Fortran Builder Overview

NAG Fortran Builder Help

Overview

The NAG Fortran Builder is an IDE (integrated development environment) for Fortran. Programmers can now create applications without having to operate from the command line. The built-in “NAG Fortran Compiler” is the successor to the world's first Fortran 90 compiler, which is known for its reliability and thorough detection of programming errors. The Fortran Builder also comes with numerical and graphical libraries.

Fortran Builder Features

  • NAG Fortran Compiler 7.1
    The NAG Fortran Compiler, Release 7.1, provides full support of Fortran 95, Fortran 2003, and Fortran 2008. In addition, approximately half of Fortran 2018 is supported (including all of its coarray features).

  • Very easy to use
    The Fortran Builder is designed so that first-time users can easily start programming in Fortran. It offers a very intuitive graphical user interface for a range of operations such as editing source code, project management, compilation, and execution.

  • 3D Graphics
    It also comes with an interface to the OpenGL/GLUT library, which provides high quality 3D graphics.

  • OpenMP 3.1
    Parallel programming with OpenMP 3.1 is fully supported.

  • GUI Programming
    Programming of Graphical User Interfaces is enhanced by provision of the capability of using the GTK+ (GIMP ToolKit) library. This comes with Glade, a GUI interface builder.

  • Linear Algebra
    It also comes with LAPACK, which is a linear algebra package freely available from netlib.org. LAPACK is precompiled and ready for immediate use.

  • Creating DLLs
    DLLs can be created easily using the Fortran Builder. This extends the possibility of using your computation code from C/C++, Excel, Java, etc.

  • NAG Library for Fortran
    The NAG Library is the world's largest commercial numerical library and can be accessed easily with the “NAG Library wizard”. Hundreds of sample programs are provided to illustrate the use of the library. (The NAG Library needs to be installed separately.)
    The Fortran Builder 7.1 has built-in support for the following NAG Library products.

    NAG Library | Product Code
    Mark 28.4, 64-bit | NLW6I284EL
    Mark 28.3, 64-bit | NLW6I283EL
    Mark 27.3, 64-bit | NLW6I273EL
    Mark 27.2, 64-bit | NLW6I272EL
    Mark 27.1, 64-bit | NLW6I271EL
    Mark 27.0, 64-bit | NLW6I27DEL

Related Items

Fortran Builder Tutorial
Fortran Builder Operation Guide
> 32-bit application redistribution
> 64-bit application redistribution
Fortran Language Guide
NAG Fortran Compiler, Release 7.1 Release Notes
NAG Fortran Compiler, Release 7.1 Manual
> Compiler Options
LAPACK Documentation
OpenGL/GLUT User Guide
GTK+ User Guide
Known Problems
FAQ – Frequently Asked Questions
Copyright Notice


Fortran Builder Tutorial

Starting and Stopping the Fortran Builder
First program using the Fortran Builder (Hello Fortran Builder!)
Execution without a project (Quick Execution)
Program using the LAPACK library
Creating a DLL (Dynamic Link Library)
Creating a static library
Program using the NAG Fortran Library
Let's debug!
Let's do multi-language programming!
Using editor input assistance
Creating a program using OpenGL/GLUT
Creating a GTK+ application

Related Items


Starting and Stopping the Fortran Builder

 Previous | Next | Up

Starting and Stopping the Fortran Builder

To start the Fortran Builder in Windows from the Start Menu, do [ All apps > NAG > NAG Fortran Builder 7.1 ]. Also, if at installation time a desktop icon was created, you can start the Fortran Builder by double-clicking on that icon.

After starting the Fortran Builder, an initial screen like the one below is displayed.

  • In the left part of the screen the Project Manager pane is displayed. The Project Manager displays the files that belong to the current project.
  • In the middle and right part of the screen the Editor pane is displayed. The source code files of the project can be edited in this window.
  • At the bottom of the screen the Messages pane is displayed. Compile-time error messages, Search results, and Runtime error messages are displayed here.

To stop the Fortran Builder, select (from the onscreen menu) [File | Exit].

Related Items
Exit


First program using the Fortran Builder (Hello Fortran Builder!)

 Previous | Next | Up

First program using the Fortran Builder (Hello Fortran Builder!)

Firstly, we explain the procedures of creating a simple Fortran program, compiling that program, and finally executing the program.

Most program development in the Fortran Builder is done using projects. To compile and execute a program using a project, it is necessary to do the following.

  1. Create the project.
  2. Create a source file in the project, and input the program.
  3. Build (compile and link) the project.
  4. Run the program.
A project is composed of a set of source program files and data files necessary to make one application program or one library. This is a simple project which consists of a single source file containing a simple program.

In this first program, “Hello Fortran Builder!” is displayed in a console window. The screenshot below shows an example of the execution result.

Related Items
New Project
New Console Application
Program using the LAPACK library
Creating a DLL (Dynamic Link Library)
Program using the NAG Fortran Library
Open Project
Project Settings
Execution without a project (Quick Execution)


Creating a project

 Previous | Next | Up

Creating a project

First of all, it is necessary to create a project. To create a project select [File | New | Project] from the menu, or click the New Project icon on the toolbar.

New Project creation menu

The following screen is displayed; select [Console Application] and type “hello” as the name of the project. Then press the [Next >>] button to advance to the next screen.

Create Project hello

Further Details There are seven kinds of project.

Console Application | Choose this to create an application that displays its output in a console window.
Static Library | Choose this to create a normal (static-link) library.
LAPACK Application | Choose this to create a console application that uses the LAPACK library.
Dynamic Link Library | Choose this to create a DLL (Dynamic Link Library).
NAG Library Application | Choose this to create a console application that uses the NAG Fortran Library.
OpenGL Application | Choose this to create an application that uses the 3D graphics library OpenGL.
GTK+ Application | Choose this to create an application that uses the GUI toolkit GTK+.

This time we specify “Console Application” because we want to create a console application.

The project name consists of alphanumeric characters; together with the folder it identifies the project. If a project with the same name already exists in the same folder, an error is reported when [Next >>] is selected. This time we specify the project name “hello”.
The project storage directory specifies the folder to preserve the project. It is also possible to specify the storage position by browsing after pushing the button in the right of the project storage position edit box. This time we want to use the default, so we do not change this.
The “Create Project”. dialogue box is display; at this point you can specify the initial source file template to use. This time, because the default settings are what we want, please press [OK] to create the project.

hello FB Create Project dialogue

The project has been successfully created if the following screen is displayed (note that on 32-bit Windows, it will not say “(64-bit)”); please proceed to the next step.

hello FB Project Created screen

Related Items
New Project
New Console Application


Hello Fortran Builder: Adding a source file to the project

 Previous | Next | Up

Adding a source file to the project

The created project is open; now we create a source file and add it to the project. The file is created by selecting [File | New | File], by pressing Ctrl+N, or by clicking the New File icon on the toolbar.

menu New File

The screen below is displayed; select [Fortran free-form source file (.f90)] and click [OK] to advance to the next screen.

Create File dialogue: File type

The [Create File] dialogue window is displayed. Please enter “prog” in the File Name field and click [OK].

Create File dialogue: File name

Further Details
The file name should consist of alphanumeric characters. The extension is automatically specified. This time, please call the file “prog”. This will create the file “prog.f90”.

The File Directory specifies the folder in which to save the file. The folder can be specified by direct editing, or by browsing using the button to the right of the input field. This time we want the default, so please do not change it.

The file has been successfully created if the following screen is displayed; please proceed to the next step.

Related Items
Add file to Project
Adding existing files to a project


Hello Fortran Builder: Entering the program source code

 Previous | Next | Up

Entering the program source code

A simple program will be placed in the newly created source file (prog.f90). Please enter the following code into the Editor window.

prog.f90 source code

When you have finished entering the source code, please select [File | Save], press Ctrl+S, or select the Save icon from the toolbar to save the file.

menu File Save

Related Items
Save


Hello Fortran Builder: Building the application

 Previous | Next | Up

Building the application

Next we build the application. The application is built by selecting [Project | Build], or by clicking the Build icon on the toolbar.

menu Project Build

If there are no build problems, the following message window contents will be displayed.

When there is a typographical or other error in the program, the error message is displayed in the Message Window, and the place where the first error was discovered is highlighted in the Editor window. For example, if the “print” in the first line of the program is mistakenly typed as “ppint”, the following Message Window contents will be displayed.

Compilation error listing

Related Items
Build


Hello Fortran Builder: Running the program

 Previous | Next | Up

Running the program

To execute the program, select [Run | Execute] or click the Run icon on the toolbar.

If no error occurs, a console window like the following will be displayed when the program is executed.

Hello Fortran Builder!

Related Items
Execute


Execution without a project (Quick Execution)

 Previous | Next | Up

Execution without a project (Quick Execution)

The Fortran Builder can compile and execute a single source file without needing a project; this is called Quick Execution.

When there is no project open, and there is a single source file is open (and selected) in the Editor window, if you select [Run | Execute] or click the Execute icon on the toolbar, the file will be compiled and executed.

Note:

  • This can only be done with no project open; to close the current project select [File | Close Project].
  • Only one source file at a time, either Fortran or C, can be compiled and executed in this way.
  • The source file can only be built as a console application.
  • You can create a project from a selected single source file at any time by selecting [File | Save Project] or by right-clicking the source file's editor window tab and selecting “Create project from file”.
  • If instead you wish to add the source file to a project, you should open that project and then select [Project | Add file to project...].
  • You can also use [File | Run | Debug Execute] or the Debug Execute button to execute the source file in debug mode.

To see how this works, first close any current project and then use [File | New | File] to create the file “prog.f90” with the contents as follows.

File | New File

Now select [File | Run | Execute] to compile and execute the file.

Run | Execute

After compiling and linking the file, the program will be executed displaying a console window like the following.

Hello FB Output

Related Items
Execute


Program using the LAPACK library

Previous | Next | Up

Program using the LAPACK library

Programs using the LAPACK library for Linear Algebra can be easily programmed using the Fortran Builder. The LAPACK library contains many linear algebra routines for reliably solving problems such as simultaneuous equations and eigenvalues.

An LAPACK manual page

The procedure of creating an application that uses the LAPACK library is as follows.

  1. Create an LAPACK project. At this time choose a single sample template program.
  2. Build the project.
  3. Execute the program and confirm its operation.
  4. Modify the program to perform the desired operations.

Related Items
New Project
New Console Application
New LAPACK Application
First program using the Fortran Builder (Hello Fortran Builder!)
Creating a DLL (Dynamic Link Library)
Program using the NAG Fortran Library
Open Project
Project Settings


Creating an LAPACK Application project

 Previous | Next | Up

Creating an LAPACK Application project

An LAPACK application project, as well as other types of project, is created by selecting [File | New | Project].

menu New Project

When the Create Project dialogue window is displayed as below, please select [LAPACK Application] and type “lapacktest” as the name of the project. Then press the [Next >>] button.

Create Project lapacktest

When the following screen is displayed, first select [Use template], then choose a single sample program from the list. This time, please select first C01: Real Linear Equation Routines, then the [DGESV] example program, and finally press the [OK] button to create the project.

LAPACK Project Template

If there are no errors creating the project a screen like the following will be displayed. Please proceed to the next step.

Project lapacktest Created

Related Items
New Project
New LAPACK Application


Building the LAPACK project

 Previous | Next | Up

Building the LAPACK project

The project can be built by selecting [Project | Build], or by clicking the Build icon on the toolbar.

menu Project Build

If no errors are found, a Message Window like the following will be displayed when building is complete. Please proceed to the next step.

lapacktest project built

Related Items
Build


Running the LAPACK program

 Previous | Next | Up

Running the LAPACK program and confirming the results

To execute the program select [Run | Execute] or the Execute icon on the toolbar.

menu Run Execute

If there are no errors, the results of the calculation will be output as follows, confirming proper execution of the program. To terminate execution, please press the [Enter] key.

Once the above LAPACK sample program has executed successfully, the next step is to change the source code to add the required operations.

Related Items
Execute


Making the required changes to the LAPACK sample program

 Previous | Next | Up

Making the required changes to the LAPACK sample program

Next, we change dgesv-ex.f90 at line 21 as shown below; this changes the title of the output.

After changing the file, please select [Run | Execute] or click the Run icon on the toolbar. Before executing the program, any necessary Build operations will be performed; this time, because the program source code has been changed, it will be compiled and linked before execution.

If there are no errors, output similar to the following will be displayed, and it can be confirmed that the change was successful.

new lapacktest output

Related Items
Execute


Creating a DLL (Dynamic Link Library)

 Previous | Next | Up

Creating a DLL (Dynamic Link Library)

The Fortran Builder makes it easy to create a DLL (Dynamic Link Library).

The procedure of making a Dynamic Link Library using the DLL project type is as follows.
  1. Create a DLL project.
  2. Add source file(s) containing user-defined functions.
  3. Change to 32-bit mode if necessary.
  4. Build the project to create the DLL file.
  5. Test the DLL from a sample C program.
  6. Test the DLL from Excel.

Related Items
New Project
New Console Application
New DLL
First program using the Fortran Builder (Hello Fortran Builder!)
Program using the LAPACK library
Program using the NAG Fortran Library
Open Project
Project Settings


Creating the DLL project

 Previous | Next | Up

Creating the DLL project

A DLL project, as well as other types of project, is created by selecting [File | New | Project].

menu New Project

When the Create Project dialogue window is displayed as below, please select [Dynamic Link Library] and type “dlltest” as the name of the project. Then press the [Next >>] button.

Create Project dlltest

When the following screen is displayed, press the [OK] button to create the project.

Creating a DLL project

If there are no errors creating the project a screen like the following will be displayed. Please proceed to the next step.

dlltest project created

Related Items
New Project
New DLL


Adding a source file with a user-defined function

 Previous | Next | Up

Adding a source file with a user-defined function

After creating the DLL project, it is necessary to add source files containing the user-defined functions that will go into the DLL. To create a new file, select [File | New | File], type Ctrl-N, or click the New File icon.

dlltest New File

The Create File dialogue will be displayed: select “Fortran free-form source file (.f90)” and click [OK].

Create File dialogue

The next screen in the Create File dialogue will be displayed; type “myfunc” into the File Name field and click [OK].

File Name myfunc

If there are no errors creating the file, the following will be displayed.

The next step is to define the function for the DLL; the following function is suggested:

myfunc.f90 source code

Please type the source code into the editor window; when you have finished, please go to the next step.

Related Items
New Project
New DLL


Changing the project to 32-bit mode (64-bit Windows only)

 Previous | Next | Up

Changing the project to 32-bit mode (64-bit Windows only)

Both 32-bit and 64-bit DLLs can be built. A 32-bit application can only load 32-bit DLLs. A 64-bit application can only load 64-bit DLLs. It is quite common to use 32-bit applications on 64-bit Windows: for example, even though the default for Microsoft Excel is 64-bit, some people use the 32-bit version as they have 32-bit plugins or libraries.

Therefore we will set this project to 32-bit mode so that the DLL it creates can be loaded by 32-bit applications. (This step should be skipped if you want to use 64-bit Excel.)

To change the mode, select [Project | Project Settings...].

The 32/64 bit mode setting is on the Basic Settings panel; select 32-bit as shown below, then click [OK].

32-bit mode setting

The new bitness will be displayed in the Fortran Builder window title. Please go to the next step.

Related Items
New Project
New DLL


Building the project and creating the DLL file

 Previous | Next | Up

Building the project and creating the DLL file

Building the project will create the DLL file in the project folder.
To build the project select [Project | Build] or click the Build icon on the toolbar.

menu Project Build

If there are no errors, a Message Window like the following will be displayed; and a DLL file will have been created in the project folder.

Related Items
Build


Using the created DLL from a C program

Previous | Next | Up

Using the created DLL from a C program

Now we will use the created DLL (dlltest.dll) from a C program execution.

Firstly, create a new console application project.

Create Project calldll

Copy the DLL file (dlltest.dll) into the project folder. Select [View | Project Folder] to display the project folder. (The dlltest project folder will be adjacent to the calldll project folder.)

menu View Project Folder

Add a C language source file to the project.

menu New File

Create File dialogue

Create File name

In the created C language source file (main.c), please input the following code (you can copy-and-paste it from this page).

#include <stdio.h>

extern double MYFUNC(double *,double *);

int main(void)
{
  double a, b;
  a = 1.23;
  b = 4.56;
  printf("a + b = %.2f\n",MYFUNC(&a,&b));
  return 0;
}

Now we need to tell the Fortran Builder to link the program with the DLL. First, select [Project | Project Settings...], then [Link]; libraries are entered on the Basic Settings panel.

dll Project Link Settings

Click the [Add] button, type in the name of the DLL, and click [OK].

dll Add DLL to project

Next, on 64-bit Windows it is necessary to set the bitness of the project to match the bitness of the DLL. Go back to the top-level Basic Settings panel of Project Settings, and select 32-bit mode.
On both 32-bit and 64-bit Windows, the “DLL compatibility” option should also be selected at this time, as shown below (the third checkbox below the mode switches).

dll Set bitness

Click [OK] to apply the new project settings.

To build and execute the project, select [Run | Execute] or the Execute icon from the toolbar.

dll Menu Run

If there are no errors, the results of the calculation will be displayed as follows. To terminate execution, press the [Enter] key.

Results of calculation

Related Items
Execute


Calling the DLL from Excel

 Previous | Next | Top

Calling the DLL from Excel

  • First, start Excel.
  • Use Alt-F11 (hold the Alt key and press the F11 key) to open the Visual Basic editor.
  • From the menu bar, select Insert and then Module (Alt-I M).
  • This is where we define our function, and tell Excel where to find it. Please type the following into the “Book1 - Module” code window, with the location replaced by the dlltest folder location (usually this is the same except for “username”).
Declare Function MYFUNC Lib "C:\Users\username\Documents\FBuilder\prjs\dlltest\dlltest.dll" ( _
   ByRef A As Double, _
   ByRef B As Double _
) As Double

Return to the Excel sheet; this can be done with Alt-F11, by clicking the small Excel icon at the left-hand end of the icon row (below File), or by clicking the Excel icon in the Windows toolbar.

Select the first cell (A1), then click in the function input field (following the f x above the cells) and type “=MYFUNC(B1,C1)” (without the quotes), i.e.

dll Excel Formula

Now enter the numbers 1.23 into B1, and 4.56 into C1. Press RETURN (or TAB, or select another cell); Excel will update A1 with the result of executing your function as shown below.

dll Excel Results

Related Items
Execute


Creating a static library

 Previous | Next | Top

Creating a static library

The Fortran Builder makes it easy to create a static library.

A static library is created using the Static Library project type using the following procedure.

  1. Create a static library project.
  2. Add source file(s) containing user-defined functions.
  3. Build the project.
  4. Test the static library using a separate program.

Related Items
New Project
New Static Library
Hello Fortran Builder!
Using the LAPACK library
Using the NAG Fortran Library
Using OpenGL/GLUT
Using GTK+/Glade
Open Project
Project Settings


Creating a static library project

 Previous | Next | Top

Creating a static library project

Like other types of project, a static library project is created by selecting [File | New | Project], or by clicking the New Project icon on the toolbar.

menu New Project

When the Create Project dialogue window is displayed as below, please select [Static Library] and type “statictest” as the name of the project. Then press the [Next >>] button.

static library Create Project

The following window is displayed to confirm the creation of the project.

Confirm static library project creation

Click [OK]; if no error occurs the project will be created as shown below.

Static library project created

Please go to the next step.

Related Items
New Project


Adding a source file with a user-defined function

 Previous | Next | Top

Adding a source file with a user-defined function

After creating the static library project, it is necessary to add source files containing the user-defined functions that will go into the library. To create a new file, select [File | New | File], type Ctrl-N, or click the New File icon.

static New File

The Create File dialogue will be displayed: select “Fortran free-form source file (.f90)” and click [OK].

Create Fortran free-form source

The next screen in the Create File dialogue will be displayed; type “myfunc” into the File Name field and click [OK].

If there is no error creating the file, the following will be displayed.

Please type the following source code into the editor window (you can copy-and-paste from this screen); when you have finished, please go to the next step.

Double Precision Function myfunc(a, b)
  Double Precision, Intent(In) :: a, b
  myfunc = a + b
End Function

Related Items
Add file to project...
Adding existing files to a project


Building the project

 Previous | Next | Top

Building the project

Now that the source file with the user function has been added, building the project will create the static library; this will be called ‘statictest.a’. To build the project select [Project | Build] or click the Build icon on the toolbar.

If there is no error building the project, the following will be displayed.

Please go to the next step.

Related Items
Build


Using the static library from another program

 Previous | Next | Top

Using the static library from another program

To test our new static library we will create another program to use it.

First, create a new console application project.

menu New Project

Select “Console Application” and type callstatic as the project name; then click [Next>>].

Create Project callstatic

The following window will be displayed; please click [OK].

Confirm project creation

Now we need to add a source file with a program that will call our function from the library. Create a new file by selecting [File | New File] or by clicking the New File icon on the toolbar.

Now select “Fortran free-form source file (.f90)”, click [OK], type main into the filename field and click [OK] to create the source file.

Create Fortran source file

Now type in (or copy-and-paste from this page) the following program into the editor window.

Program test
  Implicit None
  Interface
    Double Precision Function myfunc(a, b)
      Double Precision,Intent(In) :: a, b
    End Function
  End Interface
  Print *,myfunc(123.0d0, 456.0d0)
End Program

In order to use the static library we need to add it to our link options. Unlike a DLL this is only needed at link time, not at run time, so we will simply link to the version in the “statictest” project folder itself. Select [Project | Project Settings...] to open the Project Settings dialogue, then select [Link]; libraries are entered on the Basic Settings sub-panel.

Link Basic Settings

Click the [Add] button and type in the path of the statictest.a library. By default the statictest project will be adjacent to the callstatic project, so a relative path will be fine in this instance. (Note that the path can be also obtained by browsing using the icon to the right of the library file entry field.)

Static library location

To build and run the program select [Run | Execute] or click the Run icon on the toolbar.

If no errors are found the following will be displayed.

Related Items
Run


Using the NAG Fortran Library

 Previous | Next | Up

Program using the NAG Fortran Library

Programs that use the NAG Fortran Library can be easily developed using the Fortran Builder. The NAG Fortran Library contains more than 1600 routines covering optimisation, least squares, eigenvalues, differential equations, curve and surface fittings, time series, principal component analysis, and more topics. These routines have been developed to have high reliability and numerical stability.

NAG Library documentation page

The procedure of creating an application that uses the NAG Fortran Library is as follows.

  1. Create a NAG Fortran Library Application. At this time, choose an example program as the basis of the application.
  2. Build the project.
  3. Execute the program and confirm its operation.
  4. Modify the example program to perform the desired operations.

Related Items
New Project
New Console Application
New NAG Library Application
First program using the Fortran Builder (Hello Fortran Builder!)
Program using the LAPACK library
Creating a DLL (Dynamic Link Library)
Open Project
Project Settings


Creating a NAG Library Application project

 Previous | Next | Up

Creating a NAG Library Application project

A NAG Library Application project, as well as other types of project, is created by selecting [File | New | Project].

menu New Project

When the Create Project dialogue window is displayed as below, please select [NAG Library Application] and type “naglibtest” as the name of the project. Then press the [Next >>] button.

Create Project naglibtest

When the following screen is displayed, first select [Use template], then select the chapter, and finally a single example program from the list. This time, please select chapter [C02: Zeros of Polynomials], then select [C02ALF : All zeros of real quartic equation]; press [OK] to create the project.

Note that NAG Library projects are only available in 64-bit mode.

If there are no errors creating the project a screen like the following will be displayed. Please proceed to the next step.

naglibtest project created

Related Items
New Project
New NAG Library Application


Building the NAG Library project

 Previous | Next | Up

Building the NAG Library project

The project can be built by selecting [Project | Build], or by clicking the Build icon on the toolbar.

If no errors are found, a Message Window like the following will be displayed when building is complete. Please proceed to the next step.

Related Items
Build


Running the NAG Library example program

 Previous | Next | Up

Running the NAG Library example program

To execute the program select [Run | Execute] or the Run icon on the toolbar.

menu Run Execute

If there are no errors, the results of the calculation will be output as follows, confirming proper execution of the program. To terminate execution, please press the [Enter] key.

C02ALF example program output

Once the above NAG Library example program has executed successfully, the next step is to change the source code to add the required operations.

Related Items
Execute


Changing the example program

 Previous | Next | Up

Changing the example program

Next, we change C02ALFe.f90 at line 19 as shown below; this changes the title of the output.

Altered program text

After changing the file, please select [Run | Execute] or click the Run icon on the toolbar. Before executing the program, any necessary Build operations will be performed; this time, because the program source code has been changed, it will be compiled and linked before execution.

If there are no errors, output similar to the following will be displayed, and it can be confirmed that the change was successful.

Related Items
Execute


Let's debug!

 Previous | Next | Top

Let's debug!

Program debugging is simple with the Fortran Builder.

Debug session example

Operations like these are possible.

  • Breakpoints can be set.
  • Step execution is possible. (Steps over procedure calls.)
  • Trace execution is possible. (Steps into procedure calls.)
  • “Run to cursor” can be done.
  • Variables can be examined, and also changed.
  • Debugging can be stopped.

In this tutorial we demonstrate the following simple debugging procedures.

  1. Preparing a program for debugging.
  2. Setting a breakpoint.
  3. Debug execution, temporarily stopping at the previously set breakpoint.
  4. Examining a variable, stepping through line by line, and watching the variable change.
  5. Ending the debug session.

• The [Run | Pause on exit] option is highly recommended while debugging. Also, please use [Run | Stop program] to terminate the program, do not just close its console window.

Related Items
Starting to debug
Debug Execution


Preparing a program for debugging

 Previous | Next | Top

Preparing a program for debugging

First we will create a console application project with a program to debug.

A console application project, as well as other types of project, is created by selecting [File | New | Project...].

menu New Project

When the Create Project dialogue window is displayed as below, please select [Console Application] and type “debugtest” as the name of the project. Then press the [Next >>] button.

Create Project debugtest

When the following screen is displayed, press [OK] to create the project without any files.

Confirm Create Project

Now create a new file “dtest.f90” in the project by selecting [File | New | File].

The screen below is displayed; select “Fortran free-form source file (.f90)” and click [OK] to advance.

The [Create File] dialogue window is displayed. Please enter “dtest” in the File Name field and click [OK].

Create File dtest.f90

Now type the text below (or copy-and-paste it from this page) into the editor; this will be our program to debug.

Program dtest
  Integer :: i, ii
  ii = 0
  Do i = 1, 6, 2
    ii = ii + i
  End Do
  Print *, ii
End Program

The result should appear in the Fortran Builder as follows:

Program to debug

Necessary Debugging Options

In order to debug a program, it is necessary to be in [Debug Mode], and to have the debugging option (“-g”) set. The mode (Debug/Release) setting can be found in [Project | Project Settings... | Basic Settings]. The Debug option (“-g”) can also be found in [Project | Project Settings... | Basic Settings]. It is also highly recommended that the optimisation option be set to [None]; this option is found on the same tab.

A newly created project will already be in Debug Mode, will have the Debug option set, and the optimisation set to [None]; therefore we do not need to alter the settings at this time.

Please proceed to the next step.

Related Items


Setting a breakpoint

 Previous | Next | Up

Setting a breakpoint

To set a breakpoint, move the cursor to the line at which the breakpoint is desired and select [Run | Breakpoint]. This time please move the cursor to line 5 and set a breakpoint there.

menu Run Breakpoint

Alternatively, a breakpoint can be set by left-clicking the column in between the line number and the program text, at the line where the breakpoint is desired.

Left-click in the grey column

The line at which a breakpoint is set is marked with a red disc.

Related Items
Breakpoint Insert/Delete
Inserting and deleting breakpoints


Debug execution

 Previous | Next | Up

Debug execution

After specifying the breakpoint, start a debug execution by selecting [Run | Debug Execute] from the menu, by pressing F5, or by clicking the Debug Execute icon on the toolbar.

menu Run Debug Execute

After compiling the program, execution begins, and will temporarily stop at the breakpoint line. The line at which execution is stopped will be highlighted as seen below.

Stopped at breakpoint

Related Items
Starting to debug
Debug Execution


Variable contents display and single-step execution

 Previous | Next | Up

Variable contents display and single-step execution

While debugging, the contents of a variable and how it changes can be displayed. This time we will examine the variable i. Please select [Run | Watch Variable] from the menu.

menu Run Watch Variable

The Watching Variable Name dialogue window will open; please type i and click [OK].

Watching Variable Name

A Variable Watching window will open as below, displaying the variable name i and the value 1.

Watching Variable i, value = 1

The Variable Watching window could well appear on top of the program text; in this case you can move it out of the way by clicking and holding the left mouse button down on the title bar, and dragging it to somewhere more convenient.

Next we will single-step the execution. This is done by selecting [Run | Step], pressing F8 or clicking the Step icon on the toolbar. At this time please step execution twice.

menu Run Step

The value of the variable i as displayed in the Variable Watching window will change from 1 to 3, as shown below.

Watching Variable i, value = 3

Next we will change the value of i. Move the mouse over the line in Variable Watching that contains i and its value; clicking the mouse on the line will highlight it and cause a [...] button to appear to the right of the value. Please press this button.

Select variable i to edit

When the Change Value dialogue window appears, please change the value from 3 to 1, as shown below, and press [OK].

Change Value of i to 1

Afterwards, please step the execution again and confirm the change in the new value of i.

Related Items
Performing Step, Trace and Run-to-Cursor Operations
Watch Variable
Changing the value of a variable while debugging
Displaying the value of a variable while debugging


Stopping debugging

 Previous | Next | Up

Stopping debugging

To stop debugging select [Run | Terminate execution] from the menu or click the Stop icon on the toolbar.

menu Run Stop program

Related Items
Terminate execution


Let's do mixed-language programming!

 Previous | Next | Up

Let's do mixed-language programming!

With the Fortran Builder you can do mixed-language programming in C/C++ and Fortran. For example, in one project the main program could be in the C language and the calculation part done by a Fortran subroutine. The method of calling a subroutine or function in another language with the Fortran Builder is almost the same as the case of a single language.

When creating a new project, the following table lists the combinations of template programs and subprograms that are provided in the Fortran Builder for mixed-language programming.

Main Program | Subprogram
Fortran | C
Fortran | C++
C | Fortran
C++ | Fortran

This tutorial shows the procedures for doing mixed-language programming with a C main program and a Fortran subprogram.

  1. Create a mixed-language project (using the templates).
  2. Build the project and execute the program, confirming correct operation.
  3. Modify the template to perform the desired calculations.

Related Items
New Project
New Console Application
Open Project
Project Settings


Creating a mixed-language project

 Previous | Next | Up

Creating a mixed-language project

A mixed-language project, as well as other types of project, is created by selecting [File | New | Project].

menu New Project

When the Create Project screen is displayed, please select [Console Application] and specify “mix” as the project name as shown below; then press [Next >>] to continue.

Create Project mix

When the following dialogue window is displayed, select the “Use template” button, then select “Hello World“ as the Category, and then select “Hello World (C main, Fortran sub)” from the Example list (you will need to scroll the list down to reach this entry). Finally, press [OK] to advance.

Create Project mix

If there were no errors creating the project a screen like the following will be displayed. The file “main.c” will have been created with a C main program, and the file “sub.f90” will have been created with a Fortran subprogram. Please confirm the generated files and proceed to the next step.

mix project created

Related Items
New Project
New Console Application


Building the project and executing the program

 Previous | Next | Up

Building the project and executing the program

Next we build the project. The project is built by selecting [Project | Build] from the menu or by clicking the Build icon on the toolbar.

menu Project Build

In the absence of any errors, a Message Window like the following will be displayed.

Built with no errors

Next we execute the program. The program can be executed by selecting [Run | Execute] from the menu or by clicking the Run icon on the toolbar.

menu Run Execute

In the absence of any errors, a console window saying “Hello World” will be displayed.

mix execution output

This “Hello World” is the output from the Fortran subroutine called from the C main program. Please press the [Enter] key to continue, and proceed to the next step.

Related Items
Build
Execute


Modifying the template to add functionality

 Previous | Next | Up

Modifying the template to add functionality

Next we change the template program files to add our desired functionality. First, please change “main.c” at line 5, add a new line 9, and change line 15, as shown below.

Next, please change “sub.f90” at line 1, add new lines 2 and 4, and change line 5, as shown below.

After making the required changes, please execute the revised program by selecting [Run | Execute] from the menu or by clicking the Run icon on the toolbar. Before execution any necessary Build operations will be carried out; this time, because the program source files have been changed, the project will be built before starting execution.

If there are no problems, the new output will be displayed as follows.

Related Items
Execute


Using editor input assistance

 Previous | Next | Up

Using editor input assistance

In the Fortran Builder, Fortran language programming is made easier by editor assistance. This supplements input with Fortran keywords such as WRITE and IF, as well as variable and component names.

Editor assistance is ON by default, and can be controlled by selecting [Tool | Editor Settings] from the menu, and then selecting the Assistance panel.

Editor settings: assistance

In this tutorial, the editor assistance functions are demonstrated by the following procedure.

  1. The sample program for the operation is loaded.
  2. The program is executed, and the results confirmed.
  3. One line is added using the editor assistance function.

Related Items
Turning keyword recognition on and off
Editor Settings


Loading the program

 Previous | Next | Up

Loading the program

In this tutorial we use a program taken from “ Introductory Fortran e-Book ”. This feature is not available in the English version of the Fortran Builder; however, you may type the program in by hand, or cut and paste from the following text.

    TYPE MATERIAL
      CHARACTER(5) :: NAME
      REAL :: YOUNG
      REAL :: POISSON
    END TYPE MATERIAL
    TYPE (MATERIAL) STEEL,CONCRETE
    STEEL%NAME = 'A36'
    STEEL%YOUNG = 200.
    STEEL%POISSON = 0.3
    CONCRETE = MATERIAL( 'A36',200.,0.3 )
    PRINT *, STEEL
    PRINT *, CONCRETE
    STOP
    END

If you wish to try this yourself, please create a console application project “assistance”, with a single source file Program4-1.f90 whose contents are displayed below.

Some parts of this tutorial show the effects of assistance for variables and components; to enable those, select [Tool | Editor Settings], then the [Assistance] tab, then in the [Fortran auto completion] section make sure the boxes for Variable and Component are checked.

Related Items


Confirming execution of the program

 Previous | Next | Up

Confirming execution of the program

Please confirm proper execution of the program. Select [Run | Execute] from the menu or click the Run icon on the toolbar.

menu Run Execute

The following output should be displayed, confirming that the program is working.

assistance program output

Related Items
Execute


Using the editor assistance functions

 Previous | Next | Up

Using the editor assistance functions

We will add a new statement at line 13, showing the usage of the editor assistance.

Entire source with new statement

Firstly create a thirteenth line (by pressing the Enter key at the end of the twelfth line); the editor automatically indents the new line to be the same as the previous line. After that please enter the first character of print, “p”. At that time, the following editor assistance will be displayed. The candidates are Fortran keywords such as parameter and print (in blue), and below the keywords is a list of intrinsic functions such as pack and precision (in red); if assistance is also enabled for variables, known program variables (poisson) are also listed (in black); note that because so many items can begin with the letter P, the list has a scroll bar. Typing additional characters (such as ‘r’) will reduce the number of choices to those beginning with the whole word so far (i.e. ‘pr’).

Auto-completion items beginning with P

The currently-selected candidate is highlighted in yellow; initially, no item is selected. The candidate selection can be changed by the cursor-up and cursor-down keys, and also by clicking the mouse. The candidate can be selected (entered) by pressing the Enter key. As shown below, with an initial string of ‘pr’, please use the cursor keys to select print and press the Enter key.

The appearance of the items in the menu is the same as the subsequent insertion; both are controlled by the Editor Settings. The default case for free-form Fortran is lower case, and this can be changed to UPPER CASE or to (first letter) Capitalised.

Next we type “ *, ”, and then we want to input the variable STEEL, but here we type the first three characters. As we type the first character, then the second, then the third, the editor assistance display narrows to include only the possibilities starting with that character sequence. Press the down-arrow key to select the completion suggestion, then press the Enter key to input the whole name (and the whole name will have the case specified by the Editor Settings).

Next we demonstrate assistance with component names. After the “%” character is input, the editor assistance will display the components available together with their type information. This time, please click the mouse on YOUNG and press the Enter key. It is also possible to double-click the mouse to enter the candidate.

The result is as shown below. This completes input of the line.

Related Items


Creating a program using OpenGL/GLUT

With the Fortran Builder it is possible to create programs that produce 3D graphical output using the OpenGL/GLUT library.

The procedure of developing an application that uses the OpenGL/GLUT library is as follows.

  1. Create an OpenGL Application project. At this time, choose a sample template program as the basis of your application.
  2. Build the program.
  3. Execute the program and confirm the operation.
  4. Modify the sample program to develop it into your application.

Related Items

New Project
New OpenGL Application
First program using the Fortran Builder (Hello Fortran Builder!)
Program using the LAPACK library
Creating a DLL (Dynamic Link Library)
Program using the NAG Fortran Library
Creating a GTK+ application
Open Project
Project Settings


Creating an OpenGL application

An OpenGL application project, as well as other types of project, is created by selected [File | New | Project].

menu New Project

When the Create Project dialogue window is displayed as below, please select [OpenGL Application] and type “sample” as the name of the project. Then press the [Next >>] button.

Create OpenGL Project sample

When the following screen is displayed, first select [Use template], then choose a single sample program from the list. This time, please select the [OpenGL15: Filling polygons] sample program, and finally press the [OK] button to create the project.

Create Project with OpenGL15

If there are no errors creating the project a screen like the following will be displayed. Please proceed to the next step.

OpenGL Project created

Related Items

New Project
New OpenGL Application


Building the OpenGL project

The project can be built by selecting [Project | Build], or by clicking the Run icon on the toolbar.

menu Run Execute

If no errors are found, a Message Window like the following will be displayed when building is complete. Please proceed to the next step.

Project sample built

Related Items

Build


Running the OpenGL program and confirming the results

To execute the program select [Run | Execute] or the Run icon on the toolbar.

menu Run Execute

If there are no errors, a window like the following will be displayed, confirming proper execution of the program. To terminate execution, close both the OpenGL Window and the executable window using the X icons in the top right corners, select [Run | Terminate execution], or click the Stop icon on the toolbar.

Once the above OpenGL template program has executed successfully, the next step is to change the source code by added the required operations.

Please proceed to the next step.

Related Items

Execute
Terminate execution


Adding the desired operations to the OpenGL program.

Next, we change OpenGL15.f90 at line 104 as shown below; this changes the colour of one of the faces of the polyhedron.

After changing the file, please select [Run | Execute] or click the Run icon on the toolbar. Before executing the program, any necessary Build operations will be performed; this time, because the program source code has been changed, it will be compiled and linked before execution.

If there are no errors, output similar to the following will be displayed, and it can be confirmed that the change was successful.

Related Items

Execute


Creating a GTK+ application

With the Fortran Builder it is possible to create programs that use the GTK+ library.
GTK+ (The GIMP Toolkit) is a GUI toolkit originally developed for supporting GIMP, thus the abbreviation of Gimp Tool Kit. Later it has been adopted as a toolkit of the GNOME desktop environment.

Glade is a user interface builder for GTK+ that itself has a graphical user interface.

The procedure of developing an application that uses the GTK+ library is as follows.

  1. Create a GTK+ Application project. At this time, choose a sample template program as the basis of your application.
  2. Build the program.
  3. Execute the program and confirm the operation.
  4. Modify the sample program to develop it into your application.

Related Items

New Project
New GTK+ Application
First program using the Fortran Builder (Hello Fortran Builder!)
Program using the LAPACK library
Creating a DLL (Dynamic Link Library)
Program using the NAG Fortran Library
Creating a program using OpenGL/GLUT
Open Project
Project Settings


Creating a GTK+ project

A GTK+ application project, as well as other types of project, is created by selecting [File | New | Project].

menu New Project

When the Create Project dialogue window is displayed as below, please select [GTK+ Application] and type “samplegtk” as the name of the project. Then press the [Next >>] button.

Create GTK+ Application samplegtk

When the following screen is displayed, first select [Use template], then choose a single sample program from the list. This time, please select the [GTK03:Hello World (Glade version, 32-bit only)] sample program, and finally press the [OK] button to create the project.

Create GTK03:Hello World

If there are no errors creating the project a screen like the following will be displayed. Please proceed to the next step.

Related Items

New GTK+ Application


Changing the project to 32-bit (64-bit Windows only)

Applications that use GLADE need to link to a DLL that is only available as a 32-bit DLL. Therefore, on 64-bit Windows, the project should be changed to be 32-bit. Open Project Settings by selecting [Project | Project Settings...] from the menu bar.

The 32-bit/64-bit mode switch is located on the right-hand side; select 32-bit mode and click [OK] to apply the setting.

Project Settings samplegtk

Please go to the next step.

Related Items


Building the GTK+ project

The project can be built by selecting [Project | Build], or by clicking the Build icon on the toolbar.

Build GTK project

If no errors are found, a Message Window like the following will be displayed when building is complete. Please proceed to the next step.

GTK project built

Related Items

Build


Running the GTK+ program

To execute the program select [Run | Execute] or the Run icon on the toolbar.

menu Run Execute

If there are no errors, a window like the following will be displayed, confirming proper execution of the program. To terminate execution, click on the “Hello World” button, close the button window using the X icon in its top right corner, select [Run | Stop program], or click the Stop icon on the toolbar.

Once the above GTK+ template program has executed successfully, the next step is to change the source code by added the required operations.

Please proceed to the next step.

Related Items

Execute
Stop Program


Adding the desired operations to the GTK+ program.

Next, we change the GHelloWorld.glade file so as to make a change to the displayed window. In the Project Manager window, double-click on the GHelloWorld.glade icon.

The Glade program for building GTK+ interfaces will read the GHelloWorld.glade file and open 3 windows: one for the file itself, a “properties” window and a “Palette” window.

We will now change the “Hello World” caption to “Fortran Builder”. To make this change, the “Properties” of “button1” of “Window1” need to be changed. In order to do this, first click the triangle icon to the left of “Window1” in the “GHelloWorld.glade - Glade” window to expand the objects attached to Window1, then right-click “button1” and select “Properties” to display the properties of button1 in the “Properties” window.

Select button1 properties

In the “General” tab, the text associated with the button is in the “Label” field; change this text (currently “Hello World”) to “Fortran Builder”.

After changing the text, click the Save button ( Save icon) and then exit from Glade by selecting [File | Quit] or clicking the X icon in the top right corner.

After exiting from Glade, please select [Run | Execute] or click the Run icon on the toolbar. If there are no errors, output similar to the following will be displayed, and it can be confirmed that the change was successful.

Related Items

Execute


Fortran Builder Operation Guide

Fortran Builder Operation Manual

Fortran Builder Operation Guidance


Fortran Builder Operation Manual

General

Operation Modes
Build Messages
Runtime Errors
Function Keys
Start Menu

File Menu

Close File
Close Project
Delete Project
Exit
New File
File Creation Dialogue
New Project
New Console Application
New DLL (Dynamic Link Library)
New GTK+ Application
New LAPACK Application
New NAG Library Application
New OpenGL Application
New Static Library
Open File
Open Project
Print
Recent Files
Recent Projects
Rename Project
Save
Save As
Save Project

Edit Menu

Calculator
Case conversion
Comment out
Copy
Cut
Delete
Indent
Insert Date
Insert File
Insert Time
Paste
Redo
Select All
Select Line
Uncomment
Undo
Unindent

Search Menu

Find...
File Find
Goto...
Next
Previous
Replace...

View Menu

Command Prompt
Detailed Build Messages
File Folder
Message Window
Project Folder
Project Manager
Status bar
Tool bar

Project Menu

Add files to project...
Build
Clean
Clean All
Compile
Project Settings
Project Settings: Basic Settings
Project Settings: C/C++ Compiler
Project Settings: Directories
Project Settings: Fortran Compiler
Project Settings: Link
Rebuild
Remove files from project...

Run Menu

Break point
Command Line
Debug Execute
Execute
Next Break point
Pause on exit
Previous Break point
Run to Cursor
Step
Terminate execution
Trace
Watch Variable

Tool Menu

Call Graph...
Editor Settings...
Environment Variable Settings...
Generate DLL calling library...
Generate Interface Module...
Polish Fortran Source
Polish Settings...
Unify Precision...
Wallpaper Settings...

Help Menu

About Fortran Builder
Fortran Builder Help
NAG Fortran Library Help
NAG UK Home Page
Support Home Page


Operation Modes

The Fortran Builder has two modes of operation.

  1. Project Mode.

    When a project is open, the Fortran Builder is in “Project Mode”.

    A project consists of a project folder containing a project file and all the object files, temporary files, makefile and executable. The project folder normally also contains the source files. The project file contains all the information needed to manage the project.

    Projects are also used for building libraries.

  2. Quick Execution Mode.

    When no project is open and a single source file is open in the Editor Window, the Fortran Builder is in “Quick Execution Mode”.

    In this mode, a new source file can be created or an existing source file can be opened; this single file can be built or executed without needing to create a project to manage it.

    The various files that are needed for building and execution (makefile, object file, etc.) will be created in the directory in which the source file resides.

    A project can be created from the single source file in the active Editor Window by selecting [File | Save Project].

Related Items


Build Messages

After selecting [Project | Compile], [Project | Build], [Project | Rebuild] or [Project | Clean], various messages are displayed in the Compile Message window. Error messages are displayed with a cross on a red disc; warning messages are displayed with an exclamation mark on a yellow triangle. Double-clicking on a message will highlight the corresponding line in the source file and jump to it.

Related Items

Build
Clean
Clean All
Compile
Rebuild
Building the whole project
Checking the details of build messages
Cleaning the whole project
Compiling only the files being edited
Jumping to the error line
Rebuilding the whole project
View detailed build messages


Runtime Errors

When a program is executed, if an error is detected the program will be terminated and the error message displayed in the Runtime Error window. Double-clicking on a runtime error message will highlight the corresponding line in the source file and jump to it. (Occasionally there is no line number information available, in which case double-clicking the message will do nothing.)

Related Items

Execute


Function Keys

The following table lists the special function and control key assignments in the Fortran Builder with the actions they perform.

Function Key | Action
Ctrl+1 | (Edit) Comment Out
Ctrl+2 | (Edit) Uncomment
Ctrl+A | (Edit) Select All
Ctrl+C | (Edit) Copy
Ctrl+F | (Search) Find...
Ctrl+G | (Search) Goto...
Ctrl+N | New File
Ctrl+O | (File) Open...
Ctrl+P | (File) Print...
Ctrl+Q | (Edit) Select Line
Ctrl+R | (Search) Replace
Ctrl+S | (File) Save
Ctrl+V | (Edit) Paste
Ctrl+X | (Edit) Cut
Ctrl+Y | (Edit) Redo
Ctrl+Z | (Edit) Undo
End | Go to end of line
Ctrl+End | Go to end of file
Shift+End | Select from here to end of line
Ctrl+Shift+End | Select from here to end of file
Home | Go to beginning of line
Ctrl+Home | Go to beginning of file
Shift+Home | Select from here to beginning of line
Ctrl+Shift+Home | Select from here to beginning of file
Insert | Toggle insert/overwrite mode
Ctrl+LeftArrow | Go to beginning of word or end of previous line
Ctrl+RightArrow | Go to beginning of next word or end of line
Tab | (Edit) Indent
Shift+Tab | (Edit) Unindent
F1 | Help (context)
F3 | (Search) Next
Shift+F3 | (Search) Previous
F4 | Run to Cursor
F5 | (Search) Find all (only when in Find)
F5 | (Run) Debug Execute (except when in Find)
F6 | (Run) Execute
F7 | (Run) Trace (only when debugging)
F8 | (Run) Step (only when debugging)
F9 | (Run) Watch Variable
F10 | (Project) Rebuild

Related Items

Copy
Cut
Debug Execute
Execute
Find...
Indent
New File
Next
Open File
Paste
Previous
Print
Rebuild
Redo
Replace...
Run to Cursor
Save
Select All
Select Line
Step
Trace
Undo
Unindent
Watch Variable


Start Menu

In the Windows Start Menu, [ All apps | NAG Fortran Builder 7.0 ] has the following entries:

Fortran Builder 7.0 Help

Open the Fortran Builder Help System.

NAG Fortran Builder 7.0

Start the Fortran Builder

NAG Fortran Compiler 7.0 Command Prompt

Open a console window (“cmd”) with environment variables suitable for running the NAG Fortran Compiler (“nagfor”).

NAG NPW3270NA Licence, Request or Install

Start the program for generating licence requests and installing licences.

NAG Fortran Builder 7.0 Reset

Start the program that resets all the Fortran Builder's settings to the factory default.

Related Items


Close File

Select [File | Close File] to close the active file in the Editor window.
• If the file has been changed since the last Save, you will be asked whether to save the changes; select [Save] to save the changes, [Don't Save] to discard the changes, and [Cancel] to abort the close operation.

Related Items

New File
Open File
Recent Files
Save
Save As


Close Project

Select [File | Close Project] to close the currently-open project.
• If the project has been changed since the last Save, you will be asked whether to save the changes; select [Save] to save the changes, [Don't save] to discard the changes, and [Cancel] to abort the close operation.

Related Items

Delete Project
New Project
Open Project
Recent Projects
Rename Project
Save Project


Delete Project

Select [File | Delete Project...] to delete the currently-open project.

This brings up a confirmation dialogue box displaying the path of the project file and the project folder; select one of the following:

Delete project file only
This will delete the project file only.
Delete entire project folder
This will delete the entire project folder and its contents. Do not select this unless you are absolutely sure you do not need those files.
Cancel
This aborts deleting the project, which therefore remains open.

If the volume containing the project file or project folder supports the Recycle Bin, the deleted files will be placed there rather than permanently deleted. Files in the Recycle Bin can be manually restored.

Related Items

Close Project
New Project
Open Project
Recent Projects
Rename Project
Save Project


Exit

Select [File | Exit] to stop the Fortran Builder. If there is an unsaved project or file, you will be asked whether to save the changes. To save the changes press [Yes], to exit without saving press [No], to abort the exit operation press [Cancel].

Related Items

Starting and Stopping the Fortran Builder


New File

Select [File | New | File] (or press Ctrl+N) to display the File Creation dialogue box. This box allows the creation of new files as shown below.

Fortran | Fortran fixed-form source file (.f)
Fortran | Fortran free-form source file (.f90)
Fortran | Fortran free-form source file (.f95)
C | C source file (.c)
C++ | C++ source file (.cpp)
C/C++ header | C/C++ header file (.h)
DLL def | DLL function definition file (.def)
text | Text file (.txt)
Glade | GTK+ GUI interface definition file (.glade)

Related Items

File Creation Dialogue
Close File
Open File
Recent Files
Save
Save As
Creating a new file in the project


File Creation Dialogue

After the file type is selected and the [OK] button is pressed, the File Creation dialogue box is displayed. After specifying the file name and directory, press [OK] to create the new file. The file name excludes the extension. The directory can be changed by using the [Browse] button.

Related Items

New File
Creating a new file in the project


New Project

Select [File | New | Project] to display the Project Creation dialogue box. Specify the project kind, project name, and storage position, then press the [Next >>] button to advance. The following kinds of project can be specified.

Console Application | An application that starts with a console window.
Static Library | Statically linked library for use by other applications.
LAPACK Application | Numeric application using the LAPACK package.
OpenGL Application | 3D graphical application using the OpenGL library.
Dynamic Library | Dynamically linked library (DLL) for use by other applications.
NAG Library Application | Numeric application using the NAG Library.
GTK+ Application | Interactive application using the GTK+ GUI toolkit.

The project name must be valid for that folder. It is an error if a project with the same name already exists in the same folder. The project storage position specifies the folder to hold the project. The storage position can be changed by using the [Browse] button.

Related Items

Delete Project
New Console Application
New DLL
New GTK+ Application
New LAPACK Application
New NAG Library Application
New OpenGL Application
New Static Library
Open Project
Rename Project
First program using the Fortran Builder (Hello Fortran Builder!)
Program using the LAPACK library
Creating a DLL (Dynamic Link Library)
Program using the NAG Library
Creating a program using OpenGL/GLUT
Creating a GTK+ application


New Console Application

After selecting New Project, and Console Application, pressing the [Next >>] button advances to the Project Creation window. After specifying the information below, the project is created by pressing the [OK] button.
• If an unsaved project is currently open, you will be asked whether to save the changes. If the changes are to be saved, the new project will be created after saving the current project. If the changes are not to be saved, the new project will be created without saving the current project.

No console window | Specify this if you do not want to display the console window during execution. This setting can be changed afterwards by selecting [Project | Project Settings | Link | Option | No console window].
Initial 'Hello World' source | Specifies whether to create initial source files.
Mixed language C/C++ and Fortran | Specifies that project contains both C (or C++) and Fortran. This is only necessary (and available) if the “Initial 'Hello World' source” option is used, and you want to create two initial source files.
Main language | Whether the main program should be Fortran (free form, .f95), Fortran (fixed form, .f), C (.c) or C++ (.cpp).
File name | Specifies the name for the initial source file.
Secondary language | Whether the second source file should be Fortran (free form, .f95), Fortran (fixed form, .f), C (.c) or C++ (.cpp).

Related Items

New Project
New LAPACK Application
New NAG Library Application
Open Project
Project Settings
First program using the Fortran Builder (Hello Fortran Builder!)


New DLL (Dynamic Link Library)

After selecting New Project and DLL, pressing the [Next >>] button advances to the Project Creation window. No further specification is needed: the project is created by pressing the [OK] button.
• If an unsaved project is currently open, you will be asked whether to save the changes. If the changes are to be saved, the new project will be created after saving the current project. If the changes are not to be saved, the new project will be created without saving the current project.

Related Items

New Project
New Static Library
Open Project
Project Settings
Creating a DLL (Dynamic Link Library)


New GTK+ Application

After selecting New Project and GTK+ Application, pressing the [Next >>] button advances to the Project Creation window. After specifying the information below, the project is created by pressing the [OK] button.
• If an unsaved project is currently open, you will be asked whether to save the changes. If the changes are to be saved, the new project will be created after saving the current project. If the changes are not to be saved, the new project will be created without saving the current project.

No console window | Specify this if you do not want to display the console window during execution. This setting can be changed afterwards by selecting [Project | Project Settings | Link | Option | No console window].
Create Glade file | Specify this to create a basic Glade file for the interface.
No template | Specify this to create the application without using any GTK+ skeleton program. However, the application will still be linked automatically with the GTK+ library.
Use template | Specify this to create the application starting with a GTK+ skeleton program. Select one of the GTK+ templates from the list.

Related Items

New Project
Open Project
Project Settings
Creating a GTK+ application


New LAPACK Application

After selecting New Project and LAPACK Application, pressing the [Next >>] button will advance to the Project Creation window. After specifying the information below, the project is created by pressing the [OK] button.
• If an unsaved project is currently open, you will be asked whether to save the changes. If the changes are to be saved, the new project will be created after saving the current project. If the changes are not to be saved, the new project will be created without saving the current project.

No console window | Specify this if you do not want to display the console window during execution. This setting can be changed afterwards by selecting [Project | Project Settings | Link | Option | No console window].
No template | Specify this to create the application without using any LAPACK skeleton program. However, the application will still be linked automatically with the LAPACK library.
Use template | Specify this to create the application starting with an LAPACK skeleton program. The application will be linked automatically with the LAPACK library. When this setting is used, it is necessary to select the sample program. The LAPACK chapter should be specified first, then one of the examples from the list should be selected.
Chapter | This setting specifies the chapter from which to select the LAPACK sample program. There are 18 chapters including linear analysis and equation solving.
Example list | This setting specifies the particular example program to be used from the selected LAPACK chapter.

Related Items

New Project
New Console Application
Open Project
Project Settings
First program using the Fortran Builder (Hello Fortran Builder!)
Program using the LAPACK library


New NAG Library Application

After selecting New Project and NAG Library Application, pressing the [Next >>] button will advance to the Project Creation window. After specifying the information below, the project is created by pressing the [OK] button.
• If an unsaved project is currently open, you will be asked whether to save the changes. If the changes are to be saved, the new project will be created after saving the current project. If the changes are not to be saved, the new project will be created without saving the current project.

No console window | Specifies that the console window should not be displayed during execution. This setting can be changed afterwards by selecting [Project | Project Settings | Link | Option | No console window].
No template | Specify this to create the application without using any NAG Library example program. However, the application will still be linked automatically with the NAG Library.
Use template | Specify this to create the application starting with a NAG Library example program. The application will be linked automatically with the NAG Library. When this setting is used, it is necessary to select the example program. The NAG Library chapter should be specified first, then one of the example programs from the list should be selected.
Chapter | Specifies the chapter from which the example program is to be selected. There are 44 chapters including eigenvalues, eigenvectors, differential equations and multivariate analysis.
Example program list | After the chapter is specified, select a single example program from this list.

Related Items

New Project
New Console Application
Open Project
Project Settings
Program using the NAG library


New OpenGL Application

After selecting New Project and OpenGL Application, pressing the [Next >>] button advances to the Project Creation window. After specifying the information below, the project is created by pressing the [OK] button.
• If an unsaved project is currently open, you will be asked whether to save the changes. If the changes are to be saved, the new project will be created after saving the current project. If the changes are not to be saved, the new project will be created without saving the current project.

No console window | Specify this if you do not want to display the console window during execution. This setting can be changed afterwards by selecting [Project | Project Settings | Link | Option | No console window].
No template | Specify this to create the application without using any OpenGL skeleton program. However, the application will still be linked automatically with the OpenGL library.
Use template | Specify this to create the application starting with an OpenGL skeleton program. Select one of the OpenGL templates from the list.

Related Items

New Project
Open Project
Project Settings
Creating a program using OpenGL/GLUT


New Static Library

After selecting New Project and Static Library, pressing the [Next >>] button will advance to the Project Creation window. The project is created immediately after pressing the [OK] button, because there is no extra information needed for a static library project.
• If an unsaved project is currently open, you will be asked whether to save the changes. If the changes are to be saved, the new project will be created after saving the current project. If the changes are not to be saved, the new project will be created without saving the current project.

Related Items

New Project
New DLL
Open Project
Project Settings


Open File

Select [File | Open...] (or press Ctrl+O) to open a file. The File Selection dialogue box is displayed for you to select the file.
It is also possible to open a file by dragging-and-dropping it from Windows Explorer.

Related Items

Close File
New File
Recent Files
Save
Save As


Open Project

Selecting [File | Open Project...] opens an existing project. A browser window will be displayed; select the project file (.fbp) and press [Open] to open.
If an unsaved project is currently open, you will be asked whether to save the changes. If the changes are to be saved, the project will be opened after saving the current project. If the changes are not to be saved, the project will be opened without saving the current project.

Related Items

Close Project
Delete Project
New Project
Project Settings
Recent Projects
Rename Project
Save Project


Print

Select [File | Print] (or press Control-P) to print the currently being-edited file. Various printing parameters can be set. The image to be printed can be previewed by pressing [Preview].

[Font setting]
This specifies the name and size of the font.
[Margin Setting (mm)]
This specifies the size of the margins (left, right, top, bottom) and the spacing between lines, in millimetres.
[Page Range]
This specifies whether to print all pages, or the starting page and ending page.
[Print Settings]
This specifies whether to print all pages, only the odd-numbered pages, or only the even-numbered pages. It also specifies whether line numbers should be printed.
[Columns]
This specifies the number of columns per page (usually 1). If more than one column is being printed, it also specifies the spacing between columns.
[Header/Footer]
This specifies the text to print as the header and/or footer, and where they should be placed (‘Left’, ‘Centre’, ‘Right’, ‘(None)’).
Special format characters in the header/footer are as follows.
Meaning | Format
Page number | %p
File name (including path) | %f
File name (without path) | %F
Year | %y
Month | %m
Day | %d
Time | %t
[Print]
Pressing this button prints the file.
[Preview]
Pressing this button displays a preview of the printed page.
[Printer Settings]
Opens the Printer Settings dialogue window, for selecting the printer and changing its properties.
[Cancel]
Closes the Print dialogue window without printing.

Related Items


Recent Files

Selecting [File | Recent Files] displays a submenu containing a list of recently opened files. Selecting one of these files from the list will open it.

Related Items

Close File
New File
Open File
Save
Save As


Recent Projects

Selecting [File | Recent Projects] displays a submenu containing a list of recently opened projects. Selecting one of the projects from the list will open it.
• If an unsaved project is currently open, you will be asked whether to save the changes. If the changes are to be saved, the new project will be created after saving the current project. If the changes are not to be saved, the new project will be created without saving the current project.

Related Items

Close Project
Delete Project
New Project
Open Project
Rename Project
Save Project


Rename Project

Select [File | Rename Project...] to rename the currently-open project.

This brings up a dialogue box for entering the new name for the project. Type the new name (which is pre-initialised to be the same as the existing name) and select [OK] to rename the project. Select [Cancel] to abort the rename operation.

This command renames the project file and the executable file. The name of the project folder and the names of any other files in the project are unchanged.

Related Items

Close Project
Delete Project
New Project
Open Project
Recent Projects
Save Project


Save

Select [File | Save] (or press Ctrl+S) to save the current file.

Related Items

Close File
New File
Open File
Recent Files
Save As


Save As

Select [File | Save As...] to save the current file with a different name.
Selecting this menu item opens the File Name Selection dialogue window; select the file name and folder, and press [Save] to save it (or [Cancel] to cancel the operation). The default extension will be used if none is specified.

Related Items

Close File
New File
Open File
Recent Files
Save File


Save Project

Select [File | Save Project] to save the currently-open project.

Related Items

Close Project
Delete Project
New Project
Open Project
Recent Projects
Rename Project


Calculator

By selecting [Edit | Calculator] from the editor a simple calculator can be used. Click the Paste button to insert the calculation result in the editor at the cursor position.

Calculator shortcut keys

List of calculator button and key correspondances.

Button | Key | Meaning
% | % | Percentage operation
* | * | Multiply
+ | + | Add
+/− |  | Change sign
− | - | Subtract
. | . | Decimal point
/ | / | Divide
0-9 | 0-9 |
= | Enter | Perform calculation
BS | Backspace | Delete last character
C | Esc | Clear All
CE | Del | Clear Entry
M+ | Ctrl-Alt-P | Add to Memory
MC | Ctrl-L | Clear Memory
MR | Ctrl-Alt-R | Memory Read
MS | Ctrl-M | Memory Store
Paste | Space | Insert in editor

Related Items


Case conversion

Selecting [Edit | Case conversion] opens a submenu; select [UPPER CASE], [lower case] or [Upper case first char]. The first converts the selected text to upper case; the second converts the selected text to lower case; the third converts the first character of the selected text to upper case and the rest to lower case. Note that if the first character of the selected text is not alphabetic, [Upper case first char] will convert all alphabetic characters in the selected text to lower case.

This menu item is only available when a text selection is made.

Related Items


Comment out

Select [Edit | Comment Out] to comment out the selected code range. An initial exclamation mark (!) will be added to the beginning of every line that is selected. Performing this multiple times will add multiple exclamation marks.

Related Items

Uncomment


Copy

Select [Edit | Copy] (or press Ctrl+C) to copy the selected text to the clipboard.

Related Items

Paste
Cut


Cut

Select [Edit | Cut] (or press Ctrl+X) to delete the selected text after copying it to the clipboard.

Related Items

Copy
Paste


Delete

Select [Edit | Delete] to delete the selected text. If no text is selected, delete the character at the current cursor position.

Related Items

Cut


Indent

Select [Edit | Indent] (or press Tab) to insert blank characters or tab characters.

In Fortran 77 (fixed-form) source files, the default tab stops are at column 6, column 7, and every 4 columns afterwards. Tab characters are not used in Fortran 77 source files, only blank characters.

In Fortran 90/95 (free-form) source files, the default tab stops are at every 4 columns. Whether tab characters or blank characters are inserted is controlled by the setting of [Tool | Editor Settings | Options | Fortran90/95 Option | Use Tab characters].

In C/C++ source files the default tab stops are every 4 columns. Whether tab characters or blank characters are inserted is controlled by the setting of [Tool | Editor Settings | Options | C/C++ Option | Use Tab characters].

The default tab stops for Fortran 90/95 and C/C++ files can be changed via [Tool | Editor Settings | Options | Editor options | Tab stops].

Related Items

Unindent
Indenting a selected region


Insert Date

Select [Edit | Insert Date...] to insert the current date at the cursor position. The Date Insertion dialogue box will open; the examples below show the possible choices for the format.

Format | Example
2-digit year | 29/09/06
4-digit year | 29/09/2006
International (hyphens) | 2006-09-29
International (slashes) | 2006/09/29

Related Items

Insert File
Insert Time


Insert File

Select [Edit | Insert File...] to insert the contents of a file at the cursor position. A file selection dialogue box is displayed for you to select the file.

Related Items

Insert Date
Insert Time


Insert Time

Select [Edit | Insert Time...] to insert the current time at the cursor position. The Time Insertion dialogue box will open; the examples below show the possible choices for the format.

Format | Example
hh:mm | 08:35
hh:mm:ss | 08:35:03
h:mm AM/PM | 8:35 AM
h:mm:ss AM/PM | 8:35:03 AM

Related Items

Insert Date
Insert File


Paste

Select [Edit | Paste] (or press Ctrl-V) to insert the clipboard contents at the current cursor position.

Related Items

Copy
Cut


Redo

Select [Edit | Redo] (or press Ctrl-Y) to redo the edit that was just undone.

Related Items

Undo


Select All

Select [Edit | Select All] (or press Ctrl-A) to select all of the currently-open file.

Related Items

Select Line


Select Line

Select [Edit | Select Line] (or press Ctrl-Q) to select the whole line containing the current cursor position.

Related Items

Select All


Uncomment

Select [Edit | Uncomment] to uncomment the selected range. Every line that begins with an exclamation mark (!) will have that exclamation mark removed.

Related Items

Comment out


Undo

Select [Edit | Undo] (or press Ctrl+Z) to undo the most recent edit. An unlimited number of edits may be undone (depending on the memory).

Related Items

Redo


Unindent

Select [Edit | Unindent] (or press Shift-Tab) to delete tabs and spaces at the start of the selected lines. Each unindent operation reduces the indentation level of the selection by one.

Related Items

Indent
Indenting a selected region


Find...

Select [Search | Find...] to open the Search string dialogue window. After the search term has been input, select [Next] (or press F3) to find the next occurrence, or select [Previous] (or press Shift+F3) to find the previous occurrence. You can also press [Find all] (or press F5) to find all occurrences and display them in the Search tab of the Message Window.

• To close the Find dialogue window, select [Cancel] or the [ × ] button.
• Even while the Find dialogue window is being displayed, it is possible to edit the file.

Search string
Input field for the character string to find. A previously searched-for character string can also be chosen.

Search string 2, 3
Input fields for additional search terms for the [Find all] function only.

Find Command
• Next
Searches forwards from the current cursor position.

• Previous
Searches backwards from the current cursor position.

• Find all
Find all occurrences of the search term. Up to 3 search terms can be specified. All lines which contain any of the search terms are displayed in the Search tab of the Message Window. Lines which contain the first search term are listed first, then lines containing the second search term, and finally lines containing the third search term. Double-click on a line to jump to the position of the highlighted search term.

The setting of “Files to search (Find all)” controls which files are searched; this is either the current file only, or all files that are open in the editor.

Search Options
• Case sensitive
Treat uppercase letters as different from lowercase letters.

• Whole words
Only whole words which match the search term will be found.

Related Items

File Find
Next
Previous
Replace...


File Find

Select [Search | File Find...] to display the File Find dialogue window. Type the character string to search for into the Search field, and press [Search] to begin searching. While the search is in progress, the Search Progress dialogue window is displayed; it can be terminated by pressing [Cancel].

The search results are displayed in the Search tab of the Message Window; double-clicking on a line in the results jumps to that position in that file.

• To close the File Search dialogue window, select [Cancel] or the [ × ] button.
• Even while the File Search dialogue window is being displayed, it is possible to edit the file.

Search
Input field for the character string to find. A previously searched-for character string can also be chosen.

Search Options
• Case sensitive
Treat uppercase letters as different from lowercase letters.

• Whole word
Only whole words which match the search term will be found.

• Regular expression
The search string is interpreted as a regular expression.

Search Objects
• Project Folder
Search within the current project folder.

• Search Directory
Search within the directory specified by the [Search Directory] field.

Search Scope
• File Name
Name of the file to be searched. The name of a previously searched file can also be selected.

• Search Directory
Specifies the directory to be searched if the [Search Directory] setting is selected.

• Search subdirectories
Also search files within subdirectories of the specified directory.

Related Items

Find


Goto...

Selecting [Search | Goto...] moves the cursor position to a specified line in the current file. The [Jump to specified line] dialogue window will open; input the line number and press the [OK] button.

Related Items

Jumping to a specified line


Next

Select [Search | Next] (or press F3) to find the next occurrence of the last search string.

Related Items

File Find
Find
Previous
Replace


Previous

Select [Search | Previous] (or press Shift+F3) to find the previous occurrence of the last search string.

Related Items

File Find
Find
Next
Replace


Replace...

Select [Search | Replace...] (or press Ctrl+R) to open the [Replace string] dialogue window. Input the search string, the replacement string, and press [OK] or [Replace all].

Search area
• Whole file
Search and replace within the whole file.
• From cursor
Search and replace from the current cursor position onwards.
• Selected text
Search and replace only within the selected region of text.

Options
• Case sensitive
Treat uppercase letters as different from lowercase letters.
• Whole words only
Only whole words which match the search string will be found.
• Ask for confirmation
For each search string found, the item will be highlighted and the confirmation dialogue window displayed. From this window choose the action as follows:
• [Yes] button
Replace the item and search for the next occurrence.
• [No] button
Do not replace the item, but search for the next occurrence.
• [Cancel] button
Terminate the search-and-replace without replacing any more items.

Replace Commands
• [OK] button
Find the search string, and replace the first occurrence with the replacement string.

• [Replace all] button
Replace all occurrences of the search string with the replacement string.

Related Items

File Find
Find
Next
Previous


Command Prompt

Select [View | Command Prompt] and a command window will open. The current working directory will be set to the folder of the currently-open project. The NAG Fortran compiler (nagfor) can be run from the command line in this window.

Related items

Command prompt in the project directory


Detailed Build Messages

Select [View | Detailed Build Messages] to display the detailed build messages. This will show the messages from the previous build in this session, and can be left open to display messages from further builds.

Related items

Build Messages
Checking the details of build messages


File Folder

Select [View | File Folder] to open a Windows Explorer window on the folder in which the active file resides. (This is usually the same as the project folder, but can be different.)

Related Items

Project Folder
Opening the project folder in Windows Explorer


Message Window

Select [View | Message Window] to display (or not display) the Message Window. The Message Window shows the Compile messages, the Search results, or the Runtime Error.

The Message Window is displayed by default; disabling it gives more vertical space for the Editor window.

Related Items

Compile Messages
File Search
Runtime Errors
Status Bar


Project Folder Display

Select [View | Project Folder] to open a Windows Explorer window on the folder of the current project.

Related Items

File Folder
Opening the project folder in Windows Explorer


Project Manager

Select [View | Project Manager] to display (or not display) the Project Manager window.

The Project Manager window is displayed by default; disabling it gives more horizontal space for the Editor window.

Related Items

Message Window
Status Bar


Status bar

Select [View | Status bar] to display (or not display) the Status bar.

Related Items

Message Window


Tool bar

Select [View | Tool bar] to open a submenu controlling which groups of items are displayed on the toolbar.

The toolbar can contain any or all of the following 5 groups:

  1. File
  2. Edit
  3. Search
  4. Run
  5. Build

Related Items


Add files to project...

Add file to project...

Selecting [Project | Add file to project...], or selecting the [Add file to project] submenu item when right-clicking on a project in the Project Manager window, opens a browser window to select the file to add to the project. After the file is added to the project it will be opened.

Note that multiple files can be selected by shift-clicking and/or control-clicking; all the selected files will be added to the project, and all will be opened (up to the editor display limit).

Related Items

Adding source files to a project
Adding existing files to a project


Build

Select [Project | Build] to build the current project. This operation compiles the updated files and links the application. To recompile all files belonging to the project, please select [Project | Rebuild] instead. Build time error messages are displayed in the Compile Message window.

Related Items

Clean
Clean All
Compile
Compile Messages
Rebuild
Building the whole project
Compile (build) time error message confirming details
Compiling the currently being-edited files
Let's clean the whole project
Rebuilding the whole project


Clean

Select [Project | Clean] to delete compiled object files, executable files and library files (only in library projects). After this operation, the Build operation will compile all files. Any error messages produced by this operation will be displayed in the Compile Message window.

Related Items

Build
Clean All
Compile
Compile Messages
Rebuild
Building the whole project
Compile (build) time error message confirming details
Compiling the currently being-edited files
Cleaning the whole project
Rebuilding the whole project


Clean All

Select [Project | Clean All (Z)...] to delete all object files, module information files, executable files and library files from the project folder, even those files that do not belong to the project itself. After this operation, the Build operation will compile all files. Any error messages produced by this operation will be displayed in the Compile Message window.

Related Items

Build
Clean
Compile
Compile Messages
Rebuild
Building the whole project
Compile (build) time error message confirming details
Compiling the currently being-edited files
Cleaning the whole project
Rebuilding the whole project


Compile

Select [Project | Compile] to compile currently being-edited files. This operation compiles only, it does not link the application. Compile-time error messages are displayed in the Compile Message window.

Related Items

Build
Clean
Clean All
Compile Messages
Rebuild
Building the whole project
Compile (build) time error message confirming details
Compiling the currently being-edited files
Let's clean the whole project
Rebuilding the whole project


Project Settings

Selecting [Project | Project Settings...] opens the Project Settings window for the current project.

Separate tabs are provided for each of the groups of settings listed below.

Basic Settings
Controls basic settings such as project name and output file name.
Directories
Specifies directories to search for "include" files and library files.
Link
Specifies the linker to use, additional link options, and link libraries.
Fortran Compiler
Specifies the options etc. to give to the Fortran compiler.
C/C++ Compiler
Specifies the options etc. to give to the C/C++ compiler.

At the bottom of the Project Settings window, the following controls are available.

Help (H)
Display an appropriate Fortran Builder help page.
Factory default
Resets all project settings to the “factory default” (the default settings as originally shipped).
Set as default
If this box is checked, then exiting the window via [OK] will not only store the settings for the current project, but also store them as the default settings to use for future new projects.
OK
Store the current settings for the project and close the Project Settings window.
Cancel
Close the Project Settings window without storing the settings.

Related Items

New Project
Project Settings: Basic Settings
Project Settings: C/C++ Compiler
Project Settings: Directories
Project Settings: Fortran Compiler
Project Settings: Link
Changing project settings


Project Settings: Basic Settings

Output File Name
Specifies the name of the output file. For a non-library project, this is normally a .exe file, for a static library projects it will be a .a file, and for a DLL project it will be a .dll file.
Build Mode
Specifies whether the project will be built in Debug Mode or Release mode. In Debug Mode, additional information is included in the object file that allows breakpoints to be set and variables to be examined. In Release Mode, this information is not included and so setting breakpoints (or examining variables) is not possible.
Bit Mode
Specifies whether to build a 32-bit application or a 64-bit one. The default setting is 32-bit on 32-bit Windows and 64-bit on 64-bit Windows. Setting the mode to 64-bit on 32-bit Windows will prevent building of the application.
Pause at the end of program execution.
Specifies whether the program will pause at the end of execution, before closing the console window.
Keep compiling after errors.
Whether to stop compiling at the end of the first file which has an error, or to attempt to compile the rest of the project thus potentially finding additional errors.
DLL compatibility (−compatible).
Makes external linkages compatible with DLL naming conventions, and uses “stdcall” instead of “cdecl” for argument passing. This makes external procedure names and common block names uppercase, omitting the trailing underscore. Note that this option is only available in 32-bit mode; in 64-bit mode the linkages are always DLL compatible.
Produce debugging information (−g).
This option is necessary if debugging is to be performed.
Perform possibly unsafe optimisations (−Ounsafe).
Performs possibly unsafe optimisations that may depend on the numerical stability of the program.
Additional Libraries
Determines which libraries to automatically link with, as follows.
• Use the LAPACK library.
Specifies linking with the LAPACK library (and its dependencies).
• Use the NAG Fortran Library.
Specifies linking with the NAG Fortran Library.
• Use the OpenGL/GLUT Library.
Specifies linking with the OpenGL/GLUT library (not available for DLL projects).
• Use the GTK+/Glade Library.
Specifies linking with the GTK+/Glade library (not available for DLL projects).
Optimisation (−O)
specifies the optimisation level.
[None] specifies no optimisation; this is recommended for debugging.
[Level 1] specifies minimal quick optimisation.
[Level 2] specifies normal optimisation.
[Level 3] specifies further optimisation.
[Level 4] specifies maximal optimisation.

Related Items

Project Settings
Project Settings: C/C++ Compiler
Project Settings: Directories
Project Settings: Fortran Compiler
Project Settings: Link
Changing project settings


Project Settings: C/C++ Compiler

This tab specifies the options to use for compiling C and C++ files in the project. The settings are organised into sub-tabs.

Tab: Basic Settings

Follow ISO Standard (−ansi)
Specifies that the ISO (ANSI) standard should be obeyed, instead of GNU extensions.
Do not store floating point variables in registers (−ffloat-store).
When floating-point variables are assigned to and then subsequently used, store the values to memory instead of keeping them in registers and reusing the register value. In 32-bit mode the floating-point registers have larger range and precision (80-bit vs. 32-bit or 64-bit floating point) so reusing the register value is usually more accurate but can produce anomalous behaviour. This option significantly reduces performance.
Let the type char be unsigned, like unsigned char (−funsigned-char).
Change the treatment of type char from its default of signed (range -128 to +127) to unsigned (range 0 to 255).
Support ISO C trigraphs (−trigraphs).
Enable recognition of ISO C trigraphs in the source code.
Treat warnings as errors (−Werror)
Turns warning messages into error messages.
Warning Settings
Controls the display of warning messages:
• [All (−Wall)] displays all warning messages;
• [None (−w)] suppresses all warning messages;
• [Default] displays default warning messages.

Tab: Additional Options

Additional Compiler Options
Specifies additional compiler options. The [Add], [Edit] and [Delete] buttons can be used to add a new option, edit an existing option, or delete an option. The up-arrow and down-arrow buttons can be used to alter the ordering of the options.
Define preprocessor variables (−D)
Defines preprocessor (cpp) variables. Preprocessor definitions should be of the form "x" or "x=y" where "x" is a name and "y" is the string to set it to. Blanks are not allowed in the string. The [Add], [Edit] and [Delete] buttons can be used to add a new variable, edit an existing definition, or delete a definition. The up-arrow and down-arrow buttons can be used to alter the ordering of the definitions.

Related Items

Project Settings
Project Settings: Basic Settings
Project Settings: Directories
Project Settings: Fortran Compiler
Project Settings: Link
Changing project settings


Project Settings: Directories

The [Directories] tab of [Project | Project Settings] specifies where to search for modules, include files and libraries. It is divided into two subsidiary tabs as follows.

Tab: Include

Specifies where to search for Fortran modules, Fortran INCLUDE files, and C/C++ header files.

The [Add] button adds a directory to the list. To change an existing directory specification, select it and click the [Edit] button. To delete a directory from the list, select it and click the [Delete] button. The up-arrow and down-arrow keys move the selected item up and down the list of directories, respectively.

Tab: Library

Specifies where to search for library files at link time.

The [Add] button adds a directory to the list; the directory path may be directly input, or it may be selected by browsing with the folder button to the right of the directory input field. To change an existing directory specification, select it and click the [Edit] button. To delete a directory from the list, select it and click the [Delete] button. The up-arrow and down-arrow keys move the selected item up and down the list of directories, respectively.

Related Items

Project Settings
Project Settings: Basic Settings
Project Settings: C/C++ Compiler
Project Settings: Fortran Compiler
Project Settings: Link
Changing project settings


Project Settings: Fortran Compiler

This tab specifies the options to use for compiling Fortran files in the project. The settings are organised into sub-tabs.

Tab: Basic Settings

Produce information for interactive debugging.
Non-standard double complex intrinsics (−dcfuns).
Enables recognition of non-standard double precision complex intrinsic functions. These act as specific versions of the standard generic intrinsics as follows:
Specific | Equivalent Generic Intrinsic Function
CDABS(A) | ABS(A)
DCMPLX(X,Y) | CMPLX(X,Y,KIND=KIND(0d0))
DCONJG(Z) | CONJG(Z)
DIMAG(Z) | AIMAG(Z)
DREAL(Z) | REAL(Z) or DBLE(Z)
Allow the compilation of “legacy” software (−dusty)
Allows the compilation and execution of old software by downgrading the category of common errors found in such software from “Error” to “Warning”. This is not recommended for new software.
Enable OpenMP (−openmp).
Enables compilation of OpenMP directives for shared-memory parallel programming. This includes the effect of −thread_safe, except that global variables are permitted to be updated (it is assumed that the OpenMP facilities are being used to control global data access).
Specify that IMPLICIT NONE is in effect by default (−u).
Specifies that IMPLICIT NONE is in effect by default (unless overridden by explicit IMPLICIT statements), so that variables need to be explicitly declared. This decreases programming errors, and so is recommended.
Specify DEFAULT(NONE) for OpenMP PARALLEL/TASK (−u=sharing).
Specify that an OpenMP PARALLEL or TASK construct that does not have a DEFAULT clause has DEFAULT(NONE); this forces variables used within the construct to have their sharing explicitly specified. This also applies to the combined constructs such as PARALLEL DO. Accidentally sharing variables that need to be PRIVATE is a very common error, so this is recommended.
Fortran Standard
specifies the edition of the Fortran Standard that the program is expected to conform to; this only affects the generation of Extension messages (for features newer than the selected edition). This can be set to:
  • Fortran 2018 (−f2018);
  • Fortran 2008 (−f2008);
  • Fortran 2003 (−f2003);
  • Fortran 95 (−f95);
the default is Fortran 2008.
Coarray Parallel Execution
Enables or disables multiple “image” execution for coarray programs, and optionally sets the number of images to execute.
  • Enabled (−coarray=cosmp).
    Tick this box to enable parallel execution, untick to disable.
  • Set no. of images (−num_images=N).
    Tick this box, and enter the desired number of images in the input box, to set the number of images to execute. At most three digits can be entered; if left blank, the effect is the same as not ticking the box.
Kind Mode
Selecting [sequential] specifies that the kind numbers for all datatypes are numbered sequentially from 1, increasing with precision (e.g., default REAL is 1 and DOUBLE PRECISION is 2). This does not affect the interpretation of byte-length specifies (an extension to Fortran 77).
Selecting [byte] specifies that the kind numbers for INTEGER, REAL and LOGICAL will match the number of bytes of storage (e.g. default REAL is 4 and DOUBLE PRECISION is 8). Note that COMPLEX kind numbers are the same as its REAL components, and thus half the total byte length of the COMPLEX entity.
Selected [unique] specifies that the kind numbers for each intrinsic type are different from each other; this prevents accidentally using a REAL kind number to specify an INTEGER kind.
IEEE Mode
Specifies handling of floating-point errors:
[stop (on overflow/invalid/zero-divide)] causes program termination on floating overflow, invalid operand or divide by zero;
[full (including nonstop arithmetic)] allows the program to continue execution when floating-point errors occur.
Extra Information (-Warn=)
Controls production of extra warnings during compilation:
[Warn on auto-allocating assignment (=allocation)] warn if an intrinsic assignment might cause allocation of the variable (or a subcomponent thereof) being assigned to;
[Warn on auto-reallocating assignment (=reallocation)] warn if an intrinsic assignment might cause reallocation of an already-allocated variable (or a subcomponent thereof) being assigned to;
[Warn if all cosubscripts are constant (=constant_coindexing)] warn if all the cosubscripts on a coindexed variable are constant;
[Warn on subnormal result of constant expression (=subnormal)] warn if an intrinsic operation or function with normal operands produces a subnormal result (a subnormal result has reduced precision and is less than TINY).

Tab: Detail (1)

Unformatted I/O conversion (−convert=big_ieee)
Treat all unformatted files as big-endian with floating-point formats of IEEE binary-32, IEEE binary-64 and IEEE binary-128. This performs conversion on both reading and writing. The default (native) unformatted file format is little-endian with floating-point formats of IEEE binary-32, IEEE-binary-64 and double-double (2xIEEE binary-64).
Double size of default INTEGER, LOGICAL, REAL, COMPLEX (−double).
Doubles the size of default INTEGER, LOGICAL, REAL, COMPLEX and DOUBLE PRECISION. Entities with explicit kind numbers or byte lengths are unaffected.
All source files are fixed form (−fixed).
Specifies that all Fortran source files should be interpreted as being in fixed form.
Preprocess all source files using fpp (−fpp).
Specifies that all Fortran source files should be processed using fpp even if the extension would normally indicate an ordinary Fortran source file.
All source files are free form (−free).
Specifies that all Fortran source files should be interpreted as being in free form.
Traceback for runtime errors (−gline).
Compiles code to produce a traceback when a runtime error message is generated. Only routines compiled with this option will appear in such a traceback. This option increases both executable file size and execution time. Sample output is shown below:
Invalid character in real input field
Program terminated by I/O error on unit 5 (Input_Unit,Formatted,Sequential)
In READ_COORDINATES, line 27 of readfile.f90
Called by READ_DATA, line 111 of readfile.f90
Called by INITIAL, line 44 of main.f
Called by $main$, line 13 of main.f
Initialise REAL and COMPLEX variables to IEEE Signalling NaN (−nan).
Initialises most REAL and COMPLEX variables to IEEE Signalling NaN, causing a runtime crash if the values are used before being set. This affects local variables, module variables, and INTENT(OUT) dummy arguments only; it does not affect variables in COMMON or EQUIVALENCE.
Suppress underflow warning (−no_underflow_warning).
Suppresses any warning about floating-point underflow that may occur during program execution. This option only has effect when compiling a Fortran main program.
Default SAVE in non-RECURSIVE subprograms (−save).
Specifies that non-automatic local variables should be SAVEd (statically allocated) by default, except in RECURSIVE subprograms. This was a common but incorrect assumption in old (F66/77) code.
Safe execution in a multi-threaded environment (−thread_safe).
Compiles code for safe execution in a multi-threaded environment. It is incompatible with [Fortran Compiler | Detail (1) | Automatic garbage collection at runtime (−gc)]. Outside the Fortran Builder, this option must be specified for both compilation and linking. This option is not necessary when the “Enable OpenMP (−openmp)” option is used.
Implicit procedure argument checking
• [Allow inconsistent procedure calls (−mismatch)] downgrades consistency checking of procedure argument lists so that mismatches produce warning messages instead of error messages. This only affects calls to procedure that are not in the current file; calls to procedures in the current file must still be correct. This option disables the −C=calls option.
• [Allow incorrect procedure calls (−mismatch_all)] downgrades consistency checking of procedure argument lists so that mismatches produce warning messages instead of error messages. This affects all procedures, even ones in the same file. This option disables the −C=calls option.
Warning Selection
Controls display of warning messages as follows.
[All] specifies that all warning messages should be displayed.
[None] specifies that no warning messages should be displayed (−w=all).
[Suppress] suppresses the warning messages selected below.
  • Allocatable TR (=alloctr)
    use of allocatable components, dummy arguments and functions;
  • Questionable usage (=ques)
    code that is technically valid but of dubious intent;
  • Unreferenced variables (=unreffed)
    variables that are set (given a value) but never referenced;
  • Extensions to F77 (=x77)
    common extensions to Fortran 77 (now obsolete: TAB format, byte-length specifiers and Hollerith constants);
  • Obsolescent features (=obs)
    features specified as being obsolescent (or deleted) from the Fortran standard;
  • Unused dummy args (=uda)
    dummy arguments that are not used in any way;
  • Unused entities (=uused)
    anything that exists but is not used in any way:
  • Extensions to F95 (=x95)
    extensions to modern Fortran (NAG-specific features).

Tab: Detail (2)

Increase fixed-form line length from 72 to 132 characters (−132).
Increases the length of each fixed-form input line from 72 to 132 characters. This has no effect on free-form input.
Use the F77/90 version of the SIGN intrinsic (−f90_sign).
Specifies that the SIGN intrinsic should follow the Fortran 77/90 standards instead of the Fortran 95 standard (they differ in the treatment of negative zero).
Automatic garbage collection at runtime (−gc).
Enables automatic garbage collection of the executable program. It is incompatible with [Fortran Compiler | Detail (2) | Safe execution in a multi-threaded environment (−thread_safe)] and also with the Memory Trace (−mtrace) options. Outside the Fortran Builder, this option must be specified for both compilation and linking.
Hollerith (F66 style) input/output (−hollerith_io).
Enables Fortran-66 compatible input/output of character data stored in numeric variables using the A edit descriptor. This was superseded by the CHARACTER datatype in Fortran 77.
Disable the optimisation of constant propagation (−Onopropagate).
Disables the optimisation of constant propagation. This is the default at optimisation levels of 1 or lower.
Program does not use the coarray teams feature (−Onoteams).
Optimises use of coindexed objects by assuming teams are not being used. This no effect unless Coarray Parallel Execution is enabled.
Enable the optimisation of constant propagation (−Opropagate).
Enables the optimisation of constant propagation. This is the default at optimisation levels of 2 or higher.
Program does not alter the default rounding mode (−Orounding).
Specifies that the program does not alter the default rounding mode (e.g., by calling IEEE_SET_ROUNDING_MODE). This enables the use of faster code for the ANINT intrinsic function.
Procedures are RECURSIVE unless declared NON_RECURSIVE (−recursive).
Makes all procedures, except for assumed-length CHARACTER functions, capable of recursion unless they were declared to be NON_RECURSIVE. This is the default with Fortran 2018 (−f2018).
Produce obsolescence warning for use of "CHARACTER*" (−strict95).
Produces obsolescence warning messages for the use of “CHARACTER*len” or “CHARACTER*(len)”syntax. This is required by the Fortran 95 standard, but is not the default since most programs contain this syntax. The recommended alternative syntax is “CHARACTER(len)”.
Increase continuation line limit (−maxcontin=N).
Allows the maximum number of continuation lines (default 255) to be increased.
Set max internal proc host instances (−max_internal_proc_instances=N).
This only affects passing internal procedures as actual arguments, when it controls the maximum number of instances of a particular internal procedure's host procedure can be simultaneously executing. When OpenMP (−openmp) or thread-safe (−thread_safe) code is being generated, the default number is 160; for single-threaded code the default is 30.
Set the maximum size of a PARAMETER in MB (−max_parameter_size=N).
Specifies the maximum size of a named constant (PARAMETER) may have, in mebibytes; the default value is 50 mebibytes. This option also affects evaluation of constant expressions (in executable statements) at compile time.

Tab: Runtime Check

Runtime Check Options (−C=)
Specifies runtime checking options; select one of the following:
[No] specifies no checking;
[All (=all)] specifies all checking except for −C=undefined;
[Most (−C)] specifies all checking except for −C=undefined and −C=dangling;
[Select Options] specifies the selected options from the table, as follows.
Option | Checks
Array bounds (=array) | array bounds, array shapes, and character subranges.
Procedure references (=calls) | everything about a procedure reference: whether it is a function or subroutine, the number of arguments, and for each argument (and the function result) its class, data type, whether it is a procedure, etc.
DO loops for zero step (=do) | whether variable-sized step values for DO loops are zero.
POINTER references (=pointer) | before referencing or defining a pointer, check that it is not disassociated or (known to be) undefined. Also checks allocatable arrays for being allocated before each reference/definition.
Invalid recursion (=recursion) | for recursive calls of any procedure that is not RECURSIVE.
Bit intrinsic arguments (=bits) | that arguments to bit intrinsic function (such as BTEST) are within the range required by the standard (usually 0 to BIT_SIZE).
Dangling pointers (=dangling). | marks dangling pointers as being undefined pointers, and records how they became dangling.
Integer overflow (=intovf) | for overflow in integer operations.
OPTIONAL references (=present) | before referencing or defining an optional dummy argument, that the argument is present.
Undefined variables (=undefined) | for references to undefined variables. The entire program, including any libraries used, must be compiled with this option. Therefore this option cannot be used with NAG Library, LAPACK, GTK+ or OpenGL projects.
Memory Trace Options (−mtrace=)
Specifies runtime memory tracing options; select one of the following:
[No] specifies no tracing;
[All (=all)] specifies all tracing options;
[Select Options] specifies the selected options listed below.
Option | Effect
Display addresses (=address) | displays the address of each allocation and deallocation.
Display file/line info if known (=line) | displays location information for most allocations and deallocations.
Protect memory data structures from user program (=paranoia) | uses the hardware protection mechanism against inadvertent modification.
Display size in bytes (=size) | displays the size of each allocation.
[Display and check mtrace output] controls whether the memory trace output is intermixed with the program output, or whether it is checked for errors and displayed in a Fortran Builder Editor window after execution.

Tab: Additional Options

Additional Compiler Options
Specifies additional compiler options. The [Add], [Edit] and [Delete] buttons can be used to add a new option, edit an existing option, or delete an option. The up-arrow and down-arrow buttons can be used to alter the ordering of the options.
Define preprocessor variables (−D)
Defines preprocessor (fpp) variables. This only has effect on files that are preprocessed by fpp; these are .ff, .ff90 and .ff95 files; if the [Preprocess all source files using fpp (−fpp).] option is used, then all other Fortran files will also be affected. Preprocessor definitions should be of the form "x" or "x=y" where "x" is a name and "y" is the string to set it to. Blanks are not allowed in the string. The [Add], [Edit] and [Delete] buttons can be used to add a new variable, edit an existing definition, or delete a definition. The up-arrow and down-arrow buttons can be used to alter the ordering of the definitions.

Related Items

Project Settings
Project Settings: Basic Settings
Project Settings: C/C++ Compiler
Project Settings: Directories
Project Settings: Link
Changing project settings


Project Settings: Link

The [Link] tab of [Project | Project Settings] specifies linker settings, link options, and libraries. This is divided into two subsidiary tabs.

Tab: Basic Settings

Additional Link Options
Manually specifies additional link options. This can be used to specify link options that are unknown to the Fortran Builder.
Link Libraries
Specifies additional libraries to link with. The [Add] button adds a library to the list; the library path may be directly input, or it may be selected by browsing with the folder button to the right of the library path input field. To change an existing library specification, select it and click the [Edit] button. To delete a library from the list, select it and click the [Delete] button. The up-arrow button moves the selected item up the list, and the down-arrow button moves the selected item down the list; if one library depends on another, the dependent one should be listed later in the list.

Tab:Options

Specifies link options.

Fortran Link Options
• [Link with static nagfor runtime library (−unsharedrts).] specifies that the static NAG Fortran runtime library should be linked. This increases the executable program size, but allows it to be executed on a machine which does not have the NAG Fortran Compiler installed.
No console window.
Do not display the console window (−mwindows). When using GTK+, OpenGL or another GUI, this prevents needless display of the console window.
Strip symbols from executable.
Specifies that all symbol and debugging information should be stripped (−s) from the executable. This reduces the size of the executable, and prevents debugging.

Related Items

Project Settings
Project Settings: Basic Settings
Project Settings: C/C++ Compiler
Project Settings: Directories
Project Settings: Fortran Compiler
Changing project options
Preventing display of the console window


Rebuild

Select [Project | Rebuild] (or press F10) to rebuild the current project. This operation compiles all files belonging to the current project. Rebuild-time error and warning messages are displayed in the Compile Message window.

Related Items

Build
Clean
Clean All
Compile
Compile Messages
Building the whole project
Compile (build) time error message confirming details
Compiling the currently being-edited files
Let's clean the whole project
Rebuilding the whole project


Remove files from project...

Selecting [Project | Remove files from project...] opens the [Remove Files from Project] dialogue window. The file to be removed should be selected, and the [OK] button pressed. A file can also be removed from a project by right-clicking the filename in the Project Manager window, and selecting [Remove file from project] from the submenu. Removing a file from a project does not delete it from the disc.

Note that when using [Project | Remove files from project...], multiple files can be selected from the [Remove File from Project] dialogue window by shift-clicking and/or control-clicking; all the selected files will be removed from the project.

Related Items

Removing a file from a project


Break point

Selecting [Run | Break point] inserts a breakpoint at the current cursor position, or deletes an existing breakpoint at that position. A breakpoint can also be inserted/deleted by left-clicking column zero, between the line number and the source code in the edit window.

Related Items

Next Break point
Previous Break point
Inserting and deleting breakpoints
Setting a breakpoint


Command Line

Selecting [Run | Command Line...] opens the Command Line dialogue window, for setting the arguments to be passed to the program. This can specify both command line arguments and input/output redirection. Press [OK] to set the command line.

Input/output redirection is specified on the command line as follows.

<filename | Read standard input from filename
>filename | Write standard output to filename
>>filename | Append standard output to filename
>&filename | Write both standard output and standard error to filename
2>>filename | Append standard error to filename

Related Items

Specifying execution arguments


Debug Execute

Selecting [Run | Debug Execute] executes the program in debug mode. If there are any recently changed files, the program will be built; if there are any build errors, the program will not be executed.

Related Items

Starting to debug
Debug execution, stopping at a particular line


Execute

Selecting [Run | Execute] runs the application. If any files have recently changed, the application will first be built. If there are any build errors, the application will not be run.

Related Items

Debug Execute
Running the program


Pause on Exit

Selecting [Run | Pause on exit] toggles the “Pause on Exit” setting. If the setting is On,

    Press ENTER to continue---
will be displayed in the console window when the program finishes execution. If the console window is not being displayed, this setting is ineffective and the program will not pause.

Related Items

Preventing display of ‘Press ENTER to continue--’ on program termination


Run to Cursor

Selecting [Run | Run to Cursor] (or pressing F4) will execute the application until it reaches the current cursor position. If there are any recently changed files, the application will be built; if there are any build errors, the application will not be executed.

Related Items

Step
Trace
Performing Step, Trace and Run-to-Cursor Operations


Step

Selecting [Run | Step] (or pressing F8) will step a program being debugged through a single line of execution, completely executing any procedure references therein. If the program is not executing, a debug execution is started and the program stops at the beginning of the main program. If there are any recently changed files, the program will be built first; if there are any build errors, the program will not be executed.

Related Items

Run to Cursor
Trace
Performing Step, Trace and Run-to-Cursor operations


Terminate execution

Selecting [Run | Terminate execution] terminates execution of a currently-executing program.

Note that this is an abnormal termination; currently-open files that are (or were) being written to will not be properly closed and could become corrupted.

Related Items

Stopping debugging


Trace

Selecting [Run | Trace] ( or pressing F7 ) will step a program being debugged into a single line of execution. If the line has any procedure references, the program will stop at the beginning of the procedure; otherwise, it will stop at the next line. If the program is not executing, a debug execution is started and the program stops at the beginning of the main program. If there are any recently changed files, the program will be built first; if there are any build errors, the program will not be executed.

Related Items

Step
Run to Cursor
Performing Step, Trace and Run-to-Cursor operations


Watch Variable

Selecting [Run | Watch Variable...] (or pressing F9) while debugging opens a [Watching Variable Name] dialogue window. Type the name of the variable to watch, and press [OK]. The current value of the variable will be displayed; this value will be updated each time the program stops during debugging. To change the value of the variable, select the variable and click the [...] button beside the value.

Related Items

Displaying the value of a variable while debugging
Changing the value of a variable while debugging


Call Graph

Selecting [Tool | Call Graph...] opens a dialogue window to select the files you wish to create a call graph for. Pressing the [OK] button will produce the call graph and write it to the file ‘callgraph.txt’; this file will be opened automatically in the Fortran Builder. Only Fortran source files can be processed by this tool.

Related Items

Creating a call graph for Fortran source files


Editor Settings

Selecting [Tool | Editor Settings...] opens the Editor Settings dialogue window. After making any changes, press [OK] to set the options, or [Cancel] if no changes are desired. The [Default] button can be used to reset the editor settings to their default values.

The editor settings are organised into the following tabs.

Tab: Options

Persistent State
Select to specify that the open project and files should be restored on exiting and re-entering the Fortran Builder.
Create backup file
Select to specify that backup files should be created.
Editor options
• [Auto indent] specifies whether new lines should be automatically indented to the same level as the previous line.
• [Display ruler] specifies whether to display the column ruler.
• [Display line numbers] specifies whether line numbers should be displayed.
• [Undo before save point] specifies whether Undo should be able to undo edits before the last save (Ctrl+S) command.
• [Display TABs] specifies whether TAB characters should be displayed in an indicatory manner.
• [Line spacing] specifies the amount of spacing between lines in pixels (0-99).
• [TAB stops] specifies the number of characters between TAB stops.
Fortran 77 Options
• [Display column separators] specifies whether a column separator should be displayed before columns 6, 7, 73 and 81. This is only for fixed-form files.
• [Colour lower case keywords] specifies that lower case keywords should be recognised and displayed in the keyword colour.
• [Column separator colour] specifies the colour of the column separator, if it is being displayed.
Fortran 90/95 Option
• [Use TAB character] specifies whether TAB characters may be used when indenting (instead of only spaces).
[C/C++ Option]
• [Use TAB character] specifies whether TAB characters may be used when indenting (instead of only spaces).

Tab: Font

Font
Specifies the basic font used by the editor.
Size
Specifies the size of the font, in points.
Sample
Display a sample of the selected font.

Tab: Colour

Background colour
Specifies the normal background colour; the [Change] button brings up a colour setting window to select the new colour.
Wallpaper background colour
Specifies the character background colour to use on wallpaper. This is the same setting as [Tool | Wallpaper Settings | Text background colour].
Item settings
Controls the foreground colours and styles for different syntax items. (For some items, the background colour is also controlled.)
The possible settings are as follows.
Item | Meaning
Character | Names, operators, and other text that is not covered by other items. This includes spaces and tabs.
Keyword | Language keywords
Character '...' | Character/string constants delimited by quote (') characters.
String "..." | Character string constants delimited by double-quote (") characters.
Number | Integer and Real literal constants.
Comment | Comment lines and inline comments.
Preprocessor | Preprocessor (cpp/fpp) lines such as #ifdef.
Statement label | Fortran statement labels.
Intrinsic function | Fortran intrinsic procedures.
Err/Warn Line | How to highlight error and warning lines.
Debugging Line | The current source line when stopped in the debugger.
Line number | Line number.
Ruler | Column ruler.
Selection area | The area currently selected.
Search 1 | Matches for search string 1.
Search 2 | Matches for search string 2.
Search 3 | Matches for search string 3.

Tab: Assistance

Auto completion events
Controls when assistance is done, select from:
• On any key input
• On TAB key input
• Disable auto completion
Fortran auto completion
Controls auto completion of Fortran source code.

• [Keyword] specifies that the assistant should offer Fortran language keyword completion.
• [Intrinsic procedure] specifies that the assistant should offer completion for intrinsic procedure names.
• [Variable] specifies that the assistant should offer completion for variable names.
• [Component] specifies that the assistant should offer completion for component names.

Note: [Variable] and [Component] are only effective after the source file has been compiled at least once.
Case of Fortran 77 auto completion
Specifies whether completion in fixed-form source files should be upper or lower case.
Case of Fortran 90/95 auto completion
Specifies whether completion in free-form source files should be in upper or lower case.

Related Items

Wallpaper Settings
Changing the colours in the editor display
Restoring Fortran Builder context on restart


Environment Variable Settings

Selecting [Tool | Environment Variable Settings...] opens the Environment Variable Settings dialogue. This controls local environment variable settings within the Fortran Builder; these affect not just the Fortran Builder but are also available to programs run from the Fortran Builder.

The [Add], [Edit] and [Delete] buttons can be used to add new environment variables and to modify or delete existing ones.

Changes to the environment variable settings only have effect after restarting the Fortran Builder.

Related Items


Generate Interface Module

Selecting [Tool | Generate Interface Module...] opens a dialogue window for generating interfaces for external procedures.

Dialogue Window: Generate Interface Module

Module Name
Specifies the name of the module that will contain the generated interfaces. Note that this must be a module that does not already exist in the program, otherwise it will not work correctly. The default module name is “interfaces”.
Output File Name
Specifies the name of the source file to contain the generated module; the file type is always “.f90”. There cannot already be a file with the same name (ignoring the file type) in the project. By default the output file name will be the same as the Module Name.
Output File Directory
Specifies the folder which will contain the generated module source file. The default is the project folder.
Comment Options
Specifies whether the module should begin with a comment identifying the date (and time) of generation, and whether each interface should contain a comment identifying the file that contains the external procedure's source code. The default is to generate the “today” comment, and not to generate “provenance” comments.

Generating the module

The format of the generated module is controlled by the current “Polish Settings”. Note that analysis of the source files may be affected by the current compiler options.

The generated source file is automatically added to the current project.

If there are no external procedures in the current project, the generated module will be empty. Note that interfaces are not generated for any other kind of procedure: dummy, internal and module procedures are all excluded.

Related Items

Polish Settings
Project Settings


Polish Fortran Source

This will polish (re-format) the Fortran source file that is currently open in the editor, according to the current Polish Settings.

This command can be used on both fixed-form and free-form source files. When used on a free-form source file, the file is polished “in place”; to revert back to the unpolished version, use [Edit | Undo].

When used on a fixed-form source file, a new free-form source file is created (with the same file name with the file type changed to ‘.f90’), the fixed-form source file is removed from the project and the new file is added to the project; to revert back to the unpolished version, remove the new file from the project and add the fixed-form source file back to the project (the contents of the fixed-form source file itself are unchanged by this operation.

This command is not available when there is no file open in the editor, or the current file is not a Fortran source file.

Related Items

Add file to project...
Polish Settings
Remove file from project...
Undo


Polish Settings

Selecting [Tool | Polish Settings...] opens the Polish Settings dialogue window. These settings control the operation of [Tool | Polish Fortran Source].

Basic options

Right margin (10-1024) [default 78]
Specifies the right margin (maximum line length) of the output. This must be at least 10 more than the left margin, and at least 10 more than the maximum indent.
Indent step (0-16) [default 2]
Specifies the amount of indentation for each nested construct.
Left margin (0-16) [default 4]
Specifies the left margin (number of blanks at the beginning of each line.
Maximum indent (0-130) [default 60]
Specifies the maximum level of indentation.
Indent continuation line (0-16) [default 2]
Specifies the additional indentation for continuation lines.
Identifier Case [default lower]
Specifies UPPER case, lower case, Capitalised (initial upper case letter), Camel_Case (initial capital and capital after underscore), or Asis for names.
Keyword Case [default Capitalised]
Specifies UPPER case, lower case, Capitalised (initial upper case letter), or Camel_Case (initial capital and capital after underscore) for Fortran keywords.
Label after indentation [default disabled]
Select to specify that labels should appear after indentation (instead of before).
Blank line after declarations [default enabled]
Select to specify that there should be at least one blank line between the declarations and the first executable statement.
Terminate DO loops with ENDDO [default enabled]
Select to cause DO loops to end with END DO statements.
Old-style relational operators [default disabled]
Select to use old-style relational operators (e.g. ‘.LT.’) instead of new-style ones (e.g. ‘<’).
Right-align continuation ampersands [default disabled]
Select to align the ampersands used for continuing a line, at the right margin.
Move FORMAT to executable end [default disabled]
Select to move FORMAT statements to follow the executable statements.
Optional commas in FORMAT [default Insert]
Controls insertion and deletion of optional commas in FORMAT statements; this may be ‘Insert’ (insert commas between all edit descriptors), ‘Remove’ (remove commas between edit descriptors when optional) or ‘Asis’ (same as in the original source).
Array constructor brackets [default Asis]
Specifies the kind of brackets to use for array constructors; this may be ‘[ ]’ (use square brackets), ‘(/ /)’ (use parenthesis-slash sequences) or ‘Asis’ (same as in the original source).
KIND= in type declarations [default Asis]
Controls insertion or removal of ‘KIND=’ before the kind parameter numbers in Type Declaration and Component Declaration statements.
CHARACTER declaration style [default Asis]
Controls the style used for CHARACTER declarations; this may be ‘Use keywords’ (modern style with LEN= and KIND= keywords), ‘Use KIND= keyword only’ (modern style with KIND= keyword but no LEN=keyword), ‘Moden style without keywords’ (modern style without any keyword) or ‘Asis’ (same as in the original source)
Double colon (::) in declarations [default Asis]
Specify whether declaration statements with an optional double colon should have one inserted, have an existing one removed (as long as that is allowed), or remain asis.
Align double colons at column [default disabled]
Specify whether to align the double colons in declaration statements at the specified column. There is no effect when the double colon would appear after that column anyway.
Add names to ENDs [default Keyword only]
Specifies whether each subprogram END statement should include the subprogram keyword and name (Keyword & name), include the subprogram keyword only (Keyword only), not include either (No keyword/name) or be left as is (Asis).

Label options

Keep unused labels [default disabled]
Select to keep (instead of deleting) unused labels.
Relabel statements [default enabled]
Select to enable statement relabelling; if this box is not selected, the remaining label options have no effect.
First statement label [default 100]
The label to use for the first labelled statement.
Label step [default 10]
The amount to add for each successive label.
Relabel FORMATs separately [default disabled]
Select to specify that FORMAT statements should be relabelled in a separate sequence from other statements; if this box is not selected, the remaining label options have no effect.
First FORMAT label [default 90000]
The label to use for the first FORMAT statement.
FORMAT label step [default 10]
The amount to add for each successive FORMAT label.

Comment Options

Alter comments [default disabled]
Specifies whether comments should be altered; if this is not set, the other comment options have no effect.
Delete all comments [default disabled]
Select to delete all comments.
Indent comments [default enabled]
Select to indent comment lines to the same level as the source code.
Indent comment marker [default enabled]
Select to indent the comment marker (instead of placing it in column 1); thisonly has effect if comments are being indented.
Wrap long comments [default enabled]
Select to wrap comments longer than the right margin
Break long words when wrapping [default disabled]
Select to allow long comments to be broken in the middle of words, rather than only at spaces.
Use blank lines [default enabled]
Select to produce completely blank lines for comment lines that are blank except for the comment marker.
Delete blank lines [default disabled]
Select to delete blank comment lines.
Inline comment column (0-130) [default 35]
Specifies the column for placing inline comments.

Enhanced Polish options

Use Enhanced Polish [default disabled]
Use the enhanced polish tool instead of the normal one. This enables the options below, but can only be used on a compilable file.

When enhanced polish is used, the Asis option for “Add names to END statements” acts as if it were “Keyword only”, the Asis option for “Array constructor brackets” as as if it were “(/ /)”, and the Asis option for “Double colon (::) in declarations” as as it it were “Insert”.

Add argument keywords [default disabled]
Add keywords to actual arguments in references to user-defined procedures with an explicit interface and at least two dummy arguments, and in references to intrinsic procedures and intrinsic module procedures with at least three dummy arguments (except for MAX and MIN, where it is at least three actual arguments).
Remove intrinsic statements [default disabled]
Remove intrinsic procedure names that were not passed as actual arguments from INTRINSIC statements, and if all the names in an INTRINSIC statement are removed in this way, the INTRINSIC statement itself is removed.
Intrinsic procedure case [default As names]
Specify whether the case of intrinsic procedure names should be as the same as ordinary names (like normal polish), or the same as keywords.
Component Case
Default, or override the default rules for component names: UPPER, lower, Capitalised, or Camel_Case.
Construct name Case
Default, or override the default rules for construct names: UPPER, lower, Capitalised, or Camel_Case.
Intrinsic procedure Case
Default, or override the default rules for intrinsic procedure names: UPPER, lower, Capitalised, or Camel_Case.
PARAMETER Case
Default, or override the default rules for named constants: UPPER, lower, Capitalised, or Camel_Case.
Procedure Case
Default, or override the default rules for procedure names: UPPER, lower, Capitalised, or Camel_Case.
Type-bound procedure Case
Default, or override the default rules for type-bound procedure names: UPPER, lower, Capitalised, or Camel_Case.
Derived type parameter Case
Default, or override the default rules for derived type parameter names: UPPER, lower, Capitalised, or Camel_Case.
Derived type Case
Default, or override the default rules for derived type names: UPPER, lower, Capitalised, or Camel_Case.
Variable Case
Default, or override the default rules for variable names: UPPER, lower, Capitalised, or Camel_Case.
Specify exceptions to the case rules
This box contains a list of names that should always have the case given. Names should be separated by commas or spaces. For example, if the list contains xYz, all occurrences of the name XYZ (regardless of case, so including xyz, xYZ, etc.) will appear as xYz after polishing.

Buttons

Help
Clicking the Help button will bring up this page of the Fortran Builder Help.
Default
Clicking the Default button will reset all polish options to the factory default settings.
OK
Clicking the OK button will apply any changes to the polish settings, and exit Polish Settings.
Cancel
Clicking the Cancel button will exit Polish Settings without applying any changes.

Related Items

Reformatting Fortran source code


Unify Precision

Selecting [Tool | Unify Precision...] opens a dialogue window to begin unifying the precision of the Fortran files in the project. Unifying the precision involves adding a named constant kind specifier to every floating-point literal constant, and changing the declarations of all floating-point variables and parameters to use the same named constant as the KIND value. This named constant is accessed from a precision module; an appropriate USE statement for the module is added. Note that by “floating-point” we mean not just Real (and Double Precision) but also Complex. If a variable is implicitly typed, an explicit type declaration for it will be created. Also, references to non-generic intrinsic functions will be changed to the generic form, e.g. “DCOS(X)” → “COS(X)”.

Firstly, a warning dialogue is displayed explaining that this will change all Fortran files, and how to undo the effects (this dialogue can be suppressed). If the Unify Precision action is not cancelled at the warning stage (or the warning dialogue has been suppressed), the Unify Precision settings dialogue is displayed.

Unify Precision settings

Precision parameter name [default wp]
Specifies the name of the precision parameter to be used for literal constants and type declarations.
Precision module name [default working_precision]
Specifies the name of the module which will contain the definition of the precision parameter.
Program precision [default Double]
Specifies the precision that the program is expected to be in, and which should be used in the definition of the precision parameter. If a scoping unit in the program uses a different precision than this, a warning message will be produced. The program precision can be set to ‘Single”, ‘Double” or ‘Quadruple’ precision.
Entities that already have KIND specified [default Unify]
Specifies the action for entities that already have a KIND type parameter specified; “Unify” unifies them, “Leave as is” leaves them as is.
Create precision module [default checked]
This check box controls whether to automatically create the precision module with a definition for the precision parameter that specifies the desired program precision. If created, the new file will be added to the project. This should be unchecked if the precision module already exists.

The filename that will be used for the precision module is displayed below this box. This is not an editable field — the filename is automatically derived from the name of the precision module.

Related Items


Wallpaper Settings

Selecting [Tool | Wallpaper Settings...] opens the Wallpaper Setting dialogue window. This allows you to set your favourite image to be used as background in the editor screen. Settings are provided to retain the readability of the source code when this is done.

A single image can be set as wallpaper, or a folder containing images. For a folder, the wallpaper changer will switch between images in the folder at a specified interval.

Wallpaper Settings dialogue

Function |  | Explanation
Transparent Processing |  | Whether to use the transparency settings for the wallpaper and text background. If this is [No], the text background is completely transparent and the wallpaper is not. If this is [Yes], the transparency settings for Wallpaper and Text Background are followed. The effects of the current setting are shown in the test window.
Wallpaper Transparency (0-255) |  | The transparency setting for the wallpaper; this may be typed in directly or selected using the slider. The effect of changing this can be seen in the pictures of the cat below.
Original Size Viewer |  | Displays the image in its original size.
Image File/Folder Setting | Select Image File | In this mode a single image file is used as the wallpaper.
 | Select Image Folder | In this mode all the image files in a folder are used as the wallpaper. This mode enables the automatic wallpaper changer.
 | Select Image | This starts an Open File dialogue window to choose the image file. Supported image file types are BMP and JPEG. • The image file is checked for validity before being set.
 | Select Folder | This starts a Folder Selection dialogue window to choose the image folder. Supported image file types are BMP and JPEG. A random picture from the folder is displayed in the test window. • The folder must contain at least one image file to be accepted.
 | Change Interval | The automatic changer will select a different wallpaper after each interval. The change interval can range from 1 minute to 1 hour. • This only has effect if the image folder has more than one image.
 | Unload | This unloads the current wallpaper setting, disabling the feature.
Text Background Colour | Change | This starts a dialogue to select the text background colour to use with the wallpaper.
 | Editor Background | This sets the text background colour for wallpaper to be the same as the text background colour setting in the editor.
 | Test View | Specifies the text to display in the test window.
 | Manual Auto | Specifies the transparency processing mode for the text background colour. Manual: use the specified transparency setting. Auto: set the transparency automatically.
 | Text Background Colour Transparency (0-255) | Specifies the transparency of the text background colour. • This is ignored if the mode is [Auto].

Outline of Wallpaper Transparent Processing

The visibility of the displayed text will naturally be reduced when the wallpaper is displayed in the background of the editor as is. Therefore, the wallpaper is thinly displayed by assimilating it into the background colour; this improves the visibility of the displayed text. This process works by layering a translucent wallpaper over the background. The transparency of the wallpaper can be set between 0 and 255. At 0, the wallpaper is not at all transparent (i.e. it is displayed as is). At 255, the wallpaper is completely transparent (i.e. only the background colour is visible).

Examples
↓ The background colour is set to ♦ for these examples.↓
Transparency 0 Opaque cat | Transparency 92 Slightly transparent cat
Transparency 128 Moderately transparent cat | Transparency 170 Very transparent cat

Outline of processing that puts a shadow behind text displayed on wallpaper (for the [Auto] setting).

To improve the visibility of the text in front of the wallpaper, the shadow is cast only behind the text. This is achieved by raising its transparency only in the text part.
Moreover, the strength of the shadow is inversely proportional to the transparency of the wallpaper.

↓ Examples according to transparency of wallpaper, with text background colour ♦ ↓

Transparency 0 Lettering on opaque cat | Transparency 92 Lettering on slightly transparent cat
Transparency 128 Lettering on moderately transparent cat | Transparency 170 Lettering on very transparent cat

Related Items

Changing the wallpaper background
Editor Settings

gEdit logo Japanese copyright statement


About Fortran Builder

Selecting [Help | About Fortran Builder] will display information about the Fortran Builder, including the version number.

Related Items


Fortran Builder Help

Selecting [Help | Fortran Builder Help] opens up a help window with the online Fortran Builder help files.

Related Items

Displaying help information about a keyword.


NAG Fortran Library Help

Selecting [Help | NAG Fortran Library Help] opens up a help window with the online NAG Fortran Library help files. This menu item is only available if the NAG Fortran Library is installed.

Related Items


NAG UK Home Page

Selecting [Help | NAG UK Home Page] will display the home page of The Numerical Algorithms Group Ltd. in the default web browser.

Related Items


Support Home Page

Selecting [Help | Support Home Page] will display the Customer Support page of The Numerical Algorithms Group Ltd. in the default web browser.

Related Items


Fortran Builder Operation Guidance

Edit

Switching between edit files
Closing a file being edited
Jumping to a specified line
Commenting-out and uncommenting a region
Changing the colours in the editor display
Turning auto-completion on and off
Copying and pasting rectangular sections
Indenting a region

Project

What is a project?
Creating a new file in the project
Adding existing files to a project
Removing a file from a project
Changing project settings
Rebuilding the whole project
Building the whole project
Compiling the currently being-edited file
Cleaning the whole project
Checking the details of build messages
Jumping to the error line
Command prompt in the project folder
Opening the project folder in Windows Explorer

Help

Displaying help on keywords in source files

Debug

Inserting and deleting breakpoints
Moving to the next (previous) breakpoint
Starting to debug
Stopping debugging
Performing Step, Trace and Run to Cursor Operations
Displaying the value of a variable while debugging
Changing the value of a variable while debugging

Run

Running the program
Specifying execution arguments

Other

Converting old fixed-form Fortran files to free format
Creating a static library
Generating a DLL import library
Reformatting Fortran source code
Creating a call graph for Fortran source files
Restoring Fortran Builder context on restart
Preventing display of the console window
Preventing display of “Press ENTER to continue--” on program termination
Redistribution of 32-bit applications
Redistribution of 64-bit applications

Related Items


Switching between edit files

The file that is currently open is displayed in the upper part of the Editor area as follows.

To switch between these files, click the tab where the file name is displayed.

The tab of the file being edited is highlighted in yellow. In the image above, “sub.c” is being edited.

Related


Closing a file being edited

To close a file that is currently open, right-click on the tab for the file in the upper part of the Editor area and select [ Close ] from the menu.

If the file being closed has been edited, you will be asked whether to save the changes.

Related


Jumping to a specified line

When editing a file, it is possible to jump to a specified line number. To do this select [Search | Goto...], enter the line number in the dialogue window that opens, and press [OK].

menu Search Goto...

Jump dialogue box

The line number cannot be less than 1 or more than the number of lines in the file.

Related

Goto Line


Commenting-out and uncommenting a region

Commenting-out a region

The Fortran Builder has commands for commenting-out and uncommenting a region. The commenting-out effect is achieved by prefixing the line with an exclamation mark.

First select the region to comment out (if a part of a line is selected, that line is included in the region).

Now select [Edit | Comment out] from the menu.

menu Edit Comment out

The result is as follows: each line (whether already a comment or not) has an exclamation mark inserted before column 1.

lines commented out

The hotkey Ctrl+1 (hold down Ctrl and press 1) can also be used to comment-out a region.

Uncommenting a region

The commenting-out effect can be undone in whole or in part. First, select the region to uncomment (if some of the region is already uncommented, that does not matter).

lines to uncomment

Now select [Edit | Uncomment] from the menu.

menu Edit Uncomment

The result is as follows: each line whose initial character was an exclamation mark has that exclamation mark removed.

The hotkey Ctrl+2 (hold down Ctrl and press 2) can also be used to uncomment a region.

Related

Comment out
Uncomment


Changing the colours in the editor display

The colours used by the editor display for the background, keywords, etc., can be changed by selecting [Tool | Editor Settings] from the menu.

menu Tool Editor Settings

As shown below, select the [Colour] tab when the settings dialogue window is displayed.

Editor Settings Colour

To change the background colour, press the [Change] button beside the background colour.

The colours used for keywords, comments, etc., can be changed individually. Select the appropriate line in [Item settings], and press the [Change] button beside the foreground colour.

Related

Editor Settings
Wallpaper Settings


Turning auto-completion on and off

Automatic completion of Fortran keywords by the editor assistance function is on by default. Editor assistance displays candidate Fortran keywords as a potential keyword is typed, supporting the input of comparatively long Fortran keywords by menu selection. Editor assistance is only supplied for Fortran source files.

Editor assistance is controlled by selecting [Tool | Editor Settings] from the menu.

Tool Editor Settings

When the dialogue window is displayed, select the [Assistance] tab; checking (unchecking) the Keyword box enables (disables) editor assistance for keywords.

Editor Settings Assistance

Related

Editor Settings
Using editor input assistance


Copying and pasting rectangular sections

The Fortran Builder contains a rectangular selection function that is convenient for editing array data etc.. An arbitrary rectangular area can be selected, and this can then be copied, cut, or pasted.

Move the mouse to the upper left corner of the rectangle to be selected, and press the Alt key; while the Alt key is down, press the left mouse button. Then move the cursor to the lower right corner of the area to be selected and release the mouse botton. This selects a rectangular section.

The selected area can then be copied (Ctrl+C etc.) or cut (Ctrl+X etc.) as usual. The paste operation (Ctrl+V etc.) automatically becomes a rectangular pasting.

Related


Indenting a region

In order to make a program easy to read, it is common to indent the source code. This is a function to make such operations easy.

First, select the region you wish to indent.

region to indent, selected

After that, the TAB key will indent the region, and Shift+TAB will unindent the region. Alternatively, it is possible to perform this operation from the menu, by selecting [Edit | Indent] or [Edit | Unindent].

menu Edit Indent

Related

Indent
Unindent


What is a project?

A project is a summary of information about the source files, header files, build methods, link libraries, etc., that are needed to make a single executable file, library or DLL.

The Fortran Builder uses projects to create executables and libraries.

As shown below, there are seven kinds of project.

Console Application | An application that uses a console window for input and/or output.
LAPACK Application | A console application that uses the LAPACK linear algebra library.
NAG Library Application | A console application that uses the NAG Fortran Library.
OpenGL Application | An application that uses OpenGL for graphical output.
GTK+ Application | An application that uses the GTK+ graphical user interface library (optionally using Glade).
Static Library | A library of routines to be statically linked into programs.
Dynamic Link Library (DLL) | A library of routines to be dynamically linked into programs.

An executable file (.exe) is made in each project except for (static and dynamic) libraries.
The static library project produces a static library file (.a).
The dynamic link library project produces a DLL file (.dll).

The project type selected should be appropriate to the desired outcome, i.e. an executable project for making an executable file or a library project for making a library.

An application that is executed from the command line is made in an ordinary console application, an LAPACK application and a NAG Library application.
When an LAPACK application is made, the LAPACK libraries are automatically linked, and template (sample) programs are available.
When a NAG Library application is made, the NAG Fortran Library is automatically linked, and template (example) programs are available.*

When graphical output is desired, the OpenGL or GTk+ application project can be used. When such a project is made, the OpenGL or GTk+ library is automatically linked, and template (sample) programs are available.

*It is necessary to install the NAG Fortran Library separately.

Related Items

New Project
New Console Application
New LAPACK Application
New Static Library
New DLL (Dynamic Link Library)
New NAG Library Application
First program using the Fortran Builder (Hello Fortran Builder!)
Program using the LAPACK library
Creating a DLL (Dynamic Link Library)
Program using the NAG Fortran Library
Creating a program using OpenGL/GLUT
Creating a GTK+ application
Open Project
Project Settings


Creating a new file in the project

This creates a new file, adds it to the project, and opens it.

A new file can be created by selecting [File | New | File] from the menu, pressing Ctrl+N, or clicking the New File icon on the toolbar.

menu File New File

This will display a dialogue window; select the file type and press [OK].

Create File type

Then type the file name into the dialogue window as shown below and press [OK]; the file will be created.

Create File name

• The new file is automatically added to the currently-open project.

Related Items

New File
File Creation Dialogue


Adding existing files to a project

To add one or more existing files to a project select [Project | Add files to project...] from the menu, or select from the menu displayed by right-clicking on the project name in the Project Manager area.

menu Project Add files to project...

Right-click Add files to project...

A dialogue window will open; select the file and press [Open].

Multiple files can be selected by shift-clicking and control-clicking in the dialogue window.

Related Items

Add to Project
Adding a source file to the project


Removing a file from a project

To remove a file from the current project select [Project | Remove files from project...] from the menu, or by right-clicking on the file to be removed in the Project Manager display and selecting [Remove file from project].

menu Project Remove files from project...

Right-click menu Remove file from project

• This operation only removes the file from the project. It does not actually delete the file.

• Note that when using [Project | Remove files from project...], multiple files can be selected from the [Remove File from Project] dialogue window by shift-clicking and/or control-clicking; all the selected files will be removed from the project.

Related Items

Remove files from project...


Changing project settings

Various settings of the project can be examined and changed by selecting [Project | Project Settings] from the menu, or by right-clicking the project name in the Project Manager area and selecting [Project Settings].

menu Project Project Settings

Right-click menu Project Settings

The project settings window is displayed as below. After changing the settings, press [OK] to complete the setting, or [Cancel] to return to the previous value.

Project Settings dialogue

Project settings are divided into the following five tabs.

Basic Settings
Controls basic settings such as the project name and output file name.
Directories
Specifies directories to search for INCLUDE files, libraries, etc.
Link
Controls the method of linking and link options.
Fortran Compiler
Specifies Fortran compiler options.
C/C++ Compiler
Specifies C/C++ compiler options.

The settings can be applied as the default for future new projects by checking the “Set as default” box before clicking [OK].

Clicking [Factory default] will change the settings to the Factory default ones without exiting the Project Settings dialogue.

Related Items

Project Settings
Project Settings: Basic Settings
Project Settings: C/C++ Compiler
Project Settings: Directories
Project Settings: Fortran Compiler
Project Settings: Link


Rebuilding the whole project

To rebuild the whole project, for example after making corrections or changing compiler options, select [Project | Rebuild] from the menu, press F10, or click the Rebuild icon on the toolbar.

menu Project Rebuild

This will recompile all source files belonging to the project, whether they have been updated or not.

It is not necessary to use Rebuild to recompile changed source files; Build is sufficient for that.

Related Items

Building the whole project
Compiling the currently being-edited file
Cleaning the whole project
Checking the details of build messages
Build
Clean
Clean All
Compile
Rebuild


Building the whole project

To build the project select [Project | Build] from the menu, or click the Build icon on the toolbar.

menu Project Build

Only the files which need to be recompiled will be compiled by this operation; those files are:

  • files updated since the last Build,
  • files not built since the last Clean,
  • files never built.

    To recompile all source files regardless of whether they have been updated, use Rebuild instead.

    Related Items

    Rebuilding the whole project
    Compiling the currently being-edited file
    Cleaning the whole project
    Checking the details of build messages
    Build
    Clean
    Clean All
    Compile
    Rebuild


Compiling the currently being-edited file

To compile the file that is currently being edited, select [Project | Compile] from the menu or click the menu Project Compile icon on the toolbar.

menu Project Compile

This operation only compiles the source file, it does not link the results. Note that it will compile the current file whether or not it is part of the current project. If the current file is not a C, C++ or Fortran source file, this command is disabled.

Related Items

Rebuilding the whole project
Building the whole project
Cleaning the whole project
Checking the details of build messages
Build
Clean
Clean All
Compile
Rebuild


Cleaning the whole project

Just cleaning the project's files

All intermediate and result files of the current project will be deleted. The next Build operation will build all of these files. (Cleaning the project then Building is the same as Rebuilding.)

menu Project Clean

This operation is performed by selecting [Project | Clean] from the menu.

This operation will delete the project's .mod files, .o files and any .exe file (for application projects), .dll file (for DLL projects) or .a file (for static library projects).

Cleaning all files in the project folder

All intermediate and result files in the project folder, even those that do not belong to the project, can be deleted.

menu Project Clean All

This operation is performed by selecting [Project | Clean All] from the menu.

This operation will delete all .a, .bak, .dll, .exe, .fif, .mod and .o files in the project folder. This can be useful to clean up after (for example) renaming or deleting source files from the project, however it should not be used if there any library or object files (without matching source files) that are needed. Because of the possibility of a loss of data, a confirmation dialogue is displayed.

dialogue Really remove?

Related Items

Rebuilding the whole project
Building the whole project
Compiling the currently being-edited file
Checking the details of build messages
Build
Clean
Clean All
Compile
Rebuild


Checking the details of build messages

The compilation, build, rebuild and clean messages are displayed in the message area below the editor window. Neither the compiler nor the compiler options being used are displayed; to see this detailed information, select [View | Detailed Build Message].

menu View Detailed Build Messages

This will show the detailed commands and results from the last Compile, Build, Rebuild or Clean operation in this session.

For example, with the message below

contents of compile message display

being displayed, the details are

details

This provides more information for the expert user.

Related Items

Rebuilding the whole project
Building the whole project
Compiling the currently being-edited file
Cleaning the whole project
Build
Clean
Clean All
Compile
Compile Messages
Detailed Build Messages
Rebuild


Jumping to the error line

When the Compile, Build or Rebuild are finished, the error and warning messages are displayed in the Message Window. The first error message is selected in the Messages pane, and the corresponding line in the source file is highlighted in the Editor pane, as shown below.

Program has errors...

To move to the location of a different error or warning message, double-click the message in the Messages page. For example, in this case double-clicking the “Questionable” message will move the cursor to the beginning of line 6 in the Editor pane and highlight that line.

Related Items

Build Messages


Command prompt in the project folder

The command prompt window can be opened with the working directory set to the current project's folder. This command prompt can be used to build, run, or debug the program directly.

This operation is performed by selecting [View | Command Prompt].

menu View Command Prompt

As the following example shows, the created command prompt window has its working directory set to the current project folder.

Related Items

Command Prompt


Opening the project folder in Windows Explorer

A Windows Explorer window can be displayed for the current project folder. It is possible to use this for deleting, moving, renaming files, etc.

This operation is performed by selecting [View | Project Folder] from the menu.

menu View Project Folder

The example below shows the result of viewing a project folder.

Related Items

Project Folder Display


Displaying help on keywords in source files

When editing a Fortran source file, help concerning the language keywords can be displayed. This is done by putting the cursor on the keyword in question and then pressing the F1 key; a help window will be opened for that keyword. In the following example, the cursor is placed on the WRITE keyword (in the Editor pane).

example program fragment

The following help window is displayed when F1 is pressed.

As well as an explanation of the keyword, most help screens also link to an example program.

Related Items

Displaying help information about a keyword


Inserting and deleting breakpoints

A breakpoint is a place in the program where execution stops temporarily when debugging. To set (or delete) a breakpoint, place the editing cursor on the desired breakpoint line and then select [Run | Break point].

menu Run Break point

It is also possible to set a breakpoint by left-clicking the mouse in the grey column immediately to the right of the line number. When a breakpoint is set for a line, a red disc is displayed in the column between the line number and the source text.

Break point set

To delete a breakpoint the same procedure is followed as for setting it. For example, when [Run | Break point] is selected when the editor cursor is on a line that already has a breakpoint set, the breakpoint will be removed.

A breakpoint can also be inserted or deleted for the current line in the editor by right-clicking and selecting [Break point] from the context menu.

Related Items

Break point
Setting a breakpoint


Moving to the next (previous) breakpoint

The cursor can be moved from its current position to the next breakpoint in the file. Select [Run | Next Break point] to do this.

Right-click menu Next Break point

To move to the previous breakpoint instead, select [Run | Previous Break point].

Related Items

Next Break point
Previous Break point


Starting to debug

To start a debug execution, select [Run | Debug Execute] from the menu, press F5, or click the Debug Execute icon on the toolbar.

menu Run Debug Execute

When a debug execution is started, program execution will begin and continue until it reaches a breakpoint. At the breakpoint, execution will temporarily stop. If no breakpoint has been set, the program will be completely executed.

Related Items

Debug execution
Debug Execute


Stopping debugging

Debugging will stop when the program has finished execution. To force termination of the program, select [Run | Terminate execution] from the menu, or click the Stop icon on the toolbar.

menu Run Stop program

Related Items

Terminate execution


Performing Step, Trace and Run to Cursor Operations

While debugging, it is possible to perform single line execution (Step and Trace) and to continue execution until a specific line. These operations can be done by menu selection, toolbar icon and shortcut keys.

The Step operation is performed by selecting [Run | Step] from the menu, pressing the F8 key or clicking the Step icon on the toolbar. The Step operation executes the whole source line including any procedure references.

The Trace operation is performed by selecting [Run | Trace] from the menu, pressing the F7 key or clicking the Trace icon on the toolbar. The Trace operation will execute the source line, stopping at the first line of the first procedure referenced in that line. (If no procedure is referenced by the source line, the whole line is executed.)

The Run to Cursor operation is performed by selecting [Run | Run to Cursor] from the menu, pressing the F4 key or clicking the Run to cursor icon on the toolbar. This operation will continue execution until it reaches the source line containing the cursor, or another breakpoint is reached.

Related Items

Run to Cursor
Step
Trace
Variable contents display and single-step execution


Displaying the value of a variable while debugging

While debugging, the value of a variable can be displayed. To do this select [Run | Watch Variable] from the menu, or press the F9 key. As shown in the following screen, type the name of the variable and press [OK].

Watching Variable Name dialogue

The value of the variable is displayed as follows.

Watching variable kv2

When the variable is an array, its value is displayed as follows.

Watching variable iarray

Related Items

Changing the value of a variable while debugging
Watch Variable


Changing the value of a variable while debugging

While debugging, the value of a variable can be changed. Firstly, the value of the variable must be displayed. To do this, select [Run | Watch Variable] from the menu or press the F9 key. As shown below, type the name of the variable and press [OK].

Watching Variable Name dialogue

The value of the variable will be displayed as follows.

Watching variable kv2

Next, click the displayed line containing the value of the variable; this highlights the line and displays an icon to the right to change the value: click this icon.

Selecting the value to change

As shown below, type the new value for the variable and press [OK] to perform the change.

Changing the value

Related Items

Variable Watching
Displaying the value of a variable while debugging


Running the program

To execute the program select [Run | Execute] from the menu, press the F6 key, or click the Run icon on the toolbar.

menu Run Execute

In the case of the program needing to be built before execution, it will automatically be built and then executed. However, if any errors are found when building the program will not be executed.

Related Items

Debug Execute
Execute


Specifying execution arguments

The command-line arguments passed to the executable program and the redirection of the standard input and output files can be specified.

To specify the execution arguments, select [Run | Command Line] from the menu.

menu Run Command Line

A dialogue window like the one below will be displayed for specifying the command line. In the one below, there are three arguments (arg1, arg2 and arg3) to be passed to the program.

Redirection is specified using “<” to redirect standard input, and “>” to redirect standard output. In the example below, input will be read from the file “data.txt”.

Note that the command line, or individual command line arguments, can be accessed in Fortran with the intrinsic subroutines GET_COMMAND and GET_COMMAND_ARGUMENT. The number of command line arguments is returned by the intrinsic function COMMAND_ARGUMENT_COUNT. Input/output redirection is performed by the Fortran Builder and is not a command line argument for the user program.

Related Items

Command Line


Converting old fixed-form Fortran files to free format

Old fixed-form Fortran source files (e.g. ones that were originally Fortran 77 or even Fortran 66) can be converted to modern free-form source files.

To convert a file first open it in the Fortran Builder editor.

Now select [Tool | Polish Fortran Source] from the menu.

menu Tool Polish Fortran Source

This command “polishes” the current Editor file (this operation is also referred to as reformatting or pretty-printing), in the process converting it to free-form source. This will produce a new file with the same name but with the extension changed to ‘.f90’. If the old file is part of the current project it will automatically be removed from the project, and the new file added in its place. The old file itself is unchanged.

To control how the conversion and polishing are done, select [Tool | Polish Settings].

menu Tool Polish Settings

Polish Settings dialogue

Any changes to these settings will affect all future polishing, both converting an old fixed-form file and polishing an existing free-form file.

Related Items

Polish Fortran Source
Polish Settings


Creating a static library

To create a static library with the Fortran Builder the Static Library project is used. Firstly, select [File | New | Project] from the menu.

menu File New Project

As shown below, select the Static Library project, type the project name, and press [Next>>].

Create Project dialogue

When the following confirmation screen is displayed,
Create Project confirmation
press [OK] to create the project.

This completes creation of the project. The subroutines and functions are added to the project afterwards. Following that, [Project | Build] will compile the added files and create the library (.a) file.

Related Items

New Project
New Static Library
Open Project
Project Settings


Reformatting Fortran source code

The readability of a Fortran source file can often be improved by reformatting it; we call this polishing the source file. To polish the file currently open in the Editor pane (the active file), select [Tool | Polish Fortran Source] from the menu.

menu Tool Polish Fortran Source

The file will be immediately polished and replaced by the new version. It can be reverted to its previous state using the [Edit | Undo] command.

To control how the conversion and polishing are done, select [Tool | Polish Settings].

menu Tool Polish Settings

Polish Settings dialogue

Any changes to these settings will affect all future polishing, both converting an old fixed-form file and polishing an existing free-form file.

Related Items

Polish Fortran Source
Polish Settings


Creating a call graph for Fortran source files

The source files for a Fortran program can be analysed, and the call graph produced. The call graph shows which procedures are called by each procedure in the source files.

The call graph is produced by selecting [Tool | Call Graph] from the menu.

menu Tool Call Graph

As shown below, a dialogue window is displayed listing the source files in the current project. Check the box of each file for which a call graph is desired, and press [OK].

Call Graph dialogue

The call graph is written to the file ‘callgraph.txt’ in the project folder, and on completion is automatically opened in the Fortran Builder.

NOTES:

  1. The output has three sections, each with its own heading: the main Call Graph, followed by the Index, and finally the Called-by Table which lists the callers of each individual subprogram.
  2. Procedure renaming on USE statements and calling of ENTRY points are both illustrated by line 4; this indicates that subroutine SUB called procedure R which was a renaming of procedure E, and that procedure E is actually an entry point in subprogram S.

Related Items

Call Graph


Restoring Fortran Builder context on restart

It is possible in the Fortran Builder to have the project and file that were open when it was shut down to be opened when it is restarted. To to this, select [Tool | Editor Settings] from the menu.

menu Tool Editor Settings

When the [Editor Settings] dialogue window is displayed, select the [Options] tab and check the box marked “Persistent state”.

Editor Settings dialogue

Conversely, if you want the Fortran Builder to always start up with no project open, uncheck “Persistent state”.

Related Items

Editor Settings


Preventing display of the console window

To prevent the display of the console window in a console application, select [Project | Project Settings...] from the menu.

menu Project Project Settings...

When the [Project Settings] dialogue window is displayed, select the [Link] tab and within that, the [Options] tab. Check the box marked “No console window”, and click [OK] to change the settings. This will prevent display of the console window.

Project Settings Link Options

Related Items

Project Settings: Link


Disabling pause on exit

Preventing display of “Press ENTER to continue--” on program termination

To prevent the program pausing with the display “Press ENTER to continue--” in the console window on program termination, select [Run | Pause on exit] from the menu.

menu Run Pause on exit

This will uncheck the previously-checked “Pause on exit” box. To reactivate the pause-on-exit feature, selecting [Run | Pause on exit] will re-check an unchecked box.

Note that the pause-on-exit status is separate for Debug vs. Release mode, and is stored as part of the project settings.

Related Items

Pause on Exit


Redistribution of 32-bit applications

An application that was built with the Fortran Builder can be executed on other machines. The options used in the build must be checked, and if necessary one or more of the DLL files listed below should be distributed with the executable.

Furthermore, if in the [Project Settings | Link | Options] tab the box marked “Link with static nagfor runtime library (−unsharedrts).” is not checked, one of the NAG Fortran runtime DLLs must be included as follows (the options are found on the referenced sub-tab of the Fortran Compiler tab of Project Settings).

  • libf71rts.dll
    Normal (no special options used).
  • libf71rtsgc.dll
    “Automatic garbage collection at runtime (−gc).” – [Detail (1)].
  • libf71rtssafe.dll
    “Enable OpenMP (-openmp)” – [Basic Settings], also
    “Safe execution in a multi-threaded environment (−thread_safe)” – [Detail (2)].
  • libf71rtstpc.dll
    any “Memory Trace Options (-mtrace=)” other than No – [Runtime Check].

All the above DLLs are found in the bin subdirectory of the Fortran Builder installation directory (usually C:\Program Files\NAG\EFBuilder 6.1 on 32-bit Windows and C:\Program Files (x86)\NAG\EFBuilder 6.1 on 64-bit Windows).

Note: When using both memory tracing (-mtrace= except none) and OpenMP or multi-threading (-openmp or -thread_safe), the DLL used is libf71rtssafe.dll.

For NAG Fortran Library applications, please contact NAG Inc. (in North America), Nihon NAG KK (in Japan), or NAG Ltd. (the rest of the world) as follows.

  • The Numerical Algorithms Group, Ltd.
    30 St Giles'
    OXFORD OX1 3LE
    United Kingdom
    email: sales@nag.co.uk
    Tel: +44 (0)1865 511245
  • The Numerical Algorithms Group, Inc.
    801 Warrenville Road, Suite 185
    Lisle, IL 60532-4332
    USA
    email: sales@nag.com
    Tel: +1 630 971 2337
    Fax: +1 630 971 2706
  • Nihon Numerical Algorithms Group KK Hatchobori Frontier Building 2F
    4-9-9 Hatchobori
    Chuo-Ku
    Tokyo 104-0032
    Japan
    email: sales@nag-j.co.jp
    Tel: +81 3 5542 6311
    Fax: +81 3 5542 6312

A 32-bit application that uses the LAPACK library has no special requirements because the 32-bit LAPACK library is static.

An OpenGL application will need the following DLL.

  • glut32.dll

This DLL can be found in the bin subdirectory.

A GTK+ application needs many DLLs. We recommend downloading the GTK+ library installer gtk-dev-2.10.11-win32-1.exe from here (this is located on the Nihon NAG web site). Note that GTK+ has been revised since the Fortran Builder was produced, so this installer is not easily available from the GTK+ web site, and newer DLLs are not guaranteed to be compatible.

Related Items

Redistribution of 64-bit applications


Redistribution of 64-bit applications

An application that was built with the Fortran Builder can be executed on other machines. The options used in the build must be checked, and if necessary one or more of the DLL files listed below should be distributed with the executable.

Furthermore, if in the [Project Settings | Link | Options] tab the box marked “Link with static nagfor runtime library (−unsharedrts).” is not checked, one of the NAG Fortran runtime DLLs must be included as follows (the options are found on the referenced sub-tab of the Fortran Compiler tab of Project Settings).

  • lib64f71rts.dll
    Normal (no special options used).
  • lib64f71rtssafe.dll
    “Enable OpenMP (-openmp)” – [Basic Settings], also
    “Safe execution in a multi-threaded environment (−thread_safe)” – [Detail (2)].
  • lib64f71rtstpc.dll
    any “Memory Trace Options (-mtrace=)” other than No – [Runtime Check].

All the above DLLs are found in the bin subdirectory of the Fortran Builder installation folder (usually C:\Program Files (x86)\NAG\EFBuilder 6.1).

Note: When using both memory tracing (-mtrace= except none) and OpenMP or multi-threading (-openmp or -thread_safe), the DLL used is lib64f71rtssafe.dll.

For NAG Fortran Library applications, please contact NAG Inc. (in North America), Nihon NAG KK (in Japan), or NAG Ltd. (the rest of the world) as follows.

  • The Numerical Algorithms Group, Ltd.
    30 St Giles'
    OXFORD OX1 3LE
    United Kingdom
    email: sales@nag.co.uk
    Tel: +44 (0)1865 511245
  • The Numerical Algorithms Group, Inc.
    801 Warrenville Road, Suite 185
    Lisle, IL 60532-4332
    USA
    email: sales@nag.com
    Tel: +1 630 971 2337
    Fax: +1 630 971 2706
  • Nihon Numerical Algorithms Group KK Hatchobori Frontier Building 2F
    4-9-9 Hatchobori
    Chuo-Ku
    Tokyo 104-0032
    Japan
    email: sales@nag-j.co.jp
    Tel: +81 3 5542 6311
    Fax: +81 3 5542 6312

A 64-bit application that uses the LAPACK library has no special requirements because the included LAPACK library is static. Note:This is LAPACK version 3.6.0.

A 64-bit application that uses OpenGL has no special requirements because the 64-bit OpenGL library is static.

A GTK+ application needs many DLLs, all of which are found in the bin64 subdirectory. Please copy the entire contents of the bin64 subdirectory.

Note: These DLLs are from GTK+ for Windows (64-bit), version 2.22.1.

A mixed-language 64-bit application that uses C++ needs the following DLLs.

  • libstdc++-6.dll
  • libgcc_s_sjlj-1.dll

These DLLs can be found in the nagfor\lib\MinGW64\bin subdirectory.

Related Items

Redistribution of 32-bit applications


Fortran Language Guide

Fortran Language Guide cover page

Introduction

Fortran: A few historical details

Keyword List


Introduction

This Fortran Language Guide is originally based on the writing of Dr. Norio Takeuchi*1, with much additional material by Malcolm Cohen*2.

*1. Dr. Norio TAKEUCHI
Professor, Faculty of Engineering, Hosei University, Japan.
Director, Research Center for Computing and Multimedia Studies, Hosei University, Japan.

*2. Malcolm Cohen
Project Editor, Fortran Standard (ISO/IEC 1539-1).
Tokyo, Japan.


Fortran: A few historical details

Ancient History

In 1954 computing history was made when an IBM team lead by John Backus produced Fortran, the first high-level programming language. Because its competition was with assembly languages, efficiency was a primary concern and so the first compiler was an optimising compiler. This focus on efficiency has continued throughout Fortran's history.

In 1958 the first major revision of the language by IBM, Fortran II, introduced the concept of subroutines. Development of the language continued, not just by IBM but also by many other manufacturers, resulting in conflicting implementations on different systems. Some of the non-IBM versions became very popular, for example WATFOR and WATFIV.

In 1962 the differences between the different versions lead to growing pressure for standardisation of the language. Vendors would not give up the right to make extensions, but users who wrote to the standard could expect their code to have a good chance of compiling and even running successfully on different systems. In 1966 this resulted in the publication by ANSI (the American National Standards Institute) of the first programming language standard, now known as Fortran 66.

Fortran 66 remained the standard Fortran over a decade before dissatisfaction with some of the limitations of the language lead to the publication, again by ANSI, of a revised standard in 1978. This was known as Fortran 77, because the technical content was agreed in 1977 even though the publication was a year later. Notable new features of Fortran 77 were the CHARACTER data type and the block IF (IF – THEN – ELSE – ENDIF). Fortran 77 was not a superset of Fortran 66, having numerous (mostly minor) incompatibilities. For example, the “extended-range DO loop” was completely deleted from the standard.

In 1980 the ANSI Fortran 77 standard was published by ISO as an International Standard, without change.

Recent History: Fortran Language Standards

After many false starts (Fortran 82, Fortran 8x, Fortran 88) and much controversy, a greatly revised Fortran standard was published by ISO in 1991. This was known as Fortran 90; again, because the technical content was fully decided in 1990. It was a proper superset of Fortran 77 – all of the Fortran 77 language was included in the Fortran 90 standard. At this point NAG entered the compiler scene, releasing a compiler for the new language immediately after publication of the new standard. Other compiler vendors followed over the following two years.

It was widely agreed that the long gap between the Fortran 77 and 90 revisions had been detrimental to the language. Furthermore, as Fortran 90 was such a major revision a number of mistakes were found in the first couple of years after publication. Therefore, it was decided to produce a minor revision of the language in 1995. Initially, it was suggested that this minor revision should have no additions at all, only corrections, but activities elsewhere in the Fortran community (in particular, the High Performance Fortran activity) convinced the committee that a small number of extensions would be helpful.

This resulted in the publication of the Fortran 95 standard; due to delays in the standardisation process however, publication did not take place until December 1997. Notable new features were elemental procedures, the FORALL construct (only useful on massively parallel machines) and default initialisation for user-defined types.

Unlike Fortran 90, Fortran 95 was not a superset; it deleted a small number of so-called obsolescent features. This incompatibility is more theoretical than real however, as all existing Fortran 95 compilers include the deleted features as extensions.

The Fortran 2003 standard

Even before Fortran 95 was finished, work was underway on discovering user requirements for a more major revision of the standard. Originally this was to have been Fortran 2000, but the perhaps inevitable delays in deciding its content meant that the schedule slipped and so it became Fortran 2003.

The Fortran 2003 standard was published at the end of 2004.

Notable new features include C interoperability and object orientation. Most Fortran vendors are still working at integrating Fortran 2003 features into their compilers; due to the size and number of new features, few vendors even now have included all of Fortran 2003, and many have started including some of the features of the later Fortran 2008 standard before finishing off the more difficult Fortran 2003 features.

The Fortran 2008 standard

Continuing the pace of development in the Fortran standard, a new revision was agreed in 2008 and published in December 2010. This includes a large number of new features, but is a smaller increment than Fortran 2003. Among the new features are distributed-memory parallel programming with coarrays, the BLOCK construct that allows local declarations within executable code, and a large number of new intrinsic functions.

Malcolm Cohen, Tokyo, October 2004, revised December 2011.


Fortran Language Keywords

Colour scheme

When different parts of the descriptions apply to different editions of the Fortran standard, different colours are used as follows.

Green : Fortran 2003 feature

Purple : Fortran 2008 feature

Pink : Fortran 2018 feature

Light Orange : Obsolescent (but still standard) feature

Orange : Deleted (previously standard) feature

Dark red : Non-standard feature

Note: These colours are not used when the entire page is for the same edition of the Fortran standard.. For example, the “CLASS specifier” page is monochrome since the entire contents are applicable to Fortran 2003 onwards only (and with no changes in later standards).

Keywords

  • ABS intrinsic function
  • ACHAR intrinsic function
  • ACOS intrinsic function
  • ACOSH intrinsic function
  • ADJUSTL intrinsic function
  • ADJUSTR intrinsic function
  • ADVANCE= specifier
  • AIMAG intrinsic function
  • AINT intrinsic function
  • ALL intrinsic function
  • ALLOCATABLE attribute
  • ALLOCATE statement
  • ALLOCATED intrinsic function
  • .AND. operator
  • ANINT intrinsic function
  • ANY intrinsic function
  • ASIN intrinsic function
  • ASINH intrinsic function
  • Array Assignment
  • Array Constructor
  • Array Section
  • Array-array operations
  • Array-scalar operations
  • ASSIGN statement
  • ASSOCIATE construct
  • ASSOCIATED intrinsic function
  • ASYNCHRONOUS attribute
  • ASYNCHRONOUS= specifier
  • ATAN intrinsic function
  • ATAN2 intrinsic function
  • ATANH intrinsic function
  • ATOMIC_ADD intrinsic subroutine
  • ATOMIC_AND intrinsic subroutine
  • ATOMIC_DEFINE intrinsic subroutine
  • ATOMIC_FETCH_ADD intrinsic subroutine
  • ATOMIC_FETCH_AND intrinsic subroutine
  • ATOMIC_FETCH_OR intrinsic subroutine
  • ATOMIC_FETCH_XOR intrinsic subroutine
  • ATOMIC_OR intrinsic subroutine
  • ATOMIC_REF intrinsic subroutine
  • ATOMIC_XOR intrinsic subroutine
  • Attributes
  • BACKSPACE statement
  • BESSEL_J0 intrinsic function
  • BESSEL_J1 intrinsic function
  • BESSEL_JN intrinsic function
  • BESSEL_Y0 intrinsic function
  • BESSEL_Y1 intrinsic function
  • BESSEL_YN intrinsic function
  • BGE intrinsic function
  • BGT intrinsic function
  • BIND attribute
  • BIT_SIZE intrinsic function
  • BLE intrinsic function
  • BLOCK construct
  • BLOCK DATA subprogram
  • BLT intrinsic function
  • BTEST intrinsic function
  • CALL statement
  • CASE statement
  • CASE DEFAULT statement
  • CEILING intrinsic function
  • CHANGE TEAM statement
  • CHAR intrinsic function
  • CHARACTER type
  • CLASS specifier
  • CLASS DEFAULT statement
  • CLASS IS statement
  • CLOSE statement
  • CMPLX intrinsic function
  • CODIMENSION attribute
  • COMMAND_ARGUMENT_COUNT intrinsic function
  • COMMON statement
  • ISO_FORTRAN_ENV function COMPILER_OPTIONS
  • ISO_FORTRAN_ENV function COMPILER_VERSION
  • COMPLEX type
  • Component Definition statement
  • Concatenation (//) operator
  • CONJG intrinsic function
  • CONTAINS statement
  • CONTIGUOUS attribute
  • CONTINUE statement
  • CONVERT= specifier
  • COS intrinsic function
  • COSH intrinsic function
  • COUNT intrinsic function
  • CPU_TIME intrinsic subroutine
  • CRITICAL construct
  • CSHIFT intrinsic function
  • CYCLE statement
  • DATA statement
  • DATE_AND_TIME intrinsic subroutine
  • DBLE intrinsic function
  • DEALLOCATE statement
  • DECIMAL= specifier
  • Derived Type Definition
  • DIGITS intrinsic function
  • DIM intrinsic function
  • DIMENSION attribute
  • DO construct
  • DO CONCURRENT construct
  • DO WHILE statement
  • DOT_PRODUCT intrinsic function
  • DOUBLE COMPLEX type
  • DOUBLE PRECISION type
  • DPROD intrinsic function
  • DSHIFTL intrinsic function
  • DSHIFTR intrinsic function
  • ELEMENTAL attribute
  • ELSE statement
  • ELSE IF statement
  • ELSEWHERE statement
  • ENCODING= specifier
  • END statement
  • END ASSOCIATE statement
  • END BLOCK statement
  • END CRITICAL statement
  • END DO statement
  • END ENUM statement
  • END FUNCTION statement
  • END IF statement
  • END INTERFACE statement
  • END MODULE statement
  • END PROGRAM statement
  • END SELECT statement
  • END SUBMODULE statement
  • END SUBROUTINE statement
  • END TEAM statement
  • END TYPE statement
  • END WHERE statement
  • END= specifier
  • ENDFILE statement
  • Entity Declaration List
  • ENTRY statement
  • ENUM statement
  • ENUMERATOR statement
  • EOR= specifier
  • EOSHIFT intrinsic function
  • EPSILON intrinsic function
  • .EQ. (==) operator
  • EQUIVALENCE statement
  • .EQV. operator
  • ERF intrinsic function
  • ERFC intrinsic function
  • ERFC_SCALED intrinsic function
  • ERR= specifier
  • ERRMSG= specifier
  • ERROR STOP statement
  • EVENT POST statement
  • EVENT WAIT statement
  • EVENT_TYPE from ISO_FORTRAN_ENV
  • EXECUTE_COMMAND_LINE intrinsic subroutine
  • EXIT statement
  • EXP intrinsic function
  • EXPONENT intrinsic function
  • EXTENDS clause
  • EXTENDS_TYPE_OF intrinsic function
  • EXTERNAL attribute
  • FAIL IMAGE statement
  • FAILED_IMAGES intrinsic function
  • FINAL statement
  • FINDLOC intrinsic function
  • FLOOR intrinsic function
  • FORALL construct
  • FORALL statement
  • FORM TEAM statement
  • FORMAT statement
  • FRACTION intrinsic function
  • FUNCTION statement
  • GAMMA intrinsic function
  • .GE. (>=) operator
  • GENERIC statement
  • GET_COMMAND intrinsic subroutine
  • GET_COMMAND_ARGUMENT intrinsic subroutine
  • GET_ENVIRONMENT_VARIABLE intrinsic subroutine
  • GET_TEAM intrinsic function
  • GO TO statement
  • .GT. (>) operator
  • HUGE intrinsic function
  • HYPOT intrinsic function
  • IACHAR intrinsic function
  • IALL intrinsic function
  • IAND intrinsic function
  • IANY intrinsic function
  • IBCLR intrinsic function
  • IBITS intrinsic function
  • IBSET intrinsic function
  • ICHAR intrinsic function
  • ID= specifier
  • IEOR intrinsic function
  • IF construct
  • IF statement
  • IF THEN statement
  • Image control statements
  • Image selectors
  • IMAGE_STATUS intrinsic function
  • IMPLICIT statement
  • IMPLICIT NONE statement
  • IMPORT statement
  • IMPURE attribute
  • INCLUDE line
  • INDEX intrinsic function
  • INQUIRE statement
  • INT intrinsic function
  • INTEGER type
  • INTENT attribute
  • INTERFACE statement
  • INTERFACE ASSIGNMENT statement
  • INTERFACE OPERATOR statement
  • INTRINSIC attribute
  • IOMSG= specifier
  • IOR intrinsic function
  • IOSTAT= specifier
  • IPARITY intrinsic function
  • IS_CONTIGUOUS intrinsic function
  • IS_IOSTAT_END intrinsic function
  • IS_IOSTAT_EOR intrinsic function
  • ISHFT intrinsic function
  • ISHFTC intrinsic function
  • KIND intrinsic function
  • LBOUND intrinsic function
  • LCOBOUND intrinsic function
  • .LE. (<=) operator
  • LEADZ intrinsic function
  • LEN intrinsic function
  • LEN_TRIM intrinsic function
  • LGE intrinsic function
  • LGT intrinsic function
  • LLE intrinsic function
  • LLT intrinsic function
  • LOCK statement
  • LOCK_TYPE from ISO_FORTRAN_ENV
  • LOG intrinsic function
  • LOG_GAMMA intrinsic function
  • LOG10 intrinsic function
  • LOGICAL intrinsic function
  • LOGICAL type
  • .LT. (<) operator
  • MASKL intrinsic function
  • MASKR intrinsic function
  • MATMUL intrinsic function
  • MAXEXPONENT intrinsic function
  • MAXLOC intrinsic function
  • MAXVAL intrinsic function
  • MERGE intrinsic function
  • MERGE_BITS intrinsic function
  • MINEXPONENT intrinsic function
  • MINLOC intrinsic function
  • MINVAL intrinsic function
  • MOD intrinsic function
  • MODULE statement
  • MODULE PROCEDURE statement
  • MODULO intrinsic function
  • MOLD= specifier
  • MOVE_ALLOC intrinsic subroutine
  • MVBITS intrinsic subroutine
  • NAMELIST statement
  • .NE. (/=) operator
  • NEAREST intrinsic function
  • .NEQV. operator
  • NEW_LINE intrinsic function
  • NEWUNIT= specifier
  • NINT intrinsic function
  • NML= specifier
  • NON_RECURSIVE attribute
  • NOPASS attribute
  • NORM2 intrinsic function
  • .NOT. operator
  • NOT intrinsic function
  • NULL intrinsic function
  • NULLIFY statement
  • NUM_IMAGES intrinsic function
  • Numeric operators
  • Object-bound procedures
  • ONLY clause
  • OPEN statement
  • Operator precedence
  • OPTIONAL attribute
  • .OR. operator
  • PACK intrinsic function
  • PARAMETER attribute
  • PARITY intrinsic function
  • PASS attribute
  • PAUSE statement
  • PENDING= specifier
  • Pointer assignment statement (=>)
  • POINTER attribute
  • POPCNT intrinsic function
  • POPPAR intrinsic function
  • PRECISION intrinsic function
  • PRESENT intrinsic function
  • PRINT statement
  • PRIVATE attribute
  • PROCEDURE statements
  • PRODUCT intrinsic function
  • PROGRAM statement
  • PROTECTED attribute
  • PUBLIC attribute
  • PURE attribute
  • RADIX intrinsic function
  • RANDOM_NUMBER intrinsic subroutine
  • RANDOM_SEED intrinsic subroutine
  • RANGE intrinsic function
  • RANK statement
  • RANK DEFAULT statement
  • READ statement
  • REAL intrinsic function
  • REAL type
  • RECURSIVE attribute
  • REDUCE intrinsic function
  • Reduction intrinsic functions
  • REPEAT intrinsic function
  • RESHAPE intrinsic function
  • RESULT clause
  • RETURN statement
  • REWIND statement
  • ROUND= specifier
  • RRSPACING intrinsic function
  • SAME_TYPE_AS intrinsic function
  • SAVE attribute
  • SCALE intrinsic function
  • SCAN intrinsic function
  • SELECT CASE construct
  • SELECT CASE statement
  • SELECT RANK construct
  • SELECT TYPE construct
  • SELECTED_CHAR_KIND intrinsic function
  • SELECTED_INT_KIND intrinsic function
  • SELECTED_REAL_KIND intrinsic function
  • Separate module procedures
  • SEQUENCE statement
  • SET_EXPONENT intrinsic function
  • SHAPE intrinsic function
  • SHIFTA intrinsic function
  • SHIFTL intrinsic function
  • SHIFTR intrinsic function
  • SIGN intrinsic function
  • SIGN= specifier
  • SIN intrinsic function
  • SINH intrinsic function
  • SIZE intrinsic function
  • SIZE= specifier
  • SOURCE= specifier
  • SPACING intrinsic function
  • SPREAD intrinsic function
  • SQRT intrinsic function
  • STAT= specifier
  • STOP statement
  • STOPPED_IMAGES intrinsic function
  • STORAGE_SIZE intrinsic function
  • SUBMODULE statement
  • SUBROUTINE statement
  • SUM intrinsic function
  • SYNC ALL statement
  • SYNC IMAGES statement
  • SYNC MEMORY statement
  • SYNC TEAM statement
  • SYSTEM_CLOCK intrinsic subroutine
  • TAN intrinsic function
  • TANH intrinsic function
  • TARGET attribute
  • THIS_IMAGE intrinsic function
  • TINY intrinsic function
  • TRAILZ intrinsic function
  • TRANSFER intrinsic function
  • TRANSPOSE intrinsic function
  • TRIM intrinsic function
  • TYPE statement
  • Type-bound procedures
  • Type Declaration statement
  • TYPE IS statement
  • UBOUND intrinsic function
  • UCOBOUND intrinsic function
  • UNIT= specifier
  • UNLOCK statement
  • UNPACK intrinsic function
  • USE statement
  • VALUE attribute
  • VERIFY intrinsic function
  • VOLATILE attribute
  • WAIT statement
  • WHERE construct
  • WHERE statement
  • WRITE statement


ABS intrinsic function

Standard: F77 F90 F95 F2003 F2008 Example program

＜Syntax＞

ABS ( A )

A : Integer, Real or Complex;

Result : If A is Complex, the result is Real with the same kind as A; otherwise the result has the same type and kind as A.

＜Semantics＞

The value of the result is an approximation to the absolute value of A. Like many intrinsic functions, this is elemental; the result has the same shape as A, with the operation being applied elementwise.

If A is of type Complex, the result is mathematically equal to SQRT(REAL(A)**2+AIMAG(A)**2) but is computed without undue overflow or underflow.

＜Related＞

SQRT intrinsic function


ACHAR intrinsic function

Standard: F77 F90 F95 F2003 F2008 Example program

＜Syntax＞

ACHAR ( I [ , KIND ] )

I : Integer;
KIND : scalar Integer constant expression;

Result : Character(Len=1) or Character(Len=1,Kind=KIND).

＜Semantics＞

Convert ASCII character code (value from 0 to 127) to Character type; this is the inverse of the IACHAR intrinsic function. Like many intrinsic functions, this is elemental; the result has the same shape as I, with the operation being applied elementwise.

＜Related＞

CHAR intrinsic function, CHARACTER type, IACHAR intrinsic function, ICHAR intrinsic function


ACOS intrinsic function

Standard: F77 F90 F95 F2003 F2008 Example program

＜Syntax＞

ACOS ( X )

X : Real or Complex;

Result : Same type and kind as X.

＜Semantics＞

The value of the result is an approximation to the arc cosine of X, in radians. Like many intrinsic functions, this is elemental; the result has the same shape as X, with the operation being applied elementwise.

If X is of type Real, it must be in the range −1≤X≤+1, and the result will be in the range 0.0≤ACOS(X)≤π. If X is of type Complex, the real part of the result is in radians, in the range 0.0≤REAL(ACOS(X))≤π.

＜Related＞

ACOSH intrinsic function, COS intrinsic function


ACOSH intrinsic function

Standard: F77 F90 F95 F2003 F2008 Example program

＜Syntax＞

ACOSH ( X )

X : Real or Complex;

Result : Same type and kind as X.

＜Semantics＞

The value of the result is an approximation to the arc hyperbolic cosine of X. Like many intrinsic functions, this is elemental; the result has the same shape as X, with the operation being applied elementwise.

If X is of type Real, it must be greater than or equal to 1. If X is of type Complex, the imaginary part of the result is in radians, in the range 0.0≤AIMAG(ACOSH(X))≤π.

＜Related＞

ACOS intrinsic function, COSH intrinsic function


ADJUSTL intrinsic function

Standard: F77 F90 F95 F2003 F2008 Example program

＜Syntax＞

ADJUSTL ( STRING )

STRING : Character;

Result : Character with the same length and kind as STRING.

＜Semantics＞

The result is STRING with any leading blanks removed, and an equal number of blanks added to the end (as if it had been rotated). Like many intrinsic functions, this is elemental; the result has the same shape as STRING, with the operation being applied elementwise.

＜Related＞

ADJUSTR intrinsic function


ADJUSTR intrinsic function

Standard: F77 F90 F95 F2003 F2008 Example program

＜Syntax＞

ADJUSTR ( STRING )

STRING : Character;

Result : Character with the same length and kind as STRING.

＜Semantics＞

The result is STRING with any trailing blanks removed, and an equal number of blanks added to the beginning (as if it had been rotated). Like many intrinsic functions, this is elemental; the result has the same shape as STRING, with the operation being applied elementwise.

＜Related＞

ADJUSTL intrinsic function


ADVANCE= specifier

Standard: F77 F90 F95 F2003 F2008 Example program

＜Syntax＞

ADVANCE = expression

The ADVANCE= specifier may appear only as a ci-spec in a formatted READ or WRITE statement.

The expression must be a scalar character expression that evaluates to 'YES' or 'NO'. Case is not important (so 'no', 'No' and 'nO' are all treated as 'NO').

＜Semantics＞

Specifies whether a formatted input/output statement is advancing or nonadvancing. The default is advancing.

For a nonadvancing output statement, the record is not terminated at the end of the output statement and additional characters may be written by a subsequent output statement. For a nonadvancing input statement, the rest of the record is not skipped at the end of the input statement and may be read by a subsequent input statement.

Nonadvancing output may be used to write a “prompt” to the console, this will allow subsequent input on the same line.

＜Related＞

EOR= specifier, READ statement, SIZE= specifier, WRITE statement


AIMAG intrinsic function

Standard: F77 F90 F95 F2003 F2008 Example program

＜Syntax＞

AIMAG ( Z )

Z : Complex;

Result : Real with the same kind as Z.

＜Semantics＞

The value of the result is the imaginary part of the complex value Z. Like many intrinsic functions, this is elemental; the result has the same shape as Z, with the operation being applied elementwise.

＜Related＞

COMPLEX type


AINT intrinsic function

Standard: (F77) F90 F95 F2003 F2008 Example program

＜Syntax＞

AINT ( A [ , KIND ] )

A : Real;
KIND : scalar Integer constant expression;

Result : Real(Kind=Kind(A)) or Real(Kind=KIND).

＜Semantics＞

The value of the result is the nearest integer whose absolute value is less than or equal to that of A. Like many intrinsic functions, this is elemental; the result has the same shape as A, with the operation being applied elementwise.

＜Related＞

ANINT intrinsic function, CEILING intrinsic function, FLOOR intrinsic function, INT intrinsic function, NINT intrinsic function


ALL intrinsic function

Standard: F77 F90 F95 F2003 F2008 F2018 Example program

＜Syntax＞

ALL ( MASK )
ALL ( MASK, DIM )

MASK : rank N array of type Logical;
DIM : scalar Integer in the range 1 to N;

Result: Logical with the same kind as MASK. The result is scalar if there is no DIM or if MASK is one-dimensional, and an array with the shape of MASK with dimension DIM removed otherwise.

Prior to Fortran 2018, DIM was not permitted to be an optional dummy argument; in Fortran 2018, an optional DIM is merely required to be present.

＜Semantics＞

Reduces an array (either completely, or by collapsing one dimension) with the .AND. operation; the value is true if and only if all the values (in that dimension with DIM=) are true.

＜Related＞

.AND. operator, ANY intrinsic function, Array-scalar operations, Array-array operations, COUNT intrinsic function, IALL intrinsic function, IANY intrinsic function, IPARITY intrinsic function, MAXLOC intrinsic function, MAXVAL intrinsic function, MINLOC intrinsic function, MINVAL intrinsic function, PARITY intrinsic function, PRODUCT intrinsic function, Reduction intrinsic functions, SUM intrinsic function


ALLOCATABLE attribute

Standard: F77 F90 F95 F2003 F2008 Example program

＜Syntax＞

type , ALLOCATABLE [ , attr ]... :: decl-list

ALLOCATABLE [::] allocatable-list

allocatable-list ::= allocatable [ , allocatable ]...
allocatable ::= name [ ( deferred-shape ) ]

＜Semantics＞

Declares that a variable is allocatable. Such a variable is allocated dynamically with the ALLOCATE statement. An allocatable array must have deferred shape; that is, each dimension must be declared with a colon (‘:’); this may be done in the Type Declaration statement, the Component Definition statement, the ALLOCATABLE statement, or a separate DIMENSION statement. The values for the bounds are supplied in the ALLOCATE statement at runtime.

The initial state of an allocatable variable is unallocated. An allocatable variable is automatically deallocated on exit from the procedure it is declared in, unless it has the SAVE attribute.

Prior to Fortran 2003, all allocatable variables were required to be arrays, and were not permitted to be structure components.

If the left-hand-side of an intrinsic assignment statement is an allocatable variable, and it is either unallocated, or allocated with a different shape from the expression, or has a deferred character length and is allocated with a different length from the expression, it is reallocated to have the same shape and/or character length as the expression on the assignment. This automatic reallocation can be suppressed by using array section or substring notation.

In a structure constructor for a type with an allocatable component, the NULL intrinsic function can be used to denote an unallocated value.

In Fortran 2008, a structure constructor is not required to supply any value for an allocatable component; if the value is omitted, the component is unallocated.

＜Related＞

ALLOCATE statement, Component Definition statement, DEALLOCATE statement, DIMENSION attribute, LBOUND intrinsic function, MOVE_ALLOC intrinsic subroutine, NULL intrinsic function, SHAPE intrinsic function, SIZE intrinsic function, Type Declaration statement, UBOUND intrinsic function


ALLOCATE statement

Standard: F77 F90 F95 F2003 F2008 Example program

＜Syntax＞

ALLOCATE ( [ type-spec :: ] item-list [ , alloc-opt ]... )

item-list ::= item [ , item ]...
item ::= variable [ ( shape ) ]
shape ::= bounds [ , bounds ]...

alloc-opt | ::= | ERRMSG = variable
 | | | MOLD = expression
 | | | SOURCE = expression
 | | | STAT = variable

Each item must have the ALLOCATABLE or POINTER attribute. If an item is an array, it must be followed by a shape with the same number of bounds as the rank of the item,

The ERRMSG= variable must be a scalar character variable of default kind. The STAT= variable must be a scalar integer variable, and should be at least 16 bits in size.

SOURCE= and type-spec are mutually exclusive.

＜Semantics＞

Allocates memory for a list of pointers and allocatable variables. If an item is allocatable, it must not be currently allocated (or an error will occur).

The shape is required for each item that is an array, with the same number of bounds as the rank of the array, unless the MOLD= or SOURCE= clause appears with an array expression. If the lower bound expression is omitted, the lower bound will be 1.

If an error occurs, e.g. an allocatable item is already allocated or there is not enough memory available, the program will be terminated unless the STAT= clause is present. The STAT= variable is set to zero if all allocations succeed, or to an error code if one of them fails.

In Fortran 2003, there are several additions.

  • The ERRMSG=variable clause has been added; this sets a character string variable to an error message if an allocation fails. (This variable is unchanged if there is no error, so STAT= is still needed to prevent termination.)
  • The SOURCE=expression clause has been added; this sets the value (and type if polymorphic) of the item to that of the source expression. In this case, Fortran 2003 only permits a single item to be allocated at a time.
  • The item-list can be preceded by a type-spec; this sets the type of a polymorphic item.

In Fortran 2008, there are more additions.

  • The MOLD=expression has been added; this sets the type of a polymorphic allocation to be the same as the dynamic type of expression; the expression is permitted to be an undefined variable, since the value of the variable is not used. Any default initialisation for the type will be applied to the new object.

    If MOLD= appears, neither SOURCE= nor type-spec may appear.

  • If MOLD= or SOURCE= appears with an expression that is an array, the bounds can be omitted from the array variable. In this case, the allocated bounds will be the same as those of the expression.
  • More than one item is permitted to be allocated by an ALLOCATE statement with a SOURCE= clause.

＜Related＞

ALLOCATABLE attribute, ALLOCATED intrinsic function, ASSOCIATED intrinsic function, DEALLOCATE statement, ERRMSG= specifier, LBOUND intrinsic function, MOLD= specifier, MOVE_ALLOC intrinsic subroutine, POINTER attribute, SHAPE intrinsic function, SIZE intrinsic function, SOURCE= specifier, STAT= specifier, UBOUND intrinsic function


ALLOCATED intrinsic function

Standard: F77 F90 F95 F2003 F2008 Example program

＜Syntax＞

ALLOCATED ( ARRAY )
ALLOCATED ( SCALAR )

ARRAY : allocatable array of any type;
SCALAR : allocatable scalar of any type;

Result: Logical scalar, default kind.

＜Semantics＞

The result is .TRUE. if the argument is currently allocated, and .FALSE. if the argument is currently unallocated.

＜Related＞

ALLOCATABLE attribute, ALLOCATE statement, ASSOCIATED intrinsic function, DEALLOCATE statement, MOVE_ALLOC intrinsic subroutine, NULL intrinsic function


.AND. operator

Standard: F77 F90 F95 F2003 F2008 Example program

＜Syntax＞

expression .AND. expression

This operator has the highest precedence of the intrinsic binary logical operators; it is higher than that of .EQV., .NEQV., .OR., and user-defined binary operators, and lower than all other operators.

＜Semantics＞

Logical conjunction of two logical expressions. The kind of the result is the same as the kind of one of the expressions.

The result is .TRUE. if the expressions are both .TRUE., and .FALSE. otherwise.

＜Related＞

Concatenation (//) operator, .EQ. (==) operator, .EQV. operator, .LE. (<=) operator, .LT. (<) operator, .GE. (>=) operator, .GT. (>) operator, .NE. (/=) operator, .NEQV. operator, .NOT. operator, Numeric operators, Operator precedence, .OR. operator


ANINT intrinsic function

Standard: (F77) F90 F95 F2003 F2008 Example program

＜Syntax＞

ANINT ( A [ , KIND ] )

A : Real;
KIND : scalar Integer constant expression;

Result : Real(Kind=Kind(A)) or Real(Kind=KIND).

＜Semantics＞

The value of the result is the nearest integer to A; if two integers are equally near, the one with the larger absolute value is chosen. Like many intrinsic functions, this is elemental; the result has the same shape as A, with the operation being applied elementwise.

＜Related＞

AINT intrinsic function, CEILING intrinsic function, FLOOR intrinsic function, INT intrinsic function, NINT intrinsic function


ANY intrinsic function

Standard: F77 F90 F95 F2003 F2008 F2018 Example program

＜Syntax＞

ANY ( MASK )
ANY ( MASK, DIM )

MASK : rank N array of type Logical;
DIM : scalar Integer in the range 1 to N;

Result: Logical with the same kind as MASK. The result is scalar if there is no DIM or if MASK is one-dimensional, and an array with the shape of MASK with dimension DIM removed otherwise.

Prior to Fortran 2018, DIM was not permitted to be an optional dummy argument; in Fortran 2018, an optional DIM is merely required to be present.

＜Semantics＞

Reduces an array (either completely, or by collapsing one dimension) with the .OR. operation; the value is true if and only if any value (in that dimension with DIM=) is true.

＜Related＞

ALL intrinsic function, Array-scalar operations, Array-array operations, COUNT intrinsic function, IALL intrinsic function, IANY intrinsic function, IPARITY intrinsic function, MAXLOC intrinsic function, MAXVAL intrinsic function, MINLOC intrinsic function, MINVAL intrinsic function, .OR. operator, PARITY intrinsic function, PRODUCT intrinsic function, Reduction intrinsic functions, SUM intrinsic function


Array Assignment

Standard: F77 F90 F95 F2003 F2008 F2018 Example program

＜Syntax＞

array-variable = expression

＜Semantics＞

Intrinsic array assignment either assigns the value of expression to every element of array-variable (if the expression is scalar), or assigns corresponding elements of expression to array-variable. The array variable can be a simple name, a structure component, or an array section. If it has a vector subscript, the vector must not contain any repeated values.

If expression is an array, array-variable is a whole allocatable array, and not a coarray or coindexed object, and array-variable is not already allocated with the same shape as expression, it will be automatically (re-)allocated to have the same shape and bounds as expression; otherwise, array-variable must already have the same shape as expression.

＜Related＞

ALLOCATABLE attribute, Array Constructor, Array Section, DIMENSION attribute, FORALL statement, FORALL construct, WHERE statement, WHERE construct


Array Constructor

Standard: F77 F90 F95 F2003 F2008 F2018 Example program

＜Syntax＞

(/ ac-spec /)
‘[’ ac-spec ‘]’

ac-spec | ::= | [ type-spec :: ] ac-val [ , ac-val ]...
 | | | type-spec ::

ac-val ::= expression | ac-implied-do
ac-implied-do ::= ( ac-val [ , ac-val ]... , do-spec )

If no type-spec appears, the expressions must all have the same type and kind; furthermore, if they are of type character, they must all have the same length.

If a type-spec appears, the expressions must be assignment-compatible with the specified type and type parameters. Note that in the case of type character, this will pad or truncate the ac-val expressions to the length specified in the type-spec. If no ac-val appears, the constructor produces a zero-sized array.

＜Semantics＞

The array constructor creates an array value of rank one, with lower bound one. The type, kind (and length if character) of the value is specified by the type-spec if present, and otherwise is the same as that of the individual expressions . An expression may itself be an array, in which case it contributes the values of all of its elements in order.

If an array constructor contains an implied DO loop, the index variable is local to the array constructor: if the scoping unit has a local variable with the same name, evaluation of the array constructor (and thus execution of the implied DO) does not affect the value of that variable.

An array constructor that contains only constant expressions and implied DO loops is itself a constant, and can be used to define array parameters and initialise array variables.

In Fortran 2003, an array constructor can use square brackets [ ... ] instead of the parenthesis-slash combination (/ ... /). This makes expressions containing array constructors easier to read.

＜Related＞

Array Assignment, Array Section, DIMENSION attribute, DO statement, FORALL construct, FORALL statement, WHERE construct, WHERE statement


Array Section

Standard: F77 F90 F95 F2003 F2008 F2018 Example program

＜Syntax＞

data-object ( section [ , section ]... )

section ::= subscript | vector | triplet

subscript ::= scalar-integer-expr

vector ::= integer-expr
A vector must be an array expression of rank 1.

triplet ::= [ scalar-integer-expr ] : [ scalar-integer-expr ] [ : scalar-integer-expr ]

An array section contains at least one section that is not a subscript.

＜Semantics＞

An array section is a portion of an array variable or constant.

A vector-subscripted array section is not allowed to be modified by passing it as an actual argument; also, a vector-subscripted array section can only be assigned to if there are no repeated values in the vector(s).

Each triplet specifies a range of subscript values similarly to a DO loop, viz. lower, upper, and stride (in that order). A missing expression for any of these values is taken to be the lower bound of that dimension, the upper bound of that dimension, or one, respectively. The stride must be non-zero. If a triplet specifies no elements (e.g. “5:2”), the extent of that dimension in the array section is zero.

An array section that does not contain a vector subscript is a rectangular portion of the parent array, and its rank is equal to the number of triplets.

Note that except for zero-sized extents, all subscript values must be within the array bounds for the dimension.

The lower bounds of an array section are all equal to one, regardless of the lower bounds of the parent array.

＜Related＞

Array Assignment, Array Constructor, DIMENSION statement, FORALL construct, FORALL statement, WHERE construct, WHERE statement


Array-array Operations
Standard: F77 F90 F95 F2003 Example Program
<Syntax>
 | unary-op array array binary-op array unary-op ::= + | - | .NOT. | user-operator binary-op ::= + | - | * | / | ** | // | .AND. | .OR. | .EQV. | .NEQV. | == | /= | < | <= | > | >= | user-operator For array binary-op array, both arrays must have the same shape.
<Semantics>
 | Elemental unary operations are applied individually to each array element. Elemental binary operations are applied individually to corresponding array elements. All intrinsic operations are elemental. An elemental user-operator is defined by an INTERFACE block with the OPERATOR(user-operator) and a specific procedure that is ELEMENTAL. In Fortran 2003, an elemental user-operator may also be defined by a generic type-bound procedure with a specific type-bound procedure that is ELEMENTAL.
<Related>
 | Array Assignment, Array-scalar Operations, FUNCTION statement, INTERFACE OPERATOR statement


<Example Program>

Program array_array_op_example
Real, Dimension(2,3) :: a, b, c
a = Reshape( (/1.,2.,3.,4.,5.,6./), (/2,3/))
b = Reshape( (/2.,3.,4.,5.,6.,7./), (/2,3/))
c = a + b
Print *, c(1,:)
Print *, c(2,:)
End
Execution Results

3.0000000 7.0000000 11.0000000
5.0000000 9.0000000 13.0000000


Array-scalar Operations
Standard: F77 F90 F95 F2003 Example Program
<Syntax>
 | array binary-op scalar scalar binary-op array binary-op ::= + | - | * | / | ** | // | .AND. | .OR. | .EQV. | .NEQV. | == | /= | < | <= | > | >= | user-operator
<Semantics>
 | Elemental operations between an array and a scalar are applied individually to each element of the array; the result is as if the scalar was “broadcast” to be an array with the same shape. All intrinsic operations are elemental. An elemental user-operator is defined by an INTERFACE block with the OPERATOR(user-operator) and a specific procedure that is ELEMENTAL. In Fortran 2003, an elemental user-operator can also be defined by a generic type-bound procedure with a specific type-bound procedure that is ELEMENTAL.
<Related>
 | Array Assignment, Array-array Operations, FUNCTION statement, INTERFACE OPERATOR statement


<Example Program>

Program array_scalar_op_example
Real, Dimension(2,3) :: a, b
a = Reshape( (/1.,2.,3.,4.,5.,6./), (/2,3/))
b = 2.*a
Print *, b(1,:)
Print *, b(2,:)
End
Execution Results

2.0000000 6.0000000 10.0000000
4.0000000 8.0000000 12.0000000


ASIN intrinsic function

Standard: F77 F90 F95 F2003 F2008 Example program

＜Syntax＞

ASIN ( X )

X : Real or Complex;

Result : Same type and kind as X.

＜Semantics＞

The value of the result is an approximation to the arc sine of X, in radians. Like many intrinsic functions, this is elemental; the result has the same shape as X, with the operation being applied elementwise.

If X is of type Real, it must be in the range −1≤X≤+1, and the result will be in the range −π/2≤ASIN(X)≤π/2. If X is of type Complex, the real part of the result is in radians, in the range −π/2≤REAL(ASIN(X))≤π/2.

＜Related＞

ASINH intrinsic function, SIN intrinsic function


ASINH intrinsic function

Standard: F77 F90 F95 F2003 F2008 Example program

＜Syntax＞

ASINH ( X )

X : Real or Complex;

Result : Same type and kind as X.

＜Semantics＞

The value of the result is an approximation to the arc hyperbolic sine of X. Like many intrinsic functions, this is elemental; the result has the same shape as X, with the operation being applied elementwise.

If X is of type Complex, the imaginary part of the result is in radians, in the range −π/2≤AIMAG(ASINH(X))≤π/2.

＜Related＞

ASIN intrinsic function, SINH intrinsic function


ASSIGN statement

Standard: F77 F90 F95 F2003 F2008 Example program

＜Syntax＞

ASSIGN label TO variable

＜Semantics＞

Assigns a label to an integer variable. This does not define the integer as a variable and it must not be referenced or copied. If the label is that of a FORMAT statement, it may be used in place of a label in an input/output statement. Otherwise, it must be the label of a valid branch target statement, and may be used in an assigned GOTO statement.

This statement was deleted from the Fortran 95 standard as it was considered too error-prone and hard to understand. Computed GOTO statements, SELECT CASE statements, and character string format specifiers should be used instead.

It remains deleted in Fortran 2003 and 2008, though all compilers still accept it as an extension.

＜Related＞

CASE construct, GO TO statement, FORMAT statement


ASSOCIATE construct

Standard: F77 F90 F95 F2003 F2008 F2018 Example program

＜Syntax＞

associate-stmt
block
end-associate-stmt

The syntax of the ASSOCIATE statement (associate-stmt) is as follows.

[ construct-name : ] ASSOCIATE ( association-list )

where:
association-list ::= association [ , association ]...
association ::= associate-name => selector
selector ::= variable | expr

If the ASSOCIATE statement has a construct name (construct-name), the END ASSOCIATE statement needs to have the same construct name.

＜Semantics＞

The ASSOCIATE construct associates one or more names with a variable(s) and/or value(s) throughout execution of the construct. Each associate-name of an ASSOCIATE construct is local to the construct; its type and rank are determined by the construct and are unaffected by any declaration outside the construct.

Throughout the construct, the associate name is a variable if and only if the selector is a variable; any changes to the associate name affect the variable with which it is associated. If the selector is an expression (expr), the associate name is not permitted to appear in any context that requires a variable.

The associate name is polymorphic if and only if its selector is polymorphic. If the selector is a pointer or allocatable, it must be associated or allocated on execution of the ASSOCIATE statement; the associate name does not have the POINTER or ALLOCATABLE attribute (but will have the TARGET attribute if the selector has either the POINTER or TARGET attribute).

＜Related＞

END ASSOCIATE statement, SELECT TYPE construct


ASSOCIATED intrinsic function

Standard: F77 F90 F95 F2003 F2008 Example program

＜Syntax＞

ASSOCIATED ( POINTER [ , TARGET ] )

POINTER : pointer of any type and rank;
TARGET : pointer, variable with the TARGET attribute, or a procedure;

Result : Logical scalar, default kind.

＜Semantics＞

If TARGET is present, the result is .TRUE. if POINTER is currently associated with the TARGET, and .FALSE. otherwise. Note that if POINTER is an array, TARGET must describe the same array elements in the same order to be considered to be associated. Note also that if POINTER is polymorphic, TARGET must have the same dynamic type to be considered to be associated.

If TARGET is absent, the result is .TRUE. if POINTER is currently associated, and .FALSE. if it is currently disassociated.

Note that neither POINTER nor TARGET is permitted to be an undefined pointer. A typical undefined pointer is one that has never been given an association status, or which is “dangling”. Note also that TARGET is required to be a permissible target for POINTER in a pointer assignment. This means that the type, type parameters, rank, and procedureness must match.

Fortran 2003 has procedure pointers, so POINTER can be a procedure pointer and TARGET can be a procedure.

＜Related＞

ALLOCATE statement, ALLOCATED intrinsic function, DEALLOCATE statement, NULL intrinsic function, NULLIFY statement, POINTER attribute, Pointer assignment statement (=>), TARGET attribute.


ASYNCHRONOUS attribute

Standard: F77 F90 F95 F2003 F2008 F2018 Example program

＜Syntax＞

type , ASYNCHRONOUS [ , attr ]... :: decl-list

ASYNCHRONOUS [::] [name [ , name ]...

＜Semantics＞

Declares that a variable may be subject to asynchronous input/output. This attribute is implicitly declared by the use of a variable in an asynchronous input/output statement, so is only needed if a variable is passed as an actual argument to a procedure that does asynchronous input/output, and only then if the input/output is not completed within the single procedure.

A variable that is accessed by a USE statement or by host association is permitted to be declared ASYNCHRONOUS; this does not hide the variable, but makes it asynchronous only within the local procedure.

In Fortran 2018, this attribute is also used to signify that the variable may be subject to “asynchronous communication”. This includes things like MPI nonblocking communications such as MPI_ISEND, and low-level operating-system native asynchronous i/o.

＜Related＞

ASYNCHRONOUS= specifier, ID= specifier, INQUIRE statement, PENDING= specifier, READ statement, WAIT statement, WRITE statement


ASYNCHRONOUS= specifier

Standard: F77 F90 F95 F2003 F2008 Example program

＜Syntax＞

ASYNCHRONOUS = expression

The expression must be a scalar character expression. This specifier is permitted in the INQUIRE, OPEN, READ and WRITE statements. In the INQUIRE statement, it must be a variable designator, and is assigned the value 'YES', 'NO' or 'UNDEFINED'; in all other statements it must evaluate to 'YES' or 'NO' (ignoring case).

In the READ and WRITE statements it must be a constant expression.

＜Semantics＞

The ASYNCHRONOUS= specifier determines whether asynchronous input/output is anticipated (for OPEN), permitted (for INQUIRE) or being requested (for READ and WRITE).

An asynchronous READ or WRITE is only permitted on a file that is connected for asynchronous input/output (i.e. opened with ASYNCHRONOUS='YES').

An asynchronous READ or WRITE is not required to act asynchronously, this is only a request to the Fortran processor. The ID= specifier and the PENDING= specifier may be used to control or inquire on the progress of an asynchronous input/output operation.

A variable that is subject to asynchronous input/output must have the ASYNCHRONOUS attribute; this is conferred implicitly in any scoping unit that contains a relevant asynchronous READ or WRITE statement using that variable, but must be declared explicitly if it remains subject to asynchronous input/output on return to another scoping unit.

Note that ASYNCHRONOUS='YES' is not permitted on a READ or WRITE statement that invokes a defined input/output procedure.

＜Related＞

ASYNCHRONOUS attribute, Defined input/output, ID= specifier, INQUIRE statement, OPEN statement, PENDING= specifier, READ statement, WRITE statement


ATAN intrinsic function

Standard: F77 F90 F95 F2003 F2008 Example program

＜Syntax＞

ATAN ( X )
or ATAN ( Y, X )

X : Real or Complex;
Y : Conformable with X, same type and kind as X, which must be Real if Y is present;
the NAG Fortran Compiler also permits Y to have a different kind (this is non-standard);

Result : Same type as X, with kind the same as that of X+Y.

＜Semantics＞

The value of the result is an approximation to the arc tangent of X, in radians. Like many intrinsic functions, this is elemental; the result has the same shape as X, with the operation being applied elementwise.

If X is of type Real, the result is in radians in the range −π/2≤ATAN(X)≤π/2. If X is of type Complex, the real part of the result is in radians, in the range −π/2≤REAL(ATAN(X))≤π/2.

The 2-argument form, ATAN ( Y, X ), is identical to ATAN2 ( Y, X ).

＜Related＞

ATAN2 intrinsic function, ATANH intrinsic function, TAN intrinsic function


ATAN2 intrinsic function

Standard: F77 F90 F95 F2003 F2008 Example program

＜Syntax＞

ATAN2 ( Y, X )

X : Real;
Y : Same type and kind as X, conformable with X;
the NAG Fortran Compiler also permits Y to have a different kind (this is non-standard);

Result : Same type as X, with kind the same as the kind of X+Y.

＜Semantics＞

The value of the result is an approximation to the arc tangent of Y/X, where Y is the sine and X is the cosine. The result is in radians, in the range −π≤ATAN2(Y,X)≤π.

Like many intrinsic functions, this is elemental; if either (or both) of X and Y is an array, the result will be an array with that shape, with the value being computed elementwise.

＜Related＞

ATAN intrinsic function, ATANH intrinsic function, COS intrinsic function, SIN intrinsic function, TAN intrinsic function


ATANH intrinsic function

Standard: F77 F90 F95 F2003 F2008 Example program

＜Syntax＞

ATANH ( X )

X : Real or Complex;

Result : Same type and kind as X.

＜Semantics＞

The value of the result is an approximation to the arc hyperbolic tangent of X. Like many intrinsic functions, this is elemental; the result has the same shape as X, with the operation being applied elementwise.

If X is of type Real, it must lie in the range −1<X<+1 (the result is infinite if ABS(X)==1, and NaN if ABS(X)>1). If X is of type Complex, the imaginary part of the result is in radians, in the range −π/2≤AIMAG(ATANH(X))≤π/2.

＜Related＞

ATAN intrinsic function, TANH intrinsic function.


ATOMIC_ADD intrinsic subroutine

Standard: F77 F90 F95 F2003 F2008 F2018 Example program

＜Syntax＞

CALL ATOMIC_ADD(ATOM, VALUE [ , STAT ] )

ATOM : scalar Integer(atomic_int_kind), Intent(InOut), must be a coarray or a coindexed object;
VALUE : scalar Integer;
STAT : scalar Integer, not a coindexed object, Intent(Out). STAT must be able to represent the values −9999 to +9999 (i.e. 16 bits or larger).

＜Semantics＞

The variable ATOM is atomically assigned the value of ATOM+VALUE, without regard to the segment rules. If STAT is present, it is assigned a positive value if an error occurs, and zero otherwise. If an error occurs and STAT is not present, the program is terminated.

Note that VALUE is not required to have the same kind as ATOM; however, the values of VALUE and ATOM+VALUE must be representable in atomic_int_kind.

If ATOM is a coindexed variable that lies on a failed image, the error STAT_FAILED_IMAGE occurs.

＜Related＞

ATOMIC_AND intrinsic subroutine, ATOMIC_CAS intrinsic subroutine, ATOMIC_DEFINE intrinsic subroutine, ATOMIC_FETCH_ADD intrinsic subroutine, ATOMIC_OR intrinsic subroutine, ATOMIC_REF intrinsic subroutine, ATOMIC_XOR intrinsic subroutine, CODIMENSION attribute, Image selectors


ATOMIC_AND intrinsic subroutine

Standard: F77 F90 F95 F2003 F2008 F2018 Example program

＜Syntax＞

CALL ATOMIC_AND(ATOM, VALUE [ , STAT ] )

ATOM : scalar Integer(atomic_int_kind), Intent(InOut), must be a coarray or a coindexed object;
VALUE : scalar Integer;
STAT : scalar Integer, not a coindexed object, Intent(Out). STAT must be able to represent the values −9999 to +9999 (i.e. 16 bits or larger).

＜Semantics＞

The variable ATOM is atomically assigned the value of IAND(ATOM,INT(VALUE,atomic_int_kind)), without regard to the segment rules.

If STAT is present, it is assigned a positive value if an error occurs, and zero otherwise. If an error occurs and STAT is not present, the program is terminated.

Note that VALUE is not required to have the same kind as ATOM; however, the value of VALUE must be representable in atomic_int_kind.

If ATOM is a coindexed variable that lies on a failed image, the error STAT_FAILED_IMAGE occurs.

＜Related＞

ATOMIC_ADD intrinsic subroutine, ATOMIC_CAS intrinsic subroutine, ATOMIC_DEFINE intrinsic subroutine, ATOMIC_FETCH_AND intrinsic subroutine, ATOMIC_OR intrinsic subroutine, ATOMIC_REF intrinsic subroutine, ATOMIC_XOR intrinsic subroutine, CODIMENSION attribute, Image selectors


ATOMIC_CAS intrinsic subroutine

Standard: F77 F90 F95 F2003 F2008 F2018 Example program

＜Syntax＞

CALL ATOMIC_CAS(ATOM, OLD, COMPARE, NEW [ , STAT ] )

ATOM : scalar Integer(atomic_int_kind), Intent(InOut), must be a coarray or a coindexed object;
OLD : scalar Integer(atomic_int_kind), Intent(Out);
COMPARE : scalar Integer(atomic_int_kind);
NEW : scalar Integer(atomic_int_kind);
STAT : scalar Integer, not a coindexed object, Intent(Out).
STAT must be able to represent the values −9999 to +9999 (i.e. 16 bits or larger).

＜Semantics＞

This is an atomic Compare-And-Swap operation: the variable ATOM is atomically compared to COMPARE and changed to the value NEW if equal; if unequal, ATOM is unchanged. The variable OLD is assigned the actual value that ATOM had at the time of comparison (this means that the swap occurred if and only if OLD==COMPARE afterwards).

If STAT is present, it is assigned a positive value if an error occurs, and zero otherwise. If an error occurs and STAT is not present, the program is terminated.

If ATOM is a coindexed variable that lies on a failed image, the error STAT_FAILED_IMAGE occurs.

＜Related＞

ATOMIC_ADD intrinsic subroutine, ATOMIC_AND intrinsic subroutine, ATOMIC_DEFINE intrinsic subroutine, ATOMIC_FETCH_ADD intrinsic subroutine, ATOMIC_FETCH_AND intrinsic subroutine, ATOMIC_FETCH_OR intrinsic subroutine, ATOMIC_FETCH_XOR intrinsic subroutine, ATOMIC_OR intrinsic subroutine, ATOMIC_REF intrinsic subroutine, ATOMIC_XOR intrinsic subroutine, CODIMENSION attribute, Image selectors


ATOMIC_DEFINE intrinsic subroutine

Standard: F77 F90 F95 F2003 F2008 F2018 Example program

＜Syntax＞

CALL ATOMIC_DEFINE(ATOM, VALUE [ , STAT ] )

ATOM : scalar Integer(atomic_int_kind) or Logical(atomic_logical_kind), Intent(Out), must be a coarray or a coindexed object;
VALUE : scalar, same type as ATOM;
STAT : scalar Integer, not a coindexed object, Intent(Out).

STAT must be able to represent the values −9999 to +9999 (i.e. 16 bits or larger).

＜Semantics＞

The variable ATOM is atomically assigned the value of VALUE, without regard to the segment rules. If STAT is present, it is assigned a positive value if an error occurs, and zero otherwise. If an error occurs and STAT is not present, the program is terminated.

Note that VALUE is not required to have the same kind as ATOM; however, the value of VALUE must be representable in atomic_int_kind (e.g. if atomic_int_kind specifies 32 bits and VALUE is a 64-bit integer, the value of VALUE must not be outside the range −2147483648 to +2147483647).

If ATOM is a coindexed variable that lies on a failed image, the error STAT_FAILED_IMAGE occurs.

＜Related＞

ATOMIC_REF intrinsic subroutine, CODIMENSION attribute, Image selectors


ATOMIC_FETCH_ADD intrinsic subroutine

Standard: F77 F90 F95 F2003 F2008 F2018 Example program

＜Syntax＞

CALL ATOMIC_FETCH_ADD(ATOM, VALUE, OLD [ , STAT ] )

ATOM : scalar Integer(atomic_int_kind), Intent(InOut), must be a coarray or a coindexed object;
VALUE : scalar Integer;
OLD : scalar Integer(atomic_int_kind), Intent(Out);
STAT : scalar Integer, not a coindexed object, Intent(Out).
STAT must be able to represent the values −9999 to +9999 (i.e. 16 bits or larger).

＜Semantics＞

The variable ATOM is atomically assigned the value of ATOM+VALUE, without regard to the segment rules, and OLD is assigned the value that ATOM had immediately before the operation. If STAT is present, it is assigned a positive value if an error occurs, and zero otherwise. If an error occurs and STAT is not present, the program is terminated.

Note that VALUE is not required to have the same kind as ATOM; however, the values of VALUE and ATOM+VALUE must be representable in atomic_int_kind.

If ATOM is a coindexed variable that lies on a failed image, the error STAT_FAILED_IMAGE occurs.

＜Related＞

ATOMIC_ADD intrinsic subroutine, ATOMIC_CAS intrinsic subroutine, ATOMIC_DEFINE intrinsic subroutine, ATOMIC_FETCH_AND intrinsic subroutine, ATOMIC_FETCH_OR intrinsic subroutine, ATOMIC_FETCH_XOR intrinsic subroutine, ATOMIC_REF intrinsic subroutine, CODIMENSION attribute, Image selectors


ATOMIC_FETCH_AND intrinsic subroutine

Standard: F77 F90 F95 F2003 F2008 F2018 Example program

＜Syntax＞

CALL ATOMIC_FETCH_AND(ATOM, VALUE, OLD [ , STAT ] )

ATOM : scalar Integer(atomic_int_kind), Intent(InOut), must be a coarray or a coindexed object;
VALUE : scalar Integer;
OLD : scalar Integer(atomic_int_kind), Intent(Out);
STAT : scalar Integer, not a coindexed object, Intent(Out).
STAT must be able to represent the values −9999 to +9999 (i.e. 16 bits or larger).

＜Semantics＞

The variable ATOM is atomically assigned the value of IAND(ATOM,INT(VALUE,atomic_int_kind)), without regard to the segment rules, and OLD is assigned the value that ATOM had immediately before the operation. If STAT is present, it is assigned a positive value if an error occurs, and zero otherwise. If an error occurs and STAT is not present, the program is terminated.

Note that VALUE is not required to have the same kind as ATOM; however, the value of VALUE must be representable in atomic_int_kind.

If ATOM is a coindexed variable that lies on a failed image, the error STAT_FAILED_IMAGE occurs.

＜Related＞

ATOMIC_AND intrinsic subroutine, ATOMIC_CAS intrinsic subroutine, ATOMIC_DEFINE intrinsic subroutine, ATOMIC_FETCH_ADD intrinsic subroutine, ATOMIC_FETCH_OR intrinsic subroutine, ATOMIC_FETCH_XOR intrinsic subroutine, ATOMIC_REF intrinsic subroutine, CODIMENSION attribute, Image selectors


ATOMIC_FETCH_OR intrinsic subroutine

Standard: F77 F90 F95 F2003 F2008 F2018 Example program

＜Syntax＞

CALL ATOMIC_FETCH_OR(ATOM, VALUE, OLD [ , STAT ] )

ATOM : scalar Integer(atomic_int_kind), Intent(InOut), must be a coarray or a coindexed object;
VALUE : scalar Integer;
OLD : scalar Integer(atomic_int_kind), Intent(Out);
STAT : scalar Integer, not a coindexed object, Intent(Out).
STAT must be able to represent the values −9999 to +9999 (i.e. 16 bits or larger).

＜Semantics＞

The variable ATOM is atomically assigned the value of IOR(ATOM,INT(VALUE,atomic_int_kind)), without regard to the segment rules, and OLD is assigned the value that ATOM had immediately before the operation. If STAT is present, it is assigned a positive value if an error occurs, and zero otherwise. If an error occurs and STAT is not present, the program is terminated.

Note that VALUE is not required to have the same kind as ATOM; however, the value of VALUE must be representable in atomic_int_kind.

If ATOM is a coindexed variable that lies on a failed image, the error STAT_FAILED_IMAGE occurs.

＜Related＞

ATOMIC_CAS intrinsic subroutine, ATOMIC_DEFINE intrinsic subroutine, ATOMIC_FETCH_ADD intrinsic subroutine, ATOMIC_FETCH_AND intrinsic subroutine, ATOMIC_FETCH_XOR intrinsic subroutine, ATOMIC_OR intrinsic subroutine, ATOMIC_REF intrinsic subroutine, CODIMENSION attribute, Image selectors


ATOMIC_FETCH_XOR intrinsic subroutine

Standard: F77 F90 F95 F2003 F2008 F2018 Example program

＜Syntax＞

CALL ATOMIC_FETCH_XOR(ATOM, VALUE, OLD [ , STAT ] )

ATOM : scalar Integer(atomic_int_kind), Intent(InOut), must be a coarray or a coindexed object;
VALUE : scalar Integer;
OLD : scalar Integer(atomic_int_kind), Intent(Out);
STAT : scalar Integer, not a coindexed object, Intent(Out).
STAT must be able to represent the values −9999 to +9999 (i.e. 16 bits or larger).

＜Semantics＞

The variable ATOM is atomically assigned the value of IEOR(ATOM,INT(VALUE,atomic_int_kind)), without regard to the segment rules, and OLD is assigned the value that ATOM had immediately before the operation. If STAT is present, it is assigned a positive value if an error occurs, and zero otherwise. If an error occurs and STAT is not present, the program is terminated.

Note that VALUE is not required to have the same kind as ATOM; however, the value of VALUE must be representable in atomic_int_kind.

If ATOM is a coindexed variable that lies on a failed image, the error STAT_FAILED_IMAGE occurs.

＜Related＞

ATOMIC_CAS intrinsic subroutine, ATOMIC_DEFINE intrinsic subroutine, ATOMIC_FETCH_ADD intrinsic subroutine, ATOMIC_FETCH_AND intrinsic subroutine, ATOMIC_FETCH_OR intrinsic subroutine, ATOMIC_REF intrinsic subroutine, ATOMIC_XOR intrinsic subroutine, CODIMENSION attribute, Image selectors


ATOMIC_OR intrinsic subroutine

Standard: F77 F90 F95 F2003 F2008 F2018 Example program

＜Syntax＞

CALL ATOMIC_OR(ATOM, VALUE [ , STAT ] )

ATOM : scalar Integer(atomic_int_kind), Intent(InOut), must be a coarray or a coindexed object;
VALUE : scalar Integer;
STAT : scalar Integer, not a coindexed object, Intent(Out). STAT must be able to represent the values −9999 to +9999 (i.e. 16 bits or larger).

＜Semantics＞

The variable ATOM is atomically assigned the value of IOR(ATOM,INT(VALUE,atomic_int_kind)), without regard to the segment rules. If STAT is present, it is assigned a positive value if an error occurs, and zero otherwise. If an error occurs and STAT is not present, the program is terminated.

Note that VALUE is not required to have the same kind as ATOM; however, the value of VALUE must be representable in atomic_int_kind.

If ATOM is a coindexed variable that lies on a failed image, the error STAT_FAILED_IMAGE occurs.

＜Related＞

ATOMIC_ADD intrinsic subroutine, ATOMIC_AND intrinsic subroutine, ATOMIC_CAS intrinsic subroutine, ATOMIC_DEFINE intrinsic subroutine, ATOMIC_FETCH_OR intrinsic subroutine, ATOMIC_REF intrinsic subroutine, ATOMIC_XOR intrinsic subroutine, CODIMENSION attribute, Image selectors


ATOMIC_REF intrinsic subroutine

Standard: F77 F90 F95 F2003 F2008 F2018 Example program

＜Syntax＞

CALL ATOMIC_REF(VALUE, ATOM [ , STAT ] )

VALUE : scalar, same type and kind as ATOM;
ATOM : scalar Integer(atomic_int_kind) or Logical(atomic_logical_kind), Intent(In), must be a coarray or a coindexed object;
STAT : scalar Integer, not a coindexed object, Intent(Out).

STAT must be able to represent the values −9999 to +9999 (i.e. 16 bits or larger).

＜Semantics＞

The variable ATOM is atomically referenced, and its value assigned to VALUE, without regard to the segment rules. Note that the assignment to VALUE is not atomic, only the reference to ATOM executes atomically. If STAT is present, it is assigned a positive value if an error occurs, and zero otherwise. If an error occurs and STAT is not present, the program is terminated.

Note that VALUE is not required to have the same kind as ATOM; if it is smaller, the value of ATOM must be one that will fit into VALUE (e.g. if VALUE is a 16-bit integer, the value of ATOM must not be outside the range −32768 to +32767).

If ATOM is a coindexed variable that lies on a failed image, the error STAT_FAILED_IMAGE occurs.

＜Related＞

ATOMIC_DEFINE intrinsic subroutine, CODIMENSION attribute, Image selectors


ATOMIC_XOR intrinsic subroutine

Standard: F77 F90 F95 F2003 F2008 F2018 Example program

＜Syntax＞

CALL ATOMIC_XOR(ATOM, VALUE [ , STAT ] )

ATOM : scalar Integer(atomic_int_kind), Intent(InOut), must be a coarray or a coindexed object;
VALUE : scalar Integer;
STAT : scalar Integer, not a coindexed object, Intent(Out). STAT must be able to represent the values −9999 to +9999 (i.e. 16 bits or larger).

＜Semantics＞

The variable ATOM is atomically assigned the value of IEOR(ATOM,INT(VALUE,atomic_int_kind)), without regard to the segment rules. If STAT is present, it is assigned a positive value if an error occurs, and zero otherwise. If an error occurs and STAT is not present, the program is terminated.

Note that VALUE is not required to have the same kind as ATOM; however, the value of VALUE must be representable in atomic_int_kind.

If ATOM is a coindexed variable that lies on a failed image, the error STAT_FAILED_IMAGE occurs.

＜Related＞

ATOMIC_ADD intrinsic subroutine, ATOMIC_AND intrinsic subroutine, ATOMIC_CAS intrinsic subroutine, ATOMIC_DEFINE intrinsic subroutine, ATOMIC_FETCH_XOR intrinsic subroutine, ATOMIC_OR intrinsic subroutine, ATOMIC_REF intrinsic subroutine, CODIMENSION attribute, Image selectors


Attributes

Standard: F77 F90 F95 F2003 F2008

＜Syntax＞

attr-spec | ::= | access-spec
 | | | ALLOCATABLE
 | | | ASYNCHRONOUS
 | | | bind-spec
 | | | CODIMENSION [ coarray-spec ]
 | | | CONTIGUOUS
 | | | DIMENSION ( array-spec )
 | | | EXTERNAL
 | | | INTENT ( intent )
 | | | INTRINSIC
 | | | OPTIONAL
 | | | PARAMETER
 | | | POINTER
 | | | PROTECTED
 | | | SAVE
 | | | TARGET
 | | | VALUE
 | | | VOLATILE

access-spec | ::= | PRIVATE
 | | | PUBLIC

bind-spec ::= BIND ( C [ , NAME = expression ] )

intent ::= IN | INOUT | OUT

An attr-spec may appear in a Type Declaration statement. Also, some attr-specs may appear in a Component Definition statement; these are: access-spec, ALLOCATABLE, CODIMENSION, CONTIGUOUS, DIMENSION and POINTER. The syntax for both of these statements is

type [ [ , attr-spec ]... :: ] entity-decl-list

＜Semantics＞

Each attr-spec specifies that the entities being declared have the corresponding attribute. As well as being specified in type declaration and component definition statements, attributes may be individually specified on their own attribute specification statements.

＜Related＞

ALLOCATABLE attribute, ASYNCHRONOUS attribute, BIND attribute, Component Definition statement, CODIMENSION attribute, CONTIGUOUS attribute, DIMENSION attribute, Entity Declaration List, EXTERNAL attribute, INTENT attribute, INTRINSIC attribute, PARAMETER attribute, OPTIONAL attribute, POINTER attribute, PRIVATE attribute, PROTECTED attribute, PUBLIC attribute, SAVE attribute, TARGET attribute, Type Declaration statement, VALUE attribute, VOLATILE attribute


BACKSPACE statement

Standard: F77 F90 F95 F2003 F2008 F2018 Example program

＜Syntax＞

BACKSPACE (bs-spec-list)
BACKSPACE expression

bs-spec-list ::= bs-spec [,bs-spec]...

bs-spec | ::= | [ UNIT= ] expression
 | | | ERR=label
 | | | IOMSG=variable
 | | | IOSTAT=variable

The UNIT= specifier is required, and the optional UNIT= can be omitted only if it is the first bs-spec. The expression for the UNIT= specifier must be a scalar integer expression whose value identifies a valid i/o unit. The variable for the IOSTAT= specifier must be a scalar integer variable, and should not be smaller than 16 bits. The variable for the IOMSG= specifier must be a scalar default character variable.

The “BACKSPACE expression” form is equivalent to “BACKSPACE (UNIT=expression)”.

＜Semantics＞

Backspaces an input/output unit one record.

Note that some files are incapable of being backspaced (an error will occur).

The IOMSG= specifier was added in Fortran 2003; if an error occurs, this sets a character string variable to an error message, otherwise it is unchanged. The ERR= or IOSTAT= specifier is still needed to prevent termination on error.

＜Related＞

CLOSE statement, ENDFILE statement, ERR= specifier, IOMSG= specifier, IOSTAT= specifier, OPEN statement, PRINT statement, READ statement, REWIND statement, UNIT= specifier, WRITE statement


BESSEL_J0 intrinsic function

Standard: F77 F90 F95 F2003 F2008 F2018 Example program

＜Syntax＞

BESSEL_J0 ( X )

X : Real;

Result : Same type and kind as X.

＜Semantics＞

The value of the result is an approximation to the Bessel function of the 1st kind, order 0, at the point X. Like many intrinsic functions, this is elemental; the result has the same shape as X, with the operation being applied elementwise.

＜Related＞

BESSEL_J1 intrinsic function, BESSEL_JN intrinsic function, BESSEL_Y0 intrinsic function, BESSEL_Y1 intrinsic function, BESSEL_YN intrinsic function


BESSEL_J1 intrinsic function

Standard: F77 F90 F95 F2003 F2008 F2018 Example program

＜Syntax＞

BESSEL_J1 ( X )

X : Real;

Result : Same type and kind as X.

＜Semantics＞

The value of the result is an approximation to the Bessel function of the 1st kind, order 1, at the point X. Like many intrinsic functions, this is elemental; the result has the same shape as X, with the operation being applied elementwise.

＜Related＞

BESSEL_J0 intrinsic function, BESSEL_JN intrinsic function, BESSEL_Y0 intrinsic function, BESSEL_Y1 intrinsic function, BESSEL_YN intrinsic function


BESSEL_JN intrinsic function

Standard: F77 F90 F95 F2003 F2008 F2018 Example program

＜Syntax＞

Elemental Form

BESSEL_JN ( N, X )

N : Integer, with non-negative value;
X : Real;

Result : Same type and kind as X.

Transformational Form

BESSEL_JN ( N1, N2, X )

N1 : Integer scalar, with non-negative value;
N2 : Integer scalar, with non-negative value;
X : Real scalar;

Result : Vector of size MAX(N2-N1+1,0) with the same type and kind as X.

＜Semantics＞

For the elemental form, the value of the result is an approximation to the Bessel function of the 1st kind, order N, at the point X. Being elemental, the result has the same shape as X or N, whichever is an array, with the operation being applied elementwise. If both X and N are arrays, they must have the same shape.

For the transformational form, the value of the result is an approximation to the Bessel function of the 1st kind, orders N1 to N2, at the point X. If N2<N1, the result will be a zero-sized array.

＜Related＞

BESSEL_J0 intrinsic function, BESSEL_J1 intrinsic function, BESSEL_Y0 intrinsic function, BESSEL_Y1 intrinsic function, BESSEL_YN intrinsic function


BESSEL_Y0 intrinsic function

Standard: F77 F90 F95 F2003 F2008 F2018 Example program

＜Syntax＞

BESSEL_Y0 ( X )

X : Real, with value greater than zero;

Result : Same type and kind as X.

＜Semantics＞

The value of the result is an approximation to the Bessel function of the 2nd kind, order 0, at the point X. Like many intrinsic functions, this is elemental; the result has the same shape as X, with the operation being applied elementwise.

＜Related＞

BESSEL_J0 intrinsic function, BESSEL_J1 intrinsic function, BESSEL_JN intrinsic function, BESSEL_Y1 intrinsic function, BESSEL_YN intrinsic function


BESSEL_Y1 intrinsic function

Standard: F77 F90 F95 F2003 F2008 F2018 Example program

＜Syntax＞

BESSEL_Y1 ( X )

X : Real, with value greater than zero;

Result : Same type and kind as X.

＜Semantics＞

The value of the result is an approximation to the Bessel function of the 2nd kind, order 0, at the point X. Like many intrinsic functions, this is elemental; the result has the same shape as X, with the operation being applied elementwise.

＜Related＞

BESSEL_J0 intrinsic function, BESSEL_J1 intrinsic function, BESSEL_JN intrinsic function, BESSEL_Y0 intrinsic function, BESSEL_YN intrinsic function


BESSEL_YN intrinsic function

Standard: F77 F90 F95 F2003 F2008 F2018 Example program

＜Syntax＞

Elemental Form

BESSEL_YN ( N, X )

N : Integer, with non-negative value;
X : Real;

Result : Same type and kind as X.

Transformational Form

BESSEL_YN ( N1, N2, X )

N1 : Integer scalar, with non-negative value;
N2 : Integer scalar, with non-negative value;
X : Real scalar;

Result : Vector of size MAX(N2-N1+1,0) with the same type and kind as X.

＜Semantics＞

For the elemental form, the value of the result is an approximation to the Bessel function of the 2nd kind, order N, at the point X. Being elemental, the result has the same shape as X or N, whichever is an array, with the operation being applied elementwise. If both X and N are arrays, they must have the same shape.

For the transformational form, the value of the result is an approximation to the Bessel function of the 2nd kind, orders N1 to N2, at the point X. If N2<N1, the result will be a zero-sized array.

＜Related＞

BESSEL_J0 intrinsic function, BESSEL_J1 intrinsic function, BESSEL_JN intrinsic function, BESSEL_Y0 intrinsic function, BESSEL_Y1 intrinsic function


BGE intrinsic function

Standard: F77 F90 F95 F2003 F2008 F2018 Example program

＜Syntax＞

BGE ( I, J )

I : Integer;
J : Integer, same kind as I, conformable with I;

Result : Logical.

＜Semantics＞

This function does a bitwise comparison between two integers; the value of the result is .TRUE. if I is greater than or equal to J when treated as unsigned integers. This is an elemental function, so if either or both of I or J is an array, the result has the same shape as the operand array(s), with the operation being applied elementwise.

＜Related＞

BGT intrinsic function, BLE intrinsic function, BLT intrinsic function


BGT intrinsic function

Standard: F77 F90 F95 F2003 F2008 F2018 Example program

＜Syntax＞

BGT ( I, J )

I : Integer;
J : Integer, same kind as I, conformable with I;

Result : Logical.

＜Semantics＞

This function does a bitwise comparison between two integers; the value of the result is .TRUE. if I is greater than J when treated as unsigned integers. This is an elemental function, so if either or both of I or J is an array, the result has the same shape as the operand array(s), with the operation being applied elementwise.

＜Related＞

BGE intrinsic function, BLE intrinsic function, BLT intrinsic function


BIND attribute

Standard: F77 F90 F95 F2003 F2008 Example program

＜Syntax (variables and common blocks)＞

type, BIND(C [ , NAME=expression ] ) [ , attr ] :: decl-list

BIND ( C [ , NAME=expression ] ) [ :: ] entity [ , entity ]...

entity ::= variable-name | / common-block-name /

The expression must be a scalar constant expression of type character with default kind.

For a variable, this declaration is only allowed in the specification part of a module.

For a common block, this attribute implies the SAVE attribute (which can be confirmed explicitly). A common block with this attribute must be declared with the attribute everywhere in the program.

If NAME=name appears, only one entity or decl is allowed.

＜Syntax (types and procedures)＞

The BIND attribute for a derived type appears on the TYPE statement. The BIND attribute for a procedure appears on the FUNCTION statement or SUBROUTINE statement in an external, internal, or module subprogram (when defining the procedure) or in an interface body (when declaring an external procedure or dummy procedure with that attribute). Prior to Fortran 2008, an internal procedure was not permitted to have the BIND attribute.

The NAME= specifier is not allowed for an internal procedure, or for the interface of a dummy procedure. It is also not allowed for an abstract interface (ABSTRACT keyword on the INTERFACE statement).

＜Semantics＞

The BIND attribute specifies that the entity interoperates with C.

If NAME= appears, the character constant expression specifies the C name of the entity; this is either a C global variable or a C “extern” procedure. If the procedure is an internal or dummy procedure, or an abstract interface, it has no C name; otherwise, if NAME= does not appear, the C name is the lowercase name of the Fortran entity. If NAME= appears but the character constant expression is blank, the Fortran entity does not have a C name.

Note that for a procedure or common block with a C name, whether specified by NAME= or by default, the global identifier of that entity is the C name; the Fortran name is merely a local identifier. (Prior to Fortran 2008, the Fortran name of an external procedure or common block was also considered to be a global identifier.)

＜Semantics (variables and common blocks)＞

A variable with the BIND attribute interoperates with a C global variable. The variable must be “interoperable”; this means that it must not have the ALLOCATABLE or POINTER attribute, if it is of intrinsic type it must have interoperable kind, and if it is of derived type the type must be interoperable. Named constants for interoperable intrinsic kinds are found in the ISO_C_BINDING module. User-defined types with the BIND attribute are interoperable, as are the special derived types C_PTR and C_FUNPTR which are found in the ISO_C_BINDING module.

A common block with the BIND attribute interoperates with a C global variable that is a “structure”; this is functionally equivalent to defining a type with the common block elements as its components, and having a variable of that type. This feature is error-prone and its use is not recommended.

＜Semantics (procedures)＞

In the case of a procedure, the use of the BIND attribute on a subprogram heading or ENTRY statement defines a Fortran procedure that is accessible from C. The use of the BIND attribute on a FUNCTION or SUBROUTINE statement that begins an interface body declares, in the absence of a matching Fortran procedure, a C procedure that can be accessed from Fortran.

A procedure with the BIND attribute must

  • be a subroutine or a scalar function of interoperable type and kind, and
  • have all of its dummy arguments interoperable.

A dummy argument is interoperable if it is of interoperable type, does not have the ALLOCATABLE or POINTER attributes, and is either scalar or an explicit-shape or assumed-size array.

＜Semantics (derived types)＞

In the case of a derived type, the components must all be of interoperable type and kind, and must not be pointers or allocatable. No type-bound procedure part is allowed in the type definition.

The SEQUENCE attribute is not allowed, but types with the BIND attribute act like sequence types in every other way (in particular, they follow the same rules for type matching).

＜Related＞

Attributes, Derived Type Definition, FUNCTION statement, SUBROUTINE statement, TYPE statement, Type Declaration statement


BIT_SIZE intrinsic function

Standard: F77 F90 F95 F2003 F2008 F2018 Example program

＜Syntax＞

BIT_SIZE ( I )

I : Integer;
Result : Integer (default kind).

＜Semantics＞

This function returns the number of bits in integers with the same kind type parameter as I. This means the number of bits that may be used in the bit manipulation functions IAND, IEOR, et al.; in theory this might differ from the number of bits the integer takes in storage, but in practice it is the same.

This is an inquiry function, so I need not be defined; indeed, it is permitted to be disassociated, unallocated, or absent.

＜Related＞

DIGITS intrinsic function, INTEGER type


BLE intrinsic function

Standard: F77 F90 F95 F2003 F2008 F2018 Example program

＜Syntax＞

BLE ( I, J )

I : Integer;
J : Integer, same kind as I, conformable with I;

Result : Logical.

＜Semantics＞

This function does a bitwise comparison between two integers; the value of the result is .TRUE. if I is less than or equal to J when treated as unsigned integers. This is an elemental function, so if either or both of I or J is an array, the result has the same shape as the operand array(s), with the operation being applied elementwise.

＜Related＞

BGE intrinsic function, BGT intrinsic function, BLT intrinsic function


BLOCK construct

Standard: F77 F90 F95 F2003 F2008 F2018 Example program

＜Syntax＞

block-stmt
[ specification-part ]
block
end-block-stmt

Syntax of the BLOCK statement

[ construct-name : ] BLOCK

If the BLOCK statement has a construct name construct-name, the END BLOCK statement shall have the same construct name.

＜Semantics＞

The BLOCK construct allows declarations of entities within executable code; local entities declared in the specification-part of a BLOCK construct are local to its block. A BLOCK construct accesses entities from the surrounding context by host association, so any host entity with the same name as an entity local to the BLOCK construct is inaccessible by that name. BLOCK constructs may be nested.

The specification-part of a BLOCK construct is not permitted to contain a COMMON, EQUIVALENCE, IMPLICIT, INTENT, NAMELIST, OPTIONAL or VALUE statement, and is not permitted to define a statement function. The SAVE statement is permitted in a BLOCK construct, but must have a list of entities that are to be saved.

Note that as in other host or use association contexts, the ASYNCHRONOUS and VOLATILE statements do not necessarily create a new local entity but can be used to add the attribute to an accessible host entity.

A BLOCK construct may contain a USE statement or a declaration of an external or intrinsic procedure; this allows access to “global” entities within the BLOCK without affecting the surrounding program unit.

When execution of a BLOCK construct is completed, e.g. by executing the END BLOCK construct or branching out of the block, all its local variables that do not have the SAVE attribute cease to exist. In particular, an allocated ALLOCATABLE variable will be automatically deallocated, and a variable that is finalisable will be finalised.

The BLOCK construct is particularly useful when code is included by the INCLUDE line or by macro preprocessing, as it can be used to ensure that any temporary variables needed do not interfere with entities in the including subprogram.

＜Related＞

END BLOCK statement


BLOCK DATA subprogram

Standard: F77 F90 F95 F2003 F2008 F2018 Example program

＜Syntax＞

BLOCK DATA [ blockdata-name ]
[ specification-part ]
END [ BLOCK DATA [ blockdata-name ] ]

The blank between BLOCK and DATA is optional. The blanks in END BLOCK DATA are optional.

The BLOCK DATA subprogram is considered obsolescent in Fortran 2018.

＜Semantics＞

A BLOCK DATA subprogram supplies initial values for variables in COMMON blocks. It has no other effect. Only one unnamed BLOCK DATA subprogram is allowed.

We recommend that BLOCK DATA and COMMON be avoided, and that MODULEs be used instead.

＜Related＞

COMMON statement


BLT intrinsic function

Standard: F77 F90 F95 F2003 F2008 F2018 Example program

＜Syntax＞

BLT ( I, J )

I : Integer;
J : Integer, same kind as I, conformable with I;

Result : Logical.

＜Semantics＞

This function does a bitwise comparison between two integers; the value of the result is .TRUE. if I is less than J when treated as unsigned integers. This is an elemental function, so if either or both of I or J is an array, the result has the same shape as the operand array(s), with the operation being applied elementwise.

＜Related＞

BGE intrinsic function, BGT intrinsic function, BLE intrinsic function


BTEST intrinsic function

Standard: F77 F90 F95 F2003 F2008 F2018 Example program

＜Syntax＞

BTEST ( I, POS )

I : Integer;
POS : Integer, conformable with I, 0≤POS<BIT_SIZE(I);

Result : Logical (default kind).

＜Semantics＞

The result is .TRUE. if bit POS in I is set to one, and .FALSE. otherwise; the least significant bit (value 1) is bit 0, the most significant bit is bit BIT_SIZE(I)−1.

This is an elemental function; if any argument is an array the result is an array of the same shape, with the BTEST operation being applied elementwise.

＜Related＞

BIT_SIZE intrinsic function, IBCLR intrinsic function, IBSET intrinsic function


CALL statement

Standard: (F77) F90 F95 F2003 F2008 F2018 Example program

＜Syntax＞

CALL proc-designator [ ( [ actual-arg-list ] ) ]

proc-designator | ::= | subroutine-name
 | | | procedure-pointer-name
 | | | variable % proc-component-name
 | | | object % type-bound-procedure-name

actual-arg-list ::= actual-arg [ , actual-arg ]...

actual-arg | ::= | [ dummy-name = ] variable
 | | | [ dummy-name = ] expression
 | | | * label

＜Semantics＞

Calls the named subroutine. All the expressions in the actual argument list are evaluated before the call.

Keyword arguments (with “dummy-name=”) are only allowed for internal, intrinsic and module subroutines, and for subroutines declared with an INTERFACE block. After a keyword argument, all remaining arguments must also be keyword arguments. Keyword arguments were not available in Fortran 77.

The alternate return (“* label”) is considered to be obsolescent.

Fortran 2003 added procedure pointers. A named procedure pointer can be associated with different procedures at different times by using pointer assignment. An object-bound procedure is a procedure pointer component; like named procedure pointers, these are manipulated by pointer assignment.

Fortran 2003 also added type-bound procedures, declared in a type definition. If an object is polymorphic, the particular specific procedure invoked depends on the dynamic type of the object. Thus, both type-bound and object-bound procedures are invoked via an object, but the dynamic dispatch mechanism is via the dynamic type's definition for a type-bound procedure, and via the pointer for an object-bound procedure.

＜Related＞

Derived-type definition, ENTRY statement, INTENT attribute, INTERFACE statement, OPTIONAL attribute, RETURN statement, SUBROUTINE statement


CASE statement

Standard: F77 F90 F95 F2003 F2008 F2018 Example program

＜Syntax＞

CASE ( value [ ,value ]... ) [ construct-name ]

value | ::= | expression
 | | | : expression
 | | | expression :
 | | | expression : expression

All expressions must be scalar, and of type Integer, Real, Logical or Character. The construct-name shall appear if and only if the SELECT CASE statement is named.

＜Semantics＞

The CASE statement marks the beginning of a CASE part (and the end of any preceding CASE part). Statements in this part are executed if and only if the corresponding selector in the SELECT CASE statement satisfies the appropriate case condition:

(expression) | selector = expression
(:expression) | selector ≤ expression
(expression) | selector ≥ expression
(expression1:expression2) | expression1 ≤ selector ≤ expression2

＜Related＞

SELECT CASE construct, CASE DEFAULT statement, END SELECT statement, SELECT CASE statement


CASE DEFAULT statement

Standard: F77 F90 F95 F2003 F2008 F2018 Example program

＜Syntax＞

CASE DEFAULT [ construct-name ]

The construct-name shall appear if and only if the SELECT CASE statement is named.

＜Semantics＞

Marks the beginning of a CASE DEFAULT part (and the end of any preceding CASE part). Statements in this part are executed if and only if the corresponding SELECT expression does not satisfy any of the other CASE conditions in the construct.

＜Related＞

CASE construct, CASE statement, END SELECT statement, SELECT CASE statement


CEILING intrinsic function

Standard: F77 F90 F95 F2003 F2008 F2018 Example program

＜Syntax＞

CEILING ( A [ , KIND ] )

A : Real;
KIND : scalar Integer constant expression;

Result : Integer or Integer(Kind=KIND).

＜Semantics＞

The value of the result is the smallest integer greater than or equal to A. Like many intrinsic functions, this is elemental; the result has the same shape as A, with the operation being applied elementwise.

＜Related＞

AINT intrinsic function, ANINT intrinsic function, FLOOR intrinsic function, INT intrinsic function, NINT intrinsic function


CHANGE TEAM construct

Standard: F77 F90 F95 F2003 F2008 F2018 Example program

＜Syntax＞

[ construct-name : ] CHANGE TEAM ( team-value [ , coarray-association ]... [ , sync-stat ]... )
[ executable-construct ]...
END TEAM [ construct-name ]

The END TEAM statement may have a construct name only if the same name appears on the CHANGE TEAM statement.

Transfer of control out of the construct, e.g. by a RETURN or GOTO statement is prohibited.

team-value ::= scalar-expr
A team-value must be of type TEAM_TYPE from the intrinsic module ISO_FORTRAN_ENV.

sync-stat ::= STAT = stat-variable | ERRMSG = errmsg-variable
At most one STAT= and ERRMSG= specifier may appear in a CHANGE TEAM statement. The stat-variable must be a non-coindexed scalar integer variable (and at least 16 bits), and errmsg-variable must be a scalar default character variable.

coarray-association :: = local-coarray-name [ explicit-coshape-spec ] => outer-coarray-name

＜Semantics＞

Executing the CHANGE TEAM statement changes the current team (of images) to team-value, which must identify a subteam of the previously-current team; all images of this new team are implicitly synchronised, and all active images of the new team must execute the same CHANGE TEAM statement at this time.

If the STAT= specifier appears, the stat-variable is assigned the value zero for successful execution, and a positive value if an error occurs. If an error occurs and no STAT= specifier appears, the program is error-terminated.

If both STAT= and ERRMSG= appear and an error occurs, errmsg-variable is assigned an explanatory error message; otherwise, errmsg-variable is unchanged.

The setting of the current team remains in effect during procedure calls, so any procedure referenced by the construct will also be executed with the new team current.

The construct may be exited only by executing its END TEAM statement, or by executing an EXIT statement that belongs to the construct.

While executing a CHANGE TEAM construct, image selectors operate using the new team's image indices, the intrinsic functions NUM_IMAGES and THIS_IMAGES return the data for the new team, and SYNC ALL synchronises the new team only. The SYNC TEAM statement can be used to synchronise the parent team.

If one of the images in the new team has failed, e.g. by executing a FAIL IMAGE statement, the STAT_FAILED_IMAGE error is raised (this named constant is in the intrinsic module ISO_FORTRAN_ENV). If no STAT= specifier appears, the program is error-terminated; otherwise, the CHANGE TEAM construct is executed as if it were successful (including setting the current team and the implicit synchronisations), apart from the value assigned to the stat-variable.

If any other error occurs, the behaviour is undefined; a non-zero error code might (or might not) be assigned to stat-variable, the current team might be changed, the new team might be synchronised, or the program might be error-terminated. Any stat-variable value other than zero (for success) or STAT_FAILED_IMAGE (for image failure) should be treated by the program as fatal.

Coarray association within a CHANGE TEAM construct is more complicated (but less capable) than argument association, and is thus an advanced concept that should only be attempted by experienced programmers. It establishes local-coarray-name, with cobounds specified by explicit-coshape-spec, to be an alias for remote-coarray-name within the construct.

＜Related＞

CODIMENSION attribute, END TEAM statement, ERRMSG= specifier, FAIL IMAGE statement, FORM TEAM statement, Image control statements, STAT= specifier, SYNC ALL statement, SYNC TEAM statement


CHAR intrinsic function

Standard: F77 F90 F95 F2003 F2008 F2018 Example program

＜Syntax＞

CHAR ( I [ , KIND ] )

I : Integer;
KIND : scalar Integer constant expression;

Result : Character(Len=1) or Character(Len=1,Kind=KIND).

＜Semantics＞

Convert character code to Character type; this is the inverse of the ICHAR intrinsic function. Like many intrinsic functions, this is elemental; the result has the same shape as I, with the operation being applied elementwise.

＜Related＞

ACHAR intrinsic function, CHARACTER type, IACHAR intrinsic function, ICHAR intrinsic function, SELECTED_CHAR_KIND intrinsic function


CHARACTER type

Standard: F77 F90 F95 F2003 F2008 F2018 Example program

＜Syntax＞

CHARACTER [ char-spec ]

char-spec | ::= | * int-literal-constant
 | | | * ( char-len )
 | | | ( char-len [ , [ KIND= ] expr )
 | | | ( LEN=char-len [ , KIND=expr ] )
 | | | ( KIND=expr [ , LEN=char-len ] )

char-len ::= * | expr | :

＜Semantics＞

CHARACTER declares entities (variables, functions, etc.) to be character strings. The length of the character string is given by the int-literal-constant or char-len. If no length is specified, the length of the string is 1 character.

A char-len of “*” is allowed for a PARAMETER or a dummy argument; the length of the PARAMETER is taken from the value given for it, and the length of the dummy argument is taken from the actual argument at runtime.

A char-len of “:” is allowed for an entity with the ALLOCATABLE or POINTER attribute; this is called “deferred character length” and the actual length is determined at runtime by allocation or association.

Furthermore, assignment to a whole allocatable variable that has deferred character length will reallocate the variable to have the same character length as the right-hand-side of the assignment if either the variable was unallocated or if the length was different. This provides a true variable-length character facility. The “automatic reallocation” can be suppressed by using substring (or for an array, array section) notation if it is not desired.

There are four kinds of CHARACTER as follows:

KIND | SELECTED_CHAR_KIND | F90_KIND constant | Description
1 | 'ASCII' | ASCII | Single byte character
2 | 'JIS_0213' | JIS | 16-bit Japanese character
3 | 'UCS_2' | UCS2 | 16-bit Unicode character
4 | 'ISO_10646' | UCS4 | 32-bit Unicode character

Note that the KIND column is for sequential or byte kinds (-kind=sequential and -kind=byte options); the values are completely different for the -kind=unique option.

The default if no kind is specified is single byte character (ASCII).

Note that for CHARACTER literal constants, the kind specification precedes the value (unlike other types where it follows the value). For example, using the named constant in the F90_KIND module,
JIS_"月"
has the same value as
CHAR(35982,JIS)

The length in the CHARACTER clause may be overridden by putting “*int-literal-constant” or “*(char-len)” after the name of the entity in the declaration; for example,
Character(17) :: a, b*3, c
declares A and C to have length 17 and B to have length 3.

＜Related＞

ACHAR intrinsic function, ALLOCATABLE attribute, CHAR intrinsic function, COMPLEX type, DOUBLE PRECISION type, IACHAR intrinsic function, ICHAR intrinsic function, IMPLICIT statement, INTEGER type, KIND intrinsic function, LEN intrinsic function, LOGICAL type, POINTER attribute, REAL type, SELECTED_CHAR_KIND intrinsic function, Type Declaration statement


CLASS specifier

Standard: F77 F90 F95 F2003 F2008 F2018 Example program

＜Syntax＞

CLASS ( derived-type-name )
CLASS ( * )

An entity declared with the CLASS specifier must be a dummy argument, a pointer, or allocatable.

＜Semantics＞

The CLASS specifier with a type name declares an entity to be polymorphic, with the declared type of the derived-type-name; this must be the name of an extensible type (i.e. not a SEQUENCE or BIND(C) type).

The dynamic type of a polymorphic entity may vary at runtime.

  • The dynamic type of a pointer is that of its target, so it can change via pointer assignment or allocation.
  • The dynamic type of an allocatable variable is determined when it is allocated.
  • The dynamic type of a dummy argument is that of the associated actual argument.

The dynamic type of a polymorphic variable can be tested using the SELECT TYPE construct. Outside of a SELECT TYPE construct, only components of the declared type can be accessed directly.

The CLASS ( * ) specifier declares an “unlimited polymorphic” entity. Such an entity can take on any type at all at runtime, including intrinsic types and non-extensible derived types.

The intrinsic types are allowed in TYPE IS statements, however non-extensible derived types are not permitted in TYPE IS or CLASS IS. Instead, an unsafe pointer assignment is permitted from a non-extensible derived type pointer to a CLASS (*) target; it is the user's responsibility to keep track of the actual type in the case of non-extensible types and to ensure that only correct pointer assignments are done.

＜Related＞

CLASS DEFAULT statement, CLASS IS statement, Derived Type definition, EXTENDS clause, EXTENDS_TYPE_OF intrinsic function, SAME_TYPE_AS intrinsic function, SELECT TYPE statement, TYPE statement, Type Declaration statement, TYPE IS statement


CLASS DEFAULT statement

Standard: F77 F90 F95 F2003 F2008 F2018

＜Syntax＞

CLASS DEFAULT [ construct-name ]

This statement is part of the SELECT TYPE construct. The construct-name must appear if and only if the SELECT TYPE statement is named, and must be the same.

＜Semantics＞

The CLASS DEFAULT statement marks the beginning of the CLASS DEFAULT block in a SELECT TYPE construct. This block is executed if and only if no other block in the SELECT TYPE is chosen to be executed.

Within the CLASS DEFAULT block, the associate-name of the SELECT TYPE statement is polymorphic, and has the same declared type as the selector.

＜Related＞

CLASS specifier, CLASS IS statement, SELECT TYPE construct, TYPE statement, TYPE IS statement


CLASS IS statement

Standard: F77 F90 F95 F2003 F2008 F2018

＜Syntax＞

CLASS IS (type-specifier) [ construct-name ]

The type-specifier must specify an extensible type. If the type has length type parameters, they must be assumed (specified as “*”).

This statement is part of the SELECT TYPE construct. The construct-name must appear if and only if the SELECT TYPE statement is named, and must be the same.

＜Semantics＞

The CLASS IS statement marks the beginning of a CLASS IS block in a SELECT TYPE construct. This block is executed if the dynamic type of the selector is the same as, or an extension of, the named derived type, and if it is the most specific condition which is satisfied. That is, it is not executed if the dynamic type matches one of the TYPE IS blocks, or matches a CLASS IS block which specifies a type that is an extension of this block's type.

Within a CLASS IS block, the associate-name of the SELECT TYPE statement is polymorphic, and has the declared type of type-name.

＜Related＞

CLASS specifier, CLASS DEFAULT statement, SELECT TYPE construct, TYPE statement, TYPE IS statement


CLOSE statement

Standard: F77 F90 F95 F2003 F2008 F2018 Example program

＜Syntax＞

CLOSE ( close-spec-list )

close-spec-list ::= close-spec [ , close-spec ]...

The close specifiers (close-spec) are as follows.

CLOSE specifier | Meaning | Syntax | Acceptable Values
UNIT | The external unit number to close | [ UNIT= ] expression | Scalar non-negative integer
STATUS | Whether to keep or delete the file | STATUS= expression | 'KEEP' or 'DELETE'
ERR | Branch on error | ERR= label |
IOMSG | Return i/o error message | IOMSG= variable | Scalar default character
IOSTAT | Return i/o status code | IOSTAT= variable | Scalar integer

＜Semantics＞

Closes a unit connected to an external file. If STATUS= is omitted, the default is 'KEEP' for normal files and 'DELETE' for scratch files (files opened with STATUS='SCRATCH'); a scratch file cannot be kept.

Closing a unit that is not connected is permitted and has no effect.

The IOMSG= specifier was added in Fortran 2003; this sets a character string variable to an error message if an error occurs. The ERR= or IOSTAT= specifier is still needed to prevent termination on error.

＜Related＞

BACKSPACE statement, ENDFILE statement, ERR= specifier, IOMSG= specifier, IOSTAT= specifier, OPEN statement, PRINT statement, READ statement, REWIND statement, UNIT= specifier, WRITE statement


CMPLX intrinsic function

Standard: F77 F90 F95 F2003 F2008 F2018 Example program

＜Syntax＞

CMPLX ( X [ , Y , KIND ] )
CMPLX ( X [ , KIND ] )

X : Integer, Real, Complex or a BOZ literal constant;
Y : Integer, Real or a BOZ literal constant, conformable with X;
KIND : scalar Integer constant expression;

Result : Complex, or Complex(Kind=KIND).

If X is of type Complex, Y must not appear. If X is of type Complex, the KIND argument may appear as the second positional argument.

＜Semantics＞

When X is Complex this function produces a complex value approximating X in the kind of the result (i.e. it changes the kind of the complex value).

When X is not Complex it specifies the real part of the result, and Y specifies the imaginary part; if Y is not present, the imaginary part is zero. Note that X and Y are permitted to be of different types or kinds.

If X or Y is a BOZ literal constant it is interpreted as the internal representation (as a bitstring) of that part of the result. Note that this bitstring must not be longer that the number of bits in the real or imaginary part, unless the excess bits are all leading zeroes. If the bitstring is shorter than the number of bits in the real or imaginary part, it is padded on the left with leading zeroes.

Like many intrinsic functions, this is elemental; if either (or both) of X and Y is an array, the result will be an array with that shape, with the value being computed elementwise.

＜Related＞

AIMAG intrinsic function, COMPLEX type, REAL intrinsic function


CODIMENSION attribute

Standard: F77 F90 F95 F2003 F2008 Example program

＜Syntax＞

type, CODIMENSION ‘[’ coarray-spec ‘]’ [ , attr-spec ]... :: decl-list
(The notation ‘[’ and ‘]’ means the actual square bracket characters, i.e. not treating them as BNF optionality brackets.)

CODIMENSION [ :: ] name ‘[’ coarray-spec ‘]’ [ , name ‘[’ coarray-spec ‘]’ ]...

coarray-spec ::= explicit-coshape-spec | deferred-coshape-spec

explicit-coshape-spec ::= [ [ lower-cobound : ] upper-cobound , ]... lower-cobound : *
lower-cobound ::= expression
upper-cobound ::= expression
The cobound expressions must be scalar Integer expressions.

deferred-coshape-spec ::= [ : , ]... :

＜Semantics＞

The CODIMENSION attribute declares coarrays. A coarray with an explicit-coshape-spec must be a dummy argument or a variable with the SAVE attribute. A coarray with a deferred-coshape-spec must have the ALLOCATABLE attribute; it can be a variable or a component, but not a function result. A coarray cannot be a pointer, and is not allowed to be of type C_PTR or C_FUNPTR from the intrinsic module ISO_C_BINDING.

A variable with a coarray ultimate component must be a dummy argument or have the SAVE attribute. A variable or component that has a coarray ultimate component must be scalar, must not be a pointer or allocatable, and must not itself be a coarray.

The maximum corank of a coarray is 15 minus its rank according to the Fortran standard; the NAG Fortran Compiler supports a maximum corank of 31 minus its rank.

The CODIMENSION attribute can also be specified by putting a coarray-spec in square brackets after the entity name in a type declaration or component definition statement; this overrides any CODIMENSION clause that might be present.

＜Execution semantics＞

In a coarray program with multiple images, each image has its own separate copy of all variables. Coarray variables however can be accessed directly from another image.

To access another image's copy of a coarray, cosubscripts are used following the coarray name in square brackets; this is called “coindexing”, and such an object is a “coindexed object”. For example, given the declaration REAL,SAVE :: e[*], the coindexed object e[1] refers to the copy of E on image one, and e[13] refers to the copy of E on image 13.

When a coarray is an array, you cannot put the cosubscripts directly after the array name, but must use array section notation instead. For example, with REAL,SAVE :: g(10,10)[*], the reference g[inum] is invalid, to refer to the whole array G on image INUM you need to use g(:,:)[inum] instead.

Writing to a coarray from one image while reading (or writing) from another image is only permitted in “ordered” execution segments. Image control statements provide mechanisms for defining execution segments and synchronising them between images.

＜Related＞

Component Definition statement, Image control statements, Image selectors, LCOBOUND intrinsic function, Type Declaration statement, UCOBOUND intrinsic function,


COMMAND_ARGUMENT_COUNT intrinsic function

Standard: F77 F90 F95 F2003 F2008 F2018 Example program

＜Syntax＞

COMMAND_ARGUMENT_COUNT ( )

Result : scalar Integer.

＜Semantics＞

The result is the number of arguments on the command line for the current program execution, not counting the program name.

＜Related＞

GET_COMMAND intrinsic subroutine, GET_COMMAND_ARGUMENT intrinsic subroutine


COMMON statement

Standard: F77 F90 F95 F2003 F2008 F2018

＜Syntax＞

COMMON [ cblock ] objlist [ [ , ] cblock objlist ]...

cblock ::= / [ common-block-name ] /
objlist ::= object [ , object ]...
object ::= variable-name [ ( array-spec ) ]

＜Semantics＞

The COMMON statement declares one or more common blocks. One common block may be unnamed ("blank common"), all the others must have names. Multiple COMMON statements for a single common block are interpreted by concatenating the lists of variables.

A common block is a global entity; a common block cannot have the same name as an external procedure. A named common block must be declared to have the same size in every subprogram that uses it.

A common block can be given the BIND attribute; in this case it interoperates with an extern C structure whose members are compatible with the variables in the common block. This works as if the common block were a BIND(C) derived-type variable.

Because the use of common blocks is very error-prone, it is recommended to use MODULEs instead.

COMMON is considered obsolescent in Fortran 2018.

＜Related＞

BIND attribute, BLOCK DATA subprogram, MODULE statement


ISO_FORTRAN_ENV function COMPILER_OPTIONS

Standard: F77 F90 F95 F2003 F2008 F2018 Example program

＜Syntax＞

USE ISO_FORTRAN_ENV, ONLY:COMPILER_OPTIONS

COMPILER_OPTIONS ( )

Result : Scalar default character string.

＜Semantics＞

COMPILER_OPTIONS is a module function in the intrinsic module ISO_FORTRAN_ENV, which returns a string identifying the compiler options used to compile the source code. The function can be used in a constant expression, e.g. to initialise a variable with the compiler option information.

＜Related＞

ISO_FORTRAN_ENV function COMPILER_VERSION


ISO_FORTRAN_ENV function COMPILER_VERSION

Standard: F77 F90 F95 F2003 F2008 F2018 Example program

＜Syntax＞

USE ISO_FORTRAN_ENV, ONLY:COMPILER_VERSION

COMPILER_VERSION ( )

Result : Scalar default character string.

＜Semantics＞

COMPILER_VERSION is a module function in the intrinsic module ISO_FORTRAN_ENV, which returns a string identifying the version of the compiler used to compile the source code. The function can be used in a constant expression, e.g. to initialise a variable with the compiler version information.

＜Related＞

ISO_FORTRAN_ENV function COMPILER_OPTIONS


COMPLEX type

Standard: (F77) F90 F95 F2003 F2008 F2018 Example program

＜Syntax＞

COMPLEX [ ( [ KIND= ] expression ) ]

The expression must be a scalar integer whose value identifies a valid kind of real.

COMPLEX*4
COMPLEX*8
COMPLEX*16
COMPLEX*32
DOUBLE COMPLEX

＜Semantics＞

COMPLEX declares entities (variables, functions, etc.) to be complex numbers; a complex value has a real part and an imaginary part. The KIND number is the same as for Real type, and determines the precision of each of the real and imaginary parts. The F90_KIND module contains named constants REAL16, REAL32, REAL64 and REAL128 which are convenient for specifying 16-bit, 32-bit, 64-bit and 128-bit floating point; these are also available in the standard intrinsic module ISO_FORTRAN_ENV. If no KIND is specified, the default is single precision.

COMPLEX*4 is a synonym for COMPLEX(REAL16), COMPLEX*8 is a synonym for COMPLEX(REAL32), COMPLEX*16 is a synonym for COMPLEX(REAL64), and COMPLEX*32 is a synonym for COMPLEX(REAL128). DOUBLE COMPLEX is a synonym for COMPLEX(KIND(0d0)). These synonyms are not standard Fortran; we recommend avoiding them.

The SELECTED_REAL_KIND intrinsic function can be used to select a real kind based on decimal precision and exponent range requirements. The IEEE_SELECTED_REAL_KIND function in the standard intrinsic module IEEE_ARITHMETIC can also be used to select an ISO/IEC/IEEE 60559 conformant real kind.

＜Related＞

AIMAG intrinsic function, CHARACTER type, CMPLX intrinsic function, COMPLEX type, Component Definition statement, DIGITS intrinsic function, DOUBLE COMPLEX type specifier, IMPLICIT statement, KIND intrinsic function, LOGICAL type, REAL intrinsic function, REAL type, SELECTED_REAL_KIND intrinsic function, Type Declaration statement


Component definition statement

Standard: F77 F90 F95 F2003 F2008 Example program

＜Syntax＞

A component definition statement is either a data component definition or a procedure component definition.

data-component-def-stmt ::= type [ [ , attr ]... :: ] entity-decl-list

attr | ::= | ALLOCATABLE
 | | | CODIMENSION '[' coarray-spec ']'
 | | | CONTIGUOUS
 | | | DIMENSION ( array-spec )
 | | | POINTER
 | | | PRIVATE
 | | | PUBLIC

proc-component-def-stmt ::= PROCEDURE ( [ interface ] ) , proc-component-attr-list :: proc-component-decl-list

If ALLOCATABLE or POINTER is specified for a data component, any array-spec must be deferred-shape; otherwise any array-spec must be explicit-shape and have constant bounds.

The PUBLIC and PRIVATE attributes are only permitted in the specification part of a module.

A procedure component definition specifies an object-bound procedure; refer to that page for full syntax and semantics.

The notation '[' and ']' in the CODIMENSION attribute means the actual square bracket characters appear in the program, i.e. they are not BNF optionality brackets. The CODIMENSION attribute is only allowed in conjunction with ALLOCATABLE, and therefore the coarray-spec must be a deferred-coshape-spec.

＜Semantics＞

This statement declares one or more components of a derived type. If an entity-decl contains an initialisation (“= expression” or “=> NULL()”), it defines the default value for that component; this is called default initialisation. Default initialisation is applied whenever an object of the type is created, and for INTENT(OUT) arguments. Default initialisation also allows the value for such a component to be omitted in the structure constructor; the result of the constructor will have the default value for that component.

In Fortran 2003, a component may be explicitly declared to be PUBLIC or PRIVATE; otherwise, a component is PRIVATE if the component definition statements are preceded by a PRIVATE statement, and PUBLIC otherwise. A PRIVATE component cannot be accessed from outside the module that defines the type.

In Fortran 2008, an array pointer component can be declared to be contiguous. Such a pointer is only permitted to be associated with a contiguous target.

＜Related＞

ALLOCATABLE attribute, Attributes, CODIMENSION attribute, CONTIGUOUS attribute, Derived Type Definition, DIMENSION attribute, END TYPE statement, Entity declaration list, Object-bound procedure, POINTER attribute, PRIVATE attribute, PUBLIC attribute, TYPE statement


Concatenation (//) operator

Standard: F77 F90 F95 F2003 F2008 F2018 Example program

＜Syntax＞

expression // expression

This operator has higher precedence than all relational, logical, and binary user-defined operators, and lower precedence than the numeric and unary user-defined operators.

＜Semantics＞

Concatenation of two character expressions. The character expressions must both have the same kind, and the result is that kind. The length of the result is the sum of the lengths of the expressions.

＜Related＞

.AND. operator, .EQ. (==) operator, .EQV. operator, .GE. (>=) operator, .GT. (>) operator, .LE. (<=) operator, .LT. (<) operator, .NE. (/=) operator, .NEQV. operator, .NOT. operator, Numeric operators, Operator precedence, .OR. operator, REPEAT intrinsic function


CONJG intrinsic function

Standard: F77 F90 F95 F2003 F2008 F2018 Example program

＜Syntax＞

CONJG ( Z )

Z : Complex;

Result : Same type and kind as Z.

＜Semantics＞

The result is the complex value whose real part is the same as Z, and the imaginary part is the negative of that of Z, i.e. CMPLX(REAL(Z),-AIMAG(Z),KIND(Z)).

Like many intrinsic functions, this is elemental; the result has the same shape as Z, with the operation being applied elementwise.

＜Related＞

COMPLEX type


CONTAINS statement

Standard: F77 F90 F95 F2003 F2008 F2018 Example program

＜Syntax＞

CONTAINS

A CONTAINS statement may appear as follows.

  • In a module:
    MODULE module-name
    module-declaration-part
    CONTAINS
    module-procedure-part
    end-module-stmt
  • In a main program:
    [ PROGRAM program-name ]
    specification-part
    executable-part
    CONTAINS
    internal-procedure-part
    end-program-stmt
  • In an external subroutine or module subroutine:
    subroutine-stmt
    specification-part
    executable-part
    CONTAINS
    internal-procedure-part
    end-subroutine-stmt
  • In an external function or module function:
    function-stmt
    specification-part
    executable-part
    CONTAINS
    internal-procedure-part
    end-function-stmt
  • In a type definition:
    type-definition-stmt
    [ component-definition-stmt ]...
    CONTAINS
    type-bound-procedure-part
    end-type-stmt

＜Semantics＞

The CONTAINS statement separates:

  • the declarations of a module from its module procedures;
  • the declarations and executable statements of a main program or subprogram from its internal procedures;
  • the components of a derived type from its type-bound procedures.

＜Related＞

CALL statement, Derived Type Definition, END FUNCTION statement, END MODULE statement, END PROGRAM statement, END SUBROUTINE statement, ENTRY statement, FUNCTION statement, MODULE statement, PROGRAM statement, RETURN statement, SUBROUTINE statement


CONTIGUOUS attribute

Standard: F77 F90 F95 F2003 F2008 F2018 Example program

＜Syntax＞

type-spec, CONTIGUOUS [ , attr-spec ]... :: entity-decl-list

CONTIGUOUS [ :: ] name [ , name ]...

Each name must be the name of an array pointer or an assumed-shape array.

＜Semantics＞

The CONTIGUOUS attribute specifies that an array pointer can only become associated with a contiguous array target, or that an assumed-shape dummy array is contiguous.

In the case of an array pointer, it is an error to attempt to pointer-assign a discontiguous target to the pointer. In the case of a dummy array, the actual argument is permitted to be discontiguous, and in this case the dummy array will be a contiguous copy of the original (if the dummy is not INTENT(OUT), a copy will be made on entry, whereas if the dummy is INTENT(OUT), no copy will be made on entry but the dummy will be copied to the actual argument on exit).

If a dummy argument has the CONTIGUOUS attribute, the procedure must be referenced with an explicit interface (if it is a dummy procedure or external procedure, that means it needs an interface block).

＜Related＞

DIMENSION attribute, Pointer assignment statement, POINTER attribute, Type Declaration statement


CONTINUE statement

Standard: F77 F90 F95 F2003 F2008 F2018 Example program

＜Syntax＞

CONTINUE

＜Semantics＞

This is an executable statement that has no effect. If it has a label it may be branched to or used as the terminating statement of a DO loop. (This latter use is redundant in Fortran 90 and later.)

＜Related＞

CYCLE statement, DO construct, DO WHILE statement, END DO statement, END= specifier, EOR= specifier, ERR= specifier, EXIT statement, GO TO statement


CONVERT= specifier

Standard: F77 F90 F95 F2003 F2008 F2018 Example program

＜Syntax＞

CONVERT = expression

The expression must be a scalar default character expression. It is permitted in the INQUIRE and OPEN statements. In the INQUIRE statement, it must be a variable designator, and is assigned the conversion mode of the connection or 'UNDEFINED'; in the OPEN statement it must evaluate to one of the allowed values (ignoring case).

This specifier is a non-standard extension.

＜Semantics＞

The CONVERT= specifier is only permitted in an OPEN statement that refers to an unformatted file, and specifies the conversions to be applied when reading or writing that file. This is useful when the unformatted file was generated on a system with different endianness or a different floating-point format. The possible values for CONVERT= are:

'BIG_ENDIAN'
Same as 'BIG_IEEE';
'BIG_IEEE'
Big-endian IEEE (including 128-bit quad precision);
'BIG_IEEE_DD'
Big-endian IEEE (but quad precision is double-double);
'BIG_NATIVE'
Big-endian with native floating-point;
'LITTLE_ENDIAN'
Same as 'LITTLE_IEEE';
'LITTLE_IEEE'
Little-endian IEEE (including 128-bit quad precision);
'LITTLE_IEEE_DD'
Little-endian IEEE (but quad precision is double-double);
'LITTLE_NATIVE'
Little-endian with native floating-point;
'NATIVE'
No conversion.

The default conversion mode is 'NATIVE'.

In an INQUIRE statement, the value assigned is 'UNDEFINED' if the file is connected for formatted input/output or if there is no connection.

＜Related＞

INQUIRE statement, OPEN statement


COS intrinsic function

Standard: F77 F90 F95 F2003 F2008 F2018 Example program

＜Syntax＞

COS ( X )

X : Real or Complex;

Result : Same type and kind as X.

＜Semantics＞

The value of the result is an approximation to the cosine of X. Like many intrinsic functions, this is elemental; the result has the same shape as X, with the operation being applied elementwise.

If X is of type Real, it specifies the angle in radians. If X is of type Complex, the real part is interpreted as radians.

＜Related＞

ACOS intrinsic function, COSH intrinsic function


COSH intrinsic function

Standard: F77 F90 F95 F2003 F2008 F2018 Example program

＜Syntax＞

COSH ( X )

X : Real or Complex;

Result : Same type and kind as X.

＜Semantics＞

The value of the result is an approximation to the hyperbolic cosine of X. Like many intrinsic functions, this is elemental; the result has the same shape as X, with the operation being applied elementwise.

If X is of type Complex, its imaginary part is an angle in radians. Note that COSH(X) is identical to COS((0,1)*X).

＜Related＞

ACOSH intrinsic function, COS intrinsic function


COUNT intrinsic function

Standard: F77 F90 F95 F2003 F2008 F2018 Example program

＜Syntax＞

COUNT ( MASK [ , DIM , KIND ] )

MASK : rank N array of type Logical;
DIM : scalar Integer in the range 1 to N;
KIND : scalar Integer constant expression;

Result: Integer, or Integer(Kind=KIND).

The DIM argument must not be an optional dummy argument.

＜Semantics＞

Reduces an array (either completely, or by collapsing one dimension) by counting the number of true values; the value is the number of true values (in that dimension with DIM=).

In Fortran 2003, the KIND argument should be used when the number of true values might exceed the range of a default integer.

＜Related＞

ALL intrinsic function, ANY intrinsic function, Array-scalar operations, Array-array operations, DOT_PRODUCT intrinsic function, IALL intrinsic function, IANY intrinsic function, IPARITY intrinsic function, MAXLOC intrinsic function, MAXVAL intrinsic function, MINLOC intrinsic function, MINVAL intrinsic function, MATMUL intrinsic function, PARITY intrinsic function, PRODUCT intrinsic function, Reduction intrinsic functions, SUM intrinsic function


CPU_TIME intrinsic subroutine

Standard: F77 F90 F95 F2003 F2008 F2018 Example program

＜Syntax＞

Call CPU_TIME ( TIME )

TIME : scalar Real (any kind), Intent(Out).

＜Semantics＞

TIME is assigned an approximation to the processor (CPU) time used by the program in seconds. If this is not available, TIME is set to a negative value.

Note that the resolution of the CPU_TIME clock is usually much worse than the resolution of the real-time clock provided by SYSTEM_CLOCK.

＜Related＞

DATE_AND_TIME intrinsic subroutine, SYSTEM_CLOCK intrinsic subroutine


CRITICAL construct

Standard: F77 F90 F95 F2003 F2008 F2018 Example program

＜Syntax＞

critical-stmt
block

end-critical-stmt

critical-stmt ::= [ construct-name : ] CRITICAL [ ( [ sync-stat-list ] ) ]
sync-stat-list ::= sync-stat [ , sync-stat ]
sync-stat ::= STAT = stat-variable | ERRMSG = errmsg-variable

end-critical-stmt ::= END CRITICAL [ construct-name ]

If the CRITICAL statement has a construct name, the END CRITICAL must have the same construct name. The construct name has no effect on execution of the construct.

A stat-variable must be a non-coindexed scalar Integer variable, and should be able to represent values from −9999 to +9999. An errmsg-variable must be a non-coindexed scalar Character variable with default kind.

The block is not permitted to contain a RETURN statement, an image control statement, or a branch to a statement outside the construct. Thus, the only means of exiting a CRITICAL construct is through execution of the END CRITICAL statement.

A CRITICAL construct can invoke a procedure that is not pure, but the invoked procedure is not allowed to execute an image control statement.

＜Semantics＞

A CRITICAL construct is only executed by one image at a time; that is, if another image is already executing the construct, execution of the CRITICAL statement delays until that image executes the END CRITICAL statement.

Note that CRITICAL constructs cannot be nested (because the CRITICAL statement is an image control statement); this means that a valid program cannot deadlock due to use of CRITICAL.

If the STAT= specifier appears in a CRITICAL statement, stat-variable is assigned the value zero if no error occurs, and a positive value otherwise. If stat-variable is assigned the value of STAT_FAILED_IMAGE (from ISO_FORTRAN_ENV), it means that the preceding image failed whilst executing the CRITICAL construct (and that this image is now the only image executing inside the CRITICAL construct). If an error occurs but STAT= does not appear, the program is terminated. If ERRMSG= appears and an error occurs, errmsg-variable is assigned an explanatory message; otherwise, errmsg-variable is unchanged.

＜Related＞

END CRITICAL statement, ERRMSG= specifier, Image control statements, STAT= specifier


CSHIFT intrinsic function

Standard: F77 F90 F95 F2003 F2008 F2018 Example program

＜Syntax＞

CSHIFT ( ARRAY, SHIFT [ , DIM ] )

ARRAY : array of rank N and any type;
SHIFT : INTEGER, scalar or an array of rank N-1;
DIM : INTEGER scalar, the dimension to shift;

Result: same type and shape as ARRAY.

＜Semantics＞

The result is obtained by performing a circular shift of dimension DIM of ARRAY; if DIM is absent, it is treated as if it had the value 1 (i.e. the first dimension is shifted). SHIFT specifies the amount to shift each row/column/etc.

＜Related＞

EOSHIFT intrinsic function, PACK intrinsic function, SPREAD intrinsic function, TRANSPOSE intrinsic function, UNPACK intrinsic function


CYCLE statement

Standard: F77 F90 F95 F2003 F2008 F2018 Example program

＜Syntax＞

CYCLE [ do-construct-name ]

The CYCLE statement may only appear within a DO construct.

＜Semantics＞

The CYCLE statement immediately starts the next iteration of the DO construct. If do-construct-name appears, it is that DO construct whose next iteration is begun (this terminates any DO nested inside that construct), otherwise it is the innermost that the CYCLE statement appears in which is affected.

If there is no next iteration (because the current iteration is the last, or the WHILE condition is not satisfied), the DO construct will be terminated.

＜Related＞

CONTINUE statement, DO construct, DO WHILE statement, END DO statement, EXIT statement, GO TO statement


DATA statement

Standard: (F77) (F90) F95 F2003 F2008 Example program

＜Syntax＞

DATA data-set [ , data-set> ]...

data-set ::= data-object-list / data-value-list /

data-object-list ::= data-object [ , data-object ]...
data-object ::= variable | data-implied-do
data-implied-do ::= ( data-object [ , data-object ]... , do-spec )

data-value-list ::= data-value [ , data-value ]...
data-value ::= [ data-repeat * ] data-constant
data-repeat ::= constant &nbsp;|&nbsp; constant-subobject

data-constant | ::= | literal-constant
 | | | NULL ( )
 | | | structure-constructor
 | | | object
 | | | signed-int-literal-constant
 | | | signed-real-literal-constant

＜Semantics＞

Initialises the variables (data-objects) to the specified values (data-values). In most cases, it is recommended to initialise each variable in its type declaration statement instead.

Note that from Fortran 90 onwards, this statement implicitly confers the SAVE attribute on each variable.

From Fortran 95 onwards, a pointer can be initialised in a DATA statement to be disassociated, by using a data-constant that is a reference to the NULL intrinsic function.

Prior to Fortran 2008, the expressions in data-implied-do loop limits, and in subscript expressions for a data-object inside a data-implied-do loop, were not permitted to reference intrinsic functions even when the results were constant. From Fortran 2008, these expressions are normal constant expressions and so appropriate intrinsic functions can be referenced therein.

＜Related＞

NULL intrinsic function, PARAMETER statement, Type declaration statement


DATE_AND_TIME intrinsic subroutine

Standard: F77 F90 F95 F2003 F2008 F2018 Example program

＜Syntax＞

Call DATE_AND_TIME ( [ DATE , TIME , ZONE , VALUES ] )

DATE : default Character scalar, Intent(Out);
TIME : default Character scalar, Intent(Out);
ZONE : default Character scalar, Intent(Out);
VALUES : default Integer one-dimensional array, Intent(Out), minimum size 8.
From Fortran 2018, non-default kind is allowed provided it can represent values in the range −9999 to +9999.

＜Semantics＞

DATE is assigned the current date in the format CCYYMMDD, where CC is the century number, YY is the year number (00-99), MM is the month (01-12) and DD is the day of the month (01-31); for example 20121109 for November 9, 2012.

TIME is assigned the current time of day in the format HHMMSS.sss, where HH is the hour of the day (00-23), MM is the minute (00-59), SS is the second (00-60) and sss is the millisecond (000-999); note that this allows for representation of leap seconds.

ZONE is assigned the time zone in the format +HHMM or -HHMM representing the offset (in hours and minutes) from UTC (colloquially known as Greenwich Mean Time).

To avoid losing information, DATE should be length 8, TIME should be length 10, and ZONE should be length 5. Prior to Fortran 2003, arguments shorter than the minimum length were not permitted. If an argument is longer than the minimum, the remainder of the argument will be set to blanks.

If the date, time, or time zone information is not available, that argument is assigned all blanks.

Each element of the VALUES argument is assigned the information as an integer: in order this is the year (including the century), month, day, time zone offset in minutes, hour, minutes, seconds, and milliseconds. If any of the information is not available, that element will be assigned the value -HUGE(VALUES).

Note that all arguments are optional.

＜Related＞

CPU_TIME intrinsic subroutine, SYSTEM_CLOCK intrinsic subroutine


DBLE intrinsic function

Standard: F77 F90 F95 F2003 F2008 F2018 Example program

＜Syntax＞

DBLE ( A )

A : Integer, Real, Complex or a BOZ literal constant;

Result : Double Precision, i.e. Real(Kind=KIND(0.0d0)).

＜Semantics＞

The result is an approximation to the value of A expressed as a double precision real. If A is Complex, the imaginary part is ignored. Note that this function is entirely redundant, being exactly equal to REAL(A,KIND(0.0d0)).

If X or Y is a BOZ literal constant it is interpreted as the internal representation (as a bitstring) of the result. Note that this bitstring must not be longer that the number of bits in the result, unless the excess bits are all leading zeroes. If the bitstring is shorter than the number of bits in the result, it is padded on the left with leading zeroes.

Like many intrinsic functions, this is elemental; if A is an array, the result will be an array with the same shape, with the value being computed elementwise.

＜Related＞

REAL intrinsic function, REAL type


DEALLOCATE statement

Standard: F77 F90 F95 F2003 F2008 F2018 Example program

＜Syntax＞

DEALLOCATE( object [ , object ]... [, option ]... )

option | ::= | ERRMSG = variable
 | | | STAT = variable

Each object must be a pointer or allocatable variable. The variable for STAT= must be a scalar integer, and should be able to represent values in the range −9999 to +9999. The variable for ERRMSG= must be a scalar character of default kind. Only one of each kind of option is allowed.

＜Semantics＞

The DEALLOCATE statement deallocates storage occupied by an allocatable variable or pointer. An error is raised if an allocatable variable to be deallocated is not allocated, or if a pointer to be deallocated is disassociated or is associated with an object that was not allocated by pointer allocation.

Deallocating a pointer sets that pointer to "disassociated" but any other pointers associated with the target become undefined. Similarly, any pointers associated with an allocatable variable become undefined when the variable is deallocated.

The STAT= variable is set to zero if all the deallocations were successful or to a non-zero error code if an error occurred; if an error occurs when no STAT= is used, the program is terminated.

In Fortran 2003 the ERRMSG= specifier was added; this sets a character string variable to an error message if a deallocation fails. The variable is unchanged if there is no error.

＜Related＞

ALLOCATABLE attribute, ALLOCATE statement, ERRMSG= specifier, MOVE_ALLOC intrinsic subroutine, NULLIFY statement, POINTER attribute, STAT= specifier


DECIMAL= specifier

Standard: F77 F90 F95 F2003 F2008 F2018 Example program

＜Syntax＞

DECIMAL = expression

The expression must be a scalar character expression. It is permitted in the INQUIRE, OPEN, READ and WRITE statements. In the INQUIRE statement, it must be a variable designator, and is assigned the value 'COMMA', 'POINT' or 'UNDEFINED'; in all other statements it must evaluate to 'COMMA' or 'POINT' (ignoring case).

＜Semantics＞

The DECIMAL= specifier determines the default decimal edit mode (for OPEN), returns the default decimal edit mode (for INQUIRE), or specifies the decimal edit mode (for READ and WRITE).

The DECIMAL= specifier is only permitted in an OPEN, READ or WRITE statement that refers to a formatted file.

If a file is preconnected, or is opened without a DECIMAL= specifier, the default decimal edit mode is 'POINT'.

The decimal edit mode determines the character that is used for input and output to indicate the decimal position; if the edit mode is 'POINT' then a decimal point is used, whereas if it is 'COMMA' a decimal comma is used. When the decimal edit mode is 'COMMA', list-directed and namelist input/output will use semi-colon (instead of comma) as a value separator.

The current decimal edit mode may be overridden within a format by use of the DP (decimal point) and DC (decimal comma) edit descriptors.

In an INQUIRE statement, the value assigned is 'UNDEFINED' if the file is connected for unformatted input/output or if there is no connection.

＜Related＞

FORMAT statement, INQUIRE statement, OPEN statement, READ statement, WRITE statement


Derived Type Definition
Standard: F77 F90 F95 F2003 F2008 Example Program
<Syntax>
type-stmt
[ type-param-def-stmt ]...
[ private-or-sequence ]...
[ component-defn-stmt ]...
[ CONTAINS
[ PRIVATE ]
[ type-bound-proc-stmt ]... ]
END TYPE [ type-name ]

type-param-def-stmt ::= integer-type , type-param-attr :: type-param-decl-list
integer-type ::= INTEGER [ ( [ KIND = ] expr ) ]
type-param-attr ::= KIND | LEN
type-param-decl-list ::= type-param-decl [ , type-param-decl ]...
type-param-decl ::= type-param-name [ = expr ]

private-or-sequence ::= PRIVATE | SEQUENCE

The CONTAINS part shall not appear in a BIND(C) or SEQUENCE type.

type-bound-proc-stmt ::= specific-tbp-stmt | generic-tbp-stmt | final-procedure-stmt

The basic syntax of the statements in the type-bound procedure section is as follows.

generic-tbp-stmt ::= GENERIC [ , access ] :: generic-spec => type-bound-procedure-name-list
specific-tbp-stmt ::= PROCEDURE [ ( interface-name ) ] , type-bound-attr-list :: binding-list
final-procedure-stmt ::= FINAL [ :: ] final-subroutine-name-list

Refer to the pages on type-bound procedures and the FINAL statement for full syntax and semantics.
<Semantics>
A derived type definition defines a derived type.

If it contains the SEQUENCE statement it is a sequence derived type; objects of such a type may appear in COMMON and EQUIVALENCE. Two sequence derived types are the same if they have the same name, their components have the same names and appear in the same order, and corresponding components have the same type, rank, and attributes.

If the component part of the type definition contains the PRIVATE statement, the default accessibility of each component is PRIVATE. In Fortran 2003, this can be overridden by explicit declaration in each component definition statement. It is not permitted to give a private component a value in a structure constructor for the type when outside the module; normally this makes the structure constructor unavailable, but it can be used if the component has “default initialisation” because in that case the value for the component may be omitted in the constructor.

In Fortran 2003, a type can have a type-bound procedure part. This part defines type-bound procedures, which are procedures that are bound to the type itself and are accessible via objects of the type. The default accessibility of type-bound procedures is PUBLIC unless the type-bound procedure part contains a PRIVATE statement, even if the default accessibility of components is PRIVATE.

In Fortran 2003, a type can have type parameters. Each type parameter must be listed on the TYPE statement and be declared by a type-param-def-stmt. A type parameter is either a KIND type parameter or a LEN type parameter. If the type parameter is given a value in its declaration, this is its default value; a type parameter with a default value can be omitted from a declaration or structure constructor.

A KIND type parameter is permitted to appear in any expression inside the type definition, including within constant expressions; when declaring an entity of the type, the value supplied for a KIND type parameter must be a constant expression. A LEN type parameter is only permitted to appear within the type definition in an array bound, character length, or an expression supplied for a LEN type parameter (of a component); when declaring an entity of the type, the value supplied for a LEN type parameter can be a colon (“deferred” — only if the entity has the ALLOCATABLE or POINTER attribute), an asterisk (“assumed” — only if the entity is a dummy argument), or an expression (possibly non-constant).
<Related>
BIND attribute, Component Definition statement, END TYPE statement, EXTENDS clause, FINAL statement, PRIVATE attribute, PUBLIC attribute, SEQUENCE statement, TYPE statement, Type-bound procedure


Derived Type Definition Example Program

<Example Program 1>

Module material_type_module
  Type material
    Character(5) :: name
    Real :: young, poisson
  End Type material
End Module
Program type_definition_example
  Use material_type_module
  Type (material) steel, concrete
  steel%name = 'A36'
  steel%young = 200.
  steel%poisson = 0.3
  concrete = material( 'A36',200.,0.3 )
  Print *, steel
  Print *, concrete
End Program

Note: Execution Results

 A36 2.0000000E+02  0.3000000
 A36 2.0000000E+02  0.3000000

<Example Program 2>

Module point_type_module
  Type point(k)
    Integer, Kind :: k = Kind(0.0)
    Real(k) :: x,y,z
  End Type
End Module
Program example_2
  Use point_type_module
  Type(point) :: spx = point(1.0,2.0,3.0)
  Type(point(Kind(0d0)))
  Print *, spx
  dpy = point(Kind(0d0))(Sqrt(1d0), Sqrt(2d0), Sqrt(3d0))
  Print *, dpy
End Program

Note: Execution Results

   1.0000000   2.0000000   3.0000000
   1.0000000000000000   1.4142135623730951   1.7320508075688772

<Example Program 3>

Module vector_type_module
  Type vector(n)
    Integer, Len :: n
    Real :: v(n)
  Contains
    Procedure :: dotp
    Generic :: Operator(*) => dotp
  End Type
Contains
  Real Function dotp(a,b)
    Use Ieee_Arithmetic
    Class(vector(*)),Intent(In) :: a,b
    If (a%n/=b%n) Then
      If (.Not.Ieee_Support_Nan(dotp) .Or..Not.Ieee_Support_Flag(Ieee_Invalid)) &
        Error Stop 'dotp: inconsistent vector lengths'
      Call Ieee_Set_Flag(Ieee_Invalid,.True.)
      dotp = Ieee_Value(dotp,Ieee_Quiet_NaN)
    Else
      dotp = Dot_Product(a%v,b%v)
    End If
  End Function
End Module
Program example_3
  Use vector_type_module
  Type(vector(3)) :: x = vector(3)([1.0,2.0,3.0])
  Type(vector(3)) :: y = vector(3)([-4.0,-4.0,-4.0])
  Print *, 'x =', x
  Print *, 'y =', y
  Print *, 'x*y =', x*y
End Program

Note: Execution Results

 x =   1.0000000   2.0000000   3.0000000
 y =  -4.0000000  -4.0000000  -4.0000000
 x*y = -24.0000000


DIGITS intrinsic function

Standard: F77 F90 F95 F2003 F2008 F2018 Example program

＜Syntax＞

DIGITS ( X )

X : Integer or Real;
Result : Scalar Integer of default kind.

＜Semantics＞

This function returns the number of digits used in the model for number of the type and kind of X.

This is an inquiry function, so X need not be defined; indeed, it is permitted to be disassociated, unallocated, or absent.

All current machines with a Fortran compiler use binary integer arithmetic with bit lengths of 8, 16, 32 and 64; one bit is reserved for the sign, so the value of DIGITS(X) is one less than the number of bits.

The model for real type is that it may be zero or a signed fraction between 1 and 1/RADIX(X) consisting of DIGITS(X) digits, multiplied by an exponent RADIX(X)**e with MINEXPONENT(X)≤e≤MAXEXPONENT(X). For binary floating-point, DIGITS(X) is thus the number of bits in the mantissa, whereas for decimal floating-point it is the number of decimal digits.

＜Related＞

BIT_SIZE intrinsic function, EPSILON intrinsic function, HUGE intrinsic function, INTEGER type, MAXEXPONENT intrinsic function, MINEXPONENT intrinsic function, PRECISION intrinsic function, RADIX intrinsic function, REAL type, TINY intrinsic function


DIM intrinsic function

Standard: F77 F90 F95 F2003 F2008 Example program

＜Syntax＞

DIM ( X, Y )

X : Integer or Real;
Y : Same type and kind as X, conformable with X;
the NAG Fortran Compiler also permits Y to have a different kind (this is non-standard);

Result : Same type as X, with kind the same as the kind of X+Y.

＜Semantics＞

The result is the maximum of X−Y and zero.

Like many intrinsic functions, this is elemental; if either (or both) of X and Y is an array, the result will be an array with that shape, with the value being computed elementwise.

＜Related＞


DIMENSION attribute

Standard: (F77) F90 F95 F2003 F2008 F2018 Example program

＜Syntax＞

type, DIMENSION ( array-spec ) [ , attr-spec ]... :: decl-list

DIMENSION [ :: ] name ( array-spec ) [ , name ( array-spec ) ]...

array-spec | ::= | assumed-shape
 | | | assumed-size
 | | | deferred-shape
 | | | explicit-shape
 | | | implied-shape

assumed-shape ::= assumed-bound [ , assumed-bound ]...
assumed-bound ::= [ expression ] :

assumed-size ::= [ e-bound , ]... asize-bound
asize-bound ::= [ expression : ] *

explicit-shape ::= explicit-bound [ , explicit-bound ]...
explicit-bound ::= [ expression : ] expression

deferred-shape ::= deferred-bound [ , deferred-bound ]...
deferred-bound ::= :

implied-shape ::= implied-bound [ , implied-bound ]...
implied-bound ::= [ expression : ] *

＜Semantics＞

The DIMENSION attribute declares arrays. An assumed-shape or assumed-size array must be a dummy argument, a deferred-shape array must be a pointer or allocatable array, and an implied-shape array must be a named constant (the shape is implied by the shape of the defining expression for the constant). If a lower bound expression is omitted, that lower bound will have the value one.

The maximum rank (number of dimensions) of an array is 7 prior to Fortran 2008, and 15 from Fortran 2008 onwards. From Release 6.0 onwards, the NAG Fortran Compiler supports a maximum rank of 31.

The DIMENSION attribute can also be specified by putting an array-spec in parentheses after the entity name in a type declaration or component definition statement; this overrides any DIMENSION clause that might be present.

＜Related＞

Array assignment, Array constructor, Array section, Component Definition statement, CONTIGUOUS attribute, FORALL construct, FORALL statement, LBOUND intrinsic function, PARAMETER attribute, SHAPE intrinsic function, SIZE intrinsic function, Type Declaration statement, UBOUND intrinsic function, WHERE construct, WHERE statement


DO construct

Standard: F77 F90 F95 F2003 F2008 Example program

＜Syntax＞

do-stmt
block
end-do

The syntax of the DO statement is as follows.

[ construct-name : ] DO [ label ] [ [ , ] control ]

control | ::= | name = expr1 , expr2 [ , expr3 ]
 | | | CONCURRENT concurrent-header
 | | | WHILE ( expr )

end-do | ::= | continue-stmt
 | | | end-do-stmt

The syntax of the END DO statement is as follows.
END DO [ construct-name ]
If the DO statement has a construct name, the construct shall end with an END DO statement with the same construct name.

If the loop ends with a continue-stmt, the do-stmt must have a label and this must be the label of the CONTINUE statement.

If control is WHILE (expr), the expr shall be a scalar logical expression. If control is CONCURRENT concurrent-header, the construct is a concurrent DO construct. Otherwise, the name shall be a variable, and it and the expressions shall all be scalar integers.

＜Semantics＞

A (non-concurrent) DO construct executes the statements in its block repeatedly as follows.

  • If control is absent, it will loop forever.
  • If control is WHILE( expr ), it will loop while expr has the value true (it is only tested at the beginning of each iteration).
  • Otherwise, it will loop ( expr1 − expr2 ) ÷ expr3 times; if the iteration count is negative, it will loop zero times. If expr3 is omitted, it has the value 1.
    The variable will have the value expr1 on the first iteration, and will have expr3 added to it at the end of each iteration.

The concurrent DO construct executes the iterations in any order, and may execute more than one iteration at the same time. The syntax and semantics of the concurrent DO construct are described here.

＜Notes＞

Any DO loop can be advanced to the next iteration using a CYCLE statement, or terminated by an EXIT statement. Also, transferring control out of the loop (e.g. by GOTO) terminates the loop.

Nested DO loops can share the same ending statement, provided it is not an END DO statement. This is error-prone and considered obsolescent.

A DO loop can end on an executable statement that is not an END DO or CONTINUE statement. For the purposes of looping, this is treated as if the loop ended with CONTINUE and the executable statement was immediately before it, except that transfers (e.g. GOTO) go to the executable statement not to the implied CONTINUE. This is very error-prone and considered obsolescent.

＜Related＞

CONTINUE statement, CYCLE statement, DO CONCURRENT construct, DO WHILE statement, END DO statement, EXIT statement, GO TO statement


DO CONCURRENT construct

Standard: F77 F90 F95 F2003 F2008 F2018 Example program

＜Syntax＞

A DO CONCURRENT construct is a DO construct that begins with a DO CONCURRENT statement. The syntax of a DO CONCURRENT statement is as follows:
[ do-construct-name : ] DO [ label ] [ , ] CONCURRENT concurrent-header
where concurrent-header is
( [ integer-type-spec :: ] concurrent-control-list [ , mask-expr ] )
where concurrent-control-list is a comma-separated list of concurrent-control, which is
index-name = expr1 : expr2 [ : expr3 ]

Each expression exprn must be scalar integer, and the mask-expr (if present) must be scalar logical.

＜Semantics＞

A DO CONCURRENT construct is a DO loop with restrictions and semantics intended to allow efficient execution. The iterations of a DO CONCURRENT construct may be executed in any order, and possibly even in parallel.

Each loop index variable (index-name) is local to the construct; if integer-type-spec appears, each index-name has that type and kind, otherwise it has the type and kind of a variable with the same name outside the construct (and that type shall be Integer). The set of values of a concurrent-control has size
N = MAX( 0, (expr1 − expr2 ) ÷ expr3)
where expr3 is equal to 1 if it is not present. The index variable of a concurrent-control takes on the values in the set
{ it{expr}1+(i−1)×expr3, for i = 1 to N }

The set of iterations of a DO CONCURRENT construct is the set of all possible index variable value combinations implied by the concurrent-controls. If there is a mask-expr, only those iterations for which the mask-expr is true are executed.

The restrictions on the DO CONCURRENT construct are:

  • no branch is allowed from within the construct to outside of it (RETURN and STOP are also forbidden, but ERROR STOP is allowed);
  • the EXIT statement cannot be used to terminate the loop;
  • the CYCLE statement cannot refer to an outer loop;
  • there must be no dependencies between loop iterations &mdash; this means that
    • if a variable is assigned to by any iteration, it is not allowed to be referenced by another iteration unless that iteration assigns it a value first,
    • if a pointer has its association changed by any iteration, it is not allowed to be referenced by another iteration unless that iteration changes its association first;
    • if an allocatable variable is allocated by more than one iteration, it must be unallocated by the end of every iteration, and
    • if an allocatable variable is used in any iteration, it must either be previously allocated by that iteration, or not allocated or deallocated by any iteration;
  • all procedures referenced within the construct must be pure;
  • no reference to IEEE_GET_FLAG or IEEE_SET_HALTING_MODE is allowed.

＜Related＞

DO construct, FORALL construct, INTEGER type, PURE attribute


DO WHILE statement

Standard: F77 F90 F95 F2003 F2008 F2018 Example program

＜Syntax＞

[construct-name : ] DO [ label ] [ , ] WHILE ( expr )

The DO WHILE statement is a special case of the DO statement.

＜Semantics＞

A DO loop that begins with a DO WHILE statement executes its loop repeatedly, as long as the WHILE expr is true at the beginning of each iteration.

This is explained fully under DO construct.

＜Related＞

CONTINUE statement, CYCLE statement, DO construct, END DO statement, EXIT statement, GO TO statement


DOT_PRODUCT intrinsic function

Standard: F77 F90 F95 F2003 F2008 F2018 Example program

＜Syntax＞

DOT_PRODUCT ( VECTOR_A, VECTOR_B )

VECTOR_A : Integer, Real, Complex, or Logical array of rank one
VECTOR_B : same type and shape as VECTOR_A

＜Semantics＞

DOT_PRODUCT returns the dot product (also known as inner product) of two vectors. For Real and Integer this is the sum of the product of the corresponding array elements and is equal to SUM(VECTOR_A*VECTOR_B); for Complex it is the sum of the conjugate product of the corresponding array elements and is equal to SUM(CONJG(VECTOR_A)*VECTOR_B); for Logical “sum” is interpreted as the .OR. operation and “product” is interpreted as the .AND. operation, so this is equal to ANY(VECTOR_A.AND.VECTOR_B).

＜Related＞

Array-scalar operations, Array-array operations, MATMUL intrinsic function, PRODUCT intrinsic function, SUM intrinsic function


DOUBLE COMPLEX type specifier

Standard: F77 F90 F95 F2003 F2008 F2018

＜Syntax＞

DOUBLE COMPLEX

＜Semantics＞

This is synonymous with Complex(Kind(0d0)).

This statement is not part of any Fortran standard, and should not be used. Use Complex(Kind(0d0)) instead.

＜Related＞

COMPLEX type, DOUBLE PRECISION type specifier


DOUBLE PRECISION type specifier

Standard: F77 F90 F95 F2003 F2008 Example program

＜Syntax＞

DOUBLE PRECISION

The blank between DOUBLE and PRECISION is optional.

＜Semantics＞

DOUBLE PRECISION specifies that an entity is of type REAL and double precision kind. It is equivalent to REAL(KIND(0d0)). A double precision entity takes twice as much storage as a single precision entity.

The F90_KIND module contains named constants REAL32, REAL64 and REAL128 which are convenient for specifying Reals with a particular size. The standard intrinsic module ISO_FORTRAN_ENV also contains those constants.

The SELECTED_REAL_KIND intrinsic function can be used to select a real kind based on decimal precision and exponent range requirements. The IEEE_SELECTED_REAL_KIND function in the standard intrinsic module IEEE_ARITHMETIC can also be used to select an ISO/IEC/IEEE 60559 conformant real kind.

＜Related＞

CHARACTER type, COMPLEX type, Component Definition statement, DBLE intrinsic function, IMPLICIT statement, INTEGER type, LOGICAL type, REAL type, SELECTED_REAL_KIND intrinsic function, Type Declaration statement


DPROD intrinsic function

Standard: F77 F90 F95 F2003 F2008 F2018 Example program

＜Syntax＞

DPROD ( X, Y )

X : Real with default kind;
Y : Same type and kind as X, conformable with X;

Result : Same type and kind as X.

＜Semantics＞

The result is the double precision product of X and Y; this is essentially the same as X*DBLE(Y) or DBLE(X)*Y or DBLE(X)*DBLE(Y).

Like many intrinsic functions, this is elemental; if either (or both) of X and Y is an array, the result will be an array with that shape, with the value being computed elementwise.

＜Related＞

DBLE intrinsic function


DSHIFTL intrinsic function

Standard: F77 F90 F95 F2003 F2008 F2018 Example program

＜Syntax＞

DSHIFTL ( I, J, SHIFT )

I : BOZ literal constant or Integer;
J : BOZ literal constant or Integer (same kind as I if I is Integer);
SHIFT : Integer, conformable with I;

Result : Integer, same kind as I (or J).

Note: At least one of I and J must be of type Integer.

＜Semantics＞

The value of the result is obtained by shifting I to the left SHIFT times, with the bits shifted in on the right coming from the most significant bits of J. It is required that 0≤SHIFT≤BIT_SIZE(I). This is equivalent to the expression IOR(SHIFTL(I,SHIFT),SHIFTR(J,BIT_SIZE(J)-SHIFT)).

This is an elemental function; if any argument is an array the result is an array of the same shape, with the DSHIFTL operation being applied elementwise.

＜Related＞

DSHIFTR intrinsic function, IAND intrinsic function, IEOR intrinsic function, IOR intrinsic function, LEADZ intrinsic function, MASKL intrinsic function, MASKR intrinsic function, NOT intrinsic function, POPCNT intrinsic function, POPPAR intrinsic function, SHIFTA intrinsic function, SHIFTL intrinsic function, SHIFTR intrinsic function, TRAILZ intrinsic function


DSHIFTR intrinsic function

Standard: F77 F90 F95 F2003 F2008 F2018 Example program

＜Syntax＞

DSHIFTR ( I, J, SHIFT )

I : BOZ literal constant or Integer;
J : BOZ literal constant or Integer (same kind as I if I is Integer);
SHIFT : Integer, conformable with I;

Result : Integer, same kind as I (or J).

Note: At least one of I and J must be of type Integer.

＜Semantics＞

The value of the result is obtained by shifting J to the right SHIFT times, with the bits shifted in on the left coming from the least significant bits of I. It is required that 0≤SHIFT≤BIT_SIZE(I). This is equivalent to the expression IOR(SHIFTL(I,BIT_SIZE(I)-SHIFT),SHIFTR(J,SHIFT).

This is an elemental function; if any argument is an array the result is an array of the same shape, with the DSHIFTR operation being applied elementwise.

＜Related＞

DSHIFTL intrinsic function, IAND intrinsic function, IEOR intrinsic function, IOR intrinsic function, LEADZ intrinsic function, MASKL intrinsic function, MASKR intrinsic function, NOT intrinsic function, POPCNT intrinsic function, POPPAR intrinsic function, SHIFTA intrinsic function, SHIFTL intrinsic function, SHIFTR intrinsic function, TRAILZ intrinsic function


ELEMENTAL attribute

Standard: F77 F90 F95 F2003 F2008 F2018 Example program

＜Syntax＞

ELEMENTAL

The ELEMENTAL keyword may appear only in the prefix of a FUNCTION or SUBROUTINE statement.

＜Semantics＞

The ELEMENTAL keyword specifies that all procedures defined by this subprogram are “elemental”; that is, they can be applied elementally to one or more arrays, and if a function, produce an array of the same shape. (A subprogram can define several procedures by using the ENTRY statement.)

An elemental subprogram must obey the following rules:

  • all dummy arguments must be scalar nonallocatable nonpointer variables;
  • if it is a function subprogram, the result variable(s) must be scalar nonallocatable nonpointer, and must not have a variable character length.

The ELEMENTAL attribute also implies the PURE attribute, except when ELEMENTAL is accompanied by the IMPURE attribute; a pure elemental subprogram must additionally obey the rules for a pure subprogram. From Fortran 2018, an elemental procedure is permitted to be recursive (and this is the default).

All arguments to an elemental procedure must be conformable; that is, they may be scalar but all the array ones must have the same shape. A pure elemental procedure is applied elementwise to corresponding elements of its arguments, and is not called in any particular order; indeed, on a parallel processor it might be applied to more than one element at the same time. Because pure procedures cannot have side effects, the order of application does not make any difference to the result.

An impure elemental procedure is applied to its array arguments in array element order. Because an impure procedure can have side effects, this can make a difference to the result.}

When an elemental procedure appears in an expression in a WHERE construct, it is only applied to elements for which the current control mask is true.

＜Related＞

ENTRY statement, FUNCTION statement, IMPURE attribute, NON_RECURSIVE attribute, PURE attribute, RECURSIVE attribute, RESULT clause, SUBROUTINE statement


ELSE statement

Standard: (F77) F90 F95 F2003 F2008 F2018 Example program

＜Syntax＞

ELSE [ if-construct-name ]

The if-construct-name may appear only if the corresponding IF-THEN statement is named.

＜Semantics＞

The ELSE statement introduces the ELSE block of an IF construct. The ELSE block is executed if and only if no other block of the IF construct is executed.

＜Related＞

ELSE IF statement, END IF statement, IF statement, IF construct, IF THEN statement


ELSE IF statement

Standard: (F77) F90 F95 F2003 F2008 F2018 Example program

＜Syntax＞

ELSE IF ( expression ) THEN [ if-construct-name ]

The blank between ELSE and IF is optional. The expression shall be scalar of type Logical. The if-construct-name may appear only if the corresponding IF-THEN statement is named.

＜Semantics＞

The ELSE IF statement marks the beginning of an ELSEIF block in an IF construct. It is executed if and only if the expression in the IF statement is false, the expressions for all preceding ELSEIF blocks of the construct are false, and the expression for this ELSEIF block is true.

＜Related＞

ELSE statement, END IF statement, IF construct, IF statement, IF THEN statement


ELSEWHERE statement

Standard: F77 F90 F95 F2003 F2008 F2018 Example program

＜Syntax＞

ELSEWHERE [ construct-name ]

ELSEWHERE ( expression ) [ construct-name ]

The expression shall be of type Logical and shall have the same shape as the expression in the WHERE construct statement. The construct-name shall appear if and only if the WHERE construct is named.

Since Fortran 95, ELSEWHERE may be spelled as two words “ELSE WHERE” (Fortran 90 did not have masked ELSEWHERE).

＜Semantics＞

The ELSEWHERE and masked ELSEWHERE statements are part of the WHERE construct, which controls a set of masked array assignments.

The statements in an ELSEWHERE part are executed only for those elements for which the WHERE mask expression was false and all ELSEWHERE mask expressions of this construct are also false.

The statements in a masked ELSEWHERE part are executed only for those elements for which the WHERE mask expression was false, all previous ELSEWHERE mask expressions of this construct are false, and this ELSEWHERE mask expression is true. Note that only elements of this ELSEWHERE mask expression that correspond to false elements of all previous masks are evaluated.

＜Related＞

END WHERE statement, WHERE construct, WHERE statement


ENCODING= specifier

Standard: F77 F90 F95 F2003 F2008 F2018

＜Syntax＞

This specifier is permitted in the INQUIRE and OPEN statements only.

In the OPEN statement the syntax is
ENCODING = expression
The expression must be a scalar character expression of default kind.

In the INQUIRE statement the syntax is
ENCODING = variable
The variable must be a scalar character variable of default kind.

＜Semantics＞

In the OPEN statement the ENCODING= specifier determines the encoding method of the file. Since Release 6.0 the NAG Fortran Compiler has supported 'ASCII', 'DEFAULT', 'SHIFT_JIS' and 'UTF-8'.

In the INQUIRE statement this specifier assigns the encoding method of an open file (usually 'DEFAULT') to a variable. For an unconnected unit, or if the connection is for unformatted input/output, the variable is assigned the value 'UNDEFINED'. For a file that is not open, if the encoding method cannot be determined the variable is assigned the value 'UNKNOWN'.

＜Related＞

INQUIRE statement, OPEN statement


END statement

Standard: (F77) F90 F95 F2003 F2008 F2018 Example program

＜Syntax＞

END [ program-unit [ name ] ]

program-unit ::= BLOCK DATA | FUNCTION | MODULE | PROGRAM | SUBMODULE | SUBROUTINE

The name shall be the name of the program unit; it is not permitted on the END statement of an unnamed main program or block data subprogram.

Prior to Fortran 2008, the FUNCTION or SUBROUTINE keyword is required on the END statement of a contained subprogram (i.e. a module procedure or internal procedure).

＜Semantics＞

The END statement ends a program unit or a contained subprogram. If an END statement is executed in a FUNCTION or SUBROUTINE, it has the effect of a RETURN statement; in a main program it has the effect of a STOP statement.

＜Related＞

END FUNCTION statement, END MODULE statement, END PROGRAM statement, END MODULE statement, END SUBMODULE statement, END SUBROUTINE statement, RETURN statement, STOP statement


END ASSOCIATE statement

Standard: F77 F90 F95 F2003 F2008 F2018 Example program

＜Syntax＞

END ASSOCIATE [ construct-name ]

The blank between END and ASSOCIATE is optional. The construct-name shall appear if and only if the ASSOCIATE construct is named.

＜Semantics＞

The END ASSOCIATE statement marks the end of an ASSOCIATE construct.

＜Related＞

ASSOCIATE construct


END BLOCK statement

Standard: F77 F90 F95 F2003 F2008 Example program

＜Syntax＞

END BLOCK [ block-construct-name ]

The blank between END and BLOCK is optional. The block-construct-name shall appear if and only if the BLOCK construct is named.

＜Semantics＞

The END BLOCK statement marks the end of a BLOCK construct.

＜Related＞

BLOCK construct


END CRITICAL statement

Standard: F77 F90 F95 F2003 F2008 Example program

＜Syntax＞

END CRITICAL [ construct-name ]

The blank between END and CRITICAL is optional. The block-construct-name shall appear if and only if the CRITICAL construct is named.

＜Semantics＞

The END CRITICAL statement marks the end of a CRITICAL construct.

＜Related＞

CRITICAL construct


END DO statement

Standard: F77 F90 F95 F2003 F2008 F2018 Example program

＜Syntax＞

END DO [ do-construct-name ]

The blank between END and DO is optional. The do-construct-name shall appear if and only if the DO construct is named.

＜Semantics＞

The END DO statement ends a DO construct. When executed, it ends the current iteration of the loop.

＜Related＞

CONTINUE statement, CYCLE statement, DO construct, DO WHILE statement, EXIT statement


END ENUM statement

Standard: F77 F90 F95 F2003 F2008 F2018 Example program

＜Syntax＞

END ENUM

The blank between END and ENUM is optional.

The END ENUM statement is the last statement in an enumeration, which has the syntax
enum-stmt
enumerator-stmt
[ enumerator-stmt ]...
end-enum-stmt

＜Semantics＞

An enumeration defines a set of named constants of type Integer, all with the same kind; this is used to interoperate with a C enumeration, and the kind is chosen to be the same as the one used by the C compiler for a corresponding “enum” definition.

＜Related＞

BIND attribute, ENUM statement, ENUMERATOR statement


END FUNCTION statement

Standard: F77 F90 F95 F2003 F2008 F2018 Example program

＜Syntax＞

END [ FUNCTION [ function-name ] ]

Prior to Fortran 2008, the FUNCTION keyword is required for an internal function or module function. The blank between END and FUNCTION is optional.

＜Semantics＞

The END FUNCTION statement marks the end of a function subprogram. The function subprogram may be an external function, a module function or an internal function.

Executing an END FUNCTION statement has the same effect as a RETURN statement.

＜Related＞

CONTAINS statement, END statement, FUNCTION statement, RETURN statement


END IF statement

Standard: F77 F90 F95 F2003 F2008 F2018 Example program

＜Syntax＞

END IF [ if-construct-name ]

The blank between END and IF is optional. The if-construct-name shall be specified if and only if the IF construct is named.

＜Semantics＞

The END IF statement marks the end of an IF construct..

Executing an END IF statement has no effect.

In Fortran 77 and Fortran 90 it was permissible to branch to an END IF statement from outside the IF construct. Because this was confusing, it was deleted from Fortran 95 and remains deleted in Fortran 2003: it is only permissible to branch to an END IF statement from within the IF construct

＜Related＞

ELSE statement, ELSE IF statement, IF construct, IF statement, IF THEN statement


END INTERFACE statement

Standard: F77 F90 F95 F2003 F2008 F2018 Example program

＜Syntax＞

END INTERFACE [ generic-spec ]

The blank between END and INTERFACE is optional.

The generic-spec shall only appear if the same generic-spec appeared on the matching INTERFACE statement.

＜Semantics＞

The END INTERFACE statement marks the end of an INTERFACE block. The interface block may be an abstract interface block, a specific interface block or a generic interface block. If it is a generic interface block the same generic-spec may be specified on the END INTERFACE statement, but this is not required.

＜Related＞

INTERFACE statement, INTERFACE ASSIGNMENT statement, INTERFACE OPERATOR statement, MODULE PROCEDURE statement


END MODULE statement

Standard: F77 F90 F95 F2003 F2008 F2018 Example program

＜Syntax＞

END [ MODULE [ module-name ] ]

The blank between END and MODULE is optional.

＜Semantics＞

The END MODULE statement marks the end of a module program unit. A module program unit may contain named constants, type definitions, variables and procedures for use by other program units.

＜Related＞

END statement, MODULE statement


END PROGRAM statement

Standard: F77 F90 F95 F2003 F2008 F2018 Example program

＜Syntax＞

END [ PROGRAM [ program-name ] ]

The blank between END and PROGRAM is optional.

The program-name shall not appear on the END statement for an unnamed main program.

＜Semantics＞

The END PROGRAM statement marks the end of a main program program unit.

Executing an END PROGRAM statement terminates the program normally, the same as if a STOP statement had been executed.

＜Related＞

END statement, PROGRAM statement, STOP statement


END SELECT statement

Standard: F77 F90 F95 F2003 F2008 F2018 Example program

＜Syntax＞

END SELECT construct-name

The blank between END and SELECT is optional.

The construct-name shall appear if and only if the SELECT CASE, SELECT RANK, or SELECT TYPE construct is named.

＜Semantics＞

The END SELECT statement marks the end of a SELECT CASE, SELECT RANK, or SELECT TYPE construct.

It is permissible to branch to an END SELECT statement only from within the construct. Executing an END SELECT statement has no effect.

＜Related＞

CASE construct, CASE statement, CASE DEFAULT statement, SELECT CASE statement, SELECT RANK construct, SELECT TYPE construct


END SUBROUTINE statement

Standard: F77 F90 F95 F2003 F2008 F2018 Example program

＜Syntax＞

END [ SUBROUTINE [ subroutine-name ] ]

Prior to Fortran 2008, the SUBROUTINE keyword is required for an internal or module subroutine. The blank between END and SUBROUTINE is optional.

＜Semantics＞

The END SUBROUTINE statement marks the end of a subroutine subprogram, which may be an external subroutine, an internal subroutine or a module subroutine.

Executing an END SUBROUTINE statement returns from the subroutine, exactly as if a RETURN statement had been executed.

＜Related＞

CALL statement, CONTAINS statement, END statement, RETURN statement, SUBROUTINE statement


END TEAM statement

Standard: F77 F90 F95 F2003 F2008 F2018 Example program

＜Syntax＞

END TEAM [ ( [ sync-stat [ , sync-stat ] ] ) ] [ construct-name ]

sync-stat ::= STAT = stat-variable | ERRMSG = errmsg-variable
At most one STAT= and ERRMSG= specifier may appear in an END TEAM statement. The stat-variable must be a non-coindexed scalar integer variable (and at least 16 bits), and errmsg-variable must be a scalar default character variable.

The END TEAM statement is the last statement of a CHANGE TEAM construct.

＜Semantics＞

Executing the END TEAM statement implicitly synchronises the images of the team within the construct, which must all execute the same statement. It then restores the current team for those images to the team that was current before the CHANGE TEAM statement was executed.

If the STAT= specifier appears, the stat-variable is assigned the value zero for successful execution, and a positive value if an error occurs. If an error occurs and no STAT= specifier appears, the program is error-terminated.

If both STAT= and ERRMSG= appear and an error occurs, errmsg-variable is assigned an explanatory error message; otherwise, errmsg-variable is unchanged.

＜Related＞

CHANGE TEAM statement, ERRMSG= specifier, STAT= specifier


END TYPE statement

Standard: F77 F90 F95 F2003 F2008 F2018 Example program

＜Syntax＞

END TYPE [ type-name ]

The blank between END and TYPE is optional.

＜Semantics＞

The END TYPE statement marks the end of a derived type definition.

＜Related＞

Component Definition statement, Derived Type definition, TYPE statement


END WHERE statement

Standard: F77 F90 F95 F2003 F2008 F2018 Example program

＜Syntax＞

END WHERE [ where-construct-name ]

The blank between END and WHERE is optional. The where-construct-name shall appear if and only if the WHERE construct is named.

＜Semantics＞

The END WHERE statement marks the end of a WHERE construct.

It is not permissible to branch to an END WHERE statement.

＜Related＞

ELSE WHERE statement, WHERE construct, WHERE statement


END= specifier

Standard: F77 F90 F95 F2003 F2008 F2018

＜Syntax＞

END = label

The END= specifier is only permitted in a READ or WAIT statement.

＜Semantics＞

The END= specifier causes transfer of control to the specified label if an end-of-file condition occurs during sequential or stream input.

If an end-of-file condition occurs in a READ or WAIT statement that does not have an END= specifier but does have an ERR= specifier, control is transferred to the ERR= label. If an end-of-file condition occurs in a READ or WAIT statement that has no END=, ERR= or IOSTAT= specifier, the program is terminated.

The end-of-file condition can also be detected using the IOSTAT= specfier and the IS_IOSTAT_END intrinsic function.

＜Related＞

EOR= specifier, ERR= specifier, IOMSG= specifier, IOSTAT= specifier, IS_IOSTAT_END intrinsic function, READ statement, WAIT statement


ENDFILE statement

Standard: F77 F90 F95 F2003 F2008 F2018 Example program

＜Syntax＞

ENDFILE expression
ENDFILE ( endfile-spec-list )

endfile-spec-list ::= endfile-spec [ , endfile-spec ]...

endfile-spec | ::= | [ UNIT= ] expression
 | | | ERR=label
 | | | IOMSG=variable
 | | | IOSTAT=variable

The ENDFILE expression form is short for “ENDFILE (UNIT=expression)”. The (UNIT=) expression identifies the unit, and must be a scalar integer; its value must be non-negative or the result of the NEWUNIT= specifier.

The optional “UNIT=” are required unless it is the first endfile-spec.

ENDFILE may also be spelled as two separate words, END FILE.

＜Semantics＞

The ENDFILE statement writes an endfile record. This is a logical record that indicates the end of the file; any previous records after this point no longer exist. The endfile record need not have any physical existence. Afterwards, the file is positioned after the endfile record, and cannot be further written to unless positioned by REWIND or BACKSPACE; executing a single BACKSPACE will backspace over the endfile record.

ENDFILE is only permitted on a file connected for sequential or stream access.

The IOMSG= specifier was added in Fortran 2003; this sets a character string variable to an error message if an error occurs. The ERR= or IOSTAT= specifier is still needed to prevent termination on error.

＜Related＞

BACKSPACE statement, CLOSE statement, ERR= specifier, IOMSG= specifier, IOSTAT= specifier, NEWUNIT= specifier, OPEN statement, PRINT statement, REWIND statement, READ statement, UNIT= specifier, WRITE statement


Entity Declaration List

Standard: F77 (F90) F95 F2003 F2008 F2018

＜Syntax＞

entity-decl-list ::= entity-decl [ , entity-decl ]...

entity-decl | ::= | object-name [ * charlen ] [ dims ] [ codims ] [ initialisation ]
 | | | function-name [ * charlen ]

charlen | ::= | int-literal-constant
 | | | ( integer-specification-expr )
 | | | ( * )
 | | | ( : )

dims ::= ( array-spec )

codims ::= ‘[’ coarray-spec ‘]’

initialisation | ::= | = constant-expression
 | | | => null-intrinsic-function-ref
 | | | => initial-target

The null-intrinsic-function-ref must be a reference to the intrinsic function NULL, e.g. “NULL()”.

initial-target ::= variable-designator | procedure-name}

The variable-designator must have both the SAVE and TARGET attributes, and must not be coindexed, have a vector subscript, or have the ALLOCATABLE attribute. The procedure-name must be the name of a non-elemental external procedure, module procedure, or specific intrinsic procedure. Up to Release 7.0, the NAG Fortran Compiler does not support initial-target pointer initialisation.

The entity-decl-list is used in both Type Declaration statements and Component Definition statements.

＜Semantics＞

The entity-decl-list names the entities being declared. If *charlen appears, it specifies the CHARACTER length for that entity (overriding the length in the type-spec). If dims appears, it specifies the DIMENSION attribute for that entity (overriding any DIMENSION clause). If codims appears, it specifies the CODIMENSION attribute for that entity (overriding any CODIMENSION clause).

In a type declaration statement, if the PARAMETER keyword is present then value must be present: it specifies the value of the parameter. If the PARAMETER clause is not present, initialisation implies the SAVE attribute and specifies the initial value of the variable.

In a component definition statement, if initialisation is present it specifies default initialisation for that component. This will set the initial value of the component to that value whenever a new variable of the type is created.

An initialisation is permitted to be a reference to the NULL intrinsic function if and only if the entity is a pointer, and this specifies that the pointer is initially disassociated. Note that if the entity is allocatable, no initialisation is permitted (all allocatable entities are initially unallocated).

＜Related＞

Attributes, CHARACTER type, CODIMENSION attribute, Component Definition statement, DIMENSION attribute, NULL intrinsic function, Type Declaration statement


ENTRY statement

Standard: (F77) (F90) F95 F2003 F2008 F2018

＜Syntax＞

ENTRY name [ ( [ dummy-arg-list ] ) [ suffix ]... ]

dummy-arg-list ::= dummy-arg [ , dummy-arg ]...

dummy-arg ::= name | *

suffix | ::= | BIND ( C [ , NAME=expression ] )
 | | | RESULT ( name )

The ENTRY statement may appear in the specification part or in the executable part of a function or subroutine subprogram. It must not appear within the block of any executable construct.

The RESULT clause is only allowed within a function subprogram. A dummy-arg of “*” is only allowed within a subroutine subprogram.

Only one occurrence of any particular suffix is allowed in a single ENTRY statement.

The expression in the BIND(C) clause must be a scalar default character constant expression. It must evaluate to an empty string, or a valid external identifier, after removing trailing blanks.

ENTRY statements are only permitted in external subprograms and module procedure subprograms.

＜Semantics＞

The ENTRY statement defines an additional procedure with a subprogram. If the subprogram is a function subprogram, it defines an additional function; if it is a subroutine subprogram, it defines an additional subroutine.

The dummy arguments of the entry procedure are those listed on the ENTRY statement, and the procedure begins executing at the first executable statement after the ENTRY statement. Reference to a dummy argument is only permitted if it is listed in the statement that defines the procedure being executed; i.e., when executing an entry procedure, it is only permissible to reference dummy arguments of the entry procedure and not those of any other procedure defined by the subprogram. All other entities are shared between the defined procedures.

Multiple ENTRY statements are permitted; each one defines an additional procedure.

In a function subprogram, each entry has its own result variable (either named by the RESULT clause, or eponymous); the result variable of all functions defined by the subprogram are associated with each other. All result variables in a function subprogram must have the same type and kind, except that default real, double precision real, default integer, default logical and default complex may be mixed.

The procedure defined by an ENTRY statement inherits the ELEMENTAL, IMPURE, NON_RECURSIVE, PURE, and RECURSIVE attributes from the containing subprogram. The procedure defined by an ENTRY statement is “interoperable” if and only if the BIND clause appears on the ENTRY statement. This is completely independent of whether the containing subprogram has the BIND attribute.

It is recommended that module subprograms be used for code and data sharing instead of ENTRY statements, as their use is prone to error.

ENTRY statements are considered obscolescent in Fortran 2008.

＜Related＞

BIND attribute, ELEMENTAL attribute, IMPURE attribute, FUNCTION statement, NON_RECURSIVE attribute, PURE attribute, RECURSIVE attribute, RESULT clause, SUBROUTINE statement


ENUM statement

Standard: F77 F90 F95 F2003 F2008 F2018 Example program

＜Syntax＞

ENUM , BIND(C)

The ENUM statement is the first statement in an enumeration, which has the syntax
enum-stmt
enumerator-stmt
[ enumerator-stmt ]...
end-enum-stmt

＜Semantics＞

An enumeration defines a set of named constants of type Integer, all with the same kind; this is used to interoperate with a C enumeration, and the kind is chosen to be the same as the one used by the C compiler for a corresponding enum definition.

＜Related＞

BIND attribute, END ENUM statement, ENUMERATOR statement


ENUMERATOR statement

Standard: F77 F90 F95 F2003 F2008 F2018 Example program

＜Syntax＞

ENUMERATOR [ :: ] enum-decl [ , enum-decl ]...

enum-decl ::= name [ = expression ]

If any expression appears, the double colon (::) is required. The expression must be a scalar integer constant expression.

The ENUMERATOR statement appears only in an enumeration, which has the syntax
enum-stmt
enumerator-stmt
[ enumerator-stmt ]...
end-enum-stmt

＜Semantics＞

An enumeration defines a set of named constants of type Integer, all with the same kind; this is used to interoperate with a C enumeration, and the kind is chosen to be the same as the one used by the C compiler for a corresponding enum definition.

Each enum-decl specifies the name and value of one of the named constants. If the expression is provided the value is that of the expression; otherwise the value is zero if it is the first enum-decl in the enumeration, or one more than the last enum-decl value.

＜Related＞

BIND attribute, END ENUM statement, ENUM statement


EOR= specifier

Standard: F77 F90 F95 F2003 F2008 F2018 Example program

＜Syntax＞

EOR = label

The EOR= specifier is only permitted in a READ statement that has ADVANCE='NO', or in a WAIT statement.

＜Semantics＞

The EOR= specifier causes transfer of control to the specified label if an end-of-record condition occurs during nonadvancing input. The end-of-record condition can also be detected using the IOSTAT= specifier and the IS_IOSTAT_EOR intrinsic function.

＜Related＞

ADVANCE= specifier,
END= specifier,
ERR= specifier,
IOMSG= specifier,
IOSTAT= specifier,
IS_IOSTAT_EOR intrinsic function,
READ statement,
WAIT statement


EOSHIFT intrinsic function

Standard: F77 F90 F95 F2003 F2008 F2018 Example program

＜Syntax＞

EOSHIFT(ARRAY, SHIFT [ , BOUNDARY, DIM ] )

ARRAY : array of any type and rank N;
SHIFT : integer scalar or array of rank N−1;
BOUNDARY : same type as ARRAY, scalar or array of rank N−1;
DIM : integer scalar;

Result : same type and shape as ARRAY.

If ARRAY is of derived type, BOUNDARY must be present.

＜Semantics＞

The EOSHIFT function returns an “end-off” shifted array. The amount of the shift is specified by SHIFT. Elements shifted in are taken from the BOUNDARY argument if present; otherwise the values depend on the type of ARRAY and are

Type | Value
Real | 0.0
Integer | 0
Logical | .FALSE.
Complex | (0.,0.)
Character | ' '

＜Related＞

CSHIFT intrinsic function


EPSILON intrinsic function

Standard: F77 F90 F95 F2003 F2008 F2018 Example program

＜Syntax＞

EPSILON ( X )

X : Real, scalar or array, any kind;

Result : Scalar, same type and kind as X.

＜Semantics＞

This function returns the “model number” that is almost negligible with respect to 1.0 for the type and kind of X. This value is equal to REAL(RADIX(X),KIND(X))**(-DIGITS(X)). Adding EPSILON(X) to 1.0 (with the kind of X) will always produce a value greater than 1.0.

This is an inquiry function, so X need not be defined; indeed, it is permitted to be disassociated, unallocated, or absent.

The model for real type is that it may be zero or a signed fraction between 1 and 1/RADIX(X) consisting of DIGITS(X) digits, multiplied by an exponent RADIX(X)**e with MINEXPONENT(X)≤e≤MAXEXPONENT(X).

＜Related＞

DIGITS intrinsic function, HUGE intrinsic function, MAXEXPONENT intrinsic function, MINEXPONENT intrinsic function, PRECISION intrinsic function, RADIX intrinsic function, REAL type, TINY intrinsic function


.EQ. (==) operator

Standard: F77 F90 F95 F2003 F2008 F2018 Example program

＜Syntax＞

expression .EQ. expression
expression == expression

Each expression must be of type Integer, Real, Complex or Character. If one expression is of type Character both must be.

＜Semantics＞

Tests two expressions for equality, returning a default logical result.

Note that in the case of type Real, negative zero is considered to be equal to positive zero.

＜Related＞

.AND. operator, Concatenation (//) operator, .EQV. operator, .GE. (>=) operator, .GT. (>) operator, .LE. (<=) operator, .LT. (<) operator, .NE. (/=) operator, .NEQV. operator, .NOT. operator, Numeric operators, Operator precedence, .OR. operator


EQUIVALENCE

Standard: F77 F90 F95 F2003 F2008 F2018

＜Syntax＞

EQUIVALENCE eqv-set [ , eqv-set ]...

eqv-set ::= ( object, object [ , object ]... )

object ::= variable-name | array-element | substring

＜Semantics＞

The EQUIVALENCE statement causes variables to share the same memory locations. The variables must have the same type and kind, except that default real, double precision real, default complex, default integer and default logical may be equivalenced together.

This feature is very error-prone and its use is strongly discouraged. This feature is considered obsolescent in Fortran 2018.

＜Related＞

COMMON statement, ENTRY statement


.EQV. operator

Standard: F77 F90 F95 F2003 Example program

＜Syntax＞

expression .EQV. expression

This operator has the lowest precedence of any intrinsic operator, the same as .NEQV. and higher only than user-defined binary operators.

＜Semantics＞

Tests two logical expressions for equivalence. The kind of the result is the same as the kind of one of the expressions.

The result is .TRUE. if either the expressions are both .TRUE. or both .FALSE, and the result is .FALSE. otherwise.

＜Related＞

.AND. operator, Concatenation (//) operator, .EQ. (==) operator, .GE. (>=) operator, .GT. (>) operator, .LE. (<=) operator, .LT. (<) operator, .NE. (/=) operator, .NEQV. operator, .NOT. operator, Numeric operators, Operator precedence, .OR. operator


ERF intrinsic function

Standard: F77 F90 F95 F2003 F2008 F2018 Example program

＜Syntax＞

ERF ( X )

X : Real;

Result : Same type and kind as X.

＜Semantics＞

The value of the result is an approximation to the “error function” of X; that is (2÷√π)×∫0X e-t2dt.

Like many intrinsic functions, this is elemental; the result has the same shape as X, with the operation being applied elementwise.

This function converges to 1.0 extremely rapidly with increasing X.

＜Related＞

ERFC intrinsic function, ERFC_SCALED intrinsic function


ERFC intrinsic function

Standard: F77 F90 F95 F2003 F2008 F2018 Example program

＜Syntax＞

ERFC ( X )

X : Real;

Result : Same type and kind as X.

＜Semantics＞

The value of the result is an approximation to the “complementary error function” of X; that is mathematically equal to 1.0−ERF(X). Like many intrinsic functions, this is elemental; the result has the same shape as X, with the operation being applied elementwise.

This function converges to zero quickly with increasing X.

＜Related＞

ERF intrinsic function, ERFC_SCALED intrinsic function


ERFC_SCALED intrinsic function

Standard: F77 F90 F95 F2003 F2008 F2018 Example program

＜Syntax＞

ERFC_SCALED ( X )

X : Real;

Result : Same type and kind as X.

＜Semantics＞

The value of the result is an approximation to the exponentially-scaled “complementary error function” of X; that is ERFC(X) scaled by eX2. Like many intrinsic functions, this is elemental; the result has the same shape as X, with the operation being applied elementwise.

This function converges to zero with increasing X, but only slowly.

＜Related＞

ERF intrinsic function, ERFC intrinsic function


ERR= specifier

Standard: F77 F90 F95 F2003 F2008 F2018 Example program

＜Syntax＞

ERR = label

The ERR= specifier is permitted in all input/output statements.

＜Semantics＞

The ERR= specifier causes transfer of control to the specified label if an error condition occurs during the input/output operation.

If an error condition occurs in an input/output statement that has neither ERR= nor IOSTAT=, the program is terminated.

＜Related＞

END= specifier,
EOR= specifier,
IOMSG= specifier,
IOSTAT= specifier


ERRMSG= specifier

Standard: F77 F90 F95 F2003 F2008 F2018 Example program

＜Syntax＞

ERRMSG = variable

The variable must be a scalar Character with default kind; its length should be sufficient to hold any message of interest.

The ERRMSG= specifier is allowed in ALLOCATE and DEALLOCATE statements, and the image control statements CHANGE TEAM, END TEAM, LOCK, SYNC ALL, SYNC IMAGES, SYNC MEMORY and UNLOCK. An ERRMSG= variable in an image control statement is not allowed to be a coindexed object.

＜Semantics＞

The ERRMSG= specifier causes the specified variable to be defined with an explanatory message if an error occurs during execution of the statement (if the variable is too short, the message will be truncated). If no such condition occurs, the variable is unchanged.

Note that if no STAT= specifier appears, the program will be terminated on any error condition; therefore it is necessary to use STAT= together with the ERRMSG= specifier if it is to be useful.

＜Related＞

ALLOCATE statement, CHANGE TEAM statement, DEALLOCATE statement, END TEAM statement, EVENT POST statement, EVENT WAIT statement, LOCK statement, STAT= specifier, SYNC ALL statement, SYNC IMAGES statement, SYNC MEMORY statement, UNLOCK statement


ERROR STOP statement

Standard: F77 F90 F95 F2003 F2008 F2018 Example program

＜Syntax＞

ERROR STOP [ expression ] [ , QUIET = logical-expression ]

The expression must be a scalar constant expression of type Integer or Character, in both cases the kind must be default kind. Fortran 2018 permits the expression to be non-constant.

The logical-expression must be scalar.

Fortran 2018 permits the ERROR STOP statement to appear in a pure subprogram.

＜Semantics＞

The ERROR STOP statement causes error termination of the program. (If a coarray program has multiple images, error termination will cause every image to terminate.)

Termination of execution by an ERROR STOP statement will display an informative message on the ERROR_UNIT if any IEEE exception is signalling at that time, unless QUIET= appears and the logical-expression has the value .TRUE.; QUIET=.TRUE. also suppresses display of the “stop code” (expression).

The remaining details apply to the NAG Fortran Compiler (they are not guaranteed by the Fortran standard). If expression appears and QUIET=.TRUE. does not appear, the value of the expression is displayed on the standard error unit, prefixed with “ERROR STOP: ”. An integer value is displayed in decimal (I0 format) and a character value is displayed without quotes (A format). If expression does not appear, the message “ERROR STOP” is displayed.

If expression appears and is of type integer, the lower eight bits of its value are returned as the process exit status; otherwise, the process exit status is equal to 2.

＜Related＞

STOP statement


EVENT POST statement

Standard: F77 F90 F95 F2003 F2008 F2018 Example program

＜Syntax＞

EVENT POST ( event-variable [ , sync-stat ]... )

sync-stat ::= STAT = stat-variable | ERRMSG = errmsg-variable

The event-variable must be of type EVENT_TYPE from the intrinsic module ISO_FORTRAN_ENV. Any variable of that type must be a coarray or a subcomponent of a coarray.

At most one STAT= and at most one ERRMSG= is allowed. A stat-variable must be a non-coindexed scalar Integer variable, and should be able to support values from −9999 to +9999, i.e. it should be at least 16 bits. An errmsg-variable must be a non-coindexed default Character variable.

＜Semantics＞

Execution of an EVENT POST statement increments the event-variable's “event count” (this count is initially zero). The event-variable will usually be a coindexed variable, as it is rarely useful for an image to post an event to itself.

EVENT POST is an image control statement, beginning a new segment of execution. Synchronisation is one-sided: the segments before execution of EVENT POST precede the segments after the corresponding EVENT WAIT execution.

If STAT= appears and the post is successful, zero is assigned to the stat-variable. If the image on which the event-variable is located has stopped, STAT_STOPPED_IMAGE is assigned to the stat-variable; if the image has failed, STAT_FAILED_IMAGE is assigned, and if any other error occurs, some other positive value is assigned. If STAT= does not appear and an error occurs, the program will be error-terminated. If both STAT= and ERRMSG= appear, and any error occurs, an explanatory message is assigned to the errmsg-variable.

＜Related＞

ERRMSG= specifier, EVENT WAIT statement, EVENT_TYPE from ISO_FORTRAN_ENV, Image control statements, STAT= specifier


EVENT WAIT statement

Standard: F77 F90 F95 F2003 F2008 F2018 Example program

＜Syntax＞

EVENT WAIT ( event-variable [ , wait-spec ]... )

wait-spec | ::= | ERRMSG = errmsg-variable
 | | | STAT = stat-variable
 | | | UNTIL_COUNT = scalar-integer-expr

The event-variable must be of type EVENT_TYPE from the intrinsic module ISO_FORTRAN_ENV. This variable must not be a coindexed object, that is, an image can only wait for events posted to its own event variables.

At most one of each kind of wait-spec is allowed. A stat-variable must be a non-coindexed scalar Integer variable, and should be able to support values from −9999 to +9999, i.e. it should be at least 16 bits. An errmsg-variable must be a non-coindexed default Character variable.

＜Semantics＞

Execution of an EVENT WAIT statement waits until the event-variable's “event count” has reached the “threshold value”. The threshold value is one if the UNTIL_COUNT= specifier does not appear, or if the scalar-integer-expr is less than one; otherwise it is equal to the scalar-integer-expr. When the wait is satisfied, the event count is then decreased by the threshold value.

Synchronisation is one-sided: the segments after execution of EVENT WAIT follow the segments before the corresponding EVENT POST execution(s).

If STAT= appears, it is assigned the value zero if the wait was successful, and a positive value if any error occurred. If an error occurs and STAT= does not appear, the program is terminated. If both STAT= and ERRMSG= appear, and any error occurs, an explanatory message is assigned to the errmsg-variable.

＜Related＞

ERRMSG= specifier, EVENT POST statement, EVENT_TYPE from ISO_FORTRAN_ENV, Image control statements, STAT= specifier


EVENT_TYPE from ISO_FORTRAN_ENV

Standard: F77 F90 F95 F2003 F2008 F2018

＜Syntax＞

TYPE ( EVENT_TYPE )
CLASS ( EVENT_TYPE )

Something of type EVENT_TYPE, or which has a potential subobject component of type EVENT_TYPE, must be a variable or a data component. A named variable of type EVENT_TYPE, or which has a potential subobject component of type EVENT_TYPE, must be a coarray.

A variable of type EVENT_TYPE must not be changed except via the EVENT POST and EVENT WAIT statements.

＜Semantics＞

＜Related＞

CODIMENSION attribute, EVENT POST statement, EVENT WAIT statement


EXECUTE_COMMAND_LINE intrinsic subroutine

Standard: F77 F90 F95 F2003 F2008 Example program

＜Syntax＞

Call EXECUTE_COMMAND_LINE ( COMMAND [ , WAIT, EXITSTAT, CMDSTAT, CMDMSG ] )

COMMAND : Default character scalar;
WAIT : Default logical scalar;
EXITSTAT : Default integer scalar variable;
CMDSTAT : Default integer scalar variable;
CMDMSG : Default character scalar variable.

＜Semantics＞

The command given by COMMAND is executed by the default system command processor. The other arguments are all optional; when present, they act as follows.

WAIT indicates whether to wait for the command to finish executing; the default is true. Note that WAIT=.FALSE. is not supported by Release 7.0 of the NAG Fortran Compiler; it will cause an error to be returned through CMDSTAT, or if CMDSTAT is not present, it will cause error termination.

EXITSTAT receives the exit status of the command (only if the command is executed synchronously, otherwise it is unchanged). The meaning of the exit status is operating system (and command) dependent.

CMDSTAT is set to −2 if WAIT=.FALSE. is given, an operating system error code if an unexpected error occurs, and to zero otherwise. (The value −1 is reserved for indicating when the Fortran compiler does not support command execution.) If CMDSTAT is not present and any error occurs, the program is terminated.

CMDMSG is set to an appropriate message if an error occurs, and is unchanged if no error occurs; note that CMDSTAT must also be present to avoid program termination on any error.

＜Related＞


EXIT statement

Standard: F77 F90 F95 F2003 F2008 F2018 Example program

＜Syntax＞

EXIT [ construct-name ]

＜Semantics＞

The EXIT statement completes execution of a DO construct other than a DO CONCURRENT construct. If construct-name is specified, it completes execution of that construct and any nested constructs; otherwise it terminates the innermost DO loop.

In Fortran 2008, the construct-name is permitted to be the name of an ASSOCIATE, BLOCK, IF, SELECT CASE or SELECT TYPE construct. In Fortran 2018, the construct-name is permitted to be the name of a CHANGE TEAM or CRITICAL construct.

On execution, control is transferred to the executable statement following the completed construct. The values of any active DO index variables of the terminated loops are unchanged.

＜Related＞

ASSOCIATE construct, BLOCK construct, CHANGE TEAM construct, CONTINUE statement, CRITICAL construct, CYCLE statement, DO construct, DO WHILE statement, END DO statement, IF construct, GO TO statement, SELECT CASE construct, SELECT TYPE construct


EXP intrinsic function

Standard: F77 F90 F95 F2003 F2008 F2018 Example program

＜Syntax＞

EXP ( X )

X : Real or Complex;

Result : Same type and kind as X.

＜Semantics＞

The value of the result is an approximation to the exponential function, eX; it is the inverse of the natural logarithm (LOG function).

Like many intrinsic functions, this is elemental; the result has the same shape as X, with the operation being applied elementwise.

＜Related＞

LOG intrinsic function, LOG10 intrinsic function


EXPONENT intrinsic function

Standard: F77 F90 F95 F2003 F2008 F2018 Example program

＜Syntax＞

EXPONENT ( X )

X : Real, any kind;

Result : Integer, default kind.

＜Semantics＞

Returns the exponent of X in the real model for that kind of floating-point number. If the value of X is representable in that model, the result satisfies the relationship X = FRACTION(X)*(REAL(RADIX(X),KIND(X))**EXPONENT(X). If X is an IEEE ∞ or NaN, the result is equal to HUGE(0). Note that if X is double-double precision, the result of EXPONENT(X) is accurate but FRACTION(X) might not be.

Like many intrinsic functions, this is elemental; the result has the same shape as X, with the operation being applied elementwise.

＜Related＞

DIGITS intrinsic function, FRACTION intrinsic function, MAXEXPONENT intrinsic function, MINEXPONENT intrinsic function, RADIX intrinsic function, REAL intrinsic function, SET_EXPONENT intrinsic function


EXTENDS clause

Standard: F77 F90 F95 F2003 F2008 F2018 Example program

＜Syntax＞

TYPE, EXTENDS(parent-type-name) [ , access ] :: type-name
...
END TYPE [ type-name ]

access ::= PRIVATE | PUBLIC

The parent-type-name in EXTENDS shall be the name of an extensible type; that is, a type that does not have the SEQUENCE or BIND(C) attributes.

＜Semantics＞

A type definition with the EXTENDS clause creates a new type by extending a pre-existing one. The extension type type-name has all the components of the parent type parent-type-name; additional components may be declared, these must have names different from the inherited components and type-bound procedures. There is a special parent component of type parent-type-name; this is associated with the inherited components and can be used to manipulate and access them as a group.

The extension type has all the generic type-bound procedures of the parent type, and may declare additional generics.

The extension type has all the specific type-bound procedures of the parent type, except that it may override them. A specific type-bound procedure is overridden simply by declaring a new type-bound procedure with the same name. The overriding procedure must have exactly the same characteristics as the overridden one, except that any passed-object dummy argument shall be CLASS(type-name) instead of CLASS(parent-type-name).

＜Related＞

CLASS specifier, Derived Type definition, TYPE statement


EXTENDS_TYPE_OF intrinsic function

Standard: F77 F90 F95 F2003 F2008 F2018 Example program

＜Syntax＞

EXTENDS_TYPE_OF ( A, MOLD )

A : object of extensible type or CLASS(*);
MOLD : object of extensible type or CLASS(*);

Result : Default Logical scalar.

Both A and MOLD are permitted to be unallocated allocatables or disassociated pointers, but are not permitted to be undefined pointers.

＜Semantics＞

The result is true if and only if the dynamic type of A is the same as, or an extension of, the dynamic type of MOLD. Note that the dynamic type of unallocated allocatable or disassociated pointer is the same as its declared type; in the case of CLASS(*), which has no declared type, it is treated as if it is the parent type of everything, i.e. everything extends a disassociated CLASS(*) and a disassociated CLASS(*) is not an extension of anything else. Either A or MOLD is CLASS(*) and has a dynamic type that is not extensible, the result is processor dependent.

Note that simply knowing that a type is an extension of another does not give you access to any of the extended components; to do this you need to use the SELECT TYPE construct.

＜Related＞

CLASS specifier, Derived Type Definition, EXTENDS clause, SAME_TYPE_AS intrinsic function, SELECT TYPE construct


EXTERNAL attribute
Standard: (F77) F90 F95 F2003 Example Program
<Syntax>
type, EXTERNAL [ , attr ] :: decl-list

EXTERNAL [ :: ] name [ , name ]...
<Semantics>
The EXTERNAL attribute declares that a dummy argument is a procedure, or that an entity is an external procedure or BLOCK DATA subprogram. This attribute is required if the procedure is passed as an actual argument, but not if it is only called.

The syntax above always declares a procedure with an implicit interface; such an interface contains no information about the number and type of arguments. The EXTERNAL attribute is also conferred by an interface block and that declares a procedure with an explicit interface.
<Related>
Interface statement, INTRINSIC attribute, Type Declaration statement


EXTERNAL example program

<Example Program>

Program external_example
Real, External :: tan
Print *, tan( 45. )
End Program
Real Function tan(degrees)
radians = degrees*3.141592654/180.
tan = sin(radians)/cos(radians)
End Function
Execution Results

1.0000000


FAIL IMAGE statement

Standard: F77 F90 F95 F2003 F2008 F2018

＜Syntax＞

FAIL IMAGE

＜Semantics＞

A FAIL IMAGE statement causes the executing image to cease participating in program execution without initiating normal termination or error termination. The purpose of this statement is to facilitate testing of fault tolerant programs, by artificially causing some images to fail.

Attempting to read data from a coarray on a failed image produces incorrect results. Attempting to write data to a coarray on a failed image is ineffective. In either case, if the image selector has a STAT= specifier, the STAT= variable will be assigned the value of STAT_FAILED_IMAGE from the intrinsic module ISO_FORTRAN_ENV.

If all images have failed or stopped, the program will terminate.

＜Related＞

CODIMENSION attribute, Image selectors, STAT= specifier


FAILED_IMAGES intrinsic function

Standard: F77 F90 F95 F2003 F2008 F2018 Example program

＜Syntax＞

FAILED_IMAGES ( [ TEAM, KIND ] )

TEAM : scalar of type TEAM_TYPE from the intrinsic module ISO_FORTRAN_ENV, whose value must identify the current team or an ancestor team;
KIND : scalar Integer constant expression;

Result: Integer or Integer(Kind=KIND). The result is an array of rank one.

＜Semantics＞

Returns the image numbers of images, in the specified team, known by the invoking image to have failed. The size of the result is the number of images known to have failed. If STAT_FAILED_IMAGE was returned for an operation with the specified team, the size will be non-zero.

If TEAM is absent, the specified team is the current team.

The KIND argument is completely unnecessary as default Integer is big enough to represent two billion images.

＜Related＞

FAIL IMAGE statement, FORM TEAM statement, IMAGE_STATUS intrinsic function, STOPPED_IMAGES intrinsic function


FINAL statement

Standard: F77 F90 F95 F2003 F2008 F2018 Example program

＜Syntax＞

The FINAL statement declares one or more final subroutines for a derived type; it only appears in the “type-bound procedure part” of a type definition. When an object of the type ceases to exist, one of these final subroutines will be called.

final-procedure-stmt ::= FINAL [ :: ] final-subroutine-name-list
final-subroutine-name-list ::= final-subroutine-name [ , final-subroutine-name ]...

Each final subroutine must be the name of a module procedure with exactly one argument; that argument must be a non-allocatable, non-optional, non-pointer, non-polymorphic variable of the derived type being defined, and must not have the INTENT(OUT) or VALUE attribute. No two final subroutines of a type may have a dummy argument with the same rank.

＜Semantics＞

When an object of the type is finalised, if there is a final subroutine that accepts the rank of the object that final subroutine will be called with the object as the actual argument. A final subroutine is permitted to be elemental, in which case it will be called if there is no other final subroutine for the rank of the object.

An object is finalised when it

  • is deallocated;
  • is the variable on the left-hand side of an assignment statement;
  • is passed to an INTENT(OUT) dummy argument;
  • is a function result value and the statement containing the function reference has finished execution;
  • is a local unsaved ordinary variable of a BLOCK construct and the BLOCK construct is exited;
  • is a local unsaved ordinary variable of a procedure and the procedure returns.

If a component is finalisable, any final subroutine for the object as-a-whole will be called before finalising any component. If the parent object is an array, each element has its components finalised separately; the final subroutine called is the one for the rank of the component, not the rank of the object.

If an object of extended type has a finalisable parent type, the parent is finalised after calling any final subroutine for the extended type itself (and after calling any final subroutine for the extended components).

Note that although final subroutines are declared in the type-bound procedure section, they are not type-bound procedures: they are not callable through the type-bound procedure calling mechanism, and they are not inherited.

＜Related＞

BLOCK construct, CLASS specifier, Component definition statement, Derived Type Definition, EXTENDS clause, TYPE statement


FINDLOC intrinsic function

Standard: F77 F90 F95 F2003 F2008 F2018 Example program

＜Syntax＞

FINDLOC ( ARRAY, VALUE, DIM [ , MASK , KIND , BACK ] )
FINDLOC ( ARRAY VALUE, [ , MASK , KIND , BACK ] )

ARRAY : rank N array of intrinsic type;
VALUE : scalar value that is comparable (with == or .EQV. to ARRAY);
DIM : scalar Integer in the range 1 to N;
MASK : array of type Logical and the same shape as ARRAY;
KIND : scalar Integer constant expression;
BACK : scalar Logical;

Result: Integer or Integer(Kind=KIND). In the form without DIM, the result is a vector of length N. In the form with DIM, the result has rank N−1 (thus scalar if ARRAY is a vector), and the shape is that of ARRAY with dimension DIM removed.

＜Semantics＞

Reduces an array (either completely, or by collapsing one dimension) by the “location of the specified value” pseudo-operation.

In the form without DIM, the result is the location of the specified value among the masked elements of ARRAY. In the form with DIM, each element of the result is the location of the specified value in the dimension DIM vector.

Note that the first element is location number one, regardless of the actual array bounds. If all elements are masked out, or the array has size zero, the result is zero.

If more than one element has the specified value, the location returned is the first such element (in array element order), unless the BACK argument is present with value .TRUE., in which case it is the last such element.

The KIND argument should be used if the array dimensions might be too large for default integer.

＜Related＞

MAXLOC intrinsic function, MAXVAL intrinsic function, MINLOC intrinsic function, MINVAL intrinsic function, Reduction intrinsic functions


FLOOR intrinsic function

Standard: F77 F90 F95 F2003 F2008 F2018 Example program

＜Syntax＞

FLOOR ( A [ , KIND ] )

A : Real;
KIND : scalar Integer constant expression;

Result : Integer or Integer(Kind=KIND).

＜Semantics＞

The value of the result is the largest integer less than or equal to A. Like many intrinsic functions, this is elemental; the result has the same shape as A, with the operation being applied elementwise.

＜Related＞

AINT intrinsic function, ANINT intrinsic function, CEILING intrinsic function, INT intrinsic function, NINT intrinsic function


FORALL construct

Standard: F77 F90 F95 F2003 F2008 Example program

＜Syntax＞

[ construct-name : ] FORALL forall-spec
forall-body-construct...
END FORALL [ construct-name ]

forall-spec ::= ( [ integer-type-spec :: ] triplet-spec-list [ , mask-expr ] )

triplet-spec-list ::= triplet [ , triplet ]...
triplet ::= name = expr : expr [ : expr ]

forall-body-construct | ::= | forall-asgn-stmt
 | | | forall-construct
 | | | forall-stmt
 | | | where-construct
 | | | where-stmt

forall-asgn-stmt | ::= | variable = expr
 | | | variable => expr

The blank between END and FORALL is optional. The END FORALL statement shall have the same construct-name as the FORALL construct statement, or no construct-name if the FORALL construct statement has none.

The mask-expr shall be scalar and of type Logical. All the triplet expressions shall be scalar and of type Integer. If integer-type-spec appears, each name has that type and kind; otherwise, each name has the type and kind it would have as a variable outside the construct, and that type shall be Integer.

＜Semantics＞

The iteration space of a FORALL construct is the cross-product of the sets of possible index values defined by each triplet, masked by the mask-expr (if present). The scope of the index names is limited to the FORALL construct (or statement); any variable with the same name outside the construct is unaffected.

Each forall-body-construct is processed completely (for the entire iteration space) before proceeding to the next.

A forall-asgn-stmt is processed by evaluating its expr for every element of the iteration space before the assignment or pointer assignment to the variables. If this assignment is a defined assignment, the procedure invoked must be pure.

Each statement in a nested FORALL or WHERE construct is executed fully (over the entire iteration space) before proceeding on to the next. Again, the masks and expressions are evaluated over the entire iteration space before any assignment.

Because of these semantics, execution of FORALL implicitly creates enormous temporary variables to hold the evaluated expressions and can only copy the values into the variables after evaluation is completed. When the programmer knows that there is no conflict between the variables and expressions but it is difficult for the compiler to tell, the FORALL construct will be much slower than the equivalent set of DO loops. For this reason, FORALL should be avoided when possible; instead, use normal DO loops (or a DO CONCURRENT construct), array assignment or a WHERE construct.

The FORALL construct is considered obsolescent in Fortran 2018.

＜Related＞

Array Assignment, Array Constructor, Array Section, DO CONCURRENT construct, FORALL statement, INTEGER type, PURE attribute, WHERE construct, WHERE statement


FORALL statement

Standard: F77 F90 F95 F2003 F2008 F2018 Example program

＜Syntax＞

FORALL forall-spec forall-asgn-stmt

forall-spec ::= ( [ integer-type-spec :: ] triplet-spec-list [ , mask-expr ] )

triplet-spec-list ::= triplet [ , triplet ]...
triplet ::= name = expr : expr [ : expr ]

forall-asgn-stmt | ::= | variable = expr
 | | | variable => expr

＜Semantics＞

The FORALL statement is equivalent to a FORALL construct containing only a single Forall Assignment statement, i.e.
FORALL forall-spec forall-asgn-stmt
is exactly the same as
FORALL forall-spec
forall-asgn-stmt
END FORALL

Like the FORALL construct, the FORALL statement is not recommended for normal use. Whenever possible, use normal DO loops (or a DO CONCURRENT construct), array assignment or a WHERE construct instead.

The FORALL statement is considered obsolescent in Fortran 2018.

＜Related＞

Array assignment, DO CONCURRENT construct, FORALL construct, INTEGER type, WHERE statement, WHERE construct


FORM TEAM statement

Standard: F77 F90 F95 F2003 F2008 F2018 Example program

＜Syntax＞

FORM TEAM ( team-number , team-variable [ , form-team-spec ]... )

team-number ::= scalar-integer-expr
The team number value must be positive.

The team-variable must be of type TEAM_TYPE from the intrinsic module ISO_FORTRAN_ENV. Variables of that type are not permitted to be coarrays.

form-team-spec | ::= | ERRMSG = errmsg-variable
 | | | NEW_INDEX = scalar-integer-expr
 | | | STAT = stat-variable

At most one of each kind of form-team-spec is allowed. A stat-variable must be a non-coindexed scalar Integer variable, and should be able to support values from −9999 to +9999, i.e. it should be at least 16 bits. An errmsg-variable must be a non-coindexed default Character variable. The scalar-integer-expr in NEW_INDEX= must be positive.

＜Semantics＞

The number of subteams that execution of FORM TEAM produces is equal to the number of unique team-number values in that execution; each unique team-number value identifies a subteam in the set, and each image belongs to the subteam whose team number it specified. If NEW_INDEX= appears, it specifies the image number that the image will have in its new subteam, and therefore must be in the range 1 to N, where N is the number of images in that subteam, and must be unique. If NEW_INDEX= does not appear, it is processor-dependent what the image number in the new subteam will be.

All active images in the current team must execute the same FORM TEAM statement.

If STAT= appears and no error occurs, zero is assigned to the stat-variable. If any of the images in the current team has stopped, STAT_STOPPED_IMAGE is assigned to the stat-variable. If no other error occurs, but an image has failed, STAT_FAILED_IMAGE is assigned. If any error other than a stopped or failed image occurs, some other positive value is assigned. If STAT= does not appear and an error occurs, the program will be error-terminated. If both STAT= and ERRMSG= appear, and any error occurs, an explanatory message is assigned to the errmsg-variable.

If no error occurs or the only error is a failed image, there is an implicit synchronisation of all active images and the team-variable becomes defined on those images with a valid team value. If any error other than a failed image occurs, team-variable becomes undefined and there is no guarantee of synchronisation.

＜Related＞

CHANGE TEAM construct, ERRMSG= specifier, Image control statements, STAT= specifier


FORMAT statement
 Standard: (F77) (F90) F95 F2003 F2008 Example Program
<Syntax>
FORMAT ( [ format-list ] [ infinite-repeat-item ] )

format-list ::= format-item [ , format-item ]...
format-item | ::= | [ repeat ] data-edit
 | | | [ repeat ] ( format-list )
 | | | other-edit
infinite-repeat-item ::= * ( format-list )
data-edit | ::= | iboz-edit w [ . m ]
 | | | fd-edit w [ . d ]
 | | | eg-edit w . d [ E e ]
 | | | L w
 | | | A [ w ]
 | | | G0 [ . d ]
other-edit | ::= | t-edit digit-string
 | | | digit-string px-edit
 | | | digit-stringHtext
 | | | character-string
 | | | rounding-edit
 | | | misc-edit

repeat, w, m, d and e are all digit-string.
iboz-edit ::= I | B | O | Z
fd-edit ::= F | D
eg-edit ::= E | EN | ES | G
t-edit ::= T | TR | TL
px-edit ::= P | X | /
rounding-edit ::= RC | RD | RN | RP | RU | RZ
misc-edit ::= BN | BZ | DC | DP | S | SP | SS | / | :

In digit-stringHtext, the text following the H has exactly the number of characters specified by its digit-string; this edit descriptor was deleted in Fortran 95 because it is error-prone and less convenient than simply using a character string.

Note: the comma between adjacent format-items may be omitted only as follows:
  • between a P descriptor and a following D, E, EN, ES, F or G descriptor (prior to Fortran 2003, this is only allowed when the optional repeat is not present);
  • before a / descriptor that has no preceding digit-string;
  • after a / descriptor;
  • before or after a : descriptor.

    The field width w is used to indicate minimal width editing for the B, F, I, O and Z edit descriptors. In all other cases, w must be positive.

    • <Semantics>

    The FORMAT statement specifies a format, which may be used in a data transfer statement (PRINT, READ and WRITE) for formatted input/output. The FORMAT statement must be labelled, and it is this label that is specified in the FMT= specifier. The interpretation of each edit descriptor is given in the table below.

    Note that an explicit format may also be specified as a character string; in this case the character string is interpreted in the same way as the FORMAT statement. Also, list-directed (FMT=*) and namelist formatting (NML=namelist-name) is possible instead of explicit formatting. These two cases leave the formatting details up to the compiler and are not under user control.

    In Fortran 2008, an infinite-repeat-item can appear at the end of the format specification. As the name implies, this acts the same as an infinite repeat count — it repeats until terminated by exhaustion of the list of effective items on a colon or data edit descriptor; a data edit descriptor such as I must appear inside the infinite repetition.

    Format Item | Semantics | Example
Character string | Output of specified character string | 'abc'
/ | Advance to next record | /
: | Finish if no data items left in input list | :
A | Character type data transfer | A10
B | Integer type data transfer, binary radix | B8
BN | Blanks in numeric input are null (ignored) | BN
BZ | Blanks in numeric input are treated as zeros | BZ
D | Real type data transfer, exponential form with letter D | D12.4
DC | Change decimal edit mode to 'COMMA' | DC
DP | Change decimal edit mode to 'POINT' | DP
E | Real type data transfer, exponential form | E12.4
EN | Real type data transfer, engineering notation (exponent divisible by 3) | EN12.4
ES | Real type data transfer, scientific notation (first digit non-zero) | ES12.4
F | Real type data transfer, no exponent | F6.3
G | Generalised data transfer, form varies | G16.8
G0 | Generalised minimal width data transfer, form varies | G0.7
H | Output of specified text | nHa1a2...an
I | Integer type data transfer, decimal radix | I9
L | Logical type data transfer | L1
O | Integer type data transfer, octal radix | O3
P | Set scale factor to k | kP
RC | Compatible rounding (halves away from zero) | RC
RD | Round down (towards −∞) | RC
RN | Round to nearest (halves to even) | RN
RP | Processor-dependent rounding | RP
RU | Round up (towards +∞) | RU
RZ | Round towards zero | RZ
S | Processor-dependent “+” on positive values | S
SP | Produce “+” on positive values | SP
SS | Suppress “+” on positive values | SS
T | Move to position n in the current record | T10
TL | Move n positions to the left in the current record | T10
TR | Move n positions to the right in the current record | TR10
X | Move right n places | 6X
Z | Integer type data transfer, hexadecimal radix | Z8
    <Related>
    ASSIGN statement, BACKSPACE statement, CLOSE statement, DECIMAL= specifier, ENDFILE statement, NML= specifier, OPEN statement, PRINT statement, READ statement, REWIND statement, SIGN= specifier, WRITE statement


<Example Program 1>

Program format_example_1
Character(3) :: moji
Read (*,Fmt=50) ix,moji,z
50 Format (I5,A3,F10.0)
Print *,ix,moji,z
End
Example Input (with Q for each blank character)

QQ123ABCQQQQQ2.345

Execution Results

123 ABC 2.3450000

<Example Program 2>

Program format_example_2
Print 60, 123,'EFG',234.567
60 Format (' Answer:',I5,A3,F8.2)
End
Execution Results (with Q for each blank character)

QAnswer:QQ123EFGQQ234.57


FRACTION intrinsic function
Standard: F77 F90 F95 F2003 F2008 Example Program
<Syntax>
 | FRACTION ( X ) X : Real, any kind; Result: Same type and kind as X.
<Semantics>
 | Returns the mantissa of X in the real model for that kind of floating-point number; if X is finite, this is a value between 1/RADIX(X) and 1. If the value of X is representable in that model, the result satisfies the relationship X = FRACTION(X)*(REAL(RADIX(X),KIND(X))**EXPONENT(X), or if X is an IEEE infinity or NaN, the result is an IEEE NaN. Note that if X is double-double precision, FRACTION(X) might not be accurate but the result of EXPONENT(X) is. Like many intrinsic functions, this is elemental; the result has the same shape as X, with the operation being applied elementwise.
<Related>
 | DIGITS intrinsic function, EXPONENT intrinsic function, MAXEXPONENT intrinsic function, MINEXPONENT intrinsic function, RADIX intrinsic function, REAL type, SET_EXPONENT intrinsic function.


FRACTION example program

<Example Program>

Program fraction_example
  Real :: x(3) = [ 1.5*2.0**(-100), 1.5, 1.5*2.0**100 ]
  Integer i
  Do i=1, Size(x)
    Print *, x(i), '=', Fraction(x(i)), '*', Radix(x), '**', Exponent(x(i))
  End Do
End Program
Execution Results

   1.1832914E-30 =   0.7500000 * 2 ** -99
   1.5000000 =   0.7500000 * 2 ** 1
   1.9014759E+30 =   0.7500000 * 2 ** 101


FUNCTION statement

Standard: (F77) F90 F95 F2003 F2008 F2018 Example program

＜Syntax＞

[ prefix ]... FUNCTION name args [ suffix ]...

args ::= ( [ name [ , name ]... ] )

prefix | ::= | ELEMENTAL
 | | | IMPURE
 | | | MODULE
 | | | NON_RECURSIVE
 | | | PURE
 | | | RECURSIVE
 | | | type-spec

suffix | ::= | BIND ( C [ , NAME=expression ] )
 | | | RESULT(name)

Only one occurrence of any particular prefix or suffix is allowed in a single FUNCTION statement. If IMPURE appears, PURE must not appear. If MODULE appears, the interface or definition must be for a separate module procedure. If NON_RECURSIVE appears, RECURSIVE must not appear.

The FUNCTION statement can only occur as the first statement of a function subprogram or interface body. The syntax of a function subprogram is as follows.
function-stmt
specification-part
executable-part
[ contains-stmt
[ internal-subprogram ]... ]
end-function-stmt
An internal-subprogram is a function-subprogram or a subroutine-subprogram, and is not allowed to itself have a contains-stmt.

The syntax of a function interface body is simply:

function-stmt
specification-part
end-function-stmt

＜Semantics＞

The FUNCTION statement begins a function subprogram or interface body. If no RESULT variable is specified the result variable has the same name as the function name. If the type is not specified on the FUNCTION statement, it may be implicitly typed or the result variable may be explicitly declared.

Note that for direct recursion, a RESULT clause is necessary as well as the RECURSIVE attribute. In Fortran 2018, a procedure without NON_RECURSIVE has the RECURSIVE attribute by default, except for a CHARACTER(LEN=*) function.

＜Related＞

BIND attribute, CALL statement, CONTAINS statement, ELEMENTAL attribute, END FUNCTION statement, ENTRY statement, IMPURE attribute, NON_RECURSIVE attribute, PURE attribute, RECURSIVE attribute, RESULT clause, RETURN statement, Separate module procedures SUBROUTINE statement


GAMMA intrinsic function

Standard: F77 F90 F95 F2003 F2008 F2018 Example program

＜Syntax＞

GAMMA ( X )

X : Real;

Result : Same type and kind as X.

The value of X shall not be a negative integer or zero.

＜Semantics＞

The value of the result is an approximation to the gamma function of X. The gamma function is the extension of factorial from the integers to the reals, so that when X is a positive integer, GAMMA(X) is an approximation to (X−1)! i.e. the factorial of (X−1). Like many intrinsic functions, this is elemental; the result has the same shape as X, with the operation being applied elementwise.

This function grows extremely rapidly with increasing X, so will overflow for quite modest values of X.

＜Related＞

LOG_GAMMA intrinsic function


.GE. (>=) operator

Standard: (F77) F90 F95 F2003 F2008 F2018 Example program

＜Syntax＞

expression .GE. expression
expression >= expression

Each expression must be of type Integer, Real or Character.

＜Semantics＞

Compares two expressions, returning .TRUE. if and only if the first expression is greater than or equal to the second. The expressions must be both either Integer or Real, or both Character. If they are of type Character, the native collating sequence is used (this might differ from ASCII).

＜Related＞

.AND. operator, Concatenation (//) operator, .EQ. (==) operator, .EQV. operator, .GT. (>) operator, .LE. (<=) operator, .LT. (<) operator, .NE. (/=) operator, .NEQV. operator, .NOT. operator, Numeric operators, Operator precedence, .OR. operator


GENERIC statement

Standard: F77 F90 F95 F2003 F2008

＜Syntax＞

The GENERIC statement declares a generic type-bound procedure, which is a set of specific type-bound procedures with a generic identifier; it only appears in the “type-bound procedure part” of a type definition.

generic-type-bound-procedure ::= GENERIC [ , access ] :: generic-spec => type-bound-procedure-name-list
access ::= PRIVATE | PUBLIC
type-bound-procedure-name-list ::= type-bound-procedure-name [ , type-bound-procedure-name ]...

generic-spec | ::= | name
 | | | ASSIGNMENT (=)
 | | | OPERATOR (operator)
 | | | read-or-write (form)

read-or-write ::= READ | WRITE
form ::= FORMATTED | UNFORMATTED

For full syntax and semantics, see the type-bound procedure page.

＜Semantics＞

Each generic type-bound procedure statement either defines a new type-bound generic or extends an existing type-bound generic. If a type-bound generic is an operator or assignment, the PASS attribute is required on each specific type-bound procedure, and is used to determine which object is the invoking object. Note that unlike operators, assignment and defined i/o defined by an INTERFACE block, type-bound operators, assignment and defined i/o are always accessible whenever an object of the type is accessible, i.e. they are not blocked by the ONLY clause on a USE statement.

＜Related＞

CLASS specifier, Component definition statement, Derived Type Definition, EXTENDS clause, INTERFACE ASSIGNMENT statement, INTERFACE OPERATOR statement, NOPASS attribute, PASS attribute, PRIVATE attribute, PUBLIC attribute, TYPE statement


GET_COMMAND intrinsic subroutine

Standard: F77 F90 F95 F2003 F2008 F2018 Example program

＜Syntax＞

Call GET_COMMAND ( [ COMMAND, LENGTH, STATUS, ERRMSG ] )

COMMAND : scalar default Character, Intent(Out);
LENGTH : scalar Integer, 16 bits or larger, Intent(Out);
STATUS : scalar Integer, 16 bits or larger, Intent(Out);
ERRMSG : scalar default Character, Intent(Out).

Prior to Fortran 2018, the Integer arguments had to be of default kind.

＜Semantics＞

This intrinsic subroutine retrieves the command line for the current execution of the program, and assigns it to the COMMAND argument (if present), as if by normal character assignment.

If LENGTH is present, it is assigned the length of the command line (before its assignment to COMMAND). This may be used to allocate a COMMAND variable large enough to receive the full value of the argument.

If STATUS is present, it is assigned the value −1 if COMMAND was present but is shorter than the command line length, a positive value if an error occurs, and zero otherwise.

If an error occurs and ERRMSG is present, ERRMSG is assigned an explanatory message. Otherwise, ERRMSG is unchanged.

＜Related＞

COMMAND_ARGUMENT_COUNT intrinsic function, GET_COMMAND_ARGUMENT intrinsic subroutine


GET_COMMAND_ARGUMENT intrinsic subroutine

Standard: F77 F90 F95 F2003 F2008 F2018 Example program

＜Syntax＞

Call GET_COMMAND_ARGUMENT ( NUMBER [ , VALUE , LENGTH , STATUS, ERRMSG ] )

NUMBER : scalar Integer, 16 bits or larger, Intent(In);
VALUE : scalar default Character, Intent(Out);
LENGTH : scalar Integer, 16 bits or larger, Intent(Out);
STATUS : scalar Integer, 16 bits or larger, Intent(Out);
ERRMSG : scalar default Character, Intent(Out).

Prior to Fortran 2018, the Integer arguments had to be of default kind.

＜Semantics＞

This intrinsic subroutine retrieves the command argument for the current execution identified by NUMBER. Argument 0 is the “command name”, this might be a simple name, the full path name of the executable program (or anything in between), or blank if the command name cannot be determined. Remaining arguments, up to the number specified on the command line, are number 1 to COMMAND_ARGUMENT_COUNT() from left to right. If NUMBER is less than zero or greater than COMMAND_ARGUMENT_COUNT() an error will be produced.

If VALUE is present, it is assigned the value of the command argument as if by normal character assignment.

If LENGTH is present, it is assigned the length of the command argument (before its assignment to VALUE). This may be used to allocate a VALUE variable large enough to receive the full value of the argument.

If STATUS is present, it is assigned the value −1 if VALUE was present but is shorter than the command argument length, a positive value if an error occurs (for example, if NUMBER is out of range), and zero otherwise.

If an error occurs and ERRMSG is present, ERRMSG is assigned an explanatory message. Otherwise, ERRMSG is unchanged.

＜Related＞

COMMAND_ARGUMENT_COUNT intrinsic function, GET_COMMAND intrinsic subroutine


GET_ENVIRONMENT_VARIABLE intrinsic subroutine

Standard: F77 F90 F95 F2003 F2008 F2018 Example program

＜Syntax＞

Call GET_ENVIRONMENT_VARIABLE ( NAME [, VALUE, LENGTH , STATUS, TRIM_NAME, ERRMSG ] )

NAME : scalar default Character, Intent(In);
VALUE : scalar default Character, Intent(Out);
LENGTH : scalar Integer, 16 bits or larger, Intent(Out);
STATUS : scalar Integer, 16 bits or larger, Intent(Out);
TRIM_NAME : scalar Logical, Intent(In);
ERRMSG : scalar default Character, Intent(Out).

Prior to Fortran 2018, the Integer and Logical arguments had to be of default kind.

＜Semantics＞

This intrinsic subroutine retrieves the value of the environment called identified by NAME, and assigns it to the VALUE argument (if present), as if by normal character assignment.

If LENGTH is present, it is assigned the length of the environment variable's value (before its assignment to VALUE). This may be used to allocate a VALUE variable large enough to receive the full value of the argument.

If STATUS is present, it is assigned the value −1 if VALUE was present but is shorter than the environment variable, 1 if the environment variable does not exist, 2 if the processor does not support environment variables, a value greater than 2 if any other error occurs, and zero otherwise.

If TRIM_NAME is present with the value .FALSE., and the processor supports environment variable names having trailing blanks, any trailing blanks in NAME are considered to be part of the name of the environment variable. Otherwise, trailing blanks in NAME are ignored.

If an error occurs and ERRMSG is present, ERRMSG is assigned an explanatory message. Otherwise, ERRMSG is unchanged.

＜Related＞

COMMAND_ARGUMENT_COUNT intrinsic function, GET_COMMAND intrinsic subroutine, GET_COMMAND_ARGUMENT intrinsic subroutine


GET_TEAM intrinsic function

Standard: F77 F90 F95 F2003 F2008 F2018 Example program

＜Syntax＞

GET_TEAM ( [ LEVEL ] )

LEVEL : scalar Integer, equal to one of the named constants CURRENT_TEAM, INITIAL_TEAM or PARENT_TEAM from the intrinsic module ISO_FORTRAN_ENV;

Result : scalar of type TEAM_TYPE from the intrinsic module ISO_FORTRAN_ENV.

＜Semantics＞

This return a team value that identifies the specified team (containing the executing image). This value can be used in other intrinsic procedures and image selectors, as well as some image control statements.

＜Related＞

Image selectors, NUM_IMAGES intrinsic function, SYNC TEAM statement, THIS_IMAGE intrinsic function


GO TO statement

Standard: F77 F90 F95 F2003 F2008 F2018 Example program

＜Syntax＞

GO TO label

The blank between GO and TO is optional. The label must identify a branch target statement (and not, for example, a declaration statement).

There is also a computed GOTO statement; this is error-prone and obsolescent since Fortran 95, so the CASE construct should be used instead. The syntax of the computed GOTO statement is as follows.

GO TO ( label [ , label ]... ) expression

The expression must be a scalar Integer.

There is also an assigned GOTO statement, but it is very error-prone and has therefore been deleted from Fortran 95. Its syntax is as follows.

GO TO variable-name [ ( label [ , label ]... ) ]

The variable-name must be a scalar Integer.

＜Semantics＞

The GOTO statement transfers control to the statement with the specified label. Note that transfer of control into a construct (such as a DO loop or IF-THEN) from outside is prohibited.

The computed GOTO statement transfers control to the ith label in the list, according to the value of the expression; if the value is less than one or greater than the number of labels in the list, execution continues with the statement following the computed GOTO.

The assigned GOTO statement transfers control to the last label assigned to the variable by the ASSIGN statement.

＜Related＞

ASSIGN statement, CASE construct, CONTINUE statement, CYCLE statement, DO construct, DO WHILE statement, END DO statement, EXIT statement


.GT. (>) operator

Standard: (F77) F90 F95 F2003 F2008 F2018 Example program

＜Syntax＞

expression .GT. expression
expression > expression

Each expression must be of type Integer, Real or Character.

＜Semantics＞

Compares two expressions, returning .TRUE. if and only if the first expression is greater than the second. The expressions must be both either Integer or Real, or both Character. If they are of type Character, the native collating sequence is used (this might differ from ASCII).

＜Related＞

.AND. operator, Concatenation (//) operator, .EQ. (==) operator, .EQV. operator, .GE. (>=) operator, .LE. (<=) operator, .LT. (<) operator, .NE. (/=) operator, .NEQV. operator, .NOT. operator, Numeric operators, Operator precedence, .OR. operator


HUGE intrinsic function

Standard: F77 F90 F95 F2003 F2008 F2018 Example program

＜Syntax＞

HUGE ( X )

X : Integer or Real;
Result : Scalar, same type and kind as X.

＜Semantics＞

This function returns the largest “model number” for the type and kind of X.

This is an inquiry function, so X need not be defined; indeed, it is permitted to be disassociated, unallocated, or absent.

The model for integer type is as a sign together with DIGITS(X) digits of radix RADIX(X); the HUGE value is therefore DIGITS(X) digits that are all equal to RADIX(X)−1. For example, the model for 8-bit integers has 7 digits of radix 2, and therefore HUGE(0_int8) is equal to B'01111111'.

The model for real type is that it may be zero or a signed fraction between 1 and 1/RADIX(X) consisting of DIGITS(X) digits, multiplied by an exponent RADIX(X)**e with MINEXPONENT(X)≤e≤MAXEXPONENT(X). Thus the largest model number is the value obtained for the fraction just less than 1 (i.e. all digits set to RADIX(X)−1) and with e equal to MAXEXPONENT(X).

Note that HUGE(X) is not necessarily the largest possible value for X; for example, with IEEE floating-point, the largest possible value is +∞, which is infinitely bigger than HUGE(X). It is, however, likely to be the largest value for which the full precision of DIGITS(X) of radix RADIX(X) is available.

＜Related＞

DIGITS intrinsic function, EPSILON intrinsic function, INTEGER type, MAXEXPONENT intrinsic function, MINEXPONENT intrinsic function, RADIX intrinsic function, REAL type, TINY intrinsic function


HYPOT intrinsic function

Standard: F77 F90 F95 F2003 F2008 Example program

＜Syntax＞

HYPOT ( X , Y )

X : Real;
Y : Same type and kind as X, conformable with X;

Result : Same type and kind as X.

＜Semantics＞

The value of the result is an approximation to the Euclidean distance function of X and Y, mathematically equivalent to SQRT(X**2+Y**2), calculated without undue overflow or underflow. Like many intrinsic functions, this is elemental; if either (or both) of X and Y is an array, the result will be an array with that shape, with the value being computed elementwise.

This function gives exactly the same result as ABS(CMPLX(X,Y,KIND(X))).

＜Related＞

ABS intrinsic function, SQRT intrinsic function


IACHAR intrinsic function

Standard: F77 F90 F95 F2003 F2008 F2018

＜Syntax＞

IACHAR ( C [ , KIND ] )

C : Character with length one;
KIND : scalar Integer constant expression;

Result : Integer or Integer(Kind=KIND).

＜Semantics＞

Convert single Character value to ASCII character code; this is the inverse of the ACHAR intrinsic function. Like many intrinsic functions, this is elemental; the result has the same shape as C, with the operation being applied elementwise.

Fortran 2003 adds the optional KIND argument; this is totally useless since every character set in the world can be represented in a default Integer and ASCII itself only goes up to 127.

WARNING: If the character is not in the ASCII character set, the result is not defined; this means that ACHAR(CHAR(X)) might not give you back the original value of X, and indeed that just because the return value is in the range 0-127 does not mean that the character is actually an ASCII character. That means it is risky to use this when processing European characters (the ISO 8859-n family), and it is totally unsuitable for processing Japanese (JIS 0213) or Unicode (ISO/IEC 10646) characters.

＜Related＞

ACHAR intrinsic function, CHAR intrinsic function, CHARACTER type, ICHAR intrinsic function


IALL intrinsic function

Standard: F77 F90 F95 F2003 F2008 F2018 Example program

＜Syntax＞

IALL ( ARRAY, DIM [ , MASK ] )
IALL ( ARRAY [ , MASK ] )

ARRAY : rank N array of type Integer;
DIM : scalar Integer in the range 1 to N;
MASK : array of type Logical with the same shape as ARRAY;

Result: Same type and kind as ARRAY.

＜Semantics＞

The result is ARRAY reduced by bitwise and (the IAND intrinsic function). If DIM is absent, this is a scalar equal to the bitwise and of all the masked elements of ARRAY. If DIM is present, the result has rank N-1 and the shape of ARRAY with dimension DIM removed; each element of the result is the bitwise and of the masked elements in that dimension.

If no elements contribute to a result value, that value is NOT(zero).

＜Related＞

Array-array operations, Array-scalar operations, ALL intrinsic function, ANY intrinsic function, COUNT intrinsic function, IAND intrinsic function, IANY intrinsic function, IPARITY intrinsic function, MAXLOC intrinsic function, MAXVAL intrinsic function, MINLOC intrinsic function, MINVAL intrinsic function, PARITY intrinsic function, PRODUCT intrinsic function, Reduction intrinsic functions, SUM intrinsic function


IAND intrinsic function

Standard: F77 F90 F95 F2003 F2008 F2018 Example program

＜Syntax＞

IAND ( I, J )

I : Integer or boz-literal-constant;
J : Integer or boz-literal-constant, conformable with I, if I and J are both Integer, same kind as I;

Result : Integer, same kind as I or J (whichever one is Integer).

At least one of I and J must be Integer.

＜Semantics＞

The value of the result is the bitwise and of I and J; each bit in the result is 1 if and only if both the corresponding bits of I and J are 1. This is an elemental function; if any argument is an array the result is an array of the same shape, with the IAND operation being applied elementwise.

＜Related＞

IALL intrinsic function, IEOR intrinsic function, IOR intrinsic function, ISHFT intrinsic function, ISHFTC intrinsic function, LEADZ intrinsic function, MASKL intrinsic function, MASKR intrinsic function, NOT intrinsic function, SHIFTA intrinsic function, SHIFTL intrinsic function, SHIFTR intrinsic function, TRAILZ intrinsic function


IANY intrinsic function

Standard: F77 F90 F95 F2003 F2008 F2018 Example program

＜Syntax＞

IANY ( ARRAY, DIM [ , MASK ] )
IANY ( ARRAY [ , MASK ] )

ARRAY : rank N array of type Integer;
DIM : scalar Integer in the range 1 to N;
MASK : array of type Logical with the same shape as ARRAY;

Result: Same type and kind as ARRAY.

＜Semantics＞

The result is ARRAY reduced by bitwise or (the IOR intrinsic function). If DIM is absent, this is a scalar equal to the bitwise or of all the masked elements of ARRAY. If DIM is present, the result has rank N−1 and the shape of ARRAY with dimension DIM removed; each element of the result is the bitwise or of the masked elements in that dimension.

If no elements contribute to a result value, that value is zero.

＜Related＞

Array-array operations, Array-scalar operations, ALL intrinsic function, ANY intrinsic function, COUNT intrinsic function, IALL intrinsic function, IOR intrinsic function, IPARITY intrinsic function, MAXLOC intrinsic function, MAXVAL intrinsic function, MINLOC intrinsic function, MINVAL intrinsic function, PARITY intrinsic function, PRODUCT intrinsic function, Reduction intrinsic functions, SUM intrinsic function


IBCLR intrinsic function

Standard: F77 F90 F95 F2003 F2008 F2018 Example program

＜Syntax＞

IBCLR ( I, POS )

I : Integer;
POS : Integer, conformable with I, 0≤POS<BIT_SIZE(I);

Result : Same type and kind as I.

＜Semantics＞

The value of the result is I with bit POS set to zero; the least significant bit (value 1) is bit 0, the most significant bit is bit BIT_SIZE(I)−1. This is an elemental function; if any argument is an array the result is an array of the same shape, with the IBCLR operation being applied elementwise.

＜Related＞

BIT_SIZE intrinsic function, BTEST intrinsic function, IBSET intrinsic function


IBITS intrinsic function

Standard: F77 F90 F95 F2003 F2008 F2018 Example program

＜Syntax＞

IBITS ( I, POS, LEN )

I : Integer;
POS : Integer, conformable with I, POS≥0;
LEN : Integer, conformable with I, LEN≥0, POS+LEN≤BIT_SIZE(I);

Result : Same type and kind as I.

＜Semantics＞

The value of the result is the LEN bits of I from POS to POS+LEN−1, right-shifted by POS places. This will be equal to IAND(SHIFTR(I, POS), MASKR(LEN, KIND(I))). This is an elemental function; if any argument is an array the result is an array of the same shape, with the IBITS operation being applied elementwise.

＜Related＞

BIT_SIZE intrinsic function, IAND intrinsic function, IBCLR intrinsic function, IBSET intrinsic function, MASKR intrinsic function, MVBITS intrinsic subroutine, SHIFTR intrinsic function


IBSET intrinsic function

Standard: F77 F90 F95 F2003 F2008 F2018 Example program

＜Syntax＞

IBSET ( I, POS )

I : Integer;
POS : Integer, conformable with I, 0≤POS<BIT_SIZE(I);

Result : Same type and kind as I.

＜Semantics＞

The value of the result is I with bit POS set to one; the least significant bit (value 1) is bit 0, the most significant bit is bit BIT_SIZE(I)−1. This is an elemental function; if any argument is an array the result is an array of the same shape, with the IBSET operation being applied elementwise.

＜Related＞

BIT_SIZE intrinsic function, BTEST intrinsic function, IBCLR intrinsic function


ICHAR intrinsic function

Standard: F77 F90 F95 F2003 F2008 F2018

＜Syntax＞

ICHAR ( C [ , KIND ] )

C : Character with length one;
KIND : scalar Integer constant expression;

Result : Integer or Integer(Kind=KIND).

＜Semantics＞

Convert single Character value to native character code. Like many intrinsic functions, this is elemental; the result has the same shape as C, with the operation being applied elementwise.

Fortran 2003 adds the optional KIND argument; this is totally useless since every character set in the world can be represented in a default Integer.

＜Related＞

ACHAR intrinsic function, CHAR intrinsic function, CHARACTER type, IACHAR intrinsic function


ID= specifier

Standard: F77 F90 F95 F2003 F2008 F2018

＜Syntax＞

ID = expression

The expression must be a scalar integer expression. ID= is permitted in the INQUIRE, READ, WAIT and WRITE statements. In the READ and WRITE statements, the expression must be a variable designator, and is only permitted with ASYNCHRONOUS='YES'.

＜Semantics＞

The ID= specifier identifies an asynchronous input/output operation; in the asynchronous READ and WRITE statements, it is assigned a value identifying that operation. In the INQUIRE statement, it identifies the operation pertaining to the PENDING= specifier. In the WAIT statement, it identifies the operation to be waited on.

Note that in INQUIRE and WAIT, the value must be one that was assigned in the ID= clause of an asynchronous READ or WRITE, and one that has not been previously waited on.

Note that in the INQUIRE statement, if PENDING= returns .TRUE. then the ID= value has implicitly been waited on.

＜Related＞

ASYNCHRONOUS attribute, ASYNCHRONOUS= specifier, INQUIRE statement, PENDING= specifier, READ statement, WRITE statement


IEOR intrinsic function

Standard: F77 F90 F95 F2003 F2008 F2018 Example program

＜Syntax＞

IEOR ( I, J )

I : Integer or boz-literal-constant;
J : Integer or boz-literal-constant, conformable with I, if I and J are both Integer, same kind as I;

Result : Integer, same kind as I or J (whichever one is Integer).

At least one of I and J must be Integer.

＜Semantics＞

The value of the result is the bitwise exclusive or of I and J; each bit in the result is 1 if and only if exactly one of the corresponding bits of I and J is 1. This is an elemental function; if any argument is an array the result is an array of the same shape, with the IEOR operation being applied elementwise.

＜Related＞

IAND intrinsic function, IOR intrinsic function, IPARITY intrinsic function, ISHFT intrinsic function, ISHFTC intrinsic function, LEADZ intrinsic function, MASKL intrinsic function, MASKR intrinsic function, NOT intrinsic function, SHIFTA intrinsic function, SHIFTL intrinsic function, SHIFTR intrinsic function, TRAILZ intrinsic function


IF construct
Standard: F77 F90 F95 F2003 Example Program
<Syntax>
 | if-then-stmt block [ else-if-stmt block ]... [ else-stmt block ] end-if-stmt
<Semantics>
 | The IF construct selects a single block of statements for execution. The conditions (expressions) in the IF THEN statement and the ELSE IF statements are evaluated in order until one has the value true; if this is found, the block following that statement is executed. If all the conditions are false, the ELSE block will be executed if present; with all conditions false and no ELSE block, control will be transferred to the END IF statement.
<Related>
 | ELSE statement, ELSE IF statement, END IF statement, IF statement, IF THEN statement


<Example Program 1>

Program if_construct_example_1
Integer x
Read *, x
If (Mod(x,2)==0) Then
Print *, 'even',x
Else If (x<0) Then
Print *, 'odd negative',x
End If
End
Example Input 1

4

Execution Results

even 4
Example Input 2

-7

Execution Results

odd negative -7

<Example Program 2>

Program if_construct_example_2
Integer x
Read *, x
eventest: If (Mod(x,2)==0) Then
Print *, 'even'
If (x==4) Then
Print *, 'four'
End If
End If eventest
End
Example Input 1

2

Execution Results

even
Example Input 2

4

Execution Results

even
four


IF statement
Standard: F77 F90 F95 F2003 Example Program
<Syntax>
 | IF ( expression ) executable The expression must be a scalar Logical. The executable cannot itself be an IF statement, nor any statement that begins or ends a construct. There is also an arithmetic IF statement, but it is error-prone and obsolescent. Its syntax is as follows. IF ( expression ) label , label , label The expression must be a scalar Real or Integer.
<Semantics>
 | The IF statement controls a single executable statement, which is executed if and only the expression is true. The arithmetic IF statement transfers control to the first label if the expression is negative, to the second label if it is zero, and the third label if it is positive. For type Real, both negative and positive zero are treated as zero.
<Related>
 | ELSE statement, ELSE IF statement, END IF statement, IF construct, IF THEN statement


<Example Program>

Program if_example
Integer x
Read *,x
If (Mod(x,2)==0) Print *, 'even',x
End
Example Input

4

Execution Results

even 4


IF THEN statement
Standard: F77 F90 F95 F2003 Example Program
<Syntax>
 | [ construct-name : ] IF (expression) THEN The expression must be a scalar Logical.
<Semantics>
 | The IF-THEN statement begins an IF construct, marking the beginning of the THEN block. That block is executed if and only if the expression in the IF-THEN statement is true. If this statement has a construct name, the corresponding END IF statement must have the same construct name, and intervening ELSE and ELSE IF statements at the same level may have the same construct name.
<Related>
 | ELSE statement, ELSE IF statement, END IF statement, IF construct, IF statement


<Example Program 1>

Program ifthen_example_1
Integer x
Read *, x
If (Mod(x,2)==0) Then
Print *, 'even',x
End If
End
Example Input

4

Execution Results

even 4

<Example Program 2>

Program ifthen_example_2
Integer x
Read *, x
If (Mod(x,2)==0) Then
Print *, 'even'
If (x==4) Then
Print *, 'four'
End If
End If
End
Example Input 1

2

Execution Results

even
Example Input 2

4

Execution Results

even
four


Image control statements

Standard: F77 F90 F95 F2003 F2008 F2018

＜Semantics＞

Execution on each image is divided into segments, by “image control statements”. The segments on a single image are ordered: each segment follows the preceding segment. Segments on diffrrent images may be ordered (one following the other) by synchronisation, otherwise they are unordered. If a coarray is defined (assigned a value) in a segment on image I, another image J is only allowed to reference or define it in a segment that either follows or precedes the segment on I. That is, reference or a conflicting definition in an unordered segment is not permitted.

Note that image control statements all have side-effects, and therefore are not allowed in PURE subprograms or DO CONCURRENT constructs.

＜List of image control statements＞

  • ALLOCATE if an object being allocated is a coarray;
  • CALL MOVE_ALLOC, if the FROM and TO arguments are coarrays;
  • CHANGE TEAM;
  • CRITICAL;
  • DEALLOCATE if an object being deallocated is a coarray;
  • END BLOCK, END FUNCTION, or END SUBROUTINE if that causes automatic deallocation of an allocatable coarray;
  • END CRITICAL;
  • END TEAM;
  • EVENT POST;
  • EVENT WAIT;
  • FORM TEAM;
  • LOCK;
  • STOP;
  • SYNC ALL;
  • SYNC IMAGES;
  • SYNC MEMORY;
  • UNLOCK.

＜Related＞

ALLOCATE statement, CHANGE TEAM construct, CODIMENSION attribute, CRITICAL construct, DEALLOCATE statement, END TEAM statement, EVENT POST statement, EVENT WAIT statement, FORM TEAM statement, MOVE_ALLOC intrinsic subroutine, STOP statement, SYNC ALL statement, SYNC IMAGES statement, SYNC MEMORY statement, UNLOCK statement


Image selectors

Standard: F77 F90 F95 F2003 F2008 F2018 Example program

＜Syntax＞

The syntax for designating a variable has been extended by the addition of “image selectors”. A variable designated with an image selector is a “coindexed object”.

An image selector appears after a coarray name as follows:

coarray-name [ ( section-subscript-list ) ] [ image-selector ]

image-selector ::= '[' cosubscript-list [ , image-selector-spec ]... ']'

The notation '[' and ']' indicates that the square brackets themselves appear in the program, i.e. these square brackets are not BNF optionality specifiers.

cosubscript-list ::= expression [ , expression ]...

The number of expressions in the cosubscript-list must be equal to the “corank” (number of codimensions) of the coarray. The cosubscript expressions must be scalar and of type Integer.

image-selector-spec | ::= | STAT = stat-variable
 | | | TEAM = expression
 | | | TEAM_NUMBER = expression

The stat-variable must be a non-coindexed scalar Integer variable, and should be capable of representing the values −9999 to +9999. The expression in a TEAM= specifier must be a non-coindexed scalar value of type TEAM_TYPE from the intrinsic module ISO_FORTRAN_ENV. The expression in a TEAM_NUMBER= specifier must be a scalar Integer value.

For a substring of a coindexed object of type Character, the substring notation follows the image selector.

The same syntax is used for a coarray name that is a component, and a coarray name that is a variable. If the coarray is also an array, section-subscript-list is required: that is, the usual practice of selecting a whole array simply by using the array name cannot be used for coindexed objects.

Note that restrictions on declaring coarrays means that at most one of the variable name and component names in a designator can be a coarray, and therefore at most one image-selector can appear in a variable designator.

＜Semantics＞

In a coarray program with multiple images, the image selector on a coarray selects the image on which to access the coarray. The image number is calculated from the cosubscripts in the same way that the subscripts of an array determine the array element number.

If the selected image has failed, assignment to the coindexed object is ineffective, and reading the value of the coindexed object returns an unpredictable result; if the STAT= specifier appears, the value of STAT_FAILED_IMAGE from the intrinsic module ISO_FORTRAN_ENV is assigned to stat-variable. If the STAT= specifier appears and the selected image has not failed, the value zero is assigned to the stat-variable.

Except when using atomic subroutines, writing to a coarray from one image while reading (or writing) from another image is only permitted in “ordered” execution segments. Image control statements provide mechanisms for defining execution segments and synchronising them between images.

＜Related＞

ATOMIC_ADD intrinsic subroutine, ATOMIC_AND intrinsic subroutine, ATOMIC_CAS intrinsic subroutine, ATOMIC_DEFINE intrinsic subroutine, ATOMIC_OR intrinsic subroutine, ATOMIC_REF intrinsic subroutine, ATOMIC_XOR intrinsic subroutine, CODIMENSION attribute, Image control statements


IMAGE_STATUS intrinsic function

Standard: F77 F90 F95 F2003 F2008 F2018 Example program

＜Syntax＞

IMAGE_STATUS ( IMAGE [, TEAM ] )

IMAGE : Integer with positive value less than or equal to the number of images in the specified team;
TEAM : scalar of type TEAM_TYPE from the intrinsic module ISO_FORTRAN_ENV, whose value must identify the current team or an ancestor team;

Result: Default Integer.

＜Semantics＞

Returns the status of images in the specified team. The status for an image that has failed is STAT_FAILED_IMAGE, for an image that has stopped is STAT_STOPPED_IMAGE, and for an image that is active is zero.

Like many intrinsic functions, this is elemental; the result has the same shape as IMAGE, with the operation being applied elementwise. If was returned for an operation with the specified team, the size will be non-zero.

If TEAM is absent, the specified team is the current team.

＜Related＞

FAIL IMAGE statement, FAILED_IMAGES intrinsic function, FORM TEAM statement, STOP statement, STOPPED_IMAGES intrinsic function


IMPLICIT statement
Standard: F77 F90 F95 F2003
<Syntax>
 | IMPLICIT impl-spec [ , impl-spec ]... impl-spec ::= type-spec ( range [ , range ]... ) range ::= letter [ - letter ] The IMPLICIT statement must follow any USE or IMPORT statements, and precede any other declaration statements except for the PARAMETER statement.
<Semantics>
 | The IMPLICIT statement alters the implicit type mapping from the default setting. This determines the data type of any variable or function that does not have its type explicitly declared, according to the first letter of its name. The default map is IMPLICIT REAL(A-H,O-Z),INTEGER(I-N) in a program unit or interface body, and the same as the host mapping in a contained subprogram.
<Related>
 | IMPLICIT NONE statement


IMPLICIT NONE statement
Standard: F77 F90 F95 F2003
<Syntax>
 | IMPLICIT NONE statement The IMPLICIT NONE statement must be the first declaration following any USE or IMPORT statements.
<Semantics>
 | The IMPLICIT NONE statement sets the implicit type mapping for every letter to null, so there are no implicit types. This means that all variables and functions must be explicitly typed.
<Related>
 | IMPLICIT statement


IMPORT statement
Standard: F77 F90 F95 F2003 Example Program
<Syntax>
 | IMPORT [ [ :: ] import-name [ , import-name ]... ] The IMPORT statement is permitted only in an interface body.
<Semantics>
 | The IMPORT statement imports the named entities, which may be types, named constants, variables, or procedures, into the interface body. This is particularly useful for accessing type definitions and kind parameter values from inside an interface. If no import-name appears in the statement, all named symbols that do not have local declarations in the interface body are imported (just like host association). A symbol that is imported and used within the interface body must be defined prior to the interface block.
<Related>
 | INTERFACE statement, USE statement


IMPORT example program

<Example Program>

Module real_tree_module
Integer,Parameter :: rkind = Selected_Real_Kind(12,50)
Type real_tree_node
Private
Real(rkind) :: value
Type(real_tree_node),Pointer :: left,right
End Type
Contains
Recursive Subroutine traverse_and_apply(node,proc)
Type(real_tree_node) :: node
Interface
Subroutine proc(node)
!
! Without IMPORT, REAL_TREE_NODE could not have
! PRIVATE components, and a second module would
! be needed (or the SEQUENCE statement used),
! to access the type.
!
Import real_tree_node
Type(real_tree_node) :: node
End Subroutine
End Interface
If (Associated(node%left)) Then
Call traverse_and_apply(node%left,proc)
End If
Call proc(node)
If (Associated(node%right)) Then
Call traverse_and_apply(node%right,proc)
End If
End Subroutine
Function new(value,left,right)
Real(rkind),Intent(In) :: value
Type(real_tree_node),Optional,Pointer :: left,right
Type(real_tree_node),Pointer :: new
Allocate(new)
new%value = value
Nullify(new%left,new%right)
If (Present(left)) new%left => left
If (Present(right)) new%right => right
End Function
Subroutine print_node(node)
Type(real_tree_node) :: node
Print 1,node%value
1 Format(1x,'Value ',1PE12.3)
End Subroutine
End Module
Program import_example
Use real_tree_module
Type(real_tree_node),Pointer :: root
root => new(0.0_rkind, &
new(-3.0_rkind, &
right=new(-1.125_rkind)), &
new(555.875_rkind))
Call traverse_and_apply(root,print_node)
End Program
Execution Results

Value -3.000E+00
Value -1.125E+00
Value 0.000E+00
Value 5.559E+02


IMPURE attribute
Standard: F77 F90 F95 F2003 F2008 Example Program
<Syntax>
 | IMPURE The IMPURE keyword may appear only in the prefix of a FUNCTION or SUBROUTINE statement.
<Semantics>
 | The IMPURE keyword specifies that all procedures defined by this subprogram are “impure”; that is, they are permitted to have side effects. (A subprogram can define several procedures by using the ENTRY statement.) This attribute only has meaning when combined with the ELEMENTAL attribute, as it disables the otherwise “implicitly PURE” semantics of the ELEMENTAL attribute. However, it might be considered useful for documentation purposes for nonelemental procedures. An impure elemental procedure is applied to its array arguments in array element order. This ensures that the semantics of any side effects are deterministic. Typical uses of an impure elemental include things like printing intermediate values when debugging, terminating the program with an appropriate message if an error is discovered, and counting the number of times an operation is performed (instrumentation).
<Related>
 | ELEMENTAL attribute, ENTRY statement, FUNCTION statement, PURE attribute, RECURSIVE attribute, RESULT clause, SUBROUTINE statement


IMPURE example program

<Example Program>

Program impure_example
  Integer :: a(7) = [ 1, 0, 0, -2, -3, 0, 4 ]
  Integer :: count = 0
  Where (a/=0) a = f(a)
  Print *, a
  Print *, count, 'elements were nonzero'
Contains
  Impure Elemental Integer Function f(i)
    Integer, Intent(In) :: i
    f = 2*i**2 - i**3 + i
    count = count + 1
  End Function
End Program
Execution Results

 2 0 0 14 42 0 -28
 4 elements were nonzero


INCLUDE line
Standard: F77 F90 F95 F2003 Example Program
<Syntax>
 | INCLUDE character-string The INCLUDE line is not a statement; it must all appear on a single line with no label.
<Semantics>
 | The INCLUDE line textually includes the contents of the specified file into the program source. In most situations this is not recommended, because modules provide superior error detection and robustness.
<Related>
 | MODULE statement, USE statement


<Example Program>

Program include_example
Include 'type'
a = 1.
b = 2.
Call sub(a,b,c)
Print *, c
End
Subroutine sub(a,b,c)
Include 'type'
c = a + b
End
File 'type' contents

Real a,b,c

Execution Results

3.0000000


INDEX intrinsic function
Standard: (F77) F90 F95 F2003 F2008 Example Program
<Syntax>

INDEX ( STRING, SUBSTRING [ , BACK , KIND ] )

STRING : Character, any kind;
SUBSTRING : same type and kind as STRING;
BACK : Logical;
KIND : scalar Integer constant expression;

Result : Integer or Integer(Kind=KIND).

<Semantics>

Searches STRING for an occurrence of SUBSTRING. If BACK is absent, or present with the value .FALSE., the search begins at the start of STRING; if BACK is present with the value .TRUE., the search begins at the end of STRING.

If there are no occurrences of SUBSTRING in STRING, the value zero is returned; otherwise, the result I has the property that STRING(I:I+LEN(SUBSTRING)-1)==SUBSTRING, and is the least such value for a forwards search and the greatest such value for a backwards search.

This means that if SUBSTRING is length zero, the result is equal to 1 for a forwards search and LEN(STRING)+1 for a backwards search.

Like many intrinsic functions, this is elemental; if any of STRING, SUBSTRING or BACK is an array, the result is also an array with the same shape and the operation being applied elementwise. Note that all array arguments must have the same shape.

In the unlikely event of the string being longer than 2GB, the KIND argument should be used to specify a 64-bit integer kind for the result.

<Related>
CHARACTER type, SCAN intrinsic function, VERIFY intrinsic function.


INDEX example program

<Example Program>

Program index_example
  Character(52) :: a = 'She sells sea shells on the sea shore.'
  Character(3) :: sea = 'sea'
  Logical :: b(2) = [ .False.,.True. ]
  Integer :: i(2)
  i = Index(a,sea,b)
  Print *, i(1), a(i(1):)
  Print *, i(2), a(i(2):)
End Program
Execution Results

 11 sea shells on the sea shore.
 29 sea shore.


INQUIRE statement
Standard: F77 F90 F95 F2003 F2008
<Syntax>
INQUIRE ( IOLENGTH = variable ) output-list

INQUIRE ( inquire-spec [ , inquire-spec ]... )

The possible inquire-specs are listed in the table in the section below. In this form, either the FILE= or UNIT= specifier must appear, but not both. For the UNIT= specifier, the keyword and equals sign may be omitted if it is the first inquire-spec.
<Semantics>
The first form enquires as to the length needed to be specified for RECL= in the OPEN statement for an unformatted sequential file to be able to write records as large as the output-list.

The second form enquires the status of an external unit or external file. The effect of each clause is as below. All specifier arguments are scalar, and must be variables except for FILE=, ID= and UNIT=.

Specifier | Argument | Meaning | Values
[ UNIT= ] | Integer | External unit number | Non-negative
FILE= | Character | External file name |
ACCESS= | Character | Current access mode | 'DIRECT', 'SEQUENTIAL', 'STREAM', 'UNDEFINED'
ACTION= | Character | Currently allowed actions | 'READ', 'READWRITE', 'UNDEFINED', 'WRITE'
ASYNCHRONOUS= | Character | Is async i/o allowed? | 'YES', 'NO', 'UNDEFINED'
BLANK= | Character | Blanks are nulls or zeros? | 'NULL', 'ZERO', 'UNDEFINED'
CONVERT= | Character | Conversion mode | 'BIG_ENDIAN', 'BIG_IEEE', 'BIG_IEEE_DD', 'BIG_NATIVE', 'LITTLE_ENDIAN', 'LITTLE_IEEE', 'LITTLE_IEEE_DD', 'LITTLE_NATIVE', 'NATIVE', 'UNDEFINED'
DECIMAL= | Character | Decimal edit mode | 'POINT', 'COMMA', 'UNDEFINED'
DELIM= | Character | Character delimiter mode | 'APOSTROPHE', 'NONE', 'QUOTE', 'UNDEFINED'
DIRECT= | Character | Is direct access allowed? | 'YES', 'NO', 'UNKNOWN'
ENCODING= | Character | File encoding method | 'ASCII', 'EBCDIC', 'UTF-8', 'UNDEFINED', 'UNKNOWN'
ERR= | Label | Goto if error in INQUIRE |
EXIST= | Logical | File or unit exists? | .TRUE. , .FALSE.
FORM= | Character | Form of connection | 'FORMATTED', 'UNFORMATTED', 'UNDEFINED'
FORMATTED= | Character | Formatted i/o allowed? | 'YES', 'NO', 'UNKNOWN'
ID= | Integer | Pending data transfer identifier |
IOMSG= | Character | Error message from INQUIRE |
IOSTAT= | Integer | Status of the INQUIRE |
NAME= | Character | Name of the file |
NAMED= | Logical | Whether the file is named | .TRUE., .FALSE.
NEXTREC= | Integer | Next record for direct access |
NUMBER= | Integer | Unit number |
OPENED= | Logical | Is there a connection? | .TRUE., .FALSE.
PAD= | Character | Record padding mode | 'YES', 'NO', 'UNDEFINED'
PENDING= | Logical | Async i/o still pending? |
POS= | Integer | Next file storage unit |
POSITION= | Character | Current file position | 'ASIS', 'REWIND', 'APPEND', 'UNDEFINED'
READ= | Character | Is READ allowed? | 'YES', 'NO', 'UNKNOWN'
READWRITE= | Character | Are both READ and WRITE allowed? | 'YES' , 'NO', 'UNKNOWN'
RECL= | Integer | Record length of file |
ROUND= | Character | I/O rounding mode | 'COMPATIBLE', 'DOWN', 'NEAREST', 'PROCESSOR_DEFINED', 'UP', 'ZERO', 'UNDEFINED'
SEQUENTIAL= | Character | Is sequential access allowed? | 'YES', 'NO', 'UNKNOWN'
SIGN= | Character | Sign edit mode | 'PLUS', 'SUPPRESS', 'PROCESSOR_DEFINED', 'UNDEFINED'
STREAM= | Character | Is stream access allowed? | 'YES', 'NO', 'UNKNOWN'
UNFORMATTED= | Character | Unformatted i/o allowed? | 'YES', 'NO', 'UNKNOWN'
WRITE= | Character | Is WRITE allowed? | 'YES', 'NO', 'UNKNOWN'
<Related>
ASYNCHRONOUS= specifier, CONVERT= specifier, DECIMAL= specifier, ENCODING= specifier, ERR= specifier, ID= specifier, IOMSG= specifier, IOSTAT= specifier, OPEN statement, PENDING= specifier, READ statement, ROUND= specifier, SIGN= specifier, UNIT= specifier, WRITE statement


INT intrinsic function
Standard: (F77) F90 F95 F2003 F2008 Example Program
<Syntax>
 | INT ( A [ , KIND ] ) A : Complex, Integer, Real or a BOZ literal constant KIND : scalar Integer constant expression; Result : Integer or Integer(Kind=KIND).
<Semantics>
 | If A is of type Integer, the value of the result is the same as A. If A is of type Real, the value of the result is the nearest integer whose absolute value is less than that of A. If A is of type Complex, the value of the result is the nearest integer to the real part of A whose absolute value is less than that of the real part of A. If A is a BOZ literal constant (i.e. a binary, octal or hexadecimal literal), the result has the same value as that literal. Like many intrinsic functions, this is elemental; the result has the same shape as A, with the operation being applied elementwise.
<Related>
 | AINT intrinsic function, ANINT intrinsic function, CEILING intrinsic function, FLOOR intrinsic function, NINT intrinsic function


INTEGER type

Standard: (F77) F90 F95 F2003 F2008 Example program

＜Syntax＞

INTEGER [ ( [ KIND= ] expression ) ]

The expression must be a scalar integer whose value identifies a valid kind of integer.

INTEGER*1
INTEGER*2
INTEGER*4
INTEGER*8

＜Semantics＞

INTEGER declares entities (variables, functions, etc.) to be integers. The KIND number determines the range and representation of the integers. The F90_KIND module contains named constants INT8, INT16, INT32 and INT64 which are convenient for specifying integers with a particular binary range. The standard intrinsic module ISO_FORTRAN_ENV also contains those constants.

The SELECTED_INT_KIND intrinsic function can be used to select an integer kind based on range requirements.

The actual kind numbers used depend on whether “sequential”, “byte” or “unique” kind numbering is being used.

Sequential Kind Numbering (default)

KIND | 1 | 2 | 3 | 4
Name | INT8 | INT16 | INT32 | INT64
Range | −128 : 127 | −32768 : 32767 | −231 : 231−1 | −263 : 263−1

Byte Kind Numbering (-kind=byte option)

KIND | 1 | 2 | 4 | 8
Name | INT8 | INT16 | INT32 | INT64
Range | −128 : 127 | −32768 : 32767 | −231 : 231−1 | −263 : 263−1

Unique Kind Numbering (-kind=unique option)

KIND | 101 | 102 | 103 | 104
Name | INT8 | INT16 | INT32 | INT64
Range | −128 : 127 | −32768 : 32767 | −231 : 231−1 | −263 : 263−1

INTEGER*1, INTEGER*2, INTEGER*4 and INTEGER*8 are synonyms for INTEGER(INT8), INTEGER(INT16), INTEGER(INT32) and INTEGER(INT64) respectively. These synonyms are not standard Fortran.

＜Related＞

BIT_SIZE intrinsic function, CHARACTER type, COMPLEX type, Component Definition statement, DIGITS intrinsic function, HUGE intrinsic function, IMPLICIT statement, INT intrinsic function, KIND intrinsic function, LOGICAL type, RADIX intrinsic function, RANGE intrinsic function, REAL type, SELECTED_INT_KIND intrinsic function, Type Declaration statement


INTENT attribute
Standard: F77 F90 F95 F2003 Example Program
<Syntax>
type , INTENT(intent-spec) [ , attr ]... :: decl-list

INTENT(intent-spec) [ :: ] name [ , name ]...

intent-spec ::= IN | INOUT | OUT

The INOUT keyword may also be spelled as two separate words, IN OUT.
<Semantics>
Declares that those dummy arguments have the specified intent. An INTENT(IN) argument cannot appear in any context where it will be modified; an INTENT(OUT) argument becomes undefined on entry to the procedure (if the type of the argument has default initialisation, that will be applied). Both INTENT(INOUT) and INTENT(OUT) require the actual argument to be a variable (i.e. not an expression).
In Fortran 2003, the INTENT attribute is permitted for pointers. A pointer with INTENT(IN) is permitted to have its value changed if it is associated with a target, but is not permitted to have its pointer association status changed (i.e. it cannot be allocated, associated, deallocated or nullified). An INTENT(OUT) pointer has its association status become undefined on entry to the procedure.
<Related>
ENTRY statement, FUNCTION statement, SUBROUTINE statement, Type Declaration statement


<Example Program>

Program intent_example
Integer card(5),counter
counter = 10
Call sub1( counter, Size(card), card )
Print *,counter,card(3)
End
Subroutine sub1( counter, ncards, card )
Integer, Intent(InOut) :: counter
Integer, Intent(In) :: ncards
Integer, Intent(Out) :: card(ncards)
Do i = 1, ncards
card(i) = i*100
counter = counter + 1
End Do
End
Execution Results

15 300


INTERFACE statement

Standard: F77 F90 F95 F2003 F2008 Example program

＜Syntax＞

[ ABSTRACT ] INTERFACE [ generic-spec ]

generic-spec | ::= | name
 | | | ASSIGNMENT (=)
 | | | OPERATOR (operator)
 | | | read-or-write (form)

read-or-write ::= READ | WRITE
form ::= FORMATTED | UNFORMATTED

Fortran 2003 allows the ABSTRACT keyword; if this is present, generic-spec must not be present. Fortran 2003 also allows specification of defined input/output (of derived type).

The INTERFACE statement is the first statement of an interface block. The syntax of an interface block is as follows.

interface-stmt
[ interface-spec ]...

end-interface-stmt

interface-spec | ::= | interface-body
 | | | module-procedure-stmt

interface-body | ::= | function-stmt
 |  | specification-part
 |  | end-function-stmt
 | | | subroutine-stmt
 |  | specification-part
 |  | end-subroutine-stmt

The module-procedure-stmt can only be used in an interface block whose INTERFACE statement has a generic-spec.

＜Semantics＞

The INTERFACE statement introduces an interface block, which may be an abstract interface block, a specific interface block or a generic interface block.

In Fortran 2003, an abstract interface block starts with the ABSTRACT keyword, and declares abstract interfaces (not actual procedures). These abstract interfaces may be used to declare actual procedures using the PROCEDURE declaration statement, or to declare deferred type-bound procedures.

A specific interface block starts with an INTERFACE statement with no generic-spec. It specifies the EXTERNAL attribute and an explicit interface for the procedures it describes, which must be dummy procedures or external procedures.

A generic interface block starts with an INTERFACE statement with a generic-spec. It adds the procedures it describes (in interface bodies) or lists (in module procedure statements) to the set of specific procedures for that generic identifier. If it contains any interface bodies, it also specifies the EXTERNAL attribute and an explicit interface for those procedures. An explicit interface is automatically provided for internal, intrinsic and module procedures; for external and dummy procedures, an explicit interface is required if the procedure

  • is an array function,
  • is a pointer or allocatable,
  • is elemental,
  • has the BIND attribute,
  • has a dummy argument that is allocatable, assumed-shape, asynchronous, optional, or a pointer,
  • has a dummy argument with the TARGET, VALUE or VOLATILE attribute.

An explicit interface is also needed to be able to reference a procedure with an argument keyword, or in a context that requires it to be pure.

＜Related＞

END INTERFACE statement, EXTERNAL attribute, GENERIC statement, INTERFACE ASSIGNMENT statement, INTERFACE OPERATOR statement, MODULE PROCEDURE statement


INTERFACE ASSIGNMENT(=) statement
Standard: F77 F90 F95 F2003 Example Program
<Syntax>
INTERFACE ASSIGNMENT(=)
<Semantics>
The INTERFACE ASSIGNMENT statement is an INTERFACE statement that begins a generic interface block. This interface block declares (additional) specific procedures for the assignment statement.

A procedure that implements assignment shall be a subroutine with exactly two arguments; the first argument shall have INTENT(OUT) or INTENT(INOUT), and the second argument shall have INTENT(IN).

When an assignment statement
variable = expression
has a left-hand-side (variable) that matches the first argument of a specific procedure S, and a right-hand-side (expression) that matches the second argument of S, the procedure is called as if the statement had been written
CALL S ( variable , ( expression ) )
Note the extra parentheses around the expression: this forces a copy to be made, to avoid any problem if variable and expression happen to overlap.

Note: An assignment procedure cannot replace intrinsic assignment, except for derived-type assignment. This means that, e.g., "X = 3" where X is Real, is always the intrinsic assignment.
<Related>
END INTERFACE statement, INTERFACE statement, INTERFACE OPERATOR statement, MODULE PROCEDURE statement


INTERFACE ASSIGNMENT(=) example

<Example Program>

Module vector_module
Type vector
Real :: x,y
End Type vector
Interface Assignment(=)
Module Procedure v_asgn_int, v_asgn_real
Module Procedure v_asgn_double
End Interface
Contains
Subroutine v_asgn_int( this, a )
Integer, Intent(In) :: a
Type(vector), Intent(Out) :: this
this%x = -a ; this%y = -a
End Subroutine v_asgn_int
Subroutine v_asgn_real( this, a )
Real, Intent(In) :: a
Type(vector), Intent(Out) :: this
this%x = a*10. ; this%y = a*10.
End Subroutine v_asgn_real
Subroutine v_asgn_double( this, a )
Double Precision, Intent(In) :: a
Type(vector), Intent(Out) :: this
this%x = a*100. ; this%y = a*100.
End Subroutine v_asgn_double
End Module
Program example_program
Use vector_module
Type(vector) a,b,c
a = 2
b = 3.
c = 4d0
Print *, a
Print *, b
Print *, c
End Program
Execution Results

-2.0000000 -2.0000000
30.0000000 30.0000000
4.0000000E+02 4.0000000E+02


INTERFACE OPERATOR statement
Standard: F77 F90 F95 F2003 Example Program
<Syntax>
INTERFACE OPERATOR ( operator )

operator ::= + | - | * | / | ** | == | /= | < | <= | > | >= | // | .AND. | .OR. | .EQV. | .NEQV. | .NOT. | user-operator

user-operator ::= .letter[letter...].

A user-operator can have any sequence of letters that does not match an intrinsic operator.
<Semantics>
The INTERFACE OPERATOR statement is an INTERFACE statement that begins a generic interface block. It declares (additional) specific procedures for the specified operator.

The .NOT. operator is a unary operator, the + and - operators are both unary and binary operators, and all other intrinsic operators are binary operators. User-defined operators may be both unary and binary operators.

A procedure that implements a unary operator shall be a function with exactly one argument, and that argument shall have INTENT(IN). A procedure that implements a binary operator shall be a function with exactly two arguments, and both arguments shall have INTENT(IN). When an expression contains
operator expression
and expression matches the argument of a specific procedure F1 that implements that unary operator, that subexpression is evaluated as if it had been written
F1 ( expression )
When an expression contains
expression operator expression
and the first expression matches the first argument of a specific procedure F2 that implements that binary operator, and the second expression matches the second argument of F2, that subexpression is evaluated as if it had been written
F2 ( expression , expression )

Note: An operator procedure cannot replace any intrinsic operation, so things like "3+4" always have their intrinsic meaning. (But "3+.false." is not an intrinsic operation, and could be provided by an operator procedure.)

It is important to be careful (and use parentheses) in expressions containing user-defined operators. All operators have their normal precedence whether they are providing an intrinsic operation or referencing an operator procedure. Also, unary user-operators have the highest precedence (higher than **), and binary user-operators have the lowest precedence (lower than .EQV. and .NEQV.).
<Related>
END INTERFACE statement, INTERFACE statement, INTERFACE ASSIGNMENT statement, MODULE PROCEDURE statement


<Example Program>

Module vector_with_add
Type vector
Integer :: X,Y
End Type vector
Interface Operator(+)
Module Procedure add_vector
End Interface
Contains
Type(vector) Function add_vector( i, j ) Result( r )
Type(vector), Intent(In) :: i,j
r%x = i%x + j%x
r%y = i%y + j%y
End Function
End Module vector_with_add
Program interface_operator_example
Use vector_with_add
Type(vector) i,j,k
I = vector(1,2)
J = vector(3,4)
k = i + j
Print *, k
End Program
Execution Results

4 6


INTRINSIC attribute
Standard: F77 F90 F95 F2003 Example Program
<Syntax>
type, INTRINSIC [ , attr ]... :: decl-list

INTRINSIC [ :: ] name [ , name ]...

The INTRINSIC keyword can also appear on the USE statement; that usage is not described here.
<Semantics>
The INTRINSIC attribute declares that a procedure is an intrinsic procedure. It is required if the procedure is passed as an actual argument, but not if it is only called.

Declaring the type of an intrinsic procedure is completely useless, since the compiler already knows the interfaces of all intrinsic procedures. Doing so does not make a generic intrinsic procedure non-generic, and only provides an opportunity for error. Therefore we strongly recommend only using the plain INTRINSIC statement.
<Related>
EXTERNAL attribute, Type Declaration statement, USE statement


INTRINSIC example program

<Example Program>

Program intrinsic_example
Intrinsic Sin, Cos
Call sub( Sin, Cos, tan, 45. )
Print *, tan
End
Subroutine sub( si, cs, tan, degrees )
radians = degrees*3.141592654/180.
tan = si(radians)/cs(radians)
End Subroutine

Execution Results

1.0000000


IOMSG= specifier
Standard: F77 F90 F95 F2003
<Syntax>
 | IOMSG = variable The IOMSG= specifier is permitted in all input/output statements. The variable must be a scalar character with default kind; its length should be sufficient to hold any message of interest.
<Semantics>
 | The IOMSG= specifier causes the specified variable to be defined with an explanatory message if an error, end-of-file or end-of-record condition occurs during execution of the input/output statement (if the variable is too short, the message will be truncated). If no such condition occurs, the variable is unchanged. Note that if no IOSTAT= and no appropriate END=, EOR= or ERR= specifier appears, the program will be terminated on that condition; therefore it is necessary to use one of these together with the IOMSG= specifier if it is to be useful.
<Related>
 | END= specifier, EOR= specifier, ERR= specifier, IOSTAT= specifier


IOR intrinsic function
Standard: F77 F90 F95 F2003 Example Program
<Syntax>
 | IOR ( I, J ) I : Integer; J : Integer, same kind as I, conformable with I; Result : Same type and kind as I.
<Semantics>
 | The value of the result is the bitwise or of I and J; each bit in the result is 0 if and only if both the corresponding bits of I and J are 0. This is an elemental function; if any argument is an array the result is an array of the same shape, with the IOR operation being applied elementwise.
<Related>
 | IALL intrinsic function, IAND intrinsic function, IEOR intrinsic function, ISHFT intrinsic function, ISHFTC intrinsic function, LEADZ intrinsic function, MASKL intrinsic function, MASKR intrinsic function, NOT intrinsic function, SHIFTA intrinsic function, SHIFTL intrinsic function, SHIFTR intrinsic function, TRAILZ intrinsic function


<Example Program>

Program ior_example
Integer :: a(3), b(3)
a = [ 12,65549,263 ]
b = [ -1,1158,-3 ]
Print 1, a
1 Format(3(1X,Z8))
Print 1, b
Print 1, Ior(a,b)
End Program
Note: Execution Results
        C    1000D      107
 FFFFFFFF      486 FFFFFFFD
 FFFFFFFF    1048F FFFFFFFF


IOSTAT= specifier

Standard: F77 F90 F95 F2003 F2008 Example program

＜Syntax＞

IOSTAT = variable

The IOSTAT= specifier is permitted in all input/output statements. The variable must be a scalar integer and should be able to represent values in the range −9999 to +9999.

＜Semantics＞

The IOSTAT= specifier causes the specified variable to be assigned the value zero if the input/output operation was successful, with a positive value if an error condition occurred, with the negative value IOSTAT_END (from the intrinsic module ISO_FORTRAN_ENV) if an end-of-file condition occurred, or with the negative value IOSTAT_EOR (from the intrinsic module ISO_FORTRAN_ENV) if an end-of-record condition occurred.

If the statement also contains an END=, EOR= or ERR= specifier control will also be transferred if the corresponding condition occurred; if no appropriate END=, EOR= or ERR= appears execution continues normally.

The IOMSG= specifier can be used to retrieve the actual error message at the same time as the error code.

The F90_IOSTAT module contains named constants for each possible error code; the source code for this module can be found in the compiler library directory.

＜Related＞

END= specifier,
EOR= specifier,
ERR= specifier,
IOMSG= specifier,
IS_IOSTAT_END intrinsic function,
IS_IOSTAT_EOR intrinsic function


IPARITY intrinsic function
Standard: F77 F90 F95 F2003 F2008 Example Program
<Syntax>
 | IPARITY ( ARRAY, DIM [ , MASK ] ) IPARITY ( ARRAY [ , MASK ] ) ARRAY : rank N array of type Integer; DIM : scalar Integer in the range 1 to N; MASK : array of type Logical with the same shape as ARRAY; Result: Same type and kind as ARRAY.
<Semantics>
 | The result is ARRAY reduced by bitwise exclusive or (the IEOR intrinsic function). If DIM is absent, this is a scalar equal to the bitwise exclusive or of all the masked elements of ARRAY. If DIM is present, the result has rank N-1 and the shape of ARRAY with dimension DIM removed; each element of the result is the bitwise exclusive or of the masked elements in that dimension. If no elements contribute to a result value, that value is zero.
<Related>
 | Array-array operations, Array-scalar operations, ALL intrinsic function, ANY intrinsic function, COUNT intrinsic function, IALL intrinsic function, IANY intrinsic function, IEOR intrinsic function, MAXLOC intrinsic function, MAXVAL intrinsic function, MINLOC intrinsic function, MINVAL intrinsic function, .NEQV. operator, PARITY intrinsic function, PRODUCT intrinsic function, Reduction intrinsic functions, SUM intrinsic function


IPARITY example program

<Example Program>

Program iparity_example
Integer :: a(2,3)
a = Reshape( [ 12.,13.,5.,-12.,2.,-3. ], [ 2,3 ])
Print *, Iparity(a)
Print *, Iparity(a,1)
Print *, Iparity(Array=a,Dim=2)
Print *, Iparity(a, Mask=a>0)
End Program
Note: Execution Results

15
1 -15 -1
11 4
6


IS_CONTIGUOUS intrinsic function
 Standard: F77 F90 F95 F2003 F2008 Example Program
<Syntax>
 | IS_CONTIGUOUS ( ARRAY ) ARRAY : array of any type; Result : Logical scalar, default kind.
<Semantics>
 | The result is .TRUE. if the argument is stored contiguously, and .FALSE. if the argument is not contiguous. Contiguity refers to the spacing between array elements, so there is no meaning in the result for a zero-sized array.
<Related>
 | CONTIGUOUS attribute, DIMENSION attribute


IS_CONTIGUOUS example program

<Example Program>

Program is_contiguous_example
  Integer, Pointer :: i(:)
  Integer, Target :: k(100)
  i => k
  Print *, 'k', Is_Contiguous(i)
  i => k(100:1:-1)
  Print *, 'k backwards', Is_Contiguous(i)
  i => k(::2)
  Print *, 'k even', Is_Contiguous(i)
End Program

Execution Results

 k T
 k backwards F
 k even F


IS_IOSTAT_END intrinsic function
Standard: F77 F90 F95 F2003 F2008 Example Program
<Syntax>
 | IS_IOSTAT_END ( I ) I : Integer; Result : Logical with default kind.
<Semantics>
 | Returns .TRUE. if the value of I is the same as an IOSTAT= value that indicates an end-of-file condition, and .FALSE. otherwise. This is an elemental function; if I is an array the result is an array of the same shape, with the IS_IOSTAT_END operation applied to each element of I.
<Related>
 | END= specifier, IS_IOSTAT_EOR intrinsic function, IOSTAT= specifier.


IS_IOSTAT_END example program

<Example Program>

Program is_iostat_end_example
  Character c
  Integer ios, nchars, nlines, nvowels
  nchars = 0
  nlines = 0
  nvowels = 0
  Do
    Read (*,'(A)',Advance='No',Iostat=ios) c
    If (Is_Iostat_End(ios)) Exit
    If (ios==0) Then
      nchars = nchars + 1
      If (Verify(c,'aeiouAEIOU')>0) nvowels = nvowels + 1
    Else If (Is_Iostat_Eor(ios)) Then
      nlines = nlines + 1
    Else
      Print *, 'Unexpected i/o error', ios
      Stop
    End If
  End Do
  Print *, 'The input contained', nchars, 'characters in', nlines, 'lines.'
  Print *, nvowels, 'of the characters were vowels.'
End Program

Execution Results

When run with the input:
Now is the time◊
for all good men◊
to come to the aid◊
of the party.◊
where ◊ indicates the end of each record, the output is
 The input contained 62 characters in 4 lines.
 42 of the characters were vowels.


IS_IOSTAT_EOR intrinsic function
Standard: F77 F90 F95 F2003 F2008 Example Program
<Syntax>
 | IS_IOSTAT_EOR ( I ) I : Integer; Result : Logical with default kind.
<Semantics>
 | Returns .TRUE. if the value of I is the same as an IOSTAT= value that indicates an end-of-record condition, and .FALSE. otherwise. This is an elemental function; if I is an array the result is an array of the same shape, with the IS_IOSTAT_EOR operation applied to each element of I.
<Related>
 | EOR= specifier, IS_IOSTAT_END intrinsic function, IOSTAT= specifier.


IS_IOSTAT_EOR example program

<Example Program>

Program is_iostat_eor_example
  Character c
  Integer ios, nchars, nlines, nvowels
  nchars = 0
  nlines = 0
  nvowels = 0
  Do
    Read (*,'(A)',Advance='No',Iostat=ios) c
    If (Is_Iostat_End(ios)) Exit
    If (ios==0) Then
      nchars = nchars + 1
      If (Verify(c,'aeiouAEIOU')>0) nvowels = nvowels + 1
    Else If (Is_Iostat_Eor(ios)) Then
      nlines = nlines + 1
    Else
      Print *, 'Unexpected i/o error', ios
      Stop
    End If
  End Do
  Print *, 'The input contained', nchars, 'characters in', nlines, 'lines.'
  Print *, nvowels, 'of the characters were vowels.'
End Program

Execution Results

When run with the input:
Now is the time◊
for all good men◊
to come to the aid◊
of the party.◊
where ◊ indicates the end of each record, the output is
 The input contained 62 characters in 4 lines.
 42 of the characters were vowels.


ISHFT intrinsic function
Standard: F77 F90 F95 F2003 F2008 Example Program
<Syntax>
ISHFT ( I, SHIFT )

I : Integer;
SHIFT : Integer, conformable with I, ABS(SHIFT)≤BIT_SIZE(I);

Result : Same type and kind as I.
<Semantics>

The value of the result is obtained by shifting I to the left SHIFT times; if SHIFT is negative, the shift is to the right. Bits shifted in are zero. This is an elemental function; if any argument is an array the result is an array of the same shape, with the ISHFT operation being applied elementwise.

Note that this Fortran 90 intrinsic function function combines the functionality of the Fortran 2008 functions SHIFTL and SHIFTR.

<Related>
IAND intrinsic function, IBITS intrinsic function, IEOR intrinsic function, IOR intrinsic function, ISHFTC intrinsic function, NOT intrinsic function, SHIFTA intrinsic function, SHIFTL intrinsic function, SHIFTR intrinsic function


ISHFT example program

<Example Program>

Program ishft_example
Integer,Parameter :: i8 = Selected_Int_Kind(2)
Integer(i8) :: a(3) = [ Int(z'f0',i8),Int(z'70',i8),Int(z'0f',i8) ]
Do i=-3,3
Print '(I3,3(2X,B8.8))',i,Ishft(a,i)
End Do
End Program
Note: Execution Results

  -3  00011110  00001110  00000001
  -2  00111100  00011100  00000011
  -1  01111000  00111000  00000111
   0  11110000  01110000  00001111
   1  11100000  11100000  00011110
   2  11000000  11000000  00111100
   3  10000000  10000000  01111000


ISHFTC intrinsic function
Standard: F77 F90 F95 F2003 F2008 Example Program
<Syntax>

ISHFTC ( I, SHIFT [ , SIZE ] )

I : Integer;
SHIFT : Integer, conformable with I, ABS(SHIFT)≤BIT_SIZE(I);
SIZE : Integer, conformable with I and SHIFT, SHIFT≤SIZE≤BIT_SIZE(I);

Result : Same type and kind as I.

<Semantics>

The value of the result is obtained by circularly shifting the rightmost SIZE bits of I to the left SHIFT times; if SHIFT is negative, the shift is to the right. If SIZE is absent, the result is as if it were present with the value BIT_SIZE(I), i.e. all the bits of I are circularly shifted.

This is an elemental function; if any argument is an array the result is an array of the same shape, with the ISHFTC operation being applied elementwise.

<Related>
IAND intrinsic function, IBITS intrinsic function, IEOR intrinsic function, IOR intrinsic function, ISHFT intrinsic function, NOT intrinsic function, SHIFTA intrinsic function, SHIFTL intrinsic function, SHIFTR intrinsic function


ISHFTC example program

<Example Program>

Program ishftc_example
  Integer,Parameter :: i8 = Selected_Int_Kind(2)
  Integer(i8) :: a(3) = [ Int(z'f0',i8),Int(z'70',i8),Int(z'0f',i8) ]
  Do i=-3,3
    Print '(I3,3(2X,B8.8))',i,Ishftc(a,i)
  End Do
End Program
Note: Execution Results
 -3  00011110  00001110  11100001
 -2  00111100  00011100  11000011
 -1  01111000  00111000  10000111
  0  11110000  01110000  00001111
  1  11100001  11100000  00011110
  2  11000011  11000001  00111100
  3  10000111  10000011  01111000


KIND intrinsic function
Standard: F77 F90 F95 F2003 F2008 Example Program
<Syntax>
 | KIND ( X ) X : scalar or array of any intrinsic type; Result: scalar Integer with default kind.
<Semantics>
 | The KIND intrinsic function returns the kind type parameter value of X. This is an enquiry function; X need not have a value, and indeed can even be an unallocated allocatable variable or a disassociated or undefined pointer. In Fortran 2003, this enquiry may also be performed on a variable using the “%kind” formulation (and this can be done even if KIND is not available for use as an intrinsic function, for example, if it is the name of another local variable).
<Related>
 | CHARACTER type, COMPLEX type, INTEGER type, LEN intrinsic function, LOGICAL type, REAL type.


KIND example program

<Example Program>

Program kind_example
  Character a
  Complex b
  Integer c
  Logical d
  Real e
  Print *, 'Default character kind is', Kind(a)
  Print *, 'Default complex kind is', Kind(b)
  Print *, 'Default integer kind is', Kind(c)
  Print *, 'Default logical kind is', Kind(d)
  Print *, 'Default real kind is', Kind(e)
  Call show_double
Contains
  Subroutine show_double
    Double Precision :: kind = 1.5d0
    Print *, 'Double precision kind is', kind%kind
  End Subroutine
End Program

Execution Results

With the −kind=sequential option (default), the output will be:
 Default character kind is 1
 Default complex kind is 1
 Default integer kind is 3
 Default logical kind is 3
 Default real kind is 1
 Double precision kind is 2
With the −kind=byte option, the output will be:
 Default character kind is 1
 Default complex kind is 4
 Default integer kind is 4
 Default logical kind is 4
 Default real kind is 4
 Double precision kind is 8


LBOUND intrinsic function

Standard: F77 F90 F95 F2003 F2008 Example program

＜Syntax＞

LBOUND ( ARRAY [ , DIM , KIND ] )

ARRAY : array of any type and rank N;
DIM : scalar Integer in the range 1 to N;
KIND : scalar Integer constant expression;

Result : Integer or Integer(Kind=KIND).

＜Semantics＞

If DIM appears, the result is scalar, being the value of the lower bound of that dimension of ARRAY. If DIM does not appear, the result is a vector of length N containing all the lower bounds of ARRAY. The actual argument for DIM must not itself be an optional dummy argument.

If the array is not a variable, or is an array section, the lower bounds are considered to be 1. Also, the lower bound of any dimension with zero extent is considered to be 1.

In Fortran 2003, the KIND argument should be used when the lower bound might not be representable in the default Integer kind.

＜Related＞

DIMENSION attribute, SHAPE intrinsic function, SIZE intrinsic function, UBOUND intrinsic function


LCOBOUND intrinsic function

Standard: F77 F90 F95 F2003 F2008 Example program

＜Syntax＞

LCOBOUND ( COARRAY [ , DIM , KIND ] )

COARRAY : coarray of any type and corank N;
DIM : scalar Integer in the range 1 to N;
KIND : scalar Integer constant expression;

Result : Integer or Integer(Kind=KIND).

＜Semantics＞

If DIM appears, the result is scalar, being the value of the lower cobound of that codimension of COARRAY. If DIM does not appear, the result is a vector of length N containing all the lower cobounds of COARRAY. The actual argument for DIM must not itself be an optional dummy argument.

＜Related＞

CODIMENSION attribute, UCOBOUND intrinsic function


LEADZ intrinsic function
Standard: F77 F90 F95 F2003 F2008 Example Program
<Syntax>
 | LEADZ ( I ) I : Integer; Result : Integer (default kind).
<Semantics>
 | Returns the number of leading (most significant) zero bits in the internal representation of I. This is an elemental function; if I is an array the result is an array of the same shape, with the LEADZ operation applied to each element of I.
<Related>
 | IAND intrinsic function, IEOR intrinsic function, IOR intrinsic function, MASKL intrinsic function, MASKR intrinsic function, NOT intrinsic function, POPCNT intrinsic function, POPPAR intrinsic function, SHIFTA intrinsic function, SHIFTL intrinsic function, SHIFTR intrinsic function, TRAILZ intrinsic function


LEADZ example program

<Example Program>

Program leadz_example
Integer,Parameter :: i8 = Selected_Int_Kind(2)
Integer(i8) :: a(3) = [ Int(z'f1',i8),Int(z'7a',i8),Int(z'0f',i8) ]
Print *,Leadz(a)
End Program
Execution Results

0 1 4


.LE. (<=) operator
Standard: (F77) F90 F95 F2003 Example Program
<Syntax>
 | expression .LE. expression expression <= expression Each expression must be of type Integer, Real or Character.
<Semantics>
 | Compares two expressions, returning .TRUE. if and only if the first expression is less than or equal to the second. The expressions must be both either Integer or Real, or both Character. If they are of type Character, the native collating sequence is used (this might differ from ASCII).
<Related>
 | .AND. operator, Concatenation (//) operator, .EQ. (==) operator, .EQV. operator, .GE. (>=) operator, .GT. (>) operator, .LT. (<) operator, .NE. (/=) operator, .NEQV. operator, .NOT. operator, Numeric operators, Operator precedence, .OR. operator


<Example Program>

Program le_example
Do i=1,10
If (i**2+28<=i*11) Then
Print *,'True at',i
End If
End Do
End Program
Execution Results

True at 4
True at 5
True at 6
True at 7


LEN intrinsic function
Standard: F77 F90 F95 F2003 Example Program
<Syntax>
 | LEN ( STRING [ , KIND ] ) STRING : scalar or array of type Character, with any kind; KIND : scalar Integer constant expression; Result: scalar Integer or Integer(Kind=KIND).
<Semantics>
 | The LEN intrinsic function returns the character length of STRING; if STRING is an array, this is the number of characters in each element. This is an inquiry function; STRING need not have a value, and indeed except in the case of deferred character length (:) can even be an unallocated allocatable variable or a disassociated pointer. In Fortran 2003, the KIND argument should be used when the number of characters might exceed the range of a default integer; this is only relevant to 64-bit Windows as the ABI on 32-bit platforms and 64-bit Linux limit the maximum character length to 2GB-1. In Fortran 2003, this enquiry may also be performed on a character variable using the “%len” formulation (and this can be done even if LEN is not available for use as an intrinsic function, for example, if it is the name of another local variable).
<Related>
 | CHARACTER type, LEN_TRIM intrinsic function.


LEN example program

<Example Program>

Program len_example
  Character(:),Allocatable :: x
  Character(*),Parameter :: message = 'Hello'
  Print *, message, Len(message)
  x = message//' World'
  Print *, x, Len(x)
End Program
Execution Results

 Hello 5
 Hello World 11


LEN_TRIM intrinsic function
Standard: F77 F90 F95 F2003 Example Program
<Syntax>
 | LEN_TRIM ( STRING [ , KIND ] ) STRING : Character, with any kind; KIND : scalar Integer constant expression; Result: Integer or Integer(Kind=KIND).
<Semantics>
 | The LEN_TRIM intrinsic function returns the “trimmed” character length of STRING; this is the length of the string without counting trailing blanks. Like many intrinsic functions, this is elemental; the result has the same shape as STRING, with the operation being applied elementwise. In Fortran 2003, the KIND argument should be used when the length might exceed the range of a default integer; this is only relevant to 64-bit Windows as the ABI on 32-bit platforms and 64-bit Linux limit the maximum character length to 2GB-1.
<Related>
 | CHARACTER type, LEN intrinsic function, TRIM intrinsic function.


LEN_TRIM example program

<Example Program>

Program len_trim_example
  Character(80) :: message = 'Hello'
  Print *, Len_Trim(message), message(1:Len_Trim(message))
  message = 'Hello Blank Padding'
  Print *, Len_Trim(message), message(1:Len_Trim(message))
End Program
Execution Results

 5 Hello
 19 Hello Blank Padding


LGE intrinsic function
Standard: F77 F90 F95 F2003 F2008 Example Program
<Syntax>
 | LGE ( STRING_A, STRING_B ) STRING_A : Character with default kind or ASCII kind; STRING_B : Same type and kind as STRING_A, conformable with STRING_A; Result : Logical with default kind.
<Semantics>
 | The result is the comparison STRING_A≥STRING_B, using the ASCII collating sequence. This can differ from the >= operator only for default kind, and then only if default kind is not one of the ISO 646 or 8859 encodings; at this time, nearly all computers use the ISO 646 or 8859 encodings, and only some IBM mainframes use EBCDIC. Like many intrinsic functions, this is elemental; if either (or both) of STRING_A and STRING_B is an array, the result will be an array with that shape, with the value being computed elementwise.
<Related>
 | LGT intrinsic function, LLE intrinsic function, LLT intrinsic function.


LGE example program

<Example Program>

Program lge_example
  Character(3) :: a(3) = [ 'ab1', 'ab2', 'de3' ]
  Character(3) :: b(3) = [ 'ab0', 'ab2', 'de4' ]
  Print 1, 'A', '"'//a//'"'
1 Format(1X,A10,' =',99(:,1X,A7))
  Print 1, 'B', '"'//b//'"'
  Print 2, 'LGE(A,B)', lge(a,b)
2 Format(1X,A10,' =',99(:,1X,L5,2X))
  Print 2, 'A>=B', a>=b
End Program
Execution Results

          A =   "ab1"   "ab2"   "de3"
          B =   "ab0"   "ab2"   "de4"
   LGE(A,B) =     T       T       F
       A>=B =     T       T       F


LGT intrinsic function
Standard: F77 F90 F95 F2003 F2008 Example Program
<Syntax>
 | LGT ( STRING_A, STRING_B ) STRING_A : Character with default kind or ASCII kind; STRING_B : Same type and kind as STRING_A, conformable with STRING_A; Result : Logical with default kind.
<Semantics>
 | The result is the comparison STRING_A>STRING_B, using the ASCII collating sequence. This can differ from the > operator only for default kind, and then only if default kind is not one of the ISO 646 or 8859 encodings; at this time, nearly all computers use the ISO 646 or 8859 encodings, and only some IBM mainframes use EBCDIC. Like many intrinsic functions, this is elemental; if either (or both) of STRING_A and STRING_B is an array, the result will be an array with that shape, with the value being computed elementwise.
<Related>
 | LGE intrinsic function, LLE intrinsic function, LLT intrinsic function.


LGT example program

<Example Program>

Program lgt_example
  Character(3) :: a(3) = [ 'ab1', 'ab2', 'de3' ]
  Character(3) :: b(3) = [ 'ab0', 'ab2', 'de4' ]
  Print 1, 'A', '"'//a//'"'
1 Format(1X,A10,' =',99(:,1X,A7))
  Print 1, 'B', '"'//b//'"'
  Print 2, 'LGT(A,B)', lgt(a,b)
2 Format(1X,A10,' =',99(:,1X,L5,2X))
  Print 2, 'A>B', a>b
End Program
Execution Results

          A =   "ab1"   "ab2"   "de3"
          B =   "ab0"   "ab2"   "de4"
   LGT(A,B) =     T       F       F
        A>B =     T       F       F


LLE intrinsic function
Standard: F77 F90 F95 F2003 F2008 Example Program
<Syntax>
 | LLE ( STRING_A, STRING_B ) STRING_A : Character with default kind or ASCII kind; STRING_B : Same type and kind as STRING_A, conformable with STRING_A; Result : Logical with default kind.
<Semantics>
 | The result is the comparison STRING_A≤STRING_B, using the ASCII collating sequence. This can differ from the <= operator only for default kind, and then only if default kind is not one of the ISO 646 or 8859 encodings; at this time, nearly all computers use the ISO 646 or 8859 encodings, and only some IBM mainframes use EBCDIC. Like many intrinsic functions, this is elemental; if either (or both) of STRING_A and STRING_B is an array, the result will be an array with that shape, with the value being computed elementwise.
<Related>
 | LGE intrinsic function, LGT intrinsic function, LLT intrinsic function.


LLE example program

<Example Program>

Program lle_example
  Character(3) :: a(3) = [ 'ab1', 'ab2', 'de3' ]
  Character(3) :: b(3) = [ 'ab0', 'ab2', 'de4' ]
  Print 1, 'A', '"'//a//'"'
1 Format(1X,A10,' =',99(:,1X,A7))
  Print 1, 'B', '"'//b//'"'
  Print 2, 'LLE(A,B)', lle(a,b)
2 Format(1X,A10,' =',99(:,1X,L5,2X))
  Print 2, 'A<=B', a<=b
End Program
Execution Results

          A =   "ab1"   "ab2"   "de3"
          B =   "ab0"   "ab2"   "de4"
   LLE(A,B) =     F       T       T
       A<=B =     F       T       T


LLT intrinsic function
Standard: F77 F90 F95 F2003 F2008 Example Program
<Syntax>
 | LLT ( STRING_A, STRING_B ) STRING_A : Character with default kind or ASCII kind; STRING_B : Same type and kind as STRING_A, conformable with STRING_A; Result : Logical with default kind.
<Semantics>
 | The result is the comparison STRING_A<STRING_B, using the ASCII collating sequence. This can differ from the < operator only for default kind, and then only if default kind is not one of the ISO 646 or 8859 encodings; at this time, nearly all computers use the ISO 646 or 8859 encodings, and only some IBM mainframes use EBCDIC. Like many intrinsic functions, this is elemental; if either (or both) of STRING_A and STRING_B is an array, the result will be an array with that shape, with the value being computed elementwise.
<Related>
 | LGE intrinsic function, LGT intrinsic function, LLE intrinsic function.


LLT example program

<Example Program>

Program llt_example
  Character(3) :: a(3) = [ 'ab1', 'ab2', 'de3' ]
  Character(3) :: b(3) = [ 'ab0', 'ab2', 'de4' ]
  Print 1, 'A', '"'//a//'"'
1 Format(1X,A10,' =',99(:,1X,A7))
  Print 1, 'B', '"'//b//'"'
  Print 2, 'LLT(A,B)', llt(a,b)
2 Format(1X,A10,' =',99(:,1X,L5,2X))
  Print 2, 'A<B', a<b
End Program
Execution Results

          A =   "ab1"   "ab2"   "de3"
          B =   "ab0"   "ab2"   "de4"
   LLT(A,B) =     F       F       T
        A<B =     F       F       T


LOCK statement

Standard: F77 F90 F95 F2003 F2008 Example program

＜Syntax＞

LOCK ( lock-variable [ , lock-stat ]... )

lock-stat | ::= | ACQUIRED_LOCK = scalar-logical-variable
 | | | ERRMSG = errmsg-variable
 | | | STAT = stat-variable

The lock-variable must be a scalar variable of type LOCK_TYPE from the intrinsic module ISO_FORTRAN_ENV. The errmsg-variable must be a scalar Character variable with default kind, and the stat-variable must be a scalar Integer variable; these are further described in the STAT= and ERRMSG= specifier pages.

＜Semantics＞

This statement locks a lock variable. If the lock is already locked by another image, it will wait until it becomes unlocked unless the ACQUIRED_LOCK= specifier appears. If the lock is already locked by this image, an error occurs; the stat-variable will be assigned the value of STAT_LOCKED from the intrinsic module ISO_FORTRAN_ENV.

Note that if any error occurs and STAT= does not appear, the program will be terminated.

＜Related＞

ERRMSG= specifier, STAT= specifier, LOCK_TYPE from ISO_FORTRAN_ENV, UNLOCK statement


LOCK_TYPE from ISO_FORTRAN_ENV

Standard: F77 F90 F95 F2003 F2008

＜Syntax＞

TYPE ( LOCK_TYPE )
CLASS ( LOCK_TYPE )

Something of type LOCK_TYPE, or which has a potential subobject component of type LOCK_TYPE, must be a variable or a data component. A named variable of type LOCK_TYPE, or which has a potential subobject component of type LOCK_TYPE, must be a coarray.

A variable of type LOCK_TYPE must not be changed except via the LOCK and UNLOCK statements.

＜Semantics＞

＜Related＞

CODIMENSION attribute, LOCK statement, UNLOCK statement


LOG intrinsic function
Standard: F77 F90 F95 F2003 F2008 Example Program
<Syntax>
 | LOG ( X ) X : Real or Complex; Result : Same type and kind as X.
<Semantics>
 | The value of the result is an approximation to the natural logarithm (base e) of X. Like many intrinsic functions, this is elemental; the result has the same shape as X, with the operation being applied elementwise. If X is of type Real, it must be greater than zero. If X is of type Complex, it must not be equal to zero, and the result is the principal value with the imaginary part in the range −π ≤ AIMAG(LOG(X)) ≤ +π.
<Related>
 | EXP intrinsic function. LOG10 intrinsic function.


LOG_GAMMA intrinsic function
Standard: F77 F90 F95 F2003 F2008 Example Program
<Syntax>
 | LOG_GAMMA ( X ) X : Real; Result : Same type and kind as X. The value of X shall not be a negative integer or zero.
<Semantics>
 | The value of the result is an approximation to the natural log of the absolute value of the gamma function of X. The gamma function is the extension of factorial from the integers to the reals, so that when X is a positive integer, LOG_GAMMA(X) is an approximation to LOG((X−1)!). Like many intrinsic functions, this is elemental; the result has the same shape as X, with the operation being applied elementwise. The logarithm operation prevents overflow except for very large values of X.
<Related>
 | ABS intrinsic function, GAMMA intrinsic function, LOG intrinsic function.


LOG_GAMMA example program

<Example Program>

Program log_gamma_example
    Real :: x(8) = [ 2.0, 20.0, 200.0, 2000.0, 2e4, 2e5, 2e6, 2e7 ]
    Print 1, x
    Print 1, Log_Gamma(x)
1   Format(999ES9.2)
End Program

Execution Results

 2.00E+00 2.00E+01 2.00E+02 2.00E+03 2.00E+04 2.00E+05 2.00E+06 2.00E+07
 0.00E+00 3.93E+01 8.58E+02 1.32E+04 1.78E+05 2.24E+06 2.70E+07 3.16E+08


LOG10 intrinsic function
Standard: F77 F90 F95 F2003 F2008 Example Program
<Syntax>
 | LOG10 ( X ) X : Real, greater than zero; Result : Same type and kind as X.
<Semantics>
 | The value of the result is an approximation to the common logarithm (base 10) of X. Like many intrinsic functions, this is elemental; the result has the same shape as X, with the operation being applied elementwise.
<Related>
 | LOG intrinsic function.


LOG10 example program

<Example Program>

Program log10_example
  Real :: a(3) = [ 1,10,100 ]
  Print 1, Log10(a)
1 Format(3(2X,F0.5))
End Program

Execution Results

  .00000  1.00000  2.00000


LOGICAL intrinsic function
Standard: F77 F90 F95 F2003 F2008 Example Program
<Syntax>
 | LOGICAL ( L [ , KIND ] ) L : Logical KIND : scalar Integer constant expression; Result : if KIND is present, Logical(Kind=KIND), otherwise Logical with default kind.
<Semantics>
 | Converts a Logical value to default kind or a specified kind. Since there are only two valid values (.TRUE. and .FALSE.), the conversion is exact. This function can be used to pass a Logical value of one kind to a procedure whose dummy argument has a different kind. Like many intrinsic functions, this is elemental; the result has the same shape as L, with the conversion being applied elementwise.
<Related>
 | LOGICAL type.


LOGICAL intrinsic function

<Example Program>

Program logical_fun_example
  Logical(1) :: a ! Single-byte logical.
  a = .False.
  Call s(Logical(a))
  Call s(.Not.Logical(a))
Contains
  Subroutine s(b)
    Logical b ! Default logical.
    Print *, 'b is', b
  End Subroutine
End Program

Execution Results

 b is F
 b is T


LOGICAL type

Standard: (F77) F90 F95 F2003 F2008 Example program

＜Syntax＞

LOGICAL [ ( [ KIND= ] expression ) ]

The expression must be a scalar integer whose value identifies a valid kind of logical.

LOGICAL*1
LOGICAL*2
LOGICAL*4
LOGICAL*8

＜Semantics＞

LOGICAL declares entities (variables, functions, etc.) to have logical values. Logical values are either .TRUE. or .FALSE.. The KIND number determines the representation (storage space used); The F90_KIND module contains named constants BYTE, TWOBYTE, WORD and LOGICAL64 which are convenient for specifying logical types with a particular storage.

The actual kind numbers used depend on whether “sequential”, “byte” or “unique” kind numbering is being used.

Sequential Kind Numbering (default)

KIND | 1 | 2 | 3 | 4
Name | BYTE | TWOBYTE | WORD | LOGICAL64
Storage size | 8 bits | 16 bits | 32 bits | 64 bits

Byte Kind Numbering (-kind=byte option)

KIND | 1 | 2 | 4 | 8
Name | BYTE | TWOBYTE | WORD | LOGICAL64
Storage size | 8 bits | 16 bits | 32 bits | 64 bits

Unique Kind Numbering (-kind=unique option)

KIND | 201 | 202 | 203 | 204
Name | BYTE | TWOBYTE | WORD | LOGICAL64
Storage size | 8 bits | 16 bits | 32 bits | 64 bits

LOGICAL*1, LOGICAL*2, LOGICAL*4 and LOGICAL*8 are synonyms for LOGICAL(BYTE), LOGICAL(TWOBYTE), LOGICAL(WORD) and LOGICAL(LOGICAL64) respectively. These synonyms are not standard Fortran.

＜Related＞

CHARACTER type, COMPLEX type, Component Definition statement, IMPLICIT statement, INTEGER type, KIND intrinsic function, LOGICAL intrinsic function, REAL type, Type Declaration statement


.LT. (<) operator
Standard: F77 F90 F95 F2003 Example Program
<Syntax>
 | expression .LT. expression expression < expression Each expression must be of type Integer, Real or Character.
<Semantics>
 | Compares two expressions, returning .TRUE. if and only if the first expression is less than the second. The expressions must be both either Integer or Real, or both Character. If they are of type Character, the native collating sequence is used (this might differ from ASCII).
<Related>
 | .AND. operator, Concatenation (//) operator, .EQ. (==) operator, .EQV. operator, .GE. (>=) operator, .GT. (>) operator, .LE. (<=) operator, .NE. (/=) operator, .NEQV. operator, .NOT. operator, Numeric operators, Operator precedence, .OR. operator


<Example Program>

Program lt_example
Do i=1,10
If (i**2+28<i*11) Then
Print *,'True at',i
End If
End Do
End Program
Execution Results

True at 5
True at 6


MASKL intrinsic function
Standard: F77 F90 F95 F2003 F2008 Example Program
<Syntax>
 | MASKL ( I [ , KIND ] ) I : Integer; KIND : scalar Integer constant expression; Result : Integer or Integer(Kind=KIND).
<Semantics>
 | The value of the result is an integer with the leftmost (most significant) I bits set to one and the rest zero; I must be greater than or equal to zero, and less than or equal to the number of bits in the result. This is an elemental function; if I is an array the result is an array of the same shape, with the MASKL operation applied to each element of I.
<Related>
 | IAND intrinsic function, IEOR intrinsic function, IOR intrinsic function, LEADZ intrinsic function, MASKR intrinsic function, NOT intrinsic function, POPCNT intrinsic function, POPPAR intrinsic function, SHIFTA intrinsic function, SHIFTL intrinsic function, SHIFTR intrinsic function, TRAILZ intrinsic function


MASKL example program

<Example Program>

Program maskl_example
Integer,Parameter :: i8 = Selected_Int_Kind(2)
Do i=0,Bit_Size(0_i8)
Print '(1X,B8.8)',Maskl(i,i8)
End Do
End Program
Note: Execution Results

00000000
10000000
11000000
11100000
11110000
11111000
11111100
11111110
11111111


MASKR intrinsic function
Standard: F77 F90 F95 F2003 F2008 Example Program
<Syntax>
 | MASKR ( I [ , KIND ] ) I : Integer; KIND : scalar Integer constant expression; Result : Integer or Integer(Kind=KIND).
<Semantics>
 | The value of the result is an integer with the rightmost (least significant) I bits set to one and the rest zero; I must be greater than or equal to zero, and less than or equal to the number of bits in the result. This is an elemental function; if I is an array the result is an array of the same shape, with the MASKR operation applied to each element of I.
<Related>
 | IAND intrinsic function, IEOR intrinsic function, IOR intrinsic function, LEADZ intrinsic function, MASKL intrinsic function, NOT intrinsic function, POPCNT intrinsic function, POPPAR intrinsic function, SHIFTA intrinsic function, SHIFTL intrinsic function, SHIFTR intrinsic function, TRAILZ intrinsic function


MASKR example program

<Example Program>

Program maskr_example
Integer,Parameter :: i8 = Selected_Int_Kind(2)
Do i=0,Bit_Size(0_i8)
Print '(1X,B8.8)',Maskr(i,i8)
End Do
End Program
Note: Execution Results

00000000
00000001
00000011
00000111
00001111
00011111
00111111
01111111
11111111


MATMUL intrinsic function
Standard: F77 F90 F95 F2003 Example Program
<Syntax>
 | MATMUL(MATRIX_A,MATRIX_B) MATRIX_A : array of rank 1 or 2, and type Integer, Real, Complex or Logical. MATRIX_B : array of rank 1 or 2, and type Integer, Real, Complex or Logical. If MATRIX_A is of rank 1, MATRIX_B must be of rank 2. If either argument is of type Logical, both arguments must be of type Logical.
<Semantics>
 | Returns the matrix multiplication of MATRIX_A by MATRIX_B. If the matrices are of type Logical, the result is of type Logical and the operations used are .AND. (for multiply) and .OR. (for add). If the matrices are numeric, the result type is the same as for a numeric operation (e.g. *).
<Related>
 | Array-array operations, Array-scalar operations, ALL intrinsic function, ANY intrinsic function, COUNT intrinsic function, DOT_PRODUCT intrinsic function, PRODUCT intrinsic function, SUM intrinsic function, TRANSPOSE intrinsic function


MATMUL example program

<Example Program>

Program matmul_example
Real a(2,3), b(3,2), c(2,2)
a = Reshape( (/1.,2.,3.,4.,5.,6./), (/2,3/))
b = Reshape( (/2.,3.,4.,5.,6.,7./), (/3,2/))
c = Matmul(a,b)
Print *,c(1,:)
Print *,c(2,:)
End
Execution Results

31.0000000 58.0000000
40.0000000 76.0000000


MAXEXPONENT intrinsic function
Standard: F77 F90 F95 F2003 F2008 Example Program
<Syntax>
MAXEXPONENT ( X )

X : Real;
Result : Scalar Integer of default kind.
<Semantics>

This function returns the maximum exponent used in the model for floating-point numbers of the kind of X.

This is an inquiry function, so X need not be defined; indeed, it is permitted to be disassociated, unallocated, or absent.

The model for real type is that it may be zero or a signed fraction between 1 and 1/RADIX(X) consisting of DIGITS(X) digits, multiplied by an exponent RADIX(X)**e with MINEXPONENT(X)≤e≤MAXEXPONENT(X).

Note that the parameters of the model for real type are chosen so that it most closely reflects the actual floating-point numbers on the machine, but nearly all machine floating-point systems differ from the model in important respects. For example, in IEEE arithmetic, which is the most common floating-point available on modern hardware, there are additional values that lie outside the model; these are infinities, NaNs (Not-a-Number), and subnormal numbers (subnormal numbers have an exponent less than MINEXPONENT(X) but have less precision than model numbers).

<Related>
DIGITS intrinsic function, EXPONENT intrinsic function, HUGE intrinsic function, INTEGER type, MINEXPONENT intrinsic function, RADIX intrinsic function, REAL type, TINY intrinsic function


MAXEXPONENT example program

<Example Program>

Program maxexponent_example
Real,Pointer :: p
Double Precision,Allocatable :: q
Print *,'Default Real has maxexponent', Maxexponent(p)
Print *,'Double Precision has maxexponent', Maxexponent(q)
End Program
Execution Results

Default Real has maxexponent 128
Double Precision has maxexponent 1024


MAXLOC intrinsic function

Standard: F77 F90 F95 F2003 F2008 F2018 Example program

＜Syntax＞

MAXLOC ( ARRAY, DIM [ , MASK , KIND , BACK ] )
MAXLOC ( ARRAY [ , MASK , KIND , BACK ] )

ARRAY : rank N array of type Integer, Real or Character;
DIM : scalar Integer in the range 1 to N;
MASK : array of type Logical and the same shape as ARRAY;
KIND : scalar Integer constant expression;
BACK : scalar Logical;

Result: Integer or Integer(Kind=KIND). In the form without DIM, the result is a vector of length N. In the form with DIM, the result has rank N−1 (thus scalar if ARRAY is a vector), and the shape is that of ARRAY with dimension DIM removed.

＜Semantics＞

Reduces an array (either completely, or by collapsing one dimension) by the “location of maximum value” pseudo-operation.

In the form without DIM, the result is the location of the maximum value of the masked elements of ARRAY. In the form with DIM, each element of the result is the location of the maximum element in the dimension DIM vector.

Note that the first element is location number one, regardless of the actual array bounds. If all elements are masked out, or the array has size zero, the result is zero.

If more than one element has the maximum value, the location returned is the first such element (in array element order), unless the BACK argument is present with value .TRUE., in which case it is the last such element (the BACK argument was added by Fortran 2008).

In Fortran 2003, the KIND argument should be used if the array dimensions might be too large for default integer. Fortran 2003 also allows MAXLOC to be applied to type Character.

＜Related＞

FINDLOC intrinsic function, MAXVAL intrinsic function, MINLOC intrinsic function, MINVAL intrinsic function, Reduction intrinsic functions


MAXVAL intrinsic function
Standard: F77 F90 F95 F2003 Example Program
<Syntax>
 | MAXVAL ( ARRAY, DIM [ , MASK ] ) MAXVAL ( ARRAY [ , MASK ] ) ARRAY : rank N array of type Integer, Real or Character; DIM : scalar Integer in the range 1 to N; MASK : array of type Logical and the same shape as ARRAY; Result: Same type and type parameters as ARRAY.
<Semantics>
 | Returns the maximum value of the masked elements of ARRAY. If DIM is absent, the result is scalar. If DIM is present, it reduces the array in that dimension with the MAX operation; the result has the shape of ARRAY with dimension DIM omitted. If no elements are selected for a set of MAX operations, the result is the lowest value possible for ARRAY. The ability to apply MAXVAL to type Character was added by Fortran 2003.
<Related>
 | Array-array operations, Array-scalar operations, MAXLOC intrinsic function, MINLOC intrinsic function, MINVAL intrinsic function, Reduction intrinsic functions


<Example Program>

Program maxval_example
Real a(2,3)
a = Reshape( (/2.,3.,5.,-1.,4.,-3./), (/2,3/))
Print *, Maxval(a)
Print *, Maxval(a,Dim=1)
Print *, Maxval(a,Dim=2)
Print *, Maxval(a,Mask=a<5)
End
Execution Results

5.0000000
3.0000000 5.0000000 4.0000000
5.0000000 3.0000000
4.0000000


MERGE intrinsic function
Standard: F77 F90 F95 F2003 Example Program
<Syntax>
MERGE ( TSOURCE, FSOURCE, MASK )

TSOURCE : any type;
FSOURCE : same type as TSOURCE;
MASK : Logical;

Result : same type as TSOURCE.
<Semantics>
Returns the value of TSOURCE if MASK is true, and FSOURCE otherwise. Like many intrinsic functions, this is elemental; if all arguments are scalar the result is scalar, if any argument is an array the other arguments must either be scalars or arrays with the same shape, and the result is an array of that shape with the operation being applied elementwise.

Note that both TSOURCE and FSOURCE may be evaluated before MASK is evaluated; if it is necessary to evaluate only the one selected by MASK, you must use an IF-THEN construct.
<Related>


MERGE_BITS intrinsic function
Standard: F77 F90 F95 F2003 F2008 Example Program
<Syntax>
 | MERGE_BITS ( I, J, MASK ) I : BOZ literal constant or Integer; J : BOZ literal constant or Integer; MASK : BOZ literal constant or Integer; Result : Integer, same kind as I or J. Note: At least one of I and J must be of type Integer. If both I and J are of type Integer, they must be the same kind.
<Semantics>
 | Returns the bit-merge of I, J, and MASK; this means for each bit of MASK that is 1, the corresponding bit of the result is taken from that bit of I, and otherwise is taken from J. This is equivalent to IOR(IAND(I,MASK),IAND(J,NOT(MASK))). Like many intrinsic functions, this is elemental; if all arguments are scalar the result is scalar, if any argument is an array the other arguments must either be scalars or arrays with the same shape, and the result is an array of that shape with the operation being applied elementwise. If any argument is a BOZ literal constant, it is converted to the result type as if by the INT intrinsic function.
<Related>
 | IAND intrinsic function, IOR intrinsic function, MERGE intrinsic function, NOT intrinsic function.


MERGE_BITS example program

<Example Program>

Program merge_bits_example
  Integer,Parameter :: i8 = Selected_Int_Kind(2)
  Integer(i8) :: a = Int(z'f0',i8), b = Int(z'0f',i8)
  Print 1, a, b, Int(z'ff'), Merge_Bits(a,b,z'ff')
1 Format(1X, "Merge_Bits(z'",Z2.2,"','",Z2.2,"','",Z2.2,"') = z'",Z2.2,"'")
  Print 1, a, b, Int(z'00'), Merge_Bits(a,b,z'00')
  Print 1, a, b, Int(z'55'), Merge_Bits(a,b,z'55')
  Print 1, a, b, Int(z'ea'), Merge_Bits(a,b,z'ea')
End Program

Note: Execution Results

 Merge_Bits(z'F0','0F','FF') = z'F0'
 Merge_Bits(z'F0','0F','00') = z'0F'
 Merge_Bits(z'F0','0F','55') = z'5A'
 Merge_Bits(z'F0','0F','EA') = z'E5'


MINEXPONENT intrinsic function
Standard: F77 F90 F95 F2003 F2008 Example Program
<Syntax>
MINEXPONENT ( X )

X : Real;
Result : Scalar Integer of default kind.
<Semantics>

This function returns the minimum exponent used in the model for floating-point numbers of the kind of X.

This is an inquiry function, so X need not be defined; indeed, it is permitted to be disassociated, unallocated, or absent.

The model for real type is that it may be zero or a signed fraction between 1 and 1/RADIX(X) consisting of DIGITS(X) digits, multiplied by an exponent RADIX(X)**e with MINEXPONENT(X)≤e≤MAXEXPONENT(X).

Note that the parameters of the model for real type are chosen so that it most closely reflects the actual floating-point numbers on the machine, but nearly all machine floating-point systems differ from the model in important respects. For example, in IEEE arithmetic, which is the most common floating-point available on modern hardware, there are additional values that lie outside the model; these are infinities, NaNs (Not-a-Number), and subnormal numbers (subnormal numbers have an exponent less than MINEXPONENT(X) but have less precision than model numbers).

<Related>
DIGITS intrinsic function, EXPONENT intrinsic function, HUGE intrinsic function, MAXEXPONENT intrinsic function, INTEGER type, RADIX intrinsic function, REAL type, TINY intrinsic function


MINEXPONENT example program

<Example Program>

Program minexponent_example
Real,Pointer :: p
Double Precision,Allocatable :: q
Print *,'Default Real has minexponent', Minexponent(p)
Print *,'Double Precision has minexponent', Minexponent(q)
End Program
Execution Results

Default Real has minexponent -125
Double Precision has minexponent -1021


MINLOC intrinsic function

Standard: F77 F90 F95 F2003 F2008 F2018 Example program

＜Syntax＞

MINLOC ( ARRAY, DIM [ , MASK , KIND , BACK ] )
MINLOC ( ARRAY [ , MASK , KIND , BACK ] )

ARRAY : rank N array of type Integer, Real or Character;
DIM : scalar Integer in the range 1 to N;
MASK : array of type Logical and the same shape as ARRAY;
KIND : scalar Integer constant expression;
BACK : scalar Logical;

Result: Integer or Integer(Kind=KIND). In the form without DIM, the result is a vector of length N. In the form with DIM, the result has rank N−1 (thus scalar if ARRAY is a vector), and the shape is that of ARRAY with dimension DIM removed.

＜Semantics＞

Reduces an array (either completely, or by collapsing one dimension) by the “location of minimum value” pseudo-operation.

In the form without DIM, the result is the location of the minimum value of the masked elements of ARRAY. In the form with DIM, each element of the result is the location of the minimum element in the dimension DIM vector.

Note that the first element is location number one, regardless of the actual array bounds. If all elements are masked out, or the array has size zero, the result is zero.

If more than one element has the minimum value, the location returned is the first such element (in array element order), unless the BACK argument is present with value .TRUE., in which case it is the last such element (the BACK argument was added by Fortran 2008).

In Fortran 2003, the KIND argument should be used if the array dimensions might be too large for default integer. Fortran 2003 also allows MAXLOC to be applied to type Character.

＜Related＞

FINDLOC intrinsic function, MAXLOC intrinsic function, MAXVAL intrinsic function, MINVAL intrinsic function, Reduction intrinsic functions


MINVAL intrinsic function
Standard: F77 F90 F95 F2003 Example Program
<Syntax>
 | MINVAL ( ARRAY, DIM [ , MASK ] ) MINVAL ( ARRAY [ , MASK ] ) ARRAY : rank N array of type Integer, Real or Character; DIM : scalar Integer in the range 1 to N; MASK : array of type Logical and the same shape as ARRAY; Result: Same type and type parameters as ARRAY.
<Semantics>
 | Returns the minimum value of the masked elements of ARRAY. If DIM is absent, the result is scalar. If DIM is present, it reduces the array in that dimension with the MIN operation; the result has the shape of ARRAY with dimension DIM omitted. If no elements are selected for a set of MIN operations, the result is the highest value possible for ARRAY. The ability to apply MINVAL to type Character was added by Fortran 2003.
<Related>
 | Array-array operations, Array-scalar operations, MAXLOC intrinsic function, MAXVAL intrinsic function, MINLOC intrinsic function, Reduction intrinsic functions


<Example Program>

Program minval_example
Real a(2,3)
a = Reshape( (/2.,3.,5.,-1.,4.,-3./), (/2,3/))
Print *, Minval(a)
Print *, Minval(a,Dim=1)
Print *, Minval(a,Dim=2)
Print *, Minval(a,Mask=a>0)
End
Execution Results

-3.0000000
2.0000000 -1.0000000 -3.0000000
2.0000000 -3.0000000
2.0000000


MOD intrinsic function

Standard: F77 F90 F95 F2003 F2008 Example program

＜Syntax＞

MOD ( A, P )

A : Integer or Real;
P : Same type and kind as A, conformable with A, not equal to zero;
the NAG Fortran Compiler also permits P to have a different kind (this is non-standard);

Result : Same type as A, with kind the same as the kind of A+P.

＜Semantics＞

The result is the remainder for A divided by P, with the same sign as A; it is mathematically equal to A − INT(A÷P)×P.

Like many intrinsic functions, this is elemental; if either (or both) of A and P is an array, the result will be an array with that shape, with the value being computed elementwise.

＜Related＞

MODULO intrinsic function


MODULE statement

Standard: F77 F90 F95 F2003 F2008 F2018 Example program

＜Syntax＞

MODULE name

The MODULE statement is the first statement of a module program unit, whose syntax is as follows.

module-stmt
specification-part
[ CONTAINS
[ module-subprogram ]... ]
end-module-stmt

module-subprogram ::= function-subprogram | subroutine-subprogram | separate-module-subprogram

Before Fortran 2008, if the CONTAINS statement appeared, at least one module-subprogram had to appear.

The MODULE keyword is also used in the MODULE PROCEDURE statement.

The MODULE keyword is also used in the declaration and definition of separate module procedures.

＜Semantics＞

A module program unit may contain named constants, type declarations, variables and procedures for use by other parts of the program. Access to entities in a module is gained by the USE statement.

A module may also contain entities for its own internal use that are not accessible to other program units; these entities have the PRIVATE attribute. The default access is PUBLIC unless the module contains a global PRIVATE statement.

＜Related＞

CONTAINS statement, END MODULE statement, ONLY clause, MODULE PROCEDURE statement, PRIVATE attribute, PROTECTED attribute, PUBLIC attribute, SUBMODULE statement, USE statement


<Example Program>

Module set
Integer :: node = 0
Real :: coord = 10.
End Module
Program module_example
Use set
Print *, node,coord
Call sub()
Print *, node,coord
End Program
Subroutine sub()
Use set
node = 5
coord = 20.
End Subroutine sub
Execution Results

0 10.0000000
5 20.0000000


MODULE PROCEDURE statement

Standard: F77 F90 F95 F2003 F2008 F2018 Example program

＜Syntax＞

MODULE PROCEDURE name [ , name ]...
PROCEDURE name [ , name ]...

The MODULE PROCEDURE statement is only allowed inside a generic INTERFACE block.

In Fortran 2008, the mp-subprogram-stmt has identical syntax to a MODULE PROCEDURE statement declaring a single procedure, but appears only as the first statement of a separate module subprogram.

＜Semantics＞

The MODULE PROCEDURE statement specifies that the listed module procedures are to be included in the generic interface.

In Fortran 2003, the MODULE keyword may be omitted; when it is omitted, the list of names may include external procedures, dummy procedures and procedure pointers (provided they already have an explicit interface given elsewhere).

＜Related＞

END INTERFACE statement, INTERFACE statement, INTERFACE ASSIGNMENT statement, INTERFACE OPERATOR statement, MODULE statement, Separate module procedures


<Example Program>

Module data_swap
Interface swap
Module Procedure int_swap
Module Procedure real_swap
End Interface
Contains
Subroutine int_swap( a,b )
Integer, Intent(InOut) :: a,b
Integer :: tmp
tmp = a
a = b
b = tmp
End Subroutine int_swap
Subroutine real_swap( a,b )
Real, Intent(InOut) :: a,b
Real :: tmp
tmp = a
a = b
b = tmp
End Subroutine real_swap
End Module data_swap
Program module_procedure_example
Use data_swap
Integer :: i,j
Real :: x,y
i = 10 ; j = 20
x = 3. ; y = 4.
Call swap(i,j)
Call swap(x,y)
Print *, i,j
Print *, x,y
End
Execution Results

20 10
4.0000000 3.0000000


MODULO intrinsic function

Standard: F77 F90 F95 F2003 F2008 Example program

＜Syntax＞

MODULO ( A, P )

A : Integer or Real;
P : Same type and kind as A, conformable with A, not equal to zero;
the NAG Fortran Compiler also permits P to have a different kind (this is non-standard);

Result : Same type as A, with kind the same as the kind of A+P.

＜Semantics＞

The result is the remainder for A divided by P, with the same sign as P; for Real type it is mathematically equal to A − FLOOR(A÷P)×P, and for Integer type it is the unique integer R such that A = Q×P + R, where Q is an integer, |R|<P, and R has the same sign as P.

Like many intrinsic functions, this is elemental; if either (or both) of A and P is an array, the result will be an array with that shape, with the value being computed elementwise.

＜Related＞

MOD intrinsic function


MOLD= specifier

Standard: F77 F90 F95 F2003 F2008 Example program

＜Syntax＞

MOLD = expression

The MOLD= specifier may occur only in an ALLOCATE statement. If MOLD= appears, each item must be type-compatible with the MOLD= expression.

＜Semantics＞

With MOLD=, each item is allocated to have the same dynamic type as the MOLD= expression. The MOLD= specifier differs from SOURCE= in that the value is not copied; that means that the newly-allocated item will be undefined unless it has default initialisation.

If the MOLD= expression is an array, an item need not specify the bounds of the allocation; in this case, the bounds are taken from the MOLD= expression. (If it does specify the bounds, the MOLD= expression must be conformable.)

＜Related＞

ALLOCATE statement, CLASS specifier, SOURCE= specifier


MOVE_ALLOC intrinsic subroutine

Standard: F77 F90 F95 F2003 F2008 F2018 Example program

＜Syntax＞

Call MOVE_ALLOC ( FROM, TO [ , STAT, ERRMSG ] )

FROM : allocatable variable of any type and rank (including scalar), Intent(InOut);
TO : allocatable variable with the same type, rank and corank as FROM, Intent(Out);
STAT : scalar Integer variable, Intent(Out);
ERRMSG : scalar Character variable with default kind, Intent(InOut).

FROM and TO must either both be non-polymorphic or both polymorphic, and must have the same set of deferred type parameters. Any non-deferred type parameters must have the same value.

STAT must be able to represent the values −9999 to 9999 (i.e. 16 bits or larger). Both STAT and ERRMSG must not be coindexed (have an image selector).

＜Semantics＞

This moves the allocation status (allocated/unallocated, bounds, deferred type parameter values, and value) of FROM to TO; if TO was allocated, it will be deallocated before the move; after the move, FROM will be unallocated.

If both FROM and TO have the TARGET attribute, any pointers that were associated with any part of FROM will be associated with the corresponding part of TO after the move. If only FROM has the TARGET attribute, any pointers associated with any part of it will be undefined after the move.

This subroutine can be used to expand the size of an allocatable array with the minimum number of copies, by first allocating a new array with the required size, copying the values to the required place, then moving the new allocation to the old variable.

If STAT is present it is assigned the value zero unless an error condition occurs. If ERRMSG is present and an error condition occurs, it is assigned an explanatory message; if no error condition occurs, ERRMSG remains unchanged. If any error condition occurs and STAT is not present, the program will be terminated. No error condition is expected to occur when FROM and TO are normal variables. If FROM and TO are coarrays, and an image in the current team has stopped or failed, an error condition will occur.

＜Related＞

ALLOCATABLE attribute, ALLOCATE statement, ALLOCATED intrinsic function, DEALLOCATE statement


MVBITS intrinsic subroutine
Standard: F77 F90 F95 F2003 Example Program
<Syntax>

CALL MVBITS ( FROM, FROMPOS, LEN, TO, TOPOS )

FROM : Integer, Intent(In);
FROMPOS : Integer, Intent(In), FROMPOS≥0;
LEN : Integer, Intent(In), LEN≥0;
TO : Integer, same kind as FROM, Intent(InOut);
TOPOS : Integer, Intent(In), TOPOS≥0;

Requirements: MAX(FROMPOS,TOPOS)+LEN≤BIT_SIZE(FROM).

<Semantics>

Bits TOPOS:TOPOS+LEN-1 in TO are set to the value of bits FROMPOS:FROMPOS+LEN-1 in FROM; all other bits in TO are unaffected.

Note that FROM and TO are permitted to be the same variable.

This is an elemental subroutine; if any argument is an array, the TO argument must be an array and all array arguments must have the same shape; the MVBITS operation is executed elementwise.

Note that

    CALL MVBITS(FROM, FROMPOS, LEN, TO, TOPOS)
is equivalent to
    TO = IOR(IAND(TO,NOT(SHIFTL(MASKR(LEN,KIND(TO)),TOPOS))), &
             IAND(FROM,SHIFTL(MASKR(LEN,KIND(FROM)),FROMPOS)))
<Related>
BIT_SIZE intrinsic function, IAND intrinsic function, IBITS intrinsic function, IOR intrinsic function, MASKR intrinsic function, NOT intrinsic function, SHIFTL intrinsic function.


MVBITS example program

<Example Program>

Program mvbits_example
  Implicit None
  Integer,Parameter :: i8 = Selected_Int_Kind(2)
  Integer(i8) :: from = Int(b'10101010',i8)
  Integer(i8) :: initial_to = Int(b'11110000',i8), to
  Integer :: frompos = 5, len = 3
  Integer i
  Do i=0, Bit_Size(to) - len
    to = initial_to
    Call mvbits (from, frompos, len, to, i)
    Print 1, frompos, frompos + len - 1, from, i, initial_to, to
1   Format(1X, 'Moving bits ', I0, ':', I0, ' from ', B8.8, ' to position ', &
           I0, ' in ', B8.8, ' makes ', B8.8)
  End Do
End Program
Note: Execution Results
 Moving bits 5:7 from 10101010 to position 0 in 11110000 makes 11110101
 Moving bits 5:7 from 10101010 to position 1 in 11110000 makes 11111010
 Moving bits 5:7 from 10101010 to position 2 in 11110000 makes 11110100
 Moving bits 5:7 from 10101010 to position 3 in 11110000 makes 11101000
 Moving bits 5:7 from 10101010 to position 4 in 11110000 makes 11010000
 Moving bits 5:7 from 10101010 to position 5 in 11110000 makes 10110000


NAMELIST statement
Standard: F77 F90 F95 F2003 Example Program
<Syntax>
 | NAMELIST group [ [ , ] group ]... group ::= / group-name / name [ , name ]... Each name must be a variable name. The variable must not be or contain a pointer or allocatable component, if the variable is an array it must have constant bounds, and if it is a character string it must have constant length. But in Fortran 2003, the variable is permitted to be allocatable or a pointer, to contain an allocatable or pointer component (only if it will be processed by user-defined derived-type input/output), to have non-constant character length, or to have array bounds that are not constant; however, the variable is still not permitted to be an assumed-size array. Note that if the variable is allocatable or a pointer, it must be allocated or associated at the time of execution of a READ or WRITE statement that uses the namelist group. Furthermore, if the namelist group is PUBLIC then each variable must also be PUBLIC and must not have any PRIVATE components.
<Semantics>
 | The NAMELIST statement declares one or more namelist groups. Multiple NAMELIST specifications for the same namelist group name are treated as if they were concatenated. Namelist input/output is done using the NML= specifier in a READ or WRITE statement. A set of namelist records begins with “&group-name” and ends with a slash (“/”). This feature is difficult to use reliably, and so is not recommended except for small programs.
<Related>
 | NML= specifier, READ statement, WRITE statement


<Example Program 1>

Program namelist_example_1
Integer i1(2)
Real :: abc
Character(5) :: ch
Namelist /sample/ i1,abc,ch
i1 = (/123,-5/)
abc = 3.14
ch = 'ABCDEF'
Write (*,Nml=sample)
End
Execution Results

&SAMPLE I1 = 123 -5, ABC = 3.1400001, CH = ABCDE/

<Example Program 2>

Program namelist_example_2
Integer i1(2)
Real :: abc
Character(5) :: ch
Namelist /sample/ i1,abc,ch
i1 = (/123,-5/)
abc = 3.14
ch = 'ABCDE'
Read (*,Nml=sample)
Write (*,Nml=sample)
End
Example Input

&sample abc = 4.56/

Execution Results

&SAMPLE I1 = 123 -5, ABC = 4.5599999, CH = ABCDE/


.NE. (/=) operator
Standard: (F77) F90 F95 F2003 Example Program
<Syntax>
 | expression .NE. expression expression /= expression Each expression must be of type Integer, Real, Complex or Character.
<Semantics>
 | Tests two expressions for inequality, returning a default logical result. The expressions must be of type Integer, Real, Complex, or Character; if one expression is of type Character both must be. Note that in the case of type Real, negative zero is not considered to be different from positive zero.
<Related>
 | .AND. operator, Concatenation (//) operator, .EQ. (==) operator, .EQV. operator, .GE. (>=) operator, .GT. (>) operator, .LE. (<=) operator, .LT. (<) operator, .NEQV. operator, .NOT. operator, Numeric operators, Operator precedence, .OR. operator


<Example Program>

Program ne_example
Do i=1,10
If (i**2+28/=i*11) Then
Print *,'True at',i
End If
End Do
End Program
Execution Results

True at 1
True at 2
True at 3
True at 5
True at 6
True at 8
True at 9
True at 10


NEAREST intrinsic function
Standard: F77 F90 F95 F2003 F2008 Example Program
<Syntax>
 | NEAREST ( X, S ) X : Real; S : Real, conformable with X, S≠0; Result : Same type and kind as X.
<Semantics>
 | The value of the result is the nearest machine-representable number to X that is either less than X (if S<0) or greater than X (if S>0). Like many intrinsic functions, this is elemental; if either (or both) of X and S is an array, the result will be an array with that shape, with the value being computed elementwise.
<Related>


NEAREST example program

<Example Program>

Program nearest_example
  Real :: a(3) = [ -10.0, 0.0, 10.0 ]
  Print 1, 'A', a
  Print 1, 'Nearest(A,-1)', Nearest(a, -1.0)
  Print 1, 'Nearest(A,+1)', Nearest(a, +1.0)
1 Format (1X, A15, ' = ', 3ES16.8)
End Program
Execution Results

               A =  -1.00000000E+01  0.00000000E+00  1.00000000E+01
   Nearest(A,-1) =  -1.00000010E+01 -1.40129846E-45  9.99999905E+00
   Nearest(A,+1) =  -9.99999905E+00  1.40129846E-45  1.00000010E+01


.NEQV. operator
Standard: F77 F90 F95 F2003 Example Program
<Syntax>
 | expression .NEQV. expression
 | This operator has the lowest precedence of any intrinsic operator, the same as .EQV. and higher only than user-defined binary operators.
<Semantics>
 | Tests two logical expressions for non-equivalence. The kind of the result is the same as the kind of one of the expressions. The result is .FALSE. if either the expressions are both .TRUE. or both .FALSE, and the result is .TRUE. otherwise.
<Related>
 | .AND. operator, Concatenation (//) operator, .EQ. (==) operator, .EQV. operator, .GE. (>=) operator, .GT. (>) operator, .LE. (<=) operator, .LT. (<) operator, .NE. (/=) operator, .NOT. operator, Numeric operators, Operator precedence, .OR. operator


<Example Program>

Program neqv_example
Logical :: op1val(4) = (/ .true.,.true.,.false.,.false. /)
Logical :: op2val(4) = (/ .true.,.false.,.true.,.false. /)
Print 1,'Logical Operator Truth Table','.NEQV.'
1 Format (1x,A,/,/,1X,'Op1',T8,'Op2',T14,A)
Do i=1,4
Print 2,op1val(i),op2val(i),op1val(i).Neqv.op2val(i)
2 Format(T4,L1,T9,L1,T15,L1)
End Do
End Program
Execution Results

Logical Operator Truth Table

Op1 Op2 .NEQV.
T T F
T F T
F T T
F F F


NEW_LINE intrinsic function
Standard: F77 F90 F95 F2003 F2008 Example Program
<Syntax>
 | NEW_LINE ( A ) A : Character, scalar or array; Result : scalar Character, same kind as A.
<Semantics>
 | This returns the character that acts as a newline (record terminator) in formatted stream files, if such a character exists. For ASCII, ISO 8859, and ISO 10646 encodings, this is equal to ACHAR(10,KIND(A)). This is an enquiry function; A need not have a value, and indeed can even be an unallocated allocatable variable or a disassociated or undefined pointer.
<Related>
 | CHARACTER type.


NEW_LINE example program

<Example Program>

Program new_line_example
  Print *, 'Newline for default kind has encoding', Ichar(New_Line('x'))
End Program
Execution Results

 Newline for default kind has encoding 10


NEWUNIT= specifier
Standard: F77 F90 F95 F2003 F2008 Example Program
<Syntax>
 | NEWUNIT = variable The variable must be a scalar integer variable. This specifier is permitted only in an OPEN statement that has no UNIT= specifier, and either the FILE= specifier must appear or the STATUS= specifier must appear with the value "SCRATCH".
<Semantics>
 | If the OPEN is successful, the variable is assigned a negative value that is not equal to -1 and is not the same as any other unit that is currently open. The purpose of this specifier is to avoid conflicts between unit numbers in unrelated pieces of code; the runtime system keeps track of which units are open, and because the NEWUNIT= values are negative they can never conflict with a user-specified unit number.
<Related>
 | OPEN statement, UNIT= specifier


NINT intrinsic function
Standard: (F77) F90 F95 F2003 F2008 Example Program
<Syntax>
 | NINT ( A [ , KIND ] ) A : Real; KIND : scalar Integer constant expression; Result : Integer or Integer(Kind=KIND).
<Semantics>
 | The value of the result is the nearest integer to A; if two integers are equally near, the one with the larger absolute value is chosen. Like many intrinsic functions, this is elemental; the result has the same shape as A, with the operation being applied elementwise.
<Related>
 | AINT intrinsic function, ANINT intrinsic function, CEILING intrinsic function, FLOOR intrinsic function, INT intrinsic function


NML= specifier
Standard: F77 F90 F95 F2003 Example Program
<Syntax>
 | [ NML = ] group-name group-name must be the name of a namelist group as declared by the NAMELIST statement. The NML= specifier can only occur in a READ or WRITE statement.
<Semantics>
 | NML= specifies namelist formatting. It is an alternative to list-directed formatting (FMT=*) and explicit formatting (FMT=string and FMT=label). The NML= may be omitted if and only if it immediately follows a UNIT= specifier with the UNIT= omitted.
<Related>
 | FORMAT statement, NAMELIST statement, READ statement, WRITE statement


<Example Program 1>

Program nml_example_1
Integer i1(2)
Real :: abc
Character(5) :: ch
Namelist /sample/ i1,abc,ch
i1 = (/123,-5/)
abc = 3.14
ch = 'ABCDEF'
Write (*,Nml=sample)
End
Execution Results

&SAMPLE I1 = 123 -5, ABC = 3.1400001, CH = ABCDE/

<Example Program 2>

Program nml_example_2
Integer i1(2)
Real :: abc
Character(5) :: ch
Namelist /sample/ i1,abc,ch
i1 = (/123,-5/)
abc = 3.14
ch = 'ABCDE'
Read (*,Nml=sample)
Write (*,Nml=sample)
End
Example Input

&sample abc = 4.56/

Execution Results

&SAMPLE I1 = 123 -5, ABC = 4.5599999, CH = ABCDE/


NON_RECURSIVE attribute

Standard: F77 F90 F95 F2003 F2008 F2018 Example program

＜Syntax＞

NON_RECURSIVE

The NON_RECURSIVE keyword may appear only in the prefix of a FUNCTION or SUBROUTINE statement.

＜Semantics＞

The NON_RECURSIVE keyword specifies that all procedures defined by this subprogram are not called recursively. (A subprogram can define several procedures by using the ENTRY statement.)

This was the default prior to Fortran 2018, and remains the default for CHARACTER(*) functions.

＜Related＞

ENTRY statement, FUNCTION statement, RECURSIVE attribute, SUBROUTINE statement


NOPASS attribute
Standard: F77 F90 F95 F2003
<Syntax>
 | nopass-attr ::= NOPASS An entity with the NOPASS attribute is either an object-bound procedure (i.e. a procedure pointer component) or a type-bound procedure.
<Semantics>
 | Most object-bound and type-bound procedures have the PASS attribute, which specifies that when an object-bound or type-bound procedure is invoked, the object through which the procedure is invoked should be passed as an actual argument to the specified dummy argument. The NOPASS attribute specifies that the invoking object should not be passed to the procedure. Note that simply omitting the PASS attribute does not give the object-bound or type-bound procedure the NOPASS attribute, as the default is PASS. The NOPASS attribute must be explicitly specified if required.
<Related>
 | Derived type definition, PASS attribute, Object-bound procedure, Type-bound procedure


NORM2 intrinsic function
Standard: F77 F90 F95 F2003 F2008 Example Program
<Syntax>
 | NORM2 ( X [ , DIM ] ) X : rank N array of type Real; DIM : scalar Integer in the range 1 to N; Result: Same type and type parameters as X.
<Semantics>
 | Returns the L2 norm of X. If DIM is absent, the result is scalar. If DIM is present, it reduces the array in that dimension with the NORM2 operation; the result has the shape of X with dimension DIM omitted. If no elements are selected for a set of NORM2 operations, the result is zero. The L2 norm is the square root of the sum of the squares of the elements, computed without undue overflow or underflow. Note that if X is a 2-element vector, this is essentially the same as HYPOT(X(1),X(2)).
<Related>
 | HYPOT intrinsic function, Reduction intrinsic functions


NORM2 example program

<Example Program>

Program norm2_example
  Real :: x(5,3)
  Data x(:,1)/3.0e-30,2.0e-30,2.0e-30,2.0e-30,2.0e-30/
  Data x(:,2)/3.0,2.0,2.0,2.0,2.0/
  Data x(:,3)/3.0e+30,2.0e+30,2.0e+30,2.0e+30,2.0e+30/
  Print 1, x
1 Format(1X,'Whole array X is ',/,3(5(2X,ES12.5),/))
  Print 2, Norm2(x)
2 Format(1X,'Norm2 of (the whole of) X is ',ES12.5)
  Print 3, 1, Norm2(x,Dim=1)
3 Format(1X,'Norm2 with DIM=',I0,' is',99(1X,ES11.4,:))
  Print 3, 2, Norm2(x,Dim=2)
End Program
Execution Results

 Whole array X is
   3.00000E-30   2.00000E-30   2.00000E-30   2.00000E-30   2.00000E-30
   3.00000E+00   2.00000E+00   2.00000E+00   2.00000E+00   2.00000E+00
   3.00000E+30   2.00000E+30   2.00000E+30   2.00000E+30   2.00000E+30

 Norm2 of (the whole of) X is  5.00000E+30
 Norm2 with DIM=1 is  5.0000E-30  5.0000E+00  5.0000E+30
 Norm2 with DIM=2 is  3.0000E+30  2.0000E+30  2.0000E+30  2.0000E+30  2.0000E+30


.NOT. operator
Standard: F77 F90 F95 F2003 Example Program
<Syntax>
 | .NOT. expression
 | This operator has the highest precedence of the intrinsic logical operators; it is higher than that of .AND., .EQV., .NEQV., .OR., and user-defined binary operators, and lower than all other operators.
<Semantics>
 | Logical negation of a logical expression. The kind of the result is the same as the kind of the expression. The result is .TRUE. if the expression is .FALSE. and .FALSE. if the expression is .TRUE..
<Related>
 | .AND. operator, Concatenation (//) operator, .EQ. (==) operator, .EQV. operator, .GE. (>=) operator, .GT. (>) operator, .LE. (<=) operator, .LT. (<) operator, .NE. (/=) operator, .NEQV. operator, Numeric operators, Operator precedence, .OR. operator


NOT example program

<Example Program>

Program not_example
Logical :: opval(2) = (/ .true.,.false. /)
Print 1,'Logical Operator Truth Table','.NOT.'
1 Format (1x,A,/,/,1X,' Op',T8,A)
Do i=1,2
Print 2,opval(i),.Not.opval(i)
2 Format(T4,L1,T9,L1)
End Do
End Program
Execution Results

Logical Operator Truth Table

Op .NOT.
T F
F T


NOT intrinsic function
Standard: F77 F90 F95 F2003 Example Program
<Syntax>
 | NOT ( I ) I : Integer; Result : same type and shape as I.
<Semantics>
 | Returns the bitwise logical negation of I, with each zero bit replaced by a one bit, and vice versa. This is an elemental function; if I is an array the result is an array of the same shape, with the NOT operation applied to each element of I.
<Related>
 | IAND intrinsic function, IEOR intrinsic function, IOR intrinsic function, ISHFT intrinsic function, ISHFTC intrinsic function, LEADZ intrinsic function, MASKL intrinsic function, MASKR intrinsic function, POPCNT intrinsic function, POPPAR intrinsic function, SHIFTA intrinsic function, SHIFTL intrinsic function, SHIFTR intrinsic function, TRAILZ intrinsic function


<Example Program>

Program not_example
Integer,Parameter :: i8 = Selected_Int_Kind(2)
Integer(i8) :: a(3) = [ Int(z'f1',i8),Int(z'7a',i8),Int(z'0f',i8) ]
Print 1,Not(a)
1 Format(3(1X,Z2.2))
End Program
Execution Results

0E 85 F0


NULL intrinsic function
Standard: F77 F90 F95 F2003 F2008 Example Program
<Syntax>

NULL ( [ MOLD ] )

MOLD : pointer or allocatable of any type and rank;

Result : Same type, type parameters and rank as MOLD if present, otherwise determined by context.

<Semantics>

Depending on MOLD, or the surrounding context if MOLD is absent, the result is either a disassociated pointer or an unallocated allocatable entity.

Context | Attributes taken from
target of pointer assignment | pointer being assigned to
initialisation (in declaration or DATA) | object being initialised
default initialisation | component being default-initialised
value in a structure constructor | component it is the value for
actual argument | dummy argument

Note that in the case of an actual argument, MOLD cannot be omitted if any type parameter of the dummy argument is deferred (‘:’), or if the reference is generic and any attribute of that argument is required to resolve the generic.

<Related>
ALLOCATABLE attribute, ALLOCATED intrinsic function, ASSOCIATED intrinsic function, Component Definition statement, DATA statement, NULLIFY statement, POINTER attribute, Pointer assignment statement, Type Declaration statement.


NULL example program

<Example Program>

Program null_example
  Real, Pointer :: x(:,:) => Null()
  Print 1, Associated(x)
  Allocate(x(3,4))
  Print 1, Associated(x)
  x => Null()
  Print 1, Associated(x)
1 Format (1X, 'X is now associated: ', L1)
End Program
Execution Results

 X is now associated: F
 X is now associated: T
 X is now associated: F


NULLIFY statement
Standard: F77 F90 F95 F2003 Example Program
<Syntax>
 | NULLIFY ( variable [ , variable ]... ) Each variable must be a pointer.
<Semantics>
 | Sets the status of each pointer variable to “disassociated”, breaking any connection between the pointer and any previous target. A pointer can also become disassociated by pointer assignment from a disassociated pointer. The NULL intrinsic function returns disassociated pointers of any type. The ASSOCIATED intrinsic function returns false for a disassociated pointer. A disassociated pointer must not be referenced or defined.
<Related>
 | ASSOCIATED intrinsic function, NULL intrinsic function, POINTER attribute, TARGET attribute.


NULLIFY example program

<Example Program>

Program nullify_example
Integer, Pointer :: i(:,:)
Integer, Target :: j(2,2), k(2,3)
j = 1
k = 3
i => j
Print *,Associated(i), i
Nullify( i )
Print *,Associated(i)
i => k
Print *,Associated(i), i
End
Execution Results

T 1 1 1 1
F
T 3 3 3 3 3 3


NUM_IMAGES intrinsic function

Standard: F77 F90 F95 F2003 F2008 F2018 Example program

＜Syntax＞

NUM_IMAGES ( )
NUM_IMAGES ( TEAM )
NUM_IMAGES ( TEAM_NUMBER )

TEAM : scalar of type TEAM_TYPE from the intrinsic module ISO_FORTRAN_ENV, whose value must identify the current team or an ancestor team;
TEAM_NUMBER : scalar Integer, which must be equal to −1 for the initial team, or equal to the team number of a sibling team;

Result : scalar Integer with default kind.

＜Semantics＞

If TEAM and TEAM_NUMBER do not appear, the “specified team” is the current team.

The value of the result is the number of images (copies of the program in SPMD coarray execution) in the specified team.

＜Related＞

FORM TEAM statement, GET_TEAM intrinsic function, THIS_IMAGE intrinsic function


Numeric (+,-,*,/,**) operators
Standard: F77 F90 F95 F2003
<Syntax>
+ expression
- expression
expression + expression
expression - expression
expression * expression
expression / expression
expression ** expression
These operators have their usual mathematical precedence, and have higher precedence than any other operator except for unary user-defined operators.
<Semantics>
Numeric operations. The expressions must be of type Complex, Integer or Real.

The unary + and - operators return the same type and kind as their operators; the value of the + operator is the same as that of the expression, and the value of the - operator is the negation of the expression.

The binary +, -, *, / and ** operators perform addition, subtraction, multiplication, division and exponentiation respectively. If both expressions are of type Integer, the result has the same kind as the expression with the largest range. If one expression is of type Integer and the other expression is Complex or Real, the result has the same type and kind as the other expression. If both expressions are of type Real, the result is type Real and has the same kind as the expression with the largest precision. These rules are illustrated in the table below.

Result of numeric operation op1 op op2
Type of op1 | Type of op2 | Result type | Result kind
Complex | Complex | Complex | largest precision
Complex | Integer | Complex | KIND(op1)
Complex | Real | Complex | largest precision
Integer | Complex | Complex | KIND(op2)
Integer | Integer | Integer | largest range
Integer | Real | Real | KIND(op2)
Real | Complex | Complex | largest precision
Real | Integer | Real | KIND(op1)
Real | Real | Real | largest precision
<Related>
.AND. operator, Concatenation (//) operator, .EQ. (==) operator, .EQV. operator, .GE. (>=) operator, .GT. (>) operator, .LE. (<=) operator, .LT. (<) operator, .NE. (/=) operator, .NEQV. operator, .NOT. operator, Operator precedence, .OR. operator


Object-bound procedure
Standard: F77 F90 F95 F2003 Example Program
<Syntax>
An object-bound procedure is a procedure pointer component, declared in the component definition part of a derived type definition:

proc-component-def-stmt ::= PROCEDURE ( [ interface ] ) , proc-component-attr-list :: proc-component-decl-list

interface ::= interface-name | type
An interface-name is the name of an abstract interface or of any procedure with an explicit interface (e.g. a module procedure); the name cannot be the same as an intrinsic type name (e.g. LOGICAL). For the syntax of type see the type declaration statement.

proc-component-attr-list ::= proc-component-attr [ , proc-component-attr ]...
proc-component-attr | ::= | NOPASS
 | | | PASS [ ( dummy-arg-name ) ]
 | | | POINTER
 | | | PRIVATE
 | | | PUBLIC

The PUBLIC and PRIVATE attributes are only permitted in the specification part of a module. The POINTER attribute is required.

proc-component-decl-list ::= proc-component-decl [ , proc-component-decl ]...
proc-component-decl ::= proc-component-name [ =>NULL() ]

The syntax for invoking an object-bound procedure is as follows:

object-name % proc-component-name [ ( [ actual-arg-list ] ) ]
This syntax may appear in a CALL statement or as a function reference; as a function reference, the parentheses are required (and no alternate return specifier is permitted). The syntax of the actual-arg-list is described under the CALL statement.

<Semantics>
The procedure component definition statement declares one or more object-bound procedures (i.e. procedure pointer components) of a derived type. If a proc-component-decl contains “=> NULL()”, the procedure pointer component is default initialised to null. Default initialisation is applied whenever an object of the type is created, and for INTENT(OUT) arguments.

An object-bound procedure may be explicitly declared to be PUBLIC or PRIVATE; otherwise, it is PRIVATE if the component definition statements are preceded by a PRIVATE statement, and PUBLIC otherwise. A PRIVATE component cannot be accessed from outside the module that defines the type.

The object-bound procedure is determined by association with an actual procedure by pointer assignment (this may be either by a pointer assignment statement or implicitly in a structure constructor). When it is invoked, the invoking object is normally passed automatically to the procedure as an argument according to the PASS attribute; any supplied argument list provides values for the other arguments. The object-bound procedure is thus similar to a type-bound procedure in how the PASS attribute works, but the determination of the actual procedure to invoke depends on the pointer association of the component (for object-bound procedures) whereas for type-bound procedures it depends only on the dynamic type of the object.

<Related>
CALL statement, Component definition statement, Derived Type Definition, NOPASS attribute, PASS attribute, POINTER attribute, PRIVATE attribute, PUBLIC attribute, TYPE statement, Type declaration statement, Type-bound procedure


<Example Program>

Module simple_callback
Type callback_object
Character(6) :: id = ''
Procedure (basic_callback_proc),Pointer :: proc => Null()
End Type
Contains
Subroutine basic_callback_proc(me)
Class(callback_object) me
If (me%id/='') Then
Print *,Trim(me%id),' was called'
Else
Print *,'Anonymous was called'
End If
End Subroutine
Subroutine stop_program_callback_proc(me)
Class(callback_object) me
If (me%id/='') Then
Print *,'Stop requested by ',me%id
Else
Print *,'Anonymous stop request'
End If
Stop 'Program stopped by callback'
End Subroutine
Subroutine process(cba)
Class(callback_object) cba(:)
Do i=1,Size(cba)
If (Associated(cba(i)%proc)) Then
Call cba(i)%proc
Else If (cba(i)%id/='') Then
Print *,'No action for ',cba(i)%id
Else
Print *,'No action for anonymous item',i
End If
End Do
End Subroutine
End Module

Program example
Use simple_callback
Type(callback_object) x(5)
x(1) = callback_object('X1',basic_callback_proc)
x(2)%proc => basic_callback_proc
x(3)%id = 'Noone'
x(5)%id = 'End!'
x(5)%proc => stop_program_callback_proc
Call process(x)
End Program
Execution Results

X1 was called
Anonymous was called
No action for Noone
No action for anonymous item 4
Stop requested by End!
STOP: Program stopped by callback


ONLY clause
Standard: F77 F90 F95 F2003 Example Program
<Syntax>
The ONLY clause is part of the USE statement; the syntax of a USE statement containing an ONLY clause is as follows.

USE [ [ , nature ] :: ] name , ONLY: only-list

nature ::= INTRINSIC | NON_INTRINSIC

only-list ::= only-item [ , only-item ]...

only-item ::= name | rename
rename | ::= | local-name => remote-name
 | | | OPERATOR(local-operator) => OPERATOR(remote-operator)

Fortran 2003 allows renaming user-defined operators, e.g. “.FRED.=>.NURKE.”, but intrinsic operators such as “.NEQV.” cannot be renamed.
<Semantics>
The USE statement accesses public entities in a module. If all USE statements for a particular module in a scoping unit have the ONLY clause, only those entities listed in the ONLY lists are accessed. An only-item that is a rename provides access using a different identifier; the entity named remote-name or remote-operator in the module is available as local-name or local-operator in the USEing scope.

If any USE statement for a module is lacking the ONLY clause, all public entities in the module will be accessed, but any renaming specified in the ONLY clauses will still be effective.
<Related>
END MODULE statement, MODULE statement, PRIVATE attribute, PUBLIC attribute, USE statement


<Example Program>

Module abc
Real :: a=1., b=2., c=3.
End Module
Program only_example
Use abc, only: b, x=>c
Integer :: a=17, c=42
Print *, a,b,c,x
End Program
Execution Results

17 2.0000000 42 3.0000000


OPEN statement
Standard: F77 F90 F95 F2003 F2008 Example Program
<Syntax>
OPEN ( open-spec [ , open-spec ]... )

The possible open-specs are listed in the table in the section below. In UNIT=, the keyword and equals sign may be omitted if it is the first open-spec.
<Semantics>
The OPEN statement connects a file to a unit with the specified properties. The meaning of each open-spec specifier is as follows. Specifiers whose values are indicated as variable must be variables; all other non-label specifier values may be expressions. Note that upper case and lower case are considered the same in all input/output specifier values.

Specifier | Argument | Meaning | Values
[ UNIT= ] | Integer | Unit to connect to |
FILE= | Character | File to connect |
ACCESS= | Character | Access mode | 'DIRECT', 'SEQUENTIAL', 'STREAM'
ACTION= | Character | Permitted actions | 'READ', 'WRITE', 'READWRITE'
ASYNCHRONOUS= | Character | Asynchronous input/output? | 'YES', 'NO'
BLANK= | Character | Blank mode | 'NULL', 'ZERO'
DECIMAL= | Character | Decimal edit mode | 'COMMA', 'POINT'
CONVERT= | Character | Unformatted file conversion | 'BIG_ENDIAN', 'BIG_IEEE', 'BIG_IEEE_DD', 'BIG_NATIVE', 'LITTLE_ENDIAN', 'LITTLE_IEEE', 'LITTLE_IEEE_DD', 'LITTLE_NATIVE', 'NATIVE'
DELIM= | Character | String delimiter | 'QUOTE', 'NONE', 'APOSTROPHE'
ENCODING= | Character | File encoding | 'ASCII', 'DEFAULT', 'SHIFT_JIS', 'UTF-8'
ERR= | Label | Branch on error |
FORM= | Character | Formatting | 'FORMATTED', 'UNFORMATTED'
IOMSG= | Character | Error message | variable
IOSTAT= | Integer | Error status | variable
NEWUNIT= | Integer | New unit number | variable
PAD= | Character | Pad short records with blanks? | 'YES', 'NO'
POSITION= | Character | Initial file position | 'APPEND', 'ASIS', 'REWIND'
RECL= | Integer | Length of record in bytes | Greater than zero
ROUND= | Character | Rounding mode | 'COMPATIBLE', 'DOWN', 'NEAREST', 'PROCESSOR_DEFINED', 'UP', 'ZERO'
SIGN= | Character | Sign edit mode | 'PLUS', 'SUPPRESS', 'PROCESSOR_DEFINED'
STATUS= | Character | File status | 'NEW', 'OLD', 'REPLACE', 'SCRATCH', 'UNKNOWN'

If the unit is already open to a different file, that file is closed automatically. If the unit is already open to the same file, only the BLANK=, DECIMAL=, DELIM=, PAD= and SIGN= may have values different from the current mode.

Fortran 2003 has stream files (ACCESS='STREAM') and the additional specifiers DECIMAL=, ENCODING=, IOMSG=, ROUND= and SIGN=.
<Related>
ASYNCHRONOUS= specifier, BACKSPACE statement, CLOSE statement, CONVERT= specifier, DECIMAL= specifier, ENCODING= specifier, ENDFILE statement, ERR= specifier, INQUIRE statement, IOMSG= specifier, IOSTAT= specifier, NEWUNIT= specifier, PRINT statement, READ statement, REWIND statement, ROUND= specifier, SIGN= specifier, UNIT= specifier, WRITE statement


<Example Program>

Program open_example
Open (1,File='DAT',Status='old',Position='Rewind')
n_lines = 0
Do
Read (1,'( )',End=10)
n_lines = n_lines + 1
End Do
10 Continue
Print *,'There are',n_lines,'lines in the file'
Close(1)
End
Contents of file: DAT

This is line 1
This is line 2
This is line 3; it is longer than the other lines

Execution Results

There are 3 lines in the file


Operator precedence
Standard: (F77) F90 F95 F2003
<Syntax>
The precedence of an operator in Fortran depends only on its syntax, and is illustrated by the table below. Broadly speaking, the numeric operators have their usual mathematical precedence, this is higher than all the relational operators (who have the same precedence as each other), and this is higher than the logical operators (which have their usual precedence).

Operators which have the same precedence are associated left-to-right except for exponentiation (**) which is associated right-to-left.

Operator | Precedence
user-defined unary operators | 1 (highest)
** (exponentiation) | 2
* (multiply), / (divide) | 3
unary + (positive), - (negate) | 4
binary + (add), - (subtract) | 5
// (character concatenation) | 6
.EQ. (==), .GE. (>=), .GT. (>), .LE. (<=), .LT. (<), .NE. (/=) | 7
.NOT. | 8
.AND. | 9
.OR. | 10
.EQV., .NEQV. | 11
user-defined binary operators | 12 (lowest)
<Related>
.AND. operator, Concatenation (//) operator, .EQ. (==) operator, .EQV. operator, .GE. (>=) operator, .GT. (>) operator, .LE. (<=) operator, .LT. (<) operator, .NE. (/=) operator, .NEQV. operator, .NOT. operator, Numeric operators, .OR. operator


OPTIONAL attribute
Standard: F77 F90 F95 F2003 F2008 Example Program
<Syntax>
type, OPTIONAL [ , attr ]... :: decl-list

OPTIONAL [ :: ] name [ , name ]...

An entity with the OPTIONAL attribute must be a dummy argument.
<Semantics>

Declares that a dummy argument is optional. In a reference to a procedure with an optional dummy argument, no corresponding actual argument is needed. The PRESENT intrinsic function tests whether an optional dummy argument has a corresponding actual argument.

Note that a procedure with an optional argument must always be referenced with an explicit interface. This is automatic for module and internal procedures; for external or dummy procedures an INTERFACE block must be used.

An optional argument that is not present can be used as an actual argument to an intrinsic enquiry function that does not need its value, or as an actual argument corresponding to an optional dummy argument of any kind of procedure, but in no other way.

<Related>
INTERFACE statement, PRESENT intrinsic function, Type Declaration statement


OPTIONAL example program

<Example Program>

Program optional_example
  Call one('Hello')
  Call one
Contains
  Subroutine one(x)
    Character(*), Intent(In), Optional :: x
    Print *, 'one: x is present =', Present(x)
    Call two(x)
  End Subroutine
  Subroutine two(y)
    Character(*), Intent(In), Optional :: y
    If (Present(y)) Then
      Print *, 'two: y is present with value "', y, '"'
    Else
      Print *, 'two: y is not present'
    End If
  End Subroutine
End Program
Execution Results

 one: x is present = T
 two: y is present with value "Hello"
 one: x is present = F
 two: y is not present


.OR. operator
Standard: F77 F90 F95 F2003 Example Program
<Syntax>
 | expression .OR. expression
 | This operator has precedence higher than that of .EQV., .NEQV. and user-defined binary operators, and lower than all other operators.
<Semantics>
 | Logical disjunction of two logical expressions. The kind of the result is the same as the kind of one of the expressions. The result is .TRUE. if either expression is .TRUE., and .FALSE. only if both expressions are .FALSE..
<Related>
 | .AND. operator, Concatenation (//) operator, .EQ. (==) operator, .EQV. operator, .GE. (>=) operator, .GT. (>) operator, .LE. (<=) operator, .LT. (<) operator, .NE. (/=) operator, .NEQV. operator, .NOT. operator, Numeric operators, Operator precedence


<Example Program>

Program or_example
Logical :: op1val(4) = (/ .true.,.true.,.false.,.false. /)
Logical :: op2val(4) = (/ .true.,.false.,.true.,.false. /)
Print 1,'Logical Operator Truth Table','.OR.'
1 Format (1x,A,/,/,1X,'Op1',T8,'Op2',T14,A)
Do i=1,4
Print 2,op1val(i),op2val(i),op1val(i).Or.op2val(i)
2 Format(T4,L1,T9,L1,T15,L1)
End Do
End Program
Execution Results

Logical Operator Truth Table

Op1 Op2 .OR.
T T T
T F T
F T T
F F F


PACK intrinsic function
Standard: F77 F90 F95 F2003 Example Program
<Syntax>
PACK(ARRAY, MASK [ , VECTOR ] )

ARRAY : array of any type
MASK : Logical, conformable with ARRAY
VECTOR : vector with same type as ARRAY
<Semantics>
The result of PACK(ARRAY,MASK) is a vector containing all the masked elements of ARRAY. The size of this result will be COUNT(MASK) if MASK is an array, SIZE(ARRAY) if MASK is scalar true and zero if MASK is scalar false.

If VECTOR is present it must be at least as big as SIZE(PACK(ARRAY,MASK)). The size of PACK(ARRAY,MASK,VECTOR) is SIZE(VECTOR); if this is bigger than SIZE(PACK(ARRAY,MASK)), the remaining elements of the result are the corresponding elements of VECTOR.
<Related>
UNPACK intrinsic function


<Example Program>

Program pack_example
Real a(2,3)
a = Reshape( (/-1.,2.,-3.,4.,5.,-6./), (/2,3/))
Print *, Pack(a,Mask=a>0)
End
Execution Results

2.0000000 4.0000000 5.0000000


PARAMETER attribute
Standard: F77 F90 F95 F2003 Example Program
<Syntax>
 | type, PARAMETER [ , attr ] :: decl-list PARAMETER ( name=expr [ , name=expr ]... In a type declaration statement with the PARAMETER keyword, each decl in the decl-list must supply a value. Each name must be implicitly typed or have its type specified in a prior type declaration. The type of each expr in a PARAMETER statement must be assignment compatible with its corresponding name.
<Semantics>
 | The PARAMETER attribute specifies that an entity is a named constant. If the type, kind or character length of the expr differs from that of the name, the value is converted using the same rules as intrinsic assignment.
<Related>
 | Type Declaration statement


<Example Program 1>

Program parameter_example_1
Real, Parameter :: pai = 3.14
Print *, pai*2
End
Execution Results

6.2800002

<Example Program 2>

Program parameter_example_2
Parameter (pai = 3.14)
Print *, pai*2
End
Execution Results

6.2800002


PARITY intrinsic function
Standard: F77 F90 F95 F2003 F2008 Example Program
<Syntax>
 | PARITY ( MASK [ , DIM ] ) MASK : rank N array of type Logical; DIM : scalar Integer in the range 1 to N; Result: Logical with the same kind as MASK.
<Semantics>
 | Reduces an array (either completely, or by collapsing one dimension) with the .NEQV. operation; the value is true if and only if the number of values (in that dimension with DIM=) that are true is odd.
<Related>
 | ANY intrinsic function, ANY intrinsic function, Array-scalar operations, Array-array operations, COUNT intrinsic function, IALL intrinsic function, IANY intrinsic function, IPARITY intrinsic function, DOT_PRODUCT intrinsic function, MATMUL intrinsic function, MAXLOC intrinsic function, MAXVAL intrinsic function, MINLOC intrinsic function, MINVAL intrinsic function, PRODUCT intrinsic function, Reduction intrinsic functions, SUM intrinsic function, TRANSPOSE intrinsic function


PARITY intrinsic function

<Example Program>

Program parity_example
Real, Dimension(2,3) :: a, b
a = Reshape( (/2.,3.,5.,-1.,4.,-3./), (/2,3/))
b = Reshape( (/2.,3.,5.,-1.,0.,-3./), (/2,3/))
Print *, Parity(a==b)
Print *, Parity(a==b,1)
Print *, Parity(Mask=a.Eq.b,Dim=2)
End Program
Note: Execution Results

T
F F T
F T


PASS attribute
Standard: F77 F90 F95 F2003
<Syntax>
 | pass-attr ::= PASS [ ( dummy-arg-name ) ] An entity with the PASS attribute is either an object-bound procedure (i.e. a procedure pointer component) or a type-bound procedure.
<Semantics>
 | The PASS attribute specifies that when an object-bound or type-bound procedure is invoked, the object through which the procedure is invoked should be passed as an actual argument to the specified dummy argument. If no dummy-arg-name is provided, the first dummy argument is specified. Omitting this attribute has the same effect as specifying just PASS. To avoid passing the object as an actual argument, the NOPASS attribute must be specified.
<Related>
 | Derived type definition, NOPASS attribute, Object-bound procedure, Type-bound procedure


PAUSE statement
Standard: F77 F90 F95 F2003 F2008
<Syntax>
 | PAUSE [ constant ] In Fortran 77 and Fortran 90 the constant was required to be an unsigned integer with at most 5 digits, or a scalar character literal. The NAG Fortran Compiler accepts any scalar constant default Integer or default Character expression (the same as the extended STOP statement in Fortran 2008).
<Semantics>
 | Pauses program execution. With the NAG Fortran Compiler, a message is displayed on standard error, and execution waits for input (RETURN key) on standard input; this only works if the executing program has a terminal window. The PAUSE statement was deleted in Fortran 95 because it is not portable or reliable (the method of pausing is not defined). However, all compilers still accept it as an extension.
<Related>
 | STOP statement


PENDING= specifier
Standard: F77 F90 F95 F2003
<Syntax>
 | PENDING = variable The variable must be a scalar logical variable of default kind. This specifier is permitted only in an INQUIRE statement that has an ID= clause.
<Semantics>
 | The PENDING= specifier is assigned the value .TRUE. if the asynchronous operation indicated by the ID= clause is still pending, and .FALSE. if it has completed. If PENDING= sets the variable to .FALSE., this implicitly “waits” for the operation and the identifier value must not be used again.
<Related>
 | ASYNCHRONOUS attribute, ASYNCHRONOUS= specifier, ID= specifier, INQUIRE statement


Pointer assignment statement (=>)

Standard: F77 F90 F95 F2003 F2008 Example program

＜Syntax＞

pointer-variable => target

target ::= expression | variable

The target must either be a reference to a function that returns a pointer, or a variable with the TARGET or POINTER attribute.

The pointer variable must have the same type, type parameters, and rank as the target (except in the case of remapping).

pointer-variable ( lower-bounds ) => target
lower-bounds ::= expression : [ , expression : ]...

The number of lower bounds must be equal to the rank of the pointer.

pointer-variable ( remapping ) => target
remapping ::= bound-pair [ , bound-pair ]...
bound-pair ::= expression : expression

In the case of remapping, the target must be a rank-one array or a simply contiguous array, but the pointer may have any rank; the number of bound pairs must be equal to the rank of the pointer.

＜Semantics＞

The pointer assignment statement either copies the association of one pointer to another, or associates a pointer with a variable that has the TARGET attribute. The bounds of the pointer are the same as that of the target (unless different lower bounds are provided, or remapping is being done); if the target is an array section, the lower bounds will all be equal to one and the upper bounds will be equal to the extents.

If the lower bounds are provided, the pointer will have those lower bounds.

If remapping is being done, the pointer will have the bounds specified; in this case the target must not be a disassociated or undefined pointer, and must have at least as many elements as implied by the remapping. This form associates a multi-dimensional pointer with a single-dimensional or simply contiguous target.

＜Related＞

ALLOCATE statement, DEALLOCATE statement, DIMENSION attribute, NULL intrinsic function, NULLIFY statement, POINTER attribute, TARGET attribute


POINTER attribute
Standard: F77 F90 F95 F2003 Example Program
<Syntax>
type, POINTER [ , attr ] :: decl-list

POINTER [ :: ] ptr-decl [ , ptr-decl ]...

ptr-decl ::= name [ ( deferred-shape ) ]
<Semantics>

The POINTER attribute specifies that an entity is a pointer. At runtime, a pointer may be associated with a target (by allocation or pointer assignment), may be disassociated (by NULLIFY or by pointer assignment from another disassociated pointer) or it may have undefined association status. A pointer that is not associated must not be referenced or defined.

A pointer that is an array has its rank specified (by a deferred shape spec), but it has no bounds or shape until it is associated with a target array.

A pointer can only become associated with variables that have the TARGET attribute. Allocating a pointer creates a new variable that implicitly has the TARGET attribute.

In Fortran 2003, a character pointer can have “deferred length”, specified by a length type parameter of ‘:’. Such a pointer has no length until it is associated with a target.

<Related>
ALLOCATE statement, Component Definition statement, DEALLOCATE statement, DIMENSION attribute, NULL intrinsic function, NULLIFY statement, Pointer assignment statement (=>), TARGET attribute, Type Declaration statement


POPCNT intrinsic function
Standard: F77 F90 F95 F2003 F2008 Example Program
<Syntax>
 | POPCNT ( I ) I : Integer; Result : Integer (default kind).
<Semantics>
 | Returns the number of one bits in the internal representation of I. This is an elemental function; if I is an array the result is an array of the same shape, with the POPCNT operation applied to each element of I.
<Related>
 | IAND intrinsic function, IEOR intrinsic function, IOR intrinsic function, LEADZ intrinsic function, MASKL intrinsic function, MASKR intrinsic function, NOT intrinsic function, POPPAR intrinsic function, SHIFTA intrinsic function, SHIFTL intrinsic function, SHIFTR intrinsic function, TRAILZ intrinsic function


<Example Program>

Program popcnt_example
Integer :: a(3) = [ Int(z'ff'),Int(z'e3'),Int(z'02') ]
Print *,Popcnt(a)
End Program
Execution Results

8 5 1


POPPAR intrinsic function
Standard: F77 F90 F95 F2003 F2008 Example Program
<Syntax>
 | POPPAR ( I ) I : Integer; Result : Integer (default kind).
<Semantics>
 | Returns 1 if the number of one bits in the internal representation of I is odd, and 0 if it is even; this is the same value as IAND(POPCNT(I),1). This is an elemental function; if I is an array the result is an array of the same shape, with the POPPAR operation applied to each element of I.
<Related>
 | IAND intrinsic function, IEOR intrinsic function, IOR intrinsic function, LEADZ intrinsic function, MASKL intrinsic function, MASKR intrinsic function, NOT intrinsic function, POPCNT intrinsic function, SHIFTA intrinsic function, SHIFTL intrinsic function, SHIFTR intrinsic function, TRAILZ intrinsic function


<Example Program>

Program poppar_example
Integer :: a(3) = [ Int(z'ff'),Int(z'e3'),Int(z'02') ]
Print *,Poppar(a)
End Program
Execution Results

0 1 1


PRECISION intrinsic function
Standard: F77 F90 F95 F2003 F2008 Example Program
<Syntax>
PRECISION ( X )

X : scalar or array of type Real or Complex;

Result : scalar Integer, default kind.
<Semantics>

This function returns the decimal precision of floating-point numbers that have the same kind as X. The result is equal to INT((DIGITS(X)-1)*LOG10(REAL(RADIX(X))))+k, where k is 1 if RADIX(X) is an integral power of 10, and 0 otherwise; thus all decimal integers with PRECISION(X) digits (or fewer) can be exactly represented in this kind, but not all integers with PRECISION(X)+1 digits can be.

Note that if X is Complex, PRECISION(X) is equal to PRECISION(REAL(X)) and also PRECISION(AIMAG(X)), i.e. it is the precision of the real and imaginary parts.

This is an inquiry function, so X need not be defined; indeed, it is permitted to be an unallocated allocatable or a disassociated or undefined pointer.

<Related>
DIGITS intrinsic function, RADIX intrinsic function, REAL type, SELECTED_REAL_KIND intrinsic function.


PRECISION example program

<Example Program>

Program precision_example
  Double Precision,Pointer :: p
  Real,Allocatable :: q
  Print *,'Double precision Real has precision', Precision(p)
  Print *,'Default Real has precision', Precision(q)
End Program

Execution Results

 Double precision Real has precision 15
 Default Real has precision 6


PRESENT intrinsic function
 Standard: F77 F90 F95 F2003 F2008 Example Program
<Syntax>
 | PRESENT ( A ) A : the name of an optional dummy argument, this may have any type or rank, and may even be a procedure; Result : Logical, default kind.
<Semantics>
 | The result is true if and only if the dummy argument is present. Note that presence of a dummy argument is transitive: if it is not present, it may be passed as an actual argument to another optional dummy argument, and that dummy argument will also not be present. This is an enquiry function; the dummy argument need not be defined, associated or allocated.
<Related>
 | OPTIONAL attribute


PRESENT example program

<Example Program>

Program present_example
  Call one('Hello')
  Call one
Contains
  Subroutine one(x)
    Character(*), Intent(In), Optional :: x
    Print *, 'one: x is present =', Present(x)
    Call two(x)
  End Subroutine
  Subroutine two(y)
    Character(*), Intent(In), Optional :: y
    If (Present(y)) Then
      Print *, 'two: y is present with value "', y, '"'
    Else
      Print *, 'two: y is not present'
    End If
  End Subroutine
End Program

Execution Results

 one: x is present = T
 two: y is present with value "Hello"
 one: x is present = F
 two: y is not present


PRINT statement
Standard: F77 F90 F95 F2003 Example Program
<Syntax>
PRINT format [ , item ]...

format ::= * | label | expr

item ::= expr | implied-do
implied-do ::= ( item [ , item ]... , do-spec )
do-spec ::= name = expr , expr [ , expr ]

The label in a format must be the label of a FORMAT statement. The expr in a format must be a character expression or an integer variable name that has been ASSIGNed the label of a FORMAT statement. The name in a do-spec must be an Integer variable.
<Semantics>
The PRINT statement writes to the default output unit; it is exactly the same as
WRITE (*,format) item [ , item ]...
<Related>
ASSIGN statement, FORMAT statement, READ statement, WRITE statement


<Example Program>

Program print_example
Print *, 'Welcome'
End
Execution Results

Welcome


PRIVATE attribute
Standard: F77 F90 F95 F2003 Example Program
<Syntax>
 | type, PRIVATE [ , attr ] :: decl-list PRIVATE [ :: ] name [ , name ]... PRIVATE The PRIVATE attribute is only permitted in the specification part of a module program unit.
<Semantics>
 | The PRIVATE attribute specifies that an entity is local to the module, and is not accessible from other program units. It is the opposite to the PUBLIC attribute. A PRIVATE statement with no list of names declares that all entities in the module are private, except for those which are explicitly declared PUBLIC. A derived type definition in a module may contain a PRIVATE statement in its component definition part; it declares the default accessibility to be PRIVATE for components of the type. In Fortran 2003, the PRIVATE statement can also occur in the type-bound procedure part, where it declares the default accessibility to be PRIVATE for type-bound procedures; furthermore, individual components and type-bound procedures may be declared PRIVATE in their component definition statement or type-bound procedure statement.
<Related>
 | Component Definition statement, MODULE statement, PROTECTED attribute, PUBLIC attribute, Type Declaration statement


<Example Program>

Module steps
Integer, Private :: hidden_stepval = 0
Public :: step,step_value
Contains
Integer Function step_value()
step_value = hidden_stepval
End Function
Subroutine step
hidden_stepval = hidden_stepval + 10
End Subroutine
End Module
Program private_example
Use steps
Print *, step_value()
Call step
Print *, step_value()
End Program
Execution Results

0
10


PROCEDURE statements
Standard: F77 F90 F95 F2003
<Syntax>
There are four statements that can begin with the PROCEDURE keyword.
The procedure declaration statement has the syntax:
PROCEDURE ( [ proc-interface ] ) , proc-attr-list :: proc-decl-list
proc-interface | ::= | interface-name
 | | | declaration-type-spec
proc-attr | ::= | INTENT ( intent-spec )
 | | | OPTIONAL
 | | | POINTER
 | | | PRIVATE
 | | | PUBLIC
 | | | SAVE
proc-decl ::= proc-name [ => NULL() ]

The procedure component definition statement has the syntax:
PROCEDURE ( [ proc-interface ] ) , proc-component-attr-list :: proc-component-decl-list
proc-component-attr | ::= | NOPASS
 | | | PASS [ ( arg-name ) ]
 | | | POINTER
 | | | PRIVATE
 | | | PUBLIC
proc-component-decl ::= proc-component-name [ => NULL() ]

The type-bound procedure statement has the syntax:
PROCEDURE ( [ interface-name ] ) , binding-attr-list :: tbp-name [ => procedure-name ]
binding-attr | ::= | DEFERRED
 | | | NON_OVERRIDABLE
 | | | NOPASS
 | | | PASS [ ( arg-name ) ]
 | | | POINTER
 | | | PRIVATE
 | | | PUBLIC
The procedure statement in a generic interface block has the syntax:
[ MODULE ] PROCEDURE [ :: ] procedure-name [ , procedure-name ]...

If the keyword MODULE appears, each procedure-name must be the name of a module procedure; otherwise, each procedure-name must be the name of a module procedure, external procedure, dummy procedure or procedure pointer. In all cases, procedure-name must have an explicit interface.

The MODULE PROCEDURE version of this statement was also present in Fortran 90 and 95.
<Semantics>
The procedure declaration statement declares an external procedure, a dummy procedure, or a procedure pointer. A procedure declared by this statement is a procedure pointer if it has the POINTER attribute (which may be specified separately), a dummy procedure if it is a dummy argument, and an external procedure only if it is not a dummy argument and does not have the POINTER attribute. A dummy procedure with the POINTER attribute is a dummy procedure pointer.

The procedure component definition statement defines a procedure pointer component, also known as an object-bound procedure. See the related link for the full syntax and semantics.

The type-bound procedure statement defines a type-bound procedure. See the related link for the full syntax and semantics.

The procedure statement in a generic interface block adds the listed procedures to the generic interface.
<Related>
Derived Type Definition, MODULE PROCEDURE statement, Object-bound procedure, POINTER attribute, PRIVATE attribute, PUBLIC attribute, Type-bound procedure


PRODUCT intrinsic function
Standard: F77 F90 F95 F2003 Example Program
<Syntax>
 | PRODUCT ( ARRAY, DIM [ , MASK ] ) PRODUCT ( ARRAY [ , MASK ] ) ARRAY : rank N array of type Integer, Real or Complex; DIM : scalar Integer in the range 1 to N; MASK : array of type Logical with the same shape as ARRAY; Result: Same type and kind as ARRAY.
<Semantics>
 | The result is ARRAY reduced by multiplication ( * ). If DIM is absent, this is a scalar equal to the product of all the masked elements of ARRAY. If DIM is present, the result has rank N-1 and the shape of ARRAY with dimension DIM removed; each element of the result is the product of the masked elements in that dimension. If no elements contribute to a result value, that value is 1.
<Related>
 | Array-array operations, Array-scalar operations, ALL intrinsic function, ANY intrinsic function, COUNT intrinsic function, IALL intrinsic function, IANY intrinsic function, IPARITY intrinsic function, MAXLOC intrinsic function, MAXVAL intrinsic function, MINLOC intrinsic function, MINVAL intrinsic function, PARITY intrinsic function, Reduction intrinsic functions, SUM intrinsic function


PRODUCT example program

<Example Program>

Program product_example
Real a(2,3)
a = Reshape( (/2.,3.,5.,-1.,4.,-3./), (/2,3/))
Print *, Product(a)
Print *, Product(a,Dim=1)
Print *, Product(a,Dim=2)
Print *, Product(a,Mask=a>0)
End
Execution Results

3.6000000E+02
6.0000000 -5.0000000 -12.0000000
40.0000000 9.0000000
1.2000000E+02


PROGRAM statement
Standard: F77 F90 F95 F2003 Example Program
<Syntax>
 | PROGRAM program-name A main program program unit has the syntax: [ program-stmt ] specification-part executable-part [ CONTAINS internal-subprogram-part ] end-program-stmt
<Semantics>
 | The PROGRAM statement introduces a main program. It is optional; if it is not present, the main program has no name.
<Related>
 | CONTAINS statement, END PROGRAM statement


<Example Program>

PROGRAM program_example
Print *, 'Hello Example'
End Program program_example
Execution Results

Hello Example


PROTECTED attribute
Standard: F77 F90 F95 F2003 Example Program
<Syntax>
type, PROTECTED [ , attr ]... :: decl-list

PROTECTED [ :: ] name [ , name ]...

The PROTECTED attribute is only permitted in the specification part of a module program unit.
<Semantics>
The PROTECTED attribute protects a module variable against alteration from outside the module. Outside of its module, a variable with the PROTECTED attribute may be referenced but not defined; it is subject to the same limitations as an INTENT(IN) variable.

Note that the PROTECTED attribute is completely separate from the accessibility (PUBLIC/PRIVATE) attribute. The latter determines the visibility of the variable name, whereas PROTECTED determines what may be done to it.
<Related>
MODULE statement, PRIVATE attribute, PUBLIC attribute, Type Declaration statement


PROTECTED example

<Example Program>

Module temperature_module
Real,Protected :: temperature_c = 0, temperature_f = 32
Contains
Subroutine set_temperature_c(new_value_c)
Real,Intent(In) :: new_value_c
temperature_c = new_value_c
temperature_f = temperature_c*(9.0/5.0) + 32
End Subroutine
Subroutine set_temperature_f(new_value_f)
Real,Intent(In) :: new_value_f
temperature_f = new_value_f
temperature_c = (temperature_f - 32)*(5.0/9.0)
End Subroutine
End

Program protected_example
Use temperature_module
!
! We can print temperature_c and temperature_f directly,
! but can only change using the module procedures.
!
Call set_temperature_c(20.0)
Print '(1X,F6.2)',temperature_f
Call set_temperature_f(100.0)
Print '(1X,F6.2)',temperature_c
End Program
Execution Results

68.00
37.78


PUBLIC attribute
Standard: F77 F90 F95 F2003 Example Program
<Syntax>
 | type, PUBLIC [ , attr ] :: decl-list PUBLIC [ :: ] name [ , name ]... PUBLIC The PUBLIC attribute is only permitted in the specification part of a module program unit.
<Semantics>
 | The PUBLIC attribute specifies that a module entity is accessible from outside the module. It is the opposite to the PRIVATE attribute. A PUBLIC statement with no list of names confirms that all entities in the module are public, except for those which are explicitly declared PRIVATE. (This is the default.) In Fortran 2003, individual components and type-bound procedures in a derived type definition may be declared PUBLIC in their component definition statement or type-bound procedure statement.
<Related>
 | Component Definition statement, MODULE statement, PRIVATE attribute, PROTECTED attribute, Type Declaration statement


<Example Program>

Module steps
Integer, Private :: hidden_stepval = 0
Public :: step,step_value
Contains
Integer Function step_value()
step_value = hidden_stepval
End Function
Subroutine step
hidden_stepval = hidden_stepval + 10
End Subroutine
End Module
Program public_example
Use steps
Print *, step_value()
Call step
Print *, step_value()
End Program
Execution Results

0
10


PURE attribute

Standard: F77 F90 F95 F2003 F2008 F2018 Example program

＜Syntax＞

PURE

The PURE keyword may appear only in the prefix of a FUNCTION or SUBROUTINE statement.

＜Semantics＞

The PURE keyword specifies that all procedures defined by this subprogram are “pure”; that is, they have no side effects. (A subprogram can define several procedures by using the ENTRY statement.) A pure procedure can thus be used safely in contexts where side-effects are problematic; that is, in specification expressions and in DO CONCURRENT and FORALL constructs.

A pure subprogram must obey the following rules:

  • every nonpointer dummy argument must have an INTENT attribute, and for a pure function, that must be INTENT(IN);
  • no local variable is permitted to have the SAVE attribute;
  • it must not reference any VOLATILE variable;
  • it must not assign a value to any non-local variable, except that a pure subroutine can assign a value to an INTENT(INOUT) or INTENT(OUT) dummy variable;
  • it must not invoke a non-pure procedure;
  • it must not contain any input/output statement, except for READ or WRITE of an internal file;
  • it must not contain a STOP statement;
  • it must not contain an image control statement;
  • Fortran 2008 only: it must not contain an ERROR STOP statement (this restriction is removed in Fortran 2018).

The PURE attribute is also implied by the ELEMENTAL attribute, except when ELEMENTAL is accompanied by the IMPURE attribute.

＜Related＞

DO CONCURRENT construct, ELEMENTAL attribute, ENTRY statement, FORALL construct, FUNCTION statement, IMPURE attribute, SUBROUTINE statement


RADIX intrinsic function
Standard: F77 F90 F95 F2003 F2008 Example Program
<Syntax>
RADIX ( X )

X : Integer or Real;
Result : Scalar Integer of default kind.
<Semantics>

This function returns the radix used in the model for number of the type and kind of X.

This is an inquiry function, so X need not be defined; indeed, it is permitted to be disassociated, unallocated, or absent.

The model for integer type is as a sign together with DIGITS(X) digits of radix RADIX(X); all current machines with a Fortran compiler use binary integer arithmetic, so this has the value 2.

The model for real type is that it may be zero or a signed fraction between 1 and 1/RADIX(X) consisting of DIGITS(X) digits, multiplied by an exponent RADIX(X)**e with MINEXPONENT(X)≤e≤MAXEXPONENT(X). Most current machines with a Fortran compiler use binary floating-point arithmetic, and on those machines RADIX(X) will have the value 2. IBM OS/390 machines have both binary and hexadecimal floating-point available; in hexadecimal mode RADIX(X) will have the value 16. IEEE has recently standardised decimal floating-point arithmetic; currently there is not much hardware or software support for this, but when it becomes available such kinds of REAL will have radix 10.

<Related>
DIGITS intrinsic function, HUGE intrinsic function, INTEGER type, MAXEXPONENT intrinsic function, MINEXPONENT intrinsic function, PRECISION intrinsic function, REAL type, TINY intrinsic function


RADIX example program

<Example Program>

Program radix_example
Integer,Pointer :: p
Real,Allocatable :: q
Print *,'Default Integer has radix', Radix(p)
Print *,'Default Real has radix', Radix(q)
End Program
Execution Results

Default Integer has radix 2
Default Real has radix 2


RANDOM_NUMBER intrinsic subroutine
Standard: F77 F90 F95 F2003 F2008 Example Program
<Syntax>
 | Call RANDOM_NUMBER ( HARVEST ) HARVEST : Real (any kind), Intent(Out).
<Semantics>
 | HARVEST, or each element of HARVEST if it is an array, is assigned a value from a pseudo-random number sequence in the range 0≤HARVEST<1.
<Related>
 | RANDOM_SEED intrinsic subroutine.


RANDOM_NUMBER example program

<Example Program>

Program random_number_example
  Real x(10)
  Call Random_Number(x)
  Do i=1, Size(x)
    Print 1, i, x(i)
1   Format(1X, 'X(', I0, ') = ', F6.4)
  End Do
End Program
Execution Results

 X(1) = 0.3215
 X(2) = 0.2357
 X(3) = 0.7013
 X(4) = 0.9108
 X(5) = 0.0492
 X(6) = 0.1034
 X(7) = 0.5808
 X(8) = 0.3854
 X(9) = 0.5661
 X(10) = 0.7433


RANDOM_SEED intrinsic subroutine
Standard: F77 F90 F95 F2003 F2008 Example Program
<Syntax>

Call RANDOM_SEED ( [ SIZE, PUT, GET ] )

SIZE : scalar Integer with default kind;
PUT : Integer array with default kind;
GET : Integer array with default kind.

<Semantics>

All arguments are optional. If no arguments are supplied, the pseudo-random number generator is re-initialised; this should not be done while using the generator as the relationship between the number sequence before and after the re-initialisation will be unknown.

SIZE is assigned the value N, the number of integer values needed to represent the internal state of the pseudo-random number generator.

GET must have at least N elements; it is assigned the internal state of the pseudo-random number generator. This value can be used for a later PUT argument to RANDOM_SEED to reset the internal state of the generator.

PUT must have at least N elements; it is used to determine the internal state of the pseudo-random number generator. If the value of PUT is one that was retrieved with GET, the generator will be reset to the same state as of the call with GET. It is strongly recommended never to use PUT with anything other than the result of GET, as the generator has an extremely long period and a user-specified seed is highly likely to set the generator into an initial low-entropy state.

<Related>
RANDOM_NUMBER intrinsic subroutine.


RANDOM_SEED example program

<Example Program>

Program random_seed_example
  Implicit None
  Real x(6), y(6)
  Integer, Allocatable :: state(:)
  Integer n
  Call Random_Seed (Size=n)
  Allocate (state(n))
  Call Random_Seed (Get=state)
  Call Random_Number (x)
  Call display (x, 'x')
  Print *, 'Resetting...'
  Call Random_Seed (Put=state)
  Call Random_Number (y)
  Call display (y, 'y')
Contains
  Subroutine display (a, name)
    Real, Intent(In) :: a(:)
    Character(*), Intent(In) :: name
    Integer i
    Do i=1, Size (a)
      Print 1, name, i, a(i)
1     Format(1X, A, '(', I0, ') = ', F6.4)
    End Do
  End Subroutine
End Program
Execution Results

 x(1) = 0.8824
 x(2) = 0.6333
 x(3) = 0.7272
 x(4) = 0.2610
 x(5) = 0.5427
 x(6) = 0.4555
 Resetting...
 y(1) = 0.8824
 y(2) = 0.6333
 y(3) = 0.7272
 y(4) = 0.2610
 y(5) = 0.5427
 y(6) = 0.4555


RANGE intrinsic function
Standard: F77 F90 F95 F2003 F2008 Example Program
<Syntax>
RANGE ( X )

X : scalar or array of type Integer, Real or Complex;

Result : scalar Integer, default kind.
<Semantics>

This function returns the decimal exponent range of variables with the same type and kind as X.

For type Integer, this is equal to INT(LOG10(REAL(HUGE(X)))); integers with RANGE(X) or fewer digits can all be represented in Integer variables with the same kind as X, but not all variables with RANGE(X)+1 digits can be represented.

For Real, this is equal to INT(MIN(LOG10(HUGE(X)),-LOG10(TINY(X)))); all powers of ten in the range 10.0**(-RANGE(X)) to 10.0**RANGE(X) can be approximated by Real variables with the same kind as X.

For Complex, it is equal to RANGE(REAL(X)) or RANGE(AIMAG(X)) i.e. the range of the real and imaginary parts.

Note that attempting to exceed the decimal range of a type may result in overflow. For Real or Complex, by default this will terminate the program with an error message; for Integer, there is a runtime checking option (−C=intovf) which can detect this error.

This is an inquiry function, so X need not be defined; indeed, it is permitted to be an unallocated allocatable or a disassociated or undefined pointer.

<Related>
HUGE intrinsic function, INTEGER type, REAL type, SELECTED_INT_KIND intrinsic function, SELECTED_REAL_KIND intrinsic function, TINY intrinsic function.


RANGE example program

<Example Program>

Program range_example
    Double Precision,Pointer :: p
    Real,Allocatable :: q
    Print *,'Default Integer has range', Range(17)
    Print *,'Double precision Real has range', Range(p)
    Print *,'Default Real has range', Range(q)
End Program
Execution Results

 Default Integer has range 9
 Double precision Real has range 307
 Default Real has range 37


READ statement
Standard: F77 F90 F95 F2003 F2008 Example Program
<Syntax>
READ format [ , input-list ]
READ ( ci-spec [ , ci-spec ]... ) [ input-list ]

format ::= * | label | expr
unit ::= * | variable | expr
input-list ::= input-item [ , input-item ]...
input-item ::= variable | ( input-list , do-spec )

The possible ci-specs are listed in the table below, together with their meaning.

The UNIT= ci-spec is required. The UNIT= keyword and equals sign may be omitted if it is the first ci-spec. If UNIT= was omitted, the FMT= keyword and equals sign may be omitted if it is the second ci-spec, or the NML= keyword and equals sign may be omitted if it is the second ci-spec.
<Semantics>
The READ statement reads one or more records, or partial records, from the specified unit. Each ci-spec is listed in the table below.

If unit is *, the input is from the standard input unit (usually the keyboard); if it is a character variable, the input is from that variable; if it is an integer expr, the input is from the external unit with that number, which must be non-negative.

If format is present, the READ is a formatted READ; if format is *, list-directed formatting is used; if format is a label, that FORMAT statement is used; if format is a character expression, that expression is interpreted as an explicit format. The READ is also a formatted READ if Namelist is present, in which case namelist formatting is used.

Specifier | Argument | Meaning | Values
[ UNIT = ] | unit | Unit to read from |
[ FMT = ] | format | Formatting |
ADVANCE= | Character | Advancing input? | 'YES', 'NO'
ASYNCHRONOUS= | Character | Async i/o? | 'YES', 'NO'
BLANK= | Character | Blanks are? | 'NULL', 'ZERO'
DECIMAL= | Character | Decimal edit mode | 'COMMA', 'POINT'
END= | Label | Branch on end of file |
EOR= | Label | Branch on end of record |
ERR= | Label | Branch on error |
ID= | Integer | Pending i/o identifier |
IOMSG= | Character | Error message |
IOSTAT= | Integer | I/O status value |
[ NML= ] | Namelist | Namelist formatting |
PAD= | Character | Padding mode | 'YES', 'NO'
POS= | Integer | File storage position | Positive
REC= | Integer | Record number | Positive
ROUND= | Character | Rounding mode | 'COMPATIBLE', 'DOWN', 'NEAREST', 'PROCESSOR_DEFINED', 'UP', 'ZERO'
SIZE= | Integer | Number of characters read |

The ADVANCE= specifier is only allowed for external files. If the NML= specifier appears, no format is allowed. The EOR= and SIZE= specifiers are only allowed in conjunction with ADVANCE='NO'. The REC= specifier is only allowed for a direct access file.

In Fortran 2003, the BLANK=, DECIMAL=, PAD= and ROUND= specifiers control the initial edit modes for that READ; if omitted, the default is taken from the OPEN. The IOMSG= specifier sets its variable to an error message if an error occurs. The POS= specifier is only allowed for stream files, and specifies the file storage position at which to start reading. The ID= specifier is only allowed in conjunction with ASYNCHRONOUS='YES', and sets the variable to an identifier for that asynchronous i/o (this variable can then be used in an ID= specifier in INQUIRE).
<Related>
ADVANCE= specifier, ASYNCHRONOUS= specifier, BACKSPACE statement, CLOSE statement, DECIMAL= specifier, ENDFILE statement, END= specifier, EOR= specifier, ERR= specifier, FORMAT statement, ID= specifier, INQUIRE statement, IOMSG= specifier, IOSTAT= specifier, NAMELIST statement, NML= specifier, OPEN statement, PRINT statement, REWIND statement, ROUND= specifier, SIZE= specifier, UNIT= specifier, WRITE statement


<Example Program>

Program read_example
Read *, i,j
Print *, i,j
End
Example input 1

1,2

Execution Results

1 2
Example input 2

1 2

Execution Results

1 2


REAL intrinsic function
 Standard: F77 F90 F95 F2003 F2008 Example Program
<Syntax>
REAL ( A [ , KIND ] )

A : Integer, Real, Complex or a BOZ literal constant;
KIND : scalar Integer constant expression;

Result : if KIND is present, Real(Kind=KIND), otherwise if A is Complex then Real(Kind=Kind(A)), otherwise Real.
<Semantics>

If A is Complex, the result is the real part of A. If A is Real or Integer, the result is an approximation to A in the type and kind of the result.

If A is a BOZ literal constant it is interpreted as the internal representation (as a bitstring) of the result. Note that this bitstring must not be longer that the number of bits in the result, unless the excess bits are all leading zeroes. If the bitstring is shorter than the number of bits in the result, it is padded on the left with leading zeroes.

Like many intrinsic functions, this is elemental; the result has the same shape as A, with the conversion being applied elementwise.

<Related>
AIMAG intrinsic function, DBLE intrinsic function, COMPLEX type, REAL type.


REAL example program

<Example Program>

Program real_example
  Complex :: c(3) = [ (1,2),(3,4),(5,6) ]
  Print 1, Real(13), Real(c)
1 Format(4(2X,F0.5))
End Program

Execution Results

  13.00000  1.00000  3.00000  5.00000


REAL type

Standard: (F77) F90 F95 F2003 F2008 F2018 Example program

＜Syntax＞

REAL [ ( [ KIND= ] expression ) ]
DOUBLE PRECISION

The expression must be a scalar integer constant expression whose value identifies a valid kind of real.

REAL*2
REAL*4
REAL*8
REAL*16

＜Semantics＞

REAL declares entities (variables, functions, etc.) to be floating-point numbers. The KIND number determines the precision and exponent range of the numbers. The F90_KIND module contains named constants REAL16, REAL32, REAL64 and REAL128 which are convenient for specifying Reals with a particular size. The standard intrinsic module ISO_FORTRAN_ENV also contains those constants.

The SELECTED_REAL_KIND intrinsic function can be used to select a real kind based on decimal precision and exponent range requirements. The IEEE_SELECTED_REAL_KIND function in the standard intrinsic module IEEE_ARITHMETIC can also be used to select an ISO/IEC/IEEE 60559 conformant real kind.

The actual kind numbers used depend on whether “sequential”, “byte” or “unique” kind numbering is being used.

Sequential Kind Numbering (default)

KIND | 16 | 1 | 2 | 3
Name | REAL16 | REAL32 | REAL64 | REAL128
Precision | 3 | 6 | 15 | 30

Byte Kind Numbering (-kind=byte option)

KIND | 2 | 4 | 8 | 16
Name | REAL16 | REAL32 | REAL64 | REAL128
Precision | 3 | 6 | 15 | 30

Unique Kind Numbering (-kind=unique option)

KIND | 304 | 301 | 302 | 303
Name | REAL16 | REAL32 | REAL64 | REAL128
Precision | 3 | 6 | 15 | 30

REAL*2, REAL*4, REAL*8 and REAL*16 are synonyms for REAL(REAL16), REAL(REAL32), REAL(REAL64) and REAL(REAL128) respectively. These synonyms are not standard Fortran.

＜Related＞

CHARACTER type, COMPLEX type, Component Definition statement, DBLE intrinsic function, DIGITS intrinsic function, DOUBLE PRECISION type specifier, HUGE intrinsic function, IMPLICIT statement, INTEGER type, KIND intrinsic function, LOGICAL type, MAXEXPONENT intrinsic function, MINEXPONENT intrinsic function, PRECISION intrinsic function, RADIX intrinsic function, RANGE intrinsic function, REAL intrinsic function, SELECTED_REAL_KIND intrinsic function, Type Declaration statement


RECURSIVE attribute

Standard: F77 F90 F95 F2003 F2008 F2018 Example program

＜Syntax＞

RECURSIVE

The RECURSIVE keyword may appear only in the prefix of a FUNCTION or SUBROUTINE statement.

＜Semantics＞

The RECURSIVE keyword specifies that all procedures defined by this subprogram may be called recursively. (A subprogram can define several procedures by using the ENTRY statement.)

Note that in the case of a function, direct recursion is only possible if the RESULT clause is also used, as otherwise the function name is taken to mean the result variable name.

Prior to Fortran 2018, an elemental procedure was not permitted to have this attribute.

From Fortran 2018, all procedures, except for CHARACTER(*) functions, have this attribute by default, and thus may be called recursively. This includes elemental procedures. The NON_RECURSIVE attribute may be used to specify that a procedure will not be called recursively.

＜Related＞

ELEMENTAL attribute, ENTRY statement, FUNCTION statement, NON_RECURSIVE attribute, RESULT clause, SUBROUTINE statement


Reduction intrinsic functions

Standard: F77 F90 F95 F2003 F2008 F2018

＜Syntax＞

ALL ( MASK [ , DIM ] )
ANY ( MASK [ , DIM ] )
COUNT ( MASK [ , DIM , KIND ] )
FINDLOC ( ARRAY, VALUE [ , MASK, KIND, BACK ] )
FINDLOC ( ARRAY, VALUE, DIM [ , MASK, KIND, BACK ] )
IALL ( ARRAY [ , DIM , MASK ] )
IANY ( ARRAY [ , DIM , MASK ] )
IPARITY ( ARRAY [ , DIM , MASK ] )
MAXLOC ( ARRAY [ , MASK , KIND , BACK ] )
MAXLOC ( ARRAY, DIM [ , MASK , KIND , BACK ] )
MAXVAL ( ARRAY [ , MASK ] )
MAXVAL ( ARRAY, DIM [ , MASK ] )
MINLOC ( ARRAY [ , MASK , KIND , BACK ] )
MINLOC ( ARRAY, DIM [ , MASK , KIND , BACK ] )
MINVAL ( ARRAY [ , MASK ] )
MINVAL ( ARRAY, DIM [ , MASK ] )
PARITY ( MASK [ , DIM ] )
PRODUCT ( ARRAY [ , MASK ] )
PRODUCT ( ARRAY, DIM [ , MASK ] )
SUM ( ARRAY [ , MASK ] )
SUM ( ARRAY, DIM [ , MASK ] )

＜Semantics＞

The reduction intrinsic functions collapse an array using the specified operation to combine elements.

If an optional MASK is present, only the elements corresponding to true elements of the mask are combined.

If DIM is not present, the array is completely collapsed (i.e. every element is combined), returning a scalar value (except for FINDLOC, MAXLOC and MINLOC, which return a location vector of size equal to the rank of ARRAY).

If DIM is present, only that dimension is collapsed; the result has rank 1 less than ARRAY (or MASK), thus reducing shape [ s1, ... sDIM−1, sDIM, sDIM+1, ..., srank ] to [ s1, ... sDIM−1, sDIM+1, ..., srank ]; the value of each element in the result is obtained by combining the corresponding values in the collapsed dimension. Note that a rank 0 result is scalar.

＜Related＞

ALL intrinsic function, ANY intrinsic function, COUNT intrinsic function, FINDLOC intrinsic function, IALL intrinsic function, IANY intrinsic function, IPARITY intrinsic function, MAXLOC intrinsic function, MAXVAL intrinsic function, MINLOC intrinsic function, MINVAL intrinsic function, PARITY intrinsic function, PRODUCT intrinsic function, SUM intrinsic function,


REPEAT intrinsic function
Standard: F77 F90 F95 F2003 F2008 Example Program
<Syntax>

REPEAT ( STRING, NCOPIES )

STRING : scalar Character, any kind;
NCOPIES : scalar Integer, NCOPIES≥0;

Result : scalar Character(LEN=NCOPIES*LEN(STRING), KIND=KIND(STRING)).

<Semantics>

The result is the concatenation of NCOPIES copies of STRING.

<Related>
CHARACTER type, Concatenation (//) operator.


REPEAT example program

<Example Program>

Program repeat_example
  Character(*),Parameter :: a = 'abc.'
  Integer :: i
  Do i=0,5
    Print *, i, Repeat(a,i)
  End Do
End Program

Execution Results

 0
 1 abc.
 2 abc.abc.
 3 abc.abc.abc.
 4 abc.abc.abc.abc.
 5 abc.abc.abc.abc.abc.


RESHAPE intrinsic function
Standard: F77 F90 F95 F2003 F2008 Example Program
<Syntax>

RESHAPE ( SOURCE, SHAPE [ , PAD, ORDER ] )

SOURCE : array of any type;
SHAPE : Integer array with rank 1 and constant shape, 1≤SIZE(SHAPE)≤7;
PAD : array with the same type and type parameters as SOURCE;
ORDER : Integer array with rank 1, SIZE(ORDER)=SIZE(SHAPE);

Result : same type and type parameters as SOURCE, with shape SHAPE.

<Semantics>

If the ORDER argument is not present, the result is the array with shape SHAPE whose elements, in array element order, are the same as SOURCE; if SIZE(SOURCE)<PRODUCT(SHAPE), additional values are taken from PAD in array element order (repeatedly, if SIZE(SOURCE)+SIZE(PAD)<PRODUCT(SHAPE)).

If PAD is not present, or SIZE(PAD)=0, SIZE(SOURCE) must be greater than or equal to PRODUCT(SHAPE).

If ORDER is present, it must be a permutation vector with values [ 1 ... SIZE(SHAPE) ]. It specifies a multi-dimensional transposition that is applied to SOURCE before using its elements in the result. That is, the elements of A are taken in permuted subscript order ORDER(1), ... ORDER(rank of A). For example, if A is a 2-dimensional array,

  RESHAPE (A, [ SIZE(A,2),SIZE(A,1) ], ORDER = [ 2, 1 ] )
is equal to TRANSPOSE(A).

ORDER has no effect on the interpretation of the elements of PAD, which are always taken in array element order.

<Related>
SPREAD intrinsic function, TRANSPOSE intrinsic function.


RESHAPE example program

<Example Program>

Program reshape_example
  Implicit None
  Integer,Parameter :: v(6) = [ 1,2,3,4,5,6 ]
  Integer :: a(2,3), i
  a = Reshape(v, Shape(a))
  Print *, 'Reshape in default (array element) order'
  Do i=1, Size(a,1)
    Print 1, i, a(i,:)
1   Format(1X,'Row ',I0,' =',99(1X,I0))
  End Do
  a = Reshape(v, Shape(a), Order=[2,1])
  Print *, 'Reshape with Order argument'
  Do i=1, Size(a,1)
    Print 1, i, a(i,:)
  End Do
End Program
Execution Results

 Reshape in default (array element) order
 Row 1 = 1 3 5
 Row 2 = 2 4 6
 Reshape with Order argument
 Row 1 = 1 2 3


RESULT clause
Standard: F77 F90 F95 F2003 Example Program
<Syntax>
 | RESULT ( name ) The RESULT clause may only appear in the suffix of a FUNCTION or ENTRY statement.
<Semantics>
 | The RESULT clause specifies the name of the function result variable. If it is omitted, the result variable name is the same as the function name. Note that it is the result name that must appear in any specification statements within the function, not the name of the function itself (unless they are the same).
<Related>
 | ENTRY statement, FUNCTION statement


RESULT example program

<Example Program>

Program result_example
Real :: a=2, b=3, c=4
Real, External :: shiki1,shiki2
Print *, shiki1(2.,a,b,c)
Print *, shiki2(2.,a,b,c)
End Program
Real Function shiki1(x,a,b,c) Result( y )
Real, Intent(In) :: x,a,b,c
y = a*x**2 + b*x + c
End Function shiki1
Function shiki2(x,a,b,c) Result( y )
Real y
Real, Intent(In) :: x,a,b,c
y = a*x**2 + b*x + c
End Function
Execution Results

18.0000000
18.0000000


RETURN statement
Standard: F77 F90 F95 F2003 Example Program
<Syntax>
 | RETURN [ expression ] The expression is only allowed in a subroutine with an alternate return, and must be a scalar Integer.
<Semantics>
 | The RETURN statement completes execution of a procedure, returning control to the caller. In RETURN expression, if the expression has a value from 1 to the number of label arguments, control will be transferred to the corresponding label; this is called “alternate return”. It is not necessary to put a RETURN at the end of a subprogram, as executing the END statement has the same effect.
<Related>
 | CALL statement, ENTRY statement, END FUNCTION statement, END SUBROUTINE statement, FUNCTION statement, SUBROUTINE statement


<Example Program>

Program return_example
Real :: a=1., b=3., c=6.
Print *, shiki(a,b,c)
End
Real Function shiki(a,b,c)
shiki = 0.0
tmp = b**2 - 4.0*a*c
If (tmp<0.) Return
shiki = (-b+Sqrt(tmp))/(2.0*a)
End Function
Execution Results

0.0000000


REWIND statement
Standard: F77 F90 F95 F2003 Example Program
<Syntax>
REWIND expression
REWIND (rew-spec-list)
rew-spec-list ::= rew-spec [,rew-spec]...
rew-spec | ::= | [ UNIT= ] expression
 | | | ERR=label
 | | | IOMSG=variable
 | | | IOSTAT=variable

In the REWIND expression form, the expression shall be a scalar integer expression with non-negative value; it identifies the unit.
<Semantics>
Sets the file position of a unit to the beginning of the file. In the rew-spec-list form, the UNIT= keyword may be omitted only if it is the first item in the list.
Note that some files are incapable of being rewound (an error will occur).

The IOMSG= specifier was added in Fortran 2003; this sets a character string variable to an error message if an error occurs. The ERR= or IOSTAT= specifier is still needed to prevent termination on error.
<Related>
BACKSPACE statement, CLOSE statement, ENDFILE statement, ERR= specifier, IOMSG= specifier, IOSTAT= specifier, OPEN statement, PRINT statement, READ statement, UNIT= specifier, WRITE statement


<Example Program>

Program rewind_example
Open(1,File='TEMP',Status='OLD')
Rewind 1
n_lines = 0
Do
Read(1,'( )',End=10)
n_lines = n_lines + 1
End Do
10 Continue
Print *, n_lines
Close (1)
End
File contents: TEMP

1
2
5

Execution Results

3


ROUND= specifier

Standard: F77 F90 F95 F2003 F2008 F2018 Example program

＜Syntax＞

ROUND = expression

The expression must be a scalar character expression of default kind. It is permitted in the INQUIRE, OPEN, READ and WRITE statements. In the INQUIRE statement, it must be a variable designator and is assigned a value.

＜Semantics＞

The ROUND= specifier determines the default i/o rounding mode (for OPEN), returns the i/o rounding mode (for INQUIRE), or specifies the i/o rounding mode (for READ and WRITE).

The ROUND= specifier is not permitted in an OPEN, READ or WRITE statement that refers to an unformatted file.

In an INQUIRE statement, if the connection is formatted, the variable is assigned a value indicating the i/o rounding mode for the connection: 'COMPATIBLE', 'DOWN', 'NEAREST', 'PROCESSOR_DEFINED', 'UP' or 'ZERO'; if there is no connection, or the connection is unformatted, it is assigned 'UNDEFINED'.

In the OPEN, READ and WRITE statements it must evaluate to one of the previously listed values (except 'UNDEFINED'), ignoring case.

An input/output rounding mode of 'PROCESSOR_DEFINED' is not the same as any of the other rounding modes, but its effects are otherwise undefined. The effects of the other rounding modes are as follows:

  • ROUND='COMPATIBLE': round to nearest, with halves away from zero;
  • ROUND='DOWN': round towards −∞;
  • ROUND='NEAREST': round to nearest, with halves to even (like IEEE arithmetic);
  • ROUND='UP': round towards +∞;
  • ROUND='ZERO': round towards zero.

These effects are illustrated by the following table; output is with an F4.1 edit descriptor.

Internal Value | ROUND='COMPATIBLE' | ROUND='DOWN' | ROUND='NEAREST' | ROUND='UP' | ROUND='ZERO'
1.25 | 1.3 | 1.2 | 1.2 | 1.3 | 1.2
1.75 | 1.8 | 1.7 | 1.8 | 1.8 | 1.7
−1.25 | -1.3 | -1.3 | -1.2 | -1.2 | -1.2
−1.75 | -1.8 | -1.8 | -1.8 | -1.7 | -1.7

＜Related＞

FORMAT statement, INQUIRE statement, OPEN statement, WRITE statement


RRSPACING intrinsic function
Standard: F77 F90 F95 F2003 F2008 Example Program
<Syntax>

RRSPACING ( X )

X : Real with any kind;

Result : same type and kind as X.

<Semantics>

This function returns the reciprocal of the relative spacing of model numbers with the same kind as X, in the vicinity of X. If X is not a model number (for example, if X is an IEEE subnormal number), RRSPACING is the value for the nearest model number to X; if X is an IEEE infinity or NaN, the result is a NaN.

For a model number X, this is equal to ABS(SET_EXPONENT(X,DIGITS(X))).

Like many intrinsic functions, this is elemental; the result has the same shape as X, with the operation being applied elementwise.

<Related>
DIGITS intrinsic function, RADIX intrinsic function, REAL type, SET_EXPONENT intrinsic function, SPACING intrinsic function.


RRSPACING example program

<Example Program>

Program rrspacing_example
  Implicit None
  Real :: x(5) = [ 0.0, 1.0, 1.25, 1.5, -1.5*2.0**50 ]
  Print *,Rrspacing(x)
  Print *,Abs(Set_Exponent(x,Digits(x)))
End Program
Execution Results

   0.0000000   8.3886080E+06   1.0485760E+07   1.2582912E+07   1.2582912E+07
   0.0000000   8.3886080E+06   1.0485760E+07   1.2582912E+07   1.2582912E+07


SAME_TYPE_AS intrinsic function
Standard: F77 F90 F95 F2003 F2008 Example Program
<Syntax>
SAME_TYPE_AS ( A, B )
A : object of extensible type or CLASS(*);
B : object of extensible type or CLASS(*);

Result : Default Logical scalar.

Both A and B are permitted to be unallocated allocatables or disassociated pointers, but are not permitted to be undefined pointers.
<Semantics>

The result is true if and only if the dynamic type of A is the same as the dynamic type of B. Note that the dynamic type of unallocated allocatable or disassociated pointer is the same as its declared type; in the case of CLASS(*), there is no declared type. Either A or B is CLASS(*) and has a dynamic type that is not extensible, the result is processor dependent.

Note that simply knowing that a type is the same as another does not give you access to any of the extended components; to do this you need to use the SELECT TYPE construct.

<Related>
CLASS specifier, Derived Type Definition EXTENDS clause, EXTENDS_TYPE_OF intrinsic function, SELECT TYPE construct


SAME_TYPE_AS Example Program

<Example Program>

Module types
  Type t
    Real a
  End Type
  Type, Extends(t) :: et
    Real b
  End Type
End Module
Program example
  Use types
  Class(t),Pointer :: a, b, c
  Allocate(t::a)
  Allocate(et::b)
  Allocate(t::c)
  Print *,'Does A have the same type as B?', Same_Type_As(a, b)
  Print *,'Does A have the same type as C?', Same_Type_As(a, c)
End Program

Note: Execution Results
 Does A have the same type as B? F
 Does A have the same type as C? T


SAVE attribute
Standard: F77 F90 F95 F2003 Example Program
<Syntax>
type, SAVE [ , attr ]... :: decl-list

SAVE [ :: ] entity [ , entity ]...

SAVE

entity ::= name
| / common-block-name /
<Semantics>
The SAVE attribute specifies that a name is a local static variable, and retains its value after return from its procedure. A SAVE statement with no entity list specifies that all non-automatic entities in the procedure are saved. The SAVE attribute is also implicitly conferred on any variable that is given an initial value, either in its type declaration statement or in a DATA statement.

If a procedure that contains a saved variable is recursive, there is only one instance of that variable and it is shared between all instances of the procedure.

It is permitted to declare a variable to be saved in a main program; this has no effect.

The SAVE attribute can also be given to a common block; it specifies that all variables in the common block retain their value even when no active program unit is referencing the common block. This has no effect in NAGWare f95 (and all current Fortran compilers), because it saves common blocks by default.

Similarly, SAVE is permitted in a module, and specifies that all variables in the module retain their value even when no active program unit is referencing the module. This has no effect in NAGWare f95 (and all current Fortran compilers), because it saves module variables by default.
<Related>
Type Declaration statement


SAVE example program

<Example Program>

Program save_example
Integer, External :: fibonacci
Do I = 1, 5
Print *, fibonacci()
End Do
End
Integer Function fibonacci()
Integer, Save :: i1=1, i2=1
fibonacci = i1
next_i2 = i2 + i1
i1 = i2
i2 = next_i2
End Function
Execution Results

1
1
2
3
5


SCAN intrinsic function
Standard: F77 F90 F95 F2003 F2008 Example Program
<Syntax>

SCAN ( STRING, SET [ , BACK , KIND ] )

STRING : Character, any kind;
SET : same type and kind as STRING;
BACK : Logical;
KIND : scalar Integer constant expression;

Result : Integer or Integer(Kind=KIND).

<Semantics>

Searches STRING for an occurrence of any character in SET. If BACK is absent, or present with the value .FALSE., the search begins at the start of STRING; if BACK is present with the value .TRUE., the search begins at the end of STRING.

If there are no occurrences of any character of SET in STRING, the value zero is returned. If STRING or SET has length zero, there can be no characters found and therefore zero will be returned.

Like many intrinsic functions, this is elemental; if any of STRING, SET or BACK is an array, the result is also an array with the same shape and the operation being applied elementwise. Note that all array arguments must have the same shape.

In the unlikely event of the string being longer than 2GB, the KIND argument should be used to specify a 64-bit integer kind for the result.

<Related>
CHARACTER type, INDEX intrinsic function, VERIFY intrinsic function.


SCAN example program

<Example Program>

Program scan_example
  Character(52) :: a = 'She sells sea shells on the sea shore.'
  Character(4) :: set = 'aboz'
  Logical :: b(2) = [ .False.,.True. ]
  Integer :: i(2)
  i = Scan(a,set,b)
  Print *, i(1), a(i(1):i(1))
  Print *, i(2), a(i(2):i(2))
End Program
Execution Results

 13 a
 35 o


SELECT CASE construct

Standard: F77 F90 F95 F2003 F2008 F2018 Example program

＜Syntax＞

select-case-stmt
[ case-stmt
block ]...
end-select-stmt

＜Semantics＞

The SELECT CASE construct begins with a SELECT CASE statement and ends with an END SELECT statement. When the SELECT CASE statement is executed, its selector expression is evaluated; if its value satisfies one of the CASE conditions, the corresponding block is executed, otherwise control is transferred to the END SELECT statement.

Note that the CASE conditions must be mutually exclusive (so that no more than one condition can be satisfied at a time).

＜Related＞

CASE statement, CASE DEFAULT statement, END SELECT statement, SELECT CASE statement


SELECT CASE statement

Standard: F77 F90 F95 F2003 F2008 F2018 Example program

＜Syntax＞

[ construct-name : ] SELECT CASE ( expression )

The SELECT CASE statement can appear only as the first statement of a SELECT CASE construct. The expression must be scalar and of type Integer, Real or Character.

＜Semantics＞

The SELECT CASE statement introduces a SELECT CASE construct. This selects a single block of statements for execution, based on the value of the expression. If no block is selected, execution continues following the END SELECT statement.

＜Related＞

CASE statement, CASE DEFAULT statement, END SELECT statement, SELECT CASE construct


SELECT TYPE construct

Standard: F77 F90 F95 F2003 F2008 F2018 Example program

＜Syntax＞

select-type-stmt
[ type-guard-stmt
block ]
end-select-stmt

where

type-guard-stmt ::= type-is-stmt | class-is-stmt | class-default-stmt

If the SELECT TYPE statement has a construct-name, the END SELECT statement shall have the same construct name.

The syntax of the SELECT TYPE statement is as follows:

[ construct-name : ] SELECT TYPE ( [ associate-name => ] selector )

where selector ::= variable-name | variable | expression

The associate-name may be omitted only if selector is a variable-name; in that case, the associate name is the same as the variable name.

＜Semantics＞

The SELECT TYPE tests the dynamic type of a polymorphic variable or expression (the selector), and selects at most a single block for execution based on that type.

A TYPE IS block is executed if and only if the dynamic type is the type named in the TYPE IS statement. A CLASS IS block is executed if no TYPE IS statement matches, the dynamic type is an extension of the type named in the CLASS IS statement, and no more specific CLASS IS statement appears in the construct. A CLASS DEFAULT block is executed if no other block is executed.

The associate name of a SELECT TYPE construct is local to the construct; its type and rank are determined by the construct and are unaffected by any declaration outside the construct.

Throughout the construct, the associate name is a variable if and only if the selector is a variable-name or variable; any changes to the associate name affect the variable with which it is associated. If it is associated with an expression, the associate name is not permitted to appear in any context that requires a variable.

Within a TYPE IS block, the associate name is not polymorphic and has the type specified in the TYPE IS statement. Within a CLASS IS block, the associate name is polymorphic; it has the declared type specified in the CLASS IS statement. Within a CLASS DEFAULT block, the associate name is polymorphic, and has the same declared type as the selector.

In all cases, the associate name has the same dynamic type, rank and array bounds as the selector.

If the selector is a pointer or allocatable, it must be associated or allocated; the associate name does not have the POINTER or ALLOCATABLE attribute.

＜Related＞

CLASS specifier, CLASS DEFAULT statement, CLASS IS statement, END SELECT statement, TYPE statement, TYPE IS statement


SELECTED_CHAR_KIND intrinsic function
Standard: F77 F90 F95 F2003 F2008
<Syntax>
SELECTED_CHAR_KIND ( NAME )

NAME : scalar Character with default kind;

Result : scalar Integer with default kind.
<Semantics>

The SELECTED_CHAR_KIND intrinsic function returns the kind number for the Character type that provides the named character set. Standard character set names are 'DEFAULT' (for default Character), 'ASCII' (for ISO 646 characters) and 'ISO_10646' (for the 32-bit encoding of ISO/IEC 10646 characters). The ISO/IEC 10646 character set is also known as Unicode.

The NAG Fortran Compiler additionally recognises 'JIS_0213' (for JIS X 0213 characters) and 'UCS_2' (for the 16-bit encoding of ISO/IEC 10646 characters); it also accepts 'JIS_0208' and 'SHIFT_JIS' as synonyms for 'JIS_0213', and 'UCS_4' as a synonym for 'ISO_10646'.

If the name is not recognised, or the character set is not supported, the value −1 is returned.

<Related>
Component definition statement, CHARACTER type, SELECTED_INT_KIND intrinsic function, SELECTED_REAL_KIND intrinsic function, Type declaration statement


SELECTED_INT_KIND intrinsic function
Standard: F77 F90 F95 F2003 F2008
<Syntax>
 | SELECTED_INT_KIND ( R ) R : scalar Integer; Result : scalar Integer with default kind.
<Semantics>
 | The SELECTED_INT_KIND intrinsic function returns the kind number for an Integer type that has a decimal exponent range of at least R; that is, it can represent all the values v such that −10**R ≤ v ≤ 10**R. If more than one kind satisfies the condition, the one with the smallest range is returned. If no kind satisfies the condition, the value −1 is returned.
<Related>
 | Component definition statement, INTEGER type, RANGE intrinsic function, SELECTED_CHAR_KIND intrinsic function, SELECTED_REAL_KIND intrinsic function, Type declaration statement


SELECTED_REAL_KIND intrinsic function
Standard: F77 F90 F95 F2003 F2008
<Syntax>
SELECTED_REAL_KIND ( [ P , R , RADIX ] )

P : scalar Integer;
R : scalar Integer;
RADIX : scalar Integer;

Result : scalar Integer with default kind.
<Semantics>
The SELECTED_REAL_KIND intrinsic function returns the kind number for a Real type that has a precision of at least P (if P is present) and a decimal exponent range of at least R (if R is present), and a radix of RADIX (if RADIX is present). At least one argument must be present. If more than one kind satisfies the condition, the one with the smallest precision is returned.

If no kind satisfies the condition, the value −1 is returned to indicate that P could not be satisfied, −2 indicates that R could not be satisfied, −3 indicates that neither P nor R could be satisfied, and −4 indicates that both P and R could be satisfied but not both at once.

<Related>
Component definition statement, PRECISION intrinsic function, RADIX intrinsic function, RANGE intrinsic function, REAL type, SELECTED_INT_KIND intrinsic function, Type declaration statement


SEQUENCE statement
Standard: F77 F90 F95 F2003
<Syntax>
 | SEQUENCE The SEQUENCE statement may occur only in a derived type definition. It must precede all component definition statements.
<Semantics>
 | The SEQUENCE statement declares a derived type to be a sequence type. Variables of a sequence type are permitted to appear in COMMON blocks. Also, two sequence types are considered to be the same type if their components have the same name, type, type parameters and appear in the same order. Use of sequence types is not recommended, as they are less efficient and more error-prone than ordinary derived types.
<Related>
 | Derived Type Definition


SET_EXPONENT intrinsic function
Standard: F77 F90 F95 F2003 F2008 Example Program
<Syntax>

SET_EXPONENT ( X, I )

X : Real with any kind;
I : Integer with any kind;

Result : same type and kind as X.

<Semantics>

The result is the value obtained by taking the mantissa of X with an exponent value of I; this is equal to SCALE(X,I−EXPONENT(X)) except for IEEE infinities and NaNs, where the result is a NaN. (An alternative formulation would be FRACTION(X)*REAL(RADIX(X))**I.)

Like many intrinsic functions, this is elemental; the result has the same shape as X, with the operation being applied elementwise.

<Related>
EXPONENT intrinsic function, FRACTION intrinsic function, MAXEXPONENT intrinsic function, MINEXPONENT intrinsic function, RADIX intrinsic function, SCALE intrinsic function, REAL type.


SHAPE intrinsic function
Standard: F77 F90 F95 F2003 Example Program
<Syntax>
 | SHAPE ( ARRAY [ , KIND ] ) ARRAY : array of any type and rank N; KIND : scalar Integer constant expression; Result : Integer or Integer(Kind=KIND).
<Semantics>
 | The SHAPE intrinsic function returns the shape of an array as a vector of length N. The value of each element in the result is the extent of (number of elements in) that dimension of the array. In Fortran 2003, the KIND argument should be used when any extent might exceed the range of a default integer.
<Related>
 | DIMENSION attribute, LBOUND intrinsic function, SIZE intrinsic function, UBOUND intrinsic function


<Example Program>

Program shape_example
Real a(0:2,4)
Print *, Shape(a)
End
Execution Results

3 4


SHIFTA intrinsic function
Standard: F77 F90 F95 F2003 F2008 Example Program
<Syntax>
 | SHIFTA ( I, SHIFT ) I : Integer; SHIFT : Integer, conformable with I; Result : Same type and kind as I.
<Semantics>
 | The value of the result is obtained by shifting I to the right SHIFT times, but the leftmost bit (the “sign bit”) is replicated instead of becoming zero. It is required that 0≤SHIFT≤BIT_SIZE(I). This is an elemental function; if any argument is an array the result is an array of the same shape, with the SHIFTA operation being applied elementwise. The “A” in the name of the function is intended to mean “arithmetic”; however, SHIFTA on a negative number is only the same as division by a power of two if there are no one bits shifted out, otherwise it is rounded differently. For example, SHIFTA(-3,1) is -2, whereas -3/2 is -1.
<Related>
 | IAND intrinsic function, IEOR intrinsic function, IOR intrinsic function, ISHFT intrinsic function, ISHFTC intrinsic function, LEADZ intrinsic function, MASKL intrinsic function, MASKR intrinsic function, NOT intrinsic function, POPCNT intrinsic function, POPPAR intrinsic function, SHIFTL intrinsic function, SHIFTR intrinsic function, TRAILZ intrinsic function


SHIFTA example program

<Example Program>

Program shifta_example
Integer,Parameter :: i8 = Selected_Int_Kind(2)
Integer(i8) :: a(3) = [ Int(z'f0',i8),Int(z'70',i8),Int(z'0f',i8) ]
Do i=0,3
Print '(I3,3(2X,B8.8))',i,Shifta(a,i)
End Do
End Program
Note: Execution Results

0 11110000 01110000 00001111
1 11111000 00111000 00000111
2 11111100 00011100 00000011
3 11111110 00001110 00000001


SHIFTL intrinsic function
Standard: F77 F90 F95 F2003 F2008 Example Program
<Syntax>
 | SHIFTL ( I, SHIFT ) I : Integer; SHIFT : Integer, conformable with I; Result : Same type and kind as I.
<Semantics>
 | The value of the result is obtained by shifting I to the left SHIFT times; it is required that 0≤SHIFT≤BIT_SIZE(I). Bits shifted in on the right are zero. This is an elemental function; if any argument is an array the result is an array of the same shape, with the SHIFTL operation being applied elementwise.
<Related>
 | IAND intrinsic function, IEOR intrinsic function, IOR intrinsic function, ISHFT intrinsic function, ISHFTC intrinsic function, LEADZ intrinsic function, MASKL intrinsic function, MASKR intrinsic function, NOT intrinsic function, POPCNT intrinsic function, POPPAR intrinsic function, SHIFTA intrinsic function, SHIFTR intrinsic function, TRAILZ intrinsic function


SHIFTL example program

<Example Program>

Program shiftl_example
Integer,Parameter :: i8 = Selected_Int_Kind(2)
Integer(i8) :: a(3) = [ Int(z'f0',i8),Int(z'70',i8),Int(z'0f',i8) ]
Do i=0,3
Print '(I3,3(2X,B8.8))',i,Shiftl(a,i)
End Do
End Program
Note: Execution Results

0 11110000 01110000 00001111
1 11100000 11100000 00011110
2 11000000 11000000 00111100
3 10000000 10000000 01111000


SHIFTR intrinsic function
Standard: F77 F90 F95 F2003 F2008 Example Program
<Syntax>
 | SHIFTR ( I, SHIFT ) I : Integer; SHIFT : Integer, conformable with I; Result : Same type and kind as I.
<Semantics>
 | The value of the result is obtained by shifting I to the right SHIFT times; it is required that 0≤I≤BIT_SIZE(I). Bits shifted in on the left are zero. This is an elemental function; if any argument is an array the result is an array of the same shape, with the SHIFTR operation being applied elementwise.
<Related>
 | IAND intrinsic function, IEOR intrinsic function, IOR intrinsic function, ISHFT intrinsic function, ISHFTC intrinsic function, LEADZ intrinsic function, MASKL intrinsic function, MASKR intrinsic function, NOT intrinsic function, POPCNT intrinsic function, POPPAR intrinsic function, SHIFTA intrinsic function, SHIFTL intrinsic function, TRAILZ intrinsic function


SHIFTR example program

<Example Program>

Program shiftr_example
Integer,Parameter :: i8 = Selected_Int_Kind(2)
Integer(i8) :: a(3) = [ Int(z'f0',i8),Int(z'70',i8),Int(z'0f',i8) ]
Do i=0,3
Print '(I3,3(2X,B8.8))',i,Shiftr(a,i)
End Do
End Program
Note: Execution Results

0 11110000 01110000 00001111
1 01111000 00111000 00000111
2 00111100 00011100 00000011
3 00011110 00001110 00000001


SIGN intrinsic function

Standard: F77 F90 F95 F2003 F2008 F2018 Example program

＜Syntax＞

SIGN ( A, B )

A : Integer or Real;
B : Same type and kind as A, conformable with A;
Fortran 2018 permits B to have a different kind;

Result : Same type and kind as A.

＜Semantics＞

The result has the magnitude of A with the sign of B.

Prior to Fortran 95, if B was zero it was treated as being positive, even when it was an IEEE negative zero. From Fortran 95 onwards, the treatment of IEEE negative zero depends on the compiler; the NAG Fortran compiler treats IEEE negative zero as negative, unless the -f90_sign option was used at compilation time.

Like many intrinsic functions, this is elemental; if either (or both) of A and B is an array, the result will be an array with that shape, with the value being computed elementwise.

＜Related＞


SIGN= specifier
Standard: F77 F90 F95 F2003 Example Program
<Syntax>
SIGN = expression

The expression must be a scalar character expression of default kind. It is permitted in the INQUIRE, OPEN and WRITE statements. In the INQUIRE statement, it must be a variable designator, and is assigned the value 'PLUS', 'SUPPRESS', 'PROCESSOR_DEFINED' or 'UNDEFINED'; in OPEN and WRITE it must evaluate to 'PLUS', 'SUPPRESS' or 'PROCESSOR_DEFINED'(ignoring case).
<Semantics>
The SIGN= specifier determines the default sign mode (for OPEN), returns the default sign mode (for INQUIRE), or specifies the sign mode (for WRITE).

The SIGN= specifier is not permitted in an OPEN or WRITE statement that refers to an unformatted file.

If a file is preconnected, or is opened without a SIGN= specifier, the default sign mode is 'PROCESSOR_DEFINED'.

The sign mode determines whether the optional plus sign is produced when writing a positive numeric value. If the sign mode is 'PLUS', the plus sign is produced (providing it will fit into the format field). If the sign mode is 'SUPPRESS', the plus sign is not produced. If the sign mode is 'PROCESSOR_DEFINED', whether it is produced or not depends on the Fortran processor; for the NAG Fortran Compiler this has the same effect as SIGN='SUPPRESS'.

The current sign mode may be overridden within a format by use of the SP (sign plus), SS (sign suppress) and S (sign processor_defined) edit descriptors.

In an INQUIRE statement, the value assigned is 'UNDEFINED' if the file is connected for unformatted input/output or if there is no connection.

<Related>
FORMAT statement, INQUIRE statement, OPEN statement, WRITE statement


<Example Program>

Program sign_example
Write (*,1,Sign='Plus') 1,2,3
1 Format(1X,I5,SS,I5,SP,I5)
Write (*,1,Sign='Suppress') 1,2,3
End Program
Execution Results

+1 2 +3
1 2 +3


SIN intrinsic function
 Standard: F77 F90 F95 F2003 F2008 Example Program
<Syntax>
 | SIN ( X ) X : Real or Complex; Result : Same type and kind as X.
<Semantics>
 | The value of the result is an approximation to the sine of X. Like many intrinsic functions, this is elemental; the result has the same shape as X, with the operation being applied elementwise. If X is of type Real, it specifies the angle in radians. If X is of type Complex, the real part is interpreted as radians.
<Related>
 | ASIN intrinsic function, COS intrinsic function, SINH intrinsic function. TAN intrinsic function,


SIN example program

<Example Program>

Program sin_example
  Real, Dimension(2,3) :: a
  Complex, Dimension(3) :: c
  a = Reshape( [ 0.0,0.2,-0.4,0.6,-0.8,1.57 ], [ 2,3 ])
  c = [ (0.2,0.0),(3.1415926,0.6),(-1.5707963,-0.8) ]
  Print 1, Sin(a)
1 Format(6(2X,F0.5))
  Print 2, Sin(c)
2 Format(3(2X,'(',F0.5,',',F0.5,')'))
End Program

Execution Results

  .00000  .19867  -.38942  .56464  -.71736  1.00000
  (.19867,.00000)  (.00000,-.63665)  (-1.33744,-.00001)


SINH intrinsic function
 Standard: F77 F90 F95 F2003 F2008 Example Program
<Syntax>
SINH ( X )

X : Real or Complex;

Result : Same type and kind as X.
<Semantics>

The value of the result is an approximation to the hyperbolic sine of X. Like many intrinsic functions, this is elemental; the result has the same shape as X, with the operation being applied elementwise.

If X is of type Complex, its imaginary part is an angle in radians. Note that SINH(X) is identical to (0,-1)*SIN((0,1)*X).

<Related>
ASINH intrinsic function, COSH intrinsic function, SIN intrinsic function.


SINH example program

<Example Program>

Program sinh_example
  Real, Dimension(2,3) :: a
  Complex, Dimension(3) :: c
  a = Reshape( [ 0.0,0.2,-0.4,0.6,-1.2,5.7 ], [ 2,3 ])
  c = [ (0.2,0.0),(0.5,-1.5707963),(5.7,1.5707963) ]
  Print 1, Sinh(a)
1 Format(6(2X,F0.5))
  Print 2, Sinh(c)
2 Format(3(2X,'(',F0.5,',',F0.5,')'))
End Program

Execution Results

  .00000  .20134  -.41075  .63665  -1.50946  149.43199
  (.20134,.00000)  (.00000,-1.12763)  (.00001,149.43535)


SIZE intrinsic function
Standard: F77 F90 F95 F2003 Example Program
<Syntax>
SIZE ( ARRAY [ , DIM , KIND ] )

ARRAY : array of any type and rank N;
DIM : scalar Integer in the range 1-N;
KIND : scalar Integer constant expression;

Result: Integer or Integer(Kind=KIND).
<Semantics>
The SIZE intrinsic function returns the number of elements in the array (if DIM is absent), or the extent of the array in dimension DIM if DIM is present.

In Fortran 2003, the KIND argument should be used when the number of elements might exceed the range of a default integer.

<Related>
DIMENSION attribute, LBOUND intrinsic function, SHAPE intrinsic function, UBOUND intrinsic function


SIZE= specifier
Standard: F77 F90 F95 F2003
<Syntax>
 | SIZE = variable The SIZE= specifier may appear only as a ci-spec in a formatted READ statement that also has the ADVANCE='NO' specifier. The variable shall be a scalar Integer.
<Semantics>
 | The SIZE= specifier sets the variable to the number of characters transferred by data edit descriptors during execution of the READ statement. This is most useful in conjunction with the EOR= specifier.
<Related>
 | ADVANCE= specifier, EOR= specifier, READ statement


<Example Program>

Program size_example
Real a(0:2,4)
Print *,Size(a)
Print *,Size(a,Dim=1)
Print *,Size(a,Dim=2)
End
Execution Results

12
3
4


SOURCE= specifier

Standard: F77 F90 F95 F2003 F2008 Example program

＜Syntax＞

SOURCE = expression

The SOURCE= specifier may occur only in an ALLOCATE statement. If SOURCE= appears, Fortran 2003 permitted only one item to be allocated; Fortran 2008 permits multiple items to be allocated. Each item to be allocated must be type-compatible with the SOURCE= expression.

＜Semantics＞

With SOURCE=, the item is allocated to have the same dynamic type and value as the SOURCE= expression. This operation is sometimes known as “cloning”.

If an item is an array but the SOURCE= expression is scalar, the scalar value is broadcast to every element of the item.

If the SOURCE= expression is an array, Fortran 2003 requires the item being allocated to have that same shape specified. Fortran 2008 permits the array shape to be omitted in this case; the bounds of the allocation are taken from the bounds of the SOURCE= expression.

＜Related＞

ALLOCATE statement, CLASS specifier, MOLD= specifier


SPACING intrinsic function
Standard: F77 F90 F95 F2003 F2008 Example Program
<Syntax>

SPACING ( X )

X : Real with any kind;

Result : same type and kind as X.

<Semantics>

This function returns the spacing of model numbers with the same kind as X, in the vicinity of X. If X is not a model number (for example, if X is an IEEE subnormal number), SPACING is the value for the nearest model number to X; if X is an IEEE infinity or NaN, the result is a NaN.

For nonzero finite numbers, this is equal to REAL(RADIX(X),KIND(X))**MAX(EXPONENT(X)-DIGITS(X),MINEXPONENT(X)-1). Note that the spacing of model numbers in the vicinity of zero is TINY(X).

Like many intrinsic functions, this is elemental; the result has the same shape as X, with the operation being applied elementwise.

<Related>
DIGITS intrinsic function, RADIX intrinsic function, EXPONENT intrinsic function, MINEXPONENT intrinsic function, REAL type, RRSPACING intrinsic function, TINY intrinsic function.


SPACING example program

<Example Program>

Program spacing_example
  Implicit None
  Real :: x(5) = [ 0.0, 1.25, 1.5, 15.0, -1.5*2.0**50 ]
  Print 1,Spacing(x)
1 Format(1X,99ES15.6)
  Print 1, Tiny(x), Real(Radix(x(2:)),Kind(x(2:)))**Max(Exponent(x(2:))-Digits(x),MinExponent(x)-1)
End Program
Execution Results

    1.175494E-38   1.192093E-07   1.192093E-07   9.536743E-07   1.342177E+08
    1.175494E-38   1.192093E-07   1.192093E-07   9.536743E-07   1.342177E+08


SPREAD intrinsic function
Standard: F77 F90 F95 F2003 Example Program
<Syntax>
 | SPREAD(ARRAY,DIM,NCOPIES) ARRAY : scalar or array of any type and rank N DIM : Scalar Integer in the rank 1 to N+1 NCOPIES : Scalar Integer The rank N of ARRAY must be less than 7.
<Semantics>
 | Returns an array of rank N+1, with the same type as ARRAY. The new dimension is added as dimension DIM, and its extent is NCOPIES. If NCOPIES is less than zero it is treated as zero. Each slice of the result through the new dimension DIM has the same value as ARRAY.
<Related>
 | DIMENSION attribute, RESHAPE intrinsic function, SHAPE intrinsic function, SIZE intrinsic function


<Example Program>

Program spread_example
Real :: a(2) = (/ 1.,2. /)
Real b(3,2), c(2,3)
b = Spread(a,Dim=1,Ncopies=3)
c = Spread(a,Dim=2,Ncopies=3)
Print *, b(1,:)
Print *, b(2,:)
Print *, b(3,:)
Print *, c(1,:)
Print *, c(2,:)
End
Execution Results

1.0000000 2.0000000
1.0000000 2.0000000
1.0000000 2.0000000
1.0000000 1.0000000 1.0000000
2.0000000 2.0000000 2.0000000


SQRT intrinsic function
 Standard: F77 F90 F95 F2003 F2008 Example Program
<Syntax>
 | SQRT ( X ) X : Real or Complex; Result : Same type and kind as X.
<Semantics>
 | The value of the result is an approximation to the square root of X. Like many intrinsic functions, this is elemental; the result has the same shape as X, with the operation being applied elementwise. If X is of type Real, it must be greater than or equal to zero. If X is of type Complex, the result is the principal value with the real part non-negative; if the real part of the result is zero, the imaginary part of the result has the same sign as the imaginary part of X.
<Related>


SQRT example program

<Example Program>

Program sqrt_example
  Real :: a(3) = [ 0,2,4 ]
  Complex :: c(3) = [ (0,1), (-1,0), (5,5) ]
  Print 1, Sqrt(a)
1 Format(3(2X,F0.5))
  Print 2, Sqrt(c)
2 Format(3(2X,'(',F0.5,',',F0.5,')'))
End Program

Execution Results

  .00000  1.41421  2.00000
  (.70711,.70711)  (.00000,1.00000)  (2.45673,1.01761)


STAT= specifier

Standard: F77 F90 F95 F2003 F2008 F2018 Example program

＜Syntax＞

STAT = variable

The variable must be a scalar Integer. It should be able to support values from −9999 to +9999, i.e. it should be at least 16 bits.

The STAT= specifier is allowed in ALLOCATE and DEALLOCATE statements, the image control statements CHANGE TEAM, END TYPE, LOCK, SYNC ALL, SYNC IMAGES, SYNC MEMORY and UNLOCK, and in image selectors. A STAT= variable in an image control statement or image selector is not allowed to be a coindexed object.

＜Semantics＞

The STAT= specifier in ALLOCATE or DEALLOCATE sets its variable to the status of the allocation or deallocation. If all allocations or deallocations succeed, the variable will be set to zero. If any allocation or deallocation fails, the variable will be set to an error code. These error codes for STAT= may be found in the F90_STAT module.

The STAT= specifier in an image control statement sets the variable to zero if the operation was successful, and to an error code otherwise.

The STAT= specifier in an image selector sets the variable to STAT_FAILED_IMAGE (from ISO_FORTRAN_ENV) if the image selected is a failed image, and to zero otherwise.

＜Related＞

ALLOCATE statement, CHANGE TEAM statement, DEALLOCATE statement, END TEAM statement, ERRMSG= specifier, EVENT POST statement, EVENT WAIT statement, Image selectors, LOCK statement, SYNC ALL statement, SYNC IMAGES statement, SYNC MEMORY statement, UNLOCK statement


STOP statement

Standard: F77 F90 F95 F2003 F2008 F2018 Example program

＜Syntax＞

STOP [ expression ] [ , QUIET = logical-expression ]

Before Fortran 2008, the expression was required to be an unsigned integer literal constant with at most five digits, or a scalar character literal of default kind. In Fortran 2008, the expression is permitted to be any scalar constant expression of type Integer or Character, in both cases the kind must be the default kind. Fortran 2018 further permits the expression to be non-constant.

The logical-expression must be scalar.

＜Semantics＞

The STOP statement initiates normal program termination. Any files that are open will be closed properly (unlike error termination). Execution of the END statement of the main program will also cause normal termination.

In a coarray program with multiple images, normal termination only stops the executing image; the remaining images continue to execute, and continue to have access to coarray data on the stopped image. The whole program only finishes execution when every image has normally terminated.

Normal termination, whether by a STOP statement or otherwise, will display an informative message on the ERROR_UNIT if any IEEE exception is signalling at that time, unless QUIET= appears and the logical-expression has the value .TRUE.; QUIET=.TRUE. also suppresses display of the “stop code” (expression).

The remaining details apply to the NAG Fortran Compiler (they are not guaranteed by the Fortran standard).

If expression appears and QUIET=.TRUE. does not appear, the value of the expression is displayed on the standard error unit, prefixed with “STOP: ”. An integer value is displayed in decimal (I0 format) and a character value is displayed without quotes (A format). No message is displayed if there is no expression.

If expression appears and is of type integer, the lower eight bits of its value are returned as the process exit status; otherwise, the process exit status is zero.

＜Related＞

END statement, END PROGRAM statement, ERROR STOP statement, PAUSE statement


STOPPED_IMAGES intrinsic function

Standard: F77 F90 F95 F2003 F2008 F2018 Example program

＜Syntax＞

STOPPED_IMAGES ( [ TEAM, KIND ] )

TEAM : scalar of type TEAM_TYPE from the intrinsic module ISO_FORTRAN_ENV, whose value must identify the current team or an ancestor team;
KIND : scalar Integer constant expression;

Result: Integer or Integer(Kind=KIND). The result is an array of rank one.

＜Semantics＞

Returns the image numbers of images, in the specified team, known by the invoking image to have stopped. The size of the result is the number of images known to have stopped. If STAT_STOPPED_IMAGE was returned for an operation with the specified team, the size will be non-zero.

If TEAM is absent, the specified team is the current team.

The KIND argument is completely unnecessary as default Integer is big enough to represent two billion images.

＜Related＞

FAILED_IMAGES intrinsic function, FORM TEAM statement, IMAGE_STATUS intrinsic function, STOP statement


STORAGE_SIZE intrinsic function
Standard: F77 F90 F95 F2003 F2008 Example Program
<Syntax>
STORAGE_SIZE ( A [ , KIND ] )

A : scalar or array of any type and rank;
KIND : scalar Integer constant expression;

Result : Integer or Integer(Kind=KIND).
<Semantics>

This function returns the size, in bits, that would be occupied in memory by an array element with the dynamic type and type parameters of A.

This is an inquiry function, so A need not be defined; indeed, if it is not CLASS(*) and does not have any deferred type parameters, it is permitted to be disassociated or unallocated.

<Related>
BIT_SIZE intrinsic function, LEN intrinsic function, SIZE intrinsic function.


STORAGE_SIZE example program

<Example Program>

Program storage_size_example
  Real x, y(100)
  Character(:), Allocatable :: z
  Print *,Storage_Size(x)
  Print *,Storage_Size(y)
  z = 'Hello Everybody!!!'
  Print *,Storage_Size(z)
End Program
Execution Results
 32
 32
 144


SUBMODULE statement

Standard: F77 F90 F95 F2003 F2008 F2018 Example program

＜Syntax＞

SUBMODULE ( ancestor-module-name [ : parent-submodule-name ] ) submodule-name

The SUBMODULE statement is the first statement of a SUBMODULE program unit, which has the syntax:
submodule-stmt
specification-part
[ contains-stmt
[ module-subprogram ]... ]
END [ SUBMODULE [ submodule-name ] ]

The ancestor-module-name is the name of a module with one or more separate module procedures, parent-submodule-name (if present) is the name of another submodule of that module, and submodule-name is the name of the submodule being defined.

＜Semantics＞

The submodules of a module form a tree structure, with successive submodules being able to extend others; however, the name of a submodule is unique within that module. This structure is to facilitate creation of internal infrastructure (types, constants, and procedures) that can be used by multiple submodules, without having to put all the infrastructure inside the module itself.

The submodule being defined accesses its parent module or submodule by host association; for entities from the module, this includes access to PRIVATE entities. Any local entity it declares in the specification-part will therefore block access to an entity in the host that has the same name.

The entities (variables, types, procedures) declared by the submodule are local to that submodule, with the sole exception of separate module procedures that are declared in the ancestor module and defined in the submodule. No procedure is allowed to have a binding name, again, except in the case of a separate module procedure, where the binding name must be the same as in the interface.

Submodule information for use by other submodules is stored by the NAG Fortran Compiler in files named module.submodule.sub, in a format similar to that of .mod files. The -nomod option, which suppresses creation of .mod files, also suppresses creation of .sub files.

＜Related＞

CONTAINS statement, END SUBMODULE statement, MODULE statement, Separate module procedures


SUBROUTINE statement

Standard: (F77) F90 F95 F2003 F2008 F2018 Example program

＜Syntax＞

[ prefix ] SUBROUTINE name [ ( args ) [ bind-attr ] ]

args ::= [ arg [ , arg ]... ]
arg ::= name | *}

bind-attr ::= BIND ( C [ , NAME=expression ] )

prefix | ::= | ELEMENTAL
 | | | IMPURE
 | | | MODULE
 | | | NON_RECURSIVE
 | | | PURE
 | | | RECURSIVE

No more than one of each kind of prefix is allowed in a single SUBROUTINE statement. If IMPURE appears, PURE must not appear. If MODULE appears, the interface or definition must be for a separate module procedure. If NON_RECURSIVE appears, RECURSIVE must not appear.

The SUBROUTINE statement can only occur as the first statement of a subroutine subprogram or interface body. The syntax of a subroutine subprogram is as follows.
subroutine-stmt
specification-part
executable-part
[ contains-stmt
[ internal-subprogram ]... ]
end-subroutine-stmt
An internal-subprogram is a function-subprogram or a subroutine-subprogram, and is not allowed to itself have a contains-stmt.

The syntax of a subroutine interface body is simply:

subroutine-stmt
specification-part
end-subroutine-stmt

＜Semantics＞

The SUBROUTINE statement begins a subroutine subprogram.

Each dummy argument that is * is an alternate return; the corresponding actual argument must be a label (prefixed by ‘*’). It is possible to transfer control to one of these labels on return from a subroutine by including an expression on the RETURN statement; if the expression has the value 1 control is transferred to the first label, etc.. If the expression is less than 1 or more than the number of label arguments, execution continues with the statement following the CALL statement. Alternate returns are error-prone and their use is not recommended.

＜Related＞

BIND attribute, CALL statement, CONTAINS statement, ELEMENTAL attribute, END SUBROUTINE statement, ENTRY statement, FUNCTION statement, IMPURE attribute, NON_RECURSIVE attribute, PURE attribute, RECURSIVE attribute, RETURN statement, Separate module procedures


<Example Program>

Program subroutine_example
Real x1,x2
Call shiki(1.0,3.0,2.0,x1,x2)
Print *, x1,x2
End
Subroutine shiki(a,b,c,x1,x2)
Real, Intent(In) :: a,b,c
Real, Intent(Out) :: x1,x2
tmp = b**2 - 4.0*a*c
x1 = (-b+Sqrt(tmp))/(2.0*a)
x2 = (-b-Sqrt(tmp))/(2.0*a)
End Subroutine shiki
Execution Results

-1.0000000 -2.0000000


SUM intrinsic function
Standard: F77 F90 F95 F2003 Example Program
<Syntax>
 | SUM ( ARRAY, DIM [ , MASK ] ) SUM ( ARRAY [ , MASK ] ) ARRAY : rank N array of type Integer, Real or Complex; DIM : scalar Integer in the range 1 to N; MASK : array of type Logical with the same shape as ARRAY; Result: Same type and kind as ARRAY.
<Semantics>
 | The result is ARRAY reduced by addition ( + ). If DIM is absent, this is a scalar equal to the sum of all the masked elements of ARRAY. If DIM is present, the result has rank N-1 and the shape of ARRAY with dimension DIM removed; each element of the result is the sum of the masked elements in that dimension. If no elements contribute to a result value, that value is zero.
<Related>
 | Array-array operations, Array-scalar operations, ALL intrinsic function, ANY intrinsic function, COUNT intrinsic function, IALL intrinsic function, IANY intrinsic function, IPARITY intrinsic function, MAXLOC intrinsic function, MAXVAL intrinsic function, MINLOC intrinsic function, MINVAL intrinsic function, PARITY intrinsic function, PRODUCT intrinsic function, Reduction intrinsic functions


SUM Example Program

<Example Program>

Program sum_example
    Real a(2,3)
    a = Reshape( (/2.,3.,5.,-1.,4.,-3./), (/2,3/))
    Print *, Sum(a)
    Print *, Sum(a,Dim=1)
    Print *, Sum(a,Dim=2)
    Print *, Sum(a,Mask=a>0)
End Program

Execution Results

  10.0000000
   5.0000000   4.0000000   1.0000000
  11.0000000  -1.0000000
  14.0000000


SYNC ALL statement

Standard: F77 F90 F95 F2003 F2008 F2018 Example program

＜Syntax＞

SYNC ALL [ ( [ sync-stat-list ] ) ]
sync-stat-list ::= sync-stat [ , sync-stat ]
sync-stat ::= STAT = stat-variable | ERRMSG = errmsg-variable

A stat-variable must be a non-coindexed scalar Integer variable, and should be able to represent values from −9999 to +9999. An errmsg-variable must be a non-coindexed scalar Character variable with default kind.

＜Semantics＞

In multiple image execution of a coarray program, execution of a SYNC ALL statement synchronises with corresponding SYNC ALL statement executions on other images in the current team; the segment following the nth execution of a SYNC ALL statement on one image follows all the segments that preceded the nth execution of a SYNC ALL statement on every other image in the current team.

If the STAT= clause is present, zero is assigned to the stat-variable if no error occurs, and a positive value if an error occurs. If the ERRMSG= clause is present and an error occurs, the errmsg-variable is assigned an explanatory message; it remains unchanged if no error occurs.

＜Related＞

ERRMSG= specifier, Image control statements, STAT= specifier, SYNC IMAGES statement, SYNC TEAM statement


SYNC IMAGES statement

Standard: F77 F90 F95 F2003 F2008 F2018 Example program

＜Syntax＞

SYNC IMAGES ( expression [ , sync-stat ]... )
SYNC IMAGES ( * [ , sync-stat ]... )
sync-stat ::= STAT = stat-variable | ERRMSG = errmsg-variable

The expression must be Integer, and either scalar or a vector (array with rank one); each value must be in the range one to NUM_IMAGES().

＜Semantics＞

In multiple image execution of a coarray program, execution of a SYNC IMAGES ( expression ) statement synchronises with corresponding SYNC IMAGES statement executions on the images whose indexes are listed in the expression. Including the invoking image number in the list has no effect. The segment following the nth execution of a SYNC IMAGES statement on image number I with the value J in its expression follows the segments on image J before its nth execution of SYNC IMAGES with I in its expression.

The effect of SYNC IMAGES (*) is exactly the same as with an expression listing every image, e.g. SYNC IMAGES ( [ (i,i=1,NUM_IMAGES()) ] ).

If the STAT= clause is present, zero is assigned to the stat-variable if no error occurs, and a positive value if an error occurs. If the ERRMSG= clause is present and an error occurs, the errmsg-variable is assigned an explanatory message; it remains unchanged if no error occurs.

＜Related＞

ERRMSG= specifier, Image control statements, STAT= specifier, SYNC ALL statement, SYNC TEAM statement


SYNC MEMORY statement

Standard: F77 F90 F95 F2003 F2008 F2018 Example program

＜Syntax＞

SYNC MEMORY [ ( [ sync-stat-list ] ) ]
sync-stat-list ::= sync-stat [ , sync-stat ]...
sync-stat ::= STAT = stat-variable | ERRMSG = errmsg-variable

＜Semantics＞

In multiple image execution of a coarray program, a SYNC MEMORY statement is a segment divider that does not do any synchronisation itself. It may be useful, to preserve coarray access semantics, in conjunction with some other mechanism that performs a synchronisation. Note that it is very easy to make mistakes using this, and due to parallel non-determinacy this might well not be noticed, so this is not recommended for normal use.

If the STAT= clause is present, zero is assigned to the stat-variable if no error occurs, and a positive value if an error occurs. If the ERRMSG= clause is present and an error occurs, the errmsg-variable is assigned an explanatory message; it remains unchanged if no error occurs.

＜Related＞

ERRMSG= specifier, Image control statements, STAT= specifier, SYNC ALL statement, SYNC IMAGES statement, SYNC TEAM statement


SYNC TEAM statement

Standard: F77 F90 F95 F2003 F2008 F2018 Example program

＜Syntax＞

SYNC TEAM ( team-value [ , sync-stat ]... ) ]
sync-stat ::= STAT = stat-variable | ERRMSG = errmsg-variable

team-value ::= scalar-expression
The team-value must be of type TEAM_TYPE from the intrinsic module ISO_FORTRAN_ENV. A stat-variable must be a non-coindexed scalar Integer variable, and should be able to represent values from −9999 to +9999. An errmsg-variable must be a non-coindexed scalar Character variable with default kind.

＜Semantics＞

In multiple image execution of a coarray program, execution of a SYNC TEAM statement synchronises with corresponding SYNC TEAM statement executions on other images in the same team; the segment following the nth execution of a SYNC TEAM statement on one image in the specified team follows all the segments that preceded the nth execution of a SYNC TEAM statement on every other image in that team.

The team-value must identify the current team or an ancestor of the current team.

If the STAT= clause is present, zero is assigned to the stat-variable if no error occurs, and a positive value if an error occurs. If the ERRMSG= clause is present and an error occurs, the errmsg-variable is assigned an explanatory message; it remains unchanged if no error occurs.

＜Related＞

ERRMSG= specifier, Image control statements, STAT= specifier, SYNC ALL statement, SYNC IMAGES statement


SYSTEM_CLOCK intrinsic subroutine
 Standard: F77 (F90) F95 F2003 F2008 Example Program
<Syntax>

Call SYSTEM_CLOCK ( [ COUNT, COUNT_RATE, COUNT_MAX ] )

COUNT : Integer scalar, Intent(Out);
COUNT_RATE : Real or Integer scalar, Intent(Out);
COUNT_MAX : Integer scalar, Intent(Out).

Note that in Fortran 90, all arguments were required to be Integer with default kind.

<Semantics>

This subroutine queries the real-time system clock. This is a clock that counts from zero to COUNT_MAX at a rate of COUNT_RATE ticks per second; after reaching COUNT_MAX it restarts from zero.

COUNT is assigned the current clock value in the range zero to COUNT_MAX, or −HUGE(COUNT) if there is no clock.

COUNT_RATE is assigned the number of clock ticks per second, or zero if there is no clock.

COUNT_MAX is assigned the maximum clock value, or zero if there is no clock.

On Windows, this uses the high-precision performance clock; this clock is very precise and very accurate, but if 32-bit arguments are used it will usually reach COUNT_MAX (and thus reset to zero) every 10-20 minutes depending on the hardware. Therefore it is recommended to use 64-bit integer arguments.

Note that all arguments are optional.

<Related>
CPU_TIME intrinsic subroutine, DATE_AND_TIME intrinsic subroutine.


SYSTEM_CLOCK example program

<Example Program>

Program system_clock_example
  Integer count1,count2,rate,cmax
  Call system_clock(count1,rate,cmax)
  Print *, 'Count rate is', rate, 'and maximum value is', cmax
  Call system_clock(count2)
  Print *, 'Time taken to print that message was', count2-count1, 'ticks.'
End Program

Execution Results

 Count rate is 14318180 and maximum value is 2147483647
 Time taken to print that message was 287 ticks.


TAN intrinsic function
 Standard: F77 F90 F95 F2003 F2008 Example Program
<Syntax>
 | TAN ( X ) X : Real or Complex; Result : Same type and kind as X.
<Semantics>
 | The value of the result is an approximation to the tangent of X. Like many intrinsic functions, this is elemental; the result has the same shape as X, with the operation being applied elementwise. If X is of type Real, it specifies the angle in radians. If X is of type Complex, the real part is interpreted as radians.
<Related>
 | ATAN intrinsic function, ATAN2 intrinsic function, COS intrinsic function, SIN intrinsic function, TANH intrinsic function.


TAN example program

<Example Program>

Program tan_example
  Real, Dimension(2,3) :: a
  Complex, Dimension(3) :: c
  a = Reshape( [ 0.0,0.2,-0.4,0.6,-0.8,1.57 ], [ 2,3 ])
  c = [ (0.2,0.0),(3.1415926,0.6),(-1.5707963,-0.8) ]
  Print 1, Tan(a)
1 Format(6(2X,F0.5))
  Print 2, Tan(c)
2 Format(3(2X,'(',F0.5,',',F0.5,')'))
End Program

Execution Results

  .00000  .20271  -.42279  .68414  -1.02964  1255.84827
  (.20271,.00000)  (-.00000,.53705)  (-.00001,-1.50594)


TANH intrinsic function
 Standard: F77 F90 F95 F2003 F2008 Example Program
<Syntax>
 | TANH ( X ) X : Real or Complex; Result : Same type and kind as X.
<Semantics>
 | The value of the result is an approximation to the hyperbolic tangent of X. Like many intrinsic functions, this is elemental; the result has the same shape as X, with the operation being applied elementwise. If X is of type Complex, the imaginary part is interpreted as radians.
<Related>
 | ATANH intrinsic function, COSH intrinsic function, SINH intrinsic function, TAN intrinsic function.


TANH example program

<Example Program>

Program tanh_example
  Real, Dimension(2,3) :: a
  Complex, Dimension(3) :: c
  a = Reshape( [ 0.0,0.2,-0.4,0.6,-1.2,5.7 ], [ 2,3 ])
  c = [ (0.2,0.0),(0.5,-1.5707963),(5.7,1.5707963) ]
  Print 1, Tanh(a)
1 Format(6(2X,F0.5))
  Print 2, Tanh(c)
2 Format(3(2X,'(',F0.5,',',F0.5,')'))
End Program

Execution Results

  .00000  .19738  -.37995  .53705  -.83365  .99998
  (.19738,.00000)  (2.16395,-.00000)  (1.00002,.00000)


TARGET attribute
Standard: F77 F90 F95 F2003 Example Program
<Syntax>
type, TARGET [ , attr ]... :: decl-list

TARGET [ :: ] name [ , name ]...
<Semantics>
The TARGET attribute allows a pointer to be associated with that variable. A pointer can only become associated with things that have this attribute.

Allocation of a pointer creates an object that implicitly has the TARGET attribute.

The TARGET attribute reduces the optimisability of the program, so only use it on variables that will have pointers associated with them. If a dummy argument has the TARGET attribute, the procedure must be referenced with an explicit interface (if it is a dummy procedure or external procedure, that means it needs an interface block).
<Related>
ALLOCATE statement, INTERFACE statement, Pointer assignment statement, POINTER attribute, Type Declaration statement


<Example Program>

Program target_example
Integer, Pointer :: i(:,:)
Integer, Target :: j(2,2)
j = 1
i => j
Print *, i
Print *, j
End
Execution Results

1 1 1 1
1 1 1 1


THIS_IMAGE intrinsic function

Standard: F77 F90 F95 F2003 F2008 F2018 Example program

＜Syntax＞

THIS_IMAGE ( [ TEAM ] )
THIS_IMAGE ( COARRAY [, TEAM ] )
THIS_IMAGE ( COARRAY, DIM [, TEAM ] )

COARRAY : coarray of any type;
DIM : scalar Integer;
TEAM : scalar of type TEAM_TYPE from the intrinsic module ISO_FORTRAN_ENV, whose value must identify the current team or an ancestor team;

Result : Integer with default kind; if COARRAY appears and DIM does not appear, the result is a vector whose size is equal to the corank of COARRAY, otherwise the result is scalar.

＜Semantics＞

If TEAM does not appear, the “specified team” is the current team.

If COARRAY does not appear, the value of the result is the image index of the executing image in the specified team. Otherwise, if DIM does not appear, the value of the result is the set of cosubscripts for COARRAY that correspond to the executing image in the specified team. If both COARRAY and DIM appear, the value of the result is the cosubscript for codimension DIM that corresponds to the executing image in the specified team.

＜Related＞

CODIMENSION attribute, GET_TEAM intrinsic function, Image selectors, LCOBOUND intrinsic function, NUM_IMAGES intrinsic function, UCOBOUND intrinsic function


TINY intrinsic function
Standard: F77 F90 F95 F2003 F2008 Example Program
<Syntax>
TINY ( X )

X : Real;
Result : Scalar, same type and kind as X.
<Semantics>

This function returns the smallest “model number” for the type and kind of X.

This is an inquiry function, so X need not be defined; indeed, it is permitted to be disassociated, unallocated, or absent.

The model for real type is that it may be zero or a signed fraction between 1 and 1/RADIX(X) consisting of DIGITS(X) digits, multiplied by an exponent e with MINEXPONENT(X)≤e≤MAXEXPONENT(X). Thus the smallest model number is the value obtained for the fraction being equal to 1/RADIX(X) (i.e. the first digit 1 and the remaining digits zero) and with e equal to MINEXPONENT(X).

Note that TINY(X) is not necessarily the smallest possible value for X; for example, with IEEE floating-point, gradual underflow provides many smaller values (with less precision). It is, however, likely to be the smallest value for which the full precision of DIGITS(X) of radix RADIX(X) is available.

<Related>
DIGITS intrinsic function, EPSILON intrinsic function, HUGE intrinsic function, INTEGER type, MAXEXPONENT intrinsic function, MINEXPONENT intrinsic function, RADIX intrinsic function, REAL type


TINY example program

<Example Program>

Program tiny_example
Print *,Tiny(0.0)
End Program
Execution Results

1.1754944E-38


TRAILZ intrinsic function
Standard: F77 F90 F95 F2003 F2008 Example Program
<Syntax>
 | TRAILZ ( I ) I : Integer; Result : Integer (default kind).
<Semantics>
 | Returns the number of trailing (least significant) zero bits in the internal representation of I. This is an elemental function; if I is an array the result is an array of the same shape, with the TRAILZ operation applied to each element of I.
<Related>
 | IAND intrinsic function, IEOR intrinsic function, IOR intrinsic function, LEADZ intrinsic function, MASKL intrinsic function, MASKR intrinsic function, NOT intrinsic function, POPCNT intrinsic function, POPPAR intrinsic function, SHIFTA intrinsic function, SHIFTL intrinsic function, SHIFTR intrinsic function


<Example Program>

Program trailz_example
Integer :: a(3) = [ 32768,120,32767 ]
Print *,Trailz(a)
End Program
Execution Results

15 3 0


TRANSFER intrinsic function
Standard: F77 F90 F95 F2003 F2008 Example Program
<Syntax>

TRANSFER ( SOURCE, MOLD [ , SIZE ] )

SOURCE : scalar or array of any type;
MOLD : scalar or array of any type;
SIZE : scalar Integer, not an optional dummy argument.

Result : same type and type parameters as MOLD, scalar if MOLD is scalar and SIZE is absent, otherwise an array of rank one.

<Semantics>

The result of this function has the same internal representation (bits in memory) as SOURCE, but with the type and kind of MOLD. If SIZE is present, it specifies the number of elements in the result; otherwise, if MOLD is an array, the number of elements is the fewest such that the storage size of the result is greater than or equal to the storage size of SOURCE, e.g. for a scalar SOURCE, STORAGE_SIZE(result)*SIZE(result)≥STORAGE_SIZE(SOURCE).

If the storage size of the result is greater than the storage size of SOURCE, the first part of the result has the same internal representation as SOURCE and the remainder is undefined (can be anything).

Note that it is possible for the result of TRANSFER to be an “impossible” value for the type, and in this case the results of further execution are not defined. This is especially true if the result type is LOGICAL; if the internal representation is neither that of .TRUE. or .FALSE., in some cases it will be interpreted as true and in other cases as false.

Another potential pitfall is transferring to a floating-point type; if the result has the form of an IEEE special value (e.g. a NaN), this can cause program termination with an invalid operation.

<Related>
SIZE intrinsic function, STORAGE_SIZE intrinsic function.


TRANSFER example program

<Example Program>

Program transfer_example
  Use f90_kind
  Implicit None
  Print 1, 12345.0, Transfer(12345.0, [ 0_int8 ])
1 Format(1X, 'Real ', SP, ES13.6, ' as a string of bytes is', 99(1X,Z2.2))
  Print *, '(Note this depends on the endianness of the machine architecture,'
  Print *, ' as well as on the internal representation of Real numbers.)'
End Program
Execution Results

 Real +1.234500E+04 as a string of bytes is 00 E4 40 46
 (Note this depends on the endianness of the machine architecture,
  as well as on the internal representation of Real numbers.)


TRANSPOSE intrinsic function
Standard: F77 F90 F95 F2003 Example Program
<Syntax>
 | TRANSPOSE(MATRIX) MATRIX : array of any type and rank 2
<Semantics>
 | Returns the transpose of MATRIX. Element (i,j) of the result will be equal to element (j,i) of MATRIX. Note that a multi-dimensional transposition can be performed by the RESHAPE intrinsic function.
<Related>
 | MATMUL intrinsic function, RESHAPE intrinsic function, SHAPE intrinsic function


<Example Program>

Program transpose_example
Real a(3,2)
Real b(2,3)
a = Reshape( (/1.,2.,3.,4.,5.,6./), (/3,2/))
Print *, 'A ='
Print *, a(1,:)
Print *, a(2,:)
Print *, a(3,:)
b = Transpose(a)
Print *, 'B ='
Print *, b(1,:)
Print *, b(2,:)
End
Execution Results

A =
1.0000000 4.0000000
2.0000000 5.0000000
3.0000000 6.0000000
B =
1.0000000 2.0000000 3.0000000
4.0000000 5.0000000 6.0000000


TRIM intrinsic function
Standard: F77 F90 F95 F2003 F2008 Example Program
<Syntax>
 | TRIM ( STRING ) STRING : scalar Character, with any kind; Result: same type and kind as STRING.
<Semantics>
 | The TRIM intrinsic function returns a “trimmed” STRING; that is, the string without trailing blanks; its length is equal to LEN_TRIM(STRING). Because character comparison ignores trailing blanks, TRIM(STRING) is always equal to STRING, but might have a different length. Note that unlike LEN_TRIM, this is not elemental.
<Related>
 | CHARACTER type, LEN intrinsic function, LEN_TRIM intrinsic function.


TRIM example program

<Example Program>

Program trim_example
  Character(80) :: message = 'Hello'
  Print *, Len_Trim(message), Trim(message), '!'
  message = 'Hello Blank Padding'
  Print *, Len_Trim(message), Trim(message), '!'
End Program
Execution Results

 5 Hello!
 19 Hello Blank Padding!


TYPE statement
Standard: F77 F90 F95 F2003 Example Program
<Syntax>
TYPE [ [ , type-attr ]... :: ] type-name [ ( type-param-name-list ) ]

type-attr | ::= | ABSTRACT
 | | | BIND(C)
 | | | EXTENDS( parent-type-name )
 | | | PRIVATE
 | | | PUBLIC
type-param-name-list ::= type-param-name [ , type-param-name ]...

PUBLIC and PRIVATE are only permitted in the specification part of a module, and no more than one of them may appear.

<Semantics>
The TYPE statement introduces a derived type definition. If PUBLIC or PRIVATE appears on the TYPE statement, it specifies the accessibility of the type name.

In Fortran 2003, the ABSTRACT keyword declares an abstract type; such a type can be used only for type extension and to declare polymorphic variables. The BIND(C) clause declares that the type is interoperable with a C struct; this puts strict limitations on the kind of components that are allowed. The EXTENDS clause creates a new type by extending an old one (the “parent” type).
<Related>
BIND attribute, CLASS specifier, Component definition statement, Derived type definition, END TYPE statement, EXTENDS clause, SEQUENCE statement


Type-bound procedure

Standard: F77 F90 F95 F2003 F2008 Example program

＜Syntax＞

A specific type-bound procedure is a procedure declared in the “type-bound procedure part” of a type definition.

specific-tbp-stmt ::= PROCEDURE [ ( interface-name ) ] , type-bound-attr-list :: binding-list
binding ::= type-bound-procedure-name [ => actual-proc-name ]
binding-list ::= binding [ , binding ]...

An interface-name is only permitted with the DEFERRED attribute, and is the name of an abstract interface or of any procedure with an explicit interface (e.g. a module procedure). An actual-proc-name is the name of a module procedure or an external procedure with an explicit interface; if it is omitted, it is assumed to be the same as the type-bound-procedure-name (except with the DEFERRED attribute).

Note that Fortran 2008 permits multiple type-bound procedure bindings to be listed on a single PROCEDURE statement, but Fortran 2003 only allows one specific binding per statement.

type-bound-attr-list ::= type-bound-attr [ , type-bound-attr ]...

type-bound-attr | ::= | DEFERRED
 | | | NON_OVERRIDABLE
 | | | NOPASS
 | | | PASS [ ( dummy-arg-name ) ]
 | | | PRIVATE
 | | | PUBLIC

The PUBLIC and PRIVATE attributes are only permitted in the specification part of a module. The DEFERRED attribute is only permitted in an abstract type; it requires an interface-name to be specified, and forbids an actual-proc-name.

A generic type-bound procedure is a set of specific type-bound procedures with a generic identifier; it is also declared in the “type-bound procedure part” of a type definition.

generic-tbp-stmt ::= GENERIC [ , access ] :: generic-spec => type-bound-procedure-name-list
access ::= PRIVATE | PUBLIC
type-bound-procedure-name-list ::= type-bound-procedure-name [ , type-bound-procedure-name ]...

generic-spec | ::= | name
 | | | ASSIGNMENT (=)
 | | | OPERATOR (operator)
 | | | read-or-write (form)

read-or-write ::= READ | WRITE
form ::= FORMATTED | UNFORMATTED

Each type-bound-procedure-name must be the name of a specific type-bound procedure of the type being defined. The syntax for operator is described under the INTERFACE OPERATOR statement.

The syntax for invoking a specific type-bound procedure, or a named generic type-bound procedure, is similar to that of object-bound procedures:
object % type-bound-procedure-name [ ( [ actual-arg-list ] ) ]

This syntax may appear in a CALL statement or as a function reference; as a function reference, the parentheses are required (and no alternate return specifier is permitted). The syntax of the actual-arg-list is described under the CALL statement.

＜Semantics＞

Any type-bound procedure, specific or generic, may be explicitly declared to be PUBLIC or PRIVATE; otherwise, it is PRIVATE if the “type-bound procedure part” contains a PRIVATE statement, and PUBLIC otherwise; this is unaffected by a PRIVATE statement in the “component definition part”.

Each type-bound procedure statement defines a specific type-bound procedure. The name of the type-bound procedure is declared in the statement, and unless deferred is bound (for the type being defined) to the specified actual procedure. In the common case where the actual procedure is a module procedure with the same name as the type-bound procedure, the “=> actual-proc-name” may be omitted.

When extending a type, the type-bound procedures are automatically inherited from the parent type unless they are overridden by a new binding with the same name. If the type-bound procedure has the NON_OVERRIDABLE attribute, it cannot be overridden but will always be inherited as is.

Unless a type-bound procedure has the NOPASS attribute, it must have a scalar dummy argument of CLASS(type-name) matching the PASS attribute.

A type-bound procedure with the DEFERRED attribute has no associated actual procedure, but its interface is that given by interface-name. Such a procedure is only permitted in a type with the ABSTRACT attribute; objects of abstract type cannot be created, but if the abstract type is extended and the new type is not abstract and provides overrides for all of the deferred type-bound procedures, objects of the new type can be created. This allows an ABI for a family of types to be defined, with procedures that operate on them, while requiring any concrete type to provide replacements for the deferred procedures.

Each generic type-bound procedure statement either defines a new generic type-bound generic or extends an existing type-bound generic. If a type-bound generic is an operator or assignment, the PASS attribute is required on each specific type-bound procedure, and is used to determine which object is the invoking object. Note that unlike operators (and assignment) defined by an INTERFACE block, type-bound operators and assignment are always accessible whenever an object of the type is accessible, i.e. they are not blocked by the ONLY clause on a USE statement.

When a type-bound procedure is invoked via an object, the actual procedure invoked is the corresponding actual-proc-name in the definition for the dynamic type of the object.

＜Related＞

CALL statement, CLASS specifier, Component definition statement, Derived Type Definition, EXTENDS clause, NOPASS attribute, Object-bound procedure, PASS attribute, PRIVATE attribute, PUBLIC attribute, TYPE statement


Type declaration statement

Standard: (F77) F90 F95 F2003 F2008

＜Syntax＞

type [ [ , attr-spec ]... :: ] entity-decl-list

type | ::= | intrinsic-type-spec
 | | | CLASS ( * )
 | | | CLASS ( derived-type-spec )
 | | | TYPE ( derived-type-spec )
 | | | TYPE ( intrinsic-type-spec )

intrinsic-type-spec | ::= | CHARACTER [ char-spec ]
 | | | COMPLEX [ ( [ KIND = ] expr ) ]
 | | | DOUBLE PRECISION
 | | | INTEGER [ ( [ KIND = ] expr ) ]
 | | | LOGICAL [ ( [ KIND = ] expr ) ]
 | | | REAL [ ( [ KIND = ] expr ) ]

derived-type-spec ::= derived-type-name derived-type-param-list )
derived-type-param-list ::= derived-type-param [ , derived-type-param ]...
derived-type-param ::= [ derived-type-param-name = ] type-param-value
type-param ::= expression | : | *

attr-spec | ::= | ALLOCATABLE
 | | | ASYNCHRONOUS
 | | | BIND ( C [ , NAME = expression ] )
 | | | CODIMENSION [ coarray-spec ]
 | | | CONTIGUOUS
 | | | DIMENSION ( array-spec )
 | | | EXTERNAL
 | | | INTENT ( intent )
 | | | INTRINSIC
 | | | OPTIONAL
 | | | PARAMETER
 | | | POINTER
 | | | PRIVATE
 | | | PROTECTED
 | | | PUBLIC
 | | | SAVE
 | | | TARGET
 | | | VALUE
 | | | VOLATILE

intent ::= IN | INOUT | OUT

If ALLOCATABLE or POINTER is specified, any array-spec must be deferred-shape. If ALLOCATABLE is specified, any coarray-spec must be a deferred-coshape-spec.

The PUBLIC and PRIVATE attributes are only permitted in the specification part of a module.

＜Semantics＞

This statement declares one or more procedures or local variables. If the type specified is a derived-type-spec with type parameters, each expr in a type-param-value must be a constant expression if the entities have the SAVE or PARAMETER attributes, or the type parameter is a KIND type parameter, and a specification expression otherwise. A type-param-value can be a colon (:) only if the type parameter is a LEN type parameter and the entities declared have the POINTER or ALLOCATABLE attribute. A type-param-value can be an asterisk (*) only if the type parameter if a LEN type parameter and the entities declared are dummy arguments.

If an entity-decl contains an initialisation (“= expression” or “=> NULL()”), the entity is a named constant or a variable: if the PARAMETER attribute appears it is a named constant with the specified value (possibly converted to the type), otherwise it is a variable and its initial value is that of the expression; this implies the SAVE attribute.

＜Related＞

ALLOCATABLE attribute, ASYNCHRONOUS attribute, Attributes, BIND attribute, CODIMENSION attribute, CONTIGUOUS attribute, Derived Type Definition, DIMENSION attribute, Entity declaration list, EXTERNAL attribute, INTENT attribute, INTRINSIC attribute, OPTIONAL attribute, PARAMETER attribute, POINTER attribute, PRIVATE attribute, PROTECTED attribute, PUBLIC attribute, SAVE attribute, SELECTED_INT_KIND intrinsic function, SELECTED_REAL_KIND intrinsic function, TARGET attribute, VALUE attribute, VOLATILE attribute


TYPE IS statement
Standard: F77 F90 F95 F2003
<Syntax>
 | TYPE IS ( type-name ) [ construct-name ] The TYPE IS statement is part of the SELECT TYPE construct. The construct-name may appear only if the SELECT TYPE construct is named.
<Semantics>
 | The TYPE IS statement marks the beginning of a TYPE IS block in a SELECT TYPE construct. This block is executed if and only if the dynamic type of the selector is the same as the named derived type. Within a TYPE IS block, the associate-name has the declared type of type-name and is not polymorphic.
<Related>
 | CLASS specifier, CLASS DEFAULT statement, CLASS IS statement, SELECT TYPE statement


UBOUND intrinsic function

Standard: F77 F90 F95 F2003 F2008 Example program

＜Syntax＞

UBOUND ( ARRAY [ , DIM , KIND ] )

ARRAY : array of any type and rank N;
DIM : scalar Integer in the range 1 to N;
KIND : scalar Integer constant expression;

Result : Integer or Integer(Kind=KIND).

＜Semantics＞

If DIM appears, the result is scalar, being the value of the upper bound of that dimension of ARRAY. If DIM does not, the result is a vector of length N containing all the upper bounds of ARRAY. The actual argument for DIM must not itself be an optional dummy argument.

If the array is not a data object, or is an array section, the upper bounds are considered to be equal to the extent of the array in each dimension. Also, the upper bound of any dimension with zero extent is considered to be zero.

It is prohibited to ask for the upper bound of the last dimension of an assumed-size array; an assumed-size array is a dummy array whose last dimension is declared as “*”. In any case, assumed-size arrays are error-prone and not recommended for normal use.

In Fortran 2003, the KIND argument should be used when the upper bound might not be representable in the default Integer kind.

＜Related＞

DIMENSION attribute, LBOUND intrinsic function, SHAPE intrinsic function, SIZE intrinsic function


UCOBOUND intrinsic function

Standard: F77 F90 F95 F2003 F2008 Example program

＜Syntax＞

UCOBOUND ( COARRAY [ , DIM , KIND ] )

COARRAY : coarray of any type and corank N;
DIM : scalar Integer in the range 1 to N;
KIND : scalar Integer constant expression;

Result : Integer or Integer(Kind=KIND).

＜Semantics＞

If DIM appears, the result is scalar, being the value of the upper cobound of that codimension of COARRAY. If DIM does not appear, the result is a vector of length N containing all the upper cobounds of COARRAY. The actual argument for DIM must not itself be an optional dummy argument.

Note that if COARRAY has corank N>1, and the number of images in the current execution is not an integer multiple of the coextents up to codimension N−1, the images do not make a full rectangular pattern. In this case, the value of the last upper cobound is the maximum value that a cosubscript can take for that codimension; e.g. with a coarray-spec of [1:3,1:*] and four images in the execution, the last upper cobound will be equal to 2 because the cosubscripts [1,2] are valid even though [2,2] and [2,3] are not.

＜Related＞

CODIMENSION attribute, LCOBOUND intrinsic function


UNIT= specifier
Standard: F77 F90 F95 F2003 Example Program
<Syntax>
[ UNIT = ] io_unit

io-unit | ::= | expression
 | | | variable
 | | | *

The UNIT= specifier is permitted in any input/output statement, except for PRINT, and for INQUIRE with FILE=.

The keyword and equals sign may be omitted if and only if it is the first specifier in the statement.

If io-unit is an expression, it must be a scalar integer expression and must be non-negative, or the value of one of the constants ERROR_UNIT, INPUT_UNIT or OUTPUT_UNIT from the intrinsic module ISO_FORTRAN_ENV.

If io-unit is a variable, it must be a character variable but may be either a scalar or an array; this form is only permitted in READ and WRITE statements.

The asterisk form of io-unit is also permitted only in READ and WRITE statements.
<Semantics>
Identifies the logical unit which is the subject of the input/output statement. An io-unit that is an expression identifies an external unit; an io-unit that is a variable identifies an internal unit, and an io-unit that is an asterisk identifies the external unit INPUT_UNIT in a READ statement or the external unit OUTPUT_UNIT in a WRITE statement.

If io-unit is a scalar character variable, the internal unit contains only one record; if it is an array variable, the internal unit has a number of records equal to the number of elements of the array. In each case the length of each record is the character length of the variable.
<Related>
BACKSPACE statement, CLOSE statement, ENDFILE statement, INQUIRE statement, OPEN statement, READ statement, REWIND statement, WRITE statement


<Example Program>

Program unit_example
Open (File='TEMP',Position='Rewind',Unit=17)
Do
Read (17,*,End=10) i
Print *,i
End Do
10 Continue
Close (17)
End
File: TEMP

1
2
5

Execution Results

1
2
5


UNLOCK statement

Standard: F77 F90 F95 F2003 F2008 Example program

＜Syntax＞

UNLOCK ( lock-variable [ , sync-stat ]... )

sync-stat-list ::= sync-stat [ , sync-stat ]
sync-stat ::= STAT = stat-variable | ERRMSG = errmsg-variable

The lock-variable must be a scalar variable of type LOCK_TYPE from the intrinsic module ISO_FORTRAN_ENV. The errmsg-variable must be a scalar Character variable with default kind, and the stat-variable must be a scalar Integer variable; these are further described in the STAT= and ERRMSG= specifier pages.

＜Semantics＞

This statement unlocks a lock variable that is currently locked by the executing image.

If the lock is already unlocked, an error occurs: the stat-variable will be assigned the value of STAT_UNLOCKED from the intrinsic module ISO_FORTRAN_ENV. If the lock is locked by another image, an error occurs: the stat-variable will be assigned the value of STAT_LOCKED_OTHER_IMAGE from the intrinsic module ISO_FORTRAN_ENV.

Note that if any error occurs and STAT= does not appear, the program will be terminated.

＜Related＞

ERRMSG= specifier, LOCK statement, LOCK_TYPE from ISO_FORTRAN_ENV, STAT= specifier


UNPACK intrinsic function
Standard: F77 F90 F95 F2003 Example Program
<Syntax>
 | UNPACK(VECTOR, MASK, FIELD) VECTOR : array of any type and rank 1 MASK : Logical array FIELD : same type as VECTOR, conformable with MASK
<Semantics>
 | Returns an array with the same type as VECTOR and the same shape as MASK. The size of VECTOR shall be at least the number of true elements in MASK. Elements of the result that correspond to true elements of MASK are taken from VECTOR (this process occurs in array element order); other elements are set to the corresponding element of FIELD.
<Related>
 | PACK intrinsic function


<Example Program>

Program unpack_example
Real a(2,3),b(3),c(2,3)
a = Reshape( (/-1.,2.,-3.,4.,5.,-6./), (/2,3/))
b = (/ 10.,20.,30. /)
c = Unpack(b,a<=0,Field=a)
Print *, c(1,:)
Print *, c(2,:)
End
Execution Results

10.0000000 20.0000000 5.0000000
2.0000000 4.0000000 30.0000000


USE statement
Standard: F77 F90 F95 F2003 Example Program
<Syntax>
USE [ [ , nature ] :: ] name [ , rename ]...
USE [ [ , nature ] :: ] name , ONLY: only-list

nature ::= INTRINSIC | NON_INTRINSIC

rename | ::= | local-name => remote-name
 | | | OPERATOR(local-operator) => OPERATOR(remote-operator)

Both local-operator and remote-operator must be user-defined operators (e.g. “.FRED.”), not intrinsic operators (e.g. “+” or “.NE.”).

only-list ::= only-item [ , only-item ]...
only-item ::= name | OPERATOR ( operator ) | ASSIGNMENT (=) | rename

The syntax of operator is described on the INTERFACE OPERATOR statement page.

All USE statements must precede all the other declarations in a scoping unit.
<Semantics>
The USE statement accesses public entities in a module. Each rename in a USE statement establishes a local name for the entity from the module.

Multiple USE statements for a particular module are allowed, and all the renaming specified is effective. If all USE statements for a particular module have the ONLY clause, only the listed entities are accessed.

In Fortran 2003, the user may distinguish between intrinsic modules (provided by the compiler) and non-intrinsic modules. If nature does not appear, and there are both an intrinsic module and a non-intrinsic module of that name available, the non-intrinsic module will be used. If nature does appear, only modules of the appropriate nature will be used.

Also in Fortran 2003, user-defined operators can be renamed on the USE statement.

<Related>
END MODULE statement, INTERFACE OPERATOR statement, MODULE statement, ONLY clause, PRIVATE attribute, PUBLIC attribute


<Example Program>

Module set
Integer :: node = 0
Real :: coord = 10.
End Module
Program use_example
Use set
Print *, node,coord
Call sub()
Print *, node,coord
End Program
Subroutine sub()
Use set, x=>coord
node = 5
x = 20.
End Subroutine sub
Execution Results

0 10.0000000
5 20.0000000


VALUE attribute

Standard: F77 F90 F95 F2003 F2008 Example program

＜Syntax＞

type , VALUE [ , attr ]... :: decl-list

VALUE [ :: ] name [ , name ]...

Each name must be a dummy argument that is a variable.

＜Semantics＞

Declares that those dummy arguments are to be passed by value. This means that any change to the dummy argument does not affect the actual argument. A dummy argument with the VALUE attribute is not permitted to have the ALLOCATABLE, CODIMENSION, INTENT(INOUT), INTENT(OUT), POINTER or VOLATILE attributes.

Fortran 2003 required that a variable with the VALUE attribute be scalar, and to have constant length type parameters. Fortran 2008 permits a variable with the VALUE attribute be an array (but not assumed-size), and to have non-constant length type parameters.

This attribute is especially useful when interoperating with C procedures, because most C arguments are passed by value.

If a dummy argument has the VALUE attribute, the procedure must be referenced with an explicit interface (if it is a dummy procedure or external procedure, that means it needs an interface block).

＜Related＞

ENTRY statement, FUNCTION statement, INTENT attribute, INTERFACE statement, SUBROUTINE statement, Type Declaration statement


VERIFY intrinsic function
Standard: F77 F90 F95 F2003 F2008 Example Program
<Syntax>

VERIFY ( STRING, SET [ , BACK , KIND ] )

STRING : Character, any kind;
SET : same type and kind as STRING;
BACK : Logical;
KIND : scalar Integer constant expression;

Result : Integer or Integer(Kind=KIND).

<Semantics>

Searches STRING for an occurrence of any character that is not in SET. If BACK is absent, or present with the value .FALSE., the search begins at the start of STRING; if BACK is present with the value .TRUE., the search begins at the end of STRING.

If every character in STRING also appears in SET, the value zero is returned. If STRING has length zero, there can be no characters found and therefore zero will be returned.

Like many intrinsic functions, this is elemental; if any of STRING, SET or BACK is an array, the result is also an array with the same shape and the operation being applied elementwise. Note that all array arguments must have the same shape.

In the unlikely event of the string being longer than 2GB, the KIND argument should be used to specify a 64-bit integer kind for the result.

<Related>
CHARACTER type, INDEX intrinsic function, SCAN intrinsic function.


VERIFY example program

<Example Program>

Program verify_example
  Character(*),Parameter :: a = '12345678xyzzz999000'
  Character(10) :: set = '0123456789'
  Logical :: b(2) = [ .False.,.True. ]
  Integer :: i(2)
  i = Verify(a,set,b)
  Print *, 'The first non-digit is at', i(1), 'and is ', a(i(1):i(1))
  Print *, 'The last non-digit is at', i(2), 'and is ', a(i(2):i(2))
End Program
Execution Results

 The first non-digit is at 9 and is x
 The last non-digit is at 13 and is z


VOLATILE attribute
Standard: F77 F90 F95 F2003
<Syntax>
type , VOLATILE [ , attr ]... :: decl-list

VOLATILE [ :: ] name [ , name ]...
<Semantics>
The VOLATILE attribute means that the variable may be changed, or referenced, by means other than Fortran. You should use this attribute when a variable can be referenced asynchronously (e.g. from a parallel thread). It effectively disables optimisation of the variable and forces all references and definitions to go through memory.
A variable that is accessed by a USE statement or by host association is permitted to be declared VOLATILE; this does not hide the variable, but makes it volatile only within the local procedure.
<Related>
Type Declaration statement


WAIT statement

Standard: F77 F90 F95 F2003 Example program

＜Syntax＞

WAIT ( wait-spec-list )

wait-spec-list ::= wait-spec [ , wait-spec ]...

wait-spec | ::= | [ UNIT= ] expression
 | | | END=label
 | | | EOR=label
 | | | ERR=label
 | | | ID=expression
 | | | IOMSG=variable
 | | | IOSTAT=variable

The optional “UNIT =” may be omitted if and only if it is the first wait-spec in the list.

＜Semantics＞

The WAIT statement waits for asynchronous input/output on the specified unit to finish. If the ID= specifier is used to identify a particular asynchronous input/output operation, only that operation is waited for; otherwise all pending operations on that unit are waited for.

If a waited-for operation has an end-of-file, end-of-record or error condition, it is indicated in the WAIT statement in the normal manner through the END=, EOR=, ERR=, IOMSG= and IOSTAT= specifiers.

It is not an error to wait for asynchronous operations when there are in fact none pending, even if the unit is not open for asynchronous input/output or not even connected.

Note that the CLOSE, INQUIRE, and file positioning statements may also implicitly perform WAIT operations.

＜Related＞

ASYNCHRONOUS attribute, ASYNCHRONOUS= specifier, BACKSPACE statement, CLOSE statement, END= specifier, EOR= specifier, ERR= specifier, ID= specifier, INQUIRE statement, IOMSG= specifier, IOSTAT= specifier, OPEN statement, REWIND statement, UNIT= specifier


WAIT Example Program

<Example Program>

Program wait_example
Real,Asynchronous :: a(100,2)
Logical finished
Open (17,File='Results',Form='Unformatted',Asynchronous='Yes')
Do
Call produce_results(a(:,1),finished)
Call write_results(a(:,1))
If (finished) Exit
Call produce_results(a(:,2),finished)
Call write_results(a(:,2))
If (finished) Exit
End Do
Contains
Subroutine produce_results(vector,finished)
Real,Intent(Out) :: vector(:)
Logical,Intent(Out) :: finished
Call Random_Number(vector)
finished = vector(1)<0.1
End Subroutine
Subroutine write_results(vector)
Real,Asynchronous,Intent(In) :: vector(:)
Wait (17)
Write (17,Asynchronous='Yes') vector
End Subroutine
End Program
Comments

The use of the ASYNCHRONOUS attribute allows the overlap of the writing of one set of results while computing the next. The WAIT statement in WRITE_RESULTS waits for the previous output to unit 17 to finish, thus ensuring that the previous VECTOR can be re-used for computation.

The ASYNCHRONOUS attribute is needed to tell the compiler that A is subject to asynchronous input/output; this information prevents unsafe optimisations.


WHERE construct

Standard: F77 F90 F95 F2003 F2008 F2018 Example program

＜Syntax＞

[ construct-name : ] WHERE ( expression )
where-block
[ ELSEWHERE ( expression ) [ construct-name ]
where-block ]...
[ ELSEWHERE [ construct-name ]
where-block ]
END WHERE [ construct-name ]

where-block ::= [ where-block-stmt ]...

where-block-stmt | ::= | assignment-stmt
 | | | where-stmt
 | | | where-construct

The expressions must all be logical array expressions with the same shape. The assignment statements must all have array variables as the left-hand-side with the same shape as the expressions. The nested WHERE statements and constructs must have mask expressions with the same shape as the initial WHERE construct statement.

The ELSEWHERE keyword may be spelled ELSE WHERE. The blank between the END and WHERE keywords is optional. If the WHERE construct is named, the END WHERE statement must specify the same construct name. The optional construct name on the ELSEWHERE statement is only allowed when the construct is named, and must be the same as on the WHERE construct statement.

＜Semantics＞

The WHERE construct performs a sequence of masked assignment statements under the control of a logical mask. Elements of a variable being assigned to in the where-block of a WHERE construct statement are only assigned to if the corresponding element of the mask expression is true; for a variable in the where-block of a masked ELSEWHERE statement, only elements for which this mask is true and all previous masks were false are assigned to; and for a variable in the where-block of a simple ELSEWHERE statement, only elements for which all previous masks were false are assigned to.

For nested WHERE construct and statements, the conditions must be satisfied both for the outer WHERE and the inner WHERE.

＜Related＞

Array Assignment, Array Constructor, Array Section, DIMENSION attribute, ELSEWHERE statement, END WHERE statement, FORALL construct, FORALL statement, WHERE statement


WHERE statement

Standard: F77 F90 F95 F2003 F2008 F2018 Example program

＜Syntax＞

WHERE ( expression ) assignment-stmt

The expression must be an array of type Logical. The left-hand-side of the assignment statement must be an array variable with the same shape as expression.

＜Semantics＞

The WHERE statement is a masked assignment. The logical (mask) expression is evaluated, and only elements of the variable that correspond to true values of the mask are assigned to. Elemental operations in the right-hand-side of the assignment are likewise only performed where they correspond to true values of the mask.

＜Related＞

Array Constructor, Array Section, Array Assignment, DIMENSION attribute, ELSEWHERE statement, END WHERE statement, FORALL construct, FORALL statement, WHERE construct


<Example Program>

Program where_statement_example
Real a(2,2)
a = Reshape( (/-1.,2.,3.,4./), (/2,2/))
Where (a<0.) a = 0.0
Print *, a(1,:)
Print *, a(2,:)
End
Execution Results

0.0000000 3.0000000
2.0000000 4.0000000


WRITE statement

Standard: (F77) F90 F95 F2003 F2008 Example program

＜Syntax＞

WRITE ( ci-spec [ , ci-spec ]... ) [ output-list ]

output-list ::= output-item [ , output-item ]...
output-item ::= expr | ( output-list , do-spec )

do-spec ::= variable-name = m1 , m2 [ , m3 ]
m1 ::= initial-scalar-integer-expr
m2 ::= final-scalar-integer-expr
m3 ::= step-scalar-integer-expr

The possible ci-specs are listed in the table below, together with their meaning.

The UNIT= ci-spec is required; the UNIT= keyword and equals sign may be omitted if it is the first ci-spec. If UNIT= was omitted, the FMT= keyword and equals sign may omitted if it is the second ci-spec, or the NML= keyword and equals sign may be omitted if it is the second ci-spec.

＜Semantics＞

The WRITE statement writes one or more records, or partial records, to the specified unit. Each ci-spec is listed in the table below.

If unit is *, the output is to the standard output unit (usually the screen); if it is a character variable, the output is to that variable; if it is an integer expr, the output is to the external unit with that number, which must be non-negative.

If format is present, the WRITE is a formatted WRITE;
if format is *, list-directed formatting is used;
if format is a label, that FORMAT statement is used;
if format is a character expression, that expression is interpreted as an explicit format.
The WRITE is also a formatted WRITE if Namelist is present, in which case namelist formatting is used.

The form “( output-list , do-spec )” evaluates the output-list for each value of variable-name implied by the do-spec; for further details see the DO statement. Implied DO loops may be nested.

Specifier | Argument | Meaning | Values
[ UNIT = ] | unit | Unit to write to |
[ FMT = ] | format | Formatting |
ADVANCE= | Character | Advancing input? | 'YES', 'NO'
ASYNCHRONOUS= | Character | Async i/o? | 'YES', 'NO'
DECIMAL= | Character | Decimal edit mode | 'COMMA', 'POINT'
DELIM= | Character | Delimiter mode | 'NONE', 'QUOTE', 'APOSTROPHE'
ERR= | Label | Branch on error |
ID= | Integer | Pending i/o identifier |
IOMSG= | Character | Error message |
IOSTAT= | Integer | I/O status |
[ NML= ] | Namelist | Namelist formatting |
POS= | Integer | File storage position | Positive
REC= | Integer | Record number | Positive
ROUND= | Character | Rounding mode | 'COMPATIBLE', 'DOWN', 'NEAREST', 'PROCESSOR_DEFINED', 'UP', 'ZERO'
SIGN= | Character | Sign edit mode | 'PLUS', 'SUPPRESS', 'PROCESSOR_DEFINED'

The ADVANCE= specifier is only allowed for external files. If the [ NML= ] specifier appears, no format is allowed. The REC= specifier is only allowed for a direct access file.

In Fortran 2003, the DECIMAL=, DELIM=, ROUND= and SIGN= specifiers control the initial edit modes for that WRITE; if omitted, the default is taken from the OPEN.
The IOMSG= specifier sets its variable to an error message if an error occurs.
The POS= specifier is only allowed for stream files, and specifies the file storage position at which to start writing.
The ID= specifier is only allowed in conjunction with ASYNCHRONOUS='YES', and sets the variable to an identifier for that asynchronous input/output (this variable can then be used in an ID= specifier in INQUIRE or WAIT).

＜Related＞

ADVANCE= specifier, ASYNCHRONOUS= specifier, BACKSPACE statement, CLOSE statement, DECIMAL= specifier, DO statement, ENDFILE statement, ERR= specifier, FORMAT statement, ID= specifier, INQUIRE statement, IOMSG= specifier, IOSTAT= specifier, NAMELIST statement, NML= specifier, OPEN statement, PRINT statement, READ statement, REWIND statement, ROUND= specifier, SIGN= specifier


<Example Program>

Program write_example
Write (*,*) (i,i=1,3)
Write (*,*) (5,j=1,3)
End
Execution Results
1 2 3
5 5 5


NAG Fortran Compiler Release 7.1 Release Note

1 Introduction

Release 7.1 of the NAG Fortran Compiler is a major update.

Customers upgrading from a previous release of the NAG Fortran Compiler will need a new licence key for this release.

See KLICENCE.txt for more information about Kusari Licence Management.

2 Release Overview

Release 7.1 of the NAG Fortran Compiler supports all of Fortran 2008, in particular:

  • A reference to a function that returns a data pointer can be used as a variable in many contexts, including on the left-hand side of an assignment statement.
  • Other minor features, such as pointer target initialisation, allowing allocatable components to have recursive or mutually recursive type, and functions returning procedure pointers, are now supported.

Substantial additional support for Fortran 2018 has been added, in particular:

  • With the addition of intrinsic “collective” subroutines (CO_SUM et al), all of the coarray parallel programming features of Fortran 2018 are now supported.
  • Partial support for the advanced C interoperability has been added. Specifically, assumed-rank and assumed-type arguments, along with C descriptors, are supported.
  • Use of assumed-rank arguments directly in Fortran (rather than C) is provided by the RANK intrinsic function and the SELECT RANK construct.
  • A number of minor features, such as allowing an optional dummy argument to be used as the DIM argument of an intrinsic array reduction function (such as SUM), have been added.

Support for OpenMP programming has been improved by enabling undefined variable checking in OpenMP programs. Additionally, some minor features from newer OpenMP specifications have also been added.

Finally, there is also additional error checking available, and the bundled tools have some additional capabilities.

3 Compatibility

3.1 Compatibility with Release 7.0

Release 7.1 is compatible with Release 7.0, except that files compiled with the -C=calls option will need to be recompiled if they contain a procedure with a procedure pointer argument, or a reference to such a procedure.

3.2 Compatibility with Release 6.2

On MacOS the 32-bit ABI mode accessible via -abi=32 has been removed; consequently only 64-bit compilation is supported and the -abi= switch has been removed entirely.

Other than this, Release 7.1 is fully compatible with Release 6.2 except when coarrays are used, or when the -C=calls option is used for a subroutine that has an alternate return. Any program that uses these features will need to be recompiled.

3.3 Compatibility with Release 6.1

Programs which use features from HPF (High Performance Fortran), for example the ILEN intrinsic function or the HPF_LIBRARY module, are no longer supported.

The previously deprecated -abi=64 option on Linux x86-64 has been withdrawn. This option provided an ABI with 64-bit pointers but 32-bit object sizes and subscript arithmetic, and was only present for compatibility with Release 5.1 and earlier.

With the exception of HPF support and the deprecated option removal, Release 7.1 of the NAG Fortran Compiler is fully compatible with Release 6.1.

3.4 Compatibility with Release 6.0

With the exception of HPF support and the deprecated option removal, Release 7.1 of the NAG Fortran Compiler is compatible with Release 6.0 except that programs that use allocatable arrays of “Parameterised Derived Type” will need to be recompiled (this only affects module variables and dummy arguments).

3.5 Compatibility with Releases 5.3.1, 5.3 and 5.2

With the exception of HPF support and the deprecated option removal, Release 7.1 of the NAG Fortran Compiler is fully compatible with Release 5.3.1. It is also fully compatible with Releases 5.3 and 5.2, except that on Windows, modules or procedures whose names begin with a dollar sign ($) need to be recompiled.

For a program that uses the new “Parameterised Derived Types” feature, it is strongly recommended that all parts of the program that may allocate, deallocate, initialise or copy a polymorphic variable whose dynamic type might be a parameterised derived type, should be compiled with Release 7.1.

3.6 Compatibility with Release 5.1

Release 7.1 of the NAG Fortran Compiler is compatible with NAGWare f95 Release 5.1 except that:
  • programs that use features from HPF are not supported;
  • programs or libraries that use the CLASS keyword, or which contain types that will be extended, need to be recompiled;
  • 64-bit programs and libraries compiled with Release 5.1 on Linux x86-64 (product NPL6A51NA) are binary incompatible, and need to be recompiled.

4 New Fortran 2008 Features

  • An allocatable component can forward-reference a type, for example:
           Type t2
         Type(t),Pointer :: p
         Type(t),Allocatable :: a
       End Type
       Type t
         Integer c
       End Type

    An allocatable component can also be of recursive type, or two types can be mutually recursive. For example,

           Type t
         Integer v
         Type(t),Allocatable :: a
       End Type
    This allows lists and trees to be built using allocatable components. Building or traversing such data structures will usually require recursive procedure calls, as there is no allocatable analogue of pointer assignment.

    No matter how deeply nested such recursive data structures become, they can never be circular (again, because there is no pointer assignment). As usual, deallocating the top object of such a structure will recursively deallocate all its allocatable components.

  • A dummy argument can be used in a specification expression in an elemental subprogram, as long as it is not used to specify a type parameter (such as character length) of a function result. For type parameters of function results, they remain limited to appearing in specification enquiries (such as LEN) when the enquiry is not about a deferred characteristic.

    For example, in

      Elemental Subroutine s(x,n,y)
    Real,Intent(In) :: x
    Integer,Intent(In) :: n
    Real,Intent(Out) :: y
    Real temp(n)
    ...
    the dummy argument N can be used to declare the local array TEMP.
  • Pointers and pointer components can be initialised to point to a target. The target must be valid for that pointer (e.g. same type, rank, etc.). The main cases are:
    Named pointer initialisation
    For data pointers, the target must have the SAVE attribute (variables in modules and the main program have this attribute implicitly). For procedure pointers, the target must be a module procedure or external procedure, not a dummy procedure, internal procedure, or statement function.

    For example,

      Module m
    Real,Target :: x
    Real,Pointer :: p => x
  End Module
  Program test
    Use m
    p = 3
    Print *,x ! Will print the value 3.0
  End Program
    Component default initialisation
    Pointer components can be default-initialised to point to a target. The requirements on the target are the same as for named pointer initialisation.

    For example,

      Module m
    Real,Target :: x
    Type t
      Real,Pointer :: p => x
    End Type
  End Module
  Program test
    Use m
    Type(t) y
    y%p = 3
    Print *,x ! Will print the value 3.0
  End Program
    Component initialisation with structure constructors
    A structure constructor in a constant expression can specify a target for any pointer component. The requirements on the target are the same as for named pointer initialisation.

    For example,

      Module m
    Real,Target :: x
    Type t
      Real,Pointer :: p
    End Type
  End Module
  Program test
    Use m
    Type(t) :: y = t(x)
    y%p = 3
    Print *,x ! Will print the value 3.0
  End Program
  • A reference to a function that returns a pointer can be used as a variable in many contexts. In particular, it can be used as the variable in an assignment statement, as the actual argument corresponding to an INTENT(OUT) or INTENT(INOUT) dummy argument, and as the selector in an ASSOCIATE or SELECT TYPE construct that modifies the associate-name.

    For example, with this module,

      Module m
    Real,Target,Save :: table(100) = 0
  Contains
    Function f(n)
      Integer,Intent(In) :: n
      Real,Pointer :: f
      f => table(Min(Max(1,n),Size(table)))
    End Function
  End Module
    the program below will print “-1.23E+02”.
      Program example
    Use m
    f(13) = -123
    Print 1,f(13)
  1 Format(ES10.3)
  End Program

    It should be noted that the syntax of a statement function definition is identical to part of the syntax of a pointer function reference as a variable; the existence of a pointer-valued function that is accessible in the scope determines which of these it is. This may lead to confusing error messages in some situations.

    With the above module, this program demonstrates the use of the feature with an ASSOCIATE construct.

      Program assoc_eg
    Use m
    Associate(x=>f(3), y=>f(4))
      x = 0.5
      y = 3/x
    End Associate
    Print 1,table(3:4) ! Will print "  5.00E-01  6.00E+00"
  1 Format(2ES10.2)
  End Program

    Finally, here is an example using argument passing.

      Program argument_eg
    Use m
    Call set(f(7))
    Print 1,table(7) ! Will print "1.41421"
  1 Format(F7.5)
  Contains
    Subroutine set(x)
      Real,Intent(Out) :: x
      x = Sqrt(2.0)
    End Subroutine
  End Program

    Other contexts where a reference to a pointer-valued function may be used instead of a variable designator include:

    • as an internal file specifier in a WRITE statement (the function must return a pointer to a character string or array for this);
    • as an input-item in a READ statement;
    • as a STAT= or ERRMSG= variable in an ALLOCATE or DEALLOCATE statement, or in an image control statement such as EVENT WAIT;
    • as the team variable in a FORM TEAM statement.
  • The result of a function can be a procedure pointer. For example,
      Module ppfun
    Private
    Abstract Interface
      Subroutine charsub(string)
        Character(*),Intent(In) :: string
      End Subroutine
    End Interface
    Public charsub,hello_goodbye
  Contains
    Subroutine hello(string)
      Character(*),Intent(In) :: string
      Print *,'Hello: ',string
    End Subroutine
    Subroutine bye(string)
      Character(*),Intent(In) :: string
      Print *,'Goodbye: ',string
      Stop
    End Subroutine
    Function hello_goodbye(flag)
      Logical,Intent(In) :: flag
      Procedure(hello),Pointer :: hello_goodbye
      If (flag) Then
        hello_goodbye => hello
      Else
        hello_goodbye => bye
      End If
    End Function
  End Module
  Program example
    Use ppfun
    Procedure(charsub),Pointer :: pp
    pp => hello_goodbye(.True.)
    Call pp('One')
    pp => hello_goodbye(.False.)
    Call pp('Two')
  End Program
    The function hello_goodbye in module ppfun returns a pointer to a procedure, which needs to be pointer-assigned to a procedure pointer to be invoked. When executed, this example will print
     Hello: One
 Goodbye: Two

    Use of this feature is not recommended, as it blurs the lines between data objects and procedures; this may lead to confusion or misunderstandings during code maintenance. The feature provides no functionality that was not already provided by procedure pointer components.

5 New Fortran 2018 Features

  • The intrinsic subroutines CO_BROADCAST, CO_MAX, CO_MIN, CO_REDUCE and CO_SUM perform collective operations. These are for coarray parallelism: they compute values across all images in the current team, without explicit synchronisation.

    All of these subroutines have optional STAT and ERRMSG arguments. On successful execution, the STAT argument is assigned the value zero and the ERRMSG argument is left unchanged. If an error occurs, a positive value is assigned to STAT and an explanatory message is assigned to ERRMSG. Only the errors STAT_FAILED_IMAGE and STAT_STOPPED_IMAGE are likely to be able to be caught in this way. Because there is not full synchronisation (see below), different images may receive different errors, or none at all. If an error occurs and STAT is not present, execution is terminated. Note that if the actual arguments for STAT or ERRMSG are optional dummy arguments, they must be present on all images or absent on all images.

    A reference (CALL) to one of these subroutines is not an image control statement, does not end the current segment, and does not imply synchronisation (though some partial synchronisation will occur during the computation). However, such calls are only permitted where an image control statement is permitted.

    Each image in a team must execute the same sequence of CALL statements to collective subroutines as the other images in the team. There must be no synchronisation between the images at the time of the call; the invocations must come from unordered segments.

    All collective subroutines have the first argument “A”, which is INTENT(INOUT), and must not be a coindexed object. This argument contains the data for the calculation, and must have the same type, type parameters, and shape on all images in the current team. If it is a coarray that is a dummy argument, it must have the same ultimate argument on all images.

    SUBROUTINE CO_BROADCAST ( A, SOURCE_IMAGE [, STAT, ERRMSG ] )

    A : variable of any type; it must not be a coindexed object, and must have the same type, type parameters and shape on all images in the current team; if A is a coarray that is a dummy argument, it must have the same ultimate argument on each image;

    SOURCE_IMAGE : integer scalar, in the range one to NUM_IMAGES(), this argument must have the same value on all images in the current team;

    STAT (optional) : integer scalar variable, not coindexed;

    ERRMSG (optional) : character scalar variable of default kind, not coindexed.

    The value of argument A on image SOURCE_IMAGE is assigned to the argument A on all the other images.

    SUBROUTINE CO_MAX ( A [, RESULT_IMAGE, STAT, ERRMSG ] )

    A: variable of type Integer, Real, or Character; it must not be a coindexed object, and must have the same type, type parameters and shape on all images in the current team; if A is a coarray that is a dummy argument, it must have the same ultimate argument on each image;

    RESULT_IMAGE (optional) : integer scalar, in the range one to NUM_IMAGES(), this argument must be either present on all images or absent on all images; if present, it must have the same value on all images in the current team;

    STAT (optional) : integer scalar variable, not coindexed;

    ERRMSG (optional) : character scalar variable of default kind, not coindexed.

    This subroutine computes the maximum value of A across all images; if A is an array, the value is computed elementally. If RESULT_IMAGE is present, the result is assigned to argument A on that image, otherwise it is assigned to argument A on all images.

    SUBROUTINE CO_MIN ( A [, RESULT_IMAGE, STAT, ERRMSG ] )

    A: variable of type Integer, Real, or Character; it must not be a coindexed object, and must have the same type, type parameters and shape on all images in the current team; if A is a coarray that is a dummy argument, it must have the same ultimate argument on each image;

    RESULT_IMAGE (optional) : integer scalar, in the range one to NUM_IMAGES(), this argument must be either present on all images or absent on all images; if present, it must have the same value on all images in the current team;

    STAT (optional) : integer scalar variable, not coindexed;

    ERRMSG (optional) : character scalar variable of default kind, not coindexed.

    This subroutine computes the minimum value of A across all images; if A is an array, the value is computed elementally. If RESULT_IMAGE is present, the result is assigned to argument A on that image, otherwise it is assigned to argument A on all images.

    SUBROUTINE CO_REDUCE ( A, OPERATION [, RESULT_IMAGE, STAT, ERRMSG ] )

    A: non-polymorphic variable of any type; it must not be a coindexed object, and must have the same type, type parameters and shape on all images in the current team; if A is a coarray that is a dummy argument, it must have the same ultimate argument on each image;

    OPERATION : pure function with exactly two arguments; the dummy arguments of OPERATION must be non-allocatable, non-optional, non-pointer, non-polymorphic dummy variables, and each argument and the result of the function must be scalar with the same type and type parameters as A;

    RESULT_IMAGE (optional) : integer scalar, in the range one to NUM_IMAGES(), this argument must be either present on all images or absent on all images; if present, it must have the same value on all images in the current team;

    STAT (optional) : integer scalar variable, not coindexed;

    ERRMSG (optional) : character scalar variable of default kind, not coindexed.

    This subroutine computes an arbitrary reduction of A across all images; if A is an array, the value is computed elementally. The reduction is computed starting with the set of corresponding values of A on all images; this is an iterative process, taking two values from the set and converting them to a single value by applying the OPERATION function; the process continues until the set contains only a single value — that value is the result. If RESULT_IMAGE is present, the result is assigned to argument A on that image, otherwise it is assigned to argument A on all images.

    SUBROUTINE CO_SUM ( A [, RESULT_IMAGE, STAT, ERRMSG ] )

    A: variable of type Integer, Real, or Complex; it must not be a coindexed object, and must have the same type, type parameters and shape on all images in the current team; if A is a coarray that is a dummy argument, it must have the same ultimate argument on each image;

    RESULT_IMAGE (optional) : integer scalar, in the range one to NUM_IMAGES(), this argument must be either present on all images or absent on all images; if present, it must have the same value on all images in the current team;

    STAT (optional) : integer scalar variable, not coindexed;

    ERRMSG (optional) : character scalar variable of default kind, not coindexed.

    This subroutine computes the sum of A across all images; if A is an array, the value is computed elementally. If RESULT_IMAGE is present, the result is assigned to argument A on that image, otherwise it is assigned to argument A on all images.

  • The DIM argument to the intrinsic functions ALL, ANY, FINDLOC, IALL, IANY, IPARITY, MAXLOC, MAXVAL, MINLOC, MINVAL, NORM2, PARITY, PRODUCT and SUM can be an optional dummy argument, as long as it is present at execution time. For example,
      Subroutine sub(x,n)
    Real,Intent(In) :: x(:,:,:)
    Integer,Intent(In),Optional :: n
    If (Present(n)) Then
      Print *,Norm2(x,n) ! Rank two array result.
    Else
      Print *,Norm2(x)   ! Scalar result.
    End If
  End Subroutine
  • The SIZE= specifier can be used in a READ statement without ADVANCE='NO', that is, in a READ statement with no ADVANCE= specifier, or one with an explicit ADVANCE='YES'. For example,
        Character(65536) buf
    Integer nc
    Read(*,'(A)',Size=nc) buf
    Print *,'The number of characters on that line was',nc
    Note that SIZE= is not permitted with list-directed or namelist formatting; that would be pointless, as there are no edit descriptors with such formatting and thus no characters to be counted by SIZE=.
  • Specific intrinsic functions are reported as obsolescent with the -f2018 option. In the case of a function that is both specific and generic, e.g. SQRT, only obsolescent usage is reported, e.g. passing as an actual argument, use as a procedure interface, or being the target of a procedure pointer assignment.

    For example, in

      Program obsolete_cos_usage
    Real x
    Intrinsic cos
    Procedure(cos),Pointer :: pp    ! Obsolescent
    x = 1.5
    pp => cos                       ! Obsolescent
    Call other_procedure(cos)       ! Obsolescent
    Print *,cos(x),pp(x)
  End Program
  Subroutine other_procedure(f)
    Real,External :: f
    Print *,f(1.5)
  End Subroutine
    only the three lines marked with the comment will produce warning messages.
  • Assumed-rank dummy arguments accept actual arguments of any rank; they assume the rank from the actual argument. This rank may be zero; that is, the actual argument may be scalar. Furthermore, assumed-rank dummy arguments may have the ALLOCATABLE or POINTER attribute, and thus accept allocatable/pointer variables of any rank.

    The syntax is as follows:

      Real,Dimension(..) :: a, b
  Integer :: c(..)
    That declares three variables (which must be dummy arguments) to be assumed-rank.

    The use of assumed-rank dummy arguments within Fortran is extremely limited; basically, the intrinsic inquiry functions can be used, and there is a SELECT RANK construct, but other than that they may only appear as actual arguments to other procedures where they correspond to another assumed-rank argument.

    The main use of assumed rank is for advanced C interoperability. An assumed-rank argument is passed by reference as a “C descriptor”; it is then up to the C routine to decode what that means. The C descriptor, along with several utility functions for manipulating it, is defined by the source file ISO_Fortran_binding.h; this can be found in the compiler's library directory (on Linux this is usually /usr/local/lib/NAG_Fortran, but that can be changed at installation time).

    This topic is highly complex, and beyond the scope of a Release Note. The reader should direct their attention to the Fortran 2018 standard, or to a good textbook such as “Modern Fortran Explained” by Metcalf, Reid and Cohen.

    Here is an extremely simple example:

      Program assumed_rank_example
    Real x(1,2),y(3,4,5,6,7)
    Call showrank(1.5)
    Call showrank(x)
    Call showrank(y)
  Contains
    Subroutine showrank(a)
      Real,Intent(In) :: a(..)
      Print *,'Rank is',Rank(a)
    End Subroutine
  End Program
    That will produce the output
     Rank is 0
 Rank is 2
 Rank is 5
  • The SELECT RANK construct facilitates use of assumed rank objects in Fortran. It has the syntax
      [ construct-name ] SELECT RANK ( [ assoc_name => ] assumed-rank-variable-name )
        [ rank-stmt
            block ]...
  END SELECT [ construct-name ]
    where rank-stmt is one of:
      RANK ( scalar-int-constant-expression ) [ construct-name ]
  RANK ( * ) [ construct-name ]
  RANK DEFAULT [ construct-name ]
    In any particular SELECT RANK construct, there must not be more than one RANK DEFAULT statement, or more than one RANK (*) statement, or more than RANK (integer) with the same value integer expression. If the assumed-rank variable has the ALLOCATABLE or POINTER attribute, the RANK (*) statement is not permitted.

    The block following a RANK statement with an integer constant expression is executed if the assumed-rank variable is associated with a non-assumed-rank actual argument that has that rank, and is not an assumed-size array. Within the block it acts as if it were an assumed-shape array with that rank.

    The block following a RANK (*) is executed if the ultimate argument is an assumed-size array. Within the block it acts as if it were declared with bounds ‘(1:*)’; if different bounds or rank are desired, this can be passed to another procedure using sequence association.

    The block following a RANK DEFAULT statement is executed if no other block is selected. Within its block, it is still an assumed-rank variable, i.e. there is no change.

    Here is a simple example of the SELECT RANK construct.

      Program select_rank_example
    Integer :: a = 123, b(1,2) = Reshape( [ 10,20 ], [ 1,2 ] ), c(1,3,1) = 777, d(1,1,1,1,1)
    Call show(a)
    Call show(b)
    Call show(c)
    Call show(d)
  Contains
    Subroutine show(x)
      Integer x(..)
      Select Rank(x)
      Rank (0)
        Print 1,'scalar',x
      Rank (1)
        Print 1,'vector',x
      Rank (2)
        Print 1,'matrix',x
      Rank (3)
        Print 1,'3D array',x
      Rank Default
        Print *,'Rank',Rank(x),'not supported'
      End Select
    1 Format(1x,a,*(1x,i0,:))
    End Subroutine
  End Program
    This will produce the output
     scalar 123
 matrix 10 20
 3D array 777 777 777
 Rank 5 not supported
  • The TYPE(*) type specifier can be used to declare scalar, assumed-size, and assumed-rank dummy arguments. Such an argument is called assumed-type; the corresponding actual argument may be of any type. It must not have the ALLOCATABLE, CODIMENSION, INTENT (OUT), POINTER, or VALUE attribute.

    An assumed-type variable is extremely limited in the ways it can be used directly in Fortran:

    • it may be passed as an actual argument to another assumed-type dummy argument;
    • it may appear as the first argument to the intrinsic functions IS_CONTIGUOUS, LBOUND, PRESENT, SHAPE, SIZE, or UBOUND;
    • it may be used as the argument of the function C_LOC (in the ISO_C_BINDING intrinsic module}.
    Other than these contexts, it cannot be used in any other way at all. Note that if it is an array, you cannot subscript it or create an array section from it.

    This is mostly useful for interoperating with C programs. A TYPE(*) dummy argument interoperates with a C argument declared as “void *”. There is no difference between scalar and assumed-size on the C side, but on the Fortran side, if the dummy argument is scalar the actual argument must also be scalar, and if the dummy argument is an array, the actual argument must also be an array.

    Because an actual argument can be passed directly to a TYPE(*) dummy, the C_LOC function is not required, and so there is no need for the TARGET attribute on the actual argument.

    For example,

      Program type_star_example
    Interface
      Function checksum(scalar,size) Bind(C)
        Use Iso_C_Binding
        Type(*) scalar
        Integer(C_int),Value :: size
        Integer(C_int) checksum
      End Function
    End Interface
    Type myvec3
      Double Precision v(3)
    End Type
    Type(myvec3) x
    Call Random_Number(x%v)
    Print *,checksum(x,Storage_Size(x)/8)
  End Program
  int checksum(void *a,int n)
  {
    int i;
    int res = 0;
    unsigned char *p = a;
    for (i=0; i<n; i++) res = 0x3fffffff&((res<<1) + p[i]);
    return res;
  }
  • A BIND(C) procedure can have optional arguments. Such arguments cannot also have the VALUE attribute.

    An absent optional argument of a BIND(C) procedure is indicated by passing a null pointer argument.

    For example,

      Program optional_example
    Use Iso_C_Binding
    Interface
      Function f(a,b) Bind(C)
        Import
        Integer(C_int),Intent(In) :: a
        Integer(C_int),Intent(In),Optional :: b
        Integer(C_int) f
      End Function
    End Interface
    Integer(C_int) x,y
    x = f(3,14)
    y = f(23)
    Print *,x,y
  End Program

  int f(int *arg1,int *arg2)
  {
    int res = *arg1;
    if (arg2) res += *arg2;
    return res;
  }
    The second reference to f is missing the optional argument b, so a null pointer will be passed for it. This will result in the output:
     17 23
  • The intrinsic inquiry function RANK returns the dimensionality of its argument. It has the following syntax:
    RANK ( A )

    A : data object of any type:

    Result : scalar Integer of default kind.

    The result is the rank of A, that is, zero for scalar A, one if A is a one-dimensional array, and so on.

    This function can be used in a constant expression except when A is an assumed-rank variable.

  • The intrinsic function REDUCE performs user-defined array reductions. It has the following syntax:
    REDUCE ( ARRAY, OPERATION [, MASK, IDENTITY, ORDERED ] ) or
REDUCE ( ARRAY, OPERATION DIM [, MASK, IDENTITY, ORDERED ] )

    ARRAY : array of any type;

    OPERATION : pure function with two arguments, each argument being scalar, non-allocatable, non-pointer, non-polymorphic non-optional variables with the same declared type and type parameters as ARRAY; if one argument has the ASYNCHRONOUS, TARGET or VALUE attribute, the other must also have that attribute; the result must be a non-polymorphic scalar variable with the same type and type parameters as ARRAY;

    DIM : scalar Integer in the range 1 to N, where N is the rank of ARRAY;

    MASK : type Logical, and either scalar or an array with the same shape as ARRAY;

    IDENTITY : scalar with the same declared type and type parameters as ARRAY;

    ORDERED : scalar of type Logical;

    Result : Same type and type parameters as ARRAY.

    The result is ARRAY reduced by the user-supplied OPERATION. If DIM is absent, the whole (masked) ARRAY is reduced to a scalar result. If DIM is present, the result has rank N-1 and the shape of ARRAY with dimension DIM removed; each element of the result is the reduction of the masked elements in that dimension.

    If exactly one element contributes to a result value, that value is equal to the element; that is, OPERATION is only invoked when more that one element appears.

    If no elements contribute to a result value, the IDENTITY argument must be present, and that value is equal to IDENTITY.

    For example,

    Module triplet_m
  Type triplet
    Integer i,j,k
  End Type
Contains
  Pure Type(triplet) Function tadd(a,b)
    Type(triplet),Intent(In) :: a,b
    tadd%i = a%i + b%i
    tadd%j = a%j + b%j
    tadd%k = a%k + b%k
  End Function
End Module
Program reduce_example
  Use triplet_m
  Type(triplet) a(2,3)
  a = Reshape( [ triplet(1,2,3),triplet(1,2,4), &
                 triplet(2,2,5),triplet(2,2,6), &
                 triplet(3,2,7),triplet(3,2,8) ], [ 2,3 ] )
  Print 1, Reduce(a,tadd)
  Print 1, Reduce(a,tadd,1)
  Print 1, Reduce(a,tadd,a%i/=2)
  Print 1, Reduce(Array=a,Dim=2,Operation=tadd)
  Print 1, Reduce(a, Mask=a%i/=2, Dim=1, Operation=tadd, Identity=triplet(0,0,0))
1 Format(1x,6('triplet(',I0,',',I0,',',I0,')',:,'; '))
End Program
    This will produce the output:
     triplet(12,12,33)
 triplet(2,4,7); triplet(4,4,11); triplet(6,4,15)
 triplet(8,8,22)
 triplet(6,6,15); triplet(6,6,18)
 triplet(2,4,7); triplet(0,0,0); triplet(6,4,15)
  • Generic resolution can use the number of procedure arguments; that is, if one procedure has more non-optional procedure arguments than the other has optional plus non-optional procedure arguments, the procedures are considered to be unambiguous.

    For example,

    Module npa_example
  Interface g
    Module Procedure s1,s2
  End Interface
Contains
  Subroutine s1(a)
    External a
    Call a
  End Subroutine
  Subroutine s2(b,a)
    External b,a
    Call b
    Call a
  End Subroutine
End Module

    This example does not conform to the Fortran 2008 rules for unambiguous generic procedures, because the argument A distinguishes by position but not by keyword, the argument B distinguish by keyword but not by position, and the positional disambiguator (A) does not appear earlier in the list than the keyword disambiguator (B).

6 Additional OpenMP support

  • Undefined variable detection, with the -C=undefined option, is supported. For example, executing the program:
      Program bad
    Use omp_lib
    Real x,y(10)
    x = 3
    !$OMP PARALLEL DO DEFAULT(PRIVATE) SHARED(y)
      Do i=1,Size(y)
        y(omp_get_thread_num() + 1) = x * omp_get_thread_num()
      End Do
    !$OMP END PARALLEL DO
    Print *,y
  End Program
    produces the output
    Runtime Error: bad.f90, line 7: Reference to undefined variable X
Program terminated by fatal error
  • The OpenMP 4.0 CANCEL and CANCELLATION POINT directives are supported, along with the OMP_CANCELLATION environment variable and the OMP_GET_CANCELLATION function. Also, the OpenMP 5.0 CANCEL: keyword on the IF clause of CANCEL is supported.

    The syntax of the CANCEL directive is:

      !$OMP CANCEL construct-type [ [,] IF ( [ CANCEL: ] scalar-logical-expr ) ]
    where construct-type is one of the keywords PARALLEL, DO, SECTIONS or TASKGROUP. The directive must be closely nested in an OpenMP construct of the type specified, except for TASKGROUP where it must be closely nested in an OpenMP TASK construct. In the case of SECTIONS, the construct must not have a NOWAIT clause. In the case of DO, the construct must not have a NOWAIT clause or an ORDERED clause.

    Executing a CANCEL directive evaluates the IF clause if present, and if the IF clause is not present, or evaluates to true, and cancellation is enabled, the construct is cancelled. If cancelled, the executing thread jumps immediately to the end of the construct.

    The syntax of the CANCELLATION POINT directive is:

      !$OMP CANCELLATION POINT construct-type
    where construct-type is the same as for the CANCEL directive. As for CANCEL, the CANCELLATION POINT directive must be closely nested in the appropriate OpenMP construct. That construct should also have a CANCEL directive, otherwise there can never be any effect (other than waste CPU time) from the CANCELLATION POINT directive.

    Executing a CANCELLATION POINT directive will transfer control to the end of the construct if the construct has been cancelled; otherwise, there is no effect.

    Apart from the CANCELLATION POINT directive, there is also a cancellation point at a CANCEL directive (even if it has an IF clause that evaluates to false), a BARRIER directive, or an implied barrier (e.g. at the end of a contained construct such as END SINGLE without NOWAIT).

    After a construct has been cancelled, any barrier that is executed within the region must be closely nested inside the cancelled directive (i.e. not in a procedure called from the construct), otherwise there will either be a runtime error (with the NAG compiler) or an infinite hang (as the cancelling thread will never reach the barrier).

    Cancellation is enabled if the OMP_CANCELLATION environment variable has the value ‘TRUE’ (not case-sensitive), and is disabled if the variable has the value ‘FALSE’. If the variable does not exist, the setting is compiler-dependent; with the NAG Fortran Compiler, the default is FALSE.

    The OMP_GET_CANCELLATION function has the interface

      LOGICAL FUNCTION OMP_GET_CANCELLATION()
  END FUNCTION
    It returns .TRUE. if cancellation is enabled, and .FALSE. if disabled.

    Here is a simple example of cancellation.

      Program example
    Real a(20000,4),b(4)
    Logical ok
    Call Random_Number(a)
    a = a*10
    Call normalise(a,b,ok)
    Print 1,ok,b
    If (Any(a>2)) Print *,'Cancellation occurred'
    Call Random_Number(a)
    a = a*10
    a(:,2) = -a(:,2)
    Call normalise(a,b,ok)
    Print 1,ok,b
1   Format(1X,'Succeeded = ',L1,', vmax =',4F8.4)
    If (Any(a>2)) Print *,'Cancellation occurred'
  Contains
    Subroutine normalise(x,y,succeeded)
      Use omp_lib
      Real,Intent(InOut) :: x(:,:)
      Real,Intent(Out) :: y(Size(x,2))
      Logical,Intent(Out) :: succeeded
      Real z
      Integer me,i
      succeeded = .True.
      !$OMP PARALLEL PRIVATE(me,i,z) SHARED(x,y) NUM_THREADS(Size(x,2))
        z = 0
        me = omp_get_thread_num() + 1
        Do i=1,Size(x,1)
          If (x(i,me)>z) z = x(i,me)
        End Do
        y(me) = z
        !$OMP CANCEL PARALLEL, IF (z==0)
        z = 2.0/z
        Do i=1,Size(x,1)
          x(i,me) = x(i,me)*z
          If (Iand(i,4095)==0) Then
            ! Every 4096 elements, check to see if the whole thing was cancelled already.
            !$OMP CANCELLATION POINT PARALLEL
          End If
        End Do
      !$OMP END PARALLEL
      succeeded = All(y/=0)
    End Subroutine
  End Program

    The output from this example could look something like

     Succeeded = T, vmax =  9.9993  9.9997  9.9998  9.9974
 Succeeded = F, vmax =  9.9999  0.0000  9.9996  9.9998
 Cancellation occurred
  • The OpenMP 5.1 MASKED construct is supported. This has the form:
      !$OMP MASKED [ FILTER( scalar-integer-expression ) ]
    structured-block
  !$OMP END MASKED
    A thread executes the structured-block if and only if the scalar-integer-expression evaluates equal to the thread number. Thread numbers start at zero, which is the number of the primary thread of a PARALLEL region. If the FILTER clause is not present, it acts as if it were present as FILTER(0); that is, only the primary thread will execute the structured block.

    This is exactly equivalent to

      IF (omp_get_thread_num()==scalar-integer-expression) THEN
    structured-block
  END IF

    Note that the integer expression need not have the same value on each thread, and if that is the case, more than one thread may execute the masked region concurrently — there is no locking or synchronisation implied by this construct. That means that if any variables that are not local to the thread are updated, the necessary locking will need to be explicitly inserted by the programmer.

7 Additional error checking

  • Multiple occurrences of the same variable in an ALLOCATE or DEALLOCATE statement is now detected as an error.
  • Checking of type-bound procedure overriding and global consistency now reports differences in dummy argument shape.
  • Integer arguments to SYSTEM_CLOCK that are 8-bit or 16-bit are now detected as errors, as they are too small to receive the values.
  • Warnings are produced for argument inconsistencies for SYSTEM_CLOCK when
    • there are no arguments;
    • integer arguments have different kind (this will be invalid in Fortran 202x);
    • mixed integer and real arguments;
    • integer arguments are not 64-bit integer as recommended by Fortran 202x.
  • An error is produced for use of a NAMELIST with a variable that has an allocatable, pointer, or inaccessible component, if the variable will not be processed by defined input/output.
  • A warning is produced if a format specification that is a constant character string has non-blank characters after the closing parenthesis, for example,
      Print '(1X,I0) whatever',13
    will produce a warning like
      Questionable: file.f90, line 2: Extraneous nonblank characters "whatever" after right
                                  parenthesis in character string format specification
  • A CONTINUE statement does not have any effect, but may be a branch target statement, or the end of a DO loop, if it has a label. A CONTINUE statement with no label however, cannot be of use in any way. Therefore we produce a Note level warning. If the CONTINUE statement is within a DO loop, this is upgraded to Questionable, as a C programmer might think it has the effect of the CYCLE statement (as it does in C). For example,
      Program continues
    Continue
    Do i=1,10
      Print *,i**2
      Continue
    End Do
  End Program
    will produce the warnings
    Note: file.f90, line 2: CONTINUE statement with no label
Questionable: file.f90, line 5: CONTINUE statement with no label inside DO loop - did you
                                mean CYCLE?
  • When allocating coarrays that are of parameterised derived type, a difference in the length type parameter values on different images is now detected as a runtime error. For example,
      Allocate(w[*],Mold=z)
    where Z is a dummy argument with different type parameter values on different images, may produce a runtime error like
    Runtime Error: pco068.f90, line 17: Type parameter K1 in coarray allocation has value 1 on
                                    image one but 13 on image 2
  • Empty SELECT CASE and SELECT TYPE constructs are reported as Questionable, as they do not do anything other than evaluate the selector.

    For example, if the file sub.f90 contains:

      Subroutine sub(x,n)
    Class(*) x
    Integer n
    Select Case (n)
    End Select
    Select Type (x)
    End Select
  End Subroutine
    the following warnings will be produced:
    Questionable: sub.f90, line 4: Empty SELECT CASE construct
Questionable: sub.f90, line 6: Empty SELECT TYPE construct

    Also, evaluation of the selector may not happen if optimisation (the -O option) is used.

  • The -C=intovf option will now detect integer overflow in the SHAPE and SIZE intrinsic functions. For example,
      Program shape_overflow_example
    Real a(1,123456,3)
    Call sub(a)
  Contains
    Subroutine sub(x)
      Use Iso_Fortran_Env
      Real,Intent(In) :: x(:,:,:)
      Integer(int16) sh(3)
      sh = Shape(x,int16)
      Print *,sh
    End Subroutine
  End Program
    If compiled with -C=intovf, instead of producing the nonsense results
     1 -7616 3
    it will produce the runtime error message:
    Runtime Error: shape_overflow_example.f90, line 9: INTEGER(int16) overflow for intrinsic
 SHAPE, true result value is 123456
  • The -C=calls option now treats dummy arguments that are procedure pointers as being different from functions returning data pointers, and from functions returning procedure pointers (at any level of procedure call). These errors can only arise if a procedure is invoked with an incorrect INTERFACE block specification.

    For example, if the procedure

      Subroutine sub(f,x)
    Interface
      Function f(y)
        Real,Pointer :: f
      End Function
    End Interface
    Real,Intent(In) :: x
    Real,Pointer :: p
    p => f(x)
    Print *,Associated(p)
  End Subroutine
    is invoked (via an incorrect interface block) as follows
      Program bad
    Interface
      Subroutine sub(f,x)
        Real,External,Pointer :: f
        Real,Intent(In) :: x
      End Subroutine
    End Interface
    Real,External,Pointer :: pp
    Intrinsic sqrt
    pp => sqrt
    Call sub(pp,1.5)
  End Program
    the -C=calls option (with -gline to get a traceback) will produce the runtime error message
    Runtime Error: sub.f90, line 1: Incorrect interface block for SUB - Dummy argument F
  (number 1) is not a procedure pointer
Program terminated by fatal error
sub.f90, line 1: Error occurred in SUB
bad.f90, line 11: Called by BAD
    instead of a segmentation fault.

8 Miscellaneous enhancements

  • The polish options -idcase= and -kwcase= now have an extra possibility: ‘Camel_Case’. This differs from ‘Capitalised’ only in that a letter after an underscore will also be uppercase, not just the initial letter. For -kwcase=Camel_Case, the keywords affected are Non_Intrinsic, Non_Overridable and Non_Recursive, and the OpenMP keyword Num_Threads. Note that case specifications are not case-sensitive, and can be abbreviated to the first letter, except for Camel_Case which can be abbreviated to ‘cam’.
  • The polish option -idcase= now has an extra possibility: ‘Asis’. This preserves the case of all identifiers, including user-defined operators (but not intrinsic operators), as they appear in the input. For example, the input “eX = Ex + 1” will produce exactly the same inconsistent casing in the output. This option is not available with enhanced polish or other tools.
  • The enhanced polish option -case: allows different case settings for different kinds of name. The colon is followed by a comma-separated list of “kind=case”, where case is a case specification (UPPERCASE, lowercase, Capitalised, Camel_Case), and kind is one of the categories listed below:

    comp | Component
    constr | Construct name
    intr | Intrinsic procedure
    param | PARAMETER
    proc | Procedure
    tbp | Type-bound procedure
    tparam | Derived type parameter
    type | Derived type
    var | Variable

    For example, -case:var=lower,proc=u specifies lowercase for variables and UPPERCASE for procedures. If there is no setting for a particular kind of name, it will fall back to an appropriate category; param, type, comp, tparam and proc all fall back to var, intr will fall back to proc, and tbp will fall back to comp or proc. If there is no rule or fall-back rule, the -idcase= option setting (or default) is used.

  • The enhanced polish -casex: specifies exceptions to the case rules. The colon is followed by a comma-separated list of names in the exact case required. For example, -casex:MaxVal,XYz will result in every occurence of a name equivalent to maxval or xyz appearing as MaxVal or XYz respectively.
  • The -quiet option suppresses the compiler (or tool) banner message, and also the summary line at the end, so that only diagnostic messages will appear.
  • Extension messages now provide information on what kind of extension it is. This is either the edition of the Fortran standard that added the feature (e.g. “Extension(F2018)”), whether it is a NAG extension (“Extension(NAG)”), or whether it is an obsolete extension, e.g. to FORTRAN77, that has been superseded by standard features (“Non-standard(Obsolete)”).
  • Informational messages have been split into three levels: Note (highest), Info, and Remark (lowest). By default, Note messages are produced; this can be suppressed with the -w=note option. The -info option causes both Info and Remark messages to appear.


NAG Fortran Compiler, Release 7.1

NAG® Fortran Compiler

© 2021 The Numerical Algorithms Group Limited

All rights reserved. No part of this Manual may be reproduced, transcribed, stored in a retrieval system, translated into any language or computer language or transmitted in any form or by any means, electronic, mechanical, photocopying, recording or otherwise, except for the purpose of using the NAG Fortran Compiler.

The copyright owner gives no warranties and makes no representations about the contents of this Manual and specifically disclaims any implied warranties of merchantability or fitness for any purpose.

The copyright owner reserves the right to revise this Manual and to make changes from time to time in its contents without notifying any person of such revisions or changes.

11th Edition – December 2021

NAG is a registered trademark of:

The Numerical Algorithms Group Limited
The Numerical Algorithms Group Inc
Nihon Numerical Algorithms Group KK

All other trademarks are acknowledged.

NAG Ltd | Nihon NAG KK
30 St Giles' | Hatchobori Frontier Building 2F
OXFORD | 4-9-9
OX1 3LE | Hatchobori
United Kingdom | Chuo-ku
Tel: +44 (0)1865 511245 (general) | Tokyo
Tel: +44 (0)1865 311744 (support) | 104-0032
Web: www.nag.com | Japan
 | Tel: +81 (0)3 5542 6311
 | Fax: +81 (0)3 5542 6312
 | Web: www.nag-j.co.jp
NAG Inc |
801 Warrenville Road, Suite 185 |
Lisle, IL 60532-4332 |
USA |
Tel: +1 630 971 2337 |
Fax: +1 630 971 2706 |
Web: www.nag.com |

NAG also has a number of distributors throughout the world. Please contact NAG for further details.

  • 1 Introduction
    • 1.1 Introduction to the Compiler
      • 1.1.1 Other Fortran-related Activities at NAG
      • 1.1.2 This Manual
  • 2 Using the Compiler
    • 2.1 Usage
    • 2.2 Description
    • 2.3 File Types
    • 2.4 Compiler Options
    • 2.5 Files
    • 2.6 Compilation Messages
    • 2.7 Compiler Limits
    • 2.8 Input/Output Information
    • 2.9 OpenMP Support
    • 2.10 Automatic File Preconnection
    • 2.11 IEEE 754 Arithmetic Support
    • 2.12 Half precision floating-point
    • 2.13 Random Number Algorithm
    • 2.14 Automatic Garbage Collection
    • 2.15 Memory Tracing
    • 2.16 Undefined Variable Detection
    • 2.17 Data Types
    • 2.18 Modules
    • 2.19 Runtime Environment Variables
    • 2.20 Debugging
    • 2.21 Producing a Call Graph
    • 2.22 Dependency Analysis
    • 2.23 Generating Interfaces
    • 2.24 Source File Polishing
    • 2.25 Enhanced Source File Polishing
    • 2.26 Unifying Precision
  • 3 Debugging with dbx90
    • 3.1 dbx90 command line
    • 3.2 Description of dbx90
    • 3.3 dbx90 options
    • 3.4 dbx90 Commands
    • 3.5 dbx90 Expressions
      • 3.5.1 Scalar expressions
      • 3.5.2 Array sections
      • 3.5.3 Derived type component specification
    • 3.6 dbx90 Command aliases
    • 3.7 dbx90 limitations
    • 3.8 Example of dbx90
    • 3.9 Troubleshooting dbx90
  • 4 Preprocessing with fpp
    • 4.1 Overview of fpp
    • 4.2 fpp command line
    • 4.3 Description of fpp
    • 4.4 fpp options
    • 4.5 Using fpp
      • 4.5.1 Source files
      • 4.5.2 Output
      • 4.5.3 Directives
      • 4.5.4 Macro definition
      • 4.5.5 Including external files
      • 4.5.6 Line number control
      • 4.5.7 Conditional selection of source text
    • 4.6 Preprocessing details
      • 4.6.1 Scope of macro or variable definitions
      • 4.6.2 End of macro definition
      • 4.6.3 Function-like macro definition
      • 4.6.4 Cancelling macro definitions
      • 4.6.5 Conditional source code selection
      • 4.6.6 Including external files
      • 4.6.7 Comments
      • 4.6.8 Macro functions
      • 4.6.9 Macro expression
    • 4.7 fpp diagnostics
  • 5 Extensions
    • 5.1 Non-standard Extensions
      • 5.1.1 BOZ literal constants outside DATA statements
      • 5.1.2 Longer Names
      • 5.1.3 Dollar Sign in Names
      • 5.1.4 Input/output endian/format conversion
      • 5.1.5 Elemental BIND(C) procedures
      • 5.1.6 Maximum array rank is 31
    • 5.2 Obsolete Extensions
      • 5.2.1 Byte Sizes
      • 5.2.2 TAB Format
      • 5.2.3 Hollerith Constants
      • 5.2.4 D (debug) lines in Fixed Source Form
      • 5.2.5 Increased Line Length in Fixed Source Form
      • 5.2.6 Increased Maximum Number of Continuation Lines
      • 5.2.7 Intrinsic functions with mixed-kind arguments
      • 5.2.8 ACCESS='APPEND' specifier on OPEN statement
      • 5.2.9 VAX FORTRAN TYPE statement
      • 5.2.10 Auto-skipping NAMELIST input
      • 5.2.11 Legacy Application Support
      • 5.2.12 Mismatched Argument Lists
      • 5.2.13 Double Precision Complex Extensions
  • 6 Intrinsic Modules
    • 6.1 Intrinsic Module Overview
    • 6.2 f90_gc
    • 6.3 f90_iostat
    • 6.4 f90_kind
    • 6.5 f90_preconn_io
      • 6.5.1 Procedures
      • 6.5.2 Example
    • 6.6 f90_stat
      • 6.6.1 Parameters
      • 6.6.2 Example
    • 6.7 f90_unix_*
    • 6.8 ieee_*, iso_c_binding, iso_fortran_env
  • 7 Modern Fortran API to Posix
    • 7.1 Posix Module Overview
    • 7.2 f90_unix_dir
      • 7.2.1 Parameters
      • 7.2.2 Procedures
    • 7.3 f90_unix_dirent
      • 7.3.1 Procedures
    • 7.4 f90_unix_env
      • 7.4.1 Parameters
      • 7.4.2 Types
      • 7.4.3 Procedures
    • 7.5 f90_unix_errno
      • 7.5.1 Error Handling
      • 7.5.2 Parameters
    • 7.6 f90_unix_file
      • 7.6.1 Parameters
      • 7.6.2 Types
      • 7.6.3 Procedures
    • 7.7 f90_unix_io
      • 7.7.1 Procedures
    • 7.8 f90_unix_proc
      • 7.8.1 Parameters
      • 7.8.2 Procedures
  • 8 Standard Fortran 95
    • 8.1 Fortran 95 Program Structure
    • 8.2 Fortran 95 Expressions
    • 8.3 Fortran 95 Statements
    • 8.4 Fortran 95 Intrinsic Procedures
  • 9 Fortran 2003 Extensions
    • 9.1 Fortran 2003 Overview
    • 9.2 Object-oriented programming
      • 9.2.1 Type Extension
        • 9.2.1.1 Extending Types [5.0]
        • 9.2.1.2 Polymorphic Variables [5.0]
        • 9.2.1.3 Type Selection [5.0]
        • 9.2.1.4 Unlimited polymorphism [5.2]
        • 9.2.1.5 Ad hoc type comparison [5.3]
      • 9.2.2 Typed allocation [5.1]
      • 9.2.3 Sourced allocation (cloning) [5.1]
      • 9.2.4 Type-bound procedures [5.1]
        • 9.2.4.1 The type-bound procedure part
        • 9.2.4.2 Specific type-bound procedures
        • 9.2.4.3 Generic type-bound procedures
      • 9.2.5 Abstract derived types [5.1]
      • 9.2.6 Object-bound procedures [5.2]
    • 9.3 ALLOCATABLE extensions
      • 9.3.1 Allocatable Dummy Arrays [4.x]
      • 9.3.2 Allocatable Function Results [4.x]
      • 9.3.3 Allocatable Structure Components [4.x]
      • 9.3.4 Allocatable Component Example
      • 9.3.5 The MOVE_ALLOC intrinsic subroutine [5.2]
      • 9.3.6 Allocatable scalars [5.2]
      • 9.3.7 Automatic reallocation [5.2]
    • 9.4 Other data-oriented enhancements
      • 9.4.1 Parameterised derived types [6.0 for kind type parameters, 6.1 for length]
        • 9.4.1.1 Basic Syntax and Semantics
        • 9.4.1.2 More Semantics
        • 9.4.1.3 Assumed type parameters
        • 9.4.1.4 Deferred type parameters
      • 9.4.2 Finalisation [5.3]
      • 9.4.3 The PROTECTED attribute [5.0]
        • 9.4.3.1 Syntax
        • 9.4.3.2 Semantics
        • 9.4.3.3 Example
      • 9.4.4 Pointer enhancements
        • 9.4.4.1 INTENT for pointers [5.1]
        • 9.4.4.2 Pointer bounds specification [5.2]
        • 9.4.4.3 Rank-remapping Pointer Assignment [5.0]
      • 9.4.5 Individual component accessibility [5.1]
      • 9.4.6 Public entities of private type [5.1]
    • 9.5 C interoperability [mostly 5.1]
      • 9.5.1 The ISO_C_BINDING module
        • 9.5.1.1 The kind parameters
        • 9.5.1.2 Using C_PTR and C_FUNPTR
      • 9.5.2 BIND(C) types
      • 9.5.3 BIND(C) variables
      • 9.5.4 BIND(C) procedures
      • 9.5.5 Enumerations
    • 9.6 IEEE arithmetic support [4.x except as otherwise noted]
      • 9.6.1 Introduction
      • 9.6.2 Exception flags, modes and information flow
      • 9.6.3 Procedures in the modules
      • 9.6.4 The IEEE_FEATURES module
      • 9.6.5 IEEE_EXCEPTIONS
        • 9.6.5.1 Types and constants
        • 9.6.5.2 Procedures
      • 9.6.6 IEEE_ARITHMETIC module
        • 9.6.6.1 IEEE datatype selection
        • 9.6.6.2 Enquiry functions
        • 9.6.6.3 Rounding mode
        • 9.6.6.4 Underflow mode
        • 9.6.6.5 Number Classification
        • 9.6.6.6 Test functions
        • 9.6.6.7 Arithmetic functions
    • 9.7 Input/output Features
      • 9.7.1 Stream input/output [5.1]
      • 9.7.2 The BLANK= and PAD= specifiers [5.1]
      • 9.7.3 Decimal Comma [5.1]
      • 9.7.4 The DELIM= specifier [5.1]
      • 9.7.5 The ENCODING= specifier [5.1]
      • 9.7.6 The IOMSG= specifier [5.1]
      • 9.7.7 The IOSTAT= specifier [5.1]
      • 9.7.8 The SIGN= specifier [5.1]
      • 9.7.9 Intrinsic functions for testing IOSTAT= values [5.1]
      • 9.7.10 Input/output of IEEE infinities and NaNs [5.1]
      • 9.7.11 Output of floating-point zero [5.1]
      • 9.7.12 NAMELIST and internal files [5.1]
      • 9.7.13 Variables permitted in NAMELIST
      • 9.7.14 Recursive input/output [5.2]
      • 9.7.15 Asynchronous input/output
        • 9.7.15.1 Basic syntax [5.1]
        • 9.7.15.2 Basic Example
        • 9.7.15.3 The ASYNCHRONOUS attribute [5.2]
        • 9.7.15.4 The WAIT statement [5.2]
        • 9.7.15.5 Execution Semantics
      • 9.7.16 Scale factor followed by repeat count [5.1]
      • 9.7.17 FLUSH statement [5.2]
      • 9.7.18 Defined input/output [6.2]
    • 9.8 Miscellaneous Fortran 2003 Features
      • 9.8.1 Abstract interfaces and the PROCEDURE statement [5.1]
      • 9.8.2 Named procedure pointers [5.2]
      • 9.8.3 Intrinsic modules [4.x]
      • 9.8.4 Renaming user-defined operators on the USE statement [5.2]
      • 9.8.5 The ISO_FORTRAN_ENV module [5.1]
      • 9.8.6 The IMPORT statement [5.1]
      • 9.8.7 Length of names and statements
      • 9.8.8 Array constructor syntax enhancements
      • 9.8.9 Structure constructor syntax enhancements [5.3]
      • 9.8.10 Deferred character length [5.2]
      • 9.8.11 The ERRMSG= specifier [5.1]
      • 9.8.12 Intrinsic functions in constant expressions [5.2 partial; 5.3 complete]
      • 9.8.13 Specification functions can be recursive [6.2]
      • 9.8.14 Access to the command line [5.1]
      • 9.8.15 Access to environment variables [5.1]
      • 9.8.16 Character kind selection [5.1]
      • 9.8.17 Argument passing relaxation [5.1]
      • 9.8.18 The MAXLOC and MINLOC intrinsic functions [5.1]
      • 9.8.19 The VALUE attribute [4.x]
        • 9.8.19.1 Syntax
        • 9.8.19.2 Semantics
        • 9.8.19.3 Example
      • 9.8.20 The VOLATILE attribute [5.0]
      • 9.8.21 Enhanced complex constants [5.2]
      • 9.8.22 The ASSOCIATE construct [5.2]
      • 9.8.23 Binary, octal and hexadecimal constants [5.2]
      • 9.8.24 Character sets [5.1; 5.3]
      • 9.8.25 Intrinsic function changes for 64-bit machines [5.2]
      • 9.8.26 Miscellaneous intrinsic procedure changes [5.2]
  • 10 Fortran 2008 Extensions
    • 10.1 Fortran 2008 Overview
    • 10.2 SPMD programming with coarrays [6.2, 7.0]
      • 10.2.1 Overview
      • 10.2.2 Images
      • 10.2.3 Coarrays
      • 10.2.4 Declaring coarrays
      • 10.2.5 Accessing coarrays on other images
      • 10.2.6 Segments and synchronisation
      • 10.2.7 Allocating and deallocating coarrays
      • 10.2.8 Critical constructs
      • 10.2.9 Lock variables
      • 10.2.10 Atomic coarray accessing
      • 10.2.11 Normal termination of execution
      • 10.2.12 Error termination
      • 10.2.13 Fault tolerance
      • 10.2.14 Detailed syntax of coarray features
      • 10.2.15 Intrinsic procedures and coarrays
    • 10.3 Data declaration [mostly 6.0]
    • 10.4 Data usage and computation [mostly 5.3]
    • 10.5 Execution control [mostly 6.0]
    • 10.6 Intrinsic procedures and modules
      • 10.6.1 Additional mathematical intrinsic functions [mostly 5.3.1]
      • 10.6.2 Additional intrinsic functions for bit manipulation [mostly 5.3]
      • 10.6.3 Other new intrinsic procedures [mostly 5.3.1]
      • 10.6.4 Changes to existing intrinsic procedures [mostly 5.3.1]
      • 10.6.5 ISO_C_BINDING additions [6.2]
      • 10.6.6 ISO_FORTRAN_ENV additions
    • 10.7 Input/output extensions [mostly 5.3]
    • 10.8 Programs and procedures [mostly 5.3]
  • 11 Fortran 2018 Extensions
    • 11.1 Fortran 2018 Overview
    • 11.2 Data declaration
    • 11.3 Data usage and computation
    • 11.4 Input/output
    • 11.5 Execution control
    • 11.6 Intrinsic procedures and modules
    • 11.7 Program units and procedures
    • 11.8 Advanced C interoperability
    • 11.9 Updated IEEE arithmetic capabilities
    • 11.10 Advanced coarray programming
  • 12 Appendices
    • 12.1 Mixing Fortran and C
      • 12.1.1 Naming Conventions
      • 12.1.2 Initialisation and Termination
      • 12.1.3 Calling Conventions
      • 12.1.4 Data Types
        • 12.1.4.1 Pointers
        • 12.1.4.2 Derived types
        • 12.1.4.3 Supporting types
      • 12.1.5 SUBROUTINE return types
        • 12.1.5.1 SUBROUTINEs with label arguments
        • 12.1.5.2 SUBROUTINEs with no label arguments
      • 12.1.6 FUNCTION return types
        • 12.1.6.1 Scalar
        • 12.1.6.2 Scalar POINTER functions
        • 12.1.6.3 Array non-POINTER functions
        • 12.1.6.4 Array POINTER functions
      • 12.1.7 Argument types
        • 12.1.7.1 CHARACTER type
        • 12.1.7.2 non-POINTER non-ALLOCATABLE Scalar
        • 12.1.7.3 POINTER and ALLOCATABLE Scalar
        • 12.1.7.4 non-POINTER Array
        • 12.1.7.5 POINTER Array
        • 12.1.7.6 Procedures
        • 12.1.7.7 OPTIONAL arguments
    • 12.2 ASCII Collating Sequence
      • 12.2.1 Printing Characters
      • 12.2.2 Non-printing Characters
  • 13 Detailed Contents


NAG Fortran Compiler, Release 7.1: Introduction

 Navigation: Previous Up Next

1 Introduction

  • 1.1 Introduction to the Compiler
    • 1.1.1 Other Fortran-related Activities at NAG
    • 1.1.2 This Manual


NAG Fortran Compiler, Release 7.1: Introduction to the Compiler

 Navigation: Previous Up Next

1.1 Introduction to the Compiler

The NAG Fortran Compiler is based on the NAGWare f90 Compiler which was the world's first Fortran 90 compiler. The design goals of the development were to produce a compiler with the following characteristics:

  • compiles standard Fortran to host-compatible C;
  • good speed of compilation, reasonable efficiency of execution;
  • good error checking, comprehensible error messages;
  • full standard implementation, standard-conforming compiler (i.e. all constraints identified);
  • modular construction;
  • compiler written in C;
  • maintainability, portability and re-usability.

The compiler is multi-pass; the passes have been kept distinct to improve maintainability and to allow re-use of the components.

Pass 1:
Lexical and syntactic analysis, build symbol table and abstract syntax tree.
Pass 2:
Semantic analysis, annotate parse tree and fill in symbol table; all major error and constraint detection takes place in this pass.
Pass 3:
Code generation by parse tree transformation.
Pass 4:
Code output, generate declarations and flatten transformed parse tree to C source code.
Pass 5:
Compilation using the host operating system's C compiler.
Pass 6:
Linking to executable code using the host system's linker, including linking in the Fortran run-time libraries.

1.1.1 Other Fortran-related Activities at NAG

NAG has released several Fortran-based numerical procedure libraries: the Fortran Library, SMP Library, Parallel Library and the Fortran 90 Library. A number of implementations of these libraries, using the NAG compiler and other compilers, are available.

NAG has supported the development and standardisation of Modern Fortran, participating both in ISO/IEC JTC1/SC22 Working Group 5, and the technical development committee INCITS/PL22.3. The head of the NAG compiler team, Malcolm Cohen, is the current Project Editor of the ISO/IEC Fortran standard.

From this it can be seen that NAG is committed to Fortran.

1.1.2 This Manual

This is the documentation for the NAG Fortran Compiler. This is not intended to be a language description or tutorial, but rather a guide to the use of the software and a quick reference for some of the features of the language.

The compiler is a full implementation of the Fortran 2008 programming language [ISO/IEC 1539-1:2010(E)] and many features from the latest Fortran 2018 standard [ISO/IEC 1539-1:2018(E)].


NAG Fortran Compiler, Release 7.1: Using the Compiler

 Navigation: Previous Up Next

2 Using the Compiler

  • 2.1 Usage
  • 2.2 Description
  • 2.3 File Types
  • 2.4 Compiler Options
  • 2.5 Files
  • 2.6 Compilation Messages
  • 2.7 Compiler Limits
  • 2.8 Input/Output Information
  • 2.9 OpenMP Support
  • 2.10 Automatic File Preconnection
  • 2.11 IEEE 754 Arithmetic Support
  • 2.12 Half precision floating-point
  • 2.13 Random Number Algorithm
  • 2.14 Automatic Garbage Collection
  • 2.15 Memory Tracing
  • 2.16 Undefined Variable Detection
  • 2.17 Data Types
  • 2.18 Modules
  • 2.19 Runtime Environment Variables
  • 2.20 Debugging
  • 2.21 Producing a Call Graph
  • 2.22 Dependency Analysis
  • 2.23 Generating Interfaces
  • 2.24 Source File Polishing
  • 2.25 Enhanced Source File Polishing
  • 2.26 Unifying Precision


NAG Fortran Compiler, Release 7.1: Usage

 Navigation: Previous Up Next

2.1 Usage

nagfor [mode] [option]... file...


NAG Fortran Compiler, Release 7.1: Description

 Navigation: Previous Up Next

2.2 Description

nagfor is the interface to the NAG Fortran Compiler system. The compiler translates programs written in Fortran into executable programs, relocatable binary modules, assembler source files or C source files.

The mode determines the action performed, and can be one of

=C | Compile (and/or link) C source files, acting as the companion processor; this passes options to the C compiler that are suitable for the ABI and/or compatibility mode options specified, and differs from the =compiler mode in that it does not set NAG-specific macro definitions or alter the #include file search path to include the compiler library directory.
=compiler | Compile (and/or link) the files; this is the default mode if none is specified.
=callgraph | Produce a callgraph of the Fortran routines in the files (see the Producing a Call Graph section).
=depend | Produce a dependency analysis of the Fortran files (see the Dependency Analysis section).
=epolish | Pretty-print (polish) the Fortran files using the Enhanced Polisher (see the Enhanced Source File Polishing section).
=interfaces | Produce a module or INCLUDE file containing procedure interfaces (see the Generating Interfaces section).
=polish | Pretty-print (polish) the Fortran files (see the Source File Polishing section).
=unifyprecision | Unify the precision of floating-point and complex entities in the files (see the Unifying Precision section).

Options that do not apply to the current mode of operation (e.g. polish options when the mode is for compilation) are ignored.

The mode can also be specified as -mode=mode; this may be useful if the user's command processor has a special meaning for equals signs (e.g. zsh).


NAG Fortran Compiler, Release 7.1: File Types

 Navigation: Previous Up Next

2.3 File Types

A file ending in ‘.f90’ or ‘.f95’ is taken to be a Fortran free-form source file, a file ending in ‘.f’, ‘.for’ or ‘.ftn’ is taken to be a Fortran fixed-form source file; these assumptions can be overridden with the -fixed or -free option. A file ending in ‘.ff90’ or ‘.ff95’ is taken to be a free-form file requiring preprocessing by fpp, and a file ending in ‘.ff’ is taken to be a fixed-form file requiring preprocessing by fpp. On Unix, a file ending in ‘.F90’ or ‘.F95’ is taken to be a free-form file requiring preprocessing by fpp, and a file ending in ‘.F’ is taken to be a fixed-form files requiring preprocessing by fpp. (Note that on MacOS and Windows, the file system is not case-sensitive so uppercase and lowercase letters are equivalent in filenames including in the suffixes.)

If a filename without a suffix is provided nagfor will look for a file with the suffix ‘.f95’, and if that does not exist, the suffix ‘.f90’.

A file ending in ‘.c’ is taken to be a C source file. In the =compiler mode, this is assumed to be the output from the compiler with the -S option, and the C compiler is passed -D and -I options suitable for compiling such a file. In the =C mode, it is assumed to be a file for the companion processor; no -D is passed, and only -I options specified by the user. In both cases, options are passed to the C compiler according to the ABI and compatibility mode options.

Non-intrinsic modules, INCLUDE files and #include files are expected to exist in the current working directory or in a directory named by an -I option.


NAG Fortran Compiler, Release 7.1: Compiler Options

 Navigation: Previous Up Next

2.4 Compiler Options

-132
Increase the length of each fixed source form input line from 72 characters to 132 characters. This has no effect on free source form input.
-abi=abi
(Linux x86-64 only) Specify the ABI to compile for, either 32 (the 32-bit ABI), or one of the 64-bit ABIs: 64c or 64t. The differences between the two 64-bit ABIs are as follows:

ABI | Object size represented in | Character length represented in
-abi=64t | 64 bits | 32 bits
-abi=64c | 64 bits | 64 bits

Programs compiled with -abi=32 will run on any x86 Linux system; those compiled with any 64-bit ABI will only run on a 64-bit kernel.

The default is -abi=64t. The -abi=64c option is compatible with the ABI used by Intel Fortran.

-abi=abi
(Windows only) Specify the ABI to compile for, either 32 (the 32-bit ABI) or 64 (the 64-bit ABI). The default is -abi=64 on Windows x64; on 32-bit Windows the default is -abi=32 and the -abi=64 option is not available.
-align=alignment
(MacOS only) Specify the alignment of variables and components, which must be one of:
natural | (natural alignment for best performance; this can alter the interpretation of COMMON block or SEQUENCE type layout in a non-standard-conforming manner), or
standard | (use standard-conforming alignment; this is the default).

The whole program should be compiled with the same alignment option.

-B binding
Specify static or dynamic binding. This only has effect if specified during the link phase. The default is dynamic binding. On SPARC and SG/Irix, these options are positional and can be used to selectively bind some libraries statically and some dynamically. This option is not available on IBM z9 Open Edition.
-c
Compile only (produce .o file for each source file), do not link the .o files to produce an executable file. This option is equivalent to -otype=obj.
-C
Compile with all but the most expensive runtime checks; this omits the -C=alias, -C=dangling, -C=intovf and -C=undefined options.
-C=check
Compile checking code according to the value of check, which must be one of:

alias | (check for assignments to aliased dummy arguments),
all | (perform all checks except for -C=undefined),
array | (check array bounds),
bits | (check bit intrinsic arguments),
calls | (check procedure references),
dangling | (check for dangling pointers),
do | (check DO loops for zero step values and
illicit modification of the index variable via host association),
intovf | (check for integer overflow),
none | (do no checking: this is the default),
present | (check OPTIONAL references),
pointer | (check POINTER references),
recursion | (check for invalid recursion) or
undefined | (check for undefined variables).

The -C=alias option will produce a runtime error when it is detected that assignment to a dummy argument affects another dummy argument. At this release this is only detected for scalar dummy arguments.

The -C=dangling option will produce a runtime error when a dangling pointer is used; additionally, if the runtime option ‘show_dangling’ is set, a warning will be produced at the time the pointer becomes dangling (see Runtime Environment Variables for further information).

The -C=undefined option is subject to a number of limitations; in particular, it is not binary compatible with Fortran code compiled without that option, and is not compatible with calling C code via a BIND(C) interface. See the Undefined Variable Detection section for further details.

-coarray
This option is short for -coarray=cosmp.
-coarray=mode
Set the coarray operation mode to mode, which must be single for Single Image mode, or cosmp for Co-SMP mode; the option is not case-sensitive. The default is -coarray=single.

In Single Image mode (-coarray=single), all coarray syntax is accepted, but execution will not be in parallel: only a single image is supported.

In Co-SMP mode (-coarray=cosmp), parallel execution of multiple images on an SMP machine is supported. The maximum number of images in this mode is 1000. If the -num_images=N option is used, the default number of images to execute is N; with -num_images=auto, the default number of images is the number of hardware threads available on the processor. Note that the number of images may exceed the number of hardware threads, but doing so will only improve performance if images spend a lot of time waiting (e.g. for synchronisation or input/output). The -num_images= option may be overridden by the runtime environment variable NAGFORTRAN_NUM_IMAGES.

Code that uses any coarray features (coarray syntax or image control statements) or that has any common blocks or global (saved or initialised) variables, and that is compiled with -coarray=single, must never be executed in Co-SMP mode, as it will not work correctly. Code that avoids those features, and which is intended to work both in Co-SMP mode and single image mode, should be compiled with the -thread_safe option.

The -coarray=cosmp option cannot be used at the same time as -gline or -openmp. The -coarray=cosmp option may be specified with the -C=undefined option, but it will automatically disable the latter option.

-colour
Colour the message output from the compiler using ANSI escape sequences and the default foreground colouring scheme which is: red for error messages (including fatal errors), blue for warning messages and green for information messages.
-colour=scheme
Colour the message output from the compiler according to the specified scheme. This is a comma-separated list of colour specifications, each consisting of a message category name (“error”, “warn” or “info”) followed by a colon and the foreground colour name, optionally followed by a plus sign and the background colour name. The colouring for unspecified categories will be the default.

Colours are: black, red, green, yellow, blue, magenta, cyan and white.

E.g. -colour=error:red+blue,warn:cyan,info:magenta+yellow
would be a rather garish colour scheme.

-compatible
Make external linkages compatible with other compilers where possible; on Windows this is Microsoft Fortran (32-bit mode) or Intel Fortran (64-bit mode), on MacOS and Linux this is g77, g95 and gfortran, and on other systems this is the operating system vendor's compiler. This affects the naming convention and procedure calling convention (for example, on Windows it causes use of the “STDCALL” calling convention that is commonly used for most DLLs, and the names are in upper case with no added trailing underscore). On Windows in 64-bit mode, -compatible is always in effect.
-convert=format
Set the default conversion mode for unformatted files to format. This format may be overridden by an explicit CONVERT= specifier in the OPEN statement, or by the environment variable FORT_CONVERT n (where n is the unit number). The value of format must be one of the following (not case-sensitive):

Format | Description
BIG_ENDIAN | synonym for BIG_IEEE
BIG_IEEE_DD | big-endian with IEEE floating-point, quad precision is double-double
BIG_IEEE | big-endian with IEEE floating-point, including quad precision
BIG_NATIVE | big-endian with native floating-point format
LITTLE_ENDIAN | synonym for LITTLE_IEEE
LITTLE_IEEE_DD | little-endian with IEEE floating-point, quad precision is double-double
LITTLE_IEEE | little-endian with IEEE floating-point, including quad precision
LITTLE_NATIVE | little-endian with native floating-point format
NATIVE | no conversion (the default)
-D name
Defines name to fpp as a preprocessor variable. This only affects files that are being preprocessed by fpp.
-d_lines
In fixed form only, accept lines beginning with “D” as normal Fortran statements, replacing the D with a space. Without this option, such lines are treated as comments.
-dcfuns
Enable recognition of non-standard double precision complex intrinsic functions. These act as specific versions of the standard generic intrinsics as follows:

Non-standard | Equivalent Standard Fortran Generic Intrinsic Function
CDABS(A) | ABS(A)
DCMPLX(X,Y) | CMPLX(X,Y,KIND=KIND(0d0))
DCONJG(Z) | CONJG(Z)
DIMAG(Z) | AIMAG(Z)
DREAL(Z) | REAL(Z) or DBLE(Z)
-double
Double the size of default INTEGER, LOGICAL, REAL and COMPLEX. Entities specified with explicit kind numbers or byte lengths are unaffected. If quadruple precision REAL is available, the size of DOUBLE PRECISION is also doubled.
-dryrun
Show but do not execute commands constructed by the compiler driver.
-dusty
Allows the compilation and execution of “legacy” software by downgrading the category of common errors found in such software from “Error” to “Warning” (which may then be suppressed entirely with the -w option). This option disables -C=calls, and also enables Hollerith i/o (see the -hollerith_io option).
-encoding=charset
Specifies that the encoding system of the Fortran source files is charset, which must be one of ISO_Latin_1, Shift_JIS or UTF_8. If this option is not specified, the default encoding is UTF-8 for Fortran source files that begin with a UTF-8 Byte Order Mark, and ISO Latin-1 (if the language setting is English) or Shift-JIS (if the language setting is Japanese) for other Fortran source files.
-english
Produce compiler messages in English (default).
-F
Preprocess only, do not compile. Each file that is preprocessed will produce an output file of the same name with the suffix replaced by .f, .f90 or .f95 according to the suffix of the input file. This option is equivalent to -otype=Fortran.
-f90_sign
Use the Fortran 77/90 version of the SIGN intrinsic instead of the Fortran 95 one (they differ in the treatment of negative zero).
-f95
Specify that the base language is Fortran 95. This only affects extension message generation (Fortran 2003 and 2008 features will be reported as extensions).
-f2003
Specify that the base language is Fortran 2003. This only affects extension message generation (Fortran 2008 features will be reported as extensions).
-f2008
Specify that the base language is Fortran 2008. This is the default.
-f2018
Specify that the base language is Fortran 2018. This implies the -recursive option.
-fixed
Interpret all Fortran source files according to fixed-form rules.
-float-store
(Gnu C based systems only) Do not store floating-point variables in registers on machines with floating-point registers wider than 64 bits. This can avoid problems with excess precision.
-fpp
Preprocess the source files using fpp even if the suffix would normally indicate an ordinary Fortran file.
-framework f
(MacOS only) Use framework f during linking.
-free
Interpret all Fortran source files according to free-form rules.
-g
Produce information for interactive debugging by the host system debugger.
-g90
Produce debugging information for dbx90, a Fortran 90 aware front-end to the host system debugger. This produces a debug information (.g90) file for each Fortran source file. This option must be specified for both compilation and linking.
-gc
Enables automatic garbage collection of the executable program. This option must be specified for both compilation and linking, and is unavailable on IBM z9 OpenEdition, MacOS, and Windows. It is incompatible with the -thread_safe and -mtrace options. For more details see the Automatic Garbage Collection section.
-gline
Compile code to produce a traceback when a runtime error message is generated. Only routines compiled with this option will appear in such a traceback. This option increases both executable file size and execution time. It is incompatible with the -thread_safe, -openmp and -coarray=cosmp options.

For example:

   Runtime Error: Invalid input for real editing
   Program terminated by I/O error on unit 5 (Input_Unit,Formatted,Sequential)
   main.f90, line 28: Error occurred in READ_DATA
   main.f90, line 57: Called by READ_COORDS
   main.f90, line 40: Called by INITIAL
   main.f90, line 13: Called by $main$
-help
Display a one-line summary of the options available for the current mode (=compiler, =callgraph, =depend, =epolish, =interfaces, =polish or =unifyprecision).
-hollerith_io
Enable Fortran-66 compatible input/output of character data stored in numeric variables using the A edit descriptor. This was superseded by the CHARACTER datatype in Fortran 77.
-I pathname
Add pathname to the list of directories which are to be searched for module information (.mod) files and INCLUDE files. The current working directory is always searched first, then any directories named in -I options, then the compiler's library directory (see the -Qpath option).
-i8
Set the size of default INTEGER and LOGICAL to 64 bits. This can be useful for switching between libraries that have 32-bit integer arguments (on one platform) and 64-bit integer arguments (on another platform), but which do not provide a named constant with the necessary KIND value.

This has no effect on default REAL and COMPLEX sizes, so the compiler is not standard-conforming in this mode.

-indirect file
Read the contents of file as additional arguments to the compiler driver. This option may also be given by “@file”; note in this case there is no space between the ‘@’ and the file name.

In an indirect file, arguments may be given on separate lines; on a single line, multiple arguments may be separated by blanks. A blank can be included in an option or file name by putting the whole option or file name in quotes ("); this is the only quoting mechanism. An indirect file may reference other indirect files.

-ieee=mode
Set the mode of IEEE arithmetic operation according to mode, which must be one of full, nonstd or stop.
full
enables all IEEE arithmetic facilities including non-stop arithmetic.
nonstd
Disables non-stop arithmetic, terminating execution on floating overflow, division by zero or invalid operand. If the hardware supports it, this also disables IEEE gradual underflow, producing zero instead of a denormalised number; this can improve performance on some systems.
stop
enables all IEEE arithmetic facilities except for non-stop arithmetic; execution will be terminated on floating overflow, division by zero or invalid operand.

The -ieee option must be specified when compiling the main program unit, and its effect is global. The default mode is -ieee=stop. For more details see the IEEE 754 Arithmetic Support section. This option is not available on IBM z9 Open Edition with hexadecimal floating point.

-info
Request output of information messages, both “Info” and “Remark” (the least important). The default is to suppress these messages.
-kind=option
Specify the kind numbering system to be used; option must be one of byte, sequential or unique.

For -kind=byte, the kind numbers for INTEGER, REAL and LOGICAL will match the number of bytes of storage (e.g., default REAL is 4 and DOUBLE PRECISION is 8). Note that COMPLEX kind numbers are the same as its REAL components, and thus half of the total byte length in the entity.

For -kind=sequential (the default), the kind numbers for all datatypes are numbered sequentially from 1, increasing with precision (e.g., default REAL is 1 and DOUBLE PRECISION is 2).

For -kind=unique, the kind numbers are unique across all data types, so that a kind number for one data type cannot be accidentally used for another data type (except that COMPLEX and REAL are still the same). These kind numbers are all greater than 100 so do not match byte sizes either.

This option does not affect the interpretation of byte-length specifiers (an extension to Fortran 77).

-l x
Link with library libx.a. The linker will search for this library in the directories specified by -Ldir options followed by the normal system directories (see the ld(1) command).
-L dir
Add dir to the list of directories for library files (see the ld(1) command).
-M
Produce module information files (.mod files) only. This option is equivalent to -otype=mod.
-max_internal_proc_instances=N
Set the maximum number of simultaneously active host instances of an internal procedure that is being passed as an actual argument, or assigned to a procedure pointer, to N. The default maximum is normally 30, and increased to 160 if either the -openmp or -thread_safe options are used.
-max_parameter_size=N
Set the maximum size of a PARAMETER to N MB (megabytes). N must be in the range 1 to 1048576 (1MB to 1TB); the default is 50 MB.
-maxcontin=N
Increase the limit on the number of continuation lines from 255 to N. This option will not decrease the limit below the standard number.
-mdir dir
Write any module information (.mod) files to directory dir instead of the current working directory.
-message_encoding=charset
Set the encoding scheme for compiler messages to charset, which must be one of ISO_Latin_1, Shift_JIS or UTF_8 (not case-sensitive). The -message_encoding=ISO_Latin_1 option is incompatible with the -nihongo option. The default message encoding is Shift_JIS on Windows and UTF_8 on other systems.
-mismatch
Downgrade consistency checking of procedure argument lists so that mismatches produce warning messages instead of error messages. This only affects calls to a routine which is not in the current file; calls to a routine in the file being compiled must still be correct. This option disables -C=calls.
-mismatch_all
Further downgrade consistency checking of procedure argument lists so that calls to routines in the same file which are incorrect will produce warnings instead of error messages. This option disables -C=calls.
-mtrace
Trace memory allocation and deallocation. This option is a synonym for -mtrace=on.
-mtrace=trace_opt_list
Trace memory allocation and deallocation according to the value of trace_opt_list, which must be a comma separated list of one or more of:
address | (display addresses),
all | (all options except for off),
line | (display file/line info if known),
off | (disable tracing output),
on | (enable tracing output),
paranoia | (protect memory allocator data structures against the user program),
size | (display size in bytes) or
verbose | (all options except for off and paranoia ).

This option should be specified during both compilation and linking, and is incompatible with the -gc option. For more details see the Memory Tracing section. The -mtrace=paranoia option is not available on IBM z9 Open Edition.

-nan
Initialise REAL and COMPLEX variables to IEEE Signalling NaN, causing a runtime crash if the values are used before being set. This affects local variables, module variables, and INTENT(OUT) dummy arguments only; it does not affect variables in COMMON or EQUIVALENCE. This option is not available on IBM z9 Open Edition with hexadecimal floating point.
-nihongo
Produce compiler messages in Japanese (if necessary, the encoding can be changed by the -message_encoding= option). This option is not available on IBM z9 Open Edition.
-no_underflow_warning
Suppress the warning message that normally appears if a floating-point underflow occurred during execution. This option is only effective if specified when compiling the main program.
-nocheck_modtime
Do not check for .mod files being out of date.
-nomod
Suppress module information (.mod) file production. Combining this with -M will produce no output (other than error and warning messages) at all, equivalent to -otype=none.
-noqueue
If no licence for the compiler is immediately available, exit with an error instead of queueing for it.
-num_images=N
Set the expected number of images the program will run with to N, which should be a number in the range 1 to 1000, ‘auto’, or ‘unknown’.

In Single Image mode (-coarray=single), the only affect is on analysis of constant cosubscripts: if N is numeric, and they evaluate to an image index greater than N, an error will be produced. The effect of -num_images=unknown (or -num_images=auto) is to suppress such analysis.

In CoSMP mode (-coarray=cosmp), the effect is to specify the default number of images at execution time; this may be overridden by the runtime environment variable NAGFORTRAN_NUM_IMAGES. The effect of -num_images=auto (or -num_images=unknown) is to set the default number of images to the number of hardware threads on the processor. This option takes effect when compiling the main program.

The default in -coarray=single mode is -num_images=1, and the default in -coarray=smp mode is -num_images=auto.

-o output
Name the output file output instead of the default. If an executable is being produced the default is a.out; otherwise it is file.o with the -c option, file.c with the -S option, and file.f, file.f90 or file.f95 with the -F option, where file is the base part of the source file (i.e. with the suffix removed).
-O
Normal optimisation, equivalent to -O2.
-O N
Set the optimisation level to N. The optimisation levels are:
-O0 | No optimisation. This is the default, and is recommended when debugging.
-O1 | Minimal quick optimisation.
-O2 | Normal optimisation.
-O3 | Further optimisation.
-O4 | Maximal optimisation.
-Oassumed
This is a synonym for -Oassumed=contig.
-Oassumed=shape
Optimises assumed-shape array dummy arguments according to the value of shape, which must be one of
always_contig
Optimised for contiguous actual arguments. If the actual argument is not contiguous a runtime error will occur (the compiler is not standard-conforming under this option).
contig
Optimised for contiguous actual arguments; if the actual argument is not contiguous (i.e. it is an array section) a contiguous local copy is made. This may speed up array section accessing if a sufficiently large number of array element or array operations is performed (i.e. if the cost of making the local copy is less than the overhead of discontiguous array accesses), but usually makes such accesses slower. Note that this option does not affect dummy arguments with the TARGET attribute; these are always accessed via the dope vector.
section
Optimised for low-moderate accesses to array section (discontiguous) actual arguments. This is the default.

Note that CHARACTER arrays are not affected by these options.

-Oblock=N
Specify the dimension of the blocks used for evaluating the MATMUL intrinsic. The default value (only for -O1 and above) is system and datatype dependent.
-Onopropagate
Disable the optimisation of constant propagation. This is the default for -O1 and lower.
-Onoteams
Generate coarray access code assuming that teams are not being used. This will produce incorrect results if executed while a CHANGE TEAM construct is active.
-Opropagate
Enable the optimisation of constant propagation. This is the default for -O2 and higher.
-Orounding
Specify that the program does not alter the default rounding mode. This enables the use of faster code for the ANINT intrinsic.
-Ounroll=N
Specify the depth to which simple loops and array operations should be unrolled. The default is no unrolling (i.e. a depth of 1) for -O0 and -O1, and a depth of 2 for -O and higher optimisation levels. It can be advantageous to disable the Fortran compiler's loop unrolling if the C compiler normally does a very good job itself — this can be accomplished with -Ounroll=1.
-Ounsafe
Perform possibly unsafe optimisations that may depend on the numerical stability of the program. On IBM z9 Open Edition this option, in conjunction with -O4, passes NOSTRICT to the C compiler.
-openmp
Enable OpenMP, producing extension messages for use of OpenMP features more recent than the currently fully-supported OpenMP version. In nagfor 7.1, this is equivalent to -openmp=3.1.
-openmp=version
Recognise OpenMP directives and link with the OpenMP support library. Produce extension messages for the use of OpenMP features more recent than OpenMP version, which must be equal to 3.0, 3.1, 4.0, 4.5, 5.0 or 5.1. For more details see the OpenMP Support section. This option is incompatible with the -coarray=smp option.
-otype=filetype
Specify the type of output file required to filetype, which must be one of

c | (C source file),
exe | (executable file),
fortran | (Fortran source file),
mod | (module information file),
none | (no output file),
obj | (object file).

The -c, -F and -M options are equivalent to -otype=obj, -otype=Fortran and -otype=mod respectively.

-pg
Compile code to generate profiling information which is written at run-time to an implementation-dependent file (usually gmon.out or mon.out). An execution profile may then be generated using gprof. This option must be specified for compilation and linking and may be unavailable on some implementations.
-pic
Produce position-independent code (small model), for use in a shared library. If the shared library is too big for the small model, use -PIC. This option is not available on IBM z9 Open Edition.
-PIC
Produce position-independent code (large model), for use in a shared library. This option is not available on IBM z9 Open Edition.
-quiet
Suppress the compiler banner and the summary line, so that only diagnostic messages will appear.
-Qpath pathname
Change the compiler library pathname from its default location to pathname. (The default location on Unix is usually ‘/usr/local/lib/NAG_Fortran’ or ‘/opt/NAG_Fortran/lib’) This option is unnecessary on Windows as the installed location is automatically detected.
-r8
Double the size of default REAL and COMPLEX, and on machines for which quadruple-precision floating-point arithmetic is available, double the size of DOUBLE PRECISION (and the non-standard DOUBLE COMPLEX). REAL or COMPLEX specified with explicit KIND numbers or byte lengths are unaffected — but since the KIND intrinsic returns the correct values, COMPLEX(KIND(0d0)) on a machine with quad-precision floating-point will correctly select quad-precision COMPLEX.

This has no effect on INTEGER sizes, and so the compiler is not standard-conforming in this mode.

Note: This option has been superseded by the -double option which doubles the size of all numeric data types.

-recursive
Specifies that procedures are RECURSIVE by default. This option is implied by the -f2018 option.
-round_hreal
Round all half precision operations to half precision. Without this option, half precision expressions are evaluated in single precision and only rounded to half precision when being assigned to a variable or passed as an actual argument to a non-intrinsic or non-mathematical procedure.

This option affects compile-time evaluation as well as runtime evaluation.

-s
Strip symbol table information from the executable file. This option is only effective if specified during the link phase.
-S
Produce assembler (actually C source code). The resulting .c file should be compiled with the NAG Fortran compiler, not with the C compiler directly. This option is equivalent to -otype=c.
-save
This is equivalent to inserting the SAVE statement in all subprograms which are not pure, not declared RECURSIVE, and not RECURSIVE by default (see the -recursive option). It thus causes all non-automatic local variables in such subprograms to be statically allocated. It has no effect on variables in BLOCK constructs.
-strict95
Produce obsolescence warning messages for use of ‘CHARACTER*’ syntax. This message is not produced by default since many programs contain this syntax.
-target=machine
Specify the machine for which code should be generated and optimised.
  • For x86-32 (x86-compatible 32-bit mode compilation on Linux and Windows), machine may be one of
    i486, i586, i686, pentium2, pentium3, pentium4, prescott | the specified Intel processor,
    k6, k6-2, k6-3, k6-4, athlon, athlon-4, athlon-xp, athlon-mp | the specified AMD processor,
    pentium | (equivalent to i586) or
    pentiumpro | (equivalent to i686).

    The default is to compile for pentium4 on Linux, and prescott on Windows.

  • For x86-64 (x86-compatible 64-bit mode compilation on Linux, MacOS and Windows), machine may be athlon64, nocona, or core2.
  • For Sun/SPARC, machine may be one of
    V7
    SPARCstation 1 et al,
    V8
    SPARCstation 2 et al,
    super
    SuperSPARC,
    ultra
    UltraSPARC or
    native
    the current machine.

    The default is to compile for SPARC V7.

    Note that programs compiled for later versions of the architecture may not run, or may run much more slowly, on an earlier machine. The -target=native option is not available with gcc.

  • For HP9000/700, machine may be one of
    2.0
    the specified revision of the PA-RISC architecture (default) or
    native
    the current machine.
-tempdir directory
Set the directory used for the compiler's temporary files to directory. The default is to use the directory named by the TMPDIR environment variable, or if that is not set, /tmp on Unix-like systems and the Windows temporary folder on Windows.
-thread_safe
Compile code for safe execution in a multi-threaded environment. This must be specified when compiling and also during the link phase. It is incompatible with the -gc and -gline options.
-time
Report execution times for the various compilation phases.
-u
Specify that IMPLICIT NONE is in effect by default, unless overridden by explicit IMPLICIT statements.
-u=sharing
Specify default sharing of NONE in OpenMP PARALLEL and TASK constructs (including in combined constructs such as PARALLELDO). This has the same effect as the DEFAULT(NONE) clause, unless overridden by an explicit DEFAULT(...) directive.
-unsharedrts
Bind with the unshared (static) version of the Fortran runtime system; this allows a dynamically linked executable to be run on systems where the NAG Fortran Compiler is not installed. This option is only effective if specified during the link phase.
-v
Verbose. Print the name of each file as it is compiled.
-V
Print version information about the compiler.
-w
Suppress all warning messages. This option is a synonym for -w=all.
-w=class
Suppress the warning messages specified by class, which must be one of all, alloctr, obs, ques, uda, uei, uep, uip, ulv, unreffed, unused, uparam, usf, usy, x77 or x95.
-w=all
suppresses all warning messages;
-w=alloctr
suppresses warning messages about the use of allocatable components, dummy arguments and functions;
-w=note
Suppress informational Notes;
-w=obs
suppresses warning messages about the use of obsolescent features;
-w=ques
suppresses warning messages about questionable usage;
-w=uda
suppresses warning messages about unused dummy arguments;
-w=uei
suppresses warning messages about unused explicit imports;
-w=uep
suppresses warning messages about unused external procedures;
-w=uip
suppresses warning messages about unused intrinsic procedures;
-w=ulv
suppresses warning messages about unused local variables;
-w=unreffed
suppresses warning messages about variables set but never referenced;
-w=unused
suppresses warning messages about unused entities — this is equivalent to ‘-w=uda -w=uei -w=uep -w=uip -w=ulv -w=uparam -w=usf -w=usy’;
-w=uparam
suppresses warning messages about unused PARAMETERs;
-w=usf
suppresses warning messages about unused statement functions;
-w=usy
suppresses warning messages about unused symbols;
-w=x77
suppresses extension warnings for obsolete but common extensions to Fortran 77 — these are TAB format, byte-length specifiers, Hollerith constants and D lines;
-w=x95
suppresses extension warnings for extensions to modern Fortran (not just Fortran 95) that are not part of any Fortran standard.
-W options
The -W option can be used to specify the path to use for a compilation component or to pass an option directly to such a component. The possible combinations are:
-W0=path
Specify the path used for the Fortran Compiler front-end. Note that this does not affect the library directory; the -Qpath option should be used to specify that.
-Wc=path
Specify the path to use for invoking the C compiler; this is used both for the final stage of compilation and for linking.
-Wc,option
Pass option directly to the host C compiler when compiling (producing the .o file). Multiple options may be specified in a single -Wc, option by separating them with commas.
-Wl=path
Specify the path to use for invoking the linker (producing the executable).
-Wl,option
Pass option directly to the host C compiler when linking (producing the executable). Multiple options may be specified in a single -Wl, option by separating them with commas. A comma may be included in an option by repeating it, e.g. -Wl,-filelist=file1,,file2,,file3 becomes the linker option -filelist=file1,file2,file3.
-Wp=path
Specify the path to use for invoking the fpp preprocessor.
-Wp,option
Pass option directly to fpp when preprocessing.
-Warn=class
Produce additional warning messages specified by class, which must be one of:

allocation
warn if an intrinsic assignment might cause allocation of the variable (or a subcomponent thereof) being assigned to;
constant_coindexing
warn if an image selector has constant cosubscripts;
reallocation
warn if an intrinsic assignment might cause reallocation of an already-allocated variable (or a subcomponent thereof) being assigned to;
subnormal
warn if an intrinsic operation or function with normal operands produces a subnormal result (reduced precision, less than TINY(...)).

Reallocation only occurs when the shape of an array, the value of a deferred type parameter, or the dynamic type (if polymorphic), differs between the variable (or subcomponent) and the expression (or the corresponding subcomponent). Allocation can occur also when the variable (or subcomponent) is not allocated prior to execution of the assignment (except for broadcast assignment). Note that -Warn=allocation thus subsumes -Warn=reallocation.

-wmismatch=proc-name-list
Specify a list of external procedures for which to suppress argument data type and arrayness consistency checking. The procedure names should be separated by commas, e.g. -wmismatch=p_one,p2. Unlike the -mismatch option, this only affects data type and arrayness checking, and no warning messages are produced.
-xlicinfo
Report on the availability of licences for the compiler instead of compiling anything. Also report the exact version of Kusari being used.
-xs
(Sun/SPARC option only) Store the symbol tables in the executable (otherwise debugging is only possible if the object files are kept).


NAG Fortran Compiler, Release 7.1: Files

 Navigation: Previous Up Next

2.5 Files

file.a
Library of object files.
file.c
C source file.
file.f
Fortran source file in fixed format (obsolete).
file.f90
Fortran source file in free format.
file.f95
Fortran source file in free format.
file.ff
Preprocessor source file for fixed-form Fortran (obsolete).
file.F
(Unix) Preprocessor source file for fixed-form Fortran (obsolete).
file.ff90
Preprocessor source file for free-form Fortran.
file.F90
(Unix) Preprocessor source file for free-form Fortran.
file.ff95
Preprocessor source file for free-form Fortran.
file.F95
(Unix) Preprocessor source file for free-form Fortran.
name.mod
Compiled module information file; name is the name of the module in lower case.
file.o
Object file
library/f90_iostat.f90
Source code for the f90_iostat module.
library/f90_kind.f90
Source code for the f90_kind module.
library/f90_stat.f90
Source code for the f90_stat module.
library/f90_util.f90
A sample Fortran 90 program that displays implementation-specific information
library/iso_fortran_env.f90
Source code for the iso_fortran_env module.
library/nagfmcheck.f90
Source code for the nagfmcheck program, see the Memory Tracing section.
/opt/NAG_Fortran/lib | Default NAG Fortran Compiler library directory on Sun Solaris (see -Qpath); referred to as library hereafter.
/usr/local/lib/NAG_Fortran | Default NAG Fortran Compiler library directory on other Unix-based operating systems.
C:\Program Files\NAG\EFBuilder 7.1\nagfor\lib | Default NAG Fortran Compiler library directory on 32-bit Windows.
C:\Program Files (x86)\NAG\EFBuilder 7.1\nagfor\lib | Default NAG Fortran Compiler library directory on 64-bit Windows.


NAG Fortran Compiler, Release 7.1: Compilation Messages

 Navigation: Previous Up Next

2.6 Compilation Messages

The messages produced by the NAG Fortran Compiler itself during compilation are intended to be self-explanatory. The linker, or more rarely the host C compiler, may produce occasional messages.

Messages produced by the compiler are classified by severity level; these levels are:

Remark | a comment about the source code (this is the least important class of informational message).
Info | informational message, noting an aspect of the source code in which the user may be interested.
Note | an informational message of greater import than “Info”.
Warning | the source code appears likely to be in error.
Questionable | some questionable usage has been found in the source code which may indicate a programming error. This has the same severity as “warning”.
Extension | some non-standard-conforming source code has been detected but has successfully been compiled as an extension to the language. This has the same severity as “warning”.
Obsolescent | some archaic source code has been detected which although standard-conforming was classified as obsolescent by the Fortran standard (selected according to the -f95, -f2003 and -f2008 options). This has the same severity as “warning”.
Deleted feature used | a feature that was present in an older Fortran standard but deleted from the Fortran standard selected by a -fN option was used. This has the same severity as “warning”.
Error | the source code does not conform to the Fortran standard or does not make sense. Compilation continues after recovery.
Fatal | a serious error in the user's program from which the compiler cannot recover, the compilation is immediately terminated.
Panic | an internal inconsistency is found by one of the compiler's self-checks; this is a bug in the compiler itself and NAG should be notified.


NAG Fortran Compiler, Release 7.1: Compiler Limits

 Navigation: Previous Up Next

2.7 Compiler Limits

Item | Limit
Maximum INCLUDE file nesting | 20
Maximum number of INCLUDE file references per compilation | 2047
Maximum DATA-implied-DO loop nesting | 99
Maximum array-constructor-implied-DO loop nesting | 99
Maximum number of dummy arguments | 32767
Maximum number of arguments to MIN and MAX | 100
Maximum character length (except as below) | 2147483647
Maximum character length (64-bit Windows and -abi=64c Linux) | 1099511627775 (240-1)
Maximum array size (32-bit systems) | 2147483647 bytes
Maximum array size (64-bit systems) | 1 TiB
Maximum unit number | 2147483647
Maximum input/output record length | 2147483647 bytes


NAG Fortran Compiler, Release 7.1: Input/Output Information

 Navigation: Previous Up Next

2.8 Input/Output Information

Item | Value
Standard error (stderr) unit number | 0
Standard input (stdin) unit number | 5
Standard output (stdout) unit number | 6
Default maximum record length for formatted output | 1024 characters
Default maximum record length for unformatted output | 2147483647 bytes

The default directory used for files opened with STATUS='SCRATCH' is ‘/tmp’ on Unix and the Windows temporary directory on Windows. This default may be overridden with the TMPDIR environment variable.


NAG Fortran Compiler, Release 7.1: OpenMP Support

 Navigation: Previous Up Next

2.9 OpenMP Support

OpenMP 3.1 is fully supported. Some features from more recent OpenMP specifications are also supported; check the Release Notes for details.

When using the IEEE arithmetic support modules, the IEEE modes (rounding, halting and underflow) are propagated into spawned OpenMP threads at the beginning of a PARALLEL construct, and any IEEE flag that are set by an OpenMP thread is passed back to the parent thread at the end of the PARALLEL construct.

The following table lists the OpenMP environment variables with their default values and, if applicable, their limits.

Environment Variable | Default | Limits
OMP_NUM_THREADS | number of cores | 1-32768
OMP_DYNAMIC | False | true or false
OMP_NESTED | False | true or false
OMP_STACKSIZE | 0 | <1GB (32-bit) or 16GB (64-bit)
OMP_WAIT_POLICY | None | active or passive
OMP_MAX_ACTIVE_LEVELS | 1 | 1-64
OMP_THREAD_LIMIT | 32768 | 1-32768
OMP_CANCELLATION | False | true or false

Note that although the NAG runtime supports up to 32768 threads, operating system limits may prevent usage of so many.

OpenMP is not compatible with the -coarray=cosmp and -gline options.


NAG Fortran Compiler, Release 7.1: Automatic File Preconnection

 Navigation: Previous Up Next

2.10 Automatic File Preconnection

All logical unit numbers are automatically preconnected to specific files. These files need not exist and will only be opened or created if they are accessed with READ or WRITE without an explicit OPEN. By default the specific filename for unit n is fort.n; however if the environment variable FORT nn exists its value is used as the filename. Note that there are two digits in this variable name, e.g. the variable controlling unit 1 is FORT01 whereas the default filename is ‘fort.1’ (unless the prefix has been changed, see the description of module F90_PRECONN_IO).

A file preconnected in this manner is opened with ACCESS='SEQUENTIAL'. If the initial READ or WRITE is an unformatted i/o statement, it is opened with FORM='UNFORMATTED' otherwise it is opened with FORM='FORMATTED'. By default a formatted connection is opened with BLANK='NULL' and POSITION='REWIND' (see module F90_PRECONN_IO).

Automatic preconnection applies only to the initial use of a logical unit; once CLOSEd the unit will not be reconnected automatically but must be explicitly OPENed.

Note that this facility means that it is possible for a READ or WRITE statement with an IOSTAT= clause to receive an i/o error code associated with the implicit OPEN.


NAG Fortran Compiler, Release 7.1: IEEE 754 Arithmetic Support

 Navigation: Previous Up Next

2.11 IEEE 754 Arithmetic Support

If no floating-point option is specified, any floating divide-by-zero, overflow or invalid operand exception will cause the execution of the program to be terminated (with an informative message and usually a core dump). Occurrence of floating underflow may be reported on normal termination of the program. On hardware supporting IEEE 754 standard arithmetic gradual underflow with denormalised numbers will be enabled. Note that this mode of operation is the only one available on hardware which does not support IEEE 754.

If the -ieee=full option is specified, non-stop arithmetic is enabled; thus REAL variables may take on the values +Infinity, −Infinity and NaN (Not-a-Number). If any of the floating exceptions listed above are detected by the hardware during execution, this fact will be reported on normal termination. The -ieee=full option must be specified when compiling the main program and has global effect; that is, it affects the entire executable program.

If the -ieee=nonstd option is specified, floating-point exceptions are handled in the default manner (i.e. execution is terminated). However, gradual underflow is not enabled, so results which would have produced a denormalised number produce zero instead. This option can only be used on hardware for which this mode of operation is faster. Like -ieee=full, the -ieee=nonstd option must be specified when compiling the main program and has global effect.


NAG Fortran Compiler, Release 7.1: Half precision floating-point

 Navigation: Previous Up Next

2.12 Half precision floating-point

Half precision (16-bit) floating-point is supported for values and variables of type REAL and COMPLEX. This floating-point kind conforms to the IEEE arithmetic standard (ISO/IEC/IEEE 60559:2011).

The intrinsic function SELECTED_REAL_KIND(3) and intrinsic module function IEEE_SELECTED_REAL_KIND(3) return the kind value for half precision. In -kind=byte mode, the value will be two; in -kind=sequential mode, it will be 16 (this unusual value was chosen to maintain upward compatibility of kind numbers).

The largest finite half-precision value is 65504.0, the smallest normal half-precision value is 0.00006103515625, and the smallest subnormal value is 0.000000059604644775390625.

Scalar half-precision operations are evaluated in single precision, and only rounded to half precision when assigned to a variable or passed as an actual argument to a non-intrinsic or non-mathematical procedure (e.g. SQRT is mathematical, but NEAREST is not). This can be controlled by the -round_hreal option; if used, all half-precision operations will be rounded to half precision, both at compile time and run time.

Because of all the conversions needed, half precision is slower than single precision; its sole benefit is halving the memory and file storage requirements.


NAG Fortran Compiler, Release 7.1: Random Number Algorithm

 Navigation: Previous Up Next

2.13 Random Number Algorithm

The random number generator supplied as the intrinsic subroutine RANDOM_NUMBER is the “Mersenne Twister”.

Note that this generator has a large state (630 32-bit integers) and an extremely long period (approx 106000), and therefore it is strongly recommended that the RANDOM_SEED routine only be used with a PUT argument that is the value returned by a previous call with GET; i.e., only to repeat a previous sequence. This is because if a user-specified seed has low entropy (likely since there are 630 values to be supplied), it is highly likely to set the generator to an apparently-low-entropy part of the sequence.

If you do want to provide your own seed (and thus entropy), you should store your values in the initial elements of the seed array and set all the remaining elements to zero — trailing zero elements will be ignored and not used to initialise the generator. Note that the seed is a random bitstream, and is therefore expected to have approximately half of its bits nonzero (thus providing many small integer values will likely result in a low-entropy part of the Mersenne Twister sequence being reached).


NAG Fortran Compiler, Release 7.1: Automatic Garbage Collection

 Navigation: Previous Up Next

2.14 Automatic Garbage Collection

The -gc option enables use of the runtime garbage collector. It is necessary to use this option during the link phase for it to have effect; specifying it additionally during the compilation phase can result in improved performance.

The supplied Technical Information note (TECHINFO) lists whether garbage collection is available for your system. If it is available, there will be a file ‘gc.o’ in the compiler's library directory.

The collector used is based on version 5.3 of the publicly available general purpose garbage collecting storage allocator of Hans-J Boehm, Alan J Demers and Xerox Corporation, described in “Garbage Collection in an Uncooperative Environment” (H Boehm and M Weiser, Software Practice and Experience, September 1988, pp 807-820).

The copyright notice attached to their latest version is as follows:

Copyright 1988, 1989 Hans-J. Boehm, Alan J. Demers
Copyright (c) 1991-1995 by Xerox Corporation.  All rights reserved.
Copyright 1996-1999 by Silicon Graphics.  All rights reserved.
Copyright 1999 by Hewlett-Packard Company.  All rights reserved.

THIS MATERIAL IS PROVIDED AS IS, WITH ABSOLUTELY NO WARRANTY EXPRESSED
OR IMPLIED.  ANY USE IS AT YOUR OWN RISK.

Permission is hereby granted to use or copy this program
for any purpose,  provided the above notices are retained on all copies.
Permission to modify the code and to distribute modified code is granted,
provided the above notices are retained, and a notice that the code was
modified is included with the above copyright notice.

Note that the “NO WARRANTY” disclaimer refers to the original copyright holders Boehm, Demers, Xerox Corporation, Silicon Graphics and Hewlett-Packard Company. The modified collector distributed in binary form with the NAG Fortran Compiler is subject to the same warranty and conditions as the rest of the NAG Fortran compilation system.

The module F90_GC is provided; it contains functions and variables that can control the behaviour of the garbage collector.


NAG Fortran Compiler, Release 7.1: Memory Tracing

 Navigation: Previous Up Next

2.15 Memory Tracing

Tracing of memory allocation and deallocation is provided by the -mtrace option. Control is provided over whether the address, size, and line number of each allocation is displayed, or the tracing output can be suppressed entirely. A “paranoia” mode is provided where the memory allocator protects its data structures against inadvertent modification by the user program.

Runtime environment variables may be used to override the tracing options a program was built with, and to specify where to write the tracing output. These are only operative if the program was built with some tracing option; -mtrace=off will build a program with the tracing-capable memory allocator.

If -mtrace=off is not specified, use of any -mtrace option will implicitly do a -mtrace=on.

Basic tracing produces a message to the memory tracing file (normally standard error) for each allocation and deallocation, including those for automatic variables, i/o buffers and compiler-generated temporaries. Each allocation is numbered sequentially; the first three items are the i/o buffers for units 0, 5 and 6 (standard error, standard input and standard output).

All -mtrace= suboptions may be overridden at run time by the NAGFORTRAN_MTRACE_OPTIONS environment variable, which should be set to the required trace_opt_list (e.g. ‘on,size’). The memory tracing file may be specified at run time by the NAGFORTRAN_MTRACE_FILE environment variable.

The NAGFORTRAN_MTRACE_OPTIONS variable can also contain an option to limit the total amount of memory that may be allocated. The ‘limit=N’ option limits the maximum memory allocated to N MiB (mebibytes), but only if the program was built with a tracing option (minimally, -mtrace=off). Exceeding the memory limit will result in a normal “out of memory” condition, which if it occurs in an ALLOCATE statement, can be captured by a STAT= clause. Note that the memory limit applies to the overall memory usage including automatic variables and compiler-generated array temporaries.

The -mtrace option must be specified when linking, and is incompatible with -gc. Additionally, line number information is only available for those files compiled with -mtrace=line.

The nagfmcheck program can be used to check the output from the -mtrace option. It is designed to be used as a filter. Any lines that do not look like memory tracing output are ignored. It reports to standard output any errors it detects such as deallocating something twice, deallocating something that was never allocated, or deallocating something with a size different from that with which it was allocated. It also reports any apparent memory leaks, though this is less useful if the program terminated prematurely.


NAG Fortran Compiler, Release 7.1: Undefined Variable Detection

 Navigation: Previous Up Next

2.16 Undefined Variable Detection

Use of undefined variables can be detected with the -C=undefined option. Program units compiled with this option use a different ABI, which means that they are incompatible with program units compiled without this option, and not interoperable with C; thus the whole program must be Fortran code and compiled the same way. For this reason, -C=undefined is not part of -C or -C=all.

Currently, there are a number of other limitations on the use of -C=undefined.

  1. It is incompatible with pointers in an initialised COMMON.
  2. All intrinsic modules are available, but the ISO_C_BINDING module can only be used with all-Fortran programs as the option makes changes to the ABI.
  3. Internal READ from a CHARACTER array requires the entire specified array subobject to be “defined”, even those elements corresponding to records not actually read.
  4. Internal WRITE to a CHARACTER array is considered to define the entire specified array subobject, even those elements corresponding to records not actually written.
  5. Certain intrinsic functions require the entirety of their arguments to be defined, even if some portions are not actually required for the value of the function. For example, the PAD argument to RESHAPE when no padding is actually required, and elements of the ARRAY argument to PACK that correspond to false elements of the MASK.
  6. It is incompatible with the use of coarrays.
  7. It cannot be used on types with length type parameters.
  8. It cannot be used when CLASS(*) variables are allocated using the MOLD= specifier.
  9. It cannot be used with ALLOCATE when the SOURCE= expression is a CLASS(*) dummy and the actual argument is a constant.


NAG Fortran Compiler, Release 7.1: Data Types

 Navigation: Previous Up Next

2.17 Data Types

The table below lists the intrinsic data types provided by the NAG Fortran Compiler together with their kind numbers. There are three possible schemes for the intrinsic kind type parameters: the default mode of operation (which may be specified explicitly by the -kind=sequential option), the “byte” numbering scheme (specified by the -kind=byte option) and the “unique” numbering scheme (specified by the -kind=unique).

Type | KIND Number | KIND Number | KIND Number | Name | Description
Name | (sequential) | (byte) | (unique) |  |
REAL | 1 | 4 | 301 | REAL32* | Single precision floating-point
REAL | 2 | 8 | 302 | REAL64* | Double precision floating-point
REAL | 3 | 16 | 303 | REAL128* | Quad precision floating-point
REAL | 16 | 2 | 304 | REAL16* | Half precision floating-point
COMPLEX | 1 | 4 | 301 | REAL32* | Single precision complex
COMPLEX | 2 | 8 | 302 | REAL64* | Double precision complex
COMPLEX | 3 | 16 | 303 | REAL128* | Quadruple precision complex
COMPLEX | 16 | 2 | 304 | REAL16* | Half precision complex
LOGICAL | 1 | 1 | 201 | BYTE | Single byte logical
LOGICAL | 2 | 2 | 202 | TWOBYTE | Double byte logical
LOGICAL | 3 | 4 | 203 | WORD | Default logical
LOGICAL | 4 | 8 | 204 | LOGICAL64 | Eight byte logical
INTEGER | 1 | 1 | 101 | INT8* | 8-bit integer
INTEGER | 2 | 2 | 102 | INT16* | 16-bit integer
INTEGER | 3 | 4 | 103 | INT32* | 32-bit (default) integer
INTEGER | 4 | 8 | 104 | INT64* | 64-bit integer
CHARACTER | 1 | 1 | 646 | ASCII | ASCII or ISO 8859-1 character
CHARACTER | 2 | 2 | 213 | JIS | JIS X 0213 character
CHARACTER | 3 | 3 | 5323 | UCS2 | Unicode (UCS-2) character
CHARACTER | 4 | 4 | 10646 | UCS4 | ISO 10646 (UCS-4) character

The Name column of the table indicates the name provided by the intrinsic module F90_KIND; the ones marked * are also provided by the standard intrinsic module ISO_FORTRAN_ENV. Using these names avoids the portability problems that arise if the kind numbers are hard-coded.

Note that on all machines except Sun Solaris with the SunPro C compiler, quadruple precision is actually “double double” precision; this provides nearly twice the precision of Double precision but with a reduced exponent range.


NAG Fortran Compiler, Release 7.1: Modules

 Navigation: Previous Up Next

2.18 Modules

To use a module it must be an intrinsic module, previously compiled, or defined in the file prior to its use. When separately compiling a module the -c option should be specified.

Compiling a module creates a ‘.mod’ file and a ‘.o’ file. The ‘.mod’ file is used by the compiler at compile time to provide information about module contents, the ‘.o’ file (if generated) contains the code of any module procedures and must be specified when creating an executable file.

Note that the name of the ‘.mod’ file will be the name of the module, the ‘.o’ file will be named after the original source file.

When a previously compiled module is USEd the NAG Fortran Compiler attempts to find its source file and, if that is successful, checks the modification times producing a warning message if the ‘.mod’ file is out of date.


NAG Fortran Compiler, Release 7.1: Runtime Environment Variables

 Navigation: Previous Up Next

2.19 Runtime Environment Variables

The following variables control the runtime environment for programs compiled with the NAG Fortran Compiler.

NAGFORTRAN_MTRACE_FILE
Programs compiled using any -mtrace= option will write the memory trace to this file. The default is standard error.
NAGFORTRAN_MTRACE_OPTIONS
Changes the memory tracing options for programs compiled using any -mtrace= option.
NAGFORTRAN_NUM_IMAGES
Sets the number of images with which to execute a program in Co-SMP mode (it has no effect if the main program was compiled with -coarray=single). If the value of the variable is not an integer value, or is less than one or greater than 1000, it is ignored. In the absence of this variable, the number of images for a Co-SMP mode program is taken from the -num_images= option, or from the number of hardware threads.
NAGFORTRAN_RUNTIME_ERROR_FILE
Runtime error messages will be written to this file. The default is standard error.
NAGFORTRAN_RUNTIME_LANGUAGE
Controls the language used for runtime error messages. This may be ‘English’ or ‘Japanese’ (not case-sensitive); the default is English.
NAGFORTRAN_RUNTIME_OPTIONS
Controls runtime optional behaviour excluding memory tracing. This is a comma-separated list of options from the following list.

Option | Effect
autoskip_namelist | Enables auto-skipping namelist input.
blank_common_size=N | Sets the default size of blank COMMON blocks when
executing in Co-SMP mode.
log_autoskip_namelist | Enables auto-skipping namelist input, with logging.
show_dangling | Enables tracing of dangling pointers; this only
affects code compiled with -C=dangling.
suppress_underflow_warning | Do not produce the usual warning on program termination
when the floating-point underflow flag is set.
underflow_warning | Do produce the usual warning on program termination
when the floating-point underflow flag is set.

The autoskip_namelist option enables autoskipping namelist input. In this mode, when the name after the ampersand in the input record does not match the namelist group name in the READ statement, instead of raising an i/o error condition it skips records until it finds one that begins with an ampersand and the correct name.

The blank_common_size=N option sets the default size of blank COMMON blocks to N bytes when executing in Co-SMP mode with multiple images; it has no effect otherwise. If not specified, the default size is one mebibyte (1048576 bytes). This option is only needed if blank COMMON blocks in different program units have different sizes, and the largest one is not encountered first.

The log_autoskip_namelist option enables autoskipping namelist input (as above), with logging. In this mode, when an autoskip occurs, the location of the READ statement and the action being taken are logged to standard error, for example:

       [example.f90, line 5: Looking for namelist group NAME, skipping WRONG]

The show_dangling option causes messages to be produced on the runtime error file when a dangling pointer is created, reassociated with something else, nullified, or ceases to exist. For example,

[a.f90, line 20: Dangling pointer P detected (number 1), associated at b.f90, line 18]
[c.f90, line 7: Dangling pointer P (number 1) has been reassociated]
[c.f90, line 9: Dangling pointer Q (number 2) has been nullified]
[file.f90, line 21: Dangling pointer R (number 3) no longer exists]
The dangling pointer number is incremented every time a dangling pointer is detected. If an array with dangling pointer components ceases to exist, a message will be produced for each dangling pointer component of each element; however, the element subscripts will not be shown, instead ‘(...)’ will be produced to indicate that it is an array element, e.g.
[file.f90, line 44: Dangling pointer X(...)%A (number 8) no longer exists]

The suppress_underflow_warning runtime option has the same effect as the -no_underflow_warning compilation option; that is, it suppresses the usual warning message on program termination when the floating-point underflow flag is set.

The underflow_warning runtime option requests that if the floating-point underflow flag is set on program termination, a warning message should be produced. This is the default behaviour, but the runtime option will override the -no_underflow_warning compilation option.

TMPDIR
Controls the directory used for scratch files (the default is system-dependent).


NAG Fortran Compiler, Release 7.1: Debugging

 Navigation: Previous Up Next

2.20 Debugging

On Windows debugging is built-in to the Fortran Builder. For operating systems other than Windows a Modern Fortran-aware debugger might be available as dbx90; see TECHINFO.txt for details.

In general, host system debuggers, such as dbx or gdb, may be used successfully on Fortran code as the names of the original source files, plus line numbers, are passed through to the intermediate C files. In using such debuggers it should be noted that most local variables have an underscore appended to their names. It may be useful to look at the intermediate C code when debugging; this is produced by the -S option.


NAG Fortran Compiler, Release 7.1: Producing a Call Graph

 Navigation: Previous Up Next

2.21 Producing a Call Graph

The call graph generator takes a set of Fortran source files and produces a call graph with optional index and called-by tables. C files and fpp-processed files are not handled.

The call graph generator understands the following compiler options with the same meaning: -132, -dcfuns, -double, -dryrun, -dusty, -encoding, -english, -f2003, -f2008, -f95, -fixed, -free, -help, -I, -i8, -indirect, -info, -kind, -max_parameter_size, -maxcontin, -mismatch, -mismatch_all, -nihongo, -nocheck_modtime, -nomod, -noqueue, -o, -openmp, -Qpath, -r8, -strict95, -thread_safe, -u, -u=sharing, -v, -V, -w and -xlicinfo.

The “@filename” syntax may also be used, with the same effect as the “-indirect filename” option.

The call graph is written to the file specified by the -o option, or to standard output if no -o option is specified.

The following additional options control the output produced.

-calledby
Produce a “called-by” table showing, for each routine, the routines that call it directly or indirectly. This is produced at the end of the output.
-indent=N
Indent by N for each level in the graph, up to the maximum. The default is -indent=4.
-indent_max=N
The maximum indentation is N. The default is -indent_max=70.
-index
Produce an alphabetic index listing, for each routine, the line of the call graph where the routine first appears. This follows the call graph itself and precedes the called-by table (when the -calledby option is used).
-show_entry
Show ENTRY point names in the call graph; without this option, calls to an ENTRY point are shown as calls to the containing subprogram.
-show_generic
If a call is via a generic identifier, show the generic identifier in the call graph.
-show_host
Show the host scope names for calls to internal and module procedures.
-show_pclass
Show the class of each procedure (e.g. ‘module’, ‘internal’, ...).
-show_rename
If a called procedure was renamed on a USE statement, show the renaming.


NAG Fortran Compiler, Release 7.1: Dependency Analysis

 Navigation: Previous Up Next

2.22 Dependency Analysis

The dependency analyser takes a set of Fortran source files and produces dependency information in the form specified. C files and fpp-processed files are not handled.

The dependency analyser understands the following compiler options with the same meaning: -132, -dryrun, -english, -fixed, -free, -help, -I, -indirect, -maxcontin, -nihongo, -o, -Qpath, -tempdir, -v and -V. The “@filename” syntax may also be used with the same effect as the “-indirect filename” option.

The following additional options control the operation of the dependency analyser:

-otype=type
This option controls the output form, type must be one of:

blist | (the filenames as an ordered build list),
dfile | (the dependencies in Makefile format, written to separate file.d files),
info | (the dependencies as English descriptions) or
make | (the dependencies in Makefile format).

The default is -otype=info. If -otype=dfile is specified, no -o option is permitted; otherwise, the result is written to the file specified by the -o option or to standard output if no -o option is specified.

-paths=pathtype
Specifes the form to use for dependency paths; pathtype must be either absolute or relative. With -paths=absolute, paths for INCLUDE files that are relative specifications will be prefixed by the current working directory.


NAG Fortran Compiler, Release 7.1: Generating Interfaces

 Navigation: Previous Up Next

2.23 Generating Interfaces

The interface generator takes a set of Fortran source files and produces interfaces for the procedures therein. The output is either a module (in a new source file), or an INCLUDE file.

The interfaces are written either to the file specified by the -o option, or if module output is being produced to the file with the same name as the module and extension ‘.f90’, or otherwise (an INCLUDE file is being produced) to ‘interfaces.inc’. In each case the interfaces are all within a single INTERFACE block.

The interface generator understands the following compiler options with the same meaning: -132, -dcfuns, -double, -dryrun, -dusty, -encoding, -english, -f2003, -f2008, -f95, -fixed, -free, -help, -I, -i8, -indirect, -info, -kind, -max_parameter_size, -maxcontin, -mismatch, -mismatch_all, -nihongo, -nocheck_modtime, -noqueue, -o, -openmp, -Qpath, -r8, -strict95, -tempdir, -thread_safe, -u, -u=sharing, -v, -V, -w and -xlicinfo.

The interface generator understands all the enhanced polish options with the same meaning.

The following additional options control the operation of the interface generator:

-cmt_generation
Add a comment before the INTERFACE statement, giving the date and time that the file was generated. This is the default.
-cmt_provenance
Add a comment after each procedure heading (SUBROUTINE or FUNCTION statement) indicating the source of the procedure.
-module=X
Specifies the name of the module to generate containing procedure interfaces. The default is ‘interfaces’.
-otype=type
Specify the type of output file required to type, which must be one of

include | (INCLUDE file),
module | (Fortran module in a new source file).

The default is -otype=module.

-nocmt_generation
Do not add any comment before the INTERFACE statement.
-nocmt_provenance
Do not add any comment after each procedure heading. This is the default.


NAG Fortran Compiler, Release 7.1: Source File Polishing

 Navigation: Previous Up Next

2.24 Source File Polishing

The polisher takes a set of Fortran source files, which may be in fixed or free form, and produces a free form “polished” version of each file. C files and fpp-processed files are not handled.

The polisher understands the following compiler options with the same meaning: -132, -encoding, -english, -f2003, -f2008, -f95, -fixed, -free, -help, -I, -indirect, -info, -maxcontin, -nihongo, -noqueue, -o, -openmp, -Qpath, -tempdir, -v, -V, -w and -xlicinfo.

The polished output is written to the file specified by the -o option, or to the same filename with the extension replaced by ‘.f90_pol’ if no -o option is specified. The output file cannot have the same name as the input file.

The following additional options control the operation of the polisher:

-align_right_continuation
Align the continuation markers (ampersands) at the end of a continued line to column N+2, where N is the normal line width (specified by the -width= option). This only affects lines that do not end with an inline comment.
-alter_comments
Enable options to alter comments; without this option, any options that would otherwise alter the comments are ignored.
-array_constructor_brackets=X
Specify the form to use for array constructor delimiters; X must be one of Asis (same as the input file), ParenSlash (use parentheses+slash pairs, i.e. ‘(/ ... /)’) or Square (use square brackets, i.e. ‘[ ... ]’). The default is -array_constructor_brackets=Asis.
-blank_cmt_to_blank_line
Turn comment lines that have no text (other than the comment-initiating character) into plain blank lines; this is the default if the -alter_comments option is set.
-blank_line_after_decls
Ensure that there is a blank line after the declarations and before the first executable statement; this is the default.
-bom=X
Specify whether to write a Unicode Byte-Order Mark at the beginning of the output file; X must be one of Asis (same as the input file), Insert (insert a byte-order mark) or Remove (remove any byte-order mark). This option only has effect if the input file is known to be in UTF-8 encoding, either because it begins with a byte-order mark or the -encoding=UTF8 option was used. The default is -bom=Asis.
-break_long_comment_word
If a comment line will be split into two lines, the comment may be broken in the middle of a long word.
-character_decl=style
Specify the style to be used for CHARACTER type declaration statements; style must be one of the following (not case-sensitive):

Asis | (same as the input statement, but obey any -kind_keyword= option),
Keywords | (use LEN= and KIND=),
Kind_Keyword_Only | (use KIND= but not LEN=) or
No_Keywords | (use modern style with no keywords).

The default is Asis; with any other style, the obsolescent “CHARACTER*length” form will be changed to the modern “CHARACTER(length)” form. When both the length and kind appear in the input statement, the length will appear first in the output statement.

-commas_in_formats=X
Specify whether to add optional commas in FORMAT statements; X must be one of Asis (use the same comma scheme as the input), Insert or Remove. The default is -commas_in_formats=Insert.
-dcolon_column=N
Align double colon ‘::’ in declarations at column N and align any subsequent continuation lines to match. The default is for no special alignment, which is equivalent to -dcolon_column=0.
-dcolon_in_decls=X
Specifies how to handle the optional double colon ‘::’ in declarations; X must be one of Asis (preserve the input status), Insert (insert ‘::’ if not present), or Remove (remove ‘::’ if present and optional); the default is -dcolon_in_decls=Asis.
-delete_all_comments
Delete all comments (if the -alter_comments option is set).
-delete_blank_lines
Delete blank lines and comment lines that have no text (other than the comment-initiating character), if the -alter_comments option is set.
-delete_unused_labels
Delete labels that are never referenced; this is the default.
-format_start=N
If renumbering FORMAT statements in a separate sequence, the first FORMAT statement will be N; the default is -format_start=90000.
-format_step=N
If renumbering FORMAT statements in a separate sequence, the step from one label to the next will be N; the default is -format_step=10. Note that this may be negative (but not zero).
-idcase=X
Set the case to use for identifiers; X must be one of Asis, Capitalised, lowercase, UPPERCASE, Camel_Case, or an abbreviation thereof (both C and Ca are treated as Capitalised, not Camel_Case); the default is -idcase=lowercase. The interpretation of X is not case-sensitive (e.g. -idcase=u is the same as -idcase=U). Note that -idcase=Asis is only available for basic polishing (=polish), not in Enhanced Polish (=epolish) or any other tool (e.g. =unifyprecision).
-indent=N
Indent statements within a construct by N spaces from the current indentation level; the default is -indent=2.
-indent_comment_marker
When indenting comments, the comment-initiating character should be indented to the indentation level; this is the default.
-indent_comments
Indent comments; this is the default if the -alter_comments option is set. The result is also affected by the -indent_comment_marker option.
-indent_continuation=N
Indent continuation lines by an additional N spaces; the default is -indent_continuation=2.
-indent_max=N
Set the maximum indentation level to N spaces; the default is -indent_max=60. The value must be at least 10 less than the output line length (-width=).
-inline_comment_indent=N
Set the indentation level for inline comments to column N; the default is -inline_comment_index=35.
-keep_blank_lines
Do not delete blank lines or comment lines with no text; this is the opposite of -delete_blank_lines and is the default.
-keep_comments
Do not delete non-blank comment lines; this is the opposite of -delete_comments and is the default.
-keep_unused_labels
Do not delete unused (unreferenced) labels; this is the opposite of -delete_unused_labels.
-kind_keyword=X
Specifies how to handle the KIND= specifier in declarations; X must be one of Asis (take no action but preserve the input status), Insert (insert KIND= if not present), or Remove (remove KIND= if present); the default is -kind_keyword=Asis.
-kwcase=X
Set the case to use for language keywords; X must be one of Capitalised, lowercase, UPPERCASE, Camel_Case, or an abbreviation thereof (both C and Ca are treated as Capitalised, not Camel_Case); the default is -kwcase=Capitalised. The interpretation of X is not case-sensitive (e.g. -kwcase=u is the same as -kwcase=U). The -kwcase=C produces ‘Double Precision’ and ‘Non_recursive’; with -kwcase=Camel, the latter is produced as ‘Non_Recursive’.
-label_after_indent
Indent labels; this is the opposite to -label_before_indent.
-label_before_indent
Output the statement label, if any, before indenting the statement; this is the default.
-leave_formats_in_place
Leave FORMAT statements in the same position as they are in the input file; this is the opposite of -move_formats_to_end, and is the default.
-margin=N
Set the left margin (initial indent) to N. The value must be at least 10 less than the output line length (-width=). The default value for the left margin is 4.
-move_formats_to_end
Move FORMAT statements to the end of the subprogram or program unit, immediately before the CONTAINS or END statement.
-name_scopes=X
Specify whether to add optional keywords and scope names to the END or END TYPE statement for a scope; X must be one of Asis (leave as is), Insert (insert keywords and/or names), Keywords (insert keywords but remove names) or Remove (remove optional keywords and names). This option also applies to the END INTERFACE statement. The default is -name_scopes=Keywords.
-noalign_right_continuation
Do not align the continuation markers (ampersands) at the end of continued lines; this is the default.
-noalter_comments
Do not alter comments in any way; this is the default.
-noblank_cmt_to_blank_line
Do not turn blank comments to blank lines.
-noblank_line_after_decls
Do not insert a blank line between the last declaration and the first executable statement.
-nobreak_long_comment_word
If a comment line will be split into two lines, do not break the comment in the middle of a long word; this is the default.
-nodcolon_column
Do not align double colon ‘::’ in declarations. This is the default, and is equivalent to specifying alignment at column zero via -dcolon_column=0.
-noindent_comment_marker
Place the comment-initiating character for a comment line in column 1.
-noindent_comments
Do not indent the text of a comment line.
-norenumber
Do not renumber statement labels.
-noseparate_format_numbering
When renumbering statement labels, use a single sequence for both FORMAT and non-FORMAT statements; this is the default.
-noterminate_do_with_enddo
Do not change DO loop terminating statements.
-nowrap_comments
Do not wrap long comment lines (they will still be indented if comments are being indented).
-relational=X
Specifies the form to use for relational operators, X must be either F77- (use .EQ., .LE., etc.) or F90+ (use ==, <=, etc.); the default is -relational=F90+.
-renumber
Renumber statement labels; this is the default.
-renumber_start=N
When renumbering statement labels, the first label will be N; the default is -renumber_start=100.
-renumber_step=N
When renumbering statement labels, the step from one label to the next will be N; the default value is -renumber_step=10.
-separate_format_numbering
When renumbering statement labels, renumber FORMAT statements in a separate sequence from non-FORMAT statements.
-terminate_do_with_enddo
Change the terminating statements of all DO loops so that each loop ends with an ENDDO statement; this is the default.
-width=N
Set the maximum length of the text on each output line to N; the default is -width=78. Note that in the case of continuation lines, an additional two characters (‘ &’) will be produced after the last text on a line and this may take the line length over the limit. The width must be at least 10 more than the left margin (-margin=) and the maximum indent (-indent_max=). The maximum width setting is 1024, however values higher than 130 will produce output that does not conform to the Fortran standard.
-wrap_comments
Wrap long comment lines that would otherwise exceed the maximum line length. This is the default.


NAG Fortran Compiler, Release 7.1: Enhanced Source File Polishing

 Navigation: Previous Up Next

2.25 Enhanced Source File Polishing

The enhanced polisher takes a set of Fortran source files, which may be in fixed or free form, and produces a free form “polished” version of each file. C files and fpp-processed files are not handled. Unlike the simple polisher, the Fortran source files must be compilable without error; this is because the information needed for enhanced polishing requires successful semantic analysis of the files.

The enhanced polisher understands the following compiler options with the same meaning: -132, -abi, -dcfuns, -double, -dryrun, -dusty, -encoding, -english, -f2003, -f2008, -f95, -fixed, -free, -help, -I, -i8, -indirect, -info, -kind, -max_parameter_size, -maxcontin, -mismatch, -mismatch_all, -nihongo, -nocheck_modtime, -nomod, -noqueue, -o, -openmp, -Qpath, -r8, -strict95, -tempdir, -thread_safe, -u, -u=sharing, -v, -V, -w and -xlicinfo.

The enhanced polisher includes all the simple polish options, which are not repeated here, except for -idcase=Asis.

Note that unlike nagfor =polish, -name_scopes=Asis acts as if it were -name_scopes=Keywords, which is the default. Similarly, -array_constructor_brackets=Asis acts as if it were -array_constructor_brackets=ParenSlash, and is the default, and -dcolon_in_decls=Asis acts as if it were -dcolon_in_decls=Insert, and is the default.

The default filename extension for the output file is ‘.f90_epo’, used when no -o option is specified.

The following additional options control the operation of this tool.

-add_arg_keywords
Add keywords to actual arguments in references to user-defined procedures with an explicit interface and at least two dummy arguments, and in references to intrinsic procedures and intrinsic module procedures with at least three dummy arguments (except for MAX and MIN, where it is at least three actual arguments).

Keywords are not added to arguments that precede a label argument. The order of the arguments is unchanged.

This option is equivalent to -add_arg_keywords=all2,intrinsic3.

-add_arg_keywords=proc_class_list
Add keywords to actual arguments in procedure references, when the procedure has an explicit interface, for the classes of procedure listed in proc_class_list, which is a comma-separated list that may contain the following suboptions:

all | (all classes of procedure),
bound | (object-bound and type-bound procedures),
dummy | (dummy procedures),
external | (external procedures),
internal | (internal procedures),
intrinsic | (intrinsic procedures and intrinsic module procedures),
module | (non-intrinsic module procedures),
user | (procedures other than intrinsic procedures and intrinsic module procedures).

Keywords are not added to arguments that precede a label argument. The order of the arguments is unchanged. Procedure pointer components are also known as “object-bound procedures”, and thus included in -add_arg_keywords=bound; named procedure pointers are treated as external procedures and thus included in -add_arg_keywords=external.

A suboption name may be followed by a single nonzero digit (e.g. “intrinsic3”); this specifies that for procedures covered by that suboption, keywords are only to be added if the procedure has at least that many dummy arguments. For type-bound and object-bound procedures, the passed-object dummy argument does not count towards the limit (as it never appears in the argument list). The intrinsic MAX and MIN functions use the number of actual arguments instead.

A suboption name followed by a digit may be further followed by the letter ‘a’ (e.g. “intrinsic3a”; this specifies that the argument limit applies to the number of actual arguments in a reference to the procedure, not the number of dummy arguments (the number of actual arguments will be less than the number of dummy arguments when an optional argument is omitted).

Note that suboptions are parsed from left to right, and later suboptions override earlier ones.

-case:kind=case-list
Specifies case rules for specific kinds of name; this option overrides other case options except for -casex. The colon is followed by a comma-separated list of “kind=case”, where case is a case specification (UPPERCASE, lowercase, Capitalised, Camel_Case), and kind is one of the categories listed below:

comp | Component
constr | Construct name
intr | Intrinsic procedure
param | PARAMETER
proc | Procedure
tbp | Type-bound procedure
tparam | Derived type parameter
type | Derived type
var | Variable

For example, -case:var=lower,proc=u specifies lowercase for variables and UPPERCASE for procedures. If there is no setting for a particular kind of name, it will fall back to an appropriate category; param, type, comp, tparam and proc all fall back to var, intr will fall back to proc, and tbp will fall back to comp or proc. If there is no rule or fall-back rule, the -idcase= option setting (or default) is used.

-casex:name-list
Specifies exceptions to the case rules. The colon is followed by a comma-separated list of names in the exact case required. For example, -casex:MaxVal,XYz will result in every occurence of a name equivalent to maxval or xyz appearing as MaxVal or XYz respectively.
-intrinsic_case=analogy
Specifies whether the case of an intrinsic procedure name should be the same as other names (as_names), or the same as language keywords (as_keywords). The default is -intrinsic_case=as_names.
-remove_intrinsic_stmts
Specifies that intrinsic procedure names that were not passed as actual arguments should be removed from INTRINSIC statements, and that if all the names in an INTRINSIC statement are removed in this way, the INTRINSIC statement itself should be removed. Any comments associated with the INTRINSIC statement will remain.


NAG Fortran Compiler, Release 7.1: Unifying Precision

 Navigation: Previous Up Next

2.26 Unifying Precision

The precision unifier standardises floating-point and complex variable declarations, floating-point and complex literal constants, and some specific (non-generic) intrinsic procedures in a set of Fortran source files in order to unify the precision of these entities.

Standardisation to quadruple precision is only available on machines for which quadruple-precision floating-point arithmetic is available.

The tool attempts to make a standardising precision parameter accessible in program units (and interface blocks) via a use statement. You can control the form of this statement: the -pp_name= option controls the name of the precision parameter, and the -pp_module= option supplies the name of its host module (which is known as the ‘precision module’). The default form for the use statement (when no options are specified) is USE WORKING_PRECISION, ONLY: WP.

The -precision= option (whose default value is Double) can be supplied to set the desired unifying precision. The tool will use this setting when performing a number of checks of the validity of the standardisation process on the input files.

The precision module can be created by the tool, but otherwise does not itself undergo precision unification. A warning is issued if the tool encounters this module. A message is also emitted if no definition for the precision parameter is found in the module, or otherwise if the defined precision parameter specifies a different kind to the desired precision as provided or implied by the -precision= option.

The tool searches each program unit and interface block in the input source and determines whether the precision parameter is already accessible. If it is not, then a use statement, in the form given above, is inserted in the last allowable position for its statement type. For an internal or module procedure this statement is placed in the host. If the precision parameter is already declared in the form INTEGER, PARAMETER :: wp = constant_expression, then this declaration is deleted and a new use statement added, as previously described. (This PARAMETER form of statement is only recognised as declaring the precision parameter if it precedes all declarations of floating-point or complex entities in the scoping unit.) Any other form of definition or import of the precision parameter will not be modified, and the tool issues a warning that the standardised use statement could not be inserted.

Type declarations for floating-point and complex entities are standardised to include the precision parameter as kind parameter. Entities that are implicitly typed to be floating-point or complex are explicitly declared, in the same form. In the case when a function is defined with a floating-point or complex type specification on the function statement, this specification is deleted and a distinct type declaration statement for the function result is inserted into the function's declaration section.

Floating-point and complex literal constants are standardised to use the precision parameter as their kind.

The option -pu_floats= controls the extent of precision conversions that are applied. The default behaviour described above for floating-point and complex entities corresponds to -pu_floats=On. The value -pu_floats=Default_Kinds may be supplied in order to limit the precision unification only to entities having default kind; i.e., kind specifiers already given in type declarations or for literals will be preserved, even if they differ from the desired unifying precision. Modification of all floating-point and complex entities may be suppressed altogether via -pu_floats=Off.

The following specific procedure references are standardised to the generic replacement listed below:

Specific | Generic | Specific | Generic | Specific | Generic
ALOG10 | LOG10 | DATAN | ATAN | DSINH | SINH
ALOG | LOG | DBLE | REAL | DSIN | SIN
AMAX0(...) | REAL(MAX(...)) | DCMPLX | CMPLX | DSQRT | SQRT
AMAX1 | MAX | DCONJG | CONJG | DTANH | TANH
AMIN0(...) | REAL(MIN(...)) | DCOS | COS | DTAN | TAN
AMIN1 | MIN | DCOSH | COSH | FLOAT | REAL
AMOD | MOD | DDIM | DIM | IABS | ABS
CABS | ABS | DEXP | EXP | IDIM | DIM
CCOS | COS | DIMAG | AIMAG | IDINT | INT
CDABS | ABS | DINT | AINT | IDNINT | NINT
CEXP | EXP | DLOG10 | LOG10 | IFIX | INT
CLOG | LOG | DLOG | LOG | ISIGN | SIGN
CSIN | SIN | DMAX1 | MAX | MAX0 | MAX
CSQRT | SQRT | DMIN1 | MIN | MAX1(...) | INT(MAX(...))
DABS | ABS | DMOD | MOD | MIN0 | MIN
DACOS | ACOS | DNINT | ANINT | MIN1(...) | INT(MIN(...))
DASIN | ASIN | DREAL | REAL | SNGL | REAL
DATAN2 | ATAN2 | DSIGN | SIGN |  |

(See also the description of -dcfuns.)

Furthermore, DBLE is converted to REAL. Following that, the KIND= argument is added to calls to REAL and CMPLX, when appropriate.

In cases where unifying the precision of the input source may lead in the generated output to undesirable side effects, or even invalid Fortran, the tool will attempt to issue a warning alerting you to the possibility. Here is a non-exhaustive list of situations where it may be inappropriate to apply this tool.

  1. Your source intentionally uses a mix of floating-point and complex precisions and you are running the tool in (the default) mode -pu_floats=On.
  2. You are employing Fortran language features for generic programming (such as generic interface blocks or parameterised derived types).
  3. You have floating-point or complex data in EQUIVALENCE statements or in references to the TRANSFER intrinsic.
  4. You have explicitly-typed intrinsic functions, or are passing intrinsic functions as procedure arguments.
  5. You are using the DPROD intrinsic (perhaps as a means of performing higher- (double-) precision computations in a single-precision program unit).
  6. You are mixing Fortran and non-Fortran code.

For procedures spread across several files clearly it is desirable to make sure this tool is applied to all files consistently. This will ensure, for example, that procedure references and the corresponding procedure definitions do not become inconsistent with respect to the type standardisation.

The precision unifier understands the following compiler options with the same meaning: -132, -abi, -dcfuns, -double, -dryrun, -dusty, -encoding, -english, -f2003, -f2008, -f95, -fixed, -free, -help, -I, -i8, -indirect, -info, -kind, -max_parameter_size, -maxcontin, -mismatch, -mismatch_all, -nihongo, -nocheck_modtime, -nomod, -noqueue, -o, -openmp, -Qpath, -r8, -strict95, -tempdir, -thread_safe, -u, -u=sharing, -v, -V, -w and -xlicinfo.

Note that using the -double or -r8 option affects the meaning of the -precision= option; see the description of the latter, below.

The standardised output is written to the file specified by the -o option, or to the same filename with the extension replaced by ‘.f90_prs’ if no -o option is specified. The output file cannot have the same name as the input file.

The precision unifier understands all the enhanced polish options with the same meaning.

The following additional options control the operation of this tool:

-nocmt_generation
If creating the precision module, do not add a comment saying when it was generated.
-pp_create_module
Automatically create the precision module, in the file whose name is the name of the module, converted to lower case, with file type ‘.f90’; thus the default filename is working_precision.f90. If the file already exists it will not be overwritten by this option.

The created module will contain only the definition of the precision parameter, and unless the -nocmt_generation option is given, a comment identifying when the module was created.

-pp_name=X
Specifies the name of the precision parameter to use in the standardised output, which must be a legal identifier that does not conflict with existing names in the input source. The default is ‘WP’.
-pp_module=X
Specifies the name of the precision module from which the precision parameter is to be imported. This module name must be a legal identifier that does not conflict with existing names in the input source. The default is ‘WORKING_PRECISION’.
-pp_nocreate_module
Do not create the precision module. This is the default.
-precision=X
Specifies the desired target unifying precision in the output; X must be one of Half, Single (i.e., same precision as default REAL), Double (i.e., same precision as default DOUBLE PRECISION) or Quadruple. The default is -precision=Double.

Note that, since -double and -r8 double the size of default REAL (and possibly default DOUBLE PRECISION), specifying -double or -r8 will likewise modify the meaning of this -precision= option too.

-pu_floats=X
Controls the precision-unification mode for floating-point and complex entities; X must be one of Off, On or Default_Kinds. In the latter mode of operation already-kinded entities will not be modified. The default is -pu_floats=On.


NAG Fortran Compiler, Release 7.1: Debugging with dbx90

 Navigation: Previous Up Next

3 Debugging with dbx90

  • 3.1 dbx90 command line
  • 3.2 Description of dbx90
  • 3.3 dbx90 options
  • 3.4 dbx90 Commands
  • 3.5 dbx90 Expressions
    • 3.5.1 Scalar expressions
    • 3.5.2 Array sections
    • 3.5.3 Derived type component specification
  • 3.6 dbx90 Command aliases
  • 3.7 dbx90 limitations
  • 3.8 Example of dbx90
  • 3.9 Troubleshooting dbx90


NAG Fortran Compiler, Release 7.1:

 Navigation: Previous Up Next

3.1 dbx90 command line

dbx90 [option]... executable-file


NAG Fortran Compiler, Release 7.1: Description of

 Navigation: Previous Up Next

3.2 Description of dbx90

dbx90 is a Fortran-oriented debugger for use with the NAG Fortran Compiler on Unix-like systems (e.g. Linux, Solaris). Its syntax is quite similar to that of dbx, which it invokes as a sub-process to carry out the actual machine-dependent debugging commands. (On gcc-based implementations, gdb is used.)

The program to be debugged should be compiled and linked with the -g90 option. This creates a debug information (.g90) file for each Fortran source file.

If the environment variable DBX90_DBXPATH is defined, dbx90 will use it to locate the native debugger instead of the built-in path.


NAG Fortran Compiler, Release 7.1:

 Navigation: Previous Up Next

3.3 dbx90 options

-compatible
This permits dbx90 to debug code compiled by the NAG Fortran Compiler using the -compatible option.
-I pathname
Add pathname to the list of directories which are to be searched for module information (.mod) files and debug information (.g90) files. The current working directory is always searched first, then any directories named in -I options, then the compiler's library directory (usually ‘/usr/local/lib/NAG_Fortran’ or ‘/opt/NAG_Fortran/lib’)
-Qpath path
Set the compiler's library directory to path. This is only used for finding the module information (.mod) files for intrinsic modules.


NAG Fortran Compiler, Release 7.1:

 Navigation: Previous Up Next

3.4 dbx90 Commands

alias | List command aliases.
alias name text | Create a new alias name with the replacement value text. The replacement text is not limited to a single word but may contain spaces.
assign var = expr | Assign the value of expr to variable var. The variable can be scalar, an array (including an array section), a scalar component, or an element of an array component, but cannot be of derived type. The value must be a scalar expression (see “Expressions” for more details).
cont | Continue execution from where it was stopped (either by a breakpoint or an interrupt).
delete n | Delete breakpoint number n.
delete all | Delete all breakpoints.
display | List the expressions to be displayed after each breakpoint is reached.
display expr | Add expr to the list of expressions to display after each breakpoint. Expr may also be an array section.
dump | Display all local variables and their values.
down [n] | Move the focus down (i.e. to the procedure called by the current procedure). If n is present, move down n levels.
help [topic] | Display a brief help message on the specified topic, or on using dbx90 generally.
history List the history command buffer. Old commands can be executed with:
!!
repeat last command,
! n
repeat command n in the history buffer, and
! -n
repeat the nth last command.
history n | Set the size of the history command buffer to n commands. The default size of the history command buffer is 20.
if expr | This is actually a suffix to the breakpoint (‘stop’) commands not an independent command. It prevents the triggering of the breakpoint until the expression expr (a scalar expression) is .TRUE. (or non-zero).
list [line1[,line2]] | Display the next 10 lines of the program, display line line1 of the current file or display lines line1 to line2 of the current file.
next [n] | Execute the next n lines (default 1) of the current (or parent) procedure. Any procedure reference in these lines will be executed in its entirety unless a breakpoint is contained therein.
print expr [,expr]... | Display the value of expr, which can be a scalar expression, array section, derived type component,or a variable of any data type. Several expressions may be given separated by commas.
quit | Exit from dbx90, immediately terminating any program being debugged.
raw dbx-command | Pass dbx-command directly to “dbx”. This is not recommended for normal use.
rerun [command-line] | Begin a new execution of the program, passing command-line to it (if present) or the command-line from the previous run or rerun command if not.
run [command-line] | Begin a new execution of the program, passing command-line to it (if present) or blank command line if not.
scope [name] | Display the current procedure name or set the focus to the specified procedure name.
status | List the breakpoints which are currently set.
step [n] | Execute the next n lines (default 1) of the program, counting lines in referenced procedures (i.e. step into procedure references).
stop name | Set a breakpoint which triggers when variable name is accessed. Note that name cannot be ‘at’ or ‘in’. This command is not available on Solaris or HP-UX.
stop at lineno | Set a breakpoint at line lineno of the file containing the current procedure.
stop in name | Set a breakpoint at the beginning of procedure name. Note that this breakpoint occurs at the beginning of procedure initialisation, not at the first executable statement. If there is no procedure called ‘MAIN’, the main program can be specified using that name.
undisplay expr | Remove expr from the “display” list.
up [n] | Move the focus up (i.e. to the caller of the current procedure). If n is present, move up n levels.
whatis name | Describe how name would be explicitly declared.
where | Display the stack of active procedures with their dummy argument names.
which name | Display the fully qualified form of name which can be used for access from another scope.


NAG Fortran Compiler, Release 7.1:

 Navigation: Previous Up Next

3.5 dbx90 Expressions

3.5.1 Scalar expressions

Scalar expressions in dbx90 are composed of literal constants, scalar variable references including array elements, intrinsic operations and parentheses.

Literal constants can be of any intrinsic type, e.g.

INTEGER | 42
REAL | 1.2
 | 1.3e2
COMPLEX | (5.2,6.3)
CHARACTER | "string"
LOGICAL | .TRUE.
 | .T.

Subscript expressions must be scalar and of type INTEGER.

All intrinsic operations are supported except for exponentiation and concatenation, that is:

+, -, *, /, ==, /=, <, <=, >, >=, .AND., .OR., .NOT., .EQV., .NEQV., .EQ., .NE., .LT., .LE., .GT., .GE.

(Operator names are not case-sensitive).

Note: array operations and operations involving variables of complex, character or derived type are not supported.

3.5.2 Array sections

Assignment, printing and displaying of array sections follows the Fortran syntax, e.g.
   ARRAY(:)
   ARRAY(1:5)
   ARRAY(1:10:2)

If the stride is supplied it must be a positive scalar expression – negative strides are not supported. All subscript expressions must be scalar – vector subscripts are not supported.

3.5.3 Derived type component specification

Individual components of a derived type scalar or array may be printed using normal Fortran syntax.

For example,

     print var%a
will print the “a” component of derived type “var”.

Components of all data types are supported.

Components which are of derived type will be displayed recursively until either:

  1. there are no further nested derived types, or
  2. a derived type array component is reached.

Array components of intrinsic data types will be truncated to ‘<array>’, and derived type array components will be truncated to ‘<derived type array>’.

Allocatable components of derived types are supported.

Derived type assignment is not supported; however, scalar non-derived-type components may be assigned values.


NAG Fortran Compiler, Release 7.1:

 Navigation: Previous Up Next

3.6 dbx90 Command aliases

The following set of command aliases are defined:

a | assign
b | stop at
bp | stop in
c | cont
h | history
l | list
n | next
p | print
q | quit
r | rerun
s | step

New aliases may be created using the alias command, e.g.

  alias xp1 print x+1


NAG Fortran Compiler, Release 7.1:

 Navigation: Previous Up Next

3.7 dbx90 limitations

Breakpoints set at the beginning of a routine occur before procedure initialisation; at this point attempting to print or display an assumed-shape dummy argument, a variable with a complicated EQUIVALENCE or an automatic variable will produce dbx crashes, dbx90 crashes or nonsensical output. Execution must be stepped to the first executable statement (e.g. using the next command or by setting a second breakpoint) before any of these will work satisfactorily.

Strides in array sections must be positive.


NAG Fortran Compiler, Release 7.1: Example of

 Navigation: Previous Up Next

3.8 Example of dbx90

This is an example of the use of dbx90 in debugging some Fortran code which contains both COMMON blocks and modules.

The file to be debugged is called ‘fh4.f90’ and contains:

    MODULE fh4
      REAL r
    END MODULE fh4

    PROGRAM fh4_prog
      USE fh4
      COMMON/fh4com/i
      i = 2
      CALL sub
      PRINT *,i,r
    END PROGRAM fh4_prog

    SUBROUTINE sub
      USE fh4
      COMMON/fh4com/i
      r = 0.5*i
      i = i*3
    END SUBROUTINE sub

It is first compiled with the -g90 option and then run under dbx90:

    % nagfor -g90 -o fh4 fh4.f90
    % dbx90 fh4
    NAG dbx90 Version 5.2(22)
    Copyright 1995-2008 The Numerical Algorithms Group Ltd., Oxford, U.K.
    GNU gdb Red Hat Linux (6.5-15.fc6rh)
    Copyright (C) 2006 Free Software Foundation, Inc.
    GDB is free software, covered by the GNU General Public License, and you are
    welcome to change it and/or distribute copies of it under certain conditions.
    Type "show copying" to see the conditions.
    There is absolutely no warranty for GDB.  Type "show warranty" for details.
    This GDB was configured as "i386-redhat-linux-gnu"...Using host libthread_db lib
    rary "/lib/libthread_db.so.1".

    (dbx90)

Setting a breakpoint in routine SUB and running the program.

    (dbx90) stop in sub
    [1] stop in SUB in file "fh4.f90"
    (dbx90) run
    stopped in SUB at line 16 in file "fh4.f90"
       16     r = 0.5*i
    (dbx90)

Printing the value of a variable, which may be local, in a COMMON block, or in a USEd module.

    (dbx90) print i
    I = 2
    (dbx90) next
    17        i = i*3
    (dbx90) print r
    R = 1
    (dbx90) next
    18      END SUBROUTINE sub
    (dbx90) print i
    I = 6

Variables can also be assigned values.

    (dbx90) assign i = 7
    I  = 7
    (dbx90) cont
     7   1.0000000

    Program exited normally.
    (dbx90) quit
    %


NAG Fortran Compiler, Release 7.1: Troubleshooting

 Navigation: Previous Up Next

3.9 Troubleshooting dbx90

The diagnostic messages produced by dbx90 itself are intended to be self-explanatory.

If you receive the error message ‘Cannot exec dbx’ when starting dbx90 then you must set the environment variable DBX90_DBXPATH to the pathname of dbx (or gdb, or xdb).


NAG Fortran Compiler, Release 7.1: Preprocessing with fpp

 Navigation: Previous Up Next

4 Preprocessing with fpp

  • 4.1 Overview of fpp
  • 4.2 fpp command line
  • 4.3 Description of fpp
  • 4.4 fpp options
  • 4.5 Using fpp
    • 4.5.1 Source files
    • 4.5.2 Output
    • 4.5.3 Directives
    • 4.5.4 Macro definition
    • 4.5.5 Including external files
    • 4.5.6 Line number control
    • 4.5.7 Conditional selection of source text
  • 4.6 Preprocessing details
    • 4.6.1 Scope of macro or variable definitions
    • 4.6.2 End of macro definition
    • 4.6.3 Function-like macro definition
    • 4.6.4 Cancelling macro definitions
    • 4.6.5 Conditional source code selection
    • 4.6.6 Including external files
    • 4.6.7 Comments
    • 4.6.8 Macro functions
    • 4.6.9 Macro expression
  • 4.7 fpp diagnostics


NAG Fortran Compiler, Release 7.1: Overview of

 Navigation: Previous Up Next

4.1 Overview of fpp

The fpp preprocessor is automatically invoked by the compiler driver when the -fpp option is used or the source file has an option that implies preprocessing (e.g. ‘.ff90’), but may also be invoked from the compiler library directory (usually /usr/local/lib/NAG_Fortran).


NAG Fortran Compiler, Release 7.1:

 Navigation: Previous Up Next

4.2 fpp command line

fpp [option]... [input-file [output-file]]


NAG Fortran Compiler, Release 7.1: Description of

 Navigation: Previous Up Next

4.3 Description of fpp

fpp is the preprocessor used by the NAG Fortran compiler. It optionally accepts two filenames as arguments: input-file and output-file are, respectively, the input file read and the output file written by the preprocessor. By default standard input and output are used.

When used via nagfor, either because the input source file type was automatically recognised as requiring preprocessing (e.g. .ff90 files), or the -fpp option was used, the macro __NAG_COMPILER_RELEASE is automatically defined to be the integer release number (major*10+minor, e.g. 61 for release 6.1), and the macro __NAG_COMPILER_BUILD is automatically defined to be the build number (for release 6.1 this will have a value greater than 6100).


NAG Fortran Compiler, Release 7.1:

 Navigation: Previous Up Next

4.4 fpp options

-c_com={yes|no}
By default, C style comments are recognized. Turn this off by specifying -c_com=no.
-D name
Define the preprocessor variable name to be 1 (one). This is the same as if a -Dname=1 option appeared on the fpp command line, or as if a
#define name 1
line appeared in the input file.
-D name=def
Define name as if by a #define directive. This is the same as if a
#define name def
line appeared at the beginning of the input file. The -D option has lower precedence than the -U option. Thus, if the same name is used in both a -U option and a -D option, the name will be undefined regardless of the order of the options.
-e
Accept extended source lines, up to 132 characters long.
-fixed
Specifies fixed format input source.
-free
Specifies free format input source.
-I pathname
Add pathname to the list of directories which are to be searched for #include files whose names do not begin with ‘/’. If the #include file name is enclosed in double-quotes ("..."), it is searched for first in the directory of the file with the #include line; if the file name was enclosed in angle brackets (<...>) this directory is not searched. Then, the file is searched for in directories named in -I options, and finally in directories from the standard list.
-M
Generate a list of makefile dependencies and write them to the standard output. This list indicates that the object file which would be generated from the input file depends on the input file as well as the include files referenced.
-macro={yes|no_com|no}
By default, macros are expanded everywhere. Turn off macro expansion in comments by specifying -macro=no_com and turn off macro expansion all together by specifying -macro=no
-P
Do not put line numbering directives to the output file. Line numbering directives appear as
#line-number file-name
-U name
Remove any initial definition of name, where name is an fpp variable that is predefined by a particular preprocessor. Here is a partial list of variables that might be predefined, depending upon the architecture of the system:

Operating System: unix, __unix and __SVR4;
Hardware: sun, __sun, sparc and __sparc.

-undef
Remove initial definitions for all predefined symbols.
-w
Suppress warning messages.
-w0
Suppress warning messages.
-Xu
Convert upper-case letters to lower-case, except within character-string constants. The default is not to convert upper-case letters to lower-case.
-Xw
For fixed source form only, treat blanks as insignificant. The default for fpp is that blanks are significant in both source forms.
-Y directory
Use the specified directory instead of the standard list of directories when searching for #include files.


NAG Fortran Compiler, Release 7.1: Using fpp

 Navigation: Previous Up Next

4.5 Using fpp

4.5.1 Source files

fpp operates on both fixed and free form source files. Files with the (non-case-sensitive) extension ‘.f’, ‘.ff’, ‘.for’ or ‘.ftn’ are assumed to be fixed form source files. All other files (e.g. those with the extension ‘.ff90’) are assumed to be free form source files. These assumptions can be overridden by the -fixed and -free options. Tab format lines are recognised in fixed form.

A source file may contain fpp tokens. An fpp token is similar to a Fortran token, and is one of:

  • an fpp directive name;
  • a symbolic name or Fortran keyword;
  • a literal constant;
  • a Fortran comment;
  • an fpp comment;
  • a special character which may be a blank character, a control character, or a graphic character that is not part of one of the previously listed tokens.

4.5.2 Output

Output consists of a modified copy of the input plus line numbering directives (unless the -P option is used). A line numbering directive has the form
#line-number file-name
and these are inserted to indicate the original source line number and filename of the output line that follows.

4.5.3 Directives

All fpp directives start with the hash character (#) as the first character on a line. Blank and tab characters may appear after the initial ‘#’ to indent the directive. The directives are divided into the following groups:
  • macro definitions;
  • inclusion of external files;
  • line number control;
  • conditional source code selection.

4.5.4 Macro definition

The #define directive is used to define both simple string variables and more complicated macros:

#define name token-string

This is the definition of an fpp variable. Wherever ‘name’ appears in the source lines following the definition, ‘token-string’ will be substituted for it.

#define name([argname1[,argname2]...]) token-string

This is the definition of a function-like macro. Occurrences of the macro ‘name’ followed by a comma-separated list of arguments within parentheses are substituted by the token string produced from the macro definition. Every occurrence of an argument name from the macro definition's argument list is substituted by the token sequence of the corresponding macro actual argument.

Note that there must be no space or tab between the macro name and the left parenthesis of the argument list in this directive; otherwise, it will be interpreted as a simple macro definition with the left parenthesis treated as the first character of the replacement token-string.

#undef name

Remove any macro definition for name, whether such a definition was produced by a -D option, a #define directive or by default. No additional tokens are permitted on the directive line after the name.

The macro NAGFOR is defined by default.

4.5.5 Including external files

There are two forms of file inclusion:
#include "filename"
and
#include <filename>

Read in the contents of filename at this location. The lines read in from the file are processed by fpp as if they were part of the current file.

When the <filename> notation is used, filename is only searched for in the standard “include” directories. See the -I and -Y options above for more detail. No additional tokens are permitted in the directive line after the final ‘"’ or ‘>’.

4.5.6 Line number control

#line-number ["filename"]

Generate line control information for the next pass of the compiler. The line-number must be an unsigned integer literal constant, and specifies the line number of the following line. If "filename" does not appear, the current filename is unchanged.

4.5.7 Conditional selection of source text

There are three forms of conditional selection of source text:
  1.  #if condition_1
   block_1
 #elif condition_2
   block_2
 #else
   block_n
 #endif

  2.  #ifdef name
   block_1
 #elif condition
   block_2
 #else
   block_n
 #endif

  3.  #ifndef name
   block_1
 #elif condition
   block_2
 #else
   block_n
 #endif

The “#else” and “#elif” parts are optional. There may be more than one “#elif” part. Each condition is an expression consisting of fpp constants, macros and macro functions. Condition expressions are similar to cpp expressions, and may contain any cpp operations and operands with the exception of C long, octal and hexadecimal constants. Additionally, fpp will accept and evaluate the Fortran logical operations .NOT., .AND., .OR., .EQV., .NEQV., the relational operators .GT., .LT., .LE., .GE., and the logical constants .TRUE. and .FALSE..


NAG Fortran Compiler, Release 7.1: Preprocessing details

 Navigation: Previous Up Next

4.6 Preprocessing details

4.6.1 Scope of macro or variable definitions

The scope of a definition begins from the place of its definition and encloses all the source lines (and source lines from #included files) from that definition line to the end of the current file.

However, it does not affect:

  • files included by Fortran INCLUDE lines;
  • fpp and Fortran comments;
  • IMPLICIT single letter specifications;
  • FORMAT statements;
  • numeric and character constants.

The scope of the macro effect can be limited by means of the #undef directive.

4.6.2 End of macro definition

A macro definition can be of any length but is only one logical line. These may be split across multiple physical lines by ending each line but the last with the macro continuation character ‘\’ (backslash). The backslash and newline are not part of the replacement text. The macro definition is ended by a newline that is not preceded by a backslash.

For example:

  #define long_macro_name(x,\
  y) x*y

4.6.3 Function-like macro definition

The number of macro call arguments must be the same as the number of arguments in the corresponding macro definition. An error is produced if a macro is used with the wrong number of arguments.

4.6.4 Cancelling macro definitions

#undef name

After this directive, ‘name’ will not be interpreted by fpp as a macro or variable name. This directive has no effect if ‘name’ is not a macro name.

4.6.5 Conditional source code selection

#if condition

Condition is a constant expression, as specified below. Subsequent lines up to the first matching #elif, #else or #endif directive appear in the output only if the condition is true.

The lines following a #elif directive appear in the output only if

  • the condition in the matching #if directive was false,
  • the conditions in all previous matching #elif directives were false, and
  • the condition in this #elif directive is true.

If the condition is true, all subsequent matching #elif and #else directives are ignored up to the matching #endif.

The lines following a #else directive appear in the output only if all previous conditions in the construct were false.

The macro function ‘defined’ can be used in a constant expression; it is true if and only if its argument is a defined macro name.

The following operations are allowed.

  • C language operations: <, >, ==, !=, >=, <=, +, -, /, *, %, <<, >>, &, ~, |, !, && and ||. These are interpreted in accordance with C language semantics, for compatibility with cpp.
  • Fortran language operations: .AND., .OR., .NEQV., .XOR., .EQV., .NOT., .GT., .LT., .LE., .GE., .NE., .EQ. and **.
  • Fortran logical constants: .TRUE. and .FALSE..
Only these items, integer literal constants, and names can be used within a constant expression. Names that are not macro names are treated as if they were ‘0’. The C operation ‘!=’ (not equal) can be used in #if or #elif directives, but cannot be used in a #define directive, where the character ‘!’ is interpreted as the start of a Fortran comment.
#ifdef name
Subsequent lines up to the matching #else, #elif, or #endif appear in the output only if the name has been defined, either by a #define directive or by the -D option, and in the absence of an intervening #undef directive. No additional tokens are permitted on the directive line after name.
#ifndef name
Subsequent lines up to the matching #else, #elif, or #endif appear in the output only if name has not been defined, or if its definition has been removed with an #undef directive. No additional tokens are permitted on the directive line after name.
#elif constant-expression
Any number of #elif directives may appear between an #if, #ifdef, or #ifndef directive and a matching #else or #endif directive.
#else
This inverts the sense of the conditional directive otherwise in effect. If the preceding conditional would indicate that lines are to be included, then lines between the #else and the matching #endif are ignored. If the preceding conditional indicates that lines would be ignored, subsequent lines are included in the output.
#endif
End a section of lines begun by one of the conditional directives #if, #ifdef, or #ifndef. Each such directive must have a matching #endif.

4.6.6 Including external files

Files are searched as follows:

for #include "filename":

  • in the directory, in which the processed file has been found;
  • in the directories specified by the -I option;
  • in the default directory.
for #include <filename>:
  • in the directories specified by the -I option;
  • in the default directory.
Fpp directives (lines beginning with the # character) can be placed anywhere in the source code, in particular immediately before a Fortran continuation line. The only exception is the prohibition of fpp directives within a macro call divided on several lines by means of continuation symbols.

4.6.7 Comments

Fpp permits comments of two kinds:
  1. Fortran language comments. A source line containing one of the characters ‘C’, ‘c’, ‘*’, ‘d’ or ‘D’ in the first column is considered to be a comment line. Within such lines macro expansions are not performed. The ‘!’ character is interpreted as the beginning of a comment extending to the end of the line. The only exception is the case when this symbol occurs within a constant expression in a #if or #elif directive.
  2. Fpp comments enclosed in the ‘/*’ and ‘*/’ character sequences. These are excluded from the output. Fpp comments can be nested so that for each opening sequence ‘/*’ there must be a corresponding closing sequence ‘*/’. Fpp comments are suitable for excluding the compilation of large portions of source instead of commenting every line with Fortran comment symbols. Using “#if 0 ... #endif” achieves the same effect without being ridiculous.

4.6.8 Macro functions

The macro function

defined(name) or defined name

expands to .TRUE. if name is defined as a macro, and to .FALSE. otherwise.

4.6.9 Macro expression

If, during expansion of a macro, the column width of a line exceeds column 72 (for fixed form) or column 132 (for free form), fpp inserts appropriate continuation lines.

In fixed form there are limitations on macro expansion in the label part of the line (columns 1-5):

  • a macro call (together with possible arguments) should not extend past column 5;
  • a macro call whose name begins with one of the Fortran comment characters is treated as a comment;
  • a macro expansion may produce text extending beyond the column 5 position. In such a case a warning will be issued.
In the fixed form when the -Xw option has been specified an ambiguity may appear if a macro call occurs in a statement position and a macro name begins or coincides with a Fortran keyword. For example, in the following text:
  #define call p(x)   call f(x)
          call p(0)

fpp can not determine with certainty how to interpret the ‘call p’ token sequence. It could be considered as a macro name. The current implementation does the following:

  • the longer identifier is chosen (callp in this case);
  • from this identifier the longest macro name or keyword is extracted;
  • if a macro name has been extracted a macro expansion is performed. If the name begins with some keyword fpp outputs an appropriate warning;
  • the rest of the identifier is considered as a whole identifier.
In the above example the macro expansion would be performed and the following warning would be output:

warning: possibly incorrect substitution of macro callp

It should be noted that this situation appears only when preprocessing fixed form source code and when the blank character is not being interpreted as a token delimiter. It should be said also that if a macro name coincides with a keyword beginning part, as in the following case:

     #define INT    INTEGER*8
             INTEGER k
then in accordance with the described algorithm, the INTEGER keyword will be found earlier than the INT macro name. Thus, there will be no warning when preprocessing such a macro definition.


NAG Fortran Compiler, Release 7.1:

 Navigation: Previous Up Next

4.7 fpp diagnostics

There are three kinds of diagnostic messages:

  • warnings. preprocessing of source code is continued and the return value remains to be 0.
  • errors. Fpp continues preprocessing but sets the return code to a nonzero value, namely the number of errors.
  • fatal error. Fpp cancels preprocessing and returns a nonzero return value.
The messages produced by fpp are intended to be self-explanatory. The line number and filename where the error occurred are printed along with the diagnostic.


NAG Fortran Compiler, Release 7.1: Extensions

 Navigation: Previous Up Next

5 Extensions

  • 5.1 Non-standard Extensions
    • 5.1.1 BOZ literal constants outside DATA statements
    • 5.1.2 Longer Names
    • 5.1.3 Dollar Sign in Names
    • 5.1.4 Input/output endian/format conversion
    • 5.1.5 Elemental BIND(C) procedures
    • 5.1.6 Maximum array rank is 31
  • 5.2 Obsolete Extensions
    • 5.2.1 Byte Sizes
    • 5.2.2 TAB Format
    • 5.2.3 Hollerith Constants
    • 5.2.4 D (debug) lines in Fixed Source Form
    • 5.2.5 Increased Line Length in Fixed Source Form
    • 5.2.6 Increased Maximum Number of Continuation Lines
    • 5.2.7 Intrinsic functions with mixed-kind arguments
    • 5.2.8 ACCESS='APPEND' specifier on OPEN statement
    • 5.2.9 VAX FORTRAN TYPE statement
    • 5.2.10 Auto-skipping NAMELIST input
    • 5.2.11 Legacy Application Support
    • 5.2.12 Mismatched Argument Lists
    • 5.2.13 Double Precision Complex Extensions


NAG Fortran Compiler, Release 7.1: Non-standard Extensions

 Navigation: Previous Up Next

5.1 Non-standard Extensions

The following extensions to the standard Fortran language are accepted by the NAG Fortran Compiler.

5.1.1 BOZ literal constants outside DATA statements

The NAG Fortran Compiler accepts hexadecimal, octal and binary literal constants in any context where an integer literal would be accepted. Such constants have a data type of default INTEGER, unless there are more digits in the BOZ constant than will fit in a default INTEGER; e.g., Z'12345678' would be of type default INTEGER, and Z'123456789' would be a 64-bit integer.

5.1.2 Longer Names

Names may be up to 199 characters long.

5.1.3 Dollar Sign in Names

The dollar sign ‘$’ may appear in names as if it were a letter. On some systems this name is directly used in the link name, but on others, it is translated to DOLLAR.

5.1.4 Input/output endian/format conversion

Runtime conversion of unformatted input/output files is enabled by the CONVERT= specifier. This is an OPEN statement specifier, and takes a scalar default character argument; the accepted values are:
BIG_ENDIAN
synonym for BIG_IEEE;
BIG_IEEE_DD
big-endian with IEEE single and double precision floating point but with double-double for quad precision;
BIG_IEEE
big-endian with IEEE floating point include 128-bit quad precision;
BIG_NATIVE
big-endian with native floating-point formats;
LITTLE_ENDIAN
synonym for LITTLE_IEEE;
LITTLE_IEEE_DD
little-endian with IEEE single and double precision floating point but with double-double for quad precision;
LITTLE_IEEE
little-endian with IEEE floating point include 128-bit quad precision;
LITTLE_NATIVE
little-endian with native floating-point formats;
NATIVE
native endianness and data format.

It is also possible to specify this with an environment variable at runtime; when unit n is opened, if the environment variable FORT_CONVERT n exists, its value is interpreted as a CONVERT= specifier value. If the environment variable exists it takes precedence over any CONVERT= specifier in the OPEN statement. If the environment variable does not exist, and there is no CONVERT= specifier in the OPEN statement, the conversion mode is taken from the -convert= option at compile time; the default is NATIVE (i.e. no conversion).

The CONVERT= specifier is also available in the INQUIRE statement, and sets its argument to the current conversion mode or to 'UNKNOWN' if the file is not connected for unformatted input/output.

5.1.5 Elemental BIND(C) procedures

Interoperable (BIND(C)) procedures are permitted to be declared as ELEMENTAL. Such a procedure must satisfy the normal Fortran requirements for elemental procedures, in particular they must have scalar dummy arguments and must be pure (free from side-effects).

5.1.6 Maximum array rank is 31

The maximum rank of an array has been increased to 31 (the Fortran 2008 standard only requires 15, and previous Fortran standards only required 7). For example,
   REAL array(2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2)
declares a 30-dimensional array (which will take 4GiB of memory to store).


NAG Fortran Compiler, Release 7.1: Obsolete Extensions

 Navigation: Previous Up Next

5.2 Obsolete Extensions

The following extensions were common in the Fortran 77 era, and are still in frequent use (though they have been superseded and are thus unnecessary). Warning messages (marked ‘Extension:’) are produced for each occurrence of any extension; these particular ones may be suppressed with the -w=x77 option.

5.2.1 Byte Sizes

Byte sizes for REAL, INTEGER, LOGICAL and COMPLEX are accepted and mapped to Modern Fortran KINDS.

Byte Size Specification | Standard Fortran | Using F90_KIND or ISO_FORTRAN_ENV
REAL*2 | Real | Real(real16)
REAL*4 | Real | Real(real32)
REAL*8 | Double Precision | Real(real64)
REAL*16 | Real(Selected_Real_Kind(30)) | Real(real128)
COMPLEX*4 | Complex(Selected_Real_Kind(3)) | Complex(real16)
COMPLEX*8 | Complex | Complex(real32)
COMPLEX*16 | Complex(Kind(0d0)) | Complex(real64)
COMPLEX*32 | Complex(Selected_Real_Kind(30)) | Complex(real128)
INTEGER*1 | Integer(Selected_Int_Kind(2)) | Integer(int8)
INTEGER*2 | Integer(Selected_Int_Kind(4)) | Integer(int16)
INTEGER*4 | Integer | Integer(int32)
INTEGER*8 | Integer(Selected_Int_Kind(18)) | Integer(int64)
Byte Size Specification | Standard Fortran | Using F90_KIND
LOGICAL*1 |  | Logical(byte)
LOGICAL*2 |  | Logical(twobyte)
LOGICAL*4 | Logical | Logical(word)
LOGICAL*8 |  | Logical(logical64)

The byte length may also be overridden in the type declaration, similar to overriding the character length. For example,

    REAL X*4, Y*(8)

5.2.2 TAB Format

The occurrence of a TAB character in fixed-form source is treated as follows:
  1. an initial TAB followed by a digit is expanded to 5 spaces (putting the digit in the continuation column),
  2. an initial TAB followed by any other character is expanded to 6 spaces (putting the character after the TAB in column 7, making the line the initial line of a statement), and
  3. other TAB characters are treated as single blanks except in character context where they remain TABs (but they are still treated as taking one column for the purposes of line length).

5.2.3 Hollerith Constants

Hollerith constants may be used as actual arguments or to initialise objects in DATA. In either case they must be associated with an object of intrinsic numeric data type, not with a CHARACTER or derived type object.

Hollerith i/o (i.e., use of the A edit descriptor with non-CHARACTER data) is only enabled if the using subprogram was compiled with the -hollerith_io or -dusty option.

5.2.4 D (debug) lines in Fixed Source Form

A line with the letter ‘D’ (or ‘d’) in column one is a D line. If the -d_lines option is used, this will be treated as a normal Fortran line, as if the D were a space. Otherwise, it will be treated as a comment line, as if the D were a C.

For example, in

      SUBROUTINE TEST(N)
      INTEGER N
D     PRINT *,'TESTING N'
      ...
the PRINT statement will be compiled only if -d_lines is used.

Note that if the initial line of a statement is a D line, any continuation lines it may have must also be D lines. Similarly, if the initial line of a statement is not a D line, any continuation lines must not be D lines.

A D line can use TAB format, with the TAB expanding to one less space as the letter D already accounts for a space.

5.2.5 Increased Line Length in Fixed Source Form

The -132 option increases the effective length of each fixed source form input line from 72 characters to 132 characters.

Note that when this option is used the NAG Fortran Compiler no longer conforms to the Fortran language standard. The meaning of a program will change if it contains a character constant which is continued across a line boundary. A standard-conforming program containing an H-edit descriptor which is continued across a line boundary will very likely be rejected.

For new Fortran programs we recommend the use of free source form instead of this option. Free source form provides superior detection of typographical errors and is also part of the Fortran standard and thus fully portable to all standard-conforming compilers.

5.2.6 Increased Maximum Number of Continuation Lines

The -maxcontin=N option increases the limit on the maximum number of continuation lines to N. Note that this option can affect both fixed source form and free source form, but never decreases the continuation line limit below the standard.

The Fortran 90 and 95 standards specified that the maximum number of continuation lines in fixed source form was 19, and that the maximum number of continuation lines in free source form was 39. The Fortran 2003 standard increased this to 255 lines regardless of source form.

5.2.7 Intrinsic functions with mixed-kind arguments

The ATAN, ATAN2, DIM, MAX, MIN, MOD, MODULO and SIGN intrinsic functions will accept integer and real arguments that differ in kind; note that integer and real arguments still cannot be mixed in a single intrinsic function reference.

For SIGN, the kind of the result is the same as the kind of the first argument (which supplies the magnitude of the result), ignoring the kind of the second argument (which only supplies the sign of the result). For all the others, the kind of the result is the same as for arithmetic operations, i.e. for integers the kind with the largest number of digits, and for reals the kind with the greatest precision.

For example, if X is REAL(real32) and Y is REAL(real64):

MAX(X,Y) has kind real64 and its value is equal to MAX(REAL(X,real64),Y);
SIGN(X,Y) has kind real32 and its value is equal to SIGN(X,REAL(SIGN(1.0_real64,Y),real32)).

5.2.8 ACCESS='APPEND' specifier on OPEN statement

The VAX FORTRAN specifier ACCESS='APPEND' can be used on the OPEN statement. It is equivalent to specifying both ACCESS='SEQUENTIAL' and POSITION='APPEND'. For example,
       OPEN(17,FILE='my.log',ACCESS='APPEND')
has the same effect as
       OPEN(17,FILE='my.log',POSITION='APPEND') ! ACCESS='SEQUENTIAL' is the default.

This is supported only as an aid to porting old programs; it should be changed to the POSITION='APPEND' specifier.

5.2.9 VAX FORTRAN TYPE statement

This statement has identical syntax and semantics to the PRINT statement, except that the keyword TYPE is used instead of PRINT. Some forms of this statement where the format begins with a name are ambiguous with respect to a derived type definition, and those forms are only treated as a TYPE statement if that name is used or declared earlier in the scoping unit; otherwise, it is treated as a derived type definition.

For example,

       TYPE *,'Hello'
is equivalent to
       PRINT *,'Hello'

Processing a source file containing VAX FORTRAN TYPE statements with the enhanced polisher will turn all TYPE statements into PRINT statements. The ordinary polisher will not change any TYPE statements; furthermore, if one of the ambiguous forms is used, the remainder of the file will be incorrectly indented, as the ordinary polisher does not have semantic analysis and therefore assumes the ambiguous form is the beginning of a type definition.

5.2.10 Auto-skipping NAMELIST input

The Fortran standard requires that when namelist input is performed, the name after the ampersand in the input record must match the namelist group name (in the READ statement). However, a common extension is for the i/o library to “skip forwards” in the file, looking for an input record that matches namelist initial record required.

Normally, the NAG Fortran system raises an i/o error condition if the names do not match, but when auto-skipping namelist input is in effect, instead it skips records until it reaches the end of the file or finds a record that begins with an ampersand and the correct name.

For example, given the program

       PROGRAM asnl
         INTEGER x,y
         NAMELIST/name/x,y
         READ(*,name)
         PRINT *,'Result',x,y
       END PROGRAM
and the input data
       &wrong x = 999 y = -999 /
       &name x = 123 y = 456 /
with auto-skipping namelist it will print
        Result 123 456

Auto-skipping namelist is controlled by runtime options. The environment variable NAGFORTRAN_RUNTIME_OPTIONS contains a comma-separated list of runtime options; auto-skipping namelist is enabled by the option autoskip_namelist or log_autoskip_namelist. The latter option produces an informative message to standard error, displaying where the namelist input occurred, for example:

       [example.f90, line 5: Looking for namelist group NAME, skipping WRONG]

5.2.11 Legacy Application Support

The -dusty option downgrades the category of common errors found in “legacy” software from “Error” to “Warning”, allowing such programs to be compiled and run. (The messages may be suppressed altogether by additionally specifying the -w option.)

This option also effectively provides the extensions of allowing COMMON blocks to be initialised outside of BLOCK DATA, and of accepting VAX format octal and hexadecimal constants (these have the forms '...'O and '...'X respectively).

5.2.12 Mismatched Argument Lists

The -mismatch option downgrades checking of procedure argument lists so that inconsistencies between calls to routines which are not in the current file being processed produce warning messages rather than error messages.

The -mismatch_all option further downgrades argument list checking so that incorrect calls to routines present in the current file being processed produce warning messages instead of error messages.

5.2.13 Double Precision Complex Extensions

Double precision complex entities may be declared with the DOUBLE COMPLEX keywords instead of the standard Fortran ‘Complex(Kind(0d0))’ specification.

If the -dcfuns option has been used, additional intrinsic functions are available (see the documentation of the option for full details). These functions have all been redundant since Fortran 90.


NAG Fortran Compiler, Release 7.1: Intrinsic Modules

 Navigation: Previous Up Next

6 Intrinsic Modules

  • 6.1 Intrinsic Module Overview
  • 6.2 f90_gc
  • 6.3 f90_iostat
  • 6.4 f90_kind
  • 6.5 f90_preconn_io
    • 6.5.1 Procedures
    • 6.5.2 Example
  • 6.6 f90_stat
    • 6.6.1 Parameters
    • 6.6.2 Example
  • 6.7 f90_unix_*
  • 6.8 ieee_*, iso_c_binding, iso_fortran_env


NAG Fortran Compiler, Release 7.1: Intrinsic Module Overview

 Navigation: Previous Up Next

6.1 Intrinsic Module Overview

A number of intrinsic modules are provided that are available for use in programs. An intrinsic module is one that is pre-compiled or built in to the compiler system; several of these are part of Fortran 2003, others are specific to NAG.

The standard intrinsic modules from Fortran 2003 that are available are:

ieee_arithmetic | Special facilities for IEEE floating-point arithmetic
ieee_exceptions | IEEE arithmetic exception handling
ieee_features | IEEE feature control
iso_c_binding | Facilities for interface to C functions
iso_fortran_env | Fortran-specific environmental facilities

The non-standard intrinsic modules supplied by NAG are:

f90_gc | Garbage collector control
f90_iostat | Input/output error codes (source form provided)
f90_kind | Kind number parameters (source form provided)
f90_preconn_io | File preconnection control
f90_stat | STAT= error codes (source form provided)
f90_unix_dir | Unix system functions — directories and files
f90_unix_dirent | Unix system functions — directory reading
f90_unix_env | Unix system functions — environment
f90_unix_errno | Unix system functions — error codes
f90_unix_io | Unix system functions — input/output (incomplete)
f90_unix_proc | Unix system functions — processes

Note that although the above f90_unix_* modules contain Unix-specific functions, in many cases these are also usable on Windows and Mac OS X; a function that is not available can still be called but will return the ENOSYS error code.


NAG Fortran Compiler, Release 7.1: f90_gc

 Navigation: Previous Up Next

6.2 f90_gc

A module is provided for controlling the garbage collector more precisely, called “F90_GC”. It contains the following procedures described below.

In the description of each procedure, an argument whose KIND is denoted by ‘*’ can accept any kind of that type. Other KIND indications use the named parameters from the F90_KIND module; these named parameters are not, however, exported from F90_GC.

SUBROUTINE ENABLE_INCREMENTAL_GC()
Enables incremental garbage collection; once enabled, it cannot be disabled. Full collections will still be performed with a frequency determined by the “Full GC frequency” setting (see GET_FULL_GC_FREQUENCY and SET_FULL_GC_FREQUENCY.

LOGICAL(word) FUNCTION EXPAND_HEAP(N)
INTEGER(*),INTENT(IN) :: N
This function attempts to expand the heap by N blocks (of 4K bytes), returning .TRUE. if and only if it is successful. This is unaffected by the heap expansion setting (see GET_HEAP_EXPANSION and SET_HEAP_EXPANSION).

Note that on some systems this may return a false indication of success as the operating system delays the actual allocation of memory until an attempt is made to use it — at which point the program may be aborted. Therefore this function should not be used to attempt to allocate all the virtual memory on a system.

SUBROUTINE GCOLLECT()
Manually initiates a garbage collection; this is a full collection even if incremental collection has been enabled (see ENABLE_INCREMENTAL_GC). This is not affected by the “GC allowed” setting (see GET_GC_ALLOWED and SET_GC_ALLOWED).

SUBROUTINE GET_BYTES_SINCE_GC(NBYTES)
INTEGER(int32 or int64),INTENT(OUT) :: NBYTES

Returns the number of bytes allocated since the last collection.

SUBROUTINE GET_FREE_BYTES(NBYTES)
INTEGER(int32 or int64),INTENT(OUT) :: NBYTES

Returns a conservative estimate of the number of free bytes in the heap.

SUBROUTINE GET_FULL_GC_FREQUENCY(FREQUENCY)
INTEGER(int16 or int32 or int64),INTENT(OUT) :: FREQUENCY

Returns the number of partial collections that are done between each full collection when incremental collection is enabled (see ENABLE_INCREMENTAL_GC). This has no effect on manual collection (see GCOLLECT) or when incremental collection has not been enabled. The default value in Release 5.2 is 4.

SUBROUTINE GET_GC_ALLOWED(ALLOWED)
LOGICAL(*),INTENT(OUT) :: ALLOWED

Returns the “GC allowed” setting; the default setting is .TRUE.

SUBROUTINE GET_GC_VERBOSITY(VERBOSITY)
INTEGER(*),INTENT(OUT) :: VERBOSITY
Returns the “GC verbosity” level; this has a range of 0-100, and the default level is zero. Increasing the verbosity level increases the number of informational messages producing during garbage collection. In Release 5.2, the only significant verbosity levels are 0 and 10.

SUBROUTINE GET_HEAP_EXPANSION(ALLOWED)
LOGICAL(*),INTENT(OUT) :: ALLOWED

Returns the automatic heap expansion setting; the default setting is .TRUE.. Even when automatic heap expansion is disabled, the heap will still be expanded if that is necessary to satisfy an allocation request.

SUBROUTINE GET_HEAP_SIZE(NBYTES)
INTEGER(int32 or int64),INTENT(OUT) :: NBYTES

Returns the current heap size in bytes, or -1 if the heap size cannot be represented in the integer variable (i.e. if the current heap size is more than 2G bytes and the integer variable is only a 32-bit one).

SUBROUTINE GET_MAX_GC_RETRIES(N_RETRIES)
INTEGER(*),INTENT(OUT) :: N_RETRIES
Returns the maximum number of garbage collections attempted before reporting failure to the caller; if the allocation was not initiated by an ALLOCATE statement with a STAT= clause, this will result in program termination. The default value in Release 5.2 is zero.

SUBROUTINE GET_MAX_HEAP_SIZE(NBYTES)
INTEGER(int32 or int64),INTENT(OUT) :: NBYTES

Returns the maximum heap size setting, or zero if no maximum heap size has been set. The default setting is zero.

INTEGER(int32) FUNCTION NCOLLECTIONS()
Returns the number of garbage collections that have been performed.

SUBROUTINE SET_FULL_GC_FREQUENCY(FREQUENCY)
INTEGER(int16 or int32 or int64),INTENT(IN) :: FREQUENCY

Sets the number of partial garbage collections to be done between each full collection; this has no effect unless incremental collection has been enabled (see ENABLE_INCREMENTAL_GC). A full collection may still be done if there is a substantial increase in the number of in-use blocks.

SUBROUTINE SET_GC_ALLOWED(ALLOWED)
LOGICAL(*),INTENT(IN) :: ALLOWED

Controls the “GC allowed” setting; when this setting is .FALSE., automatic garbage collection is inhibited. This does not affect manual garbage collection (see GCOLLECT).

SUBROUTINE SET_GC_VERBOSITY(VERBOSITY)
INTEGER(*),INTENT(IN) :: VERBOSITY

Sets the verbosity level; the default value is zero, and the range is limited to 0-100. In Release 5.2, the only significant levels are 0 and 10.

SUBROUTINE SET_HEAP_EXPANSION(ALLOWED)
LOGICAL(*),INTENT(IN) :: ALLOWED
Controls whether automatic heap expansion is allowed; if this is .FALSE., automatic heap expansion will only occur if necessary to satisfy an allocation request (normally the heap is expanded when an heuristic determines that it would be advantageous). This does not affect manual heap expansion (see EXPAND_HEAP).

SUBROUTINE SET_MAX_GC_RETRIES(N_RETRIES)
INTEGER(*),INTENT(IN) :: N_RETRIES

Sets the maximum number of garbage collections attempted before reporting out of memory after heap expansion fails (i.e. is refused by the operating system). The default setting in Release 5.2 is zero.

SUBROUTINE SET_MAX_HEAP_SIZE(N)
INTEGER(int32 or int64),INTENT(IN) :: N

Sets the maximum size of the heap to N bytes. This will prevent the heap from automatic expansion beyond the specified limit, and prevent it from automatic expansion entirely if it is already beyond the limit.


NAG Fortran Compiler, Release 7.1: f90_iostat

 Navigation: Previous Up Next

6.3 f90_iostat

This module contains definitions of integer parameters for all the IOSTAT values that can be returned as a result of use of an input/output or data transfer statement.

For example:

USE f90_iostat
INTEGER ios
OPEN (10, FILE='a.b', IOSTAT=iost, STATUS='NEW')
IF (iost==IOERR_NEW_FILE_EXISTS) PRINT *, "File a.b existed already"


NAG Fortran Compiler, Release 7.1: f90_kind

 Navigation: Previous Up Next

6.4 f90_kind

This module contains definitions of integer parameters that can be used as kind numbers. Users wishing to write portable software making use of non-default kinds should USE this module and use the parameters instead of numeric values. For example, users should use LOGICAL(KIND=BYTE) instead of LOGICAL(KIND=1). The available KIND parameters are shown below; their exact meanings (i.e. the values they represent) are implementation dependent.

  INTEGER,PARAMETER :: SINGLE
For REAL and COMPLEX, selects the default real or default complex kind; this is equivalent to leaving the KIND selector off entirely.

  INTEGER,PARAMETER :: DOUBLE
Selects the double precision real kind; this is equivalent to declaring REAL entities using the DOUBLE PRECISION type specifier, to declaring COMPLEX entities using COMPLEX(KIND(0d0)), and to using the exponent letter D on literal constants.

  INTEGER,PARAMETER :: QUAD
REAL/COMPLEX kind selector for real and complex types with approximately twice the precision of DOUBLE. This might not be available on some systems; on a system without this type, the value of this parameter will be negative.

  INTEGER,PARAMETER :: REAL16
REAL/COMPLEX kind selector for real and complex types that are represented using 16-bit floating-point numbers.

  INTEGER,PARAMETER :: REAL32
REAL/COMPLEX kind selector for real and complex types that are represented using 32-bit floating-point numbers.

  INTEGER,PARAMETER :: REAL64
REAL/COMPLEX kind selector for real and complex types that are represented using 64-bit floating-point numbers.

  INTEGER,PARAMETER :: REAL64x2
REAL/COMPLEX kind selector for real and complex types that are represented using “double-double” floating-point numbers. A double-double floating-point number consists of two 64-bit values, one of which is at least DIGITS(1._REAL64) smaller than the other; this has almost twice the precision of REAL64 (except when near zero), but a smaller exponent range.

This type is not available on all systems; on a system without this type, the value of this parameter is −1.

  INTEGER,PARAMETER :: REAL128

REAL/COMPLEX kind selector for real and complex types that are represented using 128-bit floating-point numbers. This will select a “true 128-bit” floating-point type if one is available, and if not it will select a “double-double” floating-point type if that is available; if no 128-bit floating-point type is available the value of this parameter is -1.

  INTEGER,PARAMETER :: INT8
INTEGER kind selector for integer types with at least 8 bits of precision.

  INTEGER,PARAMETER :: INT16
INTEGER kind selector for integer types with at least 16 bits of precision.

  INTEGER,PARAMETER :: INT32
INTEGER kind selector for integer types with at least 32 bits of precision.

  INTEGER,PARAMETER :: INT64
INTEGER kind selector for integer types with at least 64 bits of precision.

  INTEGER,PARAMETER :: BYTE
LOGICAL kind selector for logical types occupying only one byte of memory.

  INTEGER,PARAMETER :: TWOBYTE
LOGICAL kind selector for logical types occupying the same space as INTEGER(INT16) entities.

  INTEGER,PARAMETER :: WORD
LOGICAL kind selector for a 32-bit logical type.

  INTEGER,PARAMETER :: LOGICAL64
LOGICAL kind selector for a 64-bit logical type.
  INTEGER,PARAMETER :: ASCII
CHARACTER kind selector for the ASCII character set.
  INTEGER,PARAMETER :: JIS
CHARACTER kind selector for the JIS X 0213:2004 character set.
  INTEGER,PARAMETER :: UCS2
CHARACTER kind selector for the UCS-2 (Unicode) character set.
  INTEGER,PARAMETER :: UCS4
CHARACTER kind selector for the UCS-4 (ISO 10646) character set.


NAG Fortran Compiler, Release 7.1: f90_preconn_io

 Navigation: Previous Up Next

6.5 f90_preconn_io

This module enables alteration of the default values used by automatically preconnected files.

6.5.1 Procedures

Note that in the descriptions below, LOGICAL(*) means any kind of LOGICAL. Also, note that although the VERBOSE argument is an optional argument, the actual argument is not permitted to be a non-present optional dummy argument.

SUBROUTINE GET_PCIO_OPTIONS(BLANK,POSITION,PREFIX,VERBOSE)
CHARACTER(*),OPTIONAL,INTENT(OUT) :: BLANK,POSITION,PREFIX
LOGICAL(*),OPTIONAL,INTENT(OUT) :: VERBOSE

Returns the current settings for file preconnection; the meanings for these settings are described under the IOINIT routine. Both the BLANK and POSITION values are returned in upper case, even if lower case was used in a call to IOINIT to set them.

SUBROUTINE IOINIT(BLANK,POSITION,PREFIX,VERBOSE)
CHARACTER(*),OPTIONAL,INTENT(IN) :: BLANK,POSITION,PREFIX
LOGICAL(*),OPTIONAL,INTENT(IN) :: VERBOSE

This procedure controls automatic file preconnection. Files can be automatically preconnected when a logical unit is initially referenced without an OPEN statement; preconnection does not occur again after file CLOSE.

The name of the file to be preconnected is determined first by searching for an environment variable of the form FORT nn where nn is the two-digit logical unit number; e.g. FORT03. If this environment variable is found its value is used as the filename; otherwise the name “fort.n” is used; e.g. ‘fort.3’. The file is opened either with FORM='FORMATTED' or FORM='UNFORMATTED' depending on whether the initial reference is with a formatted or unformatted i/o statement.

The BLANK and POSITION arguments control the BLANK= and
POSITION= keywords in the implied OPEN statement when the file is
preconnected;
initially these are set to BLANK='NULL' and POSITION='REWIND'.
Note that these have no meaning (and no effect) for unformatted files.

The PREFIX argument changes the prefix used to find the environment variable containing the preconnected file name. Initially this is ‘FORT’. Only the first 30 characters of PREFIX are used.

The VERBOSE argument controls activity reporting; if it is .TRUE., subsequent preconnection activity will produce informative messages on the standard error unit.

6.5.2 Example

   USE F90_PRECONN_IO
   CALL IOINIT(BLANK='ZERO',PREFIX='MYFILE')
   READ (99,10) I,J,K,L,M
10 FORMAT(I3,I1,I3,I1,I3)
When the READ statement is executed, the environment variable MYFILE99 is interrogated to discover which file is to be automatically preconnected to unit 99. The unit will be connected with BLANK='ZERO'. If no environment variable is found the file ‘fort.99’ will be opened.


NAG Fortran Compiler, Release 7.1: f90_stat

 Navigation: Previous Up Next

6.6 f90_stat

This module contains definitions of integer parameters for all the STAT= values that can be returned as a result of use of an ALLOCATE or DEALLOCATE statement.

6.6.1 Parameters

  INTEGER,PARAMETER :: STAT_ALREADY_ALLOCATED
An allocatable variable in an ALLOCATE statement is already currently allocated.

  INTEGER,PARAMETER :: STAT_MEMORY_LIMIT_EXCEEDED
An allocation in an ALLOCATE statement requested more memory than the limit in this version of the NAG Fortran compiler.

  INTEGER,PARAMETER :: STAT_NO_MEMORY
Insufficient free memory available to satisfy the requested allocation.

  INTEGER,PARAMETER :: STAT_NOT_ALLOCATED
An allocatable variable in a DEALLOCATE statement is not currently allocated.

  INTEGER,PARAMETER :: STAT_NOT_ASSOCIATED
A pointer in a DEALLOCATE statement is disassociated.

  INTEGER,PARAMETER :: STAT_PART_OF_A_LARGER_OBJECT
A pointer in a DEALLOCATE statement refers to part of a larger object.

  INTEGER,PARAMETER :: STAT_POINTER_UNDEFINED
A pointer in a DEALLOCATE statement is undefined. (This value is never returned to the user program, which is always immediately terminated if the use of an undefined pointer is detected.)

  INTEGER,PARAMETER :: STAT_WRONG_COLOUR
A pointer in a DEALLOCATE statement is associated with a target that was not created by pointer allocation.

6.6.2 Example

USE f90_stat
REAL,ALLOCATABLE :: big(:,:,:)
INTEGER :: status
ALLOCATE(big(100,1024,1024),STAT=status)
IF (status==STAT_NO_MEMORY) PRINT *,'Out of memory'


NAG Fortran Compiler, Release 7.1: f90_unix_*

 Navigation: Previous Up Next

6.7 f90_unix_*

These modules are described in the next part, Modern Fortran API to Posix.


NAG Fortran Compiler, Release 7.1: ieee_*, iso_c_binding, iso_fortran_env

 Navigation: Previous Up Next

6.8 ieee_*, iso_c_binding, iso_fortran_env

These modules are described in the Fortran 2003 Extensions part, under 10.6 IEEE arithmetic support, 10.5.1 The ISO_C_BINDING module and 10.8.5 The ISO_FORTRAN_ENV module respectively.


NAG Fortran Compiler, Release 7.1: Modern Fortran API to Posix

 Navigation: Previous Up Next

7 Modern Fortran API to Posix

  • 7.1 Posix Module Overview
  • 7.2 f90_unix_dir
    • 7.2.1 Parameters
    • 7.2.2 Procedures
  • 7.3 f90_unix_dirent
    • 7.3.1 Procedures
  • 7.4 f90_unix_env
    • 7.4.1 Parameters
    • 7.4.2 Types
    • 7.4.3 Procedures
  • 7.5 f90_unix_errno
    • 7.5.1 Error Handling
    • 7.5.2 Parameters
  • 7.6 f90_unix_file
    • 7.6.1 Parameters
    • 7.6.2 Types
    • 7.6.3 Procedures
  • 7.7 f90_unix_io
    • 7.7.1 Procedures
  • 7.8 f90_unix_proc
    • 7.8.1 Parameters
    • 7.8.2 Procedures


NAG Fortran Compiler, Release 7.1: Posix Module Overview

 Navigation: Previous Up Next

7.1 Posix Module Overview

The following modules are provided by NAG as a partial interface to the operating system facilities defined by ISO/IEC 9945-1:1990 Portable Operating System Interface (POSIX) -- Part 1: System Application Program Interface (API) [C Language].

f90_unix_dir | Directories and Files
f90_unix_dirent | Directory Reading
f90_unix_env | Environment
f90_unix_errno | Error Codes
f90_unix_file | File Characteristics
f90_unix_io | Input/Output (incomplete)
f90_unix_proc | Processes


NAG Fortran Compiler, Release 7.1: f90_unix_dir

 Navigation: Previous Up Next

7.2 f90_unix_dir

This module contains part of a Fortran API to functions detailed in ISO/IEC 9945-1:1990 Portable Operating System Interface (POSIX) - Part 1: System Application Program Interface (API) [C Language].

The procedures in this module are from sections 5.2: Working Directory, 5.3.3 Set File Creation Mask, 5.3.4 Link to a File, 5.4 Special File Creation and 5.5 File Removal.

Error handling is described in F90_UNIX_ERRNO. Note that for procedures with an optional ERRNO argument, if an error occurs and ERRNO is not present, the program will be terminated.

All the procedures in this module are both generic and specific.

7.2.1 Parameters

  INTEGER,PARAMETER :: MODE_KIND
The integer kind used to represent file permissions (see ISO/IEC 9945-1). Parameters for specific permissions are contained in F90_UNIX_FILE.

7.2.2 Procedures

  SUBROUTINE CHDIR(PATH,ERRNO)
  CHARACTER(*),INTENT(IN) :: PATH
  INTEGER(error_kind),OPTIONAL,INTENT(OUT) :: ERRNO
Sets the current working directory to PATH. Note that any trailing blanks in PATH may be significant. If ERRNO is present it receives the error status.

Possible error conditions include EACCES, ENAMETOOLONG, ENOTDIR and ENOENT (see F90_UNIX_ERRNO).

  SUBROUTINE GETCWD(PATH,LENPATH,ERRNO)
  CHARACTER(*),OPTIONAL,INTENT(OUT) :: PATH
  INTEGER(int32),OPTIONAL,INTENT(OUT) :: LENPATH
  INTEGER(error_kind),OPTIONAL,INTENT(OUT) :: ERRNO
Accesses the current working directory information. If PATH is present, it receives the name of the current working directory, blank-padded or truncated as appropriate if the length of the current working directory name differs from that of PATH. If LENPATH is present, it receives the length of the current working directory name. If ERRNO is present it receives the error status.

If neither PATH nor LENPATH is present, error EINVAL is raised. If the path to current working directory cannot be searched, error EACCES is raised. If PATH is present and LENPATH is not present, and PATH is shorter than the current working directory name, error ERANGE is raised. (See F90_UNIX_ERRNO).

  SUBROUTINE LINK(EXISTING,NEW,ERRNO)
  CHARACTER(*),INTENT(IN) :: EXISTING,NEW
  INTEGER(error_kind),OPTIONAL,INTENT(OUT) :: ERRNO
Creates a new link (with name given by NEW) for an existing file (named by EXISTING).

Possible errors include EACCES, EEXIST, EMLINK, ENAMETOOLONG, ENOENT, ENOSPC, ENOTDIR, EPERM, EROFS, EXDEV (see F90_UNIX_ERRNO).

  SUBROUTINE MKDIR(PATH,MODE,ERRNO)
  CHARACTER(*),INTENT(IN) :: PATH
  INTEGER(mode_kind),INTENT(IN) :: MODE
  INTEGER(error_kind),OPTIONAL,INTENT(OUT) :: ERRNO
Creates a new directory with name given by PATH and mode MODE (see F90_UNIX_FILE for mode values). Note that any trailing blanks in PATH may be significant.

Possible errors include EACCES, EEXIST, EMLINK, ENAMETOOLONG, ENOENT, ENOSPC, ENOTDIR and EROFS (see F90_UNIX_ERRNO).

  SUBROUTINE MKFIFO(PATH,MODE,ERRNO)
  CHARACTER(*),INTENT(IN) :: PATH
  INTEGER(mode_kind),INTENT(IN) :: MODE
  INTEGER(error_kind),OPTIONAL,INTENT(OUT) :: ERRNO
Creates a new FIFO special file with name given by PATH and mode MODE. Note that any trailing blanks in PATH may be significant. Possible errors include EACCES, EEXIST, ENAMETOOLONG, ENOENT, ENOSPC, ENOTDIR and EROFS (see F90_UNIX_ERRNO).
  SUBROUTINE RENAME(OLD,NEW,ERRNO)
  CHARACTER(*),INTENT(IN) :: OLD
  CHARACTER(*),INTENT(IN) :: NEW
  INTEGER(error_kind),OPTIONAL,INTENT(OUT) :: ERRNO
Changes the name of the file OLD to NEW. Any existing file NEW is first removed. Note that any trailing blanks in OLD or NEW may be significant.

Possible errors include EACCES, EBUSY, EEXIST, ENOTEMPTY, EINVAL, EISDIR, ENAMETOOLONG, EMLINK, ENOENT, ENOSPC, ENOTDIR, EROFS and EXDEV (see F90_UNIX_ERRNO).

  SUBROUTINE RMDIR(PATH,ERRNO)
  CHARACTER(*),INTENT(IN) :: PATH
  INTEGER(error_kind),OPTIONAL,INTENT(OUT) :: ERRNO
Removes the directory PATH. Note that any trailing blanks in PATH may be significant.

Possible errors include EACCES, EBUSY, EEXIST, ENOTEMPTY, ENAMETOOLONG, ENOENT, ENOTDIR and EROFS (see F90_UNIX_ERRNO).

  SUBROUTINE UMASK(CMASK,PMASK)
  INTEGER(mode_kind),INTENT(IN) :: CMASK
  INTEGER(mode_kind),OPTIONAL,INTENT(OUT) :: PMASK
Sets the file mode creation mask of the calling process to CMASK. If PMASK is present it receives the previous value of the mask.

  SUBROUTINE UNLINK(PATH,ERRNO)
  CHARACTER(*),INTENT(IN) :: PATH
  INTEGER(error_kind),OPTIONAL,INTENT(OUT) :: ERRNO
Deletes the file PATH. Note that any trailing blanks in PATH may be significant. Possible errors include EACCES, EBUSY, ENAMETOOLONG, ENOENT, ENOTDIR, EPERM and EROFS (see F90_UNIX_ERRNO).


NAG Fortran Compiler, Release 7.1: f90_unix_dirent

 Navigation: Previous Up Next

7.3 f90_unix_dirent

This module contains part of a Fortran API to functions detailed in ISO/IEC 9945-1:1990 Portable Operating System Interface (POSIX) - Part 1: System Application Program Interface (API) [C Language].

The functions in this module are from Section 5.1.2: Directory Operations

Error handling is described in F90_UNIX_ERRNO. Note that for procedures with an optional ERRNO argument, if an error occurs and ERRNO is not present, the program will be terminated.

All the procedures in this module are specific and not generic.

7.3.1 Procedures

In the description of each procedure, an argument whose KIND is denoted by ‘*’ can accept any kind of that type. Other KIND indications use the named parameters from the F90_KIND or F90_UNIX_ERRNO modules; these named parameters are not, however, exported from F90_UNIX_DIRENT.

  SUBROUTINE CLOSEDIR(DIRUNIT,ERRNO)
  INTEGER(*),INTENT(IN) :: DIRUNIT
  INTEGER(error_kind),OPTIONAL,INTENT(OUT) :: ERRNO
Close a directory stream that was opened by OPENDIR.

If DIRUNIT does not refer to an open directory stream, error EBADF (see F90_UNIX_ERRNO) is raised.

  SUBROUTINE OPENDIR(DIRNAME,DIRUNIT,ERRNO)
  CHARACTER(*),INTENT(IN) :: DIRNAME
  INTEGER(*),INTENT(OUT) :: DIRUNIT
  INTEGER(error_kind),OPTIONAL,INTENT(OUT) :: ERRNO
Opens a directory stream, returning a handle to it in DIRUNIT.

Possible errors include EACCES, ENAMETOOLONG, ENOENT, ENOTDIR, EMFILE and ENFILE (see F90_UNIX_ERRNO).

  SUBROUTINE READDIR(DIRUNIT,NAME,LENNAME,ERRNO)
  INTEGER(*),INTENT(IN) :: DIRUNIT
  CHARACTER(*),INTENT(OUT) :: NAME
  INTEGER(int32 or int64),INTENT(OUT) :: LENNAME
  INTEGER(error_kind),OPTIONAL,INTENT(OUT) :: ERRNO

Reads the first/next directory entry. The name of the file is placed into NAME, blank-padded or truncated as appropriate if the length of the file name differs from LEN(NAME). The length of the file name is placed in LENNAME.

If there are no more directory entries, NAME is unchanged and LENNAME is negative.

If DIRUNIT is not a directory stream handle produced by OPENDIR, or has been closed by CLOSEDIR, error EBADF (see F90_UNIX_ERRNO) is raised.

  SUBROUTINE REWINDDIR(DIRUNIT,ERRNO)
  INTEGER(*),INTENT(IN) :: DIRUNIT
  INTEGER(error_kind),OPTIONAL,INTENT(OUT) :: ERRNO
Rewinds the directory stream so that the next call to READDIR on that stream will return the name of the first file in the directory.


NAG Fortran Compiler, Release 7.1: f90_unix_env

 Navigation: Previous Up Next

7.4 f90_unix_env

This module contains part of a Fortran API to functions detailed in ISO/IEC 9945-1:1990 Portable Operating System Interface (POSIX) - Part 1: System Application Program Interface (API) [C Language].

The functions in this module are from Section 4: Process Environment, plus gethostname from 4.3BSD.

Error handling is described in F90_UNIX_ERRNO. Note that for procedures with an optional ERRNO argument, if an error occurs and ERRNO is not present, the program will be terminated.

All the procedures in this module are generic; some are also specific (this may change in a future release).

7.4.1 Parameters

INTEGER(int32),PARAMETER :: clock_tick_kind
The integer kind used for clock ticks (see TIMES).

INTEGER(int32),PARAMETER :: id_kind
Integer kind for representing IDs; that is, users (uids), groups (gids), process groups (pgids) and processes (pids).

INTEGER(int32),PARAMETER :: long_kind
The integer kind corresponding to the C type ‘long’. This is not actually used in this module, but is suitable for use when declaring a variable to receive a value from SYSCONF.

INTEGER(int32),PARAMETER :: sc_stdin_unit, sc_stdout_unit, sc_stderr_unit,
    sc_arg_max, sc_child_max, sc_clk_tck, sc_job_control, sc_open_max,
    sc_ngroups_max, sc_saved_ids, sc_stream_max, sc_tzname_max, sc_version
Values used as arguments to SYSCONF. The following table describes the returned information from SYSCONF, this is not the value of the SC_* constant.
SC_STDIN_UNIT
The logical unit number for standard input (READ *,...); this is the same value as INPUT_UNIT in the standard intrinsic module ISO_FORTRAN_ENV.
SC_STDOUT_UNIT
The logical unit number for standard output (PRINT, WRITE(*,...)); this is the same value as OUTPUT_UNIT in the standard intrinsic module ISO_FORTRAN_ENV.
SC_STDERR_UNIT
The logical unit number on which errors are reported; this is the same value as ERROR_UNIT in the standard intrinsic module ISO_FORTRAN_ENV.
SC_ARG_MAX
Maximum length of arguments for the EXEC functions, in bytes, including environment data.
SC_CHILD_MAX
Maximum number of simultaneous processes for a single user.
SC_CLK_TCK
Number of clock ticks per second. (This is the same value returned by the CLK_TCK function).
SC_JOB_CONTROL
Value available only if job control is supported by the operating system.
SC_NGROUPS_MAX
Maximum number of simultaneous supplementary group IDs per process.
SC_OPEN_MAX
Maximum number of files open simultaneously by a single process.
SC_SAVED_IDS
Value available only if each process has a saved set-uid and set-gid.
SC_STREAM_MAX
Maximum number of logical units that can be simultaneously open. Not always available.
SC_TZNAME_MAX
Maximum number of characters for the name of a time zone.
SC_VERSION
Posix version number. This will be 199009 if the underlying operating system's C interface conforms to ISO/IEC 9945-1:1990.

INTEGER(int32),PARAMETER :: time_kind
The integer kind used for holding date/time values (see TIME).

7.4.2 Types

TYPE tms
    INTEGER(clock_tick_kind) utime, stime, cutime, cstime
END TYPE
Derived type holding CPU usage time in clock ticks. UTIME and STIME contain CPU time information for a process, CUTIME and CSTIME contain CPU time information for its terminated child processes. In each case this is divided into user time (UTIME, CUTIME) and system time (STIME, CSTIME).

TYPE utsname
    CHARACTER(...) sysname, nodename, release, version, machine
END TYPE
Derived type holding data returned by UNAME. Note that the character length of each component is fixed, but may be different on different systems. The values in these components are blank-padded (if short) or truncated (if long). For further information see ISO/IEC 9945-1:1990.

7.4.3 Procedures

PURE INTEGER(KIND=clock_tick_kind) FUNCTION clk_tck()
Returns the number of clock ticks in one second of CPU time (see TIMES).

PURE SUBROUTINE ctermid(s,lens)
    CHARACTER(*),OPTIONAL,INTENT(OUT) :: s
    INTEGER(int32),OPTIONAL,INTENT(OUT) :: lens
If present, S is set to the filename of the controlling terminal. If present, LENS is set to the length of the filename of the controlling terminal. If S is longer than the filename of the controlling terminal it is padded with blanks; if S is shorter it is truncated — it is the user's responsibility to check the value of LENS to detect such truncation.

If the filename of the controlling terminal cannot be determined for any reason LENS (if present) will be set to zero and S (if present) will be blank.

SUBROUTINE getarg(k,arg,lenarg,errno)
    INTEGER(*),INTENT(IN) :: k
    CHARACTER(*),OPTIONAL,INTENT(OUT) :: arg
    INTEGER(int32),OPTIONAL,INTENT(OUT) :: lenarg
    INTEGER(error_kind),OPTIONAL,INTENT(OUT) :: errno
Accesses command-line argument number K, where argument zero is the program name. If ARG is present, it receives the argument text (blank-padded or truncated as appropriate if the length of the argument differs from that of ARG). If LENARG is present, it receives the length of the argument. If ERRNO is present, it receives the error status.

Note that if K is less than zero or greater than the number of arguments (returned by IARGC) error EINVAL (see F90_UNIX_ERRNO) is raised.

This procedure is very similar to the standard intrinsic procedure GET_COMMAND_ARGUMENT.

  PURE INTEGER(id_kind) FUNCTION getegid()
Returns the effective group number of the calling process.

SUBROUTINE getenv(name,value,lenvalue,errno)
    CHARACTER(*),INTENT(IN) :: name
    CHARACTER(*),OPTIONAL,INTENT(OUT) :: value
    INTEGER(int32),OPTIONAL,INTENT(OUT) :: lenvalue
    INTEGER(error_kind),OPTIONAL,INTENT(OUT) :: errno
Accesses the environment variable named by NAME. If VALUE is present, it receives the text value of the variable (blank-padded or truncated as appropriate if the length of the value differs from that of VALUE). If LENVALUE is present, it receives the length of the value. If ERRNO is present, it receives the error status.

If there is no such variable, error EINVAL (see F90_UNIX_ERRNO) is raised. Other possible errors include ENOMEM.

PURE INTEGER(id_kind) FUNCTION geteuid()
Returns the effective user number of the calling process.

PURE INTEGER(id_kind) FUNCTION getgid()
Returns the group number of the calling process.

SUBROUTINE getgroups(grouplist,ngroups,errno)
    INTEGER(id_kind),OPTIONAL,INTENT(OUT) :: grouplist(:)
    INTEGER(int32),OPTIONAL,INTENT(OUT) :: ngroups
    INTEGER(error_kind),OPTIONAL,INTENT(OUT) :: errno
Retrieves supplementary group number information for the calling process. If GROUPLIST is present, it is filled with the supplementary group numbers. If NGROUPS is present, it receives the number of supplementary group numbers. If ERRNO is present, it receives the error status.

If GROUPLIST is present but too small to contain the complete list of supplementary group numbers, error EINVAL (see F90_UNIX_ERRNO) is raised. The maximum number of supplementary group numbers can be found using SYSCONF (enquiry SC_NGROUPS_MAX); alternatively, ‘CALL GETGROUPS(NGROUPS=N)’ will reliably return the actual number in use.

PURE SUBROUTINE gethostname(name,lenname)
    CHARACTER(*),OPTIONAL,INTENT(OUT) :: name
    INTEGER(int32),OPTIONAL,INTENT(OUT) :: lenname
This provides the functionality of 4.3BSD's gethostname. If NAME is present it receives the text of the standard host name for the current processor, blank-padded or truncated if appropriate. If LENNAME is present it receives the length of the host name. If no host name is available LENNAME will be zero.

PURE SUBROUTINE getlogin(s,lens)
    CHARACTER(*),OPTIONAL,INTENT(OUT) :: s
    INTEGER(int32),OPTIONAL,INTENT(OUT) :: lens
Accesses the user name (login name) associated with the calling process. If S is present, it receives the text of the name (blank-padded or truncated as appropriate if the length of the login name differs from that of S). If LENS is present, it receives the length of the login name.

PURE INTEGER(id_kind) FUNCTION getpgrp()
Returns the process group number of the calling process.

PURE INTEGER(id_kind) FUNCTION getpid()
Returns the process number of the calling process.

PURE INTEGER(id_kind) FUNCTION getppid()
Returns the process number of the parent of the calling process.

PURE INTEGER(id_kind) FUNCTION getuid()
Returns the user number of the calling process.

PURE INTEGER(int32) FUNCTION iargc()
Returns the number of command-line arguments; this is the same value as the intrinsic function COMMAND_ARGUMENT_COUNT, except that it returns -1 if even the program name is unavailable (the intrinsic function erroneously returns the same value, 0, whether the program name is available or not).
SUBROUTINE isatty(lunit,answer,errno)
    INTEGER(*),INTENT(IN) :: lunit
    LOGICAL(*),INTENT(OUT) :: answer
    INTEGER(error_kind),OPTIONAL,INTENT(OUT) :: errno
ANSWER receives the value .TRUE. if and only if the logical unit identified by LUNIT is connected to a terminal.

If LUNIT is not a valid unit number or is not connected to any file, error EBADF (see F90_UNIX_ERRNO) is raised.

SUBROUTINE setgid(gid,errno)
    INTEGER(*),INTENT(IN) :: gid
    INTEGER(error_kind),OPTIONAL,INTENT(OUT) :: errno
Sets the group number of the calling process to GID. For full details refer to section 4.2.2 of ISO/IEC 9945-1:1990.

If GID is not a valid group number, error EINVAL (see F90_UNIX_ERRNO) is raised. If the process is not allowed to set the group number to GID, error EPERM is raised.

SUBROUTINE setpgid(pid,pgid,errno)
    INTEGER(*),INTENT(IN) :: pid, pgid
    INTEGER(error_kind),OPTIONAL,INTENT(OUT) :: errno
Sets the process group number of process PID (or, if PID is zero, the calling process) to PGID. For full details refer to section 4.3.3 of ISO/IEC 9945-1:1990.

Possible errors include EACCES, EINVAL, ENOSYS, EPERM, ESRCH (see F90_UNIX_ERRNO).

SUBROUTINE setsid(sid,errno)
    INTEGER(id_kind),OPTIONAL,INTENT(OUT) :: sid
    INTEGER(error_kind),OPTIONAL,INTENT(OUT) :: errno
Creates a session and sets the process group number of the calling process. For full details refer to section 4.3.2 of ISO/IEC 9945-1:1990. If SID is present it receives the new session id (equal to the process id); if an error occurs it receives -1.

Possible errors include EPERM (see F90_UNIX_ERRNO).

SUBROUTINE setuid(uid,errno)
    INTEGER(*),INTENT(IN) :: uid
    INTEGER(error_kind),OPTIONAL,INTENT(OUT) :: errno
Sets the user number of the calling process to UID. For full details refer to section 4.2.2 of ISO/IEC 9945-1:1990.

If UID is not a valid group number, error EINVAL (see F90_UNIX_ERRNO) is raised. If the process is not allowed to set the user number to UID, error EPERM is raised.

SUBROUTINE sysconf(name,val,errno)
    INTEGER(*),INTENT(IN) :: name
    INTEGER(*),INTENT(OUT) :: val
    INTEGER(error_kind),OPTIONAL,INTENT(OUT) :: errno
Returns the value of a system configuration variable. The variables are named by integer PARAMETERs defined in this module, and are described in the Parameters section.

If NAME is not a valid configuration variable name, error EINVAL (see F90_UNIX_ERRNO) is raised. If VAL is too small an integer kind to contain the result, error ERANGE is raised; kind LONG_KIND is guaranteed to be big enough for all values.

SUBROUTINE time(itime,errno)
    INTEGER(time_kind),INTENT(OUT) :: itime
    INTEGER(error_kind),OPTIONAL,INTENT(OUT) :: errno
ITIME receives the operating system date/time in seconds since the Epoch.

INTEGER(KIND=clock_tick_kind) FUNCTION times(buffer)
    TYPE(tms),INTENT(OUT) :: buffer
This function returns the elapsed real time in clock ticks since an arbitrary point in the past, or -1 if the function is unavailable. BUFFER is filled in with CPU time information for the calling process and any terminated child processes.

If this function returns zero the values in BUFFER will still be correct but the elapsed-time timer was not available.

SUBROUTINE ttyname(lunit,s,lens,errno)
    INTEGER(*),INTENT(IN) :: lunit
    CHARACTER(*),OPTIONAL,INTENT(OUT) :: s
    INTEGER(int32),OPTIONAL,INTENT(OUT) :: lens
    INTEGER(error_kind),OPTIONAL,INTENT(OUT) :: errno
Accesses the name of the terminal connected to the logical unit identified by LUNIT. If S is present, it receives the text of the terminal name (blank-padded or truncated as appropriate, if the length of the terminal name differs from that of S). If LENS is present, it receives the length of the terminal name. If ERRNO is present, it receives the error status.

If LUNIT is not a valid logical unit number, or is not connected, error EBADF (see F90_UNIX_ERRNO) is raised; otherwise, if the function is not available, ENOSYS is raised, or if LUNIT is not connected to a terminal, error ENOTTY is raised.

SUBROUTINE uname(name,errno)
    TYPE(UTSNAME),INTENT(OUT) :: name
    INTEGER(error_kind),OPTIONAL,INTENT(OUT) :: errno
Returns information about the operating system in NAME.


NAG Fortran Compiler, Release 7.1: f90_unix_errno

 Navigation: Previous Up Next

7.5 f90_unix_errno

This module contains part of a Fortran API to functions detailed in ISO/IEC 9945-1:1990 Portable Operating System Interface (POSIX) - Part 1: System Application Program Interface (API) [C Language].

The facilities in this module are from Section 2.4 Error Numbers.

7.5.1 Error Handling

Many procedures provided by the F90_UNIX_* modules have an optional ERRNO argument, declared as

INTEGER(error_kind),OPTIONAL,INTENT(OUT)
If this argument is provided it receives the error status from the procedure; zero indicates successful completion, otherwise it will be a non-zero error code, usually one of the ones listed in this module.

If the ERRNO argument is omitted and an error condition is raised, the program will be terminated with an informative error message.

If a procedure has no ERRNO argument it indicates that no error condition is possible - the procedure always succeeds.

7.5.2 Parameters

All parameters are of type INTEGER with kind ERROR_KIND. The following table lists the error message typically associated with each error code; for full details see ISO/IEC 9945-1:1990, either section 2.4 or the appropriate section for the function raising the error.

E2BIG | Arg list too long
EACCES | Permission denied
EAGAIN | Resource temporarily unavailable
EBADF | Bad file descriptor
EBUSY | Resource busy
ECHILD | No child process
EDEADLK | Resource deadlock avoided
EDOM | Domain error
EEXIST | File exists
EFAULT | Bad address
EFBIG | File too large
EINTR | Interrupted function call
EINVAL | Invalid argument
EIO | Input/Output error
EISDIR | Is a directory
EMFILE | Too many open files
EMLINK | Too many links
ENAMETOOLONG | Filename too long
ENFILE | Too many open files in system
ENODEV | No such device
ENOENT | No such file or directory
ENOEXEC | Exec format error
ENOLCK | No locks available
ENOMEM | Not enough space
ENOSPC | No space left on device
ENOSYS | Function not implemented
ENOTDIR | Not a directory
ENOTEMPTY | Directory not empty
ENOTTY | Inappropriate I/O control operation
ENXIO | No such device or address
EPERM | Operation not permitted
EPIPE | Broken pipe
ERANGE | Result too large
EROFS | Read-only file system
ESPIPE | Invalid seek
ESRCH | No such process
EXDEV | Improper link


NAG Fortran Compiler, Release 7.1: f90_unix_file

 Navigation: Previous Up Next

7.6 f90_unix_file

This module contains part of a Fortran API to functions detailed in ISO/IEC 9945-1:1990 Portable Operating System Interface (POSIX) - Part 1: System Application Program Interface (API) [C Language].

The functions in this module are from Section 5.6 File Characteristics.

Error handling is described in F90_UNIX_ERRNO. Note that for procedures with an optional ERRNO argument, if an error occurs and ERRNO is not present, the program will be terminated.

All the procedures in this module are generic; some may be specific but this is subject to change in a future release.

7.6.1 Parameters

INTEGER(int32),PARAMETER :: F_OK
Flag for requesting file existence check (see ACCESS).

USE F90_UNIX_ENV,ONLY:ID_KIND
See F90_UNIX_ENV for a description of this parameter.

USE F90_UNIX_DIR,ONLY:MODE_KIND
See F90_UNIX_DIR for a description of this parameter.

INTEGER(int32),PARAMETER :: R_OK
Flag for requesting file readability check (see ACCESS).

INTEGER(MODE_KIND),PARAMETER :: S_IRGRP
File mode bit indicating group read permission (see STAT_T).

INTEGER(MODE_KIND),PARAMETER :: S_IROTH
File mode bit indicating other read permission (see STAT_T).

INTEGER(MODE_KIND),PARAMETER :: S_IRUSR
File mode bit indicating user read permission (see STAT_T).

INTEGER(MODE_KIND),PARAMETER :: S_IRWXG
Mask to select the group accessibility bits from a file mode (see STAT_T).

INTEGER(MODE_KIND),PARAMETER :: S_IRWXO
Mask to select the other accessibility bits from a file mode (see STAT_T).

INTEGER(MODE_KIND),PARAMETER :: S_IRWXU
Mask to select the user accessibility bits from a file mode (see STAT_T).

INTEGER(MODE_KIND),PARAMETER :: S_ISGID
File mode bit indicating that the file is set-group-ID (see STAT_T).

INTEGER(MODE_KIND),PARAMETER :: S_ISUID
File mode bit indicating that the file is set-user-ID (see STAT_T).

INTEGER(MODE_KIND),PARAMETER :: S_IWGRP
File mode bit indicating group write permission (see STAT_T).

INTEGER(MODE_KIND),PARAMETER :: S_IWOTH
File mode bit indicating other write permission (see STAT_T).

INTEGER(MODE_KIND),PARAMETER :: S_IWUSR
File mode bit indicating user write permission (see STAT_T).

INTEGER(MODE_KIND),PARAMETER :: S_IXGRP
File mode bit indicating group execute permission (see STAT_T).

INTEGER(MODE_KIND),PARAMETER :: S_IXOTH
File mode bit indicating other execute permission (see STAT_T).

INTEGER(MODE_KIND),PARAMETER :: S_IXUSR
File mode bit indicating user execute permission (see STAT_T).

USE F90_UNIX_ENV,ONLY :: TIME_KIND
See F90_UNIX_ENV for a description of this parameter.

INTEGER(int32),PARAMETER :: W_OK
Flag for requesting file writability check (see ACCESS).

INTEGER(int32),PARAMETER :: X_OK
Flag for requesting file executability check (see ACCESS).

7.6.2 Types

TYPE stat_t
    INTEGER(MODE_KIND) st_mode
    INTEGER(...) st_ino
    INTEGER(...) st_dev
    INTEGER(...) st_nlink
    INTEGER(id_kind) st_uid
    INTEGER(id_kind) st_gid
    INTEGER(...) st_size
    INTEGER(TIME_KIND) st_atime, st_mtime, st_ctime
END TYPE
Derived type holding file characteristics.
ST_MODE
File mode (read/write/execute permission for user/group/other, plus set-group-ID and set-user-ID bits).
ST_INO
File serial number.
ST_DEV
ID for the device on which the file resides.
ST_NLINK
The number of links (see F90_UNIX_DIR, LINK operation) to the file.
ST_UID
User number of the file's owner.
ST_GID
Group number of the file.
ST_SIZE
File size in bytes (regular files only).
ST_ATIME
Time of last access.
ST_MTIME
Time of last modification.
ST_CTIME
Time of last file status change.

TYPE UTIMBUF
    INTEGER(time_kind) actime, modtime
END TYPE
Data type holding time values for communication to UTIME. ACTIME is the new value for ST_ATIME, MODTIME is the new value for ST_MTIME.

7.6.3 Procedures

PURE SUBROUTINE access(path,amode,errno)
    CHARACTER(*),INTENT(IN) :: path
    INTEGER(*),INTENT(IN) :: amode
    INTEGER(error_kind),INTENT(OUT) :: errno
Checks file accessibility according to the value of AMODE; this should be F_OK or a combination of R_OK, W_OK and X_OK. In the latter case the values may be combined by addition or the intrinsic function IOR.

The result of the accessibility check is returned in ERRNO, which receives zero for success (i.e. the file exists for F_OK, or all the accesses requested by the R_OK et al combination are allowed) or an error code indicating the reason for access rejection. Possible rejection codes include EACCES, ENAMETOOLONG, ENOENT, ENOTDIR and EROFS (see F90_UNIX_ERRNO).

If the value of AMODE is invalid, error EINVAL is returned.

Note that most ACCESS enquiries are equivalent to an INQUIRE statement, in particular:

CALL ACCESS(PATH,F_OK,ERRNO)
returns success (ERRNO==0) if and only if
INQUIRE(FILE=PATH,EXIST=LVAR) would set LVAR to .TRUE.;
CALL ACCESS(PATH,R_OK,ERRNO)
returns success (ERRNO==0) if and only if
INQUIRE(FILE=PATH,READ=CHVAR) would set CHVAR to 'YES';
CALL ACCESS(PATH,W_OK,ERRNO)
returns success (ERRNO==0) if and only if
INQUIRE(FILE=PATH,WRITE=CHVAR) would set CHVAR to 'YES';
CALL ACCESS(PATH,IOR(W_OK,R_OK),ERRNO)
returns success (ERRNO==0) if and only if
INQUIRE(FILE=PATH,READWRITE=CHVAR) would set CHVAR to 'YES'.
The only differences being that ACCESS returns a reason for rejection, and can test file executability.

SUBROUTINE CHMOD(PATH,MODE,ERRNO)
    CHARACTER(*),INTENT(IN) :: PATH
    INTEGER(*),INTENT(IN) :: MODE
    INTEGER(error_kind),OPTIONAL,INTENT(OUT) :: ERRNO
Sets the file mode (ST_MODE) to MODE.

Possible errors include EACCES, ENAMETOOLONG, ENOTDIR, EPERM and EROFS (see F90_UNIX_ERRNO).

SUBROUTINE CHOWN(PATH,OWNER,GROUP,ERRNO)
    CHARACTER(*),INTENT(IN) :: PATH
    INTEGER(id_kind),INTENT(IN) :: OWNER, GROUP
    INTEGER(error_kind),OPTIONAL,INTENT(OUT) :: ERRNO
Changes the owner (ST_UID) of file PATH to OWNER, and the group number (ST_GID) of the file to GROUP.

Possible errors include EACCES, EINVAL, ENAMETOOLONG, ENOTDIR, ENOENT, EPERM and EROFS (see F90_UNIX_ERRNO).

SUBROUTINE FSTAT(LUNIT,BUF,ERRNO)
    INTEGER(*),INTENT(IN) :: LUNIT
    TYPE(stat_t),INTENT(OUT) :: BUF
    INTEGER(error_kind),OPTIONAL,INTENT(OUT) :: ERRNO
BUF receives the characteristics of the file connected to logical unit LUNIT.

If LUNIT is not a valid logical unit number or is not connected to a file, error EBADF is raised (see F90_UNIX_ERRNO).

PURE LOGICAL(word) FUNCTION isblk(mode)
    INTEGER(mode_kind),INTENT(IN) :: mode

Returns .TRUE. if and only if the MODE value indicates that the file is a “block device”.

PURE LOGICAL(word) FUNCTION ischr(mode)
    INTEGER(mode_kind),INTENT(IN) :: mode

Returns .TRUE. if and only if the MODE value indicates that the file is a “character device”.

PURE LOGICAL(word) FUNCTION isdir(mode)
    INTEGER(mode_kind),INTENT(IN) :: mode

Returns .TRUE. if and only if the MODE value indicates that the file is a directory (or folder).

PURE LOGICAL(word) FUNCTION isfifo(mode)
    INTEGER(mode_kind),INTENT(IN) :: mode

Returns .TRUE. if and only if the MODE value indicates that the file is a “FIFO” (named or unnamed pipe).

PURE LOGICAL(word) FUNCTION isreg(mode)
    INTEGER(mode_kind),INTENT(IN) :: mode

Returns .TRUE. if and only if the MODE value indicates that the file is a “regular” (i.e. normal) file.

SUBROUTINE STAT(PATH,BUF,ERRNO)
    CHARACTER(*),INTENT(IN) :: PATH
    TYPE(stat_t),INTENT(OUT) :: BUF
    INTEGER(error_kind),OPTIONAL,INTENT(OUT) :: ERRNO
BUF receives the characteristics of the file PATH.

Possible errors include EACCES, ENAMETOOLONG, ENOENT and ENOTDIR (see F90_UNIX_ERRNO).

SUBROUTINE utime(path,times,errno)
    CHARACTER(*),INTENT(IN) :: path
    TYPE(utimbuf),OPTIONAL,INTENT(IN) :: times
    INTEGER(error_kind),OPTIONAL,INTENT(OUT) :: errno

Set the access and modification times of the file named by PATH to those specified by the ACTIME and MODTIME components of TIMES respectively.

Possible errors include EACCES, ENAMETOOLONG, ENOENT, ENOTDIR, EPERM and EROFS (see F90_UNIX_ERRNO).


NAG Fortran Compiler, Release 7.1: f90_unix_io

 Navigation: Previous Up Next

7.7 f90_unix_io

This module will contain part of a Fortran API to functions detailed in ISO/IEC 9945-1:1990 Portable Operating System Interface (POSIX) - Part 1: System Application Program Interface (API) [C Language].

In this release only the FLUSH procedure is supported. Users are advised to use the ONLY clause when using this module, as it will have further names added in later releases.

Error handling is described in F90_UNIX_ERRNO. Note that for procedures with an optional ERRNO argument, if an error occurs and ERRNO is not present, the program will be terminated.

All procedures in this module are generic and may also be specific (this may change in a future release).

7.7.1 Procedures

SUBROUTINE FLUSH(LUNIT,ERRNO)
INTEGER(*),INTENT(IN) :: LUNIT
INTEGER(ERROR_KIND),OPTIONAL,INTENT(OUT) :: ERRNO
Flushes the output buffer of logical unit LUNIT. The effect is similar to the Fortran 2003 FLUSH statement, except that the statement allows flushing a unit which is not connected but the procedure does not.

If LUNIT is not a valid unit number or is not connected to a file, error EBADF is raised (see F90_UNIX_ERRNO).


NAG Fortran Compiler, Release 7.1: f90_unix_proc

 Navigation: Previous Up Next

7.8 f90_unix_proc

This module contains part of a Fortran API to functions detailed in ISO/IEC 9945-1:1990 Portable Operating System Interface (POSIX) - Part 1: System Application Program Interface (API) [C Language].

The functions in this module are from Section 3: Process Primitives, excluding 3.3 Signals. The C language functions abort, atexit, exit and system are also provided by this module.

Error handling is described in F90_UNIX_ERRNO. Note that for procedures with an optional ERRNO argument, if an error occurs and ERRNO is not present, the program will be terminated.

All the procedures in this module are generic; some may be specific but this is subject to change in a future release.

7.8.1 Parameters

INTEGER(int32),PARAMETER :: atomic_int
Integer kind for “atomic” operations in signal handlers (see ALARM).

INTEGER(int32),PARAMETER :: atomic_log
Logical kind for “atomic” operations in signal handlers (see ALARM).

USE f90_unix_env, ONLY: pid_kind=>id_kind
Integer kind for representing process IDs; this has been superseded by ID_KIND from F90_UNIX_ENV.

USE f90_unix_env, ONLY: time_kind
Integer kind for representing times in seconds.

INTEGER(int32),PARAMETER :: wnohang
Option bit for WAITPID indicating that the calling process should not wait for the child process to stop or exit.

INTEGER(int32),PARAMETER :: wuntraced
Option bit for WAITPID indicating that status should be returned for stopped processes as well as terminated ones.

7.8.2 Procedures

SUBROUTINE abort(message)
    CHARACTER(*),OPTIONAL :: message
ABORT cleans up the i/o buffers and then terminates execution, producing a core dump on Unix systems. If MESSAGE is given it is written to logical unit 0 (zero) preceded by ‘ abort:’.

SUBROUTINE alarm(seconds,subroutine,secleft,errno)
    INTEGER(*),INTENT(IN) :: seconds
    INTERFACE
        SUBROUTINE subroutine()
        END
    END INTERFACE
    OPTIONAL subroutine
    INTEGER(time_kind),OPTIONAL,INTENT(OUT) :: secleft
    INTEGER(error_kind),OPTIONAL,INTENT(OUT) :: errno
Establishes an “alarm” call to the procedure SUBROUTINE to occur after SECONDS seconds have passed, or cancels an existing alarm if SECONDS==0. If SUBROUTINE is not present, any previous association of a subroutine with the alarm signal is left unchanged. If SECLEFT is present, it receives the number of seconds that were left on the preceding alarm or zero if there were no existing alarm.

The subroutine invoked by the alarm call is only permitted to define VOLATILE SAVEd variables that have the type INTEGER(atomic_int) or LOGICAL(atomic_log); defining or referencing any other kind of variable may result in unpredictable behaviour, even program termination. Furthermore, it shall not perform any array or CHARACTER operations, input/output, or invoke any intrinsic function or module procedure.

If an alarm call is established with no handler (i.e. SUBROUTINE was not present on the first call) the process may be terminated when the alarm goes off.

Possible errors include ENOSYS.

SUBROUTINE atexit(subroutine,errno)
    INTERFACE
        SUBROUTINE subroutine()
        END
    END INTERFACE
    INTEGER(error_kind),OPTIONAL,INTENT(OUT) :: errno
Registers an argumentless subroutine for execution on normal termination of the program.

If the program terminates normally, all subroutines registered with ATEXIT will be invoked in reverse order of their registration. Normal termination includes using the F90_UNIX_PROC procedure EXIT, executing a Fortran STOP statement or executing a main program END statement. ATEXIT subroutines are invoked before automatic file closure.

If the program terminates due to an error or by using the F90_UNIX_PROC procedure FASTEXIT, these subroutines will not be invoked.

Possible errors include ENOMEM.

Note: The list of ATEXIT procedures registered via Fortran is separate from those registered via C; the latter will be invoked after all files have been closed.

SUBROUTINE execl(path,arg0...,errno)
    CHARACTER(*),INTENT(IN) :: path
    CHARACTER(*),INTENT(IN) :: arg0...
    INTEGER(error_kind),OPTIONAL,INTENT(OUT) :: errno
Executes a file instead of the current image, like EXECV. The arguments to the new program are specified by the dummy arguments which are named ARG0, ARG1, etc. up to ARG20 (additional arguments may be provided in later releases). Note that these are not optional arguments, any actual argument that is itself an optional dummy argument must be present. This function is the same as EXECV except that the arguments are provided individually instead of via an array; and because they are provided individually, there is no need to provide the lengths (the lengths being taken from each argument itself).

Errors are the same as for EXECV.

SUBROUTINE execlp(file,arguments,,errno)
    CHARACTER(*),INTENT(IN) :: file
    CHARACTER(*),INTENT(IN) :: arguments
    INTEGER(error_kind),OPTIONAL,INTENT(OUT) :: errno
Executes a file instead of the current image, like EXECV. The arguments to the new program are specified by the dummy arguments which are named ARG0, ARG1, etc. up to ARG20 (additional arguments may be provided in later releases). Note that these are not optional arguments, any actual argument that is itself an optional dummy argument must be present. This function is the same as EXECL except that determination of the program to be executed follows the same rules as EXECVP.

Errors are the same as for EXECV.

SUBROUTINE execv(path,argv,lenargv,errno)
    CHARACTER(*),INTENT(IN) :: path
    CHARACTER(*),INTENT(IN) :: argv(:)
    INTEGER(*),INTENT(IN) :: lenargv(:)
    INTEGER(error_kind),OPTIONAL,INTENT(OUT) :: errno
Executes the file PATH in place of the current process image; for full details see ISO/IEC 9945-1:1990 section 3.1.2. ARGV is the array of argument strings, LENARGV containing the desired length of each argument. If ARGV is not zero-sized, ARGV(1)(:LENARGV(1)) is passed as argument zero (i.e. the program name).

If LENARGV is not the same shape as ARGV, error EINVAL is raised (see F90_UNIX_ERRNO). Other possible errors include E2BIG, EACCES, ENAMETOOLONG, ENOENT, ENOTDIR, ENOEXEC and ENOMEM.

SUBROUTINE EXECVE(path,argv,lenargv,env,lenenv,errno)
    CHARACTER(*),INTENT(IN) :: path
    CHARACTER(*),INTENT(IN) :: argv(:)
    INTEGER(*),INTENT(IN) :: lenargv(:)
    CHARACTER(*),INTENT(IN) :: env(:)
    INTEGER(*),INTENT(IN) :: lenenv(:)
    INTEGER(error_kind),OPTIONAL,INTENT(OUT) :: errno
Similar to EXECV, with the environment strings specified by ENV and LENENV being passed to the new program; for full details see ISO/IEC 9945-1:1990 section 3.1.2.

If LENARGV is not the same shape as ARGV or LENENV is not the same shape as ENV, error EINVAL is raised (see F90_UNIX_ERRNO). Other errors are the same as for EXECV.

SUBROUTINE execvp(file,argv,lenargv,errno)
    CHARACTER(*),INTENT(IN) :: file
    CHARACTER(*),INTENT(IN) :: argv(:)
    INTEGER(*),INTENT(IN) :: lenargv(:)
    INTEGER(error_kind),OPTIONAL,INTENT(OUT) :: errno
The same as EXECV except that the program to be executed, FILE, is searched for using the PATH environment variable (unless it contains a slash character, in which case EXECVP is identical in effect to EXECV).

Errors are the same as for EXECV.

SUBROUTINE exit(status)
    INTEGER(int32),OPTIONAL,INTENT(IN) :: status
Terminate execution as if executing the END statement of the main program (or an unadorned STOP statement). If STATUS is given it is returned to the operating system (where applicable) as the execution status code.

SUBROUTINE fastexit(status)
    INTEGER,OPTIONAL,INTENT(IN) :: status
This provides the functionality of ISO/IEC 9945-1:1990 function _exit (section 3.2.2). There are two main differences between FASTEXIT and EXIT:
  1. When EXIT is called all open logical units are closed (as if by a CLOSE statement). With FASTEXIT this is not done, nor are any file buffers flushed, thus the contents and status of any file connected at the time of calling FASTEXIT are undefined.
  2. Subroutines registered with ATEXIT are not executed.

SUBROUTINE fork(pid,errno)
    INTEGER(id_kind),INTENT(OUT) :: pid
    INTEGER(error_kind),OPTIONAL,INTENT(OUT) :: errno
Creates a new process which is an exact copy of the calling process. In the new process, the value returned in PID is zero; in the calling process the value returned in PID is the process ID of the new (child) process.

Possible errors include EAGAIN, ENOMEM and ENOSYS (see F90_UNIX_ERRNO).

SUBROUTINE pause(errno)
    INTEGER(error_kind),INTENT(OUT) :: errno
Suspends process execution until a signal is raised. If the action of the signal was to terminate the process, the process is terminated without returning from PAUSE. If the action of the signal was to invoke a signal handler (e.g. via ALARM), process execution continues after return from the signal handler.

If process execution is continued after a signal, ERRNO is set to EINTR.

If this functionality is not available, ERRNO is set to ENOSYS.

PURE SUBROUTINE sleep(seconds,secleft)
    INTEGER(*),INTENT(IN) :: seconds
    INTEGER(time_kind),OPTIONAL,INTENT(OUT) :: secleft
Suspends process execution for SECONDS seconds, or until a signal has been delivered. If SECLEFT is present, it receives the number of seconds remaining in the sleep time (zero unless the sleep was interrupted by a signal).

SUBROUTINE system(string,status,errno)
    CHARACTER(*),INTENT(IN) :: string
    INTEGER(error_kind),OPTIONAL,INTENT(OUT) :: status,errno
Passes STRING to the command processor for execution. If STATUS is present it receives the completion status - this is the same status returned by WAIT and can be decoded with WIFEXITED etc. If ERRNO is present it receives the error status from the SYSTEM call itself.

Possible errors are those from FORK or EXECV.

SUBROUTINE wait(status,retpid,errno)
    INTEGER(int32),OPTIONAL,INTENT(OUT) :: status
    INTEGER(id_kind),OPTIONAL,INTENT(OUT) :: retpid
    INTEGER(error_kind),OPTIONAL,INTENT(OUT) :: errno
Wait for any child process to terminate (returns immediately if one has already terminated). See ISO/IEC 9945-1:1990 section 3.2.1 for full details.

If STATUS is present it receives the termination status of the child process. If RETPID is present it receives the process number of the child process.

Possible errors include ECHILD and EINTR (see F90_UNIX_ERRNO).

SUBROUTINE waitpid(pid,status,options,retpid,errno)
    INTEGER(id_kind),INTENT(IN) :: pid
    INTEGER(int32),OPTIONAL,INTENT(OUT) :: status
    INTEGER(int32),OPTIONAL,INTENT(IN) :: options
    INTEGER(id_kind),OPTIONAL,INTENT(OUT) :: retpid
    INTEGER(error_kind),OPTIONAL,INTENT(OUT) :: errno
Wait for a particular child process to terminate (or for any one if PID==(-1)). If OPTIONS is not present it is as if it were present with a value of 0. See ISO/IEC 9945-1:1990 section 3.2.1 for full details.

Possible errors include ECHILD, EINTR and EINVAL (see F90_UNIX_ERRNO).

PURE INTEGER(int32) FUNCTION wexitstatus(stat_val)
    INTEGER(int32),INTENT(IN) :: stat_val
If WIFEXITED(STAT_VAL) is .TRUE., this function returns the low-order 8 bits of the status value supplied to EXIT or FASTEXIT by the child process. If the child process executed a STOP statement or main program END statement, the value will be zero. If WIFEXITED(STAT_VAL) is .FALSE., the function value is undefined.

PURE LOGICAL(word) FUNCTION wifexited(stat_val)
    INTEGER(error_kind),INTENT(IN) :: stat_val
Returns .TRUE. if and only if the child process terminated by calling FASTEXIT, EXIT, by executing a STOP statement or main program END statement, or possibly by some means other than Fortran.

PURE LOGICAL(word) FUNCTION wifsignaled(stat_val)
    INTEGER(int32),INTENT(IN) :: stat_val
Returns .TRUE. if and only if the child process terminated by receiving a signal that was not caught.

PURE LOGICAL(word) FUNCTION wifstopped(stat_val)
    INTEGER(int32),INTENT(IN) :: stat_val
Returns .TRUE. if and only if the child process is stopped (and not terminated). Note that WAITPID must have been used with the WUNTRACED option to receive such a status value.

PURE INTEGER(int32) FUNCTION wstopsig(stat_val)
    INTEGER(int32),INTENT(IN) :: stat_val
If WIFSTOPPED(STAT_VAL) is .TRUE., this function returns the signal number that caused the child process to stop. If WIFSTOPPED(STAT_VAL) is .FALSE., the function value is undefined.

PURE INTEGER(int32) FUNCTION wtermsig(stat_val)
    INTEGER(int32),INTENT(IN) :: stat_val
If WIFSIGNALED(STAT_VAL) is .TRUE., this function returns the signal number that caused the child process to terminate. If WIFSIGNALED(STAT_VAL) is .FALSE., the function value is undefined.


NAG Fortran Compiler, Release 7.1: Standard Fortran 95

 Navigation: Previous Up Next

8 Standard Fortran 95

  • 8.1 Fortran 95 Program Structure
  • 8.2 Fortran 95 Expressions
  • 8.3 Fortran 95 Statements
  • 8.4 Fortran 95 Intrinsic Procedures


NAG Fortran Compiler, Release 7.1: Fortran 95 Program Structure

 Navigation: Previous Up Next

8.1 Fortran 95 Program Structure

This section contains a quick reference guide to the structure of a Fortran 95 program.

Expressions are described in the next section.

  • Syntax element definition is represented by ‘::=’.
  • Names in italics (e.g., ‘expr’) are syntax element names.
  • Items in ‘[ ]’ are optional.
  • Ellipsis ‘...’ indicates optional repetition of the preceding item.
  • ‘{’ and ‘}’ are for grouping only.
  • Items separated by ‘|’ are a “one-of-many” selection.
  • Statements end in ‘-stmt’ and are described in the section “Fortran 95 Statements”.

INCLUDE Line

The INCLUDE line has the form:

INCLUDE char-literal-constant

The char-literal-constant must not have a kind-param and must be the pathname of an accessible file; relative pathnames will be searched for in the current working directory and all directories named by -I options. The INCLUDE line is effectively replaced by the contents of the named file.

Program Unit Structure

program-unit ::= main-program | module | procedure | block-data-subprogram

main-program ::= | [ program-stmt ]
 | body
 | end-program-stmt

body ::= | declaration-section
 | [ executable-section ]
 | [ contains-section ]

Note: A contains-section cannot appear in an internal procedure (an internal procedure is a procedure in the contains-section of another procedure).

contains-section ::= | contains-stmt
 | procedure...

module ::= | module-stmt
 | [ declaration-section ]
 | [ contains-section ]
 | end-module-stmt

procedure ::= function-subprogram | subroutine-subprogram

function-subprogram ::= | function-stmt
 | body
 | end-function-stmt

subroutine-subprogram ::= | subroutine-stmt
 | body
 | end-subroutine-stmt

block-data-subprogram ::= | block-data-stmt
 | declaration-section
 | end-block-data-stmt

Declaration Section

declaration-section ::= | [ use-stmt... ]
 | [ implicit-part... ]
 | [ declaration... ]

implicit-part ::= implicit-stmt | parameter-stmt | format-stmt | entry-stmt

declaration ::= | derived-type-definition | interface-block | declarative |
 | format-stmt | entry-stmt

declarative ::= | allocatable-stmt | common-stmt | data-stmt | dimension-stmt |
 | equivalence-stmt | external-stmt | intent-stmt | intrinsic-stmt | namelist-stmt |
 | optional-stmt | parameter-stmt | pointer-stmt | private-stmt | public-stmt |
 | save-stmt | statement-function-stmt | target-stmt | type-declaration-stmt

derived-type-definition ::= | type-stmt
 | component-def-stmt...
 | end-type-stmt

interface-block ::= | interface-stmt
 | { interface-body | module-procedure-stmt } ...
 | end-interface-stmt

interface-body ::= | function-stmt declaration-section end-function-stmt |
 | subroutine-stmt declaration-section end-subroutine-stmt

Executable Section

executable-section ::= [ executable | executable-construct | data-stmt ]...

executable ::= | allocate-stmt | arithmetic-if-stmt | assignment-stmt | backspace-stmt | call-stmt |
 | close-stmt | computed-goto-stmt | continue-stmt | cycle-stmt | deallocate-stmt
 | | endfile-stmt | exit-stmt | forall-stmt | goto-stmt | if-stmt | inquire-stmt |
 | nullify-stmt | open-stmt | pause-stmt | pointer-assignment-stmt | print-stmt |
 | read-stmt | return-stmt | rewind-stmt | stop-stmt | where-stmt | write-stmt

executable-construct ::= | select-case-construct | do-loop | forall-construct | if-construct |
 | where-construct

select-case-construct ::= | select-stmt
 | [ case-stmt executable-section ] ...
 | end-select-stmt

if-construct ::= | if-then-stmt
 | [ executable-section ]
 | [ elseif-stmt executable-section ] ...
 | [ else-stmt executable-section ]
 | endif-stmt

where-construct ::= | where-construct-stmt
 | where-body
 | [ elsewhere-stmt where-body ]
 | endwhere-stmt

where-body ::= | [ where-assignment-stmt | where-stmt | where-construct |
 | elsewhere-mask-stmt ] ...

forall-construct ::= | forall-construct-stmt
 | forall-body
 | end-forall-stmt

forall-body ::= | [ forall-assignment-stmt | where-stmt | where-construct | forall-stmt |
 | forall-construct ] ...

do-loop ::= | do-stmt
 | executable-section
 | do-ending

do-ending ::= enddo-stmt | executable

Note: If the do-stmt specifies a terminating label, the do-ending is the statement with that label and shall not be a goto-stmt, return-stmt, stop-stmt, exit-stmt, cycle-stmt, arithmetic-if-stmt or any form of END statement. If the do-stmt does not specify a terminating label, the do-ending shall be an enddo-stmt.


NAG Fortran Compiler, Release 7.1: Fortran 95 Expressions

 Navigation: Previous Up Next

8.2 Fortran 95 Expressions

This section contains a quick reference guide to expression syntax and semantics in Fortran 95. For more details see Metcalf, Reid and Cohen “Fortran 95/2003 Explained” or the Fortran 95 standard “IS 1539-1:1997”.

  • Syntax element definition is represented by ‘::=’.
  • Names in italics (e.g., ‘expr’) are syntax element names.
  • Items in ‘[ ]’ are optional.
  • Ellipsis ‘...’ indicates optional repetition of the preceding item.
  • ‘{’ and ‘}’ are for grouping only.
  • Items separated by ‘|’ are a “one-of-many” selection.

General Form

The general form of an expression expr is as follows:

expr ::= [ unary-operator ] operand [ binary-operator operand ]...

operand ::= | literal-constant | object | array-constructor |
 | structure-constructor | function-reference | ( expr )

binary-operator ::= | + | - | * | / | ** | == | /= | < | > | <= | >= | // |
 | .AND. | .OR. | .EQV. | .NEQV. | user-operator

unary-operator ::= + | - | .NOT. | user-operator

user-operator ::= .letter[letter...].

The operators ==, /=, <, >, <= and >= may also be represented by .EQ., .NE., .LT., .GT., .LE. and .GE. respectively.

Operators

Binary operators are associated left-to-right except for exponentiation, which associates right-to-left. The precedence of each operator is shown by the following table, from highest to lowest:

Operators | Binary/Unary
user-operator | Unary
** | Binary
* / | Binary
+ - | Unary
+ - | Binary
// | Binary
== /= < > <= >= | Binary
.NOT. | Unary
.AND. | Binary
.OR. | Binary
.EQV. .NEQV. | Binary
user-operator | Binary

Literal Constants

literal-constant ::= | integer-literal | real-literal | double-precision-literal |
 | logical-literal | complex-literal | character-literal

integer-literal ::= digit-string [ _ kind-specifier ]

digit-string ::= { 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 }...

kind-specifier ::= digit-string | name

Note: name must be an INTEGER PARAMETER name.

Examples:

      42
      17_1
      32767_int16

real-literal ::= | mantissa [ E exponent ] [ _ kind-specifier ] |
 | digit-string E exponent [ _ kind-specifier ]

mantissa ::= | digit-string . [ digit-string ] |
 | . digit-string

exponent ::= [ + | - ] digit-string

Examples:

      4.2
      .7_1
      327E+67_real64

double-precision-literal ::= { mantissa | digit-string } D exponent

Examples:

      4d2
      1.7D-10

logical-literal ::= { .TRUE. | .FALSE. } [ _ kind-specifier ]

complex-literal ::= ( int-or-real-literal , int-or-real-literal )

int-or-real-literal ::= integer-literal | real-literal

Examples:

      (42,17_1)
      (0,1d0)

character-literal ::= [ kind-specifier _ ] { ' [char...] ' | " [char...] " }

Note: char is any character other than the quoting character, or the quoting character occurring twice (e.g., '''' is the same as "'").

Examples:

      '42'
      "Say 'Hello'."

Constants

constant ::= literal-constant | name

Named constants are declared by the PARAMETER statement or by a type-declaration statement with the PARAMETER attribute

Objects

object ::= object-ref [ % object-ref ]... [ ( substring-range ) ]

object-ref ::= name [ section-subscript-list ]

section-subscript-list ::= ( section-subscript [ , section-subscript ]... )

section-subscript ::= expr | triplet

triplet ::= [ expr ] : [ expr ] [ : expr ]

substring-range ::= [ expr ] : [ expr ]

name ::= letter [ letter | digit | _ ] ...

letter ::= | A | B | C | D | E | F | G | H | I | J | K | L | M | N | O | P | Q | R | S | T | U | V | W |
 | X | Y | Z

variable ::= object

constant-subobject ::= object | character-literal ( substring-range )

Note: For a variable, the name in the initial object-ref must be that of a variable.
For a constant-subobject, the name in the initial object-ref must be that of a constant (i.e., a PARAMETER).

An object is scalar if and only if all its object-ref's are scalar. An object-ref with non-zero rank (i.e., an array) can only be followed by scalar non-pointer object-refs.

An array element is a scalar object whose final object-ref contains a section-subscript-list where each section-subscript is a scalar expression. For example

      ARRAY(I,J)
      SCALAR%ARRAY(I,J)
A structure component is an object with more than one object-ref whose final object-ref has no section-subscript-list and all preceding object-refs are scalar. For example
      SCALAR%SCALAR
      ARRAY(I,J)%SCALAR
A substring is a scalar object with a substring-range. For example
      SCALAR(I:J)
      ARRAY(I,J)(K:L)
A whole array is an array object with only one object-ref.

An array section is an array object where a non-final object-ref has non-zero rank, or the final object-ref has a section-subscript-list and one or more of the section-subscripts has non-zero rank or is a triplet. For example

      ARRAY(2:M)
      ARRAY%SCALAR

Array Constructor

array-constructor ::= (/ ac-item [ , ac-item ] ... /)

ac-item ::= expr | ac-implied-do

ac-implied-do ::= ( expr [ , expr ] ... , name = expr , expr [ , expr ] )

Note: name is an integer variable name, but its value is not affected by the execution of the array constructor. All expressions in an array constructor must have the same type and type parameters; in particular, for characters, they must have the same length.

Structure Constructor

structure-constructor ::= name ( expr [ , expr ] ... )

Note: name must be the name of a derived type. Each expression must be assignment-compatible with the corresponding component of the derived type.

Function Reference

function-reference ::= name ( [ expr [ , expr ] ... ] )

Note: name must be the name of a function.


NAG Fortran Compiler, Release 7.1: Fortran 95 Statements

 Navigation: Previous Up Next

8.3 Fortran 95 Statements

This section contains a quick reference guide to the statements in Fortran 95.

  • Syntax element definition is represented by ‘::=’.
  • Names in italics (e.g., ‘expr’) are syntax element names.
  • Items in ‘[ ]’ are optional.
  • Ellipsis ‘...’ indicates optional repetition of the preceding item.
  • ‘{’ and ‘}’ are for grouping only.
  • Items separated by ‘|’ are a “one-of-many” selection.

Type Specification

The following syntax is used by several declaration statements.

type-spec ::= | numeric-type [ kind-specifier ] |
 | numeric-type * digit-string |
 | DOUBLE PRECISION |
 | CHARACTER [ char-specifier ]

numeric-type ::= COMPLEX | INTEGER | LOGICAL | REAL

kind-specifier ::= ( [ KIND = ] expr )

char-specifier ::= | * digit-string |
 | * ( char-length ) |
 | ( char-length [ , [ KIND = ] expr ] ) |
 | ( LEN = char-length [ , KIND = expr ] ) |
 | ( KIND = expr [ , LEN = char-length ] )

char-length ::= * | expr

Labels and Construct Names

label ::= digit-string

Note that the digit-string in a label must contain at most 5 digits, and at least one of them must be non-zero. Leading zeroes are not significant, but do count towards the limit of 5.

Although it is not shown in the syntax definitions, all statements may be labelled and the FORMAT statement must be labelled.

construct-name ::= name

Construct names are “class 1” names, and must not be the same as any other class 1 name in a subprogram; class 1 names includes variables, procedures, program unit names, et cetera.

Entity Declaration List

The following syntax is used by both Component Declaration and Type Declaration statements.

entity-decl-list ::= entity-decl [ , entity-decl ] ...

entity-decl ::= name [ * char-length ] [ array-spec ] [ initial-value ]

array-spec ::= explicit-shape | assumed-shape | deferred-shape | assumed-size

explicit-shape ::= ( explicit-bound [ , explicit-bound ] ... )
explicit-bound ::= [ expr : ] expr

assumed-shape ::= ( assumed-bound [ , assumed-bound ] ... )
assumed-bound ::= [ expr ] :

deferred-shape ::= ( deferred-bound [ , deferred-bound ] ... )
deferred-bound ::= :

assumed-size ::= ( [ explicit-bound , ]... assumed-size-bound )
assumed-size-bound ::= [ expr : ] *

initial-value ::= = expression | => NULL()

Allocatable Statement

ALLOCATABLE [ :: ] name [ deferred-shape ] [ , name [ deferred-shape ] ] ...

Declares the listed entities to be allocatable arrays. If array bounds are present, they must be deferred.

Allocate Statement

ALLOCATE ( allocate-item [ , allocate-item ] ... [ , STAT = variable ] )
allocate-item ::= variable [ explicit-shape ]

Allocates a pointer or allocatable array. If the allocation fails and the STAT= clause is present, the STAT= variable will be assigned a non-zero value.

Arithmetic If Statement (obsolescent)

IF ( expr ) label , label , label

Branches to one of three labels depending on whether expr is negative, zero or positive respectively. The expression must be scalar and of type integer or real.

Assignment Statement

variable = expr

The expression is evaluated and assigned to the variable. For intrinsic assignment, it must be assignment-compatible with the variable, that is:

  1. If the variable is scalar, the expression must be scalar. If the variable is an array, the expression may be scalar or an array of the same shape.
  2. If the variable is of type LOGICAL, the expression must be LOGICAL but may be any KIND.
  3. If the variable is of type CHARACTER, the expression must be of type CHARACTER and of the same KIND.
  4. If the variable is of type INTEGER, REAL or COMPLEX, the expression must be of type INTEGER, REAL or COMPLEX.
  5. If the variable is of derived type, the expression must be of that type.
For defined assignment, there must be a generic interface for ASSIGNMENT(=) which matches the types, kinds and ranks of the variable and expression; the user-specified assignment routine is called. Note that in the case of derived types, defined assignment is permitted to override the intrinsic assignment.

Backspace Statement

BACKSPACE expr
BACKSPACE ( position-spec-list )

position-spec-list ::= position-spec [ , position-spec ]
position-spec ::= { [ UNIT= ] expr } | { IOSTAT= variable } | { ERR= label }

Note: A position-spec-list is required to have a UNIT= position-spec; the UNIT= keyword and equals sign may be omitted only if it is the first in the list.

Positions the file connected to the specified unit to the record preceding the current one. An error condition is raised if the file is not connected, or the unit does not support backspacing.

The effect of each position-spec is as below:

UNIT=
Specifies the i/o unit; it must be a scalar integer expression identifying an external file.
ERR=
Transfers control to the specified label if an error condition occurs during the i/o statement.
IOSTAT=
Sets the variable to a positive number if an error occurs and to zero otherwise.

Block Data Statement

BLOCK DATA [ name ]

This is the first statement of a block data subprogram. All but one block data subprogram must be named.

Call Statement

CALL name [ ( [ actual-arg-list ] ) ]

actual-arg-list ::= actual-arg [ , actual-arg ]...
actual-arg ::= expr | * label

Calls the named subroutine.

Case Statement

CASE DEFAULT [ construct-name ]
CASE ( case-value-range [ , case-value-range ]... ) [ construct-name ]

case-value-range ::= | expr [ : [ expr ] ] |
 | : expr

Marks the beginning of a CASE part (and the end of any preceding CASE part). Statements in this part are executed if the corresponding SELECT expression value satisfies the appropriate CASE condition:

.EQ.
A case-value-range of the form (expr).
.LE.
A case-value-range of the form (:expr).
.GE.
A case-value-range of the form (expr:).
range
A case-value-range of the form (expr:expr) is satisfied for values greater than or equal to the first expression, and less than or equal to the second expression.
DEFAULT
The CASE DEFAULT clause is selected if the value does not satisfy any other CASE statements in that SELECT construct.

Note that within a SELECT construct, each CASE statement must have distinct conditions so that only one can be satisfied.

Close Statement

CLOSE expr
CLOSE ( position-spec-list )

(See the BACKSPACE statement for the position-spec-list definition.)

Closes the specified unit.

Common Statement

COMMON | [ / [ common-block-name ] / ] common-object-list
 | [ [ , ] / [ common-block-name ] / common-object-list ]...

common-object-list ::= common-object [ , common-object ]...
common-object ::= name [ array-spec ]

Declares a common block. If no common-block-name is specified, “blank common” is the common block declared. Multiple COMMON statements for the same common block act as if the common-object-lists were concatenated in a single statement.

Component Definition Statement

type-spec [ [ , component-attribute-list ] :: ] entity-decl-list

component-attribute-list ::= component-attr [ , component-attr ]...

component-attr ::= | DIMENSION array-spec |
 | POINTER

Declares one or more components of a derived type. Any array-spec in a component definition must be deferred-shape if the POINTER attribute is present, and must be explicit-shape otherwise. Any initial-value that is present defines the default value for that component of any new entities of the type.

Computed Goto Statement (obsolescent)

GOTO ( label [ , label ] ... ) expr

The (integer scalar) expression is evaluated; if it is less than one or greater than the number of labels in the list, control is transferred to the next statement. Otherwise control is transferred to the corresponding label.

Contains Statement

CONTAINS

This statement separates the declarations of a module from its contained procedures, and the declarations and executables of a main program or procedure from its contained procedure.

Continue Statement

CONTINUE

This is an executable statement that has no effect. If it has a label it may be used as the terminating statement of a DO construct or as the target of a GOTO, computed-GOTO or assigned-GOTO.

Cycle Statement

CYCLE [ construct-name ]

Begins the next iteration of either the specified DO construct, or if construct-name is omitted, the innermost enclosing DO construct.

Data Statement

DATA data-set [ , data-set ]...

data-set ::= data-object-list / data-value-list /

data-object-list ::= data-object [ , data-object ]...
data-object ::= variable | data-implied-do
data-implied-do ::= ( data-object [ , data-object ]... do-spec )

data-value-list ::= data-value [ , data-value ]...
data-value ::= [ data-repeat * ] data-constant
data-repeat ::= constant | constant-subobject

data-constant ::= | literal-constant | NULL() | structure-constructor | object |
 | { + | - } { real-literal | integer-literal }

Declares the initial value of the specified objects. This implicitly declares those objects to have the SAVE attribute.

Deallocate Statement

DEALLOCATE ( expr [ , expr ] [ , STAT = variable ] )

Deallocates the storage occupied by an allocatable array or pointer. An error is raised if an allocatable array to be deallocated is not allocated, or if a pointer to be deallocated is dissociated or is associated with an object that was not allocated with ALLOCATE.

Dimension Statement

DIMENSION [ :: ] name array-spec [ , name array-spec ]...

Declares the name(s) to be arrays with the specified bounds.

Do Statement

[ construct-name : ] DO [ label ] [ , ] [ loop-control ]

loop-control ::= | do-spec |
 | WHILE ( logical-expr )

do-spec ::= name = expr , expr [ , expr ]

The initial statement of a DO loop. If label is present, the loop ends on the statement with that label, which cannot be a GOTO, RETURN, STOP, EXIT, CYCLE, END or arithmetic IF statement. Nested DO loops can share the same ending statement, provided it is not an ENDDO statement. If the loop-control is missing, the DO loop terminates only if control is explicitly transferred outside the loop (e.g., by an EXIT, GOTO or RETURN statement).

If construct-name is present, the DO loop must end with an ENDDO statement identified with the same construct-name.

Else Statement

ELSE [ construct-name ]

Begins the ELSE part of an IF-THEN construct. Statements in this part are executed only if the IF condition is false and all ELSEIF conditions at the same level are false. If the IF-THEN statement had a construct-name, the ELSE statement may specify the same construct-name.

Elseif Statement

ELSE IF ( expr ) THEN [ construct-name ]

Begins a (new) ELSEIF part of an IF-THEN construct. Statements in this part are executed only if the IF condition is false, all preceding ELSEIF conditions at the same level are false, and this ELSEIF condition is true. If the IF-THEN statement had a construct-name, the ELSEIF statement may specify the same construct-name.

Elsewhere Statement

ELSEWHERE [ construct-name ]

Begins the ELSEWHERE part of a WHERE construct. The statements in this part are executed only for those elements for which the WHERE mask are false, and all ELSEWHERE masks at the same level are also false.

If the WHERE statement had a construct-name, the ELSEWHERE statement may specify the same construct-name.

Elsewhere Mask Statement

ELSEWHERE ( expr ) [ construct-name ]

Begins a masked ELSEWHERE part of a WHERE construct. The statements in this part are executed only for those elements for which the previous masks are false and this ELSEWHERE mask are true. (The previous masks are the WHERE mask and all preceding ELSEWHERE masks at the same level in this WHERE construct.) Note that the elements of the ELSEWHERE mask that do not correspond to false elements of the previous masks are not evaluated.

If the WHERE statement had a construct-name, the ELSEWHERE-mask statement may specify the same construct-name.

End Block Data Statement

END [ BLOCK DATA [ name ] ]

The last statement of a block data subprogram. If name is present, the BLOCK DATA statement at the beginning of the subprogram must have specified the same name.

Enddo Statement

END DO [ construct-name ]

Marks the end of a DO construct. The construct-name shall be present if and only if it were present on the DO statement, and must be the same construct-name if so. If the DO statement specifies an ending label, the ENDDO statement must be labelled with that label.

Endfile Statement

ENDFILE expr
ENDFILE ( position-spec-list )

(See the BACKSPACE statement for the position-spec-list definition).

Writes an endfile record to the specified external file, truncating it at the current point.

End Function Statement

END [ FUNCTION [ name ] ]

The last statement of a function subprogram. If the function subprogram is a contained subprogram, the keyword FUNCTION must be present. If name is present, it must be the name of the function.

Endif Statement

END IF [ construct-name ]

Marks the end of an IF-THEN construct. The construct-name shall be present if and only if it were present on the IF-THEN statement, and must be the same construct-name if so.

End Interface Statement

END INTERFACE [ generic-spec ]

Marks the end of an interface block. If the INTERFACE statement had a generic-spec, it may appear on the ENDINTERFACE statement.

End Module Statement

END [ MODULE [ name ] ]

The final statement of a module subprogram. If name is present, it must match the name on the MODULE statement.

End Program Statement

END [ PROGRAM [ name ] ]

The final statement of a main program unit. If name is present, the main program must have a PROGRAM statement and the names must be the same.

End Select Statement

END SELECT [ construct-name ]

Marks the end of a SELECT construct. The construct-name shall be present if and only if it were present on the SELECT statement, and must be the same construct-name if so.

End Type Statement

END TYPE [ name ]

Marks the end of a derived type definition. If name is present it must be the name of the derived type.

Endwhere Statement

ENDWHERE [ construct-name ]

Marks the end of a WHERE construct. The construct-name shall be present if and only if it were present on the WHERE statement, and must be the same construct-name if so.

Equivalence Statement

EQUIVALENCE equivalence-set [ , equivalence-set ]...
equivalence-set ::= ( variable { , variable }... )

Declares each object in an equivalence-set to occupy the same storage.

Entry Statement

ENTRY name [ ( [ arg-list ] ) ]

Declares an additional entry point to the enclosing subprogram (entry points are not allowed in block data, main program, module and internal subprograms).

External Statement

EXTERNAL name [ , name ]...

Declares the listed names to be external subprograms or block data subprograms.

Exit Statement

EXIT [ construct-name ]

Transfers control to the statement following named DO loop or, if construct-name is omitted, the innermost enclosing DO loop.

Forall Statement

FORALL ( triplet-spec [ , triplet-spec ]... [ , expr ] ) forall-assignment-stmt
triplet-spec ::= name = expr : expr [ : expr ]

The iteration space of a FORALL statement or construct is the cross-product of the sets of possible index values defined by each triplet-spec masked by the final expr (if present). Note that the scope of the index names is limited to the FORALL statement – a variable with the same name outside the FORALL statement is unaffected.

The FORALL statement executes the forall-assignment statement for each index value set in the iteration space.

Forall Assignment Statement

variable = expr
variable => expr

This is exactly like a normal assignment statement except that the expr is evaluated for each element of the iteration space before assignment or pointer assignment to each variable. Note that an assignment must not assign to the same element of an array more than once in the iteration space, and if the variable is scalar then the iteration space must be exactly one element.

Forall Construct Statement

FORALL ( triplet-spec [ , triplet-spec ]... [ , expr ] )

(See the FORALL statement for the triplet-spec definition and the explanation of the iteration space.)

Begins a FORALL construct.

Format Statement

FORMAT ( [ format-list ] )

format-list ::= format-item [ , format-item ]...

format-item ::= [ digit-string ] { data-edit | ( format-list ) } | other-edit

data-edit ::= | { I | B | O | Z } digit-string [ . digit-string ] |
 | { F | D } digit-string . digit-string |
 | { E | EN | ES | G }
 | digit-string . digit-string [ E digit-string ] |
 | L digit-string |
 | A [ digit-string ]

other-edit ::= | digit-string { / | P | X } |
 | { T | TR | TL } digit-string |
 | character-literal |
 | digit-string H char... |
 | / | : | BN | BZ | S | SP | SS

Note: The character-literal must not have a kind-specifier. The H edit descriptor is followed by digit-string chars, which may be any character except end-of-line; this edit descriptor is obsolescent and the character-literal one should be used instead.

Declares an i/o format.

Note: The comma between format-items may be omitted as follows:

  1. Between a ‘P’ descriptor and a following ‘D’, ‘E’, ‘EN’, ‘ES’, ‘F’ or ‘G’ descriptor,
  2. Before a ‘/’ descriptor with no preceding digit-string,
  3. After a ‘/’ descriptor and
  4. Before or after a ‘:’ descriptor.

Function Statement

[ prefix ] FUNCTION name ( [ name [ , name ] ... ] ) [ RESULT(name) ]

prefix :: = { type-spec | RECURSIVE | PURE | ELEMENTAL }...

Note: At most one occurrence of each prefix item is allowed.

This is the first statement of a function subprogram. If no RESULT variable is specified the result variable has the same name as the function name (thus for direct recursion, a RESULT clause is necessary as well as the RECURSIVE keyword).

Goto Statement

GOTO label

Branches to the specified label, which must be on a branch target statement (i.e., the subprogram END statement, an executable statement, the first statement of an executable construct or the last statement of an enclosing executable construct).

If Statement

IF ( expr ) executable

Executes the sub-statement if and only if the condition is true. The sub-statement cannot itself be an IF statement.

If Then Statement

[ construct-name : ] IF ( expr ) THEN

Begins an IF-THEN construct and the THEN part thereof. Statements in this part are executed if and only if the condition is true. This statement may have a construct-name; if it does, the corresponding ENDIF statement shall have the same construct-name and intervening ELSE and ELSEIF statements at the same level may have the same construct-name.

Implicit Statement

IMPLICIT implicit-spec [ , implicit-spec ]...

implicit-spec ::= type-spec ( letter-spec [ , letter-spec ] ... )
letter-spec ::= letter [ - letter ]

Alters the implicit type mapping from the default. The default map is

      IMPLICIT REAL(A-H,O-Z),INTEGER(I-N)
in an external subprogram or interface body, and the same as the containing subprogram in a contained subprogram.

Implicit None Statement

IMPLICIT NONE

This statement sets the implicit type mapping for each letter to null, i.e., there are no implicit types. It must occur before any PARAMETER statements or other declarations (but after any USE statements).

Inquire Statement

INQUIRE ( IOLENGTH=object ) output-item [ , output-item ]...
INQUIRE ( inquire-spec [ , inquire-spec ]... )

inquire-spec ::= | [ UNIT= ] expr | ACCESS= variable | ACTION= variable | BLANK= variable | CONVERT= variable |
 | DELIM= variable | DIRECT= variable | ERR= label | EXIST= variable | FILE= expr |
 | FORM= variable | FORMATTED= variable | IOSTAT= variable | NAME= variable |
 | NAMED= variable | NEXTREC= variable | NUMBER= variable | OPENED= variable |
 | PAD= variable | POSITION= variable | READ= variable | READWRITE= variable |
 | RECL= variable | SEQUENTIAL= variable | UNFORMATTED= variable

output-item ::= expr | ( { output-item , } ... do-spec )

The first form enquires as to the length needed to be specified for RECL= in the OPEN statement for an unformatted sequential file to be able to write records as large as the output-item list.

The second form enquires either by unit or by file; exactly one UNIT= or FILE= clause must be present (the UNIT= keyword can be omitted if it is the first inquire-spec). If the FILE= clause is used and that file is currently connected to a unit, the effect is as if that unit were specified.

The effect of each clause is as below:

ACCESS=
Sets the scalar character object to 'SEQUENTIAL' if the unit is connected for sequential access, to 'DIRECT' if the unit is connected for direct access, and to 'UNDEFINED' if there is no connection.
ACTION=
Sets the scalar character object to 'READ' if the unit is connected for input only, to 'WRITE' if the unit is connected for output only, to 'READWRITE' if the unit is connected for both input and output, and to 'UNDEFINED' if there is no connection.
BLANK=
If the unit is connected for formatted i/o, sets the scalar character object to 'NULL' if blanks are treated as nulls on input and to 'ZERO' if they are treated as zeroes on input. Otherwise the object is set to 'UNDEFINED'.
CONVERT=
Sets the scalar character object to 'UNKNOWN' if the file is not connected for unformatted input/output, and otherwise to the value of the CONVERT= specifier in the OPEN statement or as determined by the FORT_CONVERT n environment variable. Possible values are 'NATIVE', 'BIG_NATIVE', 'LITTLE_NATIVE', 'BIG_IEEE', 'LITTLE_IEEE', 'BIG_IEEE_DD' and 'LITTLE_IEEE_DD'.
DELIM=
Sets the scalar character object to 'APOSTROPHE' if the apostrophe is used to delimit character data in list-directed or namelist output for the unit, to 'QUOTE' if the quotation mark is to be so used, to 'NONE' if no delimiter is to be used, and to 'UNDEFINED' if there is no connection.
DIRECT=
Sets the scalar character object to 'YES' if direct access is allowed for the unit, to 'NO' if direct access is not allowed, and to 'UNKNOWN' if the answer cannot be determined.
ERR=
Transfers control to the specified label if an error condition occurs during execution of the enquiry.
EXIST=
Sets the scalar default logical object to .TRUE. if the file or unit exists, and to .FALSE. otherwise.
FORM=
Sets the scalar character object to 'FORMATTED' if the unit is connected for formatted i/o, to 'UNFORMATTED' if the unit is connected for unformatted i/o, and to 'UNDEFINED' if there is no connection.
FORMATTED=
Sets the scalar character object to 'YES' if formatted i/o is allowed for the unit, to 'NO' if it is not allowed, and to 'UNKNOWN' if the answer cannot be determined.
IOSTAT=
Sets the scalar default integer object to a non-zero value to indicate an error condition occurring during the enquiry, and to zero otherwise.
NAME=
Sets the scalar character object to the name of the file connected to the unit (undefined if there is no name).
NAMED=
Sets the scalar default logical object to .TRUE. if the unit is connected to a named file, and to .FALSE. otherwise.
NEXTREC=
If the unit is connected for direct access, sets the scalar default integer object to 1 greater than the number of the record last read or written (or to 1 if no record has been read or written); otherwise the object becomes undefined.
NUMBER=
Sets the scalar default integer object to the number of the unit to which the file is connected, or to -1 if the file is not connected to a unit.
OPENED=
Sets the scalar default logical object to .TRUE. if the unit is connected to a file (or the file is connected to a unit), and to .FALSE. otherwise.
PAD=
Sets the scalar character object to 'NO' if the connection of the file to the unit included the PAD='NO' specifier; otherwise it is set to 'YES'.
POSITION=
Sets the scalar character object to 'REWIND' if the unit is positioned at the beginning of the file, to 'APPEND' if it is positioned at the end of the file, to 'ASIS' if the unit was connected with that specification (and no i/o or positioning has occurred since connection), to 'UNDEFINED' if the unit is connected for direct access or there is no connection, and to a processor-dependent value otherwise.
READ=
Sets the scalar character object to 'YES' if input is allowed for the file or unit, to 'NO' if input is not allowed for the file or unit, and to 'UNKNOWN' if the answer cannot be determined.
READWRITE=
Sets the scalar character object to 'YES' if both input and output are allowed for the file or unit, to 'NO' if at least one of input or output is not allowed for the file or unit, and to 'UNKNOWN' if the answer cannot be determined.
RECL=
Sets the scalar default integer object to the record length of a file connected for direct access or to the maximum record length of a file connected for sequential access. If there is no connection the object is undefined.
SEQUENTIAL=
Sets the scalar character object to 'YES' if sequential access is allowed for the unit, to 'NO' if sequential access is not allowed, and to 'UNKNOWN' if the answer cannot be determined.
UNFORMATTED=
Sets the scalar character object to 'YES' if unformatted i/o is allowed for the unit, to 'NO' if it is not allowed, and to 'UNKNOWN' if the answer cannot be determined.
WRITE=
Sets the scalar character object to 'YES' if output is allowed for the file or unit, to 'NO' if output is not allowed for the file or unit, and to 'UNKNOWN' if the answer cannot be determined.

Intent Statement

INTENT ( { IN | OUT | INOUT } ) [ :: ] name [ , name ]...

Declares the specified names, which must be the names of dummy arguments, to have the specified intent. INTENT(IN) arguments cannot appear in any context where they will be modified, INTENT(OUT) arguments are undefined on entry to the procedure, and INTENT(INOUT) and INTENT(OUT) arguments can only be associated with modifiable actual arguments (e.g., not expressions).

Interface Statement

INTERFACE
INTERFACE { name | ASSIGNMENT(=) | OPERATOR(operator) }

The first form introduces an interface block, containing interface bodies which specify the interfaces to external or dummy procedures. The second form additionally defines a generic name or operator by which these procedures may be referenced, and its interface block may also contain MODULE PROCEDURE statements.

Intrinsic Statement

INTRINSIC name [ , name ]...

Declares the listed names to be intrinsic procedures.

Module Statement

MODULE name

This is the first statement of a module subprogram.

Module Procedure Statement

MODULE PROCEDURE name [ , name ]...

This statement is only allowed within generic interface blocks, where it declares the listed names as module procedures to be included in the generic.

Namelist Statement

NAMELIST namelist-group [ [ , ] namelist-group ]...

namelist-group ::= /name/ name [ , name ]...

Declares one or more i/o namelists. Multiple NAMELIST specifications for the namelist group /name/ are treated as if they were concatenated. The names in a namelist group must all be variables and not automatic, adjustable, allocatable, pointer, or contain a pointer.

Nullify Statement

NULLIFY ( object [ , object ] ... )

Sets the pointer-association status of the listed objects, which must be pointers, to dissociated.

Open Statement

OPEN ( open-spec [ , open-spec ]... )

open-spec ::= | [ UNIT= ] expr | ACCESS= expr | ACTION= expr | BLANK= expr | CONVERT= expr | DELIM= expr |
 | ERR= label | FILE= expr | FORM= expr | IOSTAT= object | PAD= expr | POSITION= expr |
 | RECL= expr | STATUS= expr

Connects a file to a unit with the specified properties.

Optional Statement

OPTIONAL [ :: ] name [ , name ]...

Declares the specified names, which must be the names of dummy arguments, to be optional dummy arguments.

Parameter Statement

PARAMETER ( name = expr [ , name = expr ]... )

Declares the names to be named constants with the specified values. The expressions must be initialisation expressions and must be assignment compatible with the names.

Pause Statement (deleted)

PAUSE [ constant ]

Pauses program execution. If present, the constant must be a scalar character literal with no kind-param or a digit-string with at most 5 digits.

Pointer Statement

POINTER [ :: ] name [ deferred-shape ] [ , name [ deferred-shape ] ]...

Declares the names to be pointers.

Pointer Assignment Statement

variable => expr

Associates the pointer variable with expr, which must be another pointer, a variable with the TARGET attribute, or a reference to a function that returns a pointer result.

Print Statement

PRINT format [ , output-item ]...

format ::= * | label | expr

Synonymous with a WRITE statement with ‘UNIT=*’ and a FMT=format clause.

The possibilities for format are:

‘*’
indicates list-directed formatting.
label
must be the label of a FORMAT statement.
expr
A character expression may be supplied; its value is interpreted as the text following the keyword FORMAT of a FORMAT statement. If the expression is array-valued the concatenation of all elements is interpreted in this way.
expr
(obsolescent) A default scalar integer variable name may be supplied, in which case it must have been ASSIGNed the label of a FORMAT statement.

Private Statement

PRIVATE [ [ :: ] access-id [ , access-id ]... ]

access-id ::= name | ASSIGNMENT(=) | OPERATOR(operator)

This statement can only occur in the declaration section of a module or before the component definitions in a type definition.

When this statement appears in a type definition, there can be no access-ids; it causes the components of the type to be inaccessible from outside the module in which the type is defined.

In a module's declaration section, this statement either sets the default accessibility of entities within the module to be PRIVATE, i.e., not accessible, or the accessibility of each access-id is set to be PRIVATE.

Program Statement

PROGRAM name

This is the first statement of a main program. It is optional.

Public Statement

PUBLIC [ [ :: ] access-id [ , access-id ]... ]

This statement can only occur in the declaration section of a module. With no access-id list, it confirms that the default accessibility of entities in the module is PUBLIC. With an access-id list, it explicitly sets the accessibility of those access-ids to PUBLIC.

Read Statement

READ format [ , input-item ]...
READ ( control-spec [ , control-spec ]... ) [ input-item [ , input-item ]... ]

input-item ::= variable | ( { input-item , }... do-spec )

control-spec ::= | [ UNIT= ] { * | expr } |
 | [ FMT= ] format | [ NML= ] name | ADVANCE= expr | END= label |
 | EOR= label | ERR= label | IOSTAT= expr | REC= expr | SIZE= expr

(See the PRINT statement for format details.)

Reads one or more records (or partial records with ADVANCE='NO') from the specified unit.

The effect of each control-specifier is as below:

UNIT=
Identifies the i/o unit; ‘*’ indicates the default unit, a scalar integer expression indicates an external unit, and a character expression indicates an internal unit.
FMT=
Establishes the format; this is absent for namelist formatting or for unformatted i/o.
NML=
Specifies a namelist group name for namelist formatted i/o.
ADVANCE=
Indicates whether non-advancing (expression evaluates to 'NO') or the usual advancing (expression evaluates to 'YES') i/o is performed. This control-specifier is only allowed for formatted sequential i/o with an explicit format (i.e., not namelist or list-directed).
END=
Transfers control to the specified label if an end-of-file condition occurs during input (not allowed in WRITE).
EOR=
Transfers control to the specified label if an end-of-record condition occurs during input (not allowed in WRITE). ADVANCE='NO' must be specified.
ERR=
Transfers control to the specified label if an error condition occurs during i/o.
IOSTAT=
Sets the object to −1 if an end-of-file occurs, to −2 if an end-of-record occurs (non-advancing only), to a positive number if an error occurs, and to zero otherwise. Note that the negative values may vary on other compilers.
REC=
Specifies the record number for direct-access i/o.
SIZE=
Sets the object to the number of characters transferred by data edit descriptors (not allowed in WRITE). ADVANCE='NO' must be specified.

Return Statement

RETURN [ expr ]

Return immediately from the procedure. If the procedure is a subroutine with alternate return arguments (obsolescent), the scalar integer expression indicates to which label control is to be transferred on return (if the expression is less than one or greater than the number of alternate return arguments, execution continues with the statement following the subroutine reference).

Rewind Statement

REWIND expr
REWIND ( position-spec-list )

(See the BACKSPACE statement for the position-spec-list definition).

Positions an i/o unit, which must be connected to a rewindable file, to the beginning of the file.

Save Statement

SAVE [ [ :: ] save-item [ , save-item ]... ]

save-item ::= variable-name | /common-block-name/

Specifies the SAVE attribute for the listed variables or common blocks, or, with no save-item list, specifies that all possible variables and common blocks in the current scoping unit should implicitly have the SAVE attribute by default.

Select Statement

[ construct-name : ] SELECT CASE ( expr )

The initial statement of a SELECT CASE construct. Control is transferred to the CASE statement satisfied by the expression's value, or to the END SELECT statement if no CASE is satisfied by the value.

Statement Function Statement (obsolescent)

name ( [ name [ , name ] ... ] ) = expr

Defines a statement function.

Stop Statement

STOP [ constant ]

Halts program execution. If present, the constant must be a scalar character literal with no kind-param or a digit-string with at most 5 digits.

Subroutine Statement

[ RECURSIVE | PURE | ELEMENTAL]... SUBROUTINE name [ ( [ arg-list ] ) ]

(Note that at most one occurrence of each keyword is allowed).

arg-list ::= arg [ , arg ]...
arg ::= name | *

This is the first statement of a subroutine subprogram. RECURSIVE must be specified if the subroutine calls itself, either directly or indirectly. If PURE is specified, the subroutine must satisfy the pure subroutine constraints and can then be called from a pure function. An arg that is ‘*’ signfies an alternate return label; this is obsolescent.

Target Statement

TARGET [ :: ] name [ array-spec ] [ , name [ array-spec ] ]...

Declares that the specified entities have the TARGET attribute.

Type Statement

TYPE name

This statement marks the beginning of the definition of the derived type name.

Type Declaration Statement

type-spec [ [ , attr-spec ] ... :: ] entity-decl-list

attr-spec ::= | ALLOCATABLE | DIMENSION array-spec | EXTERNAL | INTENT ( { IN | OUT | INOUT } ) |
 | INTRINSIC | OPTIONAL | PARAMETER | POINTER | PRIVATE | PUBLIC | SAVE | TARGET

Declares the listed entities to be of the specified type with the specified attributes.

Use Statement

USE name [ , rename-list ]
USE name, ONLY: only-list

rename-list ::= rename [ , rename ]...
rename ::= local-name => remote-name

only-list ::= only-item [ , only-item ]...
only-item ::= name | rename

The USE statement accesses the named module. Multiple USE statements for the same module act as if all the rename-lists and only-lists were concatenated.

If all the USE statements in a scoping unit for a particular module have the ONLY clause, only those items listed in a rename-list or only-list are accessible.

A rename causes item remote-name in the referenced module to be accessible in the local scoping unit by local-name. An only-item that is not a rename causes the name in the referenced module to be accessible in the local scoping unit by the same name.

Where Assignment Statement

variable = expr

The expression is evaluated (and the object updated) only for those elements for which the current control mask is true.

Where Statement

WHERE ( expr ) where-assignment-stmt

Executes the Where Assignment statement with the provided expression as the control mask.

Where Construct Statement

[ construct-name : ] WHERE ( expr )

Begins a Where Construct with the provided expression as the control mask.

Write Statement

WRITE ( control-spec [ , control-spec ] ... ) output-item [ , output-item ]...

(See the READ statement for control-spec details.)

Writes one or more records (or partial records with ADVANCE='NO') to the specified unit.


NAG Fortran Compiler, Release 7.1: Fortran 95 Intrinsic Procedures

 Navigation: Previous Up Next

8.4 Fortran 95 Intrinsic Procedures

This section provides a quick reference guide to the Fortran 90/95 intrinsic functions and subroutines.

Procedures marked with ‘*’ are non-generic versions of other intrinsics. Procedures marked with ‘E’ are elemental.

Procedures marked with ‘I’ are inquiry functions; these query characteristics of a variable other than its value.

Procedures marked with ‘P’ may be supplied as actual procedure arguments; when it is used as a procedure argument all arguments are scalar, no optional arguments are allowed, and it is not generic: if the name is normally generic the procedure argument version is default INTEGER if it begins with the letter I to N, and default REAL otherwise.

Arguments named ‘KIND’ must be initialisation expressions.

Arguments printed in italics (e.g., ‘DIM’) are optional.

Intrinsic Functions

Function Name | Flags | Description
ABS(A) | EP | Absolute value.
ACHAR(I) | E | Produce character from ASCII value.
ACOS(X) | EP | Arccosine.
ADJUSTL(STRING) | E | Adjust string to the left by moving leading blanks to the end.
ADJUSTR(STRING) | E | Adjust string to the right.
AIMAG(Z) | EP | The imaginary part of a complex number.
AINT(A,KIND ) | EP | Truncate to a whole number.
ALL(MASK,DIM) |  | Reduce MASK with the .AND. operation.
ALLOCATED(ARRAY) | I | Whether an allocatable array is allocated.
ALOG(X) | *P | LOG function restricted to scalar default real.
ALOG10(X) | *P | LOG10 function restricted to scalar default real.
AMAX0(A1,A2,A3,...) | * | REAL(MAX(A1,A2,A3,...)) with scalar default integer args.
AMAX1(A1,A2,A3,...) | * | MAX function restricted to scalar default real.
AMIN0(A1,A2,A3,...) | * | REAL(MIN(A1,A2,A3,...)) with scalar default integer args.
AMIN1(A1,A2,A3,...) | * | MIN function restricted to scalar default integer.
AMOD(A,P) | *P | MOD function restricted to scalar default real.
ANINT(A,KIND) | EP | Round to a whole number.
ANY(MASK,DIM) |  | Reduce MASK with the .OR. operation.
ASIN(X) | EP | Arcsine.
ASSOCIATED(POINTER,TARGET) | I | Whether a pointer is associated with a target.
ATAN(X) | EP | Arctangent.
ATAN2(Y,X) | EP | Arctangent.
BIT_SIZE(I) |  | Number of bits in an integer type.
BTEST(I,POS) | E | Whether a particular bit is 1.
CABS(A) | *P | ABS function restricted to scalar default complex.
CCOS(X) | *P | COS function restricted to scalar default complex.
CEILING(A,KIND) | E | Smallest integer greater than or equal to A.
CEXP(X) | *P | EXP function restricted to scalar default complex.
CHAR(I,KIND) | E | Produce character from native coded character set value.
CLOG(X) | *P | LOG function restricted to scalar default complex.
CMPLX(X,Y,KIND) | E | Convert to complex.
CONJG(Z) | EP | Complex conjugate.
COS(X) | EP | Cosine.
COSH(X) | EP | Hyperbolic cosine.
COUNT(MASK,DIM) |  | Reduce MASK by counting .TRUE. elements.
CSHIFT(ARRAY,SHIFT,DIM) |  | Circular shift of an array.
CSIN(X) | *P | SIN function restricted to scalar default complex.
CSQRT(X) | *P | SQRT function restricted to scalar default complex.
DABS(A) | *P | ABS function restricted to scalar double precision.
DACOS(X) | *P | ACOS function restricted to scalar double precision.
DASIN(X) | *P | ASIN function restricted to scalar double precision.
DATAN(X) | *P | ATAN function restricted to scalar double precision.
DATAN2(Y,X) | *P | ATAN2 function restricted to scalar double precision.
DBLE(A) | E | Convert to double precision.
DCOS(X) | *P | COS function restricted to scalar double precision.
DCOSH(X) | *P | COSH function restricted to scalar double precision.
DDIM(X,Y) | *P | DIM function restricted to scalar double precision.
DEXP(X) | *P | EXP function restricted to scalar double precision.
DIGITS(X) | I | Number of mantissa digits in the model for X.
DIM(X,Y) | EP | Non-negative difference, MAX(0,X-Y).
DINT(A) | *P | AINT function restricted to scalar double precision.
DLOG(X) | *P | LOG function restricted to scalar double precision.
DLOG10(X) | *P | LOG10 function restricted to scalar double precision.
DMAX1(A1,A2,A3,...) | * | MAX function restricted to scalar double precision.
DMIN1(A1,A2,A3,...) | * | MIN function restricted to scalar double precision.
DMOD(A,P) | *P | MOD function restricted to scalar double precision.
DNINT(A) | *P | ANINT function restricted to scalar double precision.
DOT_PRODUCT(VECTOR_A,VECTOR_B) |  | Dot product.
DPROD(X,Y) | EP | Double precision result of X*Y.
DSIGN(A,B) | *P | SIGN function restricted to scalar double precision.
DSIN(X) | *P | SIN function restricted to scalar double precision.
DSINH(X) | *P | SINH function restricted to scalar double precision.
DSQRT(X) | *P | SQRT function restricted to scalar double precision.
DTAN(X) | *P | TAN function restricted to scalar double precision.
DTANH(X) | *P | TANH function restricted to scalar double precision.
EOSHIFT(ARRAY,SHIFT,BOUNDARY,DIM) |  | End-off array shift.
EPSILON(X) | I | Number almost neglible compared to 1.
EXP(X) | EP | Exponential (eX).
EXPONENT(X) | E | The exponent part of a floating-point number.
FLOAT(A) | * | REAL function restricted to scalar default integer.
FLOOR(A,KIND) | E | Largest integer less than or equal to A.
FRACTION(X) | E | The mantissa of a floating-point number.
HUGE(X) | I | The largest number in the model for a real type.
IABS(A) | *P | ABS function restricted to scalar default integer.
IACHAR(C) | E | ASCII value for a character.
IAND(I,J) | E | Bitwise and.
IBCLR(I,POS) | E | Clear specified bit.
IBITS(I,POS,LEN) | E | Extract a group of bits.
IBSET(I,POS) | E | Set a bit.
ICHAR(C) | E | Native coded character set value for a character.
IDIM(X,Y) | *P | DIM function restricted to scalar default integer.
IDINT(A) | * | INT function restricted to scalar double precision.
IDNINT(A) | *P | NINT function restricted to scalar double precision.
IEOR(I,J) | E | Bitwise exclusive or.
IFIX(A) | * | INT function restricted to scalar default real.
INDEX(STRING,SUBSTRING,BACK) | EP | Search for substring.
INT(A,KIND) | E | Convert to integer.
IOR(I,J) | E | Bitwise inclusive or.
ISHFT(I,SHIFT) | E | Shift bits.
ISHFTC(I,SHIFT,SIZE) | E | Shift bits circularly.
ISIGN(A,B) | *P | SIGN function restricted to scalar default integer.
KIND(X) | I | Kind type parameter of X.
LBOUND(ARRAY,DIM) | I | Lower bound(s) of an array.
LEN(STRING) | IP | Length of a character string.
LEN_TRIM(STRING) | E | Length of a character string ignoring trailing blanks.
LGE(STRING_A,STRING_B) | E | Comparison (>=) using ASCII collating sequence.
LGT(STRING_A,STRING_B) | E | Comparison (>) using ASCII collating sequence.
LLE(STRING_A,STRING_B) | E | Comparison (<=) using ASCII collating sequence.
LLT(STRING_A,STRING_B) | E | Comparison (<) using ASCII collating sequence.
LOG(X) | EP | Natural logarithm.
LOG10(X) | EP | Common logarithm.
LOGICAL(L,KIND) | E | Convert to a specific logical kind.
MATMUL(MATRIX_A,MATRIX_B) |  | Matrix multiplication.
MAX(A1,A2,A3,...) | E | Maximum value.
MAX0(A1,A2,A3,...) | * | MAX function restricted to scalar default integer.
MAX1(A1,A2,A3,...) | * | INT(MAX(A1,A2,A3,...)) with scalar default real args.
MAXEXPONENT(X) | I | Maximum model exponent value for X.
MAXLOC(ARRAY,MASK) |  | Position of maximum value in an array.
MAXLOC(ARRAY,DIM,MASK) |  | Dimensional reduction of maximum value positions.
MAXVAL(ARRAY,MASK) |  | Reduce a (masked) array with the MAX intrinsic.
MAXVAL(ARRAY,DIM,MASK) |  | Dimensional reduction by the MAX intrinsic.
MERGE(TSOURCE,FSOURCE,MASK) | E | Choose value depending on logical value.
MIN(A1,A2,A3,...) | E | Minimum value.
MIN0(A1,A2,A3,...) | * | MIN function restricted to scalar default integer.
MIN1(A1,A2,A3,...) | * | INT(MIN(A1,A2,A3,...)) with scalar default real args.
MINEXPONENT(X) | I | Minimum model exponent value for X.
MINLOC(ARRAY,MASK) |  | Position of minimum value in an array.
MINLOC(ARRAY,DIM,MASK) |  | Dimensional reduction of minimum value positions.
MINVAL(ARRAY,MASK) |  | Reduce a (masked) array with the MIN intrinsic.
MINVAL(ARRAY,DIM,MASK) |  | Dimensional reduction by the MIN intrinsic.
MOD(A,P) | EP | Remainder; sign(result) = sign(A).
MODULO(A,P) | E | Modulo; sign(result) = sign(P).
NEAREST(X,S) | E | Nearest machine-representable number.
NINT(A,KIND) | EP | Round and convert to integer.
NOT(I) | E | Bitwise complement.
NULL(MOLD) |  | Null (disassociated) pointer.
PACK(ARRAY,MASK,VECTOR) |  | Pack an array into a vector.
PRECISION(X) | I | Decimal model precision for X.
PRESENT(A) | I | Whether an optional argument is present.
PRODUCT(ARRAY,MASK) |  | Reduce a (masked) array by multiplication.
PRODUCT(ARRAY,DIM,MASK) |  | Dimensional reduction by multiplication.
RADIX(X) | I | Model radix for X.
RANGE(X) | I | Decimal model exponent range for X.
REAL(A,KIND) | E | Convert to real.
REPEAT(STRING,NCOPIES) |  | Concatenate a string with itself.
RESHAPE(SOURCE,SHAPE,PAD,ORDER) |  | Reshape an array.
RRSPACING(X) | E | Reciprocal relative model spacing near X.
SCALE(X,I) | E | X*RADIX(X)**I.
SCAN(STRING,SET,BACK) | E | Look for characters in a set.
SELECTED_INT_KIND(R) |  | Integer kind with at least R decimal digits.
SELECTED_REAL_KIND(P,R) |  | Real kind with at least P decimal precision and/or
 |  | at least R decimal exponent range.
SET_EXPONENT(X,I) | E | X*RADIX(X)**(I-EXPONENT(X)).
SHAPE(SOURCE) | I | Shape of an array.
SIGN(A,B) | EP | A with the sign of B.
SIN(X) | EP | Sine.
SINH(X) | EP | Hyperbolic sine.
SIZE(ARRAY,DIM) | I | Size of an array or dimension.
SNGL(A) | * | REAL function restricted to scalar double precision.
SPACING(X) | E | Spacing of model numbers near X.
SPREAD(SOURCE,DIM,NCOPIES) |  | Replicate an array in a given dimension by copying.
SQRT(X) | EP | Square root.
SUM(ARRAY,MASK) |  | Reduce a (masked) array by addition.
SUM(ARRAY,DIM,MASK) |  | Dimensional reduction of a (masked) array by addition.
TAN(X) | EP | Tangent.
TANH(X) | EP | Hyperbolic tangent.
TINY(X) | I | Smallest model number for the kind of X.
TRANSFER(SOURCE,MOLD,SIZE) |  | Copy internal representation.
TRANSPOSE(MATRIX) |  | Transpose an array.
TRIM(STRING) |  | Character string with trailing blanks removed.
UBOUND(ARRAY,DIM) | I | Upper bound(s) of an array.
UNPACK(VECTOR,MASK,FIELD) |  | Unpack a vector into an array.
VERIFY(STRING,SET,BACK) | E | Look for characters not in set.

Intrinsic Subroutines

Subroutine Name | Flags | Description
CPU_TIME(TIME) |  | CPU execution time.
DATE_AND_TIME(DATE,TIME,ZONE,VALUES) |  | Date and time information.
MVBITS(FROM,FROMPOS,LEN,TO,TOPOS) | E | Move or copy bitfield.
RANDOM_NUMBER(HARVEST) |  | Return pseudo-random number(s).
RANDOM_SEED(SIZE,PUT,GET) |  | Control pseudo-random number generator.
SYSTEM_CLOCK(COUNT,COUNT_RATE,COUNT_MAX) |  | Real-time clock information.


NAG Fortran Compiler, Release 7.1: Fortran 2003 Extensions

 Navigation: Previous Up Next

9 Fortran 2003 Extensions

  • 9.1 Fortran 2003 Overview
  • 9.2 Object-oriented programming
    • 9.2.1 Type Extension
    • 9.2.2 Typed allocation [5.1]
    • 9.2.3 Sourced allocation (cloning) [5.1]
    • 9.2.4 Type-bound procedures [5.1]
    • 9.2.5 Abstract derived types [5.1]
    • 9.2.6 Object-bound procedures [5.2]
  • 9.3 ALLOCATABLE extensions
    • 9.3.1 Allocatable Dummy Arrays [4.x]
    • 9.3.2 Allocatable Function Results [4.x]
    • 9.3.3 Allocatable Structure Components [4.x]
    • 9.3.4 Allocatable Component Example
    • 9.3.5 The MOVE_ALLOC intrinsic subroutine [5.2]
    • 9.3.6 Allocatable scalars [5.2]
    • 9.3.7 Automatic reallocation [5.2]
  • 9.4 Other data-oriented enhancements
    • 9.4.1 Parameterised derived types [6.0 for kind type parameters, 6.1 for length]
    • 9.4.2 Finalisation [5.3]
    • 9.4.3 The PROTECTED attribute [5.0]
    • 9.4.4 Pointer enhancements
    • 9.4.5 Individual component accessibility [5.1]
    • 9.4.6 Public entities of private type [5.1]
  • 9.5 C interoperability [mostly 5.1]
    • 9.5.1 The ISO_C_BINDING module
    • 9.5.2 BIND(C) types
    • 9.5.3 BIND(C) variables
    • 9.5.4 BIND(C) procedures
    • 9.5.5 Enumerations
  • 9.6 IEEE arithmetic support [4.x except as otherwise noted]
    • 9.6.1 Introduction
    • 9.6.2 Exception flags, modes and information flow
    • 9.6.3 Procedures in the modules
    • 9.6.4 The IEEE_FEATURES module
    • 9.6.5 IEEE_EXCEPTIONS
    • 9.6.6 IEEE_ARITHMETIC module
  • 9.7 Input/output Features
    • 9.7.1 Stream input/output [5.1]
    • 9.7.2 The BLANK= and PAD= specifiers [5.1]
    • 9.7.3 Decimal Comma [5.1]
    • 9.7.4 The DELIM= specifier [5.1]
    • 9.7.5 The ENCODING= specifier [5.1]
    • 9.7.6 The IOMSG= specifier [5.1]
    • 9.7.7 The IOSTAT= specifier [5.1]
    • 9.7.8 The SIGN= specifier [5.1]
    • 9.7.9 Intrinsic functions for testing IOSTAT= values [5.1]
    • 9.7.10 Input/output of IEEE infinities and NaNs [5.1]
    • 9.7.11 Output of floating-point zero [5.1]
    • 9.7.12 NAMELIST and internal files [5.1]
    • 9.7.13 Variables permitted in NAMELIST
    • 9.7.14 Recursive input/output [5.2]
    • 9.7.15 Asynchronous input/output
    • 9.7.16 Scale factor followed by repeat count [5.1]
    • 9.7.17 FLUSH statement [5.2]
    • 9.7.18 Defined input/output [6.2]
  • 9.8 Miscellaneous Fortran 2003 Features
    • 9.8.1 Abstract interfaces and the PROCEDURE statement [5.1]
    • 9.8.2 Named procedure pointers [5.2]
    • 9.8.3 Intrinsic modules [4.x]
    • 9.8.4 Renaming user-defined operators on the USE statement [5.2]
    • 9.8.5 The ISO_FORTRAN_ENV module [5.1]
    • 9.8.6 The IMPORT statement [5.1]
    • 9.8.7 Length of names and statements
    • 9.8.8 Array constructor syntax enhancements
    • 9.8.9 Structure constructor syntax enhancements [5.3]
    • 9.8.10 Deferred character length [5.2]
    • 9.8.11 The ERRMSG= specifier [5.1]
    • 9.8.12 Intrinsic functions in constant expressions [5.2 partial; 5.3 complete]
    • 9.8.13 Specification functions can be recursive [6.2]
    • 9.8.14 Access to the command line [5.1]
    • 9.8.15 Access to environment variables [5.1]
    • 9.8.16 Character kind selection [5.1]
    • 9.8.17 Argument passing relaxation [5.1]
    • 9.8.18 The MAXLOC and MINLOC intrinsic functions [5.1]
    • 9.8.19 The VALUE attribute [4.x]
    • 9.8.20 The VOLATILE attribute [5.0]
    • 9.8.21 Enhanced complex constants [5.2]
    • 9.8.22 The ASSOCIATE construct [5.2]
    • 9.8.23 Binary, octal and hexadecimal constants [5.2]
    • 9.8.24 Character sets [5.1; 5.3]
    • 9.8.25 Intrinsic function changes for 64-bit machines [5.2]
    • 9.8.26 Miscellaneous intrinsic procedure changes [5.2]


NAG Fortran Compiler, Release 7.1: Fortran 2003 Overview

 Navigation: Previous Up Next

9.1 Fortran 2003 Overview

This part of the manual describes those parts of the Fortran 2003 language which are not in Fortran 95, and indicates which features are currently supported by the NAG Fortran Compiler.

Features marked in the section heading as ‘[5.3.1]’ are newly available in release 5.3.1, those marked ‘[5.3]’ were available in release 5.3, those marked ‘[5.2]’ were available in release 5.2, those marked ‘[5.1]’ were available in release 5.1 (and in some cases earlier), and those marked ‘[n/a]’ are not yet available.

Fortran 2003 is a major advance over Fortran 95: the new language features can be grouped as follows:

  • object-oriented programming features,
  • allocatable attribute extensions,
  • other data-oriented enhancements,
  • interoperability with C,
  • IEEE arithmetic support,
  • input/output enhancements and
  • miscellaneous enhancements.

The basic object-oriented features are type extension, polymorphic variables, and type selection; these provide inheritance and the ability to program ad-hoc polymorphism in a type-safe manner. The advanced features are typed allocation, cloning, type-bound procedures, type-bound generics, and object-bound procedures. Type-bound procedures provide the mechanism for dynamic dispatch (methods).

The ALLOCATABLE attribute is extended to allow it to be used for dummy arguments, function results, structure components, and scalars (not just arrays). An intrinsic procedure has been added to transfer an allocation from one variable to another. Finally, in intrinsic assignment, allocatable variables or components are automatically reallocated with the correct size if they have a different shape or type parameter value from that of the expression. This last feature, together with deferred character length, provides the user with true varying-length character variables.

There are two other major data enhancements: the addition of type parameters to derived types, and finalisation (by final subroutines). Other significant data enhancements are the PROTECTED attribute, pointer bounds specification and rank remapping, procedure pointers, and individual accessibility control for structure components.

Interoperability with the C programming language consists of allowing C procedures to be called from Fortran, Fortran procedures to be called from C, and for the sharing of global variables between C and Fortran. This can only happen where C and Fortran facilities are equivalent: an intrinsic module provides derived types and named constants for mapping Fortran and C types, and the BIND(C) syntax is added for declaring Fortran entities that are to be shared with C. Additionally, C style enumerations have been added.

Support for IEEE arithmetic is provided by three intrinsic modules. Use of the IEEE_FEATURES module requests IEEE compliance for specific Fortran features, the IEEE_EXCEPTIONS module provides access to IEEE modes and exception handling, and the IEEE_ARITHMETIC module provides enquiry functions and utility functions for determining the extent of IEEE conformance and access to IEEE-conformant facilities.

The input/output facilities have had three major new features: asynchronous input/output, stream input/output, and user-defined procedures for derived-type input/output (referred to as “defined input/output”). Additionally, the input/output specifiers have been regularised so that where they make sense: all specifiers that can be used on an OPEN statement can also be used on a READ or WRITE statement, and vice versa. Access to input/output error messages is provided by the new IOMSG= specifier, and processor-dependent constants for input/output (e.g. the unit number for the standard input file) are provided in a new intrinsic module.

Finally, there are a large number of miscellaneous improvements in almost every aspect of the language. Some of the more significant of these are the IMPORT statement (provides host association into interface blocks), the VALUE and VOLATILE attributes, the ability to use all intrinsic functions in constant expressions, and extensions to the syntax of array and structure constructors.


NAG Fortran Compiler, Release 7.1: Object-oriented programming

 Navigation: Previous Up Next

9.2 Object-oriented programming

9.2.1 Type Extension

Type extension provides the first phase of object orientation: inheritance and polymorphic objects.

9.2.1.1 Extending Types [5.0]

Any derived type can be extended using the EXTENDS keyword, except for SEQUENCE types and BIND(C) types. (The latter types are “non-extensible”, as are intrinsic types, whereas all other derived types are “extensible”.) The extended type inherits all the components of the parent type and may add extra components.

For example:

  TYPE point
    REAL x,y
  END TYPE
  TYPE,EXTENDS(point) :: point_3d
    REAL z
  END TYPE
The type point_3d has x, y and z components. Additionally, it has a point component which refers to the inherited part; this “parent component” is “inheritance-associated” with the inherited components, so that the point%x component is identical to the x component et cetera.

However, when extending a type it is not required to add any new components; for example,

  TYPE,EXTENDS(point) :: newpoint
  END TYPE
defines a new type newpoint which has exactly the same components as point (plus the associated parent component). Similarly, it is no longer necessary for a type to contain any components:
  TYPE empty_type
  END TYPE
declares the extensible (but not extended) type empty_type which has no components at all.

9.2.1.2 Polymorphic Variables [5.0]

A polymorphic variable is a pointer, allocatable array or dummy argument that is declared using the CLASS keyword instead of the TYPE keyword. A CLASS(typename) variable can assume any type in the class of types consisting of TYPE(typename) and all extensions of typename.

For example:

  REAL FUNCTION bearing(a)
    CLASS(point) a
    bearing = atan2(a%y,a%x)
  END
The function bearing may be applied to a TYPE(point) object or to a TYPE(point_3d) object, or indeed to an object of any type that is an extension of TYPE(point).

9.2.1.3 Type Selection [5.0]

The SELECT TYPE construct provides both a means of testing the dynamic type of a polymorphic variable and access to the extended components of that variable.

For example:

  CLASS(t) x
  ...
  SELECT TYPE(p=>x)
  TYPE IS (t1)
    !
    ! This section is executed only if X is exactly of TYPE(t1), not an
    ! extension thereof.  P is TYPE(t1).
    !
  TYPE IS (t2)
    !
    ! This section is executed only if X is exactly of TYPE(t2), not an
    ! extension thereof.  P is TYPE(t2).
    !
  CLASS IS (t3)
    !
    ! This section is executed if X is of TYPE(t3), or of some extension
    ! thereof, and if it is not caught by a more specific case.  P is CLASS(t3).
    !
  END SELECT
Note that ‘SELECT TYPE(x)’ is short for ‘SELECT TYPE(x=>x)’.

9.2.1.4 Unlimited polymorphism [5.2]

A variable that is ‘CLASS(*)’ is an unlimited polymorphic variable. It has no type, but can assume any type including non-extensible types and intrinsic types (and kinds). Apart from allocation, deallocation and pointer assignment, to perform any operation on an unlimited polymorphic you first have to discover its type using SELECT TYPE. For example:
  CLASS(*),POINTER :: x
  CHARACTER(17),TARGET :: ch
  x => ch
  SELECT TYPE(x)
  TYPE IS (COMPLEX(KIND=KIND(0d0)))
    PRINT *,x+1
  TYPE IS (CHARACTER(LEN=*))
    PRINT *,LEN(x)
  END SELECT
Note that in the case of CHARACTER the length must be specified as ‘*’ and is automatically assumed from whatever the polymorphic is associated with.

In the case of a non-extensible (i.e. BIND(C) or SEQUENCE) type, SELECT TYPE cannot be used to discover the type; instead, an unsafe pointer assignment is allowed, for example:

  TYPE t
    SEQUENCE
    REAL x
  END TYPE
  CLASS(*),POINTER :: x
  TYPE(t),POINTER :: y
  ...
  y => x ! Unsafe - the compiler cannot tell whether X is TYPE(t).

9.2.1.5 Ad hoc type comparison [5.3]

Two new intrinsic functions are provided for comparing the dynamic types of polymorphic objects. These are

EXTENDS_TYPE_OF(A,MOLD)
SAME_TYPE_AS(A,B)

The arguments must be objects of extensible types (though they need not be polymorphic). SAME_TYPE_AS returns .TRUE. if and only if both A and B have the same dynamic type. EXTENDS_TYPE_OF returns .TRUE. if and only if the dynamic type of A is the same as, or an extension of, the dynamic type of MOLD. Note that if MOLD is an unallocated unlimited polymorphic (CLASS(*)), the result will be true regardless of the state of A.

The arguments are permitted to be unallocated or disassociated, but they are not permitted to be pointers with an undefined association status.

It is recommended that where possible these intrinsic functions be avoided, and that SELECT TYPE be used for type checking instead.

9.2.2 Typed allocation [5.1]

The ALLOCATE statement now accepts a type-spec; this can be used to specify the dynamic type (and type parameters, if any) of an allocation. The type-spec appears before the allocation list, and is separated from it by a double colon.

For example, if T is an extensible type and ET is an extension of T,

    CLASS(t),POINTER :: a(:)
    ALLOCATE(et::a(100))
allocates A to have dynamic type ET. Note that the type-spec in an ALLOCATE statement omits the TYPE keyword for derived types, similarly to the TYPE IS and CLASS IS statements.

An unlimited polymorphic object can be allocated to be any type including intrinsic types: for example

    CLASS(*),POINTER :: c,d
    ALLOCATE(DOUBLE PRECISION::c)
    READ *,n
    ALLOCATE(CHARACTER(LEN=n)::d)
allocates C to be double precision real, and D to be of type CHARACTER with length N.

Typed allocation is only useful for allocating polymorphic variables and CHARACTER variables with deferred length (LEN=:). For a non-polymorphic variable, the type-spec must specify the declared type and, if it is type CHARACTER but not deferred-length, to have the same character length. The character length must not be specifed as an asterisk (CHARACTER(LEN=*)) unless the allocate-object is a dummy argument with an asterisk character length (and vice versa).

Finally, since there is only one type-spec it must be compatible with all the items in the allocation list.

9.2.3 Sourced allocation (cloning) [5.1]

The ALLOCATE statement now accepts the SOURCE= specifier. The dynamic type and value of the allocated entity is taken from the expression in the specifier. If the derived type has type parameters (q.v.), the value for any deferred type parameter is taken from the source expression, and the values for other type parameters must agree. This is not just applicable to derived types: if the entity being allocated is type CHARACTER with deferred length (LEN=:), the character length is taken from the source expression.

Only one entity can be allocated when the SOURCE= specifier is used. Note that when allocating an array the array shape is not taken from the source expression but must be specified in the usual way. If the source expression is an array, it must have the same shape as the array being allocated.

For example,

    CLASS(*),POINTER :: a,b
    ...
    ALLOCATE(a,SOURCE=b)
The allocated variable A will be a “clone” of B, whatever the current type of B happens to be.

9.2.4 Type-bound procedures [5.1]

Type-bound procedures provide a means of packaging operations on a type with the type itself, and also for dynamic dispatch to a procedure depending on the dynamic type of a polymorphic variable.

9.2.4.1 The type-bound procedure part

The type-bound procedure part of a type definition is separated from the components by the CONTAINS statement. The default accessibility of type-bound procedures is public even if the components are private; this may be changed by using the PRIVATE statement after the CONTAINS.

9.2.4.2 Specific type-bound procedures

The syntax of a specific, non-deferred, type-bound procedure declaration is:

PROCEDURE [[,binding-attr-list]::] binding-name [=>procedure-name]

The name of the type-bound procedure is binding-name, and the name of the actual procedure which implements it is procedure-name. If the optional =>procedure-name is omitted, the actual procedure has the same name as the binding.

A type-bound procedure is invoked via an object of the type, e.g.

  CALL variable(i)%tbp(arguments)
Normally, the invoking variable is passed as an extra argument, the “passed-object dummy argument”; by default this is the first dummy argument of the actual procedure and so the first argument in the argument list becomes the second argument, etc. The passed-object dummy argument may be changed by declaring the type-bound procedure with the PASS(argument-name) attribute, in which case the variable is passed as the named argument. The PASS attribute may also be used to confirm the default (as the first argument), and the NOPASS attribute prevents passing the object as an argument at all. The passed-object dummy argument must be a polymorphic scalar variable of that type, e.g. CLASS(t) self.

When a type is extended, the new type either inherits or overrides each type-bound procedure of the old type. An overriding procedure must be compatible with the old procedure; in particular, each dummy argument must have the same type except for the passed-object dummy argument which must have the new type. A type-bound procedure that is declared to be NON_OVERRIDABLE cannot be overridden during type extension.

When a type-bound procedure is invoked, it is the dynamic type of the variable which determines which actual procedure to call.

The other attributes that a type-bound procedure may have are PUBLIC, PRIVATE, and DEFERRED (the latter only for abstract types, which are described later).

9.2.4.3 Generic type-bound procedures

A generic type-bound procedure is a set of specific type-bound procedures, in the same way that an ordinary generic procedure is a set of specific ordinary procedures. It is declared with the GENERIC statement, e.g.
  GENERIC :: generic_name => specific_name_1, specific_name_2, specific_name_3
Generic type-bound procedures may also be operators or assignment, e.g.
  GENERIC :: OPERATOR(+) => add_t_t, add_t_r, add_r_t
Such type-bound generic operators cannot have the NOPASS attribute; the dynamic type of the passed-object dummy argument determines which actual procedure is called.

When a type is extended, the new type inherits all the generic type-bound procedures without exception, and the new type may extend the generic with additional specific procedures. To override procedures in the generic, simply override the specific type-bound procedure. For example, in

  TYPE mycomplex
    ...
  CONTAINS
    PROCEDURE :: myc_plus_r => myc1_plus_r
    PROCEDURE,PASS(B) :: r_plus_myc => r_plus_myc1
    GENERIC :: OPERATOR(+) => myc_plus_r, r_plus_myc
  END TYPE
  ...
  TYPE,EXTENDS(mycomplex) :: mycomplex_2
    ...
  CONTAINS
    PROCEDURE :: myc_plus_r => myc2_plus_r
    PROCEDURE,PASS(B) :: r_plus_myc => r_plus_myc2
  END TYPE
the type mycomplex_2 inherits the generic operator ‘+’; invoking the generic (+) invokes the specific type-bound procedure, which for entities of type mycomplex_2 will invoke the overriding actual procedure (myc2_plus_r or r_plus_myc2).

9.2.5 Abstract derived types [5.1]

An extensible derived type can be declared to be ABSTRACT, e.g.
  TYPE, ABSTRACT :: mytype
An abstract type cannot be instantiated; i.e. it is not allowed to declare a non-polymorphic variable of abstract type, and a polymorphic variable of abstract type must be allocated to be a non-abstract extension of the type.

Abstract type may contain DEFERRED type-bound procedures, e.g.

  ...
  CONTAINS
    PROCEDURE(interface_name),DEFERRED :: tbpname
No binding (“=> name”) is allowed or implied by a deferred procedure binding. The interface_name must be the name of an abstract interface or a procedure with an explicit interface, and defines the interface of the deferred type-bound procedure.

When extending an abstract type, the extended type must also be abstract unless it overrides all of the deferred type-bound procedures with normal bindings.

9.2.6 Object-bound procedures [5.2]

These are procedure pointer components, and act similarly to type-bound procedures except that the binding is per-object not per-type. The syntax of a procedure pointer component declaration is:

PROCEDURE( [proc-interface] ) , proc-component-attr-spec-list :: proc-decl-list

where
  • each proc-component-attr-spec is one of NOPASS, PASS, PASS(arg-name), POINTER, PRIVATE or PUBLIC, and
  • each proc-decl is a component name optionally followed by default initialisation to null (‘=> NULL()’).
The POINTER attribute is required.

Note that object-bound procedures have a passed-object dummy argument just like type-bound procedures; if this is not wanted, the NOPASS attribute must be used (and this is required if the interface is implicit, i.e. when proc-interface is missing or is a type specification).

The following example demonstrates using a list of subroutines with no arguments.

  TYPE action_list
    PROCEDURE(),NOPASS,POINTER :: action => NULL()
    TYPE(action_list),POINTER :: next
  END TYPE
  TYPE(t),TARGET :: top
  TYPE(t),POINTER :: p
  EXTERNAL sub1,sub2
  top%action = sub1
  ALLOCATE(top%next)
  top%next%action = sub2
  ...
  p => top
  DO WHILE (ASSOCIATED(p))
    IF (ASSOCIATED(p%action)) CALL p%action
    p => p%next
  END DO


NAG Fortran Compiler, Release 7.1: ALLOCATABLE extensions

 Navigation: Previous Up Next

9.3 ALLOCATABLE extensions

In Fortran 2003 the ALLOCATABLE attribute is permitted not just on local variables but also on components, dummy variables, and function results. These are the same as described in the ISO Technical Report ISO/IEC TR 15581:1999.

Also, the MOVE_ALLOC intrinsic subroutine has been added, as well as automatic reallocation on assignment.

9.3.1 Allocatable Dummy Arrays [4.x]

A dummy argument can be declared to be an allocatable array, e.g.
    SUBROUTINE s(dum)
      REAL,ALLOCATABLE :: dum(:,:)
      ...
    END SUBROUTINE

Having an allocatable dummy argument means that there must be an explicit interface for any reference: i.e. if the procedure is not an internal or module procedure there must be an accessible interface block in any routine which references that procedure.

Any actual argument that is passed to an allocatable dummy array must itself be an allocatable array; it must also have the same type, kind type parameters, and rank. For example:

   REAL,ALLOCATABLE :: x(:,:)
   CALL s(x)

The actual argument need not be allocated before calling the procedure, which may itself allocate or deallocate the argument. For example:

   PROGRAM example2
     REAL,ALLOCATABLE :: x(:,:)
     OPEN(88,FILE='myfile',FORM='unformatted')
     CALL read_matrix(x,88)
     !
     ... process x in some way
     !
     REWIND(88)
     CALL write_and_delete_matrix(x,88)
   END
   !
   MODULE module
   CONTAINS
     !
     ! This procedure reads the size and contents of an array from an
     ! unformatted unit.
     !
     SUBROUTINE read_matrix(variable,unit)
       REAL,ALLOCATABLE,INTENT(OUT) :: variable(:,:)
       INTEGER,INTENT(IN) :: unit
       INTEGER dim1,dim2
       READ(unit) dim1,dim2
       ALLOCATE(variable(dim1,dim2))
       READ(unit) variable
       CLOSE(unit)
     END SUBROUTINE
     !
     ! This procedures writes the size and contents of an array to an
     ! unformatted unit, and then deallocates the array.
     !
     SUBROUTINE write_and_delete_matrix(variable,unit)
       REAL,ALLOCATABLE,INTENT(INOUT) :: variable(:,:)
       INTEGER,INTENT(IN) :: unit
       WRITE(unit) SIZE(variable,1),SIZE(variable,2)
       WRITE(unit) variable
       DEALLOCATE(variable)
     END SUBROUTINE
   END

9.3.2 Allocatable Function Results [4.x]

The result of a function can be declared to be an allocatable array, e.g.
    FUNCTION af() RESULT(res)
      REAL,ALLOCATABLE :: res

On invoking the function, the result variable will be unallocated. It must be allocated before returning from the function. For example:

    !
    ! The result of this function is the original argument with adjacent
    ! duplicate entries deleted (so if it was sorted, each element is unique).
    !
    FUNCTION compress(array)
      INTEGER,ALLOCATABLE :: compress(:)
      INTEGER,INTENT(IN) :: array(:)
      IF (SIZE(array,1)==0) THEN
        ALLOCATE(compress(0))
      ELSE
        N = 1
        DO I=2,SIZE(array,1)
          IF (array(I)/=array(I-1)) N = N + 1
        END DO
        ALLOCATE(compress(N))
        N = 1
        compress(1) = array(1)
        DO I=2,SIZE(array,1)
          IF (array(I)/=compress(N)) THEN
            N = N + 1
            compress(N) = array(I)
          END IF
        END DO
      END IF
    END

The result of an allocatable array is automatically deallocated after it has been used.

9.3.3 Allocatable Structure Components [4.x]

A structure component can be declared to be allocatable, e.g.
  MODULE matrix_example
    TYPE MATRIX
      REAL,ALLOCATABLE :: value(:,:)
    END TYPE
  END MODULE

An allocatable array component is initially not allocated, just like allocatable array variables. On exit from a procedure containing variables with allocatable components, all the allocatable components are automatically deallocated. This is in contradistinction to pointer components, which are not automatically deallocated. For example:

  SUBROUTINE sub(n,m)
    USE matrix_example
    TYPE(matrix) a,b,c
    !
    ! a%value, b%value and c%value are all unallocated at this point.
    !
    ALLOCATE(a%value(n,m),b%value(n,m))
    !
    ... do some computations, then
    !
    RETURN
    !
    ! Returning from the procedure automatically deallocates a%value, b%value,
    ! and c%value (if they are allocated).
    !
  END
Deallocating a variable that has an allocatable array component deallocates the component first; this happens recursively so that all ALLOCATABLE subobjects are deallocated with no memory leaks.

Any allocated allocatable components of a function result are automatically deallocated after the result has been used.

  PROGRAM deallocation_example
    TYPE inner
      REAL,ALLOCATABLE :: ival(:)
    END TYPE
    TYPE outer
      TYPE(inner),ALLOCATABLE :: ovalue(:)
    END TYPE
    TYPE(outer) x
    !
    ! At this point, x%ovalue is unallocated
    !
    ALLOCATE(x%ovalue(10))
    !
    ! At this point, x%ovalue(i)%ival are unallocated, i=1,10
    !
    ALLOCATE(x%ovalue(2)%ival(1000),x%ovalue(5)%ival(9999))
    !
    ! Only x%ovalue(2)%ival and x%ovalue(5)%ival are allocated
    !
    DEALLOCATE(x%ovalue)
    !
    ! This has automatically deallocated x%ovalue(2)%ival and x%ovalue(5)%ival
    !
  END
In a structure constructor for such a type, the expression corresponding to an allocatable array component can be
  • the NULL() intrinsic, indicating an unallocated array,
  • an allocatable array which may be allocated or unallocated, or
  • any other array expression, indicating an allocated array.
  SUBROUTINE constructor_example
    USE matrix_example
    TYPE(matrix) a,b,c
    REAL :: array(10,10) = 1
    REAL,ALLOCATABLE :: alloc_array(:,:)
    a = matrix(NULL())
    !
    ! At this point, a%value is unallocated
    !
    b = matrix(array*2)
    !
    ! Now, b%value is a (10,10) array with each element equal to 2.
    !
    c = matrix(alloc_array)
    !
    ! Now, c%value is unallocated (because alloc_array was unallocated).
    !
  END

Intrinsic assignment of such types does a “deep copy” of the allocatable array components; it is as if the allocatable array component were deallocated (if necessary), then if the component in the expression was allocated, the variable's component is allocated to the right size and the value copied.

  SUBROUTINE assignment_example
    USE matrix_example
    TYPE(matrix) a,b
    !
    ! First we establish a value for a
    !
    ALLOCATE(a%value(10,20))
    a%value(3,:) = 30
    !
    ! And a value for b
    !
    ALLOCATE(b%value(1,1))
    b%value = 0
    !
    ! Now the assignment
    !
    b = a
    !
    ! The old contents of b%value have been deallocated, and b%value now has
    ! the same size and contents as a%value.
    !
  END

9.3.4 Allocatable Component Example

This example shows the definition and use of a simple module that provides polynomial arithmetic. To do this it makes use of intrinsic assignment for allocatable components, the automatically provided structure constructors and defines the addition (+) operator. A more complete version of this module would provide other operators such as multiplication.
!
! Module providing a single-precision polynomial arithmetic facility
!
MODULE real_poly_module
  !
  ! Define the polynomial type with its constructor.
  ! We will use the convention of storing the coefficients in the normal
  ! order of highest degree first, thus in an N-degree polynomial, COEFF(1)
  ! is the coefficient of X**N, COEFF(N) is the coefficient of X**1, and
  ! COEFF(N+1) is the scalar.
  !
  TYPE,PUBLIC :: real_poly
    REAL,ALLOCATABLE :: coeff(:)
  END TYPE
  !
  PUBLIC OPERATOR(+)
  INTERFACE OPERATOR(+)
    MODULE PROCEDURE rp_add_rp,rp_add_r,r_add_rp
  END INTERFACE
  !
CONTAINS
  TYPE(real_poly) FUNCTION rp_add_r(poly,real)
    TYPE(real_poly),INTENT(IN) :: poly
    REAL,INTENT(IN) :: real
    INTEGER isize
    IF (.NOT.ALLOCATED(poly%coeff)) STOP 'Undefined polynomial value in +'
    isize = SIZE(poly%coeff,1)
    rp_add_r%coeff(isize) = poly%coeff(isize) + real
  END FUNCTION
  TYPE(real_poly) FUNCTION r_add_rp(real,poly)
    TYPE(real_poly),INTENT(IN) :: poly
    REAL,INTENT(IN) :: real
    r_add_rp = rp_add_r(poly,real)
  END FUNCTION
  TYPE(real_poly) FUNCTION rp_add_rp(poly1,poly2)
    TYPE(real_poly),INTENT(IN) :: poly1,poly2
    INTEGER I,N,N1,N2
    IF (.NOT.ALLOCATED(poly1%coeff).OR..NOT.ALLOCATED(poly2%coeff)) &
      STOP 'Undefined polynomial value in +'
    ! Set N1 and N2 to the degrees of the input polynomials
    N1 = SIZE(poly1%coeff) - 1
    N2 = SIZE(poly2%coeff) - 1
    ! The result polynomial is of degree N
    N = MAX(N1,N2)
    ALLOCATE(rp_add_rp%coeff(N+1))
    DO I=0,MIN(N1,N2)
      rp_add_rp%coeff(N-I+1) = poly1%coeff(N1-I+1) + poly2%coeff(N2-I+1)
    END DO
    ! At most one of the next two DO loops is ever executed
    DO I=N1+1,N
      rp_add_rp%coeff(N-I+1) = poly2%coeff(N2-I+1)
    END DO
    DO I=N2+1,N
      rp_add_rp%coeff(N-I+1) = poly1%coeff(N1-I+1)
    END DO
  END FUNCTION
END MODULE
!
! Sample program
!
PROGRAM example
  USE real_poly_module
  TYPE(real_poly) p,q,r
  p = real_poly((/1.0,2.0,4.0/))   ! x**2 + 2x + 4
  q = real_poly((/1.0,-5.5/))      ! x - 5.5
  r = p + q                        ! x**2 + 3x - 1.5
  print 1,'The coefficients of the answer are:',r%coeff
1 format(1x,A,3F8.2)
END

When executed, the above program prints:

 The coefficients of the answer are:    1.00    3.00   -1.50

9.3.5 The MOVE_ALLOC intrinsic subroutine [5.2]

This subroutine moves an allocation from one allocatable variable to another. This can be used to expand an allocatable array with only one copy operation, and allows full control over where in the new array the values should go. For example:
  REAL,ALLOCATABLE :: a(:),tmp(:)
  ...
  ALLOCATE(a(n))
  ...
  ! Here we want to double the size of A, without losing any of the values
  ! that are already stored in it.
  ALLOCATE(tmp(size(a)*2))
  tmp(1:size(a)) = a
  CALL move_alloc(from=tmp,to=a)
  ! TMP is now deallocated, and A has the new size and values.
To have the values end up somewhere different, just change the assignment statement, for example to move them all to the end:
  tmp(size(a)+1:size(a)*2) = a

9.3.6 Allocatable scalars [5.2]

The ALLOCATABLE attribute may now be applied to scalar variables and components, not just arrays. This is most useful in conjunction with polymorphism (CLASS) and/or deferred type parameters (e.g. CHARACTER(:)); for more details see the “Typed allocation”, “Sourced allocation” and “Automatic reallocation” sections.

9.3.7 Automatic reallocation [5.2]

If, in an assignment to a whole allocatable array, the expression being assigned is an array of a different size or shape, the allocatable array is reallocated to have the correct shape (in Fortran 95 this assignment would have been an error). For example:
  ALLOCATE(a(10))
  ...
  a = (/ (i,i=1,100) /)
  ! A is now size 100

Similarly, if an allocatable variable has a deferred type parameter (these are described in a later section), and is either unallocated or has a value different from that of the expression, the allocatable variable is reallocated to have the same value for that type parameter. This allows for true varying-length character variables:

  CHARACTER(:),ALLOCATABLE :: name
  ...
  name = 'John Smith'
  ! LEN(name) is now 10, whatever it was before.
  name = '?'
  ! LEN(name) is now 1.
Note that since a subobject of an allocatable object is not itself allocatable, this automatic reallocation can be suppressed by using substrings (for characters) or array sections (for arrays), e.g.
  name(:) = '?'             ! Normal assignment with truncation/padding.
  a(:) = (/ (i,i=1,100) /)  ! Asserts that A is already of size 100.


NAG Fortran Compiler, Release 7.1: Other data-oriented enhancements

 Navigation: Previous Up Next

9.4 Other data-oriented enhancements

9.4.1 Parameterised derived types [6.0 for kind type parameters, 6.1 for length]

Derived types may now have type parameters. Like those of the intrinsic types, they come in two flavours: "kind"-like ones which must be known at compile time (called “kind” type parameters), and ones like character length which may vary at runtime (called “length” type parameters).

9.4.1.1 Basic Syntax and Semantics

A derived type which has type parameters must list them in the type definition, give them a type, and specify whether they are “kind” or “length” parameters. For example,
  TYPE real_matrix(kind,n,m)
    INTEGER,KIND :: kind
    INTEGER(int64),LEN :: n,m

All type parameters must be explicitly specified to be of type INTEGER, but the kind of integer may vary. Type parameters are always scalar, never arrays. Within the type definition, “kind” type parameters may be used in constant expressions, and any type parameter may be used in a specification expression (viz array bound, character length, or “length” type parameter value). For example, the rest of the above type definition might look like:

    REAL(kind) value(n,m)
  END TYPE real_matrix

When declaring entities of such a derived type, the type parameters must be given after the name. For example,

  TYPE(real_matrix(KIND(0d0),100,200)) :: my_real_matrix_variable
Similarly, the type parameters must be given when constructing values of such a type; for example,
  my_real_matrix_variable = &
    real_matrix(kind(0d0),100,200)((/ (i*1.0d0,i=1,20000) /))

To examine the value of a derived type parameter from outside the type definition, the same notation is used as for component accesses, e.g.

  print *,'Columns =',my_real_matrix_variable%m
Thus type parameter names are in the same class as component names and type-bound procedure names. However, a type parameter cannot be changed by using its specifier on the left-hand-side of an assignment. Furthermore, the intrinsic type parameters may also be examined using this technique, for example:
  REAL :: array(:,:)
  CHARACTER(*),INTENT(IN) :: ch
  PRINT *,array%kind,ch%len
prints the same values as for KIND(array) and LEN(ch). Note that a kind parameter enquiry is always scalar, even if the object is an array.

A derived type parameter does not actually have to be used at all within the type definition, and a kind type parameter might only be used within specification expressions. For example,

  TYPE fixed_byte(n)
    INTEGER,KIND :: n
    INTEGER(1) :: value(n)
  END TYPE
  TYPE numbered_object(object_number)
    INTEGER,LEN :: object_number
  END TYPE
Even though the fixed_byte parameter n is not used in a constant expression, a constant value must always be specified for it because it has been declared to be a “kind” type parameter. Similarly, even though object_number has not been used at all, a value must always be specified for it. This is not quite as useless as it might seem: each numbered_object has a single value for object_number even if the numbered_object is an array.

9.4.1.2 More Semantics

A derived type with type parameters can have default values for one or more of them; in this case the parameters with default values may be omitted from the type specifiers. For example,
  TYPE char_with_maxlen(maxlen,kind)
    INTEGER,LEN :: maxlen = 254
    INTEGER,KIND   :: kind = SELECTED_CHAR_KIND('ascii')
    INTEGER        :: len = 0
    CHARACTER(len=maxlen,kind=kind) :: value
  END TYPE
  ...
  TYPE(char_with_maxlen) temp
  TYPE(char_with_maxlen(80)) card(1000)
  TYPE(char_with_maxlen(kind=SELECTED_CHAR_KIND('iso 10646'))) ucs4_temp

Note that although kind type parameters can be used in constant expressions and thus in default initialisation, components that are variable-sized (because they depend on length type parameters) cannot be default-initialised at all. Thus value in the example above cannot be default-initialised.

Further note that unlike intrinsic types, there are no automatic conversions for derived type assignment with different type parameter values, thus given the above declarations,

  card(1) = card(2) ! This is ok, maxlen==80 for both sides.
  temp = card       ! This is not allowed - maxlen 254 vs. maxlen 80.

9.4.1.3 Assumed type parameters

Assumed type parameters for derived types work similarly to character length, except that they are only allowed for dummy arguments (not for named constants). For example, the following subroutine works on any char_with_maxlen variable.
  SUBROUTINE stars(x)
    TYPE(char_with_maxlen(*)) x
    x%value = REPEAT('*',x%maxlen)
  END SUBROUTINE

9.4.1.4 Deferred type parameters

Deferred type parameters are completely new to Fortran 2003; these are available both for CHARACTER and for parameterised derived types, and work similarly to deferred array bounds. A variable with a deferred type parameter must have the ALLOCATABLE or POINTER attribute. The value of a deferred type parameter for an allocatable variable is that determined by allocation (either by a typed allocation, or by an intrinsic assignment with automatic reallocation). For a pointer, the value of a deferred type parameter is the value of the type parameter of its target. For example, using the type real_matrix defined above,
  TYPE(real_matrix(KIND(0.0),100,200)),TARGET :: x
  TYPE(real_matrix(KIND(0.0),:,:)),POINTER :: y, z
  ALLOCATE(real_matrix(KIND(0.0),33,44) :: y)  ! Typed allocation.
  z => x                                       ! Assumes from the target.
  PRINT *,y%n,z%n                              ! Prints 33 and 100.
Note that it is not allowed to reference the value of a deferred type parameter of an unallocated allocatable or of a pointer that is not associated with a target.

If a dummy argument is allocatable or a pointer, the actual argument must have deferred exactly the same type parameters as the dummy. For example,

  SUBROUTINE sub(rm_dble_ptr)
    TYPE(real_matrix(KIND(0d0),*,:)),POINTER :: rm_dble_ptr
  ...
  TYPE(real_matrix(KIND(0d0),100,200)),POINTER :: x
  TYPE(real_matrix(KIND(0d0),100,:)),POINTER :: y
  TYPE(real_matrix(KIND(0d0),:,:)),POINTER :: z
  CALL sub(x)  ! Invalid - X%M is not deferred (but must be).
  CALL sub(y)  ! This is ok.
  CALL sub(z)  ! Invalid - X%N is deferred (but must not be).

9.4.2 Finalisation [5.3]

An extensible derived type can have “final subroutines” associated with it; these subroutines are automatically called whenever an object of the type is about to be destroyed, whether by deallocation, procedure return, being on the left-hand-side of an intrinsic assignment, or being passed to an INTENT(OUT) dummy argument.

A final subroutine of a type must be a subroutine with exactly one argument, which must be an ordinary dummy variable of that type (and must not be INTENT(OUT)). It may be scalar or an array, and when an object of that type is destroyed the final subroutine whose argument has the same rank as the object is called. The final subroutine may be elemental, in which case it will handle any rank of object that has no other subroutine handling it. Note that if there is no final subroutine for the rank of an object, no subroutine will be called.

Final subroutines are declared in the type definition after the CONTAINS statement, like type-bound procedures. They are declared by a FINAL statement, which has the syntax

FINAL [ :: ] name [ , name ]...

where each name is a subroutine that satisfies the above rules.

A simple type with a final subroutine is as follows.

  TYPE flexible_real_vector
    LOGICAL :: value_was_allocated = .FALSE.
    REAL,POINTER :: value(:) => NULL()
  CONTAINS
    FINAL destroy_frv
  END TYPE
  ...
  ELEMENTAL SUBROUTINE destroy_frv(x)
    TYPE(flexible_real_vector),INTENT(INOUT) :: x
    IF (x%value_was_allocated) DEALLOCATE(x%value)
  END SUBROUTINE

If an object being destroyed has finalisable components, any final subroutine for the object-as-a-whole will be called before finalising any components. If the object is an array, each component will be finalised separately (and any final subroutine called will be the one for the rank of the component, not the rank of the object).

For example, in

  TYPE many_vectors
    TYPE(flexible_real_vector) scalar
    TYPE(flexible_real_vector) array(2,3)
  CONTAINS
    FINAL :: destroy_many_vectors_1
  END TYPE
  ...
  SUBROUTINE destroy_many_vectors_1(array1)
    TYPE(many_vectors) array1(:)
    PRINT *,'Destroying a',SIZE(array1),'element array of many vectors'
  END SUBROUTINE
  ...
  TYPE(many_vector) mv_object(3)
when mv_object is destroyed, firstly ‘destroy_many_vectors_1’ will be called with mv_object as its argument; this will print
 Destroying a 3 element array of many vectors
Secondly, for each element of the array, both the scalar and array components will be finalised by calling destroy_frv on each of them. These may be done in any order (or, since they are elemental, potentially in parallel).

Note that final subroutines are not inherited through type extension; instead, when an object of extended type is destroyed, first any final subroutine it has will be called, then any final subroutine of the parent type will be called on the parent component, and so on.

9.4.3 The PROTECTED attribute [5.0]

The PROTECTED attribute may be specified by the PROTECTED statement or with the PROTECTED keyword in a type declaration statement. It protects a module variable against modification from outside the module.

9.4.3.1 Syntax

The syntax of the PROTECTED statement is:

PROTECTED [ :: ] name [ , name ] ...

The PROTECTED attribute may only be specified for a variable in a module.

9.4.3.2 Semantics

Variables with the PROTECTED attribute may only be modified within the defining module. Outside of that module they are not allowed to appear in a variable definition context (e.g. on the left-hand-side of an assignment statement), similar to INTENT(IN) dummy arguments.

This allows the module writer to make the values of some variables generally available without relinquishing control over their modification.

9.4.3.3 Example

MODULE temperature_module
  REAL,PROTECTED :: temperature_c = 0, temperature_f = 32
CONTAINS
  SUBROUTINE set_temperature_c(new_value_c)
    REAL,INTENT(IN) :: new_value_c
    temperature_c = new_value_c
    temperature_f = temperature_c*(9.0/5.0) + 32
  END SUBROUTINE
  SUBROUTINE set_temperature_f(new_value_f)
    REAL,INTENT(IN) :: new_value_f
    temperature_f = new_value_f
    temperature_c = (temperature_f - 32)*(5.0/9.0)
  END SUBROUTINE
END
The PROTECTED attribute allows users of temperature_module to read the temperature in either Farenheit or Celsius, but the variables can only be changed via the provided subroutines which ensure that both values agree.

9.4.4 Pointer enhancements

9.4.4.1 INTENT for pointers [5.1]

A POINTER dummy argument may now have the INTENT attribute. This attribute applies to the pointer association status, not to the target of the pointer.

An INTENT(IN) pointer can be assigned to, but cannot be pointer-assigned, nullified, allocated or deallocated. An INTENT(OUT) pointer receives an undefined association status on entry to the procedure. An INTENT(INOUT) pointer has no restrictions on its use, but the actual argument must be a pointer variable, not a pointer function reference.

9.4.4.2 Pointer bounds specification [5.2]

The bounds of a pointer can be changed (from the default) in a pointer assignment by including them on the left-hand-side. For example,
  REAL,TARGET :: x(-100:100,-10:10)
  REAL,POINTER :: p(:,:)
  p(1:,1:) => x
The upper bound is formed by adding the extent (minus 1) to the lower bound, so in the above example, the bounds of P will be 1:201,1:21. Note that when setting the lower bound of any rank in a pointer assignment, the values must be explicitly specified (there is no default of 1 like there is in array declarators) and they must be specified for all dimensions of the pointer.

9.4.4.3 Rank-remapping Pointer Assignment [5.0]

This feature allows a multi-dimensional pointer to point to a single-dimensional object. For example:
  REAL,POINTER :: diagonal(:),matrix(:,:),base(:)
  ...
  ALLOCATE(base(n*n))
  matrix(1:n,1:n) => base
  diagonal => base(::n+1)
  !
  ! DIAGONAL now points to the diagonal elements of MATRIX.
  !

Note that when rank-remapping, the values for both the lower and upper bounds must be explicitly specified for all dimensions, there are no defaults.

9.4.5 Individual component accessibility [5.1]

It is now possible to set the accessibility of individual components in a derived type. For example,
  TYPE t
    LOGICAL, PUBLIC :: flag
    INTEGER, PRIVATE :: state
  END TYPE
The structure constructor for the type is not usable from outside the defining module if there is any private component that is not inherited, allocatable or default-initialised (see Structure constructor syntax enhancements).

9.4.6 Public entities of private type [5.1]

It is now possible to export entities (named constants, variables, procedures) from a module even if they have private type or (for procedures) have arguments of private type. For example,
  MODULE m
    TYPE, PRIVATE :: hidden_type
      CHARACTER(6) :: code
    END TYPE
    TYPE(hidden_type), PUBLIC, PARAMETER :: code_green = hidden_type('green')
    TYPE(hidden_type), PUBLIC, PARAMETER :: code_yellow = hidden_type('yellow')
    TYPE(hidden_type), PUBLIC, PARAMETER :: code_red = hidden_type('red')
  END


NAG Fortran Compiler, Release 7.1: C interoperability [mostly 5.1]

 Navigation: Previous Up Next

9.5 C interoperability [mostly 5.1]

9.5.1 The ISO_C_BINDING module

The intrinsic module ISO_C_BINDING contains
  • for each C type (e.g. float), a named constant for use as a KIND parameter for the corresponding Fortran type,
  • types C_PTR and C_FUNPTR for interoperating with C object pointers and function pointers,
  • procedures for manipulating Fortran and C pointers.

9.5.1.1 The kind parameters

The kind parameter names are for using with the corresponding Fortran types; for example, INTEGER for integral types and REAL for floating-point types. This is shown in the table below. Note that only c_int is guaranteed to be available; if there is no compatible type the value will be negative.

C type | Fortran type and kind
_Bool | LOGICAL(c_bool)
char | CHARACTER(c_char) — For characters as text.
double | REAL(c_double)
double _Complex | COMPLEX(c_double_complex) or COMPLEX(c_double)
float | REAL(c_float)
float _Complex | COMPLEX(c_float_complex) or COMPLEX(c_float)
int | INTEGER(c_int)
int16_t | INTEGER(c_int16_t)
int32_t | INTEGER(c_int32_t)
int64_t | INTEGER(c_int64_t)
int8_t | INTEGER(c_int8_t)
int_fast16_t | INTEGER(c_int_fast16_t)
int_fast32_t | INTEGER(c_int_fast32_t)
int_fast64_t | INTEGER(c_int_fast64_t)
int_fast8_t | INTEGER(c_int_fast8_t)
int_least16_t | INTEGER(c_int_least16_t)
int_least32_t | INTEGER(c_int_least32_t)
int_least64_t | INTEGER(c_int_least64_t)
int_least8_t | INTEGER(c_int_least8_t)
intmax_t | INTEGER(c_intmax_t)
intptr_t | INTEGER(c_intptr_t)
long | INTEGER(c_long)
long double | REAL(c_long_double)
long double _Complex | COMPLEX(c_long_double_complex) or COMPLEX(c_long_double)
long long | INTEGER(c_long_long)
short | INTEGER(c_short)
signed char | INTEGER(c_signed_char) — For characters as integers.
size_t | INTEGER(c_size_t)

9.5.1.2 Using C_PTR and C_FUNPTR

These are derived type names, so you use them as Type(c_ptr) and Type(c_funptr). Type(c_ptr) is essentially equivalent to the C void *; i.e. it can contain any object pointer. Type(c_funptr) does the same thing for function pointers.

For C arguments like ‘int *’, you don't need to use Type(c_ptr), you can just use a normal dummy argument (in this case of type Integer(c_int)) without the VALUE attribute. However, for more complicated pointer arguments such as pointer to pointer, or for variables or components that are pointers, you need to use Type(c_ptr).

Null pointer constants of both Type(c_ptr) and Type(c_funptr) are provided: these are named C_NULL_PTR and C_NULL_FUNPTR respectively.

To create a Type(c_ptr) value, the function C_LOC(X) is used on a Fortran object X (and X must have the TARGET attribute). Furthermore, the Fortran object cannot be polymorphic, a zero-sized array, an assumed-size array, or an array pointer. To create a Type(c_funptr) value, the function C_FUNLOC is used on a procedure; this procedure must have the BIND(C) attribute.

To test whether a Type(c_ptr) or Type(c_funptr) is null, the C_ASSOCIATED(C_PTR_1) function can be used; it returns .TRUE. if and only if C_PTR_1 is not null. Two Type(c_ptr) or two Type(c_funptr) values can be compared using C_ASSOCIATED(C_PTR_1,C_PTR_2) function; it returns .TRUE. if and only if C_PTR_1 contains the same C address as C_PTR_2.

The subroutine C_F_POINTER(CPTR,FPTR) converts the TYPE(C_PTR) value CPTR to the scalar Fortran pointer FPTR; the latter can have any type (including non-interoperable types) but must not be polymorphic. The subroutine C_F_POINTER(CPTR,FPTR,SHAPE) converts a TYPE(C_PTR) value into the Fortran array pointer FPTR, where SHAPE is an integer array of rank 1, with the same number of elements as the rank of FPTR; the lower bounds of the resultant FPTR will all be 1.

The subroutine C_F_PROCPOINTER(CPTR,FPTR) is provided. This converts the TYPE(C_FUNPTR) CPTR to the Fortran procedure pointer FPTR.

Note that in all the conversion cases it is up to the programmer to use the correct type and other information.

9.5.2 BIND(C) types

Derived types corresponding to C struct types can be created by giving the type the BIND(C) attribute, e.g.
  TYPE,BIND(C) :: mytype
The components of a BIND(C) type must have types corresponding to C types, and cannot be pointers or allocatables. Furthermore, a BIND(C) type cannot be a SEQUENCE type (it already acts like a SEQUENCE type), cannot have type-bound procedures, cannot have final procedures, and cannot be extended.

9.5.3 BIND(C) variables

Access to C global variables is provided by giving the Fortran variable the BIND(C) attribute. Such a variable can only be declared in a module, and cannot be in a COMMON block. By default, the C name of the variable is the Fortran name converted to all lowercase characters; a different name may be specified with the NAME= clause, e.g.
  INTEGER,BIND(C,NAME="StrangelyCapiTalisedCName") :: x
Within Fortran code, the variable is referred to by its Fortran name, not its C name.

9.5.4 BIND(C) procedures

A Fortran procedure that can be called from C can be defined using the BIND(C) attribute on the procedure heading. By default its C name is the Fortran name converted to lowercase; a different name may be specified with the NAME= clause. For example
  SUBROUTINE sub() BIND(C,NAME='Sub')
  ...
Again, the C name is for use only from C, the Fortran name is used from Fortran. If the C name is all blanks (or a zero-length string), there is no C name. Such a procedure can still be called from C via a procedure pointer (i.e. by assigning it to a TYPE(C_FUNPTR) variable).

A BIND(C) procedure must be a module procedure or external procedure with an explicit interface; it cannot be an internal procedure or statement function.

A BIND(C) procedure may be a subroutine or a scalar function with a type corresponding to a C type. Each dummy argument must be a variable whose type corresponds to a C type, and cannot be allocatable, assumed-shape, optional or a pointer. If the dummy argument does not have the VALUE attribute, it corresponds to a C dummy argument that is a pointer.

Here is an example of a Fortran procedure together with its reference from C:

SUBROUTINE find_minmax(x,n,max,min) BIND(C,NAME='FindMinMax')
  USE iso_c_binding
  REAL(c_double) x(*),max,min
  INTEGER(c_int),VALUE :: n
  INTRINSIC maxval,minval
  max = MAXVAL(x(:n))
  min = MINVAL(x(:n))
END

extern void FindMinMax(double *x,int n,double *maxval,double *minval);
double x[100],xmax,xmin;
int n;
...
FindMinMax(x,n,&xmax,&xmin);

This also allows C procedures to be called from Fortran, by describing the C procedure to be called in an interface block. Here is an example:

/* This is the prototype for a C library function from 4.3BSD. */
int getloadavg(double loadavg[],int nelem);

PROGRAM show_loadavg
  USE iso_c_binding
  INTERFACE
    FUNCTION getloadavg(loadavg,nelem) BIND(C)
      IMPORT c_double,c_int
      REAL(c_double) loadavg(*)
      INTEGER(c_int),VALUE :: nelem
      INTEGER(c_int) getloadavg
    END FUNCTION
  END INTERFACE
  REAL(c_double) averages(3)
  IF (getloadavg(averages,3)/=3) THEN
    PRINT *,'Unexpected error'
  ELSE
    PRINT *,'Load averages:',averages
  END IF
END

9.5.5 Enumerations

An enumeration defines a set of integer constants of the same kind, and is equivalent to the C enum declaration. For example,
  ENUM,BIND(C)
    ENUMERATOR :: open_door=4, close_door=17
    ENUMERATOR :: lock_door
  END ENUM
is equivalent to
  enum {
    open_door=4, close_door=17, lock_door
  };
If a value is not given for one of the enumerators, it will be one greater than the previous value (or zero if it is the first enumerator in the list). The kind used for a particular set of enumerators can be discovered by using the KIND intrinsic on one of the enumerators.

Note that the BIND(C) clause is required; the standard only defines enumerations for interoperating with C.


NAG Fortran Compiler, Release 7.1: IEEE arithmetic support [4.x except as otherwise noted]

 Navigation: Previous Up Next

9.6 IEEE arithmetic support [4.x except as otherwise noted]

9.6.1 Introduction

Three intrinsic modules are provided to support use of IEEE arithmetic, these are: IEEE_ARITHMETIC, IEEE_EXCEPTIONS and IEEE_FEATURES. This extension is small superset of the one described by the ISO Technical Report ISO/IEC TR 15580:1999.

9.6.2 Exception flags, modes and information flow

The model of IEEE arithmetic used by Fortran 2003 is that there is a global set of flags that indicate whether particular floating-point exceptions (such as overflow) have occurred, several operation modes which affect floating-point operations and exception handling, and a set of rules for propagating the flags and modes to obtain good performance and reliability.

The propagation rule for the exception flags is that the information “flows upwards”. Thus each procedure starts with the flags clear, and when it returns any flag that is set will cause the corresponding flag in the caller to become set. This ensures that procedures that can be executed in parallel will not interfere with each other via the IEEE exception flags. When the computer hardware only supports a single global set of flags, this model needs enforcement on in procedures that themselves examine the flags (by IEEE_GET_FLAG or IEEE_GET_STATUS).

The propagation rule for modes, is that the mode settings “flow downwards”. This enables code motion optimisations within all routines, and the only cost is that procedures which modify the modes must restore them (to the state on entry) when they return.

The modes that are available are:

  • separately, whether each floating point exception terminates the program or allows execution to continue (providing a default result and raising an exception flag);
  • rounding mode for floating-point operations;
  • underflow mode.

9.6.3 Procedures in the modules

All the procedures provided by these modules are generic procedures, and not specific: that means that they cannot be passed as actual arguments.

The function IEEE_SELECTED_REAL_KIND, and all the functions whose names begin with IEEE_SUPPORT_, are permitted to appear in specification and constant expressions (as long as the arguments are appropriate for the context). The elemental functions are also permitted to appear in specification expressions, but not constant expressions.

In the descriptions of the procedures, where it says REAL(*) it means any kind of REAL (this is not standard Fortran syntax). Conversely, where it says LOGICAL it means default LOGICAL only, not any other kind of LOGICAL.

The functions whose names begin ‘IEEE_SUPPORT_’ are all enquiry functions. Many of these take a REAL(*) argument X; only the kind of X is used by the enquiry function, so X is permitted to be undefined, unallocated, disassociated, or an undefined pointer.

Note that a procedure must not be invoked on a data type that does not support the feature the procedure uses; the “support” enquiry functions can be used to detect this.

9.6.4 The IEEE_FEATURES module

This module defines the derived type IEEE_FEATURES_TYPE, and up to 11 constants of that type representing IEEE features: these are as follows.

IEEE_DATATYPE | whether any IEEE datatypes are available
IEEE_DENORMAL | whether IEEE subnormal values are available*
IEEE_DIVIDE | whether division has the accuracy required by IEEE*
IEEE_HALTING | whether control of halting is supported
IEEE_INEXACT_FLAG | whether the inexact exception is supported*
IEEE_INF | whether IEEE positive and negative infinities are available*
IEEE_INVALID_FLAG | whether the invalid exception is supported*
IEEE_NAN | whether IEEE NaNs are available*
IEEE_ROUNDING | whether all IEEE rounding modes are available*
IEEE_SQRT | whether SQRT conforms to the IEEE standard*
IEEE_UNDERFLOW_FLAG | whether the underflow flag is supported*

(*) for at least one kind of REAL.

Those feature types which are required by the user procedure should be explicitly referenced by the USE statement with an ONLY clause, e.g.

  USE,INTRINSIC :: IEEE_FEATURES,ONLY:IEEE_SQRT

This ensures that if the feature specified is not available the compilation will fail.

The type IEEE_FEATURES_TYPE is not in itself useful.

9.6.5 IEEE_EXCEPTIONS

Provides data types, constants and generic procedures for handling IEEE floating-point exceptions.

9.6.5.1 Types and constants

TYPE IEEE_STATUS_TYPE
Variables of this type can hold a floating-point status value; it combines all the mode settings and flags.

TYPE IEEE_FLAG_TYPE
Values of this type specify individual IEEE exception flags; constants for these are available as follows.

IEEE_DIVIDE_BY_ZERO | division by zero flag
IEEE_INEXACT | inexact result flag
IEEE_INVALID | invalid operation flag
IEEE_OVERFLOW | overflow flag
IEEE_UNDERFLOW | underflow flag

In addition, two array constants are available for indicating common combinations of flags:

  TYPE(IEEE_FLAG_TYPE),PARAMETER :: &
     IEEE_USUAL(3) = (/ IEEE_DIVIDE_BY_ZERO,IEEE_INVALID,IEEE_OVERFLOW /), &
     IEEE_ALL(5) = (/ IEEE_DIVIDE_BY_ZERO,IEEE_INVALID,IEEE_OVERFLOW, &
                      IEEE_UNDERFLOW,IEEE_INEXACT /)

9.6.5.2 Procedures

The procedures provided by IEEE_EXCEPTIONS are as follows.
ELEMENTAL SUBROUTINE IEEE_GET_FLAG(FLAG,FLAG_VALUE)
  TYPE(IEEE_FLAG_TYPE),INTENT(IN) :: FLAG
  LOGICAL,INTENT(OUT) :: FLAG_VALUE
Sets FLAG_VALUE to .TRUE. if the exception flag indicated by FLAG is currently set, and to .FALSE. otherwise.

ELEMENTAL SUBROUTINE IEEE_GET_HALTING_MODE(FLAG,HALTING)
  TYPE(IEEE_FLAG_TYPE),INTENT(IN) :: FLAG
  LOGICAL,INTENT(OUT) :: HALTING
Sets HALTING to .TRUE. if the program will be terminated on the occurrence of the floating-point exception designated by FLAG, and to .FALSE. otherwise.

PURE SUBROUTINE IEEE_GET_STATUS(STATUS_VALUE)
  TYPE(IEEE_STATUS_TYPE),INTENT(OUT) :: STATUS_VALUE
Sets STATUS_VALUE to the current floating-point status; this contains all the current exception flag and mode settings.

PURE SUBROUTINE IEEE_SET_FLAG(FLAG,FLAG_VALUE)
  TYPE(IEEE_FLAG_TYPE),INTENT(IN) :: FLAG
  LOGICAL,INTENT(IN) :: FLAG_VALUE
Sets the exception flag designated by FLAG to FLAG_VALUE. FLAG may be an array of any rank, as long as it has no duplicate values, in which case FLAG_VALUE may be scalar or an array with the same shape.

PURE SUBROUTINE IEEE_SET_HALTING_MODE(FLAG,HALTING)
  TYPE(IEEE_FLAG_TYPE),INTENT(IN) :: FLAG
  LOGICAL,INTENT(IN) :: HALTING
Sets the halting mode for the exception designated by FLAG to HALTING. FLAG may be an array of any rank, as long as it has no duplicate values, in which case HALTING may be scalar or an array with the same shape.

PURE SUBROUTINE IEEE_SET_STATUS(STATUS_VALUE)
  TYPE(IEEE_STATUS_TYPE),INTENT(IN) :: STATUS_VALUE
Sets the floating-point status to that stored in STATUS_VALUE. This must have been previously obtained by calling IEEE_GET_STATUS.

PURE LOGICAL FUNCTION IEEE_SUPPORT_FLAG(FLAG)
  TYPE(IEEE_FLAG_TYPE),INTENT(IN) :: FLAG
Returns whether the exception flag designated by FLAG is supported for all kinds of REAL.

PURE LOGICAL FUNCTION IEEE_SUPPORT_FLAG(FLAG,X)
  TYPE(IEEE_FLAG_TYPE),INTENT(IN) :: FLAG
  REAL(*),INTENT(IN) :: X
Returns whether the exception flag designated by FLAG is supported for REAL with the kind of X.

PURE LOGICAL FUNCTION IEEE_SUPPORT_HALTING(FLAG)
  TYPE(IEEE_FLAG_TYPE),INTENT(IN) :: FLAG
Returns whether control of the “halting mode” for the exception designated by FLAG is supported.

9.6.6 IEEE_ARITHMETIC module

Provides additional functions supporting IEEE arithmetic: it includes the entire contents of IEEE_EXCEPTIONS.

9.6.6.1 IEEE datatype selection

The IEEE_SELECTED_REAL_KIND function is similar to the SELECTED_REAL_KIND intrinsic function, but selects among IEEE-compliant REAL types ignoring any that are not compliant.

9.6.6.2 Enquiry functions

PURE LOGICAL FUNCTION IEEE_SUPPORT_DATATYPE()
Returns whether all real variables X satisfy the conditions for IEEE_SUPPORT_DATATYPE(X).

PURE LOGICAL FUNCTION IEEE_SUPPORT_DATATYPE(X)
  REAL(*),INTENT(IN) :: X
Returns whether variables with the kind of X satisfy the following conditions:
  • the numbers with absolute value between TINY(X) and HUGE(X) are exactly those of an IEEE floating-point format;
  • the +, - and * operations conform to IEEE for at least one rounding mode;
  • the functions IEEE_COPY_SIGN, IEEE_LOGB, IEEE_NEXT_AFTER, IEEE_NEXT_DOWN, IEEE_NEXT_UP, IEEE_REM, IEEE_SCALB and IEEE_UNORDERED may be used.

PURE LOGICAL FUNCTION IEEE_SUPPORT_DENORMAL()

PURE LOGICAL FUNCTION IEEE_SUPPORT_DENORMAL(X)
  REAL(*),INTENT(IN) :: X
Returns whether for all real kinds, or variables with the kind of X, subnormal values (with absolute value between zero and TINY) exist as required by IEEE and operations on them conform to IEEE.
PURE LOGICAL FUNCTION IEEE_SUPPORT_DIVIDE()

PURE LOGICAL FUNCTION IEEE_SUPPORT_DIVIDE(X)
  REAL(*),INTENT(IN) :: X
Returns whether intrinsic division (/) conforms to IEEE, for all real kinds or variables with the kind of X respectively.

PURE LOGICAL FUNCTION IEEE_SUPPORT_INF()

PURE LOGICAL FUNCTION IEEE_SUPPORT_INF(X)
  REAL(*),INTENT(IN) :: X
Returns whether for all real kinds, or variables with the kind of X, positive and negative infinity values exist and behave in conformance with IEEE.
PURE LOGICAL FUNCTION IEEE_SUPPORT_IO()

PURE LOGICAL FUNCTION IEEE_SUPPORT_IO(X)
  REAL(*),INTENT(IN) :: X
[5.2] Returns whether for all real kinds, or variables with the kind of X, conversion to and from text during formatted input/output conforms to IEEE, for the input/output rounding modes ROUND='DOWN', 'NEAREST', 'UP' and 'ZERO' (and the corresponding edit descriptors RD, RN, RU and RZ).

PURE LOGICAL FUNCTION IEEE_SUPPORT_NAN()

PURE LOGICAL FUNCTION IEEE_SUPPORT_NAN(X)
  REAL(*),INTENT(IN) :: X
Returns whether for all real kinds, or variables with the kind of X, positive and negative “Not-a-Number” values exist and behave in conformance with IEEE.
PURE LOGICAL FUNCTION IEEE_SUPPORT_ROUNDING(ROUND_VALUE)
  TYPE(IEEE_ROUND_TYPE),INTENT(IN) :: ROUND_VALUE

PURE LOGICAL FUNCTION IEEE_SUPPORT_ROUNDING(ROUND_VALUE,X)
  TYPE(IEEE_ROUND_TYPE),INTENT(IN) :: ROUND_VALUE
  REAL(*),INTENT(IN) :: X
Returns whether for all real kinds, or variables with the kind of X, the rounding mode designated by ROUND_VALUE may be set using IEEE_SET_ROUNDING_MODE and conforms to IEEE.

PURE LOGICAL FUNCTION IEEE_SUPPORT_SQRT()

PURE LOGICAL FUNCTION IEEE_SUPPORT_SQRT(X)
  REAL(*),INTENT(IN) :: X
Returns whether the intrinsic function SQRT conforms to IEEE, for all real kinds or variables with the kind of X respectively.

PURE LOGICAL FUNCTION IEEE_SUPPORT_SUBNORMAL()

PURE LOGICAL FUNCTION IEEE_SUPPORT_SUBNORMAL(X)
  REAL(*),INTENT(IN) :: X
[7.0] Returns whether for all real kinds, or variables with the kind of X, subnormal values (with absolute value between zero and TINY) exist as required by IEEE and operations on them conform to IEEE. This function is from Fortran 2018.

PURE LOGICAL FUNCTION IEEE_SUPPORT_STANDARD()

PURE LOGICAL FUNCTION IEEE_SUPPORT_STANDARD(X)
  REAL(*),INTENT(IN) :: X
Returns whether for all real kinds, or variables with the kind of X, all the facilities described by the IEEE modules except for input/output conversions (see IEEE_SUPPORT_IO) are supported and conform to IEEE.
PURE LOGICAL FUNCTION IEEE_SUPPORT_UNDERFLOW_CONTROL()

PURE LOGICAL FUNCTION IEEE_SUPPORT_UNDERFLOW_CONTROL(X)
  REAL(*),INTENT(IN) :: X
[5.2] Returns whether for all real kinds, or variables with the kind of X, the underflow mode can be controlled with IEEE_SET_UNDERFLOW_MODE.

9.6.6.3 Rounding mode

TYPE IEEE_ROUND_TYPE
Values of this type specify the IEEE rounding mode. The following predefined constants are provided.

IEEE_DOWN | round down (towards minus infinity)
IEEE_NEAREST | round to nearest (ties to even)
IEEE_TO_ZERO | round positive numbers down, negative numbers up
IEEE_UP | round up (towards positive infinity)
IEEE_OTHER | any other rounding mode

PURE SUBROUTINE IEEE_GET_ROUNDING_MODE(ROUND_VALUE)
  TYPE(IEEE_ROUND_TYPE),INTENT(OUT) :: ROUND_VALUE
Set ROUND_VALUE to the current rounding mode.

PURE SUBROUTINE IEEE_SET_ROUNDING_MODE(ROUND_VALUE)
  TYPE(IEEE_ROUND_TYPE),INTENT(IN) :: ROUND_VALUE
Set the rounding mode to that designated by ROUND_VALUE.

9.6.6.4 Underflow mode

The underflow mode is either “gradual underflow” as specified by the IEEE standard, or “abrupt underflow”.

With gradual underflow, the space between -TINY(X) and TINY(X) is filled with equally-spaced “subnormal” numbers; the spacing of these numbers is equal to the spacing of model numbers above TINY(X) (and equal to the smallest subnormal number). This gradually reduces the precision of the numbers as they get closer to zero: the smallest number has only one bit of precision, so any calculation with such a number will have a very large relative error.

With abrupt underflow, the only value between -TINY(X) and TINY(X) is zero. This kind of underflow is nearly universal in non-IEEE arithmetics and is widely provided by hardware even for IEEE arithmetic. Its main advantage is that it can be much faster.

SUBROUTINE IEEE_GET_UNDERFLOW_MODE(GRADUAL)
  LOGICAL,INTENT(OUT) :: GRADUAL
Sets GRADUAL to .TRUE. if the current underflow mode is gradual underflow, and to .FALSE. if it is abrupt underflow.
SUBROUTINE IEEE_SET_UNDERFLOW_MODE(GRADUAL)
  LOGICAL,INTENT(IN) :: GRADUAL
Sets the underflow mode to gradual underflow if GRADUAL is .TRUE., and to abrupt underflow if it is .FALSE..

9.6.6.5 Number Classification

TYPE IEEE_CLASS_TYPE
Values of this type indicate the IEEE class of a number; this is equal to one of the provided constants:

IEEE_NEGATIVE_DENORMAL | negative subnormal number x, in the range −TINY(x)<x<0
IEEE_NEGATIVE_INF | −∞ (negative infinity)
IEEE_NEGATIVE_NORMAL | negative normal number x, in the range −HUGE(x)≤x≤−TINY(x)
IEEE_NEGATIVE_ZERO | −0 (zero with the sign bit set)
IEEE_POSITIVE_DENORMAL | positive subnormal number x, in the range 0<x<TINY(x)
IEEE_POSITIVE_INF | +∞ (positive infinity)
IEEE_POSITIVE_NORMAL | positive normal number x, in the range TINY(x)≤x≤HUGE(x)
IEEE_POSITIVE_ZERO | +0 (zero with the sign bit clear)
IEEE_QUIET_NAN | Not-a-Number (usually the result of an invalid operation)
IEEE_SIGNALING_NAN | Not-a-Number which raises the invalid signal on reference
[5.2] IEEE_OTHER_VALUE | any value that does not fit one of the above categories

[7.0] The constants IEEE_POSITIVE_SUBNORMAL and IEEE_NEGATIVE_SUBNORMAL, from Fortran 2018, are also provided; they have the same values as IEEE_POSITIVE_DENORMAL and IEEE_NEGATIVE_DENORMAL respectively.

The comparison operators .EQ. (=) and .NE. (/=) are provided for comparing values of this type.

ELEMENTAL TYPE(IEEE_CLASS_TYPE) FUNCTION IEEE_CLASS(X)
  REAL(*),INTENT(IN) :: X
returns the classification of the value of X.

ELEMENTAL REAL(*) FUNCTION IEEE_VALUE(X,CLASS)
  REAL(*),INTENT(IN) :: X
  TYPE(IEEE_CLASS_TYPE),INTENT(IN) :: CLASS
Returns a “sample” value with the kind of X and the classification designated by CLASS.

9.6.6.6 Test functions

The following procedures are provided for testing IEEE values.

ELEMENTAL LOGICAL FUNCTION IEEE_IS_FINITE(X)
  REAL(*),INTENT(IN) :: X
Returns whether X is “finite”, i.e. not an infinity, NaN, or IEEE_OTHER_VALUE.

ELEMENTAL LOGICAL FUNCTION IEEE_IS_NAN(X)
  REAL(*),INTENT(IN) :: X
Returns whether X is a NaN.

ELEMENTAL LOGICAL FUNCTION IEEE_IS_NEGATIVE(X)
  REAL(*),INTENT(IN) :: X
Returns whether X is negative; it differs the comparison X<0 only in the case of negative zero, where it returns .TRUE..

ELEMENTAL LOGICAL FUNCTION IEEE_UNORDERED(X,Y)
  REAL(*),INTENT(IN) :: X,Y
Returns the value of ‘IEEE_IS_NAN(X) .OR. IEEE_IS_NAN(Y)’.

9.6.6.7 Arithmetic functions

ELEMENTAL REAL(*) FUNCTION IEEE_COPY_SIGN(X,Y)
  REAL(*),INTENT(IN) :: X,Y
Returns X with the sign bit of Y.

ELEMENTAL REAL(*) FUNCTION IEEE_LOGB(X)
  REAL(*),INTENT(IN) :: X
If X is zero, returns −∞ if infinity is supported and -HUGE(X) otherwise. For nonzero X, returns EXPONENT(X)-1

ELEMENTAL REAL(*) FUNCTION IEEE_NEXT_AFTER(X,Y)
  REAL(*),INTENT(IN) :: X,Y
Returns the nearest number to X that is closer to Y, or X if X and Y are equal. If the result is subnormal, IEEE_UNDERFLOW is signalled. If the result is infinite but X was finite, IEEE_OVERFLOW is signalled.

ELEMENTAL REAL(*) FUNCTION IEEE_NEXT_DOWN(X)
  REAL(*),INTENT(IN) :: X
[7.0] Returns the nearest number to X that is less than it, unless X is −∞ or NaN, in which case if X is a signalling NaN a quiet NaN is returned, otherwise X is returned. No exception is signalled unless X is a signalling NaN.

ELEMENTAL REAL(*) FUNCTION IEEE_NEXT_UP(X)
  REAL(*),INTENT(IN) :: X
[7.0] Returns the nearest number to X that is greater than it, unless X is +∞ or NaN, in which case if X is a signalling NaN a quiet NaN is returned, otherwise X is returned. No exception is signalled unless X is a signalling NaN.

ELEMENTAL REAL(*) FUNCTION IEEE_REM(X,Y)
  REAL(*),INTENT(IN) :: X,Y
Returns the exact remainder resulting from the division of X by Y.

ELEMENTAL REAL(*) FUNCTION IEEE_RINT(X)
  REAL(*),INTENT(IN) :: X
Returns X rounded to an integer according to the current rounding mode.

ELEMENTAL REAL(*) FUNCTION IEEE_SCALB(X,I)
  REAL(*),INTENT(IN) :: X
  INTEGER(*),INTENT(IN) :: I
Returns SCALE(X,I), i.e. X*2I, without computing 2I separately.


NAG Fortran Compiler, Release 7.1: Input/output Features

 Navigation: Previous Up Next

9.7 Input/output Features

9.7.1 Stream input/output [5.1]

A stream file is a file that is opened with the ACCESS='STREAM' specifier. A stream file is either a formatted stream or an unformatted stream.

A formatted stream file is equivalent to a C text stream; this acts much like an ordinary sequential file, except that there is no limit on the length of a record. Just as in C, when writing to a formatted stream, an embedded newline character in the data causes a new record to be created. The new intrinsic enquiry function NEW_LINE(A) returns this character for the kind (character set) of A; if the character set is ASCII, this is equal to IACHAR(10). For example,

  OPEN(17,FORM='formatted',ACCESS='stream',STATUS='new')
  WRITE(17,'(A)'), 'This is record 1.'//NEW_LINE('A')//'This is record 2.'

An unformatted stream file is equivalent to a C binary stream, and has no record boundaries. This makes it impossible to BACKSPACE an unformatted stream. Data written to an unformatted stream is transferred to the file with no formatting, and data read from an unformatted stream is transferred directly to the variable as it appears in the file.

When reading or writing a stream file, the POS= specifier may be used to specify where in the file the data is to be written. The first character of the file is at position 1. The POS= specifier may also be used in an INQUIRE statement, in which case it returns the current position in the file. When reading or writing a formatted stream, the POS= in a READ or WRITE shall be equal to 1 (i.e. the beginning of the file) or to a value previously discovered through INQUIRE.

Note that unlike unformatted sequential files, writing to an unformatted stream file at a position earlier than the end of the file does not truncate the file. (However, this truncation does happen for formatted streams.)

Finally, the STREAM= specifier has been added to the INQUIRE statement. This specifier takes a scalar default character variable, and assigns it the value 'YES' if the file may be opened for stream input/output (i.e. with ACCESS='STREAM'), the value 'NO' if the file cannot be opened for stream input/output, and the value 'UNKNOWN' if it is not known whether the file may be opened for stream input/output.

9.7.2 The BLANK= and PAD= specifiers [5.1]

The BLANK= and PAD= specifiers, which previously were only allowed on an OPEN statement (and INQUIRE), are now allowed on a READ statement. These change the BLANK= or PAD= mode for the duration of that READ statement only.

9.7.3 Decimal Comma [5.1]

It is possible to read and write numbers with a decimal comma instead of a decimal point. Support for this is provied by the DECIMAL= specifier and the DC and DP edit descriptors. The DECIMAL= specifier may appear in OPEN, READ, WRITE and INQUIRE statements; possible values are 'POINT' (the default) and 'COMMA'. For an unconnected or unformatted unit, INQUIRE returns 'UNDEFINED'. The DC edit descriptor temporarily sets the mode to DECIMAL='COMMA', and the DP edit descriptor temporarily sets the mode to DECIMAL='POINT'.

When the mode is DECIMAL='COMMA', all floating-point output will produce a decimal comma instead of a decimal point, and all floating-point input will expect a decimal comma. For example,

  PRINT '(1X,"Value cest ",DC,F0.2)',1.25
will produce the output
 Value cest 1,25

Additionally, in this mode, a comma cannot be used in list-directed input to separate items; instead, a semi-colon may be used.

9.7.4 The DELIM= specifier [5.1]

The DELIM= specifier, which previously was only allowed on an OPEN statement (and INQUIRE), is now allowed on a WRITE statement. It changes the DELIM= mode for the duration of that WRITE statement; note that this only has any effect if the WRITE statement uses list-directed or namelist output. For example,
  WRITE(*,*,DELIM='QUOTE') "That's all folks!"
will produce the output
 'That''s all folks!'

9.7.5 The ENCODING= specifier [5.1]

The ENCODING= specifier is permitted on OPEN and INQUIRE statements. Standard values for this specifier are 'UTF-8' and the default value of 'DEFAULT'; the 'UTF-8' value is only allowed on compilers that support a Unicode character kind (see SELECTED_CHAR_KIND). This release of the NAG Fortran Compiler supports 'DEFAULT' and 'ASCII'.

9.7.6 The IOMSG= specifier [5.1]

The IOMSG= specifier has been added to all input/output statements. This takes a scalar default character variable, which in the event of an error is assigned an explanatory message. (Note that this is only useful if the statement contains an IOSTAT= or ERR= specifier, otherwise the program will be terminated on error anyway.) If no error occurs, the value of the variable remains unchanged.

9.7.7 The IOSTAT= specifier [5.1]

This now accepts any kind of integer variable (previously this was required to be default integer).

9.7.8 The SIGN= specifier [5.1]

The SIGN= specifier has been added to the OPEN, WRITE and INQUIRE statements; possible values are 'PLUS', 'SUPPRESS' and 'PROCESSOR_DEFINED' (the default). For the NAG Fortran Compiler, SIGN='PROCESSOR_DEFINED' has the same effect as SIGN='SUPPRESS'.

The effect of SIGN='PLUS' is the same as the SP edit descriptor,
the effect of SIGN='SUPPRESS' is the same as the SS edit
descriptor, and the effect of SIGN='PROCESSOR_DEFINED' is the same
as the S edit descriptor.

9.7.9 Intrinsic functions for testing IOSTAT= values [5.1]

The intrinsic functions IS_IOSTAT_END and IS_IOSTAT_EOR test IOSTAT= return values, determining whether a value indicates an end-of-file condition or an end-of-record condition. These are equivalent to testing the IOSTAT= return value against the named constants IOSTAT_END and IOSTAT_EOR respectively; these constants are available through the ISO_FORTRAN_ENV module.

9.7.10 Input/output of IEEE infinities and NaNs [5.1]

Input and output of IEEE infinities and NaNs is possible: the output format is
  • -Infinity (or -Inf if it will not fit) for negative infinity;
  • Infinity (or Inf if it will not fit) for positive infinity, or +Infinity (or +Inf) with SP or SIGN='PLUS' mode;
  • NaN for a NaN.
Furthermore, the output is right-justified within the output field. For list-directed output the output field is the minimum size to hold the result.

Input of IEEE infinities and NaNs is now possible; these take the same form as the output described above, except that:

  • case is not significant,
  • a NaN may be preceded by a sign, which is ignored, and
  • a NaN may be followed by alphanumeric characters enclosed in parentheses (the NAG Fortran Compiler also ignores these).
The result of reading a NaN value in NAG Fortran is always a quiet NaN, never a signalling one.

9.7.11 Output of floating-point zero [5.1]

List-directed and namelist output of floating-point zero is now done using F format instead of E format. (The Fortran 90 and 95 standards both specified E format.)

9.7.12 NAMELIST and internal files [5.1]

Namelist input/output is now permitted to/from internal files.

9.7.13 Variables permitted in NAMELIST

All variables except for assumed-size arrays are now permitted to appear in a namelist group [6.0 for allocatable and pointer, 5.3.1 for the rest]. Note that an allocatable variable that appears in a namelist group must be allocated, and a pointer variable that appears in a namelist group must be associated, when a READ or WRITE statement with that namelist is executed. Also, if a variable is polymorphic or has an ultimate component that is allocatable or a pointer, it is only permitted in a namelist when it will be processed by defined input/output (see below).

9.7.14 Recursive input/output [5.2]

Input/output to internal files is now permitted while input/output to another internal file or an external file is in progress. This occurs when a function in an input/output list executes an internal file READ or WRITE statement.

Input/output to an external file while external file input/output is already in progress remains prohibited, except for the case of nested data transfer (see “Defined input/output”).

9.7.15 Asynchronous input/output

9.7.15.1 Basic syntax [5.1]

Asynchronous input/output syntax is accepted; this consists of the ASYNCHRONOUS= specifier on OPEN, READ, WRITE and INQUIRE, the ID= specifier on READ, WRITE and INQUIRE, and the PENDING= specifier on INQUIRE.

Except for the INQUIRE statement, the ASYNCHRONOUS= specifier takes a scalar default character expression; this must evaluate either to 'YES' or 'NO', treating lowercase the same as uppercase. In the READ and WRITE statements, this character expression must be a constant expression, and the statement must refer to an external file whose connection allows asynchronous input/output; if ASYNCHRONOUS='YES' is specified, the data transfer may occur asynchronously. In the OPEN statement, this specifier determines whether asynchronous data transfer is allowed for that file: the default setting is 'NO'. For the INQUIRE statement, the ASYNCHRONOUS= specifier takes a scalar default character variable, and sets it to 'YES' if the file is currently connected for asynchronous input/output, 'NO' if the current connection does not allow asynchronous input/output and 'UNKNOWN' if the file is not connected.

For the READ and WRITE statements, the ID= specifier takes a scalar integer variable. This specifier is only permitted if ASYNCHRONOUS='YES' also appears. The integer variable is assigned the “identifier” of the asynchronous data transfer that the READ or WRITE initiates; this value can be used in INQUIRE and WAIT statements to track the progress of the asynchronous data transfer.

For the INQUIRE statement, the ID= specifier takes a scalar integer expression whose value must be that returned from ID= on a READ or WRITE statement for that file, and is only permitted in conjunction with the PENDING= specifier. The PENDING= specifier takes a scalar default logical variable and sets it to .TRUE. if the specified asynchronous data transfer is still underway and to .FALSE. if it has completed. If PENDING= is used without ID=, the enquiry is about all outstanding asynchronous data transfer on that file.

After initiating an asynchronous data transfer, the variables affected must not be referenced or defined until after the transfer is known to have finished. For an asynchronous WRITE of a local variable, this means not returning from the procedure until after ensuring the transfer is complete. An asynchronous data transfer is known to have been finished if there is a subsequent synchronous data transfer, an INQUIRE statement which returns .FALSE. for PENDING=, or a WAIT statement has been executed; in each case, for that file.

9.7.15.2 Basic Example

The following example uses two buffers, buf1 and buf2, alternately reading into one while processing the other, while there is still data in the file to process (each dataset being followed by a single logical value which indicates whether more is to come).
  REAL :: buf1(n,m),buf2(n,m)
  LOGICAL more,stillwaiting
  READ (unit) buf1
  DO
    READ (unit) more ! Note: synchronous
    IF (more) READ (unit,ASYNCHRONOUS='YES') buf2
    CALL process(buf1)
    IF (.NOT.more) EXIT
    READ (unit) more ! Note: synchronous
    IF (more) READ (unit,ASYNCHRONOUS='YES') buf1
    CALL process(buf2)
    IF (.NOT.more) EXIT
  END DO

Note that the synchronous READ statements automatically “wait” for any outstanding asynchronous data transfer to complete before reading the logical value; this ensures that the dataset will have finished being read into its buffer and is safe to process.

9.7.15.3 The ASYNCHRONOUS attribute [5.2]

A READ or WRITE statement with ASYNCHRONOUS='YES' automatically gives the ASYNCHRONOUS attribute to any variable that appears in its input/output list, in a SIZE= specifier, or which is part of a namelist specified by NML=. This is adequate for asynchronous data transfers that initiate and complete within a single procedure. However, it is inadequate for transfers to/from module variables or dummy arguments if the procedure returns while the transfer is still underway.

The ASYNCHRONOUS attribute may be explicitly specified in a type declaration statement or in an ASYNCHRONOUS statement. The latter has the syntax

ASYNCHRONOUS [::] variable-name [ , variable-name ]...

If a variable with the ASYNCHRONOUS attribute is a dummy array and is not an assumed-shape array or array pointer, any associated actual argument cannot be an array section, an assumed-shape array or array pointer. Furthermore, if a dummy argument has the ASYNCHRONOUS attribute the procedure must have an explicit interface. Both of these restrictions apply whether the attribute was given explicitly or implicitly.

9.7.15.4 The WAIT statement [5.2]

The WAIT statement provides the ability to wait for an asynchronous data transfer to finish without performing any other input/output operation. It has the form

WAIT ( wait-spec [ , wait-spec ]... )

where wait-spec is one of the following:

UNIT = file-unit-number
END = label
EOR = label
ERR = label
ID = scalar-integer-variable
IOMSG = scalar-default-character-variable
IOSTAT = scalar-integer-variable

The UNIT= specifier must appear, but the ‘UNIT =’ may be omitted if it is the first specifier in the list. The ID= specifier takes a scalar integer expression whose value must be that returned from ID= on a READ or WRITE statement for the file; if the ID= specifier does not appear the WAIT statement refers to all pending asynchronous data transfer for that file.

On completion of execution of the WAIT statement the specified asynchronous data transfers have been completed. If the specified file is not open for asynchronous input/output or is not connected, the WAIT statement has no effect (it is not an error unless the ID= specifier was used with an invalid value).

Here is an example of using the WAIT statement.

  REAL array(1000,1000,10),xferid(10)
  ! Start reading each segment of the array
  DO i=1,10
    READ (unit,id=xfer(i)) array(:,:,i)
  END DO
  ...
  ! Now process each segment of the array
  DO i=1,10
    WAIT (unit,id=xfer(i))
    CALL process(array(:,:,i)
  END DO

9.7.15.5 Execution Semantics

At this time all actual input/output operations remain synchronous, as allowed by the standard.

9.7.16 Scale factor followed by repeat count [5.1]

The comma that was previously required between a scale factor (n P) and a repeat count (e.g. the ‘3’ in 3E12.2), is now optional. This trivial extension was part of Fortran 66 that was removed in Fortran 77, and reinstated in Fortran 2003.

9.7.17 FLUSH statement [5.2]

Execution of a FLUSH statement causes the data written to a specified file to be made available to other processes, or causes data placed in that file by another process to become available to the program. The syntax of the FLUSH statement is similar to the BACKSPACE, ENDFILE and REWIND statements, being one of the two possibilities

FLUSH file-unit-number
FLUSH ( flush-spec [ , flush-spec ]... )

where file-unit-number is the logical unit number (a scalar integer expression), and flush-spec is one of the following:

UNIT = file-unit-number
IOSTAT = scalar-integer-variable
IOMSG = scalar-default-character-variable
ERR = label

The UNIT= specifier must appear, but the ‘UNIT =’ may be omitted if it is the first flush-spec in the list.

Here is an example of the use of a FLUSH statement.

   WRITE (pipe) my_data
   FLUSH (pipe)

9.7.18 Defined input/output [6.2]

The generic identifiers READ(FORMATTED), READ(UNFORMATTED), WRITE(FORMATTED) and WRITE(UNFORMATTED) provide the ability to replace normal input/output processing for an item of derived type. In the case of formatted input/output, the replacement will occur for list-directed formatting, namelist formatting, and for an explicit format with the DT edit descriptor: it does not affect any other edit descriptors in an explicit format. Using defined input/output, it is possible to perform input/output on derived types containing pointer components and allocatable components, since the user-defined procedure will be handling it.

Here is a type definition with defined input/output procedures.

  TYPE tree
    TYPE(tree_node),POINTER :: first
  CONTAINS
    PROCEDURE :: fmtread=>tree_fmtread
    PROCEDURE :: fmtwrite=>tree_fmtwrite
    GENERIC,PUBLIC :: READ(formatted)=>fmtread, WRITE(formatted)=>fmtwrite
  END TYPE

Given the above type definition, whenever a TYPE(tree) object is an effective item in a formatted input/output list, the module procedure tree_fmtread will be called (in a READ statement) or the module procedure tree_fmtwrite will be called (in a WRITE statement) to perform the input or output of that object. Note that a generic interface block may also be used to declare procedures for defined input/output; this is the only option for sequence or BIND(C) types but is not recommended for extensible types.

The procedures associated with each input/output generic identifier must have the same characteristics as the ones listed below, where type-declaration is CLASS(derived-type-spec) for an extensible type and TYPE(derived-type-spec) for a sequence or BIND(C) type. Note that if the derived type has any length type parameters, they must be “assumed” (specified as ‘*’).

SUBROUTINE formatted_read(var,unit,iotype,vlist,iostat,iomsg)
type-declaration,INTENT(INOUT) :: var
INTEGER,INTENT(IN) :: unit
CHARACTER(*),INTENT(IN) :: iotype
INTEGER,INTENT(IN) :: vlist(:)
INTEGER,INTENT(OUT) :: iostat
CHARACTER(*),INTENT(INOUT) :: iomsg

SUBROUTINE unformatted_read(var,unit,iostat,iomsg)
type-declaration,INTENT(INOUT) :: var
INTEGER,INTENT(IN) :: unit
INTEGER,INTENT(OUT) :: iostat
CHARACTER(*),INTENT(INOUT) :: iomsg

SUBROUTINE formatted_write(var,unit,iotype,vlist,iostat,iomsg)
type-declaration,INTENT(IN) :: var
INTEGER,INTENT(IN) :: unit
CHARACTER(*),INTENT(IN) :: iotype
INTEGER,INTENT(IN) :: vlist(:)
INTEGER,INTENT(OUT) :: iostat
CHARACTER(*),INTENT(INOUT) :: iomsg

SUBROUTINE unformatted_write(var,unit,iostat,iomsg)
type-declaration,INTENT(IN) :: var
INTEGER,INTENT(IN) :: unit
INTEGER,INTENT(OUT) :: iostat
CHARACTER(*),INTENT(INOUT) :: iomsg

In each procedure, unit is either a normal unit number if the parent input/output statement used a normal unit number, a negative number if the parent input/output statement is for an internal file, or a processor-dependent number (which might be negative) for the ‘*’ unit. The iostat argument must be assigned a value before returning from the defined input/output procedure: either zero to indicate success, the negative number IOSTAT_EOR (from the intrinsic module ISO_FORTRAN_ENV) to signal an end-of-record condition, the negative number IOSTAT_END to signal an end-of-file condition, or a positive number to indicate an error condition. The iomsg argument must be left alone if no error occurred, and must be assigned an explanatory message if iostat is set to a nonzero value.

For the formatted input/output procedures, the iotype argument will be set to ‘LISTDIRECTED’ if list-directed formatting is being done, ‘NAMELIST’ if namelist formatting is being done, and ‘DT’ concatenated with the character-literal if the DT edit descriptor is being processed. The vlist argument contains the list of values in the DT edit descriptor if present, and is otherwise a zero-sized array. Note that the syntax of the DT edit descriptor is:

DT [ character-literal ] [ ( value [ , value ]... ) ]

where blanks are insignificant, character-literal is a default character literal constant with no kind parameter, and each value is an optionally signed integer literal constant with no kind parameter. For example, ‘DT’, ‘DT"z8,i4,e10.2"’, ‘DT(100,-3,+4,666)’ and ‘DT"silly example"(0)’ are all syntactically correct DT edit descriptors: it is up to the user-defined procedure to interpret what they might mean.

During execution of a defined input/output procedure, there must be no input/output for an external unit (other than for the unit argument), but input/output for internal files is permitted. No file positioning commands are permitted. For unformatted input/output, all input/output occurs within the current record, no matter how many separate data transfer statements are executed by the procedure; that is, file positioning both before and after “nested” data transfer is suppressed. For formatted input/output, this effect is approximately equivalent to the nested data transfer statements being considered to be nonadvancing; explicit record termination (using the slash (/) edit descriptor, or transmission of newline characters to a stream file) is effective, and record termination may be performed by a nested list-directed or namelist input/output statement.

If unit is associated with an external file (i.e. non-negative, or equal to one of the constants ERROR_UNIT, INPUT_UNIT or OUTPUT_UNIT from the intrinsic module ISO_FORTRAN_ENV), the current settings for the pad mode, sign mode, etc., can be discovered by using INQUIRE with PAD=, SIGN=, etc. on the unit argument. If unit is negative (associated with an internal file), INQUIRE will raise the error condition IOSTAT_INQUIRE_INTERNAL_UNIT.

Finally, defined input/output is not compatible with asynchronous input/output; all input/output statements involved with defined input/output must be synchronous.


NAG Fortran Compiler, Release 7.1: Miscellaneous Fortran 2003 Features

 Navigation: Previous Up Next

9.8 Miscellaneous Fortran 2003 Features

9.8.1 Abstract interfaces and the PROCEDURE statement [5.1]

Abstract interfaces have been added, together with the procedure declaration statement. An abstract interface is defined in an interface block that has the ABSTRACT keyword, i.e.
  ABSTRACT INTERFACE
Each interface body in an abstract interface block defines an abstract interface instead of declaring a procedure. The name of an abstract interface can be used in the procedure declaration statement to declare a specifc procedure with that interface, e.g.
  PROCEDURE(aname) :: spec1, spec2
declares SPEC1 and SPEC2 to be procedures with the interface (i.e. type, arguments, etc.) defined by the abstract interface ANAME.

The procedure declaration statement can also be used with the name of any procedure that has an explicit interface, e.g.

  PROCEDURE(x) y
declares Y to have the same interface as X. Also, procedures with implicit interfaces can be declared by using PROCEDURE with a type specification instead of a name, or by omitting the name altogether.

The following attributes can be declared at the same time on the procedure declaration statement: BIND(C...), INTENT(intent), OPTIONAL, POINTER, PRIVATE, PUBLIC, SAVE. For example,

  PROCEDURE(aname),PRIVATE :: spec3

Note that POINTER declares a procedure pointer (see next section), and that INTENT and SAVE are only allowed for procedure pointers not for ordinary procedures. The NAG Fortran Compiler also allows the PROTECTED attribute to be specified on the procedure declaration statement: this is an extension to the published Fortran 2003 standard.

9.8.2 Named procedure pointers [5.2]

A procedure pointer is a procedure with the POINTER attribute; it may be a named pointer or a structure component (the latter are described elsewhere). The usual way of declaring a procedure pointer is with the procedure declaration statement, by including the POINTER clause in that statement: for example,
  PROCEDURE(aname),POINTER :: p => NULL()
declares P to be a procedure pointer with the interface ANAME, and initialises it to be a disassociated pointer.

A named procedure pointer may also be declared by specifying the POINTER attribute in addition to its normal procedure declaration: for example, a function declared by a type declaration statement will be a function pointer if the POINTER attribute is included in the type declaration:

  REAL, EXTERNAL, POINTER :: funptr
The POINTER statement can also be used to declare a procedure pointer, either in conjunction with an interface block, an EXTERNAL statement, or a type declaration statement, for example:
  INTERFACE
    SUBROUTINE sub(a,b)
      REAL,INTENT(INOUT) :: a,b
    END SUBROUTINE
  END INTERFACE
  POINTER sub

Procedure pointers may also be stored in derived types as procedure pointer components. The syntax and effects are slightly different, making them act like “object-bound procedures”, and as such are described in the object-oriented programming section.

9.8.3 Intrinsic modules [4.x]

The Fortran 2003 standard classifies modules as either intrinsic or non-intrinsic. A non-intrinsic module is the normal kind of module (i.e. user-defined); an intrinsic module is one that is provided as an intrinsic part of the Fortran compiler.

There are five standard modules in Fortran 2003: IEEE_ARITHMETIC, IEEE_EXCEPTIONS, IEEE_FEATURES, ISO_C_BINDING and ISO_FORTRAN_ENV.

A program is permitted to have a non-intrinsic module with the same name as that of an intrinsic module: to this end, the USE statement has been extended: ‘USE,INTRINSIC ::’ specifies that an intrinsic module is required, whereas ‘USE,NON_INTRINSIC ::’ specifies that a non-intrinsic module is required. If these are not used, the compiler will select an intrinsic module only if no user-defined module is found. For example,

  USE,INTRINSIC :: iso_fortran_env
uses the standard intrinsic module ISO_FORTRAN_ENV, whereas
  USE,NON_INTRINSIC :: iso_fortran_env
uses a user-defined module with that name. Note that the double-colon ‘::’ is required if either specifier is used.

9.8.4 Renaming user-defined operators on the USE statement [5.2]

It is now possible to rename a user-defined operator on the USE statement, similarly to how named entities can be renamed. For example,
  USE my_module, OPERATOR(.localid.)=>OPERATOR(.remotename.)
would import everything from MY_MODULE, but the .REMOTENAME. operator would have its name changed to .LOCALID..

Note that this is only available for user-defined operator names; the intrinsic operators .AND. et al cannot have their names changed in this way, nor can ASSIGNMENT(=) be renamed. The local name must be an operator if and only if the remote (module entity) name is an operator: that is, both of

  USE my_module, something=>OPERATOR(.anything.)
  USE my_module, OPERATOR(.something.)=>anything
are invalid (a syntax error will be produced).

9.8.5 The ISO_FORTRAN_ENV module [5.1]

The standard intrinsic module ISO_FORTRAN_ENV is now available. It contains the following default INTEGER named constants.
CHARACTER_STORAGE_SIZE
size of a character storage unit in bits.
ERROR_UNIT
logical unit number for error reporting (“stderr”).
FILE_STORAGE_SIZE
size of the file storage unit used by RECL= in bits.
INPUT_UNIT
default (‘*’) unit number for READ.
IOSTAT_END
IOSTAT= return value for end-of-file.
IOSTAT_EOR
IOSTAT= return value for end-of-record.
NUMERIC_STORAGE_SIZE
size of a numeric storage unit in bits.
OUTPUT_UNIT
unit used by PRINT, the same as the ‘*’ unit for WRITE.

9.8.6 The IMPORT statement [5.1]

The IMPORT statement has been added. This has the syntax

IMPORT [ [ :: ] name [ , name ]... ]

and is only allowed in an interface body, where it imports the named entities from the host scoping unit (normally, these entities cannot be accessed from an interface body). If no names are specified, normal host association rules are in effect for this interface body.

The IMPORT statement must follow any USE statements and precede all other declarations, in particular, IMPLICIT and PARAMETER statements. Anything imported with IMPORT must have been declared prior to the interface body.

9.8.7 Length of names and statements

Names are now ([4.x]) permitted to be 63 characters long (instead of 31), and statements are now ([5.2]) permitted to have 255 continuation lines (instead of 39).

9.8.8 Array constructor syntax enhancements

Square brackets ([ ]) can now ([5.1]) be used in place of the parenthesis-slash pairs ((/ /)) for array constructors. This allows expressions to be more readable when array constructors are being mixed with ordinary parentheses.
    RESHAPE((/(i/2.0,i=1,100)/),(/2,3/))  ! Old way
    RESHAPE([(i/2.0,i=1,100)],[2,3])      ! New way

Array constructors may now ([5.2]) begin with a type specification followed by a double colon (::); this makes zero-sized constructors easy (and eliminates potential ambiguity with character length), and also provides assignment conversions thus eliminating the need to pad all character strings to the same length.

   [ Logical :: ]                             ! Zero-sized logical array
   [ Double Precision :: 17.5, 0, 0.1d0 ]     ! Conversions
   [ Character(200) :: 'Alf', 'Bernadette' ]  ! Padded to length 200

9.8.9 Structure constructor syntax enhancements [5.3]

There are three enhancements that have been made to structure constructors in Fortran 2003:
  1. component names can be used as keywords, the same way that dummy argument names can be used as argument keywords;
  2. values can be omitted for components that have default initialisation; and
  3. type names can be the same as generic function names, and references are resolved by choosing a suitable function (if the syntax matches the function's argument list) and treating as a structure constructor only if no function matches the actual arguments.

A fourth enhancement is made in the Fortran 2008 standard: a value can be omitted for a component that is allocatable.

This makes structure constructors more like built-in generic functions that can be overridden when necessary. Here is an example showing all three enhancements.

  TYPE quaternion
    REAL x=0,ix=0,jx=0,kx=0
  END TYPE
  ...
  INTERFACE quaternion
    MODULE PROCEDURE quat_from_complex
  END INTERFACE
  ...
  TYPE(quaternion) FUNCTION quat_from_complex(c) RESULT(r)
    COMPLEX c
    r%x = REAL(c)
    r%y = AIMAG(c)
    r%z = 0
    r%a = 0
  END FUNCTION
  ...
  COMPLEX c
  TYPE(quaternion) q
  q = quaternion(3.14159265)  ! Structure constructor, value (~pi,0,0,0).
  q = quaternion(jx=1)        ! Structure constructor, value (0,0,1,0).
  q = quaternion(c)           ! "Constructor" function quat_from_complex.

Also, if the type is an extended type an ancestor component name can be used to provide a value for all those inherited components at once.

These extensions mean that even if a type has a private component, you can use the structure constructor if

  • the component is allocatable (it will be unallocated),
  • the component is default-initialised (it will have the default value), or
  • the component is inherited and you use an ancestor component name to provde a value for it and the other components inherited from that ancestor.

9.8.10 Deferred character length [5.2]

The length of a character pointer or allocatable variable can now be declared to be deferred, by specifying the length as a colon: for example,
  CHARACTER(LEN=:),POINTER :: ch
The length of a deferred-length pointer (or allocatable variable) is determined when it is allocated (see next section) or pointer-associated; for example
  CHARACTER,TARGET :: t1*3,t2*27
  CHARACTER(:),POINTER :: p
  p => t1
  PRINT *,LEN(p)
  p => t2
  PRINT *,LEN(p)
will first print 3 and then 27. It is not permitted to ask for the LEN of a disassociated pointer that has deferred length.

Note that deferred length is most useful in conjunction with the new features of typed allocation, sourced allocation, scalar allocatables and automatic reallocation.

9.8.11 The ERRMSG= specifier [5.1]

The ALLOCATE and DEALLOCATE statements now accept the ERRMSG= specifier. This specifier takes a scalar default character variable, which in the event of an allocation or deallocation error being detected will be assigned an explanatory message. If no error occurs the variable is left unchanged. Note that this is useless unless the STAT= specifier is also used, as otherwise the program will be terminated on error anyway.

For example,

  ALLOCATE(w(n),STAT=ierror,ERRMSG=message)
  IF (ierror/=0) THEN
    PRINT *,'Error allocating W: ',TRIM(message)
    RETURN
  END IF

9.8.12 Intrinsic functions in constant expressions [5.2 partial; 5.3 complete]

It is now allowed to use any intrinsic function with constant arguments in a constant expression. (In Fortran 95 real and complex intrinsic functions were not allowed.) For example,
MODULE m
  REAL,PARAMETER :: e = EXP(1.0)
END

9.8.13 Specification functions can be recursive [6.2]

A function that is used in a specification expression is now permitted to be recursive (defined with the RECURSIVE attribute). For example
       PURE INTEGER FUNCTION factorial(n) RESULT(r)
         INTEGER,INTENT(IN) :: n
         IF (n>1) THEN
           r = n*factorial(n-1)
         ELSE
           r = 1
         END IF
       END FUNCTION
can now be used in a specification expression. Note that a specification function must not invoke the procedure that invoked it.

9.8.14 Access to the command line [5.1]

The intrinsic procedures COMMAND_ARGUMENT_COUNT, GET_COMMAND and GET_COMMAND_ARGUMENT have been added. These duplicate functionality previously only available via the procedures IARGC and GETARG from the F90_UNIX_ENV module.

INTEGER FUNCTION command_argument_count()
Returns the number of command-line arguments. Unlike IARGC in the F90_UNIX_ENV module, this returns 0 even if the command name cannot be retrieved.

SUBROUTINE get_command(command,length,status)
  CHARACTER(*),INTENT(OUT),OPTIONAL :: command
  INTEGER,INTENT(OUT),OPTIONAL :: length,status
Accesses the command line which invoked the program. This is formed by concatenating the command name and the arguments separated by blanks. This might differ from the command the user actually typed, and should be avoided (use GET_COMMAND_ARGUMENT instead).

If COMMAND is present, it receives the command (blank-padded or truncated as appropriate). If LENGTH is present, it receives the length of the command. If STATUS is present, it is set to −1 if COMMAND is too short to hold the whole command, a positive number if the command cannot be retrieved, and zero otherwise.

SUBROUTINE get_command_argument(number,value,length,status)
  INTEGER,INTENT(IN) :: number
  CHARACTER(*),INTENT(OUT),OPTIONAL :: value
  INTEGER,INTENT(OUT),OPTIONAL :: length,status
Accesses command-line argument number NUMBER, where argument zero is the program name. If VALUE is present, it receives the argument text (blank-padded or truncated as appropriate if the length of the argument differs from that of VALUE). If LENGTH is present, it receives the length of the argument. If STATUS is present, it is set to zero for success, −1 if VALUE is too short, and a positive number if an error occurs.

Note that it is an error for NUMBER to be less than zero or greater than the number of arguments (returned by COMMAND_ARGUMENT_COUNT).

9.8.15 Access to environment variables [5.1]

The intrinsic procedure GET_ENVIRONMENT_VARIABLE has been added. This duplicates the functionality previously only available via the procedure GETENV in the F90_UNIX_ENV module.
  SUBROUTINE get_environment_variable(name,value,length,status,trim_name)
    CHARACTER(*),INTENT(IN) :: name
    CHARACTER(*),INTENT(OUT),OPTIONAL :: value
    INTEGER,INTENT(OUT),OPTIONAL :: length,status
    LOGICAL,INTENT(IN),OPTIONAL :: trim_name
  END
Accesses the environment variable named by NAME; trailing blanks in NAME are ignored unless TRIM_NAME is present with the value .FALSE.. If VALUE is present, it receives the text value of the variable (blank-padded or truncated as appropriate if the length of the value differs from that of VALUE). If LENGTH is present, it receives the length of the value. If STATUS is present, it is assigned the value 1 if the environment variable does not exist, −1 if VALUE is too short, and zero for success. Other positive values might be assigned for unusual error conditions.

9.8.16 Character kind selection [5.1]

The intrinsic function SELECTED_CHAR_KIND has been added. At this time the only character set supported is 'ASCII'.

9.8.17 Argument passing relaxation [5.1]

A CHARACTER scalar actual argument may now be passed to a routine which expects to receive a CHARACTER array, provided the array is explicit-shape or assumed-size (i.e. not assumed-shape, allocatable, or pointer). This is useful for C interoperability.

9.8.18 The MAXLOC and MINLOC intrinsic functions [5.1]

The MAXLOC and MINLOC intrinsic functions now return zeroes for empty set locations, as required by Fortran 2003 (Fortran 95 left this result processor-dependent).

9.8.19 The VALUE attribute [4.x]

The VALUE attribute specifies that an argument should be passed by value.

9.8.19.1 Syntax

The VALUE attribute may be specified by the VALUE statement or with the VALUE keyword in a type declaration statement.

The syntax of the VALUE statement is:

VALUE [ :: ] name [ , name ] ...

The VALUE attribute may only be specified for a scalar dummy argument; if the dummy argument is of type CHARACTER, its character length must be constant and equal to one.

Procedures with a VALUE dummy argument must have an explicit interface.

9.8.19.2 Semantics

A dummy argument with the VALUE attribute is “passed by value”; this means that a local copy is made of the argument on entry to the routine and so modifications to the dummy argument do not affect the associated actual argument and vice versa.

A VALUE dummy argument may be INTENT(IN) but cannot be INTENT(INOUT) or INTENT(OUT).

9.8.19.3 Example

PROGRAM value_example
  INTEGER :: i = 3
  CALL s(i)
  PRINT *,i  ! This will print the value 3
CONTAINS
  SUBROUTINE s(j)
    INTEGER,VALUE :: j
    j = j + 1  ! This changes the local J without affecting the actual argument
    PRINT *,j  ! This will print the value 4
  END SUBROUTINE
END
This example is not intended to be particularly useful, just to illustrate the functionality.

9.8.20 The VOLATILE attribute [5.0]

This is a horrible attribute which specifies that a variable can be modified by means outside of Fortran. Its semantics are basically the same as that of the C ‘volatile’ type qualifier; essentially it disables optimisation for access to that variable.

9.8.21 Enhanced complex constants [5.2]

The real or imaginary part may now be a named constant, it is not limited to being a literal constant. For example:
  REAL,PARAMETER :: minusone = -1.0
  COMPLEX,PARAMETER :: c = (0,minusone)
This is not particularly useful, since the same effect can be achieved by using the CMPLX intrinsic function.

9.8.22 The ASSOCIATE construct [5.2]

The ASSOCIATE construct establishes a temporary association between the “associate names” and the specified variables or values, during execution of a block. Its syntax is

ASSOCIATE ( association [ , association ]... )
block
END ASSOCIATE

where block is a sequence of executable statements and constructs, and association is one of

name => expression
name => variable
name

The last of those is short for ‘name => name’. The scope of each “associate name” is the block of the ASSOCIATE construct. An associate name is never allocatable or a pointer, but otherwise has the same attributes as the variable or expression (and it has the TARGET attribute if the variable or expression is a pointer). If it is being associated with an expression, the expression is evaluated on execution of the ASSOCIATE statement and its value does not change during execution of the block — in this case, the associate name is not permitted to appear on the left-hand-side of an assignment or any other context which might change its value. If it is being associated with a variable, the associate name can be treated as a variable.

The type of the associate name is that of the expression or variable with which it is associated. For example, in

ASSOCIATE(zoom=>NINT(SQRT(a+b)), alt=>state%mapval(:,i)%altitude)
  alt%x = alt%x*zoom
  alt%y = alt%y*zoom
END ASSOCIATE
ALT is associated with a variable and therefore can be modified whereas ZOOM cannot. The expression for ZOOM is of type INTEGER and therefore ZOOM is also of type INTEGER.

9.8.23 Binary, octal and hexadecimal constants [5.2]

In Fortran 95 these were restricted to DATA statements, but in Fortran 2003 these are now allowed to be arguments of the intrinsic functions CMPLX, DBLE, INT and REAL. The interpretation is processor-dependent, but the intent is that this specifies the internal representation of the complex or real value. The NAG Fortran compiler requires these constants to have the correct length for the specified kind of complex or real, viz 32 or 64 bits as appropriate.

For example, on a machine where default REAL is IEEE single precision,

  REAL(z"41280000")
has the value 10.5.

9.8.24 Character sets [5.1; 5.3]

The support for multiple character sets, especially for Unicode (ISO 10646) has been improved.

The default character set is now required to include lowercase letters and all the 7-bit ASCII printable characters.

The ENCODING= specifer for the OPEN and INQUIRE statements is described in the input/output section.

A new intrinsic function SELECTED_CHAR_KIND(NAME) has been added: this returns the character kind for the named character set, or −1 if there is no kind for that character set. Standard character set names are 'DEFAULT' for the default character kind, 'ASCII' for the 7-bit ASCII character set and 'ISO_10646' for the UCS-4 (32-bit Unicode) character set. The name is not case-sensitive. Note that although the method of requesting UCS-4 characters is standardised, the compiler is not required to support them (in which case −1 will be returned); the NAG Fortran Compiler supports UCS-4 in release 5.3 (as well as UCS-2 and JIS X 0213).

Assignment of a character value of one kind to a character value of a different kind is permitted if each kind is one of default character, ASCII character, or UCS-4 character. Assignment to and from a UCS-4 character variable preserves the original value.

Internal file input/output to variables of UCS-4 character kind is allowed (if the kind exists), including numeric conversions (e.g. the E edit descriptor), and conversions from/to default character and ASCII character. Similarly, writing default character, ASCII character and UCS-4 character values to a UTF-8 file and reading them back is permitted and preserves the value.

Finally, the intrinsic function IACHAR (for converting characters to the ASCII character set) accepts characters of any kind (in Fortran 95 it only accepted default kind).

9.8.25 Intrinsic function changes for 64-bit machines [5.2]

Especially to support machines with greater than 32-bit address spaces, but with 32-bit default integers, several intrinsic functions now all have an optional KIND argument at the end of the argument list, to specify the kind of integer they return. The functions are: COUNT, INDEX, LBOUND, LEN, LEN_TRIM, SCAN, SHAPE, SIZE, UBOUND and VERIFY.

9.8.26 Miscellaneous intrinsic procedure changes [5.2]

The intrinsic subroutine DATE_AND_TIME no longer requires the three character arguments (DATE, TIME and ZONE) to have a minimum length: if the actual argument is too small, it merely truncates the value assigned.

The intrinsic functions IACHAR and ICHAR now accept an optional KIND argument to specify the kind of integer to which to convert the character value. This serves no useful purpose since there are no character sets with characters bigger than 32 bits.

The intrinsic functions MAX, MAXLOC, MAXVAL, MIN, MINLOC and MINVAL all now accept character values; the comparison used is the native (.LT.) one, not the ASCII (LLT) one.

The intrinsic subroutine SYSTEM_CLOCK now accepts a COUNT_RATE argument of type real; this is to handle systems whose clock ticks are not an integral divisor of 1 second.


NAG Fortran Compiler, Release 7.1: Fortran 2008 Extensions

 Navigation: Previous Up Next

10 Fortran 2008 Extensions

  • 10.1 Fortran 2008 Overview
  • 10.2 SPMD programming with coarrays [6.2, 7.0]
    • 10.2.1 Overview
    • 10.2.2 Images
    • 10.2.3 Coarrays
    • 10.2.4 Declaring coarrays
    • 10.2.5 Accessing coarrays on other images
    • 10.2.6 Segments and synchronisation
    • 10.2.7 Allocating and deallocating coarrays
    • 10.2.8 Critical constructs
    • 10.2.9 Lock variables
    • 10.2.10 Atomic coarray accessing
    • 10.2.11 Normal termination of execution
    • 10.2.12 Error termination
    • 10.2.13 Fault tolerance
    • 10.2.14 Detailed syntax of coarray features
    • 10.2.15 Intrinsic procedures and coarrays
  • 10.3 Data declaration [mostly 6.0]
  • 10.4 Data usage and computation [mostly 5.3]
  • 10.5 Execution control [mostly 6.0]
  • 10.6 Intrinsic procedures and modules
    • 10.6.1 Additional mathematical intrinsic functions [mostly 5.3.1]
    • 10.6.2 Additional intrinsic functions for bit manipulation [mostly 5.3]
    • 10.6.3 Other new intrinsic procedures [mostly 5.3.1]
    • 10.6.4 Changes to existing intrinsic procedures [mostly 5.3.1]
    • 10.6.5 ISO_C_BINDING additions [6.2]
    • 10.6.6 ISO_FORTRAN_ENV additions
  • 10.7 Input/output extensions [mostly 5.3]
  • 10.8 Programs and procedures [mostly 5.3]


NAG Fortran Compiler, Release 7.1: Fortran 2008 Overview

 Navigation: Previous Up Next

10.1 Fortran 2008 Overview

This part of the manual describes those parts of the Fortran 2008 language which are not in Fortran 2003, and which are currently supported by the NAG Fortran Compiler.

Fortran 2008 is a major revision to Fortran 2003: the new language features can be grouped as follows:

  • SPMD programming with coarrays;
  • data declaration;
  • data usage and computation;
  • execution control;
  • intrinsic procedures and modules;
  • input/output extensions;
  • programs and procedures.


NAG Fortran Compiler, Release 7.1: SPMD programming with coarrays [6.2, 7.0]

 Navigation: Previous Up Next

10.2 SPMD programming with coarrays [6.2, 7.0]

10.2.1 Overview

Fortran 2008 contains an SPMD (Single Program Multiple Data) programming model, where multiple copies of a program, called “images”, are executed in parallel. Special variables called “coarrays” facilitate communication between images.

Release 6.2 of the NAG Fortran Compiler limited execution to a single image, with no parallel execution. Release 7.0 of the NAG Fortran Compiler can execute multiple images in parallel on SMP machines, using Co-SMP technology.

10.2.2 Images

Each image contains its own variables and input/output units. The number of images at execution time is not determined by the program, but by some compiler-specific method. The number of images is fixed during execution; images cannot be created or destroyed. The intrinsic function NUM_IMAGES() returns the number of images. Each image has an “image index”; this is a positive integer from 1 to the number of images. The intrinsic function THIS_IMAGE() returns the image index of the executing image.

10.2.3 Coarrays

Coarrays are variables that can be directly accessed by another image; they must have the ALLOCATABLE or SAVE attribute or be a dummy argument.

A coarray has a “corank”, which is the number of “codimensions” it has. Each codimension has a lower “cobound” and an upper cobound, determining the “coshape”. The upper cobound of the last codimension is “*”; rather like an assumed-size array. The “cosubscripts” determine the image index of the reference, in the same way that the subscripts of an array determine the array element number. Again, like an assumed-size array, the image index must be less than or equal to the number of images.

A coarray can be a scalar or an array. It cannot have the POINTER attribute, but it can have pointer components.

As well as variables, coarray components are possible. In this case, the component must be an ALLOCATABLE coarray, and any variable with such a component must be a dummy argument or have the SAVE attribute.

10.2.4 Declaring coarrays

A coarray has a coarray-spec which is declared with square brackets after the variable name, or with the CODIMENSION attribute or statement. For example,
    REAL a[100,*]
    REAL,CODIMENSION[-10:10,-10:*] :: b
    CODIMENSION c[*]
declares the coarray A to have corank 2 with lower “cobounds” both 1 and the first upper cobound 100, the coarray B to have corank 2 with lower cobounds both −10 and the first upper cobound 10, and the coarray C to have corank 1 and lower cobound 1. Note that for non-allocatable coarrays, the coarray-spec must always declare the last upper cobound with an asterisk, as this will vary depending on the number of images.

An ALLOCATABLE coarray is declared with a deferred-coshape-spec, for example,

    REAL,ALLOCATABLE :: d[:,:,:,:]
declares the coarray D to have corank 4.

10.2.5 Accessing coarrays on other images

To access another image's copy of a coarray, cosubscripts are used following the coarray name in square brackets; this is called “coindexing”, and such an object is a “coindexed object”. For example, given
    REAL,SAVE :: e[*]
the coindexed object e[1] refers to the copy of E on image 1, and e[13] refers to the copy of E on image 13. For a more complicated example: given
    REAL,SAVE :: f[10,21:30,0:*]
the reference f[3,22,1] refers to the copy of F on image 113. There is no correlation between image numbers and any topology of the computer, so it is probably best to avoid complicated codimensions, especially if different coarrays have different coshape.

When a coarray is an array, you cannot put the cosubscripts directly after the array name, but must use array section notation instead. For example, with

    REAL,SAVE :: g(10,10)[*]
the reference g[inum] is invalid, to refer to the whole array G on image INUM you need to use g(:,:)[inum] instead.

Similarly, to access a single element of G, the cosubscripts follow the subscripts, e.g. g(i,j)[inum].

Finally, note that when a coarray is accessed, whether by its own image or remotely, the segment ordering rules (see next section) must be obeyed. This is to avoid nonsense answers from data races.

10.2.6 Segments and synchronisation

Execution on each image is divided into segments, by “image control statements”. The segments on a single image are ordered: each segment follows the preceding segment. Segments on different images may be ordered (one following the other) by synchronisation, otherwise they are unordered.

If a coarray is defined (assigned a value) in a segment on image I, another image J is only allowed to reference or define it in a segment that follows the segment on I.

The image control statements, and their synchronisation effects, are as follows.

SYNC ALL
synchronises with corresponding SYNC ALL statement executions on other images; the segment following the nth execution of a SYNC ALL statement on one image follows all the segments that preceded the nth execution of a SYNC ALL statement on every other image.
SYNC IMAGES (list)
synchronises with corresponding SYNC IMAGES statement executions on the images in list, which is an integer expression that may be scalar or a vector. Including the invoking image number in list has no effect. The segment following the nth execution of a SYNC IMAGES statement on image I with the image number J in its list follows the segments on image J before its nth execution of SYNC IMAGES with I in its list.
SYNC IMAGES (*)
is equivalent to SYNC IMAGES with every image no. in its list, e.g. SYNC IMAGES ([(i,i=1,NUM_IMAGES())]).
SYNC MEMORY
This only acts as a segment divider, without synchronising with any other image. It may be useful for user-defined orderings when some other mechanism has been used to synchronise.
ALLOCATE or DEALLOCATE
with a coarray object being allocated or deallocated. This synchronises all images, which must execute the same ALLOCATE or DEALLOCATE statement.
CRITICAL and END CRITICAL
Only one image can execute a CRITICAL construct at a time. The code inside a CRITICAL construct forms a segment, which follows the previous execution (on whatever image) of the CRITICAL construct.
LOCK and UNLOCK
The segment following a LOCK statements that locks a particular lock variable follows the UNLOCK statement that previously unlocked the variable.
END statement
An END BLOCK, END FUNCTION, or END SUBROUTINE statement that causes automatic deallocation of a local ALLOCATABLE coarray, synchronises with all images (which must execute the same END statement).
MOVE_ALLOC intrinsic
Execution of the intrinsic subroutine MOVE_ALLOC with coarray arguments synchronises all images, which must execute the same CALL statement.

Note that image control statements have side-effects, and therefore are not permitted in pure procedures or within DO CONCURRENT constructs.

10.2.7 Allocating and deallocating coarrays

When you allocate an ALLOCATABLE coarray, you must give the desired cobounds in the ALLOCATE statement. For example,
    REAL,ALLOCATABLE :: x(:,:,:)[:,:]
    ...
    ALLOCATE(x(100,100,3)[1:10,*])
Note that the last upper cobound must be an asterisk, the same as when declaring an explicit-coshape coarray.

When allocating a coarray there is a synchronisation: all images must execute the same ALLOCATE statement, and all the bounds, type parameters, and cobounds of the coarray must be the same on all images.

Similarly, there is a synchronisation when a coarray is deallocated, whether by a DEALLOCATE statement or automatic deallocation by an END statement; every image must execute the same statement.

Note that the usual automatic reallocation of allocatable variables in an intrinsic assignment statement, e.g. when the expression is an array of a different shape, is not available for coarrays. An allocatable coarray variable being assigned to must already be allocated and be conformable with the expression; furthermore, if it has deferred type parameters they must have the same values, and if it is polymorphic it must have the same dynamic type.

10.2.8 Critical constructs

The CRITICAL construct provides a mechanism for ensuring that only one image at a time executes a code segment. For example,
    CRITICAL
      ...do something
    END CRITICAL
If an image I arrives at the CRITICAL statement while another image J is executing the block of the construct, it will wait until image J has executed the END CRITICAL statement before continuing. Thus the CRITICAL — END CRITICAL segment on image I follows the equivalent segment on image J.

As a construct, this may have a name, e.g.

    critsec: CRITICAL
      ...
    END CRITICAL critsec
The name has no effect on the operation of the construct. Each CRITICAL construct is separate from all others, and has no effect on their execution.

10.2.9 Lock variables

A “lock variable” is a variable of the type LOCK_TYPE, defined in the intrinsic module ISO_FORTRAN_ENV. A lock variable must be a coarray, or a component of a coarray. It is initially “unlocked”; it is locked by execution of a LOCK statement, and unlocked by execution of an UNLOCK statement. Apart from those statements, it cannot appear in any variable definition context, other than as the actual argument for an INTENT(INOUT) dummy argument.

Execution of the segment after a LOCK statement successfully locks the variable follows execution of the segment before the UNLOCK statement on the image that unlocked it. For example,

    INTEGER FUNCTION get_sequence_number()
      USE iso_fortran_env
      INTEGER :: number = 0
      TYPE(lock_type) lock[*]
      LOCK(lock[1])
      number = number + 1
      get_sequence_number = number
      UNLOCK(lock[1])
    END FUNCTION
If the variable lock on image 1 is locked when the LOCK statement is executed, it will wait for it to become unlocked before continuing. Thus the function get_sequence_number() provides an one-sided ordering relation: the segment following a call that returned the value N will follow every segment that preceded a call that returned a value less than N.

Conditional locking is provided with the ACQUIRED_LOCK= specifier; if this specifier is present, the executing image only acquires the lock if it was previously unlocked. For example,

    LOGICAL gotit
    LOCK(lock[1],ACQUIRED_LOCK=gotit)
    IF (gotit) THEN
      ! We have the lock.
    ELSE
      ! We do not have the lock - some other image does.
    END IF

It is an error for an image to try to LOCK a variable that is already locked to that image, or to UNLOCK a variable that is already unlocked, or that is locked to another image. If the STAT= specifier is used, these errors will return the values STAT_LOCKED, STAT_UNLOCKED, or STAT_LOCKED_OTHER_IMAGE respectively (these named constants are provided by the intrinsic module ISO_FORTRAN_ENV).

10.2.10 Atomic coarray accessing

As an exception to the segment ordering rules, a coarray that is an integer of kind ATOMIC_INT_KIND or a logical of kind ATOMIC_LOGICAL_KIND (these named constants are provided by the intrinsic module ISO_FORTRAN_ENV), can be defined with the intrinsic subroutine ATOMIC_DEFINE, or referenced by the intrinsic subroutine ATOMIC_REF. For example,
    MODULE stopping
      USE iso_fortran_env
      LOGICAL(atomic_logical_kind),PRIVATE :: stop_flag[*] = .FALSE.
    CONTAINS
      SUBROUTINE make_it_stop
        CALL atomic_define(stop_flag[1],.TRUE._atomic_logical_kind)
      END SUBROUTINE
      LOGICAL FUNCTION please_stop()
        CALL atomic_ref(please_stop,stop_flag[1])
      END FUNCTION
    END MODULE
In this example, it is perfectly valid for any image to call make_it_stop, and for any other image to invoke the function please_stop(), without any regard for segments. (On a distributed memory machine it might take some time for changes to the atomic variable to be visible on other images, but they should eventually get the message.)

Note that ordinary assignment and referencing should not be mixed with calls to the atomic subroutines, as ordinary assignment and referencing are always subject to the segment ordering rules.

10.2.11 Normal termination of execution

If an image executes a STOP statement, or the END PROGRAM statement, normal termination is initiated. The other images continue execution, and all data on the “stopped” image remains; other images can continue to reference and define coarrays on the stopped image.

When normal termination has been initiated on all images, the program terminates.

10.2.12 Error termination

If any image terminates due to an error, for example an input/output error in an input/output statement that does not have any IOSTAT= or ERR= specifier, the entire program is error terminated. On a distributed memory machine it may take some time for the error termination messages to reach every image, so the termination might not be immediate.

The ERROR STOP statement initiates error termination.

10.2.13 Fault tolerance

The Fortran 2018 standard adds many features for detecting, simulating, and recovering from image failure. For example, the FAIL IMAGE statement causes the executing image to fail (stop responding to accesses from other images). These extensions are listed in the detailed syntax below, even though they are not part of the Fortran 2008 standard.

The FAIL IMAGE statement itself is not very useful when the number of images is equal to one, as it inevitably causes complete program failure.

10.2.14 Detailed syntax of coarray features

Coindexed object (data object designator):

In a data object designator, a part (component or base object) that is a coarray can include an image selector: part-name [ ( section-subscript-list ) ] [ image-selector ]

where part-name identifies a coarray, and image-selector is

left-bracket cosubscript-list [, image-selector-spec ] right-bracket

The number of cosubscripts must be equal to the corank of part-name. If image-selector appears and part-name is an array, section-subscript-list must also appear. The optional image-selector-spec is Fortran 2018 (part of the fault tolerance feature), and is a comma-separated list of one or more of the following specifiers:

STAT = scalar-int-variable
TEAM = team-value
TEAM_NUMBER = scalar-int-expression

A team-value must be a scalar expression of type TEAM_TYPE from the intrinsic module ISO_FORTRAN_ENV. The STAT= variable is assigned zero if the reference or definition was successful, and the value STAT_FAILED if the image referenced has failed.

CRITICAL construct:

[ construct-name : ] CRITICAL [ ( [ sync-stat-list ] ) ]
block
END CRITICAL [ construct-name ]

where the optional sync-stat-list is a STAT= specifier, an ERRMSG= specifier, or both (separated by a comma). Note: The optional parentheses and sync-stat-list are Fortran 2018.

The block is not permitted to contain:

  • a RETURN or STOP statement;
  • an image control statement;
  • a branch whose target is outside the construct.

FAIL IMAGE statement:

FAIL IMAGE

Note: This statement is Fortran 2018.

LOCK statement:

LOCK ( lock-variable [, lock-stat-list ] )

where lock-stat-list is a comma-separated list of one or more of the following:

ACQUIRED_LOCK = scalar-logical-variable
ERRMSG = scalar-default-character-variable
STAT = scalar-int-variable

and lock-variable is a scalar variable of type LOCK_TYPE from the intrinsic module ISO_FORTRAN_ENV.

SYNC ALL statement:

SYNC ALL [ ( [ sync-stat-list ] ) ]

SYNC IMAGES statement:

SYNC IMAGES ( image-set [, sync-stat-list ] )

where image-set is an asterisk, or an integer expression that is scalar or of rank one.

SYNC MEMORY statement:

SYNC MEMORY [ ( [ sync-stat-list ] ) ]

UNLOCK statement:

UNLOCK ( lock-variable [, sync-stat-list ] )

Note:

  • The variables in sync-stat-list or lock-stat-list are not permitted to be coindexed objects, nor may they depend on anything else in the statement.

10.2.15 Intrinsic procedures and coarrays

    SUBROUTINE ATOMIC_DEFINE(ATOM, VALUE, STAT)
ATOM
is INTENT(OUT) scalar INTEGER(ATOMIC_INT_KIND) or LOGICAL(ATOMIC_LOGICAL_KIND), and must be a coarray or a coindexed object.
VALUE
is scalar with the same type as ATOM.
STAT
(Optional) is scalar Integer and must have a decimal exponent range of at least four. It must not be coindexed.
The variable ATOM is atomically assigned the value of VALUE, without regard to the segment rules. If STAT is present, it is assigned a positive value if an error occurs, and zero otherwise. Note: STAT is part of Fortran 2018.

    SUBROUTINE ATOMIC_REF(VALUE, ATOM, STAT)
VALUE
is INTENT(OUT) scalar with the same type as ATOM.
ATOM
is scalar INTEGER(ATOMIC_INT_KIND) or LOGICAL(ATOMIC_LOGICAL_KIND), and must be a coarray or a coindexed object.
STAT
(Optional) is scalar Integer and must have a decimal exponent range of at least four. It must not be coindexed.
The value of ATOM is atomically read, without regard to the segment rules, and then assigned to the variable VALUE. If STAT is present, it is assigned a positive value if an error occurs, and zero otherwise. Note: STAT is part of Fortran 2018.

    INTEGER FUNCTION IMAGE_INDEX(COARRAY, SUB)
COARRAY
a coarray of any type.
SUB
an integer vector whose size is equal to the corank of COARRAY.
If the value of SUB is a valid set of cosubscripts for COARRAY, the value of the result is the image index of the image they will reference, otherwise the result has the value zero. For example, if X is declared with cobounds [11:20,13:*], the result of IMAGE_INDEX(X,[11,13]) will be equal to one, and the result of IMAGE_INDEX(x,[1,1]) will be equal to zero.

    FUNCTION LCOBOUND(COARRAY, DIM , KIND)
COARRAY
coarray of any type and corank N;
DIM
(Optional) scalar Integer in the range 1 to N;
KIND
(Optional) scalar Integer constant expression;
Result
Integer or Integer(Kind=KIND).
If DIM appears, the result is scalar, being the value of the lower cobound of that codimension of COARRAY. If DIM does not appear, the result is a vector of length N containing all the lower cobounds of COARRAY. The actual argument for DIM must not itself be an optional dummy argument.

    SUBROUTINE MOVE_ALLOC(FROM, TO, STAT, ERRMSG)  ! Revised
FROM
an allocatable variable of any type.
TO
an allocatable with the same declared type, type parameters, rank and corank, as FROM.
STAT
INTENT(OUT) scalar Integer with a decimal exponent range of at least four.
ERRMSG
INTENT(INOUT) scalar default character variable.
If FROM and TO are coarrays, the CALL statement is an image control statement that synchronises all images. If STAT is present, it is assigned a positive value if any error occurs, otherwise it is assigned the value zero. If ERRMSG is present and an error occurs, it is assigned an explanatory message. Note: The STAT and ERRMSG arguments are Fortran 2018.

    INTEGER FUNCTION NUM_IMAGES()
This intrinsic function returns the number of images. In this release of the NAG Fortran Compiler, the value will always be equal to one.

    INTEGER FUNCTION THIS_IMAGE()
Returns the image index of the executing image.

    FUNCTION THIS_IMAGE(COARRAY)
Returns an array of type Integer with default kind, with the size equal to the corank of COARRAY, which may be a coarray of any type. The values returned are the cosubscripts for COARRAY that correspond to the executing image.

    INTEGER FUNCTION THIS_IMAGE(COARRAY, DIM)
COARRAY
is a coarray of any type.
DIM
is scalar Integer.
Returns the cosubscript for the codimension DIM that corresponds to the executing image. Note: In Fortran 2008 DIM was not permitted to be an optional dummy argument; Fortran 2018 permits that.

    FUNCTION UCOBOUND(COARRAY, DIM, KIND)
COARRAY
coarray of any type and corank N;
DIM
(Optional) scalar Integer in the range 1 to N;
KIND
(Optional) scalar Integer constant expression;
Result
Integer or Integer(Kind=KIND).

If DIM appears, the result is scalar, being the value of the upper cobound of that codimension of COARRAY. If DIM does not appear, the result is a vector of length N containing all the upper cobounds of COARRAY. The actual argument for DIM must not itself be an optional dummy argument.

Note that if COARRAY has corank N>1, and the number of images in the current execution is not an integer multiple of the coextents up to codimension N−1, the images do not make a full rectangular pattern. In this case, the value of the last upper cobound is the maximum value that a cosubscript can take for that codimension; e.g. with a coarray-spec of [1:3,1:*] and four images in the execution, the last upper cobound will be equal to 2 because the cosubscripts [1,2] are valid even though [2,2] and [2,3] are not.


NAG Fortran Compiler, Release 7.1: Data declaration [mostly 6.0]

 Navigation: Previous Up Next

10.3 Data declaration [mostly 6.0]

  • The maximum rank of an array has been increased from 7 to 15. For example,
       REAL array(2,2,2,2,2,2,2,2,2,2,2,2,2,2,2)
    declares a 15-dimensional array.
  • [3.0] 64-bit integer support is required, that is, the result of SELECTED_INT_KIND(18) is a valid integer kind number.
  • A named constant (PARAMETER) that is an array can assume its shape from its defining expression; this is called an implied-shape array. The syntax is that the upper bound of every dimension must be an asterisk, for example
       REAL,PARAMETER :: idmat3(*,*) = Reshape( [ 1,0,0,0,1,0,0,0,1 ], [ 3,3 ] )
   REAL,PARAMETER :: yeardata(2000:*) = [ 1,2,3,4,5,6,7,8,9 ]
    declares idmat3 to have the bounds (1:3,1:3), and yeardata to have the bounds (2000:2008).
  • The TYPE keyword can be used to declare entities of intrinsic type, simply by putting the intrinsic type-spec within the parentheses. For example,
       TYPE(REAL) x
   TYPE(COMPLEX(KIND(0d0))) y
   TYPE(CHARACTER(LEN=80)) z
    is completely equivalent, apart from being more confusing, to
       REAL x
   COMPLEX(KIND(0d0)) y
   CHARACTER(LEN=80) z
  • As a consequence of the preceding extension, it is no longer permitted to define a derived type that has the name DOUBLEPRECISION.
  • [5.3] A type-bound procedure declaration statement may now declare multiple type-bound procedures. For example, instead of
          PROCEDURE,NOPASS :: a
      PROCEDURE,NOPASS :: b=>x
      PROCEDURE,NOPASS :: c
    the single statement
          PROCEDURE,NOPASS :: a, b=>x, c
    will suffice.
  • [5.3 for C_ASSOCIATED, 7.0 for C_LOC and C_FUNLOC] A specification expression may now use the C_ASSOCIATED, C_LOC and C_FUNLOC functions from the ISO_C_BINDING module. For example, given a TYPE(C_PTR) variable X and another interoperable variable Y with the TARGET attribute,
           INTEGER workspace(MERGE(10,20,C_ASSOCIATED(X,C_LOC(Y))))
    is allowed, and will give workspace a size of 10 elements if the C pointer X is associated with Y, and 20 elements otherwise.
  • [7.0] A specification expression may now use a user-defined operation, provided that operation is provided by a specification function. (A specification function must be a pure function that is not a statement function or internal function, and that does not have a dummy procedure argument.) For example, given the interface block
           INTERFACE OPERATOR(.user.)
          PURE INTEGER FUNCTION userfun(x)
             REAL,INTENT(IN) :: x
          END FUNCTION
       END INTERFACE
    the user-defined operator .user. may be used in a specification expression as follows:
           LOGICAL mask(.user.(3.145))

    Note that this applies to overloaded intrinsic operators as well as user-defined operators.

  • [7.1] An allocatable component can forward-reference a type, for example:
           Type t2
         Type(t),Pointer :: p
         Type(t),Allocatable :: a
       End Type
       Type t
         Integer c
       End Type

    An allocatable component can also be of recursive type, or two types can be mutually recursive. For example,

           Type t
         Integer v
         Type(t),Allocatable :: a
       End Type
    This allows lists and trees to be built using allocatable components. Building or traversing such data structures will usually require recursive procedure calls, as there is no allocatable analogue of pointer assignment.

    No matter how deeply nested such recursive data structures become, they can never be circular (again, because there is no pointer assignment). As usual, deallocating the top object of such a structure will recursively deallocate all its allocatable components.

  • [7.1] A dummy argument can be used in a specification expression in an elemental subprogram, as long as it is not used to specify a type parameter (such as character length) of a function result. For type parameters of function results, they remain limited to appearing in specification enquiries (such as LEN) when the enquiry is not about a deferred characteristic.

    For example, in

      Elemental Subroutine s(x,n,y)
    Real,Intent(In) :: x
    Integer,Intent(In) :: n
    Real,Intent(Out) :: y
    Real temp(n)
    ...
    the dummy argument N can be used to declare the local array TEMP.
  • [7.1] Pointers and pointer components can be initialised to point to a target. The target must be valid for that pointer (e.g. same type, rank, etc.). The main cases are:
    Named pointer initialisation
    For data pointers, the target must have the SAVE attribute (variables in modules and the main program have this attribute implicitly). For procedure pointers, the target must be a module procedure or external procedure, not a dummy procedure, internal procedure, or statement function.

    For example,

      Module m
    Real,Target :: x
    Real,Pointer :: p => x
  End Module
  Program test
    Use m
    p = 3
    Print *,x ! Will print the value 3.0
  End Program
    Component default initialisation
    Pointer components can be default-initialised to point to a target. The requirements on the target are the same as for named pointer initialisation.

    For example,

      Module m
    Real,Target :: x
    Type t
      Real,Pointer :: p => x
    End Type
  End Module
  Program test
    Use m
    Type(t) y
    y%p = 3
    Print *,x ! Will print the value 3.0
  End Program
    Component initialisation with structure constructors
    A structure constructor in a constant expression can specify a target for any pointer component. The requirements on the target are the same as for named pointer initialisation.

    For example,

      Module m
    Real,Target :: x
    Type t
      Real,Pointer :: p
    End Type
  End Module
  Program test
    Use m
    Type(t) :: y = t(x)
    y%p = 3
    Print *,x ! Will print the value 3.0
  End Program
  • [7.1] A reference to a function that returns a pointer can be used as a variable in many contexts. In particular, it can be used as the variable in an assignment statement, as the actual argument corresponding to an INTENT(OUT) or INTENT(INOUT) dummy argument, and as the selector in an ASSOCIATE or SELECT TYPE construct that modifies the associate-name.

    For example, with this module,

      Module m
    Real,Target,Save :: table(100) = 0
  Contains
    Function f(n)
      Integer,Intent(In) :: n
      Real,Pointer :: f
      f => table(Min(Max(1,n),Size(table)))
    End Function
  End Module
    the program below will print “-1.23E+02”.
      Program example
    Use m
    f(13) = -123
    Print 1,f(13)
  1 Format(ES10.3)
  End Program

    It should be noted that the syntax of a statement function definition is identical to part of the syntax of a pointer function reference as a variable; the existence of a pointer-valued function that is accessible in the scope determines which of these it is. This may lead to confusing error messages in some situations.

    With the above module, this program demonstrates the use of the feature with an ASSOCIATE construct.

      Program assoc_eg
    Use m
    Associate(x=>f(3), y=>f(4))
      x = 0.5
      y = 3/x
    End Associate
    Print 1,table(3:4) ! Will print "  5.00E-01  6.00E+00"
  1 Format(2ES10.2)
  End Program

    Finally, here is an example using argument passing.

      Program argument_eg
    Use m
    Call set(f(7))
    Print 1,table(7) ! Will print "1.41421"
  1 Format(F7.5)
  Contains
    Subroutine set(x)
      Real,Intent(Out) :: x
      x = Sqrt(2.0)
    End Subroutine
  End Program

    Other contexts where a reference to a pointer-valued function may be used instead of a variable designator include:

    • as an internal file specifier in a WRITE statement (the function must return a pointer to a character string or array for this);
    • as an input-item in a READ statement;
    • as a STAT= or ERRMSG= variable in an ALLOCATE or DEALLOCATE statement, or in an image control statement such as EVENT WAIT;
    • as the team variable in a FORM TEAM statement.
  • [7.1] The result of a function can be a procedure pointer. For example,
      Module ppfun
    Private
    Abstract Interface
      Subroutine charsub(string)
        Character(*),Intent(In) :: string
      End Subroutine
    End Interface
    Public charsub,hello_goodbye
  Contains
    Subroutine hello(string)
      Character(*),Intent(In) :: string
      Print *,'Hello: ',string
    End Subroutine
    Subroutine bye(string)
      Character(*),Intent(In) :: string
      Print *,'Goodbye: ',string
      Stop
    End Subroutine
    Function hello_goodbye(flag)
      Logical,Intent(In) :: flag
      Procedure(hello),Pointer :: hello_goodbye
      If (flag) Then
        hello_goodbye => hello
      Else
        hello_goodbye => bye
      End If
    End Function
  End Module
  Program example
    Use ppfun
    Procedure(charsub),Pointer :: pp
    pp => hello_goodbye(.True.)
    Call pp('One')
    pp => hello_goodbye(.False.)
    Call pp('Two')
  End Program
    The function hello_goodbye in module ppfun returns a pointer to a procedure, which needs to be pointer-assigned to a procedure pointer to be invoked. When executed, this example will print
     Hello: One
 Goodbye: Two

    Use of this feature is not recommended, as it blurs the lines between data objects and procedures; this may lead to confusion or misunderstandings during code maintenance. The feature provides no functionality that was not already provided by procedure pointer components.


NAG Fortran Compiler, Release 7.1: Data usage and computation [mostly 5.3]

 Navigation: Previous Up Next

10.4 Data usage and computation [mostly 5.3]

  • In a structure constructor, the value for an allocatable component may be omitted: this has the same effect as specifying NULL().
  • [6.0] When allocating an array with the ALLOCATE statement, if SOURCE= or MOLD= is present and its expression is an array, the array can take its shape directly from the expression. This is a lot more concise than using SIZE or UBOUND, especially for a multi-dimensional array.

    For example,

       SUBROUTINE s(x,mask)
      REAL x(:,:,:)
      LOGICAL mask(:,:,:)
      REAL,ALLOCATABLE :: y(:,:,:)
      ALLOCATE(y,MOLD=x)
      WHERE (mask)
        y = 1/x
      ELSEWHERE
        y = HUGE(x)
      END WHERE
      ! ...
   END SUBROUTINE
  • [6.2] An ALLOCATE statement with the SOURCE= clause is permitted to have more than one allocation. The source-expr is assigned to every variable allocated in the statement. For example,
       PROGRAM multi_alloc
      INTEGER,ALLOCATABLE :: x(:),y(:,:)
      ALLOCATE(x(3),y(2,4),SOURCE=42)
      PRINT *,x,y
   END PROGRAM
    will print the value “42” eleven times (the three elements of x and the eight elements of y). If the source-expr is an array, every allocation needs to have the same shape.
  • [6.1] The real and imaginary parts of a COMPLEX object can be accessed using the complex part designators ‘%RE’ and ‘%IM’. For example, given
       COMPLEX,PARAMETER :: c = (1,2), ca(2) = [ (3,4),(5,6) ]
    the designators c%re and c%im have the values 1 and 2 respectively, and ca%re and ca%im are arrays with the values [ 3,5 ] and [ 4,6 ] respectively. In the case of variables, for example
       COMPLEX :: v, va(10)
    the real and imaginary parts can also be assigned to directly; the statement
       va%im = 0
    will set the imaginary part of each element of va to zero without affecting the real part.
  • In an ALLOCATE statement for one or more variables, the MOLD= clause can be used to give the variable(s) the dynamic type and type parameters (and optionally shape) of an expression. The expression in MOLD= must be type-compatible with each allocate-object, and if the expression is a variable (e.g. MOLD=X), the variable need not be defined. Note that the MOLD= clause may appear even if the type, type parameters and shape of the variable(s) being allocated are not mutable. For example,
       CLASS(*),POINTER :: a,b,c
   ALLOCATE(a,b,c,MOLD=125)
    will allocate the unlimited polymorphic pointers A, B and C to be of type Integer (with default kind); unlike SOURCE=, the values of A, B and C will be undefined.
  • [5.3.1] Assignment to a polymorphic allocatable variable is permitted. If the variable has different dynamic type or type parameters, or if an array, a different shape, it is first deallocated. If it is unallocated (or is deallocated by step 1), it is then allocated to have the correct type and shape. It is then assigned the value of the expression. Note that the operaton of this feature is similar to the way that ALLOCATE(variable,SOURCE=expr) works. For example, given
       CLASS(*),ALLOCATABLE :: x
    execution of the assignment statement
       x = 43
    will result in X having dynamic type Integer (with default kind) and value 43, regardless of whether X was previously unallocated or allocated with any other type (or kind).
  • [6.1] Rank-remapping pointer assignment is now permitted when the target has rank greater than one, provided it is “simply contiguous” (a term which means that it must be easily seen at compile-time to be contiguous). For example, the pointer assignment in
       REAL,TARGET :: x(100,100)
   REAL,POINTER :: x1(:)
   x1(1:Size(x)) => x
    establishes X1 as a single-dimensional alias for the whole of X.


NAG Fortran Compiler, Release 7.1: Execution control [mostly 6.0]

 Navigation: Previous Up Next

10.5 Execution control [mostly 6.0]

  • [5.3] The BLOCK construct allows declarations of entities within executable code. For example,
      Do i=1,n
    Block
      Real tmp
      tmp = a(i)**3
      If (tmp>b(i)) b(i) = tmp
    End Block
  End Do
    Here the variable tmp has its scope limited to the BLOCK construct, so will not affect anything outside it. This is particularly useful when including code by INCLUDE or by macro preprocessing.

    All declarations are allowed within a BLOCK construct except for COMMON, EQUIVALENCE, IMPLICIT, INTENT, NAMELIST, OPTIONAL and VALUE; also, statement function definitions are not permitted.

    BLOCK constructs may be nested; like other constructs, branches into a BLOCK construct from outside are not permitted. A branch out of a BLOCK construct “completes” execution of the construct.

    Entities within a BLOCK construct that do not have the SAVE attribute (including implicitly via initialisation), will cease to exist when execution of the construct is completed. For example, an allocated ALLOCATABLE variable will be automatically deallocated, and a variable with a FINAL procedure will be finalised.

  • The EXIT statement is no longer restricted to exiting from a DO construct; it can now be used to jump to the end of a named ASSOCIATE, BLOCK, IF, SELECT CASE or SELECT TYPE construct (i.e. any named construct except FORALL and WHERE). Note that an EXIT statement with no construct-name still exits from the innermost DO construct, disregarding any other named constructs it might be within.
  • In a STOP statement, the stop-code may be any scalar constant expression of type integer or default character. (In the NAG Fortran Compiler this also applies to the PAUSE statement, but that statement is no longer standard Fortran.) Additionally, the STOP statement with an integer stop-code now returns that value as the process exit status (on most operating systems there are limits on the value that can be returned, so for the NAG Fortran Compiler this returns only the lower eight bits of the value).
  • The ERROR STOP statement has been added. This is similar to the STOP statement, but causes error termination rather than normal termination. The syntax is identical to that of the STOP statement apart from the extra keyword ‘ERROR’ at the beginning. Also, the default process exit status is zero for normal termination, and non-zero for error termination.

    For example,

       IF (x<=0) ERROR STOP 'x must be positive'
  • [6.1] The FORALL construct now has an optional type specifier in the initial statement of the construct, which can be used to specify the type (which must be INTEGER) and kind of the index variables. When this is specified, the existence or otherwise of any entity in the outer scope that has the same name as an index variable does not affect the index variable in any way. For example,
      Complex i(100)
  Real x(200)
  ...
  Forall (Integer :: i=1:Size(x)) x(i) = i

    Note that the FORALL construct is still not recommended for high performance, as the semantics imply evaluating the right-hand sides into array temps the size of the iteration space, and then assigning to the variables; this usually performs worse than ordinary DO loops.

  • [6.1] The DO CONCURRENT construct is a DO loop with restrictions and semantics intended to allow efficient execution. The iterations of a DO CONCURRENT construct may be executed in any order, and possibly even in parallel. The loop index variables are local to the construct.

    The DO CONCURRENT header has similar syntax to the FORALL header, including the ability to explicitly specify the type and kind of the loop index variables, and including the scalar mask.

    The restrictions on the DO CONCURRENT construct are:

    • no branch is allowed from within the construct to outside of it (this includes the RETURN and STOP statements, but ERROR STOP is allowed);
    • the EXIT statement cannot be used to terminate the loop;
    • the CYCLE statement cannot refer to an outer loop;
    • there must be no dependencies between loop iterations, and if a variable is assigned to by any iteration, it is not allowed to be referenced by another iteration unless that iteration assigns it a value first;
    • all procedures referenced within the construct must be pure;
    • no image control statements can appear within the loop;
    • no reference to IEEE_GET_FLAG or IEEE_SET_HALTING_MODE is allowed.

    For example,

      Integer vsub(n)
  ...
  Do Concurrent (i=1:n)
    ! Safe because vsub has no duplicate values.
    x(vsub(i)) = i
  End Do

    The full syntax of the DO CONCURRENT statement is:

    [ do-construct-name : ] DO [ label ] [, ] CONCURRENT forall-header

    where forall-header is

    ( [ integer-type-spec :: ] triplet-spec [, triplet-spec ]... [, mask-expr ] )

    where mask-expr is a scalar logical expression, and triplet-spec is

    name = expr : expr [ : expr ]


NAG Fortran Compiler, Release 7.1: Intrinsic procedures and modules

 Navigation: Previous Up Next

10.6 Intrinsic procedures and modules

10.6.1 Additional mathematical intrinsic functions [mostly 5.3.1]

  • The elemental intrinsic functions ACOSH, ASINH and ATANH compute the inverse hyperbolic cosine, sine or tangent respectively. There is a single argument X, which may be of type Real or Complex; the result of the function has the same type and kind. When the argument is Complex, the imaginary part is expressed in radians and lies in the range 0≤im≤π for the ACOSH function, and −π/2≤im≤π/2 for the ASINH and ATANH functions.

    For example, ACOSH(1.543081), ASINH(1.175201) and ATANH(0.7615942) are all approximately equal to 1.0.

  • [6.1] The new elemental intrinsic functions BESSEL_J0, BESSEL_Y0, BESSEL_J1 and BESSEL_Y1 compute the Bessel functions J0, Y0, J1 and Y1 respectively. These functions are solutions to Bessel's differential equation. The J functions are of the 1st kind and the Y functions are of the 2nd kind; the following subscript indicates the order (0 or 1). There is a single argument X, which must be of type Real; the result of the function has the same type and kind. For functions of the 2nd kind (BESSEL_Y0 and BESSEL_Y1), the argument X must be positive. For example, BESSEL_J0(1.5) is approximately 0.5118276, BESSEL_Y0(1.5) is approximately 0.3824489, BESSEL_J1(1.5) is approximately 0.5579365 and BESSEL_Y1(1.5) is approximately -0.4123086.
  • [6.1] The new intrinsic functions BESSEL_JN and BESSEL_YN compute the Bessel functions Jn and Yn respectively. These functions come in two forms: an elemental form and a transformational form.

    The elemental form has two arguments: N, the order of the function to compute, and X, the argument of the Bessel function. BESSEL_JN(0,X) is identical to BESSEL_J0(X), etc..

    The transformational form has three scalar arguments: N1, N2 and X. The result is a vector of size MAX(N2-N1+1,0), containing approximations to the Bessel functions of orders N1 to N2 applied to X.

    For example, BESSEL_JN(5,7.5) is approximately 0.283474, BESSEL_YN(5,7.5) is approximately 0.175418, BESSEL_JN(3,5,7.5) is approximately [ -0.258061, 0.023825, 0.283474 ] and BESSEL_YN(3,5,7.5) is approximately [ 0.159708, 0.314180, 0.175418 ].

  • [6.0] The elemental intrinsic functions ERF, ERFC and ERFC_SCALED compute the error function, the complementary error function and the scaled complementary error function, respectively. The single argument X must be of type real.

    The error function is the integral of −t2 from 0 to X, times 2/SQRT(π); this rapidly converges to 1. The complementary error function is 1 minus the error function, and fairly quickly converges to zero. The scaled complementary error function scales the value (of 1 minus the error function) by EXP(X**2); this also converges to zero but only very slowly.

  • [6.0] The elemental intrinsic functions GAMMA and LOG_GAMMA compute the gamma function and the natural logarithm of the absolute value of the gamma function respectively. The single argument X must be of type real, and must not be zero or a negative integer.

    The gamma function is the extension of factorial from the integers to the reals; for positive integers, GAMMA(X) is equal to (X−1)!, i.e. factorial of X−1. This grows very rapidly and thus overflows for quite small X; LOG_GAMMA also diverges but much more slowly.

  • The elemental intrinsic function HYPOT computes the “Euclidean distance function” (square root of the sum of squares) of its arguments X and Y without overflow or underflow for very large or small X or Y (unless the result itself overflows or underflows). The arguments must be of type Real with the same kind, and the result is of type Real with that kind. Note that HYPOT(X,Y) is semantically and numerically equal to ABS(CMPLX(X,Y,KIND(X))).

    For example, HYPOT(3e30,4e30) is approximately equal to 5e30.

  • The array reduction intrinsic function NORM2(X,DIM) reduces Real arrays using the L2-norm operation. This operates exactly the same as SUM and PRODUCT, except for the operation involved. The L2 norm of an array is the square root of the sum of the squares of the elements. Note that unlike most of the other reduction functions, NORM2 does not have a MASK argument. The DIM argument is optional; an actual argument for DIM is not itself permitted to be an optional dummy argument.

    The calculation of the result value is done in such a way as to avoid intermediate overflow and underflow, except when the result itself is outside the maximum range. For example, NORM2([X,Y]) is approximately the same as HYPOT(X,Y).

10.6.2 Additional intrinsic functions for bit manipulation [mostly 5.3]

  • The elemental intrinsic functions BGE, BGT, BLE and BLT perform bitwise (i.e. unsigned) comparisons. They each have two arguments, I and J, which must be of type Integer but may be of different kind. The result is default Logical.

    For example, BGE(INT(Z'FF',INT8),128) is true, while INT(Z'FF',INT8)>=128 is false.

  • [5.3.1] The elemental intrinsic functions DSHIFTL and DSHIFTR perform double-width shifting. They each have three arguments, I, J and SHIFT which must be of type Integer, except that one of I or J may be a BOZ literal constant – it will be converted to the type and kind of the other I or J argument. I and J must have the same kind if they are both of type Integer. The result is of type Integer, with the same kind as I and J. The I and J arguments are effectively concatenated to form a single double-width value, which is shifted left or right by SHIFT positions; for DSHIFTL the result is the top half of the combined shift, and for DSHIFTR the result is the bottom half of the combined shift.

    For example, DSHIFTL(INT(B'11000101',1),B'11001001',2) has the value
INT(B'00010111',1) (decimal value 23), whereas
DSHIFTR(INT(B'11000101',1),B'11001001',2) has the value
INT(B'01110010',1) (decimal value 114).

  • The array reduction intrinsic functions IALL, IANY and IPARITY reduce arrays using bitwise operations. These are exactly the same as SUM and PRODUCT, except that instead of reducing the array by the + or * operation, they reduce it by the IAND, IOR and IEOR intrinsic functions respectively. That it, each element of the result is the bitwise-and, bitwise-or, or bitwise-exclusive-or of the reduced elements. If the number of reduced elements is zero, the result is zero for IANY and IPARITY, and NOT(zero) for IALL.
  • The elemental intrinsic functions LEADZ and TRAILZ return the number of leading (most significant) and trailing (least significant) zero bits in the argument I, which must be of type Integer (of any kind). The result is default Integer.
  • The elemental intrinsic functions MASKL and MASKR generate simple left-justified and right-justified bitmasks. The value of MASKL(I,KIND) is an integer with the specified kind that has its leftmost I bits set to one and the rest set to zero; I must be non-negative and less than or equal to the bitsize of the result. If KIND is omitted, the result is default integer. The value of MASKR is similar, but has its rightmost I bits set to one instead.
  • [5.3.1] The elemental intrinsic function MERGE_BITS(I,J,MASK) merges the bits from Integer values I and J, taking the bit from I when the corresponding bit in MASK is 1, and taking the bit from J when it is zero. All arguments must be BOZ literal constants or of type Integer, and all the Integer arguments must have the same kind; at least one of I and J must be of type Integer, and the result has the same type and kind.

    Note that MERGE_BITS(I,J,MASK) is identical to IOR(IAND(I,MASK),IAND(J,NOT(MASK))).

    For example, MERGE_BITS(INT(B'00110011',1),B'11110000',B'10101010') is equal to INT(B'01110010') (decimal value 114).

  • The array reduction intrinsic function PARITY reduces Logical arrays. It is exactly the same as ALL and ANY, except that instead of reducing the array by the .AND. or .OR. operation, it reduces it by the .NEQV. operation. That is, each element of the result is .TRUE. if an odd number of reduced elements is .TRUE..
  • The elemental intrinsic function POPCNT(I) returns the number of bits in the Integer argument I that are set to 1. The elemental intrinsic function POPPAR(I) returns zero if the number of bits in I that are set to 1 are even, and one if it is odd. The result is default Integer.

10.6.3 Other new intrinsic procedures [mostly 5.3.1]

  • The intrinsic subroutine EXECUTE_COMMAND_LINE passes a command line to the operating system's command processor for execution. It has five arguments, in order these are:
    CHARACTER(*),INTENT(IN) :: COMMAND — the command to be executed;
    LOGICAL,INTENT(IN),OPTIONAL :: WAIT — whether to wait for command completion (default true);
    INTEGER,INTENT(INOUT),OPTIONAL :: EXITSTAT — the result value of the command;
    INTEGER,INTENT(OUT),OPTIONAL :: CMDSTAT — see below;
    CHARACTER(*),INTENT(INOUT),OPTIONAL :: CMDMSG — the error message if CMDSTAT is non-zero.

    CMDSTAT values are zero for success, −1 if command line execution is not supported, −2 if WAIT is present and false but asynchronous execution is not supported, and a positive value to indicate some other error. If CMDSTAT is not present but would have been set non-zero, the program will be terminated. Note that Release 5.3.1 supports command line execution on all systems, and does not support asynchronous execution on any system.

    For example, CALL EXECUTE_COMMAND_LINE('echo Hello') will probably display ‘Hello’ in the console window.

  • The intrinsic function STORAGE_SIZE(A,KIND) returns the size in bits of a scalar object with the same dynamic type and type parameters as A, when it is stored as an array element (i.e. including any padding). The KIND argument is optional; the result is type Integer with kind KIND if it is present, and default kind otherwise.

    If A is allocatable or a pointer, it does not have to be allocated unless it has a deferred type parameter (e.g. CHARACTER(:)) or is CLASS(*). If it is a polymorphic pointer, it must not have an undefined status.

    For example, STORAGE_SIZE(13_1) is equal to 8 (bits).

  • [6.0] The intrinsic inquiry function IS_CONTIGUOUS has a single argument ARRAY, which can be an array of any type. The function returns true if ARRAY is stored contiguously, and false otherwise. Note that this question has no meaning for an array with no elements, or for an array expression since that is a value and not a variable.
  • [7.0] The intrinsic function FINDLOC is similar to MAXLOC and MINLOC, but instead of finding the location of the maximum or minimum value of an array, it finds a location that is equal to a specified value; thus it is available for all intrinsic types including COMPLEX and LOGICAL. It has one of the following two forms:
           FINDLOC (ARRAY, VALUE, DIM, MASK, KIND, BACK )
       FINDLOC (ARRAY, VALUE, MASK, KIND, BACK )
    where

    ARRAY | is an array of intrinsic type, with rank N;
    VALUE | is a scalar of the same type (if LOGICAL) or which may be compared with ARRAY using the intrinsic
    operator == (or .EQ.);
    DIM | is a scalar INTEGER in the range 1 to N;
    MASK | (optional) is an array of type LOGICAL with the same shape as ARRAY
    KIND | (optional) is a scalar INTEGER constant expression that is a valid Integer kind number;
    BACK | (optional) is a scalar LOGICAL value.

    The result of the function is type INTEGER, or INTEGER(KIND) if KIND is present.

    In the form without DIM, the result is a vector of length N, and is the location of the element of ARRAY that is equal to VALUE; if MASK is present, only elements for which the corresponding element of MASK are .TRUE. are considered. As in MAXLOC and MINLOC, the location is reported with 1 for the first element in each dimension; if no element equal to VALUE is found, the result is zero. If BACK is present with the value .TRUE., the element found is the last one (in array element order); otherwise, it is the first one.

    In the form with DIM, the result has rank N−1 (thus scalar if ARRAY is a vector), the shape being that of ARRAY with dimension DIM removed, and each element of the result is the location of the (masked) element in the dimension DIM vector that is equal to VALUE.

    For example, if ARRAY is an Integer vector with value [ 10,20,30,40,50 ], FINDLOC(ARRAY,30) will return the vector [ 3 ] and FINDLOC(ARRAY,7) will return the vector [ 0 ].

10.6.4 Changes to existing intrinsic procedures [mostly 5.3.1]

  • The intrinsic functions ACOS, ASIN, ATAN, COSH, SINH, TAN and TANH now accept arguments of type Complex. Note that the hyperbolic and non-hyperbolic versions of these functions and the new ACOSH, ASINH and ATANH functions are all related by simple algebraic identities, for example the new COSH(X) is identical to the old COS((0,1)*X) and the new SINH(X) is identical to the old (0,-1)*SIN((0,1)*X).
  • The intrinsic function ATAN now has an extra form ATAN(Y,X), with exactly the same semantics as ATAN2(Y,X).
  • [6.2] The intrinsic functions MAXLOC and MINLOC now have an additional optional argument BACK following the KIND argument. It is scalar and of type Logical; if present with the value .True., if there is more than one element that has the maximum value (for MAXLOC) or minimum value (for MINLOC), the array element index returned is for the last element with that value rather than the first.

    For example, the value of

           MAXLOC( [ 5,1,5 ], BACK=.TRUE.)
    is the array [ 3 ], rather than [ 1 ].
  • The intrinsic function SELECTED_REAL_KIND now has a third argument RADIX; this specifies the desired radix of the Real kind requested. Note that the function IEEE_SELECTED_REAL_KIND in the intrinsic module IEEE_ARITHMETIC also has this new third argument, and will allow requesting IEEE decimal floating-point kinds if they become available in the future.

10.6.5 ISO_C_BINDING additions [6.2]

The standard intrinsic module ISO_C_BINDING contains an additional procedure as follows.
INTERFACE c_sizeof
  PURE INTEGER(c_size_t) FUNCTION c_sizeof...(x) ! Specific name not visible
    TYPE(*) :: x(..)
  END FUNCTION
END INTERFACE

The actual argument x must be interoperable. The result is the same as the C sizeof operator applied to the conceptually corresponding C entity; that is, the size of x in bytes. If x is an array, it is the size of the whole array, not just one element. Note that x cannot be an assumed-size array.

10.6.6 ISO_FORTRAN_ENV additions

[5.3] The standard intrinsic module ISO_FORTRAN_ENV contains additional named constants as follows.
  • The additional scalar integer constants INT8, INT16, INT32, INT64, REAL32, REAL64 and REAL128 supply the kind type parameter values for integer and real kinds with the indicated bit sizes.
  • The additional named array constants CHARACTER_KINDS, INTEGER_KINDS, LOGICAL_KINDS and REAL_KINDS list the available kind type parameter values for each type (in no particular order).

[6.1] The standard intrinsic module ISO_FORTRAN_ENV contains two new functions as follows.

  • COMPILER_VERSION. This function is pure, has no arguments, and returns a scalar default character string that identifies the version of the compiler that was used to compile the source file. This function may be used in a constant expression, e.g. to initialise a variable or named constant with this information. For example,
      Module version_info
    Use Iso_Fortran_Env
    Character(Len(Compiler_Version())) :: compiler = Compiler_Version()
  End Module
  Program show_version_info
    Use version_info
    Print *,compiler
  End Program
    With release 6.1 of the NAG Fortran Compiler, this program will print something like
     NAG Fortran Compiler Release 6.1(Tozai) Build 6105
  • COMPILER_OPTIONS. This function is pure, has no arguments, and returns a scalar default character string that identifies the options supplied to the compiler when the source file was compiled. This function may be used in a constant expression, e.g. to initialise a variable or named constant with this information. For example,
      Module options_info
    Use Iso_Fortran_Env
    Character(Len(Compiler_Options())) :: compiler = Compiler_Options()
  End Module
  Program show_options_info
    Use options_info
    Print *,compiler
  End Program
    If compiled with the options -C=array -C=pointer -O, this program will print something like
     -C=array -C=pointer -O


NAG Fortran Compiler, Release 7.1: Input/output extensions [mostly 5.3]

 Navigation: Previous Up Next

10.7 Input/output extensions [mostly 5.3]

  • The NEWUNIT= specifier has been added to the OPEN statement; this allocates a new unit number that cannot clash with any other logical unit (the unit number will be a special negative value). For example,
          INTEGER unit
      OPEN(FILE='output.log',FORM='FORMATTED',NEWUNIT=unit)
      WRITE(unit,*) 'Logfile opened.'
    The NEWUNIT= specifier can only be used if either the FILE= specifier is also used, or if the STATUS= specifier is used with the value 'SCRATCH'.
  • Recursive input/output is allowed on separate units. For example, in
       Write (*,Output_Unit) f(100)
    the function f is permitted to perform i/o on any unit except Output_Unit; for example, if the value 100 is out of range, it would be allowed to produce an error message with
       Write (*,Error_Unit) 'Error in F:',n,'is out of range'
  • [6.0] A sub-format can be repeated an indefinite number of times by using an asterisk (*) as its repeat count. For example,
       SUBROUTINE s(x)
     LOGICAL x(:)
     PRINT 1,x
1    FORMAT('x =',*(:,' ',L1))
   END SUBROUTINE
    will display the entire array x on a single line, no matter how many elements x has. An indefinite repeat count is only allowed at the top level of the format specification, and must be the last format item.
  • [6.0] The G0 and G0.d edit descriptors perform generalised editing with all leading and trailing blanks (except those within a character value itself) omitted. For example,
       PRINT 1,1.25,.True.,"Hi !",123456789
1  FORMAT(*(G0,','))
    produces the output
    1.250000,T,Hi !,123456789,


NAG Fortran Compiler, Release 7.1: Programs and procedures [mostly 5.3]

 Navigation: Previous Up Next

10.8 Programs and procedures [mostly 5.3]

  • An empty internal subprogram part, module subprogram part or type-bound procedure part is now permitted following a CONTAINS statement. In the case of the type-bound procedure part, an ineffectual PRIVATE statement may appear following the unnecessary CONTAINS statement.
  • [6.0] An internal procedure can be passed as an actual argument or assigned to a procedure pointer. When the internal procedure is invoked via the dummy argument or procedure pointer, it can access the local variables of its host procedure. In the case of procedure pointer assignment, the pointer is only valid until the host procedure returns (since the local variables cease to exist at that point).

    For example,

      SUBROUTINE mysub(coeffs)
    REAL,INTENT(IN) :: coeffs(0:) ! Coefficients of polynomial.
    REAL integral
    integral = integrate(myfunc,0.0,1.0) ! Integrate from 0.0 to 1.0.
    PRINT *,'Integral =',integral
  CONTAINS
    REAL FUNCTION myfunc(x) RESULT(y)
      REAL,INTENT(IN) :: x
      INTEGER i
      y = coeffs(UBOUND(coeffs,1))
      DO i=UBOUND(coeffs,1)-1,0,-1
        y = y*x + coeffs(i)
      END DO
    END FUNCTION
  END SUBROUTINE
  • The rules used for generic resolution and for checking that procedures in a generic are unambiguous have been extended. The extra rules are that
    • a dummy procedure is distinguishable from a dummy variable;
    • an ALLOCATABLE dummy variable is distinguishable from a POINTER dummy variable that does not have INTENT(IN).
  • [6.0] A disassociated pointer, or an unallocated allocatable variable, may be passed as an actual argument to an optional nonallocatable nonpointer dummy argument. This is treated as if the actual argument were not present.
  • [5.3.1] Impure elemental procedures can be defined using the IMPURE keyword. An impure elemental procedure has the restrictions that apply to elementality (e.g. all arguments must be scalar) but does not have any of the “pure” restrictions. This means that an impure elemental procedure may have side effects and can contain input/output and STOP statements. For example,
        Impure Elemental Integer Function checked_addition(a,b) Result(c)
      Integer,Intent(In) :: a,b
      If (a>0 .And. b>0) Then
        If (b>Huge(c)-a) Stop 'Positive Integer Overflow'
      Else If (a<0 .And. b<0) Then
        If ((a+Huge(c))+b<0) Stop 'Negative Integer Overflow'
      End If
      c = a + b
    End Function
    When an argument is an array, an impure elemental procedure is applied to each element in array element order (unlike a pure elemental procedure, which has no specified order). An impure elemental procedure cannot be referenced in a context that requires a procedure to be pure, e.g. within a FORALL construct.

    Impure elemental procedures are probably most useful for debugging (because i/o is allowed) and as final procedures.

  • [6.0] If an argument of a pure procedure has the VALUE attribute it does not need any INTENT attribute. For example,
       PURE SUBROUTINE s(a,b)
     REAL,INTENT(OUT) :: a
     REAL,VALUE :: b
     a = b
   END SUBROUTINE

    Note however that the second argument of a defined assignment subroutine, and all arguments of a defined operator function, are still required to have the INTENT(IN) attribute even if they have the VALUE attribute.

  • [5.3.1] The FUNCTION or SUBROUTINE keyword on the END statement for an internal or module subprogram is now optional (when the subprogram name does not appear). Previously these keywords were only optional for external subprograms.
  • ENTRY statements are regarded as obsolescent.
  • [1.0] A line in the program is no longer prohibited from beginning with a semi-colon.
  • [6.2] The name of an external procedure with a binding label is now considered to be a local identifier only, and not a global identifier. That means that code like the following is now standard-conforming:
          SUBROUTINE sub() BIND(C,NAME='one')
        PRINT *,'one'
      END SUBROUTINE
      SUBROUTINE sub() BIND(C,NAME='two')
        PRINT *,'two'
      END SUBROUTINE
      PROGRAM test
        INTERFACE
          SUBROUTINE one() BIND(C)
          END SUBROUTINE
          SUBROUTINE two() BIND(C)
          END SUBROUTINE
        END INTERFACE
        CALL one
        CALL two
      END PROGRAM
  • [6.2] An internal procedure is permitted to have the BIND(C) attribute, as long as it does not have a NAME= specifier. Such a procedure is interoperable with C, but does not have a binding label (as if it were specified with NAME='').
  • [6.2] A dummy argument with the VALUE attribute is permitted to be an array, and is permitted to be of type CHARACTER with length non-constant and/or not equal to one. (It is still not permitted to have the ALLOCATABLE or POINTER attributes, and is not permitted to be a coarray.)

    The effect is that a copy is made of the actual argument, and the dummy argument is associated with the copy; any changes to the dummy argument do not affect the actual argument. For example,

           PROGRAM value_example_2008
         INTEGER :: a(3) = [ 1,2,3 ]
         CALL s('Hello?',a)
         PRINT '(7X,3I6)',a
       CONTAINS
         SUBROUTINE s(string,j)
           CHARACTER(*),VALUE :: string
           INTEGER,VALUE :: j(:)
           string(LEN(string):) = '!'
           j = j + 1
           PRINT '(7X,A,3I6)',string,j
         END SUBROUTINE
       END PROGRAM
    will produce the output
           Hello!     2     3     4
            1     2     3
  • [7.0] Submodules, together with separate module procedures, provide an additional method of structuring a Fortran program.

    A “separate module procedure” is a procedure whose interface is declared in the module specification part, but whose definition may provided either in the module itself, or in a submodule of that module. The interface of a separate module procedure is declared by using the MODULE keyword in the prefix of the interface body. For example,

           INTERFACE
         MODULE RECURSIVE SUBROUTINE sub(x,y)
           REAL,INTENT(INOUT) :: x,y
         END SUBROUTINE
       END INTERFACE
    An important aspect of the interface for a separate module procedure is that, unlike any other interface body, it accesses the module by host association without the need for an IMPORT statement. For example,
           INTEGER,PARAMETER :: wp = SELECTED_REAL_KIND(15)
       INTERFACE
         MODULE REAL(wp) FUNCTION f(a,b)
           REAL(wp) a,b
         END FUNCTION
       END INTERFACE
    The eventual definition of the separate module procedure, whether in the module itself or in a submodule, must have exactly the same characteristics, the same names for the dummy arguments, the same name for the result variable (if a function), the same binding-name (if it uses BIND(C)), and be RECURSIVE if and only if the interface is declared so. There are two ways to achieve this:
    1. Define the procedure in the normal way, and get all the characteristics right; the compiler will check that you have done so. Note that the definition must also include the MODULE keyword in the prefix, just like the definition. For example,
             ...
       CONTAINS
         MODULE REAL(wp) FUNCTION f(a,b)
           REAL(wp)a,b
           f = a**2 - b**3
         END FUNCTION
    2. Alternatively, the entire interface may be accessed in the definition without redeclaring everything by using the MODULE PROCEDURE statement in this context. For example,
             ...
       CONTAINS
         MODULE PROCEDURE sub
           ! Arguments A and B, their characteristics, and that this is a recursive
           ! subroutine, are all taken from the interface declaration.
           IF (a>b) THEN
             CALL sub(b,-ABS(a))
           ELSE
             a = b**2 - a
           END IF
         END PROCEDURE
    A submodule has the form (italic square brackets indicate optionality):
           submodule-stmt
         declaration-part
       [ CONTAINS
          module-subprogram-part ]
       END [ SUBMODULE [ submodule-name ] ]
    The initial submodule-stmt has the form
           SUBMODULE ( module-name [ : parent-submodule-name ] ) submodule-name
    where module-name is the name of a module with one or more separate module procedures, parent-submodule-name (if present) is the name of another submodule of that module, and submodule-name is the name of the submodule being defined. The submodules of a module thus form a tree structure, with successive submodules being able to extend others; however, the name of a submodule is unique within that module. This structure is to facilitate creation of internal infrastructure (types, constants, and procedures) that can be used by multiple submodules, without having to put all the infrastructure inside the module itself.

    The submodule being defined accesses its parent module or submodule by host association; for entities from the module, this includes access to PRIVATE entities. Any local entity it declares in the declaration-part will therefore block access to an entity in the host that has the same name.

    The entities (variables, types, procedures) declared by the submodule are local to that submodule, with the sole exception of separate module procedures that are declared in the ancestor module and defined in the submodule. No procedure is allowed to have a binding name, again, except in the case of a separate module procedure, where the binding name must be the same as in the interface.

    For example,

           MODULE mymod
         INTERFACE
           MODULE INTEGER FUNCTION next_number() RESULT(r)
           END FUNCTION
           MODULE SUBROUTINE reset()
           END SUBROUTINE
         END INTERFACE
       END MODULE
       SUBMODULE (mymod) variables
         INTEGER :: next = 1
       END SUBMODULE
       SUBMODULE (mymod:variables) functions
       CONTAINS
         MODULE PROCEDURE next_number
           r = next
           next = next + 1
         END PROCEDURE
       END SUBMODULE
       SUBMODULE (mymod:variables) subroutines
       CONTAINS
         MODULE SUBROUTINE reset()
           PRINT *,'Resetting'
           next = 1
         END SUBROUTINE
       END SUBMODULE
       PROGRAM demo
         USE mymod
         PRINT *,'Hello',next_number()
         PRINT *,'Hello again',next_number()
         CALL reset
         PRINT *,'Hello last',next_number()
       END PROGRAM

    Submodule information for use by other submodules is stored by the NAG Fortran Compiler in files named module.submodule.sub, in a format similar to that of .mod files. The -nomod option, which suppresses creation of .mod files, also suppresses creation of .sub files.


NAG Fortran Compiler, Release 7.1: Fortran 2018 Extensions

 Navigation: Previous Up Next

11 Fortran 2018 Extensions

  • 11.1 Fortran 2018 Overview
  • 11.2 Data declaration
  • 11.3 Data usage and computation
  • 11.4 Input/output
  • 11.5 Execution control
  • 11.6 Intrinsic procedures and modules
  • 11.7 Program units and procedures
  • 11.8 Advanced C interoperability
  • 11.9 Updated IEEE arithmetic capabilities
  • 11.10 Advanced coarray programming


NAG Fortran Compiler, Release 7.1: Fortran 2018 Overview

 Navigation: Previous Up Next

11.1 Fortran 2018 Overview

The new features of Fortran 2018 that are supported by the NAG Fortran Compiler can be grouped as follows:

  • Data declaration
  • Data usage and computation
  • Input/output
  • Execution control
  • Intrinsic procedures and modules
  • Program units and procedures
  • Advanced C interoperability
  • Updated IEEE arithmetic capabilities
  • Advanced coarray programming


NAG Fortran Compiler, Release 7.1: Data declaration

 Navigation: Previous Up Next

11.2 Data declaration

  • [5.3] If an object is initialised (in a type declaration statement or component definition statement), its array bounds and character length can be used in its initialisation expression.
  • [7.0] The EQUIVALENCE and COMMON statements, and the BLOCK DATA program unit, are considered to be obsolescent (and reported as such when the -f2018 option is used).
  • [7.1] Assumed-rank dummy arguments accept actual arguments of any rank; they assume the rank from the actual argument. This rank may be zero; that is, the actual argument may be scalar. Furthermore, assumed-rank dummy arguments may have the ALLOCATABLE or POINTER attribute, and thus accept allocatable/pointer variables of any rank.

    The syntax is as follows:

      Real,Dimension(..) :: a, b
  Integer :: c(..)
    That declares three variables (which must be dummy arguments) to be assumed-rank.

    The use of assumed-rank dummy arguments within Fortran is extremely limited; basically, the intrinsic inquiry functions can be used, and there is a SELECT RANK construct, but other than that they may only appear as actual arguments to other procedures where they correspond to another assumed-rank argument.

    The main use of assumed rank is for advanced C interoperability (see later section).

    Here is an extremely simple example of use within Fortran:

      Program assumed_rank_example
    Real x(1,2),y(3,4,5,6,7)
    Call showrank(1.5)
    Call showrank(x)
    Call showrank(y)
  Contains
    Subroutine showrank(a)
      Real,Intent(In) :: a(..)
      Print *,'Rank is',Rank(a)
    End Subroutine
  End Program
    That will produce the output
     Rank is 0
 Rank is 2
 Rank is 5
  • [7.1] The TYPE(*) type specifier can be used to declare scalar, assumed-size, and assumed-rank dummy arguments. Such an argument is called assumed-type; the corresponding actual argument may be of any type. It must not have the ALLOCATABLE, CODIMENSION, INTENT (OUT), POINTER, or VALUE attribute.

    An assumed-type variable is extremely limited in the ways it can be used directly in Fortran:

    • it may be passed as an actual argument to another assumed-type dummy argument;
    • it may appear as the first argument to the intrinsic functions IS_CONTIGUOUS, LBOUND, PRESENT, SHAPE, SIZE, or UBOUND;
    • it may be used as the argument of the function C_LOC (in the ISO_C_BINDING intrinsic module}.
    Other than these contexts, it cannot be used in any other way at all. Note that if it is an array, you cannot subscript it or create an array section from it.

    This is mostly useful for interoperating with C programs (see later section). Note that in a non-generic procedure reference, a scalar argument can be passed to an assumed-type argument that is an assumed-size array.


NAG Fortran Compiler, Release 7.1: Data usage and computation

 Navigation: Previous Up Next

11.3 Data usage and computation

  • [7.1] The SELECT RANK construct facilitates use of assumed rank objects within Fortran. It has the syntax
      [ construct-name ] SELECT RANK ( [ assoc_name => ] assumed-rank-variable-name )
        [ rank-stmt
            block ]...
  END SELECT [ construct-name ]
    where rank-stmt is one of:
      RANK ( scalar-int-constant-expression ) [ construct-name ]
  RANK ( * ) [ construct-name ]
  RANK DEFAULT [ construct-name ]
    In any particular SELECT RANK construct, there must not be more than one RANK DEFAULT statement, or more than one RANK (*) statement, or more than RANK (integer) with the same value integer expression. If the assumed-rank variable has the ALLOCATABLE or POINTER attribute, the RANK (*) statement is not permitted.

    The block following a RANK statement with an integer constant expression is executed if the assumed-rank variable is associated with a non-assumed-rank actual argument that has that rank, and is not an assumed-size array. Within the block it acts as if it were an assumed-shape array with that rank.

    The block following a RANK (*) is executed if the ultimate argument is an assumed-size array. Within the block it acts as if it were declared with bounds ‘(1:*)’; if different bounds or rank are desired, this can be passed to another procedure using sequence association.

    The block following a RANK DEFAULT statement is executed if no other block is selected. Within its block, it is still an assumed-rank variable, i.e. there is no change.

    Here is a simple example of the SELECT RANK construct.

      Program select_rank_example
    Integer :: a = 123, b(1,2) = Reshape( [ 10,20 ], [ 1,2 ] ), c(1,3,1) = 777, d(1,1,1,1,1)
    Call show(a)
    Call show(b)
    Call show(c)
    Call show(d)
  Contains
    Subroutine show(x)
      Integer x(..)
      Select Rank(x)
      Rank (0)
        Print 1,'scalar',x
      Rank (1)
        Print 1,'vector',x
      Rank (2)
        Print 1,'matrix',x
      Rank (3)
        Print 1,'3D array',x
      Rank Default
        Print *,'Rank',Rank(x),'not supported'
      End Select
    1 Format(1x,a,*(1x,i0,:))
    End Subroutine
  End Program
    This will produce the output
     scalar 123
 matrix 10 20
 3D array 777 777 777
 Rank 5 not supported


NAG Fortran Compiler, Release 7.1: Input/output

 Navigation: Previous Up Next

11.4 Input/output

  • [7.0] The RECL= specifier in an INQUIRE statement for an unconnected unit or file now assigns the value −1 to the variable. For a unit or file connected with ACCESS='STREAM', it assigns the value −2 to the variable. Under previous Fortran standards, the variable became undefined.
  • [7.1] The SIZE= specifier can be used in a READ statement without ADVANCE='NO', that is, in a READ statement with no ADVANCE= specifier, or one with an explicit ADVANCE='YES'. For example,
        Character(65536) buf
    Integer nc
    Read(*,'(A)',Size=nc) buf
    Print *,'The number of characters on that line was',nc
    Note that SIZE= is not permitted with list-directed or namelist formatting; that would be pointless, as there are no edit descriptors with such formatting and thus no characters to be counted by SIZE=.


NAG Fortran Compiler, Release 7.1: Execution control

 Navigation: Previous Up Next

11.5 Execution control

  • [6.2] The expression in an ERROR STOP or STOP statement can be non-constant. It is still required to be default Integer or default Character.
  • [6.2] The ERROR STOP and STOP statements now have an optional QUIET= specifier, which is preceded by a comma following the optional stop-code. This takes a Logical expression; if it is true at runtime then the STOP (or ERROR STOP) does not output any message, and information about any IEEE exceptions that are signalling will be suppressed. For example,
        STOP 13, QUIET = .True.
    will not display the usual ‘STOP: 13’, but simply do normal termination, with a process exit status of 13. Note that this means that the following two statements are equivalent:
        STOP, QUIET=.True.
    STOP 'message not output', QUIET=.TRUE.


NAG Fortran Compiler, Release 7.1: Intrinsic procedures and modules

 Navigation: Previous Up Next

11.6 Intrinsic procedures and modules

  • [6.2] The intrinsic subroutine MOVE_ALLOC now has optional STAT and ERRMSG arguments. The STAT argument must be of type Integer, with a decimal range of at least four (i.e. not an 8-bit integer); it is assigned the value zero if the subroutine executes successfully, and a nonzero value otherwise. The ERRMSG argument must be of type Character with default kind. If STAT is present and assigned a nonzero value, ERRMSG will be assigned an explanatory message (if it is present); otherwise, ERRMSG will retain its previous value (if any).

    For example,

        INTEGER,ALLOCATABLE :: x(:),y(:)
    INTEGER istat
    CHARACTER(80) emsg
    ...
    CALL MOVE_ALLOC(x,y,istat,emsg)
    IF (istat/=0) THEN
      PRINT *,'Unexpected error in MOVE_ALLOC: ',TRIM(emsg)

    The purpose of these arguments is to catch errors in multiple image coarray allocation/deallocation, such as STAT_STOPPED_IMAGE and STAT_FAILED_IMAGE.

  • [7.1] The DIM argument to the intrinsic functions ALL, ANY, FINDLOC, IALL, IANY, IPARITY, MAXLOC, MAXVAL, MINLOC, MINVAL, NORM2, PARITY, PRODUCT and SUM can be an optional dummy argument, as long as it is present at execution time. For example,
      Subroutine sub(x,n)
    Real,Intent(In) :: x(:,:,:)
    Integer,Intent(In),Optional :: n
    If (Present(n)) Then
      Print *,Norm2(x,n) ! Rank two array result.
    Else
      Print *,Norm2(x)   ! Scalar result.
    End If
  End Subroutine
  • [7.1] Specific intrinsic functions are considered to be obsolescent (and reported as such with the -f2018 option). In the case of a function that is both specific and generic, e.g. SQRT, the obsolescent usage is passing as an actual argument, use as a procedure interface, or being the target of a procedure pointer assignment.
  • [7.1] The intrinsic inquiry function RANK returns the dimensionality of its argument. It has the following syntax:
    RANK ( A )

    A : data object of any type:

    Result : scalar Integer of default kind.

    The result is the rank of A, that is, zero for scalar A, one if A is a one-dimensional array, and so on.

    This function can be used in a constant expression except when A is an assumed-rank variable.

  • [7.1] The intrinsic function REDUCE performs user-defined array reductions. It has the following syntax:
    REDUCE ( ARRAY, OPERATION [, MASK, IDENTITY, ORDERED ] ) or
REDUCE ( ARRAY, OPERATION DIM [, MASK, IDENTITY, ORDERED ] )

    ARRAY : array of any type;

    OPERATION : pure function with two arguments, each argument being scalar, non-allocatable, non-pointer, non-polymorphic non-optional variables with the same declared type and type parameters as ARRAY; if one argument has the ASYNCHRONOUS, TARGET or VALUE attribute, the other must also have that attribute; the result must be a non-polymorphic scalar variable with the same type and type parameters as ARRAY;

    DIM : scalar Integer in the range 1 to N, where N is the rank of ARRAY;

    MASK : type Logical, and either scalar or an array with the same shape as ARRAY;

    IDENTITY : scalar with the same declared type and type parameters as ARRAY;

    ORDERED : scalar of type Logical;

    Result : Same type and type parameters as ARRAY.

    The result is ARRAY reduced by the user-supplied OPERATION. If DIM is absent, the whole (masked) ARRAY is reduced to a scalar result. If DIM is present, the result has rank N-1 and the shape of ARRAY with dimension DIM removed; each element of the result is the reduction of the masked elements in that dimension.

    If exactly one element contributes to a result value, that value is equal to the element; that is, OPERATION is only invoked when more that one element appears.

    If no elements contribute to a result value, the IDENTITY argument must be present, and that value is equal to IDENTITY.

    For example,

    Module triplet_m
  Type triplet
    Integer i,j,k
  End Type
Contains
  Pure Type(triplet) Function tadd(a,b)
    Type(triplet),Intent(In) :: a,b
    tadd%i = a%i + b%i
    tadd%j = a%j + b%j
    tadd%k = a%k + b%k
  End Function
End Module
Program reduce_example
  Use triplet_m
  Type(triplet) a(2,3)
  a = Reshape( [ triplet(1,2,3),triplet(1,2,4), &
                 triplet(2,2,5),triplet(2,2,6), &
                 triplet(3,2,7),triplet(3,2,8) ], [ 2,3 ] )
  Print 1, Reduce(a,tadd)
  Print 1, Reduce(a,tadd,1)
  Print 1, Reduce(a,tadd,a%i/=2)
  Print 1, Reduce(Array=a,Dim=2,Operation=tadd)
  Print 1, Reduce(a, Mask=a%i/=2, Dim=1, Operation=tadd, Identity=triplet(0,0,0))
1 Format(1x,6('triplet(',I0,',',I0,',',I0,')',:,'; '))
End Program
    This will produce the output:
     triplet(12,12,33)
 triplet(2,4,7); triplet(4,4,11); triplet(6,4,15)
 triplet(8,8,22)
 triplet(6,6,15); triplet(6,6,18)
 triplet(2,4,7); triplet(0,0,0); triplet(6,4,15)
  • [7.0] The intrinsic atomic subroutines ATOMIC_ADD, ATOMIC_AND, ATOMIC_CAS, ATOMIC_FETCH_ADD, ATOMIC_FETCH_AND, ATOMIC_FETCH_OR, ATOMIC_FETCH_XOR, ATOMIC_OR and ATOMIC_XOR are described under Advanced coarray programming.
  • [7.1] The intrinsic collective subroutines CO_BROADCAST, CO_MAX, CO_MIN, CO_REDUCE and CO_SUM are described under Advanced coarray programming.
  • [7.0] The intrinsic functions COSHAPE, EVENT_QUERY, FAILED_IMAGES, GET_TEAM, IMAGE_STATUS, STOPPED_IMAGES, and TEAM_NUMBER, and the changes to the intrinsic functions NUM_IMAGES and THIS_IMAGE, are described under Advanced coarray programming.


NAG Fortran Compiler, Release 7.1: Program units and procedures

 Navigation: Previous Up Next

11.7 Program units and procedures

  • [7.0] If a dummy argument of a function that is part of an OPERATOR generic has the VALUE attribute, it is no longer required to have the INTENT(IN) attribute.

    For example,

           INTERFACE OPERATOR(+)
          MODULE PROCEDURE logplus
       END INTERFACE
       ...
       PURE LOGICAL FUNCTION logplus(a,b)
          LOGICAL,VALUE :: a,b
          logplus = a.OR.b
       END FUNCTION
  • [7.0] If the second argument of a subroutine that is part of an ASSIGNMENT generic has the VALUE attribute, it is no longer required to have the INTENT(IN) attribute.

    For example,

           INTERFACE ASSIGNMENT(=)
          MODULE PROCEDURE asgnli
       END INTERFACE
       ...
       PURE SUBROUTINE asgnli(a,b)
          LOGICAL,INTENT(OUT) :: a
          INTEGER,VALUE :: b
          DO WHILE (IAND(b,NOT(1))/=0)
             b = IEOR(IAND(b,1),SHIFTR(b,1))
          END DO
          a = b/=0 ! Odd number of "1" bits.
       END SUBROUTINE
  • [7.0] With the -recursive or the -f2018 option, procedures are recursive by default. For example, this subprogram
           INTEGER FUNCTION factorial(n) RESULT(r)
          IF (n>1) THEN
             r = n*factorial(n-1)
          ELSE
             r = 1
          END IF
       END FUNCTION
    is valid, just as if it had been explicitly declared with the RECURSIVE keyword.

    This does not apply to assumed-length character functions (where the result is declared with CHARACTER(LEN=*); these remain prohibited from being declared RECURSIVE.

    Note that procedures that are RECURSIVE by default are excluded from the effects of the -save option, exactly as if they were explicitly declared RECURSIVE.

  • [7.0] Elemental procedures may now be recursive, whether explicitly declared RECURSIVE or by default (when the -f2018 or -recursive options are specified). For example,
           ELEMENTAL RECURSIVE INTEGER FUNCTION factorial(n) RESULT(r)
          INTEGER,INTENT(IN) :: n
          IF (n>1) THEN
             r = n*factorial(n-1)
          ELSE
             r = 1
          END IF
       END FUNCTION
    may be invoked with
           PRINT *,factorial( [ 1,2,3,4,5 ] )
    to print the first five factorials.
  • The NON_RECURSIVE keyword explicitly declares that a procedure will not be called recursively. For example,
           NON_RECURSIVE INTEGER FUNCTION factorial(n) RESULT(r)
          r = 1
          DO i=2,n
             r = r*i
          END DO
       END FUNCTION

    In Fortran 2008 and older standards, procedures are non-recursive by default, so this keyword has no effect unless the -recursive or -f2018 is being used.

  • Generic resolution can use the number of procedure arguments; that is, if one procedure has more non-optional procedure arguments than the other has optional plus non-optional procedure arguments, the procedures are considered to be unambiguous.

    For example,

           MODULE npa_example
         INTERFACE g
           MODULE PROCEDURE s1,s2
         END INTERFACE
       CONTAINS
         SUBROUTINE s1(a)
           EXTERNAL a
           CALL a
         END SUBROUTINE
         SUBROUTINE s2(b,a)
           EXTERNAL b,a
           CALL b
           CALL a
         END SUBROUTINE
       END MODULE

    This example does not conform to the Fortran 2008 rules for unambiguous generic procedures, because the argument A distinguishes by position but not by keyword, the argument B distinguish by keyword but not by position, and the positional disambiguator (A) does not appear earlier in the list than the keyword disambiguator (B).


NAG Fortran Compiler, Release 7.1: Advanced C interoperability

 Navigation: Previous Up Next

11.8 Advanced C interoperability

  • [7.0] The C_FUNLOC function from the intrinsic module ISO_C_BINDING accepts a non-interoperable procedure argument. The C_FUNPTR value produced should not be converted to a C function pointer, but may be converted to a suitable (also non-interoperable) Fortran procedure pointer with the C_F_PROCPOINTER subroutine from ISO_C_BINDING. For example,
           USE ISO_C_BINDING
       ABSTRACT INTERFACE
         SUBROUTINE my_callback_interface(arg)
           CLASS(*) arg
         END SUBROUTINE
       END INTERFACE
       TYPE,BIND(C) :: mycallback
         TYPE(C_FUNPTR) :: callback
       END TYPE
       ...
       TYPE(mycallback) cb
       PROCEDURE(my_callback_interface),EXTERNAL :: sub
       cb%callback = C_FUNLOC(sub)
       ...
       PROCEDURE(my_callback_interface),POINTER :: pp
       CALL C_F_PROCPOINTER(cb%callback,pp)
       CALL pp(...)

    This functionality may be useful in a mixed-language program when the C_FUNPTR value is being stored in a data structure that is manipulated by C code.

  • [7.0] The C_LOC function from the intrinsic module ISO_C_BINDING accepts an array of non-interoperable type, and the C_F_POINTER function accepts an array pointer of non-interoperable type. The array must still be non-polymorphic and contiguous.

    This improves interoperability with mixed-language C and Fortran programming, by letting the program pass an opaque “handle” for a non-interoperable array through a C routine or C data structure, and reconstruct the Fortran array pointer later. This kind of usage was previously only possible for scalars.

  • [7.1] Assumed-rank variables are permitted to be dummy arguments of a BIND(C) routine, even those with the ALLOCATABLE or POINTER attribute. An assumed-rank argument is passed by reference as a “C descriptor”; it is then up to the C routine to decode what that means. The C descriptor, along with several utility functions for manipulating it, is defined by the source file ISO_Fortran_binding.h; this can be found in the compiler's library directory (on Linux this is usually /usr/local/lib/NAG_Fortran, but that can be changed at installation time).

    This topic is highly complex, and beyond the scope of this document. The reader should direct their attention to the Fortran 2018 standard, or to a good textbook.

  • [7.1] A TYPE(*) (“assumed type”) dummy argument is permitted in a BIND(C) procedure. It interoperates with a C argument declared as “void *”. There is no difference between scalar and assumed-size on the C side, but on the Fortran side, if the dummy argument is scalar the actual argument must also be scalar, and if the dummy argument is an array, the actual argument must also be an array.

    Because an actual argument can be passed directly to a TYPE(*) dummy, the C_LOC function is not required, and so there is no need for the TARGET attribute on the actual argument.

    For example,

      Program type_star_example
    Interface
      Function checksum(scalar,size) Bind(C)
        Use Iso_C_Binding
        Type(*) scalar
        Integer(C_int),Value :: size
        Integer(C_int) checksum
      End Function
    End Interface
    Type myvec3
      Double Precision v(3)
    End Type
    Type(myvec3) x
    Call Random_Number(x%v)
    Print *,checksum(x,Storage_Size(x)/8)
  End Program
  int checksum(void *a,int n)
  {
    int i;
    int res = 0;
    unsigned char *p = a;
    for (i=0; i<n; i++) res = 0x3fffffff&((res<<1) + p[i]);
    return res;
  }
  • A BIND(C) procedure can have optional arguments. Such arguments cannot also have the VALUE attribute.

    An absent optional argument of a BIND(C) procedure is indicated by passing a null pointer argument.

    For example,

      Program optional_example
    Use Iso_C_Binding
    Interface
      Function f(a,b) Bind(C)
        Import
        Integer(C_int),Intent(In) :: a
        Integer(C_int),Intent(In),Optional :: b
        Integer(C_int) f
      End Function
    End Interface
    Integer(C_int) x,y
    x = f(3,14)
    y = f(23)
    Print *,x,y
  End Program

  int f(int *arg1,int *arg2)
  {
    int res = *arg1;
    if (arg2) res += *arg2;
    return res;
  }
    The second reference to f is missing the optional argument b, so a null pointer will be passed for it. This will result in the output:
     17 23


NAG Fortran Compiler, Release 7.1: Updated IEEE arithmetic capabilities

 Navigation: Previous Up Next

11.9 Updated IEEE arithmetic capabilities

  • [7.0] The module IEEE_ARITHMETIC has new functions IEEE_NEXT_DOWN and IEEE_NEXT_UP. These are elemental with a single argument, which must be a REAL of an IEEE kind (that is, IEEE_SUPPORT_DATATYPE must return .TRUE. for that kind of REAL). They return the next IEEE value, that does not compare equal to the argument, in the downwards and upwards directions respectively, except that the next down from −∞ is −∞ itself, and the next up from +∞ is +∞ itself. These functions are superior to the old IEEE_NEXT_AFTER function in that they do not signal any exception unless the argument is a signalling NaN (in which case IEEE_INVALID is signalled).

    For example, IEEE_NEXT_UP(-0.0) and IEEE_NEXT_UP(+0.0) both return the smallest positive subnormal value (provided subnormal values are supported), without signalling IEEE_UNDERFLOW (which IEEE_NEXT_AFTER does).

    Similarly, IEEE_NEXT_UP(HUGE(0.0)) returns +∞ without signalling overflow.

  • [7.0] The module IEEE_ARITHMETIC has new named constants IEEE_NEGATIVE_SUBNORMAL, IEEE_POSITIVE_SUBNORMAL, and the new function IEEE_SUPPORT_SUBNORMAL. These are from Fortran 2018, and reflect the change of terminology in the IEEE arithmetic standard in 2008. They are equivalent to the old functions IEEE_NEGATIVE_DENORMAL, IEEE_POSITIVE_DENORMAL and IEEE_SUPPORT_DENORMAL.
  • [7.0] The requirement that the FLAG_VALUE argument to IEEE_GET_FLAG and IEEE_SET_FLAG, the HALTING argument to IEEE_GET_HALTING_MODE and IEEE_SET_HALTING_MODE, and the GRADUAL argument to IEEE_GET_UNDERFLOW_MODE and IEEE_SET_UNDERFLOW_MODE, be default LOGICAL has been dropped; any kind of LOGICAL is now permitted.

    For example,

           USE F90_KIND
       USE IEEE_ARITHMETIC
       LOGICAL(byte) flags(SIZE(IEEE_ALL))
       CALL IEEE_GET_FLAG(IEEE_ALL,flags)
    will retrieve the current IEEE flags into an array of one-byte LOGICALs.


NAG Fortran Compiler, Release 7.1: Advanced coarray programming

 Navigation: Previous Up Next

11.10 Advanced coarray programming

  • [7.0] Additional intrinsic atomic subroutines provide a means for multiple images to update atomic variables without synchronisation. These are:

    ATOMIC_ADD | (ATOM,VALUE,STAT)
    ATOMIC_AND | (ATOM,VALUE,STAT)
    ATOMIC_CAS | (ATOM,OLD,COMPARE,NEW,STAT)
    ATOMIC_FETCH_ADD | (ATOM,VALUE,OLD,STAT)
    ATOMIC_FETCH_AND | (ATOM,VALUE,OLD,STAT)
    ATOMIC_FETCH_OR | (ATOM,VALUE,OLD,STAT)
    ATOMIC_FETCH_XOR | (ATOM,VALUE,OLD,STAT)
    ATOMIC_OR | (ATOM,VALUE,STAT)
    ATOMIC_XOR | (ATOM,VALUE,STAT)

    The arguments ATOM, COMPARE, NEW and OLD are all INTEGER(ATOMIC_INT_KIND). The ATOM argument is the one that is updated, and must be a coarray or a coindexed variable. The OLD argument is INTENT(OUT), and receives the value of ATOM before the operation. The STAT argument is optional, and must be a non-coindexed variable of type INTEGER and at least 16 bits in size.

    The VALUE argument must be INTEGER but can be of any kind; however, both VALUE and the result of the operation must be representable in INTEGER(ATOMIC_INT_KIND).

    The *_ADD operation is addition, the *_AND operation is bitwise and (like IAND), the *_OR operation is bitwise or (like IOR) and the *_XOR operation is bitwise exclusive or (like IEOR).

    ATOMIC_CAS is an atomic compare-and-swap operation. If ATOM is equal to COMPARE, it is assigned the value NEW; otherwise, it remains unchanged. In either case, the value before the operation is assigned to OLD. Note that both COMPARE and NEW must also be INTEGER(ATOMIC_INT_KIND).

    If the ATOM is a coindexed variable, and is located on a failed image, the operation fails and an error condition is raised; the OLD argument becomes undefined, and if STAT is present, it is assigned the value STAT_FAILED_IMAGE; if STAT is not present, the program is terminated. If no error occurs and STAT is present, it is assigned the value zero.

  • [7.0] The intrinsic function COSHAPE returns a vector of the co-extents of a coarray; its syntax is as follows.

    COSHAPE( COARRAY [, KIND ] )

    COARRAY : coarray of any type; if it is ALLOCATABLE, it must be allocated; if it is a structure component, the rightmost component must be a coarray component;

    KIND (optional) : scalar Integer constant expression that is a valid Integer kind number;

    Result : vector of type Integer, or Integer(KIND)} if KIND is present; the size of the result is equal to the co-rank of COARRAY.

    For example, if a coarray is declared

    REAL x[5,*]

    and there are eight images in the current team, COSHAPE(x) will be equal to [ 5,2 ].
  • [7.0] The intrinsic elemental function IMAGE_STATUS enquires whether another image has stopped or failed; its syntax is as follows.

    IMAGE_STATUS( IMAGE [, TEAM ] )

    IMAGE : positive integer that is a valid image number;

    TEAM (optional) : scalar TEAM_TYPE value that identifies the current or an ancestor team;

    Result : default Integer.

    The value of the result is STAT_FAILED_IMAGE if the image has failed, STAT_STOPPED_IMAGE if the image has stopped, and zero otherwise. The optional TEAM argument specifies which team the image number applies to; if it is not specified, the current team is used.

  • [7.0] The intrinsic function STOPPED_IMAGES returns an array listing the images that have initiated normal termination (i.e. “stopped”); its syntax is as follows.

    STOPPED_IMAGES( [ TEAM, KIND ] )

    TEAM (optional) : scalar TEAM_TYPE value that identifies the current or an ancestor team;

    KIND (optional) : scalar INTEGER constant expression that is a valid Integer kind number;

    Result : vector of type Integer, or Integer(KIND) if KIND is present.

    The elements of the result are the stopped image numbers in ascending order.

  • [7.0] The type EVENT_TYPE in the intrinsic module ISO_FORTRAN_ENV, along with new statements and the intrinsic function EVENT_QUERY, provides support for events, a lightweight one-sided synchronisation mechanism.

    Like type LOCK_TYPE, entities of type EVENT_TYPE are required to be variables or components, variables of type EVENT_TYPE are required to be coarrays, and variables with noncoarray subcomponents of type LOCK_TYPE are required to be coarrays. Such variables are called event variables. An event variable is not permitted to appear in a variable definition context (i.e. any context where it might be modified), except in an EVENT POST or EVENT WAIT statement, or as an actual argument where the dummy argument is INTENT(INOUT).

    An event variable on an image may have an event “posted” to it by means of the image control statement EVENT POST, which has the form

           EVENT POST ( event-variable [, sync-stat ]... )
    where the optional sync-stats may be a single STAT=stat-variable specifier and/or a single ERRSMG=errmsg-variable specifier; stat-variable must be a scalar integer variable that can hold values up to 9999, and errmsg-variable must be a scalar default character variable. Posting an event increments the variable's “outstanding event count” (this count is initially zero). The event-variable in this statement will usually be a coindexed variable, as it is rarely useful for an image to post an event to itself.

    If STAT= appears and the post is successful, zero is assigned to the stat-variable. If the image on which the event-variable is located has stopped, STAT_STOPPED_IMAGE is assigned to the stat-variable; if the image has failed, STAT_FAILED_IMAGE is assigned, and if any other error occurs, some other positive value is assigned. If ERRMSG= appears and any error occurs, an explanatory message is assigned to the errmsg-variable. Note that if STAT= does not appear and an error occurs, the program will be error-terminated, so having ERRMSG= without STAT= is useless.

    Events are received by the image control statement EVENT WAIT, which has the form

           EVENT WAIT ( event-variable [, event-wait-spec-list ] )
    where the optional event-wait-spec-list is a comma-separated list that may contain a single STAT=stat-variable specifier, a single ERRSMG=errmsg-variable specifier, and/or a single UNTIL_COUNT=scalar-integer-expr specifier. Waiting on an event waits until its “outstanding event count” is greater than or equal to the UNTIL_COUNT= specifier value, or greater than zero if UNTIL_COUNT= does not appear. If the value specified in UNTIL_COUNT= is less than one, it is treated as if it were equal to one.

    The event-variable in this statement is not permitted to be coindexed; that is, an image can only wait for events posted to its own event variables. There is a partial synchronisation between the waiting image and the images that contributed to the “outstanding event count”; the segment following execution of the EVENT WAIT statement follows the segments before the EVENT POST statement executions. The synchronisation does not operate in reverse, that is, there is no implication that execution of any segment in a posting image follows any segment in the waiting image.

    The STAT= and ERRMSG= operate similarly to the EVENT POST statement, except of course that STAT_FAILED_IMAGE and STAT_STOPPED_IMAGE are impossible.

    Finally, the intrinsic function EVENT_QUERY can be used to interrogate an event variable without waiting for it. It has the form

           EVENT_QUERY ( EVENT, COUNT [, STAT ] )
    where EVENT is an event variable, COUNT is an integer variable at least as big as default integer, and the optional STAT is an integer variable that can hold values up to 9999. EVENT is not permitted to be a coindexed variable; that is, only the image where the event variable is located is permitted to query its count. COUNT is assigned the current “outstanding event count” of the event variable. If STAT is present, it is assigned the value zero on successful execution, and a positive value if any error occurs. If any error occurs and STAT is not present, the program is error-terminated.

    Note that event posts in unordered segments might not be included in the value assigned to count; that is, it might take some (communication) time for an event post to reach the variable, and it is only guaranteed to have reached the variable if the images have already synchronised. Use of EVENT_QUERY does not by itself imply any synchronisation.

  • [7.0] The type TEAM_TYPE in the intrinsic module ISO_FORTRAN_ENV, along with new statements and intrinsic procedures, provides support for teams, a new method of structuring coarray parallel computation. The basic idea is that while executing inside a team, the coarray environment acts as if only the images in the team exist. This facilitates splitting coarray computations into independent parts, without the hassle of passing around arrays listing the images that are involved in a particular part of the computation.

    Unlike EVENT_TYPE and LOCK_TYPE, functions that return TEAM_TYPE are permitted. Furthermore, a variable of type TEAM_TYPE is forbidden from being a coarray, and assigning a TEAM_TYPE value from another image (e.g. as a component of a derived type assignment) makes the variable undefined; this is because the TEAM_TYPE value might contain information specific to a particular image, e.g. routing information to the other images. Variables of type TEAM_TYPE are called team variables.

    Creating teams The set of all the images in the program is called the initial team. At any time, a particular image will be executing in a particular team, the current team. A set of subteams of the current team can be created at any time by using the FORM TEAM statement, which has the form
           FORM TEAM ( team-number , team-variable [, form-team-spec ]... )
    where team-number is a scalar integer expression that evaluates to a positive value, team-variable is a team variable, and each form-team-spec is STAT=, ERRMSG=, and NEW_INDEX=index-value specifier. At most one of each kind of form-team-spec may appear in a FORM TEAM statement. All active images of the current team must execute the same FORM TEAM statement. If NEW_INDEX= appears, index-value must be a positive scalar integer (see below). The STAT= and ERRMSG= specifiers have their usual form and semantics.

    The number of subteams that execution of FORM TEAM produces is equal to the number of unique team-number values in that execution; each unique team-number value identifies a subteam in the set, and each image belongs to the subteam whose team number it specified. If NEW_INDEX= appears, it specifies the image number that the image will have in its new subteam, and therefore must be in the range 1 to N, where N is the number of images in that subteam, and must be unique. If NEW_INDEX= does not appear, it is processor-dependent what the image number in the new subteam will be.

    For example,

           TYPE(TEAM_TYPE) oddeven
       myteamnumber = 111*(MOD(THIS_IMAGE(),2) + 1)
       FORM TEAM ( myteamnumber, oddeven )
    will create a set of two subteams, one with team number 111, the other with team number 222. Team 111 will contain the images with even image numbers in the current team, and team 222 will contain the images with odd image numbers in the current team. On each image, the variable oddeven identifies the subteam to which that image belongs.

    Note that the team numbers are completely arbitrary (being chosen by the program), and only have meaning within that set of subteams, which are called “sibling” teams.

    Changing to a subteam The current team is changed by executing a CHANGE TEAM construct, which has the basic form:
           CHANGE TEAM ( team-value [, sync-stat-list ] )
         statements
       END TEAM [ ( [  sync-stat-list  ] ) ]
    where team-value is a value of type TEAM_TYPE, and the optional sync-stat-list is a comma-separated list containing at most one STAT= and ERRMSG= specifier; the STAT= and ERRMSG= specifiers have their usual form and semantics. Execution of the statements within the construct are with the current team set to the team identified by team-value; this must be a subteam of the current team outside the construct. The setting of the current team remains in effect during procedure calls, so any procedure referenced by the construct will also be executed with the new team current.

    Transfer of control out of the construct, e.g. by a RETURN or GOTO statement is prohibited. The construct may be exited by executing its END TEAM statement, or by executing an EXIT statement that belongs to the construct; the latter is only possible if the construct is given a name (this is not shown in the form above, but consists of “construct-name:” prefix to the CHANGE TEAM statement, and and a “construct-name” suffix to the END TEAM statement).

    While executing a CHANGE TEAM construct, image selectors operate using the new team's image indices, the intrinsic functions NUM_IMAGES and THIS_IMAGES return the data for the new team, and SYNC ALL synchronises the new team only.

    There is an implicit synchronisation of all images of the new team both on the CHANGE TEAM statement, and on the END TEAM statement, and all active images must execute the same statement at this time.

    Synchronising parent or ancestor teams While executing within a CHANGE TEAM construct, the effects of SYNC ALL and SYNC IMAGES only apply to images within the current team. For SYNC ALL to synchronise the parent team, it would be necessary to first exit the construct. This may be inconvenient when the computation following the synchronisation would be within the team.

    For this purpose, the SYNC TEAM statement has been added, with the form

           SYNC TEAM ( team-value [, sync-stat-list ] )
    where team-value identifies the current team or an ancestor thereof, and sync-stat-list is the usual comma-separated list containing at most one STAT= specifier and at most one ERRMSG= specifier (these have their usual semantics and so are not further described here).

    The effect is to synchronise all images in the specified team.

    Team-related intrinsic functions
    • The intrinsic function GET_TEAM returns a value of type TEAM_TYPE that identifies a particular team. (This is the only way to get a TEAM_TYPE value for the initial team.) The function has the form
             GET_TEAM( [ LEVEL ] )
      where the optional LEVEL argument is a scalar integer value that is equal to one of the named constants CURRENT_TEAM, INITIAL_TEAM or PARENT_TEAM, in the intrinsic module ISO_FORTRAN_ENV. This argument specifies which team the returned TEAM_TYPE value should identify; if it is absent, the value for the current team is returned. If the current team is the initial team, the LEVEL argument must not be equal to PARENT_TEAM, as the initial team has no parent.
    • The intrinsic function TEAM_NUMBER returns a team number value (that was used in FORM TEAM by the executing image). It has the form
             TEAM_NUMBER( [ TEAM ] )
      where the optional TEAM argument specifies which team to return the information for; it must identify the current team or an ancestor team, not a subteam or unrelated team. If TEAM is absent, the team number for the current team is returned. The initial team is considered to have a team number of −1 (except for the initial team, all team numbers are positive values).
    Information about sibling and ancestor teams The intrinsic functions NUM_IMAGES and THIS_IMAGE normally return information relevant to the current team, but they can return information for an ancestor team by using the optional TEAM argument, which takes a TEAM_TYPE value that identifies the current team or an ancestor. Similarly, the NUM_IMAGES intrinsic can return information for a sibling team by using the optional TEAM_NUMBER argument, which takes an integer value that is equal to the team number of the current or a sibling team. (Note that because the executing image is never a member of a sibling team, THIS_IMAGE does not accept a TEAM_NUMBER argument.) The intrinsic function NUM_IMAGES thus has two additional forms as follows:
           NUM_IMAGES( TEAM )
       NUM_IMAGES( TEAM_NUMBER )

    For THIS_IMAGE, the revised forms it may take are as follows:

           THIS_IMAGE( [ TEAM ] )
       THIS_IMAGE( COARRAY [, TEAM ] )
       THIS_IMAGE( COARRAY, DIM [, TEAM ] )
    The meanings of the COARRAY and DIM arguments is unchanged. The optional TEAM argument specifies the team for which to return the information.
    Establishing coarrays A coarray is not allowed to be used within a team unless it is established in that team or an ancestor thereof. The basic rules for establishment are as follows:
    1. a nonallocatable coarray with the SAVE attribute (explicit or implicit) is always established;
    2. an unallocated coarray (with the ALLOCATABLE attribute) is not established;
    3. an allocated coarray is established in the team where it was allocated;
    4. a dummy coarray is established in the team that executed the procedure call (this may be different from the team where the actual argument is established).
    Allocating and deallocating coarrays in teams If a coarray with the ALLOCATABLE attribute is already allocated when a CHANGE TEAM statement is executed, it is not allowed to DEALLOCATE it within that construct (or within a procedure called from that construct).

    If a coarray with the ALLOCATABLE attribute is unallocated when a CHANGE TEAM statement is executed, it may be allocated (using ALLOCATE) within that construct (or within a procedure called from that construct), and may be subsequently deallocated as well. If such a coarray remains allocated when the END TEAM statement is executed, it is automatically deallocated at that time.

    This means that when using teams, allocatable coarrays may be allocated on some images (within the team), but unallocated on other images (outside the team), or allocated with a different shape or type parameters on other images (also outside the team). However, when executing in a team, the coarray is either unallocated on all images of the team, or allocated with the same type parameters and shape on all images of the team.

    Accessing coarrays in sibling teams Access to a coarray outside the current team, but in a sibling team, is possible using the TEAM_NUMBER= specifier in an image selector. This uses the extended syntax for image selectors:
           [ cosubscript-list [, image-selector-spec-list ] ]
    where cosubscript-list is the usual list of cosubscripts, and image-selector-spec-list contains a TEAM_NUMBER=team-number specifier, where team-number is the positive integer value that identifies a sibling team. The image-selector-spec-list may also contain a STAT= specifier (this is described later, under Fault tolerance).

    When the TEAM_NUMBER= specifier is used the cosubscripts are treated as cosubscripts in the sibling team. Note that access in this way is quite risky, and will typically require synchronisation, possibly of the whole parent team. The coarray in question must be established in the parent team.

    Accessing coarrays in ancestor teams Access to a coarray in the parent or more distant ancestor team is possible using the TEAM= specifier in an image selector. This uses the extended syntax for image selectors:
           [ cosubscript-list [, image-selector-spec-list ] ]
    where cosubscript-list is the usual list of cosubscripts, and image-selector-spec-list contains a TEAM=team-value specifier, where team-value is a value of type TEAM_TYPE that identifies the current team or an ancestor. The image-selector-spec-list may also contain a STAT= specifier (this is described later, under Fault tolerance).

    When the TEAM= specifier is used the cosubscripts are treated as cosubscripts in the specified ancestor team, and the image thus specified may lie within or outside the current team. If the access is to an image that is outside the current team, care should be taken that the images are appropriately synchronised; such synchronisation cannot be obtained by SYNC ALL or SYNC IMAGES, as they operate within a team, but may be obtained by SYNC TEAM specifying an ancestor team, or by using locks or events. The coarray in question must be established in the specified (current or ancestor) team.

    Coarray association in CHANGE TEAM It is possible to associate a local coarray-name in a CHANGE TEAM construct with a named coarray outside the construct, changing the codimension and/or coextents in the process. This acts like a limited kind of argument association; the local coarray-name has the type, parameters, rank and array shape of the outside coarray, but does not have the ALLOCATABLE attribute. The syntax of the CHANGE TEAM construct with one or more such associations is as follows:
           CHANGE TEAM ( team-value , coarray-association-list [, sync-stat-list ] )
    where coarray-association-list is a comma-separated list of
           local-coarray-name [ explicit-coshape-spec ] => outer-coarray-name
    and explicit-coshape-spec is
           [ [ lower-cobound : ] upper-cobound , ]... [ lower-cobound : ] *
    (The notation [ something ]... means something occurring zero or more times.)

    The cobounds expressions are evaluated on execution of the CHANGE TEAM statement.

    Use of this feature is not encouraged, as it is less powerful and more confusing than argument association.

  • [7.0] Fault tolerance features for coarrays are supported. These consist of the FAIL IMAGE statement, the named constant STAT_FAILED_IMAGE in the intrinsic module ISO_FORTRAN_ENV, the STAT= specifier in an image selector, and the intrinsic function FAILED_IMAGES.

    The form of the FAIL IMAGE statement is simply

           FAIL IMAGE
    and execution of this statement will cause the current image to “fail”, that is, cease to participate in program execution. This is the only way that an image can fail in NAG Fortran 7.0.

    If all images have failed or stopped, program execution will terminate. NAG Fortran will display a warning message if any images have failed.

    An image selector has an optional list of specifiers, the revised syntax of an image selector being (where the normal square brackets are literally square brackets, and the italic square brackets indicate optionality):

           [ cosubscript-list [, image-selector-spec-list ] ]
    where cosubscript-list is a comma-separated list of cosubscripts, one scalar integer per codimension of the variable, and image-selector-spec-list is a comma-separated containing at most one STAT=stat-variable specifier, and at most one TEAM= or TEAM_NUMBER= specifier (these were described earlier). If the coindexed object being accessed lies on a failed image, the value STAT_FAILED_IMAGE is assigned to the stat-variable, and otherwise the value zero is assigned.

    The intrinsic function FAILED_IMAGES returns an array of images that are known to have failed (it is possible that an image might fail and no other image realise until it tries to synchronise with it). Its syntax is as follows.

    FAILED_IMAGES( [ TEAM, KIND ] )

    TEAM (optional) : scalar TEAM_TYPE value that identifies the current or an ancestor team;

    KIND (optional) : scalar Integer constant expression that is a valid Integer kind number;

    Result : vector of type Integer, or Integer(KIND) if KIND is present.

    The elements of the result are the failed image numbers in ascending order.

    In order to be able to handle failed images, the following semantics apply:

    • writing a value to a variable on a failed image is permitted (but may have no effect);
    • reading a value from a variable on a failed image is permitted, but the result is unpredictable;
    • execution of a CHANGE TEAM, END TEAM, FORM TEAM, SYNC ALL, SYNC IMAGES or SYNC TEAM statement with a STAT= specifier is permitted, and performs the team change, creation, or synchronisation operation on the non-failed images, assigning the value STAT_FAILED_IMAGE to the STAT= variable.
    The latter effect in particular allows the program to form a team of all the non-failed images, and keep executing normally. However, since the data on the failed images is lost (reading the data produces garbage), the program would need to be carefully designed to “checkpoint” its work periodically, so that it can roll the computation state back to a known good value to recover.

    The fault tolerance features are in principle intended to permit recovery from hardware failure, with the FAIL IMAGE statement allowing some testing of recovery scenarios. The NAG Fortran Compiler does not support recovery from hardware failure (at Release 7.1).

  • [7.1] The intrinsic subroutines CO_BROADCAST, CO_MAX, CO_MIN, CO_REDUCE and CO_SUM perform collective operations. These are for coarray parallelism: they compute values across all images in the current team, without explicit synchronisation.

    All of these subroutines have optional STAT and ERRMSG arguments. On successful execution, the STAT argument is assigned the value zero and the ERRMSG argument is left unchanged. If an error occurs, a positive value is assigned to STAT and an explanatory message is assigned to ERRMSG. Only the errors STAT_FAILED_IMAGE and STAT_STOPPED_IMAGE are likely to be able to be caught in this way. Because there is not full synchronisation (see below), different images may receive different errors, or none at all. If an error occurs and STAT is not present, execution is terminated. Note that if the actual arguments for STAT or ERRMSG are optional dummy arguments, they must be present on all images or absent on all images.

    A reference (CALL) to one of these subroutines is not an image control statement, does not end the current segment, and does not imply synchronisation (though some partial synchronisation will occur during the computation). However, such calls are only permitted where an image control statement is permitted.

    Each image in a team must execute the same sequence of CALL statements to collective subroutines as the other images in the team. There must be no synchronisation between the images at the time of the call; the invocations must come from unordered segments.

    All collective subroutines have the first argument “A”, which is INTENT(INOUT), and must not be a coindexed object. This argument contains the data for the calculation, and must have the same type, type parameters, and shape on all images in the current team. If it is a coarray that is a dummy argument, it must have the same ultimate argument on all images.

    SUBROUTINE CO_BROADCAST ( A, SOURCE_IMAGE [, STAT, ERRMSG ] )

    A : variable of any type; it must not be a coindexed object, and must have the same type, type parameters and shape on all images in the current team; if A is a coarray that is a dummy argument, it must have the same ultimate argument on each image;

    SOURCE_IMAGE : integer scalar, in the range one to NUM_IMAGES(), this argument must have the same value on all images in the current team;

    STAT (optional) : integer scalar variable, not coindexed;

    ERRMSG (optional) : character scalar variable of default kind, not coindexed.

    The value of argument A on image SOURCE_IMAGE is assigned to the argument A on all the other images.

    SUBROUTINE CO_MAX ( A [, RESULT_IMAGE, STAT, ERRMSG ] )

    A: variable of type Integer, Real, or Character; it must not be a coindexed object, and must have the same type, type parameters and shape on all images in the current team; if A is a coarray that is a dummy argument, it must have the same ultimate argument on each image;

    RESULT_IMAGE (optional) : integer scalar, in the range one to NUM_IMAGES(), this argument must be either present on all images or absent on all images; if present, it must have the same value on all images in the current team;

    STAT (optional) : integer scalar variable, not coindexed;

    ERRMSG (optional) : character scalar variable of default kind, not coindexed.

    This subroutine computes the maximum value of A across all images; if A is an array, the value is computed elementally. If RESULT_IMAGE is present, the result is assigned to argument A on that image, otherwise it is assigned to argument A on all images.

    SUBROUTINE CO_MIN ( A [, RESULT_IMAGE, STAT, ERRMSG ] )

    A: variable of type Integer, Real, or Character; it must not be a coindexed object, and must have the same type, type parameters and shape on all images in the current team; if A is a coarray that is a dummy argument, it must have the same ultimate argument on each image;

    RESULT_IMAGE (optional) : integer scalar, in the range one to NUM_IMAGES(), this argument must be either present on all images or absent on all images; if present, it must have the same value on all images in the current team;

    STAT (optional) : integer scalar variable, not coindexed;

    ERRMSG (optional) : character scalar variable of default kind, not coindexed.

    This subroutine computes the minimum value of A across all images; if A is an array, the value is computed elementally. If RESULT_IMAGE is present, the result is assigned to argument A on that image, otherwise it is assigned to argument A on all images.

    SUBROUTINE CO_REDUCE ( A, OPERATION [, RESULT_IMAGE, STAT, ERRMSG ] )

    A: non-polymorphic variable of any type; it must not be a coindexed object, and must have the same type, type parameters and shape on all images in the current team; if A is a coarray that is a dummy argument, it must have the same ultimate argument on each image;

    OPERATION : pure function with exactly two arguments; the dummy arguments of OPERATION must be non-allocatable, non-optional, non-pointer, non-polymorphic dummy variables, and each argument and the result of the function must be scalar with the same type and type parameters as A;

    RESULT_IMAGE (optional) : integer scalar, in the range one to NUM_IMAGES(), this argument must be either present on all images or absent on all images; if present, it must have the same value on all images in the current team;

    STAT (optional) : integer scalar variable, not coindexed;

    ERRMSG (optional) : character scalar variable of default kind, not coindexed.

    This subroutine computes an arbitrary reduction of A across all images; if A is an array, the value is computed elementally. The reduction is computed starting with the set of corresponding values of A on all images; this is an iterative process, taking two values from the set and converting them to a single value by applying the OPERATION function; the process continues until the set contains only a single value — that value is the result. If RESULT_IMAGE is present, the result is assigned to argument A on that image, otherwise it is assigned to argument A on all images.

    SUBROUTINE CO_SUM ( A [, RESULT_IMAGE, STAT, ERRMSG ] )

    A: variable of type Integer, Real, or Complex; it must not be a coindexed object, and must have the same type, type parameters and shape on all images in the current team; if A is a coarray that is a dummy argument, it must have the same ultimate argument on each image;

    RESULT_IMAGE (optional) : integer scalar, in the range one to NUM_IMAGES(), this argument must be either present on all images or absent on all images; if present, it must have the same value on all images in the current team;

    STAT (optional) : integer scalar variable, not coindexed;

    ERRMSG (optional) : character scalar variable of default kind, not coindexed.

    This subroutine computes the sum of A across all images; if A is an array, the value is computed elementally. If RESULT_IMAGE is present, the result is assigned to argument A on that image, otherwise it is assigned to argument A on all images.


NAG Fortran Compiler, Release 7.1: Appendices

 Navigation: Previous Up Next

12 Appendices

  • 12.1 Mixing Fortran and C
    • 12.1.1 Naming Conventions
    • 12.1.2 Initialisation and Termination
    • 12.1.3 Calling Conventions
    • 12.1.4 Data Types
    • 12.1.5 SUBROUTINE return types
    • 12.1.6 FUNCTION return types
    • 12.1.7 Argument types
  • 12.2 ASCII Collating Sequence
    • 12.2.1 Printing Characters
    • 12.2.2 Non-printing Characters


NAG Fortran Compiler, Release 7.1: Mixing Fortran and C

 Navigation: Previous Up Next

12.1 Mixing Fortran and C

When mixing Fortran source code with C source code, without using the C interoperability features of Fortran 2003, the following points should be noted.

12.1.1 Naming Conventions

External procedure names and common block names are in lower case with an underscore appended (this is the same as the standard UNIX f77). The main program-unit is called ‘main’.

Module variables and module procedure names are formed by taking the module name (in lower case), appending ‘_MP_’ and then appending the entity's name (in lower case).

These conventions differ when the -compatible option is used. On Windows this causes external procedures and common blocks to be in upper case with no trailing underscore, while module entities have the module name in upper case instead of lower case (64-bit Windows is always -compatible). On most other platforms this option adds an extra underscore (after the one that is always added) for names that already had an underscore.

12.1.2 Initialisation and Termination

If the main program is not written in Fortran then either the initialisation routine
    __NAGf90_rts_init(int argc,char*argv[])
or the i/o initialisation routine
    __NAGf90_io_init(void)
should be called from C. The __NAGf90_rts_init routine initialises the Fortran floating-point environment as well as allowing command-line arguments to be accessed via the Fortran 2003 intrinsic functions and also via the F90_UNIX module. Additionally, the program should be terminated with __NAGf90_finish(int status), or alternatively __NAGf90_io_finish(void) may be called before the usual C termination routine to close all Fortran files and flush the Fortran i/o buffers (failing to do this might corrupt an output file that is still open).

12.1.3 Calling Conventions

The following sections describe in detail the calling conventions used by Fortran programs compiled with the NAG Fortran Compiler in C terms. This information is thus mostly useful to those wishing to mix Fortran and C code.

The conventions used for the Fortran 77 subset of Modern Fortran are compatible with the de facto UNIX f77 conventions (except for COMPLEX functions compiled without the -compatible option).

12.1.4 Data Types

Definitions of data types useful in communicating from C to Fortran are in the files dope.h and nagfortran.h, which are located in the compiler library directory (usually /usr/local/lib/NAG_Fortran on UNIX-like systems).

Fortran Data Type | Fortran Precision | C typedef name
INTEGER | 8 bits | Integer1
 | 16 bits | Integer2
 | 32 bits | Integer or Integer3
 | 64 bits | Integer4
LOGICAL | 8 bits | Logical1
 | 16 bits | Logical2
 | 32 bits | Logical
 | 64 bits | Logical4
REAL | half | __NAGf90_HReal
 | single | Real
 | double | Double
 | double-double | DDReal
 | quadruple | QReal
COMPLEX | half | __NAGf90_HComplex
 | single | Complex
 | double | DComplex
 | double-double | DDComplex
 | quadruple | QComplex

Note that DDReal and QReal are the same on most systems; on Sun Solaris these are different (the latter being an IEEE-conformant 128-bit floating-point type).

12.1.4.1 Pointers

Scalar non-polymorphic non-CHARACTER POINTER types are simply C pointers to the object.

An array POINTER is a dope vector describing the array pointed to. Unlike a simple address, these dope vectors are capable of directly describing non-contiguous array sections of contiguous arrays. See below (Dope N and ChDope N) for further details. Polymorphic dope vectors are NPDope N except for CLASS(*) pointers which are CSDope N.

12.1.4.2 Derived types

Fortran derived types are translated into C structs. If BIND(C) or SEQUENCE is used, the order of the items within the struct is the same as the order within the derived type definition. Otherwise, the order of items is permuted to put larger types at the front of the struct so as to improve alignment and reduce storage; the C output code can be inspected to determine the ordering used.

12.1.4.3 Supporting types

Char
unsigned char
Data type for default (single-byte) character storage.
Char2
unsigned short
Data type for 16-bit (JIS and UCS-2) character storage.
Char4
unsigned int
Data type for 32-bit (UCS-4) character storage.
Substring
struct { Char *addr; Chrlen len;}
Describes a single-byte (default) CHARACTER string; used for deferred-length default CHARACTER variables and as the return type of variable-length scalar non-POINTER default CHARACTER functions and all POINTER default CHARACTER functions.
Substring2
struct { Char2 *addr; Chrlen len;}
Describes a 16-bit (JIS or UCS-2) CHARACTER string; used for deferred-length 16-bit CHARACTER variables and as the return type of variable-length scalar non-POINTER 16-bit CHARACTER functions and all POINTER 16-bit CHARACTER functions.
Substring4
struct { Char4 *addr; Chrlen len;}
Describes a 32-bit ISO_10646 (UCS-4) CHARACTER string; used for deferred-length 32-bit CHARACTER variables and as the return type of variable-length scalar non-POINTER UCS-4 CHARACTER functions and all POINTER UCS-4 CHARACTER functions.
Offset
int, long or long long
An integer type for addressing and subscript calculations; this is int (32-bit) on 32-bit systems and small model 64-bit systems, and a 64-bit integer type on large model 64-bit systems.
Chrlen
usually int, or long long on 64-bit Windows.
An integer type for representing character length.
Pointer
usually char *.
A byte pointer used to refer to any type and for pointer arithmetic.
Triplet
struct { Offset extent,mult,lower;}
Contains the parameters of an array dimension. extent is the size of that dimension, mult is the stride (i.e., the distance between successive elements in bytes) and lower is the lower bound. It is a component of the Dope N and ChDope N structs.
Dope N
struct { Pointer addr; Offset offset; Triplet dim[N];}
Dope vectors for all non-polymorphic non-CHARACTER arrays (including arrays of derived type). N is the rank and is from 1 to 7. addr is the address of the first element, dim describes each dimension and offset is the offset to add to the subscript calculation, i.e., SUM(mult*lower). This is used as the return type for POINTER array functions; a pointer to it is used as the argument type for assumed-shape and POINTER array arguments.

An array pointer which has been nullified has an addr field which is a null pointer; note that zero-sized arrays have an addr field which is not a null pointer.

ChDope N
struct { Pointer addr; Chrlen len; Offset offset; Triplet dim[N];}
These are exactly the same as the Dope N structs with the addition of the len component which specifies the CHARACTER length.
ArrayTemp_type
struct { type *addr; Offset extent[7];}
Describes a contiguous array of type, which is one of: Integer1, Integer2, Integer, Integer4, Logical1, Logical2, Logical, Logical4, Real, Double, QReal, Complex, DComplex or QComplex. It is used as the return type for non-POINTER array functions. Note that extent values after the rank of the array being described are undefined.
ArrayTemp_Character
struct { Char *addr; Chrlen len; Offset extent[7];}
Describes a contiguous CHARACTER array; it is the same as the other array types with the addition of the len component for the CHARACTER length.
ArrayTemp_Derived
synonym for ArrayTemp_Character.
Describes a contiguous array of any derived type. The len field in this case is the size of the derived type array element.

12.1.5 SUBROUTINE return types

12.1.5.1 SUBROUTINEs with label arguments

The return type is int; its value is the index of the label to which control is to be transferred (1 for the first label, etc.). Zero or an out-of-range value indicates no control transfer is to take place.

12.1.5.2 SUBROUTINEs with no label arguments

Return type is void.

12.1.6 FUNCTION return types

12.1.6.1 Scalar

  1. INTEGER, LOGICAL and REAL.
    The intrinsic type as listed above.
  2. COMPLEX, -compatible option not used, and not Windows 64-bit mode.
    Complex or DComplex according to the precision.
  3. COMPLEX, -compatible option used, or Windows 64-bit mode.
    Return type is void. The address of a temporary of type Complex or DComplex is passed as the initial argument of the function (the result is written to this location).
  4. CHARACTER with fixed or assumed length.
    Return type is void. Two additional initial arguments are passed to the function, the first (Char*, Char2* or Char4*) being the address to which the result is to be written and the second (Chrlen) being the length of the result (in case the called function is of assumed length).
  5. CHARACTER with variable length.
    Return type is Substring, Substring2 or Substring4 (described above). The called function allocates the storage for the string being returned; it is the caller's responsibility to deallocate it when it is no longer required.
  6. Derived type.
    The derived-type struct.

12.1.6.2 Scalar POINTER functions

Note that with all POINTER-valued functions the storage to which the result points may have been allocated within the called function or the result may point to pre-existing storage.
  1. INTEGER, LOGICAL, REAL and COMPLEX.
    A pointer to the appropriate intrinsic type (e.g., Complex*).
  2. CHARACTER
    Return type is Substring, Substring2 or Substring4.
  3. Derived type.
    A pointer to the derived-type struct.

12.1.6.3 Array non-POINTER functions

  1. Intrinsic types.
    The appropriate ArrayTemp_ struct for the intrinsic type, as described above.
  2. Derived types.
    ArrayTemp_Derived is returned with the len component set to the size of the derived-type struct.

12.1.6.4 Array POINTER functions

  1. CLASS(*)
    CSDope1, CSDope2, ... or CSDope7, depending on the rank of the array.
  2. CLASS(derived-type-name) NPDope1, NPDope2, ... or NPDope7, depending on the rank of the array.
  3. Non-polymorphic non-CHARACTER type.
    Dope1, Dope2, ... or Dope7, depending on the rank of the array.
  4. CHARACTER.
    ChDope1, ChDope2, ... or ChDope7, depending on the rank of the array.

Note that non-polymorphic derived-type arrays are returned as Dope N structs.

12.1.7 Argument types

12.1.7.1 CHARACTER type

All normal arguments of CHARACTER type, whether default CHARACTER or multi-byte CHARACTER, have an additional Chrlen argument being the length of the CHARACTER entity; this additional argument is passed at the end of the argument list after all the normal arguments. When there are several CHARACTER arguments their lengths are passed in order from left to right.

This is except on 32-bit Windows when the -compatible option is specified, the additional argument immediately follows the CHARACTER argument.

The other exception to this rule is for assumed-shape CHARACTER arrays; in this case the length of the dummy argument is taken directly from the field in the dope vector and is not passed separately.

12.1.7.2 non-POINTER non-ALLOCATABLE Scalar

  1. non-CHARACTER type.
    The address of the argument is passed (e.g., Integer* for an INTEGER argument).
  2. CHARACTER.
    The address of the argument is passed, and additionally the length of the argument is passed as a separate Chrlen argument at the end of the argument list.

12.1.7.3 POINTER and ALLOCATABLE Scalar

These are passed exactly the same as the normal case except that the address of the pointer (or allocatable descriptor) is passed (e.g., Integer** for an INTEGER POINTER).

12.1.7.4 non-POINTER Array

  1. Assumed shape.
    The address of an appropriate dope vector describing the array is passed (i.e., a CSDope N*, NPDope N*, Dope N* or a ChDope N*, depending on the polymorphism and type of the dummy argument). There is no need for the array to be contiguous as long as it can be described by an array section.
  2. Other.
    The address of the first element of the array is passed. For CHARACTER arrays the length of each array element is passed as an Chrlen at the end of the argument list, the same as for scalars. The array must be contiguous.

12.1.7.5 POINTER Array

The address of an appropriate dope vector is passed, the same as for assumed-shape arrays. For CHARACTER arrays the length is passed at the end as a separate argument.

12.1.7.6 Procedures

The address of the procedure is passed. CHARACTER functions have the length passed as a separate argument at the end of the list; if the function is of variable length this length will be negative.

12.1.7.7 OPTIONAL arguments

If an OPTIONAL argument is .NOT.PRESENT() a null pointer of the appropriate type is passed (e.g., for an INTEGER scalar, an (Integer*)0 is passed).


NAG Fortran Compiler, Release 7.1: ASCII Collating Sequence

 Navigation: Previous Up Next

12.2 ASCII Collating Sequence

12.2.1 Printing Characters

Decimal value and character. The value 32 is a space.

 | 30 | 40 | 50 | 60 | 70 | 80 | 90 | 100 | 110 | 120
0 |  | ( | 2 | < | F | P | Z | d | n | x
1 |  | ) | 3 | = | G | Q | [ | e | o | y
2 |  | * | 4 | > | H | R | \ | f | p | z
3 | ! | + | 5 | ? | I | S | ] | g | q | {
4 | " | , | 6 | @ | J | T | ^ | h | r | |
5 | # | - | 7 | A | K | U | _ | i | s | }
6 | $ | . | 8 | B | L | V | ` | j | t | ~
7 | % | / | 9 | C | M | W | a | k | u |
8 | & | 0 | : | D | N | X | b | l | v |
9 | ' | 1 | ; | E | O | Y | c | m | w |
Octal value and character. The value 40 is a space.

 | 40 | 50 | 60 | 70 | 100 | 110 | 120 | 130 | 140 | 150 | 160 | 170
0 |  | ( | 0 | 8 | @ | H | P | X | ' | h | p | x
1 | ! | ) | 1 | 9 | A | I | Q | Y | a | i | q | y
2 | " | * | 2 | : | B | J | R | Z | b | j | r | z
3 | # | + | 3 | ; | C | K | S | [ | c | k | s | {
4 | $ | , | 4 | < | D | L | T | \ | d | l | t | |
5 | % | - | 5 | = | E | M | U | ] | e | m | u | }
6 | & | . | 6 | > | F | N | V | ^ | f | n | v | ~
7 | ' | / | 7 | ? | G | O | W | _ | g | o | w |

12.2.2 Non-printing Characters

Decimal | Octal | Mnemonic | Control | Description
0 | 000 | NUL | ctrl/@ | Null character
1 | 001 | SOH | ctrl/A | Start of heading
2 | 002 | STX | ctrl/B | Start of text
3 | 003 | ETX | ctrl/C | End of text
4 | 004 | EOT | ctrl/D | End of transmission
5 | 005 | ENQ | ctrl/E | Enquire
6 | 006 | ACK | ctrl/F | Acknowledge
7 | 007 | BEL | ctrl/G | Bell
8 | 010 | BS | ctrl/H | Backspace
9 | 011 | HT | ctrl/I | Horizontal tab
10 | 012 | LF | ctrl/J | Line feed
11 | 013 | VT | ctrl/K | Vertical tab
12 | 014 | FF | ctrl/L | Form feed
13 | 015 | CR | ctrl/M | Carriage return
14 | 016 | SO | ctrl/N | Shift out
15 | 017 | SI | ctrl/O | Shift in
16 | 020 | DLE | ctrl/P | Data link escape
17 | 021 | DC1 | ctrl/Q | Device control 1 (XON)
18 | 022 | DC2 | ctrl/R | Device control 2
19 | 023 | DC3 | ctrl/S | Device control 3 (XOFF)
20 | 024 | DC4 | ctrl/T | Device control 4
21 | 025 | NAK | ctrl/U | Negative acknowledge
22 | 026 | SYN | ctrl/V | Synchronise
23 | 027 | ETB | ctrl/W | End transmission of block
24 | 030 | CAN | ctrl/X | Cancel
25 | 031 | EM | ctrl/Y | End of medium
26 | 032 | EOF | ctrl/Z | End-of-file
27 | 033 | ESC | ctrl/[ | Escape
28 | 034 | FS | ctrl/\ | File separator
29 | 035 | GS | ctrl/] | Group separator
30 | 036 | RS | ctrl/^ | Record separator
31 | 037 | US | ctrl/_ | Unit separator
127 | 177 | DEL |  | Delete


NAG Fortran Compiler, Release 7.1: Detailed Contents

 Navigation: Previous Up Next

13 Detailed Contents

  • 1 Introduction
    • 1.1 Introduction to the Compiler
      • 1.1.1 Other Fortran-related Activities at NAG
      • 1.1.2 This Manual
  • 2 Using the Compiler
    • 2.1 Usage
    • 2.2 Description
    • 2.3 File Types
    • 2.4 Compiler Options
    • 2.5 Files
    • 2.6 Compilation Messages
    • 2.7 Compiler Limits
    • 2.8 Input/Output Information
    • 2.9 OpenMP Support
    • 2.10 Automatic File Preconnection
    • 2.11 IEEE 754 Arithmetic Support
    • 2.12 Half precision floating-point
    • 2.13 Random Number Algorithm
    • 2.14 Automatic Garbage Collection
    • 2.15 Memory Tracing
    • 2.16 Undefined Variable Detection
    • 2.17 Data Types
    • 2.18 Modules
    • 2.19 Runtime Environment Variables
    • 2.20 Debugging
    • 2.21 Producing a Call Graph
    • 2.22 Dependency Analysis
    • 2.23 Generating Interfaces
    • 2.24 Source File Polishing
    • 2.25 Enhanced Source File Polishing
    • 2.26 Unifying Precision
  • 3 Debugging with dbx90
    • 3.1 dbx90 command line
    • 3.2 Description of dbx90
    • 3.3 dbx90 options
    • 3.4 dbx90 Commands
    • 3.5 dbx90 Expressions
      • 3.5.1 Scalar expressions
      • 3.5.2 Array sections
      • 3.5.3 Derived type component specification
    • 3.6 dbx90 Command aliases
    • 3.7 dbx90 limitations
    • 3.8 Example of dbx90
    • 3.9 Troubleshooting dbx90
  • 4 Preprocessing with fpp
    • 4.1 Overview of fpp
    • 4.2 fpp command line
    • 4.3 Description of fpp
    • 4.4 fpp options
    • 4.5 Using fpp
      • 4.5.1 Source files
      • 4.5.2 Output
      • 4.5.3 Directives
      • 4.5.4 Macro definition
      • 4.5.5 Including external files
      • 4.5.6 Line number control
      • 4.5.7 Conditional selection of source text
    • 4.6 Preprocessing details
      • 4.6.1 Scope of macro or variable definitions
      • 4.6.2 End of macro definition
      • 4.6.3 Function-like macro definition
      • 4.6.4 Cancelling macro definitions
      • 4.6.5 Conditional source code selection
      • 4.6.6 Including external files
      • 4.6.7 Comments
      • 4.6.8 Macro functions
      • 4.6.9 Macro expression
    • 4.7 fpp diagnostics
  • 5 Extensions
    • 5.1 Non-standard Extensions
      • 5.1.1 BOZ literal constants outside DATA statements
      • 5.1.2 Longer Names
      • 5.1.3 Dollar Sign in Names
      • 5.1.4 Input/output endian/format conversion
      • 5.1.5 Elemental BIND(C) procedures
      • 5.1.6 Maximum array rank is 31
    • 5.2 Obsolete Extensions
      • 5.2.1 Byte Sizes
      • 5.2.2 TAB Format
      • 5.2.3 Hollerith Constants
      • 5.2.4 D (debug) lines in Fixed Source Form
      • 5.2.5 Increased Line Length in Fixed Source Form
      • 5.2.6 Increased Maximum Number of Continuation Lines
      • 5.2.7 Intrinsic functions with mixed-kind arguments
      • 5.2.8 ACCESS='APPEND' specifier on OPEN statement
      • 5.2.9 VAX FORTRAN TYPE statement
      • 5.2.10 Auto-skipping NAMELIST input
      • 5.2.11 Legacy Application Support
      • 5.2.12 Mismatched Argument Lists
      • 5.2.13 Double Precision Complex Extensions
  • 6 Intrinsic Modules
    • 6.1 Intrinsic Module Overview
    • 6.2 f90_gc
    • 6.3 f90_iostat
    • 6.4 f90_kind
    • 6.5 f90_preconn_io
      • 6.5.1 Procedures
      • 6.5.2 Example
    • 6.6 f90_stat
      • 6.6.1 Parameters
      • 6.6.2 Example
    • 6.7 f90_unix_*
    • 6.8 ieee_*, iso_c_binding, iso_fortran_env
  • 7 Modern Fortran API to Posix
    • 7.1 Posix Module Overview
    • 7.2 f90_unix_dir
      • 7.2.1 Parameters
      • 7.2.2 Procedures
    • 7.3 f90_unix_dirent
      • 7.3.1 Procedures
    • 7.4 f90_unix_env
      • 7.4.1 Parameters
      • 7.4.2 Types
      • 7.4.3 Procedures
    • 7.5 f90_unix_errno
      • 7.5.1 Error Handling
      • 7.5.2 Parameters
    • 7.6 f90_unix_file
      • 7.6.1 Parameters
      • 7.6.2 Types
      • 7.6.3 Procedures
    • 7.7 f90_unix_io
      • 7.7.1 Procedures
    • 7.8 f90_unix_proc
      • 7.8.1 Parameters
      • 7.8.2 Procedures
  • 8 Standard Fortran 95
    • 8.1 Fortran 95 Program Structure
    • 8.2 Fortran 95 Expressions
    • 8.3 Fortran 95 Statements
    • 8.4 Fortran 95 Intrinsic Procedures
  • 9 Fortran 2003 Extensions
    • 9.1 Fortran 2003 Overview
    • 9.2 Object-oriented programming
      • 9.2.1 Type Extension
        • 9.2.1.1 Extending Types [5.0]
        • 9.2.1.2 Polymorphic Variables [5.0]
        • 9.2.1.3 Type Selection [5.0]
        • 9.2.1.4 Unlimited polymorphism [5.2]
        • 9.2.1.5 Ad hoc type comparison [5.3]
      • 9.2.2 Typed allocation [5.1]
      • 9.2.3 Sourced allocation (cloning) [5.1]
      • 9.2.4 Type-bound procedures [5.1]
        • 9.2.4.1 The type-bound procedure part
        • 9.2.4.2 Specific type-bound procedures
        • 9.2.4.3 Generic type-bound procedures
      • 9.2.5 Abstract derived types [5.1]
      • 9.2.6 Object-bound procedures [5.2]
    • 9.3 ALLOCATABLE extensions
      • 9.3.1 Allocatable Dummy Arrays [4.x]
      • 9.3.2 Allocatable Function Results [4.x]
      • 9.3.3 Allocatable Structure Components [4.x]
      • 9.3.4 Allocatable Component Example
      • 9.3.5 The MOVE_ALLOC intrinsic subroutine [5.2]
      • 9.3.6 Allocatable scalars [5.2]
      • 9.3.7 Automatic reallocation [5.2]
    • 9.4 Other data-oriented enhancements
      • 9.4.1 Parameterised derived types [6.0 for kind type parameters, 6.1 for length]
        • 9.4.1.1 Basic Syntax and Semantics
        • 9.4.1.2 More Semantics
        • 9.4.1.3 Assumed type parameters
        • 9.4.1.4 Deferred type parameters
      • 9.4.2 Finalisation [5.3]
      • 9.4.3 The PROTECTED attribute [5.0]
        • 9.4.3.1 Syntax
        • 9.4.3.2 Semantics
        • 9.4.3.3 Example
      • 9.4.4 Pointer enhancements
        • 9.4.4.1 INTENT for pointers [5.1]
        • 9.4.4.2 Pointer bounds specification [5.2]
        • 9.4.4.3 Rank-remapping Pointer Assignment [5.0]
      • 9.4.5 Individual component accessibility [5.1]
      • 9.4.6 Public entities of private type [5.1]
    • 9.5 C interoperability [mostly 5.1]
      • 9.5.1 The ISO_C_BINDING module
        • 9.5.1.1 The kind parameters
        • 9.5.1.2 Using C_PTR and C_FUNPTR
      • 9.5.2 BIND(C) types
      • 9.5.3 BIND(C) variables
      • 9.5.4 BIND(C) procedures
      • 9.5.5 Enumerations
    • 9.6 IEEE arithmetic support [4.x except as otherwise noted]
      • 9.6.1 Introduction
      • 9.6.2 Exception flags, modes and information flow
      • 9.6.3 Procedures in the modules
      • 9.6.4 The IEEE_FEATURES module
      • 9.6.5 IEEE_EXCEPTIONS
        • 9.6.5.1 Types and constants
        • 9.6.5.2 Procedures
      • 9.6.6 IEEE_ARITHMETIC module
        • 9.6.6.1 IEEE datatype selection
        • 9.6.6.2 Enquiry functions
        • 9.6.6.3 Rounding mode
        • 9.6.6.4 Underflow mode
        • 9.6.6.5 Number Classification
        • 9.6.6.6 Test functions
        • 9.6.6.7 Arithmetic functions
    • 9.7 Input/output Features
      • 9.7.1 Stream input/output [5.1]
      • 9.7.2 The BLANK= and PAD= specifiers [5.1]
      • 9.7.3 Decimal Comma [5.1]
      • 9.7.4 The DELIM= specifier [5.1]
      • 9.7.5 The ENCODING= specifier [5.1]
      • 9.7.6 The IOMSG= specifier [5.1]
      • 9.7.7 The IOSTAT= specifier [5.1]
      • 9.7.8 The SIGN= specifier [5.1]
      • 9.7.9 Intrinsic functions for testing IOSTAT= values [5.1]
      • 9.7.10 Input/output of IEEE infinities and NaNs [5.1]
      • 9.7.11 Output of floating-point zero [5.1]
      • 9.7.12 NAMELIST and internal files [5.1]
      • 9.7.13 Variables permitted in NAMELIST
      • 9.7.14 Recursive input/output [5.2]
      • 9.7.15 Asynchronous input/output
        • 9.7.15.1 Basic syntax [5.1]
        • 9.7.15.2 Basic Example
        • 9.7.15.3 The ASYNCHRONOUS attribute [5.2]
        • 9.7.15.4 The WAIT statement [5.2]
        • 9.7.15.5 Execution Semantics
      • 9.7.16 Scale factor followed by repeat count [5.1]
      • 9.7.17 FLUSH statement [5.2]
      • 9.7.18 Defined input/output [6.2]
    • 9.8 Miscellaneous Fortran 2003 Features
      • 9.8.1 Abstract interfaces and the PROCEDURE statement [5.1]
      • 9.8.2 Named procedure pointers [5.2]
      • 9.8.3 Intrinsic modules [4.x]
      • 9.8.4 Renaming user-defined operators on the USE statement [5.2]
      • 9.8.5 The ISO_FORTRAN_ENV module [5.1]
      • 9.8.6 The IMPORT statement [5.1]
      • 9.8.7 Length of names and statements
      • 9.8.8 Array constructor syntax enhancements
      • 9.8.9 Structure constructor syntax enhancements [5.3]
      • 9.8.10 Deferred character length [5.2]
      • 9.8.11 The ERRMSG= specifier [5.1]
      • 9.8.12 Intrinsic functions in constant expressions [5.2 partial; 5.3 complete]
      • 9.8.13 Specification functions can be recursive [6.2]
      • 9.8.14 Access to the command line [5.1]
      • 9.8.15 Access to environment variables [5.1]
      • 9.8.16 Character kind selection [5.1]
      • 9.8.17 Argument passing relaxation [5.1]
      • 9.8.18 The MAXLOC and MINLOC intrinsic functions [5.1]
      • 9.8.19 The VALUE attribute [4.x]
        • 9.8.19.1 Syntax
        • 9.8.19.2 Semantics
        • 9.8.19.3 Example
      • 9.8.20 The VOLATILE attribute [5.0]
      • 9.8.21 Enhanced complex constants [5.2]
      • 9.8.22 The ASSOCIATE construct [5.2]
      • 9.8.23 Binary, octal and hexadecimal constants [5.2]
      • 9.8.24 Character sets [5.1; 5.3]
      • 9.8.25 Intrinsic function changes for 64-bit machines [5.2]
      • 9.8.26 Miscellaneous intrinsic procedure changes [5.2]
  • 10 Fortran 2008 Extensions
    • 10.1 Fortran 2008 Overview
    • 10.2 SPMD programming with coarrays [6.2, 7.0]
      • 10.2.1 Overview
      • 10.2.2 Images
      • 10.2.3 Coarrays
      • 10.2.4 Declaring coarrays
      • 10.2.5 Accessing coarrays on other images
      • 10.2.6 Segments and synchronisation
      • 10.2.7 Allocating and deallocating coarrays
      • 10.2.8 Critical constructs
      • 10.2.9 Lock variables
      • 10.2.10 Atomic coarray accessing
      • 10.2.11 Normal termination of execution
      • 10.2.12 Error termination
      • 10.2.13 Fault tolerance
      • 10.2.14 Detailed syntax of coarray features
      • 10.2.15 Intrinsic procedures and coarrays
    • 10.3 Data declaration [mostly 6.0]
    • 10.4 Data usage and computation [mostly 5.3]
    • 10.5 Execution control [mostly 6.0]
    • 10.6 Intrinsic procedures and modules
      • 10.6.1 Additional mathematical intrinsic functions [mostly 5.3.1]
      • 10.6.2 Additional intrinsic functions for bit manipulation [mostly 5.3]
      • 10.6.3 Other new intrinsic procedures [mostly 5.3.1]
      • 10.6.4 Changes to existing intrinsic procedures [mostly 5.3.1]
      • 10.6.5 ISO_C_BINDING additions [6.2]
      • 10.6.6 ISO_FORTRAN_ENV additions
    • 10.7 Input/output extensions [mostly 5.3]
    • 10.8 Programs and procedures [mostly 5.3]
  • 11 Fortran 2018 Extensions
    • 11.1 Fortran 2018 Overview
    • 11.2 Data declaration
    • 11.3 Data usage and computation
    • 11.4 Input/output
    • 11.5 Execution control
    • 11.6 Intrinsic procedures and modules
    • 11.7 Program units and procedures
    • 11.8 Advanced C interoperability
    • 11.9 Updated IEEE arithmetic capabilities
    • 11.10 Advanced coarray programming
  • 12 Appendices
    • 12.1 Mixing Fortran and C
      • 12.1.1 Naming Conventions
      • 12.1.2 Initialisation and Termination
      • 12.1.3 Calling Conventions
      • 12.1.4 Data Types
        • 12.1.4.1 Pointers
        • 12.1.4.2 Derived types
        • 12.1.4.3 Supporting types
      • 12.1.5 SUBROUTINE return types
        • 12.1.5.1 SUBROUTINEs with label arguments
        • 12.1.5.2 SUBROUTINEs with no label arguments
      • 12.1.6 FUNCTION return types
        • 12.1.6.1 Scalar
        • 12.1.6.2 Scalar POINTER functions
        • 12.1.6.3 Array non-POINTER functions
        • 12.1.6.4 Array POINTER functions
      • 12.1.7 Argument types
        • 12.1.7.1 CHARACTER type
        • 12.1.7.2 non-POINTER non-ALLOCATABLE Scalar
        • 12.1.7.3 POINTER and ALLOCATABLE Scalar
        • 12.1.7.4 non-POINTER Array
        • 12.1.7.5 POINTER Array
        • 12.1.7.6 Procedures
        • 12.1.7.7 OPTIONAL arguments
    • 12.2 ASCII Collating Sequence
      • 12.2.1 Printing Characters
      • 12.2.2 Non-printing Characters
  • 13 Detailed Contents


LAPACK Guide

Introduction

LAPACK Routines by Subject

LAPACK Extra Routines


Introduction

LAPACK is a library of Fortran subroutines for solving the most commonly occurring problems in numerical linear algebra. It has been designed to be efficient on a wide range of computers. The name LAPACK is an acronym for Linear Algebra PACKage.

LAPACK is available from http://www.netlib.org/lapack/


LAPACK Routines by Subject

  • Real Linear Equations
  • Complex Linear Equations
  • Real Linear Least Squares
  • Complex Linear Least Squares
  • Real Generalized Linear Least Squares
  • Complex Generalized Linear Least Squares
  • Real Symmetric Eigenproblems
  • Complex Hermitian Eigenproblems
  • Real Nonsymmetric Eigenproblems
  • Complex Nonsymmetric Eigenproblems
  • Real Generalized Symmetric Eigenproblems
  • Complex Generalized Hermitian Eigenproblems
  • Real Generalized Nonsymmetric Eigenproblems
  • Complex Generalized Nonsymmetric Eigenproblems
  • Real Singular Value Decomposition
  • Complex Singular Value Decomposition
  • Real Generalized Singular Value Decomposition
  • Complex Generalized Singular Value Decomposition
  • Real QR Factorization
  • Complex QR Factorization
  • Computational Routines


LAPACK:Real Linear Equations

Next: Complex Linear Equations Up: LAPACK Routines by Subject

Real Linear Equations

  • DGBSV : Solution of a real banded system of linear equations
  • DGBSVX : Solution (by LU factorization), error-bound and condition estimate for a real banded system of linear equations
  • DGESV : Solution of a real system of linear equations
  • DGESVX : Solution (by LU factorization), error-bound and condition estimate for a real system of linear equations
  • DGTSV : Solution to a real tridiagonal system of linear equations
  • DGTSVX : Solution (by LU factorization), error-bound and condition estimate for a real tridiagonal system of linear equations
  • DPBSV : Solution of a real symmetric positive definite banded system of linear equations
  • DPBSVX : Solution (by Cholesky factorization), error-bound and condition estimate for a real symmetric positive definite banded system of linear equations
  • DPOSV : Solution of a real symmetric positive definite system of linear equations
  • DPOSVX : Solution (by Cholesky factorization), error-bound and condition estimate for a real symmetric positive definite system of linear equations
  • DPPSV : Solution of a real symmetric positive definite system of linear equations, packed storage
  • DPPSVX : Solution (by Cholesky factorization), error-bound and condition estimate for a real symmetric positive definite system of linear equations, packed storage
  • DPTSV : Solution of a real symmetric positive definite tridiagonal system of linear equations
  • DPTSVX : Solution (by modified Cholesky factorization), error-bound and condition estimate for a real symmetric positive definite tridiagonal system of linear equations
  • DSGESV : Computes the solution to a real system of linear equations using mixed precision arithmetic
  • DSPOSV : Computes the solution to a real symmetric positive definite system of linear equations using mixed precision arithmetic
  • DSPSV : Solution of a real symmetric system of linear equations, packed storage
  • DSPSVX : Solution (by diagonal pivoting factorization) of a real symmetric system of linear equations, packed storage
  • DSYSV : Solution of a real symmetric system of linear equations
  • DSYSVX : Solution (by diagonal pivoting factorization) of a real symmetric system of linear equations


DGBSV example

Real Linear Equations: Solution of a real banded system of linear equations

 To solve the equations

where $ A$ is the band matrix

Details of the $ LU$ factorization of $ A$ are also output.

Data

DGBSV Example Program Data

  4  1  2                     :Values of N, KL and KU

 -0.23   2.54  -3.66
 -6.98   2.46  -2.73  -2.13
         2.56   2.46   4.07
               -4.78  -3.82   :End of matrix A

  4.42  27.13  -6.14  10.50   :End of vector B

Result

 DGBSV Example Program Results

 Solution
       -2.0000     3.0000     1.0000    -4.0000

 Details of factorization
             1          2          3          4
 1     -6.9800     2.4600    -2.7300    -2.1300
 2      0.0330     2.5600     2.4600     4.0700
 3                 0.9605    -5.9329    -3.8391
 4                            0.8057    -0.7269

 Pivot indices
             2          3          3          4

Source

    Program dgbsv_example

!     DGBSV Example Program Text

!     Copyright 2017, Numerical Algorithms Group Ltd. http://www.nag.com

!     .. Use Statements ..
      Use lapack_example_aux, Only: nagf_file_print_matrix_real_band
      Use lapack_interfaces, Only: dgbsv
      Use lapack_precision, Only: dp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter :: nin = 5, nout = 6
!     .. Local Scalars ..
      Integer :: i, ifail, info, j, k, kl, ku, ldab, n
!     .. Local Arrays ..
      Real (Kind=dp), Allocatable :: ab(:, :), b(:)
      Integer, Allocatable :: ipiv(:)
!     .. Intrinsic Procedures ..
      Intrinsic :: max, min
!     .. Executable Statements ..
      Write (nout, *) 'DGBSV Example Program Results'
      Write (nout, *)
!     Skip heading in data file
      Read (nin, *)
      Read (nin, *) n, kl, ku
      ldab = 2*kl + ku + 1
      Allocate (ab(ldab,n), b(n), ipiv(n))

!     Read the band matrix A and the right hand side b from data file

      k = kl + ku + 1
      Read (nin, *)((ab(k+i-j,j),j=max(i-kl,1),min(i+ku,n)), i=1, n)
      Read (nin, *) b(1:n)

!     Solve the equations Ax = b for x
      Call dgbsv(n, kl, ku, 1, ab, ldab, ipiv, b, n, info)

      If (info==0) Then

!       Print solution

        Write (nout, *) 'Solution'
        Write (nout, 100) b(1:n)

!       Print details of the factorization

        Write (nout, *)
        Flush (nout)

!       ifail: behaviour on error exit
!              =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
        ifail = 0
        Call nagf_file_print_matrix_real_band(n, n, kl, kl+ku, ab, ldab, &
          'Details of factorization', ifail)

!       Print pivot indices'

        Write (nout, *)
        Write (nout, *) 'Pivot indices'
        Write (nout, 110) ipiv(1:n)

      Else
        Write (nout, 120) 'The (', info, ',', info, ')', &
          ' element of the factor U is zero'
      End If

100   Format ((3X,7F11.4))
110   Format ((3X,7I11))
120   Format (1X, A, I3, A, I3, A, A)
    End Program
Full documentation of DGBSV


DGBSVX example

Real Linear Equations: Solution (by LU factorization), error-bound and condition estimate for a real banded system of linear equations

 To solve the equations

where $ A$ is the band matrix

Estimates for the backward errors, forward errors, condition number and pivotgrowth are also output, together with information on the equilibration of $ A$.

Data

DGBSVX Example Program Data
  4  2  1  2                  :Values of N, NRHS, KL and KU
 -0.23   2.54  -3.66
 -6.98   2.46  -2.73  -2.13
         2.56   2.46   4.07
               -4.78  -3.82   :End of matrix A
  4.42 -36.01
 27.13 -31.67
 -6.14  -1.16
 10.50 -25.82                 :End of matrix B

Result

 DGBSVX Example Program Results

 Solution(s)
             1          2
 1     -2.0000     1.0000
 2      3.0000    -4.0000
 3      1.0000     7.0000
 4     -4.0000    -2.0000

 Backward errors (machine-dependent)
       1.1E-16    9.9E-17

 Estimated forward error bounds (machine-dependent)
       1.6E-14    1.9E-14

 Estimate of reciprocal condition number
       1.8E-02

 A has not been equilibrated

 Estimate of reciprocal pivot growth factor
       1.0E+00

Source

    Program dgbsvx_example

!     DGBSVX Example Program Text

!     Copyright 2017, Numerical Algorithms Group Ltd. http://www.nag.com

!     .. Use Statements ..
      Use lapack_example_aux, Only: nagf_file_print_matrix_real_gen
      Use lapack_interfaces, Only: dgbsvx
      Use lapack_precision, Only: dp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=dp) :: rcond
      Integer :: i, ifail, info, j, k, kl, ku, ldab, ldafb, ldb, ldx, n, nrhs
      Character (1) :: equed
!     .. Local Arrays ..
      Real (Kind=dp), Allocatable :: ab(:, :), afb(:, :), b(:, :), berr(:), &
        c(:), ferr(:), r(:), work(:), x(:, :)
      Integer, Allocatable :: ipiv(:), iwork(:)
!     .. Intrinsic Procedures ..
      Intrinsic :: max, min
!     .. Executable Statements ..
      Write (nout, *) 'DGBSVX Example Program Results'
      Write (nout, *)
      Flush (nout)
!     Skip heading in data file
      Read (nin, *)
      Read (nin, *) n, nrhs, kl, ku
      ldb = n
      ldx = n
      ldab = kl + ku + 1
      ldafb = ldab + kl
      Allocate (ab(ldab,n), afb(ldafb,n), b(ldb,nrhs), berr(nrhs), c(n), &
        ferr(nrhs), r(n), work(3*n), x(ldx,nrhs), ipiv(n), iwork(n))

!     Read the band matrix A and B from data file

      k = ku + 1
      Read (nin, *)((ab(k+i-j,j),j=max(i-kl,1),min(i+ku,n)), i=1, n)
      Read (nin, *)(b(i,1:nrhs), i=1, n)

!     Solve the equations AX = B for X
      Call dgbsvx('Equilibration', 'No transpose', n, kl, ku, nrhs, ab, ldab, &
        afb, ldafb, ipiv, equed, r, c, b, ldb, x, ldx, rcond, ferr, berr, &
        work, iwork, info)

      If ((info==0) .Or. (info==n+1)) Then

!       Print solution, error bounds, condition number, the form
!       of equilibration and the pivot growth factor

!       ifail: behaviour on error exit
!              =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
        ifail = 0
        Call nagf_file_print_matrix_real_gen('General', ' ', n, nrhs, x, ldx, &
          'Solution(s)', ifail)

        Write (nout, *)
        Write (nout, *) 'Backward errors (machine-dependent)'
        Write (nout, 100) berr(1:nrhs)
        Write (nout, *)
        Write (nout, *) 'Estimated forward error bounds (machine-dependent)'
        Write (nout, 100) ferr(1:nrhs)
        Write (nout, *)
        Write (nout, *) 'Estimate of reciprocal condition number'
        Write (nout, 100) rcond
        Write (nout, *)
        If (equed=='N') Then
          Write (nout, *) 'A has not been equilibrated'
        Else If (equed=='R') Then
          Write (nout, *) 'A has been row scaled as diag(R)*A'
        Else If (equed=='C') Then
          Write (nout, *) 'A has been column scaled as A*diag(C)'
        Else If (equed=='B') Then
          Write (nout, *) &
            'A has been row and column scaled as diag(R)*A*diag(C)'
        End If
        Write (nout, *)
        Write (nout, *) 'Estimate of reciprocal pivot growth factor'
        Write (nout, 100) work(1)

        If (info==n+1) Then
          Write (nout, *)
          Write (nout, *) 'The matrix A is singular to working precision'
        End If
      Else
        Write (nout, 110) 'The (', info, ',', info, ')', &
          ' element of the factor U is zero'
      End If

100   Format ((3X,1P,7E11.1))
110   Format (1X, A, I3, A, I3, A, A)
    End Program
Full documentation of DGBSVX


DGESV example

Real Linear Equations: Solution of a real system of linear equations

 To find the singular values and left and right singular vectors of the 6 by 4matrix

together with approximate error bounds for the computed singular values andvectors.

The example program for DGESDD illustrates finding a singular valuedecomposition for the case [image].

Data

DGESV Example Program Data

  4                           :Value of N

  1.80   2.88   2.05  -0.89
  5.25  -2.95  -0.95  -3.80
  1.58  -2.69  -2.90  -1.04
 -1.11  -0.66  -0.59   0.80   :End of matrix A

  9.52  24.35   0.77  -6.22   :End of vector b

Result

 DGESV Example Program Results

 Solution
        1.0000    -1.0000     3.0000    -5.0000

 Details of factorization
             1          2          3          4
 1      5.2500    -2.9500    -0.9500    -3.8000
 2      0.3429     3.8914     2.3757     0.4129
 3      0.3010    -0.4631    -1.5139     0.2948
 4     -0.2114    -0.3299     0.0047     0.1314

 Pivot indices
             2          2          3          4

Source

    Program dgesv_example

!     DGESV Example Program Text

!     Copyright 2017, Numerical Algorithms Group Ltd. http://www.nag.com

!     .. Use Statements ..
      Use lapack_example_aux, Only: nagf_file_print_matrix_real_gen
      Use lapack_interfaces, Only: dgesv
      Use lapack_precision, Only: dp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter :: nin = 5, nout = 6
!     .. Local Scalars ..
      Integer :: i, ifail, info, lda, ldb, n
!     .. Local Arrays ..
      Real (Kind=dp), Allocatable :: a(:, :), b(:)
      Integer, Allocatable :: ipiv(:)
!     .. Executable Statements ..
      Write (nout, *) 'DGESV Example Program Results'
      Write (nout, *)
!     Skip heading in data file
      Read (nin, *)
      Read (nin, *) n
      lda = n
      ldb = n
      Allocate (a(lda,n), b(ldb), ipiv(n))

!     Read A and B from data file

      Read (nin, *)(a(i,1:n), i=1, n)
      Read (nin, *) b(1:n)

!     Solve the equations Ax = b for x

      Call dgesv(n, 1, a, lda, ipiv, b, ldb, info)

      If (info==0) Then

!       Print solution

        Write (nout, *) 'Solution'
        Write (nout, 100) b(1:n)

!       Print details of factorization

        Write (nout, *)
        Flush (nout)

!       ifail: behaviour on error exit
!              =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
        ifail = 0
        Call nagf_file_print_matrix_real_gen('General', ' ', n, n, a, lda, &
          'Details of factorization', ifail)

!       Print pivot indices

        Write (nout, *)
        Write (nout, *) 'Pivot indices'
        Write (nout, 110) ipiv(1:n)

      Else
        Write (nout, 120) 'The (', info, ',', info, ')', &
          ' element of the factor U is zero'
      End If

100   Format ((3X,7F11.4))
110   Format ((3X,7I11))
120   Format (1X, A, I3, A, I3, A, A)
    End Program
Full documentation of DGESV


DGESVX example

Real Linear Equations: Solution (by LU factorization), error-bound and condition estimate for a real system of linear equations

 To solve the equations

where $ A$ is the general matrix

Error estimates for the solutions, information on scaling, an estimate of thereciprocal of the condition number of the scaled matrix $ A$ and an estimate ofthe reciprocal of the pivot growth factor for the factorization of $ A$ are alsooutput.

Data

DGESVX Example Program Data

    4        2                     :Values of N and NRHS

    1.80     2.88    2.05    -0.89
  525.00  -295.00  -95.00  -380.00
    1.58    -2.69   -2.90    -1.04
   -1.11    -0.66   -0.59     0.80 :End of matrix A

    9.52    18.47
 2435.00   225.00
    0.77   -13.28
   -6.22    -6.21                  :End of matrix B

Result

 DGESVX Example Program Results

 Solution(s)
             1          2
 1      1.0000     3.0000
 2     -1.0000     2.0000
 3      3.0000     4.0000
 4     -5.0000     1.0000

 Backward errors (machine-dependent)
       6.8E-17    9.1E-17

 Estimated forward error bounds (machine-dependent)
       2.4E-14    3.6E-14

 A has been row scaled as diag(R)*A

 Reciprocal condition number estimate of scaled matrix
       1.8E-02

 Estimate of reciprocal pivot growth factor
       7.4E-01

Source

    Program dgesvx_example

!     DGESVX Example Program Text

!     Copyright 2017, Numerical Algorithms Group Ltd. http://www.nag.com

!     .. Use Statements ..
      Use lapack_example_aux, Only: nagf_file_print_matrix_real_gen
      Use lapack_interfaces, Only: dgesvx
      Use lapack_precision, Only: dp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=dp) :: rcond
      Integer :: i, ifail, info, lda, ldaf, ldb, ldx, n, nrhs
      Character (1) :: equed
!     .. Local Arrays ..
      Real (Kind=dp), Allocatable :: a(:, :), af(:, :), b(:, :), berr(:), &
        c(:), ferr(:), r(:), work(:), x(:, :)
      Integer, Allocatable :: ipiv(:), iwork(:)
!     .. Executable Statements ..
      Write (nout, *) 'DGESVX Example Program Results'
      Write (nout, *)
      Flush (nout)
!     Skip heading in data file
      Read (nin, *)
      Read (nin, *) n, nrhs
      lda = n
      ldaf = n
      ldb = n
      ldx = n
      Allocate (a(lda,n), af(ldaf,n), b(ldb,nrhs), berr(nrhs), c(n), &
        ferr(nrhs), r(n), work(4*n), x(ldx,nrhs), ipiv(n), iwork(n))

!     Read A and B from data file

      Read (nin, *)(a(i,1:n), i=1, n)
      Read (nin, *)(b(i,1:nrhs), i=1, n)

!     Solve the equations AX = B for X

      Call dgesvx('Equilibration', 'No transpose', n, nrhs, a, lda, af, ldaf, &
        ipiv, equed, r, c, b, ldb, x, ldx, rcond, ferr, berr, work, iwork, &
        info)

      If ((info==0) .Or. (info==n+1)) Then

!       Print solution, error bounds, condition number, the form
!       of equilibration and the pivot growth factor

!       ifail: behaviour on error exit
!              =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
        ifail = 0
        Call nagf_file_print_matrix_real_gen('General', ' ', n, nrhs, x, ldx, &
          'Solution(s)', ifail)

        Write (nout, *)
        Write (nout, *) 'Backward errors (machine-dependent)'
        Write (nout, 100) berr(1:nrhs)
        Write (nout, *)
        Write (nout, *) 'Estimated forward error bounds (machine-dependent)'
        Write (nout, 100) ferr(1:nrhs)
        Write (nout, *)
        If (equed=='N') Then
          Write (nout, *) 'A has not been equilibrated'
        Else If (equed=='R') Then
          Write (nout, *) 'A has been row scaled as diag(R)*A'
        Else If (equed=='C') Then
          Write (nout, *) 'A has been column scaled as A*diag(C)'
        Else If (equed=='B') Then
          Write (nout, *) &
            'A has been row and column scaled as diag(R)*A*diag(C)'
        End If
        Write (nout, *)
        Write (nout, *) &
          'Reciprocal condition number estimate of scaled matrix'
        Write (nout, 100) rcond
        Write (nout, *)
        Write (nout, *) 'Estimate of reciprocal pivot growth factor'
        Write (nout, 100) work(1)

        If (info==n+1) Then
          Write (nout, *)
          Write (nout, *) 'The matrix A is singular to working precision'
        End If
      Else
        Write (nout, 110) 'The (', info, ',', info, ')', &
          ' element of the factor U is zero'
      End If

100   Format ((3X,1P,7E11.1))
110   Format (1X, A, I3, A, I3, A, A)
    End Program
Full documentation of DGESVX


DGTSV example

Real Linear Equations: Solution to a real tridiagonal system of linear equations

 To solve the equations

where $ A$ is the tridiagonal matrix

Data

DGTSV Example Program Data
  5                            :Value of N
        2.1  -1.0   1.9   8.0
  3.0   2.3  -5.0  -0.9   7.1
  3.4   3.6   7.0  -6.0        :End of matrix A
  2.7  -0.5   2.6   0.6   2.7  :End of vector B

Result

 DGTSV Example Program Results

 Solution
     -4.0000     7.0000     3.0000    -4.0000    -3.0000

Source

    Program dgtsv_example

!     DGTSV Example Program Text

!     Copyright 2017, Numerical Algorithms Group Ltd. http://www.nag.com

!     .. Use Statements ..
      Use lapack_interfaces, Only: dgtsv
      Use lapack_precision, Only: dp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter :: nin = 5, nout = 6
!     .. Local Scalars ..
      Integer :: info, n
!     .. Local Arrays ..
      Real (Kind=dp), Allocatable :: b(:), d(:), dl(:), du(:)
!     .. Executable Statements ..
      Write (nout, *) 'DGTSV Example Program Results'
      Write (nout, *)
!     Skip heading in data file
      Read (nin, *)
      Read (nin, *) n

      Allocate (b(n), d(n), dl(n-1), du(n-1))

!     Read the tridiagonal matrix A and the right hand side B from
!     data file

      Read (nin, *) du(1:n-1)
      Read (nin, *) d(1:n)
      Read (nin, *) dl(1:n-1)
      Read (nin, *) b(1:n)

!     Solve the equations Ax = b for x

      Call dgtsv(n, 1, dl, d, du, b, n, info)

      If (info==0) Then

!       Print solution

        Write (nout, *) 'Solution'
        Write (nout, 100) b(1:n)

      Else
        Write (nout, 110) 'The (', info, ',', info, ')', &
          ' element of the factor U is zero'
      End If

100   Format ((1X,7F11.4))
110   Format (1X, A, I3, A, I3, A, A)
    End Program
Full documentation of DGTSV


DGTSVX example

Real Linear Equations: Solution (by LU factorization), error-bound and condition estimate for a real tridiagonal system of linear equations

 To solve the equations

where $ A$ is the tridiagonal matrix

Estimates for the backward errors, forward errors and condition number are alsooutput.

Data

DGTSVX Example Program Data
  5     2                      :Values of N and NRHS
        2.1  -1.0   1.9   8.0
  3.0   2.3  -5.0  -0.9   7.1
  3.4   3.6   7.0  -6.0        :End of matrix A
  2.7   6.6
 -0.5  10.8
  2.6  -3.2
  0.6 -11.2
  2.7  19.1                    :End of matrix B

Result

 DGTSVX Example Program Results

 Solution(s)
             1          2
 1     -4.0000     5.0000
 2      7.0000    -4.0000
 3      3.0000    -3.0000
 4     -4.0000    -2.0000
 5     -3.0000     1.0000

 Backward errors (machine-dependent)
       7.2E-17    5.9E-17

 Estimated forward error bounds (machine-dependent)
       9.4E-15    1.4E-14

 Estimate of reciprocal condition number
       1.1E-02

Source

    Program dgtsvx_example

!     DGTSVX Example Program Text

!     Copyright 2017, Numerical Algorithms Group Ltd. http://www.nag.com

!     .. Use Statements ..
      Use lapack_example_aux, Only: nagf_file_print_matrix_real_gen
      Use lapack_interfaces, Only: dgtsvx
      Use lapack_precision, Only: dp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=dp) :: rcond
      Integer :: i, ifail, info, ldb, ldx, n, nrhs
!     .. Local Arrays ..
      Real (Kind=dp), Allocatable :: b(:, :), berr(:), d(:), df(:), dl(:), &
        dlf(:), du(:), du2(:), duf(:), ferr(:), work(:), x(:, :)
      Integer, Allocatable :: ipiv(:), iwork(:)
!     .. Executable Statements ..
      Write (nout, *) 'DGTSVX Example Program Results'
      Write (nout, *)
      Flush (nout)
!     Skip heading in data file
      Read (nin, *)
      Read (nin, *) n, nrhs
      ldb = n
      ldx = n
      Allocate (b(ldb,nrhs), berr(nrhs), d(n), df(n), dl(n-1), dlf(n-1), &
        du(n-1), du2(n-2), duf(n-1), ferr(nrhs), work(3*n), x(ldx,nrhs), &
        ipiv(n), iwork(n))

!     Read the tridiagonal matrix A from data file

      Read (nin, *) du(1:n-1)
      Read (nin, *) d(1:n)
      Read (nin, *) dl(1:n-1)

!     Read the right hand matrix B

      Read (nin, *)(b(i,1:nrhs), i=1, n)

!     Solve the equations AX = B

      Call dgtsvx('No factors', 'No transpose', n, nrhs, dl, d, du, dlf, df, &
        duf, du2, ipiv, b, ldb, x, ldx, rcond, ferr, berr, work, iwork, info)

      If ((info==0) .Or. (info==n+1)) Then

!       Print solution, error bounds and condition number

!       ifail: behaviour on error exit
!              =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
        ifail = 0
        Call nagf_file_print_matrix_real_gen('General', ' ', n, nrhs, x, ldx, &
          'Solution(s)', ifail)

        Write (nout, *)
        Write (nout, *) 'Backward errors (machine-dependent)'
        Write (nout, 100) berr(1:nrhs)
        Write (nout, *)
        Write (nout, *) 'Estimated forward error bounds (machine-dependent)'
        Write (nout, 100) ferr(1:nrhs)
        Write (nout, *)
        Write (nout, *) 'Estimate of reciprocal condition number'
        Write (nout, 100) rcond

        If (info==n+1) Then
          Write (nout, *)
          Write (nout, *) 'The matrix A is singular to working precision'
        End If
      Else
        Write (nout, 110) 'The (', info, ',', info, ')', &
          ' element of the factor U is zero'
      End If

100   Format ((3X,1P,7E11.1))
110   Format (1X, A, I3, A, I3, A, A)
    End Program
Full documentation of DGTSVX


DPBSV example

Real Linear Equations: Solution of a real symmetric positive definite banded system of linear equations

 To solve the equations

where $ A$ is the symmetric positive definite band matrix

Error estimates for the solutions, information on equilibration and an estimateof the reciprocal of the condition number of the scaled matrix $ A$ are alsooutput.

Data

DPBSV Example Program Data

  4      1                  :Values of N and KD

  5.49   2.68
         5.63  -2.39
                2.60  -2.22
                       5.17 :End of matrix A

 22.09   9.31  -5.24  11.83 :End of vector b

Result

 DPBSV Example Program Results

 Solution
        5.0000    -2.0000    -3.0000     1.0000

 Cholesky factor U
             1          2          3          4
 1      2.3431     1.1438
 2                 2.0789    -1.1497
 3                            1.1306    -1.9635
 4                                       1.1465

Source

    Program dpbsv_example

!     DPBSV Example Program Text

!     Copyright 2017, Numerical Algorithms Group Ltd. http://www.nag.com

!     .. Use Statements ..
      Use lapack_example_aux, Only: nagf_file_print_matrix_real_band
      Use lapack_interfaces, Only: dpbsv
      Use lapack_precision, Only: dp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter :: nin = 5, nout = 6
      Character (1), Parameter :: uplo = 'U'
!     .. Local Scalars ..
      Integer :: i, ifail, info, j, kd, ldab, n
!     .. Local Arrays ..
      Real (Kind=dp), Allocatable :: ab(:, :), b(:)
!     .. Intrinsic Procedures ..
      Intrinsic :: max, min
!     .. Executable Statements ..
      Write (nout, *) 'DPBSV Example Program Results'
      Write (nout, *)
!     Skip heading in data file
      Read (nin, *)
      Read (nin, *) n, kd
      ldab = kd + 1
      Allocate (ab(ldab,n), b(n))

!     Read the upper or lower triangular part of the band matrix A
!     from data file

      If (uplo=='U') Then
        Read (nin, *)((ab(kd+1+i-j,j),j=i,min(n,i+kd)), i=1, n)
      Else If (uplo=='L') Then
        Read (nin, *)((ab(1+i-j,j),j=max(1,i-kd),i), i=1, n)
      End If

!     Read b from data file

      Read (nin, *) b(1:n)

!     Solve the equations Ax = b for x
      Call dpbsv(uplo, n, kd, 1, ab, ldab, b, n, info)

      If (info==0) Then

!       Print solution

        Write (nout, *) 'Solution'
        Write (nout, 100) b(1:n)

!       Print details of factorization

        Write (nout, *)
        Flush (nout)

!       ifail: behaviour on error exit
!              =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
        ifail = 0
        If (uplo=='U') Then
          Call nagf_file_print_matrix_real_band(n, n, 0, kd, ab, ldab, &
            'Cholesky factor U', ifail)
        Else If (uplo=='L') Then
          Call nagf_file_print_matrix_real_band(n, n, kd, 0, ab, ldab, &
            'Cholesky factor L', ifail)
        End If

      Else
        Write (nout, 110) 'The leading minor of order ', info, &
          ' is not positive definite'
      End If

100   Format ((3X,7F11.4))
110   Format (1X, A, I3, A)
    End Program
Full documentation of DPBSV


DPBSVX example

Real Linear Equations: Solution (by Cholesky factorization), error-bound and condition estimate for a real symmetric positive definite banded system of linear equations

 To solve the equations

where $ A$ is the symmetric positive definite band matrix

Error estimates for the solutions, information on equilibration and an estimateof the reciprocal of the condition number of the scaled matrix $ A$ are alsooutput.

Data

DPBSVX Example Program Data

  4      1      2           :Values of N, KD and NRHS

  5.49   2.68
         5.63  -2.39
                2.60  -2.22
                       5.17 :End of matrix A

 22.09   5.10
  9.31  30.81
 -5.24 -25.82
 11.83  22.90               :End of matrix B

Result

 DPBSVX Example Program Results

 Solution(s)
             1          2
 1      5.0000    -2.0000
 2     -2.0000     6.0000
 3     -3.0000    -1.0000
 4      1.0000     4.0000

 Backward errors (machine-dependent)
       8.6E-17    1.1E-16

 Estimated forward error bounds (machine-dependent)
       2.0E-14    2.8E-14

 Estimate of reciprocal condition number
       1.3E-02

 A has not been equilibrated

Source

    Program dpbsvx_example

!     DPBSVX Example Program Text

!     Copyright 2017, Numerical Algorithms Group Ltd. http://www.nag.com

!     .. Use Statements ..
      Use lapack_example_aux, Only: nagf_file_print_matrix_real_gen
      Use lapack_interfaces, Only: dpbsvx
      Use lapack_precision, Only: dp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter :: nin = 5, nout = 6
      Character (1), Parameter :: uplo = 'U'
!     .. Local Scalars ..
      Real (Kind=dp) :: rcond
      Integer :: i, ifail, info, j, kd, ldab, ldafb, ldb, ldx, n, nrhs
      Character (1) :: equed
!     .. Local Arrays ..
      Real (Kind=dp), Allocatable :: ab(:, :), afb(:, :), b(:, :), berr(:), &
        ferr(:), s(:), work(:), x(:, :)
      Integer, Allocatable :: iwork(:)
!     .. Intrinsic Procedures ..
      Intrinsic :: max, min
!     .. Executable Statements ..
      Write (nout, *) 'DPBSVX Example Program Results'
      Write (nout, *)
      Flush (nout)
!     Skip heading in data file
      Read (nin, *)
      Read (nin, *) n, kd, nrhs
      ldb = n
      ldx = n
      ldab = kd + 1
      ldafb = kd + 1
      Allocate (ab(ldab,n), afb(ldafb,n), b(ldb,nrhs), berr(nrhs), ferr(nrhs), &
        s(n), work(3*n), x(ldx,nrhs), iwork(n))

!     Read the upper or lower triangular part of the band matrix A
!     from data file

      If (uplo=='U') Then
        Read (nin, *)((ab(kd+1+i-j,j),j=i,min(n,i+kd)), i=1, n)
      Else If (uplo=='L') Then
        Read (nin, *)((ab(1+i-j,j),j=max(1,i-kd),i), i=1, n)
      End If

!     Read B from data file

      Read (nin, *)(b(i,1:nrhs), i=1, n)

!     Solve the equations AX = B for X
      Call dpbsvx('Equilibration', uplo, n, kd, nrhs, ab, ldab, afb, ldafb, &
        equed, s, b, ldb, x, ldx, rcond, ferr, berr, work, iwork, info)

      If ((info==0) .Or. (info==n+1)) Then

!       Print solution, error bounds, condition number and the form
!       of equilibration

!       ifail: behaviour on error exit
!              =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
        ifail = 0
        Call nagf_file_print_matrix_real_gen('General', ' ', n, nrhs, x, ldx, &
          'Solution(s)', ifail)

        Write (nout, *)
        Write (nout, *) 'Backward errors (machine-dependent)'
        Write (nout, 100) berr(1:nrhs)
        Write (nout, *)
        Write (nout, *) 'Estimated forward error bounds (machine-dependent)'
        Write (nout, 100) ferr(1:nrhs)
        Write (nout, *)
        Write (nout, *) 'Estimate of reciprocal condition number'
        Write (nout, 100) rcond
        Write (nout, *)
        If (equed=='N') Then
          Write (nout, *) 'A has not been equilibrated'
        Else If (equed=='Y') Then
          Write (nout, *) &
            'A has been row and column scaled as diag(S)*A*diag(S)'
        End If

        If (info==n+1) Then
          Write (nout, *)
          Write (nout, *) 'The matrix A is singular to working precision'
        End If
      Else
        Write (nout, 110) 'The leading minor of order ', info, &
          ' is not positive definite'
      End If

100   Format ((3X,1P,7E11.1))
110   Format (1X, A, I3, A)
    End Program
Full documentation of DPBSVX


DPOSV example

Real Linear Equations: Solution of a real symmetric positive definite system of linear equations

 To solve the equations

where $ A$ is the symmetric positive definite matrix

Details of the Cholesky factorization of $ A$ are also output.

Data

DPOSV Example Program Data
  4                         :Value of N
  4.16  -3.12   0.56  -0.10
         5.03  -0.83   1.18
                0.76   0.34
                       1.18 :End of matrix A
  8.70 -13.35   1.89  -4.14 :End of vector b

Result

 DPOSV Example Program Results

 Solution
        1.0000    -1.0000     2.0000    -3.0000

 Cholesky factor U
             1          2          3          4
 1      2.0396    -1.5297     0.2746    -0.0490
 2                 1.6401    -0.2500     0.6737
 3                            0.7887     0.6617
 4                                       0.5347

Source

    Program dposv_example

!     DPOSV Example Program Text

!     Copyright 2017, Numerical Algorithms Group Ltd. http://www.nag.com

!     .. Use Statements ..
      Use lapack_example_aux, Only: nagf_file_print_matrix_real_gen
      Use lapack_interfaces, Only: dposv
      Use lapack_precision, Only: dp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter :: nin = 5, nout = 6
!     .. Local Scalars ..
      Integer :: i, ifail, info, lda, n
!     .. Local Arrays ..
      Real (Kind=dp), Allocatable :: a(:, :), b(:)
!     .. Executable Statements ..
      Write (nout, *) 'DPOSV Example Program Results'
      Write (nout, *)
!     Skip heading in data file
      Read (nin, *)
      Read (nin, *) n
      lda = n
      Allocate (a(lda,n), b(n))

!     Read the upper triangular part of A from data file

      Read (nin, *)(a(i,i:n), i=1, n)

!     Read b from data file

      Read (nin, *) b(1:n)

!     Solve the equations Ax = b for x
      Call dposv('Upper', n, 1, a, lda, b, n, info)

      If (info==0) Then

!       Print solution

        Write (nout, *) 'Solution'
        Write (nout, 100) b(1:n)

!       Print details of factorization

        Write (nout, *)
        Flush (nout)

!       ifail: behaviour on error exit
!              =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
        ifail = 0
        Call nagf_file_print_matrix_real_gen('Upper', 'Non-unit diagonal', n, &
          n, a, lda, 'Cholesky factor U', ifail)

      Else
        Write (nout, 110) 'The leading minor of order ', info, &
          ' is not positive definite'
      End If

100   Format ((3X,7F11.4))
110   Format (1X, A, I3, A)
    End Program
Full documentation of DPOSV


DPOSVX example

Real Linear Equations: Solution (by Cholesky factorization), error-bound and condition estimate for a real symmetric positive definite system of linear equations

 To solve the equations

where $ A$ is the symmetric positive definite matrix

Error estimates for the solutions, information on equilibration and an estimateof the reciprocal of the condition number of the scaled matrix $ A$ are alsooutput.

Data

DPOSVX Example Program Data
  4      2                   :Values of N and NRHS
  4.16  -3.12   0.56  -0.10
         5.03  -0.83   1.18
                0.76   0.34
                       1.18 :End of matrix A
   8.70  8.30
 -13.35  2.13
   1.89  1.61
  -4.14  5.00               :End of matrix B

Result

 DPOSVX Example Program Results

 Solution(s)
             1          2
 1      1.0000     4.0000
 2     -1.0000     3.0000
 3      2.0000     2.0000
 4     -3.0000     1.0000

 Backward errors (machine-dependent)
       6.7E-17    7.9E-17

 Estimated forward error bounds (machine-dependent)
       2.3E-14    2.3E-14

 Estimate of reciprocal condition number
       1.0E-02

 A has not been equilibrated

Source

    Program dposvx_example

!     DPOSVX Example Program Text

!     Copyright 2017, Numerical Algorithms Group Ltd. http://www.nag.com

!     .. Use Statements ..
      Use lapack_example_aux, Only: nagf_file_print_matrix_real_gen
      Use lapack_interfaces, Only: dposvx
      Use lapack_precision, Only: dp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=dp) :: rcond
      Integer :: i, ifail, info, lda, ldaf, ldb, ldx, n, nrhs
      Character (1) :: equed
!     .. Local Arrays ..
      Real (Kind=dp), Allocatable :: a(:, :), af(:, :), b(:, :), berr(:), &
        ferr(:), s(:), work(:), x(:, :)
      Integer, Allocatable :: iwork(:)
!     .. Executable Statements ..
      Write (nout, *) 'DPOSVX Example Program Results'
      Write (nout, *)
      Flush (nout)
!     Skip heading in data file
      Read (nin, *)
      Read (nin, *) n, nrhs
      lda = n
      ldaf = n
      ldb = n
      ldx = n
      Allocate (a(lda,n), af(ldaf,n), b(ldb,nrhs), berr(nrhs), ferr(nrhs), &
        s(n), work(3*n), x(ldx,nrhs), iwork(n))

!     Read the upper triangular part of A from data file

      Read (nin, *)(a(i,i:n), i=1, n)

!     Read B from data file

      Read (nin, *)(b(i,1:nrhs), i=1, n)

!     Solve the equations AX = B for X
      Call dposvx('Equilibration', 'Upper', n, nrhs, a, lda, af, ldaf, equed, &
        s, b, ldb, x, ldx, rcond, ferr, berr, work, iwork, info)

      If ((info==0) .Or. (info==n+1)) Then

!       Print solution, error bounds, condition number and the form
!       of equilibration

!       ifail: behaviour on error exit
!              =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
        ifail = 0
        Call nagf_file_print_matrix_real_gen('General', ' ', n, nrhs, x, ldx, &
          'Solution(s)', ifail)

        Write (nout, *)
        Write (nout, *) 'Backward errors (machine-dependent)'
        Write (nout, 100) berr(1:nrhs)
        Write (nout, *)
        Write (nout, *) 'Estimated forward error bounds (machine-dependent)'
        Write (nout, 100) ferr(1:nrhs)
        Write (nout, *)
        Write (nout, *) 'Estimate of reciprocal condition number'
        Write (nout, 100) rcond
        Write (nout, *)
        If (equed=='N') Then
          Write (nout, *) 'A has not been equilibrated'
        Else If (equed=='Y') Then
          Write (nout, *) &
            'A has been row and column scaled as diag(S)*A*diag(S)'
        End If

        If (info==n+1) Then
          Write (nout, *)
          Write (nout, *) 'The matrix A is singular to working precision'
        End If
      Else
        Write (nout, 110) 'The leading minor of order ', info, &
          ' is not positive definite'
      End If

100   Format ((3X,1P,7E11.1))
110   Format (1X, A, I3, A)
    End Program
Full documentation of DPOSVX


DPPSV example

Real Linear Equations: Solution of a real symmetric positive definite system of linear equations, packed storage

 To solve the equations

where $ A$ is the symmetric positive definite matrix

Details of the Cholesky factorization of $ A$ are also output.

Data

DPPSV Example Program Data
  4                         :Value of N
  4.16  -3.12   0.56  -0.10
         5.03  -0.83   1.18
                0.76   0.34
                       1.18 :End of matrix A
  8.70 -13.35   1.89  -4.14 :End of vector b

Result

 DPPSV Example Program Results

 Solution
        1.0000    -1.0000     2.0000    -3.0000

 Cholesky factor
             1          2          3          4
 1      2.0396    -1.5297     0.2746    -0.0490
 2                 1.6401    -0.2500     0.6737
 3                            0.7887     0.6617
 4                                       0.5347

Source

    Program dppsv_example

!     DPPSV Example Program Text

!     Copyright 2017, Numerical Algorithms Group Ltd. http://www.nag.com

!     .. Use Statements ..
      Use lapack_example_aux, Only: nagf_file_print_matrix_real_packed
      Use lapack_interfaces, Only: dppsv
      Use lapack_precision, Only: dp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter :: nin = 5, nout = 6
      Character (1), Parameter :: uplo = 'U'
!     .. Local Scalars ..
      Integer :: i, ifail, info, j, n
!     .. Local Arrays ..
      Real (Kind=dp), Allocatable :: ap(:), b(:)
!     .. Executable Statements ..
      Write (nout, *) 'DPPSV Example Program Results'
      Write (nout, *)
!     Skip heading in data file
      Read (nin, *)
      Read (nin, *) n

      Allocate (ap((n*(n+1))/2), b(n))

!     Read the upper or lower triangular part of the matrix A from
!     data file

      If (uplo=='U') Then
        Read (nin, *)((ap(i+(j*(j-1))/2),j=i,n), i=1, n)
      Else If (uplo=='L') Then
        Read (nin, *)((ap(i+((2*n-j)*(j-1))/2),j=1,i), i=1, n)
      End If

!     Read b from data file

      Read (nin, *) b(1:n)

!     Solve the equations Ax = b for x
      Call dppsv(uplo, n, 1, ap, b, n, info)

      If (info==0) Then

!       Print solution

        Write (nout, *) 'Solution'
        Write (nout, 100) b(1:n)

!       Print details of factorization

        Write (nout, *)
        Flush (nout)

!       ifail: behaviour on error exit
!              =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
        ifail = 0
        Call nagf_file_print_matrix_real_packed(uplo, 'Non-unit diagonal', n, &
          ap, 'Cholesky factor', ifail)

      Else
        Write (nout, 110) 'The leading minor of order ', info, &
          ' is not positive definite'
      End If

100   Format ((3X,7F11.4))
110   Format (1X, A, I3, A)
    End Program
Full documentation of DPPSV


DPPSVX example

Real Linear Equations: Solution (by Cholesky factorization), error-bound and condition estimate for a real symmetric positive definite system of linear equations, packed storage

 To solve the equations

where $ A$ is the symmetric positive definite matrix

Error estimates for the solutions, information on equilibration and an estimateof the reciprocal of the condition number of the scaled matrix $ A$ are alsooutput.

Data

DPPSVX Example Program Data
  4      2                   :Values of N and NRHS
  4.16  -3.12   0.56  -0.10
         5.03  -0.83   1.18
                0.76   0.34
                       1.18 :End of matrix A
   8.70  8.30
 -13.35  2.13
   1.89  1.61
  -4.14  5.00               :End of matrix B

Result

 DPPSVX Example Program Results

 Solution(s)
             1          2
 1      1.0000     4.0000
 2     -1.0000     3.0000
 3      2.0000     2.0000
 4     -3.0000     1.0000

 Backward errors (machine-dependent)
       6.7E-17    7.9E-17

 Estimated forward error bounds (machine-dependent)
       2.3E-14    2.3E-14

 Estimate of reciprocal condition number
       1.0E-02

 A has not been equilibrated

Source

    Program dppsvx_example

!     DPPSVX Example Program Text

!     Copyright 2017, Numerical Algorithms Group Ltd. http://www.nag.com

!     .. Use Statements ..
      Use lapack_example_aux, Only: nagf_file_print_matrix_real_gen
      Use lapack_interfaces, Only: dppsvx
      Use lapack_precision, Only: dp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter :: nin = 5, nout = 6
      Character (1), Parameter :: uplo = 'U'
!     .. Local Scalars ..
      Real (Kind=dp) :: rcond
      Integer :: i, ifail, info, j, ldb, ldx, n, nrhs
      Character (1) :: equed
!     .. Local Arrays ..
      Real (Kind=dp), Allocatable :: afp(:), ap(:), b(:, :), berr(:), ferr(:), &
        s(:), work(:), x(:, :)
      Integer, Allocatable :: iwork(:)
!     .. Executable Statements ..
      Write (nout, *) 'DPPSVX Example Program Results'
      Write (nout, *)
      Flush (nout)
!     Skip heading in data file
      Read (nin, *)
      Read (nin, *) n, nrhs
      ldb = n
      ldx = n
      Allocate (afp((n*(n+1))/2), ap((n*(n+1))/2), b(ldb,nrhs), berr(nrhs), &
        ferr(nrhs), s(n), work(3*n), x(ldx,nrhs), iwork(n))

!     Read the upper or lower triangular part of the matrix A from
!     data file

      If (uplo=='U') Then
        Read (nin, *)((ap(i+(j*(j-1))/2),j=i,n), i=1, n)
      Else If (uplo=='L') Then
        Read (nin, *)((ap(i+((2*n-j)*(j-1))/2),j=1,i), i=1, n)
      End If

!     Read B from data file

      Read (nin, *)(b(i,1:nrhs), i=1, n)

!     Solve the equations AX = B for X
      Call dppsvx('Equilibration', uplo, n, nrhs, ap, afp, equed, s, b, ldb, &
        x, ldx, rcond, ferr, berr, work, iwork, info)

      If ((info==0) .Or. (info==n+1)) Then

!       Print solution, error bounds, condition number and the form
!       of equilibration

!       ifail: behaviour on error exit
!              =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
        ifail = 0
        Call nagf_file_print_matrix_real_gen('General', ' ', n, nrhs, x, ldx, &
          'Solution(s)', ifail)

        Write (nout, *)
        Write (nout, *) 'Backward errors (machine-dependent)'
        Write (nout, 100) berr(1:nrhs)
        Write (nout, *)
        Write (nout, *) 'Estimated forward error bounds (machine-dependent)'
        Write (nout, 100) ferr(1:nrhs)
        Write (nout, *)
        Write (nout, *) 'Estimate of reciprocal condition number'
        Write (nout, 100) rcond
        Write (nout, *)
        If (equed=='N') Then
          Write (nout, *) 'A has not been equilibrated'
        Else If (equed=='Y') Then
          Write (nout, *) &
            'A has been row and column scaled as diag(S)*A*diag(S)'
        End If

        If (info==n+1) Then
          Write (nout, *)
          Write (nout, *) 'The matrix A is singular to working precision'
        End If
      Else
        Write (nout, 110) 'The leading minor of order ', info, &
          ' is not positive definite'
      End If

100   Format ((3X,1P,7E11.1))
110   Format (1X, A, I3, A)
    End Program
Full documentation of DPPSVX


DPTSV example

Real Linear Equations: Solution of a real symmetric positive definite tridiagonal system of linear equations

 To solve the equations

where $ A$ is the symmetric positive definite tridiagonal matrix

Details of the $ L D L^T$ factorization of $ A$ are also output.

Data

DPTSV Example Program Data
  5                           :Value of N
  4.0  10.0  29.0  25.0   5.0 :End of diagonal D
 -2.0  -6.0  15.0   8.0       :End of sub-diagonal E
  6.0   9.0   2.0  14.0   7.0 :End of vector b

Result

 DPTSV Example Program Results

 Solution
      2.5000     2.0000     1.0000    -1.0000     3.0000

 Diagonal elements of the diagonal matrix D
      4.0000     9.0000    25.0000    16.0000     1.0000

 Subdiagonal elements of the Cholesky factor L
     -0.5000    -0.6667     0.6000     0.5000

Source

    Program dptsv_example

!     DPTSV Example Program Text

!     Copyright 2017, Numerical Algorithms Group Ltd. http://www.nag.com

!     .. Use Statements ..
      Use lapack_interfaces, Only: dptsv
      Use lapack_precision, Only: dp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter :: nin = 5, nout = 6
!     .. Local Scalars ..
      Integer :: info, n
!     .. Local Arrays ..
      Real (Kind=dp), Allocatable :: b(:), d(:), e(:)
!     .. Executable Statements ..
      Write (nout, *) 'DPTSV Example Program Results'
      Write (nout, *)
!     Skip heading in data file
      Read (nin, *)
      Read (nin, *) n

      Allocate (b(n), d(n), e(n-1))

!     Read the lower bidiagonal part of the tridiagonal matrix A and
!     the right hand side b from data file

      Read (nin, *) d(1:n)
      Read (nin, *) e(1:n-1)
      Read (nin, *) b(1:n)

!     Solve the equations Ax = b for x

      Call dptsv(n, 1, d, e, b, n, info)

      If (info==0) Then

!       Print solution

        Write (nout, *) 'Solution'
        Write (nout, 100) b(1:n)

!       Print details of factorization

        Write (nout, *)
        Write (nout, *) 'Diagonal elements of the diagonal matrix D'
        Write (nout, 100) d(1:n)
        Write (nout, *)
        Write (nout, *) 'Subdiagonal elements of the Cholesky factor L'
        Write (nout, 100) e(1:n-1)

      Else
        Write (nout, 110) 'The leading minor of order ', info, &
          ' is not positive definite'
      End If

100   Format (1X, 7F11.4)
110   Format (1X, A, I3, A)
    End Program
Full documentation of DPTSV


DPTSVX example

Real Linear Equations: Solution (by modified Cholesky factorization), error-bound and condition estimate for a real symmetric positive definite tridiagonal system of linear equations

 To solve the equations

where $ A$ is the symmetric positive definite tridiagonal matrix

Error estimates for the solutions and an estimate of the reciprocal of thecondition number of $ A$ are also output.

Data

DPTSVX Example Program Data
  5     2                     :Values of N and NRHS
  4.0  10.0  29.0  25.0   5.0 :End of diagonal D
 -2.0  -6.0  15.0   8.0       :End of sub-diagonal E
  6.0  10.0
  9.0   4.0
  2.0   9.0
 14.0  65.0
  7.0  23.0                   :End of matrix B

Result

 DPTSVX Example Program Results

 Solution(s)
             1          2
 1      2.5000     2.0000
 2      2.0000    -1.0000
 3      1.0000    -3.0000
 4     -1.0000     6.0000
 5      3.0000    -5.0000

 Backward errors (machine-dependent)
     0.0E+00    7.4E-17

 Estimated forward error bounds (machine-dependent)
     2.4E-14    4.7E-14

 Estimate of reciprocal condition number
     9.5E-03

Source

    Program dptsvx_example

!     DPTSVX Example Program Text

!     Copyright 2017, Numerical Algorithms Group Ltd. http://www.nag.com

!     .. Use Statements ..
      Use lapack_example_aux, Only: nagf_file_print_matrix_real_gen
      Use lapack_interfaces, Only: dptsvx
      Use lapack_precision, Only: dp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=dp) :: rcond
      Integer :: i, ifail, info, ldb, ldx, n, nrhs
!     .. Local Arrays ..
      Real (Kind=dp), Allocatable :: b(:, :), berr(:), d(:), df(:), e(:), &
        ef(:), ferr(:), work(:), x(:, :)
!     .. Executable Statements ..
      Write (nout, *) 'DPTSVX Example Program Results'
      Write (nout, *)
      Flush (nout)
!     Skip heading in data file
      Read (nin, *)
      Read (nin, *) n, nrhs
      ldb = n
      ldx = n
      Allocate (b(ldb,nrhs), berr(nrhs), d(n), df(n), e(n-1), ef(n-1), &
        ferr(nrhs), work(2*n), x(ldx,nrhs))

!     Read the lower bidiagonal part of the tridiagonal matrix A and
!     the right hand side b from data file

      Read (nin, *) d(1:n)
      Read (nin, *) e(1:n-1)
      Read (nin, *)(b(i,1:nrhs), i=1, n)

!     Solve the equations AX = B for X

      Call dptsvx('Not factored', n, nrhs, d, e, df, ef, b, ldb, x, ldx, &
        rcond, ferr, berr, work, info)

      If ((info==0) .Or. (info==n+1)) Then

!       Print solution, error bounds and condition number

!       ifail: behaviour on error exit
!              =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
        ifail = 0
        Call nagf_file_print_matrix_real_gen('General', ' ', n, nrhs, x, ldx, &
          'Solution(s)', ifail)

        Write (nout, *)
        Write (nout, *) 'Backward errors (machine-dependent)'
        Write (nout, 100) berr(1:nrhs)
        Write (nout, *)
        Write (nout, *) 'Estimated forward error bounds (machine-dependent)'
        Write (nout, 100) ferr(1:nrhs)
        Write (nout, *)
        Write (nout, *) 'Estimate of reciprocal condition number'
        Write (nout, 100) rcond

        If (info==n+1) Then
          Write (nout, *)
          Write (nout, *) 'The matrix A is singular to working precision'
        End If
      Else
        Write (nout, 110) 'The leading minor of order ', info, &
          ' is not positive definite'
      End If

100   Format (1X, 1P, 7E11.1)
110   Format (1X, A, I3, A)
    End Program
Full documentation of DPTSVX


DSGESV example

Real Linear Equations: Computes the solution to a real system of linear equations using mixed precision arithmetic

Data

DSGESV Example Program Data

  4     1                     :Value of N, R

  1.80   2.88   2.05  -0.89
  5.25  -2.95  -0.95  -3.80
  1.58  -2.69  -2.90  -1.04
 -1.11  -0.66  -0.59   0.80   :End of matrix A

  9.52  24.35   0.77  -6.22   :End of vector b

Result

 DSGESV Example Program Results

 Solution
        1.0000    -1.0000     3.0000    -5.0000

 Pivot indices
             2          2          3          4

Source

    Program dsgesv_example

!     DSGESV Example Program Text

!     Copyright 2017, Numerical Algorithms Group Ltd. http://www.nag.com

!     .. Use Statements ..
      Use lapack_interfaces, Only: dsgesv
      Use lapack_precision, Only: sp, dp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter :: nin = 5, nout = 6
!     .. Local Scalars ..
      Integer :: i, info, iter, lda, ldb, ldx, n, r
!     .. Local Arrays ..
      Real (Kind=dp), Allocatable :: a(:, :), b(:, :), work(:), x(:, :)
      Real (Kind=sp), Allocatable :: swork(:)
      Integer, Allocatable :: ipiv(:)
!     .. Executable Statements ..
      Write (nout, *) 'DSGESV Example Program Results'
      Write (nout, *)
!     Skip heading in data file
      Read (nin, *)
      Read (nin, *) n, r
      lda = n
      ldb = n
      ldx = n
      Allocate (a(lda,n), b(n,r), work(n*r), x(ldx,r), swork(n*(n+ &
        r)), ipiv(n))

!     Read A and B from data file

      Read (nin, *)(a(i,1:n), i=1, n)
      Read (nin, *)(b(i,1:r), i=1, n)

!     Solve the equations Ax = b for x

      Call dsgesv(n, r, a, lda, ipiv, b, ldb, x, ldx, work, swork, iter, info)

      If (info==0) Then

!       Print solution

        Write (nout, *) 'Solution'
        Write (nout, 100)(x(i,1:r), i=1, n)

!       Print pivot indices

        Write (nout, *)
        Write (nout, *) 'Pivot indices'
        Write (nout, 110) ipiv(1:n)

      Else
        Write (nout, 120) 'The (', info, ',', info, ')', &
          ' element of the factor U is zero'
      End If

100   Format ((3X,7F11.4))
110   Format ((3X,7I11))
120   Format (1X, A, I3, A, I3, A, A)
    End Program
Full documentation of DSGESV


DSPOSV example

Real Linear Equations: Computes the solution to a real symmetric positive definite system of linear equations using mixed precision arithmetic

Data

DSPOSV Example Program Data
  4     1                     :Value of N, R
  4.16  -3.12   0.56  -0.10
         5.03  -0.83   1.18
                0.76   0.34
                       1.18 :End of matrix A
  8.70 -13.35   1.89  -4.14 :End of vector b

Result

 DSPOSV Example Program Results

 Solution
        1.0000    -1.0000     2.0000    -3.0000

Source

    Program dsposv_example

!     DSPOSV Example Program Text

!     Copyright 2017, Numerical Algorithms Group Ltd. http://www.nag.com

!     .. Use Statements ..
      Use lapack_interfaces, Only: dsposv
      Use lapack_precision, Only: sp, dp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter :: nin = 5, nout = 6
!     .. Local Scalars ..
      Integer :: i, info, iter, lda, ldb, ldx, n, r
!     .. Local Arrays ..
      Real (Kind=dp), Allocatable :: a(:, :), b(:, :), work(:, :), x(:, :)
      Real (Kind=sp), Allocatable :: swork(:)
!     .. Executable Statements ..
      Write (nout, *) 'DSPOSV Example Program Results'
      Write (nout, *)
!     Skip heading in data file
      Read (nin, *)
      Read (nin, *) n, r
      lda = n
      ldb = n
      ldx = n
      Allocate (a(lda,n), b(n,r), work(n,r), x(ldx,r), swork(n*(n+r)))

!     Read the upper triangular part of A from data file

      Read (nin, *)(a(i,i:n), i=1, n)

!     Read B from data file

      Read (nin, *)(b(i,1:r), i=1, n)

!     Solve the equations Ax = b for x
      Call dsposv('U', n, r, a, lda, b, ldb, x, ldx, work, swork, iter, info)

      If (info==0) Then

!       Print solution

        Write (nout, *) 'Solution'
        Write (nout, 100)(x(i,1:r), i=1, n)
      Else
        Write (nout, 110) 'The leading minor of order ', info, &
          ' is not positive definite'
      End If

100   Format ((3X,7F11.4))
110   Format ((1X,A,I3,A))
    End Program
Full documentation of DSPOSV


DSPSV example

Real Linear Equations: Solution of a real symmetric system of linear equations, packed storage

 To solve the equations

where $ A$ is the symmetric matrix

Details of the factorization of $ A$ are also output.

Data

DSPSV Example Program Data
  4                         :Value of N
 -1.81   2.06   0.63  -1.15
         1.15   1.87   4.20
               -0.21   3.87
                       2.07 :End of matrix A
  0.96   6.07   8.38   9.50 :End of vector b

Result

 DSPSV Example Program Results

 Solution
       -5.0000    -2.0000     1.0000     4.0000

 Details of the factorization
             1          2          3          4
 1      0.4074     0.3031    -0.5960     0.6537
 2                -2.5907     0.8115     0.2230
 3                            1.1500     4.2000
 4                                       2.0700

 Pivot indices
           1          2         -2         -2

Source

    Program dspsv_example

!     DSPSV Example Program Text

!     Copyright 2017, Numerical Algorithms Group Ltd. http://www.nag.com

!     .. Use Statements ..
      Use lapack_example_aux, Only: nagf_file_print_matrix_real_packed
      Use lapack_interfaces, Only: dspsv
      Use lapack_precision, Only: dp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter :: nin = 5, nout = 6
      Character (1), Parameter :: uplo = 'U'
!     .. Local Scalars ..
      Integer :: i, ifail, info, j, n
!     .. Local Arrays ..
      Real (Kind=dp), Allocatable :: ap(:), b(:)
      Integer, Allocatable :: ipiv(:)
!     .. Executable Statements ..
      Write (nout, *) 'DSPSV Example Program Results'
      Write (nout, *)
!     Skip heading in data file
      Read (nin, *)
      Read (nin, *) n

      Allocate (ap((n*(n+1))/2), b(n), ipiv(n))

!     Read the upper or lower triangular part of the matrix A from
!     data file

      If (uplo=='U') Then
        Read (nin, *)((ap(i+(j*(j-1))/2),j=i,n), i=1, n)
      Else If (uplo=='L') Then
        Read (nin, *)((ap(i+((2*n-j)*(j-1))/2),j=1,i), i=1, n)
      End If

!     Read b from data file

      Read (nin, *) b(1:n)

!     Solve the equations Ax = b for x
      Call dspsv(uplo, n, 1, ap, ipiv, b, n, info)

      If (info==0) Then

!       Print solution

        Write (nout, *) 'Solution'
        Write (nout, 100) b(1:n)

!       Print details of factorization

        Write (nout, *)
        Flush (nout)

!       ifail: behaviour on error exit
!              =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
        ifail = 0
        Call nagf_file_print_matrix_real_packed(uplo, 'Non-unit diagonal', n, &
          ap, 'Details of the factorization', ifail)

!       Print pivot indices

        Write (nout, *)
        Write (nout, *) 'Pivot indices'
        Write (nout, 110) ipiv(1:n)

      Else
        Write (nout, 120) 'The diagonal block ', info, ' of D is zero'
      End If

100   Format ((3X,7F11.4))
110   Format (1X, 7I11)
120   Format (1X, A, I3, A)
    End Program
Full documentation of DSPSV


DSPSVX example

Real Linear Equations: Solution (by diagonal pivoting factorization) of a real symmetric system of linear equations, packed storage

 To solve the equations

where $ A$ is the symmetric matrix

Error estimates for the solutions, and an estimate of the reciprocal of thecondition number of the matrix $ A$ are also output.

Data

DSPSVX Example Program Data
  4      2                  :Values of N and NRHS
 -1.81   2.06   0.63  -1.15
         1.15   1.87   4.20
               -0.21   3.87
                       2.07 :End of matrix A
  0.96   3.93
  6.07  19.25
  8.38   9.90
  9.50  27.85               :End of matrix B

Result

 DSPSVX Example Program Results

 Solution(s)
             1          2
 1     -5.0000     2.0000
 2     -2.0000     3.0000
 3      1.0000     4.0000
 4      4.0000     1.0000

 Backward errors (machine-dependent)
       1.4E-16    1.0E-16

 Estimated forward error bounds (machine-dependent)
       2.5E-14    3.2E-14

 Estimate of reciprocal condition number
       1.3E-02

Source

    Program dspsvx_example

!     DSPSVX Example Program Text

!     Copyright 2017, Numerical Algorithms Group Ltd. http://www.nag.com

!     .. Use Statements ..
      Use lapack_example_aux, Only: nagf_file_print_matrix_real_gen
      Use lapack_interfaces, Only: dspsvx
      Use lapack_precision, Only: dp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter :: nin = 5, nout = 6
      Character (1), Parameter :: uplo = 'U'
!     .. Local Scalars ..
      Real (Kind=dp) :: rcond
      Integer :: i, ifail, info, j, ldb, ldx, n, nrhs
!     .. Local Arrays ..
      Real (Kind=dp), Allocatable :: afp(:), ap(:), b(:, :), berr(:), ferr(:), &
        work(:), x(:, :)
      Integer, Allocatable :: ipiv(:), iwork(:)
!     .. Executable Statements ..
      Write (nout, *) 'DSPSVX Example Program Results'
      Write (nout, *)
      Flush (nout)
!     Skip heading in data file
      Read (nin, *)
      Read (nin, *) n, nrhs
      ldb = n
      ldx = n
      Allocate (afp((n*(n+1))/2), ap((n*(n+1))/2), b(ldb,nrhs), berr(nrhs), &
        ferr(nrhs), work(3*n), x(ldx,nrhs), ipiv(n), iwork(n))

!     Read the upper or lower triangular part of the matrix A from
!     data file

      If (uplo=='U') Then
        Read (nin, *)((ap(i+(j*(j-1))/2),j=i,n), i=1, n)
      Else If (uplo=='L') Then
        Read (nin, *)((ap(i+((2*n-j)*(j-1))/2),j=1,i), i=1, n)
      End If

!     Read B from data file

      Read (nin, *)(b(i,1:nrhs), i=1, n)

!     Solve the equations AX = B for X
      Call dspsvx('Not factored', uplo, n, nrhs, ap, afp, ipiv, b, ldb, x, &
        ldx, rcond, ferr, berr, work, iwork, info)

      If ((info==0) .Or. (info==n+1)) Then

!       Print solution, error bounds and condition number

!       ifail: behaviour on error exit
!              =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
        ifail = 0
        Call nagf_file_print_matrix_real_gen('General', ' ', n, nrhs, x, ldx, &
          'Solution(s)', ifail)

        Write (nout, *)
        Write (nout, *) 'Backward errors (machine-dependent)'
        Write (nout, 100) berr(1:nrhs)
        Write (nout, *)
        Write (nout, *) 'Estimated forward error bounds (machine-dependent)'
        Write (nout, 100) ferr(1:nrhs)
        Write (nout, *)
        Write (nout, *) 'Estimate of reciprocal condition number'
        Write (nout, 100) rcond
        Write (nout, *)

        If (info==n+1) Then
          Write (nout, *)
          Write (nout, *) 'The matrix A is singular to working precision'
        End If
      Else
        Write (nout, 110) 'The diagonal block ', info, ' of D is zero'
      End If

100   Format ((3X,1P,7E11.1))
110   Format (1X, A, I3, A)
    End Program
Full documentation of DSPSVX


DSYSV example

Real Linear Equations: Solution of a real symmetric system of linear equations

 To solve the equations

where $ A$ is the symmetric matrix

Details of the factorization of $ A$ are also output.

Data

DSYSV Example Program Data
  4                         :Value of N
 -1.81   2.06   0.63  -1.15
         1.15   1.87   4.20
               -0.21   3.87
                       2.07 :End of matrix A
  0.96   6.07   8.38   9.50 :End of vector b

Result

 DSYSV Example Program Results

 Solution
       -5.0000    -2.0000     1.0000     4.0000

 Details of the factorization
             1          2          3          4
 1      0.4074     0.3031    -0.5960     0.6537
 2                -2.5907     0.8115     0.2230
 3                            1.1500     4.2000
 4                                       2.0700

 Pivot indices
           1          2         -2         -2

Source

    Program dsysv_example

!     DSYSV Example Program Text

!     Copyright 2017, Numerical Algorithms Group Ltd. http://www.nag.com

!     .. Use Statements ..
      Use lapack_example_aux, Only: nagf_file_print_matrix_real_gen
      Use lapack_interfaces, Only: dsysv
      Use lapack_precision, Only: dp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter :: nb = 64, nin = 5, nout = 6
!     .. Local Scalars ..
      Integer :: i, ifail, info, lda, lwork, n
!     .. Local Arrays ..
      Real (Kind=dp), Allocatable :: a(:, :), b(:), work(:)
      Integer, Allocatable :: ipiv(:)
!     .. Executable Statements ..
      Write (nout, *) 'DSYSV Example Program Results'
      Write (nout, *)
!     Skip heading in data file
      Read (nin, *)
      Read (nin, *) n
      lda = n
      lwork = nb*n
      Allocate (a(lda,n), b(n), work(lwork), ipiv(n))

!     Read the upper triangular part of the matrix A from data file

      Read (nin, *)(a(i,i:n), i=1, n)

!     Read b from data file

      Read (nin, *) b(1:n)

!     Solve the equations Ax = b for x
      Call dsysv('Upper', n, 1, a, lda, ipiv, b, n, work, lwork, info)

      If (info==0) Then

!       Print solution

        Write (nout, *) 'Solution'
        Write (nout, 100) b(1:n)

!       Print details of factorization

        Write (nout, *)
        Flush (nout)

!       ifail: behaviour on error exit
!              =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
        ifail = 0
        Call nagf_file_print_matrix_real_gen('Upper', 'Non-unit diagonal', n, &
          n, a, lda, 'Details of the factorization', ifail)

!       Print pivot indices

        Write (nout, *)
        Write (nout, *) 'Pivot indices'
        Write (nout, 110) ipiv(1:n)

      Else
        Write (nout, 120) 'The diagonal block ', info, ' of D is zero'
      End If

100   Format ((3X,7F11.4))
110   Format (1X, 7I11)
120   Format (1X, A, I3, A)
    End Program
Full documentation of DSYSV


DSYSVX example

Real Linear Equations: Solution (by diagonal pivoting factorization) of a real symmetric system of linear equations

 To solve the equations

where $ A$ is the symmetric matrix

Error estimates for the solutions, and an estimate of the reciprocal of thecondition number of the matrix $ A$ are also output.

Data

DSYSVX Example Program Data
  4      2                  :Values of N and NRHS
 -1.81   2.06   0.63  -1.15
         1.15   1.87   4.20
               -0.21   3.87
                       2.07 :End of matrix A
  0.96   3.93
  6.07  19.25
  8.38   9.90
  9.50  27.85               :End of matrix B

Result

 DSYSVX Example Program Results

 Solution(s)
             1          2
 1     -5.0000     2.0000
 2     -2.0000     3.0000
 3      1.0000     4.0000
 4      4.0000     1.0000

 Backward errors (machine-dependent)
       1.4E-16    1.0E-16

 Estimated forward error bounds (machine-dependent)
       2.5E-14    3.2E-14

 Estimate of reciprocal condition number
       1.3E-02

Source

    Program dsysvx_example

!     DSYSVX Example Program Text

!     Copyright 2017, Numerical Algorithms Group Ltd. http://www.nag.com

!     .. Use Statements ..
      Use lapack_example_aux, Only: nagf_file_print_matrix_real_gen
      Use lapack_interfaces, Only: dsysvx
      Use lapack_precision, Only: dp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter :: nb = 64, nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=dp) :: rcond
      Integer :: i, ifail, info, lda, ldaf, ldb, ldx, lwork, n, nrhs
!     .. Local Arrays ..
      Real (Kind=dp), Allocatable :: a(:, :), af(:, :), b(:, :), berr(:), &
        ferr(:), work(:), x(:, :)
      Integer, Allocatable :: ipiv(:), iwork(:)
!     .. Executable Statements ..
      Write (nout, *) 'DSYSVX Example Program Results'
      Write (nout, *)
      Flush (nout)
!     Skip heading in data file
      Read (nin, *)
      Read (nin, *) n, nrhs
      lda = n
      ldaf = n
      ldb = n
      ldx = n
      lwork = nb*n
      Allocate (a(lda,n), af(ldaf,n), b(ldb,nrhs), berr(nrhs), ferr(nrhs), &
        work(lwork), x(ldx,nrhs), ipiv(n), iwork(n))

!     Read the upper triangular part of A from data file

      Read (nin, *)(a(i,i:n), i=1, n)

!     Read B from data file

      Read (nin, *)(b(i,1:nrhs), i=1, n)

!     Solve the equations AX = B for X
      Call dsysvx('Not factored', 'Upper', n, nrhs, a, lda, af, ldaf, ipiv, b, &
        ldb, x, ldx, rcond, ferr, berr, work, lwork, iwork, info)

      If ((info==0) .Or. (info==n+1)) Then

!       Print solution, error bounds and condition number

!       ifail: behaviour on error exit
!              =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
        ifail = 0
        Call nagf_file_print_matrix_real_gen('General', ' ', n, nrhs, x, ldx, &
          'Solution(s)', ifail)

        Write (nout, *)
        Write (nout, *) 'Backward errors (machine-dependent)'
        Write (nout, 100) berr(1:nrhs)
        Write (nout, *)
        Write (nout, *) 'Estimated forward error bounds (machine-dependent)'
        Write (nout, 100) ferr(1:nrhs)
        Write (nout, *)
        Write (nout, *) 'Estimate of reciprocal condition number'
        Write (nout, 100) rcond
        Write (nout, *)

        If (info==n+1) Then
          Write (nout, *)
          Write (nout, *) 'The matrix A is singular to working precision'
        End If
      Else
        Write (nout, 110) 'The diagonal block ', info, ' of D is zero'
      End If

100   Format ((3X,1P,7E11.1))
110   Format (1X, A, I3, A)
    End Program
Full documentation of DSYSVX


LAPACK:Complex Linear Equations

Next: Real Linear Least Squares Up: LAPACK Routines by Subject Previous: Real Linear Equations

Complex Linear Equations

  • ZCGESV : Computes the solution to a complex system of linear equations using mixed precision arithmetic
  • ZCPOSV : Computes the solution to a complex Hermitian positive definite system of linear equations using mixed precision arithmetic
  • ZGBSV : Solution of a complex banded system of linear equations
  • ZGBSVX : Solution (by LU factorization), error-bound and condition estimate for a complex banded system of linear equations
  • ZGESV : Solution of a complex system of linear equations
  • ZGESVX : Solution (by LU factorization), error-bound and condition estimate for a complex system of linear equations
  • ZGTSV : Solution of a complex tridiagonal system of linear equations
  • ZGTSVX : Solution (by LU factorization), error-bound and condition estimate for a complex tridiagonal system of linear equations
  • ZHESV : Solution of a complex Hermitian system of linear equations
  • ZHESVX : Solution(by diagonal pivoting factorization) of a complex Hermitian system of linear equations
  • ZHPSV : Solution of a complex Hermitian system of linear equations, packed storage
  • ZHPSVX : Solution (by diagonal pivoting factorization) of a complex Hermitian system of linear equations, packed storage
  • ZPBSV : Solution of a complex Hermitian positive definite banded system of linear equations
  • ZPBSVX : Solution (by Cholesky factorization), error-bound and condition estimate for a complex Hermitian positive definite banded system of linear equations
  • ZPOSV : Solution of a complex Hermitian positive definite system of linear equations
  • ZPOSVX : Solution (by Cholesky factorization), error-bound and condition estimate for a complex Hermitian positive definite system of linear equations
  • ZPPSV : Solution of a complex Hermitian positive definite system of linear equations, packed storage
  • ZPPSVX : Solution (by Cholesky factorization), error-bound and condition estimate for a complex Hermitian positive definite system of linear equations, packed storage
  • ZPTSV : Solution of a complex Hermitian positive definite tridiagonal system of linear equations
  • ZPTSVX : Solution (by modified Cholesky factorization), error-bound and condition estimate for a complex Hermitian positive definite tridiagonal system of linear equations
  • ZSPSV : Solution of a complex symmetric system of linear equations, packed storage
  • ZSPSVX : Solution (by diagonal pivoting factorization) of a complex symmetric system of linear equations, packed storage
  • ZSYSV : Solution of a complex symmetric system of linear equations
  • ZSYSVX : Solution (by diagonal pivoting factorization) of a complex symmetric system of linear equations


ZCGESV example

Complex Linear Equations: Computes the solution to a complex system of linear equations using mixed precision arithmetic

Data

ZCGESV Example Program Data

   4    1                                                 :Value of N, R

 (-1.34, 2.55) ( 0.28, 3.17) (-6.39,-2.20) ( 0.72,-0.92)
 (-0.17,-1.41) ( 3.31,-0.15) (-0.15, 1.34) ( 1.29, 1.38)
 (-3.29,-2.39) (-1.91, 4.42) (-0.14,-1.35) ( 1.72, 1.35)
 ( 2.41, 0.39) (-0.56, 1.47) (-0.83,-0.69) (-1.96, 0.67)  :End of matrix A

 (26.26,51.78) ( 6.43,-8.68) (-5.75,25.31) ( 1.16, 2.57)  :End of vector b

Result

 ZCGESV Example Program Results

 Solution
    ( 1.0000, 1.0000) ( 2.0000,-3.0000) (-4.0000,-5.0000) ( 0.0000, 6.0000)

 Pivot indices
           3          2          3          4

Source

    Program zcgesv_example

!     ZCGESV Example Program Text

!     Copyright 2017, Numerical Algorithms Group Ltd. http://www.nag.com

!     .. Use Statements ..
      Use lapack_interfaces, Only: zcgesv
      Use lapack_precision, Only: sp, dp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter :: nin = 5, nout = 6
!     .. Local Scalars ..
      Integer :: i, info, iter, j, lda, ldb, ldx, n, r
!     .. Local Arrays ..
      Complex (Kind=dp), Allocatable :: a(:, :), b(:, :), work(:), x(:, :)
      Complex (Kind=sp), Allocatable :: swork(:)
      Real (Kind=dp), Allocatable :: rwork(:)
      Integer, Allocatable :: ipiv(:)
!     .. Executable Statements ..
      Write (nout, *) 'ZCGESV Example Program Results'
      Write (nout, *)
!     Skip heading in data file
      Read (nin, *)
      Read (nin, *) n, r
      lda = n
      ldb = n
      ldx = n
      Allocate (a(lda,n), b(ldb,r), work(n*r), x(ldx,r), swork(n*(n+ &
        r)), ipiv(n), rwork(n))

!     Read A and B from data file

      Read (nin, *)(a(i,1:n), i=1, n)
      Read (nin, *)(b(i,1:r), i=1, n)

!     Solve the equations Ax = b for x

      Call zcgesv(n, r, a, lda, ipiv, b, ldb, x, ldx, work, swork, rwork, &
        iter, info)

      If (info==0) Then

!       Print solution

        Write (nout, *) 'Solution'
        Write (nout, 100)((x(i,r),j=1,r), i=1, n)

!       Print pivot indices

        Write (nout, *)
        Write (nout, *) 'Pivot indices'
        Write (nout, 110) ipiv(1:n)

      Else
        Write (nout, 120) 'The (', info, ',', info, ')', &
          ' element of the factor U is zero'
      End If

100   Format ((3X,4(' (',F7.4,',',F7.4,')',:)))
110   Format (1X, 7I11)
120   Format (1X, A, I3, A, I3, A, A)
    End Program
Full documentation of ZCGESV


ZCPOSV example

Complex Linear Equations: Computes the solution to a complex Hermitian positive definite system of linear equations using mixed precision arithmetic

Data

ZCPOSV Example Program Data
   4           1                                             :Values of N, R
 ( 3.23,  0.00) ( 1.51, -1.92) ( 1.90,  0.84) ( 0.42,  2.50)
                ( 3.58,  0.00) (-0.23,  1.11) (-1.18,  1.37)
                               ( 4.09,  0.00) ( 2.33, -0.14)
                                              ( 4.29,  0.00) :End of matrix A
 ( 3.93, -6.14) ( 6.17,  9.42) (-7.17,-21.83) ( 1.99,-14.38) :End of vector b

Result

 ZCPOSV Example Program Results

 Solution
    ( 1.0000,-1.0000) (-0.0000, 3.0000) (-4.0000,-5.0000) ( 2.0000, 1.0000)

Source

    Program zcposv_example

!     ZCPOSV Example Program Text

!     Copyright 2017, Numerical Algorithms Group Ltd. http://www.nag.com

!     .. Use Statements ..
      Use lapack_interfaces, Only: zcposv
      Use lapack_precision, Only: sp, dp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter :: nin = 5, nout = 6
!     .. Local Scalars ..
      Integer :: i, info, iter, lda, ldb, ldx, n, r
!     .. Local Arrays ..
      Complex (Kind=dp), Allocatable :: a(:, :), b(:, :), work(:, :), x(:, :)
      Complex (Kind=sp), Allocatable :: swork(:)
      Real (Kind=dp), Allocatable :: rwork(:)
!     .. Executable Statements ..
      Write (nout, *) 'ZCPOSV Example Program Results'
      Write (nout, *)
!     Skip heading in data file
      Read (nin, *)
      Read (nin, *) n, r
      lda = n
      ldb = n
      ldx = n
      Allocate (a(lda,n), b(ldb,r), work(n,r), x(ldx,r), swork(n*(n+ &
        r)), rwork(n))

!     Read A and B from data file

      Read (nin, *)(a(i,i:n), i=1, n)
      Read (nin, *)(b(i,1:r), i=1, n)

!     Solve the equations Ax = b for x
      Call zcposv('U', n, r, a, lda, b, ldb, x, ldx, work, swork, rwork, iter, &
        info)

      If (info==0) Then

!       Print solution

        Write (nout, *) 'Solution'
        Write (nout, 100)(x(i,1:r), i=1, n)

      Else
        Write (nout, 110) 'The leading minor of order ', info, &
          ' is not positive definite'
      End If

100   Format ((3X,4(' (',F7.4,',',F7.4,')',:)))
110   Format (1X, A, I3, A)
    End Program
Full documentation of ZCPOSV


ZGBSV example

Complex Linear Equations: Solution of a complex banded system of linear equations

 To solve the equations

where $ A$ is the band matrix

and

Details of the $ LU$ factorization of $ A$ are also output.

Data

ZGBSV Example Program Data
  4  1  2                                                :Values of N, KL and KU
 (-1.65,  2.26) ( -2.05, -0.85) (  0.97, -2.84)
 ( 0.00,  6.30) ( -1.48, -1.75) ( -3.99,  4.01) (  0.59, -0.48)
                ( -0.77,  2.83) ( -1.06,  1.94) (  3.33, -1.04)
                                (  4.48, -1.09) ( -0.46, -1.72) :End of matrix A
 (-1.06, 21.50) (-22.72,-53.90) ( 28.24,-38.60) (-34.56, 16.73) :End of vector B

Result

 ZGBSV Example Program Results

 Solution
    (-3.0000, 2.0000) ( 1.0000,-7.0000) (-5.0000, 4.0000) ( 6.0000,-8.0000)

 Details of factorization
   ( 0.0000, 6.3000) (-1.4800,-1.7500) (-3.9900, 4.0100) ( 0.5900,-0.4800)
   ( 0.3587, 0.2619) (-0.7700, 2.8300) (-1.0600, 1.9400) ( 3.3300,-1.0400)
                     ( 0.2314, 0.6358) ( 4.9303,-3.0086) (-1.7692,-1.8587)
                                       ( 0.7604, 0.2429) ( 0.4338, 0.1233)

 Pivot indices
     2                 3                 3                 4

Source

    Program zgbsv_example

!     ZGBSV Example Program Text

!     Copyright 2017, Numerical Algorithms Group Ltd. http://www.nag.com

!     .. Use Statements ..
      Use lapack_example_aux, Only: nagf_file_print_matrix_complex_band_comp
      Use lapack_interfaces, Only: zgbsv
      Use lapack_precision, Only: dp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter :: nin = 5, nout = 6
!     .. Local Scalars ..
      Integer :: i, ifail, info, j, k, kl, ku, ldab, n
!     .. Local Arrays ..
      Complex (Kind=dp), Allocatable :: ab(:, :), b(:)
      Integer, Allocatable :: ipiv(:)
      Character (1) :: clabs(1), rlabs(1)
!     .. Intrinsic Procedures ..
      Intrinsic :: max, min
!     .. Executable Statements ..
      Write (nout, *) 'ZGBSV Example Program Results'
      Write (nout, *)
!     Skip heading in data file
      Read (nin, *)
      Read (nin, *) n, kl, ku
      ldab = 2*kl + ku + 1
      Allocate (ab(ldab,n), b(n), ipiv(n))

!     Read the band matrix A and the right hand side b from data file

      k = kl + ku + 1
      Read (nin, *)((ab(k+i-j,j),j=max(i-kl,1),min(i+ku,n)), i=1, n)
      Read (nin, *) b(1:n)

!     Solve the equations Ax = b for x
      Call zgbsv(n, kl, ku, 1, ab, ldab, ipiv, b, n, info)

      If (info==0) Then

!       Print solution

        Write (nout, *) 'Solution'
        Write (nout, 100) b(1:n)

!       Print details of the factorization

        Write (nout, *)
        Flush (nout)

!       ifail: behaviour on error exit
!              =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
        ifail = 0
        Call nagf_file_print_matrix_complex_band_comp(n, n, kl, kl+ku, ab, &
          ldab, 'Bracketed', 'F7.4', 'Details of factorization', 'None', &
          rlabs, 'None', clabs, 80, 0, ifail)

!       Print pivot indices'

        Write (nout, *)
        Write (nout, *) 'Pivot indices'
        Write (nout, 110) ipiv(1:n)

      Else
        Write (nout, 120) 'The (', info, ',', info, ')', &
          ' element of the factor U is zero'
      End If

100   Format ((3X,4(' (',F7.4,',',F7.4,')',:)))
110   Format (1X, I5, 3I18)
120   Format (1X, A, I3, A, I3, A, A)
    End Program
Full documentation of ZGBSV


ZGBSVX example

Complex Linear Equations: Solution (by LU factorization), error-bound and condition estimate for a complex banded system of linear equations

 To solve the equations

where $ A$ is the band matrix

and

Estimates for the backward errors, forward errors, condition number and pivotgrowth are also output, together with information on the equilibration of $ A$.

Data

ZGBSVX Example Program Data
  4  2  1  2                                       :Values of N, NRHS, KL and KU
 (-1.65, 2.26) (-2.05,-0.85) ( 0.97,-2.84)
 ( 0.00, 6.30) (-1.48,-1.75) (-3.99, 4.01) ( 0.59,-0.48)
               (-0.77, 2.83) (-1.06, 1.94) ( 3.33,-1.04)
                             ( 4.48,-1.09) (-0.46,-1.72)  :End of matrix A
 ( -1.06, 21.50) ( 12.85,  2.84)
 (-22.72,-53.90) (-70.22, 21.57)
 ( 28.24,-38.60) (-20.73, -1.23)
 (-34.56, 16.73) ( 26.01, 31.97)                          :End of matrix B

Result

 ZGBSVX Example Program Results

 Solution(s)
                    1                 2
 1  (-3.0000, 2.0000) ( 1.0000, 6.0000)
 2  ( 1.0000,-7.0000) (-7.0000,-4.0000)
 3  (-5.0000, 4.0000) ( 3.0000, 5.0000)
 4  ( 6.0000,-8.0000) (-8.0000, 2.0000)

 Backward errors (machine-dependent)
       1.8E-17    5.1E-17

 Estimated forward error bounds (machine-dependent)
       3.5E-14    4.3E-14

 Estimate of reciprocal condition number
       9.6E-03

 A has not been equilibrated

 Estimate of reciprocal pivot growth factor
       1.0E+00

Source

    Program zgbsvx_example

!     ZGBSVX Example Program Text

!     Copyright 2017, Numerical Algorithms Group Ltd. http://www.nag.com

!     .. Use Statements ..
      Use lapack_example_aux, Only: nagf_file_print_matrix_complex_gen_comp
      Use lapack_interfaces, Only: zgbsvx
      Use lapack_precision, Only: dp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=dp) :: rcond
      Integer :: i, ifail, info, j, k, kl, ku, ldab, ldafb, ldb, ldx, n, nrhs
      Character (1) :: equed
!     .. Local Arrays ..
      Complex (Kind=dp), Allocatable :: ab(:, :), afb(:, :), b(:, :), work(:), &
        x(:, :)
      Real (Kind=dp), Allocatable :: berr(:), c(:), ferr(:), r(:), rwork(:)
      Integer, Allocatable :: ipiv(:)
      Character (1) :: clabs(1), rlabs(1)
!     .. Intrinsic Procedures ..
      Intrinsic :: max, min
!     .. Executable Statements ..
      Write (nout, *) 'ZGBSVX Example Program Results'
      Write (nout, *)
      Flush (nout)
!     Skip heading in data file
      Read (nin, *)
      Read (nin, *) n, nrhs, kl, ku
      ldb = n
      ldx = n
      ldab = kl + ku + 1
      ldafb = ldab + kl
      Allocate (ab(ldab,n), afb(ldafb,n), b(ldb,nrhs), work(2*n), x(ldx,nrhs), &
        berr(nrhs), c(n), ferr(nrhs), r(n), rwork(n), ipiv(n))

!     Read the band matrix A and B from data file

      k = ku + 1
      Read (nin, *)((ab(k+i-j,j),j=max(i-kl,1),min(i+ku,n)), i=1, n)
      Read (nin, *)(b(i,1:nrhs), i=1, n)

!     Solve the equations AX = B for X

      Call zgbsvx('Equilibration', 'No transpose', n, kl, ku, nrhs, ab, ldab, &
        afb, ldafb, ipiv, equed, r, c, b, ldb, x, ldx, rcond, ferr, berr, &
        work, rwork, info)

      If ((info==0) .Or. (info==n+1)) Then

!       Print solution, error bounds, condition number, the form
!       of equilibration and the pivot growth factor

!       ifail: behaviour on error exit
!              =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
        ifail = 0
        Call nagf_file_print_matrix_complex_gen_comp('General', ' ', n, nrhs, &
          x, ldx, 'Bracketed', 'F7.4', 'Solution(s)', 'Integer', rlabs, &
          'Integer', clabs, 80, 0, ifail)

        Write (nout, *)
        Write (nout, *) 'Backward errors (machine-dependent)'
        Write (nout, 100) berr(1:nrhs)
        Write (nout, *)
        Write (nout, *) 'Estimated forward error bounds (machine-dependent)'
        Write (nout, 100) ferr(1:nrhs)
        Write (nout, *)
        Write (nout, *) 'Estimate of reciprocal condition number'
        Write (nout, 100) rcond
        Write (nout, *)
        If (equed=='N') Then
          Write (nout, *) 'A has not been equilibrated'
        Else If (equed=='R') Then
          Write (nout, *) 'A has been row scaled as diag(R)*A'
        Else If (equed=='C') Then
          Write (nout, *) 'A has been column scaled as A*diag(C)'
        Else If (equed=='B') Then
          Write (nout, *) &
            'A has been row and column scaled as diag(R)*A*diag(C)'
        End If
        Write (nout, *)
        Write (nout, *) 'Estimate of reciprocal pivot growth factor'
        Write (nout, 100) rwork(1)

        If (info==n+1) Then
          Write (nout, *)
          Write (nout, *) 'The matrix A is singular to working precision'
        End If
      Else
        Write (nout, 110) 'The (', info, ',', info, ')', &
          ' element of the factor U is zero'
      End If

100   Format ((3X,1P,7E11.1))
110   Format (1X, A, I3, A, I3, A, A)
    End Program
Full documentation of ZGBSVX


ZGESV example

Complex Linear Equations: Solution of a complex system of linear equations

 To find the singular values and left and right singular vectors of the 6 by 4matrix

together with approximate error bounds for the computed singular values andvectors.

The example program for ZGESDD illustrates finding a singular valuedecomposition for the case [image].

Data

ZGESV Example Program Data

   4                                                      :Value of N

 (-1.34, 2.55) ( 0.28, 3.17) (-6.39,-2.20) ( 0.72,-0.92)
 (-0.17,-1.41) ( 3.31,-0.15) (-0.15, 1.34) ( 1.29, 1.38)
 (-3.29,-2.39) (-1.91, 4.42) (-0.14,-1.35) ( 1.72, 1.35)
 ( 2.41, 0.39) (-0.56, 1.47) (-0.83,-0.69) (-1.96, 0.67)  :End of matrix A

 (26.26,51.78) ( 6.43,-8.68) (-5.75,25.31) ( 1.16, 2.57)  :End of vector b

Result

 ZGESV Example Program Results

 Solution
    ( 1.0000, 1.0000) ( 2.0000,-3.0000) (-4.0000,-5.0000) ( 0.0000, 6.0000)

 Details of factorization
                    1                 2                 3                 4
 1  (-3.2900,-2.3900) (-1.9100, 4.4200) (-0.1400,-1.3500) ( 1.7200, 1.3500)
 2  ( 0.2376, 0.2560) ( 4.8952,-0.7114) (-0.4623, 1.6966) ( 1.2269, 0.6190)
 3  (-0.1020,-0.7010) (-0.6691, 0.3689) (-5.1414,-1.1300) ( 0.9983, 0.3850)
 4  (-0.5359, 0.2707) (-0.2040, 0.8601) ( 0.0082, 0.1211) ( 0.1482,-0.1252)

 Pivot indices
           3          2          3          4

Source

    Program zgesv_example

!     ZGESV Example Program Text

!     Copyright 2017, Numerical Algorithms Group Ltd. http://www.nag.com

!     .. Use Statements ..
      Use lapack_example_aux, Only: nagf_file_print_matrix_complex_gen_comp
      Use lapack_interfaces, Only: zgesv
      Use lapack_precision, Only: dp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter :: nin = 5, nout = 6
!     .. Local Scalars ..
      Integer :: i, ifail, info, lda, ldb, n
!     .. Local Arrays ..
      Complex (Kind=dp), Allocatable :: a(:, :), b(:)
      Integer, Allocatable :: ipiv(:)
      Character (1) :: clabs(1), rlabs(1)
!     .. Executable Statements ..
      Write (nout, *) 'ZGESV Example Program Results'
      Write (nout, *)
!     Skip heading in data file
      Read (nin, *)
      Read (nin, *) n
      lda = n
      ldb = n
      Allocate (a(lda,n), b(ldb), ipiv(n))

!     Read A and B from data file

      Read (nin, *)(a(i,1:n), i=1, n)
      Read (nin, *) b(1:n)

!     Solve the equations Ax = b for x

      Call zgesv(n, 1, a, lda, ipiv, b, ldb, info)

      If (info==0) Then

!       Print solution

        Write (nout, *) 'Solution'
        Write (nout, 100) b(1:n)

!       Print details of factorization

        Write (nout, *)
        Flush (nout)

!       ifail: behaviour on error exit
!              =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
        ifail = 0
        Call nagf_file_print_matrix_complex_gen_comp('General', ' ', n, n, a, &
          lda, 'Bracketed', 'F7.4', 'Details of factorization', 'Integer', &
          rlabs, 'Integer', clabs, 80, 0, ifail)

!       Print pivot indices

        Write (nout, *)
        Write (nout, *) 'Pivot indices'
        Write (nout, 110) ipiv(1:n)
      Else
        Write (nout, 120) 'The (', info, ',', info, ')', &
          ' element of the factor U is zero'
      End If

100   Format ((3X,4(' (',F7.4,',',F7.4,')',:)))
110   Format (1X, 7I11)
120   Format (1X, A, I3, A, I3, A, A)
    End Program
Full documentation of ZGESV


ZGESVX example

Complex Linear Equations: Solution (by LU factorization), error-bound and condition estimate for a complex system of linear equations

 To solve the equations

where $ A$ is the general matrix

and

Error estimates for the solutions, information on scaling, an estimate of thereciprocal of the condition number of the scaled matrix $ A$ and an estimate ofthe reciprocal of the pivot growth factor for the factorization of $ A$ are alsooutput.

Data

ZGESVX Example Program Data

   4               2                                   :Values of N and NRHS

 (-1.34,  2.55) (  0.28,  3.17) (-6.39,-2.20) ( 0.72,-0.92)
 (-1.70,-14.10) ( 33.10, -1.50) (-1.50,13.40) (12.90,13.80)
 (-3.29, -2.39) ( -1.91,  4.42) (-0.14,-1.35) ( 1.72, 1.35)
 ( 2.41,  0.39) ( -0.56,  1.47) (-0.83,-0.69) (-1.96, 0.67) :End of matrix A

 (26.26, 51.78) ( 31.32, -6.70)
 (64.30,-86.80) (158.60,-14.20)
 (-5.75, 25.31) ( -2.15, 30.19)
 ( 1.16,  2.57) ( -2.56,  7.55)                             :End of matrix B

Result

 ZGESVX Example Program Results

 Solution(s)
                    1                 2
 1  ( 1.0000, 1.0000) (-1.0000,-2.0000)
 2  ( 2.0000,-3.0000) ( 5.0000, 1.0000)
 3  (-4.0000,-5.0000) (-3.0000, 4.0000)
 4  ( 0.0000, 6.0000) ( 2.0000,-3.0000)

 Backward errors (machine-dependent)
       5.3E-17    4.8E-17

 Estimated forward error bounds (machine-dependent)
       5.8E-14    7.4E-14

 A has been row scaled as diag(R)*A

 Reciprocal condition number estimate of scaled matrix
       1.0E-02

 Estimate of reciprocal pivot growth factor
       8.3E-01

Source

    Program zgesvx_example

!     ZGESVX Example Program Text

!     Copyright 2017, Numerical Algorithms Group Ltd. http://www.nag.com

!     .. Use Statements ..
      Use lapack_example_aux, Only: nagf_file_print_matrix_complex_gen_comp
      Use lapack_interfaces, Only: zgesvx
      Use lapack_precision, Only: dp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=dp) :: rcond
      Integer :: i, ifail, info, lda, ldaf, ldb, ldx, n, nrhs
      Character (1) :: equed
!     .. Local Arrays ..
      Complex (Kind=dp), Allocatable :: a(:, :), af(:, :), b(:, :), work(:), &
        x(:, :)
      Real (Kind=dp), Allocatable :: berr(:), c(:), ferr(:), r(:), rwork(:)
      Integer, Allocatable :: ipiv(:)
      Character (1) :: clabs(1), rlabs(1)
!     .. Executable Statements ..
      Write (nout, *) 'ZGESVX Example Program Results'
      Write (nout, *)
      Flush (nout)
!     Skip heading in data file
      Read (nin, *)
      Read (nin, *) n, nrhs
      lda = n
      ldaf = n
      ldb = n
      ldx = n
      Allocate (a(lda,n), af(ldaf,n), b(ldb,nrhs), work(2*n), x(ldx,nrhs), &
        berr(nrhs), c(n), ferr(nrhs), r(n), rwork(2*n), ipiv(n))

!     Read A and B from data file

      Read (nin, *)(a(i,1:n), i=1, n)
      Read (nin, *)(b(i,1:nrhs), i=1, n)

!     Solve the equations AX = B for X

      Call zgesvx('Equilibrate', 'No transpose', n, nrhs, a, lda, af, ldaf, &
        ipiv, equed, r, c, b, ldb, x, ldx, rcond, ferr, berr, work, rwork, &
        info)

      If ((info==0) .Or. (info==n+1)) Then

!       Print solution, error bounds, condition number, the form
!       of equilibration and the pivot growth factor

!       ifail: behaviour on error exit
!              =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
        ifail = 0
        Call nagf_file_print_matrix_complex_gen_comp('General', ' ', n, nrhs, &
          x, ldx, 'Bracketed', 'F7.4', 'Solution(s)', 'Integer', rlabs, &
          'Integer', clabs, 80, 0, ifail)

        Write (nout, *)
        Write (nout, *) 'Backward errors (machine-dependent)'
        Write (nout, 100) berr(1:nrhs)
        Write (nout, *)
        Write (nout, *) 'Estimated forward error bounds (machine-dependent)'
        Write (nout, 100) ferr(1:nrhs)
        Write (nout, *)
        If (equed=='N') Then
          Write (nout, *) 'A has not been equilibrated'
        Else If (equed=='R') Then
          Write (nout, *) 'A has been row scaled as diag(R)*A'
        Else If (equed=='C') Then
          Write (nout, *) 'A has been column scaled as A*diag(C)'
        Else If (equed=='B') Then
          Write (nout, *) &
            'A has been row and column scaled as diag(R)*A*diag(C)'
        End If
        Write (nout, *)
        Write (nout, *) &
          'Reciprocal condition number estimate of scaled matrix'
        Write (nout, 100) rcond
        Write (nout, *)
        Write (nout, *) 'Estimate of reciprocal pivot growth factor'
        Write (nout, 100) rwork(1)

        If (info==n+1) Then
          Write (nout, *)
          Write (nout, *) 'The matrix A is singular to working precision'
        End If
      Else
        Write (nout, 110) 'The (', info, ',', info, ')', &
          ' element of the factor U is zero'
      End If

100   Format ((3X,1P,7E11.1))
110   Format (1X, A, I3, A, I3, A, A)
    End Program
Full documentation of ZGESVX


ZGTSV example

Complex Linear Equations: Solution of a complex tridiagonal system of linear equations

 To solve the equations

where $ A$ is the tridiagonal matrix

and

Data

ZGTSV Example Program Data
   5                                                     :Value of N
 (  2.0, -1.0) (  2.0,  1.0) ( -1.0,  1.0) (  1.0, -1.0) :End of DU
 ( -1.3,  1.3) ( -1.3,  1.3) ( -1.3,  3.3) ( -0.3,  4.3)
 ( -3.3,  1.3)                                           :End of D
 (  1.0, -2.0) (  1.0 , 1.0) (  2.0, -3.0) (  1.0,  1.0) :End of  DL
 (  2.4, -5.0) (  3.4, 18.2) (-14.7,  9.7) ( 31.9, -7.7)
 ( -1.0,  1.6)                                           :End of B

Result

 ZGTSV Example Program Results

 Solution
 (  1.0000,  1.0000) (  3.0000, -1.0000) (  4.0000,  5.0000) ( -1.0000, -2.0000)
 (  1.0000, -1.0000)

Source

    Program zgtsv_example

!     ZGTSV Example Program Text

!     Copyright 2017, Numerical Algorithms Group Ltd. http://www.nag.com

!     .. Use Statements ..
      Use lapack_interfaces, Only: zgtsv
      Use lapack_precision, Only: dp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter :: nin = 5, nout = 6
!     .. Local Scalars ..
      Integer :: info, n
!     .. Local Arrays ..
      Complex (Kind=dp), Allocatable :: b(:), d(:), dl(:), du(:)
!     .. Executable Statements ..
      Write (nout, *) 'ZGTSV Example Program Results'
      Write (nout, *)
!     Skip heading in data file
      Read (nin, *)
      Read (nin, *) n

      Allocate (b(n), d(n), dl(n-1), du(n-1))

!     Read the tridiagonal matrix A and the right hand side B from
!     data file

      Read (nin, *) du(1:n-1)
      Read (nin, *) d(1:n)
      Read (nin, *) dl(1:n-1)
      Read (nin, *) b(1:n)

!     Solve the equations Ax = b for x
      Call zgtsv(n, 1, dl, d, du, b, n, info)

      If (info==0) Then

!       Print solution

        Write (nout, *) 'Solution'
        Write (nout, 100) b(1:n)

      Else
        Write (nout, 110) 'The (', info, ',', info, ')', &
          ' element of the factor U is zero'
      End If

100   Format (4(' (',F8.4,',',F8.4,')',:))
110   Format (1X, A, I3, A, I3, A, A)
    End Program
Full documentation of ZGTSV


ZGTSVX example

Complex Linear Equations: Solution (by LU factorization), error-bound and condition estimate for a complex tridiagonal system of linear equations

 To solve the equations

where $ A$ is the tridiagonal matrix

and

Estimates for the backward errors, forward errors and condition number are alsooutput.

Data

ZGTSVX Example Program Data
   5    2                                                :Values of N and NRHS
 (  2.0, -1.0) (  2.0,  1.0) ( -1.0,  1.0) (  1.0, -1.0) :End of DU
 ( -1.3,  1.3) ( -1.3,  1.3) ( -1.3,  3.3) ( -0.3,  4.3)
 ( -3.3,  1.3)                                           :End of D
 (  1.0, -2.0) (  1.0 , 1.0) (  2.0, -3.0) (  1.0,  1.0) :End of  DL
 (  2.4, -5.0) (  2.7,  6.9)
 (  3.4, 18.2) ( -6.9, -5.3)
 (-14.7,  9.7) ( -6.0, -0.6)
 ( 31.9, -7.7) ( -3.9,  9.3)
 ( -1.0,  1.6) ( -3.0, 12.2)                             :End of B

Result

 ZGTSVX Example Program Results

 Solution(s)
                    1                 2
 1  ( 1.0000, 1.0000) ( 2.0000,-1.0000)
 2  ( 3.0000,-1.0000) ( 1.0000, 2.0000)
 3  ( 4.0000, 5.0000) (-1.0000, 1.0000)
 4  (-1.0000,-2.0000) ( 2.0000, 1.0000)
 5  ( 1.0000,-1.0000) ( 2.0000,-2.0000)

 Backward errors (machine-dependent)
       7.2E-17    6.7E-17

 Estimated forward error bounds (machine-dependent)
       5.6E-14    7.4E-14

 Estimate of reciprocal condition number
       5.4E-03

Source

    Program zgtsvx_example

!     ZGTSVX Example Program Text

!     Copyright 2017, Numerical Algorithms Group Ltd. http://www.nag.com

!     .. Use Statements ..
      Use lapack_example_aux, Only: nagf_file_print_matrix_complex_gen_comp
      Use lapack_interfaces, Only: zgtsvx
      Use lapack_precision, Only: dp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=dp) :: rcond
      Integer :: i, ifail, info, ldb, ldx, n, nrhs
!     .. Local Arrays ..
      Complex (Kind=dp), Allocatable :: b(:, :), d(:), df(:), dl(:), dlf(:), &
        du(:), du2(:), duf(:), work(:), x(:, :)
      Real (Kind=dp), Allocatable :: berr(:), ferr(:), rwork(:)
      Integer, Allocatable :: ipiv(:)
      Character (1) :: clabs(1), rlabs(1)
!     .. Executable Statements ..
      Write (nout, *) 'ZGTSVX Example Program Results'
      Write (nout, *)
      Flush (nout)
!     Skip heading in data file
      Read (nin, *)
      Read (nin, *) n, nrhs
      ldb = n
      ldx = n
      Allocate (b(ldb,nrhs), d(n), df(n), dl(n-1), dlf(n-1), du(n-1), &
        du2(n-2), duf(n-1), work(2*n), x(ldx,nrhs), berr(nrhs), ferr(nrhs), &
        rwork(n), ipiv(n))

!     Read the tridiagonal matrix A from data file

      Read (nin, *) du(1:n-1)
      Read (nin, *) d(1:n)
      Read (nin, *) dl(1:n-1)

!     Read the right hand matrix B

      Read (nin, *)(b(i,1:nrhs), i=1, n)

!     Solve the equations AX = B
      Call zgtsvx('No factors', 'No transpose', n, nrhs, dl, d, du, dlf, df, &
        duf, du2, ipiv, b, ldb, x, ldx, rcond, ferr, berr, work, rwork, info)

      If ((info==0) .Or. (info==n+1)) Then

!       Print solution, error bounds and condition number

!       ifail: behaviour on error exit
!              =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
        ifail = 0
        Call nagf_file_print_matrix_complex_gen_comp('General', ' ', n, nrhs, &
          x, ldx, 'Bracketed', 'F7.4', 'Solution(s)', 'Integer', rlabs, &
          'Integer', clabs, 80, 0, ifail)

        Write (nout, *)
        Write (nout, *) 'Backward errors (machine-dependent)'
        Write (nout, 100) berr(1:nrhs)
        Write (nout, *)
        Write (nout, *) 'Estimated forward error bounds (machine-dependent)'
        Write (nout, 100) ferr(1:nrhs)
        Write (nout, *)
        Write (nout, *) 'Estimate of reciprocal condition number'
        Write (nout, 100) rcond

        If (info==n+1) Then
          Write (nout, *)
          Write (nout, *) 'The matrix A is singular to working precision'
        End If
      Else
        Write (nout, 110) 'The (', info, ',', info, ')', &
          ' element of the factor U is zero'
      End If

100   Format ((3X,1P,7E11.1))
110   Format (1X, A, I3, A, I3, A, A)
    End Program
Full documentation of ZGTSVX


ZHESV example

Complex Linear Equations: Solution of a complex Hermitian system of linear equations

 To solve the equations

where $ A$ is the Hermitian matrix

and

Details of the factorization of $ A$ are also output.

Data

ZHESV Example Program Data
    4                                                            :Value of N
 ( -1.84,  0.00) (  0.11, -0.11) ( -1.78, -1.18) (  3.91, -1.50)
                 ( -4.63 , 0.00) ( -1.84,  0.03) (  2.21,  0.21)
                                 ( -8.87,  0.00) (  1.58, -0.90)
                                                 ( -1.36 , 0.00) :End matrix A
 (  2.98,-10.18) ( -9.58,  3.88) ( -0.77,-16.05) (  7.79,  5.48) :End vector b

Result

 ZHESV Example Program Results

 Solution
    ( 2.0000, 1.0000) ( 3.0000,-2.0000) (-1.0000, 2.0000) ( 1.0000,-1.0000)

 Details of the factorization
                    1                 2                 3                 4
 1  (-7.1028, 0.0000) ( 0.2997, 0.1578) ( 0.3397, 0.0303) (-0.1518, 0.3743)
 2                    (-5.4176, 0.0000) ( 0.5637, 0.2850) ( 0.3100, 0.0433)
 3                                      (-1.8400, 0.0000) ( 3.9100,-1.5000)
 4                                                        (-1.3600, 0.0000)

 Pivot indices
           1          2         -1         -1

Source

    Program zhesv_example

!     ZHESV Example Program Text

!     Copyright 2017, Numerical Algorithms Group Ltd. http://www.nag.com

!     .. Use Statements ..
      Use lapack_example_aux, Only: nagf_file_print_matrix_complex_gen_comp
      Use lapack_interfaces, Only: zhesv
      Use lapack_precision, Only: dp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter :: nb = 64, nin = 5, nout = 6
!     .. Local Scalars ..
      Integer :: i, ifail, info, lda, lwork, n
!     .. Local Arrays ..
      Complex (Kind=dp), Allocatable :: a(:, :), b(:), work(:)
      Integer, Allocatable :: ipiv(:)
      Character (1) :: clabs(1), rlabs(1)
!     .. Executable Statements ..
      Write (nout, *) 'ZHESV Example Program Results'
      Write (nout, *)
!     Skip heading in data file
      Read (nin, *)
      Read (nin, *) n
      lda = n
      lwork = nb*n
      Allocate (a(lda,n), b(n), work(lwork), ipiv(n))

!     Read the upper triangular part of the matrix A from data file

      Read (nin, *)(a(i,i:n), i=1, n)

!     Read b from data file

      Read (nin, *) b(1:n)

!     Solve the equations Ax = b for x
      Call zhesv('Upper', n, 1, a, lda, ipiv, b, n, work, lwork, info)

      If (info==0) Then

!       Print solution

        Write (nout, *) 'Solution'
        Write (nout, 100) b(1:n)

!       Print details of factorization

        Write (nout, *)
        Flush (nout)

!       ifail: behaviour on error exit
!              =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
        ifail = 0
        Call nagf_file_print_matrix_complex_gen_comp('Upper', &
          'Non-unit diagonal', n, n, a, lda, 'Bracketed', 'F7.4', &
          'Details of the factorization', 'Integer', rlabs, 'Integer', clabs, &
          80, 0, ifail)

!       Print pivot indices

        Write (nout, *)
        Write (nout, *) 'Pivot indices'
        Write (nout, 110) ipiv(1:n)

      Else
        Write (nout, 120) 'The diagonal block ', info, ' of D is zero'
      End If

100   Format ((3X,4(' (',F7.4,',',F7.4,')',:)))
110   Format (1X, 7I11)
120   Format (1X, A, I3, A)
    End Program
Full documentation of ZHESV


ZHESVX example

Complex Linear Equations: Solution(by diagonal pivoting factorization) of a complex Hermitian system of linear equations

 To solve the equations

where $ A$ is the Hermitian matrix

and

Error estimates for the solutions, and an estimate of the reciprocal of thecondition number of the matrix $ A$ are also output.

Data

ZHESVX Example Program Data
    4               2                                            :N and NRHS
 ( -1.84,  0.00) (  0.11, -0.11) ( -1.78, -1.18) (  3.91, -1.50)
                 ( -4.63 , 0.00) ( -1.84,  0.03) (  2.21,  0.21)
                                 ( -8.87,  0.00) (  1.58, -0.90)
                                                 ( -1.36 , 0.00) :End matrix A
 (  2.98,-10.18) ( 28.68,-39.89)
 ( -9.58,  3.88) (-24.79, -8.40)
 ( -0.77,-16.05) (  4.23,-70.02)
 (  7.79,  5.48) (-35.39, 18.01)                                 :End matrix B

Result

 ZHESVX Example Program Results

 Solution(s)
                    1                 2
 1  ( 2.0000, 1.0000) (-8.0000, 6.0000)
 2  ( 3.0000,-2.0000) ( 7.0000,-2.0000)
 3  (-1.0000, 2.0000) (-1.0000, 5.0000)
 4  ( 1.0000,-1.0000) ( 3.0000,-4.0000)

 Backward errors (machine-dependent)
       5.1E-17    5.9E-17

 Estimated forward error bounds (machine-dependent)
       2.5E-15    3.0E-15

 Estimate of reciprocal condition number
       1.5E-01

Source

    Program zhesvx_example

!     ZHESVX Example Program Text

!     Copyright 2017, Numerical Algorithms Group Ltd. http://www.nag.com

!     .. Use Statements ..
      Use lapack_example_aux, Only: nagf_file_print_matrix_complex_gen_comp
      Use lapack_interfaces, Only: zhesvx
      Use lapack_precision, Only: dp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter :: nb = 64, nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=dp) :: rcond
      Integer :: i, ifail, info, lda, ldaf, ldb, ldx, lwork, n, nrhs
!     .. Local Arrays ..
      Complex (Kind=dp), Allocatable :: a(:, :), af(:, :), b(:, :), work(:), &
        x(:, :)
      Real (Kind=dp), Allocatable :: berr(:), ferr(:), rwork(:)
      Integer, Allocatable :: ipiv(:)
      Character (1) :: clabs(1), rlabs(1)
!     .. Executable Statements ..
      Write (nout, *) 'ZHESVX Example Program Results'
      Write (nout, *)
      Flush (nout)
!     Skip heading in data file
      Read (nin, *)
      Read (nin, *) n, nrhs
      lda = n
      ldaf = n
      ldb = n
      ldx = n
      lwork = nb*n
      Allocate (a(lda,n), af(ldaf,n), b(ldb,nrhs), work(lwork), x(ldx,nrhs), &
        berr(nrhs), ferr(nrhs), rwork(n), ipiv(n))

!     Read the upper triangular part of A from data file

      Read (nin, *)(a(i,i:n), i=1, n)

!     Read B from data file

      Read (nin, *)(b(i,1:nrhs), i=1, n)

!     Solve the equations AX = B for X
      Call zhesvx('Not factored', 'Upper', n, nrhs, a, lda, af, ldaf, ipiv, b, &
        ldb, x, ldx, rcond, ferr, berr, work, lwork, rwork, info)

      If ((info==0) .Or. (info==n+1)) Then

!       Print solution, error bounds and condition number

!       ifail: behaviour on error exit
!              =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
        ifail = 0
        Call nagf_file_print_matrix_complex_gen_comp('General', ' ', n, nrhs, &
          x, ldx, 'Bracketed', 'F7.4', 'Solution(s)', 'Integer', rlabs, &
          'Integer', clabs, 80, 0, ifail)

        Write (nout, *)
        Write (nout, *) 'Backward errors (machine-dependent)'
        Write (nout, 100) berr(1:nrhs)
        Write (nout, *)
        Write (nout, *) 'Estimated forward error bounds (machine-dependent)'
        Write (nout, 100) ferr(1:nrhs)
        Write (nout, *)
        Write (nout, *) 'Estimate of reciprocal condition number'
        Write (nout, 100) rcond
        Write (nout, *)

        If (info==n+1) Then
          Write (nout, *)
          Write (nout, *) 'The matrix A is singular to working precision'
        End If
      Else
        Write (nout, 110) 'The diagonal block ', info, ' of D is zero'
      End If

100   Format ((3X,1P,7E11.1))
110   Format (1X, A, I3, A)
    End Program
Full documentation of ZHESVX


ZHPSV example

Complex Linear Equations: Solution of a complex Hermitian system of linear equations, packed storage

 To solve the equations

where $ A$ is the Hermitian matrix

and

Details of the factorization of $ A$ are also output.

Data

ZHPSV Example Program Data
    4                                                            :Value of N
 ( -1.84,  0.00) (  0.11, -0.11) ( -1.78, -1.18) (  3.91, -1.50)
                 ( -4.63 , 0.00) ( -1.84,  0.03) (  2.21,  0.21)
                                 ( -8.87,  0.00) (  1.58, -0.90)
                                                 ( -1.36 , 0.00) :End matrix A
 (  2.98,-10.18) ( -9.58,  3.88) ( -0.77,-16.05) (  7.79,  5.48) :End vector b

Result

 ZHPSV Example Program Results

 Solution
    ( 2.0000, 1.0000) ( 3.0000,-2.0000) (-1.0000, 2.0000) ( 1.0000,-1.0000)

 Details of factorization
                    1                 2                 3                 4
 1  (-7.1028, 0.0000) ( 0.2997, 0.1578) ( 0.3397, 0.0303) (-0.1518, 0.3743)
 2                    (-5.4176, 0.0000) ( 0.5637, 0.2850) ( 0.3100, 0.0433)
 3                                      (-1.8400, 0.0000) ( 3.9100,-1.5000)
 4                                                        (-1.3600, 0.0000)

 Pivot indices
           1          2         -1         -1

Source

    Program zhpsv_example

!     ZHPSV Example Program Text

!     Copyright 2017, Numerical Algorithms Group Ltd. http://www.nag.com

!     .. Use Statements ..
      Use lapack_example_aux, Only: nagf_file_print_matrix_complex_packed_comp
      Use lapack_interfaces, Only: zhpsv
      Use lapack_precision, Only: dp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter :: nin = 5, nout = 6
      Character (1), Parameter :: uplo = 'U'
!     .. Local Scalars ..
      Integer :: i, ifail, info, j, n
!     .. Local Arrays ..
      Complex (Kind=dp), Allocatable :: ap(:), b(:)
      Integer, Allocatable :: ipiv(:)
      Character (1) :: clabs(1), rlabs(1)
!     .. Executable Statements ..
      Write (nout, *) 'ZHPSV Example Program Results'
      Write (nout, *)
!     Skip heading in data file
      Read (nin, *)
      Read (nin, *) n

      Allocate (ap((n*(n+1))/2), b(n), ipiv(n))

!     Read the upper or lower triangular part of the matrix A from
!     data file

      If (uplo=='U') Then
        Read (nin, *)((ap(i+(j*(j-1))/2),j=i,n), i=1, n)
      Else If (uplo=='L') Then
        Read (nin, *)((ap(i+((2*n-j)*(j-1))/2),j=1,i), i=1, n)
      End If

!     Read b from data file

      Read (nin, *) b(1:n)

!     Solve the equations Ax = b for x
      Call zhpsv(uplo, n, 1, ap, ipiv, b, n, info)

      If (info==0) Then

!       Print solution

        Write (nout, *) 'Solution'
        Write (nout, 100) b(1:n)

!       Print details of factorization

        Write (nout, *)
        Flush (nout)

!       ifail: behaviour on error exit
!              =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
        ifail = 0
        Call nagf_file_print_matrix_complex_packed_comp(uplo, &
          'Non-unit diagonal', n, ap, 'Bracketed', 'F7.4', &
          'Details of factorization', 'Integer', rlabs, 'Integer', clabs, 80, &
          0, ifail)

!       Print pivot indices

        Write (nout, *)
        Write (nout, *) 'Pivot indices'
        Write (nout, 110) ipiv(1:n)

      Else
        Write (nout, 120) 'The diagonal block ', info, ' of D is zero'
      End If

100   Format ((3X,4(' (',F7.4,',',F7.4,')',:)))
110   Format (1X, 7I11)
120   Format (1X, A, I3, A)
    End Program
Full documentation of ZHPSV


ZHPSVX example

Complex Linear Equations: Solution (by diagonal pivoting factorization) of a complex Hermitian system of linear equations, packed storage

 To solve the equations

where $ A$ is the Hermitian matrix

and

Error estimates for the solutions, and an estimate of the reciprocal of thecondition number of the matrix $ A$ are also output.

Data

ZHPSVX Example Program Data
    4               2                                            :N and NRHS
 ( -1.84,  0.00) (  0.11, -0.11) ( -1.78, -1.18) (  3.91, -1.50)
                 ( -4.63 , 0.00) ( -1.84,  0.03) (  2.21,  0.21)
                                 ( -8.87,  0.00) (  1.58, -0.90)
                                                 ( -1.36 , 0.00) :End matrix A
 (  2.98,-10.18) ( 28.68,-39.89)
 ( -9.58,  3.88) (-24.79, -8.40)
 ( -0.77,-16.05) (  4.23,-70.02)
 (  7.79,  5.48) (-35.39, 18.01)                                 :End matrix B

Result

 ZHPSVX Example Program Results

 Solution(s)
                    1                 2
 1  ( 2.0000, 1.0000) (-8.0000, 6.0000)
 2  ( 3.0000,-2.0000) ( 7.0000,-2.0000)
 3  (-1.0000, 2.0000) (-1.0000, 5.0000)
 4  ( 1.0000,-1.0000) ( 3.0000,-4.0000)

 Backward errors (machine-dependent)
       5.1E-17    5.9E-17

 Estimated forward error bounds (machine-dependent)
       2.5E-15    3.0E-15

 Estimate of reciprocal condition number
       1.5E-01

Source

    Program zhpsvx_example

!     ZHPSVX Example Program Text

!     Copyright 2017, Numerical Algorithms Group Ltd. http://www.nag.com

!     .. Use Statements ..
      Use lapack_example_aux, Only: nagf_file_print_matrix_complex_gen_comp
      Use lapack_interfaces, Only: zhpsvx
      Use lapack_precision, Only: dp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter :: nin = 5, nout = 6
      Character (1), Parameter :: uplo = 'U'
!     .. Local Scalars ..
      Real (Kind=dp) :: rcond
      Integer :: i, ifail, info, j, ldb, ldx, n, nrhs
!     .. Local Arrays ..
      Complex (Kind=dp), Allocatable :: afp(:), ap(:), b(:, :), work(:), &
        x(:, :)
      Real (Kind=dp), Allocatable :: berr(:), ferr(:), rwork(:)
      Integer, Allocatable :: ipiv(:)
      Character (1) :: clabs(1), rlabs(1)
!     .. Executable Statements ..
      Write (nout, *) 'ZHPSVX Example Program Results'
      Write (nout, *)
      Flush (nout)
!     Skip heading in data file
      Read (nin, *)
      Read (nin, *) n, nrhs
      ldb = n
      ldx = n
      Allocate (afp((n*(n+1))/2), ap((n*(n+1))/2), b(ldb,nrhs), work(2*n), x( &
        ldx,nrhs), berr(nrhs), ferr(nrhs), rwork(n), ipiv(n))

!     Read the upper or lower triangular part of the matrix A from
!     data file

      If (uplo=='U') Then
        Read (nin, *)((ap(i+(j*(j-1))/2),j=i,n), i=1, n)
      Else If (uplo=='L') Then
        Read (nin, *)((ap(i+((2*n-j)*(j-1))/2),j=1,i), i=1, n)
      End If

!     Read B from data file

      Read (nin, *)(b(i,1:nrhs), i=1, n)

!     Solve the equations AX = B for X
      Call zhpsvx('Not factored', uplo, n, nrhs, ap, afp, ipiv, b, ldb, x, &
        ldx, rcond, ferr, berr, work, rwork, info)

      If ((info==0) .Or. (info==n+1)) Then

!       Print solution, error bounds and condition number

!       ifail: behaviour on error exit
!              =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
        ifail = 0
        Call nagf_file_print_matrix_complex_gen_comp('General', ' ', n, nrhs, &
          x, ldx, 'Bracketed', 'F7.4', 'Solution(s)', 'Integer', rlabs, &
          'Integer', clabs, 80, 0, ifail)

        Write (nout, *)
        Write (nout, *) 'Backward errors (machine-dependent)'
        Write (nout, 100) berr(1:nrhs)
        Write (nout, *)
        Write (nout, *) 'Estimated forward error bounds (machine-dependent)'
        Write (nout, 100) ferr(1:nrhs)
        Write (nout, *)
        Write (nout, *) 'Estimate of reciprocal condition number'
        Write (nout, 100) rcond
        Write (nout, *)

        If (info==n+1) Then
          Write (nout, *)
          Write (nout, *) 'The matrix A is singular to working precision'
        End If
      Else
        Write (nout, 110) 'The diagonal block ', info, ' of D is zero'
      End If

100   Format ((3X,1P,7E11.1))
110   Format (1X, A, I3, A)
    End Program
Full documentation of ZHPSVX


ZPBSV example

Complex Linear Equations: Solution of a complex Hermitian positive definite banded system of linear equations

 To solve the equations

where $ A$ is the Hermitian positive definite band matrix

and

Details of the Cholesky factorization of $ A$ are also output.

Data

ZPBSV Example Program Data

    4              1                                         :Values of N and KD

 (  9.39, 0.00) (  1.08,-1.73)
                (  1.69, 0.00) ( -0.04, 0.29)
                               (  2.65, 0.00) ( -0.33, 2.24)
                                              (  2.17, 0.00) :End of matrix A

 (-12.42,68.42) ( -9.93, 0.88) (-27.30,-0.01) (  5.31,23.63) :End of vector b

Result

 ZPBSV Example Program Results

 Solution
    (-1.0000, 8.0000) ( 2.0000,-3.0000) (-4.0000,-5.0000) ( 7.0000, 6.0000)

 Cholesky factor U
                    1                 2                 3                 4
 1  ( 3.0643, 0.0000) ( 0.3524,-0.5646)
 2                    ( 1.1167, 0.0000) (-0.0358, 0.2597)
 3                                      ( 1.6066, 0.0000) (-0.2054, 1.3942)
 4                                                        ( 0.4289, 0.0000)

Source

    Program zpbsv_example

!     ZPBSV Example Program Text

!     Copyright 2017, Numerical Algorithms Group Ltd. http://www.nag.com

!     .. Use Statements ..
      Use lapack_example_aux, Only: nagf_file_print_matrix_complex_band_comp
      Use lapack_interfaces, Only: zpbsv
      Use lapack_precision, Only: dp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter :: nin = 5, nout = 6
      Character (1), Parameter :: uplo = 'U'
!     .. Local Scalars ..
      Integer :: i, ifail, info, j, kd, ldab, n
!     .. Local Arrays ..
      Complex (Kind=dp), Allocatable :: ab(:, :), b(:)
      Character (1) :: clabs(1), rlabs(1)
!     .. Intrinsic Procedures ..
      Intrinsic :: max, min
!     .. Executable Statements ..
      Write (nout, *) 'ZPBSV Example Program Results'
      Write (nout, *)
!     Skip heading in data file
      Read (nin, *)
      Read (nin, *) n, kd
      ldab = kd + 1
      Allocate (ab(ldab,n), b(n))

!     Read the upper or lower triangular part of the band matrix A
!     from data file

      If (uplo=='U') Then
        Read (nin, *)((ab(kd+1+i-j,j),j=i,min(n,i+kd)), i=1, n)
      Else If (uplo=='L') Then
        Read (nin, *)((ab(1+i-j,j),j=max(1,i-kd),i), i=1, n)
      End If

!     Read b from data file

      Read (nin, *) b(1:n)

!     Solve the equations Ax = b for x
      Call zpbsv(uplo, n, kd, 1, ab, ldab, b, n, info)

      If (info==0) Then

!       Print solution

        Write (nout, *) 'Solution'
        Write (nout, 100) b(1:n)

!       Print details of factorization

        Write (nout, *)
        Flush (nout)

!       ifail: behaviour on error exit
!              =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
        ifail = 0
        If (uplo=='U') Then
          Call nagf_file_print_matrix_complex_band_comp(n, n, 0, kd, ab, ldab, &
            'Bracketed', 'F7.4', 'Cholesky factor U', 'Integer', rlabs, &
            'Integer', clabs, 80, 0, ifail)
        Else If (uplo=='L') Then
          Call nagf_file_print_matrix_complex_band_comp(n, n, kd, 0, ab, ldab, &
            'Bracketed', 'F7.4', 'Cholesky factor L', 'Integer', rlabs, &
            'Integer', clabs, 80, 0, ifail)
        End If

      Else
        Write (nout, 110) 'The leading minor of order ', info, &
          ' is not positive definite'
      End If

100   Format ((3X,4(' (',F7.4,',',F7.4,')',:)))
110   Format (1X, A, I3, A)
    End Program
Full documentation of ZPBSV


ZPBSVX example

Complex Linear Equations: Solution (by Cholesky factorization), error-bound and condition estimate for a complex Hermitian positive definite banded system of linear equations

 To solve the equations

where $ A$ is the Hermitian positive definite band matrix

and

Error estimates for the solutions, information on equilibration and an estimateof the reciprocal of the condition number of the scaled matrix $ A$ are alsooutput.

Data

ZPBSVX Example Program Data

    4              1              2                 :Values of N, KD and NRHS

 (  9.39, 0.00) (  1.08,-1.73)
                (  1.69, 0.00) ( -0.04, 0.29)
                               (  2.65, 0.00) ( -0.33, 2.24)
                                              (  2.17, 0.00) :End of matrix A

 (-12.42,68.42) (54.30,-56.56)
 ( -9.93, 0.88) (18.32,  4.76)
 (-27.30,-0.01) (-4.40,  9.97)
 (  5.31,23.63) ( 9.43,  1.41)                               :End of matrix B

Result

 ZPBSVX Example Program Results

 Solution(s)
                    1                 2
 1  (-1.0000, 8.0000) ( 5.0000,-6.0000)
 2  ( 2.0000,-3.0000) ( 2.0000, 3.0000)
 3  (-4.0000,-5.0000) (-8.0000, 4.0000)
 4  ( 7.0000, 6.0000) (-1.0000,-7.0000)

 Backward errors (machine-dependent)
       1.0E-16    1.1E-16

 Estimated forward error bounds (machine-dependent)
       3.6E-14    3.4E-14

 Estimate of reciprocal condition number
       7.6E-03

 A has not been equilibrated

Source

    Program zpbsvx_example

!     ZPBSVX Example Program Text

!     Copyright 2017, Numerical Algorithms Group Ltd. http://www.nag.com

!     .. Use Statements ..
      Use lapack_example_aux, Only: nagf_file_print_matrix_complex_gen_comp
      Use lapack_interfaces, Only: zpbsvx
      Use lapack_precision, Only: dp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter :: nin = 5, nout = 6
      Character (1), Parameter :: uplo = 'U'
!     .. Local Scalars ..
      Real (Kind=dp) :: rcond
      Integer :: i, ifail, info, j, kd, ldab, ldafb, ldb, ldx, n, nrhs
      Character (1) :: equed
!     .. Local Arrays ..
      Complex (Kind=dp), Allocatable :: ab(:, :), afb(:, :), b(:, :), work(:), &
        x(:, :)
      Real (Kind=dp), Allocatable :: berr(:), ferr(:), rwork(:), s(:)
      Character (1) :: clabs(1), rlabs(1)
!     .. Intrinsic Procedures ..
      Intrinsic :: max, min
!     .. Executable Statements ..
      Write (nout, *) 'ZPBSVX Example Program Results'
      Write (nout, *)
      Flush (nout)
!     Skip heading in data file
      Read (nin, *)
      Read (nin, *) n, kd, nrhs
      ldab = kd + 1
      ldafb = kd + 1
      ldb = n
      ldx = n
      Allocate (ab(ldab,n), afb(ldafb,n), b(ldb,nrhs), work(3*n), x(ldx,nrhs), &
        berr(nrhs), ferr(nrhs), rwork(n), s(n))

!     Read the upper or lower triangular part of the band matrix A
!     from data file

      If (uplo=='U') Then
        Read (nin, *)((ab(kd+1+i-j,j),j=i,min(n,i+kd)), i=1, n)
      Else If (uplo=='L') Then
        Read (nin, *)((ab(1+i-j,j),j=max(1,i-kd),i), i=1, n)
      End If

!     Read B from data file

      Read (nin, *)(b(i,1:nrhs), i=1, n)

!     Solve the equations AX = B for X
      Call zpbsvx('Equilibration', uplo, n, kd, nrhs, ab, ldab, afb, ldafb, &
        equed, s, b, ldb, x, ldx, rcond, ferr, berr, work, rwork, info)

      If ((info==0) .Or. (info==n+1)) Then

!       Print solution, error bounds, condition number and the form
!       of equilibration

!       ifail: behaviour on error exit
!              =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
        ifail = 0
        Call nagf_file_print_matrix_complex_gen_comp('General', ' ', n, nrhs, &
          x, ldx, 'Bracketed', 'F7.4', 'Solution(s)', 'Integer', rlabs, &
          'Integer', clabs, 80, 0, ifail)

        Write (nout, *)
        Write (nout, *) 'Backward errors (machine-dependent)'
        Write (nout, 100) berr(1:nrhs)
        Write (nout, *)
        Write (nout, *) 'Estimated forward error bounds (machine-dependent)'
        Write (nout, 100) ferr(1:nrhs)
        Write (nout, *)
        Write (nout, *) 'Estimate of reciprocal condition number'
        Write (nout, 100) rcond
        Write (nout, *)
        If (equed=='N') Then
          Write (nout, *) 'A has not been equilibrated'
        Else If (equed=='Y') Then
          Write (nout, *) &
            'A has been row and column scaled as diag(S)*A*diag(S)'
        End If

        If (info==n+1) Then
          Write (nout, *)
          Write (nout, *) 'The matrix A is singular to working precision'
        End If
      Else
        Write (nout, 110) 'The leading minor of order ', info, &
          ' is not positive definite'
      End If

100   Format ((3X,1P,7E11.1))
110   Format (1X, A, I3, A)
    End Program
Full documentation of ZPBSVX


ZPOSV example

Complex Linear Equations: Solution of a complex Hermitian positive definite system of linear equations

 To solve the equations

where $ A$ is the symmetric positive definite matrix

and

Details of the Cholesky factorization of $ A$ are also output.

Data

ZPOSV Example Program Data
   4                                                         :Value of N
 ( 3.23,  0.00) ( 1.51, -1.92) ( 1.90,  0.84) ( 0.42,  2.50)
                ( 3.58,  0.00) (-0.23,  1.11) (-1.18,  1.37)
                               ( 4.09,  0.00) ( 2.33, -0.14)
                                              ( 4.29,  0.00) :End of matrix A
 ( 3.93, -6.14) ( 6.17,  9.42) (-7.17,-21.83) ( 1.99,-14.38) :End of vector b

Result

 ZPOSV Example Program Results

 Solution
    ( 1.0000,-1.0000) (-0.0000, 3.0000) (-4.0000,-5.0000) ( 2.0000, 1.0000)

 Cholesky factor U
                    1                 2                 3                 4
 1  ( 1.7972, 0.0000) ( 0.8402,-1.0683) ( 1.0572, 0.4674) ( 0.2337, 1.3910)
 2                    ( 1.3164, 0.0000) (-0.4702,-0.3131) ( 0.0834,-0.0368)
 3                                      ( 1.5604, 0.0000) ( 0.9360,-0.9900)
 4                                                        ( 0.6603, 0.0000)

Source

    Program zposv_example

!     ZPOSV Example Program Text

!     Copyright 2017, Numerical Algorithms Group Ltd. http://www.nag.com

!     .. Use Statements ..
      Use lapack_example_aux, Only: nagf_file_print_matrix_complex_gen_comp
      Use lapack_interfaces, Only: zposv
      Use lapack_precision, Only: dp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter :: nin = 5, nout = 6
!     .. Local Scalars ..
      Integer :: i, ifail, info, lda, n
!     .. Local Arrays ..
      Complex (Kind=dp), Allocatable :: a(:, :), b(:)
      Character (1) :: clabs(1), rlabs(1)
!     .. Executable Statements ..
      Write (nout, *) 'ZPOSV Example Program Results'
      Write (nout, *)
      Flush (nout)
!     Skip heading in data file
      Read (nin, *)
      Read (nin, *) n
      lda = n
      Allocate (a(lda,n), b(n))

!     Read the upper triangular part of A from data file

      Read (nin, *)(a(i,i:n), i=1, n)

!     Read b from data file

      Read (nin, *) b(1:n)

!     Solve the equations Ax = b for x
      Call zposv('Upper', n, 1, a, lda, b, n, info)

      If (info==0) Then

!       Print solution

        Write (nout, *) 'Solution'
        Write (nout, 100) b(1:n)

!       Print details of factorization

        Write (nout, *)
        Flush (nout)

!       ifail: behaviour on error exit
!              =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
        ifail = 0
        Call nagf_file_print_matrix_complex_gen_comp('Upper', &
          'Non-unit diagonal', n, n, a, lda, 'Bracketed', 'F7.4', &
          'Cholesky factor U', 'Integer', rlabs, 'Integer', clabs, 80, 0, &
          ifail)

      Else
        Write (nout, 110) 'The leading minor of order ', info, &
          ' is not positive definite'
      End If

100   Format ((3X,4(' (',F7.4,',',F7.4,')',:)))
110   Format (1X, A, I3, A)
    End Program
Full documentation of ZPOSV


ZPOSVX example

Complex Linear Equations: Solution (by Cholesky factorization), error-bound and condition estimate for a complex Hermitian positive definite system of linear equations

 To solve the equations

where $ A$ is the Hermitian positive definite matrix

and

Error estimates for the solutions, information on equilibration and an estimateof the reciprocal of the condition number of the scaled matrix $ A$ are alsooutput.

Data

ZPOSVX Example Program Data
   4      2                                             :Values of N and NRHS
 ( 3.23,  0.00) ( 1.51, -1.92) ( 1.90,  0.84) ( 0.42,  2.50)
                ( 3.58,  0.00) (-0.23,  1.11) (-1.18,  1.37)
                               ( 4.09,  0.00) ( 2.33, -0.14)
                                              ( 4.29,  0.00) :End of matrix A
 ( 3.93, -6.14) ( 1.48,  6.58)
 ( 6.17,  9.42) ( 4.65, -4.75)
 (-7.17,-21.83) (-4.91,  2.29)
 ( 1.99,-14.38) ( 7.64,-10.79)                               :End of matrix B

Result

 ZPOSVX Example Program Results

 Solution(s)
                    1                 2
 1  ( 1.0000,-1.0000) (-1.0000, 2.0000)
 2  (-0.0000, 3.0000) ( 3.0000,-4.0000)
 3  (-4.0000,-5.0000) (-2.0000, 3.0000)
 4  ( 2.0000, 1.0000) ( 4.0000,-5.0000)

 Backward errors (machine-dependent)
       1.1E-16    5.3E-17

 Estimated forward error bounds (machine-dependent)
       6.0E-14    7.2E-14

 Estimate of reciprocal condition number
       6.6E-03

 A has not been equilibrated

Source

    Program zposvx_example

!     ZPOSVX Example Program Text

!     Copyright 2017, Numerical Algorithms Group Ltd. http://www.nag.com

!     .. Use Statements ..
      Use lapack_example_aux, Only: nagf_file_print_matrix_complex_gen_comp
      Use lapack_interfaces, Only: zposvx
      Use lapack_precision, Only: dp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=dp) :: rcond
      Integer :: i, ifail, info, lda, ldaf, ldb, ldx, n, nrhs
      Character (1) :: equed
!     .. Local Arrays ..
      Complex (Kind=dp), Allocatable :: a(:, :), af(:, :), b(:, :), work(:), &
        x(:, :)
      Real (Kind=dp), Allocatable :: berr(:), ferr(:), rwork(:), s(:)
      Character (1) :: clabs(1), rlabs(1)
!     .. Executable Statements ..
      Write (nout, *) 'ZPOSVX Example Program Results'
      Write (nout, *)
      Flush (nout)
!     Skip heading in data file
      Read (nin, *)
      Read (nin, *) n, nrhs
      lda = n
      ldaf = n
      ldb = n
      ldx = n
      Allocate (a(lda,n), af(ldaf,n), b(ldb,nrhs), work(2*n), x(ldx,nrhs), &
        berr(nrhs), ferr(nrhs), rwork(n), s(n))

!     Read the upper triangular part of A from data file

      Read (nin, *)(a(i,i:n), i=1, n)

!     Read B from data file

      Read (nin, *)(b(i,1:nrhs), i=1, n)

!     Solve the equations AX = B for X
      Call zposvx('Equilibration', 'Upper', n, nrhs, a, lda, af, ldaf, equed, &
        s, b, ldb, x, ldx, rcond, ferr, berr, work, rwork, info)

      If ((info==0) .Or. (info==n+1)) Then

!       Print solution, error bounds, condition number and the form
!       of equilibration

!       ifail: behaviour on error exit
!              =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
        ifail = 0
        Call nagf_file_print_matrix_complex_gen_comp('General', ' ', n, nrhs, &
          x, ldx, 'Bracketed', 'F7.4', 'Solution(s)', 'Integer', rlabs, &
          'Integer', clabs, 80, 0, ifail)

        Write (nout, *)
        Write (nout, *) 'Backward errors (machine-dependent)'
        Write (nout, 100) berr(1:nrhs)
        Write (nout, *)
        Write (nout, *) 'Estimated forward error bounds (machine-dependent)'
        Write (nout, 100) ferr(1:nrhs)
        Write (nout, *)
        Write (nout, *) 'Estimate of reciprocal condition number'
        Write (nout, 100) rcond
        Write (nout, *)
        If (equed=='N') Then
          Write (nout, *) 'A has not been equilibrated'
        Else If (equed=='Y') Then
          Write (nout, *) &
            'A has been row and column scaled as diag(S)*A*diag(S)'
        End If

        If (info==n+1) Then
          Write (nout, *)
          Write (nout, *) 'The matrix A is singular to working precision'
        End If
      Else
        Write (nout, 110) 'The leading minor of order ', info, &
          ' is not positive definite'
      End If

100   Format ((3X,1P,7E11.1))
110   Format (1X, A, I3, A)
    End Program
Full documentation of ZPOSVX


ZPPSV example

Complex Linear Equations: Solution of a complex Hermitian positive definite system of linear equations, packed storage

 To solve the equations

where $ A$ is the symmetric positive definite matrix

and

Details of the Cholesky factorization of $ A$ are also output.

Data

ZPPSV Example Program Data
   4                                                         :Value of N
 ( 3.23,  0.00) ( 1.51, -1.92) ( 1.90,  0.84) ( 0.42,  2.50)
                ( 3.58,  0.00) (-0.23,  1.11) (-1.18,  1.37)
                               ( 4.09,  0.00) ( 2.33, -0.14)
                                              ( 4.29,  0.00) :End of matrix A
 ( 3.93, -6.14) ( 6.17,  9.42) (-7.17,-21.83) ( 1.99,-14.38) :End of vector b

Result

 ZPPSV Example Program Results

 Solution
    ( 1.0000,-1.0000) (-0.0000, 3.0000) (-4.0000,-5.0000) ( 2.0000, 1.0000)

 Cholesky factor
                    1                 2                 3                 4
 1  ( 1.7972, 0.0000) ( 0.8402,-1.0683) ( 1.0572, 0.4674) ( 0.2337, 1.3910)
 2                    ( 1.3164, 0.0000) (-0.4702,-0.3131) ( 0.0834,-0.0368)
 3                                      ( 1.5604, 0.0000) ( 0.9360,-0.9900)
 4                                                        ( 0.6603, 0.0000)

Source

    Program zppsv_example

!     ZPPSV Example Program Text

!     Copyright 2017, Numerical Algorithms Group Ltd. http://www.nag.com

!     .. Use Statements ..
      Use lapack_example_aux, Only: nagf_file_print_matrix_complex_packed_comp
      Use lapack_interfaces, Only: zppsv
      Use lapack_precision, Only: dp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter :: nin = 5, nout = 6
      Character (1), Parameter :: uplo = 'U'
!     .. Local Scalars ..
      Integer :: i, ifail, info, j, n
!     .. Local Arrays ..
      Complex (Kind=dp), Allocatable :: ap(:), b(:)
      Character (1) :: clabs(1), rlabs(1)
!     .. Executable Statements ..
      Write (nout, *) 'ZPPSV Example Program Results'
      Write (nout, *)
!     Skip heading in data file
      Read (nin, *)
      Read (nin, *) n

      Allocate (ap((n*(n+1))/2), b(n))

!     Read the upper or lower triangular part of the matrix A from
!     data file

      If (uplo=='U') Then
        Read (nin, *)((ap(i+(j*(j-1))/2),j=i,n), i=1, n)
      Else If (uplo=='L') Then
        Read (nin, *)((ap(i+((2*n-j)*(j-1))/2),j=1,i), i=1, n)
      End If

!     Read b from data file

      Read (nin, *) b(1:n)

!     Solve the equations Ax = b for x
      Call zppsv(uplo, n, 1, ap, b, n, info)

      If (info==0) Then

!       Print solution

        Write (nout, *) 'Solution'
        Write (nout, 100) b(1:n)

!       Print details of factorization

        Write (nout, *)
        Flush (nout)

!       ifail: behaviour on error exit
!              =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
        ifail = 0
        Call nagf_file_print_matrix_complex_packed_comp(uplo, &
          'Non-unit diagonal', n, ap, 'Bracketed', 'F7.4', 'Cholesky factor', &
          'Integer', rlabs, 'Integer', clabs, 80, 0, ifail)

      Else
        Write (nout, 110) 'The leading minor of order ', info, &
          ' is not positive definite'
      End If

100   Format ((3X,4(' (',F7.4,',',F7.4,')',:)))
110   Format (1X, A, I3, A)
    End Program
Full documentation of ZPPSV


ZPPSVX example

Complex Linear Equations: Solution (by Cholesky factorization), error-bound and condition estimate for a complex Hermitian positive definite system of linear equations, packed storage

 To solve the equations

where $ A$ is the Hermitian positive definite matrix

and

Error estimates for the solutions, information on equilibration and an estimateof the reciprocal of the condition number of the scaled matrix $ A$ are alsooutput.

Data

ZPPSVX Example Program Data
   4      2                                             :Values of N and NRHS
 ( 3.23,  0.00) ( 1.51, -1.92) ( 1.90,  0.84) ( 0.42,  2.50)
                ( 3.58,  0.00) (-0.23,  1.11) (-1.18,  1.37)
                               ( 4.09,  0.00) ( 2.33, -0.14)
                                              ( 4.29,  0.00) :End of matrix A
 ( 3.93, -6.14) ( 1.48,  6.58)
 ( 6.17,  9.42) ( 4.65, -4.75)
 (-7.17,-21.83) (-4.91,  2.29)
 ( 1.99,-14.38) ( 7.64,-10.79)                               :End of matrix B

Result

 ZPPSVX Example Program Results

 Solution(s)
                    1                 2
 1  ( 1.0000,-1.0000) (-1.0000, 2.0000)
 2  (-0.0000, 3.0000) ( 3.0000,-4.0000)
 3  (-4.0000,-5.0000) (-2.0000, 3.0000)
 4  ( 2.0000, 1.0000) ( 4.0000,-5.0000)

 Backward errors (machine-dependent)
       1.1E-16    7.9E-17

 Estimated forward error bounds (machine-dependent)
       6.1E-14    7.4E-14

 Estimate of reciprocal condition number
       6.6E-03

 A has not been equilibrated

Source

    Program zppsvx_example

!     ZPPSVX Example Program Text

!     Copyright 2017, Numerical Algorithms Group Ltd. http://www.nag.com

!     .. Use Statements ..
      Use lapack_example_aux, Only: nagf_file_print_matrix_complex_gen_comp
      Use lapack_interfaces, Only: zppsvx
      Use lapack_precision, Only: dp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter :: nin = 5, nout = 6
      Character (1), Parameter :: uplo = 'U'
!     .. Local Scalars ..
      Real (Kind=dp) :: rcond
      Integer :: i, ifail, info, j, ldb, ldx, n, nrhs
      Character (1) :: equed
!     .. Local Arrays ..
      Complex (Kind=dp), Allocatable :: afp(:), ap(:), b(:, :), work(:), &
        x(:, :)
      Real (Kind=dp), Allocatable :: berr(:), ferr(:), rwork(:), s(:)
      Character (1) :: clabs(1), rlabs(1)
!     .. Executable Statements ..
      Write (nout, *) 'ZPPSVX Example Program Results'
      Write (nout, *)
      Flush (nout)
!     Skip heading in data file
      Read (nin, *)
      Read (nin, *) n, nrhs
      ldb = n
      ldx = n
      Allocate (afp((n*(n+1))/2), ap((n*(n+1))/2), b(ldb,nrhs), work(2*n), x( &
        ldx,nrhs), berr(nrhs), ferr(nrhs), rwork(n), s(n))

!     Read the upper or lower triangular part of the matrix A from
!     data file

      If (uplo=='U') Then
        Read (nin, *)((ap(i+(j*(j-1))/2),j=i,n), i=1, n)
      Else If (uplo=='L') Then
        Read (nin, *)((ap(i+((2*n-j)*(j-1))/2),j=1,i), i=1, n)
      End If

!     Read B from data file

      Read (nin, *)(b(i,1:nrhs), i=1, n)

!     Solve the equations AX = B for X
      Call zppsvx('Equilibration', uplo, n, nrhs, ap, afp, equed, s, b, ldb, &
        x, ldx, rcond, ferr, berr, work, rwork, info)

      If ((info==0) .Or. (info==n+1)) Then

!       Print solution, error bounds, condition number and the form
!       of equilibration

!       ifail: behaviour on error exit
!              =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
        ifail = 0
        Call nagf_file_print_matrix_complex_gen_comp('General', ' ', n, nrhs, &
          x, ldx, 'Bracketed', 'F7.4', 'Solution(s)', 'Integer', rlabs, &
          'Integer', clabs, 80, 0, ifail)

        Write (nout, *)
        Write (nout, *) 'Backward errors (machine-dependent)'
        Write (nout, 100) berr(1:nrhs)
        Write (nout, *)
        Write (nout, *) 'Estimated forward error bounds (machine-dependent)'
        Write (nout, 100) ferr(1:nrhs)
        Write (nout, *)
        Write (nout, *) 'Estimate of reciprocal condition number'
        Write (nout, 100) rcond
        Write (nout, *)
        If (equed=='N') Then
          Write (nout, *) 'A has not been equilibrated'
        Else If (equed=='Y') Then
          Write (nout, *) &
            'A has been row and column scaled as diag(S)*A*diag(S)'
        End If

        If (info==n+1) Then
          Write (nout, *)
          Write (nout, *) 'The matrix A is singular to working precision'
        End If
      Else
        Write (nout, 110) 'The leading minor of order ', info, &
          ' is not positive definite'
      End If

100   Format ((3X,1P,7E11.1))
110   Format (1X, A, I3, A)
    End Program
Full documentation of ZPPSVX


ZPTSV example

Complex Linear Equations: Solution of a complex Hermitian positive definite tridiagonal system of linear equations

 To solve the equations

where $ A$ is the Hermitian positive definite tridiagonal matrix

and

Details of the $ L D L^H$ factorization of $ A$ are also output.

Data

ZPTSV Example Program Data
    4                                                    :Value of N
   16.0          41.0          46.0          21.0        :End of diagonal D
 ( 16.0, 16.0) ( 18.0, -9.0) (  1.0, -4.0)               :End of sub-diagonal E
 ( 64.0, 16.0) ( 93.0, 62.0) ( 78.0,-80.0) ( 14.0,-27.0) :End of vector b

Result

 ZPTSV Example Program Results

 Solution
 (  2.0000,  1.0000) (  1.0000,  1.0000) (  1.0000, -2.0000) (  1.0000, -1.0000)

 Diagonal elements of the diagonal matrix D
  16.0000            9.0000            1.0000            4.0000

 Subdiagonal elements of the Cholesky factor L
 (  1.0000,  1.0000) (  2.0000, -1.0000) (  1.0000, -4.0000)

Source

    Program zptsv_example

!     ZPTSV Example Program Text

!     Copyright 2017, Numerical Algorithms Group Ltd. http://www.nag.com

!     .. Use Statements ..
      Use lapack_interfaces, Only: zptsv
      Use lapack_precision, Only: dp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter :: nin = 5, nout = 6
!     .. Local Scalars ..
      Integer :: info, n
!     .. Local Arrays ..
      Complex (Kind=dp), Allocatable :: b(:), e(:)
      Real (Kind=dp), Allocatable :: d(:)
!     .. Executable Statements ..
      Write (nout, *) 'ZPTSV Example Program Results'
      Write (nout, *)
!     Skip heading in data file
      Read (nin, *)
      Read (nin, *) n

      Allocate (b(n), e(n-1), d(n))

!     Read the lower bidiagonal part of the tridiagonal matrix A and
!     the right hand side b from data file

      Read (nin, *) d(1:n)
      Read (nin, *) e(1:n-1)
      Read (nin, *) b(1:n)

!     Solve the equations Ax = b for x
      Call zptsv(n, 1, d, e, b, n, info)

      If (info==0) Then

!       Print solution

        Write (nout, *) 'Solution'
        Write (nout, 100) b(1:n)

!       Print details of factorization

        Write (nout, *)
        Write (nout, *) 'Diagonal elements of the diagonal matrix D'
        Write (nout, 110) d(1:n)
        Write (nout, *)
        Write (nout, *) 'Subdiagonal elements of the Cholesky factor L'
        Write (nout, 100) e(1:n-1)

      Else
        Write (nout, 120) 'The leading minor of order ', info, &
          ' is not positive definite'
      End If

100   Format (4(' (',F8.4,',',F8.4,')',:))
110   Format ((2X,F7.4,3(11X,F7.4)))
120   Format (1X, A, I3, A)
    End Program
Full documentation of ZPTSV


ZPTSVX example

Complex Linear Equations: Solution (by modified Cholesky factorization), error-bound and condition estimate for a complex Hermitian positive definite tridiagonal system of linear equations

 To solve the equations

where $ A$ is the Hermitian positive definite tridiagonal matrix

and

Error estimates for the solutions and an estimate of the reciprocal of thecondition number of $ A$ are also output.

Data

ZPTSVX Example Program Data
    4             2                               :Values of N and NRHS
   16.0          41.0          46.0          21.0 :End of diagonal D
 ( 16.0, 16.0) ( 18.0, -9.0) (  1.0, -4.0)        :End of sub-diagonal E
 ( 64.0, 16.0) (-16.0,-32.0)
 ( 93.0, 62.0) ( 61.0,-66.0)
 ( 78.0,-80.0) ( 71.0,-74.0)
 ( 14.0,-27.0) ( 35.0, 15.0)                      :End of matrix B

Result

 ZPTSVX Example Program Results

 Solution(s)
                    1                 2
 1  ( 2.0000, 1.0000) (-3.0000,-2.0000)
 2  ( 1.0000, 1.0000) ( 1.0000, 1.0000)
 3  ( 1.0000,-2.0000) ( 1.0000,-2.0000)
 4  ( 1.0000,-1.0000) ( 2.0000, 1.0000)

 Backward errors (machine-dependent)
     0.0E+00    0.0E+00

 Estimated forward error bounds (machine-dependent)
     9.0E-12    6.1E-12

 Estimate of reciprocal condition number
     1.1E-04

Source

    Program zptsvx_example

!     ZPTSVX Example Program Text

!     Copyright 2017, Numerical Algorithms Group Ltd. http://www.nag.com

!     .. Use Statements ..
      Use lapack_example_aux, Only: nagf_file_print_matrix_complex_gen_comp
      Use lapack_interfaces, Only: zptsvx
      Use lapack_precision, Only: dp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=dp) :: rcond
      Integer :: i, ifail, info, ldb, ldx, n, nrhs
!     .. Local Arrays ..
      Complex (Kind=dp), Allocatable :: b(:, :), e(:), ef(:), work(:), x(:, :)
      Real (Kind=dp), Allocatable :: berr(:), d(:), df(:), ferr(:), rwork(:)
      Character (1) :: clabs(1), rlabs(1)
!     .. Executable Statements ..
      Write (nout, *) 'ZPTSVX Example Program Results'
      Write (nout, *)
      Flush (nout)
!     Skip heading in data file
      Read (nin, *)
      Read (nin, *) n, nrhs
      ldb = n
      ldx = n
      Allocate (b(ldb,nrhs), e(n-1), ef(n-1), work(n), x(ldx,nrhs), &
        berr(nrhs), d(n), df(n), ferr(nrhs), rwork(n))

!     Read the lower bidiagonal part of the tridiagonal matrix A and
!     the right hand side b from data file

      Read (nin, *) d(1:n)
      Read (nin, *) e(1:n-1)
      Read (nin, *)(b(i,1:nrhs), i=1, n)

!     Solve the equations AX = B for X
      Call zptsvx('Not factored', n, nrhs, d, e, df, ef, b, ldb, x, ldx, &
        rcond, ferr, berr, work, rwork, info)

      If ((info==0) .Or. (info==n+1)) Then

!       Print solution, error bounds and condition number

!       ifail: behaviour on error exit
!              =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
        ifail = 0
        Call nagf_file_print_matrix_complex_gen_comp('General', ' ', n, nrhs, &
          x, ldx, 'Bracketed', 'F7.4', 'Solution(s)', 'Integer', rlabs, &
          'Integer', clabs, 80, 0, ifail)

        Write (nout, *)
        Write (nout, *) 'Backward errors (machine-dependent)'
        Write (nout, 100) berr(1:nrhs)
        Write (nout, *)
        Write (nout, *) 'Estimated forward error bounds (machine-dependent)'
        Write (nout, 100) ferr(1:nrhs)
        Write (nout, *)
        Write (nout, *) 'Estimate of reciprocal condition number'
        Write (nout, 100) rcond

        If (info==n+1) Then
          Write (nout, *)
          Write (nout, *) 'The matrix A is singular to working precision'
        End If
      Else
        Write (nout, 110) 'The leading minor of order ', info, &
          ' is not positive definite'
      End If

100   Format (1X, 1P, 7E11.1)
110   Format (1X, A, I3, A)
    End Program
Full documentation of ZPTSVX


ZSPSV example

Complex Linear Equations: Solution of a complex symmetric system of linear equations, packed storage

 To solve the equations

where $ A$ is the complex symmetric matrix

and

Details of the factorization of $ A$ are also output.

Data

ZSPSV Example Program Data
    4                                                            :Value of N
 ( -0.56,  0.12) ( -1.54, -2.86) (  5.32, -1.59) (  3.80,  0.92)
                 ( -2.83 ,-0.03) ( -3.52,  0.58) ( -7.86, -2.96)
                                 (  8.86,  1.81) (  5.14, -0.64)
                                                 ( -0.39 ,-0.71) :End matrix A
 ( -6.43, 19.24) ( -0.49, -1.47) (-48.18, 66.00) (-55.64, 41.22) :End vector b

Result

 ZSPSV Example Program Results

 Solution
    (-4.0000, 3.0000) ( 3.0000,-2.0000) (-2.0000, 5.0000) ( 1.0000,-1.0000)

 Details of factorization
                    1                 2                 3                 4
 1  (-2.0954,-2.2011) (-0.1071,-0.3157) (-0.4823, 0.0150) ( 0.4426, 0.1936)
 2                    ( 4.4079, 5.3991) (-0.6078, 0.2811) ( 0.5279,-0.3715)
 3                                      (-2.8300,-0.0300) (-7.8600,-2.9600)
 4                                                        (-0.3900,-0.7100)

 Pivot indices
           1          2         -2         -2

Source

    Program zspsv_example

!     ZSPSV Example Program Text

!     Copyright 2017, Numerical Algorithms Group Ltd. http://www.nag.com

!     .. Use Statements ..
      Use lapack_example_aux, Only: nagf_file_print_matrix_complex_packed_comp
      Use lapack_interfaces, Only: zspsv
      Use lapack_precision, Only: dp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter :: nin = 5, nout = 6
      Character (1), Parameter :: uplo = 'U'
!     .. Local Scalars ..
      Integer :: i, ifail, info, j, n
!     .. Local Arrays ..
      Complex (Kind=dp), Allocatable :: ap(:), b(:)
      Integer, Allocatable :: ipiv(:)
      Character (1) :: clabs(1), rlabs(1)
!     .. Executable Statements ..
      Write (nout, *) 'ZSPSV Example Program Results'
      Write (nout, *)
!     Skip heading in data file
      Read (nin, *)
      Read (nin, *) n

      Allocate (ap((n*(n+1))/2), b(n), ipiv(n))

!     Read the upper or lower triangular part of the matrix A from
!     data file

      If (uplo=='U') Then
        Read (nin, *)((ap(i+(j*(j-1))/2),j=i,n), i=1, n)
      Else If (uplo=='L') Then
        Read (nin, *)((ap(i+((2*n-j)*(j-1))/2),j=1,i), i=1, n)
      End If

!     Read b from data file

      Read (nin, *) b(1:n)

!     Solve the equations Ax = b for x
      Call zspsv(uplo, n, 1, ap, ipiv, b, n, info)

      If (info==0) Then

!       Print solution

        Write (nout, *) 'Solution'
        Write (nout, 100) b(1:n)

!       Print details of factorization

        Write (nout, *)
        Flush (nout)

!       ifail: behaviour on error exit
!              =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
        ifail = 0
        Call nagf_file_print_matrix_complex_packed_comp(uplo, &
          'Non-unit diagonal', n, ap, 'Bracketed', 'F7.4', &
          'Details of factorization', 'Integer', rlabs, 'Integer', clabs, 80, &
          0, ifail)

!       Print pivot indices

        Write (nout, *)
        Write (nout, *) 'Pivot indices'
        Write (nout, 110) ipiv(1:n)

      Else
        Write (nout, 120) 'The diagonal block ', info, ' of D is zero'
      End If

100   Format ((3X,4(' (',F7.4,',',F7.4,')',:)))
110   Format (1X, 7I11)
120   Format (1X, A, I3, A)
    End Program
Full documentation of ZSPSV


ZSPSVX example

Complex Linear Equations: Solution (by diagonal pivoting factorization) of a complex symmetric system of linear equations, packed storage

 To solve the equations

where $ A$ is the complex symmetric matrix

and

Error estimates for the solutions, and an estimate of the reciprocal of thecondition number of the matrix $ A$ are also output.

Data

ZSPSVX Example Program Data
    4               2                                            :N and NRHS
 ( -0.56,  0.12) ( -1.54, -2.86) (  5.32, -1.59) (  3.80,  0.92)
                 ( -2.83 ,-0.03) ( -3.52,  0.58) ( -7.86, -2.96)
                                 (  8.86,  1.81) (  5.14, -0.64)
                                                 ( -0.39 ,-0.71) :End matrix A
 ( -6.43, 19.24) ( -4.59,-35.53)
 ( -0.49, -1.47) (  6.95, 20.49)
 (-48.18, 66.00) (-12.08,-27.02)
 (-55.64, 41.22) (-19.09,-35.97)                                 :End matrix B

Result

 ZSPSVX Example Program Results

 Solution(s)
                    1                 2
 1  (-4.0000, 3.0000) (-1.0000, 1.0000)
 2  ( 3.0000,-2.0000) ( 3.0000, 2.0000)
 3  (-2.0000, 5.0000) ( 1.0000,-3.0000)
 4  ( 1.0000,-1.0000) (-2.0000,-1.0000)

 Backward errors (machine-dependent)
       8.1E-17    3.0E-17

 Estimated forward error bounds (machine-dependent)
       1.2E-14    1.2E-14

 Estimate of reciprocal condition number
       4.9E-02

Source

    Program zspsvx_example

!     ZSPSVX Example Program Text

!     Copyright 2017, Numerical Algorithms Group Ltd. http://www.nag.com

!     .. Use Statements ..
      Use lapack_example_aux, Only: nagf_file_print_matrix_complex_gen_comp
      Use lapack_interfaces, Only: zspsvx
      Use lapack_precision, Only: dp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter :: nin = 5, nout = 6
      Character (1), Parameter :: uplo = 'U'
!     .. Local Scalars ..
      Real (Kind=dp) :: rcond
      Integer :: i, ifail, info, j, ldb, ldx, n, nrhs
!     .. Local Arrays ..
      Complex (Kind=dp), Allocatable :: afp(:), ap(:), b(:, :), work(:), &
        x(:, :)
      Real (Kind=dp), Allocatable :: berr(:), ferr(:), rwork(:)
      Integer, Allocatable :: ipiv(:)
      Character (1) :: clabs(1), rlabs(1)
!     .. Executable Statements ..
      Write (nout, *) 'ZSPSVX Example Program Results'
      Write (nout, *)
      Flush (nout)
!     Skip heading in data file
      Read (nin, *)
      Read (nin, *) n, nrhs
      ldb = n
      ldx = n
      Allocate (afp((n*(n+1))/2), ap((n*(n+1))/2), b(ldb,nrhs), work(2*n), x( &
        ldx,nrhs), berr(nrhs), ferr(nrhs), rwork(n), ipiv(n))

!     Read the upper or lower triangular part of the matrix A from
!     data file

      If (uplo=='U') Then
        Read (nin, *)((ap(i+(j*(j-1))/2),j=i,n), i=1, n)
      Else If (uplo=='L') Then
        Read (nin, *)((ap(i+((2*n-j)*(j-1))/2),j=1,i), i=1, n)
      End If

!     Read B from data file

      Read (nin, *)(b(i,1:nrhs), i=1, n)

!     Solve the equations AX = B for X
      Call zspsvx('Not factored', uplo, n, nrhs, ap, afp, ipiv, b, ldb, x, &
        ldx, rcond, ferr, berr, work, rwork, info)

      If ((info==0) .Or. (info==n+1)) Then

!       Print solution, error bounds and condition number

!       ifail: behaviour on error exit
!              =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
        ifail = 0
        Call nagf_file_print_matrix_complex_gen_comp('General', ' ', n, nrhs, &
          x, ldx, 'Bracketed', 'F7.4', 'Solution(s)', 'Integer', rlabs, &
          'Integer', clabs, 80, 0, ifail)

        Write (nout, *)
        Write (nout, *) 'Backward errors (machine-dependent)'
        Write (nout, 100) berr(1:nrhs)
        Write (nout, *)
        Write (nout, *) 'Estimated forward error bounds (machine-dependent)'
        Write (nout, 100) ferr(1:nrhs)
        Write (nout, *)
        Write (nout, *) 'Estimate of reciprocal condition number'
        Write (nout, 100) rcond
        Write (nout, *)

        If (info==n+1) Then
          Write (nout, *)
          Write (nout, *) 'The matrix A is singular to working precision'
        End If
      Else
        Write (nout, 110) 'The diagonal block ', info, ' of D is zero'
      End If

100   Format ((3X,1P,7E11.1))
110   Format (1X, A, I3, A)
    End Program
Full documentation of ZSPSVX


ZSYSV example

Complex Linear Equations: Solution of a complex symmetric system of linear equations

 To solve the equations

where $ A$ is the complex symmetric matrix

and

Details of the factorization of $ A$ are also output.

Data

ZSYSV Example Program Data
    4                                                            :Value of N
 ( -0.56,  0.12) ( -1.54, -2.86) (  5.32, -1.59) (  3.80,  0.92)
                 ( -2.83 ,-0.03) ( -3.52,  0.58) ( -7.86, -2.96)
                                 (  8.86,  1.81) (  5.14, -0.64)
                                                 ( -0.39 ,-0.71) :End matrix A
 ( -6.43, 19.24) ( -0.49, -1.47) (-48.18, 66.00) (-55.64, 41.22) :End vector b

Result

 ZSYSV Example Program Results

 Solution
    (-4.0000, 3.0000) ( 3.0000,-2.0000) (-2.0000, 5.0000) ( 1.0000,-1.0000)

 Details of the factorization
                    1                 2                 3                 4
 1  (-2.0954,-2.2011) (-0.1071,-0.3157) (-0.4823, 0.0150) ( 0.4426, 0.1936)
 2                    ( 4.4079, 5.3991) (-0.6078, 0.2811) ( 0.5279,-0.3715)
 3                                      (-2.8300,-0.0300) (-7.8600,-2.9600)
 4                                                        (-0.3900,-0.7100)

 Pivot indices
           1          2         -2         -2

Source

    Program zsysv_example

!     ZSYSV Example Program Text

!     Copyright 2017, Numerical Algorithms Group Ltd. http://www.nag.com

!     .. Use Statements ..
      Use lapack_example_aux, Only: nagf_file_print_matrix_complex_gen_comp
      Use lapack_interfaces, Only: zsysv
      Use lapack_precision, Only: dp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter :: nb = 64, nin = 5, nout = 6
!     .. Local Scalars ..
      Integer :: i, ifail, info, lda, lwork, n
!     .. Local Arrays ..
      Complex (Kind=dp), Allocatable :: a(:, :), b(:), work(:)
      Integer, Allocatable :: ipiv(:)
      Character (1) :: clabs(1), rlabs(1)
!     .. Executable Statements ..
      Write (nout, *) 'ZSYSV Example Program Results'
      Write (nout, *)
!     Skip heading in data file
      Read (nin, *)
      Read (nin, *) n
      lda = n
      lwork = nb*n
      Allocate (a(lda,n), b(n), work(lwork), ipiv(n))

!     Read the upper triangular part of the matrix A from data file

      Read (nin, *)(a(i,i:n), i=1, n)

!     Read b from data file

      Read (nin, *) b(1:n)

!     Solve the equations Ax = b for x

      Call zsysv('Upper', n, 1, a, lda, ipiv, b, n, work, lwork, info)

      If (info==0) Then

!       Print solution

        Write (nout, *) 'Solution'
        Write (nout, 100) b(1:n)

!       Print details of factorization

        Write (nout, *)
        Flush (nout)

!       ifail: behaviour on error exit
!              =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
        ifail = 0
        Call nagf_file_print_matrix_complex_gen_comp('Upper', &
          'Non-unit diagonal', n, n, a, lda, 'Bracketed', 'F7.4', &
          'Details of the factorization', 'Integer', rlabs, 'Integer', clabs, &
          80, 0, ifail)

!       Print pivot indices

        Write (nout, *)
        Write (nout, *) 'Pivot indices'
        Write (nout, 110) ipiv(1:n)

      Else
        Write (nout, 120) 'The diagonal block ', info, ' of D is zero'
      End If

100   Format ((4X,4('(',F7.4,',',F7.4,') ')))
110   Format (1X, 7I11)
120   Format (1X, A, I3, A)
    End Program
Full documentation of ZSYSV


ZSYSVX example

Complex Linear Equations: Solution (by diagonal pivoting factorization) of a complex symmetric system of linear equations

 To solve the equations

where $ A$ is the complex symmetric matrix

and

Error estimates for the solutions, and an estimate of the reciprocal of thecondition number of the matrix $ A$ are also output.

Data

ZSYSVX Example Program Data
    4               2                                            :N and NRHS
 ( -0.56,  0.12) ( -1.54, -2.86) (  5.32, -1.59) (  3.80,  0.92)
                 ( -2.83 ,-0.03) ( -3.52,  0.58) ( -7.86, -2.96)
                                 (  8.86,  1.81) (  5.14, -0.64)
                                                 ( -0.39 ,-0.71) :End matrix A
 ( -6.43, 19.24) ( -4.59,-35.53)
 ( -0.49, -1.47) (  6.95, 20.49)
 (-48.18, 66.00) (-12.08,-27.02)
 (-55.64, 41.22) (-19.09,-35.97)                                 :End matrix B

Result

 ZSYSVX Example Program Results

 Solution(s)
                    1                 2
 1  (-4.0000, 3.0000) (-1.0000, 1.0000)
 2  ( 3.0000,-2.0000) ( 3.0000, 2.0000)
 3  (-2.0000, 5.0000) ( 1.0000,-3.0000)
 4  ( 1.0000,-1.0000) (-2.0000,-1.0000)

 Backward errors (machine-dependent)
       8.1E-17    3.0E-17

 Estimated forward error bounds (machine-dependent)
       1.2E-14    1.2E-14

 Estimate of reciprocal condition number
       4.9E-02

Source

    Program zsysvx_example

!     ZSYSVX Example Program Text

!     Copyright 2017, Numerical Algorithms Group Ltd. http://www.nag.com

!     .. Use Statements ..
      Use lapack_example_aux, Only: nagf_file_print_matrix_complex_gen_comp
      Use lapack_interfaces, Only: zsysvx
      Use lapack_precision, Only: dp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter :: nb = 64, nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=dp) :: rcond
      Integer :: i, ifail, info, lda, ldaf, ldb, ldx, lwork, n, nrhs
!     .. Local Arrays ..
      Complex (Kind=dp), Allocatable :: a(:, :), af(:, :), b(:, :), work(:), &
        x(:, :)
      Real (Kind=dp), Allocatable :: berr(:), ferr(:), rwork(:)
      Integer, Allocatable :: ipiv(:)
      Character (1) :: clabs(1), rlabs(1)
!     .. Executable Statements ..
      Write (nout, *) 'ZSYSVX Example Program Results'
      Write (nout, *)
      Flush (nout)
!     Skip heading in data file
      Read (nin, *)
      Read (nin, *) n, nrhs
      lda = n
      ldaf = n
      ldb = n
      ldx = n
      lwork = nb*n
      Allocate (a(lda,n), af(ldaf,n), b(ldb,nrhs), work(lwork), x(ldx,nrhs), &
        berr(nrhs), ferr(nrhs), rwork(n), ipiv(n))

!     Read the upper triangular part of A from data file

      Read (nin, *)(a(i,i:n), i=1, n)

!     Read B from data file

      Read (nin, *)(b(i,1:nrhs), i=1, n)

!     Solve the equations AX = B for X
      Call zsysvx('Not factored', 'Upper', n, nrhs, a, lda, af, ldaf, ipiv, b, &
        ldb, x, ldx, rcond, ferr, berr, work, lwork, rwork, info)

      If ((info==0) .Or. (info==n+1)) Then

!       Print solution, error bounds and condition number

!       ifail: behaviour on error exit
!              =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
        ifail = 0
        Call nagf_file_print_matrix_complex_gen_comp('General', ' ', n, nrhs, &
          x, ldx, 'Bracketed', 'F7.4', 'Solution(s)', 'Integer', rlabs, &
          'Integer', clabs, 80, 0, ifail)

        Write (nout, *)
        Write (nout, *) 'Backward errors (machine-dependent)'
        Write (nout, 100) berr(1:nrhs)
        Write (nout, *)
        Write (nout, *) 'Estimated forward error bounds (machine-dependent)'
        Write (nout, 100) ferr(1:nrhs)
        Write (nout, *)
        Write (nout, *) 'Estimate of reciprocal condition number'
        Write (nout, 100) rcond
        Write (nout, *)

        If (info==n+1) Then
          Write (nout, *)
          Write (nout, *) 'The matrix A is singular to working precision'
        End If
      Else
        Write (nout, 110) 'The diagonal block ', info, ' of D is zero'
      End If

100   Format ((3X,1P,7E11.1))
110   Format (1X, A, I3, A)
    End Program
Full documentation of ZSYSVX


LAPACK:Real Linear Least Squares

Next: Complex Linear Least Squares Up: LAPACK Routines by Subject Previous: Complex Linear Equations

Real Linear Least Squares

  • DGELS : Solves an overdetermined or underdetermined real linear system
  • DGELSD : Minimum-norm solution of a real linear least squares problem using singular value decomposition (divide-and-conquer)
  • DGELSS : Minimum-norm solution of a real linear least squares problem using singular value decomposition
  • DGELSY : Minimum-norm solution of a real linear least squares problem


DGELS example

Real Linear Least Squares: Solves an overdetermined or underdetermined real linear system

 To solve the linear least squares problem

where

Data

DGELS Example Program Data

  6      4                  :Values of M and N

 -0.57  -1.28  -0.39   0.25
 -1.93   1.08  -0.31  -2.14
  2.30   0.24   0.40  -0.35
 -1.93   0.64  -0.66   0.08
  0.15   0.30   0.15  -2.13
 -0.02   1.03  -1.43   0.50 :End of matrix A

 -2.67
 -0.55
  3.34
 -0.77
  0.48
  4.10                      :End of vector b

Result

 DGELS Example Program Results

 Least squares solution
      1.5339     1.8707    -1.5241     0.0392

 Square root of the residual sum of squares
      2.22E-02

Source

    Program dgels_example

!     DGELS Example Program Text

!     Copyright 2017, Numerical Algorithms Group Ltd. http://www.nag.com

!     .. Use Statements ..
      Use blas_interfaces, Only: dnrm2
      Use lapack_interfaces, Only: dgels
      Use lapack_precision, Only: dp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter :: nb = 64, nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=dp) :: rnorm
      Integer :: i, info, lda, ldb, lwork, m, n, nrhs
!     .. Local Arrays ..
      Real (Kind=dp), Allocatable :: a(:, :), b(:), work(:)
!     .. Executable Statements ..
      Write (nout, *) 'DGELS Example Program Results'
      Write (nout, *)
!     Skip heading in data file
      Read (nin, *)
      Read (nin, *) m, n
      lda = m
      lwork = n + nb*m
      Allocate (a(lda,n), b(m), work(lwork))

!     Read A and B from data file

      Read (nin, *)(a(i,1:n), i=1, m)
      Read (nin, *) b(1:m)

!     Solve the least squares problem min( norm2(b - Ax) ) for x

      nrhs = 1
      ldb = m

      Call dgels('No transpose', m, n, nrhs, a, lda, b, ldb, work, lwork, &
        info)

!     Print solution

      Write (nout, *) 'Least squares solution'
      Write (nout, 100) b(1:n)

!     Compute and print estimate of the square root of the residual
!     sum of squares

      rnorm = dnrm2(m-n, b(n+1), 1)
      Write (nout, *)
      Write (nout, *) 'Square root of the residual sum of squares'
      Write (nout, 110) rnorm

100   Format (1X, 7F11.4)
110   Format (3X, 1P, E11.2)
    End Program
Full documentation of DGELS


DGELSD example

Real Linear Least Squares: Minimum-norm solution of a real linear least squares problem using singular value decomposition (divide-and-conquer)

 To solve the linear least squares problem

for the solution, $ x$, of minimum norm, where

A tolerance of 0.01 is used to determine the effective rank of $ A$.

Data

DGELSD Example Program Data

  5      6                                :Values of M and N

 -0.09  -1.56  -1.48  -1.09   0.08  -1.59
  0.14   0.20  -0.43   0.84   0.55  -0.72
 -0.46   0.29   0.89   0.77  -1.13   1.06
  0.68   1.09  -0.71   2.11   0.14   1.24
  1.29   0.51  -0.96  -1.27   1.74   0.34 :End of matrix A

  7.4
  4.3
 -8.1
  1.8
  8.7                                     :End of vector b

Result

Warning: Floating underflow occurred
 DGELSD Example Program Results

 Least squares solution
      1.5938    -0.1180    -3.1501     0.1554     2.5529    -1.6730

 Tolerance used to estimate the rank of A
      1.00E-02
 Estimated rank of A
      4

 Singular values of A
      3.9997     2.9962     2.0001     0.9988     0.0025

Source

    Program dgelsd_example

!     DGELSD Example Program Text

!     Copyright 2017, Numerical Algorithms Group Ltd. http://www.nag.com

!     .. Use Statements ..
      Use lapack_interfaces, Only: dgelsd
      Use lapack_precision, Only: dp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=dp) :: rcond
      Integer :: i, info, lda, liwork, lwork, m, n, rank
!     .. Local Arrays ..
      Real (Kind=dp), Allocatable :: a(:, :), b(:), s(:), work(:)
      Real (Kind=dp) :: lw(1)
      Integer, Allocatable :: iwork(:)
      Integer :: liw(1)
!     .. Intrinsic Procedures ..
      Intrinsic :: nint
!     .. Executable Statements ..
      Write (nout, *) 'DGELSD Example Program Results'
      Write (nout, *)
!     Skip heading in data file
      Read (nin, *)
      Read (nin, *) m, n
      lda = m
      Allocate (a(lda,n), b(n), s(m))

!     Read A and B from data file

      Read (nin, *)(a(i,1:n), i=1, m)
      Read (nin, *) b(1:m)

!     Choose RCOND to reflect the relative accuracy of the input
!     data

      rcond = 0.01_dp

!     Call dgelsd in workspace query mode.
      lwork = -1
      Call dgelsd(m, n, 1, a, lda, b, n, s, rcond, rank, lw, lwork, liw, info)
      lwork = nint(lw(1))
      liwork = liw(1)
      Allocate (work(lwork), iwork(liwork))

!     Now Solve the least squares problem min( norm2(b - Ax) ) for the
!     x of minimum norm.
      Call dgelsd(m, n, 1, a, lda, b, n, s, rcond, rank, work, lwork, iwork, &
        info)

      If (info==0) Then

!       Print solution

        Write (nout, *) 'Least squares solution'
        Write (nout, 100) b(1:n)

!       Print the effective rank of A

        Write (nout, *)
        Write (nout, *) 'Tolerance used to estimate the rank of A'
        Write (nout, 110) rcond
        Write (nout, *) 'Estimated rank of A'
        Write (nout, 120) rank

!       Print singular values of A

        Write (nout, *)
        Write (nout, *) 'Singular values of A'
        Write (nout, 100) s(1:m)
      Else
        Write (nout, *) 'The SVD algorithm failed to converge'
      End If

100   Format (1X, 7F11.4)
110   Format (3X, 1P, E11.2)
120   Format (1X, I6)
    End Program
Full documentation of DGELSD


DGELSS example

Real Linear Least Squares: Minimum-norm solution of a real linear least squares problem using singular value decomposition

 To solve the linear least squares problem

for the solution, $ x$, of minimum norm, where

A tolerance of 0.01 is used to determine the effective rank of $ A$.

Data

DGELSS Example Program Data

  6      5                         :Values of M and N

 -0.09   0.14  -0.46   0.68   1.29
 -1.56   0.20   0.29   1.09   0.51
 -1.48  -0.43   0.89  -0.71  -0.96
 -1.09   0.84   0.77   2.11  -1.27
  0.08   0.55  -1.13   0.14   1.74
 -1.59  -0.72   1.06   1.24   0.34 :End of matrix A

  7.4
  4.2
 -8.3
  1.8
  8.6
  2.1                              :End of vector b

Result

 DGELSS Example Program Results

 Least squares solution
      0.6344     0.9699    -1.4403     3.3678     3.3992

 Tolerance used to estimate the rank of A
      1.00E-02
 Estimated rank of A
      4

 Singular values of A
      3.9997     2.9962     2.0001     0.9988     0.0025

Source

    Program dgelss_example

!     DGELSS Example Program Text

!     Copyright 2017, Numerical Algorithms Group Ltd. http://www.nag.com

!     .. Use Statements ..
      Use blas_interfaces, Only: dnrm2
      Use lapack_interfaces, Only: dgelss
      Use lapack_precision, Only: dp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter :: nb = 64, nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=dp) :: rcond, rnorm
      Integer :: i, info, lda, lwork, m, n, rank
!     .. Local Arrays ..
      Real (Kind=dp), Allocatable :: a(:, :), b(:), s(:), work(:)
!     .. Executable Statements ..
      Write (nout, *) 'DGELSS Example Program Results'
      Write (nout, *)
!     Skip heading in data file
      Read (nin, *)
      Read (nin, *) m, n
      lda = m
      lwork = 3*n + nb*(m+n)
      Allocate (a(lda,n), b(m), s(n), work(lwork))

!     Read A and B from data file

      Read (nin, *)(a(i,1:n), i=1, m)
      Read (nin, *) b(1:m)

!     Choose RCOND to reflect the relative accuracy of the input data

      rcond = 0.01_dp

!     Solve the least squares problem min( norm2(b - Ax) ) for the x
!     of minimum norm.

      Call dgelss(m, n, 1, a, lda, b, m, s, rcond, rank, work, lwork, info)

      If (info==0) Then

!       Print solution

        Write (nout, *) 'Least squares solution'
        Write (nout, 100) b(1:n)

!       Print the effective rank of A

        Write (nout, *)
        Write (nout, *) 'Tolerance used to estimate the rank of A'
        Write (nout, 110) rcond
        Write (nout, *) 'Estimated rank of A'
        Write (nout, 120) rank

!       Print singular values of A

        Write (nout, *)
        Write (nout, *) 'Singular values of A'
        Write (nout, 100) s(1:n)

!       Compute and print estimate of the square root of the
!       residual sum of squares

        If (rank==n) Then
          rnorm = dnrm2(m-n, b(n+1), 1)
          Write (nout, *)
          Write (nout, *) 'Square root of the residual sum of squares'
          Write (nout, 110) rnorm
        End If
      Else
        Write (nout, *) 'The SVD algorithm failed to converge'
      End If

100   Format (1X, 7F11.4)
110   Format (3X, 1P, E11.2)
120   Format (1X, I6)
    End Program
Full documentation of DGELSS


DGELSY example

Real Linear Least Squares: Minimum-norm solution of a real linear least squares problem

 To solve the linear least squares problem

for the solution, $ x$, of minimum norm, where

A tolerance of 0.01 is used to determine the effective rank of $ A$.

Data

DGELSY Example Program Data

  6      5                         :Values of M and N

 -0.09   0.14  -0.46   0.68   1.29
 -1.56   0.20   0.29   1.09   0.51
 -1.48  -0.43   0.89  -0.71  -0.96
 -1.09   0.84   0.77   2.11  -1.27
  0.08   0.55  -1.13   0.14   1.74
 -1.59  -0.72   1.06   1.24   0.34 :End of matrix A

  7.4
  4.2
 -8.3
  1.8
  8.6
  2.1                              :End of vector b

Result

 DGELSY Example Program Results

 Least squares solution
      0.6344     0.9699    -1.4402     3.3678     3.3992

 Tolerance used to estimate the rank of A
      1.00E-02
 Estimated rank of A
      4

Source

    Program dgelsy_example

!     DGELSY Example Program Text

!     Copyright 2017, Numerical Algorithms Group Ltd. http://www.nag.com

!     .. Use Statements ..
      Use lapack_interfaces, Only: dgelsy
      Use lapack_precision, Only: dp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter :: nb = 64, nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=dp) :: rcond
      Integer :: i, info, lda, lwork, m, n, rank
!     .. Local Arrays ..
      Real (Kind=dp), Allocatable :: a(:, :), b(:), work(:)
      Integer, Allocatable :: jpvt(:)
!     .. Executable Statements ..
      Write (nout, *) 'DGELSY Example Program Results'
      Write (nout, *)
!     Skip heading in data file
      Read (nin, *)
      Read (nin, *) m, n
      lda = m
      lwork = 3*n + nb*(n+1)
      Allocate (a(lda,n), b(m), work(lwork), jpvt(n))

!     Read A and B from data file

      Read (nin, *)(a(i,1:n), i=1, m)
      Read (nin, *) b(1:m)

!     Initialize JPVT to be zero so that all columns are free

      jpvt(1:n) = 0

!     Choose RCOND to reflect the relative accuracy of the input data

      rcond = 0.01_dp

!     Solve the least squares problem min( norm2(b - Ax) ) for the x
!     of minimum norm.

      Call dgelsy(m, n, 1, a, lda, b, m, jpvt, rcond, rank, work, lwork, info)

!     Print solution

      Write (nout, *) 'Least squares solution'
      Write (nout, 100) b(1:n)

!     Print the effective rank of A

      Write (nout, *)
      Write (nout, *) 'Tolerance used to estimate the rank of A'
      Write (nout, 110) rcond
      Write (nout, *) 'Estimated rank of A'
      Write (nout, 120) rank

100   Format (1X, 7F11.4)
110   Format (3X, 1P, E11.2)
120   Format (1X, I6)
    End Program
Full documentation of DGELSY


LAPACK:Complex Linear Least Squares

Next: Real Generalized Linear Least Squares Up: LAPACK Routines by Subject Previous: Real Linear Least Squares

Complex Linear Least Squares

  • ZGELS : Solves an overdetermined or underdetermined complex linear system
  • ZGELSD : Minimum-norm solution of a complex linear least squares problem using singular value decomposition (divide-and-conquer)
  • ZGELSS : Minimum-norm solution of a complex linear least squares problem using singular value decomposition
  • ZGELSY : Minimum-norm solution of a complex linear least squares problem


ZGELS example

Complex Linear Least Squares: Solves an overdetermined or underdetermined complex linear system

 To solve the linear least squares problem

where

and

Data

ZGELS Example Program Data

   6             4                               :Values of M, N and NRHS

 ( 0.96,-0.81) (-0.03, 0.96) (-0.91, 2.06) (-0.05, 0.41)
 (-0.98, 1.98) (-1.20, 0.19) (-0.66, 0.42) (-0.81, 0.56)
 ( 0.62,-0.46) ( 1.01, 0.02) ( 0.63,-0.17) (-1.11, 0.60)
 (-0.37, 0.38) ( 0.19,-0.54) (-0.98,-0.36) ( 0.22,-0.20)
 ( 0.83, 0.51) ( 0.20, 0.01) (-0.17,-0.46) ( 1.47, 1.59)
 ( 1.08,-0.28) ( 0.20,-0.12) (-0.07, 1.23) ( 0.26, 0.26) :End of matrix A

 (-2.09, 1.93)
 ( 3.34,-3.53)
 (-4.94,-2.04)
 ( 0.17, 4.23)
 (-5.19, 3.63)
 ( 0.98, 2.53)                                           :End of vector b

Result

 ZGELS Example Program Results

 Least squares solution
 (-0.5044,-1.2179) (-2.4281, 2.8574) ( 1.4872,-2.1955) ( 0.4537, 2.6904)

 Square root of the residual sum of squares
   6.88E-02

Source

    Program zgels_example

!     ZGELS Example Program Text

!     Copyright 2017, Numerical Algorithms Group Ltd. http://www.nag.com

!     .. Use Statements ..
      Use blas_interfaces, Only: dznrm2
      Use lapack_interfaces, Only: zgels
      Use lapack_precision, Only: dp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter :: nb = 64, nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=dp) :: rnorm
      Integer :: i, info, lda, lwork, m, n
!     .. Local Arrays ..
      Complex (Kind=dp), Allocatable :: a(:, :), b(:), work(:)
!     .. Executable Statements ..
      Write (nout, *) 'ZGELS Example Program Results'
      Write (nout, *)
!     Skip heading in data file
      Read (nin, *)
      Read (nin, *) m, n
      lda = m
      lwork = n + nb*m
      Allocate (a(lda,n), b(m), work(lwork))

!     Read A and B from data file

      Read (nin, *)(a(i,1:n), i=1, m)
      Read (nin, *) b(1:m)

!     Solve the least squares problem min( norm2(b - Ax) ) for x
      Call zgels('No transpose', m, n, 1, a, lda, b, m, work, lwork, info)

!     Print solution

      Write (nout, *) 'Least squares solution'
      Write (nout, 100) b(1:n)

!     Compute and print estimate of the square root of the residual
!     sum of squares

      rnorm = dznrm2(m-n, b(n+1), 1)
      Write (nout, *)
      Write (nout, *) 'Square root of the residual sum of squares'
      Write (nout, 110) rnorm

100   Format (4(' (',F7.4,',',F7.4,')',:))
110   Format (1X, 1P, E10.2)
    End Program
Full documentation of ZGELS


ZGELSD example

Complex Linear Least Squares: Minimum-norm solution of a complex linear least squares problem using singular value decomposition (divide-and-conquer)

 To solve the linear least squares problem

for the solution, $ x$, of minimum norm, where

and

A tolerance of 0.01 is used to determine the effective rank of $ A$.

Data

ZGELSD Example Program Data

   4             5                                            :Values of M and N

 ( 0.47,-0.34) (-0.32,-0.23) ( 0.35,-0.60) ( 0.89, 0.71) (-0.19, 0.06)
 (-0.40, 0.54) (-0.05, 0.20) (-0.52,-0.34) (-0.45,-0.45) ( 0.11,-0.85)
 ( 0.60, 0.01) (-0.26,-0.44) ( 0.87,-0.11) (-0.02,-0.57) ( 1.44, 0.80)
 ( 0.80,-1.02) (-0.43, 0.17) (-0.34,-0.09) ( 1.14,-0.78) ( 0.07, 1.14) :End of A

 ( 2.15,-0.20)
 (-2.24, 1.82)
 ( 4.45,-4.28)
 ( 5.70,-6.25)                                                  :End of vector b

Result

Warning: Floating underflow occurred
 ZGELSD Example Program Results

 Least squares solution
 ( 3.9747,-1.8377) (-0.9186, 0.8253) (-0.3105, 0.1477) ( 1.0050, 0.8626)
 (-0.2256,-1.9425)

 Tolerance used to estimate the rank of A
      1.00E-02
 Estimated rank of A
      3

 Singular values of A
      2.9979     1.9983     1.0044     0.0064

Source

    Program zgelsd_example

!     ZGELSD Example Program Text

!     Copyright 2017, Numerical Algorithms Group Ltd. http://www.nag.com

!     .. Use Statements ..
      Use lapack_interfaces, Only: zgelsd
      Use lapack_precision, Only: dp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=dp) :: rcond
      Integer :: i, info, lda, liwork, lrwork, lwork, m, n, rank
!     .. Local Arrays ..
      Complex (Kind=dp), Allocatable :: a(:, :), b(:), work(:)
      Complex (Kind=dp) :: lw(1)
      Real (Kind=dp) :: lrw(1)
      Real (Kind=dp), Allocatable :: rwork(:), s(:)
      Integer, Allocatable :: iwork(:)
      Integer :: liw(1)
!     .. Intrinsic Procedures ..
      Intrinsic :: nint, real
!     .. Executable Statements ..
      Write (nout, *) 'ZGELSD Example Program Results'
      Write (nout, *)
!     Skip heading in data file
      Read (nin, *)
      Read (nin, *) m, n
      lda = m
      Allocate (a(lda,n), b(n), s(m))

!     Read A and B from data file

      Read (nin, *)(a(i,1:n), i=1, m)
      Read (nin, *) b(1:m)

!     Choose RCOND to reflect the relative accuracy of the input
!     data

      rcond = 0.01E0_dp

!     Call zgelsd in workspace query mode.
      lwork = -1
      Call zgelsd(m, n, 1, a, lda, b, n, s, rcond, rank, lw, lwork, lrw, liw, &
        info)
      lwork = nint(real(lw(1)))
      lrwork = nint(lrw(1))
      liwork = liw(1)
      Allocate (work(lwork), rwork(lrwork), iwork(liwork))

!     Solve the least squares problem min( norm2(b - Ax) ) for the
!     x of minimum norm.

      Call zgelsd(m, n, 1, a, lda, b, n, s, rcond, rank, work, lwork, rwork, &
        iwork, info)

      If (info==0) Then

!       Print solution

        Write (nout, *) 'Least squares solution'
        Write (nout, 100) b(1:n)

!       Print the effective rank of A

        Write (nout, *)
        Write (nout, *) 'Tolerance used to estimate the rank of A'
        Write (nout, 110) rcond
        Write (nout, *) 'Estimated rank of A'
        Write (nout, 120) rank

!       Print singular values of A

        Write (nout, *)
        Write (nout, *) 'Singular values of A'
        Write (nout, 130) s(1:m)
      Else If (info>0) Then
        Write (nout, *) 'The SVD algorithm failed to converge'
      End If

100   Format (4(' (',F7.4,',',F7.4,')',:))
110   Format (3X, 1P, E11.2)
120   Format (1X, I6)
130   Format (1X, 7F11.4)
    End Program
Full documentation of ZGELSD


ZGELSS example

Complex Linear Least Squares: Minimum-norm solution of a complex linear least squares problem using singular value decomposition

 To solve the linear least squares problem

for the solution, $ x$, of minimum norm, where

and

A tolerance of 0.01 is used to determine the effective rank of $ A$.

Data

ZGELSS Example Program Data

   5             4                                       :Values of M and N

 ( 0.47,-0.34) (-0.40, 0.54) ( 0.60, 0.01) ( 0.80,-1.02)
 (-0.32,-0.23) (-0.05, 0.20) (-0.26,-0.44) (-0.43, 0.17)
 ( 0.35,-0.60) (-0.52,-0.34) ( 0.87,-0.11) (-0.34,-0.09)
 ( 0.89, 0.71) (-0.45,-0.45) (-0.02,-0.57) ( 1.14,-0.78)
 (-0.19, 0.06) ( 0.11,-0.85) ( 1.44, 0.80) ( 0.07, 1.14) :End of matrix A

 (-1.08,-2.59)
 (-2.61,-1.49)
 ( 3.13,-3.61)
 ( 7.33,-8.01)
 ( 9.12, 7.63)                                           :End of vector b

Result

 ZGELSS Example Program Results

 Least squares solution
 ( 1.1673,-3.3222) ( 1.3480, 5.5028) ( 4.1762, 2.3434) ( 0.6465, 0.0105)

 Tolerance used to estimate the rank of A
      1.00E-02
 Estimated rank of A
      3

 Singular values of A
      2.9979     1.9983     1.0044     0.0064

Source

    Program zgelss_example

!     ZGELSS Example Program Text

!     Copyright 2017, Numerical Algorithms Group Ltd. http://www.nag.com

!     .. Use Statements ..
      Use blas_interfaces, Only: dznrm2
      Use lapack_interfaces, Only: zgelss
      Use lapack_precision, Only: dp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter :: nb = 64, nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=dp) :: rcond, rnorm
      Integer :: i, info, lda, lwork, m, n, rank
!     .. Local Arrays ..
      Complex (Kind=dp), Allocatable :: a(:, :), b(:), work(:)
      Real (Kind=dp), Allocatable :: rwork(:), s(:)
!     .. Executable Statements ..
      Write (nout, *) 'ZGELSS Example Program Results'
      Write (nout, *)
!     Skip heading in data file
      Read (nin, *)
      Read (nin, *) m, n
      lda = m
      lwork = 2*n + nb*(m+n)
      Allocate (a(lda,n), b(m), work(lwork), rwork(5*n), s(n))

!     Read A and B from data file

      Read (nin, *)(a(i,1:n), i=1, m)
      Read (nin, *) b(1:m)

!     Choose RCOND to reflect the relative accuracy of the input data

      rcond = 0.01E0_dp

!     Solve the least squares problem min( norm2(b - Ax) ) for the x
!     of minimum norm.

      Call zgelss(m, n, 1, a, lda, b, m, s, rcond, rank, work, lwork, rwork, &
        info)

      If (info==0) Then

!       Print solution

        Write (nout, *) 'Least squares solution'
        Write (nout, 100) b(1:n)

!       Print the effective rank of A

        Write (nout, *)
        Write (nout, *) 'Tolerance used to estimate the rank of A'
        Write (nout, 110) rcond
        Write (nout, *) 'Estimated rank of A'
        Write (nout, 120) rank

!       Print singular values of A

        Write (nout, *)
        Write (nout, *) 'Singular values of A'
        Write (nout, 130) s(1:n)

!       Compute and print estimate of the square root of the
!       residual sum of squares

        If (rank==n) Then
          rnorm = dznrm2(m-n, b(n+1), 1)
          Write (nout, *)
          Write (nout, *) 'Square root of the residual sum of squares'
          Write (nout, 110) rnorm
        End If
      Else
        Write (nout, *) 'The SVD algorithm failed to converge'
      End If

100   Format (4(' (',F7.4,',',F7.4,')',:))
110   Format (3X, 1P, E11.2)
120   Format (1X, I6)
130   Format (1X, 7F11.4)
    End Program
Full documentation of ZGELSS


ZGELSY example

Complex Linear Least Squares: Minimum-norm solution of a complex linear least squares problem

 To solve the linear least squares problem

for the solution, $ x$, of minimum norm, where

and

A tolerance of 0.01 is used to determine the effective rank of $ A$.

Data

ZGELSY Example Program Data

   5             4                                       :Values of M and N

 ( 0.47,-0.34) (-0.40, 0.54) ( 0.60, 0.01) ( 0.80,-1.02)
 (-0.32,-0.23) (-0.05, 0.20) (-0.26,-0.44) (-0.43, 0.17)
 ( 0.35,-0.60) (-0.52,-0.34) ( 0.87,-0.11) (-0.34,-0.09)
 ( 0.89, 0.71) (-0.45,-0.45) (-0.02,-0.57) ( 1.14,-0.78)
 (-0.19, 0.06) ( 0.11,-0.85) ( 1.44, 0.80) ( 0.07, 1.14) :End of matrix A

 (-1.08,-2.59)
 (-2.61,-1.49)
 ( 3.13,-3.61)
 ( 7.33,-8.01)
 ( 9.12, 7.63)                                           :End of vector b

Result

 ZGELSY Example Program Results

 Least squares solution
 ( 1.1669,-3.3224) ( 1.3486, 5.5027) ( 4.1764, 2.3435) ( 0.6467, 0.0107)

 Tolerance used to estimate the rank of A
   1.00E-02
 Estimated rank of A
      3

Source

    Program zgelsy_example

!     ZGELSY Example Program Text

!     Copyright 2017, Numerical Algorithms Group Ltd. http://www.nag.com

!     .. Use Statements ..
      Use lapack_interfaces, Only: zgelsy
      Use lapack_precision, Only: dp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter :: nb = 64, nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=dp) :: rcond
      Integer :: i, info, lda, lwork, m, n, rank
!     .. Local Arrays ..
      Complex (Kind=dp), Allocatable :: a(:, :), b(:), work(:)
      Real (Kind=dp), Allocatable :: rwork(:)
      Integer, Allocatable :: jpvt(:)
!     .. Executable Statements ..
      Write (nout, *) 'ZGELSY Example Program Results'
      Write (nout, *)
!     Skip heading in data file
      Read (nin, *)
      Read (nin, *) m, n
      lda = m
      lwork = nb*(n+1)
      Allocate (a(lda,n), b(m), work(lwork), rwork(2*n), jpvt(n))

!     Read A and B from data file

      Read (nin, *)(a(i,1:n), i=1, m)
      Read (nin, *) b(1:m)

!     Initialize JPVT to be zero so that all columns are free

      jpvt(1:n) = 0

!     Choose RCOND to reflect the relative accuracy of the input data

      rcond = 0.01_dp

!     Solve the least squares problem min( norm2(b - Ax) ) for the x
!     of minimum norm.

      Call zgelsy(m, n, 1, a, lda, b, m, jpvt, rcond, rank, work, lwork, &
        rwork, info)

!     Print solution

      Write (nout, *) 'Least squares solution'
      Write (nout, 100) b(1:n)

!     Print the effective rank of A

      Write (nout, *)
      Write (nout, *) 'Tolerance used to estimate the rank of A'
      Write (nout, 110) rcond
      Write (nout, *) 'Estimated rank of A'
      Write (nout, 120) rank

100   Format (4(' (',F7.4,',',F7.4,')',:))
110   Format (1X, 1P, E10.2)
120   Format (1X, I6)
    End Program
Full documentation of ZGELSY


LAPACK:Real Generalized Linear Least Squares

Next: Complex Generalized Linear Least Squares Up: LAPACK Routines by Subject Previous: Complex Linear Least Squares

Real Generalized Linear Least Squares

  • DGGGLM : Solve a real general Gauss-Markov linear model (GLM) problem
  • DGGLSE : Solve a real linear equality-constrained least squares (LSE) problem


DGGGLM example

Real Generalized Linear Least Squares: Solve a real general Gauss-Markov linear model (GLM) problem

 To solve the weighted least squares problem

where

Data

DGGGLM Example Program Data

  4      3      4           :Values of M, N and P

 -0.57  -1.28  -0.39
 -1.93   1.08  -0.31
  2.30   0.24  -0.40
 -0.02   1.03  -1.43        :End of matrix A

  0.50   0.00   0.00   0.00
  0.00   1.00   0.00   0.00
  0.00   0.00   2.00   0.00
  0.00   0.00   0.00   5.00 :End of matrix B

  1.32
 -4.00
  5.52
  3.24                      :End of vector d

Result

 DGGGLM Example Program Results

 Weighted least squares solution
      1.9889    -1.0058    -2.9911

 Residual vector
     -6.37E-04  -2.45E-03  -4.72E-03   7.70E-03

 Square root of the residual sum of squares
      9.38E-03

Source

    Program dggglm_example

!     DGGGLM Example Program Text

!     Copyright 2017, Numerical Algorithms Group Ltd. http://www.nag.com

!     .. Use Statements ..
      Use blas_interfaces, Only: dnrm2
      Use lapack_interfaces, Only: dggglm
      Use lapack_precision, Only: dp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter :: nb = 64, nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=dp) :: rnorm
      Integer :: i, info, lda, ldb, lwork, m, n, p
!     .. Local Arrays ..
      Real (Kind=dp), Allocatable :: a(:, :), b(:, :), d(:), work(:), x(:), &
        y(:)
!     .. Executable Statements ..
      Write (nout, *) 'DGGGLM Example Program Results'
      Write (nout, *)
!     Skip heading in data file
      Read (nin, *)
      Read (nin, *) m, n, p
      lda = m
      ldb = m
      lwork = n + m + nb*(m+p)
      Allocate (a(lda,n), b(ldb,p), d(m), work(lwork), x(n), y(p))

!     Read A, B and D from data file

      Read (nin, *)(a(i,1:n), i=1, m)
      Read (nin, *)(b(i,1:p), i=1, m)
      Read (nin, *) d(1:m)

!     Solve the weighted least squares problem

!     minimize ||inv(B)*(d - A*x)|| (in the 2-norm)

      Call dggglm(m, n, p, a, lda, b, ldb, d, x, y, work, lwork, info)

!     Print least squares solution, x

      Write (nout, *) 'Weighted least squares solution'
      Write (nout, 100) x(1:n)

!     Print residual vector y = inv(B)*(d - A*x)

      Write (nout, *)
      Write (nout, *) 'Residual vector'
      Write (nout, 110) y(1:p)

!     Compute and print the square root of the residual sum of
!     squares

      rnorm = dnrm2(p, y, 1)

      Write (nout, *)
      Write (nout, *) 'Square root of the residual sum of squares'
      Write (nout, 110) rnorm

100   Format (1X, 7F11.4)
110   Format (3X, 1P, 7E11.2)
    End Program
Full documentation of DGGGLM


DGGLSE example

Real Generalized Linear Least Squares: Solve a real linear equality-constrained least squares (LSE) problem

 To solve the linear equality constrained least squares problem

where

The constraints $ B x = d$ correspond to $ x_{1} = x_{3}$ and $ x_{2} = x_{4}$.

Data

DGGLSE Example Program Data

  6      4      2           :Values of M, N and P

 -0.57  -1.28  -0.39   0.25
 -1.93   1.08  -0.31  -2.14
  2.30   0.24   0.40  -0.35
 -1.93   0.64  -0.66   0.08
  0.15   0.30   0.15  -2.13
 -0.02   1.03  -1.43   0.50 :End of matrix A

  1.00   0.00  -1.00   0.00
  0.00   1.00   0.00  -1.00 :End of matrix B

 -1.50
 -2.14
  1.23
 -0.54
 -1.68
  0.82                      :End of vector c

  0.00
  0.00                      :End of vector d

Result

 DGGLSE Example Program Results

 Constrained least squares solution
      0.4890     0.9975     0.4890     0.9975

 Square root of the residual sum of squares
      2.51E-02

Source

    Program dgglse_example

!     DGGLSE Example Program Text

!     Copyright 2017, Numerical Algorithms Group Ltd. http://www.nag.com

!     .. Use Statements ..
      Use blas_interfaces, Only: dnrm2
      Use lapack_interfaces, Only: dgglse
      Use lapack_precision, Only: dp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter :: nb = 64, nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=dp) :: rnorm
      Integer :: i, info, lda, ldb, lwork, m, n, p
!     .. Local Arrays ..
      Real (Kind=dp), Allocatable :: a(:, :), b(:, :), c(:), d(:), work(:), &
        x(:)
!     .. Executable Statements ..
      Write (nout, *) 'DGGLSE Example Program Results'
      Write (nout, *)
!     Skip heading in data file
      Read (nin, *)
      Read (nin, *) m, n, p
      lda = m
      ldb = p
      lwork = p + n + nb*(m+n)
      Allocate (a(lda,n), b(ldb,n), c(m), d(p), work(lwork), x(n))

!     Read A, B, C and D from data file

      Read (nin, *)(a(i,1:n), i=1, m)
      Read (nin, *)(b(i,1:n), i=1, p)
      Read (nin, *) c(1:m)
      Read (nin, *) d(1:p)

!     Solve the equality-constrained least squares problem

!     minimize ||c - A*x|| (in the 2-norm) subject to B*x = D

      Call dgglse(m, n, p, a, lda, b, ldb, c, d, x, work, lwork, info)

!     Print least squares solution

      Write (nout, *) 'Constrained least squares solution'
      Write (nout, 100) x(1:n)

!     Compute the square root of the residual sum of squares

      rnorm = dnrm2(m-n+p, c(n-p+1), 1)
      Write (nout, *)
      Write (nout, *) 'Square root of the residual sum of squares'
      Write (nout, 110) rnorm

100   Format (1X, 7F11.4)
110   Format (3X, 1P, E11.2)
    End Program
Full documentation of DGGLSE


LAPACK:Complex Generalized Linear Least Squares

Next: Real Symmetric Eigenproblems Up: LAPACK Routines by Subject Previous: Real Generalized Linear Least Squares

Complex Generalized Linear Least Squares

  • ZGGGLM : Solve a complex general Gauss-Markov linear model (GLM) problem
  • ZGGLSE : Solve a complex linear equality-constrained least squares (LSE) problem


ZGGGLM example

Complex Generalized Linear Least Squares: Solve a complex general Gauss-Markov linear model (GLM) problem

 To solve the weighted least squares problem

where

and

Data

ZGGGLM Example Program Data

  4             3             4                         :Values of M, N and P

( 0.96,-0.81) (-0.03, 0.96) (-0.91, 2.06)
(-0.98, 1.98) (-1.20, 0.19) (-0.66, 0.42)
( 0.62,-0.46) ( 1.01, 0.02) ( 0.63,-0.17)
( 1.08,-0.28) ( 0.20,-0.12) (-0.07, 1.23)               :End of matrix A

( 0.50,-1.00) ( 0.00, 0.00) ( 0.00, 0.00) ( 0.00, 0.00)
( 0.00, 0.00) ( 1.00,-2.00) ( 0.00, 0.00) ( 0.00, 0.00)
( 0.00, 0.00) ( 0.00, 0.00) ( 2.00,-3.00) ( 0.00, 0.00)
( 0.00, 0.00) ( 0.00, 0.00) ( 0.00, 0.00) ( 5.00,-4.00) :End of matrix B

( 6.00,-0.40)
(-5.27, 0.90)
( 2.72,-2.13)
(-1.30,-2.80)                                           :End of vector d

Result

 ZGGGLM Example Program Results

 Weighted least squares solution
 (  -0.9846,   1.9950) (   3.9929,  -4.9748) (  -3.0026,   0.9994)

 Residual vector
 ( 1.26E-04,-4.66E-04) ( 1.11E-03,-8.61E-04) ( 3.84E-03,-1.82E-03)
 ( 2.03E-03, 3.02E-03)

 Square root of the residual sum of squares
   5.79E-03

Source

    Program zggglm_example

!     ZGGGLM Example Program Text

!     Copyright 2017, Numerical Algorithms Group Ltd. http://www.nag.com

!     .. Use Statements ..
      Use blas_interfaces, Only: dznrm2
      Use lapack_interfaces, Only: zggglm
      Use lapack_precision, Only: dp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter :: nb = 64, nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=dp) :: rnorm
      Integer :: i, info, lda, ldb, lwork, m, n, p
!     .. Local Arrays ..
      Complex (Kind=dp), Allocatable :: a(:, :), b(:, :), d(:), work(:), x(:), &
        y(:)
!     .. Executable Statements ..
      Write (nout, *) 'ZGGGLM Example Program Results'
      Write (nout, *)
!     Skip heading in data file
      Read (nin, *)
      Read (nin, *) m, n, p
      lda = m
      ldb = m
      lwork = n + m + nb*(m+p)
      Allocate (a(lda,n), b(ldb,p), d(m), work(lwork), x(n), y(p))

!     Read A, B and D from data file

      Read (nin, *)(a(i,1:n), i=1, m)
      Read (nin, *)(b(i,1:p), i=1, m)
      Read (nin, *) d(1:m)

!     Solve the weighted least squares problem

!     minimize ||inv(B)*(d - A*x)|| (in the 2-norm)

      Call zggglm(m, n, p, a, lda, b, ldb, d, x, y, work, lwork, info)

!     Print least squares solution

      Write (nout, *) 'Weighted least squares solution'
      Write (nout, 100) x(1:n)

!     Print residual vector y = inv(B)*(d - A*x)

      Write (nout, *)
      Write (nout, *) 'Residual vector'
      Write (nout, 110) y(1:p)

!     Compute and print the square root of the residual sum of squares
      rnorm = dznrm2(p, y, 1)

      Write (nout, *)
      Write (nout, *) 'Square root of the residual sum of squares'
      Write (nout, 120) rnorm

100   Format (3(' (',F9.4,',',F9.4,')',:))
110   Format (3(' (',1P,E9.2,',',1P,E9.2,')',:))
120   Format (1X, 1P, E10.2)
    End Program
Full documentation of ZGGGLM


ZGGLSE example

Complex Generalized Linear Least Squares: Solve a complex linear equality-constrained least squares (LSE) problem

 To solve the linear equality constrained least squares problem

where

The constraints $ B x = d$ correspond to $ x_{1} = x_{3}$ and $ x_{2} = x_{4}$.

Data

ZGGLSE Example Program Data

  6             4             2                         :Values of M, N and P

( 0.96,-0.81) (-0.03, 0.96) (-0.91, 2.06) (-0.05, 0.41)
(-0.98, 1.98) (-1.20, 0.19) (-0.66, 0.42) (-0.81, 0.56)
( 0.62,-0.46) ( 1.01, 0.02) ( 0.63,-0.17) (-1.11, 0.60)
( 0.37, 0.38) ( 0.19,-0.54) (-0.98,-0.36) ( 0.22,-0.20)
( 0.83, 0.51) ( 0.20, 0.01) (-0.17,-0.46) ( 1.47, 1.59)
( 1.08,-0.28) ( 0.20,-0.12) (-0.07, 1.23) ( 0.26, 0.26) :End of matrix A

( 1.00, 0.00) ( 0.00, 0.00) (-1.00, 0.00) ( 0.00, 0.00)
( 0.00, 0.00) ( 1.00, 0.00) ( 0.00, 0.00) (-1.00, 0.00) :End of matrix B

(-2.54, 0.09)
( 1.65,-2.26)
(-2.11,-3.96)
( 1.82, 3.30)
(-6.41, 3.77)
( 2.07, 0.66)                                           :End of vector c

( 0.00, 0.00)
( 0.00, 0.00)                                           :End of vector d

Result

 ZGGLSE Example Program Results

 Constrained least squares solution
 ( 1.0874,-1.9621) (-0.7409, 3.7297) ( 1.0874,-1.9621) (-0.7409, 3.7297)

 Square root of the residual sum of squares
   1.59E-01

Source

    Program zgglse_example

!     ZGGLSE Example Program Text

!     Copyright 2017, Numerical Algorithms Group Ltd. http://www.nag.com

!     .. Use Statements ..
      Use blas_interfaces, Only: dznrm2
      Use lapack_interfaces, Only: zgglse
      Use lapack_precision, Only: dp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter :: nb = 64, nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=dp) :: rnorm
      Integer :: i, info, lda, ldb, lwork, m, n, p
!     .. Local Arrays ..
      Complex (Kind=dp), Allocatable :: a(:, :), b(:, :), c(:), d(:), work(:), &
        x(:)
!     .. Executable Statements ..
      Write (nout, *) 'ZGGLSE Example Program Results'
      Write (nout, *)
!     Skip heading in data file
      Read (nin, *)
      Read (nin, *) m, n, p
      lda = m
      ldb = p
      lwork = p + n + nb*(m+n)
      Allocate (a(lda,n), b(ldb,n), c(m), d(p), work(lwork), x(n))

!     Read A, B, C and D from data file

      Read (nin, *)(a(i,1:n), i=1, m)
      Read (nin, *)(b(i,1:n), i=1, p)
      Read (nin, *) c(1:m)
      Read (nin, *) d(1:p)

!     Solve the equality-constrained least squares problem

!     minimize ||c - A*x|| (in the 2-norm) subject to B*x = D

      Call zgglse(m, n, p, a, lda, b, ldb, c, d, x, work, lwork, info)

!     Print least squares solution

      Write (nout, *) 'Constrained least squares solution'
      Write (nout, 100) x(1:n)

!     Compute the square root of the residual sum of squares

      rnorm = dznrm2(m-n+p, c(n-p+1), 1)
      Write (nout, *)
      Write (nout, *) 'Square root of the residual sum of squares'
      Write (nout, 110) rnorm

100   Format (4(' (',F7.4,',',F7.4,')',:))
110   Format (1X, 1P, E10.2)
    End Program
Full documentation of ZGGLSE


LAPACK:Real Symmetric Eigenproblems

Next: Complex Hermitian Eigenproblems Up: LAPACK Routines by Subject Previous: Complex Generalized Linear Least Squares

Real Symmetric Eigenproblems

  • DSBEV : All eigenvalues and, optionally, eigenvectors of a real symmetric band matrix
  • DSBEVD : All eigenvalues and, optionally, all eigenvectors of real symmetric band matrix (divide-and-conquer)
  • DSBEVX : Selected eigenvalues and, optionally, eigenvectors of a real symmetric band matrix
  • DSPEV : All eigenvalues and, optionally, eigenvectors of a real symmetric matrix, packed storage
  • DSPEVD : All eigenvalues and, optionally, all eigenvectors of real symmetric matrix, packed storage (divide-and-conquer)
  • DSPEVX : Selected eigenvalues and, optionally, eigenvectors of a real symmetric matrix, packed storage
  • DSTEV : All eigenvalues and, optionally, eigenvectors of a real symmetric tridiagonal matrix
  • DSTEVD : All eigenvalues and, optionally, all eigenvectors of real symmetric tridiagonal matrix (divide-and-conquer)
  • DSTEVR : Selected eigenvalues and, optionally, eigenvectors of a real symmetric tridiagonal matrix (Relatively Robust Representations)
  • DSTEVX : Selected eigenvalues and, optionally, eigenvectors of a real symmetric tridiagonal matrix
  • DSYEV : All eigenvalues and, optionally, eigenvectors of a real symmetric matrix
  • DSYEVD : All eigenvalues and, optionally, all eigenvectors of real symmetric matrix (divide-and-conquer)
  • DSYEVR : Selected eigenvalues and, optionally, eigenvectors of a real symmetric matrix (Relatively Robust Representations)
  • DSYEVX : Selected eigenvalues and, optionally, eigenvectors of a real symmetric matrix


DSBEV example

Real Symmetric Eigenproblems: All eigenvalues and, optionally, eigenvectors of a real symmetric band matrix

 To find all the eigenvalues and eigenvectors of the symmetric band matrix

together with approximate error bounds for the computed eigenvalues andeigenvectors.

Data

DSBEV Example Program Data

  5    2                   :Values of N and KD

  1.0  2.0  3.0
       2.0  3.0  4.0
            3.0  4.0  5.0
                 4.0  5.0
                      5.0  :End of matrix A

Result

 DSBEV Example Program Results

 Eigenvalues
    -3.2474 -2.6633  1.7511  4.1599 14.9997
 Eigenvectors
          1       2       3       4       5
 1   0.0394  0.6238  0.5635  0.5165  0.1582
 2   0.5721 -0.2575 -0.3896  0.5955  0.3161
 3  -0.4372 -0.5900  0.4008  0.1470  0.5277
 4  -0.4424  0.4308 -0.5581 -0.0470  0.5523
 5   0.5332  0.1039  0.2421 -0.5956  0.5400

 Error estimate for the eigenvalues
        3.3E-15

 Error estimates for the eigenvectors
        5.7E-15    5.7E-15    1.4E-15    1.4E-15    3.1E-16

Source

    Program dsbev_example

!     DSBEV Example Program Text

!     Copyright 2017, Numerical Algorithms Group Ltd. http://www.nag.com

!     .. Use Statements ..
      Use lapack_example_aux, Only: nagf_file_print_matrix_real_gen
      Use lapack_interfaces, Only: ddisna, dsbev
      Use lapack_precision, Only: dp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter :: nin = 5, nout = 6
      Character (1), Parameter :: uplo = 'U'
!     .. Local Scalars ..
      Real (Kind=dp) :: eerrbd, eps
      Integer :: i, ifail, info, j, kd, ldab, ldz, n
!     .. Local Arrays ..
      Real (Kind=dp), Allocatable :: ab(:, :), rcondz(:), w(:), work(:), &
        z(:, :), zerrbd(:)
!     .. Intrinsic Procedures ..
      Intrinsic :: abs, epsilon, max, min
!     .. Executable Statements ..
      Write (nout, *) 'DSBEV Example Program Results'
      Write (nout, *)
!     Skip heading in data file
      Read (nin, *)
      Read (nin, *) n, kd
      ldab = kd + 1
      ldz = n
      Allocate (ab(ldab,n), rcondz(n), w(n), work(3*n-2), z(ldz,n), zerrbd(n))

!     Read the upper or lower triangular part of the symmetric band
!     matrix A from data file

      If (uplo=='U') Then
        Read (nin, *)((ab(kd+1+i-j,j),j=i,min(n,i+kd)), i=1, n)
      Else If (uplo=='L') Then
        Read (nin, *)((ab(1+i-j,j),j=max(1,i-kd),i), i=1, n)
      End If

!     Solve the band symmetric eigenvalue problem

      Call dsbev('Vectors', uplo, n, kd, ab, ldab, w, z, ldz, work, info)

      If (info==0) Then

!       Print solution

        Write (nout, *) 'Eigenvalues'
        Write (nout, 100) w(1:n)
        Flush (nout)

!       Standardize the eigenvectors so that first elements are non-negative.
        Do i = 1, n
          If (z(1,i)<0.0_dp) Then
            z(1:n, i) = -z(1:n, i)
          End If
        End Do

!       ifail: behaviour on error exit
!              =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
        ifail = 0
        Call nagf_file_print_matrix_real_gen('General', ' ', n, n, z, ldz, &
          'Eigenvectors', ifail)

!       Get the machine precision, EPS and compute the approximate
!       error bound for the computed eigenvalues.  Note that for
!       the 2-norm, max( abs(W(i)) ) = norm(A), and since the
!       eigenvalues are returned in ascending order
!       max( abs(W(i)) ) = max( abs(W(1)), abs(W(n)))

        eps = epsilon(1.0E0_dp)
        eerrbd = eps*max(abs(w(1)), abs(w(n)))

!       Call DDISNA to estimate reciprocal condition
!       numbers for the eigenvectors
        Call ddisna('Eigenvectors', n, n, w, rcondz, info)

!       Compute the error estimates for the eigenvectors

        Do i = 1, n
          zerrbd(i) = eerrbd/rcondz(i)
        End Do

!       Print the approximate error bounds for the eigenvalues
!       and vectors

        Write (nout, *)
        Write (nout, *) 'Error estimate for the eigenvalues'
        Write (nout, 110) eerrbd
        Write (nout, *)
        Write (nout, *) 'Error estimates for the eigenvectors'
        Write (nout, 110) zerrbd(1:n)
      Else
        Write (nout, 120) 'Failure in DSBEV. INFO =', info
      End If

100   Format (3X, (8F8.4))
110   Format (4X, 1P, 6E11.1)
120   Format (1X, A, I4)
    End Program
Full documentation of DSBEV


DSBEVD example

Real Symmetric Eigenproblems: All eigenvalues and, optionally, all eigenvectors of real symmetric band matrix (divide-and-conquer)

 To find all the eigenvalues and eigenvectors of the symmetric band matrix

The example program for DSBEV illustrates the computation of error bounds forthe eigenvalues and eigenvectors..

Data

DSBEVD Example Program Data
  5  2                      :Values of N and KD
  'L'                       :Value of UPLO
  1.0
  2.0  2.0
  3.0  3.0  3.0
       4.0  4.0  4.0
            5.0  5.0  5.0   :End of matrix A
  'V'                       :Value of JOB

Result

 DSBEVD Example Program Results

 Eigenvalues
    -3.2474 -2.6633  1.7511  4.1599 14.9997

 Eigenvectors
          1       2       3       4       5
 1   0.0394  0.6238  0.5635  0.5165  0.1582
 2   0.5721 -0.2575 -0.3896  0.5955  0.3161
 3  -0.4372 -0.5900  0.4008  0.1470  0.5277
 4  -0.4424  0.4308 -0.5581 -0.0470  0.5523
 5   0.5332  0.1039  0.2421 -0.5956  0.5400

Source

    Program dsbevd_example

!     DSBEVD Example Program Text

!     Copyright 2017, Numerical Algorithms Group Ltd. http://www.nag.com

!     .. Use Statements ..
      Use lapack_example_aux, Only: nagf_file_print_matrix_real_gen
      Use lapack_interfaces, Only: dsbevd
      Use lapack_precision, Only: dp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter :: nin = 5, nout = 6
!     .. Local Scalars ..
      Integer :: i, ifail, info, j, kd, ldab, ldz, liwork, lwork, n
      Character (1) :: job, uplo
!     .. Local Arrays ..
      Real (Kind=dp), Allocatable :: ab(:, :), w(:), work(:), z(:, :)
      Integer, Allocatable :: iwork(:)
!     .. Intrinsic Procedures ..
      Intrinsic :: max, min
!     .. Executable Statements ..
      Write (nout, *) 'DSBEVD Example Program Results'
!     Skip heading in data file
      Read (nin, *)
      Read (nin, *) n, kd
      ldab = kd + 1
      ldz = n
      liwork = 5*n + 3
      lwork = 2*n*n + 5*n + 1
      Allocate (ab(ldab,n), w(n), work(lwork), z(ldz,n), iwork(liwork))

!     Read A from data file

      Read (nin, *) uplo
      If (uplo=='U') Then
        Do i = 1, n
          Read (nin, *)(ab(kd+1+i-j,j), j=i, min(n,i+kd))
        End Do
      Else If (uplo=='L') Then
        Do i = 1, n
          Read (nin, *)(ab(1+i-j,j), j=max(1,i-kd), i)
        End Do
      End If

      Read (nin, *) job

!     Calculate all the eigenvalues and eigenvectors of A
      Call dsbevd(job, uplo, n, kd, ab, ldab, w, z, ldz, work, lwork, iwork, &
        liwork, info)

      Write (nout, *)
      If (info>0) Then
        Write (nout, *) 'Failure to converge.'
      Else

!       Print eigenvalues and eigenvectors

        Write (nout, *) 'Eigenvalues'
        Write (nout, 100) w(1:n)
        Write (nout, *)
        Flush (nout)

!       Standardize the eigenvectors so that first elements are non-negative.
        Do i = 1, n
          If (z(1,i)<0.0_dp) Then
            z(1:n, i) = -z(1:n, i)
          End If
        End Do

!       ifail: behaviour on error exit
!              =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
        ifail = 0
        Call nagf_file_print_matrix_real_gen('General', ' ', n, n, z, ldz, &
          'Eigenvectors', ifail)

      End If

100   Format (3X, (8F8.4))
    End Program
Full documentation of DSBEVD


DSBEVX example

Real Symmetric Eigenproblems: Selected eigenvalues and, optionally, eigenvectors of a real symmetric band matrix

 To find the eigenvalues in the half-open interval $ (-3, 3]$, and thecorresponding eigenvectors, of the symmetric band matrix

Data

DSBEVX Example Program Data

  5    2                   :Values of N and KD

 -3.0  3.0                 :Values of VL and VU

  1.0  2.0  3.0
       2.0  3.0  4.0
            3.0  4.0  5.0
                 4.0  5.0
                      5.0  :End of matrix A

Result

 DSBEVX Example Program Results

 Number of eigenvalues found =    2

 Eigenvalues
    -2.6633  1.7511
 Selected eigenvectors
          1       2
 1  -0.6238 -0.5635
 2   0.2575  0.3896
 3   0.5900 -0.4008
 4  -0.4308  0.5581
 5  -0.1039 -0.2421

Source

    Program dsbevx_example

!     DSBEVX Example Program Text

!     Copyright 2017, Numerical Algorithms Group Ltd. http://www.nag.com

!     .. Use Statements ..
      Use lapack_example_aux, Only: nagf_file_print_matrix_real_gen
      Use lapack_interfaces, Only: dsbevx
      Use lapack_precision, Only: dp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Real (Kind=dp), Parameter :: zero = 0.0E+0_dp
      Integer, Parameter :: nin = 5, nout = 6
      Character (1), Parameter :: uplo = 'U'
!     .. Local Scalars ..
      Real (Kind=dp) :: abstol, vl, vu
      Integer :: i, ifail, il, info, iu, j, kd, ldab, ldq, ldz, m, n
!     .. Local Arrays ..
      Real (Kind=dp), Allocatable :: ab(:, :), q(:, :), w(:), work(:), z(:, :)
      Integer, Allocatable :: iwork(:), jfail(:)
!     .. Intrinsic Procedures ..
      Intrinsic :: max, min
!     .. Executable Statements ..
      Write (nout, *) 'DSBEVX Example Program Results'
      Write (nout, *)
!     Skip heading in data file
      Read (nin, *)
      Read (nin, *) n, kd
      ldab = kd + 1
      ldq = n
      ldz = n
      m = n
      Allocate (ab(ldab,n), q(ldq,n), w(n), work(7*n), z(ldz,m), iwork(5*n), &
        jfail(n))

!     Read the lower and upper bounds of the interval to be searched,
!     and read the upper or lower triangular part of the matrix A
!     from data file

      Read (nin, *) vl, vu
      If (uplo=='U') Then
        Read (nin, *)((ab(kd+1+i-j,j),j=i,min(n,i+kd)), i=1, n)
      Else If (uplo=='L') Then
        Read (nin, *)((ab(1+i-j,j),j=max(1,i-kd),i), i=1, n)
      End If

!     Set the absolute error tolerance for eigenvalues.  With ABSTOL
!     set to zero, the default value is used instead

      abstol = zero

!     Solve the band symmetric eigenvalue problem
      Call dsbevx('Vectors', 'Values in range', uplo, n, kd, ab, ldab, q, ldq, &
        vl, vu, il, iu, abstol, m, w, z, ldz, work, iwork, jfail, info)

      If (info>=0) Then

!       Print solution

        Write (nout, 100) 'Number of eigenvalues found =', m
        Write (nout, *)
        Write (nout, *) 'Eigenvalues'
        Write (nout, 110) w(1:m)
        Flush (nout)

!       ifail: behaviour on error exit
!              =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
        ifail = 0
        Call nagf_file_print_matrix_real_gen('General', ' ', n, m, z, ldz, &
          'Selected eigenvectors', ifail)

        If (info>0) Then
          Write (nout, 100) 'INFO eigenvectors failed to converge, INFO =', &
            info
          Write (nout, *) 'Indices of eigenvectors that did not converge'
          Write (nout, 120) jfail(1:m)
        End If
      Else
        Write (nout, 100) 'Failure in DSBEVX. INFO =', info
      End If

100   Format (1X, A, I5)
110   Format (3X, (8F8.4))
120   Format (3X, (8I8))
    End Program
Full documentation of DSBEVX


DSPEV example

Real Symmetric Eigenproblems: All eigenvalues and, optionally, eigenvectors of a real symmetric matrix, packed storage

 To find all the eigenvalues of the symmetric matrix

together with an approximate error bound for the computed eigenvalues.

Data

DSPEV Example Program Data

  4                  :Value of N

  1.0  2.0  3.0  4.0
       2.0  3.0  4.0
            3.0  4.0
                 4.0 :End of matrix A

Result

 DSPEV Example Program Results

 Eigenvalues
    -2.0531 -0.5146 -0.2943 12.8621

 Error estimate for the eigenvalues
        2.9E-15

Source

    Program dspev_example

!     DSPEV Example Program Text

!     Copyright 2017, Numerical Algorithms Group Ltd. http://www.nag.com

!     .. Use Statements ..
      Use lapack_interfaces, Only: dspev
      Use lapack_precision, Only: dp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter :: nin = 5, nout = 6
      Character (1), Parameter :: uplo = 'U'
!     .. Local Scalars ..
      Real (Kind=dp) :: eerrbd, eps
      Integer :: i, info, j, n
!     .. Local Arrays ..
      Real (Kind=dp), Allocatable :: ap(:), w(:), work(:)
      Real (Kind=dp) :: dummy(1, 1)
!     .. Intrinsic Procedures ..
      Intrinsic :: abs, epsilon, max
!     .. Executable Statements ..
      Write (nout, *) 'DSPEV Example Program Results'
      Write (nout, *)
!     Skip heading in data file
      Read (nin, *)
      Read (nin, *) n

      Allocate (ap((n*(n+1))/2), w(n), work(3*n))

!     Read the upper or lower triangular part of the matrix A from
!     data file

      If (uplo=='U') Then
        Read (nin, *)((ap(i+(j*(j-1))/2),j=i,n), i=1, n)
      Else If (uplo=='L') Then
        Read (nin, *)((ap(i+((2*n-j)*(j-1))/2),j=1,i), i=1, n)
      End If

!     Solve the symmetric eigenvalue problem
      Call dspev('No vectors', uplo, n, ap, w, dummy, 1, work, info)

      If (info==0) Then

!       Print solution

        Write (nout, *) 'Eigenvalues'
        Write (nout, 100) w(1:n)

!       Get the machine precision, EPS and compute the approximate
!       error bound for the computed eigenvalues.  Note that for
!       the 2-norm, max( abs(W(i)) ) = norm(A), and since the
!       eigenvalues are returned in ascending order
!       max( abs(W(i)) ) = max( abs(W(1)), abs(W(n)))

        eps = epsilon(1.0E0_dp)
        eerrbd = eps*max(abs(w(1)), abs(w(n)))

!       Print the approximate error bound for the eigenvalues

        Write (nout, *)
        Write (nout, *) 'Error estimate for the eigenvalues'
        Write (nout, 110) eerrbd
      Else
        Write (nout, 120) 'Failure in DSPEV. INFO =', info
      End If

100   Format (3X, (8F8.4))
110   Format (4X, 1P, 6E11.1)
120   Format (1X, A, I4)
    End Program
Full documentation of DSPEV


DSPEVD example

Real Symmetric Eigenproblems: All eigenvalues and, optionally, all eigenvectors of real symmetric matrix, packed storage (divide-and-conquer)

 To find all the eigenvalues and eigenvectors of the symmetric matrix

The example program for DSPEV illustrates the computation of error bounds forthe eigenvalues.

Data

DSPEVD Example Program Data
  4                         :Value of N
  'L'                       :Value of UPLO
  1.0
  2.0   2.0
  3.0   3.0   3.0
  4.0   4.0   4.0   4.0     :End of matrix A
  'V'                       :Value of JOB

Result

 DSPEVD Example Program Results

 Eigenvalues
    -2.0531 -0.5146 -0.2943 12.8621

 Eigenvectors
          1       2       3       4
 1   0.7003 -0.5144 -0.2767  0.4103
 2   0.3592  0.4851  0.6634  0.4422
 3  -0.1569  0.5420 -0.6504  0.5085
 4  -0.5965 -0.4543  0.2457  0.6144

Source

    Program dspevd_example

!     DSPEVD Example Program Text

!     Copyright 2017, Numerical Algorithms Group Ltd. http://www.nag.com

!     .. Use Statements ..
      Use lapack_example_aux, Only: nagf_blas_damax_val, &
        nagf_file_print_matrix_real_gen
      Use lapack_interfaces, Only: dspevd
      Use lapack_precision, Only: dp !
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Real (Kind=dp), Parameter :: zero = 0.0E0_dp
      Integer, Parameter :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=dp) :: r
      Integer :: i, ifail, info, j, k, ldz, liwork, lwork, n
      Character (1) :: job, uplo
!     .. Local Arrays ..
      Real (Kind=dp), Allocatable :: ap(:), w(:), work(:), z(:, :)
      Integer, Allocatable :: iwork(:)
!     .. Executable Statements ..
      Write (nout, *) 'DSPEVD Example Program Results'
!     Skip heading in data file
      Read (nin, *)
      Read (nin, *) n
      ldz = n
      liwork = 5*n + 3
      lwork = n*n + 6*n + 1
      Allocate (ap(n*(n+1)/2), w(n), work(lwork), z(ldz,n), iwork(liwork))

!     Read A from data file

      Read (nin, *) uplo
      If (uplo=='U') Then
        Read (nin, *)((ap(i+j*(j-1)/2),j=i,n), i=1, n)
      Else If (uplo=='L') Then
        Read (nin, *)((ap(i+(2*n-j)*(j-1)/2),j=1,i), i=1, n)
      End If

      Read (nin, *) job

!     Calculate all the eigenvalues and eigenvectors of A
      Call dspevd(job, uplo, n, ap, w, z, ldz, work, lwork, iwork, liwork, &
        info)

      Write (nout, *)
      If (info>0) Then
        Write (nout, *) 'Failure to converge.'
      Else

!       Print eigenvalues and eigenvectors

        Write (nout, *) 'Eigenvalues'
        Write (nout, 100) w(1:n)
        Write (nout, *)
        Flush (nout)

!       Normalize the eigenvectors: largest element positive
        Do i = 1, n
          Call nagf_blas_damax_val(n, z(1,i), 1, k, r)
          If (z(k,i)<zero) Then
            z(1:n, i) = -z(1:n, i)
          End If
        End Do

!       ifail: behaviour on error exit
!              =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
        ifail = 0
        Call nagf_file_print_matrix_real_gen('General', ' ', n, n, z, ldz, &
          'Eigenvectors', ifail)

      End If

100   Format (3X, (8F8.4))
    End Program
Full documentation of DSPEVD


DSPEVX example

Real Symmetric Eigenproblems: Selected eigenvalues and, optionally, eigenvectors of a real symmetric matrix, packed storage

 To find the eigenvalues in the half-open interval $ (-1, 1]$, and thecorresponding eigenvectors, of the symmetric matrix

Data

DSPEVX Example Program Data

  4                  :Value of N
 -1.0  1.0           :Values of VL and VU

  1.0  2.0  3.0  4.0
       2.0  3.0  4.0
            3.0  4.0
                 4.0 :End of matrix A

Result

 DSPEVX Example Program Results

 Number of eigenvalues found =    2

 Eigenvalues
    -0.5146 -0.2943
 Selected eigenvectors
          1       2
 1  -0.5144 -0.2767
 2   0.4851  0.6634
 3   0.5420 -0.6504
 4  -0.4543  0.2457

Source

    Program dspevx_example

!     DSPEVX Example Program Text

!     Copyright 2017, Numerical Algorithms Group Ltd. http://www.nag.com

!     .. Use Statements ..
      Use lapack_example_aux, Only: nagf_blas_damax_val, &
        nagf_file_print_matrix_real_gen
      Use lapack_interfaces, Only: dspevx
      Use lapack_precision, Only: dp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Real (Kind=dp), Parameter :: zero = 0.0E+0_dp
      Integer, Parameter :: nin = 5, nout = 6
      Character (1), Parameter :: uplo = 'U'
!     .. Local Scalars ..
      Real (Kind=dp) :: abstol, r, vl, vu
      Integer :: i, ifail, il, info, iu, j, k, ldz, m, n
!     .. Local Arrays ..
      Real (Kind=dp), Allocatable :: ap(:), w(:), work(:), z(:, :)
      Integer, Allocatable :: iwork(:), jfail(:)
!     .. Executable Statements ..
      Write (nout, *) 'DSPEVX Example Program Results'
      Write (nout, *)
!     Skip heading in data file
      Read (nin, *)
      Read (nin, *) n
      ldz = n
      m = n
      Allocate (ap((n*(n+1))/2), w(n), work(8*n), z(ldz,m), iwork(5*n), jfail( &
        n))

!     Read the lower and upper bounds of the interval to be searched,
!     and read the upper or lower triangular part of the matrix A
!     from data file

      Read (nin, *) vl, vu
      If (uplo=='U') Then
        Read (nin, *)((ap(i+(j*(j-1))/2),j=i,n), i=1, n)
      Else If (uplo=='L') Then
        Read (nin, *)((ap(i+((2*n-j)*(j-1))/2),j=1,i), i=1, n)
      End If

!     Set the absolute error tolerance for eigenvalues.  With ABSTOL
!     set to zero, the default value is used instead

      abstol = zero

!     Solve the symmetric eigenvalue problem
      Call dspevx('Vectors', 'Values in range', uplo, n, ap, vl, vu, il, iu, &
        abstol, m, w, z, ldz, work, iwork, jfail, info)

      If (info>=0) Then

!       Print solution

        Write (nout, 100) 'Number of eigenvalues found =', m
        Write (nout, *)
        Write (nout, *) 'Eigenvalues'
        Write (nout, 110) w(1:m)
        Flush (nout)

!       Normalize the eigenvectors: largest element positive
        Do i = 1, m
          Call nagf_blas_damax_val(n, z(1,i), 1, k, r)
          If (z(k,i)<zero) Then
            z(1:n, i) = -z(1:n, i)
          End If
        End Do

!       ifail: behaviour on error exit
!              =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
        ifail = 0
        Call nagf_file_print_matrix_real_gen('General', ' ', n, m, z, ldz, &
          'Selected eigenvectors', ifail)

        If (info>0) Then
          Write (nout, 100) 'INFO eigenvectors failed to converge, INFO =', &
            info
          Write (nout, *) 'Indices of eigenvectors that did not converge'
          Write (nout, 120) jfail(1:m)
        End If
      Else
        Write (nout, 100) 'Failure in DSPEVX. INFO =', info
      End If

100   Format (1X, A, I5)
110   Format (3X, (8F8.4))
120   Format (3X, (8I8))
    End Program
Full documentation of DSPEVX


DSTEV example

Real Symmetric Eigenproblems: All eigenvalues and, optionally, eigenvectors of a real symmetric tridiagonal matrix

 To find all the eigenvalues and eigenvectors of the symmetric tridiagonal matrix

together with approximate error bounds for the computed eigenvalues andeigenvectors.

Data

DSTEV Example Program Data

  4                         :Value of N

  1.0  4.0  9.0  16.0  :End of diagonal elements
  1.0  2.0  3.0        :End of off-diagonal elements

Result

 DSTEV Example Program Results

 Eigenvalues
     0.6476  3.5470  8.6578 17.1477
 Eigenvectors
          1       2       3       4
 1   0.9396  0.3388  0.0494  0.0034
 2  -0.3311  0.8628  0.3781  0.0545
 3   0.0853 -0.3648  0.8558  0.3568
 4  -0.0167  0.0879 -0.3497  0.9326

 Error estimate for the eigenvalues
        3.8E-15

 Error estimates for the eigenvectors
        1.3E-15    1.3E-15    7.5E-16    4.5E-16

Source

    Program dstev_example

!     DSTEV Example Program Text

!     Copyright 2017, Numerical Algorithms Group Ltd. http://www.nag.com

!     .. Use Statements ..
      Use lapack_example_aux, Only: nagf_file_print_matrix_real_gen
      Use lapack_interfaces, Only: ddisna, dstev
      Use lapack_precision, Only: dp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=dp) :: eerrbd, eps
      Integer :: i, ifail, info, ldz, n
!     .. Local Arrays ..
      Real (Kind=dp), Allocatable :: d(:), e(:), rcondz(:), work(:), z(:, :), &
        zerrbd(:)
!     .. Intrinsic Procedures ..
      Intrinsic :: abs, epsilon, max
!     .. Executable Statements ..
      Write (nout, *) 'DSTEV Example Program Results'
      Write (nout, *)
!     Skip heading in data file
      Read (nin, *)
      Read (nin, *) n
      ldz = n
      Allocate (d(n), e(n-1), rcondz(n), work(2*n-2), z(ldz,n), zerrbd(n))

!     Read the diagonal and off-diagonal elements of the matrix A
!     from data file

      Read (nin, *) d(1:n)
      Read (nin, *) e(1:n-1)

!     Solve the symmetric tridiagonal eigenvalue problem
      Call dstev('Vectors', n, d, e, z, ldz, work, info)

      If (info==0) Then

!       Print solution

        Write (nout, *) 'Eigenvalues'
        Write (nout, 100) d(1:n)
        Flush (nout)

!       Standardize the eigenvectors so that first elements are non-negative.
        Do i = 1, n
          If (z(1,i)<0.0_dp) Then
            z(1:n, i) = -z(1:n, i)
          End If
        End Do

!       ifail: behaviour on error exit
!              =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
        ifail = 0
        Call nagf_file_print_matrix_real_gen('General', ' ', n, n, z, ldz, &
          'Eigenvectors', ifail)

!       Get the machine precision, EPS and compute the approximate
!       error bound for the computed eigenvalues.  Note that for
!       the 2-norm, max( abs(D(i)) ) = norm(A), and since the
!       eigenvalues are returned in ascending order
!       max( abs(D(i)) ) = max( abs(D(1)), abs(D(n)))

        eps = epsilon(1.0E0_dp)
        eerrbd = eps*max(abs(d(1)), abs(d(n)))

!       Call DDISNA to estimate reciprocal condition
!       numbers for the eigenvectors
        Call ddisna('Eigenvectors', n, n, d, rcondz, info)

!       Compute the error estimates for the eigenvectors

        Do i = 1, n
          zerrbd(i) = eerrbd/rcondz(i)
        End Do

!       Print the approximate error bounds for the eigenvalues
!       and vectors

        Write (nout, *)
        Write (nout, *) 'Error estimate for the eigenvalues'
        Write (nout, 110) eerrbd
        Write (nout, *)
        Write (nout, *) 'Error estimates for the eigenvectors'
        Write (nout, 110) zerrbd(1:n)
      Else
        Write (nout, 120) 'Failure in DSTEV. INFO =', info
      End If

100   Format (3X, (8F8.4))
110   Format (4X, 1P, 6E11.1)
120   Format (1X, A, I4)
    End Program
Full documentation of DSTEV


DSTEVD example

Real Symmetric Eigenproblems: All eigenvalues and, optionally, all eigenvectors of real symmetric tridiagonal matrix (divide-and-conquer)

 To find all the eigenvalues and eigenvectors of the symmetric tridiagonal matrix

The example program for DSTEV illustrates the computation of error bounds forthe eigenvalues and eigenvectors.

Data

DSTEVD Example Program Data
  4                         :Value of N
  1.0  4.0  9.0  16.0
  1.0  2.0  3.0             :End of T
  'V'                       :Value of JOB

Result

 DSTEVD Example Program Results

 Eigenvalues
     0.6476  3.5470  8.6578 17.1477

 Eigenvectors
          1       2       3       4
 1   0.9396  0.3388  0.0494  0.0034
 2  -0.3311  0.8628  0.3781  0.0545
 3   0.0853 -0.3648  0.8558  0.3568
 4  -0.0167  0.0879 -0.3497  0.9326

Source

    Program dstevd_example

!     DSTEVD Example Program Text

!     Copyright 2017, Numerical Algorithms Group Ltd. http://www.nag.com

!     .. Use Statements ..
      Use blas_interfaces, Only: dnrm2
      Use lapack_example_aux, Only: nagf_file_print_matrix_real_gen
      Use lapack_interfaces, Only: dstevd
      Use lapack_precision, Only: dp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=dp) :: norm
      Integer :: i, ifail, info, ldz, liwork, lwork, n
      Character (1) :: job
!     .. Local Arrays ..
      Real (Kind=dp), Allocatable :: d(:), e(:), work(:), z(:, :)
      Integer, Allocatable :: iwork(:)
!     .. Executable Statements ..
      Write (nout, *) 'DSTEVD Example Program Results'
!     Skip heading in data file
      Read (nin, *)
      Read (nin, *) n
      ldz = n
      liwork = 5*n + 3
      lwork = n*n + 4*n + 1
      Allocate (d(n), e(n-1), work(lwork), z(ldz,n), iwork(liwork))

!     Read T from data file

      Read (nin, *) d(1:n)
      Read (nin, *) e(1:n-1)

      Read (nin, *) job

!     Calculate all the eigenvalues and eigenvectors of T
      Call dstevd(job, n, d, e, z, ldz, work, lwork, iwork, liwork, info)

      Write (nout, *)
      If (info>0) Then
        Write (nout, *) 'Failure to converge.'
      Else

!       Print eigenvalues and eigenvectors

        Write (nout, *) 'Eigenvalues'
        Write (nout, 100) d(1:n)
        Write (nout, *)
        Flush (nout)

!       Normalize the eigenvectors
        Do i = 1, n
          norm = dnrm2(n, z(1,i), 1)
          If (z(1,i)<0.0_dp) Then
            norm = -norm
          End If
          z(1:n, i) = z(1:n, i)/norm
        End Do

!       ifail: behaviour on error exit
!              =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
        ifail = 0
        Call nagf_file_print_matrix_real_gen('General', ' ', n, n, z, ldz, &
          'Eigenvectors', ifail)

      End If

100   Format (3X, (8F8.4))
    End Program
Full documentation of DSTEVD


DSTEVR example

Real Symmetric Eigenproblems: Selected eigenvalues and, optionally, eigenvectors of a real symmetric tridiagonal matrix (Relatively Robust Representations)

 To find the eigenvalues whose indices are in the range $ [2, 3]$, and thecorresponding eigenvectors, of the symmetric tridiagonal matrix

Data

DSTEVR Example Program Data

  4    2    3          :Values of N, IL and IU

  1.0  4.0  9.0  16.0  :End of diagonal elements
  1.0  2.0  3.0        :End of off-diagonal elements

Result

 DSTEVR Example Program Results

 Selected eigenvalues
     3.5470  8.6578
Warning: Floating invalid operation occurred
Warning: Floating divide by zero occurred
 Selected eigenvectors
          1       2
 1   0.3388  0.0494
 2   0.8628  0.3781
 3  -0.3648  0.8558
 4   0.0879 -0.3497

Source

    Program dstevr_example

!     DSTEVR Example Program Text

!     Copyright 2017, Numerical Algorithms Group Ltd. http://www.nag.com

!     .. Use Statements ..
      Use lapack_example_aux, Only: nagf_file_print_matrix_real_gen
      Use lapack_interfaces, Only: dstevr
      Use lapack_precision, Only: dp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Real (Kind=dp), Parameter :: zero = 0.0_dp
      Integer, Parameter :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=dp) :: abstol, vl, vu
      Integer :: ifail, il, info, iu, ldz, liwork, lwork, m, n
!     .. Local Arrays ..
      Real (Kind=dp), Allocatable :: d(:), e(:), w(:), work(:), z(:, :)
      Real (Kind=dp) :: rdum(1)
      Integer :: idum(1)
      Integer, Allocatable :: isuppz(:), iwork(:)
!     .. Intrinsic Procedures ..
      Intrinsic :: max, nint
!     .. Executable Statements ..
      Write (nout, *) 'DSTEVR Example Program Results'
      Write (nout, *)
!     Skip heading in data file and read N and the lower and upper
!     indices of the eigenvalues to be found
      Read (nin, *)
      Read (nin, *) n, il, iu
      ldz = n
      m = n
      Allocate (d(n), e(n-1), w(n), z(ldz,m), isuppz(2*n))

!     Use routine workspace query to get optimal workspace.
      lwork = -1
      liwork = -1
      Call dstevr('Vectors', 'Indices', n, d, e, vl, vu, il, iu, abstol, m, w, &
        z, ldz, isuppz, rdum, lwork, idum, liwork, info)

!     Make sure that there is enough workspace for block size nb.
      lwork = max(20*n, nint(rdum(1)))
      liwork = max(10*n, idum(1))
      Allocate (work(lwork), iwork(liwork))

!     Read the diagonal and off-diagonal elements of the matrix A
!     from data file

      Read (nin, *) d(1:n)
      Read (nin, *) e(1:n-1)

!     Set the absolute error tolerance for eigenvalues.  With ABSTOL
!     set to zero, the default value is used instead

      abstol = zero

!     Solve the symmetric tridiagonal eigenvalue problem
      Call dstevr('Vectors', 'Indices', n, d, e, vl, vu, il, iu, abstol, m, w, &
        z, ldz, isuppz, work, lwork, iwork, liwork, info)

      If (info==0) Then

!       Print solution

        Write (nout, *) 'Selected eigenvalues'
        Write (nout, 100) w(1:m)
        Flush (nout)

!       ifail: behaviour on error exit
!              =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
        ifail = 0
        Call nagf_file_print_matrix_real_gen('General', ' ', n, m, z, ldz, &
          'Selected eigenvectors', ifail)

      Else
        Write (nout, 110) 'Failure in DSTEVR. INFO =', info
      End If

100   Format (3X, (8F8.4))
110   Format (1X, A, I5)
    End Program
Full documentation of DSTEVR


DSTEVX example

Real Symmetric Eigenproblems: Selected eigenvalues and, optionally, eigenvectors of a real symmetric tridiagonal matrix

 To find the eigenvalues in the half-open interval $ (0, 5]$, and thecorresponding eigenvectors, of the symmetric tridiagonal matrix

Data

DSTEVX Example Program Data

  4                    :Value of N

  0.0  5.0             :Values of VL and VU

  1.0  4.0  9.0  16.0  :End of diagonal elements
  1.0  2.0  3.0        :End of off-diagonal elements

Result

 DSTEVX Example Program Results

 Number of eigenvalues found =    2

 Eigenvalues
     0.6476  3.5470
 Selected eigenvectors
          1       2
 1   0.9396  0.3388
 2  -0.3311  0.8628
 3   0.0853 -0.3648
 4  -0.0167  0.0879

Source

    Program dstevx_example

!     DSTEVX Example Program Text

!     Copyright 2017, Numerical Algorithms Group Ltd. http://www.nag.com

!     .. Use Statements ..
      Use lapack_example_aux, Only: nagf_file_print_matrix_real_gen
      Use lapack_interfaces, Only: dstevx
      Use lapack_precision, Only: dp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=dp) :: abstol, vl, vu
      Integer :: ifail, il, info, iu, ldz, m, n
!     .. Local Arrays ..
      Real (Kind=dp), Allocatable :: d(:), e(:), w(:), work(:), z(:, :)
      Integer, Allocatable :: iwork(:), jfail(:)
!     .. Intrinsic Procedures ..
      Intrinsic :: tiny
!     .. Executable Statements ..
      Write (nout, *) 'DSTEVX Example Program Results'
      Write (nout, *)
!     Skip heading in data file
      Read (nin, *)
      Read (nin, *) n
      ldz = n
      m = n
      Allocate (d(n), e(n), w(n), work(5*n), z(ldz,m), iwork(5*n), jfail(n))

!     Read the lower and upper bounds of the interval to be searched,
!     and read the diagonal and off-diagonal elements of the matrix
!     A from data file

      Read (nin, *) vl, vu
      Read (nin, *) d(1:n)
      Read (nin, *) e(1:n-1)

!     Set the absolute error tolerance for eigenvalues.  With ABSTOL
!     set to zero, the default value would be used instead

      abstol = 2.0E0_dp*tiny(1.0E0_dp)

!     Solve the symmetric eigenvalue problem
      Call dstevx('Vectors', 'Values in range', n, d, e, vl, vu, il, iu, &
        abstol, m, w, z, ldz, work, iwork, jfail, info)

      If (info>=0) Then

!       Print solution

        Write (nout, 100) 'Number of eigenvalues found =', m
        Write (nout, *)
        Write (nout, *) 'Eigenvalues'
        Write (nout, 110) w(1:m)
        Flush (nout)

!       ifail: behaviour on error exit
!              =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
        ifail = 0
        Call nagf_file_print_matrix_real_gen('General', ' ', n, m, z, ldz, &
          'Selected eigenvectors', ifail)

        If (info>0) Then
          Write (nout, 100) 'INFO eigenvectors failed to converge, INFO =', &
            info
          Write (nout, *) 'Indices of eigenvectors that did not converge'
          Write (nout, 120) jfail(1:m)
        End If
      Else
        Write (nout, 100) 'Failure in DSTEVX. INFO =', info
      End If

100   Format (1X, A, I5)
110   Format (3X, (8F8.4))
120   Format (3X, (8I8))
    End Program
Full documentation of DSTEVX


DSYEV example

Real Symmetric Eigenproblems: All eigenvalues and, optionally, eigenvectors of a real symmetric matrix

 To find all the eigenvalues and eigenvectors of the symmetric matrix

together with approximate error bounds for the computed eigenvalues andeigenvectors.

Data

DSYEV Example Program Data

  4                  :Value of N

  1.0  2.0  3.0  4.0
       2.0  3.0  4.0
            3.0  4.0
                 4.0 :End of matrix A

Result

 DSYEV Example Program Results

 Eigenvalues
    -2.0531 -0.5146 -0.2943 12.8621
 Eigenvectors
          1       2       3       4
 1   0.7003 -0.5144 -0.2767  0.4103
 2   0.3592  0.4851  0.6634  0.4422
 3  -0.1569  0.5420 -0.6504  0.5085
 4  -0.5965 -0.4543  0.2457  0.6144

 Error estimate for the eigenvalues
        2.9E-15

 Error estimates for the eigenvectors
        1.9E-15    1.3E-14    1.3E-14    2.2E-16

Source

    Program dsyev_example

!     DSYEV Example Program Text

!     Copyright 2017, Numerical Algorithms Group Ltd. http://www.nag.com

!     .. Use Statements ..
      Use lapack_example_aux, Only: nagf_blas_damax_val, &
        nagf_file_print_matrix_real_gen
      Use lapack_interfaces, Only: ddisna, dsyev
      Use lapack_precision, Only: dp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Real (Kind=dp), Parameter :: zero = 0.0_dp
      Integer, Parameter :: nb = 64, nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=dp) :: eerrbd, eps, r
      Integer :: i, ifail, info, k, lda, lwork, n
!     .. Local Arrays ..
      Real (Kind=dp), Allocatable :: a(:, :), rcondz(:), w(:), work(:), &
        zerrbd(:)
      Real (Kind=dp) :: dummy(1)
!     .. Intrinsic Procedures ..
      Intrinsic :: abs, epsilon, max, nint
!     .. Executable Statements ..
      Write (nout, *) 'DSYEV Example Program Results'
      Write (nout, *)
!     Skip heading in data file
      Read (nin, *)
      Read (nin, *) n
      lda = n
      Allocate (a(lda,n), rcondz(n), w(n), zerrbd(n))

!     Use routine workspace query to get optimal workspace.
      lwork = -1
      Call dsyev('Vectors', 'Upper', n, a, lda, w, dummy, lwork, info)

!     Make sure that there is enough workspace for block size nb.
      lwork = max((nb+2)*n, nint(dummy(1)))
      Allocate (work(lwork))

!     Read the upper triangular part of the matrix A from data file

      Read (nin, *)(a(i,i:n), i=1, n)

!     Solve the symmetric eigenvalue problem
      Call dsyev('Vectors', 'Upper', n, a, lda, w, work, lwork, info)

      If (info==0) Then

!       Print solution

        Write (nout, *) 'Eigenvalues'
        Write (nout, 100) w(1:n)
        Flush (nout)

!       Normalize the eigenvectors: largest element positive
        Do i = 1, n
          Call nagf_blas_damax_val(n, a(1,i), 1, k, r)
          If (a(k,i)<zero) Then
            a(1:n, i) = -a(1:n, i)
          End If
        End Do

!       ifail: behaviour on error exit
!              =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
        ifail = 0
        Call nagf_file_print_matrix_real_gen('General', ' ', n, n, a, lda, &
          'Eigenvectors', ifail)

!       Get the machine precision, EPS and compute the approximate
!       error bound for the computed eigenvalues.  Note that for
!       the 2-norm, max( abs(W(i)) ) = norm(A), and since the
!       eigenvalues are returned in ascending order
!       max( abs(W(i)) ) = max( abs(W(1)), abs(W(n)))

        eps = epsilon(1.0E0_dp)
        eerrbd = eps*max(abs(w(1)), abs(w(n)))

!       Call DDISNA to estimate reciprocal condition
!       numbers for the eigenvectors
        Call ddisna('Eigenvectors', n, n, w, rcondz, info)

!       Compute the error estimates for the eigenvectors

        Do i = 1, n
          zerrbd(i) = eerrbd/rcondz(i)
        End Do

!       Print the approximate error bounds for the eigenvalues
!       and vectors

        Write (nout, *)
        Write (nout, *) 'Error estimate for the eigenvalues'
        Write (nout, 110) eerrbd
        Write (nout, *)
        Write (nout, *) 'Error estimates for the eigenvectors'
        Write (nout, 110) zerrbd(1:n)
      Else
        Write (nout, 120) 'Failure in DSYEV. INFO =', info
      End If

100   Format (3X, (8F8.4))
110   Format (4X, 1P, 6E11.1)
120   Format (1X, A, I4)
    End Program
Full documentation of DSYEV


DSYEVD example

Real Symmetric Eigenproblems: All eigenvalues and, optionally, all eigenvectors of real symmetric matrix (divide-and-conquer)

 To find all the eigenvalues and eigenvectors of the symmetric matrix

The example program for DSYEV illustrates the computation of error bounds forthe eigenvalues and eigenvectors.

Data

DSYEVD Example Program Data
  4                         :Value of N
  'L'                       :Value of UPLO
  1.0
  2.0   2.0
  3.0   3.0   3.0
  4.0   4.0   4.0   4.0     :End of matrix A
  'V'                       :Value of JOB

Result

 DSYEVD Example Program Results

 Eigenvalues
    -2.0531 -0.5146 -0.2943 12.8621

 Eigenvectors
          1       2       3       4
 1   0.7003 -0.5144 -0.2767  0.4103
 2   0.3592  0.4851  0.6634  0.4422
 3  -0.1569  0.5420 -0.6504  0.5085
 4  -0.5965 -0.4543  0.2457  0.6144

Source

    Program dsyevd_example

!     DSYEVD Example Program Text

!     Copyright 2017, Numerical Algorithms Group Ltd. http://www.nag.com

!     .. Use Statements ..
      Use lapack_example_aux, Only: nagf_blas_damax_val, &
        nagf_file_print_matrix_real_gen
      Use lapack_interfaces, Only: dsyevd
      Use lapack_precision, Only: dp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Real (Kind=dp), Parameter :: zero = 0.0_dp
      Integer, Parameter :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=dp) :: r
      Integer :: i, ifail, info, k, lda, liwork, lwork, n
      Character (1) :: job, uplo
!     .. Local Arrays ..
      Real (Kind=dp), Allocatable :: a(:, :), w(:), work(:)
      Integer, Allocatable :: iwork(:)
!     .. Executable Statements ..
      Write (nout, *) 'DSYEVD Example Program Results'
!     Skip heading in data file
      Read (nin, *)
      Read (nin, *) n
      lda = n
      liwork = 5*n + 3
      lwork = 2*n*n + 6*n + 1
      Allocate (a(lda,n), w(n), work(lwork), iwork(liwork))

!     Read A from data file

      Read (nin, *) uplo
      If (uplo=='U') Then
        Read (nin, *)(a(i,i:n), i=1, n)
      Else If (uplo=='L') Then
        Read (nin, *)(a(i,1:i), i=1, n)
      End If

      Read (nin, *) job

!     Calculate all the eigenvalues and eigenvectors of A
      Call dsyevd(job, uplo, n, a, lda, w, work, lwork, iwork, liwork, info)

      Write (nout, *)
      If (info>0) Then
        Write (nout, *) 'Failure to converge.'
      Else

!       Print eigenvalues and eigenvectors

        Write (nout, *) 'Eigenvalues'
        Write (nout, 100) w(1:n)
        Write (nout, *)
        Flush (nout)

!       Normalize the eigenvectors: largest element positive
        Do i = 1, n
          Call nagf_blas_damax_val(n, a(1,i), 1, k, r)
          If (a(k,i)<zero) Then
            a(1:n, i) = -a(1:n, i)
          End If
        End Do

!       ifail: behaviour on error exit
!              =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
        ifail = 0
        Call nagf_file_print_matrix_real_gen('General', ' ', n, n, a, lda, &
          'Eigenvectors', ifail)

      End If

100   Format (3X, (8F8.4))
    End Program
Full documentation of DSYEVD


DSYEVR example

Real Symmetric Eigenproblems: Selected eigenvalues and, optionally, eigenvectors of a real symmetric matrix (Relatively Robust Representations)

 To find the eigenvalues with indices in the range $ [2, 3]$, and thecorresponding eigenvectors, of the symmetric matrix

Information on required and provided workspace is also output.

Data

DSYEVR Example Program Data

  4    2    3        :Values of N, IL and IU

  1.0  2.0  3.0  4.0
       2.0  3.0  4.0
            3.0  4.0
                 4.0 :End of matrix A

Result

 DSYEVR Example Program Results

 Selected eigenvalues
    -0.5146 -0.2943
Warning: Floating invalid operation occurred
Warning: Floating divide by zero occurred
 Selected eigenvectors
          1       2
 1  -0.5144  0.2767
 2   0.4851 -0.6634
 3   0.5420  0.6504
 4  -0.4543 -0.2457

Source

    Program dsyevr_example

!     DSYEVR Example Program Text

!     Copyright 2017, Numerical Algorithms Group Ltd. http://www.nag.com

!     .. Use Statements ..
      Use lapack_example_aux, Only: nagf_file_print_matrix_real_gen
      Use lapack_interfaces, Only: dsyevr
      Use lapack_precision, Only: dp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Real (Kind=dp), Parameter :: zero = 0.0E+0_dp
      Integer, Parameter :: nb = 64, nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=dp) :: abstol, vl, vu
      Integer :: i, ifail, il, info, iu, lda, ldz, liwork, lwork, m, n
!     .. Local Arrays ..
      Real (Kind=dp), Allocatable :: a(:, :), w(:), work(:), z(:, :)
      Real (Kind=dp) :: dummy(1)
      Integer :: idum(1)
      Integer, Allocatable :: isuppz(:), iwork(:)
!     .. Intrinsic Procedures ..
      Intrinsic :: max, nint
!     .. Executable Statements ..
      Write (nout, *) 'DSYEVR Example Program Results'
      Write (nout, *)
!     Skip heading in data file and read N and the lower and upper
!     indices of the smallest and largest eigenvalues to be found
      Read (nin, *)
      Read (nin, *) n, il, iu
      lda = n
      ldz = n
      m = n
      Allocate (a(lda,n), w(n), z(ldz,m), isuppz(2*m))

!     Use routine workspace query to get optimal workspace.
      lwork = -1
      liwork = -1
      Call dsyevr('Vectors', 'I', 'Upper', n, a, lda, vl, vu, il, iu, abstol, &
        m, w, z, ldz, isuppz, dummy, lwork, idum, liwork, info)

!     Make sure that there is enough workspace for block size nb.
      lwork = max((nb+6)*n, nint(dummy(1)))
      liwork = max(10*n, idum(1))
      Allocate (work(lwork), iwork(liwork))

!     Read the upper triangular part of the matrix A from data file

      Read (nin, *)(a(i,i:n), i=1, n)

!     Set the absolute error tolerance for eigenvalues.  With ABSTOL
!     set to zero, the default value is used instead

      abstol = zero

!     Solve the symmetric eigenvalue problem
      Call dsyevr('Vectors', 'I', 'Upper', n, a, lda, vl, vu, il, iu, abstol, &
        m, w, z, ldz, isuppz, work, lwork, iwork, liwork, info)

      If (info==0) Then

!       Print solution

        Write (nout, *) 'Selected eigenvalues'
        Write (nout, 100) w(1:m)
        Flush (nout)

!       ifail: behaviour on error exit
!              =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
        ifail = 0
        Call nagf_file_print_matrix_real_gen('General', ' ', n, m, z, ldz, &
          'Selected eigenvectors', ifail)

      Else
        Write (nout, 110) 'Failure in DSYEVR. INFO =', info
      End If

100   Format (3X, (8F8.4))
110   Format (1X, A, I5)
    End Program
Full documentation of DSYEVR


DSYEVX example

Real Symmetric Eigenproblems: Selected eigenvalues and, optionally, eigenvectors of a real symmetric matrix

 To find the eigenvalues in the half-open interval $ (-1, 1]$, and thecorresponding eigenvectors, of the symmetric matrix

Data

DSYEVX Example Program Data
  4                  :Value of N
 -1.0  1.0           :Values of VL and VU
  1.0  2.0  3.0  4.0
       2.0  3.0  4.0
            3.0  4.0
                 4.0 :End of matrix A

Result

 DSYEVX Example Program Results

 Number of eigenvalues found =    2

 Eigenvalues
    -0.5146 -0.2943
 Selected eigenvectors
          1       2
 1  -0.5144  0.2767
 2   0.4851 -0.6634
 3   0.5420  0.6504
 4  -0.4543 -0.2457

Source

    Program dsyevx_example

!     DSYEVX Example Program Text

!     Copyright 2017, Numerical Algorithms Group Ltd. http://www.nag.com

!     .. Use Statements ..
      Use lapack_example_aux, Only: nagf_file_print_matrix_real_gen
      Use lapack_interfaces, Only: dsyevx
      Use lapack_precision, Only: dp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Real (Kind=dp), Parameter :: zero = 0.0E+0_dp
      Integer, Parameter :: nb = 64, nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=dp) :: abstol, vl, vu
      Integer :: i, ifail, il, info, iu, lda, ldz, lwork, m, n
!     .. Local Arrays ..
      Real (Kind=dp), Allocatable :: a(:, :), w(:), work(:), z(:, :)
      Real (Kind=dp) :: dummy(1)
      Integer, Allocatable :: iwork(:), jfail(:)
!     .. Intrinsic Procedures ..
      Intrinsic :: max, nint
!     .. Executable Statements ..
      Write (nout, *) 'DSYEVX Example Program Results'
      Write (nout, *)
!     Skip heading in data file
      Read (nin, *)
      Read (nin, *) n
      lda = n
      ldz = n
      m = n
      Allocate (a(lda,n), w(n), z(ldz,m), iwork(5*n), jfail(n))

!     Read the lower and upper bounds of the interval to be searched.
      Read (nin, *) vl, vu

!     Use routine workspace query to get optimal workspace.
      lwork = -1
      Call dsyevx('Vectors', 'Values in range', 'Upper', n, a, lda, vl, vu, &
        il, iu, abstol, m, w, z, ldz, dummy, lwork, iwork, jfail, info)

!     Make sure that there is enough workspace for block size nb.
      lwork = max((nb+3)*n, nint(dummy(1)))
      Allocate (work(lwork))

!     Read the upper triangular part of the matrix A.

      Read (nin, *)(a(i,i:n), i=1, n)

!     Set the absolute error tolerance for eigenvalues.  With ABSTOL
!     set to zero, the default value is used instead

      abstol = zero

!     Solve the symmetric eigenvalue problem
      Call dsyevx('Vectors', 'Values in range', 'Upper', n, a, lda, vl, vu, &
        il, iu, abstol, m, w, z, ldz, work, lwork, iwork, jfail, info)

      If (info>=0) Then

!       Print solution

        Write (nout, 100) 'Number of eigenvalues found =', m
        Write (nout, *)
        Write (nout, *) 'Eigenvalues'
        Write (nout, 110) w(1:m)
        Flush (nout)

!       ifail: behaviour on error exit
!              =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
        ifail = 0
        Call nagf_file_print_matrix_real_gen('General', ' ', n, m, z, ldz, &
          'Selected eigenvectors', ifail)

        If (info>0) Then
          Write (nout, 100) 'INFO eigenvectors failed to converge, INFO =', &
            info
          Write (nout, *) 'Indices of eigenvectors that did not converge'
          Write (nout, 120) jfail(1:m)
        End If
      Else
        Write (nout, 100) 'Failure in DSYEVX. INFO =', info
      End If

100   Format (1X, A, I5)
110   Format (3X, (8F8.4))
120   Format (3X, (8I8))
    End Program
Full documentation of DSYEVX


LAPACK:Complex Hermitian Eigenproblems

Next: Real Nonsymmetric Eigenproblems Up: LAPACK Routines by Subject Previous: Real Symmetric Eigenproblems

Complex Hermitian Eigenproblems

  • ZHBEV : All eigenvalues and, optionally, eigenvectors of a complex Hermitian band matrix
  • ZHBEVD : All eigenvalues and, optionally, all eigenvectors of complex Hermitian band matrix (divide-and-conquer)
  • ZHBEVX : Selected eigenvalues and, optionally, eigenvectors of a complex Hermitian band matrix
  • ZHEEV : All eigenvalues and, optionally, eigenvectors of a complex Hermitian matrix
  • ZHEEVD : All eigenvalues and, optionally, all eigenvectors of complex Hermitian matrix (divide-and-conquer)
  • ZHEEVR : Selected eigenvalues and, optionally, eigenvectors of a complex Hermitian matrix (Relatively Robust Representations)
  • ZHEEVX : Selected eigenvalues and, optionally, eigenvectors of a complex Hermitian matrix
  • ZHPEV : All eigenvalues and, optionally, eigenvectors of a complex Hermitian matrix, packed storage
  • ZHPEVD : All eigenvalues and, optionally, all eigenvectors of complex Hermitian matrix, packed storage (divide-and-conquer)
  • ZHPEVX : Selected eigenvalues and, optionally, eigenvectors of a complex Hermitian matrix, packed storage


ZHBEV example

Complex Hermitian Eigenproblems: All eigenvalues and, optionally, eigenvectors of a complex Hermitian band matrix

 To find all the eigenvalues and eigenvectors of the Hermitian band matrix

together with approximate error bounds for the computed eigenvalues andeigenvectors.

Data

ZHBEV Example Program Data

   5          2                                          :Values of N and KD

  (1.0, 0.0) (2.0,-1.0) (3.0,-1.0)
             (2.0, 0.0) (3.0,-2.0) (4.0,-2.0)
                        (3.0, 0.0) (4.0,-3.0) (5.0,-3.0)
                                   (4.0, 0.0) (5.0,-4.0)
                                              (5.0, 0.0) :End of matrix A

Result

 ZHBEV Example Program Results

 Eigenvalues
    -6.4185 -1.4094  1.4421  4.4856 16.9002
 Eigenvectors
          1       2       3       4       5
 1  -0.2534  0.6367 -0.2560  0.0171  0.1051
    -0.0538  0.0000  0.3721  0.5500 -0.0983

 2  -0.0662 -0.2578  0.5344 -0.2608  0.2516
     0.4301  0.2413  0.0000  0.4869 -0.1789

 3   0.5274 -0.3039 -0.4245 -0.0399  0.4994
     0.0000 -0.3481  0.0915  0.2142 -0.1513

 4   0.1061  0.3450  0.4964 -0.0253  0.5611
    -0.4981 -0.0832 -0.1546 -0.1700  0.0000

 5  -0.4519 -0.2469 -0.1979  0.5614  0.4837
     0.0424  0.2634 -0.1114 -0.0000  0.2509

 Error estimate for the eigenvalues
        3.8E-15

 Error estimates for the eigenvectors
        7.5E-16    1.3E-15    1.3E-15    1.2E-15    3.0E-16

Source

    Program zhbev_example

!     ZHBEV Example Program Text

!     Copyright 2017, Numerical Algorithms Group Ltd. http://www.nag.com

!     .. Use Statements ..
      Use blas_interfaces, Only: dznrm2
      Use lapack_example_aux, Only: nagf_file_print_matrix_complex_gen
      Use lapack_interfaces, Only: ddisna, zhbev
      Use lapack_precision, Only: dp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter :: nin = 5, nout = 6
      Character (1), Parameter :: uplo = 'U'
!     .. Local Scalars ..
      Complex (Kind=dp) :: scal
      Real (Kind=dp) :: eerrbd, eps
      Integer :: i, ifail, info, j, k, kd, ldab, ldz, n
!     .. Local Arrays ..
      Complex (Kind=dp), Allocatable :: ab(:, :), work(:), z(:, :)
      Real (Kind=dp), Allocatable :: rcondz(:), rwork(:), w(:), zerrbd(:)
!     .. Intrinsic Procedures ..
      Intrinsic :: abs, conjg, epsilon, max, maxloc, min
!     .. Executable Statements ..
      Write (nout, *) 'ZHBEV Example Program Results'
      Write (nout, *)
!     Skip heading in data file
      Read (nin, *)
      Read (nin, *) n, kd
      ldab = kd + 1
      ldz = n
      Allocate (ab(ldab,n), work(n), z(ldz,n), rcondz(n), rwork(3*n-2), w(n), &
        zerrbd(n))

!     Read the upper or lower triangular part of the symmetric band
!     matrix A from data file

      If (uplo=='U') Then
        Read (nin, *)((ab(kd+1+i-j,j),j=i,min(n,i+kd)), i=1, n)
      Else If (uplo=='L') Then
        Read (nin, *)((ab(1+i-j,j),j=max(1,i-kd),i), i=1, n)
      End If

!     Solve the band Hermitian eigenvalue problem
      Call zhbev('Vectors', uplo, n, kd, ab, ldab, w, z, ldz, work, rwork, &
        info)

      If (info==0) Then

!       Print solution

        Write (nout, *) 'Eigenvalues'
        Write (nout, 100) w(1:n)
        Flush (nout)

!       Normalize the eigenvectors, largest element real
        Do i = 1, n
          rwork(1:n) = abs(z(1:n,i))
          k = maxloc(rwork(1:n), 1)
          scal = conjg(z(k,i))/abs(z(k,i))/dznrm2(n, z(1,i), 1)
          z(1:n, i) = z(1:n, i)*scal
        End Do

!       ifail: behaviour on error exit
!              =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
        ifail = 0
        Call nagf_file_print_matrix_complex_gen('General', ' ', n, n, z, ldz, &
          'Eigenvectors', ifail)

!       Get the machine precision, EPS and compute the approximate
!       error bound for the computed eigenvalues.  Note that for
!       the 2-norm, max( abs(W(i)) ) = norm(A), and since the
!       eigenvalues are returned in ascending order
!       max( abs(W(i)) ) = max( abs(W(1)), abs(W(n)))

        eps = epsilon(1.0E0_dp)
        eerrbd = eps*max(abs(w(1)), abs(w(n)))

!       Call DDISNA to estimate reciprocal condition
!       numbers for the eigenvectors
        Call ddisna('Eigenvectors', n, n, w, rcondz, info)

!       Compute the error estimates for the eigenvectors

        Do i = 1, n
          zerrbd(i) = eerrbd/rcondz(i)
        End Do

!       Print the approximate error bounds for the eigenvalues
!       and vectors

        Write (nout, *)
        Write (nout, *) 'Error estimate for the eigenvalues'
        Write (nout, 110) eerrbd
        Write (nout, *)
        Write (nout, *) 'Error estimates for the eigenvectors'
        Write (nout, 110) zerrbd(1:n)
      Else
        Write (nout, 120) 'Failure in ZHBEV. INFO =', info
      End If

100   Format (3X, (8F8.4))
110   Format (4X, 1P, 6E11.1)
120   Format (1X, A, I4)
    End Program
Full documentation of ZHBEV


ZHBEVD example

Complex Hermitian Eigenproblems: All eigenvalues and, optionally, all eigenvectors of complex Hermitian band matrix (divide-and-conquer)

 To find all the eigenvalues and eigenvectors of the Hermitian band matrix

The example program for ZHBEV illustrates the computation of error bounds forthe eigenvalues and eigenvectors..

Data

ZHBEVD Example Program Data
  5  2                                                   :Values of N and KD
  'L'                                                    :Value of UPLO
  (1.0, 0.0)
  (2.0, 1.0) (2.0, 0.0)
  (3.0, 1.0) (3.0, 2.0) (3.0, 0.0)
             (4.0, 2.0) (4.0, 3.0) (4.0, 0.0)
                        (5.0, 3.0) (5.0, 4.0) (5.0, 0.0) :End of matrix A
  'V'                                                    :Value of JOB

Result

 ZHBEVD Example Program Results

 Eigenvalues
       1      -6.4185
       2      -1.4094
       3       1.4421
       4       4.4856
       5      16.9002

 Eigenvectors
          1       2       3       4       5
 1  -0.2534  0.6367 -0.2560  0.0171  0.1051
    -0.0538  0.0000  0.3721  0.5500 -0.0983

 2  -0.0662 -0.2578  0.5344 -0.2608  0.2516
     0.4301  0.2413  0.0000  0.4869 -0.1789

 3   0.5274 -0.3039 -0.4245 -0.0399  0.4994
     0.0000 -0.3481  0.0915  0.2142 -0.1513

 4   0.1061  0.3450  0.4964 -0.0253  0.5611
    -0.4981 -0.0832 -0.1546 -0.1700  0.0000

 5  -0.4519 -0.2469 -0.1979  0.5614  0.4837
     0.0424  0.2634 -0.1114  0.0000  0.2509

Source

    Program zhbevd_example

!     ZHBEVD Example Program Text

!     Copyright 2017, Numerical Algorithms Group Ltd. http://www.nag.com

!     .. Use Statements ..
      Use blas_interfaces, Only: dznrm2
      Use lapack_example_aux, Only: nagf_file_print_matrix_complex_gen
      Use lapack_interfaces, Only: zhbevd
      Use lapack_precision, Only: dp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter :: nin = 5, nout = 6
!     .. Local Scalars ..
      Complex (Kind=dp) :: scal
      Integer :: i, ifail, info, j, k, kd, ldab, ldz, liwork, lrwork, lwork, n
      Character (1) :: job, uplo
!     .. Local Arrays ..
      Complex (Kind=dp), Allocatable :: ab(:, :), work(:), z(:, :)
      Real (Kind=dp), Allocatable :: rwork(:), w(:)
      Integer, Allocatable :: iwork(:)
!     .. Intrinsic Procedures ..
      Intrinsic :: abs, conjg, max, maxloc, min
!     .. Executable Statements ..
      Write (nout, *) 'ZHBEVD Example Program Results'
!     Skip heading in data file
      Read (nin, *)
      Read (nin, *) n, kd
      ldab = n
      ldz = n
      liwork = 5*n + 3
      lrwork = 2*n*n + 5*n + 1
      lwork = 2*n*n
      Allocate (ab(ldab,n), work(lwork), z(ldz,n), rwork(lrwork), w(n), &
        iwork(liwork))

!     Read A from data file

      Read (nin, *) uplo
      If (uplo=='U') Then
        Do i = 1, n
          Read (nin, *)(ab(kd+1+i-j,j), j=i, min(n,i+kd))
        End Do
      Else If (uplo=='L') Then
        Do i = 1, n
          Read (nin, *)(ab(1+i-j,j), j=max(1,i-kd), i)
        End Do
      End If

      Read (nin, *) job

!     Calculate all the eigenvalues and eigenvectors of A
      Call zhbevd(job, uplo, n, kd, ab, ldab, w, z, ldz, work, lwork, rwork, &
        lrwork, iwork, liwork, info)

      Write (nout, *)
      If (info>0) Then
        Write (nout, *) 'Failure to converge.'
      Else

!       Print eigenvalues and eigenvectors

        Write (nout, *) 'Eigenvalues'
        Do i = 1, n
          Write (nout, 100) i, w(i)
        End Do
        Write (nout, *)
        Flush (nout)

!       Normalize the eigenvectors, largest element real
        Do i = 1, n
          rwork(1:n) = abs(z(1:n,i))
          k = maxloc(rwork(1:n), 1)
          scal = conjg(z(k,i))/abs(z(k,i))/dznrm2(n, z(1,i), 1)
          z(1:n, i) = z(1:n, i)*scal
        End Do

!       ifail: behaviour on error exit
!              =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
        ifail = 0
        Call nagf_file_print_matrix_complex_gen('General', ' ', n, n, z, ldz, &
          'Eigenvectors', ifail)

      End If

100   Format (3X, I5, 5X, 2F8.4)
    End Program
Full documentation of ZHBEVD


ZHBEVX example

Complex Hermitian Eigenproblems: Selected eigenvalues and, optionally, eigenvectors of a complex Hermitian band matrix

 To find the eigenvalues in the half-open interval $ (-2, 2]$, and thecorresponding eigenvectors, of the Hermitian band matrix

Data

ZHBEVX Example Program Data

   5          2                                          :Values of N and KD

  -2.0        2.0                                        :Values of VL and VU

  (1.0, 0.0) (2.0,-1.0) (3.0,-1.0)
             (2.0, 0.0) (3.0,-2.0) (4.0,-2.0)
                        (3.0, 0.0) (4.0,-3.0) (5.0,-3.0)
                                   (4.0, 0.0) (5.0,-4.0)
                                              (5.0, 0.0) :End of matrix A

Result

 ZHBEVX Example Program Results

 Number of eigenvalues found =    2

 Eigenvalues
    -1.4094  1.4421
 Selected eigenvectors
          1       2
 1   0.6367  0.4516
     0.0000  0.0000

 2  -0.2578 -0.3029
     0.2413 -0.4402

 3  -0.3039  0.3160
    -0.3481  0.2978

 4   0.3450 -0.4088
    -0.0832 -0.3213

 5  -0.2469  0.0204
     0.2634  0.2262

Source

    Program zhbevx_example

!     ZHBEVX Example Program Text

!     Copyright 2017, Numerical Algorithms Group Ltd. http://www.nag.com

!     .. Use Statements ..
      Use lapack_example_aux, Only: nagf_file_print_matrix_complex_gen
      Use lapack_interfaces, Only: zhbevx
      Use lapack_precision, Only: dp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Real (Kind=dp), Parameter :: zero = 0.0E+0_dp
      Integer, Parameter :: nin = 5, nout = 6
      Character (1), Parameter :: uplo = 'U'
!     .. Local Scalars ..
      Real (Kind=dp) :: abstol, vl, vu
      Integer :: i, ifail, il, info, iu, j, kd, ldab, ldq, ldz, m, n
!     .. Local Arrays ..
      Complex (Kind=dp), Allocatable :: ab(:, :), q(:, :), work(:), z(:, :)
      Real (Kind=dp), Allocatable :: rwork(:), w(:)
      Integer, Allocatable :: iwork(:), jfail(:)
!     .. Intrinsic Procedures ..
      Intrinsic :: max, min
!     .. Executable Statements ..
      Write (nout, *) 'ZHBEVX Example Program Results'
      Write (nout, *)
!     Skip heading in data file
      Read (nin, *)
      Read (nin, *) n, kd
      ldab = kd + 1
      ldq = n
      ldz = n
      m = n
      Allocate (ab(ldab,n), q(ldq,n), work(n), z(ldz,m), rwork(7*n), w(n), &
        iwork(5*n), jfail(n))

!     Read the lower and upper bounds of the interval to be searched,
!     and read the upper or lower triangular part of the matrix A
!     from data file

      Read (nin, *) vl, vu
      If (uplo=='U') Then
        Read (nin, *)((ab(kd+1+i-j,j),j=i,min(n,i+kd)), i=1, n)
      Else If (uplo=='L') Then
        Read (nin, *)((ab(1+i-j,j),j=max(1,i-kd),i), i=1, n)
      End If

!     Set the absolute error tolerance for eigenvalues.  With ABSTOL
!     set to zero, the default value is used instead

      abstol = zero

!     Solve the band symmetric eigenvalue problem
      Call zhbevx('Vectors', 'Values in range', uplo, n, kd, ab, ldab, q, ldq, &
        vl, vu, il, iu, abstol, m, w, z, ldz, work, rwork, iwork, jfail, info)

      If (info>=0) Then

!       Print solution

        Write (nout, 100) 'Number of eigenvalues found =', m
        Write (nout, *)
        Write (nout, *) 'Eigenvalues'
        Write (nout, 110) w(1:m)
        Flush (nout)

!       ifail: behaviour on error exit
!              =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
        ifail = 0
        Call nagf_file_print_matrix_complex_gen('General', ' ', n, m, z, ldz, &
          'Selected eigenvectors', ifail)

        If (info>0) Then
          Write (nout, 100) 'INFO eigenvectors failed to converge, INFO =', &
            info
          Write (nout, *) 'Indices of eigenvectors that did not converge'
          Write (nout, 120) jfail(1:m)
        End If
      Else
        Write (nout, 100) 'Failure in ZHBEVX. INFO =', info
      End If

100   Format (1X, A, I5)
110   Format (3X, (8F8.4))
120   Format (3X, (8I8))
    End Program
Full documentation of ZHBEVX


ZHEEV example

Complex Hermitian Eigenproblems: All eigenvalues and, optionally, eigenvectors of a complex Hermitian matrix

 To find all the eigenvalues and eigenvectors of the Hermitian matrix

together with approximate error bounds for the computed eigenvalues andeigenvectors.

Data

ZHEEV Example Program Data

  4                                                :Value of N

 (1.0, 0.0)  (2.0, -1.0)  (3.0, -1.0)  (4.0, -1.0)
             (2.0,  0.0)  (3.0, -2.0)  (4.0, -2.0)
                          (3.0,  0.0)  (4.0, -3.0)
                                       (4.0,  0.0) :End of matrix A

Result

 ZHEEV Example Program Results

 Eigenvalues
    -4.2443 -0.6886  1.1412 13.7916

 Eigenvectors
          1       2       3       4
 1  -0.3839  0.6470  0.0179  0.3309
    -0.2941  0.0000 -0.4453 -0.1986

 2  -0.4512 -0.4984  0.5706  0.3728
     0.1102 -0.1130 -0.0000 -0.2419

 3   0.0263  0.2949 -0.1530  0.4870
     0.4857  0.3165  0.5273 -0.1938

 4   0.5602 -0.2241 -0.2118  0.6155
     0.0000 -0.2878 -0.3598  0.0000

 Error estimate for the eigenvalues
        3.1E-15

 Error estimates for the eigenvectors
        8.6E-16    1.7E-15    1.7E-15    2.4E-16

Source

    Program zheev_example

!     ZHEEV Example Program Text

!     Copyright 2017, Numerical Algorithms Group Ltd. http://www.nag.com

!     .. Use Statements ..
      Use blas_interfaces, Only: zscal
      Use lapack_example_aux, Only: nagf_file_print_matrix_complex_gen
      Use lapack_interfaces, Only: ddisna, zheev
      Use lapack_precision, Only: dp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter :: nb = 64, nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=dp) :: eerrbd, eps
      Integer :: i, ifail, info, k, lda, lwork, n
!     .. Local Arrays ..
      Complex (Kind=dp), Allocatable :: a(:, :), work(:)
      Complex (Kind=dp) :: dummy(1)
      Real (Kind=dp), Allocatable :: rcondz(:), rwork(:), w(:), zerrbd(:)
!     .. Intrinsic Procedures ..
      Intrinsic :: abs, cmplx, conjg, epsilon, max, maxloc, nint, real
!     .. Executable Statements ..
      Write (nout, *) 'ZHEEV Example Program Results'
      Write (nout, *)
!     Skip heading in data file
      Read (nin, *)
      Read (nin, *) n
      lda = n
      Allocate (a(lda,n), rcondz(n), rwork(3*n-2), w(n), zerrbd(n))

!     Use routine workspace query to get optimal workspace.
      lwork = -1
      Call zheev('Vectors', 'Upper', n, a, lda, w, dummy, lwork, rwork, info)

!     Make sure that there is enough workspace for block size nb.
      lwork = max((nb+1)*n, nint(real(dummy(1))))
      Allocate (work(lwork))

!     Read the upper triangular part of the matrix A from data file

      Read (nin, *)(a(i,i:n), i=1, n)

!     Solve the Hermitian eigenvalue problem
      Call zheev('Vectors', 'Upper', n, a, lda, w, work, lwork, rwork, info)

      If (info==0) Then

!       Print solution

        Write (nout, *) 'Eigenvalues'
        Write (nout, 100) w(1:n)

        Write (nout, *)
        Flush (nout)

!       Normalize the eigenvectors so that the element of largest absolute
!       value is real.
        Do i = 1, n
          rwork(1:n) = abs(a(1:n,i))
          k = maxloc(rwork(1:n), 1)
          Call zscal(n, conjg(a(k,i))/cmplx(abs(a(k,i)),kind=dp), a(1,i), 1)
        End Do

!       ifail: behaviour on error exit
!              =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
        ifail = 0
        Call nagf_file_print_matrix_complex_gen('General', ' ', n, n, a, lda, &
          'Eigenvectors', ifail)

!       Get the machine precision, EPS and compute the approximate
!       error bound for the computed eigenvalues.  Note that for
!       the 2-norm, max( abs(W(i)) ) = norm(A), and since the
!       eigenvalues are returned in descending order
!       max( abs(W(i)) ) = max( abs(W(1)), abs(W(n)))

        eps = epsilon(1.0E0_dp)
        eerrbd = eps*max(abs(w(1)), abs(w(n)))

!       Call DDISNA to estimate reciprocal condition
!       numbers for the eigenvectors
        Call ddisna('Eigenvectors', n, n, w, rcondz, info)

!       Compute the error estimates for the eigenvectors

        Do i = 1, n
          zerrbd(i) = eerrbd/rcondz(i)
        End Do

!       Print the approximate error bounds for the eigenvalues
!       and vectors

        Write (nout, *)
        Write (nout, *) 'Error estimate for the eigenvalues'
        Write (nout, 110) eerrbd
        Write (nout, *)
        Write (nout, *) 'Error estimates for the eigenvectors'
        Write (nout, 110) zerrbd(1:n)
      Else
        Write (nout, 120) 'Failure in ZHEEV. INFO =', info
      End If

100   Format (3X, (8F8.4))
110   Format (4X, 1P, 6E11.1)
120   Format (1X, A, I4)
    End Program
Full documentation of ZHEEV


ZHEEVD example

Complex Hermitian Eigenproblems: All eigenvalues and, optionally, all eigenvectors of complex Hermitian matrix (divide-and-conquer)

 To find all the eigenvalues and eigenvectors of the Hermitian matrix

The example program for ZHEEV illustrates the computation of error bounds forthe eigenvalues and eigenvectors.

Data

ZHEEVD Example Program Data
  4                                                  :Value of N
  'L'                                                :Value of UPLO
  (1.0, 0.0)
  (2.0, 1.0)  (2.0, 0.0)
  (3.0, 1.0)  (3.0, 2.0)  (3.0, 0.0)
  (4.0, 1.0)  (4.0, 2.0)  (4.0, 3.0)  (4.0, 0.0)     :End of matrix A
  'V'                                                :Value of JOB

Result

 ZHEEVD Example Program Results

 Eigenvalues
       1      -4.2443
       2      -0.6886
       3       1.1412
       4      13.7916

 Eigenvectors
          1       2       3       4
 1  -0.3839  0.6470  0.0179  0.3309
    -0.2941  0.0000 -0.4453 -0.1986

 2  -0.4512 -0.4984  0.5706  0.3728
     0.1102 -0.1130  0.0000 -0.2419

 3   0.0263  0.2949 -0.1530  0.4870
     0.4857  0.3165  0.5273 -0.1938

 4   0.5602 -0.2241 -0.2118  0.6155
     0.0000 -0.2878 -0.3598  0.0000

Source

    Program zheevd_example

!     ZHEEVD Example Program Text

!     Copyright 2017, Numerical Algorithms Group Ltd. http://www.nag.com

!     .. Use Statements ..
      Use blas_interfaces, Only: zscal
      Use lapack_example_aux, Only: nagf_file_print_matrix_complex_gen
      Use lapack_interfaces, Only: zheevd
      Use lapack_precision, Only: dp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter :: nin = 5, nout = 6
!     .. Local Scalars ..
      Integer :: i, ifail, info, k, lda, liwork, lrwork, lwork, n
      Character (1) :: job, uplo
!     .. Local Arrays ..
      Complex (Kind=dp), Allocatable :: a(:, :), work(:)
      Real (Kind=dp), Allocatable :: rwork(:), w(:)
      Integer, Allocatable :: iwork(:)
!     .. Intrinsic Procedures ..
      Intrinsic :: abs, cmplx, conjg, maxloc
!     .. Executable Statements ..
      Write (nout, *) 'ZHEEVD Example Program Results'
!     Skip heading in data file
      Read (nin, *)
      Read (nin, *) n
      lda = n
      liwork = 5*n + 3
      lrwork = 2*n*n + 5*n + 1
      lwork = n*(n+2)
      Allocate (a(lda,n), work(lwork), rwork(lrwork), w(n), iwork(liwork))
      Read (nin, *) uplo

!     Read A from data file

      If (uplo=='U') Then
        Read (nin, *)(a(i,i:n), i=1, n)
      Else If (uplo=='L') Then
        Read (nin, *)(a(i,1:i), i=1, n)
      End If

      Read (nin, *) job

!     Calculate all the eigenvalues and eigenvectors of A
      Call zheevd(job, uplo, n, a, lda, w, work, lwork, rwork, lrwork, iwork, &
        liwork, info)

      Write (nout, *)
      If (info>0) Then
        Write (nout, *) 'Failure to converge.'
      Else

!       Print eigenvalues and eigenvectors

        Write (nout, *) 'Eigenvalues'
        Do i = 1, n
          Write (nout, 100) i, w(i)
        End Do
        Write (nout, *)
        Flush (nout)

!       Normalize the eigenvectors so that the element of largest absolute
!       value is real.
        Do i = 1, n
          rwork(1:n) = abs(a(1:n,i))
          k = maxloc(rwork(1:n), 1)
          Call zscal(n, conjg(a(k,i))/cmplx(abs(a(k,i)),kind=dp), a(1,i), 1)
        End Do

!       ifail: behaviour on error exit
!              =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
        ifail = 0
        Call nagf_file_print_matrix_complex_gen('General', ' ', n, n, a, lda, &
          'Eigenvectors', ifail)

      End If

100   Format (3X, I5, 5X, 2F8.4)
    End Program
Full documentation of ZHEEVD


ZHEEVR example

Complex Hermitian Eigenproblems: Selected eigenvalues and, optionally, eigenvectors of a complex Hermitian matrix (Relatively Robust Representations)

 To find the eigenvalues with indices in the range $ [2, 3]$, and thecorresponding eigenvectors, of the Hermitian matrix

Information on required and provided workspace is also output.

Data

ZHEEVR Example Program Data

   4           2           3                         :Values of N, IL and IU

  (1.0, 0.0)  (2.0,-1.0)  (3.0,-1.0)  (4.0,-1.0)
              (2.0, 0.0)  (3.0,-2.0)  (4.0,-2.0)
                          (3.0, 0.0)  (4.0,-3.0)
                                      (4.0, 0.0)     :End of matrix A

Result

 ZHEEVR Example Program Results

 Selected eigenvalues
    -0.6886  1.1412
Warning: Floating invalid operation occurred
Warning: Floating divide by zero occurred
 Selected eigenvectors
          1       2
 1   0.6470  0.0179
     0.0000 -0.4453

 2  -0.4984  0.5706
    -0.1130 -0.0000

 3   0.2949 -0.1530
     0.3165  0.5273

 4  -0.2241 -0.2118
    -0.2878 -0.3598

Source

    Program zheevr_example

!     ZHEEVR Example Program Text

!     Copyright 2017, Numerical Algorithms Group Ltd. http://www.nag.com

!     .. Use Statements ..
      Use blas_interfaces, Only: zscal
      Use lapack_example_aux, Only: nagf_file_print_matrix_complex_gen
      Use lapack_interfaces, Only: zheevr
      Use lapack_precision, Only: dp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Real (Kind=dp), Parameter :: zero = 0.0E+0_dp
      Integer, Parameter :: nb = 64, nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=dp) :: abstol, vl, vu
      Integer :: i, ifail, il, info, iu, k, lda, ldz, liwork, lrwork, lwork, &
        m, n
!     .. Local Arrays ..
      Complex (Kind=dp), Allocatable :: a(:, :), work(:), z(:, :)
      Complex (Kind=dp) :: dummy(1)
      Real (Kind=dp) :: rdum(1)
      Real (Kind=dp), Allocatable :: rwork(:), w(:)
      Integer :: idum(1)
      Integer, Allocatable :: isuppz(:), iwork(:)
!     .. Intrinsic Procedures ..
      Intrinsic :: abs, cmplx, conjg, max, maxloc, nint, real
!     .. Executable Statements ..
      Write (nout, *) 'ZHEEVR Example Program Results'
      Write (nout, *)
!     Skip heading in data file and read N and the lower and upper
!     indices of the smallest and largest eigenvalues to be found
      Read (nin, *)
      Read (nin, *) n, il, iu
      lda = n
      ldz = n
      m = n
      Allocate (a(lda,n), z(ldz,m), w(n), isuppz(2*m))

!     Use routine workspace query to get optimal workspace.
      lwork = -1
      liwork = -1
      lrwork = -1
      Call zheevr('Vectors', 'I', 'Upper', n, a, lda, vl, vu, il, iu, abstol, &
        m, w, z, ldz, isuppz, dummy, lwork, rdum, lrwork, idum, liwork, info)

!     Make sure that there is enough workspace for block size nb.
      lwork = max((nb+1)*n, nint(real(dummy(1))))
      lrwork = max(24*n, nint(rdum(1)))
      liwork = max(10*n, idum(1))
      Allocate (work(lwork), rwork(lrwork), iwork(liwork))

!     Read the upper triangular part of the matrix A from data file

      Read (nin, *)(a(i,i:n), i=1, n)

!     Set the absolute error tolerance for eigenvalues.  With ABSTOL
!     set to zero, the default value is used instead

      abstol = zero

!     Solve the symmetric eigenvalue problem

      Call zheevr('Vectors', 'I', 'Upper', n, a, lda, vl, vu, il, iu, abstol, &
        m, w, z, ldz, isuppz, work, lwork, rwork, lrwork, iwork, liwork, info)

      If (info==0) Then

!       Print solution

        Write (nout, *) 'Selected eigenvalues'
        Write (nout, 100) w(1:m)
        Flush (nout)

!       Normalize the eigenvectors so that the element of largest absolute
!       value is real.
        Do i = 1, m
          rwork(1:n) = abs(z(1:n,i))
          k = maxloc(rwork(1:n), 1)
          Call zscal(n, conjg(z(k,i))/cmplx(abs(z(k,i)),kind=dp), z(1,i), 1)
        End Do

!       ifail: behaviour on error exit
!              =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
        ifail = 0
        Call nagf_file_print_matrix_complex_gen('General', ' ', n, m, z, ldz, &
          'Selected eigenvectors', ifail)
      Else
        Write (nout, 110) 'Failure in ZHEEVR. INFO =', info
      End If

100   Format (3X, (8F8.4))
110   Format (1X, A, I5)
    End Program
Full documentation of ZHEEVR


ZHEEVX example

Complex Hermitian Eigenproblems: Selected eigenvalues and, optionally, eigenvectors of a complex Hermitian matrix

 To find the eigenvalues in the half-open interval $ (-2, 2]$, and thecorresponding eigenvectors, of the Hermitian matrix

Data

ZHEEVX Example Program Data
  4                                                :Value of N
 -2.0         2.0                                  :Values of VL and VU
 (1.0, 0.0)  (2.0, -1.0)  (3.0, -1.0)  (4.0, -1.0)
             (2.0,  0.0)  (3.0, -2.0)  (4.0, -2.0)
                          (3.0,  0.0)  (4.0, -3.0)
                                       (4.0,  0.0) :End of matrix A

Result

 ZHEEVX Example Program Results

 Number of eigenvalues found =    2

 Eigenvalues
    -0.6886  1.1412
 Selected eigenvectors
          1       2
 1   0.6470  0.0179
     0.0000 -0.4453

 2  -0.4984  0.5706
    -0.1130  0.0000

 3   0.2949 -0.1530
     0.3165  0.5273

 4  -0.2241 -0.2118
    -0.2878 -0.3598

Source

    Program zheevx_example

!     ZHEEVX Example Program Text

!     Copyright 2017, Numerical Algorithms Group Ltd. http://www.nag.com

!     .. Use Statements ..
      Use blas_interfaces, Only: zscal
      Use lapack_example_aux, Only: nagf_file_print_matrix_complex_gen
      Use lapack_interfaces, Only: zheevx
      Use lapack_precision, Only: dp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Real (Kind=dp), Parameter :: zero = 0.0E+0_dp
      Integer, Parameter :: nb = 64, nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=dp) :: abstol, vl, vu
      Integer :: i, ifail, il, info, iu, k, lda, ldz, lwork, m, n
!     .. Local Arrays ..
      Complex (Kind=dp), Allocatable :: a(:, :), work(:), z(:, :)
      Complex (Kind=dp) :: dummy(1)
      Real (Kind=dp), Allocatable :: rwork(:), w(:)
      Integer, Allocatable :: iwork(:), jfail(:)
!     .. Intrinsic Procedures ..
      Intrinsic :: abs, cmplx, conjg, max, maxloc, nint, real
!     .. Executable Statements ..
      Write (nout, *) 'ZHEEVX Example Program Results'
      Write (nout, *)
!     Skip heading in data file
      Read (nin, *)
      Read (nin, *) n
      lda = n
      ldz = n
      m = n
      Allocate (a(lda,n), z(ldz,m), rwork(7*n), w(n), iwork(5*n), jfail(n))

!     Read the lower and upper bounds of the interval to be searched.
      Read (nin, *) vl, vu

!     Use routine workspace query to get optimal workspace.
      lwork = -1
      Call zheevx('Vectors', 'Values in range', 'Upper', n, a, lda, vl, vu, &
        il, iu, abstol, m, w, z, ldz, dummy, lwork, rwork, iwork, jfail, info)

!     Make sure that there is enough workspace for block size nb.
      lwork = max((nb+1)*n, nint(real(dummy(1))))
      Allocate (work(lwork))

!     Read the upper triangular part of the matrix A.

      Read (nin, *)(a(i,i:n), i=1, n)

!     Set the absolute error tolerance for eigenvalues.  With ABSTOL
!     set to zero, the default value is used instead

      abstol = zero

!     Solve the Hermitian eigenvalue problem

      Call zheevx('Vectors', 'Values in range', 'Upper', n, a, lda, vl, vu, &
        il, iu, abstol, m, w, z, ldz, work, lwork, rwork, iwork, jfail, info)

      If (info>=0) Then

!       Print solution

        Write (nout, 100) 'Number of eigenvalues found =', m
        Write (nout, *)
        Write (nout, *) 'Eigenvalues'
        Write (nout, 110) w(1:m)
        Flush (nout)

!       Normalize the eigenvectors so that the element of largest absolute
!       value is real.
        Do i = 1, m
          rwork(1:n) = abs(z(1:n,i))
          k = maxloc(rwork(1:n), 1)
          Call zscal(n, conjg(z(k,i))/cmplx(abs(z(k,i)),kind=dp), z(1,i), 1)
        End Do

!       ifail: behaviour on error exit
!              =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
        ifail = 0
        Call nagf_file_print_matrix_complex_gen('General', ' ', n, m, z, ldz, &
          'Selected eigenvectors', ifail)

        If (info>0) Then
          Write (nout, 100) 'INFO eigenvectors failed to converge, INFO =', &
            info
          Write (nout, *) 'Indices of eigenvectors that did not converge'
          Write (nout, 120) jfail(1:m)
        End If
      Else
        Write (nout, 100) 'Failure in ZHEEVX. INFO =', info
      End If

100   Format (1X, A, I5)
110   Format (3X, (8F8.4))
120   Format (3X, (8I8))
    End Program
Full documentation of ZHEEVX


ZHPEV example

Complex Hermitian Eigenproblems: All eigenvalues and, optionally, eigenvectors of a complex Hermitian matrix, packed storage

 To find all the eigenvalues of the Hermitian matrix

together with an approximate error bound for the computed eigenvalues.

Data

ZHPEV Example Program Data

  4                                                :Value of N

 (1.0, 0.0)  (2.0, -1.0)  (3.0, -1.0)  (4.0, -1.0)
             (2.0,  0.0)  (3.0, -2.0)  (4.0, -2.0)
                          (3.0,  0.0)  (4.0, -3.0)
                                       (4.0,  0.0) :End of matrix A

Result

 ZHPEV Example Program Results

 Eigenvalues
    -4.2443 -0.6886  1.1412 13.7916

 Error estimate for the eigenvalues
        3.1E-15

Source

    Program zhpev_example

!     ZHPEV Example Program Text

!     Copyright 2017, Numerical Algorithms Group Ltd. http://www.nag.com

!     .. Use Statements ..
      Use lapack_interfaces, Only: zhpev
      Use lapack_precision, Only: dp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter :: nin = 5, nout = 6
      Character (1), Parameter :: uplo = 'U'
!     .. Local Scalars ..
      Real (Kind=dp) :: eerrbd, eps
      Integer :: i, info, j, n
!     .. Local Arrays ..
      Complex (Kind=dp), Allocatable :: ap(:), work(:)
      Complex (Kind=dp) :: dummy(1, 1)
      Real (Kind=dp), Allocatable :: rwork(:), w(:)
!     .. Intrinsic Procedures ..
      Intrinsic :: abs, epsilon, max
!     .. Executable Statements ..
      Write (nout, *) 'ZHPEV Example Program Results'
      Write (nout, *)
!     Skip heading in data file
      Read (nin, *)
      Read (nin, *) n

      Allocate (ap((n*(n+1))/2), work(2*n-1), rwork(3*n-2), w(n))

!     Read the upper or lower triangular part of the matrix A from
!     data file

      If (uplo=='U') Then
        Read (nin, *)((ap(i+(j*(j-1))/2),j=i,n), i=1, n)
      Else If (uplo=='L') Then
        Read (nin, *)((ap(i+((2*n-j)*(j-1))/2),j=1,i), i=1, n)
      End If

!     Solve the Hermitian eigenvalue problem

      Call zhpev('No vectors', uplo, n, ap, w, dummy, 1, work, rwork, info)

      If (info==0) Then

!       Print solution

        Write (nout, *) 'Eigenvalues'
        Write (nout, 100) w(1:n)

!       Get the machine precision, EPS and compute the approximate
!       error bound for the computed eigenvalues.  Note that for
!       the 2-norm, max( abs(W(i)) ) = norm(A), and since the
!       eigenvalues are returned in ascending order
!       max( abs(W(i)) ) = max( abs(W(1)), abs(W(n)))

        eps = epsilon(1.0E0_dp)
        eerrbd = eps*max(abs(w(1)), abs(w(n)))

!       Print the approximate error bound for the eigenvalues

        Write (nout, *)
        Write (nout, *) 'Error estimate for the eigenvalues'
        Write (nout, 110) eerrbd
      Else
        Write (nout, 120) 'Failure in ZHPEV. INFO =', info
      End If

100   Format (3X, (8F8.4))
110   Format (4X, 1P, 6E11.1)
120   Format (1X, A, I4)
    End Program
Full documentation of ZHPEV


ZHPEVD example

Complex Hermitian Eigenproblems: All eigenvalues and, optionally, all eigenvectors of complex Hermitian matrix, packed storage (divide-and-conquer)

 To find all the eigenvalues and eigenvectors of the Hermitian matrix

The example program for ZHPEV illustrates the computation of error bounds forthe eigenvalues.

Data

ZHPEVD Example Program Data
  4                                                  :Value of N
  'L'                                                :Value of UPLO
  (1.0, 0.0)
  (2.0, 1.0)  (2.0, 0.0)
  (3.0, 1.0)  (3.0, 2.0)  (3.0, 0.0)
  (4.0, 1.0)  (4.0, 2.0)  (4.0, 3.0)  (4.0, 0.0)     :End of matrix A
  'V'                                                :Value of JOB

Result

 ZHPEVD Example Program Results

 Eigenvalues
       1      -4.2443
       2      -0.6886
       3       1.1412
       4      13.7916

 Eigenvectors
          1       2       3       4
 1  -0.3839  0.6470  0.0179  0.3309
    -0.2941  0.0000 -0.4453 -0.1986

 2  -0.4512 -0.4984  0.5706  0.3728
     0.1102 -0.1130  0.0000 -0.2419

 3   0.0263  0.2949 -0.1530  0.4870
     0.4857  0.3165  0.5273 -0.1938

 4   0.5602 -0.2241 -0.2118  0.6155
     0.0000 -0.2878 -0.3598  0.0000

Source

    Program zhpevd_example

!     ZHPEVD Example Program Text

!     Copyright 2017, Numerical Algorithms Group Ltd. http://www.nag.com

!     .. Use Statements ..
      Use blas_interfaces, Only: dznrm2
      Use lapack_example_aux, Only: nagf_file_print_matrix_complex_gen
      Use lapack_interfaces, Only: zhpevd
      Use lapack_precision, Only: dp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter :: nin = 5, nout = 6
!     .. Local Scalars ..
      Complex (Kind=dp) :: scal
      Integer :: i, ifail, info, j, k, ldz, liwork, lrwork, lwork, n
      Character (1) :: job, uplo
!     .. Local Arrays ..
      Complex (Kind=dp), Allocatable :: ap(:), work(:), z(:, :)
      Real (Kind=dp), Allocatable :: rwork(:), w(:)
      Integer, Allocatable :: iwork(:)
!     .. Intrinsic Procedures ..
      Intrinsic :: abs, conjg, maxloc
!     .. Executable Statements ..
      Write (nout, *) 'ZHPEVD Example Program Results'
!     Skip heading in data file
      Read (nin, *)
      Read (nin, *) n
      ldz = n
      liwork = 5*n + 3
      lrwork = 2*n*n + 5*n + 1
      lwork = 2*n
      Allocate (ap(n*(n+1)/2), work(lwork), z(ldz,n), rwork(lrwork), w(n), &
        iwork(liwork))
      Read (nin, *) uplo

!     Read A from data file

      If (uplo=='U') Then
        Read (nin, *)((ap(i+j*(j-1)/2),j=i,n), i=1, n)
      Else If (uplo=='L') Then
        Read (nin, *)((ap(i+(2*n-j)*(j-1)/2),j=1,i), i=1, n)
      End If

      Read (nin, *) job

!     Calculate all the eigenvalues and eigenvectors of A

      Call zhpevd(job, uplo, n, ap, w, z, ldz, work, lwork, rwork, lrwork, &
        iwork, liwork, info)

      Write (nout, *)
      If (info>0) Then
        Write (nout, *) 'Failure to converge.'
      Else

!       Print eigenvalues and eigenvectors

        Write (nout, *) 'Eigenvalues'
        Do i = 1, n
          Write (nout, 100) i, w(i)
        End Do
        Write (nout, *)
        Flush (nout)

!       Normalize the eigenvectors, largest element real
        Do i = 1, n
          rwork(1:n) = abs(z(1:n,i))
          k = maxloc(rwork(1:n), 1)
          scal = conjg(z(k,i))/abs(z(k,i))/dznrm2(n, z(1,i), 1)
          z(1:n, i) = z(1:n, i)*scal
        End Do

!       ifail: behaviour on error exit
!              =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
        ifail = 0
        Call nagf_file_print_matrix_complex_gen('General', ' ', n, n, z, ldz, &
          'Eigenvectors', ifail)

      End If

100   Format (3X, I5, 5X, 2F8.4)
    End Program
Full documentation of ZHPEVD


ZHPEVX example

Complex Hermitian Eigenproblems: Selected eigenvalues and, optionally, eigenvectors of a complex Hermitian matrix, packed storage

 To find the eigenvalues in the half-open interval $ (-2, 2]$, and thecorresponding eigenvectors, of the Hermitian matrix

Data

ZHPEVX Example Program Data

  4                                                :Value of N
 -2.0         2.0                                  :Values of VL and VU

 (1.0, 0.0)  (2.0, -1.0)  (3.0, -1.0)  (4.0, -1.0)
             (2.0,  0.0)  (3.0, -2.0)  (4.0, -2.0)
                          (3.0,  0.0)  (4.0, -3.0)
                                       (4.0,  0.0) :End of matrix A

Result

 ZHPEVX Example Program Results

 Number of eigenvalues found =    2

 Eigenvalues
    -0.6886  1.1412
 Selected eigenvectors
          1       2
 1   0.6470  0.0179
     0.0000 -0.4453

 2  -0.4984  0.5706
    -0.1130 -0.0000

 3   0.2949 -0.1530
     0.3165  0.5273

 4  -0.2241 -0.2118
    -0.2878 -0.3598

Source

    Program zhpevx_example

!     ZHPEVX Example Program Text

!     Copyright 2017, Numerical Algorithms Group Ltd. http://www.nag.com

!     .. Use Statements ..
      Use blas_interfaces, Only: dznrm2
      Use lapack_example_aux, Only: nagf_file_print_matrix_complex_gen
      Use lapack_interfaces, Only: zhpevx
      Use lapack_precision, Only: dp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Real (Kind=dp), Parameter :: zero = 0.0E+0_dp
      Integer, Parameter :: nin = 5, nout = 6
      Character (1), Parameter :: uplo = 'U'
!     .. Local Scalars ..
      Complex (Kind=dp) :: scal
      Real (Kind=dp) :: abstol, vl, vu
      Integer :: i, ifail, il, info, iu, j, k, ldz, m, n
!     .. Local Arrays ..
      Complex (Kind=dp), Allocatable :: ap(:), work(:), z(:, :)
      Real (Kind=dp), Allocatable :: rwork(:), w(:)
      Integer, Allocatable :: iwork(:), jfail(:)
!     .. Intrinsic Procedures ..
      Intrinsic :: abs, conjg, maxloc
!     .. Executable Statements ..
      Write (nout, *) 'ZHPEVX Example Program Results'
      Write (nout, *)
!     Skip heading in data file
      Read (nin, *)
      Read (nin, *) n
      ldz = n
      m = n
      Allocate (ap((n*(n+1))/2), work(2*n), z(ldz,m), rwork(7*n), w(n), iwork( &
        5*n), jfail(n))

!     Read the lower and upper bounds of the interval to be searched,
!     and read the upper or lower triangular part of the matrix A
!     from data file

      Read (nin, *) vl, vu
      If (uplo=='U') Then
        Read (nin, *)((ap(i+(j*(j-1))/2),j=i,n), i=1, n)
      Else If (uplo=='L') Then
        Read (nin, *)((ap(i+((2*n-j)*(j-1))/2),j=1,i), i=1, n)
      End If

!     Set the absolute error tolerance for eigenvalues.  With ABSTOL
!     set to zero, the default value is used instead

      abstol = zero

!     Solve the Hermitian eigenvalue problem

      Call zhpevx('Vectors', 'Values in range', uplo, n, ap, vl, vu, il, iu, &
        abstol, m, w, z, ldz, work, rwork, iwork, jfail, info)

      If (info>=0) Then

!       Print solution

        Write (nout, 100) 'Number of eigenvalues found =', m
        Write (nout, *)
        Write (nout, *) 'Eigenvalues'
        Write (nout, 110) w(1:m)
        Flush (nout)

!       Normalize the eigenvectors, largest element real
        Do i = 1, m
          rwork(1:n) = abs(z(1:n,i))
          k = maxloc(rwork(1:n), 1)
          scal = conjg(z(k,i))/abs(z(k,i))/dznrm2(n, z(1,i), 1)
          z(1:n, i) = z(1:n, i)*scal
        End Do

!       ifail: behaviour on error exit
!              =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
        ifail = 0
        Call nagf_file_print_matrix_complex_gen('General', ' ', n, m, z, ldz, &
          'Selected eigenvectors', ifail)

        If (info>0) Then
          Write (nout, 100) 'INFO eigenvectors failed to converge, INFO =', &
            info
          Write (nout, *) 'Indices of eigenvectors that did not converge'
          Write (nout, 120) jfail(1:m)
        End If
      Else
        Write (nout, 100) 'Failure in ZHPEVX. INFO =', info
      End If

100   Format (1X, A, I5)
110   Format (3X, (8F8.4))
120   Format (3X, (8I8))
    End Program
Full documentation of ZHPEVX


LAPACK:Real Nonsymmetric Eigenproblems

Next: Complex Nonsymmetric Eigenproblems Up: LAPACK Routines by Subject Previous: Complex Hermitian Eigenproblems

Real Nonsymmetric Eigenproblems

  • DGEES : For a real square nonsymmetric matrix, the eigenvalues, the real Schur form, and, optionally, the matrix of Schur vectors
  • DGEESX : For a real square nonsymmetric matrix, the eigenvalues, the real Schur form, and, optionally, the matrix of Schur vectors and/or reciprocal condition numbers for selected eigenvalues
  • DGEEV : All eigenvalues and, optionally, left and/or right eigenvectors of a real nonsymmetric matrix
  • DGEEVX : All eigenvalues and, optionally, left and/or right eigenvectors of a real nonsymmetric matrix; also, optionally, the balancing transformation, the reciprocal condition numbers for the eigenvalues and for the right eigenvectors


DGEES example

Real Nonsymmetric Eigenproblems: For a real square nonsymmetric matrix, the eigenvalues, the real Schur form, and, optionally, the matrix of Schur vectors

 To find the Schur factorization of the matrix

such that the real eigenvalues of $ A$ are the top left diagonal elements of theSchur form, $ T$.

Data

DGEES Example Program Data

  4                         :Value of N

  0.35   0.45  -0.14  -0.17
  0.09   0.07  -0.54   0.35
 -0.44  -0.33  -0.03   0.17
  0.25  -0.32  -0.13   0.11 :End of matrix A

Result

 DGEES Example Program Results

 Matrix A
          1       2       3       4
 1   0.3500  0.4500 -0.1400 -0.1700
 2   0.0900  0.0700 -0.5400  0.3500
 3  -0.4400 -0.3300 -0.0300  0.1700
 4   0.2500 -0.3200 -0.1300  0.1100

 Number of eigenvalues for which SELECT is true =    1
 (dimension of invariant subspace)

 Selected eigenvalues
  (  0.7995,  0.0000)

Source

!   DGEES Example Program Text
!   Copyright 2017, Numerical Algorithms Group Ltd. http://www.nag.com

    Module dgees_mod

!     DGEES Example Program Module:
!            Parameters and User-defined Routines

!     .. Use Statements ..
      Use lapack_precision, Only: dp
!     .. Implicit None Statement ..
      Implicit None
!     .. Accessibility Statements ..
      Private
      Public :: select
!     .. Parameters ..
      Integer, Parameter, Public :: nb = 64, nin = 5, nout = 6
    Contains
      Function select(wr, wi)

!       Logical function select for use with DGEES (DGEES)
!       Returns the value .TRUE. if the eigenvalue is real and positive

!       .. Function Return Value ..
        Logical :: select
!       .. Scalar Arguments ..
        Real (Kind=dp), Intent (In) :: wi, wr
!       .. Executable Statements ..
        select = (wr>0._dp .And. wi==0._dp)
        Return
      End Function
    End Module
    Program dgees_example

!     DGEES Example Main Program

!     .. Use Statements ..
      Use blas_interfaces, Only: dgemm
      Use dgees_mod, Only: nb, nin, nout, select
      Use lapack_example_aux, Only: nagf_file_print_matrix_real_gen
      Use lapack_interfaces, Only: dgees, dlange
      Use lapack_precision, Only: dp
!     .. Implicit None Statement ..
      Implicit None
!     .. Local Scalars ..
      Real (Kind=dp) :: alpha, beta, norm
      Integer :: i, ifail, info, lda, ldc, ldd, ldvs, lwork, n, sdim
!     .. Local Arrays ..
      Real (Kind=dp), Allocatable :: a(:, :), c(:, :), d(:, :), vs(:, :), &
        wi(:), work(:), wr(:)
      Real (Kind=dp) :: dummy(1), rwork(1)
      Logical, Allocatable :: bwork(:)
!     .. Intrinsic Procedures ..
      Intrinsic :: epsilon, max, nint
!     .. Executable Statements ..
      Write (nout, *) 'DGEES Example Program Results'
      Write (nout, *)
      Flush (nout)
!     Skip heading in data file
      Read (nin, *)
      Read (nin, *) n
      lda = n
      ldc = n
      ldd = n
      ldvs = n
      Allocate (a(lda,n), c(ldc,n), d(ldd,n), vs(ldvs,n), wi(n), wr(n), &
        bwork(n))

!     Use routine workspace query to get optimal workspace.
      lwork = -1
      Call dgees('Vectors (Schur)', 'Sort', select, n, a, lda, sdim, wr, wi, &
        vs, ldvs, dummy, lwork, bwork, info)

!     Make sure that there is enough workspace for block size nb.
      lwork = max((nb+2)*n, nint(dummy(1)))
      Allocate (work(lwork))

!     Read in the matrix A
      Read (nin, *)(a(i,1:n), i=1, n)

!     Copy A into D
      d(1:n, 1:n) = a(1:n, 1:n)

!     Print matrix A
!     ifail: behaviour on error exit
!            =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
      ifail = 0
      Call nagf_file_print_matrix_real_gen('General', ' ', n, n, a, lda, &
        'Matrix A', ifail)

      Write (nout, *)
      Flush (nout)

!     Find the Schur factorization of A
      Call dgees('Vectors (Schur)', 'Sort', select, n, a, lda, sdim, wr, wi, &
        vs, ldvs, work, lwork, bwork, info)

      If (info==0 .Or. info==(n+2)) Then

!       Compute A - Z*T*Z^T from the factorization of A and store in matrix D
        alpha = 1.0_dp
        beta = 0.0_dp
        Call dgemm('N', 'N', n, n, n, alpha, vs, ldvs, a, lda, beta, c, ldc)
        alpha = -1.0_dp
        beta = 1.0_dp
        Call dgemm('N', 'T', n, n, n, alpha, c, ldc, vs, ldvs, beta, d, ldd)

!       Find norm of matrix D and print warning if it is too large
        norm = dlange('O', ldd, n, d, ldd, rwork)
        If (norm>epsilon(1.0E0_dp)**0.8_dp) Then
          Write (nout, *) 'Norm of A-(Z*T*Z^T) is much greater than 0.'
          Write (nout, *) 'Schur factorization has failed.'
        Else

!         Print solution
          Write (nout, 100) &
            'Number of eigenvalues for which SELECT is true = ', sdim, &
            '(dimension of invariant subspace)'

          Write (nout, *)
!         Print eigenvalues.
          Write (nout, *) 'Selected eigenvalues'
          Write (nout, 120)(' (', wr(i), ',', wi(i), ')', i=1, sdim)
          Write (nout, *)

          If (info==(n+2)) Then
            Write (nout, 130) '***Note that rounding errors mean ', &
              'that leading eigenvalues in the Schur form', &
              'no longer satisfy SELECT = .TRUE.'
            Write (nout, *)
          End If

        End If

      Else
        Write (nout, 110) 'Failure in DGEES. INFO = ', info
      End If

100   Format (1X, A, I4, /, 1X, A)
110   Format (1X, A, I4)
120   Format (1X, A, F8.4, A, F8.4, A)
130   Format (1X, 2A, /, 1X, A)
    End Program
Full documentation of DGEES


DGEESX example

Real Nonsymmetric Eigenproblems: For a real square nonsymmetric matrix, the eigenvalues, the real Schur form, and, optionally, the matrix of Schur vectors and/or reciprocal condition numbers for selected eigenvalues

 To find the Schur factorization of the matrix

such that the real eigenvalues of $ A$ are the top left diagonal elements of theSchur form, $ T$. Estimates of the condition numbers for the selected eigenvaluecluster and corresponding invariant subspace are also returned.

Data

DGEESX Example Program Data

  4                         :Value of N

  0.35   0.45  -0.14  -0.17
  0.09   0.07  -0.54   0.35
 -0.44  -0.33  -0.03   0.17
  0.25  -0.32  -0.13   0.11 :End of matrix A

Result

 DGEESX Example Program Results

 Matrix A
          1       2       3       4
 1   0.3500  0.4500 -0.1400 -0.1700
 2   0.0900  0.0700 -0.5400  0.3500
 3  -0.4400 -0.3300 -0.0300  0.1700
 4   0.2500 -0.3200 -0.1300  0.1100

 Number of eigenvalues for which SELECT is true =    1
 (dimension of invariant subspace)

 Selected eigenvalues
  (  0.7995,  0.0000)

Source

!   DGEESX Example Program Text
!   Copyright 2017, Numerical Algorithms Group Ltd. http://www.nag.com

    Module dgeesx_mod

!     DGEESX Example Program Module:
!            Parameters and User-defined Routines

!     .. Use Statements ..
      Use lapack_precision, Only: dp
!     .. Implicit None Statement ..
      Implicit None
!     .. Accessibility Statements ..
      Private
      Public :: select
!     .. Parameters ..
      Integer, Parameter, Public :: nb = 64, nin = 5, nout = 6
      Logical, Parameter, Public :: check_fac = .True., print_cond = .False.
    Contains
      Function select(wr, wi)

!       Logical function select for use with DGEESX (DGEESX)
!       Returns the value .TRUE. if the eigenvalue is real and positive

!       .. Function Return Value ..
        Logical :: select
!       .. Scalar Arguments ..
        Real (Kind=dp), Intent (In) :: wi, wr
!       .. Executable Statements ..
        select = (wr>0._dp .And. wi==0._dp)
        Return
      End Function
    End Module
    Program dgeesx_example

!     DGEESX Example Main Program

!     .. Use Statements ..
      Use blas_interfaces, Only: dgemm
      Use dgeesx_mod, Only: check_fac, nb, nin, nout, print_cond, select
      Use lapack_example_aux, Only: nagf_file_print_matrix_real_gen
      Use lapack_interfaces, Only: dgeesx, dlange
      Use lapack_precision, Only: dp
!     .. Implicit None Statement ..
      Implicit None
!     .. Local Scalars ..
      Real (Kind=dp) :: alpha, anorm, beta, eps, norm, rconde, rcondv, tol
      Integer :: i, ifail, info, lda, ldc, ldd, ldvs, liwork, lwork, n, sdim
!     .. Local Arrays ..
      Real (Kind=dp), Allocatable :: a(:, :), c(:, :), d(:, :), vs(:, :), &
        wi(:), work(:), wr(:)
      Real (Kind=dp) :: dummy(1)
      Integer :: idum(1)
      Integer, Allocatable :: iwork(:)
      Logical, Allocatable :: bwork(:)
!     .. Intrinsic Procedures ..
      Intrinsic :: epsilon, max, nint
!     .. Executable Statements ..
      Write (nout, *) 'DGEESX Example Program Results'
      Write (nout, *)
      Flush (nout)
!     Skip heading in data file
      Read (nin, *)
      Read (nin, *) n
      lda = n
      ldc = n
      ldd = n
      ldvs = n
      Allocate (a(lda,n), c(ldc,n), d(ldd,n), vs(ldvs,n), wi(n), wr(n), &
        bwork(n))

!     Use routine workspace query to get optimal workspace.
      lwork = -1
      liwork = -1
      Call dgeesx('Vectors (Schur)', 'Sort', select, &
        'Both reciprocal condition numbers', n, a, lda, sdim, wr, wi, vs, &
        ldvs, rconde, rcondv, dummy, lwork, idum, liwork, bwork, info)

!     Make sure that there is enough workspace for block size nb.
      liwork = max((n*n)/4, idum(1))
      lwork = max(n*(nb+2+n/2), nint(dummy(1)))
      Allocate (work(lwork), iwork(liwork))

!     Read in the matrix A
      Read (nin, *)(a(i,1:n), i=1, n)

!     Copy A into D
      d(1:n, 1:n) = a(1:n, 1:n)

!     Print matrix A
!     ifail: behaviour on error exit
!            =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
      ifail = 0
      Call nagf_file_print_matrix_real_gen('General', ' ', n, n, a, lda, &
        'Matrix A', ifail)

      Write (nout, *)
      Flush (nout)

!     Find the Frobenius norm of A
      anorm = dlange('Frobenius', n, n, a, lda, work)

!     Find the Schur factorization of A
      Call dgeesx('Vectors (Schur)', 'Sort', select, &
        'Both reciprocal condition numbers', n, a, lda, sdim, wr, wi, vs, &
        ldvs, rconde, rcondv, work, lwork, iwork, liwork, bwork, info)

      If (info/=0 .And. info/=(n+2)) Then
        Write (nout, 170) 'Failure in DGEESX. INFO =', info
        Go To 100
      End If

      If (check_fac) Then
!       Compute A - Z*T*Z^T from the factorization of A and store in matrix D
        alpha = 1.0_dp
        beta = 0.0_dp
        Call dgemm('N', 'N', n, n, n, alpha, vs, ldvs, a, lda, beta, c, ldc)
        alpha = -1.0_dp
        beta = 1.0_dp
        Call dgemm('N', 'T', n, n, n, alpha, c, ldc, vs, ldvs, beta, d, ldd)

!       Find norm of matrix D and print warning if it is too large
        norm = dlange('O', ldd, n, d, ldd, work)
        If (norm>epsilon(1.0E0_dp)**0.8_dp) Then
          Write (nout, *) 'Norm of A-(Z*T*Z^T) is much greater than 0.'
          Write (nout, *) 'Schur factorization has failed.'
          Go To 100
        End If
      End If

!     Print solution
      Write (nout, 110) 'Number of eigenvalues for which SELECT is true = ', &
        sdim, '(dimension of invariant subspace)'

      Write (nout, *)
!     Print eigenvalues.
      Write (nout, *) 'Selected eigenvalues'
      Write (nout, 120)(' (', wr(i), ',', wi(i), ')', i=1, sdim)
      Write (nout, *)

      If (info==(n+2)) Then
        Write (nout, 130) '***Note that rounding errors mean ', &
          'that leading eigenvalues in the Schur form', &
          'no longer satisfy SELECT = .TRUE.'
        Write (nout, *)
      End If
      Flush (nout)

      If (print_cond) Then
!       Print out the reciprocal condition numbers
        Write (nout, 140) 'Reciprocal of projection norm onto the invariant', &
          'subspace for the selected eigenvalues', 'RCONDE = ', rconde
        Write (nout, *)
        Write (nout, 150) &
          'Reciprocal condition number for the invariant subspace', &
          'RCONDV = ', rcondv

!       Compute the machine precision
        eps = epsilon(1.0E0_dp)
        tol = eps*anorm

!       Print out the approximate asymptotic error bound on the
!       average absolute error of the selected eigenvalues given by
!       eps*norm(A)/RCONDE
        Write (nout, *)
        Write (nout, 160) 'Approximate asymptotic error bound for selected ', &
          'eigenvalues   = ', tol/rconde

!       Print out an approximate asymptotic bound on the maximum
!       angular error in the computed invariant subspace given by
!       eps*norm(A)/RCONDV
        Write (nout, 160) &
          'Approximate asymptotic error bound for the invariant ', &
          'subspace = ', tol/rcondv
      End If
100   Continue

110   Format (1X, A, I4, /, 1X, A)
120   Format (1X, A, F8.4, A, F8.4, A)
130   Format (1X, 2A, /, 1X, A)
140   Format (1X, A, /, 1X, A, /, 1X, A, 1P, E8.1)
150   Format (1X, A, /, 1X, A, 1P, E8.1)
160   Format (1X, 2A, 1P, E8.1)
170   Format (1X, A, I4)
    End Program
Full documentation of DGEESX


DGEEV example

Real Nonsymmetric Eigenproblems: All eigenvalues and, optionally, left and/or right eigenvectors of a real nonsymmetric matrix

 To find all the eigenvalues and right eigenvectors of the matrix

Data

DGEEV Example Program Data

  4                         :Value of N

  0.35   0.45  -0.14  -0.17
  0.09   0.07  -0.54   0.35
 -0.44  -0.33  -0.03   0.17
  0.25  -0.32  -0.13   0.11 :End of matrix A

Result

 DGEEV Example Program Results

 Eigenvalue( 1) =  7.9948E-01

 Eigenvector( 1)
 -6.5509E-01
 -5.2363E-01
  5.3622E-01
 -9.5607E-02

 Eigenvalue( 2) = (-9.9412E-02, 4.0079E-01)

 Eigenvector( 2)
 (-1.9330E-01, 2.5463E-01)
 ( 2.5186E-01,-5.2240E-01)
 ( 9.7182E-02,-3.0838E-01)
 ( 6.7595E-01, 0.0000E+00)

 Eigenvalue( 3) = (-9.9412E-02,-4.0079E-01)

 Eigenvector( 3)
 (-1.9330E-01,-2.5463E-01)
 ( 2.5186E-01, 5.2240E-01)
 ( 9.7182E-02, 3.0838E-01)
 ( 6.7595E-01,-0.0000E+00)

 Eigenvalue( 4) = -1.0066E-01

 Eigenvector( 4)
  1.2533E-01
  3.3202E-01
  5.9384E-01
  7.2209E-01

Source

    Program dgeev_example

!     DGEEV Example Program Text
!     Copyright 2017, Numerical Algorithms Group Ltd. http://www.nag.com

!     .. Use Statements ..
      Use lapack_interfaces, Only: dgeev
      Use lapack_precision, Only: dp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Real (Kind=dp), Parameter :: zero = 0.0_dp
      Integer, Parameter :: nb = 64, nin = 5, nout = 6
!     .. Local Scalars ..
      Complex (Kind=dp) :: eig
      Real (Kind=dp) :: alpha, beta, scale
      Integer :: i, info, j, k, lda, ldvr, lwork, n
!     .. Local Arrays ..
      Real (Kind=dp), Allocatable :: a(:, :), vr(:, :), wi(:), work(:), wr(:)
      Real (Kind=dp) :: dummy(1, 1)
!     .. Intrinsic Procedures ..
      Intrinsic :: cmplx, max, maxloc, nint, sqrt
!     .. Executable Statements ..
      Write (nout, *) 'DGEEV Example Program Results'
!     Skip heading in data file
      Read (nin, *)
      Read (nin, *) n
      lda = n
      ldvr = n
      Allocate (a(lda,n), vr(ldvr,n), wi(n), wr(n))

!     Use routine workspace query to get optimal workspace.
      lwork = -1
      Call dgeev('No left vectors', 'Vectors (right)', n, a, lda, wr, wi, &
        dummy, 1, vr, ldvr, dummy, lwork, info)

!     Make sure that there is enough workspace for block size nb.
      lwork = max((nb+2)*n, nint(dummy(1,1)))
      Allocate (work(lwork))

!     Read the matrix A from data file

      Read (nin, *)(a(i,1:n), i=1, n)

!     Compute the eigenvalues and right eigenvectors of A

      Call dgeev('No left vectors', 'Vectors (right)', n, a, lda, wr, wi, &
        dummy, 1, vr, ldvr, work, lwork, info)

      If (info==0) Then

!       Print solution

        Do j = 1, n
          Write (nout, *)
          If (wi(j)==zero) Then
            Write (nout, 100) 'Eigenvalue(', j, ') = ', wr(j)
          Else
            eig = cmplx(wr(j), wi(j), kind=dp)
            Write (nout, 110) 'Eigenvalue(', j, ') = ', eig
          End If
          Write (nout, *)
          Write (nout, 120) 'Eigenvector(', j, ')'
          If (wi(j)==zero) Then
!           Scale by making largest element positive
            k = maxloc(vr(1:n,j), 1)
            If (vr(k,j)<zero) Then
              vr(1:n, j) = -vr(1:n, j)
            End If
            Write (nout, 130) vr(1:n, j)
          Else If (wi(j)>0.0E0_dp) Then
!           Scale by making largest element real and positive
            work(1:n) = vr(1:n, j)**2 + vr(1:n, j+1)**2
            k = maxloc(work(1:n), 1)
            scale = sqrt(work(k))
            work(1:n) = vr(1:n, j)
            alpha = vr(k, j)/scale
            beta = vr(k, j+1)/scale
            vr(1:n, j) = alpha*work(1:n) + beta*vr(1:n, j+1)
            vr(1:n, j+1) = alpha*vr(1:n, j+1) - beta*work(1:n)
            Write (nout, 140)(vr(i,j), vr(i,j+1), i=1, n)
          Else
            Write (nout, 140)(vr(i,j-1), -vr(i,j), i=1, n)
          End If
        End Do
      Else
        Write (nout, *)
        Write (nout, 150) 'Failure in DGEEV.  INFO = ', info
      End If

100   Format (1X, A, I2, A, 1P, E11.4)
110   Format (1X, A, I2, A, '(', 1P, E11.4, ',', 1P, E11.4, ')')
120   Format (1X, A, I2, A)
130   Format (1X, 1P, E11.4)
140   Format (1X, '(', 1P, E11.4, ',', 1P, E11.4, ')')
150   Format (1X, A, I4)
    End Program
Full documentation of DGEEV


DGEEVX example

Real Nonsymmetric Eigenproblems: All eigenvalues and, optionally, left and/or right eigenvectors of a real nonsymmetric matrix; also, optionally, the balancing transformation, the reciprocal condition numbers for the eigenvalues and for the right eigenvectors

 To find all the eigenvalues and right eigenvectors of the matrix

together with estimates of the condition number and forward error bounds foreach eigenvalue and eigenvector. The option to balance the matrix is used.In order to compute the condition numbers of the eigenvalues, the lefteigenvectors also have to be computed, but they are not printed out in thisexample.

Data

DGEEVX Example Program Data
  4                         :Value of N
  0.35   0.45  -0.14  -0.17
  0.09   0.07  -0.54   0.35
 -0.44  -0.33  -0.03   0.17
  0.25  -0.32  -0.13   0.11 :End of matrix A

Result

 DGEEVX Example Program Results

 Eigenvalues

          Eigenvalue           rcond    error
  1   7.9948E-01               0.9936    -
  2 (-9.9412E-02, 4.0079E-01)  0.7027    -
  3 (-9.9412E-02,-4.0079E-01)  0.7027    -
  4  -1.0066E-01               0.5710    -

 Eigenvectors

          Eigenvector          rcond    error

  1   6.5509E-01               0.8181    -
      5.2363E-01
     -5.3622E-01
      9.5607E-02

  2 (-1.9330E-01, 2.5463E-01)  0.3996    -
    ( 2.5186E-01,-5.2240E-01)
    ( 9.7182E-02,-3.0838E-01)
    ( 6.7595E-01, 0.0000E+00)

  3 (-1.9330E-01,-2.5463E-01)  0.3996    -
    ( 2.5186E-01, 5.2240E-01)
    ( 9.7182E-02, 3.0838E-01)
    ( 6.7595E-01,-0.0000E+00)

  4   1.2533E-01               0.3125    -
      3.3202E-01
      5.9384E-01
      7.2209E-01

 Errors below 10*machine precision are not displayed

Source

    Program dgeevx_example

!     DGEEVX Example Program Text

!     Copyright 2017, Numerical Algorithms Group Ltd. http://www.nag.com

!     .. Use Statements ..
      Use lapack_interfaces, Only: dgeevx
      Use lapack_precision, Only: dp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter :: nb = 64, nin = 5, nout = 6
!     .. Local Scalars ..
      Complex (Kind=dp) :: eig
      Real (Kind=dp) :: abnrm, eps, tol
      Integer :: i, ihi, ilo, info, j, k, lda, ldvl, ldvr, lwork, n
      Logical :: pair
!     .. Local Arrays ..
      Real (Kind=dp), Allocatable :: a(:, :), rconde(:), rcondv(:), scale(:), &
        vl(:, :), vr(:, :), wi(:), work(:), wr(:)
      Real (Kind=dp) :: dummy(1)
      Integer, Allocatable :: iwork(:)
!     .. Intrinsic Procedures ..
      Intrinsic :: cmplx, epsilon, max, maxloc, nint
!     .. Executable Statements ..
      Write (nout, *) 'DGEEVX Example Program Results'
!     Skip heading in data file
      Read (nin, *)
      Read (nin, *) n
      lda = n
      ldvl = n
      ldvr = n
      lwork = (2+nb)*n
      Allocate (a(lda,n), rconde(n), rcondv(n), scale(n), vl(ldvl,n), &
        vr(ldvr,n), wi(n), wr(n), iwork(2*n-2))

!     Use routine workspace query to get optimal workspace.
      lwork = -1
      Call dgeevx('Balance', 'Vectors (left)', 'Vectors (right)', &
        'Both reciprocal condition numbers', n, a, lda, wr, wi, vl, ldvl, vr, &
        ldvr, ilo, ihi, scale, abnrm, rconde, rcondv, dummy, lwork, iwork, &
        info)

!     Make sure that there is enough workspace for block size nb.
      lwork = max((nb+2)*n, nint(dummy(1)))
      Allocate (work(lwork))

!     Read the matrix A from data file

      Read (nin, *)(a(i,1:n), i=1, n)

!     Solve the eigenvalue problem
      Call dgeevx('Balance', 'Vectors (left)', 'Vectors (right)', &
        'Both reciprocal condition numbers', n, a, lda, wr, wi, vl, ldvl, vr, &
        ldvr, ilo, ihi, scale, abnrm, rconde, rcondv, work, lwork, iwork, &
        info)

      If (info==0) Then

!       Compute the machine precision
        eps = epsilon(1.0E0_dp)
        tol = eps*abnrm
        pair = .False.

!       Print the eigenvalues and vectors, and associated condition
!       number and bounds

        Write (nout, *)
        Write (nout, *) 'Eigenvalues'
        Write (nout, *)
        Write (nout, *) '         Eigenvalue           rcond    error'

        Do j = 1, n

!         Print information on j-th eigenvalue

          If (wi(j)==0.0_dp) Then
            If (rconde(j)>0.0_dp) Then
              If (tol/rconde(j)<10.0_dp*eps) Then
                Write (nout, 100) j, wr(j), rconde(j), '-'
              Else
                Write (nout, 110) j, wr(j), rconde(j), tol/rconde(j)
              End If
            Else
              Write (nout, 110) j, wr(j), rconde(j), 'Inf'
            End If
          Else
            If (rconde(j)>0.0_dp) Then
              If (tol/rconde(j)<10.0_dp*eps) Then
                Write (nout, 120) j, wr(j), wi(j), rconde(j), '-'
              Else
                Write (nout, 130) j, wr(j), wi(j), rconde(j), tol/rconde(j)
              End If
            Else
              Write (nout, 120) j, wr(j), wi(j), rconde(j), 'Inf'
            End If
          End If
        End Do

        Write (nout, *)
        Write (nout, *) 'Eigenvectors'
        Write (nout, *)
        Write (nout, *) '         Eigenvector          rcond    error'

        Do j = 1, n

!         Print information on j-th eigenvector
          Write (nout, *)

          If (wi(j)==0.0E0_dp) Then
!           Make real eigenvectors have positive first entry
            If (vr(1,j)<0.0_dp) Then
              vr(1:n, j) = -vr(1:n, j)
            End If
            If (rcondv(j)>0.0_dp) Then
              If (tol/rcondv(j)<10.0_dp*eps) Then
                Write (nout, 100) j, vr(1, j), rcondv(j), '-'
              Else
                Write (nout, 110) j, vr(1, j), rcondv(j), tol/rcondv(j)
              End If
            Else
              Write (nout, 110) j, vr(1, j), rcondv(j), 'Inf'
            End If
            Write (nout, 140) vr(2:n, j)
          Else
            If (pair) Then
              eig = cmplx(vr(1,j-1), -vr(1,j), kind=dp)
            Else
!             Make largest eigenvector element have positive first entry
              work(1:n) = vr(1:n, j)**2 + vr(1:n, j+1)**2
              k = maxloc(work(1:n), 1)
              If (vr(k,j)<0.0_dp) Then
                vr(1:n, j) = -vr(1:n, j)
              End If
              eig = cmplx(vr(1,j), vr(1,j+1), kind=dp)
            End If
            If (rcondv(j)>0.0_dp) Then
              If (tol/rcondv(j)<10.0_dp*eps) Then
                Write (nout, 120) j, eig, rcondv(j), '-'
              Else
                Write (nout, 130) j, eig, rcondv(j), tol/rcondv(j)
              End If
            Else
              Write (nout, 120) j, eig, rcondv(j), 'Inf'
            End If
            If (pair) Then
              Write (nout, 150)(vr(i,j-1), -vr(i,j), i=2, n)
            Else
              Write (nout, 150)(vr(i,j), vr(i,j+1), i=2, n)
            End If
            pair = .Not. pair
          End If
        End Do
        Write (nout, *)
        Write (nout, *) 'Errors below 10*machine precision are not displayed'
      Else
        Write (nout, *)
        Write (nout, 160) 'Failure in DGEEVX.  INFO = ', info
      End If

100   Format (1X, I2, 2X, 1P, E11.4, 14X, 0P, F7.4, 4X, A)
110   Format (1X, I2, 2X, 1P, E11.4, 11X, 0P, F7.4, 1X, 1P, E8.1)
120   Format (1X, I2, 1X, '(', 1P, E11.4, ',', E11.4, ')', 1X, 0P, F7.4, 4X, &
        A)
130   Format (1X, I2, 1X, '(', 1P, E11.4, ',', E11.4, ')', 1X, 0P, F7.4, 1X, &
        1P, E8.1)
140   Format (1X, 4X, 1P, E11.4)
150   Format (1X, 3X, '(', 1P, E11.4, ',', E11.4, ')')
160   Format (1X, A, I4)
    End Program
Full documentation of DGEEVX


LAPACK:Complex Nonsymmetric Eigenproblems

Next: Real Generalized Symmetric Eigenproblems Up: LAPACK Routines by Subject Previous: Real Nonsymmetric Eigenproblems

Complex Nonsymmetric Eigenproblems

  • ZGEES : For a complex square nonsymmetric matrix, the eigenvalues, the Schur form, and, optionally, the matrix of Schur vectors
  • ZGEESX : For a real square nonsymmetric matrix, the eigenvalues, the Schur form, and, optionally, the matrix of Schur vectors, and, also optionally, reciprocal condition numbers for selected eigenvalues
  • ZGEEV : For a complex nonsymmetric matrix, all eigenvalues and, optionally, left and/or right eigenvectors
  • ZGEEVX : For a complex nonsymmetric matrix, all eigenvalues and, optionally, left and/or right eigenvectors, and, also optionally, the balancing transformation, reciprocal condition numbers for the eigenvalues and for the right eigenvectors


ZGEES example

Complex Nonsymmetric Eigenproblems: For a complex square nonsymmetric matrix, the eigenvalues, the Schur form, and, optionally, the matrix of Schur vectors

 To find the Schur factorization of the matrix

Data

ZGEES Example Program Data

  4                                                            :Value of N

(-3.97, -5.04)  (-4.11,  3.70)  (-0.34,  1.01)  ( 1.29, -0.86)
( 0.34, -1.50)  ( 1.52, -0.43)  ( 1.88, -5.38)  ( 3.36,  0.65)
( 3.31, -3.85)  ( 2.50,  3.45)  ( 0.88, -1.08)  ( 0.64, -1.48)
(-1.10,  0.82)  ( 1.81, -1.59)  ( 3.25,  1.33)  ( 1.57, -3.44) :End of matrix A

Result

 ZGEES Example Program Results

 Matrix A
                    1                 2                 3                 4
 1  (-3.9700,-5.0400) (-4.1100, 3.7000) (-0.3400, 1.0100) ( 1.2900,-0.8600)
 2  ( 0.3400,-1.5000) ( 1.5200,-0.4300) ( 1.8800,-5.3800) ( 3.3600, 0.6500)
 3  ( 3.3100,-3.8500) ( 2.5000, 3.4500) ( 0.8800,-1.0800) ( 0.6400,-1.4800)
 4  (-1.1000, 0.8200) ( 1.8100,-1.5900) ( 3.2500, 1.3300) ( 1.5700,-3.4400)

 Eigenvalues
    1   (-6.0004,-6.9998)
    2   (-5.0000, 2.0060)
    3   ( 7.9982,-0.9964)
    4   ( 3.0023,-3.9998)

Source

    Module zgees_mod

!     ZGEES Example Program Module:
!           Parameters and User-defined Routines

!     .. Implicit None Statement ..
      Implicit None
!     .. Accessibility Statements ..
      Private
      Public :: select
    Contains
      Function select(w)
!       .. Use Statements ..
        Use lapack_precision, Only: dp
!       .. Implicit None Statement ..
        Implicit None
!       .. Function Return Value ..
        Logical :: select
!       .. Scalar Arguments ..
        Complex (Kind=dp), Intent (In) :: w
!       .. Intrinsic Procedures ..
        Intrinsic :: real
!       .. Executable Statements ..
        Continue

!       Dummy function - it is not called by ZGEES when sorting is not required.
        select = (real(w)>0._dp)

        Return
      End Function
    End Module
    Program zgees_example

!     ZGEES Example Program Text

!     Copyright 2017, Numerical Algorithms Group Ltd. http://www.nag.com

!     .. Use Statements ..
      Use blas_interfaces, Only: zgemm
      Use lapack_example_aux, Only: nagf_file_print_matrix_complex_gen_comp
      Use lapack_interfaces, Only: zgees, zlange
      Use lapack_precision, Only: dp
      Use zgees_mod, Only: select
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter :: nb = 64, nin = 5, nout = 6
!     .. Local Scalars ..
      Complex (Kind=dp) :: alpha, beta
      Real (Kind=dp) :: norm
      Integer :: i, ifail, info, lda, ldc, ldd, ldvs, lwork, n, sdim
!     .. Local Arrays ..
      Complex (Kind=dp), Allocatable :: a(:, :), c(:, :), d(:, :), vs(:, :), &
        w(:), work(:)
      Complex (Kind=dp) :: wdum(1)
      Real (Kind=dp), Allocatable :: rwork(:)
      Logical :: dummy(1)
      Character (1) :: clabs(1), rlabs(1)
!     .. Intrinsic Procedures ..
      Intrinsic :: cmplx, epsilon, max, nint, real
!     .. Executable Statements ..
      Write (nout, *) 'ZGEES Example Program Results'
      Write (nout, *)
      Flush (nout)
!     Skip heading in data file
      Read (nin, *)
      Read (nin, *) n
      lda = n
      ldc = n
      ldd = n
      ldvs = n
      Allocate (a(lda,n), vs(ldvs,n), c(ldc,n), d(ldd,n), w(n), rwork(n))

!     Use routine workspace query to get optimal workspace.
      lwork = -1
      Call zgees('Vectors (Schur)', 'No sort', select, n, a, lda, sdim, w, vs, &
        ldvs, wdum, lwork, rwork, dummy, info)

!     Make sure that there is enough workspace for block size nb.
      lwork = max((nb+1)*n, nint(real(wdum(1))))
      Allocate (work(lwork))

!     Read in the matrix A
      Read (nin, *)(a(i,1:n), i=1, n)

!     Copy A into D
      d(1:n, 1:n) = a(1:n, 1:n)

!     Print matrix A
!     ifail: behaviour on error exit
!            =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
      ifail = 0
      Call nagf_file_print_matrix_complex_gen_comp('General', ' ', n, n, a, &
        lda, 'Bracketed', 'F7.4', 'Matrix A', 'Integer', rlabs, 'Integer', &
        clabs, 80, 0, ifail)

      Write (nout, *)
      Flush (nout)

!     Find the Schur factorization of A
      Call zgees('Vectors (Schur)', 'No sort', select, n, a, lda, sdim, w, vs, &
        ldvs, work, lwork, rwork, dummy, info)

      If (info>0) Then
        Write (nout, 100) 'Failure in ZGEES. INFO =', info
      Else

!       Compute A - Z*T*Z^H from the factorization of A and store in matrix D
        alpha = cmplx(1, kind=dp)
        beta = cmplx(0, kind=dp)
        Call zgemm('N', 'N', n, n, n, alpha, vs, ldvs, a, lda, beta, c, ldc)
        alpha = cmplx(-1, kind=dp)
        beta = cmplx(1, kind=dp)
        Call zgemm('N', 'C', n, n, n, alpha, c, ldc, vs, ldvs, beta, d, ldd)

!       Find norm of matrix D and print warning if it is too large
        norm = zlange('O', ldd, n, d, ldd, rwork)
        If (norm>epsilon(1.0E0_dp)**0.5_dp) Then
          Write (nout, *) 'Norm of A-(Z*T*Z^H) is much greater than 0.'
          Write (nout, *) 'Schur factorization has failed.'
        Else
!         Print eigenvalues.
          Write (nout, *) 'Eigenvalues'
          Write (nout, 110)(i, w(i), i=1, n)
        End If
      End If

100   Format (1X, A, I4)
110   Format (1X, I4, 2X, ' (', F7.4, ',', F7.4, ')', :)
    End Program
Full documentation of ZGEES


ZGEESX example

Complex Nonsymmetric Eigenproblems: For a real square nonsymmetric matrix, the eigenvalues, the Schur form, and, optionally, the matrix of Schur vectors, and, also optionally, reciprocal condition numbers for selected eigenvalues

 To find the Schur factorization of the matrix

such that the eigenvalues $ A$ with positive real part of are the top leftdiagonal elements of the Schur form, $ T$. Estimates of the condition numbersfor the selected eigenvalue cluster and corresponding invariant subspace arealso returned.

Data

ZGEESX Example Program Data

  4                                                            :Value of N

(-3.97, -5.04)  (-4.11,  3.70)  (-0.34,  1.01)  ( 1.29, -0.86)
( 0.34, -1.50)  ( 1.52, -0.43)  ( 1.88, -5.38)  ( 3.36,  0.65)
( 3.31, -3.85)  ( 2.50,  3.45)  ( 0.88, -1.08)  ( 0.64, -1.48)
(-1.10,  0.82)  ( 1.81, -1.59)  ( 3.25,  1.33)  ( 1.57, -3.44) :End of matrix A

Result

 ZGEESX Example Program Results

 Matrix A
                    1                 2                 3                 4
 1  (-3.9700,-5.0400) (-4.1100, 3.7000) (-0.3400, 1.0100) ( 1.2900,-0.8600)
 2  ( 0.3400,-1.5000) ( 1.5200,-0.4300) ( 1.8800,-5.3800) ( 3.3600, 0.6500)
 3  ( 3.3100,-3.8500) ( 2.5000, 3.4500) ( 0.8800,-1.0800) ( 0.6400,-1.4800)
 4  (-1.1000, 0.8200) ( 1.8100,-1.5900) ( 3.2500, 1.3300) ( 1.5700,-3.4400)

 Number of eigenvalues for which SELECT is true =    2
 (dimension of invariant subspace)

 Selected eigenvalues
    1   ( 7.9982,-0.9964)
    2   ( 3.0023,-3.9998)

Source

!   ZGEESX Example Program Text
!   Copyright 2017, Numerical Algorithms Group Ltd. http://www.nag.com

    Module zgeesx_mod

!     ZGEESX Example Program Module:
!            Parameters and User-defined Routines

!     .. Use Statements ..
      Use lapack_precision, Only: dp
!     .. Implicit None Statement ..
      Implicit None
!     .. Accessibility Statements ..
      Private
      Public :: select
!     .. Parameters ..
      Integer, Parameter, Public :: nb = 64, nin = 5, nout = 6
      Logical, Parameter, Public :: check_fac = .True., print_cond = .False.
    Contains
      Function select(w)

!       Logical function select for use with ZGEESX (ZGEESX)
!       Returns the value .TRUE. if the real part of the eigenvalue
!       w is positive.

!       .. Function Return Value ..
        Logical :: select
!       .. Scalar Arguments ..
        Complex (Kind=dp), Intent (In) :: w
!       .. Intrinsic Procedures ..
        Intrinsic :: real
!       .. Executable Statements ..
        select = (real(w)>0._dp)
        Return
      End Function
    End Module
    Program zgeesx_example

!     ZGEESX Example Main Program

!     .. Use Statements ..
      Use blas_interfaces, Only: zgemm
      Use zgeesx_mod, Only: check_fac, nb, nin, nout, print_cond, select
      Use lapack_example_aux, Only: nagf_file_print_matrix_complex_gen_comp
      Use lapack_interfaces, Only: zgeesx, zlange
      Use lapack_precision, Only: dp
!     .. Implicit None Statement ..
      Implicit None
!     .. Local Scalars ..
      Complex (Kind=dp) :: alpha, beta
      Real (Kind=dp) :: anorm, eps, norm, rconde, rcondv, tol
      Integer :: i, ifail, info, lda, ldc, ldd, ldvs, lwork, n, sdim
!     .. Local Arrays ..
      Complex (Kind=dp), Allocatable :: a(:, :), c(:, :), d(:, :), vs(:, :), &
        w(:), work(:)
      Complex (Kind=dp) :: dummy(1)
      Real (Kind=dp), Allocatable :: rwork(:)
      Logical, Allocatable :: bwork(:)
      Character (1) :: clabs(1), rlabs(1)
!     .. Intrinsic Procedures ..
      Intrinsic :: cmplx, epsilon, max, nint, real
!     .. Executable Statements ..
      Write (nout, *) 'ZGEESX Example Program Results'
      Write (nout, *)
      Flush (nout)
!     Skip heading in data file
      Read (nin, *)
      Read (nin, *) n
      lda = n
      ldc = n
      ldd = n
      ldvs = n
      Allocate (a(lda,n), c(ldc,n), d(ldd,n), vs(ldvs,n), w(n), rwork(n), &
        bwork(n))

!     Use routine workspace query to get optimal workspace.
      lwork = -1
      Call zgeesx('Vectors (Schur)', 'Sort', select, &
        'Both reciprocal condition numbers', n, a, lda, sdim, w, vs, ldvs, &
        rconde, rcondv, dummy, lwork, rwork, bwork, info)

!     Make sure that there is enough workspace for block size nb.
      lwork = max(n*(nb+1+n/2), nint(real(dummy(1))))
      Allocate (work(lwork))

!     Read in the matrix A
      Read (nin, *)(a(i,1:n), i=1, n)

!     Copy A into D
      d(1:n, 1:n) = a(1:n, 1:n)

!     Print matrix A
!     ifail: behaviour on error exit
!            =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
      ifail = 0
      Call nagf_file_print_matrix_complex_gen_comp('General', ' ', n, n, a, &
        lda, 'Bracketed', 'F7.4', 'Matrix A', 'Integer', rlabs, 'Integer', &
        clabs, 80, 0, ifail)

      Write (nout, *)
      Flush (nout)

!     Find the Frobenius norm of A
      anorm = zlange('Frobenius', n, n, a, lda, rwork)

!     Find the Schur factorization of A
      Call zgeesx('Vectors (Schur)', 'Sort', select, &
        'Both reciprocal condition numbers', n, a, lda, sdim, w, vs, ldvs, &
        rconde, rcondv, work, lwork, rwork, bwork, info)

      If (info/=0 .And. info/=(n+2)) Then
        Write (nout, 170) 'Failure in ZGEESX. INFO =', info
        Go To 100
      End If

      If (check_fac) Then
!       Compute A - Z*T*Z^H from the factorization of A and store in matrix D
        alpha = cmplx(1, kind=dp)
        beta = cmplx(0, kind=dp)
        Call zgemm('N', 'N', n, n, n, alpha, vs, ldvs, a, lda, beta, c, ldc)
        alpha = cmplx(-1, kind=dp)
        beta = cmplx(1, kind=dp)
        Call zgemm('N', 'C', n, n, n, alpha, c, ldc, vs, ldvs, beta, d, ldd)

!       Find norm of matrix D and print warning if it is too large
        norm = zlange('O', ldd, n, d, ldd, rwork)
        If (norm>epsilon(1.0E0_dp)**0.5_dp) Then
          Write (nout, *) 'Norm of A-(Z*T*Z^H) is much greater than 0.'
          Write (nout, *) 'Schur factorization has failed.'
          Go To 100
        End If
      End If

!     Print solution
      Write (nout, 110) 'Number of eigenvalues for which SELECT is true = ', &
        sdim, '(dimension of invariant subspace)'

      Write (nout, *)
!     Print eigenvalues.
      Write (nout, *) 'Selected eigenvalues'
      Write (nout, 120)(i, w(i), i=1, sdim)
      Write (nout, *)

      If (info==(n+2)) Then
        Write (nout, 130) '***Note that rounding errors mean ', &
          'that leading eigenvalues in the Schur form', &
          'no longer satisfy SELECT = .TRUE.'
        Write (nout, *)
      End If
      Flush (nout)

      If (print_cond) Then
!       Print out the reciprocal condition numbers
        Write (nout, 140) 'Reciprocal of projection norm onto the invariant', &
          'subspace for the selected eigenvalues', 'RCONDE = ', rconde
        Write (nout, *)
        Write (nout, 150) &
          'Reciprocal condition number for the invariant subspace', &
          'RCONDV = ', rcondv

!       Compute the machine precision
        eps = epsilon(1.0E0_dp)
        tol = eps*anorm

!       Print out the approximate asymptotic error bound on the
!       average absolute error of the selected eigenvalues given by
!       eps*norm(A)/RCONDE
        Write (nout, *)
        Write (nout, 160) 'Approximate asymptotic error bound for selected ', &
          'eigenvalues   = ', tol/rconde

!       Print out an approximate asymptotic bound on the maximum
!       angular error in the computed invariant subspace given by
!       eps*norm(A)/RCONDV
        Write (nout, 160) &
          'Approximate asymptotic error bound for the invariant ', &
          'subspace = ', tol/rcondv
      End If
100   Continue

110   Format (1X, A, I4, /, 1X, A)
120   Format (1X, I4, 2X, ' (', F7.4, ',', F7.4, ')', :)
130   Format (1X, 2A, /, 1X, A)
140   Format (1X, A, /, 1X, A, /, 1X, A, 1P, E8.1)
150   Format (1X, A, /, 1X, A, 1P, E8.1)
160   Format (1X, 2A, 1P, E8.1)
170   Format (1X, A, I4)
    End Program
Full documentation of ZGEESX


ZGEEV example

Complex Nonsymmetric Eigenproblems: For a complex nonsymmetric matrix, all eigenvalues and, optionally, left and/or right eigenvectors

 To find all the eigenvalues and right eigenvectors of the matrix

Data

ZGEEV Example Program Data

  4                                                            :Value of N

(-3.97, -5.04)  (-4.11,  3.70)  (-0.34,  1.01)  ( 1.29, -0.86)
( 0.34, -1.50)  ( 1.52, -0.43)  ( 1.88, -5.38)  ( 3.36,  0.65)
( 3.31, -3.85)  ( 2.50,  3.45)  ( 0.88, -1.08)  ( 0.64, -1.48)
(-1.10,  0.82)  ( 1.81, -1.59)  ( 3.25,  1.33)  ( 1.57, -3.44) :End of matrix A

Result

 ZGEEV Example Program Results

 Eigenvalues
    (-6.0004,-6.9998) (-5.0000, 2.0060) ( 7.9982,-0.9964) ( 3.0023,-3.9998)

 Eigenvectors
          1       2       3       4
 1   0.8457 -0.3865 -0.1730 -0.0356
     0.0000  0.1732  0.2669 -0.1782

 2  -0.0177 -0.3539  0.6924  0.1264
     0.3036  0.4529  0.0000  0.2666

 3   0.0875  0.6124  0.3324  0.0129
     0.3115  0.0000  0.4960 -0.2966

 4  -0.0561 -0.0859  0.2504  0.8898
    -0.2906 -0.3284 -0.0147  0.0000

Source

    Program zgeev_example

!     ZGEEV Example Program Text

!     Copyright 2017, Numerical Algorithms Group Ltd. http://www.nag.com

!     .. Use Statements ..
      Use lapack_example_aux, Only: nagf_file_print_matrix_complex_gen
      Use lapack_interfaces, Only: zgeev
      Use lapack_precision, Only: dp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter :: nb = 64, nin = 5, nout = 6
!     .. Local Scalars ..
      Integer :: i, ifail, info, lda, ldvr, lwork, n
!     .. Local Arrays ..
      Complex (Kind=dp), Allocatable :: a(:, :), vr(:, :), w(:), work(:)
      Complex (Kind=dp) :: dummy(1, 1)
      Real (Kind=dp), Allocatable :: rwork(:)
!     .. Intrinsic Procedures ..
      Intrinsic :: max, nint, real
!     .. Executable Statements ..
      Write (nout, *) 'ZGEEV Example Program Results'
      Write (nout, *)
!     Skip heading in data file
      Read (nin, *)
      Read (nin, *) n
      lda = n
      ldvr = n
      Allocate (a(lda,n), vr(ldvr,n), w(n), rwork(2*n))

!     Use routine workspace query to get optimal workspace.
      lwork = -1
      Call zgeev('No left vectors', 'Vectors (right)', n, a, lda, w, dummy, 1, &
        vr, ldvr, dummy, lwork, rwork, info)

!     Make sure that there is enough workspace for block size nb.
      lwork = max((nb+1)*n, nint(real(dummy(1,1))))
      Allocate (work(lwork))

!     Read the matrix A from data file

      Read (nin, *)(a(i,1:n), i=1, n)

!     Compute the eigenvalues and right eigenvectors of A

      Call zgeev('No left vectors', 'Vectors (right)', n, a, lda, w, dummy, 1, &
        vr, ldvr, work, lwork, rwork, info)

      If (info==0) Then

!       Print solution

        Write (nout, *) 'Eigenvalues'
        Write (nout, 100) w(1:n)

        Write (nout, *)
        Flush (nout)

!       ifail: behaviour on error exit
!              =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
        ifail = 0
        Call nagf_file_print_matrix_complex_gen('General', ' ', n, n, vr, &
          ldvr, 'Eigenvectors', ifail)

      Else
        Write (nout, *)
        Write (nout, 110) 'Failure in ZGEEV.  INFO = ', info
      End If

100   Format ((3X,4(' (',F7.4,',',F7.4,')',:)))
110   Format (1X, A, I4)
    End Program
Full documentation of ZGEEV


ZGEEVX example

Complex Nonsymmetric Eigenproblems: For a complex nonsymmetric matrix, all eigenvalues and, optionally, left and/or right eigenvectors, and, also optionally, the balancing transformation, reciprocal condition numbers for the eigenvalues and for the right eigenvectors

To find all the eigenvalues and right eigenvectors of the matrix

together with estimates of the condition number and forward error bounds foreach eigenvalue and eigenvector. The option to balance the matrix is used.In order to compute the condition numbers of the eigenvalues, the lefteigenvectors also have to be computed, but they are not printed out in thisexample.

Data

ZGEEVX Example Program Data
  4                                                            :Value of N
(-3.97, -5.04)  (-4.11,  3.70)  (-0.34,  1.01)  ( 1.29, -0.86)
( 0.34, -1.50)  ( 1.52, -0.43)  ( 1.88, -5.38)  ( 3.36,  0.65)
( 3.31, -3.85)  ( 2.50,  3.45)  ( 0.88, -1.08)  ( 0.64, -1.48)
(-1.10,  0.82)  ( 1.81, -1.59)  ( 3.25,  1.33)  ( 1.57, -3.44) :End of matrix A

Result

 ZGEEVX Example Program Results

 Eigenvalues

          Eigenvalue           rcond    error
  1 (-6.0004E+00,-6.9998E+00)  0.9932  3.2E-15
  2 (-5.0000E+00, 2.0060E+00)  0.9964  3.2E-15
  3 ( 7.9982E+00,-9.9637E-01)  0.9814  3.3E-15
  4 ( 3.0023E+00,-3.9998E+00)  0.9779  3.3E-15

 Eigenvectors

          Eigenvector          rcond    error

  1 ( 8.4572E-01, 0.0000E+00)  8.4011    -
    (-1.7723E-02, 3.0361E-01)
    ( 8.7521E-02, 3.1145E-01)
    (-5.6147E-02,-2.9060E-01)

  2 ( 3.8655E-01,-1.7323E-01)  8.0214    -
    ( 3.5393E-01,-4.5288E-01)
    (-6.1237E-01,-0.0000E+00)
    ( 8.5928E-02, 3.2836E-01)

  3 ( 1.7297E-01,-2.6690E-01)  5.8292    -
    (-6.9242E-01,-0.0000E+00)
    (-3.3240E-01,-4.9598E-01)
    (-2.5039E-01, 1.4655E-02)

  4 ( 3.5614E-02, 1.7822E-01)  5.8292    -
    (-1.2637E-01,-2.6663E-01)
    (-1.2933E-02, 2.9657E-01)
    (-8.8982E-01,-0.0000E+00)

 Errors below 10*machine precision are not displayed

Source

    Program zgeevx_example

!     ZGEEVX Example Program Text

!     Copyright 2017, Numerical Algorithms Group Ltd. http://www.nag.com

!     .. Use Statements ..
      Use lapack_interfaces, Only: zgeevx
      Use lapack_precision, Only: dp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter :: nb = 64, nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=dp) :: abnrm, eps, tol
      Integer :: i, ihi, ilo, info, j, lda, ldvl, ldvr, lwork, n
!     .. Local Arrays ..
      Complex (Kind=dp), Allocatable :: a(:, :), vl(:, :), vr(:, :), w(:), &
        work(:)
      Complex (Kind=dp) :: dummy(1)
      Real (Kind=dp), Allocatable :: rconde(:), rcondv(:), rwork(:), scale(:)
!     .. Intrinsic Procedures ..
      Intrinsic :: epsilon, max, nint, real
!     .. Executable Statements ..
      Write (nout, *) 'ZGEEVX Example Program Results'
!     Skip heading in data file
      Read (nin, *)
      Read (nin, *) n
      lda = n
      ldvl = n
      ldvr = n
      Allocate (a(lda,n), vl(ldvl,n), vr(ldvr,n), w(n), rconde(n), rcondv(n), &
        rwork(2*n), scale(n))

!     Use routine workspace query to get optimal workspace.
      lwork = -1
      Call zgeevx('Balance', 'Vectors (left)', 'Vectors (right)', &
        'Both reciprocal condition numbers', n, a, lda, w, vl, ldvl, vr, ldvr, &
        ilo, ihi, scale, abnrm, rconde, rcondv, dummy, lwork, rwork, info)

!     Make sure that there is enough workspace for block size nb.
      lwork = max((nb+1)*n, nint(real(dummy(1))))
      Allocate (work(lwork))

!     Read the matrix A from data file

      Read (nin, *)(a(i,1:n), i=1, n)

!     Solve the eigenvalue problem

      Call zgeevx('Balance', 'Vectors (left)', 'Vectors (right)', &
        'Both reciprocal condition numbers', n, a, lda, w, vl, ldvl, vr, ldvr, &
        ilo, ihi, scale, abnrm, rconde, rcondv, work, lwork, rwork, info)

      If (info==0) Then

!       Compute the machine precision

        eps = epsilon(1.0E0_dp)
        tol = eps*abnrm

!       Print the eigenvalues and vectors, and associated condition
!       number and bounds

        Write (nout, *)
        Write (nout, *) 'Eigenvalues'
        Write (nout, *)
        Write (nout, *) '         Eigenvalue           rcond    error'

        Do j = 1, n

!         Print information on j-th eigenvalue

          If (rconde(j)>0.0_dp) Then
            If (tol/rconde(j)<10.0_dp*eps) Then
              Write (nout, 100) j, w(j), rconde(j), '-'
            Else
              Write (nout, 110) j, w(j), rconde(j), tol/rconde(j)
            End If
          Else
            Write (nout, 100) j, w(j), rconde(j), 'Inf'
          End If

        End Do

        Write (nout, *)
        Write (nout, *) 'Eigenvectors'
        Write (nout, *)
        Write (nout, *) '         Eigenvector          rcond    error'

        Do j = 1, n

!         Print information on j-th eigenvector

          Write (nout, *)

!         Make first real part component be positive
          If (real(vr(1,j))<0.0_dp) Then
            vr(1:n, j) = -vr(1:n, j)
          End If
          If (rcondv(j)>0.0_dp) Then
            If (tol/rcondv(j)<10.0_dp*eps) Then
              Write (nout, 100) j, vr(1, j), rcondv(j), '-'
            Else
              Write (nout, 110) j, vr(1, j), rcondv(j), tol/rcondv(j)
            End If
          Else
            Write (nout, 100) j, vr(1, j), rcondv(j), 'Inf'
          End If

          Write (nout, 120) vr(2:n, j)

        End Do
        Write (nout, *)
        Write (nout, *) 'Errors below 10*machine precision are not displayed'
      Else
        Write (nout, *)
        Write (nout, 130) 'Failure in ZGEEVX. INFO =', info
      End If

100   Format (1X, I2, 1X, '(', 1P, E11.4, ',', E11.4, ')', 1X, 0P, F7.4, 4X, &
        A)
110   Format (1X, I2, 1X, '(', 1P, E11.4, ',', E11.4, ')', 1X, 0P, F7.4, 1X, &
        1P, E8.1)
120   Format (1X, 3X, '(', 1P, E11.4, ',', E11.4, ')')
130   Format (1X, A, I4)

    End Program
Full documentation of ZGEEVX


LAPACK:Real Generalized Symmetric Eigenproblems

Next: Complex Generalized Hermitian Eigenproblems Up: LAPACK Routines by Subject Previous: Complex Nonsymmetric Eigenproblems

Real Generalized Symmetric Eigenproblems

  • DSBGV : All the eigenvalues, and, optionally, the eigenvectors of a real banded generalized symmetric-definite eigenproblem
  • DSBGVD : All the eigenvalues, and, optionally, the eigenvectors of a real banded generalized symmetric-definite eigenproblem (divide-and-conquer)
  • DSBGVX : Selected eigenvalues, and, optionally, the eigenvectors of a real banded generalized symmetric-definite eigenproblem
  • DSPGV : All the eigenvalues, and, optionally, the eigenvectors of a real generalized symmetric-definite eigenproblem, packed storage
  • DSPGVD : All the eigenvalues, and, optionally, the eigenvectors of a real generalized symmetric-definite eigenproblem, packed storage (divide-and-conquer)
  • DSPGVX : Selected eigenvalues, and, optionally, the eigenvectors of a real generalized symmetric-definite eigenproblem, packed storage
  • DSYGV : All the eigenvalues, and, optionally, the eigenvectors of a real generalized symmetric-definite eigenproblem
  • DSYGVD : All the eigenvalues, and, optionally, the eigenvectors of a real generalized symmetric-definite eigenproblem (divide-and-conquer)
  • DSYGVX : Selected eigenvalues, and, optionally, the eigenvectors of a real generalized symmetric-definite eigenproblem


DSBGV example

Real Generalized Symmetric Eigenproblems: All the eigenvalues, and, optionally, the eigenvectors of a real banded generalized symmetric-definite eigenproblem

 To find all the eigenvalues of the generalized band symmetric eigenproblem [image], where

Data

DSBGV Example Program Data

  4      2      1            :Values of N, KA and KB

  0.24   0.39   0.42
        -0.11   0.79   0.63
               -0.25   0.48
                      -0.03  :End of matrix A
  2.07   0.95
         1.69  -0.29
                0.65  -0.33
                       1.17  :End of matrix B

Result

 DSBGV Example Program Results

 Eigenvalues
       -0.8305    -0.6401     0.0992     1.8525

Source

    Program dsbgv_example

!     DSBGV Example Program Text

!     Copyright 2017, Numerical Algorithms Group Ltd. http://www.nag.com

!     .. Use Statements ..
      Use lapack_interfaces, Only: dsbgv
      Use lapack_precision, Only: dp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter :: nin = 5, nout = 6
      Character (1), Parameter :: uplo = 'U'
!     .. Local Scalars ..
      Integer :: i, info, j, ka, kb, ldab, ldbb, n
!     .. Local Arrays ..
      Real (Kind=dp), Allocatable :: ab(:, :), bb(:, :), w(:), work(:)
      Real (Kind=dp) :: dummy(1, 1)
!     .. Intrinsic Procedures ..
      Intrinsic :: max, min
!     .. Executable Statements ..
      Write (nout, *) 'DSBGV Example Program Results'
      Write (nout, *)
!     Skip heading in data file
      Read (nin, *)
      Read (nin, *) n, ka, kb
      ldab = ka + 1
      ldbb = kb + 1
      Allocate (ab(ldab,n), bb(ldbb,n), w(n), work(3*n))

!     Read the upper or lower triangular parts of the matrices A and
!     B from data file

      If (uplo=='U') Then
        Read (nin, *)((ab(ka+1+i-j,j),j=i,min(n,i+ka)), i=1, n)
        Read (nin, *)((bb(kb+1+i-j,j),j=i,min(n,i+kb)), i=1, n)
      Else If (uplo=='L') Then
        Read (nin, *)((ab(1+i-j,j),j=max(1,i-ka),i), i=1, n)
        Read (nin, *)((bb(1+i-j,j),j=max(1,i-kb),i), i=1, n)
      End If

!     Solve the generalized symmetric band eigenvalue problem
!     A*x = lambda*B*x

      Call dsbgv('No vectors', uplo, n, ka, kb, ab, ldab, bb, ldbb, w, dummy, &
        1, work, info)

      If (info==0) Then

!       Print solution

        Write (nout, *) 'Eigenvalues'
        Write (nout, 100) w(1:n)
      Else If (info>n .And. info<=2*n) Then
        i = info - n
        Write (nout, 110) 'The leading minor of order ', i, &
          ' of B is not positive definite'
      Else
        Write (nout, 120) 'Failure in DSBGV. INFO =', info
      End If

100   Format (3X, (6F11.4))
110   Format (1X, A, I4, A)
120   Format (1X, A, I4)
    End Program
Full documentation of DSBGV


DSBGVD example

Real Generalized Symmetric Eigenproblems: All the eigenvalues, and, optionally, the eigenvectors of a real banded generalized symmetric-definite eigenproblem (divide-and-conquer)

 To find all the eigenvalues of the generalized band symmetric eigenproblem [image], where

Data

DSBGVD Example Program Data

  4      2      1            :Values of N, KA and KB

  0.24   0.39   0.42
        -0.11   0.79   0.63
               -0.25   0.48
                      -0.03  :End of matrix A
  2.07   0.95
         1.69  -0.29
                0.65  -0.33
                       1.17  :End of matrix B

Result

 DSBGVD Example Program Results

 Eigenvalues
       -0.8305    -0.6401     0.0992     1.8525

Source

    Program dsbgvd_example

!     DSBGVD Example Program Text

!     Copyright 2017, Numerical Algorithms Group Ltd. http://www.nag.com

!     .. Use Statements ..
      Use lapack_interfaces, Only: dsbgvd
      Use lapack_precision, Only: dp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter :: nin = 5, nout = 6
      Character (1), Parameter :: uplo = 'U'
!     .. Local Scalars ..
      Integer :: i, info, j, ka, kb, ldab, ldbb, liwork, lwork, n
!     .. Local Arrays ..
      Real (Kind=dp), Allocatable :: ab(:, :), bb(:, :), w(:), work(:)
      Real (Kind=dp) :: dummy(1, 1)
      Integer, Allocatable :: iwork(:)
!     .. Intrinsic Procedures ..
      Intrinsic :: max, min
!     .. Executable Statements ..
      Write (nout, *) 'DSBGVD Example Program Results'
      Write (nout, *)
!     Skip heading in data file
      Read (nin, *)
      Read (nin, *) n, ka, kb
      ldab = ka + 1
      ldbb = kb + 1
      liwork = 1
      lwork = 3*n
      Allocate (ab(ldab,n), bb(ldbb,n), w(n), work(lwork), iwork(liwork))

!     Read the upper or lower triangular parts of the matrices A and
!     B from data file

      If (uplo=='U') Then
        Read (nin, *)((ab(ka+1+i-j,j),j=i,min(n,i+ka)), i=1, n)
        Read (nin, *)((bb(kb+1+i-j,j),j=i,min(n,i+kb)), i=1, n)
      Else If (uplo=='L') Then
        Read (nin, *)((ab(1+i-j,j),j=max(1,i-ka),i), i=1, n)
        Read (nin, *)((bb(1+i-j,j),j=max(1,i-kb),i), i=1, n)
      End If

!     Solve the generalized symmetric band eigenvalue problem
!     A*x = lambda*B*x

      Call dsbgvd('No vectors', uplo, n, ka, kb, ab, ldab, bb, ldbb, w, dummy, &
        1, work, lwork, iwork, liwork, info)

      If (info==0) Then

!       Print solution

        Write (nout, *) 'Eigenvalues'
        Write (nout, 100) w(1:n)
      Else If (info>n .And. info<=2*n) Then
        i = info - n
        Write (nout, 110) 'The leading minor of order ', i, &
          ' of B is not positive definite'
      Else
        Write (nout, 120) 'Failure in DSBGVD. INFO =', info
      End If

100   Format (3X, (6F11.4))
110   Format (1X, A, I4, A)
120   Format (1X, A, I4)
    End Program
Full documentation of DSBGVD


DSBGVX example

Real Generalized Symmetric Eigenproblems: Selected eigenvalues, and, optionally, the eigenvectors of a real banded generalized symmetric-definite eigenproblem

 To find the eigenvalues in the half-open interval $ (0.0, 1.0]$, andcorresponding eigenvectors, of the generalized band symmetric eigenproblem [image], where

Data

DSBGVX Example Program Data

  4      2      1            :Values of N, KA and KB

  0.0    1.0                 :Values of VL and VU

  0.24   0.39   0.42
        -0.11   0.79   0.63
               -0.25   0.48
                      -0.03  :End of matrix A
  2.07   0.95
         1.69  -0.29
                0.65  -0.33
                       1.17  :End of matrix B

Result

 DSBGVX Example Program Results

 Number of eigenvalues found =    1

 Eigenvalues
     0.0992
 Selected eigenvectors
          1
 1   0.6729
 2  -0.1009
 3   0.0155
 4  -0.3806

Source

    Program dsbgvx_example

!     DSBGVX Example Program Text

!     Copyright 2017, Numerical Algorithms Group Ltd. http://www.nag.com

!     .. Use Statements ..
      Use lapack_example_aux, Only: nagf_file_print_matrix_real_gen
      Use lapack_interfaces, Only: dsbgvx
      Use lapack_precision, Only: dp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Real (Kind=dp), Parameter :: zero = 0.0E+0_dp
      Integer, Parameter :: nin = 5, nout = 6
      Character (1), Parameter :: uplo = 'U'
!     .. Local Scalars ..
      Real (Kind=dp) :: abstol, vl, vu
      Integer :: i, ifail, il, info, iu, j, ka, kb, ldab, ldbb, ldq, ldz, m, n
!     .. Local Arrays ..
      Real (Kind=dp), Allocatable :: ab(:, :), bb(:, :), q(:, :), w(:), &
        work(:), z(:, :)
      Integer, Allocatable :: iwork(:), jfail(:)
!     .. Intrinsic Procedures ..
      Intrinsic :: max, min
!     .. Executable Statements ..
      Write (nout, *) 'DSBGVX Example Program Results'
      Write (nout, *)
!     Skip heading in data file
      Read (nin, *)
      Read (nin, *) n, ka, kb
      ldab = ka + 1
      ldbb = kb + 1
      ldq = n
      ldz = n
      m = n
      Allocate (ab(ldab,n), bb(ldbb,n), q(ldq,n), w(n), work(7*n), z(ldz,m), &
        iwork(5*n), jfail(n))

!     Read the lower and upper bounds of the interval to be searched,
!     and read the upper or lower triangular parts of the matrices A
!     and B from data file

      Read (nin, *) vl, vu
      If (uplo=='U') Then
        Read (nin, *)((ab(ka+1+i-j,j),j=i,min(n,i+ka)), i=1, n)
        Read (nin, *)((bb(kb+1+i-j,j),j=i,min(n,i+kb)), i=1, n)
      Else If (uplo=='L') Then
        Read (nin, *)((ab(1+i-j,j),j=max(1,i-ka),i), i=1, n)
        Read (nin, *)((bb(1+i-j,j),j=max(1,i-kb),i), i=1, n)
      End If

!     Set the absolute error tolerance for eigenvalues. With abstol
!     set to zero, the default value is used instead

      abstol = zero

!     Solve the generalized symmetric eigenvalue problem
!     A*x = lambda*B*x

      Call dsbgvx('Vectors', 'Values in range', uplo, n, ka, kb, ab, ldab, bb, &
        ldbb, q, ldq, vl, vu, il, iu, abstol, m, w, z, ldz, work, iwork, &
        jfail, info)

      If (info>=0 .And. info<=n) Then

!       Print solution

        Write (nout, 100) 'Number of eigenvalues found =', m
        Write (nout, *)
        Write (nout, *) 'Eigenvalues'
        Write (nout, 110) w(1:m)
        Flush (nout)

!       ifail: behaviour on error exit
!              =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
        ifail = 0
        Call nagf_file_print_matrix_real_gen('General', ' ', n, m, z, ldz, &
          'Selected eigenvectors', ifail)

        If (info>0) Then
          Write (nout, 100) 'INFO eigenvectors failed to converge, INFO =', &
            info
          Write (nout, *) 'Indices of eigenvectors that did not converge'
          Write (nout, 120) jfail(1:m)
        End If
      Else If (info>n .And. info<=2*n) Then
        i = info - n
        Write (nout, 130) 'The leading minor of order ', i, &
          ' of B is not positive definite'
        Write (nout, 100) 'Failure in DSBGVX. INFO =', info
      End If

100   Format (1X, A, I5)
110   Format (3X, (8F8.4))
120   Format (3X, (8I8))
130   Format (1X, A, I4, A)
    End Program
Full documentation of DSBGVX


DSPGV example

Real Generalized Symmetric Eigenproblems: All the eigenvalues, and, optionally, the eigenvectors of a real generalized symmetric-definite eigenproblem, packed storage

 To find all the eigenvalues and eigenvectors of the generalized symmetriceigenproblem [image], where

together with an estimate of the condition number of $ B$, and approximate errorbounds for the computed eigenvalues and eigenvectors.

The example program for DSPGVD illustrates solving a generalized symmetriceigenproblem of the form [image].

Data

DSPGV Example Program Data

  4                         :Value of N

  0.24   0.39   0.42  -0.16
        -0.11   0.79   0.63
               -0.25   0.48
                      -0.03 :End of matrix A

  4.16  -3.12   0.56  -0.10
         5.03  -0.83   1.09
                0.76   0.34
                       1.18 :End of matrix B

Result

 DSPGV Example Program Results

 Eigenvalues
       -2.2254    -0.4548     0.1001     1.1270

 Estimate of reciprocal condition number for B
        5.8E-03

 Error estimates for the eigenvalues
        9.3E-14    2.5E-14    1.1E-14    5.1E-14

Source

    Program dspgv_example

!     DSPGV Example Program Text

!     Copyright 2017, Numerical Algorithms Group Ltd. http://www.nag.com

!     .. Use Statements ..
      Use lapack_interfaces, Only: dlansp, dspgv, dtpcon
      Use lapack_precision, Only: dp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter :: nin = 5, nout = 6
      Character (1), Parameter :: uplo = 'U'
!     .. Local Scalars ..
      Real (Kind=dp) :: anorm, bnorm, eps, rcond, rcondb, t1, t2
      Integer :: i, info, j, n
!     .. Local Arrays ..
      Real (Kind=dp), Allocatable :: ap(:), bp(:), eerbnd(:), w(:), work(:)
      Real (Kind=dp) :: dummy(1, 1)
      Integer, Allocatable :: iwork(:)
!     .. Intrinsic Procedures ..
      Intrinsic :: abs, epsilon
!     .. Executable Statements ..
      Write (nout, *) 'DSPGV Example Program Results'
      Write (nout, *)
!     Skip heading in data file
      Read (nin, *)
      Read (nin, *) n

      Allocate (ap((n*(n+1))/2), bp((n*(n+1))/2), eerbnd(n), w(n), work(3*n), &
        iwork(n))

!     Read the upper or lower triangular parts of the matrices A and
!     B from data file

      If (uplo=='U') Then
        Read (nin, *)((ap(i+(j*(j-1))/2),j=i,n), i=1, n)
        Read (nin, *)((bp(i+(j*(j-1))/2),j=i,n), i=1, n)
      Else If (uplo=='L') Then
        Read (nin, *)((ap(i+((2*n-j)*(j-1))/2),j=1,i), i=1, n)
        Read (nin, *)((bp(i+((2*n-j)*(j-1))/2),j=1,i), i=1, n)
      End If

!     Compute the one-norms of the symmetric matrices A and B

      anorm = dlansp('One norm', uplo, n, ap, work)
      bnorm = dlansp('One norm', uplo, n, bp, work)

!     Solve the generalized symmetric eigenvalue problem
!     A*x = lambda*B*x (itype = 1)

      Call dspgv(1, 'No vectors', uplo, n, ap, bp, w, dummy, 1, work, info)

      If (info==0) Then

!       Print solution

        Write (nout, *) 'Eigenvalues'
        Write (nout, 100) w(1:n)

!       Call DTPCON to estimate the reciprocal condition
!       number of the Cholesky factor of B.  Note that:
!       cond(B) = 1/rcond**2

        Call dtpcon('One norm', uplo, 'Non-unit', n, bp, rcond, work, iwork, &
          info)

!       Print the reciprocal condition number of B

        rcondb = rcond**2
        Write (nout, *)
        Write (nout, *) 'Estimate of reciprocal condition number for B'
        Write (nout, 110) rcondb

!       Get the machine precision, eps, and if rcondb is not less
!       than eps**2, compute error estimates for the eigenvalues

        eps = epsilon(1.0E0_dp)
        If (rcond>=eps) Then
          t1 = eps/rcondb
          t2 = anorm/bnorm
          Do i = 1, n
            eerbnd(i) = t1*(t2+abs(w(i)))
          End Do

!         Print the approximate error bounds for the eigenvalues

          Write (nout, *)
          Write (nout, *) 'Error estimates for the eigenvalues'
          Write (nout, 110) eerbnd(1:n)
        Else
          Write (nout, *)
          Write (nout, *) 'B is very ill-conditioned, error ', &
            'estimates have not been computed'
        End If
      Else If (info>n .And. info<=2*n) Then
        i = info - n
        Write (nout, 120) 'The leading minor of order ', i, &
          ' of B is not positive definite'
      Else
        Write (nout, 130) 'Failure in DSPGV. INFO =', info
      End If

100   Format (3X, (6F11.4))
110   Format (4X, 1P, 6E11.1)
120   Format (1X, A, I4, A)
130   Format (1X, A, I4)
    End Program
Full documentation of DSPGV


DSPGVD example

Real Generalized Symmetric Eigenproblems: All the eigenvalues, and, optionally, the eigenvectors of a real generalized symmetric-definite eigenproblem, packed storage (divide-and-conquer)

 To find all the eigenvalues and eigenvectors of the generalized symmetriceigenproblem [image], where

together with an estimate of the condition number of $ B$, and approximate errorbounds for the computed eigenvalues and eigenvectors.

The example program for DSPGV illustrates solving a generalized symmetriceigenproblem of the form [image].

Data

DSPGVD Example Program Data

  4                         :Value of N

  0.24   0.39   0.42  -0.16
        -0.11   0.79   0.63
               -0.25   0.48
                      -0.03 :End of matrix A

  4.16  -3.12   0.56  -0.10
         5.03  -0.83   1.09
                0.76   0.34
                       1.18 :End of matrix B

Result

 DSPGVD Example Program Results

 Eigenvalues
       -3.5411    -0.3347     0.2983     2.2544

 Estimate of reciprocal condition number for B
        5.8E-03

 Error estimates for the eigenvalues
        1.4E-13    1.7E-14    1.6E-14    9.1E-14

Source

    Program dspgvd_example

!     DSPGVD Example Program Text

!     Copyright 2017, Numerical Algorithms Group Ltd. http://www.nag.com

!     .. Use Statements ..
      Use lapack_interfaces, Only: dlansp, dspgvd, dtpcon
      Use lapack_precision, Only: dp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter :: nin = 5, nout = 6
      Character (1), Parameter :: uplo = 'U'
!     .. Local Scalars ..
      Real (Kind=dp) :: anorm, bnorm, eps, rcond, rcondb, t1
      Integer :: aplen, i, info, j, liwork, lwork, n
!     .. Local Arrays ..
      Real (Kind=dp), Allocatable :: ap(:), bp(:), eerbnd(:), w(:), work(:)
      Real (Kind=dp) :: dummy(1, 1)
      Integer :: idum(1)
      Integer, Allocatable :: iwork(:)
!     .. Intrinsic Procedures ..
      Intrinsic :: abs, epsilon, max, nint
!     .. Executable Statements ..
      Write (nout, *) 'DSPGVD Example Program Results'
      Write (nout, *)
!     Skip heading in data file
      Read (nin, *)
      Read (nin, *) n
      aplen = (n*(n+1))/2
      Allocate (ap(aplen), bp(aplen), eerbnd(n), w(n))

!     Use routine workspace query to get optimal workspace.
      lwork = -1
      liwork = -1
      Call dspgvd(2, 'No vectors', uplo, n, ap, bp, w, dummy, n, dummy, lwork, &
        idum, liwork, info)

!     Make sure that there is at least minimum workspace.
      lwork = max(3*n, nint(dummy(1,1)))
      liwork = max(n, idum(1))
      Allocate (work(lwork), iwork(liwork))

!     Read the upper or lower triangular parts of the matrices A and
!     B from data file

      If (uplo=='U') Then
        Read (nin, *)((ap(i+(j*(j-1))/2),j=i,n), i=1, n)
        Read (nin, *)((bp(i+(j*(j-1))/2),j=i,n), i=1, n)
      Else If (uplo=='L') Then
        Read (nin, *)((ap(i+((2*n-j)*(j-1))/2),j=1,i), i=1, n)
        Read (nin, *)((bp(i+((2*n-j)*(j-1))/2),j=1,i), i=1, n)
      End If

!     Compute the one-norms of the symmetric matrices A and B

      anorm = dlansp('One norm', uplo, n, ap, work)
      bnorm = dlansp('One norm', uplo, n, bp, work)

!     Solve the generalized symmetric eigenvalue problem
!     A*B*x = lambda*x (itype = 2)

!     In the following call the 9th argument is set to n rather
!     than 1 to avoid an incorrect error message in some vendor
!     versions of LAPACK.
      Call dspgvd(2, 'No vectors', uplo, n, ap, bp, w, dummy, n, work, lwork, &
        iwork, liwork, info)

      If (info==0) Then

!       Print solution

        Write (nout, *) 'Eigenvalues'
        Write (nout, 100) w(1:n)

!       Call DTPCON to estimate the reciprocal condition
!       number of the Cholesky factor of B.  Note that:
!       cond(B) = 1/rcond**2.  DTPCON requires WORK and IWORK to be
!       of length at least 3*n and n respectively

        Call dtpcon('One norm', uplo, 'Non-unit', n, bp, rcond, work, iwork, &
          info)

!       Print the reciprocal condition number of B

        rcondb = rcond**2
        Write (nout, *)
        Write (nout, *) 'Estimate of reciprocal condition number for B'
        Write (nout, 110) rcondb

!       Get the machine precision, eps, and if rcondb is not less
!       than eps**2, compute error estimates for the eigenvalues

        eps = epsilon(1.0E0_dp)
        If (rcond>=eps) Then
          t1 = anorm*bnorm
          Do i = 1, n
            eerbnd(i) = eps*(t1+abs(w(i))/rcondb)
          End Do

!         Print the approximate error bounds for the eigenvalues

          Write (nout, *)
          Write (nout, *) 'Error estimates for the eigenvalues'
          Write (nout, 110) eerbnd(1:n)
        Else
          Write (nout, *)
          Write (nout, *) 'B is very ill-conditioned, error ', &
            'estimates have not been computed'
        End If
      Else If (info>n .And. info<=2*n) Then
        i = info - n
        Write (nout, 120) 'The leading minor of order ', i, &
          ' of B is not positive definite'
      Else
        Write (nout, 130) 'Failure in DSPGVD. INFO =', info
      End If

100   Format (3X, (6F11.4))
110   Format (4X, 1P, 6E11.1)
120   Format (1X, A, I4, A)
130   Format (1X, A, I4)
    End Program
Full documentation of DSPGVD


DSPGVX example

Real Generalized Symmetric Eigenproblems: Selected eigenvalues, and, optionally, the eigenvectors of a real generalized symmetric-definite eigenproblem, packed storage

 To find the eigenvalues in the half-open interval $ (-1.0, 1.0]$, andcorresponding eigenvectors, of the generalized symmetric eigenproblem [image], where

The example program for DSPGVD illustrates solving a generalized symmetriceigenproblem of the form [image].

Data

DSPGVX Example Program Data

  4                          :Value of N

 -1.0    1.0                 :Values of VL and VU

  0.24   0.39   0.42  -0.16
        -0.11   0.79   0.63
               -0.25   0.48
                      -0.03  :End of matrix A

  4.16  -3.12   0.56  -0.10
         5.03  -0.83   1.09
                0.76   0.34
                       1.18  :End of matrix B

Result

 DSPGVX Example Program Results

 Number of eigenvalues found =    2

 Eigenvalues
    -0.4548  0.1001
 Selected eigenvectors
          1       2
 1  -0.3080 -0.4469
 2  -0.5329 -0.0371
 3   0.3496  0.0505
 4   0.6211  0.4743

Source

    Program dspgvx_example

!     DSPGVX Example Program Text

!     Copyright 2017, Numerical Algorithms Group Ltd. http://www.nag.com

!     .. Use Statements ..
      Use lapack_example_aux, Only: nagf_blas_damax_val, &
        nagf_file_print_matrix_real_gen
      Use lapack_interfaces, Only: dspgvx
      Use lapack_precision, Only: dp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Real (Kind=dp), Parameter :: zero = 0.0E+0_dp
      Integer, Parameter :: nin = 5, nout = 6
      Character (1), Parameter :: uplo = 'U'
!     .. Local Scalars ..
      Real (Kind=dp) :: abstol, r, vl, vu
      Integer :: i, ifail, il, info, iu, j, k, ldz, m, n
!     .. Local Arrays ..
      Real (Kind=dp), Allocatable :: ap(:), bp(:), w(:), work(:), z(:, :)
      Integer, Allocatable :: iwork(:), jfail(:)
!     .. Executable Statements ..
      Write (nout, *) 'DSPGVX Example Program Results'
      Write (nout, *)
!     Skip heading in data file
      Read (nin, *)
      Read (nin, *) n
      ldz = n
      m = n
      Allocate (ap((n*(n+1))/2), bp((n*(n+1))/2), w(n), work(8*n), z(ldz,m), &
        iwork(5*n), jfail(n))

!     Read the lower and upper bounds of the interval to be searched,
!     and read the upper or lower triangular parts of the matrices A
!     and B from data file

      Read (nin, *) vl, vu
      If (uplo=='U') Then
        Read (nin, *)((ap(i+(j*(j-1))/2),j=i,n), i=1, n)
        Read (nin, *)((bp(i+(j*(j-1))/2),j=i,n), i=1, n)
      Else If (uplo=='L') Then
        Read (nin, *)((ap(i+((2*n-j)*(j-1))/2),j=1,i), i=1, n)
        Read (nin, *)((bp(i+((2*n-j)*(j-1))/2),j=1,i), i=1, n)
      End If

!     Set the absolute error tolerance for eigenvalues. With abstol
!     set to zero, the default value is used instead

      abstol = zero

!     Solve the generalized symmetric eigenvalue problem
!     A*x = lambda*B*x (itype = 1)

      Call dspgvx(1, 'Vectors', 'Values in range', uplo, n, ap, bp, vl, vu, &
        il, iu, abstol, m, w, z, ldz, work, iwork, jfail, info)

      If (info>=0 .And. info<=n) Then

!       Print solution

        Write (nout, 100) 'Number of eigenvalues found =', m
        Write (nout, *)
        Write (nout, *) 'Eigenvalues'
        Write (nout, 110) w(1:m)
        Flush (nout)

!       Normalize the eigenvectors, largest positive
        Do i = 1, m
          Call nagf_blas_damax_val(n, z(1,i), 1, k, r)
          If (z(k,i)<zero) Then
            z(1:n, i) = -z(1:n, i)
          End If
        End Do

!       ifail: behaviour on error exit
!              =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
        ifail = 0
        Call nagf_file_print_matrix_real_gen('General', ' ', n, m, z, ldz, &
          'Selected eigenvectors', ifail)

        If (info>0) Then
          Write (nout, 100) 'INFO eigenvectors failed to converge, INFO =', &
            info
          Write (nout, *) 'Indices of eigenvectors that did not converge'
          Write (nout, 120) jfail(1:m)
        End If
      Else If (info>n .And. info<=2*n) Then
        i = info - n
        Write (nout, 130) 'The leading minor of order ', i, &
          ' of B is not positive definite'
      Else
        Write (nout, 100) 'Failure in DSPGVX. INFO =', info
      End If

100   Format (1X, A, I5)
110   Format (3X, (8F8.4))
120   Format (3X, (8I8))
130   Format (1X, A, I4, A)
    End Program
Full documentation of DSPGVX


DSYGV example

Real Generalized Symmetric Eigenproblems: All the eigenvalues, and, optionally, the eigenvectors of a real generalized symmetric-definite eigenproblem

 To find all the eigenvalues and eigenvectors of the generalized symmetriceigenproblem [image], where

together with an estimate of the condition number of $ B$, and approximate errorbounds for the computed eigenvalues and eigenvectors.

The example program for DSYGVD illustrates solving a generalized symmetriceigenproblem of the form [image].

Data

DSYGV Example Program Data

  4                         :Value of N

  0.24   0.39   0.42  -0.16
        -0.11   0.79   0.63
               -0.25   0.48
                      -0.03 :End of matrix A

  4.16  -3.12   0.56  -0.10
         5.03  -0.83   1.09
                0.76   0.34
                       1.18 :End of matrix B

Result

 DSYGV Example Program Results

 Eigenvalues
       -2.2254    -0.4548     0.1001     1.1270

 Eigenvectors
             1          2          3          4
 1      0.0690    -0.3080    -0.4469     0.5528
 2      0.5740    -0.5329    -0.0371     0.6766
 3      1.5428     0.3496     0.0505     0.9276
 4     -1.4004     0.6211     0.4743    -0.2510

 Estimate of reciprocal condition number for B
        5.8E-03

 Error estimates for the eigenvalues
        9.3E-14    2.5E-14    1.1E-14    5.1E-14

 Error estimates for the eigenvectors
        1.0E-13    2.1E-13    1.8E-13    1.4E-13

Source

    Program dsygv_example

!     DSYGV Example Program Text

!     Copyright 2017, Numerical Algorithms Group Ltd. http://www.nag.com

!     .. Use Statements ..
      Use lapack_example_aux, Only: nagf_blas_damax_val, &
        nagf_file_print_matrix_real_gen
      Use lapack_interfaces, Only: ddisna, dlansy, dsygv, dtrcon
      Use lapack_precision, Only: dp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Real (Kind=dp), Parameter :: zero = 0.0_dp
      Integer, Parameter :: nb = 64, nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=dp) :: anorm, bnorm, eps, r, rcond, rcondb, t1, t2, t3
      Integer :: i, ifail, info, k, lda, ldb, lwork, n
!     .. Local Arrays ..
      Real (Kind=dp), Allocatable :: a(:, :), b(:, :), eerbnd(:), rcondz(:), &
        w(:), work(:), zerbnd(:)
      Real (Kind=dp) :: dummy(1)
      Integer, Allocatable :: iwork(:)
!     .. Intrinsic Procedures ..
      Intrinsic :: abs, epsilon, max, nint
!     .. Executable Statements ..
      Write (nout, *) 'DSYGV Example Program Results'
      Write (nout, *)
!     Skip heading in data file
      Read (nin, *)
      Read (nin, *) n
      lda = n
      ldb = n
      Allocate (a(lda,n), b(ldb,n), eerbnd(n), rcondz(n), w(n), zerbnd(n), &
        iwork(n))

!     Use routine workspace query to get optimal workspace.
      lwork = -1
      Call dsygv(1, 'Vectors', 'Upper', n, a, lda, b, ldb, w, dummy, lwork, &
        info)

!     Make sure that there is enough workspace for block size nb.
      lwork = max((nb+2)*n, nint(dummy(1)))
      Allocate (work(lwork))

!     Read the upper triangular parts of the matrices A and B

      Read (nin, *)(a(i,i:n), i=1, n)
      Read (nin, *)(b(i,i:n), i=1, n)

!     Compute the one-norms of the symmetric matrices A and B

      anorm = dlansy('One norm', 'Upper', n, a, lda, work)
      bnorm = dlansy('One norm', 'Upper', n, b, ldb, work)

!     Solve the generalized symmetric eigenvalue problem
!     A*x = lambda*B*x (ITYPE = 1)

      Call dsygv(1, 'Vectors', 'Upper', n, a, lda, b, ldb, w, work, lwork, &
        info)

      If (info==0) Then

!       Print solution

        Write (nout, *) 'Eigenvalues'
        Write (nout, 100) w(1:n)

        Write (nout, *)
        Flush (nout)

!       Normalize the eigenvectors, largest positive
        Do i = 1, n
          Call nagf_blas_damax_val(n, a(1,i), 1, k, r)
          If (a(k,i)<zero) Then
            a(1:n, i) = -a(1:n, i)
          End If
        End Do

!       ifail: behaviour on error exit
!              =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
        ifail = 0
        Call nagf_file_print_matrix_real_gen('General', ' ', n, n, a, lda, &
          'Eigenvectors', ifail)

!       Call DTRCON to estimate the reciprocal condition
!       number of the Cholesky factor of B.  Note that:
!       cond(B) = 1/rcond**2

        Call dtrcon('One norm', 'Upper', 'Non-unit', n, b, ldb, rcond, work, &
          iwork, info)

!       Print the reciprocal condition number of B

        rcondb = rcond**2
        Write (nout, *)
        Write (nout, *) 'Estimate of reciprocal condition number for B'
        Write (nout, 110) rcondb
        Flush (nout)

!       Get the machine precision, eps, and if rcondb is not less
!       than eps**2, compute error estimates for the eigenvalues and
!       eigenvectors

        eps = epsilon(1.0E0_dp)
        If (rcond>=eps) Then

!         Call DDISNA to estimate reciprocal condition
!         numbers for the eigenvectors of (A - lambda*B)

          Call ddisna('Eigenvectors', n, n, w, rcondz, info)

!         Compute the error estimates for the eigenvalues and
!         eigenvectors

          t1 = eps/rcondb
          t2 = anorm/bnorm
          t3 = t2/rcond
          Do i = 1, n
            eerbnd(i) = t1*(t2+abs(w(i)))
            zerbnd(i) = t1*(t3+abs(w(i)))/rcondz(i)
          End Do

!         Print the approximate error bounds for the eigenvalues
!         and vectors

          Write (nout, *)
          Write (nout, *) 'Error estimates for the eigenvalues'
          Write (nout, 110) eerbnd(1:n)
          Write (nout, *)
          Write (nout, *) 'Error estimates for the eigenvectors'
          Write (nout, 110) zerbnd(1:n)
        Else
          Write (nout, *)
          Write (nout, *) 'B is very ill-conditioned, error ', &
            'estimates have not been computed'
        End If
      Else If (info>n .And. info<=2*n) Then
        i = info - n
        Write (nout, 120) 'The leading minor of order ', i, &
          ' of B is not positive definite'
      Else
        Write (nout, 130) 'Failure in DSYGV. INFO =', info
      End If

100   Format (3X, (6F11.4))
110   Format (4X, 1P, 6E11.1)
120   Format (1X, A, I4, A)
130   Format (1X, A, I4)
    End Program
Full documentation of DSYGV


DSYGVD example

Real Generalized Symmetric Eigenproblems: All the eigenvalues, and, optionally, the eigenvectors of a real generalized symmetric-definite eigenproblem (divide-and-conquer)

 To find all the eigenvalues and eigenvectors of the generalized symmetriceigenproblem [image], where

together with an estimate of the condition number of $ B$, and approximate errorbounds for the computed eigenvalues and eigenvectors.

The example program for DSYGV illustrates solving a generalized symmetriceigenproblem of the form [image].

Data

DSYGVD Example Program Data

  4                         :Value of N

  0.24   0.39   0.42  -0.16
        -0.11   0.79   0.63
               -0.25   0.48
                      -0.03 :End of matrix A

  4.16  -3.12   0.56  -0.10
         5.03  -0.83   1.09
                0.76   0.34
                       1.18 :End of matrix B

Result

 DSYGVD Example Program Results

 Eigenvalues
       -3.5411    -0.3347     0.2983     2.2544
 Eigenvectors
             1          2          3          4
 1     -0.0356    -0.1039    -0.7459     0.1909
 2      0.3809     0.4322    -0.7845     0.3540
 3     -0.2943     1.5644    -0.7144     0.5665
 4     -0.3186    -1.0647     1.1184     0.3859

 Estimate of reciprocal condition number for B
        5.8E-03

 Error estimates for the eigenvalues
        1.4E-13    1.7E-14    1.6E-14    9.1E-14

 Error estimates for the eigenvectors
        5.6E-14    1.3E-13    1.3E-13    6.8E-14

Source

    Program dsygvd_example

!     DSYGVD Example Program Text

!     Copyright 2017, Numerical Algorithms Group Ltd. http://www.nag.com

!     .. Use Statements ..
      Use lapack_example_aux, Only: nagf_blas_damax_val, &
        nagf_file_print_matrix_real_gen
      Use lapack_interfaces, Only: ddisna, dlansy, dsygvd, dtrcon
      Use lapack_precision, Only: dp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Real (Kind=dp), Parameter :: one = 1.0E+0_dp
      Real (Kind=dp), Parameter :: zero = 0.0_dp
      Integer, Parameter :: nb = 64, nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=dp) :: anorm, bnorm, eps, r, rcond, rcondb, t1, t2, t3
      Integer :: i, ifail, info, k, lda, ldb, liwork, lwork, n
!     .. Local Arrays ..
      Real (Kind=dp), Allocatable :: a(:, :), b(:, :), eerbnd(:), rcondz(:), &
        w(:), work(:), zerbnd(:)
      Real (Kind=dp) :: dummy(1)
      Integer :: idum(1)
      Integer, Allocatable :: iwork(:)
!     .. Intrinsic Procedures ..
      Intrinsic :: abs, epsilon, max, nint
!     .. Executable Statements ..
      Write (nout, *) 'DSYGVD Example Program Results'
      Write (nout, *)
!     Skip heading in data file
      Read (nin, *)
      Read (nin, *) n
      lda = n
      ldb = n
      Allocate (a(lda,n), b(ldb,n), eerbnd(n), rcondz(n), w(n), zerbnd(n))

!     Use routine workspace query to get optimal workspace.
      lwork = -1
      liwork = -1
      Call dsygvd(2, 'Vectors', 'Upper', n, a, lda, b, ldb, w, dummy, lwork, &
        idum, liwork, info)

!     Make sure that there is enough workspace for block size nb.
      lwork = max(1+(nb+6+2*n)*n, nint(dummy(1)))
      liwork = max(3+5*n, idum(1))
      Allocate (work(lwork), iwork(liwork))

!     Read the upper triangular parts of the matrices A and B

      Read (nin, *)(a(i,i:n), i=1, n)
      Read (nin, *)(b(i,i:n), i=1, n)

!     Compute the one-norms of the symmetric matrices A and B

      anorm = dlansy('One norm', 'Upper', n, a, lda, work)
      bnorm = dlansy('One norm', 'Upper', n, b, ldb, work)

!     Solve the generalized symmetric eigenvalue problem
!     A*B*x = lambda*x (ITYPE = 2)

      Call dsygvd(2, 'Vectors', 'Upper', n, a, lda, b, ldb, w, work, lwork, &
        iwork, liwork, info)

      If (info==0) Then

!       Print solution

        Write (nout, *) 'Eigenvalues'
        Write (nout, 100) w(1:n)
        Flush (nout)

!       Normalize the eigenvectors, largest positive
        Do i = 1, n
          Call nagf_blas_damax_val(n, a(1,i), 1, k, r)
          If (a(k,i)<zero) Then
            a(1:n, i) = -a(1:n, i)
          End If
        End Do

!       ifail: behaviour on error exit
!              =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
        ifail = 0
        Call nagf_file_print_matrix_real_gen('General', ' ', n, n, a, lda, &
          'Eigenvectors', ifail)

!       Call DTRCON to estimate the reciprocal condition
!       number of the Cholesky factor of B.  Note that:
!       cond(B) = 1/RCOND**2

        Call dtrcon('One norm', 'Upper', 'Non-unit', n, b, ldb, rcond, work, &
          iwork, info)

!       Print the reciprocal condition number of B

        rcondb = rcond**2
        Write (nout, *)
        Write (nout, *) 'Estimate of reciprocal condition number for B'
        Write (nout, 110) rcondb
        Flush (nout)

!       Get the machine precision, EPS, and if RCONDB is not less
!       than EPS**2, compute error estimates for the eigenvalues and
!       eigenvectors

        eps = epsilon(1.0E0_dp)
        If (rcond>=eps) Then

!         Call DDISNA to estimate reciprocal condition
!         numbers for the eigenvectors of (A*B - lambda*I)

          Call ddisna('Eigenvectors', n, n, w, rcondz, info)

!         Compute the error estimates for the eigenvalues and
!         eigenvectors

          t1 = one/rcond
          t2 = eps*t1
          t3 = anorm*bnorm
          Do i = 1, n
            eerbnd(i) = eps*(t3+abs(w(i))/rcondb)
            zerbnd(i) = t2*(t3/rcondz(i)+t1)
          End Do

!         Print the approximate error bounds for the eigenvalues
!         and vectors

          Write (nout, *)
          Write (nout, *) 'Error estimates for the eigenvalues'
          Write (nout, 110) eerbnd(1:n)
          Write (nout, *)
          Write (nout, *) 'Error estimates for the eigenvectors'
          Write (nout, 110) zerbnd(1:n)
        Else
          Write (nout, *)
          Write (nout, *) 'B is very ill-conditioned, error ', &
            'estimates have not been computed'
        End If
      Else If (info>n .And. info<=2*n) Then
        i = info - n
        Write (nout, 120) 'The leading minor of order ', i, &
          ' of B is not positive definite'
      Else
        Write (nout, 130) 'Failure in DSYGVD. INFO =', info
      End If

100   Format (3X, (6F11.4))
110   Format (4X, 1P, 6E11.1)
120   Format (1X, A, I4, A)
130   Format (1X, A, I4)
    End Program
Full documentation of DSYGVD


DSYGVX example

Real Generalized Symmetric Eigenproblems: Selected eigenvalues, and, optionally, the eigenvectors of a real generalized symmetric-definite eigenproblem

 To find the eigenvalues in the half-open interval $ (-1.0, 1.0]$, andcorresponding eigenvectors, of the generalized symmetric eigenproblem [image], where

The example program for DSYGVD illustrates solving a generalized symmetriceigenproblem of the form [image].

Data

DSYGVX Example Program Data

  4                         :Value of N

 -1.0    1.0                :Values of VL and VU

  0.24   0.39   0.42  -0.16
        -0.11   0.79   0.63
               -0.25   0.48
                      -0.03 :End of matrix A

  4.16  -3.12   0.56  -0.10
         5.03  -0.83   1.09
                0.76   0.34
                       1.18 :End of matrix B

Result

 DSYGVX Example Program Results

 Number of eigenvalues found =    2

 Eigenvalues
    -0.4548  0.1001
 Selected eigenvectors
          1       2
 1  -0.3080 -0.4469
 2  -0.5329 -0.0371
 3   0.3496  0.0505
 4   0.6211  0.4743

Source

    Program dsygvx_example

!     DSYGVX Example Program Text

!     Copyright 2017, Numerical Algorithms Group Ltd. http://www.nag.com

!     .. Use Statements ..
      Use lapack_example_aux, Only: nagf_blas_damax_val, &
        nagf_file_print_matrix_real_gen
      Use lapack_interfaces, Only: dsygvx
      Use lapack_precision, Only: dp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Real (Kind=dp), Parameter :: zero = 0.0_dp
      Integer, Parameter :: nb = 64, nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=dp) :: abstol, r, vl, vu
      Integer :: i, ifail, il, info, iu, k, lda, ldb, ldz, lwork, m, n
!     .. Local Arrays ..
      Real (Kind=dp), Allocatable :: a(:, :), b(:, :), w(:), work(:), z(:, :)
      Real (Kind=dp) :: dummy(1)
      Integer, Allocatable :: iwork(:), jfail(:)
!     .. Intrinsic Procedures ..
      Intrinsic :: max, nint
!     .. Executable Statements ..
      Write (nout, *) 'DSYGVX Example Program Results'
      Write (nout, *)
!     Skip heading in data file
      Read (nin, *)
      Read (nin, *) n
      lda = n
      ldb = n
      ldz = n
      m = n
      Allocate (a(lda,n), b(ldb,n), w(n), z(ldz,m), iwork(5*n), jfail(n))

!     Read the lower and upper bounds of the interval to be searched.
      Read (nin, *) vl, vu

!     Use routine workspace query to get optimal workspace.
      lwork = -1
      Call dsygvx(1, 'Vectors', 'Values in range', 'Upper', n, a, lda, b, ldb, &
        vl, vu, il, iu, abstol, m, w, z, ldz, dummy, lwork, iwork, jfail, &
        info)

!     Make sure that there is enough workspace for block size nb.
      lwork = max((nb+3)*n, nint(dummy(1)))
      Allocate (work(lwork))

!     Read the upper triangular parts of the matrices A and B

      Read (nin, *)(a(i,i:n), i=1, n)
      Read (nin, *)(b(i,i:n), i=1, n)

!     Set the absolute error tolerance for eigenvalues.  With ABSTOL
!     set to zero, the default value is used instead

      abstol = zero

!     Solve the generalized symmetric eigenvalue problem
!     A*x = lambda*B*x (ITYPE = 1)

      Call dsygvx(1, 'Vectors', 'Values in range', 'Upper', n, a, lda, b, ldb, &
        vl, vu, il, iu, abstol, m, w, z, ldz, work, lwork, iwork, jfail, info)

      If (info>=0 .And. info<=n) Then

!       Print solution

        Write (nout, 100) 'Number of eigenvalues found =', m
        Write (nout, *)
        Write (nout, *) 'Eigenvalues'
        Write (nout, 110) w(1:m)
        Flush (nout)

!       Normalize the eigenvectors, largest positive
        Do i = 1, m
          Call nagf_blas_damax_val(n, z(1,i), 1, k, r)
          If (z(k,i)<zero) Then
            z(1:n, i) = -z(1:n, i)
          End If
        End Do

!       ifail: behaviour on error exit
!              =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
        ifail = 0
        Call nagf_file_print_matrix_real_gen('General', ' ', n, m, z, ldz, &
          'Selected eigenvectors', ifail)

        If (info>0) Then
          Write (nout, 100) 'INFO eigenvectors failed to converge, INFO =', &
            info
          Write (nout, *) 'Indices of eigenvectors that did not converge'
          Write (nout, 120) jfail(1:m)
        End If
      Else If (info>n .And. info<=2*n) Then
        i = info - n
        Write (nout, 130) 'The leading minor of order ', i, &
          ' of B is not positive definite'
      Else
        Write (nout, 100) 'Failure in DSYGVX. INFO =', info
      End If

100   Format (1X, A, I5)
110   Format (3X, (8F8.4))
120   Format (3X, (8I8))
130   Format (1X, A, I4, A)
    End Program
Full documentation of DSYGVX


LAPACK:Complex Generalized Hermitian Eigenproblems

Next: Real Generalized Nonsymmetric Eigenproblems Up: LAPACK Routines by Subject Previous: Real Generalized Symmetric Eigenproblems

Complex Generalized Hermitian Eigenproblems

  • ZHBGV : All the eigenvalues, and, optionally, the eigenvectors of a complex banded generalized Hermitian-definite eigenproblem
  • ZHBGVD : All the eigenvalues, and, optionally, the eigenvectors of a complex banded generalized Hermitian-definite eigenproblem (divide-and-conquer)
  • ZHBGVX : Selected eigenvalues, and, optionally, the eigenvectors of a complex banded generalized Hermitian-definite eigenproblem
  • ZHEGV : All the eigenvalues, and, optionally, the eigenvectors of a complex generalized Hermitian-definite eigenproblem
  • ZHEGVD : All the eigenvalues, and, optionally, the eigenvectors of a complex generalized Hermitian-definite eigenproblem (divide-and-conquer)
  • ZHEGVX : Selected eigenvalues, and, optionally, the eigenvectors of a complex generalized Hermitian-definite eigenproblem
  • ZHPGV : All the eigenvalues, and, optionally, the eigenvectors of a complex generalized Hermitian-definite eigenproblem, packed storage
  • ZHPGVD : Selected eigenvalues, and, optionally, the eigenvectors of a complex generalized Hermitian-definite eigenproblem, packed storage (divide-and-conquer)
  • ZHPGVX : Selected eigenvalues, and, optionally, the eigenvectors of a complex generalized Hermitian-definite eigenproblem, packed storage


ZHBGV example

Complex Generalized Hermitian Eigenproblems: All the eigenvalues, and, optionally, the eigenvectors of a complex banded generalized Hermitian-definite eigenproblem

 To find all the eigenvalues of the generalized band Hermitian eigenproblem [image], where

and

Data

ZHBGV Example Program Data

   4             2             1                         :Values of N, KA and KB

 (-1.13, 0.00) ( 1.94,-2.10) (-1.40, 0.25)
               (-1.91, 0.00) (-0.82,-0.89) (-0.67, 0.34)
                             (-1.87, 0.00) (-1.10,-0.16)
                                           ( 0.50, 0.00) :End of matrix A

 ( 9.89, 0.00) ( 1.08,-1.73)
               ( 1.69, 0.00) (-0.04, 0.29)
                             ( 2.65, 0.00) (-0.33, 2.24)
                                           ( 2.17, 0.00) :End of matrix B

Result

 ZHBGV Example Program Results

 Eigenvalues
       -6.6089    -2.0416     0.1603     1.7712

Source

    Program zhbgv_example

!     ZHBGV Example Program Text

!     Copyright 2017, Numerical Algorithms Group Ltd. http://www.nag.com

!     .. Use Statements ..
      Use lapack_interfaces, Only: zhbgv
      Use lapack_precision, Only: dp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter :: nin = 5, nout = 6
      Character (1), Parameter :: uplo = 'U'
!     .. Local Scalars ..
      Integer :: i, info, j, ka, kb, ldab, ldbb, n
!     .. Local Arrays ..
      Complex (Kind=dp), Allocatable :: ab(:, :), bb(:, :), work(:)
      Complex (Kind=dp) :: dummy(1, 1)
      Real (Kind=dp), Allocatable :: rwork(:), w(:)
!     .. Intrinsic Procedures ..
      Intrinsic :: max, min
!     .. Executable Statements ..
      Write (nout, *) 'ZHBGV Example Program Results'
      Write (nout, *)
!     Skip heading in data file
      Read (nin, *)
      Read (nin, *) n, ka, kb
      ldab = ka + 1
      ldbb = kb + 1
      Allocate (ab(ldab,n), bb(ldbb,n), work(n), rwork(3*n), w(n))

!     Read the upper or lower triangular parts of the matrices A and
!     B from data file

      If (uplo=='U') Then
        Read (nin, *)((ab(ka+1+i-j,j),j=i,min(n,i+ka)), i=1, n)
        Read (nin, *)((bb(kb+1+i-j,j),j=i,min(n,i+kb)), i=1, n)
      Else If (uplo=='L') Then
        Read (nin, *)((ab(1+i-j,j),j=max(1,i-ka),i), i=1, n)
        Read (nin, *)((bb(1+i-j,j),j=max(1,i-kb),i), i=1, n)
      End If

!     Solve the generalized Hermitian band eigenvalue problem
!     A*x = lambda*B*x

      Call zhbgv('No vectors', uplo, n, ka, kb, ab, ldab, bb, ldbb, w, dummy, &
        1, work, rwork, info)

      If (info==0) Then

!       Print solution

        Write (nout, *) 'Eigenvalues'
        Write (nout, 100) w(1:n)
      Else If (info>n .And. info<=2*n) Then
        i = info - n
        Write (nout, 110) 'The leading minor of order ', i, &
          ' of B is not positive definite'
      Else
        Write (nout, 120) 'Failure in ZHBGV. INFO =', info
      End If

100   Format (3X, (6F11.4))
110   Format (1X, A, I4, A)
120   Format (1X, A, I4)
    End Program
Full documentation of ZHBGV


ZHBGVD example

Complex Generalized Hermitian Eigenproblems: All the eigenvalues, and, optionally, the eigenvectors of a complex banded generalized Hermitian-definite eigenproblem (divide-and-conquer)

 To find all the eigenvalues of the generalized band Hermitian eigenproblem [image], where

and

Data

ZHBGVD Example Program Data

   4             2             1                         :Values of N, KA and KB

 (-1.13, 0.00) ( 1.94,-2.10) (-1.40, 0.25)
               (-1.91, 0.00) (-0.82,-0.89) (-0.67, 0.34)
                             (-1.87, 0.00) (-1.10,-0.16)
                                           ( 0.50, 0.00) :End of matrix A

 ( 9.89, 0.00) ( 1.08,-1.73)
               ( 1.69, 0.00) (-0.04, 0.29)
                             ( 2.65, 0.00) (-0.33, 2.24)
                                           ( 2.17, 0.00) :End of matrix B

Result

 ZHBGVD Example Program Results

 Eigenvalues
       -6.6089    -2.0416     0.1603     1.7712

Source

    Program zhbgvd_example

!     ZHBGVD Example Program Text

!     Copyright 2017, Numerical Algorithms Group Ltd. http://www.nag.com

!     .. Use Statements ..
      Use lapack_interfaces, Only: zhbgvd
      Use lapack_precision, Only: dp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter :: nin = 5, nout = 6
      Character (1), Parameter :: uplo = 'U'
!     .. Local Scalars ..
      Integer :: i, info, j, ka, kb, ldab, ldbb, liwork, lrwork, lwork, n
!     .. Local Arrays ..
      Complex (Kind=dp), Allocatable :: ab(:, :), bb(:, :), work(:)
      Complex (Kind=dp) :: dummy(1, 1)
      Real (Kind=dp), Allocatable :: rwork(:), w(:)
      Integer, Allocatable :: iwork(:)
!     .. Intrinsic Procedures ..
      Intrinsic :: max, min
!     .. Executable Statements ..
      Write (nout, *) 'ZHBGVD Example Program Results'
      Write (nout, *)
!     Skip heading in data file
      Read (nin, *)
      Read (nin, *) n, ka, kb
      ldab = ka + 1
      ldbb = kb + 1
      lrwork = n
      lwork = n
      liwork = 1
      Allocate (ab(ldab,n), bb(ldbb,n), work(lwork), rwork(lrwork), w(n), &
        iwork(liwork))

!     Read the upper or lower triangular parts of the matrices A and
!     B from data file

      If (uplo=='U') Then
        Read (nin, *)((ab(ka+1+i-j,j),j=i,min(n,i+ka)), i=1, n)
        Read (nin, *)((bb(kb+1+i-j,j),j=i,min(n,i+kb)), i=1, n)
      Else If (uplo=='L') Then
        Read (nin, *)((ab(1+i-j,j),j=max(1,i-ka),i), i=1, n)
        Read (nin, *)((bb(1+i-j,j),j=max(1,i-kb),i), i=1, n)
      End If

!     Solve the generalized Hermitian band eigenvalue problem
!     A*x = lambda*B*x

      Call zhbgvd('No vectors', uplo, n, ka, kb, ab, ldab, bb, ldbb, w, dummy, &
        1, work, lwork, rwork, lrwork, iwork, liwork, info)

      If (info==0) Then

!       Print solution

        Write (nout, *) 'Eigenvalues'
        Write (nout, 100) w(1:n)
      Else If (info>n .And. info<=2*n) Then
        i = info - n
        Write (nout, 110) 'The leading minor of order ', i, &
          ' of B is not positive definite'
      Else
        Write (nout, 120) 'Failure in ZHBGVD. INFO =', info
      End If

100   Format (3X, (6F11.4))
110   Format (1X, A, I4, A)
120   Format (1X, A, I4)
    End Program
Full documentation of ZHBGVD


ZHBGVX example

Complex Generalized Hermitian Eigenproblems: Selected eigenvalues, and, optionally, the eigenvectors of a complex banded generalized Hermitian-definite eigenproblem

 To find the eigenvalues in the half-open interval $ (0.0, 2.0]$, andcorresponding eigenvectors, of the generalized band Hermitian eigenproblem [image], where

and

Data

ZHBGVX Example Program Data

   4             2             1                         :Values of N, KA and KB

   0.0           2.0                                     :Values of VL and VU

 (-1.13, 0.00) ( 1.94,-2.10) (-1.40, 0.25)
               (-1.91, 0.00) (-0.82,-0.89) (-0.67, 0.34)
                             (-1.87, 0.00) (-1.10,-0.16)
                                           ( 0.50, 0.00) :End of matrix A

 ( 9.89, 0.00) ( 1.08,-1.73)
               ( 1.69, 0.00) (-0.04, 0.29)
                             ( 2.65, 0.00) (-0.33, 2.24)
                                           ( 2.17, 0.00) :End of matrix B

Result

 ZHBGVX Example Program Results

 Number of eigenvalues found =    2

 Eigenvalues
     0.1603  1.7712
 Selected eigenvectors
             1          2
 1      0.1908     0.0494
        0.0137    -0.0045

 2      0.1413     0.2505
        0.1012     0.4427

 3     -0.0437    -0.9705
       -0.0905     0.0679

 4     -0.2135     0.0606
        0.2880    -1.3227

Source

    Program zhbgvx_example

!     ZHBGVX Example Program Text

!     Copyright 2017, Numerical Algorithms Group Ltd. http://www.nag.com

!     .. Use Statements ..
      Use lapack_example_aux, Only: nagf_file_print_matrix_complex_gen
      Use lapack_interfaces, Only: zhbgvx
      Use lapack_precision, Only: dp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Real (Kind=dp), Parameter :: zero = 0.0E+0_dp
      Integer, Parameter :: nin = 5, nout = 6
      Character (1), Parameter :: uplo = 'U'
!     .. Local Scalars ..
      Real (Kind=dp) :: abstol, vl, vu
      Integer :: i, ifail, il, info, iu, j, ka, kb, ldab, ldbb, ldq, ldz, m, n
!     .. Local Arrays ..
      Complex (Kind=dp), Allocatable :: ab(:, :), bb(:, :), q(:, :), work(:), &
        z(:, :)
      Real (Kind=dp), Allocatable :: rwork(:), w(:)
      Integer, Allocatable :: iwork(:), jfail(:)
!     .. Intrinsic Procedures ..
      Intrinsic :: max, min
!     .. Executable Statements ..
      Write (nout, *) 'ZHBGVX Example Program Results'
      Write (nout, *)
!     Skip heading in data file
      Read (nin, *)
      Read (nin, *) n, ka, kb
      ldab = ka + 1
      ldbb = kb + 1
      ldq = n
      ldz = n
      m = n
      Allocate (ab(ldab,n), bb(ldbb,n), q(ldq,n), work(n), z(ldz,m), &
        rwork(7*n), w(n), iwork(5*n), jfail(n))

!     Read the lower and upper bounds of the interval to be searched,
!     and read the upper or lower triangular parts of the matrices A
!     and B from data file

      Read (nin, *) vl, vu
      If (uplo=='U') Then
        Read (nin, *)((ab(ka+1+i-j,j),j=i,min(n,i+ka)), i=1, n)
        Read (nin, *)((bb(kb+1+i-j,j),j=i,min(n,i+kb)), i=1, n)
      Else If (uplo=='L') Then
        Read (nin, *)((ab(1+i-j,j),j=max(1,i-ka),i), i=1, n)
        Read (nin, *)((bb(1+i-j,j),j=max(1,i-kb),i), i=1, n)
      End If

!     Set the absolute error tolerance for eigenvalues. With abstol
!     set to zero, the default value is used instead

      abstol = zero

!     Solve the generalized symmetric eigenvalue problem
!     A*x = lambda*B*x

      Call zhbgvx('Vectors', 'Values in range', uplo, n, ka, kb, ab, ldab, bb, &
        ldbb, q, ldq, vl, vu, il, iu, abstol, m, w, z, ldz, work, rwork, &
        iwork, jfail, info)

      If (info>=0 .And. info<=n) Then

!       Print solution

        Write (nout, 100) 'Number of eigenvalues found =', m
        Write (nout, *)
        Write (nout, *) 'Eigenvalues'
        Write (nout, 110) w(1:m)
        Flush (nout)

!       ifail: behaviour on error exit
!              =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
        ifail = 0
        Call nagf_file_print_matrix_complex_gen('General', ' ', n, m, z, ldz, &
          'Selected eigenvectors', ifail)

        If (info>0) Then
          Write (nout, 100) 'INFO eigenvectors failed to converge, INFO =', &
            info
          Write (nout, *) 'Indices of eigenvectors that did not converge'
          Write (nout, 120) jfail(1:m)
        End If
      Else If (info>n .And. info<=2*n) Then
        i = info - n
        Write (nout, 130) 'The leading minor of order ', i, &
          ' of B is not positive definite'
      Else
        Write (nout, 100) 'Failure in ZHBGVX. INFO =', info
      End If

100   Format (1X, A, I5)
110   Format (3X, (8F8.4))
120   Format (3X, (8I8))
130   Format (1X, A, I4, A)
    End Program
Full documentation of ZHBGVX


ZHEGV example

Complex Generalized Hermitian Eigenproblems: All the eigenvalues, and, optionally, the eigenvectors of a complex generalized Hermitian-definite eigenproblem

 To find all the eigenvalues and eigenvectors of the generalized Hermitianeigenproblem [image], where

and

together with an estimate of the condition number of $ B$, and approximate errorbounds for the computed eigenvalues and eigenvectors.

The example program for ZHEGVD illustrates solving a generalized Hermitianeigenproblem of the form [image].

Data

ZHEGV Example Program Data

   4                                                        :Value of N

 (-7.36, 0.00) ( 0.77, -0.43) (-0.64, -0.92) ( 3.01, -6.97)
               ( 3.49,  0.00) ( 2.19,  4.45) ( 1.90,  3.73)
                              ( 0.12,  0.00) ( 2.88, -3.17)
                                             (-2.54,  0.00) :End of matrix A

 ( 3.23, 0.00) ( 1.51, -1.92) ( 1.90,  0.84) ( 0.42,  2.50)
               ( 3.58,  0.00) (-0.23,  1.11) (-1.18,  1.37)
                              ( 4.09,  0.00) ( 2.33, -0.14)
                                             ( 4.29,  0.00) :End of matrix B

Result

 ZHEGV Example Program Results

 Eigenvalues
       -5.9990    -2.9936     0.5047     3.9990
 Eigenvectors
             1          2          3          4
 1      1.7405    -0.6626     0.2835     1.2378
        0.0000     0.2258    -0.5806     0.0000

 2     -0.4136    -0.1164    -0.3769    -0.5608
       -0.4689    -0.0178    -0.3194    -0.3729

 3     -0.8404     0.9098    -0.3338    -0.6643
       -0.2483     0.0000    -0.0134    -0.1021

 4      0.3021    -0.6120     0.6663     0.1589
        0.6103    -0.5348     0.0000     0.8366

 Estimate of reciprocal condition number for B
        2.5E-03

 Error estimates for the eigenvalues
        6.7E-13    4.1E-13    1.9E-13    5.0E-13

 Error estimates for the eigenvectors
        1.2E-12    1.1E-12    8.5E-13    9.4E-13

Source

    Program zhegv_example

!     ZHEGV Example Program Text

!     Copyright 2017, Numerical Algorithms Group Ltd. http://www.nag.com

!     .. Use Statements ..
      Use lapack_example_aux, Only: nagf_file_print_matrix_complex_gen
      Use lapack_interfaces, Only: ddisna, zhegv, zlanhe, ztrcon
      Use lapack_precision, Only: dp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter :: nb = 64, nin = 5, nout = 6
!     .. Local Scalars ..
      Complex (Kind=dp) :: scal
      Real (Kind=dp) :: anorm, bnorm, eps, rcond, rcondb, t1, t2, t3
      Integer :: i, ifail, info, k, lda, ldb, lwork, n
!     .. Local Arrays ..
      Complex (Kind=dp), Allocatable :: a(:, :), b(:, :), work(:)
      Complex (Kind=dp) :: dummy(1)
      Real (Kind=dp), Allocatable :: eerbnd(:), rcondz(:), rwork(:), w(:), &
        zerbnd(:)
!     .. Intrinsic Procedures ..
      Intrinsic :: abs, conjg, epsilon, max, maxloc, nint, real
!     .. Executable Statements ..
      Write (nout, *) 'ZHEGV Example Program Results'
      Write (nout, *)
!     Skip heading in data file
      Read (nin, *)
      Read (nin, *) n
      lda = n
      ldb = n
      Allocate (a(lda,n), b(ldb,n), eerbnd(n), rcondz(n), rwork(3*n-2), w(n), &
        zerbnd(n))

!     Use routine workspace query to get optimal workspace.
      lwork = -1
      Call zhegv(1, 'Vectors', 'Upper', n, a, lda, b, ldb, w, dummy, lwork, &
        rwork, info)

!     Make sure that there is enough workspace for block size nb.
      lwork = max((nb+1)*n, nint(real(dummy(1))))
      Allocate (work(lwork))

!     Read the upper triangular parts of the matrices A and B

      Read (nin, *)(a(i,i:n), i=1, n)
      Read (nin, *)(b(i,i:n), i=1, n)

!     Compute the one-norms of the symmetric matrices A and B

      anorm = zlanhe('One norm', 'Upper', n, a, lda, rwork)
      bnorm = zlanhe('One norm', 'Upper', n, b, ldb, rwork)

!     Solve the generalized Hermitian eigenvalue problem
!     A*x = lambda*B*x (itype = 1)

      Call zhegv(1, 'Vectors', 'Upper', n, a, lda, b, ldb, w, work, lwork, &
        rwork, info)

      If (info==0) Then

!       Print solution

        Write (nout, *) 'Eigenvalues'
        Write (nout, 100) w(1:n)
        Flush (nout)

!       Normalize the eigenvectors, largest element real
!       (normalization w.r.t B unaffected: Z^HBZ = I).
        Do i = 1, n
          rwork(1:n) = abs(a(1:n,i))
          k = maxloc(rwork(1:n), 1)
          scal = conjg(a(k,i))/abs(a(k,i))
          a(1:n, i) = a(1:n, i)*scal
        End Do

!       ifail: behaviour on error exit
!              =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
        ifail = 0
        Call nagf_file_print_matrix_complex_gen('General', ' ', n, n, a, lda, &
          'Eigenvectors', ifail)

!       Call ZTRCON to estimate the reciprocal condition
!       number of the Cholesky factor of B.  Note that:
!       cond(B) = 1/rcond**2
        Call ztrcon('One norm', 'Upper', 'Non-unit', n, b, ldb, rcond, work, &
          rwork, info)

!       Print the reciprocal condition number of B

        rcondb = rcond**2
        Write (nout, *)
        Write (nout, *) 'Estimate of reciprocal condition number for B'
        Write (nout, 110) rcondb
        Flush (nout)

!       Get the machine precision, eps, and if rcondb is not less
!       than eps**2, compute error estimates for the eigenvalues and
!       eigenvectors

        eps = epsilon(1.0E0_dp)
        If (rcond>=eps) Then

!         Call DDISNA to estimate reciprocal condition
!         numbers for the eigenvectors of (A - lambda*B)

          Call ddisna('Eigenvectors', n, n, w, rcondz, info)

!         Compute the error estimates for the eigenvalues and
!         eigenvectors

          t1 = eps/rcondb
          t2 = anorm/bnorm
          t3 = t2/rcond
          Do i = 1, n
            eerbnd(i) = t1*(t2+abs(w(i)))
            zerbnd(i) = t1*(t3+abs(w(i)))/rcondz(i)
          End Do

!         Print the approximate error bounds for the eigenvalues
!         and vectors

          Write (nout, *)
          Write (nout, *) 'Error estimates for the eigenvalues'
          Write (nout, 110) eerbnd(1:n)
          Write (nout, *)
          Write (nout, *) 'Error estimates for the eigenvectors'
          Write (nout, 110) zerbnd(1:n)
        Else
          Write (nout, *)
          Write (nout, *) 'B is very ill-conditioned, error ', &
            'estimates have not been computed'
        End If
      Else If (info>n) Then
        i = info - n
        Write (nout, 120) 'The leading minor of order ', i, &
          ' of B is not positive definite'
      Else
        Write (nout, 130) 'Failure in ZHEGV. INFO =', info
      End If

100   Format (3X, (6F11.4))
110   Format (4X, 1P, 6E11.1)
120   Format (1X, A, I4, A)
130   Format (1X, A, I4)
    End Program
Full documentation of ZHEGV


ZHEGVD example

Complex Generalized Hermitian Eigenproblems: All the eigenvalues, and, optionally, the eigenvectors of a complex generalized Hermitian-definite eigenproblem (divide-and-conquer)

 To find all the eigenvalues and eigenvectors of the generalized Hermitianeigenproblem [image], where

and

together with an estimate of the condition number of $ B$, and approximate errorbounds for the computed eigenvalues and eigenvectors.

The example program for ZHEGV illustrates solving a generalized Hermitianeigenproblem of the form [image].

Data

ZHEGVD Example Program Data

   4                                                        :Value of N

 (-7.36, 0.00) ( 0.77, -0.43) (-0.64, -0.92) ( 3.01, -6.97)
               ( 3.49,  0.00) ( 2.19,  4.45) ( 1.90,  3.73)
                              ( 0.12,  0.00) ( 2.88, -3.17)
                                             (-2.54,  0.00) :End of matrix A

 ( 3.23, 0.00) ( 1.51, -1.92) ( 1.90,  0.84) ( 0.42,  2.50)
               ( 3.58,  0.00) (-0.23,  1.11) (-1.18,  1.37)
                              ( 4.09,  0.00) ( 2.33, -0.14)
                                             ( 4.29,  0.00) :End of matrix B

Result

 ZHEGVD Example Program Results

 Eigenvalues
      -61.7321    -6.6195     0.0725    43.1883
 Eigenvectors
             1          2          3          4
 1      0.3903    -0.1560     2.2909    -0.1943
        0.0000    -0.0404     0.0000    -0.0690

 2     -0.1814    -0.1552    -0.5042     0.3884
        0.0114    -0.3651    -0.7120     0.0000

 3      0.0438     0.5364    -1.2701     0.0657
        0.0338     0.0000    -0.4547    -0.2095

 4     -0.2221    -0.1298     0.5706     0.2924
       -0.2272    -0.1880     1.3132    -0.0675

 Estimate of reciprocal condition number for B
        2.5E-03

 Error estimates (relative to machine precision)
 for the eigenvalues:
        2.4E+04    2.8E+03    2.3E+02    1.7E+04

 for the eigenvectors:
        4.7E+02    1.0E+03    1.0E+03    4.9E+02

Source

    Program zhegvd_example

!     ZHEGVD Example Program Text

!     Copyright 2017, Numerical Algorithms Group Ltd. http://www.nag.com

!     .. Use Statements ..
      Use lapack_example_aux, Only: nagf_file_print_matrix_complex_gen
      Use lapack_interfaces, Only: ddisna, zhegvd, zlanhe, ztrcon
      Use lapack_precision, Only: dp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Real (Kind=dp), Parameter :: one = 1.0E+0_dp
      Integer, Parameter :: nb = 64, nin = 5, nout = 6
!     .. Local Scalars ..
      Complex (Kind=dp) :: scal
      Real (Kind=dp) :: anorm, bnorm, eps, rcond, rcondb, t1, t2
      Integer :: i, ifail, info, k, lda, ldb, liwork, lrwork, lwork, n
!     .. Local Arrays ..
      Complex (Kind=dp), Allocatable :: a(:, :), b(:, :), work(:)
      Complex (Kind=dp) :: cdum(1)
      Real (Kind=dp), Allocatable :: eerbnd(:), rcondz(:), rwork(:), w(:), &
        zerbnd(:)
      Real (Kind=dp) :: rdum(1)
      Integer :: idum(1)
      Integer, Allocatable :: iwork(:)
!     .. Intrinsic Procedures ..
      Intrinsic :: abs, conjg, epsilon, max, maxloc, nint, real
!     .. Executable Statements ..
      Write (nout, *) 'ZHEGVD Example Program Results'
      Write (nout, *)
!     Skip heading in data file
      Read (nin, *)
      Read (nin, *) n
      lda = n
      ldb = n
      Allocate (a(lda,n), b(ldb,n), eerbnd(n), rcondz(n), w(n), zerbnd(n))

!     Use routine workspace query to get optimal workspace.
      lwork = -1
      liwork = -1
      lrwork = -1
      Call zhegvd(2, 'Vectors', 'Upper', n, a, lda, b, ldb, w, cdum, lwork, &
        rdum, lrwork, idum, liwork, info)

!     Make sure that there is enough workspace for block size nb.
      lwork = max((nb+2+n)*n, nint(real(cdum(1))))
      lrwork = max(1+(5+2*n)*n, nint(rdum(1)))
      liwork = max(3+5*n, idum(1))
      Allocate (work(lwork), rwork(lrwork), iwork(liwork))

!     Read the upper triangular parts of the matrices A and B

      Read (nin, *)(a(i,i:n), i=1, n)
      Read (nin, *)(b(i,i:n), i=1, n)

!     Compute the one-norms of the symmetric matrices A and B

      anorm = zlanhe('One norm', 'Upper', n, a, lda, rwork)
      bnorm = zlanhe('One norm', 'Upper', n, b, ldb, rwork)

!     Solve the generalized Hermitian eigenvalue problem
!     A*B*x = lambda*x (itype = 2)
      Call zhegvd(2, 'Vectors', 'Upper', n, a, lda, b, ldb, w, work, lwork, &
        rwork, lrwork, iwork, liwork, info)

      If (info==0) Then

!       Print solution

        Write (nout, *) 'Eigenvalues'
        Write (nout, 100) w(1:n)
        Flush (nout)

!       Normalize the eigenvectors, largest element real
        Do i = 1, n
          rwork(1:n) = abs(a(1:n,i))
          k = maxloc(rwork(1:n), 1)
          scal = conjg(a(k,i))/abs(a(k,i))
          a(1:n, i) = a(1:n, i)*scal
        End Do

!       ifail: behaviour on error exit
!              =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
        ifail = 0
        Call nagf_file_print_matrix_complex_gen('General', ' ', n, n, a, lda, &
          'Eigenvectors', ifail)

!       Call ZTRCON to estimate the reciprocal condition
!       number of the Cholesky factor of B.  Note that:
!       cond(B) = 1/rcond**2
        Call ztrcon('One norm', 'Upper', 'Non-unit', n, b, ldb, rcond, work, &
          rwork, info)

!       Print the reciprocal condition number of B

        rcondb = rcond**2
        Write (nout, *)
        Write (nout, *) 'Estimate of reciprocal condition number for B'
        Write (nout, 110) rcondb
        Flush (nout)

!       Get the machine precision, eps, and if rcondb is not less
!       than eps**2, compute error estimates for the eigenvalues and
!       eigenvectors

        eps = epsilon(1.0E0_dp)
        If (rcond>=eps) Then

!         Call DDISNA to estimate reciprocal condition
!         numbers for the eigenvectors of (A*B - lambda*I)

          Call ddisna('Eigenvectors', n, n, w, rcondz, info)

!         Compute the error estimates for the eigenvalues and
!         eigenvectors

          t1 = one/rcond
          t2 = anorm*bnorm
          Do i = 1, n
            eerbnd(i) = (t2+abs(w(i))/rcondb)
            zerbnd(i) = t1*(t2/rcondz(i)+t1)
          End Do

!         Print the approximate error bounds for the eigenvalues
!         and vectors

          Write (nout, *)
          Write (nout, *) 'Error estimates (relative to machine precision)'
          Write (nout, *) 'for the eigenvalues:'
          Write (nout, 110) eerbnd(1:n)
          Write (nout, *)
          Write (nout, *) 'for the eigenvectors:'
          Write (nout, 110) zerbnd(1:n)
        Else
          Write (nout, *)
          Write (nout, *) 'B is very ill-conditioned, error ', &
            'estimates have not been computed'
        End If
      Else If (info>n) Then
        i = info - n
        Write (nout, 120) 'The leading minor of order ', i, &
          ' of B is not positive definite'
      Else
        Write (nout, 130) 'Failure in ZHEGVD. INFO =', info
      End If

100   Format (3X, (6F11.4))
110   Format (4X, 1P, 6E11.1)
120   Format (1X, A, I4, A)
130   Format (1X, A, I4)
    End Program
Full documentation of ZHEGVD


ZHEGVX example

Complex Generalized Hermitian Eigenproblems: Selected eigenvalues, and, optionally, the eigenvectors of a complex generalized Hermitian-definite eigenproblem

 To find all the eigenvalues in the half-open interval $ (-3, 3)$, andcorresponding eigenvectors, of the generalized Hermitian eigenproblem [image], where

and

The example program for ZHEGVD illustrates solving a generalized Hermitianeigenproblem of the form [image].

Data

ZHEGVX Example Program Data

   4                                                        :Value of N

  -3.0           3.0                                        :Values of VL and VU

 (-7.36, 0.00) ( 0.77, -0.43) (-0.64, -0.92) ( 3.01, -6.97)
               ( 3.49,  0.00) ( 2.19,  4.45) ( 1.90,  3.73)
                              ( 0.12,  0.00) ( 2.88, -3.17)
                                             (-2.54,  0.00) :End of matrix A

 ( 3.23, 0.00) ( 1.51, -1.92) ( 1.90,  0.84) ( 0.42,  2.50)
               ( 3.58,  0.00) (-0.23,  1.11) (-1.18,  1.37)
                              ( 4.09,  0.00) ( 2.33, -0.14)
                                             ( 4.29,  0.00) :End of matrix B

Result

 ZHEGVX Example Program Results

 Number of eigenvalues found =    2

 Eigenvalues
    -2.9936  0.5047
 Selected eigenvectors
          1       2
 1  -0.6626  0.2835
     0.2258 -0.5806

 2  -0.1164 -0.3769
    -0.0178 -0.3194

 3   0.9098 -0.3338
    -0.0000 -0.0134

 4  -0.6120  0.6663
    -0.5348  0.0000

Source

    Program zhegvx_example

!     ZHEGVX Example Program Text

!     Copyright 2017, Numerical Algorithms Group Ltd. http://www.nag.com

!     .. Use Statements ..
      Use lapack_example_aux, Only: nagf_file_print_matrix_complex_gen
      Use lapack_interfaces, Only: zhegvx
      Use lapack_precision, Only: dp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Real (Kind=dp), Parameter :: zero = 0.0E+0_dp
      Integer, Parameter :: nb = 64, nin = 5, nout = 6
!     .. Local Scalars ..
      Complex (Kind=dp) :: scal
      Real (Kind=dp) :: abstol, vl, vu
      Integer :: i, ifail, il, info, iu, k, lda, ldb, ldz, lwork, m, n
!     .. Local Arrays ..
      Complex (Kind=dp), Allocatable :: a(:, :), b(:, :), work(:), z(:, :)
      Complex (Kind=dp) :: dummy(1)
      Real (Kind=dp), Allocatable :: rwork(:), w(:)
      Integer, Allocatable :: iwork(:), jfail(:)
!     .. Intrinsic Procedures ..
      Intrinsic :: abs, conjg, max, maxloc, nint, real
!     .. Executable Statements ..
      Write (nout, *) 'ZHEGVX Example Program Results'
      Write (nout, *)
!     Skip heading in data file
      Read (nin, *)
      Read (nin, *) n
      lda = n
      ldb = n
      ldz = n
      m = n
      Allocate (a(lda,n), b(ldb,n), z(ldz,m), rwork(7*n), w(n), iwork(5*n), &
        jfail(n))

!     Read the lower and upper bounds of the interval to be searched.
      Read (nin, *) vl, vu

!     Use routine workspace query to get optimal workspace.
      lwork = -1
      Call zhegvx(1, 'Vectors', 'Values in range', 'Upper', n, a, lda, b, ldb, &
        vl, vu, il, iu, abstol, m, w, z, ldz, dummy, lwork, rwork, iwork, &
        jfail, info)

!     Make sure that there is enough workspace for block size nb.
      lwork = max((nb+1)*n, nint(real(dummy(1))))
      Allocate (work(lwork))

!     Read the upper triangular parts of the matrices A and B

      Read (nin, *)(a(i,i:n), i=1, n)
      Read (nin, *)(b(i,i:n), i=1, n)

!     Set the absolute error tolerance for eigenvalues.  With abstol
!     set to zero, the default value is used instead

      abstol = zero

!     Solve the generalized Hermitian eigenvalue problem
!     A*x = lambda*B*x (itype = 1)

      Call zhegvx(1, 'Vectors', 'Values in range', 'Upper', n, a, lda, b, ldb, &
        vl, vu, il, iu, abstol, m, w, z, ldz, work, lwork, rwork, iwork, &
        jfail, info)

      If (info>=0 .And. info<=n) Then

!       Print solution

        Write (nout, 100) 'Number of eigenvalues found =', m
        Write (nout, *)
        Write (nout, *) 'Eigenvalues'
        Write (nout, 110) w(1:m)
        Flush (nout)

!       Normalize the eigenvectors, largest element real
        Do i = 1, m
          rwork(1:n) = abs(z(1:n,i))
          k = maxloc(rwork(1:n), 1)
          scal = conjg(z(k,i))/abs(z(k,i))
          z(1:n, i) = z(1:n, i)*scal
        End Do

!       ifail: behaviour on error exit
!              =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
        ifail = 0
        Call nagf_file_print_matrix_complex_gen('General', ' ', n, m, z, ldz, &
          'Selected eigenvectors', ifail)

        If (info>0) Then
          Write (nout, 100) 'INFO eigenvectors failed to converge, INFO =', &
            info
          Write (nout, *) 'Indices of eigenvectors that did not converge'
          Write (nout, 120) jfail(1:m)
        End If
      Else If (info>n .And. info<=2*n) Then
        i = info - n
        Write (nout, 130) 'The leading minor of order ', i, &
          ' of B is not positive definite'
      Else
        Write (nout, 100) 'Failure in ZHEGVX. INFO =', info
      End If

100   Format (1X, A, I5)
110   Format (3X, (8F8.4))
120   Format (3X, (8I8))
130   Format (1X, A, I4, A)
    End Program
Full documentation of ZHEGVX


ZHPGV example

Complex Generalized Hermitian Eigenproblems: All the eigenvalues, and, optionally, the eigenvectors of a complex generalized Hermitian-definite eigenproblem, packed storage

 To find all the eigenvalues and eigenvectors of the generalized Hermitianeigenproblem [image], where

and

together with an estimate of the condition number of $ B$, and approximate errorbounds for the computed eigenvalues and eigenvectors.

The example program for ZHPGVD illustrates solving a generalized symmetriceigenproblem of the form [image].

Data

ZHPGV Example Program Data

   4                                                        :Value of N

 (-7.36, 0.00) ( 0.77, -0.43) (-0.64, -0.92) ( 3.01, -6.97)
               ( 3.49,  0.00) ( 2.19,  4.45) ( 1.90,  3.73)
                              ( 0.12,  0.00) ( 2.88, -3.17)
                                             (-2.54,  0.00) :End of matrix A

 ( 3.23, 0.00) ( 1.51, -1.92) ( 1.90,  0.84) ( 0.42,  2.50)
               ( 3.58,  0.00) (-0.23,  1.11) (-1.18,  1.37)
                              ( 4.09,  0.00) ( 2.33, -0.14)
                                             ( 4.29,  0.00) :End of matrix B

Result

 ZHPGV Example Program Results

 Eigenvalues
       -5.9990    -2.9936     0.5047     3.9990

 Estimate of reciprocal condition number for B
        2.5E-03

 Error estimates for the eigenvalues
        6.7E-13    4.1E-13    1.9E-13    5.0E-13

Source

    Program zhpgv_example

!     ZHPGV Example Program Text

!     Copyright 2017, Numerical Algorithms Group Ltd. http://www.nag.com

!     .. Use Statements ..
      Use lapack_interfaces, Only: zhpgv, zlanhp, ztpcon
      Use lapack_precision, Only: dp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter :: nin = 5, nout = 6
      Character (1), Parameter :: uplo = 'U'
!     .. Local Scalars ..
      Real (Kind=dp) :: anorm, bnorm, eps, rcond, rcondb, t1, t2
      Integer :: i, info, j, n
!     .. Local Arrays ..
      Complex (Kind=dp), Allocatable :: ap(:), bp(:), work(:)
      Complex (Kind=dp) :: dummy(1, 1)
      Real (Kind=dp), Allocatable :: eerbnd(:), rwork(:), w(:)
!     .. Intrinsic Procedures ..
      Intrinsic :: abs, epsilon
!     .. Executable Statements ..
      Write (nout, *) 'ZHPGV Example Program Results'
      Write (nout, *)
!     Skip heading in data file
      Read (nin, *)
      Read (nin, *) n

      Allocate (ap((n*(n+1))/2), bp((n*(n+1))/2), work(2*n), eerbnd(n), rwork( &
        3*n-2), w(n))

!     Read the upper or lower triangular parts of the matrices A and
!     B from data file

      If (uplo=='U') Then
        Read (nin, *)((ap(i+(j*(j-1))/2),j=i,n), i=1, n)
        Read (nin, *)((bp(i+(j*(j-1))/2),j=i,n), i=1, n)
      Else If (uplo=='L') Then
        Read (nin, *)((ap(i+((2*n-j)*(j-1))/2),j=1,i), i=1, n)
        Read (nin, *)((bp(i+((2*n-j)*(j-1))/2),j=1,i), i=1, n)
      End If

!     Compute the one-norms of the symmetric matrices A and B

      anorm = zlanhp('One norm', uplo, n, ap, rwork)
      bnorm = zlanhp('One norm', uplo, n, bp, rwork)

!     Solve the generalized symmetric eigenvalue problem
!     A*x = lambda*B*x (ITYPE = 1)

      Call zhpgv(1, 'No vectors', uplo, n, ap, bp, w, dummy, 1, work, rwork, &
        info)

      If (info==0) Then

!       Print solution

        Write (nout, *) 'Eigenvalues'
        Write (nout, 100) w(1:n)

!       Call ZTPCON to estimate the reciprocal condition
!       number of the Cholesky factor of B.  Note that:
!       cond(B) = 1/RCOND**2

        Call ztpcon('One norm', uplo, 'Non-unit', n, bp, rcond, work, rwork, &
          info)

!       Print the reciprocal condition number of B

        rcondb = rcond**2
        Write (nout, *)
        Write (nout, *) 'Estimate of reciprocal condition number for B'
        Write (nout, 110) rcondb

!       Get the machine precision, EPS, and if RCONDB is not less
!       than EPS**2, compute error estimates for the eigenvalues

        eps = epsilon(1.0E0_dp)
        If (rcond>=eps) Then
          t1 = eps/rcondb
          t2 = anorm/bnorm
          Do i = 1, n
            eerbnd(i) = t1*(t2+abs(w(i)))
          End Do

!         Print the approximate error bounds for the eigenvalues

          Write (nout, *)
          Write (nout, *) 'Error estimates for the eigenvalues'
          Write (nout, 110) eerbnd(1:n)
        Else
          Write (nout, *)
          Write (nout, *) 'B is very ill-conditioned, error ', &
            'estimates have not been computed'
        End If
      Else If (info>n .And. info<=2*n) Then
        i = info - n
        Write (nout, 120) 'The leading minor of order ', i, &
          ' of B is not positive definite'
      Else
        Write (nout, 130) 'Failure in ZHPGV. INFO =', info
      End If

100   Format (3X, (6F11.4))
110   Format (4X, 1P, 6E11.1)
120   Format (1X, A, I4, A)
130   Format (1X, A, I4)
    End Program
Full documentation of ZHPGV


ZHPGVD example

Complex Generalized Hermitian Eigenproblems: Selected eigenvalues, and, optionally, the eigenvectors of a complex generalized Hermitian-definite eigenproblem, packed storage (divide-and-conquer)

 To find all the eigenvalues and eigenvectors of the generalized Hermitianeigenproblem [image], where

and

together with an estimate of the condition number of $ B$, and approximate errorbounds for the computed eigenvalues and eigenvectors.

The example program for ZHPGV illustrates solving a generalized Hermitianeigenproblem of the form [image].

Data

ZHPGVD Example Program Data

   4                                                        :Value of N

 (-7.36, 0.00) ( 0.77, -0.43) (-0.64, -0.92) ( 3.01, -6.97)
               ( 3.49,  0.00) ( 2.19,  4.45) ( 1.90,  3.73)
                              ( 0.12,  0.00) ( 2.88, -3.17)
                                             (-2.54,  0.00) :End of matrix A

 ( 3.23, 0.00) ( 1.51, -1.92) ( 1.90,  0.84) ( 0.42,  2.50)
               ( 3.58,  0.00) (-0.23,  1.11) (-1.18,  1.37)
                              ( 4.09,  0.00) ( 2.33, -0.14)
                                             ( 4.29,  0.00) :End of matrix B

Result

 ZHPGVD Example Program Results

 Eigenvalues
      -61.7321    -6.6195     0.0725    43.1883

 Estimate of reciprocal condition number for B
        2.5E-03

 Error estimates (relative to machine precision)
 for the eigenvalues:
        2.4E+04    2.8E+03    2.3E+02    1.7E+04

Source

    Program zhpgvd_example

!     ZHPGVD Example Program Text

!     Copyright 2017, Numerical Algorithms Group Ltd. http://www.nag.com

!     .. Use Statements ..
      Use lapack_interfaces, Only: zhpgvd, zlanhp, ztpcon
      Use lapack_precision, Only: dp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter :: nin = 5, nout = 6
      Character (1), Parameter :: uplo = 'U'
!     .. Local Scalars ..
      Real (Kind=dp) :: anorm, bnorm, eps, rcond, rcondb, t1
      Integer :: aplen, i, info, j, liwork, lrwork, lwork, n
!     .. Local Arrays ..
      Complex (Kind=dp), Allocatable :: ap(:), bp(:), work(:)
      Complex (Kind=dp) :: dummy(1, 1)
      Real (Kind=dp), Allocatable :: eerbnd(:), rwork(:), w(:)
      Real (Kind=dp) :: rdum(1)
      Integer :: idum(1)
      Integer, Allocatable :: iwork(:)
!     .. Intrinsic Procedures ..
      Intrinsic :: abs, epsilon, max, nint, real
!     .. Executable Statements ..
      Write (nout, *) 'ZHPGVD Example Program Results'
      Write (nout, *)
!     Skip heading in data file
      Read (nin, *)
      Read (nin, *) n
      aplen = (n*(n+1))/2
      Allocate (ap(aplen), bp(aplen), eerbnd(n), w(n))

!     Use routine workspace query to get optimal workspace.
      lwork = -1
      liwork = -1
      lrwork = -1
      Call zhpgvd(2, 'No vectors', uplo, n, ap, bp, w, dummy, 1, dummy, lwork, &
        rdum, lrwork, idum, liwork, info)

!     Make sure that there is at least the minimum workspace
      lwork = max(2*n, nint(real(dummy(1,1))))
      lrwork = max(n, nint(rdum(1)))
      liwork = max(1, idum(1))
      Allocate (work(lwork), rwork(lrwork), iwork(liwork))

!     Read the upper or lower triangular parts of the matrices A and
!     B from data file

      If (uplo=='U') Then
        Read (nin, *)((ap(i+(j*(j-1))/2),j=i,n), i=1, n)
        Read (nin, *)((bp(i+(j*(j-1))/2),j=i,n), i=1, n)
      Else If (uplo=='L') Then
        Read (nin, *)((ap(i+((2*n-j)*(j-1))/2),j=1,i), i=1, n)
        Read (nin, *)((bp(i+((2*n-j)*(j-1))/2),j=1,i), i=1, n)
      End If

!     Compute the one-norms of the symmetric matrices A and B

      anorm = zlanhp('One norm', uplo, n, ap, rwork)
      bnorm = zlanhp('One norm', uplo, n, bp, rwork)

!     Solve the generalized symmetric eigenvalue problem
!     A*B*x = lambda*x (itype = 2)

      Call zhpgvd(2, 'No vectors', uplo, n, ap, bp, w, dummy, 1, work, lwork, &
        rwork, lrwork, iwork, liwork, info)

      If (info==0) Then

!       Print solution

        Write (nout, *) 'Eigenvalues'
        Write (nout, 100) w(1:n)

!       Call ZTPCON to estimate the reciprocal condition
!       number of the Cholesky factor of B.  Note that:
!       cond(B) = 1/rcond**2.  ZTPCON requires WORK and RWORK to be
!       of length at least 2*n and n respectively

        Call ztpcon('One norm', uplo, 'Non-unit', n, bp, rcond, work, rwork, &
          info)

!       Print the reciprocal condition number of B

        rcondb = rcond**2
        Write (nout, *)
        Write (nout, *) 'Estimate of reciprocal condition number for B'
        Write (nout, 110) rcondb

!       Get the machine precision, eps, and if rcondb is not less
!       than eps**2, compute error estimates for the eigenvalues

        eps = epsilon(1.0E0_dp)
        If (rcond>=eps) Then
          t1 = anorm*bnorm
          Do i = 1, n
            eerbnd(i) = t1 + abs(w(i))/rcondb
          End Do

!         Print the approximate error bounds for the eigenvalues

          Write (nout, *)
          Write (nout, *) 'Error estimates (relative to machine precision)'
          Write (nout, *) 'for the eigenvalues:'
          Write (nout, 110) eerbnd(1:n)
        Else
          Write (nout, *)
          Write (nout, *) 'B is very ill-conditioned, error ', &
            'estimates have not been computed'
        End If
      Else If (info>n .And. info<=2*n) Then
        i = info - n
        Write (nout, 120) 'The leading minor of order ', i, &
          ' of B is not positive definite'
      Else
        Write (nout, 130) 'Failure in ZHPGVD. INFO =', info
      End If

100   Format (3X, (6F11.4))
110   Format (4X, 1P, 6E11.1)
120   Format (1X, A, I4, A)
130   Format (1X, A, I4)
    End Program
Full documentation of ZHPGVD


ZHPGVX example

Complex Generalized Hermitian Eigenproblems: Selected eigenvalues, and, optionally, the eigenvectors of a complex generalized Hermitian-definite eigenproblem, packed storage

 To find all the eigenvalues in the half-open interval $ (-3, 3]$, andcorresponding eigenvectors, of the generalized Hermitian eigenproblem [image], where

and

The example program for ZHPGVD illustrates solving a generalized symmetriceigenproblem of the form [image].

Data

ZHPGVX Example Program Data

   4                                                        :Value of N

  -3.0           3.0                                        :Values of VL and VU

 (-7.36, 0.00) ( 0.77, -0.43) (-0.64, -0.92) ( 3.01, -6.97)
               ( 3.49,  0.00) ( 2.19,  4.45) ( 1.90,  3.73)
                              ( 0.12,  0.00) ( 2.88, -3.17)
                                             (-2.54,  0.00) :End of matrix A

 ( 3.23, 0.00) ( 1.51, -1.92) ( 1.90,  0.84) ( 0.42,  2.50)
               ( 3.58,  0.00) (-0.23,  1.11) (-1.18,  1.37)
                              ( 4.09,  0.00) ( 2.33, -0.14)
                                             ( 4.29,  0.00) :End of matrix B

Result

 ZHPGVX Example Program Results

 Number of eigenvalues found =    2

 Eigenvalues
    -2.9936  0.5047
 Selected eigenvectors
          1       2
 1  -0.6626  0.2835
     0.2258 -0.5806

 2  -0.1164 -0.3769
    -0.0178 -0.3194

 3   0.9098 -0.3338
    -0.0000 -0.0134

 4  -0.6120  0.6663
    -0.5348  0.0000

Source

    Program zhpgvx_example

!     ZHPGVX Example Program Text

!     Copyright 2017, Numerical Algorithms Group Ltd. http://www.nag.com

!     .. Use Statements ..
      Use lapack_example_aux, Only: nagf_file_print_matrix_complex_gen
      Use lapack_interfaces, Only: zhpgvx
      Use lapack_precision, Only: dp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Real (Kind=dp), Parameter :: zero = 0.0E+0_dp
      Integer, Parameter :: nin = 5, nout = 6
      Character (1), Parameter :: uplo = 'U'
!     .. Local Scalars ..
      Complex (Kind=dp) :: scal
      Real (Kind=dp) :: abstol, vl, vu
      Integer :: i, ifail, il, info, iu, j, k, ldz, m, n
!     .. Local Arrays ..
      Complex (Kind=dp), Allocatable :: ap(:), bp(:), work(:), z(:, :)
      Real (Kind=dp), Allocatable :: rwork(:), w(:)
      Integer, Allocatable :: iwork(:), jfail(:)
!     .. Intrinsic Procedures ..
      Intrinsic :: abs, conjg, maxloc
!     .. Executable Statements ..
      Write (nout, *) 'ZHPGVX Example Program Results'
      Write (nout, *)
!     Skip heading in data file
      Read (nin, *)
      Read (nin, *) n
      ldz = n
      m = n
      Allocate (ap((n*(n+1))/2), bp((n*(n+1))/2), work(2*n), z(ldz,m), rwork(7 &
        *n), w(n), iwork(5*n), jfail(n))

!     Read the lower and upper bounds of the interval to be searched,
!     and read the upper or lower triangular parts of the matrices A
!     and B from data file

      Read (nin, *) vl, vu
      If (uplo=='U') Then
        Read (nin, *)((ap(i+(j*(j-1))/2),j=i,n), i=1, n)
        Read (nin, *)((bp(i+(j*(j-1))/2),j=i,n), i=1, n)
      Else If (uplo=='L') Then
        Read (nin, *)((ap(i+((2*n-j)*(j-1))/2),j=1,i), i=1, n)
        Read (nin, *)((bp(i+((2*n-j)*(j-1))/2),j=1,i), i=1, n)
      End If

!     Set the absolute error tolerance for eigenvalues. With abstol
!     set to zero, the default value is used instead

      abstol = zero

!     Solve the generalized Hermitian eigenvalue problem
!     A*x = lambda*B*x (itype = 1)

      Call zhpgvx(1, 'Vectors', 'Values in range', uplo, n, ap, bp, vl, vu, &
        il, iu, abstol, m, w, z, ldz, work, rwork, iwork, jfail, info)

      If (info>=0 .And. info<=n) Then

!       Print solution

        Write (nout, 100) 'Number of eigenvalues found =', m
        Write (nout, *)
        Write (nout, *) 'Eigenvalues'
        Write (nout, 110) w(1:m)
        Flush (nout)

!       Normalize the eigenvectors, largest element real
        Do i = 1, m
          rwork(1:n) = abs(z(1:n,i))
          k = maxloc(rwork(1:n), 1)
          scal = conjg(z(k,i))/abs(z(k,i))
          z(1:n, i) = z(1:n, i)*scal
        End Do

!       ifail: behaviour on error exit
!              =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
        ifail = 0
        Call nagf_file_print_matrix_complex_gen('General', ' ', n, m, z, ldz, &
          'Selected eigenvectors', ifail)

        If (info>0) Then
          Write (nout, 100) 'INFO eigenvectors failed to converge, INFO =', &
            info
          Write (nout, *) 'Indices of eigenvectors that did not converge'
          Write (nout, 120) jfail(1:m)
        End If
      Else If (info>n .And. info<=2*n) Then
        i = info - n
        Write (nout, 130) 'The leading minor of order ', i, &
          ' of B is not positive definite'
      Else
        Write (nout, 100) 'Failure in ZHPGVX. INFO =', info
      End If

100   Format (1X, A, I5)
110   Format (3X, (8F8.4))
120   Format (3X, (8I8))
130   Format (1X, A, I4, A)
    End Program
Full documentation of ZHPGVX


LAPACK:Real Generalized Nonsymmetric Eigenproblems

Next: Complex Generalized Nonsymmetric Eigenproblems Up: LAPACK Routines by Subject Previous: Complex Generalized Hermitian Eigenproblems

Real Generalized Nonsymmetric Eigenproblems

  • DGGES : For a real nonsymmetric matrix pair, the generalized eigenvalues, the generalized real Schur form and, optionally, the left and/or right matrices of Schur vectors
  • DGGES3 : Computes, for a real nonsymmetric matrix pair, using BLAS-3, the generalized eigenvalues, the generalized real Schur form and, optionally, the left and/or right matrices of Schur vectors
  • DGGESX : For a real nonsymmetric matrix pair, the generalized eigenvalues, the generalized real Schur form and, optionally, the left and/or right matrices of Schur vectors; also, optionally, reciprocal condition numbers for selected eigenvalues
  • DGGEV : For a real nonsymmetric matrix pair, the generalized eigenvalues, and optionally, the left and/or right generalized eigenvectors
  • DGGEV3 : Computes, for a real nonsymmetric matrix pair, using BLAS-3, the generalized eigenvalues, and optionally, the left and/or right generalized eigenvectors
  • DGGEVX : For a real nonsymmetric matrix pair, the generalized eigenvalues, and optionally, the left and/or right generalized eigenvectors; also, optionally, the balancing transformation, the reciprocal condition numbers for the eigenvalues and for the right eigenvectors


DGGES example

Real Generalized Nonsymmetric Eigenproblems: For a real nonsymmetric matrix pair, the generalized eigenvalues, the generalized real Schur form and, optionally, the left and/or right matrices of Schur vectors

 To find the generalized Schur factorization of the matrix pair $ (A,B)$, where

such that the real eigenvalues of $ (A,B)$ correspond to the top left diagonalelements of the generalized Schur form, $ (S,T)$.

Data

DGGES Example Program Data
   4                     :Value of N
   3.9  12.5 -34.5  -0.5
   4.3  21.5 -47.5   7.5
   4.3  21.5 -43.5   3.5
   4.4  26.0 -46.0   6.0 :End of matrix A
   1.0   2.0  -3.0   1.0
   1.0   3.0  -5.0   4.0
   1.0   3.0  -4.0   3.0
   1.0   3.0  -4.0   4.0 :End of matrix B

Result

 DGGES Example Program Results

 Matrix A
             1          2          3          4
 1      3.9000    12.5000   -34.5000    -0.5000
 2      4.3000    21.5000   -47.5000     7.5000
 3      4.3000    21.5000   -43.5000     3.5000
 4      4.4000    26.0000   -46.0000     6.0000

 Matrix B
             1          2          3          4
 1      1.0000     2.0000    -3.0000     1.0000
 2      1.0000     3.0000    -5.0000     4.0000
 3      1.0000     3.0000    -4.0000     3.0000
 4      1.0000     3.0000    -4.0000     4.0000

Warning: Floating underflow occurred
 Number of eigenvalues for which SELCTG is true =    2
 (dimension of deflating subspaces)

 Selected generalized eigenvalues
    1     (  2.000,  0.000)
    2     (  4.000,  0.000)

Source

!   DGGES Example Program Text
!   Copyright 2017, Numerical Algorithms Group Ltd. http://www.nag.com

    Module dgges_mod

!     DGGES Example Program Module:
!            Parameters and User-defined Routines

!     .. Use Statements ..
      Use lapack_precision, Only: dp
!     .. Implicit None Statement ..
      Implicit None
!     .. Accessibility Statements ..
      Private
      Public :: selctg
!     .. Parameters ..
      Integer, Parameter, Public :: nb = 64, nin = 5, nout = 6
    Contains
      Function selctg(ar, ai, b)

!       Logical function selctg for use with DGGES (DGGES)
!       Returns the value .TRUE. if the eigenvalue is real and positive

!       .. Function Return Value ..
        Logical :: selctg
!       .. Scalar Arguments ..
        Real (Kind=dp), Intent (In) :: ai, ar, b
!       .. Executable Statements ..
        selctg = (ar>0._dp .And. ai==0._dp .And. b/=0._dp)
        Return
      End Function
    End Module
    Program dgges_example

!     DGGES Example Main Program

!     .. Use Statements ..
      Use blas_interfaces, Only: dgemm
      Use dgges_mod, Only: nb, nin, nout, selctg
      Use lapack_example_aux, Only: nagf_file_print_matrix_real_gen
      Use lapack_interfaces, Only: dgges, dlange
      Use lapack_precision, Only: dp
!     .. Implicit None Statement ..
      Implicit None
!     .. Local Scalars ..
      Real (Kind=dp) :: alph, bet, normd, norme
      Integer :: i, ifail, info, lda, ldb, ldc, ldd, lde, ldvsl, ldvsr, lwork, &
        n, sdim
!     .. Local Arrays ..
      Real (Kind=dp), Allocatable :: a(:, :), alphai(:), alphar(:), b(:, :), &
        beta(:), c(:, :), d(:, :), e(:, :), vsl(:, :), vsr(:, :), work(:)
      Real (Kind=dp) :: dummy(1)
      Logical, Allocatable :: bwork(:)
!     .. Intrinsic Procedures ..
      Intrinsic :: epsilon, max, nint
!     .. Executable Statements ..
      Write (nout, *) 'DGGES Example Program Results'
      Write (nout, *)
      Flush (nout)
!     Skip heading in data file
      Read (nin, *)
      Read (nin, *) n
      lda = n
      ldb = n
      ldc = n
      ldd = n
      lde = n
      ldvsl = n
      ldvsr = n
      Allocate (a(lda,n), alphai(n), alphar(n), b(ldb,n), beta(n), &
        vsl(ldvsl,n), vsr(ldvsr,n), bwork(n), c(ldc,n), d(ldd,n), e(lde,n))

!     Use routine workspace query to get optimal workspace.
      lwork = -1
      Call dgges('Vectors (left)', 'Vectors (right)', 'Sort', selctg, n, a, &
        lda, b, ldb, sdim, alphar, alphai, beta, vsl, ldvsl, vsr, ldvsr, &
        dummy, lwork, bwork, info)

!     Make sure that there is enough workspace for block size nb.
      lwork = max(8*n+16+n*nb, nint(dummy(1)))
      Allocate (work(lwork))

!     Read in the matrices A and B
      Read (nin, *)(a(i,1:n), i=1, n)
      Read (nin, *)(b(i,1:n), i=1, n)

!     Copy A and B into D and E respectively
      d(1:n, 1:n) = a(1:n, 1:n)
      e(1:n, 1:n) = b(1:n, 1:n)

!     Print matrices A and B
!     ifail: behaviour on error exit
!            =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
      ifail = 0
      Call nagf_file_print_matrix_real_gen('General', ' ', n, n, a, lda, &
        'Matrix A', ifail)
      Write (nout, *)
      Flush (nout)

      ifail = 0
      Call nagf_file_print_matrix_real_gen('General', ' ', n, n, b, ldb, &
        'Matrix B', ifail)
      Write (nout, *)
      Flush (nout)

!     Find the generalized Schur form
      Call dgges('Vectors (left)', 'Vectors (right)', 'Sort', selctg, n, a, &
        lda, b, ldb, sdim, alphar, alphai, beta, vsl, ldvsl, vsr, ldvsr, work, &
        lwork, bwork, info)

      If (info==0 .Or. info==(n+2)) Then

!       Compute A - Q*S*Z^T from the factorization of (A,B) and store in
!       matrix D
        alph = 1.0_dp
        bet = 0.0_dp
        Call dgemm('N', 'N', n, n, n, alph, vsl, ldvsl, a, lda, bet, c, ldc)
        alph = -1.0_dp
        bet = 1.0_dp
        Call dgemm('N', 'T', n, n, n, alph, c, ldc, vsr, ldvsr, bet, d, ldd)

!       Compute B - Q*T*Z^T from the factorization of (A,B) and store in
!       matrix E
        alph = 1.0_dp
        bet = 0.0_dp
        Call dgemm('N', 'N', n, n, n, alph, vsl, ldvsl, b, ldb, bet, c, ldc)
        alph = -1.0_dp
        bet = 1.0_dp
        Call dgemm('N', 'T', n, n, n, alph, c, ldc, vsr, ldvsr, bet, e, lde)

!       Find norms of matrices D and E and warn if either is too large
        normd = dlange('O', ldd, n, d, ldd, work)
        norme = dlange('O', lde, n, e, lde, work)
        If (normd>epsilon(1.0E0_dp)**0.8_dp .Or. norme>epsilon(1.0E0_dp)** &
          0.8_dp) Then
          Write (nout, *) 'Norm of A-(Q*S*Z^T) or norm of B-(Q*T*Z^T) &
            &is much greater than 0.'
          Write (nout, *) 'Schur factorization has failed.'
        Else

!         Print solution
          Write (nout, 100) &
            'Number of eigenvalues for which SELCTG is true = ', sdim, &
            '(dimension of deflating subspaces)'

          Write (nout, *)
!         Print generalized eigenvalues
          Write (nout, *) 'Selected generalized eigenvalues'

          Do i = 1, sdim
            If (beta(i)/=0.0_dp) Then
              Write (nout, 120) i, '(', alphar(i)/beta(i), ',', &
                alphai(i)/beta(i), ')'
            Else
              Write (nout, 130) i
            End If
          End Do
          Write (nout, *)

          If (info==(n+2)) Then
            Write (nout, 140) '***Note that rounding errors mean ', &
              'that leading eigenvalues in the generalized', &
              'Schur form no longer satisfy SELCTG = .TRUE.'
            Write (nout, *)
          End If

        End If

      Else
        Write (nout, 110) 'Failure in DGGES. INFO =', info
      End If

100   Format (1X, A, I4, /, 1X, A)
110   Format (1X, A, I4)
120   Format (1X, I4, 5X, A, F7.3, A, F7.3, A)
130   Format (1X, I4, 'Eigenvalue is infinite')
140   Format (1X, 2A, /, 1X, A)
    End Program
Full documentation of DGGES


DGGES3 example

Real Generalized Nonsymmetric Eigenproblems: Computes, for a real nonsymmetric matrix pair, using BLAS-3, the generalized eigenvalues, the generalized real Schur form and, optionally, the left and/or right matrices of Schur vectors

Data

DGGES3 Example Program Data
   4                     :Value of N
   3.9  12.5 -34.5  -0.5
   4.3  21.5 -47.5   7.5
   4.3  21.5 -43.5   3.5
   4.4  26.0 -46.0   6.0 :End of matrix A
   1.0   2.0  -3.0   1.0
   1.0   3.0  -5.0   4.0
   1.0   3.0  -4.0   3.0
   1.0   3.0  -4.0   4.0 :End of matrix B

Result

 DGGES3 Example Program Results

 Matrix A
             1          2          3          4
 1      3.9000    12.5000   -34.5000    -0.5000
 2      4.3000    21.5000   -47.5000     7.5000
 3      4.3000    21.5000   -43.5000     3.5000
 4      4.4000    26.0000   -46.0000     6.0000

 Matrix B
             1          2          3          4
 1      1.0000     2.0000    -3.0000     1.0000
 2      1.0000     3.0000    -5.0000     4.0000
 3      1.0000     3.0000    -4.0000     3.0000
 4      1.0000     3.0000    -4.0000     4.0000

Warning: Floating underflow occurred
 Number of eigenvalues for which SELCTG is true =    2
 (dimension of deflating subspaces)

 Selected generalized eigenvalues
    1     (  2.000,  0.000)
    2     (  4.000,  0.000)

Source

!   DGGES3 Example Program Text
!   Copyright 2017, Numerical Algorithms Group Ltd. http://www.nag.com

    Module dgges3_mod

!     DGGES3 Example Program Module:
!            Parameters and User-defined Routines

!     .. Use Statements ..
      Use lapack_precision, Only: dp
!     .. Implicit None Statement ..
      Implicit None
!     .. Accessibility Statements ..
      Private
      Public :: selctg
!     .. Parameters ..
      Integer, Parameter, Public :: nb = 64, nin = 5, nout = 6
    Contains
      Function selctg(ar, ai, b)

!       Logical function selctg for use with DGGES3 (DGGES3)
!       Returns the value .TRUE. if the eigenvalue is real and positive

!       .. Function Return Value ..
        Logical :: selctg
!       .. Scalar Arguments ..
        Real (Kind=dp), Intent (In) :: ai, ar, b
!       .. Executable Statements ..
        selctg = (ar>0._dp .And. ai==0._dp .And. b/=0._dp)
        Return
      End Function
    End Module
    Program dgges3_example

!     DGGES3 Example Main Program

!     .. Use Statements ..
      Use blas_interfaces, Only: dgemm
      Use dgges3_mod, Only: nb, nin, nout, selctg
      Use lapack_example_aux, Only: nagf_file_print_matrix_real_gen
      Use lapack_interfaces, Only: dgges3, dlange
      Use lapack_precision, Only: dp
!     .. Implicit None Statement ..
      Implicit None
!     .. Local Scalars ..
      Real (Kind=dp) :: alph, bet, normd, norme
      Integer :: i, ifail, info, lda, ldb, ldc, ldd, lde, ldvsl, ldvsr, lwork, &
        n, sdim
!     .. Local Arrays ..
      Real (Kind=dp), Allocatable :: a(:, :), alphai(:), alphar(:), b(:, :), &
        beta(:), c(:, :), d(:, :), e(:, :), vsl(:, :), vsr(:, :), work(:)
      Real (Kind=dp) :: dummy(1)
      Logical, Allocatable :: bwork(:)
!     .. Intrinsic Procedures ..
      Intrinsic :: epsilon, max, nint
!     .. Executable Statements ..
      Write (nout, *) 'DGGES3 Example Program Results'
      Write (nout, *)
      Flush (nout)
!     Skip heading in data file
      Read (nin, *)
      Read (nin, *) n
      lda = n
      ldb = n
      ldc = n
      ldd = n
      lde = n
      ldvsl = n
      ldvsr = n
      Allocate (a(lda,n), alphai(n), alphar(n), b(ldb,n), beta(n), &
        vsl(ldvsl,n), vsr(ldvsr,n), bwork(n), c(ldc,n), d(ldd,n), e(lde,n))

!     Use routine workspace query to get optimal workspace.
      lwork = -1
      Call dgges3('Vectors (left)', 'Vectors (right)', 'Sort', selctg, n, a, &
        lda, b, ldb, sdim, alphar, alphai, beta, vsl, ldvsl, vsr, ldvsr, &
        dummy, lwork, bwork, info)

!     Make sure that there is enough workspace for block size nb.
      lwork = max(8*n+16+n*nb, nint(dummy(1)))
      Allocate (work(lwork))

!     Read in the matrices A and B
      Read (nin, *)(a(i,1:n), i=1, n)
      Read (nin, *)(b(i,1:n), i=1, n)

!     Copy A and B into D and E respectively
      d(1:n, 1:n) = a(1:n, 1:n)
      e(1:n, 1:n) = b(1:n, 1:n)

!     Print matrices A and B
!     ifail: behaviour on error exit
!            =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
      ifail = 0
      Call nagf_file_print_matrix_real_gen('General', ' ', n, n, a, lda, &
        'Matrix A', ifail)
      Write (nout, *)
      Flush (nout)

      ifail = 0
      Call nagf_file_print_matrix_real_gen('General', ' ', n, n, b, ldb, &
        'Matrix B', ifail)
      Write (nout, *)
      Flush (nout)

!     Find the generalized Schur form
      Call dgges3('Vectors (left)', 'Vectors (right)', 'Sort', selctg, n, a, &
        lda, b, ldb, sdim, alphar, alphai, beta, vsl, ldvsl, vsr, ldvsr, work, &
        lwork, bwork, info)

      If (info==0 .Or. info==(n+2)) Then

!       Compute A - Q*S*Z^T from the factorization of (A,B) and store in
!       matrix D
        alph = 1.0_dp
        bet = 0.0_dp
        Call dgemm('N', 'N', n, n, n, alph, vsl, ldvsl, a, lda, bet, c, ldc)
        alph = -1.0_dp
        bet = 1.0_dp
        Call dgemm('N', 'T', n, n, n, alph, c, ldc, vsr, ldvsr, bet, d, ldd)

!       Compute B - Q*T*Z^T from the factorization of (A,B) and store in
!       matrix E
        alph = 1.0_dp
        bet = 0.0_dp
        Call dgemm('N', 'N', n, n, n, alph, vsl, ldvsl, b, ldb, bet, c, ldc)
        alph = -1.0_dp
        bet = 1.0_dp
        Call dgemm('N', 'T', n, n, n, alph, c, ldc, vsr, ldvsr, bet, e, lde)

!       Find norms of matrices D and E and warn if either is too large
        normd = dlange('O', ldd, n, d, ldd, work)
        norme = dlange('O', lde, n, e, lde, work)
        If (normd>epsilon(1.0E0_dp)**0.8_dp .Or. norme>epsilon(1.0E0_dp)** &
          0.8_dp) Then
          Write (nout, *) 'Norm of A-(Q*S*Z^T) or norm of B-(Q*T*Z^T) &
            &is much greater than 0.'
          Write (nout, *) 'Schur factorization has failed.'
        Else

!         Print solution
          Write (nout, 100) &
            'Number of eigenvalues for which SELCTG is true = ', sdim, &
            '(dimension of deflating subspaces)'

          Write (nout, *)
!         Print generalized eigenvalues
          Write (nout, *) 'Selected generalized eigenvalues'

          Do i = 1, sdim
            If (beta(i)/=0.0_dp) Then
              Write (nout, 120) i, '(', alphar(i)/beta(i), ',', &
                alphai(i)/beta(i), ')'
            Else
              Write (nout, 130) i
            End If
          End Do
          Write (nout, *)

          If (info==(n+2)) Then
            Write (nout, 140) '***Note that rounding errors mean ', &
              'that leading eigenvalues in the generalized', &
              'Schur form no longer satisfy SELCTG = .TRUE.'
            Write (nout, *)
          End If

        End If

      Else
        Write (nout, 110) 'Failure in DGGES3. INFO =', info
      End If

100   Format (1X, A, I4, /, 1X, A)
110   Format (1X, A, I4)
120   Format (1X, I4, 5X, A, F7.3, A, F7.3, A)
130   Format (1X, I4, 'Eigenvalue is infinite')
140   Format (1X, 2A, /, 1X, A)
    End Program
Full documentation of DGGES3


DGGESX example

Real Generalized Nonsymmetric Eigenproblems: For a real nonsymmetric matrix pair, the generalized eigenvalues, the generalized real Schur form and, optionally, the left and/or right matrices of Schur vectors; also, optionally, reciprocal condition numbers for selected eigenvalues

 To find the generalized Schur factorization of the matrix pair $ (A,B)$, where

such that the real eigenvalues of $ (A,B)$ correspond to the top left diagonalelements of the generalized Schur form, $ (S,T)$. Estimates of the conditionnumbers for the selected eigenvalue cluster and corresponding deflatingsubspaces are also returned.

Data

DGGESX Example Program Data
   4                     :Value of N
   3.9  12.5 -34.5  -0.5
   4.3  21.5 -47.5   7.5
   4.3  21.5 -43.5   3.5
   4.4  26.0 -46.0   6.0 :End of matrix A
   1.0   2.0  -3.0   1.0
   1.0   3.0  -5.0   4.0
   1.0   3.0  -4.0   3.0
   1.0   3.0  -4.0   4.0 :End of matrix B

Result

 DGGESX Example Program Results

 Matrix A
             1          2          3          4
 1      3.9000    12.5000   -34.5000    -0.5000
 2      4.3000    21.5000   -47.5000     7.5000
 3      4.3000    21.5000   -43.5000     3.5000
 4      4.4000    26.0000   -46.0000     6.0000

 Matrix B
             1          2          3          4
 1      1.0000     2.0000    -3.0000     1.0000
 2      1.0000     3.0000    -5.0000     4.0000
 3      1.0000     3.0000    -4.0000     3.0000
 4      1.0000     3.0000    -4.0000     4.0000

 Number of eigenvalues for which SELCTG is true =    2
 (dimension of deflating subspaces)

 Selected generalized eigenvalues
    1     (  2.000,  0.000)
    2     (  4.000,  0.000)

 Reciprocals of left and right projection norms onto
 the deflating subspaces for the selected eigenvalues
 RCONDE(1) =  1.9E-01, RCONDE(2) =  1.8E-02

 Reciprocal condition numbers for the left and right
 deflating subspaces
 RCONDV(1) =  5.4E-02, RCONDV(2) =  9.0E-02
Warning: Floating underflow occurred

 Approximate asymptotic error bound for selected eigenvalues    =  1.1E-13
 Approximate asymptotic error bound for the deflating subspaces =  2.4E-13

Source

!   DGGESX Example Program Text
!   Copyright 2017, Numerical Algorithms Group Ltd. http://www.nag.com

    Module dggesx_mod

!     DGGESX Example Program Module:
!            Parameters and User-defined Routines

!     .. Use Statements ..
      Use lapack_precision, Only: dp
!     .. Implicit None Statement ..
      Implicit None
!     .. Accessibility Statements ..
      Private
      Public :: selctg
!     .. Parameters ..
      Integer, Parameter, Public :: nb = 64, nin = 5, nout = 6
    Contains
      Function selctg(ar, ai, b)

!       Logical function selctg for use with DGGESX (DGGESX)
!       Returns the value .TRUE. if the eigenvalue is real and positive

!       .. Function Return Value ..
        Logical :: selctg
!       .. Scalar Arguments ..
        Real (Kind=dp), Intent (In) :: ai, ar, b
!       .. Executable Statements ..
        selctg = (ar>0._dp .And. ai==0._dp .And. b/=0._dp)
        Return
      End Function
    End Module
    Program dggesx_example

!     DGGESX Example Main Program

!     .. Use Statements ..
      Use blas_interfaces, Only: dgemm
      Use dggesx_mod, Only: nb, nin, nout, selctg
      Use lapack_example_aux, Only: nagf_blas_dpyth, &
        nagf_file_print_matrix_real_gen
      Use lapack_interfaces, Only: dggesx, dlange
      Use lapack_precision, Only: dp
!     .. Implicit None Statement ..
      Implicit None
!     .. Local Scalars ..
      Real (Kind=dp) :: abnorm, alph, anorm, bet, bnorm, eps, normd, norme, &
        tol
      Integer :: i, ifail, info, lda, ldb, ldc, ldd, lde, ldvsl, ldvsr, &
        liwork, lwork, n, sdim
!     .. Local Arrays ..
      Real (Kind=dp), Allocatable :: a(:, :), alphai(:), alphar(:), b(:, :), &
        beta(:), c(:, :), d(:, :), e(:, :), vsl(:, :), vsr(:, :), work(:)
      Real (Kind=dp) :: rconde(2), rcondv(2), rdum(1)
      Integer :: idum(1)
      Integer, Allocatable :: iwork(:)
      Logical, Allocatable :: bwork(:)
!     .. Intrinsic Procedures ..
      Intrinsic :: epsilon, max, nint
!     .. Executable Statements ..
      Write (nout, *) 'DGGESX Example Program Results'
      Write (nout, *)
      Flush (nout)
!     Skip heading in data file
      Read (nin, *)
      Read (nin, *) n
      lda = n
      ldb = n
      ldc = n
      ldd = n
      lde = n
      ldvsl = n
      ldvsr = n
      Allocate (a(lda,n), alphai(n), alphar(n), b(ldb,n), beta(n), &
        vsl(ldvsl,n), vsr(ldvsr,n), bwork(n), c(ldc,n), d(ldd,n), e(lde,n))

!     Use routine workspace query to get optimal workspace.
      lwork = -1
      liwork = -1
      Call dggesx('Vectors (left)', 'Vectors (right)', 'Sort', selctg, &
        'Both reciprocal condition numbers', n, a, lda, b, ldb, sdim, alphar, &
        alphai, beta, vsl, ldvsl, vsr, ldvsr, rconde, rcondv, rdum, lwork, &
        idum, liwork, bwork, info)

!     Make sure that there is enough workspace for block size nb.
      lwork = max(8*(n+1)+16+n*nb+n*n/2, nint(rdum(1)))
      liwork = max(n+6, idum(1))
      Allocate (work(lwork), iwork(liwork))

!     Read in the matrices A and B
      Read (nin, *)(a(i,1:n), i=1, n)
      Read (nin, *)(b(i,1:n), i=1, n)

!     Copy A and B into D and E respectively
      d(1:n, 1:n) = a(1:n, 1:n)
      e(1:n, 1:n) = b(1:n, 1:n)

!     Print matrices A and B
!     ifail: behaviour on error exit
!            =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
      ifail = 0
      Call nagf_file_print_matrix_real_gen('General', ' ', n, n, a, lda, &
        'Matrix A', ifail)
      Write (nout, *)
      Flush (nout)

      ifail = 0
      Call nagf_file_print_matrix_real_gen('General', ' ', n, n, b, ldb, &
        'Matrix B', ifail)
      Write (nout, *)
      Flush (nout)

!     Find the Frobenius norms of A and B
      anorm = dlange('Frobenius', n, n, a, lda, work)
      bnorm = dlange('Frobenius', n, n, b, ldb, work)

!     Find the generalized Schur form
      Call dggesx('Vectors (left)', 'Vectors (right)', 'Sort', selctg, &
        'Both reciprocal condition numbers', n, a, lda, b, ldb, sdim, alphar, &
        alphai, beta, vsl, ldvsl, vsr, ldvsr, rconde, rcondv, work, lwork, &
        iwork, liwork, bwork, info)

      If (info==0 .Or. info==(n+2)) Then

!       Compute A - Q*S*Z^T from the factorization of (A,B) and store in
!       matrix D
        alph = 1.0_dp
        bet = 0.0_dp
        Call dgemm('N', 'N', n, n, n, alph, vsl, ldvsl, a, lda, bet, c, ldc)
        alph = -1.0_dp
        bet = 1.0_dp
        Call dgemm('N', 'T', n, n, n, alph, c, ldc, vsr, ldvsr, bet, d, ldd)

!       Compute B - Q*T*Z^T from the factorization of (A,B) and store in
!       matrix E
        alph = 1.0_dp
        bet = 0.0_dp
        Call dgemm('N', 'N', n, n, n, alph, vsl, ldvsl, b, ldb, bet, c, ldc)
        alph = -1.0_dp
        bet = 1.0_dp
        Call dgemm('N', 'T', n, n, n, alph, c, ldc, vsr, ldvsr, bet, e, lde)

!       Find norms of matrices D and E and warn if either is too large
        normd = dlange('O', ldd, n, d, ldd, work)
        norme = dlange('O', lde, n, e, lde, work)
        If (normd>epsilon(1.0E0_dp)**0.8_dp .Or. norme>epsilon(1.0E0_dp)** &
          0.8_dp) Then
          Write (nout, *) 'Norm of A-(Q*S*Z^T) or norm of B-(Q*T*Z^T) &
            &is much greater than 0.'
          Write (nout, *) 'Schur factorization has failed.'
        Else

!         Print solution
          Write (nout, 100) &
            'Number of eigenvalues for which SELCTG is true = ', sdim, &
            '(dimension of deflating subspaces)'

          Write (nout, *)
!         Print generalized eigenvalues
          Write (nout, *) 'Selected generalized eigenvalues'

          Do i = 1, sdim
            If (beta(i)/=0.0_dp) Then
              Write (nout, 110) i, '(', alphar(i)/beta(i), ',', &
                alphai(i)/beta(i), ')'
            Else
              Write (nout, 120) i
            End If
          End Do

          If (info==(n+2)) Then
            Write (nout, 130) '***Note that rounding errors mean ', &
              'that leading eigenvalues in the generalized', &
              'Schur form no longer satisfy SELCTG = .TRUE.'
            Write (nout, *)
          End If
          Flush (nout)

!         Print out the reciprocal condition numbers
          Write (nout, *)
          Write (nout, 140) &
            'Reciprocals of left and right projection norms onto', &
            'the deflating subspaces for the selected eigenvalues', &
            'RCONDE(1) = ', rconde(1), ', RCONDE(2) = ', rconde(2)
          Write (nout, *)
          Write (nout, 140) &
            'Reciprocal condition numbers for the left and right', &
            'deflating subspaces', 'RCONDV(1) = ', rcondv(1), &
            ', RCONDV(2) = ', rcondv(2)
          Flush (nout)

!         Compute the machine precision and sqrt(anorm**2+bnorm**2)
          eps = epsilon(1.0E0_dp)
          abnorm = nagf_blas_dpyth(anorm, bnorm)
          tol = eps*abnorm

!         Print out the approximate asymptotic error bound on the
!         average absolute error of the selected eigenvalues given by
!         eps*norm((A, B))/PL,   where PL = RCONDE(1)
          Write (nout, *)
          Write (nout, 150) 'Approximate asymptotic error bound for selected ' &
            , 'eigenvalues    = ', tol/rconde(1)

!         Print out an approximate asymptotic bound on the maximum
!         angular error in the computed deflating subspaces given by
!         eps*norm((A, B))/DIF(2),   where DIF(2) = RCONDV(2)
          Write (nout, 150) &
            'Approximate asymptotic error bound for the deflating ', &
            'subspaces = ', tol/rcondv(2)

        End If

      Else
        Write (nout, 100) 'Failure in DGGESX. INFO =', info
      End If

100   Format (1X, A, I4, /, 1X, A)
110   Format (1X, I4, 5X, A, F7.3, A, F7.3, A)
120   Format (1X, I4, 'Eigenvalue is infinite')
130   Format (1X, 2A, /, 1X, A)
140   Format (1X, A, /, 1X, A, /, 1X, 2(A,1P,E8.1))
150   Format (1X, 2A, 1P, E8.1)
    End Program
Full documentation of DGGESX


DGGEV example

Real Generalized Nonsymmetric Eigenproblems: For a real nonsymmetric matrix pair, the generalized eigenvalues, and optionally, the left and/or right generalized eigenvectors

 To find all the eigenvalues and right eigenvectors of the matrix pair $ (A,B)$,where

Data

DGGEV Example Program Data
   4                     :Value of N
   3.9  12.5 -34.5  -0.5
   4.3  21.5 -47.5   7.5
   4.3  21.5 -43.5   3.5
   4.4  26.0 -46.0   6.0 :End of matrix A
   1.0   2.0  -3.0   1.0
   1.0   3.0  -5.0   4.0
   1.0   3.0  -4.0   3.0
   1.0   3.0  -4.0   4.0 :End of matrix B

Result

Warning: Floating underflow occurred
 DGGEV Example Program Results

 Eigenvalue( 1) =      20.000

 Eigenvector( 1)
    10.00000
     0.05714
     0.62857
     0.62857

 Eigenvalue( 2) = (     30.000,    -40.000)

 Eigenvector( 2)
 (    7.12215,    0.00000)
 (    1.42443,   -0.00000)
 (    0.85466,    1.13954)
 (    0.85466,    1.13954)

 Eigenvalue( 3) = (     30.000,     40.000)

 Eigenvector( 3)
 (    7.12215,   -0.00000)
 (    1.42443,    0.00000)
 (    0.85466,   -1.13954)
 (    0.85466,   -1.13954)

 Eigenvalue( 4) =      40.000

 Eigenvector( 4)
    10.00000
     0.11111
    -0.33333
     1.55556

Source

    Program dggev_example

!     DGGEV Example Program Text

!     Copyright 2017, Numerical Algorithms Group Ltd. http://www.nag.com

!     .. Use Statements ..
      Use lapack_example_aux, Only: nagf_sort_realmat_rank_rows, &
        nagf_sort_realvec_rank_rearrange
      Use lapack_interfaces, Only: dggev
      Use lapack_precision, Only: dp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Real (Kind=dp), Parameter :: zero = 0.0_dp
      Integer, Parameter :: nb = 64, nin = 5, nout = 6
!     .. Local Scalars ..
      Complex (Kind=dp) :: eig
      Real (Kind=dp) :: scal_i, scal_r, small
      Integer :: i, ifail, info, j, k, lda, ldb, ldvr, lwork, n
      Logical :: pair
!     .. Local Arrays ..
      Real (Kind=dp), Allocatable :: a(:, :), alphai(:), alphar(:), b(:, :), &
        beta(:), vr(:, :), vr_row(:), work(:)
      Real (Kind=dp) :: dummy(1, 1)
      Integer, Allocatable :: irank(:)
!     .. Intrinsic Procedures ..
      Intrinsic :: abs, all, cmplx, epsilon, max, maxloc, nint, sqrt, tiny
!     .. Executable Statements ..
      Write (nout, *) 'DGGEV Example Program Results'
!     Skip heading in data file
      Read (nin, *)
      Read (nin, *) n
      lda = n
      ldb = n
      ldvr = n
      Allocate (a(lda,n), alphai(n), alphar(n), b(ldb,n), beta(n), vr(ldvr,n), &
        irank(n))

!     Use routine workspace query to get optimal workspace.
      lwork = -1
      Call dggev('No left vectors', 'Vectors (right)', n, a, lda, b, ldb, &
        alphar, alphai, beta, dummy, 1, vr, ldvr, dummy, lwork, info)

!     Make sure that there is enough workspace for block size nb.
      lwork = max((nb+7)*n, nint(dummy(1,1)))
      Allocate (work(lwork))

!     Read in the matrices A and B

      Read (nin, *)(a(i,1:n), i=1, n)
      Read (nin, *)(b(i,1:n), i=1, n)

!     Solve the generalized eigenvalue problem

      Call dggev('No left vectors', 'Vectors (right)', n, a, lda, b, ldb, &
        alphar, alphai, beta, dummy, 1, vr, ldvr, work, lwork, info)

      If (info>0) Then
        Write (nout, *)
        Write (nout, 100) 'Failure in DGGEV. INFO =', info
      Else
!       If beta(:) > eps, Order eigenvalues by ascending real parts
!       and then by ascending imaginary parts
        If (all(abs(beta(1:n))>epsilon(1.0E0_dp))) Then
          work(1:n) = alphar(1:n)/beta(1:n)
          work(n+1:2*n) = alphai(1:n)/beta(1:n)
          ifail = 0
          Call nagf_sort_realmat_rank_rows(work, n, 1, n, 1, 2, 'Ascending', &
            irank, ifail)
          Call nagf_sort_realvec_rank_rearrange(alphar, 1, n, irank, ifail)
          Call nagf_sort_realvec_rank_rearrange(alphai, 1, n, irank, ifail)
          Call nagf_sort_realvec_rank_rearrange(beta, 1, n, irank, ifail)
!         Order the eigenvectors in the same way
          Allocate (vr_row(n))
          Do j = 1, n
            vr_row(1:n) = vr(j, 1:n)
            Call nagf_sort_realvec_rank_rearrange(vr_row, 1, n, irank, ifail)
            vr(j, 1:n) = vr_row(1:n)
          End Do
          Deallocate (vr_row)
        End If
        small = tiny(1.0E0_dp)
        pair = .False.
        Do j = 1, n
          Write (nout, *)
          If ((abs(alphar(j))+abs(alphai(j)))*small>=abs(beta(j))) Then
            Write (nout, 110) 'Eigenvalue(', j, ')', &
              ' is numerically infinite or undetermined', 'ALPHAR(', j, &
              ') = ', alphar(j), ', ALPHAI(', j, ') = ', alphai(j), ', BETA(', &
              j, ') = ', beta(j)
          Else
            If (alphai(j)==zero) Then
              Write (nout, 120) 'Eigenvalue(', j, ') = ', alphar(j)/beta(j)
            Else
              eig = cmplx(alphar(j), alphai(j), kind=dp)/ &
                cmplx(beta(j), kind=dp)
              Write (nout, 130) 'Eigenvalue(', j, ') = ', eig
            End If
          End If
          Write (nout, *)
          Write (nout, 140) 'Eigenvector(', j, ')'
          If (alphai(j)==zero) Then
!           Let largest element be positive
            work(1:n) = abs(vr(1:n,j))
            k = maxloc(work(1:n), 1)
            If (vr(k,j)<zero) Then
              vr(1:n, j) = -vr(1:n, j)
            End If
            Write (nout, 150)(vr(i,j), i=1, n)
          Else
            If (pair) Then
              Write (nout, 160)(vr(i,j-1), -vr(i,j), i=1, n)
            Else
!             Let largest element be real (and positive).
              work(1:n) = vr(1:n, j)**2 + vr(1:n, j+1)**2
              k = maxloc(work(1:n), 1)
              scal_r = vr(k, j)/sqrt(work(k))
              scal_i = -vr(k, j+1)/sqrt(work(k))
              work(1:n) = vr(1:n, j)
              vr(1:n, j) = scal_r*work(1:n) - scal_i*vr(1:n, j+1)
              vr(1:n, j+1) = scal_r*vr(1:n, j+1) + scal_i*work(1:n)
              Write (nout, 160)(vr(i,j), vr(i,j+1), i=1, n)
            End If
            pair = .Not. pair
          End If
        End Do

      End If

100   Format (1X, A, I4)
110   Format (1X, A, I2, 2A, /, 1X, 2(A,I2,A,1P,F11.3,3X), A, I2, A, 1P, &
        F11.3)
120   Format (1X, A, I2, A, 1P, F11.3)
130   Format (1X, A, I2, A, '(', 1P, F11.3, ',', 1P, F11.3, ')')
140   Format (1X, A, I2, A)
150   Format (1X, 1P, F11.5)
160   Format (1X, '(', 1P, F11.5, ',', 1P, F11.5, ')')
    End Program
Full documentation of DGGEV


DGGEV3 example

Real Generalized Nonsymmetric Eigenproblems: Computes, for a real nonsymmetric matrix pair, using BLAS-3, the generalized eigenvalues, and optionally, the left and/or right generalized eigenvectors

Data

DGGEV3 Example Program Data
   4                     :Value of N
   3.9  12.5 -34.5  -0.5
   4.3  21.5 -47.5   7.5
   4.3  21.5 -43.5   3.5
   4.4  26.0 -46.0   6.0 :End of matrix A
   1.0   2.0  -3.0   1.0
   1.0   3.0  -5.0   4.0
   1.0   3.0  -4.0   3.0
   1.0   3.0  -4.0   4.0 :End of matrix B

Result

 DGGEV3 Example Program Results
 Eigenvalues:
             1          2          3          4
 1      3.0000     3.0000     4.0000     2.0000
        4.0000    -4.0000     0.0000     0.0000

Warning: Floating underflow occurred
 Right Eigenvectors (columns):
          1       2       3       4
 1   0.7122  0.7122  1.0000  1.0000
     0.0000  0.0000  0.0000  0.0000

 2   0.1424  0.1424  0.0111  0.0057
     0.0000 -0.0000  0.0000  0.0000

 3   0.0855  0.0855 -0.0333  0.0629
    -0.1140  0.1140 -0.0000  0.0000

 4   0.0855  0.0855  0.1556  0.0629
    -0.1140  0.1140  0.0000  0.0000

Source

    Program dggev3_example

!     DGGEV3 Example Program Text

!     Copyright 2017, Numerical Algorithms Group Ltd. http://www.nag.com

!     .. Use Statements ..
      Use lapack_example_aux, Only: nagf_sort_cmplxvec_rank_rearrange, &
        nagf_sort_realmat_rank_rows, nagf_file_print_matrix_complex_gen, &
        nagf_file_print_matrix_real_gen
      Use lapack_interfaces, Only: dggev3
      Use lapack_precision, Only: dp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Real (Kind=dp), Parameter :: zero = 0.0_dp
      Integer, Parameter :: nin = 5, nout = 6
!     .. Local Scalars ..
      Complex (Kind=dp) :: scal
      Integer :: i, ifail, info, j, k, lda, ldb, ldvr, lwork, n
!     .. Local Arrays ..
      Complex (Kind=dp), Allocatable :: eigval(:), eigvec(:, :)
      Real (Kind=dp), Allocatable :: a(:, :), alphai(:), alphar(:), b(:, :), &
        beta(:), vr(:, :), work(:)
      Real (Kind=dp) :: dummy(1, 1)
      Integer, Allocatable :: irank(:)
!     .. Intrinsic Procedures ..
      Intrinsic :: abs, all, cmplx, conjg, epsilon, maxloc, nint
!     .. Executable Statements ..
      Write (nout, *) 'DGGEV3 Example Program Results'
      Flush (nout)
!     Skip heading in data file
      Read (nin, *)
      Read (nin, *) n
      lda = n
      ldb = n
      ldvr = n
      Allocate (a(lda,n), alphai(n), alphar(n), b(ldb,n), beta(n), vr(ldvr,n), &
        eigvec(n,n), eigval(n), irank(n))

!     Use routine workspace query to get optimal workspace.
      lwork = -1
      Call dggev3('No left vectors', 'Vectors (right)', n, a, lda, b, ldb, &
        alphar, alphai, beta, dummy, 1, vr, ldvr, dummy, lwork, info)

      lwork = nint(dummy(1,1))
      Allocate (work(lwork))

!     Read in the matrices A and B

      Read (nin, *)(a(i,1:n), i=1, n)
      Read (nin, *)(b(i,1:n), i=1, n)

!     Solve the generalized eigenvalue problem

      Call dggev3('No left vectors', 'Vectors (right)', n, a, lda, b, ldb, &
        alphar, alphai, beta, dummy, 1, vr, ldvr, work, lwork, info)
      If (info>0) Then
        Write (nout, *)
        Write (nout, 110) 'Failure in DGGEV3. INFO =', info
        Go To 100
      End If

!     Re-normalize the eigenvectors, largest absolute element real
      j = 0
      Do i = 1, n
        If (alphai(i)==zero) Then
          eigvec(1:n, i) = cmplx(vr(1:n,i), zero, kind=dp)
        Else If (j==0) Then
          eigvec(1:n, i) = cmplx(vr(1:n,i), vr(1:n,i+1), kind=dp)
          j = 1
        Else
          eigvec(1:n, i) = cmplx(vr(1:n,i-1), -vr(1:n,i), kind=dp)
          j = 0
        End If
        work(1:n) = abs(eigvec(1:n,i))
        k = maxloc(work(1:n), 1)
        scal = conjg(eigvec(k,i))/abs(eigvec(k,i))
        eigvec(1:n, i) = eigvec(1:n, i)*scal
      End Do

!     If eigenvalues are finite, order by descending absolute values
      If (all(abs(beta(1:n))>epsilon(1.0E0_dp))) Then
!       add small amount to alphai to distinguish conjugates
        alphai(1:n) = alphai(1:n) + epsilon(1.0E0_dp)*10.0_dp
        eigval(1:n) = cmplx(alphar(1:n), alphai(1:n), kind=dp)
        eigval(1:n) = eigval(1:n)/beta(1:n)
        work(1:n) = abs(eigval(1:n))
        ifail = 0
        Call nagf_sort_realmat_rank_rows(work, n, 1, n, 1, 1, 'Descending', &
          irank, ifail)
        Call nagf_sort_cmplxvec_rank_rearrange(eigval, 1, n, irank, ifail)

!       Print ordered eigenvalues
        ifail = 0
        Call nagf_file_print_matrix_complex_gen('Gen', ' ', 1, n, eigval, 1, &
          'Eigenvalues:', ifail)

!       Order the eigenvectors in the same way and print
        Do j = 1, n
          eigval(1:n) = eigvec(j, 1:n)
          Call nagf_sort_cmplxvec_rank_rearrange(eigval, 1, n, irank, ifail)
          eigvec(j, 1:n) = eigval(1:n)
        End Do

        Write (nout, *)
        Flush (nout)
        ifail = 0
        Call nagf_file_print_matrix_complex_gen('Gen', ' ', n, n, eigvec, n, &
          'Right Eigenvectors (columns):', ifail)
      Else
        Write (nout, *) 'Some of the eigenvalues are infinite'
        Write (nout, *)
        Flush (nout)
        ifail = 0
        Call nagf_file_print_matrix_real_gen('Gen', ' ', 1, n, alphar, 1, &
          'Alpha (real):', ifail)
        Call nagf_file_print_matrix_real_gen('Gen', ' ', 1, n, alphai, 1, &
          'Alpha (imag):', ifail)
        Call nagf_file_print_matrix_real_gen('Gen', ' ', 1, n, beta, 1, &
          'Beta:', ifail)
      End If
100   Continue

110   Format (1X, A, I4)
    End Program
Full documentation of DGGEV3


DGGEVX example

Real Generalized Nonsymmetric Eigenproblems: For a real nonsymmetric matrix pair, the generalized eigenvalues, and optionally, the left and/or right generalized eigenvectors; also, optionally, the balancing transformation, the reciprocal condition numbers for the eigenvalues and for the right eigenvectors

 To find all the eigenvalues and right eigenvectors of the matrix pair $ (A,B)$,where

together with estimates of the condition number and forward error bounds foreach eigenvalue and eigenvector. The option to balance the matrix pair is used.

Data

DGGEVX Example Program Data
   4                     :Value of N
   3.9  12.5 -34.5  -0.5
   4.3  21.5 -47.5   7.5
   4.3  21.5 -43.5   3.5
   4.4  26.0 -46.0   6.0 :End of matrix A
   1.0   2.0  -3.0   1.0
   1.0   3.0  -5.0   4.0
   1.0   3.0  -4.0   3.0
   1.0   3.0  -4.0   4.0 :End of matrix B

Result

Warning: Floating underflow occurred
 DGGEVX Example Program Results

 Eigenvalue( 1) =     2.00000

 Eigenvector( 1)
     0.99606
     0.00569
     0.06261
     0.06261

 Eigenvalue( 2) = (    3.00000,   -4.00000)

 Eigenvector( 2)
 (    0.94491,   -0.00000)
 (    0.18898,    0.00000)
 (    0.11339,    0.15119)
 (    0.11339,    0.15119)

 Eigenvalue( 3) = (    3.00000,    4.00000)

 Eigenvector( 3)
 (    0.94491,    0.00000)
 (    0.18898,   -0.00000)
 (    0.11339,   -0.15119)
 (    0.11339,   -0.15119)

 Eigenvalue( 4) =     4.00000

 Eigenvector( 4)
     0.98752
     0.01097
    -0.03292
     0.15361

Source

    Program dggevx_example

!     DGGEVX Example Program Text

!     Copyright 2017, Numerical Algorithms Group Ltd. http://www.nag.com

!     .. Use Statements ..
      Use blas_interfaces, Only: dnrm2
      Use lapack_example_aux, Only: nagf_sort_realvec_rank, &
        nagf_sort_realvec_rank_rearrange
      Use lapack_interfaces, Only: dggevx
      Use lapack_precision, Only: dp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter :: nb = 64, nin = 5, nout = 6
      Logical, Parameter :: verbose = .False.
!     .. Local Scalars ..
      Complex (Kind=dp) :: eig
      Real (Kind=dp) :: abnrm, bbnrm, eps, jswap, rcnd, scal_i, scal_r, small
      Integer :: i, ifail, ihi, ilo, info, j, k, lda, ldb, ldvr, lwork, n
      Logical :: pair
!     .. Local Arrays ..
      Real (Kind=dp), Allocatable :: a(:, :), alphai(:), alphar(:), b(:, :), &
        beta(:), lscale(:), rconde(:), rcondv(:), rscale(:), vr(:, :), &
        vr_row(:), work(:)
      Real (Kind=dp) :: dummy(1, 1)
      Integer, Allocatable :: iwork(:)
      Logical, Allocatable :: bwork(:)
!     .. Intrinsic Procedures ..
      Intrinsic :: abs, all, cmplx, epsilon, max, maxloc, nint, sqrt, sum, &
        tiny
!     .. Executable Statements ..
      Write (nout, *) 'DGGEVX Example Program Results'
!     Skip heading in data file
      Read (nin, *)
      Read (nin, *) n
      lda = n
      ldb = n
      ldvr = n
      Allocate (a(lda,n), alphai(n), alphar(n), b(ldb,n), beta(n), lscale(n), &
        rconde(n), rcondv(n), rscale(n), vr(ldvr,n), iwork(n+6), bwork(n))

!     Use routine workspace query to get optimal workspace.
      lwork = -1
      Call dggevx('Balance', 'No vectors (left)', 'Vectors (right)', &
        'Both reciprocal condition numbers', n, a, lda, b, ldb, alphar, &
        alphai, beta, dummy, 1, vr, ldvr, ilo, ihi, lscale, rscale, abnrm, &
        bbnrm, rconde, rcondv, dummy, lwork, iwork, bwork, info)

!     Make sure that there is enough workspace for block size nb.
      lwork = max((nb+2*n)*n, nint(dummy(1,1)))
      Allocate (work(lwork))

!     Read in the matrices A and B

      Read (nin, *)(a(i,1:n), i=1, n)
      Read (nin, *)(b(i,1:n), i=1, n)

!     Solve the generalized eigenvalue problem

      Call dggevx('Balance', 'No vectors (left)', 'Vectors (right)', &
        'Both reciprocal condition numbers', n, a, lda, b, ldb, alphar, &
        alphai, beta, dummy, 1, vr, ldvr, ilo, ihi, lscale, rscale, abnrm, &
        bbnrm, rconde, rcondv, work, lwork, iwork, bwork, info)

      If (info>0) Then
        Write (nout, *)
        Write (nout, 100) 'Failure in DGGEVX. INFO =', info
      Else

!       Compute the machine precision and the safe range parameter
!       small

        eps = epsilon(1.0E0_dp)
        small = tiny(1.0E0_dp)

!       If beta(:) > eps, Order eigenvalues by ascending real parts
        If (all(abs(beta(1:n))>eps)) Then
          work(1:n) = alphar(1:n)/beta(1:n)
          ifail = 0
          Call nagf_sort_realvec_rank(work, 1, n, 'Ascending', iwork, ifail)
          Call nagf_sort_realvec_rank_rearrange(alphar, 1, n, iwork, ifail)
          Call nagf_sort_realvec_rank_rearrange(alphai, 1, n, iwork, ifail)
          Call nagf_sort_realvec_rank_rearrange(beta, 1, n, iwork, ifail)
!         Order the eigenvectors in the same way
          Allocate (vr_row(n))
          Do j = 1, n
            vr_row(1:n) = vr(j, 1:n)
            Call nagf_sort_realvec_rank_rearrange(vr_row, 1, n, iwork, ifail)
            vr(j, 1:n) = vr_row(1:n)
          End Do
          Deallocate (vr_row)
        End If

!       Print out eigenvalues and vectors and associated condition
!       number and bounds

        pair = .False.
        Do j = 1, n

!         Print out information on the j-th eigenvalue

          Write (nout, *)
          If ((abs(alphar(j))+abs(alphai(j)))*small>=abs(beta(j))) Then
            Write (nout, 110) 'Eigenvalue(', j, ')', &
              ' is numerically infinite or undetermined', 'ALPHAR(', j, &
              ') = ', alphar(j), ', ALPHAI(', j, ') = ', alphai(j), ', BETA(', &
              j, ') = ', beta(j)
          Else
            If (.Not. pair) Then
              jswap = 1.0_dp
              If (alphai(j)>0.0_dp) Then
                jswap = -jswap
              End If
            End If
            If (alphai(j)==0.0E0_dp) Then
              Write (nout, 120) 'Eigenvalue(', j, ') = ', alphar(j)/beta(j)
            Else
              eig = cmplx(alphar(j), jswap*alphai(j), kind=dp)/ &
                cmplx(beta(j), kind=dp)
              Write (nout, 130) 'Eigenvalue(', j, ') = ', eig
            End If
          End If

          If (verbose) Then
            rcnd = rconde(j)
            Write (nout, *)
            Write (nout, 140) '  Reciprocal condition number = ', rcnd
          End If

!         Print out information on the j-th eigenvector

          Write (nout, *)
          Write (nout, 150) 'Eigenvector(', j, ')'
          If (alphai(j)==0.0E0_dp) Then
!           Let largest element be positive
            work(1:n) = abs(vr(1:n,j))
            k = maxloc(work(1:n), 1)
            If (vr(k,j)<0.0_dp) Then
              vr(1:n, j) = -vr(1:n, j)/dnrm2(n, vr(1,j), 1)
            End If
            Write (nout, 160)(vr(i,j), i=1, n)
          Else
            If (pair) Then
              Write (nout, 170)(vr(i,j-1), -jswap*vr(i,j), i=1, n)
            Else
!             Let largest element be real (and positive).
              work(1:n) = vr(1:n, j)**2 + vr(1:n, j+1)**2
              k = maxloc(work(1:n), 1)
              scal_r = vr(k, j)/sqrt(work(k))/sqrt(sum(work(1:n)))
              scal_i = -vr(k, j+1)/sqrt(work(k))/sqrt(sum(work(1:n)))
              work(1:n) = vr(1:n, j)
              vr(1:n, j) = scal_r*work(1:n) - scal_i*vr(1:n, j+1)
              vr(1:n, j+1) = scal_r*vr(1:n, j+1) + scal_i*work(1:n)
              vr(k, j+1) = 0.0_dp
              Write (nout, 170)(vr(i,j), jswap*vr(i,j+1), i=1, n)
            End If
            pair = .Not. pair
          End If
          If (verbose) Then
            rcnd = rcondv(j)
            Write (nout, *)
            Write (nout, 140) '  Reciprocal condition number = ', rcnd
          End If
        End Do

      End If

100   Format (1X, A, I4)
110   Format (/, 1X, A, I2, 2A, /, 1X, 2(A,I2,A,F11.5), A, I2, A, F11.5)
120   Format (/, 1X, A, I2, A, F11.5)
130   Format (/, 1X, A, I2, A, '(', F11.5, ',', F11.5, ')')
140   Format (1X, A, 1P, E8.1)
150   Format (1X, A, I2, A)
160   Format (1X, F11.5)
170   Format (1X, '(', F11.5, ',', F11.5, ')')
    End Program
Full documentation of DGGEVX


LAPACK:Complex Generalized Nonsymmetric Eigenproblems

Next: Real Singular Value Decomposition Up: LAPACK Routines by Subject Previous: Real Generalized Nonsymmetric Eigenproblems

Complex Generalized Nonsymmetric Eigenproblems

  • ZGGES : For a complex nonsymmetric matrix pair, the generalized eigenvalues, the generalized complex Schur form and, optionally, the left and/or right matrices of Schur vectors
  • ZGGES3 : Computes, for a complex nonsymmetric matrix pair, using BLAS-3, the generalized eigenvalues, the generalized complex Schur form and, optionally, the left and/or right matrices of Schur vectors
  • ZGGESX : For a complex nonsymmetric matrix pair, the generalized eigenvalues, the generalized complex Schur form and, optionally, the left and/or right matrices of Schur vectors; also, optionally, reciprocal condition numbers for selected eigenvalues
  • ZGGEV : For a complex nonsymmetric matrix pair, the generalized eigenvalues, and optionally, the left and/or right generalized eigenvectors
  • ZGGEV3 : Computes, for a complex nonsymmetric matrix pair, using BLAS-3, the generalized eigenvalues, and optionally, the left and/or right generalized eigenvectors
  • ZGGEVX : For a complex nonsymmetric matrix pair, the generalized eigenvalues, and optionally, the left and/or right generalized eigenvectors; also, optionally, the balancing transformation, the reciprocal condition numbers for the eigenvalues and for the right eigenvectors


ZGGES example

Complex Generalized Nonsymmetric Eigenproblems: For a complex nonsymmetric matrix pair, the generalized eigenvalues, the generalized complex Schur form and, optionally, the left and/or right matrices of Schur vectors

 To find the generalized Schur factorization of the matrix pair $ (A,B)$, where

and

Data

ZGGES Example Program Data
  4                                                               : Value of N
  (-21.10,-22.50) ( 53.50,-50.50) (-34.50,127.50) (  7.50,  0.50)
  ( -0.46, -7.78) ( -3.50,-37.50) (-15.50, 58.50) (-10.50, -1.50)
  (  4.30, -5.50) ( 39.70,-17.10) (-68.50, 12.50) ( -7.50, -3.50)
  (  5.50,  4.40) ( 14.40, 43.30) (-32.50,-46.00) (-19.00,-32.50) : End of A
  (  1.00, -5.00) (  1.60,  1.20) ( -3.00,  0.00) (  0.00, -1.00)
  (  0.80, -0.60) (  3.00, -5.00) ( -4.00,  3.00) ( -2.40, -3.20)
  (  1.00,  0.00) (  2.40,  1.80) ( -4.00, -5.00) (  0.00, -3.00)
  (  0.00,  1.00) ( -1.80,  2.40) (  0.00, -4.00) (  4.00, -5.00) : End of B

Result

 ZGGES Example Program Results

 Generalized Eigenvalues
  1   (  3.00, -9.00)
  2   (  4.00, -5.00)
  3   (  2.00, -5.00)
  4   (  3.00, -1.00)

Source

    Module zgges_mod

!     ZGGES Example Program Module:

!     .. Implicit None Statement ..
      Implicit None
!     .. Accessibility Statements ..
      Private
      Public :: selctg
    Contains
      Function selctg(a, b)
!       .. Use Statements ..
        Use lapack_precision, Only: dp
!       .. Implicit None Statement ..
        Implicit None
!       .. Function Return Value ..
        Logical :: selctg
!       .. Scalar Arguments ..
        Complex (Kind=dp), Intent (In) :: a, b
!       .. Intrinsic Procedures ..
        Intrinsic :: abs
!       .. Executable Statements ..
        Continue

!       Dummy function - it is not called by ZGGES when sorting is not required.
        selctg = (abs(a)<6.0_dp*abs(b))

        Return
      End Function
    End Module
    Program zgges_example

!     ZGGES Example Program Text

!     Copyright 2017, Numerical Algorithms Group Ltd. http://www.nag.com

!     .. Use Statements ..
      Use blas_interfaces, Only: zgemm
      Use lapack_example_aux, Only: nagf_sort_realvec_rank, &
        nagf_file_print_matrix_complex_gen_comp, &
        nagf_sort_cmplxvec_rank_rearrange
      Use lapack_interfaces, Only: zgges, zlange
      Use lapack_precision, Only: dp
      Use zgges_mod, Only: selctg
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter :: nb = 64, nin = 5, nout = 6
      Logical, Parameter :: chkfac = .False., prmat = .False.
!     .. Local Scalars ..
      Complex (Kind=dp) :: alph, bet
      Real (Kind=dp) :: normd, norme
      Integer :: i, ifail, info, lda, ldb, ldc, ldd, lde, ldvsl, ldvsr, lwork, &
        n, sdim
      Logical :: factor
!     .. Local Arrays ..
      Complex (Kind=dp), Allocatable :: a(:, :), alpha(:), b(:, :), beta(:), &
        c(:, :), d(:, :), e(:, :), vsl(:, :), vsr(:, :), work(:)
      Complex (Kind=dp) :: wdum(1)
      Real (Kind=dp), Allocatable :: rwork(:)
      Integer, Allocatable :: irank(:)
      Logical, Allocatable :: bwork(:)
      Character (1) :: clabs(1), rlabs(1)
!     .. Intrinsic Procedures ..
      Intrinsic :: abs, all, cmplx, epsilon, max, nint, real
!     .. Executable Statements ..
      Write (nout, *) 'ZGGES Example Program Results'
      Write (nout, *)
      Flush (nout)
!     Skip heading in data file
      Read (nin, *)
      Read (nin, *) n
      lda = n
      ldb = n
      ldc = n
      ldd = n
      lde = n
      ldvsl = n
      ldvsr = n
      Allocate (a(lda,n), alpha(n), b(ldb,n), beta(n), c(ldc,n), d(ldd,n), &
        e(lde,n), vsl(ldvsl,n), vsr(ldvsr,n), rwork(8*n), bwork(n), irank(n))

!     Use routine workspace query to get optimal workspace.
      lwork = -1
      Call zgges('Vectors (left)', 'Vectors (right)', 'No sort', selctg, n, a, &
        lda, b, ldb, sdim, alpha, beta, vsl, ldvsl, vsr, ldvsr, wdum, lwork, &
        rwork, bwork, info)

!     Make sure that there is enough workspace for block size nb.
      lwork = max((nb+1)*n, nint(real(wdum(1))))
      Allocate (work(lwork))

!     Read in the matrices A and B
      Read (nin, *)(a(i,1:n), i=1, n)
      Read (nin, *)(b(i,1:n), i=1, n)

!     Copy A and B into D and E respectively
      d(1:n, 1:n) = a(1:n, 1:n)
      e(1:n, 1:n) = b(1:n, 1:n)

      If (prmat) Then
!       Print matrices A and B
!       ifail: behaviour on error exit
!              =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
        ifail = 0
        Call nagf_file_print_matrix_complex_gen_comp('General', ' ', n, n, a, &
          lda, 'Bracketed', 'F8.4', 'Matrix A', 'Integer', rlabs, 'Integer', &
          clabs, 80, 0, ifail)
        Write (nout, *)
        Flush (nout)

        ifail = 0
        Call nagf_file_print_matrix_complex_gen_comp('General', ' ', n, n, b, &
          ldb, 'Bracketed', 'F8.4', 'Matrix B', 'Integer', rlabs, 'Integer', &
          clabs, 80, 0, ifail)
        Write (nout, *)
        Flush (nout)
      End If

      factor = .True.
!     Find the generalized Schur form
      Call zgges('Vectors (left)', 'Vectors (right)', 'No sort', selctg, n, a, &
        lda, b, ldb, sdim, alpha, beta, vsl, ldvsl, vsr, ldvsr, work, lwork, &
        rwork, bwork, info)

      If (info>0) Then
        Write (nout, 100) 'Failure in ZGGES. INFO =', info
        factor = .False.
      Else If (chkfac) Then

!       Compute A - Q*S*Z^H from the factorization of (A,B) and store in
!       matrix D
        alph = cmplx(1, kind=dp)
        bet = cmplx(0, kind=dp)
        Call zgemm('N', 'N', n, n, n, alph, vsl, ldvsl, a, lda, bet, c, ldc)
        alph = cmplx(-1, kind=dp)
        bet = cmplx(1, kind=dp)
        Call zgemm('N', 'C', n, n, n, alph, c, ldc, vsr, ldvsr, bet, d, ldd)

!       Compute B - Q*T*Z^H from the factorization of (A,B) and store in
!       matrix E
        alph = cmplx(1, kind=dp)
        bet = cmplx(0, kind=dp)
        Call zgemm('N', 'N', n, n, n, alph, vsl, ldvsl, b, ldb, bet, c, ldc)
        alph = cmplx(-1, kind=dp)
        bet = cmplx(1, kind=dp)
        Call zgemm('N', 'C', n, n, n, alph, c, ldc, vsr, ldvsr, bet, e, lde)

!       Find norms of matrices D and E and warn if either is too large
        normd = zlange('O', ldd, n, d, ldd, rwork)
        norme = zlange('O', lde, n, e, lde, rwork)
        If (normd>epsilon(1.0E0_dp)**0.75_dp) Then
          Write (nout, *) 'Norm of A-(Q*S*Z^H) is much greater than 0.'
          factor = .False.
        End If
        If (norme>epsilon(1.0E0_dp)**0.75_dp) Then
          Write (nout, *) 'Norm of B-(Q*T*Z^H) is much greater than 0.'
          factor = .False.
        End If
      End If
      If (factor) Then
!       Sort and print generalized eigenvalues if none are infinite
        If (all(real(beta(1:n))>0.0_dp)) Then
          work(1:n) = alpha(1:n)/beta(1:n)
          rwork(1:n) = abs(work(1:n))

!         Rank eigenvalues
          ifail = 0
          Call nagf_sort_realvec_rank(rwork, 1, n, 'Descending', irank, ifail)

!         Sort eigenvalues in work(1:n)
          Call nagf_sort_cmplxvec_rank_rearrange(work, 1, n, irank, ifail)
          Write (nout, *) 'Generalized Eigenvalues'
          Do i = 1, n
            Write (nout, 110) i, work(i)
          End Do
        End If
      Else
        Write (nout, *) 'Schur factorization has failed.'
      End If

100   Format (1X, A, I4)
110   Format (1X, I2, 3X, '(', F6.2, ',', F6.2, ')')
    End Program
Full documentation of ZGGES


ZGGES3 example

Complex Generalized Nonsymmetric Eigenproblems: Computes, for a complex nonsymmetric matrix pair, using BLAS-3, the generalized eigenvalues, the generalized complex Schur form and, optionally, the left and/or right matrices of Schur vectors

Data

ZGGES3 Example Program Data
  4                                                               : Value of N
  (-21.10,-22.50) ( 53.50,-50.50) (-34.50,127.50) (  7.50,  0.50)
  ( -0.46, -7.78) ( -3.50,-37.50) (-15.50, 58.50) (-10.50, -1.50)
  (  4.30, -5.50) ( 39.70,-17.10) (-68.50, 12.50) ( -7.50, -3.50)
  (  5.50,  4.40) ( 14.40, 43.30) (-32.50,-46.00) (-19.00,-32.50) : End of A
  (  1.00, -5.00) (  1.60,  1.20) ( -3.00,  0.00) (  0.00, -1.00)
  (  0.80, -0.60) (  3.00, -5.00) ( -4.00,  3.00) ( -2.40, -3.20)
  (  1.00,  0.00) (  2.40,  1.80) ( -4.00, -5.00) (  0.00, -3.00)
  (  0.00,  1.00) ( -1.80,  2.40) (  0.00, -4.00) (  4.00, -5.00) : End of B

Result

 ZGGES3 Example Program Results

 Matrix A
                      1                   2                   3
 1  (-21.1000,-22.5000) ( 53.5000,-50.5000) (-34.5000,127.5000)
 2  ( -0.4600, -7.7800) ( -3.5000,-37.5000) (-15.5000, 58.5000)
 3  (  4.3000, -5.5000) ( 39.7000,-17.1000) (-68.5000, 12.5000)
 4  (  5.5000,  4.4000) ( 14.4000, 43.3000) (-32.5000,-46.0000)

                      4
 1  (  7.5000,  0.5000)
 2  (-10.5000, -1.5000)
 3  ( -7.5000, -3.5000)
 4  (-19.0000,-32.5000)

 Matrix B
                      1                   2                   3
 1  (  1.0000, -5.0000) (  1.6000,  1.2000) ( -3.0000,  0.0000)
 2  (  0.8000, -0.6000) (  3.0000, -5.0000) ( -4.0000,  3.0000)
 3  (  1.0000,  0.0000) (  2.4000,  1.8000) ( -4.0000, -5.0000)
 4  (  0.0000,  1.0000) ( -1.8000,  2.4000) (  0.0000, -4.0000)

                      4
 1  (  0.0000, -1.0000)
 2  ( -2.4000, -3.2000)
 3  (  0.0000, -3.0000)
 4  (  4.0000, -5.0000)

 Generalized Eigenvalues
 Eigenvalues:
             1          2          3          4
 1      3.0000     4.0000     2.0000     3.0000
       -9.0000    -5.0000    -5.0000    -1.0000

Source

    Module zgges3_mod

!     ZGGES3 Example Program Module:

!     .. Implicit None Statement ..
      Implicit None
!     .. Accessibility Statements ..
      Private
      Public :: selctg
    Contains
      Function selctg(a, b)
!       .. Use Statements ..
        Use lapack_precision, Only: dp
!       .. Implicit None Statement ..
        Implicit None
!       .. Function Return Value ..
        Logical :: selctg
!       .. Scalar Arguments ..
        Complex (Kind=dp), Intent (In) :: a, b
!       .. Intrinsic Procedures ..
        Intrinsic :: abs
!       .. Executable Statements ..
        Continue

!       Dummy function - it is not called by ZGGES3 when sorting is not required.
        selctg = (abs(a)<6.0_dp*abs(b))

        Return
      End Function
    End Module
    Program zgges3_example

!     ZGGES3 Example Program Text

!     Copyright 2017, Numerical Algorithms Group Ltd. http://www.nag.com

!     .. Use Statements ..
      Use blas_interfaces, Only: zgemm
      Use lapack_example_aux, Only: nagf_sort_cmplxvec_rank_rearrange, &
        nagf_sort_realvec_rank, nagf_file_print_matrix_complex_gen, &
        nagf_file_print_matrix_complex_gen_comp
      Use lapack_interfaces, Only: zgges3, zlange
      Use lapack_precision, Only: dp
      Use zgges3_mod, Only: selctg
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter :: nb = 64, nin = 5, nout = 6
!     .. Local Scalars ..
      Complex (Kind=dp) :: alph, bet
      Real (Kind=dp) :: normd, norme
      Integer :: i, ifail, info, lda, ldb, ldc, ldd, lde, ldvsl, ldvsr, lwork, &
        n, sdim
!     .. Local Arrays ..
      Complex (Kind=dp), Allocatable :: a(:, :), alpha(:), b(:, :), beta(:), &
        c(:, :), d(:, :), e(:, :), vsl(:, :), vsr(:, :), work(:)
      Complex (Kind=dp) :: wdum(1)
      Real (Kind=dp), Allocatable :: rwork(:)
      Integer, Allocatable :: irank(:)
      Logical, Allocatable :: bwork(:)
      Character (1) :: clabs(1), rlabs(1)
!     .. Intrinsic Procedures ..
      Intrinsic :: abs, all, cmplx, epsilon, max, nint, real
!     .. Executable Statements ..
      Write (nout, *) 'ZGGES3 Example Program Results'
      Write (nout, *)
      Flush (nout)
!     Skip heading in data file
      Read (nin, *)
      Read (nin, *) n
      lda = n
      ldb = n
      ldc = n
      ldd = n
      lde = n
      ldvsl = n
      ldvsr = n
      Allocate (a(lda,n), alpha(n), b(ldb,n), beta(n), c(ldc,n), d(ldd,n), &
        e(lde,n), vsl(ldvsl,n), vsr(ldvsr,n), rwork(8*n), bwork(n))

!     Use routine workspace query to get optimal workspace.
      lwork = -1
      Call zgges3('Vectors (left)', 'Vectors (right)', 'No sort', selctg, n, &
        a, lda, b, ldb, sdim, alpha, beta, vsl, ldvsl, vsr, ldvsr, wdum, &
        lwork, rwork, bwork, info)

!     Make sure that there is enough workspace for block size nb.
      lwork = max((nb+1)*n, nint(real(wdum(1))))
      Allocate (work(lwork))

!     Read in the matrices A and B
      Read (nin, *)(a(i,1:n), i=1, n)
      Read (nin, *)(b(i,1:n), i=1, n)

!     Copy A and B into D and E respectively
      d(1:n, 1:n) = a(1:n, 1:n)
      e(1:n, 1:n) = b(1:n, 1:n)

!     Print matrices A and B
!     ifail: behaviour on error exit
!            =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
      ifail = 0
      Call nagf_file_print_matrix_complex_gen_comp('General', ' ', n, n, a, &
        lda, 'Bracketed', 'F8.4', 'Matrix A', 'Integer', rlabs, 'Integer', &
        clabs, 80, 0, ifail)
      Write (nout, *)
      Flush (nout)

      ifail = 0
      Call nagf_file_print_matrix_complex_gen_comp('General', ' ', n, n, b, &
        ldb, 'Bracketed', 'F8.4', 'Matrix B', 'Integer', rlabs, 'Integer', &
        clabs, 80, 0, ifail)
      Write (nout, *)
      Flush (nout)

!     Find the generalized Schur form
      Call zgges3('Vectors (left)', 'Vectors (right)', 'No sort', selctg, n, &
        a, lda, b, ldb, sdim, alpha, beta, vsl, ldvsl, vsr, ldvsr, work, &
        lwork, rwork, bwork, info)

      If (info>0) Then
        Write (nout, 100) 'Failure in ZGGES3. INFO =', info
      Else

!       Compute A - Q*S*Z^H from the factorization of (A,B) and store in
!       matrix D
        alph = cmplx(1, kind=dp)
        bet = cmplx(0, kind=dp)
        Call zgemm('N', 'N', n, n, n, alph, vsl, ldvsl, a, lda, bet, c, ldc)
        alph = cmplx(-1, kind=dp)
        bet = cmplx(1, kind=dp)
        Call zgemm('N', 'C', n, n, n, alph, c, ldc, vsr, ldvsr, bet, d, ldd)

!       Compute B - Q*T*Z^H from the factorization of (A,B) and store in
!       matrix E
        alph = cmplx(1, kind=dp)
        bet = cmplx(0, kind=dp)
        Call zgemm('N', 'N', n, n, n, alph, vsl, ldvsl, b, ldb, bet, c, ldc)
        alph = cmplx(-1, kind=dp)
        bet = cmplx(1, kind=dp)
        Call zgemm('N', 'C', n, n, n, alph, c, ldc, vsr, ldvsr, bet, e, lde)

!       Find norms of matrices D and E and warn if either is too large
        normd = zlange('O', ldd, n, d, ldd, rwork)
        norme = zlange('O', lde, n, e, lde, rwork)
        If (normd>epsilon(1.0E0_dp)**0.75_dp .Or. norme>epsilon(1.0E0_dp)** &
          0.75_dp) Then
          Write (nout, *) 'Norm of A-(Q*S*Z^H) or norm of B-(Q*T*Z^H) &
            &is much greater than 0.'
          Write (nout, *) 'Schur factorization has failed.'
        Else
!         Print generalized eigenvalues
          Write (nout, *) 'Generalized Eigenvalues'

          If (all(abs(beta(1:n))>epsilon(1.0E0_dp))) Then
            alpha(1:n) = alpha(1:n)/beta(1:n)
!           Reorder eigenvalues by descending absolute value
            rwork(1:n) = abs(alpha(1:n))
            Allocate (irank(n))
            ifail = 0
            Call nagf_sort_realvec_rank(rwork, 1, n, 'Descending', irank, &
              ifail)
            Call nagf_sort_cmplxvec_rank_rearrange(alpha, 1, n, irank, ifail)
            ifail = 0
            Call nagf_file_print_matrix_complex_gen('Gen', ' ', 1, n, alpha, &
              1, 'Eigenvalues:', ifail)
            Write (nout, *)
            Flush (nout)
          Else
            Do i = 1, n
              If (beta(i)/=0.0_dp) Then
                Write (nout, 110) i, alpha(i)/beta(i)
              Else
                Write (nout, 120) i
              End If
            End Do
          End If
        End If
      End If

100   Format (1X, A, I4)
110   Format (1X, I2, 1X, '(', 1P, E11.4, ',', E11.4, ')')
120   Format (1X, I4, 'Eigenvalue is infinite')
    End Program
Full documentation of ZGGES3


ZGGESX example

Complex Generalized Nonsymmetric Eigenproblems: For a complex nonsymmetric matrix pair, the generalized eigenvalues, the generalized complex Schur form and, optionally, the left and/or right matrices of Schur vectors; also, optionally, reciprocal condition numbers for selected eigenvalues

 To find the generalized Schur factorization of the matrix pair $ (A,B)$, where

and

such that the eigenvalues of $ (A,B)$ for which [image] correspond tothe top left diagonal elements of the generalized Schur form, $ (S,T)$.Estimates of the condition numbers for the selected eigenvalue cluster andcorresponding deflating subspaces are also returned.

Data

ZGGESX Example Program Data
  4                                                               : Value of N
  (-21.10,-22.50) ( 53.50,-50.50) (-34.50,127.50) (  7.50,  0.50)
  ( -0.46, -7.78) ( -3.50,-37.50) (-15.50, 58.50) (-10.50, -1.50)
  (  4.30, -5.50) ( 39.70,-17.10) (-68.50, 12.50) ( -7.50, -3.50)
  (  5.50,  4.40) ( 14.40, 43.30) (-32.50,-46.00) (-19.00,-32.50) : End of A
  (  1.00, -5.00) (  1.60,  1.20) ( -3.00,  0.00) (  0.00, -1.00)
  (  0.80, -0.60) (  3.00, -5.00) ( -4.00,  3.00) ( -2.40, -3.20)
  (  1.00,  0.00) (  2.40,  1.80) ( -4.00, -5.00) (  0.00, -3.00)
  (  0.00,  1.00) ( -1.80,  2.40) (  0.00, -4.00) (  4.00, -5.00) : End of B

Result

 ZGGESX Example Program Results

 Number of eigenvalues for which SELCTG is true =    2
 (dimension of deflating subspaces)

 Selected generalized eigenvalues
  1 (  2.00, -5.00)
  2 (  3.00, -1.00)

Source

!   ZGGESX Example Program Text
!   Copyright 2017, Numerical Algorithms Group Ltd. http://www.nag.com

    Module zggesx_mod

!     ZGGESX Example Program Module:
!            Parameters and User-defined Routines

!     .. Use Statements ..
      Use lapack_precision, Only: dp
!     .. Implicit None Statement ..
      Implicit None
!     .. Accessibility Statements ..
      Private
      Public :: selctg
!     .. Parameters ..
      Integer, Parameter, Public :: nb = 64, nin = 5, nout = 6
      Logical, Parameter, Public :: chkfac = .False., prcond = .False., &
        prmat = .False.
    Contains
      Function selctg(a, b)

!       Logical function selctg for use with ZGGESX (ZGGESX)
!       Returns the value .TRUE. if the absolute value of the eigenvalue
!       a/b < 6.0

!       .. Function Return Value ..
        Logical :: selctg
!       .. Scalar Arguments ..
        Complex (Kind=dp), Intent (In) :: a, b
!       .. Intrinsic Procedures ..
        Intrinsic :: abs
!       .. Executable Statements ..
        selctg = (abs(a)<6.0_dp*abs(b))
        Return
      End Function
    End Module
    Program zggesx_example

!     ZGGESX Example Main Program

!     .. Use Statements ..
      Use blas_interfaces, Only: zgemm
      Use zggesx_mod, Only: chkfac, nb, nin, nout, prcond, prmat, selctg
      Use lapack_example_aux, Only: nagf_sort_realvec_rank, nagf_blas_dpyth, &
        nagf_file_print_matrix_complex_gen_comp, &
        nagf_sort_cmplxvec_rank_rearrange
      Use lapack_interfaces, Only: zggesx, zlange
      Use lapack_precision, Only: dp
!     .. Implicit None Statement ..
      Implicit None
!     .. Local Scalars ..
      Complex (Kind=dp) :: alph, bet
      Real (Kind=dp) :: abnorm, anorm, bnorm, eps, normd, norme, tol
      Integer :: i, ifail, info, lda, ldb, ldc, ldd, lde, ldvsl, ldvsr, &
        liwork, lwork, n, sdim
      Logical :: factor
!     .. Local Arrays ..
      Complex (Kind=dp), Allocatable :: a(:, :), alpha(:), b(:, :), beta(:), &
        c(:, :), d(:, :), e(:, :), vsl(:, :), vsr(:, :), work(:)
      Complex (Kind=dp) :: dummy(1)
      Real (Kind=dp) :: rconde(2), rcondv(2)
      Real (Kind=dp), Allocatable :: rwork(:)
      Integer :: idum(1)
      Integer, Allocatable :: iwork(:)
      Logical, Allocatable :: bwork(:)
      Character (1) :: clabs(1), rlabs(1)
!     .. Intrinsic Procedures ..
      Intrinsic :: abs, cmplx, epsilon, max, nint, real
!     .. Executable Statements ..
      Write (nout, *) 'ZGGESX Example Program Results'
      Write (nout, *)
      Flush (nout)
!     Skip heading in data file
      Read (nin, *)
      Read (nin, *) n
      lda = n
      ldb = n
      ldc = n
      ldd = n
      lde = n
      ldvsl = n
      ldvsr = n
      Allocate (a(lda,n), alpha(n), b(ldb,n), beta(n), c(ldc,n), d(ldd,n), &
        e(lde,n), vsl(ldvsl,n), vsr(ldvsr,n), rwork(8*n), bwork(n))

!     Use routine workspace query to get optimal workspace.
      lwork = -1
      liwork = -1
      Call zggesx('Vectors (left)', 'Vectors (right)', 'Sort', selctg, &
        'Both reciprocal condition numbers', n, a, lda, b, ldb, sdim, alpha, &
        beta, vsl, ldvsl, vsr, ldvsr, rconde, rcondv, dummy, lwork, rwork, &
        idum, liwork, bwork, info)

!     Make sure that there is enough workspace for block size nb.
      lwork = max(n*nb+n*n/2, nint(real(dummy(1))))
      liwork = max(n+2, idum(1))
      Allocate (work(lwork), iwork(liwork))

!     Read in the matrices A and B
      Read (nin, *)(a(i,1:n), i=1, n)
      Read (nin, *)(b(i,1:n), i=1, n)

      If (chkfac) Then
!       Copy A and B into D and E respectively
        d(1:n, 1:n) = a(1:n, 1:n)
        e(1:n, 1:n) = b(1:n, 1:n)
      End If

!     Find the Frobenius norms of A and B
      anorm = zlange('Frobenius', n, n, a, lda, rwork)
      bnorm = zlange('Frobenius', n, n, b, ldb, rwork)

      If (prmat) Then
!       Print matrices A and B
!       ifail: behaviour on error exit
!              =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
        ifail = 0
        Call nagf_file_print_matrix_complex_gen_comp('General', ' ', n, n, a, &
          lda, 'Bracketed', 'F8.4', 'Matrix A', 'Integer', rlabs, 'Integer', &
          clabs, 80, 0, ifail)
        Write (nout, *)
        Flush (nout)

        ifail = 0
        Call nagf_file_print_matrix_complex_gen_comp('General', ' ', n, n, b, &
          ldb, 'Bracketed', 'F8.4', 'Matrix B', 'Integer', rlabs, 'Integer', &
          clabs, 80, 0, ifail)
        Write (nout, *)
        Flush (nout)
      End If

      factor = .True.
!     Find the generalized Schur form
      Call zggesx('Vectors (left)', 'Vectors (right)', 'Sort', selctg, &
        'Both reciprocal condition numbers', n, a, lda, b, ldb, sdim, alpha, &
        beta, vsl, ldvsl, vsr, ldvsr, rconde, rcondv, work, lwork, rwork, &
        iwork, liwork, bwork, info)

      If (info/=0 .And. info/=(n+2)) Then
        Write (nout, 100) 'Failure in ZGGESX. INFO =', info
        factor = .False.
      Else If (chkfac) Then
!       Compute A - Q*S*Z^H from the factorization of (A,B) and store in
!       matrix D
        alph = cmplx(1, kind=dp)
        bet = cmplx(0, kind=dp)
        Call zgemm('N', 'N', n, n, n, alph, vsl, ldvsl, a, lda, bet, c, ldc)
        alph = cmplx(-1, kind=dp)
        bet = cmplx(1, kind=dp)
        Call zgemm('N', 'C', n, n, n, alph, c, ldc, vsr, ldvsr, bet, d, ldd)

!       Compute B - Q*T*Z^H from the factorization of (A,B) and store in
!       matrix E
        alph = cmplx(1, kind=dp)
        bet = cmplx(0, kind=dp)
        Call zgemm('N', 'N', n, n, n, alph, vsl, ldvsl, b, ldb, bet, c, ldc)
        alph = cmplx(-1, kind=dp)
        bet = cmplx(1, kind=dp)
        Call zgemm('N', 'C', n, n, n, alph, c, ldc, vsr, ldvsr, bet, e, lde)

!       Find norms of matrices D and E and warn if either is too large
        normd = zlange('O', ldd, n, d, ldd, rwork)
        If (normd>epsilon(1.0E0_dp)**0.75_dp) Then
          Write (nout, *) 'Norm of A-(Q*S*Z^T) is much greater than 0.'
          factor = .False.
          Write (nout, *) 'Schur factorization has failed.'
        End If
        norme = zlange('O', lde, n, e, lde, rwork)
        If (norme>epsilon(1.0E0_dp)**0.75_dp) Then
          Write (nout, *) 'Norm of B-(Q*T*Z^T) is much greater than 0.'
          factor = .False.
        End If
      End If

      If (factor) Then
!       Print eigenvalue details
        Write (nout, 100) 'Number of eigenvalues for which SELCTG is true = ', &
          sdim, '(dimension of deflating subspaces)'

        Write (nout, *)
!       Print selected (finite) generalized eigenvalues
        Write (nout, *) 'Selected generalized eigenvalues'

!       Store absolute values of eigenvalues for ranking
        work(1:n) = alpha(1:n)/beta(1:n)
        rwork(1:n) = abs(work(1:n))

!       Rank eigenvalues
        ifail = 0
        Call nagf_sort_realvec_rank(rwork, 1, sdim, 'Descending', iwork, &
          ifail)

!       Sort eigenvalues in work(1:n)
        Call nagf_sort_cmplxvec_rank_rearrange(work, 1, sdim, iwork, ifail)
        Do i = 1, sdim
          Write (nout, 110) i, work(i)
        End Do

        If (info==(n+2)) Then
          Write (nout, 120) '*** Note that rounding errors mean ', &
            'that leading eigenvalues in the', &
            'generalized Schur form no longer satisfy SELCTG = .TRUE.'
          Write (nout, *)
        End If
        Flush (nout)

        If (prcond) Then
!         Compute the machine precision and sqrt(anorm**2+bnorm**2)
          eps = epsilon(1.0E0_dp)
          abnorm = nagf_blas_dpyth(anorm, bnorm)
          tol = eps*abnorm

!         Print out the reciprocal condition numbers and error bound for
!         selected eigenvalues
          Write (nout, *)
          Write (nout, 130) &
            'Reciprocal condition numbers for the average of the', &
            'selected eigenvalues and their asymptotic error bound', &
            'rcond-left = ', rconde(1), ', rcond-right = ', rconde(2), &
            ', error = ', tol/rconde(1)

          Write (nout, *)
          Write (nout, 130) &
            'Reciprocal condition numbers for the deflating subspaces', &
            'and their approximate asymptotic error bound', 'rcond-left = ', &
            rcondv(1), ', rcond-right = ', rcondv(2), ', error = ', &
            tol/rcondv(2)
        End If

      Else
        Write (nout, *) 'Schur factorization has failed.'
      End If

100   Format (1X, A, I4, /, 1X, A)
110   Format (1X, I2, 1X, '(', F6.2, ',', F6.2, ')')
120   Format (1X, 2A, /, 1X, A)
130   Format (1X, A, /, 1X, A, /, 1X, 3(A,1P,E8.1))
    End Program
Full documentation of ZGGESX


ZGGEV example

Complex Generalized Nonsymmetric Eigenproblems: For a complex nonsymmetric matrix pair, the generalized eigenvalues, and optionally, the left and/or right generalized eigenvectors

 To find all the eigenvalues and right eigenvectors of the matrix pair $ (A,B)$,where

and

Data

ZGGEV Example Program Data
  4                                                               : Value of N
  (-21.10,-22.50) ( 53.50,-50.50) (-34.50,127.50) (  7.50,  0.50)
  ( -0.46, -7.78) ( -3.50,-37.50) (-15.50, 58.50) (-10.50, -1.50)
  (  4.30, -5.50) ( 39.70,-17.10) (-68.50, 12.50) ( -7.50, -3.50)
  (  5.50,  4.40) ( 14.40, 43.30) (-32.50,-46.00) (-19.00,-32.50) : End of A
  (  1.00, -5.00) (  1.60,  1.20) ( -3.00,  0.00) (  0.00, -1.00)
  (  0.80, -0.60) (  3.00, -5.00) ( -4.00,  3.00) ( -2.40, -3.20)
  (  1.00,  0.00) (  2.40,  1.80) ( -4.00, -5.00) (  0.00, -3.00)
  (  0.00,  1.00) ( -1.80,  2.40) (  0.00, -4.00) (  4.00, -5.00) : End of B

Result

 ZGGEV Example Program Results

 Eigenvalues:
             1          2          3          4
 1      3.0000     4.0000     2.0000     3.0000
       -9.0000    -5.0000    -5.0000    -1.0000

 Eigenvectors (columns):
          1       2       3       4
 1   1.0000  1.0000  1.0000  1.0000
     0.0000  0.0000  0.0000  0.0000

 2   0.1600  0.0089  0.0046  0.1600
    -0.1200 -0.0067 -0.0034 -0.1200

 3   0.1200 -0.0333  0.0629  0.1200
     0.1600 -0.0000  0.0000 -0.1600

 4  -0.1600  0.0000 -0.0000  0.1600
     0.1200  0.1556  0.0629  0.1200

Source

    Program zggev_example

!     ZGGEV Example Program Text

!     Copyright 2017, Numerical Algorithms Group Ltd. http://www.nag.com

!     .. Use Statements ..
      Use lapack_example_aux, Only: nagf_file_print_matrix_complex_gen, &
        nagf_sort_cmplxvec_rank_rearrange, nagf_sort_realvec_rank
      Use lapack_interfaces, Only: zggev
      Use lapack_precision, Only: dp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Real (Kind=dp), Parameter :: one = 1.0_dp
      Real (Kind=dp), Parameter :: zero = 0.0_dp
      Integer, Parameter :: nb = 64, nin = 5, nout = 6
      Complex (Kind=dp), Parameter :: cone = (one, zero)
!     .. Local Scalars ..
      Complex (Kind=dp) :: scal
      Integer :: i, ifail, info, j, k, lda, ldb, ldvr, lwork, n
!     .. Local Arrays ..
      Complex (Kind=dp), Allocatable :: a(:, :), alpha(:), b(:, :), beta(:), &
        vr(:, :), work(:)
      Complex (Kind=dp) :: dummy(1, 1)
      Real (Kind=dp), Allocatable :: rwork(:)
      Integer, Allocatable :: irank(:)
!     .. Intrinsic Procedures ..
      Intrinsic :: abs, all, epsilon, max, maxloc, nint, real
!     .. Executable Statements ..
      Write (nout, *) 'ZGGEV Example Program Results'
      Flush (nout)
!     Skip heading in data file
      Read (nin, *)
      Read (nin, *) n
      lda = n
      ldb = n
      ldvr = n
      Allocate (a(lda,n), alpha(n), b(ldb,n), beta(n), vr(ldvr,n), rwork(8*n))

!     Use routine workspace query to get optimal workspace.
      lwork = -1
      Call zggev('No left vectors', 'Vectors (right)', n, a, lda, b, ldb, &
        alpha, beta, dummy, 1, vr, ldvr, dummy, lwork, rwork, info)

!     Make sure that there is enough workspace for block size nb.
      lwork = max((nb+1)*n, nint(real(dummy(1,1))))
      Allocate (work(lwork))

!     Read in the matrices A and B

      Read (nin, *)(a(i,1:n), i=1, n)
      Read (nin, *)(b(i,1:n), i=1, n)

!     Solve the generalized eigenvalue problem

      Call zggev('No left vectors', 'Vectors (right)', n, a, lda, b, ldb, &
        alpha, beta, dummy, 1, vr, ldvr, work, lwork, rwork, info)

      If (info>0) Then
        Write (nout, *)
        Write (nout, 100) 'Failure in ZGGEV. INFO =', info
      Else
!       Re-normalize the eigenvectors, largest absolute element real (=1)
        Do i = 1, n
          rwork(1:n) = abs(vr(1:n,i))
          k = maxloc(rwork(1:n), 1)
          scal = cone/vr(k, i)
          vr(1:n, i) = vr(1:n, i)*scal
          vr(k, i) = cone
        End Do

        Write (nout, *)
        Flush (nout)
        If (all(abs(beta(1:n))>epsilon(1.0E0_dp))) Then
!         Reorder eigenvalues by descending absolute value and print
          alpha(1:n) = alpha(1:n)/beta(1:n)
          rwork(1:n) = abs(alpha(1:n))
          Allocate (irank(n))
          ifail = 0
          Call nagf_sort_realvec_rank(rwork, 1, n, 'Descending', irank, ifail)
          Call nagf_sort_cmplxvec_rank_rearrange(alpha, 1, n, irank, ifail)
          ifail = 0
          Call nagf_file_print_matrix_complex_gen('Gen', ' ', 1, n, alpha, 1, &
            'Eigenvalues:', ifail)

!         Reorder eigenvectors accordingly
          Do j = 1, n
            beta(1:n) = vr(j, 1:n)
            Call nagf_sort_cmplxvec_rank_rearrange(beta, 1, n, irank, ifail)
            vr(j, 1:n) = beta(1:n)
          End Do
        Else
          Write (nout, *) &
            'Some of the eigenvalues are infinite or undetermined'
          Write (nout, *)
          Flush (nout)
          ifail = 0
          Call nagf_file_print_matrix_complex_gen('Gen', ' ', 1, n, alpha, 1, &
            'Alpha:', ifail)
          Call nagf_file_print_matrix_complex_gen('Gen', ' ', 1, n, beta, 1, &
            'Beta:', ifail)
        End If
        Write (nout, *)
        Flush (nout)
        ifail = 0
        Call nagf_file_print_matrix_complex_gen('Gen', ' ', n, n, vr, ldvr, &
          'Eigenvectors (columns):', ifail)
      End If

100   Format (1X, A, I4)
    End Program
Full documentation of ZGGEV


ZGGEV3 example

Complex Generalized Nonsymmetric Eigenproblems: Computes, for a complex nonsymmetric matrix pair, using BLAS-3, the generalized eigenvalues, and optionally, the left and/or right generalized eigenvectors

Data

ZGGEV3 Example Program Data
  4                                                               : Value of N
  (-21.10,-22.50) ( 53.50,-50.50) (-34.50,127.50) (  7.50,  0.50)
  ( -0.46, -7.78) ( -3.50,-37.50) (-15.50, 58.50) (-10.50, -1.50)
  (  4.30, -5.50) ( 39.70,-17.10) (-68.50, 12.50) ( -7.50, -3.50)
  (  5.50,  4.40) ( 14.40, 43.30) (-32.50,-46.00) (-19.00,-32.50) : End of A
  (  1.00, -5.00) (  1.60,  1.20) ( -3.00,  0.00) (  0.00, -1.00)
  (  0.80, -0.60) (  3.00, -5.00) ( -4.00,  3.00) ( -2.40, -3.20)
  (  1.00,  0.00) (  2.40,  1.80) ( -4.00, -5.00) (  0.00, -3.00)
  (  0.00,  1.00) ( -1.80,  2.40) (  0.00, -4.00) (  4.00, -5.00) : End of B

Result

 ZGGEV3 Example Program Results

 Eigenvalues:
             1          2          3          4
 1      3.0000     4.0000     2.0000     3.0000
       -9.0000    -5.0000    -5.0000    -1.0000

 Right Eigenvectors (columns):
          1       2       3       4
 1   0.9449  0.9875  0.9961  0.9449
     0.0000 -0.0000  0.0000  0.0000

 2   0.1512  0.0088  0.0046  0.1512
    -0.1134 -0.0066 -0.0034 -0.1134

 3   0.1134 -0.0329  0.0626  0.1134
     0.1512 -0.0000  0.0000 -0.1512

 4  -0.1512  0.0000 -0.0000  0.1512
     0.1134  0.1536  0.0626  0.1134

Source

    Program zggev3_example

!     ZGGEV3 Example Program Text

!     Copyright 2017, Numerical Algorithms Group Ltd. http://www.nag.com

!     .. Use Statements ..
      Use blas_interfaces, Only: dznrm2
      Use lapack_example_aux, Only: nagf_file_print_matrix_complex_gen, &
        nagf_sort_cmplxvec_rank_rearrange, nagf_sort_realvec_rank
      Use lapack_interfaces, Only: zggev3
      Use lapack_precision, Only: dp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter :: nin = 5, nout = 6
!     .. Local Scalars ..
      Complex (Kind=dp) :: scal
      Integer :: i, ifail, info, j, k, lda, ldb, ldvr, lwork, n
!     .. Local Arrays ..
      Complex (Kind=dp), Allocatable :: a(:, :), alpha(:), b(:, :), beta(:), &
        temp(:), vr(:, :), work(:)
      Complex (Kind=dp) :: dummy(1, 1)
      Real (Kind=dp), Allocatable :: rwork(:)
      Integer, Allocatable :: irank(:)
!     .. Intrinsic Procedures ..
      Intrinsic :: abs, all, conjg, epsilon, maxloc, nint, real
!     .. Executable Statements ..
      Write (nout, *) 'ZGGEV3 Example Program Results'
      Write (nout, *)
      Flush (nout)
!     Skip heading in data file
      Read (nin, *)
      Read (nin, *) n
      lda = n
      ldb = n
      ldvr = n
      Allocate (a(lda,n), alpha(n), b(ldb,n), beta(n), vr(ldvr,n), rwork(8*n))

!     Use routine workspace query to get optimal workspace.
      lwork = -1
      Call zggev3('No left vectors', 'Vectors (right)', n, a, lda, b, ldb, &
        alpha, beta, dummy, 1, vr, ldvr, dummy, lwork, rwork, info)

      lwork = nint(real(dummy(1,1)))
      Allocate (work(lwork))

!     Read in the matrices A and B

      Read (nin, *)(a(i,1:n), i=1, n)
      Read (nin, *)(b(i,1:n), i=1, n)

!     Solve the generalized eigenvalue problem

      Call zggev3('No left vectors', 'Vectors (right)', n, a, lda, b, ldb, &
        alpha, beta, dummy, 1, vr, ldvr, work, lwork, rwork, info)

      If (info>0) Then
        Write (nout, *)
        Write (nout, 100) 'Failure in ZGGEV3. INFO =', info
      Else If (all(abs(beta(1:n))>epsilon(1.0E0_dp))) Then
!       Re-normalize the eigenvectors, largest absolute element real
        Do i = 1, n
          rwork(1:n) = abs(vr(1:n,i))
          k = maxloc(rwork(1:n), 1)
          scal = conjg(vr(k,i))/rwork(k)/dznrm2(n, vr(1,i), 1)
          vr(1:n, i) = vr(1:n, i)*scal
        End Do
        alpha(1:n) = alpha(1:n)/beta(1:n)

!       Reorder eigenvalues by descending absolute value
        rwork(1:n) = abs(alpha(1:n))
        Allocate (irank(n), temp(n))
        ifail = 0
        Call nagf_sort_realvec_rank(rwork, 1, n, 'Descending', irank, ifail)
        Call nagf_sort_cmplxvec_rank_rearrange(alpha, 1, n, irank, ifail)

!       Reorder eigenvectors accordingly
        Do j = 1, n
          temp(1:n) = vr(j, 1:n)
          Call nagf_sort_cmplxvec_rank_rearrange(temp, 1, n, irank, ifail)
          vr(j, 1:n) = temp(1:n)
        End Do

        ifail = 0
        Call nagf_file_print_matrix_complex_gen('Gen', ' ', 1, n, alpha, 1, &
          'Eigenvalues:', ifail)
        Write (nout, *)
        Flush (nout)
        Call nagf_file_print_matrix_complex_gen('Gen', ' ', n, n, vr, ldvr, &
          'Right Eigenvectors (columns):', ifail)
      Else
        Write (nout, *) 'Some of the eigenvalues are infinite.'
        Write (nout, *)
        Flush (nout)
        ifail = 0
        Call nagf_file_print_matrix_complex_gen('Gen', ' ', 1, n, alpha, 1, &
          'Alpha', ifail)
        Call nagf_file_print_matrix_complex_gen('Gen', ' ', 1, n, beta, 1, &
          'Beta', ifail)
      End If

100   Format (1X, A, I4)
    End Program
Full documentation of ZGGEV3


ZGGEVX example

Complex Generalized Nonsymmetric Eigenproblems: For a complex nonsymmetric matrix pair, the generalized eigenvalues, and optionally, the left and/or right generalized eigenvectors; also, optionally, the balancing transformation, the reciprocal condition numbers for the eigenvalues and for the right eigenvectors

 To find all the eigenvalues and right eigenvectors of the matrix pair $ (A,B)$,where

and

together with estimates of the condition number and forward error bounds foreach eigenvalue and eigenvector. The option to balance the matrix pair is used.

Data

ZGGEVX Example Program Data
  4                                                               : Value of N
  (-21.10,-22.50) ( 53.50,-50.50) (-34.50,127.50) (  7.50,  0.50)
  ( -0.46, -7.78) ( -3.50,-37.50) (-15.50, 58.50) (-10.50, -1.50)
  (  4.30, -5.50) ( 39.70,-17.10) (-68.50, 12.50) ( -7.50, -3.50)
  (  5.50,  4.40) ( 14.40, 43.30) (-32.50,-46.00) (-19.00,-32.50) : End of A
  (  1.00, -5.00) (  1.60,  1.20) ( -3.00,  0.00) (  0.00, -1.00)
  (  0.80, -0.60) (  3.00, -5.00) ( -4.00,  3.00) ( -2.40, -3.20)
  (  1.00,  0.00) (  2.40,  1.80) ( -4.00, -5.00) (  0.00, -3.00)
  (  0.00,  1.00) ( -1.80,  2.40) (  0.00, -4.00) (  4.00, -5.00) : End of B

Result

Warning: Floating underflow occurred
 ZGGEVX Example Program Results

 Eigenvalues

          Eigenvalue
  1 ( 3.0000E+00,-9.0000E+00)
  2 ( 4.0000E+00,-5.0000E+00)
  3 ( 2.0000E+00,-5.0000E+00)
  4 ( 3.0000E+00,-1.0000E+00)

 Eigenvectors

          Eigenvector

  1 ( 1.0000E+00, 0.0000E+00)
    ( 1.6000E-01,-1.2000E-01)
    ( 1.2000E-01, 1.6000E-01)
    (-1.6000E-01, 1.2000E-01)

  2 ( 1.0000E+00, 0.0000E+00)
    ( 8.8889E-03,-6.6667E-03)
    (-3.3333E-02, 1.1796E-16)
    ( 4.1633E-16, 1.5556E-01)

  3 ( 1.0000E+00, 0.0000E+00)
    ( 4.5714E-03,-3.4286E-03)
    ( 6.2857E-02,-1.4572E-16)
    ( 1.4572E-16, 6.2857E-02)

  4 ( 1.0000E+00, 0.0000E+00)
    ( 1.6000E-01,-1.2000E-01)
    ( 1.2000E-01,-1.6000E-01)
    ( 1.6000E-01, 1.2000E-01)

Source

    Program zggevx_example

!     ZGGEVX Example Program Text

!     Copyright 2017, Numerical Algorithms Group Ltd. http://www.nag.com

!     .. Use Statements ..
      Use lapack_example_aux, Only: nagf_sort_realvec_rank_rearrange, &
        nagf_blas_dpyth, nagf_sort_cmplxvec_rank_rearrange, &
        nagf_sort_realvec_rank
      Use lapack_interfaces, Only: zggevx
      Use lapack_precision, Only: dp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter :: nb = 64, nin = 5, nout = 6
      Logical, Parameter :: verbose = .False.
!     .. Local Scalars ..
      Complex (Kind=dp) :: eig, scal
      Real (Kind=dp) :: abnorm, abnrm, bbnrm, eps, small, tol
      Integer :: i, ifail, ihi, ilo, info, j, k, lda, ldb, ldvr, lwork, n
!     .. Local Arrays ..
      Complex (Kind=dp), Allocatable :: a(:, :), alpha(:), b(:, :), beta(:), &
        temp(:), vr(:, :), work(:)
      Complex (Kind=dp) :: dummy(1, 1)
      Real (Kind=dp), Allocatable :: lscale(:), rconde(:), rcondv(:), &
        rscale(:), rwork(:)
      Integer, Allocatable :: irank(:), iwork(:)
      Logical, Allocatable :: bwork(:)
!     .. Intrinsic Procedures ..
      Intrinsic :: abs, epsilon, max, maxloc, nint, real, tiny
!     .. Executable Statements ..
      Write (nout, *) 'ZGGEVX Example Program Results'
!     Skip heading in data file
      Read (nin, *)
      Read (nin, *) n
      lda = n
      ldb = n
      ldvr = n
      Allocate (a(lda,n), alpha(n), b(ldb,n), beta(n), vr(ldvr,n), lscale(n), &
        rconde(n), rcondv(n), rscale(n), rwork(6*n), iwork(n+2), bwork(n), &
        temp(n))

!     Use routine workspace query to get optimal workspace.
      lwork = -1
      Call zggevx('Balance', 'No vectors (left)', 'Vectors (right)', &
        'Both reciprocal condition numbers', n, a, lda, b, ldb, alpha, beta, &
        dummy, 1, vr, ldvr, ilo, ihi, lscale, rscale, abnrm, bbnrm, rconde, &
        rcondv, dummy, lwork, rwork, iwork, bwork, info)

!     Make sure that there is enough workspace for block size nb.
      lwork = max((nb+2*n)*n, nint(real(dummy(1,1))))
      Allocate (work(lwork))

!     Read in the matrices A and B

      Read (nin, *)(a(i,1:n), i=1, n)
      Read (nin, *)(b(i,1:n), i=1, n)

!     Solve the generalized eigenvalue problem

      Call zggevx('Balance', 'No vectors (left)', 'Vectors (right)', &
        'Both reciprocal condition numbers', n, a, lda, b, ldb, alpha, beta, &
        dummy, 1, vr, ldvr, ilo, ihi, lscale, rscale, abnrm, bbnrm, rconde, &
        rcondv, work, lwork, rwork, iwork, bwork, info)

      If (info>0) Then
        Write (nout, *)
        Write (nout, 100) 'Failure in ZGGEVX. INFO =', info
      Else

!       Compute the machine precision, the safe range parameter
!       SMALL and sqrt(ABNRM**2+BBNRM**2)

        eps = epsilon(1.0E0_dp)
        small = tiny(1.0E0_dp)
        abnorm = nagf_blas_dpyth(abnrm, bbnrm)
        tol = eps*abnorm

!       Reorder eigenvalues by descending absolute value
        rwork(1:n) = abs(alpha(1:n)/beta(1:n))
        Allocate (irank(n))
        ifail = 0
        Call nagf_sort_realvec_rank(rwork, 1, n, 'Descending', irank, ifail)
        Call nagf_sort_cmplxvec_rank_rearrange(alpha, 1, n, irank, ifail)
        Call nagf_sort_cmplxvec_rank_rearrange(beta, 1, n, irank, ifail)
        Call nagf_sort_realvec_rank_rearrange(rconde, 1, n, irank, ifail)
!       Reorder eigenvectors accordingly
        Do j = 1, n
          temp(1:n) = vr(j, 1:n)
          Call nagf_sort_cmplxvec_rank_rearrange(temp, 1, n, irank, ifail)
          vr(j, 1:n) = temp(1:n)
        End Do
        Call nagf_sort_realvec_rank_rearrange(rcondv, 1, n, irank, ifail)

!       Print out eigenvalues and vectors and associated condition
!       number and bounds

        Write (nout, *)
        Write (nout, *) 'Eigenvalues'
        Write (nout, *)
        If (verbose) Then
          Write (nout, *) '         Eigenvalue           rcond    error'
        Else
          Write (nout, *) '         Eigenvalue'
        End If

        Do j = 1, n

!         Print out information on the j-th eigenvalue

          If ((abs(alpha(j)))*small>=abs(beta(j))) Then
            If (rconde(j)>0.0_dp) Then
              If (tol/rconde(j)<500.0_dp*eps) Then
                Write (nout, 140) j, rconde(j), '-'
              Else
                Write (nout, 150) j, rconde(j), tol/rconde(j)
              End If
            Else
              Write (nout, 140) j, rconde(j), 'Inf'
            End If
          Else
            eig = alpha(j)/beta(j)
            If (verbose) Then
              If (rconde(j)>0.0_dp) Then
                If (tol/rconde(j)<500.0_dp*eps) Then
                  Write (nout, 110) j, eig, rconde(j), '-'
                Else
                  Write (nout, 120) j, eig, rconde(j), tol/rconde(j)
                End If
              Else
                Write (nout, 110) j, eig, rconde(j), 'Inf'
              End If
            Else
              Write (nout, 110) j, eig
            End If
          End If

        End Do

        Write (nout, *)
        Write (nout, *) 'Eigenvectors'
        Write (nout, *)
        If (verbose) Then
          Write (nout, *) '         Eigenvector          rcond    error'
        Else
          Write (nout, *) '         Eigenvector'
        End If

        Do j = 1, n

!         Print information on j-th eigenvector
          Write (nout, *)

!         Re-normalize eigenvector, largest absolute element real (=1)
          rwork(1:n) = abs(vr(1:n,j))
          k = maxloc(rwork(1:n), 1)
          scal = (1.0_dp, 0.0_dp)/vr(k, j)
          vr(1:n, j) = vr(1:n, j)*scal

          If (verbose) Then
            If (rcondv(j)>0.0_dp) Then
              If (tol/rcondv(j)<500.0_dp*eps) Then
                Write (nout, 110) j, vr(1, j), rcondv(j), '-'
              Else
                Write (nout, 120) j, vr(1, j), rcondv(j), tol/rcondv(j)
              End If
            Else
              Write (nout, 110) j, vr(1, j), rcondv(j), 'Inf'
            End If
          Else
            Write (nout, 110) j, vr(1, j)
          End If
          Write (nout, 130) vr(2:n, j)

        End Do

        If (verbose) Then
          Write (nout, *)
          Write (nout, *) &
            'Errors below 500*machine precision are not displayed'
        End If
      End If

100   Format (1X, A, I4)
110   Format (1X, I2, 1X, '(', 1P, E11.4, ',', E11.4, ')', 1X, 0P, F7.4, 4X, &
        A)
120   Format (1X, I2, 1X, '(', 1P, E11.4, ',', E11.4, ')', 1X, 0P, F7.4, 1X, &
        1P, E8.1)
130   Format (1X, 3X, '(', 1P, E11.4, ',', E11.4, ')')
140   Format (1X, I2, 1X, '  Infinite or undetermined', 1X, 0P, F7.4, 4X, A)
150   Format (1X, I2, 1X, '  Infinite or undetermined', 1X, 0P, F7.4, 1X, 1P, &
        E8.1)

    End Program
Full documentation of ZGGEVX


LAPACK:Real Singular Value Decomposition

Next: Complex Singular Value Decomposition Up: LAPACK Routines by Subject Previous: Complex Generalized Nonsymmetric Eigenproblems

Real Singular Value Decomposition

  • DBDSVDX : Computes all or selected singular values of the singular value decomposition of a real square bidiagonal matrix, optionally computing the corresponding left and right singular vectors
  • DGESDD : Singular value decomposition (by divide-and-conquer) of a real matrix, and, optionally, left and/or right singular vectors
  • DGESVD : Singular value decomposition of a real matrix, and, optionally, left and/or right singular vectors
  • DGESVDX : Computes all or selected singular values of the singular value decomposition of a real general matrix, optionally computing the corresponding left and right singular vectors


DBDSVDX example

Real Singular Value Decomposition: Computes all or selected singular values of the singular value decomposition of a real square bidiagonal matrix, optionally computing the corresponding left and right singular vectors

Data

DBDSVDX Example Program Data

  4                          : n

  3.62  -2.41   1.92  -1.43  : diagonal elements,  d
  1.26  -1.53   1.19         : off-diagonal elements, e

  'V'
  0.00   4.00

Result

 DBDSVDX Example Program Results

  3 singular values of B in the range [  0.000,  4.000]:
         3.0006        1.9960        0.9998

Source

    Program dbdsvdx_example

!     DBDSVDX Example Program Text

!     Copyright 2017, Numerical Algorithms Group Ltd. http://www.nag.com

!     .. Use Statements ..
      Use lapack_interfaces, Only: dbdsvdx
      Use lapack_precision, Only: dp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=dp) :: vl, vu
      Integer :: il, info, iu, ldz, n, ns
      Character (1) :: range
!     .. Local Arrays ..
      Real (Kind=dp), Allocatable :: d(:), e(:), s(:), work(:), z(:, :)
      Integer, Allocatable :: iwork(:)
!     .. Executable Statements ..
      Write (nout, *) 'DBDSVDX Example Program Results'
      Write (nout, *)
      Flush (nout)
!     Skip heading in data file
      Read (nin, *)
      Read (nin, *) n
      ldz = 2*n
      Allocate (d(n), e(n-1), s(n), z(ldz,n+1), work(14*n), iwork(12*n))

!     Read the bidiagonal matrix B from data file, first
!     the diagonal elements, and then the off diagonal elements

      Read (nin, *) d(1:n)
      Read (nin, *) e(1:n-1)

!     Read range for selected singular values
      Read (nin, *) range

      If (range=='I' .Or. range=='i') Then
        Read (nin, *) il, iu
      Else If (range=='V' .Or. range=='v') Then
        Read (nin, *) vl, vu
      End If

!     Calculate the singular values and singular vectors of B.

      Call dbdsvdx('Upper', 'V', range, n, d, e, vl, vu, il, iu, ns, s, z, &
        ldz, work, iwork, info)

      If (info==0) Then
!       Print the singular values of B.

        If (range=='I' .Or. range=='i') Then
          Write (nout, 100) ns, il, iu
        Else If (range=='V' .Or. range=='v') Then
          Write (nout, 110) ns, vl, vu
        End If
        Write (nout, 120) s(1:ns)
      Else
        Write (nout, 130) '** DBDSVDX failed with INFO = ', info
      End If

100   Format (1X, I2, 1X, 'singular values of B in the index range [', I2, &
        ',', I2, ']:')
110   Format (1X, I2, 1X, 'singular values of B in the range [', F7.3, ',', &
        F7.3, ']:')
120   Format (1X, 4(3X,F11.4))
130   Format (1X, A, I10)
    End Program
Full documentation of DBDSVDX


DGESDD example

Real Singular Value Decomposition: Singular value decomposition (by divide-and-conquer) of a real matrix, and, optionally, left and/or right singular vectors

 To find the singular values and left and right singular vectors of the 4 by 6matrix

together with approximate error bounds for the computed singular values andvectors.

The example program for DGESVD illustrates finding a singular valuedecomposition for the case [image].

Data

DGESDD Example Program Data

   4      6                                 :Values of M and N

   2.27   0.28  -0.48   1.07  -2.35   0.62
  -1.54  -1.67  -3.09   1.22   2.93  -7.39
   1.15   0.94   0.99   0.79  -1.45   1.03
  -1.94  -0.78  -0.21   0.63   2.30  -2.57  :End of matrix A

Result

 DGESDD Example Program Results

 Singular values
     9.9966  3.6831  1.3569  0.5000
 Left singular vectors
          1       2       3       4
 1   0.1921  0.8030  0.0041  0.5642
 2  -0.8794  0.3926 -0.0752 -0.2587
 3   0.2140  0.2980  0.7827 -0.5027
 4  -0.3795 -0.3351  0.6178  0.6017

 Right singular vectors by row (first m rows of V**T)
          1       2       3       4       5       6
 1   0.2774  0.2020  0.2918 -0.0938 -0.4213  0.7816
 2   0.6003  0.0301 -0.3348  0.3699 -0.5266 -0.3353
 3  -0.1277  0.2805  0.6453  0.6781  0.0413 -0.1645
 4  -0.1323 -0.7034 -0.1906  0.5399  0.0575  0.3957

 Error estimate for the singular values
        2.2E-15

 Error estimates for the left singular vectors
        3.5E-16    9.5E-16    2.6E-15    2.6E-15

 Error estimates for the right singular vectors
        3.5E-16    9.5E-16    2.6E-15    4.4E-15

Source

    Program dgesdd_example

!     DGESDD Example Program Text

!     Copyright 2017, Numerical Algorithms Group Ltd. http://www.nag.com

!     .. Use Statements ..
      Use lapack_example_aux, Only: nagf_file_print_matrix_real_gen
      Use lapack_interfaces, Only: ddisna, dgesdd
      Use lapack_precision, Only: dp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter :: nb = 64, nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=dp) :: eps, serrbd
      Integer :: i, ifail, info, lda, ldu, lwork, m, n
!     .. Local Arrays ..
      Real (Kind=dp), Allocatable :: a(:, :), rcondu(:), rcondv(:), s(:), &
        u(:, :), uerrbd(:), verrbd(:), work(:)
      Real (Kind=dp) :: dummy(1, 1)
      Integer, Allocatable :: iwork(:)
!     .. Intrinsic Procedures ..
      Intrinsic :: epsilon, max, min, nint
!     .. Executable Statements ..
      Write (nout, *) 'DGESDD Example Program Results'
      Write (nout, *)
!     Skip heading in data file
      Read (nin, *)
      Read (nin, *) m, n
      lda = m
      ldu = m
      Allocate (a(lda,n), rcondu(m), rcondv(m), s(m), u(ldu,m), uerrbd(m), &
        verrbd(m), iwork(8*min(m,n)))

!     Use routine workspace query to get optimal workspace.
      lwork = -1
      Call dgesdd('Overwrite A by tranpose(V)', m, n, a, lda, s, u, ldu, &
        dummy, 1, dummy, lwork, iwork, info)

!     Make sure that there is enough workspace for block size nb.
      lwork = max((5*m+9)*m+n+nb*(m+n), nint(dummy(1,1)))
      Allocate (work(lwork))

!     Read the m by n matrix A from data file

      Read (nin, *)(a(i,1:n), i=1, m)

!     Compute the singular values and left and right singular vectors
!     of A (A = U*S*(V**T), m.le.n)

      Call dgesdd('Overwrite A by tranpose(V)', m, n, a, lda, s, u, ldu, &
        dummy, 1, work, lwork, iwork, info)

      If (info==0) Then

!       Print solution

        Write (nout, *) 'Singular values'
        Write (nout, 100) s(1:m)
        Flush (nout)

!       Normalize so that u(1,j)>=0
        Do i = 1, m
          If (u(1,i)<0.0_dp) Then
            u(1:m, i) = -u(1:m, i)
            a(i, 1:n) = -a(i, 1:n)
          End If
        End Do
!       ifail: behaviour on error exit
!              =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
        ifail = 0
        Call nagf_file_print_matrix_real_gen('General', ' ', m, m, u, ldu, &
          'Left singular vectors', ifail)

        Write (nout, *)
        Flush (nout)

        Call nagf_file_print_matrix_real_gen('General', ' ', m, n, a, lda, &
          'Right singular vectors by row '//'(first m rows of V**T)', ifail)

!       Get the machine precision, EPS and compute the approximate
!       error bound for the computed singular values.  Note that for
!       the 2-norm, S(1) = norm(A)

        eps = epsilon(1.0E0_dp)
        serrbd = eps*s(1)

!       Call DDISNA to estimate reciprocal condition
!       numbers for the singular vectors

        Call ddisna('Left', m, n, s, rcondu, info)
        Call ddisna('Right', m, n, s, rcondv, info)

!       Compute the error estimates for the singular vectors

        Do i = 1, m
          uerrbd(i) = serrbd/rcondu(i)
          verrbd(i) = serrbd/rcondv(i)
        End Do

!       Print the approximate error bounds for the singular values
!       and vectors

        Write (nout, *)
        Write (nout, *) 'Error estimate for the singular values'
        Write (nout, 110) serrbd
        Write (nout, *)
        Write (nout, *) 'Error estimates for the left singular vectors'
        Write (nout, 110) uerrbd(1:m)
        Write (nout, *)
        Write (nout, *) 'Error estimates for the right singular vectors'
        Write (nout, 110) verrbd(1:m)
      Else
        Write (nout, 120) 'Failure in DGESDD. INFO =', info
      End If

100   Format (3X, (8F8.4))
110   Format (4X, 1P, 6E11.1)
120   Format (1X, A, I4)
    End Program
Full documentation of DGESDD


DGESVD example

Real Singular Value Decomposition: Singular value decomposition of a real matrix, and, optionally, left and/or right singular vectors

 To find the singular values and left and right singular vectors of the 6 by 4matrix

together with approximate error bounds for the computed singular values andvectors.

The example program for DGESDD illustrates finding a singular valuedecomposition for the case [image].

Data

DGESVD Example Program Data

   6      4                   :Values of M and N

   2.27  -1.54   1.15  -1.94
   0.28  -1.67   0.94  -0.78
  -0.48  -3.09   0.99  -0.21
   1.07   1.22   0.79   0.63
  -2.35   2.93  -1.45   2.30
   0.62  -7.39   1.03  -2.57  :End of matrix A

   1.0    1.0    1.0    1.0
   1.0    1.0                 :RHS b(1:m)

Result

 DGESVD Example Program Results

 Singular values of A:
         9.9966        3.6831        1.3569        0.5000

 Least squares solution:
        -0.0563       -0.1700        0.8202        0.5545

 Norm of Residual:
         1.7472

Source

    Program dgesvd_example

!     DGESVD Example Program Text

!     Copyright 2017, Numerical Algorithms Group Ltd. http://www.nag.com

!     .. Use Statements ..
      Use lapack_interfaces, Only: dgesvd
      Use lapack_precision, Only: dp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter :: nb = 64, nin = 5, nout = 6, prerr = 0
!     .. Local Scalars ..
      Integer :: i, info, lda, ldu, ldvt, lwork, m, n
!     .. Local Arrays ..
      Real (Kind=dp), Allocatable :: a(:, :), a_copy(:, :), b(:), s(:), &
        u(:, :), vt(:, :), work(:)
      Real (Kind=dp) :: dummy(1, 1)
!     .. Intrinsic Procedures ..
      Intrinsic :: max, min, nint
!     .. Executable Statements ..
      Write (nout, *) 'DGESVD Example Program Results'
      Write (nout, *)
!     Skip heading in data file
      Read (nin, *)
      Read (nin, *) m, n
      lda = m
      ldu = m
      ldvt = n
      Allocate (a(lda,n), a_copy(m,n), s(n), vt(ldvt,n), u(ldu,m), b(m))

!     Read the m by n matrix A from data file
      Read (nin, *)(a(i,1:n), i=1, m)

!     Read the right hand side of the linear system
      Read (nin, *) b(1:m)

      a_copy(1:m, 1:n) = a(1:m, 1:n)

!     Use routine workspace query to get optimal workspace.
      lwork = -1
      Call dgesvd('A', 'S', m, n, a, lda, s, u, ldu, vt, ldvt, dummy, lwork, &
        info)

!     Make sure that there is enough workspace for block size nb.
      lwork = max(m+4*n+nb*(m+n), nint(dummy(1,1)))
      Allocate (work(lwork))

!     Compute the singular values and left and right singular vectors
!     of A.

      Call dgesvd('A', 'S', m, n, a, lda, s, u, ldu, vt, ldvt, work, lwork, &
        info)

      If (info/=0) Then
        Write (nout, 100) 'Failure in DGESVD. INFO =', info
100     Format (1X, A, I4)
        Go To 120
      End If

!     Print the significant singular values of A

      Write (nout, *) 'Singular values of A:'
      Write (nout, 110) s(1:min(m,n))
110   Format (1X, 4(3X,F11.4))

      If (prerr>0) Then
        Call compute_error_bounds(m, n, s)
      End If

      If (m>n) Then
!       Compute V*Inv(S)*U^T * b to get least squares solution.
        Call compute_least_squares(m, n, a_copy, m, u, ldu, vt, ldvt, s, b)
      End If

120   Continue

    Contains
      Subroutine compute_least_squares(m, n, a, lda, u, ldu, vt, ldvt, s, b)

!       .. Use Statements ..
        Use blas_interfaces, Only: dgemv, dnrm2
!       .. Implicit None Statement ..
        Implicit None
!       .. Scalar Arguments ..
        Integer, Intent (In) :: lda, ldu, ldvt, m, n
!       .. Array Arguments ..
        Real (Kind=dp), Intent (In) :: a(lda, n), s(n), u(ldu, m), vt(ldvt, n)
        Real (Kind=dp), Intent (Inout) :: b(m)
!       .. Local Scalars ..
        Real (Kind=dp) :: alpha, beta, norm
!       .. Local Arrays ..
        Real (Kind=dp), Allocatable :: x(:), y(:)
!       .. Intrinsic Procedures ..
        Intrinsic :: allocated
!       .. Executable Statements ..
        Allocate (x(n), y(n))

!       Compute V*Inv(S)*U^T * b to get least squares solution.

!       y = U^T b
        alpha = 1._dp
        beta = 0._dp
        Call dgemv('T', m, n, alpha, u, ldu, b, 1, beta, y, 1)

        y(1:n) = y(1:n)/s(1:n)

!       x = V y
        Call dgemv('T', n, n, alpha, vt, ldvt, y, 1, beta, x, 1)

        Write (nout, *)
        Write (nout, *) 'Least squares solution:'
        Write (nout, 100) x(1:n)

!       Find norm of residual ||b-Ax||.
        alpha = -1._dp
        beta = 1._dp
        Call dgemv('N', m, n, alpha, a, lda, x, 1, beta, b, 1)

        norm = dnrm2(m, b, 1)

        Write (nout, *)
        Write (nout, *) 'Norm of Residual:'
        Write (nout, 100) norm

        If (allocated(x)) Then
          Deallocate (x)
        End If
        If (allocated(y)) Then
          Deallocate (y)
        End If

100     Format (1X, 4(3X,F11.4))

      End Subroutine

      Subroutine compute_error_bounds(m, n, s)

!       Error estimates for singular values and vectors is computed
!       and printed here.

!       .. Use Statements ..
        Use lapack_interfaces, Only: ddisna
        Use lapack_precision, Only: dp
!       .. Implicit None Statement ..
        Implicit None
!       .. Scalar Arguments ..
        Integer, Intent (In) :: m, n
!       .. Array Arguments ..
        Real (Kind=dp), Intent (In) :: s(n)
!       .. Local Scalars ..
        Real (Kind=dp) :: eps, serrbd
        Integer :: i, info
!       .. Local Arrays ..
        Real (Kind=dp), Allocatable :: rcondu(:), rcondv(:), uerrbd(:), &
          verrbd(:)
!       .. Intrinsic Procedures ..
        Intrinsic :: epsilon
!       .. Executable Statements ..
        Allocate (rcondu(n), rcondv(n), uerrbd(n), verrbd(n))

!       Get the machine precision, EPS and compute the approximate
!       error bound for the computed singular values.  Note that for
!       the 2-norm, S(1) = norm(A)

        eps = epsilon(1.0E0_dp)
        serrbd = eps*s(1)

!       Call DDISNA to estimate reciprocal condition
!       numbers for the singular vectors

        Call ddisna('Left', m, n, s, rcondu, info)
        Call ddisna('Right', m, n, s, rcondv, info)

!       Compute the error estimates for the singular vectors

        Do i = 1, n
          uerrbd(i) = serrbd/rcondu(i)
          verrbd(i) = serrbd/rcondv(i)
        End Do

!       Print the approximate error bounds for the singular values
!       and vectors

        Write (nout, *)
        Write (nout, *) 'Error estimate for the singular values'
        Write (nout, 100) serrbd
        Write (nout, *)
        Write (nout, *) 'Error estimates for the left singular vectors'
        Write (nout, 100) uerrbd(1:n)
        Write (nout, *)
        Write (nout, *) 'Error estimates for the right singular vectors'
        Write (nout, 100) verrbd(1:n)

100     Format (4X, 1P, 6E11.1)

      End Subroutine

    End Program
Full documentation of DGESVD


DGESVDX example

Real Singular Value Decomposition: Computes all or selected singular values of the singular value decomposition of a real general matrix, optionally computing the corresponding left and right singular vectors

Data

DGESVDX Example Program Data

   6      4                   : Values of m and n

   2.27  -1.54   1.15  -1.94
   0.28  -1.67   0.94  -0.78
  -0.48  -3.09   0.99  -0.21
   1.07   1.22   0.79   0.63
  -2.35   2.93  -1.45   2.30
   0.62  -7.39   1.03  -2.57  : End of matrix A

   1.0    1.0    1.0    1.0
   1.0    1.0                 : RHS b(1:m)

   'V'                        : range
   1.00   4.00                : (vl,vu) or (il,iu)

Result

 DGESVDX Example Program Results

 Singular values of A:
         3.6831        1.3569

 Estimates given as multiples of machine precision
 Error estimate for the singular values
              4

 Error estimates for the left singular vectors
              2          3

 Error estimates for the right singular vectors
              2          2

Source

    Program dgesvdx_example

!     DGESVDX Example Program Text

!     Copyright 2017, Numerical Algorithms Group Ltd. http://www.nag.com

!     .. Use Statements ..
      Use lapack_interfaces, Only: dgesvdx
      Use lapack_precision, Only: dp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=dp) :: vl, vu
      Integer :: i, il, info, iu, lda, ldu, ldvt, lwork, m, n, ns
      Character (1) :: range
!     .. Local Arrays ..
      Real (Kind=dp), Allocatable :: a(:, :), a_copy(:, :), b(:), s(:), &
        u(:, :), vt(:, :), work(:)
      Real (Kind=dp) :: dummy(1, 1)
      Integer, Allocatable :: iwork(:)
!     .. Intrinsic Procedures ..
      Intrinsic :: nint
!     .. Executable Statements ..
      Write (nout, *) 'DGESVDX Example Program Results'
      Write (nout, *)
!     Skip heading in data file
      Read (nin, *)
      Read (nin, *) m, n
      lda = m
      ldu = m
      ldvt = n
      Allocate (a(lda,n), a_copy(m,n), s(n), vt(ldvt,n), u(ldu,m), b(m), &
        iwork(12*m))

!     Read the m by n matrix A from data file
      Read (nin, *)(a(i,1:n), i=1, m)

!     Read the right hand side of the linear system
      Read (nin, *) b(1:m)

!     Read range for selected singular values
      Read (nin, *) range

      If (range=='I' .Or. range=='i') Then
        Read (nin, *) il, iu
      Else If (range=='V' .Or. range=='v') Then
        Read (nin, *) vl, vu
      End If

      a_copy(1:m, 1:n) = a(1:m, 1:n)

!     Use routine workspace query to get optimal workspace.
      lwork = -1
      Call dgesvdx('V', 'V', range, m, n, a, lda, vl, vu, il, iu, ns, s, u, &
        ldu, vt, ldvt, dummy, lwork, iwork, info)

!     Make sure that there is enough workspace for block size nb.
      lwork = nint(dummy(1,1))
      Allocate (work(lwork))

!     Compute the singular values and left and right singular vectors
!     of A.

      Call dgesvdx('V', 'V', range, m, n, a, lda, vl, vu, il, iu, ns, s, u, &
        ldu, vt, ldvt, work, lwork, iwork, info)

      If (info/=0) Then
        Write (nout, 100) 'Failure in DGESVDX. INFO =', info
100     Format (1X, A, I4)
        Go To 120
      End If

!     Print the selected singular values of A

      Write (nout, *) 'Singular values of A:'
      Write (nout, 110) s(1:ns)
110   Format (1X, 4(3X,F11.4))

      Call compute_error_bounds(m, ns, s)

      If (m>n .And. ns==n) Then
!       Compute V*Inv(S)*U^T * b to get least squares solution.
        Call compute_least_squares(m, n, a_copy, m, u, ldu, vt, ldvt, s, b)
      End If

120   Continue

    Contains
      Subroutine compute_least_squares(m, n, a, lda, u, ldu, vt, ldvt, s, b)

!       .. Use Statements ..
        Use blas_interfaces, Only: dgemv, dnrm2
!       .. Implicit None Statement ..
        Implicit None
!       .. Scalar Arguments ..
        Integer, Intent (In) :: lda, ldu, ldvt, m, n
!       .. Array Arguments ..
        Real (Kind=dp), Intent (In) :: a(lda, n), s(n), u(ldu, m), vt(ldvt, n)
        Real (Kind=dp), Intent (Inout) :: b(m)
!       .. Local Scalars ..
        Real (Kind=dp) :: alpha, beta, norm
!       .. Local Arrays ..
        Real (Kind=dp), Allocatable :: x(:), y(:)
!       .. Intrinsic Procedures ..
        Intrinsic :: allocated
!       .. Executable Statements ..
        Allocate (x(n), y(n))

!       Compute V*Inv(S)*U^T * b to get least squares solution.

!       y = U^T b
        alpha = 1._dp
        beta = 0._dp
        Call dgemv('T', m, n, alpha, u, ldu, b, 1, beta, y, 1)

        y(1:n) = y(1:n)/s(1:n)

!       x = V y
        Call dgemv('T', n, n, alpha, vt, ldvt, y, 1, beta, x, 1)

        Write (nout, *)
        Write (nout, *) 'Least squares solution:'
        Write (nout, 100) x(1:n)

!       Find norm of residual ||b-Ax||.
        alpha = -1._dp
        beta = 1._dp
        Call dgemv('N', m, n, alpha, a, lda, x, 1, beta, b, 1)

        norm = dnrm2(m, b, 1)

        Write (nout, *)
        Write (nout, *) 'Norm of Residual:'
        Write (nout, 100) norm

        If (allocated(x)) Then
          Deallocate (x)
        End If
        If (allocated(y)) Then
          Deallocate (y)
        End If

100     Format (1X, 4(3X,F11.4))

      End Subroutine

      Subroutine compute_error_bounds(m, n, s)

!       Error estimates for singular values and vectors is computed
!       and printed here.

!       .. Use Statements ..
        Use lapack_interfaces, Only: ddisna
        Use lapack_precision, Only: dp
!       .. Implicit None Statement ..
        Implicit None
!       .. Scalar Arguments ..
        Integer, Intent (In) :: m, n
!       .. Array Arguments ..
        Real (Kind=dp), Intent (In) :: s(n)
!       .. Local Scalars ..
        Real (Kind=dp) :: eps, serrbd
        Integer :: i, info
!       .. Local Arrays ..
        Real (Kind=dp), Allocatable :: rcondu(:), rcondv(:), uerrbd(:), &
          verrbd(:)
!       .. Intrinsic Procedures ..
        Intrinsic :: epsilon
!       .. Executable Statements ..
        Allocate (rcondu(n), rcondv(n), uerrbd(n), verrbd(n))

!       Get the machine precision, EPS and compute the approximate
!       error bound for the computed singular values.  Note that for
!       the 2-norm, S(1) = norm(A)

        eps = epsilon(1.0E0_dp)
        serrbd = eps*s(1)

!       Call DDISNA to estimate reciprocal condition
!       numbers for the singular vectors

        Call ddisna('Left', m, n, s, rcondu, info)
        Call ddisna('Right', m, n, s, rcondv, info)

!       Compute the error estimates for the singular vectors

        Do i = 1, n
          uerrbd(i) = serrbd/rcondu(i)
          verrbd(i) = serrbd/rcondv(i)
        End Do

!       Print the approximate error bounds for the singular values
!       and vectors

        Write (nout, *)
        Write (nout, *) 'Estimates given as multiples of machine precision'
        Write (nout, *) 'Error estimate for the singular values'
        Write (nout, 100) nint(serrbd/epsilon(1.0E0_dp))
        Write (nout, *)
        Write (nout, *) 'Error estimates for the left singular vectors'
        Write (nout, 100) nint(uerrbd(1:n)/epsilon(1.0E0_dp))
        Write (nout, *)
        Write (nout, *) 'Error estimates for the right singular vectors'
        Write (nout, 100) nint(verrbd(1:n)/epsilon(1.0E0_dp))

100     Format (4X, 6I11)

      End Subroutine

    End Program
Full documentation of DGESVDX


LAPACK:Complex Singular Value Decomposition

Next: Real Generalized Singular Value Decomposition Up: LAPACK Routines by Subject Previous: Real Singular Value Decomposition

Complex Singular Value Decomposition

  • ZGESDD : Singular value decomposition (by divide-and-conquer) of a complex matrix, and, optionally, left and/or right singular vectors
  • ZGESVD : Singular value decomposition of a complex matrix, and, optionally, left and/or right singular vectors
  • ZGESVDX : Computes all or selected singular values of the singular value decomposition of a complex general matrix, optionally computing the corresponding left and right singular vectors


ZGESDD example

Complex Singular Value Decomposition: Singular value decomposition (by divide-and-conquer) of a complex matrix, and, optionally, left and/or right singular vectors

 To find the singular values and left and right singular vectors of the 4 by 6matrix

together with approximate error bounds for the computed singular values andvectors.

The example program for ZGESVD illustrates finding a singular valuedecomposition for the case [image].

Data

ZGESDD Example Program Data

   4             6                         : m and n

 ( 0.96, 0.81) (-0.98,-1.98) ( 0.62, 0.46)
 (-0.37,-0.38) ( 0.83,-0.51) ( 1.08, 0.28)

 (-0.03,-0.96) (-1.20,-0.19) ( 1.01,-0.02)
 ( 0.19, 0.54) ( 0.20,-0.01) ( 0.20, 0.12)

 (-0.91,-2.06) (-0.66,-0.42) ( 0.63, 0.17)
 (-0.98, 0.36) (-0.17, 0.46) (-0.07,-1.23)

 (-0.05,-0.41) (-0.81,-0.56) (-1.11,-0.60)
 ( 0.22, 0.20) ( 1.47,-1.59) ( 0.26,-0.26) : Matrix A(1:m,1:n)

 ( 1.00, 0.00) ( 1.00, 0.00) ( 1.00, 0.00)
 ( 1.00, 0.00)                             : RHS b(1:n)

Result

 ZGESDD Example Program Results

 Singular values of A:
         3.9994        3.0003        1.9944        0.9995

 Minimum norm solution:
    ( -0.4024,  0.3777)
    ( -0.2272,  0.3626)
    (  0.1704, -0.1532)
    (  0.2125,  0.0781)
    (  0.2041,  0.2236)
    (  0.2766, -0.1517)

 Norm of Solution:
         0.8846

 Norm of Residual:
         0.0000

Source

    Program zgesdd_example

!     ZGESDD Example Program Text

!     Copyright 2017, Numerical Algorithms Group Ltd. http://www.nag.com

!     .. Use Statements ..
      Use lapack_interfaces, Only: zgesdd
      Use lapack_precision, Only: dp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter :: nb = 64, nin = 5, nout = 6, prerr = 0
!     .. Local Scalars ..
      Integer :: i, info, lda, ldu, ldvt, lwork, m, n
!     .. Local Arrays ..
      Complex (Kind=dp), Allocatable :: a(:, :), a_copy(:, :), b(:), u(:, :), &
        vt(:, :), work(:)
      Complex (Kind=dp) :: dummy(1, 1)
      Real (Kind=dp), Allocatable :: rwork(:), s(:)
      Integer, Allocatable :: iwork(:)
!     .. Intrinsic Procedures ..
      Intrinsic :: max, min, nint, real
!     .. Executable Statements ..
      Write (nout, *) 'ZGESDD Example Program Results'
      Write (nout, *)
!     Skip heading in data file
      Read (nin, *)
      Read (nin, *) m, n
      lda = m
      ldu = m
      ldvt = n
      Allocate (a(lda,n), a_copy(m,n), s(m), u(ldu,m), vt(ldvt,n), b(m), &
        rwork((5*m+7)*n), iwork(8*m))

!     Read the m by n matrix A from data file
      Read (nin, *)(a(i,1:n), i=1, m)

!     Read the right hand side of the linear system
      Read (nin, *) b(1:m)

      a_copy(1:m, 1:n) = a(1:m, 1:n)

!     Use routine workspace query to get optimal workspace.
      lwork = -1
      Call zgesdd('A', m, n, a, lda, s, u, ldu, vt, ldvt, dummy, lwork, rwork, &
        iwork, info)

!     Make sure that there is enough workspace for block size nb.
      lwork = max((2*m+2)*m+2*n+nb*(m+n), nint(real(dummy(1,1))))
      Allocate (work(lwork))

!     Compute the singular values and left and right singular vectors
!     of A.

      Call zgesdd('A', m, n, a, lda, s, u, ldu, vt, ldvt, work, lwork, rwork, &
        iwork, info)

      If (info/=0) Then
        Write (nout, 100) 'Failure in ZGESDD. INFO =', info
100     Format (1X, A, I4)
        Go To 120
      End If

!     Print the significant singular values of A

      Write (nout, *) 'Singular values of A:'
      Write (nout, 110) s(1:min(m,n))
110   Format (1X, 4(3X,F11.4))

      If (prerr>0) Then
        Call compute_error_bounds(m, n, s)
      End If

      If (m<n) Then
!       Compute V*Inv(S)*U^T * b to get minimum norm solution.
        Call compute_minimum_norm(m, n, a_copy, m, u, ldu, vt, ldvt, s, b)
      End If

120   Continue

    Contains
      Subroutine compute_minimum_norm(m, n, a, lda, u, ldu, vt, ldvt, s, b)

!       .. Use Statements ..
        Use blas_interfaces, Only: dznrm2, zgemv
!       .. Implicit None Statement ..
        Implicit None
!       .. Scalar Arguments ..
        Integer, Intent (In) :: lda, ldu, ldvt, m, n
!       .. Array Arguments ..
        Complex (Kind=dp), Intent (In) :: a(lda, n), u(ldu, m), vt(ldvt, n)
        Complex (Kind=dp), Intent (Inout) :: b(m)
        Real (Kind=dp), Intent (In) :: s(m)
!       .. Local Scalars ..
        Complex (Kind=dp) :: alpha, beta
        Real (Kind=dp) :: norm
!       .. Local Arrays ..
        Complex (Kind=dp), Allocatable :: x(:), y(:)
!       .. Intrinsic Procedures ..
        Intrinsic :: allocated, cmplx
!       .. Executable Statements ..
        Allocate (x(n), y(m))

!       Compute V*Inv(S)*U^H * b to get least squares solution.

!       y = U^H b
        alpha = cmplx(1.0_dp, 0.0_dp, kind=dp)
        beta = cmplx(0.0_dp, 0.0_dp, kind=dp)
        Call zgemv('C', m, m, alpha, u, ldu, b, 1, beta, y, 1)

        y(1:m) = y(1:m)/s(1:m)

!       x = V y
        Call zgemv('C', m, n, alpha, vt, ldvt, y, 1, beta, x, 1)

        Write (nout, *)
        Write (nout, *) 'Minimum norm solution:'
        Write (nout, 100) x(1:n)

        norm = dznrm2(n, x, 1)

        Write (nout, *)
        Write (nout, *) 'Norm of Solution:'
        Write (nout, 110) norm

!       Find norm of residual ||b-Ax||, should be zero.
        alpha = cmplx(-1.0_dp, 0.0_dp, kind=dp)
        beta = cmplx(1._dp, 0.0_dp, kind=dp)
        Call zgemv('N', m, n, alpha, a, lda, x, 1, beta, b, 1)

        norm = dznrm2(m, b, 1)

        Write (nout, *)
        Write (nout, *) 'Norm of Residual:'
        Write (nout, 110) norm

        If (allocated(x)) Then
          Deallocate (x)
        End If
        If (allocated(y)) Then
          Deallocate (y)
        End If

100     Format (4X, '(', F8.4, ',', F8.4, ')')
110     Format (4X, F11.4)

      End Subroutine

      Subroutine compute_error_bounds(m, n, s)

!       Error estimates for singular values and vectors is computed
!       and printed here.

!       .. Use Statements ..
        Use lapack_interfaces, Only: ddisna
        Use lapack_precision, Only: dp
!       .. Implicit None Statement ..
        Implicit None
!       .. Scalar Arguments ..
        Integer, Intent (In) :: m, n
!       .. Array Arguments ..
        Real (Kind=dp), Intent (In) :: s(m)
!       .. Local Scalars ..
        Real (Kind=dp) :: eps, serrbd
        Integer :: i, info
!       .. Local Arrays ..
        Real (Kind=dp), Allocatable :: rcondu(:), rcondv(:), uerrbd(:), &
          verrbd(:)
!       .. Intrinsic Procedures ..
        Intrinsic :: epsilon
!       .. Executable Statements ..
        Allocate (rcondu(n), rcondv(n), uerrbd(n), verrbd(n))

!       Get the machine precision, EPS and compute the approximate
!       error bound for the computed singular values.  Note that for
!       the 2-norm, S(1) = norm(A)

        eps = epsilon(1.0E0_dp)
        serrbd = eps*s(1)

!       Call DDISNA to estimate reciprocal condition
!       numbers for the singular vectors

        Call ddisna('Left', m, n, s, rcondu, info)
        Call ddisna('Right', m, n, s, rcondv, info)

!       Compute the error estimates for the singular vectors

        Do i = 1, n
          uerrbd(i) = serrbd/rcondu(i)
          verrbd(i) = serrbd/rcondv(i)
        End Do

!       Print the approximate error bounds for the singular values
!       and vectors

        Write (nout, *)
        Write (nout, *) 'Error estimate for the singular values'
        Write (nout, 100) serrbd
        Write (nout, *)
        Write (nout, *) 'Error estimates for the left singular vectors'
        Write (nout, 100) uerrbd(1:n)
        Write (nout, *)
        Write (nout, *) 'Error estimates for the right singular vectors'
        Write (nout, 100) verrbd(1:n)

100     Format (4X, 1P, 6E11.1)

      End Subroutine

    End Program
Full documentation of ZGESDD


ZGESVD example

Complex Singular Value Decomposition: Singular value decomposition of a complex matrix, and, optionally, left and/or right singular vectors

 To find the singular values and left and right singular vectors of the 6 by 4matrix

together with approximate error bounds for the computed singular values andvectors.

The example program for ZGESDD illustrates finding a singular valuedecomposition for the case [image].

Data

ZGESVD Example Program Data

   6             4                                       : m and n

 ( 0.96,-0.81) (-0.03, 0.96) (-0.91, 2.06) (-0.05, 0.41)
 (-0.98, 1.98) (-1.20, 0.19) (-0.66, 0.42) (-0.81, 0.56)
 ( 0.62,-0.46) ( 1.01, 0.02) ( 0.63,-0.17) (-1.11, 0.60)
 (-0.37, 0.38) ( 0.19,-0.54) (-0.98,-0.36) ( 0.22,-0.20)
 ( 0.83, 0.51) ( 0.20, 0.01) (-0.17,-0.46) ( 1.47, 1.59)
 ( 1.08,-0.28) ( 0.20,-0.12) (-0.07, 1.23) ( 0.26, 0.26) : Matrix A(1:m,1:n)

 ( 1.00, 0.00) ( 1.00, 0.00) ( 1.00, 0.00)
 ( 1.00, 0.00) ( 1.00, 0.00) ( 1.00, 0.00)               : RHS b(1:n)

Result

 ZGESVD Example Program Results

 Singular values of A:
         3.9994        3.0003        1.9944        0.9995

 Least squares solution:
    ( -0.0719, -0.2761)
    (  0.6796,  0.4326)
    ( -0.3832, -0.5447)
    (  0.0096, -0.3489)

 Norm of Residual:
         1.5266

Source

    Program zgesvd_example

!     ZGESVD Example Program Text

!     Copyright 2017, Numerical Algorithms Group Ltd. http://www.nag.com

!     .. Use Statements ..
      Use lapack_interfaces, Only: zgesvd
      Use lapack_precision, Only: dp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter :: nb = 64, nin = 5, nout = 6, prerr = 0
!     .. Local Scalars ..
      Integer :: i, info, lda, ldu, ldvt, lwork, m, n
!     .. Local Arrays ..
      Complex (Kind=dp), Allocatable :: a(:, :), a_copy(:, :), b(:), u(:, :), &
        vt(:, :), work(:)
      Complex (Kind=dp) :: dummy(1, 1)
      Real (Kind=dp), Allocatable :: rwork(:), s(:)
!     .. Intrinsic Procedures ..
      Intrinsic :: max, min, nint, real
!     .. Executable Statements ..
      Write (nout, *) 'ZGESVD Example Program Results'
      Write (nout, *)
!     Skip heading in data file
      Read (nin, *)
      Read (nin, *) m, n
      lda = m
      ldu = m
      ldvt = n
      Allocate (a(lda,n), a_copy(m,n), s(n), u(ldu,m), vt(ldvt,n), b(m), &
        rwork(5*n))

!     Read the m by n matrix A from data file
      Read (nin, *)(a(i,1:n), i=1, m)

!     Read the right hand side of the linear system
      Read (nin, *) b(1:m)

      a_copy(1:m, 1:n) = a(1:m, 1:n)

!     Use routine workspace query to get optimal workspace.
      lwork = -1
      Call zgesvd('A', 'S', m, n, a, lda, s, u, ldu, vt, ldvt, dummy, lwork, &
        rwork, info)

!     Make sure that there is enough workspace for block size nb.
      lwork = max(m+3*n+nb*(m+n), nint(real(dummy(1,1))))
      Allocate (work(lwork))

!     Compute the singular values and left and right singular vectors
!     of A.

      Call zgesvd('A', 'S', m, n, a, lda, s, u, ldu, vt, ldvt, work, lwork, &
        rwork, info)

      If (info/=0) Then
        Write (nout, 100) 'Failure in ZGESVD. INFO =', info
100     Format (1X, A, I4)
        Go To 120
      End If

!     Print the significant singular values of A

      Write (nout, *) 'Singular values of A:'
      Write (nout, 110) s(1:min(m,n))
110   Format (1X, 4(3X,F11.4))

      If (prerr>0) Then
        Call compute_error_bounds(m, n, s)
      End If

      If (m>n) Then
!       Compute V*Inv(S)*U^T * b to get least squares solution.
        Call compute_least_squares(m, n, a_copy, m, u, ldu, vt, ldvt, s, b)
      End If

120   Continue

    Contains
      Subroutine compute_least_squares(m, n, a, lda, u, ldu, vt, ldvt, s, b)

!       .. Use Statements ..
        Use blas_interfaces, Only: dznrm2, zgemv
!       .. Implicit None Statement ..
        Implicit None
!       .. Scalar Arguments ..
        Integer, Intent (In) :: lda, ldu, ldvt, m, n
!       .. Array Arguments ..
        Complex (Kind=dp), Intent (In) :: a(lda, n), u(ldu, m), vt(ldvt, n)
        Complex (Kind=dp), Intent (Inout) :: b(m)
        Real (Kind=dp), Intent (In) :: s(n)
!       .. Local Scalars ..
        Complex (Kind=dp) :: alpha, beta
        Real (Kind=dp) :: norm
!       .. Local Arrays ..
        Complex (Kind=dp), Allocatable :: x(:), y(:)
!       .. Intrinsic Procedures ..
        Intrinsic :: allocated, cmplx
!       .. Executable Statements ..
        Allocate (x(n), y(n))

!       Compute V*Inv(S)*U^H * b to get least squares solution.

!       y = U^T b
        alpha = cmplx(1.0_dp, 0.0_dp, kind=dp)
        beta = cmplx(0.0_dp, 0.0_dp, kind=dp)
        Call zgemv('C', m, n, alpha, u, ldu, b, 1, beta, y, 1)

        y(1:n) = y(1:n)/s(1:n)

!       x = V y
        Call zgemv('C', n, n, alpha, vt, ldvt, y, 1, beta, x, 1)

        Write (nout, *)
        Write (nout, *) 'Least squares solution:'
        Write (nout, 100) x(1:n)

!       Find norm of residual ||b-Ax||.
        alpha = cmplx(-1.0_dp, 0.0_dp, kind=dp)
        beta = cmplx(1._dp, 0.0_dp, kind=dp)
        Call zgemv('N', m, n, alpha, a, lda, x, 1, beta, b, 1)

        norm = dznrm2(m, b, 1)

        Write (nout, *)
        Write (nout, *) 'Norm of Residual:'
        Write (nout, 110) norm

        If (allocated(x)) Then
          Deallocate (x)
        End If
        If (allocated(y)) Then
          Deallocate (y)
        End If

100     Format (4X, '(', F8.4, ',', F8.4, ')')
110     Format (4X, F11.4)

      End Subroutine

      Subroutine compute_error_bounds(m, n, s)

!       Error estimates for singular values and vectors is computed
!       and printed here.

!       .. Use Statements ..
        Use lapack_interfaces, Only: ddisna
        Use lapack_precision, Only: dp
!       .. Implicit None Statement ..
        Implicit None
!       .. Scalar Arguments ..
        Integer, Intent (In) :: m, n
!       .. Array Arguments ..
        Real (Kind=dp), Intent (In) :: s(n)
!       .. Local Scalars ..
        Real (Kind=dp) :: eps, serrbd
        Integer :: i, info
!       .. Local Arrays ..
        Real (Kind=dp), Allocatable :: rcondu(:), rcondv(:), uerrbd(:), &
          verrbd(:)
!       .. Intrinsic Procedures ..
        Intrinsic :: epsilon
!       .. Executable Statements ..
        Allocate (rcondu(n), rcondv(n), uerrbd(n), verrbd(n))

!       Get the machine precision, EPS and compute the approximate
!       error bound for the computed singular values.  Note that for
!       the 2-norm, S(1) = norm(A)

        eps = epsilon(1.0E0_dp)
        serrbd = eps*s(1)

!       Call DDISNA to estimate reciprocal condition
!       numbers for the singular vectors

        Call ddisna('Left', m, n, s, rcondu, info)
        Call ddisna('Right', m, n, s, rcondv, info)

!       Compute the error estimates for the singular vectors

        Do i = 1, n
          uerrbd(i) = serrbd/rcondu(i)
          verrbd(i) = serrbd/rcondv(i)
        End Do

!       Print the approximate error bounds for the singular values
!       and vectors

        Write (nout, *)
        Write (nout, *) 'Error estimate for the singular values'
        Write (nout, 100) serrbd
        Write (nout, *)
        Write (nout, *) 'Error estimates for the left singular vectors'
        Write (nout, 100) uerrbd(1:n)
        Write (nout, *)
        Write (nout, *) 'Error estimates for the right singular vectors'
        Write (nout, 100) verrbd(1:n)

100     Format (4X, 1P, 6E11.1)

      End Subroutine

    End Program
Full documentation of ZGESVD


ZGESVDX example

Complex Singular Value Decomposition: Computes all or selected singular values of the singular value decomposition of a complex general matrix, optionally computing the corresponding left and right singular vectors

Data

ZGESVDX Example Program Data

   6             4                                       : m and n

 ( 0.96,-0.81) (-0.03, 0.96) (-0.91, 2.06) (-0.05, 0.41)
 (-0.98, 1.98) (-1.20, 0.19) (-0.66, 0.42) (-0.81, 0.56)
 ( 0.62,-0.46) ( 1.01, 0.02) ( 0.63,-0.17) (-1.11, 0.60)
 (-0.37, 0.38) ( 0.19,-0.54) (-0.98,-0.36) ( 0.22,-0.20)
 ( 0.83, 0.51) ( 0.20, 0.01) (-0.17,-0.46) ( 1.47, 1.59)
 ( 1.08,-0.28) ( 0.20,-0.12) (-0.07, 1.23) ( 0.26, 0.26) : matrix A

 'V'                                                     : range
 1.00   4.00

Result

 ZGESVDX Example Program Results

 Singular values of A:
         3.9994        3.0003        1.9944

 Error estimates (as multiples of machine precision):
   for the singular values
              4

   for the left singular vectors
              4          4          4

   for the right singular vectors
              4          4          4

Source

    Program zgesvdx_example

!     ZGESVDX Example Program Text

!     Copyright 2017, Numerical Algorithms Group Ltd. http://www.nag.com

!     .. Use Statements ..
      Use lapack_interfaces, Only: zgesvdx
      Use lapack_precision, Only: dp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=dp) :: vl, vu
      Integer :: i, il, info, iu, lda, ldu, ldvt, liwork, lrwork, lwork, m, n, &
        ns
      Character (1) :: range
!     .. Local Arrays ..
      Complex (Kind=dp), Allocatable :: a(:, :), u(:, :), vt(:, :), work(:)
      Real (Kind=dp), Allocatable :: rwork(:), s(:)
      Integer, Allocatable :: iwork(:)
!     .. Intrinsic Procedures ..
      Intrinsic :: nint
!     .. Executable Statements ..
      Write (nout, *) 'ZGESVDX Example Program Results'
      Write (nout, *)
!     Skip heading in data file
      Read (nin, *)
      Read (nin, *) m, n
      lda = m
      ldu = m
      ldvt = n
      lwork = 2*n**2 + 4*n
      lrwork = 2*n*2 + 34*n
      liwork = 12*n
      Allocate (a(lda,n), s(n), vt(ldvt,n), u(ldu,m), iwork(liwork), &
        work(lwork), rwork(lrwork))

!     Read the m by n matrix A from data file
      Read (nin, *)(a(i,1:n), i=1, m)

!     Read range for selected singular values
      Read (nin, *) range

      If (range=='I' .Or. range=='i') Then
        Read (nin, *) il, iu
      Else If (range=='V' .Or. range=='v') Then
        Read (nin, *) vl, vu
      End If

!     Compute the singular values and left and right singular vectors
!     of A.

      Call zgesvdx('V', 'V', range, m, n, a, lda, vl, vu, il, iu, ns, s, u, &
        ldu, vt, ldvt, work, lwork, rwork, iwork, info)

      If (info/=0) Then
        Write (nout, 100) 'Failure in ZGESVDX. INFO =', info
100     Format (1X, A, I4)
        Go To 120
      End If

!     Print the selected singular values of A

      Write (nout, *) 'Singular values of A:'
      Write (nout, 110) s(1:ns)
110   Format (1X, 4(3X,F11.4))

      Call compute_error_bounds(m, ns, s)

120   Continue

    Contains
      Subroutine compute_error_bounds(m, n, s)

!       Error estimates for singular values and vectors is computed
!       and printed here.

!       .. Use Statements ..
        Use lapack_interfaces, Only: ddisna
        Use lapack_precision, Only: dp
!       .. Implicit None Statement ..
        Implicit None
!       .. Scalar Arguments ..
        Integer, Intent (In) :: m, n
!       .. Array Arguments ..
        Real (Kind=dp), Intent (In) :: s(n)
!       .. Local Scalars ..
        Real (Kind=dp) :: eps, serrbd
        Integer :: i, info
!       .. Local Arrays ..
        Real (Kind=dp), Allocatable :: rcondu(:), rcondv(:), uerrbd(:), &
          verrbd(:)
!       .. Intrinsic Procedures ..
        Intrinsic :: epsilon
!       .. Executable Statements ..
        Allocate (rcondu(n), rcondv(n), uerrbd(n), verrbd(n))

!       Get the machine precision, EPS and compute the approximate
!       error bound for the computed singular values.  Note that for
!       the 2-norm, S(1) = norm(A)

        eps = epsilon(1.0E0_dp)
        serrbd = eps*s(1)

!       Call DDISNA to estimate reciprocal condition
!       numbers for the singular vectors

        Call ddisna('Left', m, n, s, rcondu, info)
        Call ddisna('Right', m, n, s, rcondv, info)

!       Compute the error estimates for the singular vectors

        Do i = 1, n
          uerrbd(i) = serrbd/rcondu(i)
          verrbd(i) = serrbd/rcondv(i)
        End Do

!       Print the approximate error bounds for the singular values
!       and vectors

        Write (nout, *)
        Write (nout, *) 'Error estimates (as multiples of machine precision):'
        Write (nout, *) '  for the singular values'
        Write (nout, 100) nint(serrbd/epsilon(1.0E0_dp))
        Write (nout, *)
        Write (nout, *) '  for the left singular vectors'
        Write (nout, 100) nint(uerrbd(1:n)/epsilon(1.0E0_dp))
        Write (nout, *)
        Write (nout, *) '  for the right singular vectors'
        Write (nout, 100) nint(verrbd(1:n)/epsilon(1.0E0_dp))

100     Format (4X, 6I11)

      End Subroutine

    End Program
Full documentation of ZGESVDX


LAPACK:Real Generalized Singular Value Decomposition

Next: Complex Generalized Singular Value Decomposition Up: LAPACK Routines by Subject Previous: Complex Singular Value Decomposition

Real Generalized Singular Value Decomposition

  • DGGSVD : Computes the generalized singular value decomposition of a real matrix pair
  • DGGSVD3 : Computes, using BLAS-3, the generalized singular value decomposition of a real matrix pair


DGGSVD example

Real Generalized Singular Value Decomposition: Computes the generalized singular value decomposition of a real matrix pair

 To find the generalized singular value decomposition

where

together with estimates for the condition number of $ R$ and the error bound forthe computed generalized singular values.

The example program assumes that [image], and would need slight modificationif this is not the case.

Data

DGGSVD Example Program Data

  4    3    2   :Values of M, N and P

  1.0  2.0  3.0
  3.0  2.0  1.0
  4.0  5.0  6.0
  7.0  8.0  8.0 :End of matrix A

 -2.0 -3.0  3.0
  4.0  6.0  5.0 :End of matrix B

Result

 DGGSVD Example Program Results

 Number of infinite generalized singular values (K)
     1
 Number of finite generalized singular values (L)
     2
 Numerical rank of (A**T B**T)**T (K+L)
     3

 Finite generalized singular values
     1.3151E+00  8.0185E-02

 Orthogonal matrix U
              1           2           3           4
 1  -1.3484E-01  5.2524E-01 -2.0924E-01  8.1373E-01
 2   6.7420E-01 -5.2213E-01 -3.8886E-01  3.4874E-01
 3   2.6968E-01  5.2757E-01 -6.5782E-01 -4.6499E-01
 4   6.7420E-01  4.1615E-01  6.1014E-01  1.5127E-15

 Orthogonal matrix V
              1           2
 1   3.5539E-01 -9.3472E-01
 2   9.3472E-01  3.5539E-01

 Orthogonal matrix Q
              1           2           3
 1  -8.3205E-01 -9.4633E-02 -5.4657E-01
 2   5.5470E-01 -1.4195E-01 -8.1985E-01
 3   0.0000E+00 -9.8534E-01  1.7060E-01

 Nonsingular upper triangular matrix R
              1           2           3
 1  -2.0569E+00 -9.0121E+00 -9.3705E+00
 2              -1.0882E+01 -7.2688E+00
 3                          -6.0405E+00

 Estimate of reciprocal condition number for R
     4.2E-02

 Error estimate for the generalized singular values
     5.3E-15

Source

    Program dggsvd_example

!     DGGSVD Example Program Text

!     Copyright 2017, Numerical Algorithms Group Ltd. http://www.nag.com

!     .. Use Statements ..
      Use lapack_example_aux, Only: nagf_file_print_matrix_real_gen_comp
      Use lapack_interfaces, Only: dggsvd3, dtrcon
      Use lapack_precision, Only: dp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=dp) :: eps, rcond, serrbd
      Integer :: i, ifail, info, irank, j, k, l, lda, ldb, ldq, ldu, ldv, &
        lwork, m, n, p
!     .. Local Arrays ..
      Real (Kind=dp), Allocatable :: a(:, :), alpha(:), b(:, :), beta(:), &
        q(:, :), u(:, :), v(:, :), work(:)
      Integer, Allocatable :: iwork(:)
      Character (1) :: clabs(1), rlabs(1)
!     .. Intrinsic Procedures ..
      Intrinsic :: epsilon
!     .. Executable Statements ..
      Write (nout, *) 'DGGSVD Example Program Results'
      Write (nout, *)
      Flush (nout)
!     Skip heading in data file
      Read (nin, *)
      Read (nin, *) m, n, p
      lda = m
      ldb = p
      ldq = n
      ldu = m
      ldv = p
      Allocate (a(lda,n), alpha(n), b(ldb,n), beta(n), q(ldq,n), u(ldu,m), &
        v(ldv,p), work(m+3*n), iwork(n))

!     Read the m by n matrix A and p by n matrix B from data file

      Read (nin, *)(a(i,1:n), i=1, m)
      Read (nin, *)(b(i,1:n), i=1, p)

!     Compute the generalized singular value decomposition of (A, B)
!     (A = U*D1*(0 R)*(Q**T), B = V*D2*(0 R)*(Q**T), m>=n)
      lwork = m + 3*n
      Call dggsvd3('U', 'V', 'Q', m, n, p, k, l, a, lda, b, ldb, alpha, beta, &
        u, ldu, v, ldv, q, ldq, work, lwork, iwork, info)

      If (info==0) Then

!       Print solution

        irank = k + l
        Write (nout, *) 'Number of infinite generalized singular values (K)'
        Write (nout, 100) k
        Write (nout, *) 'Number of finite generalized singular values (L)'
        Write (nout, 100) l
        Write (nout, *) 'Numerical rank of (A**T B**T)**T (K+L)'
        Write (nout, 100) irank
        Write (nout, *)
        Write (nout, *) 'Finite generalized singular values'
        Write (nout, 110)(alpha(j)/beta(j), j=k+1, irank)

        Write (nout, *)
        Flush (nout)

!       ifail: behaviour on error exit
!              =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
        ifail = 0
        Call nagf_file_print_matrix_real_gen_comp('General', ' ', m, m, u, &
          ldu, '1P,E12.4', 'Orthogonal matrix U', 'Integer', rlabs, 'Integer', &
          clabs, 80, 0, ifail)

        Write (nout, *)
        Flush (nout)

        Call nagf_file_print_matrix_real_gen_comp('General', ' ', p, p, v, &
          ldv, '1P,E12.4', 'Orthogonal matrix V', 'Integer', rlabs, 'Integer', &
          clabs, 80, 0, ifail)

        Write (nout, *)
        Flush (nout)

        Call nagf_file_print_matrix_real_gen_comp('General', ' ', n, n, q, &
          ldq, '1P,E12.4', 'Orthogonal matrix Q', 'Integer', rlabs, 'Integer', &
          clabs, 80, 0, ifail)

        Write (nout, *)
        Flush (nout)

        Call nagf_file_print_matrix_real_gen_comp('Upper triangular', &
          'Non-unit', irank, irank, a(1,n-irank+1), lda, '1P,E12.4', &
          'Nonsingular upper triangular matrix R', 'Integer', rlabs, &
          'Integer', clabs, 80, 0, ifail)

!       Call DTRCON to estimate the reciprocal condition
!       number of R

        Call dtrcon('Infinity-norm', 'Upper', 'Non-unit', irank, &
          a(1,n-irank+1), lda, rcond, work, iwork, info)

        Write (nout, *)
        Write (nout, *) 'Estimate of reciprocal condition number for R'
        Write (nout, 120) rcond
        Write (nout, *)

!       So long as irank = n, get the machine precision, eps, and
!       compute the approximate error bound for the computed
!       generalized singular values

        If (irank==n) Then
          eps = epsilon(1.0E0_dp)
          serrbd = eps/rcond
          Write (nout, *) 'Error estimate for the generalized singular values'
          Write (nout, 120) serrbd
        Else
          Write (nout, *) '(A**T B**T)**T is not of full rank'
        End If
      Else
        Write (nout, 130) 'Failure in DGGSVD3. INFO =', info
      End If

100   Format (1X, I5)
110   Format (3X, 8(1P,E12.4))
120   Format (1X, 1P, E11.1)
130   Format (1X, A, I4)
    End Program
Full documentation of DGGSVD


DGGSVD3 example

Real Generalized Singular Value Decomposition: Computes, using BLAS-3, the generalized singular value decomposition of a real matrix pair

Data

DGGSVD3 Example Program Data

  4    3    2   :Values of M, N and P

  1.0  2.0  3.0
  3.0  2.0  1.0
  4.0  5.0  6.0
  7.0  8.0  8.0 :End of matrix A

 -2.0 -3.0  3.0
  4.0  6.0  5.0 :End of matrix B

Result

 DGGSVD3 Example Program Results

 Number of infinite generalized singular values (K)
     1
 Number of finite generalized singular values (L)
     2
 Numerical rank of (A**T B**T)**T (K+L)
     3

 Finite generalized singular values
     1.3151E+00  8.0185E-02

 Orthogonal matrix U
              1           2           3           4
 1  -1.3484E-01  5.2524E-01 -2.0924E-01  8.1373E-01
 2   6.7420E-01 -5.2213E-01 -3.8886E-01  3.4874E-01
 3   2.6968E-01  5.2757E-01 -6.5782E-01 -4.6499E-01
 4   6.7420E-01  4.1615E-01  6.1014E-01  1.5127E-15

 Orthogonal matrix V
              1           2
 1   3.5539E-01 -9.3472E-01
 2   9.3472E-01  3.5539E-01

 Orthogonal matrix Q
              1           2           3
 1  -8.3205E-01 -9.4633E-02 -5.4657E-01
 2   5.5470E-01 -1.4195E-01 -8.1985E-01
 3   0.0000E+00 -9.8534E-01  1.7060E-01

 Nonsingular upper triangular matrix R
              1           2           3
 1  -2.0569E+00 -9.0121E+00 -9.3705E+00
 2              -1.0882E+01 -7.2688E+00
 3                          -6.0405E+00

 Estimate of reciprocal condition number for R
     4.2E-02

 Error estimate for the generalized singular values
     5.3E-15

Source

    Program dggsvd3_example

!     DGGSVD3 Example Program Text

!     Copyright 2017, Numerical Algorithms Group Ltd. http://www.nag.com

!     .. Use Statements ..
      Use lapack_example_aux, Only: nagf_file_print_matrix_real_gen_comp
      Use lapack_interfaces, Only: dggsvd3, dtrcon
      Use lapack_precision, Only: dp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=dp) :: eps, rcond, serrbd
      Integer :: i, ifail, info, irank, j, k, l, lda, ldb, ldq, ldu, ldv, &
        lwork, m, n, p
!     .. Local Arrays ..
      Real (Kind=dp), Allocatable :: a(:, :), alpha(:), b(:, :), beta(:), &
        q(:, :), u(:, :), v(:, :), work(:)
      Real (Kind=dp) :: wdum(1)
      Integer, Allocatable :: iwork(:)
      Character (1) :: clabs(1), rlabs(1)
!     .. Intrinsic Procedures ..
      Intrinsic :: epsilon, nint
!     .. Executable Statements ..
      Write (nout, *) 'DGGSVD3 Example Program Results'
      Write (nout, *)
      Flush (nout)
!     Skip heading in data file
      Read (nin, *)
      Read (nin, *) m, n, p
      lda = m
      ldb = p
      ldq = n
      ldu = m
      ldv = p
      Allocate (a(lda,n), alpha(n), b(ldb,n), beta(n), q(ldq,n), u(ldu,m), &
        v(ldv,p), iwork(n))

!     Perform workspace query to get optimal size of work
      lwork = -1
      Call dggsvd3('U', 'V', 'Q', m, n, p, k, l, a, lda, b, ldb, alpha, beta, &
        u, ldu, v, ldv, q, ldq, wdum, lwork, iwork, info)
      lwork = nint(wdum(1))
      Allocate (work(lwork))

!     Read the m by n matrix A and p by n matrix B from data file

      Read (nin, *)(a(i,1:n), i=1, m)
      Read (nin, *)(b(i,1:n), i=1, p)

!     Compute the generalized singular value decomposition of (A, B)
!     (A = U*D1*(0 R)*(Q**T), B = V*D2*(0 R)*(Q**T), m>=n)
      Call dggsvd3('U', 'V', 'Q', m, n, p, k, l, a, lda, b, ldb, alpha, beta, &
        u, ldu, v, ldv, q, ldq, work, lwork, iwork, info)

      If (info==0) Then

!       Print solution

        irank = k + l
        Write (nout, *) 'Number of infinite generalized singular values (K)'
        Write (nout, 100) k
        Write (nout, *) 'Number of finite generalized singular values (L)'
        Write (nout, 100) l
        Write (nout, *) 'Numerical rank of (A**T B**T)**T (K+L)'
        Write (nout, 100) irank
        Write (nout, *)
        Write (nout, *) 'Finite generalized singular values'
        Write (nout, 110)(alpha(j)/beta(j), j=k+1, irank)

        Write (nout, *)
        Flush (nout)

!       ifail: behaviour on error exit
!              =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
        ifail = 0
        Call nagf_file_print_matrix_real_gen_comp('General', ' ', m, m, u, &
          ldu, '1P,E12.4', 'Orthogonal matrix U', 'Integer', rlabs, 'Integer', &
          clabs, 80, 0, ifail)

        Write (nout, *)
        Flush (nout)

        Call nagf_file_print_matrix_real_gen_comp('General', ' ', p, p, v, &
          ldv, '1P,E12.4', 'Orthogonal matrix V', 'Integer', rlabs, 'Integer', &
          clabs, 80, 0, ifail)

        Write (nout, *)
        Flush (nout)

        Call nagf_file_print_matrix_real_gen_comp('General', ' ', n, n, q, &
          ldq, '1P,E12.4', 'Orthogonal matrix Q', 'Integer', rlabs, 'Integer', &
          clabs, 80, 0, ifail)

        Write (nout, *)
        Flush (nout)

        Call nagf_file_print_matrix_real_gen_comp('Upper triangular', &
          'Non-unit', irank, irank, a(1,n-irank+1), lda, '1P,E12.4', &
          'Nonsingular upper triangular matrix R', 'Integer', rlabs, &
          'Integer', clabs, 80, 0, ifail)

!       Call DTRCON to estimate the reciprocal condition
!       number of R

        Call dtrcon('Infinity-norm', 'Upper', 'Non-unit', irank, &
          a(1,n-irank+1), lda, rcond, work, iwork, info)

        Write (nout, *)
        Write (nout, *) 'Estimate of reciprocal condition number for R'
        Write (nout, 120) rcond
        Write (nout, *)

!       So long as irank = n, get the machine precision, eps, and
!       compute the approximate error bound for the computed
!       generalized singular values

        If (irank==n) Then
          eps = epsilon(1.0E0_dp)
          serrbd = eps/rcond
          Write (nout, *) 'Error estimate for the generalized singular values'
          Write (nout, 120) serrbd
        Else
          Write (nout, *) '(A**T B**T)**T is not of full rank'
        End If
      Else
        Write (nout, 130) 'Failure in DGGSVD3. INFO =', info
      End If

100   Format (1X, I5)
110   Format (3X, 8(1P,E12.4))
120   Format (1X, 1P, E11.1)
130   Format (1X, A, I4)
    End Program
Full documentation of DGGSVD3


LAPACK:Complex Generalized Singular Value Decomposition

Next: Real QR Factorization Up: LAPACK Routines by Subject Previous: Real Generalized Singular Value Decomposition

Complex Generalized Singular Value Decomposition

  • ZGGSVD : Computes the generalized singular value decomposition of a complex matrix pair
  • ZGGSVD3 : Computes, using BLAS-3, the generalized singular value decomposition of a complex matrix pair


ZGGSVD example

Complex Generalized Singular Value Decomposition: Computes the generalized singular value decomposition of a complex matrix pair

 To find the generalized singular value decomposition

where

and

together with estimates for the condition number of $ R$ and the error bound forthe computed generalized singular values.

The example program assumes that [image], and would need slight modificationif this is not the case.

Data

ZGGSVD Example Program Data

  6             4             2                         :Values of M, N and P

( 0.96,-0.81) (-0.03, 0.96) (-0.91, 2.06) (-0.05, 0.41)
(-0.98, 1.98) (-1.20, 0.19) (-0.66, 0.42) (-0.81, 0.56)
( 0.62,-0.46) ( 1.01, 0.02) ( 0.63,-0.17) (-1.11, 0.60)
( 0.37, 0.38) ( 0.19,-0.54) (-0.98,-0.36) ( 0.22,-0.20)
( 0.83, 0.51) ( 0.20, 0.01) (-0.17,-0.46) ( 1.47, 1.59)
( 1.08,-0.28) ( 0.20,-0.12) (-0.07, 1.23) ( 0.26, 0.26) :End of matrix A

( 1.00, 0.00) ( 0.00, 0.00) (-1.00, 0.00) ( 0.00, 0.00)
( 0.00, 0.00) ( 1.00, 0.00) ( 0.00, 0.00) (-1.00, 0.00) :End of matrix B

Result

 ZGGSVD Example Program Results

 Number of infinite generalized singular values (K)
     2
 Number of finite generalized singular values (L)
     2
 Numerical rank of (A**H B**H)**H (K+L)
     4

 Finite generalized singular values
       2.0720E+00   1.1058E+00

 Unitary matrix U
                              1                           2
 1  ( -1.3038E-02, -3.2595E-01) ( -1.4039E-01, -2.6167E-01)
 2  (  4.2764E-01, -6.2582E-01) (  8.6298E-02, -3.8174E-02)
 3  ( -3.2595E-01,  1.6428E-01) (  3.8163E-01, -1.8219E-01)
 4  (  1.5906E-01, -5.2151E-03) ( -2.8207E-01,  1.9732E-01)
 5  ( -1.7210E-01, -1.3038E-02) ( -5.0942E-01, -5.0319E-01)
 6  ( -2.6336E-01, -2.4772E-01) ( -1.0861E-01,  2.8474E-01)

                              3                           4
 1  (  2.5177E-01, -7.9789E-01) ( -5.0956E-02, -2.1750E-01)
 2  ( -3.2188E-01,  1.6112E-01) (  1.1979E-01,  1.6319E-01)
 3  (  1.3231E-01, -1.4565E-02) ( -5.0671E-01,  1.8615E-01)
 4  (  2.1598E-01,  1.8813E-01) ( -4.0163E-01,  2.6787E-01)
 5  (  3.6488E-02,  2.0316E-01) (  1.9271E-01,  1.5574E-01)
 6  (  1.0906E-01, -1.2712E-01) ( -8.8159E-02,  5.6169E-01)

                              5                           6
 1  ( -4.5947E-02,  1.4052E-04) ( -5.2773E-02, -2.2492E-01)
 2  ( -8.0311E-02, -4.3605E-01) ( -3.8117E-02, -2.1907E-01)
 3  (  5.9714E-02, -5.8974E-01) ( -1.3850E-01, -9.0941E-02)
 4  ( -4.6443E-02,  3.0864E-01) ( -3.7354E-01, -5.5148E-01)
 5  (  5.7843E-01, -1.2439E-01) ( -1.8815E-02, -5.5686E-02)
 6  (  1.5763E-02,  4.7130E-02) (  6.5007E-01,  4.9173E-03)

 Unitary matrix V
                              1                           2
 1  (  9.8930E-01,  1.9041E-19) ( -1.1461E-01,  9.0250E-02)
 2  ( -1.1461E-01, -9.0250E-02) ( -9.8930E-01,  1.9041E-19)

 Unitary matrix Q
                              1                           2
 1  (  7.0711E-01,  0.0000E+00) (  0.0000E+00,  0.0000E+00)
 2  (  0.0000E+00,  0.0000E+00) (  7.0711E-01,  0.0000E+00)
 3  (  7.0711E-01,  0.0000E+00) (  0.0000E+00,  0.0000E+00)
 4  (  0.0000E+00,  0.0000E+00) (  7.0711E-01,  0.0000E+00)

                              3                           4
 1  (  6.9954E-01,  4.7274E-19) (  8.1044E-02, -6.3817E-02)
 2  ( -8.1044E-02, -6.3817E-02) (  6.9954E-01, -4.7274E-19)
 3  ( -6.9954E-01, -4.7274E-19) ( -8.1044E-02,  6.3817E-02)
 4  (  8.1044E-02,  6.3817E-02) ( -6.9954E-01,  4.7274E-19)

 Nonsingular upper triangular matrix R
                              1                           2
 1  ( -2.7118E+00,  0.0000E+00) ( -1.4390E+00, -1.0315E+00)
 2                              ( -1.8583E+00,  0.0000E+00)
 3
 4

                              3                           4
 1  ( -7.6930E-02,  1.3613E+00) ( -2.8137E-01, -3.2425E-02)
 2  ( -1.0760E+00,  3.1016E-02) (  1.3292E+00,  3.6772E-01)
 3  (  3.2537E+00,  0.0000E+00) ( -6.3858E-17,  6.3858E-17)
 4                              ( -2.1084E+00,  0.0000E+00)

 Estimate of reciprocal condition number for R
       1.3E-01

 Error estimate for the generalized singular values
       1.7E-15

Source

    Program zggsvd_example

!     ZGGSVD Example Program Text

!     Copyright 2017, Numerical Algorithms Group Ltd. http://www.nag.com

!     .. Use Statements ..
      Use lapack_example_aux, Only: nagf_file_print_matrix_complex_gen_comp
      Use lapack_interfaces, Only: zggsvd3, ztrcon
      Use lapack_precision, Only: dp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=dp) :: eps, rcond, serrbd
      Integer :: i, ifail, info, irank, j, k, l, lda, ldb, ldq, ldu, ldv, &
        lwork, m, n, p
!     .. Local Arrays ..
      Complex (Kind=dp), Allocatable :: a(:, :), b(:, :), q(:, :), u(:, :), &
        v(:, :), work(:)
      Real (Kind=dp), Allocatable :: alpha(:), beta(:), rwork(:)
      Integer, Allocatable :: iwork(:)
      Character (1) :: clabs(1), rlabs(1)
!     .. Intrinsic Procedures ..
      Intrinsic :: epsilon
!     .. Executable Statements ..
      Write (nout, *) 'ZGGSVD Example Program Results'
      Write (nout, *)
      Flush (nout)
!     Skip heading in data file
      Read (nin, *)
      Read (nin, *) m, n, p
      lda = m
      ldb = p
      ldq = n
      ldu = m
      ldv = p
      Allocate (a(lda,n), b(ldb,n), q(ldq,n), u(ldu,m), v(ldv,p), work(m+3*n), &
        alpha(n), beta(n), rwork(2*n), iwork(n))

!     Read the m by n matrix A and p by n matrix B from data file

      Read (nin, *)(a(i,1:n), i=1, m)
      Read (nin, *)(b(i,1:n), i=1, p)

!     Compute the generalized singular value decomposition of (A, B)
!     (A = U*D1*(0 R)*(Q**H), B = V*D2*(0 R)*(Q**H), m.ge.n)
      lwork = m + 3*n
      Call zggsvd3('U', 'V', 'Q', m, n, p, k, l, a, lda, b, ldb, alpha, beta, &
        u, ldu, v, ldv, q, ldq, work, lwork, rwork, iwork, info)

      If (info==0) Then

!       Print solution

        irank = k + l
        Write (nout, *) 'Number of infinite generalized singular values (K)'
        Write (nout, 100) k
        Write (nout, *) 'Number of finite generalized singular values (L)'
        Write (nout, 100) l
        Write (nout, *) 'Numerical rank of (A**H B**H)**H (K+L)'
        Write (nout, 100) irank
        Write (nout, *)
        Write (nout, *) 'Finite generalized singular values'
        Write (nout, 110)(alpha(j)/beta(j), j=k+1, irank)

        Write (nout, *)
        Flush (nout)

!       ifail: behaviour on error exit
!              =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
        ifail = 0
        Call nagf_file_print_matrix_complex_gen_comp('General', ' ', m, m, u, &
          ldu, 'Bracketed', '1P,E12.4', 'Unitary matrix U', 'Integer', rlabs, &
          'Integer', clabs, 80, 0, ifail)

        Write (nout, *)
        Flush (nout)

        Call nagf_file_print_matrix_complex_gen_comp('General', ' ', p, p, v, &
          ldv, 'Bracketed', '1P,E12.4', 'Unitary matrix V', 'Integer', rlabs, &
          'Integer', clabs, 80, 0, ifail)

        Write (nout, *)
        Flush (nout)

        Call nagf_file_print_matrix_complex_gen_comp('General', ' ', n, n, q, &
          ldq, 'Bracketed', '1P,E12.4', 'Unitary matrix Q', 'Integer', rlabs, &
          'Integer', clabs, 80, 0, ifail)

        Write (nout, *)
        Flush (nout)

        Call nagf_file_print_matrix_complex_gen_comp('Upper triangular', &
          'Non-unit', irank, irank, a(1,n-irank+1), lda, 'Bracketed', &
          '1P,E12.4', 'Nonsingular upper triangular matrix R', 'Integer', &
          rlabs, 'Integer', clabs, 80, 0, ifail)

!       Call ZTRCON to estimate the reciprocal condition
!       number of R

        Call ztrcon('Infinity-norm', 'Upper', 'Non-unit', irank, &
          a(1,n-irank+1), lda, rcond, work, rwork, info)

        Write (nout, *)
        Write (nout, *) 'Estimate of reciprocal condition number for R'
        Write (nout, 120) rcond
        Write (nout, *)

!       So long as irank = n, get the machine precision, eps, and
!       compute the approximate error bound for the computed
!       generalized singular values

        If (irank==n) Then
          eps = epsilon(1.0E0_dp)
          serrbd = eps/rcond
          Write (nout, *) 'Error estimate for the generalized singular values'
          Write (nout, 120) serrbd
        Else
          Write (nout, *) '(A**H B**H)**H is not of full rank'
        End If
      Else
        Write (nout, 130) 'Failure in ZGGSVD3. INFO =', info
      End If

100   Format (1X, I5)
110   Format (4X, 8(1P,E13.4))
120   Format (3X, 1P, E11.1)
130   Format (1X, A, I4)
    End Program
Full documentation of ZGGSVD


ZGGSVD3 example

Complex Generalized Singular Value Decomposition: Computes, using BLAS-3, the generalized singular value decomposition of a complex matrix pair

Data

ZGGSVD3 Example Program Data

  6             4             2                         :Values of M, N and P

( 0.96,-0.81) (-0.03, 0.96) (-0.91, 2.06) (-0.05, 0.41)
(-0.98, 1.98) (-1.20, 0.19) (-0.66, 0.42) (-0.81, 0.56)
( 0.62,-0.46) ( 1.01, 0.02) ( 0.63,-0.17) (-1.11, 0.60)
( 0.37, 0.38) ( 0.19,-0.54) (-0.98,-0.36) ( 0.22,-0.20)
( 0.83, 0.51) ( 0.20, 0.01) (-0.17,-0.46) ( 1.47, 1.59)
( 1.08,-0.28) ( 0.20,-0.12) (-0.07, 1.23) ( 0.26, 0.26) :End of matrix A

( 1.00, 0.00) ( 0.00, 0.00) (-1.00, 0.00) ( 0.00, 0.00)
( 0.00, 0.00) ( 1.00, 0.00) ( 0.00, 0.00) (-1.00, 0.00) :End of matrix B

Result

 ZGGSVD3 Example Program Results

 Number of infinite generalized singular values (K)
     2
 Number of finite generalized singular values (L)
     2
 Numerical rank of (A**T B**T)**T (K+L)
     4

 Finite generalized singular values
       2.0720E+00   1.1058E+00

 Unitary matrix U
                              1                           2
 1  ( -1.3038E-02, -3.2595E-01) ( -1.4039E-01, -2.6167E-01)
 2  (  4.2764E-01, -6.2582E-01) (  8.6298E-02, -3.8174E-02)
 3  ( -3.2595E-01,  1.6428E-01) (  3.8163E-01, -1.8219E-01)
 4  (  1.5906E-01, -5.2151E-03) ( -2.8207E-01,  1.9732E-01)
 5  ( -1.7210E-01, -1.3038E-02) ( -5.0942E-01, -5.0319E-01)
 6  ( -2.6336E-01, -2.4772E-01) ( -1.0861E-01,  2.8474E-01)

                              3                           4
 1  (  2.5177E-01, -7.9789E-01) ( -5.0956E-02, -2.1750E-01)
 2  ( -3.2188E-01,  1.6112E-01) (  1.1979E-01,  1.6319E-01)
 3  (  1.3231E-01, -1.4565E-02) ( -5.0671E-01,  1.8615E-01)
 4  (  2.1598E-01,  1.8813E-01) ( -4.0163E-01,  2.6787E-01)
 5  (  3.6488E-02,  2.0316E-01) (  1.9271E-01,  1.5574E-01)
 6  (  1.0906E-01, -1.2712E-01) ( -8.8159E-02,  5.6169E-01)

                              5                           6
 1  ( -4.5947E-02,  1.4052E-04) ( -5.2773E-02, -2.2492E-01)
 2  ( -8.0311E-02, -4.3605E-01) ( -3.8117E-02, -2.1907E-01)
 3  (  5.9714E-02, -5.8974E-01) ( -1.3850E-01, -9.0941E-02)
 4  ( -4.6443E-02,  3.0864E-01) ( -3.7354E-01, -5.5148E-01)
 5  (  5.7843E-01, -1.2439E-01) ( -1.8815E-02, -5.5686E-02)
 6  (  1.5763E-02,  4.7130E-02) (  6.5007E-01,  4.9173E-03)

 Unitary matrix V
                              1                           2
 1  (  9.8930E-01,  1.9041E-19) ( -1.1461E-01,  9.0250E-02)
 2  ( -1.1461E-01, -9.0250E-02) ( -9.8930E-01,  1.9041E-19)

 Unitary matrix Q
                              1                           2
 1  (  7.0711E-01,  0.0000E+00) (  0.0000E+00,  0.0000E+00)
 2  (  0.0000E+00,  0.0000E+00) (  7.0711E-01,  0.0000E+00)
 3  (  7.0711E-01,  0.0000E+00) (  0.0000E+00,  0.0000E+00)
 4  (  0.0000E+00,  0.0000E+00) (  7.0711E-01,  0.0000E+00)

                              3                           4
 1  (  6.9954E-01,  4.7274E-19) (  8.1044E-02, -6.3817E-02)
 2  ( -8.1044E-02, -6.3817E-02) (  6.9954E-01, -4.7274E-19)
 3  ( -6.9954E-01, -4.7274E-19) ( -8.1044E-02,  6.3817E-02)
 4  (  8.1044E-02,  6.3817E-02) ( -6.9954E-01,  4.7274E-19)

 Nonsingular upper triangular matrix R
                              1                           2
 1  ( -2.7118E+00,  0.0000E+00) ( -1.4390E+00, -1.0315E+00)
 2                              ( -1.8583E+00,  0.0000E+00)
 3
 4

                              3                           4
 1  ( -7.6930E-02,  1.3613E+00) ( -2.8137E-01, -3.2425E-02)
 2  ( -1.0760E+00,  3.1016E-02) (  1.3292E+00,  3.6772E-01)
 3  (  3.2537E+00,  0.0000E+00) ( -6.3858E-17,  6.3858E-17)
 4                              ( -2.1084E+00,  0.0000E+00)

 Estimate of reciprocal condition number for R
       1.3E-01

 Error estimate for the generalized singular values
       1.7E-15

Source

    Program zggsvd3_example

!     ZGGSVD3 Example Program Text

!     Copyright 2017, Numerical Algorithms Group Ltd. http://www.nag.com

!     .. Use Statements ..
      Use lapack_example_aux, Only: nagf_file_print_matrix_complex_gen_comp
      Use lapack_interfaces, Only: zggsvd3, ztrcon
      Use lapack_precision, Only: dp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=dp) :: eps, rcond, serrbd
      Integer :: i, ifail, info, irank, j, k, l, lda, ldb, ldq, ldu, ldv, &
        lwork, m, n, p
!     .. Local Arrays ..
      Complex (Kind=dp), Allocatable :: a(:, :), b(:, :), q(:, :), u(:, :), &
        v(:, :), work(:)
      Complex (Kind=dp) :: wdum(1)
      Real (Kind=dp), Allocatable :: alpha(:), beta(:), rwork(:)
      Integer, Allocatable :: iwork(:)
      Character (1) :: clabs(1), rlabs(1)
!     .. Intrinsic Procedures ..
      Intrinsic :: epsilon, nint, real
!     .. Executable Statements ..
      Write (nout, *) 'ZGGSVD3 Example Program Results'
      Write (nout, *)
      Flush (nout)
!     Skip heading in data file
      Read (nin, *)
      Read (nin, *) m, n, p
      lda = m
      ldb = p
      ldq = n
      ldu = m
      ldv = p
      Allocate (a(lda,n), b(ldb,n), q(ldq,n), u(ldu,m), v(ldv,p), alpha(n), &
        beta(n), rwork(2*n), iwork(n))

!     Perform workspace query to get optimal size of work
      lwork = -1
      Call zggsvd3('U', 'V', 'Q', m, n, p, k, l, a, lda, b, ldb, alpha, beta, &
        u, ldu, v, ldv, q, ldq, wdum, lwork, rwork, iwork, info)
      lwork = nint(real(wdum(1)))
      Allocate (work(lwork))

!     Read the m by n matrix A and p by n matrix B from data file

      Read (nin, *)(a(i,1:n), i=1, m)
      Read (nin, *)(b(i,1:n), i=1, p)

!     Compute the generalized singular value decomposition of (A, B)
!     (A = U*D1*(0 R)*(Q**H), B = V*D2*(0 R)*(Q**H), m.ge.n)
      Call zggsvd3('U', 'V', 'Q', m, n, p, k, l, a, lda, b, ldb, alpha, beta, &
        u, ldu, v, ldv, q, ldq, work, lwork, rwork, iwork, info)

      If (info==0) Then

!       Print solution

        irank = k + l
        Write (nout, *) 'Number of infinite generalized singular values (K)'
        Write (nout, 100) k
        Write (nout, *) 'Number of finite generalized singular values (L)'
        Write (nout, 100) l
        Write (nout, *) 'Numerical rank of (A**T B**T)**T (K+L)'
        Write (nout, 100) irank
        Write (nout, *)
        Write (nout, *) 'Finite generalized singular values'
        Write (nout, 110)(alpha(j)/beta(j), j=k+1, irank)

        Write (nout, *)
        Flush (nout)

!       ifail: behaviour on error exit
!              =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
        ifail = 0
        Call nagf_file_print_matrix_complex_gen_comp('General', ' ', m, m, u, &
          ldu, 'Bracketed', '1P,E12.4', 'Unitary matrix U', 'Integer', rlabs, &
          'Integer', clabs, 80, 0, ifail)

        Write (nout, *)
        Flush (nout)

        Call nagf_file_print_matrix_complex_gen_comp('General', ' ', p, p, v, &
          ldv, 'Bracketed', '1P,E12.4', 'Unitary matrix V', 'Integer', rlabs, &
          'Integer', clabs, 80, 0, ifail)

        Write (nout, *)
        Flush (nout)

        Call nagf_file_print_matrix_complex_gen_comp('General', ' ', n, n, q, &
          ldq, 'Bracketed', '1P,E12.4', 'Unitary matrix Q', 'Integer', rlabs, &
          'Integer', clabs, 80, 0, ifail)

        Write (nout, *)
        Flush (nout)

        Call nagf_file_print_matrix_complex_gen_comp('Upper triangular', &
          'Non-unit', irank, irank, a(1,n-irank+1), lda, 'Bracketed', &
          '1P,E12.4', 'Nonsingular upper triangular matrix R', 'Integer', &
          rlabs, 'Integer', clabs, 80, 0, ifail)

!       Call ZTRCON to estimate the reciprocal condition
!       number of R

        Call ztrcon('Infinity-norm', 'Upper', 'Non-unit', irank, &
          a(1,n-irank+1), lda, rcond, work, rwork, info)

        Write (nout, *)
        Write (nout, *) 'Estimate of reciprocal condition number for R'
        Write (nout, 120) rcond
        Write (nout, *)

!       So long as irank = n, get the machine precision, eps, and
!       compute the approximate error bound for the computed
!       generalized singular values

        If (irank==n) Then
          eps = epsilon(1.0E0_dp)
          serrbd = eps/rcond
          Write (nout, *) 'Error estimate for the generalized singular values'
          Write (nout, 120) serrbd
        Else
          Write (nout, *) '(A**T B**T)**T is not of full rank'
        End If
      Else
        Write (nout, 130) 'Failure in ZGGSVD3. INFO =', info
      End If

100   Format (1X, I5)
110   Format (4X, 8(1P,E13.4))
120   Format (3X, 1P, E11.1)
130   Format (1X, A, I4)
    End Program
Full documentation of ZGGSVD3


LAPACK:Real QR Factorization

Next: Complex QR Factorization Up: LAPACK Routines by Subject Previous: Complex Generalized Singular Value Decomposition

Real QR Factorization

  • DGEQPF : QR factorization, with column pivoting, of real general rectangular matrix


DGEQPF example

Real QR Factorization: QR factorization, with column pivoting, of real general rectangular matrix

Data

DGEQPF Example Program Data
  6  5  2                            :Values of M, N and NRHS
 -0.09   0.14  -0.46   0.68   1.29
 -1.56   0.20   0.29   1.09   0.51
 -1.48  -0.43   0.89  -0.71  -0.96
 -1.09   0.84   0.77   2.11  -1.27
  0.08   0.55  -1.13   0.14   1.74
 -1.59  -0.72   1.06   1.24   0.34   :End of matrix A
 -0.01  -0.04
  0.04  -0.03
  0.05   0.01
 -0.03  -0.02
  0.02   0.05
 -0.06   0.07                        :End of matrix B

Result

 DGEQPF Example Program Results

 Least squares solution
          1       2
 1  -0.0370 -0.0044
 2   0.0647 -0.0335
 3   0.0000  0.0000
 4  -0.0515  0.0018
 5   0.0066  0.0102

Source

    Program dgeqpf_example

!     DGEQPF Example Program Text

!     Copyright 2017, Numerical Algorithms Group Ltd. http://www.nag.com

!     .. Use Statements ..
      Use blas_interfaces, Only: dtrsv
      Use lapack_example_aux, Only: nagf_file_print_matrix_real_gen
      Use lapack_interfaces, Only: dgeqp3, dormqr
      Use lapack_precision, Only: dp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Real (Kind=dp), Parameter :: zero = 0.0E0_dp
      Integer, Parameter :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=dp) :: tol
      Integer :: i, ifail, info, k, lda, ldb, ldx, lwork, m, n, nrhs
!     .. Local Arrays ..
      Real (Kind=dp), Allocatable :: a(:, :), b(:, :), tau(:), work(:), &
        x(:, :)
      Integer, Allocatable :: jpvt(:)
!     .. Intrinsic Procedures ..
      Intrinsic :: abs
!     .. Executable Statements ..
      Write (nout, *) 'DGEQPF Example Program Results'
!     Skip heading in data file
      Read (nin, *)
      Read (nin, *) m, n, nrhs
      lda = m
      ldb = m
      ldx = m
      lwork = 64*n
      Allocate (a(lda,n), b(ldb,nrhs), tau(n), work(lwork), x(ldx,nrhs), &
        jpvt(n))

!     Read A and B from data file

      Read (nin, *)(a(i,1:n), i=1, m)
      Read (nin, *)(b(i,1:nrhs), i=1, m)

!     Initialize JPVT to be zero so that all columns are free

      jpvt(1:n) = 0

!     Compute the QR factorization of A

      Call dgeqp3(m, n, a, lda, jpvt, tau, work, lwork, info)

!     Choose TOL to reflect the relative accuracy of the input data

      tol = 0.01E0_dp

!     Determine which columns of R to use

loop: Do k = 1, n
        If (abs(a(k,k))<=tol*abs(a(1,1))) Then
          Exit loop
        End If
      End Do loop

!     Compute C = (Q**T)*B, storing the result in B

      k = k - 1

      Call dormqr('Left', 'Transpose', m, nrhs, n, a, lda, tau, b, ldb, work, &
        lwork, info)

!     Compute least squares solution by back-substitution in R*B = C
      Do i = 1, nrhs

        Call dtrsv('Upper', 'No transpose', 'Non-Unit', k, a, lda, b(1,i), 1)

!       Set the unused elements of the I-th solution vector to zero

        b(k+1:n, i) = zero

      End Do

!     Unscramble the least squares solution stored in B

      Do i = 1, n
        x(jpvt(i), 1:nrhs) = b(i, 1:nrhs)
      End Do

!     Print least squares solution

      Write (nout, *)
      Flush (nout)

!     ifail: behaviour on error exit
!             =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
      ifail = 0
      Call nagf_file_print_matrix_real_gen('General', ' ', n, nrhs, x, ldx, &
        'Least squares solution', ifail)

    End Program
Full documentation of DGEQPF


LAPACK:Complex QR Factorization

Next: Computational Routines Up: LAPACK Routines by Subject Previous: Real QR Factorization

Complex QR Factorization

  • ZGEQPF : QR factorization, with column pivoting, of complex general rectangular matrix


ZGEQPF example

Complex QR Factorization: QR factorization, with column pivoting, of complex general rectangular matrix

Data

ZGEQPF Example Program Data
  5  4  2                                          :Values of M, N and NRHS
 ( 0.47,-0.34) (-0.40, 0.54) ( 0.60, 0.01) ( 0.80,-1.02)
 (-0.32,-0.23) (-0.05, 0.20) (-0.26,-0.44) (-0.43, 0.17)
 ( 0.35,-0.60) (-0.52,-0.34) ( 0.87,-0.11) (-0.34,-0.09)
 ( 0.89, 0.71) (-0.45,-0.45) (-0.02,-0.57) ( 1.14,-0.78)
 (-0.19, 0.06) ( 0.11,-0.85) ( 1.44, 0.80) ( 0.07, 1.14)   :End of matrix A
 (-0.85,-1.63) ( 2.49, 4.01)
 (-2.16, 3.52) (-0.14, 7.98)
 ( 4.57,-5.71) ( 8.36,-0.28)
 ( 6.38,-7.40) (-3.55, 1.29)
 ( 8.41, 9.39) (-6.72, 5.03)                               :End of matrix B

Result

 ZGEQPF Example Program Results

 Least squares solution
                    1                 2
 1  ( 0.0000, 0.0000) ( 0.0000, 0.0000)
 2  ( 2.6925, 8.0446) (-2.0563,-2.9759)
 3  ( 2.7602, 2.5455) ( 1.0588, 1.4635)
 4  ( 2.7383, 0.5123) (-1.4150, 0.2982)

Source

    Program zgeqpf_example

!     ZGEQPF Example Program Text

!     Copyright 2017, Numerical Algorithms Group Ltd. http://www.nag.com

!     .. Use Statements ..
      Use blas_interfaces, Only: ztrsv
      Use lapack_example_aux, Only: nagf_file_print_matrix_complex_gen_comp
      Use lapack_interfaces, Only: zgeqp3, zunmqr
      Use lapack_precision, Only: dp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Complex (Kind=dp), Parameter :: zero = (0.0E0_dp, 0.0E0_dp)
      Integer, Parameter :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=dp) :: tol
      Integer :: i, ifail, info, k, lda, ldb, ldx, lwork, m, n, nrhs
!     .. Local Arrays ..
      Complex (Kind=dp), Allocatable :: a(:, :), b(:, :), tau(:), work(:), &
        x(:, :)
      Real (Kind=dp), Allocatable :: rwork(:)
      Integer, Allocatable :: jpvt(:)
      Character (1) :: clabs(1), rlabs(1)
!     .. Intrinsic Procedures ..
      Intrinsic :: abs
!     .. Executable Statements ..
      Write (nout, *) 'ZGEQPF Example Program Results'
!     Skip heading in data file
      Read (nin, *)
      Read (nin, *) m, n, nrhs
      lda = m
      ldb = m
      ldx = m
      lwork = 64*n
      Allocate (a(lda,n), b(ldb,nrhs), tau(n), work(lwork), x(ldx,nrhs), &
        rwork(2*n), jpvt(n))

!     Read A and B from data file

      Read (nin, *)(a(i,1:n), i=1, m)
      Read (nin, *)(b(i,1:nrhs), i=1, m)

!     Initialize JPVT to be zero so that all columns are free

      jpvt(1:n) = 0

!     Compute the QR factorization of A
      Call zgeqp3(m, n, a, lda, jpvt, tau, work, lwork, rwork, info)

!     Choose TOL to reflect the relative accuracy of the input data

      tol = 0.01_dp

!     Determine which columns of R to use

loop: Do k = 1, n
        If (abs(a(k,k))<=tol*abs(a(1,1))) Then
          Exit loop
        End If
      End Do loop

!     Compute C = (Q**H)*B, storing the result in B

      k = k - 1

      Call zunmqr('Left', 'Conjugate Transpose', m, nrhs, k, a, lda, tau, b, &
        ldb, work, lwork, info)

!     Compute least squares solution by back-substitution in R*B = C

      Do i = 1, nrhs

        Call ztrsv('Upper', 'No transpose', 'Non-Unit', k, a, lda, b(1,i), 1)

!       Set the unused elements of the I-th solution vector to zero

        b(k+1:n, i) = zero

      End Do

!     Unscramble the least squares solution stored in B

      Do i = 1, n
        x(jpvt(i), 1:nrhs) = b(i, 1:nrhs)
      End Do

!     Print least squares solution

      Write (nout, *)
      Flush (nout)

!     ifail: behaviour on error exit
!             =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
      ifail = 0
      Call nagf_file_print_matrix_complex_gen_comp('General', ' ', n, nrhs, x, &
        ldx, 'Bracketed', 'F7.4', 'Least squares solution', 'Integer', rlabs, &
        'Integer', clabs, 80, 0, ifail)

    End Program
Full documentation of ZGEQPF


LAPACK:Computational Routines

Up: LAPACK Routines by Subject Previous: Complex QR Factorization

Computational Routines

  • DBDSDC : Computes the singular value decomposition of a real bidiagonal matrix, optionally computing the singular vectors (divide-and-conquer)
  • DBDSQR : SVD of real bidiagonal matrix reduced from real general matrix
  • DGBBRD : Reduction of real rectangular band matrix to upper bidiagonal form
  • DGBCON : Estimate condition number of real band matrix, matrix already factorized by DGBTRF
  • DGBEQU : Computes row and column scalings intended to equilibrate a real banded matrix and reduce its condition number
  • DGBRFS : Refined solution with error bounds of real band system of linear equations, multiple right-hand sides
  • DGBTRF : LU factorization of real m by n band matrix
  • DGBTRS : Solution of real band system of linear equations, multiple right-hand sides, matrix already factorized by DGBTRF
  • DGEBAL : Balance real general matrix
  • DGEBRD : Orthogonal reduction of real general rectangular matrix to bidiagonal form
  • DGECON : Estimate condition number of real matrix, matrix already factorized by DGETRF
  • DGEEQU : Computes row and column scalings intended to equilibrate a general real matrix and reduce its condition number
  • DGEHRD : Orthogonal reduction of real general matrix to upper Hessenberg form
  • DGEJSV : Computes the singular value decomposition of a real matrix, optionally computing the left and/or right singular vectors (preconditioned Jacobi)
  • DGELQF : LQ factorization of real general rectangular matrix
  • DGEQLF : QL factorization of real general rectangular matrix
  • DGEQP3 : QR factorization of real general rectangular matrix with column pivoting, using BLAS-3
  • DGEQRF : QR factorization of real general rectangular matrix
  • DGEQRT : Performs a QR factorization of real general rectangular matrix, with explicit blocking
  • DGERFS : Refined solution with error bounds of real system of linear equations, multiple right-hand sides
  • DGERQF : RQ factorization of real general rectangular matrix
  • DGESVJ : Computes the singular value decomposition of a real matrix, optionally computing the left and/or right singular vectors (fast Jacobi)
  • DGETRF : LU factorization of real m by n matrix
  • DGETRI : Inverse of real matrix, matrix already factorized by DGETRF
  • DGETRS : Solution of real system of linear equations, multiple right-hand sides, matrix already factorized by DGETRF
  • DGGQRF : Computes a generalized QR factorization of a real matrix pair
  • DGGRQF : Computes a generalized RQ factorization of a real matrix pair
  • DGGSVP3 : Produces orthogonal matrices, using BLAS-3, that simultaneously reduce the m by n matrix A and the p by n matrix B to upper triangular form
  • DGTCON : Estimates the reciprocal of the condition number of a real tridiagonal matrix using the LU factorization computed by DGTTRF
  • DGTRFS : Refined solution with error bounds of real tridiagonal system of linear equations, multiple right-hand sides
  • DGTTRF : LU factorization of real tridiagonal matrix
  • DGTTRS : Solves a real tridiagonal system of linear equations using the LU factorization computed by DGTTRF
  • DHGEQZ : Eigenvalues and generalized Schur factorization of real generalized upper Hessenberg matrix reduced from a pair of real general matrices
  • DHSEQR : Eigenvalues and Schur factorization of real upper Hessenberg matrix reduced from real general matrix
  • DOPGTR : Generate orthogonal transformation matrix from reduction to tridiagonal form determined by DSPTRD
  • DOPMTR : Apply orthogonal transformation determined by DSPTRD
  • DORCSD : Computes the CS decomposition of an orthogonal matrix partitioned into four real submatrices
  • DORGBR : Generate orthogonal transformation matrices from reduction to bidiagonal form determined by DGEBRD
  • DORGHR : Generate orthogonal transformation matrix from reduction to Hessenberg form determined by DGEHRD
  • DORGLQ : Form all or part of orthogonal Q from LQ factorization determined by DGELQF
  • DORGQL : Form all or part of orthogonal Q from QL factorization determined by DGEQLF
  • DORGQR : Form all or part of orthogonal Q from QR factorization determined by DGEQRF or DGEQPF
  • DORGRQ : Form all or part of orthogonal Q from RQ factorization determined by DGERQF
  • DORGTR : Generate orthogonal transformation matrix from reduction to tridiagonal form determined by DSYTRD
  • DORMBR : Apply orthogonal transformations from reduction to bidiagonal form determined by DGEBRD
  • DORMHR : Apply orthogonal transformation matrix from reduction to Hessenberg form determined by DGEHRD
  • DORMTR : Apply orthogonal transformation determined by DSYTRD
  • DPBCON : Estimate condition number of real symmetric positive-definite band matrix, matrix already factorized by DPBTRF
  • DPBEQU : Computes row and column scalings intended to equilibrate a real symmetric positive-definite banded matrix and reduce its condition number
  • DPBRFS : Refined solution with error bounds of real symmetric positive-definite band system of linear equations, multiple right-hand sides
  • DPBTRF : Cholesky factorization of real symmetric positive-definite band matrix
  • DPBTRS : Solution of real symmetric positive-definite band system of linear equations, multiple right-hand sides, matrix already factorized by DPBTRF
  • DPFTRF : Cholesky factorization of real symmetric positive definite matrix, Rectangular Full Packed format
  • DPFTRI : Inverse of real symmetric positive definite matrix, matrix already factorized by DPFTRF, Rectangular Full Packed format
  • DPFTRS : Solution of real symmetric positive definite system of linear equations, multiple right-hand sides, coefficient matrix already factorized by DPFTRF, Rectangular Full Packed format
  • DPOCON : Estimate condition number of real symmetric positive-definite matrix, matrix already factorized by DPOTRF
  • DPOEQU : Computes row and column scalings intended to equilibrate a real symmetric positive-definite matrix and reduce its condition number
  • DPORFS : Refined solution with error bounds of real symmetric positive-definite system of linear equations, multiple right-hand sides
  • DPOTRF : Cholesky factorization of real symmetric positive-definite matrix
  • DPOTRI : Inverse of real symmetric positive-definite matrix, matrix already factorized by DPOTRF
  • DPOTRS : Solution of real symmetric positive-definite system of linear equations, multiple right-hand sides, matrix already factorized by DPOTRF
  • DPPCON : Estimate condition number of real symmetric positive-definite matrix, matrix already factorized by DPPTRF, packed storage
  • DPPEQU : Computes row and column scalings intended to equilibrate a real symmetric positive-definite matrix and reduce its condition number, packed storage
  • DPPRFS : Refined solution with error bounds of real symmetric positive-definite system of linear equations, multiple right-hand sides, packed storage
  • DPPTRF : Cholesky factorization of real symmetric positive-definite matrix, packed storage
  • DPPTRI : Inverse of real symmetric positive-definite matrix, matrix already factorized by DPPTRF, packed storage
  • DPPTRS : Solution of real symmetric positive-definite system of linear equations, multiple right-hand sides, matrix already factorized by DPPTRF, packed storage
  • DPSTRF : Cholesky factorization of real symmetric positive semidefinite matrix
  • DPTCON : Computes the reciprocal of the condition number of a real symmetric positive-definite tridiagonal system using the L * D * L' factorization computed by DPTTRF
  • DPTEQR : All eigenvalues and eigenvectors of real symmetric positive-definite tridiagonal matrix, reduced from real symmetric positive-definite matrix
  • DPTRFS : Refined solution with error bounds of real symmetric positive-definite tridiagonal system of linear equations, multiple right-hand sides
  • DPTTRF : Computes the L * D * L' factorization of a real symmetric positive-definite tridiagonal matrix
  • DPTTRS : Solves a real symmetric positive-definite tridiagonal system using the L * D * L' factorization computed by DPTTRF
  • DSBGST : Reduction of real symmetric-definite banded generalized eigenproblem Ax = lambda Bx to standard form Cy = lambda y, such that C has the same bandwidth as A
  • DSBTRD : Orthogonal reduction of real symmetric band matrix to symmetric tridiagonal form
  • DSPCON : Estimate condition number of real symmetric indefinite matrix, matrix already factorized by DSPTRF, packed storage
  • DSPGST : Reduction to standard form of real symmetric-definite generalized eigenproblem Ax = lambda Bx, ABx = lambda x or BAx = lambda x, packed storage, B factorized by DPPTRF
  • DSPRFS : Refined solution with error bounds of real symmetric indefinite system of linear equations, multiple right-hand sides, packed storage
  • DSPTRD : Orthogonal reduction of real symmetric matrix to symmetric tridiagonal form, packed storage
  • DSPTRF : Bunch-Kaufman factorization of real symmetric indefinite matrix, packed storage
  • DSPTRI : Inverse of real symmetric indefinite matrix, matrix already factorized by DSPTRF, packed storage
  • DSPTRS : Solution of real symmetric indefinite system of linear equations, multiple right-hand sides, matrix already factorized by DSPTRF, packed storage
  • DSTEDC : Computes all eigenvalues and, optionally, eigenvectors of a real symmetric tridiagonal matrix or a matrix reduced to this form (divide-and-conquer)
  • DSTEGR : Computes all eigenvalues and, optionally, eigenvectors of a real symmetric tridiagonal matrix or a symmetric matrix reduced to this form (Relatively Robust Representations)
  • DSTEQR : All eigenvalues and eigenvectors of real symmetric tridiagonal matrix, reduced from real symmetric matrix using implicit QL or QR
  • DSTERF : All eigenvalues of real symmetric tridiagonal matrix, root-free variant of QL or QR
  • DSYCON : Estimate condition number of real symmetric indefinite matrix, matrix already factorized by DSYTRF
  • DSYGST : Reduction to standard form of real symmetric-definite generalized eigenproblem Ax = lambda Bx, ABx = lambda x or BAx = lambda x, B factorized by DPOTRF
  • DSYRFS : Refined solution with error bounds of real symmetric indefinite system of linear equations, multiple right-hand sides
  • DSYTRD : Orthogonal reduction of real symmetric matrix to symmetric tridiagonal form
  • DSYTRF : Bunch-Kaufman factorization of real symmetric indefinite matrix
  • DSYTRI : Inverse of real symmetric indefinite matrix, matrix already factorized by DSYTRF
  • DSYTRS : Solution of real symmetric indefinite system of linear equations, multiple right-hand sides, matrix already factorized by DSYTRF
  • DTBCON : Estimate condition number of real band triangular matrix
  • DTBRFS : Error bounds for solution of real band triangular system of linear equations, multiple right-hand sides
  • DTBTRS : Solution of real band triangular system of linear equations, multiple right-hand sides
  • DTFTRI : Inverse of real triangular matrix, Rectangular Full Packed format, expert driver
  • DTGEVC : Left and right eigenvectors of a pair of real upper quasi-triangular matrices
  • DTGEXC : Reorders the generalized real Schur decomposition of a real matrix pair using an orthogonal equivalence transformation
  • DTGSEN : Reorders the generalized real Schur decomposition of a real matrix pair using an orthogonal equivalence transformation, computes the generalized eigenvalues of the reordered pair and, optionally, computes the estimates of reciprocal condition numbers for eigenvalues and eigenspaces
  • DTGSJA : Computes the generalized singular value decomposition of a real upper triangular (or trapezoidal) matrix pair
  • DTGSNA : Estimates reciprocal condition numbers for specified eigenvalues and/or eigenvectors of a real matrix pair in generalized real Schur canonical form
  • DTGSYL : Solves the real-valued generalized Sylvester equation
  • DTPCON : Estimate condition number of real triangular matrix, packed storage
  • DTPQRT : QR factorization of real general triangular-pentagonal matrix
  • DTPRFS : Error bounds for solution of real triangular system of linear equations, multiple right-hand sides, packed storage
  • DTPTRI : Inverse of real triangular matrix, packed storage
  • DTPTRS : Solution of real triangular system of linear equations, multiple right-hand sides, packed storage
  • DTRCON : Estimate condition number of real triangular matrix
  • DTREXC : Reorder Schur factorization of real matrix using orthogonal similarity transformation
  • DTRRFS : Error bounds for solution of real triangular system of linear equations, multiple right-hand sides
  • DTRSEN : Reorder Schur factorization of real matrix, form orthonormal basis of right invariant subspace for selected eigenvalues, with estimates of sensitivities
  • DTRSNA : Estimates of sensitivities of selected eigenvalues and eigenvectors of real upper quasi-triangular matrix
  • DTRSYL : Solve real Sylvester matrix equation AX + XB = C, A and B are upper quasi-triangular or transposes
  • DTRTRI : Inverse of real triangular matrix
  • DTRTRS : Solution of real triangular system of linear equations, multiple right-hand sides
  • DTZRZF : Reduces a real upper trapezoidal matrix to upper triangular form
  • ZGBBRD : Reduction of complex rectangular band matrix to upper bidiagonal form
  • ZGBCON : Estimate condition number of complex band matrix, matrix already factorized by ZGBTRF
  • ZGBEQU : Computes row and column scalings intended to equilibrate a complex banded matrix and reduce its condition number
  • ZGBRFS : Refined solution with error bounds of complex band system of linear equations, multiple right-hand sides
  • ZGBTRF : LU factorization of complex m by n band matrix
  • ZGBTRS : Solution of complex band system of linear equations, multiple right-hand sides, matrix already factorized by ZGBTRF
  • ZGEBAL : Balance complex general matrix
  • ZGEBRD : Unitary reduction of complex general rectangular matrix to bidiagonal form
  • ZGECON : Estimate condition number of complex matrix, matrix already factorized by ZGETRF
  • ZGEEQU : Computes row and column scalings intended to equilibrate a general complex matrix and reduce its condition number
  • ZGEHRD : Unitary reduction of complex general matrix to upper Hessenberg form
  • ZGEJSV : Computes the singular value decomposition of a complex matrix, optionally computing the left and/or right singular vectors (preconditioned Jacobi)
  • ZGELQF : LQ factorization of complex general rectangular matrix
  • ZGEQLF : QL factorization of complex general rectangular matrix
  • ZGEQP3 : QR factorization of complex general rectangular matrix with column pivoting, using BLAS-3
  • ZGEQRF : QR factorization of complex general rectangular matrix
  • ZGEQRT : Performs a QR factorization of complex general rectangular matrix using recursive algorithm
  • ZGERFS : Refined solution with error bounds of complex system of linear equations, multiple right-hand sides
  • ZGERQF : RQ factorization of complex general rectangular matrix
  • ZGESVJ : Computes the singular value decomposition of a complex matrix, optionally computing the left and/or right singular vectors (fast Jacobi)
  • ZGETRF : LU factorization of complex m by n matrix
  • ZGETRI : Inverse of complex matrix, matrix already factorized by ZGETRF
  • ZGETRS : Solution of complex system of linear equations, multiple right-hand sides, matrix already factorized by ZGETRF
  • ZGGQRF : Computes a generalized QR factorization of a complex matrix pair
  • ZGGRQF : Computes a generalized RQ factorization of a complex matrix pair
  • ZGGSVP3 : Produces unitary matrices, using BLAS-3, that simultaneously reduce the complex, m by n, matrix A and the complex, p by n, matrix B to upper triangular form
  • ZGTCON : Estimates the reciprocal of the condition number of a complex tridiagonal matrix using the LU factorization computed by DGTTRF
  • ZGTRFS : Refined solution with error bounds of complex tridiagonal system of linear equations, multiple right-hand sides
  • ZGTTRF : LU factorization of complex tridiagonal matrix
  • ZGTTRS : Solves a complex tridiagonal system of linear equations using the LU factorization computed by DGTTRF
  • ZHBGST : Reduction of complex Hermitian-definite banded generalized eigenproblem Ax = lambda Bx to standard form Cy = lambda y, such that C has the same bandwidth as A
  • ZHBTRD : Unitary reduction of complex Hermitian band matrix to real symmetric tridiagonal form
  • ZHECON : Estimate condition number of complex Hermitian indefinite matrix, matrix already factorized by ZHETRF
  • ZHEGST : Reduction to standard form of complex Hermitian-definite generalized eigenproblem Ax = lambda Bx, ABx = lambda x or BAx = lambda x, B factorized by ZPOTRF
  • ZHERFS : Refined solution with error bounds of complex Hermitian indefinite system of linear equations, multiple right-hand sides
  • ZHETRD : Unitary reduction of complex Hermitian matrix to real symmetric tridiagonal form
  • ZHETRF : Bunch-Kaufman factorization of complex Hermitian indefinite matrix
  • ZHETRI : Inverse of complex Hermitian indefinite matrix, matrix already factorized by ZHETRF
  • ZHETRS : Solution of complex Hermitian indefinite system of linear equations, multiple right-hand sides, matrix already factorized by ZHETRF
  • ZHGEQZ : Eigenvalues and generalized Schur factorization of complex generalized upper Hessenberg matrix reduced from a pair of complex general matrices
  • ZHPCON : Estimate condition number of complex Hermitian indefinite matrix, matrix already factorized by ZHPTRF, packed storage
  • ZHPGST : Reduction to standard form of complex Hermitian-definite generalized eigenproblem Ax = lambda Bx, ABx = lamda x or BAx = lambda x, packed storage, B factorized by ZPPTRF
  • ZHPRFS : Refined solution with error bounds of complex Hermitian indefinite system of linear equations, multiple right-hand sides, packed storage
  • ZHPTRD : Unitary reduction of complex Hermitian matrix to real symmetric tridiagonal form, packed storage
  • ZHPTRF : Bunch-Kaufman factorization of complex Hermitian indefinite matrix, packed storage
  • ZHPTRI : Inverse of complex Hermitian indefinite matrix, matrix already factorized by ZHPTRF, packed storage
  • ZHPTRS : Solution of complex Hermitian indefinite system of linear equations, multiple right-hand sides, matrix already factorized by ZHPTRF, packed storage
  • ZHSEQR : Eigenvalues and Schur factorization of complex upper Hessenberg matrix reduced from complex general matrix
  • ZPBCON : Estimate condition number of complex Hermitian positive-definite band matrix, matrix already factorized by ZPBTRF
  • ZPBEQU : Computes row and column scalings intended to equilibrate a complex Hermitian positive-definite banded matrix and reduce its condition number
  • ZPBRFS : Refined solution with error bounds of complex Hermitian positive-definite band system of linear equations, multiple right-hand sides
  • ZPBTRF : Cholesky factorization of complex Hermitian positive-definite band matrix
  • ZPBTRS : Solution of complex Hermitian positive-definite band system of linear equations, multiple right-hand sides, matrix already factorized by ZPBTRF
  • ZPFTRF : Cholesky factorization of complex Hermitian positive definite matrix, Rectangular Full Packed format
  • ZPFTRI : Inverse of complex Hermitian positive definite matrix, matrix already factorized by ZPFTRF, Rectangular Full Packed format
  • ZPFTRS : Solution of complex Hermitian positive definite system of linear equations, multiple right-hand sides, coefficient matrix already factorized by ZPFTRF, Rectangular Full Packed format
  • ZPOCON : Estimate condition number of complex Hermitian positive-definite matrix, matrix already factorized by ZPOTRF
  • ZPOEQU : Computes row and column scalings intended to equilibrate a complex Hermitian positive-definite matrix and reduce its condition number
  • ZPORFS : Refined solution with error bounds of complex Hermitian positive-definite system of linear equations, multiple right-hand sides
  • ZPOTRF : Cholesky factorization of complex Hermitian positive-definite matrix
  • ZPOTRI : Inverse of complex Hermitian positive-definite matrix, matrix already factorized by ZPOTRF
  • ZPOTRS : Solution of complex Hermitian positive-definite system of linear equations, multiple right-hand sides, matrix already factorized by ZPOTRF
  • ZPPCON : Estimate condition number of complex Hermitian positive-definite matrix, matrix already factorized by ZPPTRF, packed storage
  • ZPPEQU : Computes row and column scalings intended to equilibrate a complex Hermitian positive-definite matrix and reduce its condition number, packed storage
  • ZPPRFS : Refined solution with error bounds of complex Hermitian positive-definite system of linear equations, multiple right-hand sides, packed storage
  • ZPPTRF : Cholesky factorization of complex Hermitian positive-definite matrix, packed storage
  • ZPPTRI : Inverse of complex Hermitian positive-definite matrix, matrix already factorized by ZPPTRF, packed storage
  • ZPPTRS : Solution of complex Hermitian positive-definite system of linear equations, multiple right-hand sides, matrix already factorized by ZPPTRF, packed storage
  • ZPSTRF : Cholesky factorization of complex Hermitian positive semidefinite matrix
  • ZPTCON : Computes the reciprocal of the condition number of a complex Hermitian positive-definite tridiagonal system using the L * D * L' factorization computed by ZPTTRF
  • ZPTEQR : All eigenvalues and eigenvectors of real symmetric positive-definite tridiagonal matrix, reduced from complex Hermitian positive-definite matrix
  • ZPTRFS : Refined solution with error bounds of complex Hermitian positive-definite tridiagonal system of linear equations, multiple right-hand sides
  • ZPTTRF : Computes the L * D * L' factorization of a complex Hermitian positive-definite tridiagonal matrix
  • ZPTTRS : Solves a complex Hermitian positive-definite tridiagonal system using the L * D * L' factorization computed by ZPTTRF
  • ZSPCON : Estimate condition number of complex symmetric matrix, matrix already factorized by ZSPTRF, packed storage
  • ZSPRFS : Refined solution with error bounds of complex symmetric system of linear equations, multiple right-hand sides, packed storage
  • ZSPTRF : Bunch-Kaufman factorization of complex symmetric matrix, packed storage
  • ZSPTRI : Inverse of complex symmetric matrix, matrix already factorized by ZSPTRF, packed storage
  • ZSPTRS : Solution of complex symmetric system of linear equations, multiple right-hand sides, matrix already factorized by ZSPTRF, packed storage
  • ZSTEDC : Computes all eigenvalues and, optionally, eigenvectors of a real symmetric tridiagonal matrix or a complex Hermitian matrix reduced to this form (divide-and-conquer)
  • ZSTEGR : Computes all eigenvalues and, optionally, eigenvectors of a real symmetric tridiagonal matrix or a complex Hermitian matrix reduced to this form (Relatively Robust Representations)
  • ZSYCON : Estimate condition number of complex symmetric matrix, matrix already factorized by ZSYTRF
  • ZSYRFS : Refined solution with error bounds of complex symmetric system of linear equations, multiple right-hand sides
  • ZSYTRF : Bunch-Kaufman factorization of complex symmetric matrix
  • ZSYTRI : Inverse of complex symmetric matrix, matrix already factorized by ZSYTRF
  • ZSYTRS : Solution of complex symmetric system of linear equations, multiple right-hand sides, matrix already factorized by ZSYTRF
  • ZTBCON : Estimate condition number of complex band triangular matrix
  • ZTBRFS : Error bounds for solution of complex band triangular system of linear equations, multiple right-hand sides
  • ZTBTRS : Solution of complex band triangular system of linear equations, multiple right-hand sides
  • ZTFTRI : Inverse of complex triangular matrix, Rectangular Full Packed format
  • ZTGEVC : Left and right eigenvectors of a pair of complex upper triangular matrices
  • ZTGEXC : Reorders the generalized Schur decomposition of a complex matrix pair using an unitary equivalence transformation
  • ZTGSEN : Reorders the generalized Schur decomposition of a complex matrix pair using an unitary equivalence transformation, computes the generalized eigenvalues of the reordered pair and, optionally, computes the estimates of reciprocal condition numbers for eigenvalues and eigenspaces
  • ZTGSJA : Computes the generalized singular value decomposition of a complex upper triangular (or trapezoidal) matrix pair
  • ZTGSNA : Estimates reciprocal condition numbers for specified eigenvalues and/or eigenvectors of a complex matrix pair in generalized Schur canonical form
  • ZTGSYL : Solves the complex generalized Sylvester equation
  • ZTPCON : Estimate condition number of complex triangular matrix, packed storage
  • ZTPQRT : QR factorization of complex triangular-pentagonal matrix
  • ZTPRFS : Error bounds for solution of complex triangular system of linear equations, multiple right-hand sides, packed storage
  • ZTPTRI : Inverse of complex triangular matrix, packed storage
  • ZTPTRS : Solution of complex triangular system of linear equations, multiple right-hand sides, packed storage
  • ZTRCON : Estimate condition number of complex triangular matrix
  • ZTREXC : Reorder Schur factorization of complex matrix using unitary similarity transformation
  • ZTRRFS : Error bounds for solution of complex triangular system of linear equations, multiple right-hand sides
  • ZTRSEN : Reorder Schur factorization of complex matrix, form orthonormal basis of right invariant subspace for selected eigenvalues, with estimates of sensitivities
  • ZTRSNA : Estimates of sensitivities of selected eigenvalues and eigenvectors of complex upper triangular matrix
  • ZTRSYL : Solve complex Sylvester matrix equation AX + XB = C, A and B are upper triangular or conjugate-transposes
  • ZTRTRI : Inverse of complex triangular matrix
  • ZTRTRS : Solution of complex triangular system of linear equations, multiple right-hand sides
  • ZTZRZF : Reduces a complex upper trapezoidal matrix to upper triangular form
  • ZUNCSD : Computes the CS decomposition of a unitary matrix partitioned into four complex submatrices
  • ZUNGBR : Generate unitary transformation matrices from reduction to bidiagonal form determined by ZGEBRD
  • ZUNGHR : Generate unitary transformation matrix from reduction to Hessenberg form determined by ZGEHRD
  • ZUNGLQ : Form all or part of unitary Q from LQ factorization determined by ZGELQF
  • ZUNGQL : Form all or part of orthogonal Q from QL factorization determined by ZGEQLF
  • ZUNGQR : Form all or part of unitary Q from QR factorization determined by ZGEQRF or ZGEQPF
  • ZUNGRQ : Form all or part of orthogonal Q from RQ factorization determined by ZGERQF
  • ZUNGTR : Generate unitary transformation matrix from reduction to tridiagonal form determined by ZHETRD
  • ZUNMBR : Apply unitary transformations from reduction to bidiagonal form determined by ZGEBRD
  • ZUNMHR : Apply unitary transformation matrix from reduction to Hessenberg form determined by ZGEHRD
  • ZUNMTR : Apply unitary transformation matrix determined by ZHETRD
  • ZUPGTR : Generate unitary transformation matrix from reduction to tridiagonal form determined by ZHPTRD
  • ZUPMTR : Apply unitary transformation matrix determined by ZHPTRD


DBDSDC example

Computational Routines: Computes the singular value decomposition of a real bidiagonal matrix, optionally computing the singular vectors (divide-and-conquer)

Data

DBDSDC Example Program Data

  4                          :Value of N

  3.62  -2.41   1.92  -1.43  :End of diagonal elements
  1.26  -1.53   1.19         :End of off-diagonal elements

Result

 DBDSDC Example Program Results

 Singular values of B:
         4.0001        3.0006        1.9960        0.9998

Source

    Program dbdsdc_example

!     DBDSDC Example Program Text

!     Copyright 2017, Numerical Algorithms Group Ltd. http://www.nag.com

!     .. Use Statements ..
      Use lapack_interfaces, Only: dbdsdc
      Use lapack_precision, Only: dp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter :: nin = 5, nout = 6
!     .. Local Scalars ..
      Integer :: info, ldb, ldu, ldvt, n
!     .. Local Arrays ..
      Real (Kind=dp), Allocatable :: b(:, :), d(:), e(:), u(:, :), vt(:, :), &
        work(:)
      Real (Kind=dp) :: q(1)
      Integer :: iq(1)
      Integer, Allocatable :: iwork(:)
!     .. Executable Statements ..
      Write (nout, *) 'DBDSDC Example Program Results'
      Write (nout, *)
      Flush (nout)
!     Skip heading in data file
      Read (nin, *)
      Read (nin, *) n
      ldb = n
      ldu = n
      ldvt = n
      Allocate (b(ldb,n), d(n), e(n-1), u(ldu,n), vt(ldvt,n), work(n*(3*n+ &
        4)), iwork(8*n))

!     Read the bidiagonal matrix B from data file, first
!     the diagonal elements, and then the off diagonal elements

      Read (nin, *) d(1:n)
      Read (nin, *) e(1:n-1)

!     Calculate the singular values and left and right singular
!     vectors of B.

      Call dbdsdc('Upper', 'I', n, d, e, u, ldu, vt, ldvt, q, iq, work, iwork, &
        info)

      If (info==0) Then
!       Print the singular values of B.

        Write (nout, *) 'Singular values of B:'
        Write (nout, 100) d(1:n)
      Else
        Write (nout, 110) '** DBDSDC failed with INFO = ', info
      End If

100   Format (1X, 4(3X,F11.4))
110   Format (1X, A, I10)
    End Program
Full documentation of DBDSDC


DBDSQR example

Computational Routines: SVD of real bidiagonal matrix reduced from real general matrix

Data

DBDSQR Example Program Data
  4                           :Value of N
  3.62  -2.41   1.92  -1.43
  1.26  -1.53   1.19          :End of matrix B
  'U'                         :Value of UPLO

Result

 DBDSQR Example Program Results

 Singular values
     4.0001  3.0006  1.9960  0.9998

 Right singular vectors, by row
          1       2       3       4
 1   0.8261  0.5246  0.2024  0.0369
 2   0.4512 -0.4056 -0.7350 -0.3030
 3   0.2823 -0.5644  0.1731  0.7561
 4   0.1852 -0.4916  0.6236 -0.5789

 Left singular vectors, by column
          1       2       3       4
 1   0.9129  0.3740  0.1556  0.0512
 2  -0.3935  0.7005  0.5489  0.2307
 3   0.1081 -0.5904  0.6173  0.5086
 4  -0.0132  0.1444 -0.5417  0.8280

Source

    Program dbdsqr_example

!     DBDSQR Example Program Text

!     Copyright 2017, Numerical Algorithms Group Ltd. http://www.nag.com

!     .. Use Statements ..
      Use lapack_example_aux, Only: nagf_file_print_matrix_real_gen
      Use lapack_interfaces, Only: dbdsqr, dlaset
      Use lapack_precision, Only: dp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Real (Kind=dp), Parameter :: one = 1.0_dp
      Real (Kind=dp), Parameter :: zero = 0.0_dp
      Integer, Parameter :: nin = 5, nout = 6
!     .. Local Scalars ..
      Integer :: ifail, info, ldc, ldu, ldvt, n
      Character (1) :: uplo
!     .. Local Arrays ..
      Real (Kind=dp), Allocatable :: c(:, :), d(:), e(:), u(:, :), vt(:, :), &
        work(:)
!     .. Executable Statements ..
      Write (nout, *) 'DBDSQR Example Program Results'
!     Skip heading in data file
      Read (nin, *)
      Read (nin, *) n
      ldc = 1
      ldu = n
      ldvt = n
      Allocate (c(ldc,1), d(n), e(n-1), u(ldu,n), vt(ldvt,n), work(4*n))

!     Read B from data file

      Read (nin, *) d(1:n)
      Read (nin, *) e(1:n-1)

      Read (nin, *) uplo

!     Initialize U and VT to be the unit matrix
      Call dlaset('General', n, n, zero, one, u, ldu)
      Call dlaset('General', n, n, zero, one, vt, ldvt)

!     Calculate the SVD of B
      Call dbdsqr(uplo, n, n, n, 0, d, e, vt, ldvt, u, ldu, c, ldc, work, &
        info)

      Write (nout, *)
      If (info>0) Then
        Write (nout, *) 'Failure to converge.'
      Else

!       Print singular values, left & right singular vectors

        Write (nout, *) 'Singular values'
        Write (nout, 100) d(1:n)
        Write (nout, *)
        Flush (nout)

!       ifail: behaviour on error exit
!              =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
        ifail = 0
        Call nagf_file_print_matrix_real_gen('General', ' ', n, n, vt, ldvt, &
          'Right singular vectors, by row', ifail)

        Write (nout, *)
        Flush (nout)

        ifail = 0
        Call nagf_file_print_matrix_real_gen('General', ' ', n, n, u, ldu, &
          'Left singular vectors, by column', ifail)

      End If

100   Format (3X, (8F8.4))
    End Program
Full documentation of DBDSQR


DGBBRD example

Computational Routines: Reduction of real rectangular band matrix to upper bidiagonal form

Data

DGBBRD Example Program Data
  6  4  2  1  0               :Values of M, N, KL, KU and NCC
 -0.57  -1.28
 -1.93   1.08  -0.31
  2.30   0.24   0.40  -0.35
         0.64  -0.66   0.08
                0.15  -2.13
                       0.50   :End of matrix A

Result

 DGBBRD Example Program Results

 Diagonal D:
         3.0561        1.5259        0.9690        1.5685

 Off-diagonal E:
         0.6206        1.2353        1.1240

Source

    Program dgbbrd_example

!     DGBBRD Example Program Text

!     Copyright 2017, Numerical Algorithms Group Ltd. http://www.nag.com

!     .. Use Statements ..
      Use lapack_interfaces, Only: dgbbrd
      Use lapack_precision, Only: dp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter :: nin = 5, nout = 6
      Character (1), Parameter :: vect = 'B'
!     .. Local Scalars ..
      Integer :: i, info, j, kl, ku, ldab, ldb, ldc, ldpt, ldq, m, n, ncc
!     .. Local Arrays ..
      Real (Kind=dp), Allocatable :: ab(:, :), b(:, :), c(:, :), d(:), e(:), &
        pt(:, :), q(:, :), work(:)
!     .. Intrinsic Procedures ..
      Intrinsic :: abs, max, min
!     .. Executable Statements ..
      Write (nout, *) 'DGBBRD Example Program Results'
!     Skip heading in data file
      Read (nin, *)
      Read (nin, *) m, n, kl, ku, ncc
      ldab = kl + ku + 1
      ldb = m
      ldc = m
      ldpt = n
      ldq = m
      Allocate (ab(ldab,n), b(ldb,n), c(m,ncc), d(n), e(n-1), pt(ldpt,n), &
        q(ldq,m), work(2*m+2*n))

!     Read A from data file

      Read (nin, *)((ab(ku+1+i-j,j),j=max(i-kl,1),min(i+ku,n)), i=1, m)

!     Reduce A to upper bidiagonal form
      Call dgbbrd(vect, m, n, ncc, kl, ku, ab, ldab, d, e, q, ldq, pt, ldpt, &
        c, ldc, work, info)

!     Print the absolute values of bidiagonal vectors d and e.
!     Any of these can differ by a sign change by combinations of sign
!     changes in columns of Q and P (rows of PT).
      Write (nout, *)
      Write (nout, *) 'Diagonal D:'
      Write (nout, 100) abs(d(1:n))
      Write (nout, *)
      Write (nout, *) 'Off-diagonal E:'
      Write (nout, 100) abs(e(1:n-1))
100   Format (1X, 4(3X,F11.4))

    End Program
Full documentation of DGBBRD


DGBCON example

Computational Routines: Estimate condition number of real band matrix, matrix already factorized by DGBTRF

Data

DGBCON Example Program Data
  4  1  2                     :Values of N, KL and KU
 -0.23   2.54  -3.66
 -6.98   2.46  -2.73  -2.13
         2.56   2.46   4.07
               -4.78  -3.82   :End of matrix A

Result

 DGBCON Example Program Results

 Estimate of condition number =  5.64E+01

Source

    Program dgbcon_example

!     DGBCON Example Program Text

!     Copyright 2017, Numerical Algorithms Group Ltd. http://www.nag.com

!     .. Use Statements ..
      Use lapack_interfaces, Only: dgbcon, dgbtrf, dlangb
      Use lapack_precision, Only: dp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter :: nin = 5, nout = 6
      Character (1), Parameter :: norm = '1'
!     .. Local Scalars ..
      Real (Kind=dp) :: anorm, rcond
      Integer :: i, info, j, k, kl, ku, ldab, n
!     .. Local Arrays ..
      Real (Kind=dp), Allocatable :: ab(:, :), work(:)
      Integer, Allocatable :: ipiv(:), iwork(:)
!     .. Intrinsic Procedures ..
      Intrinsic :: epsilon, max, min
!     .. Executable Statements ..
      Write (nout, *) 'DGBCON Example Program Results'
!     Skip heading in data file
      Read (nin, *)
      Read (nin, *) n, kl, ku
      ldab = 2*kl + ku + 1
      Allocate (ab(ldab,n), work(3*n), ipiv(n), iwork(n))

!     Read A from data file

      k = kl + ku + 1
      Read (nin, *)((ab(k+i-j,j),j=max(i-kl,1),min(i+ku,n)), i=1, n)

!     Compute norm of A
      anorm = dlangb(norm, n, kl, ku, ab(kl+1,1), ldab, work)

!     Factorize A

      Call dgbtrf(n, n, kl, ku, ab, ldab, ipiv, info)

      Write (nout, *)
      If (info==0) Then

!       Estimate condition number

        Call dgbcon(norm, n, kl, ku, ab, ldab, ipiv, anorm, rcond, work, &
          iwork, info)

        If (rcond>=epsilon(1.0E0_dp)) Then
          Write (nout, 100) 'Estimate of condition number =', 1.0_dp/rcond
        Else
          Write (nout, *) 'A is singular to working precision'
        End If
      Else
        Write (nout, *) 'The factor U is singular'
      End If

100   Format (1X, A, 1P, E10.2)
    End Program
Full documentation of DGBCON


DGBEQU example

Computational Routines: Computes row and column scalings intended to equilibrate a real banded matrix and reduce its condition number

Data

DGBEQU Example Program Data
  4  1  2                                     :Values of N, KL and KU
 -2.30D-01   2.54D+00  -3.66D-10
 -6.98D+10   2.46D+10  -2.73D+00  -2.13D+10
             2.56D+00   2.46D-10   4.07D+00
                       -4.78D-10  -3.82D+00   :End of matrix A

Result

 DGBEQU Example Program Results

 Matrix A
               1            2            3            4
 1   -2.3000E-01   2.5400E+00  -3.6600E-10
 2   -6.9800E+10   2.4600E+10  -2.7300E+00  -2.1300E+10
 3                 2.5600E+00   2.4600E-10   4.0700E+00
 4                             -4.7800E-10  -3.8200E+00

 ROWCND = 3.6E-11, COLCND = 1.4E-10, AMAX = 7.0E+10

 Row scale factors
    3.94E-01   1.43E-11   2.46E-01   2.62E-01

 Column scale factors
    1.00E+00   1.00E+00   6.94E+09   1.00E+00

 Scaled matrix
          1       2       3       4
 1  -0.0906  1.0000 -1.0000
 2  -1.0000  0.3524 -0.2714 -0.3052
 3           0.6290  0.4195  1.0000
 4                  -0.8684 -1.0000

Source

    Program dgbequ_example

!     DGBEQU Example Program Text

!     Copyright 2017, Numerical Algorithms Group Ltd. http://www.nag.com

!     .. Use Statements ..
      Use blas_interfaces, Only: dscal
      Use lapack_example_aux, Only: nagf_blas_ddscl, &
        nagf_file_print_matrix_real_band
      Use lapack_interfaces, Only: dgbequ
      Use lapack_precision, Only: dp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Real (Kind=dp), Parameter :: one = 1.0_dp
      Real (Kind=dp), Parameter :: thresh = 0.1_dp
      Integer, Parameter :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=dp) :: amax, big, colcnd, rowcnd, small
      Integer :: i, i0, i1, ifail, ilen, info, j, k, kl, ku, ldab, n
!     .. Local Arrays ..
      Real (Kind=dp), Allocatable :: ab(:, :), c(:), r(:)
!     .. Intrinsic Procedures ..
      Intrinsic :: epsilon, max, min, radix, real, tiny
!     .. Executable Statements ..
      Write (nout, *) 'DGBEQU Example Program Results'
      Write (nout, *)
      Flush (nout)
!     Skip heading in data file
      Read (nin, *)
      Read (nin, *) n, kl, ku
      ldab = kl + ku + 1
      Allocate (ab(ldab,n), c(n), r(n))

!     Read the band matrix A from data file

      k = ku + 1
      Read (nin, *)((ab(k+i-j,j),j=max(i-kl,1),min(i+ku,n)), i=1, n)

!     Print the matrix A

!     ifail: behaviour on error exit
!             =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
      ifail = 0
      Call nagf_file_print_matrix_real_band(n, n, kl, ku, ab, ldab, &
        'Matrix A', ifail)

      Write (nout, *)

!     Compute row and column scaling factors

      Call dgbequ(n, n, kl, ku, ab, ldab, r, c, rowcnd, colcnd, amax, info)

      If (info>0) Then
        If (info<=n) Then
          Write (nout, 100) 'Row ', info, ' of A is exactly zero'
        Else
          Write (nout, 100) 'Column ', info - n, ' of A is exactly zero'
        End If
      Else

!       Print ROWCND, COLCND, AMAX and the scale factors

        Write (nout, 110) 'ROWCND =', rowcnd, ', COLCND =', colcnd, &
          ', AMAX =', amax
        Write (nout, *)
        Write (nout, *) 'Row scale factors'
        Write (nout, 120) r(1:n)
        Write (nout, *)
        Write (nout, *) 'Column scale factors'
        Write (nout, 120) c(1:n)
        Write (nout, *)
        Flush (nout)

!       Compute values close to underflow and overflow

        small = tiny(1.0E0_dp)/(epsilon(1.0E0_dp)*real(radix(1.0E0_dp),kind=dp &
          ))
        big = one/small
        If ((rowcnd>=thresh) .And. (amax>=small) .And. (amax<=big)) Then
          If (colcnd<thresh) Then
!           Just column scale A
            Do j = 1, n
              i1 = 1 + max(1, j-ku) - (j-ku)
              ilen = min(n, j+kl) - max(1, j-ku) + 1
              Call dscal(ilen, c(j), ab(i1,j), 1)
            End Do

          End If
        Else If (colcnd>=thresh) Then

!         Just row scale A
          Do j = 1, n
            i0 = max(1, j-ku)
            i1 = 1 + i0 - (j-ku)
            ilen = min(n, j+kl) - i0 + 1
            Call nagf_blas_ddscl(ilen, r(i0), 1, ab(i1,j), 1)
          End Do

        Else

!         Row and column scale A
          Do j = 1, n
            i0 = max(1, j-ku)
            i1 = 1 + i0 - (j-ku)
            ilen = min(n, j+kl) - i0 + 1
            Call dscal(ilen, c(j), ab(i1,j), 1)
            Call nagf_blas_ddscl(ilen, r(i0), 1, ab(i1,j), 1)
          End Do

        End If

!       Print the scaled matrix
        ifail = 0
        Call nagf_file_print_matrix_real_band(n, n, kl, ku, ab, ldab, &
          'Scaled matrix', ifail)

      End If

100   Format (1X, A, I4, A)
110   Format (1X, 3(A,1P,E8.1))
120   Format ((1X,1P,7E11.2))
    End Program
Full documentation of DGBEQU


DGBRFS example

Computational Routines: Refined solution with error bounds of real band system of linear equations, multiple right-hand sides

Data

DGBRFS Example Program Data
  4  2  1  2                  :Values of N, NRHS, KL and KU
 -0.23   2.54  -3.66
 -6.98   2.46  -2.73  -2.13
         2.56   2.46   4.07
               -4.78  -3.82   :End of matrix A
  4.42 -36.01
 27.13 -31.67
 -6.14  -1.16
 10.50 -25.82                 :End of matrix B

Result

 DGBRFS Example Program Results

 Solution(s)
             1          2
 1     -2.0000     1.0000
 2      3.0000    -4.0000
 3      1.0000     7.0000
 4     -4.0000    -2.0000

 Backward errors (machine-dependent)
       1.1E-16    9.9E-17
 Estimated forward error bounds (machine-dependent)
       1.6E-14    1.9E-14

Source

    Program dgbrfs_example

!     DGBRFS Example Program Text

!     Copyright 2017, Numerical Algorithms Group Ltd. http://www.nag.com

!     .. Use Statements ..
      Use lapack_example_aux, Only: nagf_file_print_matrix_real_gen
      Use lapack_interfaces, Only: dgbrfs, dgbtrf, dgbtrs
      Use lapack_precision, Only: dp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Real (Kind=dp), Parameter :: zero = 0.0E0_dp
      Integer, Parameter :: nin = 5, nout = 6
      Character (1), Parameter :: trans = 'N'
!     .. Local Scalars ..
      Integer :: i, ifail, info, j, k, kl, ku, ldab, ldafb, ldb, ldx, n, nrhs
!     .. Local Arrays ..
      Real (Kind=dp), Allocatable :: ab(:, :), afb(:, :), b(:, :), berr(:), &
        ferr(:), work(:), x(:, :)
      Integer, Allocatable :: ipiv(:), iwork(:)
!     .. Intrinsic Procedures ..
      Intrinsic :: max, min
!     .. Executable Statements ..
      Write (nout, *) 'DGBRFS Example Program Results'
!     Skip heading in data file
      Read (nin, *)
      Read (nin, *) n, nrhs, kl, ku
      ldab = kl + ku + 1
      ldafb = 2*kl + ku + 1
      ldb = n
      ldx = n
      Allocate (ab(ldab,n), afb(ldafb,n), b(ldb,nrhs), berr(nrhs), ferr(nrhs), &
        work(3*n), x(ldx,n), ipiv(n), iwork(n))

!     Set A to zero to avoid referencing uninitialized elements

      ab(1:kl+ku+1, 1:n) = zero

!     Read A and B from data file, and copy A to AFB and B to X

      k = ku + 1
      Read (nin, *)((ab(k+i-j,j),j=max(i-kl,1),min(i+ku,n)), i=1, n)
      Read (nin, *)(b(i,1:nrhs), i=1, n)

      afb(kl+1:2*kl+ku+1, 1:n) = ab(1:kl+ku+1, 1:n)
      x(1:n, 1:nrhs) = b(1:n, 1:nrhs)

!     Factorize A in the array AFB
      Call dgbtrf(n, n, kl, ku, afb, ldafb, ipiv, info)

      Write (nout, *)
      Flush (nout)
      If (info==0) Then

!       Compute solution in the array X
        Call dgbtrs(trans, n, kl, ku, nrhs, afb, ldafb, ipiv, x, ldx, info)

!       Improve solution, and compute backward errors and
!       estimated bounds on the forward errors

        Call dgbrfs(trans, n, kl, ku, nrhs, ab, ldab, afb, ldafb, ipiv, b, &
          ldb, x, ldx, ferr, berr, work, iwork, info)

!       Print solution

!       ifail: behaviour on error exit
!              =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
        ifail = 0
        Call nagf_file_print_matrix_real_gen('General', ' ', n, nrhs, x, ldx, &
          'Solution(s)', ifail)

        Write (nout, *)
        Write (nout, *) 'Backward errors (machine-dependent)'
        Write (nout, 100) berr(1:nrhs)
        Write (nout, *) 'Estimated forward error bounds (machine-dependent)'
        Write (nout, 100) ferr(1:nrhs)
      Else
        Write (nout, *) 'The factor U is singular'
      End If

100   Format ((3X,1P,7E11.1))
    End Program
Full documentation of DGBRFS


DGBTRF example

Computational Routines: LU factorization of real m by n band matrix

Data

DGBTRF Example Program Data
  4  4  1  2                  :Values of M, N, KL and KU
 -0.23   2.54  -3.66
 -6.98   2.46  -2.73  -2.13
         2.56   2.46   4.07
               -4.78  -3.82   :End of matrix A

Result

 DGBTRF Example Program Results

 Details of factorization
             1          2          3          4
 1     -6.9800     2.4600    -2.7300    -2.1300
 2      0.0330     2.5600     2.4600     4.0700
 3                 0.9605    -5.9329    -3.8391
 4                            0.8057    -0.7269

 IPIV
             2          3          3          4

Source

    Program dgbtrf_example

!     DGBTRF Example Program Text

!     Copyright 2017, Numerical Algorithms Group Ltd. http://www.nag.com

!     .. Use Statements ..
      Use lapack_example_aux, Only: nagf_file_print_matrix_real_band
      Use lapack_interfaces, Only: dgbtrf
      Use lapack_precision, Only: dp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter :: nin = 5, nout = 6
!     .. Local Scalars ..
      Integer :: i, ifail, info, j, k, kl, ku, ldab, m, n
!     .. Local Arrays ..
      Real (Kind=dp), Allocatable :: ab(:, :)
      Integer, Allocatable :: ipiv(:)
!     .. Intrinsic Procedures ..
      Intrinsic :: max, min
!     .. Executable Statements ..
      Write (nout, *) 'DGBTRF Example Program Results'
!     Skip heading in data file
      Read (nin, *)
      Read (nin, *) m, n, kl, ku
      ldab = 2*kl + ku + 1
      Allocate (ab(ldab,n), ipiv(n))

!     Read A from data file

      k = kl + ku + 1
      Read (nin, *)((ab(k+i-j,j),j=max(i-kl,1),min(i+ku,n)), i=1, m)

!     Factorize A
      Call dgbtrf(m, n, kl, ku, ab, ldab, ipiv, info)

!     Print details of factorization

      Write (nout, *)
      Flush (nout)

!     ifail: behaviour on error exit
!             =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
      ifail = 0
      Call nagf_file_print_matrix_real_band(m, n, kl, kl+ku, ab, ldab, &
        'Details of factorization', ifail)

!     Print pivot indices

      Write (nout, *)
      Write (nout, *) 'IPIV'
      Write (nout, 100) ipiv(1:min(m,n))

      If (info/=0) Then
        Write (nout, *) 'The factor U is singular'
      End If

100   Format ((3X,7I11))
    End Program
Full documentation of DGBTRF


DGBTRS example

Computational Routines: Solution of real band system of linear equations, multiple right-hand sides, matrix already factorized by DGBTRF

Data

DGBTRS Example Program Data
  4  2  1  2                  :Values of N, NRHS, KL and KU
 -0.23   2.54  -3.66
 -6.98   2.46  -2.73  -2.13
         2.56   2.46   4.07
               -4.78  -3.82   :End of matrix A
  4.42 -36.01
 27.13 -31.67
 -6.14  -1.16
 10.50 -25.82                 :End of matrix B

Result

 DGBTRS Example Program Results

 Solution(s)
             1          2
 1     -2.0000     1.0000
 2      3.0000    -4.0000
 3      1.0000     7.0000
 4     -4.0000    -2.0000

Source

    Program dgbtrs_example

!     DGBTRS Example Program Text

!     Copyright 2017, Numerical Algorithms Group Ltd. http://www.nag.com

!     .. Use Statements ..
      Use lapack_example_aux, Only: nagf_file_print_matrix_real_gen
      Use lapack_interfaces, Only: dgbtrf, dgbtrs
      Use lapack_precision, Only: dp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter :: nin = 5, nout = 6
      Character (1), Parameter :: trans = 'N'
!     .. Local Scalars ..
      Integer :: i, ifail, info, j, k, kl, ku, ldab, ldb, n, nrhs
!     .. Local Arrays ..
      Real (Kind=dp), Allocatable :: ab(:, :), b(:, :)
      Integer, Allocatable :: ipiv(:)
!     .. Intrinsic Procedures ..
      Intrinsic :: max, min
!     .. Executable Statements ..
      Write (nout, *) 'DGBTRS Example Program Results'
!     Skip heading in data file
      Read (nin, *)
      Read (nin, *) n, nrhs, kl, ku
      ldab = 2*kl + ku + 1
      ldb = n
      Allocate (ab(ldab,n), b(ldb,nrhs), ipiv(n))

!     Read A and B from data file

      k = kl + ku + 1
      Read (nin, *)((ab(k+i-j,j),j=max(i-kl,1),min(i+ku,n)), i=1, n)
      Read (nin, *)(b(i,1:nrhs), i=1, n)

!     Factorize A
      Call dgbtrf(n, n, kl, ku, ab, ldab, ipiv, info)

      Write (nout, *)
      Flush (nout)
      If (info==0) Then

!       Compute solution
        Call dgbtrs(trans, n, kl, ku, nrhs, ab, ldab, ipiv, b, ldb, info)

!       Print solution

!       ifail: behaviour on error exit
!              =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
        ifail = 0
        Call nagf_file_print_matrix_real_gen('General', ' ', n, nrhs, b, ldb, &
          'Solution(s)', ifail)

      Else
        Write (nout, *) 'The factor U is singular'
      End If

    End Program
Full documentation of DGBTRS


DGEBAL example

Computational Routines: Balance real general matrix

Data

DGEBAL Example Program Data
  4                         :Value of N
 5.14  0.91   0.00 -32.80
 0.91  0.20   0.00  34.50
 1.90  0.80  -0.40  -3.00
-0.33  0.35   0.00   0.66   :End of matrix A

Result

 DGEBAL Example Program Results

 Eigenvalues
  ( -0.4000,  0.0000)
  ( -4.0208,  0.0000)
  (  3.0136,  0.0000)
  (  7.0072,  0.0000)

 Contents of array VR
          1       2       3       4
 1   0.0000 -0.4381  0.4654  0.9513
 2   0.0000  0.8923  0.7888 -0.1714
 3   1.0000 -0.0481  0.3981  0.2494
 4   0.0000 -0.0976  0.0521 -0.0589

Source

    Program dgebal_example

!     DGEBAL Example Program Text

!     Copyright 2017, Numerical Algorithms Group Ltd. http://www.nag.com

!     .. Use Statements ..
      Use blas_interfaces, Only: dnrm2
      Use lapack_example_aux, Only: nagf_blas_damax_val, &
        nagf_file_print_matrix_real_gen
      Use lapack_interfaces, Only: dgebak, dgebal, dgehrd, dhseqr, dorghr, &
        dtrevc
      Use lapack_precision, Only: dp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Real (Kind=dp), Parameter :: zero = 0.0_dp
      Integer, Parameter :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=dp) :: r
      Integer :: i, ifail, ihi, ilo, info, k, lda, ldh, ldvl, ldvr, lwork, m, &
        n
!     .. Local Arrays ..
      Real (Kind=dp), Allocatable :: a(:, :), h(:, :), scale(:), tau(:), &
        vl(:, :), vr(:, :), wi(:), work(:), wr(:)
      Logical :: select(1)
!     .. Executable Statements ..
      Write (nout, *) 'DGEBAL Example Program Results'
!     Skip heading in data file
      Read (nin, *)
      Read (nin, *) n
      ldvl = 1
      lda = n
      ldh = n
      ldvr = n
      lwork = 64*n
      Allocate (a(lda,n), h(ldh,n), scale(n), tau(n), vl(ldvl,1), vr(ldvr,n), &
        wi(n), work(lwork), wr(n))

!     Read A from data file
      Read (nin, *)(a(i,1:n), i=1, n)

!     Balance A
      Call dgebal('Both', n, a, lda, ilo, ihi, scale, info)

!     Reduce A to upper Hessenberg form H = (Q**T)*A*Q
      Call dgehrd(n, ilo, ihi, a, lda, tau, work, lwork, info)

!     Copy A to H and VR
      h(1:n, 1:n) = a(1:n, 1:n)
      vr(1:n, 1:n) = a(1:n, 1:n)

!     Form Q explicitly, storing the result in VR
      Call dorghr(n, 1, n, vr, ldvr, tau, work, lwork, info)

!     Calculate the eigenvalues and Schur factorization of A
      Call dhseqr('Schur form', 'Vectors', n, ilo, ihi, h, ldh, wr, wi, vr, &
        ldvr, work, lwork, info)

      Write (nout, *)
      If (info>0) Then
        Write (nout, *) 'Failure to converge.'
      Else
        Write (nout, *) 'Eigenvalues'
        Write (nout, 100)(' (', wr(i), ',', wi(i), ')', i=1, n)

!       Calculate the eigenvectors of A, storing the result in VR

        Call dtrevc('Right', 'Backtransform', select, n, h, ldh, vl, ldvl, vr, &
          ldvr, n, m, work, info)

        Call dgebak('Both', 'Right', n, ilo, ihi, scale, m, vr, ldvr, info)

!       Print eigenvectors

        Write (nout, *)
        Flush (nout)

!       Normalize the eigenvectors, largest positive
        Do i = 1, m
          Call nagf_blas_damax_val(n, vr(1,i), 1, k, r)
          If (vr(k,i)<zero) Then
            vr(1:n, i) = -vr(1:n, i)
          End If
          r = dnrm2(n, vr(1,i), 1)
          vr(1:n, i) = vr(1:n, i)/r
        End Do

!       ifail: behaviour on error exit
!              =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
        ifail = 0
        Call nagf_file_print_matrix_real_gen('General', ' ', n, m, vr, ldvr, &
          'Contents of array VR', ifail)

      End If

100   Format (1X, A, F8.4, A, F8.4, A)
    End Program
Full documentation of DGEBAL


DGEBRD example

Computational Routines: Orthogonal reduction of real general rectangular matrix to bidiagonal form

Data

DGEBRD Example Program Data
  6  4                        :Values of M and N
 -0.57  -1.28  -0.39   0.25
 -1.93   1.08  -0.31  -2.14
  2.30   0.24   0.40  -0.35
 -1.93   0.64  -0.66   0.08
  0.15   0.30   0.15  -2.13
 -0.02   1.03  -1.43   0.50   :End of matrix A

Result

 DGEBRD Example Program Results

 Diagonal
    3.6177   2.4161  -1.9213  -1.4265
 Superdiagonal
    1.2587   1.5262  -1.1895

Source

    Program dgebrd_example

!     DGEBRD Example Program Text

!     Copyright 2017, Numerical Algorithms Group Ltd. http://www.nag.com

!     .. Use Statements ..
      Use lapack_interfaces, Only: dgebrd
      Use lapack_precision, Only: dp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter :: nin = 5, nout = 6
!     .. Local Scalars ..
      Integer :: i, info, lda, lwork, m, n
!     .. Local Arrays ..
      Real (Kind=dp), Allocatable :: a(:, :), d(:), e(:), taup(:), tauq(:), &
        work(:)
!     .. Intrinsic Procedures ..
      Intrinsic :: min
!     .. Executable Statements ..
      Write (nout, *) 'DGEBRD Example Program Results'
!     Skip heading in data file
      Read (nin, *)
      Read (nin, *) m, n
      lda = m
      lwork = 64*(m+n)
      Allocate (a(lda,n), d(n), e(n-1), taup(n), tauq(n), work(lwork))

!     Read A from data file

      Read (nin, *)(a(i,1:n), i=1, m)

!     Reduce A to bidiagonal form

      Call dgebrd(m, n, a, lda, d, e, tauq, taup, work, lwork, info)

!     Print bidiagonal form

      Write (nout, *)
      Write (nout, *) 'Diagonal'
      Write (nout, 100) d(1:min(m,n))
      If (m>=n) Then
        Write (nout, *) 'Superdiagonal'
      Else
        Write (nout, *) 'Subdiagonal'
      End If
      Write (nout, 100) e(1:min(m,n)-1)

100   Format (1X, 8F9.4)
    End Program
Full documentation of DGEBRD


DGECON example

Computational Routines: Estimate condition number of real matrix, matrix already factorized by DGETRF

Data

DGECON Example Program Data
  4                           :Value of N
  1.80   2.88   2.05  -0.89
  5.25  -2.95  -0.95  -3.80
  1.58  -2.69  -2.90  -1.04
 -1.11  -0.66  -0.59   0.80   :End of matrix A

Result

 DGECON Example Program Results

 Estimate of condition number =  1.52E+02

Source

    Program dgecon_example

!     DGECON Example Program Text

!     Copyright 2017, Numerical Algorithms Group Ltd. http://www.nag.com

!     .. Use Statements ..
      Use lapack_interfaces, Only: dgecon, dgetrf, dlange
      Use lapack_precision, Only: dp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter :: nin = 5, nout = 6
      Character (1), Parameter :: norm = '1'
!     .. Local Scalars ..
      Real (Kind=dp) :: anorm, rcond
      Integer :: i, info, lda, n
!     .. Local Arrays ..
      Real (Kind=dp), Allocatable :: a(:, :), work(:)
      Integer, Allocatable :: ipiv(:), iwork(:)
!     .. Intrinsic Procedures ..
      Intrinsic :: epsilon
!     .. Executable Statements ..
      Write (nout, *) 'DGECON Example Program Results'
!     Skip heading in data file
      Read (nin, *)
      Read (nin, *) n
      lda = n
      Allocate (a(lda,n), work(4*n), ipiv(n), iwork(n))

!     Read A from data file

      Read (nin, *)(a(i,1:n), i=1, n)

!     Compute norm of A

      anorm = dlange(norm, n, n, a, lda, work)

!     Factorize A
      Call dgetrf(n, n, a, lda, ipiv, info)

      Write (nout, *)
      If (info==0) Then

!       Estimate condition number

        Call dgecon(norm, n, a, lda, anorm, rcond, work, iwork, info)

        If (rcond>=epsilon(1.0E0_dp)) Then
          Write (nout, 100) 'Estimate of condition number =', 1.0E0_dp/rcond
        Else
          Write (nout, *) 'A is singular to working precision'
        End If
      Else
        Write (nout, *) 'The factor U is singular'
      End If

100   Format (1X, A, 1P, E10.2)
    End Program
Full documentation of DGECON


DGEEQU example

Computational Routines: Computes row and column scalings intended to equilibrate a general real matrix and reduce its condition number

Data

DGEEQU Example Program Data

  4                                         :Value of N

  1.80D+10   2.88D+10   2.05D+00  -8.90D+09
  5.25D+00  -2.95D+00  -9.50D-09  -3.80D+00
  1.58D+00  -2.69D+00  -2.90D-10  -1.04D+00
 -1.11D+00  -6.60D-01  -5.90D-11   8.00D-01 :End of matrix A

Result

 DGEEQU Example Program Results

 Matrix A
               1            2            3            4
 1    1.8000E+10   2.8800E+10   2.0500E+00  -8.9000E+09
 2    5.2500E+00  -2.9500E+00  -9.5000E-09  -3.8000E+00
 3    1.5800E+00  -2.6900E+00  -2.9000E-10  -1.0400E+00
 4   -1.1100E+00  -6.6000E-01  -5.9000E-11   8.0000E-01

 ROWCND = 3.9E-11, COLCND = 1.8E-09, AMAX = 2.9E+10

 Row scale factors
    3.47E-11   1.90E-01   3.72E-01   9.01E-01

 Column scale factors
    1.00E+00   1.00E+00   5.53E+08   1.38E+00

 Scaled matrix
             1          2          3          4
 1      0.6250     1.0000     0.0393    -0.4269
 2      1.0000    -0.5619    -1.0000    -1.0000
 3      0.5874    -1.0000    -0.0596    -0.5341
 4     -1.0000    -0.5946    -0.0294     0.9957

Source

    Program dgeequ_example

!     DGEEQU Example Program Text

!     Copyright 2017, Numerical Algorithms Group Ltd. http://www.nag.com

!     .. Use Statements ..
      Use blas_interfaces, Only: dscal
      Use lapack_example_aux, Only: nagf_blas_ddscl, &
        nagf_file_print_matrix_real_gen
      Use lapack_interfaces, Only: dgeequ
      Use lapack_precision, Only: dp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Real (Kind=dp), Parameter :: one = 1.0_dp
      Real (Kind=dp), Parameter :: thresh = 0.1_dp
      Integer, Parameter :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=dp) :: amax, big, colcnd, rowcnd, small
      Integer :: i, ifail, info, j, lda, n
!     .. Local Arrays ..
      Real (Kind=dp), Allocatable :: a(:, :), c(:), r(:)
!     .. Intrinsic Procedures ..
      Intrinsic :: epsilon, radix, real, tiny
!     .. Executable Statements ..
      Write (nout, *) 'DGEEQU Example Program Results'
      Write (nout, *)
      Flush (nout)
!     Skip heading in data file
      Read (nin, *)
      Read (nin, *) n
      lda = n
      Allocate (a(lda,n), c(n), r(n))

!     Read the N by N matrix A from data file

      Read (nin, *)(a(i,1:n), i=1, n)

!     Print the matrix A

!     ifail: behaviour on error exit
!             =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
      ifail = 0
      Call nagf_file_print_matrix_real_gen('General', ' ', n, n, a, lda, &
        'Matrix A', ifail)
      Write (nout, *)

!     Compute row and column scaling factors

      Call dgeequ(n, n, a, lda, r, c, rowcnd, colcnd, amax, info)

      If (info>0) Then
        If (info<=n) Then
          Write (nout, 100) 'Row ', info, ' of A is exactly zero'
        Else
          Write (nout, 100) 'Column ', info - n, ' of A is exactly zero'
        End If
      Else

!       Print ROWCND, COLCND, AMAX and the scale factors

        Write (nout, 110) 'ROWCND =', rowcnd, ', COLCND =', colcnd, &
          ', AMAX =', amax
        Write (nout, *)
        Write (nout, *) 'Row scale factors'
        Write (nout, 120) r(1:n)
        Write (nout, *)
        Write (nout, *) 'Column scale factors'
        Write (nout, 120) c(1:n)
        Write (nout, *)
        Flush (nout)

!       Compute values close to underflow and overflow

        small = tiny(1.0E0_dp)/(epsilon(1.0E0_dp)*real(radix(1.0E0_dp),kind=dp &
          ))
        big = one/small
        If ((rowcnd>=thresh) .And. (amax>=small) .And. (amax<=big)) Then
          If (colcnd<thresh) Then

!           Just column scale A
            Do j = 1, n
              Call dscal(n, c(j), a(1,j), 1)
            End Do

          End If
        Else If (colcnd>=thresh) Then

!         Just row scale A
          Do j = 1, n
            Call nagf_blas_ddscl(n, r, 1, a(1,j), 1)
          End Do

        Else

!         Row and column scale A
          Do j = 1, n
            Call dscal(n, c(j), a(1,j), 1)
            Call nagf_blas_ddscl(n, r, 1, a(1,j), 1)
          End Do

        End If

!       Print the scaled matrix
        ifail = 0
        Call nagf_file_print_matrix_real_gen('General', ' ', n, n, a, lda, &
          'Scaled matrix', ifail)

      End If

100   Format (1X, A, I4, A)
110   Format (1X, 3(A,1P,E8.1))
120   Format ((1X,1P,7E11.2))
    End Program
Full documentation of DGEEQU


DGEHRD example

Computational Routines: Orthogonal reduction of real general matrix to upper Hessenberg form

Data

DGEHRD Example Program Data
  4                           :Value of N
  0.35   0.45  -0.14  -0.17
  0.09   0.07  -0.54   0.35
 -0.44  -0.33  -0.03   0.17
  0.25  -0.32  -0.13   0.11   :End of matrix A

Result

 DGEHRD Example Program Results

 Upper Hessenberg form
          1       2       3       4
 1   0.3500 -0.1160 -0.3886 -0.2942
 2  -0.5140  0.1225  0.1004  0.1126
 3   0.0000  0.6443 -0.1357 -0.0977
 4   0.0000  0.0000  0.4262  0.1632

Source

    Program dgehrd_example

!     DGEHRD Example Program Text

!     Copyright 2017, Numerical Algorithms Group Ltd. http://www.nag.com

!     .. Use Statements ..
      Use lapack_example_aux, Only: nagf_file_print_matrix_real_gen
      Use lapack_interfaces, Only: dgehrd
      Use lapack_precision, Only: dp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Real (Kind=dp), Parameter :: zero = 0.0E0_dp
      Integer, Parameter :: nin = 5, nout = 6
!     .. Local Scalars ..
      Integer :: i, ifail, info, lda, lwork, n
!     .. Local Arrays ..
      Real (Kind=dp), Allocatable :: a(:, :), tau(:), work(:)
!     .. Executable Statements ..
      Write (nout, *) 'DGEHRD Example Program Results'
!     Skip heading in data file
      Read (nin, *)
      Read (nin, *) n
      lda = n
      lwork = 64*n
      Allocate (a(lda,n), tau(n-1), work(lwork))

!     Read A from data file

      Read (nin, *)(a(i,1:n), i=1, n)

!     Reduce A to upper Hessenberg form

      Call dgehrd(n, 1, n, a, lda, tau, work, lwork, info)

!     Set the elements below the first subdiagonal to zero

      Do i = 1, n - 2
        a(i+2:n, i) = zero
      End Do

!     Print upper Hessenberg form

      Write (nout, *)
      Flush (nout)

!     ifail: behaviour on error exit
!             =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
      ifail = 0
      Call nagf_file_print_matrix_real_gen('General', ' ', n, n, a, lda, &
        'Upper Hessenberg form', ifail)

    End Program
Full documentation of DGEHRD


DGEJSV example

Computational Routines: Computes the singular value decomposition of a real matrix, optionally computing the left and/or right singular vectors (preconditioned Jacobi)

Data

DGEJSV Example Program Data

   6      4                   :Values of M and N

   2.27  -1.54   1.15  -1.94
   0.28  -1.67   0.94  -0.78
  -0.48  -3.09   0.99  -0.21
   1.07   1.22   0.79   0.63
  -2.35   2.93  -1.45   2.30
   0.62  -7.39   1.03  -2.57  :End of matrix A

Result

 DGEJSV Example Program Results

 Singular values
     9.9966  3.6831  1.3569  0.5000

 Left singular vectors
          1       2       3       4
 1   0.2774 -0.6003 -0.1277  0.1323
 2   0.2020 -0.0301  0.2805  0.7034
 3   0.2918  0.3348  0.6453  0.1906
 4  -0.0938 -0.3699  0.6781 -0.5399
 5  -0.4213  0.5266  0.0413 -0.0575
 6   0.7816  0.3353 -0.1645 -0.3957

 Right singular vectors
          1       2       3       4
 1   0.1921 -0.8030  0.0041 -0.5642
 2  -0.8794 -0.3926 -0.0752  0.2587
 3   0.2140 -0.2980  0.7827  0.5027
 4  -0.3795  0.3351  0.6178 -0.6017

 Estimate of the condition number of column equilibrated A
        9.0E+00

 Error estimate for the singular values
        2.2E-15

 Error estimates for left singular vectors
        3.5E-16    9.5E-16    2.6E-15    4.4E-15

 Error estimates for right singular vectors
        3.5E-16    9.5E-16    2.6E-15    2.6E-15

Source

    Program dgejsv_example

!     DGEJSV Example Program Text

!     Copyright 2017, Numerical Algorithms Group Ltd. http://www.nag.com

!     .. Use Statements ..
      Use lapack_example_aux, Only: nagf_file_print_matrix_real_gen
      Use lapack_interfaces, Only: ddisna, dgejsv
      Use lapack_precision, Only: dp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter :: nb = 64, nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=dp) :: eps, serrbd
      Integer :: i, ifail, info, j, lda, ldu, ldv, lwork, m, n
!     .. Local Arrays ..
      Real (Kind=dp), Allocatable :: a(:, :), rcondu(:), rcondv(:), s(:), &
        u(:, :), v(:, :), work(:)
      Integer, Allocatable :: iwork(:)
!     .. Intrinsic Procedures ..
      Intrinsic :: abs, epsilon, max
!     .. Executable Statements ..
      Write (nout, *) 'DGEJSV Example Program Results'
      Write (nout, *)
      Flush (nout)
!     Skip heading in data file
      Read (nin, *)
      Read (nin, *) m, n
      lda = m
      ldu = m
      ldv = n
      lwork = max(3*n+n*n+m, 3*n+n*n+n*nb, 7)
      Allocate (a(lda,n), rcondu(m), rcondv(m), s(n), u(ldu,n), v(ldv,n), &
        work(lwork), iwork(m+3*n))

!     Read the m by n matrix A from data file
      Read (nin, *)((a(i,j),j=1,n), i=1, m)

!     Compute the singular values and left and right singular vectors
!     of A (A = U*S*V^T, m.ge.n)
      Call dgejsv('E', 'U', 'V', 'R', 'N', 'N', m, n, a, lda, s, u, ldu, v, &
        ldv, work, lwork, iwork, info)

      If (info==0) Then

!       Compute the approximate error bound for the computed singular values
!       using the 2-norm, s(1) = norm(A), and machine precision, eps.
        eps = epsilon(1.0E0_dp)
        serrbd = eps*s(1)

!       Print solution
        If (abs(work(1)-work(2))<2.0_dp*eps) Then
!         No scaling required
          Write (nout, '(1X,A)') 'Singular values'
          Write (nout, 100)(s(j), j=1, n)
        Else
          Write (nout, '(/1X,A)') 'Scaled singular values'
          Write (nout, 100)(s(j), j=1, n)
          Write (nout, '(/1X,A)') 'For true singular values, multiply by a/b,'
          Write (nout, 130) ' where a = ', work(1), ' and b = ', work(2)
        End If

!       ifail: behaviour on error exit
!              =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
        Write (nout, *)
        Flush (nout)
        ifail = 0
        Call nagf_file_print_matrix_real_gen('General', ' ', m, n, u, ldu, &
          'Left singular vectors', ifail)

        Write (nout, *)
        Flush (nout)
        ifail = 0
        Call nagf_file_print_matrix_real_gen('General', ' ', n, n, v, ldv, &
          'Right singular vectors', ifail)

!       Call DDISNA to estimate reciprocal condition numbers for
!       the singular vectors.

        Call ddisna('Left', m, n, s, rcondu, info)
        Call ddisna('Right', m, n, s, rcondv, info)

!       Print the approximate error bounds for the singular values
!       and vectors.
        Write (nout, *)
        Write (nout, '(/1X,A)') &
          'Estimate of the condition number of column equilibrated A'
        Write (nout, 110) work(3)
        Write (nout, '(/1X,A)') 'Error estimate for the singular values'
        Write (nout, 110) serrbd
        Write (nout, '(/1X,A)') 'Error estimates for left singular vectors'
        Write (nout, 110)(serrbd/rcondu(i), i=1, n)
        Write (nout, '(/1X,A)') 'Error estimates for right singular vectors'
        Write (nout, 110)(serrbd/rcondv(i), i=1, n)
      Else
        Write (nout, 120) 'Failure in DGEJSV. INFO =', info
      End If

100   Format (3X, 8F8.4)
110   Format (4X, 1P, 6E11.1)
120   Format (1X, A, I4)
130   Format (1X, 2(A,1P,E13.5))
    End Program
Full documentation of DGEJSV


DGELQF example

Computational Routines: LQ factorization of real general rectangular matrix

Data

DGELQF Example Program Data
  4  6  2                                   :Values of M, N and NRHS
 -5.42   3.28  -3.68   0.27   2.06   0.46
 -1.65  -3.40  -3.20  -1.03  -4.06  -0.01
 -0.37   2.35   1.90   4.31  -1.76   1.13
 -3.15  -0.11   1.99  -2.70   0.26   4.50   :End of matrix A
 -2.87  -5.23
  1.63   0.29
 -3.52   4.76
  0.45  -8.41                               :End of matrix B

Result

 DGELQF Example Program Results

 Minimum-norm solution(s)
             1          2
 1      0.2371     0.7383
 2     -0.4575     0.0158
 3     -0.0085    -0.0161
 4     -0.5192     1.0768
 5      0.0239    -0.6436
 6     -0.0543    -0.6613

Source

    Program dgelqf_example

!     DGELQF Example Program Text

!     Copyright 2017, Numerical Algorithms Group Ltd. http://www.nag.com

!     .. Use Statements ..
      Use blas_interfaces, Only: dtrsm
      Use lapack_example_aux, Only: nagf_file_print_matrix_real_gen
      Use lapack_interfaces, Only: dgelqf, dormlq
      Use lapack_precision, Only: dp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Real (Kind=dp), Parameter :: one = 1.0E0_dp
      Real (Kind=dp), Parameter :: zero = 0.0E0_dp
      Integer, Parameter :: nin = 5, nout = 6
!     .. Local Scalars ..
      Integer :: i, ifail, info, lda, ldb, lwork, m, n, nrhs
!     .. Local Arrays ..
      Real (Kind=dp), Allocatable :: a(:, :), b(:, :), tau(:), work(:)
!     .. Executable Statements ..
      Write (nout, *) 'DGELQF Example Program Results'
!     Skip heading in data file
      Read (nin, *)
      Read (nin, *) m, n, nrhs
      lda = m
      ldb = n
      lwork = 64*n
      Allocate (a(lda,n), b(ldb,nrhs), tau(n), work(lwork))

!     Read A and B from data file

      Read (nin, *)(a(i,1:n), i=1, m)
      Read (nin, *)(b(i,1:nrhs), i=1, m)

!     Compute the LQ factorization of A
      Call dgelqf(m, n, a, lda, tau, work, lwork, info)

!     Solve L*Y = B, storing the result in B
      Call dtrsm('Left', 'Lower', 'No transpose', 'Non-Unit', m, nrhs, one, a, &
        lda, b, ldb)

!     Set rows (M+1) to N of B to zero

      If (m<n) Then
        b(m+1:n, 1:nrhs) = zero
      End If

!     Compute minimum-norm solution X = (Q**T)*B in B
      Call dormlq('Left', 'Transpose', n, nrhs, m, a, lda, tau, b, ldb, work, &
        lwork, info)

!     Print minimum-norm solution(s)

      Write (nout, *)
      Flush (nout)

!     ifail: behaviour on error exit
!             =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
      ifail = 0
      Call nagf_file_print_matrix_real_gen('General', ' ', n, nrhs, b, ldb, &
        'Minimum-norm solution(s)', ifail)

    End Program
Full documentation of DGELQF


DGEQLF example

Computational Routines: QL factorization of real general rectangular matrix

Data

DGEQLF Example Program Data

  6      4      2           :Values of M, N and NRHS

 -0.57  -1.28  -0.39   0.25
 -1.93   1.08  -0.31  -2.14
  2.30   0.24   0.40  -0.35
 -1.93   0.64  -0.66   0.08
  0.15   0.30   0.15  -2.13
 -0.02   1.03  -1.43   0.50 :End of matrix A

 -2.67   0.41
 -0.55  -3.10
  3.34  -4.01
 -0.77   2.76
  0.48  -6.17
  4.10   0.21               :End of matrix B

Result

 DGEQLF Example Program Results

 Least squares solution(s)
             1          2
 1      1.5339    -1.5753
 2      1.8707     0.5559
 3     -1.5241     1.3119
 4      0.0392     2.9585

 Square root(s) of the residual sum(s) of squares
        2.22E-02   1.38E-02

Source

    Program dgeqlf_example

!     DGEQLF Example Program Text

!     Copyright 2017, Numerical Algorithms Group Ltd. http://www.nag.com

!     .. Use Statements ..
      Use blas_interfaces, Only: dnrm2
      Use lapack_example_aux, Only: nagf_file_print_matrix_real_gen
      Use lapack_interfaces, Only: dgeqlf, dormql, dtrtrs
      Use lapack_precision, Only: dp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter :: nb = 64, nin = 5, nout = 6
!     .. Local Scalars ..
      Integer :: i, ifail, info, j, lda, ldb, lwork, m, n, nrhs
!     .. Local Arrays ..
      Real (Kind=dp), Allocatable :: a(:, :), b(:, :), rnorm(:), tau(:), &
        work(:)
!     .. Executable Statements ..
      Write (nout, *) 'DGEQLF Example Program Results'
      Write (nout, *)
      Flush (nout)
!     Skip heading in data file
      Read (nin, *)
      Read (nin, *) m, n, nrhs
      lda = m
      ldb = m
      lwork = nb*n
      Allocate (a(lda,n), b(ldb,nrhs), rnorm(nrhs), tau(n), work(lwork))

!     Read A and B from data file

      Read (nin, *)(a(i,1:n), i=1, m)
      Read (nin, *)(b(i,1:nrhs), i=1, m)

!     Compute the QL factorization of A
      Call dgeqlf(m, n, a, lda, tau, work, lwork, info)

!     Compute C = (C1) = (Q**T)*B, storing the result in B
!                  (C2)
      Call dormql('Left', 'Transpose', m, nrhs, n, a, lda, tau, b, ldb, work, &
        lwork, info)

!     Compute least squares solutions by back-substitution in
!     L*X = C2
      Call dtrtrs('Lower', 'No transpose', 'Non-Unit', n, nrhs, a(m-n+1,1), &
        lda, b(m-n+1,1), ldb, info)

      If (info>0) Then
        Write (nout, *) 'The lower triangular factor, L, of A is singular, '
        Write (nout, *) 'the least squares solution could not be computed'
      Else

!       Print least squares solution(s)

!       ifail: behaviour on error exit
!              =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
        ifail = 0
        Call nagf_file_print_matrix_real_gen('General', ' ', n, nrhs, &
          b(m-n+1,1), ldb, 'Least squares solution(s)', ifail)

!       Compute and print estimates of the square roots of the residual
!       sums of squares

        Do j = 1, nrhs
          rnorm(j) = dnrm2(m-n, b(1,j), 1)
        End Do

        Write (nout, *)
        Write (nout, *) 'Square root(s) of the residual sum(s) of squares'
        Write (nout, 100) rnorm(1:nrhs)
      End If

100   Format (5X, 1P, 7E11.2)
    End Program
Full documentation of DGEQLF


DGEQP3 example

Computational Routines: QR factorization of real general rectangular matrix with column pivoting, using BLAS-3

Data

DGEQP3 Example Program Data

  6      5      2                  :Values of M, N and NRHS

 -0.09   0.14  -0.46   0.68   1.29
 -1.56   0.20   0.29   1.09   0.51
 -1.48  -0.43   0.89  -0.71  -0.96
 -1.09   0.84   0.77   2.11  -1.27
  0.08   0.55  -1.13   0.14   1.74
 -1.59  -0.72   1.06   1.24   0.34 :End of matrix A

  7.4    2.7
  4.2   -3.0
 -8.3   -9.6
  1.8    1.1
  8.6    4.0
  2.1   -5.7                       :End of matrix B

Result

 DGEQP3 Example Program Results

 Tolerance used to estimate the rank of A
        1.00E-02
 Estimated rank of A
        4

 Least squares solution(s)
             1          2
 1      0.9767     4.0159
 2      1.9861     2.9867
 3      0.0000     0.0000
 4      2.9927     2.0032
 5      4.0272     0.9976

 Square root(s) of the residual sum(s) of squares
        2.54E-02   3.65E-02

Source

    Program dgeqp3_example

!     DGEQP3 Example Program Text

!     Copyright 2017, Numerical Algorithms Group Ltd. http://www.nag.com

!     .. Use Statements ..
      Use blas_interfaces, Only: dnrm2, dtrsm
      Use lapack_example_aux, Only: nagf_file_print_matrix_real_gen
      Use lapack_interfaces, Only: dgeqp3, dormqr
      Use lapack_precision, Only: dp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Real (Kind=dp), Parameter :: one = 1.0E0_dp
      Real (Kind=dp), Parameter :: zero = 0.0E0_dp
      Integer, Parameter :: inc1 = 1, nb = 64, nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=dp) :: tol
      Integer :: i, ifail, info, j, k, lda, ldb, lwork, m, n, nrhs
!     .. Local Arrays ..
      Real (Kind=dp), Allocatable :: a(:, :), b(:, :), rnorm(:), tau(:), &
        work(:)
      Integer, Allocatable :: jpvt(:)
!     .. Intrinsic Procedures ..
      Intrinsic :: abs
!     .. Executable Statements ..
      Write (nout, *) 'DGEQP3 Example Program Results'
      Write (nout, *)
!     Skip heading in data file
      Read (nin, *)
      Read (nin, *) m, n, nrhs
      lda = m
      ldb = m
      lwork = 2*n + (n+1)*nb
      Allocate (a(lda,n), b(ldb,nrhs), rnorm(n), tau(n), work(lwork), jpvt(n))

!     Read A and B from data file

      Read (nin, *)(a(i,1:n), i=1, m)
      Read (nin, *)(b(i,1:nrhs), i=1, m)

!     Initialize JPVT to be zero so that all columns are free

      jpvt(1:n) = 0

!     Compute the QR factorization of A
      Call dgeqp3(m, n, a, lda, jpvt, tau, work, lwork, info)

!     Compute C = (C1) = (Q**T)*B, storing the result in B
!                  (C2)
      Call dormqr('Left', 'Transpose', m, nrhs, n, a, lda, tau, b, ldb, work, &
        lwork, info)

!     Choose TOL to reflect the relative accuracy of the input data

      tol = 0.01_dp

!     Determine and print the rank, K, of R relative to TOL

loop: Do k = 1, n
        If (abs(a(k,k))<=tol*abs(a(1,1))) Then
          Exit loop
        End If
      End Do loop
      k = k - 1

      Write (nout, *) 'Tolerance used to estimate the rank of A'
      Write (nout, 100) tol
      Write (nout, *) 'Estimated rank of A'
      Write (nout, 110) k
      Write (nout, *)
      Flush (nout)

!     Compute least squares solutions by back-substitution in
!     R(1:K,1:K)*Y = C1, storing the result in B

      Call dtrsm('Left', 'Upper', 'No transpose', 'Non-Unit', k, nrhs, one, a, &
        lda, b, ldb)

!     Compute estimates of the square roots of the residual sums of
!     squares (2-norm of each of the columns of C2)

      Do j = 1, nrhs
        rnorm(j) = dnrm2(m-k, b(k+1,j), inc1)
      End Do

!     Set the remaining elements of the solutions to zero (to give
!     the basic solutions)

      b(k+1:n, 1:nrhs) = zero

!     Permute the least squares solutions stored in B to give X = P*Y

      Do j = 1, nrhs
        work(jpvt(1:n)) = b(1:n, j)
        b(1:n, j) = work(1:n)
      End Do

!     Print least squares solutions

!     ifail: behaviour on error exit
!             =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
      ifail = 0
      Call nagf_file_print_matrix_real_gen('General', ' ', n, nrhs, b, ldb, &
        'Least squares solution(s)', ifail)

!     Print the square roots of the residual sums of squares

      Write (nout, *)
      Write (nout, *) 'Square root(s) of the residual sum(s) of squares'
      Write (nout, 100) rnorm(1:nrhs)

100   Format (5X, 1P, 6E11.2)
110   Format (1X, I8)
    End Program
Full documentation of DGEQP3


DGEQRF example

Computational Routines: QR factorization of real general rectangular matrix

Data

DGEQRF Example Program Data

  6      4      2           :Values of M, N and NRHS

 -0.57  -1.28  -0.39   0.25
 -1.93   1.08  -0.31  -2.14
  2.30   0.24   0.40  -0.35
 -1.93   0.64  -0.66   0.08
  0.15   0.30   0.15  -2.13
 -0.02   1.03  -1.43   0.50 :End of matrix A

 -2.67   0.41
 -0.55  -3.10
  3.34  -4.01
 -0.77   2.76
  0.48  -6.17
  4.10   0.21               :End of matrix B

Result

 DGEQRF Example Program Results

 Least squares solution(s)
             1          2
 1      1.5339    -1.5753
 2      1.8707     0.5559
 3     -1.5241     1.3119
 4      0.0392     2.9585

 Square root(s) of the residual sum(s) of squares
        2.22E-02   1.38E-02

Source

    Program dgeqrf_example

!     DGEQRF Example Program Text

!     Copyright 2017, Numerical Algorithms Group Ltd. http://www.nag.com

!     .. Use Statements ..
      Use blas_interfaces, Only: dnrm2
      Use lapack_example_aux, Only: nagf_file_print_matrix_real_gen
      Use lapack_interfaces, Only: dgeqrf, dormqr, dtrtrs
      Use lapack_precision, Only: dp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter :: nb = 64, nin = 5, nout = 6
!     .. Local Scalars ..
      Integer :: i, ifail, info, j, lda, ldb, lwork, m, n, nrhs
!     .. Local Arrays ..
      Real (Kind=dp), Allocatable :: a(:, :), b(:, :), rnorm(:), tau(:), &
        work(:)
!     .. Executable Statements ..
      Write (nout, *) 'DGEQRF Example Program Results'
      Write (nout, *)
      Flush (nout)
!     Skip heading in data file
      Read (nin, *)
      Read (nin, *) m, n, nrhs
      lda = m
      ldb = m
      lwork = nb*n
      Allocate (a(lda,n), b(ldb,nrhs), rnorm(nrhs), tau(n), work(lwork))

!     Read A and B from data file

      Read (nin, *)(a(i,1:n), i=1, m)
      Read (nin, *)(b(i,1:nrhs), i=1, m)

!     Compute the QR factorization of A
      Call dgeqrf(m, n, a, lda, tau, work, lwork, info)

!     Compute C = (C1) = (Q**T)*B, storing the result in B
!                 (C2)
      Call dormqr('Left', 'Transpose', m, nrhs, n, a, lda, tau, b, ldb, work, &
        lwork, info)

!     Compute least squares solutions by back-substitution in
!     R*X = C1
      Call dtrtrs('Upper', 'No transpose', 'Non-Unit', n, nrhs, a, lda, b, &
        ldb, info)

      If (info>0) Then
        Write (nout, *) 'The upper triangular factor, R, of A is singular, '
        Write (nout, *) 'the least squares solution could not be computed'
      Else

!       Print least squares solutions

!       ifail: behaviour on error exit
!              =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
        ifail = 0
        Call nagf_file_print_matrix_real_gen('General', ' ', n, nrhs, b, ldb, &
          'Least squares solution(s)', ifail)

!       Compute and print estimates of the square roots of the residual
!       sums of squares

        Do j = 1, nrhs
          rnorm(j) = dnrm2(m-n, b(n+1,j), 1)
        End Do

        Write (nout, *)
        Write (nout, *) 'Square root(s) of the residual sum(s) of squares'
        Write (nout, 100) rnorm(1:nrhs)
      End If

100   Format (5X, 1P, 7E11.2)
    End Program
Full documentation of DGEQRF


DGEQRT example

Computational Routines: Performs a QR factorization of real general rectangular matrix, with explicit blocking

Data

DGEQRT Example Program Data

  6      4      2           : m, n and nrhs

 -0.57  -1.28  -0.39   0.25
 -1.93   1.08  -0.31  -2.14
  2.30   0.24   0.40  -0.35
 -1.93   0.64  -0.66   0.08
  0.15   0.30   0.15  -2.13
 -0.02   1.03  -1.43   0.50 : matrix A

 -2.67   0.41
 -0.55  -3.10
  3.34  -4.01
 -0.77   2.76
  0.48  -6.17
  4.10   0.21               : matrix B

Result

 DGEQRT Example Program Results

 Least squares solution(s)
             1          2
 1      1.5339    -1.5753
 2      1.8707     0.5559
 3     -1.5241     1.3119
 4      0.0392     2.9585

 Square root(s) of the residual sum(s) of squares
        2.22E-02   1.38E-02

Source

    Program dgeqrt_example

!     DGEQRT Example Program Text

!     Copyright 2017, Numerical Algorithms Group Ltd. http://www.nag.com

!     .. Use Statements ..
      Use blas_interfaces, Only: dnrm2
      Use lapack_example_aux, Only: nagf_file_print_matrix_real_gen
      Use lapack_interfaces, Only: dgemqrt, dgeqrt, dtrtrs
      Use lapack_precision, Only: dp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter :: nbmax = 64, nin = 5, nout = 6
!     .. Local Scalars ..
      Integer :: i, ifail, info, j, lda, ldb, ldt, lwork, m, n, nb, nrhs
!     .. Local Arrays ..
      Real (Kind=dp), Allocatable :: a(:, :), b(:, :), rnorm(:), t(:, :), &
        work(:)
!     .. Intrinsic Procedures ..
      Intrinsic :: max, min
!     .. Executable Statements ..
      Write (nout, *) 'DGEQRT Example Program Results'
      Write (nout, *)
      Flush (nout)
!     Skip heading in data file
      Read (nin, *)
      Read (nin, *) m, n, nrhs
      lda = m
      ldb = m
      nb = min(m, n, nbmax)
      ldt = nb
      lwork = nb*max(n, m)
      Allocate (a(lda,n), b(ldb,nrhs), rnorm(nrhs), t(ldt,min(m, &
        n)), work(lwork))

!     Read A and B from data file

      Read (nin, *)(a(i,1:n), i=1, m)
      Read (nin, *)(b(i,1:nrhs), i=1, m)

!     Compute the QR factorization of A
      Call dgeqrt(m, n, nb, a, lda, t, ldt, work, info)

!     Compute C = (C1) = (Q**T)*B, storing the result in B
!                 (C2)
      Call dgemqrt('Left', 'Transpose', m, nrhs, n, nb, a, lda, t, ldt, b, &
        ldb, work, info)

!     Compute least squares solutions by back-substitution in
!     R*X = C1
      Call dtrtrs('Upper', 'No transpose', 'Non-Unit', n, nrhs, a, lda, b, &
        ldb, info)

      If (info>0) Then
        Write (nout, *) 'The upper triangular factor, R, of A is singular, '
        Write (nout, *) 'the least squares solution could not be computed'
      Else

!       Print least squares solutions

!       ifail: behaviour on error exit
!              =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
        ifail = 0
        Call nagf_file_print_matrix_real_gen('General', ' ', n, nrhs, b, ldb, &
          'Least squares solution(s)', ifail)

!       Compute and print estimates of the square roots of the residual
!       sums of squares

        Do j = 1, nrhs
          rnorm(j) = dnrm2(m-n, b(n+1,j), 1)
        End Do

        Write (nout, *)
        Write (nout, *) 'Square root(s) of the residual sum(s) of squares'
        Write (nout, 100) rnorm(1:nrhs)
      End If

100   Format (5X, 1P, 7E11.2)
    End Program
Full documentation of DGEQRT


DGERFS example

Computational Routines: Refined solution with error bounds of real system of linear equations, multiple right-hand sides

Data

DGERFS Example Program Data
  4  2                        :Values of N and NRHS
  1.80   2.88   2.05  -0.89
  5.25  -2.95  -0.95  -3.80
  1.58  -2.69  -2.90  -1.04
 -1.11  -0.66  -0.59   0.80   :End of matrix A
  9.52  18.47
 24.35   2.25
  0.77 -13.28
 -6.22  -6.21                 :End of matrix B

Result

 DGERFS Example Program Results

 Solution(s)
             1          2
 1      1.0000     3.0000
 2     -1.0000     2.0000
 3      3.0000     4.0000
 4     -5.0000     1.0000

 Backward errors (machine-dependent)
       9.4E-17    3.7E-17
 Estimated forward error bounds (machine-dependent)
       2.4E-14    3.3E-14

Source

    Program dgerfs_example

!     DGERFS Example Program Text

!     Copyright 2017, Numerical Algorithms Group Ltd. http://www.nag.com

!     .. Use Statements ..
      Use lapack_example_aux, Only: nagf_file_print_matrix_real_gen
      Use lapack_interfaces, Only: dgerfs, dgetrf, dgetrs
      Use lapack_precision, Only: dp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter :: nin = 5, nout = 6
      Character (1), Parameter :: trans = 'N'
!     .. Local Scalars ..
      Integer :: i, ifail, info, lda, ldaf, ldb, ldx, n, nrhs
!     .. Local Arrays ..
      Real (Kind=dp), Allocatable :: a(:, :), af(:, :), b(:, :), berr(:), &
        ferr(:), work(:), x(:, :)
      Integer, Allocatable :: ipiv(:), iwork(:)
!     .. Executable Statements ..
      Write (nout, *) 'DGERFS Example Program Results'
!     Skip heading in data file
      Read (nin, *)
      Read (nin, *) n, nrhs
      lda = n
      ldaf = n
      ldb = n
      ldx = n
      Allocate (a(lda,n), af(ldaf,n), b(ldb,nrhs), berr(nrhs), ferr(nrhs), &
        work(3*n), x(ldx,n), ipiv(n), iwork(n))

!     Read A and B from data file, and copy A to AF and B to X

      Read (nin, *)(a(i,1:n), i=1, n)
      Read (nin, *)(b(i,1:nrhs), i=1, n)

      af(1:n, 1:n) = a(1:n, 1:n)
      x(1:n, 1:nrhs) = b(1:n, 1:nrhs)

!     Factorize A in the array AF

      Call dgetrf(n, n, af, ldaf, ipiv, info)

      Write (nout, *)
      Flush (nout)
      If (info==0) Then

!       Compute solution in the array X

        Call dgetrs(trans, n, nrhs, af, ldaf, ipiv, x, ldx, info)

!       Improve solution, and compute backward errors and
!       estimated bounds on the forward errors

        Call dgerfs(trans, n, nrhs, a, lda, af, ldaf, ipiv, b, ldb, x, ldx, &
          ferr, berr, work, iwork, info)

!       Print solution

!       ifail: behaviour on error exit
!              =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
        ifail = 0

        Call nagf_file_print_matrix_real_gen('General', ' ', n, nrhs, x, ldx, &
          'Solution(s)', ifail)

        Write (nout, *)
        Write (nout, *) 'Backward errors (machine-dependent)'
        Write (nout, 100) berr(1:nrhs)
        Write (nout, *) 'Estimated forward error bounds (machine-dependent)'
        Write (nout, 100) ferr(1:nrhs)
      Else
        Write (nout, *) 'The factor U is singular'
      End If

100   Format ((3X,1P,7E11.1))
    End Program
Full documentation of DGERFS


DGERQF example

Computational Routines: RQ factorization of real general rectangular matrix

Data

DGERQF Example Program Data

  4      6                                :Values of M and N

 -5.42   3.28  -3.68   0.27   2.06   0.46
 -1.65  -3.40  -3.20  -1.03  -4.06  -0.01
 -0.37   2.35   1.90   4.31  -1.76   1.13
 -3.15  -0.11   1.99  -2.70   0.26   4.50 :End of matrix A

 -2.87
  1.63
 -3.52
  0.45                                    :End of vector b

Result

 DGERQF Example Program Results

 Minimum-norm solution
    0.2371  -0.4575  -0.0085  -0.5192   0.0239  -0.0543

Source

    Program dgerqf_example

!     DGERQF Example Program Text

!     Copyright 2017, Numerical Algorithms Group Ltd. http://www.nag.com

!     .. Use Statements ..
      Use lapack_interfaces, Only: dgerqf, dormrq, dtrtrs
      Use lapack_precision, Only: dp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Real (Kind=dp), Parameter :: zero = 0.0E0_dp
      Integer, Parameter :: nb = 64, nin = 5, nout = 6
!     .. Local Scalars ..
      Integer :: i, info, lda, lwork, m, n
!     .. Local Arrays ..
      Real (Kind=dp), Allocatable :: a(:, :), b(:), tau(:), work(:), x(:)
!     .. Executable Statements ..
      Write (nout, *) 'DGERQF Example Program Results'
      Write (nout, *)
!     Skip heading in data file
      Read (nin, *)
      Read (nin, *) m, n
      lda = m
      lwork = nb*m
      Allocate (a(lda,n), b(m), tau(m), work(lwork), x(n))

!     Read the matrix A and the vector b from data file

      Read (nin, *)(a(i,1:n), i=1, m)
      Read (nin, *) b(1:m)

!     Compute the RQ factorization of A
      Call dgerqf(m, n, a, lda, tau, work, lwork, info)

!     Copy the m element vector b into elements x(n-m+1), ..., x(n) of x

      x(n-m+1:n) = b(1:m)

!     Solve R*y2 = b, storing the result in x2
      Call dtrtrs('Upper', 'No transpose', 'Non-Unit', m, 1, a(1,n-m+1), lda, &
        x(n-m+1), m, info)

      If (info>0) Then
        Write (nout, *) 'The upper triangular factor, R, of A is singular, '
        Write (nout, *) 'the least squares solution could not be computed'
      Else

        x(1:n-m) = zero

!       Compute the minimum-norm solution x = (Q**T)*y
        Call dormrq('Left', 'Transpose', n, 1, m, a, lda, tau, x, n, work, &
          lwork, info)

!       Print minimum-norm solution

        Write (nout, *) 'Minimum-norm solution'
        Write (nout, 100) x(1:n)

      End If

100   Format (1X, 8F9.4)
    End Program
Full documentation of DGERQF


DGESVJ example

Computational Routines: Computes the singular value decomposition of a real matrix, optionally computing the left and/or right singular vectors (fast Jacobi)

Data

DGESVJ Example Program Data

   6      4                   :Values of M and N

   2.27  -1.54   1.15  -1.94
   0.28  -1.67   0.94  -0.78
  -0.48  -3.09   0.99  -0.21
   1.07   1.22   0.79   0.63
  -2.35   2.93  -1.45   2.30
   0.62  -7.39   1.03  -2.57  :End of matrix A

Result

 DGESVJ Example Program Results

 Singular values
     9.9966  3.6831  1.3569  0.5000
 Left singular vectors
          1       2       3       4
 1  -0.2774  0.6003 -0.1277  0.1323
 2  -0.2020  0.0301  0.2805  0.7034
 3  -0.2918 -0.3348  0.6453  0.1906
 4   0.0938  0.3699  0.6781 -0.5399
 5   0.4213 -0.5266  0.0413 -0.0575
 6  -0.7816 -0.3353 -0.1645 -0.3957

 Right singular vectors
          1       2       3       4
 1  -0.1921  0.8030  0.0041 -0.5642
 2   0.8794  0.3926 -0.0752  0.2587
 3  -0.2140  0.2980  0.7827  0.5027
 4   0.3795 -0.3351  0.6178 -0.6017

 Error estimate for the singular values
        2.2E-15

 Error estimates for left singular vectors
        3.5E-16    9.5E-16    2.6E-15    4.4E-15

 Error estimates for right singular vectors
        3.5E-16    9.5E-16    2.6E-15    2.6E-15

Source

    Program dgesvj_example

!     DGESVJ Example Program Text

!     Copyright 2017, Numerical Algorithms Group Ltd. http://www.nag.com

!     .. Use Statements ..
      Use lapack_example_aux, Only: nagf_file_print_matrix_real_gen
      Use lapack_interfaces, Only: ddisna, dgesvj
      Use lapack_precision, Only: dp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=dp) :: eps, serrbd
      Integer :: i, ifail, info, j, lda, ldv, lwork, m, n
!     .. Local Arrays ..
      Real (Kind=dp), Allocatable :: a(:, :), rcondu(:), rcondv(:), s(:), &
        v(:, :), work(:)
!     .. Intrinsic Procedures ..
      Intrinsic :: abs, epsilon
!     .. Executable Statements ..
      Write (nout, *) 'DGESVJ Example Program Results'
      Write (nout, *)
      Flush (nout)
!     Skip heading in data file
      Read (nin, *)
      Read (nin, *) m, n
      lda = m
      ldv = n
      lwork = n + m
      Allocate (a(lda,n), rcondu(m), rcondv(m), s(n), v(ldv,n), work(lwork))

!     Read the m by n matrix A from data file

      Read (nin, *)((a(i,j),j=1,n), i=1, m)

!     Compute the singular values and left and right singular vectors
!     of A (A = U*S*V, m.ge.n)

      Call dgesvj('G', 'U', 'V', m, n, a, lda, s, 0, v, ldv, work, lwork, &
        info)

      If (info==0) Then

!       Compute the approximate error bound for the computed singular values
!       using the 2-norm, s(1) = norm(A), and machine precision, eps.
        eps = epsilon(1.0E0_dp)
        serrbd = eps*s(1)

!       Print solution
        Write (nout, *) 'Singular values'
        Write (nout, 100)(s(j), j=1, n)

        If (abs(work(1)-1.0_dp)>eps) Then
          Write (nout, 130) 'Values need scaling by factor = ', work(1)
        End If
        Flush (nout)

!       ifail: behaviour on error exit
!              =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
        ifail = 0
        Call nagf_file_print_matrix_real_gen('General', ' ', m, n, a, lda, &
          'Left singular vectors', ifail)

        Write (nout, *)
        Flush (nout)

        ifail = 0
        Call nagf_file_print_matrix_real_gen('General', ' ', n, n, v, ldv, &
          'Right singular vectors', ifail)

!       Call DDISNA to estimate reciprocal condition
!       numbers for the singular vectors
        Call ddisna('Left', m, n, s, rcondu, info)
        Call ddisna('Right', m, n, s, rcondv, info)

!       Print the approximate error bounds for the singular values
!       and vectors
        Write (nout, '(/1X,A)') 'Error estimate for the singular values'
        Write (nout, 110) serrbd
        Write (nout, '(/1X,A)') 'Error estimates for left singular vectors'
        Write (nout, 110)(serrbd/rcondu(i), i=1, n)
        Write (nout, '(/1X,A)') 'Error estimates for right singular vectors'
        Write (nout, 110)(serrbd/rcondv(i), i=1, n)
      Else
        Write (nout, 120) 'Failure in DGESVJ. INFO =', info
      End If

100   Format (3X, (8F8.4))
110   Format (4X, 1P, 6E11.1)
120   Format (1X, A, I4)
130   Format (/, 1X, A, 1P, E13.5)
    End Program
Full documentation of DGESVJ


DGETRF example

Computational Routines: LU factorization of real m by n matrix

Data

DGETRF Example Program Data
  4  4                        :Values of M and N
  1.80   2.88   2.05  -0.89
  5.25  -2.95  -0.95  -3.80
  1.58  -2.69  -2.90  -1.04
 -1.11  -0.66  -0.59   0.80   :End of matrix A

Result

 DGETRF Example Program Results

 Details of factorization
             1          2          3          4
 1      5.2500    -2.9500    -0.9500    -3.8000
 2      0.3429     3.8914     2.3757     0.4129
 3      0.3010    -0.4631    -1.5139     0.2948
 4     -0.2114    -0.3299     0.0047     0.1314

 IPIV
             2          2          3          4

Source

    Program dgetrf_example

!     DGETRF Example Program Text

!     Copyright 2017, Numerical Algorithms Group Ltd. http://www.nag.com

!     .. Use Statements ..
      Use lapack_example_aux, Only: nagf_file_print_matrix_real_gen
      Use lapack_interfaces, Only: dgetrf
      Use lapack_precision, Only: dp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter :: nin = 5, nout = 6
!     .. Local Scalars ..
      Integer :: i, ifail, info, lda, m, n
!     .. Local Arrays ..
      Real (Kind=dp), Allocatable :: a(:, :)
      Integer, Allocatable :: ipiv(:)
!     .. Intrinsic Procedures ..
      Intrinsic :: min
!     .. Executable Statements ..
      Write (nout, *) 'DGETRF Example Program Results'
!     Skip heading in data file
      Read (nin, *)
      Read (nin, *) m, n
      lda = m
      Allocate (a(lda,n), ipiv(n))

!     Read A from data file

      Read (nin, *)(a(i,1:n), i=1, m)

!     Factorize A

      Call dgetrf(m, n, a, lda, ipiv, info)

!     Print details of factorization

      Write (nout, *)
      Flush (nout)

!     ifail: behaviour on error exit
!             =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
      ifail = 0
      Call nagf_file_print_matrix_real_gen('General', ' ', m, n, a, lda, &
        'Details of factorization', ifail)

!     Print pivot indices

      Write (nout, *)
      Write (nout, *) 'IPIV'
      Write (nout, 100) ipiv(1:min(m,n))

      If (info/=0) Then
        Write (nout, *) 'The factor U is singular'
      End If

100   Format ((3X,7I11))
    End Program
Full documentation of DGETRF


DGETRI example

Computational Routines: Inverse of real matrix, matrix already factorized by DGETRF

Data

DGETRI Example Program Data
  4                           :Value of N
  1.80   2.88   2.05  -0.89
  5.25  -2.95  -0.95  -3.80
  1.58  -2.69  -2.90  -1.04
 -1.11  -0.66  -0.59   0.80   :End of matrix A

Result

 DGETRI Example Program Results

 Inverse
             1          2          3          4
 1      1.7720     0.5757     0.0843     4.8155
 2     -0.1175    -0.4456     0.4114    -1.7126
 3      0.1799     0.4527    -0.6676     1.4824
 4      2.4944     0.7650    -0.0360     7.6119

Source

    Program dgetri_example

!     DGETRI Example Program Text

!     Copyright 2017, Numerical Algorithms Group Ltd. http://www.nag.com

!     .. Use Statements ..
      Use lapack_example_aux, Only: nagf_file_print_matrix_real_gen
      Use lapack_interfaces, Only: dgetrf, dgetri
      Use lapack_precision, Only: dp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter :: nin = 5, nout = 6
!     .. Local Scalars ..
      Integer :: i, ifail, info, lda, lwork, n
!     .. Local Arrays ..
      Real (Kind=dp), Allocatable :: a(:, :), work(:)
      Integer, Allocatable :: ipiv(:)
!     .. Executable Statements ..
      Write (nout, *) 'DGETRI Example Program Results'
!     Skip heading in data file
      Read (nin, *)
      Read (nin, *) n
      lda = n
      lwork = 64*n
      Allocate (a(lda,n), work(lwork), ipiv(n))

!     Read A from data file

      Read (nin, *)(a(i,1:n), i=1, n)

!     Factorize A

      Call dgetrf(n, n, a, lda, ipiv, info)

      Write (nout, *)
      Flush (nout)
      If (info==0) Then

!       Compute inverse of A

        Call dgetri(n, a, lda, ipiv, work, lwork, info)

!       Print inverse

!       ifail: behaviour on error exit
!              =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
        ifail = 0
        Call nagf_file_print_matrix_real_gen('General', ' ', n, n, a, lda, &
          'Inverse', ifail)

      Else
        Write (nout, *) 'The factor U is singular'
      End If

    End Program
Full documentation of DGETRI


DGETRS example

Computational Routines: Solution of real system of linear equations, multiple right-hand sides, matrix already factorized by DGETRF

Data

DGETRS Example Program Data
  4  2                        :Values of N and NRHS
  1.80   2.88   2.05  -0.89
  5.25  -2.95  -0.95  -3.80
  1.58  -2.69  -2.90  -1.04
 -1.11  -0.66  -0.59   0.80   :End of matrix A
  9.52  18.47
 24.35   2.25
  0.77 -13.28
 -6.22  -6.21                 :End of matrix B

Result

 DGETRS Example Program Results

 Solution(s)
             1          2
 1      1.0000     3.0000
 2     -1.0000     2.0000
 3      3.0000     4.0000
 4     -5.0000     1.0000

Source

    Program dgetrs_example

!     DGETRS Example Program Text

!     Copyright 2017, Numerical Algorithms Group Ltd. http://www.nag.com

!     .. Use Statements ..
      Use lapack_example_aux, Only: nagf_file_print_matrix_real_gen
      Use lapack_interfaces, Only: dgetrf, dgetrs
      Use lapack_precision, Only: dp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter :: nin = 5, nout = 6
      Character (1), Parameter :: trans = 'N'
!     .. Local Scalars ..
      Integer :: i, ifail, info, lda, ldb, n, nrhs
!     .. Local Arrays ..
      Real (Kind=dp), Allocatable :: a(:, :), b(:, :)
      Integer, Allocatable :: ipiv(:)
!     .. Executable Statements ..
      Write (nout, *) 'DGETRS Example Program Results'
!     Skip heading in data file
      Read (nin, *)
      Read (nin, *) n, nrhs
      lda = n
      ldb = n
      Allocate (a(lda,n), b(ldb,nrhs), ipiv(n))

!     Read A and B from data file

      Read (nin, *)(a(i,1:n), i=1, n)
      Read (nin, *)(b(i,1:nrhs), i=1, n)

!     Factorize A

      Call dgetrf(n, n, a, lda, ipiv, info)

      Write (nout, *)
      Flush (nout)
      If (info==0) Then

!       Compute solution

        Call dgetrs(trans, n, nrhs, a, lda, ipiv, b, ldb, info)

!       Print solution

!       ifail: behaviour on error exit
!              =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
        ifail = 0
        Call nagf_file_print_matrix_real_gen('General', ' ', n, nrhs, b, ldb, &
          'Solution(s)', ifail)
      Else
        Write (nout, *) 'The factor U is singular'
      End If

    End Program
Full documentation of DGETRS


DGGQRF example

Computational Routines: Computes a generalized QR factorization of a real matrix pair

Data

DGGQRF Example Program Data

  4      3      4           :Values of N, M and P

 -0.57  -1.28  -0.39
 -1.93   1.08  -0.31
  2.30   0.24  -0.40
 -0.02   1.03  -1.43        :End of matrix A

  0.50   0.00   0.00   0.00
  0.00   1.00   0.00   0.00
  0.00   0.00   2.00   0.00
  0.00   0.00   0.00   5.00 :End of matrix B

  1.32
 -4.00
  5.52
  3.24                      :End of vector d

Result

 DGGQRF Example Program Results

 Generalized least squares solution
      1.9889    -1.0058    -2.9911

 Residual vector
     -6.37E-04  -2.45E-03  -4.72E-03   7.70E-03

 Square root of the residual sum of squares
      9.38E-03

Source

    Program dggqrf_example

!     DGGQRF Example Program Text

!     Copyright 2017, Numerical Algorithms Group Ltd. http://www.nag.com

!     .. Use Statements ..
      Use blas_interfaces, Only: dgemv, dnrm2
      Use lapack_interfaces, Only: dggqrf, dormqr, dormrq, dtrtrs
      Use lapack_precision, Only: dp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Real (Kind=dp), Parameter :: one = 1.0E0_dp
      Real (Kind=dp), Parameter :: zero = 0.0E0_dp
      Integer, Parameter :: nb = 64, nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=dp) :: rnorm
      Integer :: i, info, lda, ldb, lwork, m, n, p
!     .. Local Arrays ..
      Real (Kind=dp), Allocatable :: a(:, :), b(:, :), d(:), taua(:), taub(:), &
        work(:), y(:)
!     .. Intrinsic Procedures ..
      Intrinsic :: max, min
!     .. Executable Statements ..
      Write (nout, *) 'DGGQRF Example Program Results'
      Write (nout, *)
!     Skip heading in data file
      Read (nin, *)
      Read (nin, *) n, m, p
      lda = n
      ldb = n
      lwork = nb*(m+p)
      Allocate (a(lda,m), b(ldb,p), d(n), taua(m), taub(m+p), work(lwork), &
        y(p))

!     Read A, B and D from data file
      Read (nin, *)(a(i,1:m), i=1, n)
      Read (nin, *)(b(i,1:p), i=1, n)
      Read (nin, *) d(1:n)

!     Compute the generalized QR factorization of (A,B) as
!     A = Q*(R),   B = Q*(T11 T12)*Z
!            (0)          ( 0  T22)
      Call dggqrf(n, m, p, a, lda, taua, b, ldb, taub, work, lwork, info)

!     Compute c = (c1) = (Q**T)*d, storing the result in D
!                  (c2)
      Call dormqr('Left', 'Transpose', n, 1, m, a, lda, taua, d, n, work, &
        lwork, info)

!     Putting Z*y = w = (w1), set w1 = 0, storing the result in Y1
!                        (w2)
      y(1:m+p-n) = zero

      If (n>m) Then

!       Copy c2 into Y2
        y(m+p-n+1:p) = d(m+1:n)

!       Solve T22*w2 = c2 for w2, storing result in Y2
        Call dtrtrs('Upper', 'No transpose', 'Non-unit', n-m, 1, &
          b(m+1,m+p-n+1), ldb, y(m+p-n+1), n-m, info)

        If (info>0) Then
          Write (nout, *) &
            'The upper triangular factor, T22, of B is singular, '
          Write (nout, *) 'the least squares solution could not be computed'
          Go To 100
        End If

!       Compute estimate of the square root of the residual sum of squares
!       norm(y) = norm(w2)

        rnorm = dnrm2(n-m, y(m+p-n+1), 1)

!       Form c1 - T12*w2 in D
        Call dgemv('No transpose', m, n-m, -one, b(1,m+p-n+1), ldb, &
          y(m+p-n+1), 1, one, d, 1)
      End If

!     Solve R*x = c1 - T12*w2 for x
      Call dtrtrs('Upper', 'No transpose', 'Non-unit', m, 1, a, lda, d, m, &
        info)

      If (info>0) Then
        Write (nout, *) 'The upper triangular factor, R, of A is singular, '
        Write (nout, *) 'the least squares solution could not be computed'
      Else

!       Compute y = (Z**T)*w
        Call dormrq('Left', 'Transpose', p, 1, min(n,p), b(max(1, &
          n-p+1),1), ldb, taub, y, p, work, lwork, info)

!       Print least squares solution x

        Write (nout, *) 'Generalized least squares solution'
        Write (nout, 110) d(1:m)

!       Print residual vector y

        Write (nout, *)
        Write (nout, *) 'Residual vector'
        Write (nout, 120) y(1:p)

!       Print estimate of the square root of the residual sum of squares

        Write (nout, *)
        Write (nout, *) 'Square root of the residual sum of squares'
        Write (nout, 120) rnorm
      End If
100   Continue

110   Format (1X, 7F11.4)
120   Format (3X, 1P, 7E11.2)
    End Program
Full documentation of DGGQRF


DGGRQF example

Computational Routines: Computes a generalized RQ factorization of a real matrix pair

Data

DGGRQF Example Program Data

  6      4      2           : m, n and p

 -0.57  -1.28  -0.39   0.25
 -1.93   1.08  -0.31  -2.14
  2.30   0.24   0.40  -0.35
 -1.93   0.64  -0.66   0.08
  0.15   0.30   0.15  -2.13
 -0.02   1.03  -1.43   0.50 : A

  1.00   0.00  -1.00   0.00
  0.00   1.00   0.00  -1.00 : B

 -1.50
 -2.14
  1.23
 -0.54
 -1.68
  0.82                      : c

  0.00
  0.00                      : d

Result

 DGGRQF Example Program Results

 Constrained least squares solution
      0.4890     0.9975     0.4890     0.9975

 Square root of the residual sum of squares
      2.51E-02

Source

    Program dggrqf_example

!     DGGRQF Example Program Text

!     Copyright 2017, Numerical Algorithms Group Ltd. http://www.nag.com

!     .. Use Statements ..
      Use blas_interfaces, Only: dgemv, dnrm2, dtrmv
      Use lapack_interfaces, Only: dggrqf, dormqr, dormrq, dtrtrs
      Use lapack_precision, Only: dp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Real (Kind=dp), Parameter :: one = 1.0E0_dp
      Integer, Parameter :: nb = 64, nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=dp) :: rnorm
      Integer :: i, info, lda, ldb, lwork, m, n, p
!     .. Local Arrays ..
      Real (Kind=dp), Allocatable :: a(:, :), b(:, :), c(:), d(:), taua(:), &
        taub(:), work(:), x(:)
!     .. Intrinsic Procedures ..
      Intrinsic :: min
!     .. Executable Statements ..
      Write (nout, *) 'DGGRQF Example Program Results'
      Write (nout, *)
!     Skip heading in data file
      Read (nin, *)
      Read (nin, *) m, n, p
      lda = m
      ldb = p
      lwork = nb*(p+n)
      Allocate (a(lda,n), b(ldb,n), c(m), d(p), taua(n), taub(n), work(lwork), &
        x(n))

!     Read B, A, C and D from data file
      Read (nin, *)(a(i,1:n), i=1, m)
      Read (nin, *)(b(i,1:n), i=1, p)
      Read (nin, *) c(1:m)
      Read (nin, *) d(1:p)

!     Compute the generalized RQ factorization of (B,A) as
!     B = (0 T12)*Q,   A = Z*(R11 R12)*Q, where T12, R11
!                            ( 0  R22)
!     are upper triangular
      Call dggrqf(p, m, n, b, ldb, taub, a, lda, taua, work, lwork, info)

!     Set Qx = y. The problem then reduces to:
!                 minimize (Ry - Z^Tc) subject to Ty = d
!     Update c = Z^T*c -> minimize (Ry-c)
      Call dormqr('Left', 'Transpose', m, 1, min(m,n), a, lda, taua, c, m, &
        work, lwork, info)

!     Putting y = (y1), solve T12*w = d for w, storing result in d
!                 (w )
      Call dtrtrs('Upper', 'No transpose', 'Non-unit', p, 1, b(1,n-p+1), ldb, &
        d, p, info)

      If (info>0) Then
        Write (nout, *) 'The upper triangular factor of B is singular, '
        Write (nout, *) 'the least squares solution could not be computed'
        Go To 100
      End If

!     From first n-p rows of (Ry-c) we have: R11*y1 + R12*w = c(1:n-p) = c1
!     Form c1 = c1 - R12*w = R11*y1
      Call dgemv('No transpose', n-p, p, -one, a(1,n-p+1), lda, d, 1, one, c, &
        1)

!     Solve R11*y1 = c1 for y1, storing result in c(1:n-p)
      Call dtrtrs('Upper', 'No transpose', 'Non-unit', n-p, 1, a, lda, c, n-p, &
        info)

      If (info>0) Then
        Write (nout, *) 'The upper triangular factor of A is singular, '
        Write (nout, *) 'the least squares solution could not be computed'
        Go To 100
      End If

!     Copy y into X (first y1, then w)
      x(1:n-p) = c(1:n-p)
      x(n-p+1:n) = d(1:p)

!     Compute x = (Q**T)*y
      Call dormrq('Left', 'Transpose', n, 1, p, b, ldb, taub, x, n, work, &
        lwork, info)

!     The least squares solution is in x, the remainder here is to compute
!     the residual, which equals c2 - R22*w.

!     Upper triangular part of R22 first
      Call dtrmv('Upper', 'No transpose', 'Non-unit', min(m,n)-n+p, &
        a(n-p+1,n-p+1), lda, d, 1)
      Do i = 1, min(m, n) - n + p
        c(n-p+i) = c(n-p+i) - d(i)
      End Do

      If (m<n) Then

!       Additional rectangular part of R22
        Call dgemv('No transpose', m-n+p, n-m, -one, a(n-p+1,m+1), lda, &
          d(m-n+p+1), 1, one, c(n-p+1), 1)
      End If

!     Compute norm of residual sum of squares.
      rnorm = dnrm2(m-(n-p), c(n-p+1), 1)

!     Print least squares solution x
      Write (nout, *) 'Constrained least squares solution'
      Write (nout, 110) x(1:n)

!     Print estimate of the square root of the residual sum of squares
      Write (nout, *)
      Write (nout, *) 'Square root of the residual sum of squares'
      Write (nout, 120) rnorm

100   Continue

110   Format (1X, 7F11.4)
120   Format (3X, 1P, E11.2)
    End Program
Full documentation of DGGRQF


DGGSVP3 example

Computational Routines: Produces orthogonal matrices, using BLAS-3, that simultaneously reduce the m by n matrix A and the p by n matrix B to upper triangular form

Data

DGGSVP3 Example Program Data

  4    3    2   :Values of M, N and P

  1.0  2.0  3.0
  3.0  2.0  1.0
  4.0  5.0  6.0
  7.0  8.0  8.0 :End of matrix A

 -2.0 -3.0  3.0
  4.0  6.0  5.0 :End of matrix B

Result

 DGGSVP3 Example Program Results

 Number of infinite generalized singular values (k)
     1
 Number of finite generalized singular values (l)
     2
 Effective Numerical rank of (A; B) (k+l)
     3

 Finite generalized singular values
     1.3151E+00  8.0185E-02

 Orthogonal matrix U
              1           2           3           4
 1  -1.3484E-01  5.2524E-01 -2.0924E-01  8.1373E-01
 2   6.7420E-01 -5.2213E-01 -3.8886E-01  3.4874E-01
 3   2.6968E-01  5.2757E-01 -6.5782E-01 -4.6499E-01
 4   6.7420E-01  4.1615E-01  6.1014E-01  1.5127E-15

 Orthogonal matrix V
              1           2
 1   3.5539E-01 -9.3472E-01
 2   9.3472E-01  3.5539E-01

 Orthogonal matrix Q
              1           2           3
 1  -8.3205E-01 -9.4633E-02 -5.4657E-01
 2   5.5470E-01 -1.4195E-01 -8.1985E-01
 3   0.0000E+00 -9.8534E-01  1.7060E-01

 Nonsingular upper triangular matrix R
              1           2           3
 1  -2.0569E+00 -9.0121E+00 -9.3705E+00
 2              -1.0882E+01 -7.2688E+00
 3                          -6.0405E+00

 Number of cycles of the Kogbetliantz method
     2

Source

    Program dggsvp3_example

!     DGGSVP3 Example Program Text

!     Copyright 2017, Numerical Algorithms Group Ltd. http://www.nag.com

!     .. Use Statements ..
      Use lapack_example_aux, Only: nagf_file_print_matrix_real_gen_comp
      Use lapack_interfaces, Only: dggsvp3, dlange, dtgsja
      Use lapack_precision, Only: dp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=dp) :: eps, tola, tolb
      Integer :: i, ifail, info, irank, j, k, l, lda, ldb, ldq, ldu, ldv, &
        lwork, m, n, ncycle, p
!     .. Local Arrays ..
      Real (Kind=dp), Allocatable :: a(:, :), alpha(:), b(:, :), beta(:), &
        q(:, :), tau(:), u(:, :), v(:, :), work(:)
      Real (Kind=dp) :: wdum(1)
      Integer, Allocatable :: iwork(:)
      Character (1) :: clabs(1), rlabs(1)
!     .. Intrinsic Procedures ..
      Intrinsic :: epsilon, max, nint, real
!     .. Executable Statements ..
      Write (nout, *) 'DGGSVP3 Example Program Results'
      Write (nout, *)
      Flush (nout)

!     Skip heading in data file
      Read (nin, *)
      Read (nin, *) m, n, p
      lda = m
      ldb = p
      ldq = n
      ldu = m
      ldv = p
      Allocate (a(lda,n), alpha(n), b(ldb,n), beta(n), q(ldq,n), tau(n), &
        u(ldu,m), v(ldv,p), iwork(n))

!     Perform workspace query to get optimal size of work
      lwork = -1
      Call dggsvp3('U', 'V', 'Q', m, p, n, a, lda, b, ldb, tola, tolb, k, l, &
        u, ldu, v, ldv, q, ldq, iwork, tau, wdum, lwork, info)
      lwork = nint(wdum(1))
      Allocate (work(lwork))

!     Read the m by n matrix A and p by n matrix B from data file

      Read (nin, *)(a(i,1:n), i=1, m)
      Read (nin, *)(b(i,1:n), i=1, p)

!     Compute tola and tolb as
!         tola = max(m,n)*norm(A)*macheps
!         tolb = max(p,n)*norm(B)*macheps

      eps = epsilon(1.0E0_dp)
      tola = real(max(m,n), kind=dp)*dlange('One-norm', m, n, a, lda, work)* &
        eps
      tolb = real(max(p,n), kind=dp)*dlange('One-norm', p, n, b, ldb, work)* &
        eps

!     Compute the factorization of (A, B)
!         (A = U*S*(Q**T), B = V*T*(Q**T))

      Call dggsvp3('U', 'V', 'Q', m, p, n, a, lda, b, ldb, tola, tolb, k, l, &
        u, ldu, v, ldv, q, ldq, iwork, tau, work, lwork, info)

!     Given the factors above find the generalized SVD of (A, B)

      Call dtgsja('U', 'V', 'Q', m, p, n, k, l, a, lda, b, ldb, tola, tolb, &
        alpha, beta, u, ldu, v, ldv, q, ldq, work, ncycle, info)

!     Print solution

      irank = k + l
      Write (nout, *) 'Number of infinite generalized singular values (k)'
      Write (nout, 100) k
      Write (nout, *) 'Number of finite generalized singular values (l)'
      Write (nout, 100) l
      Write (nout, *) 'Effective Numerical rank of (A; B) (k+l)'
      Write (nout, 100) irank
      Write (nout, *)
      Write (nout, *) 'Finite generalized singular values'
      Write (nout, 110)(alpha(j)/beta(j), j=k+1, irank)

      Write (nout, *)
      Flush (nout)

      Call nagf_file_print_matrix_real_gen_comp('General', ' ', m, m, u, ldu, &
        '1P,E12.4', 'Orthogonal matrix U', 'Integer', rlabs, 'Integer', clabs, &
        80, 0, ifail)

      Write (nout, *)
      Flush (nout)

      Call nagf_file_print_matrix_real_gen_comp('General', ' ', p, p, v, ldv, &
        '1P,E12.4', 'Orthogonal matrix V', 'Integer', rlabs, 'Integer', clabs, &
        80, 0, ifail)

      Write (nout, *)
      Flush (nout)

      Call nagf_file_print_matrix_real_gen_comp('General', ' ', n, n, q, ldq, &
        '1P,E12.4', 'Orthogonal matrix Q', 'Integer', rlabs, 'Integer', clabs, &
        80, 0, ifail)

      Write (nout, *)
      Flush (nout)

      Call nagf_file_print_matrix_real_gen_comp('Upper triangular', &
        'Non-unit', irank, irank, a(1,n-irank+1), lda, '1P,E12.4', &
        'Nonsingular upper triangular matrix R', 'Integer', rlabs, 'Integer', &
        clabs, 80, 0, ifail)

      Write (nout, *)
      Write (nout, *) 'Number of cycles of the Kogbetliantz method'
      Write (nout, 100) ncycle

100   Format (1X, I5)
110   Format (3X, 8(1P,E12.4))
    End Program
Full documentation of DGGSVP3


DGTCON example

Computational Routines: Estimates the reciprocal of the condition number of a real tridiagonal matrix using the LU factorization computed by DGTTRF

Data

DGTCON Example Program Data
   5                           :Value of N
        2.1  -1.0   1.9   8.0
  3.0   2.3  -5.0  -0.9   7.1
  3.4   3.6   7.0  -6.0        :End of matrix A

Result

 DGTCON Example Program Results

 Estimate of condition number =   9.27E+01

Source

    Program dgtcon_example

!     DGTCON Example Program Text

!     Copyright 2017, Numerical Algorithms Group Ltd. http://www.nag.com

!     .. Use Statements ..
      Use lapack_interfaces, Only: dgtcon, dgttrf, dlangt
      Use lapack_precision, Only: dp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=dp) :: anorm, rcond
      Integer :: info, n
!     .. Local Arrays ..
      Real (Kind=dp), Allocatable :: d(:), dl(:), du(:), du2(:), work(:)
      Integer, Allocatable :: ipiv(:), iwork(:)
!     .. Intrinsic Procedures ..
      Intrinsic :: epsilon
!     .. Executable Statements ..
      Write (nout, *) 'DGTCON Example Program Results'
      Write (nout, *)
!     Skip heading in data file
      Read (nin, *)
      Read (nin, *) n

      Allocate (d(n), dl(n-1), du(n-1), du2(n-2), work(2*n), ipiv(n), &
        iwork(n))

!     Read the tridiagonal matrix A from data file

      Read (nin, *) du(1:n-1)
      Read (nin, *) d(1:n)
      Read (nin, *) dl(1:n-1)

!     Compute the 1-norm of A
      anorm = dlangt('1-norm', n, dl, d, du)

!     Factorize the tridiagonal matrix A
      Call dgttrf(n, dl, d, du, du2, ipiv, info)

      If (info==0) Then

!       Estimate the condition number of A
        Call dgtcon('1-norm', n, dl, d, du, du2, ipiv, anorm, rcond, work, &
          iwork, info)

!       Print the estimated condition number

        If (rcond>=epsilon(1.0E0_dp)) Then
          Write (nout, 100) 'Estimate of condition number = ', 1.0_dp/rcond
        Else
          Write (nout, 100) 'A is singular to working precision. RCOND = ', &
            rcond
        End If

      Else
        Write (nout, 110) 'The (', info, ',', info, ')', &
          ' element of the factor U is zero'
      End If

100   Format (1X, A, 1P, E10.2)
110   Format (1X, A, I3, A, I3, A, A)
    End Program
Full documentation of DGTCON


DGTRFS example

Computational Routines: Refined solution with error bounds of real tridiagonal system of linear equations, multiple right-hand sides

Data

DGTRFS Example Program Data
  5     2                      :Values of N and NRHS
        2.1  -1.0   1.9   8.0
  3.0   2.3  -5.0  -0.9   7.1
  3.4   3.6   7.0  -6.0        :End of matrix A
  2.7   6.6
 -0.5  10.8
  2.6  -3.2
  0.6 -11.2
  2.7  19.1                    :End of matrix B

Result

 DGTRFS Example Program Results

 Solution(s)
             1          2
 1     -4.0000     5.0000
 2      7.0000    -4.0000
 3      3.0000    -3.0000
 4     -4.0000    -2.0000
 5     -3.0000     1.0000

 Backward errors (machine-dependent)
       7.2E-17    5.9E-17

 Estimated forward error bounds (machine-dependent)
       9.4E-15    1.4E-14

Source

    Program dgtrfs_example

!     DGTRFS Example Program Text

!     Copyright 2017, Numerical Algorithms Group Ltd. http://www.nag.com

!     .. Use Statements ..
      Use lapack_example_aux, Only: nagf_file_print_matrix_real_gen
      Use lapack_interfaces, Only: dgtrfs, dgttrf, dgttrs
      Use lapack_precision, Only: dp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter :: nin = 5, nout = 6
!     .. Local Scalars ..
      Integer :: i, ifail, info, ldb, ldx, n, nrhs
!     .. Local Arrays ..
      Real (Kind=dp), Allocatable :: b(:, :), berr(:), d(:), df(:), dl(:), &
        dlf(:), du(:), du2(:), duf(:), ferr(:), work(:), x(:, :)
      Integer, Allocatable :: ipiv(:), iwork(:)
!     .. Executable Statements ..
      Write (nout, *) 'DGTRFS Example Program Results'
      Write (nout, *)
      Flush (nout)
!     Skip heading in data file
      Read (nin, *)
      Read (nin, *) n, nrhs
      ldb = n
      ldx = n
      Allocate (b(ldb,nrhs), berr(nrhs), d(n), df(n), dl(n-1), dlf(n-1), &
        du(n-1), du2(n-2), duf(n-1), ferr(nrhs), work(3*n), x(ldx,nrhs), &
        ipiv(n), iwork(n))

!     Read the tridiagonal matrix A from data file

      Read (nin, *) du(1:n-1)
      Read (nin, *) d(1:n)
      Read (nin, *) dl(1:n-1)

!     Read the right hand matrix B

      Read (nin, *)(b(i,1:nrhs), i=1, n)

!     Copy A into DUF, DF and DLF, and copy B into X

      duf(1:n-1) = du(1:n-1)
      df(1:n) = d(1:n)
      dlf(1:n-1) = dl(1:n-1)
      x(1:n, 1:nrhs) = b(1:n, 1:nrhs)

!     Factorize the copy of the tridiagonal matrix A
      Call dgttrf(n, dlf, df, duf, du2, ipiv, info)

      If (info==0) Then

!       Solve the equations AX = B
        Call dgttrs('No transpose', n, nrhs, dlf, df, duf, du2, ipiv, x, ldx, &
          info)

!       Improve the solution and compute error estimates
        Call dgtrfs('No transpose', n, nrhs, dl, d, du, dlf, df, duf, du2, &
          ipiv, b, ldb, x, ldx, ferr, berr, work, iwork, info)

!       Print the solution and the forward and backward error
!       estimates

!       ifail: behaviour on error exit
!              =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
        ifail = 0
        Call nagf_file_print_matrix_real_gen('General', ' ', n, nrhs, x, ldx, &
          'Solution(s)', ifail)

        Write (nout, *)
        Write (nout, *) 'Backward errors (machine-dependent)'
        Write (nout, 100) berr(1:nrhs)
        Write (nout, *)
        Write (nout, *) 'Estimated forward error bounds (machine-dependent)'
        Write (nout, 100) ferr(1:nrhs)
      Else
        Write (nout, 110) 'The (', info, ',', info, ')', &
          ' element of the factor U is zero'
      End If

100   Format ((3X,1P,7E11.1))
110   Format (1X, A, I3, A, I3, A, A)
    End Program
Full documentation of DGTRFS


DGTTRF example

Computational Routines: LU factorization of real tridiagonal matrix

Data

DGTTRF Example Program Data
   5                           :Value of N
        2.1  -1.0   1.9   8.0
  3.0   2.3  -5.0  -0.9   7.1
  3.4   3.6   7.0  -6.0        :End of matrix A

Result

 DGTTRF Example Program Results

 Details of factorization

  Second superdiagonal of U
   -1.0000   1.9000   8.0000

  First superdiagonal of U
    2.3000  -5.0000  -0.9000   7.1000

  Main diagonal of U
    3.4000   3.6000   7.0000  -6.0000  -1.0154

  Multipliers
    0.8824   0.0196   0.1401  -0.0148

  Vector of interchanges
         2        3        4        5        5

Source

    Program dgttrf_example

!     DGTTRF Example Program Text

!     Copyright 2017, Numerical Algorithms Group Ltd. http://www.nag.com

!     .. Use Statements ..
      Use lapack_interfaces, Only: dgttrf
      Use lapack_precision, Only: dp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter :: nin = 5, nout = 6
!     .. Local Scalars ..
      Integer :: info, n
!     .. Local Arrays ..
      Real (Kind=dp), Allocatable :: d(:), dl(:), du(:), du2(:)
      Integer, Allocatable :: ipiv(:)
!     .. Executable Statements ..
      Write (nout, *) 'DGTTRF Example Program Results'
      Write (nout, *)
!     Skip heading in data file
      Read (nin, *)
      Read (nin, *) n

      Allocate (d(n), dl(n-1), du(n-1), du2(n-2), ipiv(n))

!     Read the tridiagonal matrix A from data file

      Read (nin, *) du(1:n-1)
      Read (nin, *) d(1:n)
      Read (nin, *) dl(1:n-1)

!     Factorize the tridiagonal matrix A
      Call dgttrf(n, dl, d, du, du2, ipiv, info)

      If (info>0) Then
        Write (nout, 100) 'The (', info, ',', info, ')', &
          ' element of the factor U is zero'
      End If

!     Print details of the factorization

      Write (nout, *) 'Details of factorization'
      Write (nout, *)
      Write (nout, *) ' Second superdiagonal of U'
      Write (nout, 110) du2(1:n-2)
      Write (nout, *)
      Write (nout, *) ' First superdiagonal of U'
      Write (nout, 110) du(1:n-1)
      Write (nout, *)
      Write (nout, *) ' Main diagonal of U'
      Write (nout, 110) d(1:n)
      Write (nout, *)
      Write (nout, *) ' Multipliers'
      Write (nout, 110) dl(1:n-1)
      Write (nout, *)
      Write (nout, *) ' Vector of interchanges'
      Write (nout, 120) ipiv(1:n)

100   Format (1X, A, I3, A, I3, A, A)
110   Format (1X, 8F9.4)
120   Format (1X, 5I9)
    End Program
Full documentation of DGTTRF


DGTTRS example

Computational Routines: Solves a real tridiagonal system of linear equations using the LU factorization computed by DGTTRF

Data

DGTTRS Example Program Data
  5     2                      :Values of N and NRHS
        2.1  -1.0   1.9   8.0
  3.0   2.3  -5.0  -0.9   7.1
  3.4   3.6   7.0  -6.0        :End of matrix A
  2.7   6.6
 -0.5  10.8
  2.6  -3.2
  0.6 -11.2
  2.7  19.1                    :End of matrix B

Result

 DGTTRS Example Program Results

 Solution(s)
             1          2
 1     -4.0000     5.0000
 2      7.0000    -4.0000
 3      3.0000    -3.0000
 4     -4.0000    -2.0000
 5     -3.0000     1.0000

Source

    Program dgttrs_example

!     DGTTRS Example Program Text

!     Copyright 2017, Numerical Algorithms Group Ltd. http://www.nag.com

!     .. Use Statements ..
      Use lapack_example_aux, Only: nagf_file_print_matrix_real_gen
      Use lapack_interfaces, Only: dgttrf, dgttrs
      Use lapack_precision, Only: dp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter :: nin = 5, nout = 6
!     .. Local Scalars ..
      Integer :: i, ifail, info, ldb, n, nrhs
!     .. Local Arrays ..
      Real (Kind=dp), Allocatable :: b(:, :), d(:), dl(:), du(:), du2(:)
      Integer, Allocatable :: ipiv(:)
!     .. Executable Statements ..
      Write (nout, *) 'DGTTRS Example Program Results'
      Write (nout, *)
      Flush (nout)
!     Skip heading in data file
      Read (nin, *)
      Read (nin, *) n, nrhs
      ldb = n
      Allocate (b(ldb,nrhs), d(n), dl(n-1), du(n-1), du2(n-2), ipiv(n))

!     Read the tridiagonal matrix A from data file

      Read (nin, *) du(1:n-1)
      Read (nin, *) d(1:n)
      Read (nin, *) dl(1:n-1)

!     Read the right hand matrix B
      Read (nin, *)(b(i,1:nrhs), i=1, n)

!     Factorize the tridiagonal matrix A
      Call dgttrf(n, dl, d, du, du2, ipiv, info)

      If (info==0) Then

!       Solve the equations AX = B
        Call dgttrs('No transpose', n, nrhs, dl, d, du, du2, ipiv, b, ldb, &
          info)

!       Print the solution

!       ifail: behaviour on error exit
!              =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
        ifail = 0
        Call nagf_file_print_matrix_real_gen('General', ' ', n, nrhs, b, ldb, &
          'Solution(s)', ifail)

      Else
        Write (nout, 100) 'The (', info, ',', info, ')', &
          ' element of the factor U is zero'
      End If

100   Format (1X, A, I3, A, I3, A, A)
    End Program
Full documentation of DGTTRS


DHGEQZ example

Computational Routines: Eigenvalues and generalized Schur factorization of real generalized upper Hessenberg matrix reduced from a pair of real general matrices

Data

DHGEQZ Example Program Data
   5                                                  :Value of N
1.00        1.00        1.00        1.00        1.00
2.00        4.00        8.00       16.00       32.00
3.00        9.00       27.00       81.00      243.00
4.00       16.00       64.00      256.00     1024.00
5.00       25.00      125.00      625.00     3125.00  :End of matrix A
1.00        2.00        3.00        4.00        5.00
1.00        4.00        9.00       16.00       25.00
1.00        8.00       27.00       64.00      125.00
1.00       16.00       81.00      256.00      625.00
1.00       32.00      243.00     1024.00     3125.00  :End of matrix B

Result

 DHGEQZ Example Program Results
 Matrix A after balancing
             1          2          3          4          5
 1      1.0000     1.0000     0.1000     0.1000     0.1000
 2      2.0000     4.0000     0.8000     1.6000     3.2000
 3      0.3000     0.9000     0.2700     0.8100     2.4300
 4      0.4000     1.6000     0.6400     2.5600    10.2400
 5      0.5000     2.5000     1.2500     6.2500    31.2500

 Matrix B after balancing
             1          2          3          4          5
 1      1.0000     2.0000     0.3000     0.4000     0.5000
 2      1.0000     4.0000     0.9000     1.6000     2.5000
 3      0.1000     0.8000     0.2700     0.6400     1.2500
 4      0.1000     1.6000     0.8100     2.5600     6.2500
 5      0.1000     3.2000     2.4300    10.2400    31.2500

 Matrix A in Hessenberg form
             1          2          3          4          5
 1     -2.1898    -0.3181     2.0547     4.7371    -4.6249
 2     -0.8395    -0.0426     1.7132     7.5194   -17.1850
 3      0.0000    -0.2846    -1.0101    -7.5927    26.4499
 4      0.0000     0.0000     0.0376     1.4070    -3.3643
 5      0.0000     0.0000     0.0000     0.3813    -0.9937

 Matrix B is triangular
             1          2          3          4          5
 1     -1.4248    -0.3476     2.1175     5.5813    -3.9269
 2      0.0000    -0.0782     0.1189     8.0940   -15.2928
 3      0.0000     0.0000     1.0021   -10.9356    26.5971
 4      0.0000     0.0000     0.0000     0.5820    -0.0730
 5      0.0000     0.0000     0.0000     0.0000     0.5321

 Minimal required LWORK =      5
 Actual value of  LWORK =     30

 Generalized eigenvalues
    1     ( -2.437,  0.000)
    2     (  0.607,  0.795)
    3     (  0.607, -0.795)
    4     (  1.000,  0.000)
    5     ( -0.410,  0.000)

Source

    Program dhgeqz_example

!     DHGEQZ Example Program Text

!     Copyright 2017, Numerical Algorithms Group Ltd. http://www.nag.com

!     .. Use Statements ..
      Use lapack_example_aux, Only: nagf_file_print_matrix_real_gen
      Use lapack_interfaces, Only: dgeqrf, dggbal, dgghd3, dhgeqz, dormqr
      Use lapack_precision, Only: dp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter :: nin = 5, nout = 6
!     .. Local Scalars ..
      Integer :: i, ifail, ihi, ilo, info, irows, jwork, lda, ldb, ldq, ldz, &
        lwork, n
      Character (1) :: compq, compz, job
!     .. Local Arrays ..
      Real (Kind=dp), Allocatable :: a(:, :), alphai(:), alphar(:), b(:, :), &
        beta(:), lscale(:), q(:, :), rscale(:), tau(:), work(:), z(:, :)
!     .. Intrinsic Procedures ..
      Intrinsic :: nint
!     .. Executable Statements ..
      Write (nout, *) 'DHGEQZ Example Program Results'
      Flush (nout)

!     Skip heading in data file

      Read (nin, *)
      Read (nin, *) n
      ldq = 1
      ldz = 1
      lda = n
      ldb = n
      lwork = 6*n
      Allocate (alphai(n), alphar(n), beta(n), a(lda,n), lscale(n), &
        q(ldq,ldq), rscale(n), b(ldb,n), tau(n), work(lwork), z(ldz,ldz))

!     READ matrix A from data file
      Read (nin, *)(a(i,1:n), i=1, n)

!     READ matrix B from data file
      Read (nin, *)(b(i,1:n), i=1, n)

!     Balance matrix pair (A,B)
      job = 'B'

      Call dggbal(job, n, a, lda, b, ldb, ilo, ihi, lscale, rscale, work, &
        info)

!     Matrix A after balancing

!     ifail: behaviour on error exit
!             =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
      ifail = 0
      Call nagf_file_print_matrix_real_gen('General', ' ', n, n, a, lda, &
        'Matrix A after balancing', ifail)

      Write (nout, *)
      Flush (nout)

!     Matrix B after balancing

      ifail = 0
      Call nagf_file_print_matrix_real_gen('General', ' ', n, n, b, ldb, &
        'Matrix B after balancing', ifail)

      Write (nout, *)
      Flush (nout)

!     Reduce B to triangular form using QR
      irows = ihi + 1 - ilo

      Call dgeqrf(irows, irows, b(ilo,ilo), ldb, tau, work, lwork, info)

!     Apply the orthogonal transformation to matrix A
      Call dormqr('L', 'T', irows, irows, irows, b(ilo,ilo), ldb, tau, &
        a(ilo,ilo), lda, work, lwork, info)

!     Compute the generalized Hessenberg form of (A,B) -> (H,T)
      compq = 'N'
      compz = 'N'

      Call dgghd3(compq, compz, irows, 1, irows, a(ilo,ilo), lda, b(ilo,ilo), &
        ldb, q, ldq, z, ldz, work, lwork, info)

!     Matrix A (H) in generalized Hessenberg form.

      ifail = 0
      Call nagf_file_print_matrix_real_gen('General', ' ', n, n, a, lda, &
        'Matrix A in Hessenberg form', ifail)

      Write (nout, *)
      Flush (nout)

!     Matrix B (T) in generalized Hessenberg form.

      ifail = 0
      Call nagf_file_print_matrix_real_gen('General', ' ', n, n, b, ldb, &
        'Matrix B is triangular', ifail)

!     Routine DHGEQZ
!     Workspace query: jwork = -1

      jwork = -1
      job = 'E'

      Call dhgeqz(job, compq, compz, n, ilo, ihi, a, lda, b, ldb, alphar, &
        alphai, beta, q, ldq, z, ldz, work, jwork, info)

      Write (nout, *)
      Write (nout, 100) nint(work(1))
      Write (nout, 110) lwork
      Write (nout, *)

!     Compute the generalized Schur form
!     if the workspace lwork is adequate

      If (nint(work(1))<=lwork) Then

        Call dhgeqz(job, compq, compz, n, ilo, ihi, a, lda, b, ldb, alphar, &
          alphai, beta, q, ldq, z, ldz, work, lwork, info)

!       Print the generalized eigenvalues

        Write (nout, 120)

        Do i = 1, n
          If (beta(i)/=0.0E0_dp) Then
            Write (nout, 130) i, '(', alphar(i)/beta(i), ',', &
              alphai(i)/beta(i), ')'
          Else
            Write (nout, 150) i
          End If
        End Do
      Else
        Write (nout, 140)
      End If

100   Format (1X, 'Minimal required LWORK = ', I6)
110   Format (1X, 'Actual value of  LWORK = ', I6)
120   Format (1X, 'Generalized eigenvalues')
130   Format (1X, I4, 5X, A, F7.3, A, F7.3, A)
140   Format (1X, 'Insufficient workspace allocated for call to DHGEQZ')
150   Format (1X, I4, 'Eigenvalue is infinite')
    End Program
Full documentation of DHGEQZ


DHSEQR example

Computational Routines: Eigenvalues and Schur factorization of real upper Hessenberg matrix reduced from real general matrix

Data

DHSEQR Example Program Data
  4                                   :Value of N
  0.3500  -0.1160  -0.3886  -0.2942
 -0.5140   0.1225   0.1004   0.1126
  0.0000   0.6443  -0.1357  -0.0977
  0.0000   0.0000   0.4262   0.1632   :End of matrix H

Result

 DHSEQR Example Program Results
 Matrix H
          1       2       3       4
 1   0.3500 -0.1160 -0.3886 -0.2942
 2  -0.5140  0.1225  0.1004  0.1126
 3   0.0000  0.6443 -0.1357 -0.0977
 4   0.0000  0.0000  0.4262  0.1632

 Eigenvalues
  (  0.7995,  0.0000)
  ( -0.0994,  0.4008)
  ( -0.0994, -0.4008)
  ( -0.1007,  0.0000)

Source

    Program dhseqr_example

!     DHSEQR Example Program Text

!     Copyright 2017, Numerical Algorithms Group Ltd. http://www.nag.com

!     .. Use Statements ..
      Use blas_interfaces, Only: dgemm
      Use lapack_example_aux, Only: nagf_file_print_matrix_real_gen
      Use lapack_interfaces, Only: dhseqr, dlange
      Use lapack_precision, Only: dp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=dp) :: alpha, beta, norm
      Integer :: i, ifail, info, ldc, ldd, ldh, ldz, lwork, n
!     .. Local Arrays ..
      Real (Kind=dp), Allocatable :: c(:, :), d(:, :), h(:, :), wi(:), &
        work(:), wr(:), z(:, :)
!     .. Intrinsic Procedures ..
      Intrinsic :: epsilon
!     .. Executable Statements ..
      Write (nout, *) 'DHSEQR Example Program Results'
      Flush (nout)

!     Skip heading in data file
      Read (nin, *)
      Read (nin, *) n
      ldc = n
      ldd = n
      ldh = n
      ldz = n
      lwork = n
      Allocate (c(ldc,n), d(ldd,n), h(ldh,n), wi(n), work(lwork), wr(n), &
        z(ldz,n))

!     Read H from data file
      Read (nin, *)(h(i,1:n), i=1, n)

!     Copy H into D
      d(1:n, 1:n) = h(1:n, 1:n)

!     Print Matrix H
!     ifail: behaviour on error exit
!            =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
      ifail = 0
      Call nagf_file_print_matrix_real_gen('General', ' ', n, n, h, ldh, &
        'Matrix H', ifail)

!     Calculate the eigenvalues and Schur factorization of H

      Call dhseqr('Schur form', 'Initialize Z', n, 1, n, h, ldh, wr, wi, z, &
        ldz, work, lwork, info)

      Write (nout, *)
      If (info>0) Then
        Write (nout, *) 'Failure to converge.'
      Else

!       Compute H - Z*T*Z^T from the factorization of A and store in matrix D
        alpha = 1.0_dp
        beta = 0.0_dp
        Call dgemm('N', 'N', n, n, n, alpha, z, ldz, h, ldh, beta, c, ldc)
        alpha = -1.0_dp
        beta = 1.0_dp
        Call dgemm('N', 'T', n, n, n, alpha, c, ldc, z, ldz, beta, d, ldd)

!       Find norm of matrix D and print warning if it is too large
        norm = dlange('O', ldd, n, d, ldd, work)
        If (norm>epsilon(1.0E0_dp)**0.8_dp) Then
          Write (nout, *) 'Norm of H-(Z*T*Z^T) is much greater than 0.'
          Write (nout, *) 'Schur factorization has failed.'
        Else
!         Print eigenvalues
          Write (nout, *) 'Eigenvalues'
          Write (nout, 100)(' (', wr(i), ',', wi(i), ')', i=1, n)
        End If
      End If

100   Format (1X, A, F8.4, A, F8.4, A)
    End Program
Full documentation of DHSEQR


DOPGTR example

Computational Routines: Generate orthogonal transformation matrix from reduction to tridiagonal form determined by DSPTRD

Data

DOPGTR Example Program Data
  4                           :Value of N
  'L'                         :Value of UPLO
  2.07
  3.87  -0.21
  4.20   1.87   1.15
 -1.15   0.63   2.06  -1.81   :End of matrix A

Result

 DOPGTR Example Program Results

 Eigenvalues
    -5.0034 -1.9987  0.2013  8.0008

 Eigenvectors
          1       2       3       4
 1   0.5658 -0.2328 -0.3965  0.6845
 2  -0.3478  0.7994 -0.1780  0.4564
 3  -0.4740 -0.4087  0.5381  0.5645
 4   0.5781  0.3737  0.7221  0.0676

Source

    Program dopgtr_example

!     DOPGTR Example Program Text

!     Copyright 2017, Numerical Algorithms Group Ltd. http://www.nag.com

!     .. Use Statements ..
      Use lapack_example_aux, Only: nagf_blas_damax_val, &
        nagf_file_print_matrix_real_gen
      Use lapack_interfaces, Only: dopgtr, dsptrd, dsteqr
      Use lapack_precision, Only: dp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Real (Kind=dp), Parameter :: zero = 0.0E0_dp
      Integer, Parameter :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=dp) :: r
      Integer :: i, ifail, info, j, k, ldq, n
      Character (1) :: uplo
!     .. Local Arrays ..
      Real (Kind=dp), Allocatable :: ap(:), d(:), e(:), q(:, :), tau(:), &
        work(:)
!     .. Executable Statements ..
      Write (nout, *) 'DOPGTR Example Program Results'
!     Skip heading in data file
      Read (nin, *)
      Read (nin, *) n
      ldq = n
      Allocate (ap(n*(n+1)/2), d(n), e(n), q(ldq,n), tau(n), work(2*n-2))

!     Read A from data file

      Read (nin, *) uplo
      If (uplo=='U') Then
        Read (nin, *)((ap(i+j*(j-1)/2),j=i,n), i=1, n)
      Else If (uplo=='L') Then
        Read (nin, *)((ap(i+(2*n-j)*(j-1)/2),j=1,i), i=1, n)
      End If

!     Reduce A to tridiagonal form T = (Q**T)*A*Q
      Call dsptrd(uplo, n, ap, d, e, tau, info)

!     Form Q explicitly, storing the result in Q
      Call dopgtr(uplo, n, ap, tau, q, ldq, work, info)

!     Calculate all the eigenvalues and eigenvectors of A
      Call dsteqr('V', n, d, e, q, ldq, work, info)

      Write (nout, *)
      If (info>0) Then
        Write (nout, *) 'Failure to converge.'
      Else

!       Print eigenvalues and eigenvectors

        Write (nout, *) 'Eigenvalues'
        Write (nout, 100) d(1:n)
        Write (nout, *)
        Flush (nout)

!       Normalize the eigenvectors: largest element positive
        Do i = 1, n
          Call nagf_blas_damax_val(n, q(1,i), 1, k, r)
          If (q(k,i)<zero) Then
            q(1:n, i) = -q(1:n, i)
          End If
        End Do

!       ifail: behaviour on error exit
!              =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
        ifail = 0
        Call nagf_file_print_matrix_real_gen('General', ' ', n, n, q, ldq, &
          'Eigenvectors', ifail)

      End If

100   Format (3X, (8F8.4))
    End Program
Full documentation of DOPGTR


DOPMTR example

Computational Routines: Apply orthogonal transformation determined by DSPTRD

Data

DOPMTR Example Program Data
  4                           :Value of N
  'L'                         :Value of UPLO
  2.07
  3.87  -0.21
  4.20   1.87   1.15
 -1.15   0.63   2.06  -1.81   :End of matrix A

Result

 DOPMTR Example Program Results

 Eigenvalues
    -5.0034 -1.9987

 Eigenvectors
          1       2
 1   0.5658 -0.2328
 2  -0.3478  0.7994
 3  -0.4740 -0.4087
 4   0.5781  0.3737

Source

    Program dopmtr_example

!     DOPMTR Example Program Text

!     Copyright 2017, Numerical Algorithms Group Ltd. http://www.nag.com

!     .. Use Statements ..
      Use lapack_example_aux, Only: nagf_blas_damax_val, &
        nagf_file_print_matrix_real_gen
      Use lapack_interfaces, Only: dopmtr, dsptrd, dstebz, dstein
      Use lapack_precision, Only: dp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Real (Kind=dp), Parameter :: zero = 0.0E0_dp
      Integer, Parameter :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=dp) :: r, vl, vu
      Integer :: i, ifail, info, j, k, ldc, m, n, nsplit
      Character (1) :: uplo
!     .. Local Arrays ..
      Real (Kind=dp), Allocatable :: ap(:), c(:, :), d(:), e(:), tau(:), w(:), &
        work(:)
      Integer, Allocatable :: iblock(:), ifailv(:), isplit(:), iwork(:)
!     .. Executable Statements ..
      Write (nout, *) 'DOPMTR Example Program Results'
!     Skip heading in data file
      Read (nin, *)
      Read (nin, *) n
      ldc = n
      Allocate (ap(n*(n+1)/2), c(ldc,n), d(n), e(n), tau(n), w(n), work(5*n), &
        iblock(n), ifailv(n), isplit(n), iwork(3*n))

!     Read A from data file

      Read (nin, *) uplo
      If (uplo=='U') Then
        Read (nin, *)((ap(i+j*(j-1)/2),j=i,n), i=1, n)
      Else If (uplo=='L') Then
        Read (nin, *)((ap(i+(2*n-j)*(j-1)/2),j=1,i), i=1, n)
      End If

!     Reduce A to tridiagonal form T = (Q**T)*A*Q
      Call dsptrd(uplo, n, ap, d, e, tau, info)

!     Calculate the two smallest eigenvalues of T (same as A)
      Call dstebz('I', 'B', n, vl, vu, 1, 2, zero, d, e, m, nsplit, w, iblock, &
        isplit, work, iwork, info)

      Write (nout, *)
      If (info>0) Then
        Write (nout, *) 'Failure to converge.'
      Else
        Write (nout, *) 'Eigenvalues'
        Write (nout, 100) w(1:m)

!       Calculate the eigenvectors of T, storing the result in C
        Call dstein(n, d, e, m, w, iblock, isplit, c, ldc, work, iwork, &
          ifailv, info)

        If (info>0) Then
          Write (nout, *) 'Failure to converge.'
        Else

!         Calculate the eigenvectors of A = Q * (eigenvectors of T)
          Call dopmtr('Left', uplo, 'No transpose', n, m, ap, tau, c, ldc, &
            work, info)

!         Print eigenvectors
          Write (nout, *)
          Flush (nout)

!         Normalize the eigenvectors
          Do i = 1, m
            Call nagf_blas_damax_val(n, c(1,i), 1, k, r)
            If (c(k,i)<zero) Then
              c(1:n, i) = -c(1:n, i)
            End If
          End Do

!         ifail: behaviour on error exit
!                =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
          ifail = 0
          Call nagf_file_print_matrix_real_gen('General', ' ', n, m, c, ldc, &
            'Eigenvectors', ifail)

        End If
      End If

100   Format (3X, (9F8.4))
    End Program
Full documentation of DOPMTR


DORCSD example

Computational Routines: Computes the CS decomposition of an orthogonal matrix partitioned into four real submatrices

Data

DORCSD Example Program Data
  5     3      2                         : m, p, q
 -0.7576  0.3697  0.3838  0.2126 -0.3112
 -0.4077 -0.1552 -0.1129  0.2676  0.8517
 -0.0488  0.7240 -0.6730 -0.1301  0.0602
 -0.2287  0.0088  0.2235 -0.9235  0.2120
  0.4530  0.5612  0.5806  0.1162  0.3595 : orthogonal matrix X

Result

 DORCSD Example Program Results

     Orthogonal matrix X
          1       2       3       4       5
 1  -0.7576  0.3697  0.3838  0.2126 -0.3112
 2  -0.4077 -0.1552 -0.1129  0.2676  0.8517
 3  -0.0488  0.7240 -0.6730 -0.1301  0.0602
 4  -0.2287  0.0088  0.2235 -0.9235  0.2120
 5   0.4530  0.5612  0.5806  0.1162  0.3595

 Components of CS factorization of X:

     Theta
          1
 1   0.1811
 2   0.8255

     U1
          1       2       3
 1   0.8249  0.3370 -0.4538
 2   0.2042  0.5710  0.7952
 3   0.5271 -0.7486  0.4022

     U2
          1       2
 1   0.9802  0.1982
 2   0.1982 -0.9802

     V1T
          1       2
 1  -0.7461  0.6658
 2  -0.6658 -0.7461

     V2T
          1       2       3
 1   0.3397 -0.8967  0.2837
 2  -0.7738 -0.4379 -0.4576
 3   0.5346 -0.0640 -0.8427

     Recombined matrix X = U * Sigma_p * V^T
          1       2       3       4       5
 1  -0.7576  0.3697  0.3838  0.2126 -0.3112
 2  -0.4077 -0.1551 -0.1129  0.2677  0.8517
 3  -0.0488  0.7240 -0.6730 -0.1300  0.0602
 4  -0.2287  0.0088  0.2235 -0.9234  0.2120
 5   0.4530  0.5612  0.5806  0.1162  0.3595

Source

    Program dorcsd_example

!     DORCSD Example Program Text

!     Copyright 2017, Numerical Algorithms Group Ltd. http://www.nag.com

!     .. Use Statements ..
      Use blas_interfaces, Only: dgemm
      Use lapack_example_aux, Only: nagf_file_print_matrix_real_gen
      Use lapack_interfaces, Only: dorcsd
      Use lapack_precision, Only: dp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Real (Kind=dp), Parameter :: one = 1.0_dp
      Real (Kind=dp), Parameter :: zero = 0.0_dp
      Integer, Parameter :: nin = 5, nout = 6, recombine = 1, reprint = 0
!     .. Local Scalars ..
      Integer :: i, ifail, info, info2, j, ldu, ldu1, ldu2, ldv, ldv1t, ldv2t, &
        ldx, ldx11, ldx12, ldx21, ldx22, lwork, m, n11, n12, n21, n22, p, q, r
!     .. Local Arrays ..
      Real (Kind=dp), Allocatable :: theta(:), u(:, :), u1(:, :), u2(:, :), &
        v(:, :), v1t(:, :), v2t(:, :), w(:, :), work(:), x(:, :), x11(:, :), &
        x12(:, :), x21(:, :), x22(:, :)
      Real (Kind=dp) :: wdum(1)
      Integer, Allocatable :: iwork(:)
!     .. Intrinsic Procedures ..
      Intrinsic :: cos, min, nint, sin
!     .. Executable Statements ..
      Write (nout, *) 'DORCSD Example Program Results'
      Write (nout, *)
      Flush (nout)
!     Skip heading in data file
      Read (nin, *)
      Read (nin, *) m, p, q

      r = min(min(p,q), min(m-p,m-q))

      ldx = m
      ldx11 = p
      ldx12 = p
      ldx21 = m - p
      ldx22 = m - p
      ldu = m
      ldu1 = p
      ldu2 = m - p
      ldv = m
      ldv1t = q
      ldv2t = m - q
      Allocate (x(ldx,m), u(ldu,m), v(ldv,m), theta(r), iwork(m), w(ldx,m))
      Allocate (x11(ldx11,q), x12(ldx12,m-q), x21(ldx21,q), x22(ldx22,m-q))
      Allocate (u1(ldu1,p), u2(ldu2,m-p), v1t(ldv1t,q), v2t(ldv2t,m-q))

!     Read and print orthogonal X from data file
!     (as, say, generated by a generalized singular value decomposition).

      Read (nin, *)(x(i,1:m), i=1, m)

!     Print general matrix using simple matrix printing routine nagf_file_print_matrix_real_gen.
!     ifail: behaviour on error exit
!            =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
      ifail = 0
      Call nagf_file_print_matrix_real_gen('G', 'N', m, m, x, ldx, &
        '    Orthogonal matrix X', ifail)
      Write (nout, *)

!     Compute the complete CS factorization of X:
!        X11 is stored in X(1:p,   1:q), X12 is stored in X(1:p,   q+1:m)
!        X21 is stored in X(p+1:m, 1:q), X22 is stored in X(p+1:m, q+1:m)
!        U1  is stored in U(1:p,   1:p), U2  is stored in U(p+1:m, p+1:m)
!        V1  is stored in V(1:q,   1:q), V2  is stored in V(q+1:m, q+1:m)
      x11(1:p, 1:q) = x(1:p, 1:q)
      x12(1:p, 1:m-q) = x(1:p, q+1:m)
      x21(1:m-p, 1:q) = x(p+1:m, 1:q)
      x22(1:m-p, 1:m-q) = x(p+1:m, q+1:m)

!     Workspace query first to get length of work array for complete CS
!     factorization routine dorcsd.
      lwork = -1
      Call dorcsd('Yes U1', 'Yes U2', 'Yes V1T', 'Yes V2T', 'Column', &
        'Default', m, p, q, x, ldx, x(1,q+1), ldx, x(p+1,1), ldx, x(p+1,q+1), &
        ldx, theta, u, ldu, u(p+1,p+1), ldu, v, ldv, v(q+1,q+1), ldv, wdum, &
        lwork, iwork, info)
      lwork = nint(wdum(1))
      Allocate (work(lwork))
!     Initialize all of  u, v to zero.
      u(1:m, 1:m) = zero
      v(1:m, 1:m) = zero

!     This is how you might pass partitions as sub-matrices
      Call dorcsd('Yes U1', 'Yes U2', 'Yes V1T', 'Yes V2T', 'Column', &
        'Default', m, p, q, x, ldx, x(1,q+1), ldx, x(p+1,1), ldx, x(p+1,q+1), &
        ldx, theta, u, ldu, u(p+1,p+1), ldu, v, ldv, v(q+1,q+1), ldv, work, &
        lwork, iwork, info)
      If (info/=0) Then
        Write (nout, 110) 'Failure in DORCSD. info =', info
        Go To 100
      End If
!     Print Theta, U1, U2, V1T, V2T using matrix printing routine nagf_file_print_matrix_real_gen.
      Write (nout, 120) 'Components of CS factorization of X:'
      Flush (nout)
      ifail = 0
      Call nagf_file_print_matrix_real_gen('G', 'N', r, 1, theta, r, &
        '    Theta', ifail)
      Write (nout, *)
      Flush (nout)
!     By changes of sign the first r elements of the first row of U1 can be
!     made positive.
      Do i = 1, r
        If (u(1,i)<0.0_dp) Then
          u(1:p, i) = -u(1:p, i)
          u(p+1:m, p+i) = -u(p+1:m, p+i)
          v(i, 1:q) = -v(i, 1:q)
          v(q+i, q+1:m) = -v(q+i, q+1:m)
        End If
      End Do
      ifail = 0
      Call nagf_file_print_matrix_real_gen('G', 'N', p, p, u, ldu, '    U1', &
        ifail)
      Write (nout, *)
      Flush (nout)
      ifail = 0
      Call nagf_file_print_matrix_real_gen('G', 'N', m-p, m-p, u(p+1,p+1), &
        ldu, '    U2', ifail)
      Write (nout, *)
      Flush (nout)
      ifail = 0
      Call nagf_file_print_matrix_real_gen('G', 'N', q, q, v, ldv, '    V1T', &
        ifail)
      Write (nout, *)
      Flush (nout)
      ifail = 0
      Call nagf_file_print_matrix_real_gen('G', 'N', m-q, m-q, v(q+1,q+1), &
        ldv, '    V2T', ifail)
      Write (nout, *)

!     And this is how you might pass partitions as separate matrices.
      Call dorcsd('Yes U1', 'Yes U2', 'Yes V1T', 'Yes V2T', 'Column', &
        'Default', m, p, q, x11, ldx11, x12, ldx12, x21, ldx21, x22, ldx22, &
        theta, u1, ldu1, u2, ldu2, v1t, ldv1t, v2t, ldv2t, work, lwork, iwork, &
        info2)
      If (info2/=0) Then
        Write (nout, 110) 'Failure in DORCSD. info =', info
        Go To 100
      End If

!     Print Theta, U1, U2, V1T, V2T using matrix printing routine nagf_file_print_matrix_real_gen.
      If (reprint/=0) Then
!       By changes of sign the first r elements of the first row of U1 can be
!       made positive.
        Do i = 1, r
          If (u1(1,i)<0.0_dp) Then
            u1(1:p, i) = -u1(1:p, i)
            u2(1:m-p, i) = -u2(1:m-p, i)
            v1t(i, 1:q) = -v1t(i, 1:q)
            v2t(i, 1:m-q) = -v2t(i, 1:m-q)
          End If
        End Do
        Write (nout, 120) 'Components of CS factorization of X:'
        Flush (nout)
        ifail = 0
        Call nagf_file_print_matrix_real_gen('G', 'N', r, 1, theta, r, &
          '    Theta', ifail)
        Write (nout, *)
        Flush (nout)
        ifail = 0
        Call nagf_file_print_matrix_real_gen('G', 'N', p, p, u1, ldu1, &
          '    U1', ifail)
        Write (nout, *)
        Flush (nout)
        ifail = 0
        Call nagf_file_print_matrix_real_gen('G', 'N', m-p, m-p, u2, ldu2, &
          '    U2', ifail)
        Write (nout, *)
        Flush (nout)
        ifail = 0
        Call nagf_file_print_matrix_real_gen('G', 'N', q, q, v1t, ldv1t, &
          '    V1T', ifail)
        Write (nout, *)
        Flush (nout)
        ifail = 0
        Call nagf_file_print_matrix_real_gen('G', 'N', m-q, m-q, v2t, ldv2t, &
          '    V2T', ifail)
        Write (nout, *)
        Flush (nout)
      End If
      If (recombine/=0) Then
!       Recombining should return the original matrix
!       Assemble Sigma_p into X
        x(1:m, 1:m) = zero
        n11 = min(p, q) - r
        n12 = min(p, m-q) - r
        n21 = min(m-p, q) - r
        n22 = min(m-p, m-1) - r
!       Top Half
        Do j = 1, n11
          x(j, j) = one
        End Do
        Do j = 1, r
          x(j+n11, j+n11) = cos(theta(j))
          x(j+n11, j+n11+r+n21+n22) = -sin(theta(j))
        End Do
        Do j = 1, n12
          x(j+n11+r, j+n11+r+n21+n22+r) = -one
        End Do
!       Bottom half
        Do j = 1, n22
          x(p+j, q+j) = one
        End Do
        Do j = 1, r
          x(p+n22+j, j+n11) = sin(theta(j))
          x(p+n22+j, j+r+n21+n22) = cos(theta(j))
        End Do
        Do j = 1, n21
          x(p+n22+r+j, n11+r+j) = one
        End Do
!       multiply U * Sigma_p into w
        Call dgemm('n', 'n', m, m, m, one, u, ldu, x, ldx, zero, w, ldx)
!       form U * Sigma_p * V^T into u
        Call dgemm('n', 'n', m, m, m, one, w, ldx, v, ldv, zero, u, ldu)

        Flush (nout)
        ifail = 0
        Call nagf_file_print_matrix_real_gen('G', 'N', m, m, u, ldu, &
          '    Recombined matrix X = U * Sigma_p * V^T', ifail)
      End If

100   Continue

110   Format (1X, A, I4)
120   Format (1X, A, /)
    End Program
Full documentation of DORCSD


DORGBR example

Computational Routines: Generate orthogonal transformation matrices from reduction to bidiagonal form determined by DGEBRD

Data

DORGBR Example Program Data
  6  4                                      :Values of M and N, Example 1
 -0.57  -1.28  -0.39   0.25
 -1.93   1.08  -0.31  -2.14
  2.30   0.24   0.40  -0.35
 -1.93   0.64  -0.66   0.08
  0.15   0.30   0.15  -2.13
 -0.02   1.03  -1.43   0.50                 :End of matrix A
  4  6                                      :Values of M and N, Example 2
 -5.42   3.28  -3.68   0.27   2.06   0.46
 -1.65  -3.40  -3.20  -1.03  -4.06  -0.01
 -0.37   2.35   1.90   4.31  -1.76   1.13
 -3.15  -0.11   1.99  -2.70   0.26   4.50   :End of matrix A

Result

 DORGBR Example Program Results

 Example 1: singular values
     3.9987  3.0005  1.9967  0.9999

 Example 1: right singular vectors, by row
          1       2       3       4
 1   0.8251 -0.2794  0.2048  0.4463
 2  -0.4530 -0.2121 -0.2622  0.8252
 3  -0.2829 -0.7961  0.4952 -0.2026
 4   0.1841 -0.4931 -0.8026 -0.2807

 Example 1: left singular vectors, by column
          1       2       3       4
 1  -0.0203  0.2794  0.4690  0.7692
 2  -0.7284 -0.3464 -0.0169 -0.0383
 3   0.4393 -0.4955 -0.2868  0.0822
 4  -0.4678  0.3258 -0.1536 -0.1636
 5  -0.2200 -0.6428  0.1125  0.3572
 6  -0.0935  0.1927 -0.8132  0.4957

 Example 2: singular values
     7.9987  7.0059  5.9952  4.9989

 Example 2: right singular vectors, by row
          1       2       3       4       5       6
 1  -0.7933  0.3163 -0.3342 -0.1514  0.2142  0.3001
 2   0.1002  0.6442  0.4371  0.4890  0.3771  0.0501
 3   0.0111  0.1724 -0.6367  0.4354 -0.0430 -0.6111
 4   0.2361  0.0216 -0.1025 -0.5286  0.7460 -0.3120

 Example 2: left singular vectors, by column
          1       2       3       4
 1   0.8884  0.1275  0.4331  0.0838
 2   0.0733 -0.8264  0.1943 -0.5234
 3  -0.0361  0.5435  0.0756 -0.8352
 4   0.4518 -0.0733 -0.8769 -0.1466

Source

    Program dorgbr_example

!     DORGBR Example Program Text

!     Copyright 2017, Numerical Algorithms Group Ltd. http://www.nag.com

!     .. Use Statements ..
      Use lapack_example_aux, Only: nagf_file_print_matrix_real_gen
      Use lapack_interfaces, Only: dbdsqr, dgebrd, dlacpy, dorgbr
      Use lapack_precision, Only: dp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter :: nin = 5, nout = 6
!     .. Local Scalars ..
      Integer :: i, ic, ifail, info, lda, ldc, ldu, ldvt, lwork, m, n
!     .. Local Arrays ..
      Real (Kind=dp), Allocatable :: a(:, :), c(:, :), d(:), e(:), taup(:), &
        tauq(:), u(:, :), vt(:, :), work(:)
!     .. Executable Statements ..
      Write (nout, *) 'DORGBR Example Program Results'
!     Skip heading in data file
      Read (nin, *)
      Do ic = 1, 2
        Read (nin, *) m, n
        lda = m
        ldc = n
        ldu = m
        ldvt = n
        lwork = 64*(m+n)
        Allocate (a(lda,n), c(ldc,n), d(n), e(n-1), taup(n), tauq(n), &
          u(ldu,n), vt(ldvt,n), work(lwork))

!       Read A from data file

        Read (nin, *)(a(i,1:n), i=1, m)

!       Reduce A to bidiagonal form
        Call dgebrd(m, n, a, lda, d, e, tauq, taup, work, lwork, info)

        If (m>=n) Then

!         Copy A to VT and U

          Call dlacpy('Upper', n, n, a, lda, vt, ldvt)
          Call dlacpy('Lower', m, n, a, lda, u, ldu)

!         Form P**T explicitly, storing the result in VT
          Call dorgbr('P', n, n, m, vt, ldvt, taup, work, lwork, info)

!         Form Q explicitly, storing the result in U
          Call dorgbr('Q', m, n, n, u, ldu, tauq, work, lwork, info)

!         Compute the SVD of A
          Call dbdsqr('Upper', n, n, m, 0, d, e, vt, ldvt, u, ldu, c, ldc, &
            work, info)

!         Print singular values, left & right singular vectors

          Write (nout, *)
          Write (nout, *) 'Example 1: singular values'
          Write (nout, 100) d(1:n)
          Write (nout, *)
          Flush (nout)

!         ifail: behaviour on error exit
!                =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
          ifail = 0
          Call nagf_file_print_matrix_real_gen('General', ' ', n, n, vt, ldvt, &
            'Example 1: right singular vectors, by row', ifail)

          Write (nout, *)
          Flush (nout)

          Call nagf_file_print_matrix_real_gen('General', ' ', m, n, u, ldu, &
            'Example 1: left singular vectors, by column', ifail)

        Else

!         Copy A to VT and U

          Call dlacpy('Upper', m, n, a, lda, vt, ldvt)
          Call dlacpy('Lower', m, m, a, lda, u, ldu)

!         Form P**T explicitly, storing the result in VT
          Call dorgbr('P', m, n, m, vt, ldvt, taup, work, lwork, info)

!         Form Q explicitly, storing the result in U
          Call dorgbr('Q', m, m, n, u, ldu, tauq, work, lwork, info)

!         Compute the SVD of A
          Call dbdsqr('Lower', m, n, m, 0, d, e, vt, ldvt, u, ldu, c, ldc, &
            work, info)

!         Print singular values, left & right singular vectors

          Write (nout, *)
          Write (nout, *) 'Example 2: singular values'
          Write (nout, 100) d(1:m)
          Write (nout, *)
          Flush (nout)

          ifail = 0
          Call nagf_file_print_matrix_real_gen('General', ' ', m, n, vt, ldvt, &
            'Example 2: right singular vectors, by row', ifail)

          Write (nout, *)
          Flush (nout)

          Call nagf_file_print_matrix_real_gen('General', ' ', m, m, u, ldu, &
            'Example 2: left singular vectors, by column', ifail)

        End If
        Deallocate (a, c, d, e, taup, tauq, u, vt, work)
      End Do

100   Format (3X, (8F8.4))
    End Program
Full documentation of DORGBR


DORGHR example

Computational Routines: Generate orthogonal transformation matrix from reduction to Hessenberg form determined by DGEHRD

Data

DORGHR Example Program Data
  4                           :Value of N
  0.35   0.45  -0.14  -0.17
  0.09   0.07  -0.54   0.35
 -0.44  -0.33  -0.03   0.17
  0.25  -0.32  -0.13   0.11   :End of matrix A

Result

 DORGHR Example Program Results

 Matrix A
          1       2       3       4
 1   0.3500  0.4500 -0.1400 -0.1700
 2   0.0900  0.0700 -0.5400  0.3500
 3  -0.4400 -0.3300 -0.0300  0.1700
 4   0.2500 -0.3200 -0.1300  0.1100

 Eigenvalues
  (  0.7995,  0.0000)
  ( -0.0994,  0.4008)
  ( -0.0994, -0.4008)
  ( -0.1007,  0.0000)

Source

    Program dorghr_example

!     DORGHR Example Program Text

!     Copyright 2017, Numerical Algorithms Group Ltd. http://www.nag.com

!     .. Use Statements ..
      Use blas_interfaces, Only: dgemm
      Use lapack_example_aux, Only: nagf_file_print_matrix_real_gen
      Use lapack_interfaces, Only: dgehrd, dhseqr, dlange, dorghr
      Use lapack_precision, Only: dp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=dp) :: alpha, beta, norm
      Integer :: i, ifail, info, lda, ldc, ldd, ldz, lwork, n
!     .. Local Arrays ..
      Real (Kind=dp), Allocatable :: a(:, :), c(:, :), d(:, :), tau(:), wi(:), &
        work(:), wr(:), z(:, :)
!     .. Intrinsic Procedures ..
      Intrinsic :: epsilon
!     .. Executable Statements ..
      Write (nout, *) 'DORGHR Example Program Results'
!     Skip heading in data file
      Read (nin, *)
      Read (nin, *) n
      lda = n
      ldz = n
      ldc = n
      ldd = n
      lwork = 64*(n-1)
      Allocate (a(lda,n), c(ldc,n), d(ldd,n), tau(n), wi(n), work(lwork), &
        wr(n), z(ldz,n))

!     Read A from data file
      Read (nin, *)(a(i,1:n), i=1, n)

!     Copy A into D.
      d(1:n, 1:n) = a(1:n, 1:n)

      Write (nout, *)
      Flush (nout)

!     Print Matrix A
!     ifail: behaviour on error exit
!             =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
      ifail = 0
      Call nagf_file_print_matrix_real_gen('General', ' ', n, n, a, lda, &
        'Matrix A', ifail)

      Write (nout, *)
      Flush (nout)

!     Reduce A to upper Hessenberg form H = (Q**T)*A*Q
      Call dgehrd(n, 1, n, a, lda, tau, work, lwork, info)

!     Copy A into Z
      z(1:n, 1:n) = a(1:n, 1:n)

!     Form Q explicitly, storing the result in Z
      Call dorghr(n, 1, n, z, ldz, tau, work, lwork, info)

!     Calculate the Schur factorization of H = Y*T*(Y**T) and form
!     Q*Y explicitly, storing the result in Z

!     Note that A = Z*T*(Z**T), where Z = Q*Y
      Call dhseqr('Schur form', 'Vectors', n, 1, n, a, lda, wr, wi, z, ldz, &
        work, lwork, info)

!     Compute A - Z*T*Z^T from the factorization of A and store in matrix D.
      alpha = 1.0_dp
      beta = 0.0_dp
      Call dgemm('N', 'N', n, n, n, alpha, z, ldz, a, lda, beta, c, ldc)
      alpha = -1.0_dp
      beta = 1.0_dp
      Call dgemm('N', 'T', n, n, n, alpha, c, ldc, z, ldz, beta, d, ldd)

!     Find norm of difference matrix D and warn if it is too large;
      norm = dlange('O', ldd, n, d, ldd, work)
      If (norm>epsilon(1.0E0_dp)**0.8_dp) Then
        Write (nout, *) 'Norm of A-(Z*T*Z^T) is much greater than 0.'
        Write (nout, *) 'Schur factorization has failed.'
      Else
!       Print eigenvalues.
        Write (nout, *) 'Eigenvalues'
        Write (nout, 100)(' (', wr(i), ',', wi(i), ')', i=1, n)
      End If

100   Format (1X, A, F8.4, A, F8.4, A)

    End Program
Full documentation of DORGHR


DORGLQ example

Computational Routines: Form all or part of orthogonal Q from LQ factorization determined by DGELQF

Data

DORGLQ Example Program Data
  4  6                                      :Values of M and N
 -5.42   3.28  -3.68   0.27   2.06   0.46
 -1.65  -3.40  -3.20  -1.03  -4.06  -0.01
 -0.37   2.35   1.90   4.31  -1.76   1.13
 -3.15  -0.11   1.99  -2.70   0.26   4.50   :End of matrix A

Result

 DORGLQ Example Program Results

 The leading  4 rows of Q
          1       2       3       4       5       6
 1  -0.7104  0.4299 -0.4824  0.0354  0.2700  0.0603
 2  -0.2412 -0.5323 -0.4845 -0.1595 -0.6311 -0.0027
 3   0.1287 -0.2619 -0.2108 -0.7447  0.5227 -0.2063
 4  -0.3403 -0.0921  0.4546 -0.3869 -0.0465  0.7191

Source

    Program dorglq_example

!     DORGLQ Example Program Text

!     Copyright 2017, Numerical Algorithms Group Ltd. http://www.nag.com

!     .. Use Statements ..
      Use lapack_example_aux, Only: nagf_file_print_matrix_real_gen
      Use lapack_interfaces, Only: dgelqf, dorglq
      Use lapack_precision, Only: dp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter :: nin = 5, nout = 6
!     .. Local Scalars ..
      Integer :: i, ifail, info, lda, lwork, m, n
      Character (30) :: title
!     .. Local Arrays ..
      Real (Kind=dp), Allocatable :: a(:, :), tau(:), work(:)
!     .. Executable Statements ..
      Write (nout, *) 'DORGLQ Example Program Results'
!     Skip heading in data file
      Read (nin, *)
      Read (nin, *) m, n
      lda = m
      lwork = 64*m
      Allocate (a(lda,n), tau(n), work(lwork))

!     Read A from data file

      Read (nin, *)(a(i,1:n), i=1, m)

!     Compute the LQ factorization of A
      Call dgelqf(m, n, a, lda, tau, work, lwork, info)

!     Form the leading M rows of Q explicitly
      Call dorglq(m, n, m, a, lda, tau, work, lwork, info)

!     Print the leading M rows of Q only

      Write (nout, *)
      Write (title, 100) m
      Flush (nout)

!     ifail: behaviour on error exit
!             =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
      ifail = 0
      Call nagf_file_print_matrix_real_gen('General', ' ', m, n, a, lda, &
        title, ifail)

100   Format ('The leading ', I2, ' rows of Q')
    End Program
Full documentation of DORGLQ


DORGQL example

Computational Routines: Form all or part of orthogonal Q from QL factorization determined by DGEQLF

Data

DORGQL Example Program Data

  6      4                   :Values of M and N

 -0.57  -1.28  -0.39   0.25
 -1.93   1.08  -0.31  -2.14
  2.30   0.24   0.40  -0.35
 -1.93   0.64  -0.66   0.08
  0.15   0.30   0.15  -2.13
 -0.02   1.03  -1.43   0.50 :End of matrix A

Result

 DORGQL Example Program Results

 The leading    4 columns of Q
          1       2       3       4
 1  -0.0833  0.9100 -0.2202 -0.0809
 2   0.2972 -0.1080 -0.2706  0.6922
 3  -0.6404 -0.2351  0.2220  0.1132
 4   0.4461 -0.1620 -0.3866 -0.0259
 5  -0.2938  0.2022  0.0015  0.6890
 6  -0.4575 -0.1946 -0.8243 -0.1617

Source

    Program dorgql_example

!     DORGQL Example Program Text

!     Copyright 2017, Numerical Algorithms Group Ltd. http://www.nag.com

!     .. Use Statements ..
      Use lapack_example_aux, Only: nagf_file_print_matrix_real_gen
      Use lapack_interfaces, Only: dgeqlf, dorgql
      Use lapack_precision, Only: dp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter :: nb = 64, nin = 5, nout = 6
!     .. Local Scalars ..
      Integer :: i, ifail, info, lda, lwork, m, n
      Character (30) :: title
!     .. Local Arrays ..
      Real (Kind=dp), Allocatable :: a(:, :), tau(:), work(:)
!     .. Executable Statements ..
      Write (nout, *) 'DORGQL Example Program Results'
      Write (nout, *)
!     Skip heading in data file
      Read (nin, *)
      Read (nin, *) m, n
      lda = m
      lwork = nb*n
      Allocate (a(lda,n), tau(n), work(lwork))

!     Read A from data file

      Read (nin, *)(a(i,1:n), i=1, m)

!     Compute the QL factorization of A

      Call dgeqlf(m, n, a, lda, tau, work, lwork, info)

!     Form the leading N columns of Q explicitly

      Call dorgql(m, n, n, a, lda, tau, work, lwork, info)

!     Form the heading for NAGF_FILE_PRINT_MATRIX_REAL_GEN

      Write (title, 100) n
      Flush (nout)

!     Print the leading N columns of Q

!     ifail: behaviour on error exit
!             =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
      ifail = 0
      Call nagf_file_print_matrix_real_gen('General', ' ', m, n, a, lda, &
        title, ifail)

100   Format ('The leading ', I4, ' columns of Q')
    End Program
Full documentation of DORGQL


DORGQR example

Computational Routines: Form all or part of orthogonal Q from QR factorization determined by DGEQRF or DGEQPF

Data

DORGQR Example Program Data
  6  4                        :Values of M and N
 -0.57  -1.28  -0.39   0.25
 -1.93   1.08  -0.31  -2.14
  2.30   0.24   0.40  -0.35
 -1.93   0.64  -0.66   0.08
  0.15   0.30   0.15  -2.13
 -0.02   1.03  -1.43   0.50   :End of matrix A

Result

 DORGQR Example Program Results

 The leading  4 columns of Q
          1       2       3       4
 1  -0.1576  0.6744 -0.4571  0.4489
 2  -0.5335 -0.3861  0.2583  0.3898
 3   0.6358 -0.2928  0.0165  0.1930
 4  -0.5335 -0.1692 -0.0834 -0.2350
 5   0.0415 -0.1593  0.1475  0.7436
 6  -0.0055 -0.5064 -0.8339  0.0335

Source

    Program dorgqr_example

!     DORGQR Example Program Text

!     Copyright 2017, Numerical Algorithms Group Ltd. http://www.nag.com

!     .. Use Statements ..
      Use lapack_example_aux, Only: nagf_file_print_matrix_real_gen
      Use lapack_interfaces, Only: dgeqrf, dorgqr
      Use lapack_precision, Only: dp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter :: nin = 5, nout = 6
!     .. Local Scalars ..
      Integer :: i, ifail, info, lda, lwork, m, n
      Character (30) :: title
!     .. Local Arrays ..
      Real (Kind=dp), Allocatable :: a(:, :), tau(:), work(:)
!     .. Executable Statements ..
      Write (nout, *) 'DORGQR Example Program Results'
!     Skip heading in data file
      Read (nin, *)
      Read (nin, *) m, n
      lda = m
      lwork = 64*n
      Allocate (a(lda,n), tau(n), work(lwork))

!     Read A from data file

      Read (nin, *)(a(i,1:n), i=1, m)

!     Compute the QR factorization of A
      Call dgeqrf(m, n, a, lda, tau, work, lwork, info)

!     Form the leading N columns of Q explicitly
      Call dorgqr(m, n, n, a, lda, tau, work, lwork, info)

!     Print the leading N columns of Q only

      Write (nout, *)
      Write (title, 100) n
      Flush (nout)

!     ifail: behaviour on error exit
!             =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
      ifail = 0
      Call nagf_file_print_matrix_real_gen('General', ' ', m, n, a, lda, &
        title, ifail)

100   Format ('The leading ', I2, ' columns of Q')
    End Program
Full documentation of DORGQR


DORGRQ example

Computational Routines: Form all or part of orthogonal Q from RQ factorization determined by DGERQF

Data

DORGRQ Example Program Data

  4      6                                :Values of M and N

 -0.57  -1.93   2.30  -1.93   0.15  -0.02
 -1.28   1.08   0.24   0.64   0.30   1.03
 -0.39  -0.31   0.40  -0.66   0.15  -1.43
  0.25  -2.14  -0.35   0.08  -2.13   0.50 :End of matrix A

Result

 DORGRQ Example Program Results

 The leading    4 rows of Q
          1       2       3       4       5       6
 1  -0.0833  0.2972 -0.6404  0.4461 -0.2938 -0.4575
 2   0.9100 -0.1080 -0.2351 -0.1620  0.2022 -0.1946
 3  -0.2202 -0.2706  0.2220 -0.3866  0.0015 -0.8243
 4  -0.0809  0.6922  0.1132 -0.0259  0.6890 -0.1617

Source

    Program dorgrq_example

!     DORGRQ Example Program Text

!     Copyright 2017, Numerical Algorithms Group Ltd. http://www.nag.com

!     .. Use Statements ..
      Use lapack_example_aux, Only: nagf_file_print_matrix_real_gen
      Use lapack_interfaces, Only: dgerqf, dorgrq
      Use lapack_precision, Only: dp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter :: nb = 64, nin = 5, nout = 6
!     .. Local Scalars ..
      Integer :: i, ifail, info, lda, lwork, m, n
      Character (26) :: title
!     .. Local Arrays ..
      Real (Kind=dp), Allocatable :: a(:, :), tau(:), work(:)
!     .. Executable Statements ..
      Write (nout, *) 'DORGRQ Example Program Results'
      Write (nout, *)
!     Skip heading in data file
      Read (nin, *)
      Read (nin, *) m, n
      lda = m
      lwork = nb*m
      Allocate (a(lda,n), tau(n), work(lwork))

!     Read A from data file

      Read (nin, *)(a(i,1:n), i=1, m)

!     Compute the RQ factorization of A
      Call dgerqf(m, n, a, lda, tau, work, lwork, info)

!     Form the leading M rows of Q explicitly
      Call dorgrq(m, n, m, a, lda, tau, work, lwork, info)

!     Form the heading for NAGF_FILE_PRINT_MATRIX_REAL_GEN

      Write (title, 100) m
      Flush (nout)

!     Print the leading M rows of Q

!     ifail: behaviour on error exit
!             =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
      ifail = 0
      Call nagf_file_print_matrix_real_gen('General', ' ', m, n, a, lda, &
        title, ifail)

100   Format ('The leading ', I4, ' rows of Q')
    End Program
Full documentation of DORGRQ


DORGTR example

Computational Routines: Generate orthogonal transformation matrix from reduction to tridiagonal form determined by DSYTRD

Data

DORGTR Example Program Data
  4                           :Value of N
  'L'                         :Value of UPLO
  2.07
  3.87  -0.21
  4.20   1.87   1.15
 -1.15   0.63   2.06  -1.81   :End of matrix A

Result

 DORGTR Example Program Results

 Eigenvalues
    -5.0034 -1.9987  0.2013  8.0008

 Eigenvectors
          1       2       3       4
 1   0.5658 -0.2328 -0.3965  0.6845
 2  -0.3478  0.7994 -0.1780  0.4564
 3  -0.4740 -0.4087  0.5381  0.5645
 4   0.5781  0.3737  0.7221  0.0676

Source

    Program dorgtr_example

!     DORGTR Example Program Text

!     Copyright 2017, Numerical Algorithms Group Ltd. http://www.nag.com

!     .. Use Statements ..
      Use lapack_example_aux, Only: nagf_blas_damax_val, &
        nagf_file_print_matrix_real_gen
      Use lapack_interfaces, Only: dlacpy, dorgtr, dsteqr, dsytrd
      Use lapack_precision, Only: dp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Real (Kind=dp), Parameter :: zero = 0.0_dp
      Integer, Parameter :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=dp) :: r
      Integer :: i, ifail, info, k, lda, ldz, lwork, n
      Character (1) :: uplo
!     .. Local Arrays ..
      Real (Kind=dp), Allocatable :: a(:, :), d(:), e(:), tau(:), work(:), &
        z(:, :)
!     .. Executable Statements ..
      Write (nout, *) 'DORGTR Example Program Results'
!     Skip heading in data file
      Read (nin, *)
      Read (nin, *) n
      lda = n
      ldz = n
      lwork = 64*n
      Allocate (a(lda,n), d(n), e(n), tau(n), work(lwork), z(ldz,n))

!     Read A from data file

      Read (nin, *) uplo
      If (uplo=='U') Then
        Read (nin, *)(a(i,i:n), i=1, n)
      Else If (uplo=='L') Then
        Read (nin, *)(a(i,1:i), i=1, n)
      End If

!     Reduce A to tridiagonal form T = (Q**T)*A*Q
      Call dsytrd(uplo, n, a, lda, d, e, tau, work, lwork, info)

!     Copy A into Z
      Call dlacpy(uplo, n, n, a, lda, z, ldz)

!     Form Q explicitly, storing the result in Z
      Call dorgtr(uplo, n, z, ldz, tau, work, lwork, info)

!     Calculate all the eigenvalues and eigenvectors of A
      Call dsteqr('V', n, d, e, z, ldz, work, info)

      Write (nout, *)
      If (info>0) Then
        Write (nout, *) 'Failure to converge.'
      Else

!       Print eigenvalues and eigenvectors

        Write (nout, *) 'Eigenvalues'
        Write (nout, 100) d(1:n)
        Write (nout, *)
        Flush (nout)

!       Normalize the eigenvectors: largest element positive
        Do i = 1, n
          Call nagf_blas_damax_val(n, z(1,i), 1, k, r)
          If (z(k,i)<zero) Then
            z(1:n, i) = -z(1:n, i)
          End If
        End Do

!       ifail: behaviour on error exit
!              =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
        ifail = 0
        Call nagf_file_print_matrix_real_gen('General', ' ', n, n, z, ldz, &
          'Eigenvectors', ifail)

      End If

100   Format (3X, (8F8.4))
    End Program
Full documentation of DORGTR


DORMBR example

Computational Routines: Apply orthogonal transformations from reduction to bidiagonal form determined by DGEBRD

Data

DORMBR Example Program Data
  6  4                                      :Values of M and N, Example 1
 -0.57  -1.28  -0.39   0.25
 -1.93   1.08  -0.31  -2.14
  2.30   0.24   0.40  -0.35
 -1.93   0.64  -0.66   0.08
  0.15   0.30   0.15  -2.13
 -0.02   1.03  -1.43   0.50                 :End of matrix A
  4  6                                      :Values of M and N, Example 2
 -5.42   3.28  -3.68   0.27   2.06   0.46
 -1.65  -3.40  -3.20  -1.03  -4.06  -0.01
 -0.37   2.35   1.90   4.31  -1.76   1.13
 -3.15  -0.11   1.99  -2.70   0.26   4.50   :End of matrix A

Result

 DORMBR Example Program Results

 Example 1: bidiagonal matrix B
 Diagonal
     3.6177 -2.4161  1.9213 -1.4265
 Superdiagonal
     1.2587 -1.5262  1.1895

 Example 1: matrix Q
          1       2       3       4
 1  -0.1576 -0.2690  0.2612  0.8513
 2  -0.5335  0.5311 -0.2922  0.0184
 3   0.6358  0.3495 -0.0250 -0.0210
 4  -0.5335  0.0035  0.1537 -0.2592
 5   0.0415  0.5572 -0.2917  0.4523
 6  -0.0055  0.4614  0.8585 -0.0532

 Example 2: bidiagonal matrix B
 Diagonal
    -7.7724  6.1573 -6.0576  5.7933
 Superdiagonal
     1.1926  0.5734 -1.9143

 Example 2: matrix P**T
          1       2       3       4       5       6
 1  -0.7104  0.4299 -0.4824  0.0354  0.2700  0.0603
 2   0.3583  0.1382 -0.4110  0.4044  0.0951 -0.7148
 3  -0.0507  0.4244  0.3795  0.7402 -0.2773  0.2203
 4   0.2442  0.4016  0.4158 -0.1354  0.7666 -0.0137

Source

    Program dormbr_example

!     DORMBR Example Program Text

!     Copyright 2017, Numerical Algorithms Group Ltd. http://www.nag.com

!     .. Use Statements ..
      Use lapack_example_aux, Only: nagf_file_print_matrix_real_gen
      Use lapack_interfaces, Only: dgebrd, dgelqf, dgeqrf, dlacpy, dlaset, &
        dorglq, dorgqr, dormbr
      Use lapack_precision, Only: dp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Real (Kind=dp), Parameter :: zero = 0.0E0_dp
      Integer, Parameter :: nin = 5, nout = 6
!     .. Local Scalars ..
      Integer :: i, ic, ifail, info, lda, ldpt, ldu, lwork, m, n
!     .. Local Arrays ..
      Real (Kind=dp), Allocatable :: a(:, :), d(:), e(:), pt(:, :), tau(:), &
        taup(:), tauq(:), u(:, :), work(:)
!     .. Executable Statements ..
      Write (nout, *) 'DORMBR Example Program Results'
!     Skip heading in data file
      Read (nin, *)
      Do ic = 1, 2
        Read (nin, *) m, n
        lda = m
        ldpt = n
        ldu = m
        lwork = 64*(m+n)
        Allocate (a(lda,n), d(n), e(n-1), pt(ldpt,n), tau(n), taup(n), &
          tauq(n), u(ldu,n), work(lwork))

!       Read A from data file

        Read (nin, *)(a(i,1:n), i=1, m)

        If (m>=n) Then

!         Compute the QR factorization of A
          Call dgeqrf(m, n, a, lda, tau, work, lwork, info)

!         Copy A to U
          Call dlacpy('Lower', m, n, a, lda, u, ldu)

!         Form Q explicitly, storing the result in U
          Call dorgqr(m, n, n, u, ldu, tau, work, lwork, info)

!         Copy R to PT (used as workspace)
          Call dlacpy('Upper', n, n, a, lda, pt, ldpt)

!         Set the strictly lower triangular part of R to zero
          Call dlaset('Lower', n-1, n-1, zero, zero, pt(2,1), ldpt)

!         Bidiagonalize R
          Call dgebrd(n, n, pt, ldpt, d, e, tauq, taup, work, lwork, info)

!         Update Q, storing the result in U
          Call dormbr('Q', 'Right', 'No transpose', m, n, n, pt, ldpt, tauq, &
            u, ldu, work, lwork, info)

!         Print bidiagonal form and matrix Q

          Write (nout, *)
          Write (nout, *) 'Example 1: bidiagonal matrix B'
          Write (nout, *) 'Diagonal'
          Write (nout, 100) d(1:n)
          Write (nout, *) 'Superdiagonal'
          Write (nout, 100) e(1:n-1)
          Write (nout, *)
          Flush (nout)

!         ifail: behaviour on error exit
!                =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
          ifail = 0
          Call nagf_file_print_matrix_real_gen('General', ' ', m, n, u, ldu, &
            'Example 1: matrix Q', ifail)

        Else

!         Compute the LQ factorization of A
          Call dgelqf(m, n, a, lda, tau, work, lwork, info)

!         Copy A to PT
          Call dlacpy('Upper', m, n, a, lda, pt, ldpt)

!         Form Q explicitly, storing the result in PT
          Call dorglq(n, n, m, pt, ldpt, tau, work, lwork, info)

!         Copy L to U (used as workspace)
          Call dlacpy('Lower', m, m, a, lda, u, ldu)

!         Set the strictly upper triangular part of L to zero
          Call dlaset('Upper', m-1, m-1, zero, zero, u(1,2), ldu)

!         Bidiagonalize L
          Call dgebrd(m, m, u, ldu, d, e, tauq, taup, work, lwork, info)

!         Update P**T, storing the result in PT
          Call dormbr('P', 'Left', 'Transpose', m, n, m, u, ldu, taup, pt, &
            ldpt, work, lwork, info)

!         Print bidiagonal form and matrix P**T

          Write (nout, *)
          Write (nout, *) 'Example 2: bidiagonal matrix B'
          Write (nout, *) 'Diagonal'
          Write (nout, 100) d(1:m)
          Write (nout, *) 'Superdiagonal'
          Write (nout, 100) e(1:m-1)
          Write (nout, *)
          Flush (nout)

          ifail = 0
          Call nagf_file_print_matrix_real_gen('General', ' ', m, n, pt, ldpt, &
            'Example 2: matrix P**T', ifail)

        End If
        Deallocate (a, d, e, pt, tau, taup, tauq, u, work)
      End Do

100   Format (3X, (8F8.4))
    End Program
Full documentation of DORMBR


DORMHR example

Computational Routines: Apply orthogonal transformation matrix from reduction to Hessenberg form determined by DGEHRD

Data

DORMHR Example Program Data
  4                           :Value of N
  0.35   0.45  -0.14  -0.17
  0.09   0.07  -0.54   0.35
 -0.44  -0.33  -0.03   0.17
  0.25  -0.32  -0.13   0.11   :End of matrix A
  0.0                         :Value of THRESH

Result

 DORMHR Example Program Results

 Eigenvalues
  (  0.7995,  0.0000)
  ( -0.0994,  0.4008)
  ( -0.0994, -0.4008)
  ( -0.1007,  0.0000)

 Contents of array C
          1       2       3
 1  -0.1933  0.2546  0.1253
 2   0.2519 -0.5224  0.3320
 3   0.0972 -0.3084  0.5938
 4   0.6760  0.0000  0.7221

Source

    Program dormhr_example

!     DORMHR Example Program Text

!     Copyright 2017, Numerical Algorithms Group Ltd. http://www.nag.com

!     .. Use Statements ..
      Use blas_interfaces, Only: dnrm2
      Use lapack_example_aux, Only: nagf_blas_damax_val, &
        nagf_file_print_matrix_real_gen
      Use lapack_interfaces, Only: dgehrd, dhsein, dhseqr, dormhr
      Use lapack_precision, Only: dp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Real (Kind=dp), Parameter :: zero = 0.0_dp
      Integer, Parameter :: nin = 5, nout = 6
!     .. Local Scalars ..
      Complex (Kind=dp) :: eig, eig1
      Real (Kind=dp) :: r, thresh
      Integer :: i, ifail, info, j, k, l, lda, ldc, ldh, ldvl, ldz, lwork, m, &
        n
!     .. Local Arrays ..
      Real (Kind=dp), Allocatable :: a(:, :), c(:, :), h(:, :), tau(:), &
        vl(:, :), wi(:), work(:), wr(:), z(:, :)
      Integer, Allocatable :: ifaill(:), ifailr(:)
      Logical, Allocatable :: select(:)
!     .. Intrinsic Procedures ..
      Intrinsic :: aimag, cmplx, conjg, maxloc, real, sqrt, sum
!     .. Executable Statements ..
      Write (nout, *) 'DORMHR Example Program Results'
!     Skip heading in data file
      Read (nin, *)
      Read (nin, *) n
      ldz = 1
      lda = n
      ldc = n
      ldh = n
      ldvl = n
      lwork = 64*n
      Allocate (a(lda,n), c(ldc,n), h(ldh,n), tau(n), vl(ldvl,n), wi(n), &
        work(lwork), wr(n), z(ldz,1), ifaill(n), ifailr(n), select(n))

!     Read A from data file

      Read (nin, *)(a(i,1:n), i=1, n)

      Read (nin, *) thresh

!     Reduce A to upper Hessenberg form H = (Q**T)*A*Q
      Call dgehrd(n, 1, n, a, lda, tau, work, lwork, info)

!     Copy A to H
      h(1:n, 1:n) = a(1:n, 1:n)

!     Calculate the eigenvalues of H (same as A)
      Call dhseqr('Eigenvalues', 'No vectors', n, 1, n, h, ldh, wr, wi, z, &
        ldz, work, lwork, info)

      Write (nout, *)
      If (info>0) Then
        Write (nout, *) 'Failure to converge.'
      Else
        Write (nout, *) 'Eigenvalues'
        Write (nout, 100)(' (', wr(i), ',', wi(i), ')', i=1, n)

        Do i = 1, n
          select(i) = wr(i) < thresh
        End Do

!       Calculate the eigenvectors of H (as specified by SELECT),
!       storing the result in C
        Call dhsein('Right', 'QR', 'No initial vectors', select, n, a, lda, &
          wr, wi, vl, ldvl, c, ldc, n, m, work, ifaill, ifailr, info)

!       Calculate the eigenvectors of A = Q * (eigenvectors of H)
        Call dormhr('Left', 'No transpose', n, m, 1, n, a, lda, tau, c, ldc, &
          work, lwork, info)

!       Print eigenvectors

        Write (nout, *)
        Flush (nout)

!       Normalize selected eigenvectors
        j = 0
        k = 1
        Do While (k<=n)
          If (select(k)) Then
            j = j + 1
            If (wi(k)==0.0_dp) Then
!             Normalize real eigenvector by making largest positive
              Call nagf_blas_damax_val(n, c(1,j), 1, l, r)
              r = dnrm2(n, c(1,j), 1)
              c(1:n, j) = c(1:n, j)/r
              If (c(l,j)<zero) Then
                c(1:n, j) = -c(1:n, j)
              End If
            Else
!             Normalize complex eigenvectors making largest element real
              work(1:n) = c(1:n, j)**2 + c(1:n, j+1)**2
              l = maxloc(work(1:n), 1)
              eig1 = cmplx(c(l,j), c(l,j+1), kind=dp)
              eig1 = conjg(eig1)/sqrt(work(l)*sum(work(1:n)))
              Do i = 1, n
                eig = cmplx(c(i,j), c(i,j+1), kind=dp)
                eig = eig*eig1
                c(i, j) = real(eig)
                c(i, j+1) = aimag(eig)
              End Do
              c(l, j+1) = 0.0_dp
              j = j + 1
              k = k + 1
            End If
          End If
          k = k + 1
        End Do

!       ifail: behaviour on error exit
!              =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
        ifail = 0
        Call nagf_file_print_matrix_real_gen('General', ' ', n, m, c, ldc, &
          'Contents of array C', ifail)

      End If

100   Format (1X, A, F8.4, A, F8.4, A)
    End Program
Full documentation of DORMHR


DORMTR example

Computational Routines: Apply orthogonal transformation determined by DSYTRD

Data

DORMTR Example Program Data
  4                           :Value of N
  'L'                         :Value of UPLO
  2.07
  3.87  -0.21
  4.20   1.87   1.15
 -1.15   0.63   2.06  -1.81   :End of matrix A

Result

 DORMTR Example Program Results

 Eigenvalues
    -5.0034 -1.9987

 Eigenvectors
          1       2
 1   0.5658 -0.2328
 2  -0.3478  0.7994
 3  -0.4740 -0.4087
 4   0.5781  0.3737

Source

    Program dormtr_example

!     DORMTR Example Program Text

!     Copyright 2017, Numerical Algorithms Group Ltd. http://www.nag.com

!     .. Use Statements ..
      Use lapack_example_aux, Only: nagf_file_print_matrix_real_gen
      Use lapack_interfaces, Only: dormtr, dstebz, dstein, dsytrd
      Use lapack_precision, Only: dp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Real (Kind=dp), Parameter :: zero = 0.0E0_dp
      Integer, Parameter :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=dp) :: vl, vu
      Integer :: i, ifail, info, lda, ldc, lwork, m, n, nsplit
      Character (1) :: uplo
!     .. Local Arrays ..
      Real (Kind=dp), Allocatable :: a(:, :), c(:, :), d(:), e(:), tau(:), &
        w(:), work(:)
      Integer, Allocatable :: iblock(:), ifailv(:), isplit(:), iwork(:)
!     .. Executable Statements ..
      Write (nout, *) 'DORMTR Example Program Results'
!     Skip heading in data file
      Read (nin, *)
      Read (nin, *) n
      lda = n
      ldc = n
      lwork = 64*n
      Allocate (a(lda,n), c(ldc,n), d(n), e(n), tau(n), w(n), work(lwork), &
        iblock(n), ifailv(n), isplit(n), iwork(3*n))

!     Read A from data file

      Read (nin, *) uplo
      If (uplo=='U') Then
        Read (nin, *)(a(i,i:n), i=1, n)
      Else If (uplo=='L') Then
        Read (nin, *)(a(i,1:i), i=1, n)
      End If

!     Reduce A to tridiagonal form T = (Q**T)*A*Q
      Call dsytrd(uplo, n, a, lda, d, e, tau, work, lwork, info)

!     Calculate the two smallest eigenvalues of T (same as A)

      Call dstebz('I', 'B', n, vl, vu, 1, 2, zero, d, e, m, nsplit, w, iblock, &
        isplit, work, iwork, info)

      Write (nout, *)
      If (info>0) Then
        Write (nout, *) 'Failure to converge.'
      Else
        Write (nout, *) 'Eigenvalues'
        Write (nout, 100) w(1:m)

!       Calculate the eigenvectors of T, storing the result in C
        Call dstein(n, d, e, m, w, iblock, isplit, c, ldc, work, iwork, &
          ifailv, info)

        If (info>0) Then
          Write (nout, *) 'Failure to converge.'
        Else

!         Calculate the eigenvectors of A = Q * (eigenvectors of T)
          Call dormtr('Left', uplo, 'No transpose', n, m, a, lda, tau, c, ldc, &
            work, lwork, info)

!         Print eigenvectors

          Write (nout, *)
          Flush (nout)

!         ifail: behaviour on error exit
!                =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
          ifail = 0
          Call nagf_file_print_matrix_real_gen('General', ' ', n, m, c, ldc, &
            'Eigenvectors', ifail)

        End If
      End If

100   Format (3X, (9F8.4))
    End Program
Full documentation of DORMTR


DPBCON example

Computational Routines: Estimate condition number of real symmetric positive-definite band matrix, matrix already factorized by DPBTRF

Data

DPBCON Example Program Data
  4  1                        :Values of N and KD
  'L'                         :Value of UPLO
  5.49
  2.68   5.63
        -2.39   2.60
               -2.22   5.17   :End of matrix A

Result

 DPBCON Example Program Results

 Estimate of condition number =  7.42E+01

Source

    Program dpbcon_example

!     DPBCON Example Program Text

!     Copyright 2017, Numerical Algorithms Group Ltd. http://www.nag.com

!     .. Use Statements ..
      Use lapack_interfaces, Only: dlansb, dpbcon, dpbtrf
      Use lapack_precision, Only: dp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=dp) :: anorm, rcond
      Integer :: i, info, j, kd, ldab, n
      Character (1) :: uplo
!     .. Local Arrays ..
      Real (Kind=dp), Allocatable :: ab(:, :), work(:)
      Integer, Allocatable :: iwork(:)
!     .. Intrinsic Procedures ..
      Intrinsic :: epsilon, max, min
!     .. Executable Statements ..
      Write (nout, *) 'DPBCON Example Program Results'
!     Skip heading in data file
      Read (nin, *)
      Read (nin, *) n, kd
      ldab = kd + 1
      Allocate (ab(ldab,n), work(3*n), iwork(n))

!     Read A from data file

      Read (nin, *) uplo
      If (uplo=='U') Then
        Do i = 1, n
          Read (nin, *)(ab(kd+1+i-j,j), j=i, min(n,i+kd))
        End Do
      Else If (uplo=='L') Then
        Do i = 1, n
          Read (nin, *)(ab(1+i-j,j), j=max(1,i-kd), i)
        End Do
      End If

!     Compute norm of A

      anorm = dlansb('1-norm', uplo, n, kd, ab, ldab, work)

!     Factorize A
      Call dpbtrf(uplo, n, kd, ab, ldab, info)

      Write (nout, *)
      If (info==0) Then

!       Estimate condition number
        Call dpbcon(uplo, n, kd, ab, ldab, anorm, rcond, work, iwork, info)

        If (rcond>=epsilon(1.0E0_dp)) Then
          Write (nout, 100) 'Estimate of condition number =', 1.0_dp/rcond
        Else
          Write (nout, *) 'A is singular to working precision'
        End If
      Else
        Write (nout, *) 'A is not positive definite'
      End If

100   Format (1X, A, 1P, E10.2)
    End Program
Full documentation of DPBCON


DPBEQU example

Computational Routines: Computes row and column scalings intended to equilibrate a real symmetric positive-definite banded matrix and reduce its condition number

Data

DPBEQU Example Program Data
  4  1                                      :Values of N and KD
  5.49E+00   2.68E+10
             5.63E+20  -2.39E+10
                        2.60E+00  -2.22E+00
                                   5.17E+00 :End of matrix A

Result

 DPBEQU Example Program Results

 Matrix A
               1            2            3            4
 1    5.4900E+00   2.6800E+10
 2                 5.6300E+20  -2.3900E+10
 3                              2.6000E+00  -2.2200E+00
 4                                           5.1700E+00

 SCOND = 6.8E-11, AMAX = 5.6E+20

 Diagonal scaling factors
     4.3E-01    4.2E-11    6.2E-01    4.4E-01

 Scaled matrix
             1          2          3          4
 1      1.0000     0.4821
 2                 1.0000    -0.6247
 3                            1.0000    -0.6055
 4                                       1.0000

Source

    Program dpbequ_example

!     DPBEQU Example Program Text

!     Copyright 2017, Numerical Algorithms Group Ltd. http://www.nag.com

!     .. Use Statements ..
      Use blas_interfaces, Only: dscal
      Use lapack_example_aux, Only: nagf_blas_ddscl, &
        nagf_file_print_matrix_real_band
      Use lapack_interfaces, Only: dpbequ
      Use lapack_precision, Only: dp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Real (Kind=dp), Parameter :: one = 1.0_dp
      Real (Kind=dp), Parameter :: thresh = 0.1_dp
      Integer, Parameter :: nin = 5, nout = 6
      Character (1), Parameter :: uplo = 'U'
!     .. Local Scalars ..
      Real (Kind=dp) :: amax, big, scond, small
      Integer :: i, i0, i1, ifail, ilen, info, j, kd, ldab, n
!     .. Local Arrays ..
      Real (Kind=dp), Allocatable :: ab(:, :), s(:)
!     .. Intrinsic Procedures ..
      Intrinsic :: epsilon, max, min, radix, real, tiny
!     .. Executable Statements ..
      Write (nout, *) 'DPBEQU Example Program Results'
      Write (nout, *)
      Flush (nout)
!     Skip heading in data file
      Read (nin, *)
      Read (nin, *) n, kd
      ldab = kd + 1
      Allocate (ab(ldab,n), s(n))

!     Read the upper or lower triangular part of the band matrix A
!     from data file

      If (uplo=='U') Then
        Do i = 1, n
          Read (nin, *)(ab(kd+1+i-j,j), j=i, min(n,i+kd))
        End Do
      Else If (uplo=='L') Then
        Do i = 1, n
          Read (nin, *)(ab(1+i-j,j), j=max(1,i-kd), i)
        End Do
      End If

!     Print the matrix A

!     ifail: behaviour on error exit
!             =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
      ifail = 0
      If (uplo=='U') Then
        Call nagf_file_print_matrix_real_band(n, n, 0, kd, ab, ldab, &
          'Matrix A', ifail)
      Else If (uplo=='L') Then
        Call nagf_file_print_matrix_real_band(n, n, kd, 0, ab, ldab, &
          'Matrix A', ifail)
      End If

      Write (nout, *)

!     Compute diagonal scaling factors
      Call dpbequ(uplo, n, kd, ab, ldab, s, scond, amax, info)

      If (info>0) Then
        Write (nout, 100) 'Diagonal element', info, ' of A is non positive'
      Else

!       Print SCOND, AMAX and the scale factors

        Write (nout, 110) 'SCOND =', scond, ', AMAX =', amax
        Write (nout, *)
        Write (nout, *) 'Diagonal scaling factors'
        Write (nout, 120) s(1:n)
        Write (nout, *)
        Flush (nout)

!       Compute values close to underflow and overflow

        small = tiny(1.0E0_dp)/(epsilon(1.0E0_dp)*real(radix(1.0E0_dp),kind=dp &
          ))
        big = one/small
        If ((scond<thresh) .Or. (amax<small) .Or. (amax>big)) Then

!         Scale A
          If (uplo=='U') Then

            Do j = 1, n
              i0 = max(1, j-kd)
              i1 = 1 + i0 - (j-kd)
              ilen = j - i0 + 1
              Call dscal(ilen, s(j), ab(i1,j), 1)
              Call nagf_blas_ddscl(ilen, s(i0), 1, ab(i1,j), 1)
            End Do

          Else If (uplo=='L') Then
            Do j = 1, n
              i1 = 1
              ilen = min(n, j+kd) - j + 1
              Call dscal(ilen, s(j), ab(i1,j), 1)
              Call nagf_blas_ddscl(ilen, s(j), 1, ab(i1,j), 1)
            End Do
          End If

!         Print the scaled matrix

          ifail = 0
          If (uplo=='U') Then
            Call nagf_file_print_matrix_real_band(n, n, 0, kd, ab, ldab, &
              'Scaled matrix', ifail)
          Else If (uplo=='L') Then
            Call nagf_file_print_matrix_real_band(n, n, kd, 0, ab, ldab, &
              'Scaled matrix', ifail)
          End If
        End If
      End If

100   Format (1X, A, I4, A)
110   Format (1X, 2(A,1P,E8.1))
120   Format ((1X,1P,7E11.1))
    End Program
Full documentation of DPBEQU


DPBRFS example

Computational Routines: Refined solution with error bounds of real symmetric positive-definite band system of linear equations, multiple right-hand sides

Data

DPBRFS Example Program Data
  4  1  2                     :Values of N, KD and NRHS
  'L'                         :Value of UPLO
  5.49
  2.68   5.63
        -2.39   2.60
               -2.22   5.17   :End of matrix A
 22.09   5.10
  9.31  30.81
 -5.24 -25.82
 11.83  22.90                 :End of matrix B

Result

 DPBRFS Example Program Results

 Solution(s)
             1          2
 1      5.0000    -2.0000
 2     -2.0000     6.0000
 3     -3.0000    -1.0000
 4      1.0000     4.0000

 Backward errors (machine-dependent)
       4.4E-17    9.2E-17
 Estimated forward error bounds (machine-dependent)
       2.0E-14    2.9E-14

Source

    Program dpbrfs_example

!     DPBRFS Example Program Text

!     Copyright 2017, Numerical Algorithms Group Ltd. http://www.nag.com

!     .. Use Statements ..
      Use lapack_example_aux, Only: nagf_file_print_matrix_real_gen
      Use lapack_interfaces, Only: dpbrfs, dpbtrf, dpbtrs
      Use lapack_precision, Only: dp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Real (Kind=dp), Parameter :: zero = 0.0E0_dp
      Integer, Parameter :: nin = 5, nout = 6
!     .. Local Scalars ..
      Integer :: i, ifail, info, j, kd, ldab, ldafb, ldb, ldx, n, nrhs
      Character (1) :: uplo
!     .. Local Arrays ..
      Real (Kind=dp), Allocatable :: ab(:, :), afb(:, :), b(:, :), berr(:), &
        ferr(:), work(:), x(:, :)
      Integer, Allocatable :: iwork(:)
!     .. Intrinsic Procedures ..
      Intrinsic :: max, min
!     .. Executable Statements ..
      Write (nout, *) 'DPBRFS Example Program Results'
!     Skip heading in data file
      Read (nin, *)
      Read (nin, *) n, kd, nrhs
      ldab = kd + 1
      ldafb = kd + 1
      ldb = n
      ldx = n
      Allocate (ab(ldab,n), afb(ldafb,n), b(ldb,nrhs), berr(nrhs), ferr(nrhs), &
        work(3*n), x(ldx,n), iwork(n))

!     Set A to zero to avoid referencing uninitialized elements

      ab(1:kd+1, 1:n) = zero

!     Read A and B from data file, and copy A to AFB and B to X

      Read (nin, *) uplo
      If (uplo=='U') Then
        Do i = 1, n
          Read (nin, *)(ab(kd+1+i-j,j), j=i, min(n,i+kd))
        End Do
      Else If (uplo=='L') Then
        Do i = 1, n
          Read (nin, *)(ab(1+i-j,j), j=max(1,i-kd), i)
        End Do
      End If
      Read (nin, *)(b(i,1:nrhs), i=1, n)

      afb(1:kd+1, 1:n) = ab(1:kd+1, 1:n)
      x(1:n, 1:nrhs) = b(1:n, 1:nrhs)

!     Factorize A in the array AFB
      Call dpbtrf(uplo, n, kd, afb, ldafb, info)

      Write (nout, *)
      Flush (nout)
      If (info==0) Then

!       Compute solution in the array X
        Call dpbtrs(uplo, n, kd, nrhs, afb, ldafb, x, ldx, info)

!       Improve solution, and compute backward errors and
!       estimated bounds on the forward errors

        Call dpbrfs(uplo, n, kd, nrhs, ab, ldab, afb, ldafb, b, ldb, x, ldx, &
          ferr, berr, work, iwork, info)

!       Print solution

!       ifail: behaviour on error exit
!              =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
        ifail = 0
        Call nagf_file_print_matrix_real_gen('General', ' ', n, nrhs, x, ldx, &
          'Solution(s)', ifail)

        Write (nout, *)
        Write (nout, *) 'Backward errors (machine-dependent)'
        Write (nout, 100) berr(1:nrhs)
        Write (nout, *) 'Estimated forward error bounds (machine-dependent)'
        Write (nout, 100) ferr(1:nrhs)
      Else
        Write (nout, *) 'A is not positive definite'
      End If

100   Format ((3X,1P,7E11.1))
    End Program
Full documentation of DPBRFS


DPBTRF example

Computational Routines: Cholesky factorization of real symmetric positive-definite band matrix

Data

DPBTRF Example Program Data
  4  1                        :Values of N and KD
  'L'                         :Value of UPLO
  5.49
  2.68   5.63
        -2.39   2.60
               -2.22   5.17   :End of matrix A

Result

 DPBTRF Example Program Results

 Factor
             1          2          3          4
 1      2.3431
 2      1.1438     2.0789
 3                -1.1497     1.1306
 4                           -1.9635     1.1465

Source

    Program dpbtrf_example

!     DPBTRF Example Program Text

!     Copyright 2017, Numerical Algorithms Group Ltd. http://www.nag.com

!     .. Use Statements ..
      Use lapack_example_aux, Only: nagf_file_print_matrix_real_band
      Use lapack_interfaces, Only: dpbtrf
      Use lapack_precision, Only: dp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter :: nin = 5, nout = 6
!     .. Local Scalars ..
      Integer :: i, ifail, info, j, kd, ldab, n
      Character (1) :: uplo
!     .. Local Arrays ..
      Real (Kind=dp), Allocatable :: ab(:, :)
!     .. Intrinsic Procedures ..
      Intrinsic :: max, min
!     .. Executable Statements ..
      Write (nout, *) 'DPBTRF Example Program Results'
!     Skip heading in data file
      Read (nin, *)
      Read (nin, *) n, kd
      ldab = kd + 1
      Allocate (ab(ldab,n))

!     Read A from data file

      Read (nin, *) uplo
      If (uplo=='U') Then
        Do i = 1, n
          Read (nin, *)(ab(kd+1+i-j,j), j=i, min(n,i+kd))
        End Do
      Else If (uplo=='L') Then
        Do i = 1, n
          Read (nin, *)(ab(1+i-j,j), j=max(1,i-kd), i)
        End Do
      End If

!     Factorize A
      Call dpbtrf(uplo, n, kd, ab, ldab, info)

      Write (nout, *)
      Flush (nout)
      If (info==0) Then

!       Print factor

!       ifail: behaviour on error exit
!              =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
        ifail = 0

        If (uplo=='U') Then

          Call nagf_file_print_matrix_real_band(n, n, 0, kd, ab, ldab, &
            'Factor', ifail)

        Else If (uplo=='L') Then

          Call nagf_file_print_matrix_real_band(n, n, kd, 0, ab, ldab, &
            'Factor', ifail)

        End If

      Else
        Write (nout, *) 'A is not positive definite'
      End If

    End Program
Full documentation of DPBTRF


DPBTRS example

Computational Routines: Solution of real symmetric positive-definite band system of linear equations, multiple right-hand sides, matrix already factorized by DPBTRF

Data

DPBTRS Example Program Data
  4  1  2                     :Values of N, KD and NRHS
  'L'                         :Value of UPLO
  5.49
  2.68   5.63
        -2.39   2.60
               -2.22   5.17   :End of matrix A
 22.09   5.10
  9.31  30.81
 -5.24 -25.82
 11.83  22.90                 :End of matrix B

Result

 DPBTRS Example Program Results

 Solution(s)
             1          2
 1      5.0000    -2.0000
 2     -2.0000     6.0000
 3     -3.0000    -1.0000
 4      1.0000     4.0000

Source

    Program dpbtrs_example

!     DPBTRS Example Program Text

!     Copyright 2017, Numerical Algorithms Group Ltd. http://www.nag.com

!     .. Use Statements ..
      Use lapack_example_aux, Only: nagf_file_print_matrix_real_gen
      Use lapack_interfaces, Only: dpbtrf, dpbtrs
      Use lapack_precision, Only: dp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter :: nin = 5, nout = 6
!     .. Local Scalars ..
      Integer :: i, ifail, info, j, kd, ldab, ldb, n, nrhs
      Character (1) :: uplo
!     .. Local Arrays ..
      Real (Kind=dp), Allocatable :: ab(:, :), b(:, :)
!     .. Intrinsic Procedures ..
      Intrinsic :: max, min
!     .. Executable Statements ..
      Write (nout, *) 'DPBTRS Example Program Results'
!     Skip heading in data file
      Read (nin, *)
      Read (nin, *) n, kd, nrhs
      ldab = kd + 1
      ldb = n
      Allocate (ab(ldab,n), b(ldb,nrhs))

!     Read A and B from data file

      Read (nin, *) uplo
      If (uplo=='U') Then
        Do i = 1, n
          Read (nin, *)(ab(kd+1+i-j,j), j=i, min(n,i+kd))
        End Do
      Else If (uplo=='L') Then
        Do i = 1, n
          Read (nin, *)(ab(1+i-j,j), j=max(1,i-kd), i)
        End Do
      End If
      Read (nin, *)(b(i,1:nrhs), i=1, n)

!     Factorize A
      Call dpbtrf(uplo, n, kd, ab, ldab, info)

      Write (nout, *)
      Flush (nout)
      If (info==0) Then

!       Compute solution
        Call dpbtrs(uplo, n, kd, nrhs, ab, ldab, b, ldb, info)

!       Print solution

!       ifail: behaviour on error exit
!              =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
        ifail = 0
        Call nagf_file_print_matrix_real_gen('General', ' ', n, nrhs, b, ldb, &
          'Solution(s)', ifail)

      Else
        Write (nout, *) 'A is not positive definite'
      End If

    End Program
Full documentation of DPBTRS


DPFTRF example

Computational Routines: Cholesky factorization of real symmetric positive definite matrix, Rectangular Full Packed format

Data

DPFTRF Example Program Data
  4       'L'      'N' : n, uplo, transr
  0.76    0.34
  4.16    1.18
 -3.12    5.03
  0.56   -0.83
 -0.10    1.18         : RFP matrix AR

Result

 DPFTRF Example Program Results

 Factor
             1          2          3          4
 1      2.0396
 2     -1.5297     1.6401
 3      0.2746    -0.2500     0.7887
 4     -0.0490     0.6737     0.6617     0.5347

Source

    Program dpftrf_example

!     DPFTRF Example Program Text

!     Copyright 2017, Numerical Algorithms Group Ltd. http://www.nag.com

!     .. Use Statements ..
      Use lapack_example_aux, Only: nagf_file_print_matrix_real_gen
      Use lapack_interfaces, Only: dpftrf, dtfttr
      Use lapack_precision, Only: dp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter :: nin = 5, nout = 6
!     .. Local Scalars ..
      Integer :: i, ifail, info, k, lar1, lda, lenar, n, q
      Character (1) :: transr, uplo
!     .. Local Arrays ..
      Real (Kind=dp), Allocatable :: a(:, :), ar(:)
!     .. Executable Statements ..
      Write (nout, *) 'DPFTRF Example Program Results'
!     Skip heading in data file
      Read (nin, *)
      Read (nin, *) n, uplo, transr

      lenar = n*(n+1)/2
      lda = n
      Allocate (ar(lenar), a(lda,n))

!     Setup notional dimensions of RFP matrix AR
      k = n/2
      q = n - k
      If (transr=='N' .Or. transr=='n') Then
        lar1 = 2*k + 1
      Else
        lar1 = q
      End If

!     Read an RFP matrix into array AR
      Do i = 1, lar1
        Read (nin, *) ar(i:lenar:lar1)
      End Do

!     Factorize A
      Call dpftrf(transr, uplo, n, ar, info)

      Write (nout, *)
      Flush (nout)
      If (info==0) Then

!       Convert factor to full array form, and print it
        Call dtfttr(transr, uplo, n, ar, a, lda, info)
        ifail = 0
        Call nagf_file_print_matrix_real_gen(uplo, 'Nonunit', n, n, a, lda, &
          'Factor', ifail)

      Else
        Write (nout, *) 'A is not positive definite'
      End If

    End Program
Full documentation of DPFTRF


DPFTRI example

Computational Routines: Inverse of real symmetric positive definite matrix, matrix already factorized by DPFTRF, Rectangular Full Packed format

Data

DPFTRI Example Program Data
  4       'L'       'N'   : n, uplo, transr

  0.76    0.34
  4.16    1.18
 -3.12    5.03
  0.56   -0.83
 -0.10    1.18            : AR

Result

 DPFTRI Example Program Results

 Inverse
             1          2          3          4
 1      0.6995
 2      0.7769     1.4239
 3      0.7508     1.8255     4.0688
 4     -0.9340    -1.8841    -2.9342     3.4978

Source

    Program dpftri_example

!     DPFTRI Example Program Text

!     Copyright 2017, Numerical Algorithms Group Ltd. http://www.nag.com

!     .. Use Statements ..
      Use lapack_example_aux, Only: nagf_file_print_matrix_real_gen
      Use lapack_interfaces, Only: dpftrf, dpftri, dtfttr
      Use lapack_precision, Only: dp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter :: nin = 5, nout = 6
!     .. Local Scalars ..
      Integer :: i, ifail, info, k, lar1, lda, lenar, n, q
      Character (1) :: transr, uplo
!     .. Local Arrays ..
      Real (Kind=dp), Allocatable :: a(:, :), ar(:)
!     .. Executable Statements ..
      Write (nout, *) 'DPFTRI Example Program Results'
!     Skip heading in data file
      Read (nin, *)
      Read (nin, *) n, uplo, transr

      lenar = n*(n+1)/2
      lda = n
      Allocate (ar(lenar), a(lda,n))

!     Setup notional dimensions of RFP matrix AR
      k = n/2
      q = n - k
      If (transr=='N' .Or. transr=='n') Then
        lar1 = 2*k + 1
      Else
        lar1 = q
      End If

!     Read an RFP matrix into array AR
      Do i = 1, lar1
        Read (nin, *) ar(i:lenar:lar1)
      End Do

!     Factorize A
      Call dpftrf(transr, uplo, n, ar, info)

      Write (nout, *)
      Flush (nout)
      If (info==0) Then

!       Compute inverse of A
        Call dpftri(transr, uplo, n, ar, info)

!       Convert inverse to full array form, and print it
        Call dtfttr(transr, uplo, n, ar, a, lda, info)
        ifail = 0
        Call nagf_file_print_matrix_real_gen(uplo, 'Nonunit', n, n, a, lda, &
          'Inverse', ifail)

      Else
        Write (nout, *) 'A is not positive definite'
      End If

    End Program
Full documentation of DPFTRI


DPFTRS example

Computational Routines: Solution of real symmetric positive definite system of linear equations, multiple right-hand sides, coefficient matrix already factorized by DPFTRF, Rectangular Full Packed format

Data

DPFTRS Example Program Data
  4 2     'L'     'N'    : n, nrhs, uplo, transr
  0.76    0.34
  4.16    1.18
 -3.12    5.03
  0.56   -0.83
 -0.10    1.18           : AR

  8.70   8.30
-13.35   2.13
  1.89   1.61
 -4.14   5.00            : B

Result

 DPFTRS Example Program Results

 Solution(s)
             1          2
 1      1.0000     4.0000
 2     -1.0000     3.0000
 3      2.0000     2.0000
 4     -3.0000     1.0000

Source

    Program dpftrs_example

!     DPFTRS Example Program Text

!     Copyright 2017, Numerical Algorithms Group Ltd. http://www.nag.com

!     .. Use Statements ..
      Use lapack_example_aux, Only: nagf_file_print_matrix_real_gen
      Use lapack_interfaces, Only: dpftrf, dpftrs
      Use lapack_precision, Only: dp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter :: nin = 5, nout = 6
!     .. Local Scalars ..
      Integer :: i, ifail, info, k, lar1, ldb, lenar, n, nrhs, q
      Character (1) :: transr, uplo
!     .. Local Arrays ..
      Real (Kind=dp), Allocatable :: ar(:), b(:, :)
!     .. Executable Statements ..
      Write (nout, *) 'DPFTRS Example Program Results'
!     Skip heading in data file
      Read (nin, *)
      Read (nin, *) n, nrhs, uplo, transr

      lenar = n*(n+1)/2
      ldb = n
      Allocate (ar(lenar), b(ldb,nrhs))

!     Setup notional dimensions of RFP matrix AR
      k = n/2
      q = n - k
      If (transr=='N' .Or. transr=='n') Then
        lar1 = 2*k + 1
      Else
        lar1 = q
      End If

!     Read an RFP matrix into array AR
      Do i = 1, lar1
        Read (nin, *) ar(i:lenar:lar1)
      End Do

!     Read RHS matrix B
      Do i = 1, n
        Read (nin, *) b(i, 1:nrhs)
      End Do

!     Factorize A
      Call dpftrf(transr, uplo, n, ar, info)

      Write (nout, *)
      Flush (nout)
      If (info==0) Then

!       Compute solution
        Call dpftrs(transr, uplo, n, nrhs, ar, b, ldb, info)

!       Print solution
        ifail = 0
        Call nagf_file_print_matrix_real_gen('General', ' ', n, nrhs, b, ldb, &
          'Solution(s)', ifail)

      Else
        Write (nout, *) 'A is not positive definite'
      End If

    End Program
Full documentation of DPFTRS


DPOCON example

Computational Routines: Estimate condition number of real symmetric positive-definite matrix, matrix already factorized by DPOTRF

Data

DPOCON Example Program Data
  4                           :Value of N
  'L'                         :Value of UPLO
  4.16
 -3.12   5.03
  0.56  -0.83   0.76
 -0.10   1.18   0.34   1.18   :End of matrix A

Result

 DPOCON Example Program Results

 Estimate of condition number =  9.73E+01

Source

    Program dpocon_example

!     DPOCON Example Program Text

!     Copyright 2017, Numerical Algorithms Group Ltd. http://www.nag.com

!     .. Use Statements ..
      Use lapack_interfaces, Only: dlansy, dpocon, dpotrf
      Use lapack_precision, Only: dp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=dp) :: anorm, rcond
      Integer :: i, info, lda, n
      Character (1) :: uplo
!     .. Local Arrays ..
      Real (Kind=dp), Allocatable :: a(:, :), work(:)
      Integer, Allocatable :: iwork(:)
!     .. Intrinsic Procedures ..
      Intrinsic :: epsilon
!     .. Executable Statements ..
      Write (nout, *) 'DPOCON Example Program Results'
!     Skip heading in data file
      Read (nin, *)
      Read (nin, *) n
      lda = n
      Allocate (a(lda,n), work(3*n), iwork(n))

!     Read A from data file

      Read (nin, *) uplo
      If (uplo=='U') Then
        Read (nin, *)(a(i,i:n), i=1, n)
      Else If (uplo=='L') Then
        Read (nin, *)(a(i,1:i), i=1, n)
      End If

!     Compute norm of A
      anorm = dlansy('1-norm', uplo, n, a, lda, work)

!     Factorize A
      Call dpotrf(uplo, n, a, lda, info)

      Write (nout, *)
      If (info==0) Then

!       Estimate condition number

        Call dpocon(uplo, n, a, lda, anorm, rcond, work, iwork, info)

        If (rcond>=epsilon(1.0E0_dp)) Then
          Write (nout, 100) 'Estimate of condition number =', 1.0_dp/rcond
        Else
          Write (nout, *) 'A is singular to working precision'
        End If
      Else
        Write (nout, *) 'A is not positive definite'
      End If

100   Format (1X, A, 1P, E10.2)
    End Program
Full documentation of DPOCON


DPOEQU example

Computational Routines: Computes row and column scalings intended to equilibrate a real symmetric positive-definite matrix and reduce its condition number

Data

DPOEQU Example Program Data
  4                                         :Value of N
  4.16D+00  -3.12D+05   0.56D+00  -0.10D+00
             5.03D+10  -0.83D+05   1.18D+05
                        0.76D+00   0.34D+00
                                   1.18D+00 :End of matrix A

Result

 DPOEQU Example Program Results

 Matrix A
               1            2            3            4
 1    4.1600E+00  -3.1200E+05   5.6000E-01  -1.0000E-01
 2                 5.0300E+10  -8.3000E+04   1.1800E+05
 3                              7.6000E-01   3.4000E-01
 4                                           1.1800E+00

 SCOND = 3.9E-06, AMAX = 5.0E+10

 Diagonal scaling factors
     4.9E-01    4.5E-06    1.1E+00    9.2E-01

 Scaled matrix
             1          2          3          4
 1      1.0000    -0.6821     0.3149    -0.0451
 2                 1.0000    -0.4245     0.4843
 3                            1.0000     0.3590
 4                                       1.0000

Source

    Program dpoequ_example

!     DPOEQU Example Program Text

!     Copyright 2017, Numerical Algorithms Group Ltd. http://www.nag.com

!     .. Use Statements ..
      Use blas_interfaces, Only: dscal
      Use lapack_example_aux, Only: nagf_blas_ddscl, &
        nagf_file_print_matrix_real_gen
      Use lapack_interfaces, Only: dpoequ
      Use lapack_precision, Only: dp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Real (Kind=dp), Parameter :: one = 1.0_dp
      Real (Kind=dp), Parameter :: thresh = 0.1_dp
      Integer, Parameter :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=dp) :: amax, big, scond, small
      Integer :: i, ifail, info, j, lda, n
!     .. Local Arrays ..
      Real (Kind=dp), Allocatable :: a(:, :), s(:)
!     .. Intrinsic Procedures ..
      Intrinsic :: epsilon, radix, real, tiny
!     .. Executable Statements ..
      Write (nout, *) 'DPOEQU Example Program Results'
      Write (nout, *)
      Flush (nout)
!     Skip heading in data file
      Read (nin, *)
      Read (nin, *) n
      lda = n
      Allocate (a(lda,n), s(n))

!     Read the upper triangular part of the matrix A from data file

      Read (nin, *)(a(i,i:n), i=1, n)

!     Print the matrix A

!     ifail: behaviour on error exit
!             =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
      ifail = 0
      Call nagf_file_print_matrix_real_gen('Upper', 'Non-unit', n, n, a, lda, &
        'Matrix A', ifail)

      Write (nout, *)

!     Compute diagonal scaling factors
      Call dpoequ(n, a, lda, s, scond, amax, info)

      If (info>0) Then
        Write (nout, 100) 'Diagonal element', info, ' of A is non positive'
      Else

!       Print SCOND, AMAX and the scale factors

        Write (nout, 110) 'SCOND =', scond, ', AMAX =', amax
        Write (nout, *)
        Write (nout, *) 'Diagonal scaling factors'
        Write (nout, 120) s(1:n)
        Write (nout, *)
        Flush (nout)

!       Compute values close to underflow and overflow

        small = tiny(1.0E0_dp)/(epsilon(1.0E0_dp)*real(radix(1.0E0_dp),kind=dp &
          ))
        big = one/small
        If ((scond<thresh) .Or. (amax<small) .Or. (amax>big)) Then

!         Scale A
          Do j = 1, n
            Call dscal(j, s(j), a(1,j), 1)
            Call nagf_blas_ddscl(j, s, 1, a(1,j), 1)
          End Do

!         Print the scaled matrix

          ifail = 0
          Call nagf_file_print_matrix_real_gen('Upper', 'Non-unit', n, n, a, &
            lda, 'Scaled matrix', ifail)

        End If
      End If

100   Format (1X, A, I4, A)
110   Format (1X, 2(A,1P,E8.1))
120   Format ((1X,1P,7E11.1))
    End Program
Full documentation of DPOEQU


DPORFS example

Computational Routines: Refined solution with error bounds of real symmetric positive-definite system of linear equations, multiple right-hand sides

Data

DPORFS Example Program Data
  4  2                        :Values of N and NRHS
  'L'                         :Value of UPLO
  4.16
 -3.12   5.03
  0.56  -0.83   0.76
 -0.10   1.18   0.34   1.18   :End of matrix A
  8.70   8.30
-13.35   2.13
  1.89   1.61
 -4.14   5.00                 :End of matrix B

Result

 DPORFS Example Program Results

 Solution(s)
             1          2
 1      1.0000     4.0000
 2     -1.0000     3.0000
 3      2.0000     2.0000
 4     -3.0000     1.0000

 Backward errors (machine-dependent)
       1.0E-16    5.0E-17
 Estimated forward error bounds (machine-dependent)
       2.3E-14    2.3E-14

Source

    Program dporfs_example

!     DPORFS Example Program Text

!     Copyright 2017, Numerical Algorithms Group Ltd. http://www.nag.com

!     .. Use Statements ..
      Use lapack_example_aux, Only: nagf_file_print_matrix_real_gen
      Use lapack_interfaces, Only: dlacpy, dporfs, dpotrf, dpotrs
      Use lapack_precision, Only: dp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter :: nin = 5, nout = 6
!     .. Local Scalars ..
      Integer :: i, ifail, info, lda, ldaf, ldb, ldx, n, nrhs
      Character (1) :: uplo
!     .. Local Arrays ..
      Real (Kind=dp), Allocatable :: a(:, :), af(:, :), b(:, :), berr(:), &
        ferr(:), work(:), x(:, :)
      Integer, Allocatable :: iwork(:)
!     .. Executable Statements ..
      Write (nout, *) 'DPORFS Example Program Results'
!     Skip heading in data file
      Read (nin, *)
      Read (nin, *) n, nrhs
      lda = n
      ldaf = n
      ldb = n
      ldx = n
      Allocate (a(lda,n), af(ldaf,n), b(ldb,nrhs), berr(nrhs), ferr(nrhs), &
        work(3*n), x(ldx,n), iwork(n))

!     Read A and B from data file, and copy A to AF and B to X

      Read (nin, *) uplo
      If (uplo=='U') Then
        Read (nin, *)(a(i,i:n), i=1, n)
      Else If (uplo=='L') Then
        Read (nin, *)(a(i,1:i), i=1, n)
      End If
      Read (nin, *)(b(i,1:nrhs), i=1, n)

      Call dlacpy(uplo, n, n, a, lda, af, ldaf)

      x(1:n, 1:nrhs) = b(1:n, 1:nrhs)

!     Factorize A in the array AF
      Call dpotrf(uplo, n, af, ldaf, info)

      Write (nout, *)
      Flush (nout)
      If (info==0) Then

!       Compute solution in the array X
        Call dpotrs(uplo, n, nrhs, af, ldaf, x, ldx, info)

!       Improve solution, and compute backward errors and
!       estimated bounds on the forward errors

        Call dporfs(uplo, n, nrhs, a, lda, af, ldaf, b, ldb, x, ldx, ferr, &
          berr, work, iwork, info)

!       Print solution

!       ifail: behaviour on error exit
!              =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
        ifail = 0
        Call nagf_file_print_matrix_real_gen('General', ' ', n, nrhs, x, ldx, &
          'Solution(s)', ifail)

        Write (nout, *)
        Write (nout, *) 'Backward errors (machine-dependent)'
        Write (nout, 100) berr(1:nrhs)
        Write (nout, *) 'Estimated forward error bounds (machine-dependent)'
        Write (nout, 100) ferr(1:nrhs)
      Else
        Write (nout, *) 'A is not positive definite'
      End If

100   Format ((3X,1P,7E11.1))
    End Program
Full documentation of DPORFS


DPOTRF example

Computational Routines: Cholesky factorization of real symmetric positive-definite matrix

Data

DPOTRF Example Program Data
  4                           :Value of N
  'L'                         :Value of UPLO
  4.16
 -3.12   5.03
  0.56  -0.83   0.76
 -0.10   1.18   0.34   1.18   :End of matrix A

Result

 DPOTRF Example Program Results

 Factor
             1          2          3          4
 1      2.0396
 2     -1.5297     1.6401
 3      0.2746    -0.2500     0.7887
 4     -0.0490     0.6737     0.6617     0.5347

Source

    Program dpotrf_example

!     DPOTRF Example Program Text

!     Copyright 2017, Numerical Algorithms Group Ltd. http://www.nag.com

!     .. Use Statements ..
      Use lapack_example_aux, Only: nagf_file_print_matrix_real_gen
      Use lapack_interfaces, Only: dpotrf
      Use lapack_precision, Only: dp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter :: nin = 5, nout = 6
!     .. Local Scalars ..
      Integer :: i, ifail, info, lda, n
      Character (1) :: uplo
!     .. Local Arrays ..
      Real (Kind=dp), Allocatable :: a(:, :)
!     .. Executable Statements ..
      Write (nout, *) 'DPOTRF Example Program Results'
!     Skip heading in data file
      Read (nin, *)
      Read (nin, *) n
      lda = n
      Allocate (a(lda,n))

!     Read A from data file

      Read (nin, *) uplo
      If (uplo=='U') Then
        Read (nin, *)(a(i,i:n), i=1, n)
      Else If (uplo=='L') Then
        Read (nin, *)(a(i,1:i), i=1, n)
      End If

!     Factorize A
      Call dpotrf(uplo, n, a, lda, info)

      Write (nout, *)
      Flush (nout)
      If (info==0) Then

!       Print factor

!       ifail: behaviour on error exit
!              =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
        ifail = 0
        Call nagf_file_print_matrix_real_gen(uplo, 'Nonunit', n, n, a, lda, &
          'Factor', ifail)

      Else
        Write (nout, *) 'A is not positive definite'
      End If

    End Program
Full documentation of DPOTRF


DPOTRI example

Computational Routines: Inverse of real symmetric positive-definite matrix, matrix already factorized by DPOTRF

Data

DPOTRI Example Program Data
  4                           :Value of N
  'L'                         :Value of UPLO
  4.16
 -3.12   5.03
  0.56  -0.83   0.76
 -0.10   1.18   0.34   1.18   :End of matrix A

Result

 DPOTRI Example Program Results

 Inverse
             1          2          3          4
 1      0.6995
 2      0.7769     1.4239
 3      0.7508     1.8255     4.0688
 4     -0.9340    -1.8841    -2.9342     3.4978

Source

    Program dpotri_example

!     DPOTRI Example Program Text

!     Copyright 2017, Numerical Algorithms Group Ltd. http://www.nag.com

!     .. Use Statements ..
      Use lapack_example_aux, Only: nagf_file_print_matrix_real_gen
      Use lapack_interfaces, Only: dpotrf, dpotri
      Use lapack_precision, Only: dp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter :: nin = 5, nout = 6
!     .. Local Scalars ..
      Integer :: i, ifail, info, lda, n
      Character (1) :: uplo
!     .. Local Arrays ..
      Real (Kind=dp), Allocatable :: a(:, :)
!     .. Executable Statements ..
      Write (nout, *) 'DPOTRI Example Program Results'
!     Skip heading in data file
      Read (nin, *)
      Read (nin, *) n
      lda = n
      Allocate (a(lda,n))

!     Read A from data file

      Read (nin, *) uplo
      If (uplo=='U') Then
        Read (nin, *)(a(i,i:n), i=1, n)
      Else If (uplo=='L') Then
        Read (nin, *)(a(i,1:i), i=1, n)
      End If

!     Factorize A
      Call dpotrf(uplo, n, a, lda, info)

      Write (nout, *)
      Flush (nout)
      If (info==0) Then

!       Compute inverse of A
        Call dpotri(uplo, n, a, lda, info)

!       Print inverse

!       ifail: behaviour on error exit
!              =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
        ifail = 0
        Call nagf_file_print_matrix_real_gen(uplo, 'Nonunit', n, n, a, lda, &
          'Inverse', ifail)

      Else
        Write (nout, *) 'A is not positive definite'
      End If

    End Program
Full documentation of DPOTRI


DPOTRS example

Computational Routines: Solution of real symmetric positive-definite system of linear equations, multiple right-hand sides, matrix already factorized by DPOTRF

Data

DPOTRS Example Program Data
  4  2                        :Values of N and NRHS
  'L'                         :Value of UPLO
  4.16
 -3.12   5.03
  0.56  -0.83   0.76
 -0.10   1.18   0.34   1.18   :End of matrix A
  8.70   8.30
-13.35   2.13
  1.89   1.61
 -4.14   5.00                 :End of matrix B

Result

 DPOTRS Example Program Results

 Solution(s)
             1          2
 1      1.0000     4.0000
 2     -1.0000     3.0000
 3      2.0000     2.0000
 4     -3.0000     1.0000

Source

    Program dpotrs_example

!     DPOTRS Example Program Text

!     Copyright 2017, Numerical Algorithms Group Ltd. http://www.nag.com

!     .. Use Statements ..
      Use lapack_example_aux, Only: nagf_file_print_matrix_real_gen
      Use lapack_interfaces, Only: dpotrf, dpotrs
      Use lapack_precision, Only: dp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter :: nin = 5, nout = 6
!     .. Local Scalars ..
      Integer :: i, ifail, info, lda, ldb, n, nrhs
      Character (1) :: uplo
!     .. Local Arrays ..
      Real (Kind=dp), Allocatable :: a(:, :), b(:, :)
!     .. Executable Statements ..
      Write (nout, *) 'DPOTRS Example Program Results'
!     Skip heading in data file
      Read (nin, *)
      Read (nin, *) n, nrhs
      lda = n
      ldb = n
      Allocate (a(lda,n), b(ldb,nrhs))

!     Read A and B from data file

      Read (nin, *) uplo
      If (uplo=='U') Then
        Read (nin, *)(a(i,i:n), i=1, n)
      Else If (uplo=='L') Then
        Read (nin, *)(a(i,1:i), i=1, n)
      End If
      Read (nin, *)(b(i,1:nrhs), i=1, n)

!     Factorize A
      Call dpotrf(uplo, n, a, lda, info)

      Write (nout, *)
      Flush (nout)
      If (info==0) Then

!       Compute solution
        Call dpotrs(uplo, n, nrhs, a, lda, b, ldb, info)

!       Print solution

!       ifail: behaviour on error exit
!              =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
        ifail = 0
        Call nagf_file_print_matrix_real_gen('General', ' ', n, nrhs, b, ldb, &
          'Solution(s)', ifail)
      Else
        Write (nout, *) 'A is not positive definite'
      End If

    End Program
Full documentation of DPOTRS


DPPCON example

Computational Routines: Estimate condition number of real symmetric positive-definite matrix, matrix already factorized by DPPTRF, packed storage

Data

DPPCON Example Program Data
  4                           :Value of N
  'L'                         :Value of UPLO
  4.16
 -3.12   5.03
  0.56  -0.83   0.76
 -0.10   1.18   0.34   1.18   :End of matrix A

Result

 DPPCON Example Program Results

 Estimate of condition number =  9.73E+01

Source

    Program dppcon_example

!     DPPCON Example Program Text

!     Copyright 2017, Numerical Algorithms Group Ltd. http://www.nag.com

!     .. Use Statements ..
      Use lapack_interfaces, Only: dlansp, dppcon, dpptrf
      Use lapack_precision, Only: dp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=dp) :: anorm, rcond
      Integer :: i, info, j, n
      Character (1) :: uplo
!     .. Local Arrays ..
      Real (Kind=dp), Allocatable :: ap(:), work(:)
      Integer, Allocatable :: iwork(:)
!     .. Intrinsic Procedures ..
      Intrinsic :: epsilon
!     .. Executable Statements ..
      Write (nout, *) 'DPPCON Example Program Results'
!     Skip heading in data file
      Read (nin, *)
      Read (nin, *) n

      Allocate (ap(n*(n+1)/2), work(3*n), iwork(n))

!     Read A from data file

      Read (nin, *) uplo
      If (uplo=='U') Then
        Read (nin, *)((ap(i+j*(j-1)/2),j=i,n), i=1, n)
      Else If (uplo=='L') Then
        Read (nin, *)((ap(i+(2*n-j)*(j-1)/2),j=1,i), i=1, n)
      End If

!     Compute norm of A
      anorm = dlansp('1-norm', uplo, n, ap, work)

!     Factorize A
      Call dpptrf(uplo, n, ap, info)

      Write (nout, *)
      If (info==0) Then

!       Estimate condition number

        Call dppcon(uplo, n, ap, anorm, rcond, work, iwork, info)

        If (rcond>=epsilon(1.0E0_dp)) Then
          Write (nout, 100) 'Estimate of condition number =', 1.0_dp/rcond
        Else
          Write (nout, *) 'A is singular to working precision'
        End If
      Else
        Write (nout, *) 'A is not positive definite'
      End If

100   Format (1X, A, 1P, E10.2)
    End Program
Full documentation of DPPCON


DPPEQU example

Computational Routines: Computes row and column scalings intended to equilibrate a real symmetric positive-definite matrix and reduce its condition number, packed storage

Data

DPPEQU Example Program Data
  4                                         :Value of N
  4.16D+00  -3.12D+05   0.56D+00  -0.10D+00
             5.03D+10  -0.83D+05   1.18D+05
                        0.76D+00   0.34D+00
                                   1.18D+00 :End of matrix A

Result

 DPPEQU Example Program Results

 Matrix A
               1            2            3            4
 1    4.1600E+00  -3.1200E+05   5.6000E-01  -1.0000E-01
 2                 5.0300E+10  -8.3000E+04   1.1800E+05
 3                              7.6000E-01   3.4000E-01
 4                                           1.1800E+00

 SCOND = 3.9E-06, AMAX = 5.0E+10

 Diagonal scaling factors
     4.9E-01    4.5E-06    1.1E+00    9.2E-01

 Scaled matrix
             1          2          3          4
 1      1.0000    -0.6821     0.3149    -0.0451
 2                 1.0000    -0.4245     0.4843
 3                            1.0000     0.3590
 4                                       1.0000

Source

    Program dppequ_example

!     DPPEQU Example Program Text

!     Copyright 2017, Numerical Algorithms Group Ltd. http://www.nag.com

!     .. Use Statements ..
      Use blas_interfaces, Only: dscal
      Use lapack_example_aux, Only: nagf_blas_ddscl, &
        nagf_file_print_matrix_real_packed
      Use lapack_interfaces, Only: dppequ
      Use lapack_precision, Only: dp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Real (Kind=dp), Parameter :: one = 1.0_dp
      Real (Kind=dp), Parameter :: thresh = 0.1_dp
      Integer, Parameter :: nin = 5, nout = 6
      Character (1), Parameter :: uplo = 'U'
!     .. Local Scalars ..
      Real (Kind=dp) :: amax, big, scond, small
      Integer :: i, ifail, info, j, jinc, jj, n
!     .. Local Arrays ..
      Real (Kind=dp), Allocatable :: ap(:), s(:)
!     .. Intrinsic Procedures ..
      Intrinsic :: epsilon, radix, real, tiny
!     .. Executable Statements ..
      Write (nout, *) 'DPPEQU Example Program Results'
      Write (nout, *)
      Flush (nout)
!     Skip heading in data file
      Read (nin, *)
      Read (nin, *) n

      Allocate (ap((n*(n+1))/2), s(n))

!     Read the upper or lower triangular part of the matrix A from
!     data file

      If (uplo=='U') Then
        Read (nin, *)((ap(i+(j*(j-1))/2),j=i,n), i=1, n)
      Else If (uplo=='L') Then
        Read (nin, *)((ap(i+((2*n-j)*(j-1))/2),j=1,i), i=1, n)
      End If

!     Print the matrix A

!     ifail: behaviour on error exit
!             =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
      ifail = 0
      Call nagf_file_print_matrix_real_packed(uplo, 'Non-unit diagonal', n, &
        ap, 'Matrix A', ifail)

      Write (nout, *)

!     Compute diagonal scaling factors
      Call dppequ(uplo, n, ap, s, scond, amax, info)

      If (info>0) Then
        Write (nout, 100) 'Diagonal element', info, ' of A is non positive'
      Else

!       Print SCOND, AMAX and the scale factors

        Write (nout, 110) 'SCOND =', scond, ', AMAX =', amax
        Write (nout, *)
        Write (nout, *) 'Diagonal scaling factors'
        Write (nout, 120) s(1:n)
        Write (nout, *)
        Flush (nout)

!       Compute values close to underflow and overflow

        small = tiny(1.0E0_dp)/(epsilon(1.0E0_dp)*real(radix(1.0E0_dp),kind=dp &
          ))
        big = one/small
        If ((scond<thresh) .Or. (amax<small) .Or. (amax>big)) Then

!         Scale A

          If (uplo=='U') Then
            jj = 1
            Do j = 1, n
              Call dscal(j, s(j), ap(jj), 1)
              Call nagf_blas_ddscl(j, s, 1, ap(jj), 1)
              jj = jj + j
            End Do
          Else If (uplo=='L') Then
            jj = 1
            jinc = n
            Do j = 1, n
              Call dscal(jinc, s(j), ap(jj), 1)
              Call nagf_blas_ddscl(jinc, s(j), 1, ap(jj), 1)
              jj = jj + jinc
              jinc = jinc - 1
            End Do
          End If

!         Print the scaled matrix

          ifail = 0
          Call nagf_file_print_matrix_real_packed(uplo, 'Non-unit diagonal', &
            n, ap, 'Scaled matrix', ifail)

        End If
      End If

100   Format (1X, A, I4, A)
110   Format (1X, 2(A,1P,E8.1))
120   Format ((1X,1P,7E11.1))
    End Program
Full documentation of DPPEQU


DPPRFS example

Computational Routines: Refined solution with error bounds of real symmetric positive-definite system of linear equations, multiple right-hand sides, packed storage

Data

DPPRFS Example Program Data
  4  2                        :Values of N and NRHS
  'L'                         :Value of UPLO
  4.16
 -3.12   5.03
  0.56  -0.83   0.76
 -0.10   1.18   0.34   1.18   :End of matrix A
  8.70   8.30
-13.35   2.13
  1.89   1.61
 -4.14   5.00                 :End of matrix B

Result

 DPPRFS Example Program Results

 Solution(s)
             1          2
 1      1.0000     4.0000
 2     -1.0000     3.0000
 3      2.0000     2.0000
 4     -3.0000     1.0000

 Backward errors (machine-dependent)
       5.1E-17    6.1E-17
 Estimated forward error bounds (machine-dependent)
       2.3E-14    2.3E-14

Source

    Program dpprfs_example

!     DPPRFS Example Program Text

!     Copyright 2017, Numerical Algorithms Group Ltd. http://www.nag.com

!     .. Use Statements ..
      Use lapack_example_aux, Only: nagf_file_print_matrix_real_gen
      Use lapack_interfaces, Only: dpprfs, dpptrf, dpptrs
      Use lapack_precision, Only: dp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter :: nin = 5, nout = 6
!     .. Local Scalars ..
      Integer :: aplen, i, ifail, info, j, ldb, ldx, n, nrhs
      Character (1) :: uplo
!     .. Local Arrays ..
      Real (Kind=dp), Allocatable :: afp(:), ap(:), b(:, :), berr(:), ferr(:), &
        work(:), x(:, :)
      Integer, Allocatable :: iwork(:)
!     .. Executable Statements ..
      Write (nout, *) 'DPPRFS Example Program Results'
!     Skip heading in data file
      Read (nin, *)
      Read (nin, *) n, nrhs
      ldb = n
      ldx = n
      aplen = n*(n+1)/2
      Allocate (afp(aplen), ap(aplen), b(ldb,nrhs), berr(nrhs), ferr(nrhs), &
        work(3*n), x(ldx,n), iwork(n))

!     Read A and B from data file, and copy A to AFP and B to X

      Read (nin, *) uplo
      If (uplo=='U') Then
        Read (nin, *)((ap(i+j*(j-1)/2),j=i,n), i=1, n)
      Else If (uplo=='L') Then
        Read (nin, *)((ap(i+(2*n-j)*(j-1)/2),j=1,i), i=1, n)
      End If
      Read (nin, *)(b(i,1:nrhs), i=1, n)

      afp(1:aplen) = ap(1:aplen)
      x(1:n, 1:nrhs) = b(1:n, 1:nrhs)

!     Factorize A in the array AFP
      Call dpptrf(uplo, n, afp, info)

      Write (nout, *)
      Flush (nout)
      If (info==0) Then

!       Compute solution in the array X
        Call dpptrs(uplo, n, nrhs, afp, x, ldx, info)

!       Improve solution, and compute backward errors and
!       estimated bounds on the forward errors

        Call dpprfs(uplo, n, nrhs, ap, afp, b, ldb, x, ldx, ferr, berr, work, &
          iwork, info)

!       Print solution

!       ifail: behaviour on error exit
!              =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
        ifail = 0
        Call nagf_file_print_matrix_real_gen('General', ' ', n, nrhs, x, ldx, &
          'Solution(s)', ifail)

        Write (nout, *)
        Write (nout, *) 'Backward errors (machine-dependent)'
        Write (nout, 100) berr(1:nrhs)
        Write (nout, *) 'Estimated forward error bounds (machine-dependent)'
        Write (nout, 100) ferr(1:nrhs)
      Else
        Write (nout, *) 'A is not positive definite'
      End If

100   Format ((3X,1P,7E11.1))
    End Program
Full documentation of DPPRFS


DPPTRF example

Computational Routines: Cholesky factorization of real symmetric positive-definite matrix, packed storage

Data

DPPTRF Example Program Data
  4                           :Value of N
  'L'                         :Value of UPLO
  4.16
 -3.12   5.03
  0.56  -0.83   0.76
 -0.10   1.18   0.34   1.18   :End of matrix A

Result

 DPPTRF Example Program Results

 Factor
             1          2          3          4
 1      2.0396
 2     -1.5297     1.6401
 3      0.2746    -0.2500     0.7887
 4     -0.0490     0.6737     0.6617     0.5347

Source

    Program dpptrf_example

!     DPPTRF Example Program Text

!     Copyright 2017, Numerical Algorithms Group Ltd. http://www.nag.com

!     .. Use Statements ..
      Use lapack_example_aux, Only: nagf_file_print_matrix_real_packed
      Use lapack_interfaces, Only: dpptrf
      Use lapack_precision, Only: dp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter :: nin = 5, nout = 6
!     .. Local Scalars ..
      Integer :: i, ifail, info, j, n
      Character (1) :: uplo
!     .. Local Arrays ..
      Real (Kind=dp), Allocatable :: ap(:)
!     .. Executable Statements ..
      Write (nout, *) 'DPPTRF Example Program Results'
!     Skip heading in data file
      Read (nin, *)
      Read (nin, *) n

      Allocate (ap(n*(n+1)/2))

!     Read A from data file

      Read (nin, *) uplo
      If (uplo=='U') Then
        Read (nin, *)((ap(i+j*(j-1)/2),j=i,n), i=1, n)
      Else If (uplo=='L') Then
        Read (nin, *)((ap(i+(2*n-j)*(j-1)/2),j=1,i), i=1, n)
      End If

!     Factorize A
      Call dpptrf(uplo, n, ap, info)

      Write (nout, *)
      Flush (nout)
      If (info==0) Then

!       Print factor

!       ifail: behaviour on error exit
!              =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
        ifail = 0
        Call nagf_file_print_matrix_real_packed(uplo, 'Nonunit', n, ap, &
          'Factor', ifail)

      Else
        Write (nout, *) 'A is not positive definite'
      End If

    End Program
Full documentation of DPPTRF


DPPTRI example

Computational Routines: Inverse of real symmetric positive-definite matrix, matrix already factorized by DPPTRF, packed storage

Data

DPPTRI Example Program Data
  4                           :Value of N
  'L'                         :Value of UPLO
  4.16
 -3.12   5.03
  0.56  -0.83   0.76
 -0.10   1.18   0.34   1.18   :End of matrix A

Result

 DPPTRI Example Program Results

 Inverse
             1          2          3          4
 1      0.6995
 2      0.7769     1.4239
 3      0.7508     1.8255     4.0688
 4     -0.9340    -1.8841    -2.9342     3.4978

Source

    Program dpptri_example

!     DPPTRI Example Program Text

!     Copyright 2017, Numerical Algorithms Group Ltd. http://www.nag.com

!     .. Use Statements ..
      Use lapack_example_aux, Only: nagf_file_print_matrix_real_packed
      Use lapack_interfaces, Only: dpptrf, dpptri
      Use lapack_precision, Only: dp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter :: nin = 5, nout = 6
!     .. Local Scalars ..
      Integer :: i, ifail, info, j, n
      Character (1) :: uplo
!     .. Local Arrays ..
      Real (Kind=dp), Allocatable :: ap(:)
!     .. Executable Statements ..
      Write (nout, *) 'DPPTRI Example Program Results'
!     Skip heading in data file
      Read (nin, *)
      Read (nin, *) n

      Allocate (ap(n*(n+1)/2))

!     Read A from data file

      Read (nin, *) uplo
      If (uplo=='U') Then
        Read (nin, *)((ap(i+j*(j-1)/2),j=i,n), i=1, n)
      Else If (uplo=='L') Then
        Read (nin, *)((ap(i+(2*n-j)*(j-1)/2),j=1,i), i=1, n)
      End If

!     Factorize A
      Call dpptrf(uplo, n, ap, info)

      Write (nout, *)
      Flush (nout)
      If (info==0) Then

!       Compute inverse of A
        Call dpptri(uplo, n, ap, info)

!       Print inverse

!       ifail: behaviour on error exit
!              =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
        ifail = 0
        Call nagf_file_print_matrix_real_packed(uplo, 'Nonunit', n, ap, &
          'Inverse', ifail)

      Else
        Write (nout, *) 'A is not positive definite'
      End If

    End Program
Full documentation of DPPTRI


DPPTRS example

Computational Routines: Solution of real symmetric positive-definite system of linear equations, multiple right-hand sides, matrix already factorized by DPPTRF, packed storage

Data

DPPTRS Example Program Data
  4  2                        :Values of N and NRHS
  'L'                         :Value of UPLO
  4.16
 -3.12   5.03
  0.56  -0.83   0.76
 -0.10   1.18   0.34   1.18   :End of matrix A
  8.70   8.30
-13.35   2.13
  1.89   1.61
 -4.14   5.00                 :End of matrix B

Result

 DPPTRS Example Program Results

 Solution(s)
             1          2
 1      1.0000     4.0000
 2     -1.0000     3.0000
 3      2.0000     2.0000
 4     -3.0000     1.0000

Source

    Program dpptrs_example

!     DPPTRS Example Program Text

!     Copyright 2017, Numerical Algorithms Group Ltd. http://www.nag.com

!     .. Use Statements ..
      Use lapack_example_aux, Only: nagf_file_print_matrix_real_gen
      Use lapack_interfaces, Only: dpptrf, dpptrs
      Use lapack_precision, Only: dp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter :: nin = 5, nout = 6
!     .. Local Scalars ..
      Integer :: i, ifail, info, j, ldb, n, nrhs
      Character (1) :: uplo
!     .. Local Arrays ..
      Real (Kind=dp), Allocatable :: ap(:), b(:, :)
!     .. Executable Statements ..
      Write (nout, *) 'DPPTRS Example Program Results'
!     Skip heading in data file
      Read (nin, *)
      Read (nin, *) n, nrhs
      ldb = n
      Allocate (ap(n*(n+1)/2), b(ldb,nrhs))

!     Read A and B from data file

      Read (nin, *) uplo
      If (uplo=='U') Then
        Read (nin, *)((ap(i+j*(j-1)/2),j=i,n), i=1, n)
      Else If (uplo=='L') Then
        Read (nin, *)((ap(i+(2*n-j)*(j-1)/2),j=1,i), i=1, n)
      End If
      Read (nin, *)(b(i,1:nrhs), i=1, n)

!     Factorize A
      Call dpptrf(uplo, n, ap, info)

      Write (nout, *)
      Flush (nout)
      If (info==0) Then

!       Compute solution
        Call dpptrs(uplo, n, nrhs, ap, b, ldb, info)

!       Print solution

!       ifail: behaviour on error exit
!              =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
        ifail = 0
        Call nagf_file_print_matrix_real_gen('General', ' ', n, nrhs, b, ldb, &
          'Solution(s)', ifail)

      Else
        Write (nout, *) 'A is not positive definite'
      End If

    End Program
Full documentation of DPPTRS


DPSTRF example

Computational Routines: Cholesky factorization of real symmetric positive semidefinite matrix

Data

DPSTRF Example Program Data
  5 'L'                               : n, uplo
  2.51
  4.04   8.22
  3.34   7.38   7.06
  1.34   2.68   2.24   0.96
  1.29   2.44   2.14   0.80   0.74    : End of matrix A

Result

 DPSTRF Example Program Results

 Computed rank:   3

 Factor
             1          2          3          4          5
 1      2.8671
 2      1.4091     0.7242
 3      2.5741    -0.3965     0.5262
 4      0.9348     0.0315    -0.2920     0.0000
 5      0.8510     0.1254    -0.0018     0.0000     0.0000

 PIV
             2          1          3          4          5

Source

    Program dpstrf_example

!     DPSTRF Example Program Text

!     Copyright 2017, Numerical Algorithms Group Ltd. http://www.nag.com

!     .. Use Statements ..
      Use lapack_example_aux, Only: nagf_file_print_matrix_integer_comp, &
        nagf_file_print_matrix_real_gen
      Use lapack_interfaces, Only: dpstrf
      Use lapack_precision, Only: dp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Real (Kind=dp), Parameter :: zero = 0.0E0_dp
      Integer, Parameter :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=dp) :: tol
      Integer :: i, ifail, info, j, lda, n, rank
      Character (1) :: uplo
!     .. Local Arrays ..
      Real (Kind=dp), Allocatable :: a(:, :), work(:)
      Integer, Allocatable :: piv(:)
      Character (1) :: clabs(1), rlabs(1)
!     .. Executable Statements ..
      Write (nout, *) 'DPSTRF Example Program Results'
!     Skip heading in data file
      Read (nin, *)
      Read (nin, *) n, uplo
      lda = n
      Allocate (a(lda,n), piv(n), work(2*n))

!     Read A from data file
      If (uplo=='U') Then
        Read (nin, *)(a(i,i:n), i=1, n)
      Else If (uplo=='L') Then
        Read (nin, *)(a(i,1:i), i=1, n)
      End If
      tol = -1.0_dp

!     Factorize A
      Call dpstrf(uplo, n, a, lda, piv, rank, tol, work, info)

!     Zero out columns rank+1 to n
      If (uplo=='U') Then
        Do j = rank + 1, n
          a(rank+1:j, j) = zero
        End Do
      Else If (uplo=='L') Then
        Do j = rank + 1, n
          a(j:n, j) = zero
        End Do
      End If

!     Print rank
      Write (nout, *)
      Write (nout, '(1X,A15,I3)') 'Computed rank: ', rank

!     Print factor
      Write (nout, *)
      Flush (nout)
      ifail = 0
      Call nagf_file_print_matrix_real_gen(uplo, 'Nonunit', n, n, a, lda, &
        'Factor', ifail)

!     Print pivot indices
      Write (nout, *)
      Write (nout, *) 'PIV'
      Flush (nout)

      ifail = 0
      Call nagf_file_print_matrix_integer_comp('General', 'Non-unit', 1, n, &
        piv, 1, 'I11', ' ', 'No', rlabs, 'No', clabs, 80, 1, ifail)

    End Program
Full documentation of DPSTRF


DPTCON example

Computational Routines: Computes the reciprocal of the condition number of a real symmetric positive-definite tridiagonal system using the L * D * L' factorization computed by DPTTRF

Data

DPTCON Example Program Data
  5                           :Value of N
  4.0  10.0  29.0  25.0   5.0 :End of diagonal D
 -2.0  -6.0  15.0   8.0       :End of sub-diagonal E

Result

 DPTCON Example Program Results

 Estimate of condition number =   1.05E+02

Source

    Program dptcon_example

!     DPTCON Example Program Text

!     Copyright 2017, Numerical Algorithms Group Ltd. http://www.nag.com

!     .. Use Statements ..
      Use lapack_interfaces, Only: dlanst, dptcon, dpttrf
      Use lapack_precision, Only: dp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=dp) :: anorm, rcond
      Integer :: info, n
!     .. Local Arrays ..
      Real (Kind=dp), Allocatable :: d(:), e(:), work(:)
!     .. Intrinsic Procedures ..
      Intrinsic :: epsilon
!     .. Executable Statements ..
      Write (nout, *) 'DPTCON Example Program Results'
      Write (nout, *)
!     Skip heading in data file
      Read (nin, *)
      Read (nin, *) n

      Allocate (d(n), e(n-1), work(n))

!     Read the lower bidiagonal part of the tridiagonal matrix A from
!     data file

      Read (nin, *) d(1:n)
      Read (nin, *) e(1:n-1)

!     Compute the 1-norm of A
      anorm = dlanst('1-norm', n, d, e)

!     Factorize the tridiagonal matrix A
      Call dpttrf(n, d, e, info)

      If (info==0) Then

!       Estimate the condition number of A
        Call dptcon(n, d, e, anorm, rcond, work, info)

!       Print the estimated condition number

        If (rcond>=epsilon(1.0E0_dp)) Then
          Write (nout, 100) 'Estimate of condition number = ', 1.0_dp/rcond
        Else
          Write (nout, 100) 'A is singular to working precision. RCOND = ', &
            rcond
        End If

      Else
        Write (nout, 110) 'The leading minor of order ', info, &
          ' is not positive definite'
      End If

100   Format (1X, A, 1P, E10.2)
110   Format (1X, A, I3, A)
    End Program
Full documentation of DPTCON


DPTEQR example

Computational Routines: All eigenvalues and eigenvectors of real symmetric positive-definite tridiagonal matrix, reduced from real symmetric positive-definite matrix

Data

DPTEQR Example Program Data
  4                           :Value of N
  4.16   5.25   1.09   0.62
  3.17  -0.97   0.55          :End of matrix T

Result

 DPTEQR Example Program Results

 Eigenvalues
     8.0023  1.9926  1.0014  0.1237

 Eigenvectors
          1       2       3       4
 1   0.6326  0.6245 -0.4191  0.1847
 2   0.7668 -0.4270  0.4176 -0.2352
 3  -0.1082  0.6071  0.4594 -0.6393
 4  -0.0081  0.2432  0.6625  0.7084

Source

    Program dpteqr_example

!     DPTEQR Example Program Text

!     Copyright 2017, Numerical Algorithms Group Ltd. http://www.nag.com

!     .. Use Statements ..
      Use lapack_example_aux, Only: nagf_blas_damax_val, &
        nagf_file_print_matrix_real_gen
      Use lapack_interfaces, Only: dpteqr
      Use lapack_precision, Only: dp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Real (Kind=dp), Parameter :: zero = 0.0_dp
      Integer, Parameter :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=dp) :: r
      Integer :: i, ifail, info, k, ldz, n
!     .. Local Arrays ..
      Real (Kind=dp), Allocatable :: d(:), e(:), work(:), z(:, :)
!     .. Executable Statements ..
      Write (nout, *) 'DPTEQR Example Program Results'
!     Skip heading in data file
      Read (nin, *)
      Read (nin, *) n
      ldz = n
      Allocate (d(n), e(n-1), work(4*n), z(ldz,n))

!     Read T from data file

      Read (nin, *) d(1:n)
      Read (nin, *) e(1:n-1)

!     Calculate all the eigenvalues and eigenvectors of T
      Call dpteqr('I', n, d, e, z, ldz, work, info)

      Write (nout, *)
      If (info>0 .And. info<=n) Then
        Write (nout, *) 'T is not positive definite.'
      Else If (info>n) Then
        Write (nout, *) 'Failure to converge.'
      Else

!       Print eigenvalues and eigenvectors

        Write (nout, *) 'Eigenvalues'
        Write (nout, 100) d(1:n)
        Write (nout, *)
        Flush (nout)

!       Normalize the eigenvectors, largest positive
        Do i = 1, n
          Call nagf_blas_damax_val(n, z(1,i), 1, k, r)
          If (z(k,i)<zero) Then
            z(1:n, i) = -z(1:n, i)
          End If
        End Do

!       ifail: behaviour on error exit
!              =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
        ifail = 0
        Call nagf_file_print_matrix_real_gen('General', ' ', n, n, z, ldz, &
          'Eigenvectors', ifail)

      End If

100   Format (3X, (8F8.4))
    End Program
Full documentation of DPTEQR


DPTRFS example

Computational Routines: Refined solution with error bounds of real symmetric positive-definite tridiagonal system of linear equations, multiple right-hand sides

Data

DPTRFS Example Program Data
  5     2                     :Values of N and NRHS
  4.0  10.0  29.0  25.0   5.0 :End of diagonal D
 -2.0  -6.0  15.0   8.0       :End of super-diagonal E
  6.0  10.0
  9.0   4.0
  2.0   9.0
 14.0  65.0
  7.0  23.0                   :End of matrix B

Result

 DPTRFS Example Program Results

 Solution(s)
             1          2
 1      2.5000     2.0000
 2      2.0000    -1.0000
 3      1.0000    -3.0000
 4     -1.0000     6.0000
 5      3.0000    -5.0000

 Backward errors (machine-dependent)
       0.0E+00    7.4E-17

 Estimated forward error bounds (machine-dependent)
       2.4E-14    4.7E-14

Source

    Program dptrfs_example

!     DPTRFS Example Program Text

!     Copyright 2017, Numerical Algorithms Group Ltd. http://www.nag.com

!     .. Use Statements ..
      Use lapack_example_aux, Only: nagf_file_print_matrix_real_gen
      Use lapack_interfaces, Only: dptrfs, dpttrf, dpttrs
      Use lapack_precision, Only: dp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter :: nin = 5, nout = 6
!     .. Local Scalars ..
      Integer :: i, ifail, info, ldb, ldx, n, nrhs
!     .. Local Arrays ..
      Real (Kind=dp), Allocatable :: b(:, :), berr(:), d(:), df(:), e(:), &
        ef(:), ferr(:), work(:), x(:, :)
!     .. Executable Statements ..
      Write (nout, *) 'DPTRFS Example Program Results'
      Write (nout, *)
      Flush (nout)
!     Skip heading in data file
      Read (nin, *)
      Read (nin, *) n, nrhs
      ldb = n
      ldx = n
      Allocate (b(ldb,nrhs), berr(nrhs), d(n), df(n), e(n-1), ef(n-1), &
        ferr(nrhs), work(2*n), x(ldx,nrhs))

!     Read the lower bidiagonal part of the tridiagonal matrix A from
!     data file

      Read (nin, *) d(1:n)
      Read (nin, *) e(1:n-1)

!     Read the right hand matrix B

      Read (nin, *)(b(i,1:nrhs), i=1, n)

!     Copy A into DF and EF, and copy B into X

      df(1:n) = d(1:n)
      ef(1:n-1) = e(1:n-1)
      x(1:n, 1:nrhs) = b(1:n, 1:nrhs)

!     Factorize the copy of the tridiagonal matrix A
      Call dpttrf(n, df, ef, info)

      If (info==0) Then

!       Solve the equations AX = B
        Call dpttrs(n, nrhs, df, ef, x, ldx, info)

!       Improve the solution and compute error estimates
        Call dptrfs(n, nrhs, d, e, df, ef, b, ldb, x, ldx, ferr, berr, work, &
          info)

!       Print the solution and the forward and backward error
!       estimates

!       ifail: behaviour on error exit
!              =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
        ifail = 0
        Call nagf_file_print_matrix_real_gen('General', ' ', n, nrhs, x, ldx, &
          'Solution(s)', ifail)

        Write (nout, *)
        Write (nout, *) 'Backward errors (machine-dependent)'
        Write (nout, 100) berr(1:nrhs)
        Write (nout, *)
        Write (nout, *) 'Estimated forward error bounds (machine-dependent)'
        Write (nout, 100) ferr(1:nrhs)
      Else
        Write (nout, 110) 'The leading minor of order ', info, &
          ' is not positive definite'
      End If

100   Format ((3X,1P,7E11.1))
110   Format (1X, A, I3, A)
    End Program
Full documentation of DPTRFS


DPTTRF example

Computational Routines: Computes the L * D * L' factorization of a real symmetric positive-definite tridiagonal matrix

Data

DPTTRF Example Program Data
  5                           :Value of N
  4.0  10.0  29.0  25.0   5.0 :End of diagonal D
 -2.0  -6.0  15.0   8.0       :End of sub-diagonal E

Result

 DPTTRF Example Program Results

 Details of factorization

  The diagonal elements of D
    4.0000   9.0000  25.0000  16.0000   1.0000

  Subdiagonal elements of the Cholesky factor L
   -0.5000  -0.6667   0.6000   0.5000

Source

    Program dpttrf_example

!     DPTTRF Example Program Text

!     Copyright 2017, Numerical Algorithms Group Ltd. http://www.nag.com

!     .. Use Statements ..
      Use lapack_interfaces, Only: dpttrf
      Use lapack_precision, Only: dp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter :: nin = 5, nout = 6
!     .. Local Scalars ..
      Integer :: info, n
!     .. Local Arrays ..
      Real (Kind=dp), Allocatable :: d(:), e(:)
!     .. Executable Statements ..
      Write (nout, *) 'DPTTRF Example Program Results'
      Write (nout, *)
!     Skip heading in data file
      Read (nin, *)
      Read (nin, *) n

      Allocate (d(n), e(n-1))

!     Read the lower bidiagonal part of the tridiagonal matrix A from
!     data file

      Read (nin, *) d(1:n)
      Read (nin, *) e(1:n-1)

!     Factorize the tridiagonal matrix A

      Call dpttrf(n, d, e, info)

      If (info>0) Then
        Write (nout, 100) 'The leading minor of order ', info, &
          ' is not positive definite'
      End If

!     Print details of the factorization

      Write (nout, *) 'Details of factorization'
      Write (nout, *)
      Write (nout, *) ' The diagonal elements of D'
      Write (nout, 110) d(1:n)
      Write (nout, *)
      Write (nout, *) ' Subdiagonal elements of the Cholesky factor L'
      Write (nout, 110) e(1:n-1)

100   Format (1X, A, I3, A)
110   Format (1X, 8F9.4)
    End Program
Full documentation of DPTTRF


DPTTRS example

Computational Routines: Solves a real symmetric positive-definite tridiagonal system using the L * D * L' factorization computed by DPTTRF

Data

DPTTRS Example Program Data
  5     2                     :Values of N and NRHS
       -2.0  -6.0  15.0   8.0 :End of super-diagonal E
  4.0  10.0  29.0  25.0   5.0 :End of diagonal D
  6.0  10.0
  9.0   4.0
  2.0   9.0
 14.0  65.0
  7.0  23.0                   :End of matrix B

Result

 DPTTRS Example Program Results

 Solution(s)
             1          2
 1      2.5000     2.0000
 2      2.0000    -1.0000
 3      1.0000    -3.0000
 4     -1.0000     6.0000
 5      3.0000    -5.0000

Source

    Program dpttrs_example

!     DPTTRS Example Program Text

!     Copyright 2017, Numerical Algorithms Group Ltd. http://www.nag.com

!     .. Use Statements ..
      Use lapack_example_aux, Only: nagf_file_print_matrix_real_gen
      Use lapack_interfaces, Only: dpttrf, dpttrs
      Use lapack_precision, Only: dp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter :: nin = 5, nout = 6
!     .. Local Scalars ..
      Integer :: i, ifail, info, ldb, n, nrhs
!     .. Local Arrays ..
      Real (Kind=dp), Allocatable :: b(:, :), d(:), e(:)
!     .. Executable Statements ..
      Write (nout, *) 'DPTTRS Example Program Results'
      Write (nout, *)
      Flush (nout)
!     Skip heading in data file
      Read (nin, *)
      Read (nin, *) n, nrhs
      ldb = n
      Allocate (b(ldb,nrhs), d(n), e(n-1))

!     Read the upper bidiagonal part of the tridiagonal matrix A from
!     data file

      Read (nin, *) e(1:n-1)
      Read (nin, *) d(1:n)

!     Read the right hand matrix B

      Read (nin, *)(b(i,1:nrhs), i=1, n)

!     Factorize the tridiagonal matrix A
      Call dpttrf(n, d, e, info)

      If (info==0) Then

!       Solve the equations AX = B
        Call dpttrs(n, nrhs, d, e, b, ldb, info)

!       Print the solution

!       ifail: behaviour on error exit
!              =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
        ifail = 0
        Call nagf_file_print_matrix_real_gen('General', ' ', n, nrhs, b, ldb, &
          'Solution(s)', ifail)

      Else
        Write (nout, 100) 'The leading minor of order ', info, &
          ' is not positive definite'
      End If

100   Format (1X, A, I3, A)
    End Program
Full documentation of DPTTRS


DSBGST example

Computational Routines: Reduction of real symmetric-definite banded generalized eigenproblem Ax = lambda Bx to standard form Cy = lambda y, such that C has the same bandwidth as A

Data

DSBGST Example Program Data
  4  2  1                     :Values of N, KA and KB
  'L'                         :Value of UPLO
  0.24
  0.39  -0.11
  0.42   0.79  -0.25
         0.63   0.48  -0.03   :End of matrix A
  2.07
  0.95   1.69
        -0.29   0.65
               -0.33   1.17   :End of matrix B

Result

 DSBGST Example Program Results

 Eigenvalues
    -0.8305 -0.6401  0.0992  1.8525

Source

    Program dsbgst_example

!     DSBGST Example Program Text

!     Copyright 2017, Numerical Algorithms Group Ltd. http://www.nag.com

!     .. Use Statements ..
      Use lapack_interfaces, Only: dpbstf, dsbgst, dsbtrd, dsterf
      Use lapack_precision, Only: dp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter :: nin = 5, nout = 6
!     .. Local Scalars ..
      Integer :: i, info, j, ka, kb, ldab, ldbb, ldx, n
      Character (1) :: uplo
!     .. Local Arrays ..
      Real (Kind=dp), Allocatable :: ab(:, :), bb(:, :), d(:), e(:), work(:), &
        x(:, :)
!     .. Intrinsic Procedures ..
      Intrinsic :: max, min
!     .. Executable Statements ..
      Write (nout, *) 'DSBGST Example Program Results'
!     Skip heading in data file
      Read (nin, *)
      Read (nin, *) n, ka, kb
      ldab = ka + 1
      ldbb = kb + 1
      ldx = n
      Allocate (ab(ldab,n), bb(ldbb,n), d(n), e(n-1), work(2*n), x(ldx,n))

!     Read A and B from data file

      Read (nin, *) uplo
      If (uplo=='U') Then
        Do i = 1, n
          Read (nin, *)(ab(ka+1+i-j,j), j=i, min(n,i+ka))
        End Do
        Do i = 1, n
          Read (nin, *)(bb(kb+1+i-j,j), j=i, min(n,i+kb))
        End Do
      Else If (uplo=='L') Then
        Do i = 1, n
          Read (nin, *)(ab(1+i-j,j), j=max(1,i-ka), i)
        End Do
        Do i = 1, n
          Read (nin, *)(bb(1+i-j,j), j=max(1,i-kb), i)
        End Do
      End If

!     Compute the split Cholesky factorization of B
      Call dpbstf(uplo, n, kb, bb, ldbb, info)

      Write (nout, *)
      If (info>0) Then
        Write (nout, *) 'B is not positive definite.'
      Else

!       Reduce the problem to standard form C*y = lambda*y, storing
!       the result in A
        Call dsbgst('N', uplo, n, ka, kb, ab, ldab, bb, ldbb, x, ldx, work, &
          info)

!       Reduce C to tridiagonal form T = (Q**T)*C*Q
        Call dsbtrd('N', uplo, n, ka, ab, ldab, d, e, x, ldx, work, info)

!       Calculate the eigenvalues of T (same as C)
        Call dsterf(n, d, e, info)

        If (info>0) Then
          Write (nout, *) 'Failure to converge.'
        Else

!         Print eigenvalues

          Write (nout, *) 'Eigenvalues'
          Write (nout, 100) d(1:n)
        End If
      End If

100   Format (3X, (8F8.4))
    End Program
Full documentation of DSBGST


DSBTRD example

Computational Routines: Orthogonal reduction of real symmetric band matrix to symmetric tridiagonal form

Data

DSBTRD Example Program Data
  4  2                        :Values of N and KD
  'L'                         :Value of UPLO
  4.99
  0.04   1.05
  0.22  -0.79  -2.31
         1.04  -1.30  -0.43   :End of matrix A

Result

 DSBTRD Example Program Results

 Eigenvalues
    -2.9943 -0.7000  1.9974  4.9969

 Eigenvectors
          1       2       3       4
 1   0.0251  0.0162  0.0113  0.9995
 2  -0.0656 -0.5859  0.8077  0.0020
 3  -0.9002 -0.3135 -0.3006  0.0311
 4  -0.4298  0.7471  0.5070 -0.0071

Source

    Program dsbtrd_example

!     DSBTRD Example Program Text

!     Copyright 2017, Numerical Algorithms Group Ltd. http://www.nag.com

!     .. Use Statements ..
      Use lapack_example_aux, Only: nagf_file_print_matrix_real_gen
      Use lapack_interfaces, Only: dsbtrd, dsteqr
      Use lapack_precision, Only: dp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter :: nin = 5, nout = 6
!     .. Local Scalars ..
      Integer :: i, ifail, info, j, kd, ldab, ldq, n
      Character (1) :: uplo
!     .. Local Arrays ..
      Real (Kind=dp), Allocatable :: ab(:, :), d(:), e(:), q(:, :), work(:)
!     .. Intrinsic Procedures ..
      Intrinsic :: max, min
!     .. Executable Statements ..
      Write (nout, *) 'DSBTRD Example Program Results'
!     Skip heading in data file
      Read (nin, *)
      Read (nin, *) n, kd
      ldab = kd + 1
      ldq = n
      Allocate (ab(ldab,n), d(n), e(n-1), q(ldq,n), work(2*n-2))

!     Read A from data file

      Read (nin, *) uplo
      If (uplo=='U') Then
        Do i = 1, n
          Read (nin, *)(ab(kd+1+i-j,j), j=i, min(n,i+kd))
        End Do
      Else If (uplo=='L') Then
        Do i = 1, n
          Read (nin, *)(ab(1+i-j,j), j=max(1,i-kd), i)
        End Do
      End If

!     Reduce A to tridiagonal form T = (Q**T)*A*Q (and form Q)
      Call dsbtrd('V', uplo, n, kd, ab, ldab, d, e, q, ldq, work, info)

!     Calculate all the eigenvalues and eigenvectors of A
      Call dsteqr('V', n, d, e, q, ldq, work, info)

      Write (nout, *)
      If (info>0) Then
        Write (nout, *) 'Failure to converge.'
      Else

!       Print eigenvalues and eigenvectors

        Write (nout, *) 'Eigenvalues'
        Write (nout, 100) d(1:n)
        Write (nout, *)
        Flush (nout)

!       Standardize the eigenvectors so that first elements are non-negative.
        Do i = 1, n
          If (q(1,i)<0.0_dp) Then
            q(1:n, i) = -q(1:n, i)
          End If
        End Do

!       ifail: behaviour on error exit
!              =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
        ifail = 0
        Call nagf_file_print_matrix_real_gen('General', ' ', n, n, q, ldq, &
          'Eigenvectors', ifail)

      End If

100   Format (3X, (8F8.4))
    End Program
Full documentation of DSBTRD


DSPCON example

Computational Routines: Estimate condition number of real symmetric indefinite matrix, matrix already factorized by DSPTRF, packed storage

Data

DSPCON Example Program Data
  4                           :Value of N
  'L'                         :Value of UPLO
  2.07
  3.87  -0.21
  4.20   1.87   1.15
 -1.15   0.63   2.06  -1.81   :End of matrix A

Result

 DSPCON Example Program Results

 Estimate of condition number =  7.57E+01

Source

    Program dspcon_example

!     DSPCON Example Program Text

!     Copyright 2017, Numerical Algorithms Group Ltd. http://www.nag.com

!     .. Use Statements ..
      Use lapack_interfaces, Only: dlansp, dspcon, dsptrf
      Use lapack_precision, Only: dp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=dp) :: anorm, rcond
      Integer :: i, info, j, n
      Character (1) :: uplo
!     .. Local Arrays ..
      Real (Kind=dp), Allocatable :: ap(:), work(:)
      Integer, Allocatable :: ipiv(:), iwork(:)
!     .. Intrinsic Procedures ..
      Intrinsic :: epsilon
!     .. Executable Statements ..
      Write (nout, *) 'DSPCON Example Program Results'
!     Skip heading in data file
      Read (nin, *)
      Read (nin, *) n

      Allocate (ap(n*(n+1)/2), work(2*n), ipiv(n), iwork(n))

!     Read A from data file

      Read (nin, *) uplo
      If (uplo=='U') Then
        Read (nin, *)((ap(i+j*(j-1)/2),j=i,n), i=1, n)
      Else If (uplo=='L') Then
        Read (nin, *)((ap(i+(2*n-j)*(j-1)/2),j=1,i), i=1, n)
      End If

!     Compute norm of A
      anorm = dlansp('1-norm', uplo, n, ap, work)

!     Factorize A
      Call dsptrf(uplo, n, ap, ipiv, info)

      Write (nout, *)
      If (info==0) Then

!       Estimate condition number
        Call dspcon(uplo, n, ap, ipiv, anorm, rcond, work, iwork, info)

        If (rcond>=epsilon(1.0E0_dp)) Then
          Write (nout, 100) 'Estimate of condition number =', 1.0_dp/rcond
        Else
          Write (nout, *) 'A is singular to working precision'
        End If
      Else
        Write (nout, *) 'The factor D is singular'
      End If

100   Format (1X, A, 1P, E10.2)
    End Program
Full documentation of DSPCON


DSPGST example

Computational Routines: Reduction to standard form of real symmetric-definite generalized eigenproblem Ax = lambda Bx, ABx = lambda x or BAx = lambda x, packed storage, B factorized by DPPTRF

Data

DSPGST Example Program Data
  4                           :Value of N
  'L'                         :Value of UPLO
  0.24
  0.39  -0.11
  0.42   0.79  -0.25
 -0.16   0.63   0.48  -0.03   :End of matrix A
  4.16
 -3.12   5.03
  0.56  -0.83   0.76
 -0.10   1.09   0.34   1.18   :End of matrix B

Result

 DSPGST Example Program Results

 Eigenvalues
    -2.2254 -0.4548  0.1001  1.1270

Source

    Program dspgst_example

!     DSPGST Example Program Text

!     Copyright 2017, Numerical Algorithms Group Ltd. http://www.nag.com

!     .. Use Statements ..
      Use lapack_interfaces, Only: dpptrf, dspgst, dsptrd, dsterf
      Use lapack_precision, Only: dp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter :: nin = 5, nout = 6
!     .. Local Scalars ..
      Integer :: i, info, j, n
      Character (1) :: uplo
!     .. Local Arrays ..
      Real (Kind=dp), Allocatable :: ap(:), bp(:), d(:), e(:), tau(:)
!     .. Executable Statements ..
      Write (nout, *) 'DSPGST Example Program Results'
!     Skip heading in data file
      Read (nin, *)
      Read (nin, *) n

      Allocate (ap(n*(n+1)/2), bp(n*(n+1)/2), d(n), e(n-1), tau(n))

!     Read A and B from data file

      Read (nin, *) uplo
      If (uplo=='U') Then
        Read (nin, *)((ap(i+j*(j-1)/2),j=i,n), i=1, n)
        Read (nin, *)((bp(i+j*(j-1)/2),j=i,n), i=1, n)
      Else If (uplo=='L') Then
        Read (nin, *)((ap(i+(2*n-j)*(j-1)/2),j=1,i), i=1, n)
        Read (nin, *)((bp(i+(2*n-j)*(j-1)/2),j=1,i), i=1, n)
      End If

!     Compute the Cholesky factorization of B
      Call dpptrf(uplo, n, bp, info)

      Write (nout, *)
      If (info>0) Then
        Write (nout, *) 'B is not positive definite.'
      Else

!       Reduce the problem to standard form C*y = lambda*y, storing
!       the result in A
        Call dspgst(1, uplo, n, ap, bp, info)

!       Reduce C to tridiagonal form T = (Q**T)*C*Q
        Call dsptrd(uplo, n, ap, d, e, tau, info)

!       Calculate the eigenvalues of T (same as C)
        Call dsterf(n, d, e, info)

        If (info>0) Then
          Write (nout, *) 'Failure to converge.'
        Else

!         Print eigenvalues

          Write (nout, *) 'Eigenvalues'
          Write (nout, 100) d(1:n)
        End If
      End If

100   Format (3X, (9F8.4))
    End Program
Full documentation of DSPGST


DSPRFS example

Computational Routines: Refined solution with error bounds of real symmetric indefinite system of linear equations, multiple right-hand sides, packed storage

Data

DSPRFS Example Program Data
  4  2                        :Values of N and NRHS
  'L'                         :Value of UPLO
  2.07
  3.87  -0.21
  4.20   1.87   1.15
 -1.15   0.63   2.06  -1.81   :End of matrix A
 -9.50  27.85
 -8.38   9.90
 -6.07  19.25
 -0.96   3.93                 :End of matrix B

Result

 DSPRFS Example Program Results

 Solution(s)
             1          2
 1     -4.0000     1.0000
 2     -1.0000     4.0000
 3      2.0000     3.0000
 4      5.0000     2.0000

 Backward errors (machine-dependent)
       9.9E-17    8.3E-17
 Estimated forward error bounds (machine-dependent)
       2.4E-14    3.2E-14

Source

    Program dsprfs_example

!     DSPRFS Example Program Text

!     Copyright 2017, Numerical Algorithms Group Ltd. http://www.nag.com

!     .. Use Statements ..
      Use lapack_example_aux, Only: nagf_file_print_matrix_real_gen
      Use lapack_interfaces, Only: dsprfs, dsptrf, dsptrs
      Use lapack_precision, Only: dp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter :: nin = 5, nout = 6
!     .. Local Scalars ..
      Integer :: i, ifail, info, j, ldb, ldx, len, n, nrhs
      Character (1) :: uplo
!     .. Local Arrays ..
      Real (Kind=dp), Allocatable :: afp(:), ap(:), b(:, :), berr(:), ferr(:), &
        work(:), x(:, :)
      Integer, Allocatable :: ipiv(:), iwork(:)
!     .. Executable Statements ..
      Write (nout, *) 'DSPRFS Example Program Results'
!     Skip heading in data file
      Read (nin, *)
      Read (nin, *) n, nrhs
      ldb = n
      ldx = n
      len = n*(n+1)/2
      Allocate (afp(len), ap(len), b(ldb,nrhs), berr(nrhs), ferr(nrhs), &
        work(3*n), x(ldx,n), ipiv(n), iwork(n))

!     Read A and B from data file, and copy A to AFP and B to X

      Read (nin, *) uplo
      If (uplo=='U') Then
        Read (nin, *)((ap(i+j*(j-1)/2),j=i,n), i=1, n)
      Else If (uplo=='L') Then
        Read (nin, *)((ap(i+(2*n-j)*(j-1)/2),j=1,i), i=1, n)
      End If
      Read (nin, *)(b(i,1:nrhs), i=1, n)

      afp(1:len) = ap(1:len)
      x(1:n, 1:nrhs) = b(1:n, 1:nrhs)

!     Factorize A in the array AFP
      Call dsptrf(uplo, n, afp, ipiv, info)

      Write (nout, *)
      Flush (nout)
      If (info==0) Then

!       Compute solution in the array X
        Call dsptrs(uplo, n, nrhs, afp, ipiv, x, ldx, info)

!       Improve solution, and compute backward errors and
!       estimated bounds on the forward errors

        Call dsprfs(uplo, n, nrhs, ap, afp, ipiv, b, ldb, x, ldx, ferr, berr, &
          work, iwork, info)

!       Print solution

!       ifail: behaviour on error exit
!              =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
        ifail = 0
        Call nagf_file_print_matrix_real_gen('General', ' ', n, nrhs, x, ldx, &
          'Solution(s)', ifail)

        Write (nout, *)
        Write (nout, *) 'Backward errors (machine-dependent)'
        Write (nout, 100) berr(1:nrhs)
        Write (nout, *) 'Estimated forward error bounds (machine-dependent)'
        Write (nout, 100) ferr(1:nrhs)
      Else
        Write (nout, *) 'The factor D is singular'
      End If

100   Format ((3X,1P,7E11.1))
    End Program
Full documentation of DSPRFS


DSPTRD example

Computational Routines: Orthogonal reduction of real symmetric matrix to symmetric tridiagonal form, packed storage

Data

DSPTRD Example Program Data
  4                           :Value of N
  'L'                         :Value of UPLO
  2.07
  3.87  -0.21
  4.20   1.87   1.15
 -1.15   0.63   2.06  -1.81   :End of matrix A

Result

 DSPTRD Example Program Results

 Diagonal and off-diagonal elements of tridiagonal form

     i         D            E
     1      2.07000      5.82575
     2      1.47409      2.62405
     3     -0.64916      0.91627
     4     -1.69493

Source

    Program dsptrd_example

!     DSPTRD Example Program Text

!     Copyright 2017, Numerical Algorithms Group Ltd. http://www.nag.com

!     .. Use Statements ..
      Use lapack_interfaces, Only: dsptrd
      Use lapack_precision, Only: dp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter :: nin = 5, nout = 6
!     .. Local Scalars ..
      Integer :: i, info, j, n
      Character (1) :: uplo
!     .. Local Arrays ..
      Real (Kind=dp), Allocatable :: ap(:), d(:), e(:), tau(:)
!     .. Intrinsic Procedures ..
      Intrinsic :: abs
!     .. Executable Statements ..
      Write (nout, *) 'DSPTRD Example Program Results'
!     Skip heading in data file
      Read (nin, *)
      Read (nin, *) n

      Allocate (ap(n*(n+1)/2), d(n), e(n-1), tau(n-1))

!     Read A from data file and copy A into AW

      Read (nin, *) uplo
      If (uplo=='U') Then
        Read (nin, *)((ap(i+j*(j-1)/2),j=i,n), i=1, n)
      Else If (uplo=='L') Then
        Read (nin, *)((ap(i+(2*n-j)*(j-1)/2),j=1,i), i=1, n)
      End If

!     Reduce A to tridiagonal form
      Call dsptrd(uplo, n, ap, d, e, tau, info)

      If (info==0) Then
!       Print the diagonal and off-diagonal of tridiagonal T.
!       The absolute value of E is printed since this can vary by a change of
!       sign (corresponding to multiplying through a column of Q by -1).

        Write (nout, *)
        Write (nout, *) &
          'Diagonal and off-diagonal elements of tridiagonal form'
        Write (nout, *)
        Write (nout, 100) 'i', 'D', 'E'
        Do i = 1, n - 1
          Write (nout, 110) i, d(i), abs(e(i))
        End Do
        Write (nout, 110) n, d(n)

      Else
        Write (nout, 120) info
      End If

100   Format (5X, A, 9X, A, 12X, A)
110   Format (1X, I5, 2(1X,F12.5))
120   Format (1X, '** DSPTRD retuned with INFO = ', I10)

    End Program
Full documentation of DSPTRD


DSPTRF example

Computational Routines: Bunch-Kaufman factorization of real symmetric indefinite matrix, packed storage

Data

DSPTRF Example Program Data
  4                           :Value of N
  'L'                         :Value of UPLO
  2.07
  3.87  -0.21
  4.20   1.87   1.15
 -1.15   0.63   2.06  -1.81   :End of matrix A

Result

 DSPTRF Example Program Results

 Details of factorization
             1          2          3          4
 1      2.0700
 2      4.2000     1.1500
 3      0.2230     0.8115    -2.5907
 4      0.6537    -0.5960     0.3031     0.4074

 IPIV
            -3         -3          3          4

Source

    Program dsptrf_example

!     DSPTRF Example Program Text

!     Copyright 2017, Numerical Algorithms Group Ltd. http://www.nag.com

!     .. Use Statements ..
      Use lapack_example_aux, Only: nagf_file_print_matrix_real_packed
      Use lapack_interfaces, Only: dsptrf
      Use lapack_precision, Only: dp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter :: nin = 5, nout = 6
!     .. Local Scalars ..
      Integer :: i, ifail, info, j, n
      Character (1) :: uplo
!     .. Local Arrays ..
      Real (Kind=dp), Allocatable :: ap(:)
      Integer, Allocatable :: ipiv(:)
!     .. Executable Statements ..
      Write (nout, *) 'DSPTRF Example Program Results'
!     Skip heading in data file
      Read (nin, *)
      Read (nin, *) n

      Allocate (ap(n*(n+1)/2), ipiv(n))

!     Read A from data file

      Read (nin, *) uplo
      If (uplo=='U') Then
        Read (nin, *)((ap(i+j*(j-1)/2),j=i,n), i=1, n)
      Else If (uplo=='L') Then
        Read (nin, *)((ap(i+(2*n-j)*(j-1)/2),j=1,i), i=1, n)
      End If

!     Factorize A
      Call dsptrf(uplo, n, ap, ipiv, info)

      Write (nout, *)
      Flush (nout)

!     Print details of factorization

!     ifail: behaviour on error exit
!            =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
      ifail = 0
      Call nagf_file_print_matrix_real_packed(uplo, 'Nonunit', n, ap, &
        'Details of factorization', ifail)

!     Print pivot indices

      Write (nout, *)
      Write (nout, *) 'IPIV'
      Write (nout, 100) ipiv(1:n)

      If (info/=0) Then
        Write (nout, *) 'The factor D is singular'
      End If

100   Format ((3X,7I11))
    End Program
Full documentation of DSPTRF


DSPTRI example

Computational Routines: Inverse of real symmetric indefinite matrix, matrix already factorized by DSPTRF, packed storage

Data

DSPTRI Example Program Data
  4                           :Value of N
  'L'                         :Value of UPLO
  2.07
  3.87  -0.21
  4.20   1.87   1.15
 -1.15   0.63   2.06  -1.81   :End of matrix A

Result

 DSPTRI Example Program Results

 Inverse
             1          2          3          4
 1      0.7485
 2      0.5221    -0.1605
 3     -1.0058    -0.3131     1.3501
 4     -1.4386    -0.7440     2.0667     2.4547

Source

    Program dsptri_example

!     DSPTRI Example Program Text

!     Copyright 2017, Numerical Algorithms Group Ltd. http://www.nag.com

!     .. Use Statements ..
      Use lapack_example_aux, Only: nagf_file_print_matrix_real_packed
      Use lapack_interfaces, Only: dsptrf, dsptri
      Use lapack_precision, Only: dp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter :: nin = 5, nout = 6
!     .. Local Scalars ..
      Integer :: i, ifail, info, j, n
      Character (1) :: uplo
!     .. Local Arrays ..
      Real (Kind=dp), Allocatable :: ap(:), work(:)
      Integer, Allocatable :: ipiv(:)
!     .. Executable Statements ..
      Write (nout, *) 'DSPTRI Example Program Results'
!     Skip heading in data file
      Read (nin, *)
      Read (nin, *) n

      Allocate (ap(n*(n+1)/2), work(n), ipiv(n))

!     Read A from data file

      Read (nin, *) uplo
      If (uplo=='U') Then
        Read (nin, *)((ap(i+j*(j-1)/2),j=i,n), i=1, n)
      Else If (uplo=='L') Then
        Read (nin, *)((ap(i+(2*n-j)*(j-1)/2),j=1,i), i=1, n)
      End If

!     Factorize A
      Call dsptrf(uplo, n, ap, ipiv, info)

      Write (nout, *)
      Flush (nout)
      If (info==0) Then

!       Compute inverse of A
        Call dsptri(uplo, n, ap, ipiv, work, info)

!       Print inverse

!       ifail: behaviour on error exit
!              =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
        ifail = 0
        Call nagf_file_print_matrix_real_packed(uplo, 'Nonunit', n, ap, &
          'Inverse', ifail)

      Else
        Write (nout, *) 'The factor D is singular'
      End If

    End Program
Full documentation of DSPTRI


DSPTRS example

Computational Routines: Solution of real symmetric indefinite system of linear equations, multiple right-hand sides, matrix already factorized by DSPTRF, packed storage

Data

DSPTRS Example Program Data
  4  2                        :Values of N and NRHS
  'L'                         :Value of UPLO
  2.07
  3.87  -0.21
  4.20   1.87   1.15
 -1.15   0.63   2.06  -1.81   :End of matrix A
 -9.50  27.85
 -8.38   9.90
 -6.07  19.25
 -0.96   3.93                 :End of matrix B

Result

 DSPTRS Example Program Results

 Solution(s)
             1          2
 1     -4.0000     1.0000
 2     -1.0000     4.0000
 3      2.0000     3.0000
 4      5.0000     2.0000

Source

    Program dsptrs_example

!     DSPTRS Example Program Text

!     Copyright 2017, Numerical Algorithms Group Ltd. http://www.nag.com

!     .. Use Statements ..
      Use lapack_example_aux, Only: nagf_file_print_matrix_real_gen
      Use lapack_interfaces, Only: dsptrf, dsptrs
      Use lapack_precision, Only: dp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter :: nin = 5, nout = 6
!     .. Local Scalars ..
      Integer :: i, ifail, info, j, ldb, n, nrhs
      Character (1) :: uplo
!     .. Local Arrays ..
      Real (Kind=dp), Allocatable :: ap(:), b(:, :)
      Integer, Allocatable :: ipiv(:)
!     .. Executable Statements ..
      Write (nout, *) 'DSPTRS Example Program Results'
!     Skip heading in data file
      Read (nin, *)
      Read (nin, *) n, nrhs
      ldb = n
      Allocate (ap(n*(n+1)/2), b(ldb,nrhs), ipiv(n))

!     Read A and B from data file

      Read (nin, *) uplo
      If (uplo=='U') Then
        Read (nin, *)((ap(i+j*(j-1)/2),j=i,n), i=1, n)
      Else If (uplo=='L') Then
        Read (nin, *)((ap(i+(2*n-j)*(j-1)/2),j=1,i), i=1, n)
      End If
      Read (nin, *)(b(i,1:nrhs), i=1, n)

!     Factorize A
      Call dsptrf(uplo, n, ap, ipiv, info)

      Write (nout, *)
      Flush (nout)
      If (info==0) Then

!       Compute solution
        Call dsptrs(uplo, n, nrhs, ap, ipiv, b, ldb, info)

!       Print solution

!       ifail: behaviour on error exit
!              =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
        ifail = 0
        Call nagf_file_print_matrix_real_gen('General', ' ', n, nrhs, b, ldb, &
          'Solution(s)', ifail)

      Else
        Write (nout, *) 'The factor D is singular'
      End If

    End Program
Full documentation of DSPTRS


DSTEDC example

Computational Routines: Computes all eigenvalues and, optionally, eigenvectors of a real symmetric tridiagonal matrix or a matrix reduced to this form (divide-and-conquer)

Data

DSTEDC Example Program Data

  4      2                   :Values of N and KD

  4.99   0.04   0.22
         1.05  -0.79   1.04
               -2.31  -1.30
                      -0.43  :End of matrix A

Result

 DSTEDC Example Program Results

 Eigenvalues
    -2.9943 -0.7000  1.9974  4.9969

 Eigenvectors
          1       2       3       4
 1   0.0251  0.0162  0.0113  0.9995
 2  -0.0656 -0.5859  0.8077  0.0020
 3  -0.9002 -0.3135 -0.3006  0.0311
 4  -0.4298  0.7471  0.5070 -0.0071

Source

    Program dstedc_example

!     DSTEDC Example Program Text

!     Copyright 2017, Numerical Algorithms Group Ltd. http://www.nag.com

!     .. Use Statements ..
      Use lapack_example_aux, Only: nagf_file_print_matrix_real_gen
      Use lapack_interfaces, Only: dsbtrd, dstedc
      Use lapack_precision, Only: dp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter :: nin = 5, nout = 6
      Character (1), Parameter :: uplo = 'U'
!     .. Local Scalars ..
      Integer :: i, ifail, info, j, kd, ldab, ldz, lgn, liwork, lwork, n
!     .. Local Arrays ..
      Real (Kind=dp), Allocatable :: ab(:, :), d(:), e(:), work(:), z(:, :)
      Real (Kind=dp) :: rdum(1)
      Integer :: idum(1)
      Integer, Allocatable :: iwork(:)
!     .. Intrinsic Procedures ..
      Intrinsic :: ceiling, log, max, min, nint, real
!     .. Executable Statements ..
      Write (nout, *) 'DSTEDC Example Program Results'
      Write (nout, *)
!     Skip heading in data file
      Read (nin, *)
      Read (nin, *) n, kd
      ldab = kd + 1
      ldz = n
      lgn = ceiling(log(real(n,kind=dp))/log(2.0E0_dp))
      Allocate (ab(ldab,n), d(n), e(n-1), z(ldz,n))

!     Use routine workspace query to get optimal workspace.
      lwork = -1
      liwork = -1
      Call dstedc('V', n, d, e, z, ldz, rdum, lwork, idum, liwork, info)

!     Make sure that there is enough workspace.
      lwork = max(1+3*n+2*n*lgn+4*n*n, nint(rdum(1)))
      liwork = max(6+6*n+5*n*lgn, idum(1))
      Allocate (work(lwork), iwork(liwork))

!     Read the upper or lower triangular part of the band matrix A
!     from data file

      If (uplo=='U') Then
        Do i = 1, n
          Read (nin, *)(ab(kd+1+i-j,j), j=i, min(n,i+kd))
        End Do
      Else If (uplo=='L') Then
        Do i = 1, n
          Read (nin, *)(ab(1+i-j,j), j=max(1,i-kd), i)
        End Do
      End If

!     Reduce A to tridiagonal form T = (Z**T)*A*Z, and form Z
      Call dsbtrd('V', uplo, n, kd, ab, ldab, d, e, z, ldz, work, info)

!     Calculate all the eigenvalues and eigenvectors of A,
!     from T and Z
      Call dstedc('V', n, d, e, z, ldz, work, lwork, iwork, liwork, info)

      If (info==0) Then

!       Print eigenvalues and eigenvectors

        Write (nout, *) 'Eigenvalues'
        Write (nout, 100) d(1:n)

        Write (nout, *)
        Flush (nout)

!       Standardize the eigenvectors so that first elements are non-negative.
        Do i = 1, n
          If (z(1,i)<0.0_dp) Then
            z(1:n, i) = -z(1:n, i)
          End If
        End Do

!       ifail: behaviour on error exit
!               =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
        ifail = 0
        Call nagf_file_print_matrix_real_gen('General', ' ', n, n, z, ldz, &
          'Eigenvectors', ifail)

      Else
        Write (nout, 110) 'Failure in DSTEDC. INFO = ', info
      End If

100   Format ((3X,8F8.4))
110   Format (1X, A, I10)
    End Program
Full documentation of DSTEDC


DSTEGR example

Computational Routines: Computes all eigenvalues and, optionally, eigenvectors of a real symmetric tridiagonal matrix or a symmetric matrix reduced to this form (Relatively Robust Representations)

Data

DSTEGR Example Program Data

  4                    :Value of N

  1.0  4.0  9.0  16.0  :End of D
  1.0  2.0  3.0        :End of E

  'V'                  :Value of JOBZ

Result

 DSTEGR Example Program Results

 Eigenvalues
     0.6476  3.5470  8.6578 17.1477

Warning: Floating invalid operation occurred
Warning: Floating divide by zero occurred
Warning: Floating underflow occurred
 Eigenvectors
          1       2       3       4
 1   0.9396  0.3388  0.0494  0.0034
 2  -0.3311  0.8628  0.3781  0.0545
 3   0.0853 -0.3648  0.8558  0.3568
 4  -0.0167  0.0879 -0.3497  0.9326

Source

    Program dstegr_example

!     DSTEGR Example Program Text

!     Copyright 2017, Numerical Algorithms Group Ltd. http://www.nag.com

!     .. Use Statements ..
      Use lapack_example_aux, Only: nagf_file_print_matrix_real_gen
      Use lapack_interfaces, Only: dstegr
      Use lapack_precision, Only: dp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Real (Kind=dp), Parameter :: vl = 0.0E0_dp
      Real (Kind=dp), Parameter :: vu = 0.0E0_dp
      Integer, Parameter :: il = 0, iu = 0, nin = 5, nout = 6
      Character (1), Parameter :: range = 'A'
!     .. Local Scalars ..
      Real (Kind=dp) :: abstol
      Integer :: i, ifail, info, ldz, liwork, lwork, m, n
      Character (1) :: jobz
!     .. Local Arrays ..
      Real (Kind=dp), Allocatable :: d(:), e(:), w(:), work(:), z(:, :)
      Integer, Allocatable :: isuppz(:), iwork(:)
!     .. Executable Statements ..
      Write (nout, *) 'DSTEGR Example Program Results'
      Write (nout, *)
!     Skip heading in data file
      Read (nin, *)
      Read (nin, *) n
      ldz = n
      liwork = 10*n
      lwork = 18*n
      Allocate (d(n), e(n), w(n), work(lwork), z(ldz,n), isuppz(2*n), &
        iwork(liwork))

!     Read the symmetric tridiagonal matrix T from data file, first
!     the diagonal elements, then the off diagonal elements and then
!     JOBV ('N' - eigenvalues only, 'V' - vectors as well)

      Read (nin, *) d(1:n)
      Read (nin, *) e(1:n-1)
      Read (nin, *) jobz

!     Calculate all the eigenvalues of T. Set ABSTOL to zero so that
!     the default value is used.

      abstol = 0.0E0_dp
      Call dstegr(jobz, range, n, d, e, vl, vu, il, iu, abstol, m, w, z, ldz, &
        isuppz, work, lwork, iwork, liwork, info)

      If (info==0) Then

!       Print eigenvalues and eigenvectors

        Write (nout, *) 'Eigenvalues'
        Write (nout, 100) w(1:m)

        Write (nout, *)
        Flush (nout)

!       Standardize the eigenvectors so that first elements are non-negative.
        Do i = 1, m
          If (z(1,i)<0.0_dp) Then
            z(1:n, i) = -z(1:n, i)
          End If
        End Do

!       ifail: behaviour on error exit
!              =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
        ifail = 0
        Call nagf_file_print_matrix_real_gen('General', ' ', n, m, z, ldz, &
          'Eigenvectors', ifail)

      Else
        Write (nout, 110) 'Failure to compute an eigenvalue, INFO = ', info
      End If

100   Format ((3X,8F8.4))
110   Format (1X, A, I10)
    End Program
Full documentation of DSTEGR


DSTEQR example

Computational Routines: All eigenvalues and eigenvectors of real symmetric tridiagonal matrix, reduced from real symmetric matrix using implicit QL or QR

Data

DSTEQR Example Program Data
  4                           :Value of N
 -6.99   7.92   2.34   0.32
 -0.44  -2.63  -1.18          :End of matrix T

Result

 DSTEQR Example Program Results

 Eigenvalues
    -7.0037 -0.4059  2.0028  8.9968

 Eigenvectors
          1       2       3       4
 1   0.9995  0.0109  0.0167  0.0255
 2   0.0310 -0.1627 -0.3408 -0.9254
 3   0.0089 -0.5170 -0.7696  0.3746
 4   0.0014 -0.8403  0.5397 -0.0509

Source

    Program dsteqr_example

!     DSTEQR Example Program Text

!     Copyright 2017, Numerical Algorithms Group Ltd. http://www.nag.com

!     .. Use Statements ..
      Use lapack_example_aux, Only: nagf_file_print_matrix_real_gen
      Use lapack_interfaces, Only: dsteqr
      Use lapack_precision, Only: dp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter :: nin = 5, nout = 6
!     .. Local Scalars ..
      Integer :: i, ifail, info, ldz, n
!     .. Local Arrays ..
      Real (Kind=dp), Allocatable :: d(:), e(:), work(:), z(:, :)
!     .. Executable Statements ..
      Write (nout, *) 'DSTEQR Example Program Results'
!     Skip heading in data file
      Read (nin, *)
      Read (nin, *) n
      ldz = n
      Allocate (d(n), e(n-1), work(2*n-2), z(ldz,n))

!     Read T from data file

      Read (nin, *) d(1:n)
      Read (nin, *) e(1:n-1)

!     Calculate all the eigenvalues and eigenvectors of T
      Call dsteqr('I', n, d, e, z, ldz, work, info)

      Write (nout, *)
      If (info>0) Then
        Write (nout, *) 'Failure to converge.'
      Else

!       Print eigenvalues and eigenvectors

        Write (nout, *) 'Eigenvalues'
        Write (nout, 100) d(1:n)
        Write (nout, *)
        Flush (nout)

!       Standardize the eigenvectors so that first elements are non-negative.
        Do i = 1, n
          If (z(1,i)<0.0_dp) Then
            z(1:n, i) = -z(1:n, i)
          End If
        End Do

!       ifail: behaviour on error exit
!              =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
        ifail = 0
        Call nagf_file_print_matrix_real_gen('General', ' ', n, n, z, ldz, &
          'Eigenvectors', ifail)

      End If

100   Format (3X, (8F8.4))
    End Program
Full documentation of DSTEQR


DSTERF example

Computational Routines: All eigenvalues of real symmetric tridiagonal matrix, root-free variant of QL or QR

Data

DSTERF Example Program Data
  4                           :Value of N
 -6.99   7.92   2.34   0.32
 -0.44  -2.63  -1.18          :End of matrix T

Result

 DSTERF Example Program Results

 Eigenvalues
    -7.0037 -0.4059  2.0028  8.9968

Source

    Program dsterf_example

!     DSTERF Example Program Text

!     Copyright 2017, Numerical Algorithms Group Ltd. http://www.nag.com

!     .. Use Statements ..
      Use lapack_interfaces, Only: dsterf
      Use lapack_precision, Only: dp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter :: nin = 5, nout = 6
!     .. Local Scalars ..
      Integer :: info, n
!     .. Local Arrays ..
      Real (Kind=dp), Allocatable :: d(:), e(:)
!     .. Executable Statements ..
      Write (nout, *) 'DSTERF Example Program Results'
!     Skip heading in data file
      Read (nin, *)
      Read (nin, *) n

      Allocate (d(n), e(n-1))

!     Read T from data file

      Read (nin, *) d(1:n)
      Read (nin, *) e(1:n-1)

!     Calculate the eigenvalues of T
      Call dsterf(n, d, e, info)

      Write (nout, *)
      If (info>0) Then
        Write (nout, *) 'Failure to converge.'
      Else
        Write (nout, *) 'Eigenvalues'
        Write (nout, 100) d(1:n)
      End If

100   Format (3X, (9F8.4))
    End Program
Full documentation of DSTERF


DSYCON example

Computational Routines: Estimate condition number of real symmetric indefinite matrix, matrix already factorized by DSYTRF

Data

DSYCON Example Program Data
  4                           :Value of N
  'L'                         :Value of UPLO
  2.07
  3.87  -0.21
  4.20   1.87   1.15
 -1.15   0.63   2.06  -1.81   :End of matrix A

Result

 DSYCON Example Program Results

 Estimate of condition number =  7.57E+01

Source

    Program dsycon_example

!     DSYCON Example Program Text

!     Copyright 2017, Numerical Algorithms Group Ltd. http://www.nag.com

!     .. Use Statements ..
      Use lapack_interfaces, Only: dlansy, dsycon, dsytrf
      Use lapack_precision, Only: dp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=dp) :: anorm, rcond
      Integer :: i, info, lda, lwork, n
      Character (1) :: uplo
!     .. Local Arrays ..
      Real (Kind=dp), Allocatable :: a(:, :), work(:)
      Integer, Allocatable :: ipiv(:), iwork(:)
!     .. Intrinsic Procedures ..
      Intrinsic :: epsilon
!     .. Executable Statements ..
      Write (nout, *) 'DSYCON Example Program Results'
!     Skip heading in data file
      Read (nin, *)
      Read (nin, *) n
      lda = n
      lwork = 64*n
      Allocate (a(lda,n), work(lwork), ipiv(n), iwork(n))

!     Read A from data file

      Read (nin, *) uplo
      If (uplo=='U') Then
        Read (nin, *)(a(i,i:n), i=1, n)
      Else If (uplo=='L') Then
        Read (nin, *)(a(i,1:i), i=1, n)
      End If

!     Compute norm of A
      anorm = dlansy('1-norm', uplo, n, a, lda, work)

!     Factorize A
      Call dsytrf(uplo, n, a, lda, ipiv, work, lwork, info)

      Write (nout, *)
      If (info==0) Then

!       Estimate condition number
        Call dsycon(uplo, n, a, lda, ipiv, anorm, rcond, work, iwork, info)

        If (rcond>=epsilon(1.0E0_dp)) Then
          Write (nout, 100) 'Estimate of condition number =', 1.0_dp/rcond
        Else
          Write (nout, *) 'A is singular to working precision'
        End If
      Else
        Write (nout, *) 'The factor D is singular'
      End If

100   Format (1X, A, 1P, E10.2)
    End Program
Full documentation of DSYCON


DSYGST example

Computational Routines: Reduction to standard form of real symmetric-definite generalized eigenproblem Ax = lambda Bx, ABx = lambda x or BAx = lambda x, B factorized by DPOTRF

Data

DSYGST Example Program Data
  4                           :Value of N
  'L'                         :Value of UPLO
  0.24
  0.39  -0.11
  0.42   0.79  -0.25
 -0.16   0.63   0.48  -0.03   :End of matrix A
  4.16
 -3.12   5.03
  0.56  -0.83   0.76
 -0.10   1.09   0.34   1.18   :End of matrix B

Result

 DSYGST Example Program Results

 Eigenvalues
    -2.2254 -0.4548  0.1001  1.1270

Source

    Program dsygst_example

!     DSYGST Example Program Text

!     Copyright 2017, Numerical Algorithms Group Ltd. http://www.nag.com

!     .. Use Statements ..
      Use lapack_interfaces, Only: dpotrf, dsterf, dsygst, dsytrd
      Use lapack_precision, Only: dp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter :: nin = 5, nout = 6
!     .. Local Scalars ..
      Integer :: i, info, lda, ldb, lwork, n
      Character (1) :: uplo
!     .. Local Arrays ..
      Real (Kind=dp), Allocatable :: a(:, :), b(:, :), d(:), e(:), tau(:), &
        work(:)
!     .. Executable Statements ..
      Write (nout, *) 'DSYGST Example Program Results'
!     Skip heading in data file
      Read (nin, *)
      Read (nin, *) n
      lda = n
      ldb = n
      lwork = 64*n
      Allocate (a(lda,n), b(ldb,n), d(n), e(n-1), tau(n), work(lwork))

!     Read A and B from data file

      Read (nin, *) uplo
      If (uplo=='U') Then
        Read (nin, *)(a(i,i:n), i=1, n)
        Read (nin, *)(b(i,i:n), i=1, n)
      Else If (uplo=='L') Then
        Read (nin, *)(a(i,1:i), i=1, n)
        Read (nin, *)(b(i,1:i), i=1, n)
      End If

!     Compute the Cholesky factorization of B
      Call dpotrf(uplo, n, b, ldb, info)

      Write (nout, *)
      If (info>0) Then
        Write (nout, *) 'B is not positive definite.'
      Else

!       Reduce the problem to standard form C*y = lambda*y, storing
!       the result in A
        Call dsygst(1, uplo, n, a, lda, b, ldb, info)

!       Reduce C to tridiagonal form T = (Q**T)*C*Q
        Call dsytrd(uplo, n, a, lda, d, e, tau, work, lwork, info)

!       Calculate the eigenvalues of T (same as C)
        Call dsterf(n, d, e, info)

        If (info>0) Then
          Write (nout, *) 'Failure to converge.'
        Else

!         Print eigenvalues

          Write (nout, *) 'Eigenvalues'
          Write (nout, 100) d(1:n)
        End If
      End If

100   Format (3X, (9F8.4))
    End Program
Full documentation of DSYGST


DSYRFS example

Computational Routines: Refined solution with error bounds of real symmetric indefinite system of linear equations, multiple right-hand sides

Data

DSYRFS Example Program Data
  4  2                        :Values of N and NRHS
  'L'                         :Value of UPLO
  2.07
  3.87  -0.21
  4.20   1.87   1.15
 -1.15   0.63   2.06  -1.81   :End of matrix A
 -9.50  27.85
 -8.38   9.90
 -6.07  19.25
 -0.96   3.93                 :End of matrix B

Result

 DSYRFS Example Program Results

 Solution(s)
             1          2
 1     -4.0000     1.0000
 2     -1.0000     4.0000
 3      2.0000     3.0000
 4      5.0000     2.0000

 Backward errors (machine-dependent)
       9.9E-17    8.3E-17
 Estimated forward error bounds (machine-dependent)
       2.4E-14    3.2E-14

Source

    Program dsyrfs_example

!     DSYRFS Example Program Text

!     Copyright 2017, Numerical Algorithms Group Ltd. http://www.nag.com

!     .. Use Statements ..
      Use lapack_example_aux, Only: nagf_file_print_matrix_real_gen
      Use lapack_interfaces, Only: dsyrfs, dsytrf, dsytrs
      Use lapack_precision, Only: dp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter :: nin = 5, nout = 6
!     .. Local Scalars ..
      Integer :: i, ifail, info, lda, ldaf, ldb, ldx, lwork, n, nrhs
      Character (1) :: uplo
!     .. Local Arrays ..
      Real (Kind=dp), Allocatable :: a(:, :), af(:, :), b(:, :), berr(:), &
        ferr(:), work(:), x(:, :)
      Integer, Allocatable :: ipiv(:), iwork(:)
!     .. Executable Statements ..
      Write (nout, *) 'DSYRFS Example Program Results'
!     Skip heading in data file
      Read (nin, *)
      Read (nin, *) n, nrhs
      lda = n
      ldaf = n
      ldb = n
      ldx = n
      lwork = 64*n
      Allocate (a(lda,n), af(ldaf,n), b(ldb,nrhs), berr(nrhs), ferr(nrhs), &
        work(lwork), x(ldx,n), ipiv(n), iwork(n))

!     Read A and B from data file, and copy A to AF and B to X

      Read (nin, *) uplo
      If (uplo=='U') Then
        Do i = 1, n
          Read (nin, *) a(i, i:n)
          af(i, i:n) = a(i, i:n)
        End Do
      Else If (uplo=='L') Then
        Do i = 1, n
          Read (nin, *) a(i, 1:i)
          af(i, 1:i) = a(i, 1:i)
        End Do
      End If
      Read (nin, *)(b(i,1:nrhs), i=1, n)

      x(1:n, 1:nrhs) = b(1:n, 1:nrhs)

!     Factorize A in the array AF
      Call dsytrf(uplo, n, af, ldaf, ipiv, work, lwork, info)

      Write (nout, *)
      Flush (nout)
      If (info==0) Then

!       Compute solution in the array X
        Call dsytrs(uplo, n, nrhs, af, ldaf, ipiv, x, ldx, info)

!       Improve solution, and compute backward errors and
!       estimated bounds on the forward errors
        Call dsyrfs(uplo, n, nrhs, a, lda, af, ldaf, ipiv, b, ldb, x, ldx, &
          ferr, berr, work, iwork, info)

!       Print solution

!       ifail: behaviour on error exit
!              =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
        ifail = 0
        Call nagf_file_print_matrix_real_gen('General', ' ', n, nrhs, x, ldx, &
          'Solution(s)', ifail)

        Write (nout, *)
        Write (nout, *) 'Backward errors (machine-dependent)'
        Write (nout, 100) berr(1:nrhs)
        Write (nout, *) 'Estimated forward error bounds (machine-dependent)'
        Write (nout, 100) ferr(1:nrhs)
      Else
        Write (nout, *) 'The factor D is singular'
      End If

100   Format ((3X,1P,7E11.1))
    End Program
Full documentation of DSYRFS


DSYTRD example

Computational Routines: Orthogonal reduction of real symmetric matrix to symmetric tridiagonal form

Data

DSYTRD Example Program Data
  4                           :Value of N
  'L'                         :Value of UPLO
  2.07
  3.87  -0.21
  4.20   1.87   1.15
 -1.15   0.63   2.06  -1.81   :End of matrix A

Result

 DSYTRD Example Program Results

 Diagonal and off-diagonal elements of tridiagonal form

     i         D            E
     1      2.07000      5.82575
     2      1.47409      2.62405
     3     -0.64916      0.91627
     4     -1.69493

Source

    Program dsytrd_example

!     DSYTRD Example Program Text

!     Copyright 2017, Numerical Algorithms Group Ltd. http://www.nag.com

!     .. Use Statements ..
      Use lapack_interfaces, Only: dsytrd
      Use lapack_precision, Only: dp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter :: nin = 5, nout = 6
!     .. Local Scalars ..
      Integer :: i, info, lda, lwork, n
      Character (1) :: uplo
!     .. Local Arrays ..
      Real (Kind=dp), Allocatable :: a(:, :), d(:), e(:), tau(:), work(:)
!     .. Intrinsic Procedures ..
      Intrinsic :: abs
!     .. Executable Statements ..
      Write (nout, *) 'DSYTRD Example Program Results'
!     Skip heading in data file
      Read (nin, *)
      Read (nin, *) n
      lda = n
      lwork = 64*n
      Allocate (a(lda,n), d(n), e(n-1), tau(n-1), work(lwork))

!     Read A from data file and copy A into C to store as a full matrix

      Read (nin, *) uplo
      If (uplo=='U') Then
        Read (nin, *)(a(i,i:n), i=1, n)
      Else If (uplo=='L') Then
        Read (nin, *)(a(i,1:i), i=1, n)
      End If

!     Reduce A to tridiagonal form
      Call dsytrd(uplo, n, a, lda, d, e, tau, work, lwork, info)

      If (info==0) Then
!       Print the diagonal and off-diagonal of tridiagonal T.
!       The absolute value of E is printed since this can vary by a change of
!       sign (corresponding to multiplying through a column of Q by -1).

        Write (nout, *)
        Write (nout, *) &
          'Diagonal and off-diagonal elements of tridiagonal form'
        Write (nout, *)
        Write (nout, 100) 'i', 'D', 'E'
        Do i = 1, n - 1
          Write (nout, 110) i, d(i), abs(e(i))
        End Do
        Write (nout, 110) n, d(n)

      Else
        Write (nout, 120) info
      End If

100   Format (5X, A, 9X, A, 12X, A)
110   Format (1X, I5, 2(1X,F12.5))
120   Format (1X, '** DSYTRD retuned with INFO = ', I10)

    End Program
Full documentation of DSYTRD


DSYTRF example

Computational Routines: Bunch-Kaufman factorization of real symmetric indefinite matrix

Data

DSYTRF Example Program Data
  4                           :Value of N
  'L'                         :Value of UPLO
  2.07
  3.87  -0.21
  4.20   1.87   1.15
 -1.15   0.63   2.06  -1.81   :End of matrix A

Result

 DSYTRF Example Program Results

 Details of factorization
             1          2          3          4
 1      2.0700
 2      4.2000     1.1500
 3      0.2230     0.8115    -2.5907
 4      0.6537    -0.5960     0.3031     0.4074

 IPIV
            -3         -3          3          4

Source

    Program dsytrf_example

!     DSYTRF Example Program Text

!     Copyright 2017, Numerical Algorithms Group Ltd. http://www.nag.com

!     .. Use Statements ..
      Use lapack_example_aux, Only: nagf_file_print_matrix_real_gen
      Use lapack_interfaces, Only: dsytrf
      Use lapack_precision, Only: dp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter :: nin = 5, nout = 6
!     .. Local Scalars ..
      Integer :: i, ifail, info, lda, lwork, n
      Character (1) :: uplo
!     .. Local Arrays ..
      Real (Kind=dp), Allocatable :: a(:, :), work(:)
      Integer, Allocatable :: ipiv(:)
!     .. Executable Statements ..
      Write (nout, *) 'DSYTRF Example Program Results'
!     Skip heading in data file
      Read (nin, *)
      Read (nin, *) n
      lda = n
      lwork = 64*n
      Allocate (a(lda,n), work(lwork), ipiv(n))

!     Read A from data file

      Read (nin, *) uplo
      If (uplo=='U') Then
        Read (nin, *)(a(i,i:n), i=1, n)
      Else If (uplo=='L') Then
        Read (nin, *)(a(i,1:i), i=1, n)
      End If

!     Factorize A
      Call dsytrf(uplo, n, a, lda, ipiv, work, lwork, info)

      Write (nout, *)
      Flush (nout)

!     Print details of factorization

!     ifail: behaviour on error exit
!             =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
      ifail = 0
      Call nagf_file_print_matrix_real_gen(uplo, 'Nonunit', n, n, a, lda, &
        'Details of factorization', ifail)

!     Print pivot indices

      Write (nout, *)
      Write (nout, *) 'IPIV'
      Write (nout, 100) ipiv(1:n)

      If (info/=0) Then
        Write (nout, *) 'The factor D is singular'
      End If

100   Format ((3X,7I11))
    End Program
Full documentation of DSYTRF


DSYTRI example

Computational Routines: Inverse of real symmetric indefinite matrix, matrix already factorized by DSYTRF

Data

DSYTRI Example Program Data
  4                           :Value of N
  'L'                         :Value of UPLO
  2.07
  3.87  -0.21
  4.20   1.87   1.15
 -1.15   0.63   2.06  -1.81   :End of matrix A

Result

 DSYTRI Example Program Results

 Inverse
             1          2          3          4
 1      0.7485
 2      0.5221    -0.1605
 3     -1.0058    -0.3131     1.3501
 4     -1.4386    -0.7440     2.0667     2.4547

Source

    Program dsytri_example

!     DSYTRI Example Program Text

!     Copyright 2017, Numerical Algorithms Group Ltd. http://www.nag.com

!     .. Use Statements ..
      Use lapack_example_aux, Only: nagf_file_print_matrix_real_gen
      Use lapack_interfaces, Only: dsytrf, dsytri
      Use lapack_precision, Only: dp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter :: nin = 5, nout = 6
!     .. Local Scalars ..
      Integer :: i, ifail, info, lda, lwork, n
      Character (1) :: uplo
!     .. Local Arrays ..
      Real (Kind=dp), Allocatable :: a(:, :), work(:)
      Integer, Allocatable :: ipiv(:)
!     .. Executable Statements ..
      Write (nout, *) 'DSYTRI Example Program Results'
!     Skip heading in data file
      Read (nin, *)
      Read (nin, *) n
      lda = n
      lwork = 64*n
      Allocate (a(lda,n), work(lwork), ipiv(n))

!     Read A from data file

      Read (nin, *) uplo
      If (uplo=='U') Then
        Read (nin, *)(a(i,i:n), i=1, n)
      Else If (uplo=='L') Then
        Read (nin, *)(a(i,1:i), i=1, n)
      End If

!     Factorize A
      Call dsytrf(uplo, n, a, lda, ipiv, work, lwork, info)

      Write (nout, *)
      Flush (nout)
      If (info==0) Then

!       Compute inverse of A
        Call dsytri(uplo, n, a, lda, ipiv, work, info)

!       Print inverse

!       ifail: behaviour on error exit
!              =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
        ifail = 0
        Call nagf_file_print_matrix_real_gen(uplo, 'Nonunit', n, n, a, lda, &
          'Inverse', ifail)

      Else
        Write (nout, *) 'The factor D is singular'
      End If

    End Program
Full documentation of DSYTRI


DSYTRS example

Computational Routines: Solution of real symmetric indefinite system of linear equations, multiple right-hand sides, matrix already factorized by DSYTRF

Data

DSYTRS Example Program Data
  4  2                        :Values of N and NRHS
  'L'                         :Value of UPLO
  2.07
  3.87  -0.21
  4.20   1.87   1.15
 -1.15   0.63   2.06  -1.81   :End of matrix A
 -9.50  27.85
 -8.38   9.90
 -6.07  19.25
 -0.96   3.93                 :End of matrix B

Result

 DSYTRS Example Program Results

 Solution(s)
             1          2
 1     -4.0000     1.0000
 2     -1.0000     4.0000
 3      2.0000     3.0000
 4      5.0000     2.0000

Source

    Program dsytrs_example

!     DSYTRS Example Program Text

!     Copyright 2017, Numerical Algorithms Group Ltd. http://www.nag.com

!     .. Use Statements ..
      Use lapack_example_aux, Only: nagf_file_print_matrix_real_gen
      Use lapack_interfaces, Only: dsytrf, dsytrs
      Use lapack_precision, Only: dp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter :: nin = 5, nout = 6
!     .. Local Scalars ..
      Integer :: i, ifail, info, lda, ldb, lwork, n, nrhs
      Character (1) :: uplo
!     .. Local Arrays ..
      Real (Kind=dp), Allocatable :: a(:, :), b(:, :), work(:)
      Integer, Allocatable :: ipiv(:)
!     .. Executable Statements ..
      Write (nout, *) 'DSYTRS Example Program Results'
!     Skip heading in data file
      Read (nin, *)
      Read (nin, *) n, nrhs
      lda = n
      ldb = n
      lwork = 64*n
      Allocate (a(lda,n), b(ldb,nrhs), work(lwork), ipiv(n))

!     Read A and B from data file

      Read (nin, *) uplo
      If (uplo=='U') Then
        Read (nin, *)(a(i,i:n), i=1, n)
      Else If (uplo=='L') Then
        Read (nin, *)(a(i,1:i), i=1, n)
      End If
      Read (nin, *)(b(i,1:nrhs), i=1, n)

!     Factorize A
      Call dsytrf(uplo, n, a, lda, ipiv, work, lwork, info)

      Write (nout, *)
      Flush (nout)
      If (info==0) Then

!       Compute solution
        Call dsytrs(uplo, n, nrhs, a, lda, ipiv, b, ldb, info)

!       Print solution

!       ifail: behaviour on error exit
!              =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
        ifail = 0
        Call nagf_file_print_matrix_real_gen('General', ' ', n, nrhs, b, ldb, &
          'Solution(s)', ifail)

      Else
        Write (nout, *) 'The factor D is singular'
      End If

    End Program
Full documentation of DSYTRS


DTBCON example

Computational Routines: Estimate condition number of real band triangular matrix

Data

DTBCON Example Program Data
  4  1                        :Values of N and KD
  'L'                         :Value of UPLO
 -4.16
 -2.25   4.78
         5.86   6.32
               -4.82   0.16   :End of matrix A

Result

 DTBCON Example Program Results

 Estimate of condition number =  6.96E+01

Source

    Program dtbcon_example

!     DTBCON Example Program Text

!     Copyright 2017, Numerical Algorithms Group Ltd. http://www.nag.com

!     .. Use Statements ..
      Use lapack_interfaces, Only: dtbcon
      Use lapack_precision, Only: dp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter :: nin = 5, nout = 6
      Character (1), Parameter :: diag = 'N', norm = '1'
!     .. Local Scalars ..
      Real (Kind=dp) :: rcond
      Integer :: i, info, j, kd, ldab, n
      Character (1) :: uplo
!     .. Local Arrays ..
      Real (Kind=dp), Allocatable :: ab(:, :), work(:)
      Integer, Allocatable :: iwork(:)
!     .. Intrinsic Procedures ..
      Intrinsic :: epsilon, max, min
!     .. Executable Statements ..
      Write (nout, *) 'DTBCON Example Program Results'
!     Skip heading in data file
      Read (nin, *)
      Read (nin, *) n, kd
      ldab = kd + 1
      Allocate (ab(ldab,n), work(3*n), iwork(n))

!     Read A from data file

      Read (nin, *) uplo
      If (uplo=='U') Then
        Do i = 1, n
          Read (nin, *)(ab(kd+1+i-j,j), j=i, min(n,i+kd))
        End Do
      Else If (uplo=='L') Then
        Do i = 1, n
          Read (nin, *)(ab(1+i-j,j), j=max(1,i-kd), i)
        End Do
      End If

!     Estimate condition number
      Call dtbcon(norm, uplo, diag, n, kd, ab, ldab, rcond, work, iwork, info)

      Write (nout, *)
      If (rcond>=epsilon(1.0E0_dp)) Then
        Write (nout, 100) 'Estimate of condition number =', 1.0E0_dp/rcond
      Else
        Write (nout, *) 'A is singular to working precision'
      End If

100   Format (1X, A, 1P, E10.2)
    End Program
Full documentation of DTBCON


DTBRFS example

Computational Routines: Error bounds for solution of real band triangular system of linear equations, multiple right-hand sides

Data

DTBRFS Example Program Data
  4  1  2                     :Values of N, KD and NRHS
  'L'                         :Value of UPLO
 -4.16
 -2.25   4.78
         5.86   6.32
               -4.82   0.16   :End of matrix A
-16.64  -4.16
-13.78 -16.59
 13.10  -4.94
-14.14  -9.96                 :End of matrix B

Result

 DTBRFS Example Program Results

 Solution(s)
             1          2
 1      4.0000     1.0000
 2     -1.0000    -3.0000
 3      3.0000     2.0000
 4      2.0000    -2.0000

 Backward errors (machine-dependent)
       4.7E-17    2.5E-17
 Estimated forward error bounds (machine-dependent)
       5.4E-14    5.8E-14

Source

    Program dtbrfs_example

!     DTBRFS Example Program Text

!     Copyright 2017, Numerical Algorithms Group Ltd. http://www.nag.com

!     .. Use Statements ..
      Use lapack_example_aux, Only: nagf_file_print_matrix_real_gen
      Use lapack_interfaces, Only: dtbrfs, dtbtrs
      Use lapack_precision, Only: dp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter :: nin = 5, nout = 6
      Character (1), Parameter :: diag = 'N', trans = 'N'
!     .. Local Scalars ..
      Integer :: i, ifail, info, j, kd, ldab, ldb, ldx, n, nrhs
      Character (1) :: uplo
!     .. Local Arrays ..
      Real (Kind=dp), Allocatable :: ab(:, :), b(:, :), berr(:), ferr(:), &
        work(:), x(:, :)
      Integer, Allocatable :: iwork(:)
!     .. Intrinsic Procedures ..
      Intrinsic :: max, min
!     .. Executable Statements ..
      Write (nout, *) 'DTBRFS Example Program Results'
!     Skip heading in data file
      Read (nin, *)
      Read (nin, *) n, kd, nrhs
      ldab = kd + 1
      ldb = n
      ldx = n
      Allocate (ab(ldab,n), b(ldb,nrhs), berr(nrhs), ferr(nrhs), work(3*n), &
        x(ldx,n), iwork(n))

!     Read A and B from data file, and copy B to X

      Read (nin, *) uplo
      If (uplo=='U') Then
        Do i = 1, n
          Read (nin, *)(ab(kd+1+i-j,j), j=i, min(n,i+kd))
        End Do
      Else If (uplo=='L') Then
        Do i = 1, n
          Read (nin, *)(ab(1+i-j,j), j=max(1,i-kd), i)
        End Do
      End If
      Read (nin, *)(b(i,1:nrhs), i=1, n)

      x(1:n, 1:nrhs) = b(1:n, 1:nrhs)

!     Compute solution in the array X
      Call dtbtrs(uplo, trans, diag, n, kd, nrhs, ab, ldab, x, ldx, info)

!     Compute backward errors and estimated bounds on the
!     forward errors

      Call dtbrfs(uplo, trans, diag, n, kd, nrhs, ab, ldab, b, ldb, x, ldx, &
        ferr, berr, work, iwork, info)

!     Print solution

      Write (nout, *)
      Flush (nout)

!     ifail: behaviour on error exit
!             =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
      ifail = 0
      Call nagf_file_print_matrix_real_gen('General', ' ', n, nrhs, x, ldx, &
        'Solution(s)', ifail)

      Write (nout, *)
      Write (nout, *) 'Backward errors (machine-dependent)'
      Write (nout, 100) berr(1:nrhs)
      Write (nout, *) 'Estimated forward error bounds (machine-dependent)'
      Write (nout, 100) ferr(1:nrhs)

100   Format ((3X,1P,7E11.1))
    End Program
Full documentation of DTBRFS


DTBTRS example

Computational Routines: Solution of real band triangular system of linear equations, multiple right-hand sides

Data

DTBTRS Example Program Data
  4  1  2                     :Values of N, KD and NRHS
  'L'                         :Value of UPLO
 -4.16
 -2.25   4.78
         5.86   6.32
               -4.82   0.16   :End of matrix A
-16.64  -4.16
-13.78 -16.59
 13.10  -4.94
-14.14  -9.96                 :End of matrix B

Result

 DTBTRS Example Program Results

 Solution(s)
             1          2
 1      4.0000     1.0000
 2     -1.0000    -3.0000
 3      3.0000     2.0000
 4      2.0000    -2.0000

Source

    Program dtbtrs_example

!     DTBTRS Example Program Text

!     Copyright 2017, Numerical Algorithms Group Ltd. http://www.nag.com

!     .. Use Statements ..
      Use lapack_example_aux, Only: nagf_file_print_matrix_real_gen
      Use lapack_interfaces, Only: dtbtrs
      Use lapack_precision, Only: dp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter :: nin = 5, nout = 6
      Character (1), Parameter :: diag = 'N', trans = 'N'
!     .. Local Scalars ..
      Integer :: i, ifail, info, j, kd, ldab, ldb, n, nrhs
      Character (1) :: uplo
!     .. Local Arrays ..
      Real (Kind=dp), Allocatable :: ab(:, :), b(:, :)
!     .. Intrinsic Procedures ..
      Intrinsic :: max, min
!     .. Executable Statements ..
      Write (nout, *) 'DTBTRS Example Program Results'
!     Skip heading in data file
      Read (nin, *)
      Read (nin, *) n, kd, nrhs
      ldab = kd + 1
      ldb = n
      Allocate (ab(ldab,n), b(ldb,nrhs))

!     Read A and B from data file

      Read (nin, *) uplo
      If (uplo=='U') Then
        Do i = 1, n
          Read (nin, *)(ab(kd+1+i-j,j), j=i, min(n,i+kd))
        End Do
      Else If (uplo=='L') Then
        Do i = 1, n
          Read (nin, *)(ab(1+i-j,j), j=max(1,i-kd), i)
        End Do
      End If
      Read (nin, *)(b(i,1:nrhs), i=1, n)

!     Compute solution
      Call dtbtrs(uplo, trans, diag, n, kd, nrhs, ab, ldab, b, ldb, info)

!     Print solution

      Write (nout, *)
      Flush (nout)
      If (info==0) Then

!       ifail: behaviour on error exit
!              =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
        ifail = 0
        Call nagf_file_print_matrix_real_gen('General', ' ', n, nrhs, b, ldb, &
          'Solution(s)', ifail)

      Else
        Write (nout, *) 'A is singular'
      End If

    End Program
Full documentation of DTBTRS


DTFTRI example

Computational Routines: Inverse of real triangular matrix, Rectangular Full Packed format, expert driver

Data

DTFTRI Example Program Data
  4       'L'   'N'   'N' : n, uplo, transr, diag
 -8.02   -5.95
  4.30    0.12
 -3.96   -4.87
  0.40    0.31
 -0.27    0.07            : AR

Result

 DTFTRI Example Program Results

 Inverse
             1          2          3          4
 1      0.2326
 2     -0.1891    -0.2053
 3      0.0043    -0.0079    -0.1247
 4      0.8463    -0.2738    -6.1825     8.3333

Source

    Program dtftri_example

!     DTFTRI Example Program Text

!     Copyright 2017, Numerical Algorithms Group Ltd. http://www.nag.com

!     .. Use Statements ..
      Use lapack_example_aux, Only: nagf_file_print_matrix_real_gen
      Use lapack_interfaces, Only: dtftri, dtfttr
      Use lapack_precision, Only: dp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter :: nin = 5, nout = 6
!     .. Local Scalars ..
      Integer :: i, ifail, info, k, lar1, lda, lenar, n, q
      Character (1) :: diag, transr, uplo
!     .. Local Arrays ..
      Real (Kind=dp), Allocatable :: a(:, :), ar(:)
!     .. Executable Statements ..
      Write (nout, *) 'DTFTRI Example Program Results'
!     Skip heading in data file
      Read (nin, *)
      Read (nin, *) n, uplo, transr, diag

      lenar = n*(n+1)/2
      lda = n
      Allocate (ar(lenar), a(lda,n))

!     Setup notional dimensions of RFP matrix AR
      k = n/2
      q = n - k
      If (transr=='N' .Or. transr=='n') Then
        lar1 = 2*k + 1
      Else
        lar1 = q
      End If

!     Read an RFP matrix into array AR
      Do i = 1, lar1
        Read (nin, *) ar(i:lenar:lar1)
      End Do

!     Compute inverse of A
      Call dtftri(transr, uplo, diag, n, ar, info)

      Write (nout, *)
      Flush (nout)
      If (info==0) Then

!       Convert inverse to full array form, and print it
        Call dtfttr(transr, uplo, n, ar, a, lda, info)
        ifail = 0
        Call nagf_file_print_matrix_real_gen(uplo, 'Nonunit', n, n, a, lda, &
          'Inverse', ifail)
      Else
        Write (nout, *) 'A is singular'
      End If

    End Program
Full documentation of DTFTRI


DTGEVC example

Computational Routines: Left and right eigenvectors of a pair of real upper quasi-triangular matrices

Data

DTGEVC Example Program Data
   5                                                         :Value of N
1.00        1.00        1.00        1.00        1.00
2.00        4.00        8.00       16.00       32.00
3.00        9.00       27.00       81.00      243.00
4.00       16.00       64.00      256.00     1024.00
5.00       25.00      125.00      625.00     3125.00          :End of matrix A
1.00        2.00        3.00        4.00        5.00
1.00        4.00        9.00       16.00       25.00
1.00        8.00       27.00       64.00      125.00
1.00       16.00       81.00      256.00      625.00
1.00       32.00      243.00     1024.00     3125.00          :End of matrix B

Result

 DTGEVC Example Program Results
 Matrix A after balancing
          1       2       3       4       5
 1   1.0000  1.0000  0.1000  0.1000  0.1000
 2   2.0000  4.0000  0.8000  1.6000  3.2000
 3   0.3000  0.9000  0.2700  0.8100  2.4300
 4   0.4000  1.6000  0.6400  2.5600 10.2400
 5   0.5000  2.5000  1.2500  6.2500 31.2500

 Matrix B after balancing
          1       2       3       4       5
 1   1.0000  2.0000  0.3000  0.4000  0.5000
 2   1.0000  4.0000  0.9000  1.6000  2.5000
 3   0.1000  0.8000  0.2700  0.6400  1.2500
 4   0.1000  1.6000  0.8100  2.5600  6.2500
 5   0.1000  3.2000  2.4300 10.2400 31.2500

 Matrix A in Hessenberg form
          1       2       3       4       5
 1  -2.1898 -0.3181  2.0547  4.7371 -4.6249
 2  -0.8395 -0.0426  1.7132  7.5194-17.1850
 3   0.0000 -0.2846 -1.0101 -7.5927 26.4499
 4   0.0000  0.0000  0.0376  1.4070 -3.3643
 5   0.0000  0.0000  0.0000  0.3813 -0.9937

 Matrix B in Hessenberg form
          1       2       3       4       5
 1  -1.4248 -0.3476  2.1175  5.5813 -3.9269
 2   0.0000 -0.0782  0.1189  8.0940-15.2928
 3   0.0000  0.0000  1.0021-10.9356 26.5971
 4   0.0000  0.0000  0.0000  0.5820 -0.0730
 5   0.0000  0.0000  0.0000  0.0000  0.5321

 Minimal required LWORK =      5
 Actual value of  LWORK =     30

 Generalized eigenvalues

    1     ( -2.437,  0.000)
    2     (  0.607,  0.795)
    3     (  0.607, -0.795)
    4     (  1.000,  0.000)
    5     ( -0.410,  0.000)

 Right eigenvectors
          1       2       3       4       5
 1  -0.3083  0.7026  0.0000 -0.3985 -0.3747
 2   0.6622 -0.5582 -0.3678  0.7287  0.7339
 3  -0.6244  0.1600  0.1763 -0.5380 -0.5394
 4   0.2732 -0.0211 -0.0492  0.1423  0.1720
 5  -0.0438  0.0010  0.0072 -0.0199 -0.0192

 Left eigenvectors
          1       2       3       4       5
 1  -0.3747  0.7026  0.0000 -0.3985  0.3083
 2   0.7339 -0.5582 -0.3678  0.7287 -0.6622
 3  -0.5394  0.1600  0.1763 -0.5380  0.6244
 4   0.1720 -0.0211 -0.0492  0.1423 -0.2732
 5  -0.0192  0.0010  0.0072 -0.0199  0.0438

Source

!   DTGEVC Example Program Text
!   Copyright 2017, Numerical Algorithms Group Ltd. http://www.nag.com

    Module dtgevc_mod

!     DTGEVC Example Program Module:
!            Parameters and User-defined Routines

!     .. Use Statements ..
      Use lapack_precision, Only: dp
!     .. Implicit None Statement ..
      Implicit None
!     .. Accessibility Statements ..
      Private
      Public :: normalize
!     .. Parameters ..
      Real (Kind=dp), Parameter, Public :: one = 1.0_dp
      Real (Kind=dp), Parameter, Public :: zero = 0.0_dp
      Integer, Parameter, Public :: nin = 5, nout = 6
    Contains
      Subroutine normalize(n, alphai, v, ldv)

!       .. Use Statements ..
        Use blas_interfaces, Only: dnrm2
!       .. Implicit None Statement ..
        Implicit None
!       .. Scalar Arguments ..
        Integer, Intent (In) :: ldv, n
!       .. Array Arguments ..
        Real (Kind=dp), Intent (In) :: alphai(n)
        Real (Kind=dp), Intent (Inout) :: v(ldv, *)
!       .. Local Scalars ..
        Real (Kind=dp) :: a, b, r, r1, r2, v1, v2
        Integer :: i, j, k
!       .. Intrinsic Procedures ..
        Intrinsic :: sqrt
!       .. Executable Statements ..

        Do j = 1, n

          If (alphai(j)>=0.0_dp) Then
            If (alphai(j)==0.0_dp) Then
!             Real eigenvalue
!             The 2-norm of Q is calculated using dnrm2.
              r = dnrm2(n, v(1,j), 1)
              v(1:n, j) = v(1:n, j)/r
            Else
!             Complex eigenvalue (positive imaginary part)
!             Make largest element real and positive
              r1 = dnrm2(n, v(1,j), 1)
              r2 = dnrm2(n, v(1,j+1), 1)
              r1 = sqrt(r1**2+r2**2)
              r2 = -1.0_dp
              Do i = 1, n
                r = v(i, j)**2 + v(i, j+1)**2
                If (r>r2) Then
                  r2 = r
                  k = i
                End If
              End Do
              r = r1*sqrt(r2)
              a = v(k, j)/r
              b = v(k, j+1)/r
              Do i = 1, n
                v1 = v(i, j)
                v2 = v(i, j+1)
                v(i, j) = v1*a + v2*b
                v(i, j+1) = v2*a - v1*b
              End Do
            End If
          End If
        End Do
      End Subroutine
    End Module
    Program dtgevc_example

!     DTGEVC Example Main Program

!     .. Use Statements ..
      Use dtgevc_mod, Only: nin, normalize, nout, one, zero
      Use lapack_example_aux, Only: nagf_file_print_matrix_real_gen_comp
      Use lapack_interfaces, Only: dgeqrf, dggbak, dggbal, dgghrd, dhgeqz, &
        dlacpy, dlaset, dorgqr, dormqr, dtgevc
      Use lapack_precision, Only: dp
!     .. Implicit None Statement ..
      Implicit None
!     .. Local Scalars ..
      Integer :: i, icols, ifail, ihi, ilo, info, irows, jwork, lda, ldb, &
        ldvl, ldvr, lwork, m, n
      Logical :: ileft, iright
      Character (1) :: compq, compz, howmny, job, side
!     .. Local Arrays ..
      Real (Kind=dp), Allocatable :: a(:, :), alphai(:), alphar(:), b(:, :), &
        beta(:), lscale(:), rscale(:), tau(:), vl(:, :), vr(:, :), work(:)
      Logical, Allocatable :: select(:)
      Character (0) :: clabs(1), rlabs(1)
!     .. Intrinsic Procedures ..
      Intrinsic :: nint
!     .. Executable Statements ..
      Write (nout, *) 'DTGEVC Example Program Results'
      Flush (nout)

!     ileft  is TRUE if left  eigenvectors are required
!     iright is TRUE if right eigenvectors are required

      ileft = .True.
      iright = .True.

!     Skip heading in data file

      Read (nin, *)
      Read (nin, *) n
      lda = n
      ldb = n
      ldvl = n
      ldvr = n
      lwork = 6*n
      Allocate (a(lda,n), alphai(n), alphar(n), b(ldb,n), beta(n), lscale(n), &
        rscale(n), tau(n), vl(ldvl,ldvl), vr(ldvr,ldvr), work(lwork), &
        select(n))

!     READ matrix A from data file
      Read (nin, *)(a(i,1:n), i=1, n)

!     READ matrix B from data file
      Read (nin, *)(b(i,1:n), i=1, n)

!     Balance matrix pair (A,B)
      job = 'B'
      Call dggbal(job, n, a, lda, b, ldb, ilo, ihi, lscale, rscale, work, &
        info)

!     Matrix A after balancing
!     ifail: behaviour on error exit
!             =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
      ifail = 0
      Call nagf_file_print_matrix_real_gen_comp('General', ' ', n, n, a, lda, &
        'F8.4', 'Matrix A after balancing', 'I', rlabs, 'I', clabs, 80, 0, &
        ifail)
      Write (nout, *)
      Flush (nout)

!     Matrix B after balancing
      ifail = 0
      Call nagf_file_print_matrix_real_gen_comp('General', ' ', n, n, b, ldb, &
        'F8.4', 'Matrix B after balancing', 'I', rlabs, 'I', clabs, 80, 0, &
        ifail)
      Write (nout, *)
      Flush (nout)

!     Reduce B to triangular form using QR
      irows = ihi + 1 - ilo
      icols = n + 1 - ilo
      Call dgeqrf(irows, icols, b(ilo,ilo), ldb, tau, work, lwork, info)

!     Apply the orthogonal transformation to matrix A
      Call dormqr('L', 'T', irows, icols, irows, b(ilo,ilo), ldb, tau, &
        a(ilo,ilo), lda, work, lwork, info)

!     Initialize VL (if left eigenvectors are required)
      If (ileft) Then

        Call dlaset('General', n, n, zero, one, vl, ldvl)
        Call dlacpy('Lower', irows-1, irows-1, b(ilo+1,ilo), ldb, &
          vl(ilo+1,ilo), ldvl)

        Call dorgqr(irows, irows, irows, vl(ilo,ilo), ldvl, tau, work, lwork, &
          info)
      End If

!     Initialize VR (if right eigenvectors are required)
      If (iright) Then
        Call dlaset('General', n, n, zero, one, vr, ldvr)
      End If

!     Compute the generalized Hessenberg form of (A,B)
      compq = 'V'
      compz = 'V'
      Call dgghrd(compq, compz, n, ilo, ihi, a, lda, b, ldb, vl, ldvl, vr, &
        ldvr, info)

!     Matrix A in generalized Hessenberg form
      ifail = 0
      Call nagf_file_print_matrix_real_gen_comp('General', ' ', n, n, a, lda, &
        'F8.4', 'Matrix A in Hessenberg form', 'I', rlabs, 'I', clabs, 80, 0, &
        ifail)
      Write (nout, *)
      Flush (nout)

!     Matrix B in generalized Hessenberg form
      ifail = 0
      Call nagf_file_print_matrix_real_gen_comp('General', ' ', n, n, b, ldb, &
        'F8.4', 'Matrix B in Hessenberg form', 'I', rlabs, 'I', clabs, 80, 0, &
        ifail)

!     Routine DHGEQZ
!     Workspace query: jwork = -1

      jwork = -1
      job = 'S'

      Call dhgeqz(job, compq, compz, n, ilo, ihi, a, lda, b, ldb, alphar, &
        alphai, beta, vl, ldvl, vr, ldvr, work, jwork, info)

      Write (nout, *)
      Write (nout, 100) nint(work(1))
      Write (nout, 110) lwork
      Write (nout, *)
      Write (nout, 120)
      Write (nout, 130)

!     Compute the generalized Schur form
!     if the workspace lwork is adequate
!     The Schur form also gives parameters
!     required to compute generalized eigenvalues

      If (nint(work(1))<=lwork) Then

        Call dhgeqz(job, compq, compz, n, ilo, ihi, a, lda, b, ldb, alphar, &
          alphai, beta, vl, ldvl, vr, ldvr, work, lwork, info)

!       Print the generalized eigenvalues

        Do i = 1, n
          If (beta(i)/=0.0E0_dp) Then
            Write (nout, 140) i, '(', alphar(i)/beta(i), ',', &
              alphai(i)/beta(i), ')'
          Else
            Write (nout, 130) i
          End If
        End Do
        Write (nout, *)
        Flush (nout)

!       Compute left and right generalized eigenvectors
!       of the balanced matrix

        howmny = 'B'
        If (ileft .And. iright) Then
          side = 'B'
        Else If (ileft) Then
          side = 'L'
        Else If (iright) Then
          side = 'R'
        End If

        Call dtgevc(side, howmny, select, n, a, lda, b, ldb, vl, ldvl, vr, &
          ldvr, n, m, work, info)

        If (iright) Then

!         Compute right eigenvectors of the original matrix

          job = 'B'
          side = 'R'

          Call dggbak(job, side, n, ilo, ihi, lscale, rscale, n, vr, ldvr, &
            info)

          Call normalize(n, alphai, vr, ldvr)
!         Print the right eigenvectors

          ifail = 0
          Call nagf_file_print_matrix_real_gen_comp('General', ' ', n, n, vr, &
            ldvr, 'F8.4', 'Right eigenvectors', 'I', rlabs, 'I', clabs, 80, 0, &
            ifail)

          Write (nout, *)
          Flush (nout)
        End If

!       Compute left eigenvectors of the original matrix

        If (ileft) Then
          job = 'B'
          side = 'L'

          Call dggbak(job, side, n, ilo, ihi, lscale, rscale, n, vl, ldvl, &
            info)

          Call normalize(n, alphai, vl, ldvl)
!         Print the left eigenvectors

          ifail = 0
          Call nagf_file_print_matrix_real_gen_comp('General', ' ', n, n, vl, &
            ldvl, 'F8.4', 'Left eigenvectors', 'I', rlabs, 'I', clabs, 80, 0, &
            ifail)

        End If
      Else
        Write (nout, 150)
      End If

100   Format (1X, 'Minimal required LWORK = ', I6)
110   Format (1X, 'Actual value of  LWORK = ', I6)
120   Format (1X, 'Generalized eigenvalues')
130   Format (1X, I4, 5X, 'Infinite eigenvalue')
140   Format (1X, I4, 5X, A, F7.3, A, F7.3, A)
150   Format (1X, 'Insufficient workspace for array WORK', /, ' in DHGEQZ/', &
        'DHGEQZ')
    End Program
Full documentation of DTGEVC


DTGEXC example

Computational Routines: Reorders the generalized real Schur decomposition of a real matrix pair using an orthogonal equivalence transformation

Data

DTGEXC Example Program Data
  4                    :Value of N
  4.0  1.0  1.0  2.0
  0.0  3.0  4.0  1.0
  0.0  1.0  3.0  1.0
  0.0  0.0  0.0  6.0   :End of matrix A
  2.0  1.0  1.0  3.0
  0.0  1.0  2.0  1.0
  0.0  0.0  1.0  1.0
  0.0  0.0  0.0  2.0   :End of matrix B
  2  1                 :Values of IFST and ILST

Result

 DTGEXC Example Program Results

 Reordered Schur matrix A
             1          2          3          4
 1      4.1926     1.2591     2.5578     0.4520
 2     -0.8712     0.8627     2.7912     1.1383
 3      0.0000     0.0000     4.2426     2.1213
 4      0.0000     0.0000     0.0000     6.0000

 Reordered Schur matrix B
             1          2          3          4
 1      1.7439     0.0000     0.7533     0.0661
 2      0.0000     0.5406     1.8972     1.7308
 3      0.0000     0.0000     2.1213     2.8284
 4      0.0000     0.0000     0.0000     2.0000

Source

    Program dtgexc_example

!     DTGEXC Example Program Text

!     Copyright 2017, Numerical Algorithms Group Ltd. http://www.nag.com

!     .. Use Statements ..
      Use lapack_example_aux, Only: nagf_file_print_matrix_real_gen
      Use lapack_interfaces, Only: dtgexc
      Use lapack_precision, Only: dp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter :: nin = 5, nout = 6
      Logical, Parameter :: wantq = .False., wantz = .False.
!     .. Local Scalars ..
      Integer :: i, ifail, ifst, ilst, info, lda, ldb, ldq, ldz, lwork, n
!     .. Local Arrays ..
      Real (Kind=dp), Allocatable :: a(:, :), b(:, :), q(:, :), work(:), &
        z(:, :)
!     .. Executable Statements ..
      Write (nout, *) 'DTGEXC Example Program Results'
      Write (nout, *)
      Flush (nout)
!     Skip heading in data file
      Read (nin, *)
      Read (nin, *) n
      ldq = 1
      ldz = 1
      lda = n
      ldb = n
      lwork = 4*n + 16
      Allocate (a(lda,n), b(ldb,n), q(ldq,1), work(lwork), z(ldz,1))

!     Read A and B from data file

      Read (nin, *)(a(i,1:n), i=1, n)
      Read (nin, *)(b(i,1:n), i=1, n)

!     Read the row indices

      Read (nin, *) ifst, ilst

!     Reorder A and B

      Call dtgexc(wantq, wantz, n, a, lda, b, ldb, q, ldq, z, ldz, ifst, ilst, &
        work, lwork, info)

      If (info/=0) Then
        Write (nout, 100) info, ilst
        Write (nout, *)
        Flush (nout)
      End If

!     The resulting reordered Schur matrices can differ by +- signs by
!     multiplying rows and columns of Q and Z by -1. We will normalize here by
!     making the diagonals and last column of B positive.
      Call normalize(a, b)

!     Print reordered generalized Schur form

!     ifail: behaviour on error exit
!             =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
      ifail = 0
      Call nagf_file_print_matrix_real_gen('General', ' ', n, n, a, lda, &
        'Reordered Schur matrix A', ifail)

      Write (nout, *)
      Flush (nout)

      ifail = 0
      Call nagf_file_print_matrix_real_gen('General', ' ', n, n, b, ldb, &
        'Reordered Schur matrix B', ifail)

100   Format (' Reordering could not be completed. INFO = ', I3, ' ILST = ', &
        I5)

    Contains
      Subroutine normalize(a, b)

!       .. Array Arguments ..
        Real (Kind=dp), Intent (Inout) :: a(lda, n), b(ldb, n)
!       .. Local Scalars ..
        Integer :: i, j
!       .. Intrinsic Procedures ..
        Intrinsic :: max
!       .. Executable Statements ..

!       Last column of B positive
        Do i = 1, n
          j = max(1, i-1)
          If (b(i,n)<0.0_dp) Then
            a(i, j:n) = -a(i, j:n)
            b(i, i:n) = -b(i, i:n)
          End If
        End Do

!       Diagonals of B positive
        Do i = 1, n - 1
          If (b(i,i)<0.0_dp) Then
            a(1:i+1, i) = -a(1:i+1, i)
            b(1:i, i) = -b(1:i, i)
          End If
        End Do
      End Subroutine
    End Program
Full documentation of DTGEXC


DTGSEN example

Computational Routines: Reorders the generalized real Schur decomposition of a real matrix pair using an orthogonal equivalence transformation, computes the generalized eigenvalues of the reordered pair and, optionally, computes the estimates of reciprocal condition numbers for eigenvalues and eigenspaces

Data

DTGSEN Example Program Data
  4                    :Value of N
  4.0  1.0  1.0  2.0
  0.0  3.0  4.0  1.0
  0.0  1.0  3.0  1.0
  0.0  0.0  0.0  6.0   :End of matrix A
  2.0  1.0  1.0  3.0
  0.0  1.0  2.0  1.0
  0.0  0.0  1.0  1.0
  0.0  0.0  0.0  2.0   :End of matrix B
  1.0  0.0  0.0  0.0
  0.0  1.0  0.0  0.0
  0.0  0.0  1.0  0.0
  0.0  0.0  0.0  1.0   :End of matrix Q
  1.0  0.0  0.0  0.0
  0.0  1.0  0.0  0.0
  0.0  0.0  1.0  0.0
  0.0  0.0  0.0  1.0   :End of matrix Z
  T    F    F    T     :End of SELECT

Result

 DTGSEN Example Program Results

Warning: Floating underflow occurred
 Number of selected eigenvalues  =    2

 Selected Generalized Eigenvalues

  1 ( 2.0000E+00, 0.0000E+00)
  2 ( 3.0000E+00, 0.0000E+00)

 Norm estimate of projection onto left  eigenspace for selected cluster
   2.69E+00

 Norm estimate of projection onto right eigenspace for selected cluster
   1.50E+00

 F-norm based upper bound on Difu
   2.52E-01

 F-norm based upper bound on Difl
   2.45E-01

Source

    Program dtgsen_example

!     DTGSEN Example Program Text

!     Copyright 2017, Numerical Algorithms Group Ltd. http://www.nag.com

!     .. Use Statements ..
      Use lapack_interfaces, Only: dtgsen
      Use lapack_precision, Only: dp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=dp) :: pl, pr
      Integer :: i, ijob, info, lda, ldb, ldc, ldq, ldz, liwork, lwork, m, n
      Logical :: wantq, wantz
!     .. Local Arrays ..
      Real (Kind=dp), Allocatable :: a(:, :), alphai(:), alphar(:), b(:, :), &
        beta(:), c(:, :), q(:, :), work(:), z(:, :)
      Real (Kind=dp) :: dif(2)
      Integer, Allocatable :: iwork(:)
      Logical, Allocatable :: select(:)
!     .. Executable Statements ..
      Write (nout, *) 'DTGSEN Example Program Results'
      Write (nout, *)
      Flush (nout)
!     Skip heading in data file
      Read (nin, *)
      Read (nin, *) n
      lda = n
      ldb = n
      ldc = n
      ldq = n
      ldz = n
      liwork = (n*n)/2 + 6
      lwork = n*(n+4) + 16
      Allocate (a(lda,n), alphai(n), alphar(n), b(ldb,n), beta(n), c(ldc,n), &
        q(ldq,n), work(lwork), z(ldz,n), iwork(liwork), select(n))

!     Read A, B, Q, Z and the logical array SELECT from data file

      Read (nin, *)(a(i,1:n), i=1, n)
      Read (nin, *)(b(i,1:n), i=1, n)
      Read (nin, *)(q(i,1:n), i=1, n)
      Read (nin, *)(z(i,1:n), i=1, n)

      Read (nin, *) select(1:n)

!     Set ijob, wantq and wantz
      ijob = 4
      wantq = .True.
      wantz = .True.

!     Reorder the Schur factors A and B and update the matrices
!     Q and Z

      Call dtgsen(ijob, wantq, wantz, select, n, a, lda, b, ldb, alphar, &
        alphai, beta, q, ldq, z, ldz, m, pl, pr, dif, work, lwork, iwork, &
        liwork, info)

      If (info>0) Then
        Write (nout, 100) info
        Write (nout, *)
        Flush (nout)
      End If

!     Print Results
      Write (nout, 130) 'Number of selected eigenvalues  = ', m
      Write (nout, *)
      Write (nout, *) 'Selected Generalized Eigenvalues'
      Write (nout, *)
      Write (nout, 120)(i, alphar(i)/beta(i), alphai(i)/beta(i), i=1, m)

      Write (nout, *)
      Write (nout, 110) 'Norm estimate of projection onto', &
        ' left  eigenspace for selected cluster', 1.0_dp/pl
      Write (nout, *)
      Write (nout, 110) 'Norm estimate of projection onto', &
        ' right eigenspace for selected cluster', 1.0_dp/pr
      Write (nout, *)
      Write (nout, 110) 'F-norm based upper bound on', ' Difu', dif(1)
      Write (nout, *)
      Write (nout, 110) 'F-norm based upper bound on', ' Difl', dif(2)

100   Format (' Reordering could not be completed. INFO = ', I3)
110   Format (1X, 2A, /, 1X, 1P, E10.2)
120   Format (1X, I2, 1X, '(', 1P, E11.4, ',', E11.4, ')')
130   Format (1X, A, I4)
    End Program
Full documentation of DTGSEN


DTGSJA example

Computational Routines: Computes the generalized singular value decomposition of a real upper triangular (or trapezoidal) matrix pair

Data

DTGSJA Example Program Data

  4    3    2   :Values of M, N and P

  1.0  2.0  3.0
  3.0  2.0  1.0
  4.0  5.0  6.0
  7.0  8.0  8.0 :End of matrix A

 -2.0 -3.0  3.0
  4.0  6.0  5.0 :End of matrix B

Result

 DTGSJA Example Program Results

 Number of infinite generalized singular values (K)
     1
 Number of finite generalized singular values (L)
     2
  Effective Numerical rank of (A**T B**T)**T (K+L)
     3

 Finite generalized singular values
     1.3151E+00  8.0185E-02

 Orthogonal matrix U
              1           2           3           4
 1  -1.3484E-01  5.2524E-01 -2.0924E-01  8.1373E-01
 2   6.7420E-01 -5.2213E-01 -3.8886E-01  3.4874E-01
 3   2.6968E-01  5.2757E-01 -6.5782E-01 -4.6499E-01
 4   6.7420E-01  4.1615E-01  6.1014E-01  1.5127E-15

 Orthogonal matrix V
              1           2
 1   3.5539E-01 -9.3472E-01
 2   9.3472E-01  3.5539E-01

 Orthogonal matrix Q
              1           2           3
 1  -8.3205E-01 -9.4633E-02 -5.4657E-01
 2   5.5470E-01 -1.4195E-01 -8.1985E-01
 3   0.0000E+00 -9.8534E-01  1.7060E-01

 Nonsingular upper triangular matrix R
              1           2           3
 1  -2.0569E+00 -9.0121E+00 -9.3705E+00
 2              -1.0882E+01 -7.2688E+00
 3                          -6.0405E+00

 Number of cycles of the Kogbetliantz method
     2

Source

    Program dtgsja_example

!     DTGSJA Example Program Text

!     Copyright 2017, Numerical Algorithms Group Ltd. http://www.nag.com

!     .. Use Statements ..
      Use lapack_example_aux, Only: nagf_file_print_matrix_real_gen_comp
      Use lapack_interfaces, Only: dggsvp3, dlange, dtgsja
      Use lapack_precision, Only: dp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=dp) :: eps, tola, tolb
      Integer :: i, ifail, info, irank, j, k, l, lda, ldb, ldq, ldu, ldv, &
        lwork, m, n, ncycle, p
!     .. Local Arrays ..
      Real (Kind=dp), Allocatable :: a(:, :), alpha(:), b(:, :), beta(:), &
        q(:, :), tau(:), u(:, :), v(:, :), work(:)
      Real (Kind=dp) :: wdum(1)
      Integer, Allocatable :: iwork(:)
      Character (1) :: clabs(1), rlabs(1)
!     .. Intrinsic Procedures ..
      Intrinsic :: epsilon, max, nint, real
!     .. Executable Statements ..
      Write (nout, *) 'DTGSJA Example Program Results'
      Write (nout, *)
      Flush (nout)
!     Skip heading in data file
      Read (nin, *)
      Read (nin, *) m, n, p
      lda = m
      ldb = p
      ldq = n
      ldu = m
      ldv = p
      Allocate (a(lda,n), alpha(n), b(ldb,n), beta(n), q(ldq,n), tau(n), &
        u(ldu,m), v(ldv,p), iwork(n))

!     Determine maximum workspace needed by dggsvp3 and dtgsja
      Call dggsvp3('U', 'V', 'Q', m, p, n, a, lda, b, ldb, tola, tolb, k, l, &
        u, ldu, v, ldv, q, ldq, iwork, tau, wdum, -1, info)
      lwork = max(nint(wdum(1)), 2*n)
      Allocate (work(lwork))

!     Read the m by n matrix A and p by n matrix B from data file

      Read (nin, *)(a(i,1:n), i=1, m)
      Read (nin, *)(b(i,1:n), i=1, p)

!     Compute tola and tolb as
!         tola = max(m,n)*norm(A)*macheps
!         tolb = max(p,n)*norm(B)*macheps

      eps = epsilon(1.0E0_dp)
      tola = real(max(m,n), kind=dp)*dlange('One-norm', m, n, a, lda, work)* &
        eps
      tolb = real(max(p,n), kind=dp)*dlange('One-norm', p, n, b, ldb, work)* &
        eps

!     Compute the factorization of (A, B)
!         (A = U1*S*(Q1**T), B = V1*T*(Q1**T))
      Call dggsvp3('U', 'V', 'Q', m, p, n, a, lda, b, ldb, tola, tolb, k, l, &
        u, ldu, v, ldv, q, ldq, iwork, tau, work, lwork, info)

!     Compute the generalized singular value decomposition of (A, B)
!         (A = U*D1*(0 R)*(Q**T), B = V*D2*(0 R)*(Q**T))
      Call dtgsja('U', 'V', 'Q', m, p, n, k, l, a, lda, b, ldb, tola, tolb, &
        alpha, beta, u, ldu, v, ldv, q, ldq, work, ncycle, info)

      If (info==0) Then

!       Print solution

        irank = k + l
        Write (nout, *) 'Number of infinite generalized singular values (K)'
        Write (nout, 100) k
        Write (nout, *) 'Number of finite generalized singular values (L)'
        Write (nout, 100) l
        Write (nout, *) ' Effective Numerical rank of (A**T B**T)**T (K+L)'
        Write (nout, 100) irank
        Write (nout, *)
        Write (nout, *) 'Finite generalized singular values'
        Write (nout, 110)(alpha(j)/beta(j), j=k+1, irank)

        Write (nout, *)
        Flush (nout)

!       ifail: behaviour on error exit
!              =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
        ifail = 0
        Call nagf_file_print_matrix_real_gen_comp('General', ' ', m, m, u, &
          ldu, '1P,E12.4', 'Orthogonal matrix U', 'Integer', rlabs, 'Integer', &
          clabs, 80, 0, ifail)

        Write (nout, *)
        Flush (nout)

        Call nagf_file_print_matrix_real_gen_comp('General', ' ', p, p, v, &
          ldv, '1P,E12.4', 'Orthogonal matrix V', 'Integer', rlabs, 'Integer', &
          clabs, 80, 0, ifail)

        Write (nout, *)
        Flush (nout)

        Call nagf_file_print_matrix_real_gen_comp('General', ' ', n, n, q, &
          ldq, '1P,E12.4', 'Orthogonal matrix Q', 'Integer', rlabs, 'Integer', &
          clabs, 80, 0, ifail)

        Write (nout, *)
        Flush (nout)

        Call nagf_file_print_matrix_real_gen_comp('Upper triangular', &
          'Non-unit', irank, irank, a(1,n-irank+1), lda, '1P,E12.4', &
          'Nonsingular upper triangular matrix R', 'Integer', rlabs, &
          'Integer', clabs, 80, 0, ifail)

        Write (nout, *)
        Write (nout, *) 'Number of cycles of the Kogbetliantz method'
        Write (nout, 100) ncycle
      Else
        Write (nout, 120) 'Failure in DTGSJA. INFO =', info
      End If

100   Format (1X, I5)
110   Format (3X, 8(1P,E12.4))
120   Format (1X, A, I4)
    End Program
Full documentation of DTGSJA


DTGSNA example

Computational Routines: Estimates reciprocal condition numbers for specified eigenvalues and/or eigenvectors of a real matrix pair in generalized real Schur canonical form

Data

DTGSNA Example Program Data
  4                    :Value of N
  4.0  1.0  1.0  2.0
  0.0  3.0 -1.0  1.0
  0.0  1.0  3.0  1.0
  0.0  0.0  0.0  6.0   :End of matrix A
  2.0  1.0  1.0  3.0
  0.0  1.0  0.0  1.0
  0.0  0.0  1.0  1.0
  0.0  0.0  0.0  2.0   :End of matrix B

Result

Warning: Floating underflow occurred
 DTGSNA Example Program Results

 S
       1.6E+00    1.7E+00    1.7E+00    1.4E+00

 DIF
       5.4E-01    1.5E-01    1.5E-01    1.2E-01

 Approximate error estimates for eigenvalues of (A,B)
       1.7E-15    1.6E-15    1.6E-15    2.0E-15

 Approximate error estimates for right eigenvectors of (A,B)
       5.0E-15    1.8E-14    1.8E-14    2.2E-14

Source

    Program dtgsna_example

!     DTGSNA Example Program Text

!     Copyright 2017, Numerical Algorithms Group Ltd. http://www.nag.com

!     .. Use Statements ..
      Use lapack_example_aux, Only: nagf_blas_dpyth
      Use lapack_interfaces, Only: dlange, dtgevc, dtgsna
      Use lapack_precision, Only: dp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=dp) :: eps, snorm, stnrm, tnorm
      Integer :: i, info, lda, ldb, ldvl, ldvr, lwork, m, n
!     .. Local Arrays ..
      Real (Kind=dp), Allocatable :: a(:, :), b(:, :), dif(:), s(:), vl(:, :), &
        vr(:, :), work(:)
      Integer, Allocatable :: iwork(:)
      Logical :: select(1)
!     .. Intrinsic Procedures ..
      Intrinsic :: epsilon
!     .. Executable Statements ..
      Write (nout, *) 'DTGSNA Example Program Results'
      Write (nout, *)
!     Skip heading in data file
      Read (nin, *)
      Read (nin, *) n
      lda = n
      ldb = n
      ldvl = n
      ldvr = n
      lwork = 2*n*(n+2) + 16
      Allocate (a(lda,n), b(ldb,n), dif(n), s(n), vl(ldvl,n), vr(ldvr,n), &
        work(lwork), iwork(n+6))

!     Read A and B from data file

      Read (nin, *)(a(i,1:n), i=1, n)
      Read (nin, *)(b(i,1:n), i=1, n)

!     Calculate the left and right generalized eigenvectors of the
!     pair (A,B). Note that DTGEVC requires WORK to be of dimension
!     at least 6*n.

      Call dtgevc('Both', 'All', select, n, a, lda, b, ldb, vl, ldvl, vr, &
        ldvr, n, m, work, info)

      If (info>0) Then
        Write (nout, 100) info, info + 1
      Else

!       Estimate condition numbers for all the generalized eigenvalues
!       and right eigenvectors of the pair (A,B)

        Call dtgsna('Both', 'All', select, n, a, lda, b, ldb, vl, ldvl, vr, &
          ldvr, s, dif, n, m, work, lwork, iwork, info)

!       Print condition numbers of eigenvalues and right eigenvectors

        Write (nout, *) 'S'
        Write (nout, 110) s(1:m)
        Write (nout, *)
        Write (nout, *) 'DIF'
        Write (nout, 110) dif(1:m)

!       Calculate approximate error estimates

!       Compute the 1-norms of A and B and then compute
!       SQRT(snorm**2 + tnorm**2)

        eps = epsilon(1.0E0_dp)
        snorm = dlange('1-norm', n, n, a, lda, work)
        tnorm = dlange('1-norm', n, n, b, ldb, work)
        stnrm = nagf_blas_dpyth(snorm, tnorm)
        Write (nout, *)
        Write (nout, *) 'Approximate error estimates for eigenvalues of (A,B)'
        Write (nout, 110)(eps*stnrm/s(i), i=1, m)
        Write (nout, *)
        Write (nout, *) 'Approximate error estimates for right ', &
          'eigenvectors of (A,B)'
        Write (nout, 110)(eps*stnrm/dif(i), i=1, m)
      End If

100   Format (' The 2-by-2 block (', I5, ':', I5, ') does not have a co', &
        'mplex eigenvalue')
110   Format ((3X,1P,7E11.1))
    End Program
Full documentation of DTGSNA


DTGSYL example

Computational Routines: Solves the real-valued generalized Sylvester equation

Data

DTGSYL Example Program Data
  4  4                        :Values of M and N
  4.0   1.0   1.0   2.0
  0.0   3.0   4.0   1.0
  0.0   1.0   3.0   1.0
  0.0   0.0   0.0   6.0   :End of matrix A
  1.0   1.0   1.0   1.0
  0.0   3.0   4.0   1.0
  0.0   1.0   3.0   1.0
  0.0   0.0   0.0   4.0   :End of matrix B
  2.0   1.0   1.0   3.0
  0.0   1.0   2.0   1.0
  0.0   0.0   1.0   1.0
  0.0   0.0   0.0   2.0   :End of matrix D
  1.0   1.0   1.0   2.0
  0.0   1.0   4.0   1.0
  0.0   0.0   1.0   1.0
  0.0   0.0   0.0   1.0   :End of matrix E
 -4.0   7.0   1.0  12.0
 -9.0   2.0  -2.0  -2.0
 -4.0   2.0  -2.0   8.0
 -7.0   7.0  -6.0  19.0   :End of matrix C
 -7.0   5.0   0.0   7.0
 -5.0   1.0  -8.0   0.0
 -1.0   2.0  -3.0   5.0
 -3.0   2.0   0.0   5.0   :End of matrix F

Result

 DTGSYL Example Program Results

 Solution matrix R
             1          2          3          4
 1      1.0000     1.0000     1.0000     1.0000
 2     -1.0000     2.0000    -1.0000    -1.0000
 3     -1.0000     1.0000     3.0000     1.0000
 4     -1.0000     1.0000    -1.0000     4.0000

 Solution matrix L
             1          2          3          4
 1      4.0000    -1.0000     1.0000    -1.0000
 2      1.0000     3.0000    -1.0000     1.0000
 3     -1.0000     1.0000     2.0000    -1.0000
 4      1.0000    -1.0000     1.0000     1.0000

 SCALE =   1.00E+00

Source

    Program dtgsyl_example

!     DTGSYL Example Program Text

!     Copyright 2017, Numerical Algorithms Group Ltd. http://www.nag.com

!     .. Use Statements ..
      Use lapack_example_aux, Only: nagf_file_print_matrix_real_gen
      Use lapack_interfaces, Only: dtgsyl
      Use lapack_precision, Only: dp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=dp) :: dif, scale
      Integer :: i, ifail, ijob, info, lda, ldb, ldc, ldd, lde, ldf, lwork, m, &
        n
!     .. Local Arrays ..
      Real (Kind=dp), Allocatable :: a(:, :), b(:, :), c(:, :), d(:, :), &
        e(:, :), f(:, :), work(:)
      Integer, Allocatable :: iwork(:)
!     .. Executable Statements ..
      Write (nout, *) 'DTGSYL Example Program Results'
      Write (nout, *)
      Flush (nout)
!     Skip heading in data file
      Read (nin, *)
      Read (nin, *) m, n
      lda = m
      ldb = n
      ldc = m
      ldd = m
      lde = n
      ldf = m
      lwork = 1
      Allocate (a(lda,m), b(ldb,n), c(ldc,n), d(ldd,m), e(lde,n), f(ldf,n), &
        work(lwork), iwork(m+n+6))

!     Read A, B, D, E, C and F from data file

      Read (nin, *)(a(i,1:m), i=1, m)
      Read (nin, *)(b(i,1:n), i=1, n)
      Read (nin, *)(d(i,1:m), i=1, m)
      Read (nin, *)(e(i,1:n), i=1, n)
      Read (nin, *)(c(i,1:n), i=1, m)
      Read (nin, *)(f(i,1:n), i=1, m)

!     Solve the Sylvester equations
!         A*R - L*B = scale*C and D*R - L*E = scale*F
!     for R and L.
      ijob = 0

      Call dtgsyl('No transpose', ijob, m, n, a, lda, b, ldb, c, ldc, d, ldd, &
        e, lde, f, ldf, scale, dif, work, lwork, iwork, info)

      If (info>=1) Then
        Write (nout, 100)
        Write (nout, *)
        Flush (nout)
      End If

!     Print the solution matrices R and L

!     ifail: behaviour on error exit
!             =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
      ifail = 0
      Call nagf_file_print_matrix_real_gen('General', ' ', m, n, c, ldc, &
        'Solution matrix R', ifail)

      Write (nout, *)
      Flush (nout)

      ifail = 0
      Call nagf_file_print_matrix_real_gen('General', ' ', m, n, f, ldf, &
        'Solution matrix L', ifail)

      Write (nout, *)
      Write (nout, 110) 'SCALE = ', scale

100   Format (/, ' (A,D) and (B,E) have common or very close eigenval', &
        'ues.', /, ' Perturbed values were used to solve the equations')
110   Format (1X, A, 1P, E10.2)
    End Program
Full documentation of DTGSYL


DTPCON example

Computational Routines: Estimate condition number of real triangular matrix, packed storage

Data

DTPCON Example Program Data
  4                           :Value of N
  'L'                         :Value of UPLO
  4.30
 -3.96  -4.87
  0.40   0.31  -8.02
 -0.27   0.07  -5.95   0.12   :End of matrix A

Result

 DTPCON Example Program Results

 Estimate of condition number =  1.16E+02

Source

    Program dtpcon_example

!     DTPCON Example Program Text

!     Copyright 2017, Numerical Algorithms Group Ltd. http://www.nag.com

!     .. Use Statements ..
      Use lapack_interfaces, Only: dtpcon
      Use lapack_precision, Only: dp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter :: nin = 5, nout = 6
      Character (1), Parameter :: diag = 'N', norm = '1'
!     .. Local Scalars ..
      Real (Kind=dp) :: rcond
      Integer :: i, info, j, n
      Character (1) :: uplo
!     .. Local Arrays ..
      Real (Kind=dp), Allocatable :: ap(:), work(:)
      Integer, Allocatable :: iwork(:)
!     .. Intrinsic Procedures ..
      Intrinsic :: epsilon
!     .. Executable Statements ..
      Write (nout, *) 'DTPCON Example Program Results'
!     Skip heading in data file
      Read (nin, *)
      Read (nin, *) n

      Allocate (ap(n*(n+1)/2), work(3*n), iwork(n))

!     Read A from data file

      Read (nin, *) uplo
      If (uplo=='U') Then
        Read (nin, *)((ap(i+j*(j-1)/2),j=i,n), i=1, n)
      Else If (uplo=='L') Then
        Read (nin, *)((ap(i+(2*n-j)*(j-1)/2),j=1,i), i=1, n)
      End If

!     Estimate condition number
      Call dtpcon(norm, uplo, diag, n, ap, rcond, work, iwork, info)

      Write (nout, *)
      If (rcond>=epsilon(1.0E0_dp)) Then
        Write (nout, 100) 'Estimate of condition number =', 1.0E0_dp/rcond
      Else
        Write (nout, *) 'A is singular to working precision'
      End If

100   Format (1X, A, 1P, E10.2)
    End Program
Full documentation of DTPCON


DTPQRT example

Computational Routines: QR factorization of real general triangular-pentagonal matrix

Data

DTPQRT Example Program Data

  6      4      2           : m, n and nrhs

 -0.57  -1.28  -0.39   0.25
 -1.93   1.08  -0.31  -2.14
  2.30   0.24   0.40  -0.35
 -1.93   0.64  -0.66   0.08
  0.15   0.30   0.15  -2.13
 -0.02   1.03  -1.43   0.50 : matrix A

 -2.67   0.41
 -0.55  -3.10
  3.34  -4.01
 -0.77   2.76
  0.48  -6.17
  4.10   0.21               : matrix B

Result

 DTPQRT Example Program Results

 solution(s) for n rows
             1          2
 1      1.5179    -1.5850
 2      1.8629     0.5531
 3     -1.4608     1.3485
 4      0.0398     2.9619

 Least squares solution(s) for all rows
             1          2
 1      1.5339    -1.5753
 2      1.8707     0.5559
 3     -1.5241     1.3119
 4      0.0392     2.9585

 Square root(s) of the residual sum(s) of squares
        2.22E-02   1.38E-02

Source

    Program dtpqrt_example

!     DTPQRT Example Program Text

!     Copyright 2017, Numerical Algorithms Group Ltd. http://www.nag.com

!     .. Use Statements ..
      Use blas_interfaces, Only: dnrm2
      Use lapack_example_aux, Only: nagf_file_print_matrix_real_gen
      Use lapack_interfaces, Only: dgemqrt, dgeqrt, dtpmqrt, dtpqrt, dtrtrs
      Use lapack_precision, Only: dp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter :: nbmax = 64, nin = 5, nout = 6
!     .. Local Scalars ..
      Integer :: i, ifail, info, j, lda, ldb, ldt, lwork, m, n, nb, nrhs
!     .. Local Arrays ..
      Real (Kind=dp), Allocatable :: a(:, :), b(:, :), c(:, :), rnorm(:), &
        t(:, :), work(:)
!     .. Intrinsic Procedures ..
      Intrinsic :: max, min
!     .. Executable Statements ..
      Write (nout, *) 'DTPQRT Example Program Results'
      Write (nout, *)
      Flush (nout)
!     Skip heading in data file
      Read (nin, *)
      Read (nin, *) m, n, nrhs
      lda = m
      ldb = m
      nb = min(m, n, nbmax)
      ldt = nb
      lwork = nb*max(n, m)
      Allocate (a(lda,n), b(ldb,nrhs), c(ldb,nrhs), rnorm(nrhs), t(ldt,min(m, &
        n)), work(lwork))

!     Read A and B from data file

      Read (nin, *)(a(i,1:n), i=1, m)
      Read (nin, *)(b(i,1:nrhs), i=1, m)

      c(1:m, 1:nrhs) = b(1:m, 1:nrhs)
!     Compute the QR factorization of first n rows of A
      Call dgeqrt(n, n, nb, a, lda, t, ldt, work, info)

!     Compute C = (C1) = (Q**T)*B, storing the result in C
!                  (C2)
      Call dgemqrt('Left', 'Transpose', n, nrhs, n, nb, a, lda, t, ldt, c, &
        ldb, work, info)

      b(1:n, 1:nrhs) = c(1:n, 1:nrhs)
!     Compute least squares solutions for first n rows by back-substitution in
!     R*X = C1
      Call dtrtrs('Upper', 'No transpose', 'Non-Unit', n, nrhs, a, lda, c, &
        ldb, info)

      If (info>0) Then
        Write (nout, *) 'The upper triangular factor, R, of A is singular, '
        Write (nout, *) 'the least squares solution could not be computed'
      Else

!       Print solution using first n rows

!       ifail: behaviour on error exit
!              =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
        ifail = 0
        Call nagf_file_print_matrix_real_gen('General', ' ', n, nrhs, c, ldb, &
          'solution(s) for n rows', ifail)

      End If

!     Now add the remaining rows and perform QR update
      Call dtpqrt(m-n, n, 0, nb, a, lda, a(n+1,1), lda, t, ldt, work, info)

!     Apply orthogonal transformations to C
      Call dtpmqrt('Left', 'Transpose', m-n, nrhs, n, 0, nb, a(n+1,1), lda, t, &
        ldt, b, ldb, b(5,1), ldb, work, info)
!     Compute least squares solutions for first n rows by bac-substitution in
!     R*X = C1
      Call dtrtrs('Upper', 'No transpose', 'Non-Unit', n, nrhs, a, lda, b, &
        ldb, info)

      If (info>0) Then
        Write (nout, *) 'The upper triangular factor, R, of A is singular, '
        Write (nout, *) 'the least squares solution could not be computed'
      Else

!       Print least squares solutions
        Write (nout, *)
        Flush (nout)
        ifail = 0
        Call nagf_file_print_matrix_real_gen('G', ' ', n, nrhs, b, ldb, &
          'Least squares solution(s) for all rows', ifail)

!       Compute and print estimates of the square roots of the residual
!       sums of squares

        Do j = 1, nrhs
          rnorm(j) = dnrm2(m-n, b(n+1,j), 1)
        End Do

        Write (nout, *)
        Write (nout, *) 'Square root(s) of the residual sum(s) of squares'
        Write (nout, 100) rnorm(1:nrhs)
      End If

100   Format (5X, 1P, 7E11.2)
    End Program
Full documentation of DTPQRT


DTPRFS example

Computational Routines: Error bounds for solution of real triangular system of linear equations, multiple right-hand sides, packed storage

Data

DTPRFS Example Program Data
  4  2                        :Values of N and NRHS
  'L'                         :Value of UPLO
  4.30
 -3.96  -4.87
  0.40   0.31  -8.02
 -0.27   0.07  -5.95   0.12   :End of matrix A
-12.90 -21.50
 16.75  14.93
-17.55   6.33
-11.04   8.09                 :End of matrix B

Result

 DTPRFS Example Program Results

 Solution(s)
             1          2
 1     -3.0000    -5.0000
 2     -1.0000     1.0000
 3      2.0000    -1.0000
 4      1.0000     6.0000

 Backward errors (machine-dependent)
       6.9E-17    0.0E+00
 Estimated forward error bounds (machine-dependent)
       8.3E-14    2.6E-14

Source

    Program dtprfs_example

!     DTPRFS Example Program Text

!     Copyright 2017, Numerical Algorithms Group Ltd. http://www.nag.com

!     .. Use Statements ..
      Use lapack_example_aux, Only: nagf_file_print_matrix_real_gen
      Use lapack_interfaces, Only: dtprfs, dtptrs
      Use lapack_precision, Only: dp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter :: nin = 5, nout = 6
      Character (1), Parameter :: diag = 'N', trans = 'N'
!     .. Local Scalars ..
      Integer :: i, ifail, info, j, ldb, ldx, n, nrhs
      Character (1) :: uplo
!     .. Local Arrays ..
      Real (Kind=dp), Allocatable :: ap(:), b(:, :), berr(:), ferr(:), &
        work(:), x(:, :)
      Integer, Allocatable :: iwork(:)
!     .. Executable Statements ..
      Write (nout, *) 'DTPRFS Example Program Results'
!     Skip heading in data file
      Read (nin, *)
      Read (nin, *) n, nrhs
      ldb = n
      ldx = n
      Allocate (ap(n*(n+1)/2), b(ldb,nrhs), berr(nrhs), ferr(nrhs), work(3*n), &
        x(ldx,n), iwork(n))

!     Read A and B from data file, and copy B to X

      Read (nin, *) uplo
      If (uplo=='U') Then
        Read (nin, *)((ap(i+j*(j-1)/2),j=i,n), i=1, n)
      Else If (uplo=='L') Then
        Read (nin, *)((ap(i+(2*n-j)*(j-1)/2),j=1,i), i=1, n)
      End If
      Read (nin, *)(b(i,1:nrhs), i=1, n)

      x(1:n, 1:nrhs) = b(1:n, 1:nrhs)

!     Compute solution in the array X
      Call dtptrs(uplo, trans, diag, n, nrhs, ap, x, ldx, info)

!     Compute backward errors and estimated bounds on the
!     forward errors

      Call dtprfs(uplo, trans, diag, n, nrhs, ap, b, ldb, x, ldx, ferr, berr, &
        work, iwork, info)

!     Print solution

      Write (nout, *)
      Flush (nout)

!     ifail: behaviour on error exit
!             =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
      ifail = 0
      Call nagf_file_print_matrix_real_gen('General', ' ', n, nrhs, x, ldx, &
        'Solution(s)', ifail)

      Write (nout, *)
      Write (nout, *) 'Backward errors (machine-dependent)'
      Write (nout, 100) berr(1:nrhs)
      Write (nout, *) 'Estimated forward error bounds (machine-dependent)'
      Write (nout, 100) ferr(1:nrhs)

100   Format ((3X,1P,7E11.1))
    End Program
Full documentation of DTPRFS


DTPTRI example

Computational Routines: Inverse of real triangular matrix, packed storage

Data

DTPTRI Example Program Data
  4                           :Value of N
  'L'                         :Value of UPLO
  4.30
 -3.96  -4.87
  0.40   0.31  -8.02
 -0.27   0.07  -5.95   0.12   :End of matrix A

Result

 DTPTRI Example Program Results

 Inverse
             1          2          3          4
 1      0.2326
 2     -0.1891    -0.2053
 3      0.0043    -0.0079    -0.1247
 4      0.8463    -0.2738    -6.1825     8.3333

Source

    Program dtptri_example

!     DTPTRI Example Program Text

!     Copyright 2017, Numerical Algorithms Group Ltd. http://www.nag.com

!     .. Use Statements ..
      Use lapack_example_aux, Only: nagf_file_print_matrix_real_packed
      Use lapack_interfaces, Only: dtptri
      Use lapack_precision, Only: dp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter :: nin = 5, nout = 6
      Character (1), Parameter :: diag = 'N'
!     .. Local Scalars ..
      Integer :: i, ifail, info, j, n
      Character (1) :: uplo
!     .. Local Arrays ..
      Real (Kind=dp), Allocatable :: ap(:)
!     .. Executable Statements ..
      Write (nout, *) 'DTPTRI Example Program Results'
!     Skip heading in data file
      Read (nin, *)
      Read (nin, *) n

      Allocate (ap(n*(n+1)/2))

!     Read A from data file

      Read (nin, *) uplo
      If (uplo=='U') Then
        Read (nin, *)((ap(i+j*(j-1)/2),j=i,n), i=1, n)
      Else If (uplo=='L') Then
        Read (nin, *)((ap(i+(2*n-j)*(j-1)/2),j=1,i), i=1, n)
      End If

!     Compute inverse of A
      Call dtptri(uplo, diag, n, ap, info)

!     Print inverse

      Write (nout, *)
      Flush (nout)

!     ifail: behaviour on error exit
!             =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
      ifail = 0
      Call nagf_file_print_matrix_real_packed(uplo, diag, n, ap, 'Inverse', &
        ifail)

    End Program
Full documentation of DTPTRI


DTPTRS example

Computational Routines: Solution of real triangular system of linear equations, multiple right-hand sides, packed storage

Data

DTPTRS Example Program Data
  4  2                        :Values of N and NRHS
  'L'                         :Value of UPLO
  4.30
 -3.96  -4.87
  0.40   0.31  -8.02
 -0.27   0.07  -5.95   0.12   :End of matrix A
-12.90 -21.50
 16.75  14.93
-17.55   6.33
-11.04   8.09                 :End of matrix B

Result

 DTPTRS Example Program Results

 Solution(s)
             1          2
 1     -3.0000    -5.0000
 2     -1.0000     1.0000
 3      2.0000    -1.0000
 4      1.0000     6.0000

Source

    Program dtptrs_example

!     DTPTRS Example Program Text

!     Copyright 2017, Numerical Algorithms Group Ltd. http://www.nag.com

!     .. Use Statements ..
      Use lapack_example_aux, Only: nagf_file_print_matrix_real_gen
      Use lapack_interfaces, Only: dtptrs
      Use lapack_precision, Only: dp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter :: nin = 5, nout = 6
      Character (1), Parameter :: diag = 'N', trans = 'N'
!     .. Local Scalars ..
      Integer :: i, ifail, info, j, ldb, n, nrhs
      Character (1) :: uplo
!     .. Local Arrays ..
      Real (Kind=dp), Allocatable :: ap(:), b(:, :)
!     .. Executable Statements ..
      Write (nout, *) 'DTPTRS Example Program Results'
!     Skip heading in data file
      Read (nin, *)
      Read (nin, *) n, nrhs
      ldb = n
      Allocate (ap(n*(n+1)/2), b(ldb,nrhs))

!     Read A and B from data file

      Read (nin, *) uplo
      If (uplo=='U') Then
        Read (nin, *)((ap(i+j*(j-1)/2),j=i,n), i=1, n)
      Else If (uplo=='L') Then
        Read (nin, *)((ap(i+(2*n-j)*(j-1)/2),j=1,i), i=1, n)
      End If
      Read (nin, *)(b(i,1:nrhs), i=1, n)

!     Compute solution
      Call dtptrs(uplo, trans, diag, n, nrhs, ap, b, ldb, info)

!     Print solution

      Write (nout, *)
      Flush (nout)
      If (info==0) Then

!       ifail: behaviour on error exit
!              =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
        ifail = 0
        Call nagf_file_print_matrix_real_gen('General', ' ', n, nrhs, b, ldb, &
          'Solution(s)', ifail)

      Else
        Write (nout, *) 'A is singular'
      End If

    End Program
Full documentation of DTPTRS


DTRCON example

Computational Routines: Estimate condition number of real triangular matrix

Data

DTRCON Example Program Data
  4                           :Value of N
  'L'                         :Value of UPLO
  4.30
 -3.96  -4.87
  0.40   0.31  -8.02
 -0.27   0.07  -5.95   0.12   :End of matrix A

Result

 DTRCON Example Program Results

 Estimate of condition number =  1.16E+02

Source

    Program dtrcon_example

!     DTRCON Example Program Text

!     Copyright 2017, Numerical Algorithms Group Ltd. http://www.nag.com

!     .. Use Statements ..
      Use lapack_interfaces, Only: dtrcon
      Use lapack_precision, Only: dp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter :: nin = 5, nout = 6
      Character (1), Parameter :: diag = 'N', norm = '1'
!     .. Local Scalars ..
      Real (Kind=dp) :: rcond
      Integer :: i, info, lda, n
      Character (1) :: uplo
!     .. Local Arrays ..
      Real (Kind=dp), Allocatable :: a(:, :), work(:)
      Integer, Allocatable :: iwork(:)
!     .. Intrinsic Procedures ..
      Intrinsic :: epsilon
!     .. Executable Statements ..
      Write (nout, *) 'DTRCON Example Program Results'
!     Skip heading in data file
      Read (nin, *)
      Read (nin, *) n
      lda = n
      Allocate (a(lda,n), work(3*n), iwork(n))

!     Read A from data file

      Read (nin, *) uplo
      If (uplo=='U') Then
        Read (nin, *)(a(i,i:n), i=1, n)
      Else If (uplo=='L') Then
        Read (nin, *)(a(i,1:i), i=1, n)
      End If

!     Estimate condition number
      Call dtrcon(norm, uplo, diag, n, a, lda, rcond, work, iwork, info)

      Write (nout, *)
      If (rcond>=epsilon(1.0E0_dp)) Then
        Write (nout, 100) 'Estimate of condition number =', 1.0E0_dp/rcond
      Else
        Write (nout, *) 'A is singular to working precision'
      End If

100   Format (1X, A, 1P, E10.2)
    End Program
Full documentation of DTRCON


DTREXC example

Computational Routines: Reorder Schur factorization of real matrix using orthogonal similarity transformation

Data

DTREXC Example Program Data
  4                           :Value of N
  0.80  -0.11   0.01   0.03
  0.00  -0.10   0.25   0.35
  0.00  -0.65  -0.10   0.20
  0.00   0.00   0.00  -0.10   :End of matrix T
  2  1                        :Values of IFST and ILST

Result

 DTREXC Example Program Results

 Reordered Schur form
          1       2       3       4
 1  -0.1000 -0.6463  0.0874  0.2010
 2   0.2514 -0.1000  0.0927  0.3505
 3   0.0000  0.0000  0.8000 -0.0117
 4   0.0000  0.0000  0.0000 -0.1000

Source

    Program dtrexc_example

!     DTREXC Example Program Text

!     Copyright 2017, Numerical Algorithms Group Ltd. http://www.nag.com

!     .. Use Statements ..
      Use lapack_example_aux, Only: nagf_file_print_matrix_real_gen
      Use lapack_interfaces, Only: dtrexc
      Use lapack_precision, Only: dp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter :: nin = 5, nout = 6
!     .. Local Scalars ..
      Integer :: i, ifail, ifst, ilst, info, ldq, ldt, n
!     .. Local Arrays ..
      Real (Kind=dp), Allocatable :: q(:, :), t(:, :), work(:)
!     .. Executable Statements ..
      Write (nout, *) 'DTREXC Example Program Results'
      Write (nout, *)
      Flush (nout)
!     Skip heading in data file
      Read (nin, *)
      Read (nin, *) n
      ldq = 1
      ldt = n
      Allocate (q(ldq,1), t(ldt,n), work(n))

!     Read T from data file

      Read (nin, *)(t(i,1:n), i=1, n)

!     Read the row indices

      Read (nin, *) ifst, ilst

!     Reorder the Schur factor T

      Call dtrexc('No update', n, t, ldt, q, ldq, ifst, ilst, work, info)
      If (info>0) Then
        Write (nout, 100) info, ilst
        Write (nout, *)
        Flush (nout)
      End If

!     Print reordered Schur factor

!     ifail: behaviour on error exit
!             =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
      ifail = 0
      Call nagf_file_print_matrix_real_gen('General', ' ', n, n, t, ldt, &
        'Reordered Schur form', ifail)

100   Format (' Reordering could not be completed. INFO = ', I3, ' ILST = ', &
        I5)
    End Program
Full documentation of DTREXC


DTRRFS example

Computational Routines: Error bounds for solution of real triangular system of linear equations, multiple right-hand sides

Data

DTRRFS Example Program Data
  4  2                        :Values of N and NRHS
  'L'                         :Value of UPLO
  4.30
 -3.96  -4.87
  0.40   0.31  -8.02
 -0.27   0.07  -5.95   0.12   :End of matrix A
-12.90 -21.50
 16.75  14.93
-17.55   6.33
-11.04   8.09                 :End of matrix B

Result

 DTRRFS Example Program Results

 Solution(s)
             1          2
 1     -3.0000    -5.0000
 2     -1.0000     1.0000
 3      2.0000    -1.0000
 4      1.0000     6.0000

 Backward errors (machine-dependent)
       6.9E-17    0.0E+00
 Estimated forward error bounds (machine-dependent)
       8.3E-14    2.6E-14

Source

    Program dtrrfs_example

!     DTRRFS Example Program Text

!     Copyright 2017, Numerical Algorithms Group Ltd. http://www.nag.com

!     .. Use Statements ..
      Use lapack_example_aux, Only: nagf_file_print_matrix_real_gen
      Use lapack_interfaces, Only: dtrrfs, dtrtrs
      Use lapack_precision, Only: dp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter :: nin = 5, nout = 6
      Character (1), Parameter :: diag = 'N', trans = 'N'
!     .. Local Scalars ..
      Integer :: i, ifail, info, lda, ldb, ldx, n, nrhs
      Character (1) :: uplo
!     .. Local Arrays ..
      Real (Kind=dp), Allocatable :: a(:, :), b(:, :), berr(:), ferr(:), &
        work(:), x(:, :)
      Integer, Allocatable :: iwork(:)
!     .. Executable Statements ..
      Write (nout, *) 'DTRRFS Example Program Results'
!     Skip heading in data file
      Read (nin, *)
      Read (nin, *) n, nrhs
      lda = n
      ldb = n
      ldx = n
      Allocate (a(lda,n), b(ldb,nrhs), berr(nrhs), ferr(nrhs), work(3*n), &
        x(ldx,n), iwork(n))

!     Read A and B from data file, and copy B to X

      Read (nin, *) uplo
      If (uplo=='U') Then
        Read (nin, *)(a(i,i:n), i=1, n)
      Else If (uplo=='L') Then
        Read (nin, *)(a(i,1:i), i=1, n)
      End If
      Read (nin, *)(b(i,1:nrhs), i=1, n)

      x(1:n, 1:nrhs) = b(1:n, 1:nrhs)

!     Compute solution in the array X
      Call dtrtrs(uplo, trans, diag, n, nrhs, a, lda, x, ldx, info)

!     Compute backward errors and estimated bounds on the
!     forward errors

      Call dtrrfs(uplo, trans, diag, n, nrhs, a, lda, b, ldb, x, ldx, ferr, &
        berr, work, iwork, info)

!     Print solution

      Write (nout, *)
      Flush (nout)

!     ifail: behaviour on error exit
!             =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
      ifail = 0
      Call nagf_file_print_matrix_real_gen('General', ' ', n, nrhs, x, ldx, &
        'Solution(s)', ifail)

      Write (nout, *)
      Write (nout, *) 'Backward errors (machine-dependent)'
      Write (nout, 100) berr(1:nrhs)
      Write (nout, *) 'Estimated forward error bounds (machine-dependent)'
      Write (nout, 100) ferr(1:nrhs)

100   Format ((3X,1P,7E11.1))
    End Program
Full documentation of DTRRFS


DTRSEN example

Computational Routines: Reorder Schur factorization of real matrix, form orthonormal basis of right invariant subspace for selected eigenvalues, with estimates of sensitivities

Data

DTRSEN Example Program Data
  4                                   :Value of N
  0.7995  -0.1144   0.0060   0.0336
  0.0000  -0.0994   0.2478   0.3474
  0.0000  -0.6483  -0.0994   0.2026
  0.0000   0.0000   0.0000  -0.1007   :End of matrix T
  0.6551   0.1037   0.3450   0.6641
  0.5236  -0.5807  -0.6141  -0.1068
 -0.5362  -0.3073  -0.2935   0.7293
  0.0956   0.7467  -0.6463   0.1249   :End of matrix Q
  T   F   F   T                       :End of SELECT

Result

 DTRSEN Example Program Results

 Matrix A computed from Q*T*Q^T
          1       2       3       4
 1   0.3500  0.4500 -0.1400 -0.1700
 2   0.0900  0.0700 -0.5399  0.3500
 3  -0.4400 -0.3300 -0.0300  0.1700
 4   0.2500 -0.3200 -0.1300  0.1100

 Condition number estimate of the selected cluster of eigenvalues =   1.75E+00

 Condition number estimate of the specified invariant subspace    =   3.22E+00

Source

    Program dtrsen_example

!     DTRSEN Example Program Text

!     Copyright 2017, Numerical Algorithms Group Ltd. http://www.nag.com

!     .. Use Statements ..
      Use blas_interfaces, Only: dgemm
      Use lapack_example_aux, Only: nagf_file_print_matrix_real_gen
      Use lapack_interfaces, Only: dlange, dtrsen
      Use lapack_precision, Only: dp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=dp) :: alpha, beta, norm, s, sep
      Integer :: i, ifail, info, lda, ldc, ldq, ldt, liwork, lwork, m, n
!     .. Local Arrays ..
      Real (Kind=dp), Allocatable :: a(:, :), c(:, :), q(:, :), t(:, :), &
        wi(:), work(:), wr(:)
      Integer, Allocatable :: iwork(:)
      Logical, Allocatable :: select(:)
!     .. Intrinsic Procedures ..
      Intrinsic :: epsilon
!     .. Executable Statements ..
      Write (nout, *) 'DTRSEN Example Program Results'
      Write (nout, *)
      Flush (nout)
!     Skip heading in data file
      Read (nin, *)
      Read (nin, *) n
      lda = n
      ldc = n
      ldq = n
      ldt = n
      liwork = (n*n)/4
      lwork = (n*n)/2
      Allocate (a(lda,n), c(ldc,n), q(ldq,n), t(ldt,n), wi(n), work(lwork), &
        wr(n), iwork(liwork), select(n))

!     Read T, Q and the logical array SELECT from data file

      Read (nin, *)(t(i,1:n), i=1, n)
      Read (nin, *)(q(i,1:n), i=1, n)

      Read (nin, *) select(1:n)

!     Compute Q * T * Q**T to find  A
      alpha = 1._dp
      beta = 0._dp
      Call dgemm('N', 'N', n, n, n, alpha, q, ldq, t, ldt, beta, c, ldc)
      Call dgemm('N', 'T', n, n, n, alpha, c, ldc, q, ldq, beta, a, lda)

!     Print Matrix A, as computed from Q * T * Q**T
!     ifail: behaviour on error exit
!            =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
      ifail = 0
      Call nagf_file_print_matrix_real_gen('General', ' ', n, n, a, lda, &
        'Matrix A computed from Q*T*Q^T', ifail)

      Write (nout, *)
      Flush (nout)

!     Reorder the Schur factor T and update the matrix Q to obtain TT and QT

      Call dtrsen('Both', 'Vectors', select, n, t, ldt, q, ldq, wr, wi, m, s, &
        sep, work, lwork, iwork, liwork, info)

!     Compute (Q * T * Q^T) - (QT * TT * QT^T) and store in A,
!     i.e. the difference between reconstructed A using Schur and reordered
!          Schur decompositions.
      alpha = 1._dp
      beta = 0._dp
      Call dgemm('N', 'N', n, n, n, alpha, q, ldq, t, ldt, beta, c, ldc)
      alpha = -1._dp
      beta = 1._dp
      Call dgemm('N', 'T', n, n, n, alpha, c, ldc, q, ldq, beta, a, lda)

!     Find norm of difference matrix and print warning if it is too large
      norm = dlange('O', lda, n, a, lda, work)
      If (norm>epsilon(1.0E0_dp)**0.8_dp) Then
        Write (nout, *) 'Norm of A - (QT * TT * QT^T) is much greater than 0.'
        Write (nout, *) 'Schur factorization has failed.'
      Else
!       Print Result
        Write (nout, 100) 'Condition number estimate', &
          ' of the selected cluster of eigenvalues = ', 1.0_dp/s
        Write (nout, *)
        Write (nout, 100) 'Condition number estimate of the spec', &
          'ified invariant subspace    = ', 1.0_dp/sep
      End If

100   Format (1X, A, A, 1P, E10.2)
    End Program
Full documentation of DTRSEN


DTRSNA example

Computational Routines: Estimates of sensitivities of selected eigenvalues and eigenvectors of real upper quasi-triangular matrix

Data

DTRSNA Example Program Data
  4                                   :Value of N
  0.7995  -0.1144   0.0060   0.0336
  0.0000  -0.0994   0.2478   0.3474
  0.0000  -0.6483  -0.0994   0.2026
  0.0000   0.0000   0.0000  -0.1007   :End of matrix T

Result

 DTRSNA Example Program Results

 S
       9.9E-01    7.0E-01    7.0E-01    5.7E-01

 SEP
       6.3E-01    3.7E-01    3.7E-01    3.1E-01

 Approximate error estimates for eigenvalues of T (machine-dependent)
       1.9E-16    2.7E-16    2.7E-16    3.4E-16

 Approximate error estimates for right eigenvectors of T (machine-dependent)
       3.1E-16    5.1E-16    5.1E-16    6.1E-16

Source

    Program dtrsna_example

!     DTRSNA Example Program Text

!     Copyright 2017, Numerical Algorithms Group Ltd. http://www.nag.com

!     .. Use Statements ..
      Use lapack_interfaces, Only: dlange, dtrevc, dtrsna
      Use lapack_precision, Only: dp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=dp) :: eps, tnorm
      Integer :: i, info, ldt, ldvl, ldvr, ldwork, m, n
!     .. Local Arrays ..
      Real (Kind=dp), Allocatable :: s(:), sep(:), t(:, :), vl(:, :), &
        vr(:, :), work(:, :)
      Integer, Allocatable :: iwork(:)
      Logical :: select(1)
!     .. Intrinsic Procedures ..
      Intrinsic :: epsilon
!     .. Executable Statements ..
      Write (nout, *) 'DTRSNA Example Program Results'
      Write (nout, *)
!     Skip heading in data file
      Read (nin, *)
      Read (nin, *) n
      ldt = n
      ldvl = n
      ldvr = n
      ldwork = n
      Allocate (s(n), sep(n), t(ldt,n), vl(ldvl,n), vr(ldvr,n), &
        work(ldwork,n+6), iwork(2*n-1))

!     Read T from data file

      Read (nin, *)(t(i,1:n), i=1, n)

!     Calculate the left and right eigenvectors of T

      Call dtrevc('Both', 'All', select, n, t, ldt, vl, ldvl, vr, ldvr, n, m, &
        work, info)

!     Estimate condition numbers for all the eigenvalues and right
!     eigenvectors of T

      Call dtrsna('Both', 'All', select, n, t, ldt, vl, ldvl, vr, ldvr, s, &
        sep, n, m, work, ldwork, iwork, info)

!     Print condition numbers of eigenvalues and right eigenvectors

      Write (nout, *) 'S'
      Write (nout, 100) s(1:m)
      Write (nout, *)
      Write (nout, *) 'SEP'
      Write (nout, 100) sep(1:m)

!     Calculate approximate error estimates (using the 1-norm)

      eps = epsilon(1.0E0_dp)
      tnorm = dlange('1-norm', n, n, t, ldt, work)
      Write (nout, *)
      Write (nout, *) 'Approximate error estimates for eigenvalues ', &
        'of T (machine-dependent)'
      Write (nout, 100)(eps*tnorm/s(i), i=1, m)
      Write (nout, *)
      Write (nout, *) 'Approximate error estimates for right ', &
        'eigenvectors of T (machine-dependent)'
      Write (nout, 100)(eps*tnorm/sep(i), i=1, m)

100   Format ((3X,1P,7E11.1))
    End Program
Full documentation of DTRSNA


DTRSYL example

Computational Routines: Solve real Sylvester matrix equation AX + XB = C, A and B are upper quasi-triangular or transposes

Data

DTRSYL Example Program Data
  4  4                        :Values of M and N
  0.10   0.50   0.68  -0.21
 -0.50   0.10  -0.24   0.67
  0.00   0.00   0.19  -0.35
  0.00   0.00   0.00  -0.72   :End of matrix A
 -0.99  -0.17   0.39   0.58
  0.00   0.48  -0.84  -0.15
  0.00   0.00   0.75   0.25
  0.00   0.00  -0.25   0.75   :End of matrix B
  0.63  -0.56   0.08  -0.23
 -0.45  -0.31   0.27   1.21
  0.20  -0.35   0.41   0.84
  0.49  -0.05  -0.52  -0.08   :End of matrix C

Result

 DTRSYL Example Program Results

 Solution Matrix
          1       2       3       4
 1  -0.4209  0.1764  0.2438 -0.9577
 2   0.5600 -0.8337 -0.7221  0.5386
 3  -0.1246 -0.3392  0.6221  0.8691
 4  -0.2865  0.4113  0.5535  0.3174

Source

    Program dtrsyl_example

!     DTRSYL Example Program Text

!     Copyright 2017, Numerical Algorithms Group Ltd. http://www.nag.com

!     .. Use Statements ..
      Use lapack_example_aux, Only: nagf_file_print_matrix_real_gen
      Use lapack_interfaces, Only: dtrsyl
      Use lapack_precision, Only: dp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=dp) :: scale
      Integer :: i, ifail, info, lda, ldb, ldc, m, n, sign
!     .. Local Arrays ..
      Real (Kind=dp), Allocatable :: a(:, :), b(:, :), c(:, :)
!     .. Executable Statements ..
      Write (nout, *) 'DTRSYL Example Program Results'
      Write (nout, *)
      Flush (nout)
!     Skip heading in data file
      Read (nin, *)
      Read (nin, *) m, n
      lda = m
      ldb = n
      ldc = m
      sign = 1
      Allocate (a(lda,m), b(ldb,n), c(ldc,n))

!     Read A, B and C from data file

      Read (nin, *)(a(i,1:m), i=1, m)
      Read (nin, *)(b(i,1:n), i=1, n)
      Read (nin, *)(c(i,1:n), i=1, m)

!     Solve the Sylvester equation A*X + X*B = C for X
      Call dtrsyl('No transpose', 'No transpose', sign, m, n, a, lda, b, ldb, &
        c, ldc, scale, info)
      If (info==1) Then
        Write (nout, 100)
        Write (nout, *)
      End If

      Flush (nout)

!     Print X
!     ifail: behaviour on error exit
!             =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
      ifail = 0
      Call nagf_file_print_matrix_real_gen('General', ' ', m, n, c, ldc, &
        'Solution Matrix', ifail)

100   Format (/, ' A and B have common or very close eigenvalues.', /, ' Pe', &
        'rturbed values were used to solve the equations')
    End Program
Full documentation of DTRSYL


DTRTRI example

Computational Routines: Inverse of real triangular matrix

Data

DTRTRI Example Program Data
  4                           :Value of N
  'L'                         :Value of UPLO
  4.30
 -3.96  -4.87
  0.40   0.31  -8.02
 -0.27   0.07  -5.95   0.12   :End of matrix A

Result

 DTRTRI Example Program Results

 Inverse
             1          2          3          4
 1      0.2326
 2     -0.1891    -0.2053
 3      0.0043    -0.0079    -0.1247
 4      0.8463    -0.2738    -6.1825     8.3333

Source

    Program dtrtri_example

!     DTRTRI Example Program Text

!     Copyright 2017, Numerical Algorithms Group Ltd. http://www.nag.com

!     .. Use Statements ..
      Use lapack_example_aux, Only: nagf_file_print_matrix_real_gen
      Use lapack_interfaces, Only: dtrtri
      Use lapack_precision, Only: dp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter :: nin = 5, nout = 6
      Character (1), Parameter :: diag = 'N'
!     .. Local Scalars ..
      Integer :: i, ifail, info, lda, n
      Character (1) :: uplo
!     .. Local Arrays ..
      Real (Kind=dp), Allocatable :: a(:, :)
!     .. Executable Statements ..
      Write (nout, *) 'DTRTRI Example Program Results'
!     Skip heading in data file
      Read (nin, *)
      Read (nin, *) n
      lda = n
      Allocate (a(lda,n))

!     Read A from data file

      Read (nin, *) uplo
      If (uplo=='U') Then
        Read (nin, *)(a(i,i:n), i=1, n)
      Else If (uplo=='L') Then
        Read (nin, *)(a(i,1:i), i=1, n)
      End If

!     Compute inverse of A
      Call dtrtri(uplo, diag, n, a, lda, info)

!     Print inverse

      Write (nout, *)
      Flush (nout)

!     ifail: behaviour on error exit
!             =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
      ifail = 0
      Call nagf_file_print_matrix_real_gen(uplo, diag, n, n, a, lda, &
        'Inverse', ifail)

    End Program
Full documentation of DTRTRI


DTRTRS example

Computational Routines: Solution of real triangular system of linear equations, multiple right-hand sides

Data

DTRTRS Example Program Data
  4  2                        :Values of N and NRHS
  'L'                         :Value of UPLO
  4.30
 -3.96  -4.87
  0.40   0.31  -8.02
 -0.27   0.07  -5.95   0.12   :End of matrix A
-12.90 -21.50
 16.75  14.93
-17.55   6.33
-11.04   8.09                 :End of matrix B

Result

 DTRTRS Example Program Results

 Solution(s)
             1          2
 1     -3.0000    -5.0000
 2     -1.0000     1.0000
 3      2.0000    -1.0000
 4      1.0000     6.0000

Source

    Program dtrtrs_example

!     DTRTRS Example Program Text

!     Copyright 2017, Numerical Algorithms Group Ltd. http://www.nag.com

!     .. Use Statements ..
      Use lapack_example_aux, Only: nagf_file_print_matrix_real_gen
      Use lapack_interfaces, Only: dtrtrs
      Use lapack_precision, Only: dp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter :: nin = 5, nout = 6
      Character (1), Parameter :: diag = 'N', trans = 'N'
!     .. Local Scalars ..
      Integer :: i, ifail, info, lda, ldb, n, nrhs
      Character (1) :: uplo
!     .. Local Arrays ..
      Real (Kind=dp), Allocatable :: a(:, :), b(:, :)
!     .. Executable Statements ..
      Write (nout, *) 'DTRTRS Example Program Results'
!     Skip heading in data file
      Read (nin, *)
      Read (nin, *) n, nrhs
      lda = n
      ldb = n
      Allocate (a(lda,n), b(ldb,nrhs))

!     Read A and B from data file

      Read (nin, *) uplo
      If (uplo=='U') Then
        Read (nin, *)(a(i,i:n), i=1, n)
      Else If (uplo=='L') Then
        Read (nin, *)(a(i,1:i), i=1, n)
      End If
      Read (nin, *)(b(i,1:nrhs), i=1, n)

!     Compute solution

      Call dtrtrs(uplo, trans, diag, n, nrhs, a, lda, b, ldb, info)

!     Print solution

      Write (nout, *)
      Flush (nout)
      If (info==0) Then

!       ifail: behaviour on error exit
!              =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
        ifail = 0
        Call nagf_file_print_matrix_real_gen('General', ' ', n, nrhs, b, ldb, &
          'Solution(s)', ifail)

      Else
        Write (nout, *) 'A is singular'
      End If

    End Program
Full documentation of DTRTRS


DTZRZF example

Computational Routines: Reduces a real upper trapezoidal matrix to upper triangular form

Data

DTZRZF Example Program Data

  6  5  2                          :Values of M, N and NRHS

 -0.09   0.14  -0.46   0.68   1.29
 -1.56   0.20   0.29   1.09   0.51
 -1.48  -0.43   0.89  -0.71  -0.96
 -1.09   0.84   0.77   2.11  -1.27
  0.08   0.55  -1.13   0.14   1.74
 -1.59  -0.72   1.06   1.24   0.34 :End of matrix A

  7.4    2.7
  4.2   -3.0
 -8.3   -9.6
  1.8    1.1
  8.6    4.0
  2.1   -5.7                       :End of matrix B

Result

 DTZRZF Example Program Results

 Tolerance used to estimate the rank of A
        1.00E-02
 Estimated rank of A
        4

 Least squares solution(s)
             1          2
 1      0.6344     3.6258
 2      0.9699     1.8284
 3     -1.4402    -1.6416
 4      3.3678     2.4307
 5      3.3992     0.2818

 Square root(s) of the residual sum(s) of squares
        2.54E-02   3.65E-02

Source

    Program dtzrzf_example

!     DTZRZF Example Program Text

!     Copyright 2017, Numerical Algorithms Group Ltd. http://www.nag.com

!     .. Use Statements ..
      Use blas_interfaces, Only: dnrm2, dtrsm
      Use lapack_example_aux, Only: nagf_file_print_matrix_real_gen
      Use lapack_interfaces, Only: dgeqp3, dormqr, dormrz, dtzrzf
      Use lapack_precision, Only: dp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Real (Kind=dp), Parameter :: one = 1.0E0_dp
      Real (Kind=dp), Parameter :: zero = 0.0E0_dp
      Integer, Parameter :: inc1 = 1, nb = 64, nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=dp) :: tol
      Integer :: i, ifail, info, j, k, lda, ldb, lwork, m, n, nrhs
!     .. Local Arrays ..
      Real (Kind=dp), Allocatable :: a(:, :), b(:, :), rnorm(:), tau(:), &
        work(:)
      Integer, Allocatable :: jpvt(:)
!     .. Intrinsic Procedures ..
      Intrinsic :: abs
!     .. Executable Statements ..
      Write (nout, *) 'DTZRZF Example Program Results'
      Write (nout, *)
!     Skip heading in data file
      Read (nin, *)
      Read (nin, *) m, n, nrhs
      lda = m
      ldb = m
      lwork = 2*n + (n+1)*nb
      Allocate (a(lda,n), b(ldb,nrhs), rnorm(n), tau(n), work(lwork), jpvt(n))

!     Read A and B from data file

      Read (nin, *)(a(i,1:n), i=1, m)
      Read (nin, *)(b(i,1:nrhs), i=1, m)

!     Initialize JPVT to be zero so that all columns are free

      jpvt(1:n) = 0

!     Compute the QR factorization of A with column pivoting as
!     A = Q*(R11 R12)*(P**T)
!            ( 0  R22)

      Call dgeqp3(m, n, a, lda, jpvt, tau, work, lwork, info)

!     Compute C = (C1) = (Q**T)*B, storing the result in B
!                  (C2)
      Call dormqr('Left', 'Transpose', m, nrhs, n, a, lda, tau, b, ldb, work, &
        lwork, info)

!     Choose TOL to reflect the relative accuracy of the input data

      tol = 0.01_dp

!     Determine and print the rank, K, of R relative to TOL

loop: Do k = 1, n
        If (abs(a(k,k))<=tol*abs(a(1,1))) Then
          Exit loop
        End If
      End Do loop
      k = k - 1

      Write (nout, *) 'Tolerance used to estimate the rank of A'
      Write (nout, 100) tol
      Write (nout, *) 'Estimated rank of A'
      Write (nout, 110) k
      Write (nout, *)
      Flush (nout)

!     Compute the RZ factorization of the K by K part of R as
!     (R11 R12) = (T 0)*Z
      Call dtzrzf(k, n, a, lda, tau, work, lwork, info)

!     Compute least squares solutions of triangular problems by
!     back-substitution in T*Y1 = C1, storing the result in B
      Call dtrsm('Left', 'Upper', 'No transpose', 'Non-Unit', k, nrhs, one, a, &
        lda, b, ldb)

!     Compute estimates of the square roots of the residual sums of
!     squares (2-norm of each of the columns of C2)
      Do j = 1, nrhs
        rnorm(j) = dnrm2(m-k, b(k+1,j), inc1)
      End Do

!     Set the remaining elements of the solutions to zero (to give
!     the minimum-norm solutions), Y2 = 0

      b(k+1:n, 1:nrhs) = zero

!     Form W = (Z**T)*Y

      Call dormrz('Left', 'Transpose', n, nrhs, k, n-k, a, lda, tau, b, ldb, &
        work, lwork, info)

!     Permute the least squares solutions stored in B to give X = P*W

      Do j = 1, nrhs
        work(jpvt(1:n)) = b(1:n, j)
        b(1:n, j) = work(1:n)
      End Do

!     Print least squares solutions

!     ifail: behaviour on error exit
!             =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
      ifail = 0
      Call nagf_file_print_matrix_real_gen('General', ' ', n, nrhs, b, ldb, &
        'Least squares solution(s)', ifail)

!     Print the square roots of the residual sums of squares

      Write (nout, *)
      Write (nout, *) 'Square root(s) of the residual sum(s) of squares'
      Write (nout, 100) rnorm(1:nrhs)

100   Format (5X, 1P, 6E11.2)
110   Format (1X, I8)
    End Program
Full documentation of DTZRZF


ZGBBRD example

Computational Routines: Reduction of complex rectangular band matrix to upper bidiagonal form

Data

ZGBBRD Example Program Data
  6  4  2  1  0                             :Values of M, N, KL, KU and NCC
 ( 0.96,-0.81) (-0.03, 0.96)
 (-0.98, 1.98) (-1.20, 0.19) (-0.66, 0.42)
 ( 0.62,-0.46) ( 1.01, 0.02) ( 0.63,-0.17) (-1.11, 0.60)
               ( 0.19,-0.54) (-0.98,-0.36) ( 0.22,-0.20)
                             (-0.17,-0.46) ( 1.47, 1.59)
                                           ( 0.26, 0.26)   :End of matrix A

Result

 ZGBBRD Example Program Results

 Diagonal
    2.6560   1.7501   2.0607   0.8658
 Superdiagonal
    1.7033   1.2800   0.1467

Source

    Program zgbbrd_example

!     ZGBBRD Example Program Text

!     Copyright 2017, Numerical Algorithms Group Ltd. http://www.nag.com

!     .. Use Statements ..
      Use lapack_interfaces, Only: zgbbrd
      Use lapack_precision, Only: dp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter :: nin = 5, nout = 6
      Character (1), Parameter :: vect = 'N'
!     .. Local Scalars ..
      Integer :: i, info, j, kl, ku, ldab, ldc, ldpt, ldq, m, n, ncc
!     .. Local Arrays ..
      Complex (Kind=dp), Allocatable :: ab(:, :), c(:, :), pt(:, :), q(:, :), &
        work(:)
      Real (Kind=dp), Allocatable :: d(:), e(:), rwork(:)
!     .. Intrinsic Procedures ..
      Intrinsic :: max, min
!     .. Executable Statements ..
      Write (nout, *) 'ZGBBRD Example Program Results'
!     Skip heading in data file
      Read (nin, *)
      Read (nin, *) m, n, kl, ku, ncc
      ldab = kl + ku + 1
      ldc = m
      ldpt = n
      ldq = m
      Allocate (ab(ldab,n), c(m,ncc), pt(ldpt,n), q(ldq,m), work(m+n), d(n), &
        e(n-1), rwork(m+n))

!     Read A from data file

      Read (nin, *)((ab(ku+1+i-j,j),j=max(i-kl,1),min(i+ku,n)), i=1, m)

!     Reduce A to upper bidiagonal form

      Call zgbbrd(vect, m, n, ncc, kl, ku, ab, ldab, d, e, q, ldq, pt, ldpt, &
        c, ldc, work, rwork, info)

!     Print bidiagonal form

      Write (nout, *)
      Write (nout, *) 'Diagonal'
      Write (nout, 100) d(1:min(m,n))
      Write (nout, *) 'Superdiagonal'
      Write (nout, 100) e(1:min(m,n)-1)

100   Format (1X, 8F9.4)
    End Program
Full documentation of ZGBBRD


ZGBCON example

Computational Routines: Estimate condition number of complex band matrix, matrix already factorized by ZGBTRF

Data

ZGBCON Example Program Data
  4  1  2                                                :Values of N, KL and KU
 (-1.65, 2.26) (-2.05,-0.85) ( 0.97,-2.84)
 ( 0.00, 6.30) (-1.48,-1.75) (-3.99, 4.01) ( 0.59,-0.48)
               (-0.77, 2.83) (-1.06, 1.94) ( 3.33,-1.04)
                             ( 4.48,-1.09) (-0.46,-1.72)  :End of matrix A

Result

 ZGBCON Example Program Results

 Estimate of condition number =  1.04E+02

Source

    Program zgbcon_example

!     ZGBCON Example Program Text

!     Copyright 2017, Numerical Algorithms Group Ltd. http://www.nag.com

!     .. Use Statements ..
      Use lapack_interfaces, Only: zgbcon, zgbtrf, zlangb
      Use lapack_precision, Only: dp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter :: nin = 5, nout = 6
      Character (1), Parameter :: norm = '1'
!     .. Local Scalars ..
      Real (Kind=dp) :: anorm, rcond
      Integer :: i, info, j, k, kl, ku, ldab, n
!     .. Local Arrays ..
      Complex (Kind=dp), Allocatable :: ab(:, :), work(:)
      Real (Kind=dp), Allocatable :: rwork(:)
      Integer, Allocatable :: ipiv(:)
!     .. Intrinsic Procedures ..
      Intrinsic :: epsilon, max, min
!     .. Executable Statements ..
      Write (nout, *) 'ZGBCON Example Program Results'
!     Skip heading in data file
      Read (nin, *)
      Read (nin, *) n, kl, ku
      ldab = 2*kl + ku + 1
      Allocate (ab(ldab,n), work(2*n), rwork(n), ipiv(n))

!     Read A from data file

      k = kl + ku + 1
      Read (nin, *)((ab(k+i-j,j),j=max(i-kl,1),min(i+ku,n)), i=1, n)

      anorm = zlangb(norm, n, kl, ku, ab(kl+1,1), ldab, rwork)

!     Factorize A
      Call zgbtrf(n, n, kl, ku, ab, ldab, ipiv, info)

      Write (nout, *)
      If (info==0) Then

!       Estimate condition number
        Call zgbcon(norm, n, kl, ku, ab, ldab, ipiv, anorm, rcond, work, &
          rwork, info)

        If (rcond>=epsilon(1.0E0_dp)) Then
          Write (nout, 100) 'Estimate of condition number =', 1.0E0_dp/rcond
        Else
          Write (nout, *) 'A is singular to working precision'
        End If
      Else
        Write (nout, *) 'The factor U is singular'
      End If

100   Format (1X, A, 1P, E10.2)
    End Program
Full documentation of ZGBCON


ZGBEQU example

Computational Routines: Computes row and column scalings intended to equilibrate a complex banded matrix and reduce its condition number

Data

ZGBEQU Example Program Data
  4  1  2                                                :Values of N, KL and KU
 (-1.65, 2.26) (-2.05D-10,-8.50D-11) ( 9.70D-01,-2.84D+00)
 ( 0.00, 6.30) (-1.48D-10,-1.75D-10) (-2.99D+00, 3.01D+00) ( 0.59D+00,-0.48D+00)
               (-7.70D-01, 2.83D+00) (-1.06D+10, 1.94D+10) ( 3.33D+10,-1.04D+10)
                                     ( 4.48D+00,-1.09D+00) (-0.46D+00,-1.72D+00)
                                                                :End of matrix A

Result

 ZGBEQU Example Program Results

 Matrix A
               1            2            3            4
 1   -1.6500E+00  -2.0500E-10   9.7000E-01
      2.2600E+00  -8.5000E-11  -2.8400E+00

 2    0.0000E+00  -1.4800E-10  -2.9900E+00   5.9000E-01
      6.3000E+00  -1.7500E-10   3.0100E+00  -4.8000E-01

 3                -7.7000E-01  -1.0600E+10   3.3300E+10
                   2.8300E+00   1.9400E+10  -1.0400E+10

 4                              4.4800E+00  -4.6000E-01
                               -1.0900E+00  -1.7200E+00

 ROWCND = 8.9E-11, COLCND = 8.2E-11, AMAX = 4.4E+10

 Row scale factors
    2.56E-01   1.59E-01   2.29E-11   1.80E-01

 Column scale factors
    1.00E+00   1.21E+10   1.00E+00   1.00E+00

 Scaled matrix
          1       2       3       4
 1  -0.4220 -0.6364  0.2481
     0.5780 -0.2639 -0.7263

 2   0.0000 -0.2852 -0.4746  0.0937
     1.0000 -0.3372  0.4778 -0.0762

 3          -0.2139 -0.2426  0.7620
             0.7861  0.4439 -0.2380

 4                   0.8043 -0.0826
                    -0.1957 -0.3088

Source

    Program zgbequ_example

!     ZGBEQU Example Program Text

!     Copyright 2017, Numerical Algorithms Group Ltd. http://www.nag.com

!     .. Use Statements ..
      Use blas_interfaces, Only: zdscal
      Use lapack_example_aux, Only: nagf_blas_zddscl, &
        nagf_file_print_matrix_complex_band
      Use lapack_interfaces, Only: zgbequ
      Use lapack_precision, Only: dp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Real (Kind=dp), Parameter :: one = 1.0_dp
      Real (Kind=dp), Parameter :: thresh = 0.1_dp
      Integer, Parameter :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=dp) :: amax, big, colcnd, rowcnd, small
      Integer :: i, i0, i1, ifail, ilen, info, j, k, kl, ku, ldab, n
!     .. Local Arrays ..
      Complex (Kind=dp), Allocatable :: ab(:, :)
      Real (Kind=dp), Allocatable :: c(:), r(:)
!     .. Intrinsic Procedures ..
      Intrinsic :: epsilon, max, min, radix, real, tiny
!     .. Executable Statements ..
      Write (nout, *) 'ZGBEQU Example Program Results'
      Write (nout, *)
      Flush (nout)
!     Skip heading in data file
      Read (nin, *)
      Read (nin, *) n, kl, ku
      ldab = kl + ku + 1
      Allocate (ab(ldab,n), c(n), r(n))

!     Read the band matrix A from data file

      k = ku + 1
      Read (nin, *)((ab(k+i-j,j),j=max(i-kl,1),min(i+ku,n)), i=1, n)

!     Print the matrix A

!     ifail: behaviour on error exit
!             =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
      ifail = 0
      Call nagf_file_print_matrix_complex_band(n, n, kl, ku, ab, ldab, &
        'Matrix A', ifail)

      Write (nout, *)

!     Compute row and column scaling factors

      Call zgbequ(n, n, kl, ku, ab, ldab, r, c, rowcnd, colcnd, amax, info)

      If (info>0) Then
        If (info<=n) Then
          Write (nout, 100) 'Row ', info, ' of A is exactly zero'
        Else
          Write (nout, 100) 'Column ', info - n, ' of A is exactly zero'
        End If
      Else

!       Print ROWCND, COLCND, AMAX and the scale factors

        Write (nout, 110) 'ROWCND =', rowcnd, ', COLCND =', colcnd, &
          ', AMAX =', amax
        Write (nout, *)
        Write (nout, *) 'Row scale factors'
        Write (nout, 120) r(1:n)
        Write (nout, *)
        Write (nout, *) 'Column scale factors'
        Write (nout, 120) c(1:n)
        Write (nout, *)
        Flush (nout)

!       Compute values close to underflow and overflow

        small = tiny(1.0E0_dp)/(epsilon(1.0E0_dp)*real(radix(1.0E0_dp),kind=dp &
          ))
        big = one/small
        If ((rowcnd>=thresh) .And. (amax>=small) .And. (amax<=big)) Then
          If (colcnd<thresh) Then

!           Just column scale A
            Do j = 1, n
              i1 = 1 + max(1, j-ku) - (j-ku)
              ilen = min(n, j+kl) - max(1, j-ku) + 1
              Call zdscal(ilen, c(j), ab(i1,j), 1)
            End Do

          End If
        Else If (colcnd>=thresh) Then

!         Just row scale A
          Do j = 1, n
            i0 = max(1, j-ku)
            i1 = 1 + i0 - (j-ku)
            ilen = min(n, j+kl) - i0 + 1
            Call nagf_blas_zddscl(ilen, r(i0), 1, ab(i1,j), 1)
          End Do

        Else

!         Row and column scale A
          Do j = 1, n
            i0 = max(1, j-ku)
            i1 = 1 + i0 - (j-ku)
            ilen = min(n, j+kl) - i0 + 1
            Call zdscal(ilen, c(j), ab(i1,j), 1)
            Call nagf_blas_zddscl(ilen, r(i0), 1, ab(i1,j), 1)
          End Do

        End If

!       Print the scaled matrix
        ifail = 0
        Call nagf_file_print_matrix_complex_band(n, n, kl, ku, ab, ldab, &
          'Scaled matrix', ifail)

      End If

100   Format (1X, A, I4, A)
110   Format (1X, 3(A,1P,E8.1))
120   Format ((1X,1P,7E11.2))
    End Program
Full documentation of ZGBEQU


ZGBRFS example

Computational Routines: Refined solution with error bounds of complex band system of linear equations, multiple right-hand sides

Data

ZGBRFS Example Program Data
  4  2  1  2                                       :Values of N, NRHS, KL and KU
 (-1.65, 2.26) (-2.05,-0.85) ( 0.97,-2.84)
 ( 0.00, 6.30) (-1.48,-1.75) (-3.99, 4.01) ( 0.59,-0.48)
               (-0.77, 2.83) (-1.06, 1.94) ( 3.33,-1.04)
                             ( 4.48,-1.09) (-0.46,-1.72)  :End of matrix A
 ( -1.06, 21.50) ( 12.85,  2.84)
 (-22.72,-53.90) (-70.22, 21.57)
 ( 28.24,-38.60) (-20.73, -1.23)
 (-34.56, 16.73) ( 26.01, 31.97)                          :End of matrix B

Result

 ZGBRFS Example Program Results

 Solution(s)
                    1                 2
 1  (-3.0000, 2.0000) ( 1.0000, 6.0000)
 2  ( 1.0000,-7.0000) (-7.0000,-4.0000)
 3  (-5.0000, 4.0000) ( 3.0000, 5.0000)
 4  ( 6.0000,-8.0000) (-8.0000, 2.0000)

 Backward errors (machine-dependent)
         1.8E-17           5.1E-17
 Estimated forward error bounds (machine-dependent)
         3.5E-14           4.3E-14

Source

    Program zgbrfs_example

!     ZGBRFS Example Program Text

!     Copyright 2017, Numerical Algorithms Group Ltd. http://www.nag.com

!     .. Use Statements ..
      Use lapack_example_aux, Only: nagf_file_print_matrix_complex_gen_comp
      Use lapack_interfaces, Only: zgbrfs, zgbtrf, zgbtrs
      Use lapack_precision, Only: dp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Complex (Kind=dp), Parameter :: zero = (0.0_dp, 0.0_dp)
      Integer, Parameter :: nin = 5, nout = 6
      Character (1), Parameter :: trans = 'N'
!     .. Local Scalars ..
      Integer :: i, ifail, info, j, k, kl, ku, ldab, ldafb, ldb, ldx, n, nrhs
!     .. Local Arrays ..
      Complex (Kind=dp), Allocatable :: ab(:, :), afb(:, :), b(:, :), work(:), &
        x(:, :)
      Real (Kind=dp), Allocatable :: berr(:), ferr(:), rwork(:)
      Integer, Allocatable :: ipiv(:)
      Character (1) :: clabs(1), rlabs(1)
!     .. Intrinsic Procedures ..
      Intrinsic :: max, min
!     .. Executable Statements ..
      Write (nout, *) 'ZGBRFS Example Program Results'
!     Skip heading in data file
      Read (nin, *)
      Read (nin, *) n, nrhs, kl, ku
      ldb = n
      ldx = n
      ldab = kl + ku + 1
      ldafb = 2*kl + ku + 1
      Allocate (ab(ldab,n), afb(ldafb,n), b(ldb,nrhs), work(2*n), x(ldx,n), &
        berr(nrhs), ferr(nrhs), rwork(n), ipiv(n))

!     Set A to zero to avoid referencing uninitialized elements

      ab(1:kl+ku+1, 1:n) = zero

!     Read A and B from data file, and copy A to AFB and B to X

      k = ku + 1
      Read (nin, *)((ab(k+i-j,j),j=max(i-kl,1),min(i+ku,n)), i=1, n)
      Read (nin, *)(b(i,1:nrhs), i=1, n)

      afb(kl+1:2*kl+ku+1, 1:n) = ab(1:kl+ku+1, 1:n)
      x(1:n, 1:nrhs) = b(1:n, 1:nrhs)

!     Factorize A in the array AFB
      Call zgbtrf(n, n, kl, ku, afb, ldafb, ipiv, info)

      Write (nout, *)
      Flush (nout)
      If (info==0) Then

!       Compute solution in the array X
        Call zgbtrs(trans, n, kl, ku, nrhs, afb, ldafb, ipiv, x, ldx, info)

!       Improve solution, and compute backward errors and
!       estimated bounds on the forward errors
        Call zgbrfs(trans, n, kl, ku, nrhs, ab, ldab, afb, ldafb, ipiv, b, &
          ldb, x, ldx, ferr, berr, work, rwork, info)

!       Print solution

!       ifail: behaviour on error exit
!              =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
        ifail = 0
        Call nagf_file_print_matrix_complex_gen_comp('General', ' ', n, nrhs, &
          x, ldx, 'Bracketed', 'F7.4', 'Solution(s)', 'Integer', rlabs, &
          'Integer', clabs, 80, 0, ifail)

        Write (nout, *)
        Write (nout, *) 'Backward errors (machine-dependent)'
        Write (nout, 100) berr(1:nrhs)
        Write (nout, *) 'Estimated forward error bounds (machine-dependent)'
        Write (nout, 100) ferr(1:nrhs)
      Else
        Write (nout, *) 'The factor U is singular'
      End If

100   Format ((5X,1P,4(E11.1,7X)))
    End Program
Full documentation of ZGBRFS


ZGBTRF example

Computational Routines: LU factorization of complex m by n band matrix

Data

ZGBTRF Example Program Data
  4  4  1  2                                          :Values of M, N, KL and KU
 (-1.65, 2.26) (-2.05,-0.85) ( 0.97,-2.84)
 ( 0.00, 6.30) (-1.48,-1.75) (-3.99, 4.01) ( 0.59,-0.48)
               (-0.77, 2.83) (-1.06, 1.94) ( 3.33,-1.04)
                             ( 4.48,-1.09) (-0.46,-1.72)  :End of matrix A

Result

 ZGBTRF Example Program Results

 Details of factorization
                    1                 2                 3                 4
 1  ( 0.0000, 6.3000) (-1.4800,-1.7500) (-3.9900, 4.0100) ( 0.5900,-0.4800)
 2  ( 0.3587, 0.2619) (-0.7700, 2.8300) (-1.0600, 1.9400) ( 3.3300,-1.0400)
 3                    ( 0.2314, 0.6358) ( 4.9303,-3.0086) (-1.7692,-1.8587)
 4                                      ( 0.7604, 0.2429) ( 0.4338, 0.1233)

 IPIV
            2                 3                 3                 4

Source

    Program zgbtrf_example

!     ZGBTRF Example Program Text

!     Copyright 2017, Numerical Algorithms Group Ltd. http://www.nag.com

!     .. Use Statements ..
      Use lapack_example_aux, Only: nagf_file_print_matrix_complex_band_comp
      Use lapack_interfaces, Only: zgbtrf
      Use lapack_precision, Only: dp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter :: nin = 5, nout = 6
!     .. Local Scalars ..
      Integer :: i, ifail, info, j, k, kl, ku, ldab, m, n
!     .. Local Arrays ..
      Complex (Kind=dp), Allocatable :: ab(:, :)
      Integer, Allocatable :: ipiv(:)
      Character (1) :: clabs(1), rlabs(1)
!     .. Intrinsic Procedures ..
      Intrinsic :: max, min
!     .. Executable Statements ..
      Write (nout, *) 'ZGBTRF Example Program Results'
!     Skip heading in data file
      Read (nin, *)
      Read (nin, *) m, n, kl, ku
      ldab = 2*kl + ku + 1
      Allocate (ab(ldab,n), ipiv(n))

!     Read A from data file

      k = kl + ku + 1
      Read (nin, *)((ab(k+i-j,j),j=max(i-kl,1),min(i+ku,n)), i=1, m)

!     Factorize A
      Call zgbtrf(m, n, kl, ku, ab, ldab, ipiv, info)

!     Print details of factorization

      Write (nout, *)
      Flush (nout)

!     ifail: behaviour on error exit
!             =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
      ifail = 0
      Call nagf_file_print_matrix_complex_band_comp(m, n, kl, kl+ku, ab, ldab, &
        'Bracketed', 'F7.4', 'Details of factorization', 'Integer', rlabs, &
        'Integer', clabs, 80, 0, ifail)

!     Print pivot indices

      Write (nout, *)
      Write (nout, *) 'IPIV'
      Write (nout, 100) ipiv(1:min(m,n))

      If (info/=0) Then
        Write (nout, *) 'The factor U is singular'
      End If

100   Format ((1X,I12,3I18))
    End Program
Full documentation of ZGBTRF


ZGBTRS example

Computational Routines: Solution of complex band system of linear equations, multiple right-hand sides, matrix already factorized by ZGBTRF

Data

ZGBTRS Example Program Data
  4  2  1  2                                       :Values of N, NRHS, KL and KU
 (-1.65, 2.26) (-2.05,-0.85) ( 0.97,-2.84)
 ( 0.00, 6.30) (-1.48,-1.75) (-3.99, 4.01) ( 0.59,-0.48)
               (-0.77, 2.83) (-1.06, 1.94) ( 3.33,-1.04)
                             ( 4.48,-1.09) (-0.46,-1.72)  :End of matrix A
 ( -1.06, 21.50) ( 12.85,  2.84)
 (-22.72,-53.90) (-70.22, 21.57)
 ( 28.24,-38.60) (-20.73, -1.23)
 (-34.56, 16.73) ( 26.01, 31.97)                          :End of matrix B

Result

 ZGBTRS Example Program Results

 Solution(s)
                    1                 2
 1  (-3.0000, 2.0000) ( 1.0000, 6.0000)
 2  ( 1.0000,-7.0000) (-7.0000,-4.0000)
 3  (-5.0000, 4.0000) ( 3.0000, 5.0000)
 4  ( 6.0000,-8.0000) (-8.0000, 2.0000)

Source

    Program zgbtrs_example

!     ZGBTRS Example Program Text

!     Copyright 2017, Numerical Algorithms Group Ltd. http://www.nag.com

!     .. Use Statements ..
      Use lapack_example_aux, Only: nagf_file_print_matrix_complex_gen_comp
      Use lapack_interfaces, Only: zgbtrf, zgbtrs
      Use lapack_precision, Only: dp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter :: nin = 5, nout = 6
      Character (1), Parameter :: trans = 'N'
!     .. Local Scalars ..
      Integer :: i, ifail, info, j, k, kl, ku, ldab, ldb, n, nrhs
!     .. Local Arrays ..
      Complex (Kind=dp), Allocatable :: ab(:, :), b(:, :)
      Integer, Allocatable :: ipiv(:)
      Character (1) :: clabs(1), rlabs(1)
!     .. Intrinsic Procedures ..
      Intrinsic :: max, min
!     .. Executable Statements ..
      Write (nout, *) 'ZGBTRS Example Program Results'
!     Skip heading in data file
      Read (nin, *)
      Read (nin, *) n, nrhs, kl, ku
      ldab = 2*kl + ku + 1
      ldb = n
      Allocate (ab(ldab,n), b(ldb,nrhs), ipiv(n))

!     Read A and B from data file

      k = kl + ku + 1
      Read (nin, *)((ab(k+i-j,j),j=max(i-kl,1),min(i+ku,n)), i=1, n)
      Read (nin, *)(b(i,1:nrhs), i=1, n)

!     Factorize A

      Call zgbtrf(n, n, kl, ku, ab, ldab, ipiv, info)

      Write (nout, *)
      Flush (nout)
      If (info==0) Then

!       Compute solution
        Call zgbtrs(trans, n, kl, ku, nrhs, ab, ldab, ipiv, b, ldb, info)

!       Print solution

!       ifail: behaviour on error exit
!              =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
        ifail = 0
        Call nagf_file_print_matrix_complex_gen_comp('General', ' ', n, nrhs, &
          b, ldb, 'Bracketed', 'F7.4', 'Solution(s)', 'Integer', rlabs, &
          'Integer', clabs, 80, 0, ifail)

      Else
        Write (nout, *) 'The factor U is singular'
      End If

    End Program
Full documentation of ZGBTRS


ZGEBAL example

Computational Routines: Balance complex general matrix

Data

ZGEBAL Example Program Data
  4                                                         :Value of N
 ( 1.50,-2.75) ( 0.00, 0.00) ( 0.00, 0.00) ( 0.00, 0.00)
 (-8.06,-1.24) (-2.50,-0.50) ( 0.00, 0.00) (-0.75, 0.50)
 (-2.09, 7.56) ( 1.39, 3.97) (-1.25, 0.75) (-4.82,-5.67)
 ( 6.18, 9.79) (-0.92,-0.62) ( 0.00, 0.00) (-2.50,-0.50)   :End of matrix A

Result

 ZGEBAL Example Program Results

 Eigenvalues
    (-3.5000,-0.5025) ( 1.5000,-2.7500) (-1.5000,-0.4975) (-1.2500, 0.7500)

 Contents of array VR
                    1                 2                 3                 4
 1  ( 0.0000,-0.0000) ( 0.1418,-0.0407) ( 0.0000, 0.0000) ( 0.0000, 0.0000)
 2  ( 0.1756,-0.4131) (-0.2711,-0.1812) (-0.1015, 0.0009) ( 0.0000, 0.0000)
 3  ( 0.7420, 0.0000) ( 0.8213, 0.0000) ( 0.9884, 0.0000) ( 1.0000, 0.0000)
 4  ( 0.4170,-0.2722) ( 0.1110, 0.4303) ( 0.0941, 0.0619) ( 0.0000, 0.0000)

Source

    Program zgebal_example

!     ZGEBAL Example Program Text

!     Copyright 2017, Numerical Algorithms Group Ltd. http://www.nag.com

!     .. Use Statements ..
      Use blas_interfaces, Only: dznrm2
      Use lapack_example_aux, Only: nagf_sort_realvec_rank, &
        nagf_file_print_matrix_complex_gen_comp, &
        nagf_sort_cmplxvec_rank_rearrange
      Use lapack_interfaces, Only: zgebak, zgebal, zgehrd, zhseqr, ztrevc, &
        zunghr
      Use lapack_precision, Only: dp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter :: nin = 5, nout = 6
!     .. Local Scalars ..
      Complex (Kind=dp) :: scal
      Integer :: i, ifail, ihi, ilo, info, k, lda, ldh, ldvl, ldvr, lwork, m, &
        n
!     .. Local Arrays ..
      Complex (Kind=dp), Allocatable :: a(:, :), h(:, :), tau(:), vl(:, :), &
        vr(:, :), vr_row(:), w(:), work(:)
      Real (Kind=dp), Allocatable :: rwork(:), scale(:)
      Integer, Allocatable :: irank(:)
      Logical :: select(1)
      Character (1) :: clabs(1), rlabs(1)
!     .. Intrinsic Procedures ..
      Intrinsic :: abs, aimag, conjg, maxloc, real
!     .. Executable Statements ..
      Write (nout, *) 'ZGEBAL Example Program Results'
      Flush (nout)
!     Skip heading in data file
      Read (nin, *)
      Read (nin, *) n
      ldvl = 1
      lda = n
      ldh = n
      ldvr = n
      lwork = 64*n
      Allocate (a(lda,n), h(ldh,n), tau(n), vl(ldvl,1), vr(ldvr,n), w(n), &
        work(lwork), rwork(n), scale(n), irank(n))

!     Read A from data file
      Read (nin, *)(a(i,1:n), i=1, n)

!     Balance A
      Call zgebal('Both', n, a, lda, ilo, ihi, scale, info)

!     Reduce A to upper Hessenberg form H = (Q**H)*A*Q
      Call zgehrd(n, ilo, ihi, a, lda, tau, work, lwork, info)

!     Copy A to H and VR
      h(1:n, 1:n) = a(1:n, 1:n)
      vr(1:n, 1:n) = a(1:n, 1:n)

!     Form Q explicitly, storing the result in VR
      Call zunghr(n, 1, n, vr, ldvr, tau, work, lwork, info)

!     Calculate the eigenvalues and Schur factorization of A
      Call zhseqr('Schur form', 'Vectors', n, ilo, ihi, h, ldh, w, vr, ldvr, &
        work, lwork, info)

      Write (nout, *)
      If (info>0) Then
        Write (nout, *) 'Failure to converge.'
      Else
!       Sort eigenvalues into descending absolute value
        rwork(1:n) = abs(w(1:n))
!       ifail: behaviour on error exit
!              =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
        ifail = 0
        Call nagf_sort_realvec_rank(rwork, 1, n, 'Descending', irank, ifail)
!       ifail: behaviour on error exit
!              =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
        ifail = 0
        Call nagf_sort_cmplxvec_rank_rearrange(w, 1, n, irank, ifail)

        Write (nout, *) 'Eigenvalues'
        Write (nout, 100)(' (', real(w(i)), ',', aimag(w(i)), ')', i=1, n)
        Flush (nout)

!       Calculate the eigenvectors of A, storing the result in VR
        Call ztrevc('Right', 'Backtransform', select, n, h, ldh, vl, ldvl, vr, &
          ldvr, n, m, work, rwork, info)

        Call zgebak('Both', 'Right', n, ilo, ihi, scale, m, vr, ldvr, info)

!       Reorder eigenvectors using irank
        Allocate (vr_row(n))
        Do i = 1, n
          vr_row(1:n) = vr(i, 1:n)
!         ifail: behaviour on error exit
!                =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
          ifail = 0
          Call nagf_sort_cmplxvec_rank_rearrange(vr_row, 1, n, irank, ifail)
          vr(i, 1:n) = vr_row(1:n)
        End Do
        Deallocate (vr_row)

!       Print eigenvectors

        Write (nout, *)
        Flush (nout)

!       Normalize the eigenvectors, largest element real
        Do i = 1, m
          rwork(1:n) = abs(vr(1:n,i))
          k = maxloc(rwork(1:n), 1)
          scal = conjg(vr(k,i))/abs(vr(k,i))/dznrm2(n, vr(1,i), 1)
          vr(1:n, i) = vr(1:n, i)*scal
        End Do

!       ifail: behaviour on error exit
!              =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
        ifail = 0
        Call nagf_file_print_matrix_complex_gen_comp('General', ' ', n, m, vr, &
          ldvr, 'Bracketed', 'F7.4', 'Contents of array VR', 'Integer', rlabs, &
          'Integer', clabs, 80, 0, ifail)

      End If

100   Format ((3X,4(A,F7.4,A,F7.4,A,:)))
    End Program
Full documentation of ZGEBAL


ZGEBRD example

Computational Routines: Unitary reduction of complex general rectangular matrix to bidiagonal form

Data

ZGEBRD Example Program Data
  6  4                                                     :Values of M and N
 ( 0.96,-0.81) (-0.03, 0.96) (-0.91, 2.06) (-0.05, 0.41)
 (-0.98, 1.98) (-1.20, 0.19) (-0.66, 0.42) (-0.81, 0.56)
 ( 0.62,-0.46) ( 1.01, 0.02) ( 0.63,-0.17) (-1.11, 0.60)
 (-0.37, 0.38) ( 0.19,-0.54) (-0.98,-0.36) ( 0.22,-0.20)
 ( 0.83, 0.51) ( 0.20, 0.01) (-0.17,-0.46) ( 1.47, 1.59)
 ( 1.08,-0.28) ( 0.20,-0.12) (-0.07, 1.23) ( 0.26, 0.26)   :End of matrix A

Result

 ZGEBRD Example Program Results

 Diagonal
   -3.0870   2.0660   1.8731   2.0022
 Superdiagonal
    2.1126   1.2628  -1.6126

Source

    Program zgebrd_example

!     ZGEBRD Example Program Text

!     Copyright 2017, Numerical Algorithms Group Ltd. http://www.nag.com

!     .. Use Statements ..
      Use lapack_interfaces, Only: zgebrd
      Use lapack_precision, Only: dp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter :: nin = 5, nout = 6
!     .. Local Scalars ..
      Integer :: i, info, lda, lwork, m, n
!     .. Local Arrays ..
      Complex (Kind=dp), Allocatable :: a(:, :), taup(:), tauq(:), work(:)
      Real (Kind=dp), Allocatable :: d(:), e(:)
!     .. Intrinsic Procedures ..
      Intrinsic :: min
!     .. Executable Statements ..
      Write (nout, *) 'ZGEBRD Example Program Results'
!     Skip heading in data file
      Read (nin, *)
      Read (nin, *) m, n
      lda = m
      lwork = 64*(m+n)
      Allocate (a(lda,n), taup(n), tauq(n), work(lwork), d(n), e(n-1))

!     Read A from data file

      Read (nin, *)(a(i,1:n), i=1, m)

!     Reduce A to bidiagonal form

      Call zgebrd(m, n, a, lda, d, e, tauq, taup, work, lwork, info)

!     Print bidiagonal form

      Write (nout, *)
      Write (nout, *) 'Diagonal'
      Write (nout, 100) d(1:min(m,n))
      If (m>=n) Then
        Write (nout, *) 'Superdiagonal'
      Else
        Write (nout, *) 'Subdiagonal'
      End If
      Write (nout, 100) e(1:min(m,n)-1)

100   Format (1X, 8F9.4)
    End Program
Full documentation of ZGEBRD


ZGECON example

Computational Routines: Estimate condition number of complex matrix, matrix already factorized by ZGETRF

Data

ZGECON Example Program Data
  4                                                       :Value of N
 (-1.34, 2.55) ( 0.28, 3.17) (-6.39,-2.20) ( 0.72,-0.92)
 (-0.17,-1.41) ( 3.31,-0.15) (-0.15, 1.34) ( 1.29, 1.38)
 (-3.29,-2.39) (-1.91, 4.42) (-0.14,-1.35) ( 1.72, 1.35)
 ( 2.41, 0.39) (-0.56, 1.47) (-0.83,-0.69) (-1.96, 0.67)  :End of matrix A

Result

 ZGECON Example Program Results

 Estimate of condition number =  1.50E+02

Source

    Program zgecon_example

!     ZGECON Example Program Text

!     Copyright 2017, Numerical Algorithms Group Ltd. http://www.nag.com

!     .. Use Statements ..
      Use lapack_interfaces, Only: zgecon, zgetrf, zlange
      Use lapack_precision, Only: dp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter :: nin = 5, nout = 6
      Character (1), Parameter :: norm = '1'
!     .. Local Scalars ..
      Real (Kind=dp) :: anorm, rcond
      Integer :: i, info, lda, n
!     .. Local Arrays ..
      Complex (Kind=dp), Allocatable :: a(:, :), work(:)
      Real (Kind=dp), Allocatable :: rwork(:)
      Integer, Allocatable :: ipiv(:)
!     .. Intrinsic Procedures ..
      Intrinsic :: epsilon
!     .. Executable Statements ..
      Write (nout, *) 'ZGECON Example Program Results'
!     Skip heading in data file
      Read (nin, *)
      Read (nin, *) n
      lda = n
      Allocate (a(lda,n), work(2*n), rwork(2*n), ipiv(n))

!     Read A from data file

      Read (nin, *)(a(i,1:n), i=1, n)

!     Compute norm of A
      anorm = zlange(norm, n, n, a, lda, rwork)

!     Factorize A
      Call zgetrf(n, n, a, lda, ipiv, info)

      Write (nout, *)
      If (info==0) Then

!       Estimate condition number

        Call zgecon(norm, n, a, lda, anorm, rcond, work, rwork, info)

        If (rcond>=epsilon(1.0E0_dp)) Then
          Write (nout, 100) 'Estimate of condition number =', 1.0_dp/rcond
        Else
          Write (nout, *) 'A is singular to working precision'
        End If
      Else
        Write (nout, *) 'The factor U is singular'
      End If

100   Format (1X, A, 1P, E10.2)
    End Program
Full documentation of ZGECON


ZGEEQU example

Computational Routines: Computes row and column scalings intended to equilibrate a general complex matrix and reduce its condition number

Data

ZGEEQU Example Program Data

  3                                                             :Value of N

 (-1.34D+00, 2.55D+00) ( 0.28D+10, 3.17D+10) (-6.39D+00,-2.20D+00)
 (-1.70D+00,-1.41D+00) ( 3.31D+10,-0.15D+10) (-0.15D+00, 1.34D+00)
 ( 2.41D-10, 0.39D-10) (-0.56D+00, 1.47D+00) (-0.83D-10,-0.69D-10)

                                                                :End of matrix A

Result

 ZGEEQU Example Program Results

 Matrix A
                          1                       2                       3
 1  ( -1.34E+00,  2.55E+00) (  2.80E+09,  3.17E+10) ( -6.39E+00, -2.20E+00)
 2  ( -1.70E+00, -1.41E+00) (  3.31E+10, -1.50E+09) ( -1.50E-01,  1.34E+00)
 3  (  2.41E-10,  3.90E-11) ( -5.60E-01,  1.47E+00) ( -8.30E-11, -6.90E-11)

 ROWCND = 5.9E-11, COLCND = 1.4E-10, AMAX = 3.5E+10

 Row scale factors
    2.90E-11   2.89E-11   4.93E-01

 Column scale factors
    7.25E+09   1.00E+00   4.02E+09

 Scaled matrix
                      1                   2                   3
 1  ( -0.2816,  0.5359) (  0.0812,  0.9188) ( -0.7439, -0.2561)
 2  ( -0.3562, -0.2954) (  0.9566, -0.0434) ( -0.0174,  0.1555)
 3  (  0.8607,  0.1393) ( -0.2759,  0.7241) ( -0.1642, -0.1365)

Source

    Program zgeequ_example

!     ZGEEQU Example Program Text

!     Copyright 2017, Numerical Algorithms Group Ltd. http://www.nag.com

!     .. Use Statements ..
      Use blas_interfaces, Only: zdscal
      Use lapack_example_aux, Only: nagf_blas_zddscl, &
        nagf_file_print_matrix_complex_gen_comp
      Use lapack_interfaces, Only: zgeequ
      Use lapack_precision, Only: dp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Real (Kind=dp), Parameter :: one = 1.0_dp
      Real (Kind=dp), Parameter :: thresh = 0.1_dp
      Integer, Parameter :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=dp) :: amax, big, colcnd, rowcnd, small
      Integer :: i, ifail, info, j, lda, n
!     .. Local Arrays ..
      Complex (Kind=dp), Allocatable :: a(:, :)
      Real (Kind=dp), Allocatable :: c(:), r(:)
      Character (1) :: clabs(1), rlabs(1)
!     .. Intrinsic Procedures ..
      Intrinsic :: epsilon, radix, real, tiny
!     .. Executable Statements ..
      Write (nout, *) 'ZGEEQU Example Program Results'
      Write (nout, *)
      Flush (nout)
!     Skip heading in data file
      Read (nin, *)
      Read (nin, *) n
      lda = n
      Allocate (a(lda,n), c(n), r(n))

!     Read the N by N matrix A from data file

      Read (nin, *)(a(i,1:n), i=1, n)

!     Print the matrix A

!     ifail: behaviour on error exit
!             =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
      ifail = 0
      Call nagf_file_print_matrix_complex_gen_comp('General', ' ', n, n, a, &
        lda, 'Bracketed', '1P,E10.2', 'Matrix A', 'Integer', rlabs, 'Integer', &
        clabs, 80, 0, ifail)

      Write (nout, *)

!     Compute row and column scaling factors

      Call zgeequ(n, n, a, lda, r, c, rowcnd, colcnd, amax, info)

      If (info>0) Then
        If (info<=n) Then
          Write (nout, 100) 'Row ', info, ' of A is exactly zero'
        Else
          Write (nout, 100) 'Column ', info - n, ' of A is exactly zero'
        End If
      Else

!       Print ROWCND, COLCND, AMAX and the scale factors

        Write (nout, 110) 'ROWCND =', rowcnd, ', COLCND =', colcnd, &
          ', AMAX =', amax
        Write (nout, *)
        Write (nout, *) 'Row scale factors'
        Write (nout, 120) r(1:n)
        Write (nout, *)
        Write (nout, *) 'Column scale factors'
        Write (nout, 120) c(1:n)
        Write (nout, *)
        Flush (nout)

!       Compute values close to underflow and overflow

        small = tiny(1.0E0_dp)/(epsilon(1.0E0_dp)*real(radix(1.0E0_dp),kind=dp &
          ))
        big = one/small
        If ((rowcnd>=thresh) .And. (amax>=small) .And. (amax<=big)) Then
          If (colcnd<thresh) Then

!           Just column scale A
            Do j = 1, n
              Call zdscal(n, c(j), a(1,j), 1)
            End Do

          End If
        Else If (colcnd>=thresh) Then

!         Just row scale A
          Do j = 1, n
            Call nagf_blas_zddscl(n, r, 1, a(1,j), 1)
          End Do

        Else

!         Row and column scale A
          Do j = 1, n
            Call zdscal(n, c(j), a(1,j), 1)
            Call nagf_blas_zddscl(n, r, 1, a(1,j), 1)
          End Do

        End If

!       Print the scaled matrix
        ifail = 0
        Call nagf_file_print_matrix_complex_gen_comp('General', ' ', n, n, a, &
          lda, 'Bracketed', ' ', 'Scaled matrix', 'Integer', rlabs, 'Integer', &
          clabs, 80, 0, ifail)

      End If

100   Format (1X, A, I4, A)
110   Format (1X, 3(A,1P,E8.1))
120   Format ((1X,1P,7E11.2))
    End Program
Full documentation of ZGEEQU


ZGEHRD example

Computational Routines: Unitary reduction of complex general matrix to upper Hessenberg form

Data

ZGEHRD Example Program Data
  4                                                        :Value of N
 (-3.97,-5.04) (-4.11, 3.70) (-0.34, 1.01) ( 1.29,-0.86)
 ( 0.34,-1.50) ( 1.52,-0.43) ( 1.88,-5.38) ( 3.36, 0.65)
 ( 3.31,-3.85) ( 2.50, 3.45) ( 0.88,-1.08) ( 0.64,-1.48)
 (-1.10, 0.82) ( 1.81,-1.59) ( 3.25, 1.33) ( 1.57,-3.44)   :End of matrix A

Result

 ZGEHRD Example Program Results

 Upper Hessenberg form
                    1                 2                 3                 4
 1  (-3.9700,-5.0400) (-1.1318,-2.5693) (-4.6027,-0.1426) (-1.4249, 1.7330)
 2  (-5.4797, 0.0000) ( 1.8585,-1.5502) ( 4.4145,-0.7638) (-0.4805,-1.1976)
 3  ( 0.0000, 0.0000) ( 6.2673, 0.0000) (-0.4504,-0.0290) (-1.3467, 1.6579)
 4  ( 0.0000, 0.0000) ( 0.0000, 0.0000) (-3.5000, 0.0000) ( 2.5619,-3.3708)

Source

    Program zgehrd_example

!     ZGEHRD Example Program Text

!     Copyright 2017, Numerical Algorithms Group Ltd. http://www.nag.com

!     .. Use Statements ..
      Use lapack_example_aux, Only: nagf_file_print_matrix_complex_gen_comp
      Use lapack_interfaces, Only: zgehrd
      Use lapack_precision, Only: dp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Complex (Kind=dp), Parameter :: zero = (0.0E0_dp, 0.0E0_dp)
      Integer, Parameter :: nin = 5, nout = 6
!     .. Local Scalars ..
      Integer :: i, ifail, info, lda, lwork, n
!     .. Local Arrays ..
      Complex (Kind=dp), Allocatable :: a(:, :), tau(:), work(:)
      Character (1) :: clabs(1), rlabs(1)
!     .. Executable Statements ..
      Write (nout, *) 'ZGEHRD Example Program Results'
!     Skip heading in data file
      Read (nin, *)
      Read (nin, *) n
      lda = n
      lwork = 64*n
      Allocate (a(lda,n), tau(n-1), work(lwork))

!     Read A from data file

      Read (nin, *)(a(i,1:n), i=1, n)

!     Reduce A to upper Hessenberg form

      Call zgehrd(n, 1, n, a, lda, tau, work, lwork, info)

!     Set the elements below the first subdiagonal to zero

      Do i = 1, n - 2
        a(i+2:n, i) = zero
      End Do

!     Print upper Hessenberg form

      Write (nout, *)
      Flush (nout)

!     ifail: behaviour on error exit
!             =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
      ifail = 0
      Call nagf_file_print_matrix_complex_gen_comp('General', ' ', n, n, a, &
        lda, 'Bracketed', 'F7.4', 'Upper Hessenberg form', 'Integer', rlabs, &
        'Integer', clabs, 80, 0, ifail)

    End Program
Full documentation of ZGEHRD


ZGEJSV example

Computational Routines: Computes the singular value decomposition of a complex matrix, optionally computing the left and/or right singular vectors (preconditioned Jacobi)

Data

ZGEJSV Example Program Data
  6  4                                                   : m and n
 ( 0.96,-0.81) (-0.03, 0.96) (-0.91, 2.06) (-0.05, 0.41)
 (-0.98, 1.98) (-1.20, 0.19) (-0.66, 0.42) (-0.81, 0.56)
 ( 0.62,-0.46) ( 1.01, 0.02) ( 0.63,-0.17) (-1.11, 0.60)
 (-0.37, 0.38) ( 0.19,-0.54) (-0.98,-0.36) ( 0.22,-0.20)
 ( 0.83, 0.51) ( 0.20, 0.01) (-0.17,-0.46) ( 1.47, 1.59)
 ( 1.08,-0.28) ( 0.20,-0.12) (-0.07, 1.23) ( 0.26, 0.26) : matrix A

Result

 ZGEJSV Example Program Results

 Singular values
     3.9994  3.0003  1.9944  0.9995

 Left singular vectors
          1       2       3       4
 1   0.5634 -0.1804  0.0757  0.0127
    -0.0021  0.3395 -0.5208  0.4822

 2  -0.1200  0.1917 -0.4535  0.0220
     0.6109  0.2443 -0.1124 -0.0420

 3   0.0815  0.4205  0.6021  0.1237
    -0.1614  0.0403 -0.0346 -0.2071

 4  -0.1440 -0.2257  0.0942  0.5805
     0.1534 -0.1364 -0.1237 -0.1439

 5   0.2488  0.1251 -0.2252  0.0533
     0.0924 -0.6961 -0.1398  0.0860

 6   0.3758 -0.0684  0.0004  0.0448
    -0.0796  0.0540 -0.2158 -0.5805

Warning: Floating underflow occurred
 Right singular vectors
          1       2       3       4
 1   0.6971 -0.0729  0.4144 -0.2817
    -0.0006 -0.2289  0.3013 -0.3384

 2   0.0864  0.2006  0.3471  0.8276
    -0.3549 -0.1400  0.0379 -0.0000

 3  -0.0564  0.5794 -0.3585 -0.2202
    -0.5399  0.0755  0.3776 -0.2106

 4   0.1876 -0.4206 -0.5845  0.1264
    -0.2254 -0.6035  0.0527  0.1116

 Estimate of the condition number of column equilibrated A
       2.61E+00

 Error estimates (as multiples of machine precision):

   for the singular values
       4

   for left singular vectors
       4   4   4   4

   for right singular vectors
       4   4   4   4

Source

    Program zgejsv_example

!     ZGEJSV Example Program Text

!     Copyright 2017, Numerical Algorithms Group Ltd. http://www.nag.com

!     .. Use Statements ..
      Use lapack_example_aux, Only: nagf_file_print_matrix_complex_gen
      Use lapack_interfaces, Only: ddisna, zgejsv
      Use lapack_precision, Only: dp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=dp) :: eps, serrbd
      Integer :: i, ifail, info, j, lda, ldu, ldv, lrwork, lwork, m, n
!     .. Local Arrays ..
      Complex (Kind=dp), Allocatable :: a(:, :), cwork(:), u(:, :), v(:, :)
      Real (Kind=dp), Allocatable :: rcondu(:), rcondv(:), rwork(:), sva(:)
      Integer, Allocatable :: iwork(:)
!     .. Intrinsic Procedures ..
      Intrinsic :: abs, epsilon, nint
!     .. Executable Statements ..
      Write (nout, *) 'ZGEJSV Example Program Results'
      Write (nout, *)
      Flush (nout)
!     Skip heading in data file
      Read (nin, *)
      Read (nin, *) m, n
      lda = m
      ldu = m
      ldv = n
      lwork = 5*n + n*n + 1000
      lrwork = n + 2*m + 7
      Allocate (a(lda,n), rcondu(m), rcondv(m), sva(n), u(ldu,n), v(ldv,n), &
        cwork(lwork), rwork(lrwork), iwork(m+3*n+3))

!     Read the m by n matrix A from data file
      Read (nin, *)((a(i,j),j=1,n), i=1, m)

!     Compute the singular values and left and right singular vectors
!     of A (A = U*S*V^T, m.ge.n)
      Call zgejsv('E', 'U', 'V', 'R', 'N', 'N', m, n, a, lda, sva, u, ldu, v, &
        ldv, cwork, lwork, rwork, lrwork, iwork, info)

      If (info==0) Then

!       Compute the approximate error bound for the computed singular values
!       using the 2-norm, s(1) = norm(A), and machine precision, eps.
        eps = epsilon(1.0E0_dp)
        serrbd = eps*sva(1)

!       Print solution
        If (abs(rwork(1)-rwork(2))<2.0_dp*eps) Then
!         No scaling required
          Write (nout, '(1X,A)') 'Singular values'
          Write (nout, 100)(sva(j), j=1, n)
        Else
          Write (nout, '(/1X,A)') 'Scaled singular values'
          Write (nout, 100)(sva(j), j=1, n)
          Write (nout, '(/1X,A)') 'For true singular values, multiply by a/b,'
          Write (nout, 140) ' where a = ', rwork(1), ' and b = ', rwork(2)
        End If

!       ifail: behaviour on error exit
!              =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
        Write (nout, *)
        Flush (nout)
        ifail = 0
        Call nagf_file_print_matrix_complex_gen('General', ' ', m, n, u, ldu, &
          'Left singular vectors', ifail)

        Write (nout, *)
        Flush (nout)
        ifail = 0
        Call nagf_file_print_matrix_complex_gen('General', ' ', n, n, v, ldv, &
          'Right singular vectors', ifail)

!       Call DDISNA to estimate reciprocal condition numbers for
!       the singular vectors.

        Call ddisna('Left', m, n, sva, rcondu, info)
        Call ddisna('Right', m, n, sva, rcondv, info)

!       Print the approximate error bounds for the singular values
!       and vectors.
        Write (nout, *)
        Write (nout, '(/1X,A)') &
          'Estimate of the condition number of column equilibrated A'
        Write (nout, 110) rwork(3)
        Write (nout, '(/1X,A)') &
          'Error estimates (as multiples of machine precision):'
        Write (nout, '(/1X,A)') '  for the singular values'
        Write (nout, 120) nint(serrbd/epsilon(1.0E0_dp))
        Write (nout, '(/1X,A)') '  for left singular vectors'
        Write (nout, 120)(nint(serrbd/rcondu(i)/epsilon(1.0E0_dp)), i=1, n)
        Write (nout, '(/1X,A)') '  for right singular vectors'
        Write (nout, 120)(nint(serrbd/rcondv(i)/epsilon(1.0E0_dp)), i=1, n)
      Else
        Write (nout, 130) 'Failure in ZGEJSV. INFO =', info
      End If

100   Format (3X, 8F8.4)
110   Format (4X, 1P, E11.2)
120   Format (4X, 6I4)
130   Format (1X, A, I4)
140   Format (1X, 2(A,1P,E13.5))
    End Program
Full documentation of ZGEJSV


ZGELQF example

Computational Routines: LQ factorization of complex general rectangular matrix

Data

ZGELQF Example Program Data
  3  4  2                                          :Values of M, N and NRHS
 ( 0.28,-0.36) ( 0.50,-0.86) (-0.77,-0.48) ( 1.58, 0.66)
 (-0.50,-1.10) (-1.21, 0.76) (-0.32,-0.24) (-0.27,-1.15)
 ( 0.36,-0.51) (-0.07, 1.33) (-0.75, 0.47) (-0.08, 1.01)   :End of matrix A
 (-1.35, 0.19) ( 4.83,-2.67)
 ( 9.41,-3.56) (-7.28, 3.34)
 (-7.57, 6.93) ( 0.62, 4.53)                               :End of matrix B

Result

 ZGELQF Example Program Results

 Minimum-norm solution(s)
                    1                 2
 1  (-2.8501, 6.4683) (-1.1682,-1.8886)
 2  ( 1.6264,-0.7799) ( 2.8377, 0.7654)
 3  ( 6.9290, 4.6481) (-1.7610,-0.7041)
 4  ( 1.4048, 3.2400) ( 1.0518,-1.6365)

Source

    Program zgelqf_example

!     ZGELQF Example Program Text

!     Copyright 2017, Numerical Algorithms Group Ltd. http://www.nag.com

!     .. Use Statements ..
      Use blas_interfaces, Only: ztrsm
      Use lapack_example_aux, Only: nagf_file_print_matrix_complex_gen_comp
      Use lapack_interfaces, Only: zgelqf, zunmlq
      Use lapack_precision, Only: dp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Complex (Kind=dp), Parameter :: one = (1.0_dp, 0.0_dp)
      Complex (Kind=dp), Parameter :: zero = (0.0_dp, 0.0_dp)
      Integer, Parameter :: nin = 5, nout = 6
!     .. Local Scalars ..
      Integer :: i, ifail, info, lda, ldb, lwork, m, n, nrhs
!     .. Local Arrays ..
      Complex (Kind=dp), Allocatable :: a(:, :), b(:, :), tau(:), work(:)
      Character (1) :: clabs(1), rlabs(1)
!     .. Executable Statements ..
      Write (nout, *) 'ZGELQF Example Program Results'
!     Skip heading in data file
      Read (nin, *)
      Read (nin, *) m, n, nrhs
      lda = m
      ldb = n
      lwork = 64*n
      Allocate (a(lda,n), b(ldb,nrhs), tau(n), work(lwork))

!     Read A and B from data file

      Read (nin, *)(a(i,1:n), i=1, m)
      Read (nin, *)(b(i,1:nrhs), i=1, m)

!     Compute the LQ factorization of A
      Call zgelqf(m, n, a, lda, tau, work, lwork, info)

!     Solve L*Y = B, storing the result in B
      Call ztrsm('Left', 'Lower', 'No transpose', 'Non-Unit', m, nrhs, one, a, &
        lda, b, ldb)

!     Set rows (M+1) to N of B to zero

      If (m<n) Then
        b(m+1:n, 1:nrhs) = zero
      End If

!     Compute minimum-norm solution X = (Q**H)*B in B
      Call zunmlq('Left', 'Conjugate transpose', n, nrhs, m, a, lda, tau, b, &
        ldb, work, lwork, info)

!     Print minimum-norm solution(s)

      Write (nout, *)
      Flush (nout)

!     ifail: behaviour on error exit
!             =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
      ifail = 0
      Call nagf_file_print_matrix_complex_gen_comp('General', ' ', n, nrhs, b, &
        ldb, 'Bracketed', 'F7.4', 'Minimum-norm solution(s)', 'Integer', &
        rlabs, 'Integer', clabs, 80, 0, ifail)

    End Program
Full documentation of ZGELQF


ZGEQLF example

Computational Routines: QL factorization of complex general rectangular matrix

Data

ZGEQLF Example Program Data
   6             4            2                  :Values of M, N and NRHS

 ( 0.96,-0.81) (-0.03, 0.96) (-0.91, 2.06) (-0.05, 0.41)
 (-0.98, 1.98) (-1.20, 0.19) (-0.66, 0.42) (-0.81, 0.56)
 ( 0.62,-0.46) ( 1.01, 0.02) ( 0.63,-0.17) (-1.11, 0.60)
 (-0.37, 0.38) ( 0.19,-0.54) (-0.98,-0.36) ( 0.22,-0.20)
 ( 0.83, 0.51) ( 0.20, 0.01) (-0.17,-0.46) ( 1.47, 1.59)
 ( 1.08,-0.28) ( 0.20,-0.12) (-0.07, 1.23) ( 0.26, 0.26) :End of matrix A

 (-2.09, 1.93) ( 3.26,-2.70)
 ( 3.34,-3.53) (-6.22, 1.16)
 (-4.94,-2.04) ( 7.94,-3.13)
 ( 0.17, 4.23) ( 1.04,-4.26)
 (-5.19, 3.63) (-2.31,-2.12)
 ( 0.98, 2.53) (-1.39,-4.05)                             :End of matrix B

Result

 ZGEQLF Example Program Results

 Least squares solution(s)
                    1                 2
 1  (-0.5044,-1.2179) ( 0.7629, 1.4529)
 2  (-2.4281, 2.8574) ( 5.1570,-3.6089)
 3  ( 1.4872,-2.1955) (-2.6518, 2.1203)
 4  ( 0.4537, 2.6904) (-2.7606, 0.3318)

 Square root(s) of the residual sum(s) of squares
      6.88E-02   1.87E-01

Source

    Program zgeqlf_example

!     ZGEQLF Example Program Text

!     Copyright 2017, Numerical Algorithms Group Ltd. http://www.nag.com

!     .. Use Statements ..
      Use blas_interfaces, Only: dznrm2
      Use lapack_example_aux, Only: nagf_file_print_matrix_complex_gen_comp
      Use lapack_interfaces, Only: zgeqlf, ztrtrs, zunmql
      Use lapack_precision, Only: dp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter :: nb = 64, nin = 5, nout = 6
!     .. Local Scalars ..
      Integer :: i, ifail, info, j, lda, ldb, lwork, m, n, nrhs
!     .. Local Arrays ..
      Complex (Kind=dp), Allocatable :: a(:, :), b(:, :), tau(:), work(:)
      Real (Kind=dp), Allocatable :: rnorm(:)
      Character (1) :: clabs(1), rlabs(1)
!     .. Executable Statements ..
      Write (nout, *) 'ZGEQLF Example Program Results'
      Write (nout, *)
      Flush (nout)
!     Skip heading in data file
      Read (nin, *)
      Read (nin, *) m, n, nrhs
      lda = m
      ldb = m
      lwork = nb*n
      Allocate (a(lda,n), b(ldb,nrhs), tau(n), work(lwork), rnorm(nrhs))

!     Read A and B from data file

      Read (nin, *)(a(i,1:n), i=1, m)
      Read (nin, *)(b(i,1:nrhs), i=1, m)

!     Compute the QL factorization of A
      Call zgeqlf(m, n, a, lda, tau, work, lwork, info)

!     Compute C = (C1) = (Q**H)*B, storing the result in B
!                  (C2)
      Call zunmql('Left', 'Conjugate Transpose', m, nrhs, n, a, lda, tau, b, &
        ldb, work, lwork, info)

!     Compute least squares solutions by back-substitution in
!     L*X = C2
      Call ztrtrs('Lower', 'No transpose', 'Non-Unit', n, nrhs, a(m-n+1,1), &
        lda, b(m-n+1,1), ldb, info)

      If (info>0) Then
        Write (nout, *) 'The lower triangular factor, L, of A is singular, '
        Write (nout, *) 'the least squares solution could not be computed'
      Else

!       Print least squares solution(s)

!       ifail: behaviour on error exit
!              =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
        ifail = 0
        Call nagf_file_print_matrix_complex_gen_comp('General', ' ', n, nrhs, &
          b(m-n+1,1), ldb, 'Bracketed', 'F7.4', 'Least squares solution(s)', &
          'Integer', rlabs, 'Integer', clabs, 80, 0, ifail)

!       Compute and print estimates of the square roots of the residual
!       sums of squares
        Do j = 1, nrhs
          rnorm(j) = dznrm2(m-n, b(1,j), 1)
        End Do

        Write (nout, *)
        Write (nout, *) 'Square root(s) of the residual sum(s) of squares'
        Write (nout, 100) rnorm(1:nrhs)
      End If

100   Format (3X, 1P, 7E11.2)
    End Program
Full documentation of ZGEQLF


ZGEQP3 example

Computational Routines: QR factorization of complex general rectangular matrix with column pivoting, using BLAS-3

Data

ZGEQP3 Example Program Data

   5             4             2                 :Values of M, N and NRHS

 ( 0.47,-0.34) (-0.40, 0.54) ( 0.60, 0.01) ( 0.80,-1.02)
 (-0.32,-0.23) (-0.05, 0.20) (-0.26,-0.44) (-0.43, 0.17)
 ( 0.35,-0.60) (-0.52,-0.34) ( 0.87,-0.11) (-0.34,-0.09)
 ( 0.89, 0.71) (-0.45,-0.45) (-0.02,-0.57) ( 1.14,-0.78)
 (-0.19, 0.06) ( 0.11,-0.85) ( 1.44, 0.80) ( 0.07, 1.14) :End of matrix A

 (-1.08,-2.59) ( 2.22, 2.35)
 (-2.61,-1.49) ( 1.62,-1.48)
 ( 3.13,-3.61) ( 1.65, 3.43)
 ( 7.33,-8.01) (-0.98, 3.08)
 ( 9.12, 7.63) (-2.84, 2.78)                             :End of matrix B

Result

 ZGEQP3 Example Program Results

 Tolerance used to estimate the rank of A
      1.00E-02
 Estimated rank of A
        3

 Least squares solution(s)
                    1                 2
 1  ( 0.0000, 0.0000) ( 0.0000, 0.0000)
 2  ( 2.7020, 8.0911) (-2.2682,-2.9884)
 3  ( 2.8888, 2.5012) ( 0.9779, 1.3565)
 4  ( 2.7100, 0.4791) (-1.3734, 0.2212)

 Square root(s) of the residual sum(s) of squares
      2.51E-01   8.10E-02

Source

    Program zgeqp3_example

!     ZGEQP3 Example Program Text

!     Copyright 2017, Numerical Algorithms Group Ltd. http://www.nag.com

!     .. Use Statements ..
      Use blas_interfaces, Only: dznrm2, ztrsm
      Use lapack_example_aux, Only: nagf_file_print_matrix_complex_gen_comp
      Use lapack_interfaces, Only: zgeqp3, zunmqr
      Use lapack_precision, Only: dp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Complex (Kind=dp), Parameter :: one = (1.0E0_dp, 0.0E0_dp)
      Complex (Kind=dp), Parameter :: zero = (0.0E0_dp, 0.0E0_dp)
      Integer, Parameter :: inc1 = 1, nb = 64, nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=dp) :: tol
      Integer :: i, ifail, info, j, k, lda, ldb, lwork, m, n, nrhs
!     .. Local Arrays ..
      Complex (Kind=dp), Allocatable :: a(:, :), b(:, :), tau(:), work(:)
      Real (Kind=dp), Allocatable :: rnorm(:), rwork(:)
      Integer, Allocatable :: jpvt(:)
      Character (1) :: clabs(1), rlabs(1)
!     .. Intrinsic Procedures ..
      Intrinsic :: abs
!     .. Executable Statements ..
      Write (nout, *) 'ZGEQP3 Example Program Results'
      Write (nout, *)
!     Skip heading in data file
      Read (nin, *)
      Read (nin, *) m, n, nrhs
      lda = m
      ldb = m
      lwork = (n+1)*nb
      Allocate (a(lda,n), b(ldb,nrhs), tau(n), work(lwork), rnorm(nrhs), &
        rwork(2*n), jpvt(n))

!     Read A and B from data file

      Read (nin, *)(a(i,1:n), i=1, m)
      Read (nin, *)(b(i,1:nrhs), i=1, m)

!     Initialize JPVT to be zero so that all columns are free

      jpvt(1:n) = 0

!     Compute the QR factorization of A

      Call zgeqp3(m, n, a, lda, jpvt, tau, work, lwork, rwork, info)

!     Compute C = (C1) = (Q**H)*B, storing the result in B
!                  (C2)

      Call zunmqr('Left', 'Conjugate Transpose', m, nrhs, n, a, lda, tau, b, &
        ldb, work, lwork, info)

!     Choose TOL to reflect the relative accuracy of the input data

      tol = 0.01_dp

!     Determine and print the rank, K, of R relative to TOL

loop: Do k = 1, n
        If (abs(a(k,k))<=tol*abs(a(1,1))) Then
          Exit loop
        End If
      End Do loop
      k = k - 1

      Write (nout, *) 'Tolerance used to estimate the rank of A'
      Write (nout, 100) tol
      Write (nout, *) 'Estimated rank of A'
      Write (nout, 110) k
      Write (nout, *)
      Flush (nout)

!     Compute least squares solutions by back-substitution in
!     R(1:K,1:K)*Y = C1, storing the result in B

      Call ztrsm('Left', 'Upper', 'No transpose', 'Non-Unit', k, nrhs, one, a, &
        lda, b, ldb)

!     Compute estimates of the square roots of the residual sums of
!     squares (2-norm of each of the columns of C2)

      Do j = 1, nrhs
        rnorm(j) = dznrm2(m-k, b(k+1,j), inc1)
      End Do

!     Set the remaining elements of the solutions to zero (to give
!     the basic solutions)

      b(k+1:n, 1:nrhs) = zero

!     Permute the least squares solutions stored in B to give X = P*Y

      Do j = 1, nrhs
        work(jpvt(1:n)) = b(1:n, j)
        b(1:n, j) = work(1:n)
      End Do

!     Print least squares solutions

!     ifail: behaviour on error exit
!             =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
      ifail = 0
      Call nagf_file_print_matrix_complex_gen_comp('General', ' ', n, nrhs, b, &
        ldb, 'Bracketed', 'F7.4', 'Least squares solution(s)', 'Integer', &
        rlabs, 'Integer', clabs, 80, 0, ifail)

!     Print the square roots of the residual sums of squares

      Write (nout, *)
      Write (nout, *) 'Square root(s) of the residual sum(s) of squares'
      Write (nout, 100) rnorm(1:nrhs)

100   Format (3X, 1P, 7E11.2)
110   Format (1X, I8)
    End Program
Full documentation of ZGEQP3


ZGEQRF example

Computational Routines: QR factorization of complex general rectangular matrix

Data

ZGEQRF Example Program Data

   6             4             2                 :Values of M, N and NRHS

 ( 0.96,-0.81) (-0.03, 0.96) (-0.91, 2.06) (-0.05, 0.41)
 (-0.98, 1.98) (-1.20, 0.19) (-0.66, 0.42) (-0.81, 0.56)
 ( 0.62,-0.46) ( 1.01, 0.02) ( 0.63,-0.17) (-1.11, 0.60)
 (-0.37, 0.38) ( 0.19,-0.54) (-0.98,-0.36) ( 0.22,-0.20)
 ( 0.83, 0.51) ( 0.20, 0.01) (-0.17,-0.46) ( 1.47, 1.59)
 ( 1.08,-0.28) ( 0.20,-0.12) (-0.07, 1.23) ( 0.26, 0.26) :End of matrix A

 (-2.09, 1.93) ( 3.26,-2.70)
 ( 3.34,-3.53) (-6.22, 1.16)
 (-4.94,-2.04) ( 7.94,-3.13)
 ( 0.17, 4.23) ( 1.04,-4.26)
 (-5.19, 3.63) (-2.31,-2.12)
 ( 0.98, 2.53) (-1.39,-4.05)                             :End of matrix B

Result

 ZGEQRF Example Program Results

 Least squares solution(s)
                    1                 2
 1  (-0.5044,-1.2179) ( 0.7629, 1.4529)
 2  (-2.4281, 2.8574) ( 5.1570,-3.6089)
 3  ( 1.4872,-2.1955) (-2.6518, 2.1203)
 4  ( 0.4537, 2.6904) (-2.7606, 0.3318)

 Square root(s) of the residual sum(s) of squares
      6.88E-02   1.87E-01

Source

    Program zgeqrf_example

!     ZGEQRF Example Program Text

!     Copyright 2017, Numerical Algorithms Group Ltd. http://www.nag.com

!     .. Use Statements ..
      Use blas_interfaces, Only: dznrm2
      Use lapack_example_aux, Only: nagf_file_print_matrix_complex_gen_comp
      Use lapack_interfaces, Only: zgeqrf, ztrtrs, zunmqr
      Use lapack_precision, Only: dp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter :: nb = 64, nin = 5, nout = 6
!     .. Local Scalars ..
      Integer :: i, ifail, info, j, lda, ldb, lwork, m, n, nrhs
!     .. Local Arrays ..
      Complex (Kind=dp), Allocatable :: a(:, :), b(:, :), tau(:), work(:)
      Real (Kind=dp), Allocatable :: rnorm(:)
      Character (1) :: clabs(1), rlabs(1)
!     .. Executable Statements ..
      Write (nout, *) 'ZGEQRF Example Program Results'
      Write (nout, *)
      Flush (nout)
!     Skip heading in data file
      Read (nin, *)
      Read (nin, *) m, n, nrhs
      lda = m
      ldb = m
      lwork = nb*n
      Allocate (a(lda,n), b(ldb,nrhs), tau(n), work(lwork), rnorm(nrhs))

!     Read A and B from data file

      Read (nin, *)(a(i,1:n), i=1, m)
      Read (nin, *)(b(i,1:nrhs), i=1, m)

!     Compute the QR factorization of A
      Call zgeqrf(m, n, a, lda, tau, work, lwork, info)

!     Compute C = (C1) = (Q**H)*B, storing the result in B
!                  (C2)
      Call zunmqr('Left', 'Conjugate transpose', m, nrhs, n, a, lda, tau, b, &
        ldb, work, lwork, info)

!     Compute least squares solutions by back-substitution in
!     R*X = C1
      Call ztrtrs('Upper', 'No transpose', 'Non-Unit', n, nrhs, a, lda, b, &
        ldb, info)

      If (info>0) Then
        Write (nout, *) 'The upper triangular factor, R, of A is singular, '
        Write (nout, *) 'the least squares solution could not be computed'
      Else

!       Print least squares solutions

!       ifail: behaviour on error exit
!              =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
        ifail = 0
        Call nagf_file_print_matrix_complex_gen_comp('General', ' ', n, nrhs, &
          b, ldb, 'Bracketed', 'F7.4', 'Least squares solution(s)', 'Integer', &
          rlabs, 'Integer', clabs, 80, 0, ifail)

!       Compute and print estimates of the square roots of the residual
!       sums of squares
        Do j = 1, nrhs
          rnorm(j) = dznrm2(m-n, b(n+1,j), 1)
        End Do

        Write (nout, *)
        Write (nout, *) 'Square root(s) of the residual sum(s) of squares'
        Write (nout, 100) rnorm(1:nrhs)
      End If

100   Format (3X, 1P, 7E11.2)
    End Program
Full documentation of ZGEQRF


ZGEQRT example

Computational Routines: Performs a QR factorization of complex general rectangular matrix using recursive algorithm

Data

ZGEQRT Example Program Data

   6             4             2                         : m, n and nrhs

 ( 0.96,-0.81) (-0.03, 0.96) (-0.91, 2.06) (-0.05, 0.41)
 (-0.98, 1.98) (-1.20, 0.19) (-0.66, 0.42) (-0.81, 0.56)
 ( 0.62,-0.46) ( 1.01, 0.02) ( 0.63,-0.17) (-1.11, 0.60)
 (-0.37, 0.38) ( 0.19,-0.54) (-0.98,-0.36) ( 0.22,-0.20)
 ( 0.83, 0.51) ( 0.20, 0.01) (-0.17,-0.46) ( 1.47, 1.59)
 ( 1.08,-0.28) ( 0.20,-0.12) (-0.07, 1.23) ( 0.26, 0.26) : matrix A

 (-2.09, 1.93) ( 3.26,-2.70)
 ( 3.34,-3.53) (-6.22, 1.16)
 (-4.94,-2.04) ( 7.94,-3.13)
 ( 0.17, 4.23) ( 1.04,-4.26)
 (-5.19, 3.63) (-2.31,-2.12)
 ( 0.98, 2.53) (-1.39,-4.05)                             : matrix B

Result

 ZGEQRT Example Program Results

 Least squares solution(s)
                    1                 2
 1  (-0.5044,-1.2179) ( 0.7629, 1.4529)
 2  (-2.4281, 2.8574) ( 5.1570,-3.6089)
 3  ( 1.4872,-2.1955) (-2.6518, 2.1203)
 4  ( 0.4537, 2.6904) (-2.7606, 0.3318)

 Square root(s) of the residual sum(s) of squares
      6.88E-02   1.87E-01

Source

    Program zgeqrt_example

!     ZGEQRT Example Program Text

!     Copyright 2017, Numerical Algorithms Group Ltd. http://www.nag.com

!     .. Use Statements ..
      Use blas_interfaces, Only: dznrm2
      Use lapack_example_aux, Only: nagf_file_print_matrix_complex_gen_comp
      Use lapack_interfaces, Only: zgemqrt, zgeqrt, ztrtrs
      Use lapack_precision, Only: dp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter :: nbmax = 64, nin = 5, nout = 6
!     .. Local Scalars ..
      Integer :: i, ifail, info, j, lda, ldb, ldt, lwork, m, n, nb, nrhs
!     .. Local Arrays ..
      Complex (Kind=dp), Allocatable :: a(:, :), b(:, :), t(:, :), work(:)
      Real (Kind=dp), Allocatable :: rnorm(:)
      Character (1) :: clabs(1), rlabs(1)
!     .. Intrinsic Procedures ..
      Intrinsic :: max, min
!     .. Executable Statements ..
      Write (nout, *) 'ZGEQRT Example Program Results'
      Write (nout, *)
      Flush (nout)
!     Skip heading in data file
      Read (nin, *)
      Read (nin, *) m, n, nrhs
      lda = m
      ldb = m
      nb = min(m, n, nbmax)
      ldt = nb
      lwork = nb*max(m, n)
      Allocate (a(lda,n), b(ldb,nrhs), t(ldt,min(m,n)), work(lwork), rnorm( &
        nrhs))

!     Read A and B from data file

      Read (nin, *)(a(i,1:n), i=1, m)
      Read (nin, *)(b(i,1:nrhs), i=1, m)

!     Compute the QR factorization of A
      Call zgeqrt(m, n, nb, a, lda, t, ldt, work, info)

!     Compute C = (C1) = (Q**H)*B, storing the result in B
!                  (C2)
      Call zgemqrt('Left', 'Conjugate transpose', m, nrhs, n, nb, a, lda, t, &
        ldt, b, ldb, work, info)

!     Compute least squares solutions by back-substitution in
!     R*X = C1
      Call ztrtrs('Upper', 'No transpose', 'Non-Unit', n, nrhs, a, lda, b, &
        ldb, info)

      If (info>0) Then
        Write (nout, *) 'The upper triangular factor, R, of A is singular, '
        Write (nout, *) 'the least squares solution could not be computed'
      Else

!       Print least squares solutions

!       ifail: behaviour on error exit
!              =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
        ifail = 0
        Call nagf_file_print_matrix_complex_gen_comp('General', ' ', n, nrhs, &
          b, ldb, 'Bracketed', 'F7.4', 'Least squares solution(s)', 'Integer', &
          rlabs, 'Integer', clabs, 80, 0, ifail)

!       Compute and print estimates of the square roots of the residual
!       sums of squares
        Do j = 1, nrhs
          rnorm(j) = dznrm2(m-n, b(n+1,j), 1)
        End Do

        Write (nout, *)
        Write (nout, *) 'Square root(s) of the residual sum(s) of squares'
        Write (nout, 100) rnorm(1:nrhs)
      End If

100   Format (3X, 1P, 7E11.2)
    End Program
Full documentation of ZGEQRT


ZGERFS example

Computational Routines: Refined solution with error bounds of complex system of linear equations, multiple right-hand sides

Data

ZGERFS Example Program Data
  4  2                                                    :Values of N and NRHS
 (-1.34, 2.55) ( 0.28, 3.17) (-6.39,-2.20) ( 0.72,-0.92)
 (-0.17,-1.41) ( 3.31,-0.15) (-0.15, 1.34) ( 1.29, 1.38)
 (-3.29,-2.39) (-1.91, 4.42) (-0.14,-1.35) ( 1.72, 1.35)
 ( 2.41, 0.39) (-0.56, 1.47) (-0.83,-0.69) (-1.96, 0.67)  :End of matrix A
 (26.26, 51.78) (31.32, -6.70)
 ( 6.43, -8.68) (15.86, -1.42)
 (-5.75, 25.31) (-2.15, 30.19)
 ( 1.16,  2.57) (-2.56,  7.55)                            :End of matrix B

Result

 ZGERFS Example Program Results

 Solution(s)
                    1                 2
 1  ( 1.0000, 1.0000) (-1.0000,-2.0000)
 2  ( 2.0000,-3.0000) ( 5.0000, 1.0000)
 3  (-4.0000,-5.0000) (-3.0000, 4.0000)
 4  ( 0.0000, 6.0000) ( 2.0000,-3.0000)

 Backward errors (machine-dependent)
         4.1E-17           8.7E-17
 Estimated forward error bounds (machine-dependent)
         5.8E-14           7.9E-14

Source

    Program zgerfs_example

!     ZGERFS Example Program Text

!     Copyright 2017, Numerical Algorithms Group Ltd. http://www.nag.com

!     .. Use Statements ..
      Use lapack_example_aux, Only: nagf_file_print_matrix_complex_gen_comp
      Use lapack_interfaces, Only: zgerfs, zgetrf, zgetrs
      Use lapack_precision, Only: dp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter :: nin = 5, nout = 6
      Character (1), Parameter :: trans = 'N'
!     .. Local Scalars ..
      Integer :: i, ifail, info, lda, ldaf, ldb, ldx, n, nrhs
!     .. Local Arrays ..
      Complex (Kind=dp), Allocatable :: a(:, :), af(:, :), b(:, :), work(:), &
        x(:, :)
      Real (Kind=dp), Allocatable :: berr(:), ferr(:), rwork(:)
      Integer, Allocatable :: ipiv(:)
      Character (1) :: clabs(1), rlabs(1)
!     .. Executable Statements ..
      Write (nout, *) 'ZGERFS Example Program Results'
!     Skip heading in data file
      Read (nin, *)
      Read (nin, *) n, nrhs
      lda = n
      ldaf = n
      ldb = n
      ldx = n
      Allocate (a(lda,n), af(ldaf,n), b(ldb,nrhs), work(2*n), x(ldx,n), &
        berr(nrhs), ferr(nrhs), rwork(n), ipiv(n))

!     Read A and B from data file, and copy A to AF and B to X

      Read (nin, *)(a(i,1:n), i=1, n)
      Read (nin, *)(b(i,1:nrhs), i=1, n)

      af(1:n, 1:n) = a(1:n, 1:n)
      x(1:n, 1:nrhs) = b(1:n, 1:nrhs)

!     Factorize A in the array AF
      Call zgetrf(n, n, af, ldaf, ipiv, info)

      Write (nout, *)
      Flush (nout)
      If (info==0) Then

!       Compute solution in the array X

        Call zgetrs(trans, n, nrhs, af, ldaf, ipiv, x, ldx, info)

!       Improve solution, and compute backward errors and
!       estimated bounds on the forward errors

        Call zgerfs(trans, n, nrhs, a, lda, af, ldaf, ipiv, b, ldb, x, ldx, &
          ferr, berr, work, rwork, info)

!       Print solution

!       ifail: behaviour on error exit
!              =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
        ifail = 0
        Call nagf_file_print_matrix_complex_gen_comp('General', ' ', n, nrhs, &
          x, ldx, 'Bracketed', 'F7.4', 'Solution(s)', 'Integer', rlabs, &
          'Integer', clabs, 80, 0, ifail)

        Write (nout, *)
        Write (nout, *) 'Backward errors (machine-dependent)'
        Write (nout, 100) berr(1:nrhs)
        Write (nout, *) 'Estimated forward error bounds (machine-dependent)'
        Write (nout, 100) ferr(1:nrhs)
      Else
        Write (nout, *) 'The factor U is singular'
      End If

100   Format ((5X,1P,4(E11.1,7X)))
    End Program
Full documentation of ZGERFS


ZGERQF example

Computational Routines: RQ factorization of complex general rectangular matrix

Data

ZGERQF Example Program Data

   3             4                               :Values of M, N and NRHS

 ( 0.28,-0.36) ( 0.50,-0.86) (-0.77,-0.48) ( 1.58, 0.66)
 (-0.50,-1.10) (-1.21, 0.76) (-0.32,-0.24) (-0.27,-1.15)
 ( 0.36,-0.51) (-0.07, 1.33) (-0.75, 0.47) (-0.08, 1.01) :End of matrix A

 (-1.35, 0.19)
 ( 9.41,-3.56)
 (-7.57, 6.93)                                           :End of vector b

Result

 ZGERQF Example Program Results

 Minimum-norm solution
 ( -2.8501,  6.4683) (  1.6264, -0.7799) (  6.9290,  4.6481) (  1.4048,  3.2400)

Source

    Program zgerqf_example

!     ZGERQF Example Program Text

!     Copyright 2017, Numerical Algorithms Group Ltd. http://www.nag.com

!     .. Use Statements ..
      Use lapack_interfaces, Only: zgerqf, ztrtrs, zunmrq
      Use lapack_precision, Only: dp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Complex (Kind=dp), Parameter :: zero = (0.0_dp, 0.0_dp)
      Integer, Parameter :: nb = 64, nin = 5, nout = 6
!     .. Local Scalars ..
      Integer :: i, info, lda, lwork, m, n
!     .. Local Arrays ..
      Complex (Kind=dp), Allocatable :: a(:, :), b(:), tau(:), work(:), x(:)
!     .. Executable Statements ..
      Write (nout, *) 'ZGERQF Example Program Results'
      Write (nout, *)
!     Skip heading in data file
      Read (nin, *)
      Read (nin, *) m, n
      lda = m
      lwork = nb*m
      Allocate (a(lda,n), b(m), tau(m), work(lwork), x(n))

!     Read the matrix A and the vector b from data file

      Read (nin, *)(a(i,1:n), i=1, m)
      Read (nin, *) b(1:m)

!     Compute the RQ factorization of A
      Call zgerqf(m, n, a, lda, tau, work, lwork, info)

!     Copy the m-element vector b into elements x(n-m+1), ..., x(n) of x

      x(n-m+1:n) = b(1:m)

!     Solve R*y2 = b, storing the result in x2
      Call ztrtrs('Upper', 'No transpose', 'Non-Unit', m, 1, a(1,n-m+1), lda, &
        x(n-m+1), m, info)

      If (info>0) Then
        Write (nout, *) 'The upper triangular factor, R, of A is singular, '
        Write (nout, *) 'the least squares solution could not be computed'
      Else

!       Set y1 to zero (stored in x(1:n-m))

        x(1:n-m) = zero

!       Compute minimum-norm solution x = (Q**H)*y
        Call zunmrq('Left', 'Conjugate transpose', n, 1, m, a, lda, tau, x, n, &
          work, lwork, info)

!       Print minimum-norm solution

        Write (nout, *) 'Minimum-norm solution'
        Write (nout, 100) x(1:n)
      End If

100   Format (4(' (',F8.4,',',F8.4,')',:))
    End Program
Full documentation of ZGERQF


ZGESVJ example

Computational Routines: Computes the singular value decomposition of a complex matrix, optionally computing the left and/or right singular vectors (fast Jacobi)

Data

ZGESVJ Example Program Data
  6  4                                                    : m and n
 ( 0.96,-0.81) (-0.03, 0.96) (-0.91, 2.06) (-0.05, 0.41)
 (-0.98, 1.98) (-1.20, 0.19) (-0.66, 0.42) (-0.81, 0.56)
 ( 0.62,-0.46) ( 1.01, 0.02) ( 0.63,-0.17) (-1.11, 0.60)
 (-0.37, 0.38) ( 0.19,-0.54) (-0.98,-0.36) ( 0.22,-0.20)
 ( 0.83, 0.51) ( 0.20, 0.01) (-0.17,-0.46) ( 1.47, 1.59)
 ( 1.08,-0.28) ( 0.20,-0.12) (-0.07, 1.23) ( 0.26, 0.26)  : matrix A

Result

 ZGESVJ Example Program Results

 Singular values
     3.9994  3.0003  1.9944  0.9995

 Left singular vectors
          1       2       3       4
 1   0.5632 -0.1814 -0.4517 -0.0171
     0.0151 -0.3390  0.2700  0.4820

 2  -0.1386 -0.3097  0.1991  0.0245
     0.6070  0.0231  0.4227 -0.0405

 3   0.0864 -0.2677 -0.4069  0.1363
    -0.1588  0.3268 -0.4452 -0.1991

 4  -0.1486  0.2390 -0.1554  0.5883
     0.1489 -0.1115  0.0051 -0.1077

 5   0.2459  0.5084  0.0337  0.0479
     0.1000  0.4916  0.2629  0.0891

 6   0.3780 -0.0068 -0.1676  0.0806
    -0.0681 -0.0870  0.1359 -0.5766

 Right singular vectors
          1       2       3       4
 1   0.6968  0.2307 -0.0278 -0.2602
     0.0207  0.0670 -0.5116 -0.3552

 2   0.0972  0.0045 -0.1897  0.8260
    -0.3520  0.2446 -0.2932  0.0511

 3  -0.0399 -0.3854  0.5192 -0.2068
    -0.5414  0.4391  0.0397 -0.2237

 4   0.1944  0.7355  0.4098  0.1193
    -0.2196 -0.0131  0.4201  0.1192

 Error estimates (as multiples of machine precision):

   for the singular values
       4

   for left singular vectors
       4   4   4   4

   for right singular vectors
       4   4   4   4

Source

    Program zgesvj_example

!     ZGESVJ Example Program Text

!     Copyright 2017, Numerical Algorithms Group Ltd. http://www.nag.com

!     .. Use Statements ..
      Use lapack_example_aux, Only: nagf_file_print_matrix_complex_gen
      Use lapack_interfaces, Only: ddisna, zgesvj
      Use lapack_precision, Only: dp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=dp) :: eps, serrbd
      Integer :: i, ifail, info, j, lda, ldv, lrwork, lwork, m, n
!     .. Local Arrays ..
      Complex (Kind=dp), Allocatable :: a(:, :), cwork(:), v(:, :)
      Real (Kind=dp), Allocatable :: rcondu(:), rcondv(:), rwork(:), sva(:)
!     .. Intrinsic Procedures ..
      Intrinsic :: abs, epsilon, max, nint
!     .. Executable Statements ..
      Write (nout, *) 'ZGESVJ Example Program Results'
      Write (nout, *)
      Flush (nout)
!     Skip heading in data file
      Read (nin, *)
      Read (nin, *) m, n
      lda = m
      ldv = n
      lwork = n + m
      lrwork = max(6, n)
      Allocate (a(lda,n), rcondu(m), rcondv(m), sva(n), v(ldv,n), &
        cwork(lwork), rwork(lrwork))

!     Read the m by n matrix A from data file

      Read (nin, *)((a(i,j),j=1,n), i=1, m)

!     Compute the singular values and left and right singular vectors
!     of A (A = U*S*V, m.ge.n)

      Call zgesvj('G', 'U', 'V', m, n, a, lda, sva, 0, v, ldv, cwork, lwork, &
        rwork, lrwork, info)
      If (info==0) Then

!       Compute the approximate error bound for the computed singular values
!       using the 2-norm, s(1) = norm(A), and machine precision, eps.
        eps = epsilon(1.0E0_dp)
        serrbd = eps*sva(1)

!       Print solution
        Write (nout, *) 'Singular values'
        Write (nout, 100)(sva(j), j=1, n)

        If (abs(rwork(1)-1.0_dp)>eps) Then
          Write (nout, 130) 'Values need scaling by factor = ', rwork(1)
        End If
        Write (nout, *)
        Flush (nout)

!       ifail: behaviour on error exit
!              =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
        ifail = 0
        Call nagf_file_print_matrix_complex_gen('General', ' ', m, n, a, lda, &
          'Left singular vectors', ifail)

        Write (nout, *)
        Flush (nout)

        ifail = 0
        Call nagf_file_print_matrix_complex_gen('General', ' ', n, n, v, ldv, &
          'Right singular vectors', ifail)

!       Call DDISNA to estimate reciprocal condition
!       numbers for the singular vectors
        Call ddisna('Left', m, n, sva, rcondu, info)
        Call ddisna('Right', m, n, sva, rcondv, info)

!       Print the approximate error bounds for the singular values
!       and vectors
        Write (nout, '(/1X,A)') &
          'Error estimates (as multiples of machine precision):'
        Write (nout, '(/1X,A)') '  for the singular values'
        Write (nout, 110) nint(serrbd/epsilon(1.0E0_dp))
        Write (nout, '(/1X,A)') '  for left singular vectors'
        Write (nout, 110)(nint(serrbd/rcondu(i)/epsilon(1.0E0_dp)), i=1, n)
        Write (nout, '(/1X,A)') '  for right singular vectors'
        Write (nout, 110)(nint(serrbd/rcondv(i)/epsilon(1.0E0_dp)), i=1, n)
      Else
        Write (nout, 120) 'Failure in ZGESVJ. INFO =', info
      End If

100   Format (3X, (8F8.4))
110   Format (4X, 6I4)
120   Format (1X, A, I4)
130   Format (/, 1X, A, 1P, E13.5)
    End Program
Full documentation of ZGESVJ


ZGETRF example

Computational Routines: LU factorization of complex m by n matrix

Data

ZGETRF Example Program Data
  4  4                                                    :Values of M and N
 (-1.34, 2.55) ( 0.28, 3.17) (-6.39,-2.20) ( 0.72,-0.92)
 (-0.17,-1.41) ( 3.31,-0.15) (-0.15, 1.34) ( 1.29, 1.38)
 (-3.29,-2.39) (-1.91, 4.42) (-0.14,-1.35) ( 1.72, 1.35)
 ( 2.41, 0.39) (-0.56, 1.47) (-0.83,-0.69) (-1.96, 0.67)  :End of matrix A

Result

 ZGETRF Example Program Results

 Details of factorization
                    1                 2                 3                 4
 1  (-3.2900,-2.3900) (-1.9100, 4.4200) (-0.1400,-1.3500) ( 1.7200, 1.3500)
 2  ( 0.2376, 0.2560) ( 4.8952,-0.7114) (-0.4623, 1.6966) ( 1.2269, 0.6190)
 3  (-0.1020,-0.7010) (-0.6691, 0.3689) (-5.1414,-1.1300) ( 0.9983, 0.3850)
 4  (-0.5359, 0.2707) (-0.2040, 0.8601) ( 0.0082, 0.1211) ( 0.1482,-0.1252)

 IPIV
            3                 2                 3                 4

Source

    Program zgetrf_example

!     ZGETRF Example Program Text

!     Copyright 2017, Numerical Algorithms Group Ltd. http://www.nag.com

!     .. Use Statements ..
      Use lapack_example_aux, Only: nagf_file_print_matrix_complex_gen_comp
      Use lapack_interfaces, Only: zgetrf
      Use lapack_precision, Only: dp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter :: nin = 5, nout = 6
!     .. Local Scalars ..
      Integer :: i, ifail, info, lda, m, n
!     .. Local Arrays ..
      Complex (Kind=dp), Allocatable :: a(:, :)
      Integer, Allocatable :: ipiv(:)
      Character (1) :: clabs(1), rlabs(1)
!     .. Intrinsic Procedures ..
      Intrinsic :: min
!     .. Executable Statements ..
      Write (nout, *) 'ZGETRF Example Program Results'
!     Skip heading in data file
      Read (nin, *)
      Read (nin, *) m, n
      lda = m
      Allocate (a(lda,n), ipiv(n))

!     Read A from data file

      Read (nin, *)(a(i,1:n), i=1, m)

!     Factorize A

      Call zgetrf(m, n, a, lda, ipiv, info)

!     Print details of factorization

      Write (nout, *)
      Flush (nout)

!     ifail: behaviour on error exit
!             =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
      ifail = 0
      Call nagf_file_print_matrix_complex_gen_comp('General', ' ', m, n, a, &
        lda, 'Bracketed', 'F7.4', 'Details of factorization', 'Integer', &
        rlabs, 'Integer', clabs, 80, 0, ifail)

!     Print pivot indices

      Write (nout, *)
      Write (nout, *) 'IPIV'
      Write (nout, 100) ipiv(1:min(m,n))

      If (info/=0) Then
        Write (nout, *) 'The factor U is singular'
      End If

100   Format ((1X,I12,3I18))
    End Program
Full documentation of ZGETRF


ZGETRI example

Computational Routines: Inverse of complex matrix, matrix already factorized by ZGETRF

Data

ZGETRI Example Program Data
  4                                                       :Value of N
 (-1.34, 2.55) ( 0.28, 3.17) (-6.39,-2.20) ( 0.72,-0.92)
 (-0.17,-1.41) ( 3.31,-0.15) (-0.15, 1.34) ( 1.29, 1.38)
 (-3.29,-2.39) (-1.91, 4.42) (-0.14,-1.35) ( 1.72, 1.35)
 ( 2.41, 0.39) (-0.56, 1.47) (-0.83,-0.69) (-1.96, 0.67)  :End of matrix A

Result

 ZGETRI Example Program Results

 Inverse
                    1                 2                 3                 4
 1  ( 0.0757,-0.4324) ( 1.6512,-3.1342) ( 1.2663, 0.0418) ( 3.8181, 1.1195)
 2  (-0.1942, 0.0798) (-1.1900,-0.1426) (-0.2401,-0.5889) (-0.0101,-1.4969)
 3  (-0.0957,-0.0491) ( 0.7371,-0.4290) ( 0.3224, 0.0776) ( 0.6887, 0.7891)
 4  ( 0.3702,-0.5040) ( 3.7253,-3.1813) ( 1.7014, 0.7267) ( 3.9367, 3.3255)

Source

    Program zgetri_example

!     ZGETRI Example Program Text

!     Copyright 2017, Numerical Algorithms Group Ltd. http://www.nag.com

!     .. Use Statements ..
      Use lapack_example_aux, Only: nagf_file_print_matrix_complex_gen_comp
      Use lapack_interfaces, Only: zgetrf, zgetri
      Use lapack_precision, Only: dp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter :: nin = 5, nout = 6
!     .. Local Scalars ..
      Integer :: i, ifail, info, lda, lwork, n
!     .. Local Arrays ..
      Complex (Kind=dp), Allocatable :: a(:, :), work(:)
      Integer, Allocatable :: ipiv(:)
      Character (1) :: clabs(1), rlabs(1)
!     .. Executable Statements ..
      Write (nout, *) 'ZGETRI Example Program Results'
!     Skip heading in data file
      Read (nin, *)
      Read (nin, *) n
      lda = n
      lwork = 64*n
      Allocate (a(lda,n), work(lwork), ipiv(n))

!     Read A from data file

      Read (nin, *)(a(i,1:n), i=1, n)

!     Factorize A
      Call zgetrf(n, n, a, lda, ipiv, info)

      Write (nout, *)
      Flush (nout)
      If (info==0) Then

!       Compute inverse of A
        Call zgetri(n, a, lda, ipiv, work, lwork, info)

!       Print inverse

!       ifail: behaviour on error exit
!              =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
        ifail = 0
        Call nagf_file_print_matrix_complex_gen_comp('General', ' ', n, n, a, &
          lda, 'Bracketed', 'F7.4', 'Inverse', 'Integer', rlabs, 'Integer', &
          clabs, 80, 0, ifail)

      Else
        Write (nout, *) 'The factor U is singular'
      End If

    End Program
Full documentation of ZGETRI


ZGETRS example

Computational Routines: Solution of complex system of linear equations, multiple right-hand sides, matrix already factorized by ZGETRF

Data

ZGETRS Example Program Data
  4  2                                                    :Values of N and NRHS
 (-1.34, 2.55) ( 0.28, 3.17) (-6.39,-2.20) ( 0.72,-0.92)
 (-0.17,-1.41) ( 3.31,-0.15) (-0.15, 1.34) ( 1.29, 1.38)
 (-3.29,-2.39) (-1.91, 4.42) (-0.14,-1.35) ( 1.72, 1.35)
 ( 2.41, 0.39) (-0.56, 1.47) (-0.83,-0.69) (-1.96, 0.67)  :End of matrix A
 (26.26, 51.78) (31.32, -6.70)
 ( 6.43, -8.68) (15.86, -1.42)
 (-5.75, 25.31) (-2.15, 30.19)
 ( 1.16,  2.57) (-2.56,  7.55)                            :End of matrix B

Result

 ZGETRS Example Program Results

 Solution(s)
                    1                 2
 1  ( 1.0000, 1.0000) (-1.0000,-2.0000)
 2  ( 2.0000,-3.0000) ( 5.0000, 1.0000)
 3  (-4.0000,-5.0000) (-3.0000, 4.0000)
 4  ( 0.0000, 6.0000) ( 2.0000,-3.0000)

Source

    Program zgetrs_example

!     ZGETRS Example Program Text

!     Copyright 2017, Numerical Algorithms Group Ltd. http://www.nag.com

!     .. Use Statements ..
      Use lapack_example_aux, Only: nagf_file_print_matrix_complex_gen_comp
      Use lapack_interfaces, Only: zgetrf, zgetrs
      Use lapack_precision, Only: dp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter :: nin = 5, nout = 6
      Character (1), Parameter :: trans = 'N'
!     .. Local Scalars ..
      Integer :: i, ifail, info, lda, ldb, n, nrhs
!     .. Local Arrays ..
      Complex (Kind=dp), Allocatable :: a(:, :), b(:, :)
      Integer, Allocatable :: ipiv(:)
      Character (1) :: clabs(1), rlabs(1)
!     .. Executable Statements ..
      Write (nout, *) 'ZGETRS Example Program Results'
!     Skip heading in data file
      Read (nin, *)
      Read (nin, *) n, nrhs
      lda = n
      ldb = n
      Allocate (a(lda,n), b(ldb,nrhs), ipiv(n))

!     Read A and B from data file

      Read (nin, *)(a(i,1:n), i=1, n)
      Read (nin, *)(b(i,1:nrhs), i=1, n)

!     Factorize A

      Call zgetrf(n, n, a, lda, ipiv, info)

      Write (nout, *)
      Flush (nout)
      If (info==0) Then

!       Compute solution

        Call zgetrs(trans, n, nrhs, a, lda, ipiv, b, ldb, info)

!       Print solution

!       ifail: behaviour on error exit
!              =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
        ifail = 0
        Call nagf_file_print_matrix_complex_gen_comp('General', ' ', n, nrhs, &
          b, ldb, 'Bracketed', 'F7.4', 'Solution(s)', 'Integer', rlabs, &
          'Integer', clabs, 80, 0, ifail)

      Else
        Write (nout, *) 'The factor U is singular'
      End If

    End Program
Full documentation of ZGETRS


ZGGQRF example

Computational Routines: Computes a generalized QR factorization of a complex matrix pair

Data

ZGGQRF Example Program Data

  4             3             4                         :Values of N, M and P

( 0.96,-0.81) (-0.03, 0.96) (-0.91, 2.06)
(-0.98, 1.98) (-1.20, 0.19) (-0.66, 0.42)
( 0.62,-0.46) ( 1.01, 0.02) ( 0.63,-0.17)
( 1.08,-0.28) ( 0.20,-0.12) (-0.07, 1.23)               :End of matrix A

( 0.50,-1.00) ( 0.00, 0.00) ( 0.00, 0.00) ( 0.00, 0.00)
( 0.00, 0.00) ( 1.00,-2.00) ( 0.00, 0.00) ( 0.00, 0.00)
( 0.00, 0.00) ( 0.00, 0.00) ( 2.00,-3.00) ( 0.00, 0.00)
( 0.00, 0.00) ( 0.00, 0.00) ( 0.00, 0.00) ( 5.00,-4.00) :End of matrix B

( 6.00,-0.40)
(-5.27, 0.90)
( 2.72,-2.13)
(-1.30,-2.80)                                           :End of vector d

Result

 ZGGQRF Example Program Results

 Generalized least squares solution
 (  -0.9846,   1.9950) (   3.9929,  -4.9748) (  -3.0026,   0.9994)

 Residual vector
 ( 1.26E-04,-4.66E-04) ( 1.11E-03,-8.61E-04) ( 3.84E-03,-1.82E-03)
 ( 2.03E-03, 3.02E-03)

 Square root of the residual sum of squares
   5.79E-03

Source

    Program zggqrf_example

!     ZGGQRF Example Program Text

!     Copyright 2017, Numerical Algorithms Group Ltd. http://www.nag.com

!     .. Use Statements ..
      Use blas_interfaces, Only: dznrm2, zgemv
      Use lapack_interfaces, Only: zggqrf, ztrtrs, zunmqr, zunmrq
      Use lapack_precision, Only: dp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Complex (Kind=dp), Parameter :: one = (1.0E0_dp, 0.0E0_dp)
      Complex (Kind=dp), Parameter :: zero = (0.0E0_dp, 0.0E0_dp)
      Integer, Parameter :: nb = 64, nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=dp) :: rnorm
      Integer :: i, info, lda, ldb, lwork, m, n, p
!     .. Local Arrays ..
      Complex (Kind=dp), Allocatable :: a(:, :), b(:, :), d(:), taua(:), &
        taub(:), work(:), y(:)
!     .. Intrinsic Procedures ..
      Intrinsic :: max, min
!     .. Executable Statements ..
      Write (nout, *) 'ZGGQRF Example Program Results'
      Write (nout, *)
!     Skip heading in data file
      Read (nin, *)
      Read (nin, *) n, m, p
      lda = n
      ldb = n
      lwork = nb*(m+p)
      Allocate (a(lda,m), b(ldb,p), d(n), taua(m), taub(m+p), work(lwork), &
        y(p))

!     Read A, B and D from data file
      Read (nin, *)(a(i,1:m), i=1, n)
      Read (nin, *)(b(i,1:p), i=1, n)
      Read (nin, *) d(1:n)

!     Compute the generalized QR factorization of (A,B) as
!     A = Q*(R),   B = Q*(T11 T12)*Z
!            (0)          ( 0  T22)
      Call zggqrf(n, m, p, a, lda, taua, b, ldb, taub, work, lwork, info)

!     Compute c = (c1) = (Q**H)*d, storing the result in D
!                  (c2)
      Call zunmqr('Left', 'Conjugate transpose', n, 1, m, a, lda, taua, d, n, &
        work, lwork, info)

!     Putting Z*y = w = (w1), set w1 = 0, storing the result in Y1
!                        (w2)
      y(1:m+p-n) = zero

      If (n>m) Then

!       Copy c2 into Y2

        y(m+p-n+1:p) = d(m+1:n)

!       Solve T22*w2 = c2 for w2, storing result in Y2

        Call ztrtrs('Upper', 'No transpose', 'Non-unit', n-m, 1, &
          b(m+1,m+p-n+1), ldb, y(m+p-n+1), n-m, info)

        If (info>0) Then
          Write (nout, *) &
            'The upper triangular factor, T22, of B is singular, '
          Write (nout, *) 'the least squares solution could not be computed'
          Go To 100
        End If

!       Compute estimate of the square root of the residual sum of
!       squares norm(y) = norm(w2)
        rnorm = dznrm2(n-m, y(m+p-n+1), 1)

!       Form c1 - T12*w2 in D
        Call zgemv('No transpose', m, n-m, -one, b(1,m+p-n+1), ldb, &
          y(m+p-n+1), 1, one, d, 1)
      End If

!     Solve R*x = c1 - T12*w2 for x
      Call ztrtrs('Upper', 'No transpose', 'Non-unit', m, 1, a, lda, d, m, &
        info)

      If (info>0) Then
        Write (nout, *) 'The upper triangular factor, R, of A is singular, '
        Write (nout, *) 'the least squares solution could not be computed'
      Else

!       Compute y = (Z**H)*w
        Call zunmrq('Left', 'Conjugate transpose', p, 1, min(n,p), b(max(1, &
          n-p+1),1), ldb, taub, y, p, work, lwork, info)

!       Print least squares solution x
        Write (nout, *) 'Generalized least squares solution'
        Write (nout, 110) d(1:m)

!       Print residual vector y
        Write (nout, *)
        Write (nout, *) 'Residual vector'
        Write (nout, 120) y(1:p)

!       Print estimate of the square root of the residual sum of
!       squares
        Write (nout, *)
        Write (nout, *) 'Square root of the residual sum of squares'
        Write (nout, 130) rnorm
      End If
100   Continue

110   Format (3(' (',F9.4,',',F9.4,')',:))
120   Format (3(' (',1P,E9.2,',',1P,E9.2,')',:))
130   Format (1X, 1P, E10.2)
    End Program
Full documentation of ZGGQRF


ZGGRQF example

Computational Routines: Computes a generalized RQ factorization of a complex matrix pair

Data

ZGGRQF Example Program Data

  6             4             2                         : m, n and p

( 0.96,-0.81) (-0.03, 0.96) (-0.91, 2.06) (-0.05, 0.41)
(-0.98, 1.98) (-1.20, 0.19) (-0.66, 0.42) (-0.81, 0.56)
( 0.62,-0.46) ( 1.01, 0.02) ( 0.63,-0.17) (-1.11, 0.60)
( 0.37, 0.38) ( 0.19,-0.54) (-0.98,-0.36) ( 0.22,-0.20)
( 0.83, 0.51) ( 0.20, 0.01) (-0.17,-0.46) ( 1.47, 1.59)
( 1.08,-0.28) ( 0.20,-0.12) (-0.07, 1.23) ( 0.26, 0.26) : A

( 1.00, 0.00) ( 0.00, 0.00) (-1.00, 0.00) ( 0.00, 0.00)
( 0.00, 0.00) ( 1.00, 0.00) ( 0.00, 0.00) (-1.00, 0.00) : B

(-2.54, 0.09)
( 1.65,-2.26)
(-2.11,-3.96)
( 1.82, 3.30)
(-6.41, 3.77)
( 2.07, 0.66)                                           : c

( 0.00, 0.00)
( 0.00, 0.00)                                           : d

Result

 ZGGRQF Example Program Results

 Constrained least squares solution
 ( 1.0874,-1.9621) (-0.7409, 3.7297) ( 1.0874,-1.9621) (-0.7409, 3.7297)

 Square root of the residual sum of squares
   1.59E-01

Source

    Program zggrqf_example

!     ZGGRQF Example Program Text

!     Copyright 2017, Numerical Algorithms Group Ltd. http://www.nag.com

!     .. Use Statements ..
      Use blas_interfaces, Only: dznrm2, zgemv, ztrmv
      Use lapack_interfaces, Only: zggrqf, ztrtrs, zunmqr, zunmrq
      Use lapack_precision, Only: dp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Complex (Kind=dp), Parameter :: one = (1.0E0_dp, 0.0E0_dp)
      Integer, Parameter :: nb = 64, nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=dp) :: rnorm
      Integer :: i, info, lda, ldb, lwork, m, n, p
!     .. Local Arrays ..
      Complex (Kind=dp), Allocatable :: a(:, :), b(:, :), c(:), d(:), taua(:), &
        taub(:), work(:), x(:)
!     .. Intrinsic Procedures ..
      Intrinsic :: min
!     .. Executable Statements ..
      Write (nout, *) 'ZGGRQF Example Program Results'
      Write (nout, *)
!     Skip heading in data file
      Read (nin, *)
      Read (nin, *) m, n, p
      lda = m
      ldb = p
      lwork = nb*(p+n)
      Allocate (a(lda,n), b(ldb,n), c(m), d(p), taua(n), taub(n), work(lwork), &
        x(n))

!     Read A, B, C and D from data file

      Read (nin, *)(a(i,1:n), i=1, m)
      Read (nin, *)(b(i,1:n), i=1, p)
      Read (nin, *) c(1:m)
      Read (nin, *) d(1:p)

!     Compute the generalized RQ factorization of (B,A) as
!     B = (0 T12)*Q,   A = Z*(R11 R12)*Q, where T12 and R11
!                            ( 0  R22)
!     are upper triangular
      Call zggrqf(p, m, n, b, ldb, taub, a, lda, taua, work, lwork, info)

!     Set Qx = y. The problem then reduces to:
!                 minimize (Ry - Z^Hc) subject to Ty = d
!     Update c = Z^H*c -> minimize (Ry-c)
      Call zunmqr('Left', 'Conjugate transpose', m, 1, min(m,n), a, lda, taua, &
        c, m, work, lwork, info)

!     Putting y = (y1), solve T12*w = d for w, storing result in d
!                 (w )
      Call ztrtrs('Upper', 'No transpose', 'Non-unit', p, 1, b(1,n-p+1), ldb, &
        d, p, info)

      If (info>0) Then
        Write (nout, *) 'The upper triangular factor of B is singular, '
        Write (nout, *) 'the least squares solution could not be computed'
        Go To 100
      End If

!     From first n-p rows of (Ry-c) we have
!     R11*y1 + R12*w = c(1:n-p) = c1
!     Form c1 = c1 - R12*w = R11*y1

      Call zgemv('No transpose', n-p, p, -one, a(1,n-p+1), lda, d, 1, one, c, &
        1)

!     Solve R11*y1 = c1 for y1, storing result in c(1:n-p)
      Call ztrtrs('Upper', 'No transpose', 'Non-unit', n-p, 1, a, lda, c, n-p, &
        info)

      If (info>0) Then
        Write (nout, *) 'The upper triangular factor of A is singular, '
        Write (nout, *) 'the least squares solution could not be computed'
        Go To 100
      End If

!     Copy y into x (first y1, then w)
      x(1:n-p) = c(1:n-p)
      x(n-p+1:n) = d(1:p)

!     Compute x = (Q**H)*y
      Call zunmrq('Left', 'Conjugate transpose', n, 1, p, b, ldb, taub, x, n, &
        work, lwork, info)

!     The least squares solution is in x, the remainder here is to compute
!     the residual, which equals c2 - R22*w.

!     Upper triangular part of R22 first
      Call ztrmv('Upper', 'No transpose', 'Non-unit', min(m,n)-n+p, &
        a(n-p+1,n-p+1), lda, d, 1)
      Do i = 1, min(m, n) - n + p
        c(n-p+i) = c(n-p+i) - d(i)
      End Do

      If (m<n) Then

!       Additional rectangular part of R22
        Call zgemv('No transpose', m-n+p, n-m, -one, a(n-p+1,m+1), lda, &
          d(m-n+p+1), 1, one, c(n-p+1), 1)

      End If

!     Compute norm of residual sum of squares.
      rnorm = dznrm2(m-(n-p), c(n-p+1), 1)

!     Print least squares solution x
      Write (nout, *) 'Constrained least squares solution'
      Write (nout, 110) x(1:n)

!     Print estimate of the square root of the residual sum of
!     squares
      Write (nout, *)
      Write (nout, *) 'Square root of the residual sum of squares'
      Write (nout, 120) rnorm

100   Continue

110   Format (4(' (',F7.4,',',F7.4,')',:))
120   Format (1X, 1P, E10.2)
    End Program
Full documentation of ZGGRQF


ZGGSVP3 example

Computational Routines: Produces unitary matrices, using BLAS-3, that simultaneously reduce the complex, m by n, matrix A and the complex, p by n, matrix B to upper triangular form

Data

ZGGSVP3 Example Program Data

  6             4             2                         :Values of M, N and P

( 0.96,-0.81) (-0.03, 0.96) (-0.91, 2.06) (-0.05, 0.41)
(-0.98, 1.98) (-1.20, 0.19) (-0.66, 0.42) (-0.81, 0.56)
( 0.62,-0.46) ( 1.01, 0.02) ( 0.63,-0.17) (-1.11, 0.60)
( 0.37, 0.38) ( 0.19,-0.54) (-0.98,-0.36) ( 0.22,-0.20)
( 0.83, 0.51) ( 0.20, 0.01) (-0.17,-0.46) ( 1.47, 1.59)
( 1.08,-0.28) ( 0.20,-0.12) (-0.07, 1.23) ( 0.26, 0.26) :End of matrix A

( 1.00, 0.00) ( 0.00, 0.00) (-1.00, 0.00) ( 0.00, 0.00)
( 0.00, 0.00) ( 1.00, 0.00) ( 0.00, 0.00) (-1.00, 0.00) :End of matrix B

Result

 ZGGSVP3 Example Program Results

 Number of infinite generalized singular values (k)
     2
 Number of finite generalized singular values (l)
     2
 Effective Numerical rank of (A; B) (k+l)
     4

 Finite generalized singular values
     2.0720E+00  1.1058E+00

 Unitary matrix U
                              1                           2
 1  ( -1.3038E-02, -3.2595E-01) ( -1.4039E-01, -2.6167E-01)
 2  (  4.2764E-01, -6.2582E-01) (  8.6298E-02, -3.8174E-02)
 3  ( -3.2595E-01,  1.6428E-01) (  3.8163E-01, -1.8219E-01)
 4  (  1.5906E-01, -5.2151E-03) ( -2.8207E-01,  1.9732E-01)
 5  ( -1.7210E-01, -1.3038E-02) ( -5.0942E-01, -5.0319E-01)
 6  ( -2.6336E-01, -2.4772E-01) ( -1.0861E-01,  2.8474E-01)

                              3                           4
 1  (  2.5177E-01, -7.9789E-01) ( -5.0956E-02, -2.1750E-01)
 2  ( -3.2188E-01,  1.6112E-01) (  1.1979E-01,  1.6319E-01)
 3  (  1.3231E-01, -1.4565E-02) ( -5.0671E-01,  1.8615E-01)
 4  (  2.1598E-01,  1.8813E-01) ( -4.0163E-01,  2.6787E-01)
 5  (  3.6488E-02,  2.0316E-01) (  1.9271E-01,  1.5574E-01)
 6  (  1.0906E-01, -1.2712E-01) ( -8.8159E-02,  5.6169E-01)

                              5                           6
 1  ( -4.5947E-02,  1.4052E-04) ( -5.2773E-02, -2.2492E-01)
 2  ( -8.0311E-02, -4.3605E-01) ( -3.8117E-02, -2.1907E-01)
 3  (  5.9714E-02, -5.8974E-01) ( -1.3850E-01, -9.0941E-02)
 4  ( -4.6443E-02,  3.0864E-01) ( -3.7354E-01, -5.5148E-01)
 5  (  5.7843E-01, -1.2439E-01) ( -1.8815E-02, -5.5686E-02)
 6  (  1.5763E-02,  4.7130E-02) (  6.5007E-01,  4.9173E-03)

 Unitary matrix V
                              1                           2
 1  (  9.8930E-01,  1.9041E-19) ( -1.1461E-01,  9.0250E-02)
 2  ( -1.1461E-01, -9.0250E-02) ( -9.8930E-01,  1.9041E-19)

 Unitary matrix Q
                              1                           2
 1  (  7.0711E-01,  0.0000E+00) (  0.0000E+00,  0.0000E+00)
 2  (  0.0000E+00,  0.0000E+00) (  7.0711E-01,  0.0000E+00)
 3  (  7.0711E-01,  0.0000E+00) (  0.0000E+00,  0.0000E+00)
 4  (  0.0000E+00,  0.0000E+00) (  7.0711E-01,  0.0000E+00)

                              3                           4
 1  (  6.9954E-01,  4.7274E-19) (  8.1044E-02, -6.3817E-02)
 2  ( -8.1044E-02, -6.3817E-02) (  6.9954E-01, -4.7274E-19)
 3  ( -6.9954E-01, -4.7274E-19) ( -8.1044E-02,  6.3817E-02)
 4  (  8.1044E-02,  6.3817E-02) ( -6.9954E-01,  4.7274E-19)

 Nonsingular upper triangular matrix R
                              1                           2
 1  ( -2.7118E+00,  0.0000E+00) ( -1.4390E+00, -1.0315E+00)
 2                              ( -1.8583E+00,  0.0000E+00)
 3
 4

                              3                           4
 1  ( -7.6930E-02,  1.3613E+00) ( -2.8137E-01, -3.2425E-02)
 2  ( -1.0760E+00,  3.1016E-02) (  1.3292E+00,  3.6772E-01)
 3  (  3.2537E+00,  0.0000E+00) ( -6.3858E-17,  6.3858E-17)
 4                              ( -2.1084E+00,  0.0000E+00)

 Number of cycles of the Kogbetliantz method
     2

Source

    Program zggsvp3_example

!     ZGGSVP3 Example Program Text

!     Copyright 2017, Numerical Algorithms Group Ltd. http://www.nag.com

!     .. Use Statements ..
      Use lapack_example_aux, Only: nagf_file_print_matrix_complex_gen_comp
      Use lapack_interfaces, Only: zggsvp3, zlange, ztgsja
      Use lapack_precision, Only: dp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=dp) :: eps, tola, tolb
      Integer :: i, ifail, info, irank, j, k, l, lda, ldb, ldq, ldu, ldv, &
        lwork, m, n, ncycle, p
!     .. Local Arrays ..
      Complex (Kind=dp), Allocatable :: a(:, :), b(:, :), q(:, :), tau(:), &
        u(:, :), v(:, :), work(:)
      Complex (Kind=dp) :: wdum(1)
      Real (Kind=dp), Allocatable :: alpha(:), beta(:), rwork(:)
      Integer, Allocatable :: iwork(:)
      Character (1) :: clabs(1), rlabs(1)
!     .. Intrinsic Procedures ..
      Intrinsic :: epsilon, max, nint, real
!     .. Executable Statements ..
      Write (nout, *) 'ZGGSVP3 Example Program Results'
      Write (nout, *)
      Flush (nout)
!     Skip heading in data file
      Read (nin, *)
      Read (nin, *) m, n, p
      lda = m
      ldb = p
      ldq = n
      ldu = m
      ldv = p
      Allocate (a(lda,n), alpha(n), b(ldb,n), beta(n), q(ldq,n), tau(n), &
        u(ldu,m), v(ldv,p), rwork(2*n), iwork(n))

!     Perform workspace query to get optimal size of work
      lwork = -1
      Call zggsvp3('U', 'V', 'Q', m, p, n, a, lda, b, ldb, tola, tolb, k, l, &
        u, ldu, v, ldv, q, ldq, iwork, rwork, tau, wdum, lwork, info)
      lwork = nint(real(wdum(1)))
      Allocate (work(lwork))

!     Read the m by n matrix A and p by n matrix B from data file

      Read (nin, *)(a(i,1:n), i=1, m)
      Read (nin, *)(b(i,1:n), i=1, p)

!     Compute tola and tolb as
!         tola = max(m,n)*norm(A)*macheps
!         tolb = max(p,n)*norm(B)*macheps

      eps = epsilon(1.0E0_dp)
      tola = real(max(m,n), kind=dp)*zlange('One-norm', m, n, a, lda, rwork)* &
        eps
      tolb = real(max(p,n), kind=dp)*zlange('One-norm', p, n, b, ldb, rwork)* &
        eps

!     Compute the factorization of (A, B)
!         (A = U*S*(Q**H), B = V*T*(Q**H))

      Call zggsvp3('U', 'V', 'Q', m, p, n, a, lda, b, ldb, tola, tolb, k, l, &
        u, ldu, v, ldv, q, ldq, iwork, rwork, tau, work, lwork, info)

!     Compute the generalized singular value decomposition of (A, B)
!         (A = U*D1*(0 R)*(Q**H), B = V*D2*(0 R)*(Q**H))

      Deallocate (work)
      Allocate (work(2*n))

      Call ztgsja('U', 'V', 'Q', m, p, n, k, l, a, lda, b, ldb, tola, tolb, &
        alpha, beta, u, ldu, v, ldv, q, ldq, work, ncycle, info)

!     Print solution

      irank = k + l
      Write (nout, *) 'Number of infinite generalized singular values (k)'
      Write (nout, 100) k
      Write (nout, *) 'Number of finite generalized singular values (l)'
      Write (nout, 100) l
      Write (nout, *) 'Effective Numerical rank of (A; B) (k+l)'
      Write (nout, 100) irank
      Write (nout, *)
      Write (nout, *) 'Finite generalized singular values'
      Write (nout, 110)(alpha(j)/beta(j), j=k+1, irank)
      Write (nout, *)
      Flush (nout)

!     ifail: behaviour on error exit
!            =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
      ifail = 0
      Call nagf_file_print_matrix_complex_gen_comp('General', ' ', m, m, u, &
        ldu, 'Bracketed', '1P,E12.4', 'Unitary matrix U', 'Integer', rlabs, &
        'Integer', clabs, 80, 0, ifail)

      Write (nout, *)
      Flush (nout)

      Call nagf_file_print_matrix_complex_gen_comp('General', ' ', p, p, v, &
        ldv, 'Bracketed', '1P,E12.4', 'Unitary matrix V', 'Integer', rlabs, &
        'Integer', clabs, 80, 0, ifail)

      Write (nout, *)
      Flush (nout)

      Call nagf_file_print_matrix_complex_gen_comp('General', ' ', n, n, q, &
        ldq, 'Bracketed', '1P,E12.4', 'Unitary matrix Q', 'Integer', rlabs, &
        'Integer', clabs, 80, 0, ifail)

      Write (nout, *)
      Flush (nout)

      Call nagf_file_print_matrix_complex_gen_comp('Upper triangular', &
        'Non-unit', irank, irank, a(1,n-irank+1), lda, 'Bracketed', &
        '1P,E12.4', 'Nonsingular upper triangular matrix R', 'Integer', rlabs, &
        'Integer', clabs, 80, 0, ifail)

      Write (nout, *)
      Write (nout, *) 'Number of cycles of the Kogbetliantz method'
      Write (nout, 100) ncycle

100   Format (1X, I5)
110   Format (3X, 8(1P,E12.4))
    End Program
Full documentation of ZGGSVP3


ZGTCON example

Computational Routines: Estimates the reciprocal of the condition number of a complex tridiagonal matrix using the LU factorization computed by DGTTRF

Data

ZGTCON Example Program Data
   5                                             :Value of N
 ( 2.0,-1.0) ( 2.0, 1.0) (-1.0, 1.0) ( 1.0,-1.0) :End of DU
 (-1.3, 1.3) (-1.3, 1.3) (-1.3, 3.3) (-0.3, 4.3)
 (-3.3, 1.3)                                     :End of D
 ( 1.0,-2.0) ( 1.0, 1.0) ( 2.0,-3.0) ( 1.0, 1.0) :End of DL

Result

 ZGTCON Example Program Results

 Estimate of condition number =   1.84E+02

Source

    Program zgtcon_example

!     ZGTCON Example Program Text

!     Copyright 2017, Numerical Algorithms Group Ltd. http://www.nag.com

!     .. Use Statements ..
      Use lapack_interfaces, Only: zgtcon, zgttrf, zlangt
      Use lapack_precision, Only: dp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=dp) :: anorm, rcond
      Integer :: info, n
!     .. Local Arrays ..
      Complex (Kind=dp), Allocatable :: d(:), dl(:), du(:), du2(:), work(:)
      Integer, Allocatable :: ipiv(:)
!     .. Intrinsic Procedures ..
      Intrinsic :: epsilon
!     .. Executable Statements ..
      Write (nout, *) 'ZGTCON Example Program Results'
      Write (nout, *)
!     Skip heading in data file
      Read (nin, *)
      Read (nin, *) n

      Allocate (d(n), dl(n-1), du(n-1), du2(n-2), work(2*n), ipiv(n))

!     Read the tridiagonal matrix A from data file

      Read (nin, *) du(1:n-1)
      Read (nin, *) d(1:n)
      Read (nin, *) dl(1:n-1)

!     Compute the 1-norm of A
      anorm = zlangt('1-norm', n, dl, d, du)

!     Factorize the tridiagonal matrix A
      Call zgttrf(n, dl, d, du, du2, ipiv, info)

      If (info==0) Then

!       Estimate the condition number of A
        Call zgtcon('1-norm', n, dl, d, du, du2, ipiv, anorm, rcond, work, &
          info)

!       Print the estimated condition number

        If (rcond>=epsilon(1.0E0_dp)) Then
          Write (nout, 100) 'Estimate of condition number = ', 1.0E0_dp/rcond
        Else
          Write (nout, 100) 'A is singular to working precision. RCOND = ', &
            rcond
        End If

      Else
        Write (nout, 110) 'The (', info, ',', info, ')', &
          ' element of the factor U is zero'
      End If

100   Format (1X, A, 1P, E10.2)
110   Format (1X, A, I3, A, I3, A, A)
    End Program
Full documentation of ZGTCON


ZGTRFS example

Computational Routines: Refined solution with error bounds of complex tridiagonal system of linear equations, multiple right-hand sides

Data

ZGTRFS Example Program Data
   5    2                                                :Values of N and NRHS
 (  2.0, -1.0) (  2.0,  1.0) ( -1.0,  1.0) (  1.0, -1.0) :End of DU
 ( -1.3,  1.3) ( -1.3,  1.3) ( -1.3,  3.3) ( -0.3,  4.3)
 ( -3.3,  1.3)                                           :End of D
 (  1.0, -2.0) (  1.0 , 1.0) (  2.0, -3.0) (  1.0,  1.0) :End of  DL
 (  2.4, -5.0) (  2.7,  6.9)
 (  3.4, 18.2) ( -6.9, -5.3)
 (-14.7,  9.7) ( -6.0, -0.6)
 ( 31.9, -7.7) ( -3.9,  9.3)
 ( -1.0,  1.6) ( -3.0, 12.2)                             :End of B

Result

 ZGTRFS Example Program Results

 Solution(s)
                    1                 2
 1  ( 1.0000, 1.0000) ( 2.0000,-1.0000)
 2  ( 3.0000,-1.0000) ( 1.0000, 2.0000)
 3  ( 4.0000, 5.0000) (-1.0000, 1.0000)
 4  (-1.0000,-2.0000) ( 2.0000, 1.0000)
 5  ( 1.0000,-1.0000) ( 2.0000,-2.0000)

 Backward errors (machine-dependent)
       7.2E-17    6.7E-17

 Estimated forward error bounds (machine-dependent)
       5.6E-14    7.4E-14

Source

    Program zgtrfs_example

!     ZGTRFS Example Program Text

!     Copyright 2017, Numerical Algorithms Group Ltd. http://www.nag.com

!     .. Use Statements ..
      Use lapack_example_aux, Only: nagf_file_print_matrix_complex_gen_comp
      Use lapack_interfaces, Only: zgtrfs, zgttrf, zgttrs
      Use lapack_precision, Only: dp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter :: nin = 5, nout = 6
!     .. Local Scalars ..
      Integer :: i, ifail, info, ldb, ldx, n, nrhs
!     .. Local Arrays ..
      Complex (Kind=dp), Allocatable :: b(:, :), d(:), df(:), dl(:), dlf(:), &
        du(:), du2(:), duf(:), work(:), x(:, :)
      Real (Kind=dp), Allocatable :: berr(:), ferr(:), rwork(:)
      Integer, Allocatable :: ipiv(:)
      Character (1) :: clabs(1), rlabs(1)
!     .. Executable Statements ..
      Write (nout, *) 'ZGTRFS Example Program Results'
      Write (nout, *)
      Flush (nout)
!     Skip heading in data file
      Read (nin, *)
      Read (nin, *) n, nrhs
      ldb = n
      ldx = n
      Allocate (b(ldb,nrhs), d(n), df(n), dl(n-1), dlf(n-1), du(n-1), &
        du2(n-2), duf(n-1), work(2*n), x(ldx,nrhs), berr(nrhs), ferr(nrhs), &
        rwork(n), ipiv(n))

!     Read the tridiagonal matrix A from data file

      Read (nin, *) du(1:n-1)
      Read (nin, *) d(1:n)
      Read (nin, *) dl(1:n-1)

!     Read the right hand matrix B

      Read (nin, *)(b(i,1:nrhs), i=1, n)

!     Copy A into DUF, DF and DLF, and copy B into X

      duf(1:n-1) = du(1:n-1)
      df(1:n) = d(1:n)
      dlf(1:n-1) = dl(1:n-1)
      x(1:n, 1:nrhs) = b(1:n, 1:nrhs)

!     Factorize the copy of the tridiagonal matrix A
      Call zgttrf(n, dlf, df, duf, du2, ipiv, info)

      If (info==0) Then

!       Solve the equations AX = B
        Call zgttrs('No transpose', n, nrhs, dlf, df, duf, du2, ipiv, x, ldx, &
          info)

!       Improve the solution and compute error estimates
        Call zgtrfs('No transpose', n, nrhs, dl, d, du, dlf, df, duf, du2, &
          ipiv, b, ldb, x, ldx, ferr, berr, work, rwork, info)

!       Print the solution and the forward and backward error
!       estimates

!       ifail: behaviour on error exit
!              =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
        ifail = 0
        Call nagf_file_print_matrix_complex_gen_comp('General', ' ', n, nrhs, &
          x, ldx, 'Bracketed', 'F7.4', 'Solution(s)', 'Integer', rlabs, &
          'Integer', clabs, 80, 0, ifail)

        Write (nout, *)
        Write (nout, *) 'Backward errors (machine-dependent)'
        Write (nout, 100) berr(1:nrhs)
        Write (nout, *)
        Write (nout, *) 'Estimated forward error bounds (machine-dependent)'
        Write (nout, 100) ferr(1:nrhs)
      Else
        Write (nout, 110) 'The (', info, ',', info, ')', &
          ' element of the factor U is zero'
      End If

100   Format ((3X,1P,7E11.1))
110   Format (1X, A, I3, A, I3, A, A)
    End Program
Full documentation of ZGTRFS


ZGTTRF example

Computational Routines: LU factorization of complex tridiagonal matrix

Data

ZGTTRF Example Program Data
   5                                             :Value of N
 ( 2.0,-1.0) ( 2.0, 1.0) (-1.0, 1.0) ( 1.0,-1.0) :End of DU
 (-1.3, 1.3) (-1.3, 1.3) (-1.3, 3.3) (-0.3, 4.3)
 (-3.3, 1.3)                                     :End of D
 ( 1.0,-2.0) ( 1.0, 1.0) ( 2.0,-3.0) ( 1.0, 1.0) :End of DL

Result

 ZGTTRF Example Program Results

 Details of factorization

  Second superdiagonal of U
 (  2.0000,  1.0000) ( -1.0000,  1.0000) (  1.0000, -1.0000)

  First superdiagonal of U
 ( -1.3000,  1.3000) ( -1.3000,  3.3000) ( -0.3000,  4.3000) ( -3.3000,  1.3000)

  Main diagonal of U
 (  1.0000, -2.0000) (  1.0000,  1.0000) (  2.0000, -3.0000) (  1.0000,  1.0000)
 ( -1.3399,  0.2875)

  Multipliers
 ( -0.7800, -0.2600) (  0.1620, -0.4860) ( -0.0452, -0.0010) ( -0.3979, -0.0562)

  Vector of interchanges
       2      3      4      5      5

Source

    Program zgttrf_example

!     ZGTTRF Example Program Text

!     Copyright 2017, Numerical Algorithms Group Ltd. http://www.nag.com

!     .. Use Statements ..
      Use lapack_interfaces, Only: zgttrf
      Use lapack_precision, Only: dp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter :: nin = 5, nout = 6
!     .. Local Scalars ..
      Integer :: info, n
!     .. Local Arrays ..
      Complex (Kind=dp), Allocatable :: d(:), dl(:), du(:), du2(:)
      Integer, Allocatable :: ipiv(:)
!     .. Executable Statements ..
      Write (nout, *) 'ZGTTRF Example Program Results'
      Write (nout, *)
!     Skip heading in data file
      Read (nin, *)
      Read (nin, *) n

      Allocate (d(n), dl(n-1), du(n-1), du2(n-2), ipiv(n))

!     Read the tridiagonal matrix A from data file

      Read (nin, *) du(1:n-1)
      Read (nin, *) d(1:n)
      Read (nin, *) dl(1:n-1)

!     Factorize the tridiagonal matrix A
      Call zgttrf(n, dl, d, du, du2, ipiv, info)

      If (info>0) Then
        Write (nout, 100) 'The (', info, ',', info, ')', &
          ' element of the factor U is zero'
      End If

!     Print details of the factorization

      Write (nout, *) 'Details of factorization'
      Write (nout, *)
      Write (nout, *) ' Second superdiagonal of U'
      Write (nout, 110) du2(1:n-2)
      Write (nout, *)
      Write (nout, *) ' First superdiagonal of U'
      Write (nout, 110) du(1:n-1)
      Write (nout, *)
      Write (nout, *) ' Main diagonal of U'
      Write (nout, 110) d(1:n)
      Write (nout, *)
      Write (nout, *) ' Multipliers'
      Write (nout, 110) dl(1:n-1)
      Write (nout, *)
      Write (nout, *) ' Vector of interchanges'
      Write (nout, 120) ipiv(1:n)

100   Format (1X, A, I3, A, I3, A, A)
110   Format (4(' (',F8.4,',',F8.4,')',:))
120   Format (1X, 5I7)
    End Program
Full documentation of ZGTTRF


ZGTTRS example

Computational Routines: Solves a complex tridiagonal system of linear equations using the LU factorization computed by DGTTRF

Data

ZGTTRS Example Program Data
   5    2                                                :Values of N and NRHS
 (  2.0, -1.0) (  2.0,  1.0) ( -1.0,  1.0) (  1.0, -1.0) :End of DU
 ( -1.3,  1.3) ( -1.3,  1.3) ( -1.3,  3.3) ( -0.3,  4.3)
 ( -3.3,  1.3)                                           :End of D
 (  1.0, -2.0) (  1.0 , 1.0) (  2.0, -3.0) (  1.0,  1.0) :End of  DL
 (  2.4, -5.0) (  2.7,  6.9)
 (  3.4, 18.2) ( -6.9, -5.3)
 (-14.7,  9.7) ( -6.0, -0.6)
 ( 31.9, -7.7) ( -3.9,  9.3)
 ( -1.0,  1.6) ( -3.0, 12.2)                             :End of B

Result

 ZGTTRS Example Program Results

 Solution(s)
                    1                 2
 1  ( 1.0000, 1.0000) ( 2.0000,-1.0000)
 2  ( 3.0000,-1.0000) ( 1.0000, 2.0000)
 3  ( 4.0000, 5.0000) (-1.0000, 1.0000)
 4  (-1.0000,-2.0000) ( 2.0000, 1.0000)
 5  ( 1.0000,-1.0000) ( 2.0000,-2.0000)

Source

    Program zgttrs_example

!     ZGTTRS Example Program Text

!     Copyright 2017, Numerical Algorithms Group Ltd. http://www.nag.com

!     .. Use Statements ..
      Use lapack_example_aux, Only: nagf_file_print_matrix_complex_gen_comp
      Use lapack_interfaces, Only: zgttrf, zgttrs
      Use lapack_precision, Only: dp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter :: nin = 5, nout = 6
!     .. Local Scalars ..
      Integer :: i, ifail, info, ldb, n, nrhs
!     .. Local Arrays ..
      Complex (Kind=dp), Allocatable :: b(:, :), d(:), dl(:), du(:), du2(:)
      Integer, Allocatable :: ipiv(:)
      Character (1) :: clabs(1), rlabs(1)
!     .. Executable Statements ..
      Write (nout, *) 'ZGTTRS Example Program Results'
      Write (nout, *)
      Flush (nout)
!     Skip heading in data file
      Read (nin, *)
      Read (nin, *) n, nrhs
      ldb = n
      Allocate (b(ldb,nrhs), d(n), dl(n-1), du(n-1), du2(n-2), ipiv(n))

!     Read the tridiagonal matrix A from data file

      Read (nin, *) du(1:n-1)
      Read (nin, *) d(1:n)
      Read (nin, *) dl(1:n-1)

!     Read the right hand matrix B

      Read (nin, *)(b(i,1:nrhs), i=1, n)

!     Factorize the tridiagonal matrix A
      Call zgttrf(n, dl, d, du, du2, ipiv, info)

      If (info==0) Then

!       Solve the equations AX = B
        Call zgttrs('No transpose', n, nrhs, dl, d, du, du2, ipiv, b, ldb, &
          info)

!       Print the solution

!       ifail: behaviour on error exit
!              =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
        ifail = 0
        Call nagf_file_print_matrix_complex_gen_comp('General', ' ', n, nrhs, &
          b, ldb, 'Bracketed', 'F7.4', 'Solution(s)', 'Integer', rlabs, &
          'Integer', clabs, 80, 0, ifail)

      Else
        Write (nout, 100) 'The (', info, ',', info, ')', &
          ' element of the factor U is zero'
      End If

100   Format (1X, A, I3, A, I3, A, A)
    End Program
Full documentation of ZGTTRS


ZHBGST example

Computational Routines: Reduction of complex Hermitian-definite banded generalized eigenproblem Ax = lambda Bx to standard form Cy = lambda y, such that C has the same bandwidth as A

Data

ZHBGST Example Program Data
  4  2  1                                            :Values of N, KA and KB
  'L'                                                :Value of UPLO
 (-1.13, 0.00)
 ( 1.94, 2.10) (-1.91, 0.00)
 (-1.40,-0.25) (-0.82, 0.89) (-1.87, 0.00)
               (-0.67,-0.34) (-1.10, 0.16) ( 0.50, 0.00)    :End of matrix A
 ( 9.89, 0.00)
 ( 1.08, 1.73) ( 1.69, 0.00)
               (-0.04,-0.29) ( 2.65, 0.00)
                             (-0.33,-2.24) ( 2.17, 0.00)    :End of matrix B

Result

 ZHBGST Example Program Results

 Eigenvalues
    -6.6089 -2.0416  0.1603  1.7712

Source

    Program zhbgst_example

!     ZHBGST Example Program Text

!     Copyright 2017, Numerical Algorithms Group Ltd. http://www.nag.com

!     .. Use Statements ..
      Use lapack_interfaces, Only: dsterf, zhbgst, zhbtrd, zpbstf
      Use lapack_precision, Only: dp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter :: nin = 5, nout = 6
!     .. Local Scalars ..
      Integer :: i, info, j, ka, kb, ldab, ldbb, ldx, n
      Character (1) :: uplo
!     .. Local Arrays ..
      Complex (Kind=dp), Allocatable :: ab(:, :), bb(:, :), work(:), x(:, :)
      Real (Kind=dp), Allocatable :: d(:), e(:), rwork(:)
!     .. Intrinsic Procedures ..
      Intrinsic :: max, min
!     .. Executable Statements ..
      Write (nout, *) 'ZHBGST Example Program Results'
!     Skip heading in data file
      Read (nin, *)
      Read (nin, *) n, ka, kb
      ldab = ka + 1
      ldbb = kb + 1
      ldx = n
      Allocate (ab(ldab,n), bb(ldbb,n), work(n), x(ldx,n), d(n), e(n-1), &
        rwork(n))

!     Read A and B from data file

      Read (nin, *) uplo
      If (uplo=='U') Then
        Do i = 1, n
          Read (nin, *)(ab(ka+1+i-j,j), j=i, min(n,i+ka))
        End Do
        Do i = 1, n
          Read (nin, *)(bb(kb+1+i-j,j), j=i, min(n,i+kb))
        End Do
      Else If (uplo=='L') Then
        Do i = 1, n
          Read (nin, *)(ab(1+i-j,j), j=max(1,i-ka), i)
        End Do
        Do i = 1, n
          Read (nin, *)(bb(1+i-j,j), j=max(1,i-kb), i)
        End Do
      End If

!     Compute the split Cholesky factorization of B
      Call zpbstf(uplo, n, kb, bb, ldbb, info)

      Write (nout, *)
      If (info>0) Then
        Write (nout, *) 'B is not positive definite.'
      Else

!       Reduce the problem to standard form C*y = lambda*y, storing
!       the result in A
        Call zhbgst('N', uplo, n, ka, kb, ab, ldab, bb, ldbb, x, ldx, work, &
          rwork, info)

!       Reduce C to tridiagonal form T = (Q**H)*C*Q
        Call zhbtrd('N', uplo, n, ka, ab, ldab, d, e, x, ldx, work, info)

!       Calculate the eigenvalues of T (same as C)
        Call dsterf(n, d, e, info)

        If (info>0) Then
          Write (nout, *) 'Failure to converge.'
        Else

!         Print eigenvalues

          Write (nout, *) 'Eigenvalues'
          Write (nout, 100) d(1:n)
        End If
      End If

100   Format (3X, (8F8.4))
    End Program
Full documentation of ZHBGST


ZHBTRD example

Computational Routines: Unitary reduction of complex Hermitian band matrix to real symmetric tridiagonal form

Data

ZHBTRD Example Program Data
  4  2                                                     :Values of N and KD
  'L'                                                      :Value of UPLO
 (-3.13, 0.00)
 ( 1.94, 2.10) (-1.91, 0.00)
 (-3.40,-0.25) (-0.82, 0.89) (-2.87, 0.00)
               (-0.67,-0.34) (-2.10, 0.16) ( 0.50, 0.00)   :End of matrix A

Result

 ZHBTRD Example Program Results

 Eigenvalues
        -7.0042           -4.0038            0.5968            3.0012

 Eigenvectors
                    1                 2                 3                 4
 1  ( 0.7293, 0.0000) (-0.2128, 0.1511) (-0.3354,-0.1604) (-0.5114,-0.0163)
 2  (-0.1654,-0.2046) ( 0.7316, 0.0000) (-0.2804,-0.3413) (-0.2374,-0.3796)
 3  ( 0.6081, 0.0301) ( 0.3910,-0.3843) (-0.0144, 0.1532) ( 0.5523,-0.0000)
 4  ( 0.1653,-0.0303) ( 0.2775,-0.1378) ( 0.8019, 0.0000) (-0.4517, 0.1693)

Source

    Program zhbtrd_example

!     ZHBTRD Example Program Text

!     Copyright 2017, Numerical Algorithms Group Ltd. http://www.nag.com

!     .. Use Statements ..
      Use blas_interfaces, Only: dznrm2
      Use lapack_example_aux, Only: nagf_file_print_matrix_complex_gen_comp
      Use lapack_interfaces, Only: zhbtrd, zsteqr
      Use lapack_precision, Only: dp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter :: nin = 5, nout = 6
!     .. Local Scalars ..
      Complex (Kind=dp) :: scal
      Integer :: i, ifail, info, j, k, kd, ldab, ldq, n
      Character (1) :: uplo
!     .. Local Arrays ..
      Complex (Kind=dp), Allocatable :: ab(:, :), q(:, :), work(:)
      Real (Kind=dp), Allocatable :: d(:), e(:), rwork(:)
      Character (1) :: clabs(1), rlabs(1)
!     .. Intrinsic Procedures ..
      Intrinsic :: abs, conjg, max, maxloc, min
!     .. Executable Statements ..
      Write (nout, *) 'ZHBTRD Example Program Results'
!     Skip heading in data file
      Read (nin, *)
      Read (nin, *) n, kd
      ldab = kd + 1
      ldq = n
      Allocate (ab(ldab,n), q(ldq,n), work(n), d(n), e(n-1), rwork(2*n-2))

!     Read A from data file

      Read (nin, *) uplo
      If (uplo=='U') Then
        Do i = 1, n
          Read (nin, *)(ab(kd+1+i-j,j), j=i, min(n,i+kd))
        End Do
      Else If (uplo=='L') Then
        Do i = 1, n
          Read (nin, *)(ab(1+i-j,j), j=max(1,i-kd), i)
        End Do
      End If

!     Reduce A to tridiagonal form T = (Q**H)*A*Q (and form Q)
      Call zhbtrd('V', uplo, n, kd, ab, ldab, d, e, q, ldq, work, info)

!     Calculate all the eigenvalues and eigenvectors of A
      Call zsteqr('V', n, d, e, q, ldq, rwork, info)

      Write (nout, *)
      If (info>0) Then
        Write (nout, *) 'Failure to converge.'
      Else

!       Print eigenvalues and eigenvectors

        Write (nout, *) 'Eigenvalues'
        Write (nout, 100) d(1:n)
        Write (nout, *)
        Flush (nout)

!       Normalize the eigenvectors, largest element real
        Do i = 1, n
          rwork(1:n) = abs(q(1:n,i))
          k = maxloc(rwork(1:n), 1)
          scal = conjg(q(k,i))/abs(q(k,i))/dznrm2(n, q(1,i), 1)
          q(1:n, i) = q(1:n, i)*scal
        End Do

!       ifail: behaviour on error exit
!              =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
        ifail = 0
        Call nagf_file_print_matrix_complex_gen_comp('General', ' ', n, n, q, &
          ldq, 'Bracketed', 'F7.4', 'Eigenvectors', 'Integer', rlabs, &
          'Integer', clabs, 80, 0, ifail)

      End If

100   Format (8X, 4(F7.4,11X,:))
    End Program
Full documentation of ZHBTRD


ZHECON example

Computational Routines: Estimate condition number of complex Hermitian indefinite matrix, matrix already factorized by ZHETRF

Data

ZHECON Example Program Data
  4                                                       :Value of N
  'L'                                                     :Value of UPLO
 (-1.36, 0.00)
 ( 1.58,-0.90) (-8.87, 0.00)
 ( 2.21, 0.21) (-1.84, 0.03) (-4.63, 0.00)
 ( 3.91,-1.50) (-1.78,-1.18) ( 0.11,-0.11) (-1.84, 0.00)  :End of matrix A

Result

 ZHECON Example Program Results

 Estimate of condition number =  6.68E+00

Source

    Program zhecon_example

!     ZHECON Example Program Text

!     Copyright 2017, Numerical Algorithms Group Ltd. http://www.nag.com

!     .. Use Statements ..
      Use lapack_interfaces, Only: zhecon, zhetrf, zlanhe
      Use lapack_precision, Only: dp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=dp) :: anorm, rcond
      Integer :: i, info, lda, lwork, n
      Character (1) :: uplo
!     .. Local Arrays ..
      Complex (Kind=dp), Allocatable :: a(:, :), work(:)
      Real (Kind=dp), Allocatable :: rwork(:)
      Integer, Allocatable :: ipiv(:)
!     .. Intrinsic Procedures ..
      Intrinsic :: epsilon
!     .. Executable Statements ..
      Write (nout, *) 'ZHECON Example Program Results'
!     Skip heading in data file
      Read (nin, *)
      Read (nin, *) n
      lda = n
      lwork = 64*n
      Allocate (a(lda,n), work(lwork), rwork(n), ipiv(n))

!     Read A from data file

      Read (nin, *) uplo
      If (uplo=='U') Then
        Read (nin, *)(a(i,i:n), i=1, n)
      Else If (uplo=='L') Then
        Read (nin, *)(a(i,1:i), i=1, n)
      End If

!     Compute norm of A
      anorm = zlanhe('1-norm', uplo, n, a, lda, rwork)

!     Factorize A
      Call zhetrf(uplo, n, a, lda, ipiv, work, lwork, info)

      Write (nout, *)
      If (info==0) Then

!       Estimate condition number
        Call zhecon(uplo, n, a, lda, ipiv, anorm, rcond, work, info)

        If (rcond>=epsilon(1.0E0_dp)) Then
          Write (nout, 100) 'Estimate of condition number =', 1.0_dp/rcond
        Else
          Write (nout, *) 'A is singular to working precision'
        End If
      Else
        Write (nout, *) 'The factor D is singular'
      End If

100   Format (1X, A, 1P, E10.2)
    End Program
Full documentation of ZHECON


ZHEGST example

Computational Routines: Reduction to standard form of complex Hermitian-definite generalized eigenproblem Ax = lambda Bx, ABx = lambda x or BAx = lambda x, B factorized by ZPOTRF

Data

ZHEGST Example Program Data
  4                                                       :Value of N
  'L'                                                     :Value of UPLO
 (-7.36, 0.00)
 ( 0.77, 0.43) ( 3.49, 0.00)
 (-0.64, 0.92) ( 2.19,-4.45) ( 0.12, 0.00)
 ( 3.01, 6.97) ( 1.90,-3.73) ( 2.88, 3.17) (-2.54, 0.00)  :End of matrix A
 ( 3.23, 0.00)
 ( 1.51, 1.92) ( 3.58, 0.00)
 ( 1.90,-0.84) (-0.23,-1.11) ( 4.09, 0.00)
 ( 0.42,-2.50) (-1.18,-1.37) ( 2.33, 0.14) ( 4.29, 0.00)  :End of matrix B

Result

 ZHEGST Example Program Results

 Eigenvalues
    -5.9990 -2.9936  0.5047  3.9990

Source

    Program zhegst_example

!     ZHEGST Example Program Text

!     Copyright 2017, Numerical Algorithms Group Ltd. http://www.nag.com

!     .. Use Statements ..
      Use lapack_interfaces, Only: dsterf, zhegst, zhetrd, zpotrf
      Use lapack_precision, Only: dp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter :: nin = 5, nout = 6
!     .. Local Scalars ..
      Integer :: i, info, lda, ldb, lwork, n
      Character (1) :: uplo
!     .. Local Arrays ..
      Complex (Kind=dp), Allocatable :: a(:, :), b(:, :), tau(:), work(:)
      Real (Kind=dp), Allocatable :: d(:), e(:)
!     .. Executable Statements ..
      Write (nout, *) 'ZHEGST Example Program Results'
!     Skip heading in data file
      Read (nin, *)
      Read (nin, *) n
      lda = n
      ldb = n
      lwork = 64*n
      Allocate (a(lda,n), b(ldb,n), tau(n), work(lwork), d(n), e(n-1))

!     Read A and B from data file

      Read (nin, *) uplo
      If (uplo=='U') Then
        Read (nin, *)(a(i,i:n), i=1, n)
        Read (nin, *)(b(i,i:n), i=1, n)
      Else If (uplo=='L') Then
        Read (nin, *)(a(i,1:i), i=1, n)
        Read (nin, *)(b(i,1:i), i=1, n)
      End If

!     Compute the Cholesky factorization of B
      Call zpotrf(uplo, n, b, ldb, info)

      Write (nout, *)
      If (info>0) Then
        Write (nout, *) 'B is not positive definite.'
      Else

!       Reduce the problem to standard form C*y = lambda*y, storing
!       the result in A
        Call zhegst(1, uplo, n, a, lda, b, ldb, info)

!       Reduce C to tridiagonal form T = (Q**H)*C*Q
        Call zhetrd(uplo, n, a, lda, d, e, tau, work, lwork, info)

!       Calculate the eigenvalues of T (same as C)
        Call dsterf(n, d, e, info)

        If (info>0) Then
          Write (nout, *) 'Failure to converge.'
        Else

!         Print eigenvalues

          Write (nout, *) 'Eigenvalues'
          Write (nout, 100) d(1:n)
        End If
      End If

100   Format (3X, (9F8.4))
    End Program
Full documentation of ZHEGST


ZHERFS example

Computational Routines: Refined solution with error bounds of complex Hermitian indefinite system of linear equations, multiple right-hand sides

Data

ZHERFS Example Program Data
  4  2                                                    :Values of N and NRHS
  'L'                                                     :Value of UPLO
 (-1.36, 0.00)
 ( 1.58,-0.90) (-8.87, 0.00)
 ( 2.21, 0.21) (-1.84, 0.03) (-4.63, 0.00)
 ( 3.91,-1.50) (-1.78,-1.18) ( 0.11,-0.11) (-1.84, 0.00)  :End of matrix A
 ( 7.79,  5.48) (-35.39, 18.01)
 (-0.77,-16.05) (  4.23,-70.02)
 (-9.58,  3.88) (-24.79, -8.40)
 ( 2.98,-10.18) ( 28.68,-39.89)                           :End of matrix B

Result

 ZHERFS Example Program Results

 Solution(s)
                    1                 2
 1  ( 1.0000,-1.0000) ( 3.0000,-4.0000)
 2  (-1.0000, 2.0000) (-1.0000, 5.0000)
 3  ( 3.0000,-2.0000) ( 7.0000,-2.0000)
 4  ( 2.0000, 1.0000) (-8.0000, 6.0000)

 Backward errors (machine-dependent)
         5.1E-17           3.5E-17
 Estimated forward error bounds (machine-dependent)
         2.5E-15           3.0E-15

Source

    Program zherfs_example

!     ZHERFS Example Program Text

!     Copyright 2017, Numerical Algorithms Group Ltd. http://www.nag.com

!     .. Use Statements ..
      Use lapack_example_aux, Only: nagf_file_print_matrix_complex_gen_comp
      Use lapack_interfaces, Only: zherfs, zhetrf, zhetrs, zlacpy
      Use lapack_precision, Only: dp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter :: nin = 5, nout = 6
!     .. Local Scalars ..
      Integer :: i, ifail, info, lda, ldaf, ldb, ldx, lwork, n, nrhs
      Character (1) :: uplo
!     .. Local Arrays ..
      Complex (Kind=dp), Allocatable :: a(:, :), af(:, :), b(:, :), work(:), &
        x(:, :)
      Real (Kind=dp), Allocatable :: berr(:), ferr(:), rwork(:)
      Integer, Allocatable :: ipiv(:)
      Character (1) :: clabs(1), rlabs(1)
!     .. Executable Statements ..
      Write (nout, *) 'ZHERFS Example Program Results'
!     Skip heading in data file
      Read (nin, *)
      Read (nin, *) n, nrhs
      lda = n
      ldaf = n
      ldb = n
      ldx = n
      lwork = 64*n
      Allocate (a(lda,n), af(ldaf,n), b(ldb,nrhs), work(lwork), x(ldx,n), &
        berr(nrhs), ferr(nrhs), rwork(n), ipiv(n))

!     Read A and B from data file, and copy A to AF and B to X

      Read (nin, *) uplo
      If (uplo=='U') Then
        Read (nin, *)(a(i,i:n), i=1, n)
      Else If (uplo=='L') Then
        Read (nin, *)(a(i,1:i), i=1, n)
      End If
      Read (nin, *)(b(i,1:nrhs), i=1, n)

      Call zlacpy(uplo, n, n, a, lda, af, ldaf)
      x(1:n, 1:nrhs) = b(1:n, 1:nrhs)

!     Factorize A in the array AF
      Call zhetrf(uplo, n, af, ldaf, ipiv, work, lwork, info)

      Write (nout, *)
      Flush (nout)
      If (info==0) Then

!       Compute solution in the array X
        Call zhetrs(uplo, n, nrhs, af, ldaf, ipiv, x, ldx, info)

!       Improve solution, and compute backward errors and
!       estimated bounds on the forward errors

        Call zherfs(uplo, n, nrhs, a, lda, af, ldaf, ipiv, b, ldb, x, ldx, &
          ferr, berr, work, rwork, info)

!       Print solution

!       ifail: behaviour on error exit
!              =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
        ifail = 0
        Call nagf_file_print_matrix_complex_gen_comp('General', ' ', n, nrhs, &
          x, ldx, 'Bracketed', 'F7.4', 'Solution(s)', 'Integer', rlabs, &
          'Integer', clabs, 80, 0, ifail)

        Write (nout, *)
        Write (nout, *) 'Backward errors (machine-dependent)'
        Write (nout, 100) berr(1:nrhs)
        Write (nout, *) 'Estimated forward error bounds (machine-dependent)'
        Write (nout, 100) ferr(1:nrhs)
      Else
        Write (nout, *) 'The factor D is singular'
      End If

100   Format ((5X,1P,4(E11.1,7X)))
    End Program
Full documentation of ZHERFS


ZHETRD example

Computational Routines: Unitary reduction of complex Hermitian matrix to real symmetric tridiagonal form

Data

ZHETRD Example Program Data
  4                                                        :Value of N
  'L'                                                      :Value of UPLO
 (-2.28, 0.00)
 ( 1.78, 2.03) (-1.12, 0.00)
 ( 2.26,-0.10) ( 0.01,-0.43) (-0.37, 0.00)
 (-0.12,-2.53) (-1.07,-0.86) ( 2.31, 0.92) (-0.73, 0.00)   :End of matrix A

Result

 ZHETRD Example Program Results

 Diagonal and off-diagonal elements of tridiagonal form

     i         D            E
     1     -2.28000      4.33846
     2     -0.12846      2.02259
     3     -0.16659      1.80232
     4     -1.92495

Source

    Program zhetrd_example

!     ZHETRD Example Program Text

!     Copyright 2017, Numerical Algorithms Group Ltd. http://www.nag.com

!     .. Use Statements ..
      Use lapack_interfaces, Only: zhetrd
      Use lapack_precision, Only: dp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter :: nin = 5, nout = 6
!     .. Local Scalars ..
      Integer :: i, info, lda, lwork, n
      Character (1) :: uplo
!     .. Local Arrays ..
      Complex (Kind=dp), Allocatable :: a(:, :), tau(:), work(:)
      Real (Kind=dp), Allocatable :: d(:), e(:)
!     .. Intrinsic Procedures ..
      Intrinsic :: abs
!     .. Executable Statements ..
      Write (nout, *) 'ZHETRD Example Program Results'
!     Skip heading in data file
      Read (nin, *)
      Read (nin, *) n
      lda = n
      lwork = 64*n
      Allocate (a(lda,n), tau(n-1), work(lwork), d(n), e(n-1))

!     Read A from data file and copy A into C

      Read (nin, *) uplo
      If (uplo=='U') Then
        Read (nin, *)(a(i,i:n), i=1, n)
      Else If (uplo=='L') Then
        Read (nin, *)(a(i,1:i), i=1, n)
      End If

!     Reduce A to tridiagonal form
      Call zhetrd(uplo, n, a, lda, d, e, tau, work, lwork, info)

      If (info==0) Then
!       Print the diagonal and off-diagonal of tridiagonal T.
!       The absolute value of E is printed since this can vary by a change of
!       sign (corresponding to multiplying through a column of Q by -1).

        Write (nout, *)
        Write (nout, *) &
          'Diagonal and off-diagonal elements of tridiagonal form'
        Write (nout, *)
        Write (nout, 100) 'i', 'D', 'E'
        Do i = 1, n - 1
          Write (nout, 110) i, d(i), abs(e(i))
        End Do
        Write (nout, 110) n, d(n)

      Else
        Write (nout, 120) info
      End If

100   Format (5X, A, 9X, A, 12X, A)
110   Format (1X, I5, 2(1X,F12.5))
120   Format (1X, '** ZHETRD retuned with INFO = ', I10)

    End Program
Full documentation of ZHETRD


ZHETRF example

Computational Routines: Bunch-Kaufman factorization of complex Hermitian indefinite matrix

Data

ZHETRF Example Program Data
  4                                                       :Value of N
  'L'                                                     :Value of UPLO
 (-1.36, 0.00)
 ( 1.58,-0.90) (-8.87, 0.00)
 ( 2.21, 0.21) (-1.84, 0.03) (-4.63, 0.00)
 ( 3.91,-1.50) (-1.78,-1.18) ( 0.11,-0.11) (-1.84, 0.00)  :End of matrix A

Result

 ZHETRF Example Program Results

 Details of factorization
                    1                 2                 3                 4
 1  (-1.3600, 0.0000)
 2  ( 3.9100,-1.5000) (-1.8400, 0.0000)
 3  ( 0.3100, 0.0433) ( 0.5637, 0.2850) (-5.4176, 0.0000)
 4  (-0.1518, 0.3743) ( 0.3397, 0.0303) ( 0.2997, 0.1578) (-7.1028, 0.0000)

 IPIV
           -4                -4                 3                 4

Source

    Program zhetrf_example

!     ZHETRF Example Program Text

!     Copyright 2017, Numerical Algorithms Group Ltd. http://www.nag.com

!     .. Use Statements ..
      Use lapack_example_aux, Only: nagf_file_print_matrix_complex_gen_comp
      Use lapack_interfaces, Only: zhetrf
      Use lapack_precision, Only: dp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter :: nin = 5, nout = 6
!     .. Local Scalars ..
      Integer :: i, ifail, info, lda, lwork, n
      Character (1) :: uplo
!     .. Local Arrays ..
      Complex (Kind=dp), Allocatable :: a(:, :), work(:)
      Integer, Allocatable :: ipiv(:)
      Character (1) :: clabs(1), rlabs(1)
!     .. Executable Statements ..
      Write (nout, *) 'ZHETRF Example Program Results'
!     Skip heading in data file
      Read (nin, *)
      Read (nin, *) n
      lda = n
      lwork = 64*n
      Allocate (a(lda,n), work(lwork), ipiv(n))

!     Read A from data file

      Read (nin, *) uplo
      If (uplo=='U') Then
        Read (nin, *)(a(i,i:n), i=1, n)
      Else If (uplo=='L') Then
        Read (nin, *)(a(i,1:i), i=1, n)
      End If

!     Factorize A
      Call zhetrf(uplo, n, a, lda, ipiv, work, lwork, info)

      Write (nout, *)
      Flush (nout)

!     Print details of factorization

!     ifail: behaviour on error exit
!             =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
      ifail = 0
      Call nagf_file_print_matrix_complex_gen_comp(uplo, 'Nonunit', n, n, a, &
        lda, 'Bracketed', 'F7.4', 'Details of factorization', 'Integer', &
        rlabs, 'Integer', clabs, 80, 0, ifail)

!     Print pivot indices

      Write (nout, *)
      Write (nout, *) 'IPIV'
      Write (nout, 100) ipiv(1:n)

      If (info/=0) Then
        Write (nout, *) 'The factor D is singular'
      End If

100   Format ((1X,I12,3I18))
    End Program
Full documentation of ZHETRF


ZHETRI example

Computational Routines: Inverse of complex Hermitian indefinite matrix, matrix already factorized by ZHETRF

Data

ZHETRI Example Program Data
  4                                                       :Value of N
  'L'                                                     :Value of UPLO
 (-1.36, 0.00)
 ( 1.58,-0.90) (-8.87, 0.00)
 ( 2.21, 0.21) (-1.84, 0.03) (-4.63, 0.00)
 ( 3.91,-1.50) (-1.78,-1.18) ( 0.11,-0.11) (-1.84, 0.00)  :End of matrix A

Result

 ZHETRI Example Program Results

 Inverse
                    1                 2                 3                 4
 1  ( 0.0826, 0.0000)
 2  (-0.0335, 0.0440) (-0.1408, 0.0000)
 3  ( 0.0603,-0.0105) ( 0.0422,-0.0222) (-0.2007, 0.0000)
 4  ( 0.2391,-0.0926) ( 0.0304, 0.0203) ( 0.0982,-0.0635) ( 0.0073, 0.0000)

Source

    Program zhetri_example

!     ZHETRI Example Program Text

!     Copyright 2017, Numerical Algorithms Group Ltd. http://www.nag.com

!     .. Use Statements ..
      Use lapack_example_aux, Only: nagf_file_print_matrix_complex_gen_comp
      Use lapack_interfaces, Only: zhetrf, zhetri
      Use lapack_precision, Only: dp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter :: nin = 5, nout = 6
!     .. Local Scalars ..
      Integer :: i, ifail, info, lda, lwork, n
      Character (1) :: uplo
!     .. Local Arrays ..
      Complex (Kind=dp), Allocatable :: a(:, :), work(:)
      Integer, Allocatable :: ipiv(:)
      Character (1) :: clabs(1), rlabs(1)
!     .. Executable Statements ..
      Write (nout, *) 'ZHETRI Example Program Results'
!     Skip heading in data file
      Read (nin, *)
      Read (nin, *) n
      lda = n
      lwork = 64*n
      Allocate (a(lda,n), work(lwork), ipiv(n))

!     Read A from data file

      Read (nin, *) uplo
      If (uplo=='U') Then
        Read (nin, *)(a(i,i:n), i=1, n)
      Else If (uplo=='L') Then
        Read (nin, *)(a(i,1:i), i=1, n)
      End If

!     Factorize A
      Call zhetrf(uplo, n, a, lda, ipiv, work, lwork, info)

      Write (nout, *)
      Flush (nout)
      If (info==0) Then

!       Compute inverse of A
        Call zhetri(uplo, n, a, lda, ipiv, work, info)

!       Print inverse

!       ifail: behaviour on error exit
!              =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
        ifail = 0
        Call nagf_file_print_matrix_complex_gen_comp(uplo, 'Nonunit', n, n, a, &
          lda, 'Bracketed', 'F7.4', 'Inverse', 'Integer', rlabs, 'Integer', &
          clabs, 80, 0, ifail)

      Else
        Write (nout, *) 'The factor D is singular'
      End If

    End Program
Full documentation of ZHETRI


ZHETRS example

Computational Routines: Solution of complex Hermitian indefinite system of linear equations, multiple right-hand sides, matrix already factorized by ZHETRF

Data

ZHETRS Example Program Data
  4  2                                                    :Values of N and NRHS
  'L'                                                     :Value of UPLO
 (-1.36, 0.00)
 ( 1.58,-0.90) (-8.87, 0.00)
 ( 2.21, 0.21) (-1.84, 0.03) (-4.63, 0.00)
 ( 3.91,-1.50) (-1.78,-1.18) ( 0.11,-0.11) (-1.84, 0.00)  :End of matrix A
 ( 7.79,  5.48) (-35.39, 18.01)
 (-0.77,-16.05) (  4.23,-70.02)
 (-9.58,  3.88) (-24.79, -8.40)
 ( 2.98,-10.18) ( 28.68,-39.89)                           :End of matrix B

Result

 ZHETRS Example Program Results

 Solution(s)
                    1                 2
 1  ( 1.0000,-1.0000) ( 3.0000,-4.0000)
 2  (-1.0000, 2.0000) (-1.0000, 5.0000)
 3  ( 3.0000,-2.0000) ( 7.0000,-2.0000)
 4  ( 2.0000, 1.0000) (-8.0000, 6.0000)

Source

    Program zhetrs_example

!     ZHETRS Example Program Text

!     Copyright 2017, Numerical Algorithms Group Ltd. http://www.nag.com

!     .. Use Statements ..
      Use lapack_example_aux, Only: nagf_file_print_matrix_complex_gen_comp
      Use lapack_interfaces, Only: zhetrf, zhetrs
      Use lapack_precision, Only: dp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter :: nin = 5, nout = 6
!     .. Local Scalars ..
      Integer :: i, ifail, info, lda, ldb, lwork, n, nrhs
      Character (1) :: uplo
!     .. Local Arrays ..
      Complex (Kind=dp), Allocatable :: a(:, :), b(:, :), work(:)
      Integer, Allocatable :: ipiv(:)
      Character (1) :: clabs(1), rlabs(1)
!     .. Executable Statements ..
      Write (nout, *) 'ZHETRS Example Program Results'
!     Skip heading in data file
      Read (nin, *)
      Read (nin, *) n, nrhs
      lda = n
      ldb = n
      lwork = 64*n
      Allocate (a(lda,n), b(ldb,nrhs), work(lwork), ipiv(n))

!     Read A and B from data file

      Read (nin, *) uplo
      If (uplo=='U') Then
        Read (nin, *)(a(i,i:n), i=1, n)
      Else If (uplo=='L') Then
        Read (nin, *)(a(i,1:i), i=1, n)
      End If
      Read (nin, *)(b(i,1:nrhs), i=1, n)

!     Factorize A
      Call zhetrf(uplo, n, a, lda, ipiv, work, lwork, info)

      Write (nout, *)
      Flush (nout)
      If (info==0) Then

!       Compute solution
        Call zhetrs(uplo, n, nrhs, a, lda, ipiv, b, ldb, info)

!       Print solution

!       ifail: behaviour on error exit
!              =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
        ifail = 0
        Call nagf_file_print_matrix_complex_gen_comp('General', ' ', n, nrhs, &
          b, ldb, 'Bracketed', 'F7.4', 'Solution(s)', 'Integer', rlabs, &
          'Integer', clabs, 80, 0, ifail)

      Else
        Write (nout, *) 'The factor D is singular'
      End If

    End Program
Full documentation of ZHETRS


ZHGEQZ example

Computational Routines: Eigenvalues and generalized Schur factorization of complex generalized upper Hessenberg matrix reduced from a pair of complex general matrices

Data

ZHGEQZ Example Program Data
   4                                                    : n

(  1.0, 3.0)  (  1.0, 4.0)  (  1.0, 5.0)  (  1.0, 6.0)
(  2.0, 2.0)  (  4.0, 3.0)  (  8.0, 4.0)  ( 16.0, 5.0)
(  3.0, 1.0)  (  9.0, 2.0)  ( 27.0, 3.0)  ( 81.0, 4.0)
(  4.0, 0.0)  ( 16.0, 1.0)  ( 64.0, 2.0)  (256.0, 3.0)  : A

(  1.0, 0.0)  (  2.0, 1.0)  (  3.0, 2.0)  (  4.0, 3.0)
(  1.0, 1.0)  (  4.0, 2.0)  (  9.0, 3.0)  ( 16.0, 4.0)
(  1.0, 2.0)  (  8.0, 3.0)  ( 27.0, 4.0)  ( 64.0, 5.0)
(  1.0, 3.0)  ( 16.0, 4.0)  ( 81.0, 5.0)  (256.0, 6.0)  : B

Result

 ZHGEQZ Example Program Results
 Matrix A after balancing
                    1                 2                 3                 4
 1  ( 1.0000, 3.0000) ( 1.0000, 4.0000) ( 0.1000, 0.5000) ( 0.1000, 0.6000)
 2  ( 2.0000, 2.0000) ( 4.0000, 3.0000) ( 0.8000, 0.4000) ( 1.6000, 0.5000)
 3  ( 0.3000, 0.1000) ( 0.9000, 0.2000) ( 0.2700, 0.0300) ( 0.8100, 0.0400)
 4  ( 0.4000, 0.0000) ( 1.6000, 0.1000) ( 0.6400, 0.0200) ( 2.5600, 0.0300)

 Matrix B after balancing
                    1                 2                 3                 4
 1  ( 1.0000, 0.0000) ( 2.0000, 1.0000) ( 0.3000, 0.2000) ( 0.4000, 0.3000)
 2  ( 1.0000, 1.0000) ( 4.0000, 2.0000) ( 0.9000, 0.3000) ( 1.6000, 0.4000)
 3  ( 0.1000, 0.2000) ( 0.8000, 0.3000) ( 0.2700, 0.0400) ( 0.6400, 0.0500)
 4  ( 0.1000, 0.3000) ( 1.6000, 0.4000) ( 0.8100, 0.0500) ( 2.5600, 0.0600)

 Matrix A in Hessenberg form
                    1                 2                 3                 4
 1  ( -2.868, -1.595) ( -0.809, -0.328) ( -4.900, -0.987) ( -0.048,  1.163)
 2  ( -2.672,  0.595) ( -0.790,  0.049) ( -4.955, -0.163) ( -0.439, -0.574)
 3  (  0.000,  0.000) ( -0.098, -0.011) ( -1.168, -0.137) ( -1.756, -0.205)
 4  (  0.000,  0.000) (  0.000,  0.000) (  0.087,  0.004) (  0.032,  0.001)

 Matrix B is triangular
                    1                 2                 3                 4
 1  ( -1.775,  0.000) ( -0.721,  0.043) ( -5.021,  1.190) ( -0.145,  0.726)
 2  (  0.000,  0.000) ( -0.218,  0.035) ( -2.541, -0.146) ( -0.823, -0.418)
 3  (  0.000,  0.000) (  0.000,  0.000) ( -1.396, -0.163) ( -1.747, -0.204)
 4  (  0.000,  0.000) (  0.000,  0.000) (  0.000,  0.000) ( -0.100, -0.004)

 Minimal required LWORK =      4
 Actual value of  LWORK =     24

 Generalized eigenvalues

    1     ( -0.635,  1.653)
    2     (  0.493,  0.910)
    3     (  0.458, -0.843)
    4     (  0.674, -0.050)

Source

    Program zhgeqz_example

!     ZHGEQZ Example Program Text

!     Copyright 2017, Numerical Algorithms Group Ltd. http://www.nag.com

!     .. Use Statements ..
      Use lapack_example_aux, Only: nagf_sort_realvec_rank, &
        nagf_file_print_matrix_complex_gen_comp, &
        nagf_sort_cmplxvec_rank_rearrange
      Use lapack_interfaces, Only: zgeqrf, zggbal, zgghd3, zhgeqz, zunmqr
      Use lapack_precision, Only: dp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter :: nin = 5, nout = 6
!     .. Local Scalars ..
      Integer :: i, ifail, ihi, ilo, info, irows, jwork, lda, ldb, ldq, ldz, &
        lwork, n, ni
      Character (1) :: compq, compz, job
!     .. Local Arrays ..
      Complex (Kind=dp), Allocatable :: a(:, :), alpha(:), b(:, :), beta(:), &
        e(:), q(:, :), tau(:), work(:), z(:, :)
      Real (Kind=dp), Allocatable :: emod(:), lscale(:), rscale(:), rwork(:)
      Integer, Allocatable :: irank(:)
      Character (1) :: clabs(1), rlabs(1)
!     .. Intrinsic Procedures ..
      Intrinsic :: abs, aimag, nint, real
!     .. Executable Statements ..
      Write (nout, *) 'ZHGEQZ Example Program Results'
      Flush (nout)

!     Skip heading in data file

      Read (nin, *)
      Read (nin, *) n
      ldq = 1
      ldz = 1
      lda = n
      ldb = n
      lwork = 6*n
      Allocate (a(lda,n), alpha(n), b(ldb,n), beta(n), q(ldq,ldq), tau(n), &
        work(lwork), z(ldz,ldz), lscale(n), rscale(n), rwork(6*n))

!     READ matrix A from data file
      Read (nin, *)(a(i,1:n), i=1, n)

!     READ matrix B from data file
      Read (nin, *)(b(i,1:n), i=1, n)

!     Balance matrix pair (A,B)
      job = 'B'
      Call zggbal(job, n, a, lda, b, ldb, ilo, ihi, lscale, rscale, rwork, &
        info)

!     Matrix A after balancing

!     ifail: behaviour on error exit
!             =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
      ifail = 0
      Call nagf_file_print_matrix_complex_gen_comp('General', ' ', n, n, a, &
        lda, 'Bracketed', 'F7.4', 'Matrix A after balancing', 'Integer', &
        rlabs, 'Integer', clabs, 80, 0, ifail)

      Write (nout, *)
      Flush (nout)

!     Matrix B after balancing

      ifail = 0
      Call nagf_file_print_matrix_complex_gen_comp('General', ' ', n, n, b, &
        ldb, 'Bracketed', 'F7.4', 'Matrix B after balancing', 'Integer', &
        rlabs, 'Integer', clabs, 80, 0, ifail)

      Write (nout, *)
      Flush (nout)

!     Reduce B to triangular form using QR
      irows = ihi + 1 - ilo

      Call zgeqrf(irows, irows, b(ilo,ilo), ldb, tau, work, lwork, info)

!     Apply the orthogonal transformation to A
      Call zunmqr('L', 'C', irows, irows, irows, b(ilo,ilo), ldb, tau, &
        a(ilo,ilo), lda, work, lwork, info)

!     Compute the generalized Hessenberg form of (A,B) -> (H,T)
      compq = 'N'
      compz = 'N'

      Call zgghd3(compq, compz, irows, 1, irows, a(ilo,ilo), lda, b(ilo,ilo), &
        ldb, q, ldq, z, ldz, work, lwork, info)

!     Matrix A (H) in generalized Hessenberg form
      ifail = 0
      Call nagf_file_print_matrix_complex_gen_comp('General', ' ', n, n, a, &
        lda, 'Bracketed', 'F7.3', 'Matrix A in Hessenberg form', 'Integer', &
        rlabs, 'Integer', clabs, 80, 0, ifail)

      Write (nout, *)
      Flush (nout)

!     Matrix B (T) in generalized Hessenberg form
      ifail = 0
      Call nagf_file_print_matrix_complex_gen_comp('General', ' ', n, n, b, &
        ldb, 'Bracketed', 'F7.3', 'Matrix B is triangular', 'Integer', rlabs, &
        'Integer', clabs, 80, 0, ifail)

!     Routine ZHGEQZ
!     Workspace query: jwork = -1

      jwork = -1
      job = 'E'
      Call zhgeqz(job, compq, compz, n, ilo, ihi, a, lda, b, ldb, alpha, beta, &
        q, ldq, z, ldz, work, jwork, rwork, info)
      Write (nout, *)
      Write (nout, 100) nint(real(work(1)))
      Write (nout, 110) lwork
      Write (nout, *)
      Write (nout, 120)
      Write (nout, *)
      Flush (nout)

!     Compute the generalized Schur form
!     if the workspace lwork is adequate

      If (nint(real(work(1)))<=lwork) Then

        Call zhgeqz(job, compq, compz, n, ilo, ihi, a, lda, b, ldb, alpha, &
          beta, q, ldq, z, ldz, work, lwork, rwork, info)

!       Print the generalized eigenvalues in descending size order
!       Note: the actual values of beta are real and non-negative

!       Calculate the moduli of the finite eigenvalues.
        Allocate (e(n), emod(n), irank(n))
        ni = 0
        Do i = 1, n
          If (real(beta(i))/=0.0_dp) Then
            ni = ni + 1
            e(ni) = alpha(i)/beta(i)
            emod(ni) = abs(e(ni))
          Else
            Write (nout, 130) i
          End If
        End Do

!       Rearrange the finite eigenvalues in descending order of modulus.
        ifail = 0
        Call nagf_sort_realvec_rank(emod, 1, ni, 'Descending', irank, ifail)
        ifail = 0
        Call nagf_sort_cmplxvec_rank_rearrange(e, 1, ni, irank, ifail)

        Write (nout, 140)(i, '(', real(e(i)), ',', aimag(e(i)), ')', i=1, ni)
      Else
        Write (nout, 150)
      End If

100   Format (1X, 'Minimal required LWORK = ', I6)
110   Format (1X, 'Actual value of  LWORK = ', I6)
120   Format (1X, 'Generalized eigenvalues')
130   Format (1X, I4, 5X, 'Infinite eigenvalue')
140   Format (1X, I4, 5X, A, F7.3, A, F7.3, A)
150   Format (1X, 'Insufficient workspace allocated for call to ZHGEQZ')
    End Program
Full documentation of ZHGEQZ


ZHPCON example

Computational Routines: Estimate condition number of complex Hermitian indefinite matrix, matrix already factorized by ZHPTRF, packed storage

Data

ZHPCON Example Program Data
  4                                                       :Value of N
  'L'                                                     :Value of UPLO
 (-1.36, 0.00)
 ( 1.58,-0.90) (-8.87, 0.00)
 ( 2.21, 0.21) (-1.84, 0.03) (-4.63, 0.00)
 ( 3.91,-1.50) (-1.78,-1.18) ( 0.11,-0.11) (-1.84, 0.00)  :End of matrix A

Result

 ZHPCON Example Program Results

 Estimate of condition number =  6.68E+00

Source

    Program zhpcon_example

!     ZHPCON Example Program Text

!     Copyright 2017, Numerical Algorithms Group Ltd. http://www.nag.com

!     .. Use Statements ..
      Use lapack_interfaces, Only: zhpcon, zhptrf, zlanhp
      Use lapack_precision, Only: dp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=dp) :: anorm, rcond
      Integer :: i, info, j, n
      Character (1) :: uplo
!     .. Local Arrays ..
      Complex (Kind=dp), Allocatable :: ap(:), work(:)
      Real (Kind=dp), Allocatable :: rwork(:)
      Integer, Allocatable :: ipiv(:)
!     .. Intrinsic Procedures ..
      Intrinsic :: epsilon
!     .. Executable Statements ..
      Write (nout, *) 'ZHPCON Example Program Results'
!     Skip heading in data file
      Read (nin, *)
      Read (nin, *) n

      Allocate (ap(n*(n+1)/2), work(2*n), rwork(n), ipiv(n))

!     Read A from data file

      Read (nin, *) uplo
      If (uplo=='U') Then
        Read (nin, *)((ap(i+j*(j-1)/2),j=i,n), i=1, n)
      Else If (uplo=='L') Then
        Read (nin, *)((ap(i+(2*n-j)*(j-1)/2),j=1,i), i=1, n)
      End If

!     Compute norm of A
      anorm = zlanhp('1-norm', uplo, n, ap, rwork)

!     Factorize A
      Call zhptrf(uplo, n, ap, ipiv, info)

      Write (nout, *)
      If (info==0) Then

!       Estimate condition number
        Call zhpcon(uplo, n, ap, ipiv, anorm, rcond, work, info)

        If (rcond>=epsilon(1.0E0_dp)) Then
          Write (nout, 100) 'Estimate of condition number =', 1.0_dp/rcond
        Else
          Write (nout, *) 'A is singular to working precision'
        End If
      Else
        Write (nout, *) 'The factor D is singular'
      End If

100   Format (1X, A, 1P, E10.2)
    End Program
Full documentation of ZHPCON


ZHPGST example

Computational Routines: Reduction to standard form of complex Hermitian-definite generalized eigenproblem Ax = lambda Bx, ABx = lamda x or BAx = lambda x, packed storage, B factorized by ZPPTRF

Data

ZHPGST Example Program Data
  4                                                       :Value of N
  'L'                                                     :Value of UPLO
 (-7.36, 0.00)
 ( 0.77, 0.43) ( 3.49, 0.00)
 (-0.64, 0.92) ( 2.19,-4.45) ( 0.12, 0.00)
 ( 3.01, 6.97) ( 1.90,-3.73) ( 2.88, 3.17) (-2.54, 0.00)  :End of matrix A
 ( 3.23, 0.00)
 ( 1.51, 1.92) ( 3.58, 0.00)
 ( 1.90,-0.84) (-0.23,-1.11) ( 4.09, 0.00)
 ( 0.42,-2.50) (-1.18,-1.37) ( 2.33, 0.14) ( 4.29, 0.00)  :End of matrix B

Result

 ZHPGST Example Program Results

 Eigenvalues
    -5.9990 -2.9936  0.5047  3.9990

Source

    Program zhpgst_example

!     ZHPGST Example Program Text

!     Copyright 2017, Numerical Algorithms Group Ltd. http://www.nag.com

!     .. Use Statements ..
      Use lapack_interfaces, Only: dsterf, zhpgst, zhptrd, zpptrf
      Use lapack_precision, Only: dp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter :: nin = 5, nout = 6
!     .. Local Scalars ..
      Integer :: i, info, j, n
      Character (1) :: uplo
!     .. Local Arrays ..
      Complex (Kind=dp), Allocatable :: ap(:), bp(:), tau(:)
      Real (Kind=dp), Allocatable :: d(:), e(:)
!     .. Executable Statements ..
      Write (nout, *) 'ZHPGST Example Program Results'
!     Skip heading in data file
      Read (nin, *)
      Read (nin, *) n

      Allocate (ap(n*(n+1)/2), bp(n*(n+1)/2), tau(n), d(n), e(n-1))

!     Read A and B from data file

      Read (nin, *) uplo
      If (uplo=='U') Then
        Read (nin, *)((ap(i+j*(j-1)/2),j=i,n), i=1, n)
        Read (nin, *)((bp(i+j*(j-1)/2),j=i,n), i=1, n)
      Else If (uplo=='L') Then
        Read (nin, *)((ap(i+(2*n-j)*(j-1)/2),j=1,i), i=1, n)
        Read (nin, *)((bp(i+(2*n-j)*(j-1)/2),j=1,i), i=1, n)
      End If

!     Compute the Cholesky factorization of B
      Call zpptrf(uplo, n, bp, info)

      Write (nout, *)
      If (info>0) Then
        Write (nout, *) 'B is not positive definite.'
      Else

!       Reduce the problem to standard form C*y = lambda*y, storing
!       the result in A
        Call zhpgst(1, uplo, n, ap, bp, info)

!       Reduce C to tridiagonal form T = (Q**H)*C*Q
        Call zhptrd(uplo, n, ap, d, e, tau, info)

!       Calculate the eigenvalues of T (same as C)
        Call dsterf(n, d, e, info)

        If (info>0) Then
          Write (nout, *) 'Failure to converge.'
        Else

!         Print eigenvalues

          Write (nout, *) 'Eigenvalues'
          Write (nout, 100) d(1:n)
        End If
      End If

100   Format (3X, (9F8.4))
    End Program
Full documentation of ZHPGST


ZHPRFS example

Computational Routines: Refined solution with error bounds of complex Hermitian indefinite system of linear equations, multiple right-hand sides, packed storage

Data

ZHPRFS Example Program Data
  4  2                                                    :Values of N and NRHS
  'L'                                                     :Value of UPLO
 (-1.36, 0.00)
 ( 1.58,-0.90) (-8.87, 0.00)
 ( 2.21, 0.21) (-1.84, 0.03) (-4.63, 0.00)
 ( 3.91,-1.50) (-1.78,-1.18) ( 0.11,-0.11) (-1.84, 0.00)  :End of matrix A
 ( 7.79,  5.48) (-35.39, 18.01)
 (-0.77,-16.05) (  4.23,-70.02)
 (-9.58,  3.88) (-24.79, -8.40)
 ( 2.98,-10.18) ( 28.68,-39.89)                           :End of matrix B

Result

 ZHPRFS Example Program Results

 Solution(s)
                    1                 2
 1  ( 1.0000,-1.0000) ( 3.0000,-4.0000)
 2  (-1.0000, 2.0000) (-1.0000, 5.0000)
 3  ( 3.0000,-2.0000) ( 7.0000,-2.0000)
 4  ( 2.0000, 1.0000) (-8.0000, 6.0000)

 Backward errors (machine-dependent)
         5.1E-17           3.5E-17
 Estimated forward error bounds (machine-dependent)
         2.5E-15           3.0E-15

Source

    Program zhprfs_example

!     ZHPRFS Example Program Text

!     Copyright 2017, Numerical Algorithms Group Ltd. http://www.nag.com

!     .. Use Statements ..
      Use lapack_example_aux, Only: nagf_file_print_matrix_complex_gen_comp
      Use lapack_interfaces, Only: zhprfs, zhptrf, zhptrs
      Use lapack_precision, Only: dp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter :: nin = 5, nout = 6
!     .. Local Scalars ..
      Integer :: aplen, i, ifail, info, j, ldb, ldx, n, nrhs
      Character (1) :: uplo
!     .. Local Arrays ..
      Complex (Kind=dp), Allocatable :: afp(:), ap(:), b(:, :), work(:), &
        x(:, :)
      Real (Kind=dp), Allocatable :: berr(:), ferr(:), rwork(:)
      Integer, Allocatable :: ipiv(:)
      Character (1) :: clabs(1), rlabs(1)
!     .. Executable Statements ..
      Write (nout, *) 'ZHPRFS Example Program Results'
!     Skip heading in data file
      Read (nin, *)
      Read (nin, *) n, nrhs
      ldb = n
      ldx = n
      aplen = n*(n+1)/2
      Allocate (afp(aplen), ap(aplen), b(ldb,nrhs), work(2*n), x(ldx,n), &
        berr(nrhs), ferr(nrhs), rwork(n), ipiv(n))

!     Read A and B from data file, and copy A to AFP and B to X

      Read (nin, *) uplo
      If (uplo=='U') Then
        Read (nin, *)((ap(i+j*(j-1)/2),j=i,n), i=1, n)
      Else If (uplo=='L') Then
        Read (nin, *)((ap(i+(2*n-j)*(j-1)/2),j=1,i), i=1, n)
      End If
      Read (nin, *)(b(i,1:nrhs), i=1, n)

      afp(1:aplen) = ap(1:aplen)
      x(1:n, 1:nrhs) = b(1:n, 1:nrhs)

!     Factorize A in the array AFP
      Call zhptrf(uplo, n, afp, ipiv, info)

      Write (nout, *)
      Flush (nout)
      If (info==0) Then

!       Compute solution in the array X
        Call zhptrs(uplo, n, nrhs, afp, ipiv, x, ldx, info)

!       Improve solution, and compute backward errors and
!       estimated bounds on the forward errors

        Call zhprfs(uplo, n, nrhs, ap, afp, ipiv, b, ldb, x, ldx, ferr, berr, &
          work, rwork, info)

!       Print solution

!       ifail: behaviour on error exit
!              =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
        ifail = 0
        Call nagf_file_print_matrix_complex_gen_comp('General', ' ', n, nrhs, &
          x, ldx, 'Bracketed', 'F7.4', 'Solution(s)', 'Integer', rlabs, &
          'Integer', clabs, 80, 0, ifail)

        Write (nout, *)
        Write (nout, *) 'Backward errors (machine-dependent)'
        Write (nout, 100) berr(1:nrhs)
        Write (nout, *) 'Estimated forward error bounds (machine-dependent)'
        Write (nout, 100) ferr(1:nrhs)
      Else
        Write (nout, *) 'The factor D is singular'
      End If

100   Format ((5X,1P,4(E11.1,7X)))
    End Program
Full documentation of ZHPRFS


ZHPTRD example

Computational Routines: Unitary reduction of complex Hermitian matrix to real symmetric tridiagonal form, packed storage

Data

ZHPTRD Example Program Data
  4                                                        :Value of N
  'L'                                                      :Value of UPLO
 (-2.28, 0.00)
 ( 1.78, 2.03) (-1.12, 0.00)
 ( 2.26,-0.10) ( 0.01,-0.43) (-0.37, 0.00)
 (-0.12,-2.53) (-1.07,-0.86) ( 2.31, 0.92) (-0.73, 0.00)   :End of matrix A

Result

 ZHPTRD Example Program Results

 Diagonal and off-diagonal elements of tridiagonal form

     i         D            E
     1     -2.28000      4.33846
     2     -0.12846      2.02259
     3     -0.16659      1.80232
     4     -1.92495

Source

    Program zhptrd_example

!     ZHPTRD Example Program Text

!     Copyright 2017, Numerical Algorithms Group Ltd. http://www.nag.com

!     .. Use Statements ..
      Use lapack_interfaces, Only: zhptrd
      Use lapack_precision, Only: dp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter :: nin = 5, nout = 6
!     .. Local Scalars ..
      Integer :: i, info, j, n
      Character (1) :: uplo
!     .. Local Arrays ..
      Complex (Kind=dp), Allocatable :: ap(:), tau(:)
      Real (Kind=dp), Allocatable :: d(:), e(:)
!     .. Intrinsic Procedures ..
      Intrinsic :: abs
!     .. Executable Statements ..
      Write (nout, *) 'ZHPTRD Example Program Results'
!     Skip heading in data file
      Read (nin, *)
      Read (nin, *) n

      Allocate (ap(n*(n+1)/2), tau(n-1), d(n), e(n-1))

!     Read A from data file and copy a into AW

      Read (nin, *) uplo
      If (uplo=='U') Then
        Read (nin, *)((ap(i+j*(j-1)/2),j=i,n), i=1, n)
      Else If (uplo=='L') Then
        Read (nin, *)((ap(i+(2*n-j)*(j-1)/2),j=1,i), i=1, n)
      End If

!     Reduce A to tridiagonal form
      Call zhptrd(uplo, n, ap, d, e, tau, info)

      If (info==0) Then
!       Print the diagonal and off-diagonal of tridiagonal T.
!       The absolute value of E is printed since this can vary by a change of
!       sign (corresponding to multiplying through a column of Q by -1).

        Write (nout, *)
        Write (nout, *) &
          'Diagonal and off-diagonal elements of tridiagonal form'
        Write (nout, *)
        Write (nout, 100) 'i', 'D', 'E'
        Do i = 1, n - 1
          Write (nout, 110) i, d(i), abs(e(i))
        End Do
        Write (nout, 110) n, d(n)

      Else
        Write (nout, 120) info
      End If

100   Format (5X, A, 9X, A, 12X, A)
110   Format (1X, I5, 2(1X,F12.5))
120   Format (1X, '** ZHPTRD retuned with INFO = ', I10)

    End Program
Full documentation of ZHPTRD


ZHPTRF example

Computational Routines: Bunch-Kaufman factorization of complex Hermitian indefinite matrix, packed storage

Data

ZHPTRF Example Program Data
  4                                                       :Value of N
  'L'                                                     :Value of UPLO
 (-1.36, 0.00)
 ( 1.58,-0.90) (-8.87, 0.00)
 ( 2.21, 0.21) (-1.84, 0.03) (-4.63, 0.00)
 ( 3.91,-1.50) (-1.78,-1.18) ( 0.11,-0.11) (-1.84, 0.00)  :End of matrix A

Result

 ZHPTRF Example Program Results

 Details of factorization
                    1                 2                 3                 4
 1  (-1.3600, 0.0000)
 2  ( 3.9100,-1.5000) (-1.8400, 0.0000)
 3  ( 0.3100, 0.0433) ( 0.5637, 0.2850) (-5.4176, 0.0000)
 4  (-0.1518, 0.3743) ( 0.3397, 0.0303) ( 0.2997, 0.1578) (-7.1028, 0.0000)

 IPIV
           -4                -4                 3                 4

Source

    Program zhptrf_example

!     ZHPTRF Example Program Text

!     Copyright 2017, Numerical Algorithms Group Ltd. http://www.nag.com

!     .. Use Statements ..
      Use lapack_example_aux, Only: nagf_file_print_matrix_complex_packed_comp
      Use lapack_interfaces, Only: zhptrf
      Use lapack_precision, Only: dp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter :: nin = 5, nout = 6
!     .. Local Scalars ..
      Integer :: i, ifail, info, j, n
      Character (1) :: uplo
!     .. Local Arrays ..
      Complex (Kind=dp), Allocatable :: ap(:)
      Integer, Allocatable :: ipiv(:)
      Character (1) :: clabs(1), rlabs(1)
!     .. Executable Statements ..
      Write (nout, *) 'ZHPTRF Example Program Results'
!     Skip heading in data file
      Read (nin, *)
      Read (nin, *) n

      Allocate (ap(n*(n+1)/2), ipiv(n))

!     Read A from data file

      Read (nin, *) uplo
      If (uplo=='U') Then
        Read (nin, *)((ap(i+j*(j-1)/2),j=i,n), i=1, n)
      Else If (uplo=='L') Then
        Read (nin, *)((ap(i+(2*n-j)*(j-1)/2),j=1,i), i=1, n)
      End If

!     Factorize A
      Call zhptrf(uplo, n, ap, ipiv, info)

      Write (nout, *)
      Flush (nout)

!     Print details of factorization

!     ifail: behaviour on error exit
!            =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
      ifail = 0
      Call nagf_file_print_matrix_complex_packed_comp(uplo, 'Nonunit', n, ap, &
        'Bracketed', 'F7.4', 'Details of factorization', 'Integer', rlabs, &
        'Integer', clabs, 80, 0, ifail)

!     Print pivot indices

      Write (nout, *)
      Write (nout, *) 'IPIV'
      Write (nout, 100) ipiv(1:n)

      If (info/=0) Then
        Write (nout, *) 'The factor D is singular'
      End If

100   Format ((1X,I12,3I18))
    End Program
Full documentation of ZHPTRF


ZHPTRI example

Computational Routines: Inverse of complex Hermitian indefinite matrix, matrix already factorized by ZHPTRF, packed storage

Data

ZHPTRI Example Program Data
  4                                                       :Value of N
  'L'                                                     :Value of UPLO
 (-1.36, 0.00)
 ( 1.58,-0.90) (-8.87, 0.00)
 ( 2.21, 0.21) (-1.84, 0.03) (-4.63, 0.00)
 ( 3.91,-1.50) (-1.78,-1.18) ( 0.11,-0.11) (-1.84, 0.00)  :End of matrix A

Result

 ZHPTRI Example Program Results

 Inverse
                    1                 2                 3                 4
 1  ( 0.0826, 0.0000)
 2  (-0.0335, 0.0440) (-0.1408, 0.0000)
 3  ( 0.0603,-0.0105) ( 0.0422,-0.0222) (-0.2007, 0.0000)
 4  ( 0.2391,-0.0926) ( 0.0304, 0.0203) ( 0.0982,-0.0635) ( 0.0073, 0.0000)

Source

    Program zhptri_example

!     ZHPTRI Example Program Text

!     Copyright 2017, Numerical Algorithms Group Ltd. http://www.nag.com

!     .. Use Statements ..
      Use lapack_example_aux, Only: nagf_file_print_matrix_complex_packed_comp
      Use lapack_interfaces, Only: zhptrf, zhptri
      Use lapack_precision, Only: dp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter :: nin = 5, nout = 6
!     .. Local Scalars ..
      Integer :: i, ifail, info, j, n
      Character (1) :: uplo
!     .. Local Arrays ..
      Complex (Kind=dp), Allocatable :: ap(:), work(:)
      Integer, Allocatable :: ipiv(:)
      Character (1) :: clabs(1), rlabs(1)
!     .. Executable Statements ..
      Write (nout, *) 'ZHPTRI Example Program Results'
!     Skip heading in data file
      Read (nin, *)
      Read (nin, *) n

      Allocate (ap(n*(n+1)/2), work(n), ipiv(n))

!     Read A from data file

      Read (nin, *) uplo
      If (uplo=='U') Then
        Read (nin, *)((ap(i+j*(j-1)/2),j=i,n), i=1, n)
      Else If (uplo=='L') Then
        Read (nin, *)((ap(i+(2*n-j)*(j-1)/2),j=1,i), i=1, n)
      End If

!     Factorize A
      Call zhptrf(uplo, n, ap, ipiv, info)

      Write (nout, *)
      Flush (nout)
      If (info==0) Then

!       Compute inverse of A
        Call zhptri(uplo, n, ap, ipiv, work, info)

!       Print inverse

!       ifail: behaviour on error exit
!              =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
        ifail = 0
        Call nagf_file_print_matrix_complex_packed_comp(uplo, 'Nonunit', n, &
          ap, 'Bracketed', 'F7.4', 'Inverse', 'Integer', rlabs, 'Integer', &
          clabs, 80, 0, ifail)

      Else
        Write (nout, *) 'The factor D is singular'
      End If

    End Program
Full documentation of ZHPTRI


ZHPTRS example

Computational Routines: Solution of complex Hermitian indefinite system of linear equations, multiple right-hand sides, matrix already factorized by ZHPTRF, packed storage

Data

ZHPTRS Example Program Data
  4  2                                                    :Values of N and NRHS
  'L'                                                     :Value of UPLO
 (-1.36, 0.00)
 ( 1.58,-0.90) (-8.87, 0.00)
 ( 2.21, 0.21) (-1.84, 0.03) (-4.63, 0.00)
 ( 3.91,-1.50) (-1.78,-1.18) ( 0.11,-0.11) (-1.84, 0.00)  :End of matrix A
 ( 7.79,  5.48) (-35.39, 18.01)
 (-0.77,-16.05) (  4.23,-70.02)
 (-9.58,  3.88) (-24.79, -8.40)
 ( 2.98,-10.18) ( 28.68,-39.89)                           :End of matrix B

Result

 ZHPTRS Example Program Results

 Solution(s)
                    1                 2
 1  ( 1.0000,-1.0000) ( 3.0000,-4.0000)
 2  (-1.0000, 2.0000) (-1.0000, 5.0000)
 3  ( 3.0000,-2.0000) ( 7.0000,-2.0000)
 4  ( 2.0000, 1.0000) (-8.0000, 6.0000)

Source

    Program zhptrs_example

!     ZHPTRS Example Program Text

!     Copyright 2017, Numerical Algorithms Group Ltd. http://www.nag.com

!     .. Use Statements ..
      Use lapack_example_aux, Only: nagf_file_print_matrix_complex_gen_comp
      Use lapack_interfaces, Only: zhptrf, zhptrs
      Use lapack_precision, Only: dp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter :: nin = 5, nout = 6
!     .. Local Scalars ..
      Integer :: i, ifail, info, j, ldb, n, nrhs
      Character (1) :: uplo
!     .. Local Arrays ..
      Complex (Kind=dp), Allocatable :: ap(:), b(:, :)
      Integer, Allocatable :: ipiv(:)
      Character (1) :: clabs(1), rlabs(1)
!     .. Executable Statements ..
      Write (nout, *) 'ZHPTRS Example Program Results'
!     Skip heading in data file
      Read (nin, *)
      Read (nin, *) n, nrhs
      ldb = n
      Allocate (ap(n*(n+1)/2), b(ldb,nrhs), ipiv(n))

!     Read A and B from data file

      Read (nin, *) uplo
      If (uplo=='U') Then
        Read (nin, *)((ap(i+j*(j-1)/2),j=i,n), i=1, n)
      Else If (uplo=='L') Then
        Read (nin, *)((ap(i+(2*n-j)*(j-1)/2),j=1,i), i=1, n)
      End If
      Read (nin, *)(b(i,1:nrhs), i=1, n)

!     Factorize A
      Call zhptrf(uplo, n, ap, ipiv, info)

      Write (nout, *)
      Flush (nout)
      If (info==0) Then

!       Compute solution
        Call zhptrs(uplo, n, nrhs, ap, ipiv, b, ldb, info)

!       Print solution

!       ifail: behaviour on error exit
!              =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
        ifail = 0
        Call nagf_file_print_matrix_complex_gen_comp('General', ' ', n, nrhs, &
          b, ldb, 'Bracketed', 'F7.4', 'Solution(s)', 'Integer', rlabs, &
          'Integer', clabs, 80, 0, ifail)

      Else
        Write (nout, *) 'The factor D is singular'
      End If

    End Program
Full documentation of ZHPTRS


ZHSEQR example

Computational Routines: Eigenvalues and Schur factorization of complex upper Hessenberg matrix reduced from complex general matrix

Data

ZHSEQR Example Program Data
  4                                                             :Value of N
 (-3.9700,-5.0400) (-1.1318,-2.5693) (-4.6027,-0.1426) (-1.4249, 1.7330)
 (-5.4797, 0.0000) ( 1.8585,-1.5502) ( 4.4145,-0.7638) (-0.4805,-1.1976)
 ( 0.0000, 0.0000) ( 6.2673, 0.0000) (-0.4504,-0.0290) (-1.3467, 1.6579)
 ( 0.0000, 0.0000) ( 0.0000, 0.0000) (-3.5000, 0.0000) ( 2.5619,-3.3708)
                                                      :End of matrix H

Result

 ZHSEQR Example Program Results

 Matrix H
                    1                 2                 3                 4
 1  (-3.9700,-5.0400) (-1.1318,-2.5693) (-4.6027,-0.1426) (-1.4249, 1.7330)
 2  (-5.4797, 0.0000) ( 1.8585,-1.5502) ( 4.4145,-0.7638) (-0.4805,-1.1976)
 3  ( 0.0000, 0.0000) ( 6.2673, 0.0000) (-0.4504,-0.0290) (-1.3467, 1.6579)
 4  ( 0.0000, 0.0000) ( 0.0000, 0.0000) (-3.5000, 0.0000) ( 2.5619,-3.3708)

 Eigenvalues
    (-6.0004,-6.9998) (-5.0000, 2.0060) ( 7.9982,-0.9964) ( 3.0023,-3.9998)

Source

    Program zhseqr_example

!     ZHSEQR Example Program Text

!     Copyright 2017, Numerical Algorithms Group Ltd. http://www.nag.com

!     .. Use Statements ..
      Use blas_interfaces, Only: zgemm
      Use lapack_example_aux, Only: nagf_file_print_matrix_complex_gen_comp
      Use lapack_interfaces, Only: zhseqr, zlange
      Use lapack_precision, Only: dp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter :: nin = 5, nout = 6
!     .. Local Scalars ..
      Complex (Kind=dp) :: alpha, beta
      Real (Kind=dp) :: norm
      Integer :: i, ifail, info, ldc, ldd, ldh, ldz, lwork, n
!     .. Local Arrays ..
      Complex (Kind=dp), Allocatable :: c(:, :), d(:, :), h(:, :), w(:), &
        work(:), z(:, :)
      Real (Kind=dp) :: rwork(1)
      Character (1) :: clabs(1), rlabs(1)
!     .. Intrinsic Procedures ..
      Intrinsic :: cmplx, epsilon
!     .. Executable Statements ..
      Write (nout, *) 'ZHSEQR Example Program Results'
      Write (nout, *)
      Flush (nout)
!     Skip heading in data file
      Read (nin, *)
      Read (nin, *) n
      ldc = n
      ldd = n
      ldh = n
      ldz = n
      lwork = n
      Allocate (c(ldc,n), d(ldd,n), h(ldh,n), w(n), work(lwork), z(ldz,n))

!     Read H from data file

      Read (nin, *)(h(i,1:n), i=1, n)

!     Store H in D
      d(1:ldd, 1:n) = h(1:ldh, 1:n)

!     Print matrix H
!     ifail: behaviour on error exit
!            =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
      ifail = 0
      Call nagf_file_print_matrix_complex_gen_comp('General', ' ', n, n, h, &
        ldh, 'Bracketed', 'F7.4', 'Matrix H', 'Integer', rlabs, 'Integer', &
        clabs, 80, 0, ifail)

!     Calculate the eigenvalues and Schur factorization of H

      Call zhseqr('Schur form', 'Initialize Z', n, 1, n, h, ldh, w, z, ldz, &
        work, lwork, info)

      Write (nout, *)
      If (info>0) Then
        Write (nout, *) 'Failure to converge.'
      Else

!       Compute A - Z*T*Z^H from Schur factorization of A, and store in matrix
!       D
        alpha = cmplx(1, kind=dp)
        beta = cmplx(0, kind=dp)
        Call zgemm('N', 'N', n, n, n, alpha, z, ldz, h, ldh, beta, c, ldc)
        alpha = cmplx(-1, kind=dp)
        beta = cmplx(1, kind=dp)
        Call zgemm('N', 'C', n, n, n, alpha, c, ldc, z, ldz, beta, d, ldd)

!       Find norm of matrix D and print warning if it is too large
        norm = zlange('O', ldd, n, d, ldd, rwork)

        If (norm>epsilon(1.0E0_dp)**0.5_dp) Then
          Write (nout, *) 'Norm of A-(Z*T*Z^H) is much greater than 0.'
          Write (nout, *) 'Schur factorization has failed.'
        Else
!         Print eigenvalues
          Write (nout, *) 'Eigenvalues'
          Write (nout, 100)(w(i), i=1, n)
        End If

      End If

100   Format ((3X,4(' (',F7.4,',',F7.4,')',:)))
    End Program
Full documentation of ZHSEQR


ZPBCON example

Computational Routines: Estimate condition number of complex Hermitian positive-definite band matrix, matrix already factorized by ZPBTRF

Data

ZPBCON Example Program Data
  4  1                                                    :Values of N and KD
  'L'                                                     :Value of UPLO
 ( 9.39, 0.00)
 ( 1.08, 1.73) ( 1.69, 0.00)
               (-0.04,-0.29) ( 2.65, 0.00)
                             (-0.33,-2.24) ( 2.17, 0.00)  :End of matrix A

Result

 ZPBCON Example Program Results

 Estimate of condition number =  1.32E+02

Source

    Program zpbcon_example

!     ZPBCON Example Program Text

!     Copyright 2017, Numerical Algorithms Group Ltd. http://www.nag.com

!     .. Use Statements ..
      Use lapack_interfaces, Only: zlanhb, zpbcon, zpbtrf
      Use lapack_precision, Only: dp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=dp) :: anorm, rcond
      Integer :: i, info, j, kd, ldab, n
      Character (1) :: uplo
!     .. Local Arrays ..
      Complex (Kind=dp), Allocatable :: ab(:, :), work(:)
      Real (Kind=dp), Allocatable :: rwork(:)
!     .. Intrinsic Procedures ..
      Intrinsic :: epsilon, max, min
!     .. Executable Statements ..
      Write (nout, *) 'ZPBCON Example Program Results'
!     Skip heading in data file
      Read (nin, *)
      Read (nin, *) n, kd
      ldab = kd + 1
      Allocate (ab(ldab,n), work(2*n), rwork(n))

!     Read A from data file

      Read (nin, *) uplo
      If (uplo=='U') Then
        Do i = 1, n
          Read (nin, *)(ab(kd+1+i-j,j), j=i, min(n,i+kd))
        End Do
      Else If (uplo=='L') Then
        Do i = 1, n
          Read (nin, *)(ab(1+i-j,j), j=max(1,i-kd), i)
        End Do
      End If

!     Compute norm of A
      anorm = zlanhb('1-norm', uplo, n, kd, ab, ldab, rwork)

!     Factorize A
      Call zpbtrf(uplo, n, kd, ab, ldab, info)

      Write (nout, *)
      If (info==0) Then

!       Estimate condition number
        Call zpbcon(uplo, n, kd, ab, ldab, anorm, rcond, work, rwork, info)

        If (rcond>=epsilon(1.0E0_dp)) Then
          Write (nout, 100) 'Estimate of condition number =', 1.0_dp/rcond
        Else
          Write (nout, *) 'A is singular to working precision'
        End If
      Else
        Write (nout, *) 'A is not positive definite'
      End If

100   Format (1X, A, 1P, E10.2)
    End Program
Full documentation of ZPBCON


ZPBEQU example

Computational Routines: Computes row and column scalings intended to equilibrate a complex Hermitian positive-definite banded matrix and reduce its condition number

Data

ZPBEQU Example Program Data
  4  1                                                       :Values of N and KD
 (  9.39, 0.00) (  1.08,-1.73)
                (  1.69, 0.00) ( -0.04E+10, 0.29E+10)
                               (  2.64E+20, 0.00    ) ( -0.33E+10, 2.24E+10)
                                                      (  2.17,     0.00    )
                                                             :End of matrix A

Result

 ZPBEQU Example Program Results

 Matrix A
                          1                       2                       3
 1  (  9.39E+00,  0.00E+00) (  1.08E+00, -1.73E+00)
 2                          (  1.69E+00,  0.00E+00) ( -4.00E+08,  2.90E+09)
 3                                                  (  2.64E+20,  0.00E+00)
 4

                          4
 1
 2
 3  ( -3.30E+09,  2.24E+10)
 4  (  2.17E+00,  0.00E+00)

 SCOND = 8.0E-11, AMAX = 2.6E+20

 Diagonal scaling factors
     3.3E-01    7.7E-01    6.2E-11    6.8E-01

 Scaled matrix
                    1                 2                 3                 4
 1  ( 1.0000, 0.0000) ( 0.2711,-0.4343)
 2                    ( 1.0000, 0.0000) (-0.0189, 0.1373)
 3                                      ( 1.0000, 0.0000) (-0.1379, 0.9359)
 4                                                        ( 1.0000, 0.0000)

Source

    Program zpbequ_example

!     ZPBEQU Example Program Text

!     Copyright 2017, Numerical Algorithms Group Ltd. http://www.nag.com

!     .. Use Statements ..
      Use blas_interfaces, Only: zdscal
      Use lapack_example_aux, Only: nagf_blas_zddscl, &
        nagf_file_print_matrix_complex_band_comp
      Use lapack_interfaces, Only: zpbequ
      Use lapack_precision, Only: dp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Real (Kind=dp), Parameter :: one = 1.0_dp
      Real (Kind=dp), Parameter :: thresh = 0.1_dp
      Integer, Parameter :: nin = 5, nout = 6
      Character (1), Parameter :: uplo = 'U'
!     .. Local Scalars ..
      Real (Kind=dp) :: amax, big, scond, small
      Integer :: i, i0, i1, ifail, ilen, info, j, kd, ldab, n
!     .. Local Arrays ..
      Complex (Kind=dp), Allocatable :: ab(:, :)
      Real (Kind=dp), Allocatable :: s(:)
      Character (1) :: clabs(1), rlabs(1)
!     .. Intrinsic Procedures ..
      Intrinsic :: epsilon, max, min, radix, real, tiny
!     .. Executable Statements ..
      Write (nout, *) 'ZPBEQU Example Program Results'
      Write (nout, *)
      Flush (nout)
!     Skip heading in data file
      Read (nin, *)
      Read (nin, *) n, kd
      ldab = kd + 1
      Allocate (ab(ldab,n), s(n))

!     Read the upper or lower triangular part of the band matrix A
!     from data file

      If (uplo=='U') Then
        Do i = 1, n
          Read (nin, *)(ab(kd+1+i-j,j), j=i, min(n,i+kd))
        End Do
      Else If (uplo=='L') Then
        Do i = 1, n
          Read (nin, *)(ab(1+i-j,j), j=max(1,i-kd), i)
        End Do
      End If

!     Print the matrix A

!     ifail: behaviour on error exit
!             =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
      ifail = 0
      If (uplo=='U') Then
        Call nagf_file_print_matrix_complex_band_comp(n, n, 0, kd, ab, ldab, &
          'Bracketed', '1P,E10.2', 'Matrix A', 'Integer', rlabs, 'Integer', &
          clabs, 80, 0, ifail)
      Else If (uplo=='L') Then
        Call nagf_file_print_matrix_complex_band_comp(n, n, kd, 0, ab, ldab, &
          'Bracketed', '1P,E10.2', 'Matrix A', 'Integer', rlabs, 'Integer', &
          clabs, 80, 0, ifail)
      End If

      Write (nout, *)

!     Compute diagonal scaling factors

      Call zpbequ(uplo, n, kd, ab, ldab, s, scond, amax, info)

      If (info>0) Then
        Write (nout, 100) 'Diagonal element', info, ' of A is non positive'
      Else

!       Print SCOND, AMAX and the scale factors

        Write (nout, 110) 'SCOND =', scond, ', AMAX =', amax
        Write (nout, *)
        Write (nout, *) 'Diagonal scaling factors'
        Write (nout, 120) s(1:n)
        Write (nout, *)
        Flush (nout)

!       Compute values close to underflow and overflow

        small = tiny(1.0E0_dp)/(epsilon(1.0E0_dp)*real(radix(1.0E0_dp),kind=dp &
          ))
        big = one/small
        If ((scond<thresh) .Or. (amax<small) .Or. (amax>big)) Then

!         Scale A

          If (uplo=='U') Then
            Do j = 1, n
              i0 = max(1, j-kd)
              i1 = 1 + i0 - (j-kd)
              ilen = j - i0 + 1
              Call zdscal(ilen, s(j), ab(i1,j), 1)
              Call nagf_blas_zddscl(ilen, s(i0), 1, ab(i1,j), 1)
            End Do

          Else If (uplo=='L') Then
            Do j = 1, n
              i1 = 1
              ilen = min(n, j+kd) - j + 1
              Call zdscal(ilen, s(j), ab(i1,j), 1)
              Call nagf_blas_zddscl(ilen, s(j), 1, ab(i1,j), 1)
            End Do
          End If

!         Print the scaled matrix

          ifail = 0
          If (uplo=='U') Then
            Call nagf_file_print_matrix_complex_band_comp(n, n, 0, kd, ab, &
              ldab, 'Bracketed', 'F7.4', 'Scaled matrix', 'Integer', rlabs, &
              'Integer', clabs, 80, 0, ifail)
          Else If (uplo=='L') Then
            Call nagf_file_print_matrix_complex_band_comp(n, n, kd, 0, ab, &
              ldab, 'Bracketed', 'F7.4', 'Scaled matrix', 'Integer', rlabs, &
              'Integer', clabs, 80, 0, ifail)
          End If
        End If
      End If

100   Format (1X, A, I4, A)
110   Format (1X, 2(A,1P,E8.1))
120   Format ((1X,1P,7E11.1))
    End Program
Full documentation of ZPBEQU


ZPBRFS example

Computational Routines: Refined solution with error bounds of complex Hermitian positive-definite band system of linear equations, multiple right-hand sides

Data

ZPBRFS Example Program Data
  4  1  2                                              :Values of N, KD and NRHS
  'L'                                                     :Value of UPLO
 ( 9.39, 0.00)
 ( 1.08, 1.73) ( 1.69, 0.00)
               (-0.04,-0.29) ( 2.65, 0.00)
                             (-0.33,-2.24) ( 2.17, 0.00)  :End of matrix A
 (-12.42,68.42) (54.30,-56.56)
 ( -9.93, 0.88) (18.32,  4.76)
 (-27.30,-0.01) (-4.40,  9.97)
 (  5.31,23.63) ( 9.43,  1.41)                            :End of matrix B

Result

 ZPBRFS Example Program Results

 Solution(s)
                    1                 2
 1  (-1.0000, 8.0000) ( 5.0000,-6.0000)
 2  ( 2.0000,-3.0000) ( 2.0000, 3.0000)
 3  (-4.0000,-5.0000) (-8.0000, 4.0000)
 4  ( 7.0000, 6.0000) (-1.0000,-7.0000)

 Backward errors (machine-dependent)
         8.2E-17           8.3E-17
 Estimated forward error bounds (machine-dependent)
         3.5E-14           3.2E-14

Source

    Program zpbrfs_example

!     ZPBRFS Example Program Text

!     Copyright 2017, Numerical Algorithms Group Ltd. http://www.nag.com

!     .. Use Statements ..
      Use lapack_example_aux, Only: nagf_file_print_matrix_complex_gen_comp
      Use lapack_interfaces, Only: zpbrfs, zpbtrf, zpbtrs
      Use lapack_precision, Only: dp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Complex (Kind=dp), Parameter :: zero = (0.0E0_dp, 0.0E0_dp)
      Integer, Parameter :: nin = 5, nout = 6
!     .. Local Scalars ..
      Integer :: i, ifail, info, j, kd, ldab, ldafb, ldb, ldx, n, nrhs
      Character (1) :: uplo
!     .. Local Arrays ..
      Complex (Kind=dp), Allocatable :: ab(:, :), afb(:, :), b(:, :), work(:), &
        x(:, :)
      Real (Kind=dp), Allocatable :: berr(:), ferr(:), rwork(:)
      Character (1) :: clabs(1), rlabs(1)
!     .. Intrinsic Procedures ..
      Intrinsic :: max, min
!     .. Executable Statements ..
      Write (nout, *) 'ZPBRFS Example Program Results'
!     Skip heading in data file
      Read (nin, *)
      Read (nin, *) n, kd, nrhs
      ldab = kd + 1
      ldafb = kd + 1
      ldb = n
      ldx = n
      Allocate (ab(ldab,n), afb(ldafb,n), b(ldb,nrhs), work(2*n), x(ldx,n), &
        berr(nrhs), ferr(nrhs), rwork(n))

!     Set A to zero to avoid referencing uninitialized elements

      ab(1:kd+1, 1:n) = zero

!     Read A and B from data file, and copy A to AFB and B to X

      Read (nin, *) uplo
      If (uplo=='U') Then
        Do i = 1, n
          Read (nin, *)(ab(kd+1+i-j,j), j=i, min(n,i+kd))
        End Do
      Else If (uplo=='L') Then
        Do i = 1, n
          Read (nin, *)(ab(1+i-j,j), j=max(1,i-kd), i)
        End Do
      End If
      Read (nin, *)(b(i,1:nrhs), i=1, n)

      afb(1:kd+1, 1:n) = ab(1:kd+1, 1:n)
      x(1:n, 1:nrhs) = b(1:n, 1:nrhs)

!     Factorize A in the array AFB

      Call zpbtrf(uplo, n, kd, afb, ldafb, info)

      Write (nout, *)
      Flush (nout)
      If (info==0) Then

!       Compute solution in the array X

        Call zpbtrs(uplo, n, kd, nrhs, afb, ldafb, x, ldx, info)

!       Improve solution, and compute backward errors and
!       estimated bounds on the forward errors

        Call zpbrfs(uplo, n, kd, nrhs, ab, ldab, afb, ldafb, b, ldb, x, ldx, &
          ferr, berr, work, rwork, info)

!       Print solution

!       ifail: behaviour on error exit
!              =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
        ifail = 0
        Call nagf_file_print_matrix_complex_gen_comp('General', ' ', n, nrhs, &
          x, ldx, 'Bracketed', 'F7.4', 'Solution(s)', 'Integer', rlabs, &
          'Integer', clabs, 80, 0, ifail)

        Write (nout, *)
        Write (nout, *) 'Backward errors (machine-dependent)'
        Write (nout, 100) berr(1:nrhs)
        Write (nout, *) 'Estimated forward error bounds (machine-dependent)'
        Write (nout, 100) ferr(1:nrhs)
      Else
        Write (nout, *) 'A is not positive definite'
      End If

100   Format ((5X,1P,4(E11.1,7X)))
    End Program
Full documentation of ZPBRFS


ZPBTRF example

Computational Routines: Cholesky factorization of complex Hermitian positive-definite band matrix

Data

ZPBTRF Example Program Data
  4  1                                                    :Values of N and KD
  'L'                                                     :Value of UPLO
 ( 9.39, 0.00)
 ( 1.08, 1.73) ( 1.69, 0.00)
               (-0.04,-0.29) ( 2.65, 0.00)
                             (-0.33,-2.24) ( 2.17, 0.00)  :End of matrix A

Result

 ZPBTRF Example Program Results

 Factor
                    1                 2                 3                 4
 1  ( 3.0643, 0.0000)
 2  ( 0.3524, 0.5646) ( 1.1167, 0.0000)
 3                    (-0.0358,-0.2597) ( 1.6066, 0.0000)
 4                                      (-0.2054,-1.3942) ( 0.4289, 0.0000)

Source

    Program zpbtrf_example

!     ZPBTRF Example Program Text

!     Copyright 2017, Numerical Algorithms Group Ltd. http://www.nag.com

!     .. Use Statements ..
      Use lapack_example_aux, Only: nagf_file_print_matrix_complex_band_comp
      Use lapack_interfaces, Only: zpbtrf
      Use lapack_precision, Only: dp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter :: nin = 5, nout = 6
!     .. Local Scalars ..
      Integer :: i, ifail, info, j, kd, ldab, n
      Character (1) :: uplo
!     .. Local Arrays ..
      Complex (Kind=dp), Allocatable :: ab(:, :)
      Character (1) :: clabs(1), rlabs(1)
!     .. Intrinsic Procedures ..
      Intrinsic :: max, min
!     .. Executable Statements ..
      Write (nout, *) 'ZPBTRF Example Program Results'
!     Skip heading in data file
      Read (nin, *)
      Read (nin, *) n, kd
      ldab = kd + 1
      Allocate (ab(ldab,n))

!     Read A from data file

      Read (nin, *) uplo
      If (uplo=='U') Then
        Do i = 1, n
          Read (nin, *)(ab(kd+1+i-j,j), j=i, min(n,i+kd))
        End Do
      Else If (uplo=='L') Then
        Do i = 1, n
          Read (nin, *)(ab(1+i-j,j), j=max(1,i-kd), i)
        End Do
      End If

!     Factorize A
      Call zpbtrf(uplo, n, kd, ab, ldab, info)

      Write (nout, *)
      Flush (nout)
      If (info==0) Then

!       Print factor

!       ifail: behaviour on error exit
!              =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
        ifail = 0
        If (uplo=='U') Then

          Call nagf_file_print_matrix_complex_band_comp(n, n, 0, kd, ab, ldab, &
            'Bracketed', 'F7.4', 'Factor', 'Integer', rlabs, 'Integer', clabs, &
            80, 0, ifail)

        Else If (uplo=='L') Then

          Call nagf_file_print_matrix_complex_band_comp(n, n, kd, 0, ab, ldab, &
            'Bracketed', 'F7.4', 'Factor', 'Integer', rlabs, 'Integer', clabs, &
            80, 0, ifail)

        End If

      Else
        Write (nout, *) 'A is not positive definite'
      End If

    End Program
Full documentation of ZPBTRF


ZPBTRS example

Computational Routines: Solution of complex Hermitian positive-definite band system of linear equations, multiple right-hand sides, matrix already factorized by ZPBTRF

Data

ZPBTRS Example Program Data
  4  1  2                                             :Values of N, KD and NRHS
  'L'                                                     :Value of UPLO
 ( 9.39, 0.00)
 ( 1.08, 1.73) ( 1.69, 0.00)
               (-0.04,-0.29) ( 2.65, 0.00)
                             (-0.33,-2.24) ( 2.17, 0.00)  :End of matrix A
 (-12.42,68.42) (54.30,-56.56)
 ( -9.93, 0.88) (18.32,  4.76)
 (-27.30,-0.01) (-4.40,  9.97)
 (  5.31,23.63) ( 9.43,  1.41)                            :End of matrix B

Result

 ZPBTRS Example Program Results

 Solution(s)
                    1                 2
 1  (-1.0000, 8.0000) ( 5.0000,-6.0000)
 2  ( 2.0000,-3.0000) ( 2.0000, 3.0000)
 3  (-4.0000,-5.0000) (-8.0000, 4.0000)
 4  ( 7.0000, 6.0000) (-1.0000,-7.0000)

Source

    Program zpbtrs_example

!     ZPBTRS Example Program Text

!     Copyright 2017, Numerical Algorithms Group Ltd. http://www.nag.com

!     .. Use Statements ..
      Use lapack_example_aux, Only: nagf_file_print_matrix_complex_gen_comp
      Use lapack_interfaces, Only: zpbtrf, zpbtrs
      Use lapack_precision, Only: dp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter :: nin = 5, nout = 6
!     .. Local Scalars ..
      Integer :: i, ifail, info, j, kd, ldab, ldb, n, nrhs
      Character (1) :: uplo
!     .. Local Arrays ..
      Complex (Kind=dp), Allocatable :: ab(:, :), b(:, :)
      Character (1) :: clabs(1), rlabs(1)
!     .. Intrinsic Procedures ..
      Intrinsic :: max, min
!     .. Executable Statements ..
      Write (nout, *) 'ZPBTRS Example Program Results'
!     Skip heading in data file
      Read (nin, *)
      Read (nin, *) n, kd, nrhs
      ldab = kd + 1
      ldb = n
      Allocate (ab(ldab,n), b(ldb,nrhs))

!     Read A and B from data file

      Read (nin, *) uplo
      If (uplo=='U') Then
        Do i = 1, n
          Read (nin, *)(ab(kd+1+i-j,j), j=i, min(n,i+kd))
        End Do
      Else If (uplo=='L') Then
        Do i = 1, n
          Read (nin, *)(ab(1+i-j,j), j=max(1,i-kd), i)
        End Do
      End If
      Read (nin, *)(b(i,1:nrhs), i=1, n)

!     Factorize A
      Call zpbtrf(uplo, n, kd, ab, ldab, info)

      Write (nout, *)
      Flush (nout)
      If (info==0) Then

!       Compute solution
        Call zpbtrs(uplo, n, kd, nrhs, ab, ldab, b, ldb, info)

!       Print solution

!       ifail: behaviour on error exit
!              =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
        ifail = 0
        Call nagf_file_print_matrix_complex_gen_comp('General', ' ', n, nrhs, &
          b, ldb, 'Bracketed', 'F7.4', 'Solution(s)', 'Integer', rlabs, &
          'Integer', clabs, 80, 0, ifail)

      Else
        Write (nout, *) 'A is not positive definite'
      End If

    End Program
Full documentation of ZPBTRS


ZPFTRF example

Computational Routines: Cholesky factorization of complex Hermitian positive definite matrix, Rectangular Full Packed format

Data

ZPFTRF Example Program Data
   4     'L'     'N'           : n, uplo, transr
 ( 4.09, 0.00)   ( 2.33, 0.14)
 ( 3.23, 0.00)   ( 4.29, 0.00)
 ( 1.51, 1.92)   ( 3.58, 0.00)
 ( 1.90,-0.84)   (-0.23,-1.11)
 ( 0.42,-2.50)   (-1.18,-1.37) : AR

Result

 ZPFTRF Example Program Results

 Factor
                    1                 2                 3                 4
 1  ( 1.7972, 0.0000)
 2  ( 0.8402, 1.0683) ( 1.3164, 0.0000)
 3  ( 1.0572,-0.4674) (-0.4702, 0.3131) ( 1.5604,-0.0000)
 4  ( 0.2337,-1.3910) ( 0.0834, 0.0368) ( 0.9360, 0.8105) ( 0.8713,-0.0000)

Source

    Program zpftrf_example

!     ZPFTRF Example Program Text

!     Copyright 2017, Numerical Algorithms Group Ltd. http://www.nag.com

!     .. Use Statements ..
      Use lapack_example_aux, Only: nagf_file_print_matrix_complex_gen_comp
      Use lapack_interfaces, Only: zpftrf, ztfttr
      Use lapack_precision, Only: dp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter :: nin = 5, nout = 6
!     .. Local Scalars ..
      Integer :: i, ifail, info, k, lar1, lda, lenar, n, q
      Character (1) :: transr, uplo
!     .. Local Arrays ..
      Complex (Kind=dp), Allocatable :: a(:, :), ar(:)
      Character (1) :: clabs(1), rlabs(1)
!     .. Executable Statements ..
      Write (nout, *) 'ZPFTRF Example Program Results'
!     Skip heading in data file
      Read (nin, *)
      Read (nin, *) n, uplo, transr

      lenar = n*(n+1)/2
      lda = n
      Allocate (ar(lenar), a(lda,n))

!     Setup notional dimensions of RFP matrix AR
      k = n/2
      q = n - k
      If (transr=='N' .Or. transr=='n') Then
        lar1 = 2*k + 1
      Else
        lar1 = q
      End If

!     Read an RFP matrix into array AR
      Do i = 1, lar1
        Read (nin, *) ar(i:lenar:lar1)
      End Do

!     Factorize A
      Call zpftrf(transr, uplo, n, ar, info)

      Write (nout, *)
      Flush (nout)
      If (info==0) Then

!       Convert and print factor
        Call ztfttr(transr, uplo, n, ar, a, lda, info)
        ifail = 0
        Call nagf_file_print_matrix_complex_gen_comp(uplo, 'Nonunit', n, n, a, &
          lda, 'Bracketed', 'F7.4', 'Factor', 'Integer', rlabs, 'Integer', &
          clabs, 80, 0, ifail)

      Else
        Write (nout, *) 'A is not positive definite'
      End If

    End Program
Full documentation of ZPFTRF


ZPFTRI example

Computational Routines: Inverse of complex Hermitian positive definite matrix, matrix already factorized by ZPFTRF, Rectangular Full Packed format

Data

ZPFTRI Example Program Data
   4     'L'    'N'           : n, uplo, transr
 ( 4.09, 0.00)  ( 2.33,-0.14)
 ( 3.23, 0.00)  ( 4.29, 0.00)
 ( 1.51, 1.92)  ( 3.58, 0.00)
 ( 1.90,-0.84)  (-0.23,-1.11)
 ( 0.42,-2.50)  (-1.18,-1.37) : AR

Result

 ZPFTRI Example Program Results

 Inverse
                    1                 2                 3                 4
 1  ( 5.4691, 0.0000)
 2  (-1.2624,-1.5491) ( 1.1024, 0.0000)
 3  (-2.9746,-0.9616) ( 0.8989,-0.5672) ( 2.1589,-0.0000)
 4  ( 1.1962, 2.9772) (-0.9826,-0.2566) (-1.3756,-1.4550) ( 2.2934, 0.0000)

Source

    Program zpftri_example

!     ZPFTRI Example Program Text

!     Copyright 2017, Numerical Algorithms Group Ltd. http://www.nag.com

!     .. Use Statements ..
      Use lapack_example_aux, Only: nagf_file_print_matrix_complex_gen_comp
      Use lapack_interfaces, Only: zpftrf, zpftri, ztfttr
      Use lapack_precision, Only: dp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter :: nin = 5, nout = 6
!     .. Local Scalars ..
      Integer :: i, ifail, info, k, lar1, lda, lenar, n, q
      Character (1) :: transr, uplo
!     .. Local Arrays ..
      Complex (Kind=dp), Allocatable :: a(:, :), ar(:)
      Character (1) :: clabs(1), rlabs(1)
!     .. Executable Statements ..
      Write (nout, *) 'ZPFTRI Example Program Results'
!     Skip heading in data file
      Read (nin, *)
      Read (nin, *) n, uplo, transr

      lenar = n*(n+1)/2
      lda = n
      Allocate (ar(lenar), a(lda,n))

!     Setup notional dimensions of RFP matrix AR
      k = n/2
      q = n - k
      If (transr=='N' .Or. transr=='n') Then
        lar1 = 2*k + 1
      Else
        lar1 = q
      End If

!     Read an RFP matrix into array AR
      Do i = 1, lar1
        Read (nin, *) ar(i:lenar:lar1)
      End Do

!     Factorize A
      Call zpftrf(transr, uplo, n, ar, info)

      Write (nout, *)
      Flush (nout)
      If (info==0) Then

!       Compute inverse of A
        Call zpftri(transr, uplo, n, ar, info)

!       Convert and print inverse
        Call ztfttr(transr, uplo, n, ar, a, lda, info)
        ifail = 0
        Call nagf_file_print_matrix_complex_gen_comp(uplo, 'Nonunit', n, n, a, &
          lda, 'Bracketed', 'F7.4', 'Inverse', 'Integer', rlabs, 'Integer', &
          clabs, 80, 0, ifail)

      Else
        Write (nout, *) 'A is not positive definite'
      End If

    End Program
Full documentation of ZPFTRI


ZPFTRS example

Computational Routines: Solution of complex Hermitian positive definite system of linear equations, multiple right-hand sides, coefficient matrix already factorized by ZPFTRF, Rectangular Full Packed format

Data

ZPFTRS Example Program Data
   4      2       'L'    'N'    : n, nrhs, uplo, transr
 ( 4.09,  0.00) ( 2.33, -0.14)
 ( 3.23,  0.00) ( 4.29,  0.00)
 ( 1.51,  1.92) ( 3.58,  0.00)
 ( 1.90, -0.84) (-0.23, -1.11)
 ( 0.42, -2.50) (-1.18, -1.37)  : AR

 ( 3.93, -6.14) ( 1.48,  6.58)
 ( 6.17,  9.42) ( 4.65, -4.75)
 (-7.17,-21.83) (-4.91,  2.29)
 ( 1.99,-14.38) ( 7.64,-10.79)  : B

Result

 ZPFTRS Example Program Results

 Solution(s)
                    1                 2
 1  ( 1.0000,-1.0000) (-1.0000, 2.0000)
 2  (-0.0000, 3.0000) ( 3.0000,-4.0000)
 3  (-4.0000,-5.0000) (-2.0000, 3.0000)
 4  ( 2.0000, 1.0000) ( 4.0000,-5.0000)

Source

    Program zpftrs_example

!     ZPFTRS Example Program Text

!     Copyright 2017, Numerical Algorithms Group Ltd. http://www.nag.com

!     .. Use Statements ..
      Use lapack_example_aux, Only: nagf_file_print_matrix_complex_gen_comp
      Use lapack_interfaces, Only: zpftrf, zpftrs
      Use lapack_precision, Only: dp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter :: nin = 5, nout = 6
!     .. Local Scalars ..
      Integer :: i, ifail, info, k, lar1, ldb, lenar, n, nrhs, q
      Character (1) :: transr, uplo
!     .. Local Arrays ..
      Complex (Kind=dp), Allocatable :: ar(:), b(:, :)
      Character (1) :: clabs(1), rlabs(1)
!     .. Executable Statements ..
      Write (nout, *) 'ZPFTRS Example Program Results'
!     Skip heading in data file
      Read (nin, *)
      Read (nin, *) n, nrhs, uplo, transr

      lenar = n*(n+1)/2
      ldb = n
      Allocate (ar(lenar), b(ldb,nrhs))

!     Setup notional dimensions of RFP matrix AR
      k = n/2
      q = n - k
      If (transr=='N' .Or. transr=='n') Then
        lar1 = 2*k + 1
      Else
        lar1 = q
      End If

!     Read an RFP matrix into array AR
      Do i = 1, lar1
        Read (nin, *) ar(i:lenar:lar1)
      End Do

!     Read RHS matrix B
      Do i = 1, n
        Read (nin, *) b(i, 1:nrhs)
      End Do

!     Factorize A
      Call zpftrf(transr, uplo, n, ar, info)

      Write (nout, *)
      Flush (nout)
      If (info==0) Then

!       Compute solution
        Call zpftrs(transr, uplo, n, nrhs, ar, b, ldb, info)

!       Print solution
        ifail = 0
        Call nagf_file_print_matrix_complex_gen_comp('General', ' ', n, nrhs, &
          b, ldb, 'Bracketed', 'F7.4', 'Solution(s)', 'Integer', rlabs, &
          'Integer', clabs, 80, 0, ifail)

      Else
        Write (nout, *) 'A is not positive definite'
      End If

    End Program
Full documentation of ZPFTRS


ZPOCON example

Computational Routines: Estimate condition number of complex Hermitian positive-definite matrix, matrix already factorized by ZPOTRF

Data

ZPOCON Example Program Data
  4                                                      :Value of N
  'L'                                                    :Value of UPLO
 (3.23, 0.00)
 (1.51, 1.92) ( 3.58, 0.00)
 (1.90,-0.84) (-0.23,-1.11) ( 4.09, 0.00)
 (0.42,-2.50) (-1.18,-1.37) ( 2.33, 0.14) ( 4.29, 0.00)  :End of matrix A

Result

 ZPOCON Example Program Results

 Estimate of condition number =  1.51E+02

Source

    Program zpocon_example

!     ZPOCON Example Program Text

!     Copyright 2017, Numerical Algorithms Group Ltd. http://www.nag.com

!     .. Use Statements ..
      Use lapack_interfaces, Only: zlanhe, zpocon, zpotrf
      Use lapack_precision, Only: dp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=dp) :: anorm, rcond
      Integer :: i, info, lda, n
      Character (1) :: uplo
!     .. Local Arrays ..
      Complex (Kind=dp), Allocatable :: a(:, :), work(:)
      Real (Kind=dp), Allocatable :: rwork(:)
!     .. Intrinsic Procedures ..
      Intrinsic :: epsilon
!     .. Executable Statements ..
      Write (nout, *) 'ZPOCON Example Program Results'
!     Skip heading in data file
      Read (nin, *)
      Read (nin, *) n
      lda = n
      Allocate (a(lda,n), work(2*n), rwork(n))

!     Read A from data file

      Read (nin, *) uplo
      If (uplo=='U') Then
        Read (nin, *)(a(i,i:n), i=1, n)
      Else If (uplo=='L') Then
        Read (nin, *)(a(i,1:i), i=1, n)
      End If

!     Compute norm of A
      anorm = zlanhe('1-norm', uplo, n, a, lda, rwork)

!     Factorize A
      Call zpotrf(uplo, n, a, lda, info)

      Write (nout, *)
      If (info==0) Then

!       Estimate condition number
        Call zpocon(uplo, n, a, lda, anorm, rcond, work, rwork, info)

        If (rcond>=epsilon(1.0E0_dp)) Then
          Write (nout, 100) 'Estimate of condition number =', 1.0E0_dp/rcond
        Else
          Write (nout, *) 'A is singular to working precision'
        End If
      Else
        Write (nout, *) 'A is not positive definite'
      End If

100   Format (1X, A, 1P, E10.2)
    End Program
Full documentation of ZPOCON


ZPOEQU example

Computational Routines: Computes row and column scalings intended to equilibrate a complex Hermitian positive-definite matrix and reduce its condition number

Data

ZPOEQU Example Program Data
   4                                                            :Value of N
 ( 3.23, 0.00) ( 1.51,-1.92) ( 1.90D+05, 0.84D+05) ( 0.42D+00, 2.50D+00)
               ( 3.58, 0.00) (-0.23D+05, 1.11D+05) (-1.18D+00, 1.37D+00)
                             ( 4.09D+10, 0.00D+00) ( 2.33D+05,-0.14D+05)
                                                   ( 4.29D+00, 0.00D+00)
                                                                :End of matrix A

Result

 ZPOEQU Example Program Results

 Matrix A
                          1                       2                       3
 1  (  3.23E+00,  0.00E+00) (  1.51E+00, -1.92E+00) (  1.90E+05,  8.40E+04)
 2                          (  3.58E+00,  0.00E+00) ( -2.30E+04,  1.11E+05)
 3                                                  (  4.09E+10,  0.00E+00)
 4

                          4
 1  (  4.20E-01,  2.50E+00)
 2  ( -1.18E+00,  1.37E+00)
 3  (  2.33E+05, -1.40E+04)
 4  (  4.29E+00,  0.00E+00)

 SCOND = 8.9E-06, AMAX = 4.1E+10

 Diagonal scaling factors
     5.6E-01    5.3E-01    4.9E-06    4.8E-01

 Scaled matrix
                      1                   2                   3
 1  (  1.0000,  0.0000) (  0.4441, -0.5646) (  0.5227,  0.2311)
 2                      (  1.0000,  0.0000) ( -0.0601,  0.2901)
 3                                          (  1.0000,  0.0000)
 4

                      4
 1  (  0.1128,  0.6716)
 2  ( -0.3011,  0.3496)
 3  (  0.5562, -0.0334)
 4  (  1.0000,  0.0000)

Source

    Program zpoequ_example

!     ZPOEQU Example Program Text

!     Copyright 2017, Numerical Algorithms Group Ltd. http://www.nag.com

!     .. Use Statements ..
      Use blas_interfaces, Only: zdscal
      Use lapack_example_aux, Only: nagf_blas_zddscl, &
        nagf_file_print_matrix_complex_gen_comp
      Use lapack_interfaces, Only: zpoequ
      Use lapack_precision, Only: dp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Real (Kind=dp), Parameter :: one = 1.0_dp
      Real (Kind=dp), Parameter :: thresh = 0.1_dp
      Integer, Parameter :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=dp) :: amax, big, scond, small
      Integer :: i, ifail, info, j, lda, n
!     .. Local Arrays ..
      Complex (Kind=dp), Allocatable :: a(:, :)
      Real (Kind=dp), Allocatable :: s(:)
      Character (1) :: clabs(1), rlabs(1)
!     .. Intrinsic Procedures ..
      Intrinsic :: epsilon, radix, real, tiny
!     .. Executable Statements ..
      Write (nout, *) 'ZPOEQU Example Program Results'
      Write (nout, *)
      Flush (nout)
!     Skip heading in data file
      Read (nin, *)
      Read (nin, *) n
      lda = n
      Allocate (a(lda,n), s(n))

!     Read the upper triangular part of the matrix A from data file

      Read (nin, *)(a(i,i:n), i=1, n)

!     Print the matrix A

!     ifail: behaviour on error exit
!             =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
      ifail = 0
      Call nagf_file_print_matrix_complex_gen_comp('Upper', 'Non-unit', n, n, &
        a, lda, 'Bracketed', '1P,E10.2', 'Matrix A', 'Integer', rlabs, &
        'Integer', clabs, 80, 0, ifail)

      Write (nout, *)

!     Compute diagonal scaling factors

      Call zpoequ(n, a, lda, s, scond, amax, info)

      If (info>0) Then
        Write (nout, 100) 'Diagonal element', info, ' of A is non positive'
      Else

!       Print SCOND, AMAX and the scale factors

        Write (nout, 110) 'SCOND =', scond, ', AMAX =', amax
        Write (nout, *)
        Write (nout, *) 'Diagonal scaling factors'
        Write (nout, 120) s(1:n)
        Write (nout, *)
        Flush (nout)

!       Compute values close to underflow and overflow

        small = tiny(1.0E0_dp)/(epsilon(1.0E0_dp)*real(radix(1.0E0_dp),kind=dp &
          ))
        big = one/small
        If ((scond<thresh) .Or. (amax<small) .Or. (amax>big)) Then

!         Scale A
          Do j = 1, n
            Call zdscal(j, s(j), a(1,j), 1)
            Call nagf_blas_zddscl(j, s, 1, a(1,j), 1)
          End Do

!         Print the scaled matrix

          ifail = 0
          Call nagf_file_print_matrix_complex_gen_comp('Upper', 'Non-unit', n, &
            n, a, lda, 'Bracketed', 'F8.4', 'Scaled matrix', 'Integer', rlabs, &
            'Integer', clabs, 80, 0, ifail)

        End If
      End If

100   Format (1X, A, I4, A)
110   Format (1X, 2(A,1P,E8.1))
120   Format ((1X,1P,7E11.1))
    End Program
Full documentation of ZPOEQU


ZPORFS example

Computational Routines: Refined solution with error bounds of complex Hermitian positive-definite system of linear equations, multiple right-hand sides

Data

ZPORFS Example Program Data
  4  2                                                   :Values of N and NRHS
  'L'                                                    :Value of UPLO
 (3.23, 0.00)
 (1.51, 1.92) ( 3.58, 0.00)
 (1.90,-0.84) (-0.23,-1.11) ( 4.09, 0.00)
 (0.42,-2.50) (-1.18,-1.37) ( 2.33, 0.14) ( 4.29, 0.00)  :End of matrix A
 ( 3.93, -6.14) ( 1.48,  6.58)
 ( 6.17,  9.42) ( 4.65, -4.75)
 (-7.17,-21.83) (-4.91,  2.29)
 ( 1.99,-14.38) ( 7.64,-10.79)                           :End of matrix B

Result

 ZPORFS Example Program Results

 Solution(s)
                    1                 2
 1  ( 1.0000,-1.0000) (-1.0000, 2.0000)
 2  (-0.0000, 3.0000) ( 3.0000,-4.0000)
 3  (-4.0000,-5.0000) (-2.0000, 3.0000)
 4  ( 2.0000, 1.0000) ( 4.0000,-5.0000)

 Backward errors (machine-dependent)
         1.1E-16           1.1E-16
 Estimated forward error bounds (machine-dependent)
         5.8E-14           7.3E-14

Source

    Program zporfs_example

!     ZPORFS Example Program Text

!     Copyright 2017, Numerical Algorithms Group Ltd. http://www.nag.com

!     .. Use Statements ..
      Use lapack_example_aux, Only: nagf_file_print_matrix_complex_gen_comp
      Use lapack_interfaces, Only: zlacpy, zporfs, zpotrf, zpotrs
      Use lapack_precision, Only: dp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter :: nin = 5, nout = 6
!     .. Local Scalars ..
      Integer :: i, ifail, info, lda, ldaf, ldb, ldx, n, nrhs
      Character (1) :: uplo
!     .. Local Arrays ..
      Complex (Kind=dp), Allocatable :: a(:, :), af(:, :), b(:, :), work(:), &
        x(:, :)
      Real (Kind=dp), Allocatable :: berr(:), ferr(:), rwork(:)
      Character (1) :: clabs(1), rlabs(1)
!     .. Executable Statements ..
      Write (nout, *) 'ZPORFS Example Program Results'
!     Skip heading in data file
      Read (nin, *)
      Read (nin, *) n, nrhs
      lda = n
      ldaf = n
      ldb = n
      ldx = n
      Allocate (a(lda,n), af(ldaf,n), b(ldb,nrhs), work(2*n), x(ldx,n), &
        berr(nrhs), ferr(nrhs), rwork(n))

!     Read A and B from data file, and copy A to AF and B to X

      Read (nin, *) uplo
      If (uplo=='U') Then
        Read (nin, *)(a(i,i:n), i=1, n)
      Else If (uplo=='L') Then
        Read (nin, *)(a(i,1:i), i=1, n)
      End If
      Read (nin, *)(b(i,1:nrhs), i=1, n)

      Call zlacpy(uplo, n, n, a, lda, af, ldaf)
      x(1:n, 1:nrhs) = b(1:n, 1:nrhs)

!     Factorize A in the array AF
      Call zpotrf(uplo, n, af, ldaf, info)

      Write (nout, *)
      Flush (nout)
      If (info==0) Then

!       Compute solution in the array X
        Call zpotrs(uplo, n, nrhs, af, ldaf, x, ldx, info)

!       Improve solution, and compute backward errors and
!       estimated bounds on the forward errors

        Call zporfs(uplo, n, nrhs, a, lda, af, ldaf, b, ldb, x, ldx, ferr, &
          berr, work, rwork, info)

!       Print solution

!       ifail: behaviour on error exit
!              =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
        ifail = 0
        Call nagf_file_print_matrix_complex_gen_comp('General', ' ', n, nrhs, &
          x, ldx, 'Bracketed', 'F7.4', 'Solution(s)', 'Integer', rlabs, &
          'Integer', clabs, 80, 0, ifail)

        Write (nout, *)
        Write (nout, *) 'Backward errors (machine-dependent)'
        Write (nout, 100) berr(1:nrhs)
        Write (nout, *) 'Estimated forward error bounds (machine-dependent)'
        Write (nout, 100) ferr(1:nrhs)
      Else
        Write (nout, *) 'A is not positive definite'
      End If

100   Format ((5X,1P,4(E11.1,7X)))
    End Program
Full documentation of ZPORFS


ZPOTRF example

Computational Routines: Cholesky factorization of complex Hermitian positive-definite matrix

Data

ZPOTRF Example Program Data
  4                                                      :Value of N
  'L'                                                    :Value of UPLO
 (3.23, 0.00)
 (1.51, 1.92) ( 3.58, 0.00)
 (1.90,-0.84) (-0.23,-1.11) ( 4.09, 0.00)
 (0.42,-2.50) (-1.18,-1.37) ( 2.33, 0.14) ( 4.29, 0.00)  :End of matrix A

Result

 ZPOTRF Example Program Results

 Factor
                    1                 2                 3                 4
 1  ( 1.7972, 0.0000)
 2  ( 0.8402, 1.0683) ( 1.3164, 0.0000)
 3  ( 1.0572,-0.4674) (-0.4702, 0.3131) ( 1.5604, 0.0000)
 4  ( 0.2337,-1.3910) ( 0.0834, 0.0368) ( 0.9360, 0.9900) ( 0.6603, 0.0000)

Source

    Program zpotrf_example

!     ZPOTRF Example Program Text

!     Copyright 2017, Numerical Algorithms Group Ltd. http://www.nag.com

!     .. Use Statements ..
      Use lapack_example_aux, Only: nagf_file_print_matrix_complex_gen_comp
      Use lapack_interfaces, Only: zpotrf
      Use lapack_precision, Only: dp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter :: nin = 5, nout = 6
!     .. Local Scalars ..
      Integer :: i, ifail, info, lda, n
      Character (1) :: uplo
!     .. Local Arrays ..
      Complex (Kind=dp), Allocatable :: a(:, :)
      Character (1) :: clabs(1), rlabs(1)
!     .. Executable Statements ..
      Write (nout, *) 'ZPOTRF Example Program Results'
!     Skip heading in data file
      Read (nin, *)
      Read (nin, *) n
      lda = n
      Allocate (a(lda,n))

!     Read A from data file

      Read (nin, *) uplo
      If (uplo=='U') Then
        Read (nin, *)(a(i,i:n), i=1, n)
      Else If (uplo=='L') Then
        Read (nin, *)(a(i,1:i), i=1, n)
      End If

!     Factorize A
      Call zpotrf(uplo, n, a, lda, info)

      Write (nout, *)
      Flush (nout)
      If (info==0) Then

!       Print factor

!       ifail: behaviour on error exit
!              =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
        ifail = 0
        Call nagf_file_print_matrix_complex_gen_comp(uplo, 'Nonunit', n, n, a, &
          lda, 'Bracketed', 'F7.4', 'Factor', 'Integer', rlabs, 'Integer', &
          clabs, 80, 0, ifail)

      Else
        Write (nout, *) 'A is not positive definite'
      End If

    End Program
Full documentation of ZPOTRF


ZPOTRI example

Computational Routines: Inverse of complex Hermitian positive-definite matrix, matrix already factorized by ZPOTRF

Data

ZPOTRI Example Program Data
  4                                                      :Value of N
  'L'                                                    :Value of UPLO
 (3.23, 0.00)
 (1.51, 1.92) ( 3.58, 0.00)
 (1.90,-0.84) (-0.23,-1.11) ( 4.09, 0.00)
 (0.42,-2.50) (-1.18,-1.37) ( 2.33, 0.14) ( 4.29, 0.00)  :End of matrix A

Result

 ZPOTRI Example Program Results

 Inverse
                    1                 2                 3                 4
 1  ( 5.4691, 0.0000)
 2  (-1.2624,-1.5491) ( 1.1024, 0.0000)
 3  (-2.9746,-0.9616) ( 0.8989,-0.5672) ( 2.1589, 0.0000)
 4  ( 1.1962, 2.9772) (-0.9826,-0.2566) (-1.3756,-1.4550) ( 2.2934,-0.0000)

Source

    Program zpotri_example

!     ZPOTRI Example Program Text

!     Copyright 2017, Numerical Algorithms Group Ltd. http://www.nag.com

!     .. Use Statements ..
      Use lapack_example_aux, Only: nagf_file_print_matrix_complex_gen_comp
      Use lapack_interfaces, Only: zpotrf, zpotri
      Use lapack_precision, Only: dp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter :: nin = 5, nout = 6
!     .. Local Scalars ..
      Integer :: i, ifail, info, lda, n
      Character (1) :: uplo
!     .. Local Arrays ..
      Complex (Kind=dp), Allocatable :: a(:, :)
      Character (1) :: clabs(1), rlabs(1)
!     .. Executable Statements ..
      Write (nout, *) 'ZPOTRI Example Program Results'
!     Skip heading in data file
      Read (nin, *)
      Read (nin, *) n
      lda = n
      Allocate (a(lda,n))

!     Read A from data file

      Read (nin, *) uplo
      If (uplo=='U') Then
        Read (nin, *)(a(i,i:n), i=1, n)
      Else If (uplo=='L') Then
        Read (nin, *)(a(i,1:i), i=1, n)
      End If

!     Factorize A
      Call zpotrf(uplo, n, a, lda, info)

      Write (nout, *)
      Flush (nout)
      If (info==0) Then

!       Compute inverse of A
        Call zpotri(uplo, n, a, lda, info)

!       Print inverse

!       ifail: behaviour on error exit
!              =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
        ifail = 0
        Call nagf_file_print_matrix_complex_gen_comp(uplo, 'Nonunit', n, n, a, &
          lda, 'Bracketed', 'F7.4', 'Inverse', 'Integer', rlabs, 'Integer', &
          clabs, 80, 0, ifail)
      Else
        Write (nout, *) 'A is not positive definite'
      End If

    End Program
Full documentation of ZPOTRI


ZPOTRS example

Computational Routines: Solution of complex Hermitian positive-definite system of linear equations, multiple right-hand sides, matrix already factorized by ZPOTRF

Data

ZPOTRS Example Program Data
  4  2                                                   :Values of N and NRHS
  'L'                                                    :Value of UPLO
 (3.23, 0.00)
 (1.51, 1.92) ( 3.58, 0.00)
 (1.90,-0.84) (-0.23,-1.11) ( 4.09, 0.00)
 (0.42,-2.50) (-1.18,-1.37) ( 2.33, 0.14) ( 4.29, 0.00)  :End of matrix A
 ( 3.93, -6.14) ( 1.48,  6.58)
 ( 6.17,  9.42) ( 4.65, -4.75)
 (-7.17,-21.83) (-4.91,  2.29)
 ( 1.99,-14.38) ( 7.64,-10.79)                           :End of matrix B

Result

 ZPOTRS Example Program Results

 Solution(s)
                    1                 2
 1  ( 1.0000,-1.0000) (-1.0000, 2.0000)
 2  (-0.0000, 3.0000) ( 3.0000,-4.0000)
 3  (-4.0000,-5.0000) (-2.0000, 3.0000)
 4  ( 2.0000, 1.0000) ( 4.0000,-5.0000)

Source

    Program zpotrs_example

!     ZPOTRS Example Program Text

!     Copyright 2017, Numerical Algorithms Group Ltd. http://www.nag.com

!     .. Use Statements ..
      Use lapack_example_aux, Only: nagf_file_print_matrix_complex_gen_comp
      Use lapack_interfaces, Only: zpotrf, zpotrs
      Use lapack_precision, Only: dp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter :: nin = 5, nout = 6
!     .. Local Scalars ..
      Integer :: i, ifail, info, lda, ldb, n, nrhs
      Character (1) :: uplo
!     .. Local Arrays ..
      Complex (Kind=dp), Allocatable :: a(:, :), b(:, :)
      Character (1) :: clabs(1), rlabs(1)
!     .. Executable Statements ..
      Write (nout, *) 'ZPOTRS Example Program Results'
!     Skip heading in data file
      Read (nin, *)
      Read (nin, *) n, nrhs
      lda = n
      ldb = n
      Allocate (a(lda,n), b(ldb,nrhs))

!     Read A and B from data file

      Read (nin, *) uplo
      If (uplo=='U') Then
        Read (nin, *)(a(i,i:n), i=1, n)
      Else If (uplo=='L') Then
        Read (nin, *)(a(i,1:i), i=1, n)
      End If
      Read (nin, *)(b(i,1:nrhs), i=1, n)

!     Factorize A
      Call zpotrf(uplo, n, a, lda, info)

      Write (nout, *)
      Flush (nout)
      If (info==0) Then

!       Compute solution
        Call zpotrs(uplo, n, nrhs, a, lda, b, ldb, info)

!       Print solution

!       ifail: behaviour on error exit
!              =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
        ifail = 0
        Call nagf_file_print_matrix_complex_gen_comp('General', ' ', n, nrhs, &
          b, ldb, 'Bracketed', 'F7.4', 'Solution(s)', 'Integer', rlabs, &
          'Integer', clabs, 80, 0, ifail)

      Else
        Write (nout, *) 'A is not positive definite'
      End If

    End Program
Full documentation of ZPOTRS


ZPPCON example

Computational Routines: Estimate condition number of complex Hermitian positive-definite matrix, matrix already factorized by ZPPTRF, packed storage

Data

ZPPCON Example Program Data
  4                                                      :Value of N
  'L'                                                    :Value of UPLO
 (3.23, 0.00)
 (1.51, 1.92) ( 3.58, 0.00)
 (1.90,-0.84) (-0.23,-1.11) ( 4.09, 0.00)
 (0.42,-2.50) (-1.18,-1.37) ( 2.33, 0.14) ( 4.29, 0.00)  :End of matrix A

Result

 ZPPCON Example Program Results

 Estimate of condition number =  1.51E+02

Source

    Program zppcon_example

!     ZPPCON Example Program Text

!     Copyright 2017, Numerical Algorithms Group Ltd. http://www.nag.com

!     .. Use Statements ..
      Use lapack_interfaces, Only: zlanhp, zppcon, zpptrf
      Use lapack_precision, Only: dp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=dp) :: anorm, rcond
      Integer :: i, info, j, n
      Character (1) :: uplo
!     .. Local Arrays ..
      Complex (Kind=dp), Allocatable :: ap(:), work(:)
      Real (Kind=dp), Allocatable :: rwork(:)
!     .. Intrinsic Procedures ..
      Intrinsic :: epsilon
!     .. Executable Statements ..
      Write (nout, *) 'ZPPCON Example Program Results'
!     Skip heading in data file
      Read (nin, *)
      Read (nin, *) n

      Allocate (ap(n*(n+1)/2), work(2*n), rwork(n))

!     Read A from data file

      Read (nin, *) uplo
      If (uplo=='U') Then
        Read (nin, *)((ap(i+j*(j-1)/2),j=i,n), i=1, n)
      Else If (uplo=='L') Then
        Read (nin, *)((ap(i+(2*n-j)*(j-1)/2),j=1,i), i=1, n)
      End If

!     Compute norm of A
      anorm = zlanhp('1-norm', uplo, n, ap, rwork)

!     Factorize A
      Call zpptrf(uplo, n, ap, info)

      Write (nout, *)
      If (info==0) Then

!       Estimate condition number

        Call zppcon(uplo, n, ap, anorm, rcond, work, rwork, info)

        If (rcond>=epsilon(1.0E0_dp)) Then
          Write (nout, 100) 'Estimate of condition number =', 1.0_dp/rcond
        Else
          Write (nout, *) 'A is singular to working precision'
        End If
      Else
        Write (nout, *) 'A is not positive definite'
      End If

100   Format (1X, A, 1P, E10.2)
    End Program
Full documentation of ZPPCON


ZPPEQU example

Computational Routines: Computes row and column scalings intended to equilibrate a complex Hermitian positive-definite matrix and reduce its condition number, packed storage

Data

ZPPEQU Example Program Data
   4                                                            :Value of N
 ( 3.23, 0.00) ( 1.51,-1.92) ( 1.90D+05, 0.84D+05) ( 0.42D+00, 2.50D+00)
               ( 3.58, 0.00) (-0.23D+05, 1.11D+05) (-1.18D+00, 1.37D+00)
                             ( 4.09D+10, 0.00D+00) ( 2.33D+05,-0.14D+05)
                                                   ( 4.29D+00, 0.00D+00)
                                                                :End of matrix A

Result

 ZPPEQU Example Program Results

 Matrix A
                          1                       2                       3
 1  (  3.23E+00,  0.00E+00) (  1.51E+00, -1.92E+00) (  1.90E+05,  8.40E+04)
 2                          (  3.58E+00,  0.00E+00) ( -2.30E+04,  1.11E+05)
 3                                                  (  4.09E+10,  0.00E+00)
 4

                          4
 1  (  4.20E-01,  2.50E+00)
 2  ( -1.18E+00,  1.37E+00)
 3  (  2.33E+05, -1.40E+04)
 4  (  4.29E+00,  0.00E+00)

 SCOND = 8.9E-06, AMAX = 4.1E+10

 Diagonal scaling factors
     5.6E-01    5.3E-01    4.9E-06    4.8E-01

 Scaled matrix
                      1                   2                   3
 1  (  1.0000,  0.0000) (  0.4441, -0.5646) (  0.5227,  0.2311)
 2                      (  1.0000,  0.0000) ( -0.0601,  0.2901)
 3                                          (  1.0000,  0.0000)
 4

                      4
 1  (  0.1128,  0.6716)
 2  ( -0.3011,  0.3496)
 3  (  0.5562, -0.0334)
 4  (  1.0000,  0.0000)

Source

    Program zppequ_example

!     ZPPEQU Example Program Text

!     Copyright 2017, Numerical Algorithms Group Ltd. http://www.nag.com

!     .. Use Statements ..
      Use blas_interfaces, Only: zdscal
      Use lapack_example_aux, Only: nagf_blas_zddscl, &
        nagf_file_print_matrix_complex_packed_comp
      Use lapack_interfaces, Only: zppequ
      Use lapack_precision, Only: dp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Real (Kind=dp), Parameter :: one = 1.0_dp
      Real (Kind=dp), Parameter :: thresh = 0.1_dp
      Integer, Parameter :: nin = 5, nout = 6
      Character (1), Parameter :: uplo = 'U'
!     .. Local Scalars ..
      Real (Kind=dp) :: amax, big, scond, small
      Integer :: i, ifail, info, j, jinc, jj, n
!     .. Local Arrays ..
      Complex (Kind=dp), Allocatable :: ap(:)
      Real (Kind=dp), Allocatable :: s(:)
      Character (1) :: clabs(1), rlabs(1)
!     .. Intrinsic Procedures ..
      Intrinsic :: epsilon, radix, real, tiny
!     .. Executable Statements ..
      Write (nout, *) 'ZPPEQU Example Program Results'
      Write (nout, *)
      Flush (nout)
!     Skip heading in data file
      Read (nin, *)
      Read (nin, *) n

      Allocate (ap((n*(n+1))/2), s(n))

!     Read the upper or lower triangular part of the matrix A from
!     data file

      If (uplo=='U') Then
        Read (nin, *)((ap(i+(j*(j-1))/2),j=i,n), i=1, n)
      Else If (uplo=='L') Then
        Read (nin, *)((ap(i+((2*n-j)*(j-1))/2),j=1,i), i=1, n)
      End If

!     Print the matrix A

!     ifail: behaviour on error exit
!             =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
      ifail = 0
      Call nagf_file_print_matrix_complex_packed_comp(uplo, &
        'Non-unit diagonal', n, ap, 'Bracketed', '1P,E10.2', 'Matrix A', &
        'Integer', rlabs, 'Integer', clabs, 80, 0, ifail)

      Write (nout, *)

!     Compute diagonal scaling factors
      Call zppequ(uplo, n, ap, s, scond, amax, info)

      If (info>0) Then
        Write (nout, 100) 'Diagonal element', info, ' of A is non positive'
      Else

!       Print SCOND, AMAX and the scale factors

        Write (nout, 110) 'SCOND =', scond, ', AMAX =', amax
        Write (nout, *)
        Write (nout, *) 'Diagonal scaling factors'
        Write (nout, 120) s(1:n)
        Write (nout, *)
        Flush (nout)

!       Compute values close to underflow and overflow

        small = tiny(1.0E0_dp)/(epsilon(1.0E0_dp)*real(radix(1.0E0_dp),kind=dp &
          ))
        big = one/small
        If ((scond<thresh) .Or. (amax<small) .Or. (amax>big)) Then

!         Scale A

          If (uplo=='U') Then

            jj = 1
            Do j = 1, n
              Call zdscal(j, s(j), ap(jj), 1)
              Call nagf_blas_zddscl(j, s, 1, ap(jj), 1)
              jj = jj + j
            End Do
          Else If (uplo=='L') Then
            jj = 1
            jinc = n
            Do j = 1, n
              Call zdscal(jinc, s(j), ap(jj), 1)
              Call nagf_blas_zddscl(jinc, s(j), 1, ap(jj), 1)
              jj = jj + jinc
              jinc = jinc - 1
            End Do
          End If

!         Print the scaled matrix

          ifail = 0
          Call nagf_file_print_matrix_complex_packed_comp(uplo, &
            'Non-unit diagonal', n, ap, 'Bracketed', 'F8.4', 'Scaled matrix', &
            'Integer', rlabs, 'Integer', clabs, 80, 0, ifail)

        End If
      End If

100   Format (1X, A, I4, A)
110   Format (1X, 2(A,1P,E8.1))
120   Format ((1X,1P,7E11.1))
    End Program
Full documentation of ZPPEQU


ZPPRFS example

Computational Routines: Refined solution with error bounds of complex Hermitian positive-definite system of linear equations, multiple right-hand sides, packed storage

Data

ZPPRFS Example Program Data
  4  2                                                   :Values of N and NRHS
  'L'                                                    :Value of UPLO
 (3.23, 0.00)
 (1.51, 1.92) ( 3.58, 0.00)
 (1.90,-0.84) (-0.23,-1.11) ( 4.09, 0.00)
 (0.42,-2.50) (-1.18,-1.37) ( 2.33, 0.14) ( 4.29, 0.00)  :End of matrix A
 ( 3.93, -6.14) ( 1.48,  6.58)
 ( 6.17,  9.42) ( 4.65, -4.75)
 (-7.17,-21.83) (-4.91,  2.29)
 ( 1.99,-14.38) ( 7.64,-10.79)                           :End of matrix B

Result

 ZPPRFS Example Program Results

 Solution(s)
                    1                 2
 1  ( 1.0000,-1.0000) (-1.0000, 2.0000)
 2  (-0.0000, 3.0000) ( 3.0000,-4.0000)
 3  (-4.0000,-5.0000) (-2.0000, 3.0000)
 4  ( 2.0000, 1.0000) ( 4.0000,-5.0000)

 Backward errors (machine-dependent)
         5.5E-17           7.9E-17
 Estimated forward error bounds (machine-dependent)
         6.0E-14           7.2E-14

Source

    Program zpprfs_example

!     ZPPRFS Example Program Text

!     Copyright 2017, Numerical Algorithms Group Ltd. http://www.nag.com

!     .. Use Statements ..
      Use lapack_example_aux, Only: nagf_file_print_matrix_complex_gen_comp
      Use lapack_interfaces, Only: zpprfs, zpptrf, zpptrs
      Use lapack_precision, Only: dp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter :: nin = 5, nout = 6
!     .. Local Scalars ..
      Integer :: aplen, i, ifail, info, j, ldb, ldx, n, nrhs
      Character (1) :: uplo
!     .. Local Arrays ..
      Complex (Kind=dp), Allocatable :: afp(:), ap(:), b(:, :), work(:), &
        x(:, :)
      Real (Kind=dp), Allocatable :: berr(:), ferr(:), rwork(:)
      Character (1) :: clabs(1), rlabs(1)
!     .. Executable Statements ..
      Write (nout, *) 'ZPPRFS Example Program Results'
!     Skip heading in data file
      Read (nin, *)
      Read (nin, *) n, nrhs
      ldb = n
      ldx = n
      aplen = n*(n+1)/2
      Allocate (afp(aplen), ap(aplen), b(ldb,nrhs), work(2*n), x(ldx,n), &
        berr(nrhs), ferr(nrhs), rwork(n))

!     Read A and B from data file, and copy A to AFP and B to X

      Read (nin, *) uplo
      If (uplo=='U') Then
        Read (nin, *)((ap(i+j*(j-1)/2),j=i,n), i=1, n)
      Else If (uplo=='L') Then
        Read (nin, *)((ap(i+(2*n-j)*(j-1)/2),j=1,i), i=1, n)
      End If
      Read (nin, *)(b(i,1:nrhs), i=1, n)

      afp(1:aplen) = ap(1:aplen)
      x(1:n, 1:nrhs) = b(1:n, 1:nrhs)

!     Factorize A in the array AFP
      Call zpptrf(uplo, n, afp, info)

      Write (nout, *)
      Flush (nout)
      If (info==0) Then

!       Compute solution in the array X
        Call zpptrs(uplo, n, nrhs, afp, x, ldx, info)

!       Improve solution, and compute backward errors and
!       estimated bounds on the forward errors

        Call zpprfs(uplo, n, nrhs, ap, afp, b, ldb, x, ldx, ferr, berr, work, &
          rwork, info)

!       Print solution

!       ifail: behaviour on error exit
!              =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
        ifail = 0
        Call nagf_file_print_matrix_complex_gen_comp('General', ' ', n, nrhs, &
          x, ldx, 'Bracketed', 'F7.4', 'Solution(s)', 'Integer', rlabs, &
          'Integer', clabs, 80, 0, ifail)

        Write (nout, *)
        Write (nout, *) 'Backward errors (machine-dependent)'
        Write (nout, 100) berr(1:nrhs)
        Write (nout, *) 'Estimated forward error bounds (machine-dependent)'
        Write (nout, 100) ferr(1:nrhs)
      Else
        Write (nout, *) 'A is not positive definite'
      End If

100   Format ((5X,1P,4(E11.1,7X)))
    End Program
Full documentation of ZPPRFS


ZPPTRF example

Computational Routines: Cholesky factorization of complex Hermitian positive-definite matrix, packed storage

Data

ZPPTRF Example Program Data
  4                                                      :Value of N
  'L'                                                    :Value of UPLO
 (3.23, 0.00)
 (1.51, 1.92) ( 3.58, 0.00)
 (1.90,-0.84) (-0.23,-1.11) ( 4.09, 0.00)
 (0.42,-2.50) (-1.18,-1.37) ( 2.33, 0.14) ( 4.29, 0.00)  :End of matrix A

Result

 ZPPTRF Example Program Results

 Factor
                    1                 2                 3                 4
 1  ( 1.7972, 0.0000)
 2  ( 0.8402, 1.0683) ( 1.3164, 0.0000)
 3  ( 1.0572,-0.4674) (-0.4702, 0.3131) ( 1.5604, 0.0000)
 4  ( 0.2337,-1.3910) ( 0.0834, 0.0368) ( 0.9360, 0.9900) ( 0.6603, 0.0000)

Source

    Program zpptrf_example

!     ZPPTRF Example Program Text

!     Copyright 2017, Numerical Algorithms Group Ltd. http://www.nag.com

!     .. Use Statements ..
      Use lapack_example_aux, Only: nagf_file_print_matrix_complex_packed_comp
      Use lapack_interfaces, Only: zpptrf
      Use lapack_precision, Only: dp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter :: nin = 5, nout = 6
!     .. Local Scalars ..
      Integer :: i, ifail, info, j, n
      Character (1) :: uplo
!     .. Local Arrays ..
      Complex (Kind=dp), Allocatable :: ap(:)
      Character (1) :: clabs(1), rlabs(1)
!     .. Executable Statements ..
      Write (nout, *) 'ZPPTRF Example Program Results'
!     Skip heading in data file
      Read (nin, *)
      Read (nin, *) n

      Allocate (ap(n*(n+1)/2))

!     Read A from data file

      Read (nin, *) uplo
      If (uplo=='U') Then
        Read (nin, *)((ap(i+j*(j-1)/2),j=i,n), i=1, n)
      Else If (uplo=='L') Then
        Read (nin, *)((ap(i+(2*n-j)*(j-1)/2),j=1,i), i=1, n)
      End If

!     Factorize A
      Call zpptrf(uplo, n, ap, info)

      Write (nout, *)
      Flush (nout)
      If (info==0) Then

!       Print factor

!       ifail: behaviour on error exit
!              =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
        ifail = 0
        Call nagf_file_print_matrix_complex_packed_comp(uplo, 'Nonunit', n, &
          ap, 'Bracketed', 'F7.4', 'Factor', 'Integer', rlabs, 'Integer', &
          clabs, 80, 0, ifail)

      Else
        Write (nout, *) 'A is not positive definite'
      End If

    End Program
Full documentation of ZPPTRF


ZPPTRI example

Computational Routines: Inverse of complex Hermitian positive-definite matrix, matrix already factorized by ZPPTRF, packed storage

Data

ZPPTRI Example Program Data
  4                                                      :Value of N
  'L'                                                    :Value of UPLO
 (3.23, 0.00)
 (1.51, 1.92) ( 3.58, 0.00)
 (1.90,-0.84) (-0.23,-1.11) ( 4.09, 0.00)
 (0.42,-2.50) (-1.18,-1.37) ( 2.33, 0.14) ( 4.29, 0.00)  :End of matrix A

Result

 ZPPTRI Example Program Results

 Inverse
                    1                 2                 3                 4
 1  ( 5.4691, 0.0000)
 2  (-1.2624,-1.5491) ( 1.1024, 0.0000)
 3  (-2.9746,-0.9616) ( 0.8989,-0.5672) ( 2.1589, 0.0000)
 4  ( 1.1962, 2.9772) (-0.9826,-0.2566) (-1.3756,-1.4550) ( 2.2934, 0.0000)

Source

    Program zpptri_example

!     ZPPTRI Example Program Text

!     Copyright 2017, Numerical Algorithms Group Ltd. http://www.nag.com

!     .. Use Statements ..
      Use lapack_example_aux, Only: nagf_file_print_matrix_complex_packed_comp
      Use lapack_interfaces, Only: zpptrf, zpptri
      Use lapack_precision, Only: dp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter :: nin = 5, nout = 6
!     .. Local Scalars ..
      Integer :: i, ifail, info, j, n
      Character (1) :: uplo
!     .. Local Arrays ..
      Complex (Kind=dp), Allocatable :: ap(:)
      Character (1) :: clabs(1), rlabs(1)
!     .. Executable Statements ..
      Write (nout, *) 'ZPPTRI Example Program Results'
!     Skip heading in data file
      Read (nin, *)
      Read (nin, *) n

      Allocate (ap(n*(n+1)/2))

!     Read A from data file

      Read (nin, *) uplo
      If (uplo=='U') Then
        Read (nin, *)((ap(i+j*(j-1)/2),j=i,n), i=1, n)
      Else If (uplo=='L') Then
        Read (nin, *)((ap(i+(2*n-j)*(j-1)/2),j=1,i), i=1, n)
      End If

!     Factorize A
      Call zpptrf(uplo, n, ap, info)

      Write (nout, *)
      Flush (nout)
      If (info==0) Then

!       Compute inverse of A
        Call zpptri(uplo, n, ap, info)

!       Print inverse

!       ifail: behaviour on error exit
!              =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
        ifail = 0
        Call nagf_file_print_matrix_complex_packed_comp(uplo, 'Nonunit', n, &
          ap, 'Bracketed', 'F7.4', 'Inverse', 'Integer', rlabs, 'Integer', &
          clabs, 80, 0, ifail)

      Else
        Write (nout, *) 'A is not positive definite'
      End If

    End Program
Full documentation of ZPPTRI


ZPPTRS example

Computational Routines: Solution of complex Hermitian positive-definite system of linear equations, multiple right-hand sides, matrix already factorized by ZPPTRF, packed storage

Data

ZPPTRS Example Program Data
  4  2                                                   :Values of N and NRHS
  'L'                                                    :Value of UPLO
 (3.23, 0.00)
 (1.51, 1.92) ( 3.58, 0.00)
 (1.90,-0.84) (-0.23,-1.11) ( 4.09, 0.00)
 (0.42,-2.50) (-1.18,-1.37) ( 2.33, 0.14) ( 4.29, 0.00)  :End of matrix A
 ( 3.93, -6.14) ( 1.48,  6.58)
 ( 6.17,  9.42) ( 4.65, -4.75)
 (-7.17,-21.83) (-4.91,  2.29)
 ( 1.99,-14.38) ( 7.64,-10.79)                           :End of matrix B

Result

 ZPPTRS Example Program Results

 Solution(s)
                    1                 2
 1  ( 1.0000,-1.0000) (-1.0000, 2.0000)
 2  (-0.0000, 3.0000) ( 3.0000,-4.0000)
 3  (-4.0000,-5.0000) (-2.0000, 3.0000)
 4  ( 2.0000, 1.0000) ( 4.0000,-5.0000)

Source

    Program zpptrs_example

!     ZPPTRS Example Program Text

!     Copyright 2017, Numerical Algorithms Group Ltd. http://www.nag.com

!     .. Use Statements ..
      Use lapack_example_aux, Only: nagf_file_print_matrix_complex_gen_comp
      Use lapack_interfaces, Only: zpptrf, zpptrs
      Use lapack_precision, Only: dp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter :: nin = 5, nout = 6
!     .. Local Scalars ..
      Integer :: i, ifail, info, j, ldb, n, nrhs
      Character (1) :: uplo
!     .. Local Arrays ..
      Complex (Kind=dp), Allocatable :: ap(:), b(:, :)
      Character (1) :: clabs(1), rlabs(1)
!     .. Executable Statements ..
      Write (nout, *) 'ZPPTRS Example Program Results'
!     Skip heading in data file
      Read (nin, *)
      Read (nin, *) n, nrhs
      ldb = n
      Allocate (ap(n*(n+1)/2), b(ldb,nrhs))

!     Read A and B from data file

      Read (nin, *) uplo
      If (uplo=='U') Then
        Read (nin, *)((ap(i+j*(j-1)/2),j=i,n), i=1, n)
      Else If (uplo=='L') Then
        Read (nin, *)((ap(i+(2*n-j)*(j-1)/2),j=1,i), i=1, n)
      End If
      Read (nin, *)(b(i,1:nrhs), i=1, n)

!     Factorize A
      Call zpptrf(uplo, n, ap, info)

      Write (nout, *)
      Flush (nout)
      If (info==0) Then

!       Compute solution
        Call zpptrs(uplo, n, nrhs, ap, b, ldb, info)

!       Print solution

!       ifail: behaviour on error exit
!              =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
        ifail = 0
        Call nagf_file_print_matrix_complex_gen_comp('General', ' ', n, nrhs, &
          b, ldb, 'Bracketed', 'F7.4', 'Solution(s)', 'Integer', rlabs, &
          'Integer', clabs, 80, 0, ifail)

      Else
        Write (nout, *) 'A is not positive definite'
      End If

    End Program
Full documentation of ZPPTRS


ZPSTRF example

Computational Routines: Cholesky factorization of complex Hermitian positive semidefinite matrix

Data

ZPSTRF Example Program Data
  5 'L'                                                               : n, uplo
(12.40, 0.00)
( 2.39, 0.00) ( 1.63, 0.00)
( 5.50, 0.05) ( 1.04, 0.10) ( 2.45, 0.00)
( 4.47, 0.00) ( 1.14, 0.00) ( 1.98,-0.03) ( 1.71, 0.00)
(11.89, 0.00) ( 1.81, 0.00) ( 5.28,-0.02) ( 4.14, 0.00) (11.63, 0.00) : End of A

Result

 ZPSTRF Example Program Results

 Computed rank:   3

 Factor
                1             2             3             4             5
 1  ( 3.52, 0.00)
 2  ( 0.68, 0.00) ( 1.08, 0.00)
 3  ( 1.27, 0.00) ( 0.26, 0.00) ( 0.18, 0.00)
 4  ( 1.56, 0.01) (-0.02, 0.08) ( 0.01,-0.05) ( 0.00, 0.00)
 5  ( 3.38, 0.00) (-0.45, 0.00) (-0.17, 0.00) ( 0.00, 0.00) ( 0.00, 0.00)

 PIV
                1             2             4             3             5

Source

    Program zpstrf_example

!     ZPSTRF Example Program Text

!     Copyright 2017, Numerical Algorithms Group Ltd. http://www.nag.com

!     .. Use Statements ..
      Use lapack_example_aux, Only: nagf_file_print_matrix_complex_gen_comp, &
        nagf_file_print_matrix_integer_comp
      Use lapack_interfaces, Only: zpstrf
      Use lapack_precision, Only: dp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Complex (Kind=dp), Parameter :: zero = (0.0E0_dp, 0.0E0_dp)
      Integer, Parameter :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=dp) :: tol
      Integer :: i, ifail, info, j, lda, n, rank
      Character (1) :: uplo
!     .. Local Arrays ..
      Complex (Kind=dp), Allocatable :: a(:, :)
      Real (Kind=dp), Allocatable :: work(:)
      Integer, Allocatable :: piv(:)
      Character (1) :: clabs(1), rlabs(1)
!     .. Executable Statements ..
      Write (nout, *) 'ZPSTRF Example Program Results'
!     Skip heading in data file
      Read (nin, *)
      Read (nin, *) n, uplo
      lda = n
      Allocate (a(lda,n), piv(n), work(2*n))

!     Read A from data file
      If (uplo=='U') Then
        Read (nin, *)(a(i,i:n), i=1, n)
      Else If (uplo=='L') Then
        Read (nin, *)(a(i,1:i), i=1, n)
      End If
      tol = -1.0_dp

!     Factorize A
      Call zpstrf(uplo, n, a, lda, piv, rank, tol, work, info)

!     Zero out columns rank+1 to n
      If (uplo=='U') Then
        Do j = rank + 1, n
          a(rank+1:j, j) = zero
        End Do
      Else If (uplo=='L') Then
        Do j = rank + 1, n
          a(j:n, j) = zero
        End Do
      End If

!     Print rank
      Write (nout, *)
      Write (nout, '(1X,A15,I3)') 'Computed rank: ', rank

!     Print factor
      Write (nout, *)
      Flush (nout)
      ifail = 0
      Call nagf_file_print_matrix_complex_gen_comp(uplo, 'Nonunit', n, n, a, &
        lda, 'Bracketed', 'F5.2', 'Factor', 'Integer', rlabs, 'Integer', &
        clabs, 80, 0, ifail)

!     Print pivot indices
      Write (nout, *)
      Write (nout, *) 'PIV'
      Flush (nout)
      ifail = 0
      Call nagf_file_print_matrix_integer_comp('General', 'Non-unit', 1, n, &
        piv, 1, 'I14', ' ', 'No', rlabs, 'No', clabs, 80, 1, ifail)

    End Program
Full documentation of ZPSTRF


ZPTCON example

Computational Routines: Computes the reciprocal of the condition number of a complex Hermitian positive-definite tridiagonal system using the L * D * L' factorization computed by ZPTTRF

Data

ZPTCON Example Program Data
    4                                                    :Value of N
   16.0          41.0          46.0          21.0        :End of diagonal D
 ( 16.0, 16.0) ( 18.0, -9.0) (  1.0, -4.0)               :End of sub-diagonal E

Result

 ZPTCON Example Program Results

 Estimate of condition number =   9.21E+03

Source

    Program zptcon_example

!     ZPTCON Example Program Text

!     Copyright 2017, Numerical Algorithms Group Ltd. http://www.nag.com

!     .. Use Statements ..
      Use lapack_interfaces, Only: zlanht, zptcon, zpttrf
      Use lapack_precision, Only: dp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=dp) :: anorm, rcond
      Integer :: info, n
!     .. Local Arrays ..
      Complex (Kind=dp), Allocatable :: e(:)
      Real (Kind=dp), Allocatable :: d(:), rwork(:)
!     .. Intrinsic Procedures ..
      Intrinsic :: epsilon
!     .. Executable Statements ..
      Write (nout, *) 'ZPTCON Example Program Results'
      Write (nout, *)
!     Skip heading in data file
      Read (nin, *)
      Read (nin, *) n

      Allocate (e(n-1), d(n), rwork(n))

!     Read the lower bidiagonal part of the tridiagonal matrix A from
!     data file

      Read (nin, *) d(1:n)
      Read (nin, *) e(1:n-1)

!     Compute the 1-norm of A
      anorm = zlanht('1-norm', n, d, e)

!     Factorize the tridiagonal matrix A
      Call zpttrf(n, d, e, info)

      If (info==0) Then

!       Estimate the condition number of A
        Call zptcon(n, d, e, anorm, rcond, rwork, info)

!       Print the estimated condition number

        If (rcond>=epsilon(1.0E0_dp)) Then
          Write (nout, 100) 'Estimate of condition number = ', 1.0E0_dp/rcond
        Else
          Write (nout, 100) 'A is singular to working precision. RCOND = ', &
            rcond
        End If

      Else
        Write (nout, 110) 'The leading minor of order ', info, &
          ' is not positive definite'
      End If

100   Format (1X, A, 1P, E10.2)
110   Format (1X, A, I3, A)
    End Program
Full documentation of ZPTCON


ZPTEQR example

Computational Routines: All eigenvalues and eigenvectors of real symmetric positive-definite tridiagonal matrix, reduced from complex Hermitian positive-definite matrix

Data

ZPTEQR Example Program Data
  4                                                        :Value of N
  'L'                                                      :Value of UPLO
 ( 6.02, 0.00)
 (-0.45,-0.25) ( 2.91, 0.00)
 (-1.30,-1.74) ( 0.05,-1.56) ( 3.29, 0.00)
 ( 1.45, 0.66) (-1.04,-1.27) ( 0.14,-1.70) ( 4.18, 0.00)   :End of matrix A

Result

 ZPTEQR Example Program Results

 Eigenvalues
         7.9995            5.9976            2.0003            0.4026

 Eigenvectors
                    1                 2                 3                 4
 1  ( 0.7289, 0.0000) ( 0.2001, 0.4724) (-0.2133, 0.1498) ( 0.0995,-0.3573)
 2  (-0.1651,-0.2067) (-0.2461, 0.3742) ( 0.7308, 0.0000) ( 0.2867,-0.3364)
 3  (-0.4170,-0.1413) ( 0.4476, 0.1455) (-0.3282, 0.0471) ( 0.6890, 0.0000)
 4  ( 0.1748, 0.4175) ( 0.5610, 0.0000) ( 0.5203, 0.1317) ( 0.0659, 0.4336)

Source

    Program zpteqr_example

!     ZPTEQR Example Program Text

!     Copyright 2017, Numerical Algorithms Group Ltd. http://www.nag.com

!     .. Use Statements ..
      Use blas_interfaces, Only: dznrm2
      Use lapack_example_aux, Only: nagf_file_print_matrix_complex_gen_comp
      Use lapack_interfaces, Only: zhetrd, zlacpy, zpteqr, zungtr
      Use lapack_precision, Only: dp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter :: nin = 5, nout = 6
!     .. Local Scalars ..
      Complex (Kind=dp) :: scal
      Integer :: i, ifail, info, k, lda, ldz, lwork, n
      Character (1) :: uplo
!     .. Local Arrays ..
      Complex (Kind=dp), Allocatable :: a(:, :), tau(:), work(:), z(:, :)
      Real (Kind=dp), Allocatable :: d(:), e(:), rwork(:)
      Character (1) :: clabs(1), rlabs(1)
!     .. Intrinsic Procedures ..
      Intrinsic :: abs, conjg, maxloc
!     .. Executable Statements ..
      Write (nout, *) 'ZPTEQR Example Program Results'
!     Skip heading in data file
      Read (nin, *)
      Read (nin, *) n
      lda = n
      ldz = n
      lwork = 64*n
      Allocate (a(lda,n), tau(n), work(lwork), z(ldz,n), d(n), e(n), &
        rwork(4*n))

!     Read A from data file

      Read (nin, *) uplo
      If (uplo=='U') Then
        Read (nin, *)(a(i,i:n), i=1, n)
      Else If (uplo=='L') Then
        Read (nin, *)(a(i,1:i), i=1, n)
      End If

!     Reduce A to tridiagonal form T = (Q**H)*A*Q

      Call zhetrd(uplo, n, a, lda, d, e, tau, work, lwork, info)

!     Copy A into Z

      Call zlacpy(uplo, n, n, a, lda, z, ldz)

!     Form Q explicitly, storing the result in Z

      Call zungtr(uplo, n, z, ldz, tau, work, lwork, info)

!     Calculate all the eigenvalues and eigenvectors of A

      Call zpteqr('V', n, d, e, z, ldz, rwork, info)

      Write (nout, *)
      If (info>0) Then
        Write (nout, *) 'Failure to converge.'
      Else

!       Print eigenvalues and eigenvectors

        Write (nout, *) 'Eigenvalues'
        Write (nout, 100) d(1:n)
        Write (nout, *)
        Flush (nout)

!       Normalize the eigenvectors, largest element real
        Do i = 1, n
          rwork(1:n) = abs(z(1:n,i))
          k = maxloc(rwork(1:n), 1)
          scal = conjg(z(k,i))/abs(z(k,i))/dznrm2(n, z(1,i), 1)
          z(1:n, i) = z(1:n, i)*scal
        End Do

!       ifail: behaviour on error exit
!              =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
        ifail = 0
        Call nagf_file_print_matrix_complex_gen_comp('General', ' ', n, n, z, &
          ldz, 'Bracketed', 'F7.4', 'Eigenvectors', 'Integer', rlabs, &
          'Integer', clabs, 80, 0, ifail)

      End If

100   Format (8X, 4(F7.4,11X,:))
    End Program
Full documentation of ZPTEQR


ZPTRFS example

Computational Routines: Refined solution with error bounds of complex Hermitian positive-definite tridiagonal system of linear equations, multiple right-hand sides

Data

ZPTRFS Example Program Data
    4             2                               :Values of N and NRHS
   16.0          41.0          46.0          21.0 :End of diagonal D
 ( 16.0, 16.0) ( 18.0, -9.0) (  1.0, -4.0)        :End of sub-diagonal E
 ( 64.0, 16.0) (-16.0,-32.0)
 ( 93.0, 62.0) ( 61.0,-66.0)
 ( 78.0,-80.0) ( 71.0,-74.0)
 ( 14.0,-27.0) ( 35.0, 15.0)                      :End of matrix B

Result

 ZPTRFS Example Program Results

 Solution(s)
                    1                 2
 1  ( 2.0000, 1.0000) (-3.0000,-2.0000)
 2  ( 1.0000, 1.0000) ( 1.0000, 1.0000)
 3  ( 1.0000,-2.0000) ( 1.0000,-2.0000)
 4  ( 1.0000,-1.0000) ( 2.0000, 1.0000)

 Backward errors (machine-dependent)
       0.0E+00    0.0E+00

 Estimated forward error bounds (machine-dependent)
       9.0E-12    6.1E-12

Source

    Program zptrfs_example

!     ZPTRFS Example Program Text

!     Copyright 2017, Numerical Algorithms Group Ltd. http://www.nag.com

!     .. Use Statements ..
      Use lapack_example_aux, Only: nagf_file_print_matrix_complex_gen_comp
      Use lapack_interfaces, Only: zptrfs, zpttrf, zpttrs
      Use lapack_precision, Only: dp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter :: nin = 5, nout = 6
!     .. Local Scalars ..
      Integer :: i, ifail, info, ldb, ldx, n, nrhs
!     .. Local Arrays ..
      Complex (Kind=dp), Allocatable :: b(:, :), e(:), ef(:), work(:), x(:, :)
      Real (Kind=dp), Allocatable :: berr(:), d(:), df(:), ferr(:), rwork(:)
      Character (1) :: clabs(1), rlabs(1)
!     .. Executable Statements ..
      Write (nout, *) 'ZPTRFS Example Program Results'
      Write (nout, *)
      Flush (nout)
!     Skip heading in data file
      Read (nin, *)
      Read (nin, *) n, nrhs
      ldb = n
      ldx = n
      Allocate (b(ldb,nrhs), e(n-1), ef(n-1), work(n), x(ldx,nrhs), &
        berr(nrhs), d(n), df(n), ferr(nrhs), rwork(n))

!     Read the lower bidiagonal part of the tridiagonal matrix A from
!     data file

      Read (nin, *) d(1:n)
      Read (nin, *) e(1:n-1)

!     Read the right hand matrix B

      Read (nin, *)(b(i,1:nrhs), i=1, n)

!     Copy A into DF and EF, and copy B into X
      df(1:n) = d(1:n)
      ef(1:n-1) = e(1:n-1)
      x(1:n, 1:nrhs) = b(1:n, 1:nrhs)

!     Factorize the copy of the tridiagonal matrix A
      Call zpttrf(n, df, ef, info)

      If (info==0) Then

!       Solve the equations AX = B
        Call zpttrs('Lower', n, nrhs, df, ef, x, ldx, info)

!       Improve the solution and compute error estimates
        Call zptrfs('Lower', n, nrhs, d, e, df, ef, b, ldb, x, ldx, ferr, &
          berr, work, rwork, info)

!       Print the solution and the forward and backward error estimates

!       ifail: behaviour on error exit
!              =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
        ifail = 0
        Call nagf_file_print_matrix_complex_gen_comp('General', ' ', n, nrhs, &
          x, ldx, 'Bracketed', 'F7.4', 'Solution(s)', 'Integer', rlabs, &
          'Integer', clabs, 80, 0, ifail)

        Write (nout, *)
        Write (nout, *) 'Backward errors (machine-dependent)'
        Write (nout, 100) berr(1:nrhs)
        Write (nout, *)
        Write (nout, *) 'Estimated forward error bounds (machine-dependent)'
        Write (nout, 100) ferr(1:nrhs)
      Else
        Write (nout, 110) 'The leading minor of order ', info, &
          ' is not positive definite'
      End If

100   Format ((3X,1P,7E11.1))
110   Format (1X, A, I3, A)
    End Program
Full documentation of ZPTRFS


ZPTTRF example

Computational Routines: Computes the L * D * L' factorization of a complex Hermitian positive-definite tridiagonal matrix

Data

ZPTTRF Example Program Data
    4                                                    :Value of N
   16.0          41.0          46.0          21.0        :End of diagonal D
 ( 16.0, 16.0) ( 18.0, -9.0) (  1.0, -4.0)               :End of sub-diagonal E

Result

 ZPTTRF Example Program Results

 Details of factorization

  The diagonal elements of D
   16.0000   9.0000   1.0000   4.0000

  Subdiagonal elements of the Cholesky factor L
    1.0000   1.0000   2.0000  -1.0000   1.0000  -4.0000

Source

    Program zpttrf_example

!     ZPTTRF Example Program Text

!     Copyright 2017, Numerical Algorithms Group Ltd. http://www.nag.com

!     .. Use Statements ..
      Use lapack_interfaces, Only: zpttrf
      Use lapack_precision, Only: dp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter :: nin = 5, nout = 6
!     .. Local Scalars ..
      Integer :: info, n
!     .. Local Arrays ..
      Complex (Kind=dp), Allocatable :: e(:)
      Real (Kind=dp), Allocatable :: d(:)
!     .. Executable Statements ..
      Write (nout, *) 'ZPTTRF Example Program Results'
      Write (nout, *)
!     Skip heading in data file
      Read (nin, *)
      Read (nin, *) n

      Allocate (e(n-1), d(n))

!     Read the lower bidiagonal part of the tridiagonal matrix A from
!     data file

      Read (nin, *) d(1:n)
      Read (nin, *) e(1:n-1)

!     Factorize the tridiagonal matrix A
      Call zpttrf(n, d, e, info)

      If (info>0) Then
        Write (nout, 100) 'The leading minor of order ', info, &
          ' is not positive definite'
      End If

!     Print details of the factorization

      Write (nout, *) 'Details of factorization'
      Write (nout, *)
      Write (nout, *) ' The diagonal elements of D'
      Write (nout, 110) d(1:n)
      Write (nout, *)
      Write (nout, *) ' Subdiagonal elements of the Cholesky factor L'
      Write (nout, 110) e(1:n-1)

100   Format (1X, A, I3, A)
110   Format (1X, 8F9.4)
    End Program
Full documentation of ZPTTRF


ZPTTRS example

Computational Routines: Solves a complex Hermitian positive-definite tridiagonal system using the L * D * L' factorization computed by ZPTTRF

Data

ZPTTRS Example Program Data
    4             2                                      :Values of N and NRHS
               ( 16.0,-16.0) ( 18.0,  9.0) (  1.0,  4.0) :End of superdiagonal E
   16.0          41.0          46.0          21.0        :End of diagonal D
 ( 64.0, 16.0) (-16.0,-32.0)
 ( 93.0, 62.0) ( 61.0,-66.0)
 ( 78.0,-80.0) ( 71.0,-74.0)
 ( 14.0,-27.0) ( 35.0, 15.0)                             :End of matrix B

Result

 ZPTTRS Example Program Results

 Solution(s)
                            1                         2
 1  (     2.0000,     1.0000) (    -3.0000,    -2.0000)
 2  (     1.0000,     1.0000) (     1.0000,     1.0000)
 3  (     1.0000,    -2.0000) (     1.0000,    -2.0000)
 4  (     1.0000,    -1.0000) (     2.0000,     1.0000)

Source

    Program zpttrs_example

!     ZPTTRS Example Program Text

!     Copyright 2017, Numerical Algorithms Group Ltd. http://www.nag.com

!     .. Use Statements ..
      Use lapack_example_aux, Only: nagf_file_print_matrix_complex_gen_comp
      Use lapack_interfaces, Only: zpttrf, zpttrs
      Use lapack_precision, Only: dp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter :: nin = 5, nout = 6
      Character (1), Parameter :: uplo = 'U'
!     .. Local Scalars ..
      Integer :: i, ifail, info, ldb, n, nrhs
!     .. Local Arrays ..
      Complex (Kind=dp), Allocatable :: b(:, :), e(:)
      Real (Kind=dp), Allocatable :: d(:)
      Character (1) :: clabs(1), rlabs(1)
!     .. Executable Statements ..
      Write (nout, *) 'ZPTTRS Example Program Results'
      Write (nout, *)
      Flush (nout)
!     Skip heading in data file
      Read (nin, *)
      Read (nin, *) n, nrhs
      ldb = n
      Allocate (b(ldb,nrhs), e(n-1), d(n))

!     Read the upper bidiagonal part of the tridiagonal matrix A from
!     data file

      Read (nin, *) e(1:n-1)
      Read (nin, *) d(1:n)

!     Read the right hand matrix B

      Read (nin, *)(b(i,1:nrhs), i=1, n)

!     Factorize the tridiagonal matrix A
      Call zpttrf(n, d, e, info)

      If (info==0) Then

!       Solve the equations AX = B
        Call zpttrs(uplo, n, nrhs, d, e, b, ldb, info)

!       Print the solution

!       ifail: behaviour on error exit
!              =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
        ifail = 0
        Call nagf_file_print_matrix_complex_gen_comp('General', ' ', n, nrhs, &
          b, ldb, 'Bracketed', ' ', 'Solution(s)', 'Integer', rlabs, &
          'Integer', clabs, 80, 0, ifail)

      Else
        Write (nout, 100) 'The leading minor of order ', info, &
          ' is not positive definite'
      End If

100   Format (1X, A, I3, A)
    End Program
Full documentation of ZPTTRS


ZSPCON example

Computational Routines: Estimate condition number of complex symmetric matrix, matrix already factorized by ZSPTRF, packed storage

Data

ZSPCON Example Program Data
  4                                                       :Value of N
  'L'                                                     :Value of UPLO
 (-0.39,-0.71)
 ( 5.14,-0.64) ( 8.86, 1.81)
 (-7.86,-2.96) (-3.52, 0.58) (-2.83,-0.03)
 ( 3.80, 0.92) ( 5.32,-1.59) (-1.54,-2.86) (-0.56, 0.12)  :End of matrix A

Result

 ZSPCON Example Program Results

 Estimate of condition number =  2.06E+01

Source

    Program zspcon_example

!     ZSPCON Example Program Text

!     Copyright 2017, Numerical Algorithms Group Ltd. http://www.nag.com

!     .. Use Statements ..
      Use lapack_interfaces, Only: zlansp, zspcon, zsptrf
      Use lapack_precision, Only: dp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=dp) :: anorm, rcond
      Integer :: i, info, j, n
      Character (1) :: uplo
!     .. Local Arrays ..
      Complex (Kind=dp), Allocatable :: ap(:), work(:)
      Real (Kind=dp), Allocatable :: rwork(:)
      Integer, Allocatable :: ipiv(:)
!     .. Intrinsic Procedures ..
      Intrinsic :: epsilon
!     .. Executable Statements ..
      Write (nout, *) 'ZSPCON Example Program Results'
!     Skip heading in data file
      Read (nin, *)
      Read (nin, *) n

      Allocate (ap(n*(n+1)/2), work(2*n), rwork(n), ipiv(n))

!     Read A from data file

      Read (nin, *) uplo
      If (uplo=='U') Then
        Read (nin, *)((ap(i+j*(j-1)/2),j=i,n), i=1, n)
      Else If (uplo=='L') Then
        Read (nin, *)((ap(i+(2*n-j)*(j-1)/2),j=1,i), i=1, n)
      End If

!     Compute norm of A
      anorm = zlansp('1-norm', uplo, n, ap, rwork)

!     Factorize A
      Call zsptrf(uplo, n, ap, ipiv, info)

      Write (nout, *)
      If (info==0) Then

!       Estimate condition number
        Call zspcon(uplo, n, ap, ipiv, anorm, rcond, work, info)

        If (rcond>=epsilon(1.0E0_dp)) Then
          Write (nout, 100) 'Estimate of condition number =', 1.0E0_dp/rcond
        Else
          Write (nout, *) 'A is singular to working precision'
        End If
      Else
        Write (nout, *) 'The factor D is singular'
      End If

100   Format (1X, A, 1P, E10.2)
    End Program
Full documentation of ZSPCON


ZSPRFS example

Computational Routines: Refined solution with error bounds of complex symmetric system of linear equations, multiple right-hand sides, packed storage

Data

ZSPRFS Example Program Data
  4  2                                                    :Values of N and NRHS
  'L'                                                     :Value of UPLO
 (-0.39,-0.71)
 ( 5.14,-0.64) ( 8.86, 1.81)
 (-7.86,-2.96) (-3.52, 0.58) (-2.83,-0.03)
 ( 3.80, 0.92) ( 5.32,-1.59) (-1.54,-2.86) (-0.56, 0.12)  :End of matrix A
 (-55.64, 41.22) (-19.09,-35.97)
 (-48.18, 66.00) (-12.08,-27.02)
 ( -0.49, -1.47) (  6.95, 20.49)
 ( -6.43, 19.24) ( -4.59,-35.53)                          :End of matrix B

Result

 ZSPRFS Example Program Results

 Solution(s)
                    1                 2
 1  ( 1.0000,-1.0000) (-2.0000,-1.0000)
 2  (-2.0000, 5.0000) ( 1.0000,-3.0000)
 3  ( 3.0000,-2.0000) ( 3.0000, 2.0000)
 4  (-4.0000, 3.0000) (-1.0000, 1.0000)

 Backward errors (machine-dependent)
         8.9E-17           7.3E-17
 Estimated forward error bounds (machine-dependent)
         1.2E-14           1.2E-14

Source

    Program zsprfs_example

!     ZSPRFS Example Program Text

!     Copyright 2017, Numerical Algorithms Group Ltd. http://www.nag.com

!     .. Use Statements ..
      Use lapack_example_aux, Only: nagf_file_print_matrix_complex_gen_comp
      Use lapack_interfaces, Only: zsprfs, zsptrf, zsptrs
      Use lapack_precision, Only: dp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter :: nin = 5, nout = 6
!     .. Local Scalars ..
      Integer :: aplen, i, ifail, info, j, ldb, ldx, n, nrhs
      Character (1) :: uplo
!     .. Local Arrays ..
      Complex (Kind=dp), Allocatable :: afp(:), ap(:), b(:, :), work(:), &
        x(:, :)
      Real (Kind=dp), Allocatable :: berr(:), ferr(:), rwork(:)
      Integer, Allocatable :: ipiv(:)
      Character (1) :: clabs(1), rlabs(1)
!     .. Executable Statements ..
      Write (nout, *) 'ZSPRFS Example Program Results'
!     Skip heading in data file
      Read (nin, *)
      Read (nin, *) n, nrhs
      ldb = n
      ldx = n
      aplen = n*(n+1)/2
      Allocate (afp(aplen), ap(aplen), b(ldb,nrhs), work(2*n), x(ldx,n), &
        berr(nrhs), ferr(nrhs), rwork(n), ipiv(n))

!     Read A and B from data file, and copy A to AFP and B to X

      Read (nin, *) uplo
      If (uplo=='U') Then
        Read (nin, *)((ap(i+j*(j-1)/2),j=i,n), i=1, n)
      Else If (uplo=='L') Then
        Read (nin, *)((ap(i+(2*n-j)*(j-1)/2),j=1,i), i=1, n)
      End If
      Read (nin, *)(b(i,1:nrhs), i=1, n)

      afp(1:aplen) = ap(1:aplen)
      x(1:n, 1:nrhs) = b(1:n, 1:nrhs)

!     Factorize A in the array AFP
      Call zsptrf(uplo, n, afp, ipiv, info)

      Write (nout, *)
      Flush (nout)
      If (info==0) Then

!       Compute solution in the array X
        Call zsptrs(uplo, n, nrhs, afp, ipiv, x, ldx, info)

!       Improve solution, and compute backward errors and
!       estimated bounds on the forward errors

        Call zsprfs(uplo, n, nrhs, ap, afp, ipiv, b, ldb, x, ldx, ferr, berr, &
          work, rwork, info)

!       Print solution

!       ifail: behaviour on error exit
!              =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
        ifail = 0
        Call nagf_file_print_matrix_complex_gen_comp('General', ' ', n, nrhs, &
          x, ldx, 'Bracketed', 'F7.4', 'Solution(s)', 'Integer', rlabs, &
          'Integer', clabs, 80, 0, ifail)

        Write (nout, *)
        Write (nout, *) 'Backward errors (machine-dependent)'
        Write (nout, 100) berr(1:nrhs)
        Write (nout, *) 'Estimated forward error bounds (machine-dependent)'
        Write (nout, 100) ferr(1:nrhs)
      Else
        Write (nout, *) 'The factor D is singular'
      End If

100   Format ((5X,1P,4(E11.1,7X)))
    End Program
Full documentation of ZSPRFS


ZSPTRF example

Computational Routines: Bunch-Kaufman factorization of complex symmetric matrix, packed storage

Data

ZSPTRF Example Program Data
  4                                                       :Value of N
  'L'                                                     :Value of UPLO
 (-0.39,-0.71)
 ( 5.14,-0.64) ( 8.86, 1.81)
 (-7.86,-2.96) (-3.52, 0.58) (-2.83,-0.03)
 ( 3.80, 0.92) ( 5.32,-1.59) (-1.54,-2.86) (-0.56, 0.12)  :End of matrix A

Result

 ZSPTRF Example Program Results

 Details of factorization
                    1                 2                 3                 4
 1  (-0.3900,-0.7100)
 2  (-7.8600,-2.9600) (-2.8300,-0.0300)
 3  ( 0.5279,-0.3715) (-0.6078, 0.2811) ( 4.4079, 5.3991)
 4  ( 0.4426, 0.1936) (-0.4823, 0.0150) (-0.1071,-0.3157) (-2.0954,-2.2011)

 IPIV
           -3                -3                 3                 4

Source

    Program zsptrf_example

!     ZSPTRF Example Program Text

!     Copyright 2017, Numerical Algorithms Group Ltd. http://www.nag.com

!     .. Use Statements ..
      Use lapack_example_aux, Only: nagf_file_print_matrix_complex_packed_comp
      Use lapack_interfaces, Only: zsptrf
      Use lapack_precision, Only: dp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter :: nin = 5, nout = 6
!     .. Local Scalars ..
      Integer :: i, ifail, info, j, n
      Character (1) :: uplo
!     .. Local Arrays ..
      Complex (Kind=dp), Allocatable :: ap(:)
      Integer, Allocatable :: ipiv(:)
      Character (1) :: clabs(1), rlabs(1)
!     .. Executable Statements ..
      Write (nout, *) 'ZSPTRF Example Program Results'
!     Skip heading in data file
      Read (nin, *)
      Read (nin, *) n

      Allocate (ap(n*(n+1)/2), ipiv(n))

!     Read A from data file

      Read (nin, *) uplo
      If (uplo=='U') Then
        Read (nin, *)((ap(i+j*(j-1)/2),j=i,n), i=1, n)
      Else If (uplo=='L') Then
        Read (nin, *)((ap(i+(2*n-j)*(j-1)/2),j=1,i), i=1, n)
      End If

!     Factorize A
      Call zsptrf(uplo, n, ap, ipiv, info)

      Write (nout, *)
      Flush (nout)

!     Print details of factorization

!     ifail: behaviour on error exit
!            =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
      ifail = 0
      Call nagf_file_print_matrix_complex_packed_comp(uplo, 'Nonunit', n, ap, &
        'Bracketed', 'F7.4', 'Details of factorization', 'Integer', rlabs, &
        'Integer', clabs, 80, 0, ifail)

!     Print pivot indices

      Write (nout, *)
      Write (nout, *) 'IPIV'
      Write (nout, 100) ipiv(1:n)

      If (info/=0) Then
        Write (nout, *) 'The factor D is singular'
      End If

100   Format ((1X,I12,3I18))
    End Program
Full documentation of ZSPTRF


ZSPTRI example

Computational Routines: Inverse of complex symmetric matrix, matrix already factorized by ZSPTRF, packed storage

Data

ZSPTRI Example Program Data
  4                                                       :Value of N
  'L'                                                     :Value of UPLO
 (-0.39,-0.71)
 ( 5.14,-0.64) ( 8.86, 1.81)
 (-7.86,-2.96) (-3.52, 0.58) (-2.83,-0.03)
 ( 3.80, 0.92) ( 5.32,-1.59) (-1.54,-2.86) (-0.56, 0.12)  :End of matrix A

Result

 ZSPTRI Example Program Results

 Inverse
                    1                 2                 3                 4
 1  (-0.1562,-0.1014)
 2  ( 0.0400, 0.1527) ( 0.0946,-0.1475)
 3  ( 0.0550, 0.0845) (-0.0326,-0.1370) (-0.1320,-0.0102)
 4  ( 0.2162,-0.0742) (-0.0995,-0.0461) (-0.1793, 0.1183) (-0.2269, 0.2383)

Source

    Program zsptri_example

!     ZSPTRI Example Program Text

!     Copyright 2017, Numerical Algorithms Group Ltd. http://www.nag.com

!     .. Use Statements ..
      Use lapack_example_aux, Only: nagf_file_print_matrix_complex_packed_comp
      Use lapack_interfaces, Only: zsptrf, zsptri
      Use lapack_precision, Only: dp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter :: nin = 5, nout = 6
!     .. Local Scalars ..
      Integer :: i, ifail, info, j, n
      Character (1) :: uplo
!     .. Local Arrays ..
      Complex (Kind=dp), Allocatable :: ap(:), work(:)
      Integer, Allocatable :: ipiv(:)
      Character (1) :: clabs(1), rlabs(1)
!     .. Executable Statements ..
      Write (nout, *) 'ZSPTRI Example Program Results'
!     Skip heading in data file
      Read (nin, *)
      Read (nin, *) n

      Allocate (ap(n*(n+1)/2), work(n), ipiv(n))

!     Read A from data file

      Read (nin, *) uplo
      If (uplo=='U') Then
        Read (nin, *)((ap(i+j*(j-1)/2),j=i,n), i=1, n)
      Else If (uplo=='L') Then
        Read (nin, *)((ap(i+(2*n-j)*(j-1)/2),j=1,i), i=1, n)
      End If

!     Factorize A
      Call zsptrf(uplo, n, ap, ipiv, info)

      Write (nout, *)
      Flush (nout)
      If (info==0) Then

!       Compute inverse of A
        Call zsptri(uplo, n, ap, ipiv, work, info)

!       Print inverse

!       ifail: behaviour on error exit
!              =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
        ifail = 0
        Call nagf_file_print_matrix_complex_packed_comp(uplo, 'Nonunit', n, &
          ap, 'Bracketed', 'F7.4', 'Inverse', 'Integer', rlabs, 'Integer', &
          clabs, 80, 0, ifail)

      Else
        Write (nout, *) 'The factor D is singular'
      End If

    End Program
Full documentation of ZSPTRI


ZSPTRS example

Computational Routines: Solution of complex symmetric system of linear equations, multiple right-hand sides, matrix already factorized by ZSPTRF, packed storage

Data

ZSPTRS Example Program Data
  4  2                                                    :Values of N and NRHS
  'L'                                                     :Value of UPLO
 (-0.39,-0.71)
 ( 5.14,-0.64) ( 8.86, 1.81)
 (-7.86,-2.96) (-3.52, 0.58) (-2.83,-0.03)
 ( 3.80, 0.92) ( 5.32,-1.59) (-1.54,-2.86) (-0.56, 0.12)  :End of matrix A
 (-55.64, 41.22) (-19.09,-35.97)
 (-48.18, 66.00) (-12.08,-27.02)
 ( -0.49, -1.47) (  6.95, 20.49)
 ( -6.43, 19.24) ( -4.59,-35.53)                          :End of matrix B

Result

 ZSPTRS Example Program Results

 Solution(s)
                    1                 2
 1  ( 1.0000,-1.0000) (-2.0000,-1.0000)
 2  (-2.0000, 5.0000) ( 1.0000,-3.0000)
 3  ( 3.0000,-2.0000) ( 3.0000, 2.0000)
 4  (-4.0000, 3.0000) (-1.0000, 1.0000)

Source

    Program zsptrs_example

!     ZSPTRS Example Program Text

!     Copyright 2017, Numerical Algorithms Group Ltd. http://www.nag.com

!     .. Use Statements ..
      Use lapack_example_aux, Only: nagf_file_print_matrix_complex_gen_comp
      Use lapack_interfaces, Only: zsptrf, zsptrs
      Use lapack_precision, Only: dp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter :: nin = 5, nout = 6
!     .. Local Scalars ..
      Integer :: i, ifail, info, j, ldb, n, nrhs
      Character (1) :: uplo
!     .. Local Arrays ..
      Complex (Kind=dp), Allocatable :: ap(:), b(:, :)
      Integer, Allocatable :: ipiv(:)
      Character (1) :: clabs(1), rlabs(1)
!     .. Executable Statements ..
      Write (nout, *) 'ZSPTRS Example Program Results'
!     Skip heading in data file
      Read (nin, *)
      Read (nin, *) n, nrhs
      ldb = n
      Allocate (ap(n*(n+1)/2), b(ldb,nrhs), ipiv(n))

!     Read A and B from data file

      Read (nin, *) uplo
      If (uplo=='U') Then
        Read (nin, *)((ap(i+j*(j-1)/2),j=i,n), i=1, n)
      Else If (uplo=='L') Then
        Read (nin, *)((ap(i+(2*n-j)*(j-1)/2),j=1,i), i=1, n)
      End If
      Read (nin, *)(b(i,1:nrhs), i=1, n)

!     Factorize A
      Call zsptrf(uplo, n, ap, ipiv, info)

      Write (nout, *)
      Flush (nout)
      If (info==0) Then

!       Compute solution
        Call zsptrs(uplo, n, nrhs, ap, ipiv, b, ldb, info)

!       Print solution

!       ifail: behaviour on error exit
!              =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
        ifail = 0
        Call nagf_file_print_matrix_complex_gen_comp('General', ' ', n, nrhs, &
          b, ldb, 'Bracketed', 'F7.4', 'Solution(s)', 'Integer', rlabs, &
          'Integer', clabs, 80, 0, ifail)

      Else
        Write (nout, *) 'The factor D is singular'
      End If

    End Program
Full documentation of ZSPTRS


ZSTEDC example

Computational Routines: Computes all eigenvalues and, optionally, eigenvectors of a real symmetric tridiagonal matrix or a complex Hermitian matrix reduced to this form (divide-and-conquer)

Data

ZSTEDC Example Program Data

    4               2                                      :Values of N and KD

 ( -3.13 , 0.00) (  1.94, -2.10) ( -3.40,  0.25)
                 ( -1.91,  0.00) ( -0.82, -0.89) ( -0.67,  0.34)
                                 ( -2.87,  0.00) ( -2.10, -0.16)
                                                 (  0.50,  0.00) :End matrix A

Result

 ZSTEDC Example Program Results

 Eigenvalues
     -7.0042           -4.0038            0.5968            3.0012

 Eigenvectors
                    1                 2                 3                 4
 1  ( 0.7293, 0.0000) (-0.2128, 0.1511) (-0.3354,-0.1604) (-0.5114,-0.0163)
 2  (-0.1654,-0.2046) ( 0.7316, 0.0000) (-0.2804,-0.3413) (-0.2374,-0.3796)
 3  ( 0.6081, 0.0301) ( 0.3910,-0.3843) (-0.0144, 0.1532) ( 0.5523,-0.0000)
 4  ( 0.1653,-0.0303) ( 0.2775,-0.1378) ( 0.8019, 0.0000) (-0.4517, 0.1693)

Source

    Program zstedc_example

!     ZSTEDC Example Program Text

!     Copyright 2017, Numerical Algorithms Group Ltd. http://www.nag.com

!     .. Use Statements ..
      Use blas_interfaces, Only: dznrm2
      Use lapack_example_aux, Only: nagf_file_print_matrix_complex_gen_comp
      Use lapack_interfaces, Only: zhbtrd, zstedc
      Use lapack_precision, Only: dp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter :: nin = 5, nout = 6
      Character (1), Parameter :: uplo = 'U'
!     .. Local Scalars ..
      Complex (Kind=dp) :: scal
      Integer :: i, ifail, info, j, k, kd, ldab, ldz, lgn, liwork, lrwork, &
        lwork, n
!     .. Local Arrays ..
      Complex (Kind=dp), Allocatable :: ab(:, :), work(:), z(:, :)
      Complex (Kind=dp) :: cdum(1)
      Real (Kind=dp), Allocatable :: d(:), e(:), rwork(:)
      Real (Kind=dp) :: rdum(1)
      Integer :: idum(1)
      Integer, Allocatable :: iwork(:)
      Character (1) :: clabs(1), rlabs(1)
!     .. Intrinsic Procedures ..
      Intrinsic :: abs, ceiling, conjg, log, max, maxloc, min, nint, real
!     .. Executable Statements ..
      Write (nout, *) 'ZSTEDC Example Program Results'
      Write (nout, *)
!     Skip heading in data file
      Read (nin, *)
      Read (nin, *) n, kd
      ldab = kd + 1
      ldz = n
      lgn = ceiling(log(real(n,kind=dp))/log(2.0_dp))
      Allocate (ab(ldab,n), z(ldz,n), d(n), e(n-1))

!     Use routine workspace query to get optimal workspace.
      lwork = -1
      lrwork = -1
      liwork = -1
      Call zstedc('V', n, d, e, z, ldz, cdum, lwork, rdum, lrwork, idum, &
        liwork, info)

!     Make sure that there is enough workspace.
      lwork = max(n*n, nint(real(cdum(1))))
      lrwork = max(1+3*n+2*n*lgn+4*n*n, nint(rdum(1)))
      liwork = max(6+6*n+5*n*lgn, idum(1))
      Allocate (work(lwork), rwork(lrwork), iwork(liwork))

!     Read the upper or lower triangular part of the band matrix A
!     from data file

      If (uplo=='U') Then
        Do i = 1, n
          Read (nin, *)(ab(kd+1+i-j,j), j=i, min(n,i+kd))
        End Do
      Else If (uplo=='L') Then
        Do i = 1, n
          Read (nin, *)(ab(1+i-j,j), j=max(1,i-kd), i)
        End Do
      End If

!     Reduce A to tridiagonal form T = (Z**T)*A*Z, and form Z

      Call zhbtrd('V', uplo, n, kd, ab, ldab, d, e, z, ldz, work, info)

!     Calculate all the eigenvalues and eigenvectors of A,
!     from T and Z

      Call zstedc('V', n, d, e, z, ldz, work, lwork, rwork, lrwork, iwork, &
        liwork, info)

      If (info==0) Then

!       Print eigenvalues and eigenvectors

        Write (nout, *) 'Eigenvalues'
        Write (nout, 100) d(1:n)

        Write (nout, *)
        Flush (nout)

!       Normalize the eigenvectors, largest element real
        Do i = 1, n
          rwork(1:n) = abs(z(1:n,i))
          k = maxloc(rwork(1:n), 1)
          scal = conjg(z(k,i))/abs(z(k,i))/dznrm2(n, z(1,i), 1)
          z(1:n, i) = z(1:n, i)*scal
        End Do

!       ifail: behaviour on error exit
!              =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
        ifail = 0
        Call nagf_file_print_matrix_complex_gen_comp('General', ' ', n, n, z, &
          ldz, 'Bracketed', 'F7.4', 'Eigenvectors', 'Integer', rlabs, &
          'Integer', clabs, 80, 0, ifail)

      Else
        Write (nout, 110) 'Failure in ZSTEDC. INFO = ', info
      End If

100   Format (4X, F8.4, 3(10X,F8.4))
110   Format (1X, A, I10)
    End Program
Full documentation of ZSTEDC


ZSTEGR example

Computational Routines: Computes all eigenvalues and, optionally, eigenvectors of a real symmetric tridiagonal matrix or a complex Hermitian matrix reduced to this form (Relatively Robust Representations)

Data

ZSTEGR Example Program Data

  4                    :Value of N

  1.0  4.0  9.0  16.0  :End of D
  1.0  2.0  3.0        :End of E

  'V'                  :Value of JOBZ

Result

 ZSTEGR Example Program Results

 Eigenvalues
     0.6476  3.5470  8.6578 17.1477

Warning: Floating invalid operation occurred
Warning: Floating divide by zero occurred
Warning: Floating underflow occurred
 Eigenvectors
          1       2       3       4
 1   0.9396  0.3388  0.0494  0.0034
     0.0000  0.0000  0.0000  0.0000

 2  -0.3311  0.8628  0.3781  0.0545
    -0.0000  0.0000  0.0000  0.0000

 3   0.0853 -0.3648  0.8558  0.3568
     0.0000 -0.0000  0.0000  0.0000

 4  -0.0167  0.0879 -0.3497  0.9326
    -0.0000  0.0000 -0.0000  0.0000

Source

    Program zstegr_example

!     ZSTEGR Example Program Text

!     Copyright 2017, Numerical Algorithms Group Ltd. http://www.nag.com

!     .. Use Statements ..
      Use lapack_example_aux, Only: nagf_file_print_matrix_complex_gen
      Use lapack_interfaces, Only: zstegr
      Use lapack_precision, Only: dp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Real (Kind=dp), Parameter :: vl = 0.0E0_dp
      Real (Kind=dp), Parameter :: vu = 0.0E0_dp
      Integer, Parameter :: il = 0, iu = 0, nin = 5, nout = 6
      Character (1), Parameter :: range = 'A'
!     .. Local Scalars ..
      Real (Kind=dp) :: abstol
      Integer :: i, ifail, info, ldz, liwork, lwork, m, n
      Character (1) :: jobz
!     .. Local Arrays ..
      Complex (Kind=dp), Allocatable :: z(:, :)
      Real (Kind=dp), Allocatable :: d(:), e(:), w(:), work(:)
      Integer, Allocatable :: isuppz(:), iwork(:)
!     .. Intrinsic Procedures ..
      Intrinsic :: real
!     .. Executable Statements ..
      Write (nout, *) 'ZSTEGR Example Program Results'
      Write (nout, *)
!     Skip heading in data file
      Read (nin, *)
      Read (nin, *) n
      ldz = n
      liwork = 10*n
      lwork = 18*n
      Allocate (z(ldz,n), d(n), e(n), w(n), work(lwork), isuppz(2*n), &
        iwork(liwork))

!     Read the symmetric tridiagonal matrix T from data file, first
!     the diagonal elements, then the off diagonal elements and then
!     JOBV ('N' - eigenvalues only, 'V' - vectors as well)

      Read (nin, *) d(1:n)
      Read (nin, *) e(1:n-1)
      Read (nin, *) jobz

!     Calculate all the eigenvalues of T. Set ABSTOL to zero so that
!     the default value is used.

      abstol = 0.0E0_dp
      Call zstegr(jobz, range, n, d, e, vl, vu, il, iu, abstol, m, w, z, ldz, &
        isuppz, work, lwork, iwork, liwork, info)

      If (info==0) Then

!       Print eigenvalues and eigenvectors

        Write (nout, *) 'Eigenvalues'
        Write (nout, 100) w(1:m)

        Write (nout, *)
        Flush (nout)

!       Standardize the eigenvectors so that first elements are non-negative.
        Do i = 1, m
          If (real(z(1,i))<0.0_dp) Then
            z(1:n, i) = -z(1:n, i)
          End If
        End Do

!       ifail: behaviour on error exit
!              =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
        ifail = 0
        Call nagf_file_print_matrix_complex_gen('General', ' ', n, m, z, ldz, &
          'Eigenvectors', ifail)

      Else
        Write (nout, 110) 'Failure to compute an eigenvalue, INFO = ', info
      End If

100   Format ((3X,8F8.4))
110   Format (1X, A, I10)
    End Program
Full documentation of ZSTEGR


ZSYCON example

Computational Routines: Estimate condition number of complex symmetric matrix, matrix already factorized by ZSYTRF

Data

ZSYCON Example Program Data
  4                                                       :Value of N
  'L'                                                     :Value of UPLO
 (-0.39,-0.71)
 ( 5.14,-0.64) ( 8.86, 1.81)
 (-7.86,-2.96) (-3.52, 0.58) (-2.83,-0.03)
 ( 3.80, 0.92) ( 5.32,-1.59) (-1.54,-2.86) (-0.56, 0.12)  :End of matrix A

Result

 ZSYCON Example Program Results

 Estimate of condition number =  2.06E+01

Source

    Program zsycon_example

!     ZSYCON Example Program Text

!     Copyright 2017, Numerical Algorithms Group Ltd. http://www.nag.com

!     .. Use Statements ..
      Use lapack_interfaces, Only: zlansy, zsycon, zsytrf
      Use lapack_precision, Only: dp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=dp) :: anorm, rcond
      Integer :: i, info, lda, lwork, n
      Character (1) :: uplo
!     .. Local Arrays ..
      Complex (Kind=dp), Allocatable :: a(:, :), work(:)
      Real (Kind=dp), Allocatable :: rwork(:)
      Integer, Allocatable :: ipiv(:)
!     .. Intrinsic Procedures ..
      Intrinsic :: epsilon
!     .. Executable Statements ..
      Write (nout, *) 'ZSYCON Example Program Results'
!     Skip heading in data file
      Read (nin, *)
      Read (nin, *) n
      lda = n
      lwork = 64*n
      Allocate (a(lda,n), work(lwork), rwork(n), ipiv(n))

!     Read A from data file

      Read (nin, *) uplo
      If (uplo=='U') Then
        Read (nin, *)(a(i,i:n), i=1, n)
      Else If (uplo=='L') Then
        Read (nin, *)(a(i,1:i), i=1, n)
      End If

!     Compute norm of A
      anorm = zlansy('1-norm', uplo, n, a, lda, rwork)

!     Factorize A
      Call zsytrf(uplo, n, a, lda, ipiv, work, lwork, info)

      Write (nout, *)
      If (info==0) Then

!       Estimate condition number
        Call zsycon(uplo, n, a, lda, ipiv, anorm, rcond, work, info)

        If (rcond>=epsilon(1.0E0_dp)) Then
          Write (nout, 100) 'Estimate of condition number =', 1.0_dp/rcond
        Else
          Write (nout, *) 'A is singular to working precision'
        End If
      Else
        Write (nout, *) 'The factor D is singular'
      End If

100   Format (1X, A, 1P, E10.2)
    End Program
Full documentation of ZSYCON


ZSYRFS example

Computational Routines: Refined solution with error bounds of complex symmetric system of linear equations, multiple right-hand sides

Data

ZSYRFS Example Program Data
  4  2                                                    :Values of N and NRHS
  'L'                                                     :Value of UPLO
 (-0.39,-0.71)
 ( 5.14,-0.64) ( 8.86, 1.81)
 (-7.86,-2.96) (-3.52, 0.58) (-2.83,-0.03)
 ( 3.80, 0.92) ( 5.32,-1.59) (-1.54,-2.86) (-0.56, 0.12)  :End of matrix A
 (-55.64, 41.22) (-19.09,-35.97)
 (-48.18, 66.00) (-12.08,-27.02)
 ( -0.49, -1.47) (  6.95, 20.49)
 ( -6.43, 19.24) ( -4.59,-35.53)                          :End of matrix B

Result

 ZSYRFS Example Program Results

 Solution(s)
                    1                 2
 1  ( 1.0000,-1.0000) (-2.0000,-1.0000)
 2  (-2.0000, 5.0000) ( 1.0000,-3.0000)
 3  ( 3.0000,-2.0000) ( 3.0000, 2.0000)
 4  (-4.0000, 3.0000) (-1.0000, 1.0000)

 Backward errors (machine-dependent)
         8.9E-17           7.3E-17
 Estimated forward error bounds (machine-dependent)
         1.2E-14           1.2E-14

Source

    Program zsyrfs_example

!     ZSYRFS Example Program Text

!     Copyright 2017, Numerical Algorithms Group Ltd. http://www.nag.com

!     .. Use Statements ..
      Use lapack_example_aux, Only: nagf_file_print_matrix_complex_gen_comp
      Use lapack_interfaces, Only: zlacpy, zsyrfs, zsytrf, zsytrs
      Use lapack_precision, Only: dp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter :: nin = 5, nout = 6
!     .. Local Scalars ..
      Integer :: i, ifail, info, lda, ldaf, ldb, ldx, lwork, n, nrhs
      Character (1) :: uplo
!     .. Local Arrays ..
      Complex (Kind=dp), Allocatable :: a(:, :), af(:, :), b(:, :), work(:), &
        x(:, :)
      Real (Kind=dp), Allocatable :: berr(:), ferr(:), rwork(:)
      Integer, Allocatable :: ipiv(:)
      Character (1) :: clabs(1), rlabs(1)
!     .. Executable Statements ..
      Write (nout, *) 'ZSYRFS Example Program Results'
!     Skip heading in data file
      Read (nin, *)
      Read (nin, *) n, nrhs
      lda = n
      ldaf = n
      ldb = n
      ldx = n
      lwork = 64*n
      Allocate (a(lda,n), af(ldaf,n), b(ldb,nrhs), work(lwork), x(ldx,n), &
        berr(nrhs), ferr(nrhs), rwork(n), ipiv(n))

!     Read A and B from data file, and copy A to AF and B to X

      Read (nin, *) uplo
      If (uplo=='U') Then
        Read (nin, *)(a(i,i:n), i=1, n)
      Else If (uplo=='L') Then
        Read (nin, *)(a(i,1:i), i=1, n)
      End If
      Read (nin, *)(b(i,1:nrhs), i=1, n)
      Call zlacpy(uplo, n, n, a, lda, af, ldaf)
      x(1:n, 1:nrhs) = b(1:n, 1:nrhs)

!     Factorize A in the array AF
      Call zsytrf(uplo, n, af, ldaf, ipiv, work, lwork, info)

      Write (nout, *)
      Flush (nout)
      If (info==0) Then

!       Compute solution in the array X
        Call zsytrs(uplo, n, nrhs, af, ldaf, ipiv, x, ldx, info)

!       Improve solution, and compute backward errors and
!       estimated bounds on the forward errors

        Call zsyrfs(uplo, n, nrhs, a, lda, af, ldaf, ipiv, b, ldb, x, ldx, &
          ferr, berr, work, rwork, info)

!       Print solution

!       ifail: behaviour on error exit
!              =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
        ifail = 0
        Call nagf_file_print_matrix_complex_gen_comp('General', ' ', n, nrhs, &
          x, ldx, 'Bracketed', 'F7.4', 'Solution(s)', 'Integer', rlabs, &
          'Integer', clabs, 80, 0, ifail)

        Write (nout, *)
        Write (nout, *) 'Backward errors (machine-dependent)'
        Write (nout, 100) berr(1:nrhs)
        Write (nout, *) 'Estimated forward error bounds (machine-dependent)'
        Write (nout, 100) ferr(1:nrhs)
      Else
        Write (nout, *) 'The factor D is singular'
      End If

100   Format ((5X,1P,4(E11.1,7X)))
    End Program
Full documentation of ZSYRFS


ZSYTRF example

Computational Routines: Bunch-Kaufman factorization of complex symmetric matrix

Data

ZSYTRF Example Program Data
  4                                                       :Value of N
  'L'                                                     :Value of UPLO
 (-0.39,-0.71)
 ( 5.14,-0.64) ( 8.86, 1.81)
 (-7.86,-2.96) (-3.52, 0.58) (-2.83,-0.03)
 ( 3.80, 0.92) ( 5.32,-1.59) (-1.54,-2.86) (-0.56, 0.12)  :End of matrix A

Result

 ZSYTRF Example Program Results

 Details of factorization
                    1                 2                 3                 4
 1  (-0.3900,-0.7100)
 2  (-7.8600,-2.9600) (-2.8300,-0.0300)
 3  ( 0.5279,-0.3715) (-0.6078, 0.2811) ( 4.4079, 5.3991)
 4  ( 0.4426, 0.1936) (-0.4823, 0.0150) (-0.1071,-0.3157) (-2.0954,-2.2011)

 IPIV
           -3                -3                 3                 4

Source

    Program zsytrf_example

!     ZSYTRF Example Program Text

!     Copyright 2017, Numerical Algorithms Group Ltd. http://www.nag.com

!     .. Use Statements ..
      Use lapack_example_aux, Only: nagf_file_print_matrix_complex_gen_comp
      Use lapack_interfaces, Only: zsytrf
      Use lapack_precision, Only: dp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter :: nin = 5, nout = 6
!     .. Local Scalars ..
      Integer :: i, ifail, info, lda, lwork, n
      Character (1) :: uplo
!     .. Local Arrays ..
      Complex (Kind=dp), Allocatable :: a(:, :), work(:)
      Integer, Allocatable :: ipiv(:)
      Character (1) :: clabs(1), rlabs(1)
!     .. Executable Statements ..
      Write (nout, *) 'ZSYTRF Example Program Results'
!     Skip heading in data file
      Read (nin, *)
      Read (nin, *) n
      lda = n
      lwork = 64*n
      Allocate (a(lda,n), work(lwork), ipiv(n))

!     Read A from data file

      Read (nin, *) uplo
      If (uplo=='U') Then
        Read (nin, *)(a(i,i:n), i=1, n)
      Else If (uplo=='L') Then
        Read (nin, *)(a(i,1:i), i=1, n)
      End If

!     Factorize A
      Call zsytrf(uplo, n, a, lda, ipiv, work, lwork, info)

      Write (nout, *)
      Flush (nout)

!     Print details of factorization

!     ifail: behaviour on error exit
!            =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
      ifail = 0
      Call nagf_file_print_matrix_complex_gen_comp(uplo, 'Nonunit', n, n, a, &
        lda, 'Bracketed', 'F7.4', 'Details of factorization', 'Integer', &
        rlabs, 'Integer', clabs, 80, 0, ifail)

!     Print pivot indices

      Write (nout, *)
      Write (nout, *) 'IPIV'
      Write (nout, 100) ipiv(1:n)

      If (info/=0) Then
        Write (nout, *) 'The factor D is singular'
      End If

100   Format ((1X,I12,3I18))
    End Program
Full documentation of ZSYTRF


ZSYTRI example

Computational Routines: Inverse of complex symmetric matrix, matrix already factorized by ZSYTRF

Data

ZSYTRI Example Program Data
  4                                                       :Value of N
  'L'                                                     :Value of UPLO
 (-0.39,-0.71)
 ( 5.14,-0.64) ( 8.86, 1.81)
 (-7.86,-2.96) (-3.52, 0.58) (-2.83,-0.03)
 ( 3.80, 0.92) ( 5.32,-1.59) (-1.54,-2.86) (-0.56, 0.12)  :End of matrix A

Result

 ZSYTRI Example Program Results

 Inverse
                    1                 2                 3                 4
 1  (-0.1562,-0.1014)
 2  ( 0.0400, 0.1527) ( 0.0946,-0.1475)
 3  ( 0.0550, 0.0845) (-0.0326,-0.1370) (-0.1320,-0.0102)
 4  ( 0.2162,-0.0742) (-0.0995,-0.0461) (-0.1793, 0.1183) (-0.2269, 0.2383)

Source

    Program zsytri_example

!     ZSYTRI Example Program Text

!     Copyright 2017, Numerical Algorithms Group Ltd. http://www.nag.com

!     .. Use Statements ..
      Use lapack_example_aux, Only: nagf_file_print_matrix_complex_gen_comp
      Use lapack_interfaces, Only: zsytrf, zsytri
      Use lapack_precision, Only: dp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter :: nin = 5, nout = 6
!     .. Local Scalars ..
      Integer :: i, ifail, info, lda, lwork, n
      Character (1) :: uplo
!     .. Local Arrays ..
      Complex (Kind=dp), Allocatable :: a(:, :), work(:)
      Integer, Allocatable :: ipiv(:)
      Character (1) :: clabs(1), rlabs(1)
!     .. Executable Statements ..
      Write (nout, *) 'ZSYTRI Example Program Results'
!     Skip heading in data file
      Read (nin, *)
      Read (nin, *) n
      lda = n
      lwork = 64*n
      Allocate (a(lda,n), work(lwork), ipiv(n))

!     Read A from data file

      Read (nin, *) uplo
      If (uplo=='U') Then
        Read (nin, *)(a(i,i:n), i=1, n)
      Else If (uplo=='L') Then
        Read (nin, *)(a(i,1:i), i=1, n)
      End If

!     Factorize A
      Call zsytrf(uplo, n, a, lda, ipiv, work, lwork, info)

      Write (nout, *)
      Flush (nout)
      If (info==0) Then

!       Compute inverse of A
        Call zsytri(uplo, n, a, lda, ipiv, work, info)

!       Print inverse

!       ifail: behaviour on error exit
!              =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
        ifail = 0
        Call nagf_file_print_matrix_complex_gen_comp(uplo, 'Nonunit', n, n, a, &
          lda, 'Bracketed', 'F7.4', 'Inverse', 'Integer', rlabs, 'Integer', &
          clabs, 80, 0, ifail)

      Else
        Write (nout, *) 'The factor D is singular'
      End If

    End Program
Full documentation of ZSYTRI


ZSYTRS example

Computational Routines: Solution of complex symmetric system of linear equations, multiple right-hand sides, matrix already factorized by ZSYTRF

Data

ZSYTRS Example Program Data
  4  2                                                    :Values of N and NRHS
  'L'                                                     :Value of UPLO
 (-0.39,-0.71)
 ( 5.14,-0.64) ( 8.86, 1.81)
 (-7.86,-2.96) (-3.52, 0.58) (-2.83,-0.03)
 ( 3.80, 0.92) ( 5.32,-1.59) (-1.54,-2.86) (-0.56, 0.12)  :End of matrix A
 (-55.64, 41.22) (-19.09,-35.97)
 (-48.18, 66.00) (-12.08,-27.02)
 ( -0.49, -1.47) (  6.95, 20.49)
 ( -6.43, 19.24) ( -4.59,-35.53)                          :End of matrix B

Result

 ZSYTRS Example Program Results

 Solution(s)
                    1                 2
 1  ( 1.0000,-1.0000) (-2.0000,-1.0000)
 2  (-2.0000, 5.0000) ( 1.0000,-3.0000)
 3  ( 3.0000,-2.0000) ( 3.0000, 2.0000)
 4  (-4.0000, 3.0000) (-1.0000, 1.0000)

Source

    Program zsytrs_example

!     ZSYTRS Example Program Text

!     Copyright 2017, Numerical Algorithms Group Ltd. http://www.nag.com

!     .. Use Statements ..
      Use lapack_example_aux, Only: nagf_file_print_matrix_complex_gen_comp
      Use lapack_interfaces, Only: zsytrf, zsytrs
      Use lapack_precision, Only: dp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter :: nin = 5, nout = 6
!     .. Local Scalars ..
      Integer :: i, ifail, info, lda, ldb, lwork, n, nrhs
      Character (1) :: uplo
!     .. Local Arrays ..
      Complex (Kind=dp), Allocatable :: a(:, :), b(:, :), work(:)
      Integer, Allocatable :: ipiv(:)
      Character (1) :: clabs(1), rlabs(1)
!     .. Executable Statements ..
      Write (nout, *) 'ZSYTRS Example Program Results'
!     Skip heading in data file
      Read (nin, *)
      Read (nin, *) n, nrhs
      lda = n
      ldb = n
      lwork = 64*n
      Allocate (a(lda,n), b(ldb,nrhs), work(lwork), ipiv(n))

!     Read A and B from data file

      Read (nin, *) uplo
      If (uplo=='U') Then
        Read (nin, *)(a(i,i:n), i=1, n)
      Else If (uplo=='L') Then
        Read (nin, *)(a(i,1:i), i=1, n)
      End If
      Read (nin, *)(b(i,1:nrhs), i=1, n)

!     Factorize A
      Call zsytrf(uplo, n, a, lda, ipiv, work, lwork, info)

      Write (nout, *)
      Flush (nout)
      If (info==0) Then

!       Compute solution
        Call zsytrs(uplo, n, nrhs, a, lda, ipiv, b, ldb, info)

!       Print solution

!       ifail: behaviour on error exit
!              =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
        ifail = 0
        Call nagf_file_print_matrix_complex_gen_comp('General', ' ', n, nrhs, &
          b, ldb, 'Bracketed', 'F7.4', 'Solution(s)', 'Integer', rlabs, &
          'Integer', clabs, 80, 0, ifail)

      Else
        Write (nout, *) 'The factor D is singular'
      End If

    End Program
Full documentation of ZSYTRS


ZTBCON example

Computational Routines: Estimate condition number of complex band triangular matrix

Data

ZTBCON Example Program Data
  4  2                                                    :Values of N and KD
  'L'                                                     :Value of UPLO
 (-1.94, 4.43)
 (-3.39, 3.44) ( 4.12,-4.27)
 ( 1.62, 3.68) (-1.84, 5.53) ( 0.43,-2.66)
               (-2.77,-1.93) ( 1.74,-0.04) ( 0.44, 0.10)  :End of matrix A

Result

 ZTBCON Example Program Results

 Estimate of condition number =  3.35E+01

Source

    Program ztbcon_example

!     ZTBCON Example Program Text

!     Copyright 2017, Numerical Algorithms Group Ltd. http://www.nag.com

!     .. Use Statements ..
      Use lapack_interfaces, Only: ztbcon
      Use lapack_precision, Only: dp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter :: nin = 5, nout = 6
      Character (1), Parameter :: diag = 'N', norm = '1'
!     .. Local Scalars ..
      Real (Kind=dp) :: rcond
      Integer :: i, info, j, kd, ldab, n
      Character (1) :: uplo
!     .. Local Arrays ..
      Complex (Kind=dp), Allocatable :: ab(:, :), work(:)
      Real (Kind=dp), Allocatable :: rwork(:)
!     .. Intrinsic Procedures ..
      Intrinsic :: epsilon, max, min
!     .. Executable Statements ..
      Write (nout, *) 'ZTBCON Example Program Results'
!     Skip heading in data file
      Read (nin, *)
      Read (nin, *) n, kd
      ldab = kd + 1
      Allocate (ab(ldab,n), work(2*n), rwork(n))

!     Read A from data file

      Read (nin, *) uplo
      If (uplo=='U') Then
        Do i = 1, n
          Read (nin, *)(ab(kd+1+i-j,j), j=i, min(n,i+kd))
        End Do
      Else If (uplo=='L') Then
        Do i = 1, n
          Read (nin, *)(ab(1+i-j,j), j=max(1,i-kd), i)
        End Do
      End If

!     Estimate condition number
      Call ztbcon(norm, uplo, diag, n, kd, ab, ldab, rcond, work, rwork, info)

      Write (nout, *)
      If (rcond>=epsilon(1.0E0_dp)) Then
        Write (nout, 100) 'Estimate of condition number =', 1.0E0_dp/rcond
      Else
        Write (nout, *) 'A is singular to working precision'
      End If

100   Format (1X, A, 1P, E10.2)
    End Program
Full documentation of ZTBCON


ZTBRFS example

Computational Routines: Error bounds for solution of complex band triangular system of linear equations, multiple right-hand sides

Data

ZTBRFS Example Program Data
  4  2  2                                              :Values of N, KD and NRHS
  'L'                                                     :Value of UPLO
 (-1.94, 4.43)
 (-3.39, 3.44) ( 4.12,-4.27)
 ( 1.62, 3.68) (-1.84, 5.53) ( 0.43,-2.66)
               (-2.77,-1.93) ( 1.74,-0.04) ( 0.44, 0.10)  :End of matrix A
 ( -8.86, -3.88) (-24.09, -5.27)
 (-15.57,-23.41) (-57.97,  8.14)
 ( -7.63, 22.78) ( 19.09,-29.51)
 (-14.74, -2.40) ( 19.17, 21.33)                          :End of matrix B

Result

 ZTBRFS Example Program Results

 Solution(s)
                    1                 2
 1  ( 0.0000, 2.0000) ( 1.0000, 5.0000)
 2  ( 1.0000,-3.0000) (-7.0000,-2.0000)
 3  (-4.0000,-5.0000) ( 3.0000, 4.0000)
 4  ( 2.0000,-1.0000) (-6.0000,-9.0000)

 Backward errors (machine-dependent)
         4.1E-17           4.2E-17
 Estimated forward error bounds (machine-dependent)
         1.8E-14           2.2E-14

Source

    Program ztbrfs_example

!     ZTBRFS Example Program Text

!     Copyright 2017, Numerical Algorithms Group Ltd. http://www.nag.com

!     .. Use Statements ..
      Use lapack_example_aux, Only: nagf_file_print_matrix_complex_gen_comp
      Use lapack_interfaces, Only: ztbrfs, ztbtrs
      Use lapack_precision, Only: dp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter :: nin = 5, nout = 6
      Character (1), Parameter :: diag = 'N', trans = 'N'
!     .. Local Scalars ..
      Integer :: i, ifail, info, j, kd, ldab, ldb, ldx, n, nrhs
      Character (1) :: uplo
!     .. Local Arrays ..
      Complex (Kind=dp), Allocatable :: ab(:, :), b(:, :), work(:), x(:, :)
      Real (Kind=dp), Allocatable :: berr(:), ferr(:), rwork(:)
      Character (1) :: clabs(1), rlabs(1)
!     .. Intrinsic Procedures ..
      Intrinsic :: max, min
!     .. Executable Statements ..
      Write (nout, *) 'ZTBRFS Example Program Results'
!     Skip heading in data file
      Read (nin, *)
      Read (nin, *) n, kd, nrhs
      ldab = kd + 1
      ldb = n
      ldx = n
      Allocate (ab(ldab,n), b(ldb,nrhs), work(2*n), x(ldx,n), berr(nrhs), &
        ferr(nrhs), rwork(n))

!     Read A and B from data file, and copy B to X

      Read (nin, *) uplo
      If (uplo=='U') Then
        Do i = 1, n
          Read (nin, *)(ab(kd+1+i-j,j), j=i, min(n,i+kd))
        End Do
      Else If (uplo=='L') Then
        Do i = 1, n
          Read (nin, *)(ab(1+i-j,j), j=max(1,i-kd), i)
        End Do
      End If
      Read (nin, *)(b(i,1:nrhs), i=1, n)
      x(1:n, 1:nrhs) = b(1:n, 1:nrhs)

!     Compute solution in the array X
      Call ztbtrs(uplo, trans, diag, n, kd, nrhs, ab, ldab, x, ldx, info)

!     Compute backward errors and estimated bounds on the
!     forward errors

      Call ztbrfs(uplo, trans, diag, n, kd, nrhs, ab, ldab, b, ldb, x, ldx, &
        ferr, berr, work, rwork, info)

!     Print solution

      Write (nout, *)
      Flush (nout)

!     ifail: behaviour on error exit
!             =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
      ifail = 0
      Call nagf_file_print_matrix_complex_gen_comp('General', ' ', n, nrhs, x, &
        ldx, 'Bracketed', 'F7.4', 'Solution(s)', 'Integer', rlabs, 'Integer', &
        clabs, 80, 0, ifail)

      Write (nout, *)
      Write (nout, *) 'Backward errors (machine-dependent)'
      Write (nout, 100) berr(1:nrhs)
      Write (nout, *) 'Estimated forward error bounds (machine-dependent)'
      Write (nout, 100) ferr(1:nrhs)

100   Format ((5X,1P,4(E11.1,7X)))
    End Program
Full documentation of ZTBRFS


ZTBTRS example

Computational Routines: Solution of complex band triangular system of linear equations, multiple right-hand sides

Data

ZTBTRS Example Program Data
  4  2  2                                              :Values of N, KD and NRHS
  'L'                                                     :Value of UPLO
 (-1.94, 4.43)
 (-3.39, 3.44) ( 4.12,-4.27)
 ( 1.62, 3.68) (-1.84, 5.53) ( 0.43,-2.66)
               (-2.77,-1.93) ( 1.74,-0.04) ( 0.44, 0.10)  :End of matrix A
 ( -8.86, -3.88) (-24.09, -5.27)
 (-15.57,-23.41) (-57.97,  8.14)
 ( -7.63, 22.78) ( 19.09,-29.51)
 (-14.74, -2.40) ( 19.17, 21.33)                          :End of matrix B

Result

 ZTBTRS Example Program Results

 Solution(s)
                    1                 2
 1  ( 0.0000, 2.0000) ( 1.0000, 5.0000)
 2  ( 1.0000,-3.0000) (-7.0000,-2.0000)
 3  (-4.0000,-5.0000) ( 3.0000, 4.0000)
 4  ( 2.0000,-1.0000) (-6.0000,-9.0000)

Source

    Program ztbtrs_example

!     ZTBTRS Example Program Text

!     Copyright 2017, Numerical Algorithms Group Ltd. http://www.nag.com

!     .. Use Statements ..
      Use lapack_example_aux, Only: nagf_file_print_matrix_complex_gen_comp
      Use lapack_interfaces, Only: ztbtrs
      Use lapack_precision, Only: dp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter :: nin = 5, nout = 6
      Character (1), Parameter :: diag = 'N', trans = 'N'
!     .. Local Scalars ..
      Integer :: i, ifail, info, j, kd, ldab, ldb, n, nrhs
      Character (1) :: uplo
!     .. Local Arrays ..
      Complex (Kind=dp), Allocatable :: ab(:, :), b(:, :)
      Character (1) :: clabs(1), rlabs(1)
!     .. Intrinsic Procedures ..
      Intrinsic :: max, min
!     .. Executable Statements ..
      Write (nout, *) 'ZTBTRS Example Program Results'
!     Skip heading in data file
      Read (nin, *)
      Read (nin, *) n, kd, nrhs
      ldab = kd + 1
      ldb = n
      Allocate (ab(ldab,n), b(ldb,nrhs))

!     Read A and B from data file

      Read (nin, *) uplo
      If (uplo=='U') Then
        Do i = 1, n
          Read (nin, *)(ab(kd+1+i-j,j), j=i, min(n,i+kd))
        End Do
      Else If (uplo=='L') Then
        Do i = 1, n
          Read (nin, *)(ab(1+i-j,j), j=max(1,i-kd), i)
        End Do
      End If
      Read (nin, *)(b(i,1:nrhs), i=1, n)

!     Compute solution
      Call ztbtrs(uplo, trans, diag, n, kd, nrhs, ab, ldab, b, ldb, info)

!     Print solution

      Write (nout, *)
      Flush (nout)
      If (info==0) Then

!       ifail: behaviour on error exit
!              =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
        ifail = 0
        Call nagf_file_print_matrix_complex_gen_comp('General', ' ', n, nrhs, &
          b, ldb, 'Bracketed', 'F7.4', 'Solution(s)', 'Integer', rlabs, &
          'Integer', clabs, 80, 0, ifail)

      Else
        Write (nout, *) 'A is singular'
      End If

    End Program
Full documentation of ZTBTRS


ZTFTRI example

Computational Routines: Inverse of complex triangular matrix, Rectangular Full Packed format

Data

ZTFTRI Example Program Data
   4     'L'     'N'     'N'  : n, uplo, transr, diag
 ( 4.15,-0.80)  (-0.02,-0.46)
 ( 4.78, 4.56)  ( 0.33, 0.26)
 ( 2.00,-0.30)  (-4.11, 1.25)
 ( 2.89,-1.34)  ( 2.36,-4.25)
 (-1.89, 1.15)  ( 0.04,-3.69) : AR

Result

 ZTFTRI Example Program Results

 Inverse
                    1                 2                 3                 4
 1  ( 0.1095,-0.1045)
 2  ( 0.0582,-0.0411) (-0.2227,-0.0677)
 3  ( 0.0032, 0.1905) ( 0.1538,-0.2192) ( 0.2323,-0.0448)
 4  ( 0.7602, 0.2814) ( 1.6184,-1.4346) ( 0.1289,-0.2250) ( 1.8697, 1.4731)

Source

    Program ztftri_example

!     ZTFTRI Example Program Text

!     Copyright 2017, Numerical Algorithms Group Ltd. http://www.nag.com

!     .. Use Statements ..
      Use lapack_example_aux, Only: nagf_file_print_matrix_complex_gen_comp
      Use lapack_interfaces, Only: ztftri, ztfttr
      Use lapack_precision, Only: dp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter :: nin = 5, nout = 6
!     .. Local Scalars ..
      Integer :: i, ifail, info, k, lar1, lda, lenar, n, q
      Character (1) :: diag, transr, uplo
!     .. Local Arrays ..
      Complex (Kind=dp), Allocatable :: a(:, :), ar(:)
      Character (1) :: clabs(1), rlabs(1)
!     .. Executable Statements ..
      Write (nout, *) 'ZTFTRI Example Program Results'
!     Skip heading in data file
      Read (nin, *)
      Read (nin, *) n, uplo, transr, diag

      lenar = n*(n+1)/2
      lda = n
      Allocate (ar(1:lenar), a(lda,n))

!     Setup notional dimensions of RFP matrix AR
      k = n/2
      q = n - k
      If (transr=='N' .Or. transr=='n') Then
        lar1 = 2*k + 1
      Else
        lar1 = q
      End If

!     Read an RFP matrix into array AR
      Do i = 1, lar1
        Read (nin, *) ar(i:lenar:lar1)
      End Do

!     Compute inverse of A
      Call ztftri(transr, uplo, diag, n, ar, info)

      Write (nout, *)
      Flush (nout)
      If (info==0) Then

!       Convert and print inverse
        Call ztfttr(transr, uplo, n, ar, a, lda, info)
        ifail = 0

        Call nagf_file_print_matrix_complex_gen_comp(uplo, 'Nonunit', n, n, a, &
          lda, 'Bracketed', 'F7.4', 'Inverse', 'Integer', rlabs, 'Integer', &
          clabs, 80, 0, ifail)
      Else
        Write (nout, *) 'A is singular'
      End If

    End Program
Full documentation of ZTFTRI


ZTGEVC example

Computational Routines: Left and right eigenvectors of a pair of complex upper triangular matrices

Data

ZTGEVC Example Program Data
   4                                                            :Value of N
(  1.00, 3.00)  (  1.00, 4.00)  (  1.00, 5.00)  (  1.00, 6.00)
(  2.00, 2.00)  (  4.00, 3.00)  (  8.00, 4.00)  ( 16.00, 5.00)
(  3.00, 1.00)  (  9.00, 2.00)  ( 27.00, 3.00)  ( 81.00, 4.00)
(  4.00, 0.00)  ( 16.00, 1.00)  ( 64.00, 2.00)  (256.00, 3.00)  :End of matrix A
(  1.00, 0.00)  (  2.00, 1.00)  (  3.00, 2.00)  (  4.00, 3.00)
(  1.00, 1.00)  (  4.00, 2.00)  (  9.00, 3.00)  ( 16.00, 4.00)
(  1.00, 2.00)  (  8.00, 3.00)  ( 27.00, 4.00)  ( 64.00, 5.00)
(  1.00, 3.00)  ( 16.00, 4.00)  ( 81.00, 5.00)  (256.00, 6.00)  :End of matrix B

Result

 ZTGEVC Example Program Results

 Generalized eigenvalues
    1     ( -0.635,  1.653)
    2     (  0.493,  0.910)
    3     (  0.458, -0.843)
    4     (  0.674, -0.050)

 Right eigenvectors
                    1                 2                 3                 4
 1  ( 0.7186, 0.0000) (-0.3946, 0.0246) (-0.4649, 0.0156) (-0.6788,-0.1233)
 2  (-0.6208,-0.2009) ( 0.7921, 0.0000) ( 0.7652, 0.0000) ( 0.7184, 0.0000)
 3  ( 0.2251, 0.0762) (-0.4554, 0.0334) (-0.4275,-0.0912) (-0.0886,-0.0067)
 4  (-0.0372,-0.0088) ( 0.0824,-0.0322) ( 0.0707, 0.0442) (-0.0048, 0.0006)

 Left eigenvectors
                    1                 2                 3                 4
 1  ( 0.7397, 0.0000) (-0.3240,-0.1559) (-0.3722,-0.0016) (-0.4118,-0.2276)
 2  (-0.5812, 0.2589) ( 0.8063, 0.0000) ( 0.8003, 0.0000) ( 0.8681, 0.0000)
 3  ( 0.1875,-0.1097) (-0.4523, 0.0903) (-0.4606,-0.0279) (-0.1564, 0.0136)
 4  (-0.0219, 0.0195) ( 0.0755,-0.0453) ( 0.0839, 0.0311) ( 0.0206,-0.0038)

Source

    Program ztgevc_example

!     ZTGEVC Example Program Text

!     Copyright 2017, Numerical Algorithms Group Ltd. http://www.nag.com

!     .. Use Statements ..
      Use blas_interfaces, Only: dznrm2
      Use lapack_example_aux, Only: nagf_blas_zmload, &
        nagf_file_print_matrix_complex_gen_comp, &
        nagf_sort_cmplxvec_rank_rearrange, nagf_sort_realvec_rank
      Use lapack_interfaces, Only: zgeqrf, zggbak, zggbal, zgghrd, zhgeqz, &
        zlacpy, ztgevc, zungqr, zunmqr
      Use lapack_precision, Only: dp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Complex (Kind=dp), Parameter :: cone = (1.0E0_dp, 0.0E0_dp)
      Complex (Kind=dp), Parameter :: czero = (0.0E0_dp, 0.0E0_dp)
      Integer, Parameter :: nin = 5, nout = 6
      Logical, Parameter :: prbal = .False., prhess = .False.
!     .. Local Scalars ..
      Complex (Kind=dp) :: scal
      Integer :: i, icols, ifail, ihi, ilo, info, irows, j, jwork, k, lda, &
        ldb, ldvl, ldvr, lwork, m, n
      Logical :: ileft, iright
      Character (1) :: compq, compz, howmny, job, side
!     .. Local Arrays ..
      Complex (Kind=dp), Allocatable :: a(:, :), alpha(:), b(:, :), beta(:), &
        tau(:), v(:, :), vl(:, :), vr(:, :), work(:), zwork(:)
      Real (Kind=dp), Allocatable :: lscale(:), rscale(:), rwork(:)
      Integer, Allocatable :: irank(:)
      Logical, Allocatable :: select(:)
      Character (1) :: clabs(1), rlabs(1)
!     .. Intrinsic Procedures ..
      Intrinsic :: abs, aimag, all, cmplx, conjg, maxloc, nint, real
!     .. Executable Statements ..
      Write (nout, *) 'ZTGEVC Example Program Results'
      Flush (nout)

!     ileft  is TRUE if left  eigenvectors are required
!     iright is TRUE if right eigenvectors are required

      ileft = .True.
      iright = .True.

!     Skip heading in data file
      Read (nin, *)
      Read (nin, *) n
      lda = n
      ldb = n
      ldvl = n
      ldvr = n
      lwork = 6*n
      Allocate (a(lda,n), alpha(n), b(ldb,n), beta(n), tau(n), vl(ldvl,ldvl), &
        vr(ldvr,ldvr), work(lwork), lscale(n), rscale(n), rwork(6*n), &
        select(n), irank(n), v(n,n))

!     READ matrix A from data file
      Read (nin, *)(a(i,1:n), i=1, n)

!     READ matrix B from data file
      Read (nin, *)(b(i,1:n), i=1, n)

!     Balance matrix pair (A,B)
      job = 'B'
      Call zggbal(job, n, a, lda, b, ldb, ilo, ihi, lscale, rscale, rwork, &
        info)

      If (prbal) Then
!       Matrix A after balancing
!       ifail: behaviour on error exit
!               =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
        ifail = 0
        Call nagf_file_print_matrix_complex_gen_comp('General', ' ', n, n, a, &
          lda, 'Bracketed', 'F7.4', 'Matrix A after balancing', 'Integer', &
          rlabs, 'Integer', clabs, 80, 0, ifail)
        Write (nout, *)
        Flush (nout)

!       Matrix B after balancing
        ifail = 0
        Call nagf_file_print_matrix_complex_gen_comp('General', ' ', n, n, b, &
          ldb, 'Bracketed', 'F7.4', 'Matrix B after balancing', 'Integer', &
          rlabs, 'Integer', clabs, 80, 0, ifail)
        Write (nout, *)
        Flush (nout)
      End If

!     Reduce B to triangular form using QR
      irows = ihi + 1 - ilo
      icols = n + 1 - ilo
      Call zgeqrf(irows, icols, b(ilo,ilo), ldb, tau, work, lwork, info)

!     Apply the orthogonal transformation to A
      Call zunmqr('L', 'C', irows, icols, irows, b(ilo,ilo), ldb, tau, &
        a(ilo,ilo), lda, work, lwork, info)

!     Initialize VL (for left eigenvectors)
      If (ileft) Then

        Call nagf_blas_zmload('General', n, n, czero, cone, vl, ldvl)
        Call zlacpy('Lower', irows-1, irows-1, b(ilo+1,ilo), ldb, &
          vl(ilo+1,ilo), ldvl)
        Call zungqr(irows, irows, irows, vl(ilo,ilo), ldvl, tau, work, lwork, &
          info)

      End If

!     Initialize VR for right eigenvectors
      If (iright) Then
        Call nagf_blas_zmload('General', n, n, czero, cone, vr, ldvr)
      End If

!     Compute the generalized Hessenberg form of (A,B)
      compq = 'V'
      compz = 'V'
      Call zgghrd(compq, compz, n, ilo, ihi, a, lda, b, ldb, vl, ldvl, vr, &
        ldvr, info)

      If (prhess) Then
!       Matrix A in generalized Hessenberg form
        ifail = 0
        Call nagf_file_print_matrix_complex_gen_comp('General', ' ', n, n, a, &
          lda, 'Bracketed', 'F7.3', 'Matrix A in Hessenberg form', 'Integer', &
          rlabs, 'Integer', clabs, 80, 0, ifail)
        Write (nout, *)
        Flush (nout)

!       Matrix B in generalized Hessenberg form
        ifail = 0
        Call nagf_file_print_matrix_complex_gen_comp('General', ' ', n, n, b, &
          ldb, 'Bracketed', 'F7.3', 'Matrix B in Hessenberg form', 'Integer', &
          rlabs, 'Integer', clabs, 80, 0, ifail)
        Write (nout, *)
        Flush (nout)
      End If

!     Routine ZHGEQZ
!     Workspace query: jwork = -1
      jwork = -1
      job = 'S'
      Call zhgeqz(job, compq, compz, n, ilo, ihi, a, lda, b, ldb, alpha, beta, &
        vl, ldvl, vr, ldvr, work, jwork, rwork, info)

      lwork = nint(real(work(1)))
      Allocate (zwork(lwork))

!     Compute the generalized Schur form
      Call zhgeqz(job, compq, compz, n, ilo, ihi, a, lda, b, ldb, alpha, beta, &
        vl, ldvl, vr, ldvr, zwork, lwork, rwork, info)

!     Sort and print generalized eigenvalues if none are infinite.
      If (all(real(beta(1:n))>0.0_dp)) Then
!       Store absolute values of eigenvalues for ranking
        work(1:n) = alpha(1:n)/beta(1:n)
        rwork(1:n) = abs(work(1:n))

!       Rank eigenvalues
        ifail = 0
        Call nagf_sort_realvec_rank(rwork, 1, n, 'Descending', irank, ifail)

!       Sort eigenvalues in work(1:n)
        Call nagf_sort_cmplxvec_rank_rearrange(work, 1, n, irank, ifail)

        Write (nout, 100)
        Do i = 1, n
          Write (nout, 110) i, '(', real(work(i)), ',', aimag(work(i)), ')'
        End Do
        Write (nout, *)
        Flush (nout)
      Else
        irank(1:n) = (/ (i,i=1,n) /)
      End If

!     Compute left and right generalized eigenvectors
!     of the balanced matrix
      howmny = 'B'
      If (ileft .And. iright) Then
        side = 'B'
      Else If (ileft) Then
        side = 'L'
      Else If (iright) Then
        side = 'R'
      End If

      Call ztgevc(side, howmny, select, n, a, lda, b, ldb, vl, ldvl, vr, ldvr, &
        n, m, work, rwork, info)

!     Compute right eigenvectors of the original matrix

      If (iright) Then
        job = 'B'
        side = 'R'

        Call zggbak(job, side, n, ilo, ihi, lscale, rscale, n, vr, ldvr, info)

!       Normalize the right eigenvectors
        Do i = 1, n
          j = irank(i)
          rwork(1:n) = abs(vr(1:n,i))
          k = maxloc(rwork(1:n), 1)
          scal = conjg(vr(k,i))/abs(vr(k,i))/dznrm2(n, vr(1,i), 1)
          v(1:n, j) = vr(1:n, i)*scal
          v(k, j) = cmplx(real(v(k,j)), kind=dp)
        End Do

!       Print the right eigenvectors

        ifail = 0
        Call nagf_file_print_matrix_complex_gen_comp('General', ' ', n, n, v, &
          n, 'Bracketed', 'F7.4', 'Right eigenvectors', 'Integer', rlabs, &
          'Integer', clabs, 80, 0, ifail)

        Write (nout, *)
        Flush (nout)

      End If

!     Compute left eigenvectors of the original matrix

      If (ileft) Then
        job = 'B'
        side = 'L'

        Call zggbak(job, side, n, ilo, ihi, lscale, rscale, n, vl, ldvl, info)

!       Normalize the left eigenvectors
        Do i = 1, n
          j = irank(i)
          rwork(1:n) = abs(vl(1:n,i))
          k = maxloc(rwork(1:n), 1)
          scal = conjg(vl(k,i))/abs(vl(k,i))/dznrm2(n, vl(1,i), 1)
          v(1:n, j) = vl(1:n, i)*scal
          v(k, j) = cmplx(real(v(k,j)), kind=dp)
        End Do

!       Print the left eigenvectors

        ifail = 0
        Call nagf_file_print_matrix_complex_gen_comp('General', ' ', n, n, v, &
          n, 'Bracketed', 'F7.4', 'Left eigenvectors', 'Integer', rlabs, &
          'Integer', clabs, 80, 0, ifail)

      End If

100   Format (1X, /, 1X, 'Generalized eigenvalues')
110   Format (1X, I4, 5X, A, F7.3, A, F7.3, A)
    End Program
Full documentation of ZTGEVC


ZTGEXC example

Computational Routines: Reorders the generalized Schur decomposition of a complex matrix pair using an unitary equivalence transformation

Data

ZTGEXC Example Program Data
  4                                                :Value of N
 ( 4.0, 4.0) ( 1.0, 1.0) ( 1.0, 1.0) ( 2.0,-1.0)
 ( 0.0, 0.0) ( 2.0, 1.0) ( 1.0, 1.0) ( 1.0, 1.0)
 ( 0.0, 0.0) ( 0.0, 0.0) ( 2.0,-1.0) ( 1.0, 1.0)
 ( 0.0, 0.0) ( 0.0, 0.0) ( 0.0, 0.0) ( 6.0,-2.0)   :End of matrix A
 ( 2.0, 0.0) ( 1.0, 1.0) ( 1.0, 1.0) ( 3.0,-1.0)
 ( 0.0, 0.0) ( 1.0, 0.0) ( 2.0, 1.0) ( 1.0, 1.0)
 ( 0.0, 0.0) ( 0.0, 0.0) ( 1.0, 0.0) ( 1.0, 1.0)
 ( 0.0, 0.0) ( 0.0, 0.0) ( 0.0, 0.0) ( 2.0, 0.0)   :End of matrix B
  1  4                                             :Values of IFST and ILST

Result

 ZTGEXC Example Program Results

 Reordered Schur matrix A
                    1                 2                 3                 4
 1  ( 3.7081, 3.7081) (-2.0834,-0.5688) ( 2.6374, 1.0772) ( 0.2845, 0.7991)
 2  ( 0.0000, 0.0000) ( 1.6097, 1.5656) (-0.0634, 1.9234) (-0.0301, 0.9720)
 3  ( 0.0000, 0.0000) ( 0.0000, 0.0000) ( 4.7029,-2.1187) ( 1.1379,-3.1199)
 4  ( 0.0000, 0.0000) ( 0.0000, 0.0000) ( 0.0000, 0.0000) ( 2.3085,-1.8289)

 Reordered Schur matrix B
                    1                 2                 3                 4
 1  ( 2.2249, 0.7416) (-1.1631, 1.5347) ( 2.2608, 2.0851) ( 1.1094,-0.3205)
 2  ( 0.0000, 0.0000) ( 0.3308, 0.9482) ( 0.3919, 1.8172) (-0.6305, 1.6053)
 3  ( 0.0000, 0.0000) ( 0.0000, 0.0000) ( 1.6227,-0.1653) ( 0.9966,-0.9074)
 4  ( 0.0000, 0.0000) ( 0.0000, 0.0000) ( 0.0000, 0.0000) ( 0.1199,-1.0343)

Source

    Program ztgexc_example

!     ZTGEXC Example Program Text

!     Copyright 2017, Numerical Algorithms Group Ltd. http://www.nag.com

!     .. Use Statements ..
      Use lapack_example_aux, Only: nagf_file_print_matrix_complex_gen_comp
      Use lapack_interfaces, Only: ztgexc
      Use lapack_precision, Only: dp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter :: nin = 5, nout = 6
      Logical, Parameter :: wantq = .False., wantz = .False.
!     .. Local Scalars ..
      Integer :: i, ifail, ifst, ilst, info, lda, ldb, ldq, ldz, n
!     .. Local Arrays ..
      Complex (Kind=dp), Allocatable :: a(:, :), b(:, :), q(:, :), z(:, :)
      Character (1) :: clabs(1), rlabs(1)
!     .. Executable Statements ..
      Write (nout, *) 'ZTGEXC Example Program Results'
      Write (nout, *)
      Flush (nout)
!     Skip heading in data file
      Read (nin, *)
      Read (nin, *) n
      ldq = 1
      ldz = 1
      lda = n
      ldb = n
      Allocate (a(lda,n), b(ldb,n), q(ldq,1), z(ldz,1))

!     Read A and B from data file

      Read (nin, *)(a(i,1:n), i=1, n)
      Read (nin, *)(b(i,1:n), i=1, n)

!     Read the row indices

      Read (nin, *) ifst, ilst

!     Reorder the A and B

      Call ztgexc(wantq, wantz, n, a, lda, b, ldb, q, ldq, z, ldz, ifst, ilst, &
        info)

      If (info/=0) Then
        Write (nout, 100) info, ilst
        Write (nout, *)
        Flush (nout)
      End If

!     Print reordered generalized Schur form

!     ifail: behaviour on error exit
!             =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
      ifail = 0
      Call nagf_file_print_matrix_complex_gen_comp('General', ' ', n, n, a, &
        lda, 'Bracketed', 'F7.4', 'Reordered Schur matrix A', 'Integer', &
        rlabs, 'Integer', clabs, 80, 0, ifail)

      Write (nout, *)
      Flush (nout)

      ifail = 0
      Call nagf_file_print_matrix_complex_gen_comp('General', ' ', n, n, b, &
        ldb, 'Bracketed', 'F7.4', 'Reordered Schur matrix B', 'Integer', &
        rlabs, 'Integer', clabs, 80, 0, ifail)

100   Format (' Reordering could not be completed. INFO = ', I3, ' ILST = ', &
        I5)
    End Program
Full documentation of ZTGEXC


ZTGSEN example

Computational Routines: Reorders the generalized Schur decomposition of a complex matrix pair using an unitary equivalence transformation, computes the generalized eigenvalues of the reordered pair and, optionally, computes the estimates of reciprocal condition numbers for eigenvalues and eigenspaces

Data

ZTGSEN Example Program Data
  4                                                :Value of N
 ( 4.0, 4.0) ( 1.0, 1.0) ( 1.0, 1.0) ( 2.0,-1.0)
 ( 0.0, 0.0) ( 2.0, 1.0) ( 1.0, 1.0) ( 1.0, 1.0)
 ( 0.0, 0.0) ( 0.0, 0.0) ( 2.0,-1.0) ( 1.0, 1.0)
 ( 0.0, 0.0) ( 0.0, 0.0) ( 0.0, 0.0) ( 6.0,-2.0)   :End of matrix A
 ( 2.0, 0.0) ( 1.0, 1.0) ( 1.0, 1.0) ( 3.0,-1.0)
 ( 0.0, 0.0) ( 1.0, 0.0) ( 2.0, 1.0) ( 1.0, 1.0)
 ( 0.0, 0.0) ( 0.0, 0.0) ( 1.0, 0.0) ( 1.0, 1.0)
 ( 0.0, 0.0) ( 0.0, 0.0) ( 0.0, 0.0) ( 2.0, 0.0)   :End of matrix B
 ( 1.0, 0.0) ( 0.0, 0.0) ( 0.0, 0.0) ( 0.0, 0.0)
 ( 0.0, 0.0) ( 1.0, 0.0) ( 0.0, 0.0) ( 0.0, 0.0)
 ( 0.0, 0.0) ( 0.0, 0.0) ( 1.0, 0.0) ( 0.0, 0.0)
 ( 0.0, 0.0) ( 0.0, 0.0) ( 0.0, 0.0) ( 1.0, 0.0)   :End of matrix Q
 ( 1.0, 0.0) ( 0.0, 0.0) ( 0.0, 0.0) ( 0.0, 0.0)
 ( 0.0, 0.0) ( 1.0, 0.0) ( 0.0, 0.0) ( 0.0, 0.0)
 ( 0.0, 0.0) ( 0.0, 0.0) ( 1.0, 0.0) ( 0.0, 0.0)
 ( 0.0, 0.0) ( 0.0, 0.0) ( 0.0, 0.0) ( 1.0, 0.0)   :End of matrix Z
   F           T           T           F           :End of SELECT

Result

 ZTGSEN Example Program Results

 Reordered Schur matrix A
                    1                 2                 3                 4
 1  ( 4.6904, 2.3452) (-2.1563, 0.1192) ( 1.9599,-0.5174) ( 1.8091,-1.2060)
 2  ( 0.0000, 0.0000) ( 2.0084,-1.0042) ( 0.9161,-0.2762) ( 1.8574,-0.5326)
 3  ( 0.0000, 0.0000) ( 0.0000, 0.0000) ( 1.6985, 1.6985) ( 0.1270, 0.7231)
 4  ( 0.0000, 0.0000) ( 0.0000, 0.0000) ( 0.0000, 0.0000) ( 6.0000,-2.0000)

 Reordered Schur matrix B
                    1                 2                 3                 4
 1  ( 2.3452, 0.0000) (-0.6181, 1.8237) ( 0.9290, 0.5409) ( 2.7136,-1.5076)
 2  ( 0.0000, 0.0000) ( 1.0042, 0.0000) ( 1.2251,-1.1857) ( 1.8541,-0.2929)
 3  ( 0.0000, 0.0000) ( 0.0000, 0.0000) ( 0.8492, 0.0000) ( 0.1435, 0.9053)
 4  ( 0.0000, 0.0000) ( 0.0000, 0.0000) ( 0.0000, 0.0000) ( 2.0000, 0.0000)

 Basis of left deflating invariant subspace
                    1                 2
 1  ( 0.9045, 0.3015) (-0.0033,-0.2397)
 2  ( 0.3015, 0.0000) ( 0.2497, 0.7157)
 3  ( 0.0000, 0.0000) ( 0.0549, 0.6042)
 4  ( 0.0000, 0.0000) ( 0.0000, 0.0000)

 Basis of right deflating invariant subspace
                    1                 2
 1  ( 0.7071, 0.0000) (-0.5607, 0.0000)
 2  ( 0.7071, 0.0000) ( 0.5607, 0.0000)
 3  ( 0.0000, 0.0000) ( 0.0552, 0.6067)
 4  ( 0.0000, 0.0000) ( 0.0000, 0.0000)

 Norm estimate of projection onto left  eigenspace for selected cluster
   8.90E+00

 Norm estimate of projection onto right eigenspace for selected cluster
   7.02E+00

 F-norm based upper bound on Difu
   2.18E-01

 F-norm based upper bound on Difl
   2.62E-01

Source

    Program ztgsen_example

!     ZTGSEN Example Program Text

!     Copyright 2017, Numerical Algorithms Group Ltd. http://www.nag.com

!     .. Use Statements ..
      Use lapack_example_aux, Only: nagf_file_print_matrix_complex_gen_comp
      Use lapack_interfaces, Only: ztgsen
      Use lapack_precision, Only: dp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=dp) :: pl, pr
      Integer :: i, ifail, ijob, info, lda, ldb, ldq, ldz, liwork, lwork, m, n
      Logical :: wantq, wantz
!     .. Local Arrays ..
      Complex (Kind=dp), Allocatable :: a(:, :), alpha(:), b(:, :), beta(:), &
        q(:, :), work(:), z(:, :)
      Real (Kind=dp) :: dif(2)
      Integer, Allocatable :: iwork(:)
      Logical, Allocatable :: select(:)
      Character (1) :: clabs(1), rlabs(1)
!     .. Executable Statements ..
      Write (nout, *) 'ZTGSEN Example Program Results'
      Write (nout, *)
      Flush (nout)
!     Skip heading in data file
      Read (nin, *)
      Read (nin, *) n
      lda = n
      ldb = n
      ldq = n
      ldz = n
      liwork = (n*n)/2 + 2
      lwork = n*n
      Allocate (a(lda,n), alpha(n), b(ldb,n), beta(n), q(ldq,n), work(lwork), &
        z(ldz,n), iwork(liwork), select(n))

!     Read A, B, Q, Z and the logical array SELECT from data file

      Read (nin, *)(a(i,1:n), i=1, n)
      Read (nin, *)(b(i,1:n), i=1, n)
      Read (nin, *)(q(i,1:n), i=1, n)
      Read (nin, *)(z(i,1:n), i=1, n)

      Read (nin, *) select(1:n)

!     Set ijob, wantq and wantz
      ijob = 4
      wantq = .True.
      wantz = .True.

!     Reorder the Schur factors A and B and update the matrices
!     Q and Z

      Call ztgsen(ijob, wantq, wantz, select, n, a, lda, b, ldb, alpha, beta, &
        q, ldq, z, ldz, m, pl, pr, dif, work, lwork, iwork, liwork, info)

      If (info/=0) Then
        Write (nout, 100) info
        Write (nout, *)
        Flush (nout)
      End If

!     Print reordered generalized Schur form

!     ifail: behaviour on error exit
!             =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
      ifail = 0
      Call nagf_file_print_matrix_complex_gen_comp('General', ' ', n, n, a, &
        lda, 'Bracketed', 'F7.4', 'Reordered Schur matrix A', 'Integer', &
        rlabs, 'Integer', clabs, 80, 0, ifail)

      Write (nout, *)
      Flush (nout)

      ifail = 0
      Call nagf_file_print_matrix_complex_gen_comp('General', ' ', n, n, b, &
        ldb, 'Bracketed', 'F7.4', 'Reordered Schur matrix B', 'Integer', &
        rlabs, 'Integer', clabs, 80, 0, ifail)

!     Print deflating subspaces

      Write (nout, *)
      Flush (nout)

      ifail = 0
      Call nagf_file_print_matrix_complex_gen_comp('General', ' ', n, m, q, &
        ldq, 'Bracketed', 'F7.4', 'Basis of left deflating invariant subspace' &
        , 'Integer', rlabs, 'Integer', clabs, 80, 0, ifail)

      Write (nout, *)
      Flush (nout)

      ifail = 0
      Call nagf_file_print_matrix_complex_gen_comp('General', ' ', n, m, z, &
        ldz, 'Bracketed', 'F7.4', &
        'Basis of right deflating invariant subspace', 'Integer', rlabs, &
        'Integer', clabs, 80, 0, ifail)

!     Print norm estimates and F-norm upper bounds

      Write (nout, *)
      Write (nout, 110) 'Norm estimate of projection onto', &
        ' left  eigenspace for selected cluster', 1.0E0_dp/pl
      Write (nout, *)
      Write (nout, 110) 'Norm estimate of projection onto', &
        ' right eigenspace for selected cluster', 1.0E0_dp/pr
      Write (nout, *)
      Write (nout, 110) 'F-norm based upper bound on', ' Difu', dif(1)
      Write (nout, *)
      Write (nout, 110) 'F-norm based upper bound on', ' Difl', dif(2)

100   Format (' Reordering could not be completed. INFO = ', I3)
110   Format (1X, 2A, /, 1X, 1P, E10.2)
    End Program
Full documentation of ZTGSEN


ZTGSJA example

Computational Routines: Computes the generalized singular value decomposition of a complex upper triangular (or trapezoidal) matrix pair

Data

ZTGSJA Example Program Data

  6             4             2                         :Values of M, N and P

( 0.96,-0.81) (-0.03, 0.96) (-0.91, 2.06) (-0.05, 0.41)
(-0.98, 1.98) (-1.20, 0.19) (-0.66, 0.42) (-0.81, 0.56)
( 0.62,-0.46) ( 1.01, 0.02) ( 0.63,-0.17) (-1.11, 0.60)
( 0.37, 0.38) ( 0.19,-0.54) (-0.98,-0.36) ( 0.22,-0.20)
( 0.83, 0.51) ( 0.20, 0.01) (-0.17,-0.46) ( 1.47, 1.59)
( 1.08,-0.28) ( 0.20,-0.12) (-0.07, 1.23) ( 0.26, 0.26) :End of matrix A

( 1.00, 0.00) ( 0.00, 0.00) (-1.00, 0.00) ( 0.00, 0.00)
( 0.00, 0.00) ( 1.00, 0.00) ( 0.00, 0.00) (-1.00, 0.00) :End of matrix B

Result

 ZTGSJA Example Program Results

 Number of infinite generalized singular values (K)
     2
 Number of finite generalized singular values (L)
     2
  Effective Numerical rank of (A**T B**T)**T (K+L)
     4

 Finite generalized singular values
     2.0720E+00  1.1058E+00

 Unitary matrix U
                              1                           2
 1  ( -1.3038E-02, -3.2595E-01) ( -1.4039E-01, -2.6167E-01)
 2  (  4.2764E-01, -6.2582E-01) (  8.6298E-02, -3.8174E-02)
 3  ( -3.2595E-01,  1.6428E-01) (  3.8163E-01, -1.8219E-01)
 4  (  1.5906E-01, -5.2151E-03) ( -2.8207E-01,  1.9732E-01)
 5  ( -1.7210E-01, -1.3038E-02) ( -5.0942E-01, -5.0319E-01)
 6  ( -2.6336E-01, -2.4772E-01) ( -1.0861E-01,  2.8474E-01)

                              3                           4
 1  (  2.5177E-01, -7.9789E-01) ( -5.0956E-02, -2.1750E-01)
 2  ( -3.2188E-01,  1.6112E-01) (  1.1979E-01,  1.6319E-01)
 3  (  1.3231E-01, -1.4565E-02) ( -5.0671E-01,  1.8615E-01)
 4  (  2.1598E-01,  1.8813E-01) ( -4.0163E-01,  2.6787E-01)
 5  (  3.6488E-02,  2.0316E-01) (  1.9271E-01,  1.5574E-01)
 6  (  1.0906E-01, -1.2712E-01) ( -8.8159E-02,  5.6169E-01)

                              5                           6
 1  ( -4.5947E-02,  1.4052E-04) ( -5.2773E-02, -2.2492E-01)
 2  ( -8.0311E-02, -4.3605E-01) ( -3.8117E-02, -2.1907E-01)
 3  (  5.9714E-02, -5.8974E-01) ( -1.3850E-01, -9.0941E-02)
 4  ( -4.6443E-02,  3.0864E-01) ( -3.7354E-01, -5.5148E-01)
 5  (  5.7843E-01, -1.2439E-01) ( -1.8815E-02, -5.5686E-02)
 6  (  1.5763E-02,  4.7130E-02) (  6.5007E-01,  4.9173E-03)

 Unitary matrix V
                              1                           2
 1  (  9.8930E-01,  1.9041E-19) ( -1.1461E-01,  9.0250E-02)
 2  ( -1.1461E-01, -9.0250E-02) ( -9.8930E-01,  1.9041E-19)

 Unitary matrix Q
                              1                           2
 1  (  7.0711E-01,  0.0000E+00) (  0.0000E+00,  0.0000E+00)
 2  (  0.0000E+00,  0.0000E+00) (  7.0711E-01,  0.0000E+00)
 3  (  7.0711E-01,  0.0000E+00) (  0.0000E+00,  0.0000E+00)
 4  (  0.0000E+00,  0.0000E+00) (  7.0711E-01,  0.0000E+00)

                              3                           4
 1  (  6.9954E-01,  4.7274E-19) (  8.1044E-02, -6.3817E-02)
 2  ( -8.1044E-02, -6.3817E-02) (  6.9954E-01, -4.7274E-19)
 3  ( -6.9954E-01, -4.7274E-19) ( -8.1044E-02,  6.3817E-02)
 4  (  8.1044E-02,  6.3817E-02) ( -6.9954E-01,  4.7274E-19)

 Nonsingular upper triangular matrix R
                              1                           2
 1  ( -2.7118E+00,  0.0000E+00) ( -1.4390E+00, -1.0315E+00)
 2                              ( -1.8583E+00,  0.0000E+00)
 3
 4

                              3                           4
 1  ( -7.6930E-02,  1.3613E+00) ( -2.8137E-01, -3.2425E-02)
 2  ( -1.0760E+00,  3.1016E-02) (  1.3292E+00,  3.6772E-01)
 3  (  3.2537E+00,  0.0000E+00) ( -6.3858E-17,  6.3858E-17)
 4                              ( -2.1084E+00,  0.0000E+00)

 Number of cycles of the Kogbetliantz method
     2

Source

    Program ztgsja_example

!     ZTGSJA Example Program Text

!     Copyright 2017, Numerical Algorithms Group Ltd. http://www.nag.com

!     .. Use Statements ..
      Use lapack_example_aux, Only: nagf_file_print_matrix_complex_gen_comp
      Use lapack_interfaces, Only: zggsvp3, zlange, ztgsja
      Use lapack_precision, Only: dp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=dp) :: eps, tola, tolb
      Integer :: i, ifail, info, irank, j, k, l, lda, ldb, ldq, ldu, ldv, &
        lwork, m, n, ncycle, p
!     .. Local Arrays ..
      Complex (Kind=dp), Allocatable :: a(:, :), b(:, :), q(:, :), tau(:), &
        u(:, :), v(:, :), work(:)
      Complex (Kind=dp) :: wdum(1)
      Real (Kind=dp), Allocatable :: alpha(:), beta(:), rwork(:)
      Integer, Allocatable :: iwork(:)
      Character (1) :: clabs(1), rlabs(1)
!     .. Intrinsic Procedures ..
      Intrinsic :: epsilon, max, nint, real
!     .. Executable Statements ..
      Write (nout, *) 'ZTGSJA Example Program Results'
      Write (nout, *)
      Flush (nout)

!     Skip heading in data file
      Read (nin, *)
      Read (nin, *) m, n, p
      lda = m
      ldb = p
      ldq = n
      ldu = m
      ldv = p
      Allocate (a(lda,n), b(ldb,n), q(ldq,n), tau(n), u(ldu,m), v(ldv,p), &
        alpha(n), beta(n), rwork(2*n), iwork(n))

!     Determine maximum workspace needed by zggsvp3 and ztgsja
      Call zggsvp3('U', 'V', 'Q', m, p, n, a, lda, b, ldb, tola, tolb, k, l, &
        u, ldu, v, ldv, q, ldq, iwork, rwork, tau, wdum, -1, info)
      lwork = max(nint(real(wdum(1))), 2*n)
      Allocate (work(lwork))

!     Read the m by n matrix A and p by n matrix B from data file

      Read (nin, *)(a(i,1:n), i=1, m)
      Read (nin, *)(b(i,1:n), i=1, p)

!     Compute tola and tolb as
!         tola = max(m,n)*norm(A)*macheps
!         tolb = max(p,n)*norm(B)*macheps

      eps = epsilon(1.0E0_dp)
      tola = real(max(m,n), kind=dp)*zlange('One-norm', m, n, a, lda, rwork)* &
        eps
      tolb = real(max(p,n), kind=dp)*zlange('One-norm', p, n, b, ldb, rwork)* &
        eps

!     Compute the factorization of (A, B)
!         (A = U1*S*(Q1**H), B = V1*T*(Q1**H))

      Call zggsvp3('U', 'V', 'Q', m, p, n, a, lda, b, ldb, tola, tolb, k, l, &
        u, ldu, v, ldv, q, ldq, iwork, rwork, tau, work, lwork, info)

!     Compute the generalized singular value decomposition of (A, B)
!         (A = U*D1*(0 R)*(Q**H), B = V*D2*(0 R)*(Q**H))

      Call ztgsja('U', 'V', 'Q', m, p, n, k, l, a, lda, b, ldb, tola, tolb, &
        alpha, beta, u, ldu, v, ldv, q, ldq, work, ncycle, info)

      If (info==0) Then

!       Print solution

        irank = k + l
        Write (nout, *) 'Number of infinite generalized singular values (K)'
        Write (nout, 100) k
        Write (nout, *) 'Number of finite generalized singular values (L)'
        Write (nout, 100) l
        Write (nout, *) ' Effective Numerical rank of (A**T B**T)**T (K+L)'
        Write (nout, 100) irank
        Write (nout, *)
        Write (nout, *) 'Finite generalized singular values'
        Write (nout, 110)(alpha(j)/beta(j), j=k+1, irank)
        Write (nout, *)
        Flush (nout)

!       ifail: behaviour on error exit
!              =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
        ifail = 0
        Call nagf_file_print_matrix_complex_gen_comp('General', ' ', m, m, u, &
          ldu, 'Bracketed', '1P,E12.4', 'Unitary matrix U', 'Integer', rlabs, &
          'Integer', clabs, 80, 0, ifail)

        Write (nout, *)
        Flush (nout)

        Call nagf_file_print_matrix_complex_gen_comp('General', ' ', p, p, v, &
          ldv, 'Bracketed', '1P,E12.4', 'Unitary matrix V', 'Integer', rlabs, &
          'Integer', clabs, 80, 0, ifail)

        Write (nout, *)
        Flush (nout)

        Call nagf_file_print_matrix_complex_gen_comp('General', ' ', n, n, q, &
          ldq, 'Bracketed', '1P,E12.4', 'Unitary matrix Q', 'Integer', rlabs, &
          'Integer', clabs, 80, 0, ifail)

        Write (nout, *)
        Flush (nout)

        Call nagf_file_print_matrix_complex_gen_comp('Upper triangular', &
          'Non-unit', irank, irank, a(1,n-irank+1), lda, 'Bracketed', &
          '1P,E12.4', 'Nonsingular upper triangular matrix R', 'Integer', &
          rlabs, 'Integer', clabs, 80, 0, ifail)

        Write (nout, *)
        Write (nout, *) 'Number of cycles of the Kogbetliantz method'
        Write (nout, 100) ncycle
      Else
        Write (nout, 120) 'Failure in ZTGSJA. INFO =', info
      End If

100   Format (1X, I5)
110   Format (3X, 8(1P,E12.4))
120   Format (1X, A, I4)
    End Program
Full documentation of ZTGSJA


ZTGSNA example

Computational Routines: Estimates reciprocal condition numbers for specified eigenvalues and/or eigenvectors of a complex matrix pair in generalized Schur canonical form

Data

ZTGSNA Example Program Data
  4                                                :Value of N
 ( 4.0, 4.0) ( 1.0, 1.0) ( 1.0, 1.0) ( 2.0,-1.0)
 ( 0.0, 0.0) ( 2.0, 1.0) ( 1.0, 1.0) ( 1.0, 1.0)
 ( 0.0, 0.0) ( 0.0, 0.0) ( 2.0,-1.0) ( 1.0, 1.0)
 ( 0.0, 0.0) ( 0.0, 0.0) ( 0.0, 0.0) ( 6.0,-2.0)   :End of matrix A
 ( 2.0, 0.0) ( 1.0, 1.0) ( 1.0, 1.0) ( 3.0,-1.0)
 ( 0.0, 0.0) ( 1.0, 0.0) ( 2.0, 1.0) ( 1.0, 1.0)
 ( 0.0, 0.0) ( 0.0, 0.0) ( 1.0, 0.0) ( 1.0, 1.0)
 ( 0.0, 0.0) ( 0.0, 0.0) ( 0.0, 0.0) ( 2.0, 0.0)   :End of matrix B

Result

 ZTGSNA Example Program Results

 S
       1.0E+00    8.2E-01    7.2E-01    8.2E-01

 DIF
       3.2E-01    3.6E-01    5.5E-01    2.8E-01

 Approximate error estimates for eigenvalues of (A,B)
       3.0E-15    3.8E-15    4.3E-15    3.8E-15

 Approximate error estimates for right eigenvectors of (A,B)
       9.5E-15    8.6E-15    5.6E-15    1.1E-14

Source

    Program ztgsna_example

!     ZTGSNA Example Program Text

!     Copyright 2017, Numerical Algorithms Group Ltd. http://www.nag.com

!     .. Use Statements ..
      Use lapack_example_aux, Only: nagf_blas_dpyth
      Use lapack_interfaces, Only: zlange, ztgevc, ztgsna
      Use lapack_precision, Only: dp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=dp) :: eps, snorm, stnrm, tnorm
      Integer :: i, info, lda, ldb, ldvl, ldvr, lwork, m, n
!     .. Local Arrays ..
      Complex (Kind=dp), Allocatable :: a(:, :), b(:, :), vl(:, :), vr(:, :), &
        work(:)
      Real (Kind=dp), Allocatable :: dif(:), rwork(:), s(:)
      Integer, Allocatable :: iwork(:)
      Logical :: select(1)
!     .. Intrinsic Procedures ..
      Intrinsic :: epsilon
!     .. Executable Statements ..
      Write (nout, *) 'ZTGSNA Example Program Results'
      Write (nout, *)
!     Skip heading in data file
      Read (nin, *)
      Read (nin, *) n
      lda = n
      ldb = n
      ldvl = n
      ldvr = n
      lwork = 2*n*n
      Allocate (a(lda,n), b(ldb,n), vl(ldvl,n), vr(ldvr,n), work(lwork), &
        dif(n), rwork(2*n), s(n), iwork(n+2))

!     Read A and B from data file

      Read (nin, *)(a(i,1:n), i=1, n)
      Read (nin, *)(b(i,1:n), i=1, n)

!     Calculate the left and right generalized eigenvectors of the
!     pair (A,B).

      Call ztgevc('Both', 'All', select, n, a, lda, b, ldb, vl, ldvl, vr, &
        ldvr, n, m, work, rwork, info)

!     Estimate condition numbers for all the generalized eigenvalues
!     and right eigenvectors of the pair (A,B)

      Call ztgsna('Both', 'All', select, n, a, lda, b, ldb, vl, ldvl, vr, &
        ldvr, s, dif, n, m, work, lwork, iwork, info)

!     Print condition numbers of eigenvalues and right eigenvectors

      Write (nout, *) 'S'
      Write (nout, 100) s(1:m)
      Write (nout, *)
      Write (nout, *) 'DIF'
      Write (nout, 100) dif(1:m)

!     Calculate approximate error estimates

!     Compute the 1-norms of A and B and then compute
!     SQRT(snorm**2 + tnorm**2)

      eps = epsilon(1.0E0_dp)
      snorm = zlange('1-norm', n, n, a, lda, rwork)
      tnorm = zlange('1-norm', n, n, b, ldb, rwork)
      stnrm = nagf_blas_dpyth(snorm, tnorm)
      Write (nout, *)
      Write (nout, *) 'Approximate error estimates for eigenvalues of (A,B)'
      Write (nout, 100)(eps*stnrm/s(i), i=1, m)
      Write (nout, *)
      Write (nout, *) &
        'Approximate error estimates for right eigenvectors of (A,B)'
      Write (nout, 100)(eps*stnrm/dif(i), i=1, m)

100   Format ((3X,1P,7E11.1))
    End Program
Full documentation of ZTGSNA


ZTGSYL example

Computational Routines: Solves the complex generalized Sylvester equation

Data

ZTGSYL Example Program Data
  4  4                                                     :Values of M and N
 (  4.0,  4.0) (  1.0,  1.0)  (  1.0,  1.0) (  2.0, -1.0)
 (  0.0,  0.0) (  2.0,  1.0) (  1.0,  1.0) (  1.0,  1.0)
 (  0.0,  0.0) (  0.0,  0.0) (  2.0, -1.0) (  1.0,  1.0)
 (  0.0,  0.0) (  0.0,  0.0) (  0.0,  0.0) (  6.0, -2.0)   :End of matrix A
 (  2.0,  0.0) (  1.0,  1.0) (  1.0,  1.0) (  3.0, -1.0)
 (  0.0,  0.0) (  1.0,  0.0) (  2.0,  1.0) (  1.0,  1.0)
 (  0.0,  0.0) (  0.0,  0.0) (  1.0,  0.0) (  1.0,  1.0)
 (  0.0,  0.0) (  0.0,  0.0) (  0.0,  0.0) (  2.0,  0.0)   :End of matrix B
 (  1.0,  1.0) (  1.0, -1.0) (  1.0,  1.0) (  1.0, -1.0)
 (  0.0,  0.0) (  6.0, -4.0) (  1.0, -1.0) (  1.0,  1.0)
 (  0.0,  0.0) (  0.0,  0.0) (  2.0,  4.0) (  1.0, -1.0)
 (  0.0,  0.0) (  0.0,  0.0) (  0.0,  0.0) (  2.0,  3.0)   :End of matrix D
 (  1.0,  0.0) (  1.0,  1.0) (  1.0, -1.0) (  1.0,  1.0)
 (  0.0,  0.0) (  2.0,  0.0) (  1.0,  1.0) (  1.0, -1.0)
 (  0.0,  0.0) (  0.0,  0.0) (  2.0,  0.0) (  1.0,  1.0)
 (  0.0,  0.0) (  0.0,  0.0) (  0.0,  0.0) (  1.0,  0.0)   :End of matrix E
 (-13.0,  9.0) (  2.0,  8.0) ( -2.0,  8.0) ( -2.0,  5.0)
 ( -9.0, -1.0) (  0.0,  5.0) ( -7.0, -3.0) ( -6.0,  0.0)
 ( -1.0,  1.0) (  4.0,  2.0) (  4.0, -5.0) (  9.0, -5.0)
 ( -6.0,  6.0) (  9.0,  1.0) ( -2.0,  4.0) ( 22.0, -8.0)  :End of matrix C
 ( -6.0,  5.0) (  4.0, -4.0) ( -3.0, 11.0) (  3.0, -7.0)
 ( -5.0, 11.0) ( 12.0, -4.0) ( -2.0,  2.0) (  0.0, 14.0)
 ( -5.0, -1.0) (  0.0,  4.0) ( -2.0, 10.0) (  3.0, -1.0)
 ( -6.0, -2.0) (  1.0,  1.0) ( -7.0, -3.0) (  4.0,  7.0)  :End of matrix F

Result

 ZTGSYL Example Program Results

 Solution matrix R
                    1                 2                 3                 4
 1  ( 1.0000, 1.0000) ( 1.0000, 1.0000) ( 1.0000, 1.0000) ( 1.0000, 1.0000)
 2  (-1.0000, 1.0000) ( 2.0000, 1.0000) (-1.0000, 1.0000) (-1.0000, 1.0000)
 3  (-1.0000, 1.0000) ( 1.0000, 1.0000) ( 3.0000, 1.0000) ( 1.0000, 1.0000)
 4  (-1.0000, 1.0000) ( 1.0000, 1.0000) (-1.0000, 1.0000) ( 4.0000, 1.0000)

 Solution matrix L
                    1                 2                 3                 4
 1  ( 4.0000, 1.0000) (-1.0000, 1.0000) ( 1.0000, 1.0000) (-1.0000, 1.0000)
 2  ( 1.0000, 1.0000) ( 3.0000, 1.0000) (-1.0000, 1.0000) ( 1.0000, 1.0000)
 3  (-1.0000, 1.0000) ( 1.0000, 1.0000) ( 2.0000, 1.0000) (-1.0000, 1.0000)
 4  ( 1.0000, 1.0000) (-1.0000, 1.0000) ( 1.0000, 1.0000) ( 1.0000, 1.0000)

 SCALE =   1.00E+00

Source

    Program ztgsyl_example

!     ZTGSYL Example Program Text

!     Copyright 2017, Numerical Algorithms Group Ltd. http://www.nag.com

!     .. Use Statements ..
      Use lapack_example_aux, Only: nagf_file_print_matrix_complex_gen_comp
      Use lapack_interfaces, Only: ztgsyl
      Use lapack_precision, Only: dp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=dp) :: dif, scale
      Integer :: i, ifail, ijob, info, lda, ldb, ldc, ldd, lde, ldf, lwork, m, &
        n
!     .. Local Arrays ..
      Complex (Kind=dp), Allocatable :: a(:, :), b(:, :), c(:, :), d(:, :), &
        e(:, :), f(:, :), work(:)
      Integer, Allocatable :: iwork(:)
      Character (1) :: clabs(1), rlabs(1)
!     .. Executable Statements ..
      Write (nout, *) 'ZTGSYL Example Program Results'
      Write (nout, *)
      Flush (nout)
!     Skip heading in data file
      Read (nin, *)
      Read (nin, *) m, n
      lda = m
      ldb = n
      ldc = m
      ldd = m
      lde = n
      ldf = m
      lwork = 1
      Allocate (a(lda,m), b(ldb,n), c(ldc,n), d(ldd,m), e(lde,n), f(ldf,n), &
        work(lwork), iwork(m+n+2))

!     Read A, B, D, E, C and F from data file

      Read (nin, *)(a(i,1:m), i=1, m)
      Read (nin, *)(b(i,1:n), i=1, n)
      Read (nin, *)(d(i,1:m), i=1, m)
      Read (nin, *)(e(i,1:n), i=1, n)
      Read (nin, *)(c(i,1:n), i=1, m)
      Read (nin, *)(f(i,1:n), i=1, m)

!     Solve the Sylvester equations
!         A*R - L*B = scale*C and D*R - L*E = scale*F
!     for R and L.

      ijob = 0

      Call ztgsyl('No transpose', ijob, m, n, a, lda, b, ldb, c, ldc, d, ldd, &
        e, lde, f, ldf, scale, dif, work, lwork, iwork, info)

      If (info>=1) Then
        Write (nout, 100)
        Write (nout, *)
        Flush (nout)
      End If

!     Print the solution matrices R and L

!     ifail: behaviour on error exit
!             =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
      ifail = 0
      Call nagf_file_print_matrix_complex_gen_comp('General', ' ', m, n, c, &
        ldc, 'Bracketed', 'F7.4', 'Solution matrix R', 'Integer', rlabs, &
        'Integer', clabs, 80, 0, ifail)

      Write (nout, *)
      Flush (nout)

      ifail = 0
      Call nagf_file_print_matrix_complex_gen_comp('General', ' ', m, n, f, &
        ldf, 'Bracketed', 'F7.4', 'Solution matrix L', 'Integer', rlabs, &
        'Integer', clabs, 80, 0, ifail)

      Write (nout, *)
      Write (nout, 110) 'SCALE = ', scale

100   Format (/, ' (A,D) and (B,E) have common or very close eigenval', &
        'ues.', /, ' Perturbed values were used to solve the equations')
110   Format (1X, A, 1P, E10.2)
    End Program
Full documentation of ZTGSYL


ZTPCON example

Computational Routines: Estimate condition number of complex triangular matrix, packed storage

Data

ZTPCON Example Program Data
  4                                                       :Value of N
  'L'                                                     :Value of UPLO
 ( 4.78, 4.56)
 ( 2.00,-0.30) (-4.11, 1.25)
 ( 2.89,-1.34) ( 2.36,-4.25) ( 4.15, 0.80)
 (-1.89, 1.15) ( 0.04,-3.69) (-0.02, 0.46) ( 0.33,-0.26)  :End of matrix A

Result

 ZTPCON Example Program Results

 Estimate of condition number =  3.74E+01

Source

    Program ztpcon_example

!     ZTPCON Example Program Text

!     Copyright 2017, Numerical Algorithms Group Ltd. http://www.nag.com

!     .. Use Statements ..
      Use lapack_interfaces, Only: ztpcon
      Use lapack_precision, Only: dp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter :: nin = 5, nout = 6
      Character (1), Parameter :: diag = 'N', norm = '1'
!     .. Local Scalars ..
      Real (Kind=dp) :: rcond
      Integer :: i, info, j, n
      Character (1) :: uplo
!     .. Local Arrays ..
      Complex (Kind=dp), Allocatable :: ap(:), work(:)
      Real (Kind=dp), Allocatable :: rwork(:)
!     .. Intrinsic Procedures ..
      Intrinsic :: epsilon
!     .. Executable Statements ..
      Write (nout, *) 'ZTPCON Example Program Results'
!     Skip heading in data file
      Read (nin, *)
      Read (nin, *) n

      Allocate (ap(n*(n+1)/2), work(2*n), rwork(n))

!     Read A from data file

      Read (nin, *) uplo
      If (uplo=='U') Then
        Read (nin, *)((ap(i+j*(j-1)/2),j=i,n), i=1, n)
      Else If (uplo=='L') Then
        Read (nin, *)((ap(i+(2*n-j)*(j-1)/2),j=1,i), i=1, n)
      End If

!     Estimate condition number
      Call ztpcon(norm, uplo, diag, n, ap, rcond, work, rwork, info)

      Write (nout, *)
      If (rcond>=epsilon(1.0E0_dp)) Then
        Write (nout, 100) 'Estimate of condition number =', 1.0E0_dp/rcond
      Else
        Write (nout, *) 'A is singular to working precision'
      End If

100   Format (1X, A, 1P, E10.2)
    End Program
Full documentation of ZTPCON


ZTPQRT example

Computational Routines: QR factorization of complex triangular-pentagonal matrix

Data

ZTPQRT Example Program Data

  6      4      2                                        : m, n and nrhs

 ( 0.96,-0.81) (-0.03, 0.96) (-0.91, 2.06) (-0.05, 0.41)
 (-0.98, 1.98) (-1.20, 0.19) (-0.66, 0.42) (-0.81, 0.56)
 ( 0.62,-0.46) ( 1.01, 0.02) ( 0.63,-0.17) (-1.11, 0.60)
 (-0.37, 0.38) ( 0.19,-0.54) (-0.98,-0.36) ( 0.22,-0.20)
 ( 0.83, 0.51) ( 0.20, 0.01) (-0.17,-0.46) ( 1.47, 1.59)
 ( 1.08,-0.28) ( 0.20,-0.12) (-0.07, 1.23) ( 0.26, 0.26) : matrix A

 (-2.09, 1.93) ( 3.26,-2.70)
 ( 3.34,-3.53) (-6.22, 1.16)
 (-4.94,-2.04) ( 7.94,-3.13)
 ( 0.17, 4.23) ( 1.04,-4.26)
 (-5.19, 3.63) (-2.31,-2.12)
 ( 0.98, 2.53) (-1.39,-4.05)                             : matrix B

Result

 ZTPQRT Example Program Results

 solution(s) for n rows
                    1                 2
 1  (-0.5091,-1.2428) ( 0.7569, 1.4384)
 2  (-2.3789, 2.8651) ( 5.1727,-3.6193)
 3  ( 1.4634,-2.2064) (-2.6613, 2.1339)
 4  ( 0.4701, 2.6964) (-2.6933, 0.2724)

 Least squares solution(s) for all rows
                    1                 2
 1  (-0.5044,-1.2179) ( 0.7629, 1.4529)
 2  (-2.4281, 2.8574) ( 5.1570,-3.6089)
 3  ( 1.4872,-2.1955) (-2.6518, 2.1203)
 4  ( 0.4537, 2.6904) (-2.7606, 0.3318)

 Square root(s) of the residual sum(s) of squares
        6.88E-02   1.87E-01

Source

    Program ztpqrt_example

!     ZTPQRT Example Program Text

!     Copyright 2017, Numerical Algorithms Group Ltd. http://www.nag.com

!     .. Use Statements ..
      Use blas_interfaces, Only: dznrm2
      Use lapack_example_aux, Only: nagf_file_print_matrix_complex_gen_comp
      Use lapack_interfaces, Only: zgemqrt, zgeqrt, ztpmqrt, ztpqrt, ztrtrs
      Use lapack_precision, Only: dp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter :: nbmax = 64, nin = 5, nout = 6
!     .. Local Scalars ..
      Integer :: i, ifail, info, j, lda, ldb, ldt, lwork, m, n, nb, nrhs
!     .. Local Arrays ..
      Complex (Kind=dp), Allocatable :: a(:, :), b(:, :), c(:, :), t(:, :), &
        work(:)
      Real (Kind=dp), Allocatable :: rnorm(:)
      Character (1) :: clabs(1), rlabs(1)
!     .. Intrinsic Procedures ..
      Intrinsic :: max, min
!     .. Executable Statements ..
      Write (nout, *) 'ZTPQRT Example Program Results'
      Write (nout, *)
      Flush (nout)
!     Skip heading in data file
      Read (nin, *)
      Read (nin, *) m, n, nrhs
      lda = m
      ldb = m
      nb = min(m, n, nbmax)
      ldt = nb
      lwork = nb*max(n, m)
      Allocate (a(lda,n), b(ldb,nrhs), c(ldb,nrhs), rnorm(nrhs), t(ldt,min(m, &
        n)), work(lwork))

!     Read A and B from data file

      Read (nin, *)(a(i,1:n), i=1, m)
      Read (nin, *)(b(i,1:nrhs), i=1, m)

      c(1:m, 1:nrhs) = b(1:m, 1:nrhs)
!     Compute the QR factorization of first n rows of A
      Call zgeqrt(n, n, nb, a, lda, t, ldt, work, info)

!     Compute C = (C1) = (Q**H)*B, storing the result in C
!                 (C2)
      Call zgemqrt('Left', 'Conjugate Transpose', n, nrhs, n, nb, a, lda, t, &
        ldt, c, ldb, work, info)

      b(1:n, 1:nrhs) = c(1:n, 1:nrhs)
!     Compute least squares solutions for first n rows by back-substitution in
!     R*X = C1
      Call ztrtrs('Upper', 'No transpose', 'Non-Unit', n, nrhs, a, lda, c, &
        ldb, info)

      If (info>0) Then
        Write (nout, *) 'The upper triangular factor, R, of A is singular, '
        Write (nout, *) 'the least squares solution could not be computed'
      Else

!       Print solution using first n rows

!       ifail: behaviour on error exit
!              =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
        ifail = 0
        Call nagf_file_print_matrix_complex_gen_comp('General', ' ', n, nrhs, &
          c, ldb, 'Bracketed', 'F7.4', 'solution(s) for n rows', 'Integer', &
          rlabs, 'Integer', clabs, 80, 0, ifail)

      End If

!     Now add the remaining rows and perform QR update
      Call ztpqrt(m-n, n, 0, nb, a, lda, a(n+1,1), lda, t, ldt, work, info)

!     Apply orthogonal transformations to C
      Call ztpmqrt('Left', 'Conjugate Transpose', m-n, nrhs, n, 0, nb, &
        a(n+1,1), lda, t, ldt, b, ldb, b(5,1), ldb, work, info)
!     Compute least squares solutions for first n rows by back-substitution in
!     R*X = C1
      Call ztrtrs('Upper', 'No transpose', 'Non-Unit', n, nrhs, a, lda, b, &
        ldb, info)

      If (info>0) Then
        Write (nout, *) 'The upper triangular factor, R, of A is singular, '
        Write (nout, *) 'the least squares solution could not be computed'
      Else

!       Print least squares solutions
        Write (nout, *)
        Flush (nout)
        ifail = 0
        Call nagf_file_print_matrix_complex_gen_comp('G', ' ', n, nrhs, b, &
          ldb, 'Bracketed', 'F7.4', 'Least squares solution(s) for all rows', &
          'Integer', rlabs, 'Integer', clabs, 80, 0, ifail)

!       Compute and print estimates of the square roots of the residual
!       sums of squares

        Do j = 1, nrhs
          rnorm(j) = dznrm2(m-n, b(n+1,j), 1)
        End Do

        Write (nout, *)
        Write (nout, *) 'Square root(s) of the residual sum(s) of squares'
        Write (nout, 100) rnorm(1:nrhs)
      End If

100   Format (5X, 1P, 7E11.2)
    End Program
Full documentation of ZTPQRT


ZTPRFS example

Computational Routines: Error bounds for solution of complex triangular system of linear equations, multiple right-hand sides, packed storage

Data

ZTPRFS Example Program Data
  4  2                                                    :Values of N and NRHS
  'L'                                                     :Value of UPLO
 ( 4.78, 4.56)
 ( 2.00,-0.30) (-4.11, 1.25)
 ( 2.89,-1.34) ( 2.36,-4.25) ( 4.15, 0.80)
 (-1.89, 1.15) ( 0.04,-3.69) (-0.02, 0.46) ( 0.33,-0.26)  :End of matrix A
 (-14.78,-32.36) (-18.02, 28.46)
 (  2.98, -2.14) ( 14.22, 15.42)
 (-20.96, 17.06) (  5.62, 35.89)
 (  9.54,  9.91) (-16.46, -1.73)                          :End of matrix B

Result

 ZTPRFS Example Program Results

 Solution(s)
                    1                 2
 1  (-5.0000,-2.0000) ( 1.0000, 5.0000)
 2  (-3.0000,-1.0000) (-2.0000,-2.0000)
 3  ( 2.0000, 1.0000) ( 3.0000, 4.0000)
 4  ( 4.0000, 3.0000) ( 4.0000,-3.0000)

 Backward errors (machine-dependent)
         3.1E-17           3.5E-17
 Estimated forward error bounds (machine-dependent)
         2.9E-14           3.2E-14

Source

    Program ztprfs_example

!     ZTPRFS Example Program Text

!     Copyright 2017, Numerical Algorithms Group Ltd. http://www.nag.com

!     .. Use Statements ..
      Use lapack_example_aux, Only: nagf_file_print_matrix_complex_gen_comp
      Use lapack_interfaces, Only: ztprfs, ztptrs
      Use lapack_precision, Only: dp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter :: nin = 5, nout = 6
      Character (1), Parameter :: diag = 'N', trans = 'N'
!     .. Local Scalars ..
      Integer :: i, ifail, info, j, ldb, ldx, n, nrhs
      Character (1) :: uplo
!     .. Local Arrays ..
      Complex (Kind=dp), Allocatable :: ap(:), b(:, :), work(:), x(:, :)
      Real (Kind=dp), Allocatable :: berr(:), ferr(:), rwork(:)
      Character (1) :: clabs(1), rlabs(1)
!     .. Executable Statements ..
      Write (nout, *) 'ZTPRFS Example Program Results'
!     Skip heading in data file
      Read (nin, *)
      Read (nin, *) n, nrhs
      ldb = n
      ldx = n
      Allocate (ap(n*(n+1)/2), b(ldb,nrhs), work(2*n), x(ldx,n), berr(nrhs), &
        ferr(nrhs), rwork(n))

!     Read A and B from data file, and copy B to X

      Read (nin, *) uplo
      If (uplo=='U') Then
        Read (nin, *)((ap(i+j*(j-1)/2),j=i,n), i=1, n)
      Else If (uplo=='L') Then
        Read (nin, *)((ap(i+(2*n-j)*(j-1)/2),j=1,i), i=1, n)
      End If
      Read (nin, *)(b(i,1:nrhs), i=1, n)
      x(1:n, 1:nrhs) = b(1:n, 1:nrhs)

!     Compute solution in the array X
      Call ztptrs(uplo, trans, diag, n, nrhs, ap, x, ldx, info)

!     Compute backward errors and estimated bounds on the
!     forward errors

      Call ztprfs(uplo, trans, diag, n, nrhs, ap, b, ldb, x, ldx, ferr, berr, &
        work, rwork, info)

!     Print solution

      Write (nout, *)
      Flush (nout)

!     ifail: behaviour on error exit
!             =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
      ifail = 0
      Call nagf_file_print_matrix_complex_gen_comp('General', ' ', n, nrhs, x, &
        ldx, 'Bracketed', 'F7.4', 'Solution(s)', 'Integer', rlabs, 'Integer', &
        clabs, 80, 0, ifail)

      Write (nout, *)
      Write (nout, *) 'Backward errors (machine-dependent)'
      Write (nout, 100) berr(1:nrhs)
      Write (nout, *) 'Estimated forward error bounds (machine-dependent)'
      Write (nout, 100) ferr(1:nrhs)

100   Format ((5X,1P,4(E11.1,7X)))
    End Program
Full documentation of ZTPRFS


ZTPTRI example

Computational Routines: Inverse of complex triangular matrix, packed storage

Data

ZTPTRI Example Program Data
  4                                                       :Value of N
  'L'                                                     :Value of UPLO
 ( 4.78, 4.56)
 ( 2.00,-0.30) (-4.11, 1.25)
 ( 2.89,-1.34) ( 2.36,-4.25) ( 4.15, 0.80)
 (-1.89, 1.15) ( 0.04,-3.69) (-0.02, 0.46) ( 0.33,-0.26)  :End of matrix A

Result

 ZTPTRI Example Program Results

 Inverse
                    1                 2                 3                 4
 1  ( 0.1095,-0.1045)
 2  ( 0.0582,-0.0411) (-0.2227,-0.0677)
 3  ( 0.0032, 0.1905) ( 0.1538,-0.2192) ( 0.2323,-0.0448)
 4  ( 0.7602, 0.2814) ( 1.6184,-1.4346) ( 0.1289,-0.2250) ( 1.8697, 1.4731)

Source

    Program ztptri_example

!     ZTPTRI Example Program Text

!     Copyright 2017, Numerical Algorithms Group Ltd. http://www.nag.com

!     .. Use Statements ..
      Use lapack_example_aux, Only: nagf_file_print_matrix_complex_packed_comp
      Use lapack_interfaces, Only: ztptri
      Use lapack_precision, Only: dp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter :: nin = 5, nout = 6
      Character (1), Parameter :: diag = 'N'
!     .. Local Scalars ..
      Integer :: i, ifail, info, j, n
      Character (1) :: uplo
!     .. Local Arrays ..
      Complex (Kind=dp), Allocatable :: ap(:)
      Character (1) :: clabs(1), rlabs(1)
!     .. Executable Statements ..
      Write (nout, *) 'ZTPTRI Example Program Results'
!     Skip heading in data file
      Read (nin, *)
      Read (nin, *) n

      Allocate (ap(n*(n+1)/2))

!     Read A from data file

      Read (nin, *) uplo
      If (uplo=='U') Then
        Read (nin, *)((ap(i+j*(j-1)/2),j=i,n), i=1, n)
      Else If (uplo=='L') Then
        Read (nin, *)((ap(i+(2*n-j)*(j-1)/2),j=1,i), i=1, n)
      End If

!     Compute inverse of A
      Call ztptri(uplo, diag, n, ap, info)

!     Print inverse

      Write (nout, *)
      Flush (nout)

!     ifail: behaviour on error exit
!             =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
      ifail = 0
      Call nagf_file_print_matrix_complex_packed_comp(uplo, diag, n, ap, &
        'Bracketed', 'F7.4', 'Inverse', 'Integer', rlabs, 'Integer', clabs, &
        80, 0, ifail)

    End Program
Full documentation of ZTPTRI


ZTPTRS example

Computational Routines: Solution of complex triangular system of linear equations, multiple right-hand sides, packed storage

Data

ZTPTRS Example Program Data
  4  2                                                    :Values of N and NRHS
  'L'                                                     :Value of UPLO
 ( 4.78, 4.56)
 ( 2.00,-0.30) (-4.11, 1.25)
 ( 2.89,-1.34) ( 2.36,-4.25) ( 4.15, 0.80)
 (-1.89, 1.15) ( 0.04,-3.69) (-0.02, 0.46) ( 0.33,-0.26)  :End of matrix A
 (-14.78,-32.36) (-18.02, 28.46)
 (  2.98, -2.14) ( 14.22, 15.42)
 (-20.96, 17.06) (  5.62, 35.89)
 (  9.54,  9.91) (-16.46, -1.73)                          :End of matrix B

Result

 ZTPTRS Example Program Results

 Solution(s)
                    1                 2
 1  (-5.0000,-2.0000) ( 1.0000, 5.0000)
 2  (-3.0000,-1.0000) (-2.0000,-2.0000)
 3  ( 2.0000, 1.0000) ( 3.0000, 4.0000)
 4  ( 4.0000, 3.0000) ( 4.0000,-3.0000)

Source

    Program ztptrs_example

!     ZTPTRS Example Program Text

!     Copyright 2017, Numerical Algorithms Group Ltd. http://www.nag.com

!     .. Use Statements ..
      Use lapack_example_aux, Only: nagf_file_print_matrix_complex_gen_comp
      Use lapack_interfaces, Only: ztptrs
      Use lapack_precision, Only: dp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter :: nin = 5, nout = 6
      Character (1), Parameter :: diag = 'N', trans = 'N'
!     .. Local Scalars ..
      Integer :: i, ifail, info, j, ldb, n, nrhs
      Character (1) :: uplo
!     .. Local Arrays ..
      Complex (Kind=dp), Allocatable :: ap(:), b(:, :)
      Character (1) :: clabs(1), rlabs(1)
!     .. Executable Statements ..
      Write (nout, *) 'ZTPTRS Example Program Results'
!     Skip heading in data file
      Read (nin, *)
      Read (nin, *) n, nrhs
      ldb = n
      Allocate (ap(n*(n+1)/2), b(ldb,nrhs))

!     Read A and B from data file

      Read (nin, *) uplo
      If (uplo=='U') Then
        Read (nin, *)((ap(i+j*(j-1)/2),j=i,n), i=1, n)
      Else If (uplo=='L') Then
        Read (nin, *)((ap(i+(2*n-j)*(j-1)/2),j=1,i), i=1, n)
      End If
      Read (nin, *)(b(i,1:nrhs), i=1, n)

!     Compute solution
      Call ztptrs(uplo, trans, diag, n, nrhs, ap, b, ldb, info)

!     Print solution

      Write (nout, *)
      Flush (nout)
      If (info==0) Then

!       ifail: behaviour on error exit
!              =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
        ifail = 0
        Call nagf_file_print_matrix_complex_gen_comp('General', ' ', n, nrhs, &
          b, ldb, 'Bracketed', 'F7.4', 'Solution(s)', 'Integer', rlabs, &
          'Integer', clabs, 80, 0, ifail)

      Else
        Write (nout, *) 'A is singular'
      End If

    End Program
Full documentation of ZTPTRS


ZTRCON example

Computational Routines: Estimate condition number of complex triangular matrix

Data

ZTRCON Example Program Data
  4                                                       :Value of N
  'L'                                                     :Value of UPLO
 ( 4.78, 4.56)
 ( 2.00,-0.30) (-4.11, 1.25)
 ( 2.89,-1.34) ( 2.36,-4.25) ( 4.15, 0.80)
 (-1.89, 1.15) ( 0.04,-3.69) (-0.02, 0.46) ( 0.33,-0.26)  :End of matrix A

Result

 ZTRCON Example Program Results

 Estimate of condition number =  3.74E+01

Source

    Program ztrcon_example

!     ZTRCON Example Program Text

!     Copyright 2017, Numerical Algorithms Group Ltd. http://www.nag.com

!     .. Use Statements ..
      Use lapack_interfaces, Only: ztrcon
      Use lapack_precision, Only: dp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter :: nin = 5, nout = 6
      Character (1), Parameter :: diag = 'N', norm = '1'
!     .. Local Scalars ..
      Real (Kind=dp) :: rcond
      Integer :: i, info, lda, n
      Character (1) :: uplo
!     .. Local Arrays ..
      Complex (Kind=dp), Allocatable :: a(:, :), work(:)
      Real (Kind=dp), Allocatable :: rwork(:)
!     .. Intrinsic Procedures ..
      Intrinsic :: epsilon
!     .. Executable Statements ..
      Write (nout, *) 'ZTRCON Example Program Results'
!     Skip heading in data file
      Read (nin, *)
      Read (nin, *) n
      lda = n
      Allocate (a(lda,n), work(2*n), rwork(n))

!     Read A from data file

      Read (nin, *) uplo
      If (uplo=='U') Then
        Read (nin, *)(a(i,i:n), i=1, n)
      Else If (uplo=='L') Then
        Read (nin, *)(a(i,1:i), i=1, n)
      End If

!     Estimate condition number
      Call ztrcon(norm, uplo, diag, n, a, lda, rcond, work, rwork, info)

      Write (nout, *)
      If (rcond>=epsilon(1.0E0_dp)) Then
        Write (nout, 100) 'Estimate of condition number =', 1.0_dp/rcond
      Else
        Write (nout, *) 'A is singular to working precision'
      End If

100   Format (1X, A, 1P, E10.2)
    End Program
Full documentation of ZTRCON


ZTREXC example

Computational Routines: Reorder Schur factorization of complex matrix using unitary similarity transformation

Data

ZTREXC Example Program Data
  4                                                        :Value of N
 (-6.00,-7.00) ( 0.36,-0.36) (-0.19, 0.48) ( 0.88,-0.25)
 ( 0.00, 0.00) (-5.00, 2.00) (-0.03,-0.72) (-0.23, 0.13)
 ( 0.00, 0.00) ( 0.00, 0.00) ( 8.00,-1.00) ( 0.94, 0.53)
 ( 0.00, 0.00) ( 0.00, 0.00) ( 0.00, 0.00) ( 3.00,-4.00)   :End of matrix T
  1  4                                             :Values of IFST and ILST

Result

 ZTREXC Example Program Results

 Reordered Schur form
                    1                 2                 3                 4
 1  (-5.0000, 2.0000) (-0.1574, 0.7143) ( 0.1781,-0.1913) ( 0.3950, 0.3861)
 2  ( 0.0000, 0.0000) ( 8.0000,-1.0000) ( 1.0742, 0.1447) ( 0.2515,-0.3397)
 3  ( 0.0000, 0.0000) ( 0.0000, 0.0000) ( 3.0000,-4.0000) ( 0.2264, 0.8962)
 4  ( 0.0000, 0.0000) ( 0.0000, 0.0000) ( 0.0000, 0.0000) (-6.0000,-7.0000)

Source

    Program ztrexc_example

!     ZTREXC Example Program Text

!     Copyright 2017, Numerical Algorithms Group Ltd. http://www.nag.com

!     .. Use Statements ..
      Use lapack_example_aux, Only: nagf_file_print_matrix_complex_gen_comp
      Use lapack_interfaces, Only: ztrexc
      Use lapack_precision, Only: dp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter :: nin = 5, nout = 6
!     .. Local Scalars ..
      Integer :: i, ifail, ifst, ilst, info, ldq, ldt, n
!     .. Local Arrays ..
      Complex (Kind=dp), Allocatable :: q(:, :), t(:, :)
      Character (1) :: clabs(1), rlabs(1)
!     .. Executable Statements ..
      Write (nout, *) 'ZTREXC Example Program Results'
      Write (nout, *)
      Flush (nout)
!     Skip heading in data file
      Read (nin, *)
      Read (nin, *) n
      ldq = 1
      ldt = n
      Allocate (q(ldq,1), t(ldt,n))

!     Read T from data file

      Read (nin, *)(t(i,1:n), i=1, n)

!     Read the row indices

      Read (nin, *) ifst, ilst

!     Reorder the Schur factor T

      Call ztrexc('No update', n, t, ldt, q, ldq, ifst, ilst, info)
      If (info/=0) Then
        Write (nout, 100) info, ilst
        Write (nout, *)
        Flush (nout)
      End If

!     Print reordered Schur form

!     ifail: behaviour on error exit
!             =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
      ifail = 0
      Call nagf_file_print_matrix_complex_gen_comp('General', ' ', n, n, t, &
        ldt, 'Bracketed', 'F7.4', 'Reordered Schur form', 'Integer', rlabs, &
        'Integer', clabs, 80, 0, ifail)

100   Format (' Reordering could not be completed. INFO = ', I3, ' ILST = ', &
        I5)
    End Program
Full documentation of ZTREXC


ZTRRFS example

Computational Routines: Error bounds for solution of complex triangular system of linear equations, multiple right-hand sides

Data

ZTRRFS Example Program Data
  4  2                                                    :Values of N and NRHS
  'L'                                                     :Value of UPLO
 ( 4.78, 4.56)
 ( 2.00,-0.30) (-4.11, 1.25)
 ( 2.89,-1.34) ( 2.36,-4.25) ( 4.15, 0.80)
 (-1.89, 1.15) ( 0.04,-3.69) (-0.02, 0.46) ( 0.33,-0.26)  :End of matrix A
 (-14.78,-32.36) (-18.02, 28.46)
 (  2.98, -2.14) ( 14.22, 15.42)
 (-20.96, 17.06) (  5.62, 35.89)
 (  9.54,  9.91) (-16.46, -1.73)                          :End of matrix B

Result

 ZTRRFS Example Program Results

 Solution(s)
                    1                 2
 1  (-5.0000,-2.0000) ( 1.0000, 5.0000)
 2  (-3.0000,-1.0000) (-2.0000,-2.0000)
 3  ( 2.0000, 1.0000) ( 3.0000, 4.0000)
 4  ( 4.0000, 3.0000) ( 4.0000,-3.0000)

 Backward errors (machine-dependent)
         3.1E-17           3.5E-17
 Estimated forward error bounds (machine-dependent)
         2.9E-14           3.2E-14

Source

    Program ztrrfs_example

!     ZTRRFS Example Program Text

!     Copyright 2017, Numerical Algorithms Group Ltd. http://www.nag.com

!     .. Use Statements ..
      Use lapack_example_aux, Only: nagf_file_print_matrix_complex_gen_comp
      Use lapack_interfaces, Only: ztrrfs, ztrtrs
      Use lapack_precision, Only: dp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter :: nin = 5, nout = 6
      Character (1), Parameter :: diag = 'N', trans = 'N'
!     .. Local Scalars ..
      Integer :: i, ifail, info, lda, ldb, ldx, n, nrhs
      Character (1) :: uplo
!     .. Local Arrays ..
      Complex (Kind=dp), Allocatable :: a(:, :), b(:, :), work(:), x(:, :)
      Real (Kind=dp), Allocatable :: berr(:), ferr(:), rwork(:)
      Character (1) :: clabs(1), rlabs(1)
!     .. Executable Statements ..
      Write (nout, *) 'ZTRRFS Example Program Results'
!     Skip heading in data file
      Read (nin, *)
      Read (nin, *) n, nrhs
      lda = n
      ldb = n
      ldx = n
      Allocate (a(lda,n), b(ldb,nrhs), work(2*n), x(ldx,n), berr(nrhs), &
        ferr(nrhs), rwork(n))

!     Read A and B from data file, and copy B to X

      Read (nin, *) uplo
      If (uplo=='U') Then
        Read (nin, *)(a(i,i:n), i=1, n)
      Else If (uplo=='L') Then
        Read (nin, *)(a(i,1:i), i=1, n)
      End If
      Read (nin, *)(b(i,1:nrhs), i=1, n)
      x(1:n, 1:nrhs) = b(1:n, 1:nrhs)

!     Compute solution in the array X
      Call ztrtrs(uplo, trans, diag, n, nrhs, a, lda, x, ldx, info)

!     Compute backward errors and estimated bounds on the
!     forward errors

      Call ztrrfs(uplo, trans, diag, n, nrhs, a, lda, b, ldb, x, ldx, ferr, &
        berr, work, rwork, info)

!     Print solution

      Write (nout, *)
      Flush (nout)

!     ifail: behaviour on error exit
!             =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
      ifail = 0
      Call nagf_file_print_matrix_complex_gen_comp('General', ' ', n, nrhs, x, &
        ldx, 'Bracketed', 'F7.4', 'Solution(s)', 'Integer', rlabs, 'Integer', &
        clabs, 80, 0, ifail)

      Write (nout, *)
      Write (nout, *) 'Backward errors (machine-dependent)'
      Write (nout, 100) berr(1:nrhs)
      Write (nout, *) 'Estimated forward error bounds (machine-dependent)'
      Write (nout, 100) ferr(1:nrhs)

100   Format ((5X,1P,4(E11.1,7X)))
    End Program
Full documentation of ZTRRFS


ZTRSEN example

Computational Routines: Reorder Schur factorization of complex matrix, form orthonormal basis of right invariant subspace for selected eigenvalues, with estimates of sensitivities

Data

ZTRSEN Example Program Data
  4                                                     :Value of N
 (-6.0004,-6.9999) ( 0.3637,-0.3656) (-0.1880, 0.4787) ( 0.8785,-0.2539)
 ( 0.0000, 0.0000) (-5.0000, 2.0060) (-0.0307,-0.7217) (-0.2290, 0.1313)
 ( 0.0000, 0.0000) ( 0.0000, 0.0000) ( 7.9982,-0.9964) ( 0.9357, 0.5359)
 ( 0.0000, 0.0000) ( 0.0000, 0.0000) ( 0.0000, 0.0000) ( 3.0023,-3.9998)
                                                        :End of matrix T
 (-0.8347,-0.1364) (-0.0628, 0.3806) ( 0.2765,-0.0846) ( 0.0633,-0.2199)
 ( 0.0664,-0.2968) ( 0.2365, 0.5240) (-0.5877,-0.4208) ( 0.0835, 0.2183)
 (-0.0362,-0.3215) ( 0.3143,-0.5473) ( 0.0576,-0.5736) ( 0.0057,-0.4058)
 ( 0.0086, 0.2958) (-0.3416,-0.0757) (-0.1900,-0.1600) ( 0.8327,-0.1868)
                                                        :End of matrix Q
  T   F   F   T                                         :End of SELECT

Result

 ZTRSEN Example Program Results

 Matrix A created from Q*T*Q^T
                    1                 2                 3                 4
 1  (-3.9702,-5.0406) (-4.1108, 3.7002) (-0.3403, 1.0098) ( 1.2899,-0.8590)
 2  ( 0.3397,-1.5006) ( 1.5201,-0.4301) ( 1.8797,-5.3804) ( 3.3606, 0.6498)
 3  ( 3.3101,-3.8506) ( 2.4996, 3.4504) ( 0.8802,-1.0802) ( 0.6401,-1.4800)
 4  (-1.0999, 0.8199) ( 1.8103,-1.5905) ( 3.2502, 1.3297) ( 1.5701,-3.4397)

 Condition number estimate of the selected cluster of eigenvalues =   1.02E+00

 Condition number estimate of the specified invariant subspace    =   1.82E-01

Source

    Program ztrsen_example

!     ZTRSEN Example Program Text

!     Copyright 2017, Numerical Algorithms Group Ltd. http://www.nag.com

!     .. Use Statements ..
      Use blas_interfaces, Only: zgemm
      Use lapack_example_aux, Only: nagf_file_print_matrix_complex_gen_comp
      Use lapack_interfaces, Only: zlange, ztrsen
      Use lapack_precision, Only: dp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter :: nin = 5, nout = 6
!     .. Local Scalars ..
      Complex (Kind=dp) :: alpha, beta
      Real (Kind=dp) :: norm, s, sep
      Integer :: i, ifail, info, lda, ldc, ldq, ldt, lwork, m, n
!     .. Local Arrays ..
      Complex (Kind=dp), Allocatable :: a(:, :), c(:, :), q(:, :), t(:, :), &
        w(:), work(:)
      Real (Kind=dp) :: rwork(1)
      Logical, Allocatable :: select(:)
      Character (1) :: clabs(1), rlabs(1)
!     .. Intrinsic Procedures ..
      Intrinsic :: cmplx, epsilon
!     .. Executable Statements ..
      Write (nout, *) 'ZTRSEN Example Program Results'
      Write (nout, *)
      Flush (nout)
!     Skip heading in data file
      Read (nin, *)
      Read (nin, *) n
      ldc = n
      lda = n
      ldq = n
      ldt = n
      lwork = (n*n)/2
      Allocate (a(lda,n), c(ldc,n), q(ldq,n), t(ldt,n), w(n), work(lwork), &
        select(n))

!     Read T, Q and the logical array SELECT from data file

      Read (nin, *)(t(i,1:n), i=1, n)
      Read (nin, *)
      Read (nin, *)(q(i,1:n), i=1, n)
      Read (nin, *)
      Read (nin, *) select(1:n)

!     Compute Q * T * Q**T to find  A
      alpha = cmplx(1, kind=dp)
      beta = cmplx(0, kind=dp)
      Call zgemm('N', 'N', n, n, n, alpha, q, ldq, t, ldt, beta, c, ldc)
      Call zgemm('N', 'C', n, n, n, alpha, c, ldc, q, ldq, beta, a, lda)

!     Print Matrix A, as computed from Q * T * Q**T
!     ifail: behaviour on error exit
!            =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
      ifail = 0
      Call nagf_file_print_matrix_complex_gen_comp('General', ' ', n, n, a, &
        lda, 'Bracketed', 'F7.4', 'Matrix A created from Q*T*Q^T', 'Integer', &
        rlabs, 'Integer', clabs, 80, 0, ifail)

      Write (nout, *)
      Flush (nout)

!     Reorder the Schur factor T and update the matrix Q to obtain TT and QT

      Call ztrsen('Both', 'Vectors', select, n, t, ldt, q, ldq, w, m, s, sep, &
        work, lwork, info)

!     Compute (Q * T * Q^H) - (QT * TT * QT^H) and store in A,
!     i.e. the difference between reconstructed A using Schur and reordered
!          Schur decompositions.
      alpha = cmplx(1, kind=dp)
      beta = cmplx(0, kind=dp)
      Call zgemm('N', 'N', n, n, n, alpha, q, ldq, t, ldt, beta, c, ldc)
      alpha = cmplx(-1, kind=dp)
      beta = cmplx(1, kind=dp)
      Call zgemm('N', 'C', n, n, n, alpha, c, ldc, q, ldq, beta, a, lda)

!     Find norm of difference matrix and print warning if it is too large
      norm = zlange('O', lda, n, a, lda, rwork)
      If (norm>epsilon(1.0E0_dp)**0.5_dp) Then
        Write (nout, *) 'Norm of A - (QT * TT * QT^H) is much greater than 0.'
        Write (nout, *) 'Schur factorization has failed.'
      Else
!       Print condition estimates
        Write (nout, 100) 'Condition number estimate', &
          ' of the selected cluster of eigenvalues = ', 1.0_dp/s
        Write (nout, *)
        Write (nout, 100) 'Condition number estimate of the specified ', &
          'invariant subspace    = ', 1.0_dp/sep
      End If

100   Format (1X, A, A, 1P, E10.2)
    End Program
Full documentation of ZTRSEN


ZTRSNA example

Computational Routines: Estimates of sensitivities of selected eigenvalues and eigenvectors of complex upper triangular matrix

Data

ZTRSNA Example Program Data
  4                                                             :Value of N
 (-6.0004,-6.9999) ( 0.3637,-0.3656) (-0.1880, 0.4787) ( 0.8785,-0.2539)
 ( 0.0000, 0.0000) (-5.0000, 2.0060) (-0.0307,-0.7217) (-0.2290, 0.1313)
 ( 0.0000, 0.0000) ( 0.0000, 0.0000) ( 7.9982,-0.9964) ( 0.9357, 0.5359)
 ( 0.0000, 0.0000) ( 0.0000, 0.0000) ( 0.0000, 0.0000) ( 3.0023,-3.9998)
                                                                :End of matrix T

Result

 ZTRSNA Example Program Results

 S
       9.9E-01    1.0E+00    9.8E-01    9.8E-01

 SEP
       8.4E+00    8.0E+00    5.8E+00    5.8E+00

 Approximate error estimates for eigenvalues of T (machine-dependent)
       2.1E-15    2.1E-15    2.1E-15    2.1E-15

 Approximate error estimates for right eigenvectors of T (machine-dependent)
       2.5E-16    2.6E-16    3.5E-16    3.5E-16

Source

    Program ztrsna_example

!     ZTRSNA Example Program Text

!     Copyright 2017, Numerical Algorithms Group Ltd. http://www.nag.com

!     .. Use Statements ..
      Use lapack_interfaces, Only: zlange, ztrevc, ztrsna
      Use lapack_precision, Only: dp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=dp) :: eps, tnorm
      Integer :: i, info, ldt, ldvl, ldvr, ldwork, m, n
!     .. Local Arrays ..
      Complex (Kind=dp), Allocatable :: t(:, :), vl(:, :), vr(:, :), &
        work(:, :)
      Real (Kind=dp), Allocatable :: rwork(:), s(:), sep(:)
      Logical :: select(1)
!     .. Intrinsic Procedures ..
      Intrinsic :: epsilon
!     .. Executable Statements ..
      Write (nout, *) 'ZTRSNA Example Program Results'
      Write (nout, *)
!     Skip heading in data file
      Read (nin, *)
      Read (nin, *) n
      ldt = n
      ldvl = n
      ldvr = n
      ldwork = n
      Allocate (t(ldt,n), vl(ldvl,n), vr(ldvr,n), work(ldwork,n+1), rwork(n), &
        s(n), sep(n))

!     Read T from data file

      Read (nin, *)(t(i,1:n), i=1, n)

!     Calculate the left and right eigenvectors of T

      Call ztrevc('Both', 'All', select, n, t, ldt, vl, ldvl, vr, ldvr, n, m, &
        work, rwork, info)

!     Estimate condition numbers for all the eigenvalues and right
!     eigenvectors of T

      Call ztrsna('Both', 'All', select, n, t, ldt, vl, ldvl, vr, ldvr, s, &
        sep, n, m, work, ldwork, rwork, info)

!     Print condition numbers of eigenvalues and right eigenvectors

      Write (nout, *) 'S'
      Write (nout, 100) s(1:m)
      Write (nout, *)
      Write (nout, *) 'SEP'
      Write (nout, 100) sep(1:m)

!     Calculate approximate error estimates (using the 1-norm)

      eps = epsilon(1.0E0_dp)
      tnorm = zlange('1-norm', n, n, t, ldt, rwork)
      Write (nout, *)
      Write (nout, *) 'Approximate error estimates for eigenvalues ', &
        'of T (machine-dependent)'
      Write (nout, 100)(eps*tnorm/s(i), i=1, m)
      Write (nout, *)
      Write (nout, *) 'Approximate error estimates for right ', &
        'eigenvectors of T (machine-dependent)'
      Write (nout, 100)(eps*tnorm/sep(i), i=1, m)

100   Format ((3X,1P,7E11.1))
    End Program
Full documentation of ZTRSNA


ZTRSYL example

Computational Routines: Solve complex Sylvester matrix equation AX + XB = C, A and B are upper triangular or conjugate-transposes

Data

ZTRSYL Example Program Data
  4  4                                                     :Values of M and N
 (-6.00,-7.00) ( 0.36,-0.36) (-0.19, 0.48) ( 0.88,-0.25)
 ( 0.00, 0.00) (-5.00, 2.00) (-0.03,-0.72) (-0.23, 0.13)
 ( 0.00, 0.00) ( 0.00, 0.00) ( 8.00,-1.00) ( 0.94, 0.53)
 ( 0.00, 0.00) ( 0.00, 0.00) ( 0.00, 0.00) ( 3.00,-4.00)   :End of matrix A
 ( 0.50,-0.20) (-0.29,-0.16) (-0.37, 0.84) (-0.55, 0.73)
 ( 0.00, 0.00) (-0.40, 0.90) ( 0.06, 0.22) (-0.43, 0.17)
 ( 0.00, 0.00) ( 0.00, 0.00) (-0.90,-0.10) (-0.89,-0.42)
 ( 0.00, 0.00) ( 0.00, 0.00) ( 0.00, 0.00) ( 0.30,-0.70)   :End of matrix B
 ( 0.63, 0.35) ( 0.45,-0.56) ( 0.08,-0.14) (-0.17,-0.23)
 (-0.17, 0.09) (-0.07,-0.31) ( 0.27,-0.54) ( 0.35, 1.21)
 (-0.93,-0.44) (-0.33,-0.35) ( 0.41,-0.03) ( 0.57, 0.84)
 ( 0.54, 0.25) (-0.62,-0.05) (-0.52,-0.13) ( 0.11,-0.08)   :End of matrix C

Result

 ZTRSYL Example Program Results

 Solution Matrix
                      1                   2                   3
 1  ( -0.0611,  0.0249) ( -0.0031,  0.0798) ( -0.0062,  0.0165)
 2  (  0.0215, -0.0003) ( -0.0155,  0.0570) ( -0.0665,  0.0718)
 3  ( -0.0949, -0.0785) ( -0.0415, -0.0298) (  0.0357,  0.0244)
 4  (  0.0281,  0.1052) ( -0.0970, -0.1214) ( -0.0271, -0.0940)

                      4
 1  (  0.0054, -0.0063)
 2  (  0.0290, -0.2636)
 3  (  0.0284,  0.1108)
 4  (  0.0402,  0.0048)

Source

    Program ztrsyl_example

!     ZTRSYL Example Program Text

!     Copyright 2017, Numerical Algorithms Group Ltd. http://www.nag.com

!     .. Use Statements ..
      Use lapack_example_aux, Only: nagf_file_print_matrix_complex_gen_comp
      Use lapack_interfaces, Only: ztrsyl
      Use lapack_precision, Only: dp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=dp) :: scale
      Integer :: i, ifail, info, lda, ldb, ldc, m, n
!     .. Local Arrays ..
      Complex (Kind=dp), Allocatable :: a(:, :), b(:, :), c(:, :)
      Character (1) :: clabs(1), rlabs(1)
!     .. Executable Statements ..
      Write (nout, *) 'ZTRSYL Example Program Results'
      Write (nout, *)
      Flush (nout)
!     Skip heading in data file
      Read (nin, *)
      Read (nin, *) m, n
      lda = m
      ldb = n
      ldc = m
      Allocate (a(lda,m), b(ldb,n), c(ldc,n))

!     Read A, B and C from data file

      Read (nin, *)(a(i,1:m), i=1, m)
      Read (nin, *)(b(i,1:n), i=1, n)
      Read (nin, *)(c(i,1:n), i=1, m)

!     Solve the Sylvester equation A*X + X*B = C for X
      Call ztrsyl('No transpose', 'No transpose', 1, m, n, a, lda, b, ldb, c, &
        ldc, scale, info)
      If (info>=1) Then
        Write (nout, 100)
        Write (nout, *)
        Flush (nout)
      End If

!     Print X
!     ifail: behaviour on error exit
!             =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
      ifail = 0
      Call nagf_file_print_matrix_complex_gen_comp('General', ' ', m, n, c, &
        ldc, 'Bracketed', 'F8.4', 'Solution Matrix', 'I', rlabs, 'I', clabs, &
        80, 0, ifail)

100   Format (/, ' A and B have common or very close eigenvalues.', /, ' Pe', &
        'rturbed values were used to solve the equations')
    End Program
Full documentation of ZTRSYL


ZTRTRI example

Computational Routines: Inverse of complex triangular matrix

Data

ZTRTRI Example Program Data
  4                                                       :Value of N
  'L'                                                     :Value of UPLO
 ( 4.78, 4.56)
 ( 2.00,-0.30) (-4.11, 1.25)
 ( 2.89,-1.34) ( 2.36,-4.25) ( 4.15, 0.80)
 (-1.89, 1.15) ( 0.04,-3.69) (-0.02, 0.46) ( 0.33,-0.26)  :End of matrix A

Result

 ZTRTRI Example Program Results

 Inverse
                    1                 2                 3                 4
 1  ( 0.1095,-0.1045)
 2  ( 0.0582,-0.0411) (-0.2227,-0.0677)
 3  ( 0.0032, 0.1905) ( 0.1538,-0.2192) ( 0.2323,-0.0448)
 4  ( 0.7602, 0.2814) ( 1.6184,-1.4346) ( 0.1289,-0.2250) ( 1.8697, 1.4731)

Source

    Program ztrtri_example

!     ZTRTRI Example Program Text

!     Copyright 2017, Numerical Algorithms Group Ltd. http://www.nag.com

!     .. Use Statements ..
      Use lapack_example_aux, Only: nagf_file_print_matrix_complex_gen_comp
      Use lapack_interfaces, Only: ztrtri
      Use lapack_precision, Only: dp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter :: nin = 5, nout = 6
      Character (1), Parameter :: diag = 'N'
!     .. Local Scalars ..
      Integer :: i, ifail, info, lda, n
      Character (1) :: uplo
!     .. Local Arrays ..
      Complex (Kind=dp), Allocatable :: a(:, :)
      Character (1) :: clabs(1), rlabs(1)
!     .. Executable Statements ..
      Write (nout, *) 'ZTRTRI Example Program Results'
!     Skip heading in data file
      Read (nin, *)
      Read (nin, *) n
      lda = n
      Allocate (a(lda,n))

!     Read A from data file

      Read (nin, *) uplo
      If (uplo=='U') Then
        Read (nin, *)(a(i,i:n), i=1, n)
      Else If (uplo=='L') Then
        Read (nin, *)(a(i,1:i), i=1, n)
      End If

!     Compute inverse of A
      Call ztrtri(uplo, diag, n, a, lda, info)

!     Print inverse

      Write (nout, *)
      Flush (nout)

!     ifail: behaviour on error exit
!             =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
      ifail = 0
      Call nagf_file_print_matrix_complex_gen_comp(uplo, diag, n, n, a, lda, &
        'Bracketed', 'F7.4', 'Inverse', 'Integer', rlabs, 'Integer', clabs, &
        80, 0, ifail)

    End Program
Full documentation of ZTRTRI


ZTRTRS example

Computational Routines: Solution of complex triangular system of linear equations, multiple right-hand sides

Data

ZTRTRS Example Program Data
  4  2                                                    :Values of N and NRHS
  'L'                                                     :Value of UPLO
 ( 4.78, 4.56)
 ( 2.00,-0.30) (-4.11, 1.25)
 ( 2.89,-1.34) ( 2.36,-4.25) ( 4.15, 0.80)
 (-1.89, 1.15) ( 0.04,-3.69) (-0.02, 0.46) ( 0.33,-0.26)  :End of matrix A
 (-14.78,-32.36) (-18.02, 28.46)
 (  2.98, -2.14) ( 14.22, 15.42)
 (-20.96, 17.06) (  5.62, 35.89)
 (  9.54,  9.91) (-16.46, -1.73)                          :End of matrix B

Result

 ZTRTRS Example Program Results

 Solution(s)
                    1                 2
 1  (-5.0000,-2.0000) ( 1.0000, 5.0000)
 2  (-3.0000,-1.0000) (-2.0000,-2.0000)
 3  ( 2.0000, 1.0000) ( 3.0000, 4.0000)
 4  ( 4.0000, 3.0000) ( 4.0000,-3.0000)

Source

    Program ztrtrs_example

!     ZTRTRS Example Program Text

!     Copyright 2017, Numerical Algorithms Group Ltd. http://www.nag.com

!     .. Use Statements ..
      Use lapack_example_aux, Only: nagf_file_print_matrix_complex_gen_comp
      Use lapack_interfaces, Only: ztrtrs
      Use lapack_precision, Only: dp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter :: nin = 5, nout = 6
      Character (1), Parameter :: diag = 'N', trans = 'N'
!     .. Local Scalars ..
      Integer :: i, ifail, info, lda, ldb, n, nrhs
      Character (1) :: uplo
!     .. Local Arrays ..
      Complex (Kind=dp), Allocatable :: a(:, :), b(:, :)
      Character (1) :: clabs(1), rlabs(1)
!     .. Executable Statements ..
      Write (nout, *) 'ZTRTRS Example Program Results'
!     Skip heading in data file
      Read (nin, *)
      Read (nin, *) n, nrhs
      lda = n
      ldb = n
      Allocate (a(lda,n), b(ldb,nrhs))

!     Read A and B from data file

      Read (nin, *) uplo
      If (uplo=='U') Then
        Read (nin, *)(a(i,i:n), i=1, n)
      Else If (uplo=='L') Then
        Read (nin, *)(a(i,1:i), i=1, n)
      End If
      Read (nin, *)(b(i,1:nrhs), i=1, n)

!     Compute solution
      Call ztrtrs(uplo, trans, diag, n, nrhs, a, lda, b, ldb, info)

!     Print solution

      Write (nout, *)
      Flush (nout)
      If (info==0) Then

!       ifail: behaviour on error exit
!              =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
        ifail = 0
        Call nagf_file_print_matrix_complex_gen_comp('General', ' ', n, nrhs, &
          b, ldb, 'Bracketed', 'F7.4', 'Solution(s)', 'Integer', rlabs, &
          'Integer', clabs, 80, 0, ifail)

      Else
        Write (nout, *) 'A is singular'
      End If

    End Program
Full documentation of ZTRTRS


ZTZRZF example

Computational Routines: Reduces a complex upper trapezoidal matrix to upper triangular form

Data

ZTZRZF Example Program Data

   5             4             2                 :Values of M, N and NRHS

 ( 0.47,-0.34) (-0.40, 0.54) ( 0.60, 0.01) ( 0.80,-1.02)
 (-0.32,-0.23) (-0.05, 0.20) (-0.26,-0.44) (-0.43, 0.17)
 ( 0.35,-0.60) (-0.52,-0.34) ( 0.87,-0.11) (-0.34,-0.09)
 ( 0.89, 0.71) (-0.45,-0.45) (-0.02,-0.57) ( 1.14,-0.78)
 (-0.19, 0.06) ( 0.11,-0.85) ( 1.44, 0.80) ( 0.07, 1.14) :End of matrix A

 (-1.08,-2.59) ( 2.22, 2.35)
 (-2.61,-1.49) ( 1.62,-1.48)
 ( 3.13,-3.61) ( 1.65, 3.43)
 ( 7.33,-8.01) (-0.98, 3.08)
 ( 9.12, 7.63) (-2.84, 2.78)                             :End of matrix B

Result

 ZTZRZF Example Program Results

 Tolerance used to estimate the rank of A
      1.00E-02
 Estimated rank of A
      3

 Least squares solution(s)
                    1                 2
 1  ( 1.1669,-3.3224) (-0.5023, 1.8323)
 2  ( 1.3486, 5.5027) (-1.4418,-1.6465)
 3  ( 4.1764, 2.3435) ( 0.2908, 1.4900)
 4  ( 0.6467, 0.0107) (-0.2453, 0.3951)

 Square root(s) of the residual sum(s) of squares
      2.51E-01   8.10E-02

Source

    Program ztzrzf_example

!     ZTZRZF Example Program Text

!     Copyright 2017, Numerical Algorithms Group Ltd. http://www.nag.com

!     .. Use Statements ..
      Use blas_interfaces, Only: dznrm2, ztrsm
      Use lapack_example_aux, Only: nagf_file_print_matrix_complex_gen_comp
      Use lapack_interfaces, Only: zgeqp3, ztzrzf, zunmqr, zunmrz
      Use lapack_precision, Only: dp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Complex (Kind=dp), Parameter :: one = (1.0_dp, 0.0_dp)
      Complex (Kind=dp), Parameter :: zero = (0.0_dp, 0.0_dp)
      Integer, Parameter :: inc1 = 1, nb = 64, nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=dp) :: tol
      Integer :: i, ifail, info, j, k, lda, ldb, lwork, m, n, nrhs
!     .. Local Arrays ..
      Complex (Kind=dp), Allocatable :: a(:, :), b(:, :), tau(:), work(:)
      Real (Kind=dp), Allocatable :: rnorm(:), rwork(:)
      Integer, Allocatable :: jpvt(:)
      Character (1) :: clabs(1), rlabs(1)
!     .. Intrinsic Procedures ..
      Intrinsic :: abs
!     .. Executable Statements ..
      Write (nout, *) 'ZTZRZF Example Program Results'
      Write (nout, *)
!     Skip heading in data file
      Read (nin, *)
      Read (nin, *) m, n, nrhs
      lda = m
      ldb = m
      lwork = (n+1)*nb
      Allocate (a(lda,n), b(ldb,nrhs), tau(n), work(lwork), rnorm(n), &
        rwork(2*n), jpvt(n))

!     Read A and B from data file

      Read (nin, *)(a(i,1:n), i=1, m)
      Read (nin, *)(b(i,1:nrhs), i=1, m)

!     Initialize JPVT to be zero so that all columns are free

      jpvt(1:n) = 0

!     Compute the QR factorization of A with column pivoting as
!     A = Q*(R11 R12)*(P**T)
!            ( 0  R22)
      Call zgeqp3(m, n, a, lda, jpvt, tau, work, lwork, rwork, info)

!     Compute C = (C1) = (Q**H)*B, storing the result in B
!                  (C2)
      Call zunmqr('Left', 'Conjugate transpose', m, nrhs, n, a, lda, tau, b, &
        ldb, work, lwork, info)

!     Choose TOL to reflect the relative accuracy of the input data

      tol = 0.01_dp

!     Determine and print the rank, K, of R relative to TOL

loop: Do k = 1, n
        If (abs(a(k,k))<=tol*abs(a(1,1))) Then
          Exit loop
        End If
      End Do loop
      k = k - 1

      Write (nout, *) 'Tolerance used to estimate the rank of A'
      Write (nout, 100) tol
      Write (nout, *) 'Estimated rank of A'
      Write (nout, 110) k
      Write (nout, *)
      Flush (nout)

!     Compute the RZ factorization of the K by K part of R as
!     (R1 R2) = (T 0)*Z
      Call ztzrzf(k, n, a, lda, tau, work, lwork, info)

!     Compute least squares solutions of triangular problems by
!     back substitution in T*Y1 = C1, storing the result in B
      Call ztrsm('Left', 'Upper', 'No transpose', 'Non-Unit', k, nrhs, one, a, &
        lda, b, ldb)

!     Compute estimates of the square roots of the residual sums of
!     squares (2-norm of each of the columns of C2)

      Do j = 1, nrhs
        rnorm(j) = dznrm2(m-k, b(k+1,j), inc1)
      End Do

!     Set the remaining elements of the solutions to zero (to give
!     the minimum-norm solutions), Y2 = 0

      b(k+1:n, 1:nrhs) = zero

!     Form W = (Z**H)*Y
      Call zunmrz('Left', 'Conjugate transpose', n, nrhs, k, n-k, a, lda, tau, &
        b, ldb, work, lwork, info)

!     Permute the least squares solutions stored in B to give X = P*W

      Do j = 1, nrhs
        Do i = 1, n
          work(jpvt(i)) = b(i, j)
        End Do
        b(1:n, j) = work(1:n)
      End Do

!     Print least squares solutions

!     ifail: behaviour on error exit
!             =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
      ifail = 0
      Call nagf_file_print_matrix_complex_gen_comp('General', ' ', n, nrhs, b, &
        ldb, 'Bracketed', 'F7.4', 'Least squares solution(s)', 'Integer', &
        rlabs, 'Integer', clabs, 80, 0, ifail)

!     Print the square roots of the residual sums of squares

      Write (nout, *)
      Write (nout, *) 'Square root(s) of the residual sum(s) of squares'
      Write (nout, 100) rnorm(1:nrhs)

100   Format (3X, 1P, 7E11.2)
110   Format (1X, I6)
    End Program
Full documentation of ZTZRZF


ZUNCSD example

Computational Routines: Computes the CS decomposition of a unitary matrix partitioned into four complex submatrices

Data

ZUNCSD Example Program Data

   6        2       4        : m    p    q

 ( -1.3038E-02, -3.2597E-01)
 (  4.2764E-01, -6.2582E-01)
 ( -3.2597E-01,  1.6428E-01)
 (  1.5906E-01, -5.2151E-03)
 ( -1.7210E-01, -1.3027E-02)
 ( -2.6336E-01, -2.4772E-01) : column 1 of unitary matrix X

 ( -1.4039E-01, -2.6167E-01)
 (  8.6298E-02, -3.8174E-02)
 (  3.8163E-01, -1.8219E-01)
 ( -2.8207E-01,  1.9734E-01)
 ( -5.0942E-01, -5.0319E-01)
 ( -1.0861E-01,  2.8474E-01) : column 2 of unitary matrix X

 (  2.5177E-01, -7.9789E-01)
 ( -3.2188E-01,  1.6112E-01)
 (  1.3231E-01, -1.4563E-02)
 (  2.1598E-01,  1.8813E-01)
 (  3.6488E-02,  2.0319E-01)
 (  1.0906E-01, -1.2712E-01) : column 3 of unitary matrix X

 ( -5.0956E-02, -2.1750E-01)
 (  1.1979E-01,  1.6319E-01)
 ( -5.0671E-01,  1.8612E-01)
 ( -4.0163E-01,  2.6787E-01)
 (  1.9271E-01,  1.5574E-01)
 ( -8.8179E-02,  5.6169E-01) : column 4 of unitary matrix X

 ( -4.5947E-02,  1.4052E-04)
 ( -8.0311E-02, -4.3611E-01)
 (  5.9714E-02, -5.8970E-01)
 ( -4.6443E-02,  3.0864E-01)
 (  5.7843E-01, -1.2439E-01)
 (  1.5763E-02,  4.7130E-02) : column 5 of unitary matrix X

 ( -5.2773E-02, -2.2492E-01)
 ( -3.8117E-02, -2.1907E-01)
 ( -1.3850E-01, -9.0941E-02)
 ( -3.7354E-01, -5.5148E-01)
 ( -1.8818E-02, -5.5686E-02)
 (  6.5007E-01,  4.9173E-03) : column 6 of unitary matrix X

Result

 ZUNCSD Example Program Results

     Unitary matrix X
                    1                 2                 3                 4
 1  (-0.0130,-0.3260) (-0.1404,-0.2617) ( 0.2518,-0.7979) (-0.0510,-0.2175)
 2  ( 0.4276,-0.6258) ( 0.0863,-0.0382) (-0.3219, 0.1611) ( 0.1198, 0.1632)
 3  (-0.3260, 0.1643) ( 0.3816,-0.1822) ( 0.1323,-0.0146) (-0.5067, 0.1861)
 4  ( 0.1591,-0.0052) (-0.2821, 0.1973) ( 0.2160, 0.1881) (-0.4016, 0.2679)
 5  (-0.1721,-0.0130) (-0.5094,-0.5032) ( 0.0365, 0.2032) ( 0.1927, 0.1557)
 6  (-0.2634,-0.2477) (-0.1086, 0.2847) ( 0.1091,-0.1271) (-0.0882, 0.5617)

                    5                 6
 1  (-0.0459, 0.0001) (-0.0528,-0.2249)
 2  (-0.0803,-0.4361) (-0.0381,-0.2191)
 3  ( 0.0597,-0.5897) (-0.1385,-0.0909)
 4  (-0.0464, 0.3086) (-0.3735,-0.5515)
 5  ( 0.5784,-0.1244) (-0.0188,-0.0557)
 6  ( 0.0158, 0.0471) ( 0.6501, 0.0049)

 Theta Component of CS factorization of X:

     Theta
          1
 1   0.1973
 2   0.5387

 Components of CS factorization of X:

     Theta
          1
 1   0.1973
 2   0.5387

     Recombined matrix X = U * Sigma_p * V^H
                    1                 2                 3                 4
 1  (-0.0130,-0.3260) (-0.1404,-0.2617) ( 0.2518,-0.7979) (-0.0510,-0.2175)
 2  ( 0.4276,-0.6258) ( 0.0863,-0.0382) (-0.3219, 0.1611) ( 0.1198, 0.1632)
 3  (-0.3260, 0.1643) ( 0.3816,-0.1822) ( 0.1323,-0.0146) (-0.5067, 0.1861)
 4  ( 0.1591,-0.0052) (-0.2821, 0.1973) ( 0.2160, 0.1881) (-0.4016, 0.2679)
 5  (-0.1721,-0.0131) (-0.5094,-0.5032) ( 0.0365, 0.2032) ( 0.1927, 0.1557)
 6  (-0.2634,-0.2477) (-0.1086, 0.2847) ( 0.1091,-0.1271) (-0.0882, 0.5617)

                    5                 6
 1  (-0.0459, 0.0001) (-0.0528,-0.2249)
 2  (-0.0803,-0.4361) (-0.0381,-0.2191)
 3  ( 0.0597,-0.5897) (-0.1385,-0.0909)
 4  (-0.0464, 0.3086) (-0.3735,-0.5515)
 5  ( 0.5784,-0.1244) (-0.0188,-0.0557)
 6  ( 0.0158, 0.0471) ( 0.6501, 0.0049)

Source

    Program zuncsd_example

!     ZUNCSD Example Program Text

!     Copyright 2017, Numerical Algorithms Group Ltd. http://www.nag.com

!     .. Use Statements ..
      Use blas_interfaces, Only: zgemm
      Use lapack_example_aux, Only: nagf_file_print_matrix_complex_gen_comp, &
        nagf_file_print_matrix_real_gen
      Use lapack_interfaces, Only: zuncsd
      Use lapack_precision, Only: dp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Complex (Kind=dp), Parameter :: one = (1.0_dp, 0.0_dp)
      Complex (Kind=dp), Parameter :: zero = (0.0_dp, 0.0_dp)
      Integer, Parameter :: nin = 5, nout = 6, recombine = 1, reprint = 1
!     .. Local Scalars ..
      Integer :: i, ifail, info, info2, j, ldu, ldu1, ldu2, ldv, ldv1t, ldv2t, &
        ldx, ldx11, ldx12, ldx21, ldx22, lrwork, lwork, m, n11, n12, n21, n22, &
        p, q, r
!     .. Local Arrays ..
      Complex (Kind=dp), Allocatable :: u(:, :), u1(:, :), u2(:, :), v(:, :), &
        v1t(:, :), v2t(:, :), w(:, :), work(:), x(:, :), x11(:, :), x12(:, :), &
        x21(:, :), x22(:, :)
      Complex (Kind=dp) :: wdum(1)
      Real (Kind=dp) :: rwdum(1)
      Real (Kind=dp), Allocatable :: rwork(:), theta(:)
      Integer, Allocatable :: iwork(:)
      Character (1) :: clabs(1), rlabs(1)
!     .. Intrinsic Procedures ..
      Intrinsic :: cmplx, cos, min, nint, real, sin
!     .. Executable Statements ..
      Write (nout, *) 'ZUNCSD Example Program Results'
      Write (nout, *)
      Flush (nout)
!     Skip heading in data file
      Read (nin, *)
      Read (nin, *) m, p, q

      r = min(min(p,q), min(m-p,m-q))

      ldx = m
      ldx11 = p
      ldx12 = p
      ldx21 = m - p
      ldx22 = m - p
      ldu = m
      ldu1 = p
      ldu2 = m - p
      ldv = m
      ldv1t = q
      ldv2t = m - q
      Allocate (x(ldx,m), u(ldu,m), v(ldv,m), theta(r), iwork(m), w(ldx,m))
      Allocate (x11(ldx11,q), x12(ldx12,m-q), x21(ldx21,q), x22(ldx22,m-q))
      Allocate (u1(ldu1,p), u2(ldu2,m-p), v1t(ldv1t,q), v2t(ldv2t,m-q))

!     Read (by column) and print unitary X from data file
!      (as, say, generated by a generalized singular value decomposition).

      Do i = 1, m
        Read (nin, *) x(1:m, i)
      End Do

!     Print general complex matrix using matrix printing routine nagf_file_print_matrix_complex_gen_comp.
!     ifail: behaviour on error exit
!            =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
      ifail = 0
      Call nagf_file_print_matrix_complex_gen_comp('General', 'N', m, m, x, &
        ldx, 'Bracketed', 'F7.4', '    Unitary matrix X', 'Integer', rlabs, &
        'Integer', clabs, 80, 0, ifail)
      Write (nout, *)

!     Compute the complete CS factorization of X:
!        X11 is stored in X(1:p,   1:q), X12 is stored in X(1:p,   q+1:m)
!        X21 is stored in X(p+1:m, 1:q), X22 is stored in X(p+1:m, q+1:m)
!        U1  is stored in U(1:p,   1:p), U2  is stored in U(p+1:m, p+1:m)
!        V1  is stored in V(1:q,   1:q), V2  is stored in V(q+1:m, q+1:m)
      x11(1:p, 1:q) = x(1:p, 1:q)
      x12(1:p, 1:m-q) = x(1:p, q+1:m)
      x21(1:m-p, 1:q) = x(p+1:m, 1:q)
      x22(1:m-p, 1:m-q) = x(p+1:m, q+1:m)

!     Workspace query first to get length of work array for complete CS
!     factorization routine zuncsd.
      lwork = -1
      lrwork = -1
      Call zuncsd('Yes U1', 'Yes U2', 'Yes V1T', 'Yes V2T', 'Column', &
        'Default', m, p, q, x, ldx, x(1,q+1), ldx, x(p+1,1), ldx, x(p+1,q+1), &
        ldx, theta, u, ldu, u(p+1,p+1), ldu, v, ldv, v(q+1,q+1), ldv, wdum, &
        lwork, rwdum, lrwork, iwork, info)
      lwork = nint(real(wdum(1)))
      lrwork = nint(rwdum(1))
      Allocate (work(lwork), rwork(lrwork))
!     Initialize all of  u, v to zero.
      u(1:m, 1:m) = zero
      v(1:m, 1:m) = zero

!     This is how you might pass partitions as sub-matrices
      Call zuncsd('Yes U1', 'Yes U2', 'Yes V1T', 'Yes V2T', 'Column', &
        'Default', m, p, q, x, ldx, x(1,q+1), ldx, x(p+1,1), ldx, x(p+1,q+1), &
        ldx, theta, u, ldu, u(p+1,p+1), ldu, v, ldv, v(q+1,q+1), ldv, work, &
        lwork, rwork, lrwork, iwork, info)
      If (info/=0) Then
        Write (nout, 110) 'Failure in ZUNCSD. info =', info
        Go To 100
      End If

!     Print Theta using real matrix printing routine nagf_file_print_matrix_real_gen
!     Note: U1, U2, V1T, V2T not printed since these may differ by a sign
!     change in columns of U1, U2 and corresponding rows of V1T, V2T.
      Write (nout, 120) 'Theta Component of CS factorization of X:'
      Flush (nout)
      ifail = 0
      Call nagf_file_print_matrix_real_gen('G', 'N', r, 1, theta, r, &
        '    Theta', ifail)
      Write (nout, *)
      Flush (nout)

!     And this is how you might pass partitions as separate matrices.
      Call zuncsd('Yes U1', 'Yes U2', 'Yes V1T', 'Yes V2T', 'Column', &
        'Default', m, p, q, x11, ldx11, x12, ldx12, x21, ldx21, x22, ldx22, &
        theta, u1, ldu1, u2, ldu2, v1t, ldv1t, v2t, ldv2t, work, lwork, rwork, &
        lrwork, iwork, info2)
      If (info/=0) Then
        Write (nout, 110) 'Failure in ZUNCSD. info =', info
        Go To 100
      End If

!     Reprint Theta using matrix printing routine nagf_file_print_matrix_real_gen.
      If (reprint/=0) Then
        Write (nout, 120) 'Components of CS factorization of X:'
        Flush (nout)
        ifail = 0
        Call nagf_file_print_matrix_real_gen('G', 'N', r, 1, theta, r, &
          '    Theta', ifail)
        Write (nout, *)
        Flush (nout)
      End If

      If (recombine/=0) Then
!       Recombining should return the original matrix
!       Assemble Sigma_p into X
        x(1:m, 1:m) = zero
        n11 = min(p, q) - r
        n12 = min(p, m-q) - r
        n21 = min(m-p, q) - r
        n22 = min(m-p, m-q) - r
!       Top Half
        Do j = 1, n11
          x(j, j) = one
        End Do
        Do j = 1, r
          x(j+n11, j+n11) = cmplx(cos(theta(j)), 0.0_dp, kind=dp)
          x(j+n11, j+n11+r+n21+n22) = cmplx(-sin(theta(j)), 0.0_dp, kind=dp)
        End Do
        Do j = 1, n12
          x(j+n11+r, j+n11+r+n21+n22+r) = -one
        End Do
!       Bottom half
        Do j = 1, n22
          x(p+j, q+j) = one
        End Do
        Do j = 1, r
          x(p+n22+j, j+n11) = cmplx(sin(theta(j)), 0.0_dp, kind=dp)
          x(p+n22+j, j+r+n21+n22) = cmplx(cos(theta(j)), 0.0_dp, kind=dp)
        End Do
        Do j = 1, n21
          x(p+n22+r+j, n11+r+j) = one
        End Do
!       multiply U * Sigma_p into w
        Call zgemm('n', 'n', m, m, m, one, u, ldu, x, ldx, zero, w, ldx)
!       form U * Sigma_p * V^T into u
        Call zgemm('n', 'n', m, m, m, one, w, ldx, v, ldv, zero, u, ldu)

!       Print recombined matrix using complex matrix printing routine nagf_file_print_matrix_complex_gen_comp.
        Write (nout, *)
        Flush (nout)
        ifail = 0
        Call nagf_file_print_matrix_complex_gen_comp('General', 'N', m, m, u, &
          ldu, 'Bracketed', 'F7.4', &
          '    Recombined matrix X = U * Sigma_p * V^H', 'Integer', rlabs, &
          'Integer', clabs, 80, 0, ifail)
      End If
100   Continue

110   Format (1X, A, I4)
120   Format (/, 1X, A, /)
    End Program
Full documentation of ZUNCSD


ZUNGBR example

Computational Routines: Generate unitary transformation matrices from reduction to bidiagonal form determined by ZGEBRD

Data

ZUNGBR Example Program Data
  6  4                                        :Values of M and N, Example 1
 ( 0.96,-0.81) (-0.03, 0.96) (-0.91, 2.06) (-0.05, 0.41)
 (-0.98, 1.98) (-1.20, 0.19) (-0.66, 0.42) (-0.81, 0.56)
 ( 0.62,-0.46) ( 1.01, 0.02) ( 0.63,-0.17) (-1.11, 0.60)
 (-0.37, 0.38) ( 0.19,-0.54) (-0.98,-0.36) ( 0.22,-0.20)
 ( 0.83, 0.51) ( 0.20, 0.01) (-0.17,-0.46) ( 1.47, 1.59)
 ( 1.08,-0.28) ( 0.20,-0.12) (-0.07, 1.23) ( 0.26, 0.26)   :End of matrix A
  3  4                                        :Values of M and N, Example 2
 ( 0.28,-0.36) ( 0.50,-0.86) (-0.77,-0.48) ( 1.58, 0.66)
 (-0.50,-1.10) (-1.21, 0.76) (-0.32,-0.24) (-0.27,-1.15)
 ( 0.36,-0.51) (-0.07, 1.33) (-0.75, 0.47) (-0.08, 1.01)   :End of matrix A

Result

 ZUNGBR Example Program Results

 Example 1: singular values
         3.9994            3.0003            1.9944            0.9995

 Example 1: right singular vectors, by row
                    1                 2                 3                 4
 1  (-0.6971,-0.0000) (-0.0867,-0.3548) ( 0.0560,-0.5400) (-0.1878,-0.2253)
 2  ( 0.2403, 0.0000) ( 0.0725,-0.2336) (-0.2477,-0.5291) ( 0.7026, 0.2177)
 3  (-0.5123, 0.0000) (-0.3030,-0.1735) ( 0.0678, 0.5162) ( 0.4418, 0.3864)
 4  (-0.4403, 0.0000) ( 0.5294, 0.6361) (-0.3027,-0.0346) ( 0.1667, 0.0258)

 Example 1: left singular vectors, by column
                    1                 2                 3                 4
 1  (-0.5634, 0.0016) (-0.2687,-0.2749) ( 0.2451, 0.4657) ( 0.3787, 0.2987)
 2  ( 0.1205,-0.6108) (-0.2909, 0.1085) ( 0.4329,-0.1758) (-0.0182,-0.0437)
 3  (-0.0816, 0.1613) (-0.1660, 0.3885) (-0.4667, 0.3821) (-0.0800,-0.2276)
 4  ( 0.1441,-0.1532) ( 0.1984,-0.1737) (-0.0034, 0.1555) ( 0.2608,-0.5382)
 5  (-0.2487,-0.0926) ( 0.6253, 0.3304) ( 0.2643,-0.0194) ( 0.1002, 0.0140)
 6  (-0.3758, 0.0793) (-0.0307,-0.0816) ( 0.1266, 0.1747) (-0.4175,-0.4058)

 Example 2: singular values
         3.0004            1.9967            0.9973

 Example 2: right singular vectors, by row
                    1                 2                 3                 4
 1  ( 0.2454,-0.0001) ( 0.2942,-0.5843) ( 0.0162,-0.0810) ( 0.6794, 0.2083)
 2  (-0.1692, 0.5194) ( 0.1915,-0.4374) ( 0.5205,-0.0244) (-0.3149,-0.3208)
 3  (-0.5553, 0.1403) ( 0.1438,-0.1507) (-0.5684,-0.5505) (-0.0318,-0.0378)

 Example 2: left singular vectors, by column
                    1                 2                 3
 1  ( 0.6518, 0.0000) (-0.4312, 0.0000) ( 0.6239, 0.0000)
 2  (-0.4437,-0.5027) (-0.3794, 0.1026) ( 0.2014, 0.5961)
 3  (-0.2012, 0.2916) (-0.8122, 0.0030) (-0.3511,-0.3026)

Source

    Program zungbr_example

!     ZUNGBR Example Program Text

!     Copyright 2017, Numerical Algorithms Group Ltd. http://www.nag.com

!     .. Use Statements ..
      Use lapack_example_aux, Only: nagf_file_print_matrix_complex_gen_comp
      Use lapack_interfaces, Only: zbdsqr, zgebrd, zlacpy, zungbr
      Use lapack_precision, Only: dp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter :: nin = 5, nout = 6
!     .. Local Scalars ..
      Integer :: i, ic, ifail, info, lda, ldc, ldu, ldvt, lwork, m, n
!     .. Local Arrays ..
      Complex (Kind=dp), Allocatable :: a(:, :), c(:, :), taup(:), tauq(:), &
        u(:, :), vt(:, :), work(:)
      Real (Kind=dp), Allocatable :: d(:), e(:), rwork(:)
      Character (1) :: clabs(1), rlabs(1)
!     .. Executable Statements ..
      Write (nout, *) 'ZUNGBR Example Program Results'
!     Skip heading in data file
      Read (nin, *)
      Do ic = 1, 2
        Read (nin, *) m, n
        lda = m
        ldc = n
        ldu = m
        ldvt = n
        lwork = 64*(m+n)
        Allocate (a(lda,n), c(ldc,n), taup(n), tauq(n), u(ldu,n), vt(ldvt,n), &
          work(lwork), d(n), e(n-1), rwork(4*n-4))

!       Read A from data file
        Read (nin, *)(a(i,1:n), i=1, m)

!       Reduce A to bidiagonal form
        Call zgebrd(m, n, a, lda, d, e, tauq, taup, work, lwork, info)

        If (m>=n) Then

!         Copy A to VT and U
          Call zlacpy('Upper', n, n, a, lda, vt, ldvt)
          Call zlacpy('Lower', m, n, a, lda, u, ldu)

!         Form P**H explicitly, storing the result in VT
          Call zungbr('P', n, n, m, vt, ldvt, taup, work, lwork, info)

!         Form Q explicitly, storing the result in U
          Call zungbr('Q', m, n, n, u, ldu, tauq, work, lwork, info)

!         Compute the SVD of A
          Call zbdsqr('Upper', n, n, m, 0, d, e, vt, ldvt, u, ldu, c, ldc, &
            rwork, info)

!         Print singular values, left & right singular vectors

          Write (nout, *)
          Write (nout, *) 'Example 1: singular values'
          Write (nout, 100) d(1:n)
          Write (nout, *)
          Flush (nout)

!         ifail: behaviour on error exit
!                =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
          ifail = 0
          Call nagf_file_print_matrix_complex_gen_comp('General', ' ', n, n, &
            vt, ldvt, 'Bracketed', 'F7.4', &
            'Example 1: right singular vectors, by row', 'Integer', rlabs, &
            'Integer', clabs, 80, 0, ifail)

          Write (nout, *)
          Flush (nout)

          Call nagf_file_print_matrix_complex_gen_comp('General', ' ', m, n, &
            u, ldu, 'Bracketed', 'F7.4', &
            'Example 1: left singular vectors, by column', 'Integer', rlabs, &
            'Integer', clabs, 80, 0, ifail)

        Else

!         Copy A to VT and U
          Call zlacpy('Upper', m, n, a, lda, vt, ldvt)
          Call zlacpy('Lower', m, m, a, lda, u, ldu)

!         Form P**H explicitly, storing the result in VT
          Call zungbr('P', m, n, m, vt, ldvt, taup, work, lwork, info)

!         Form Q explicitly, storing the result in U
          Call zungbr('Q', m, m, n, u, ldu, tauq, work, lwork, info)

!         Compute the SVD of A
          Call zbdsqr('Lower', m, n, m, 0, d, e, vt, ldvt, u, ldu, c, ldc, &
            rwork, info)

!         Print singular values, left & right singular vectors

          Write (nout, *)
          Write (nout, *) 'Example 2: singular values'
          Write (nout, 100) d(1:m)
          Write (nout, *)
          Flush (nout)

          ifail = 0
          Call nagf_file_print_matrix_complex_gen_comp('General', ' ', m, n, &
            vt, ldvt, 'Bracketed', 'F7.4', &
            'Example 2: right singular vectors, by row', 'Integer', rlabs, &
            'Integer', clabs, 80, 0, ifail)

          Write (nout, *)
          Flush (nout)

          Call nagf_file_print_matrix_complex_gen_comp('General', ' ', m, m, &
            u, ldu, 'Bracketed', 'F7.4', &
            'Example 2: left singular vectors, by column', 'Integer', rlabs, &
            'Integer', clabs, 80, 0, ifail)

        End If
        Deallocate (a, c, taup, tauq, u, vt, work, d, e, rwork)
      End Do

100   Format (8X, 4(F7.4,11X,:))
    End Program
Full documentation of ZUNGBR


ZUNGHR example

Computational Routines: Generate unitary transformation matrix from reduction to Hessenberg form determined by ZGEHRD

Data

ZUNGHR Example Program Data
  4                                                        :Value of N
 (-3.97,-5.04) (-4.11, 3.70) (-0.34, 1.01) ( 1.29,-0.86)
 ( 0.34,-1.50) ( 1.52,-0.43) ( 1.88,-5.38) ( 3.36, 0.65)
 ( 3.31,-3.85) ( 2.50, 3.45) ( 0.88,-1.08) ( 0.64,-1.48)
 (-1.10, 0.82) ( 1.81,-1.59) ( 3.25, 1.33) ( 1.57,-3.44)   :End of matrix A

Result

 ZUNGHR Example Program Results

 Matrix A
                    1                 2                 3                 4
 1  (-3.9700,-5.0400) (-4.1100, 3.7000) (-0.3400, 1.0100) ( 1.2900,-0.8600)
 2  ( 0.3400,-1.5000) ( 1.5200,-0.4300) ( 1.8800,-5.3800) ( 3.3600, 0.6500)
 3  ( 3.3100,-3.8500) ( 2.5000, 3.4500) ( 0.8800,-1.0800) ( 0.6400,-1.4800)
 4  (-1.1000, 0.8200) ( 1.8100,-1.5900) ( 3.2500, 1.3300) ( 1.5700,-3.4400)

 Eigenvalues
    (-6.0004,-6.9998) (-5.0000, 2.0060) ( 7.9982,-0.9964) ( 3.0023,-3.9998)

Source

    Program zunghr_example

!     ZUNGHR Example Program Text

!     Copyright 2017, Numerical Algorithms Group Ltd. http://www.nag.com

!     .. Use Statements ..
      Use blas_interfaces, Only: zgemm
      Use lapack_example_aux, Only: nagf_file_print_matrix_complex_gen_comp
      Use lapack_interfaces, Only: zgehrd, zhseqr, zlange, zunghr
      Use lapack_precision, Only: dp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter :: nin = 5, nout = 6
!     .. Local Scalars ..
      Complex (Kind=dp) :: alpha, beta
      Real (Kind=dp) :: norm
      Integer :: i, ifail, info, lda, ldc, ldd, ldz, lwork, n
!     .. Local Arrays ..
      Complex (Kind=dp), Allocatable :: a(:, :), c(:, :), d(:, :), tau(:), &
        w(:), work(:), z(:, :)
      Real (Kind=dp), Allocatable :: rwork(:)
      Character (1) :: clabs(1), rlabs(1)
!     .. Intrinsic Procedures ..
      Intrinsic :: cmplx, epsilon
!     .. Executable Statements ..
      Write (nout, *) 'ZUNGHR Example Program Results'
      Write (nout, *)
      Flush (nout)
!     Skip heading in data file
      Read (nin, *)
      Read (nin, *) n
      lda = n
      ldc = n
      ldd = n
      ldz = n
      lwork = 64*(n-1)
      Allocate (a(lda,n), c(ldc,n), d(ldd,n), rwork(lda), tau(n), w(n), &
        work(lwork), z(ldz,n))

!     Read A from data file
      Read (nin, *)(a(i,1:n), i=1, n)

!     Store A in D
      d(1:ldd, 1:n) = a(1:lda, 1:n)

!     Print matrix A
!     ifail: behaviour on error exit
!            =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
      ifail = 0
      Call nagf_file_print_matrix_complex_gen_comp('General', ' ', n, n, a, &
        lda, 'Bracketed', 'F7.4', 'Matrix A', 'Integer', rlabs, 'Integer', &
        clabs, 80, 0, ifail)
      Write (nout, *)
      Flush (nout)

!     Reduce A to upper Hessenberg form H = (Q**H)*A*Q

      Call zgehrd(n, 1, n, a, lda, tau, work, lwork, info)

!     Copy A into Z
      z(1:n, 1:n) = a(1:n, 1:n)

!     Form Q explicitly, storing the result in Z
      Call zunghr(n, 1, n, z, ldz, tau, work, lwork, info)

!     Calculate the Schur factorization of H = Y*T*(Y**H) and form
!     Q*Y explicitly, storing the result in Z

!     Note that A = Z*T*(Z**H), where Z = Q*Y

      Call zhseqr('Schur form', 'Vectors', n, 1, n, a, lda, w, z, ldz, work, &
        lwork, info)

!     Compute A - Z*T*Z^H from Schur factorization of A, and store in matrix D
      alpha = cmplx(1, kind=dp)
      beta = cmplx(0, kind=dp)
      Call zgemm('N', 'N', n, n, n, alpha, z, ldz, a, lda, beta, c, ldc)
      alpha = cmplx(-1, kind=dp)
      beta = cmplx(1, kind=dp)
      Call zgemm('N', 'C', n, n, n, alpha, c, ldc, z, ldz, beta, d, ldd)

!     Find norm of matrix D and print warning if it is too large
      norm = zlange('O', ldd, n, d, ldd, rwork)
      If (norm>epsilon(1.0E0_dp)**0.5_dp) Then
        Write (nout, *) 'Norm of A-(Z*T*Z^H) is much greater than 0.'
        Write (nout, *) 'Schur factorization has failed.'
      Else
!       Print eigenvalues.
        Write (nout, *) 'Eigenvalues'
        Write (nout, 100)(w(i), i=1, n)
      End If

100   Format ((3X,4(' (',F7.4,',',F7.4,')',:)))

    End Program
Full documentation of ZUNGHR


ZUNGLQ example

Computational Routines: Form all or part of unitary Q from LQ factorization determined by ZGELQF

Data

ZUNGLQ Example Program Data
  3  4                                                     :Values of M and N
 ( 0.28,-0.36) ( 0.50,-0.86) (-0.77,-0.48) ( 1.58, 0.66)
 (-0.50,-1.10) (-1.21, 0.76) (-0.32,-0.24) (-0.27,-1.15)
 ( 0.36,-0.51) (-0.07, 1.33) (-0.75, 0.47) (-0.08, 1.01)   :End of matrix A

Result

 ZUNGLQ Example Program Results

 The leading  3 rows of Q
                    1                 2                 3                 4
 1  (-0.1258, 0.1618) (-0.2247, 0.3864) ( 0.3460, 0.2157) (-0.7099,-0.2966)
 2  (-0.1163,-0.6380) (-0.3240, 0.4272) (-0.1995,-0.5009) (-0.0323,-0.0162)
 3  (-0.4607, 0.1090) ( 0.2171,-0.4062) ( 0.2733,-0.6106) (-0.0994,-0.3261)

Source

    Program zunglq_example

!     ZUNGLQ Example Program Text

!     Copyright 2017, Numerical Algorithms Group Ltd. http://www.nag.com

!     .. Use Statements ..
      Use lapack_example_aux, Only: nagf_file_print_matrix_complex_gen_comp
      Use lapack_interfaces, Only: zgelqf, zunglq
      Use lapack_precision, Only: dp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter :: nin = 5, nout = 6
!     .. Local Scalars ..
      Integer :: i, ifail, info, lda, lwork, m, n
      Character (30) :: title
!     .. Local Arrays ..
      Complex (Kind=dp), Allocatable :: a(:, :), tau(:), work(:)
      Character (1) :: clabs(1), rlabs(1)
!     .. Executable Statements ..
      Write (nout, *) 'ZUNGLQ Example Program Results'
!     Skip heading in data file
      Read (nin, *)
      Read (nin, *) m, n
      lda = m
      lwork = 64*m
      Allocate (a(lda,n), tau(n), work(lwork))

!     Read A from data file

      Read (nin, *)(a(i,1:n), i=1, m)

!     Compute the LQ factorization of A
      Call zgelqf(m, n, a, lda, tau, work, lwork, info)

!     Form the leading M rows of Q explicitly
      Call zunglq(m, n, m, a, lda, tau, work, lwork, info)

!     Print the leading M rows of Q only

      Write (nout, *)
      Write (title, 100) m
      Flush (nout)

!     ifail: behaviour on error exit
!             =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
      ifail = 0
      Call nagf_file_print_matrix_complex_gen_comp('General', ' ', m, n, a, &
        lda, 'Bracketed', 'F7.4', title, 'Integer', rlabs, 'Integer', clabs, &
        80, 0, ifail)

100   Format ('The leading ', I2, ' rows of Q')
    End Program
Full documentation of ZUNGLQ


ZUNGQL example

Computational Routines: Form all or part of orthogonal Q from QL factorization determined by ZGEQLF

Data

ZUNGQL Example Program Data

   6             4                                       :Values of M and N

 ( 0.96,-0.81) (-0.03, 0.96) (-0.91, 2.06) (-0.05, 0.41)
 (-0.98, 1.98) (-1.20, 0.19) (-0.66, 0.42) (-0.81, 0.56)
 ( 0.62,-0.46) ( 1.01, 0.02) ( 0.63,-0.17) (-1.11, 0.60)
 (-0.37, 0.38) ( 0.19,-0.54) (-0.98,-0.36) ( 0.22,-0.20)
 ( 0.83, 0.51) ( 0.20, 0.01) (-0.17,-0.46) ( 1.47, 1.59)
 ( 1.08,-0.28) ( 0.20,-0.12) (-0.07, 1.23) ( 0.26, 0.26) :End of matrix A

Result

 ZUNGQL Example Program Results

 The leading    4 columns of Q
                    1                 2                 3                 4
 1  ( 0.2810, 0.5020) (-0.2051,-0.1092) ( 0.3083,-0.6874) ( 0.0181,-0.1483)
 2  ( 0.2707,-0.3296) ( 0.5711, 0.0432) ( 0.2251,-0.1313) ( 0.2930,-0.2025)
 3  (-0.2864,-0.0094) (-0.5416, 0.0454) (-0.2062, 0.0691) ( 0.4015,-0.2170)
 4  ( 0.2262,-0.3854) (-0.3387, 0.2228) ( 0.3259, 0.1178) (-0.0796, 0.0723)
 5  ( 0.0341,-0.0760) ( 0.0098,-0.0712) ( 0.0753, 0.1412) (-0.5317,-0.5751)
 6  (-0.3936,-0.2083) (-0.1296, 0.3691) ( 0.0264,-0.4134) (-0.0940,-0.0940)

Source

    Program zungql_example

!     ZUNGQL Example Program Text

!     Copyright 2017, Numerical Algorithms Group Ltd. http://www.nag.com

!     .. Use Statements ..
      Use lapack_example_aux, Only: nagf_file_print_matrix_complex_gen_comp
      Use lapack_interfaces, Only: zgeqlf, zungql
      Use lapack_precision, Only: dp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter :: nb = 64, nin = 5, nout = 6
!     .. Local Scalars ..
      Integer :: i, ifail, info, lda, lwork, m, n
      Character (30) :: title
!     .. Local Arrays ..
      Complex (Kind=dp), Allocatable :: a(:, :), tau(:), work(:)
      Character (1) :: clabs(1), rlabs(1)
!     .. Executable Statements ..
      Write (nout, *) 'ZUNGQL Example Program Results'
      Write (nout, *)
!     Skip heading in data file
      Read (nin, *)
      Read (nin, *) m, n
      lda = m
      lwork = nb*n
      Allocate (a(lda,n), tau(n), work(lwork))

!     Read A from data file

      Read (nin, *)(a(i,1:n), i=1, m)

!     Compute the QL factorization of A
      Call zgeqlf(m, n, a, lda, tau, work, lwork, info)

!     Form the leading N columns of Q explicitly
      Call zungql(m, n, n, a, lda, tau, work, lwork, info)

!     Form the heading for NAGF_FILE_PRINT_MATRIX_COMPLEX_GEN_COMP

      Write (title, 100) n
      Flush (nout)

!     Print the leading N columns of Q

!     ifail: behaviour on error exit
!             =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
      ifail = 0
      Call nagf_file_print_matrix_complex_gen_comp('General', ' ', m, n, a, &
        lda, 'Bracketed', 'F7.4', title, 'Integer', rlabs, 'Integer', clabs, &
        80, 0, ifail)

100   Format ('The leading ', I4, ' columns of Q')
    End Program
Full documentation of ZUNGQL


ZUNGQR example

Computational Routines: Form all or part of unitary Q from QR factorization determined by ZGEQRF or ZGEQPF

Data

ZUNGQR Example Program Data
  6  4                                                     :Values of M and N
 ( 0.96,-0.81) (-0.03, 0.96) (-0.91, 2.06) (-0.05, 0.41)
 (-0.98, 1.98) (-1.20, 0.19) (-0.66, 0.42) (-0.81, 0.56)
 ( 0.62,-0.46) ( 1.01, 0.02) ( 0.63,-0.17) (-1.11, 0.60)
 (-0.37, 0.38) ( 0.19,-0.54) (-0.98,-0.36) ( 0.22,-0.20)
 ( 0.83, 0.51) ( 0.20, 0.01) (-0.17,-0.46) ( 1.47, 1.59)
 ( 1.08,-0.28) ( 0.20,-0.12) (-0.07, 1.23) ( 0.26, 0.26)   :End of matrix A

Result

 ZUNGQR Example Program Results

 The leading  4 columns of Q
                    1                 2                 3                 4
 1  (-0.3110, 0.2624) (-0.3175, 0.4835) ( 0.4966,-0.2997) (-0.0072,-0.3718)
 2  ( 0.3175,-0.6414) (-0.2062, 0.1577) (-0.0793,-0.3094) (-0.0282,-0.1491)
 3  (-0.2008, 0.1490) ( 0.4892,-0.0900) ( 0.0357,-0.0219) ( 0.5625,-0.0710)
 4  ( 0.1199,-0.1231) ( 0.2566,-0.3055) ( 0.4489,-0.2141) (-0.1651, 0.1800)
 5  (-0.2689,-0.1652) ( 0.1697,-0.2491) (-0.0496, 0.1158) (-0.4885,-0.4540)
 6  (-0.3499, 0.0907) (-0.0491,-0.3133) (-0.1256,-0.5300) ( 0.1039, 0.0450)

Source

    Program zungqr_example

!     ZUNGQR Example Program Text

!     Copyright 2017, Numerical Algorithms Group Ltd. http://www.nag.com

!     .. Use Statements ..
      Use lapack_example_aux, Only: nagf_file_print_matrix_complex_gen_comp
      Use lapack_interfaces, Only: zgeqrf, zungqr
      Use lapack_precision, Only: dp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter :: nin = 5, nout = 6
!     .. Local Scalars ..
      Integer :: i, ifail, info, lda, lwork, m, n
      Character (30) :: title
!     .. Local Arrays ..
      Complex (Kind=dp), Allocatable :: a(:, :), tau(:), work(:)
      Character (1) :: clabs(1), rlabs(1)
!     .. Executable Statements ..
      Write (nout, *) 'ZUNGQR Example Program Results'
!     Skip heading in data file
      Read (nin, *)
      Read (nin, *) m, n
      lda = m
      lwork = 64*n
      Allocate (a(lda,n), tau(n), work(lwork))

!     Read A from data file

      Read (nin, *)(a(i,1:n), i=1, m)

!     Compute the QR factorization of A
      Call zgeqrf(m, n, a, lda, tau, work, lwork, info)

!     Form the leading N columns of Q explicitly
      Call zungqr(m, n, n, a, lda, tau, work, lwork, info)

!     Print the leading N columns of Q only

      Write (nout, *)
      Write (title, 100) n
      Flush (nout)

!     ifail: behaviour on error exit
!             =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
      ifail = 0
      Call nagf_file_print_matrix_complex_gen_comp('General', ' ', m, n, a, &
        lda, 'Bracketed', 'F7.4', title, 'Integer', rlabs, 'Integer', clabs, &
        80, 0, ifail)

100   Format ('The leading ', I2, ' columns of Q')
    End Program
Full documentation of ZUNGQR


ZUNGRQ example

Computational Routines: Form all or part of orthogonal Q from RQ factorization determined by ZGERQF

Data

ZUNGRQ Example Program Data

   4             6                                           :Values of M and N

 ( 0.96,-0.81) (-0.98, 1.98) ( 0.62,-0.46) (-0.37, 0.38) ( 0.83, 0.51)
 ( 1.08,-0.28)
 (-0.03, 0.96) (-1.20, 0.19) ( 1.01, 0.02) ( 0.19,-0.54) ( 0.20, 0.01)
 ( 0.20,-0.12)
 (-0.91, 2.06) (-0.66, 0.42) ( 0.63,-0.17) (-0.98,-0.36) (-0.17,-0.46)
 (-0.07, 1.23)
 (-0.05, 0.41) (-0.81, 0.56) (-1.11, 0.60) ( 0.22,-0.20) ( 1.47, 1.59)
 ( 0.26, 0.26)                                                 :End of matrix A

Result

 ZUNGRQ Example Program Results

 The leading    4 rows of Q
                    1                 2                 3                 4
 1  ( 0.2810, 0.5020) ( 0.2707,-0.3296) (-0.2864,-0.0094) ( 0.2262,-0.3854)
 2  (-0.2051,-0.1092) ( 0.5711, 0.0432) (-0.5416, 0.0454) (-0.3387, 0.2228)
 3  ( 0.3083,-0.6874) ( 0.2251,-0.1313) (-0.2062, 0.0691) ( 0.3259, 0.1178)
 4  ( 0.0181,-0.1483) ( 0.2930,-0.2025) ( 0.4015,-0.2170) (-0.0796, 0.0723)

                    5                 6
 1  ( 0.0341,-0.0760) (-0.3936,-0.2083)
 2  ( 0.0098,-0.0712) (-0.1296, 0.3691)
 3  ( 0.0753, 0.1412) ( 0.0264,-0.4134)
 4  (-0.5317,-0.5751) (-0.0940,-0.0940)

Source

    Program zungrq_example

!     ZUNGRQ Example Program Text

!     Copyright 2017, Numerical Algorithms Group Ltd. http://www.nag.com

!     .. Use Statements ..
      Use lapack_example_aux, Only: nagf_file_print_matrix_complex_gen_comp
      Use lapack_interfaces, Only: zgerqf, zungrq
      Use lapack_precision, Only: dp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter :: nb = 64, nin = 5, nout = 6
!     .. Local Scalars ..
      Integer :: i, ifail, info, lda, lwork, m, n
      Character (26) :: title
!     .. Local Arrays ..
      Complex (Kind=dp), Allocatable :: a(:, :), tau(:), work(:)
      Character (1) :: clabs(1), rlabs(1)
!     .. Executable Statements ..
      Write (nout, *) 'ZUNGRQ Example Program Results'
      Write (nout, *)
!     Skip heading in data file
      Read (nin, *)
      Read (nin, *) m, n
      lda = m
      lwork = nb*m
      Allocate (a(lda,n), tau(n), work(lwork))

!     Read A from data file

      Read (nin, *)(a(i,1:n), i=1, m)

!     Compute the RQ factorization of A
      Call zgerqf(m, n, a, lda, tau, work, lwork, info)

!     Form the leading M rows of Q explicitly
      Call zungrq(m, n, m, a, lda, tau, work, lwork, info)

!     Form the heading for NAGF_FILE_PRINT_MATRIX_COMPLEX_GEN_COMP

      Write (title, 100) m
      Flush (nout)

!     Print the leading M rows of Q

!     ifail: behaviour on error exit
!             =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
      ifail = 0
      Call nagf_file_print_matrix_complex_gen_comp('General', ' ', m, n, a, &
        lda, 'Bracketed', 'F7.4', title, 'Integer', rlabs, 'Integer', clabs, &
        80, 0, ifail)

100   Format ('The leading ', I4, ' rows of Q')
    End Program
Full documentation of ZUNGRQ


ZUNGTR example

Computational Routines: Generate unitary transformation matrix from reduction to tridiagonal form determined by ZHETRD

Data

ZUNGTR Example Program Data
  4                                                        :Value of N
  'L'                                                      :Value of UPLO
 (-2.28, 0.00)
 ( 1.78, 2.03) (-1.12, 0.00)
 ( 2.26,-0.10) ( 0.01,-0.43) (-0.37, 0.00)
 (-0.12,-2.53) (-1.07,-0.86) ( 2.31, 0.92) (-0.73, 0.00)   :End of matrix A

Result

 ZUNGTR Example Program Results

 Eigenvalues
        -6.0002           -3.0030            0.5036            3.9996

 Eigenvectors
                    1                 2                 3                 4
 1  ( 0.7299, 0.0000) (-0.2120, 0.1497) ( 0.1000,-0.3570) ( 0.1991, 0.4720)
 2  (-0.1663,-0.2061) ( 0.7307,-0.0000) ( 0.2863,-0.3353) (-0.2467, 0.3751)
 3  (-0.4165,-0.1417) (-0.3291, 0.0479) ( 0.6890, 0.0000) ( 0.4468, 0.1466)
 4  ( 0.1743, 0.4162) ( 0.5200, 0.1329) ( 0.0662, 0.4347) ( 0.5612, 0.0000)

Source

    Program zungtr_example

!     ZUNGTR Example Program Text

!     Copyright 2017, Numerical Algorithms Group Ltd. http://www.nag.com

!     .. Use Statements ..
      Use blas_interfaces, Only: zscal
      Use lapack_example_aux, Only: nagf_file_print_matrix_complex_gen_comp
      Use lapack_interfaces, Only: zhetrd, zlacpy, zsteqr, zungtr
      Use lapack_precision, Only: dp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter :: nin = 5, nout = 6
!     .. Local Scalars ..
      Integer :: i, ifail, info, k, lda, ldz, lwork, n
      Character (1) :: uplo
!     .. Local Arrays ..
      Complex (Kind=dp), Allocatable :: a(:, :), tau(:), work(:), z(:, :)
      Real (Kind=dp), Allocatable :: d(:), e(:), rwork(:)
      Character (1) :: clabs(1), rlabs(1)
!     .. Intrinsic Procedures ..
      Intrinsic :: abs, cmplx, conjg, maxloc
!     .. Executable Statements ..
      Write (nout, *) 'ZUNGTR Example Program Results'
!     Skip heading in data file
      Read (nin, *)
      Read (nin, *) n
      lda = n
      ldz = n
      lwork = 64*n
      Allocate (a(lda,n), tau(n), work(lwork), z(ldz,n), d(n), e(n), &
        rwork(2*n-2))

!     Read A from data file

      Read (nin, *) uplo
      If (uplo=='U') Then
        Read (nin, *)(a(i,i:n), i=1, n)
      Else If (uplo=='L') Then
        Read (nin, *)(a(i,1:i), i=1, n)
      End If

!     Reduce A to tridiagonal form T = (Q**H)*A*Q

      Call zhetrd(uplo, n, a, lda, d, e, tau, work, lwork, info)

!     Copy A into Z
      Call zlacpy(uplo, n, n, a, lda, z, ldz)

!     Form Q explicitly, storing the result in Z
      Call zungtr(uplo, n, z, ldz, tau, work, lwork, info)

!     Calculate all the eigenvalues and eigenvectors of A
      Call zsteqr('V', n, d, e, z, ldz, rwork, info)

      Write (nout, *)
      If (info>0) Then
        Write (nout, *) 'Failure to converge.'
      Else

!       Print eigenvalues and eigenvectors

        Write (nout, *) 'Eigenvalues'
        Write (nout, 100) d(1:n)
        Write (nout, *)
        Flush (nout)

!       Normalize the eigenvectors so that the element of largest absolute
!       value is real.
        Do i = 1, n
          rwork(1:n) = abs(z(1:n,i))
          k = maxloc(rwork(1:n), 1)
          Call zscal(n, conjg(z(k,i))/cmplx(abs(z(k,i)),kind=dp), z(1,i), 1)
        End Do

!       ifail: behaviour on error exit
!              =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
        ifail = 0
        Call nagf_file_print_matrix_complex_gen_comp('General', ' ', n, n, z, &
          ldz, 'Bracketed', 'F7.4', 'Eigenvectors', 'Integer', rlabs, &
          'Integer', clabs, 80, 0, ifail)

      End If

100   Format (8X, 4(F7.4,11X,:))
    End Program
Full documentation of ZUNGTR


ZUNMBR example

Computational Routines: Apply unitary transformations from reduction to bidiagonal form determined by ZGEBRD

Data

ZUNMBR Example Program Data
  6  4                                        :Values of M and N, Example 1
 ( 0.96,-0.81) (-0.03, 0.96) (-0.91, 2.06) (-0.05, 0.41)
 (-0.98, 1.98) (-1.20, 0.19) (-0.66, 0.42) (-0.81, 0.56)
 ( 0.62,-0.46) ( 1.01, 0.02) ( 0.63,-0.17) (-1.11, 0.60)
 (-0.37, 0.38) ( 0.19,-0.54) (-0.98,-0.36) ( 0.22,-0.20)
 ( 0.83, 0.51) ( 0.20, 0.01) (-0.17,-0.46) ( 1.47, 1.59)
 ( 1.08,-0.28) ( 0.20,-0.12) (-0.07, 1.23) ( 0.26, 0.26)   :End of matrix A
  3  4                                        :Values of M and N, Example 2
 ( 0.28,-0.36) ( 0.50,-0.86) (-0.77,-0.48) ( 1.58, 0.66)
 (-0.50,-1.10) (-1.21, 0.76) (-0.32,-0.24) (-0.27,-1.15)
 ( 0.36,-0.51) (-0.07, 1.33) (-0.75, 0.47) (-0.08, 1.01)   :End of matrix A

Result

 ZUNMBR Example Program Results

 Example 1: bidiagonal matrix B
 Diagonal
    -3.0870 -2.0660 -1.8731 -2.0022
 Superdiagonal
     2.1126 -1.2628  1.6126

 Example 1: matrix Q
                    1                 2                 3                 4
 1  (-0.3110, 0.2624) ( 0.6521, 0.5532) ( 0.0427, 0.0361) (-0.2634,-0.0741)
 2  ( 0.3175,-0.6414) ( 0.3488, 0.0721) ( 0.2287, 0.0069) ( 0.1101,-0.0326)
 3  (-0.2008, 0.1490) (-0.3103, 0.0230) ( 0.1855,-0.1817) (-0.2956, 0.5648)
 4  ( 0.1199,-0.1231) (-0.0046,-0.0005) (-0.3305, 0.4821) (-0.0675, 0.3464)
 5  (-0.2689,-0.1652) ( 0.1794,-0.0586) (-0.5235,-0.2580) ( 0.3927, 0.1450)
 6  (-0.3499, 0.0907) ( 0.0829,-0.0506) ( 0.3202, 0.3038) ( 0.3174, 0.3241)

 Example 2: bidiagonal matrix B
 Diagonal
     2.7615  1.6298 -1.3275
 Superdiagonal
    -0.9500 -1.0183

 Example 2: matrix P**H
                    1                 2                 3                 4
 1  (-0.1258, 0.1618) (-0.2247, 0.3864) ( 0.3460, 0.2157) (-0.7099,-0.2966)
 2  ( 0.4148, 0.1795) ( 0.1368,-0.3976) ( 0.6885, 0.3386) ( 0.1667,-0.0494)
 3  ( 0.4575,-0.4807) (-0.2733, 0.4981) (-0.0230, 0.3861) ( 0.1730, 0.2395)

Source

    Program zunmbr_example

!     ZUNMBR Example Program Text

!     Copyright 2017, Numerical Algorithms Group Ltd. http://www.nag.com

!     .. Use Statements ..
      Use lapack_example_aux, Only: nagf_blas_zmload, &
        nagf_file_print_matrix_complex_gen_comp
      Use lapack_interfaces, Only: zgebrd, zgelqf, zgeqrf, zlacpy, zunglq, &
        zungqr, zunmbr
      Use lapack_precision, Only: dp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Complex (Kind=dp), Parameter :: zero = (0.0E0_dp, 0.0E0_dp)
      Integer, Parameter :: nin = 5, nout = 6
!     .. Local Scalars ..
      Integer :: i, ic, ifail, info, lda, ldph, ldu, lwork, m, n
!     .. Local Arrays ..
      Complex (Kind=dp), Allocatable :: a(:, :), ph(:, :), tau(:), taup(:), &
        tauq(:), u(:, :), work(:)
      Real (Kind=dp), Allocatable :: d(:), e(:)
      Character (1) :: clabs(1), rlabs(1)
!     .. Executable Statements ..
      Write (nout, *) 'ZUNMBR Example Program Results'
!     Skip heading in data file
      Read (nin, *)
      Do ic = 1, 2
        Read (nin, *) m, n
        lda = m
        ldph = n
        ldu = m
        lwork = 64*(m+n)
        Allocate (a(lda,n), ph(ldph,n), tau(n), taup(n), tauq(n), u(ldu,n), &
          work(lwork), d(n), e(n-1))

!       Read A from data file

        Read (nin, *)(a(i,1:n), i=1, m)

        If (m>=n) Then

!         Compute the QR factorization of A
          Call zgeqrf(m, n, a, lda, tau, work, lwork, info)

!         Copy A to U
          Call zlacpy('Lower', m, n, a, lda, u, ldu)

!         Form Q explicitly, storing the result in U
          Call zungqr(m, n, n, u, ldu, tau, work, lwork, info)

!         Copy R to PH (used as workspace)
          Call zlacpy('Upper', n, n, a, lda, ph, ldph)

!         Set the strictly lower triangular part of R to zero
          Call nagf_blas_zmload('Lower', n-1, n-1, zero, zero, ph(2,1), ldph)

!         Bidiagonalize R
          Call zgebrd(n, n, ph, ldph, d, e, tauq, taup, work, lwork, info)

!         Update Q, storing the result in U
          Call zunmbr('Q', 'Right', 'No transpose', m, n, n, ph, ldph, tauq, &
            u, ldu, work, lwork, info)

!         Print bidiagonal form and matrix Q

          Write (nout, *)
          Write (nout, *) 'Example 1: bidiagonal matrix B'
          Write (nout, *) 'Diagonal'
          Write (nout, 100) d(1:n)
          Write (nout, *) 'Superdiagonal'
          Write (nout, 100) e(1:n-1)
          Write (nout, *)
          Flush (nout)

!         ifail: behaviour on error exit
!                =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
          ifail = 0
          Call nagf_file_print_matrix_complex_gen_comp('General', ' ', m, n, &
            u, ldu, 'Bracketed', 'F7.4', 'Example 1: matrix Q', 'Integer', &
            rlabs, 'Integer', clabs, 80, 0, ifail)

        Else

!         Compute the LQ factorization of A
          Call zgelqf(m, n, a, lda, tau, work, lwork, info)

!         Copy A to PH
          Call zlacpy('Upper', m, n, a, lda, ph, ldph)

!         Form Q explicitly, storing the result in PH
          Call zunglq(n, n, m, ph, ldph, tau, work, lwork, info)

!         Copy L to U (used as workspace)
          Call zlacpy('Lower', m, m, a, lda, u, ldu)

!         Set the strictly upper triangular part of L to zero
          Call nagf_blas_zmload('Upper', m-1, m-1, zero, zero, u(1,2), ldu)

!         Bidiagonalize L
          Call zgebrd(m, m, u, ldu, d, e, tauq, taup, work, lwork, info)

!         Update P**H, storing the result in PH
          Call zunmbr('P', 'Left', 'Conjugate transpose', m, n, m, u, ldu, &
            taup, ph, ldph, work, lwork, info)

!         Print bidiagonal form and matrix P**H

          Write (nout, *)
          Write (nout, *) 'Example 2: bidiagonal matrix B'
          Write (nout, *) 'Diagonal'
          Write (nout, 100) d(1:m)
          Write (nout, *) 'Superdiagonal'
          Write (nout, 100) e(1:m-1)
          Write (nout, *)
          Flush (nout)

          ifail = 0
          Call nagf_file_print_matrix_complex_gen_comp('General', ' ', m, n, &
            ph, ldph, 'Bracketed', 'F7.4', 'Example 2: matrix P**H', &
            'Integer', rlabs, 'Integer', clabs, 80, 0, ifail)

        End If
        Deallocate (a, ph, tau, taup, tauq, u, work, d, e)
      End Do

100   Format (3X, (8F8.4))
    End Program
Full documentation of ZUNMBR


ZUNMHR example

Computational Routines: Apply unitary transformation matrix from reduction to Hessenberg form determined by ZGEHRD

Data

ZUNMHR Example Program Data
  4                                                        :Value of N
 (-3.97,-5.04) (-4.11, 3.70) (-0.34, 1.01) ( 1.29,-0.86)
 ( 0.34,-1.50) ( 1.52,-0.43) ( 1.88,-5.38) ( 3.36, 0.65)
 ( 3.31,-3.85) ( 2.50, 3.45) ( 0.88,-1.08) ( 0.64,-1.48)
 (-1.10, 0.82) ( 1.81,-1.59) ( 3.25, 1.33) ( 1.57,-3.44)   :End of matrix A
  0.0                                                      :Value of THRESH

Result

 ZUNMHR Example Program Results

 Eigenvalues
    (-6.0004,-6.9998) (-5.0000, 2.0060) ( 7.9982,-0.9964) ( 3.0023,-3.9998)

 Contents of array C
                    1                 2
 1  ( 0.8457, 0.0000) (-0.3865, 0.1732)
 2  (-0.0177, 0.3036) (-0.3539, 0.4529)
 3  ( 0.0875, 0.3115) ( 0.6124, 0.0000)
 4  (-0.0561,-0.2906) (-0.0859,-0.3284)

Source

    Program zunmhr_example

!     ZUNMHR Example Program Text

!     Copyright 2017, Numerical Algorithms Group Ltd. http://www.nag.com

!     .. Use Statements ..
      Use blas_interfaces, Only: dznrm2
      Use lapack_example_aux, Only: nagf_file_print_matrix_complex_gen_comp
      Use lapack_interfaces, Only: zgehrd, zhsein, zhseqr, zunmhr
      Use lapack_precision, Only: dp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter :: nin = 5, nout = 6
!     .. Local Scalars ..
      Complex (Kind=dp) :: scal
      Real (Kind=dp) :: thresh
      Integer :: i, ifail, info, k, lda, ldc, ldh, ldvl, ldz, lwork, m, n
!     .. Local Arrays ..
      Complex (Kind=dp), Allocatable :: a(:, :), c(:, :), h(:, :), tau(:), &
        vl(:, :), w(:), work(:), z(:, :)
      Real (Kind=dp), Allocatable :: rwork(:)
      Integer, Allocatable :: ifaill(:), ifailr(:)
      Logical, Allocatable :: select(:)
      Character (1) :: clabs(1), rlabs(1)
!     .. Intrinsic Procedures ..
      Intrinsic :: abs, aimag, conjg, maxloc, real
!     .. Executable Statements ..
      Write (nout, *) 'ZUNMHR Example Program Results'
      Flush (nout)
!     Skip heading in data file
      Read (nin, *)
      Read (nin, *) n
      ldz = 1
      lda = n
      ldc = n
      ldh = n
      ldvl = n
      lwork = 64*n
      Allocate (a(lda,n), c(ldc,n), h(ldh,n), tau(n), vl(ldvl,n), w(n), &
        work(lwork), z(ldz,1), rwork(n), ifaill(n), ifailr(n), select(n))

!     Read A from data file
      Read (nin, *)(a(i,1:n), i=1, n)

      Read (nin, *) thresh

!     Reduce A to upper Hessenberg form H = (Q**H)*A*Q
      Call zgehrd(n, 1, n, a, lda, tau, work, lwork, info)

!     Copy A to H
      h(1:n, 1:n) = a(1:n, 1:n)

!     Calculate the eigenvalues of H (same as A)
      Call zhseqr('Eigenvalues', 'No vectors', n, 1, n, h, ldh, w, z, ldz, &
        work, lwork, info)

      Write (nout, *)
      If (info>0) Then
        Write (nout, *) 'Failure to converge.'
      Else
        Write (nout, *) 'Eigenvalues'
        Write (nout, 100)(' (', real(w(i)), ',', aimag(w(i)), ')', i=1, n)
        Flush (nout)

        Do i = 1, n
          select(i) = real(w(i)) < thresh
        End Do

!       Calculate the eigenvectors of H (as specified by SELECT),
!       storing the result in C
        Call zhsein('Right', 'QR', 'No initial vectors', select, n, a, lda, w, &
          vl, ldvl, c, ldc, n, m, work, rwork, ifaill, ifailr, info)

!       Calculate the eigenvectors of A = Q * (eigenvectors of H)
        Call zunmhr('Left', 'No transpose', n, m, 1, n, a, lda, tau, c, ldc, &
          work, lwork, info)

!       Print eigenvectors

        Write (nout, *)
        Flush (nout)

!       Normalize the eigenvectors, largest element real
        Do i = 1, m
          rwork(1:n) = abs(c(1:n,i))
          k = maxloc(rwork(1:n), 1)
          scal = conjg(c(k,i))/abs(c(k,i))/dznrm2(n, c(1,i), 1)
          c(1:n, i) = c(1:n, i)*scal
        End Do

!       ifail: behaviour on error exit
!              =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
        ifail = 0
        Call nagf_file_print_matrix_complex_gen_comp('General', ' ', n, m, c, &
          ldc, 'Bracketed', 'F7.4', 'Contents of array C', 'Integer', rlabs, &
          'Integer', clabs, 80, 0, ifail)

      End If

100   Format ((3X,4(A,F7.4,A,F7.4,A,:)))
    End Program
Full documentation of ZUNMHR


ZUNMTR example

Computational Routines: Apply unitary transformation matrix determined by ZHETRD

Data

ZUNMTR Example Program Data
  4                                                        :Value of N
  'L'                                                      :Value of UPLO
 (-2.28, 0.00)
 ( 1.78, 2.03) (-1.12, 0.00)
 ( 2.26,-0.10) ( 0.01,-0.43) (-0.37, 0.00)
 (-0.12,-2.53) (-1.07,-0.86) ( 2.31, 0.92) (-0.73, 0.00)   :End of matrix A

Result

 ZUNMTR Example Program Results

 Eigenvalues
        -6.0002           -3.0030

 Eigenvectors
                    1                 2
 1  ( 0.7299, 0.0000) (-0.2120, 0.1497)
 2  (-0.1663,-0.2061) ( 0.7307, 0.0000)
 3  (-0.4165,-0.1417) (-0.3291, 0.0479)
 4  ( 0.1743, 0.4162) ( 0.5200, 0.1329)

Source

    Program zunmtr_example

!     ZUNMTR Example Program Text

!     Copyright 2017, Numerical Algorithms Group Ltd. http://www.nag.com

!     .. Use Statements ..
      Use blas_interfaces, Only: zscal
      Use lapack_example_aux, Only: nagf_file_print_matrix_complex_gen_comp
      Use lapack_interfaces, Only: dstebz, zhetrd, zstein, zunmtr
      Use lapack_precision, Only: dp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Real (Kind=dp), Parameter :: zero = 0.0E0_dp
      Integer, Parameter :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=dp) :: vl, vu
      Integer :: i, ifail, info, k, lda, ldc, lwork, m, n, nsplit
      Character (1) :: uplo
!     .. Local Arrays ..
      Complex (Kind=dp), Allocatable :: a(:, :), c(:, :), tau(:), work(:)
      Real (Kind=dp), Allocatable :: d(:), e(:), rwork(:), w(:)
      Integer, Allocatable :: iblock(:), ifailv(:), isplit(:), iwork(:)
      Character (1) :: clabs(1), rlabs(1)
!     .. Intrinsic Procedures ..
      Intrinsic :: abs, cmplx, conjg, maxloc
!     .. Executable Statements ..
      Write (nout, *) 'ZUNMTR Example Program Results'
!     Skip heading in data file
      Read (nin, *)
      Read (nin, *) n
      lda = n
      ldc = n
      lwork = 64*n
      Allocate (a(lda,n), c(ldc,n), tau(n), work(lwork), d(n), e(n), &
        rwork(5*n), w(n), iblock(n), ifailv(n), isplit(n), iwork(3*n))

!     Read A from data file

      Read (nin, *) uplo
      If (uplo=='U') Then
        Read (nin, *)(a(i,i:n), i=1, n)
      Else If (uplo=='L') Then
        Read (nin, *)(a(i,1:i), i=1, n)
      End If

!     Reduce A to tridiagonal form T = (Q**H)*A*Q
      Call zhetrd(uplo, n, a, lda, d, e, tau, work, lwork, info)

!     Calculate the two smallest eigenvalues of T (same as A)

      Call dstebz('I', 'B', n, vl, vu, 1, 2, zero, d, e, m, nsplit, w, iblock, &
        isplit, rwork, iwork, info)

      Write (nout, *)
      If (info>0) Then
        Write (nout, *) 'Failure to converge.'
      Else
        Write (nout, *) 'Eigenvalues'
        Write (nout, 100) w(1:m)

!       Calculate the eigenvectors of T, storing the result in C
        Call zstein(n, d, e, m, w, iblock, isplit, c, ldc, rwork, iwork, &
          ifailv, info)

        If (info>0) Then
          Write (nout, *) 'Failure to converge.'
        Else

!         Calculate the eigenvectors of A = Q * (eigenvectors of T)
          Call zunmtr('Left', uplo, 'No transpose', n, m, a, lda, tau, c, ldc, &
            work, lwork, info)

!         Print eigenvectors
          Write (nout, *)
          Flush (nout)

!         Normalize the eigenvectors so that the element of largest absolute
!         value is real.
          Do i = 1, m
            rwork(1:n) = abs(c(1:n,i))
            k = maxloc(rwork(1:n), 1)
            Call zscal(n, conjg(c(k,i))/cmplx(abs(c(k,i)),kind=dp), c(1,i), 1)
          End Do

!         ifail: behaviour on error exit
!                =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
          ifail = 0
          Call nagf_file_print_matrix_complex_gen_comp('General', ' ', n, m, &
            c, ldc, 'Bracketed', 'F7.4', 'Eigenvectors', 'Integer', rlabs, &
            'Integer', clabs, 80, 0, ifail)

        End If
      End If

100   Format (8X, 4(F7.4,11X,:))
    End Program
Full documentation of ZUNMTR


ZUPGTR example

Computational Routines: Generate unitary transformation matrix from reduction to tridiagonal form determined by ZHPTRD

Data

ZUPGTR Example Program Data
  4                                                        :Value of N
  'L'                                                      :Value of UPLO
 (-2.28, 0.00)
 ( 1.78, 2.03) (-1.12, 0.00)
 ( 2.26,-0.10) ( 0.01,-0.43) (-0.37, 0.00)
 (-0.12,-2.53) (-1.07,-0.86) ( 2.31, 0.92) (-0.73, 0.00)   :End of matrix A

Result

 ZUPGTR Example Program Results

 Eigenvalues
        -6.0002           -3.0030            0.5036            3.9996

 Eigenvectors
                    1                 2                 3                 4
 1  ( 0.7299, 0.0000) (-0.2120, 0.1497) ( 0.1000,-0.3570) ( 0.1991, 0.4720)
 2  (-0.1663,-0.2061) ( 0.7307,-0.0000) ( 0.2863,-0.3353) (-0.2467, 0.3751)
 3  (-0.4165,-0.1417) (-0.3291, 0.0479) ( 0.6890, 0.0000) ( 0.4468, 0.1466)
 4  ( 0.1743, 0.4162) ( 0.5200, 0.1329) ( 0.0662, 0.4347) ( 0.5612, 0.0000)

Source

    Program zupgtr_example

!     ZUPGTR Example Program Text

!     Copyright 2017, Numerical Algorithms Group Ltd. http://www.nag.com

!     .. Use Statements ..
      Use blas_interfaces, Only: dznrm2
      Use lapack_example_aux, Only: nagf_file_print_matrix_complex_gen_comp
      Use lapack_interfaces, Only: zhptrd, zsteqr, zupgtr
      Use lapack_precision, Only: dp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter :: nin = 5, nout = 6
!     .. Local Scalars ..
      Complex (Kind=dp) :: scal
      Integer :: i, ifail, info, j, k, ldq, n
      Character (1) :: uplo
!     .. Local Arrays ..
      Complex (Kind=dp), Allocatable :: ap(:), q(:, :), tau(:), work(:)
      Real (Kind=dp), Allocatable :: d(:), e(:), rwork(:)
      Character (1) :: clabs(1), rlabs(1)
!     .. Intrinsic Procedures ..
      Intrinsic :: abs, conjg, maxloc
!     .. Executable Statements ..
      Write (nout, *) 'ZUPGTR Example Program Results'
!     Skip heading in data file
      Read (nin, *)
      Read (nin, *) n
      ldq = n
      Allocate (ap(n*(n+1)/2), q(ldq,n), tau(n), work(n-1), d(n), e(n), rwork( &
        2*n-2))

!     Read A from data file

      Read (nin, *) uplo
      If (uplo=='U') Then
        Read (nin, *)((ap(i+j*(j-1)/2),j=i,n), i=1, n)
      Else If (uplo=='L') Then
        Read (nin, *)((ap(i+(2*n-j)*(j-1)/2),j=1,i), i=1, n)
      End If

!     Reduce A to tridiagonal form T = (Q**H)*A*Q
      Call zhptrd(uplo, n, ap, d, e, tau, info)

!     Form Q explicitly, storing the result in Q
      Call zupgtr(uplo, n, ap, tau, q, ldq, work, info)

!     Calculate all the eigenvalues and eigenvectors of A
      Call zsteqr('V', n, d, e, q, ldq, rwork, info)

      Write (nout, *)
      If (info>0) Then
        Write (nout, *) 'Failure to converge.'
      Else

!       Print eigenvalues and eigenvectors

        Write (nout, *) 'Eigenvalues'
        Write (nout, 100) d(1:n)
        Write (nout, *)
        Flush (nout)

!       Normalize the eigenvectors, largest element real
        Do i = 1, n
          rwork(1:n) = abs(q(1:n,i))
          k = maxloc(rwork(1:n), 1)
          scal = conjg(q(k,i))/abs(q(k,i))/dznrm2(n, q(1,i), 1)
          q(1:n, i) = q(1:n, i)*scal
        End Do

!       ifail: behaviour on error exit
!              =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
        ifail = 0
        Call nagf_file_print_matrix_complex_gen_comp('General', ' ', n, n, q, &
          ldq, 'Bracketed', 'F7.4', 'Eigenvectors', 'Integer', rlabs, &
          'Integer', clabs, 80, 0, ifail)

      End If

100   Format (8X, 4(F7.4,11X,:))
    End Program
Full documentation of ZUPGTR


ZUPMTR example

Computational Routines: Apply unitary transformation matrix determined by ZHPTRD

Data

ZUPMTR Example Program Data
  4                                                        :Value of N
  'L'                                                      :Value of UPLO
 (-2.28, 0.00)
 ( 1.78, 2.03) (-1.12, 0.00)
 ( 2.26,-0.10) ( 0.01,-0.43) (-0.37, 0.00)
 (-0.12,-2.53) (-1.07,-0.86) ( 2.31, 0.92) (-0.73, 0.00)   :End of matrix A

Result

 ZUPMTR Example Program Results

 Eigenvalues
        -6.0002           -3.0030

 Eigenvectors
                    1                 2
 1  ( 0.7299, 0.0000) (-0.2120, 0.1497)
 2  (-0.1663,-0.2061) ( 0.7307, 0.0000)
 3  (-0.4165,-0.1417) (-0.3291, 0.0479)
 4  ( 0.1743, 0.4162) ( 0.5200, 0.1329)

Source

    Program zupmtr_example

!     ZUPMTR Example Program Text

!     Copyright 2017, Numerical Algorithms Group Ltd. http://www.nag.com

!     .. Use Statements ..
      Use blas_interfaces, Only: dznrm2
      Use lapack_example_aux, Only: nagf_file_print_matrix_complex_gen_comp
      Use lapack_interfaces, Only: dstebz, zhptrd, zstein, zupmtr
      Use lapack_precision, Only: dp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Real (Kind=dp), Parameter :: zero = 0.0E0_dp
      Integer, Parameter :: nin = 5, nout = 6
!     .. Local Scalars ..
      Complex (Kind=dp) :: scal
      Real (Kind=dp) :: vl, vu
      Integer :: i, ifail, info, j, k, ldc, m, n, nsplit
      Character (1) :: uplo
!     .. Local Arrays ..
      Complex (Kind=dp), Allocatable :: ap(:), c(:, :), tau(:), work(:)
      Real (Kind=dp), Allocatable :: d(:), e(:), rwork(:), w(:)
      Integer, Allocatable :: iblock(:), ifailv(:), isplit(:), iwork(:)
      Character (1) :: clabs(1), rlabs(1)
!     .. Intrinsic Procedures ..
      Intrinsic :: abs, conjg, maxloc
!     .. Executable Statements ..
      Write (nout, *) 'ZUPMTR Example Program Results'
!     Skip heading in data file
      Read (nin, *)
      Read (nin, *) n
      ldc = n
      Allocate (ap(n*(n+1)/2), c(ldc,n), tau(n), work(n), d(n), e(n), rwork(5* &
        n), w(n), iblock(n), ifailv(n), isplit(n), iwork(3*n))

!     Read A from data file

      Read (nin, *) uplo
      If (uplo=='U') Then
        Read (nin, *)((ap(i+j*(j-1)/2),j=i,n), i=1, n)
      Else If (uplo=='L') Then
        Read (nin, *)((ap(i+(2*n-j)*(j-1)/2),j=1,i), i=1, n)
      End If

!     Reduce A to tridiagonal form T = (Q**H)*A*Q
      Call zhptrd(uplo, n, ap, d, e, tau, info)

!     Calculate the two smallest eigenvalues of T (same as A)

      Call dstebz('I', 'B', n, vl, vu, 1, 2, zero, d, e, m, nsplit, w, iblock, &
        isplit, rwork, iwork, info)

      Write (nout, *)
      If (info>0) Then
        Write (nout, *) 'Failure to converge.'
      Else
        Write (nout, *) 'Eigenvalues'
        Write (nout, 100) w(1:m)

!       Calculate the eigenvectors of T, storing the result in C
        Call zstein(n, d, e, m, w, iblock, isplit, c, ldc, rwork, iwork, &
          ifailv, info)

        If (info>0) Then
          Write (nout, *) 'Failure to converge.'
        Else

!         Calculate the eigenvectors of A = Q * (eigenvectors of T)
          Call zupmtr('Left', uplo, 'No transpose', n, m, ap, tau, c, ldc, &
            work, info)

!         Print eigenvectors

          Write (nout, *)
          Flush (nout)

!         Normalize the eigenvectors, largest element real
          Do i = 1, m
            rwork(1:n) = abs(c(1:n,i))
            k = maxloc(rwork(1:n), 1)
            scal = conjg(c(k,i))/abs(c(k,i))/dznrm2(n, c(1,i), 1)
            c(1:n, i) = c(1:n, i)*scal
          End Do

!         ifail: behaviour on error exit
!                =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
          ifail = 0
          Call nagf_file_print_matrix_complex_gen_comp('General', ' ', n, m, &
            c, ldc, 'Bracketed', 'F7.4', 'Eigenvectors', 'Integer', rlabs, &
            'Integer', clabs, 80, 0, ifail)

        End If
      End If

100   Format (8X, 4(F7.4,11X,:))
    End Program
Full documentation of ZUPMTR


LAPACK Extra Routines

Extra routines

These extra routines are being used in the example programs. They are also in NAG Fortran Library (but with different names). Please refer to NAG Fortran Library document for the routines.

  • nagf_blas_damax_val (F16JQF)
    F16JQF (BLAS_DAMAX_VAL) computes, with respect to absolute value, the largest component of a real vector, along with the index of that component.
  • nagf_blas_ddscl (F06FCF)
    F06FCF multiplies a real vector by a real diagonal matrix.
  • nagf_blas_dpyth (F06BNF)
    F06BNF returns the value √(A2+B2).
  • nagf_blas_zddscl (F06KCF)
    F06KCF multiplies a complex vector by a real diagonal matrix.
  • nagf_blas_zmload (F06THF)
    F06THF forms the complex m by n rectangular or trapezoidal matrix A given by A(i,j) = MERGE(DIAG,CON,i==j).
  • nagf_file_print_matrix_complex_band (X04DEF)
    X04DEF is an easy-to-use routine to print a complex band matrix stored in a packed two-dimensional array.
  • nagf_file_print_matrix_complex_band_comp (X04DFF)
    X04DFF prints a complex band matrix stored in a packed two-dimensional array.
  • nagf_file_print_matrix_complex_gen (X04DAF)
    X04DAF is an easy-to-use routine to print a complex matrix stored in a two-dimensional array.
  • nagf_file_print_matrix_complex_gen_comp (X04DBF)
    X04DBF prints a complex matrix stored in a two-dimensional array.
  • nagf_file_print_matrix_complex_packed_comp (X04DDF)
    X04DDF prints a complex triangular matrix stored in a packed one-dimensional array.
  • nagf_file_print_matrix_integer_comp (X04EBF)
    X04EBF prints an integer matrix stored in a two-dimensional array.
  • nagf_file_print_matrix_real_band (X04CEF)
    X04CEF is an easy-to-use routine to print a real band matrix stored in a packed two-dimensional array.
  • nagf_file_print_matrix_real_gen (X04CAF)
    X04CAF is an easy-to-use routine to print a real matrix stored in a two-dimensional array.
  • nagf_file_print_matrix_real_gen_comp (X04CBF)
    X04CBF prints a real matrix stored in a two-dimensional array.
  • nagf_file_print_matrix_real_packed (X04CCF)
    X04CCF is an easy-to-use routine to print a real triangular matrix stored in a packed one-dimensional array.
  • nagf_sort_cmplxvec_rank_rearrange (M01EDF)
    M01EDF rearranges a vector of complex numbers into the order specified by a vector of ranks.
  • nagf_sort_realmat_rank_rows (M01DEF)
    M01DEF ranks the rows of a matrix of real numbers in ascending or descending order.
  • nagf_sort_realvec_rank (M01DAF)
    M01DAF ranks a vector of real numbers in ascending or descending order.
  • nagf_sort_realvec_rank_rearrange (M01EAF)
    M01EAF rearranges a vector of real numbers into the order specified by a vector of ranks.


GTK+ User Guide

GTK+
The GIMP Toolkit

GTK+ Project Web Site
http://www.gtk.org/

Licence
Outline of GTK+
Template Programs
GTK+ 2.0 Tutorial (for Fortran Builder)
Reference Manuals


About the GTK+ Licence

As stated on the official website,

GTK+ is licensed under the GNU LGPL 2.1 allowing development of both free and proprietary software with GTK+ without any license fees or royalties.
The text of the GNU LGPL 2.1 is reproduced below.

          GNU LESSER GENERAL PUBLIC LICENSE
               Version 2.1, February 1999

 Copyright (C) 1991, 1999 Free Software Foundation, Inc.
 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
 Everyone is permitted to copy and distribute verbatim copies
 of this license document, but changing it is not allowed.

[This is the first released version of the Lesser GPL.  It also counts
 as the successor of the GNU Library Public License, version 2, hence
 the version number 2.1.]

                Preamble

  The licenses for most software are designed to take away your
freedom to share and change it.  By contrast, the GNU General Public
Licenses are intended to guarantee your freedom to share and change
free software--to make sure the software is free for all its users.

  This license, the Lesser General Public License, applies to some
specially designated software packages--typically libraries--of the
Free Software Foundation and other authors who decide to use it.  You
can use it too, but we suggest you first think carefully about whether
this license or the ordinary General Public License is the better
strategy to use in any particular case, based on the explanations below.

  When we speak of free software, we are referring to freedom of use,
not price.  Our General Public Licenses are designed to make sure that
you have the freedom to distribute copies of free software (and charge
for this service if you wish); that you receive source code or can get
it if you want it; that you can change the software and use pieces of
it in new free programs; and that you are informed that you can do
these things.

  To protect your rights, we need to make restrictions that forbid
distributors to deny you these rights or to ask you to surrender these
rights.  These restrictions translate to certain responsibilities for
you if you distribute copies of the library or if you modify it.

  For example, if you distribute copies of the library, whether gratis
or for a fee, you must give the recipients all the rights that we gave
you.  You must make sure that they, too, receive or can get the source
code.  If you link other code with the library, you must provide
complete object files to the recipients, so that they can relink them
with the library after making changes to the library and recompiling
it.  And you must show them these terms so they know their rights.

  We protect your rights with a two-step method: (1) we copyright the
library, and (2) we offer you this license, which gives you legal
permission to copy, distribute and/or modify the library.

  To protect each distributor, we want to make it very clear that
there is no warranty for the free library.  Also, if the library is
modified by someone else and passed on, the recipients should know
that what they have is not the original version, so that the original
author's reputation will not be affected by problems that might be
introduced by others.

  Finally, software patents pose a constant threat to the existence of
any free program.  We wish to make sure that a company cannot
effectively restrict the users of a free program by obtaining a
restrictive license from a patent holder.  Therefore, we insist that
any patent license obtained for a version of the library must be
consistent with the full freedom of use specified in this license.

  Most GNU software, including some libraries, is covered by the
ordinary GNU General Public License.  This license, the GNU Lesser
General Public License, applies to certain designated libraries, and
is quite different from the ordinary General Public License.  We use
this license for certain libraries in order to permit linking those
libraries into non-free programs.

  When a program is linked with a library, whether statically or using
a shared library, the combination of the two is legally speaking a
combined work, a derivative of the original library.  The ordinary
General Public License therefore permits such linking only if the
entire combination fits its criteria of freedom.  The Lesser General
Public License permits more lax criteria for linking other code with
the library.

  We call this license the "Lesser" General Public License because it
does Less to protect the user's freedom than the ordinary General
Public License.  It also provides other free software developers Less
of an advantage over competing non-free programs.  These disadvantages
are the reason we use the ordinary General Public License for many
libraries.  However, the Lesser license provides advantages in certain
special circumstances.

  For example, on rare occasions, there may be a special need to
encourage the widest possible use of a certain library, so that it becomes
a de-facto standard.  To achieve this, non-free programs must be
allowed to use the library.  A more frequent case is that a free
library does the same job as widely used non-free libraries.  In this
case, there is little to gain by limiting the free library to free
software only, so we use the Lesser General Public License.

  In other cases, permission to use a particular library in non-free
programs enables a greater number of people to use a large body of
free software.  For example, permission to use the GNU C Library in
non-free programs enables many more people to use the whole GNU
operating system, as well as its variant, the GNU/Linux operating
system.

  Although the Lesser General Public License is Less protective of the
users' freedom, it does ensure that the user of a program that is
linked with the Library has the freedom and the wherewithal to run
that program using a modified version of the Library.

  The precise terms and conditions for copying, distribution and
modification follow.  Pay close attention to the difference between a
"work based on the library" and a "work that uses the library".  The
former contains code derived from the library, whereas the latter must
be combined with the library in order to run.

          GNU LESSER GENERAL PUBLIC LICENSE
   TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION

  0. This License Agreement applies to any software library or other
program which contains a notice placed by the copyright holder or
other authorized party saying it may be distributed under the terms of
this Lesser General Public License (also called "this License").
Each licensee is addressed as "you".

  A "library" means a collection of software functions and/or data
prepared so as to be conveniently linked with application programs
(which use some of those functions and data) to form executables.

  The "Library", below, refers to any such software library or work
which has been distributed under these terms.  A "work based on the
Library" means either the Library or any derivative work under
copyright law: that is to say, a work containing the Library or a
portion of it, either verbatim or with modifications and/or translated
straightforwardly into another language.  (Hereinafter, translation is
included without limitation in the term "modification".)

  "Source code" for a work means the preferred form of the work for
making modifications to it.  For a library, complete source code means
all the source code for all modules it contains, plus any associated
interface definition files, plus the scripts used to control compilation
and installation of the library.

  Activities other than copying, distribution and modification are not
covered by this License; they are outside its scope.  The act of
running a program using the Library is not restricted, and output from
such a program is covered only if its contents constitute a work based
on the Library (independent of the use of the Library in a tool for
writing it).  Whether that is true depends on what the Library does
and what the program that uses the Library does.

  1. You may copy and distribute verbatim copies of the Library's
complete source code as you receive it, in any medium, provided that
you conspicuously and appropriately publish on each copy an
appropriate copyright notice and disclaimer of warranty; keep intact
all the notices that refer to this License and to the absence of any
warranty; and distribute a copy of this License along with the
Library.

  You may charge a fee for the physical act of transferring a copy,
and you may at your option offer warranty protection in exchange for a
fee.

  2. You may modify your copy or copies of the Library or any portion
of it, thus forming a work based on the Library, and copy and
distribute such modifications or work under the terms of Section 1
above, provided that you also meet all of these conditions:

    a) The modified work must itself be a software library.

    b) You must cause the files modified to carry prominent notices
    stating that you changed the files and the date of any change.

    c) You must cause the whole of the work to be licensed at no
    charge to all third parties under the terms of this License.

    d) If a facility in the modified Library refers to a function or a
    table of data to be supplied by an application program that uses
    the facility, other than as an argument passed when the facility
    is invoked, then you must make a good faith effort to ensure that,
    in the event an application does not supply such function or
    table, the facility still operates, and performs whatever part of
    its purpose remains meaningful.

    (For example, a function in a library to compute square roots has
    a purpose that is entirely well-defined independent of the
    application.  Therefore, Subsection 2d requires that any
    application-supplied function or table used by this function must
    be optional: if the application does not supply it, the square
    root function must still compute square roots.)

These requirements apply to the modified work as a whole.  If
identifiable sections of that work are not derived from the Library,
and can be reasonably considered independent and separate works in
themselves, then this License, and its terms, do not apply to those
sections when you distribute them as separate works.  But when you
distribute the same sections as part of a whole which is a work based
on the Library, the distribution of the whole must be on the terms of
this License, whose permissions for other licensees extend to the
entire whole, and thus to each and every part regardless of who wrote
it.

Thus, it is not the intent of this section to claim rights or contest
your rights to work written entirely by you; rather, the intent is to
exercise the right to control the distribution of derivative or
collective works based on the Library.

In addition, mere aggregation of another work not based on the Library
with the Library (or with a work based on the Library) on a volume of
a storage or distribution medium does not bring the other work under
the scope of this License.

  3. You may opt to apply the terms of the ordinary GNU General Public
License instead of this License to a given copy of the Library.  To do
this, you must alter all the notices that refer to this License, so
that they refer to the ordinary GNU General Public License, version 2,
instead of to this License.  (If a newer version than version 2 of the
ordinary GNU General Public License has appeared, then you can specify
that version instead if you wish.)  Do not make any other change in
these notices.

  Once this change is made in a given copy, it is irreversible for
that copy, so the ordinary GNU General Public License applies to all
subsequent copies and derivative works made from that copy.

  This option is useful when you wish to copy part of the code of
the Library into a program that is not a library.

  4. You may copy and distribute the Library (or a portion or
derivative of it, under Section 2) in object code or executable form
under the terms of Sections 1 and 2 above provided that you accompany
it with the complete corresponding machine-readable source code, which
must be distributed under the terms of Sections 1 and 2 above on a
medium customarily used for software interchange.

  If distribution of object code is made by offering access to copy
from a designated place, then offering equivalent access to copy the
source code from the same place satisfies the requirement to
distribute the source code, even though third parties are not
compelled to copy the source along with the object code.

  5. A program that contains no derivative of any portion of the
Library, but is designed to work with the Library by being compiled or
linked with it, is called a "work that uses the Library".  Such a
work, in isolation, is not a derivative work of the Library, and
therefore falls outside the scope of this License.

  However, linking a "work that uses the Library" with the Library
creates an executable that is a derivative of the Library (because it
contains portions of the Library), rather than a "work that uses the
library".  The executable is therefore covered by this License.
Section 6 states terms for distribution of such executables.

  When a "work that uses the Library" uses material from a header file
that is part of the Library, the object code for the work may be a
derivative work of the Library even though the source code is not.
Whether this is true is especially significant if the work can be
linked without the Library, or if the work is itself a library.  The
threshold for this to be true is not precisely defined by law.

  If such an object file uses only numerical parameters, data
structure layouts and accessors, and small macros and small inline
functions (ten lines or less in length), then the use of the object
file is unrestricted, regardless of whether it is legally a derivative
work.  (Executables containing this object code plus portions of the
Library will still fall under Section 6.)

  Otherwise, if the work is a derivative of the Library, you may
distribute the object code for the work under the terms of Section 6.
Any executables containing that work also fall under Section 6,
whether or not they are linked directly with the Library itself.

  6. As an exception to the Sections above, you may also combine or
link a "work that uses the Library" with the Library to produce a
work containing portions of the Library, and distribute that work
under terms of your choice, provided that the terms permit
modification of the work for the customer's own use and reverse
engineering for debugging such modifications.

  You must give prominent notice with each copy of the work that the
Library is used in it and that the Library and its use are covered by
this License.  You must supply a copy of this License.  If the work
during execution displays copyright notices, you must include the
copyright notice for the Library among them, as well as a reference
directing the user to the copy of this License.  Also, you must do one
of these things:

    a) Accompany the work with the complete corresponding
    machine-readable source code for the Library including whatever
    changes were used in the work (which must be distributed under
    Sections 1 and 2 above); and, if the work is an executable linked
    with the Library, with the complete machine-readable "work that
    uses the Library", as object code and/or source code, so that the
    user can modify the Library and then relink to produce a modified
    executable containing the modified Library.  (It is understood
    that the user who changes the contents of definitions files in the
    Library will not necessarily be able to recompile the application
    to use the modified definitions.)

    b) Use a suitable shared library mechanism for linking with the
    Library.  A suitable mechanism is one that (1) uses at run time a
    copy of the library already present on the user's computer system,
    rather than copying library functions into the executable, and (2)
    will operate properly with a modified version of the library, if
    the user installs one, as long as the modified version is
    interface-compatible with the version that the work was made with.

    c) Accompany the work with a written offer, valid for at
    least three years, to give the same user the materials
    specified in Subsection 6a, above, for a charge no more
    than the cost of performing this distribution.

    d) If distribution of the work is made by offering access to copy
    from a designated place, offer equivalent access to copy the above
    specified materials from the same place.

    e) Verify that the user has already received a copy of these
    materials or that you have already sent this user a copy.

  For an executable, the required form of the "work that uses the
Library" must include any data and utility programs needed for
reproducing the executable from it.  However, as a special exception,
the materials to be distributed need not include anything that is
normally distributed (in either source or binary form) with the major
components (compiler, kernel, and so on) of the operating system on
which the executable runs, unless that component itself accompanies
the executable.

  It may happen that this requirement contradicts the license
restrictions of other proprietary libraries that do not normally
accompany the operating system.  Such a contradiction means you cannot
use both them and the Library together in an executable that you
distribute.

  7. You may place library facilities that are a work based on the
Library side-by-side in a single library together with other library
facilities not covered by this License, and distribute such a combined
library, provided that the separate distribution of the work based on
the Library and of the other library facilities is otherwise
permitted, and provided that you do these two things:

    a) Accompany the combined library with a copy of the same work
    based on the Library, uncombined with any other library
    facilities.  This must be distributed under the terms of the
    Sections above.

    b) Give prominent notice with the combined library of the fact
    that part of it is a work based on the Library, and explaining
    where to find the accompanying uncombined form of the same work.

  8. You may not copy, modify, sublicense, link with, or distribute
the Library except as expressly provided under this License.  Any
attempt otherwise to copy, modify, sublicense, link with, or
distribute the Library is void, and will automatically terminate your
rights under this License.  However, parties who have received copies,
or rights, from you under this License will not have their licenses
terminated so long as such parties remain in full compliance.

  9. You are not required to accept this License, since you have not
signed it.  However, nothing else grants you permission to modify or
distribute the Library or its derivative works.  These actions are
prohibited by law if you do not accept this License.  Therefore, by
modifying or distributing the Library (or any work based on the
Library), you indicate your acceptance of this License to do so, and
all its terms and conditions for copying, distributing or modifying
the Library or works based on it.

  10. Each time you redistribute the Library (or any work based on the
Library), the recipient automatically receives a license from the
original licensor to copy, distribute, link with or modify the Library
subject to these terms and conditions.  You may not impose any further
restrictions on the recipients' exercise of the rights granted herein.
You are not responsible for enforcing compliance by third parties with
this License.

  11. If, as a consequence of a court judgment or allegation of patent
infringement or for any other reason (not limited to patent issues),
conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License.  If you cannot
distribute so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you
may not distribute the Library at all.  For example, if a patent
license would not permit royalty-free redistribution of the Library by
all those who receive copies directly or indirectly through you, then
the only way you could satisfy both it and this License would be to
refrain entirely from distribution of the Library.

If any portion of this section is held invalid or unenforceable under any
particular circumstance, the balance of the section is intended to apply,
and the section as a whole is intended to apply in other circumstances.

It is not the purpose of this section to induce you to infringe any
patents or other property right claims or to contest validity of any
such claims; this section has the sole purpose of protecting the
integrity of the free software distribution system which is
implemented by public license practices.  Many people have made
generous contributions to the wide range of software distributed
through that system in reliance on consistent application of that
system; it is up to the author/donor to decide if he or she is willing
to distribute software through any other system and a licensee cannot
impose that choice.

This section is intended to make thoroughly clear what is believed to
be a consequence of the rest of this License.

  12. If the distribution and/or use of the Library is restricted in
certain countries either by patents or by copyrighted interfaces, the
original copyright holder who places the Library under this License may add
an explicit geographical distribution limitation excluding those countries,
so that distribution is permitted only in or among countries not thus
excluded.  In such case, this License incorporates the limitation as if
written in the body of this License.

  13. The Free Software Foundation may publish revised and/or new
versions of the Lesser General Public License from time to time.
Such new versions will be similar in spirit to the present version,
but may differ in detail to address new problems or concerns.

Each version is given a distinguishing version number.  If the Library
specifies a version number of this License which applies to it and
"any later version", you have the option of following the terms and
conditions either of that version or of any later version published by
the Free Software Foundation.  If the Library does not specify a
license version number, you may choose any version ever published by
the Free Software Foundation.

  14. If you wish to incorporate parts of the Library into other free
programs whose distribution conditions are incompatible with these,
write to the author to ask for permission.  For software which is
copyrighted by the Free Software Foundation, write to the Free
Software Foundation; we sometimes make exceptions for this.  Our
decision will be guided by the two goals of preserving the free status
of all derivatives of our free software and of promoting the sharing
and reuse of software generally.

                NO WARRANTY

  15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO
WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW.
EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR
OTHER PARTIES PROVIDE THE LIBRARY "AS IS" WITHOUT WARRANTY OF ANY
KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE.  THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE
LIBRARY IS WITH YOU.  SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME
THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION.

  16. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN
WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY
AND/OR REDISTRIBUTE THE LIBRARY AS PERMITTED ABOVE, BE LIABLE TO YOU
FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR
CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE
LIBRARY (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING
RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A
FAILURE OF THE LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF
SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH
DAMAGES.

             END OF TERMS AND CONDITIONS

           How to Apply These Terms to Your New Libraries

  If you develop a new library, and you want it to be of the greatest
possible use to the public, we recommend making it free software that
everyone can redistribute and change.  You can do so by permitting
redistribution under these terms (or, alternatively, under the terms of the
ordinary General Public License).

  To apply these terms, attach the following notices to the library.  It is
safest to attach them to the start of each source file to most effectively
convey the exclusion of warranty; and each file should have at least the
"copyright" line and a pointer to where the full notice is found.

    <one line to give the library's name and a brief idea of what it does.>
    Copyright (C) <year>  <name of author>

    This library is free software; you can redistribute it and/or
    modify it under the terms of the GNU Lesser General Public
    License as published by the Free Software Foundation; either
    version 2.1 of the License, or (at your option) any later version.

    This library is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
    Lesser General Public License for more details.

    You should have received a copy of the GNU Lesser General Public
    License along with this library; if not, write to the Free Software
    Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA

Also add information on how to contact you by electronic and paper mail.

You should also get your employer (if you work as a programmer) or your
school, if any, to sign a "copyright disclaimer" for the library, if
necessary.  Here is a sample; alter the names:

  Yoyodyne, Inc., hereby disclaims all copyright interest in the
  library `Frob' (a library for tweaking knobs) written by James Random Hacker.

  <signature of Ty Coon>, 1 April 1990
  Ty Coon, President of Vice

That's all there is to it!


Outline of GTK+

The official public website of the GTK+ project can be found at http://www.gtk.org.

What is GTK+?

GTK+ is a highly usable, feature rich toolkit for creating graphical user interfaces which boasts cross platform compatibility and an easy to use API. GTK+ it is written in C, but has bindings to many other popular programming languages such as C++, Python and C# among others. GTK+ is licensed under the GNU LGPL 2.1 allowing development of both free and proprietary software with GTK+ without any license fees or royalties.

Creation

GTK+ was initially developed for and used by the GIMP, the GNU Image Manipulation Program. It is called the “The GIMP ToolKit” so that the origins of the project are remembered. Today it is more commonly known as GTK+ for short and is used by a large number of applications including the GNU project's GNOME desktop.

Peter Mattis started it all, with help from Spencer Kimball and Josh Macdonald. Marius Vollmer taught us how to make GTK+ work for language bindings. Lars Hamann and Stefan Jeske added all sorts of features to the core widgets. Carsten Haitzler designed and did the first implementation of theme support. Shawn Amundson did release management for GTK+ 1.0 and GTK+ 1.2.

Architecture

Over time GTK+ has been built up to be based on four libraries, also developed by the GTK+ team:

  • GLib, a low-level core library that forms the basis of GTK+. It provides data structure handling for C, portability wrappers and interfaces for such run-time functionality as an event loop, threads, dynamic loading and an object system.
  • Pango, a library for layout and rendering of text with an emphasis on internationalization. It forms the core of text and font handling for GTK+ 2.0.
  • Cairo, a library for 2D graphics with support for multiple output devices (including the X Window System, Win32) while producing a consistent output on all media while taking advantage of display hardware acceleration when available.
  • ATK, a library for a set of interfaces providing accessibility. By supporting the ATK interfaces, an application or toolkit can be used with tools such as screen readers, magnifiers, and alternative input devices.


GTK+ Template Programs

GTK01 | Base application
GTK02 | Hello world
GTK03 | Hello world (Glade version)
GTK04 | Table packing
GTK05 | Normal buttons
GTK06 | Toggle buttons
GTK07 | Check buttons
GTK08 | Radio buttons
GTK09 | Arrow buttons
GTK10 | Progress bars
GTK11 | Rulers
GTK12 | Status bars
GTK13 | Text entries
GTK14 | Spin buttons
GTK15 | Calendar
GTK16 | Range controls
GTK17 | Colour selection dialogue
GTK18 | File selection dialogue
GTK19 | Event box
GTK20 | Fixed container
GTK21 | Frames
GTK22 | Aspect frames
GTK23 | Paned window widgets
GTK24 | Scrolled windows
GTK25 | Button boxes
GTK26 | Notebooks
GTK27 | Creating menus manually
GTK28 | Example of item factory
GTK29 | Example of using rc file
GTK30 | Curve using Glade
GTK31 | Simple sketching window
GTK32 | Gears using OpenGL
GTK33 | Sphere using Glade+OpenGL
GTK34 | Two view areas using Glade+OpenGL
GTK35 | Pendulum using Glade+OpenGL
GTK36 | OpenGL drawing to two windows using Glade+OpenGL
GTK37 | Cool waves using OpenGL
GTK38 | Main application window
GTK39 | Assistant
GTK40 | Clipboard with drag and drop
GTK41 | Colour selector
GTK42 | Various combination boxes
GTK43 | Dialogue and message box
GTK44 | Drawing area
GTK45 | Entry completion
GTK46 | Expander
GTK47 | Displaying file folder icon
GTK48 | Editing, Drag-and-drop of colour icon
GTK49 | Animation and progressive display
GTK50 | Example of creating menu
GTK51 | Paned widgets
GTK52 | Various selectors
GTK53 | Image animation
GTK54 | Example of printing
GTK55 | Drawing rotated text
GTK56 | Size groups
GTK57 | Browsing stock item icons
GTK58 | Hypertext
GTK59 | Multiple hypertext views
GTK60 | Automatic text scrolling
GTK61 | Editable cells
GTK62 | List view and sorting
GTK63 | Tree store (example list of holidays)
GTK64 | User interface manager
GTK65 | 3D spring model


GTK+ 2.0 Tutorial (for Fortran Builder)

GTK+ 2.0 Tutorial

Tony Gale

Ian Main

& the GTK team

modified by
Nihon Numerical Algorithms Group K.K.
for the Fortran Builder.

Table of Contents
Tutorial Availability
Introduction
Getting Started
Hello World in GTK
Compiling Hello World
Theory of Signals and Callbacks
Events
Stepping Through Hello World
Moving On
Data Types
More on Signal Handlers
An Upgraded Hello World
Packing Widgets
Theory of Packing Boxes
Details of Boxes
Packing Demonstration Program
Packing Using Tables
Table Packing Example
Widget Overview
Casting
Widget Hierarchy
Widgets Without Windows
The Button Widget
Normal Buttons
Toggle Buttons
Check Buttons
Radio Buttons
Adjustments
Creating an Adjustment
Using Adjustments the Easy Way
Adjustment Internals
Range Widgets
Scrollbar Widgets
Scale Widgets
Creating a Scale Widget
Functions and Signals (well, functions, at least)
Common Range Functions
Setting the Update Policy
Getting and Setting Adjustments
Key and Mouse bindings
Example
Miscellaneous Widgets
Labels
Arrows
The Tooltips Object
Progress Bars
Dialogues
Rulers
Statusbars
Text Entries
Spin Buttons
Combo Box
Calendar
Colour Selection
File Selections
Container Widgets
The EventBox
The Alignment widget
Fixed Container
Layout Container
Frames
Aspect Frames
Paned Window Widgets
Viewports
Scrolled Windows
Button Boxes
Toolbar
Notebooks
Menu Widget
Manual Menu Creation
Manual Menu Example
Using ItemFactory
ItemFactory entries
Creating an ItemFactory
Making use of the menu and its menu items
Item Factory Example
Undocumented Widgets
Accel Label
Option Menu
Menu Items
Check Menu Item
Radio Menu Item
Separator Menu Item
Tearoff Menu Item
Curves
Drawing Area
Font Selection Dialogue
Message Dialogue
Gamma Curve
Image
Plugs and Sockets
Tree View
Text View
Setting Widget Attributes
Timeouts, I/O and Idle Functions
Timeouts
Monitoring Input/Output
Idle Functions
Advanced Event and Signal Handling
Signal Functions
Connecting and Disconnecting Signal Handlers
Blocking and Unblocking Signal Handlers
Emitting and Stopping Signals
Signal Emission and Propagation
Managing Selections
Overview
Retrieving the selection
Supplying the selection
Drag-and-drop (DND)
Overview
Properties
Functions
Setting up the source widget
Signals on the source widget:
Setting up a destination widget:
Signals on the destination widget:
GLib
Definitions
Doubly Linked Lists
Singly Linked Lists
Memory Management
Timers
String Handling
Utility and Error Functions
GTK's rc Files
Functions For rc Files
GTK's rc File Format
Example rc file
Writing Your Own Widgets
Overview
The Anatomy Of A Widget
Creating a Composite widget
Introduction
Choosing a parent class
The header file
The _get_type() function
The _class_init() function
The _init() function
And the rest...
Creating a widget from scratch
Introduction
Displaying a widget on the screen
The origins of the Dial Widget
The Basics
gtk_dial_realize()
Size negotiation
gtk_dial_expose()
Event handling
Possible Enhancements
Learning More
Scribble, A Simple Example Drawing Program
Overview
Event Handling
The DrawingArea Widget, And Drawing
Credits
Tutorial Copyright and Permissions Notice
GTK Signals
GtkObject
GtkWidget
GtkContainer
GtkCalendar
GtkEditable
GtkNotebook
GtkList
GtkMenuShell
GtkToolbar
GtkButton
GtkItem
GtkWindow
GtkHandleBox
GtkToggleButton
GtkMenuItem
GtkCheckMenuItem
GtkInputDialog
GtkColorSelection
GtkStatusBar
GtkCurve
GtkAdjustment
GDK Event Types
Code Examples
GtkDial
gtkdial.h
gtkdial.c
dial_test.c
Scribble
scribble-simple.f95
scribble-xinput.f95
Next >>>
Tutorial Availability


Tutorial Availability

A copy of the original tutorial in SGML and HTML is distributed with each source code release of GTK+. For binary distributions, please check with your vendor.

A copy is available online for reference at http://www.gtk.org/documentation.html#Tutorials . You can also find other GTK+ tutorials there.

A packaged version of the original tutorial is available from ftp://ftp.gtk.org/pub/gtk/tutorial which contains the tutorial in various different formats. This package is primary for those people wanting to have the tutorial available for offline reference and for printing. Note that the packaged version may be older than the online version.

<<< Previous | Home | Next >>>
GTK+ 2.0 Tutorial |  | Introduction


Introduction

GTK (GIMP Toolkit) is a library for creating graphical user interfaces. It is licensed using the LGPL license, so you can develop open software, free software, or even commercial non-free software using GTK without having to spend anything for licenses or royalties.

It's called the GIMP toolkit because it was originally written for developing the GNU Image Manipulation Program (GIMP), but GTK has now been used in a large number of software projects, including the GNU Network Object Model Environment (GNOME) project. GTK is built on top of GDK (GIMP Drawing Kit) which is basically a wrapper around the low-level functions for accessing the underlying windowing functions (Xlib in the case of the X windows system), and gdk-pixbuf, a library for client-side image manipulation.

GTK is essentially an object oriented application programmers interface (API). Although written completely in C, it is implemented using the idea of classes and callback functions (pointers to functions).

There is also a third component called GLib which contains a few replacements for some standard calls, as well as some additional functions for handling linked lists, etc. The replacement functions are used to increase GTK's portability, as some of the functions implemented here are not available or are nonstandard on other Unixes such as g_strerror(). Some also contain enhancements to the libc versions, such as g_malloc() that has enhanced debugging utilities.

In version 2.0, GLib has picked up the type system which forms the foundation for GTK's class hierarchy, the signal system which is used throughout GTK, a thread API which abstracts the different native thread APIs of the various platforms and a facility for loading modules.

As the last component, GTK uses the Pango library for internationalized text output.

This tutorial describes the C interface to GTK. There are GTK bindings for many other languages including C++, Guile, Perl, Python, TOM, Ada95, Objective C, Free Pascal, Eiffel, Java and C#. If you intend to use another language's bindings to GTK, look at that binding's documentation first. In some cases that documentation may describe some important conventions (which you should know first) and then refer you back to this tutorial. There are also some cross-platform APIs (such as wxWindows and V) which use GTK as one of their target platforms; again, consult their documentation first.

If you're developing your GTK application in C++, a few extra notes are in order. There's a C++ binding to GTK called GTK--, which provides a more C++-like interface to GTK; you should probably look into this instead. If you don't like that approach for whatever reason, there are two alternatives for using GTK. First, you can use only the C subset of C++ when interfacing with GTK and then use the C interface as described in this tutorial. Second, you can use GTK and C++ together by declaring all callbacks as static functions in C++ classes, and again calling GTK using its C interface. If you choose this last approach, you can include as the callback's data value a pointer to the object to be manipulated (the so-called "this" value). Selecting between these options is simply a matter of preference, since in all three approaches you get C++ and GTK. None of these approaches requires the use of a specialized preprocessor, so no matter what you choose you can use standard C++ with GTK.

This tutorial is an attempt to document as much as possible of GTK, but it is by no means complete. This tutorial assumes a good understanding of C, and how to create C programs. It would be a great benefit for the reader to have previous X programming experience, but it shouldn't be necessary. If you are learning GTK as your first widget set, please comment on how you found this tutorial, and what you had trouble with. There are also C++, Objective C, ADA, Guile and other language bindings available, but I don't follow these.

This document is a "work in progress". Please look for updates on http://www.gtk.org/ .

I would very much like to hear of any problems you have learning GTK from this document, and would appreciate input as to how it may be improved. Please see the section on Contributing for further information.

Conventions used in the Fortran Interface to GTK

The following conventions are widely used in the Fortran interface. Many of these are visible in the tutorial material.

  • As GTK is a C library, it uses integers to represent Logical values. Nearly all routines in this interface follow that convention, with type Integer(gboolean) indicating an integer that is used as a Logical value. Named constants TRUE and FALSE of type Integer(gboolean) are provided by the module and used in the examples for documentary purposes.
  • Many C functions return a pointer to a null-terminated C character string (“char *”). The Fortran interface has these returning a Fortran character array pointer (“Character,Pointer,Dimension(:)”), with the size of the array being the length (via strlen) of the C string excluding the trailing null character. If the C function returns a null pointer, the Fortran function also returns a null pointer.
  • Most C routines that accept character strings expect a null-terminated one. The corresponding Fortran routines generally expect a normal Fortran character string, no null-termination is expected. A few Fortran routines are generic and will also accept a character array; these also do not need null-termination. A few Fortran routines are generic and will also accept a Type(C_Ptr) argument in place of a character string; in this case the C pointer is expected to be address of a C character string (i.e. already null-terminated).
  • GTK uses a naming convention in C where upper case indicates a macro or enum value (e.g. G_CALLBACK or GTK_ARROW_UP), mixed case indicates a non-intrinsic type (e.g. GtkWidget), and lower case indicates a function or a renamed intrinsic type (e.g. gtk_init and gboolean). Fortran is not case-sensitive, thus in Fortran gtK_arroW_uP is the same as GTK_ARROW_UP; however, this document uses the same case for the Fortran entities as for the corresponding C entities, to avoid confusion.
<<< Previous | Home | Next >>>
Tutorial Availability |  | Getting Started


Getting Started

For working in the Fortran Builder, the GTK libraries and modules are already installed.

For working in C on Unix, the first thing to do, is to download the GTK source and install it. You can always get the latest version from ftp.gtk.org. You can also view other sources of GTK information on http://www.gtk.org/. GTK uses GNU autoconf for configuration. Once untar'd, type ./configure --help to see a list of options.

The GTK source distribution also contains the complete source to the C versions of all of the examples used in this tutorial, along with Makefiles to aid compilation.

To begin our introduction to GTK, we'll start with the simplest program possible. This program will create a 200x200 pixel window and has no way of exiting except to be killed by using the shell.

Program main
  Use gtk

  Type(GtkWidget),Pointer :: window

  Call gtk_init()

  window => gtk_window_new(GTK_WINDOW_TOPLEVEL)
  Call gtk_widget_show(window)

  Call gtk_main()

End Program

You can compile and link the abve program in the Fortran Builder, by making a “GTK+ application” for it. This is explained in New GTK+ Application.

All programs will of course use the GTK module which declares the variables, functions, structures, etc. that will be used in your GTK application.

The next line:
Call gtk_init
calls the subroutine gtk_init which will be called in all GTK applications. This sets up a few things for us such as the default visual and color map and then proceeds to call gdk_init. This function initializes the library for use, sets up default signal handlers, and checks the arguments passed to your application on the command line, looking for one of the following:

  • --gtk-module
  • --g-fatal-warnings
  • --gtk-debug
  • --gtk-no-debug
  • --gdk-debug
  • --gdk-no-debug
  • --display
  • --sync
  • --name
  • --class

It removes these from the argument list, leaving anything it does not recognize for your application to parse or ignore. This creates a set of standard arguments accepted by all GTK applications.

The next two lines of code create and display a window.

  window => gtk_window_new (GTK_WINDOW_TOPLEVEL)
  Call gtk_widget_show (window)

The GTK_WINDOW_TOPLEVEL argument specifies that we want the window to undergo window manager decoration and placement. Rather than create a window of 0x0 size, a window without children is set to 200x200 by default so you can still manipulate it.

The gtk_widget_show() subroutine lets GTK know that we are done setting the attributes of this widget, and that it can display it.

The last line enters the GTK main processing loop.

  Call gtk_main ()

A call to gtk_main is another call you will see in every GTK application. When control reaches this point, GTK will sleep waiting for X events (such as button or key presses), timeouts, or file input/output notifications to occur. In our simple example, however, events are ignored.

Hello World in GTK

Now for a program with a widget (a button). It's the classic hello world a la GTK.

Module hello_world
  Use gtk
Contains

  ! This is a callback procedure.  The data argument is ignored
  ! in this example.  More on callbacks below.
  Subroutine hello(widget,data) Bind(C,Name='')
    Type(C_Ptr),Value :: widget,data

    Print *,"Hello World"
  End Subroutine

  Integer(gboolean) Function delete_event(pwidget,pevent,puser_data) &
  Bind(C,Name='')
    Type(C_Ptr),Value :: pwidget,pevent,puser_data

    ! If you return FALSE in the "delete_event" signal handler,
    ! GTK will emit the "destroy" signal.  Returning TRUE means
    ! you don't want the window to be destroyed.
    ! This is useful for popping up 'are you sure you want to quit?'
    ! type dialogs.

    Print *,'delete event occurred'

    ! Change TRUE to FALSE and the main window will be destroyed with
    ! a "delete_event".

    delete_event = TRUE
  End Function

  Subroutine destroy(widget,data) Bind(C,Name='')
    Type(C_Ptr),Value :: widget,data

    Call gtk_main_quit
  End Subroutine

End Module

Program main
  Use hello_world

  ! GtkWidget is the storage type for widgets.
  Type(GtkWidget),Pointer :: window,button

  ! This is called in all GTK applications.  Arguments are parsed
  ! from the command line and are returned to the application.
  Call gtk_init

  ! Create a new window.
  window => gtk_window_new(GTK_WINDOW_TOPLEVEL)

  ! When the window is given the "delete_event" signal (this is given
  ! by the window manager, usually by the "close" option, or on the
  ! titlebar), we ask it to call the delete_event function defined above.
  ! The data passed to the callback function is C_Null_Ptr and happens to be
  ! ignored in the callback function.
  Call g_signal_connect(G_OBJECT(window),"delete_event", &
                        C_FunLoc(delete_event),C_Null_Ptr)

  ! Here we connect the "destroy" event to a signal handler.
  ! This event occurs when we call gtk_widget_destroy() on the window,
  ! or if we return FALSE in the "delete_event" callback.
  Call g_signal_connect(G_OBJECT(window),"destroy", &
                        C_FunLoc(destroy),C_Null_Ptr)

  ! Sets the border width of the window.
  Call gtk_container_set_border_width(GTK_CONTAINER(window),10)

  ! Creates a new button with the label "Hello World".
  button => gtk_button_new_with_label("Hello World")

  ! When the button receives the "clicked" signal, it will call the
  ! procedure hello() passing it C_Null_Ptr as its argument.
  ! The hello() procedure is defined above.
  Call g_signal_connect(G_OBJECT(button),"clicked", &
                        C_FunLoc(hello),C_Null_Ptr)

  ! This will cause the window to be destroyed by calling
  ! gtk_widget_destroy(window) when "clicked".
  ! Again, the destroy signal could come from here, or the window manager.
  Call g_signal_connect_swapped(G_OBJECT(button),"clicked", &
                                C_FunLoc(gtk_widget_destroy),C_Loc(window))

  ! This packs the button into the window (a gtk container).
  Call gtk_container_add(GTK_CONTAINER(window),button)

  ! The penultimate step is to display this newly created widget...
  Call gtk_widget_show(button)

  ! ...and the window.
  Call gtk_widget_show(window)

  ! All GTK applications must have a gtk_main().  Control ends here
  ! and waits for an event to occur (like a key press or mouse event).
  Call gtk_main
End Program

<<< Previous | Home | Next >>>
Introduction |  | Compiling Hello World


Compiling Hello World

To compile and link, please refer to the Fortran Builder Tutorial and Operation Manual, in particular to Creating a GTK+ application, New GTK+ Application and Build.

The libraries that are usually linked in with a GTK+ application are:

  • the GTK library (-lgtk), the widget library, based on top of GDK;
  • the GDK library (-lgdk), the Xlib wrapper;
  • the gdk-pixbuf library (-lgdk_pixbuf), the image manipulation library;
  • the Pango library (-lpango) for internationalized text;
  • the gobject library (-lgobject), containing the type system on which GTK is based;
  • the gmodule library (-lgmodule), which is used to load run time extensions;
  • the GLib library (-lglib), containing miscellaneous functions (GTK is built on top of GLib so you will always require this library, see the section on GLib for details);
  • the math library (-lm).

These libraries are all linked automatically by the Fortran Builder for a GTK+ application, so no user action is necessary.

<<< Previous | Home | Next >>>
Getting Started | Up | Theory of Signals and Callbacks


Theory of Signals and Callbacks

Note

In version 2.0, the signal system has been moved from GTK to GLib, therefore the procedures and types explained in this section have a ‘g_’ prefix rather than a ‘gtk_’ prefix. We won't go into details about the extensions which the GLib 2.0 signal system has relative to the GTK 1.2 signal system.

Before we look in detail at helloworld, we'll discuss signals and callbacks. GTK is an event driven toolkit, which means it will sleep in gtk_main until an event occurs and control is passed to the appropriate procedure.

This passing of control is done using the idea of “signals”. (Note that these signals are not the same as the Unix system signals, and are not implemented using them, although the terminology is almost identical.) When an event occurs, such as the press of a mouse button, the appropriate signal will be “emitted” by the widget that was pressed. This is how GTK does most of its useful work. There are signals that all widgets inherit, such as “destroy”, and there are signals that are widget specific, such as “toggled” on a toggle button.

To make a button perform an action, we set up a signal handler to catch these signals and call the appropriate procedure. This is done by using a procedure such as
Subroutine g_signal_connect(instance,event,callback,data)
  Type(GObject),Pointer :: instance
  Character(*) :: event
  Type(C_Ptr) :: data
  Type(C_FunPtr),Value :: callback
where the first argument is the widget which will be emitting the signal, and the second the name of the signal you wish to catch. The third is the procedure you wish to be called when it is caught, and the fourth, the data you wish to have passed to this procedure.

The procedure specified in the third argument is called a “callback function”, and should generally be of the form
Subroutine callback_func(widget,callback_data) Bind(C,Name='')
  Type(GtkWidget),Pointer :: widget
  Type(C_Ptr),Value :: callback_data
where the first argument will be a pointer to the widget that emitted the signal, and the last a pointer to the data given as the last argument to the g_signal_connect procedure as shown above.

Note that the above form for a signal callback procedure declaration is only a general guide, as some widget specific signals generate different calling parameters.

Another call used in the helloworld example is
Subroutine g_signal_connect_swapped(instance,event,callback,data)
  Type(GObject),Pointer :: instance
  Character(*) :: event
  Type(C_FunPtr),Value :: callback
  Type(C_Ptr) :: data

g_signal_connect_swapped is the same as g_signal_connect except that the instance on which the signal is emitted and data will be swapped when calling the handler. So when using this procedure to connect signals, the callback should be of the form
Subroutine callback_func(object) Bind(C,Name='')
  Type(C_Ptr),Value :: object
where the object is usually a widget. We usually don't setup callbacks for g_signal_connect_swapped however. They are usually used to call a GTK procedure that accepts a single widget or object as an argument, when a signal is emitted on some other object. In the helloworld example, we connect to the “clicked” signal on the button, but call gtk_widget_destroy on the window.

If your callbacks need additional data, use g_signal_connect instead of g_signal_connect_swapped.

The signals that are available depend on the widget type. The most common widget types have their signals listed in the GTK Signals section. Note that each widget type inherits the signals of its parent, so you need to use the widget type hierarchy to work out the full list of signals available.

<<< Previous | Home | Next >>>
Compiling Hello World | Up | Events


Events

In addition to the signal mechanism described above, there is a set of events that reflect the X event mechanism. Callbacks may also be attached to these events. These events are:

  • event
  • button_press_event
  • button_release_event
  • scroll_event
  • motion_notify_event
  • delete_event
  • destroy_event
  • expose_event
  • key_press_event
  • key_release_event
  • enter_notify_event
  • leave_notify_event
  • configure_event
  • focus_in_event
  • focus_out_event
  • map_event
  • unmap_event
  • property_notify_event
  • selection_clear_event
  • selection_request_event
  • selection_notify_event
  • proximity_in_event
  • proximity_out_event
  • visibility_notify_event
  • client_event
  • no_expose_event
  • window_state_event

In order to connect a callback function to one of these events you use the procedure g_signal_connect, as described above, using one of the above event names as the name argument. The callback function for events has a slightly different form than that for signals:

Integer Function callback_func(widget,event,callback_data) Bind(C)
  Type(C_Ptr),Value :: widget,event,user_data

GdkEvent is a C union pointer whose type will depend upon which of the above events has occurred. In order for us to tell which event has been issued each of the possible alternatives has a type member that reflects the event being issued. The other components of the event structure will depend upon the type of the event. Possible values for the type are:
  GDK_NOTHING
  GDK_DELETE
  GDK_DESTROY
  GDK_EXPOSE
  GDK_MOTION_NOTIFY
  GDK_BUTTON_PRESS
  GDK_2BUTTON_PRESS
  GDK_3BUTTON_PRESS
  GDK_BUTTON_RELEASE
  GDK_KEY_PRESS
  GDK_KEY_RELEASE
  GDK_ENTER_NOTIFY
  GDK_LEAVE_NOTIFY
  GDK_FOCUS_CHANGE
  GDK_CONFIGURE
  GDK_MAP
  GDK_UNMAP
  GDK_PROPERTY_NOTIFY
  GDK_SELECTION_CLEAR
  GDK_SELECTION_REQUEST
  GDK_SELECTION_NOTIFY
  GDK_PROXIMITY_IN
  GDK_PROXIMITY_OUT
  GDK_DRAG_ENTER
  GDK_DRAG_LEAVE
  GDK_DRAG_MOTION
  GDK_DRAG_STATUS
  GDK_DROP_START
  GDK_DROP_FINISHED
  GDK_CLIENT_EVENT
  GDK_VISIBILITY_NOTIFY
  GDK_NO_EXPOSE
  GDK_SCROLL
  GDK_WINDOW_STATE
  GDK_SETTING

So, to connect a callback function to one of these events we would use something like
Call g_signal_connect(G_OBJECT(button),"button_press_event", &
                      C_FunLoc(button_press_callback),C_Null_Ptr)

This assumes that button is a Button widget. Now, when the mouse is over the button and a mouse button is pressed, the function button_press_callback will be called. This function may be declared as
Integer Function button_press_callback(widget,pevent,data) Bind(C)
  Type(C_Ptr),Value :: widget,pevent,user_data
  Type(GdkEventButton),Pointer :: event

  Call C_F_Pointer(pevent,event)

Note that we can declare the second argument as type GdkEventButton as we know what type of event will occur for this function to be called.

The value returned from this function indicates whether the event should be propagated further by the GTK event handling mechanism. Returning TRUE indicates that the event has been handled, and that it should not propagate further. Returning FALSE continues the normal event handling. See the section on Advanced Event and Signal Handling for more details on this propagation process.

For details on the GdkEvent data types, see the appendix entitled GDK Event Types .

The GDK selection and drag-and-drop APIs also emit a number of events which are reflected in GTK by the signals. See Signals on the source widget and Signals on the destination widget for details on the signatures of the callback functions for these signals:

  • selection_received
  • selection_get
  • drag_begin_event
  • drag_end_event
  • drag_data_delete
  • drag_motion
  • drag_drop
  • drag_data_get
  • drag_data_received

<<< Previous | Home | Next >>>
Theory of Signals and Callbacks | Up | Stepping Through Hello World


Stepping Through Hello World

Now that we know the theory behind this, let's clarify by walking through the example helloworld program.

Here is the callback function that will be called when the button is “clicked”. We ignore both the widget and the data in this example, but it is not hard to do things with them. The next example will use the data argument to tell us which button was pressed.

Subroutine hello(widget,data) Bind(C,Name='')
  Type(GtkWidget),Pointer :: widget
  Type(C_Ptr),Value :: data

  Print *,"Hello World"

End Subroutine

The next callback is a bit special. The “delete_event” occurs when the window manager sends this event to the application. We have a choice here as to what to do about these events. We can ignore them, make some sort of response, or simply quit the application.

The value you return in this callback lets GTK know what action to take. By returning TRUE, we let it know that we don't want to have the “destroy” signal emitted, keeping our application running. By returning FALSE, we ask that “destroy” be emitted, which in turn will call our “destroy” signal handler.

Integer(gboolean) Function delete_event(widget,event,data) Bind(C,Name='')
  Type(GtkWidget),Pointer :: widget
  Type(C_Ptr) :: event,data

  Print *,"delete event occurred"

  delete_event = TRUE

End Function

Here is another callback function which causes the program to quit by calling gtk_main_quit(). This function tells GTK that it is to exit from gtk_main when control is returned to it.

Subroutine destroy(widget,data) Bind(C,Name='')
  Type(GtkWidget),Pointer :: widget
  Type(C_Ptr) :: data

  Call gtk_main_quit

End Subroutine

I assume you know about the main program... yes, as with other applications, all GTK applications will also have one of these.

Program hello_world

This next part declares pointers to structures of type GtkWidget. These are used below to create a window and a button.

    Type(GtkWidget),Pointer :: window,button

Here is our call to gtk_init again. As before, this initializes the toolkit, and parses the arguments found on the command line. It removes any argument it recognizes from the command line, making it look like they never existed and allowing your application to parse the remaining arguments.

   Call gtk_init

Create a new window. This is fairly straightforward. Memory is allocated for the GtkWidget window structure so window now points to a valid structure. It sets up a new window, but it is not displayed until we call gtk_widget_show(window) near the end of our program.

  window => gtk_window_new(GTK_WINDOW_TOPLEVEL)

Here are two examples of connecting a signal handler to an object, in this case, the window. Here, the “delete_event” and “destroy” signals are caught. The first is emitted when we use the window manager to kill the window, or when we call gtk_widget_destroy call passing in the window widget as the object to destroy. The second is emitted when, in the “delete_event” handler, we return FALSE. The G_OBJECT function packages the widget up for this use.

  Call g_signal_connect(G_OBJECT(window),"delete_event", &
                        C_FunLoc(delete_event),C_Null_Ptr)
  Call g_signal_connect(G_OBJECT(window),"destroy", &
                        C_FunLoc(destroy),C_Null_Ptr)

The next procedure is used to set an attribute of a container object. This just sets the window so it has a blank area along the inside of it 10 pixels wide where no widgets will go. There are other similar procedures which we will look at in the section on Setting Widget Attributes.

And again, GTK_CONTAINER is a function to package up the widget for this call.

  Call gtk_container_set_border_width(GTK_CONTAINER(window),10)

The next function reference creates a new button. It allocates space for a new GtkWidget structure in memory, initializes it, and makes the button pointer point to it. It will have the label ‘Hello World’ on it when displayed.

  button => gtk_button_new_with_label("Hello World")

Here, we take this button, and make it do something useful. We attach a signal handler to it so that when it emits the “clicked” signal, our hello procedure will be called. The data is ignored, so we simply pass in C_Null_Ptr to the hello callback function. Obviously, the “clicked” signal is emitted when we click the button with our mouse pointer.

   Call g_signal_connect(G_OBJECT(button),"clicked", &
                         C_FunLoc(hello),C_Null_Ptr)

We are also going to use this button to exit our program. This will illustrate how the “destroy” signal may come from either the window manager, or our program. When the button is “clicked”, same as above, it calls the first hello callback function, and then this one in the order they are set up. You may have as many callback functions as you need, and all will be executed in the order you connected them. Because the gtk_widget_destroy function accepts only a GtkWidget,Pointer::widget as an argument, we use the g_signal_connect_swapped procedure here instead of straight g_signal_connect.

  Call g_signal_connect_swapped(G_OBJECT(button),"clicked", &
                                C_Funloc(gtk_widget_destroy), &
                                C_Loc(window))

This is a packing call, which will be explained in depth later on in Packing Widgets. But it is fairly easy to understand. It simply tells GTK that the button is to be placed in the window where it will be displayed. Note that a GTK container can only contain one widget. There are other widgets, that are described later, which are designed to layout multiple widgets in various ways.

  Call gtk_container_add(GTK_CONTAINER(window),button)

Now we have everything set up the way we want it to be. With all the signal handlers in place, and the button placed in the window where it should be, we ask GTK to “show” the widgets on the screen. The window widget is shown last so the whole window will pop up at once rather than seeing the window pop up, and then the button form inside of it. Although with such a simple example, you'd never notice.

  Call gtk_widget_show(button)

  Call gtk_widget_show(window)

And of course, we call gtk_main which waits for events to come from the window system and will call on the widgets to emit signals when these events come.

  Call gtk_main

And the end of the program. Control returns here after gtk_main_quit is called.

  End Program

Now, when we click the mouse button on a GTK button, the widget emits a “clicked” signal. In order for us to use this information, our program sets up a signal handler to catch that signal, which dispatches the function of our choice. In our example, when the button we created is “clicked”, the hello procedure is called with a C_Null_Ptr argument, and then the next handler for this signal is called. This calls the gtk_widget_destroy procedure, passing it the window widget as its argument, destroying the window widget. This causes the window to emit the “destroy” signal, which is caught, and calls our destroy callback function, which simply exits GTK.

Another course of events is to use the window manager to kill the window, which will cause the “delete_event” to be emitted. This will call our delete_event procedure. If we return TRUE here, the window will be left as is and nothing will happen. Returning FALSE will cause GTK to emit the “destroy” signal which of course calls the destroy callback, exiting GTK.

<<< Previous | Home | Next >>>
Events | Up | Moving On


Moving On

Data Types

There are a few things you probably noticed in the previous example that need explaining. The gboolean that you saw is a kind type parameter that is part of the GLib system. This is done to get around that nasty dependency on the size of simple data types when doing calculations.

A good example is “gint32” which is a kind type parameter for 32 bit integer regardless of the default integer size. These are described further in the GLib section.

You'll also notice GTK's ability to use GtkWidget when the function calls for a GtkObject. GTK is an object oriented design, and a widget is an object.

<<< Previous | Home | Next >>>
Stepping Through Hello World |  | More on Signal Handlers


More on Signal Handlers

Lets take another look at the g_signal_connect specification.

Subroutine g_signal_connect(instance,event,callback,data,id)
    Type(GObject),Pointer :: instance
    Character(*),Intent(In) :: event
    Type(C_Ptr),Intent(In) :: data
    Type(C_FunPtr),Value :: callback
    Integer(gulong),Optional,Intent(Out) :: id

The value returned in the optional argument id, if present, is a “tag” that identifies the callback function. As stated above, you may have as many callbacks per signal and per object as you need, and each will be executed in turn, in the order they were attached.

This tag allows you to remove this callback from the list by using
Subroutine g_signal_handler_disconnect(instance,handler_id)
    Type(C_Ptr),Intent(In) :: instance
    Integer(gulong),Intent(In) :: handler_id

So, by passing in the widget you wish to remove the handler from, and the tag returned by one of the signal_connect procedures, you can disconnect a signal handler.

You can also temporarily disable signal handlers with the g_signal_handler_block and g_signal_handler_unblock family of procedures.

Subroutine g_signal_handler_block(instance,handler_id)
    Type(C_Ptr),Intent(In) :: instance
    Integer(gulong),Intent(In) :: handler_id

Subroutine g_signal_handlers_block_by_func(object,func,data)
    Type(C_Ptr),Intent(In) :: object
    Type(C_FunPtr),Value :: func
    Type(C_Ptr),Intent(In) :: data

Subroutine g_signal_handler_unblock(instance,handler_id)
    Type(C_Ptr),Intent(In) :: instance
    Integer(gulong),Intent(In) :: handler_id

Subroutine g_signal_handlers_unblock_by_func(object,func,data)
    Type(C_Ptr),Intent(In) :: object
    Type(C_FunPtr),Value :: func
    Type(C_Ptr),Intent(In) :: data

<<< Previous | Home | Next >>>
Moving On | Up | An Upgraded Hello World


An Upgraded Hello World

Let's take a look at a slightly improved helloworld with better examples of callbacks. This will also introduce us to our next topic, packing widgets.

Module hello_world2
    Use gtk

    ! Type for storing strings up to 16 characters in length.
    Type mystr
        Character(16) :: str
    End Type

Contains

    ! Our new improved callback.
    ! The data passed to this function is printed to standard output.
    Integer(gboolean) Function callback(pwidget,pevent,puser_data) &
    Bind(C,Name='')
        Type(C_Ptr),Value :: pwidget
        Type(C_Ptr),Value :: pevent
        Type(C_Ptr),Value :: puser_data
        Type(mystr),Pointer :: pstr

        Call c_f_pointer(pevent,pstr)

        Call g_print('Hello again - '//Trim(pstr%str)//' was pressed'//C_New_Line)

        callback = 0

    End Function

    ! Another callback.
    Integer(gboolean) Function delete_event(widget,event,data) Bind(C,Name='')
        Type(C_Ptr) :: widget,event,data

        Call gtk_main_quit
        delete_event = FALSE

    End Function

End Module

Program main
    Use hello_world2

    ! GtkWidget is the storage type for widgets.
    Type(GtkWidget),Pointer :: window,button,box1
    Type(mystr),Target :: btnstr1 = mystr("button 1")
    Type(mystr),Target :: btnstr2 = mystr("button 2")

    ! This is called in all GTK applications.  Arguments are parsed
    ! from the command line and are returned to the application.
    Call gtk_init

    ! Create a new window.
    window => gtk_window_new(GTK_WINDOW_TOPLEVEL)

    ! This is a new call, which just sets the title of our new window.
    Call gtk_window_set_title(GTK_WINDOW(window),'Hello Buttons!')

    ! Here we just set a handler for delete_event that immediately exits GTK.
    Call g_signal_connect(G_OBJECT(window),'delete_event', &
                          C_FunLoc(delete_event),C_Null_Ptr)

    ! Sets the border width of the window.
    Call gtk_container_set_border_width(GTK_CONTAINER(window),10)

    ! We create a box to pack widgets into.  This is described in detail
    ! in the "packing" section.  The box is not really visible, it
    ! is just used as a tool to arrange widgets.
    box1 => gtk_hbox_new(FALSE,0)

    ! Put the box into the main window.
    Call gtk_container_add(GTK_CONTAINER(window),box1)

    ! Creates a new button with the label "Button 1".
    button => gtk_button_new_with_label('Button 1')

    ! Now when the button is clicked, we call the "callback" function
    ! with a pointer to mystr("button 1") as its argument.
    Call g_signal_connect(G_OBJECT(button),"clicked", &
                          C_FunLoc(callback),C_Loc(btnstr1))

    ! Instead of gtk_container_add, we pack this button into the invisible box,
    ! which has been packed into the window.
    Call gtk_box_pack_start(GTK_BOX(box1),button,TRUE,TRUE,0)

    ! Always remember this step, this tells GTK that our preparation for
    ! this button is complete, and it can now be displayed.
    Call gtk_widget_show(button)

    ! Do these same steps again to create a second button.
    button => gtk_button_new_with_label("Button 2")

    ! Call the same callback function with a different argument,
    ! passing a pointer to mystr("button 2") instead.
    Call g_signal_connect(G_OBJECT (button),'clicked', &
                          C_FunLoc(callback),C_Loc(btnstr2))

    Call gtk_box_pack_start(GTK_BOX(box1),button,TRUE,TRUE,0)

    ! The order in which we show the buttons is not really important, but I
    ! recommend showing the window last, so it all pops up at once.
    Call gtk_widget_show(button)

    Call gtk_widget_show(box1)

    Call gtk_widget_show(window)

    ! Rest in gtk_main and wait for the fun to begin!
    Call gtk_main

End Program

Compile this program in the same way as our first example. You'll notice this time there is no easy way to exit the program, you have to use your window manager or command line to kill it. A good exercise for the reader would be to insert a third “Quit” button that will exit the program. You may also wish to play with the options to gtk_box_pack_start while reading the next section. Try resizing the window, and observe the behavior.

<<< Previous | Home | Next >>>
More on Signal Handlers | Up | Packing Widgets


Packing Widgets

When creating an application, you'll want to put more than one widget inside a window. Our first helloworld example only used one widget so we could simply use a gtk_container_add call to “pack” the widget into the window. But when you want to put more than one widget into a window, how do you control where that widget is positioned? This is where packing comes in.

Theory of Packing Boxes

Most packing is done by creating boxes. These are invisible widget containers that we can pack our widgets into which come in two forms, a horizontal box, and a vertical box. When packing widgets into a horizontal box, the objects are inserted horizontally from left to right or right to left depending on the call used. In a vertical box, widgets are packed from top to bottom or vice versa. You may use any combination of boxes inside or beside other boxes to create the desired effect.

To create a new horizontal box, we use a call to gtk_hbox_new, and for vertical boxes, gtk_vbox_new. The gtk_box_pack_start and gtk_box_pack_end procedures are used to place objects inside of these containers. The gtk_box_pack_start procedure will start at the top and work its way down in a vbox, and pack left to right in an hbox. gtk_box_pack_end will do the opposite, packing from bottom to top in a vbox, and right to left in an hbox. Using these procedures allows us to right justify or left justify our widgets and may be mixed in any way to achieve the desired effect. We will use gtk_box_pack_start in most of our examples. An object may be another container or a widget. In fact, many widgets are actually containers themselves, including the button, but we usually only use a label inside a button.

By using these calls, GTK knows where you want to place your widgets so it can do automatic resizing and other nifty things. There are also a number of options as to how your widgets should be packed. As you can imagine, this method gives us a quite a bit of flexibility when placing and creating widgets.

<<< Previous | Home | Next >>>
An Upgraded Hello World |  | Details of Boxes


Details of Boxes

Because of this flexibility, packing boxes in GTK can be confusing at first. There are a lot of options, and it's not immediately obvious how they all fit together. In the end, however, there are basically five different styles.

Each line contains one horizontal box (hbox) with several buttons. The call to gtk_box_pack is shorthand for the call to pack each of the buttons into the hbox. Each of the buttons is packed into the hbox the same way (i.e., same arguments to the gtk_box_pack_start procedure).

This is the declaration of the gtk_box_pack_start procedure.

Subroutine gtk_box_pack_start(box,child,expand,fill,padding)
    Type(GtkBox),Pointer :: box
    Type(GtkWidget),Pointer :: child
    Integer(gboolean),Intent(In) :: expand,fill
    Integer(guint),Intent(In) :: padding

The first argument is the box you are packing the object into, the second is the object. The objects will all be buttons for now, so we'll be packing buttons into boxes.

The expand argument to gtk_box_pack_start and gtk_box_pack_end controls whether the widgets are laid out in the box to fill in all the extra space in the box so the box is expanded to fill the area allotted to it (TRUE); or the box is shrunk to just fit the widgets (FALSE). Setting expand to FALSE will allow you to do right and left justification of your widgets. Otherwise, they will all expand to fit into the box, and the same effect could be achieved by using only one of gtk_box_pack_start or gtk_box_pack_end.

The fill argument to the gtk_box_pack procedures control whether the extra space is allocated to the objects themselves (TRUE), or as extra padding in the box around these objects (FALSE). It only has an effect if the expand argument is also TRUE.

When creating a new box, the function looks like this:

Function gtk_hbox_new(homogeneous,spacing)
    Integer(gboolean),Intent(In) :: homogeneous
    Integer(gint),Intent(In) :: spacing
    Type(GtkWidget),Pointer :: gtk_hbox_new

The homogeneous argument to gtk_hbox_new (and the same for gtk_vbox_new) controls whether each object in the box has the same size (i.e., the same width in an hbox, or the same height in a vbox). If it is set, the gtk_box_pack routines function essentially as if the expand argument was always turned on.

What's the difference between spacing (set when the box is created) and padding (set when elements are packed)? Spacing is added between objects, and padding is added on either side of an object. The following figure should make it clearer:

Here is the code used to create the above images. I've commented it fairly heavily so I hope you won't have any problems following it. Compile it yourself and play with it.

<<< Previous | Home | Next >>>
Packing Widgets | Up | Packing Demonstration Program


Packing Demonstration Program

Module packing
  Use gtk
Contains

  Integer(gboolean) Function delete_event(widget,event,data) Bind(C,Name='')
    Type(C_Ptr),Value :: widget,event,data

    Call gtk_main_quit
    delete_event = FALSE
  End Function

  ! Make a new hbox filled with button-labels. Arguments for the
  ! variables we're interested are passed in to this function.
  ! We do not show the box, but do show everything inside.
  Function make_box(homogeneous,spacing,expand,fill,padding) Result(box)
    Integer(gboolean),Intent(In) :: homogeneous,expand,fill
    Integer(gint),Intent(In) :: spacing
    Integer(guint),Intent(In) :: padding
    Type(GtkWidget),Pointer :: box

    Type(GtkWidget),Pointer :: button
    Character(len=80) :: padstr

    ! Create a new hbox with the appropriate homogeneous and
    ! spacing settings.
    box => gtk_hbox_new(homogeneous,spacing)

    ! Create a series of buttons with the appropriate settings.
    button => gtk_button_new_with_label("gtk_box_pack")
    Call gtk_box_pack_start(GTK_BOX(box),button,expand,fill,padding)
    Call gtk_widget_show(button)

    button => gtk_button_new_with_label("(box,")
    Call gtk_box_pack_start(GTK_BOX(box),button,expand,fill,padding)
    Call gtk_widget_show(button)

    button => gtk_button_new_with_label("button,")
    Call gtk_box_pack_start(GTK_BOX(box),button,expand,fill,padding)
    Call gtk_widget_show(button)

    ! Create a button with the label depending on the value of expand.
    If (expand==TRUE) Then
      button => gtk_button_new_with_label("TRUE,")
    Else
      button => gtk_button_new_with_label("FALSE,")
    End If

    Call gtk_box_pack_start(GTK_BOX(box),button,expand,fill,padding)
    Call gtk_widget_show(button)

    ! This is the same as the button creation for "expand" above.
    button => gtk_button_new_with_label(Trim(Merge("TRUE, ","FALSE,",fill==TRUE)))
    Call gtk_box_pack_start(GTK_BOX(box),button,expand,fill,padding)
    Call gtk_widget_show(button)

    Write (padstr,*) padding,");",C_Null_Char

    button => gtk_button_new_with_label(padstr)
    Call gtk_box_pack_start(GTK_BOX(box),button,expand,fill,padding)
    Call gtk_widget_show(button)
  End Function

End Module

Program main
  Use packing

  Type(GtkWidget),Pointer :: window,button,box1,box2,separator,label,quitbox
  Integer ios,which
  Character(80) arg

  Select Case (Command_Argument_Count())
  Case (0)
    which = 1
  Case (1)
    Call Get_Command_Argument(1,arg)
    Read (arg,*,Iostat=ios) which
    If (ios/=0) which = -1
  Case Default
    Print *,'usage: packbox [ num ]'
    Stop 'Too many arguments'
  End Select
  If (which<1 .Or. which>3) Then
    Print *,'usage: packbox [ num ]'
    Print *,'If num is present, it must be 1, 2 or 3, not "',Trim(arg),'".'
    Stop
  End If

  ! Our init, don't forget this! :)
  Call gtk_init

  ! Create our window.
  window => gtk_window_new(GTK_WINDOW_TOPLEVEL)

  ! You should always remember to connect the delete_event signal to the
  ! main window.  This is very important for proper intuitive behaviour.
  Call g_signal_connect(G_OBJECT(window),"delete_event", &
                        C_FunLoc(delete_event),C_Null_Ptr)
  Call gtk_container_set_border_width(GTK_CONTAINER(window),10)

  ! We create a vertical box (vbox) to pack the horizontal boxes into.
  ! This allows us to stack the horizontal boxes filled with buttons one
  ! on top of the other in this vbox.
  box1 => gtk_vbox_new(FALSE,0)

  Select Case (which)
  Case(1)
    ! Create a new label.
    label => gtk_label_new("gtk_hbox_new(FALSE,0);")

    ! Align the label to the left side.  We'll discuss this function and
    ! others in the section on Widget Attributes.
    Call gtk_misc_set_alignment(GTK_MISC(label),xalign=0.0,yalign=0.0)

    ! Pack the label into the vertical box (vbox box1).  Remember that
    ! widgets added to a vbox will be packed one on top of the other in
    ! order.
    Call gtk_box_pack_start(GTK_BOX(box1),label,FALSE,FALSE,0)

    ! Show the label.
    Call gtk_widget_show(label)

    ! Call our make box function - homogeneous = FALSE, spacing = 0,
    ! expand = FALSE, fill = FALSE, padding = 0.
    box2 => make_box(FALSE,0,FALSE,FALSE,0)
    Call gtk_box_pack_start(GTK_BOX(box1),box2,FALSE,FALSE,0)
    Call gtk_widget_show(box2)

    ! Call our make box function - homogeneous = FALSE, spacing = 0,
    ! expand = TRUE, fill = FALSE, padding = 0.
    box2 => make_box(FALSE,0,TRUE,FALSE,0)
    Call gtk_box_pack_start(GTK_BOX(box1),box2,FALSE,FALSE,0)
    Call gtk_widget_show(box2)

    ! Args are: homogeneous, spacing, expand, fill, padding.
    box2 => make_box(FALSE,0,TRUE,TRUE,0)
    Call gtk_box_pack_start(GTK_BOX(box1),box2,FALSE,FALSE,0)
    Call gtk_widget_show(box2)

    ! Creates a separator, we'll learn more about these later,
    ! but they are quite simple.
    separator => gtk_hseparator_new()

    ! Pack the separator into the vbox. Remember each of these widgets
    ! is being packed into a vbox, so they'll be stacked vertically.
    Call gtk_box_pack_start(GTK_BOX(box1),separator,FALSE,TRUE,5)
    Call gtk_widget_show(separator)

    ! Create another new label, and show it.
    label => gtk_label_new("gtk_hbox_new(TRUE,0);")
    Call gtk_misc_set_alignment(GTK_MISC(label),xalign=0.0,yalign=0.0)
    Call gtk_box_pack_start(GTK_BOX(box1),label,FALSE,FALSE,0)
    Call gtk_widget_show(label)

    box2 => make_box(homogeneous=TRUE,spacing=0,expand=TRUE,fill=FALSE,padding=0)
    Call gtk_box_pack_start(GTK_BOX(box1),box2,FALSE,FALSE,0)
    Call gtk_widget_show(box2)

    box2 => make_box(homogeneous=TRUE,spacing=0,expand=TRUE,fill=TRUE,padding=0)
    Call gtk_box_pack_start(GTK_BOX(box1),box2,FALSE,FALSE,0)
    Call gtk_widget_show(box2)

    ! Another new separator.
    separator => gtk_hseparator_new()
    ! The last 3 arguments to gtk_box_pack_start are: expand, fill, padding.
    Call gtk_box_pack_start(GTK_BOX(box1),separator,FALSE,TRUE,5)
    Call gtk_widget_show(separator)

  Case (2)
    ! Create a new label, remember box1 is a vbox as created
    ! near the beginning of the main program.
    label => gtk_label_new("gtk_hbox_new (FALSE, 10);")
    Call gtk_misc_set_alignment(GTK_MISC(label),xalign=0.0,yalign=0.0)
    Call gtk_box_pack_start(GTK_BOX(box1),label,FALSE,FALSE,0)
    Call gtk_widget_show(label)

    ! Args are: homogeneous, spacing, expand, fill, padding.
    box2 => make_box(FALSE,10,TRUE,FALSE,0)
    Call gtk_box_pack_start(GTK_BOX(box1),box2,FALSE,FALSE,0)
    Call gtk_widget_show(box2)

    ! Args are: homogeneous, spacing, expand, fill, padding.
    box2 => make_box(FALSE,10,TRUE,TRUE,0)
    Call gtk_box_pack_start(GTK_BOX(box1),box2,FALSE,FALSE,0)
    Call gtk_widget_show(box2)

    separator => gtk_hseparator_new()
    Call gtk_box_pack_start(GTK_BOX(box1),separator,expand=FALSE,fill=TRUE,padding=5)
    Call gtk_widget_show(separator)

    label => gtk_label_new("gtk_hbox_new (FALSE, 0);")
    Call gtk_misc_set_alignment(GTK_MISC(label),xalign=0.0,yalign=0.0)
    Call gtk_box_pack_start(GTK_BOX(box1),label,FALSE,FALSE,0)
    Call gtk_widget_show(label)

    box2 => make_box(homogeneous=FALSE,spacing=0,expand=TRUE,fill=FALSE,padding=10)
    Call gtk_box_pack_start(GTK_BOX(box1),box2,FALSE,FALSE,0)
    Call gtk_widget_show(box2)

    box2 => make_box(homogeneous=FALSE,spacing=0,expand=TRUE,fill=TRUE,padding=10)
    Call gtk_box_pack_start(GTK_BOX(box1),box2,FALSE,FALSE,0)
    Call gtk_widget_show(box2)

    separator => gtk_hseparator_new()
    Call gtk_box_pack_start(GTK_BOX(box1),separator,expand=FALSE,fill=TRUE,padding=5)
    Call gtk_widget_show(separator)

  Case (3)
    ! This demonstrates the ability to use gtk_box_pack_end to
    ! right justify widgets. First, we create a new box as before.
    box2 => make_box(FALSE,0,FALSE,FALSE,0)

    ! Create the label that will be put at the end.
    label => gtk_label_new("end")
    ! Pack it using gtk_box_pack_end, so it is put on the right side
    ! of the hbox created in the make_box call.
    Call gtk_box_pack_end(GTK_BOX(box2),label,FALSE,FALSE,0)
    ! Show the label.
    Call gtk_widget_show(label)

    ! Pack box2 into box1 (the vbox remember ? :)
    Call gtk_box_pack_start(GTK_BOX(box1),box2,FALSE,FALSE,0)
    Call gtk_widget_show(box2)

    ! A separator for the bottom.
    separator => gtk_hseparator_new()
    ! This explicitly sets the separator to 400 pixels wide by 5 pixels high.
    ! This is so the hbox we created will also be 400 pixels wide,and the
    ! "end" label will be separated from the other labels in the hbox.
    ! Otherwise, all the widgets in the hbox would be packed as closely
    ! together as possible.
    Call gtk_widget_set_size_request(separator,400,5)
    ! Pack the separator into the vbox (box1) created near the start
    ! of the main program.
    Call gtk_box_pack_start(GTK_BOX(box1),separator,FALSE,TRUE,5)
    Call gtk_widget_show(separator)

  End Select

  ! Create another new hbox... remember we can use as many as we need!
  quitbox => gtk_hbox_new(FALSE,0)

  ! Our quit button.
  button => gtk_button_new_with_label("Quit")

  ! Setup the signal to terminate the program when the button is clicked.
  Call g_signal_connect_swapped(G_OBJECT(button),"clicked", &
                                C_FunLoc(gtk_main_quit),C_Loc(window))

  ! Pack the button into the quitbox.
  ! The last 3 arguments to gtk_box_pack_start are: expand, fill, padding.
  Call gtk_box_pack_start(GTK_BOX(quitbox),button,TRUE,FALSE,0)

  ! Pack the quitbox into the vbox (box1).
  Call gtk_box_pack_start(GTK_BOX(box1),quitbox,FALSE,FALSE,0)

  ! Pack the vbox (box1) which now contains all our widgets,
  ! into the main window.
  Call gtk_container_add(GTK_CONTAINER(window),box1)

  ! And show everything left.
  Call gtk_widget_show(button)
  Call gtk_widget_show(quitbox)

  Call gtk_widget_show(box1)
  ! Showing the window last so everything pops up at once.
  Call gtk_widget_show(window)

  ! And of course, our main procedure.
  Call gtk_main

End Program

<<< Previous | Home | Next >>>
Details of Boxes | Up | Packing Using Tables


Packing Using Tables

Let's take a look at another way of packing – Tables. These can be extremely useful in certain situations.

Using tables, we create a grid that we can place widgets in. The widgets may take up as many spaces as we specify.

The first thing to look at, of course, is the gtk_table_new function:

Function gtk_table_new(rows,columns,homogeneous)
    Integer(guint),Intent(In) :: rows,columns
    Integer(gboolean),Intent(In) :: homogeneous
    Type(GtkWidget),Pointer :: gtk_table_new

The first argument is the number of rows to make in the table, while the second, obviously, is the number of columns.

The homogeneous argument has to do with how the table's boxes are sized. If homogeneous is TRUE, the table boxes are resized to the size of the largest widget in the table. If homogeneous is FALSE, the size of a table box is dictated by the tallest widget in its same row, and the widest widget in its column.

The rows and columns are laid out with borders numbered from 0 to rows and 0 to columns respectively. So, if you specify rows=2 and columns=2, the layout would look something like this:

 0          1          2
0+----------+----------+
 |          |          |
1+----------+----------+
 |          |          |
2+----------+----------+

Note that the coordinate system starts in the upper left hand corner. To place a widget into a box, use the following procedure:

Subroutine gtk_table_attach(table,child,left_attach,right_attach,top_attach, &
                            bottom_attach,xoptions,yoptions,xpadding,ypadding)
    Type(GtkTable),Pointer :: table
    Type(GtkWidget),Pointer :: child
    Integer(guint),Intent(In) :: left_attach,right_attach,top_attach,bottom_attach
    Integer(GtkAttachOptions),Intent(In) :: xoptions,yoptions
    Integer(guint),Intent(In) :: xpadding,ypadding

The first argument (table) is the table you've created and the second (child) the widget you wish to place in the table.

The left and right attach arguments specify where to place the widget, and how many boxes to use. If you want a button in the lower right table entry of our 2x2 table, and want it to fill that entry only, the settings would be left_attach=1, right_attach=2, top_attach=1, bottom_attach=2.

Now, if you wanted a widget to take up the whole top row of our 2x2 table, you'd use left_attach=0, right_attach=2, top_attach=0, bottom_attach=1.

The xoptions and yoptions arguments are used to specify packing options and may be bitwise OR'ed together to allow multiple options.

These options are:

GTK_FILL

If the table box is larger than the widget, and GTK_FILL is specified, the widget will expand to use all the room available.

GTK_SHRINK

If the table widget was allocated less space then was requested (usually by the user resizing the window), then the widgets would normally just be pushed off the bottom of the window and disappear. If GTK_SHRINK is specified, the widgets will shrink with the table.

GTK_EXPAND

This will cause the table to expand to use up any remaining space in the window.

Padding is just like in boxes, creating a clear area around the widget specified in pixels.

gtk_table_attach has a lot of options. So, there's a shortcut:

Subroutine gtk_table_attach_defaults(table,widget,left_attach,right_attach, &
                                     top_attach,bottom_attach)
    Type(GtkTable),Pointer :: table
    Type(GtkWidget),Pointer :: widget
    Integer(guint),Intent(In) :: left_attach,right_attach,top_attach,bottom_attach

The X and Y options default to Ior(GTK_FILL,GTK_EXPAND), and X and Y padding are set to 0. The rest of the arguments are identical to the previous function.

We also have gtk_table_set_row_spacing and gtk_table_set_col_spacing. These place spacing between the rows (or columns) at the specified row or column.

Subroutine gtk_table_set_row_spacing(table,row,spacing)
    Type(GtkTable),Pointer :: table
    Integer(guint),Intent(In) :: row,spacing

and

Subroutine gtk_table_set_col_spacing(table,column,spacing)
    Type(GtkTable),Pointer :: table
    Integer(guint),Intent(In) :: column,spacing

Note that for columns, the space goes to the right of the column, and for rows, the space goes below the row.

You can also set a consistent spacing of all rows and/or columns with:

Subroutine gtk_table_set_row_spacings(table,spacing)
    Type(GtkTable),Pointer :: table
    Integer(guint),Intent(In) :: spacing

And,

Subroutine gtk_table_set_col_spacings(table,spacing)
    Type(GtkTable),Pointer :: table
    Integer(guint),Intent(In) :: spacing

Note that with these calls, the last row and last column do not get any spacing.

<<< Previous | Home | Next >>>
Packing Demonstration Program | Up | Table Packing Example


Table Packing Example

Here we make a window with three buttons in a 2x2 table. The first two buttons will be placed in the upper row. A third, quit button, is placed in the lower row, spanning both columns. Which means it should look something like this:

Here's the source code:

Module TablePack
  Use gtk

  Type mystr
    Character(16) :: str
  End Type

Contains

  ! Our callback.
  ! The data passed to this procedure are printed on standard output.
  Subroutine callback(pwidget,data) Bind(C,Name='')
    Type(GtkWidget) :: widget
    Type(C_Ptr),Value :: data
    Type(mystr),Pointer :: strptr
    Call C_F_Pointer(data,strptr)

    Print *,'Hello again - ',Trim(strptr%str), ' was pressed'

  End Subroutine

  ! This callback quits the program.
  Integer(gboolean) Function delete_event(widget,event,data) Bind(C,Name='')
    Type(GtkWidget) :: widget
    Type(GdkEvent) :: event
    Type(C_Ptr),Value :: data

    Call gtk_main_quit
    delete_event = FALSE
  End Function

End Module

Program TablePack_Main
    Use TablePack

    Type(GtkWidget),Pointer :: window,button,table
    Type(mystr),Target :: btn1str = mystr('button 1')
    Type(mystr),Target :: btn2str = mystr('button 2')

    Call gtk_init()

    ! Create a new window
    window => gtk_window_new(GTK_WINDOW_TOPLEVEL)

    ! Set the window title.
    Call gtk_window_set_title(GTK_WINDOW(window),'Table')

    ! Set a handler for delete_event that immediately exits GTK.
    Call g_signal_connect(G_OBJECT(window),'delete_event', &
                          C_FunLoc(delete_event),C_Null_Ptr)

    ! Sets the border width of the window.
    Call gtk_container_set_border_width(GTK_CONTAINER(window),20)

    ! Create a 2x2 table.
    table => gtk_table_new(2,2,TRUE)

    ! Put the table in the main window.
    Call gtk_container_add(GTK_CONTAINER(window),table)

    ! Create first button.
     button => gtk_button_new_with_label('button 1')

    ! When the button is clicked, we call the "callback" procedure
    ! with a pointer to 'button 1' as its argument.
    Call g_signal_connect(G_OBJECT(button),'clicked', &
                          C_FunLoc(callback),C_Loc(btn1str))

    ! Insert button 1 into the upper left quadrant of the table.
    Call gtk_table_attach_defaults(GTK_TABLE(table),button,0,1,0,1)

    Call gtk_widget_show(button)

    ! Create second button.
    button => gtk_button_new_with_label('button 2')

    ! When the button is clicked, we call the "callback": procedure
    ! with a pointer to 'button 2' as its argument.
    Call g_signal_connect(G_OBJECT(button),'clicked',C_FunLoc(callback), &
                          C_Loc(btn2str))

    ! Insert button 2 into the upper right quadrant of the table.
    Call gtk_table_attach_defaults(GTK_TABLE(table),button,1,2,0,1)

    Call gtk_widget_show(button)

    ! Create "Quit" button.
    button => gtk_button_new_with_label('Quit')

    ! When the button is clicked, we call the "delete_event" procedure
    ! and the program is terminated.
    Call g_signal_connect(G_OBJECT(button),'clicked',C_FunLoc(delete_event), &
                          C_Loc(btn2str))

    ! Insert the "Quit" button into both the lower quadrants
    ! of the table.
    Call gtk_table_attach_defaults(GTK_TABLE (table),button,0,2,1,2)

    Call gtk_widget_show(button)
    Call gtk_widget_show(table)
    Call gtk_widget_show(window)

    Call gtk_main

End Program

<<< Previous | Home | Next >>>
Packing Using Tables | Up | Widget Overview


Widget Overview

The general steps to creating a widget in GTK are:

  1. gtk_*_new() - one of various functions to create a new widget. These are all detailed in this section.

  2. Connect all signals and events we wish to use to the appropriate handlers.

  3. Set the attributes of the widget.

  4. Pack the widget into a container using the appropriate call such as to gtk_container_add or gtk_box_pack_start.

  5. gtk_widget_show the widget.

gtk_widget_show lets GTK know that we are done setting the attributes of the widget, and it is ready to be displayed. You may also use gtk_widget_hide to make it disappear again. The order in which you show the widgets is not important, but I suggest showing the window last so the whole window pops up at once rather than seeing the individual widgets come up on the screen as they're formed. The children of a widget (a window is a widget too) will not be displayed until the window itself is shown using the gtk_widget_show function.

Casting

You'll notice as you go on that GTK uses a type casting system. This is always done using functions that both test the ability to cast the given item, and perform the cast. Some common ones you will see are:

  G_OBJECT (object)
  GTK_WIDGET (widget)
  GTK_OBJECT (object)
  GTK_SIGNAL_FUNC (function)
  GTK_CONTAINER (container)
  GTK_WINDOW (window)
  GTK_BOX (box)

These are all used to cast arguments in function references. You'll see them in the examples, and can usually tell when to use them simply by looking at the function's declaration.

As you can see below in the class hierarchy, all GtkWidgets are derived from the GObject base class. This means you can use a widget in any place the function asks for an object – simply use the G_OBJECT() function.

For example:

Call g_signal_connect(G_OBJECT (button),'clicked', &
                      C_FunLoc(callback_function),callback_data);

This casts the button into an object, and provides a conversion for the function pointer to the callback.

Many widgets are also containers. If you look in the class hierarchy below, you'll notice that many widgets derive from the Container class. Any one of these widgets may be used with the GTK_CONTAINER function to pass them to functions that ask for containers.

Unfortunately, these functions are not extensively covered in the tutorial, but I recommend taking a look through the GTK header files or the GTK API reference manual. It can be very educational. In fact, it's not difficult to learn how a widget works just by looking at the function declarations.

<<< Previous | Home | Next >>>
Table Packing Example |  | Widget Hierarchy


Widget Hierarchy

For your reference, here is the class hierarchy tree used to implement widgets. (Deprecated widgets and auxiliary classes have been omitted.)

GObject
 |
 GtkObject
  +GtkWidget
  | +GtkMisc
  | | +GtkLabel
  | | | `GtkAccelLabel
  | | +GtkArrow
  | | `GtkImage
  | +GtkContainer
  | | +GtkBin
  | | | +GtkAlignment
  | | | +GtkFrame
  | | | | `GtkAspectFrame
  | | | +GtkButton
  | | | | +GtkToggleButton
  | | | | | `GtkCheckButton
  | | | | |   `GtkRadioButton
  | | | | `GtkOptionMenu
  | | | +GtkItem
  | | | | +GtkMenuItem
  | | | |   +GtkCheckMenuItem
  | | | |   | `GtkRadioMenuItem
  | | | |   +GtkImageMenuItem
  | | | |   +GtkSeparatorMenuItem
  | | | |   `GtkTearoffMenuItem
  | | | +GtkWindow
  | | | | +GtkDialog
  | | | | | +GtkColorSelectionDialog
  | | | | | +GtkFileSelection
  | | | | | +GtkFontSelectionDialog
  | | | | | +GtkInputDialog
  | | | | | `GtkMessageDialog
  | | | | `GtkPlug
  | | | +GtkEventBox
  | | | +GtkHandleBox
  | | | +GtkScrolledWindow
  | | | `GtkViewport
  | | +GtkBox
  | | | +GtkButtonBox
  | | | | +GtkHButtonBox
  | | | | `GtkVButtonBox
  | | | +GtkVBox
  | | | | +GtkColorSelection
  | | | | +GtkFontSelection
  | | | | `GtkGammaCurve
  | | | `GtkHBox
  | | |   +GtkCombo
  | | |   `GtkStatusbar
  | | +GtkFixed
  | | +GtkPaned
  | | | +GtkHPaned
  | | | `GtkVPaned
  | | +GtkLayout
  | | +GtkMenuShell
  | | | +GtkMenuBar
  | | | `GtkMenu
  | | +GtkNotebook
  | | +GtkSocket
  | | +GtkTable
  | | +GtkTextView
  | | +GtkToolbar
  | | `GtkTreeView
  | +GtkCalendar
  | +GtkDrawingArea
  | | `GtkCurve
  | +GtkEditable
  | | +GtkEntry
  | |   `GtkSpinButton
  | +GtkRuler
  | | +GtkHRuler
  | | `GtkVRuler
  | +GtkRange
  | | +GtkScale
  | | | +GtkHScale
  | | | `GtkVScale
  | | `GtkScrollbar
  | |   +GtkHScrollbar
  | |   `GtkVScrollbar
  | +GtkSeparator
  | | +GtkHSeparator
  | | `GtkVSeparator
  | +GtkInvisible
  | +GtkPreview
  | `GtkProgressBar
  +GtkAdjustment
  +GtkCellRenderer
  | +GtkCellRendererPixbuf
  | +GtkCellRendererText
  | +GtkCellRendererToggle
  +GtkItemFactory
  +GtkTooltips
  `GtkTreeViewColumn

<<< Previous | Home | Next >>>
Widget Overview | Up | Widgets Without Windows


Widgets Without Windows

The following widgets do not have an associated window. If you want to capture events, you'll have to use the EventBox. See the section on the EventBox widget.

GtkAlignment
GtkArrow
GtkBin
GtkBox
GtkButton
GtkCheckButton
GtkFixed
GtkImage
GtkLabel
GtkMenuItem
GtkNotebook
GtkPaned
GtkRadioButton
GtkRange
GtkScrolledWindow
GtkSeparator
GtkTable
GtkToolbar
GtkAspectFrame
GtkFrame
GtkVBox
GtkHBox
GtkVSeparator
GtkHSeparator

We'll further our exploration of GTK by examining each widget in turn, creating a few simple functions to display them. Another good source is the testgtk program that comes with GTK. It can be found in tests/testgtk.c .

<<< Previous | Home | Next >>>
Widget Hierarchy | Up | The Button Widget


The Button Widget

Normal Buttons

We've almost seen all there is to see of the button widget. It's pretty simple. There is however more than one way to create a button. You can use gtk_button_new_with_label or gtk_button_new_with_mnemonic to create a button with a label, use gtk_button_new_from_stock to create a button containing the image and text from a stock item or use gtk_button_new to create a blank button. It's then up to you to pack a label or pixmap into this new button. To do this, create a new box, and then pack your objects into this box using the usual gtk_box_pack_start, and then use gtk_container_add to pack the box into the button.

Here's an example of using gtk_button_new to create a button with a image and a label in it. I've broken up the code to create a box from the rest so you can use it in your programs. There are further examples of using images later in the tutorial.

Module cool_btn
  Use gtk

  Type mystr
    Character(12) :: str
  End Type

Contains

  ! Create a new hbox with an image and a label packed into it
  ! and return the box.
  Function xpm_label_box(xpm_filename,label_text) Result(box)
    Character(*),Intent(In) :: xpm_filename
    Character(*),Intent(In) :: label_text
    Type(GtkWidget),Pointer :: box

    Type(GtkWidget),Pointer :: label,image

    ! Create hbox for image and label.
    box => gtk_hbox_new (FALSE, 0)
    Call gtk_container_set_border_width(GTK_CONTAINER(box),2)

    ! Now on to the image stuff.
    image => gtk_image_new_from_file(xpm_filename)

    ! Create a label for the button.
    label => gtk_label_new(label_text)

    ! Pack the image and label into the box.
    Call gtk_box_pack_start(GTK_BOX(box),image,FALSE,FALSE,3)
    Call gtk_box_pack_start(GTK_BOX(box),label,FALSE,FALSE,3)

    Call gtk_widget_show(image)
    Call gtk_widget_show(label)
  End Function

  ! Our usual callback procedure.
  Subroutine callback(widget,data) Bind(C,Name='')
    Type(GtkWidget) :: widget
    Type(C_Ptr),Value :: data
    Type(mystr),Pointer :: pstr

    Call C_F_Pointer(data,pstr)

    Print *,'Hello again - ',Trim(pstr%str),' was pressed'
  End Subroutine

End Module

Program main491
  Use cool_btn

  ! GtkWidget is the storage type for widgets.
  Type(GtkWidget),Pointer :: window,button,box
  Type(mystr),Target :: str = mystr('cool button')

  Call gtk_init

  ! Create a new window.
  window => gtk_window_new(GTK_WINDOW_TOPLEVEL)
  Call gtk_window_set_title(GTK_WINDOW(window),"Pixmap'd Buttons!")

  ! It's a good idea to do this for all windows.
  Call g_signal_connect(G_OBJECT(window),"destroy", &
                        C_FunLoc(gtk_main_quit),C_Null_Ptr)
  Call g_signal_connect(G_OBJECT(window),"delete_event", &
                        C_FunLoc(gtk_main_quit),C_Null_Ptr)

  ! Sets the border width of the window.
  Call gtk_container_set_border_width(GTK_CONTAINER(window),10)

  ! Create a new button.
  button => gtk_button_new()

  ! Connected the "clicked" signal of the button to our callback.
  Call g_signal_connect(G_OBJECT(button),"clicked", &
                        C_FunLoc(callback),C_Loc(str))

  ! This calls our box creating function.
  box => xpm_label_box('NormalButtons.bmp','cool button')

  ! Pack and show all our widgets.
  Call gtk_widget_show(box)

  Call gtk_container_add(GTK_CONTAINER(button),box)

  Call gtk_widget_show(button)

  Call gtk_container_add(GTK_CONTAINER(window),button)

  Call gtk_widget_show(window)

  ! Rest in gtk_main and wait for the fun to begin!
  Call gtk_main

End Program

The xpm_label_box function could be used to pack images and labels into any widget that can be a container.

The Button widget has the following signals:

  • pressed — emitted when pointer button is pressed within Button widget;
  • released — emitted when pointer button is released within Button widget;
  • clicked — emitted when pointer button is pressed and then released within Button widget;
  • enter — emitted when pointer enters Button widget;
  • leave — emitted when pointer leaves Button widget.

<<< Previous | Home | Next >>>
Widgets Without Windows |  | Toggle Buttons


Toggle Buttons

Toggle buttons are derived from normal buttons and are very similar, except they will always be in one of two states, alternated by a click. They may be depressed, and when you click again, they will pop back up. Click again, and they will pop back down.

Toggle buttons are the basis for check buttons and radio buttons, as such, many of the calls used for toggle buttons are inherited by radio and check buttons. I will point these out when we come to them.

Creating a new toggle button:

Function gtk_toggle_button_new()
    Type(GtkWidget),Pointer :: gtk_toggle_button_new

Function gtk_toggle_button_new_with_label(label)
    Character(*),Intent(In) :: label
    Type(GtkWidget),Pointer :: gtk_toggle_button_new_with_label

Function gtk_toggle_button_new_with_mnemonic(label)
    Character(*),Intent(In) :: label
    Type(GtkWidget),Pointer :: gtk_toggle_button_new_with_mnemonic

As you can imagine, these work identically to the normal button widget calls. The first creates a blank toggle button, and the last two, a button with a label widget already packed into it. The _mnemonic variant additionally parses the label for underscore-prefixed mnemonic characters.

To retrieve the state of the toggle widget, including radio and check buttons, we use a construct as shown in our example below. This tests the state of the toggle button, by accessing the active field of the toggle widget's structure, after first using the GTK_TOGGLE_BUTTON function to cast the widget pointer into a toggle widget pointer. The signal of interest to us emitted by toggle buttons (the toggle button, check button, and radio button widgets) is the “toggled” signal. To check the state of these buttons, set up a signal handler to catch the toggled signal, and access the structure to determine its state. The callback will look something like:

Subroutine toggle_button_callback(widget,data) Bind(C,Name='')
  Type(GtkWidget) widget
  Type(C_Ptr),Value :: data

  If (gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(widget))==FALSE) Then
    ! If control reaches here, the toggle button is up.
  Else
    ! If control reaches here, the toggle button is down.
  End If
End Subroutine

To force the state of a toggle button, and its children, the radio and check buttons, use this procedure:

Subroutine gtk_toggle_button_set_active(toggle_button,is_active)
  Type(GtkToggleButton),Pointer :: toggle_button
  Integer(gboolean),Intent(In) :: is_active

The above call can be used to set the state of the toggle button, and its children the radio and check buttons. Pass in your created button as the first argument, and a TRUE or FALSE for the second state argument to specify whether it should be down (depressed) or up (released). The default is up, or FALSE.

Note that when you use the gtk_toggle_button_set_active procedure, and the state is actually changed, it causes the “clicked” and “toggled” signals to be emitted from the button.

Integer(gboolean) Function gtk_toggle_button_get_active(toggle_button)
    Type(GtkToggleButton),Pointer :: toggle_button

This returns the current state of the toggle button as an Integer(gboolean) TRUE/FALSE value.

<<< Previous | Home | Next >>>
The Button Widget | Up | Check Buttons


Check Buttons

Check buttons inherit many properties and functions from the the toggle buttons above, but look a little different. Rather than being buttons with text inside them, they are small squares with the text to the right of them. These are often used for toggling options on and off in applications.

The creation functions are similar to those of the normal button.

Function gtk_check_button_new() Result(res)
    Type(GtkWidget),Pointer :: res

Function gtk_check_button_new_with_label(label) Result(res)
    Character(*),Intent(In) :: label
    Type(GtkWidget),Pointer :: res

Function gtk_check_button_new_with_mnemonic(label) Result(res)
    Character(*),Intent(In) :: label
    Type(GtkWidget),Pointer :: res

The gtk_check_button_new_with_label function creates a check button with a label beside it.

Checking the state of the check button is identical to that of the toggle button.

<<< Previous | Home | Next >>>
Toggle Buttons | Up | Radio Buttons


Radio Buttons

Radio buttons are similar to check buttons except they are grouped so that only one may be selected/depressed at a time. This is good for places in your application where you need to select from a short list of options.

Creating a new radio button is done with one of these calls:

Function gtk_radio_button_new (group)
    Type(GSList),Pointer :: group
    Type(GtkWidget),Pointer :: gtk_radio_button_new

Function gtk_radio_button_new_from_widget(radio_group_member)
    Type(GtkRadioButton),Pointer :: radio_group_member
    Type(GtkWidget),Pointer :: gtk_radio_button_new_from_widget

Function gtk_radio_button_new_with_label(group,label)
    Type(GSList),Pointer :: group
    Character(*),Intent(In) :: label
    Type(GtkWidget),Pointer :: gtk_radio_button_new_with_label

Function gtk_radio_button_new_with_label_from_widget(radio_group_member,label) &
Result(res)
    Type(GtkRadioButton),Pointer :: radio_group_member
    Character(*),Intent(In) :: label
    Type(GtkWidget),Pointer :: res

Function gtk_radio_button_new_with_mnemonic(group,label) Result(res)
    Type(GSList),Pointer :: group
    Character(*),Intent(In) :: label
    Type(GtkWidget),Pointer :: res

Function gtk_radio_button_new_with_mnemonic_from_widget(radio_group_member,label) &
Result(res)
    Type(GtkRadioButton),Pointer :: radio_group_member
    Character(*),Intent(In) :: label
    Type(GtkWidget),Pointer :: res

You'll notice the extra argument to these calls. They require a group to perform their duty properly. The first call to gtk_radio_button_new or gtk_radio_button_new_with_label should pass Null() as the first argument. Then create a group using:

Function gtk_radio_button_get_group(radio_button)
    Type(GtkRadioButton),Pointer :: radio_button
    Type(GSList),Pointer :: gtk_radio_button_get_group

The important thing to remember is that gtk_radio_button_get_group must be called for each new button added to the group, with the previous button passed in as an argument. The result is then passed into the next call to gtk_radio_button_new or gtk_radio_button_new_with_label. This allows a chain of buttons to be established. The example below should make this clear.

You can shorten this slightly by using the following syntax, which removes the need for a variable to hold the list of buttons:

    button2 => gtk_radio_button_new_with_label( &
                 gtk_radio_button_get_group(GTK_RADIO_BUTTON(button1)), &
                                            "button2")

The _from_widget variants of the creation functions allow you to shorten this further, by omitting the gtk_radio_button_get_group call. This form is used in the example to create the third button:

    button2 => gtk_radio_button_new_with_label_from_widget( &
                 GTK_RADIO_BUTTON(button1), &
                 "button2")

It is also a good idea to explicitly set which button should be the default depressed button with:

Subroutine gtk_toggle_button_set_active(toggle_button,is_active)
    Type(GtkToggleButton),Pointer :: toggle_button
    Integer(gboolean),Intent(In) :: is_active

This is described in the section on toggle buttons, and works in exactly the same way. Once the radio buttons are grouped together, only one of the group may be active at a time. If the user clicks on one radio button, and then on another, the first radio button will first emit a “toggled” signal (to report becoming inactive), and then the second will emit its “toggled” signal (to report becoming active).

The following example creates a radio button group with three buttons.

Module radio_btn
  Use gtk
Contains

  Integer(gboolean) Function close_application(widget,event,data) &
  Bind(C,Name='')
    Type(GtkWidget) widget
    Type(GdkEvent) event
    Type(C_Ptr),Value :: data
    Call gtk_main_quit
    close_application = FALSE
  End Function

End Module

Program main
  Use radio_btn

  Type(GtkWidget),Pointer::window,box1,box2,button,separator
  Type(GSList),Pointer :: group

  Call gtk_init

  window => gtk_window_new(GTK_WINDOW_TOPLEVEL)
  Call g_signal_connect(G_OBJECT(window), "delete_event", &
                        C_FunLoc(gtk_main_quit),C_Null_Ptr)
  Call gtk_window_set_title(GTK_WINDOW(window),"radio buttons")
  Call gtk_container_set_border_width(GTK_CONTAINER (window),0)

  box1 => gtk_vbox_new(FALSE,0)
  Call gtk_container_add(GTK_CONTAINER (window),box1)
  Call gtk_widget_show(box1)

  box2 => gtk_vbox_new(FALSE,10)
  Call gtk_container_set_border_width(GTK_CONTAINER (box2),10)

  Call gtk_box_pack_start(GTK_BOX(box1),box2,TRUE,TRUE,0)
  Call gtk_widget_show(box2)

  button => gtk_radio_button_new_with_label(Null(),"button1")
  Call gtk_box_pack_start(GTK_BOX(box2),button,TRUE,TRUE,0)
  Call gtk_widget_show(button)

  group  => gtk_radio_button_get_group(GTK_RADIO_BUTTON(button))
  button => gtk_radio_button_new_with_label(group,"button2")
  Call gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(button),TRUE)
  Call gtk_box_pack_start(GTK_BOX(box2),button,TRUE,TRUE,0)
  Call gtk_widget_show(button)

  button => &
    gtk_radio_button_new_with_label_from_widget(GTK_RADIO_BUTTON(button), &
                                                "button3")
  Call gtk_box_pack_start(GTK_BOX(box2),button,TRUE,TRUE,0)
  Call gtk_widget_show(button)

  separator => gtk_hseparator_new()
  Call gtk_box_pack_start(GTK_BOX(box1),separator,FALSE,TRUE,0)
  Call gtk_widget_show(separator)

  box2 => gtk_vbox_new(FALSE,10)
  Call gtk_container_set_border_width(GTK_CONTAINER (box2),10)
  Call gtk_box_pack_start(GTK_BOX(box1),box2,FALSE,TRUE,0)
  Call gtk_widget_show(box2)

  button => gtk_button_new_with_label("close")
  Call g_signal_connect_swapped(G_OBJECT(button),"clicked", &
                                C_FunLoc(close_application),C_Loc(window))
  Call gtk_box_pack_start(GTK_BOX(box2),button,TRUE,TRUE,0)
  Call GTK_WIDGET_SET_FLAGS(button,GTK_CAN_DEFAULT)
  Call gtk_widget_grab_default(button)
  Call gtk_widget_show(button)
  Call gtk_widget_show(window)

  Call gtk_main

End Program

<<< Previous | Home | Next >>>
Check Buttons | Up | Adjustments


Adjustments

GTK has various widgets that can be adjusted by the user using the mouse or the keyboard, such as the range widgets, described in the Range Widgets section. There are also a few widgets that display some adjustable portion of a larger area of data, such as the text widget and the viewport widget.

Obviously, an application needs to be able to react to changes the user makes in range widgets. One way to do this would be to have each widget emit its own type of signal when its adjustment changes, and either pass the new value to the signal handler, or require it to look inside the widget's data structure in order to ascertain the value. But you may also want to connect the adjustments of several widgets together, so that adjusting one adjusts the others. The most obvious example of this is connecting a scrollbar to a panning viewport or a scrolling text area. If each widget has its own way of setting or getting the adjustment value, then the programmer may have to write their own signal handlers to translate between the output of one widget's signal and the input of another's adjustment setting function.

GTK solves this problem using the Adjustment object, which is not a widget but a way for widgets to store and pass adjustment information in an abstract and flexible form. The most obvious use of Adjustment is to store the configuration parameters and values of range widgets, such as scrollbars and scale controls. However, since Adjustments are derived from Object, they have some special powers beyond those of normal data structures. Most importantly, they can emit signals, just like widgets, and these signals can be used not only to allow your program to react to user input on adjustable widgets, but also to propagate adjustment values transparently between adjustable widgets.

You will see how adjustments fit in when you see the other widgets that incorporate them: Progress Bars, Viewports, Scrolled Windows, and others.

Creating an Adjustment

Many of the widgets which use adjustment objects do so automatically, but some cases will be shown in later examples where you may need to create one yourself. You create an adjustment using:

Function gtk_adjustment_new(value,lower,upper,step_increment, &
                            page_increment,page_size)
    Double Precision :: value,lower,upper,step_increment, &
                        page_increment,page_size
    Type(GtkObject),Pointer :: gtk_adjustment_new

The value argument is the initial value you want to give to the adjustment, usually corresponding to the topmost or leftmost position of an adjustable widget. The lower argument specifies the lowest value which the adjustment can hold. The step_increment argument specifies the smaller of the two increments by which the user can change the value, while the page_increment is the larger one. The page_size argument usually corresponds somehow to the visible area of a panning widget. The upper argument is used to represent the bottom most or right most coordinate in a panning widget's child. Therefore it is not always the largest number that value can take, since the page_size of such widgets is usually non-zero.

<<< Previous | Home | Next >>>
Radio Buttons |  | Using Adjustments the Easy Way


Using Adjustments the Easy Way

The adjustable widgets can be roughly divided into those which use and require specific units for these values and those which treat them as arbitrary numbers. The group which treats the values as arbitrary numbers includes the range widgets (scrollbars and scales, the progress bar widget, and the spin button widget). These widgets are all the widgets which are typically adjusted directly by the user with the mouse or keyboard. They will treat the lower and upper values of an adjustment as a range within which the user can manipulate the adjustment's value. By default, they will only modify the value of an adjustment.

The other group includes the text widget, the viewport widget, the compound list widget, and the scrolled window widget. All of these widgets use pixel values for their adjustments. These are also all widgets which are typically adjusted indirectly using scrollbars. While all widgets which use adjustments can either create their own adjustments or use ones you supply, you'll generally want to let this particular category of widgets create its own adjustments. Usually, they will eventually override all the values except the value itself in whatever adjustments you give them, but the results are, in general, undefined (meaning, you'll have to read the source code to find out, and it may be different from widget to widget).

Now, you're probably thinking, since text widgets and viewports insist on setting everything except the value of their adjustments, while scrollbars will only touch the adjustment's value, if you share an adjustment object between a scrollbar and a text widget, will manipulating the scrollbar automatically adjust the viewport widget? Of course it will! Just like this:

  ! Creates its own adjustments.
  viewport => gtk_viewport_new(C_Null_Ptr,C_Null_Ptr)
  ! Uses the newly-created adjustment for the scrollbar as well.
  vscrollbar => gtk_vscrollbar_new(gtk_viewport_get_vadjustment(viewport))

<<< Previous | Home | Next >>>
Adjustments | Up | Adjustment Internals


Adjustment Internals

Ok, you say, that's nice, but what if I want to create my own handlers to respond when the user adjusts a range widget or a spin button, and how do I get at the value of the adjustment in these handlers? To answer these questions and more, let's start by taking a look at type GtkAdjustment itself:

Type,Bind(C) :: GtkAdjustment
  Type(GtkObject) :: parent_instance
  Real(C_Double) :: lower,upper,value,step_increment,page_increment,page_size
End Type

If you don't like to poke directly at the internal structure like a C programmer, you can use the following accessor to inspect the value of an adjustment:

Double Precision Function gtk_adjustment_get_value(adjustment)
  Type(GtkAdjustment),Pointer :: adjustment

Since, when you set the value of an adjustment, you generally want the change to be reflected by every widget that uses this adjustment, GTK provides this convenience function to do this:

Subroutine gtk_adjustment_set_value(adjustment,value)
  Type(GtkAdjustment),Pointer :: adjustment
  Double Precision :: value

As mentioned earlier, Adjustment is a subclass of Object just like all the various widgets, and thus it is able to emit signals. This is, of course, why updates happen automagically when you share an adjustment object between a scrollbar and another adjustable widget; all adjustable widgets connect signal handlers to their adjustment's “value_changed” signal, as can your program. The signal handler interface is:

Subroutine value_changed(adjustment)
  Type(GtkAdjustment) adjustment

The various widgets that use the Adjustment object will emit this signal on an adjustment whenever they change its value. This happens both when user input causes the slider to move on a range widget, as well as when the program explicitly changes the value with gtk_adjustment_set_value. So, for example, if you have a scale widget, and you want to change the rotation of a picture whenever its value changes, you would create a callback like this:

Subroutine cb_rotate_picture(adj,picture) Bind(C)
  Type(GtkAdjustment) adj
  Type(GtkWidget) picture

  Call set_picture_rotation(picture,gtk_adjustment_get_value(adj))
  ...

and connect it to the scale widget's adjustment like this:

Call g_signal_connect(G_OBJECT(adj),"value_changed", &
                      C_FunLoc(cb_rotate_picture),C_Loc(picture))

What about when a widget reconfigures the upper or lower fields of its adjustment, such as when a user adds more text to a text widget? In this case, it emits the changed signal, which looks like this:

Subroutine changed(adjustment)
  Type(GtkAdjustment) adjustment

Range widgets typically connect a handler to this signal, which changes their appearance to reflect the change; for example, the size of the slider in a scrollbar will grow or shrink in inverse proportion to the difference between the lower and upper values of its adjustment.

You probably won't ever need to attach a handler to this signal, unless you're writing a new type of range widget. However, if you change any of the values in a Adjustment directly, you should emit this signal on it to reconfigure whatever widgets are using it, like this:

Call g_signal_emit_by_name(G_OBJECT(adjustment),"changed")

Now go forth and adjust!

<<< Previous | Home | Next >>>
Using Adjustments the Easy Way | Up | Range Widgets


Range Widgets

The category of range widgets includes the ubiquitous scrollbar widget and the less common scale widget. Though these two types of widgets are generally used for different purposes, they are quite similar in function and implementation. All range widgets share a set of common graphic elements, each of which has its own window and receives events. They all contain a “trough” and a “slider” (what is sometimes called a “thumbwheel” in other GUI environments). Dragging the slider with the pointer moves it back and forth within the trough, while clicking in the trough advances the slider towards the location of the click, either completely, or by a designated amount, depending on which mouse button is used.

As mentioned in Adjustments above, all range widgets are associated with an adjustment object, from which they calculate the length of the slider and its position within the trough. When the user manipulates the slider, the range widget will change the value of the adjustment.

Scrollbar Widgets

These are your standard, run-of-the-mill scrollbars. These should be used only for scrolling some other widget, such as a list, a text box, or a viewport (and it's generally easier to use the scrolled window widget in most cases). For other purposes, you should use scale widgets, as they are friendlier and more featureful.

There are separate types for horizontal and vertical scrollbars. There really isn't much to say about these. You create them with the following functions:

Function gtk_hscrollbar_new(adjustment) Result(r)
    Type(GtkAdjustment),Pointer :: adjustment
    Type(GtkWidget),Pointer :: r

Function gtk_vscrollbar_new(adjustment) Result(r)
    Type(GtkAdjustment),Pointer :: adjustment
    Type(GtkWidget),Pointer :: r

and that's about it. The adjustment argument can either be a pointer to an existing Adjustment, or NULL(), in which case one will be created for you. Specifying NULL() might actually be useful in this case, if you wish to pass the newly-created adjustment to the constructor function of some other widget which will configure it for you, such as a text widget.

<<< Previous | Home | Next >>>
Adjustment Internals |  | Scale Widgets


Scale Widgets

Scale widgets are used to allow the user to visually select and manipulate a value within a specific range. You might want to use a scale widget, for example, to adjust the magnification level on a zoomed preview of a picture, or to control the brightness of a color, or to specify the number of minutes of inactivity before a screensaver takes over the screen.

Creating a Scale Widget

As with scrollbars, there are separate widget types for horizontal and vertical scale widgets. (Most programmers seem to favour horizontal scale widgets.) Since they work essentially the same way, there's no need to treat them separately here. The following functions create vertical and horizontal scale widgets, respectively:

Function gtk_vscale_new(adjustment) Result(res)
  Type(GtkAdjustment),Pointer :: adjustment
  Type(GtkWidget),Pointer :: res

Function gtk_vscale_new_with_range(min,max,step) Result(res)
  Double Precision,Intent(In) :: min,max,step
  Type(GtkWidget),Pointer :: res

Function gtk_hscale_new(adjustment) Result(res)
  Type(GtkAdjustment),Pointer :: adjustment
  Type(GtkWidget),Pointer :: res

Function gtk_hscale_new_with_range(min,max,step) Result(res)
  Double Precision,Intent(In) :: min,max,step
  Type(GtkWidget),Pointer :: res

The adjustment argument can either be an adjustment which has already been created with gtk_adjustment_new or NULL(); in the latter case, an anonymous Adjustment is created with all of its values set to 0.0 (which isn't very useful). In order to avoid confusing yourself, you probably want to create your adjustment with a page_size of zero so that its upper value actually corresponds to the highest value the user can select. The _new_with_range variants take care of creating a suitable adjustment. (If you're already thoroughly confused, read the section on Adjustments again for an explanation of what exactly adjustments do and how to create and manipulate them.)

Functions and Signals (well, functions, at least)

Scale widgets can display their current value as a number beside the trough. The default behaviour is to show the value, but you can change this with this function:

Subroutine gtk_scale_set_draw_value(scale,draw_value)
  Type(GtkScale),Pointer :: scale
  Integer(gboolean),Intent(In) :: draw_value

As you might have guessed, draw_value is either TRUE or FALSE, with predictable consequences for either one.

The value displayed by a scale widget is rounded to one decimal point by default, as is the value field in its Adjustment. You can change this with:

Subroutine gtk_scale_set_digits(scale,digits)
  Type(GtkScale),Pointer :: scale
  Integer(gint),Intent(In) :: digits

where digits is the number of decimal places you want. You can set digits to anything you like, but no more than 13 decimal places will actually be drawn on screen.

Finally, the value can be drawn in different positions relative to the trough:

Subroutine gtk_scale_set_value_pos(scale,pos)
  Type(GtkScale),Pointer :: scale
  Integer(GtkPositionType),Intent(In) :: pos

The argument pos is of type Integer(GtkPositionType), and must be one of the following values:

  GTK_POS_LEFT
  GTK_POS_RIGHT
  GTK_POS_TOP
  GTK_POS_BOTTOM

If you position the value on the “side” of the trough (e.g., on the top or bottom of a horizontal scale widget), then it will follow the slider up and down the trough.

<<< Previous | Home | Next >>>
Range Widgets | Up | Common Range Functions


Common Range Functions

The Range widget class is fairly complicated internally, but, like all the “base class” widgets, most of its complexity is only interesting if you want to hack on it. Also, almost all of the functions and signals it defines are only really used in writing derived widgets. There are, however, a few useful functions that will work on all range widgets.

Setting the Update Policy

The “update policy” of a range widget defines at what points during user interaction it will change the value field of its Adjustment and emit the value_changed signal on this Adjustment. The update policies, defined as type Integer(GtkUpdateType), are:

GTK_UPDATE_CONTINUOUS

This is the default. The "value_changed" signal is emitted continuously, i.e., whenever the slider is moved by even the tiniest amount.

GTK_UPDATE_DISCONTINUOUS

The "value_changed" signal is only emitted once the slider has stopped moving and the user has released the mouse button.

GTK_UPDATE_DELAYED

The "value_changed" signal is emitted when the user releases the mouse button, or if the slider stops moving for a short period of time.

The update policy of a range widget can be set by casting it using the GTK_RANGE(widget) function and passing it to this procedure:

Subroutine gtk_range_set_update_policy(range,policy)
  Type(GtkRange),Pointer :: range
  Integer(GtkUpdateType) :: policy

Getting and Setting Adjustments

Getting and setting the adjustment for a range widget “on the fly” is done, predictably, with:

Function gtk_range_get_adjustment(range) Result(r)
  Type(GtkRange),Pointer :: range
  Type(GtkAdjustment),Pointer :: r

Subroutine gtk_range_set_adjustment(range,adjustment)
  Type(GtkRange),Pointer :: range
  Type(GtkAdjustment),Pointer :: adjustment

gtk_range_get_adjustment returns a pointer to the adjustment to which range is connected.

gtk_range_set_adjustment does absolutely nothing if you pass it the adjustment that range is already using, regardless of whether you changed any of its fields or not. If you pass it a new Adjustment, it will unreference the old one if it exists (possibly destroying it), connect the appropriate signals to the new one, and call the private function gtk_range_adjustment_changed, which will (or at least, is supposed to...) recalculate the size and/or position of the slider and redraw if necessary. As mentioned in the section on adjustments, if you wish to reuse the same Adjustment, when you modify its values directly, you should emit the "changed" signal on it, like this:

Call g_signal_emit_by_name(G_OBJECT(adjustment),"changed")

<<< Previous | Home | Next >>>
Scale Widgets | Up | Key and Mouse bindings


Key and Mouse bindings

All of the GTK range widgets react to mouse clicks in more or less the same way. Clicking button-1 in the trough will cause its adjustment's page_increment to be added or subtracted from its value, and the slider to be moved accordingly. Clicking mouse button-2 in the trough will jump the slider to the point at which the button was clicked. Clicking button-3 in the trough of a range or any button on a scrollbar's arrows will cause its adjustment's value to change by step_increment at a time.

Scrollbars are not focusable, thus have no key bindings. The key bindings for the other range widgets (which are, of course, only active when the widget has focus) do not differentiate between horizontal and vertical range widgets.

All range widgets can be operated with the left, right, up and down arrow keys, as well as with the Page Up and Page Down keys. The arrows move the slider up and down by step_increment, while Page Up and Page Down move it by page_increment.

The user can also move the slider all the way to one end or the other of the trough using the keyboard. This is done with the Home and End keys.

<<< Previous | Home | Next >>>
Common Range Functions | Up | Example


Example

This example is a somewhat modified version of the “range controls” test program. It basically puts up a window with three range widgets all connected to the same adjustment, and a couple of controls for adjusting some of the parameters mentioned above and in the section on adjustments, so you can see how they affect the way these widgets work for the user.

Module range_controls
  Use gtk
  Use glib
  Implicit None

  Type(GtkWidget),Pointer :: hscale => Null(), vscale => Null()

Contains

  Subroutine cb_pos_menu_select(item,pos) Bind(C,Name='')
    Type(GtkWidget) :: item
    Integer(GtkPositionType),Value :: pos

    ! Set the value position on both scale widgets.
    Call gtk_scale_set_value_pos(GTK_SCALE(C_Loc(hscale)),pos)
    Call gtk_scale_set_value_pos(GTK_SCALE(C_Loc(vscale)),pos)
  End Subroutine

  Subroutine cb_update_menu_select(item,policy) Bind(C,Name='')
    Type(GtkWidget) item
    Integer(GtkUpdateType),Value :: policy
    ! Set the update policy for both scale widgets.
    Call gtk_range_set_update_policy(GTK_RANGE(hscale),policy)
    Call gtk_range_set_update_policy(GTK_RANGE(vscale),policy)
  End Subroutine

  Subroutine cb_digits_scale(adj) Bind(C,Name='')
    Type(GtkAdjustment) adj
    ! Set the number of decimal places to which adj->value is rounded.
    Call gtk_scale_set_digits(GTK_SCALE(c_loc(hscale)),Int(adj%value,gint))
    Call gtk_scale_set_digits(GTK_SCALE(c_loc(vscale)),Int(adj%value,gint))
  End Subroutine

  Subroutine cb_page_size(get,set) Bind(C,Name='')
    Type(GtkAdjustment) :: get
    Type(GtkAdjustment),Target,Intent(InOut) :: set
    Type(GtkAdjustment),Pointer :: pset

    ! Set the page size and page increment size of the sample adjustment
    ! to the value specified by the "Page Size" scale.
    set%page_size      = get%value
    set%page_increment = get%value

    ! This sets the adjustment and makes it emit the "changed" signal
    ! to reconfigure all the widgets that are attached to this signal.
    pset => set
    Call gtk_adjustment_set_value(pset,CLAMP(set%value,set%lower, &
                                             set%upper - set%page_size))
    Call g_signal_emit_by_name(G_OBJECT(C_Loc(set)),"changed")
  End Subroutine

  Subroutine cb_draw_value(button) Bind(C,Name='')
    Type(GtkToggleButton),Target :: button
    Integer :: active
    Type(GtkToggleButton),Pointer :: pbutton

    pbutton => button
    ! Turn the value display on the scale widgets off or on depending
    ! on the state of the checkbutton.
    active = gtk_toggle_button_get_active(pbutton)
    Call gtk_scale_set_draw_value (GTK_SCALE(c_loc(hscale)),active)
    active = gtk_toggle_button_get_active(pbutton)
    Call gtk_scale_set_draw_value (GTK_SCALE(c_loc(vscale)),active)
  End Subroutine

  ! Convenience procedures.
  Subroutine make_menu_item(item,name,callback,data)
    Type(GtkWidget),Pointer :: item
    Character(*) :: name
    Type(C_FunPtr),Value :: callback
    Type(C_Ptr),Value :: data

    item => gtk_menu_item_new_with_label(name)
    Call g_signal_connect(G_OBJECT(item),"activate",callback,data)
    Call gtk_widget_show(item)
  End Subroutine

  Subroutine scale_set_default_values(scale)
    Type(GtkScale),Pointer :: scale

    Call gtk_range_set_update_policy(GTK_RANGE(C_Loc(scale)),GTK_UPDATE_CONTINUOUS)
    Call gtk_scale_set_digits(scale,1)
    Call gtk_scale_set_value_pos(scale,GTK_POS_TOP)
    Call gtk_scale_set_draw_value(scale,TRUE)
  End Subroutine

  ! Makes the sample window.
  Subroutine create_range_controls
    Type(GtkWidget),Pointer :: window,box1,box2,box3,button,scrollbar, &
                               separator,opt, menu, item,label,scale
    Type(GtkObject),Pointer :: adj1,adj2

    ! Standard window-creating stuff.
    window => gtk_window_new(GTK_WINDOW_TOPLEVEL)
    Call g_signal_connect(G_OBJECT(C_Loc(window)),"destroy", &
                          C_FunLoc(gtk_main_quit),C_Null_Ptr)
    Call gtk_window_set_title(GTK_WINDOW(window),"range controls")

    box1 => gtk_vbox_new(FALSE,0)
    Call gtk_container_add(GTK_CONTAINER(window),box1)
    Call gtk_widget_show(box1)

    box2 => gtk_hbox_new(FALSE,10)
    Call gtk_container_set_border_width(GTK_CONTAINER(box2),10)
    Call gtk_box_pack_start(GTK_BOX(box1),box2,TRUE,TRUE,0)
    Call gtk_widget_show(box2)

    ! value, lower, upper, step_increment, page_increment, page_size
    ! Note that the page_size value only makes a difference for
    ! scrollbar widgets, and the highest value you'll get is actually
    ! (upper - page_size).
    adj1 => gtk_adjustment_new(0.0d0,0.0d0,101.0d0,0.1d0,1.0d0,1.0d0)
    vscale => gtk_vscale_new(GTK_ADJUSTMENT(C_Loc(adj1)))
    Call scale_set_default_values(GTK_SCALE(C_Loc(vscale)))
    Call gtk_box_pack_start(GTK_BOX(box2),vscale,TRUE,TRUE,0)
    Call gtk_widget_show(vscale)

    box3 => gtk_vbox_new(FALSE,10)
    Call gtk_box_pack_start(GTK_BOX(box2),box3,TRUE,TRUE,0)
    Call gtk_widget_show(box3)

    ! Reuse the same adjustment.
    hscale => gtk_hscale_new(GTK_ADJUSTMENT(C_Loc(adj1)))
    Call gtk_widget_set_size_request(hscale,200,-1)
    Call scale_set_default_values(GTK_SCALE(C_Loc(hscale)))
    Call gtk_box_pack_start(GTK_BOX(box3),hscale,TRUE,TRUE,0)
    Call gtk_widget_show(hscale)

    ! Reuse the same adjustment again.
    scrollbar => gtk_hscrollbar_new(GTK_ADJUSTMENT(C_Loc(adj1)))
    ! Notice how this causes the scales to always be updated
    ! continuously when the scrollbar is moved.
    Call gtk_range_set_update_policy(GTK_RANGE(scrollbar),GTK_UPDATE_CONTINUOUS)
    Call gtk_box_pack_start(GTK_BOX(box3),scrollbar,TRUE,TRUE,0)
    Call gtk_widget_show(scrollbar)

    box2 => gtk_hbox_new(FALSE,10)
    Call gtk_container_set_border_width(GTK_CONTAINER(box2),10)
    Call gtk_box_pack_start(GTK_BOX(box1),box2,TRUE,TRUE,0)
    Call gtk_widget_show(box2)

    ! A checkbutton to control whether the value is displayed or not.
    button => gtk_check_button_new_with_label("Display value on scale widgets")
    Call gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(C_Loc(button)),TRUE)
    Call g_signal_connect(G_OBJECT(button),"toggled", &
                          C_FunLoc(cb_draw_value),C_Null_Ptr)
    Call gtk_box_pack_start(GTK_BOX(box2),button,TRUE,TRUE,0)
    Call gtk_widget_show(button)

    box2 => gtk_hbox_new(FALSE,10)
    Call gtk_container_set_border_width(GTK_CONTAINER(box2),10)

    ! An option menu to change the position of the value.
    label => gtk_label_new("Scale Value Position:")
    Call gtk_box_pack_start(GTK_BOX(box2),label,FALSE,FALSE,0)
    Call gtk_widget_show(label)

    opt => gtk_option_menu_new()
    menu => gtk_menu_new()

    Call make_menu_item(item,"Top",C_FunLoc(cb_pos_menu_select), &
                        GINT_TO_POINTER(GTK_POS_TOP))
    Call gtk_menu_shell_append(GTK_MENU_SHELL(menu),item)

    call make_menu_item(item,"Bottom",C_FunLoc(cb_pos_menu_select), &
                        GINT_TO_POINTER(GTK_POS_BOTTOM))
    Call gtk_menu_shell_append(GTK_MENU_SHELL(menu),item)

    Call make_menu_item(item,"Left",C_FunLoc(cb_pos_menu_select), &
                        GINT_TO_POINTER(GTK_POS_LEFT))
    Call gtk_menu_shell_append(GTK_MENU_SHELL(menu),item)

    Call make_menu_item(item,"Right",C_FunLoc(cb_pos_menu_select), &
                        GINT_TO_POINTER(GTK_POS_RIGHT))
    Call gtk_menu_shell_append(GTK_MENU_SHELL(menu),item)

    Call gtk_option_menu_set_menu(GTK_OPTION_MENU(C_Loc(opt)),menu)
    Call gtk_box_pack_start(GTK_BOX(box2),opt,TRUE,TRUE,0)
    Call gtk_widget_show(opt)

    Call gtk_box_pack_start(GTK_BOX(box1),box2,TRUE,TRUE,0)
    Call gtk_widget_show(box2)

    box2 => gtk_hbox_new(FALSE,10)
    Call gtk_container_set_border_width(GTK_CONTAINER(box2),10)

    ! Yet another option menu, this time for the update policy of the
    ! scale widgets.
    label => gtk_label_new("Scale Update Policy:")
    Call gtk_box_pack_start(GTK_BOX(box2),label,FALSE,FALSE,0)
    Call gtk_widget_show(label)

    opt => gtk_option_menu_new()
    menu => gtk_menu_new()

    Call make_menu_item(item,"Continuous", &
                        C_FunLoc(cb_update_menu_select), &
                        GINT_TO_POINTER(GTK_UPDATE_CONTINUOUS))
    Call gtk_menu_shell_append(GTK_MENU_SHELL(menu),item)

    Call make_menu_item(item,"Discontinuous", &
                        C_FunLoc(cb_update_menu_select), &
                        GINT_TO_POINTER(GTK_UPDATE_DISCONTINUOUS))
    Call gtk_menu_shell_append(GTK_MENU_SHELL(menu),item)

    Call make_menu_item(item,"Delayed",C_FunLoc(cb_update_menu_select), &
                        GINT_TO_POINTER(GTK_UPDATE_DELAYED))
    Call gtk_menu_shell_append(GTK_MENU_SHELL(menu),item)

    Call gtk_option_menu_set_menu(GTK_OPTION_MENU(C_Loc(opt)),menu)
    Call gtk_box_pack_start(GTK_BOX(box2),opt,TRUE,TRUE,0)
    Call gtk_widget_show(opt)

    Call gtk_box_pack_start(GTK_BOX(box1),box2,TRUE,TRUE,0)
    Call gtk_widget_show(box2)

    box2 => gtk_hbox_new(FALSE,10)
    Call gtk_container_set_border_width(GTK_CONTAINER(box2),10)

    ! An HScale widget for adjusting the number of digits on the
    ! sample scales.
    label => gtk_label_new("Scale Digits:")
    Call gtk_box_pack_start(GTK_BOX(box2),label,FALSE,FALSE,0)
    Call gtk_widget_show(label)

    adj2 => gtk_adjustment_new(1.0d0,0.0d0,5.0d0,1.0d0,1.0d0,0.0d0)
    Call g_signal_connect(G_OBJECT(adj2),"value_changed", &
                          C_FunLoc(cb_digits_scale),C_Null_Ptr)
    scale => gtk_hscale_new(GTK_ADJUSTMENT(C_Loc(adj2)))
    Call gtk_scale_set_digits(GTK_SCALE(C_Loc(scale)),0)
    Call gtk_box_pack_start(GTK_BOX(box2),scale,TRUE,TRUE,0)
    Call gtk_widget_show(scale)

    Call gtk_box_pack_start(GTK_BOX(box1),box2,TRUE,TRUE,0)
    Call gtk_widget_show(box2)

    box2 => gtk_hbox_new(FALSE,10)
    Call gtk_container_set_border_width(GTK_CONTAINER(box2),10)

    ! And one last HScale widget for adjusting the page size of the scrollbar.
    label => gtk_label_new("Scrollbar Page Size:")
    Call gtk_box_pack_start(GTK_BOX(box2),label,FALSE,FALSE,0)
    Call gtk_widget_show(label)

    adj2 => gtk_adjustment_new(1.0d0,1.0d0,101.0d0,1.0d0,1.0d0,0.0d0)
    Call g_signal_connect(G_OBJECT(adj2),"value_changed", &
                          C_FunLoc(cb_page_size),C_Loc(adj1))
    scale => gtk_hscale_new(GTK_ADJUSTMENT(C_Loc(adj2)))
    Call gtk_scale_set_digits(GTK_SCALE(C_Loc(scale)),0)
    Call gtk_box_pack_start(GTK_BOX(box2),scale,TRUE,TRUE,0)
    Call gtk_widget_show(scale)

    Call gtk_box_pack_start(GTK_BOX(box1),box2,TRUE,TRUE,0)
    Call gtk_widget_show(box2)

    separator => gtk_hseparator_new()
    Call gtk_box_pack_start(GTK_BOX(box1),separator,FALSE,TRUE,0)
    Call gtk_widget_show(separator)

    box2 => gtk_vbox_new(FALSE,10)
    Call gtk_container_set_border_width(GTK_CONTAINER(box2),10)
    Call gtk_box_pack_start(GTK_BOX(box1),box2,FALSE,TRUE,0)
    Call gtk_widget_show(box2)

    button => gtk_button_new_with_label("Quit")
    Call g_signal_connect(G_OBJECT(button),"clicked", &
                          C_FunLoc(gtk_main_quit),C_Null_Ptr)
    Call gtk_box_pack_start(GTK_BOX(box2),button,TRUE,TRUE,0)
    Call GTK_WIDGET_SET_FLAGS(button,GTK_CAN_DEFAULT)
    Call gtk_widget_grab_default(button)
    Call gtk_widget_show(button)

    Call gtk_widget_show(window)
  End Subroutine

End Module

Program main
  Use range_controls

  Call gtk_init
  Call create_range_controls
  Call gtk_main
End Program

You will notice that the program does not call g_signal_connect for the "delete_event", but only for the "destroy" signal. This will still perform the desired function, because an unhandled "delete_event" will result in a "destroy" signal being given to the window.

<<< Previous | Home | Next >>>
Key and Mouse bindings | Up | Miscellaneous Widgets


Miscellaneous Widgets

Labels

Labels are used a lot in GTK, and are relatively simple. Labels emit no signals as they do not have an associated window. If you need to catch signals, or do clipping, place it inside a EventBox widget or a Button widget.

To create a new label, use:

Function gtk_label_new(str) Result(r)
    Character(*) :: str
    Type(GtkWidget),Pointer :: r

Function gtk_label_new_with_mnemonic(str) Result(r)
    Character(*) :: str
    Type(GtkWidget),Pointer :: r

The sole argument is the string you wish the label to display.

To change the label's text after creation, use the procedure

Subroutine gtk_label_set_text(label,str)
    Type(GtkLabel),Pointer :: label
    Character(*) :: str

The first argument is the label you created previously (cast using the GTK_LABEL() function), and the second is the new string.

The space needed for the new string will be automatically adjusted if needed. You can produce multi-line labels by putting C_New_Line in the label string.

To retrieve the current string, use:

Function gtk_label_get_text(label) Result(r)
    Type(GtkLabel),Pointer :: label
    Character,Pointer :: r(:)

Do not free the returned string, as it is used internally by GTK.

The label text can be justified using:

Subroutine gtk_label_set_justify(label,jtype)
    Type(GtkLabel),Pointer :: label
    Integer(GtkJustification) :: jtype

Values for jtype are:

GTK_JUSTIFY_LEFT
GTK_JUSTIFY_RIGHT
GTK_JUSTIFY_CENTER (the default)
GTK_JUSTIFY_FILL

The label widget is also capable of line wrapping the text automatically. This can be activated using:

Subroutine gtk_label_set_line_wrap(label,wrap)
    Type(GtkLabel),Pointer :: label
    Integer :: wrap

The wrap argument takes a TRUE or FALSE value.

If you want your label underlined, then you can set a pattern on the label:

Subroutine gtk_label_set_pattern(label,pattern)
    Type(GtkLabel),Pointer :: label
    Character(*) :: pattern

The pattern argument indicates how the underlining should look. It consists of a string of underscore and space characters. An underscore indicates that the corresponding character in the label should be underlined. For example, the string "__     __" would underline the first two characters and eight and ninth characters.

Note

If you simply want to have an underlined accelerator (“mnemonic”) in your label, you should use gtk_label_new_with_mnemonic or gtk_label_set_text_with_mnemonic, not gtk_label_set_pattern.

Below is a short example to illustrate these functions. This example makes use of the Frame widget to better demonstrate the label styles. You can ignore this for now as the Frame widget is explained later on.

In GTK+ 2.0, label texts can contain markup for font and other text attribute changes, and labels may be selectable (for copy-and-paste). These advanced features won't be explained here.

Program main
  Use gtk

  Type(GtkWidget),Pointer :: window

  Type(GtkWidget),Pointer :: hbox,vbox,frame,label

  Character(*),Parameter :: long_labelstr1 = &
        "This is an example of a line-wrapped label.  It"   // &
        " should not be taking up the entire            "   // & !big space to test spacing
        "width allocated to it, but automatically "         // &
        "wraps the words to fit. "                          // &
        "The time has come, for all good men, to come to "  // &
        "the aid of their party. "                          // &
        "The sixth sheik's six sheep's sick." // c_new_line // &
        "     It supports multiple paragraphs correctly, "  // &
        "and  correctly   adds "                            // &
        "many          extra  spaces. "

    Character(*),Parameter :: long_labelstr2 = &
        "This is an example of a line-wrapped, filled label.  " // &
        "It should be taking "                                  // &
        "up the entire              width allocated to it.  "   // &
        "Here is a sentence to prove "                          // &
        "my point.  Here is another sentence. "                 // &
        "Here comes the sun, do de do de do." // c_new_line     // &
        "    This is a new paragraph." // c_new_line            // &
        "    This is another newer, longer, better "            // &
        "paragraph.  It is coming to an end, "                  // &
        "unfortunately."

  Call gtk_init

  window => gtk_window_new(GTK_WINDOW_TOPLEVEL)
  Call g_signal_connect(G_OBJECT(window),"destroy", &
                        G_CALLBACK(gtk_main_quit),C_Null_Ptr)

  Call gtk_window_set_title(GTK_WINDOW(window),"Label")
  vbox => gtk_vbox_new(FALSE,5)
  hbox => gtk_hbox_new(FALSE,5)
  Call gtk_container_add(GTK_CONTAINER(window),hbox)
  Call gtk_box_pack_start(GTK_BOX(hbox),vbox,FALSE,FALSE,0)
  Call gtk_container_set_border_width(GTK_CONTAINER(window),5)

  frame => gtk_frame_new("Normal Label")
  label => gtk_label_new("This is a Normal label")
  Call gtk_container_add(GTK_CONTAINER(frame),label)
  Call gtk_box_pack_start(GTK_BOX(vbox),frame,FALSE,FALSE,0)

  frame => gtk_frame_new("Multi-line Label")
  label => gtk_label_new("This is a Multi-line label."//C_New_Line// &
                            "Second line"//C_New_Line//"Third line")
  Call gtk_container_add(GTK_CONTAINER(frame),label)
  Call gtk_box_pack_start(GTK_BOX(vbox),frame,FALSE,FALSE,0)

  frame => gtk_frame_new("Left Justified Label")
  label => gtk_label_new("This is a Left-Justified"//C_New_Line// &
                            "Multi-line label."//C_New_Line// &
                            "Third      line")
  Call gtk_label_set_justify(GTK_LABEL(label),GTK_JUSTIFY_LEFT)
  Call gtk_container_add(GTK_CONTAINER(frame),label)
  Call gtk_box_pack_start(GTK_BOX(vbox),frame,FALSE,FALSE,0)

  frame => gtk_frame_new("Right Justified Label")
  label => gtk_label_new("This is a Right-Justified"//C_New_Line// &
                            "Multi-line label."//C_New_Line// &
                            "Fourth line, (j/k)")
  Call gtk_label_set_justify(GTK_LABEL(label),GTK_JUSTIFY_RIGHT)
  Call gtk_container_add(GTK_CONTAINER(frame),label)
  Call gtk_box_pack_start(GTK_BOX(vbox),frame,FALSE,FALSE,0)
  vbox => gtk_vbox_new(FALSE,5)
  Call gtk_box_pack_start(GTK_BOX(hbox),vbox,FALSE,FALSE,0)
  frame => gtk_frame_new("Line wrapped label1")

  label => gtk_label_new(long_labelstr1)

  Call gtk_label_set_line_wrap(GTK_LABEL(label),TRUE)
  Call gtk_container_add(GTK_CONTAINER(frame),label)
  Call gtk_box_pack_start(GTK_BOX(vbox),frame,FALSE,FALSE,0)

  frame => gtk_frame_new("Filled, wrapped label")

  label => gtk_label_new(long_labelstr2)

  Call gtk_label_set_justify(GTK_LABEL(label),GTK_JUSTIFY_FILL)
  Call gtk_label_set_line_wrap(GTK_LABEL(label),TRUE)
  Call gtk_container_add(GTK_CONTAINER(frame),label)
  Call gtk_box_pack_start(GTK_BOX(vbox),frame,FALSE,FALSE,0)

  frame => gtk_frame_new("Underlined label")
  label => gtk_label_new("This label is underlined!"//C_New_Line// &
                            "This one is underlined in quite a funky fashion")
  Call gtk_label_set_justify(GTK_LABEL(label),GTK_JUSTIFY_LEFT)
  Call gtk_label_set_pattern(GTK_LABEL(label), &
                             "_________________________ _ _________ _ ______     __ _______ ___")
  Call gtk_container_add(GTK_CONTAINER(frame),label)
  Call gtk_box_pack_start(GTK_BOX(vbox),frame,FALSE,FALSE,0)

  Call gtk_widget_show_all(window)

  Call gtk_main

End Program

<<< Previous | Home | Next >>>
Example |  | Arrows


Arrows

The Arrow widget draws an arrowhead, facing in a number of possible directions and having a number of possible styles. It can be very useful when placed on a button in many applications. Like the Label widget, it emits no signals.

There are only two procedures for manipulating an Arrow widget:

Function gtk_arrow_new(arrow_type,shadow_type) Result(r)
    Integer(GtkArrowType) :: arrow_type
    Integer(GtkShadowType) :: shadow_type
    Type(GtkWidget),Pointer :: r

Subroutine gtk_arrow_set(arrow,arrow_type,shadow_type)
    Type(GtkArrow),Pointer :: arrow
    Integer(GtkArrowType) :: arrow_type
    Integer(GtkShadowType) :: shadow_type

The first creates a new arrow widget with the indicated type and appearance. The second allows these values to be altered retrospectively. The arrow_type argument may take one of the following values:

GTK_ARROW_UP
GTK_ARROW_DOWN
GTK_ARROW_LEFT
GTK_ARROW_RIGHT

These values obviously indicate the direction in which the arrow will point. The shadow_type argument may take one of these values:

GTK_SHADOW_IN
GTK_SHADOW_OUT (the default)
GTK_SHADOW_ETCHED_IN
GTK_SHADOW_ETCHED_OUT

Here's a brief example to illustrate their use.

Module Arrow_Buttons
  Use Iso_C_Binding
  Use gtk

Contains

  ! Create an Arrow widget with the specified parameters
  ! and pack it into a button.
  Function create_arrow_button(arrow_type,shadow_type) Result(button)
    Type(GtkWidget),Pointer :: arrow
    Integer :: arrow_type,shadow_type
    Type(GtkWidget),Pointer :: button

    button => gtk_button_new()
    arrow  => gtk_arrow_new(arrow_type,shadow_type)

    Call gtk_container_add(GTK_CONTAINER(button),arrow)

    Call gtk_widget_show(button)
    Call gtk_widget_show(arrow)

  End Function

End Module

Program main
  Use Arrow_Buttons

  ! GtkWidget is the storage type for widgets.
  Type(GtkWidget),Pointer :: window,button,box

  ! Initialise GTK.
  Call gtk_init

  ! Create a new window.
  window => gtk_window_new(GTK_WINDOW_TOPLEVEL)
  Call gtk_window_set_title(GTK_WINDOW(window),"Arrow Buttons")

  ! It's a good idea to do this for all windows.
  Call g_signal_connect(G_OBJECT(window),"destroy", &
                        C_FunLoc(gtk_main_quit),C_Null_Ptr)

  ! Sets the border width of the window.
  Call gtk_container_set_border_width(GTK_CONTAINER(window),10)

  ! Create a box to hold the arrows/buttons.
  box => gtk_hbox_new(FALSE,0)
  Call gtk_container_set_border_width(GTK_CONTAINER(box),2)

  Call gtk_container_add(GTK_CONTAINER(window),box)

  ! Pack and show all our widgets.
  Call gtk_widget_show(box)

  button => create_arrow_button(GTK_ARROW_UP,GTK_SHADOW_IN)
  Call gtk_box_pack_start(GTK_BOX(box),button,FALSE,FALSE,3)

  button => create_arrow_button(GTK_ARROW_DOWN,GTK_SHADOW_OUT)
  Call gtk_box_pack_start(GTK_BOX(box),button,FALSE,FALSE,3)

  button => create_arrow_button(GTK_ARROW_LEFT,GTK_SHADOW_ETCHED_IN)
  Call gtk_box_pack_start(GTK_BOX(box),button,FALSE,FALSE,3)

  button => create_arrow_button(GTK_ARROW_RIGHT,GTK_SHADOW_ETCHED_OUT)
  Call gtk_box_pack_start(GTK_BOX(box),button,FALSE,FALSE,3)

  Call gtk_widget_show(window)

  ! Rest in gtk_main and wait for the fun to begin!
  Call gtk_main

End Program

<<< Previous | Home | Next >>>
Miscellaneous Widgets | Up | The Tooltips Object


The Tooltips Object

These are the little text strings that pop up when you leave your pointer over a button or other widget for a few seconds. They are easy to use, so I will just explain them without giving an example.

Widgets that do not receive events (widgets that do not have their own window) will not work with tooltips.

The first call you will use creates a new tooltip. You only need to do this once for a set of tooltips as the GtkTooltips object this function returns can be used to create multiple tooltips.

Function gtk_tooltips_new() Result(r)
    Type(GtkTooltips),Pointer :: r

Once you have created a new tooltip, and the widget you wish to use it on, simply use this call to set it:

Subroutine gtk_tooltips_set_tip(tooltips,widget,tip_text,tip_private)
    Type(GtkTooltips),Pointer :: tooltips
    Type(GtkWidget),Pointer :: widget
    Character(*) :: tip_text,tip_private

The first argument is the tooltip you've already created, followed by the widget you wish to have this tooltip pop up for, and the text you wish it to say. The last argument is a text string that can be used as an identifier when using GtkTipsQuery to implement context sensitive help. For now, you can set it to the zero-length string ''.

Here's a short example:

  Type(GtkTooltips),Pointer :: tooltips
  Type(GtkWidget),Pointer :: button
  .
  .
  .
  tooltips => gtk_tooltips_new()
  button => gtk_button_new_with_label("button 1")
  .
  .
  .
  Call gtk_tooltips_set_tip(tooltips,button,"This is button 1",'')

There are other calls that can be used with tooltips. I will just list them with a brief description of what they do.

Subroutine gtk_tooltips_enable(tooltips)
    Type(GtkTooltips),Pointer :: tooltips

Enable a disabled set of tooltips.

Subroutine gtk_tooltips_disable(tooltips)
    Type(GtkTooltips),Pointer :: tooltips

Disable an enabled set of tooltips.

And that's all the functions associated with tooltips. More than you'll ever want to know :-)

<<< Previous | Home | Next >>>
Arrows | Up | Progress Bars


Progress Bars

Progress bars are used to show the status of an operation. They are pretty easy to use, as you will see with the code below. But first lets start out with the calls to create a new progress bar.

Function gtk_progress_bar_new() Result(r)
    Type(GtkWidget),Pointer :: r

Now that the progress bar has been created we can use it.

Subroutine gtk_progress_bar_set_fraction(pbar,fraction)
    Type(GtkProgressBar),Pointer :: pbar
    Double Precision :: fraction

The first argument is the progress bar you wish to operate on, and the second argument is the amount “completed”, meaning the amount the progress bar has been filled from 0-100%. This is passed to the function as a real number ranging from 0 to 1.

GTK v1.2 has added new functionality to the progress bar that enables it to display its value in different ways, and to inform the user of its current value and its range.

A progress bar may be set to one of a number of orientations using the function

Subroutine gtk_progress_bar_set_orientation(pbar,orientation)
    Type(GtkProgressBar),Pointer :: pbar
    Integer(GtkProgressBarOrientation) :: orientation

The orientation argument may take one of the following values to indicate the direction in which the progress bar moves:

  GTK_PROGRESS_LEFT_TO_RIGHT
  GTK_PROGRESS_RIGHT_TO_LEFT
  GTK_PROGRESS_BOTTOM_TO_TOP
  GTK_PROGRESS_TOP_TO_BOTTOM

As well as indicating the amount of progress that has occured, the progress bar may be set to just indicate that there is some activity. This can be useful in situations where progress cannot be measured against a value range. The following function indicates that some progress has been made.

Subroutine gtk_progress_bar_pulse(pbar)
    Type(GtkProgressBar),Pointer :: pbar

The step size of the activity indicator is set using the following function.

Subroutine gtk_progress_bar_set_pulse_step(pbar,fraction)
    Type(GtkProgressBar),Pointer :: pbar
    Double Precision :: fraction

When not in activity mode, the progress bar can also display a configurable text string within its trough, using the following function.

Subroutine gtk_progress_bar_set_text(pbar,text)
    Type(GtkProgressBar),Pointer :: pbar
    Character(*) :: text

Note

Note that gtk_progress_bar_set_text doesn't support the printf()-like formatting of the GTK+ 1.2 Progressbar.

You can turn off the display of the string by calling gtk_progess_bar_set_text again with the zero-length string '' as the second argument.

The current text setting of a progressbar can be retrieved with the following function. Do not free the returned string.

Function gtk_progress_bar_get_text(pbar) Result(r)
    Type(GtkProgressBar),Pointer :: pbar
    Character,Pointer :: r(:)

Progress Bars are usually used with timeouts or other such functions (see section on Timeouts, I/O and Idle Functions) to give the illusion of multitasking. All will employ the gtk_progress_bar_set_fraction or gtk_progress_bar_pulse functions in the same manner.

Here is an example of the progress bar, updated using timeouts. This code also shows you how to reset the Progress Bar.

Module Progress_Bars
  Use gtk
  Use glib
  Implicit None

  Type ProgressData
    Type(GtkWidget),Pointer :: window,pbar
    Integer :: timer,activity_mode
  End Type

Contains

  ! Update the value of the progress bar so that we get some movement.
  Integer(gboolean) Function progress_timeout(data) Bind(C,Name='')
    Type(C_Ptr),Value :: data

    Type(ProgressData),Pointer :: pdata
    Type(GtkProgressBar),Pointer :: ProgressBar
    Double Precision new_val

    Call C_F_Pointer(data,pdata)

    If (pdata%activity_mode/=FALSE) Then
      ProgressBar => GTK_PROGRESS_BAR(C_Loc(pdata%pbar))
      Call gtk_progress_bar_pulse(ProgressBar)
    Else
      ! Calculate the value of the progress bar using the
      ! value range set in the adjustment object.
      ProgressBar => GTK_PROGRESS_BAR(C_Loc(pdata%pbar))
      new_val = gtk_progress_bar_get_fraction(ProgressBar) + 0.01d0

      If (new_val>1) new_val = 0

      ! Set the new value.
      ProgressBar => GTK_PROGRESS_BAR(C_Loc(pdata%pbar))
      Call gtk_progress_bar_set_fraction(ProgressBar,new_val)
    End If

    ! As this is a timeout function, return TRUE so that it
    ! continues to get called.
    progress_timeout = TRUE
  End Function

  ! Callback that toggles the text display within the progress bar trough.
  Subroutine toggle_show_text(widget,datap) Bind(C,Name='')
    Type(GtkWidget) widget
    Type(C_Ptr),Value :: datap
    Type(ProgressData),Pointer :: pdata

    Type(GtkProgressBar),pointer :: ProgressBar
    Character,Pointer :: text(:)
    Logical currently_displayed

    Call C_F_Pointer(datap,pdata)
    ProgressBar => GTK_PROGRESS_BAR(C_Loc(pdata%pbar))

    text => gtk_progress_bar_get_text(ProgressBar)
    If (.Not.Associated(text)) Then
      currently_displayed = .False.
    Else
      currently_displayed = Any(text/=' ')
    End If

    If (currently_displayed) Then
      Call gtk_progress_bar_set_text(ProgressBar,"")
    Else
      Call gtk_progress_bar_set_text(ProgressBar,"some text")
    End If
  End Subroutine

  ! Callback that toggles the activity mode of the progress bar.
  Subroutine toggle_activity_mode(widget,datap) Bind(C,Name='')
    Type(GtkWidget) widget
    Type(C_Ptr),Value :: datap

    Type(ProgressData),Pointer :: pdata
    Type(GtkProgressBar),Pointer :: ProgressBar

    Call C_F_Pointer(datap,pdata)
    If (pdata%activity_mode==FALSE) Then
      pdata%activity_mode = TRUE
    Else
      pdata%activity_mode = FALSE
    End If

    ProgressBar => GTK_PROGRESS_BAR(C_Loc(pdata%pbar))
    If (pdata%activity_mode/=FALSE) Then
      Call gtk_progress_bar_pulse(ProgressBar)
    Else
      Call gtk_progress_bar_set_fraction(ProgressBar,0.0d0)
    End If
  End Subroutine

  ! Callback that toggles the orientation of the progress bar.
  Subroutine toggle_orientation(widget,datap) Bind(C,Name='')
    Type(GtkWidget) widget
    Type(C_Ptr),Value :: datap
    Type(ProgressData),Pointer :: pdata
    Type(GtkProgressBar),pointer :: ProgressBar

    Call C_F_Pointer(datap,pdata)
    ProgressBar => GTK_PROGRESS_BAR(C_Loc(pdata%pbar))

    Select Case(gtk_progress_bar_get_orientation(ProgressBar))
    Case (GTK_PROGRESS_LEFT_TO_RIGHT)
      Call gtk_progress_bar_set_orientation(ProgressBar, &
                                            GTK_PROGRESS_RIGHT_TO_LEFT)
    Case (GTK_PROGRESS_RIGHT_TO_LEFT)
      Call gtk_progress_bar_set_orientation(ProgressBar, &
                                            GTK_PROGRESS_LEFT_TO_RIGHT)
    ! Case Default: do nothing.
    End Select
  End Subroutine

  ! Clean up allocated memory and remove the timer.
  Subroutine destroy_progress(widget,datap) Bind(C,Name='')
    Type(GtkWidget) widget
    Type(C_Ptr),Value :: datap
    Type(ProgressData),Pointer :: pdata

    Integer :: junk

    Call C_F_Pointer(datap,pdata)
    junk = g_source_remove(pdata%timer)
    pdata%timer = 0
    Nullify(pdata%window)
    Deallocate(pdata)
    Call gtk_main_quit
  End Subroutine

End Module

Program main
  Use Progress_Bars

  Type(ProgressData),Pointer :: pdata
  Type(GtkWidget),Pointer :: align,separator,table,button,check,vbox
  Type(GtkProgressBar),Pointer :: ProgressBar

  Call gtk_init

  ! Allocate memory for the data that is passed to the callbacks.
  Allocate(pdata)

  pdata%window => gtk_window_new(GTK_WINDOW_TOPLEVEL)
  Call gtk_window_set_resizable(GTK_WINDOW(pdata%window),TRUE)

  Call g_signal_connect(G_OBJECT(pdata%window),"destroy", &
                        C_FunLoc(destroy_progress),C_Loc(pdata))
  Call gtk_window_set_title(GTK_WINDOW(pdata%window),"GtkProgressBar")
  Call gtk_container_set_border_width(GTK_CONTAINER(pdata%window),0)

  vbox => gtk_vbox_new(FALSE,5)
  Call gtk_container_set_border_width(GTK_CONTAINER(vbox),10)
  Call gtk_container_add(GTK_CONTAINER(pdata%window),vbox)
  Call gtk_widget_show(vbox)

  ! Create a centreing alignment object.
  align => gtk_alignment_new(0.5,0.5,0.0,0.0)
  Call gtk_box_pack_start(GTK_BOX(vbox),align,FALSE,FALSE,5)
  Call gtk_widget_show(align)

  ! Create the GtkProgressBar.
  pdata%pbar => gtk_progress_bar_new()
  pdata%activity_mode = FALSE
  Call C_F_Pointer(C_Loc(pdata%pbar),ProgressBar)

  Call gtk_container_add(GTK_CONTAINER(align),pdata%pbar)
  Call gtk_widget_show(pdata%pbar)

  ! Add a timer callback to update the value of the progress bar.
  pdata%timer = g_timeout_add(100,C_FunLoc(progress_timeout),C_Loc(pdata))

  separator => gtk_hseparator_new()
  Call gtk_box_pack_start(GTK_BOX(vbox),separator,FALSE,FALSE,0)
  Call gtk_widget_show(separator)

  table => gtk_table_new(rows=2,columns=3,homogeneous=FALSE)
  Call gtk_box_pack_start(GTK_BOX(vbox),table,FALSE,TRUE,0)
  Call gtk_widget_show(table)

  ! Add a check button to select displaying of the trough text.
  check => gtk_check_button_new_with_label("Show text")
  Call gtk_table_attach(GTK_TABLE(table),check,0,1,0,1, &
                        Ior(GTK_EXPAND,GTK_FILL),Ior(GTK_EXPAND,GTK_FILL),5,5)
  Call g_signal_connect(G_OBJECT(check),"clicked", &
                        C_FunLoc(toggle_show_text),C_Loc(pdata))
  Call gtk_widget_show(check)

  ! Add a check button to toggle activity mode.
  check => gtk_check_button_new_with_label("Activity mode")
  Call gtk_table_attach(GTK_TABLE(table),check,0,1,1,2, &
                        Ior(GTK_EXPAND,GTK_FILL),Ior(GTK_EXPAND,GTK_FILL),5,5)
  Call g_signal_connect(G_OBJECT(check),"clicked", &
                        C_FunLoc(toggle_activity_mode),C_Loc(pdata))
  Call gtk_widget_show(check)

  ! Add a check button to toggle orientation.
  check => gtk_check_button_new_with_label("Right to Left")
  Call gtk_table_attach(GTK_TABLE(table),check,0,1,2,3, &
                        Ior(GTK_EXPAND,GTK_FILL),Ior(GTK_EXPAND,GTK_FILL),5,5)
  Call g_signal_connect(G_OBJECT(check),"clicked", &
                        C_FunLoc(toggle_orientation),C_Loc(pdata))
  Call gtk_widget_show(check)

  ! Add a button to exit the program.
  button => gtk_button_new_with_label("close")
  Call g_signal_connect_swapped(G_OBJECT(button),"clicked", &
                                C_FunLoc(gtk_widget_destroy), &
                                C_Loc(pdata%window))
  Call gtk_box_pack_start(GTK_BOX(vbox),button,FALSE,FALSE,0)

  ! This makes it so the button is the default.
  Call GTK_WIDGET_SET_FLAGS(button,GTK_CAN_DEFAULT)

  ! This grabs this button to be the default button.
  ! Simply hitting the "Enter" key will cause this button to activate.
  Call gtk_widget_grab_default(button)
  Call gtk_widget_show(button)

  Call gtk_widget_show(pdata%window)

  Call gtk_main
End Program

<<< Previous | Home | Next >>>
The Tooltips Object | Up | Dialogues


Dialogues

The Dialog widget is very simple, and is actually just a window with a few things pre-packed into it for you. The structure for a Dialog is:

Type,Bind(C) :: GtkDialog
  Type(GtkWindow) :: window
  Type(C_Ptr) :: vbox,action_area,separator
End Type

So you see, it simply creates a window, and then packs a vbox into the top, which contains a separator and then an hbox called the “action_area”.

The Dialog widget can be used for pop-up messages to the user, and other similar tasks. There are two functions to create a new Dialog.

Function gtk_dialog_new() Result(r)
  Type(GtkWidget),Pointer :: r

Function gtk_dialog_new_with_buttons(title,parent,flags,first_button_text,op1, &
                                     op2,op3,op4,op5,op6,op7) Result(res)
  Character(*),Intent(In) :: title
  Type(GtkWindow),Pointer :: parent
  Integer(GtkDialogFlags),Intent(In) :: flags
  Character(*),Intent(In) :: first_button_text
  Character(*),Optional,Intent(In) :: op2,op4,op6
  Integer,Optional,Intent(In) :: op1,op3,op5,op7
  Type(GtkWidget),Pointer :: res

The first function will create an empty dialogue, and it is now up to you to use it. You could pack a button in the action_area by doing something like this:

    Type(GtkDialog),Pointer :: dlg
    button => ...
    dlg => GTK_DIALOG(window)
    Call gtk_box_pack_start(GTK_BOX(dlg%action_area),button,TRUE,TRUE,0)
    Call gtk_widget_show(button)

And you could add to the vbox area by packing, for instance, a label in it, try something like this:

  Type(GtkDialog),Pointer :: dlg
  ...
  label => gtk_label_new("Dialogs are groovy")
  dlg => GTK_DIALOG(window)
  Call gtk_box_pack_start(GTK_BOX(dlg%vbox),label,TRUE,TRUE,0)
  Call gtk_widget_show(label)

As an example in using the dialogue box, you could put two buttons in the action_area, a Cancel button and an Ok button, and a label in the vbox area, asking the user a question or giving an error etc.. Then you could attach a different signal to each of the buttons and perform the operation the user selects.

If the simple functionality provided by the default vertical and horizontal boxes in the two areas doesn't give you enough control for your application, then you can simply pack another layout widget into the boxes provided. For example, you could pack a table into the vertical box.

The more complicated gtk_dialog_new_with_buttons variant lets you set one or more of the following flags:

GTK_DIALOG_MODAL
makes the dialog modal;
GTK_DIALOG_DESTROY_WITH_PARENT
ensures that the dialogue window is destroyed together with the specified parent;
GTK_DIALOG_NO_SEPARATOR
omits the separator between the vbox and the action_area.

<<< Previous | Home | Next >>>
Progress Bars | Up | Rulers


Rulers

Ruler widgets are used to indicate the location of the mouse pointer in a given window. A window can have a vertical ruler spanning across the height and a horizontal ruler spanning down the width. A small triangular indicator on the ruler shows the exact location of the pointer relative to the ruler.

A ruler must first be created. Horizontal and vertical rulers are created using

Function gtk_hruler_new() Result(r) ! A horizontal ruler.
    Type(GtkWidget),Pointer :: r

Function gtk_vruler_new() Result(r) ! A vertical ruler.
    Type(GtkWidget),Pointer :: r

Once a ruler is created, we can define the unit of measurement. Units of measure for rulers can be GTK_PIXELS, GTK_INCHES or GTK_CENTIMETERS. This is set using

Subroutine gtk_ruler_set_metric(ruler,metric)
    Type(GtkRuler),Pointer :: ruler
    Integer(GtkMetricType) :: metric

The default measure is GTK_PIXELS.

  Call gtk_ruler_set_metric(GTK_RULER(ruler),GTK_PIXELS)

Other important characteristics of a ruler are how to mark the units of scale and where the position indicator is initially placed. These are set for a ruler using

Subroutine gtk_ruler_set_range(ruler,lower,upper,position,max_size)
  Type(GtkRuler),Pointer :: ruler
  Double Precision :: lower,upper,position,max_size

The lower and upper arguments define the extent of the ruler, and max_size is the largest possible number that will be displayed. Position defines the initial position of the pointer indicator within the ruler.

A vertical ruler can span an 800 pixel wide window thus

    Call gtk_ruler_set_range(GTK_RULER(vruler),0.0d0,800.0d0,0.0d0,800.0d0)

The markings displayed on the ruler will be from 0 to 800, with a number for every 100 pixels. If instead we wanted the ruler to range from 7 to 16, we would code

    Call gtk_ruler_set_range(GTK_RULER(vruler),7.0d0,16.0d0,0.0d0,20.0d0)

The indicator on the ruler is a small triangular mark that indicates the position of the pointer relative to the ruler. If the ruler is used to follow the mouse pointer, the motion_notify_event signal should be connected to the motion_notify_event method of the ruler. To follow all mouse movements within a window area, we would use

  ! Get the Widget's class and from that its "motion_notify_event" handler.
  Type(C_FunPtr) Function get_motion_event_handler(widget)
    Type(GtkWidget) widget
    Type(GtkWidgetClass),Pointer :: class
    Call C_F_Pointer(GTK_WIDGET_GET_CLASS(widget),class)
    get_motion_event_handler = class%motion_notify_event
  End Function
  ...
  Call g_signal_connect_swapped(G_OBJECT(area),'motion_notify_event', &
                                get_motion_event_handler(ruler), &
                                G_OBJECT(ruler));

The following example creates a drawing area with a horizontal ruler above it and a vertical ruler to the left of it. The size of the drawing area is 600 pixels wide by 400 pixels high. The horizontal ruler spans from 7 to 13 with a mark every 100 pixels, while the vertical ruler spans from 0 to 400 with a mark every 100 pixels. Placement of the drawing area and the rulers is done using a table.

Module myruler
  Use gtk

  Integer,Parameter,Public :: XSIZE = 600, YSIZE = 400

Contains

  ! Get the Widget's class and from that its "motion_notify_event" handler.
  Type(C_FunPtr) Function get_motion_event_handler(widget)
    Type(GtkWidget) widget
    Type(GtkWidgetClass),Pointer :: class
    Call C_F_Pointer(GTK_WIDGET_GET_CLASS(widget),class)
    get_motion_event_handler = class%motion_notify_event
  End Function

  ! This routine gets control when the close button is clicked.
  Integer(gboolean) Function close_application(widget,event,data)
    Type(GtkWidget) widget
    Type(GdkEvent) event
    Type(C_Ptr),Value :: data

    Call gtk_main_quit
    close_application = FALSE

  End Function

End Module

Program main
  Use myruler

  Type(GtkWidget),Pointer :: window,table,area,hrule,vrule

  ! Initialise GTK and create the main window.
  Call gtk_init

  window => gtk_window_new(GTK_WINDOW_TOPLEVEL)
  Call g_signal_connect(G_OBJECT(window),"delete_event", &
                        C_FunLoc(gtk_main_quit),C_Null_Ptr)
  Call gtk_container_set_border_width(GTK_CONTAINER(window),10)

  ! Create a table for placing the ruler and the drawing area.
  table => gtk_table_new(3,2,FALSE)
  Call gtk_container_add(GTK_CONTAINER(window),table)

  area => gtk_drawing_area_new()
  Call gtk_widget_set_size_request(area,XSIZE,YSIZE)
  Call gtk_table_attach(GTK_TABLE(table),area,1,2,1,2, &
                        Ior(GTK_EXPAND,GTK_FILL),GTK_FILL,0,0)
  Call gtk_widget_set_events(area,Ior(GDK_POINTER_MOTION_MASK, &
                                      GDK_POINTER_MOTION_HINT_MASK))

  ! The horizontal ruler goes on top.  As the mouse moves across the
  ! drawing area, a motion_notify_event is passed to the
  ! appropriate event handler for the ruler.
  hrule  => gtk_hruler_new()
  Call gtk_ruler_set_metric(GTK_RULER(hrule),GTK_PIXELS)
  Call gtk_ruler_set_range(GTK_RULER(hrule),7d0,13d0,0d0,20d0)
  Call g_signal_connect_swapped(G_OBJECT(area),"motion_notify_event", &
                                get_motion_event_handler(hrule), &
                                C_Loc(hrule))
  Call gtk_table_attach(GTK_TABLE(table),hrule,1,2,0,1, &
                        Ior(Ior(GTK_EXPAND,GTK_SHRINK),GTK_FILL), &
                        GTK_FILL,0,0)

  ! The vertical ruler goes on the left.  As the mouse moves across
  ! the drawing area, a motion_notify_event is passed to the
  ! appropriate event handler for the ruler.
  vrule  => gtk_vruler_new()
  Call gtk_ruler_set_metric(GTK_RULER(vrule),GTK_PIXELS)
  Call gtk_ruler_set_range(GTK_RULER (vrule),0d0,Dble(YSIZE),10d0,Dble(YSIZE))
  Call g_signal_connect_swapped(G_OBJECT(area),"motion_notify_event", &
                                get_motion_event_handler(vrule), &
                                C_Loc(vrule))
  Call gtk_table_attach(GTK_TABLE(table),vrule,0,1,1,2,GTK_FILL, &
                                  Ior(Ior(GTK_EXPAND,GTK_SHRINK),GTK_FILL),0,0)

  ! Now show everything.
  Call gtk_widget_show(area)
  Call gtk_widget_show(hrule)
  Call gtk_widget_show(vrule)
  Call gtk_widget_show(table)
  Call gtk_widget_show(window)

  Call gtk_main

End Program

<<< Previous | Home | Next >>>
Dialogues | Up | Statusbars


Statusbars

Statusbars are simple widgets used to display a text message. They keep a stack of the messages pushed onto them, so that popping the current message will re-display the previous text message.

In order to allow different parts of an application to use the same statusbar to display messages, the statusbar widget issues Context Identifiers which are used to identify different “users”. The message on top of the stack is the one displayed, no matter what context it is in. Messages are stacked in last-in-first-out order, not context identifier order.

A statusbar is created with a call to:

Function gtk_statusbar_new() Result(res)
  Type(GtkWidget),Pointer :: res

A new Context Identifier is requested using a call to the following function with a short textual description of the context:

Integer(guint) Function gtk_statusbar_get_context_id(statusbar,context_description)
  Type(GtkStatusbar),Pointer :: statusbar
  Character(*),Intent(In) :: context_description

There are three functions that can operate on statusbars:

Integer(guint) Function gtk_statusbar_push(statusbar,context_id,text)
  Type(GtkStatusbar),Pointer :: statusbar
  Integer(guint),Intent(In) :: context_id
  Character(*),Intent(In) :: text

Subroutine gtk_statusbar_pop(statusbar,context_id)
  Type(GtkStatusbar),Pointer :: statusbar
  Integer(guint),Intent(In) :: context_id

Subroutine gtk_statusbar_remove(statusbar,context_id,message_id)
  Type(GtkStatusbar),Pointer :: statusbar
  Integer(guint),Intent(In) :: context_id,message_id

The first, gtk_statusbar_push, is used to add a new message to the statusbar. It returns a Message Identifier, which can be passed later to the function gtk_statusbar_remove to remove the message with the given Message and Context Identifiers from the statusbar's stack.

The function gtk_statusbar_pop removes the message highest in the stack with the given Context Identifier.

In addition to messages, statusbars may also display a resize grip, which can be dragged with the mouse to resize the toplevel window containing the statusbar, similar to dragging the window frame. The following functions control the display of the resize grip.

Subroutine gtk_statusbar_set_has_resize_grip(statusbar,setting)
  Type(GtkStatusbar),Pointer :: statusbar
  Integer(gboolean),Intent(In) :: setting

Integer(gboolean) Function gtk_statusbar_get_has_resize_grip(statusbar)
  Type(GtkStatusbar),Pointer :: statusbar

The following example creates a statusbar and two buttons, one for pushing items onto the statusbar, and one for popping the last item back off.

Module statusbar_event
  Use gtk
  Use glib
  Implicit None

  Type(GtkWidget),Pointer :: status_bar

Contains

  Subroutine push_item(widget,data) Bind(C,Name='')
    Type(GtkWidget) widget
    Type(C_Ptr),Value :: data
    Integer,Save :: count = 1
    Character(len=128) :: buff
    Integer :: res

    Write (buff,*) 'Item ',count,C_Null_Char
    count = count + 1
    res = gtk_statusbar_push(GTK_STATUSBAR(status_bar), &
                             GPOINTER_TO_INT(data),buff)
  End Subroutine

  Subroutine pop_item(widget,data) Bind(C,Name='')
    Type(GtkWidget) widget
    Type(C_Ptr),Value :: data

    Call gtk_statusbar_pop(GTK_STATUSBAR(status_bar),GPOINTER_TO_INT(data))
  End Subroutine

  Integer(gboolean) Function exit_event(pwidget,pevent,user_data) &
  Bind(C,Name='')
    Type(C_Ptr),Value :: pwidget,pevent,user_data

    Call gtk_main_quit
    exit_event = FALSE
  End Function

End Module

Program simple
  Use statusbar_event
  Implicit None

  Type(GtkWidget),Pointer :: window,vbox,button
  Integer :: context_id

  Call gtk_init

  ! Create a new window.
  window => gtk_window_new(GTK_WINDOW_TOPLEVEL)
  Call gtk_widget_set_size_request(GTK_WIDGET(window),200,100)
  Call gtk_window_set_title(GTK_WINDOW(window),"GTK Statusbar Example")
  Call g_signal_connect(G_OBJECT(window),"delete_event", &
                        C_FunLoc(exit_event),C_Null_Ptr)

  vbox => gtk_vbox_new(FALSE,1)
  Call gtk_container_add(GTK_CONTAINER(window),vbox)
  Call gtk_widget_show(vbox)

  status_bar => gtk_statusbar_new()
  Call gtk_box_pack_start(GTK_BOX(vbox),status_bar,TRUE,TRUE,0)
  Call gtk_widget_show(status_bar)

  context_id = gtk_statusbar_get_context_id(GTK_STATUSBAR(status_bar), &
                                            "Statusbar example")

  button => gtk_button_new_with_label("push item")
  Call g_signal_connect(G_OBJECT(button),"clicked", &
                        C_FunLoc(push_item),GINT_TO_POINTER(context_id))

  Call gtk_box_pack_start(GTK_BOX(vbox),button,TRUE,TRUE,2)
  Call gtk_widget_show(button)

  button => gtk_button_new_with_label("pop last item")
  Call g_signal_connect(G_OBJECT(button),"clicked", &
                        C_FunLoc(pop_item),GINT_TO_POINTER(context_id))
  Call gtk_box_pack_start(GTK_BOX(vbox),button,TRUE,TRUE,2)
  Call gtk_widget_show(button)

  ! Always display the window as the last step so it all splashes on
  ! the screen at once.
  Call gtk_widget_show(window)

  Call gtk_main
End Program

<<< Previous | Home | Next >>>
Rulers | Up | Text Entries


Text Entries

The Entry widget allows text to be typed and displayed in a single line text box. The text may be set with function calls that allow new text to replace, prepend or append the current contents of the Entry widget.

Create a new Entry widget with the following function.

Function gtk_entry_new() Result(r)
  Type(GtkWidget),Pointer :: r

The next procedure alters the text which is currently within the Entry widget.

Subroutine gtk_entry_set_text(entry,text)
  Type(GtkEntry),Pointer :: entry
  Character(*),Intent(In),Target :: text
or Character(*),Intent(In) :: text(:)
or Type(C_Ptr),Value :: text

The procedure gtk_entry_set_text sets the contents of the Entry widget, replacing the current contents. Due to an unfortunate mistake in an earlier version of this library, text cannot safely be a length=1 scalar; it can be an array (in which case all the array elements are concatenated together) or a Type(C_Ptr) pointer to a null-terminated C string. Note that the class Entry implements the Editable interface (yes, gobject supports Java-like interfaces) which contains some more functions for manipulating the contents.

The contents of the Entry can be retrieved by using a call to the following function. This is useful in the callback functions described below.

Function gtk_entry_get_text(entry) Result(r)
  Type(GtkEntry),Pointer :: entry
  Character,Pointer :: r(:)

The value returned by this function is used internally, and must not be freed using the Deallocate statement or the C functions free or g_free.

If we don't want the contents of the Entry to be changed by someone typing into it, we can change its editable state.

Subroutine gtk_editable_set_editable(editable,is_editable)
  Type(GtkEditable),Pointer :: editable
  Integer(gboolean),Intent(In) :: is_editable

The function above allows us to toggle the editable state of the Entry widget by passing in a TRUE or FALSE value for the is_editable argument.

If we are using the Entry where we don't want the text entered to be visible, for example when a password is being entered, we can use the following function, which also takes a boolean flag.

Subroutine gtk_entry_set_visibility(entry,visible )
  Type(GtkEntry),Pointer :: entry
  Integer(gboolean),Intent(In) :: visible

A region of the text may be set as selected by using the following procedure. This would most often be used after setting some default text in an Entry, making it easy for the user to remove it.

Subroutine gtk_editable_select_region(editable,start,end)
  Type(GtkEditable),Pointer :: editable
  Integer(gint),Intent(In) :: start,end

If we want to catch when the user has entered text, we can connect to the activate or changed signal. Activate is raised when the user hits the enter key within the Entry widget. Changed is raised when the text changes at all, e.g., for every character entered or removed.

The following code is an example of using an Entry widget.

Module mytext
  Use gtk
  Implicit None

Contains

  Subroutine enter_callback(widget,entry) Bind(C,Name='')
    Type(GtkWidget) :: widget
    Type(C_Ptr),Value :: entry
    Character,Pointer :: entry_text(:)

    entry_text => gtk_entry_get_text(GTK_ENTRY(entry))
    Print *,"Entry contents: ",entry_text
  End Subroutine

  Subroutine entry_toggle_editable(widget,entry) Bind(C,Name='')
    Type(C_Ptr),Value :: widget,entry
    Integer :: active

    active = gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(widget))
    Call gtk_editable_set_editable(GTK_EDITABLE(entry),active)
  End Subroutine

  Subroutine entry_toggle_visibility(widget,entry) Bind(C,Name='')
    Type(C_Ptr),Value :: widget,entry
    Integer :: active

    active = gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(widget))
    Call gtk_entry_set_visibility(GTK_ENTRY(entry),active)
  End Subroutine
End Module

Program main
  Use mytext

  Type(GtkWidget),Pointer :: window,vbox,hbox,entry,button,check
  Type(GtkEntry),Pointer :: entryobj
  Integer :: tmp_pos

  Call gtk_init

  window => gtk_window_new(GTK_WINDOW_TOPLEVEL)
  Call gtk_widget_set_size_request(window,200,100)
  Call gtk_window_set_title(GTK_WINDOW(window),"GTK Entry")
  Call g_signal_connect(G_OBJECT(window),"destroy", &
                        C_FunLoc(gtk_main_quit),C_Null_Ptr)
  Call g_signal_connect_swapped(G_OBJECT(window),"delete_event", &
                                C_FunLoc(gtk_widget_destroy),C_Loc(window))

  vbox => gtk_vbox_new(FALSE,0)
  Call gtk_container_add(GTK_CONTAINER(window),vbox)
  Call gtk_widget_show(vbox)

  entry => gtk_entry_new()
  Call gtk_entry_set_max_length(GTK_ENTRY(Entry),50)
  Call g_signal_connect(G_OBJECT(entry),"activate", &
                        C_FunLoc(enter_callback),C_Loc(entry))
  Call gtk_entry_set_text(GTK_ENTRY(entry),"hello")

  entryobj => GTK_ENTRY(Entry)
  tmp_pos = entryobj%text_length
  Call gtk_editable_insert_text(GTK_EDITABLE(entry)," world",-1, &
                                tmp_pos)
  tmp_pos = entryobj%text_length
  Call gtk_editable_select_region(GTK_EDITABLE(entry),0,tmp_pos)

  Call gtk_box_pack_start(GTK_BOX(vbox),entry,TRUE,TRUE,0)
  Call gtk_widget_show(entry)

  hbox => gtk_hbox_new(FALSE,0)
  Call gtk_container_add(GTK_CONTAINER(vbox),hbox)
  Call gtk_widget_show(hbox)

  check => gtk_check_button_new_with_label("Editable")
  Call gtk_box_pack_start(GTK_BOX(hbox),check,TRUE,TRUE,0)
  Call g_signal_connect(G_OBJECT(check),"toggled", &
                        C_FunLoc(entry_toggle_editable),C_Loc(entry))
  Call gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(check),TRUE)
  Call gtk_widget_show(check)

  check => gtk_check_button_new_with_label("Visible")
  Call gtk_box_pack_start(GTK_BOX(hbox),check,TRUE,TRUE,0)
  Call g_signal_connect(G_OBJECT(check),"toggled", &
                        C_FunLoc(entry_toggle_visibility),C_Loc(entry))
  Call gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(check),TRUE)
  Call gtk_widget_show(check)
  button => gtk_button_new_from_stock(GTK_STOCK_CLOSE)
  Call g_signal_connect_swapped(G_OBJECT(button),"clicked", &
                                C_FunLoc(gtk_widget_destroy),C_Loc(window))
  Call gtk_box_pack_start(GTK_BOX(vbox),button,TRUE,TRUE,0)
  Call GTK_WIDGET_SET_FLAGS(button,GTK_CAN_DEFAULT)
  Call gtk_widget_grab_default(button)
  Call gtk_widget_show(button)

  Call gtk_widget_show(window)

  Call gtk_main
End Program

<<< Previous | Home | Next >>>
Statusbars | Up | Spin Buttons


Spin Buttons

The Spin Button widget is generally used to allow the user to select a value from a range of numeric values. It consists of a text entry box with up and down arrow buttons attached to the side. Selecting one of the buttons causes the value to “spin” up and down the range of possible values. The entry box may also be edited directly to enter a specific value.

The Spin Button allows the value to have zero or a number of decimal places and to be incremented/decremented in configurable steps. The action of holding down one of the buttons optionally results in an acceleration of change in the value according to how long it is depressed.

The Spin Button uses an Adjustment object to hold information about the range of values that the spin button can take. This makes for a powerful Spin Button widget.

Recall that an adjustment widget is created with the following function, which illustrates the information that it holds:

Function gtk_adjustment_new(value,lower,upper,step_increment,page_increment, &
                            page_size) Result(res)
  Real(gdouble),Intent(In) :: value,lower,upper,step_increment, &
                              page_increment,page_size
  Type(GtkObject),Pointer :: res

These attributes of an Adjustment are used by the Spin Button in the following way:

  • value: initial value for the Spin Button;
  • lower: lower range value;
  • upper: upper range value;
  • step_increment: value to increment/decrement when pressing mouse button 1 on a button;
  • page_increment: value to increment/decrement when pressing mouse button 2 on a button;
  • page_size: unused.

Additionally, mouse button 3 can be used to jump directly to the upper or lower values when used to select one of the buttons. Lets look at how to create a Spin Button:

Function gtk_spin_button_new(adjustment,climb_rate,digits) Result(res)
  Type(GtkAdjustment),Pointer :: adjustment
  Real(gdouble),Intent(In) :: climb_rate
  Integer(guint),Intent(In) :: digits
  Type(GtkWidget),Pointer :: res

The climb_rate argument take a value between 0.0 and 1.0 and indicates the amount of acceleration that the Spin Button has. The digits argument specifies the number of decimal places to which the value will be displayed.

A Spin Button can be reconfigured after creation using the following procedure:

Subroutine gtk_spin_button_configure(spin_button,adjustment,climb_rate,digits)
  Type(GtkSpinButton),Pointer :: spin_button
  Type(GtkAdjustment),Pointer :: adjustment
  Double Precision,Intent(In) :: climb_rate
  Integer(guint),Intent(In) :: digits

The spin_button argument specifies the Spin Button widget that is to be reconfigured. The other arguments are as specified above.

The adjustment can be set and retrieved independently using the following two procedures:

Subroutine gtk_spin_button_set_adjustment(spin_button,adjustment)
  Type(GtkSpinButton),Pointer :: spin_button
  type(GtkAdjustment),Pointer :: adjustment

Function gtk_spin_button_get_adjustment(spin_button) Result(res)
  Type(GtkSpinButton),Pointer :: spin_button
  Type(GtkAdjustment),Pointer :: res

The number of decimal places can also be altered using:

Subroutine gtk_spin_button_set_digits(spin_button,digits)
  Type(GtkSpinButton),Pointer :: spin_button
  Integer(guint),Intent(In) :: digits

The value that a Spin Button is currently displaying can be changed using the following procedure:

Subroutine gtk_spin_button_set_value(spin_button,value)
  Type(GtkSpinButton),Pointer :: spin_button
  Double Precision :: value

The current value of a Spin Button can be retrieved as either a floating point or integer value with the following functions:

Real(gdouble) Function gtk_spin_button_get_value(spin_button)
  Type(GtkSpinButton),Pointer :: spin_button

Integer(gint) Function gtk_spin_button_get_value_as_int(spin_button)
  Type(GtkSpinButton),Pointer :: spin_button

If you want to alter the value of a Spin Button relative to its current value, then the following procedure can be used:

Subroutine gtk_spin_button_spin(spin_button,direction,increment)
  Type(GtkSpinButton),Pointer :: spin_button
  Integer(GtkSpinType),Intent(In) :: direction
  Real(gdouble),Intent(In) :: increment

The direction parameter can take one of the following values:

  GTK_SPIN_STEP_FORWARD
  GTK_SPIN_STEP_BACKWARD
  GTK_SPIN_PAGE_FORWARD
  GTK_SPIN_PAGE_BACKWARD
  GTK_SPIN_HOME
  GTK_SPIN_END
  GTK_SPIN_USER_DEFINED

This function packs in quite a bit of functionality, which I will attempt to explain clearly. Many of these settings use values from the Adjustment object that is associated with a Spin Button.

GTK_SPIN_STEP_FORWARD and GTK_SPIN_STEP_BACKWARD change the value of the Spin Button by the amount specified by increment, unless increment is equal to 0, in which case the value is changed by the value of step_increment in theAdjustment.

GTK_SPIN_PAGE_FORWARD and GTK_SPIN_PAGE_BACKWARD simply alter the value of the Spin Button by increment.

GTK_SPIN_HOME sets the value of the Spin Button to the bottom of the Adjustments range.

GTK_SPIN_END sets the value of the Spin Button to the top of the Adjustments range.

GTK_SPIN_USER_DEFINED simply alters the value of the Spin Button by the specified amount.

We move away from procedures for setting and retrieving the range attributes of the Spin Button now, and move onto procedures that affect the appearance and behaviour of the Spin Button widget itself.

The first of these procedures is used to constrain the text box of the Spin Button such that it may only contain a numeric value. This prevents a user from typing anything other than numeric values into the text box of a Spin Button:

Subroutine gtk_spin_button_set_numeric(spin_button,numeric)
  Type(GtkSpinButton),Pointer :: spin_button
  Integer(gboolean),Intent(In) :: numeric

You can set whether a Spin Button will wrap around between the upper and lower range values with the following procedure:

Subroutine gtk_spin_button_set_wrap(spin_button,wrap)
  Type(GtkSpinButton),Pointer :: spin_button
  Integer(gboolean),Intent(In) :: wrap

You can set a Spin Button to round the value to the nearest step_increment, which is set within the Adjustment object used with the Spin Button. This is accomplished with the following procedure:

Subroutine gtk_spin_button_set_snap_to_ticks(spin_button,snap_to_ticks)
  Type(GtkSpinButton),Pointer :: spin_button
  Integer(gboolean),Intent(In) :: snap_to_ticks

The update policy of a Spin Button can be changed with the following procedure:

Subroutine gtk_spin_button_set_update_policy(spin_button,policy)
  Type(GtkSpinButton),Pointer :: spin_button
  Integer(GtkSpinButtonUpdatePolicy),Intent(In) :: policy

The possible values of policy are either GTK_UPDATE_ALWAYS or GTK_UPDATE_IF_VALID.

These policies affect the behavior of a Spin Button when parsing inserted text and syncing its value with the values of the Adjustment.

In the case of GTK_UPDATE_IF_VALID the Spin Button value only gets changed if the text input is a numeric value that is within the range specified by the Adjustment. Otherwise the text is reset to the current value.

In case of GTK_UPDATE_ALWAYS we ignore errors while converting text into a numeric value.

Finally, you can explicitly request that a Spin Button update itself:

Subroutine gtk_spin_button_update(spin_button)
  Type(GtkSpinButton),Pointer :: spin_button

It's example time again.

Module myspin
  Use gtk
  Implicit None

  Type(GtkWidget),Pointer :: spinner1 => Null()

Contains

  Subroutine toggle_snap(widget,spin) Bind(C)
    Type(C_Ptr),Value :: widget,spin
    Integer :: active

    active = gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(widget))
    Call gtk_spin_button_set_snap_to_ticks(GTK_SPIN_BUTTON (spin),active)

  End Subroutine

  Subroutine toggle_numeric(widget,spin) Bind(C)
    Type(C_Ptr),Value :: widget,spin
    Integer :: active

    active = gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(widget))
    Call gtk_spin_button_set_numeric(GTK_SPIN_BUTTON(spin),active)

  End Subroutine

  Subroutine change_digits(widget,spin) Bind(C)
    Type(C_Ptr),Value :: widget,spin
    Integer digits

    digits = gtk_spin_button_get_value_as_int(GTK_SPIN_BUTTON(spin))
    Call gtk_spin_button_set_digits(GTK_SPIN_BUTTON(spinner1),digits)

  End Subroutine

  Subroutine get_value(widget,data) Bind(C)
    Type(C_Ptr),Value :: widget,data
    Character(32) :: buf,fmt
    Type(GtkLabel),Pointer :: label
    Type(C_Ptr) :: d
    Integer :: val
    Double Precision :: dval

    d = g_object_get_data(G_OBJECT(widget),"user_data")
    label => GTK_LABEL(d)
    If (GPOINTER_TO_INT(data)==1) Then
      val = gtk_spin_button_get_value_as_int(GTK_SPIN_BUTTON(spinner1))
      Write (buf,'(I0)') val
    Else
      val = gtk_spin_button_get_digits(GTK_SPIN_BUTTON(spinner1))
      dval = gtk_spin_button_get_value(GTK_SPIN_BUTTON(spinner1))
      If (Log10(Abs(dval)+0.1d0)+1+val>28) Then
        Write (fmt,'("(ES",I0,".",I0,"E3)")') 28,28-val-4
      Else
        Write (fmt,'("(F0.",I0,")")') val
      End If
      Write (buf,fmt) dval
    End If
    Call gtk_label_set_text(label,buf(:Len_Trim(buf)))
  End Subroutine

End Module

Program main
  Use myspin

  Type(GtkWidget),Pointer :: window,main_vbox,vbox,vbox2,hbox,frame, &
                             spinner2,spinner,button,label,val_label
  Type(GtkObject),Pointer :: adj

  ! Initialise GTK
  Call gtk_init

  window => gtk_window_new(GTK_WINDOW_TOPLEVEL)
  Call g_signal_connect(G_OBJECT(window),"destroy", &
                        C_FunLoc(gtk_main_quit),C_Null_Ptr)
  Call gtk_window_set_title(GTK_WINDOW(window),"Spin Button")

  main_vbox => gtk_vbox_new(FALSE,5)
  Call gtk_container_set_border_width(GTK_CONTAINER(main_vbox),10)
  Call gtk_container_add(GTK_CONTAINER(window),main_vbox)

  frame => gtk_frame_new("Not accelerated")
  Call gtk_box_pack_start(GTK_BOX(main_vbox),frame,TRUE,TRUE,0)

  vbox => gtk_vbox_new(FALSE,0)
  Call gtk_container_set_border_width(GTK_CONTAINER(vbox),5)
  Call gtk_container_add(GTK_CONTAINER(frame),vbox)

  ! Day, month, year spinners
  hbox => gtk_hbox_new(FALSE,0)
  Call gtk_box_pack_start(GTK_BOX(vbox),hbox,TRUE,TRUE,5)

  vbox2 => gtk_vbox_new(FALSE,0)
  Call gtk_box_pack_start(GTK_BOX(hbox),vbox2,TRUE,TRUE,5)

  label => gtk_label_new("Day :")
  Call gtk_misc_set_alignment(GTK_MISC(C_Loc(label)),0.0,0.5)
  Call gtk_box_pack_start(GTK_BOX(vbox2),label,FALSE,TRUE,0)

  adj => gtk_adjustment_new(1.0d0,1.0d0,31.0d0,1.0d0,5.0d0,0.0d0)
  spinner => gtk_spin_button_new(GTK_ADJUSTMENT(C_Loc(adj)),0d0,0)
  Call gtk_spin_button_set_wrap(GTK_SPIN_BUTTON(spinner),TRUE)
  Call gtk_box_pack_start(GTK_BOX(vbox2),spinner,FALSE,TRUE,0)

  vbox2 => gtk_vbox_new(FALSE,0)
  Call gtk_box_pack_start(GTK_BOX(hbox),vbox2,TRUE,TRUE,5)

  label => gtk_label_new("Month :")
  Call gtk_misc_set_alignment(GTK_MISC(C_Loc(label)),0.0,0.5)
  Call gtk_box_pack_start(GTK_BOX(vbox2),label,FALSE,TRUE,0)

  adj     => gtk_adjustment_new(1.0d0,1.0d0,12.0d0,1.0d0,5.0d0,0.0d0)
  spinner => gtk_spin_button_new(GTK_ADJUSTMENT(c_loc(adj)),0d0,0)
  Call gtk_spin_button_set_wrap(GTK_SPIN_BUTTON(spinner),TRUE)
  Call gtk_box_pack_start(GTK_BOX(vbox2),spinner,FALSE,TRUE,0)

  vbox2 => gtk_vbox_new(FALSE,0)
  Call gtk_box_pack_start(GTK_BOX(hbox),vbox2,TRUE,TRUE,5)

  label => gtk_label_new("Year :")
  Call gtk_misc_set_alignment(GTK_MISC(C_Loc(label)),0.0,0.5)
  Call gtk_box_pack_start(GTK_BOX(vbox2),label,FALSE,TRUE,0)

  adj     => gtk_adjustment_new(1998.0d0,0.0d0,2100.0d0,1.0d0,100.0d0,0.0d0)
  spinner => gtk_spin_button_new(GTK_ADJUSTMENT(C_Loc(adj)),0d0,0)
  Call gtk_spin_button_set_wrap(GTK_SPIN_BUTTON(spinner),FALSE)
  Call gtk_widget_set_size_request(spinner,55,-1)
  Call gtk_box_pack_start(GTK_BOX(vbox2),spinner,FALSE,TRUE,0)

  frame => gtk_frame_new("Accelerated")
  Call gtk_box_pack_start(GTK_BOX(main_vbox),frame,TRUE,TRUE,0)

  vbox => gtk_vbox_new(FALSE,0)
  Call gtk_container_set_border_width(GTK_CONTAINER(vbox),5)
  Call gtk_container_add(GTK_CONTAINER(frame),vbox)

  hbox => gtk_hbox_new(FALSE,0)
  Call gtk_box_pack_start(GTK_BOX(vbox),hbox,FALSE,TRUE,5)

  vbox2 => gtk_vbox_new(FALSE,0)
  Call gtk_box_pack_start(GTK_BOX(hbox),vbox2,TRUE,TRUE,5)
  label => gtk_label_new("Value :")
  Call gtk_misc_set_alignment(GTK_MISC(C_Loc(label)),0.0,0.5)
  Call gtk_box_pack_start(GTK_BOX(vbox2),label,FALSE,TRUE,0)

  adj => gtk_adjustment_new(0.0d0,-10000.0d0,10000.0d0,0.5d0,100.0d0,0.0d0)
  spinner1 => gtk_spin_button_new(GTK_ADJUSTMENT(C_Loc(adj)),1.0d0,2)

  Call gtk_spin_button_set_wrap(GTK_SPIN_BUTTON(spinner1),TRUE)
  Call gtk_widget_set_size_request(spinner1,100,-1)
  Call gtk_box_pack_start(GTK_BOX(vbox2),spinner1,FALSE,TRUE,0)

  vbox2 => gtk_vbox_new(FALSE,0)
  Call gtk_box_pack_start(GTK_BOX(hbox),vbox2,TRUE,TRUE,5)

  label => gtk_label_new("Digits :")
  Call gtk_misc_set_alignment(GTK_MISC(C_Loc(label)),0.0,0.5)
  Call gtk_box_pack_start(GTK_BOX(vbox2),label,FALSE,TRUE,0)

  adj      => gtk_adjustment_new(2d0,1d0,5d0,1d0,1d0,0d0)
  spinner2 => gtk_spin_button_new(GTK_ADJUSTMENT(c_loc(adj)),0.0d0, 0)
  Call gtk_spin_button_set_wrap(GTK_SPIN_BUTTON(spinner2),TRUE)
  Call g_signal_connect(G_OBJECT(adj),"value_changed", &
                        C_FunLoc(change_digits),C_Loc(spinner2))
  Call gtk_box_pack_start(GTK_BOX(vbox2),spinner2,FALSE,TRUE,0)

  hbox => gtk_hbox_new(FALSE,0)
  call gtk_box_pack_start(GTK_BOX(vbox),hbox,FALSE,TRUE,5)

  button => gtk_check_button_new_with_label("Snap to 0.5-ticks")
  Call g_signal_connect(G_OBJECT(button),"clicked", &
                        C_FunLoc(toggle_snap),C_Loc(spinner1))
  Call gtk_box_pack_start(GTK_BOX(vbox),button,TRUE,TRUE,0)
  Call gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(button),TRUE)

  button => gtk_check_button_new_with_label("Numeric only input mode")
  Call g_signal_connect(G_OBJECT(button),"clicked", &
                        C_FunLoc(toggle_numeric),C_Loc(spinner1))
  Call gtk_box_pack_start(GTK_BOX(vbox),button,TRUE,TRUE,0)
  Call gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(button),TRUE)

  val_label => gtk_label_new("")

  hbox => gtk_hbox_new(FALSE,0)
  Call gtk_box_pack_start(GTK_BOX(vbox),hbox,FALSE,TRUE,5)
  button => gtk_button_new_with_label("Value as Int")
  Call g_object_set_data(G_OBJECT(button),"user_data",C_Loc(val_label))

  Call g_signal_connect(G_OBJECT(button),"clicked", &
                        C_FunLoc(get_value),GINT_TO_POINTER(1))
  Call gtk_box_pack_start(GTK_BOX(hbox),button,TRUE,TRUE,5)

  button => gtk_button_new_with_label("Value as Float")
  Call g_object_set_data(G_OBJECT(button),"user_data", &
                         C_Loc(val_label))
  Call g_signal_connect(G_OBJECT(button),"clicked", &
                        C_FunLoc(get_value),GINT_TO_POINTER(2))
  Call gtk_box_pack_start(GTK_BOX(hbox),button,TRUE,TRUE,5)

  Call gtk_box_pack_start(GTK_BOX(vbox),val_label,TRUE,TRUE,0)
  Call gtk_label_set_text(GTK_LABEL(C_Loc(val_label)),"0")

  hbox => gtk_hbox_new(FALSE,0)
  Call gtk_box_pack_start(GTK_BOX(main_vbox),hbox,FALSE,TRUE,0)

  button => gtk_button_new_with_label("Close")
  Call g_signal_connect_swapped(G_OBJECT(button),"clicked", &
                                C_FunLoc(gtk_widget_destroy),C_Loc(window))
  Call gtk_box_pack_start(GTK_BOX(hbox),button,TRUE,TRUE,5)

  Call gtk_widget_show_all(window)

  ! Enter the event loop.
  Call gtk_main

End Program

<<< Previous | Home | Next >>>
Text Entries | Up | Combo Box


Combo Box

The combo box is another fairly simple widget that is really just a collection of other widgets. From the user's point of view, the widget consists of a text entry box and a pull down menu from which the user can select one of a set of predefined entries. Alternatively, the user can type a different option directly into the text box.

The following extract from the structure that defines a Combo Box identifies several of the components:

Type,Bind(C) :: GtkCombo
  Type(GtkHBox) :: hbox
  Type(C_Ptr) :: entry,button,popup,popwin,list ! All GtkWidget*.
  ...

As you can see, the Combo Box has two principal parts that you really care about: an entry and a list.

First off, to create a combo box, use:

Function gtk_combo_new() Result(res)
  Type(GtkWidget),Pointer :: res

Now, if you want to set the string in the entry section of the combo box, this is done by manipulating the entry widget directly:

  Type(GtkCombo),Pointer :: combo
  ...
  combo => GTK_COMBO(combo)
  Call gtk_entry_set_text(GTK_ENTRY(combo%entry),"My String.")

To set the values in the popdown list, one uses the procedure:

Subroutine gtk_combo_set_popdown_strings(combo,strings)
  Type(GtkCombo),Pointer :: combo
  Type(GList),Pointer :: strings

Before you can do this, you have to assemble a GList of the strings that you want. GList is a linked list implementation that is part of GLib, a library supporting GTK. For the moment, the quick and dirty explanation is that you need to set up a GList pointer, nullify it, then append strings to it with
Function g_list_append(list,data) Result(res)
  Type(GList),Pointer :: list,res
  Type(C_Ptr),Value :: data

It is important that you nullify the initial GList pointer. The value returned from the g_list_append function must be used as the new pointer to the GList.

Here's a typical code segment for creating a set of options:

  Type(GList),Pointer :: glist

  Nullify(glist)

  glist => g_list_append(glist,"String 1")
  glist => g_list_append(glist,"String 2")
  glist => g_list_append(glist,"String 3")
  glist => g_list_append(glist,"String 4")

  Call gtk_combo_set_popdown_strings(GTK_COMBO(combo),glist)

  ! Can deallocate glist now, combo took a copy.

The combo widget makes a copy of the strings passed to it in the glist structure. As a result, you need to make sure you deallocate the memory used by the list if that is appropriate for your application.

At this point you have a working combo box that has been set up. There are a few aspects of its behavior that you can change. These are accomplished with the procedures:

Subroutine gtk_combo_set_use_arrows(combo,val)
  Type(GtkCombo),Pointer :: combo
  Integer(gboolean),Intent(In) :: val

Subroutine gtk_combo_set_use_arrows_always(combo,val)
  Type(GtkCombo),Pointer :: combo
  Integer(gboolean),Intent(In) :: val

Subroutine gtk_combo_set_case_sensitive(combo,val)
  Type(GtkCombo),Pointer :: combo
  Integer(gboolean),Intent(In) :: val

gtk_combo_set_use_arrows lets the user change the value in the entry using the up/down arrow keys. This doesn't bring up the list, but rather replaces the current text in the entry with the next list entry (up or down, as your key choice indicates). It does this by searching in the list for the item corresponding to the current value in the entry and selecting the previous/next item accordingly. Usually in an entry the arrow keys are used to change focus (you can do that anyway using TAB). Note that when the current item is the last of the list and you press arrow-down it changes the focus (the same applies with the first item and arrow-up).

If the current value in the entry is not in the list, then the function of gtk_combo_set_use_arrows is disabled.

gtk_combo_set_use_arrows_always similarly allows the use the the up/down arrow keys to cycle through the choices in the dropdown list, except that it wraps around the values in the list, completely disabling the use of the up and down arrow keys for changing focus.

gtk_combo_set_case_sensitive toggles whether or not GTK searches for entries in a case sensitive manner. This is used when the Combo widget is asked to find a value from the list using the current entry in the text box. This completion can be performed in either a case sensitive or insensitive manner, depending upon the use of this procedure. The Combo widget can also simply complete the current entry if the user presses the key combination MOD-1 and “Tab”. MOD-1 is often mapped to the “Alt” key. Note, however that some window managers also use this key combination, which will override its use within GTK.

Now that we have a combo box, tailored to look and act how we want it, all that remains is being able to get data from the combo box. This is relatively straightforward. The majority of the time, all you are going to care about getting data from is the entry. The entry is accessed simply by GTK_ENTRY (GTK_COMBO (combo)->entry). The two principal things that you are going to want to do with it are connect to the activate signal, which indicates that the user has pressed the Return or Enter key, and read the text. The first is accomplished using something like:

  Type(GtkCombo),Pointer :: combo
  ...
  combo => GTK_COMBO(combo)
  Call g_signal_connect(G_OBJECT(combo%entry),"activate", &
                        C_FunLoc(my_callback_function),C_Loc(my_data))

Getting the text at any arbitrary time is accomplished by simply using the entry function:

Function gtk_entry_get_text(entry) Result(res)
  Type(GtkEntry),Pointer :: entry
  Character,Pointer :: res(:)

For example,
  Character,Pointer :: string(:)
  Type(GtkCombo),Pointer :: combo
  ...
  combo => GTK_COMBO(combo)
  string => gtk_entry_get_text(GTK_ENTRY(combo%entry))

That's about all there is to it. There is a procedure

Subroutine gtk_combo_disable_activate(combo)
  Type(GtkCombo),Pointer :: combo

that will disable the activate signal on the entry widget in the combo box. Personally, I can't think of why you'd want to use it, but it does exist.

<<< Previous | Home | Next >>>
Spin Buttons | Up | Calendar


Calendar

The Calendar widget is an effective way to display and retrieve monthly date related information. It is a very simple widget to create and work with.

Creating a GtkCalendar widget is a simple as:

Function gtk_calendar_new() Result(r)
  Type(GtkWidget),Pointer :: r

There might be times where you need to change a lot of information within this widget and the following procedures allow you to make multiple change to a Calendar widget without the user seeing multiple on-screen updates.

Subroutine gtk_calendar_freeze(calendar)
  Type(GtkCalendar),Pointer :: calendar

Subroutine gtk_calendar_thaw(calendar)
  Type(GtkCalendar),Pointer :: calendar

They work just like the freeze/thaw functions of every other widget.

The Calendar widget has a few options that allow you to change the way the widget both looks and operates by using the procedure

Subroutine gtk_calendar_display_options(calendar,flags)
  Type(GtkCalendar),Pointer :: calendar
  Integer(GtkCalendarDisplayOptions),Intent(In) :: flags

The flags argument can be formed by combining any of the following five options using the intrinsic Ior function:

GTK_CALENDAR_SHOW_HEADING

specifies that the month and year should be shown when drawing the calendar;

GTK_CALENDAR_SHOW_DAY_NAMES

specifies that the names of each day should be displayed (in a C, POSIX, or English locale, the three-letter abbreviation is displayed);

GTK_CALENDAR_NO_MONTH_CHANGE

specifies that the user should not and can not change the currently displayed month (this can be good if you only need to display a particular month such as if you are displaying 12 calendar widgets for every month in a particular year);

GTK_CALENDAR_SHOW_WEEK_NUMBERS

specifies that the number for each week should be displayed down the left side of the calendar (e.g. Jan 1 = Week 1,Dec 31 = Week 52);

GTK_CALENDAR_WEEK_START_MONDAY

used to specify that the calender week will start on Monday instead of Sunday which was the default, but now displays a warning message on standard error that this setting is determined by the locale and the setting is ignored.

The following procedures are used to set the the currently displayed date:

Integer(gboolean) Function gtk_calendar_select_month(calendar,month,year)
  Type(GtkCalendar),Pointer :: calendar
  Integer(guint),Intent(In) :: month,year

Subroutine gtk_calendar_select_day(calendar,day)
  Type(GtkCalendar),Pointer :: calendar
  Integer(guint),Intent(In) :: day

The return value from gtk_calendar_select_month is a boolean value indicating whether the selection was successful.

With gtk_calendar_select_day the specified day number is selected within the current month, if that is possible. A day value of 0 will deselect any current selection.

In addition to having a day selected, any number of days in the month may be “marked”. A marked day is highlighted within the calendar display. The following functions are provided to manipulate marked days:

Integer(gboolean) Function gtk_calendar_mark_day(calendar,day)
  Type(GtkCalendar),Pointer :: calendar
  Integer(guint),Intent(In) :: day

Integer(gboolean) Function gtk_calendar_unmark_day(calendar,day)
  Type(GtkCalendar),Pointer :: calendar
  Integer(guint),Intent(In) :: day

Subroutine gtk_calendar_clear_marks(calendar)
  Type(GtkCalendar),Pointer :: calendar

The currently marked days are stored within an array within the GtkCalendar structure. This array is 31 elements long so to test whether a particular day is currently marked, you need to access the corresponding element of the array. For example:

  Type(GtkCalendar),Pointer :: calendar
  calendar => gtk_calendar_new()
  ...
  ! Is day 7 marked?
  If (gtk_calendar_mark_day(calendar,7)==TRUE) Then
    ! Day is marked.

Note that marks are persistent across month and year changes.

The final Calendar widget procedure is used to retrieve the currently selected date, month and/or year.

Subroutine gtk_calendar_get_date(calendar,year,month,day)
  Type(GtkCalendar),Pointer :: calendar
  Integer(guint),Intent(Out) :: year,month,day

The Calendar widget can generate a number of signals indicating date selection and change. The names of these signals are self explanatory, and are:

  • month_changed

  • day_selected

  • day_selected_double_click

  • prev_month

  • next_month

  • prev_year

  • next_year

That just leaves us with the need to put all of this together into example code.

!
! Copyright (C) 1998 Cesar Miquel, Shawn T. Amundson, Mattias Gronlund
! Copyright (C) 2000 Tony Gale
!
! This program is free software; you can redistribute it and/or modify
! it under the terms of the GNU General Public License as published by
! the Free Software Foundation; either version 2 of the License, or
! (at your option) any later version.
!
! This program is distributed in the hope that it will be useful,
! but WITHOUT ANY WARRANTY; without even the implied warranty of
! MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
! GNU General Public License for more details.
!
! You should have received a copy of the GNU General Public License
! along with this program; if not, write to the Free Software
! Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
!
Module calendar_module
  Use cairo
  Use pango
  Use gtk
  Implicit None

  Integer :: DEF_PAD       = 10
  Integer :: DEF_PAD_SMALL = 5

  Integer :: TM_YEAR_BASE  = 1900

  Type CalendarData
    Type(C_Ptr) :: flag_checkboxes(0:4)
    Integer(Kind=gboolean) :: settings(0:4)
    Type(GtkWidget),Pointer :: font_dialogue => Null()
    Type(GtkWidget),Pointer :: window => Null()
    Type(GtkWidget),Pointer :: prev2_sig => Null()
    Type(GtkWidget),Pointer :: prev_sig => Null()
    Type(GtkWidget),Pointer :: last_sig => Null()
    Type(GtkWidget),Pointer :: month => Null()
  End Type

  Type(CalendarData),Target,Save :: calendar_data

  Enum,Bind(C)
    Enumerator :: calendar_show_header
    Enumerator :: calendar_show_days
    Enumerator :: calendar_month_change
    Enumerator :: calendar_show_week
    Enumerator :: calendar_monday_first
  End Enum

Contains

  !
  ! GtkCalendar.
  !
  Subroutine calendar_date_to_string(data,buffer)
    Type(CalendarData),Intent(In),Target :: data
    Character(*),Intent(Out) :: buffer
    Type(GDate),Target :: date
    Type(GDate),Pointer :: pdate
    Integer :: year,month,day
    Integer(GDateDay) :: gday
    Integer(GDateMonth) :: gmonth
    Integer(GDateYear) :: gyear
    Integer :: dmy
    Type(GtkCalendar),Pointer :: calendar

    calendar => GTK_CALENDAR(C_Loc(data%window))
    Call gtk_calendar_get_date(Calendar,year,month,day)
    gday   = day
    gmonth = month + 1
    gyear  = year
    pdate => date
    Call g_date_set_dmy(pdate,gday,gmonth,gyear)
    dmy = g_date_strftime(buffer,'%x',pdate)
    If (dmy==0) buffer = Repeat('*',Len(buffer)) ! Buffer too small for date.
  End Subroutine

  Subroutine calendar_set_signal_strings(sigstr,data)
    Character(*) :: sigstr
    Type(CalendarData),Intent(InOut),Target :: data
    Character,Pointer :: pprev_sig(:)

    pprev_sig => gtk_label_get_text(GTK_LABEL(data%prev_sig))
    Call gtk_label_set_text(GTK_LABEL(data%prev2_sig),pprev_sig)
    pprev_sig => gtk_label_get_text(GTK_LABEL(data%last_sig))
    Call gtk_label_set_text(GTK_LABEL(data%prev_sig),pprev_sig)
    Call gtk_label_set_text(GTK_LABEL(data%last_sig),sigstr(:Len_Trim(sigstr)))
  End Subroutine

  Subroutine calendar_month_changed(widget,pdata) Bind(C,Name='')
    Type(GtkWidget) widget
    Type(C_Ptr),Value :: pdata

    Type(CalendarData),Pointer :: data
    Character(256) :: buffer = 'month_changed: '

    Call C_F_Pointer(pdata,data)

    Call calendar_date_to_string (data,buffer(16:))
    Call calendar_set_signal_strings(buffer,data)
  End Subroutine

  Subroutine calendar_day_selected(widget,pdata) Bind(C,Name='')
    Type(GtkWidget) :: widget
    Type(C_Ptr),Value :: pdata

    Type(CalendarData),Pointer :: data
    Character(256) :: buffer = 'day_selected: '

    Call C_F_Pointer(pdata,data)

    Call calendar_date_to_string(data,buffer(15:))
    Call calendar_set_signal_strings(buffer,data)
  End Subroutine

  Subroutine calendar_day_selected_double_click(widget,pdata) Bind(C,Name='')
    Type(GtkWidget) widget
    Type(C_Ptr),Value :: pdata

    Type(CalendarData),pointer :: data
    Type(GtkCalendar),Pointer :: Calendar
    Character(256) :: buffer = 'day_selected_double_click: '
    Integer :: year,month,day,dmy

    Call c_f_pointer(pdata,data)

    Call calendar_date_to_string(data,buffer(28:))
    Call calendar_set_signal_strings(buffer,data)

    Calendar => GTK_CALENDAR(C_Loc(data%window))
    Call gtk_calendar_get_date(Calendar,year,month,day)

    If (Calendar%marked_date(day-1)==0) Then
      dmy = gtk_calendar_mark_day(Calendar,day)
    Else
      dmy = gtk_calendar_unmark_day(Calendar,day)
    End If
  End Subroutine

  Subroutine calendar_prev_month(widget,pdata) Bind(C,Name='')
    Type(GtkWidget) widget
    Type(C_Ptr),Value :: pdata
    Type(CalendarData),Pointer :: data
    Character(256) :: buffer = 'prev_month: '

    Call C_F_Pointer(pdata,data)
    Call calendar_date_to_string(data,buffer(13:))
    Call calendar_set_signal_strings(buffer,data)
  End Subroutine

  Subroutine calendar_next_month(widget,pdata) Bind(C,Name='')
    Type(GtkWidget) widget
    Type(C_Ptr),Value :: pdata
    Type(CalendarData),Pointer :: data
    Character(256) :: buffer = 'next_month: '

    Call C_F_Pointer(pdata,data)
    Call calendar_date_to_string(data,buffer(13:))
    Call calendar_set_signal_strings(buffer,data)
  End Subroutine

  Subroutine calendar_prev_year(widget,pdata) Bind(C,Name='')
    Type(GtkWidget) widget
    Type(C_Ptr),Value :: pdata
    Type(CalendarData),Pointer :: data
    Character(256) :: buffer = 'prev_year: '

    Call C_F_Pointer(pdata,data)
    Call calendar_date_to_string(data,buffer(12:))
    Call calendar_set_signal_strings(buffer,data)
  End Subroutine

  Subroutine calendar_next_year(widget,pdata) Bind(C,Name='')
    Type(GtkWidget) widget
    Type(C_Ptr),Value :: pdata
    Type(CalendarData),Pointer :: data
    Character(256) :: buffer = 'next_year: '

    Call C_F_Pointer(pdata,data)
    Call calendar_date_to_string(data,buffer(12:))
    Call calendar_set_signal_strings(buffer,data)
  End Subroutine

  Subroutine calendar_set_flags(calendar)
    Type(CalendarData) :: calendar
    Integer :: i,options

    options = 0
    Do i = Lbound(calendar%settings,1),Ubound(calendar%settings,1)
      If (calendar%settings(i)/=0) &
        options = options + Ishft(1,i-Lbound(calendar%settings,1))
    End Do

    If (Associated(calendar%window)) &
      Call gtk_calendar_display_options(GTK_CALENDAR(C_Loc(calendar%window)), &
                                        options)
  End Subroutine

  Subroutine calendar_toggle_flag(toggle,pcalendar) Bind(C,Name='')
    Type(C_Ptr),Value :: toggle,pcalendar
    Type(CalendarData),Pointer :: calendar
    Integer :: i,j

    Call C_F_Pointer(pcalendar,calendar)
    j = 0
    Do i = Lbound(calendar%flag_checkboxes,1),Ubound(calendar%flag_checkboxes,1)
      If (C_Associated(calendar%flag_checkboxes(i),toggle)) j = i
    End Do
    calendar%settings(j) = Merge(1,0,calendar%settings(j)==0)
    Call calendar_set_flags(calendar)
  End Subroutine

  Subroutine calendar_font_selection_ok(pbutton,pcalendar) Bind(C,Name='')
    Type(C_Ptr),Value :: pbutton,pcalendar
    Type(CalendarData),Pointer :: calendar
    Type(GtkFontSelectionDialog),Pointer :: seldialogue
    Type(PangoFontDescription),Pointer :: desc

    Type(GtkRcStyle),Pointer :: style
    Character,Pointer :: font_name(:)

    Call C_F_Pointer(pcalendar,calendar)

    If (Associated(calendar%window)) Then
      seldialogue => GTK_FONT_SELECTION_DIALOG(calendar%font_dialogue)
      font_name => gtk_font_selection_dialog_get_font_name(seldialogue)
      If (Size(font_name)>0) Then
        style => gtk_rc_style_new()
        Call C_F_Pointer(style%font_desc,desc)
        Call pango_font_description_free(desc)
        desc => pango_font_description_from_string(font_name)
        style%font_desc = C_Loc(desc)
        Call gtk_widget_modify_style(calendar%window,style)
        Call g_free(C_Loc(font_name(1)))
      End If
    End If

    Call gtk_widget_destroy(calendar%font_dialogue)

  End Subroutine

  Subroutine calendar_select_font(pwidget,pcalendar) Bind(C,Name='')
    Type(C_Ptr),Value :: pwidget,pcalendar
    Type(CalendarData),Pointer :: calendar
    Type(GtkWidget),Pointer :: window
    Type(GtkFontSelectionDialog),Pointer :: seldlg

    Call C_F_Pointer(pcalendar,calendar)

    If (.Not.Associated(calendar%font_dialogue)) Then
      window => gtk_font_selection_dialog_new("Font Selection Dialogue")
      calendar%font_dialogue => window
      Call gtk_window_set_position(GTK_WINDOW(window),GTK_WIN_POS_MOUSE)
      Call g_signal_connect(G_OBJECT(window),"destroy", &
                            C_FunLoc(fontdlg_destroy), &
                            C_Loc(calendar%font_dialogue))

      seldlg => GTK_FONT_SELECTION_DIALOG(window)
      Call g_signal_connect(G_OBJECT(seldlg%ok_button),"clicked", &
                            C_FunLoc(calendar_font_selection_ok), &
                            C_Loc(calendar))
      Call g_signal_connect_swapped(G_OBJECT(seldlg%cancel_button), &
                                    "clicked", &
                                    C_FunLoc(fontdlg_destroy), &
                                    C_Loc(calendar%font_dialogue))
    End If

    window => calendar%font_dialogue
    If (GTK_WIDGET_VISIBLE(window)==0) Then
      Call gtk_widget_show(window)
    Else
      Call gtk_widget_destroy(window)
    End If
  End Subroutine

  Subroutine fontdlg_destroy(pobj) Bind(C,Name='')
    Type(C_Ptr),Value :: pobj

    Call gtk_widget_destroy(GTK_WIDGET(pobj))
    Nullify(calendar_data%font_dialogue)
  End Subroutine

  Subroutine create_calendar()
    Type(GtkWidget),Pointer :: window,vbox,vbox2,vbox3,hbox,hbbox,calendar, &
                               toggle,button,frame,separator,label,bbox
    Type(CalendarData),Pointer :: pcalendar
    Integer :: i,dmy
    Character(Len=20),Parameter :: flags(0:4) = &
      (/ Character(20) :: 'Show Heading', &
                          'Show Day Names', &
                          'No Month Change', &
                          'Show Week Numbers', &
                          'Week Start Monday' /)

    pcalendar => calendar_data
    calendar_data%window => Null()
    calendar_data%font_dialogue => Null()
    calendar_data%settings = 0

    If (Size(flags)/=Size(calendar_data%settings)) Stop 'Inconsistent sizes'

    window => gtk_window_new(GTK_WINDOW_TOPLEVEL)
    Call gtk_window_set_title(GTK_WINDOW(window),"GtkCalendar Example")
    Call gtk_container_set_border_width(GTK_CONTAINER(window),5)
    Call g_signal_connect(G_OBJECT(window),"destroy", &
                          C_FunLoc(gtk_main_quit),C_Null_Ptr)
    Call g_signal_connect(G_OBJECT(window),"delete-event", &
                          C_FunLoc(gtk_main_quit),C_Null_Ptr)

    Call gtk_window_set_resizable(GTK_WINDOW(window),FALSE)

    vbox => gtk_vbox_new(FALSE,DEF_PAD)
    Call gtk_container_add(GTK_CONTAINER(window),vbox)

    !
    ! The top part of the window, Calendar, flags and fontsel.
    !
    hbox => gtk_hbox_new(FALSE,DEF_PAD)
    Call gtk_box_pack_start(GTK_BOX(vbox),hbox,TRUE,TRUE,DEF_PAD)
    hbbox => gtk_hbutton_box_new()
    Call gtk_box_pack_start(GTK_BOX(hbox),hbbox,FALSE,FALSE,DEF_PAD)
    Call gtk_button_box_set_layout(GTK_BUTTON_BOX(hbbox),GTK_BUTTONBOX_SPREAD)
    Call gtk_box_set_spacing(GTK_BOX(hbbox),5)

    ! Calendar widget.
    frame => gtk_frame_new("Calendar")
    Call gtk_box_pack_start(GTK_BOX(hbbox),frame,FALSE,TRUE,DEF_PAD)
    calendar => gtk_calendar_new()
    calendar_data%window => calendar
    Call calendar_set_flags(calendar_data)
    dmy = gtk_calendar_mark_day(GTK_CALENDAR(calendar),19)
    Call gtk_container_add(GTK_CONTAINER(frame),calendar)
    Call g_signal_connect(G_OBJECT(calendar),"month_changed", &
                          C_FunLoc(calendar_month_changed),C_Loc(pcalendar))
    Call g_signal_connect(G_OBJECT(calendar),"day_selected", &
                          C_FunLoc(calendar_day_selected),C_Loc(pcalendar))
    Call g_signal_connect(G_OBJECT(calendar),"day_selected_double_click",&
                          C_FunLoc(calendar_day_selected_double_click), &
                          C_Loc(pcalendar))
    Call g_signal_connect(G_OBJECT(calendar),"prev_month", &
                          C_FunLoc(calendar_prev_month),C_Loc(pcalendar))
    Call g_signal_connect(G_OBJECT(calendar),"next_month", &
                          C_FunLoc(calendar_next_month),C_Loc(pcalendar))
    Call g_signal_connect(G_OBJECT(calendar),"prev_year", &
                          C_FunLoc(calendar_prev_year),C_Loc(pcalendar))
    Call g_signal_connect(G_OBJECT(calendar),"next_year", &
                          C_FunLoc(calendar_next_year),C_Loc(pcalendar))

    separator => gtk_vseparator_new()
    Call gtk_box_pack_start(GTK_BOX(hbox),separator,FALSE,TRUE,0)

    vbox2 => gtk_vbox_new(FALSE,DEF_PAD)
    Call gtk_box_pack_start(GTK_BOX(hbox),vbox2,FALSE,FALSE,DEF_PAD)

    ! Build the Right frame with the flags in.
    frame => gtk_frame_new("Flags")
    Call gtk_box_pack_start(GTK_BOX(vbox2),frame,TRUE,TRUE,DEF_PAD)
    vbox3 => gtk_vbox_new(TRUE,DEF_PAD_SMALL)
    Call gtk_container_add(GTK_CONTAINER(frame),vbox3)

    Do i=Lbound(flags,1),Ubound(flags,1)
      toggle => gtk_check_button_new_with_label(Trim(flags(i)))
      Call g_signal_connect(G_OBJECT(toggle),"toggled", &
                            C_FunLoc(calendar_toggle_flag),C_Loc(pcalendar))
      Call gtk_box_pack_start(GTK_BOX(vbox3),toggle,TRUE,TRUE,0)
      calendar_data%flag_checkboxes(i) = C_Loc(toggle)
    End Do
    ! Build the right font-button.
    button => gtk_button_new_with_label("Font...")
    Call g_signal_connect(G_OBJECT(button),"clicked", &
                          C_FunLoc(calendar_select_font),C_Loc(pcalendar))
    Call gtk_box_pack_start(GTK_BOX(vbox2),button,FALSE,FALSE,0)

    !
    ! Build the Signal-event part.
    !
    frame => gtk_frame_new("Signal events")
    Call gtk_box_pack_start(GTK_BOX(vbox),frame,TRUE,TRUE,DEF_PAD)

    vbox2 => gtk_vbox_new(TRUE,DEF_PAD_SMALL)
    Call gtk_container_add(GTK_CONTAINER(frame),vbox2)

    hbox => gtk_hbox_new(FALSE,3)
    Call gtk_box_pack_start(GTK_BOX(vbox2),hbox,FALSE,TRUE,0)
    label => gtk_label_new("Signal:")
    Call gtk_box_pack_start(GTK_BOX(hbox),label,FALSE,TRUE,0)
    calendar_data%last_sig => gtk_label_new("")
    Call gtk_box_pack_start(GTK_BOX(hbox),calendar_data%last_sig,FALSE,TRUE,0)

    hbox => gtk_hbox_new(FALSE,3)
    Call gtk_box_pack_start(GTK_BOX(vbox2),hbox,FALSE,TRUE,0)
    label => gtk_label_new("Previous signal:")
    Call gtk_box_pack_start(GTK_BOX(hbox),label,FALSE,TRUE,0)
    calendar_data%prev_sig => gtk_label_new()
    Call gtk_box_pack_start(GTK_BOX(hbox),calendar_data%prev_sig,FALSE,TRUE,0)

    hbox => gtk_hbox_new(FALSE,3)
    Call gtk_box_pack_start(GTK_BOX(vbox2),hbox,FALSE,TRUE,0)
    label => gtk_label_new("Second previous signal:")
    Call gtk_box_pack_start(GTK_BOX(hbox),label,FALSE,TRUE,0)
    calendar_data%prev2_sig => gtk_label_new()
    Call gtk_box_pack_start(GTK_BOX(hbox),calendar_data%prev2_sig,FALSE,TRUE,0)

    bbox => gtk_hbutton_box_new()
    Call gtk_box_pack_start(GTK_BOX(vbox),bbox,FALSE,FALSE,0)
    Call gtk_button_box_set_layout(GTK_BUTTON_BOX(bbox),GTK_BUTTONBOX_END)

    button => gtk_button_new_with_label("Close")
    Call g_signal_connect(G_OBJECT(button),"clicked", &
                          C_FunLoc(gtk_main_quit),C_Null_Ptr)
    Call gtk_container_add(GTK_CONTAINER(bbox),button)
    Call GTK_WIDGET_SET_FLAGS(button,GTK_CAN_DEFAULT)
    Call gtk_widget_grab_default(button)

    Call gtk_widget_show_all(window)
  End Subroutine
End Module

Program main
  Use calendar_module

  Call gtk_init
  Call create_calendar
  Call gtk_main
End Program

<<< Previous | Home | Next >>>
Combo Box | Up | Colour Selection


Colour Selection

The colour selection widget is, not surprisingly, a widget for interactive selection of colours. This composite widget lets the user select a colour by manipulating RGB (Red, Green, Blue) and HSV (Hue, Saturation, Value) triples. This is done either by adjusting single values with sliders or entries, or by picking the desired colour from a hue-saturation wheel/value bar. Optionally, the opacity of the colour can also be set.

The colour selection widget currently emits only one signal, “color_changed”, which is emitted whenever the current colour in the widget changes, either when the user changes it or if it's set explicitly through gtk_color_selection_set_color.

Lets have a look at what the colour selection widget has to offer us. The widget comes in two flavours: GtkColorSelection and GtkColorSelectionDialog.

Function gtk_color_selection_new() Result(r)
  Type(GtkWidget),Pointer :: r

You will probably not want to use this constructor directly. It creates an orphan ColorSelection widget which you would have to “parent” yourself. The ColorSelection widget inherits from the VBox widget.

Function gtk_color_selection_dialog_new(title) Result(r)
  Character(*) :: title
  Type(GtkWidget),Pointer :: r

This is the most common colour selection constructor. It creates a ColorSelectionDialog. It consists of a Frame containing a ColorSelection widget, an HSeparator and an HBox with three buttons, [Ok], [Cancel] and [Help]. You can reach these buttons by accessing the “ok_button”, “cancel_button” and “help_button” widgets in the ColorSelectionDialog structure, for example:
    Type(GtkColorSelectionDialog),Pointer :: gsdp
    gdsp => GTK_COLOR_SELECTION_DIALOG(colorseldialog)
    ... gdsp%ok_button

Subroutine gtk_color_selection_set_has_opacity_control(colorsel,has_opacity)
  Type(GtkColorSelection),Pointer :: colorsel
  Integer(gboolean),Intent(In) :: has_opacity

The colour selection widget supports adjusting the opacity of a colour (also known as the alpha channel). This is disabled by default. Calling this function with has_opacity set to TRUE enables opacity. Likewise, has_opacity set to FALSE will disable opacity.

Subroutine gtk_color_selection_set_current_color(colorsel,color)
  Type(GtkColorSelection),Pointer :: colorsel
  Type(GdkColor),Pointer :: color

Subroutine gtk_color_selection_set_current_alpha(colorsel,alpha)
  Type(GtkColorSelection),Pointer :: colorsel
  Integer :: alpha

You can set the current colour explicitly by calling gtk_color_selection_set_current_color with a pointer to a GdkColor. Setting the opacity (alpha channel) is done with gtk_color_selection_set_current_alpha. The alpha value should be between 0 (fully transparent) and 65535 (fully opaque).

Subroutine gtk_color_selection_get_current_color(colorsel,color)
  Type(GtkColorSelection),Pointer :: colorsel
  Type(GdkColor),Pointer :: color

Integer Function gtk_color_selection_get_current_alpha(colorsel)
  Type(GtkColorSelection),Pointer :: colorsel

When you need to query the current colour, typically when you've received a “color_changed” signal, you use these procedures.

Here's a simple example demonstrating the use of the ColorSelectionDialog. The program displays a window containing a drawing area. Clicking on it opens a colour selection dialog, and changing the colour in the colour selection dialog changes the background colour.

Module colour_select
  Use gtk

  Type(GtkWidget),Pointer :: colourseldlg => Null()
  Type(GtkWidget),Pointer :: drawing_area => Null()
  Type(GdkColor),Pointer :: colour

Contains

  ! Colour change handler.
  Subroutine colourchange_cb(widget,coloursel) Bind(C,Name='')
    Type(GtkWidget) widget
    Type(C_Ptr),Value :: coloursel

    Type(GdkColor),Pointer :: pcolour
    Type(GdkColor),Target :: ncolour

    pcolour => ncolour
    Call gtk_color_selection_get_current_color(GTK_COLOR_SELECTION(coloursel), &
                                               pcolour)
    Call gtk_widget_modify_bg(drawing_area,GTK_STATE_NORMAL,pcolour)
  End Subroutine

  ! Drawing-area event handler.
  Integer(gboolean) Function area_event(pwidget,pevent,puser_data) &
  Bind(C,Name='')
    Type(C_Ptr),Value :: pwidget,pevent,puser_data

    Integer,Pointer :: event_type
    Type(GtkColorSelection),Pointer :: coloursel
    Type(GtkColorSelectionDialog),Pointer :: ColorSelectionDialog

    ! Check if we've received a button-pressed event.
    Call C_F_Pointer(pevent,event_type)
    If (event_type/=GDK_BUTTON_PRESS) Then
      area_event = FALSE
    Else
      area_event = TRUE

      ! Create colour selection dialogue.
      If (.Not. Associated(colourseldlg)) &
        colourseldlg => gtk_color_selection_dialog_new ("Select background colour")

      ! Get the ColorSelection widget.
      ColorSelectionDialog => GTK_COLOR_SELECTION_DIALOG(colourseldlg)
      coloursel => GTK_COLOR_SELECTION(ColorSelectionDialog%colorsel)

      Call gtk_color_selection_set_previous_color(coloursel,colour)
      Call gtk_color_selection_set_current_color(coloursel,colour)
      Call gtk_color_selection_set_has_palette(coloursel,TRUE)

      ! Connect to the "color_changed" signal,
      ! set the client data to the coloursel widget.
      Call g_signal_connect(G_OBJECT(C_Loc(coloursel)),"color_changed", &
                            C_FunLoc(colourchange_cb),C_Loc(coloursel))

      ! Show the dialogue.
      If (gtk_dialog_run(GTK_DIALOG(colourseldlg))==GTK_RESPONSE_OK) Then
        Call gtk_color_selection_get_current_color(coloursel,colour)
      Else
        Call gtk_widget_modify_bg(drawing_area,GTK_STATE_NORMAL,colour)
      End If
      Call gtk_widget_hide(colourseldlg)
    End If
  End Function

  ! Close down and exit event handler.
  Integer(gboolean) Function destroy_window(widget,event,client_data) &
  Bind(C,Name='')
    Type(C_Ptr) :: widget,event,client_data

    Call gtk_main_quit
    destroy_window = TRUE
  End Function
End Module

Program main
  Use colour_select

  Type(GtkWidget),Pointer :: window
  Type(GdkColor),Target :: colour_obj

  Call gtk_init

  ! Create top-level window, set title and policies.
  window => gtk_window_new(GTK_WINDOW_TOPLEVEL)
  Call gtk_window_set_title(GTK_WINDOW(window),"Colour selection test")
  Call gtk_window_set_policy(GTK_WINDOW(window),TRUE,TRUE,TRUE)

  ! Attach to the "delete" and "destroy" events
  ! so we can exit.
  Call g_signal_connect(G_OBJECT(window),"delete_event", &
                        C_FunLoc(destroy_window),C_Loc(window))

  ! Create drawing area, set size and catch button events.
  drawing_area => gtk_drawing_area_new()

  colour => colour_obj
  colour%red = 0
  colour%blue = 65535
  colour%green = 0

  Call gtk_widget_modify_bg(drawing_area,GTK_STATE_NORMAL,colour)
  Call gtk_widget_set_size_request(drawing_area,200,200)
  Call gtk_widget_set_events(drawing_area,GDK_BUTTON_PRESS_MASK)
  Call g_signal_connect(G_OBJECT(drawing_area),"event", &
                        C_FunLoc(area_event),C_Loc(drawing_area))

  ! Add drawing_area to window, then show them both.
  Call gtk_container_add(GTK_CONTAINER(window),drawing_area)

  Call gtk_widget_show(drawing_area)
  Call gtk_widget_show(window)

  ! Enter the GTK main loop (this never returns).
  Call gtk_main

End Program

<<< Previous | Home | Next >>>
Calendar | Up | File Selections


File Selections

The file selection widget is a quick and simple way to display a File dialogue box. It comes complete with [Ok], [Cancel], and [Help] buttons, a great way to cut down on programming time.

To create a new file selection box use:

Function gtk_file_selection_new(title) Result(r)
  Character(*) :: title
  Type(GtkWidget),Pointer :: r

To set the filename, for example to bring up a specific directory, or give a default filename, use this procedure:

Subroutine gtk_file_selection_set_filename(filesel,filename)
  Type(GtkFileSelection),Pointer :: filesel
  Character(*) :: filename

To grab the text that the user has entered or clicked on, use this function:

Function gtk_file_selection_get_filename(filesel) Result(r)
  Type(GtkFileSelection),Pointer :: filesel
  Character,Pointer :: r(:)

There are also pointers to the widgets contained within the file selection widget. These are:

  dir_list
  file_list
  selection_entry
  selection_text
  main_vbox
  ok_button
  cancel_button
  help_button

Most likely you will want to use the ok_button, cancel_button, and help_button pointers in signalling their use.

Here is a simple example. As you will see, there is nothing much to creating a file selection widget. While in this example the Help button appears on the screen, it does nothing as there is no signal attached to it.

Module file_select
  Use gtk

Contains

  ! Get the selected filename and print it to the console.
  Subroutine file_ok_sel(pw,pfs) Bind(C,Name='')
    Type(C_Ptr),Value :: pw,pfs
    Print *,gtk_file_selection_get_filename(GTK_FILE_SELECTION(pfs))
  End Subroutine

End Module

Program main
  Use file_select

  Type(GtkWidget),Pointer :: filew
  Type(GtkFileSelection),Pointer :: fs

  Call gtk_init

  ! Create a new file selection widget.
  filew => gtk_file_selection_new("File selection")
  Call g_signal_connect(G_OBJECT(filew),"destroy", &
                        C_FunLoc(gtk_main_quit),C_Null_Ptr)

  ! Connect the ok_button to the file_ok_sel procedure.
  fs => GTK_FILE_SELECTION(C_Loc(filew))
  Call g_signal_connect(G_OBJECT(fs%ok_button),"clicked", &
                        C_FunLoc(file_ok_sel),C_Loc(filew))

  ! Connect the cancel_button to destroy the widget.
  Call g_signal_connect_swapped(G_OBJECT(fs%cancel_button),"clicked", &
                                C_FunLoc(gtk_widget_destroy),C_Loc(filew))

  ! Let's set the filename, as if this were a save dialogue and we were giving
  ! a default filename.
  Call gtk_file_selection_set_filename(fs,"penguin.png")

  Call gtk_widget_show(filew)

  Call gtk_main

End Program

<<< Previous | Home | Next >>>
Colour Selection | Up | Container Widgets


Container Widgets

The EventBox

Some GTK widgets don't have associated windows, so they just draw on their parents. Because of this, they cannot receive events and if they are incorrectly sized, they don't clip so you can get messy overwriting, etc.. If you require more from these widgets, the EventBox is for you.

At first glance, the EventBox widget might appear to be totally useless. It draws nothing on the screen and responds to no events. However, it does serve a function - it provides a window for its child widget. This is important as many GTK widgets do not have an associated window. Not having a window saves memory and improves performance, but also has some drawbacks. A widget without a window cannot receive events, and does not perform any clipping on its contents. Although the name EventBox emphasizes the event-handling function, the widget can also be used for clipping (and more, see the example below).

To create a new EventBox widget, use:

Function gtk_event_box_new() Result(r)
  Type(GtkWidget),Pointer :: r

A child widget can then be added to this EventBox:

Call gtk_container_add(GTK_CONTAINER(event_box),child_widget)

The following example demonstrates both uses of an EventBox; a label is created that is clipped to a small box, and set up so that a mouse-click on the label causes the program to exit. Resizing the window reveals varying amounts of the label.

Program main
  Use gtk
  Use gdk

  ! GtkWidget is the storage type for widgets.
  Type(GtkWidget),Pointer :: window,event_box,label

  Call gtk_init

  window => gtk_window_new(GTK_WINDOW_TOPLEVEL)

  Call gtk_window_set_title(GTK_WINDOW(window),"Event Box")
  Call g_signal_connect(G_OBJECT(window),"destroy", &
                        C_FunLoc(gtk_main_quit),C_Null_Ptr)
  Call gtk_container_set_border_width(GTK_CONTAINER(window),10)

  ! Create an EventBox and add it to our toplevel window.
  event_box => gtk_event_box_new()
  Call gtk_container_add(GTK_CONTAINER(window),event_box)
  Call gtk_widget_show(event_box)

  ! Create a long label.
  label => gtk_label_new("Click here to quit, quit, quit, quit, quit")
  Call gtk_container_add(GTK_CONTAINER(event_box),label)
  Call gtk_widget_show(label)

  ! Clip it short.
  Call gtk_widget_set_size_request(label,110,20)

  ! And bind an action to it.
  Call gtk_widget_set_events(event_box,GDK_BUTTON_PRESS_MASK)
  Call g_signal_connect(G_OBJECT(event_box),"button_press_event", &
                        C_FunLoc(gtk_main_quit),C_Null_Ptr)

  ! Yet one more thing you need a window for...
  Call gtk_widget_realize(event_box)

  Call gdk_window_set_cursor(GDK_WINDOW(event_box%window), &
                             gdk_cursor_new(GDK_HAND1))

  Call gtk_widget_show(window)

  Call gtk_main

End Program

<<< Previous | Home | Next >>>
File Selections |  | The Alignment widget


The Alignment widget

The alignment widget allows you to place a widget within its window at a position and size relative to the size of the Alignment widget itself. For example, it can be very useful for centring a widget within the window.

There are only two procedures associated with the Alignment widget:

Function gtk_alignment_new(xalign,yalign,xscale,yscale) Result(r)
  Real :: xalign,yalign,xscale,yscale
  Type(GtkWidget),Pointer :: r

Subroutine gtk_alignment_set(alignment,xalign,yalign,xscale,yscale)
  Type(GtkAlignment),Pointer :: alignment
  Real :: xalign,yalign,xscale,yscale

The first function creates a new Alignment widget with the specified parameters. The second function allows the alignment parameters of an exisiting Alignment widget to be altered.

All four alignment parameters are floating point numbers which can range from 0.0 to 1.0. The xalign and yalign arguments affect the position of the widget placed within the Alignment widget. The xscale and yscale arguments affect the amount of space allocated to the widget.

A child widget can be added to this Alignment widget using:

  Call gtk_container_add(GTK_CONTAINER(alignment),child_widget)

For an example of using an Alignment widget, refer to the example for the Progress Bar widget.

<<< Previous | Home | Next >>>
Container Widgets | Up | Fixed Container


Fixed Container

The Fixed container allows you to place widgets at a fixed position within it's window, relative to it's upper left hand corner. The position of the widgets can be changed dynamically.

There are only a few functions associated with the fixed widget:

Function gtk_fixed_new() Result(r)
  Type(GtkWidget),Pointer :: r

Subroutine gtk_fixed_put(fixed,widget,x,y)
  Type(GtkFixed),Pointer :: fixed
  Type(GtkWidget),Pointer :: widget
  Integer(gint),Intent(In) :: x,y

Subroutine gtk_fixed_move(fixed,widget,x,y)
  Type(GtkFixed),Pointer :: fixed
  Type(GtkWidget),Pointer :: widget
  Integer(gint),Intent(In) :: x,y

The function gtk_fixed_new allows you to create a new Fixed container.

gtk_fixed_put places widget in the container fixed at the position specified by x and y.

gtk_fixed_move allows the specified widget to be moved to a new position.

Subroutine gtk_fixed_set_has_window(fixed,has_window)
  Type(GtkFixed),Pointer :: fixed
  Integer(gboolean),Intent(In) :: has_window

Integer(gboolean) Function gtk_fixed_get_has_window(fixed)
  Type(GtkFixed),Pointer :: fixed

Normally, Fixed widgets don't have their own window. Since this is different from the behaviour of Fixed widgets in earlier releases of GTK, the function gtk_fixed_set_has_window allows the creation of Fixed widgets with their own window. It has to be called before realizing the widget.

The following example illustrates how to use the Fixed Container.

Module fixed_container
  Use gtk

  ! I'm going to be lazy and use some global variables to
  ! store the position of the widget within the fixed container.
  Integer :: x = 50, y = 50

Contains

  ! This callback procedure moves the button to a new position
  ! in the Fixed container.
  Subroutine move_button(pwidget,pfixed) Bind(C,Name='')
    Type(C_Ptr),Value :: pwidget,pfixed

    x = Mod(x + 30, 300)
    y = Mod(y + 50, 300)
    Call gtk_fixed_move(GTK_FIXED(pfixed),GTK_WIDGET(pwidget),x,y)
  End Subroutine

End Module

Program main
  Use fixed_container

  ! GtkWidget is the storage type for widgets.
  Type(GtkWidget),Pointer :: window,fixed,button
  Integer :: i

  Call gtk_init

  window => gtk_window_new(GTK_WINDOW_TOPLEVEL)
  Call gtk_window_set_title(GTK_WINDOW (window),"Fixed Container")

  Call g_signal_connect(G_OBJECT(window),"destroy", &
                        C_FunLoc(gtk_main_quit),C_Null_Ptr)

  Call gtk_container_set_border_width(GTK_CONTAINER(window),10)

  ! Create a fixed container.
  fixed => gtk_fixed_new()
  Call gtk_container_add(GTK_CONTAINER(window),fixed)
  Call gtk_widget_show(fixed)

  Do i=1,3
    ! Creates a new button with the label "Press me".
    button => gtk_button_new_with_label("Press me")

    ! When the button receives the "clicked" signal, it will call the
    ! procedure move_button() passing it the Fixed Container as its
    ! argument.
    Call g_signal_connect(G_OBJECT(button),"clicked", &
                          C_FunLoc(move_button),C_Loc(fixed))

    ! This packs the button into the fixed containers window.
    Call gtk_fixed_put(GTK_FIXED(fixed),button,i*50,i*50)

    ! The final step is to display this newly created widget.
    Call gtk_widget_show(button)

  End Do

  ! Display the window.
  Call gtk_widget_show(window)

  ! Enter the event loop.
  Call gtk_main

End Program

<<< Previous | Home | Next >>>
The Alignment widget | Up | Layout Container


Layout Container

The Layout container is similar to the Fixed container except that it implements an extremely large (up to 232 pixels) scrolling area. Some window systems have a limitation where windows can be at most 32767 pixels wide or tall; the Layout container gets around this limitation by doing some exotic stuff using window and bit gravities, so that you can have smooth scrolling even when you have many child widgets in your scrolling area.

A Layout container is created using:

Function gtk_layout_new(hadjustment,vadjustment) Result(r)
  Type(GtkAdjustment),Pointer :: hadjustment,vadjustment
  Type(GtkWidget),Pointer :: r

As you can see, you can optionally specify the Adjustment objects that the Layout widget will use for its scrolling.

You can add and move widgets in the Layout container using the following two procedures:

Subroutine gtk_layout_put (layout,child_widget,x,y)
  Type(GtkLayout),Pointer :: layout
  Type(GtkWidget),Pointer :: child_widget
  Integer(gint),Intent(In) :: x,y

Subroutine gtk_layout_move(layout,child_widget,x,y)
    Type(GtkLayout),Pointer :: layout
    Type(GtkWidget),Pointer :: child_widget
    Integer(gint),Intent(In) :: x,y

The size of the Layout container can be set using the next procedure:

Subroutine gtk_layout_set_size(layout,width,height)
  Type(GtkLayout),Pointer :: layout
  Integer(guint),Intent(In) :: width,height

The final four procedures for use with Layout widgets are for manipulating the horizontal and vertical adjustment widgets:

Function gtk_layout_get_hadjustment(layout) Result(r)
  Type(GtkLayout),Pointer :: layout
  Type(GtkAdjustment),Pointer :: r

Function gtk_layout_get_vadjustment(layout) Result(r)
  Type(GtkLayout),Pointer :: layout
  Type(GtkAdjustment),Pointer :: r

Subroutine gtk_layout_set_hadjustment(layout,adjustment)
  Type(GtkLayout),Pointer :: layout
  Type(GtkAdjustment),Pointer :: adjustment

Subroutine gtk_layout_set_vadjustment(layout,adjustment)
  Type(GtkLayout),Pointer :: layout
  Type(GtkAdjustment),Pointer :: adjustment

<<< Previous | Home | Next >>>
Fixed Container | Up | Frames


Frames

Frames can be used to enclose one or a group of widgets with a box which can optionally be labelled. The position of the label and the style of the box can be altered to suit.

A Frame can be created with the following function:

Function gtk_frame_new(label) Result(res)
  Character(*),Intent(In) :: label
  Type(GtkWidget),Pointer :: res

The label is by default placed in the upper left hand corner of the frame. A value of "" (the zero-length string) for the label argument will result in no label being displayed. The text of the label can be changed using the next procedure.

Subroutine gtk_frame_set_label(frame,label)
  Type(GtkFrame),Pointer :: frame
  Character(*),Intent(In) :: label

The position of the label can be changed using this procedure:

Subroutine gtk_frame_set_label_align(frame,xalign,yalign)
  Type(GtkFrame),Pointer :: frame
  Real(C_float),Intent(In) :: xalign,yalign

xalign and yalign take values between 0.0 and 1.0. xalign indicates the position of the label along the top horizontal of the frame. yalign is not currently used. The default value of xalign is 0.0 which places the label at the left hand end of the frame.

The next procedure alters the style of the box that is used to outline the frame.

Subroutine gtk_frame_set_shadow_type(frame,type)
  Type(GtkFrame),Pointer :: frame
  Integer(GtkShadowType),Intent(In) :: type

The type argument may take one of the following values:

  GTK_SHADOW_NONE

  GTK_SHADOW_IN

  GTK_SHADOW_OUT

  GTK_SHADOW_ETCHED_IN (the default)

  GTK_SHADOW_ETCHED_OUT

The following code example illustrates the use of the Frame widget.

Program frames
  Use gtk

  ! GtkWidget is the storage type for widgets.
  Type(GtkWidget),Pointer :: window,frame

  ! Initialise GTK.
  Call gtk_init

  ! Create a new window.
  window => gtk_window_new (GTK_WINDOW_TOPLEVEL)
  Call gtk_window_set_title(GTK_WINDOW (window),"Frame Example")

  ! Here we connect the "destroy" event to a signal handler.
  Call g_signal_connect(G_OBJECT(window),"destroy", &
                        C_FunLoc(gtk_main_quit),C_Null_Ptr)
  Call gtk_widget_set_size_request(window,300,300)
  ! Sets the border width of the window.
  Call gtk_container_set_border_width(GTK_CONTAINER(window),10)

  ! Create a Frame.
  frame => gtk_frame_new('')
  Call gtk_container_add(GTK_CONTAINER(window),frame)

  ! Set the frame's label.
  Call gtk_frame_set_label(GTK_FRAME(frame),"GTK Frame Widget")

  ! Align the label at the right of the frame.
  Call gtk_frame_set_label_align(GTK_FRAME(frame),1.0,0.0)

  ! Set the style of the frame.
  Call gtk_frame_set_shadow_type(GTK_FRAME(frame),GTK_SHADOW_ETCHED_OUT)

  Call gtk_widget_show(frame)

  ! Display the window.
  Call gtk_widget_show(window)

  ! Enter the event loop.
  Call gtk_main

End Program

<<< Previous | Home | Next >>>
Layout Container | Up | Aspect Frames


Aspect Frames

The aspect frame widget is like a frame widget, except that it also enforces the aspect ratio (that is, the ratio of the width to the height) of the child widget to have a certain value, adding extra space if necessary. This is useful, for instance, if you want to preview a larger image. The size of the preview should vary when the user resizes the window, but the aspect ratio needs to always match the original image.

To create a new aspect frame use:

Function gtk_aspect_frame_new(label,xalign,yalign,ratio,obey_child) Result(r)
  Character(*),Intent(In) :: label
  Real,Intent(In) :: xalign,yalign,ratio
  Integer,Intent(In) :: obey_child
  Type(GtkWidget),Pointer :: r

xalign and yalign specify alignment as with Alignment widgets. If obey_child is TRUE, the aspect ratio of a child widget will match the aspect ratio of the ideal size it requests. Otherwise, it is given by ratio .

To change the options of an existing aspect frame, you can use:

Subroutine gtk_aspect_frame_set(aspect_frame,xalign,yalign,ratio,obey_child)
  Type(GtkAspectFrame),Pointer :: aspect_frame
  Real,Intent(In) :: xalign,yalign,ratio
  Integer,Intent(In) :: obey_child

As an example, the following program uses an AspectFrame to present a drawing area whose aspect ratio will always be 2:1, no matter how the user resizes the top-level window.

Program main
  Use gtk

  Type(GtkWidget),Pointer :: window,aspect_frame,drawing_area

  Call gtk_init

  window => gtk_window_new(GTK_WINDOW_TOPLEVEL)
  Call gtk_window_set_title(GTK_WINDOW (window),"Aspect Frame")
  Call g_signal_connect(G_OBJECT(window),"destroy", &
                        C_FunLoc(gtk_main_quit),C_Null_Ptr)

  Call gtk_container_set_border_width(GTK_CONTAINER(window),10)

  ! Create an aspect_frame and add it to our toplevel window.
  aspect_frame => gtk_aspect_frame_new("2x1", & ! label,
                                       0.5, &   ! centre x,
                                       0.5, &   ! centre y,
                                       2.0, &   ! xsize/ysize==2,
                                       FALSE)   ! ignore child's aspect.

  Call gtk_container_add(GTK_CONTAINER(window),aspect_frame)

  Call gtk_widget_show(aspect_frame)

  ! Now add a child widget to the aspect frame.
  drawing_area => gtk_drawing_area_new()

  ! Ask for a 200x200 window, but the AspectFrame will give us a 200x100
  ! window since we are forcing a 2x1 aspect ratio.
  Call gtk_widget_set_size_request(drawing_area,200,200)
  Call gtk_container_add(GTK_CONTAINER(aspect_frame),drawing_area)
  Call gtk_widget_show(drawing_area)

  Call gtk_widget_show(window)
  Call gtk_main

End Program

<<< Previous | Home | Next >>>
Frames | Up | Paned Window Widgets


Paned Window Widgets

The paned window widgets are useful when you want to divide an area into two parts, with the relative size of the two parts controlled by the user. A groove is drawn between the two portions with a handle that the user can drag to change the ratio. The division can either be horizontal (HPaned) or vertical (VPaned).

To create a new paned window, call one of:

Function gtk_hpaned_new() Result(r)
    Type(GtkWidget),Pointer :: r

Function gtk_vpaned_new() Result(r)
    Type(GtkWidget),Pointer :: r

After creating the paned window widget, you need to add child widgets to its two halves. To do this, use the procedures:

Subroutine gtk_paned_add1(paned,child)
    Type(GtkPaned),Pointer :: paned
    Type(GtkWidget),Pointer :: child

Subroutine gtk_paned_add2(paned,child)
    Type(GtkPaned),Pointer :: paned
    Type(GtkWidget),Pointer :: child

gtk_paned_add1 adds the child widget to the left or top half of the paned window. gtk_paned_add2 adds the child widget to the right or bottom half of the paned window.

As an example, we will create part of the user interface of an imaginary email program. A window is divided into two portions vertically, with the top portion being a list of email messages and the bottom portion the text of the email message. Most of the program is pretty straightforward. A couple of points to note: text can't be added to a Text widget until it is realized. This could be done by calling gtk_widget_realize, but as a demonstration of an alternate technique, we connect a handler to the “realize” signal to add the text. Also, we need to add the GTK_SHRINK option to some of the items in the table containing the text window and its scrollbars, so that when the bottom portion is made smaller, the correct portions shrink instead of being pushed off the bottom of the window.

Module paned_window
  Use gtk
  Use glib
  Implicit None

  Character(Len=*),Parameter :: winmes = &
        "From: pathfinder@nasa.gov" // C_New_Line &
        & // "To: mom@nasa.gov" // C_New_Line &
        & // "Subject: Made it!" // C_New_Line &
        & // C_New_Line &
        & // "We just got in this morning. The weather has been" // C_New_Line &
        & // "great - clear but cold, and there are lots of fun sights."// C_New_Line &
        & // "Sojourner says hi, See you soon." // C_New_Line &
        & // " -Path" // C_New_Line // C_Null_Char

Contains

  Subroutine make_gvalue_string(gval,val)
    Type(GValue),Pointer :: gval
    Character(*),Intent(In) :: val
    Call g_value_set_string(g_value_init(gval,G_TYPE_STRING),Trim(val))
  End Subroutine

  ! Create the list of messages.
  Function create_list() Result(r)
    Type(GtkWidget),Pointer :: r

    Type(GtkWidget),Pointer :: scrolled_window,tree_view
    Type(GtkListStore),Pointer :: model
    Type(GtkTreeIter),Pointer :: iter
    Type(GtkCellRenderer),Pointer :: cell
    Type(GtkTreeViewColumn),Pointer :: column
    Character(Len=80) :: msg
    Integer :: i,col
    Type(GValue),Pointer :: gval

    Allocate(iter,gval)
    ! Create a new scrolled window, with scrollbars only if needed.
    scrolled_window => gtk_scrolled_window_new(Null(),Null())
    Call gtk_scrolled_window_set_policy(GTK_SCROLLED_WINDOW(scrolled_window), &
                                        GTK_POLICY_AUTOMATIC, &
                                        GTK_POLICY_AUTOMATIC)

    model => gtk_list_store_new(1,G_TYPE_STRING)
    tree_view => gtk_tree_view_new()
    Call gtk_scrolled_window_add_with_viewport(GTK_SCROLLED_WINDOW(scrolled_window), &
                                               tree_view)
    Call gtk_tree_view_set_model(GTK_TREE_VIEW(tree_view), &
                                 GTK_TREE_MODEL(C_Loc(model)))
    Call gtk_widget_show(tree_view)

    ! Add some messages to the window.
    Do i=0,9
      Call gtk_list_store_append(GTK_LIST_STORE(C_Loc(model)),iter)
      Write (msg,'(A,I0)') 'Message #',i
      Call make_gvalue_string(gval,msg)
      Call gtk_list_store_set_value(GTK_LIST_STORE(C_Loc(model)),iter,0,gval)
      Call g_value_unset(gval)
    End Do

    cell => gtk_cell_renderer_text_new()
    column => gtk_tree_view_column_new()
    Call gtk_tree_view_column_pack_start(column,cell,FALSE)
    Call gtk_tree_view_column_set_title(column,"Messages")
    Call gtk_tree_view_column_add_attribute(column,cell,"text",0)

    col =  gtk_tree_view_append_column(GTK_TREE_VIEW(tree_view), &
                                       GTK_TREE_VIEW_COLUMN(C_Loc(column)))

    r => scrolled_window;

    Deallocate(iter,gval)

  End Function

  ! Add some text to our text widget - this is a callback that is invoked
  ! when our window is realized.  We could also force our window to be
  ! realized with gtk_widget_realize, but it would have to be part of
  ! a hierarchy first.
  Subroutine insert_text(buffer)
    Type(GtkTextBuffer),Pointer :: buffer
    Type(GtkTextIter),Pointer :: iter

    Allocate(iter)

    Call gtk_text_buffer_get_iter_at_offset(buffer,iter,0)
    Call gtk_text_buffer_insert(buffer,iter,winmes,-1)

    Deallocate(iter)

  End Subroutine

  ! Create a scrolled text area that displays a message.
  Function create_text()
    Type(GtkWidget),Pointer :: create_text
    Type(GtkWidget),Pointer :: scrolled_window,view
    Type(GtkTextBuffer),Pointer :: buffer

    view => gtk_text_view_new()
    buffer => gtk_text_view_get_buffer(GTK_TEXT_VIEW(view))

    scrolled_window => gtk_scrolled_window_new(Null(),Null())
    Call gtk_scrolled_window_set_policy(GTK_SCROLLED_WINDOW(scrolled_window), &
                                        GTK_POLICY_AUTOMATIC, &
                                        GTK_POLICY_AUTOMATIC)

    Call gtk_container_add (GTK_CONTAINER(scrolled_window),view)
    Call insert_text(buffer)

    Call gtk_widget_show_all(scrolled_window)

    create_text => scrolled_window

  End Function

End Module

Program main
  Use paned_window
  Implicit None

  Type(GtkWidget),Pointer :: window,vpaned,list,text

  Call gtk_init

  window => gtk_window_new(GTK_WINDOW_TOPLEVEL)
  Call gtk_window_set_title(GTK_WINDOW(window),"Paned Window")
  Call g_signal_connect(G_OBJECT(window),"destroy", &
                        C_FunLoc(gtk_main_quit),C_Null_Ptr)
  Call gtk_container_set_border_width(GTK_CONTAINER(window),10)
  call gtk_widget_set_size_request (window, 450, 400)

  ! Create a vpaned widget and add it to our toplevel window.
  vpaned => gtk_vpaned_new()
  Call gtk_container_add(GTK_CONTAINER(window),vpaned)
  Call gtk_widget_show(vpaned)

  ! Now create the contents of the two halves of the window.
  list => create_list()
  Call gtk_paned_add1(GTK_PANED(vpaned),list)
  Call gtk_widget_show(list)

  text => create_text()
  Call gtk_paned_add2(GTK_PANED(vpaned),text)
  Call gtk_widget_show(text)
  Call gtk_widget_show(window)

  Call gtk_main

End Program

<<< Previous | Home | Next >>>
Aspect Frames | Up | Viewports


Viewports

It is unlikely that you will ever need to use the Viewport widget directly. You are much more likely to use the Scrolled Window widget which itself uses the Viewport.

A viewport widget allows you to place a larger widget within it such that you can view a part of it at a time. It uses Adjustments to define the area that is currently in view.

A Viewport is created with the function

Function gtk_viewport_new(hadjustment,vadjustment) Result(res)
    Type(GtkAdjustment),Pointer :: hadjustment,vadjustment
    Type(GtkWidget),Pointer :: res

As you can see you can specify the horizontal and vertical Adjustments that the widget is to use when you create the widget. It will create its own if you pass NULL() as the value of the arguments.

You can get and set the adjustments after the widget has been created using the following four procedures:

Function gtk_viewport_get_hadjustment(viewport) Result(res)
    Type(GtkViewport),Pointer :: viewport
    Type(GtkAdjustment),Pointer :: res

Function gtk_viewport_get_vadjustment(viewport) Result(res)
    Type(GtkViewport),Pointer :: viewport
    Type(GtkAdjustment),Pointer :: res

Subroutine gtk_viewport_set_hadjustment(viewport,adjustment)
    Type(GtkViewport),Pointer :: viewport
    Type(GtkAdjustment),Pointer :: adjustment

Subroutine gtk_viewport_set_vadjustment(viewport,adjustment)
    Type(GtkViewport),Pointer :: viewport
    Type(GtkAdjustment),Pointer :: adjustment

The only other viewport procedure is used to alter its appearance:

Subroutine gtk_viewport_set_shadow_type(viewport,type)
    Type(GtkViewport),Pointer :: viewport
    Integer(GtkShadowType) :: type

Possible values for the type argument are:

  GTK_SHADOW_NONE,
  GTK_SHADOW_IN,
  GTK_SHADOW_OUT,
  GTK_SHADOW_ETCHED_IN,
  GTK_SHADOW_ETCHED_OUT

<<< Previous | Home | Next >>>
Paned Window Widgets | Up | Scrolled Windows


Scrolled Windows

Scrolled windows are used to create a scrollable area with another widget inside it. You may insert any type of widget into a scrolled window, and it will be accessible regardless of the size by using the scrollbars.

The following function is used to create a new scrolled window.

Function gtk_scrolled_window_new(hadjustment,vadjustment) Result(res)
    Type(GtkAdjustment),Pointer :: hadjustment,vadjustment
    Type(GtkWidget),Pointer :: res

The first argument is the adjustment for the horizontal direction, and the second, the adjustment for the vertical direction. These are almost always NULL().

Subroutine gtk_scrolled_window_set_policy(scrolled_window,hscrollbar_policy, &
                                          vscrollbar_policy)
    Type(GtkScrolledWindow),Pointer :: scrolled_window
    Integer(GtkPolicyType),Intent(In) :: hscrollbar_policy,vscrollbar_policy

This sets the policy to be used with respect to the scrollbars. The first argument is the scrolled window you wish to change. The second sets the policy for the horizontal scrollbar, and the third the policy for the vertical scrollbar.

The policy may be one of GTK_POLICY_AUTOMATIC or GTK_POLICY_ALWAYS. GTK_POLICY_AUTOMATIC will automatically decide whether you need scrollbars, whereas GTK_POLICY_ALWAYS will always leave the scrollbars there.

You can then place your object into the scrolled window using the following procedure.

Subroutine gtk_scrolled_window_add_with_viewport(scrolled_window,child)
    Type(GtkScrolledWindow),Pointer :: scrolled_window
    Type(GtkWidget),Pointer :: child

Here is a simple example that packs a table with 100 toggle buttons into a scrolled window. I've only commented on the parts that might be new to you.

Program main
  Use gtk

  Type(GtkWidget),Pointer :: window,scrolled_window,table,button
  Type(GtkDialog),Pointer :: dlg
  Character(32) :: buffer
  Integer :: i,j

  Call gtk_init

  ! Create a new dialog window for the scrolled window to be packed into.
  window => gtk_dialog_new()
  Call g_signal_connect(G_OBJECT(window),"destroy", &
                        C_FunLoc(gtk_main_quit),C_Null_Ptr)
  Call gtk_window_set_title(GTK_WINDOW(window),"GtkScrolledWindow example")
  Call gtk_container_set_border_width(GTK_CONTAINER(window),0)
  Call gtk_widget_set_size_request(window,300,300)

  ! Create a new scrolled window.
  scrolled_window => gtk_scrolled_window_new(Null(),Null())

  Call gtk_container_set_border_width(GTK_CONTAINER(scrolled_window),10)

  ! The policy is one of GTK_POLICY AUTOMATIC, or GTK_POLICY_ALWAYS.
  ! GTK_POLICY_AUTOMATIC will automatically decide whether you need scrollbars,
  ! whereas GTK_POLICY_ALWAYS will always leave the scrollbars there.
  ! The first one is the horizontal scrollbar, the second, the vertical one.
  !
  Call gtk_scrolled_window_set_policy(GTK_SCROLLED_WINDOW (scrolled_window), &
                                      GTK_POLICY_AUTOMATIC,GTK_POLICY_ALWAYS)
  ! The dialogue window is created with a vbox packed into it.
  dlg => GTK_DIALOG(window)
  Call gtk_box_pack_start(GTK_BOX(dlg%vbox),scrolled_window,TRUE,TRUE,0)
  Call gtk_widget_show(scrolled_window)

  ! Create a table of 10 by 10 squares.
  table => gtk_table_new(10,10,FALSE)

  ! Set the spacing to 10 on x and 10 on y.
  Call gtk_table_set_row_spacings(GTK_TABLE(table),10)
  Call gtk_table_set_col_spacings(GTK_TABLE(table),10)

  ! Pack the table into the scrolled window.
  Call gtk_scrolled_window_add_with_viewport(GTK_SCROLLED_WINDOW(scrolled_window), &
                                             table)
  Call gtk_widget_show(table)

  ! This simply creates a grid of toggle buttons on the table
  ! to demonstrate the scrolled window.
  Do i=0,9
      Do j=0,9
          Write (buffer,'("button (",I0,",",I0,")")') i,j
          button => gtk_toggle_button_new_with_label(Trim(buffer))
          Call gtk_table_attach_defaults(GTK_TABLE(table),button,i,i+1,j,j+1)
          Call gtk_widget_show(button)
      End Do
  End Do
  ! Add a "close" button to the bottom of the dialogue.
  button => gtk_button_new_with_label("close")
  Call g_signal_connect_swapped(G_OBJECT (button),"clicked", &
                                C_FunLoc(gtk_widget_destroy),C_Loc(window))

  ! This makes it so the button is the default.
  Call GTK_WIDGET_SET_FLAGS(button,GTK_CAN_DEFAULT)

  dlg => GTK_DIALOG(window)
  Call gtk_box_pack_start(GTK_BOX(dlg%action_area),button,TRUE,TRUE,0)

  ! This grabs this button to be the default button.  Simply hitting
  ! the [Enter] key will cause this button to activate.
  Call gtk_widget_grab_default(button)
  Call gtk_widget_show(button)

  Call gtk_widget_show(window)

  Call gtk_main

End Program

Try playing with resizing the window. You'll notice how the scrollbars react. You may also wish to use the gtk_widget_set_size_request call to set the default size of the window or other widgets.

<<< Previous | Home | Next >>>
Viewports | Up | Button Boxes


Button Boxes

Button Boxes are a convenient way to quickly layout a group of buttons. They come in both horizontal and vertical flavours. You create a new Button Box with one of the following calls, which create a horizontal or vertical box, respectively:

Function gtk_hbutton_box_new() Result(res)
    Type(GtkWidget),Pointer :: res

Function gtk_vbutton_box_new() Result(res)
    Type(GtkWidget),Pointer :: res

Buttons are added to a Button Box using the usual procedure:

  Call gtk_container_add(GTK_CONTAINER(button_box),C_Loc(child_widget))

Here's an example that illustrates all the different layout settings for Button Boxes.

Module button_boxes
  Use gtk
  Implicit None
Contains
  ! Create a Button Box with the specified parameters.
  Function create_bbox(horizontal,title,spacing,child_w,child_h,layout)
    Integer,Intent(In) :: spacing,child_w,child_h,layout
    Logical,Intent(In) :: horizontal
    Character(*),Intent(In) :: title
    Type(GtkWidget),Pointer :: create_bbox

    Type(GtkWidget),Pointer :: bbox,button

    create_bbox => gtk_frame_new(title)

    If (horizontal) Then
        bbox => gtk_hbutton_box_new ()
    Else
        bbox => gtk_vbutton_box_new ()
    End If

    Call gtk_container_set_border_width(GTK_CONTAINER(bbox),5)
    Call gtk_container_add(GTK_CONTAINER(create_bbox),bbox)

    ! Set the appearance of the Button Box.
    Call gtk_button_box_set_layout(GTK_BUTTON_BOX(bbox),layout)
    Call gtk_box_set_spacing(GTK_BOX(bbox),spacing)

    button => gtk_button_new_from_stock(GTK_STOCK_OK)
    Call gtk_container_add(GTK_CONTAINER(bbox),button)

    button => gtk_button_new_from_stock(GTK_STOCK_CANCEL)
    Call gtk_container_add(GTK_CONTAINER(bbox),button)

    button => gtk_button_new_from_stock(GTK_STOCK_HELP)
    Call gtk_container_add(GTK_CONTAINER(bbox),button)

  End Function

End Module

Program main
  Use button_boxes

  Type(GtkWidget),Pointer :: window,main_vbox,vbox,hbox,frame_horz,frame_vert

  ! Initialise GTK.
  Call gtk_init

  window => gtk_window_new(GTK_WINDOW_TOPLEVEL)
  Call gtk_window_set_title(GTK_WINDOW(window),"Button Boxes")

  Call g_signal_connect(G_OBJECT(window),"destroy", &
                        C_FunLoc(gtk_main_quit),C_Null_Ptr)

  Call gtk_container_set_border_width(GTK_CONTAINER(window),10)

  main_vbox => gtk_vbox_new(FALSE,0)
  Call gtk_container_add(GTK_CONTAINER(window),main_vbox)

  frame_horz => gtk_frame_new("Horizontal Button Boxes")
  Call gtk_box_pack_start(GTK_BOX(main_vbox),frame_horz,TRUE,TRUE,10)

  vbox => gtk_vbox_new(FALSE,0)
  Call gtk_container_set_border_width(GTK_CONTAINER(vbox),10)
  Call gtk_container_add(GTK_CONTAINER(frame_horz),vbox)

  Call gtk_box_pack_start(GTK_BOX(vbox), &
                          create_bbox(.True.,"Spread (spacing 40)", &
                                      40,85,20,GTK_BUTTONBOX_SPREAD), &
                          TRUE,TRUE,0)

  Call gtk_box_pack_start(GTK_BOX(vbox), &
                          create_bbox(.True.,"Edge (spacing 30)", &
                                      30,85,20,GTK_BUTTONBOX_EDGE), &
                          TRUE,TRUE,5)

  Call gtk_box_pack_start(GTK_BOX(vbox), &
                          create_bbox(.True.,"Start (spacing 20)", &
                                      20,85,20,GTK_BUTTONBOX_START), &
                          TRUE,TRUE,5)

  Call gtk_box_pack_start(GTK_BOX(vbox), &
                          create_bbox(.True.,"End (spacing 10)", &
                                      10,85,20,GTK_BUTTONBOX_END), &
                          TRUE,TRUE,5)

  frame_vert => gtk_frame_new("Vertical Button Boxes")
  Call gtk_box_pack_start(GTK_BOX(main_vbox),frame_vert,TRUE,TRUE,10)

  hbox => gtk_hbox_new(FALSE,0)
  Call gtk_container_set_border_width(GTK_CONTAINER(hbox),10)
  Call gtk_container_add(GTK_CONTAINER(frame_vert),hbox)

  Call gtk_box_pack_start(GTK_BOX(hbox), &
                          create_bbox(.False.,"Spread (spacing 5)", &
                                      5,85,20,GTK_BUTTONBOX_SPREAD), &
                          TRUE,TRUE,0)

  Call gtk_box_pack_start(GTK_BOX(hbox), &
                          create_bbox(.False.,"Edge (spacing 30)", &
                                      30,85,20,GTK_BUTTONBOX_EDGE), &
                          TRUE,TRUE,5)

  Call gtk_box_pack_start(GTK_BOX(hbox), &
                          create_bbox(.False.,"Start (spacing 20)", &
                                      20,85,20,GTK_BUTTONBOX_START), &
                          TRUE,TRUE,5)

  Call gtk_box_pack_start(GTK_BOX(hbox), &
                          create_bbox(.False.,"End (spacing 20)", &
                                       20,85,20,GTK_BUTTONBOX_END), &
                          TRUE,TRUE,5)

  Call gtk_widget_show_all(window)

  ! Enter the event loop.
  Call gtk_main

End Program

<<< Previous | Home | Next >>>
Scrolled Windows | Up | Toolbar


Toolbar

Toolbars are usually used to group some number of widgets in order to simplify customization of their look and layout. Typically a toolbar consists of buttons with icons, labels and tooltips, but any other widget can also be put inside a toolbar. Finally, items can be arranged horizontally or vertically and buttons can be displayed with icons, labels, or both.

Creating a toolbar is (as one may already suspect) done with the following function:

Function gtk_toolbar_new() Result(res)
    Type(GtkWidget),Pointer :: res

After creating a toolbar one can append, prepend and insert items (that means simple text strings) or elements (that means any widget types) into the toolbar. To describe an item we need a label text, a tooltip text, a private tooltip text, an icon for the button and a callback function for it. For example, to append or prepend an item you may use the following functions:

Function gtk_toolbar_append_item(toolbar,text,tooltip_text, &
                                 tooltip_private_text,icon, &
                                 callback,user_data) Result(res)
  Type(GtkToolbar),Pointer :: toolbar
  Character(*),Intent(In) :: text,tooltip_text,tooltip_private_text
  Type(GtkWidget),Pointer :: icon
  Type(C_FunPtr),Value :: callback
  Type(C_Ptr) :: user_data
  Type(GtkWidget),Pointer :: res

Function gtk_toolbar_prepend_item(toolbar,text,tooltip_text, &
                                  tooltip_private_text,icon, &
                                  callback,user_data) Result(res)
  Type(GtkToolbar),Pointer :: toolbar
  Character(*),Intent(In) :: text,tooltip_text,tooltip_private_text
  Type(GtkWidget),Pointer :: icon
  Type(C_FunPtr),Value :: callback
  Type(C_Ptr) :: user_data
  Type(GtkWidget),Pointer :: res

If you want to use gtk_toolbar_insert_item, the only additional parameter which must be specified is the position in which the item should be inserted, thus:

Function gtk_toolbar_insert_item(toolbar,text,tooltip_text, &
                                 tooltip_private_text,icon,callback, &
                                 user_data,position) Result(res)
  Type(GtkToolbar),Pointer :: toolbar
  Character(*),Intent(In) :: text,tooltip_text,tooltip_private_text
  Type(GtkWidget),Pointer :: icon
  Type(C_FunPtr),Value :: callback
  Type(C_Ptr) :: user_data
  Integer,Intent(In) :: position
  Type(GtkWidget),Pointer :: res

To simplify adding spaces between toolbar items, you may use the following procedures:

Subroutine gtk_toolbar_append_space(toolbar)
    Type(GtkToolbar),Pointer :: toolbar

Subroutine gtk_toolbar_prepend_space(toolbar)
    Type(GtkToolbar),Pointer :: toolbar

Subroutine gtk_toolbar_insert_space(toolbar,position)
    Type(GtkToolbar),Pointer :: toolbar
    Integer,Intent(In) :: position

If it's required, the orientation of a toolbar and its style can be changed “on the fly” using the following procedures:

Subroutine gtk_toolbar_set_orientation(toolbar,orientation)
    Type(GtkToolbar),Pointer :: toolbar
    Integer(GtkOrientation),Intent(In) :: orientation

Subroutine gtk_toolbar_set_style(toolbar,style)
    Type(GtkToolbar),Pointer :: toolbar
    Integer(GtkToolbarStyle),Intent(In) :: style

Subroutine gtk_toolbar_set_tooltips(toolbar,enable)
    Type(GtkToolbar),Pointer :: toolbar
    Integer,Intent(In) :: enable

Where orientation is one of GTK_ORIENTATION_HORIZONTAL or GTK_ORIENTATION_VERTICAL. The style is used to set appearance of the toolbar items by using one of GTK_TOOLBAR_ICONS, GTK_TOOLBAR_TEXT or GTK_TOOLBAR_BOTH.

To show some other things that can be done with a toolbar, let's take the following program (we'll interrupt the listing with some additional explanations). There is one additional thing though, we include a nice XPM picture to serve as an icon for all of the buttons.

Module toolbar_mod
  Use gtk

  ! This button will emit signal to close application.
  Type(GtkWidget),Pointer :: close_button
  ! To enable/disable tooltips.
  Type(GtkWidget),Pointer :: tooltips_button
  ! Radio buttons for toolbar style.
  Type(GtkWidget),Pointer :: text_button,icon_button,both_button
  ! A text entry to show packing any widget into toolbar.
  Type(GtkWidget),Pointer :: entry
Contains

In fact not all of the above widgets are needed here, but to make things clearer I put them all together.

  ! This function is connected to the Close button or
  ! closing the window from the WM.
  Integer Function delete_event(pwidget,pevent,pdata) Bind(C)
    Type(C_Ptr),Value :: pwidget,pevent,pdata
    Call gtk_main_quit
    delete_event = FALSE
  End Function

The above beginning must seem familiar to you if it's not your first GTK program.

  ! This is easy... when one of the buttons is toggled, we just check
  ! which one is active and set the style of the toolbar accordingly.
  ! ATTENTION: our toolbar is passed as data to callback!
  Subroutine radio_event(pwidget,pdata) Bind(C)
    Type(C_Ptr),Value :: pwidget,pdata

    If (gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(text_button))==TRUE) Then
      Call gtk_toolbar_set_style(GTK_TOOLBAR (pdata),GTK_TOOLBAR_TEXT)
    Else If (gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(icon_button))==TRUE) Then
      Call gtk_toolbar_set_style(GTK_TOOLBAR (pdata),GTK_TOOLBAR_ICONS)
    Else If (gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(both_button))==TRUE) Then
      Call gtk_toolbar_set_style(GTK_TOOLBAR(pdata),GTK_TOOLBAR_BOTH)
    End If
  End Subroutine

  ! Even easier, just check given toggle button and enable/disable tooltips.
  Subroutine toggle_event(pwidget,pdata) Bind(C)
    Type(C_Ptr),Value :: pwidget,pdata
    Call gtk_toolbar_set_tooltips(GTK_TOOLBAR (pdata), &
                                  gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(pwidget)))
  End Subroutine

End Module

The above are just two callback functions that will be called when one of the buttons on a toolbar is pressed. You should already be familiar with things like this if you've already used toggle buttons (and radio buttons).

Program main
  Use toolbar_mod

  ! Here is our main window (a dialogue) and a handle for the handlebox.
  Type(GtkWidget),Pointer :: dialogue,handlebox

  ! Ok, we need a toolbar, an icon with a mask (one for all of the buttons)
  ! and an icon widget to put this icon in (but we'll create a separate widget
  ! for each button).
  Type(GtkWidget),Pointer :: toolbar,iconw

  ! Convenience variables.
  Type(GtkDialog),Pointer :: dptr
  Type(GValue),Pointer :: gval

  ! this is called in all GTK applications.
  Call gtk_init

  ! Create a new window with a given title, and nice size.
  dialogue => gtk_dialog_new()
  Call gtk_window_set_title(GTK_WINDOW(dialogue),"GTKToolbar Tutorial")
  Call gtk_widget_set_size_request(GTK_WIDGET(dialogue),600,300)

  ! Set allow_shrink property to TRUE.
  Allocate(gval)
  Call g_value_set_boolean(g_value_init(gval,G_TYPE_BOOLEAN),TRUE)
  Call g_object_set_property(G_OBJECT(dialogue),'allow_shrink',gval)
  Deallocate(gval)

  ! Typically we quit if someone tries to close us.
  Call g_signal_connect(G_OBJECT(dialogue),"delete_event", &
                        C_FunLoc(delete_event),C_Null_Ptr)

  ! We need to realize the window because we use pixmaps for
  ! items on the toolbar.
  Call gtk_widget_realize(dialogue)

  ! To make it nice we'll put the toolbar into the handle box,
  ! so that it can be detached from the main window.
  handlebox => gtk_handle_box_new()
  dptr => GTK_DIALOG(dialogue)
  Call gtk_box_pack_start(GTK_BOX(dptr%vbox),handlebox,FALSE,FALSE,5)

The above should be similar to any other GTK application. Just initialization of GTK, creating the window, etc.. There is only one thing that probably needs some explanation: a handle box. A handle box is just another box that can be used to pack widgets into. The difference between it and typical boxes is that it can be detached from a parent window (actually the handle box remains in the parent, but it is reduced to a tiny rectangle, while all of its contents are reparented to a new freely floating window). It is usually nice to have a detachable toolbar, so these two widgets occur together quite often.

  ! Toolbar will be horizontal, with both icons and text, and with 5 pixel
  ! spaces between items; finally, we'll also put it into our handlebox.
  toolbar => gtk_toolbar_new()
  Call gtk_toolbar_set_orientation(GTK_TOOLBAR(toolbar), &
                                   GTK_ORIENTATION_HORIZONTAL)
  Call gtk_toolbar_set_style(GTK_TOOLBAR(toolbar),GTK_TOOLBAR_BOTH)
  Call gtk_container_set_border_width(GTK_CONTAINER(toolbar),5)
  Call gtk_container_add(GTK_CONTAINER(handlebox),toolbar)

Well, what we do above is just a straightforward initialization of the toolbar widget.

  ! Our first item is the Close button.
  iconw => gtk_image_new_from_file("gtk.xpm") ! Icon widget.
  close_button => &
    gtk_toolbar_append_item(GTK_TOOLBAR(toolbar), & ! Our toolbar.
                             "Close",             & ! Button label.
                             "Closes this app",   & ! This button's tooltip.
                             "Private",           & ! Tooltip private info.
                             iconw,               & ! Icon widget.
                             C_FunLoc(delete_event), & ! A signal.
                             C_Null_Ptr)
  Call gtk_toolbar_append_space(GTK_TOOLBAR(toolbar)) ! Space after item.

In the above code you see the simplest case: adding a button to toolbar. Just before appending a new item, we have to construct an image widget to serve as an icon for this item; this step will have to be repeated for each new item. Just after the item we also add a space, so the following items will not touch each other. As you see, gtk_toolbar_append_item returns a pointer to our newly created button widget, so that we can work with it in the normal way.

  ! Now, let's make our radio buttons group...
  iconw => gtk_image_new_from_file ("gtk.xpm")
  icon_button => &
    gtk_toolbar_append_element( &
      GTK_TOOLBAR (toolbar), &
      GTK_TOOLBAR_CHILD_RADIOBUTTON, & ! A type of element.
      Null(),                        & ! Pointer to widget.
      "Icon",                        & ! Label.
      "Only icons in toolbar",       & ! Tooltip.
      "Private",                     & ! Tooltip private string.
      iconw,                         & ! Icon.
      C_FunLoc(radio_event),         & ! Signal.
      C_Loc(toolbar))                  ! Data for signal.
  Call gtk_toolbar_append_space(GTK_TOOLBAR(toolbar))

Here we begin creating a radio buttons group. To do this we use gtk_toolbar_append_element. In fact, using this function one can also add simple items or even spaces (type = GTK_TOOLBAR_CHILD_SPACE or GTK_TOOLBAR_CHILD_BUTTON). In the above case we start creating a radio group. In creating other radio buttons for this group a pointer to the previous button in the group is required, so that a list of buttons can be easily constructed (see the section on Radio Buttons earlier in this tutorial).

  ! Following radio buttons refer to previous ones.
  iconw => gtk_image_new_from_file ("gtk.xpm")
  text_button => &
    gtk_toolbar_append_element(GTK_TOOLBAR(toolbar), &
                               GTK_TOOLBAR_CHILD_RADIOBUTTON, &
                               icon_button, &
                               "Text", &
                               "Only texts in toolbar", &
                               "Private", &
                               iconw, &
                               C_FunLoc(radio_event), &
                               C_Loc(toolbar))
  Call gtk_toolbar_append_space(GTK_TOOLBAR(toolbar))

  iconw => gtk_image_new_from_file("gtk.xpm")
  both_button => &
    gtk_toolbar_append_element(GTK_TOOLBAR(toolbar), &
                               GTK_TOOLBAR_CHILD_RADIOBUTTON, &
                               text_button, &
                               "Both", &
                               "Icons and text in toolbar", &
                               "Private", &
                               iconw, &
                               C_FunLoc(radio_event), &
                               C_Loc(toolbar))
  Call gtk_toolbar_append_space(GTK_TOOLBAR(toolbar))
  Call gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(both_button),TRUE)

In the end we have to set the state of one of the buttons manually (otherwise they all stay in active state, preventing us from switching between them).

  ! Here we have just a simple toggle button.
  iconw => gtk_image_new_from_file ("gtk.xpm");
  tooltips_button => &
    gtk_toolbar_append_element(GTK_TOOLBAR (toolbar), &
                               GTK_TOOLBAR_CHILD_TOGGLEBUTTON, &
                               Null(), &
                               "Tooltips", &
                               "Toolbar with or without tips", &
                               "Private", &
                               iconw, &
                               C_FunLoc(toggle_event), &
                               C_Loc(toolbar))
  Call gtk_toolbar_append_space(GTK_TOOLBAR (toolbar))
  Call gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON (tooltips_button),TRUE)

A toggle button can be created in the obvious way (if one knows how to create radio buttons already).

  ! To pack a widget into toolbar, we only have to create it and
  ! append it with an appropriate tooltip.
  entry => gtk_entry_new()
  Call gtk_toolbar_append_widget(GTK_TOOLBAR(toolbar), &
                                 entry, &
                                 "This is just an entry", &
                                 "Private")

  ! Well, it isn't created within the toolbar, so we must still show it.
  Call gtk_widget_show(entry)

As you see, adding any kind of widget to a toolbar is simple. The one thing you have to remember is that this widget must be shown manually (contrary to other items which will be shown together with the toolbar).

  ! That's it ! let's show everything.
  Call gtk_widget_show(toolbar)
  Call gtk_widget_show(handlebox)
  Call gtk_widget_show(dialogue)

  ! Rest in gtk_main and wait for the fun to begin!
  Call gtk_main

End Program

So, here we are at the end of toolbar tutorial. Of course, to appreciate it in full you need also this nice XPM icon, so here it is (the format of an XPM file is the same as that of a C header file): you should save this as “gtk.xpm”.

/* XPM */
static char * gtk_xpm[] = {
"32 39 5 1",
".      c none",
"+      c black",
"@      c #3070E0",
"#      c #F05050",
"$      c #35E035",
"................+...............",
"..............+++++.............",
"............+++++@@++...........",
"..........+++++@@@@@@++.........",
"........++++@@@@@@@@@@++........",
"......++++@@++++++++@@@++.......",
".....+++@@@+++++++++++@@@++.....",
"...+++@@@@+++@@@@@@++++@@@@+....",
"..+++@@@@+++@@@@@@@@+++@@@@@++..",
".++@@@@@@+++@@@@@@@@@@@@@@@@@@++",
".+#+@@@@@@++@@@@+++@@@@@@@@@@@@+",
".+##++@@@@+++@@@+++++@@@@@@@@$@.",
".+###++@@@@+++@@@+++@@@@@++$$$@.",
".+####+++@@@+++++++@@@@@+@$$$$@.",
".+#####+++@@@@+++@@@@++@$$$$$$+.",
".+######++++@@@@@@@++@$$$$$$$$+.",
".+#######+##+@@@@+++$$$$$$@@$$+.",
".+###+++##+##+@@++@$$$$$$++$$$+.",
".+###++++##+##+@@$$$$$$$@+@$$@+.",
".+###++++++#+++@$$@+@$$@++$$$@+.",
".+####+++++++#++$$@+@$$++$$$$+..",
".++####++++++#++$$@+@$++@$$$$+..",
".+#####+++++##++$$++@+++$$$$$+..",
".++####+++##+#++$$+++++@$$$$$+..",
".++####+++####++$$++++++@$$$@+..",
".+#####++#####++$$+++@++++@$@+..",
".+#####++#####++$$++@$$@+++$@@..",
".++####++#####++$$++$$$$$+@$@++.",
".++####++#####++$$++$$$$$$$$+++.",
".+++####+#####++$$++$$$$$$$@+++.",
"..+++#########+@$$+@$$$$$$+++...",
"...+++########+@$$$$$$$$@+++....",
".....+++######+@$$$$$$$+++......",
"......+++#####+@$$$$$@++........",
".......+++####+@$$$$+++.........",
".........++###+$$$@++...........",
"..........++##+$@+++............",
"...........+++++++..............",
".............++++..............."};

<<< Previous | Home | Next >>>
Button Boxes | Up | Notebooks


Notebooks

The NoteBook Widget is a collection of “pages” that overlap each other, each page contains different information with only one page visible at a time. This widget has become more common lately in GUI programming, and it is a good way to show blocks of similar information that warrant separation in their display.

The first function call you will need to know, as you can probably guess by now, is used to create a new notebook widget.

Function gtk_notebook_new() Result(res)
    Type(GtkWidget),Pointer :: res

Once the notebook has been created, there are a number of procedures that operate on the notebook widget. Let's look at them individually.

The first one we will look at is how to position the page indicators. These page indicators or “tabs” as they are referred to, can be positioned in four ways: top, bottom, left, or right.

Subroutine gtk_notebook_set_tab_pos(notebook,pos)
    Type(GtkNotebook),Pointer :: notebook
    Integer(GtkPositionType),Intent(In) :: pos

The pos argument will be one of the following, which are pretty self explanatory: GTK_POS_LEFT, GTK_POS_RIGHT, GTK_POS_TOP (the default) and GTK_POS_BOTTOM.

Next we will look at how to add pages to the notebook. There are three ways to add pages to the NoteBook. Let's look at the first two together as they are quite similar.

Integer(gint) Function gtk_notebook_append_page(notebook,child,tab_label)
  Type(GtkNotebook),Pointer :: notebook
  Type(GtkWidget),Pointer :: child,tab_label

Integer(gint) Function gtk_notebook_prepend_page(notebook,child,tab_label)
  Type(GtkNotebook),Pointer :: notebook
  Type(GtkWidget),Pointer :: child,tab_label

These functions add pages to the notebook by inserting them from the back of the notebook (append), or the front of the notebook (prepend). child is the widget that is placed within the notebook page, and tab_label is the label for the page being added. The child widget must be created separately, and is typically a set of options setup witin one of the other container widgets, such as a table.

The final procedure for adding a page to the notebook contains all of the properties of the previous two, but it allows you to specify what position you want the page to be in the notebook.

Integer(gint) Function gtk_notebook_insert_page(notebook,child,tab_label, &
                                                position)
    Type(GtkNotebook),Pointer :: notebook
    Type(GtkWidget),Pointer :: child,tab_label
    Integer,Intent(In) :: position

The parameters are the same as _append_ and _prepend_ except it contains an extra parameter, position. This parameter is used to specify where this page will be inserted; the 1st page is position 0, the 2nd page is position 1, etc..

Now that we know how to add a page, lets see how we can remove a page from the notebook.

Subroutine gtk_notebook_remove_page(notebook,page_num)
    Type(GtkNotebook),Pointer :: notebook
    Integer,Intent(In) :: page_num

This function takes the page specified by page_num and removes it from the widget pointed to by notebook.

To find out what the current page is in a notebook use the function:

Integer Function gtk_notebook_get_current_page(notebook)
    Type(GtkNotebook),Pointer :: notebook

These next two procedures are simple calls to move the notebook page forward or backward. Simply provide the respective function call with the notebook widget you wish to operate on. Note that if the NoteBook is on the last page and gtk_notebook_next_page is called, the notebook will wrap back to the first page. Likewise, if the NoteBook is on the first page and gtk_notebook_prev_page is called, the notebook will wrap to the last page.

Subroutine gtk_notebook_next_page(notebook)
    Type(GtkNotebook),Pointer :: notebook

Subroutine gtk_notebook_prev_page(notebook)
    Type(GtkNotebook),Pointer :: notebook

This next procedure sets the “active” page. If you wish the notebook to be opened to page 5 for example, you would use this procedure. Otherwise, the notebook defaults to the first page.

Subroutine gtk_notebook_set_current_page(notebook,page_num)
    Type(GtkNotebook),Pointer :: notebook
    Integer,Intent(In) :: page_num

The next two procedures add or remove the notebook page tabs and the notebook border respectively.

Subroutine gtk_notebook_set_show_tabs(notebook,show_tabs)
    Type(GtkNotebook),Pointer :: notebook
    Integer(gboolean),Intent(In) :: show_tabs

Subroutine gtk_notebook_set_show_border(notebook,show_border)
    Type(GtkNotebook),Pointer :: notebook
    Integer(gboolean),Intent(In) :: show_border

The next procedure is useful when the you have a large number of pages, and the tabs don't fit on the page. It allows the tabs to be scrolled through using two arrow buttons.

Subroutine gtk_notebook_set_scrollable(notebook,scrollable)
    Type(GtkNotebook),Pointer :: notebook
    Integer(gboolean),Intent(In) :: scrollable

show_tabs, show_border and scrollable can be either TRUE or FALSE.

Now let's look at an example. This small program creates a window with a notebook and six buttons. The notebook contains 11 pages, added in three different ways, appended, inserted, and prepended. The buttons allow you rotate the tab positions, add/remove the tabs and border, remove a page, change pages in both a forward and backward manner, and exit the program.

Module note_books
  Use gtk

Contains

  ! This function rotates the position of the tabs.
  Subroutine rotate_book(button,notebook) Bind(C,Name='')
    Type(C_Ptr),Value :: button,notebook

    Integer :: pos
    pos = gtk_notebook_get_tab_pos(GTK_NOTEBOOK(notebook))
    Call gtk_notebook_set_tab_pos(GTK_NOTEBOOK(notebook),MOD(pos+1,4))
  End Subroutine

  ! Add/Remove the page tabs and the borders.
  Subroutine tabsborder_book(button,notebook) Bind(C,Name='')
    Type(C_Ptr),Value :: button,notebook

    Integer(gboolean) :: bval,tval

    tval = FALSE
    bval = FALSE
    If (gtk_notebook_get_show_tabs(GTK_NOTEBOOK(notebook))==FALSE) Then
      tval = TRUE
    End If
    If (gtk_notebook_get_show_border(GTK_NOTEBOOK(notebook))==FALSE) Then
      bval = TRUE
    End If
    Call gtk_notebook_set_show_tabs(GTK_NOTEBOOK(notebook),tval)
    Call gtk_notebook_set_show_border(GTK_NOTEBOOK(notebook),bval)
  End Subroutine

  ! Remove a page from the notebook.
  Subroutine remove_book(button,notebook) Bind(C,Name='')
    Type(C_Ptr),Value :: button,notebook

    Integer :: page
    page = gtk_notebook_get_current_page(GTK_NOTEBOOK(notebook))
    Call gtk_notebook_remove_page(GTK_NOTEBOOK(notebook),page)
    ! Need to refresh the widget -- this forces the widget to redraw itself.
    Call gtk_widget_queue_draw(GTK_WIDGET(notebook))
  End Subroutine

  Subroutine my_gtk_notebook_next_page(object) Bind(C,Name='')
    Type(C_Ptr),Value :: object

    Call gtk_notebook_next_page(GTK_NOTEBOOK(object))
  End Subroutine

  Subroutine my_gtk_notebook_prev_page(object) Bind(C,Name='')
    Type(C_Ptr),Value :: object

    Call gtk_notebook_prev_page(GTK_NOTEBOOK(object))
  End Subroutine

End Module

Program note_book_example
  Use note_books
  Implicit None

  Type(GtkWidget),Pointer :: window,button,table,notebook,frame,label,checkbutton
  Integer :: i,res
  Character(32) :: bufferf,bufferl

  Call gtk_init

  window => gtk_window_new(GTK_WINDOW_TOPLEVEL)

  Call g_signal_connect(G_OBJECT(window),"delete_event", &
                        C_FunLoc(gtk_main_quit),C_Null_Ptr)

  Call gtk_container_set_border_width(GTK_CONTAINER(window),10)

  table => gtk_table_new(3,6,FALSE)
  Call gtk_container_add(GTK_CONTAINER(window),table)

  ! Create a new notebook, place the position of the tabs.
  notebook => gtk_notebook_new()
  Call gtk_notebook_set_tab_pos(GTK_NOTEBOOK(notebook),GTK_POS_TOP)
  Call gtk_table_attach_defaults(GTK_TABLE(table),notebook,0,6,0,1)
  Call gtk_widget_show(notebook)

  ! Let's append a bunch of pages to the notebook.
  Do i=0,4
    Write (bufferf,'("Append Frame ",I0)') i + 1
    Write (bufferl,'("Page ",I0)') i + 1

    frame => gtk_frame_new(Trim(bufferf))
    Call gtk_container_set_border_width(GTK_CONTAINER(frame),10)
    Call gtk_widget_set_size_request(frame,100,75)
    Call gtk_widget_show(frame)

    label => gtk_label_new(Trim(bufferf))
    Call gtk_container_add(GTK_CONTAINER(frame),label)
    Call gtk_widget_show(label)

    label => gtk_label_new(Trim(bufferl))
    res = gtk_notebook_append_page(GTK_NOTEBOOK(notebook),frame,label)
  End Do

  ! Now let's add a page to a specific spot.
  checkbutton => gtk_check_button_new_with_label("Check me please!")
  Call gtk_widget_set_size_request(checkbutton,100,75)
  Call gtk_widget_show(checkbutton)

  label => gtk_label_new("Add page")
  res = gtk_notebook_insert_page(GTK_NOTEBOOK(notebook),checkbutton,label,2)

  ! Now let's prepend pages to the notebook.
  Do i=0,4
    Write (bufferf,'("Prepend Frame ",I0)') i + 1
    Write (bufferl,'("PPage ",I0)') i + 1

    frame => gtk_frame_new(Trim(bufferf))
    Call gtk_container_set_border_width(GTK_CONTAINER(frame),10)
    Call gtk_widget_set_size_request(frame,100,75)
    Call gtk_widget_show(frame)

    label => gtk_label_new(Trim(bufferf))
    Call gtk_container_add(GTK_CONTAINER(frame),label)
    Call gtk_widget_show(label)

    label => gtk_label_new(Trim(bufferl))
    res = gtk_notebook_prepend_page(GTK_NOTEBOOK(notebook),frame,label)
  End Do

  ! Set what page to start at (page 4).
  Call gtk_notebook_set_current_page(GTK_NOTEBOOK(notebook),3)

  ! Create a bunch of buttons.
  button => gtk_button_new_with_label("close")
  Call g_signal_connect_swapped(G_OBJECT(button),"clicked", &
                                C_FunLoc(gtk_main_quit),C_Null_Ptr)
  Call gtk_table_attach_defaults(GTK_TABLE(table),button,0,1,1,2)
  Call gtk_widget_show(button)

  button => gtk_button_new_with_label("next page")
  Call g_signal_connect_swapped(G_OBJECT(button),"clicked", &
                                C_FunLoc(my_gtk_notebook_next_page), &
                                C_Loc(notebook))
  Call gtk_table_attach_defaults(GTK_TABLE(table),button,1,2,1,2)
  Call gtk_widget_show(button)

  button => gtk_button_new_with_label("prev page")
  Call g_signal_connect_swapped(G_OBJECT(button),"clicked", &
                                C_FunLoc(my_gtk_notebook_prev_page), &
                                C_Loc(notebook))
  Call gtk_table_attach_defaults(GTK_TABLE(table),button,2,3,1,2)
  Call gtk_widget_show(button)

  button => gtk_button_new_with_label("tab position")
  Call g_signal_connect(G_OBJECT(button),"clicked", &
                        C_FunLoc(rotate_book),C_Loc(notebook))
  Call gtk_table_attach_defaults(GTK_TABLE(table),button,3,4,1,2)
  Call gtk_widget_show(button)

  button => gtk_button_new_with_label("tabs/border on/off")
  Call g_signal_connect(G_OBJECT(button),"clicked", &
                        C_FunLoc(tabsborder_book),C_Loc(notebook))
  Call gtk_table_attach_defaults(GTK_TABLE(table),button,4,5,1,2)
  Call gtk_widget_show(button)

  button => gtk_button_new_with_label("remove page")
  Call g_signal_connect(G_OBJECT(button),"clicked", &
                        C_FunLoc(remove_book),C_Loc(notebook))
  Call gtk_table_attach_defaults(GTK_TABLE (table),button,5,6,1,2)
  Call gtk_widget_show(button)

  Call gtk_widget_show(table)
  Call gtk_widget_show(window)

  Call gtk_main

End Program

I hope this helps you on your way with creating notebooks for your GTK applications.

<<< Previous | Home | Next >>>
Toolbar | Up | Menu Widget


Menu Widget

There are two ways to create menus: there's the easy way, and there's the hard way. Both have their uses, but you can usually use the Itemfactory (the easy way). The hard way is to create all the menus using the calls directly. The easy way is to use the gtk_item_factory calls. This is much simpler, but there are advantages and disadvantages to each approach.

The Itemfactory is much easier to use, and to add new menus to, although writing a few wrapper functions to create menus using the manual method could go a long way towards usability. With the Itemfactory, it is not possible to add images or the character ‘/’ to the menus.

Manual Menu Creation

In the true tradition of teaching, we'll show you the hard way first. :)

There are three widgets that go into making a menubar and submenus:

  1. a menu item, which is what the user wants to select, e.g., “Save”;
  2. a menu, which acts as a container for the menu items;
  3. a menubar, which is a container for each of the individual menus.

This is slightly complicated by the fact that menu item widgets are used for two different things. They are both the widgets that are packed into the menu, and the widget that is packed into the menubar, which, when selected, activates the menu.

Let's look at the functions that are used to create menus and menubars. The first function is used to create a new menubar.

Function gtk_menu_bar_new() Result(res)
    Type(GtkWidget),Pointer :: res

This rather self explanatory function creates a new menubar. You use gtk_container_add to pack this into a window, or the box_pack procedures to pack it into a box — the same as buttons.

Function gtk_menu_new() Result(res)
    Type(GtkWidget),Pointer :: res

This function returns a pointer to a new menu; it is never actually shown (with gtk_widget_show), it is just a container for the menu items. I hope this will become more clear when you look at the example below.

The next three functions are used to create menu items that are packed into the menu (and menubar).

Function gtk_menu_item_new() Result(res)
  Type(GtkWidget),Pointer :: res

Function gtk_menu_item_new_with_label(label) Result(res)
  Character(*),Intent(In) :: label
  Type(GtkWidget),Pointer :: res

Function gtk_menu_item_new_with_mnemonic(label) Result(res)
  Character(*),Intent(In) :: label
  Type(GtkWidget),Pointer :: res

These calls are used to create the menu items that are to be displayed. Remember to differentiate between a “menu” created by gtk_menu_new and a “menu item” created by the gtk_menu_item_new functions. The menu item will be an actual button with an associated action, whereas a menu will be a container holding menu items.

The gtk_menu_item_new_with_label and gtk_menu_item_new functions are just as you'd expect after reading about the buttons. One creates a new menu item with a label already packed into it, and the other just creates a blank menu item.

Once you've created a menu item you have to put it into a menu. This is done using the function gtk_menu_shell_append. In order to capture when the item is selected by the user, we need to connect to the activate signal in the usual way. So, if we wanted to create a standard File menu, with the options Open, Save, and Quit, the code would look something like:

  Character(80),Target :: file_open = "file.open"//C_Null_Char, &
                          file_save = "file.save"//C_Null_Char, &
                          file_quit = "file.quit"//C_Null_Char

  file_menu => gtk_menu_new()    ! Don't need to show menus.

  ! Create the menu items.
  open_item => gtk_menu_item_new_with_label("Open")
  save_item => gtk_menu_item_new_with_label("Save")
  quit_item => gtk_menu_item_new_with_label("Quit")

  ! Add them to the menu.
  call gtk_menu_shell_append(GTK_MENU_SHELL(file_menu),open_item)
  call gtk_menu_shell_append(GTK_MENU_SHELL(file_menu),save_item)
  call gtk_menu_shell_append(GTK_MENU_SHELL(file_menu),quit_item)

  ! Attach the callback functions to the activate signal.
  Call g_signal_connect_swapped(G_OBJECT(open_item),"activate", &
                                C_FunLoc(menuitem_response),C_Loc(file_open))
  Call g_signal_connect_swapped(G_OBJECT(save_item),"activate", &
                                C_FunLoc(menuitem_response),C_Loc(file_save))

  ! We can attach the Quit menu item to our exit function.
  Call g_signal_connect_swapped(G_OBJECT(quit_item),"activate", &
                                C_FunLoc(destroy),C_Loc(file_quit))

  ! We do need to show menu items.
  Call gtk_widget_show(open_item)
  Call gtk_widget_show(save_item)
  Call gtk_widget_show(quit_item)

At this point we have our menu. Now we need to create a menubar and a menu item for the File entry, to which we add our menu. The code looks like this:

  menu_bar => gtk_menu_bar_new()
  Call gtk_container_add(GTK_CONTAINER(window),menu_bar)
  Call gtk_widget_show(menu_bar)

  file_item => gtk_menu_item_new_with_label("File")
  Call gtk_widget_show(file_item)

Now we need to associate the menu with file_item. This is done with the procedure
Subroutine gtk_menu_item_set_submenu(menu_item,submenu)
    Type(GtkMenuItem),Pointer :: menu_item
    Type(GtkWidget),Pointer :: submenu

So, our example would continue with
    Call gtk_menu_item_set_submenu(GTK_MENU_ITEM(file_item),file_menu)

All that is left to do is to add the menu to the menubar, which is accomplished using the procedure
Subroutine gtk_menu_bar_append(menu_bar,child)
    Type(GtkMenuBar),Pointer :: menu_bar
    Type(GtkWidget),Pointer :: child
which in our case looks like this:
    Call gtk_menu_bar_append(GTK_MENU_BAR(C_Loc(menu_bar)),file_item)

If we wanted the menu right justified on the menubar, such as help menus often are, we can use the following procedure (again on file_item in the current example) before attaching it to the menubar.

Subroutine gtk_menu_item_right_justify(menu_item)
    Type(GtkMenuItem),Pointer :: menu_item

Here is a summary of the steps needed to create a menu bar with menus attached:

  1. Create a new menu using gtk_menu_new.
  2. Call gtk_menu_item_new for each item you wish to have on your menu, and use gtk_menu_shell_append to put each of these new items on to the menu.
  3. Create a menu item using gtk_menu_item_new. This will be the root of the menu, the text appearing here will be on the menubar itself.
  4. Use gtk_menu_item_set_submenu to attach the menu to the root menu item (the one created in the above step).
  5. Create a new menubar using gtk_menu_bar_new. This step only needs to be done once when creating a series of menus on one menu bar.
  6. Use gtk_menu_bar_append to put the root menu onto the menubar.

Creating a popup menu is nearly the same. The difference is that the menu is not posted automatically by a menubar, but explicitly by calling the function gtk_menu_popup, e.g. from a button-press event. Take these steps:

  1. Create an event handling function. It needs to have the interface
    Integer Function handler(widget,event) Bind(C)
  Type(C_Ptr),Value :: widget,event
    and it will use the event to find out where to pop up the menu. To access the widget and event entities directly, you might find it useful to do

      Type(GtkWidget),Pointer :: pwidget
  Type(GtkEvent),Pointer :: pevent
  pwidget => GTK_WIDGET(widget)
  Call C_F_Pointer(event,pevent)

  2. In the event handler, if the event is a mouse button press, treat event as a button event (which it is) and use it as shown in the sample code to pass information to gtk_menu_popup.

  3. Bind that event handler to a widget with
        Call g_signal_connect_swapped(G_OBJECT(widget),"event", &
                                  C_FunLoc(handler),C_Loc(menu))
    where widget is the widget you are binding to, handler is the handling function, and menu is a menu created with gtk_menu_new. This can be a menu which is also posted by a menu bar, as shown in the sample code.

<<< Previous | Home | Next >>>
Notebooks |  | Manual Menu Example


Manual Menu Example

That should about do it. Let's take a look at an example to help clarify.

Module manual_menu
  Use gtk
  Use gdk
  Use glib
  Implicit None

Contains

  ! Respond to a button-press by posting a menu passed in as widget.
  !
  ! Note that the widget argument is the menu being posted, NOT
  ! the button that was pressed.
  Integer(gboolean) Function button_press(pwidget,pevent) Bind(C,Name='')
    Type(C_Ptr),Value :: pwidget,pevent
    Integer(GdkEventType),Pointer :: etype
    Type(GdkEventButton),Pointer :: bevent

    Call C_F_Pointer(pevent,etype)

    If (etype==GDK_BUTTON_PRESS) Then
      Call C_F_Pointer(pevent,bevent)
      Call gtk_menu_popup(GTK_MENU(pwidget),Null(),Null(),C_Null_FunPtr, &
                          C_Null_Ptr,bevent%button,bevent%time)
      ! Tell calling code that we have handled this event;
      ! the buck stops here.
      button_press = TRUE
    Else
      ! Tell calling code that we have not handled this event; pass it on.
      button_press = FALSE
    End If
  End Function

  ! Print a string when a menu item is selected.
  Subroutine menuitem_response(string) Bind(C,Name='')
    Type(C_Ptr),Value :: string
    Print *,g_cstring_cptr_to_fstring_scalar_ptr(string)
  End Subroutine

End Module

Program main
  Use manual_menu

  Type(GtkWidget),Pointer :: window,menu,menu_bar,root_menu,menu_items, &
                             vbox,button
  Character(128),Target :: buf
  Type(C_Ptr) :: pbuf
  Integer :: i,buflen

  Call gtk_init

  ! Create a new window.
  window => gtk_window_new(GTK_WINDOW_TOPLEVEL)
  Call gtk_widget_set_size_request(GTK_WIDGET(window),200,100)
  Call gtk_window_set_title(GTK_WINDOW(window),"GTK Menu Test")
  Call g_signal_connect(G_OBJECT(window),"delete_event", &
                        C_FunLoc(gtk_main_quit),c_null_ptr)

  ! Init the menu-widget, and remember -- never
  ! gtk_show_widget() the menu widget!!
  ! This is the menu that holds the menu items, the one that
  ! will pop up when you click on the "Root Menu".
  menu => gtk_menu_new()

  ! Next we make a little loop that makes three menu-entries for "test-menu".
  ! Notice the call to gtk_menu_shell_append.  Here we are adding a list of
  ! menu items to our menu.  Normally, we'd also catch the "clicked"
  ! signal on each of the menu items and setup a callback for it,
  ! but it's omitted here to save space.
  Do i=0,2
    ! Write a new menu name, and get its length.
    Write(buf,'("Test-undermenu - ",I0)') i
    buflen = Len_Trim(buf)

    ! Create a new menu-item with that name.
    menu_items => gtk_menu_item_new_with_label(buf(:buflen))

    ! ...and add it to the menu.
    Call gtk_menu_shell_append(GTK_MENU_SHELL(menu),menu_items)

    ! Do something interesting when the menuitem is selected.
    pbuf = g_fstrdup(buf(:buflen))
    Call g_signal_connect_swapped(G_OBJECT(menu_items),"activate", &
                                    C_FunLoc(menuitem_response),pbuf)

    ! Show the widget.
    Call gtk_widget_show(menu_items)
  End Do

  ! This is the root menu, and will be the label displayed on the menu bar.
  ! There won't be a signal handler attached, as it only pops up the rest of
  ! the menu when pressed.
  root_menu => gtk_menu_item_new_with_label("Root Menu")

  Call gtk_widget_show(root_menu)

  ! Now we specify that we want our newly created "menu"
  ! to be the menu for the"root menu".
  Call gtk_menu_item_set_submenu(GTK_MENU_ITEM(root_menu),menu)

  ! A vbox to put a menu and a button in.
  vbox => gtk_vbox_new(FALSE,0)
  Call gtk_container_add(GTK_CONTAINER(window),vbox)
  Call gtk_widget_show(vbox)

  ! Create a menu-bar to hold the menus and add it to our main window.
  menu_bar => gtk_menu_bar_new()
  Call gtk_box_pack_start(GTK_BOX(vbox),menu_bar,FALSE,FALSE,2)
  Call gtk_widget_show(menu_bar)

  ! Create a button to which to attach menu as a popup.
  button => gtk_button_new_with_label("press me")
  Call g_signal_connect_swapped(G_OBJECT(button),"event", &
                                C_FunLoc(button_press),C_Loc(menu))
  Call gtk_box_pack_end(GTK_BOX(vbox),button,TRUE,TRUE,2)
  Call gtk_widget_show(button)

  ! And finally we append the menu-item to the menu-bar -- this is the
  ! "root" menu-item I have been raving about =).
  Call gtk_menu_shell_append(GTK_MENU_SHELL(menu_bar),root_menu)

  ! Always display the window as the last step so it all splashes on
  ! the screen at once.
  Call gtk_widget_show(window)

  Call gtk_main

End Program

You may also set a menu item to be insensitive and, using an accelerator table, bind keys to menu functions.

<<< Previous | Home | Next >>>
Menu Widget | Up | Using ItemFactory


Using ItemFactory

Now that we've shown you the hard way, here's how you do it using the gtk_item_factory calls.

ItemFactory creates a menu out of an array of ItemFactory entries. This means you can define your menu in its simplest form and then create the menu/menubar widgets with a minimum of function calls.

ItemFactory entries

At the core of ItemFactory is the ItemFactoryEntry. This structure defines one menu item, and when an array of these entries is defined a whole menu is formed. The ItemFactory entry struct definition looks like this:

Type,Bind(C) :: GtkItemFactoryEntry
    Type(C_Ptr) :: path = c_null_ptr
    Type(C_Ptr) :: accelerator = c_null_ptr
    Type(C_FunPtr) :: callback = c_null_funptr
    Integer(C_int) :: callback_action
    Type(C_Ptr) :: item_type = c_null_ptr
    Type(C_Ptr) :: extra_data = c_null_ptr
End Type

Each field defines part of the menu item.

path is a pointer to a null-terminated string which defines both the name and the path of a menu item; for example, "/File/Open" would be the name of a menu item which would come under the ItemFactory entry with path "/File". Note however that "/File/Open" would be displayed in the File menu as "Open". Also note since the forward slashes are used to define the path of the menu, they cannot be used as part of the name. A letter preceded by an underscore indicates an accelerator (shortcut) key once the menu is open.

Note that all strings need to be null-terminated because the whole data structure will be interpreted by a C routine, and C expects strings to be null-terminated.

accelerator is a pointer to a null-terminated string that indicates a key combination that can be used as a shortcut to that menu item. The string can be made up of either a single character, or a combination of modifier keys with a single character. It is case insensitive.

The available modifier keys are:
"<ALT>" | Alt
"<CTL>", "<CTRL>" or "<CONTROL>" | Control
"<MOD1>" to "<MOD5>" | Modifier N
"<SHFT>" or "<SHIFT>" | Shift

Examples:

"<ConTroL>a"
"<SHFT><ALT><CONTROL>X"

callback is the procedure that is called when the menu item emits the “activate” signal. The form of the callback is described in the Callback Description section.

The value of callback_action is passed to the callback procedure. It also affects the procedure interface, as shown in the Callback Description section.

item_type is a pointer to a string that defines what type of widget is created and packed into the menu items container. It can be:

NULL or "" or "<Item>" - a simple item
"<Title>"              - a title item
"<CheckItem>"          - a check item
"<ToggleItem>"         - a toggle item
"<RadioItem>"          - a (root) radio item
"Path"                 - a sister radio item
"<Tearoff>"            - a tearoff
"<Separator>"          - a separator
"<Branch>"             - an item to hold submenus (optional)
"<LastBranch>"         - a right justified branch
"<StockItem>"          - a simple item with a stock image

Note that <LastBranch> is only useful for one submenu of a menubar. The visual rendering of <StockItem> depends on the value supplied as extra_data; stock images are available via the character strings defined as GTK_STOCK_* in the GTK module.

Callback Description

The callback for an ItemFactory entry can take two forms. If callback_action is zero, it is of the form
Subroutine callback() Bind(C)
otherwise it is of the form
Subroutine callback(callback_data,callback_action,widget) Bind(C)
    Type(C_Ptr),Value :: callback_data,widget
    Integer(guint),Value :: callback_action

callback_data is a pointer to an arbitrary piece of data and is set during the call to gtk_item_factory_create_items.

callback_action is the same value as callback_action in the ItemFactory entry.

widget is a pointer to a menu item widget (described in Manual Menu Creation).

ItemFactory entry examples

Creating a simple menu item:

Type(GtkItemFactoryEntry) :: entry
Character(40),Target :: entry_path = '/_File/_Open...'//C_Null_Char
Character(20),Target :: entry_accel = '<CTRL>O'//C_Null_Char
Character(20),Target :: entry_data = '<Item>'//C_Null_Char
entry = GtkItemFactoryEntry(C_Loc(entry_path),C_Loc(entry_accel), &
                            C_FunLoc(print_hello),0,C_Loc(entry_data), &
                            C_Null_Ptr)

This will define a new simple menu entry "/File/Open" (displayed as "Open"), under the menu entry "/File". It has the accelerator (shortcut) Control-O that when clicked calls the function print_hello. print_hello has the interface

Subroutine print_hello()
since the callback_action field is zero. When displayed the ‘O’ in "Open" will be underlined and if the menu item is visible on the screen pressing ‘O’ will activate the item. Note that "File/_Open" could also have been used as the path instead of "/_File/_Open".

Creating an entry with a more complex callback:

Type(GtkItemFactoryEntry) :: entry2
Character(40),Target :: entry2_path = '/_View/Display _FPS'//C_Null_Char
Character(20),Target :: entry2_data = '<CheckItem>'//C_Null_Char
entry2 = GtkItemFactoryEntry(C_Loc(entry2_path),C_Null_Ptr, &
                             C_FunLoc(print_state),7,C_Loc(entry2_data), &
                             C_Null_Ptr)

This defines a new menu item displayed as “Display FPS” which is under the menu item “View”. When clicked the procedure print_state will be called. Since callback_action is not zero, print_state must have an interface compatible with:
Subroutine print_state(callback_data,callback_action,widget) Bind(C)
    Type(C_Ptr),Value :: callback_data,widget
    Integer(guint),Value :: callback_action

When print_state is called, the callback_action argument will be equal to 7.

Creating a radio button set:

Type(GtkItemFactoryEntry) entry3a,entry3b
Character(30),Target :: entry3a_path = '/_View/_Low Resolution'//C_Null_Char
Character(30),Target :: entry3a_data = '<RadioButton>'//C_Null_Char
Character(30),Target :: entry3b_path = '/_View/_High Resolution'//C_Null_Char
Character(30),Target :: entry3b_data = '/View/Low Resolution'//C_Null_Char
entry3a = GtkItemFactoryEntry(C_Loc(entry3a_path),C_Null_Ptr, &
                              C_FunLoc(change_resolution),1,C_Loc(entry3a_data))
entry3b = GtkItemFactoryEntry(C_Loc(entry3b_path),C_Null_Ptr, &
                              C_FunLoc(change_resolution),2,C_Loc(entry3b_data))

entry3a defines a lone radio button that when toggled calls the procedure change_resolution with the argument callback_action equal to 1. change_resolution must have an interface compatible with:
Subroutine change_resolution(callback_data,callback_action,widget) Bind(C)
    Type(C_Ptr),Value :: callback_data,widget
    Integer(guint),Value :: callback_action

entry3b defines a radio button that belongs to the radio group that entry3a belongs to. It calls the same function when toggled but with the argument callback_action equal to 2. Note that the item_type of entry3b is the path of entry3awithout the accelerators (‘_’). If another radio button was required in the same group then it would be defined in the same way as entry3b was with its item_type again equal to "/View/Low Resolution".

ItemFactoryEntry Arrays

An ItemFactoryEntry on its own however isn't useful. An array of entries is what's required to define a menu. Below is an example of one way of creating such an array. We define a helper function to dynamically create each item; because the data is being interpreted in C, there is actually a little work that needs to be done to put it into the correct format.

Type(GtkItemFactoryEntry) Function fentry(path,item_type,accelerator, &
                                          callback,callback_action,extra_data, &
                                          cextra_data)
  ! Note slightly different ordering from the type:
  ! we put item_type second because we always expect it.
  ! Also, we allow extra_data to be supplied either as a character string,
  ! or as a Type(C_Ptr).
  Character(*),Intent(In) :: path
  Character(*),Intent(In) :: item_type
  Character(*),Intent(In),Optional :: accelerator
  Type(C_FunPtr),Intent(In),Optional :: callback
  Integer(C_int),Intent(In),Optional :: callback_action
  Character(*),Intent(In),Optional :: extra_data
  Type(C_Ptr),Intent(In),Optional :: cextra_data
  fentry%path = string_to_cptr(path)
  fentry%item_type = string_to_cptr(item_type)
  If (Present(accelerator)) fentry%accelerator = string_to_cptr(accelerator)
  If (Present(callback)) Then
    fentry%callback = callback
  Else
    fentry%callback = C_Null_FunPtr
  End If
  If (Present(callback_action)) fentry%callback_action = callback_action
  If (Present(extra_data)) fentry%extra_data = string_to_cptr(extra_data)
  If (Present(cextra_data)) fentry%extra_data = cextra_data
Contains
  Type(C_Ptr) Function string_to_cptr(string)
    Character(*),Intent(In) :: string
    Character(:),Pointer :: cstring
    Integer :: n
    n = Len_Trim(string)
    Allocate(Character(n+1)::cstring)
    cstring(1:n) = string
    cstring(n+1:n+1) = C_Null_Char
    string_to_cptr = C_Loc(cstring(1:1))
  End Function
End Function

Type(GtkItemFactoryEntry) :: entries(6)
entries = (/ &
  fentry( '/_File',         '<Branch>'), &
  fentry( '/File/tear1',    '<Tearoff>' ), &
  fentry( '/File/_New',     '<Item>', '<CTRL>N', C_FunLoc(new_file), 1), &
  fentry( '/File/_Open...', '<Item>', '<CTRL>O', C_FunLoc(open_file), 1), &
  fentry( '/File/sep1',     '<Separator>'), &
  fentry( '/File/_Quit',    '<StockItem>', '<CTRL>Q', C_FunLoc(quit_program), 0, GTK_STOCK_QUIT ) /)

Creating an ItemFactory

An array of GtkItemFactoryEntry items defines a menu. Once this array is defined then the item factory can be created. The function that does this is:

Function gtk_item_factory_new(container_type,path,accel_group) Result(res)
    Integer(GType),Intent(in) :: container_type
    Character(*),Intent(in) :: path
    Type(GtkAccelGroup),Pointer :: accel_group
    Type(GtkItemFactory),Pointer :: res

container_type can be one of:

GTK_TYPE_MENU
GTK_TYPE_MENU_BAR
GTK_TYPE_OPTION_MENU

container_type defines what type of menu you want, so when you extract it later it is either a menu (for pop-ups for instance), a menu bar, or an option menu (like a combo box but with a menu of pull downs).

path defines the path of the root of the menu. Basically it is a unique name for the root of the menu, it must be surrounded by "<>". This is important for the naming of the accelerators and should be unique. It should be unique both for each menu and between each program. For example in a program named “foo”, the main menu should be called "<FooMain>", and a pop-up menu "<FooImagePopUp>", or similar. What's important is that they're unique.

accel_group is a pointer to a gtk_accel_group. The item factory sets up the accelerator table while generating menus. New accelerator groups are generated by gtk_accel_group_new.

But this is just the first step. To convert the array of GtkItemFactoryEntry information into widgets the following procedure is used:

Subroutine gtk_item_factory_create_items(ifactory,entries,callback_data)
    Type(GtkItemFactory),Pointer :: ifactory
    Type(GtkItemFactoryEntry) :: entries(:)
    Type(C_Ptr),Optional :: callback_data

ifactory is a pointer to the above created item factory.

entries is an array of GtkItemFactoryEntry.

callback_data is what gets passed to all the callback functions for all the entries with callback_action≠0. If callback_data is not present, C_Null_Ptr will be used for any callback data.

The accelerator group has now been formed, so you'll probably want to attach it to the window the menu is in:

Subroutine gtk_window_add_accel_group(window,accel_group)
    Type(GtkWindow),Pointer :: window
    Type(GtkAccelGroup),Pointer :: accel_group

Making use of the menu and its menu items

The last thing to do is make use of the menu. The following function extracts the relevant widgets from the ItemFactory:

Function gtk_item_factory_get_widget(ifactory,path) Result(res)
    Type(GtkItemFactory),Pointer :: ifactory
    Character(*),Intent(In) :: path
    Type(GtkWidget),Pointer :: res

For instance if an ItemFactory has two entries "/File" and "/File/New", using a path of "/File" would retrieve a menu widget from the ItemFactory. Using a path of "/File/New" would retrieve a menu item widget. This makes it possible to set the initial state of menu items. For example to set the default radio item to the one with the path "/Shape/Oval" then the following code would be used:

Type(GtkWidget),Pointer :: item
...
item => gtk_item_factory_get_item(item_factory,"/Shape/Oval")
Call gtk_check_menu_item_set_active(GTK_CHECK_MENU_ITEM(item),TRUE)

Finally to retrieve the root of the menu use gtk_item_factory_get_item with a path of "<main>" (or whatever path was used in gtk_item_factory_new). In the case of the ItemFactory being created with type GTK_TYPE_MENU_BAR this returns a menu bar widget. With type GTK_TYPE_MENU a menu widget is returned. With type GTK_TYPE_OPTION_MENU an option menu widget is returned.

Remember for an entry defined with path "/_File" the path here is actually "/File".

Now you have a menubar or menu which can be manipulated in the same way as shown in the Manual Menu Creation section.

<<< Previous | Home | Next >>>
Manual Menu Example | Up | Item Factory Example


Item Factory Example

Here is an example using the GTK item factory.

Module item_factory
  Use glib
  Use gtk
  Use gdk
  Implicit None

  Type(GtkItemFactoryEntry),Pointer :: menu_items(:)

Contains
  ! Convert Fortran string to pointer to null-terminated C string.
  Type(C_Ptr) Function string_to_cptr(string)
    Character(*),Intent(In) :: string
    Character(:),Pointer :: cstring
    Integer :: n
    n = Len_Trim(string)
    If (n==0) Then
      string_to_cptr = C_Null_Ptr
    Else
      Allocate(Character(n+1)::cstring)
      cstring(1:n) = string
      cstring(n+1:n+1) = C_Null_Char
      string_to_cptr = C_Loc(cstring(1:1))
    End If
  End Function

  !  Obligatory basic callback.
  Subroutine print_hello(w,data) Bind(C,Name='')
    Type(C_Ptr),Value :: w,data
    Print *,'Hello World!'
  End Subroutine

  !  For the check button.
  Subroutine print_toggle(callback_data,callback_action,menu_item) &
  Bind(C,Name='')
    Type(C_Ptr),Value :: callback_data,menu_item
    Integer,Value :: callback_action

    ! Is check menu active?
    Print *,'Check button state -', &
            gtk_check_menu_item_get_active(GTK_CHECK_MENU_ITEM (menu_item))
  End Subroutine

  !  For the radio buttons.
  Subroutine print_selected(callback_data,callback_action,menu_item) &
  Bind(C,Name='')
    Type(C_Ptr)   ,Value :: callback_data,menu_item
    Integer(guint),Value :: callback_action

    If (gtk_check_menu_item_get_active(GTK_CHECK_MENU_ITEM(menu_item))==TRUE) &
      Print *,'Radio button',callback_action,'selected'
  End Subroutine

  !  Returns a menubar widget made from the above menu.
  Function get_menubar_menu(window) Result(res)
    Type(GtkWidget),Pointer :: window
    Type(GtkWidget),Pointer :: res
    Type(GtkItemFactory),Pointer :: item_factory
    Type(GtkAccelGroup),Pointer :: accel_group

    ! Make an accelerator group (shortcut keys).
    accel_group => gtk_accel_group_new()

    ! Make an ItemFactory (that makes a menubar).
    item_factory => gtk_item_factory_new(GTK_TYPE_MENU_BAR(),'<main>', &
                                            accel_group)
    ! This function generates the menu items.
    ! Pass the item factory and the array; if there is any callback data, pass
    ! that too (after the array).
    Call gtk_item_factory_create_items(item_factory,menu_items)

    ! Attach the new accelerator group to the window.
    Call gtk_window_add_accel_group(GTK_WINDOW(window),accel_group)

    ! Finally, return the actual menu bar created by the item factory.
    res => gtk_item_factory_get_widget(item_factory,'<main>')

  End Function

  !  Popup the menu when the popup button is pressed.
  Integer(gboolean) Function popup_cb(widget,event,menu) Bind(C,Name='')
    Type(C_Ptr),Value ::widget,event,menu
    Type(GdkEventButton),Pointer :: bevent

    ! Just assume the event is a button event.
    Call C_F_Pointer(event,bevent)

    ! Only take button presses.
    If (bevent%type==GDK_BUTTON_PRESS) then
      ! Show the menu.
      Call gtk_menu_popup(GTK_MENU(menu),Null(),Null(),C_Null_Funptr, &
                          C_Null_Ptr,bevent%button,bevent%time)
      popup_cb = TRUE
    Else
      popup_cb = FALSE
    End If
  End Function

  ! Same as with get_menubar_menu, but just return a button with a signal to
  ! call a popup menu.
  Function get_popup_menu() Result(button)
    Type(GtkItemFactory),Pointer :: item_factory
    Type(GtkWidget),Pointer :: button
    Type(GtkWidget),Pointer :: menu

    ! Same as before but don't bother with the accelerators.
    item_factory => gtk_item_factory_new(GTK_TYPE_MENU(),'<main>',Null())
    Call gtk_item_factory_create_items(item_factory,menu_items)
    menu => gtk_item_factory_get_widget(item_factory,'<main>')

    ! Make a button to activate the popup menu.
    button => gtk_button_new_with_label('Popup')
    ! Make the menu popup when clicked.
    Call g_signal_connect(G_OBJECT(button),'event',C_FunLoc(popup_cb), &
                         C_Loc(menu))
  End Function

  ! Same again but return an option menu.
  Function get_option_menu() Result(option_menu)
    Type(GtkItemFactory),Pointer :: item_factory
    Type(GtkWidget),Pointer :: option_menu

    ! Same again, not bothering with the accelerators.
    item_factory => gtk_item_factory_new(GTK_TYPE_OPTION_MENU(), &
                                            '<main>',Null())
    Call gtk_item_factory_create_items(item_factory,menu_items)
    option_menu => gtk_item_factory_get_widget(item_factory,'<main>')
  End Function

  Type(GtkItemFactoryEntry) Function fentry(path,item_type,accelerator, &
                                            callback,callback_action, &
                                            extra_data,cextra_data)
    ! Note slightly different ordering from the type:
    ! we put item_type second because it is always present.
    ! Also, we allow extra_data to be supplied either as a character string,
    ! or as a Type(C_Ptr).
    Character(*),Intent(In) :: path,item_type
    Character(*),Intent(In),Optional :: accelerator
    Type(C_FunPtr),Intent(In),Optional :: callback
    Integer(C_int),Intent(In),Optional :: callback_action
    Character(*),Intent(In),Optional :: extra_data
    Type(C_Ptr),Intent(In),Optional :: cextra_data
    fentry%path = string_to_cptr(path)
    fentry%item_type = string_to_cptr(item_type)
    If (Present(accelerator)) fentry%accelerator = string_to_cptr(accelerator)
    If (Present(callback)) Then
      fentry%callback = callback
    Else
      fentry%callback = C_Null_FunPtr
    End If
    If (Present(callback_action)) fentry%callback_action = callback_action
    If (Present(extra_data)) fentry%extra_data = string_to_cptr(extra_data)
    If (Present(cextra_data)) fentry%extra_data = cextra_data
  End Function

  Function entry_array(array)
    Type(GtkItemFactoryEntry),Intent(In) :: array(:)
    Type(GtkItemFactoryEntry),Pointer :: entry_array(:)
    Allocate(entry_array(Size(array)),Source=array)
  End Function

End Module

! You have to start somewhere.
Program main
  Use item_factory

  Type(GtkWidget),Pointer :: window,main_vbox,menubar,option_menu,popup_button
  Type(C_FunPtr) :: hello

  ! Initialize GTK.
  Call gtk_init

  ! Make a window.
  window => gtk_window_new(GTK_WINDOW_TOPLEVEL)
  Call g_signal_connect(G_OBJECT(window),'destroy',C_FunLoc(gtk_main_quit), &
                        C_Null_Ptr)
  Call gtk_window_set_title(GTK_WINDOW(window),'Item Factory')
  Call gtk_widget_set_size_request(GTK_WIDGET(window),300,200)

  !  Make a vbox to put the three menus in.
  main_vbox => gtk_vbox_new(FALSE,1)
  Call gtk_container_set_border_width(GTK_CONTAINER(main_vbox),1)
  Call gtk_container_add(GTK_CONTAINER(window),main_vbox)

  ! Our menu, an array of GtkItemFactoryEntry structures
  ! that define each menu item.
  hello = C_FunLoc(print_hello)
  menu_items => entry_array( (/ &
    fentry('/_File','<Branch>'), &
    fentry('/File/_New','<StockItem>','<control>N',hello,0,GTK_STOCK_NEW), &
    fentry('/File/_Open','<StockItem>','<control>O',hello,0,GTK_STOCK_OPEN), &
    fentry('/File/_Save','<StockItem>','<control>S',hello,0,GTK_STOCK_SAVE), &
    fentry('/File/Save _As','<Item>'), &
    fentry('/File/sep1','<Separator>'), &
    fentry('/File/_Quit','<StockItem>','<CTRL>Q',C_FunLoc(gtk_main_quit),0, &
           GTK_STOCK_QUIT), &
    fentry('/_Options','<Branch>'), &
    fentry('/Options/tear','<Tearoff>'), &
    fentry('/Options/Check','<CheckItem>','',C_FunLoc(print_toggle),1), &
    fentry('/Options/sep','<Separator>'), &
    fentry('/Options/Rad1','<RadioItem>','',C_FunLoc(print_selected),1), &
    fentry('/Options/Rad2','/Options/Rad1','',C_FunLoc(print_selected),2), &
    fentry('/Options/Rad3','/Options/Rad1','',C_FunLoc(print_selected),3), &
    fentry('/_Help','<LastBranch>'), &
    fentry('/_Help/About','<Item>') /) )

  ! Get the three types of menu.
  ! Note: all 3 menus are separately created, so they are not the same menu.
  menubar => get_menubar_menu(window)
  popup_button => get_popup_menu()
  option_menu => get_option_menu()

  !  Pack it all together.
  Call gtk_box_pack_start(GTK_BOX(main_vbox),menubar,FALSE,TRUE,0)
  Call gtk_box_pack_end (GTK_BOX(main_vbox),popup_button,FALSE,TRUE,0)
  Call gtk_box_pack_end (GTK_BOX(main_vbox),option_menu,FALSE,TRUE,0)

  !  Show the widgets.
  Call gtk_widget_show_all(window)

  !  Finished!
  Call gtk_main

End Program

<<< Previous | Home | Next >>>
Using ItemFactory | Up | Undocumented Widgets


Undocumented Widgets

These all require authors! :) Please consider contributing to our tutorial.

If you must use one of these widgets that are undocumented, I strongly suggest you take a look at their respective header files in the GTK distribution. GTK's function names are very descriptive. Once you have an understanding of how things work, it's not difficult to figure out how to use a widget simply by looking at its function declarations. This, along with a few examples from others' code, and it should be no problem.

When you do come to understand all the functions of a new undocumented widget, please consider writing a tutorial on it so others may benefit from your time.

Accel Label

<<< Previous | Home | Next >>>
Item Factory Example |  | Option Menu


Option Menu

<<< Previous | Home | Next >>>
Undocumented Widgets | Up | Menu Items


Menu Items

Check Menu Item

Radio Menu Item

Separator Menu Item

Tearoff Menu Item

<<< Previous | Home | Next >>>
Option Menu | Up | Curves


Curves

<<< Previous | Home | Next >>>
Menu Items | Up | Drawing Area


Drawing Area

<<< Previous | Home | Next >>>
Curves | Up | Font Selection Dialogue


Font Selection Dialogue

<<< Previous | Home | Next >>>
Drawing Area | Up | Message Dialogue


Message Dialogue

<<< Previous | Home | Next >>>
Font Selection Dialogue | Up | Gamma Curve


Gamma Curve

<<< Previous | Home | Next >>>
Message Dialogue | Up | Image


Image

<<< Previous | Home | Next >>>
Gamma Curve | Up | Plugs and Sockets


Plugs and Sockets

<<< Previous | Home | Next >>>
Image | Up | Tree View


Tree View

This is very complicated. It starts with the following procedure; after that, you are on your own.

Function gtk_tree_view_new() Result(res)
  Type(GtkWidget),Pointer :: res

<<< Previous | Home | Next >>>
Plugs and Sockets | Up | Text View


Text View

The simplest usage of GtkTextView might look like this.

  Type(GtkWidget),Pointer :: view
  Type(GtkTextBuffer),Pointer :: buffer

  view => gtk_text_view_new()

  buffer => gtk_text_view_get_buffer(GTK_TEXT_VIEW(view))

  Call gtk_text_buffer_set_text(buffer,'Hello, this is some text.')

After that you might put the view in a container and display it on the screen. When the user edits the text, various signals on the buffer will be emitted, such as “changed”, “insert_text” and so on.

Here are the interfaces of the above-referenced procedures.

Function gtk_text_view_new() Result(res)
  Type(GtkWidget),Pointer :: res

Function gtk_text_view_get_buffer(text_view) Result(res)
  Type(GtkTextView),Pointer :: text_view
  Type(GtkTextBuffer),Pointer :: res

Subroutine gtk_text_buffer_set_text(buffer,text)
  Type(GtkTextBuffer),Intent(InOut) :: buffer
  Character(*),Intent(In) :: text

<<< Previous | Home | Next >>>
Tree View | Up | Setting Widget Attributes


Setting Widget Attributes

This describes the procedures used to operate on widgets. These can be used to set style, padding, size, etc.

Integer Function gtk_widget_activate(widget)
    Type(GtkWidget),Pointer :: widget

Subroutine gtk_widget_set_name(widget,name)
    Type(GtkWidget),Pointer :: widget
    Character(*),Intent(In) :: name

Function gtk_widget_get_name(widget) Result(res)
    Type(GtkWidget),Pointer :: widget
    Character,Pointer :: res(:)

Subroutine gtk_widget_set_sensitive(widget,sensitive)
    Type(GtkWidget),Pointer :: widget
    Integer,Intent(In) :: sensitive

Subroutine gtk_widget_set_style(widget,style)
    Type(GtkWidget),Pointer :: widget
    Type(GtkStyle),Pointer :: style

Subroutine gtk_widget_set_style(widget,style)
    Type(GtkWidget),Pointer :: widget
    Type(GtkStyle),Pointer :: style

Function gtk_widget_get_default_style() Result(res)
    Type(GtkStyle),Pointer :: res

Subroutine gtk_widget_set_size_request(widget,width,height)
    Type(GtkWidget),Pointer :: widget
    Integer,Intent(In) :: width,height

Subroutine gtk_widget_grab_focus(widget)
    Type(GtkWidget),Pointer :: widget

Subroutine gtk_widget_show(widget)
    Type(GtkWidget),Pointer :: widget

Subroutine gtk_widget_hide(widget)
    Type(GtkWidget),Pointer :: widget

<<< Previous | Home | Next >>>
Text View |  | Timeouts, I/O and Idle Functions


Timeouts, I/O and Idle Functions

Timeouts

You may be wondering how you make GTK do useful work when in gtk_main. Well, you have several options. Using the following function you can create a timeout function that will be called every interval milliseconds.

Integer(guint) Function gtk_timeout_add(interval,function,data)
  Integer(guint32),Intent(In) :: interval
  Interface
    Function function(data) Bind(C)
      Use Iso_C_Binding
      Type(C_Ptr),Value :: data
    End Function
  End Interface
  Type(C_Ptr) :: data

The first argument is the number of milliseconds between calls to your function. The second argument is the function you wish to have called, and the third, the data passed to this callback function. The return value is an integer “id” which may be used to stop the timeout by calling:

Subroutine gtk_timeout_remove(timeout_handler_id)
    Integer(guint),Intent(In) :: timeout_handler_id

You may also stop the timeout function by returning zero from your callback function. Obviously this means if you want your function to continue to be called, it should return a non-zero value, e.g. 1.

Finally, gtk_timeout_add is generic, so if you have a Type(C_FunPtr) pointer to a function you wish to add as a callback, you can pass that as the function argument instead.

<<< Previous | Home | Next >>>
Setting Widget Attributes |  | Monitoring Input/Output


Monitoring Input/Output

A nifty feature of GDK (the library that underlies GTK), is the ability to have it check for data on a Posix file descriptor for you (as returned by open or socket). This might not be not very useful on Windows, but on Posix systems can be useful for networking applications.

Input/Output monitoring is established by calling the function
Integer Function gdk_input_add(source,condition,function,data)
    Integer,Intent(In) :: source
    Integer(GdkInputCondition),Intent(In) :: condition
    Type(C_FunPtr),Value :: function
    Type(C_Ptr) :: data
where the first argument is the file descriptor you wish to have watched, and the second specifies what you want GDK to look for. This may be one of

  • GDK_INPUT_READ – call your function when there is data ready for reading on your file descriptor;
  • GDK_INPUT_WRITE – call your function when the file descriptor is ready for writing.

As I'm sure you've figured out already, the third argument is a C pointer to the procedure you wish to have called when the above conditions are satisfied, and the fourth is the data to pass to this procedure.

The return value is a tag that may be used to stop GDK from monitoring this file descriptor using the following procedure.

Subroutine gdk_input_remove(tag)
    Integer,Intent(In)::tag

The interface of the callback procedure must be compatible with
Subroutine input_callback(data,source,condition) Bind(C)
    Type(C_Ptr),Value :: data
    Integer(gint),Value :: source
    Integer(GdkInputCondition),Value :: condition
where source and condition are as specified above.

<<< Previous | Home | Next >>>
Timeouts, I/O and Idle Functions | Up | Idle Functions


Idle Functions

What if you have a function which you want to be called when nothing else is happening?

Integer(guint) Function g_idle_add(function,data)
    Procedure(GSourceFunc) :: function
    Type(C_Ptr) :: data

This causes GTK to call the specified function whenever nothing else is happening.

I won't explain the meaning of the arguments as they follow very much like the ones above. The function pointed to by the first argument to g_idle_add will be called whenever the opportunity arises. As with the timeout and i/o callback functions, returning FALSE will stop the idle function from being called.

The interface of your function must be compatible with GSourceFunc, which is:
Integer(gboolean) Function GSourceFunc(data) Bind(C)
    Type(C_Ptr),Value :: data

To remove the idle function (other than by it returning FALSE), use the following procedure.

Subroutine g_idle_remove(idle_handler_id)
    Integer,Intent(In) :: idle_handler_id

Note that g_idle_add and g_idle_remove are GLIB functions, the GTK equivalents have been deprecated.

<<< Previous | Home | Next >>>
Monitoring Input/Output | Up | Advanced Event and Signal Handling


Advanced Event and Signal Handling

Signal Functions

Connecting and Disconnecting Signal Handlers

Subroutine g_signal_connect(instance,event,callback,data,handler_id)
    Type(GObject),Pointer :: instance
    Character(*),Intent(In) :: event
    Type(C_Ptr),Intent(In) :: data
    Type(C_Funptr),Value :: callback
    Integer(gulong),Optional,Intent(Out) :: handler_id

Subroutine g_signal_connect_after(instance,event,callback,data,handler_id)
    Type(GObject),Pointer :: instance
    Character(*),Intent(In) :: event
    Type(C_FunPtr),Value :: callback
    Type(C_Ptr),Intent(In) :: data
    Integer(gulong),Optional,Intent(Out) :: handler_id

Subroutine g_signal_connect_swapped(instance,event,callback,data,handler_id)
    Type(GObject),Pointer :: instance
    Character(*),Intent(In) :: event
    Type(C_FunPtr),Value :: callback
    Type(C_Ptr),Intent(In) :: data
    Integer(gulong),Optional,Intent(Out) :: handler_id

Subroutine g_signal_handler_disconnect(instance,handler_id)
        Type(C_Ptr),Intent(In) :: instance
        Integer(gulong),Intent(In) :: handler_id

Subroutine g_signal_handlers_disconnect_by_func(object,func,data)
    Type(GObject),Pointer :: object
    Type(C_FunPtr),Value :: func
    Type(C_Ptr),Intent(In) :: data

Blocking and Unblocking Signal Handlers

Subroutine g_signal_handler_block(instance,handler_id)
  Type(C_Ptr),Intent(In) :: instance
  Integer(gulong),Intent(In) :: handler_id

Subroutine g_signal_handlers_block_by_func(object,func,data)
  Type(C_Ptr),Intent(In) :: object
  Type(C_FunPtr),Value :: func
  Type(C_Ptr),Intent(In) :: data

Subroutine g_signal_handler_unblock(instance,handler_id)
  Type(C_Ptr),Intent(In) :: instance
  Integer(gulong),Intent(In) :: handler_id

Subroutine g_signal_handlers_unblock_by_func(object,func,data)
  Type(C_Ptr),Intent(In) :: object
  Type(C_FunPtr),Value :: func
  Type(C_Ptr),Intent(In) :: data

Emitting and Stopping Signals

! g_signal_emit is not available from Fortran.
! g_signal_emit_by_name is not available from Fortran.

Subroutine g_signal_emitv(instance_and_params,signal_id,detail,return_value)
  Type(GValue),Pointer :: instance_and_params
  Integer(guint),Intent(In) :: signal_id
  Integer(GQuark),Intent(In) :: detail
  Type(GValue),Pointer :: return_value

Subroutine g_signal_stop_emission(instance,signal_id,detail)
  Type(C_Ptr),Intent(In) :: instance
  Integer(guint),Intent(In) :: signal_id
  Integer(GQuark),Intent(In) :: detail

Subroutine g_signal_stop_emission_by_name(instance,detailed_signal)
  Type(C_Ptr),Intent(In) :: instance
  Character(*),Intent(In) :: detailed_signal

<<< Previous | Home | Next >>>
Idle Functions |  | Signal Emission and Propagation


Signal Emission and Propagation

Signal emission is the process whereby GLIB runs all handlers for a specific object and signal.

First, note that the return value from a signal emission is the return value of the last handler executed. Since event signals are all of type GTK_RUN_LAST, this will be the default (GTK supplied) handler, unless you connect with g_signal_connect_after.

The way an event (say “button_press_event”) is handled, is:

  • Start with the widget where the event occured.

  • Emit the generic “event” signal. If that signal handler returns a value of TRUE, stop all processing.

  • Otherwise, emit a specific, “button_press_event” signal. If that returns TRUE, stop all processing.

  • Otherwise, go to the widget's parent, and repeat the above two steps.

  • Continue until some signal handler returns TRUE, or until the top-level widget is reached.

Some consequences of the above are:

  • Your handler's return value will have no effect if there is a default handler, unless you connect with g_signal_connect_after.

  • To prevent the default handler from being run, you need to connect with g_signal_connect and use g_signal_stop_emission_by_name – the return value only affects whether the signal is propagated, not the current emission.

<<< Previous | Home | Next >>>
Advanced Event and Signal Handling | Up | Managing Selections


Managing Selections

NOTE

Most of this is specific to the X window system and so is probably useless on Microsoft Windows; however, it is documented here for completeness.

Overview

One type of interprocess communication supported by GTK is selection. A selection identifies a chunk of data, for instance, a portion of text, selected by the user in some fashion, for instance, by dragging with the mouse. Only one application on a display (the owner) can own a particular selection at one time, so when a selection is claimed by one application, the previous owner must indicate to the user that selection has been relinquished. Other applications can request the contents of a selection in different forms, called targets. There can be any number of selections, but most GTK applications only handle one, the primary selection.

In most cases, it isn't necessary for a GTK application to deal with selections itself. The standard widgets, such as the Entry widget, already have the capability to claim the selection when appropriate (e.g. when the user drags over text), and to retrieve the contents of the selection owned by another widget or another application (e.g. when the user clicks the second mouse button). However, there may be cases in which you want to give other widgets the ability to supply the selection, or you wish to retrieve targets not supported by default.

A fundamental concept needed to understand selection handling is that of the atom. An atom is an integer that uniquely identifies a string (on a certain display). Certain atoms are predefined by the X server, and in some cases there are constants in gtk.h corresponding to these atoms. For instance the constant GDK_PRIMARY_SELECTION corresponds to the string "PRIMARY". In other cases, you should use the functions gdk_atom_intern, to get the atom corresponding to a string, and gdk_atom_name, to get the name of an atom. Both selections and targets are identified by atoms.

<<< Previous | Home | Next >>>
Signal Emission and Propagation |  | Retrieving the selection


Retrieving the selection

Retrieving the selection is an asynchronous process. To start the process, you call:

Integer Function gtk_selection_convert(widget,selection,target,time_)
    Type(GtkWidget),Pointer :: widget
    Integer(GdkAtom),Intent(In) :: selection,target
    Integer(guint32),Intent(In) :: time_

This converts the selection into the form specified by target. If at all possible, the time field should be the time from the event that triggered the selection; this helps make sure that events occur in the order that the user requested them. However, if it is not available (for instance, if the conversion was triggered by a “clicked” signal), then you can use the constant GDK_CURRENT_TIME.

When the selection owner responds to the request, a “selection_received” signal is sent to your application. The handler for this signal receives a pointer to a GtkSelectionData structure, which is defined as
Type,Bind(C) :: GtkSelectionData
    Integer(GdkAtom) :: selection,target,type
    Integer(C_int) :: format
    Type(C_Ptr) :: data
    Integer(C_int) :: length
    Type(C_Ptr) :: display ! Pointer to GdkDisplay.
End Type

selection and target are the values you gave in your gtk_selection_convert call. type is an atom that identifies the type of data returned by the selection owner. Some possible values are “STRING”, a string of latin-1 characters, “ATOM”, a series of atoms, “INTEGER”, an integer, etc.. Most targets can only return one type. format gives the length of the units (for instance characters) in bits. Usually, you don't care about this when receiving data. data is a pointer to the returned data, and length gives the length of the returned data, in bytes. If length is negative, then an error occurred and the selection could not be retrieved. This might happen if no application owned the selection, or if you requested a target that the application didn't support. The buffer is actually guaranteed to be one byte longer than length; the extra byte will always be zero, so it isn't necessary to make a copy of strings just to null-terminate them.

In the following example, we retrieve the special target “TARGETS”, which is a list of all targets into which the selection can be converted.

Module selection_mod
  Use gtk
  Use gdk
Contains

  ! Signal handler invoked when user clicks on the "Get Targets" button.
  Subroutine get_targets(pwidget,pdata) Bind(C)
    Type(C_Ptr),Value :: pwidget,pdata
    Integer(GdkAtom),Save :: targets_atom
    Logical :: first = .True.
    Type(GtkWidget),Pointer :: window
    Integer :: status

    window => GTK_WIDGET(pdata)

    If (first) Then
      targets_atom = gdk_atom_intern("TARGETS",FALSE)
      first = .False.
    End If

    ! And request the "TARGETS" target for the primary selection.
    status = gtk_selection_convert(window,GDK_SELECTION_PRIMARY,targets_atom, &
                                   GDK_CURRENT_TIME)
  End Subroutine

  ! Signal handler called when the selections owner returns the data.
  Subroutine selection_received(pwidget,pselection_data,pdata) Bind(C)
    Type(C_Ptr),Value :: pwidget,pselection_data,pdata
    Type(GtkSelectionData),Pointer :: selection_data
    Integer(GdkAtom),Pointer :: atoms(:)
    Type(GList),Pointer :: item_list
    Integer :: i,atom_num
    Character,Pointer :: name(:)

    Call C_F_Pointer(pselection_data,selection_data)
    ! **** IMPORTANT **** Check to see if retrieval succeeded.
    If (selection_data%length<0) Then
      Print *,"Selection retrieval failed"
      Return
    End If
    ! Make sure we got the data in the expected form.
    If (selection_data%type/=GDK_SELECTION_TYPE_ATOM) Then
      Print *,'Selection "TARGETS" was not returned as atoms!'
      Return
    End If

    ! Work out the number of atoms; assuming an atom is 4 bytes.
    atom_num = selection_data%length/4
    ! And make a Fortran pointer to the array.
    Call C_F_Pointer(selection_data%data,atoms,(/atom_num/))

    item_list => Null()

    Do i=1,atom_num
      name => gdk_atom_name(atoms(i))
      If (Associated(name)) Then
        Print *,name
      Else
        Print *,"(bad atom)"
      End If
    End Do
  End Subroutine

End Module

Program main
  Use selection_mod

  Type(GtkWidget),Pointer :: window,button

  Call gtk_init

  ! Create the toplevel window.
  window => gtk_window_new(GTK_WINDOW_TOPLEVEL)
  Call gtk_window_set_title(GTK_WINDOW (window),"Event Box")
  Call gtk_container_set_border_width(GTK_CONTAINER(window),10)

  Call g_signal_connect(G_OBJECT(window),"destroy", &
                        G_CALLBACK(gtk_main_quit),C_Null_Ptr)

  ! Create a button the user can click to get targets.
  button => gtk_button_new_with_label("Get Targets")
  Call gtk_container_add(GTK_CONTAINER(window),button)

  Call g_signal_connect(G_OBJECT(button),"clicked", &
                        G_CALLBACK(get_targets),C_Loc(window))
  Call g_signal_connect(G_OBJECT(window),"selection_received", &
                        G_CALLBACK(selection_received),C_Null_Ptr)

  Call gtk_widget_show(button)
  Call gtk_widget_show(window)

  Call gtk_main

End Program

<<< Previous | Home | Next >>>
Managing Selections | Up | Supplying the selection


Supplying the selection

Supplying the selection is a bit more complicated. You must register handlers that will be called when your selection is requested. For each selection/target pair you will handle, you make a call to

Subroutine gtk_selection_add_target(widget,selection,target,info)
    Type(GtkWidget),Pointer :: widget
    Integer(GdkAtom),Intent(In) :: selection,target
    Integer(guint),Intent(In) :: info

widget, selection, and target identify the requests this handler will manage. When a request for a selection is received, the “selection_get” signal will be called. info can be used as an enumerator to identify the specific target within the callback procedure.

The callback procedure must have an interface compatible with

Subroutine selection_get_interface(widget,selection_data,info,time) Bind(C)
    Type(GtkWidget),Target,Intent(InOut) :: widget
    Type(GtkSelectionData),Target,Intent(InOut) :: selection_data
    Type(guint),Value :: info,time

The GtkSelectionData is the same as above, but this time, we're responsible for filling in the fields type, format, data, and length. (The format field is actually important here – the X server uses it to figure out whether the data needs to be byte-swapped or not. Usually it will be 8 (for character data) or 32 (for 32-bit integer data). This is done by calling the procedure

Subroutine gtk_selection_data_set (selection_data,type,format,data,length)
    type(GtkSelectionData),pointer::selection_data
    Integer(GdkAtom),Intent(In) :: type
    Integer(gint),Intent(In) :: format
    Type(C_Ptr),Value :: data
    Integer(gint),Intent(In) :: length

This function takes care of properly making a copy of the data so that you don't have to worry about keeping it around. (You should not fill in the fields of the GtkSelectionData structure by hand.)

When prompted by the user, you claim ownership of the selection by calling

Integer function gtk_selection_owner_set (widget,selection,time_)
    Type(GtkWidget),Pointer :: widget
    Integer(GdkAtom),Intent(In) :: selection
    Integer(guint32),Intent(In) :: time_

If another application claims ownership of the selection, you will receive a “selection_clear_event”.

As an example of supplying the selection, the following program adds selection functionality to a toggle button. When the toggle button is depressed, the program claims the primary selection. The only target supported (aside from certain targets like “TARGETS” supplied by GTK itself), is the “STRING” target. When this target is requested, a string representation of the time is returned.

Module selection_serv
  Use gtk
  Use gdk

  Type(GtkWidget),Pointer :: selection_button,selection_widget

Contains

  ! Callback when the user toggles the selection.
  Subroutine selection_toggled(pwidget,have_selection) Bind(C)
    Type(C_Ptr),Value :: pwidget
    Integer(gint) :: have_selection
    Type(GtkWidget),Pointer :: widget
    Type(GtkToggleButton),Pointer :: toggle
    integer::status
    type(GdkWindow),pointer::gdk_win

    widget => GTK_WIDGET(pwidget)
    toggle => GTK_TOGGLE_BUTTON(widget)

    If (gtk_toggle_button_get_active(toggle)==TRUE) Then
      have_selection = gtk_selection_owner_set(selection_widget, &
                                               GDK_SELECTION_PRIMARY, &
                                               GDK_CURRENT_TIME)
      ! If claiming the selection failed, we turn the button off again.
      If (have_selection==0) &
        Call gtk_toggle_button_set_active(toggle,FALSE)
    Else If (have_selection/=0) Then
      ! Before clearing the selection by setting the owner to NULL,
      ! we check if we are the actual owner.
      gdk_win => gdk_selection_owner_get(GDK_SELECTION_PRIMARY)
      If (C_Associated(C_Loc(gdk_win),widget%window)) &
        status = gtk_selection_owner_set(Null(),GDK_SELECTION_PRIMARY, &
                                         GDK_CURRENT_TIME)
      have_selection = FALSE
    End If
  End Subroutine

  ! Called when another application claims the selection.
  Integer(gboolean) Function selection_clear(pwidget,pevent,have_selection) &
  Bind(C)
    Type(C_Ptr),Value :: pwidget,pevent
    Integer(gint) :: have_selection
    have_selection = FALSE
    Call gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(selection_button),FALSE)
    selection_clear = TRUE
  End Function

  ! Supplies the current time as the selection.
  Subroutine selection_handle(widget,pselection_data,info,time_stamp,data) bind(c)
    Type(C_Ptr),Value :: widget,pselection_data,data
    Integer(guint),Value :: info,time_stamp
    Type(GtkSelectionData),Pointer :: selection_data
    Character(18),Target :: timestamp_string

    Call Date_And_Time(timestamp_string(1:8),timestamp_string(9:18))
    Call C_F_Pointer(pselection_data,selection_data)
    Call gtk_selection_data_set(selection_data,GDK_SELECTION_TYPE_STRING,8, &
                                C_Loc(timestamp_string(1:1)), &
                                Len_Trim(timestamp_string))
  End Subroutine

End Module

Program main
  Use selection_serv

  Type(GtkWidget),Pointer :: window

  Integer(gint),Target :: have_selection = FALSE

  Call gtk_init

  ! Create the toplevel window.

  window => gtk_window_new(GTK_WINDOW_TOPLEVEL)
  Call gtk_window_set_title(GTK_WINDOW(window),"Event Box")
  Call gtk_container_set_border_width(GTK_CONTAINER(window),10)

  Call g_signal_connect(G_OBJECT(window),"destroy", &
                        G_CALLBACK(gtk_main_quit),C_Null_Ptr)

  ! Create a toggle button to act as the selection.

  selection_widget => gtk_invisible_new()
  selection_button => gtk_toggle_button_new_with_label("Claim Selection")
  Call gtk_container_add(GTK_CONTAINER(window),selection_button)
  Call gtk_widget_show(selection_button)

  Call g_signal_connect(G_OBJECT(selection_button),"toggled", &
                        G_CALLBACK(selection_toggled),C_Loc(have_selection))
  Call g_signal_connect(G_OBJECT(selection_widget),"selection_clear_event", &
                        G_CALLBACK(selection_clear),C_Loc(have_selection))

  Call gtk_selection_add_target(selection_widget,GDK_SELECTION_PRIMARY, &
                                GDK_SELECTION_TYPE_STRING,1)
  Call g_signal_connect(G_OBJECT(selection_widget),"selection_get", &
                        G_CALLBACK(selection_handle),C_Loc(have_selection))

  Call gtk_widget_show(selection_button)
  Call gtk_widget_show(window)

  Call gtk_main

End Program

<<< Previous | Home | Next >>>
Retrieving the selection | Up | Drag-and-drop (DND)


Drag-and-drop (DND)

GTK+ has a high level set of functions for doing inter-process communication via the drag-and-drop system. GTK+ can perform drag-and-drop on top of the low level Xdnd and Motif drag-and-drop protocols. This is probably useless on Windows, but is documented here in any case for completeness.

Overview

An application capable of GTK+ drag-and-drop first defines and sets up the GTK+ widget(s) for drag-and-drop. Each widget can be a source and/or destination for drag-and-drop. Note that these GTK+ widgets must have an associated X Window, check using GTK_WIDGET_NO_WINDOW(widget)).

Source widgets can send out drag data, thus allowing the user to drag things off of them, while destination widgets can receive drag data. Drag-and-drop destinations can limit who they accept drag data from, e.g. the same application or any application (including itself).

Sending and receiving drop data makes use of GTK+ signals. Dropping an item to a destination widget requires both a data request (for the source widget) and data received signal handler (for the target widget). Additional signal handers can be connected if you want to know when a drag begins (at the very instant it starts), to when a drop is made, and when the entire drag-and-drop procedure has ended (successfully or not).

Your application will need to provide data for source widgets when requested, that involves having a drag data request signal handler. For destination widgets they will need a drop data received signal handler.

So a typical drag-and-drop cycle would look as follows:

  1. Drag begins.

  2. Drag data request (when a drop occurs).

  3. Drop data received (may be on same or different application).

  4. Drag data delete (if the drag was a move).

  5. Drag-and-drop procedure done.

There are a few minor steps that go in between here and there, but we will get into detail about that later.

<<< Previous | Home | Next >>>
Supplying the selection |  | Properties


Properties

Drag data has the following properties:

  • Drag action type (ie GDK_ACTION_COPY, GDK_ACTION_MOVE).

  • Client specified arbitrary drag-and-drop type (a name and number pair).

  • Sent and received data format type.

Drag actions are quite obvious, they specify if the widget can drag with the specified action(s), e.g. GDK_ACTION_COPY and/or GDK_ACTION_MOVE. A GDK_ACTION_COPY would be a typical drag-and-drop without the source data being deleted while GDK_ACTION_MOVE would be just like GDK_ACTION_COPY but the source data will be “suggested” to be deleted after the received signal handler is called. There are additional drag actions including GDK_ACTION_LINK which you may want to look into when you get to more advanced levels of drag-and-drop.

The client specified arbitrary drag-and-drop type is much more flexible, because your application will be defining and checking for that specifically. You will need to set up your destination widgets to receive certain drag-and-drop types by specifying a name and/or number. It would be more reliable to use a name since another application may just happen to use the same number for an entirely different meaning.

Sent and received data format types (selection target) come into play only in your request and received data handler functions. The term selection target is somewhat misleading. It is a term adapted from GTK+ selection (cut/copy and paste). What selection target actually means is the data's format type (i.e. GdkAtom, integer, or string) that is being sent or received. Your request data handler function needs to specify the type (selection target) of data that it sends out and your received data handler needs to handle the type (selection target) of data received.

<<< Previous | Home | Next >>>
Drag-and-drop (DND) | Up | Functions


Functions

Setting up the source widget

The procedure gtk_drag_source_set specifies a set of target types for a drag operation on a widget.

Subroutine gtk_drag_source_set(widget,start_button_mask,actions,targets)
  Type(GtkWidget),Pointer :: widget
  Integer(GdkModifierType),Intent(In) :: start_button_mask
  Integer(GdkDragAction),Intent(In) :: actions
  Type(GtkTargetEntry),Optional :: targets(:)

The meanings of the arguments are:

  • widget specifies the drag source widget;
  • start_button_mask specifies a bitmask of buttons that can start the drag (e.g. GDK_BUTTON1_MASK);
  • actions specifies a bitmask of possible actions for a drag from this window;
  • targets specifies a table of target data types the drag will support (note that this is optional).

The targets argument is an array of the following structure.

Type,Bind(C) :: GtkTargetEntry
    Type(C_Ptr) :: target ! Pointer to a character string.
    Integer(guint) :: flags,info
End Type

The fields specify a string representing the drag type, optional flags and application assigned integer identifier.

If a widget is no longer required to act as a source for drag-and-drop operations, the procedure gtk_drag_source_unset can be used to remove a set of drag-and-drop target types.

Subroutine gtk_drag_source_unset(widget)
    Type(GtkWidget),Pointer :: widget

Signals on the source widget:

The source widget is sent the following signals during a drag-and-drop operation.

Table 1. Source widget signals

drag_begin Subroutine drag_begin(widget,dc,data) Bind(C)
  Type(GtkWidget),Target :: widget
  Type(GdkDragContext),Target :: dc
  Type(C_Ptr),Value :: data
drag_motion Integer(gboolean) Function drag_motion(widget,dc,x,y,t,data) Bind(C)
  Type(GtkWidget),Target :: widget
  Type(GdkDragContext),Target :: dc
  Integer(gint),Value :: x,y
  Integer(guint),Value :: t
  Type(C_Ptr),Value :: data
drag_data_get Subroutine drag_data_get(widget,dc,selection_data,info,t,data) Bind(C)
  Type(GtkWidget),Target :: widget
  Type(GdkDragContext),Target :: dc
  Type(GtkSelectionData),Target :: selection_data
  Integer(guint),Value :: info,t
  Type(C_Ptr),Value :: data
drag_data_delete Subroutine drag_data_delete(widget,dc,data) Bind(C)
  Type(GtkWidget),Target :: widget
  Type(GdkDragContext),Target :: dc
  Type(C_Ptr),Value :: data
drag_drop Integer(gboolean) Function drag_drop(widget,dc,x,y,t,data) Bind(C)
  Type(GtkWidget),Target :: widget
  Type(GdkDragContext),Target :: dc
  Integer(gint),Value :: x,y
  Integer(guint),Value :: t
  Type(C_Ptr),Value :: data
drag_end Subroutine drag_end(widget,dc,data) Bind(C)
  Type(GtkWidget),Target :: widget
  Type(GdkDragContext),Target :: dc
  Type(C_Ptr),Value :: data

Setting up a destination widget:

gtk_drag_dest_set specifies that this widget can receive drops and specifies what types of drops it can receive.

gtk_drag_dest_unset specifies that the widget can no longer receive drops.

Subroutine gtk_drag_source_set(widget,start_button_mask,actions,targets)
  Type(GtkWidget),Pointer :: widget
  Integer(GdkModifierType),Intent(In) :: start_button_mask
  Integer(GdkDragAction),Intent(In) :: actions
  Type(GtkTargetEntry),Intent(In),Optional,Target :: targets(:)

Subroutine gtk_drag_dest_unset(widget)
  Type(GtkWidget),Pointer :: widget

Signals on the destination widget:

The destination widget is sent the following signals during a drag-and-drop operation.

Table 2. Destination widget signals

drag_data_received Subroutine drag_data_received(widget,dc,x,y,selection_data,info,t,data) Bind(C)
  Type(GtkWidget),Target :: widget
  Type(GdkDragContext),Target :: dc
  Integer(gint),Value :: x,y
  Type(GtkSelectionData),Target :: selection_data
  Integer(guint),Value :: info,t
  Type(C_Ptr),Value :: data
<<< Previous | Home | Next >>>
Properties | Up | GLib


GLib

GLib is a lower-level library that provides many useful definitions and functions available for use when creating GDK and GTK applications. These include definitions for basic types and their limits, type conversions, byte order, memory allocation, warnings and assertions, message logging, timers, string utilities, hook functions, a lexical scanner, dynamic loading of modules, and automatic string completion. A number of data structures (and their related operations) are also defined, including memory chunks, doubly-linked lists, singly-linked lists, hash tables, strings (which can grow dynamically), string chunks (groups of strings), arrays (which can grow in size as elements are added), balanced binary trees, N-ary trees, quarks (a two-way association of a string and a unique integer identifier), keyed data lists (lists of data elements accessible by a string or integer id), relations and tuples (tables of data which can be indexed on any number of fields), and caches.

A summary of some of GLib's capabilities follows; not every function, data structure, or operation is covered here. For more complete information about the GLib routines, see the GLib documentation. One source of GLib documentation is http://www.gtk.org/.

Note that that documentation is all about C. Some GLib functionality is available natively in Fortran, but in any case most of it is only useful when interoperating with GDK and GTK.

Definitions

The following parameters are defined for kind numbers, in terms of the standard parameters from ISO_C_BINDING.

Parameter | Data Type | Equivalent to
gboolean | Integer | C_int
gint16 | Integer | C_int16_t
gint32 | Integer | C_int32_t
gint64 | Integer | C_int64_t
gint8 | Integer | C_int8_t
gint | Integer | C_int
glong | Integer | C_long
gsize | Integer | C_int
guint16 | Integer | C_int16_t
guint32 | Integer | C_int32_t
guint64 | Integer | C_int64_t
guint8 | Integer | C_int8_t
guint | Integer | C_int
gulong | Integer | C_long

You might well ask why so many aliases for C_int, why there is no equivalent of C_size_t, and why the duplication of the standard bit-length types.

<<< Previous | Home | Next >>>
Functions |  | Doubly Linked Lists


Doubly Linked Lists

The following functions are used to create, manage, and destroy Glib-defined doubly linked lists. Each element in the list contains a piece of data, together with pointers which link to the previous and next elements in the list. This enables easy movement in either direction through the list. The data item is of Type(C_Ptr), which means the data should be a pointer to your real data but C programmers often just use the bits to store integer values instead (very unportably). These routines internally allocate list elements in blocks, which is less efficient than allocating elements in Fortran.

There is no function to specifically create a list. Instead, simply create a Pointer variable of Type(GList) and nullify it; a null pointer is considered to be the empty list.

To add elements to a list, use the g_list_append, g_list_prepend, g_list_insert, or g_list_insert_sorted routines. In all cases they accept a pointer to the beginning of the list, and return the (possibly changed) pointer to the beginning of the list.

Function g_list_append(list,data) Result(res)
    Type(GList),Pointer :: list
    Type(C_Ptr),Intent(In) :: data
    Type(GList),Pointer :: res

This adds a new element (with value data) onto the end of the list.

Function g_list_prepend(list,data) Result(res)
    Type(GList),Pointer :: list
    Type(C_Ptr),Intent(In) :: data
    Type(GList),Pointer :: res

This adds a new element (with value data) to the beginning of the list.

Function g_list_insert(list,data,position) Result(res)
    Type(GList),Pointer :: list
    Type(C_Ptr),Intent(In) :: data
    Integer(gint),Intent(In) :: position
    Type(GList),Pointer :: res

This inserts a new element (with value data) into the list at the given position. If position is 0, this is just like g_list_prepend; if position is less than 0, this is just like g_list_append.

Function g_list_insert_sorted(list,data,func) Result(res)
  Type(GList),Pointer :: list
  Type(C_Ptr),Intent(In) :: data
  Type(C_FunPtr),Value :: func
  Type(GList),Pointer :: res

This inserts a new element (with value data) into a sorted list; func is the comparison function used to find right position. The function should have the signature
    Integer(gint) Function func(a,b)
        Type(C_Ptr),Value :: a,b
and should return a negative integer if a should come before b and a positive integer if b should come before a.

Function g_list_remove(list,data) Result(res)
    Type(GList),Pointer :: list
    Type(C_Ptr),Intent(In) :: data
    Type(GList),Pointer :: res

This removes the element in the list with the value data; if the element isn't there, the list is unchanged.

Subroutine g_list_free(list)
    Type(GList),Pointer :: list

This frees all of the memory used by a GList. If the list elements refer to dynamically-allocated memory, then they should be freed first.

There are many other GLib procedures that support doubly linked lists; see the glib documentation for more information. Here are a few of the more useful procedures' interfaces:

Function g_list_remove_link(list,llink) Result(res)
    Type(GList),Pointer :: list,llink
    Type(GList),Pointer :: res

Function g_list_reverse(list) Result(res)
    Type(GList),Pointer :: list
    Type(GList),Pointer :: res

Function g_list_nth(list,n) Result(res)
    Type(GList),Pointer :: list
    Integer(gint),Intent(In) :: n
    Type(GList),Pointer :: res

Function g_list_find(list,data) Result(res)
    Type(GList),Pointer :: list
    Type(C_Ptr),Intent(In) :: data
    Type(GList),Pointer :: res

Function g_list_last(list) Result(res)
    Type(GList),Pointer :: list
    Type(GList),Pointer :: res

Function g_list_first(list) Result(res)
    Type(GList),Pointer :: list
    Type(GList),Pointer :: res

Integer(gint) Function g_list_length(list)
    Type(GList),Pointer :: list

Subroutine g_list_foreach(list,func,user_data)
    Type(GList),Pointer :: list
    Type(C_FunPtr),Value :: func
    Type(C_Ptr),Intent(In) :: user_data

<<< Previous | Home | Next >>>
GLib | Up | Singly Linked Lists


Singly Linked Lists

Many of the above functions for singly linked lists are similar to the above. Here is a list of some of their operations:

Function g_slist_append(list,data) Result(res)
    Type(GSList),Pointer :: list
    Type(C_Ptr),Intent(In) :: data
    Type(GSList),Pointer :: res

Function g_slist_prepend(list,data) Result(res)
    Type(GSList),Pointer :: list
    Type(C_Ptr),Intent(In) :: data
    Type(GSList),Pointer :: res

Function g_slist_insert(list,data,position) Result(res)
    Type(GSList),Pointer :: list
    Type(C_Ptr),Intent(In) :: data
    Integer(gint),Intent(In) :: position
    Type(GSList),Pointer :: res

Function g_slist_remove(list,data) Result(res)
    Type(GSList),Pointer :: list
    Type(C_Ptr),Intent(In) :: data
    Type(GSList),Pointer :: res

Function g_slist_remove_link(list,link_) Result(res)
    Type(GSList),Pointer :: list,link_
    Type(GSList),Pointer :: res

Function g_slist_reverse(list) Result(res)
    Type(GSList),Pointer :: list
    Type(GSList),Pointer :: res

Function g_slist_nth(list,n) Result(res)
    Type(GSList),Pointer :: list
    Integer(guint),Intent(In) :: n
    Type(GSList),Pointer :: res

Function g_slist_find(list,data) Result(res)
    Type(GSList),Pointer :: list
    Type(C_Ptr),Intent(In) :: data
    Type(GSList),Pointer :: res

Function g_slist_last(list) Result(res)
    Type(GSList),Pointer :: list
    Type(GSList),Pointer :: res

Integer(guint) Function g_slist_length(list)
    Type(GSList),Pointer :: list

Subroutine g_slist_foreach(list,func,user_data)
    Type(GSList),Pointer :: list
    Type(C_FunPtr),Value :: func
    Type(C_Ptr),Intent(In) :: user_data

<<< Previous | Home | Next >>>
Doubly Linked Lists | Up | Memory Management


Memory Management

Type(C_Ptr) Function g_malloc(n_bytes)
    Integer(gulong),Intent(In) :: n_bytes

This is a replacement for the C malloc function; it should only be used when necessary to interact with GTK, as the native Fortran Allocate is more efficient. You do not need to check the return value as it is done for you in this function. If the memory allocation fails for whatever reasons, your application will be terminated.

Type(C_Ptr) Function g_malloc0(n_bytes)
    Integer(gulong),Intent(In) :: n_bytes

Same as above, but zeroes the memory before returning a pointer to it.

Type(C_Ptr) Function g_realloc(mem,n_bytes)
    Type(C_Ptr),Intent(In) :: mem
    Integer(gulong),Intent(In) :: n_bytes

Changes the size of the memory allocation identified by mem to be n_bytes bytes. The allocation must have been by a previous call of g_malloc, g_malloc0 or g_realloc.

Subroutine g_free(mem)
    Type(C_Ptr),Intent(In) :: mem

Frees memory previously allocated by one of the above routines. If mem is equal to C_Null_Ptr it simply returns.

Subroutine g_mem_profile()

Dumps a profile of used memory; this only does anything if the GLib installation supports such profiling (the default one does not).

<<< Previous | Home | Next >>>
Singly Linked Lists | Up | Timers


Timers

Timer functions can be used to time operations (e.g., to see how much time has elapsed). First, you create a new timer with g_timer_new. You can then use g_timer_start to start timing an operation, g_timer_stop to stop timing an operation, and g_timer_elapsed to determine the elapsed time.

Note that although these are very flexible, for simple timing operations you should use the native Fortran System_Clock intrinsic which has smaller overheads and greater precision.

Function g_timer_new() Result(res)
    Type(GTimer),Pointer :: res

Subroutine g_timer_destroy(timer)
    Type(GTimer),Pointer :: timer

Subroutine g_timer_start(timer)
    Type(GTimer),Pointer :: timer

Subroutine g_timer_stop(timer)
    Type(GTimer),Pointer :: timer

Subroutine g_timer_reset(timer)
    Type(GTimer),Pointer :: timer

Real(gdouble) Function g_timer_elapsed(timer,microseconds)
    Type(GTimer),Pointer :: timer
    Integer(gulong),Intent(Out),Optional :: microseconds

<<< Previous | Home | Next >>>
Memory Management | Up | String Handling


String Handling

GLib defines a new type called a GString, which is similar to a standard C string but one that grows automatically. Its string data is null-terminated. This is useful for programming in C, as it gives you protection against buffer overflow. For programming in Fortran, GString is more complicated and less convenient than use of deferred-length character strings, which should be used instead. Even if you don't want to use deferred-length strings, the GString API is very error-prone and so should only be used to interoperate with C libraries that themselves use GString.

GString itself has a simple public definition:

Type,Bind(C) :: GString
  Type(C_Ptr) :: str ! Pointer to the string data, null-terminated.
  Integer(gsize) :: len,allocated_len
End Type

As you might expect, there are a number of operations you can do with a GString.

Function g_string_new(init) Result(res)
    Character(*),Intent(In),Optional :: init
    Type(GString),Pointer :: res

This constructs a GString, copying the string value of init into the GString and returning a pointer to it. If init is not present, the GString is initially empty.

Function g_string_free(string,free_segment) Result(res)
    Type(GString),Pointer :: string
    Integer(gboolean),Intent(In) :: free_segment
    Character,Pointer :: res(:)

This frees the memory for the given GString. If free_segment is TRUE, then this also frees its character data. The return value is a pointer to the character data (if the data remains).

Function g_string_assign(string,rval) Result(res)
    Type(GString),Pointer :: string
    Character(*),Intent(In) :: rval
    Type(GString),Pointer :: res

This copies the characters from rval into string, destroying the previous contents of string. Note that string will be lengthened as necessary to hold the new contents, unlike the C strcpy function.

The rest of these functions should be relatively obvious:

Function g_string_truncate(string,len) Result(res)
    Type(GString),Pointer :: string
    Integer(gsize),Intent(In) :: len
    Type(GString),Pointer :: res

Function g_string_append(string,val) Result(res)
    Type(GString),Pointer :: String
    Character(*),Intent(In) :: val
    Type(GString),Pointer :: res

Function g_string_prepend(string,val) Result(res)
    Type(GString),Pointer :: string
    Character(*),Intent(In) :: val
    Type(GString),Pointer :: res

<<< Previous | Home | Next >>>
Timers | Up | Utility and Error Functions


Utility and Error Functions

Type(C_Ptr) Function g_cstrdup(str)
    Type(C_Ptr),Value :: str

Type(C_Ptr) Function g_fstrdup(str)
    Character(*),Intent(In) :: str

Replacement strdup function; comes in two flavours, one for duplicating a Fortran string (and null-terminating it), the other for duplicating a C string which is already null-terminated. Copies the original strings contents to newly allocated memory, and returns a C pointer to it.

There are multiple other error and utility functions in GLib, but they are either useless or dangerous (or both!) in Fortran, so are not documented here. For example, if you want to print out a message, just use the Print statement.

<<< Previous | Home | Next >>>
String Handling | Up | GTK's rc Files


GTK's rc Files

GTK has its own way of dealing with application defaults, by using rc files. These can be used to set the colours of just about any widget, and can also be used to tile pixmaps onto the background of some widgets.

Functions For rc Files

When your application starts, you should include a call to
    Subroutine gtk_rc_parse(filename)
        Character(*),Intent(In) :: filename
passing in the filename of your rc file. This will cause GTK to read this file, and use the style settings for the widget types defined there.

If you wish to have a special set of widgets that can take on a different style from others, or any other logical division of widgets, use a call to
    Subroutine gtk_widget_set_name(widget,name)
        Type(GtkWidget),Pointer :: widget
        Character(*),Intent(In) :: name
passing your newly created widget as the first argument, and the name you wish to give it as the second. This will allow you to change the attributes of this widget by name through the rc file.

If we use a call something like
button => gtk_button_new_with_label("Special Button")
Call gtk_widget_set_name(button,"special button")
then this button is given the name “special button” and may be addressed by name in the rc file as “special button.GtkButton”.

The example rc file below sets the properties of the main window, and lets all children of that main window inherit the style described by the “main button” style. The code used in the application is:

window => gtk_window_new(GTK_WINDOW_TOPLEVEL)
Call gtk_widget_set_name(window,"main window")

The style is defined in the rc file using:

widget "main window.*GtkButton*" style "main_button"

This sets all the Button widgets in the “main window” to the “main_buttons” style as defined in the rc file.

As you can see, this is a fairly powerful and flexible system. Use your imagination as to how best to take advantage of this.

<<< Previous | Home | Next >>>
Utility and Error Functions |  | GTK's rc File Format


GTK's rc File Format

The format of the GTK file is illustrated in the example below. This is the testgtkrc file from the GTK distribution, but I've added a few comments and things. You may wish to include this explanation in your application to allow the user to fine tune his application.

There are several directives to change the attributes of a widget.

  • fg – Sets the foreground color of a widget.

  • bg – Sets the background color of a widget.

  • bg_pixmap – Sets the background of a widget to a tiled pixmap.

  • font – Sets the font to be used with the given widget.

In addition to this, there are several states a widget can be in, and you can set different colors, pixmaps and fonts for each state. These states are:

  • NORMAL – The normal state of a widget, without the mouse over top of it, and not being pressed, etc..

  • PRELIGHT – When the mouse is over top of the widget, colours defined using this state will be in effect.

  • ACTIVE – When the widget is pressed or clicked it will be active, and the attributes assigned by this tag will be in effect.

  • INSENSITIVE – When a widget is set insensitive, and cannot be activated, it will take these attributes.

  • SELECTED - When an object is selected, it takes these attributes.

When using the “fg” and “bg” keywords to set the colours of widgets, the format is:

fg[<STATE>] = { Red, Green, Blue }

Where STATE is one of the above states (PRELIGHT, ACTIVE, etc), and the Red, Green and Blue are values in the range of 0 - 1.0, { 1.0, 1.0, 1.0 } being white. They must be in float form, or they will register as 0, so a straight “1” will not work, it must be “1.0”. A straight “0” is fine because it doesn't matter if it's not recognized. Unrecognised values are set to zero.

bg_pixmap is very similar to the above, except the colours are replaced by a filename.

pixmap_path is a list of paths separated by colons (:). These paths will be searched for any pixmap you specify.

The font directive is simply:

font = "<font name>"

The “widget_class” sets the style of a class of widgets. These classes are listed in the widget overview on the class hierarchy.

The “widget” directive sets a specifically named set of widgets to a given style, overriding any style set for the given widget class. These widgets are registered inside the application using the gtk_widget_set_name call. This allows you to specify the attributes of a widget on a per widget basis, rather than setting the attributes of an entire widget class. I urge you to document any of these special widgets so users may customize them.

When the keyword parent is used as an attribute, the widget will take on the attributes of its parent in the application.

When defining a style, you may assign the attributes of a previously defined style to this new one.

style "main_button" = "button"
{
  font = "-adobe-helvetica-medium-r-normal--*-100-*-*-*-*-*-*"
  bg[PRELIGHT] = { 0.75, 0, 0 }
}

This example takes the “button” style, and creates a new “main_button” style simply by changing the font and prelight background color of the “button” style.

Of course, many of these attributes don't apply to all widgets. It's a simple matter of common sense really. Anything that could apply, should.

<<< Previous | Home | Next >>>
GTK's rc Files | Up | Example rc file


Example rc file

# pixmap_path "<dir 1>:<dir 2>:<dir 3>:..."
#
pixmap_path "/usr/include/X11R6/pixmaps:/home/imain/pixmaps"
#
# style <name> [= <name>]
# {
#   <option>
# }
#
# widget <widget_set> style <style_name>
# widget_class <widget_class_set> style <style_name>

# Here is a list of all the possible states.  Note that some do not apply to
# certain widgets.
#
# NORMAL - The normal state of a widget, without the mouse over top of
# it, and not being pressed, etc.
#
# PRELIGHT - When the mouse is over top of the widget, colors defined
# using this state will be in effect.
#
# ACTIVE - When the widget is pressed or clicked it will be active, and
# the attributes assigned by this tag will be in effect.
#
# INSENSITIVE - When a widget is set insensitive, and cannot be
# activated, it will take these attributes.
#
# SELECTED - When an object is selected, it takes these attributes.
#
# Given these states, we can set the attributes of the widgets in each of
# these states using the following directives.
#
# fg - Sets the foreground color of a widget.
# fg - Sets the background color of a widget.
# bg_pixmap - Sets the background of a widget to a tiled pixmap.
# font - Sets the font to be used with the given widget.
#

# This sets a style called "button".  The name is not really important, as
# it is assigned to the actual widgets at the bottom of the file.

style "window"
{
  #This sets the padding around the window to the pixmap specified.
  #bg_pixmap[<STATE>] = "<pixmap filename>"
  bg_pixmap[NORMAL] = "warning.xpm"
}

style "scale"
{
  #Sets the foreground color (font color) to red when in the "NORMAL"
  #state.

  fg[NORMAL] = { 1.0, 0, 0 }

  #Sets the background pixmap of this widget to that of its parent.
  bg_pixmap[NORMAL] = "<parent>"
}

style "button"
{
  # This shows all the possible states for a button.  The only one that
  # doesn't apply is the SELECTED state.

  fg[PRELIGHT] = { 0, 1.0, 1.0 }
  bg[PRELIGHT] = { 0, 0, 1.0 }
  bg[ACTIVE] = { 1.0, 0, 0 }
  fg[ACTIVE] = { 0, 1.0, 0 }
  bg[NORMAL] = { 1.0, 1.0, 0 }
  fg[NORMAL] = { .99, 0, .99 }
  bg[INSENSITIVE] = { 1.0, 1.0, 1.0 }
  fg[INSENSITIVE] = { 1.0, 0, 1.0 }
}

# In this example, we inherit the attributes of the "button" style and then
# override the font and background color when prelit to create a new
# "main_button" style.

style "main_button" = "button"
{
  font = "-adobe-helvetica-medium-r-normal--*-100-*-*-*-*-*-*"
  bg[PRELIGHT] = { 0.75, 0, 0 }
}

style "toggle_button" = "button"
{
  fg[NORMAL] = { 1.0, 0, 0 }
  fg[ACTIVE] = { 1.0, 0, 0 }

  # This sets the background pixmap of the toggle_button to that of its
  # parent widget (as defined in the application).
  bg_pixmap[NORMAL] = "<parent>"
}

style "text"
{
  bg_pixmap[NORMAL] = "marble.xpm"
  fg[NORMAL] = { 1.0, 1.0, 1.0 }
}

style "ruler"
{
  font = "-adobe-helvetica-medium-r-normal--*-80-*-*-*-*-*-*"
}

# pixmap_path "~/.pixmaps"

# These set the widget types to use the styles defined above.
# The widget types are listed in the class hierarchy, but could probably be
# just listed in this document for the users reference.

widget_class "GtkWindow" style "window"
widget_class "GtkDialog" style "window"
widget_class "GtkFileSelection" style "window"
widget_class "*Gtk*Scale" style "scale"
widget_class "*GtkCheckButton*" style "toggle_button"
widget_class "*GtkRadioButton*" style "toggle_button"
widget_class "*GtkButton*" style "button"
widget_class "*Ruler" style "ruler"
widget_class "*GtkText" style "text"

# This sets all the buttons that are children of the "main window" to
# the main_button style.  These must be documented to be taken advantage of.
widget "main window.*GtkButton*" style "main_button"

<<< Previous | Home | Next >>>
GTK's rc File Format | Up | Writing Your Own Widgets


Writing Your Own Widgets

Overview

Although the GTK distribution comes with many types of widgets that should cover most basic needs, there may come a time when you need to create your own new widget type. Since GTK uses widget inheritance extensively, and there is already a widget that is close to what you want, it is often possible to make a useful new widget type in just a few lines of code. But before starting work on a new widget, check around first to make sure that someone has not already written it. This will prevent duplication of effort and keep the number of GTK widgets out there to a minimum, which will help keep both the code and the interface of different applications consistent. As a flip side to this, once you finish your widget, announce it to the world so other people can benefit.

Complete sources for the example widgets are probably available somewhere on http://www.gtk.org/, but they might be well hidden – good luck!

<<< Previous | Home | Next >>>
Example rc file |  | The Anatomy Of A Widget


The Anatomy Of A Widget

In order to create a new widget, it is important to have an understanding of how GTK objects work. This section is just meant as a brief overview. See the reference documentation for the details.

GTK widgets are implemented in an object oriented fashion. However, they are implemented in standard C. This greatly improves portability and stability over using current generation C++ compilers; however, it does mean that the widget writer has to pay attention to some of the implementation details. The information common to all instances of one class of widgets (e.g., to all Button widgets) is stored in the class structure. There is only one copy of this in which is stored information about the class's signals (which act like virtual functions in C). To support inheritance, the first field in the class structure must be a copy of the parent's class structure. The declaration of the class structure of GtkButtton looks like:

struct _GtkButtonClass
{
  GtkContainerClass parent_class;

  void (* pressed)  (GtkButton *button);
  void (* released) (GtkButton *button);
  void (* clicked)  (GtkButton *button);
  void (* enter)    (GtkButton *button);
  void (* leave)    (GtkButton *button);
};

When a button is treated as a container (for instance, when it is resized), its class structure can be cast to GtkContainerClass, and the relevant fields used to handle the signals.

There is also a structure for each widget that is created on a per-instance basis. This structure has fields to store information that is different for each instance of the widget. We'll call this structure the object structure. For the Button class, it looks like:

struct _GtkButton
{
  GtkContainer container;

  GtkWidget *child;

  guint in_button : 1;
  guint button_down : 1;
};

Note that, similar to the class structure, the first field is the object structure of the parent class, so that this structure can be cast to the parent class' object structure as needed.

<<< Previous | Home | Next >>>
Writing Your Own Widgets | Up | Creating a Composite widget


Creating a Composite widget

Introduction

One type of widget that you may be interested in creating is a widget that is merely an aggregate of other GTK widgets. This type of widget does nothing that couldn't be done without creating new widgets, but provides a convenient way of packaging user interface elements for reuse. The FileSelection and ColorSelection widgets in the standard distribution are examples of this type of widget.

The example widget that we'll create in this section is the Tictactoe widget, a 3x3 array of toggle buttons which triggers a signal when all three buttons in a row, column, or on one of the diagonals are depressed.

Choosing a parent class

The parent class for a composite widget is typically the container class that holds all of the elements of the composite widget. For example, the parent class of the FileSelection widget is the Dialog class. Since our buttons will be arranged in a table, it is natural to make our parent class the Table class.

The header file

Each GObject class has a header file which declares the object and class structures for that object, along with public functions. A couple of features are worth pointing out. To prevent duplicate definitions, we wrap the entire header file in:

#ifndef __TICTACTOE_H__
#define __TICTACTOE_H__
.
.
.
#endif /* __TICTACTOE_H__ */

And to keep C++ programs that include the header file happy, in:

#include <glib.h>

G_BEGIN_DECLS
.
.
.
G_END_DECLS

Along with the functions and structures, we declare five standard macros in our header file, TICTACTOE_TYPE, TICTACTOE(obj), TICTACTOE_CLASS(klass), IS_TICTACTOE(obj), and IS_TICTACTOE_CLASS(klass), which cast a pointer into a pointer to the object or class structure, and check if an object is a Tictactoe widget respectively.

The _get_type() function

We now continue on to the implementation of our widget. A core function for every object is the function WIDGETNAME_get_type(). This function, when first called, tells Glib about the new class, and gets an ID that uniquely identifies the class. Upon subsequent calls, it just returns the ID.

GType
tictactoe_get_type (void)
{
  static GType ttt_type = 0;

  if (!ttt_type)
    {
      static const GTypeInfo ttt_info =
      {
    sizeof (TictactoeClass),
    NULL, /* base_init */
    NULL, /* base_finalize */
    (GClassInitFunc) tictactoe_class_init,
    NULL, /* class_finalize */
    NULL, /* class_data */
    sizeof (Tictactoe),
    0,    /* n_preallocs */
    (GInstanceInitFunc) tictactoe_init,
      };

      ttt_type = g_type_register_static (GTK_TYPE_TABLE,
                                         "Tictactoe",
                                         &ttt_info,
                                         0);
    }

  return ttt_type;
}

The GTypeInfo structure has the following definition:

struct _GTypeInfo
{
  /* interface types, classed types, instantiated types */
  guint16                class_size;

  GBaseInitFunc          base_init;
  GBaseFinalizeFunc      base_finalize;

  /* classed types, instantiated types */
  GClassInitFunc         class_init;
  GClassFinalizeFunc     class_finalize;
  gconstpointer          class_data;

  /* instantiated types */
  guint16                instance_size;
  guint16                n_preallocs;
  GInstanceInitFunc      instance_init;

  /* value handling */
  const GTypeValueTable *value_table;
};

The important fields of this structure are pretty self-explanatory. We'll ignore the base_init and base_finalize as well as the value_table fields here. Once Glib has a correctly filled in copy of this structure, it knows how to create objects of a particular type.

The _class_init() function

The WIDGETNAME_class_init() function initializes the fields of the widget's class structure, and sets up any signals for the class. For our Tictactoe widget it looks like:

enum {
  TICTACTOE_SIGNAL,
  LAST_SIGNAL
};

static guint tictactoe_signals[LAST_SIGNAL] = { 0 };

static void
tictactoe_class_init (TictactoeClass *klass)
{
  tictactoe_signals[TICTACTOE_SIGNAL] =
    g_signal_new ("tictactoe",
                  G_TYPE_FROM_CLASS (klass),
                  G_SIGNAL_RUN_FIRST | G_SIGNAL_ACTION,
                  G_STRUCT_OFFSET (TictactoeClass, tictactoe),
                  NULL, NULL,
                  g_cclosure_marshal_VOID__VOID, G_TYPE_NONE, 0);
}

Our widget has just one signal, the tictactoe signal that is invoked when a row, column, or diagonal is completely filled in. Not every composite widget needs signals, so if you are reading this for the first time, you may want to skip to the next section now, as things are going to get a bit complicated.

The function:

guint g_signal_new( const gchar         *signal_name,
                    GType                itype,
                    GSignalFlags         signal_flags,
                    guint                class_offset,
                    GSignalAccumulator  *accumulator,
                    gpointer             accu_data,
                    GSignalCMarshaller  *c_marshaller,
                    GType                return_type,
                    guint                n_params,
                    ...);

Creates a new signal. The parameters are:

  • signal_name: The name of the signal.

  • itype: The ID of the object that this signal applies to. (It will also apply to that objects descendants.)

  • signal_flags: Whether the default handler runs before or after user handlers and other flags. Usually this will be one of G_SIGNAL_RUN_FIRST or G_SIGNAL_RUN_LAST, although there are other possibilities. The flag G_SIGNAL_ACTION specifies that no extra code needs to run that performs special pre or post emission adjustments. This means that the signal can also be emitted from object external code.

  • class_offset: The offset within the class structure of a pointer to the default handler.

  • accumulator: For most classes this can be set to NULL.

  • accu_data: User data that will be handed to the accumulator function.

  • c_marshaller: A function that is used to invoke the signal handler. For signal handlers that have no arguments other than the object that emitted the signal and user data, we can use the pre-supplied marshaller function g_cclosure_marshal_VOID__VOID.

  • return_type: The type of the return value.

  • n_params: The number of parameters of the signal handler (other than the two default ones mentioned above).

  • ...: The types of the parameters.

When specifying types, the following standard types can be used:

G_TYPE_INVALID
G_TYPE_NONE
G_TYPE_INTERFACE
G_TYPE_CHAR
G_TYPE_UCHAR
G_TYPE_BOOLEAN
G_TYPE_INT
G_TYPE_UINT
G_TYPE_LONG
G_TYPE_ULONG
G_TYPE_INT64
G_TYPE_UINT64
G_TYPE_ENUM
G_TYPE_FLAGS
G_TYPE_FLOAT
G_TYPE_DOUBLE
G_TYPE_STRING
G_TYPE_POINTER
G_TYPE_BOXED
G_TYPE_PARAM
G_TYPE_OBJECT

g_signal_new() returns a unique integer identifier for the signal, that we store in the tictactoe_signals array, which we index using an enumeration. (Conventionally, the enumeration elements are the signal name, uppercased, but here there would be a conflict with the TICTACTOE() macro, so we called it TICTACTOE_SIGNAL instead.

The _init() function

Each class also needs a function to initialize the object structure. Usually, this function has the fairly limited role of setting the fields of the structure to default values. For composite widgets, however, this function also creates the component widgets.

static void
tictactoe_init (Tictactoe *ttt)
{
  gint i,j;

  gtk_table_resize (GTK_TABLE (ttt), 3, 3);
  gtk_table_set_homogeneous (GTK_TABLE (ttt), TRUE);

  for (i=0;i<3; i++)
    for (j=0;j<3; j++)
      {
    ttt->buttons[i][j] = gtk_toggle_button_new ();
    gtk_table_attach_defaults (GTK_TABLE (ttt), ttt->buttons[i][j],
                   i, i+1, j, j+1);
    g_signal_connect (G_OBJECT (ttt->buttons[i][j]), "toggled",
              G_CALLBACK (tictactoe_toggle), ttt);
    gtk_widget_set_size_request (ttt->buttons[i][j], 20, 20);
    gtk_widget_show (ttt->buttons[i][j]);
      }
}

And the rest...

There is one more function that every object (except for abstract classes like Bin that cannot be instantiated) needs to have – the function that the user calls to create an object of that type. This is conventionally called OBJECTNAME_new(). In some widgets, though not for the Tictactoe widgets, this function takes arguments, and does some setup based on the arguments. The other two functions are specific to the Tictactoe widget.

tictactoe_clear() is a public function that resets all the buttons in the widget to the up position. Note the use of g_signal_handlers_block_matched() to keep our signal handler for button toggles from being triggered unnecessarily.

tictactoe_toggle() is the signal handler that is invoked when the user clicks on a button. It checks to see if there are any winning combinations that involve the toggled button, and if so, emits the “tictactoe” signal.

GtkWidget*
tictactoe_new (void)
{
  return GTK_WIDGET ( g_object_new (TICTACTOE_TYPE, NULL));
}

void
tictactoe_clear (Tictactoe *ttt)
{
  int i,j;

  for (i=0;i<3;i++)
    for (j=0;j<3;j++)
      {
    g_signal_handlers_block_matched (G_OBJECT (ttt->buttons[i][j]),
                                         G_SIGNAL_MATCH_DATA,
                                         0, 0, NULL, NULL, ttt);
    gtk_toggle_button_set_active (GTK_TOGGLE_BUTTON (ttt->buttons[i][j]),
                     FALSE);
    g_signal_handlers_unblock_matched (G_OBJECT (ttt->buttons[i][j]),
                                           G_SIGNAL_MATCH_DATA,
                                           0, 0, NULL, NULL, ttt);
      }
}

static void
tictactoe_toggle (GtkWidget *widget, Tictactoe *ttt)
{
  int i,k;

  static int rwins[8][3] = { { 0, 0, 0 }, { 1, 1, 1 }, { 2, 2, 2 },
                 { 0, 1, 2 }, { 0, 1, 2 }, { 0, 1, 2 },
                 { 0, 1, 2 }, { 0, 1, 2 } };
  static int cwins[8][3] = { { 0, 1, 2 }, { 0, 1, 2 }, { 0, 1, 2 },
                 { 0, 0, 0 }, { 1, 1, 1 }, { 2, 2, 2 },
                 { 0, 1, 2 }, { 2, 1, 0 } };

  int success, found;

  for (k=0; k<8; k++)
    {
      success = TRUE;
      found = FALSE;

      for (i=0;i<3;i++)
    {
      success = success &&
        GTK_TOGGLE_BUTTON(ttt->buttons[rwins[k][i]][cwins[k][i]])->active;
      found = found ||
        ttt->buttons[rwins[k][i]][cwins[k][i]] == widget;
    }

      if (success && found)
    {
      g_signal_emit (G_OBJECT (ttt),
             tictactoe_signals[TICTACTOE_SIGNAL], 0);
      break;
    }
    }
}

And finally, an example program using our Tictactoe widget:

#include <gtk/gtk.h>
#include "tictactoe.h"

/* Invoked when a row, column or diagonal is completed */
void
win (GtkWidget *widget, gpointer data)
{
  g_print ("Yay!\n");
  tictactoe_clear (TICTACTOE (widget));
}

int
main (int argc, char *argv[])
{
  GtkWidget *window;
  GtkWidget *ttt;

  gtk_init (&argc, &argv);

  window = gtk_window_new (GTK_WINDOW_TOPLEVEL);

  gtk_window_set_title (GTK_WINDOW (window), "Aspect Frame");

  g_signal_connect (G_OBJECT (window), "destroy",
                    G_CALLBACK (exit), NULL);

  gtk_container_set_border_width (GTK_CONTAINER (window), 10);

  /* Create a new Tictactoe widget */
  ttt = tictactoe_new ();
  gtk_container_add (GTK_CONTAINER (window), ttt);
  gtk_widget_show (ttt);

  /* And attach to its "tictactoe" signal */
  g_signal_connect (G_OBJECT (ttt), "tictactoe",
                    G_CALLBACK (win), NULL);

  gtk_widget_show (window);

  gtk_main ();

  return 0;
}

<<< Previous | Home | Next >>>
The Anatomy Of A Widget | Up | Creating a widget from scratch


Creating a widget from scratch

Introduction

In this section, we'll learn more about how widgets display themselves on the screen and interact with events. As an example of this, we'll create an analogue dial widget with a pointer that the user can drag to set the value.

Displaying a widget on the screen

There are several steps that are involved in displaying on the screen. After the widget is created with a call to WIDGETNAME_new(), several more functions are needed:

  • WIDGETNAME_realize() is responsible for creating an X window for the widget if it has one.

  • WIDGETNAME_map() is invoked after the user calls gtk_widget_show(). It is responsible for making sure the widget is actually drawn on the screen (mapped). For a container class, it must also make calls to map() functions of any child widgets.

  • WIDGETNAME_draw() is invoked when gtk_widget_draw() is called for the widget or one of its ancestors. It makes the actual calls to the drawing functions to draw the widget on the screen. For container widgets, this function must make calls to gtk_widget_draw() for its child widgets.

  • WIDGETNAME_expose() is a handler for expose events for the widget. It makes the necessary calls to the drawing functions to draw the exposed portion on the screen. For container widgets, this function must generate expose events for its child widgets which don't have their own windows. (If they have their own windows, then X will generate the necessary expose events.)

You might notice that the last two functions are quite similar – each is responsible for drawing the widget on the screen. In fact many types of widgets don't really care about the difference between the two. The default draw() function in the widget class simply generates a synthetic expose event for the redrawn area. However, some types of widgets can save work by distinguishing between the two functions. For instance, if a widget has multiple X windows, then since expose events identify the exposed window, it can redraw only the affected window, which is not possible for calls to draw().

Container widgets, even if they don't care about the difference for themselves, can't simply use the default draw() function because their child widgets might care about the difference. However, it would be wasteful to duplicate the drawing code between the two functions. The convention is that such widgets have a function called WIDGETNAME_paint() that does the actual work of drawing the widget, that is then called by the draw() and expose() functions.

In our example approach, since the dial widget is not a container widget, and only has a single window, we can take the simplest approach and use the default draw() function and only implement an expose() function.

The origins of the Dial Widget

Just as all land animals are just variants on the first amphibian that crawled up out of the mud, GTK widgets tend to start off as variants of some other, previously written widget. Thus, although this section is entitled "Creating a Widget from Scratch", the Dial widget really began with the source code for the Range widget. This was picked as a starting point because it would be nice if our Dial had the same interface as the Scale widgets which are just specialized descendants of the Range widget. So, though the source code is presented below in finished form, it should not be implied that it was written, ab initio in this fashion. Also, if you aren't yet familiar with how scale widgets work from the application writer's point of view, it would be a good idea to look them over before continuing.

The Basics

Quite a bit of our widget should look pretty familiar from the Tictactoe widget. First, we have a header file:

/* GTK - The GIMP Toolkit
 * Copyright (C) 1995-1997 Peter Mattis, Spencer Kimball and Josh MacDonald
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Library General Public
 * License as published by the Free Software Foundation; either
 * version 2 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Library General Public License for more details.
 *
 * You should have received a copy of the GNU Library General Public
 * License along with this library; if not, write to the Free
 * Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
 */

#ifndef __GTK_DIAL_H__
#define __GTK_DIAL_H__

#include <gdk/gdk.h>
#include <gtk/gtkadjustment.h>
#include <gtk/gtkwidget.h>

#ifdef __cplusplus
extern "C" {
#endif /* __cplusplus */

#define GTK_DIAL(obj)          GTK_CHECK_CAST (obj, gtk_dial_get_type (), GtkDial)
#define GTK_DIAL_CLASS(klass)  GTK_CHECK_CLASS_CAST (klass, gtk_dial_get_type (), GtkDialClass)
#define GTK_IS_DIAL(obj)       GTK_CHECK_TYPE (obj, gtk_dial_get_type ())

typedef struct _GtkDial        GtkDial;
typedef struct _GtkDialClass   GtkDialClass;

struct _GtkDial
{
  GtkWidget widget;

  /* update policy (GTK_UPDATE_[CONTINUOUS/DELAYED/DISCONTINUOUS]) */
  guint policy : 2;

  /* Button currently pressed or 0 if none */
  guint8 button;

  /* Dimensions of dial components */
  gint radius;
  gint pointer_width;

  /* ID of update timer, or 0 if none */
  guint32 timer;

  /* Current angle */
  gfloat angle;

  /* Old values from adjustment stored so we know when something changes */
  gfloat old_value;
  gfloat old_lower;
  gfloat old_upper;

  /* The adjustment object that stores the data for this dial */
  GtkAdjustment *adjustment;
};

struct _GtkDialClass
{
  GtkWidgetClass parent_class;
};

GtkWidget*     gtk_dial_new                    (GtkAdjustment *adjustment);
GtkType        gtk_dial_get_type               (void);
GtkAdjustment* gtk_dial_get_adjustment         (GtkDial      *dial);
void           gtk_dial_set_update_policy      (GtkDial      *dial,
                        GtkUpdateType  policy);

void           gtk_dial_set_adjustment         (GtkDial      *dial,
                        GtkAdjustment *adjustment);
#ifdef __cplusplus
}
#endif /* __cplusplus */

#endif /* __GTK_DIAL_H__ */

Since there is quite a bit more going on in this widget than the last one, we have more fields in the data structure, but otherwise things are pretty similar.

Next, after including header files and declaring a few constants, we have some functions to provide information about the widget and initialize it:

#include <math.h>
#include <stdio.h>
#include <gtk/gtkmain.h>
#include <gtk/gtksignal.h>

#include "gtkdial.h"

#define SCROLL_DELAY_LENGTH  300
#define DIAL_DEFAULT_SIZE 100

/* Forward declarations */

[ omitted to save space ]

/* Local data */

static GtkWidgetClass *parent_class = NULL;

GtkType
gtk_dial_get_type ()
{
  static GtkType dial_type = 0;

  if (!dial_type)
    {
      static const GtkTypeInfo dial_info =
      {
    "GtkDial",
    sizeof (GtkDial),
    sizeof (GtkDialClass),
    (GtkClassInitFunc) gtk_dial_class_init,
    (GtkObjectInitFunc) gtk_dial_init,
    /* reserved_1 */ NULL,
    /* reserved_1 */ NULL,
    (GtkClassInitFunc) NULL
      };

      dial_type = gtk_type_unique (GTK_TYPE_WIDGET, &dial_info);
    }

  return dial_type;
}

static void
gtk_dial_class_init (GtkDialClass *class)
{
  GtkObjectClass *object_class;
  GtkWidgetClass *widget_class;

  object_class = (GtkObjectClass*) class;
  widget_class = (GtkWidgetClass*) class;

  parent_class = gtk_type_class (gtk_widget_get_type ());

  object_class->destroy = gtk_dial_destroy;

  widget_class->realize = gtk_dial_realize;
  widget_class->expose_event = gtk_dial_expose;
  widget_class->size_request = gtk_dial_size_request;
  widget_class->size_allocate = gtk_dial_size_allocate;
  widget_class->button_press_event = gtk_dial_button_press;
  widget_class->button_release_event = gtk_dial_button_release;
  widget_class->motion_notify_event = gtk_dial_motion_notify;
}

static void
gtk_dial_init (GtkDial *dial)
{
  dial->button = 0;
  dial->policy = GTK_UPDATE_CONTINUOUS;
  dial->timer = 0;
  dial->radius = 0;
  dial->pointer_width = 0;
  dial->angle = 0.0;
  dial->old_value = 0.0;
  dial->old_lower = 0.0;
  dial->old_upper = 0.0;
  dial->adjustment = NULL;
}

GtkWidget*
gtk_dial_new (GtkAdjustment *adjustment)
{
  GtkDial *dial;

  dial = gtk_type_new (gtk_dial_get_type ());

  if (!adjustment)
    adjustment = (GtkAdjustment*) gtk_adjustment_new (0.0, 0.0, 0.0, 0.0, 0.0, 0.0);

  gtk_dial_set_adjustment (dial, adjustment);

  return GTK_WIDGET (dial);
}

static void
gtk_dial_destroy (GtkObject *object)
{
  GtkDial *dial;

  g_return_if_fail (object != NULL);
  g_return_if_fail (GTK_IS_DIAL (object));

  dial = GTK_DIAL (object);

  if (dial->adjustment)
    gtk_object_unref (GTK_OBJECT (dial->adjustment));

  if (GTK_OBJECT_CLASS (parent_class)->destroy)
    (* GTK_OBJECT_CLASS (parent_class)->destroy) (object);
}

Note that this init() function does less than for the Tictactoe widget, since this is not a composite widget, and the new() function does more, since it now has an argument. Also, note that when we store a pointer to the Adjustment object, we increment its reference count, (and correspondingly decrement it when we no longer use it) so that GTK can keep track of when it can be safely destroyed.

Also, there are a few function to manipulate the widget's options:

GtkAdjustment*
gtk_dial_get_adjustment (GtkDial *dial)
{
  g_return_val_if_fail (dial != NULL, NULL);
  g_return_val_if_fail (GTK_IS_DIAL (dial), NULL);

  return dial->adjustment;
}

void
gtk_dial_set_update_policy (GtkDial      *dial,
                 GtkUpdateType  policy)
{
  g_return_if_fail (dial != NULL);
  g_return_if_fail (GTK_IS_DIAL (dial));

  dial->policy = policy;
}

void
gtk_dial_set_adjustment (GtkDial      *dial,
              GtkAdjustment *adjustment)
{
  g_return_if_fail (dial != NULL);
  g_return_if_fail (GTK_IS_DIAL (dial));

  if (dial->adjustment)
    {
      gtk_signal_disconnect_by_data (GTK_OBJECT (dial->adjustment), (gpointer) dial);
      gtk_object_unref (GTK_OBJECT (dial->adjustment));
    }

  dial->adjustment = adjustment;
  gtk_object_ref (GTK_OBJECT (dial->adjustment));

  gtk_signal_connect (GTK_OBJECT (adjustment), "changed",
              (GtkSignalFunc) gtk_dial_adjustment_changed,
              (gpointer) dial);
  gtk_signal_connect (GTK_OBJECT (adjustment), "value_changed",
              (GtkSignalFunc) gtk_dial_adjustment_value_changed,
              (gpointer) dial);

  dial->old_value = adjustment->value;
  dial->old_lower = adjustment->lower;
  dial->old_upper = adjustment->upper;

  gtk_dial_update (dial);
}

gtk_dial_realize()

Now we come to some new types of functions. First, we have a function that does the work of creating the X window. Notice that a mask is passed to the function gdk_window_new() which specifies which fields of the GdkWindowAttr structure actually have data in them (the remaining fields will be given default values). Also worth noting is the way the event mask of the widget is created. We call gtk_widget_get_events() to retrieve the event mask that the user has specified for this widget (with gtk_widget_set_events()), and add the events that we are interested in ourselves.

After creating the window, we set its style and background, and put a pointer to the widget in the user data field of the GdkWindow. This last step allows GTK to dispatch events for this window to the correct widget.

static void
gtk_dial_realize (GtkWidget *widget)
{
  GtkDial *dial;
  GdkWindowAttr attributes;
  gint attributes_mask;

  g_return_if_fail (widget != NULL);
  g_return_if_fail (GTK_IS_DIAL (widget));

  GTK_WIDGET_SET_FLAGS (widget, GTK_REALIZED);
  dial = GTK_DIAL (widget);

  attributes.x = widget->allocation.x;
  attributes.y = widget->allocation.y;
  attributes.width = widget->allocation.width;
  attributes.height = widget->allocation.height;
  attributes.wclass = GDK_INPUT_OUTPUT;
  attributes.window_type = GDK_WINDOW_CHILD;
  attributes.event_mask = gtk_widget_get_events (widget) |
    GDK_EXPOSURE_MASK | GDK_BUTTON_PRESS_MASK |
    GDK_BUTTON_RELEASE_MASK | GDK_POINTER_MOTION_MASK |
    GDK_POINTER_MOTION_HINT_MASK;
  attributes.visual = gtk_widget_get_visual (widget);
  attributes.colormap = gtk_widget_get_colormap (widget);

  attributes_mask = GDK_WA_X | GDK_WA_Y | GDK_WA_VISUAL | GDK_WA_COLORMAP;
  widget->window = gdk_window_new (gtk_widget_get_parent_window (widget), &attributes, attributes_mask);

  widget->style = gtk_style_attach (widget->style, widget->window);

  gdk_window_set_user_data (widget->window, widget);

  gtk_style_set_background (widget->style, widget->window, GTK_STATE_ACTIVE);
}

Size negotiation

Before the first time that the window containing a widget is displayed, and whenever the layout of the window changes, GTK asks each child widget for its desired size. This request is handled by the function gtk_dial_size_request(). Since our widget isn't a container widget, and has no real constraints on its size, we just return a reasonable default value.

static void
gtk_dial_size_request (GtkWidget      *widget,
               GtkRequisition *requisition)
{
  requisition->width = DIAL_DEFAULT_SIZE;
  requisition->height = DIAL_DEFAULT_SIZE;
}

After all the widgets have requested an ideal size, the layout of the window is computed and each child widget is notified of its actual size. Usually, this will be at least as large as the requested size, but if for instance the user has resized the window, it may occasionally be smaller than the requested size. The size notification is handled by the function gtk_dial_size_allocate(). Notice that as well as computing the sizes of some component pieces for future use, this routine also does the grunt work of moving the widget's X window into the new position and size.

static void
gtk_dial_size_allocate (GtkWidget     *widget,
            GtkAllocation *allocation)
{
  GtkDial *dial;

  g_return_if_fail (widget != NULL);
  g_return_if_fail (GTK_IS_DIAL (widget));
  g_return_if_fail (allocation != NULL);

  widget->allocation = *allocation;
  if (GTK_WIDGET_REALIZED (widget))
    {
      dial = GTK_DIAL (widget);

      gdk_window_move_resize (widget->window,
                  allocation->x, allocation->y,
                  allocation->width, allocation->height);

      dial->radius = MAX(allocation->width,allocation->height) * 0.45;
      dial->pointer_width = dial->radius / 5;
    }
}

gtk_dial_expose()

As mentioned above, all the drawing of this widget is done in the handler for expose events. There's not much to remark on here except the use of the function gtk_draw_polygon to draw the pointer with three dimensional shading according to the colors stored in the widget's style.

static gboolean
gtk_dial_expose( GtkWidget      *widget,
         GdkEventExpose *event )
{
  GtkDial *dial;
  GdkPoint points[3];
  gdouble s,c;
  gdouble theta;
  gint xc, yc;
  gint tick_length;
  gint i;

  g_return_val_if_fail (widget != NULL, FALSE);
  g_return_val_if_fail (GTK_IS_DIAL (widget), FALSE);
  g_return_val_if_fail (event != NULL, FALSE);

  if (event->count > 0)
    return FALSE;

  dial = GTK_DIAL (widget);

  gdk_window_clear_area (widget->window,
             0, 0,
             widget->allocation.width,
             widget->allocation.height);

  xc = widget->allocation.width/2;
  yc = widget->allocation.height/2;

  /* Draw ticks */

  for (i=0; i<25; i++)
    {
      theta = (i*M_PI/18. - M_PI/6.);
      s = sin(theta);
      c = cos(theta);

      tick_length = (i%6 == 0) ? dial->pointer_width : dial->pointer_width/2;

      gdk_draw_line (widget->window,
             widget->style->fg_gc[widget->state],
             xc + c*(dial->radius - tick_length),
             yc - s*(dial->radius - tick_length),
             xc + c*dial->radius,
             yc - s*dial->radius);
    }

  /* Draw pointer */

  s = sin(dial->angle);
  c = cos(dial->angle);

  points[0].x = xc + s*dial->pointer_width/2;
  points[0].y = yc + c*dial->pointer_width/2;
  points[1].x = xc + c*dial->radius;
  points[1].y = yc - s*dial->radius;
  points[2].x = xc - s*dial->pointer_width/2;
  points[2].y = yc - c*dial->pointer_width/2;

  gtk_draw_polygon (widget->style,
            widget->window,
            GTK_STATE_NORMAL,
            GTK_SHADOW_OUT,
            points, 3,
            TRUE);

  return FALSE;
}

Event handling

The rest of the widget's code handles various types of events, and isn't too different from what would be found in many GTK applications. Two types of events can occur – either the user can click on the widget with the mouse and drag to move the pointer, or the value of the Adjustment object can change due to some external circumstance.

When the user clicks on the widget, we check to see if the click was appropriately near the pointer, and if so, store the button that the user clicked with in the button field of the widget structure, and grab all mouse events with a call to gtk_grab_add(). Subsequent motion of the mouse causes the value of the control to be recomputed (by the function gtk_dial_update_mouse). Depending on the policy that has been set, “value_changed” events are either generated instantly (GTK_UPDATE_CONTINUOUS), after a delay in a timer added with g_timeout_add() (GTK_UPDATE_DELAYED), or only when the button is released (GTK_UPDATE_DISCONTINUOUS).

static gboolean
gtk_dial_button_press( GtkWidget      *widget,
               GdkEventButton *event )
{
  GtkDial *dial;
  gint dx, dy;
  double s, c;
  double d_parallel;
  double d_perpendicular;

  g_return_val_if_fail (widget != NULL, FALSE);
  g_return_val_if_fail (GTK_IS_DIAL (widget), FALSE);
  g_return_val_if_fail (event != NULL, FALSE);

  dial = GTK_DIAL (widget);

  /* Determine if button press was within pointer region - we
     do this by computing the parallel and perpendicular distance of
     the point where the mouse was pressed from the line passing through
     the pointer */

  dx = event->x - widget->allocation.width / 2;
  dy = widget->allocation.height / 2 - event->y;

  s = sin(dial->angle);
  c = cos(dial->angle);

  d_parallel = s*dy + c*dx;
  d_perpendicular = fabs(s*dx - c*dy);

  if (!dial->button &&
      (d_perpendicular < dial->pointer_width/2) &&
      (d_parallel > - dial->pointer_width))
    {
      gtk_grab_add (widget);

      dial->button = event->button;

      gtk_dial_update_mouse (dial, event->x, event->y);
    }

  return FALSE;
}

static gboolean
gtk_dial_button_release( GtkWidget      *widget,
             GdkEventButton *event )
{
  GtkDial *dial;

  g_return_val_if_fail (widget != NULL, FALSE);
  g_return_val_if_fail (GTK_IS_DIAL (widget), FALSE);
  g_return_val_if_fail (event != NULL, FALSE);

  dial = GTK_DIAL (widget);

  if (dial->button == event->button)
    {
      gtk_grab_remove (widget);

      dial->button = 0;

      if (dial->policy == GTK_UPDATE_DELAYED)
    g_source_remove (dial->timer);

      if ((dial->policy != GTK_UPDATE_CONTINUOUS) &&
      (dial->old_value != dial->adjustment->value))
    gtk_signal_emit_by_name (GTK_OBJECT (dial->adjustment), "value_changed");
    }

  return FALSE;
}

static gboolean
gtk_dial_motion_notify( GtkWidget      *widget,
                        GdkEventMotion *event )
{
  GtkDial *dial;
  GdkModifierType mods;
  gint x, y, mask;

  g_return_val_if_fail (widget != NULL, FALSE);
  g_return_val_if_fail (GTK_IS_DIAL (widget), FALSE);
  g_return_val_if_fail (event != NULL, FALSE);

  dial = GTK_DIAL (widget);

  if (dial->button != 0)
    {
      x = event->x;
      y = event->y;

      if (event->is_hint || (event->window != widget->window))
    gdk_window_get_pointer (widget->window, &x, &y, &mods);

      switch (dial->button)
    {
    case 1:
      mask = GDK_BUTTON1_MASK;
      break;
    case 2:
      mask = GDK_BUTTON2_MASK;
      break;
    case 3:
      mask = GDK_BUTTON3_MASK;
      break;
    default:
      mask = 0;
      break;
    }

      if (mods & mask)
    gtk_dial_update_mouse (dial, x,y);
    }

  return FALSE;
}

static gboolean
gtk_dial_timer( GtkDial *dial )
{
  g_return_val_if_fail (dial != NULL, FALSE);
  g_return_val_if_fail (GTK_IS_DIAL (dial), FALSE);

  if (dial->policy == GTK_UPDATE_DELAYED)
    gtk_signal_emit_by_name (GTK_OBJECT (dial->adjustment), "value_changed");

  return FALSE;
}

static void
gtk_dial_update_mouse (GtkDial *dial, gint x, gint y)
{
  gint xc, yc;
  gfloat old_value;

  g_return_if_fail (dial != NULL);
  g_return_if_fail (GTK_IS_DIAL (dial));

  xc = GTK_WIDGET(dial)->allocation.width / 2;
  yc = GTK_WIDGET(dial)->allocation.height / 2;

  old_value = dial->adjustment->value;
  dial->angle = atan2(yc-y, x-xc);

  if (dial->angle < -M_PI/2.)
    dial->angle += 2*M_PI;

  if (dial->angle < -M_PI/6)
    dial->angle = -M_PI/6;

  if (dial->angle > 7.*M_PI/6.)
    dial->angle = 7.*M_PI/6.;

  dial->adjustment->value = dial->adjustment->lower + (7.*M_PI/6 - dial->angle) *
    (dial->adjustment->upper - dial->adjustment->lower) / (4.*M_PI/3.);

  if (dial->adjustment->value != old_value)
    {
      if (dial->policy == GTK_UPDATE_CONTINUOUS)
    {
      gtk_signal_emit_by_name (GTK_OBJECT (dial->adjustment), "value_changed");
    }
      else
    {
      gtk_widget_draw (GTK_WIDGET(dial), NULL);

      if (dial->policy == GTK_UPDATE_DELAYED)
        {
          if (dial->timer)
        g_source_remove (dial->timer);

          dial->timer = g_timeout_add (SCROLL_DELAY_LENGTH,
                           (GtkFunction) gtk_dial_timer,
                       (gpointer) dial);
        }
    }
    }
}

Changes to the Adjustment by external means are communicated to our widget by the “changed” and “value_changed” signals. The handlers for these functions call gtk_dial_update() to validate the arguments, compute the new pointer angle, and redraw the widget (by calling gtk_widget_draw()).

static void
gtk_dial_update (GtkDial *dial)
{
  gfloat new_value;

  g_return_if_fail (dial != NULL);
  g_return_if_fail (GTK_IS_DIAL (dial));

  new_value = dial->adjustment->value;

  if (new_value < dial->adjustment->lower)
    new_value = dial->adjustment->lower;

  if (new_value > dial->adjustment->upper)
    new_value = dial->adjustment->upper;

  if (new_value != dial->adjustment->value)
    {
      dial->adjustment->value = new_value;
      gtk_signal_emit_by_name (GTK_OBJECT (dial->adjustment), "value_changed");
    }

  dial->angle = 7.*M_PI/6. - (new_value - dial->adjustment->lower) * 4.*M_PI/3. /
    (dial->adjustment->upper - dial->adjustment->lower);

  gtk_widget_draw (GTK_WIDGET(dial), NULL);
}

static void
gtk_dial_adjustment_changed (GtkAdjustment *adjustment,
                  gpointer       data)
{
  GtkDial *dial;

  g_return_if_fail (adjustment != NULL);
  g_return_if_fail (data != NULL);

  dial = GTK_DIAL (data);

  if ((dial->old_value != adjustment->value) ||
      (dial->old_lower != adjustment->lower) ||
      (dial->old_upper != adjustment->upper))
    {
      gtk_dial_update (dial);

      dial->old_value = adjustment->value;
      dial->old_lower = adjustment->lower;
      dial->old_upper = adjustment->upper;
    }
}

static void
gtk_dial_adjustment_value_changed (GtkAdjustment *adjustment,
                    gpointer       data)
{
  GtkDial *dial;

  g_return_if_fail (adjustment != NULL);
  g_return_if_fail (data != NULL);

  dial = GTK_DIAL (data);

  if (dial->old_value != adjustment->value)
    {
      gtk_dial_update (dial);

      dial->old_value = adjustment->value;
    }
}

Possible Enhancements

The Dial widget as we've described it so far runs about 670 lines of code. Although that might sound like a fair bit, we've really accomplished quite a bit with that much code, especially since much of that length is headers and boilerplate. However, there are quite a few more enhancements that could be made to this widget:

  • If you try this widget out, you'll find that there is some flashing as the pointer is dragged around. This is because the entire widget is erased every time the pointer is moved before being redrawn. Often, the best way to handle this problem is to draw to an offscreen pixmap, then copy the final results onto the screen in one step. (The ProgressBar widget draws itself in this fashion.)

  • The user should be able to use the up and down arrow keys to increase and decrease the value.

  • It would be nice if the widget had buttons to increase and decrease the value in small or large steps. Although it would be possible to use embedded Button widgets for this, we would also like the buttons to auto-repeat when held down, as the arrows on a scrollbar do. Most of the code to implement this type of behavior can be found in the Range widget.

  • The Dial widget could be made into a container widget with a single child widget positioned at the bottom between the buttons mentioned above. The user could then add their choice of a label or entry widget to display the current value of the dial.

<<< Previous | Home | Next >>>
Creating a Composite widget | Up | Learning More


Learning More

Only a small part of the many details involved in creating widgets could be described above. If you want to write your own widgets, the best source of examples is the GTK source itself. Ask yourself some questions about the widget you want to write: IS it a Container widget? Does it have its own window? Is it a modification of an existing widget? Then find a similar widget, and start making changes. Good luck!

<<< Previous | Home | Next >>>
Creating a widget from scratch | Up | Scribble, A Simple Example Drawing Program


Scribble, A Simple Example Drawing Program

Overview

In this section, we will build a simple drawing program. In the process, we will examine how to handle mouse events, how to draw in a window, and how to do drawing better by using a backing pixmap. After creating the simple drawing program, we will extend it by adding support for XInput devices, such as drawing tablets. GTK provides support routines which makes getting extended information, such as pressure and tilt, from such devices quite easy.

<<< Previous | Home | Next >>>
Learning More |  | Event Handling


Event Handling

The GTK signals we have already discussed are for high-level actions, such as a menu item being selected. However, sometimes it is useful to learn about lower-level occurrences, such as the mouse being moved, or a key being pressed. There are also GTK signals corresponding to these low-level events. The handlers for these signals have an extra parameter which is a pointer to a structure containing information about the event. For instance, motion event handlers are passed a pointer to a GdkEventMotion structure which looks (in part) like:

Type,Bind(C) :: GdkEventMotion
    Integer(GdkEventType) :: type
    Type(C_Ptr) :: window ! Type(GdkWindow),Pointer.
    ...
    Integer(guint32) :: time
    Real(c_double) :: x,y
    ...
    Integer(guint) :: state
    ...
End Type

type will be set to the event type, in this case GDK_MOTION_NOTIFY, window is the window in which the event occurred. x and y give the coordinates of the event. state specifies the modifier state when the event occurred (that is, it specifies which modifier keys and mouse buttons were pressed). It is the bitwise OR (intrinsic function Ior) of some of the following:

GDK_SHIFT_MASK
GDK_LOCK_MASK
GDK_CONTROL_MASK
GDK_MOD1_MASK
GDK_MOD2_MASK
GDK_MOD3_MASK
GDK_MOD4_MASK
GDK_MOD5_MASK
GDK_BUTTON1_MASK
GDK_BUTTON2_MASK
GDK_BUTTON3_MASK
GDK_BUTTON4_MASK
GDK_BUTTON5_MASK

As for other signals, to determine what happens when an event occurs we call gtk_signal_connect(). But we also need let GTK know which events we want to be notified about. To do this, we call the procedure:

Subroutine gtk_widget_set_events(widget,events) Bind(C)
    Type(GtkWidget),Pointer :: widget
    Integer(gint),Intent(In) :: events

The second argument specifies the events we are interested in. It is the bitwise OR of constants that specify different types of events. For future reference the event types are:

GDK_EXPOSURE_MASK
GDK_POINTER_MOTION_MASK
GDK_POINTER_MOTION_HINT_MASK
GDK_BUTTON_MOTION_MASK
GDK_BUTTON1_MOTION_MASK
GDK_BUTTON2_MOTION_MASK
GDK_BUTTON3_MOTION_MASK
GDK_BUTTON_PRESS_MASK
GDK_BUTTON_RELEASE_MASK
GDK_KEY_PRESS_MASK
GDK_KEY_RELEASE_MASK
GDK_ENTER_NOTIFY_MASK
GDK_LEAVE_NOTIFY_MASK
GDK_FOCUS_CHANGE_MASK
GDK_STRUCTURE_MASK
GDK_PROPERTY_CHANGE_MASK
GDK_PROXIMITY_IN_MASK
GDK_PROXIMITY_OUT_MASK

There are a few subtle points that have to be observed when calling gtk_widget_set_events. First, it must be called before the window for a GTK widget is created. In practical terms, this means you should call it immediately after creating the widget. Second, the widget must have an associated window. For efficiency, many widget types do not have their own window, but draw in their parent's window. These widgets are:

GtkAlignment
GtkArrow
GtkBin
GtkBox
GtkImage
GtkItem
GtkLabel
GtkPixmap
GtkScrolledWindow
GtkSeparator
GtkTable
GtkAspectFrame
GtkFrame
GtkVBox
GtkHBox
GtkVSeparator
GtkHSeparator

To capture events for these widgets, you need to use an EventBox widget. See the section on the EventBox widget for details.

For our drawing program, we want to know when the mouse button is pressed and when the mouse is moved, so we specify GDK_POINTER_MOTION_MASK and GDK_BUTTON_PRESS_MASK. We also want to know when we need to redraw our window, so we specify GDK_EXPOSURE_MASK. Although we want to be notified via a Configure event when our window size changes, we don't have to specify the corresponding GDK_STRUCTURE_MASK flag, because it is automatically specified for all windows.

It turns out, however, that there is a problem with just specifying GDK_POINTER_MOTION_MASK. This will cause the server to add a new motion event to the event queue every time the user moves the mouse. Imagine that it takes us 0.1 seconds to handle a motion event, but the server queues a new motion event every 0.05 seconds. We will soon get way behind the users drawing. If the user draws for 5 seconds, it will take us another 5 seconds to catch up after they release the mouse button! What we would like is to only get one motion event for each event we process. The way to do this is to specify GDK_POINTER_MOTION_HINT_MASK.

When we specify GDK_POINTER_MOTION_HINT_MASK, the server sends us a motion event the first time the pointer moves after entering our window, or after a button press or release event. Subsequent motion events will be suppressed until we explicitly ask for the position of the pointer using the function:

Function gdk_window_get_pointer(window,x,y,mask) Result(res)
    Type(GdkWindow),Pointer :: window
    Integer(gint),Intent(Out) :: x,y
    Integer(GdkModifierType),Intent(Out) :: mask
    Type(GdkWindow),Pointer :: res

(There is another function, gtk_widget_get_pointer() which has a simpler interface, but turns out not to be very useful, since it only retrieves the position of the mouse, not whether the buttons are pressed.)

The code to set the events for our window then looks like:

  Integer(gint) :: mask
  :
  Call gtk_signal_connect(GTK_OBJECT(drawing_area),"expose_event", &
                          C_FunLoc(expose_event),C_Null_Ptr)
  Call gtk_signal_connect(GTK_OBJECT(drawing_area),"configure_event", &
                          C_FunLoc(configure_event),C_Null_Ptr)
  Call gtk_signal_connect(GTK_OBJECT(drawing_area),"motion_notify_event", &
                          C_FunLoc(motion_notify_event),C_Null_Ptr)
  Call gtk_signal_connect(GTK_OBJECT(drawing_area),"button_press_event", &
                          C_FunLoc(button_press_event),C_Null_Ptr)

  mask = Ior(Ior(Ior(Ior(GDK_EXPOSURE_MASK,GDK_LEAVE_NOTIFY_MASK), &
                     GDK_BUTTON_PRESS_MASK), &
                 GDK_POINTER_MOTION_MASK, &
             GDK_POINTER_MOTION_HINT_MASK)

  Call gtk_widget_set_events(drawing_area,mask)

We'll save the “expose_event” and “configure_event” handlers for later. The “motion_notify_event” and “button_press_event” handlers are pretty simple:

Integer(gboolean) Function button_press_event(pwidget,pevent) Bind(C)
  Type(C_Ptr),Value :: pwidget,pevent

  Type(GtkWidget),Pointer :: widget
  Type(GdkEventButton),Pointer :: event

  widget => GTK_WIDGET(pwidget)
  Call C_F_Pointer(pevent,event)

  If (event%button==1 .And. Associated(pixmap)) &
    Call draw_brush(widget,event%x,event%y)
  button_press_event = TRUE
End Function

Integer(gboolean) Function motion_notify_event(pwidget,pevent) Bind(C)
  Type(C_Ptr),Value :: pwidget,pevent

  Type(GtkWidget),Pointer :: widget
  Type(GdkWindow),Pointer :: dmy
  Integer :: x,y
  Integer(GdkModifierType) :: state

  widget => GTK_WIDGET(pwidget)
  Call C_F_Pointer(pevent,event)

  If (event%is_hint/=0) Then
    dmy => gdk_window_get_pointer(GDK_WINDOW(event%window),x,y,state)
  Else
    x = event%x
    y = event%y
    state = event%state
  End If

  If (state/=0 .And. GDK_BUTTON1_MASK/=0 .And. Associated(pixmap)) &
    Call draw_brush(widget,Dble(x),Dble(y))

  motion_notify_event = TRUE
End Function

<<< Previous | Home | Next >>>
Scribble, A Simple Example Drawing Program | Up | The DrawingArea Widget, And Drawing


The DrawingArea Widget, And Drawing

We now turn to the process of drawing on the screen. The widget we use for this is the DrawingArea widget. A drawing area widget is essentially a window and nothing more. It is a blank canvas in which we can draw whatever we like. A drawing area is created using the call:

Function gtk_drawing_area_new() Result(res)
    Type(GtkWidget),Pointer :: res

A default size for the widget can be specified by calling:

Subroutine gtk_drawing_area_size(darea,width,height)
  Type(GtkDrawingArea),Pointer :: darea
  Integer(gint),Intent(In) :: width,height

This default size can be overridden, as is true for all widgets, by calling gtk_widget_set_size_request, and that, in turn, can be overridden if the user manually resizes the the window containing the drawing area.

It should be noted that when we create a DrawingArea widget, we are completely responsible for drawing the contents. If our window is obscured then uncovered, we get an exposure event and must redraw what was previously hidden.

Having to remember everything that was drawn on the screen so we can properly redraw it can, to say the least, be a nuisance. In addition, it can be visually distracting if portions of the window are cleared, then redrawn step by step. The solution to this problem is to use an offscreen backing pixmap. Instead of drawing directly to the screen, we draw to an image stored in server memory but not displayed, then when the image changes or new portions of the image are displayed, we copy the relevant portions onto the screen.

To create an offscreen pixmap, we call the function:

Function gdk_pixmap_new(drawable,width,height,depth) Result(res)
    Type(GdkDrawable),Pointer :: drawable
    Integer,Intent(In) :: width,height,depth
    Type(GdkPixmap),Pointer :: res

The window parameter specifies a GDK window that this pixmap takes some of its properties from. width and height specify the size of the pixmap. depth specifies the colour depth, that is the number of bits per pixel, for the new window. If the depth is specified as -1, it will match the depth of window.

We create the pixmap in our “configure_event” handler. This event is generated whenever the window changes size, including when it is originally created.

! Backing pixmap for drawing area.
type(GdkPixmap),pointer::pixmap => null()
...
! Create a new backing pixmap of the appropriate size.
Integer(gboolean) Function configure_event(pwidget,pevent) Bind(C)
  Type(C_Ptr),Value :: pwidget,pevent

  Type(GtkWidget),Pointer :: widget
  Type(GtkStyle),Pointer :: style

  widget => GTK_WIDGET(pwidget)
  If (Associated(pixmap)) Call g_object_unref(C_Loc(pixmap))

  pixmap => gdk_pixmap_new(GDK_DRAWABLE(widget%window), &
                              widget%allocation%width, &
                              widget%allocation%height,-1)
  style => GTK_STYLE(widget%style)
  Call gdk_draw_rectangle(GDK_DRAWABLE(C_Loc(pixmap)), &
                          GDK_GC(style%white_gc),TRUE,0,0, &
                          widget%allocation%width,widget%allocation%height)
  configure_event = TRUE
End Function

The call to gdk_draw_rectangle clears the pixmap initially to white. We'll say more about that in a moment.

Our exposure event handler then simply copies the relevant portion of the pixmap onto the screen (we determine the area we need to redraw by using the event->area field of the exposure event):

! Redraw the screen from the backing pixmap.
Integer(gboolean) Function expose_event(pwidget,pevent) Bind(C)
  Type(C_Ptr),Value :: pwidget,pevent

  Type(GtkWidget),Pointer :: widget
  Type(GdkEventExpose),Pointer :: event
  Type(GtkStyle),Pointer :: style
  Integer :: state

  widget => GTK_WIDGET(pwidget)
  style  => GTK_STYLE(widget%style)
  Call C_F_Pointer(pevent,event)

  state = GTK_WIDGET_STATE(widget)
  Call gdk_draw_drawable(GDK_DRAWABLE(widget%window), &
                         GDK_GC(style%fg_gc(state)), &
                         GDK_DRAWABLE(C_Loc(pixmap)),&
                         event%area%x,event%area%y, &
                         event%area%x,event%area%y, &
                         event%area%width,event%area%height)
  expose_event = FALSE
End Function

We've now seen how to keep the screen up to date with our pixmap, but how do we actually draw interesting stuff on our pixmap? There are a large number of calls in GTK's GDK library for drawing on drawables. A drawable is simply something that can be drawn on. It can be a window, a pixmap, or a bitmap (a black and white image). We've already seen two such calls above, gdk_draw_rectangle and gdk_draw_drawable. The complete list is:

gdk_draw_point ()
gdk_draw_line ()
gdk_draw_rectangle ()
gdk_draw_arc ()
gdk_draw_polygon ()
gdk_draw_pixmap ()
gdk_draw_bitmap ()
gdk_draw_image ()
gdk_draw_points ()
gdk_draw_segments ()
gdk_draw_lines ()
gdk_draw_pixbuf ()
gdk_draw_glyphs ()
gdk_draw_layout_line ()
gdk_draw_layout ()
gdk_draw_layout_line_with_colors ()
gdk_draw_layout_with_colors ()
gdk_draw_glyphs_transformed ()
gdk_draw_glyphs_trapezoids ()

See the reference documentation or the header file <gdk/gdkdrawable.h> for further details on these functions. Fortran versions are available from the GDK module. These functions all share the same first two arguments. The first argument is the drawable to draw upon, the second argument is a graphics context (GC).

A graphics context encapsulates information about things such as foreground and background colour and line width. GDK has a full set of functions for creating and modifying graphics contexts, but to keep things simple we'll just use predefined graphics contexts. Each widget has an associated style. (Which can be modified in a gtkrc file, see the section GTK's rc file.) This, among other things, stores a number of graphics contexts. Some examples of accessing these graphics contexts are:

widget%style%white_gc
widget%style%black_gc
widget%style%fg_gc(GTK_STATE_NORMAL)
widget%style%bg_gc(GTK_WIDGET_STATE(widget))

The fields fg_gc, bg_gc, dark_gc, and light_gc are indexed by a parameter of type GtkStateType which can take on the values:

GTK_STATE_NORMAL,
GTK_STATE_ACTIVE,
GTK_STATE_PRELIGHT,
GTK_STATE_SELECTED,
GTK_STATE_INSENSITIVE

For instance, for GTK_STATE_SELECTED the default foreground colour is white and the default background colour, dark blue.

Our function draw_brush, which does the actual drawing on the screen, is then:

! Draw a rectangle on the screen.
Subroutine draw_brush(widget,x,y)
  Type(GtkWidget),Pointer :: widget
  Double Precision :: x,y

  Type(GdkRectangle) :: update_rect
  Type(GtkStyle),Pointer :: style

  update_rect%x      = x - 5
  update_rect%y      = y - 5
  update_rect%width  = 10
  update_rect%height = 10

  style => GTK_STYLE(widget%style)

  Call gdk_draw_rectangle(GDK_DRAWABLE(C_Loc(pixmap)), &
                          GDK_GC(Style%black_gc),TRUE,update_rect%x, &
                          update_rect%y,update_rect%width,update_rect%height)
  Call gtk_widget_queue_draw_area(widget,update_rect%x,update_rect%y, &
                                  update_rect%width,update_rect%height)
End Subroutine

After we draw the rectangle representing the brush onto the pixmap, we call the procedure:

Subroutine gtk_widget_queue_draw_area(widget,x,y,width,height)
  Type(GtkWidget),Pointer :: widget
  Integer(gint),Intent(In) :: x,y,width,height

which notifies X that the area given by the x, y, width and height parameters needs to be updated. Eventually, an expose event will be generated (possibly combining the areas passed in several calls to gtk_widget_queue_draw_area) which will cause our expose event handler to copy the relevant portions to the screen.

We have now covered the entire drawing program except for a few mundane details like creating the main window.

<<< Previous | Home | Next >>>
Event Handling | Up | Credits


Credits

The authors of the original GTK+ tutorial would like to thank the following for their contributions to that tutorial.

  • Bawer Dagdeviren, chamele0n@geocities.com for the menus tutorial.

  • Raph Levien, raph@acm.org for hello world ala GTK, widget packing, and general all around wisdom. He's also generously donated a home for this tutorial.

  • Peter Mattis, petm@xcf.berkeley.edu for the simplest GTK program.. and the ability to make it :)

  • Werner Koch werner.koch@guug.de for converting the original plain text to SGML, and the widget class hierarchy.

  • Mark Crichton crichton@expert.cc.purdue.edu for the menu factory code, and the table packing tutorial.

  • Owen Taylor owt1@cornell.edu for the EventBox widget section (and the patch to the distro). He's also responsible for the selections code and tutorial, as well as the sections on writing your own GTK widgets, and the example application. Thanks a lot Owen for all you help!

  • Mark VanderBoom mvboom42@calvin.edu for his wonderful work on the Notebook, Progress Bar, Dialogs, and File selection widgets. Thanks a lot Mark! You've been a great help.

  • Tim Janik timj@gtk.org for his great job on the Lists Widget. His excellent work on automatically extracting the widget tree and signal information from GTK. Thanks Tim :)

  • Rajat Datta rajat@ix.netcom.com for the excellent job on the Pixmap tutorial.

  • Michael K. Johnson johnsonm@redhat.com for info and code for popup menus.

  • David Huggins-Daines bn711@freenet.carleton.ca for the Range Widgets and Tree Widget sections.

  • Stefan Mars mars@lysator.liu.se for the CList section.

  • David A. Wheeler dwheeler@ida.org for portions of the text on GLib and various tutorial fixups and improvements. The GLib text was in turn based on material developed by Damon Chaplin DAChaplin@msn.com

  • David King for style checking the entire document.

And to all of you who commented on and helped refine this document.

Thanks.

<<< Previous | Home | Next >>>
The DrawingArea Widget, And Drawing |  | Tutorial Copyright and Permissions Notice


Tutorial Copyright and Permissions Notice

Original GTK Tutorial Copyright Notice

The GTK Tutorial is Copyright (C) 1997 Ian Main.

Copyright (C) 1998-2002 Tony Gale.

Permission is granted to make and distribute verbatim copies of this manual provided the copyright notice and this permission notice are preserved on all copies.

Permission is granted to copy and distribute modified versions of this document under the conditions for verbatim copying, provided that this copyright notice is included exactly as in the original, and that the entire resulting derived work is distributed under the terms of a permission notice identical to this one.

Permission is granted to copy and distribute translations of this document into another language, under the above conditions for modified versions.

If you are intending to incorporate this document into a published work, please contact the maintainer, and we will make an effort to ensure that you have the most up to date information available.

There is no guarantee that this document lives up to its intended purpose. This is simply provided as a free resource. As such, the authors and maintainers of the information provided within can not make any guarantee that the information is even accurate.

Fortran GTK Tutorial Copyright Notice

The modifications to the GTK+ Tutorial for Fortran support are

© Copyright 2010 The Numerical Algorithms Group Ltd., Oxford, U.K.

<<< Previous | Home | Next >>>
Credits |  | GTK Signals


GTK Signals

As GTK is an object oriented widget set, it has a hierarchy of inheritance. This inheritance mechanism applies for signals. Therefore, you should refer to the widget hierarchy tree when using the signals listed in this section.

GtkObject

Subroutine destroy(pobject,data) Bind(C)
    Type(C_Ptr),Value :: pobject,data
    Type(GtkObject),Pointer :: object
    Call C_F_Pointer(pobject,object)

<<< Previous | Home | Next >>>
Tutorial Copyright and Permissions Notice |  | GtkWidget


GtkWidget

In the interfaces below, the name of each subroutine is the same as that of the signal, except that any hyphens in the signal name have been replaced by underscores in the subroutine name.

The local Fortran pointer declarations (e.g. for widget) and calls to C_F_Pointer are strictly speaking not part of the interface, but illustrate how to turn the C pointer into the right type of Fortran pointer.

Subroutine accel_closures_changed(pwidget,data) Bind(C)
    Type(C_Ptr),Value :: pwidget,data
    Type(GtkWidget),Pointer :: widget
    Call C_F_Pointer(pwidget,widget)

Integer(gboolean) Function button_press_event(pwidget,pevent,data) Bind(C)
    Type(C_Ptr),Value :: pwidget,pevent,data
    Type(GtkWidget),Pointer :: widget
    Type(GdkEventButton),Pointer :: event
    Call C_F_Pointer(pwidget,widget)
    Call C_F_Pointer(pevent,event)

Integer(gboolean) Function button_release_event(pwidget,pevent,data) Bind(C)
    Type(C_Ptr),Value :: pwidget,pevent,data
    Type(GtkWidget),Pointer :: widget
    Type(GdkEventButton),Pointer :: event
    Call C_F_Pointer(pwidget,widget)
    Call C_F_Pointer(pevent,event)

Integer(gboolean) Function can_activate_accel(pwidget,signal_id,data) Bind(C)
    Type(C_Ptr),Value :: pwidget,data
    Integer(guint),Value :: signal_id
    Type(GtkWidget),Pointer :: widget
    Call C_F_Pointer(pwidget,widget)

Subroutine child_notify(pwidget,ppspec,data) Bind(C)
    Type(C_Ptr),Value :: pwidget,ppspec,data
    Type(GtkWidget),Pointer :: widget
    Type(GParamSpec),Pointer :: pspec
    Call C_F_Pointer(pwidget,widget)
    Call C_F_Pointer(ppspec,pspec)

Integer(gboolean) Function client_event(pwidget,pevent,data) Bind(C)
    Type(C_Ptr),Value :: pwidget,pevent,data
    Type(GtkWidget),Pointer :: widget
    Type(GdkEventClient),Pointer :: event
    Call C_F_Pointer(pwidget,widget)
    Call C_F_Pointer(pevent,event)

Subroutine composited_changed(pwidget,data) Bind(C)
    Type(C_Ptr),Value :: pwidget,data
    Type(GtkWidget),Pointer :: widget
    Call C_F_Pointer(pwidget,widget)

Integer(gboolean) Function configure_event(pwidget,pevent,data) Bind(C)
    Type(C_Ptr),Value :: pwidget,pevent,data
    Type(GtkWidget),Pointer :: widget
    Type(GdkEventConfigure),Pointer :: event
    Call C_F_Pointer(pwidget,widget)
    Call C_F_Pointer(pevent,event)

Integer(gboolean) Function delete_event(pwidget,pevent,data) Bind(C)
    Type(C_Ptr),Value :: pwidget,pevent,data
    Type(GtkWidget),Pointer :: widget
    Type(GdkEvent),Pointer :: event
    Call C_F_Pointer(pwidget,widget)
    Call C_F_Pointer(pevent,event)

Integer(gboolean) Function destroy_event(pwidget,pevent,data) Bind(C)
    Type(C_Ptr),Value :: pwidget,pevent,data
    Type(GtkWidget),Pointer :: widget
    Type(GdkEvent),Pointer :: event
    Call C_F_Pointer(pwidget,widget)
    Call C_F_Pointer(pevent,event)

Subroutine direction_changed(pwidget,arg1,data) Bind(C)
    Type(C_Ptr),Value :: pwidget,data
    Integer(GtkTextDirection),Value :: arg1
    Type(GtkWidget),Pointer :: widget
    Call C_F_Pointer(pwidget,widget)

Subroutine drag_begin(pwidget,pcontext,data) Bind(C)
    Type(C_Ptr),Value :: pwidget,pcontext,data
    Type(GtkWidget),Pointer :: widget
    Type(GdkDragContext),Pointer :: context
    Call C_F_Pointer(pwidget,widget)
    Call C_F_Pointer(context,pcontext)

Subroutine drag_data_delete(pwidget,pcontext,data) Bind(C)
    Type(C_Ptr),Value :: pwidget,pcontext,data
    Type(GtkWidget),Pointer :: widget
    Type(GdkDragContext),Pointer :: context
    Call C_F_Pointer(pwidget,widget)
    Call C_F_Pointer(context,pcontext)

Subroutine drag_data_get(pwidget,pcontext,psel_data,info,time,data) Bind(C)
    Type(C_Ptr),Value :: pwidget,pcontext,psel_data,data
    Integer(guint),Value :: info,time
    Type(GtkWidget),Pointer :: widget
    Type(GtkSelectionData),Pointer :: sel_data
    Call C_F_Pointer(pwidget,widget)
    Call C_F_Pointer(sel_data,psel_data)

Subroutine drag_data_received(pwidget,pcontext,x,y,psel_data,info,time,data) Bind(C)
    Type(C_Ptr),Value :: pwidget,pcontext,psel_data,data
    Integer(guint),Value :: x,y,info,time
    Type(GtkWidget),Pointer :: widget
    Type(GtkSelectionData),Pointer :: sel_data
    Call C_F_Pointer(pwidget,widget)
    Call C_F_Pointer(sel_data,psel_data)

Integer(gboolean) Function drag_drop(pwidget,pcontext,x,y,time,data) Bind(C)
    Type(C_Ptr),Value :: pwidget,pcontext,data
    Integer(guint),Value :: x,y,time
    Type(GtkWidget),Pointer :: widget
    Type(GdkDragContext),Pointer :: context
    Call C_F_Pointer(pwidget,widget)
    Call C_F_Pointer(context,pcontext)

Subroutine drag_end(pwidget,pcontext,data) Bind(C)
    Type(C_Ptr),Value :: pwidget,pcontext,data
    Type(GtkWidget),Pointer :: widget
    Type(GdkDragContext),Pointer :: context
    Call C_F_Pointer(pwidget,widget)
    Call C_F_Pointer(context,pcontext)

Subroutine drag_leave(pwidget,pcontext,time,data) Bind(C)
    Type(C_Ptr),Value :: pwidget,pcontext,data
    Integer(guint),Value :: time
    Type(GtkWidget),Pointer :: widget
    Type(GdkDragContext),Pointer :: context
    Call C_F_Pointer(pwidget,widget)
    Call C_F_Pointer(context,pcontext)

Integer(gboolean) Function drag_motion(pwidget,pcontext,x,y,time,data) Bind(C)
    Type(C_Ptr),Value :: pwidget,pcontext,data
    Integer(guint),Value :: x,y,time
    Type(GtkWidget),Pointer :: widget
    Type(GdkDragContext),Pointer :: context
    Call C_F_Pointer(pwidget,widget)
    Call C_F_Pointer(context,pcontext)

Integer(gboolean) Function enter_notify_event(pwidget,pevent,data) Bind(C)
    Type(C_Ptr),Value :: pwidget,pevent,data
    Type(GtkWidget),Pointer :: widget
    Type(GdkEventCrossing),Pointer :: event
    Call C_F_Pointer(pwidget,widget)
    Call C_F_Pointer(pevent,event)

Integer(gboolean) Function event(pwidget,pevent,data) Bind(C)
    Type(C_Ptr),Value :: pwidget,pevent,data
    Type(GtkWidget),Pointer :: widget
    Type(GdkEvent),Pointer :: eventp
    Call C_F_Pointer(pwidget,widget)
    Call C_F_Pointer(pevent,eventp)

Subroutine event_after(pwidget,pevent,data) Bind(C)
    Type(C_Ptr),Value :: pwidget,pevent,data
    Type(GtkWidget),Pointer :: widget
    Type(GdkEvent),Pointer :: event
    Call C_F_Pointer(pwidget,widget)
    Call C_F_Pointer(pevent,event)

Integer(gboolean) Function expose_event(pwidget,pevent,data) Bind(C)
    Type(C_Ptr),Value :: pwidget,pevent,data
    Type(GtkWidget),Pointer :: widget
    Type(GdkEventExpose),Pointer :: event
    Call C_F_Pointer(pwidget,widget)
    Call C_F_Pointer(pevent,event)

Subroutine focus(pwidget,arg1,data) Bind(C)
    Type(C_Ptr),Value :: pwidget,data
    Integer(GtkDirectionType),Value :: arg1
    Type(GtkWidget),Pointer :: widget
    Call C_F_Pointer(pwidget,widget)

Integer(gboolean) Function focus_in_event(pwidget,pevent,data) Bind(C)
    Type(C_Ptr),Value :: pwidget,pevent,data
    Type(GtkWidget),Pointer :: widget
    Type(GdkEventFocus),Pointer :: event
    Call C_F_Pointer(pwidget,widget)
    Call C_F_Pointer(pevent,event)

Integer(gboolean) Function focus_out_event(pwidget,pevent,data) Bind(C)
    Type(C_Ptr),Value :: pwidget,pevent,data
    Type(GtkWidget),Pointer :: widget
    Type(GdkEventFocus),Pointer :: event
    Call C_F_Pointer(pwidget,widget)
    Call C_F_Pointer(pevent,event)

Integer Function grab_broken_event(pwidget,pevent,data) Bind(C)
    Type(C_Ptr),Value :: pwidget,pevent,data
    Type(GtkWidget),Pointer :: widget
    Type(GdkEventGrabBroken),Pointer :: event
    Call C_F_Pointer(pwidget,widget)
    Call C_F_Pointer(pevent,event)

Subroutine grab_focus(pwidget,data) Bind(C)
    Type(C_Ptr),Value :: pwidget,data
    Type(GtkWidget),Pointer :: widget
    Call C_F_Pointer(pwidget,widget)

Subroutine grab_notify(pwidget,was_grabbed,data) Bind(C)
    Type(C_Ptr),Value :: pwidget,data
    Integer(gboolean),Value :: was_grabbed
    Type(GtkWidget),Pointer :: widget
    Call C_F_Pointer(pwidget,widget)

Subroutine hide(pwidget,data) Bind(C)
    Type(C_Ptr),Value :: pwidget,data
    Type(GtkWidget),Pointer :: widget
    Call C_F_Pointer(pwidget,widget)

Subroutine hierarchy_changed(pwidget,pwidget2,data) Bind(C)
    Type(C_Ptr),Value :: pwidget,pwidget2,data
    Type(GtkWidget),Pointer :: widget,widget2
    Call C_F_Pointer(pwidget,widget)
    Call C_F_Pointer(pwidget2,widget2)

Integer(gboolean) Function key_press_event(pwidget,pevent,data) Bind(C)
    Type(C_Ptr),Value :: pwidget,pevent,data
    Type(GtkWidget),Pointer :: widget
    Type(GdkEventKey),Pointer :: event
    Call C_F_Pointer(pwidget,widget)
    Call C_F_Pointer(pevent,event)

Integer(gboolean) Function key_release_event(pwidget,pevent,data) Bind(C)
    Type(C_Ptr),Value :: pwidget,pevent,data
    Type(GtkWidget),Pointer :: widget
    Type(GdkEventKey),Pointer :: event
    Call C_F_Pointer(pwidget,widget)
    Call C_F_Pointer(pevent,event)

Integer(gboolean) Function leave_notify_event(pwidget,pevent,data) Bind(C)
    Type(C_Ptr),Value :: pwidget,pevent,data
    Type(GtkWidget),Pointer :: widget
    Type(GdkEventCrossing),Pointer :: event
    Call C_F_Pointer(pwidget,widget)
    Call C_F_Pointer(pevent,event)

Subroutine map(pwidget,data) Bind(C)
    Type(C_Ptr),Value :: pwidget,data
    Type(GtkWidget),Pointer :: widget
    Call C_F_Pointer(pwidget,widget)

Integer(gboolean) Function map_event(pwidget,pevent,data) Bind(C)
    Type(C_Ptr),Value :: pwidget,pevent,data
    Type(GtkWidget),Pointer :: widget
    Type(GdkEvent),Pointer :: event
    Call C_F_Pointer(pwidget,widget)
    Call C_F_Pointer(pevent,event)

Integer(gboolean) Function mnemonic_activate(pwidget,arg1,data) Bind(C)
    Type(C_Ptr),Value :: pwidget,data
    Integer(gboolean),Value :: arg1
    Type(GtkWidget),Pointer :: widget
    Call C_F_Pointer(pwidget,widget)

Integer(gboolean) Function motion_notify_event(pwidget,pevent,data) Bind(C)
    Type(C_Ptr),Value :: pwidget,pevent,data
    Type(GtkWidget),Pointer :: widget
    Type(GdkEventMotion),Pointer :: event
    Call C_F_Pointer(pwidget,widget)
    Call C_F_Pointer(pevent,event)

Integer(gboolean) Function no_expose_event(pwidget,pevent,data) Bind(C)
    Type(C_Ptr),Value :: pwidget,pevent,data
    Type(GtkWidget),Pointer :: widget
    Type(GdkEventMotion),Pointer :: event
    Call C_F_Pointer(pwidget,widget)
    Call C_F_Pointer(pevent,event)

Subroutine parent_set(pwidget,pobject,data) Bind(C)
    Type(C_Ptr),Value :: pwidget,pobject,data
    Type(GtkWidget),Pointer :: widget
    Type(GtkObject),Pointer :: object
    Call C_F_Pointer(pwidget,widget)
    Call C_F_Pointer(pobject,object)

Integer(gboolean) Function popup_menu(pwidget,data) Bind(C)
    Type(C_Ptr),Value :: pwidget,data
    Type(GtkWidget),Pointer :: widget
    Call C_F_Pointer(pwidget,widget)

Integer(gboolean) Function property_notify_event(pwidget,pevent,data) Bind(C)
    Type(C_Ptr),Value :: pwidget,pevent,data
    Type(GtkWidget),Pointer :: widget
    Type(GdkEventProperty),Pointer :: event
    Call C_F_Pointer(pwidget,widget)
    Call C_F_Pointer(pevent,event)

Integer(gboolean) Function proximity_in_event(pwidget,pevent,data) Bind(C)
    Type(C_Ptr),Value :: pwidget,pevent,data
    Type(GtkWidget),Pointer :: widget
    Type(GdkEventProximity),Pointer :: event
    Call C_F_Pointer(pwidget,widget)
    Call C_F_Pointer(pevent,event)

Integer(gboolean) Function proximity_out_event(pwidget,pevent,data) Bind(C)
    Type(C_Ptr),Value :: pwidget,pevent,data
    Type(GtkWidget),Pointer :: widget
    Type(GdkEventProximity),Pointer :: event
    Call C_F_Pointer(pwidget,widget)
    Call C_F_Pointer(pevent,event)

Subroutine realize(pwidget,data) Bind(C)
    Type(C_Ptr),Value :: pwidget,data
    Type(GtkWidget),Pointer :: widget
    Call C_F_Pointer(pwidget,widget)

Subroutine screen_changed(pwidget,parg1,data) Bind(C)
    Type(C_Ptr),Value :: pwidget,parg1,data
    Type(GtkWidget),Pointer :: widget
    Type(GdkScreen),Pointer :: arg1
    Call C_F_Pointer(pwidget,widget)
    Call C_F_Pointer(parg1,arg1)

Integer(gboolean) Function scroll_event(pwidget,pevent,data) Bind(C)
    Type(C_Ptr),Value :: pwidget,pevent,data
    Type(GtkWidget),Pointer :: widget
    Type(GdkEventScroll),Pointer :: event
    Call C_F_Pointer(pwidget,widget)
    Call C_F_Pointer(pevent,event)

Integer(gboolean) Function selection_clear_event(pwidget,pevent,data) Bind(C)
    Type(C_Ptr),Value :: pwidget,pevent,data
    Type(GtkWidget),Pointer :: widget
    Type(GdkEventSelection),Pointer :: event
    Call C_F_Pointer(pwidget,widget)
    Call C_F_Pointer(pevent,event)

Subroutine selection_get(pwidget,psel_data,pevent,info,time,data) Bind(C)
    Type(C_Ptr),Value :: pwidget,psel_data,pevent,data
    Integer(guint),Value :: info,time
    Type(GtkWidget),Pointer :: widget
    Type(GtkSelectionData),Pointer :: sel_data
    Call C_F_Pointer(pwidget,widget)
    Call C_F_Pointer(psel_data,sel_data)

Integer(gboolean) Function selection_notify_event(pwidget,pevent,data) Bind(C)
    Type(C_Ptr),Value :: pwidget,pevent,data
    Type(GtkWidget),Pointer :: widget
    Type(GdkEventSelection),Pointer :: event
    Call C_F_Pointer(pwidget,widget)
    Call C_F_Pointer(pevent,event)

Subroutine selection_received(pwidget,psel_data,time,data) Bind(C)
    Type(C_Ptr),Value :: pwidget,psel_data,data
    Integer(guint),Value :: time
    Type(GtkWidget),Pointer :: widget
    Type(GtkSelectionData),Pointer :: sel_data
    Call C_F_Pointer(pwidget,widget)
    Call C_F_Pointer(psel_data,sel_data)

Integer(gboolean) Function selection_request_event(pwidget,pevent,data) Bind(C)
    Type(C_Ptr),Value :: pwidget,pevent,data
    Type(GtkWidget),Pointer :: widget
    Type(GdkEventSelection),Pointer :: event
    Call C_F_Pointer(pwidget,widget)
    Call C_F_Pointer(pevent,event)

Subroutine show(pwidget,data) Bind(C)
    Type(C_Ptr),Value :: pwidget,data
    Type(GtkWidget),Pointer :: widget
    Call C_F_Pointer(pwidget,widget)

Integer Function show_help(pwidget,arg1,data) Bind(C)
    Type(C_Ptr),Value :: pwidget,data
    Integer(GtkWidgetHelpType),Value :: arg1
    Type(GtkWidget),Pointer :: widget
    Call C_F_Pointer(pwidget,widget)

Subroutine size_allocate(pwidget,pallocation,data) Bind(C)
    Type(C_Ptr),Value :: pwidget,pallocation,data
    Type(GtkWidget),Pointer :: widget
    Type(GtkRequisition),Pointer :: allocation
    Call C_F_Pointer(pwidget,widget)
    Call C_F_Pointer(pallocation,allocation)

Subroutine size_request(pwidget,prequisition,data) Bind(C)
    Type(C_Ptr),Value :: pwidget,prequisition,data
    Type(GtkWidget),Pointer :: widget
    Type(GtkRequisition),Pointer :: requisition
    Call C_F_Pointer(pwidget,widget)
    Call C_F_Pointer(prequisition,requisition)

Subroutine state_changed(pwidget,state_type,data) Bind(C)
    Type(C_Ptr),Value :: pwidget,data
    Integer(GtkStateType),Value :: state_type
    Type(GtkWidget),Pointer :: widget
    Call C_F_Pointer(pwidget,widget)

Subroutine style_set(pwidget,pprevious_style,data) Bind(C)
    Type(C_Ptr),Value :: pwidget,pprevious_style,data
    Type(GtkWidget),Pointer :: widget
    Type(GtkStyle),Pointer :: previous_style
    Call C_F_Pointer(pwidget,widget)
    Call C_F_Pointer(pprevious_style,previous_style)

Subroutine unmap(pwidget,data) Bind(C)
    Type(C_Ptr),Value :: pwidget,data
    Type(GtkWidget),Pointer :: widget
    Call C_F_Pointer(pwidget,widget)

Integer(gboolean) Function unmap_event(pwidget,pevent,data) Bind(C)
    Type(C_Ptr),Value :: pwidget,pevent,data
    Type(GtkWidget),Pointer :: widget
    Type(GdkEvent),Pointer :: event
    Call C_F_Pointer(pwidget,widget)
    Call C_F_Pointer(pevent,event)

Subroutine unrealize(pwidget,data) Bind(C)
    Type(C_Ptr),Value :: pwidget,data
    Type(GtkWidget),Pointer :: widget
    Call C_F_Pointer(pwidget,widget)

Integer(gboolean) Function visibility_notify_event(pwidget,pevent,data) Bind(C)
    Type(C_Ptr),Value :: pwidget,pevent,data
    Type(GtkWidget),Pointer :: widget
    Type(GdkEventVisibility),Pointer :: event
    Call C_F_Pointer(pwidget,widget)
    Call C_F_Pointer(pevent,event)

Integer(gboolean) Function window_state_event(pwidget,pevent,data) Bind(C)
    Type(C_Ptr),Value :: pwidget,pevent,data
    Type(GtkWidget),Pointer :: widget
    Type(GdkWindowEventState),Pointer :: event
    Call C_F_Pointer(pwidget,widget)
    Call C_F_Pointer(pevent,event)
Additionally, the following interfaces are listed in the GTK+ tutorial as signals, but do not appear in the GTK 2.0 documentation.
Subroutine draw(pwidget,data) Bind(C)
    Type(C_Ptr),Value :: pwidget,data
    Type(GtkWidget),Pointer :: widget
    Call C_F_Pointer(pwidget,widget)

Subroutine draw_default(pwidget,data) Bind(C)
    Type(C_Ptr),Value :: pwidget,data
    Type(GtkWidget),Pointer :: widget
    Call C_F_Pointer(pwidget,widget)

Subroutine draw_focus(pwidget,data) Bind(C)
    Type(C_Ptr),Value :: pwidget,data
    Type(GtkWidget),Pointer :: widget
    Call C_F_Pointer(pwidget,widget)

Subroutine add_accelerator(pwidget,accel_signal_id,paccel_group,accel_key, &
                           accel_mods,accel_flags,data) Bind(C)
    Type(C_Ptr),Value :: pwidget,paccel_group,data
    Integer(guint),Value :: accel_signal_id,accel_key
    Integer(GdkModifierType),Value :: accel_mods
    Integer(GtkAccelFlags),Value :: accel_flags
    Type(GtkWidget),Pointer :: widget
    Type(GtkAccelGroup),Pointer :: accel_group
    Call C_F_Pointer(pwidget,widget)
    Call C_F_Pointer(paccel_group,accel_group)

Subroutine remove_accelerator(pwidget,paccel_group,accel_key,accel_mods,data) &
Bind(C)
    Type(C_Ptr),Value :: pwidget,paccel_group,data
    Integer(guint),Value :: accel_key
    Integer(GdkModifierType),Value :: accel_mods
    Type(GtkWidget),Pointer :: widget
    Type(GtkAccelGroup),Pointer :: accel_group
    Call C_F_Pointer(pwidget,widget)
    Call C_F_Pointer(paccel_group,accel_group)

<<< Previous | Home | Next >>>
GTK Signals | Up | GtkContainer


GtkContainer

In the interfaces below, the name of each subroutine is the same as that of the signal, except that any hyphens in the signal name have been replaced by underscores in the subroutine name.

The local Fortran pointer declarations (e.g. for widget) and calls to C_F_Pointer are strictly speaking not part of the interface, but illustrate how to turn the C pointer into the right type of Fortran pointer.

Subroutine add(pcontainer,pwidget,data) Bind(C)
    Type(C_Ptr),Value :: pcontainer,pwidget,data
    Type(GtkContainer),Pointer :: container
    Type(GtkWidget),Pointer :: widget
    Call C_F_Pointer(pcontainer,container)
    Call C_F_Pointer(pwidget,widget)

Subroutine remove(pcontainer,pwidget,data) Bind(C)
    Type(C_Ptr),Value :: pcontainer,pwidget,data
    Type(GtkContainer),Pointer :: container
    Type(GtkWidget),Pointer :: widget
    Call C_F_Pointer(pcontainer,container)
    Call C_F_Pointer(pwidget,widget)

Subroutine check_resize(pcontainer,data) Bind(C)
    Type(C_Ptr),Value :: pcontainer,data
    Type(GtkContainer),Pointer :: container
    Call C_F_Pointer(pcontainer,container)

Subroutine remove(pcontainer,data) Bind(C)
    Type(C_Ptr),Value :: pcontainer,data
    Type(GtkContainer),Pointer :: container
    Call C_F_Pointer(pcontainer,container)

Subroutine set_focus_child(pcontainer,pwidget,data) Bind(C)
    Type(C_Ptr),Value :: pcontainer,pwidget,data
    Type(GtkContainer),Pointer :: container
    Type(GtkWidget),Pointer :: widget
    Call C_F_Pointer(pcontainer,container)
    Call C_F_Pointer(pwidget,widget)

<<< Previous | Home | Next >>>
GtkWidget | Up | GtkCalendar


GtkCalendar

Subroutine day_selected(pcalendar,pdata) Bind(C)
    Type(C_Ptr),Value :: pcalendar,pdata
    Type(GtkCalendar),Pointer :: calendar
    Call C_F_Pointer(pcalendar,calendar)

Subroutine day_selected_double_click(pcalendar,pdata) Bind(C)
    Type(C_Ptr),Value :: pcalendar,pdata
    Type(GtkCalendar),Pointer :: calendar
    Call C_F_Pointer(pcalendar,calendar)

Subroutine month_changed(pcalendar,pdata) Bind(C)
    Type(C_Ptr),Value :: pcalendar,pdata
    Type(GtkCalendar),Pointer :: calendar
    Call C_F_Pointer(pcalendar,calendar)

Subroutine next_month(pcalendar,pdata) Bind(C)
    Type(C_Ptr),Value :: pcalendar,pdata
    Type(GtkCalendar),Pointer :: calendar
    Call C_F_Pointer(pcalendar,calendar)

Subroutine next_year(pcalendar,pdata) Bind(C)
    Type(C_Ptr),Value :: pcalendar,pdata
    Type(GtkCalendar),Pointer :: calendar
    Call C_F_Pointer(pcalendar,calendar)

Subroutine prev_month(pcalendar,pdata) Bind(C)
    Type(C_Ptr),Value :: pcalendar,pdata
    Type(GtkCalendar),Pointer :: calendar
    Call C_F_Pointer(pcalendar,calendar)

Subroutine prev_year(pcalendar,pdata) Bind(C)
    Type(C_Ptr),Value :: pcalendar,pdata
    Type(GtkCalendar),Pointer :: calendar
    Call C_F_Pointer(pcalendar,calendar)

<<< Previous | Home | Next >>>
GtkContainer | Up | GtkEditable


GtkEditable

In the interfaces below, the name of each subroutine is the same as that of the signal, except that any hyphens in the signal name have been replaced by underscores in the subroutine name.

The local Fortran pointer declarations (e.g. for widget) and calls to C_F_Pointer are strictly speaking not part of the interface, but illustrate how to turn the C pointer into the right type of Fortran pointer.

Subroutine changed(pedit,data) Bind(C)
    Type(C_Ptr),Value :: pedit,data
    Type(GtkEditable),Pointer :: edit
    Call C_F_Pointer(pedit,edit)

Subroutine delete_text(pedit,start_pos,end_pos,data) Bind(C)
    Type(C_Ptr),Value :: pedit,data
    Integer(gint),Value :: start_pos,end_pos
    Type(GtkEditable),Pointer :: edit
    Call C_F_Pointer(pedit,edit)

Subroutine insert_text(pedit,new_text,new_text_length,position,data) Bind(C)
    Type(C_Ptr),Value :: pedit,data
    Character :: new_text(*) ! Either length-counted or null-terminated.
    Integer,Value :: new_text_length
    Integer(gint),Intent(InOut) :: position
    Type(GtkEditable),Pointer :: edit
    Call C_F_Pointer(pedit,edit)

The remaining signal interfaces are not in GtkEditable, but in GtkOldEditable; they appear here only because the tutorial still thinks that they are in GtkEditable. GtkOldEditable (and thus presumably these interfaces) have been officially deprecated and should not be used.

Subroutine activate(pedit,data) Bind(C)
    Type(C_Ptr),Value :: pedit,data
    Type(GtkEditable),Pointer :: edit
    Call C_F_Pointer(pedit,edit)

Subroutine copy_clipboard(pedit,data) Bind(C)
    Type(C_Ptr),Value :: pedit,data
    Type(GtkEditable),Pointer :: edit
    Call C_F_Pointer(pedit,edit)

Subroutine cut_clipboard(pedit,data) Bind(C)
    Type(C_Ptr),Value :: pedit,data
    Type(GtkEditable),Pointer :: edit
    Call C_F_Pointer(pedit,edit)

Subroutine kill_char(pedit,direction,data) Bind(C)
    Type(C_Ptr),Value :: pedit,data
    Integer(gint),Value :: direction,
    Type(GtkEditable),Pointer :: edit
    Call C_F_Pointer(pedit,edit)

Subroutine kill_line(pedit,direction,data) Bind(C)
    Type(C_Ptr),Value :: pedit,data
    Integer(gint),Value :: direction,
    Type(GtkEditable),Pointer :: edit
    Call C_F_Pointer(pedit,edit)

Subroutine kill_word(pedit,direction,data) Bind(C)
    Type(C_Ptr),Value :: pedit,data
    Integer(gint),Value :: direction,
    Type(GtkEditable),Pointer :: edit
    Call C_F_Pointer(pedit,edit)

Subroutine move_cursor(pedit,x,y,data) Bind(C)
    Type(C_Ptr),Value :: pedit,data
    Integer(gint),Value :: x,y
    Type(GtkEditable),Pointer :: edit
    Call C_F_Pointer(pedit,edit)

Subroutine move_page(pedit,x,y,data) Bind(C)
    Type(C_Ptr),Value :: pedit,data
    Integer(gint),Value :: x,y
    Type(GtkEditable),Pointer :: edit
    Call C_F_Pointer(pedit,edit)

Subroutine move_to_column(pedit,column,data) Bind(C)
    Type(C_Ptr),Value :: pedit,data
    Integer(gint),Value :: column
    Type(GtkEditable),Pointer :: edit
    Call C_F_Pointer(pedit,edit)

Subroutine move_to_row(pedit,row,data) Bind(C)
    Type(C_Ptr),Value :: pedit,data
    Integer(gint),Value :: row
    Type(GtkEditable),Pointer :: edit
    Call C_F_Pointer(pedit,edit)

Subroutine move_word(pedit,num_words,data) Bind(C)
    Type(C_Ptr),Value :: pedit,data
    Integer(gint),Value :: num_words
    Type(GtkEditable),Pointer :: edit
    Call C_F_Pointer(pedit,edit)

Subroutine paste_clipboard(pedit,data) Bind(C)
    Type(C_Ptr),Value :: pedit,data
    Type(GtkEditable),Pointer :: edit
    Call C_F_Pointer(pedit,edit)

Subroutine set_editable(pedit,is_editable,data) Bind(C)
    Type(C_Ptr),Value :: pedit,data
    Integer(gboolean),Value :: is_editable
    Type(GtkEditable),Pointer :: edit
    Call C_F_Pointer(pedit,edit)

<<< Previous | Home | Next >>>
GtkCalendar | Up | GtkNotebook


GtkNotebook

In the interfaces below, the name of each subroutine is the same as that of the signal, except that any hyphens in the signal name have been replaced by underscores in the subroutine name.

The local Fortran pointer declarations (e.g. for widget) and calls to C_F_Pointer are strictly speaking not part of the interface, but illustrate how to turn the C pointer into the right type of Fortran pointer.

Integer(gboolean) Function change_current_page(pnotebook,arg1,data) Bind(C)
    Type(C_Ptr),Value :: pnotebook,data
    Integer(gint),Value :: arg1
    Type(GtkNotebook),Pointer :: notebook
    Call C_F_Pointer(pnotebook,notebook)

Subroutine switch_page(pnotebook,ppage,page_num,data) Bind(C)
    Type(C_Ptr),Value :: pnotebook,ppage,data
    Integer(gint),Value :: page_num
    Type(GtkNotebook),Pointer :: notebook
    Type(GtkNotebookPage),Pointer :: page
    Call C_F_Pointer(pnotebook,notebook)
    Call C_F_Pointer(ppage,page)

<<< Previous | Home | Next >>>
GtkEditable | Up | GtkList


GtkList

Subroutine select_child(plist,pwidget,data) Bind(C)
    Type(C_Ptr),Value :: plist,pwidget,data
    Type(GtkList),Pointer :: list
    Type(GtkWidget),Pointer :: widget
    Call C_F_Pointer(plist,list)
    Call C_F_Pointer(pwidget,widget)

Subroutine selection_changed(plist,data) Bind(C)
    Type(C_Ptr),Value :: plist,data
    Type(GtkList),Pointer :: list
    Call C_F_Pointer(plist,list)

Subroutine unselect_child(plist,pwidget,data) Bind(C)
    Type(C_Ptr),Value :: plist,pwidget,data
    Type(GtkList),Pointer :: list
    Type(GtkWidget),Pointer :: widget
    Call C_F_Pointer(plist,list)
    Call C_F_Pointer(pwidget,widget)

<<< Previous | Home | Next >>>
GtkNotebook | Up | GtkMenuShell


GtkMenuShell

Subroutine activate_current(pmenushell,force_hide,data) Bind(C)
    Type(C_Ptr),Value :: pmenushell,data
    Integer(gboolean),Value :: force_hide
    Type(GtkMenuShell),Pointer :: menushell
    Call C_F_Pointer(pmenushell,menushell)

Subroutine cancel(pmenushell,data) Bind(C)
    Type(C_Ptr),Value :: pmenushell,data
    Type(GtkMenuShell),Pointer :: menushell
    Call C_F_Pointer(pmenushell,menushell)

Subroutine cycle_focus(pmenushell,arg1,data) Bind(C)
    Type(C_Ptr),Value :: pmenushell,data
    Integer(GtkDirectionType),Value :: arg1
    Type(GtkMenuShell),Pointer :: menushell
    Call C_F_Pointer(pmenushell,menushell)

Subroutine deactivate(pmenushell,data) Bind(C)
    Type(C_Ptr),Value :: pmenushell,data
    Type(GtkMenuShell),Pointer :: menushell
    Call C_F_Pointer(pmenushell,menushell)

Subroutine move_current(pmenushell,direction,data) Bind(C)
    Type(C_Ptr),Value :: pmenushell,data
    Integer(GtkMenuDirectionType),Value :: direction
    Type(GtkMenuShell),Pointer :: menushell
    Call C_F_Pointer(pmenushell,menushell)

Subroutine selection_done(pmenushell,data) Bind(C)
    Type(C_Ptr),Value :: pmenushell,data
    Type(GtkMenuShell),Pointer :: menushell
    Call C_F_Pointer(pmenushell,menushell)

<<< Previous | Home | Next >>>
GtkList | Up | GtkToolbar


GtkToolbar

Subroutine orientation_changed(ptool_bar,orientation,data) Bind(C)
    Type(C_Ptr),Value :: ptool_bar,data
    Integer(GtkOrientation),Value :: orientation
    Type(GtkToolbar),Pointer :: tool_bar
    Call C_F_Pointer(ptool_bar,tool_bar)

Subroutine style_changed(ptool_bar,style,data) Bind(C)
    Type(C_Ptr),Value :: ptool_bar,data
    Integer(GtkToolbarStyle),Value :: style
    Type(GtkToolbar),Pointer :: tool_bar
    Call C_F_Pointer(ptool_bar,tool_bar)
Note that this is not a complete list of signals for this widget.
<<< Previous | Home | Next >>>
GtkMenuShell | Up | GtkButton


GtkButton

Subroutine clicked(pbutton,data) Bind(C)
    Type(C_Ptr),Value :: pbutton,data
    Type(GtkButton),Pointer :: button
    Call C_F_Pointer(pbutton,button)

Subroutine enter(pbutton,data) Bind(C)
    Type(C_Ptr),Value :: pbutton,data
    Type(GtkButton),Pointer :: button
    Call C_F_Pointer(pbutton,button)

Subroutine leave(pbutton,data) Bind(C)
    Type(C_Ptr),Value :: pbutton,data
    Type(GtkButton),Pointer :: button
    Call C_F_Pointer(pbutton,button)

Subroutine pressed(pbutton,data) Bind(C)
    Type(C_Ptr),Value :: pbutton,data
    Type(GtkButton),Pointer :: button
    Call C_F_Pointer(pbutton,button)

Subroutine released(pbutton,data) Bind(C)
    Type(C_Ptr),Value :: pbutton,data
    Type(GtkButton),Pointer :: button
    Call C_F_Pointer(pbutton,button)
Note that these are all deprecated except for “clicked”, the corresponding GtkWidget signals (e.g. GtkWidget::enter-notify-event) should be used instead.
<<< Previous | Home | Next >>>
GtkToolbar | Up | GtkItem


GtkItem

Subroutine select(pitem,data) Bind(C)
    Type(C_Ptr),Value :: pitem,data
    Type(GtkButton),Pointer :: item
    Call C_F_Pointer(pitem,item)

Subroutine deselect(pitem,data) Bind(C)
    Type(C_Ptr),Value :: pitem,data
    Type(GtkButton),Pointer :: item
    Call C_F_Pointer(pitem,item)

Subroutine toggle(pitem,data) Bind(C)
    Type(C_Ptr),Value :: pitem,data
    Type(GtkButton),Pointer :: item
    Call C_F_Pointer(pitem,item)

<<< Previous | Home | Next >>>
GtkButton | Up | GtkWindow


GtkWindow

Subroutine set_focus(pwin,pwidget,data) Bind(C)
    Type(C_Ptr),Value :: pwin,pwidget,data
    Type(GtkWindow),Pointer :: win
    Type(GtkWidget),Pointer :: widget
    Call C_F_Pointer(pwin,win)
    Call C_F_Pointer(pwidget,widget)
Note: There are several other signals that are not documented here.
<<< Previous | Home | Next >>>
GtkItem | Up | GtkHandleBox


GtkHandleBox

Subroutine child_attached(phbox,pwidget,data) bind(c)
    Type(C_Ptr),Value :: phbox,pwidget,data
    Type(GtkHandleBox),Pointer :: hbox
    Type(GtkWidget),Pointer :: widget
    Call C_F_Pointer(phbox,hbox)
    Call C_F_Pointer(pwidget,widget)

Subroutine child_detached(phbox,pwidget,data) Bind(C)
    Type(C_Ptr),Value :: phbox,pwidget,data
    Type(GtkHandleBox),Pointer :: hbox
    Type(GtkWidget),Pointer :: widget
    Call C_F_Pointer(phbox,hbox)
    Call C_F_Pointer(pwidget,widget)

<<< Previous | Home | Next >>>
GtkWindow | Up | GtkToggleButton


GtkToggleButton

Subroutine toggled(ptoggle_button,data) Bind(C)
    Type(C_Ptr),Value :: ptoggle_button,data
    Type(GtkToggleButton),Pointer :: toggle_button
    Call C_F_Pointer(ptoggle_button,toggle_button)

<<< Previous | Home | Next >>>
GtkHandleBox | Up | GtkMenuItem


GtkMenuItem

Subroutine activate(pmenu_item,data) Bind(C)
    Type(C_Ptr),Value :: pmenu_item,data
    Type(GtkMenuItem),Pointer :: menu_item
    Call C_F_Pointer(pmenu_item,menu_item)

Subroutine activate_item(pmenu_item,data) Bind(C)
    Type(C_Ptr),Value :: pmenu_item,data
    Type(GtkMenuItem),Pointer :: menu_item
    Call C_F_Pointer(pmenu_item,menu_item)
Note: This is not a complete list of signals for this widget.
<<< Previous | Home | Next >>>
GtkToggleButton | Up | GtkCheckMenuItem


GtkCheckMenuItem

Subroutine toggled(pmenu_item,data) Bind(C)
    Type(C_Ptr),Value :: pmenu_item,data
    Type(GtkCheckMenuItem),Pointer :: menu_item
    Call C_F_Pointer(pmenu_item,menu_item)

<<< Previous | Home | Next >>>
GtkMenuItem | Up | GtkInputDialog


GtkInputDialog

Subroutine disable_device(pdialogue,pdevice,data) Bind(C)
    Type(C_Ptr),Value :: pdialogue,pdevice,data
    Type(GtkInputDialog),Pointer :: dialogue
    Type(GdkDevice),Pointer :: device
    Call C_F_Pointer(pdialogue,dialogue)
    Call C_F_Pointer(pdevice,device)

Subroutine enable_device(pdialogue,pdevice,data) Bind(C)
    Type(C_Ptr),Value :: pdialogue,pdevice,data
    Type(GtkInputDialog),Pointer :: dialogue
    Type(GdkDevice),Pointer :: device
    Call C_F_Pointer(pdialog,dialogue)
    Call C_F_Pointer(pdevice,device)

<<< Previous | Home | Next >>>
GtkCheckMenuItem | Up | GtkColorSelection


GtkColorSelection

Subroutine color_changed(pcolor_selection,data) Bind(C)
    Type(C_Ptr),Value :: pcolor_selection,data
    Type(GtkColorSelection),Pointer :: color_selection
    Call C_F_Pointer(pcolor_selection,color_selection)

<<< Previous | Home | Next >>>
GtkInputDialog | Up | GtkStatusBar


GtkStatusBar

Subroutine text_popped(pstatusbar,context_id,text,data) Bind(C)
    Type(C_Ptr),Value :: pstatusbar,data
    Integer(guint),Value :: context_id
    Character :: text(*) ! Null-terminated.
    Type(GtkStatusbar),Pointer :: statusbar
    Call C_F_Pointer(pstatusbar,statusbar)

Subroutine text_pushed(pstatusbar,context_id,text,data) Bind(C)
    Type(C_Ptr),Value :: pstatusbar,data
    Integer(guint),Value :: context_id
    Character :: text(*) ! Null-terminated.
    Type(GtkStatusbar),Pointer :: statusbar
    Call C_F_Pointer(pstatusbar,statusbar)

<<< Previous | Home | Next >>>
GtkColorSelection | Up | GtkCurve


GtkCurve

Subroutine curve_type_changed(pcurve,data) Bind(C)
    Type(C_Ptr),Value :: pcurve,data
    Type(GtkCurve),Pointer :: curve
    Call C_F_Pointer(pcurve,curve)

<<< Previous | Home | Next >>>
GtkStatusBar | Up | GtkAdjustment


GtkAdjustment

Subroutine changed(padjustment,data) Bind(C)
    Type(C_Ptr),Value :: padjustment,data
    Type(GtkAdjustment),Pointer :: adjustment
    Call C_F_Pointer(padjustment,adjustment)

Subroutine value_changed(padjustment,data) Bind(C)
    Type(C_Ptr),Value :: padjustment,data
    Type(GtkAdjustment),Pointer :: adjustment
    Call C_F_Pointer(padjustment,adjustment)

<<< Previous | Home | Next >>>
GtkCurve | Up | GDK Event Types


GDK Event Types

The following data types are passed into event handlers by GTK+. For each data type listed, the signals that use this data type are listed.

  • GdkEvent

    • drag_end_event

  • GdkEventType

  • GdkEventAny

    • delete_event

    • destroy_event

    • map_event

    • unmap_event

    • no_expose_event

  • GdkEventExpose

    • expose_event

  • GdkEventNoExpose

  • GdkEventVisibility

  • GdkEventMotion

    • motion_notify_event

  • GdkEventButton

    • button_press_event

    • button_release_event

  • GdkEventKey

    • key_press_event

    • key_release_event

  • GdkEventCrossing

    • enter_notify_event

    • leave_notify_event

  • GdkEventFocus

    • focus_in_event

    • focus_out_event

  • GdkEventConfigure

    • configure_event

  • GdkEventProperty

    • property_notify_event

  • GdkEventSelection

    • selection_clear_event

    • selection_request_event

    • selection_notify_event

  • GdkEventProximity

    • proximity_in_event

    • proximity_out_event

  • GdkEventDragBegin

    • drag_begin_event

  • GdkEventDragRequest

    • drag_request_event

  • GdkEventDropEnter

    • drop_enter_event

  • GdkEventDropLeave

    • drop_leave_event

  • GdkEventDropDataAvailable

    • drop_data_available_event

  • GdkEventClient

    • client_event

  • GdkEventOther

    • other_event

The data type GdkEventType is a special data type that is used by all the other data types as an indicator of the data type being passed to the signal handler. As you will see below, each of the event data structures has a member of this type. It is defined as an enumeration type as follows:

Enum,Bind(C)
    Enumerator :: GDK_NOTHING           = -1
    Enumerator :: GDK_DELETE            = 0
    Enumerator :: GDK_DESTROY           = 1
    Enumerator :: GDK_EXPOSE            = 2
    Enumerator :: GDK_MOTION_NOTIFY     = 3
    Enumerator :: GDK_BUTTON_PRESS      = 4
    Enumerator :: GDK_2BUTTON_PRESS     = 5
    Enumerator :: GDK_3BUTTON_PRESS     = 6
    Enumerator :: GDK_BUTTON_RELEASE    = 7
    Enumerator :: GDK_KEY_PRESS         = 8
    Enumerator :: GDK_KEY_RELEASE       = 9
    Enumerator :: GDK_ENTER_NOTIFY      = 10
    Enumerator :: GDK_LEAVE_NOTIFY      = 11
    Enumerator :: GDK_FOCUS_CHANGE      = 12
    Enumerator :: GDK_CONFIGURE         = 13
    Enumerator :: GDK_MAP               = 14
    Enumerator :: GDK_UNMAP             = 15
    Enumerator :: GDK_PROPERTY_NOTIFY   = 16
    Enumerator :: GDK_SELECTION_CLEAR   = 17
    Enumerator :: GDK_SELECTION_REQUEST = 18
    Enumerator :: GDK_SELECTION_NOTIFY  = 19
    Enumerator :: GDK_PROXIMITY_IN      = 20
    Enumerator :: GDK_PROXIMITY_OUT     = 21
    Enumerator :: GDK_DRAG_ENTER        = 22
    Enumerator :: GDK_DRAG_LEAVE        = 23
    Enumerator :: GDK_DRAG_MOTION_      = 24
    Enumerator :: GDK_DRAG_STATUS_      = 25
    Enumerator :: GDK_DROP_START        = 26
    Enumerator :: GDK_DROP_FINISHED     = 27
    Enumerator :: GDK_CLIENT_EVENT      = 28
    Enumerator :: GDK_VISIBILITY_NOTIFY = 29
    Enumerator :: GDK_NO_EXPOSE         = 30
    Enumerator :: GDK_SCROLL            = 31
    Enumerator :: GDK_WINDOW_STATE      = 32
    Enumerator :: GDK_SETTING           = 33
    Enumerator :: GDK_OWNER_CHANGE      = 34
    Enumerator :: GDK_GRAB_BROKEN       = 35
End Enum

The other event type that is different from the others is GdkEvent itself. This is a union of all the other data types, which allows it to be cast to a specific event data type within a signal handler.

So, the event data types are defined as follows:

Type,Bind(C) :: GdkEventAny
    Integer(GdkEventType) :: type
    Type(C_Ptr)           :: window ! Type(GdkWindow),Pointer.
    Integer(gint8)        :: send_event
End Type

Type,Bind(C) :: GdkEventExpose
    Integer(GdkEventType) :: type
    Type(C_Ptr)           :: window ! Type(GdkWindow),Pointer.
    Integer(gint8)        :: send_event
    Type(GdkRectangle)    :: area
    Type(C_Ptr)           :: region ! Type(GdkRegion),Pointer.
    Integer               :: count ! If non-zero, how many more events follow.
End Type

Type,Bind(C) :: GdkEventNoExpose
    Integer(GdkEventType) :: type
    Type(C_Ptr) :: window ! Type(GdkWindow),Pointer.
    Integer(gint8) :: send_event
End Type

Type,Bind(C) :: GdkEventVisibility
    Integer(GdkEventType) :: type
    Type(C_Ptr) :: window
    Integer(gint8) :: send_event
    Integer(GdkVisibilityState)::state
End Type

Type,Bind(C) :: GdkEventMotion
    Integer(GdkEventType) :: type
    Type(C_Ptr) :: window
    Integer(gint8) :: send_event
    Integer(guint32) :: time
    Real(gdouble) :: x,y
    Type(C_Ptr) :: axes ! Real(gdouble),Dimension(:),Pointer.
    Integer :: state
    Integer(gint16) :: is_hint
    Type(C_Ptr) :: device ! Type(GdkDevice),Pointer.
    Real(gdouble) :: x_root,y_root
End Type

Type,Bind(C) :: GdkEventButton
    Integer(GdkEventType) :: type
    Type(C_Ptr) :: window
    Integer(gint8) :: send_event
    Integer(guint32) :: time
    Real(gdouble) :: x,y
    Type(C_Ptr) :: axes
    Integer(guint) :: state
    Integer(guint) :: button
    Type(C_Ptr) :: device
    Real(gdouble) :: x_root,y_root
End Type

Type,Bind(C) :: GdkEventKey
    Integer(GdkEventType) :: type
    Type(C_Ptr) :: window
    Integer(gint8) :: send_event
    Integer(guint32) :: time
    Integer(guint) :: state
    Integer(guint) :: keyval
    Integer(gint) :: length
    Type(C_Ptr) :: string
    Integer(guint16) :: hardware_keycode
    Integer(guint8) :: group
    Integer(guint),Private :: is_modifier_flags
End Type

Type,Bind(C) :: GdkEventCrossing
    Integer(GdkEventType) :: type
    Type(C_Ptr) :: window
    Integer(gint8) :: send_event
    Type(C_Ptr) :: subwindow
    Integer(c_int) :: time
    Real(gdouble) :: x,y,x_root,y_root
    Integer(GdkCrossingMode) :: mode
    Integer(GdkNotifyType) :: detail
    Integer(gboolean) :: focus
    Integer(guint) :: state
End Type

Type,Bind(C) :: GdkEventFocus
    Integer(GdkEventType) :: type
    Type(C_Ptr) :: window
    Integer(gint8) :: send_event
    Integer(gint16) :: in
End Type

Type,Bind(C) :: GdkEventConfigure
    Integer(GdkEventType) :: type
    Type(C_Ptr) :: window
    Integer(gint8) :: send_event
    Integer(gint) :: x, y
    Integer(gint) :: width
    Integer(gint) :: height
End Type

Type,Bind(C) :: GdkEventProperty
    Integer(GdkEventType) :: type
    Type(C_Ptr) :: window
    Integer(gint8) :: send_event
    Integer(GdkAtom) :: atom
    Integer(guint32) :: time
    Integer(guint) :: state
End Type

Type,Bind(C) :: GdkEventSelection
    Integer(GdkEventType) :: type
    Type(C_Ptr) :: window
    Integer(gint8) :: send_event
    Integer(GdkAtom) :: selection
    Integer(GdkAtom) :: target
    Integer(GdkAtom) :: property
    Integer(guint32) :: time
    Integer(GdkNativeWindow) :: requestor
End Type

! This event type will be used pretty rarely. It only is important
! for XInput aware programs that are drawing their own cursor

Type,Bind(C) :: GdkEventProximity
    Integer(GdkEventType) :: type
    Type(C_Ptr) :: window
    Integer(gint8) :: send_event
    Integer(guint32) :: time
    Type(C_Ptr) :: device
End Type

Type,Bind(C) :: GdkEventClient
    Integer(GdkEventType) :: type
    Type(C_Ptr) :: window
    Integer(gint8) :: send_event
    Integer(GdkAtom) :: message_type
    Type(C_Ptr) :: data_format
    Integer(glong) :: data(0:4)
end type

<<< Previous | Home | Next >>>
GtkAdjustment |  | Code Examples


Code Examples

Below are the code examples that are used in the above text which are not included in complete form elsewhere.

<<< Previous | Home | Next >>>
GDK Event Types |  | GtkDial


GtkDial

gtkdial.h

/* GTK - The GIMP Toolkit
 * Copyright (C) 1995-1997 Peter Mattis, Spencer Kimball and Josh MacDonald
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Library General Public
 * License as published by the Free Software Foundation; either
 * version 2 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Library General Public License for more details.
 *
 * You should have received a copy of the GNU Library General Public
 * License along with this library; if not, write to the
 * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
 * Boston, MA 02111-1307, USA.
 */
#ifndef __GTK_DIAL_H__
#define __GTK_DIAL_H__

#include <gdk/gdk.h>
#include <gtk/gtkadjustment.h>
#include <gtk/gtkwidget.h>

#ifdef __cplusplus
extern "C" {
#endif /* __cplusplus */

#define GTK_DIAL(obj)          GTK_CHECK_CAST (obj, gtk_dial_get_type (), GtkDial)
#define GTK_DIAL_CLASS(klass)  GTK_CHECK_CLASS_CAST (klass, gtk_dial_get_type (), GtkDialClass)
#define GTK_IS_DIAL(obj)       GTK_CHECK_TYPE (obj, gtk_dial_get_type ())

typedef struct _GtkDial        GtkDial;
typedef struct _GtkDialClass   GtkDialClass;

struct _GtkDial
{
  GtkWidget widget;

  /* update policy (GTK_UPDATE_[CONTINUOUS/DELAYED/DISCONTINUOUS]) */
  guint policy : 2;

  /* Button currently pressed or 0 if none */
  guint8 button;

  /* Dimensions of dial components */
  gint radius;
  gint pointer_width;

  /* ID of update timer, or 0 if none */
  guint32 timer;

  /* Current angle */
  gfloat angle;
  gfloat last_angle;

  /* Old values from adjustment stored so we know when something changes */
  gfloat old_value;
  gfloat old_lower;
  gfloat old_upper;

  /* The adjustment object that stores the data for this dial */
  GtkAdjustment *adjustment;
};

struct _GtkDialClass
{
  GtkWidgetClass parent_class;
};

GtkWidget*     gtk_dial_new                    (GtkAdjustment *adjustment);
GtkType        gtk_dial_get_type               (void);
GtkAdjustment* gtk_dial_get_adjustment         (GtkDial      *dial);
void           gtk_dial_set_update_policy      (GtkDial      *dial,
                        GtkUpdateType  policy);

void           gtk_dial_set_adjustment         (GtkDial      *dial,
                        GtkAdjustment *adjustment);
#ifdef __cplusplus
}
#endif /* __cplusplus */

#endif /* __GTK_DIAL_H__ */

gtkdial.c

/* GTK - The GIMP Toolkit
 * Copyright (C) 1995-1997 Peter Mattis, Spencer Kimball and Josh MacDonald
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Library General Public
 * License as published by the Free Software Foundation; either
 * version 2 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Library General Public License for more details.
 *
 * You should have received a copy of the GNU Library General Public
 * License along with this library; if not, write to the
 * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
 * Boston, MA 02111-1307, USA.
 */
#include <math.h>
#include <stdio.h>
#include <gtk/gtkmain.h>
#include <gtk/gtksignal.h>

#include "gtkdial.h"

#define SCROLL_DELAY_LENGTH  300
#define DIAL_DEFAULT_SIZE 100

/* Forward declarations */

static void gtk_dial_class_init               (GtkDialClass     *klass);
static void gtk_dial_init                     (GtkDial          *dial);
static void gtk_dial_destroy                  (GtkObject        *object);
static void gtk_dial_realize                  (GtkWidget        *widget);
static void gtk_dial_size_request             (GtkWidget        *widget,
                                               GtkRequisition   *requisition);
static void gtk_dial_size_allocate            (GtkWidget        *widget,
                                               GtkAllocation    *allocation);
static gboolean gtk_dial_expose               (GtkWidget        *widget,
                                               GdkEventExpose   *event);
static gboolean gtk_dial_button_press         (GtkWidget        *widget,
                                               GdkEventButton   *event);
static gboolean gtk_dial_button_release       (GtkWidget        *widget,
                                               GdkEventButton   *event);
static gboolean gtk_dial_motion_notify        (GtkWidget        *widget,
                                               GdkEventMotion   *event);
static gboolean gtk_dial_timer                (GtkDial          *dial);

static void gtk_dial_update_mouse             (GtkDial *dial, gint x, gint y);
static void gtk_dial_update                   (GtkDial *dial);
static void gtk_dial_adjustment_changed       (GtkAdjustment    *adjustment,
                        gpointer          data);
static void gtk_dial_adjustment_value_changed (GtkAdjustment    *adjustment,
                        gpointer          data);

/* Local data */

static GtkWidgetClass *parent_class = NULL;

GType
gtk_dial_get_type ()
{
  static GType dial_type = 0;

  if (!dial_type)
    {
      static const GTypeInfo dial_info =
      {
    sizeof (GtkDialClass),
    NULL,
    NULL,
    (GClassInitFunc) gtk_dial_class_init,
    NULL,
    NULL,
    sizeof (GtkDial),
        0,
    (GInstanceInitFunc) gtk_dial_init,
      };

      dial_type = g_type_register_static (GTK_TYPE_WIDGET, "GtkDial", &dial_info, 0);
    }

  return dial_type;
}

static void
gtk_dial_class_init (GtkDialClass *class)
{
  GtkObjectClass *object_class;
  GtkWidgetClass *widget_class;

  object_class = (GtkObjectClass*) class;
  widget_class = (GtkWidgetClass*) class;

  parent_class = gtk_type_class (gtk_widget_get_type ());

  object_class->destroy = gtk_dial_destroy;

  widget_class->realize = gtk_dial_realize;
  widget_class->expose_event = gtk_dial_expose;
  widget_class->size_request = gtk_dial_size_request;
  widget_class->size_allocate = gtk_dial_size_allocate;
  widget_class->button_press_event = gtk_dial_button_press;
  widget_class->button_release_event = gtk_dial_button_release;
  widget_class->motion_notify_event = gtk_dial_motion_notify;
}

static void
gtk_dial_init (GtkDial *dial)
{
  dial->button = 0;
  dial->policy = GTK_UPDATE_CONTINUOUS;
  dial->timer = 0;
  dial->radius = 0;
  dial->pointer_width = 0;
  dial->angle = 0.0;
  dial->old_value = 0.0;
  dial->old_lower = 0.0;
  dial->old_upper = 0.0;
  dial->adjustment = NULL;
}

GtkWidget*
gtk_dial_new (GtkAdjustment *adjustment)
{
  GtkDial *dial;

  dial = g_object_new (gtk_dial_get_type (), NULL);

  if (!adjustment)
    adjustment = (GtkAdjustment*) gtk_adjustment_new (0.0, 0.0, 0.0, 0.0, 0.0, 0.0);

  gtk_dial_set_adjustment (dial, adjustment);

  return GTK_WIDGET (dial);
}

static void
gtk_dial_destroy (GtkObject *object)
{
  GtkDial *dial;

  g_return_if_fail (object != NULL);
  g_return_if_fail (GTK_IS_DIAL (object));

  dial = GTK_DIAL (object);

  if (dial->adjustment)
    {
      g_object_unref (GTK_OBJECT (dial->adjustment));
      dial->adjustment = NULL;
    }

  if (GTK_OBJECT_CLASS (parent_class)->destroy)
    (* GTK_OBJECT_CLASS (parent_class)->destroy) (object);
}

GtkAdjustment*
gtk_dial_get_adjustment (GtkDial *dial)
{
  g_return_val_if_fail (dial != NULL, NULL);
  g_return_val_if_fail (GTK_IS_DIAL (dial), NULL);

  return dial->adjustment;
}

void
gtk_dial_set_update_policy (GtkDial      *dial,
                 GtkUpdateType  policy)
{
  g_return_if_fail (dial != NULL);
  g_return_if_fail (GTK_IS_DIAL (dial));

  dial->policy = policy;
}

void
gtk_dial_set_adjustment (GtkDial      *dial,
              GtkAdjustment *adjustment)
{
  g_return_if_fail (dial != NULL);
  g_return_if_fail (GTK_IS_DIAL (dial));

  if (dial->adjustment)
    {
      g_signal_handlers_disconnect_by_func (GTK_OBJECT (dial->adjustment), NULL, (gpointer) dial);
      g_object_unref (GTK_OBJECT (dial->adjustment));
    }

  dial->adjustment = adjustment;
  g_object_ref (GTK_OBJECT (dial->adjustment));

  g_signal_connect (GTK_OBJECT (adjustment), "changed",
            GTK_SIGNAL_FUNC (gtk_dial_adjustment_changed),
            (gpointer) dial);
  g_signal_connect (GTK_OBJECT (adjustment), "value_changed",
            GTK_SIGNAL_FUNC (gtk_dial_adjustment_value_changed),
            (gpointer) dial);

  dial->old_value = adjustment->value;
  dial->old_lower = adjustment->lower;
  dial->old_upper = adjustment->upper;

  gtk_dial_update (dial);
}

static void
gtk_dial_realize (GtkWidget *widget)
{
  GtkDial *dial;
  GdkWindowAttr attributes;
  gint attributes_mask;

  g_return_if_fail (widget != NULL);
  g_return_if_fail (GTK_IS_DIAL (widget));

  GTK_WIDGET_SET_FLAGS (widget, GTK_REALIZED);
  dial = GTK_DIAL (widget);

  attributes.x = widget->allocation.x;
  attributes.y = widget->allocation.y;
  attributes.width = widget->allocation.width;
  attributes.height = widget->allocation.height;
  attributes.wclass = GDK_INPUT_OUTPUT;
  attributes.window_type = GDK_WINDOW_CHILD;
  attributes.event_mask = gtk_widget_get_events (widget) |
    GDK_EXPOSURE_MASK | GDK_BUTTON_PRESS_MASK |
    GDK_BUTTON_RELEASE_MASK | GDK_POINTER_MOTION_MASK |
    GDK_POINTER_MOTION_HINT_MASK;
  attributes.visual = gtk_widget_get_visual (widget);
  attributes.colormap = gtk_widget_get_colormap (widget);

  attributes_mask = GDK_WA_X | GDK_WA_Y | GDK_WA_VISUAL | GDK_WA_COLORMAP;
  widget->window = gdk_window_new (widget->parent->window, &attributes, attributes_mask);

  widget->style = gtk_style_attach (widget->style, widget->window);

  gdk_window_set_user_data (widget->window, widget);

  gtk_style_set_background (widget->style, widget->window, GTK_STATE_ACTIVE);
}

static void
gtk_dial_size_request (GtkWidget      *widget,
               GtkRequisition *requisition)
{
  requisition->width = DIAL_DEFAULT_SIZE;
  requisition->height = DIAL_DEFAULT_SIZE;
}

static void
gtk_dial_size_allocate (GtkWidget     *widget,
            GtkAllocation *allocation)
{
  GtkDial *dial;

  g_return_if_fail (widget != NULL);
  g_return_if_fail (GTK_IS_DIAL (widget));
  g_return_if_fail (allocation != NULL);

  widget->allocation = *allocation;
  dial = GTK_DIAL (widget);

  if (GTK_WIDGET_REALIZED (widget))
    {

      gdk_window_move_resize (widget->window,
                  allocation->x, allocation->y,
                  allocation->width, allocation->height);

    }
  dial->radius = MIN (allocation->width, allocation->height) * 0.45;
  dial->pointer_width = dial->radius / 5;
}

static gboolean
gtk_dial_expose( GtkWidget      *widget,
         GdkEventExpose *event )
{
  GtkDial *dial;
  GdkPoint points[6];
  gdouble s,c;
  gdouble theta, last, increment;
  GtkStyle      *blankstyle;
  gint xc, yc;
  gint upper, lower;
  gint tick_length;
  gint i, inc;

  g_return_val_if_fail (widget != NULL, FALSE);
  g_return_val_if_fail (GTK_IS_DIAL (widget), FALSE);
  g_return_val_if_fail (event != NULL, FALSE);

  if (event->count > 0)
    return FALSE;

  dial = GTK_DIAL (widget);

/*  gdk_window_clear_area (widget->window,
             0, 0,
             widget->allocation.width,
             widget->allocation.height);
*/
  xc = widget->allocation.width / 2;
  yc = widget->allocation.height / 2;

  upper = dial->adjustment->upper;
  lower = dial->adjustment->lower;

  /* Erase old pointer */

  s = sin (dial->last_angle);
  c = cos (dial->last_angle);
  dial->last_angle = dial->angle;

  points[0].x = xc + s*dial->pointer_width/2;
  points[0].y = yc + c*dial->pointer_width/2;
  points[1].x = xc + c*dial->radius;
  points[1].y = yc - s*dial->radius;
  points[2].x = xc - s*dial->pointer_width/2;
  points[2].y = yc - c*dial->pointer_width/2;
  points[3].x = xc - c*dial->radius/10;
  points[3].y = yc + s*dial->radius/10;
  points[4].x = points[0].x;
  points[4].y = points[0].y;

  blankstyle = gtk_style_new ();
  blankstyle->bg_gc[GTK_STATE_NORMAL] =
                widget->style->bg_gc[GTK_STATE_NORMAL];
  blankstyle->dark_gc[GTK_STATE_NORMAL] =
                widget->style->bg_gc[GTK_STATE_NORMAL];
  blankstyle->light_gc[GTK_STATE_NORMAL] =
                widget->style->bg_gc[GTK_STATE_NORMAL];
  blankstyle->black_gc =
                widget->style->bg_gc[GTK_STATE_NORMAL];

  gtk_paint_polygon (blankstyle,
                    widget->window,
                    GTK_STATE_NORMAL,
                    GTK_SHADOW_OUT,
                NULL,
                    widget,
                    NULL,
                    points, 5,
                    FALSE);

  g_object_unref (blankstyle);

  /* Draw ticks */

  if ((upper - lower) == 0)
    return FALSE;

  increment = (100*M_PI) / (dial->radius*dial->radius);

  inc = (upper - lower);

  while (inc < 100) inc *= 10;
  while (inc >= 1000) inc /= 10;
  last = -1;

  for (i = 0; i <= inc; i++)
    {
      theta = ((gfloat)i*M_PI / (18*inc/24.) - M_PI/6.);

      if ((theta - last) < (increment))
    continue;
      last = theta;

      s = sin (theta);
      c = cos (theta);

      tick_length = (i%(inc/10) == 0) ? dial->pointer_width : dial->pointer_width / 2;

      gdk_draw_line (widget->window,
                     widget->style->fg_gc[widget->state],
                     xc + c*(dial->radius - tick_length),
                     yc - s*(dial->radius - tick_length),
                     xc + c*dial->radius,
                     yc - s*dial->radius);
    }

  /* Draw pointer */

  s = sin (dial->angle);
  c = cos (dial->angle);
  dial->last_angle = dial->angle;

  points[0].x = xc + s*dial->pointer_width/2;
  points[0].y = yc + c*dial->pointer_width/2;
  points[1].x = xc + c*dial->radius;
  points[1].y = yc - s*dial->radius;
  points[2].x = xc - s*dial->pointer_width/2;
  points[2].y = yc - c*dial->pointer_width/2;
  points[3].x = xc - c*dial->radius/10;
  points[3].y = yc + s*dial->radius/10;
  points[4].x = points[0].x;
  points[4].y = points[0].y;

  gtk_paint_polygon (widget->style,
            widget->window,
            GTK_STATE_NORMAL,
            GTK_SHADOW_OUT,
                NULL,
                    widget,
                    NULL,
            points, 5,
            TRUE);

  return FALSE;
}

static gboolean
gtk_dial_button_press( GtkWidget      *widget,
               GdkEventButton *event )
{
  GtkDial *dial;
  gint dx, dy;
  double s, c;
  double d_parallel;
  double d_perpendicular;

  g_return_val_if_fail (widget != NULL, FALSE);
  g_return_val_if_fail (GTK_IS_DIAL (widget), FALSE);
  g_return_val_if_fail (event != NULL, FALSE);

  dial = GTK_DIAL (widget);

  /* Determine if button press was within pointer region - we
     do this by computing the parallel and perpendicular distance of
     the point where the mouse was pressed from the line passing through
     the pointer */

  dx = event->x - widget->allocation.width / 2;
  dy = widget->allocation.height / 2 - event->y;

  s = sin (dial->angle);
  c = cos (dial->angle);

  d_parallel = s*dy + c*dx;
  d_perpendicular = fabs (s*dx - c*dy);

  if (!dial->button &&
      (d_perpendicular < dial->pointer_width/2) &&
      (d_parallel > - dial->pointer_width))
    {
      gtk_grab_add (widget);

      dial->button = event->button;

      gtk_dial_update_mouse (dial, event->x, event->y);
    }

  return FALSE;
}

static gboolean
gtk_dial_button_release( GtkWidget      *widget,
                         GdkEventButton *event )
{
  GtkDial *dial;

  g_return_val_if_fail (widget != NULL, FALSE);
  g_return_val_if_fail (GTK_IS_DIAL (widget), FALSE);
  g_return_val_if_fail (event != NULL, FALSE);

  dial = GTK_DIAL (widget);

  if (dial->button == event->button)
    {
      gtk_grab_remove (widget);

      dial->button = 0;

      if (dial->policy == GTK_UPDATE_DELAYED)
    g_source_remove (dial->timer);

      if ((dial->policy != GTK_UPDATE_CONTINUOUS) &&
      (dial->old_value != dial->adjustment->value))
    g_signal_emit_by_name (GTK_OBJECT (dial->adjustment), "value_changed");
    }

  return FALSE;
}

static gboolean
gtk_dial_motion_notify( GtkWidget      *widget,
                        GdkEventMotion *event )
{
  GtkDial *dial;
  GdkModifierType mods;
  gint x, y, mask;

  g_return_val_if_fail (widget != NULL, FALSE);
  g_return_val_if_fail (GTK_IS_DIAL (widget), FALSE);
  g_return_val_if_fail (event != NULL, FALSE);

  dial = GTK_DIAL (widget);

  if (dial->button != 0)
    {
      x = event->x;
      y = event->y;

      if (event->is_hint || (event->window != widget->window))
    gdk_window_get_pointer (widget->window, &x, &y, &mods);

      switch (dial->button)
    {
    case 1:
      mask = GDK_BUTTON1_MASK;
      break;
    case 2:
      mask = GDK_BUTTON2_MASK;
      break;
    case 3:
      mask = GDK_BUTTON3_MASK;
      break;
    default:
      mask = 0;
      break;
    }

      if (mods & mask)
    gtk_dial_update_mouse (dial, x,y);
    }

  return FALSE;
}

static gboolean
gtk_dial_timer( GtkDial *dial )
{
  g_return_val_if_fail (dial != NULL, FALSE);
  g_return_val_if_fail (GTK_IS_DIAL (dial), FALSE);

  if (dial->policy == GTK_UPDATE_DELAYED)
    g_signal_emit_by_name (GTK_OBJECT (dial->adjustment), "value_changed");

  return FALSE;
}

static void
gtk_dial_update_mouse( GtkDial *dial, gint x, gint y )
{
  gint xc, yc;
  gfloat old_value;

  g_return_if_fail (dial != NULL);
  g_return_if_fail (GTK_IS_DIAL (dial));

  xc = GTK_WIDGET(dial)->allocation.width / 2;
  yc = GTK_WIDGET(dial)->allocation.height / 2;

  old_value = dial->adjustment->value;
  dial->angle = atan2(yc-y, x-xc);

  if (dial->angle < -M_PI/2.)
    dial->angle += 2*M_PI;

  if (dial->angle < -M_PI/6)
    dial->angle = -M_PI/6;

  if (dial->angle > 7.*M_PI/6.)
    dial->angle = 7.*M_PI/6.;

  dial->adjustment->value = dial->adjustment->lower + (7.*M_PI/6 - dial->angle) *
    (dial->adjustment->upper - dial->adjustment->lower) / (4.*M_PI/3.);

  if (dial->adjustment->value != old_value)
    {
      if (dial->policy == GTK_UPDATE_CONTINUOUS)
    {
      g_signal_emit_by_name (GTK_OBJECT (dial->adjustment), "value_changed");
    }
      else
    {
      gtk_widget_queue_draw (GTK_WIDGET (dial));

      if (dial->policy == GTK_UPDATE_DELAYED)
        {
          if (dial->timer)
        g_source_remove (dial->timer);

          dial->timer = g_timeout_add (SCROLL_DELAY_LENGTH,
                       (GtkFunction) gtk_dial_timer,
                       (gpointer) dial);
        }
    }
    }
}

static void
gtk_dial_update (GtkDial *dial)
{
  gfloat new_value;

  g_return_if_fail (dial != NULL);
  g_return_if_fail (GTK_IS_DIAL (dial));

  new_value = dial->adjustment->value;

  if (new_value < dial->adjustment->lower)
    new_value = dial->adjustment->lower;

  if (new_value > dial->adjustment->upper)
    new_value = dial->adjustment->upper;

  if (new_value != dial->adjustment->value)
    {
      dial->adjustment->value = new_value;
      g_signal_emit_by_name (GTK_OBJECT (dial->adjustment), "value_changed");
    }

  dial->angle = 7.*M_PI/6. - (new_value - dial->adjustment->lower) * 4.*M_PI/3. /
    (dial->adjustment->upper - dial->adjustment->lower);

  gtk_widget_queue_draw (GTK_WIDGET (dial));
}

static void
gtk_dial_adjustment_changed (GtkAdjustment *adjustment,
                  gpointer       data)
{
  GtkDial *dial;

  g_return_if_fail (adjustment != NULL);
  g_return_if_fail (data != NULL);

  dial = GTK_DIAL (data);

  if ((dial->old_value != adjustment->value) ||
      (dial->old_lower != adjustment->lower) ||
      (dial->old_upper != adjustment->upper))
    {
      gtk_dial_update (dial);

      dial->old_value = adjustment->value;
      dial->old_lower = adjustment->lower;
      dial->old_upper = adjustment->upper;
    }
}

static void
gtk_dial_adjustment_value_changed (GtkAdjustment *adjustment,
                    gpointer       data)
{
  GtkDial *dial;

  g_return_if_fail (adjustment != NULL);
  g_return_if_fail (data != NULL);

  dial = GTK_DIAL (data);

  if (dial->old_value != adjustment->value)
    {
      gtk_dial_update (dial);

      dial->old_value = adjustment->value;
    }
}

dial_test.c

#include <stdio.h>
#include <stdlib.h>
#include <gtk/gtk.h>
#include "gtkdial.h"

void value_changed( GtkAdjustment *adjustment,
                    GtkWidget     *label )
{
  char buffer[16];

  sprintf(buffer,"%4.2f",adjustment->value);
  gtk_label_set_text (GTK_LABEL (label), buffer);
}

int main( int   argc,
          char *argv[])
{
  GtkWidget *window;
  GtkAdjustment *adjustment;
  GtkWidget *dial;
  GtkWidget *frame;
  GtkWidget *vbox;
  GtkWidget *label;

  gtk_init (&argc, &argv);

  window = gtk_window_new (GTK_WINDOW_TOPLEVEL);

  gtk_window_set_title (GTK_WINDOW (window), "Dial");

  g_signal_connect (G_OBJECT (window), "destroy",
            G_CALLBACK (exit), NULL);

  gtk_container_set_border_width (GTK_CONTAINER (window), 10);

  vbox = gtk_vbox_new (FALSE, 5);
  gtk_container_add (GTK_CONTAINER (window), vbox);
  gtk_widget_show (vbox);

  frame = gtk_frame_new (NULL);
  gtk_frame_set_shadow_type (GTK_FRAME (frame), GTK_SHADOW_IN);
  gtk_container_add (GTK_CONTAINER (vbox), frame);
  gtk_widget_show (frame);

  adjustment = GTK_ADJUSTMENT (gtk_adjustment_new (0, 0, 100, 0.01, 0.1, 0));

  dial = gtk_dial_new (adjustment);
  gtk_dial_set_update_policy (GTK_DIAL (dial), GTK_UPDATE_DELAYED);
  /*  gtk_widget_set_size_request (dial, 100, 100); */

  gtk_container_add (GTK_CONTAINER (frame), dial);
  gtk_widget_show (dial);

  label = gtk_label_new ("0.00");
  gtk_box_pack_end (GTK_BOX (vbox), label, 0, 0, 0);
  gtk_widget_show (label);

  g_signal_connect (G_OBJECT (adjustment), "value_changed",
            G_CALLBACK (value_changed), (gpointer) label);

  gtk_widget_show (window);

  gtk_main ();

  return 0;
}

<<< Previous | Home | Next >>>
Code Examples | Up | Scribble


Scribble

scribble-simple.f95

! GTK - The GIMP Toolkit
! Copyright (C) 1995-1997 Peter Mattis, Spencer Kimball and Josh MacDonald
!
! This library is free software; you can redistribute it and/or
! modify it under the terms of the GNU Library General Public
! License as published by the Free Software Foundation; either
! version 2 of the License, or (at your option) any later version.
!
! This library is distributed in the hope that it will be useful,
! but WITHOUT ANY WARRANTY; without even the implied warranty of
! MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
! Library General Public License for more details.
!
! You should have received a copy of the GNU Library General Public
! License along with this library; if not, write to the
! Free Software Foundation, Inc., 59 Temple Place - Suite 330,
! Boston, MA 02111-1307, USA.
!
Module scribble_window
  Use cairo
  Use pango
  Use gtk
  Use gdk
  Use glib
  Implicit None

  Type(GtkWidget),Pointer :: drawing_area

  ! Backing pixmap for drawing area.
  Type(GdkPixmap),Pointer :: pixmap => Null()

Contains

  ! Create a new backing pixmap of the appropriate size
  Integer(gboolean) Function configure_event(pwidget,pevent) Bind(C,Name='')
    Type(C_Ptr),Value :: pwidget,pevent
    Type(GtkWidget),Pointer :: widget
    Type(GtkStyle),Pointer :: Style

    widget => GTK_WIDGET(pwidget)

    If (Associated(pixmap)) Then
      Call g_object_unref(C_Loc(pixmap))
      Nullify(pixmap)
    End If

    pixmap => gdk_pixmap_new(GDK_DRAWABLE(widget%window), &
                             widget%allocation%width, &
                             widget%allocation%height,-1)
    Style => GTK_STYLE(widget%style)
    Call gdk_draw_rectangle(GDK_DRAWABLE(C_Loc(pixmap)), &
                            GDK_GC(Style%white_gc),TRUE,0,0, &
                            widget%allocation%width,widget%allocation%height)
    configure_event = TRUE
  End Function

  ! Redraw the screen from the backing pixmap.
  Integer(gboolean) Function expose_event(pwidget,pevent) Bind(C,Name='')
    Type(C_Ptr),Value :: pwidget,pevent

    Type(GtkWidget),Pointer :: widget
    Type(GdkEventExpose),Pointer :: event
    Type(GtkStyle),Pointer :: Style
    Integer :: state

    widget => GTK_WIDGET(pwidget)
    Style  => GTK_STYLE(widget%style)
    Call C_F_Pointer(pevent,event)

    state = GTK_WIDGET_STATE(widget)
    Call gdk_draw_drawable(GDK_DRAWABLE(widget%window), &
                           GDK_GC(Style%fg_gc(state)), &
                           GDK_DRAWABLE(C_Loc(pixmap)), &
                           event%area%x,event%area%y, &
                           event%area%x,event%area%y, &
                           event%area%width,event%area%height)
    expose_event = FALSE
  End Function

  ! Draw a rectangle on the screen.
  Subroutine draw_brush(widget,x,y)
    Type(GtkWidget),Pointer :: widget
    Double Precision,Intent(In) :: x,y
    Type(GdkRectangle) :: update_rect
    Type(GtkStyle),Pointer :: Style

    update_rect%x      = x - 5
    update_rect%y      = y - 5
    update_rect%width  = 10
    update_rect%height = 10

    Style => GTK_STYLE(widget%style)

    Call gdk_draw_rectangle(GDK_DRAWABLE(C_Loc(pixmap)), &
                            GDK_GC(Style%black_gc),TRUE, &
                            update_rect%x,update_rect%y, &
                            update_rect%width,update_rect%height)
    Call gtk_widget_queue_draw_area(widget,update_rect%x,update_rect%y, &
                                    update_rect%width,update_rect%height)
  End Subroutine

  Integer(gboolean) Function button_press_event(pwidget,pevent) Bind(C,Name='')
    Type(C_Ptr),Value :: pwidget,pevent

    Type(GtkWidget),Pointer :: widget
    Type(GdkEventButton),Pointer :: event

    widget => GTK_WIDGET(pwidget)
    Call C_F_Pointer(pevent,event)

    If (event%button==1 .And. Associated(pixmap)) &
      Call draw_brush(widget,event%x,event%y)
    button_press_event = TRUE
  End Function

  Integer(gboolean) Function motion_notify_event(pwidget,pevent) Bind(C,Name='')
    Type(C_Ptr),Value :: pwidget,pevent
    Type(GdkEventMotion),Pointer :: event
    Type(GtkWidget),Pointer :: widget
    Type(GdkWindow),Pointer :: dmy
    Integer :: x,y
    Integer(GdkModifierType) :: state

    widget => GTK_WIDGET(pwidget)
    Call C_F_Pointer(pevent,event)

    If (event%is_hint/=0) Then
      dmy => gdk_window_get_pointer(GDK_WINDOW(event%window),x,y,state)
    Else
      x = event%x
      y = event%y
      state = event%state
    End If

    If (state/=0 .And. GDK_BUTTON1_MASK/=0 .And. Associated(pixmap)) &
      Call draw_brush(widget,dble(x),dble(y))
    motion_notify_event = TRUE

  End Function

End Module

Program main
  Use scribble_window

  Type(GtkWidget),Pointer :: vbox,button,window
  Integer :: mask

  Call gtk_init

  window => gtk_window_new(GTK_WINDOW_TOPLEVEL)
  Call gtk_widget_set_name(window,"Test Input")

  vbox => gtk_vbox_new(FALSE,0)
  Call gtk_container_add(GTK_CONTAINER(window),vbox)
  Call gtk_widget_show(vbox)

  Call g_signal_connect(G_OBJECT(window),"destroy", &
                        C_FunLoc(gtk_main_quit),C_Null_Ptr)

  ! Create the drawing area.

  drawing_area => gtk_drawing_area_new()
  Call gtk_widget_set_size_request(GTK_WIDGET(C_Loc(drawing_area)),200,200)
  Call gtk_box_pack_start(GTK_BOX(vbox),drawing_area,TRUE,TRUE,0)

  Call gtk_widget_show(drawing_area)

  ! Signals used to handle backing pixmap.
  Call g_signal_connect(G_OBJECT(drawing_area),"expose_event", &
                        C_FunLoc(expose_event),C_Null_Ptr)
  Call g_signal_connect(G_OBJECT(drawing_area),"configure_event", &
                        C_FunLoc(configure_event),C_Null_Ptr)

  ! Event signals.
  Call g_signal_connect(G_OBJECT(drawing_area),"motion_notify_event", &
                        C_FunLoc(motion_notify_event),C_Null_Ptr)
  Call g_signal_connect(G_OBJECT(drawing_area),"button_press_event", &
                        C_FunLoc(button_press_event),C_Null_Ptr)

  mask = ior(GDK_EXPOSURE_MASK,GDK_LEAVE_NOTIFY_MASK)
  mask = ior(mask             ,GDK_BUTTON_PRESS_MASK)
  mask = ior(mask             ,GDK_POINTER_MOTION_MASK)
  mask = ior(mask             ,GDK_POINTER_MOTION_HINT_MASK)
  Call gtk_widget_set_events(drawing_area,mask)

  ! ... And a quit button.
  button => gtk_button_new_with_label("Quit")
  Call gtk_box_pack_start(GTK_BOX(vbox),button,FALSE,FALSE,0)
  Call g_signal_connect_swapped(G_OBJECT(button),"clicked", &
                                C_FunLoc(gtk_widget_destroy),C_Loc(window))
  Call gtk_widget_show(button)

  Call gtk_widget_show(window)

  Call gtk_main

End Program

scribble-xinput.f95

! GTK - The GIMP Toolkit
! Copyright (C) 1995-1997 Peter Mattis, Spencer Kimball and Josh MacDonald
!
! This library is free software; you can redistribute it and/or
! modify it under the terms of the GNU Library General Public
! License as published by the Free Software Foundation; either
! version 2 of the License, or (at your option) any later version.
!
! This library is distributed in the hope that it will be useful,
! but WITHOUT ANY WARRANTY; without even the implied warranty of
! MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
! Library General Public License for more details.
!
! You should have received a copy of the GNU Library General Public
! License along with this library; if not, write to the
! Free Software Foundation, Inc., 59 Temple Place - Suite 330,
! Boston, MA 02111-1307, USA.
!
Module scribble_xinput
  Use cairo
  Use pango
  Use gtk
  Use gdk
  Use glib
  Implicit None

  Type(GtkWidget),Pointer :: drawing_area
  ! Backing pixmap for drawing area.
  Type(GdkPixmap),Pointer :: pixmap => null()

Contains

  Integer(gboolean) Function configure_event(pwidget,pevent) Bind(C,Name='')
    Type(C_Ptr),Value :: pwidget,pevent
    Type(GtkWidget),Pointer :: widget
    Type(GtkStyle),Pointer :: Style

    widget => GTK_WIDGET(pwidget)

    If (Associated(pixmap)) Then
      Call g_object_unref(C_Loc(pixmap))
      Nullify(pixmap)
    End If

    pixmap => gdk_pixmap_new(GDK_DRAWABLE(widget%window), &
                             widget%allocation%width, &
                             widget%allocation%height,-1)
    Style => GTK_STYLE(widget%style)
    Call gdk_draw_rectangle(GDK_DRAWABLE(C_Loc(pixmap)), &
                            GDK_GC(Style%white_gc),TRUE,0,0, &
                            widget%allocation%width,widget%allocation%height)
    configure_event = TRUE
  End Function

  Integer(gboolean) Function expose_event(pwidget,pevent) Bind(C,Name='')
    Type(C_Ptr),Value :: pwidget,pevent

    Type(GtkWidget),Pointer :: widget
    Type(GdkEventExpose),Pointer :: event
    Type(GtkStyle),Pointer :: Style
    Integer :: state

    widget => GTK_WIDGET(pwidget)
    Style  => GTK_STYLE(widget%style)
    Call C_F_Pointer(pevent,event)

    state = GTK_WIDGET_STATE(widget)
    Call gdk_draw_drawable(GDK_DRAWABLE(widget%window), &
                                        GDK_GC(Style%fg_gc(state)), &
                                        GDK_DRAWABLE(C_Loc(pixmap)),&
                                        event%area%x,event%area%y, &
                                        event%area%x,event%area%y, &
                                        event%area%width,event%area%height)
    expose_event = FALSE
  End Function

  Subroutine draw_brush(widget,source,x,y,pressure)
    Type(GtkWidget),Pointer :: widget
    Integer(GdkInputSource) :: source
    Double Precision :: x,y,pressure
    Type(GdkRectangle) :: update_rect
    Type(GtkStyle),Pointer :: style
    Type(GdkGC),Pointer :: gc

    style => GTK_STYLE(widget%style)

    Select Case(source)
    Case (GDK_SOURCE_MOUSE)
      Call C_F_Pointer(style%dark_gc(GTK_WIDGET_STATE(widget)),gc)
    Case(GDK_SOURCE_PEN)
      Call C_F_Pointer(style%black_gc,gc)
    Case(GDK_SOURCE_ERASER)
      Call C_F_Pointer(style%white_gc,gc)
    Case Default
      Call C_F_Pointer(style%light_gc(GTK_WIDGET_STATE(widget)),gc)
    End Select

    update_rect%x = x - 10 * pressure
    update_rect%y = y - 10 * pressure
    update_rect%width = 20 * pressure
    update_rect%height = 20 * pressure

    Call gdk_draw_rectangle(GDK_DRAWABLE(C_Loc(pixmap)), &
                            GDK_GC(Style%black_gc),TRUE, &
                            update_rect%x,update_rect%y, &
                            update_rect%width,update_rect%height)
   Call gtk_widget_queue_draw_area(widget,update_rect%x,update_rect%y, &
                                   update_rect%width,update_rect%height)
  End Subroutine

  Subroutine print_button_press(device)
    Type(GdkDevice),Pointer :: device
    Character,Pointer :: pstr

    Call C_F_Pointer(device%name,pstr) ! This is a lie.
    Call g_print("Button press on device '")
    Call g_print(pstr) ! Only works due to faulty runtime.
    Call g_print("'" // c_new_line)
  End Subroutine

  Integer(gboolean) Function button_press_event(pwidget,pevent) Bind(C,Name='')
    Type(C_Ptr),Value :: pwidget,pevent
    Real(gdouble) :: pressure
    Type(GtkWidget),Pointer :: widget
    Type(GdkEventButton),Pointer :: event
    Type(GdkDevice),Pointer :: device
    Type(GdkEvent),Pointer :: gevent
    Integer :: status

    widget => GTK_WIDGET(pwidget)
    Call C_F_Pointer(pevent,event)
    Call C_F_Pointer(event%device,device)
    Call C_F_Pointer(pevent,gevent)

    Call print_button_press(device)

    If (event%button==1 .And. Associated(pixmap)) Then
        status = gdk_event_get_axis(gevent,GDK_AXIS_PRESSURE,pressure)
        Call draw_brush (widget,device%source,event%x,event%y,pressure)
    End If
    button_press_event = TRUE
  End Function

  Integer(gboolean) Function motion_notify_event(pwidget,pevent) Bind(C,Name='')
    Type(C_Ptr),Value :: pwidget,pevent
    Type(GdkEventMotion),Pointer :: event
    Type(GtkWidget),Pointer :: widget
    Type(GdkWindow),Pointer :: gwin
    Type(GdkEvent),Pointer :: gevent
    Type(GdkDevice),Pointer :: device
    Double Precision :: dmy,dx,dy
    Integer :: x,y
    Integer(GdkModifierType) :: state
    Real(gdouble) :: pressure
    Integer :: res

    widget => GTK_WIDGET(pwidget)
    Call C_F_Pointer(pevent,event)
    Call C_F_Pointer(pevent,gevent)
    Call C_F_Pointer(event%device,device)
    Call C_F_Pointer(event%window,gwin)
    If (event%is_hint/=0) Then
      Call gdk_device_get_state(device,gwin,dmy,state)
      res = gdk_event_get_axis(gevent,GDK_AXIS_X,dx)
      res = gdk_event_get_axis(gevent,GDK_AXIS_Y,dy)
      res = gdk_event_get_axis(gevent,GDK_AXIS_PRESSURE,pressure)
      x = dx
      y = dy
    Else
      x = event%x
      y = event%y
      res = gdk_event_get_axis(gevent,GDK_AXIS_PRESSURE,pressure)
      state = event%state
    End If

    If (state/=0 .And. GDK_BUTTON1_MASK/=0 .And. Associated(pixmap)) &
      Call draw_brush(widget,device%source,dble(x),dble(y),pressure)

    motion_notify_event = TRUE
  End Function

  Subroutine input_dialog_destroy(w,data) Bind(C,Name='')
    Type(C_Ptr),Value :: w
    Type(C_Ptr) :: data
    data = C_Null_Ptr
  End Subroutine

  Subroutine create_input_dialog() Bind(C,Name='')
    Type(GtkWidget),Pointer :: inputd => Null()
    Type(GtkInputDialog),Pointer :: dialog

    If (.Not. Associated(inputd)) Then
      inputd => gtk_input_dialog_new()
      dialog => GTK_INPUT_DIALOG(inputd)
      Call g_signal_connect(G_OBJECT(inputd),"destroy", &
                            C_FunLoc(input_dialog_destroy),C_Loc(inputd))
      Call g_signal_connect_swapped(G_OBJECT(dialog%close_button),"clicked", &
                                    C_FunLoc(gtk_widget_hide),C_Loc(inputd))
      Call gtk_widget_hide(dialog%save_button)
      Call gtk_widget_show(inputd)
    Else
      If (GTK_WIDGET_MAPPED(inputd)==0) Then
        Call gtk_widget_show(inputd)
      Else
        Call gdk_window_raise(GDK_WINDOW(inputd%window))
      End If
    End If
  End Subroutine

End Module

Program main
  Use scribble_xinput

  Type(GtkWidget),Pointer :: vbox,button,window
  Integer :: mask

  Call gtk_init()

  window => gtk_window_new(GTK_WINDOW_TOPLEVEL)
  Call gtk_widget_set_name(window,"Test Input")

  vbox => gtk_vbox_new(FALSE,0)
  Call gtk_container_add(GTK_CONTAINER(window),vbox)
  Call gtk_widget_show(vbox)

  Call g_signal_connect(G_OBJECT(window),"destroy", &
                        C_FunLoc(gtk_main_quit),C_Null_Ptr)

  drawing_area => gtk_drawing_area_new()
  Call gtk_widget_set_size_request(GTK_WIDGET(C_Loc(drawing_area)),200,200)
  Call gtk_box_pack_start(GTK_BOX(vbox),drawing_area,TRUE,TRUE,0)

  Call gtk_widget_show(drawing_area)

  Call g_signal_connect(G_OBJECT(drawing_area),"expose_event", &
                        C_FunLoc(expose_event),C_Null_Ptr)
  Call g_signal_connect(G_OBJECT(drawing_area),"configure_event", &
                        C_FunLoc(configure_event),C_Null_Ptr)

  Call g_signal_connect(G_OBJECT(drawing_area),"motion_notify_event", &
                        C_FunLoc(motion_notify_event),C_Null_Ptr)
  Call g_signal_connect(G_OBJECT(drawing_area),"button_press_event", &
                        C_FunLoc(button_press_event),C_Null_Ptr)

  mask = ior(GDK_EXPOSURE_MASK,GDK_LEAVE_NOTIFY_MASK)
  mask = ior(mask             ,GDK_BUTTON_PRESS_MASK)
  mask = ior(mask             ,GDK_POINTER_MOTION_MASK)
  mask = ior(mask             ,GDK_POINTER_MOTION_HINT_MASK)
  Call gtk_widget_set_events(drawing_area,mask)

  ! The following call enables tracking and processing of extension
  ! events for the drawing area.
  Call gtk_widget_set_extension_events(drawing_area,GDK_EXTENSION_EVENTS_CURSOR)

  ! .. And some buttons.
  button => gtk_button_new_with_label("Input Dialogue")
  Call gtk_box_pack_start(GTK_BOX(vbox), button, FALSE, FALSE,0)

  Call g_signal_connect(G_OBJECT(button),"clicked", &
                        C_FunLoc(create_input_dialog),C_Null_Ptr)
  Call gtk_widget_show(button)

  button => gtk_button_new_with_label("Quit")
  Call gtk_box_pack_start(GTK_BOX(vbox),button,FALSE,FALSE,0)
  Call g_signal_connect_swapped(G_OBJECT(button),"clicked", &
                                C_FunLoc(gtk_widget_destroy),C_Loc(window))
  Call gtk_widget_show(button)

  Call gtk_widget_show(window)

  Call gtk_main ()

End Program

<<< Previous | Home
GtkDial | Up


GTK+ Project Documentation (for C)

These references are for using GTK+ from C. They are available directly from the GTK+ project website, http://www.gtk.org/, and included here as is for reference.

List of reference manuals

GTK+ Reference Manual

GDK Reference Manual

Libglade Reference Manual

GtkGLExt Reference Manual

GLib Reference Manual

GObject Reference Manual

Pango Reference Manual

Cairo: A Vector Graphics Library

The gdk-pixbuf Library

RSVG Reference Manual


GTK+ Reference Manual

for GTK+ 2.10.11

I. GTK+ Overview
Compiling the GTK+ libraries — How to compile GTK+ itself
Compiling GTK+ Applications — How to compile your GTK+ application
Running GTK+ Applications — How to run and debug your GTK+ application
Using GTK+ on the X Window System — X11 aspects of using GTK+
Using GTK+ on Windows — Windows-specific aspects of using GTK+
Using GTK+ on Mac OS X — OS X-specific aspects of using GTK+
Using GTK+ on DirectFB — DirectFB-specific aspects of using GTK+
Using GTK+ on the Framebuffer — Linux framebuffer aspects of using GTK+
Mailing lists and bug reports — Getting help with GTK+
Common Questions — Find answers to common questions in the GTK+ manual
II. GTK+ Core Reference
Main loop and Events — Library initialization, main event loop, and events
Accelerator Groups — Groups of global keyboard accelerators for an entire GtkWindow
Accelerator Maps — Loadable keyboard accelerator specifications
Clipboards — Storing data on clipboards
Drag and Drop — Functions for controlling drag and drop handling
GtkIconTheme — Looking up icons by name
Stock Items — Prebuilt common menu/toolbar items and corresponding icons
Themeable Stock Images — Manipulating stock icons
Resource Files — Routines for handling resource files
Settings — Sharing settings between applications
Bindings — Key bindings for individual widgets
Standard Enumerations — Public enumerated types used throughout GTK+
Graphics Contexts — A shared pool of GdkGC objects
Styles — Functions for drawing widget parts
Selections — Functions for handling inter-process communication via selections
Version Information — Variables and functions to check the GTK+ version
Signals — Object methods and callbacks
Types — Handle run-time type creation
III. GTK+ Widgets and Objects
Object Hierarchy
Widget Gallery
Windows
GtkDialog — Create popup windows
GtkInvisible — A widget which is not displayed
GtkMessageDialog — A convenient message window
GtkWindow — Toplevel which can contain other widgets
GtkWindowGroup — Limit the effect of grabs
GtkAboutDialog — Display information about an application
GtkAssistant — A widget used to guide users through multi-step operations
Display Widgets
GtkAccelLabel — A label which displays an accelerator key on the right of the text
GtkImage — A widget displaying an image
GtkLabel — A widget that displays a small to medium amount of text
GtkProgressBar — A widget which indicates progress visually
GtkStatusbar — Report messages of minor importance to the user
GtkStatusIcon — Display an icon in the system tray
Buttons and Toggles
GtkButton — A widget that creates a signal when clicked on
GtkCheckButton — Create widgets with a discrete toggle button
GtkRadioButton — A choice from multiple check buttons
GtkToggleButton — Create buttons which retain their state
GtkLinkButton — Create buttons bound to a URL
Numeric/Text Data Entry
GtkEntry — A single line text entry field
GtkEntryCompletion — Completion functionality for GtkEntry
GtkHScale — A horizontal slider widget for selecting a value from a range
GtkVScale — A vertical slider widget for selecting a value from a range
GtkSpinButton — Retrieve an integer or floating-point number from the user
GtkEditable — Interface for text-editing widgets
Multiline Text Editor
Text Widget Overview — Overview of GtkTextBuffer, GtkTextView, and friends
GtkTextIter — Text buffer iterator
GtkTextMark — A position in the buffer preserved across buffer modifications
GtkTextBuffer — Stores attributed text for display in a GtkTextView
GtkTextTag — A tag that can be applied to text in a GtkTextBuffer
GtkTextTagTable — Collection of tags that can be used together
GtkTextView — Widget that displays a GtkTextBuffer
Tree, List and Icon Grid Widgets
Tree and List Widget Overview — Overview of GtkTreeModel, GtkTreeView, and other associated widgets
GtkTreeModel — The tree interface used by GtkTreeView
GtkTreeSelection — The selection object for GtkTreeView
GtkTreeViewColumn — A visible column in a GtkTreeView widget
GtkTreeView — A widget for displaying both trees and lists
GtkTreeView drag-and-drop — Interfaces for drag-and-drop support in GtkTreeView
GtkCellView — A widget displaying a single row of a GtkTreeModel
GtkIconView — A widget which displays a list of icons in a grid
GtkTreeSortable — The interface for sortable models used by GtkTreeView
GtkTreeModelSort — A GtkTreeModel which makes an underlying tree model sortable
GtkTreeModelFilter — A GtkTreeModel which hides parts of an underlying tree model
GtkCellLayout — An interface for packing cells
GtkCellRenderer — An object for rendering a single cell on a GdkDrawable
GtkCellEditable — Interface for widgets which can are used for editing cells
GtkCellRendererAccel — Renders a keyboard accelerator in a cell
GtkCellRendererCombo — Renders a combobox in a cell
GtkCellRendererPixbuf — Renders a pixbuf in a cell
GtkCellRendererProgress — Renders numbers as progress bars
GtkCellRendererSpin — Renders a spin button in a cell
GtkCellRendererText — Renders text in a cell
GtkCellRendererToggle — Renders a toggle button in a cell
GtkListStore — A list-like data structure that can be used with the GtkTreeView
GtkTreeStore — A tree-like data structure that can be used with the GtkTreeView
Menus, Combo Box, Toolbar
GtkComboBox — A widget used to choose from a list of items
GtkComboBoxEntry — A text entry field with a dropdown list
GtkMenu — A menu widget
GtkMenuBar — A subclass widget for GtkMenuShell which holds GtkMenuItem widgets
GtkMenuItem — The widget used for item in menus
GtkMenuShell — A base class for menu objects
GtkImageMenuItem — A menu item with an icon
GtkRadioMenuItem — A choice from multiple check menu items
GtkCheckMenuItem — A menu item with a check box
GtkSeparatorMenuItem — A separator used in menus
GtkTearoffMenuItem — A menu item used to tear off and reattach its menu
GtkToolbar — Create bars of buttons and other widgets
GtkToolItem — The base class of widgets that can be added to GtkToolbar
GtkSeparatorToolItem — A toolbar item that separates groups of other toolbar items
GtkToolButton — A GtkToolItem subclass that displays buttons
GtkMenuToolButton — A GtkToolItem containing a button with an additional dropdown menu
GtkToggleToolButton — A GtkToolItem containing a toggle button
GtkRadioToolButton — A toolbar item that contains a radio button
Action-based menus and toolbars
GtkUIManager — Constructing menus and toolbars from an XML description
GtkActionGroup — A group of actions
GtkAction — An action which can be triggered by a menu or toolbar item
GtkToggleAction — An action which can be toggled between two states
GtkRadioAction — An action of which only one in a group can be active
Selectors (File/Font/Color/Input Devices)
GtkColorButton — A button to launch a color selection dialog
GtkColorSelection — A widget used to select a color
GtkColorSelectionDialog — A standard dialog box for selecting a color
GtkFileSelection — Prompt the user for a file or directory name
GtkFileChooser — File chooser interface used by GtkFileChooserWidget and GtkFileChooserDialog
GtkFileChooserButton — A button to launch a file selection dialog
GtkFileChooserDialog — A file chooser dialog, suitable for "File/Open" or "File/Save" commands
GtkFileChooserWidget — File chooser widget that can be embedded in other widgets
GtkFileFilter — A filter for selecting a file subset
GtkFontButton — A button to launch a font selection dialog
GtkFontSelection — A widget for selecting fonts
GtkFontSelectionDialog — A dialog box for selecting fonts
GtkInputDialog — Configure devices for the XInput extension
Layout Containers
GtkAlignment — A widget which controls the alignment and size of its child
GtkAspectFrame — A frame that constrains its child to a particular aspect ratio
GtkHBox — A horizontal container box
GtkVBox — A vertical container box
GtkHButtonBox — A container for arranging buttons horizontally
GtkVButtonBox — A container for arranging buttons vertically
GtkFixed — A container which allows you to position widgets at fixed coordinates
GtkHPaned — A container with two panes arranged horizontally
GtkVPaned — A container with two panes arranged vertically
GtkLayout — Infinite scrollable area containing child widgets and/or custom drawing
GtkNotebook — A tabbed notebook container
GtkTable — Pack widgets in regular patterns
GtkExpander — A container which can hide its child
Ornaments
GtkFrame — A bin with a decorative frame and optional label
GtkHSeparator — A horizontal separator
GtkVSeparator — A vertical separator
Scrolling
GtkHScrollbar — A horizontal scrollbar
GtkVScrollbar — A vertical scrollbar
GtkScrolledWindow — Adds scrollbars to its child widget
Printing
GtkPrintOperation — High-level Printing API
GtkPrintContext — Encapsulates context for drawing pages
GtkPrintSettings — Stores print settings
GtkPageSetup — Stores page setup information
GtkPaperSize — Support for named paper sizes
GtkPrinter — Represents a printer
GtkPrintJob — Represents a print job
GtkPrintUnixDialog — A print dialog
GtkPageSetupUnixDialog — A page setup dialog
Miscellaneous
GtkAdjustment — A GtkObject representing an adjustable bounded value
GtkArrow — Displays an arrow
GtkCalendar — Displays a calendar and allows the user to select a date
GtkDrawingArea — A widget for custom user interface elements
GtkEventBox — A widget used to catch events for widgets which do not have their own window
GtkHandleBox — a widget for detachable window portions
GtkIMContextSimple — An input method context supporting table-based input methods
GtkIMMulticontext — An input method context supporting multiple, loadable input methods
GtkSizeGroup — Grouping widgets so they request the same size
GtkTooltips — Add tips to your widgets
GtkViewport — An adapter which makes widgets scrollable
GtkAccessible — Accessibility support for widgets
Abstract Base Classes
GtkBin — A container with just one child
GtkBox — Base class for box containers
GtkButtonBox — Base class for GtkHButtonBox and GtkVButtonBox
GtkContainer — Base class for widgets which contain other widgets
GtkItem — Abstract base class for GtkMenuItem, GtkListItem and GtkTreeItem
GtkMisc — Base class for widgets with alignments and padding
GtkObject — The base class of the GTK+ type hierarchy
GtkPaned — Base class for widgets with two adjustable panes
GtkRange — Base class for widgets which visualize an adjustment
GtkScale — Base class for GtkHScale and GtkVScale
GtkScrollbar — Base class for GtkHScrollbar and GtkVScrollbar
GtkSeparator — Base class for GtkHSeparator and GtkVSeparator
GtkWidget — Base class for all widgets
GtkIMContext — Base class for input method contexts
Cross-process Embedding
GtkPlug — Toplevel for embedding into other processes
GtkSocket — Container for widgets from other processes
Special-purpose features
GtkCurve — Allows direct editing of a curve
GtkGammaCurve — a subclass of GtkCurve for editing gamma curves.
GtkRuler — Base class for horizontal or vertical rulers
GtkHRuler — A horizontal ruler.
GtkVRuler — A vertical ruler.
Recently Used Documents
GtkRecentManager — Managing Recently Used Files
GtkRecentChooser — Interface implemented by GtkRecentChooserWidget, GtkRecentChooserMenu and GtkRecentChooserDialog
GtkRecentChooserDialog — Displays recently used files in a dialog
GtkRecentChooserMenu — Displays recently used files in a menu
GtkRecentChooserWidget — Displays recently used files
GtkRecentFilter — A filter for selecting a subset of recently used files
Deprecated
GtkCList — A multi-columned scrolling list widget
GtkCTree — A widget displaying a hierarchical tree
GtkCombo — A text entry field with a dropdown list
GtkItemFactory — A factory for menus
GtkList — Widget for packing a list of selectable items
GtkListItem — An item in a GtkList
GtkOldEditable — Base class for text-editing widgets
GtkOptionMenu — A widget used to choose from a list of valid choices
GtkPixmap — A widget displaying a graphical image or icon
GtkPreview — A widget to display RGB or grayscale data
GtkProgress — Base class for GtkProgressBar
GtkText — A text widget
GtkTipsQuery — Displays help about widgets in the user interface
GtkTree — A tree widget
GtkTreeItem — The widget used for items in a GtkTree
IV. Migrating from Previous Versions of GTK+
Migration Checklist
Implement GtkWidget::popup_menu
Use GdkEventExpose.region
Test for modifier keys correctly
Use named icons
Changes from 1.0 to 1.2 — Incompatible changes made between version 1.0 and version 1.2
Changes from 1.2 to 2.0 — Incompatible changes made between version 1.2 and version 2.0
Migrating from GtkFileSelection to GtkFileChooser
Creating a GtkFileChooserDialog
Selection Modes
Installing a Preview widget
Installing Extra Widgets
New features
Migrating from old menu and toolbar systems to GtkAction
Actions and Action Groups
User Interface Manager Object
Migrating from GnomeUIInfo
Migrating from GtkOptionMenu and GtkCombo to GtkComboBox and GtkComboBoxEntry
Migrating from GtkOptionMenu to GtkComboBox
Migrating from GtkCombo to GtkComboBoxEntry
New features
Migrating from GnomeIconList to GtkIconView
Migrating from GnomeAbout to GtkAboutDialog
Migrating from GnomeColorPicker to GtkColorButton
Migrating from GnomeDruid to GtkAssistant
Inserting pages
Decorating the assistant pages
Setting the page flow
Migrating from EggRecent to GtkRecentChooser
Managing the Recently Used Documents
Displaying the Recently Used Documents
Advanced usage
Migrating from GnomeHRef to GtkLinkButton
V. GTK+ Tools
gtk-query-immodules-2.0 — Input method module registration utility
gtk-update-icon-cache — Icon theme caching utility
Glossary
Index
Index of deprecated symbols
Index of new symbols in 2.2
Index of new symbols in 2.4
Index of new symbols in 2.6
Index of new symbols in 2.8
Index of new symbols in 2.10


GDK Reference Manual

for GDK 2.10.11

I. API Reference
General — Library initialization and miscellaneous functions
Multi-head Support Overview — Overview of GdkDisplay and GdkScreen
GdkDisplay — Controls the keyboard/mouse pointer grabs and a set of GdkScreens
GdkDisplayManager — Maintains a list of all open GdkDisplays
GdkScreen — Object representing a physical screen
Points, Rectangles and Regions — Simple graphical data types
Graphics Contexts — Objects to encapsulate drawing properties
Drawing Primitives — Functions for drawing points, lines, arcs, and text
Bitmaps and Pixmaps — Offscreen drawables
GdkRGB — Renders RGB, grayscale, or indexed image data to a GdkDrawable
Images — A client-side area for bit-mapped graphics
Pixbufs — Functions for rendering pixbufs on drawables
Colormaps and Colors — Manipulation of colors and colormaps
Visuals — Low-level display hardware information
Fonts — Loading and manipulating fonts
Cursors — Standard and pixmap cursors
Windows — Onscreen display areas in the target window system
Events — Functions for handling events from the window system
Event Structures — Data structures specific to each type of event
Key Values — Functions for manipulating keyboard codes
Selections — Functions for transfering data via the X selection mechanism
Drag and Drop — Functions for controlling drag and drop handling
Properties and Atoms — Functions to manipulate properties on windows
Threads — Functions for using GDK in multi-threaded programs
Input — Callbacks on file descriptors
Input Devices — Functions for handling extended input devices
Pango Interaction — Using Pango in GDK
Cairo Interaction — Functions to support using Cairo
X Window System Interaction — X backend-specific functions
Index
Index of deprecated symbols
Index of new symbols in 2.2
Index of new symbols in 2.4
Index of new symbols in 2.6
Index of new symbols in 2.8
Index of new symbols in 2.10


Libglade Reference Manual

James Henstridge

<james@daa.com.au>

for libglade 2.5.0

Copyright © 1999-2002 James Henstridge

Permission is granted to copy, distribute and/or modify this document under the terms of the GNU Free Documentation License, Version 1.1 or any later version published by the Free Software Foundation with no Invariant Sections, no Front-Cover Texts, and no Back-Cover Texts. You may obtain a copy of the GNU Free Documentation License from the Free Software Foundation by visiting their Web site or by writing to: Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.

Many of the names used by companies to distinguish their products and services are claimed as trademarks. Where those names appear in any GNOME documentation, and those trademarks are made aware to the members of the GNOME Documentation Project, the names have been printed in caps or initial caps.

Abstract

This manual documents the interfaces of the libglade library and has some short notes to help get you up to speed with using the library.

Table of Contents

Libglade Programming Notes
Libglade Programming Basics
Libglade Modules
Internationalisation with Libglade
Extending Libglade
Embedding Libglade Interfaces
Glade 2.0 File Format
Property Representations
Exceptions
I. Libglade Library Reference
Libglade Initialisation - Routines used to initialise libglade.
GladeXML - Allows dynamic loading of user interfaces from XML descriptions.
Libglade SAX Parser - Declarations and routines for accessing the SAX based parser.
Libglade Build - Routines used by widget building routines
Libglade Programming Notes >>


GtkGLExt Reference Manual

for GtkGLExt 1.0.5

Table of Contents

I. GtkGLExt Overview
Compiling the GtkGLExt libraries - How to compile GtkGLExt
Running GtkGLExt Applications - How to run and debug your GtkGLExt application
II. GdkGLExt API Reference
Initialization - Library initialization functions
Query - Functions to query OpenGL support information
Frame Buffer Configuration - OpenGL frame buffer configuration object
Rendering Context - OpenGL rendering context object
Rendering Surface - OpenGL rendering surface interface
OpenGL Pixmap - OpenGL pixmap which is maintained off-screen
OpenGL Window - OpenGL window which is located on-screen
Font Rendering - Functions for font rendering in OpenGL
Geometric Object Rendering - Functions for generating easily recognizable 3D geometric objects
Tokens - OpenGL-related tokens
X Window System Interaction - Internal X-related functions
Version Information - Variables and macros to check the GdkGLExt version
III. GtkGLExt API Reference
Initialization - Library initialization functions
OpenGL-Capable Widget - OpenGL extension to GtkWidget API
Version Information - Variables and macros to check the GtkGLExt version
Part I. GtkGLExt Overview >>


GLib Reference Manual

for GLib 2.12.11

GLib Overview
Compiling the GLib package — How to compile GLib itself
Cross-compiling the GLib package — How to cross-compile GLib
Compiling GLib Applications — How to compile your GLib application
Running GLib Applications — How to run and debug your GLib application
Changes to GLib — Incompatible changes made between successing versions of GLib
Mailing lists and bug reports — Getting help with GLib
GLib Fundamentals
Version Information — Variables and functions to check the GLib version
Basic Types — standard GLib types, defined for ease-of-use and portability.
Limits of Basic Types — portable method of determining the limits of the standard types.
Standard Macros — commonly-used macros.
Type Conversion Macros — portably storing integers in pointer variables.
Byte Order Macros — a portable way to convert between different byte orders.
Numerical Definitions — mathematical constants, and floating point decomposition.
Miscellaneous Macros — specialized macros which are not used often.
Atomic Operations — basic atomic integer and pointer operations
GLib Core Application Support
The Main Event Loop — manages all available sources of events.
Threads — thread abstraction; including threads, different mutexes, conditions and thread private data.
Thread Pools — pools of threads to execute work concurrently.
Asynchronous Queues — asynchronous communication between threads.
Dynamic Loading of Modules — portable method for dynamically loading 'plug-ins'.
Memory Allocation — general memory-handling.
IO Channels — portable support for using files, pipes and sockets.
Error Reporting — a system for reporting errors.
Message Output and Debugging Functions — functions to output messages and help debug applications.
Message Logging — versatile support for logging messages with different levels of importance.
GLib Utilities
String Utility Functions — various string-related functions.
Character Set Conversion — convert strings between different character sets using iconv().
Unicode Manipulation — functions operating on Unicode characters and UTF-8 strings.
Base64 Encoding — encodes and decodes data in Base64 format
Internationalization — gettext support macros.
Date and Time Functions — calendrical calculations and miscellaneous time stuff.
Random Numbers — pseudo-random number generator.
Hook Functions — support for manipulating lists of hook functions.
Miscellaneous Utility Functions — a selection of portable utility functions.
Lexical Scanner — a general purpose lexical scanner.
Automatic String Completion — support for automatic completion using a group of target strings.
Timers — keep track of elapsed time.
Spawning Processes — process launching with fork()/exec().
File Utilities — various file-related functions.
Shell-related Utilities — shell-like commandline handling.
Commandline option parser — parses commandline options
Glob-style pattern matching — matches strings against patterns containing '*' (wildcard) and '?' (joker).
Simple XML Subset Parser — parses a subset of XML.
Key-value file parser — parses .ini-like config files
Bookmark file parser — parses files containing bookmarks
Windows Compatibility Functions — UNIX emulation on Windows.
GLib Data Types
Memory Slices — efficient way to allocate groups of equal-sized chunks of memory.
Memory Chunks — deprecated way to allocate groups of equal-sized chunks of memory.
Doubly-Linked Lists — linked lists containing integer values or pointers to data, with the ability to iterate over the list in both directions.
Singly-Linked Lists — linked lists containing integer values or pointers to data, limited to iterating over the list in one direction.
Double-ended Queues — double-ended queue data structure.
Trash Stacks — maintain a stack of unused allocated memory chunks.
Hash Tables — associations between keys and values so that given a key the value can be found quickly.
Strings — text buffers which grow automatically as text is added.
String Chunks — efficient storage of groups of strings.
Arrays — arrays of arbitrary elements which grow automatically as elements are added.
Pointer Arrays — arrays of pointers to any type of data, which grow automatically as new elements are added.
Byte Arrays — arrays of bytes, which grow automatically as elements are added.
Balanced Binary Trees — a sorted collection of key/value pairs optimized for searching and traversing in order.
N-ary Trees — trees of data with any number of branches.
Quarks — a 2-way association between a string and a unique integer identifier.
Keyed Data Lists — lists of data elements which are accessible by a string or GQuark identifier.
Datasets — associate groups of data elements with particular memory locations.
Relations and Tuples — tables of data which can be indexed on any number of fields.
Caches — caches allow sharing of complex data structures to save resources.
Memory Allocators — deprecated way to allocate chunks of memory for GList, GSList and GNode.
GLib Tools
glib-gettextize — gettext internationalization utility
Index
Index of deprecated symbols
Index of new symbols in 2.2
Index of new symbols in 2.4
Index of new symbols in 2.6
Index of new symbols in 2.8
Index of new symbols in 2.10
Index of new symbols in 2.12


GObject Reference Manual

for GLib 2.12.11

Introduction
I. Concepts
Background
Data types and programming
Exporting a C API
The Glib Dynamic Type System
Copy functions
Conventions
Non-Instantiable non-classed fundamental types
Instantiable classed types: objects
Non-instantiable classed types: Interfaces.
Interface Initialization
Interface Destruction
The GObject base class
Object instanciation
Object memory management
Reference count
Weak References
Reference counts and cycles
Object properties
Accessing multiple properties at once
The GObject messaging system
Closures
C Closures
non-C closures (for the fearless).
Signals
Signal registration
Signal connection
Signal emission
The detail argument
II. API Reference
GType — The GLib Runtime type identification and management system
GTypePlugin — An interface for dynamically loadable types
GTypeModule — Type loading modules
GObject — The base object type
Enums and Flags — Enumeration and flags types
GBoxed — A mechanism to wrap opaque C structures registered by the type system
Generic Values — A polymorphic type that can hold values of any other type
Parameters and Values — Standard Parameter and Value Types
Varargs Value Collection — Converting varargs to generic values
GParamSpec — Metadata for parameter specifications
Signals — A means for customization of object behaviour and a general purpose notification mechanism
Closures — Functions as first-class objects
Value arrays — A container structure to maintain an array of generic values
III. Tools Reference
glib-mkenums — C language enum description generation utility
glib-genmarshal — C code marshaller generation utility for GLib closures
gobject-query — display a tree of types
IV. Tutorial
How To define and implement a new GObject?
Boilerplate header code
Boilerplate code
Object Construction
Object Destruction
Object methods
Non-virtual public methods
Virtual public methods
Virtual private Methods
Chaining up
How To define and implement Interfaces?
How To define Interfaces?
How To define implement an Interface?
Interface definition prerequisites
Interface Properties
Howto create and use signals
Simple use of signals
How to provide more flexibility to users?
How most people do the same thing with less code
How users can abuse signals (and why some think it is good)
V. Related Tools
GObject builder
Graphical inspection of Gobjects
Debugging reference count problems
Writing API docs
Index
Index of deprecated symbols
Index of new symbols in 2.2
Index of new symbols in 2.4
Index of new symbols in 2.6
Index of new symbols in 2.8
Index of new symbols in 2.10
Index of new symbols in 2.12


Pango Reference Manual

for Pango 1.16.0

Table of Contents

Basic Pango Interfaces
Rendering - Functions to run the rendering pipeline
Glyph Storage - Structures for storing information about glyphs
Fonts - Structures representing abstract fonts
Text Attributes - Font and other attributes for annotating text
Tab Stops - Structures for storing tab stops
Text Attribute Markup - Simple markup language to encode text with attributes
Layout Objects - High-level layout driver objects
Scripts - Identifying writing systems
Vertical Text - Laying text out in vertical directions
Rendering with Pango
Win32 Fonts and Rendering - Functions for shape engines to manipulate Win32 fonts
FreeType Fonts and Rendering - Functions for shape engines to manipulate FreeType fonts
Xft Fonts and Rendering - Font handling and rendering with the Xft backend
Cairo Rendering - Rendering with the Cairo backend
ATSUI Fonts - Font handling and rendering with ATSUI fonts
Deprecated X font backend - Font handling and rendering with the deprecated X font backend
Low Level Functionality
PangoRenderer - Rendering driver base class
PangoFcFontMap - Base fontmap class for Fontconfig-based backends
PangoFcFont - Base font class for Fontconfig-based backends
PangoFcDecoder - Custom font encoding handling
OpenType Font Handling - Obtaining information from OpenType tables
Coverage Maps - Unicode character range coverage storage
Engines - Language-specific and rendering-system-specific processing
PangoEngineLang - Rendering-system independent script engines
PangoEngineShape - Rendering-system dependent script engines
Modules - Support for loadable modules
Miscellaneous Utilities - Various convenience and utility functions
Version Checking - Tools for checking Pango version at compile- and run-time.
Pango Tools
pango-querymodules - Module registration utility
Object Hierarchy
Index
Index of deprecated symbols
Index of new symbols in 1.2
Index of new symbols in 1.4
Index of new symbols in 1.6
Index of new symbols in 1.8
Index of new symbols in 1.10
Index of new symbols in 1.12
Index of new symbols in 1.14
Index of new symbols in 1.16


Cairo: A Vector Graphics Library

for Cairo 1.2.6

Table of Contents

I. Tutorial
II. Reference
Drawing
cairo_t - The cairo drawing context
Paths - Creating paths and manipulating path data
Patterns - Gradients and filtered sources
Transformations - Manipulating the current transformation matrix
Text - Rendering text and sets of glyphs
Fonts
cairo_font_face_t - Base class for fonts
Scaled Fonts - Caching metrics for a particular font size
Font Options - How a font should be rendered
FreeType Fonts - Font support for FreeType
Win32 Fonts - Font support for Microsoft Windows
Surfaces
cairo_surface_t - Base class for surfaces
Image Surfaces - Rendering to memory buffers
PDF Surfaces - Rendering PDF documents
PNG Support - Reading and writing PNG images
PostScript Surfaces - Rendering PostScript documents
Win32 Surfaces - Microsoft Windows surface support
SVG Surfaces - Rendering SVG documents
XLib Surfaces - X Window System rendering using XLib
Utilities
cairo_matrix_t - Generic matrix operations
Error handling - Decoding cairo's status
Version Information - Compile-time and run-time version checks.
Types - Generic data types used in the cairo API
Index
Index of new symbols in 1.2
A. Creating a language binding for cairo
General considerations
Memory Management
Multiple return values
Overloading and optional arguments
Streams and File I/O
Error handling
Patterns
Surfaces
Fonts
cairo_path_t


The gdk-pixbuf Library

Federico Mena Quintero

<federico@gimp.org>

Version 2.10.11

Copyright © 2000 The Free Software Foundation

Permission is granted to copy, distribute and/or modify this document under the terms of the GNU Free Documentation License, Version 1.1 or any later version published by the Free Software Foundation with no Invariant Sections, no Front-Cover Texts, and no Back-Cover Texts. You may obtain a copy of the GNU Free Documentation License from the Free Software Foundation by visiting their Web site or by writing to:

The Free Software Foundation, Inc.,
59 Temple Place - Suite 330,
Boston, MA 02111-1307,
USA

Many of the names used by companies to distinguish their products and services are claimed as trademarks. Where those names appear in any GNOME documentation, and those trademarks are made aware to the members of the GNOME Documentation Project, the names have been printed in caps or initial caps.

I. API Reference
Initialization and Versions — Library version numbers.
The GdkPixbuf Structure — Information that describes an image.
Reference Counting and Memory Mangement — Functions for reference counting and memory management on pixbufs.
File Loading — Loading a pixbuf from a file.
File saving — Saving a pixbuf to a file.
Image Data in Memory — Creating a pixbuf from image data that is already in memory.
Inline data — Functions for inlined pixbuf handling.
Scaling — Scaling pixbufs and scaling and compositing pixbufs
Rendering — Rendering a pixbuf to a GDK drawable.
Drawables to Pixbufs — Getting parts of a GDK drawable's image data into a pixbuf.
Utilities — Utility and miscellaneous convenience functions.
Animations — Animated images.
GdkPixbufLoader — Application-driven progressive image loading.
Module Interface — Extending gdk-pixbuf
gdk-pixbuf Xlib initialization — Initializing the gdk-pixbuf Xlib library.
Xlib Rendering — Rendering a pixbuf to an X drawable.
X Drawables to Pixbufs — Getting parts of an X drawable's image data into a pixbuf.
XlibRGB — Rendering RGB buffers to X drawables.
II. Tools Reference
gdk-pixbuf-csource — C code generation utility for GdkPixbuf images
gdk-pixbuf-query-loaders — GdkPixbuf loader registration utility
Index
Index of deprecated symbols
Index of new symbols in 2.2
Index of new symbols in 2.4
Index of new symbols in 2.6
Index of new symbols in 2.8
A. Porting applications from Imlib to gdk-pixbuf
Introduction
Differences between Imlib and gdk-pixbuf
Initialization
Memory management
The Rendering Process
Converting Applications to gdk-pixbuf
Image loading and creation
Rendering Images
Scaling Images
Getting Image Data from a Drawable
B. License


RSVG Reference Manual

I. RSVG Overview
II. Using RSVG
Core API —

Create and manipulate SVG objects

III. Using RSVG with Cairo
Cairo
IV. Using RSVG with GdkPixbuf
Rendering SVGs with GdkPixbuf —

How to render SVGs into GdkPixbufs, for easy use in GTK+ applications

Index


OpenGL/GLUT User Guide

OpenGL
(Open Graphics Library)

OpenGL Project Web Site
http://www.opengl.org/
Licence
Outline of OpenGL/GLUT
Template Programs


About the OpenGL Licence

The text of the licence for developers using OpenGL is reproduced below from the original.

Applications developers DO NOT need to license OpenGL.

If you are a software or applications developer, you do not need to license OpenGL. Generally, hardware vendors that are creating binaries to ship with their hardware, or software developers that write an OpenGL driver, are the only developers that need to have a license. If an application developer wants to use the OpenGL API, the developer needs to obtain copies of a linkable OpenGL library for a particular hardware device or machine. Those OpenGL libraries may be bundled with the development and/or run-time options or may be purchased from a third-party software vendor without licensing the source code or use of the OpenGL trademark.

For complete information on Licensing, see the SGI OpenGL Licensing Programs page.


Outline of OpenGL/GLUT

The official public website of the OpenGL project can be found at http://www.opengl.org/.

OpenGL (Open Graphics Library) was developed by Silicon Graphics Inc. (SGI) as a programming interface for 3D graphics. It also supports 2D graphics.

OpenGL is a cross-platform interface that can be used on UNIX workstations from many manufacturers such as HP, Sun, SGI, IBM, in addition to Apple Mac, Windows and PC UNIX such as Linux and FreeBSD.

GLUT (OpenGL Utility Toolkit) is a widely-used library that acts as a useful toolkit for OpenGL. GLUT was developed by Silicon Graphics Inc. (SGI) and Mark J. Kilgard.

In the Fortran Builder, using the NAG Fortran Compiler, it is possible to develop applications using OpenGL/GLUT in the Fortran language. Moreover, basic template programs showing the usage of OpenGL are supplied; these programs were prepared under the supervision of Professor Takeuchi of Hosei University.


OpenGL Template Programs

OpenGL01: Window creation.
OpenGL02: Drawing straight lines.
OpenGL03: Advanced line drawing.
OpenGL04: Drawing polygons.
OpenGL05: Contour shading.
OpenGL06: Viewport setting.
OpenGL07: 2D projection.
OpenGL08: 2D animation.
OpenGL09: Keyboard input.
OpenGL10: Mouse input.
OpenGL11: Orthogonal projection and geometric transformation.
OpenGL12: Orthogonal projection and view transformation.
OpenGL13: Perspective projection (1).
OpenGL14: Perspective projection (2).
OpenGL15: Filling polygons.
OpenGL16: Culling filled polygons.
OpenGL17: Lighting.
OpenGL18: Shading.
OpenGL19: Surface property (material characteristics).
OpenGL20: Texture mapping.
OpenGL21: 3D animation.


OpenGL01: Window creation program

Window Creation Program

! ===== Window Creation Program =====< OpenGL01.f95>
MODULE myOpenGL

  USE opengl_gl      ! GL  (OpenGL Core library)
  USE opengl_glu     ! GLU (OpenGL Utility library)
  USE opengl_glut    ! GLUT(OpenGL Utility Toolkit)

 !-------
 CONTAINS
 !-------

  !< Window Creation >----------

  SUBROUTINE myWindow

    INTEGER :: win

    CALL glutInitDisplayMode(GLUT_RGBA)     ! Set the display mode.
    CALL glutInitWindowPosition(100, 200)   ! Window position from top left in pixels.
    CALL glutInitWindowSize(640, 480)       ! Window size (width, height) in pixels.
    win = glutCreateWindow("OpenGL Window") ! Create the window.
    CALL glClearColor(1.0,1.0,1.0,1.0)      ! Set the window fill colour (red,green,blue,alpha).

  END SUBROUTINE myWindow

  !< Draw the (contents of) the window >----------

  SUBROUTINE myDisplay

    CALL glClear(GL_COLOR_BUFFER_BIT)  ! Fill window with the set colour.
    CALL glFlush                       ! Actually do it.

  END SUBROUTINE myDisplay

END MODULE myOpenGL
!==================================
!========== Main Program ==========
PROGRAM main

  USE myOpenGL                     ! Our own module.

  CALL glutInit                    ! Initialise GLUT library.
  CALL myWindow                    ! Create our window.
  CALL glutDisplayFunc(myDisplay)  ! Use myDisplay to draw the window.
  CALL glutMainLoop                ! Run the main event loop.

END PROGRAM main
!==================================

opengl_gl, opengl_glu, opengl_glut
To use OpenGL commands, it is necessary to USE these modules:
opengl_gl | — is the OpenGL core library;
opengl_glu | — is the OpenGL Utility library;
opengl_glut | — is the OpenGL Utility Toolkit library.
Subroutine glutInit
It is necessary to CALL this first, to initialise the GLUT library.
Subroutine glutInitDisplayMode(mode)
Integer(glcuint),Intent(In) :: mode
Set the display mode (GLUT_RGBA is the default value).
Integer(glcuint),Parameter :: GLUT_RGBA ! (default)
Mode setting that the colour can be specified with RGB (Red, Green and Blue) values. There are other modes available; these are not described here.
Subroutine glutInitWindowPosition(x0,y0)
Integer(glcint),Intent(In) :: x0,y0
Screen coordinates of the upper left corner of the window, expressed as the number of pixels to the right of (x0) and down from (y0) the top left corner of the screen; this is depicted in the diagram below. Note that this is the actual user window corner position, ignoring any window manager decoration.
Subroutine glutInitWindowSize(width,height)
Integer(glcint),Intent(in) :: width,height
Set the size of the window in pixels; this is depicted in the diagram above.
Subroutine glutCreateWindow(title)
Character(*),Intent(In) :: title
Creates the window.
Subroutine glClearColor(red,green,blue,alpha)
Real(glclampf),Intent(In) :: red,green,blue,alpha
Sets the colour specification that will be used to fill the window when it is cleared (with glClear); values should be in the range 0.0 to 1.0. Alpha is the transparency, 0 = fully transparent, 1 = fully opaque.
Subroutine glutDisplayFunc(displayfunc)
Interface
  Subroutine displayfunc
  End Subroutine
End Interface
Sets the procedure that will be used to (re)draw the window, for example when it becomes visible.
Subroutine glClear(mask)
Integer(glbitfield),Intent(In) :: masj
Clear the window (by painting it with the colour specification set by glClearColor). The mask argument controls the action as detailed below.
Integer(glbitfield),Parameter :: GL_COLOR_BUFFER_BIT
Only clear the colour buffer, not the window.
Subroutine glFlush
Execute all pending OpenGL commands. Most OpenGL commands are buffered; this routine needs to be called to make their effects visible.
Subroutine glutMainLoop
Runs the main GLUT event loop. This loop receives all window events and calls the appropriate routine (e.g. the display procedure set by glutDisplayFunc) to handle them.

The result of executing OpenGL_01.f95:

Kind values

The values used for the OpenGL/GLUT kinds mentioned above are as follows.
Integer,Parameter :: glcbitfield = int32
Integer,Parameter :: glcint = int32
Integer,Parameter :: glclampf = real32
Integer,Parameter :: glcuint = int32


OpenGL02: Straight line drawing program

Straight Line Drawing Program

!===== Straight Line Drawing Program =====< OpenGL02.f95>
MODULE myOpenGL

  USE opengl_gl      ! GL  (OpenGL Core library)
  USE opengl_glu     ! GLU (OpenGL Utility library)
  USE opengl_glut    ! GLUT(OpenGL Utility Toolkit)

 !-------
 CONTAINS
 !-------

  !< Window Creation >----------

  SUBROUTINE myWindow

    INTEGER :: win

    CALL glutInitDisplayMode(GLUT_RGBA)     ! Set the display mode.
    CALL glutInitWindowPosition(100, 200)   ! Window position from top left in pixels.
    CALL glutInitWindowSize(640, 480)       ! Window size (width, height) in pixels.
    win = glutCreateWindow("OpenGL Window") ! Create the window.
    CALL glClearColor(1.0,1.0,1.0,1.0)      ! Set the window fill colour (red,green,blue,alpha).

  END SUBROUTINE myWindow

  !< Draw the window. >----------

  SUBROUTINE myDisplay

    CALL glClear(GL_COLOR_BUFFER_BIT)  ! Fill the window with the set colour.
    CALL myLine                        ! Draw the line.
    CALL glFlush                       ! Actually do it.

  END SUBROUTINE myDisplay

  !< Draw some lines. >----------

  SUBROUTINE myLine

    INTEGER(2) :: pat(2)
    DATA pat/z'00ff',z'1c47'/    ! Wavy line pattern (wavy line and one-point wany line).

    CALL glColor3f(1.0,0.0,0.0)  ! Set drawing colour (Red,Green,Blue) to Red.
    y = 0.5
    DO i = 1, 4
      y = y - 0.2
      CALL glLineWidth(REAL(i*2))    ! Set line width.
      CALL glBegin(GL_LINES)         ! Begin drawing a straight line between two points.
        CALL glVertex2f(-0.5,y)        ! Starting point.
        CALL glVertex2f(-0.1,y)        ! Ending point.
      CALL glEnd                     ! End drawing that line.
    END DO

    CALL glColor3f(0.0,0.0,1.0)      ! Set drawing colour to Blue.
    CALL glLineWidth(1.0)            ! Set line width.
    CALL glEnable(GL_LINE_STIPPLE)   ! Enable wavy line.
    y = 0.5
    DO i = 1, 2
      DO j = 1, 2
        y = y - 0.2
        CALL glLineStipple(j,pat(i)) ! Set the wavy line pattern.
        CALL glBegin(GL_LINES)       ! Begin drawing a straight line between two points.
          CALL glVertex2f(0.1,y)       ! Starting position.
          CALL glVertex2f(0.5,y)       ! Ending position.
        CALL glEnd                   ! End drawing that line.
      END DO
    END DO
    CALL glDisable(GL_LINE_STIPPLE)  ! Disable wavy line.

  END SUBROUTINE myLine

END MODULE myOpenGL
!==================================
!========== Main Program ==========
PROGRAM main

  USE myOpenGL                     ! Access our module.

  CALL glutInit                    ! Initialise GLUT library.
  CALL myWindow                    ! Create our window.
  CALL glutDisplayFunc(myDisplay)  ! Use myDisplay to draw the window.
  CALL glutMainLoop                ! Run the main event loop.

END PROGRAM main
!==================================

The program sections coloured in green are described below; for OpenGL/GLUT calls in the black portion of the program, refer to the preceding template program's documentation.

Subroutine glColor3f(red,green,blue)
Real(glfloat),Intent(In) :: red,green,blue
Sets the colour used for drawing shapes (including lines). The colour component values must be in the range 0.0 to 1.0. Note that the colour can also be set by glColor3d and glColor3i.
Subroutine glLineWidth(width)
Real(glfloat),Intent(In) :: width
Sets the width of the line when drawing, in pixels; the default value is one pixel. Note however that the width of the line will be thickened if the display resolution is very low.
Subroutine glEnable(cap)
Integer(glenum),Intent(In) :: cap
Enables the specified capability. For cap equal to GL_LINE_STIPPLE, wavy line processing is enabled.
Subroutine glDisable(cap)
Integer(glenum),Intent(In) :: cap
Disables the specified capability. For cap equal to GL_LINE_STIPPLE, wavy line processing is disabled.
Subroutine glLineStipple(factor,pattern)
Integer(glint),Intent(In) :: factor
Integer(glushort),Intent(In) :: pattern
Sets the pattern to be used for drawing wavy lines; by default, a plain straight line is drawn. The value of pattern is treated as a sequence of 16 bits; each bit of the pattern is repeated factortimes. When the line is drawn on the screen, only those bits of the line that correspond to 1 bits in the pattern are drawn.
Subroutine glBegin(mode)
Integer(glenum),Intent(In) :: mode
Begin drawing the data (about to be supplied) in the specified mode. A mode of GL_LINES specifies drawing lines.
Subroutine glEnd
Ends the drawing begun by glBegin.
Subroutine glVertex2f(x,y)
Real(glfloat),Intent(In) :: x,y
Supplies data point at (x,y), where x and y have values in the range -1.0 to 1.0, with the meaning shown in the diagram below. Note that these ranges apply even if the aspect ratio (width/height) is not 1, so care must be taken to avoid distorting the picture. In GL_LINES mode, a line is drawn between each successive pair of data points, i.e. between data points 1 and 2, 3 and 4, etc.. Data points can also be supplied using glVertex2d (for double precision) and glVertex2i (for integer values).

The result of executing OpenGL_02.f95:

Red and blue, solid and dashed, lines

Kind values

The values used for the OpenGL/GLUT kinds mentioned above are as follows.
Integer,Parameter :: glenum = int32
Integer,Parameter :: glfloat = real32
Integer,Parameter :: glint = int32
Integer,Parameter :: glushort = int16


OpenGL03: Advanced line drawing program

Advanced Line Drawing Program

!===== Advanced Line Drawing Program =====< OpenGL03.f95>
MODULE myOpenGL

  USE opengl_gl      ! GL  (OpenGL Core library)
  USE opengl_glu     ! GLU (OpenGL Utility library)
  USE opengl_glut    ! GLUT(OpenGL Utility Toolkit)

 !-------
 CONTAINS
 !-------

  !< Window Creation >----------

  SUBROUTINE myWindow

    INTEGER :: win

    CALL glutInitDisplayMode(GLUT_RGBA)     ! Set the display mode.
    CALL glutInitWindowPosition(100, 200)   ! Window position from top left in pixels.
    CALL glutInitWindowSize(640, 480)       ! Window size (width, height) in pixels.
    win = glutCreateWindow("OpenGL Window") ! Create the window.
    CALL glClearColor(1.0,1.0,1.0,1.0)      ! Set window fill colour (R,G,B,alpha).

  END SUBROUTINE myWindow

  !< Draw the window. >----------

  SUBROUTINE myDisplay

    CALL glClear(GL_COLOR_BUFFER_BIT)  ! Fill the window with the set colour.
    CALL myPolygonalLine               ! Draw multiple lines.
    CALL glFlush                       ! Actually do it.

  END SUBROUTINE myDisplay

  !< Draw some tangents. >----------

  SUBROUTINE myPolygonalLine

    CALL glColor3f(1.0,0.0,0.0)  ! Set drawing colour (RGB) to Red.
    CALL glBegin(GL_LINES)       ! Begin drawing straight lines.
      CALL glVertex2f(0.0,0.0)     ! Starting point.
      CALL glVertex2f(1.0,1.0)     ! Ending point.
    CALL glEnd                   ! End drawing that line.

    CALL glColor3f(0.0,1.0,0.0)  ! Set drawing colour (RGB) to Green.
    CALL glBegin(GL_LINE_STRIP)  ! Begin drawing connected lines.
      CALL glVertex2f( 0.0,0.0)    ! Starting point.
      CALL glVertex2f(-0.5,0.0)    ! Middle point (multiple connected lines).
      CALL glVerTex2f(-0.5,0.5)    ! Ending point.
    CALL glEnd                   ! End drawing those lines.

    CALL glColor3f(0.0,0.0,1.0)  ! Set drawing colour (RGB) to Blue.
    CALL glBegin(GL_LINE_LOOP)   ! Begin drawing a polygon (the ending point will
                                 ! also have a line drawn to the starting point).
      CALL glVertex2f( 0.0, 0.0)   ! Starting point.
      CALL glVertex2f(-0.5,-0.5)   ! Middle point (multiple points acceptable).
      CALL glVertex2f( 0.0,-0.5)   ! Ending point.
    CALL glEnd                   ! End drawing the polygon.

  END SUBROUTINE myPolygonalLine

END MODULE myOpenGL
!==================================
!========== Main Program ==========
PROGRAM main

  USE myOpenGL                     ! Access our module.

  CALL glutInit                    ! Initialise the GLUT library.
  CALL myWindow                    ! Create our window.
  CALL glutDisplayFunc(myDisplay)  ! Use myDisplay to draw the window.
  CALL glutMainLoop                ! Run the main event loop.

END PROGRAM main
!==================================

The program sections coloured in green are described below; for OpenGL/GLUT calls in the black portion of the program, refer to the preceding template program's documentation.

Subroutine glBegin(mode)
Integer(glenum),Intent(In) :: mode
Begin drawing the data (about to be supplied) in the specified mode as follows.
GL_POINTS
Draw a point at the position of each data point.
GL_LINES
Draw a line between each successive pair of points.
GL_LINE_STRIP
Draw a line from each point to the next point in sequence (stopping at the end).
GL_LINE_LOOP
Draw a line from each point to the next point in sequence, plus a line from the last point to the first point.
These modes are illustrated by the diagram below.
Subroutine glEnd
Ends the drawing begun by glBegin.
Subroutine glVertex2f(x,y)
Real(glfloat),Intent(In) :: x,y
Supplies data point at (x,y), where x and y have values in the range -1.0 to 1.0, with the meaning shown in the diagram below. Note that these ranges apply even if the aspect ratio (width/height) is not 1, so care must be taken to avoid distorting the picture. Data points can also be supplied using glVertex2d (for double precision) and glVertex2i (for integer values).

The result of executing OpenGL_03.f95:

Blue triangle, red line, green bent line

The origin is located at the point where the triangle and the red and green lines touch.

Kind values

The values used for the OpenGL/GLUT kinds mentioned above are as follows.
Integer,Parameter :: glenum = int32
Integer,Parameter :: glfloat = real32


OpenGL04: Polygon drawing program

Polygon Drawing Program

!===== Polygon Drawing Program =====< OpenGL04.f95>
MODULE myOpenGL

  USE opengl_gl      ! GL  (OpenGL Core library)
  USE opengl_glu     ! GLU (OpenGL Utility library)
  USE opengl_glut    ! GLUT(OpenGL Utility Toolkit)

 !-------
 CONTAINS
 !-------

  !< Window Creation >----------

  SUBROUTINE myWindow

    INTEGER :: win

    CALL glutInitDisplayMode(GLUT_RGBA)     ! Set the display mode.
    CALL glutInitWindowPosition(100, 200)   ! Window position from top left in pixels.
    CALL glutInitWindowSize(640, 480)       ! Window size (width, height) in pixels.
    win = glutCreateWindow("OpenGL Window") ! Create the window.
    CALL glClearColor(1.0,1.0,1.0,1.0)      ! Set window fill colour (R,G,B,alpha).

  END SUBROUTINE myWindow

  !< Draw the window. >----------

  SUBROUTINE myDisplay

    CALL glClear(GL_COLOR_BUFFER_BIT)  ! Fill the window with the set colour.
    CALL myPolygon                     ! Draw polygons.
    CALL glFlush                       ! Actually do it.

  END SUBROUTINE myDisplay

  !< Draw some polygons. >----------

  SUBROUTINE myPolygon

    CALL glColor3f(1.0,0.0,0.0)           ! Set drawing colour (RGB) to Red.

    CALL glPolygonMode(GL_FRONT, GL_FILL) ! Fill the front surface of the polygon.
    CALL glPolygonMode(GL_BACK,  GL_LINE) ! The back surface is just an outline.

    CALL glBegin(GL_TRIANGLES)            ! Begin drawing triangle: anticlockwise.
      CALL glVertex2f(0.0,0.0)              ! First corner.
      CALL glVertex2f(0.5,0.0)              ! Second corner.
      CALL glVertex2f(0.5,0.5)              ! Third corner.
    CALL glEnd                            ! Finished drawing that triangle.

    CALL glBegin(GL_TRIANGLES)            ! Begin drawing triangle: clockwise.
      CALL glVertex2f( 0.0,0.0)             ! First corner.
      CALL glVertex2f(-0.5,0.0)             ! Second corner.
      CALL glVertex2f(-0.5,0.5)             ! Third corner.
    CALL glEnd                            ! Finished drawing that triangle.

    CALL glColor3f(0.0,1.0,0.0)           ! Set drawing colour to Green.
    CALL glBegin(GL_QUADS)                ! Draw a quadrilateral, anticlockwise.
      CALL glVertex2f(0.1,-0.5)             ! First corner.
      CALL glVertex2f(0.5,-0.5)             ! Second corner.
      CALL glVertex2f(0.5,-0.1)             ! Third corner.
      CALL glVertex2f(0.1,-0.1)             ! Fourth corner.
    CALL glEnd                            ! Finished drawing that quadrilateral.

    CALL glColor3f(0.0,0.0,1.0)           ! Set drawing colour to Blue.
    CALL glBegin(GL_TRIANGLE_FAN)         ! Draw a quadrilateral, anticlockwise.
      CALL glVertex2f(-0.5,-0.5)            ! First corner.
      CALL glVertex2f(-0.1,-0.5)            ! Second corner.
      CALL glVertex2f(-0.1,-0.1)            ! Third corner.
      CALL glVertex2f(-0.5,-0.1)            ! Fourth corner.
    CALL glEnd                            ! Finished drawing.

  END SUBROUTINE myPolygon

END MODULE myOpenGL
!==================================
!========== Main Program ==========
PROGRAM main

  USE myOpenGL                     ! Access our module.

  CALL glutInit                    ! Initialise the GLUT library.
  CALL myWindow                    ! Create our window.
  CALL glutDisplayFunc(myDisplay)  ! Use myDisplay to draw the window.
  CALL glutMainLoop                ! Run the main event loop.

END PROGRAM main
!==================================

The program sections coloured in green are described below; for OpenGL/GLUT calls in the black portion of the program, refer to the preceding template program's documentation.

Subroutine glPolygonMode(face,mode)
Integer(glenum),Intent(In) :: face,mode
Set the polygon rasterisation mode. If face is
GL_FRONT, the setting is for front-facing (anti-clockwise) polygons;
GL_BACK, the setting is for back-facing (clockwise) polygons; GL_FRONT_AND_BACK, the setting is for both front and back-facing polygons.
The following diagram illustrates the concepts of front-facing and back-facing.

The available modes are
GL_POINT: each vertex is drawn as a point;
GL_LINE: each edge is drawn as a line;
GL_FILL: the polygon is filled.
The default is GL_FILL.
Subroutine glBegin(mode)
Integer(glenum),Intent(In) :: mode
Begin drawing the data (about to be supplied) in the specified mode as follows.
GL_TRIANGLES
Draws a triangle for each three consecutive data points.
GL_QUADS
Draws a quadrilateral for each four consecutive data points.
GL_POLYGON
Draws a single polygon.
GL_TRIANGLE_FAN
Draws a set of triangles fanning out from the first data point, i.e. a triangle is drawn starting from the first data point for each consecutive pair of data points following.
GL_TRIANGLE_STRIP
Draws a set of triangles connected along the edges; i.e. after the first triangle, each additional data point draws a triangle that combines it and the previous two data points.
GL_QUAD_STRIP
Draws a set of quadrilaterals connected along the edges; i.e. after the first quadrilateral, each additional two data points draws a quadrilateral that combines those and the previous two data points.
These modes are illustrated by the diagram below.

The result of executing OpenGL_04.f95:

Red triangles, blue and green rectangles

Kind values

The values used for the OpenGL/GLUT kinds mentioned above are as follows.
Integer,Parameter :: glenum = int32


OpenGL05: Contour shading program

Contour shading Program

!===== Contour Shading Program =====< OpenGL05.f95>
MODULE myOpenGL

  USE opengl_gl      ! GL  (OpenGL Core library)
  USE opengl_glu     ! GLU (OpenGL Utility library)
  USE opengl_glut    ! GLUT(OpenGL Utility Toolkit)

 !-------
 CONTAINS
 !-------

  !< Window Creation >----------

  SUBROUTINE myWindow

    INTEGER :: win

    CALL glutInitDisplayMode(GLUT_RGBA)     ! Set the display mode.
    CALL glutInitWindowPosition(100, 200)   ! Window position from top left in pixels.
    CALL glutInitWindowSize(640, 480)       ! Window size (width, height) in pixels.
    win = glutCreateWindow("OpenGL Window") ! Create the window.
    CALL glClearColor(1.0,1.0,1.0,1.0)      ! Set window fill colour (R,G,B,alpha).

  END SUBROUTINE myWindow

  !< Draw the window. >----------

  SUBROUTINE myDisplay

    CALL glClear(GL_COLOR_BUFFER_BIT)  ! Fill the window with the set colour.
    CALL myContour                     ! Draw colour-shaded contour.
    CALL glFlush                       ! Actually do it.

  END SUBROUTINE myDisplay

  !< Draw a contour, shaded. >----------

  SUBROUTINE myContour

    CALL glBegin(GL_TRIANGLES)             ! Begin drawing a triangle, anticlockwise.
      CALL glColor3f(1.0,0.0,0.0)            ! Set drawing colour to Red.
      CALL glVertex2f(0.0,0.0)               ! First corner.
      CALL glColor3f(0.0,1.0,0.0)            ! Set drawing colour to Green.
      CALL glVertex2f(0.5,0.0)               ! Second corner.
      CALL glColor3f(0.0,0.0,1.0)            ! Set drawing colour to Blue.
      CALL glVertex2f(0.5,0.5)               ! Third corner.
    CALL glEnd                             ! Finished drawing the triangle.

  END SUBROUTINE myContour

END MODULE myOpenGL
!==================================
!========== Main Program ==========
PROGRAM main

  USE myOpenGL                     ! Access our module.

  CALL glutInit                    ! Initialise the GLUT library.
  CALL myWindow                    ! Create our window.
  CALL glutDisplayFunc(myDisplay)  ! Use myDisplay to draw the window.
  CALL glutMainLoop                ! Run the main event loop.

END PROGRAM main
!==================================

The program sections coloured in green draw a polygon, with each vertex set to a different colour (red, green and blue respectively). When the polygon is filled, the rasterisation algorithm will create a smooth colour transition between those fixed points.

The result of executing OpenGL_05.f95:


OpenGL06: Viewport setting program

Viewport Setting Program

!===== Viewport Setting Program =====< OpenGL06.f95>
MODULE myOpenGL

  USE opengl_gl      ! GL  (OpenGL Core library)
  USE opengl_glu     ! GLU (OpenGL Utility library)
  USE opengl_glut    ! GLUT(OpenGL Utility Toolkit)

 !-------
 CONTAINS
 !-------

  !< Window Creation >----------

  SUBROUTINE myWindow

    INTEGER :: win

    CALL glutInitDisplayMode(GLUT_RGBA)     ! Set the display mode.
    CALL glutInitWindowPosition(100, 200)   ! Window position from top left in pixels.
    CALL glutInitWindowSize(640, 480)       ! Window size (width, height) in pixels.
    win = glutCreateWindow("OpenGL Window") ! Create the window.
    CALL glClearColor(1.0,1.0,1.0,1.0)      ! Set window fill colour (R,G,B,alpha).

  END SUBROUTINE myWindow

  !< Window Resize Handler >----------

  SUBROUTINE myResize(w, h)

    INTEGER, INTENT(INOUT) :: w, h      ! Current window width and height in pixels.

    CALL glViewport(100, 100, 300, 300) ! Set viewport (in pixels).

  END SUBROUTINE myResize

  !< Draw the window. >----------

  SUBROUTINE myDisplay

    CALL glClear(GL_COLOR_BUFFER_BIT)  ! Fill the window with the set colour.
    CALL myPicture                     ! Draw a picture.
    CALL glFlush                       ! Actually do it.

  END SUBROUTINE myDisplay

  !< Draw a picture. >----------

  SUBROUTINE myPicture

    CALL glColor3f(1.0,0.0,0.0)            ! Set drawing colour to Red.
    CALL glBegin(GL_TRIANGLES)             ! Begin drawing a triangle.
      CALL glVertex2f(0.0,0.0)               ! First corner.
      CALL glVertex2f(0.5,0.0)               ! Second corner.
      CALL glVertex2f(0.5,0.5)               ! Third corner.
    CALL glEnd                             ! Finished drawing the triangle.

  END SUBROUTINE myPicture

END MODULE myOpenGL
!==================================
!========== Main Program ==========
PROGRAM main

  USE myOpenGL                     ! Access our module.

  CALL glutInit                    ! Initialise the GLUT library.
  CALL myWindow                    ! Create our window.
  CALL glutReshapeFunc(myResize)   ! Use myResize to handle window size changes.
  CALL glutDisplayFunc(myDisplay)  ! Use myDisplay to draw the window.
  CALL glutMainLoop                ! Run the main event loop.

END PROGRAM main
!==================================

The program sections coloured in green are described below; for OpenGL/GLUT calls in the black portion of the program, refer to the previous template programs' documentation.

Subroutine glutReshapeFunc(reshapefunc)
Interface
  Subroutine reshapefunc(width,height)
  Use opengl_kinds
  Integer(glcint),Intent(InOut) :: width,height
  End Subroutine
End Interface
Sets the reshape handler for the current window. The reshape handler procedure will be called after the window is created, whenever the window is resized, or whenever an overlay for the window is established. On entry, width and height are set to the new sizes of the window in pixels; changing these values has no effect.
Subroutine glViewport(x,y,width,height)
Integer(glint),Intent(In) :: x,y
Integer(glsizei),Intent(In) :: width,height
Sets the viewport; x and y specify the lower left corner of the viewport rectangle in pixels; width and height specify the size of the viewport in pixels. The default is for the viewport to be the whole window. The viewport affects the affine transformation from normalised device coordinates to window coordinates as follows.

The result of executing OpenGL_06.f95:

Kind values

The values used for the OpenGL/GLUT kinds mentioned above are as follows.
Integer,Parameter :: glint = int32
Integer,Parameter :: glsizei = int32


OpenGL07: 2D projection program

2D Projection Program

!===== 2D Projection Program =====< OpenGL07.f95>
MODULE myOpenGL

  USE opengl_gl      ! GL  (OpenGL Core library)
  USE opengl_glu     ! GLU (OpenGL Utility library)
  USE opengl_glut    ! GLUT(OpenGL Utility Toolkit)

 !-------
 CONTAINS
 !-------

  !< Window Creation >----------

  SUBROUTINE myWindow

    INTEGER :: win

    CALL glutInitDisplayMode(GLUT_RGBA)     ! Set the display mode.
    CALL glutInitWindowPosition(100, 200)   ! Window position from top left in pixels.
    CALL glutInitWindowSize(640, 480)       ! Window size (width, height) in pixels.
    win = glutCreateWindow("OpenGL Window") ! Create the window.
    CALL glClearColor(1.0,1.0,1.0,1.0)      ! Set window fill colour (R,G,B,alpha).

  END SUBROUTINE myWindow

  !< Window Resize Handler >----------

  SUBROUTINE myResize(w, h)

    INTEGER, INTENT(INOUT) :: w, h         ! Current window width and height in pixels.

    CALL glViewport(100, 100, 300, 300)    ! Set viewport (in pixels).
    CALL glLoadIdentity                    ! Initialise transformation matrix.
    CALL gluOrtho2D(0.D0,10.D0,0.D0,10.D0) ! Project these 2D coordinates onto the screen.

  END SUBROUTINE myResize

  !< Draw the window. >----------

  SUBROUTINE myDisplay

    CALL glClear(GL_COLOR_BUFFER_BIT)  ! Fill the window with the set colour.
    CALL myPicture                     ! Draw a picture.
    CALL glFlush                       ! Actually do it.

  END SUBROUTINE myDisplay

  !< Draw a picture. >----------

  SUBROUTINE myPicture

    CALL glColor3f(1.0,0.0,0.0)            ! Set drawing colour to Red.
    CALL glBegin(GL_TRIANGLES)             ! Begin drawing a triangle.
      CALL glVertex2f(0.0,0.0)               ! First corner in world coordinates.
      CALL glVertex2f(5.0,0.0)               ! Second corner in world coordinates.
      CALL glVertex2f(5.0,5.0)               ! Third corner in world coordinates.
    CALL glEnd                             ! Finished drawing the triangle.

  END SUBROUTINE myPicture

END MODULE myOpenGL
!==================================
!========== Main Program ==========
PROGRAM main

  USE myOpenGL                     ! Access our module.

  CALL glutInit                    ! Initialise the GLUT library.
  CALL myWindow                    ! Create our window.
  CALL glutReshapeFunc(myResize)   ! Use myResize to handle window size changes.
  CALL glutDisplayFunc(myDisplay)  ! Use myDisplay to draw the window.
  CALL glutMainLoop                ! Run the main event loop.

END PROGRAM main
!==================================

The program sections coloured in green are described below; for OpenGL/GLUT calls in the black portion of the program, refer to the previous template programs' documentation.

Subroutine glLoadIdentity
Sets the current transformation matrix to the identity matrix.
Subroutine gluOrtho2D(left,right,bottom,top)
Real(gldouble),Intent(In) :: left,right,bottom,top
Applies a 2D orthographic projection to the current transformation matrix; left, right, bottom and top specify the coordinates of the two vertical and two horizontal clipping planes. The effect of this projection is illustrated in the following diagram.

After the projection has been defined, calls to draw on the window will use the world coordinates, not the device coordinates.

The result of executing OpenGL_07.f95:

Kind values

The values used for the OpenGL/GLUT kinds mentioned above are as follows.
Integer,Parameter :: gldouble = real64


OpenGL08: 2D animation program

2D Animation Program

!===== 2D Animation Program =====< OpenGL08.f95>
MODULE myOpenGL

  USE opengl_gl      ! GL  (OpenGL Core library)
  USE opengl_glu     ! GLU (OpenGL Utility library)
  USE opengl_glut    ! GLUT(OpenGL Utility Toolkit)

 !-------
 CONTAINS
 !-------

  !< Window Creation >----------

  SUBROUTINE myWindow

    INTEGER :: win

    CALL glutInitDisplayMode(ior(GLUT_RGBA, GLUT_DOUBLE)) ! Set the display mode; double-buffered.
    CALL glutInitWindowPosition(10, 10)     ! Window position from top left in pixels.
    CALL glutInitWindowSize(500, 500)       ! Window size (width, height) in pixels.
    win = glutCreateWindow("OpenGL Window") ! Create the window.
    CALL glClearColor(1.0,1.0,1.0,1.0)      ! Set the window fill colour (red,green,blue,alpha).

  END SUBROUTINE myWindow

  !< Processing when there is nothing else to do. >----------

  SUBROUTINE myIdle

    CALL glutPostRedisplay  ! Issue a redraw event.

  END SUBROUTINE myIdle

  !< Draw the window. >----------

  SUBROUTINE myDisplay

    CALL glClear(GL_COLOR_BUFFER_BIT)  ! Fill the window with the set colour.
    CALL myAnimation                   ! Draw animation.
    CALL glutSwapBuffers               ! Double-buffering buffer swap.

  END SUBROUTINE myDisplay

  !< Draw an animation. >----------

  SUBROUTINE myAnimation

    REAL :: y = 0.
    REAL :: dy = 0.01

    y = y + dy
    CALL glColor3f(1.0, 0.0, 0.0)      ! Set drawing colour to Red.
    CALL glPointSize(10.0)             ! Set point size.
    CALL glBegin(GL_POINTS)            ! Start drawing points.
      CALL glVertex2f(0.,y)            ! Draw one point.
    CALL glEnd                         ! Finished drawing points.

    IF(y > 1.0) THEN
      dy = -0.01
     ELSE IF(y < -1) THEN
      dy = 0.01
    END IF

  END SUBROUTINE myAnimation

END MODULE myOpenGL
!==================================
!========== Main Program ==========
PROGRAM main

  USE myOpenGL                     ! Access our module.

  CALL glutInit                    ! Initialise the GLUT library.
  CALL myWindow                    ! Create our window.
  CALL glutIdleFunc(myIdle)        ! Set idle loop function, called when there is nothing else to do.
  CALL glutDisplayFunc(myDisplay)  ! Use myDisplay to draw the window.
  CALL glutMainLoop                ! Run the main event loop.

END PROGRAM main
!==================================

The program sections coloured in green are described below; for OpenGL/GLUT calls in the black portion of the program, refer to the previous template programs' documentation.

Subroutine glutIdleFunc(idlefunc)
Interface
  Subroutine idlefunc
  End Subroutine
End Interface
Sets the idle function handler; this subroutine is repeatedly called as long as there are no window events to handle.
Subroutine glutPostRedisplay
Adds a “display window” event to the event queue, causing the current window to be redrawn.
Subroutine glutInitDisplayMode(mode)
Integer(glcuint),Intent(In) :: mode
Sets the initial display mode to be used for subsequently creahed windows; mode is a bit mask, the intrinsic function IOR should be used to combine multiple bits. Relevant bits for this program are
GL_RGBA: set the display mode to RGBA (default);
GL_DOUBLE: make the window double-buffered (the default is single).
Subroutine glutSwapBuffers
Swaps the buffers of the current window (if it is double-buffered), making everything drawn since the last buffer swap visible. Usually, the buffer swap occurs during the display's “vertical retrace”; this gives better quality than modifying the buffer during display, but limits the speed of the animation to the display's refresh rate (typically around 60Hz).

The result of executing OpenGL_08.f95:

Bouncing red dot

Kind values

The values used for the OpenGL/GLUT kinds mentioned above are as follows.
Integer,Parameter :: glcuint = int32


OpenGL09: Keyboard input program

Keyboard Input Program

!===== Keyboard Input Program =====< OpenGL09.f95>
MODULE myOpenGL

  USE opengl_gl      ! GL  (OpenGL Core library)
  USE opengl_glu     ! GLU (OpenGL Utility library)
  USE opengl_glut    ! GLUT(OpenGL Utility Toolkit)

 !-------
 CONTAINS
 !-------

  !< Window Creation >----------

  SUBROUTINE myWindow

    INTEGER :: win

    CALL glutInitDisplayMode(ior(GLUT_RGBA, GLUT_DOUBLE)) ! Set the display mode; double-buffered.
    CALL glutInitWindowPosition(10, 10)     ! Window position from top left in pixels.
    CALL glutInitWindowSize(500, 500)       ! Window size (width, height) in pixels.
    win = glutCreateWindow("OpenGL Window") ! Create the window.
    CALL glClearColor(1.0,1.0,1.0,1.0)      ! Set the window fill colour (red,green,blue,alpha).

  END SUBROUTINE myWindow

  !< Keyboard Input Event Handler >----------

  SUBROUTINE myKeyboard(ikey, x, y)

    INTEGER, INTENT(INOUT) :: ikey, x, y
    CHARACTER(LEN=1)       :: ckey

    ckey = CHAR(ikey)

    SELECT CASE (ckey)

      CASE ("q","Q")
        CALL glutIdleFunc(glutnullfunc)  ! Stop the animation.

      CASE (char(27))                    ! ESC key.
        STOP                             ! Terminate job.

    END SELECT

  END SUBROUTINE myKeyboard

  !< Processing when there is nothing else to do. >----------

  SUBROUTINE myIdle

    CALL glutPostRedisplay  ! Issue a redraw event.

  END SUBROUTINE myIdle

  !< Draw the window. >----------

  SUBROUTINE myDisplay

    CALL glClear(GL_COLOR_BUFFER_BIT)  ! Fill the window with the set colour.
    CALL myAnimation                   ! Draw animation.
    CALL glutSwapBuffers               ! Double-buffering buffer swap.

  END SUBROUTINE myDisplay

  !< Draw an animation. >----------

  SUBROUTINE myAnimation

    REAL :: y = 0.
    REAL :: dy = 0.01

    y = y + dy
    CALL glColor3f(1.0, 0.0, 0.0)      ! Set drawing colour to Red.
    CALL glPointSize(10.0)             ! Set point size.
    CALL glBegin(GL_POINTS)            ! Start drawing points.
      CALL glVertex2f(0.,y)            ! Draw one point.
    CALL glEnd                         ! Finished drawing points.

    IF(y > 1.0) THEN
      dy = -0.01
     ELSE IF(y < -1) THEN
      dy = 0.01
    END IF

  END SUBROUTINE myAnimation

END MODULE myOpenGL
!==================================
!========== Main Program ==========
PROGRAM main

  USE myOpenGL                      ! Access our module.

  CALL glutInit                     ! Initialise the GLUT library.
  CALL myWindow                     ! Create our window.
  CALL glutKeyboardFunc(myKeyboard) ! Set keyboard input event handler.
  CALL glutIdleFunc(myIdle)         ! Set idle loop function, called when there is nothing else to do.
  CALL glutDisplayFunc(myDisplay)   ! Use myDisplay to draw the window.
  CALL glutMainLoop                 ! Run the main event loop.

END PROGRAM main
!==================================

The program sections coloured in green are described below; for OpenGL/GLUT calls in the black portion of the program, refer to the previous template programs' documentation.

Subroutine glutIdleFunc(idlefunc)
Interface
  Subroutine idlefunc
  End Subroutine
End Interface
Sets the idle function handler; this subroutine is repeatedly called as long as there are no window events to handle. If the argument is equal to glutnullfunc, the idle function is disabled.
Subroutine glutKeyboardFunc(keyboardfunc)
Interface
  Subroutine keyboardfunc(key,x,y)
  Use opengl_kinds
  Integer(glint),Intent(InOut) :: key
  Integer(glcint),Intent(InOut) :: x, y
  End Subroutine
End Interface
Sets the keyboard event handler; this is called for each actual character produced by the keyboard, there is no event for keys such as Shift or Alt that don't generate characters. The key argument contains the ASCII character code of the key pressed; this can be converted to Character type with the ACHAR or CHAR intrinsic functions. The x and y arguments indicate the mouse position at the time the key was pressed.

The result of executing OpenGL_09.f95:

Whilst executing the program, if the OpenGL window is selected and the ‘q’ or ‘Q’ key is pressed, the animation will stop. Pressing the ESC key will terminate execution.

Moving red dot

Kind values

The values used for the OpenGL/GLUT kinds mentioned above are as follows.
Integer,Parameter :: glcint = int32
Integer,Parameter :: glint = int32


OpenGL10: Mouse input program

Mouse Input Program

!===== Mouse Input Program =====< OpenGL10.f95>
MODULE myOpenGL

  USE opengl_gl      ! GL  (OpenGL Core library)
  USE opengl_glu     ! GLU (OpenGL Utility library)
  USE opengl_glut    ! GLUT(OpenGL Utility Toolkit)

 !-------
 CONTAINS
 !-------

  !< Window Creation >----------

  SUBROUTINE myWindow

    INTEGER :: win

    CALL glutInitDisplayMode(GLUT_RGBA)     ! Set the display mode.
    CALL glutInitWindowPosition(100, 100)   ! Window position from top left in pixels.
    CALL glutInitWindowSize(640, 480)       ! Window size (width, height) in pixels.
    win = glutCreateWindow("OpenGL Window") ! Create the window.
    CALL glClearColor(1.0,1.0,1.0,1.0)      ! Set the window fill colour (red,green,blue,alpha).

  END SUBROUTINE myWindow

  !< Draw the window. >----------

  SUBROUTINE myDisplay

    CALL glClear(GL_COLOR_BUFFER_BIT)  ! Fill the window with the set colour.
    CALL glFlush                       ! Actually do it.

  END SUBROUTINE myDisplay

  !< Mouse Click Handler >----------

  SUBROUTINE myMouse(button, state, x, y)

    INTEGER, INTENT(INOUT) :: button, state, x, y
    REAL :: px,py
    CHARACTER(LEN=6) :: b_name
    CHARACTER(LEN=4) :: b_updown

    SELECT CASE (button)

      CASE (GLUT_LEFT_BUTTON)   ! Left mouse button event.
          b_name =  "left  "

      CASE (GLUT_MIDDLE_BUTTON) ! Middle mouse button event.
          b_name = "middle"

      CASE (GLUT_RIGHT_BUTTON)  ! Right mouse button event.
          b_name = "right "

    END SELECT

    SELECT CASE (state)

      CASE (GLUT_UP)            ! Mouse button released.
          b_updown = "up  "
          CALL glColor3f(1.0, 0.0, 0.0)  ! Set drawing colour to Red.
          CALL glPointSize(5.0)          ! Set point size.
          px = (x-320)/320.              ! Convert mouse postion to X coordinate.
          py = (240-y)/240.              ! Convert mouse position to Y coordinate.
          CALL glBegin(GL_POINTS)        ! Start drawing points.
            CALL glVertex2f(px,py)       ! Draw one point.
          CALL glEnd                     ! Finished drawing points.
          CALL glFlush

      CASE (GLUT_DOWN)          ! Mouse button pressed.
          b_updown = "down"

    END SELECT

    PRINT *, b_name," button is ",b_updown," at ", x, y

  END SUBROUTINE myMouse

END MODULE myOpenGL
!==================================
!========== Main Program ==========
PROGRAM main

  USE myOpenGL                      ! Access our module.

  CALL glutInit                     ! Initialise the GLUT library.
  CALL myWindow                     ! Create our window.
  CALL glutMouseFunc(myMouse)       ! Set mouse button event handler.
  CALL glutDisplayFunc(myDisplay)   ! Use myDisplay to draw the window.
  CALL glutMainLoop                 ! Run the main event loop.

END PROGRAM main
!==================================

The program sections coloured in green are described below; for OpenGL/GLUT calls in the black portion of the program, refer to the previous template programs' documentation.

Subroutine glutMouseFunc(mousefunc)
Interface
  Subroutine mousefunc(button,state,x,y)
  Use opengl_kinds
  Integer(glcint),Intent(InOut) :: button,state,x,y
  End Subroutine
End Interface
Sets the mouse event handler; this is called when a mouse button is either pressed or released. The button argument indicates which mouse button, and will be one of GLUT_LEFT_BUTTON, GLUT_MIDDLE_BUTTON and GLUT_RIGHT_BUTTON. The state argument indicates the new mouse state, either GLUT_DOWN (for a press) or GLUT_UP (for a release). The x and y arguments indicate the mouse position in pixels at the time the key was pressed, as shown in the following diagram.

The result of executing OpenGL_10.f95:

Scattered red dots

The console window below shows some of the mouse events for that run.

Console showing mouse events

Kind values

The values used for the OpenGL/GLUT kinds mentioned above are as follows.
Integer,Parameter :: glcint = int32


OpenGL11: 3D Orthogonal projection (geometric transform) and modelling program

3D Orthogonal Projection (geometric transform) and Modelling Program

!===== 3D Orthogonal Projection (geometric transform) and Modelling Program =====< OpenGL11.f95>
MODULE myOpenGL

  USE opengl_gl      ! GL  (OpenGL Core library)
  USE opengl_glu     ! GLU (OpenGL Utility library)
  USE opengl_glut    ! GLUT(OpenGL Utility Toolkit)

  REAL,    DIMENSION(3,8)  :: coord  ! Vertex coordinates.
  INTEGER, DIMENSION(2,12) :: edge   ! Vertex numbers for each edge.

 !-------
 CONTAINS
 !-------

  !< Window Creation >----------

  SUBROUTINE myWindow

    INTEGER :: win

    CALL glutInitDisplayMode(GLUT_RGBA)     ! Set the display mode.
    CALL glutInitWindowPosition(100, 200)   ! Window position from top left in pixels.
    CALL glutInitWindowSize(640, 480)       ! Window size (width, height) in pixels.
    win = glutCreateWindow("OpenGL Window") ! Create the window.
    CALL glClearColor(1.0,1.0,1.0,1.0)      ! Set window fill colour (red,green,blue,alpha).

  END SUBROUTINE myWindow

  !< Window Resize Handler >----------

  SUBROUTINE myResize(w, h)

    INTEGER, INTENT(INOUT) :: w, h         ! Current window width and height in pixels.

    CALL glViewport(100, 100, 300, 300)            ! Set viewport (in pixels).
    CALL glLoadIdentity                            ! Initialise transformation matrix.
    CALL glOrtho(-2.D0,2.D0,-2.D0,2.D0,-2.D0,2.D0) ! Define projection (parallel projection).
    CALL glRotatef( 30.,1.,0.,0.)                  ! Rotate figure 30 degrees in X axis.
    CALL glRotatef( 20.,0.,1.,0.)                  ! Rotate figure 20 degrees in Y axis.

  END SUBROUTINE myResize

  !< Draw the window. >----------

  SUBROUTINE myDisplay

    CALL glClear(GL_COLOR_BUFFER_BIT)  ! Fill the window with the set colour.
    CALL myCube                        ! Draw the cube.
    CALL glFlush                       ! Actually do it.

  END SUBROUTINE myDisplay

  !< Draw a cube. >----------

  SUBROUTINE myCube

    CALL glColor3f(0.0, 0.0, 0.0)              ! Set drawing colour to Black.
    CALL glBegin(GL_LINES)                     ! Start drawing lines.
      DO i = 1, 12
        CALL glVertex3f(coord(1,edge(1,i)), &
                        coord(2,edge(1,i)), &
                        coord(3,edge(1,i)))
        CALL glVertex3f(coord(1,edge(2,i)), &
                        coord(2,edge(2,i)), &
                        coord(3,edge(2,i)))
      END DO
    CALL glEnd                                 ! Finished drawing lines.

   END SUBROUTINE myCube

  !< Make a model of a cube. >----------

  SUBROUTINE myModel

    coord(1:3,1) = (/0.0, 0.0, 0.0/) ! First vertex coordinates (x,y,z).
    coord(1:3,2) = (/1.0, 0.0, 0.0/) ! Second vertex coordinates (x,y,z).
    coord(1:3,3) = (/1.0, 1.0, 0.0/) ! Third vertex coordinates (x,y,z).
    coord(1:3,4) = (/0.0, 1.0, 0.0/) ! Fourth vertex coordinates (x,y,z).
    coord(1:3,5) = (/0.0, 0.0, 1.0/) ! Fifth vertex coordinates (x,y,z).
    coord(1:3,6) = (/1.0, 0.0, 1.0/) ! Sixth vertex coordinates (x,y,z).
    coord(1:3,7) = (/1.0, 1.0, 1.0/) ! Seventh vertex coordinates (x,y,z).
    coord(1:3,8) = (/0.0, 1.0, 1.0/) ! Eightth vertex coordinates (x,y,z).

    edge(1:2, 1) = (/1, 2/) ! Edge  1 starting and ending vertex numbers.
    edge(1:2, 2) = (/2, 3/) ! Edge  2 starting and ending vertex numbers.
    edge(1:2, 3) = (/3, 4/) ! Edge  3 starting and ending vertex numbers.
    edge(1:2, 4) = (/4, 1/) ! Edge  4 starting and ending vertex numbers.
    edge(1:2, 5) = (/5, 6/) ! Edge  5 starting and ending vertex numbers.
    edge(1:2, 6) = (/6, 7/) ! Edge  6 starting and ending vertex numbers.
    edge(1:2, 7) = (/7, 8/) ! Edge  7 starting and ending vertex numbers.
    edge(1:2, 8) = (/8, 5/) ! Edge  8 starting and ending vertex numbers.
    edge(1:2, 9) = (/1, 5/) ! Edge  9 starting and ending vertex numbers.
    edge(1:2,10) = (/2, 6/) ! Edge 10 starting and ending vertex numbers.
    edge(1:2,11) = (/3, 7/) ! Edge 11 starting and ending vertex numbers.
    edge(1:2,12) = (/4, 8/) ! Edge 12 starting and ending vertex numbers.

  END SUBROUTINE myModel

END MODULE myOpenGL
!==================================
!========== Main Program ==========
PROGRAM main

  USE myOpenGL                     ! Access our module.

  CALL myModel                     ! Make the cube model.
  CALL glutInit                    ! Initialise the GLUT library.
  CALL myWindow                    ! Create our window.
  CALL glutReshapeFunc(myResize)   ! Use myResize to handle window size changes.
  CALL glutDisplayFunc(myDisplay)  ! Use myDisplay to draw the window.
  CALL glutMainLoop                ! Run the main event loop.

END PROGRAM main
!==================================

The program sections coloured in green are described below; for OpenGL/GLUT calls in the black portion of the program, refer to the previous template programs' documentation.

Subroutine glVertex3f(x,y,z)
Real(glfloat),Intent(In) :: x,y,z
Specifies a vertex or point in 3-space, in world coordinates. The subroutine glVertex3d is available for double precision data.
Subroutine glOrtho(left,right,bottom,top,near,far)
Real(gldouble),Intent(In) :: left,right,bottom,top,near,far
Applies an orthographic transformation to the current transformation matrix. This produces a parallel projection, as seen in the diagram below.

The arguments specify the coordinates of the vertical, horizontal and depth clipping planes, as shown in the next diagram.
Subroutine glRotatef(angle,x,y,z)
Real(glfloat),Intent(In) :: angle,x,y,z
Applies a rotation to the current transformation matrix. This produces a rotation of angle degrees around the vector (x,y,z). The subroutine glRotated is available for double precision data.
Subroutine glScalef(x,y,z)
Real(glfloat),Intent(In) :: x,y,z
Applies a general scaling operation to the current transformation matrix. This scales the X axis by x, the Y axis by y and the Z axis by z. The subroutine glScaled is available for double precision data.

Note that glScalef and glTranslatef are not used in OpenGL_11.f95, but documented here for convenience.

The result of executing OpenGL_11.f95:

Kind values

The values used for the OpenGL/GLUT kinds mentioned above are as follows.
Integer,Parameter :: gldouble = real64
Integer,Parameter :: glfloat = real32


OpenGL12: 3D Orthogonal projection (view transform) and modelling program

3D Orthogonal Projection (view transform) and Modelling Program

!===== 3D Orthogonal Projection (view transform) and Modelling Program =====< OpenGL12.f95>
MODULE myOpenGL

  USE opengl_gl      ! GL  (OpenGL Core library)
  USE opengl_glu     ! GLU (OpenGL Utility library)
  USE opengl_glut    ! GLUT(OpenGL Utility Toolkit)

  REAL,    DIMENSION(3,8)  :: coord  ! Vertex coordinates.
  INTEGER, DIMENSION(2,12) :: edge   ! Vertex numbers for each edge.

 !-------
 CONTAINS
 !-------

  !< Window Creation >----------

  See OpenGL11 for subroutine myWindow.

  !< Window Resize Handler >----------

  SUBROUTINE myResize(w, h)

    INTEGER, INTENT(INOUT) :: w, h         ! Current window width and height in pixels.

    CALL glViewport(100, 100, 300, 300)            ! Set viewport (in pixels).
    CALL glLoadIdentity                            ! Initialise transformation matrix.
    CALL glOrtho(-2.D0,2.D0,-2.D0,2.D0,-2.D0,2.D0) ! Define a parallel projection.
    CALL gluLookAt(0.9D0,0.8D0,1.0D0, &
                   0.5D0,1.0D0,0.5D0, &
                   0.0D0,1.0D0,0.0D0)              ! Set view transformation matrix.

  END SUBROUTINE myResize

  !< Draw the window. >----------
  !< Draw a cube. >----------
  !< Make a model of a cube. >----------

  See OpenGL11 for subroutines myDisplay, myCube and myModel.

END MODULE myOpenGL
!==================================
!========== Main Program ==========

  See OpenGL11 for the main program.

!==================================

The program sections coloured in green are described below; for OpenGL/GLUT calls in the black portion of the program, refer to the previous template programs' documentation.

Subroutine gluLookAt(eyex,eyey,eyez,centerx,centery,centerz,upx,upy,upz)
Real(gldouble),Intent(In) :: eyex,eyey,eyez,centerx,centery,centerz,upx,upy,upz
Applies a transformation to the current transformation matrix based on the eye position specified by (eyex,eyey,eyez), the centre position of the scene specified by (centerx,centery,centerz) and the up direction specified by the vector (upx,upy,upz). This transformation maps the centre point to the negative Z-axis and the eye point to the origin, so that a typical projection will map the centre of the scene to the centre of the viewport. Also, the up vector is mapped to the positive Y-axis, i.e. points upwards in the viewport. This is illustrated in the diagram below.

The result of executing OpenGL_12.f95:

Kind values

The values used for the OpenGL/GLUT kinds mentioned above are as follows.
Integer,Parameter :: gldouble = real64


OpenGL13: 3D perspective projection program 1

3D Perspective Projection, Program 1

!===== 3D Perspective Projection, Program 1 =====< OpenGL13.f95>
MODULE myOpenGL

  USE opengl_gl      ! GL  (OpenGL Core library)
  USE opengl_glu     ! GLU (OpenGL Utility library)
  USE opengl_glut    ! GLUT(OpenGL Utility Toolkit)

  REAL,    DIMENSION(3,8)  :: coord  ! Vertex coordinates.
  INTEGER, DIMENSION(2,12) :: edge   ! Vertex numbers for each edge.

 !-------
 CONTAINS
 !-------

  !< Window Creation >----------

  See OpenGL11 for subroutine myWindow.

  !< Window Resize Handler >----------

  SUBROUTINE myResize(w, h)

    INTEGER, INTENT(INOUT) :: w, h         ! Current window width and height in pixels.

    CALL glViewport(0,0,500,500)                    ! Set viewport (in pixels).
    CALL glMatrixMode(GL_PROJECTION)                ! Set transformation matrix mode.
    CALL glLoadIdentity                             ! Initialise transformation matrix.
    CALL glFrustum(0.D0,2.D0,0.D0,2.D0,1.5D0,50.D0) ! Create matrix for perspective-view frustrum.

    CALL glMatrixMode(GL_MODELVIEW)   ! Set the model view matrix.
    CALL glLoadIdentity               ! Initialise transformation mode.
    CALL glTranslatef(1.,1.,-3.)      ! Perform translation.

  END SUBROUTINE myResize

  !< Draw the window. >----------
  !< Draw a cube. >----------
  !< Make a model of a cube. >----------

  See OpenGL11 for subroutines myDisplay, myCube and myModel.

END MODULE myOpenGL
!==================================
!========== Main Program ==========

  See OpenGL11 for the main program.

!==================================

The program sections coloured in green are described below; for OpenGL/GLUT calls in the black portion of the program, refer to the previous template programs' documentation.

Subroutine glMatrixMode(mode)
Integer(glenum),Intent(In) :: mode
Specifies which matrix is the current matrix (and thus affected by subsequent matrix operations); mode must be one of:
GL_MODELVIEW: the model view matrix;
GL_PROJECTION: the projection matrix;
GL_TEXTURE: the texture matrix.
Subroutine glFrustum(left,right,bottom,top,near,far)
Real(gldouble),Intent(In) :: left,right,bottom,top,near,far
Multiplies the current matrix by a perspective matrix, specified by the six supplied clipping planes.
Subroutine glTranslatef(x,y,z)
Real(glfloat),Intent(In) :: x,y,z
Applies a translation to the current transformation matrix. This results in the translation specified by the vector (x,y,z). The subroutine glTranslated is available for double precision data.

The result of executing OpenGL_13.f95:

Wire-frame cube in perspective

Kind values

The values used for the OpenGL/GLUT kinds mentioned above are as follows.
Integer,Parameter :: gldouble = real64
Integer,Parameter :: glenum = int32


OpenGL14: 3D perspective projection program 2

3D Perspective Projection, Program 2

!===== 3D Perspective Projection, Program 2 =====< OpenGL14.f95>
MODULE myOpenGL

  USE opengl_gl      ! GL  (OpenGL Core library)
  USE opengl_glu     ! GLU (OpenGL Utility library)
  USE opengl_glut    ! GLUT(OpenGL Utility Toolkit)

  REAL,    DIMENSION(3,8)  :: coord  ! Vertex coordinates.
  INTEGER, DIMENSION(2,12) :: edge   ! Vertex numbers for each edge.

 !-------
 CONTAINS
 !-------

  !< Window Creation >----------

  See OpenGL11 for subroutine myWindow.

  !< Window Resize Handler >----------

  SUBROUTINE myResize(w, h)

    INTEGER, INTENT(INOUT) :: w, h              ! Current window width and height in pixels.

    CALL glViewport(0,0,500,500)                ! Set viewport (in pixels).
    CALL glMatrixMode(GL_PROJECTION)            ! Set transformation matrix mode.
    CALL glLoadIdentity                         ! Initialise transformation matrix.
    CALL gluPerspective(60.D0,1.D0,2.D0,100.D0) ! Set perspective view.

    CALL glMatrixMode(GL_MODELVIEW)             ! Set the model view matrix.
    CALL glLoadIdentity                         ! Initialise transformation matrix.
    CALL gluLookAt(0.5D0,-0.5D0,5.0D0, &
                   0.5D0, 0.5D0,0.5D0, &
                   0.0D0, 1.0D0,0.0D0)          ! Set view transformation matrix.

  END SUBROUTINE myResize

  !< Draw the window. >----------
  !< Draw a cube. >----------
  !< Make a model of a cube. >----------

  See OpenGL11 for subroutines myDisplay, myCube and myModel.

END MODULE myOpenGL
!==================================
!========== Main Program ==========

  See OpenGL11 for the main program.

!==================================

The program sections coloured in green are described below; for OpenGL/GLUT calls in the black portion of the program, refer to the previous template programs' documentation.

Subroutine glMatrixMode(mode)
Integer(glenum),Intent(In) :: mode
Specifies which matrix is the current matrix (and thus affected by subsequent matrix operations); mode must be one of:
GL_MODELVIEW: the model view matrix;
GL_PROJECTION: the projection matrix;
GL_TEXTURE: the texture matrix.
Subroutine gluPerspective(fovy,aspect,znear,zfar)
Real(gldouble),Intent(In) :: fovy,aspect,znear,zfar
Sets up a perspective projection matrix. The fovy argument specifies the field-of-view angle, in degrees, in the Y direction. The aspect argument specifies the aspect ratio; this determines the field of view in the X direction, i.e. the aspect ratio is the X width divided by the Y height. The znear and zfar arguments specify the distance from the viewer to the near and far clipping planes, respectively; this distance is always positive. This is illustrated by the diagram below.
Subroutine gluLookAt(eyex,eyey,eyez,centerx,centery,centerz,upx,upy,upz)
Real(gldouble),Intent(In) :: eyex,eyey,eyez,centerx,centery,centerz,upx,upy,upz
The effects of gluLookAt are described under OpenGL12.

The result of executing OpenGL_14.f95:

Wire-frame cube in perspective

Kind values

The values used for the OpenGL/GLUT kinds mentioned above are as follows.
Integer,Parameter :: gldouble = real64
Integer,Parameter :: glenum = int32


OpenGL15: Polygon filling program

Polygon Filling Program

!===== Polygon Filling Program =====< OpenGL15.f95>
MODULE myOpenGL

  USE opengl_gl      ! GL  (OpenGL Core library)
  USE opengl_glu     ! GLU (OpenGL Utility library)
  USE opengl_glut    ! GLUT(OpenGL Utility Toolkit)

  REAL,    DIMENSION(3,8) :: coord  ! 3D coordinates of the cube.
  REAL,    DIMENSION(3,6) :: colour ! Colour of each face.
  INTEGER, DIMENSION(4,6) :: face   ! Define each face.

 !-------
 CONTAINS
 !-------

  !< Window Creation >----------

  SUBROUTINE myWindow

    INTEGER :: win

    CALL glutInitDisplayMode(ior(GLUT_RGBA, & ! Set the display mode,
                                 GLUT_DEPTH)) ! with depth (Z-buffer).
    CALL glutInitWindowPosition(100, 200)     ! Window position from top left in pixels.
    CALL glutInitWindowSize(640, 480)         ! Window size (width, height) in pixels.
    win = glutCreateWindow("OpenGL Window")   ! Create the window.
    CALL glClearColor(1.0,1.0,1.0,1.0)        ! Fill the window with white.

    CALL glEnable(GL_DEPTH_TEST)              ! Enable hidden surface removal.

  END SUBROUTINE myWindow

  !< Window Resize Handler >----------

  SUBROUTINE myResize(w, h)

    INTEGER, INTENT(INOUT) :: w, h         ! Current window width and height in pixels.

    CALL glViewport(100, 100, 300, 300)            ! Set viewport (in pixels).
    CALL glLoadIdentity                            ! Initialise transformation matrix.
    CALL glOrtho(-2.D0,2.D0,-2.D0,2.D0,-4.D0,4.D0) ! Define the projection.
    CALL gluLookAt(-0.8D0,1.0D0,2.0D0, &           ! View: position of eye;
                    0.5D0,0.0D0,0.5D0, &           ! View: reference point;
                    0.0D0,1.0D0,0.0D0)             ! View: direction of "up".

  END SUBROUTINE myResize

  !< Draw the window. >----------

  SUBROUTINE myDisplay

    CALL glClear(ior(GL_COLOR_BUFFER_BIT, &   ! Clear colours and
                     GL_DEPTH_BUFFER_BIT))    ! z buffer.
    CALL myCube                               ! Draw the cube.
    CALL glFlush                              ! Produce the actual output.

  END SUBROUTINE myDisplay

  !< Draw a cube. >----------

  SUBROUTINE myCube

    CALL glBegin(GL_QUADS)                     ! Start drawing quadrilaterals.
      DO i = 1, 6
        CALL glColor3f(colour(1,i),colour(2,i),colour(3,i)) ! Set colour.
        DO j = 1, 4
          n = face(j,i)
          CALL glVertex3f(coord(1,n),coord(2,n),coord(3,n))
        END DO
      END DO
    CALL glEnd                                 ! Finish.

   END SUBROUTINE myCube

  ! < Make a model of a cube. >----------

  SUBROUTINE myModel

    coord(1:3,1) = (/0.0, 0.0, 0.0/) ! Vertex 1 coordinates (x,y,z).
    coord(1:3,2) = (/1.0, 0.0, 0.0/) ! Vertex 2 coordinates (x,y,z).
    coord(1:3,3) = (/1.0, 1.0, 0.0/) ! Vertex 3 coordinates (x,y,z).
    coord(1:3,4) = (/0.0, 1.0, 0.0/) ! Vertex 4 coordinates (x,y,z).
    coord(1:3,5) = (/0.0, 0.0, 1.0/) ! Vertex 5 coordinates (x,y,z).
    coord(1:3,6) = (/1.0, 0.0, 1.0/) ! Vertex 6 coordinates (x,y,z).
    coord(1:3,7) = (/1.0, 1.0, 1.0/) ! Vertex 7 coordinates (x,y,z).
    coord(1:3,8) = (/0.0, 1.0, 1.0/) ! Vertex 8 coordinates (x,y,z).

    face(1:4,1) = (/1, 4, 3, 2/) ! Face 1 corner vertex numbers.
    face(1:4,2) = (/2, 3, 7, 6/) ! Face 2 corner vertex numbers.
    face(1:4,3) = (/5, 6, 7, 8/) ! Face 3 corner vertex numbers.
    face(1:4,4) = (/5, 8, 4, 1/) ! Face 4 corner vertex numbers.
    face(1:4,5) = (/5, 1, 2, 6/) ! Face 5 corner vertex numbers.
    face(1:4,6) = (/4, 8, 7, 3/) ! Face 6 corner vertex numbers.

    colour(1:3,1) = (/1.0, 0.0, 0.0/) ! Face 1 colour is Red.
    colour(1:3,2) = (/0.0, 1.0, 0.0/) ! Face 2 colour is Green.
    colour(1:3,3) = (/0.0, 0.0, 1.0/) ! Face 3 colour is Blue.
    colour(1:3,4) = (/1.0, 1.0, 0.0/) ! Face 4 colour is Yellow.
    colour(1:3,5) = (/1.0, 0.0, 1.0/) ! Face 5 colour is Purple.
    colour(1:3,6) = (/0.0, 1.0, 1.0/) ! Face 6 colour is Turquoise.

  END SUBROUTINE myModel

END MODULE myOpenGL
!==================================
!========== Main Program ==========
PROGRAM main

  USE myOpenGL                     ! Access our module.

  CALL myModel                     ! Make the cube model.
  CALL glutInit                    ! Initialise the GLUT library.
  CALL myWindow                    ! Create our window.
  CALL glutReshapeFunc(myResize)   ! Use myResize to handle window size changes.
  CALL glutDisplayFunc(myDisplay)  ! Use myDisplay to draw the window.
  CALL glutMainLoop                ! Run the main event loop.

END PROGRAM main
!==================================

The program sections coloured in green are described below; for OpenGL/GLUT calls in the black portion of the program, refer to the previous template programs' documentation.

Subroutine glutInitDisplayMode(mode)
Integer(glcuint),Intent(In) :: mode
Sets the initial display mode to be used for subsequently creahed windows; mode is a bit mask, the intrinsic function IOR should be used to combine multiple bits. Relevant bits for this program are
GL_RGBA: set the display mode to RGBA (default);
GL_DEPTH: the window should have a depth buffer.
Subroutine glEnable(cap)
Integer(glenum),Intent(In) :: cap
Enables the specified capability. If cap is equal to GLUT_DEPTH_TEST, do depth comparisons and update the depth buffer.
Subroutine glDisable(cap)
Integer(glenum),Intent(In) :: cap
Disables the specified capability.
Subroutine glColor3f(red,green,blue)
Real(glfloat),Intent(In) :: red,green,blue
Sets the colour used for drawing. The colour component values must be in the range 0.0 to 1.0. Note that the colour can also be set by glColor3d and glColor3i.
Subroutine glVertex3f(x,y,z)
Real(glfloat),Intent(In) :: x,y,z
Specifies a vertex or point in 3-space, in world coordinates. The subroutine glVertex3d is available for double precision data.

The result of executing OpenGL_15.f95:

Kind values

The values used for the OpenGL/GLUT kinds mentioned above are as follows.
Integer,Parameter :: glcuint = int32
Integer,Parameter :: glenum = int32
Integer,Parameter :: glfloat = real32


OpenGL16: Polygon filling and culling program

Polygon Filling and Culling Program

!===== Polygon Filling and Culling Program =====< OpenGL16.f95>
MODULE myOpenGL

  USE opengl_gl      ! GL  (OpenGL Core library)
  USE opengl_glu     ! GLU (OpenGL Utility library)
  USE opengl_glut    ! GLUT(OpenGL Utility Toolkit)

  REAL,    DIMENSION(3,8) :: coord  ! 3D coordinates of the cube.
  REAL,    DIMENSION(3,6) :: colour ! Colour of each face.
  INTEGER, DIMENSION(4,6) :: face   ! Define each face.

 !-------
 CONTAINS
 !-------

  !< Window Creation >----------

  SUBROUTINE myWindow

    INTEGER :: win

    CALL glutInitDisplayMode(ior(GLUT_RGBA, & ! Set the display mode,
                                 GLUT_DEPTH)) ! with depth (Z-buffer).
    CALL glutInitWindowPosition(100, 200)     ! Window position from top left in pixels.
    CALL glutInitWindowSize(640, 480)         ! Window size (width, height) in pixels.
    win = glutCreateWindow("OpenGL Window")   ! Create the window.
    CALL glClearColor(1.0,1.0,1.0,1.0)        ! Fill the window with white.

    CALL glEnable(GL_DEPTH_TEST)              ! Enable hidden surface removal.
    CALL glEnable(GL_CULL_FACE)               ! Enable culling.
    CALL glCullFace(GL_BACK)                  ! Do not display the back faces.

  END SUBROUTINE myWindow

  !< Window Resize Handler >----------

  SUBROUTINE myResize(w, h)

    INTEGER, INTENT(INOUT) :: w, h         ! Current window width and height in pixels.

    CALL glViewport(100, 100, 300, 300)            ! Set viewport (in pixels).
    CALL glLoadIdentity                            ! Initialise transformation matrix.
    CALL glOrtho(-2.D0,2.D0,-2.D0,2.D0,-4.D0,4.D0) ! Define the projection.
    CALL gluLookAt(-0.8D0,1.0D0,2.0D0, &           ! View: position of eye;
                    0.5D0,0.0D0,0.5D0, &           ! View: reference point;
                    0.0D0,1.0D0,0.0D0)             ! View: direction of "up".

  END SUBROUTINE myResize

  !< Draw the window. >----------

  SUBROUTINE myDisplay

    CALL glClear(ior(GL_COLOR_BUFFER_BIT, &   ! Clear colours and
                     GL_DEPTH_BUFFER_BIT))    ! z buffer.
    CALL myCube                               ! Draw the cube.
    CALL glFlush                              ! Produce the actual output.

  END SUBROUTINE myDisplay

  !< Draw a cube. >----------

  SUBROUTINE myCube

    CALL glBegin(GL_QUADS)                     ! Start drawing quadrilaterals.
      DO i = 1, 6
        CALL glColor3f(colour(1,i),colour(2,i),colour(3,i)) ! Set colour.
        DO j = 1, 4
          n = face(j,i)
          CALL glVertex3f(coord(1,n),coord(2,n),coord(3,n))
        END DO
      END DO
    CALL glEnd                                 ! Finish.

   END SUBROUTINE myCube

  ! < Make a model of a cube. >----------

  SUBROUTINE myModel

    coord(1:3,1) = (/0.0, 0.0, 0.0/) ! Vertex 1 coordinates (x,y,z).
    coord(1:3,2) = (/1.0, 0.0, 0.0/) ! Vertex 2 coordinates (x,y,z).
    coord(1:3,3) = (/1.0, 1.0, 0.0/) ! Vertex 3 coordinates (x,y,z).
    coord(1:3,4) = (/0.0, 1.0, 0.0/) ! Vertex 4 coordinates (x,y,z).
    coord(1:3,5) = (/0.0, 0.0, 1.0/) ! Vertex 5 coordinates (x,y,z).
    coord(1:3,6) = (/1.0, 0.0, 1.0/) ! Vertex 6 coordinates (x,y,z).
    coord(1:3,7) = (/1.0, 1.0, 1.0/) ! Vertex 7 coordinates (x,y,z).
    coord(1:3,8) = (/0.0, 1.0, 1.0/) ! Vertex 8 coordinates (x,y,z).

    face(1:4,1) = (/1, 4, 3, 2/)     ! Face 1 corner vertex numbers.
    face(1:4,2) = (/2, 3, 7, 6/)     ! Face 2 corner vertex numbers.
    face(1:4,3) = (/5, 6, 7, 8/)     ! Face 3 corner vertex numbers.
    face(1:4,4) = (/5, 8, 4, 1/)     ! Face 4 corner vertex numbers.
    face(1:4,5) = (/5, 1, 2, 6/)     ! Face 5 corner vertex numbers.
    face(1:4,6) = (/4, 8, 7, 3/)     ! Face 6 corner vertex numbers.

    color(1:3,1) = (/1.0, 0.0, 0.0/) ! Face 1 colour is Red.
    color(1:3,2) = (/0.0, 1.0, 0.0/) ! Face 2 colour is Green.
    color(1:3,3) = (/0.0, 0.0, 1.0/) ! Face 3 colour is Blue.
    color(1:3,4) = (/1.0, 1.0, 0.0/) ! Face 4 colour is Yellow.
    color(1:3,5) = (/1.0, 0.0, 1.0/) ! Face 5 colour is Purple.
    color(1:3,6) = (/0.0, 1.0, 1.0/) ! Face 6 colour is Turquoise.

  END SUBROUTINE myModel

END MODULE myOpenGL
!==================================
!========== Main Program ==========
PROGRAM main

  USE myOpenGL                     ! Access our module.

  CALL myModel                     ! Make the cube model.
  CALL glutInit                    ! Initialise the GLUT library.
  CALL myWindow                    ! Create our window.
  CALL glutReshapeFunc(myResize)   ! Use myResize to handle window size changes.
  CALL glutDisplayFunc(myDisplay)  ! Use myDisplay to draw the window.
  CALL glutMainLoop                ! Run the main event loop.

END PROGRAM main
!==================================

The program sections coloured in green are described below; for OpenGL/GLUT calls in the black portion of the program, refer to the previous template programs' documentation.

Subroutine glEnable(cap)
Integer(glenum),Intent(In) :: cap
Enables the specified capability. If cap is equal to GLUT_CULL_FACE, cull polygons depending on whether they are showing their front or back face in window coordinates.
Subroutine glCullFace(mode)
Integer(glenum),Intent(In) :: mode
The mode argument specifies whether front faces (GL_FRONT), back faces (GL_BACK) or both faces (GL_FRONT_AND_BACK) of each polygon will be culled. In the case of GL_FRONT_AND_BACK, the edges and vertexes of each polygon will still be displayed.

The result of executing OpenGL_16.f95:

Kind values

The values used for the OpenGL/GLUT kinds mentioned above are as follows.
Integer,Parameter :: glenum = int32
Integer,Parameter :: glfloat = real32


OpenGL17: Lighting program

Lighting Program

!===== Lighting Program =====< OpenGL17.f95>
MODULE myOpenGL

  USE opengl_gl      ! GL  (OpenGL Core library)
  USE opengl_glu     ! GLU (OpenGL Utility library)
  USE opengl_glut    ! GLUT(OpenGL Utility Toolkit)

  REAL,    DIMENSION(3,8) :: coord  ! 3D coordinates of the cube.
  REAL,    DIMENSION(3,6) :: normal ! Normal vector for each face.
  INTEGER, DIMENSION(4,6) :: face   ! Define each face.

 !-------
 CONTAINS
 !-------

  !< Window Creation >----------

  SUBROUTINE myWindow

    INTEGER :: win

    CALL glutInitDisplayMode(ior(GLUT_RGBA, & ! Set the display mode,
                                 GLUT_DEPTH)) ! with depth (Z-buffer).
    CALL glutInitWindowPosition(100, 100)     ! Window position from top left in pixels.
    CALL glutInitWindowSize(640, 480)         ! Window size (width, height) in pixels.
    win = glutCreateWindow("OpenGL Window")   ! Create the window.
    CALL glClearColor(1.0,1.0,1.0,1.0)        ! Fill the window with white.

    CALL glEnable(GL_DEPTH_TEST)              ! Enable hidden surface removal.
    CALL glEnable(GL_CULL_FACE)               ! Enable culling.
    CALL glCullFace(GL_BACK)                  ! Do not display the back faces.

    CALL glEnable(GL_LIGHT0)                  ! Enable light source.
    CALL glEnable(GL_LIGHTING)                ! Enable shading.

  END SUBROUTINE myWindow

  !< Window Resize Handler >----------

  SUBROUTINE myResize(w, h)

    INTEGER, INTENT(INOUT) :: w, h                 ! Current window width and height in pixels.

    CALL glViewport(100, 100, 300, 300)            ! Set viewport (in pixels).
    CALL glMatrixMode(GL_PROJECTION)               ! Set transformation matrix mode.
    CALL glLoadIdentity                            ! Initialise transformation matrix.
    CALL glOrtho(-2.D0,2.D0,-2.D0,2.D0,-5.D0,5.D0) ! Define the projection.
    CALL glMatrixMode(GL_MODELVIEW)                ! Set model view matrix mode.
    CALL glLoadIdentity                            ! Initialise transformation matrix.
    CALL gluLookAt( -1.0D0,2.0D0,-3.0D0, &         ! View: position of eye;
                     0.0D0,0.0D0, 0.0D0, &         ! View: reference point;
                     0.0D0,1.0D0, 0.0D0)           ! View: direction of "up".

  END SUBROUTINE myResize

  !< Draw the window. >----------

  SUBROUTINE myDisplay

    CALL glClear(ior(GL_COLOR_BUFFER_BIT, &   ! Clear colours and
                     GL_DEPTH_BUFFER_BIT))    ! z buffer.
    CALL myCube                               ! Draw the cube.
    CALL glFlush                              ! Produce the actual output.

  END SUBROUTINE myDisplay

  !< Draw a cube. >----------

  SUBROUTINE myCube

    CALL glEnable(GL_LIGHTING)         ! Enable shading.
    CALL glBegin(GL_QUADS)             ! Start drawing quadrilaterals.
      DO i = 1, 6
        CALL glNormal3fv(normal(:,i))  ! Set normal vector.
        DO j = 1, 4
          n = face(j,i)
          CALL glVertex3fv(coord(:,n))
        END DO
      END DO
    CALL glEnd                         ! End drawing quadrilaterals.
    CALL glDisable(GL_LIGHTING)        ! Disable further shading.

   END SUBROUTINE myCube

  ! < Make a model of a cube. >----------

  SUBROUTINE myModel

    coord(1:3,1) = (/0.0, 0.0, 0.0/) ! Vertex 1 coordinates (x,y,z).
    coord(1:3,2) = (/1.0, 0.0, 0.0/) ! Vertex 2 coordinates (x,y,z).
    coord(1:3,3) = (/1.0, 1.0, 0.0/) ! Vertex 3 coordinates (x,y,z).
    coord(1:3,4) = (/0.0, 1.0, 0.0/) ! Vertex 4 coordinates (x,y,z).
    coord(1:3,5) = (/0.0, 0.0, 1.0/) ! Vertex 5 coordinates (x,y,z).
    coord(1:3,6) = (/1.0, 0.0, 1.0/) ! Vertex 6 coordinates (x,y,z).
    coord(1:3,7) = (/1.0, 1.0, 1.0/) ! Vertex 7 coordinates (x,y,z).
    coord(1:3,8) = (/0.0, 1.0, 1.0/) ! Vertex 8 coordinates (x,y,z).

    face(1:4,1) = (/1, 4, 3, 2/)     ! Face 1 corner vertex numbers.
    face(1:4,2) = (/2, 3, 7, 6/)     ! Face 2 corner vertex numbers.
    face(1:4,3) = (/5, 6, 7, 8/)     ! Face 3 corner vertex numbers.
    face(1:4,4) = (/5, 8, 4, 1/)     ! Face 4 corner vertex numbers.
    face(1:4,5) = (/5, 1, 2, 6/)     ! Face 5 corner vertex numbers.
    face(1:4,6) = (/4, 8, 7, 3/)     ! Face 6 corner vertex numbers.

    normal(1:3,1) = (/ 0.0, 0.0,-1.0/) ! Face 1 normal vector.
    normal(1:3,2) = (/ 1.0, 0.0, 0.0/) ! Face 2 normal vector.
    normal(1:3,3) = (/ 0.0, 0.0, 1.0/) ! Face 3 normal vector.
    normal(1:3,4) = (/-1.0, 0.0, 0.0/) ! Face 4 normal vector.
    normal(1:3,5) = (/ 0.0,-1.0, 0.0/) ! Face 5 normal vector.
    normal(1:3,6) = (/ 0.0, 1.0, 0.0/) ! Face 6 normal vector.

  END SUBROUTINE myModel

END MODULE myOpenGL
!==================================
!========== Main Program ==========
PROGRAM main

  USE myOpenGL                     ! Access our module.

  CALL myModel                     ! Make the cube model.
  CALL glutInit                    ! Initialise the GLUT library.
  CALL myWindow                    ! Create our window.
  CALL glutReshapeFunc(myResize)   ! Use myResize to handle window size changes.
  CALL glutDisplayFunc(myDisplay)  ! Use myDisplay to draw the window.
  CALL glutMainLoop                ! Run the main event loop.

END PROGRAM main
!==================================

The program sections coloured in green are described below; for OpenGL/GLUT calls in the black portion of the program, refer to the previous template programs' documentation.

Subroutine glEnable(cap)
Integer(glenum),Intent(In) :: cap
Enables the specified capability. If cap is equal to GL_LIGHT0, light 0 is included when calculating the effects of lighting (GL_LIGHT1 to GL_LIGHT7 are also available). If cap is equal to GL_LIGHTING, lighting calculations are performed to calculate the colour of each vertex.
Subroutine glNormal3fv(v)
Real(glfloat),Intent(In) :: v(*)
Sets the current normal vector to v, which must have at least 3 elements.

The result of executing OpenGL_17.f95:

Kind values

The values used for the OpenGL/GLUT kinds mentioned above are as follows.
Integer,Parameter :: glenum = int32
Integer,Parameter :: glfloat = real32


OpenGL18: Shading program

Shading Program

!===== Shading Program =====< OpenGL18.f95>
MODULE myOpenGL

  USE opengl_gl      ! GL  (OpenGL Core library)
  USE opengl_glu     ! GLU (OpenGL Utility library)
  USE opengl_glut    ! GLUT(OpenGL Utility Toolkit)

  REAL,    DIMENSION(4)   :: L_position0     ! Light position.

 !-------
 CONTAINS
 !-------

  !< Window Creation >----------

  SUBROUTINE myWindow

    INTEGER :: win

    CALL glutInitDisplayMode(ior(GLUT_RGBA, & ! Set the display mode,
                                 GLUT_DEPTH)) ! with depth (Z-buffer).
    CALL glutInitWindowPosition(100, 100)     ! Window position from top left in pixels.
    CALL glutInitWindowSize(500, 500)         ! Window size (width, height) in pixels.
    win = glutCreateWindow("OpenGL Window")   ! Create the window.
    CALL glClearColor(1.0,1.0,1.0,1.0)        ! Fill the window with white.

    CALL glEnable(GL_DEPTH_TEST)              ! Enable hidden surface removal.
    CALL glEnable(GL_CULL_FACE)               ! Enable culling.

    L_position0 = (/1.0,1.0,1.5,1.0/)                   ! Light position.
    CALL glLightfv(GL_LIGHT0, GL_POSITION, L_position0) ! Set light position.
    CALL glEnable(GL_LIGHT0)                            ! Enable light source.
    CALL glEnable(GL_LIGHTING)                          ! Enable shading.

  END SUBROUTINE myWindow

  !< Window Resize Handler >----------

  SUBROUTINE myResize(w, h)

    INTEGER, INTENT(INOUT) :: w, h                 ! Current window width and height in pixels.

    CALL glViewport(0, 0, 500, 500)                ! Set viewport (in pixels).
    CALL glMatrixMode(GL_PROJECTION)               ! Set transformation matrix mode.
    CALL glLoadIdentity                            ! Initialise transformation matrix.
    CALL glOrtho(-3.D0,3.D0,-3.D0,3.D0,-5.D0,5.D0) ! Define the projection.
    CALL glMatrixMode(GL_MODELVIEW)                ! Set model view matrix mode.
    CALL glLoadIdentity                            ! Initialise transformation matrix.

  END SUBROUTINE myResize

  !< Draw the window. >----------

  SUBROUTINE myDisplay

    CALL glClear(ior(GL_COLOR_BUFFER_BIT, &   ! Clear colours and
                     GL_DEPTH_BUFFER_BIT))    ! z buffer.

    CALL glShadeModel(GL_FLAT)           ! Flat shading.
    CALL glPushMatrix                    ! Start conversion.
      CALL glTranslatef(1.2,0.0,0.0)     ! Translation.
      CALL glutSolidSphere(1.0D0,20,16)  ! Draw a ball.
    CALL glPopMatrix                     ! End conversion.

    CALL glShadeModel(GL_SMOOTH)         ! Smooth shading.
    CALL glPushMatrix                    ! Start conversion.
      CALL glTranslatef(-1.2,0.0,0.0)    ! Translation.
      CALL glutSolidSphere(1.0D0,20,16)  ! Draw a ball.
    CALL glPopMatrix                     ! End conversion.

    CALL glFlush                         ! Actually do it.

  END SUBROUTINE myDisplay

END MODULE myOpenGL
!==================================
!========== Main Program ==========
PROGRAM main

  USE myOpenGL                     ! Access our module.

  CALL glutInit                    ! Initialise the GLUT library.
  CALL myWindow                    ! Create our window.
  CALL glutReshapeFunc(myResize)   ! Use myResize to handle window size changes.
  CALL glutDisplayFunc(myDisplay)  ! Use myDisplay to draw the window.
  CALL glutMainLoop                ! Run the main event loop.

END PROGRAM main
!==================================

The program sections coloured in green are described below; for OpenGL/GLUT calls in the black portion of the program, refer to the previous template programs' documentation.

Subroutine glLightfv(light,pname,params)
Integer(glenum),Intent(In) :: light,pname
            Real(glfloat),Intent(In) :: params(*)
Sets the parameter values of a light source from the argument params. The light source is specified by light, and must be one of GL_LIGHT0 to GL_LIGHT7. The parameter to set is specified by pname; the relevant values for this program are:
GL_AMBIENT: the ambient intensity of the light in RGBA (4 values);
GL_DIFFUSE: the diffuse intensity of the light in RGBA (4 values);
GL_POSITION: the position of the light in homogeneous object coordinates (4 values);
GL_SPECULAR: the specular intensity of the light in RGBA (4 values).
Subroutine glPushMatrix
Push the current matrix stack.
Subroutine glPopMatrix
Pop the current matrix stack.
Subroutine glShadeModel(mode)
Integer(glenum),Intent(In) :: mode
Select the shading technique specified by mode. The possibilities are GL_FLAT and GL_SMOOTH (the default).
Subroutine glutSolidSphere(radius,slices,stacks)
Real(gldouble),Intent(In) :: radius
Integer(glint),Intent(In) :: slices,stacks
Draw a sphere at the modelling coordinates origin. The sphere has the specified radius, and is subdivided around the Z axis into slices slices and along the Z axis into stacks stacks.

The result of executing OpenGL_18.f95:

Kind values

The values used for the OpenGL/GLUT kinds mentioned above are as follows.
Integer,Parameter :: gldouble = real64
Integer,Parameter :: glenum = int32
Integer,Parameter :: glint = int32
Integer,Parameter :: glfloat = real32


OpenGL19: Surface property (material characteristics) program

Surface Property (Material Characteristics) Program

!===== Surface Property (Material Characteristics) Program =====< OpenGL19.f95>
MODULE myOpenGL

  USE opengl_gl      ! GL  (OpenGL Core library)
  USE opengl_glu     ! GLU (OpenGL Utility library)
  USE opengl_glut    ! GLUT(OpenGL Utility Toolkit)

  REAL, DIMENSION(4) :: L_position0     ! Light position.
  REAL, DIMENSION(4) :: lt_ambient
  REAL, DIMENSION(4) :: lt_diffuse
  REAL, DIMENSION(4) :: lt_specular
  REAL, DIMENSION(4) :: mt_ambient
  REAL, DIMENSION(4) :: mt_diffuse
  REAL, DIMENSION(4) :: mt_specular
  REAL               :: mt_shininess

 !-------
 CONTAINS
 !-------

  !< Window Creation >----------

  SUBROUTINE myWindow

    INTEGER :: win

    CALL glutInitDisplayMode(ior(GLUT_RGBA, & ! Set the display mode,
                                 GLUT_DEPTH)) ! with depth (Z-buffer).
    CALL glutInitWindowPosition(100, 100)     ! Window position from top left in pixels.
    CALL glutInitWindowSize(500, 500)         ! Window size (width, height) in pixels.
    win = glutCreateWindow("OpenGL Window")   ! Create the window.
    CALL glClearColor(1.0,1.0,1.0,1.0)        ! Fill the window with white.

    CALL glEnable(GL_DEPTH_TEST)              ! Enable hidden surface removal.
    CALL glEnable(GL_CULL_FACE)               ! Enable culling.

    L_position0 = (/1.0,1.0,3.0,0.0/)         ! Light position.
    lt_ambient  = (/0.5,0.5,0.5,1.0/) ! Light source ambient property in RGBA.
    lt_diffuse  = (/0.2,0.2,1.0,1.0/) ! Light source diffusion property in RGBA.
    lt_specular = (/0.5,0.5,0.5,1.0/) ! Light source specular property in RGBA.
    CALL glLightfv(GL_LIGHT0, GL_POSITION, L_position0) ! Set light position.
    CALL glLightfv(GL_LIGHT0, GL_AMBIENT,  lt_ambient ) ! Set ambient property.
    CALL glLightfv(GL_LIGHT0, GL_DIFFUSE,  lt_diffuse ) ! Set diffusion.
    CALL glLightfv(GL_LIGHT0, GL_SPECULAR, lt_specular )! Set specular.
    CALL glEnable(GL_LIGHT0)                            ! Enable light source.
    CALL glEnable(GL_LIGHTING)                          ! Enable shading.

    mt_ambient  = (/0.1,0.1,0.1,1.0/) ! Material ambient property in RGBA.
    mt_diffuse  = (/0.0,0.0,1.0,1.0/) ! Material diffusion property in RGBA.
    mt_specular = (/0.5,0.5,1.0,1.0/) ! Material specular property in RGBA.
    mt_shininess = 128.               ! Material specular coefficient.
    CALL glMaterialfv(GL_FRONT, GL_AMBIENT,   mt_ambient )   ! Set surface ambient property.
    CALL glMaterialfv(GL_FRONT, GL_DIFFUSE,   mt_diffuse )   ! Set surface diffusion property.
    CALL glMaterialfv(GL_FRONT, GL_SPECULAR,  mt_specular )  ! Set surface specular property.
    CALL glMaterialf (GL_FRONT, GL_SHININESS, mt_shininess ) ! Set surface specular coefficient.

  END SUBROUTINE myWindow

  !< Window Resize Handler >----------

  SUBROUTINE myResize(w, h)

    INTEGER, INTENT(INOUT) :: w, h                 ! Current window width and height in pixels.

    CALL glViewport(0, 0, 500, 500)                ! Set viewport (in pixels).
    CALL glMatrixMode(GL_PROJECTION)               ! Set transformation matrix mode.
    CALL glLoadIdentity                            ! Initialise transformation matrix.
    CALL glOrtho(-3.D0,3.D0,-3.D0,3.D0,-5.D0,5.D0) ! Define the projection.
    CALL glMatrixMode(GL_MODELVIEW)                ! Set model view matrix mode.
    CALL glLoadIdentity                            ! Initialise transformation matrix.

  END SUBROUTINE myResize

  !< Draw the window. >----------

  SUBROUTINE myDisplay

    CALL glClear(ior(GL_COLOR_BUFFER_BIT, &   ! Clear colours and
                     GL_DEPTH_BUFFER_BIT))    ! z buffer.

    CALL glShadeModel(GL_SMOOTH)         ! Smooth shading.

    CALL glutSolidSphere(1.0D0,20,16)    ! Draw a ball.

    CALL glFlush                         ! Actually do it.

  END SUBROUTINE myDisplay

END MODULE myOpenGL
!==================================
!========== Main Program ==========
PROGRAM main

  USE myOpenGL                     ! Access our module.

  CALL glutInit                    ! Initialise the GLUT library.
  CALL myWindow                    ! Create our window.
  CALL glutReshapeFunc(myResize)   ! Use myResize to handle window size changes.
  CALL glutDisplayFunc(myDisplay)  ! Use myDisplay to draw the window.
  CALL glutMainLoop                ! Run the main event loop.

END PROGRAM main
!==================================

The program sections coloured in green are described below; for OpenGL/GLUT calls in the black portion of the program, refer to the previous template programs' documentation.

Subroutine glMaterialfv(face,pname,params)
Integer(glenum),Intent(In) :: face,pname
Real(glfloat),Intent(In) :: params(*)
Sets the values of the material parameters. The face argument specifies whether the parameters are for front-facing (GL_FRONT), back-facing (GL_BACK) or both front and back facing (GL_FRONT_AND_BACK) polygons. The new values are supplied in params, and applied to the characteristic specified by pname; for this program the relevant characteristics are:
GL_AMBIENT: the ambient RGBA reflectance (4 values);
GL_DIFFUSE: the diffuse RGBA reflectance (4 values);
GL_EMISSION: the RGBA emitted light intensity (4 values);
GL_SHININESS: the RGBA specular exponent (1 value, range 0-128);
GL_SPECULAR: the specular RGBA reflectance (4 values).

The result of executing OpenGL_19.f95:

Kind values

The values used for the OpenGL/GLUT kinds mentioned above are as follows.
Integer,Parameter :: glenum = int32
Integer,Parameter :: glfloat = real32


OpenGL20: Texture mapping program

Texture Mapping Program

!===== Texture Mapping Program =====< OpenGL20.f95>
MODULE myOpenGL

  USE opengl_gl      ! GL  (OpenGL Core library)
  USE opengl_glu     ! GLU (OpenGL Utility library)
  USE opengl_glut    ! GLUT(OpenGL Utility Toolkit)

  INTEGER, PARAMETER :: ImageWidth  = 256
  INTEGER, PARAMETER :: ImageHeight = 256
  INTEGER(GLubyte)   :: Image(0:2,0:ImageWidth-1,0:ImageHeight-1)

 !-------
 CONTAINS
 !-------

  !< Window Creation >----------

  SUBROUTINE myWindow

    INTEGER :: win

    CALL glutInitDisplayMode(ior(GLUT_RGBA, & ! Set the display mode,
                                 GLUT_DEPTH)) ! with depth (Z-buffer).
    CALL glutInitWindowPosition(100, 100)     ! Window position from top left in pixels.
    CALL glutInitWindowSize(500, 500)         ! Window size (width, height) in pixels.
    win = glutCreateWindow("OpenGL Window")   ! Create the window.
    CALL glClearColor(0.0,0.0,0.0,0.0)        ! Fill the window with black.

    CALL glEnable(GL_DEPTH_TEST)              ! Enable hidden surface removal.
    CALL glDepthFunc(GL_LESS)

    CALL glShadeModel(GL_FLAT)                ! Flat shading.

    CALL makeImage()
    CALL glPixelStorei(GL_UNPACK_ALIGNMENT, 1)
    CALL glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP)
    CALL glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP)
    CALL glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST)
    CALL glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST)
    CALL glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, ImageWidth, ImageHeight, &
                      0, GL_RGB, GL_UNSIGNED_BYTE, &
                      reshape(Image,(/3*ImageWidth*ImageHeight/)))
    CALL glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_DECAL)
    CALL glEnable(GL_TEXTURE_2D)

  END SUBROUTINE myWindow

  !< Window Resize Handler >----------

  SUBROUTINE myResize(w, h)

    INTEGER, INTENT(INOUT) :: w, h                ! Current window width and height in pixels.
    DOUBLE PRECISION :: asp

    CALL glViewport(0, 0, w, h)                   ! Set viewport (in pixels).
    CALL glMatrixMode(GL_PROJECTION)              ! Set transformation matrix mode.
    CALL glLoadIdentity                           ! Initialise transformation matrix.
    asp = REAL(w)/REAL(h)
    CALL gluPerspective(60.D0, asp, 0.1D0, 20.D0)
    CALL glMatrixMode(GL_MODELVIEW)
    CALL glLoadIdentity
    CALL glTranslatef(0.0, 0.0, -3.6)

  END SUBROUTINE myResize

  !< Draw the window. >----------

  SUBROUTINE myDisplay

    CALL glClear(ior(GL_COLOR_BUFFER_BIT, &   ! Clear colours and
                     GL_DEPTH_BUFFER_BIT))    ! z buffer.

    CALL glBegin(GL_QUADS)

    CALL glTexCoord2f(0.0, 0.0); CALL glVertex3f(-2.0, -1.0, 0.0)
    CALL glTexCoord2f(0.0, 1.0); CALL glVertex3f(-2.0, 1.0, 0.0)
    CALL glTexCoord2f(1.0, 1.0); CALL glVertex3f(0.0, 1.0, 0.0)
    CALL glTexCoord2f(1.0, 0.0); CALL glVertex3f(0.0, -1.0, 0.0)

    CALL glTexCoord2f(0.0, 0.0); CALL glVertex3f(1.0, -1.0, 0.0)
    CALL glTexCoord2f(0.0, 1.0); CALL glVertex3f(1.0, 1.0, 0.0)
    CALL glTexCoord2f(1.0, 1.0); CALL glVertex3f(2.41421, 1.0, -1.41421)
    CALL glTexCoord2f(1.0, 0.0); CALL glVertex3f(2.41421, -1.0, -1.41421)

    CALL glEnd()

    CALL glFlush                         ! Actually do the operations.

  END SUBROUTINE myDisplay

  !< Make a chequered image. >----------

  SUBROUTINE makeImage()
    INTEGER :: i, j, c, icenter, jcenter

    DO i = 0, ImageWidth-1
      DO j = 0, ImageHeight-1
        icenter = i / 32 * 32 + 15
        jcenter = j / 32 * 32 + 15
        IF (SQRT( DBLE((icenter-i)*(icenter-i) + (jcenter-j)*(jcenter-j)) ) < 15.5d0 .AND. &
            IAND(i,32)/=IAND(j,32)) THEN
          c = 255
        ELSE
          c = 0
        END IF
        Image(0,i,j) = c
        Image(1,i,j) = c
        Image(2,i,j) = c
      END DO
    END DO

  END SUBROUTINE makeImage

END MODULE myOpenGL
!==================================
!========== Main Program ==========
PROGRAM main

  USE myOpenGL                     ! Access our module.

  CALL glutInit                    ! Initialise the GLUT library.
  CALL myWindow                    ! Create our window.
  CALL glutReshapeFunc(myResize)   ! Use myResize to handle window size changes.
  CALL glutDisplayFunc(myDisplay)  ! Use myDisplay to draw the window.
  CALL glutMainLoop                ! Run the main event loop.

END PROGRAM main
!==================================

The program sections coloured in green are described below; for OpenGL/GLUT calls in the black portion of the program, refer to the previous template programs' documentation.

Subroutine glPixelStorei(pname,param)
Integer(glenum),Intent(In) :: pname
Integer(glint),Intent(In) :: param
Sets a pixel storage mode parameter. This parameter to be set is specified by pname; this program sets the GL_UNPACK_ALIGNMENT parameter, for which the value of param specifies the alignment requirements in terms of bytes. Possible values are 1, 2, 4 and 8 which specify that rows will be unaligned, aligned on 2-byte boundaries, etc..
Subroutine glTexParameteri(xtarget,pname,param)
Integer(glenum),Intent(In) :: xtarget,pname
Integer(glint),Intent(In) :: param
Sets a texture parameter. The texture whose parameter is to be set is specified by xtarget, which must be GL_TEXTURE_1D, GL_TEXTURE_2D, GL_TEXTURE_3D or GL_TEXTURE_CUBE_MAP. The parameter to set is specified by pname, and its value by param; for this program the relevant possibilities are:
GL_TEXTURE_MAG_FILTER: the texture magnification function (used when the pixel maps to one texture element or smaller), either to GL_LINEAR or GL_NEAREST;
GL_TEXTURE_MIN_FILTER: the texture minifying function (used when the pixel maps to an area greater than one texture element), to GL_LINEAR or GL_NEAREST (other functions are also available);
GL_TEXTURE_WRAP_S: the wrap parameter for texture coordinate S, typical values are GL_CLAMP (clamp S coordinates to the range 0-1) and GL_REPEAT (ignore the integer part of the S coordinate, producing a repeating pattern);
GL_TEXTURE_WRAP_T: the wrap parameter for texture coordinate T, same as for coordinate S.
Subroutine glTexImage2D(xtarget,level,components,width,border,format,xtype,pixels)
Integer(glenum),Intent(In) :: xtarget
Integer(glint),Intent(In) :: level,components
Integer(glsizei),Intent(In) :: width,height
Integer(glint),Intent(In) :: border
Integer(glenum),Intent(In) :: format,xtype
Integer(glubyte),Intent(In) :: pixels(:)
Specifies a two-dimensional texture image to be used in each graphical primitive for which texturing is enabled. The arguments are as follows.
xtarget: the target texture, which must be one of GL_PROXY_TEXTURE_2D, GL_PROXY_TEXTURE_CUBE_MAP, GL_TEXTURE_2D, GL_TEXTURE_CUBE_MAP_NEGATIVE_X, GL_TEXTURE_CUBE_MAP_NEGATIVE_Y, GL_TEXTURE_CUBE_MAP_NEGATIVE_Z, GL_TEXTURE_CUBE_MAP_POSITIVE_X, GL_TEXTURE_CUBE_MAP_POSITIVE_Y or GL_TEXTURE_CUBE_MAP_POSITIVE_Z;
level: the level of detail, where zero is the base image level, and N is the Nth mipmap reduction image;
components: the number of colour components, in the range 1-4 or one of the named constants GL_ALPHA, GL_ALPHA12, GL_ALPHA16, GL_ALPHA4, GL_ALPHA8, GL_COMPRESSED_ALPHA, GL_COMPRESSED_INTENSITY, GL_COMPRESSED_LUMINANCE, GL_COMPRESSED_LUMINANCE_ALPHA, GL_COMPRESSED_RGB, GL_COMPRESSED_RGBA, GL_DEPTH_COMPONENT, GL_DEPTH_COMPONENT16, GL_DEPTH_COMPONENT24, GL_DEPTH_COMPONENT32, GL_INTENSITY, GL_INTENSITY12, GL_INTENSITY16, GL_INTENSITY4, GL_INTENSITY8, GL_LUMINANCE, GL_LUMINANCE12, GL_LUMINANCE12_ALPHA12, GL_LUMINANCE12_ALPHA4, GL_LUMINANCE16, GL_LUMINANCE16_ALPHA16, GL_LUMINANCE4, GL_LUMINANCE4_ALPHA4, GL_LUMINANCE6_ALPHA2, GL_LUMINANCE8, GL_LUMINANCE8_ALPHA8, GL_LUMINANCE_ALPHA, GL_R3_G3_B2, GL_RGB, GL_RGB10, GL_RGB10_A2, GL_RGB12, GL_RGB16, GL_RGB4, GL_RGB5, GL_RGB5_A1, GL_RGB8, GL_RGBA, GL_RGBA12, GL_RGBA16, GL_RGBA2, GL_RGBA4, GL_RGBA8, GL_SLUMINANCE, GL_SLUMINANCE8, GL_SLUMINANCE8_ALPHA8, GL_SLUMINANCE_ALPHA, GL_SRGB, GL_SRGB8, GL_SRGB8_ALPHA8 or GL_SRGB_ALPHA;
width: the width of the texture image including any border;
height: the height of the texture image including any border;
border: the width of the border, which must be zero or 1;
format: the format of the pixel data, which must be one of GL_ALPHA, GL_BGR, GL_BGRA, GL_BLUE, GL_COLOR_INDEX, GL_GREEN, GL_LUMINANCE, GL_LUMINANCE_ALPHA, GL_RED, GL_RGB or GL_RGBA;
xtype: the type of the pixel data, which must be one of GL_BITMAP, GL_BYTE, GL_FLOAT, GL_INT, GL_SHORT, GL_UNSIGNED_BYTE, GL_UNSIGNED_BYTE_2_3_3_REV, GL_UNSIGNED_BYTE_3_3_2, GL_UNSIGNED_INT, GL_UNSIGNED_INT_10_10_10_2, GL_UNSIGNED_INT_2_10_10_10_REV, GL_UNSIGNED_INT_8_8_8_8, GL_UNSIGNED_INT_8_8_8_8_REV, GL_UNSIGNED_SHORT, GL_UNSIGNED_SHORT_1_5_5_5_REV, GL_UNSIGNED_SHORT_4_4_4_4, GL_UNSIGNED_SHORT_4_4_4_4_REV, GL_UNSIGNED_SHORT_5_5_5_1, GL_UNSIGNED_SHORT_5_6_5 or GL_UNSIGNED_SHORT_5_6_5_REV;
pixels: the pixel data in the specified format and type.
Subroutine glTexEnvi(xtarget,pname,param)
Integer(glenum),Intent(In) :: xtarget,pname
Integer(glint),Intent(In) :: param
Sets texture environment parameters. The arguments are as follows.
xtarget: must be GL_TEXTURE_ENV;
pname: must be GL_TEXTURE_ENV_MODE;
param: the environment parameter, which must be GL_BLEND, GL_DECAL, GL_MODULATE or GL_REPLACE.
Subroutine glEnable(cap)
Integer(glenum),Intent(In) :: cap
Enables the specified capability. For cap equal to GL_TEXTURE_2D, 2-dimensional texture mapping is enabled.

The result of executing OpenGL_20.f95:

Kind values

The values used for the OpenGL/GLUT kinds mentioned above are as follows.
Integer,Parameter :: glenum = int32
Integer,Parameter :: glint = int32


OpenGL21: 3D animation program

3D Animation Program

!===== 3D Animation Program =====< OpenGL21.f95>
MODULE myOpenGL

  USE opengl_gl      ! GL  (OpenGL Core library)
  USE opengl_glu     ! GLU (OpenGL Utility library)
  USE opengl_glut    ! GLUT(OpenGL Utility Toolkit)

  REAL, DIMENSION(4) :: L_position0     ! Light position.
  REAL, DIMENSION(4) :: lt_ambient
  REAL, DIMENSION(4) :: lt_diffuse
  REAL, DIMENSION(4) :: lt_specular
  REAL, DIMENSION(4) :: mt_ambient
  REAL, DIMENSION(4) :: mt_diffuse
  REAL, DIMENSION(4) :: mt_specular
  REAL               :: mt_shininess

  INTEGER :: time = 20  ! Timer period (milliseconds).

  REAL :: g      = 9.8
  REAL :: rad    = 0.0174533
  REAL :: length = 1.
  REAL :: height = 1.
  REAL :: omega  = 0.0
  REAL :: theta  = 30.
  REAL :: alpha  = 0.0
  REAL :: px     = 0.0
  REAL :: py     = 0.0
  REAL :: pz     = 0.0
  REAL :: dt     = 0.05

 !-------
 CONTAINS
 !-------

  !< Window Creation >----------

  SUBROUTINE myWindow

    INTEGER :: win

    CALL glutInitDisplayMode(ior(ior(GLUT_RGBA,   & ! Set the display mode,
                                     GLUT_DEPTH), & ! with depth (Z-buffer),
                                     GLUT_DOUBLE))  ! and double-buffering.
    CALL glutInitWindowPosition(100, 100)     ! Window position from top left in pixels.
    CALL glutInitWindowSize(500, 500)         ! Window size (width, height) in pixels.
    win = glutCreateWindow("OpenGL Window")   ! Create the window.
    CALL glClearColor(1.0,1.0,1.0,1.0)        ! Fill the window with white.

    CALL glEnable(GL_DEPTH_TEST)              ! Enable hidden surface removal.
    CALL glEnable(GL_CULL_FACE)               ! Enable culling.

    L_position0 = (/1.0,1.0,3.0,0.0/)         ! Light position.
    lt_ambient  = (/0.5,0.5,0.5,1.0/) ! Light source ambient property in RGBA.
    lt_diffuse  = (/0.2,0.2,1.0,1.0/) ! Light source diffusion property in RGBA.
    lt_specular = (/0.5,0.5,0.5,1.0/) ! Light source specular property in RGBA.
    CALL glLightfv(GL_LIGHT0, GL_POSITION, L_position0) ! Set light position.
    CALL glLightfv(GL_LIGHT0, GL_AMBIENT,  lt_ambient ) ! Set ambient property.
    CALL glLightfv(GL_LIGHT0, GL_DIFFUSE,  lt_diffuse ) ! Set diffusion.
    CALL glLightfv(GL_LIGHT0, GL_SPECULAR, lt_specular )! Set specular.
    CALL glEnable(GL_LIGHT0)                            ! Enable light source.
    CALL glEnable(GL_LIGHTING)                          ! Enable shading.

    mt_ambient  = (/0.1,0.1,0.1,1.0/) ! Material ambient property in RGBA.
    mt_diffuse  = (/0.0,0.0,1.0,1.0/) ! Material diffusion property in RGBA.
    mt_specular = (/0.5,0.5,1.0,1.0/) ! Material specular property in RGBA.
    mt_shininess = 128.               ! Material specular coefficient.
    CALL glMaterialfv(GL_FRONT, GL_AMBIENT,   mt_ambient )   ! Set surface ambient property.
    CALL glMaterialfv(GL_FRONT, GL_DIFFUSE,   mt_diffuse )   ! Set surface diffusion property.
    CALL glMaterialfv(GL_FRONT, GL_SPECULAR,  mt_specular )  ! Set surface specular property.
    CALL glMaterialf (GL_FRONT, GL_SHININESS, mt_shininess ) ! Set surface specular coefficient.

  END SUBROUTINE myWindow

  !< Window Resize Handler >----------

  SUBROUTINE myResize(w, h)

    INTEGER, INTENT(INOUT) :: w, h                ! Current window width and height in pixels.
    DOUBLE PRECISION :: asp

    CALL glViewport(0, 0, w, h)                   ! Set viewport (in pixels).
    CALL glMatrixMode(GL_PROJECTION)              ! Set transformation matrix mode.
    CALL glLoadIdentity                           ! Initialise transformation matrix.
    asp = REAL(w)/REAL(h)
    CALL gluPerspective(30.D0, asp, 0.1D0, 10.D0)
    CALL glTranslatef(0.0, 0.0, -3.6)
    CALL glMatrixMode(GL_MODELVIEW)               ! Set model view matrix.
    CALL glLoadIdentity
    CALL gluLookAt(0.D0,0.D0,1.D0, &
                   0.D0,0.D0,0.D0, &
                   0.D0,1.D0,0.D0)

  END SUBROUTINE myResize

  !< Draw the window. >----------

  SUBROUTINE myDisplay

    CALL glClear(ior(GL_COLOR_BUFFER_BIT, &   ! Clear colours and
                     GL_DEPTH_BUFFER_BIT))    ! z buffer.
    CALL myAnimation
    CALL glutSwapBuffers               ! Actually paint the window by doing a buffer swap.

  END SUBROUTINE myDisplay

  !< Animation. >----------

  SUBROUTINE myAnimation

    CALL glBegin(GL_LINES)               ! Begin drawing lines.
      CALL glVertex3f(0.0,height,0.0)    ! Starting position.
      CALL glVertex3f(px,py,pz)          ! Ending position.
    CALL glEnd                           ! Finished drawing lines.

    CALL glPushMatrix                    ! Begin conversion.
      CALL glShadeModel(GL_SMOOTH)       ! Smooth shading.
      CALL glTranslatef(px,py,pz)        ! Translate ball.
      CALL glutSolidSphere(0.05D0,10,10) ! Draw ball.
    CALL glPopMatrix

  END SUBROUTINE myAnimation

  !< Timer function. >----------

  RECURSIVE SUBROUTINE myTimer( TimerNo )

    INTEGER, INTENT(INOUT) :: TimerNo

    IF( TimerNo == 1 ) THEN
      CALL glutTimerFunc(time,myTimer,1) ! Set timer function.

      alpha = - g*sin( theta*rad ) / length
      omega = omega + alpha*dt
      theta = theta + omega*dt/rad
      px = length*sin(theta*rad)
      py = height - length*cos(theta*rad)

      CALL glutPostRedisplay
    END IF

  END SUBROUTINE myTimer

END MODULE myOpenGL
!==================================
!========== Main Program ==========
PROGRAM main

  USE myOpenGL                       ! Access our module.

  CALL glutInit                      ! Initialise the GLUT library.
  CALL myWindow                      ! Create our window.
  CALL glutReshapeFunc(myResize)     ! Use myResize to handle window size changes.
  CALL glutDisplayFunc(myDisplay)    ! Use myDisplay to draw the window.
  CALL glutTimerFunc(time,myTimer,1) ! Set timer function.
  CALL glutMainLoop                  ! Run the main event loop.

END PROGRAM main
!==================================

The program sections coloured in green are described below; for OpenGL/GLUT calls in the black portion of the program, refer to the previous template programs' documentation.

Subroutine glutTimerFunc(millis,timerfunc,value)
Integer(glcuint),Intent(In) :: millis
Interface
  Subroutine timerfunc(value)
  Use opengl_kinds
  Integer(glcint),Intent(InOut) :: value
  End Subroutine
End Interface
Integer(glcint),Intent(In) :: value
Adds a timer callback procedure that will not be triggered for at least millis milliseconds. At that time, timerfunc will be called with its value argument set to the value argument from this call.
Subroutine glutPostRedisplay
Marks the current window as needing to be redisplayed; the next iteration through the GLUT main event loop will call the window's display routine.

The result of executing OpenGL_21.f95:

Kind values

The values used for the OpenGL/GLUT kinds mentioned above are as follows.
Integer,Parameter :: glcuint = int32
Integer,Parameter :: glcint = int32


FAQ – Frequently Asked Questions

FAQ - Frequently Asked Questions

  1. What versions of Windows can the Fortran Builder be used with? Answer.
  2. Why can I not Build or Run my program (the buttons are greyed out)? Answer.
  3. What is the difference between [Compile], [Build] and [Rebuild]? Answer.
  4. What do the ‘.a’ and ‘.o’ file extensions mean? Answer.
  5. I created a new file in my project folder and now builds fail; what is wrong? Answer.
  6. The Fortran Builder says it cannot find my NAG Library installation; how do I tell it where to find the NAG Library? Answer.
  7. How can I use CDABS, DCMPLX, DCONJG, DIMAG and DREAL? Answer.
  8. Are non-standard specific intrinsic functions such as CDEXP available? Answer.
  9. Is there a DTIME or ETIME function? Answer.
  10. Is there a FLUSH procedure? Answer.
  11. Is there a GETENV procedure? Answer.
  12. Is there a SYSTEM procedure? Answer.
  13. Can I use ‘$’ in a format to suppress newline? Answer.
  14. How can I compile a very old (Fortran 66/77) program without getting errors? Answer.
  15. What does the warning “TAB format input” mean? Answer.
  16. Why does the message “Byte count on numeric data type” appear? Answer.
  17. Why do I get the message “KIND value does not specify a valid representation method” with the NAG compiler? Answer.
  18. What does “Buffer overflow on output” mean? Answer.
  19. Why does my program not “Pause on exit” when I run it from the command line, even though I built it with that option? Answer.
  20. Why do I get the message “Variable X size of N bytes is too big”? Answer.
  21. How can I control the maximum size of a named constant (PARAMETER)? Answer.
  22. When doing mixed-language programming, what are the functions __NAGf90_rts_init and __NAGf90_io_finish? Answer.
  23. On program termination, the warning “Floating underflow occurred”; how can I find out where this is happening? Answer.
  24. On program termination, the warning “Floating underflow occurred”; how can I stop this warning from appearing? Answer.
  25. How can I read unformatted files written on a system with a different file format (e.g. endianness)? Answer.
  26. How can I write unformatted files so they can be read on a system with a different file format (e.g. endianness)? Answer.
  27. Is it possible to redistribute applications built with the Fortran Builder? Answer.
  28. The Fortran Builder has terminated with “External Exception EEFFACE”, what does this mean and how can I recover? Answer.
  29. How should RANDOM_SEED be used to initialise the random number generator? Answer.
Question: What versions of Windows can the Fortran Builder be used with?
Answer:
  • Windows 7 / 8.1 / 10

On 32-bit Windows, only 32-bit applications can be built.
On 64-bit Windows, both 64-bit and 32-bit applications can be built.

Question: Why can I not Build or Run my program (the buttons are greyed out)?
Answer:

Perhaps your program is already running? If your program is already running, you need to stop it before attempting to Build it or Run it again. You can do that by selecting [Run | Stop program] or by clicking the Stop button.

Question: What is the difference between [Compile], [Build] and [Rebuild]?
Answer:

[Compile] compiles the currently-active file in the edit pane, whether it is part of the current project or not; this will only produce an object file, not an executable file or library file.

[Build] builds the current project; in Quick Execution mode, it compiles and links the currently-active file to produce an executable file.

[Rebuild] cleans the project (deleting Dependent Files and object files) and then builds the project.

Question: What do the ‘.a’ and ‘.o’ file extensions mean?
Answer:

The tools underlying the Fortran Builder use the ‘.a’ file extension for static libraries (including DLL import libraries) and the ‘.o’ extension for object files; they are equivalent to Microsoft's ‘.lib’ and ‘.obj’ respectively.

Question: I created a new file in my project folder and now builds fail; what is wrong?
Answer:

The build system used by the Fortran Builder recognises a number of file extensions apart from the obvious ones you see in the product documentation. In some cases the presence of such a file may result in Fortran Builder taking build actions that are not desired.

  1. All file extensions that may be used by Fortran Builder should be reserved for files of the appropriate type within the project, that is: .a, .c, .cc, .def, .dll, .exe, .f, .f90, .f95, .ff, .ff90, .ff95, .h, .make, .mod and .o.
  2. Other file extensions that are recognised by the underlying build system should be avoided, these are .ch, .cpp, .dvi, .el, .elc, .info, .l, .ln, .out, .p, .r, .s, .sh, .sym, .tex, .texinfo, texi, .txinfo, .w, .web and .y.
Question: The Fortran Builder says it cannot find my NAG Library installation; how do I tell it where to find the NAG Library?
Answer:

The location of the NAG Fortran Library is determined from the registry, so this message should not appear unless the library was moved after installation (not recommended). If the registry information is missing or incorrect, and the NAG Fortran Library was not installed in the default location, the new installation directory must appear in either the LIB or PATH environment variable. To set an environment variable for the Fortran Builder only (without changing its value elsewhere), use the [Tool | Environment Variable Settings] menu item; note that the Fortran Builder will need to be restarted after this has been done.

Question: How can I use CDABS, DCMPLX, DCONJG, DIMAG and DREAL?
Answer: These are not standard Fortran intrinsic functions, though they are a common extension. We recommend that they be converted to standard Fortran using the following table.
Specific | Equivalent Modern Fortran Generic Intrinsic Function
CDABS(A) | Abs(a)
DCMPLX(X,Y) | Cmplx(x,y,Kind=Kind(0d0))
DCONJG(Z) | Conjg(z)
DIMAG(Z) | Aimag(z)
DREAL(Z) | Real(z)

Alternatively, the ‘−dcfuns’ option can be used to make the compiler recognise these functions. This option is available in the Fortran Builder via [Project | Project Settings... | Fortran Compiler | Basic Settings].
Question: Are non-standard specific intrinsic functions such as CDEXP available?
Answer:

No. These functions have never been part of any Fortran standard, and there is not universal agreement on their spelling.

However, they are never needed: just use the standard generic intrinsic functions: ABS, ACOS, ASIN, ATAN, ATAN2, CONJG, COS, COSH, DIM, EXP, LOG, LOG10, MAX, MIN, SIGN, SIN, SINH, SQRT, TAN and TANH can all be applied to any precision Real (and where appropriate, Complex) data.

If you have a program that uses a specific intrinsic (non-standard or standard) that consists of a prefix in front of one of the functions listed above, removing the prefix (usually C, CD, CQ, D, Q or Z) is nearly always the right thing to do; for example, references to an intrinsic CEXP, DEXP, CDEXP, CQEXP, DCEXP, QEXP, ZEXP can all safely be replaced by EXP.

For a few functions, the rule is slightly different: x INT and x NINT, where x is one of the prefixes listed above, should be changed to AINT or ANINT respectively.

Question: Is there a DTIME or ETIME function?
Answer: No.

These functions are not standard Fortran; their functionality is provided by the standard Fortran intrinsic subroutines CPU_TIME and SYSTEM_CLOCK. If you have a package that wants to use the DTIME and/or ETIME procedures, you can add one or two of the following examples to your code. The first example provides DTIME and ETIME> written entirely in standard Fortran 95 (and thus will work on any Fortran 95 compiler); the second provides DTIME and ETIME using the NAG Fortran Compiler interface to Posix.

NOTE: By design, the DTIME and ETIME functions are not and cannot be thread-safe. If your code might be executed in a multi-threaded environment, you should use SYSTEM_CLOCK to measure elapsed time.

! DTIME in standard Fortran.
Real Function dtime(time)
  Real time(2)
  Double Precision,Save :: last_time = 0
  Double Precision this_time
  Intrinsic Cpu_Time
  Call Cpu_Time(this_time)
  time(1) = this_time - last_time
  time(2) = 0
  dtime = time(1)
  last_time = this_time
End Function
! DTIME via NAG Fortran Compiler Posix module.
Real Function dtime(time)
  Use F90_Unix_Env,Only:tms,times
  Real time(2)
  Type(tms),Save :: lastbuf
  Logical :: start = .True.
  Type(tms) buffer
  Integer junk
  junk = times(buffer)
  If (start) Then
    lastbuf%utime = 0
    lastbuf%stime = 0
    start = .false.
  End If
  time(1) = buffer%utime - lastbuf%utime
  time(2) = buffer%stime - lastbuf%stime
  dtime = time(1) + time(2)
  lastbuf = buffer
End Function
! ETIME in standard Fortran.
Real Function etime(time)
  Real time(2)
  Call Cpu_Time(etime)
  time(1) = etime
  time(2) = 0
End Function
! ETIME via NAG Fortran Compiler Posix module.
Real Function etime(time)
  Use F90_Unix_Env,Only:tms,times
  Real time(2)
  Type(tms) buffer
  Integer junk
  junk = times(buffer)
  time(1) = buffer%utime
  time(2) = buffer%stime
  etime = buffer%utime + buffer%stime
End Function
Question: Is there a FLUSH procedure?
Answer: Yes.

The NAG Fortran Compiler has a number of built-in modules to provide access to a large number of Posix-related system calls. In order to access these, the appropriate module must be accessed with a USE statement. The FLUSH routine is in the F90_UNIX_IO module.

However, from Fortran 2003 this functionality is available through the FLUSH statement; we recommend that this be used in new programs. Here is a simple example showing how to use it.

Program slow_dots
!
! This program prints 10 dots, one per second.
!
  Use Iso_Fortran_Env,Only:output_unit
  Implicit None
  Integer i
  Do i = 1,10
    Write(*,'(a)',Advance='No') '.'
    Call delay
    Flush(output_unit)
  End Do
  Print *,'Done.'
Contains
  Subroutine delay
    Integer per_sec,start,now
    Intrinsic System_Clock
    Call System_Clock(Count=start,Count_Rate=per_sec)
    If (start==-huge(start)) Stop 'No clock.'
    Do
      Call System_Clock(Count=now)
      If (now<start .Or. now>=start+per_sec) Exit
    End Do
  End Subroutine
End Program
Question: Is there a GETENV procedure?
Answer: Yes.

The NAG Fortran Compiler has a number of built-in modules to provide access to a large number of Posix-related system calls. In order to access these, the appropriate module must be accessed with a USE statement. The GETENV routine is in the F90_UNIX_ENV module.

However, from Fortran 2003 this functionality is available through the standard intrinsic procedure GET_ENVIRONMENT_VARIABLE; we recommend that this be used in new programs. Here is a simple example showing how to use it.

Program environment_example
!
! This program displays the values of the environment
! variables FRED and USERNAME (if they exist).
!
  Implicit None
  Call show('FRED')
  Call show('USERNAME')
Contains
  Subroutine show(name)
    Character(*),Intent(In) :: name
    Character(:),Allocatable :: value
    Integer n,s
    Intrinsic Get_Environment_Variable
    Call Get_Environment_Variable(name,Status=s,Length=n)
    If (s==1) Then
      Print *,'Variable "',name,'" does not exist.'
    Else If (s/=0) Then
      Print *,'Error',s,'for variable "',name,'"'
    Else
      Allocate(Character(n) :: value)
      Call Get_Environment_Variable(name,Value=value)
      Print *,'Variable "',name,'" value is "',value,'".'
    End If
  End Subroutine
End Program
Question: Is there a “SYSTEM” procedure?
Answer: Yes. The NAG Fortran Compiler has a number of built-in modules to provide access to a large number of Posix system calls. In order to access these, the appropriate module must be accessed with a USE statement. The SYSTEM routine is in the F90_UNIX_PROC module.

However, from Fortran 2008 this functionality is available through the standard intrinsic procedure EXECUTE_COMMAND_LINE; we recommend that this be used in new programs. Here is a simple example showing how to use it.
Program system_example
  Implicit None
  Call execute_command_line('dir')
End Program
Question: Can I use ‘$’ in a format to suppress newline?
Answer:

No, the NAG Fortran Compiler does not accept this extension.

This extension is completely obsolete with the introduction, by Fortran 90, of non-advancing input/output. Here is an example of how to produce a prompt with standard Fortran.

    Program prompting
      Character(80) name
      Write (*,90000,Advance='No')
90000 Format('What is your name? ')
      Read *, name
      Print *, 'Hello ', Trim(name)
    End Program
Question: How can I compile a very old (Fortran 66/77) program without getting errors?
Answer:

The Fortran Builder carries out a strict check for conformance to the Fortran standard and also carries out a large number of checks for obviously incorrect code. While this is the correct behaviour for a compiler when new code is being developed, it is sometimes necessary to reduce the stringency of error checking to allow older code written to lower standards to compile. There are a number of compiler options to compile such legacy code.

−dusty
Downgrades a number of common errors found in legacy code to warnings. Hence compilation can continue; these warnings can be suppressed by the ‘−w’ option. This option implies the ‘−mismatch_all’ option.
−mismatch
Downgrades errors resulting from mismatch in argument lists to warnings. Calls to routines in the same file must still be correct.
−mismatch_all
As ‘−mismatch’, but even incorrect calls to routines in the same file are accepted.

These options can be found in the Fortran Builder under [Project | Project Settings... | Fortran Compiler | Basic Settings].
Question: What does the warning “TAB format input” mean?
Answer: TAB format is an extension to Fortran 77, and operates when TAB characters are found in fixed form source files. Because it is an extension, a warning message is produced. This format is a bit complicated, and not recommended for new programs (use free form source instead).
Question: Why does the message “Byte count on numeric data type” appear?
Answer:

This is an extension to Fortran 77 that was made obsolete by Fortran 90. Instead of specifying the number of bytes, Fortran 90 has kinds of each datatype, and intrinsic functions for choosing a kind based on the desired properties (SELECTED_INT_KIND and SELECTED_REAL_KIND). The NAG Fortran Compiler also provides a module, F90_KIND, which has named constants for convenient kind selection (the names for Integer and Real/Complex are also available from the standard intrinsic module ISO_FORTRAN_ENV). The equivalence between byte sizes and kinds using these names is as follows.

Type * Byte Size | Type(Kind Name)
INTEGER*1 | Integer(int8)
INTEGER*2 | Integer(int16)
INTEGER*4 | Integer(int32)
INTEGER*8 | Integer(int64)
LOGICAL*1 | Logical(byte)
LOGICAL*2 | Logical(twobyte)
LOGICAL*4 | Logical(word)
LOGICAL*8 | Logical(logical64)
REAL*4 | Real(real32)
REAL*8 | Real(real64)
REAL*16 | Real(real128)
COMPLEX*8 | Complex(real32)
COMPLEX*16 | Complex(real64)
COMPLEX*32 | Complex(real128)

The kind of an integer or real constant is specified by appending an underscore and the kind value (or name); e.g. 120_int8 is an 8-bit integer constant, and 3.14159265358979323846264338327950288_real128 is a 128-bit real value.

Question: Why do I get the message “KIND value does not specify a valid representation method” with the NAG compiler?
Answer:

The interpretation of kind values depends on the compiler. There are at least two obvious methods: sequential (1 to N, where N is the number of kinds) and byte (use the number of bytes for Integer and Real type). The NAG Fortran Compiler (and some other compilers) by default uses sequential kind numbering, so single and double precision real are REAL(1) and REAL(2), not REAL(4) and REAL(8). The disadvantage of the so-called “byte” scheme is that for the Complex type, the setting is the number of bytes for each part, i.e. half the total, which can be confusing. The NAG Fortran Compiler also offers “unique” kind values; in this mode, the kind values are unique for each type, allowing diagnosis of the mistake of using, for example, a REAL kind value to specify an INTEGER type.

The kind mode can be found in the Fortran Builder under [Project | Project Settings... | Fortran Compiler | Basic Settings].

Question: What does “Buffer overflow on output” mean?
Answer:

This means that your program attempted a sequential write, in a single record, with more bytes than will fit into the file buffer for that unit. The default buffer size for formatted input/output is 65536 bytes; for unformatted input/output, the default is 231−1 for record files and unlimited for stream files.

To change the buffer size you can use the RECL= specifier in the OPEN statement for the file you wish to write. For example,
      Open(13,File="myfile",Form="Formatted",Recl=200000)
will establish a buffer size of 200000 bytes on unit 13.

Note that Fortran provides the IOLENGTH= specifier in the INQUIRE statement to discover the needed value for RECL= for an unformatted file. For example,
      Inquire(Iolength=n) big_array
      Open(13,File="dump",Form="Unformatted",Recl=N)
will establish a sufficiently large buffer for unit 13 to allow the entirety of big_array to be read or written in one input/output statement.

An unlimited buffer size can be established for formatted input/output by using the Fortran 2003 feature “stream access”; however, this will disable the BACKSPACE statement on that unit. For example,
      Open(13,File="list",Form="Formatted",Access="Stream")
will open unit 13 for stream access, enabling formatted input/output of records of unlimited length, but disabling the ability to backspace the unit.

Question: Why does my program not “Pause on exit” when I run it from the command line, even though I built it with that option?
Answer: The “Pause on exit” option is a runtime option, not a build option. To make your program pause on exit you need to define the environment variable NAGFORTRAN_PAUSE_ON_EXIT (to be something non-null). Conversely, if you do not want your program to pause on exit you should not define that environment variable.
Question: Why do I get the message “Variable X size of N bytes is too big”?
Answer:

This means that your variable is larger than the maximum object size supported by the Fortran Builder's current mode. The maximum object size supported by the Fortran Builder is as follows

Application Bitness | Variable Size Limit
32-bit | 2GB
64-bit | 1TB

These limits also apply to the total amount of memory used by variables at runtime.

Question: How can I control the maximum size of a named constant (PARAMETER)?
Answer:

The maximum size of a named constant is controlled with the −max_parameter_size= option. This takes a limit in megabytes (MB); the default is −max_parameter_size=50. In the Fortran Builder, to specify this option use the Additional Options tab of the Fortran Compiler pane of Project Settings; use the [Add] button to manually specify the option.

Question: When doing mixed-language programming, what are the functions __NAGf90_rts_init and __NAGf90_io_finish?
Answer:

These functions are needed when the main program is in C instead of Fortran. The __NAGf90_rts_init function initialises the Fortran environment, including the floating-point status, command-line arguments, and input/output subsystem. The __NAGf90_io_finish function writes the contents of all the Fortran output buffers to their files, and closes all the Fortran files. The following example shows how to use these functions.

int main(int argc,char *argv[])
{
  __NAGf90_rts_init(argc,argv);
  /* Fortran routines can be safely called here. */
  __NAGf90_io_finish();
  return 0;
}

Note: In previous releases, these functions were called f90_init and f90_io_finish; the old names will still work for an old program, but are now considered to be part of the user namespace, and a new program can use these names itself without conflict.

Question: On program termination, the warning “Floating underflow occurred”; how can I find out where this is happening?
Answer:

Floating underflow is quite common in programs, and is rarely a problem. If it is a problem, you can set the IEEE halting mode for underflow to cause the program to stop when it happens; note that you should also set the “Traceback for runtime errors (−gline)” option so that the location will be reported. In the Fortran Builder this option is on the Detail (1) tab of the Fortran Compiler pane of Project Settings.

The following program shows how to use IEEE halting mode to cause termination on underflow.

Program underflow_halt
  Use Ieee_Exceptions
  Implicit None
  Call Ieee_Set_Halting_Mode(Ieee_Underflow, .True.)
  Call make_underflow(0.5)
Contains
  Subroutine make_underflow(x)
    Real, Intent(In) :: x
    Real :: y
    Integer :: n
    y = x
    n = 1
    Do
      y = y**2
      If (y==0) Exit
      n = n + 1
      Print *, 'Step', n, 'value', y
    End Do
    Print *, 'Zero reached at step', n
  End Subroutine
End Program
Question: On program termination, the warning “Floating underflow occurred”; how can I stop this warning from appearing?
Answer:

The Floating underflow warning can be suppressed in two ways:

  1. the underflow flag can be set to false before program termination;
  2. the compile-time option −no_underflow_warning can be used when compiling the main program – in the Fortran Builder this option is on the Details(1) tab of the Fortran Compiler pane of Project Settings.

The following program shows how to use IEEE halting mode to turn the underflow flag off prior to program termination.

Program turn_underflow_flag_off
  Use Ieee_Exceptions
  Implicit None
  Call make_underflow(0.5)
  Call Ieee_Set_Flag(Ieee_Underflow, .False.)
Contains
  Subroutine make_underflow(x)
    Real, Intent(In) :: x
    Real :: y
    Integer :: n
    y = x
    n = 1
    Do
      y = y**2
      If (y==0) Exit
      n = n + 1
      Print *, 'Step', n, 'value', y
    End Do
    Print *, 'Zero reached at step', n
  End Subroutine
End Program
Question: How can I read unformatted files written on a system with a different file format (e.g. endianness)?
How can I write unformatted files so they can be read on a system with a different file format (e.g. endianness)?
Answer:

Unformatted file conversion is provided by three mechanisms:

  1. the −convert= option;
  2. the CONVERT= specifier on the OPEN statement;
  3. the FORT_CONVERTn environment variable.

Unformatted file conversion affects both reading and writing, so the same mechanism provides the answer for both questions.

The most common conversion requirement is for big-endian files with all floating-point data in IEEE format; this is provided in the Fortran Builder by the “Unformatted I/O conversion (−convert=big_ieee)” option which is on the Detail (1) tab of the Fortran Compiler pane of Project Settings.

For full details of the conversion mechanisms please refer to the NAG Fortran Compiler Release 7.1 Manual; compiler options are explained in section 2.4, and the specifier and environment variable are explained in section 5.1.4.

Question: Is it possible to redistribute applications built with the Fortran Builder?
Answer:

Yes, it is possible. If no graphical or numerical libraries have been used, using the “Link with static nagfor runtime library (-unsharedrts)” link option will produce a standalone executable that will work on other compatible machines. This option can be found in the Fortran Builder under [Project | Project Settings... | Link | Options].

If a library has been used there might be a dependency on one or more DLLs; detailed guidelines are provided in the Fortran Builder Operation Manual; for 32-bit applications the details are here, and for 64-bit applications the details are here.

Question: The Fortran Builder has terminated with “External Exception EEFFACE”, what does this mean and how can I recover?
Answer:

This exception can occur if the Fortran Builder runs out of memory; it is very unlikely to happen unless you have hundreds of files and many thousands of variables. If you are using 64-bit Windows, you can use FortranBuilder_3G.exe instead of FortranBuilder.exe; this version is set to be “Large Address Aware”, which increases the amount of memory available to the Fortran Builder to approximately 3GB (from 2GB).

To permanently change to using the “3G” version, you can rename FortranBuilder.exe to FortranBuilder_Original.exe and then rename FortranBuilder_3G.exe to FortranBuilder.exe.

The default location of these files is C:\Program Files (x86)\NAG\EFBuilder 6.1\bin.

If you are using 32-bit Windows, you can recover the Fortran Builder by deleting all the “.fif” (Fortran Info) files in the project folder. This will allow it to operate on that project again, but if you attempt to do any debugging they will be recreated and you will again risk running out of memory.

Question: How should RANDOM_SEED be used to initialise the random number generator?
Answer:

  • RANDOM_SEED is not necessary to initialise the random number generator, provided you are happy to get a different sequence with each execution. When you use RANDOM_NUMBER the generator will be initialised automatically.

    Here is an example:

    Program unique_sequences
  Implicit None
  Print *,'First sequence'
  Call show_random(8)
  Print *,'Second (different) sequence'
  Call show_random(8)
Contains
  Subroutine show_random(n)
    Integer,Intent(In) :: n
    Real x(n)
    Call Random_Number(x)
    Print 1,x
1   Format(99F8.5)
  End Subroutine
End Program

  • RANDOM_NUMBER is the Mersenne Twister; this generator has a large amount of state (630 32-bit integers) and incorrect initialisation can result in poor quality numbers being generated. Therefore it is recommended that RANDOM_SEED only be used to replay a previous sequence.

    Here is an example:

    Program sequence_restarting
  Implicit None
  Integer rsize
  Integer,Allocatable :: rseed(:)
  Call Random_Seed(Size=rsize) ! Get the size of the seed (630 for NAG).
  Allocate(rseed(rsize))       ! Allocate an array to save it.
  Call Random_Seed(Get=rseed)  ! Save it.
  Print *,'First sequence'
  Call show_random(8)
  Call Random_Seed(Put=rseed)  ! Restart the sequence at the saved state.
  Print *,'Second (restarted) sequence'
  Call show_random(8)
Contains
  Subroutine show_random(n)
    Integer,Intent(In) :: n
    Real x(n)
    Call Random_Number(x)
    Print 1,x
1   Format(99F8.5)
  End Subroutine
End Program

  • In the case of wanting the same sequence with every execution, you can use RANDOM_SEED with your own seed data. The Mersenne Twister state is a random bit sequence and it should therefore have approximately equal numbers of zero and one bits. If you do not have 630 32-bit integers worth of random data, you should set the remaining elements of the seed array to zero so that the generator will know that these do not contain any useful entropy.

    Here is an example:

    Program repeatable_sequences
  Implicit None
  Integer rsize
  Integer,Allocatable :: rseed(:)
  Call Random_Seed(Size=rsize) ! Get the seed size.
  Allocate(rseed(rsize))       ! Allocate the seed.
  rseed(1) = Int(z'1f2d3b5a')  ! Assign the "random" values we have.
  rseed(2:) = 0                ! Set the rest to zero.
  Call Random_Seed(Put=rseed)  ! Initialise the generator.
  Print *,'First sequence (always the same)'
  Call show_random(8)
  Call Random_Seed(Put=rseed)  ! Re-initialise the generator.
  Print *,'Second sequence (also always the same)'
  Call show_random(8)
Contains
  Subroutine show_random(n)
    Integer,Intent(In) :: n
    Real x(n)
    Call Random_Number(x)
    Print 1,x
1   Format(99F8.5)
  End Subroutine
End Program


Known Problems

  • The ability to use the GTK+ library in 32-bit mode with the −compatible option has been removed, as it cannot work reliably (different argument passing convention for callbacks).

  • If the name of a source file contains an apostrophe, Build (and also Compile and Link) will not work. For example, “bad'prog.f90” or “C:\bad'folder\abc.f90”

  • If an external link library specified in [ Project Settings | Link | Libraries ] has a name beginning with “lib”, and there is a file in the current working directory that has the same name and the extension .lib, .a or .dll, a link error is very likely on build as the local file will be referenced instead of the external file.

  • When a source file is polished, any lexical error messages will be reported with the line number in the original source file (before polishing). If the polished file was free form source, you can jump to the error line simply by using Ctrl-Z to revert the polish then double-clicking the error message.


Copyright Notice

Copyright Notice for the Fortran Builder.

The Fortran Builder is
Copyright © 2007-2022 by The Numerical Algorithms Group Ltd., Oxford, U.K.

All Wallpaper functions, searching functions and parts of the Editor functions of the Fortran Builder are
Copyright © 2005-2022 by Gou Nakano. All Rights Reserved.


NAG Fortran Builder 7.0 Release Notes

1 Introduction

This document describes the changes to the user interface and supported software in Release 7.0 of the NAG Fortran Builder Integrated Development Environment.

2 Fortran Compiler Project Settings

  • Conformance checking to a particular revision of the Fortran standard now includes Fortran 2018. The default remains Fortran 2008.
  • Support for coarray parallel execution is enabled via the Basic Settings page of the Fortran Compiler panel in Project Settings. This also contains an optional setting for the number of images to execute (if parallel execution is enabled, but the number of images is not specified, the default is one image per hardware thread). Note that at Release 7.0 if the NAG Fortran Compiler, coarray parallel execution is incompatible with using OpenMP.
  • The new optimisation option for parallel coarray execution, -Onoteams, is located on the Detail(2) page of the panel.
  • The old setting for “Known number of images”, which was on the Detail(2) page of the panel, has been removed as it is superceded by the new controls. In the unlikely event of wishing to check constant subscripts against the number of images, without actually enabling parallel execution, simply set the number of images (for parallel execution) to the desired value on the Basic Settings page and then disable parallel execution.
  • The new option to make procedures RECURSIVE by default is located on the Detail(2) page of the Fortran Compiler panel.
  • The option to suppress underflow warnings, -no_underflow_warning, is no longer a Link option but a Fortran compiler option, and has therefore been moved from the Link Options panel to the Detail(1) page of the Fortran Compiler panel.
  • The automatic garbage collection option, -gc, has been moved from the Detail(1) page to the Detail(2) page as it is infrequently used.

3 Tool Changes

  • The Polish Settings panel can request alignment of double colons (in declarations) to a particular column. This option has no effect on statements where the specified column is already exceeded by the time polish reaches the double colon.
  • The Unify Precision tool can be made to leave floating-point entities that already have a kind specified as they are. The default is to Unify such entities. Changing to "Leave as is" makes the Unify Precision tool usable on programs that need to use a specific precision for some parts, and have that kind specified already.

4 Updated project support

  • The Simdem Application project is no longer provided as a built-in part of the Fortran Builder. Users wishing to use the Simdem library are encouraged to get the latest version from the author's website, https://www.simfit.org.uk/simdem.html.
  • The NAG Library Application project now supports the following NAG Fortran Library products:
    • Mark 27, 64-bit (NLW6I27DEL).
    • Mark 26, 64-bit (FLW6I26DEL).


Error handling

The error handling approach in C for Cairo has multiple elements:

  • When a method on an object fails, the object is put into an error state. Subsequent operations on the object do nothing. The status of the object can be queried with a function like status().

  • Constructors, rather than returning NULL on out-of-memory failure, return a special singleton object on which all operations do nothing. Retrieving the status of the singleton object returns CAIRO_STATUS_NO_MEMORY

    Is this going to apply to cairo_surface_t as well?

    What about cairo_copy_path_data()? It's probably going to have to return NULL.

  • Errors propagate from object to object. Setting a pattern in an out-of-memory state as the source of a cairo_t puts the type into an error state.

Much of the above is not yet implemented at the time of this writing

A language binding could copy the C approach, and for a language without exceptions, this is likely the right thing to do. However, for a language with exceptions, exposing a completely different style of error handling for cairo would be strange. So, instead, status should be checked after every call to cairo, and exceptions thrown as necessary.

One problem that can arise with this, in languages where handling exceptions is mandatory (like Java), is that almost every cairo function can result in a status being set, usually because of an out-of-memory condition. This could make cairo hard to use. To resolve this problem, let's classify then cairo status codes:

/* Memory */
CAIRO_STATUS_NO_MEMORY,

/* Programmer error */
CAIRO_STATUS_INVALID_RESTORE
CAIRO_STATUS_INVALID_POP_GROUP
CAIRO_STATUS_NO_CURRENT_POINT
CAIRO_STATUS_INVALID_MATRIX
CAIRO_STATUS_NO_TARGET_SURFACE
CAIRO_STATUS_INVALID_STRING
CAIRO_STATUS_SURFACE_FINISHED
CAIRO_STATUS_BAD_NESTING

/* Language binding implementation */
CAIRO_STATUS_NULL_POINTER
CAIRO_STATUS_INVALID_PATH_DATA
CAIRO_STATUS_SURFACE_TYPE_MISMATCH

/* Other */
CAIRO_STATUS_READ_ERROR
CAIRO_STATUS_WRITE_ERROR

If we look at these, the CAIRO_STATUS_NO_MEMORY should map to the native out-of-memory exception, which could happen at any point in any case. Most of the others indicate programmer error, and handling them in user code would be silly. These should be mapped into whatever the language uses for assertion failures, rather than errors that are normally handled. (In Java, a subclass of Error rather than Exception, perhaps.) And CAIRO_STATUS_READ_ERROR, and CAIRO_STATUS_WRITE_ERROR can occur only in very specific places. (In fact, as described in the section called “Streams and File I/O”, these errors may be mapped into the language's native I/O error types.) So, there really aren't exceptions that the programmer must handle at most points in the Cairo API.


Fonts

Fonts are once more an area where there is a hierarchy of types:

cairo_font_face_t
   cairo_ft_font_face_t
   cairo_win32_font_face_t
cairo_scaled_font_t
   cairo_ft_scaled_font_t
   cairo_win32_scaled_font_t

The methods on the subtypes are, however, not useful without bindings for fontconfig and FreeType or for the Win32 GDI, so most language bindings will choose not to bind these types.

The cairo_font_face_set_user_data(), and cairo_font_face_get_user_data() methods are provided for use in language bindings, and should not be directly exposed to applications.


Memory Management

The objects in cairo can roughly be divided into two types: reference-counted, opaque types like cairo_surface_t and plain structures like cairo_glyph_t. cairo_path_t and cairo_path_data_t are special cases and are treated separately in this appendix.

Refcounted opaque types all have a ..._reference() function to increase the refcount by one and a ..._destroy() to decrease the refcount by one. These should not be exposed to the user of the language binding, but rather used to implement memory management within the language binding. The simplest way to do memory management for a language binding is to treat the language binding object as a simple handle to the cairo object. The language binding object references the cairo object, and unreferences it when finalized. This is the recommended method, though there are a couple of caveats to be noted:

  • Equality won't work as expected. You can have two language objects for the same cairo and they won't necessarily compare equal. If the language allows customizing the equality operation, then this is fixable by comparing the underlying pointers. It also can be fixed by creating at most one language object per cairo object, and uniquifying via a pin table (a hash table that goes from cairo object to language object). For cairo_surface_t you can use also cairo_surface_set_user_data() instead of a separate pin table.

  • Derivation from the language object doesn't work because you can lose the language object while keeping the Cairo object. Code like:

    public class MySurface (ImageSurface) {
   public MySurface (width, height) {
      super (Format.ARGB32, width, height);
   }
   public int get42 () {
      return 42;
   }
}

   cr = Cairo(MySurface(width, height));
   surface = cr.getTarget();

    Can result in surface containing an ImageSurface not a MySurface. This is not easily fixable without creating memory leaks, and it's probably best to simply forbid deriving from the language objects.

When a plain structure is used as a return value from cairo, this is done by passing it as a “out parameter”.

cairo_font_extents_t extents;

cairo_font_extents (cr, &extents);

In a language binding, this should typically be treated as a return value:

FontExtents extents = cr.fontExtents ();

A language binding has a choice in how it implements the language objects for plain structures. It can use a pure language object with fields corresponding to those of the C structure, and convert from and to the C structure when calling cairo functions or converting cairo return values. Or it can keep a pointer to the C structure internally and wrap it inside a language object much like occurs for refcounted objects. The choice should be invisible to the user: they should be able to imagine that it is implemented as a pure language object.


Overloading and optional arguments

Function overloading (having a several variants of a function with the same name and different arguments) is a language feature available in many languages but not in C.

In general, language binding authors should use restraint in combining functions in the cairo API via function overloading. What may seem like an obvious overload now may turn out to be strange with future additions to cairo. It might seem logical to make cairo_set_source_rgb() an overload of cairo_set_source(), but future plans to add cairo_set_source_rgb_premultiplied(), which will also take three doubles make this a bad idea. For this reason, only the following pairs of functions should be combined via overloading

void
cairo_set_source (cairo_t *cr, cairo_pattern_t *source);

void
cairo_set_source_surface (cairo_t          *cr,
                          cairo_surface_t  *source,
                          double            surface_x,
                          double            surface_y);

void
cairo_mask (cairo_t         *cr,
        cairo_pattern_t *pattern);

void
cairo_mask_surface (cairo_t         *cr,
            cairo_surface_t *surface,
            double           surface_x,
            double           surface_y);

cairo_surface_t *
cairo_image_surface_create (cairo_format_t	format,
                int			width,
                int			height);
cairo_surface_t *
cairo_image_surface_create_for_data (unsigned char	       *data,
                     cairo_format_t		format,
                     int			width,
                     int			height,
                     int			stride);

cairo_status_t
cairo_surface_write_to_png (cairo_surface_t	*surface,
                const char		*filename);

cairo_status_t
cairo_surface_write_to_png_stream (cairo_surface_t	*surface,
                   cairo_write_func_t	write_func,
                   void			*closure);

cairo_surface_t *
cairo_image_surface_create_from_png (const char	*filename);

cairo_surface_t *
cairo_image_surface_create_from_png_stream (cairo_read_func_t	read_func,
                        void		*closure);

Note that there are cases where all constructors for a type aren't overloaded together. For example cairo_image_surface_create_from_png() should not be overloaded together with cairo_image_surface_create(). In such cases, the remaining constructors will typically need to be bound as static methods. In Java, for example, we might have:

Surface surface1 = ImageSurface(Format.RGB24, 100, 100);
Surface surface2 = ImageSurface.createFromPNG("camera.png");

Some other overloads that add combinations not found in C may be convenient for users for language bindings that provide cairo_point_t and cairo_rectangle_t types, for example:

void
cairo_move_to (cairo_t       *cr,
               cairo_point_t *point);
void
cairo_rectangle (cairo_t           *cr,
                 cairo_rectangle_t *rectangle);


cairo_path_t

The cairo_path_t type is one area in which most language bindings will differ significantly from the C API. The C API for cairo_path_t is designed for efficiency and to avoid auxiliary objects that would be have to be manually memory managed by the application. However, a language binding should not present cairo_path_t as an array, but rather as an opaque that can be iterated over. Different languages have quite different conventions for how iterators work, so it is impossible to give an exact specification for how this API should work, but the type names and methods should be similar to the language's mapping of the following:

typedef struct cairo_path_iterator cairo_path_iterator_t;
typedef struct cairo_path_element cairo_path_element_t;

cairo_path_iterator_t *
cairo_path_get_iterator (cairo_path_t *path);

cairo_bool_t
cairo_path_iterator_has_next (cairo_path_iterator_t *iterator);

cairo_path_element_t *
cairo_path_iterator_next (cairo_path_iterator_t *iterator);

cairo_path_element_type_t
cairo_path_element_get_type (cairo_path_element_t *element);

void
cairo_path_element_get_point (cairo_path_element_t *element,
                              int                   index,
                              double                *x,
                              double                *y);

The above is written using the Java conventions for iterators. To illustrate how the API for PathIterator might depend on the native iteration conventions of the API, examine three versions of the loop, first written in a hypothetical Java binding:

PathIterator iter = cr.copyPath().iterator();
while (cr.hasNext()) {
    PathElement element = iter.next();
    if (element.getType() == PathElementType.MOVE_TO) {
        Point p = element.getPoint(0);
        doMoveTo (p.x, p.y);
    }
}

And then in a hypothetical C++ binding:

Path path = cr.copyPath();
for (PathIterator iter = path.begin(); iter != path.end(); iter++) {
    PathElement element = *iter;
    if (element.getType() == PathElementType.MOVE_TO) {
        Point p = element.getPoint(0);
        doMoveTo (p.x, p.y);
    }
}

And then finally in a Python binding:

for element in cr.copy_path():
    if element.getType == cairo.PATH_ELEMENT_MOVE_TO:
        (x, y) = element.getPoint(0)
        doMoveTo (x, y);

While many of the API elements stay the same in the three examples, the exact iteration mechanism is quite different, to match how users of the language would expect to iterate over a container.

You should not present an API for mutating or for creating new cairo_path_t objects. In the future, these guidelines may be extended to present an API for creating a cairo_path_t from scratch for use with cairo_append_path() but the current expectation is that cairo_append_path() will mostly be used with paths from cairo_copy_path().


Patterns

The cairo C API allows for creating a number of different types of patterns. All of these different types of patterns map to cairo_pattern_t in C, but in an object oriented language, there should instead be a hierarchy of types. (The functions that should map to constructors for the various types are listed after the type, methods on that type are listed below)

cairo_pattern_t
      cairo_pattern_set_matrix()
      cairo_pattern_get_matrix()
   cairo_solid_pattern_t
   cairo_surface_pattern_t (cairo_pattern_create_for_surface())
         cairo_pattern_set_extend()
         cairo_pattern_get_extend()
         cairo_pattern_set_filter()
         cairo_pattern_get_filter()
   cairo_gradient_t
         cairo_pattern_add_color_stop_rgb()
         cairo_pattern_add_color_stop_rgba()
      cairo_linear_gradient_t (cairo_pattern_create_linear())
      cairo_radial_gradient_t (cairo_pattern_create_radial())


Multiple return values

There are a number of functions in the cairo API that have multiple out parameters or in-out parameters. In some languages these can be translated into multiple return values. In Python, what is:

cairo_user_to_device (cr, &x, &y);

can by mapped to:

(x, y) = cr.user_to_device (cr, x, y);

but many languages don't have provisions for multiple return values, so it is necessary to introduce auxiliary types. Most of the functions that require the auxiliary types require a type that would, in C, look like

typedef struct _cairo_point cairo_point_t;
struct _cairo_point {
    double x;
    double y;
}

The same type should be used both for functions that use a pair of coordinates as an absolute position, and functions that use a pair of coordinates as a displacement. While an argument could be made that having a separate “distance” type is more correct, it is more likely just to confuse users.

void
cairo_user_to_device (cairo_t *cr, double *x, double *y);

void
cairo_user_to_device_distance (cairo_t *cr, double *dx, double *dy);

void
cairo_device_to_user (cairo_t *cr, double *x, double *y);

void
cairo_device_to_user_distance (cairo_t *cr, double *dx, double *dy);

void
cairo_matrix_transform_distance (cairo_matrix_t *matrix, double *dx, double *dy);

void
cairo_matrix_transform_point (cairo_matrix_t *matrix, double *x, double *y);

void
cairo_get_current_point (cairo_t *cr, double *x, double *y);

There are also a couple of functions that return four values representing a rectangle. These should be mapped to a “rectangle” type that looks like:

typedef struct _cairo_rectangle cairo_rectangle_t;
struct _cairo_rectangle {
    double x;
    double y;
    double width;
    double height;
}

The C function returns the rectangle as a set of two points to facilitate rounding to integral extents, but this isn't worth adding a “box” type to go along with the more obvious “rectangle” representation.

Q: Would it make sense here to define a standard cairo_rectangle_round() method that language bindings should map?

void
cairo_stroke_extents (cairo_t *cr,
              double *x1, double *y1,
              double *x2, double *y2);

void
cairo_fill_extents (cairo_t *cr,
            double *x1, double *y1,
            double *x2, double *y2);


Streams and File I/O

Various places in the cairo API deal with reading and writing data, whether from and to files, or to other sources and destinations. In these cases, what is typically provided in the C API is a simple version that just takes a filename, and a complex version that takes a callback function. An example is the PNG handling functions:

cairo_surface_t *
cairo_image_surface_create_from_png (const char	*filename);

cairo_surface_t *
cairo_image_surface_create_from_png_stream (cairo_read_func_t read_func,
                        void             *closure);

cairo_status_t
cairo_surface_write_to_png (cairo_surface_t	*surface,
                const char		*filename);

cairo_status_t
cairo_surface_write_to_png_stream (cairo_surface_t	*surface,
                   cairo_write_func_t	write_func,
                   void			*closure);

The expectation is that the filename version will be mapped literally in the language binding, but the callback version will be mapped to a version that takes a language stream object. For example, in Java, the four functions above might be mapped to:

static public ImageSurface createFromPNG (String filename) throws IOException;
static public ImageSurface createFromPNG (InputStream stream) throws IOException;
public void writeToPNG (String filename) throws IOException;
public void writeToPNG (OutputStream stream) throws IOException;

In many cases, it will be better to implement the filename version internally using the stream version, rather than building it on top of the filename version in C. The reason for this is that will naturally give a more standard handling of file errors for the language, as seen in the above Java example, where createFromPNG() is marked as raising an exception. Propagating exceptions from inside the callback function to the caller will pose a challenge to the language binding implementor, since an exception must not propagate through the Cairo code. A technique that will be useful in some cases is to catch the exception in the callback, store the exception object inside a structure pointed to by closure, and then rethrow it once the function returns.

I'm not sure how to handle this for cairo_pdf_surface_create_for_callback(). Other than keep a “exception to rethrow” thread-specific variable that is checked after every call to a Cairo function.


Surfaces

Like patterns, surfaces, which use only the cairo_surface_t type in the C API should be broken up into a hierarchy of types in a language binding.

cairo_surface_t
    cairo_image_surface_t
    cairo_atsui_surface_t
    cairo_win32_surface_t
    cairo_xlib_surface_t
    cairo_beos_surface_t

Unlike patterns, the constructors and methods on these types are clearly named, and can be trivially associated with the appropriate subtype. Many language bindings will want to avoid binding the platform-specific subtypes at all, since the methods on these types are not useful without passing in native C types. Unless there is a language binding for Xlib available, there is no way to represent a XLib Display * in that language.

This doesn't mean that platform-specific surface types can't be used in a language binding that doesn't bind the constructor. A very common situation is to use a cairo language binding in combination with a binding for a higher level system like the GTK+ widget toolkit. In such a situation, the higher level toolkit provides ways to get references to platform specific surfaces.

The cairo_surface_set_user_data(), and cairo_surface_get_user_data() methods are provided for use in language bindings, and should not be directly exposed to applications. One example of the use of these functions in a language binding is creating a binding for:

cairo_surface_t *
cairo_image_surface_create_for_data (unsigned char	       *data,
                     cairo_format_t		format,
                     int			width,
                     int			height,
                     int			stride);

The memory block passed in for data must be kept around until the surface is destroyed, so the language binding must have some way of determining when that happens. The way to do this is to use the destroy argument to cairo_surface_set_user_data().

Some languages may not have a suitable “pointer to a block of data” type to pass in for data. And even where a language does have such a type, the user will be frequently able to cause the backing store to be reallocated to a different location or truncated. Should we recommend a standard type name and binding for a buffer object here?


cairo_font_face_t

cairo_font_face_t — Base class for fonts

Synopsis

typedef     cairo_font_face_t;
cairo_font_face_t* cairo_font_face_reference
                                            (cairo_font_face_t *font_face);
void        cairo_font_face_destroy         (cairo_font_face_t *font_face);
cairo_status_t cairo_font_face_status       (cairo_font_face_t *font_face);
void*       cairo_font_face_get_user_data   (cairo_font_face_t *font_face,
                                             const cairo_user_data_key_t *key);
cairo_status_t cairo_font_face_set_user_data
                                            (cairo_font_face_t *font_face,
                                             const cairo_user_data_key_t *key,
                                             void *user_data,
                                             cairo_destroy_func_t destroy);
enum        cairo_font_type_t;
cairo_font_type_t cairo_font_face_get_type  (cairo_font_face_t *font_face);

Description

Details

cairo_font_face_t

typedef struct _cairo_font_face cairo_font_face_t;

A cairo_font_face_t specifies all aspects of a font other than the size or font matrix (a font matrix is used to distort a font by sheering it or scaling it unequally in the two directions) . A font face can be set on a cairo_t by using cairo_set_font_face(); the size and font matrix are set with cairo_set_font_size() and cairo_set_font_matrix().

cairo_font_face_reference ()

cairo_font_face_t* cairo_font_face_reference
                                            (cairo_font_face_t *font_face);

Increases the reference count on font_face by one. This prevents font_face from being destroyed until a matching call to cairo_font_face_destroy() is made.

font_face : | a cairo_font_face_t, (may be NULL in which case this function does nothing).
Returns : | the referenced cairo_font_face_t.

cairo_font_face_destroy ()

void        cairo_font_face_destroy         (cairo_font_face_t *font_face);

Decreases the reference count on font_face by one. If the result is zero, then font_face and all associated resources are freed. See cairo_font_face_reference().

font_face : a cairo_font_face_t

cairo_font_face_status ()

cairo_status_t cairo_font_face_status       (cairo_font_face_t *font_face);

Checks whether an error has previously occurred for this font face

font_face : | a cairo_font_face_t
Returns : | CAIRO_STATUS_SUCCESS or another error such as CAIRO_STATUS_NO_MEMORY.

cairo_font_face_get_user_data ()

void*       cairo_font_face_get_user_data   (cairo_font_face_t *font_face,
                                             const cairo_user_data_key_t *key);

Return user data previously attached to font_face using the specified key. If no user data has been attached with the given key this function returns NULL.

font_face : | a cairo_font_face_t
key : | the address of the cairo_user_data_key_t the user data was attached to
Returns : | the user data previously attached or NULL.

cairo_font_face_set_user_data ()

cairo_status_t cairo_font_face_set_user_data
                                            (cairo_font_face_t *font_face,
                                             const cairo_user_data_key_t *key,
                                             void *user_data,
                                             cairo_destroy_func_t destroy);

Attach user data to font_face. To remove user data from a font face, call this function with the key that was used to set it and NULL for data.

font_face : | a cairo_font_face_t
key : | the address of a cairo_user_data_key_t to attach the user data to
user_data : | the user data to attach to the font face
destroy : | a cairo_destroy_func_t which will be called when the font face is destroyed or when new user data is attached using the same key.
Returns : | CAIRO_STATUS_SUCCESS or CAIRO_STATUS_NO_MEMORY if a slot could not be allocated for the user data.

enum cairo_font_type_t

typedef enum _cairo_font_type {
    CAIRO_FONT_TYPE_TOY,
    CAIRO_FONT_TYPE_FT,
    CAIRO_FONT_TYPE_WIN32,
    CAIRO_FONT_TYPE_ATSUI
} cairo_font_type_t;

cairo_font_type_t is used to describe the type of a given font face or scaled font. The font types are also known as "font backends" within cairo.

The type of a font face is determined by the function used to create it, which will generally be of the form cairo_type_font_face_create. The font face type can be queried with cairo_font_face_get_type()

The various cairo_font_face functions can be used with a font face of any type.

The type of a scaled font is determined by the type of the font face passed to cairo_scaled_font_create. The scaled font type can be queried with cairo_scaled_font_get_type()

The various cairo_scaled_font functions can be used with scaled fonts of any type, but some font backends also provide type-specific functions that must only be called with a scaled font of the appropriate type. These functions have names that begin with cairo_type_scaled_font such as cairo_ft_scaled_font_lock_face.

The behavior of calling a type-specific function with a scaled font of the wrong type is undefined.

New entries may be added in future versions.

CAIRO_FONT_TYPE_TOY | The font was created using cairo's toy font api
CAIRO_FONT_TYPE_FT | The font is of type FreeType
CAIRO_FONT_TYPE_WIN32 | The font is of type Win32
CAIRO_FONT_TYPE_ATSUI | The font is of type ATSUI

Since 1.2

cairo_font_face_get_type ()

cairo_font_type_t cairo_font_face_get_type  (cairo_font_face_t *font_face);

This function returns the type of the backend used to create a font face. See cairo_font_type_t for available types.

font_face : | a cairo_font_face_t
Returns : | The type of font_face.

Since 1.2


cairo_matrix_t

cairo_matrix_t — Generic matrix operations

Synopsis

            cairo_matrix_t;
void        cairo_matrix_init               (cairo_matrix_t *matrix,
                                             double xx,
                                             double yx,
                                             double xy,
                                             double yy,
                                             double x0,
                                             double y0);
void        cairo_matrix_init_identity      (cairo_matrix_t *matrix);
void        cairo_matrix_init_translate     (cairo_matrix_t *matrix,
                                             double tx,
                                             double ty);
void        cairo_matrix_init_scale         (cairo_matrix_t *matrix,
                                             double sx,
                                             double sy);
void        cairo_matrix_init_rotate        (cairo_matrix_t *matrix,
                                             double radians);
void        cairo_matrix_translate          (cairo_matrix_t *matrix,
                                             double tx,
                                             double ty);
void        cairo_matrix_scale              (cairo_matrix_t *matrix,
                                             double sx,
                                             double sy);
void        cairo_matrix_rotate             (cairo_matrix_t *matrix,
                                             double radians);
cairo_status_t cairo_matrix_invert          (cairo_matrix_t *matrix);
void        cairo_matrix_multiply           (cairo_matrix_t *result,
                                             const cairo_matrix_t *a,
                                             const cairo_matrix_t *b);
void        cairo_matrix_transform_distance (const cairo_matrix_t *matrix,
                                             double *dx,
                                             double *dy);
void        cairo_matrix_transform_point    (const cairo_matrix_t *matrix,
                                             double *x,
                                             double *y);

Description

cairo_matrix_t is used throughout cairo to convert between different coordinate spaces. A cairo_matrix_t holds an affine transformation, such as a scale, rotation, shear, or a combination of these. The transformation of a point (x,y) is given by:

    x_new = xx * x + xy * y + x0;
    y_new = yx * x + yy * y + y0;

The current transformation matrix of a cairo_t, represented as a cairo_matrix_t, defines the transformation from user-space coordinates to device-space coordinates. See cairo_get_matrix() and cairo_set_matrix().

Details

cairo_matrix_t

typedef struct {
    double xx; double yx;
    double xy; double yy;
    double x0; double y0;
} cairo_matrix_t;

A cairo_matrix_t holds an affine transformation, such as a scale, rotation, shear, or a combination of those. The transformation of a point (x, y) is given by:

    x_new = xx * x + xy * y + x0;
    y_new = yx * x + yy * y + y0;

double xx; | xx component of the affine transformation
double yx; | yx component of the affine transformation
double xy; | xy component of the affine transformation
double yy; | yy component of the affine transformation
double x0; | X translation component of the affine transformation
double y0; | Y translation component of the affine transformation

cairo_matrix_init ()

void        cairo_matrix_init               (cairo_matrix_t *matrix,
                                             double xx,
                                             double yx,
                                             double xy,
                                             double yy,
                                             double x0,
                                             double y0);

Sets matrix to be the affine transformation given by xx, yx, xy, yy, x0, y0. The transformation is given by:

 x_new = xx * x + xy * y + x0;
 y_new = yx * x + yy * y + y0;

matrix : | a cairo_matrix_t
xx : | xx component of the affine transformation
yx : | yx component of the affine transformation
xy : | xy component of the affine transformation
yy : | yy component of the affine transformation
x0 : | X translation component of the affine transformation
y0 : | Y translation component of the affine transformation

cairo_matrix_init_identity ()

void        cairo_matrix_init_identity      (cairo_matrix_t *matrix);

Modifies matrix to be an identity transformation.

matrix : a cairo_matrix_t

cairo_matrix_init_translate ()

void        cairo_matrix_init_translate     (cairo_matrix_t *matrix,
                                             double tx,
                                             double ty);

Initializes matrix to a transformation that translates by tx and ty in the X and Y dimensions, respectively.

matrix : | a cairo_matrix_t
tx : | amount to translate in the X direction
ty : | amount to translate in the Y direction

cairo_matrix_init_scale ()

void        cairo_matrix_init_scale         (cairo_matrix_t *matrix,
                                             double sx,
                                             double sy);

Initializes matrix to a transformation that scales by sx and sy in the X and Y dimensions, respectively.

matrix : | a cairo_matrix_t
sx : | scale factor in the X direction
sy : | scale factor in the Y direction

cairo_matrix_init_rotate ()

void        cairo_matrix_init_rotate        (cairo_matrix_t *matrix,
                                             double radians);

Initialized matrix to a transformation that rotates by radians.

matrix : | a cairo_matrix_t
radians : | angle of rotation, in radians. The direction of rotation is defined such that positive angles rotate in the direction from the positive X axis toward the positive Y axis. With the default axis orientation of cairo, positive angles rotate in a clockwise direction.

cairo_matrix_translate ()

void        cairo_matrix_translate          (cairo_matrix_t *matrix,
                                             double tx,
                                             double ty);

Applies a translation by tx, ty to the transformation in matrix. The effect of the new transformation is to first translate the coordinates by tx and ty, then apply the original transformation to the coordinates.

matrix : | a cairo_matrix_t
tx : | amount to translate in the X direction
ty : | amount to translate in the Y direction

cairo_matrix_scale ()

void        cairo_matrix_scale              (cairo_matrix_t *matrix,
                                             double sx,
                                             double sy);

Applies scaling by tx, ty to the transformation in matrix. The effect of the new transformation is to first scale the coordinates by sx and sy, then apply the original transformation to the coordinates.

matrix : | a cairo_matrix_t
sx : | scale factor in the X direction
sy : | scale factor in the Y direction

cairo_matrix_rotate ()

void        cairo_matrix_rotate             (cairo_matrix_t *matrix,
                                             double radians);

Applies rotation by radians to the transformation in matrix. The effect of the new transformation is to first rotate the coordinates by radians, then apply the original transformation to the coordinates.

matrix : | a cairo_matrix_t
radians : | angle of rotation, in radians. The direction of rotation is defined such that positive angles rotate in the direction from the positive X axis toward the positive Y axis. With the default axis orientation of cairo, positive angles rotate in a clockwise direction.

cairo_matrix_invert ()

cairo_status_t cairo_matrix_invert          (cairo_matrix_t *matrix);

Changes matrix to be the inverse of it's original value. Not all transformation matrices have inverses; if the matrix collapses points together (it is degenerate), then it has no inverse and this function will fail.

Returns: If matrix has an inverse, modifies matrix to be the inverse matrix and returns CAIRO_STATUS_SUCCESS. Otherwise,

matrix : | a cairo_matrix_t
Returns : | CAIRO_STATUS_INVALID_MATRIX.

cairo_matrix_multiply ()

void        cairo_matrix_multiply           (cairo_matrix_t *result,
                                             const cairo_matrix_t *a,
                                             const cairo_matrix_t *b);

Multiplies the affine transformations in a and b together and stores the result in result. The effect of the resulting transformation is to first apply the transformation in a to the coordinates and then apply the transformation in b to the coordinates.

It is allowable for result to be identical to either a or b.

result : | a cairo_matrix_t in which to store the result
a : | a cairo_matrix_t
b : | a cairo_matrix_t

cairo_matrix_transform_distance ()

void        cairo_matrix_transform_distance (const cairo_matrix_t *matrix,
                                             double *dx,
                                             double *dy);

Transforms the distance vector (dx,dy) by matrix. This is similar to cairo_matrix_transform_point() except that the translation components of the transformation are ignored. The calculation of the returned vector is as follows:

dx2 = dx1 * a + dy1 * c;
dy2 = dx1 * b + dy1 * d;

Affine transformations are position invariant, so the same vector always transforms to the same vector. If (x1,y1) transforms to (x2,y2) then (x1+dx1,y1+dy1) will transform to (x1+dx2,y1+dy2) for all values of x1 and x2.

matrix : | a cairo_matrix_t
dx : | X component of a distance vector. An in/out parameter
dy : | Y component of a distance vector. An in/out parameter

cairo_matrix_transform_point ()

void        cairo_matrix_transform_point    (const cairo_matrix_t *matrix,
                                             double *x,
                                             double *y);

Transforms the point (x, y) by matrix.

matrix : | a cairo_matrix_t
x : | X position. An in/out parameter
y : | Y position. An in/out parameter


cairo_surface_t

cairo_surface_t — Base class for surfaces

Synopsis

typedef     cairo_surface_t;
enum        cairo_content_t;
cairo_surface_t* cairo_surface_create_similar
                                            (cairo_surface_t *other,
                                             cairo_content_t content,
                                             int width,
                                             int height);
void        cairo_surface_destroy           (cairo_surface_t *surface);
void        cairo_surface_finish            (cairo_surface_t *surface);
void        cairo_surface_flush             (cairo_surface_t *surface);
void        cairo_surface_get_font_options  (cairo_surface_t *surface,
                                             cairo_font_options_t *options);
cairo_content_t cairo_surface_get_content   (cairo_surface_t *surface);
cairo_status_t cairo_surface_set_user_data  (cairo_surface_t *surface,
                                             const cairo_user_data_key_t *key,
                                             void *user_data,
                                             cairo_destroy_func_t destroy);
void*       cairo_surface_get_user_data     (cairo_surface_t *surface,
                                             const cairo_user_data_key_t *key);
void        cairo_surface_mark_dirty        (cairo_surface_t *surface);
void        cairo_surface_mark_dirty_rectangle
                                            (cairo_surface_t *surface,
                                             int x,
                                             int y,
                                             int width,
                                             int height);
cairo_surface_t* cairo_surface_reference    (cairo_surface_t *surface);
void        cairo_surface_set_device_offset (cairo_surface_t *surface,
                                             double x_offset,
                                             double y_offset);
void        cairo_surface_get_device_offset (cairo_surface_t *surface,
                                             double *x_offset,
                                             double *y_offset);
void        cairo_surface_set_fallback_resolution
                                            (cairo_surface_t *surface,
                                             double x_pixels_per_inch,
                                             double y_pixels_per_inch);
cairo_status_t cairo_surface_status         (cairo_surface_t *surface);
enum        cairo_surface_type_t;
cairo_surface_type_t cairo_surface_get_type (cairo_surface_t *surface);

Description

Details

cairo_surface_t

typedef struct _cairo_surface cairo_surface_t;

A cairo_surface_t represents an image, either as the destination of a drawing operation or as source when drawing onto another surface. There are different subtypes of cairo_surface_t for different drawing backends; for example, cairo_image_surface_create() creates a bitmap image in memory.

Memory management of cairo_surface_t is done with cairo_surface_reference() and cairo_surface_destroy().

enum cairo_content_t

typedef enum _cairo_content {
    CAIRO_CONTENT_COLOR		= 0x1000,
    CAIRO_CONTENT_ALPHA		= 0x2000,
    CAIRO_CONTENT_COLOR_ALPHA	= 0x3000
} cairo_content_t;

cairo_content_t is used to describe the content that a surface will contain, whether color information, alpha information (translucence vs. opacity), or both.

Note: The large values here are designed to keep cairo_content_t values distinct from cairo_format_t values so that the implementation can detect the error if users confuse the two types.

CAIRO_CONTENT_COLOR | The surface will hold color content only.
CAIRO_CONTENT_ALPHA | The surface will hold alpha content only.
CAIRO_CONTENT_COLOR_ALPHA | The surface will hold color and alpha content.

cairo_surface_create_similar ()

cairo_surface_t* cairo_surface_create_similar
                                            (cairo_surface_t *other,
                                             cairo_content_t content,
                                             int width,
                                             int height);

Create a new surface that is as compatible as possible with an existing surface. For example the new surface will have the same fallback resolution and font options as other. Generally, the new surface will also use the same backend as other, unless that is not possible for some reason. The type of the returned surface may be examined with cairo_surface_get_type().

Initially the surface contents are all 0 (transparent if contents have transparency, black otherwise.)

other : | an existing surface used to select the backend of the new surface
content : | the content for the new surface
width : | width of the new surface, (in device-space units)
height : | height of the new surface (in device-space units)
Returns : | a pointer to the newly allocated surface. The caller owns the surface and should call cairo_surface_destroy when done with it. This function always returns a valid pointer, but it will return a pointer to a "nil" surface if other is already in an error state or any other error occurs.

cairo_surface_destroy ()

void        cairo_surface_destroy           (cairo_surface_t *surface);

Decreases the reference count on surface by one. If the result is zero, then surface and all associated resources are freed. See cairo_surface_reference().

surface : a cairo_t

cairo_surface_finish ()

void        cairo_surface_finish            (cairo_surface_t *surface);

This function finishes the surface and drops all references to external resources. For example, for the Xlib backend it means that cairo will no longer access the drawable, which can be freed. After calling cairo_surface_finish() the only valid operations on a surface are getting and setting user data and referencing and destroying it. Further drawing to the surface will not affect the surface but will instead trigger a CAIRO_STATUS_SURFACE_FINISHED error.

When the last call to cairo_surface_destroy() decreases the reference count to zero, cairo will call cairo_surface_finish() if it hasn't been called already, before freeing the resources associated with the surface.

surface : the cairo_surface_t to finish

cairo_surface_flush ()

void        cairo_surface_flush             (cairo_surface_t *surface);

Do any pending drawing for the surface and also restore any temporary modification's cairo has made to the surface's state. This function must be called before switching from drawing on the surface with cairo to drawing on it directly with native APIs. If the surface doesn't support direct access, then this function does nothing.

surface : a cairo_surface_t

cairo_surface_get_font_options ()

void        cairo_surface_get_font_options  (cairo_surface_t *surface,
                                             cairo_font_options_t *options);

Retrieves the default font rendering options for the surface. This allows display surfaces to report the correct subpixel order for rendering on them, print surfaces to disable hinting of metrics and so forth. The result can then be used with cairo_scaled_font_create().

surface : | a cairo_surface_t
options : | a cairo_font_options_t object into which to store the retrieved options. All existing values are overwritten

cairo_surface_get_content ()

cairo_content_t cairo_surface_get_content   (cairo_surface_t *surface);

surface : | a cairo_surface_t
Returns : | The content type of surface which indicates whether the surface contains color and/or alpha information. See cairo_content_t.

Since 1.2

cairo_surface_set_user_data ()

cairo_status_t cairo_surface_set_user_data  (cairo_surface_t *surface,
                                             const cairo_user_data_key_t *key,
                                             void *user_data,
                                             cairo_destroy_func_t destroy);

Attach user data to surface. To remove user data from a surface, call this function with the key that was used to set it and NULL for data.

surface : | a cairo_surface_t
key : | the address of a cairo_user_data_key_t to attach the user data to
user_data : | the user data to attach to the surface
destroy : | a cairo_destroy_func_t which will be called when the surface is destroyed or when new user data is attached using the same key.
Returns : | CAIRO_STATUS_SUCCESS or CAIRO_STATUS_NO_MEMORY if a slot could not be allocated for the user data.

cairo_surface_get_user_data ()

void*       cairo_surface_get_user_data     (cairo_surface_t *surface,
                                             const cairo_user_data_key_t *key);

Return user data previously attached to surface using the specified key. If no user data has been attached with the given key this function returns NULL.

surface : | a cairo_surface_t
key : | the address of the cairo_user_data_key_t the user data was attached to
Returns : | the user data previously attached or NULL.

cairo_surface_mark_dirty ()

void        cairo_surface_mark_dirty        (cairo_surface_t *surface);

Tells cairo that drawing has been done to surface using means other than cairo, and that cairo should reread any cached areas. Note that you must call cairo_surface_flush() before doing such drawing.

surface : a cairo_surface_t

cairo_surface_mark_dirty_rectangle ()

void        cairo_surface_mark_dirty_rectangle
                                            (cairo_surface_t *surface,
                                             int x,
                                             int y,
                                             int width,
                                             int height);

Like cairo_surface_mark_dirty(), but drawing has been done only to the specified rectangle, so that cairo can retain cached contents for other parts of the surface.

Any cached clip set on the surface will be reset by this function, to make sure that future cairo calls have the clip set that they expect.

surface : | a cairo_surface_t
x : | X coordinate of dirty rectangle
y : | Y coordinate of dirty rectangle
width : | width of dirty rectangle
height : | height of dirty rectangle

cairo_surface_reference ()

cairo_surface_t* cairo_surface_reference    (cairo_surface_t *surface);

Increases the reference count on surface by one. This prevents surface from being destroyed until a matching call to cairo_surface_destroy() is made.

surface : | a cairo_surface_t
Returns : | the referenced cairo_surface_t.

cairo_surface_set_device_offset ()

void        cairo_surface_set_device_offset (cairo_surface_t *surface,
                                             double x_offset,
                                             double y_offset);

Sets an offset that is added to the device coordinates determined by the CTM when drawing to surface. One use case for this function is when we want to create a cairo_surface_t that redirects drawing for a portion of an onscreen surface to an offscreen surface in a way that is completely invisible to the user of the cairo API. Setting a transformation via cairo_translate() isn't sufficient to do this, since functions like cairo_device_to_user() will expose the hidden offset.

Note that the offset affects drawing to the surface as well as using the surface in a source pattern.

surface : | a cairo_surface_t
x_offset : | the offset in the X direction, in device units
y_offset : | the offset in the Y direction, in device units

cairo_surface_get_device_offset ()

void        cairo_surface_get_device_offset (cairo_surface_t *surface,
                                             double *x_offset,
                                             double *y_offset);

This function returns the previous device offset set by cairo_surface_set_device_offset().

surface : | a cairo_surface_t
x_offset : | the offset in the X direction, in device units
y_offset : | the offset in the Y direction, in device units

Since 1.2

cairo_surface_set_fallback_resolution ()

void        cairo_surface_set_fallback_resolution
                                            (cairo_surface_t *surface,
                                             double x_pixels_per_inch,
                                             double y_pixels_per_inch);

Set the horizontal and vertical resolution for image fallbacks.

When certain operations aren't supported natively by a backend, cairo will fallback by rendering operations to an image and then overlaying that image onto the output. For backends that are natively vector-oriented, this function can be used to set the resolution used for these image fallbacks, (larger values will result in more detailed images, but also larger file sizes).

Some examples of natively vector-oriented backends are the ps, pdf, and svg backends.

For backends that are natively raster-oriented, image fallbacks are still possible, but they are always performed at the native device resolution. So this function has no effect on those backends.

NOTE: The fallback resolution only takes effect at the time of completing a page (with cairo_show_page() or cairo_copy_page()) so there is currently no way to have more than one fallback resolution in effect on a single page.

surface : | a cairo_surface_t
x_pixels_per_inch : | horizontal setting for pixels per inch
y_pixels_per_inch : | vertical setting for pixels per inch

Since 1.2

cairo_surface_status ()

cairo_status_t cairo_surface_status         (cairo_surface_t *surface);

Checks whether an error has previously occurred for this surface.

surface : | a cairo_surface_t
Returns : | CAIRO_STATUS_SUCCESS, CAIRO_STATUS_NULL_POINTER, CAIRO_STATUS_NO_MEMORY, CAIRO_STATUS_READ_ERROR, CAIRO_STATUS_INVALID_CONTENT, CAIRO_STATUS_INVALUE_FORMAT, or CAIRO_STATUS_INVALID_VISUAL.

enum cairo_surface_type_t

typedef enum _cairo_surface_type {
    CAIRO_SURFACE_TYPE_IMAGE,
    CAIRO_SURFACE_TYPE_PDF,
    CAIRO_SURFACE_TYPE_PS,
    CAIRO_SURFACE_TYPE_XLIB,
    CAIRO_SURFACE_TYPE_XCB,
    CAIRO_SURFACE_TYPE_GLITZ,
    CAIRO_SURFACE_TYPE_QUARTZ,
    CAIRO_SURFACE_TYPE_WIN32,
    CAIRO_SURFACE_TYPE_BEOS,
    CAIRO_SURFACE_TYPE_DIRECTFB,
    CAIRO_SURFACE_TYPE_SVG
} cairo_surface_type_t;

cairo_surface_type_t is used to describe the type of a given surface. The surface types are also known as "backends" or "surface backends" within cairo.

The type of a surface is determined by the function used to create it, which will generally be of the form cairo_type_surface_create, (though see cairo_surface_create_similar as well).

The surface type can be queried with cairo_surface_get_type()

The various cairo_surface functions can be used with surfaces of any type, but some backends also provide type-specific functions that must only be called with a surface of the appropriate type. These functions have names that begin with cairo_type_surface such as cairo_image_surface_get_width().

The behavior of calling a type-specific function with a surface of the wrong type is undefined.

New entries may be added in future versions.

CAIRO_SURFACE_TYPE_IMAGE | The surface is of type image
CAIRO_SURFACE_TYPE_PDF | The surface is of type pdf
CAIRO_SURFACE_TYPE_PS | The surface is of type ps
CAIRO_SURFACE_TYPE_XLIB | The surface is of type xlib
CAIRO_SURFACE_TYPE_XCB | The surface is of type xcb
CAIRO_SURFACE_TYPE_GLITZ | The surface is of type glitz
CAIRO_SURFACE_TYPE_QUARTZ | The surface is of type quartz
CAIRO_SURFACE_TYPE_WIN32 | The surface is of type win32
CAIRO_SURFACE_TYPE_BEOS | The surface is of type beos
CAIRO_SURFACE_TYPE_DIRECTFB | The surface is of type directfb
CAIRO_SURFACE_TYPE_SVG | The surface is of type svg

Since 1.2

cairo_surface_get_type ()

cairo_surface_type_t cairo_surface_get_type (cairo_surface_t *surface);

This function returns the type of the backend used to create a surface. See cairo_surface_type_t for available types.

surface : | a cairo_surface_t
Returns : | The type of surface.

Since 1.2


cairo_t

cairo_t — The cairo drawing context

Synopsis

typedef     cairo_t;
cairo_t*    cairo_create                    (cairo_surface_t *target);
cairo_t*    cairo_reference                 (cairo_t *cr);
void        cairo_destroy                   (cairo_t *cr);
cairo_status_t cairo_status                 (cairo_t *cr);
void        cairo_save                      (cairo_t *cr);
void        cairo_restore                   (cairo_t *cr);
cairo_surface_t* cairo_get_target           (cairo_t *cr);
void        cairo_push_group                (cairo_t *cr);
void        cairo_push_group_with_content   (cairo_t *cr,
                                             cairo_content_t content);
cairo_pattern_t* cairo_pop_group            (cairo_t *cr);
void        cairo_pop_group_to_source       (cairo_t *cr);
cairo_surface_t* cairo_get_group_target     (cairo_t *cr);
void        cairo_set_source_rgb            (cairo_t *cr,
                                             double red,
                                             double green,
                                             double blue);
void        cairo_set_source_rgba           (cairo_t *cr,
                                             double red,
                                             double green,
                                             double blue,
                                             double alpha);
void        cairo_set_source                (cairo_t *cr,
                                             cairo_pattern_t *source);
void        cairo_set_source_surface        (cairo_t *cr,
                                             cairo_surface_t *surface,
                                             double x,
                                             double y);
cairo_pattern_t* cairo_get_source           (cairo_t *cr);
enum        cairo_antialias_t;
void        cairo_set_antialias             (cairo_t *cr,
                                             cairo_antialias_t antialias);
cairo_antialias_t cairo_get_antialias       (cairo_t *cr);
void        cairo_set_dash                  (cairo_t *cr,
                                             const double *dashes,
                                             int num_dashes,
                                             double offset);
enum        cairo_fill_rule_t;
void        cairo_set_fill_rule             (cairo_t *cr,
                                             cairo_fill_rule_t fill_rule);
cairo_fill_rule_t cairo_get_fill_rule       (cairo_t *cr);
enum        cairo_line_cap_t;
void        cairo_set_line_cap              (cairo_t *cr,
                                             cairo_line_cap_t line_cap);
cairo_line_cap_t cairo_get_line_cap         (cairo_t *cr);
enum        cairo_line_join_t;
void        cairo_set_line_join             (cairo_t *cr,
                                             cairo_line_join_t line_join);
cairo_line_join_t cairo_get_line_join       (cairo_t *cr);
void        cairo_set_line_width            (cairo_t *cr,
                                             double width);
double      cairo_get_line_width            (cairo_t *cr);
void        cairo_set_miter_limit           (cairo_t *cr,
                                             double limit);
double      cairo_get_miter_limit           (cairo_t *cr);
enum        cairo_operator_t;
void        cairo_set_operator              (cairo_t *cr,
                                             cairo_operator_t op);
cairo_operator_t cairo_get_operator         (cairo_t *cr);
void        cairo_set_tolerance             (cairo_t *cr,
                                             double tolerance);
double      cairo_get_tolerance             (cairo_t *cr);
void        cairo_clip                      (cairo_t *cr);
void        cairo_clip_preserve             (cairo_t *cr);
void        cairo_reset_clip                (cairo_t *cr);
void        cairo_fill                      (cairo_t *cr);
void        cairo_fill_preserve             (cairo_t *cr);
void        cairo_fill_extents              (cairo_t *cr,
                                             double *x1,
                                             double *y1,
                                             double *x2,
                                             double *y2);
cairo_bool_t cairo_in_fill                  (cairo_t *cr,
                                             double x,
                                             double y);
void        cairo_mask                      (cairo_t *cr,
                                             cairo_pattern_t *pattern);
void        cairo_mask_surface              (cairo_t *cr,
                                             cairo_surface_t *surface,
                                             double surface_x,
                                             double surface_y);
void        cairo_paint                     (cairo_t *cr);
void        cairo_paint_with_alpha          (cairo_t *cr,
                                             double alpha);
void        cairo_stroke                    (cairo_t *cr);
void        cairo_stroke_preserve           (cairo_t *cr);
void        cairo_stroke_extents            (cairo_t *cr,
                                             double *x1,
                                             double *y1,
                                             double *x2,
                                             double *y2);
cairo_bool_t cairo_in_stroke                (cairo_t *cr,
                                             double x,
                                             double y);
void        cairo_copy_page                 (cairo_t *cr);
void        cairo_show_page                 (cairo_t *cr);

Description

cairo_t is the main object used when drawing with cairo. To draw with cairo, you create a cairo_t, set the target surface, and drawing options for the cairo_t, create shapes with functions like cairo_move_to() and cairo_line_to(), and then draw shapes with cairo_stroke() or cairo_fill().

cairo_t's can be pushed to a stack via cairo_save(). They may then safely be changed, without loosing the current state. Use cairo_restore() to restore to the saved state.

Details

cairo_t

typedef struct _cairo cairo_t;

A cairo_t contains the current state of the rendering device, including coordinates of yet to be drawn shapes.

cairo_create ()

cairo_t*    cairo_create                    (cairo_surface_t *target);

Creates a new cairo_t with all graphics state parameters set to default values and with target as a target surface. The target surface should be constructed with a backend-specific function such as cairo_image_surface_create() (or any other cairo_<backend>_surface_create variant).

This function references target, so you can immediately call cairo_surface_destroy() on it if you don't need to maintain a separate reference to it.

target : | target surface for the context
Returns : | a newly allocated cairo_t with a reference count of 1. The initial reference count should be released with cairo_destroy() when you are done using the cairo_t. This function never returns NULL. If memory cannot be allocated, a special cairo_t object will be returned on which cairo_status() returns CAIRO_STATUS_NO_MEMORY. You can use this object normally, but no drawing will be done.

cairo_reference ()

cairo_t*    cairo_reference                 (cairo_t *cr);

Increases the reference count on cr by one. This prevents cr from being destroyed until a matching call to cairo_destroy() is made.

cr : | a cairo_t
Returns : | the referenced cairo_t.

cairo_destroy ()

void        cairo_destroy                   (cairo_t *cr);

Decreases the reference count on cr by one. If the result is zero, then cr and all associated resources are freed. See cairo_reference().

cr : a cairo_t

cairo_status ()

cairo_status_t cairo_status                 (cairo_t *cr);

Checks whether an error has previously occurred for this context.

cr : | a cairo context
Returns : | the current status of this context, see cairo_status_t

cairo_save ()

void        cairo_save                      (cairo_t *cr);

Makes a copy of the current state of cr and saves it on an internal stack of saved states for cr. When cairo_restore() is called, cr will be restored to the saved state. Multiple calls to cairo_save() and cairo_restore() can be nested; each call to cairo_restore() restores the state from the matching paired cairo_save().

It isn't necessary to clear all saved states before a cairo_t is freed. If the reference count of a cairo_t drops to zero in response to a call to cairo_destroy(), any saved states will be freed along with the cairo_t.

cr : a cairo_t

cairo_restore ()

void        cairo_restore                   (cairo_t *cr);

Restores cr to the state saved by a preceding call to cairo_save() and removes that state from the stack of saved states.

cr : a cairo_t

cairo_get_target ()

cairo_surface_t* cairo_get_target           (cairo_t *cr);

Gets the target surface for the cairo context as passed to cairo_create().

This function will always return a valid pointer, but the result can be a "nil" surface if cr is already in an error state, (ie. cairo_status() != CAIRO_STATUS_SUCCESS). A nil surface is indicated by cairo_surface_status() != CAIRO_STATUS_SUCCESS.

cr : | a cairo context
Returns : | the target surface. This object is owned by cairo. To keep a reference to it, you must call cairo_surface_reference().

cairo_push_group ()

void        cairo_push_group                (cairo_t *cr);

Temporarily redirects drawing to an intermediate surface known as a group. The redirection lasts until the group is completed by a call to cairo_pop_group() or cairo_pop_group_to_source(). These calls provide the result of any drawing to the group as a pattern, (either as an explicit object, or set as the source pattern).

This group functionality can be convenient for performing intermediate compositing. One common use of a group is to render objects as opaque within the group, (so that they occlude each other), and then blend the result with translucence onto the destination.

Groups can be nested arbitrarily deep by making balanced calls to cairo_push_group()/cairo_pop_group(). Each call pushes/pops the new target group onto/from a stack.

The cairo_push_group() function calls cairo_save() so that any changes to the graphics state will not be visible outside the group, (the pop_group functions call cairo_restore()).

By default the intermediate group will have a content type of CAIRO_CONTENT_COLOR_ALPHA. Other content types can be chosen for the group by using cairo_push_group_with_content() instead.

As an example, here is how one might fill and stroke a path with translucence, but without any portion of the fill being visible under the stroke:

cairo_push_group (cr);
cairo_set_source (cr, fill_pattern);
cairo_fill_preserve (cr);
cairo_set_source (cr, stroke_pattern);
cairo_stroke (cr);
cairo_pop_group_to_source (cr);
cairo_paint_with_alpha (cr, alpha);

cr : a cairo context

Since 1.2

cairo_push_group_with_content ()

void        cairo_push_group_with_content   (cairo_t *cr,
                                             cairo_content_t content);

Temporarily redirects drawing to an intermediate surface known as a group. The redirection lasts until the group is completed by a call to cairo_pop_group() or cairo_pop_group_to_source(). These calls provide the result of any drawing to the group as a pattern, (either as an explicit object, or set as the source pattern).

The group will have a content type of content. The ability to control this content type is the only distinction between this function and cairo_push_group() which you should see for a more detailed description of group rendering.

cr : | a cairo context
content : | a cairo_content_t indicating the type of group that will be created

Since 1.2

cairo_pop_group ()

cairo_pattern_t* cairo_pop_group            (cairo_t *cr);

Terminates the redirection begun by a call to cairo_push_group() or cairo_push_group_with_content() and returns a new pattern containing the results of all drawing operations performed to the group.

The cairo_pop_group() function calls cairo_restore(), (balancing a call to cairo_save() by the push_group function), so that any changes to the graphics state will not be visible outside the group.

cr : | a cairo context
Returns : | a newly created (surface) pattern containing the results of all drawing operations performed to the group. The caller owns the returned object and should call cairo_pattern_destroy() when finished with it.

Since 1.2

cairo_pop_group_to_source ()

void        cairo_pop_group_to_source       (cairo_t *cr);

Terminates the redirection begun by a call to cairo_push_group() or cairo_push_group_with_content() and installs the resulting pattern as the source pattern in the given cairo context.

The behavior of this function is equivalent to the sequence of operations:

cairo_pattern_t *group = cairo_pop_group (cr);
cairo_set_source (cr, group);
cairo_pattern_destroy (group);

but is more convenient as their is no need for a variable to store the short-lived pointer to the pattern.

The cairo_pop_group() function calls cairo_restore(), (balancing a call to cairo_save() by the push_group function), so that any changes to the graphics state will not be visible outside the group.

cr : a cairo context

Since 1.2

cairo_get_group_target ()

cairo_surface_t* cairo_get_group_target     (cairo_t *cr);

Gets the target surface for the current group as started by the most recent call to cairo_push_group() or cairo_push_group_with_content().

This function will return NULL if called "outside" of any group rendering blocks, (that is, after the last balancing call to cairo_pop_group() or cairo_pop_group_to_source()).

cr : | a cairo context
Returns : | the target group surface, or NULL if none. This object is owned by cairo. To keep a reference to it, you must call cairo_surface_reference().

Since 1.2

cairo_set_source_rgb ()

void        cairo_set_source_rgb            (cairo_t *cr,
                                             double red,
                                             double green,
                                             double blue);

Sets the source pattern within cr to an opaque color. This opaque color will then be used for any subsequent drawing operation until a new source pattern is set.

The color components are floating point numbers in the range 0 to 1. If the values passed in are outside that range, they will be clamped.

cr : | a cairo context
red : | red component of color
green : | green component of color
blue : | blue component of color

cairo_set_source_rgba ()

void        cairo_set_source_rgba           (cairo_t *cr,
                                             double red,
                                             double green,
                                             double blue,
                                             double alpha);

Sets the source pattern within cr to a translucent color. This color will then be used for any subsequent drawing operation until a new source pattern is set.

The color and alpha components are floating point numbers in the range 0 to 1. If the values passed in are outside that range, they will be clamped.

cr : | a cairo context
red : | red component of color
green : | green component of color
blue : | blue component of color
alpha : | alpha component of color

cairo_set_source ()

void        cairo_set_source                (cairo_t *cr,
                                             cairo_pattern_t *source);

Sets the source pattern within cr to source. This pattern will then be used for any subsequent drawing operation until a new source pattern is set.

Note: The pattern's transformation matrix will be locked to the user space in effect at the time of cairo_set_source(). This means that further modifications of the current transformation matrix will not affect the source pattern. See cairo_pattern_set_matrix().

XXX: I'd also like to direct the reader's attention to some (not-yet-written) section on cairo's imaging model. How would I do that if such a section existed? (cworth).

cr : | a cairo context
source : | a cairo_pattern_t to be used as the source for subsequent drawing operations.

cairo_set_source_surface ()

void        cairo_set_source_surface        (cairo_t *cr,
                                             cairo_surface_t *surface,
                                             double x,
                                             double y);

This is a convenience function for creating a pattern from surface and setting it as the source in cr with cairo_set_source().

The x and y parameters give the user-space coordinate at which the surface origin should appear. (The surface origin is its upper-left corner before any transformation has been applied.) The x and y patterns are negated and then set as translation values in the pattern matrix.

Other than the initial translation pattern matrix, as described above, all other pattern attributes, (such as its extend mode), are set to the default values as in cairo_pattern_create_for_surface(). The resulting pattern can be queried with cairo_get_source() so that these attributes can be modified if desired, (eg. to create a repeating pattern with cairo_pattern_set_extend()).

cr : | a cairo context
surface : | a surface to be used to set the source pattern
x : | User-space X coordinate for surface origin
y : | User-space Y coordinate for surface origin

cairo_get_source ()

cairo_pattern_t* cairo_get_source           (cairo_t *cr);

Gets the current source pattern for cr.

cr : | a cairo context
Returns : | the current source pattern. This object is owned by cairo. To keep a reference to it, you must call cairo_pattern_reference().

enum cairo_antialias_t

typedef enum _cairo_antialias {
    CAIRO_ANTIALIAS_DEFAULT,
    CAIRO_ANTIALIAS_NONE,
    CAIRO_ANTIALIAS_GRAY,
    CAIRO_ANTIALIAS_SUBPIXEL
} cairo_antialias_t;

Specifies the type of antialiasing to do when rendering text or shapes.

CAIRO_ANTIALIAS_DEFAULT | Use the default antialiasing for the subsystem and target device
CAIRO_ANTIALIAS_NONE | Use a bilevel alpha mask
CAIRO_ANTIALIAS_GRAY | Perform single-color antialiasing (using shades of gray for black text on a white background, for example).
CAIRO_ANTIALIAS_SUBPIXEL | Perform antialiasing by taking advantage of the order of subpixel elements on devices such as LCD panels

cairo_set_antialias ()

void        cairo_set_antialias             (cairo_t *cr,
                                             cairo_antialias_t antialias);

Set the antialiasing mode of the rasterizer used for drawing shapes. This value is a hint, and a particular backend may or may not support a particular value. At the current time, no backend supports CAIRO_ANTIALIAS_SUBPIXEL when drawing shapes.

Note that this option does not affect text rendering, instead see cairo_font_options_set_antialias().

cr : | a cairo_t
antialias : | the new antialiasing mode

cairo_get_antialias ()

cairo_antialias_t cairo_get_antialias       (cairo_t *cr);

Gets the current shape antialiasing mode, as set by cairo_set_shape_antialias().

cr : | a cairo context
Returns : | the current shape antialiasing mode.

cairo_set_dash ()

void        cairo_set_dash                  (cairo_t *cr,
                                             const double *dashes,
                                             int num_dashes,
                                             double offset);

Sets the dash pattern to be used by cairo_stroke(). A dash pattern is specified by dashes, an array of positive values. Each value provides the length of alternate "on" and "off" portions of the stroke. The offset specifies an offset into the pattern at which the stroke begins.

Each "on" segment will have caps applied as if the segment were a separate sub-path. In particular, it is valid to use an "on" length of 0.0 with CAIRO_LINE_CAP_ROUND or CAIRO_LINE_CAP_SQUARE in order to distributed dots or squares along a path.

Note: The length values are in user-space units as evaluated at the time of stroking. This is not necessarily the same as the user space at the time of cairo_set_dash().

If num_dashes is 0 dashing is disabled.

If num_dashes is 1 a symmetric pattern is assumed with alternating on and off portions of the size specified by the single value in dashes.

If any value in dashes is negative, or if all values are 0, then cairo_t will be put into an error state with a status of CAIRO_STATUS_INVALID_DASH.

cr : | a cairo context
dashes : | an array specifying alternate lengths of on and off stroke portions
num_dashes : | the length of the dashes array
offset : | an offset into the dash pattern at which the stroke should start

enum cairo_fill_rule_t

typedef enum _cairo_fill_rule {
    CAIRO_FILL_RULE_WINDING,
    CAIRO_FILL_RULE_EVEN_ODD
} cairo_fill_rule_t;

cairo_fill_rule_t is used to select how paths are filled. For both fill rules, whether or not a point is included in the fill is determined by taking a ray from that point to infinity and looking at intersections with the path. The ray can be in any direction, as long as it doesn't pass through the end point of a segment or have a tricky intersection such as intersecting tangent to the path. (Note that filling is not actually implemented in this way. This is just a description of the rule that is applied.)

New entries may be added in future versions.

CAIRO_FILL_RULE_WINDING | If the path crosses the ray from left-to-right, counts +1. If the path crosses the ray from right to left, counts -1. (Left and right are determined from the perspective of looking along the ray from the starting point.) If the total count is non-zero, the point will be filled.
CAIRO_FILL_RULE_EVEN_ODD | Counts the total number of intersections, without regard to the orientation of the contour. If the total number of intersections is odd, the point will be filled.

cairo_set_fill_rule ()

void        cairo_set_fill_rule             (cairo_t *cr,
                                             cairo_fill_rule_t fill_rule);

Set the current fill rule within the cairo context. The fill rule is used to determine which regions are inside or outside a complex (potentially self-intersecting) path. The current fill rule affects both cairo_fill and cairo_clip. See cairo_fill_rule_t for details on the semantics of each available fill rule.

cr : | a cairo_t
fill_rule : | a fill rule, specified as a cairo_fill_rule_t

cairo_get_fill_rule ()

cairo_fill_rule_t cairo_get_fill_rule       (cairo_t *cr);

Gets the current fill rule, as set by cairo_set_fill_rule().

cr : | a cairo context
Returns : | the current fill rule.

enum cairo_line_cap_t

typedef enum _cairo_line_cap {
    CAIRO_LINE_CAP_BUTT,
    CAIRO_LINE_CAP_ROUND,
    CAIRO_LINE_CAP_SQUARE
} cairo_line_cap_t;

enumeration for style of line-endings

CAIRO_LINE_CAP_BUTT | start(stop) the line exactly at the start(end) point
CAIRO_LINE_CAP_ROUND | use a round ending, the center of the circle is the end point
CAIRO_LINE_CAP_SQUARE | use squared ending, the center of the square is the end point

cairo_set_line_cap ()

void        cairo_set_line_cap              (cairo_t *cr,
                                             cairo_line_cap_t line_cap);

Sets the current line cap style within the cairo context. See cairo_line_cap_t for details about how the available line cap styles are drawn.

As with the other stroke parameters, the current line cap style is examined by cairo_stroke(), cairo_stroke_extents(), and cairo_stroke_to_path(), but does not have any effect during path construction.

cr : | a cairo context, as a cairo_t
line_cap : | a line cap style, as a cairo_line_cap_t

cairo_get_line_cap ()

cairo_line_cap_t cairo_get_line_cap         (cairo_t *cr);

Gets the current line cap style, as set by cairo_set_line_cap().

cr : | a cairo context
Returns : | the current line cap style.

enum cairo_line_join_t

typedef enum _cairo_line_join {
    CAIRO_LINE_JOIN_MITER,
    CAIRO_LINE_JOIN_ROUND,
    CAIRO_LINE_JOIN_BEVEL
} cairo_line_join_t;

cairo_set_line_join ()

void        cairo_set_line_join             (cairo_t *cr,
                                             cairo_line_join_t line_join);

Sets the current line join style within the cairo context. See cairo_line_join_t for details about how the available line join styles are drawn.

As with the other stroke parameters, the current line join style is examined by cairo_stroke(), cairo_stroke_extents(), and cairo_stroke_to_path(), but does not have any effect during path construction.

cr : | a cairo context, as a cairo_t
line_join : | a line joint style, as a cairo_line_join_t

cairo_get_line_join ()

cairo_line_join_t cairo_get_line_join       (cairo_t *cr);

Gets the current line join style, as set by cairo_set_line_join().

cr : | a cairo context
Returns : | the current line join style.

cairo_set_line_width ()

void        cairo_set_line_width            (cairo_t *cr,
                                             double width);

Sets the current line width within the cairo context. The line width value specifies the diameter of a pen that is circular in user space, (though device-space pen may be an ellipse in general due to scaling/shear/rotation of the CTM).

Note: When the description above refers to user space and CTM it refers to the user space and CTM in effect at the time of the stroking operation, not the user space and CTM in effect at the time of the call to cairo_set_line_width(). The simplest usage makes both of these spaces identical. That is, if there is no change to the CTM between a call to cairo_set_line_with() and the stroking operation, then one can just pass user-space values to cairo_set_line_width() and ignore this note.

As with the other stroke parameters, the current line width is examined by cairo_stroke(), cairo_stroke_extents(), and cairo_stroke_to_path(), but does not have any effect during path construction.

The default line width value is 2.0.

cr : | a cairo_t
width : | a line width

cairo_get_line_width ()

double      cairo_get_line_width            (cairo_t *cr);

cr : | a cairo context
Returns : | the current line width value exactly as set by cairo_set_line_width(). Note that the value is unchanged even if the CTM has changed between the calls to cairo_set_line_width() and cairo_get_line_width().

cairo_set_miter_limit ()

void        cairo_set_miter_limit           (cairo_t *cr,
                                             double limit);

cr :
limit :

cairo_get_miter_limit ()

double      cairo_get_miter_limit           (cairo_t *cr);

Gets the current miter limit, as set by cairo_set_miter_limit().

cr : | a cairo context
Returns : | the current miter limit.

enum cairo_operator_t

typedef enum _cairo_operator {
    CAIRO_OPERATOR_CLEAR,

    CAIRO_OPERATOR_SOURCE,
    CAIRO_OPERATOR_OVER,
    CAIRO_OPERATOR_IN,
    CAIRO_OPERATOR_OUT,
    CAIRO_OPERATOR_ATOP,

    CAIRO_OPERATOR_DEST,
    CAIRO_OPERATOR_DEST_OVER,
    CAIRO_OPERATOR_DEST_IN,
    CAIRO_OPERATOR_DEST_OUT,
    CAIRO_OPERATOR_DEST_ATOP,

    CAIRO_OPERATOR_XOR,
    CAIRO_OPERATOR_ADD,
    CAIRO_OPERATOR_SATURATE
} cairo_operator_t;

cairo_set_operator ()

void        cairo_set_operator              (cairo_t *cr,
                                             cairo_operator_t op);

Sets the compositing operator to be used for all drawing operations. See cairo_operator_t for details on the semantics of each available compositing operator.

XXX: I'd also like to direct the reader's attention to some (not-yet-written) section on cairo's imaging model. How would I do that if such a section existed? (cworth).

cr : | a cairo_t
op : | a compositing operator, specified as a cairo_operator_t

cairo_get_operator ()

cairo_operator_t cairo_get_operator         (cairo_t *cr);

Gets the current compositing operator for a cairo context.

cr : | a cairo context
Returns : | the current compositing operator.

cairo_set_tolerance ()

void        cairo_set_tolerance             (cairo_t *cr,
                                             double tolerance);

Sets the tolerance used when converting paths into trapezoids. Curved segments of the path will be subdivided until the maximum deviation between the original path and the polygonal approximation is less than tolerance. The default value is 0.1. A larger value will give better performance, a smaller value, better appearance. (Reducing the value from the default value of 0.1 is unlikely to improve appearance significantly.)

cr : | a cairo_t
tolerance : | the tolerance, in device units (typically pixels)

cairo_get_tolerance ()

double      cairo_get_tolerance             (cairo_t *cr);

Gets the current tolerance value, as set by cairo_set_tolerance().

cr : | a cairo context
Returns : | the current tolerance value.

cairo_clip ()

void        cairo_clip                      (cairo_t *cr);

Establishes a new clip region by intersecting the current clip region with the current path as it would be filled by cairo_fill() and according to the current fill rule (see cairo_set_fill_rule()).

After cairo_clip, the current path will be cleared from the cairo context.

The current clip region affects all drawing operations by effectively masking out any changes to the surface that are outside the current clip region.

Calling cairo_clip() can only make the clip region smaller, never larger. But the current clip is part of the graphics state, so a temporary restriction of the clip region can be achieved by calling cairo_clip() within a cairo_save()/cairo_restore() pair. The only other means of increasing the size of the clip region is cairo_reset_clip().

cr : a cairo context

cairo_clip_preserve ()

void        cairo_clip_preserve             (cairo_t *cr);

Establishes a new clip region by intersecting the current clip region with the current path as it would be filled by cairo_fill() and according to the current fill rule (see cairo_set_fill_rule()).

Unlike cairo_clip(), cairo_clip_preserve preserves the path within the cairo context.

The current clip region affects all drawing operations by effectively masking out any changes to the surface that are outside the current clip region.

Calling cairo_clip() can only make the clip region smaller, never larger. But the current clip is part of the graphics state, so a temporary restriction of the clip region can be achieved by calling cairo_clip() within a cairo_save()/cairo_restore() pair. The only other means of increasing the size of the clip region is cairo_reset_clip().

cr : a cairo context

cairo_reset_clip ()

void        cairo_reset_clip                (cairo_t *cr);

Reset the current clip region to its original, unrestricted state. That is, set the clip region to an infinitely large shape containing the target surface. Equivalently, if infinity is too hard to grasp, one can imagine the clip region being reset to the exact bounds of the target surface.

Note that code meant to be reusable should not call cairo_reset_clip() as it will cause results unexpected by higher-level code which calls cairo_clip(). Consider using cairo_save() and cairo_restore() around cairo_clip() as a more robust means of temporarily restricting the clip region.

cr : a cairo context

cairo_fill ()

void        cairo_fill                      (cairo_t *cr);

A drawing operator that fills the current path according to the current fill rule, (each sub-path is implicitly closed before being filled). After cairo_fill, the current path will be cleared from the cairo context. See cairo_set_fill_rule() and cairo_fill_preserve().

cr : a cairo context

cairo_fill_preserve ()

void        cairo_fill_preserve             (cairo_t *cr);

A drawing operator that fills the current path according to the current fill rule, (each sub-path is implicitly closed before being filled). Unlike cairo_fill(), cairo_fill_preserve preserves the path within the cairo context.

See cairo_set_fill_rule() and cairo_fill().

cr : a cairo context

cairo_fill_extents ()

void        cairo_fill_extents              (cairo_t *cr,
                                             double *x1,
                                             double *y1,
                                             double *x2,
                                             double *y2);

cr :
x1 :
y1 :
x2 :
y2 :

cairo_in_fill ()

cairo_bool_t cairo_in_fill                  (cairo_t *cr,
                                             double x,
                                             double y);

Tests whether the given point is inside the area that would be filled by doing a cairo_fill() operation on cr given the current path and filling parameters.

See cairo_fill(), cairo_set_fill_rule() and cairo_fill_preserve().

cr : | a cairo context
x : | X coordinate of the point to test
y : | Y coordinate of the point to test
Returns : | A non-zero value if the point is inside, or zero if outside.

cairo_mask ()

void        cairo_mask                      (cairo_t *cr,
                                             cairo_pattern_t *pattern);

A drawing operator that paints the current source using the alpha channel of pattern as a mask. (Opaque areas of pattern are painted with the source, transparent areas are not painted.)

cr : | a cairo context
pattern : | a cairo_pattern_t

cairo_mask_surface ()

void        cairo_mask_surface              (cairo_t *cr,
                                             cairo_surface_t *surface,
                                             double surface_x,
                                             double surface_y);

A drawing operator that paints the current source using the alpha channel of surface as a mask. (Opaque areas of surface are painted with the source, transparent areas are not painted.)

cr : | a cairo context
surface : | a cairo_surface_t
surface_x : | X coordinate at which to place the origin of surface
surface_y : | Y coordinate at which to place the origin of surface

cairo_paint ()

void        cairo_paint                     (cairo_t *cr);

A drawing operator that paints the current source everywhere within the current clip region.

cr : a cairo context

cairo_paint_with_alpha ()

void        cairo_paint_with_alpha          (cairo_t *cr,
                                             double alpha);

A drawing operator that paints the current source everywhere within the current clip region using a mask of constant alpha value alpha. The effect is similar to cairo_paint(), but the drawing is faded out using the alpha value.

cr : | a cairo context
alpha : | alpha value, between 0 (transparent) and 1 (opaque)

cairo_stroke ()

void        cairo_stroke                    (cairo_t *cr);

A drawing operator that strokes the current path according to the current line width, line join, line cap, and dash settings. After cairo_stroke, the current path will be cleared from the cairo context. See cairo_set_line_width(), cairo_set_line_join(), cairo_set_line_cap(), cairo_set_dash(), and cairo_stroke_preserve().

Note: Degenerate segments and sub-paths are treated specially and provide a useful result. These can result in two different situations:

1. Zero-length "on" segments set in cairo_set_dash(). If the cap style is CAIRO_LINE_CAP_ROUND or CAIRO_LINE_CAP_SQUARE then these segments will be drawn as circular dots or squares respectively. In the case of CAIRO_LINE_CAP_SQUARE, the orientation of the squares is determined by the direction of the underlying path.

2. A sub-path created by cairo_move_to() followed by either a cairo_close_path() or one or more calls to cairo_line_to() to the same coordinate as the cairo_move_to(). If the cap style is CAIRO_LINE_CAP_ROUND then these sub-paths will be drawn as circular dots. Note that in the case of CAIRO_LINE_CAP_SQUARE a degenerate sub-path will not be drawn at all, (since the correct orientation is indeterminate).

In no case will a cap style of CAIRO_LINE_CAP_BUTT cause anything to be drawn in the case of either degenerate segments or sub-paths.

cr : a cairo context

cairo_stroke_preserve ()

void        cairo_stroke_preserve           (cairo_t *cr);

A drawing operator that strokes the current path according to the current line width, line join, line cap, and dash settings. Unlike cairo_stroke(), cairo_stroke_preserve preserves the path within the cairo context.

See cairo_set_line_width(), cairo_set_line_join(),
cairo_set_line_cap(), cairo_set_dash(), and
cairo_stroke_preserve().

cr : a cairo context

cairo_stroke_extents ()

void        cairo_stroke_extents            (cairo_t *cr,
                                             double *x1,
                                             double *y1,
                                             double *x2,
                                             double *y2);

cr :
x1 :
y1 :
x2 :
y2 :

cairo_in_stroke ()

cairo_bool_t cairo_in_stroke                (cairo_t *cr,
                                             double x,
                                             double y);

Tests whether the given point is inside the area that would be stroked by doing a cairo_stroke() operation on cr given the current path and stroking parameters.

See cairo_stroke(), cairo_set_line_width(), cairo_set_line_join(),
cairo_set_line_cap(), cairo_set_dash(), and
cairo_stroke_preserve().

cr : | a cairo context
x : | X coordinate of the point to test
y : | Y coordinate of the point to test
Returns : | A non-zero value if the point is inside, or zero if outside.

cairo_copy_page ()

void        cairo_copy_page                 (cairo_t *cr);

Emits the current page for backends that support multiple pages, but doesn't clear it, so, the contents of the current page will be retained for the next page too. Use cairo_show_page() if you want to get an empty page after the emission.

cr : a cairo context

cairo_show_page ()

void        cairo_show_page                 (cairo_t *cr);

Emits and clears the current page for backends that support multiple pages. Use cairo_copy_page() if you don't want to clear the page.

cr : a cairo context


Error handling

Error handling — Decoding cairo's status

Synopsis

enum        cairo_status_t;
const char* cairo_status_to_string          (cairo_status_t status);
void        cairo_debug_reset_static_data   (void);

Description

Details

enum cairo_status_t

typedef enum _cairo_status {
    CAIRO_STATUS_SUCCESS = 0,
    CAIRO_STATUS_NO_MEMORY,
    CAIRO_STATUS_INVALID_RESTORE,
    CAIRO_STATUS_INVALID_POP_GROUP,
    CAIRO_STATUS_NO_CURRENT_POINT,
    CAIRO_STATUS_INVALID_MATRIX,
    CAIRO_STATUS_INVALID_STATUS,
    CAIRO_STATUS_NULL_POINTER,
    CAIRO_STATUS_INVALID_STRING,
    CAIRO_STATUS_INVALID_PATH_DATA,
    CAIRO_STATUS_READ_ERROR,
    CAIRO_STATUS_WRITE_ERROR,
    CAIRO_STATUS_SURFACE_FINISHED,
    CAIRO_STATUS_SURFACE_TYPE_MISMATCH,
    CAIRO_STATUS_PATTERN_TYPE_MISMATCH,
    CAIRO_STATUS_INVALID_CONTENT,
    CAIRO_STATUS_INVALID_FORMAT,
    CAIRO_STATUS_INVALID_VISUAL,
    CAIRO_STATUS_FILE_NOT_FOUND,
    CAIRO_STATUS_INVALID_DASH,
    CAIRO_STATUS_INVALID_DSC_COMMENT
} cairo_status_t;

cairo_status_t is used to indicate errors that can occur when using Cairo. In some cases it is returned directly by functions. but when using cairo_t, the last error, if any, is stored in the context and can be retrieved with cairo_status().

New entries may be added in future versions. Use cairo_status_to_string() to get a human-readable representation of an error message.

CAIRO_STATUS_SUCCESS | no error has occurred
CAIRO_STATUS_NO_MEMORY | out of memory
CAIRO_STATUS_INVALID_RESTORE | cairo_restore without matching cairo_save
CAIRO_STATUS_INVALID_POP_GROUP | no saved group to pop
CAIRO_STATUS_NO_CURRENT_POINT | no current point defined
CAIRO_STATUS_INVALID_MATRIX | invalid matrix (not invertible)
CAIRO_STATUS_INVALID_STATUS | invalid value for an input cairo_status_t
CAIRO_STATUS_NULL_POINTER | NULL pointer
CAIRO_STATUS_INVALID_STRING | input string not valid UTF-8
CAIRO_STATUS_INVALID_PATH_DATA | input path data not valid
CAIRO_STATUS_READ_ERROR | error while reading from input stream
CAIRO_STATUS_WRITE_ERROR | error while writing to output stream
CAIRO_STATUS_SURFACE_FINISHED | target surface has been finished
CAIRO_STATUS_SURFACE_TYPE_MISMATCH | the surface type is not appropriate for the operation
CAIRO_STATUS_PATTERN_TYPE_MISMATCH | the pattern type is not appropriate for the operation
CAIRO_STATUS_INVALID_CONTENT | invalid value for an input cairo_content_t
CAIRO_STATUS_INVALID_FORMAT | invalid value for an input cairo_format_t
CAIRO_STATUS_INVALID_VISUAL | invalid value for an input Visual*
CAIRO_STATUS_FILE_NOT_FOUND | file not found
CAIRO_STATUS_INVALID_DASH | invalid value for a dash setting
CAIRO_STATUS_INVALID_DSC_COMMENT | invalid value for a DSC comment (Since 1.2)

cairo_status_to_string ()

const char* cairo_status_to_string          (cairo_status_t status);

Provides a human-readable description of a cairo_status_t.

status : | a cairo status
Returns : | a string representation of the status

cairo_debug_reset_static_data ()

void        cairo_debug_reset_static_data   (void);

Resets all static data within cairo to its original state, (ie. identical to the state at the time of program invocation). For example, all caches within cairo will be flushed empty.

This function is intended to be useful when using memory-checking tools such as valgrind. When valgrind's memcheck analyzes a cairo-using program without a call to cairo_debug_reset_static_data, it will report all data reachable via cairo's static objects as "still reachable". Calling cairo_debug_reset_static_data just prior to program termination will make it easier to get squeaky clean reports from valgrind.

WARNING: It is only safe to call this function when there are no active cairo objects remaining, (ie. the appropriate destroy functions have been called as necessary). If there are active cairo objects, this call is likely to cause a crash, (eg. an assertion failure due to a hash table being destroyed when non-empty).


Font Options

Font Options — How a font should be rendered

Synopsis

typedef     cairo_font_options_t;
cairo_font_options_t* cairo_font_options_create
                                            (void);
cairo_font_options_t* cairo_font_options_copy
                                            (const cairo_font_options_t *original);
void        cairo_font_options_destroy      (cairo_font_options_t *options);
cairo_status_t cairo_font_options_status    (cairo_font_options_t *options);
void        cairo_font_options_merge        (cairo_font_options_t *options,
                                             const cairo_font_options_t *other);
unsigned long cairo_font_options_hash       (const cairo_font_options_t *options);
cairo_bool_t cairo_font_options_equal       (const cairo_font_options_t *options,
                                             const cairo_font_options_t *other);
void        cairo_font_options_set_antialias
                                            (cairo_font_options_t *options,
                                             cairo_antialias_t antialias);
cairo_antialias_t cairo_font_options_get_antialias
                                            (const cairo_font_options_t *options);
enum        cairo_subpixel_order_t;
void        cairo_font_options_set_subpixel_order
                                            (cairo_font_options_t *options,
                                             cairo_subpixel_order_t subpixel_order);
cairo_subpixel_order_t cairo_font_options_get_subpixel_order
                                            (const cairo_font_options_t *options);
enum        cairo_hint_style_t;
void        cairo_font_options_set_hint_style
                                            (cairo_font_options_t *options,
                                             cairo_hint_style_t hint_style);
cairo_hint_style_t cairo_font_options_get_hint_style
                                            (const cairo_font_options_t *options);
enum        cairo_hint_metrics_t;
void        cairo_font_options_set_hint_metrics
                                            (cairo_font_options_t *options,
                                             cairo_hint_metrics_t hint_metrics);
cairo_hint_metrics_t cairo_font_options_get_hint_metrics
                                            (const cairo_font_options_t *options);

Description

Details

cairo_font_options_t

typedef struct _cairo_font_options cairo_font_options_t;

cairo_font_options_create ()

cairo_font_options_t* cairo_font_options_create
                                            (void);

Allocates a new font options object with all options initialized to default values.

Returns : a newly allocated cairo_font_options_t. Free with cairo_font_options_destroy(). This function always returns a valid pointer; if memory cannot be allocated, then a special error object is returned where all operations on the object do nothing. You can check for this with cairo_font_options_status().

cairo_font_options_copy ()

cairo_font_options_t* cairo_font_options_copy
                                            (const cairo_font_options_t *original);

Allocates a new font options object copying the option values from original.

original : | a cairo_font_options_t
Returns : | a newly allocated cairo_font_options_t. Free with cairo_font_options_destroy(). This function always returns a valid pointer; if memory cannot be allocated, then a special error object is returned where all operations on the object do nothing. You can check for this with cairo_font_options_status().

cairo_font_options_destroy ()

void        cairo_font_options_destroy      (cairo_font_options_t *options);

Destroys a cairo_font_options_t object created with with cairo_font_options_create() or cairo_font_options_copy().

options : a cairo_font_options_t

cairo_font_options_status ()

cairo_status_t cairo_font_options_status    (cairo_font_options_t *options);

Checks whether an error has previously occurred for this font options object

options : | a cairo_font_options_t
Returns : | CAIRO_STATUS_SUCCESS or CAIRO_STATUS_NO_MEMORY

cairo_font_options_merge ()

void        cairo_font_options_merge        (cairo_font_options_t *options,
                                             const cairo_font_options_t *other);

Merges non-default options from other into options, replacing existing values. This operation can be thought of as somewhat similar to compositing other onto options with the operation of CAIRO_OPERATION_OVER.

options : | a cairo_font_options_t
other : | another cairo_font_options_t

cairo_font_options_hash ()

unsigned long cairo_font_options_hash       (const cairo_font_options_t *options);

Compute a hash for the font options object; this value will be useful when storing an object containing a cairo_font_options_t in a hash table.

options : | a cairo_font_options_t
Returns : | the hash value for the font options object. The return value can be cast to a 32-bit type if a 32-bit hash value is needed.

cairo_font_options_equal ()

cairo_bool_t cairo_font_options_equal       (const cairo_font_options_t *options,
                                             const cairo_font_options_t *other);

Compares two font options objects for equality.

options : | a cairo_font_options_t
other : | another cairo_font_options_t
Returns : | TRUE if all fields of the two font options objects match

cairo_font_options_set_antialias ()

void        cairo_font_options_set_antialias
                                            (cairo_font_options_t *options,
                                             cairo_antialias_t antialias);

Sets the antiliasing mode for the font options object. This specifies the type of antialiasing to do when rendering text.

options : | a cairo_font_options_t
antialias : | the new antialiasing mode

cairo_font_options_get_antialias ()

cairo_antialias_t cairo_font_options_get_antialias
                                            (const cairo_font_options_t *options);

Gets the antialising mode for the font options object.

options : | a cairo_font_options_t
Returns : | the antialiasing mode

enum cairo_subpixel_order_t

typedef enum _cairo_subpixel_order {
    CAIRO_SUBPIXEL_ORDER_DEFAULT,
    CAIRO_SUBPIXEL_ORDER_RGB,
    CAIRO_SUBPIXEL_ORDER_BGR,
    CAIRO_SUBPIXEL_ORDER_VRGB,
    CAIRO_SUBPIXEL_ORDER_VBGR
} cairo_subpixel_order_t;

The subpixel order specifies the order of color elements within each pixel on the display device when rendering with an antialiasing mode of CAIRO_ANTIALIAS_SUBPIXEL.

CAIRO_SUBPIXEL_ORDER_DEFAULT | Use the default subpixel order for for the target device
CAIRO_SUBPIXEL_ORDER_RGB | Subpixel elements are arranged horizontally with red at the left
CAIRO_SUBPIXEL_ORDER_BGR | Subpixel elements are arranged horizontally with blue at the left
CAIRO_SUBPIXEL_ORDER_VRGB | Subpixel elements are arranged vertically with red at the top
CAIRO_SUBPIXEL_ORDER_VBGR | Subpixel elements are arranged vertically with blue at the top

cairo_font_options_set_subpixel_order ()

void        cairo_font_options_set_subpixel_order
                                            (cairo_font_options_t *options,
                                             cairo_subpixel_order_t subpixel_order);

Sets the subpixel order for the font options object. The subpixel order specifies the order of color elements within each pixel on the display device when rendering with an antialiasing mode of CAIRO_ANTIALIAS_SUBPIXEL. See the documentation for cairo_subpixel_order_t for full details.

options : | a cairo_font_options_t
subpixel_order : | the new subpixel order

cairo_font_options_get_subpixel_order ()

cairo_subpixel_order_t cairo_font_options_get_subpixel_order
                                            (const cairo_font_options_t *options);

Gets the subpixel order for the font options object. See the documentation for cairo_subpixel_order_t for full details.

options : | a cairo_font_options_t
Returns : | the subpixel order for the font options object

enum cairo_hint_style_t

typedef enum _cairo_hint_style {
    CAIRO_HINT_STYLE_DEFAULT,
    CAIRO_HINT_STYLE_NONE,
    CAIRO_HINT_STYLE_SLIGHT,
    CAIRO_HINT_STYLE_MEDIUM,
    CAIRO_HINT_STYLE_FULL
} cairo_hint_style_t;

Specifies the type of hinting to do on font outlines. Hinting is the process of fitting outlines to the pixel grid in order to improve the appearance of the result. Since hinting outlines involves distorting them, it also reduces the faithfulness to the original outline shapes. Not all of the outline hinting styles are supported by all font backends.

New entries may be added in future versions.

CAIRO_HINT_STYLE_DEFAULT | Use the default hint style for for font backend and target device
CAIRO_HINT_STYLE_NONE | Do not hint outlines
CAIRO_HINT_STYLE_SLIGHT | Hint outlines slightly to improve contrast while retaining good fidelity to the original shapes.
CAIRO_HINT_STYLE_MEDIUM | Hint outlines with medium strength giving a compromise between fidelity to the original shapes and contrast
CAIRO_HINT_STYLE_FULL | Hint outlines to maximize contrast

cairo_font_options_set_hint_style ()

void        cairo_font_options_set_hint_style
                                            (cairo_font_options_t *options,
                                             cairo_hint_style_t hint_style);

Sets the hint style for font outlines for the font options object. This controls whether to fit font outlines to the pixel grid, and if so, whether to optimize for fidelity or contrast. See the documentation for cairo_hint_style_t for full details.

options : | a cairo_font_options_t
hint_style : | the new hint style

cairo_font_options_get_hint_style ()

cairo_hint_style_t cairo_font_options_get_hint_style
                                            (const cairo_font_options_t *options);

Gets the hint style for font outlines for the font options object. See the documentation for cairo_hint_style_t for full details.

options : | a cairo_font_options_t
Returns : | the hint style for the font options object

enum cairo_hint_metrics_t

typedef enum _cairo_hint_metrics {
    CAIRO_HINT_METRICS_DEFAULT,
    CAIRO_HINT_METRICS_OFF,
    CAIRO_HINT_METRICS_ON
} cairo_hint_metrics_t;

Specifies whether to hint font metrics; hinting font metrics means quantizing them so that they are integer values in device space. Doing this improves the consistency of letter and line spacing, however it also means that text will be laid out differently at different zoom factors.

CAIRO_HINT_METRICS_DEFAULT | Hint metrics in the default manner for the font backend and target device
CAIRO_HINT_METRICS_OFF | Do not hint font metrics
CAIRO_HINT_METRICS_ON | Hint font metrics

cairo_font_options_set_hint_metrics ()

void        cairo_font_options_set_hint_metrics
                                            (cairo_font_options_t *options,
                                             cairo_hint_metrics_t hint_metrics);

Sets the metrics hinting mode for the font options object. This controls whether metrics are quantized to integer values in device units. See the documentation for cairo_hint_metrics_t for full details.

options : | a cairo_font_options_t
hint_metrics : | the new metrics hinting mode

cairo_font_options_get_hint_metrics ()

cairo_hint_metrics_t cairo_font_options_get_hint_metrics
                                            (const cairo_font_options_t *options);

Gets the metrics hinting mode for the font options object. See the documentation for cairo_hint_metrics_t for full details.

options : | a cairo_font_options_t
Returns : | the metrics hinting mode for the font options object


FreeType Fonts

FreeType Fonts — Font support for FreeType

Synopsis

cairo_font_face_t* cairo_ft_font_face_create_for_ft_face
                                            (FT_Face face,
                                             int load_flags);
cairo_font_face_t* cairo_ft_font_face_create_for_pattern
                                            (FcPattern *pattern);
void        cairo_ft_font_options_substitute
                                            (const cairo_font_options_t *options,
                                             FcPattern *pattern);
FT_Face     cairo_ft_scaled_font_lock_face  (cairo_scaled_font_t *scaled_font);
void        cairo_ft_scaled_font_unlock_face
                                            (cairo_scaled_font_t *scaled_font);

Description

Details

cairo_ft_font_face_create_for_ft_face ()

cairo_font_face_t* cairo_ft_font_face_create_for_ft_face
                                            (FT_Face face,
                                             int load_flags);

Creates a new font face for the FreeType font backend from a pre-opened FreeType face. This font can then be used with cairo_set_font_face() or cairo_scaled_font_create(). The cairo_scaled_font_t returned from cairo_scaled_font_create() is also for the FreeType backend and can be used with functions such as cairo_ft_font_lock_face().

face : | A FreeType face object, already opened. This must be kept around until the face's ref_count drops to zero and it is freed. Since the face may be referenced internally to Cairo, the best way to determine when it is safe to free the face is to pass a cairo_destroy_func_t to cairo_font_face_set_user_data()
load_flags : | flags to pass to FT_Load_Glyph when loading glyphs from the font. These flags are OR'ed together with the flags derived from the cairo_font_options_t passed to cairo_scaled_font_create(), so only a few values such as FT_LOAD_VERTICAL_LAYOUT, and FT_LOAD_FORCE_AUTOHINT are useful. You should not pass any of the flags affecting the load target, such as FT_LOAD_TARGET_LIGHT.
Returns : | a newly created cairo_font_face_t. Free with cairo_font_face_destroy() when you are done using it.

cairo_ft_font_face_create_for_pattern ()

cairo_font_face_t* cairo_ft_font_face_create_for_pattern
                                            (FcPattern *pattern);

Creates a new font face for the FreeType font backend based on a fontconfig pattern. This font can then be used with cairo_set_font_face() or cairo_scaled_font_create(). The cairo_scaled_font_t returned from cairo_scaled_font_create() is also for the FreeType backend and can be used with functions such as cairo_ft_font_lock_face().

Font rendering options are representated both here and when you call cairo_scaled_font_create(). Font options that have a representation in a FcPattern must be passed in here; to modify FcPattern appropriately to reflect the options in a cairo_font_options_t, call cairo_ft_font_options_substitute().

pattern : | A fully resolved fontconfig pattern. A pattern can be resolved, by, among other things, calling FcConfigSubstitute(), FcDefaultSubstitute(), then FcFontMatch(). Cairo will call FcPatternReference() on this pattern, so you should not further modify the pattern, but you can release your reference to the pattern with FcPatternDestroy() if you no longer need to access it.
Returns : | a newly created cairo_font_face_t. Free with cairo_font_face_destroy() when you are done using it.

cairo_ft_font_options_substitute ()

void        cairo_ft_font_options_substitute
                                            (const cairo_font_options_t *options,
                                             FcPattern *pattern);

Add options to a FcPattern based on a cairo_font_options_t font options object. Options that are already in the pattern, are not overriden, so you should call this function after calling FcConfigSubstitute() (the user's settings should override options based on the surface type), but before calling FcDefaultSubstitute().

options : | a cairo_font_options_t object
pattern : | an existing FcPattern

cairo_ft_scaled_font_lock_face ()

FT_Face     cairo_ft_scaled_font_lock_face  (cairo_scaled_font_t *scaled_font);

cairo_ft_font_lock_face() gets the FT_Face object from a FreeType backend font and scales it appropriately for the font. You must release the face with cairo_ft_font_unlock_face() when you are done using it. Since the FT_Face object can be shared between multiple cairo_scaled_font_t objects, you must not lock any other font objects until you unlock this one. A count is kept of the number of times cairo_ft_font_lock_face() is called. cairo_ft_font_unlock_face() must be called the same number of times.

You must be careful when using this function in a library or in a threaded application, because other threads may lock faces that share the same FT_Face object. For this reason, you must call cairo_ft_lock() before locking any face objects, and cairo_ft_unlock() after you are done. (These functions are not yet implemented, so this function cannot be currently safely used in a threaded application.)

scaled_font : | A cairo_scaled_font_t from the FreeType font backend. Such an object can be created by calling cairo_scaled_font_create() on a FreeType backend font face (see cairo_ft_font_face_create_for_pattern(), cairo_ft_font_face_create_for_face()).
Returns : | The FT_Face object for font, scaled appropriately, or NULL if scaled_font is in an error state (see cairo_scaled_font_status()) or there is insufficient memory.

cairo_ft_scaled_font_unlock_face ()

void        cairo_ft_scaled_font_unlock_face
                                            (cairo_scaled_font_t *scaled_font);

Releases a face obtained with cairo_ft_scaled_font_lock_face().

scaled_font : A cairo_scaled_font_t from the FreeType font backend. Such an object can be created by calling cairo_scaled_font_create() on a FreeType backend font face (see cairo_ft_font_face_create_for_pattern(), cairo_ft_font_face_create_for_ft_face()).


Image Surfaces

Image Surfaces — Rendering to memory buffers

Synopsis

enum        cairo_format_t;
cairo_surface_t* cairo_image_surface_create (cairo_format_t format,
                                             int width,
                                             int height);
cairo_surface_t* cairo_image_surface_create_for_data
                                            (unsigned char *data,
                                             cairo_format_t format,
                                             int width,
                                             int height,
                                             int stride);
unsigned char* cairo_image_surface_get_data (cairo_surface_t *surface);
cairo_format_t cairo_image_surface_get_format
                                            (cairo_surface_t *surface);
int         cairo_image_surface_get_width   (cairo_surface_t *surface);
int         cairo_image_surface_get_height  (cairo_surface_t *surface);
int         cairo_image_surface_get_stride  (cairo_surface_t *surface);

Description

Image surfaces provide the ability to render to memory buffers either allocated by cairo or by the calling code. The supported image formats are those defined in cairo_format_t.

Details

enum cairo_format_t

typedef enum _cairo_format {
    CAIRO_FORMAT_ARGB32,
    CAIRO_FORMAT_RGB24,
    CAIRO_FORMAT_A8,
    CAIRO_FORMAT_A1,
    CAIRO_FORMAT_RGB16_565
} cairo_format_t;

cairo_format_t is used to identify the memory format of image data.

New entries may be added in future versions.

CAIRO_FORMAT_ARGB32 | each pixel is a 32-bit quantity, with alpha in the upper 8 bits, then red, then green, then blue. The 32-bit quantities are stored native-endian. Pre-multiplied alpha is used. (That is, 50% transparent red is 0x80800000, not 0x80ff0000.)
CAIRO_FORMAT_RGB24 | each pixel is a 32-bit quantity, with the upper 8 bits unused. Red, Green, and Blue are stored in the remaining 24 bits in that order.
CAIRO_FORMAT_A8 | each pixel is a 8-bit quantity holding an alpha value.
CAIRO_FORMAT_A1 | each pixel is a 1-bit quantity holding an alpha value. Pixels are packed together into 32-bit quantities. The ordering of the bits matches the endianess of the platform. On a big-endian machine, the first pixel is in the uppermost bit, on a little-endian machine the first pixel is in the least-significant bit.
CAIRO_FORMAT_RGB16_565 | This format value is deprecated. It has never been properly implemented in cairo and should not be used by applications. For example, any attempt to create an image surface with a format of CAIRO_FORMAT_RGB16_565 will fail. This format value was added as part of fixing cairo's xlib backend to work with X servers advertising a 16-bit, 565 visual. But as it turned out, adding this format to cairo_format_t was not necessary, and was a mistake, (cairo's xlib backend can work fine with 16-bit visuals in the same way it works with BGR visuals without any BGR formats in cairo_format_t). (Since 1.2)

cairo_image_surface_create ()

cairo_surface_t* cairo_image_surface_create (cairo_format_t format,
                                             int width,
                                             int height);

Creates an image surface of the specified format and dimensions. Initially the surface contents are all 0. (Specifically, within each pixel, each color or alpha channel belonging to format will be 0. The contents of bits within a pixel, but not belonging to the given format are undefined).

format : | format of pixels in the surface to create
width : | width of the surface, in pixels
height : | height of the surface, in pixels
Returns : | a pointer to the newly created surface. The caller owns the surface and should call cairo_surface_destroy when done with it. This function always returns a valid pointer, but it will return a pointer to a "nil" surface if an error such as out of memory occurs. You can use cairo_surface_status() to check for this.

cairo_image_surface_create_for_data ()

cairo_surface_t* cairo_image_surface_create_for_data
                                            (unsigned char *data,
                                             cairo_format_t format,
                                             int width,
                                             int height,
                                             int stride);

Creates an image surface for the provided pixel data. The output buffer must be kept around until the cairo_surface_t is destroyed or cairo_surface_finish() is called on the surface. The initial contents of buffer will be used as the inital image contents; you must explicitely clear the buffer, using, for example, cairo_rectangle() and cairo_fill() if you want it cleared.

data : | a pointer to a buffer supplied by the application in which to write contents.
format : | the format of pixels in the buffer
width : | the width of the image to be stored in the buffer
height : | the height of the image to be stored in the buffer
stride : | the number of bytes between the start of rows in the buffer. Having this be specified separate from width allows for padding at the end of rows, or for writing to a subportion of a larger image.
Returns : | a pointer to the newly created surface. The caller owns the surface and should call cairo_surface_destroy when done with it. This function always returns a valid pointer, but it will return a pointer to a "nil" surface if an error such as out of memory occurs. You can use cairo_surface_status() to check for this. See cairo_surface_set_user_data() for a means of attaching a destroy-notification fallback to the surface if necessary.

cairo_image_surface_get_data ()

unsigned char* cairo_image_surface_get_data (cairo_surface_t *surface);

Get a pointer to the data of the image surface, for direct inspection or modification.

surface : | a cairo_image_surface_t
Returns : | a pointer to the image data of this surface or NULL if surface is not an image surface.

Since 1.2

cairo_image_surface_get_format ()

cairo_format_t cairo_image_surface_get_format
                                            (cairo_surface_t *surface);

Get the format of the surface.

surface : | a cairo_image_surface_t
Returns : | the format of the surface

Since 1.2

cairo_image_surface_get_width ()

int         cairo_image_surface_get_width   (cairo_surface_t *surface);

Get the width of the image surface in pixels.

surface : | a cairo_image_surface_t
Returns : | the width of the surface in pixels.

cairo_image_surface_get_height ()

int         cairo_image_surface_get_height  (cairo_surface_t *surface);

Get the height of the image surface in pixels.

surface : | a cairo_image_surface_t
Returns : | the height of the surface in pixels.

cairo_image_surface_get_stride ()

int         cairo_image_surface_get_stride  (cairo_surface_t *surface);

Get the stride of the image surface in bytes

surface : | a cairo_image_surface_t
Returns : | the stride of the image surface in bytes (or 0 if surface is not an image surface). The stride is the distance in bytes from the beginning of one row of the image data to the beginning of the next row.

Since 1.2


Paths

Paths — Creating paths and manipulating path data

Synopsis

            cairo_path_t;
union       cairo_path_data_t;
enum        cairo_path_data_type_t;
cairo_path_t* cairo_copy_path               (cairo_t *cr);
cairo_path_t* cairo_copy_path_flat          (cairo_t *cr);
void        cairo_path_destroy              (cairo_path_t *path);
void        cairo_append_path               (cairo_t *cr,
                                             cairo_path_t *path);
void        cairo_get_current_point         (cairo_t *cr,
                                             double *x,
                                             double *y);
void        cairo_new_path                  (cairo_t *cr);
void        cairo_new_sub_path              (cairo_t *cr);
void        cairo_close_path                (cairo_t *cr);
void        cairo_arc                       (cairo_t *cr,
                                             double xc,
                                             double yc,
                                             double radius,
                                             double angle1,
                                             double angle2);
void        cairo_arc_negative              (cairo_t *cr,
                                             double xc,
                                             double yc,
                                             double radius,
                                             double angle1,
                                             double angle2);
void        cairo_curve_to                  (cairo_t *cr,
                                             double x1,
                                             double y1,
                                             double x2,
                                             double y2,
                                             double x3,
                                             double y3);
void        cairo_line_to                   (cairo_t *cr,
                                             double x,
                                             double y);
void        cairo_move_to                   (cairo_t *cr,
                                             double x,
                                             double y);
void        cairo_rectangle                 (cairo_t *cr,
                                             double x,
                                             double y,
                                             double width,
                                             double height);
void        cairo_glyph_path                (cairo_t *cr,
                                             cairo_glyph_t *glyphs,
                                             int num_glyphs);
void        cairo_text_path                 (cairo_t *cr,
                                             const char *utf8);
void        cairo_rel_curve_to              (cairo_t *cr,
                                             double dx1,
                                             double dy1,
                                             double dx2,
                                             double dy2,
                                             double dx3,
                                             double dy3);
void        cairo_rel_line_to               (cairo_t *cr,
                                             double dx,
                                             double dy);
void        cairo_rel_move_to               (cairo_t *cr,
                                             double dx,
                                             double dy);

Description

Details

cairo_path_t

typedef struct {
    cairo_status_t status;
    cairo_path_data_t *data;
    int num_data;
} cairo_path_t;

A data structure for holding a path. This data structure serves as the return value for cairo_copy_path() and cairo_copy_path_flat() as well the input value for cairo_append_path().

See cairo_path_data_t for hints on how to iterate over the actual data within the path.

The num_data member gives the number of elements in the data array. This number is larger than the number of independent path portions (defined in cairo_path_data_type_t), since the data includes both headers and coordinates for each portion.

cairo_status_t status; | the current error status
cairo_path_data_t *data; | the elements in the path
int num_data; | the number of elements in the data array

union cairo_path_data_t

union cairo_path_data_t {
    struct {
    cairo_path_data_type_t type;
    int length;
    } header;
    struct {
    double x, y;
    } point;
};

cairo_path_data_t is used to represent the path data inside a cairo_path_t.

The data structure is designed to try to balance the demands of efficiency and ease-of-use. A path is represented as an array of cairo_path_data_t, which is a union of headers and points.

Each portion of the path is represented by one or more elements in the array, (one header followed by 0 or more points). The length value of the header is the number of array elements for the current portion including the header, (ie. length == 1 + # of points), and where the number of points for each element type must be as follows:

    CAIRO_PATH_MOVE_TO:     1 point
    CAIRO_PATH_LINE_TO:     1 point
    CAIRO_PATH_CURVE_TO:    3 points
    CAIRO_PATH_CLOSE_PATH:  0 points

The semantics and ordering of the coordinate values are consistent with cairo_move_to(), cairo_line_to(), cairo_curve_to(), and cairo_close_path().

Here is sample code for iterating through a cairo_path_t:

     int i;
     cairo_path_t *path;
     cairo_path_data_t *data;

     path = cairo_copy_path (cr);

     for (i=0; i < path->num_data; i += path->data[i].header.length) {
         data = &path->data[i];
         switch (data->header.type) {
         case CAIRO_PATH_MOVE_TO:
             do_move_to_things (data[1].point.x, data[1].point.y);
             break;
         case CAIRO_PATH_LINE_TO:
             do_line_to_things (data[1].point.x, data[1].point.y);
             break;
         case CAIRO_PATH_CURVE_TO:
             do_curve_to_things (data[1].point.x, data[1].point.y,
                                 data[2].point.x, data[2].point.y,
                                 data[3].point.x, data[3].point.y);
             break;
         case CAIRO_PATH_CLOSE_PATH:
             do_close_path_things();
             break;
         }
     }
     cairo_path_destroy (path);

enum cairo_path_data_type_t

typedef enum _cairo_path_data_type {
    CAIRO_PATH_MOVE_TO,
    CAIRO_PATH_LINE_TO,
    CAIRO_PATH_CURVE_TO,
    CAIRO_PATH_CLOSE_PATH
} cairo_path_data_type_t;

cairo_copy_path ()

cairo_path_t* cairo_copy_path               (cairo_t *cr);

Creates a copy of the current path and returns it to the user as a cairo_path_t. See cairo_path_data_t for hints on how to iterate over the returned data structure.

This function will always return a valid pointer, but the result will have no data (data==NULL and num_data==0), if either of the following conditions hold:

  1. If there is insufficient memory to copy the path. In this case path->status will be set to CAIRO_STATUS_NO_MEMORY.
  2. If cr is already in an error state. In this case path->status will contain the same status that would be returned by cairo_status().

In either case, path->status will be set to CAIRO_STATUS_NO_MEMORY (regardless of what the error status in cr might have been).

cr : | a cairo context
Returns : | the copy of the current path. The caller owns the returned object and should call cairo_path_destroy() when finished with it.

cairo_copy_path_flat ()

cairo_path_t* cairo_copy_path_flat          (cairo_t *cr);

Gets a flattened copy of the current path and returns it to the user as a cairo_path_t. See cairo_path_data_t for hints on how to iterate over the returned data structure.

This function is like cairo_copy_path() except that any curves in the path will be approximated with piecewise-linear approximations, (accurate to within the current tolerance value). That is, the result is guaranteed to not have any elements of type CAIRO_PATH_CURVE_TO which will instead be replaced by a series of CAIRO_PATH_LINE_TO elements.

This function will always return a valid pointer, but the result will have no data (data==NULL and num_data==0), if either of the following conditions hold:

  1. If there is insufficient memory to copy the path. In this case path->status will be set to CAIRO_STATUS_NO_MEMORY.
  2. If cr is already in an error state. In this case path->status will contain the same status that would be returned by cairo_status().

cr : | a cairo context
Returns : | the copy of the current path. The caller owns the returned object and should call cairo_path_destroy() when finished with it.

cairo_path_destroy ()

void        cairo_path_destroy              (cairo_path_t *path);

Immediately releases all memory associated with path. After a call to cairo_path_destroy() the path pointer is no longer valid and should not be used further.

NOTE: cairo_path_destroy function should only be called with a pointer to a cairo_path_t returned by a cairo function. Any path that is created manually (ie. outside of cairo) should be destroyed manually as well.

path : a path previously returned by either cairo_copy_path() or cairo_copy_path_flat().

cairo_append_path ()

void        cairo_append_path               (cairo_t *cr,
                                             cairo_path_t *path);

Append the path onto the current path. The path may be either the return value from one of cairo_copy_path() or cairo_copy_path_flat() or it may be constructed manually. See cairo_path_t for details on how the path data structure should be initialized, and note that path->status must be initialized to CAIRO_STATUS_SUCCESS.

cr : | a cairo context
path : | path to be appended

cairo_get_current_point ()

void        cairo_get_current_point         (cairo_t *cr,
                                             double *x,
                                             double *y);

Gets the current point of the current path, which is conceptually the final point reached by the path so far.

The current point is returned in the user-space coordinate system. If there is no defined current point then x and y will both be set to 0.0.

Most path construction functions alter the current point. See the following for details on how they affect the current point:

cairo_new_path(), cairo_move_to(), cairo_line_to(),
cairo_curve_to(), cairo_arc(), cairo_rel_move_to(),
cairo_rel_line_to(), cairo_rel_curve_to(), cairo_arc(),
cairo_text_path(), cairo_stroke_to_path()

cr : | a cairo context
x : | return value for X coordinate of the current point
y : | return value for Y coordinate of the current point

cairo_new_path ()

void        cairo_new_path                  (cairo_t *cr);

Clears the current path. After this call there will be no path and no current point.

cr : a cairo context

cairo_new_sub_path ()

void        cairo_new_sub_path              (cairo_t *cr);

Begin a new sub-path. Note that the existing path is not affected. After this call there will be no current point.

In many cases, this call is not needed since new sub-paths are frequently started with cairo_move_to().

A call to cairo_new_sub_path() is particularly useful when beginning a new sub-path with one of the cairo_arc() calls. This makes things easier as it is no longer necessary to manually compute the arc's initial coordinates for a call to cairo_move_to().

cr : a cairo context

Since 1.2

cairo_close_path ()

void        cairo_close_path                (cairo_t *cr);

Adds a line segment to the path from the current point to the beginning of the current sub-path, (the most recent point passed to cairo_move_to()), and closes this sub-path. After this call the current point will be at the joined endpoint of the sub-path.

The behavior of cairo_close_path() is distinct from simply calling cairo_line_to() with the equivalent coordinate in the case of stroking. When a closed sub-path is stroked, there are no caps on the ends of the sub-path. Instead, there is a line join connecting the final and initial segments of the sub-path.

If there is no current point before the call to cairo_close_path, this function will have no effect.

Note: As of cairo version 1.2.4 any call to cairo_close_path will place an explicit MOVE_TO element into the path immediately after the CLOSE_PATH element, (which can be seen in cairo_copy_path() for example). This can simplify path processing in some cases as it may not be necessary to save the "last move_to point" during processing as the MOVE_TO immediately after the CLOSE_PATH will provide that point.

cr : a cairo context

cairo_arc ()

void        cairo_arc                       (cairo_t *cr,
                                             double xc,
                                             double yc,
                                             double radius,
                                             double angle1,
                                             double angle2);

Adds a circular arc of the given radius to the current path. The arc is centered at (xc, yc), begins at angle1 and proceeds in the direction of increasing angles to end at angle2. If angle2 is less than angle1 it will be progressively increased by 2*M_PI until it is greater than angle1.

If there is a current point, an initial line segment will be added to the path to connect the current point to the beginning of the arc.

Angles are measured in radians. An angle of 0.0 is in the direction of the positive X axis (in user space). An angle of M_PI/2.0 radians (90 degrees) is in the direction of the positive Y axis (in user space). Angles increase in the direction from the positive X axis toward the positive Y axis. So with the default transformation matrix, angles increase in a clockwise direction.

(To convert from degrees to radians, use degrees * (M_PI / 180.).)

This function gives the arc in the direction of increasing angles; see cairo_arc_negative() to get the arc in the direction of decreasing angles.

The arc is circular in user space. To achieve an elliptical arc, you can scale the current transformation matrix by different amounts in the X and Y directions. For example, to draw an ellipse in the box given by x, y, width, height:

cairo_save (cr);
cairo_translate (cr, x + width / 2., y + height / 2.);
cairo_scale (cr, 1. / (height / 2.), 1. / (width / 2.));
cairo_arc (cr, 0., 0., 1., 0., 2 * M_PI);
cairo_restore (cr);

cr : | a cairo context
xc : | X position of the center of the arc
yc : | Y position of the center of the arc
radius : | the radius of the arc
angle1 : | the start angle, in radians
angle2 : | the end angle, in radians

cairo_arc_negative ()

void        cairo_arc_negative              (cairo_t *cr,
                                             double xc,
                                             double yc,
                                             double radius,
                                             double angle1,
                                             double angle2);

Adds a circular arc of the given radius to the current path. The arc is centered at (xc, yc), begins at angle1 and proceeds in the direction of decreasing angles to end at angle2. If angle2 is greater than angle1 it will be progressively decreased by 2*M_PI until it is greater than angle1.

See cairo_arc() for more details. This function differs only in the direction of the arc between the two angles.

cr : | a cairo context
xc : | X position of the center of the arc
yc : | Y position of the center of the arc
radius : | the radius of the arc
angle1 : | the start angle, in radians
angle2 : | the end angle, in radians

cairo_curve_to ()

void        cairo_curve_to                  (cairo_t *cr,
                                             double x1,
                                             double y1,
                                             double x2,
                                             double y2,
                                             double x3,
                                             double y3);

Adds a cubic Bézier spline to the path from the current point to position (x3, y3) in user-space coordinates, using (x1, y1) and (x2, y2) as the control points. After this call the current point will be (x3, y3).

If there is no current point before the call to cairo_curve_to() this function will behave as if preceded by a call to cairo_move_to (cr, x1, y1).

cr : | a cairo context
x1 : | the X coordinate of the first control point
y1 : | the Y coordinate of the first control point
x2 : | the X coordinate of the second control point
y2 : | the Y coordinate of the second control point
x3 : | the X coordinate of the end of the curve
y3 : | the Y coordinate of the end of the curve

cairo_line_to ()

void        cairo_line_to                   (cairo_t *cr,
                                             double x,
                                             double y);

Adds a line to the path from the current point to position (x, y) in user-space coordinates. After this call the current point will be (x, y).

If there is no current point before the call to cairo_line_to() this function will behave as cairo_move_to (cr, x, y).

cr : | a cairo context
x : | the X coordinate of the end of the new line
y : | the Y coordinate of the end of the new line

cairo_move_to ()

void        cairo_move_to                   (cairo_t *cr,
                                             double x,
                                             double y);

Begin a new sub-path. After this call the current point will be (x, y).

cr : | a cairo context
x : | the X coordinate of the new position
y : | the Y coordinate of the new position

cairo_rectangle ()

void        cairo_rectangle                 (cairo_t *cr,
                                             double x,
                                             double y,
                                             double width,
                                             double height);

Adds a closed sub-path rectangle of the given size to the current path at position (x, y) in user-space coordinates.

This function is logically equivalent to:

cairo_move_to (cr, x, y);
cairo_rel_line_to (cr, width, 0);
cairo_rel_line_to (cr, 0, height);
cairo_rel_line_to (cr, -width, 0);
cairo_close_path (cr);

cr : | a cairo context
x : | the X coordinate of the top left corner of the rectangle
y : | the Y coordinate to the top left corner of the rectangle
width : | the width of the rectangle
height : | the height of the rectangle

cairo_glyph_path ()

void        cairo_glyph_path                (cairo_t *cr,
                                             cairo_glyph_t *glyphs,
                                             int num_glyphs);

cr :
glyphs :
num_glyphs :

cairo_text_path ()

void        cairo_text_path                 (cairo_t *cr,
                                             const char *utf8);

cr :
utf8 :

cairo_rel_curve_to ()

void        cairo_rel_curve_to              (cairo_t *cr,
                                             double dx1,
                                             double dy1,
                                             double dx2,
                                             double dy2,
                                             double dx3,
                                             double dy3);

Relative-coordinate version of cairo_curve_to(). All offsets are relative to the current point. Adds a cubic Bézier spline to the path from the current point to a point offset from the current point by (dx3, dy3), using points offset by (dx1, dy1) and (dx2, dy2) as the control points. After this call the current point will be offset by (dx3, dy3).

Given a current point of (x, y), cairo_rel_curve_to (cr, dx1, dy1, dx2, dy2, dx3, dy3) is logically equivalent to cairo_curve_to (cr, x + dx1, y + dy1, x + dx2, y + dy2, x + dx3, y + dy3).

It is an error to call this function with no current point. Doing so will cause cr to shutdown with a status of CAIRO_STATUS_NO_CURRENT_POINT.

cr : | a cairo context
dx1 : | the X offset to the first control point
dy1 : | the Y offset to the first control point
dx2 : | the X offset to the second control point
dy2 : | the Y offset to the second control point
dx3 : | the X offset to the end of the curve
dy3 : | the Y offset to the end of the curve

cairo_rel_line_to ()

void        cairo_rel_line_to               (cairo_t *cr,
                                             double dx,
                                             double dy);

Relative-coordinate version of cairo_line_to(). Adds a line to the path from the current point to a point that is offset from the current point by (dx, dy) in user space. After this call the current point will be offset by (dx, dy).

Given a current point of (x, y), cairo_rel_line_to(cr, dx, dy) is logically equivalent to cairo_line_to (cr, x + dx, y + dy).

It is an error to call this function with no current point. Doing so will cause cr to shutdown with a status of CAIRO_STATUS_NO_CURRENT_POINT.

cr : | a cairo context
dx : | the X offset to the end of the new line
dy : | the Y offset to the end of the new line

cairo_rel_move_to ()

void        cairo_rel_move_to               (cairo_t *cr,
                                             double dx,
                                             double dy);

Begin a new sub-path. After this call the current point will offset by (x, y).

Given a current point of (x, y), cairo_rel_move_to(cr, dx, dy) is logically equivalent to cairo_move_to (cr, x + dx, y + dy).

It is an error to call this function with no current point. Doing so will cause cr to shutdown with a status of CAIRO_STATUS_NO_CURRENT_POINT.

cr : | a cairo context
dx : | the X offset
dy : | the Y offset


Patterns

Patterns — Gradients and filtered sources

Synopsis

typedef     cairo_pattern_t;
void        cairo_pattern_add_color_stop_rgb
                                            (cairo_pattern_t *pattern,
                                             double offset,
                                             double red,
                                             double green,
                                             double blue);
void        cairo_pattern_add_color_stop_rgba
                                            (cairo_pattern_t *pattern,
                                             double offset,
                                             double red,
                                             double green,
                                             double blue,
                                             double alpha);
cairo_pattern_t* cairo_pattern_create_rgb   (double red,
                                             double green,
                                             double blue);
cairo_pattern_t* cairo_pattern_create_rgba  (double red,
                                             double green,
                                             double blue,
                                             double alpha);
cairo_pattern_t* cairo_pattern_create_for_surface
                                            (cairo_surface_t *surface);
cairo_pattern_t* cairo_pattern_create_linear
                                            (double x0,
                                             double y0,
                                             double x1,
                                             double y1);
cairo_pattern_t* cairo_pattern_create_radial
                                            (double cx0,
                                             double cy0,
                                             double radius0,
                                             double cx1,
                                             double cy1,
                                             double radius1);
void        cairo_pattern_destroy           (cairo_pattern_t *pattern);
cairo_pattern_t* cairo_pattern_reference    (cairo_pattern_t *pattern);
cairo_status_t cairo_pattern_status         (cairo_pattern_t *pattern);
enum        cairo_extend_t;
void        cairo_pattern_set_extend        (cairo_pattern_t *pattern,
                                             cairo_extend_t extend);
cairo_extend_t cairo_pattern_get_extend     (cairo_pattern_t *pattern);
enum        cairo_filter_t;
void        cairo_pattern_set_filter        (cairo_pattern_t *pattern,
                                             cairo_filter_t filter);
cairo_filter_t cairo_pattern_get_filter     (cairo_pattern_t *pattern);
void        cairo_pattern_set_matrix        (cairo_pattern_t *pattern,
                                             const cairo_matrix_t *matrix);
void        cairo_pattern_get_matrix        (cairo_pattern_t *pattern,
                                             cairo_matrix_t *matrix);
enum        cairo_pattern_type_t;
cairo_pattern_type_t cairo_pattern_get_type (cairo_pattern_t *pattern);

Description

Details

cairo_pattern_t

typedef struct _cairo_pattern cairo_pattern_t;

cairo_pattern_add_color_stop_rgb ()

void        cairo_pattern_add_color_stop_rgb
                                            (cairo_pattern_t *pattern,
                                             double offset,
                                             double red,
                                             double green,
                                             double blue);

Adds an opaque color stop to a gradient pattern. The offset specifies the location along the gradient's control vector. For example, a linear gradient's control vector is from (x0,y0) to (x1,y1) while a radial gradient's control vector is from any point on the start circle to the corresponding point on the end circle.

The color is specified in the same way as in cairo_set_source_rgb().

Note: If the pattern is not a gradient pattern, (eg. a linear or radial pattern), then the pattern will be put into an error status with a status of CAIRO_STATUS_PATTERN_TYPE_MISMATCH.

pattern : | a cairo_pattern_t
offset : | an offset in the range [0.0 .. 1.0]
red : | red component of color
green : | green component of color
blue : | blue component of color

cairo_pattern_add_color_stop_rgba ()

void        cairo_pattern_add_color_stop_rgba
                                            (cairo_pattern_t *pattern,
                                             double offset,
                                             double red,
                                             double green,
                                             double blue,
                                             double alpha);

Adds a translucent color stop to a gradient pattern. The offset specifies the location along the gradient's control vector. For example, a linear gradient's control vector is from (x0,y0) to (x1,y1) while a radial gradient's control vector is from any point on the start circle to the corresponding point on the end circle.

The color is specified in the same way as in cairo_set_source_rgba().

Note: If the pattern is not a gradient pattern, (eg. a linear or radial pattern), then the pattern will be put into an error status with a status of CAIRO_STATUS_PATTERN_TYPE_MISMATCH.

pattern : | a cairo_pattern_t
offset : | an offset in the range [0.0 .. 1.0]
red : | red component of color
green : | green component of color
blue : | blue component of color
alpha : | alpha component of color

cairo_pattern_create_rgb ()

cairo_pattern_t* cairo_pattern_create_rgb   (double red,
                                             double green,
                                             double blue);

Creates a new cairo_pattern_t corresponding to an opaque color. The color components are floating point numbers in the range 0 to 1. If the values passed in are outside that range, they will be clamped.

red : | red component of the color
green : | green component of the color
blue : | blue component of the color
Returns : | the newly created cairo_pattern_t if succesful, or an error pattern in case of no memory. The caller owns the returned object and should call cairo_pattern_destroy() when finished with it. This function will always return a valid pointer, but if an error occurred the pattern status will be set to an error. To inspect the status of a pattern use cairo_pattern_status().

cairo_pattern_create_rgba ()

cairo_pattern_t* cairo_pattern_create_rgba  (double red,
                                             double green,
                                             double blue,
                                             double alpha);

Creates a new cairo_pattern_t corresponding to a translucent color. The color components are floating point numbers in the range 0 to 1. If the values passed in are outside that range, they will be clamped.

red : | red component of the color
green : | green component of the color
blue : | blue component of the color
alpha : | alpha component of the color
Returns : | the newly created cairo_pattern_t if succesful, or an error pattern in case of no memory. The caller owns the returned object and should call cairo_pattern_destroy() when finished with it. This function will always return a valid pointer, but if an error occurred the pattern status will be set to an error. To inspect the status of a pattern use cairo_pattern_status().

cairo_pattern_create_for_surface ()

cairo_pattern_t* cairo_pattern_create_for_surface
                                            (cairo_surface_t *surface);

Create a new cairo_pattern_t for the given surface.

surface : | the surface
Returns : | the newly created cairo_pattern_t if succesful, or an error pattern in case of no memory. The caller owns the returned object and should call cairo_pattern_destroy() when finished with it. This function will always return a valid pointer, but if an error occurred the pattern status will be set to an error. To inspect the status of a pattern use cairo_pattern_status().

cairo_pattern_create_linear ()

cairo_pattern_t* cairo_pattern_create_linear
                                            (double x0,
                                             double y0,
                                             double x1,
                                             double y1);

Create a new linear gradient cairo_pattern_t along the line defined by (x0, y0) and (x1, y1). Before using the gradient pattern, a number of color stops should be defined using cairo_pattern_add_color_stop_rgb() or cairo_pattern_add_color_stop_rgba().

Note: The coordinates here are in pattern space. For a new pattern, pattern space is identical to user space, but the relationship between the spaces can be changed with cairo_pattern_set_matrix().

x0 : | x coordinate of the start point
y0 : | y coordinate of the start point
x1 : | x coordinate of the end point
y1 : | y coordinate of the end point
Returns : | the newly created cairo_pattern_t if succesful, or an error pattern in case of no memory. The caller owns the returned object and should call cairo_pattern_destroy() when finished with it. This function will always return a valid pointer, but if an error occurred the pattern status will be set to an error. To inspect the status of a pattern use cairo_pattern_status().

cairo_pattern_create_radial ()

cairo_pattern_t* cairo_pattern_create_radial
                                            (double cx0,
                                             double cy0,
                                             double radius0,
                                             double cx1,
                                             double cy1,
                                             double radius1);

Creates a new radial gradient cairo_pattern_t between the two circles defined by (x0, y0, c0) and (x1, y1, c0). Before using the gradient pattern, a number of color stops should be defined using cairo_pattern_add_color_stop_rgb() or cairo_pattern_add_color_stop_rgba().

Note: The coordinates here are in pattern space. For a new pattern, pattern space is identical to user space, but the relationship between the spaces can be changed with cairo_pattern_set_matrix().

cx0 : | x coordinate for the center of the start circle
cy0 : | y coordinate for the center of the start circle
radius0 : | radius of the start cirle
cx1 : | x coordinate for the center of the end circle
cy1 : | y coordinate for the center of the end circle
radius1 : | radius of the end cirle
Returns : | the newly created cairo_pattern_t if succesful, or an error pattern in case of no memory. The caller owns the returned object and should call cairo_pattern_destroy() when finished with it. This function will always return a valid pointer, but if an error occurred the pattern status will be set to an error. To inspect the status of a pattern use cairo_pattern_status().

cairo_pattern_destroy ()

void        cairo_pattern_destroy           (cairo_pattern_t *pattern);

Decreases the reference count on pattern by one. If the result is zero, then pattern and all associated resources are freed. See cairo_pattern_reference().

pattern : a cairo_pattern_t

cairo_pattern_reference ()

cairo_pattern_t* cairo_pattern_reference    (cairo_pattern_t *pattern);

Increases the reference count on pattern by one. This prevents pattern from being destroyed until a matching call to cairo_pattern_destroy() is made.

pattern : | a cairo_pattern_t
Returns : | the referenced cairo_pattern_t.

cairo_pattern_status ()

cairo_status_t cairo_pattern_status         (cairo_pattern_t *pattern);

Checks whether an error has previously occurred for this pattern.

pattern : | a cairo_pattern_t
Returns : | CAIRO_STATUS_SUCCESS, CAIRO_STATUS_NO_MEMORY, or CAIRO_STATUS_PATTERN_TYPE_MISMATCH.

enum cairo_extend_t

typedef enum _cairo_extend {
    CAIRO_EXTEND_NONE,
    CAIRO_EXTEND_REPEAT,
    CAIRO_EXTEND_REFLECT,
    CAIRO_EXTEND_PAD
} cairo_extend_t;

cairo_extend_t is used to describe how the area outside of a pattern will be drawn.

New entries may be added in future versions.

CAIRO_EXTEND_NONE | pixels outside of the source pattern are fully transparent
CAIRO_EXTEND_REPEAT | the pattern is tiled by repeating
CAIRO_EXTEND_REFLECT | the pattern is tiled by reflecting at the edges (not implemented for surface patterns currently)
CAIRO_EXTEND_PAD | pixels outside of the pattern copy the closest pixel from the source (Since 1.2; not implemented for surface patterns currently)

cairo_pattern_set_extend ()

void        cairo_pattern_set_extend        (cairo_pattern_t *pattern,
                                             cairo_extend_t extend);

Sets the mode to be used for drawing outside the area of a pattern. See cairo_extend_t for details on the semantics of each extend strategy.

pattern : | a cairo_pattern_t
extend : | a cairo_extend_t describing how the area outside of the pattern will be drawn

cairo_pattern_get_extend ()

cairo_extend_t cairo_pattern_get_extend     (cairo_pattern_t *pattern);

Gets the current extend mode for a pattern. See cairo_extend_t for details on the semantics of each extend strategy.

pattern : | a cairo_pattern_t
Returns : | the current extend strategy used for drawing the pattern.

enum cairo_filter_t

typedef enum _cairo_filter {
    CAIRO_FILTER_FAST,
    CAIRO_FILTER_GOOD,
    CAIRO_FILTER_BEST,
    CAIRO_FILTER_NEAREST,
    CAIRO_FILTER_BILINEAR,
    CAIRO_FILTER_GAUSSIAN
} cairo_filter_t;

cairo_pattern_set_filter ()

void        cairo_pattern_set_filter        (cairo_pattern_t *pattern,
                                             cairo_filter_t filter);

pattern :
filter :

cairo_pattern_get_filter ()

cairo_filter_t cairo_pattern_get_filter     (cairo_pattern_t *pattern);

pattern :
Returns :

cairo_pattern_set_matrix ()

void        cairo_pattern_set_matrix        (cairo_pattern_t *pattern,
                                             const cairo_matrix_t *matrix);

Sets the pattern's transformation matrix to matrix. This matrix is a transformation from user space to pattern space.

When a pattern is first created it always has the identity matrix for its transformation matrix, which means that pattern space is initially identical to user space.

Important: Please note that the direction of this transformation matrix is from user space to pattern space. This means that if you imagine the flow from a pattern to user space (and on to device space), then coordinates in that flow will be transformed by the inverse of the pattern matrix.

For example, if you want to make a pattern appear twice as large as it does by default the correct code to use is:

cairo_matrix_init_scale (&matrix, 0.5, 0.5);
cairo_pattern_set_matrix (pattern, &matrix);

Meanwhile, using values of 2.0 rather than 0.5 in the code above would cause the pattern to appear at half of its default size.

Also, please note the discussion of the user-space locking semantics of cairo_set_source().

pattern : | a cairo_pattern_t
matrix : | a cairo_matrix_t

cairo_pattern_get_matrix ()

void        cairo_pattern_get_matrix        (cairo_pattern_t *pattern,
                                             cairo_matrix_t *matrix);

Stores the pattern's transformation matrix into matrix.

pattern : | a cairo_pattern_t
matrix : | return value for the matrix

enum cairo_pattern_type_t

typedef enum _cairo_pattern_type {
    CAIRO_PATTERN_TYPE_SOLID,
    CAIRO_PATTERN_TYPE_SURFACE,
    CAIRO_PATTERN_TYPE_LINEAR,
    CAIRO_PATTERN_TYPE_RADIAL
} cairo_pattern_type_t;

cairo_pattern_type_t is used to describe the type of a given pattern.

The type of a pattern is determined by the function used to create it. The cairo_pattern_create_rgb() and cairo_pattern_create_rgba() functions create SOLID patterns. The remaining cairo_pattern_create functions map to pattern types in obvious ways.

The pattern type can be queried with cairo_pattern_get_type()

Most cairo_pattern functions can be called with a pattern of any type, (though trying to change the extend or filter for a solid pattern will have no effect). A notable exception is cairo_pattern_add_color_stop_rgb() and cairo_pattern_add_color_stop_rgba() which must only be called with gradient patterns (either LINEAR or RADIAL). Otherwise the pattern will be shutdown and put into an error state.

New entries may be added in future versions.

CAIRO_PATTERN_TYPE_SOLID | The pattern is a solid (uniform) color. It may be opaque or translucent.
CAIRO_PATTERN_TYPE_SURFACE | The pattern is a based on a surface (an image).
CAIRO_PATTERN_TYPE_LINEAR | The pattern is a linear gradient.
CAIRO_PATTERN_TYPE_RADIAL | The pattern is a radial gradient.

Since 1.2

cairo_pattern_get_type ()

cairo_pattern_type_t cairo_pattern_get_type (cairo_pattern_t *pattern);

This function returns the type a pattern. See cairo_pattern_type_t for available types.

pattern : | a cairo_pattern_t
Returns : | The type of pattern.

Since 1.2


PDF Surfaces

PDF Surfaces — Rendering PDF documents

Synopsis

cairo_surface_t* cairo_pdf_surface_create   (const char *filename,
                                             double width_in_points,
                                             double height_in_points);
cairo_surface_t* cairo_pdf_surface_create_for_stream
                                            (cairo_write_func_t write_func,
                                             void *closure,
                                             double width_in_points,
                                             double height_in_points);
void        cairo_pdf_surface_set_size      (cairo_surface_t *surface,
                                             double width_in_points,
                                             double height_in_points);

Description

Details

cairo_pdf_surface_create ()

cairo_surface_t* cairo_pdf_surface_create   (const char *filename,
                                             double width_in_points,
                                             double height_in_points);

Creates a PDF surface of the specified size in points to be written to filename.

filename : | a filename for the PDF output (must be writable)
width_in_points : | width of the surface, in points (1 point == 1/72.0 inch)
height_in_points : | height of the surface, in points (1 point == 1/72.0 inch)
Returns : | a pointer to the newly created surface. The caller owns the surface and should call cairo_surface_destroy when done with it. This function always returns a valid pointer, but it will return a pointer to a "nil" surface if an error such as out of memory occurs. You can use cairo_surface_status() to check for this.

Since 1.2

cairo_pdf_surface_create_for_stream ()

cairo_surface_t* cairo_pdf_surface_create_for_stream
                                            (cairo_write_func_t write_func,
                                             void *closure,
                                             double width_in_points,
                                             double height_in_points);

Creates a PDF surface of the specified size in points to be written incrementally to the stream represented by write_func and closure.

write_func : | a cairo_write_func_t to accept the output data
closure : | the closure argument for write_func
width_in_points : | width of the surface, in points (1 point == 1/72.0 inch)
height_in_points : | height of the surface, in points (1 point == 1/72.0 inch)
Returns : | a pointer to the newly created surface. The caller owns the surface and should call cairo_surface_destroy when done with it. This function always returns a valid pointer, but it will return a pointer to a "nil" surface if an error such as out of memory occurs. You can use cairo_surface_status() to check for this.

Since 1.2

cairo_pdf_surface_set_size ()

void        cairo_pdf_surface_set_size      (cairo_surface_t *surface,
                                             double width_in_points,
                                             double height_in_points);

Changes the size of a PDF surface for the current (and subsequent) pages.

This function should only be called before any drawing operations have been performed on the current page. The simplest way to do this is to call this function immediately after creating the surface or immediately after completing a page with either cairo_show_page() or cairo_copy_page().

surface : | a PDF cairo_surface_t
width_in_points : | new surface width, in points (1 point == 1/72.0 inch)
height_in_points : | new surface height, in points (1 point == 1/72.0 inch)

Since 1.2


PNG Support

PNG Support — Reading and writing PNG images

Synopsis

cairo_surface_t* cairo_image_surface_create_from_png
                                            (const char *filename);
cairo_status_t (*cairo_read_func_t)         (void *closure,
                                             unsigned char *data,
                                             unsigned int length);
cairo_surface_t* cairo_image_surface_create_from_png_stream
                                            (cairo_read_func_t read_func,
                                             void *closure);
cairo_status_t cairo_surface_write_to_png   (cairo_surface_t *surface,
                                             const char *filename);
cairo_status_t (*cairo_write_func_t)        (void *closure,
                                             unsigned char *data,
                                             unsigned int length);
cairo_status_t cairo_surface_write_to_png_stream
                                            (cairo_surface_t *surface,
                                             cairo_write_func_t write_func,
                                             void *closure);

Description

Details

cairo_image_surface_create_from_png ()

cairo_surface_t* cairo_image_surface_create_from_png
                                            (const char *filename);

Creates a new image surface and initializes the contents to the given PNG file.

filename : | name of PNG file to load
Returns : | a new cairo_surface_t initialized with the contents of the PNG file, or a "nil" surface if any error occurred. A nil surface can be checked for with cairo_surface_status(surface) which may return one of the following values: CAIRO_STATUS_NO_MEMORY CAIRO_STATUS_FILE_NOT_FOUND CAIRO_STATUS_READ_ERROR

cairo_read_func_t ()

cairo_status_t (*cairo_read_func_t)         (void *closure,
                                             unsigned char *data,
                                             unsigned int length);

cairo_read_func_t is the type of function which is called when a backend needs to read data from an intput stream. It is passed the closure which was specified by the user at the time the read function was registered, the buffer to read the data into and the length of the data in bytes. The read function should return CAIRO_STATUS_SUCCESS if all the data was successfully read, CAIRO_STATUS_READ_ERROR otherwise.

closure : | the input closure
data : | the buffer into which to read the data
length : | the amount of data to read
Returns : | the status code of the read operation

cairo_image_surface_create_from_png_stream ()

cairo_surface_t* cairo_image_surface_create_from_png_stream
                                            (cairo_read_func_t read_func,
                                             void *closure);

Creates a new image surface from PNG data read incrementally via the read_func function.

read_func : | function called to read the data of the file
closure : | data to pass to read_func.
Returns : | a new cairo_surface_t initialized with the contents of the PNG file or NULL if the data read is not a valid PNG image or memory could not be allocated for the operation.

cairo_surface_write_to_png ()

cairo_status_t cairo_surface_write_to_png   (cairo_surface_t *surface,
                                             const char *filename);

Writes the contents of surface to a new file filename as a PNG image.

surface : | a cairo_surface_t with pixel contents
filename : | the name of a file to write to
Returns : | CAIRO_STATUS_SUCCESS if the PNG file was written successfully. Otherwise, CAIRO_STATUS_NO_MEMORY if memory could not be allocated for the operation or CAIRO_STATUS_SURFACE_TYPE_MISMATCH if the surface does not have pixel contents, or CAIRO_STATUS_WRITE_ERROR if an I/O error occurs while attempting to write the file.

cairo_write_func_t ()

cairo_status_t (*cairo_write_func_t)        (void *closure,
                                             unsigned char *data,
                                             unsigned int length);

cairo_write_func_t is the type of function which is called when a backend needs to write data to an output stream. It is passed the closure which was specified by the user at the time the write function was registered, the data to write and the length of the data in bytes. The write function should return CAIRO_STATUS_SUCCESS if all the data was successfully written, CAIRO_STATUS_WRITE_ERROR otherwise.

closure : | the output closure
data : | the buffer containing the data to write
length : | the amount of data to write
Returns : | the status code of the write operation

cairo_surface_write_to_png_stream ()

cairo_status_t cairo_surface_write_to_png_stream
                                            (cairo_surface_t *surface,
                                             cairo_write_func_t write_func,
                                             void *closure);

Writes the image surface to the write function.

surface : | a cairo_surface_t with pixel contents
write_func : | a cairo_write_func_t
closure : | closure data for the write function
Returns : | CAIRO_STATUS_SUCCESS if the PNG file was written successfully. Otherwise, CAIRO_STATUS_NO_MEMORY is returned if memory could not be allocated for the operation, CAIRO_STATUS_SURFACE_TYPE_MISMATCH if the surface does not have pixel contents.


PostScript Surfaces

PostScript Surfaces — Rendering PostScript documents

Synopsis

cairo_surface_t* cairo_ps_surface_create    (const char *filename,
                                             double width_in_points,
                                             double height_in_points);
cairo_surface_t* cairo_ps_surface_create_for_stream
                                            (cairo_write_func_t write_func,
                                             void *closure,
                                             double width_in_points,
                                             double height_in_points);
void        cairo_ps_surface_set_size       (cairo_surface_t *surface,
                                             double width_in_points,
                                             double height_in_points);
void        cairo_ps_surface_dsc_begin_setup
                                            (cairo_surface_t *surface);
void        cairo_ps_surface_dsc_begin_page_setup
                                            (cairo_surface_t *surface);
void        cairo_ps_surface_dsc_comment    (cairo_surface_t *surface,
                                             const char *comment);

Description

Details

cairo_ps_surface_create ()

cairo_surface_t* cairo_ps_surface_create    (const char *filename,
                                             double width_in_points,
                                             double height_in_points);

Creates a PostScript surface of the specified size in points to be written to filename. See cairo_ps_surface_create_for_stream() for a more flexible mechanism for handling the PostScript output than simply writing it to a named file.

Note that the size of individual pages of the PostScript output can vary. See cairo_ps_surface_set_size().

filename : | a filename for the PS output (must be writable)
width_in_points : | width of the surface, in points (1 point == 1/72.0 inch)
height_in_points : | height of the surface, in points (1 point == 1/72.0 inch)
Returns : | a pointer to the newly created surface. The caller owns the surface and should call cairo_surface_destroy when done with it. This function always returns a valid pointer, but it will return a pointer to a "nil" surface if an error such as out of memory occurs. You can use cairo_surface_status() to check for this.

Since 1.2

cairo_ps_surface_create_for_stream ()

cairo_surface_t* cairo_ps_surface_create_for_stream
                                            (cairo_write_func_t write_func,
                                             void *closure,
                                             double width_in_points,
                                             double height_in_points);

Creates a PostScript surface of the specified size in points to be written incrementally to the stream represented by write_func and closure. See cairo_ps_surface_create() for a more convenient way to simply direct the PostScript output to a named file.

Note that the size of individual pages of the PostScript output can vary. See cairo_ps_surface_set_size().

write_func : | a cairo_write_func_t to accept the output data
closure : | the closure argument for write_func
width_in_points : | width of the surface, in points (1 point == 1/72.0 inch)
height_in_points : | height of the surface, in points (1 point == 1/72.0 inch)
Returns : | a pointer to the newly created surface. The caller owns the surface and should call cairo_surface_destroy when done with it. This function always returns a valid pointer, but it will return a pointer to a "nil" surface if an error such as out of memory occurs. You can use cairo_surface_status() to check for this.

Since 1.2

cairo_ps_surface_set_size ()

void        cairo_ps_surface_set_size       (cairo_surface_t *surface,
                                             double width_in_points,
                                             double height_in_points);

Changes the size of a PostScript surface for the current (and subsequent) pages.

This function should only be called before any drawing operations have been performed on the current page. The simplest way to do this is to call this function immediately after creating the surface or immediately after completing a page with either cairo_show_page() or cairo_copy_page().

surface : | a PostScript cairo_surface_t
width_in_points : | new surface width, in points (1 point == 1/72.0 inch)
height_in_points : | new surface height, in points (1 point == 1/72.0 inch)

Since 1.2

cairo_ps_surface_dsc_begin_setup ()

void        cairo_ps_surface_dsc_begin_setup
                                            (cairo_surface_t *surface);

This function indicates that subsequent calls to cairo_ps_surface_dsc_comment() should direct comments to the Setup section of the PostScript output.

This function should be called at most once per surface, and must be called before any call to cairo_ps_surface_dsc_begin_page_setup() and before any drawing is performed to the surface.

See cairo_ps_surface_dsc_comment() for more details.

surface : a PostScript cairo_surface_t

Since 1.2

cairo_ps_surface_dsc_begin_page_setup ()

void        cairo_ps_surface_dsc_begin_page_setup
                                            (cairo_surface_t *surface);

This function indicates that subsequent calls to cairo_ps_surface_dsc_comment() should direct comments to the PageSetup section of the PostScript output.

This function call is only needed for the first page of a surface. It should be called after any call to cairo_ps_surface_dsc_begin_setup() and before any drawing is performed to the surface.

See cairo_ps_surface_dsc_comment() for more details.

surface : a PostScript cairo_surface_t

Since 1.2

cairo_ps_surface_dsc_comment ()

void        cairo_ps_surface_dsc_comment    (cairo_surface_t *surface,
                                             const char *comment);

Emit a comment into the PostScript output for the given surface.

The comment is expected to conform to the PostScript Language Document Structuring Conventions (DSC). Please see that manual for details on the available comments and their meanings. In particular, the %IncludeFeature comment allows a device-independent means of controlling printer device features. So the PostScript Printer Description Files Specification will also be a useful reference.

The comment string must begin with a percent character (%) and the total length of the string (including any initial percent characters) must not exceed 255 characters. Violating either of these conditions will place surface into an error state. But beyond these two conditions, this function will not enforce conformance of the comment with any particular specification.

The comment string should not have a trailing newline.

The DSC specifies different sections in which particular comments can appear. This function provides for comments to be emitted within three sections: the header, the Setup section, and the PageSetup section. Comments appearing in the first two sections apply to the entire document while comments in the BeginPageSetup section apply only to a single page.

For comments to appear in the header section, this function should be called after the surface is created, but before a call to cairo_ps_surface_begin_setup().

For comments to appear in the Setup section, this function should be called after a call to cairo_ps_surface_begin_setup() but before a call to cairo_ps_surface_begin_page_setup().

For comments to appear in the PageSetup section, this function should be called after a call to cairo_ps_surface_begin_page_setup().

Note that it is only necessary to call cairo_ps_surface_begin_page_setup() for the first page of any surface. After a call to cairo_show_page() or cairo_copy_page() comments are unambiguously directed to the PageSetup section of the current page. But it doesn't hurt to call this function at the beginning of every page as that consistency may make the calling code simpler.

As a final note, cairo automatically generates several comments on its own. As such, applications must not manually generate any of the following comments:

Header section: %!PS-Adobe-3.0, %Creator, %CreationDate, %Pages, %BoundingBox, %DocumentData, %LanguageLevel, %EndComments.

Setup section: %BeginSetup, %EndSetup

PageSetup section: %BeginPageSetup, %PageBoundingBox, %EndPageSetup.

Other sections: %BeginProlog, %EndProlog, %Page, %Trailer, %EOF

Here is an example sequence showing how this function might be used:

cairo_surface_t *surface = cairo_ps_surface_create (filename, width, height);
...
cairo_ps_surface_dsc_comment (surface, "%Title: My excellent document");
cairo_ps_surface_dsc_comment (surface, "%Copyright: Copyright (C) 2006 Cairo Lover")
...
cairo_ps_surface_dsc_begin_setup (surface);
cairo_ps_surface_dsc_comment (surface, "%IncludeFeature: *MediaColor White");
...
cairo_ps_surface_dsc_begin_page_setup (surface);
cairo_ps_surface_dsc_comment (surface, "%IncludeFeature: *PageSize A3");
cairo_ps_surface_dsc_comment (surface, "%IncludeFeature: *InputSlot LargeCapacity");
cairo_ps_surface_dsc_comment (surface, "%IncludeFeature: *MediaType Glossy");
cairo_ps_surface_dsc_comment (surface, "%IncludeFeature: *MediaColor Blue");
... draw to first page here ..
cairo_show_page (cr);
...
cairo_ps_surface_dsc_comment (surface, "%IncludeFeature: *PageSize A5");
...

surface : | a PostScript cairo_surface_t
comment : | a comment string to be emitted into the PostScript output

Since 1.2


Scaled Fonts

Scaled Fonts — Caching metrics for a particular font size

Synopsis

typedef     cairo_scaled_font_t;
cairo_scaled_font_t* cairo_scaled_font_create
                                            (cairo_font_face_t *font_face,
                                             const cairo_matrix_t *font_matrix,
                                             const cairo_matrix_t *ctm,
                                             const cairo_font_options_t *options);
cairo_scaled_font_t* cairo_scaled_font_reference
                                            (cairo_scaled_font_t *scaled_font);
void        cairo_scaled_font_destroy       (cairo_scaled_font_t *scaled_font);
cairo_status_t cairo_scaled_font_status     (cairo_scaled_font_t *scaled_font);
            cairo_font_extents_t;
void        cairo_scaled_font_extents       (cairo_scaled_font_t *scaled_font,
                                             cairo_font_extents_t *extents);
            cairo_text_extents_t;
void        cairo_scaled_font_text_extents  (cairo_scaled_font_t *scaled_font,
                                             const char *utf8,
                                             cairo_text_extents_t *extents);
void        cairo_scaled_font_glyph_extents (cairo_scaled_font_t *scaled_font,
                                             cairo_glyph_t *glyphs,
                                             int num_glyphs,
                                             cairo_text_extents_t *extents);
cairo_font_face_t* cairo_scaled_font_get_font_face
                                            (cairo_scaled_font_t *scaled_font);
void        cairo_scaled_font_get_font_options
                                            (cairo_scaled_font_t *scaled_font,
                                             cairo_font_options_t *options);
void        cairo_scaled_font_get_font_matrix
                                            (cairo_scaled_font_t *scaled_font,
                                             cairo_matrix_t *font_matrix);
void        cairo_scaled_font_get_ctm       (cairo_scaled_font_t *scaled_font,
                                             cairo_matrix_t *ctm);
cairo_font_type_t cairo_scaled_font_get_type
                                            (cairo_scaled_font_t *scaled_font);

Description

Details

cairo_scaled_font_t

typedef struct _cairo_scaled_font cairo_scaled_font_t;

A cairo_scaled_font_t is a font scaled to a particular size and device resolution. A cairo_scaled_font_t is most useful for low-level font usage where a library or application wants to cache a reference to a scaled font to speed up the computation of metrics.

cairo_scaled_font_create ()

cairo_scaled_font_t* cairo_scaled_font_create
                                            (cairo_font_face_t *font_face,
                                             const cairo_matrix_t *font_matrix,
                                             const cairo_matrix_t *ctm,
                                             const cairo_font_options_t *options);

Creates a cairo_scaled_font_t object from a font face and matrices that describe the size of the font and the environment in which it will be used.

font_face : | a cairo_font_face_t
font_matrix : | font space to user space transformation matrix for the font. In the simplest case of a N point font, this matrix is just a scale by N, but it can also be used to shear the font or stretch it unequally along the two axes. See cairo_set_font_matrix().
ctm : | user to device transformation matrix with which the font will be used.
options : | options to use when getting metrics for the font and rendering with it.
Returns : | a newly created cairo_scaled_font_t. Destroy with cairo_scaled_font_destroy()

cairo_scaled_font_reference ()

cairo_scaled_font_t* cairo_scaled_font_reference
                                            (cairo_scaled_font_t *scaled_font);

Increases the reference count on scaled_font by one. This prevents scaled_font from being destroyed until a matching call to cairo_scaled_font_destroy() is made.

scaled_font : | a cairo_scaled_font_t, (may be NULL in which case this function does nothing)
Returns : | the referenced cairo_scaled_font_t

cairo_scaled_font_destroy ()

void        cairo_scaled_font_destroy       (cairo_scaled_font_t *scaled_font);

Decreases the reference count on font by one. If the result is zero, then font and all associated resources are freed. See cairo_scaled_font_reference().

scaled_font : a cairo_scaled_font_t

cairo_scaled_font_status ()

cairo_status_t cairo_scaled_font_status     (cairo_scaled_font_t *scaled_font);

Checks whether an error has previously occurred for this scaled_font.

scaled_font : | a cairo_scaled_font_t
Returns : | CAIRO_STATUS_SUCCESS or another error such as CAIRO_STATUS_NO_MEMORY.

cairo_font_extents_t

typedef struct {
    double ascent;
    double descent;
    double height;
    double max_x_advance;
    double max_y_advance;
} cairo_font_extents_t;

The cairo_font_extents_t structure stores metric information for a font. Values are given in the current user-space coordinate system.

Because font metrics are in user-space coordinates, they are mostly, but not entirely, independent of the current transformation matrix. If you call cairo_scale(cr, 2.0, 2.0), text will be drawn twice as big, but the reported text extents will not be doubled. They will change slightly due to hinting (so you can't assume that metrics are independent of the transformation matrix), but otherwise will remain unchanged.

double ascent; | the distance that the font extends above the baseline. Note that this is not always exactly equal to the maximum of the extents of all the glyphs in the font, but rather is picked to express the font designer's intent as to how the font should align with elements above it.
double descent; | the distance that the font extends below the baseline. This value is positive for typical fonts that include portions below the baseline. Note that this is not always exactly equal to the maximum of the extents of all the glyphs in the font, but rather is picked to express the font designer's intent as to how the the font should align with elements below it.
double height; | the recommended vertical distance between baselines when setting consecutive lines of text with the font. This is greater than ascent+descent by a quantity known as the line spacing or external leading. When space is at a premium, most fonts can be set with only a distance of ascent+descent between lines.
double max_x_advance; | the maximum distance in the X direction that the the origin is advanced for any glyph in the font.
double max_y_advance; | the maximum distance in the Y direction that the the origin is advanced for any glyph in the font. this will be zero for normal fonts used for horizontal writing. (The scripts of East Asia are sometimes written vertically.)

cairo_scaled_font_extents ()

void        cairo_scaled_font_extents       (cairo_scaled_font_t *scaled_font,
                                             cairo_font_extents_t *extents);

Gets the metrics for a cairo_scaled_font_t.

scaled_font : | a cairo_scaled_font_t
extents : | a cairo_font_extents_t which to store the retrieved extents.

cairo_text_extents_t

typedef struct {
    double x_bearing;
    double y_bearing;
    double width;
    double height;
    double x_advance;
    double y_advance;
} cairo_text_extents_t;

The cairo_text_extents_t structure stores the extents of a single glyph or a string of glyphs in user-space coordinates. Because text extents are in user-space coordinates, they are mostly, but not entirely, independent of the current transformation matrix. If you call cairo_scale(cr, 2.0, 2.0), text will be drawn twice as big, but the reported text extents will not be doubled. They will change slightly due to hinting (so you can't assume that metrics are independent of the transformation matrix), but otherwise will remain unchanged.

double x_bearing; | the horizontal distance from the origin to the leftmost part of the glyphs as drawn. Positive if the glyphs lie entirely to the right of the origin.
double y_bearing; | the vertical distance from the origin to the topmost part of the glyphs as drawn. Positive only if the glyphs lie completely below the origin; will usually be negative.
double width; | width of the glyphs as drawn
double height; | height of the glyphs as drawn
double x_advance; | distance to advance in the X direction after drawing these glyphs
double y_advance; | distance to advance in the Y direction after drawing these glyphs. Will typically be zero except for vertical text layout as found in East-Asian languages.

cairo_scaled_font_text_extents ()

void        cairo_scaled_font_text_extents  (cairo_scaled_font_t *scaled_font,
                                             const char *utf8,
                                             cairo_text_extents_t *extents);

Gets the extents for a string of text. The extents describe a user-space rectangle that encloses the "inked" portion of the text drawn at the origin (0,0) (as it would be drawn by cairo_show_text() if the cairo graphics state were set to the same font_face, font_matrix, ctm, and font_options as scaled_font). Additionally, the x_advance and y_advance values indicate the amount by which the current point would be advanced by cairo_show_text().

Note that whitespace characters do not directly contribute to the size of the rectangle (extents.width and extents.height). They do contribute indirectly by changing the position of non-whitespace characters. In particular, trailing whitespace characters are likely to not affect the size of the rectangle, though they will affect the x_advance and y_advance values.

scaled_font : | a cairo_scaled_font_t
utf8 : | a string of text, encoded in UTF-8
extents : | a cairo_text_extents_t which to store the retrieved extents.

Since 1.2

cairo_scaled_font_glyph_extents ()

void        cairo_scaled_font_glyph_extents (cairo_scaled_font_t *scaled_font,
                                             cairo_glyph_t *glyphs,
                                             int num_glyphs,
                                             cairo_text_extents_t *extents);

Gets the extents for an array of glyphs. The extents describe a user-space rectangle that encloses the "inked" portion of the glyphs, (as they would be drawn by cairo_show_glyphs() if the cairo graphics state were set to the same font_face, font_matrix, ctm, and font_options as scaled_font). Additionally, the x_advance and y_advance values indicate the amount by which the current point would be advanced by cairo_show_glyphs.

Note that whitespace glyphs do not contribute to the size of the rectangle (extents.width and extents.height).

scaled_font : | a cairo_scaled_font_t
glyphs : | an array of glyph IDs with X and Y offsets.
num_glyphs : | the number of glyphs in the glyphs array
extents : | a cairo_text_extents_t which to store the retrieved extents.

cairo_scaled_font_get_font_face ()

cairo_font_face_t* cairo_scaled_font_get_font_face
                                            (cairo_scaled_font_t *scaled_font);

Gets the font face that this scaled font was created for.

scaled_font : | a cairo_scaled_font_t
Returns : | The cairo_font_face_t with which scaled_font was created.

Since 1.2

cairo_scaled_font_get_font_options ()

void        cairo_scaled_font_get_font_options
                                            (cairo_scaled_font_t *scaled_font,
                                             cairo_font_options_t *options);

Stores the font options with which scaled_font was created into options.

scaled_font : | a cairo_scaled_font_t
options : | return value for the font options

Since 1.2

cairo_scaled_font_get_font_matrix ()

void        cairo_scaled_font_get_font_matrix
                                            (cairo_scaled_font_t *scaled_font,
                                             cairo_matrix_t *font_matrix);

Stores the font matrix with which scaled_font was created into matrix.

scaled_font : | a cairo_scaled_font_t
font_matrix : | return value for the matrix

Since 1.2

cairo_scaled_font_get_ctm ()

void        cairo_scaled_font_get_ctm       (cairo_scaled_font_t *scaled_font,
                                             cairo_matrix_t *ctm);

Stores the CTM with which scaled_font was created into ctm.

scaled_font : | a cairo_scaled_font_t
ctm : | return value for the CTM

Since 1.2

cairo_scaled_font_get_type ()

cairo_font_type_t cairo_scaled_font_get_type
                                            (cairo_scaled_font_t *scaled_font);

This function returns the type of the backend used to create a scaled font. See cairo_font_type_t for available types.

scaled_font : | a cairo_scaled_font_t
Returns : | The type of scaled_font.

Since 1.2


SVG Surfaces

SVG Surfaces — Rendering SVG documents

Synopsis

cairo_surface_t* cairo_svg_surface_create   (const char *filename,
                                             double width_in_points,
                                             double height_in_points);
cairo_surface_t* cairo_svg_surface_create_for_stream
                                            (cairo_write_func_t write_func,
                                             void *closure,
                                             double width_in_points,
                                             double height_in_points);
void        cairo_svg_surface_restrict_to_version
                                            (cairo_surface_t *surface,
                                             cairo_svg_version_t version);
enum        cairo_svg_version_t;
void        cairo_svg_get_versions          (cairo_svg_version_t const	**versions,
                                             int *num_versions);
const char* cairo_svg_version_to_string     (cairo_svg_version_t version);

Description

Details

cairo_svg_surface_create ()

cairo_surface_t* cairo_svg_surface_create   (const char *filename,
                                             double width_in_points,
                                             double height_in_points);

Creates a SVG surface of the specified size in points to be written to filename.

filename : | a filename for the SVG output (must be writable)
width_in_points : | width of the surface, in points (1 point == 1/72.0 inch)
height_in_points : | height of the surface, in points (1 point == 1/72.0 inch)
Returns : | a pointer to the newly created surface. The caller owns the surface and should call cairo_surface_destroy when done with it. This function always returns a valid pointer, but it will return a pointer to a "nil" surface if an error such as out of memory occurs. You can use cairo_surface_status() to check for this.

Since 1.2

cairo_svg_surface_create_for_stream ()

cairo_surface_t* cairo_svg_surface_create_for_stream
                                            (cairo_write_func_t write_func,
                                             void *closure,
                                             double width_in_points,
                                             double height_in_points);

Creates a SVG surface of the specified size in points to be written incrementally to the stream represented by write_func and closure.

write_func : | a cairo_write_func_t to accept the output data
closure : | the closure argument for write_func
width_in_points : | width of the surface, in points (1 point == 1/72.0 inch)
height_in_points : | height of the surface, in points (1 point == 1/72.0 inch)
Returns : | a pointer to the newly created surface. The caller owns the surface and should call cairo_surface_destroy when done with it. This function always returns a valid pointer, but it will return a pointer to a "nil" surface if an error such as out of memory occurs. You can use cairo_surface_status() to check for this.

Since 1.2

cairo_svg_surface_restrict_to_version ()

void        cairo_svg_surface_restrict_to_version
                                            (cairo_surface_t *surface,
                                             cairo_svg_version_t version);

Restricts the generated SVG file to version. See cairo_svg_get_versions() for a list of available version values that can be used here.

This function should only be called before any drawing operations have been performed on the given surface. The simplest way to do this is to call this function immediately after creating the surface.

surface : | a SVG cairo_surface_t
version : | SVG version

Since 1.2

enum cairo_svg_version_t

typedef enum {
    CAIRO_SVG_VERSION_1_1,
    CAIRO_SVG_VERSION_1_2
} cairo_svg_version_t;

cairo_svg_version_t is used to describe the version number of the SVG specification that a generated SVG file will conform to.

CAIRO_SVG_VERSION_1_1 | The version 1.1 of the SVG specification.
CAIRO_SVG_VERSION_1_2 | The version 1.2 of the SVG specification.

cairo_svg_get_versions ()

void        cairo_svg_get_versions          (cairo_svg_version_t const	**versions,
                                             int *num_versions);

Used to retrieve the list of supported versions. See cairo_svg_surface_restrict_to_version().

versions : | supported version list
num_versions : | list length

Since 1.2

cairo_svg_version_to_string ()

const char* cairo_svg_version_to_string     (cairo_svg_version_t version);

Get the string representation of the given version id. This function will return NULL if version isn't valid. See cairo_svg_get_versions() for a way to get the list of valid version ids.

version : | a version id
Returns : | the string associated to given version.

Since 1.2


Text

Text — Rendering text and sets of glyphs

Synopsis

            cairo_glyph_t;
enum        cairo_font_slant_t;
enum        cairo_font_weight_t;
void        cairo_select_font_face          (cairo_t *cr,
                                             const char *family,
                                             cairo_font_slant_t slant,
                                             cairo_font_weight_t weight);
void        cairo_set_font_size             (cairo_t *cr,
                                             double size);
void        cairo_set_font_matrix           (cairo_t *cr,
                                             const cairo_matrix_t *matrix);
void        cairo_get_font_matrix           (cairo_t *cr,
                                             cairo_matrix_t *matrix);
void        cairo_set_font_options          (cairo_t *cr,
                                             const cairo_font_options_t *options);
void        cairo_get_font_options          (cairo_t *cr,
                                             cairo_font_options_t *options);
void        cairo_show_text                 (cairo_t *cr,
                                             const char *utf8);
void        cairo_show_glyphs               (cairo_t *cr,
                                             cairo_glyph_t *glyphs,
                                             int num_glyphs);
cairo_font_face_t* cairo_get_font_face      (cairo_t *cr);
void        cairo_font_extents              (cairo_t *cr,
                                             cairo_font_extents_t *extents);
void        cairo_set_font_face             (cairo_t *cr,
                                             cairo_font_face_t *font_face);
void        cairo_set_scaled_font           (cairo_t *cr,
                                             const cairo_scaled_font_t *scaled_font);
void        cairo_text_extents              (cairo_t *cr,
                                             const char *utf8,
                                             cairo_text_extents_t *extents);
void        cairo_glyph_extents             (cairo_t *cr,
                                             cairo_glyph_t *glyphs,
                                             int num_glyphs,
                                             cairo_text_extents_t *extents);

Description

Details

cairo_glyph_t

typedef struct {
  unsigned long        index;
  double               x;
  double               y;
} cairo_glyph_t;

The cairo_glyph_t structure holds information about a single glyph when drawing or measuring text. A font is (in simple terms) a collection of shapes used to draw text. A glyph is one of these shapes. There can be multiple glyphs for a single character (alternates to be used in different contexts, for example), or a glyph can be a ligature of multiple characters. Cairo doesn't expose any way of converting input text into glyphs, so in order to use the Cairo interfaces that take arrays of glyphs, you must directly access the appropriate underlying font system.

Note that the offsets given by x and y are not cumulative. When drawing or measuring text, each glyph is individually positioned with respect to the overall origin

unsigned long index; | glyph index in the font. The exact interpretation of the glyph index depends on the font technology being used.
double x; | the offset in the X direction between the origin used for drawing or measuring the string and the origin of this glyph.
double y; | the offset in the Y direction between the origin used for drawing or measuring the string and the origin of this glyph.

enum cairo_font_slant_t

typedef enum _cairo_font_slant {
  CAIRO_FONT_SLANT_NORMAL,
  CAIRO_FONT_SLANT_ITALIC,
  CAIRO_FONT_SLANT_OBLIQUE
} cairo_font_slant_t;

enum cairo_font_weight_t

typedef enum _cairo_font_weight {
  CAIRO_FONT_WEIGHT_NORMAL,
  CAIRO_FONT_WEIGHT_BOLD
} cairo_font_weight_t;

cairo_select_font_face ()

void        cairo_select_font_face          (cairo_t *cr,
                                             const char *family,
                                             cairo_font_slant_t slant,
                                             cairo_font_weight_t weight);

Selects a family and style of font from a simplified description as a family name, slant and weight. This function is meant to be used only for applications with simple font needs: Cairo doesn't provide for operations such as listing all available fonts on the system, and it is expected that most applications will need to use a more comprehensive font handling and text layout library in addition to cairo.

cr : | a cairo_t
family : | a font family name, encoded in UTF-8
slant : | the slant for the font
weight : | the weight for the font

cairo_set_font_size ()

void        cairo_set_font_size             (cairo_t *cr,
                                             double size);

Sets the current font matrix to a scale by a factor of size, replacing any font matrix previously set with cairo_set_font_size() or cairo_set_font_matrix(). This results in a font size of size user space units. (More precisely, this matrix will result in the font's em-square being a size by size square in user space.)

cr : | a cairo_t
size : | the new font size, in user space units

cairo_set_font_matrix ()

void        cairo_set_font_matrix           (cairo_t *cr,
                                             const cairo_matrix_t *matrix);

Sets the current font matrix to matrix. The font matrix gives a transformation from the design space of the font (in this space, the em-square is 1 unit by 1 unit) to user space. Normally, a simple scale is used (see cairo_set_font_size()), but a more complex font matrix can be used to shear the font or stretch it unequally along the two axes

cr : | a cairo_t
matrix : | a cairo_matrix_t describing a transform to be applied to the current font.

cairo_get_font_matrix ()

void        cairo_get_font_matrix           (cairo_t *cr,
                                             cairo_matrix_t *matrix);

Stores the current font matrix into matrix. See cairo_set_font_matrix().

cr : | a cairo_t
matrix : | return value for the matrix

cairo_set_font_options ()

void        cairo_set_font_options          (cairo_t *cr,
                                             const cairo_font_options_t *options);

Sets a set of custom font rendering options for the cairo_t. Rendering options are derived by merging these options with the options derived from underlying surface; if the value in options has a default value (like CAIRO_ANTIALIAS_DEFAULT), then the value from the surface is used.

cr : | a cairo_t
options : | font options to use

cairo_get_font_options ()

void        cairo_get_font_options          (cairo_t *cr,
                                             cairo_font_options_t *options);

Retrieves font rendering options set via cairo_set_font_options. Note that the returned options do not include any options derived from the underlying surface; they are literally the options passed to cairo_set_font_options().

cr : | a cairo_t
options : | a cairo_font_options_t object into which to store the retrieved options. All existing values are overwritten

cairo_show_text ()

void        cairo_show_text                 (cairo_t *cr,
                                             const char *utf8);

A drawing operator that generates the shape from a string of UTF-8 characters, rendered according to the current font_face, font_size (font_matrix), and font_options.

This function first computes a set of glyphs for the string of text. The first glyph is placed so that its origin is at the current point. The origin of each subsequent glyph is offset from that of the previous glyph by the advance values of the previous glyph.

After this call the current point is moved to the origin of where the next glyph would be placed in this same progression. That is, the current point will be at the origin of the final glyph offset by its advance values. This allows for easy display of a single logical string with multiple calls to cairo_show_text().

NOTE: The cairo_show_text() function call is part of what the cairo designers call the "toy" text API. It is convenient for short demos and simple programs, but it is not expected to be adequate for the most serious of text-using applications. See cairo_show_glyphs() for the "real" text display API in cairo.

cr : | a cairo context
utf8 : | a string of text encoded in UTF-8

cairo_show_glyphs ()

void        cairo_show_glyphs               (cairo_t *cr,
                                             cairo_glyph_t *glyphs,
                                             int num_glyphs);

cr :
glyphs :
num_glyphs :

cairo_get_font_face ()

cairo_font_face_t* cairo_get_font_face      (cairo_t *cr);

Gets the current font face for a cairo_t.

cr : | a cairo_t
Returns : | the current font object. Can return NULL on out-of-memory or if the context is already in an error state. This object is owned by cairo. To keep a reference to it, you must call cairo_font_face_reference().

cairo_font_extents ()

void        cairo_font_extents              (cairo_t *cr,
                                             cairo_font_extents_t *extents);

Gets the font extents for the currently selected font.

cr : | a cairo_t
extents : | a cairo_font_extents_t object into which the results will be stored.

cairo_set_font_face ()

void        cairo_set_font_face             (cairo_t *cr,
                                             cairo_font_face_t *font_face);

Replaces the current cairo_font_face_t object in the cairo_t with font_face. The replaced font face in the cairo_t will be destroyed if there are no other references to it.

cr : | a cairo_t
font_face : | a cairo_font_face_t, or NULL to restore to the default font

cairo_set_scaled_font ()

void        cairo_set_scaled_font           (cairo_t *cr,
                                             const cairo_scaled_font_t *scaled_font);

Replaces the current font face, font matrix, and font options in the cairo_t with those of the cairo_scaled_font_t. Except for some translation, the current CTM of the cairo_t should be the same as that of the cairo_scaled_font_t, which can be accessed using cairo_scaled_font_get_ctm().

cr : | a cairo_t
scaled_font : | a cairo_scaled_font_t

Since 1.2

cairo_text_extents ()

void        cairo_text_extents              (cairo_t *cr,
                                             const char *utf8,
                                             cairo_text_extents_t *extents);

Gets the extents for a string of text. The extents describe a user-space rectangle that encloses the "inked" portion of the text, (as it would be drawn by cairo_show_text()). Additionally, the x_advance and y_advance values indicate the amount by which the current point would be advanced by cairo_show_text().

Note that whitespace characters do not directly contribute to the size of the rectangle (extents.width and extents.height). They do contribute indirectly by changing the position of non-whitespace characters. In particular, trailing whitespace characters are likely to not affect the size of the rectangle, though they will affect the x_advance and y_advance values.

cr : | a cairo_t
utf8 : | a string of text, encoded in UTF-8
extents : | a cairo_text_extents_t object into which the results will be stored

cairo_glyph_extents ()

void        cairo_glyph_extents             (cairo_t *cr,
                                             cairo_glyph_t *glyphs,
                                             int num_glyphs,
                                             cairo_text_extents_t *extents);

Gets the extents for an array of glyphs. The extents describe a user-space rectangle that encloses the "inked" portion of the glyphs, (as they would be drawn by cairo_show_glyphs()). Additionally, the x_advance and y_advance values indicate the amount by which the current point would be advanced by cairo_show_glyphs.

Note that whitespace glyphs do not contribute to the size of the rectangle (extents.width and extents.height).

cr : | a cairo_t
glyphs : | an array of cairo_glyph_t objects
num_glyphs : | the number of elements in glyphs
extents : | a cairo_text_extents_t object into which the results will be stored


Transformations

Transformations — Manipulating the current transformation matrix

Synopsis

void        cairo_translate                 (cairo_t *cr,
                                             double tx,
                                             double ty);
void        cairo_scale                     (cairo_t *cr,
                                             double sx,
                                             double sy);
void        cairo_rotate                    (cairo_t *cr,
                                             double angle);
void        cairo_transform                 (cairo_t *cr,
                                             const cairo_matrix_t *matrix);
void        cairo_set_matrix                (cairo_t *cr,
                                             const cairo_matrix_t *matrix);
void        cairo_get_matrix                (cairo_t *cr,
                                             cairo_matrix_t *matrix);
void        cairo_identity_matrix           (cairo_t *cr);
void        cairo_user_to_device            (cairo_t *cr,
                                             double *x,
                                             double *y);
void        cairo_user_to_device_distance   (cairo_t *cr,
                                             double *dx,
                                             double *dy);
void        cairo_device_to_user            (cairo_t *cr,
                                             double *x,
                                             double *y);
void        cairo_device_to_user_distance   (cairo_t *cr,
                                             double *dx,
                                             double *dy);

Description

Details

cairo_translate ()

void        cairo_translate                 (cairo_t *cr,
                                             double tx,
                                             double ty);

Modifies the current transformation matrix (CTM) by translating the user-space origin by (tx, ty). This offset is interpreted as a user-space coordinate according to the CTM in place before the new call to cairo_translate. In other words, the translation of the user-space origin takes place after any existing transformation.

cr : | a cairo context
tx : | amount to translate in the X direction
ty : | amount to translate in the Y direction

cairo_scale ()

void        cairo_scale                     (cairo_t *cr,
                                             double sx,
                                             double sy);

Modifies the current transformation matrix (CTM) by scaling the X and Y user-space axes by sx and sy respectively. The scaling of the axes takes place after any existing transformation of user space.

cr : | a cairo context
sx : | scale factor for the X dimension
sy : | scale factor for the Y dimension

cairo_rotate ()

void        cairo_rotate                    (cairo_t *cr,
                                             double angle);

Modifies the current transformation matrix (CTM) by rotating the user-space axes by angle radians. The rotation of the axes takes places after any existing transformation of user space. The rotation direction for positive angles is from the positive X axis toward the positive Y axis.

cr : | a cairo context
angle : | angle (in radians) by which the user-space axes will be rotated

cairo_transform ()

void        cairo_transform                 (cairo_t *cr,
                                             const cairo_matrix_t *matrix);

Modifies the current transformation matrix (CTM) by applying matrix as an additional transformation. The new transformation of user space takes place after any existing transformation.

cr : | a cairo context
matrix : | a transformation to be applied to the user-space axes

cairo_set_matrix ()

void        cairo_set_matrix                (cairo_t *cr,
                                             const cairo_matrix_t *matrix);

Modifies the current transformation matrix (CTM) by setting it equal to matrix.

cr : | a cairo context
matrix : | a transformation matrix from user space to device space

cairo_get_matrix ()

void        cairo_get_matrix                (cairo_t *cr,
                                             cairo_matrix_t *matrix);

Stores the current transformation matrix (CTM) into matrix.

cr : | a cairo context
matrix : | return value for the matrix

cairo_identity_matrix ()

void        cairo_identity_matrix           (cairo_t *cr);

Resets the current transformation matrix (CTM) by setting it equal to the identity matrix. That is, the user-space and device-space axes will be aligned and one user-space unit will transform to one device-space unit.

cr : a cairo context

cairo_user_to_device ()

void        cairo_user_to_device            (cairo_t *cr,
                                             double *x,
                                             double *y);

Transform a coordinate from user space to device space by multiplying the given point by the current transformation matrix (CTM).

cr : | a cairo context
x : | X value of coordinate (in/out parameter)
y : | Y value of coordinate (in/out parameter)

cairo_user_to_device_distance ()

void        cairo_user_to_device_distance   (cairo_t *cr,
                                             double *dx,
                                             double *dy);

Transform a distance vector from user space to device space. This function is similar to cairo_user_to_device() except that the translation components of the CTM will be ignored when transforming (dx,dy).

cr : | a cairo context
dx : | X component of a distance vector (in/out parameter)
dy : | Y component of a distance vector (in/out parameter)

cairo_device_to_user ()

void        cairo_device_to_user            (cairo_t *cr,
                                             double *x,
                                             double *y);

Transform a coordinate from device space to user space by multiplying the given point by the inverse of the current transformation matrix (CTM).

cr : | a cairo
x : | X value of coordinate (in/out parameter)
y : | Y value of coordinate (in/out parameter)

cairo_device_to_user_distance ()

void        cairo_device_to_user_distance   (cairo_t *cr,
                                             double *dx,
                                             double *dy);

Transform a distance vector from device space to user space. This function is similar to cairo_device_to_user() except that the translation components of the inverse CTM will be ignored when transforming (dx,dy).

cr : | a cairo context
dx : | X component of a distance vector (in/out parameter)
dy : | Y component of a distance vector (in/out parameter)


Types

Types — Generic data types used in the cairo API

Synopsis

typedef     cairo_bool_t;
            cairo_user_data_key_t;
void        (*cairo_destroy_func_t)         (void *data);

Description

Details

cairo_bool_t

typedef int cairo_bool_t;

cairo_bool_t is used for boolean values. Returns of type cairo_bool_t will always be either 0 or 1, but testing against these values explicitly is not encouraged; just use the value as a boolean condition.

 if (cairo_in_stroke (cr, x, y)) {
     /* do something */
 }

cairo_user_data_key_t

typedef struct {
    int unused;
} cairo_user_data_key_t;

cairo_user_data_key_t is used for attaching user data to cairo data structures. The actual contents of the struct is never used, and there is no need to initialize the object; only the unique address of a cairo_data_key_t object is used. Typically, you would just use the address of a static cairo_data_key_t object.

int unused; not used; ignore.

cairo_destroy_func_t ()

void        (*cairo_destroy_func_t)         (void *data);

cairo_destroy_func_t the type of function which is called when a data element is destroyed. It is passed the pointer to the data element and should free any memory and resources allocated for it.

data : The data element being destroyed.


Version Information

Version Information — Compile-time and run-time version checks.

Synopsis

#define     CAIRO_VERSION
#define     CAIRO_VERSION_MAJOR
#define     CAIRO_VERSION_MINOR
#define     CAIRO_VERSION_MICRO
#define     CAIRO_VERSION_STRING
#define     CAIRO_VERSION_ENCODE            (major, minor, micro)
int         cairo_version                   (void);
const char* cairo_version_string            (void);

Description

Cairo has a three-part version number scheme. In this scheme, we use even vs. odd numbers to distinguish fixed points in the software vs. in-progress development, (such as from CVS instead of a tar file, or as a "snapshot" tar file as opposed to a "release" tar file).

 _____ Major. Always 1, until we invent a new scheme.
/  ___ Minor. Even/Odd = Release/Snapshot (tar files) or Branch/Head (CVS)
| /  _ Micro. Even/Odd = Tar-file/CVS
| | /
1.0.0

Here are a few examples of versions that one might see.

Releases
--------
1.0.0 - A major release
1.0.2 - A subsequent maintenance release
1.2.0 - Another major release

Snapshots
---------
1.1.2 - A snapshot (working toward the 1.2.0 release)

In-progress development (eg. from CVS)
--------------------------------------
1.0.1 - Development on a maintenance branch (toward 1.0.2 release)
1.1.1 - Development on head (toward 1.1.2 snapshot and 1.2.0 release)

Compatibility

The API/ABI compatibility guarantees for various versions are as follows. First, let's assume some cairo-using application code that is successfully using the API/ABI "from" one version of cairo. Then let's ask the question whether this same code can be moved "to" the API/ABI of another version of cairo.

Moving from a release to any later version (release, snapshot, development) is always guaranteed to provide compatibility.

Moving from a snapshot to any later version is not guaranteed to provide compatibility, since snapshots may introduce new API that ends up being removed before the next release.

Moving from an in-development version (odd micro component) to any later version is not guaranteed to provide compatibility. In fact, there's not even a guarantee that the code will even continue to work with the same in-development version number. This is because these numbers don't correspond to any fixed state of the software, but rather the many states between snapshots and releases.

Examining the version

Cairo provides the ability to examine the version at either compile-time or run-time and in both a human-readable form as well as an encoded form suitable for direct comparison. Cairo also provides a macro (CAIRO_VERSION_ENCODE) to perform the encoding.

Compile-time
------------
CAIRO_VERSION_STRING	Human-readable
CAIRO_VERSION		Encoded, suitable for comparison

Run-time
--------
cairo_version_string()	Human-readable
cairo_version()		Encoded, suitable for comparison

For example, checking that the cairo version is greater than or equal to 1.0.0 could be achieved at compile-time or run-time as follows:

#if CAIRO_VERSION >= CAIRO_VERSION_ENCODE(1, 0, 0)
printf ("Compiling with suitable cairo version: %s\n", CAIRO_VERSION_STRING);
#endif

if (cairo_version() >= CAIRO_VERSION_ENCODE(1, 0, 0))
    printf ("Running with suitable cairo version: %s\n", cairo_version_string());

Details

CAIRO_VERSION

#define     CAIRO_VERSION

CAIRO_VERSION_MAJOR

#define CAIRO_VERSION_MAJOR 1

CAIRO_VERSION_MINOR

#define CAIRO_VERSION_MINOR 2

CAIRO_VERSION_MICRO

#define CAIRO_VERSION_MICRO 6

CAIRO_VERSION_STRING

#define CAIRO_VERSION_STRING "1.2.6"

CAIRO_VERSION_ENCODE()

#define     CAIRO_VERSION_ENCODE(major, minor, micro)

major :
minor :
micro :

cairo_version ()

int         cairo_version                   (void);

Returns the version of the cairo library encoded in a single integer as per CAIRO_VERSION_ENCODE. The encoding ensures that later versions compare greater than earlier versions.

A run-time comparison to check that cairo's version is greater than or equal to version X.Y.Z could be performed as follows:

if (cairo_version() >= CAIRO_VERSION_ENCODE(X,Y,Z)) {...}

See also cairo_version_string() as well as the compile-time equivalents CAIRO_VERSION and CAIRO_VERSION_STRING.

Returns : the encoded version.

cairo_version_string ()

const char* cairo_version_string            (void);

Returns the version of the cairo library as a human-readable string of the form "X.Y.Z".

See also cairo_version() as well as the compile-time equivalents CAIRO_VERSION_STRING and CAIRO_VERSION.

Returns : a string containing the version.


Win32 Fonts

Win32 Fonts — Font support for Microsoft Windows

Synopsis

cairo_font_face_t* cairo_win32_font_face_create_for_logfontw
                                            (LOGFONTW *logfont);
cairo_font_face_t* cairo_win32_font_face_create_for_hfont
                                            (HFONT font);
cairo_status_t cairo_win32_scaled_font_select_font
                                            (cairo_scaled_font_t *scaled_font,
                                             HDC hdc);
void        cairo_win32_scaled_font_done_font
                                            (cairo_scaled_font_t *scaled_font);
double      cairo_win32_scaled_font_get_metrics_factor
                                            (cairo_scaled_font_t *scaled_font);

Description

Details

cairo_win32_font_face_create_for_logfontw ()

cairo_font_face_t* cairo_win32_font_face_create_for_logfontw
                                            (LOGFONTW *logfont);

Creates a new font for the Win32 font backend based on a LOGFONT. This font can then be used with cairo_set_font_face() or cairo_scaled_font_create(). The cairo_scaled_font_t returned from cairo_scaled_font_create() is also for the Win32 backend and can be used with functions such as cairo_win32_scaled_font_select_font().

logfont : | A LOGFONTW structure specifying the font to use. The lfHeight, lfWidth, lfOrientation and lfEscapement fields of this structure are ignored.
Returns : | a newly created cairo_font_face_t. Free with cairo_font_face_destroy() when you are done using it.

cairo_win32_font_face_create_for_hfont ()

cairo_font_face_t* cairo_win32_font_face_create_for_hfont
                                            (HFONT font);

Creates a new font for the Win32 font backend based on a HFONT. This font can then be used with cairo_set_font_face() or cairo_scaled_font_create(). The cairo_scaled_font_t returned from cairo_scaled_font_create() is also for the Win32 backend and can be used with functions such as cairo_win32_scaled_font_select_font().

font : | An HFONT structure specifying the font to use.
Returns : | a newly created cairo_font_face_t. Free with cairo_font_face_destroy() when you are done using it.

cairo_win32_scaled_font_select_font ()

cairo_status_t cairo_win32_scaled_font_select_font
                                            (cairo_scaled_font_t *scaled_font,
                                             HDC hdc);

Selects the font into the given device context and changes the map mode and world transformation of the device context to match that of the font. This function is intended for use when using layout APIs such as Uniscribe to do text layout with the cairo font. After finishing using the device context, you must call cairo_win32_scaled_font_done_font() to release any resources allocated by this function.

See cairo_win32_scaled_font_get_metrics_factor() for converting logical coordinates from the device context to font space.

Normally, calls to SaveDC() and RestoreDC() would be made around the use of this function to preserve the original graphics state.

scaled_font : | A cairo_scaled_font_t from the Win32 font backend. Such an object can be created with cairo_win32_scaled_font_create_for_logfontw().
hdc : | a device context
Returns : | CAIRO_STATUS_SUCCESS if the operation succeeded. otherwise an error such as CAIRO_STATUS_NO_MEMORY and the device context is unchanged.

cairo_win32_scaled_font_done_font ()

void        cairo_win32_scaled_font_done_font
                                            (cairo_scaled_font_t *scaled_font);

Releases any resources allocated by cairo_win32_scaled_font_select_font()

scaled_font : A cairo_scaled_font_t from the Win32 font backend.

cairo_win32_scaled_font_get_metrics_factor ()

double      cairo_win32_scaled_font_get_metrics_factor
                                            (cairo_scaled_font_t *scaled_font);

Gets a scale factor between logical coordinates in the coordinate space used by cairo_win32_scaled_font_select_font() (that is, the coordinate system used by the Windows functions to return metrics) and font space coordinates.

scaled_font : | a cairo_scaled_font_t from the Win32 font backend
Returns : | factor to multiply logical units by to get font space coordinates.


Win32 Surfaces

Win32 Surfaces — Microsoft Windows surface support

Synopsis

cairo_surface_t* cairo_win32_surface_create (HDC hdc);
cairo_surface_t* cairo_win32_surface_create_with_dib
                                            (cairo_format_t format,
                                             int width,
                                             int height);
HDC         cairo_win32_surface_get_dc      (cairo_surface_t *surface);

Description

Details

cairo_win32_surface_create ()

cairo_surface_t* cairo_win32_surface_create (HDC hdc);

Creates a cairo surface that targets the given DC. The DC will be queried for its initial clip extents, and this will be used as the size of the cairo surface. Also, if the DC is a raster DC, it will be queried for its pixel format and the cairo surface format will be set appropriately.

hdc : | the DC to create a surface for
Returns : | the newly created surface

cairo_win32_surface_create_with_dib ()

cairo_surface_t* cairo_win32_surface_create_with_dib
                                            (cairo_format_t format,
                                             int width,
                                             int height);

Creates a device-independent-bitmap surface not associated with any particular existing surface or device context. The created bitmap will be unititialized.

format : | format of pixels in the surface to create
width : | width of the surface, in pixels
height : | height of the surface, in pixels
Returns : | the newly created surface

Since 1.2

cairo_win32_surface_get_dc ()

HDC         cairo_win32_surface_get_dc      (cairo_surface_t *surface);

Returns the HDC associated with this surface, or NULL if none. Also returns NULL if the surface is not a win32 surface.

surface : | a cairo_surface_t
Returns : | HDC or NULL if no HDC available.

Since 1.2


XLib Surfaces

XLib Surfaces — X Window System rendering using XLib

Synopsis

cairo_surface_t* cairo_xlib_surface_create  (Display *dpy,
                                             Drawable drawable,
                                             Visual *visual,
                                             int width,
                                             int height);
cairo_surface_t* cairo_xlib_surface_create_for_bitmap
                                            (Display *dpy,
                                             Pixmap bitmap,
                                             Screen *screen,
                                             int width,
                                             int height);
void        cairo_xlib_surface_set_size     (cairo_surface_t *surface,
                                             int width,
                                             int height);
Display*    cairo_xlib_surface_get_display  (cairo_surface_t *surface);
Screen*     cairo_xlib_surface_get_screen   (cairo_surface_t *surface);
void        cairo_xlib_surface_set_drawable (cairo_surface_t *surface,
                                             Drawable drawable,
                                             int width,
                                             int height);
Drawable    cairo_xlib_surface_get_drawable (cairo_surface_t *surface);
Visual*     cairo_xlib_surface_get_visual   (cairo_surface_t *surface);
int         cairo_xlib_surface_get_width    (cairo_surface_t *surface);
int         cairo_xlib_surface_get_height   (cairo_surface_t *surface);
int         cairo_xlib_surface_get_depth    (cairo_surface_t *surface);

Description

Details

cairo_xlib_surface_create ()

cairo_surface_t* cairo_xlib_surface_create  (Display *dpy,
                                             Drawable drawable,
                                             Visual *visual,
                                             int width,
                                             int height);

Creates an Xlib surface that draws to the given drawable. The way that colors are represented in the drawable is specified by the provided visual.

NOTE: If drawable is a Window, then the function cairo_xlib_surface_set_size must be called whenever the size of the window changes.

dpy : | an X Display
drawable : | an X Drawable, (a Pixmap or a Window)
visual : | the visual to use for drawing to drawable. The depth of the visual must match the depth of the drawable. Currently, only TrueColor visuals are fully supported.
width : | the current width of drawable.
height : | the current height of drawable.
Returns : | the newly created surface

cairo_xlib_surface_create_for_bitmap ()

cairo_surface_t* cairo_xlib_surface_create_for_bitmap
                                            (Display *dpy,
                                             Pixmap bitmap,
                                             Screen *screen,
                                             int width,
                                             int height);

Creates an Xlib surface that draws to the given bitmap. This will be drawn to as a CAIRO_FORMAT_A1 object.

dpy : | an X Display
bitmap : | an X Drawable, (a depth-1 Pixmap)
screen : | the X Screen associated with bitmap
width : | the current width of bitmap.
height : | the current height of bitmap.
Returns : | the newly created surface

cairo_xlib_surface_set_size ()

void        cairo_xlib_surface_set_size     (cairo_surface_t *surface,
                                             int width,
                                             int height);

Informs cairo of the new size of the X Drawable underlying the surface. For a surface created for a Window (rather than a Pixmap), this function must be called each time the size of the window changes. (For a subwindow, you are normally resizing the window yourself, but for a toplevel window, it is necessary to listen for ConfigureNotify events.)

A Pixmap can never change size, so it is never necessary to call this function on a surface created for a Pixmap.

surface : | a cairo_surface_t for the XLib backend
width : | the new width of the surface
height : | the new height of the surface

cairo_xlib_surface_get_display ()

Display*    cairo_xlib_surface_get_display  (cairo_surface_t *surface);

Get the X Display for the underlying X Drawable.

surface : | a cairo_xlib_surface_t
Returns : | the display.

Since 1.2

cairo_xlib_surface_get_screen ()

Screen*     cairo_xlib_surface_get_screen   (cairo_surface_t *surface);

Get the X Screen for the underlying X Drawable.

surface : | a cairo_xlib_surface_t
Returns : | the screen.

Since 1.2

cairo_xlib_surface_set_drawable ()

void        cairo_xlib_surface_set_drawable (cairo_surface_t *surface,
                                             Drawable drawable,
                                             int width,
                                             int height);

Informs cairo of a new X Drawable underlying the surface. The drawable must match the display, screen and format of the existing drawable or the application will get X protocol errors and will probably terminate. No checks are done by this function to ensure this compatibility.

surface : | a cairo_surface_t for the XLib backend
drawable : | the new drawable for the surface
width : | the width of the new drawable
height : | the height of the new drawable

cairo_xlib_surface_get_drawable ()

Drawable    cairo_xlib_surface_get_drawable (cairo_surface_t *surface);

Get the underlying X Drawable used for the surface.

surface : | a cairo_xlib_surface_t
Returns : | the drawable.

Since 1.2

cairo_xlib_surface_get_visual ()

Visual*     cairo_xlib_surface_get_visual   (cairo_surface_t *surface);

Get the X Visual used for underlying X Drawable.

surface : | a cairo_xlib_surface_t
Returns : | the visual.

Since 1.2

cairo_xlib_surface_get_width ()

int         cairo_xlib_surface_get_width    (cairo_surface_t *surface);

Get the width of the X Drawable underlying the surface in pixels.

surface : | a cairo_xlib_surface_t
Returns : | the width of the surface in pixels.

Since 1.2

cairo_xlib_surface_get_height ()

int         cairo_xlib_surface_get_height   (cairo_surface_t *surface);

Get the height of the X Drawable underlying the surface in pixels.

surface : | a cairo_xlib_surface_t
Returns : | the height of the surface in pixels.

Since 1.2

cairo_xlib_surface_get_depth ()

int         cairo_xlib_surface_get_depth    (cairo_surface_t *surface);

Get the number of bits used to represent each pixel value.

surface : | a cairo_xlib_surface_t
Returns : | the depth of the surface in bits.

Since 1.2


Drawing

cairo_t - The cairo drawing context
Paths - Creating paths and manipulating path data
Patterns - Gradients and filtered sources
Transformations - Manipulating the current transformation matrix
Text - Rendering text and sets of glyphs


Fonts

cairo_font_face_t - Base class for fonts
Scaled Fonts - Caching metrics for a particular font size
Font Options - How a font should be rendered
FreeType Fonts - Font support for FreeType
Win32 Fonts - Font support for Microsoft Windows


Index

, Description

C

cairo_antialias_t, enum cairo_antialias_t
cairo_append_path, cairo_append_path ()
cairo_arc, cairo_arc ()
cairo_arc_negative, cairo_arc_negative ()
cairo_bool_t, cairo_bool_t
cairo_clip, cairo_clip ()
cairo_clip_preserve, cairo_clip_preserve ()
cairo_close_path, cairo_close_path ()
cairo_content_t, enum cairo_content_t
cairo_copy_page, cairo_copy_page ()
cairo_copy_path, cairo_copy_path ()
cairo_copy_path_flat, cairo_copy_path_flat ()
cairo_create, cairo_create ()
cairo_curve_to, cairo_curve_to ()
cairo_debug_reset_static_data, cairo_debug_reset_static_data ()
cairo_destroy, cairo_destroy ()
cairo_destroy_func_t, cairo_destroy_func_t ()
cairo_device_to_user, cairo_device_to_user ()
cairo_device_to_user_distance, cairo_device_to_user_distance ()
cairo_extend_t, enum cairo_extend_t
cairo_fill, cairo_fill ()
cairo_fill_extents, cairo_fill_extents ()
cairo_fill_preserve, cairo_fill_preserve ()
cairo_fill_rule_t, enum cairo_fill_rule_t
cairo_filter_t, enum cairo_filter_t
cairo_font_extents, cairo_font_extents ()
cairo_font_extents_t, cairo_font_extents_t
cairo_font_face_destroy, cairo_font_face_destroy ()
cairo_font_face_get_type, cairo_font_face_get_type ()
cairo_font_face_get_user_data, cairo_font_face_get_user_data ()
cairo_font_face_reference, cairo_font_face_reference ()
cairo_font_face_set_user_data, cairo_font_face_set_user_data ()
cairo_font_face_status, cairo_font_face_status ()
cairo_font_face_t, cairo_font_face_t
cairo_font_options_copy, cairo_font_options_copy ()
cairo_font_options_create, cairo_font_options_create ()
cairo_font_options_destroy, cairo_font_options_destroy ()
cairo_font_options_equal, cairo_font_options_equal ()
cairo_font_options_get_antialias, cairo_font_options_get_antialias ()
cairo_font_options_get_hint_metrics, cairo_font_options_get_hint_metrics ()
cairo_font_options_get_hint_style, cairo_font_options_get_hint_style ()
cairo_font_options_get_subpixel_order, cairo_font_options_get_subpixel_order ()
cairo_font_options_hash, cairo_font_options_hash ()
cairo_font_options_merge, cairo_font_options_merge ()
cairo_font_options_set_antialias, cairo_font_options_set_antialias ()
cairo_font_options_set_hint_metrics, cairo_font_options_set_hint_metrics ()
cairo_font_options_set_hint_style, cairo_font_options_set_hint_style ()
cairo_font_options_set_subpixel_order, cairo_font_options_set_subpixel_order ()
cairo_font_options_status, cairo_font_options_status ()
cairo_font_options_t, cairo_font_options_t
cairo_font_slant_t, enum cairo_font_slant_t
cairo_font_type_t, enum cairo_font_type_t
cairo_font_weight_t, enum cairo_font_weight_t
cairo_format_t, enum cairo_format_t
cairo_ft_font_face_create_for_ft_face, cairo_ft_font_face_create_for_ft_face ()
cairo_ft_font_face_create_for_pattern, cairo_ft_font_face_create_for_pattern ()
cairo_ft_font_options_substitute, cairo_ft_font_options_substitute ()
cairo_ft_scaled_font_lock_face, cairo_ft_scaled_font_lock_face ()
cairo_ft_scaled_font_unlock_face, cairo_ft_scaled_font_unlock_face ()
cairo_get_antialias, cairo_get_antialias ()
cairo_get_current_point, cairo_get_current_point ()
cairo_get_fill_rule, cairo_get_fill_rule ()
cairo_get_font_face, cairo_get_font_face ()
cairo_get_font_matrix, cairo_get_font_matrix ()
cairo_get_font_options, cairo_get_font_options ()
cairo_get_group_target, cairo_get_group_target ()
cairo_get_line_cap, cairo_get_line_cap ()
cairo_get_line_join, cairo_get_line_join ()
cairo_get_line_width, cairo_get_line_width ()
cairo_get_matrix, cairo_get_matrix ()
cairo_get_miter_limit, cairo_get_miter_limit ()
cairo_get_operator, cairo_get_operator ()
cairo_get_source, cairo_get_source ()
cairo_get_target, cairo_get_target ()
cairo_get_tolerance, cairo_get_tolerance ()
cairo_glyph_extents, cairo_glyph_extents ()
cairo_glyph_path, cairo_glyph_path ()
cairo_glyph_t, cairo_glyph_t
cairo_hint_metrics_t, enum cairo_hint_metrics_t
cairo_hint_style_t, enum cairo_hint_style_t
cairo_identity_matrix, cairo_identity_matrix ()
cairo_image_surface_create, cairo_image_surface_create ()
cairo_image_surface_create_for_data, cairo_image_surface_create_for_data ()
cairo_image_surface_create_from_png, cairo_image_surface_create_from_png ()
cairo_image_surface_create_from_png_stream, cairo_image_surface_create_from_png_stream ()
cairo_image_surface_get_data, cairo_image_surface_get_data ()
cairo_image_surface_get_format, cairo_image_surface_get_format ()
cairo_image_surface_get_height, cairo_image_surface_get_height ()
cairo_image_surface_get_stride, cairo_image_surface_get_stride ()
cairo_image_surface_get_width, cairo_image_surface_get_width ()
cairo_in_fill, cairo_in_fill ()
cairo_in_stroke, cairo_in_stroke ()
cairo_line_cap_t, enum cairo_line_cap_t
cairo_line_join_t, enum cairo_line_join_t
cairo_line_to, cairo_line_to ()
cairo_mask, cairo_mask ()
cairo_mask_surface, cairo_mask_surface ()
cairo_matrix_init, cairo_matrix_init ()
cairo_matrix_init_identity, cairo_matrix_init_identity ()
cairo_matrix_init_rotate, cairo_matrix_init_rotate ()
cairo_matrix_init_scale, cairo_matrix_init_scale ()
cairo_matrix_init_translate, cairo_matrix_init_translate ()
cairo_matrix_invert, cairo_matrix_invert ()
cairo_matrix_multiply, cairo_matrix_multiply ()
cairo_matrix_rotate, cairo_matrix_rotate ()
cairo_matrix_scale, cairo_matrix_scale ()
cairo_matrix_t, cairo_matrix_t
cairo_matrix_transform_distance, cairo_matrix_transform_distance ()
cairo_matrix_transform_point, cairo_matrix_transform_point ()
cairo_matrix_translate, cairo_matrix_translate ()
cairo_move_to, cairo_move_to ()
cairo_new_path, cairo_new_path ()
cairo_new_sub_path, cairo_new_sub_path ()
cairo_operator_t, enum cairo_operator_t
cairo_paint, cairo_paint ()
cairo_paint_with_alpha, cairo_paint_with_alpha ()
cairo_path_data_t, union cairo_path_data_t
cairo_path_data_type_t, enum cairo_path_data_type_t
cairo_path_destroy, cairo_path_destroy ()
cairo_path_t, cairo_path_t
cairo_pattern_add_color_stop_rgb, cairo_pattern_add_color_stop_rgb ()
cairo_pattern_add_color_stop_rgba, cairo_pattern_add_color_stop_rgba ()
cairo_pattern_create_for_surface, cairo_pattern_create_for_surface ()
cairo_pattern_create_linear, cairo_pattern_create_linear ()
cairo_pattern_create_radial, cairo_pattern_create_radial ()
cairo_pattern_create_rgb, cairo_pattern_create_rgb ()
cairo_pattern_create_rgba, cairo_pattern_create_rgba ()
cairo_pattern_destroy, cairo_pattern_destroy ()
cairo_pattern_get_extend, cairo_pattern_get_extend ()
cairo_pattern_get_filter, cairo_pattern_get_filter ()
cairo_pattern_get_matrix, cairo_pattern_get_matrix ()
cairo_pattern_get_type, cairo_pattern_get_type ()
cairo_pattern_reference, cairo_pattern_reference ()
cairo_pattern_set_extend, cairo_pattern_set_extend ()
cairo_pattern_set_filter, cairo_pattern_set_filter ()
cairo_pattern_set_matrix, cairo_pattern_set_matrix ()
cairo_pattern_status, cairo_pattern_status ()
cairo_pattern_t, cairo_pattern_t
cairo_pattern_type_t, enum cairo_pattern_type_t
cairo_pdf_surface_create, cairo_pdf_surface_create ()
cairo_pdf_surface_create_for_stream, cairo_pdf_surface_create_for_stream ()
cairo_pdf_surface_set_size, cairo_pdf_surface_set_size ()
cairo_pop_group, cairo_pop_group ()
cairo_pop_group_to_source, cairo_pop_group_to_source ()
cairo_ps_surface_create, cairo_ps_surface_create ()
cairo_ps_surface_create_for_stream, cairo_ps_surface_create_for_stream ()
cairo_ps_surface_dsc_begin_page_setup, cairo_ps_surface_dsc_begin_page_setup ()
cairo_ps_surface_dsc_begin_setup, cairo_ps_surface_dsc_begin_setup ()
cairo_ps_surface_dsc_comment, cairo_ps_surface_dsc_comment ()
cairo_ps_surface_set_size, cairo_ps_surface_set_size ()
cairo_push_group, cairo_push_group ()
cairo_push_group_with_content, cairo_push_group_with_content ()
cairo_read_func_t, cairo_read_func_t ()
cairo_rectangle, cairo_rectangle ()
cairo_reference, cairo_reference ()
cairo_rel_curve_to, cairo_rel_curve_to ()
cairo_rel_line_to, cairo_rel_line_to ()
cairo_rel_move_to, cairo_rel_move_to ()
cairo_reset_clip, cairo_reset_clip ()
cairo_restore, cairo_restore ()
cairo_rotate, cairo_rotate ()
cairo_save, cairo_save ()
cairo_scale, cairo_scale ()
cairo_scaled_font_create, cairo_scaled_font_create ()
cairo_scaled_font_destroy, cairo_scaled_font_destroy ()
cairo_scaled_font_extents, cairo_scaled_font_extents ()
cairo_scaled_font_get_ctm, cairo_scaled_font_get_ctm ()
cairo_scaled_font_get_font_face, cairo_scaled_font_get_font_face ()
cairo_scaled_font_get_font_matrix, cairo_scaled_font_get_font_matrix ()
cairo_scaled_font_get_font_options, cairo_scaled_font_get_font_options ()
cairo_scaled_font_get_type, cairo_scaled_font_get_type ()
cairo_scaled_font_glyph_extents, cairo_scaled_font_glyph_extents ()
cairo_scaled_font_reference, cairo_scaled_font_reference ()
cairo_scaled_font_status, cairo_scaled_font_status ()
cairo_scaled_font_t, cairo_scaled_font_t
cairo_scaled_font_text_extents, cairo_scaled_font_text_extents ()
cairo_select_font_face, cairo_select_font_face ()
cairo_set_antialias, cairo_set_antialias ()
cairo_set_dash, cairo_set_dash ()
cairo_set_fill_rule, cairo_set_fill_rule ()
cairo_set_font_face, cairo_set_font_face ()
cairo_set_font_matrix, cairo_set_font_matrix ()
cairo_set_font_options, cairo_set_font_options ()
cairo_set_font_size, cairo_set_font_size ()
cairo_set_line_cap, cairo_set_line_cap ()
cairo_set_line_join, cairo_set_line_join ()
cairo_set_line_width, cairo_set_line_width ()
cairo_set_matrix, cairo_set_matrix ()
cairo_set_miter_limit, cairo_set_miter_limit ()
cairo_set_operator, cairo_set_operator ()
cairo_set_scaled_font, cairo_set_scaled_font ()
cairo_set_source, cairo_set_source ()
cairo_set_source_rgb, cairo_set_source_rgb ()
cairo_set_source_rgba, cairo_set_source_rgba ()
cairo_set_source_surface, cairo_set_source_surface ()
cairo_set_tolerance, cairo_set_tolerance ()
cairo_show_glyphs, cairo_show_glyphs ()
cairo_show_page, cairo_show_page ()
cairo_show_text, cairo_show_text ()
cairo_status, cairo_status ()
cairo_status_t, enum cairo_status_t
cairo_status_to_string, cairo_status_to_string ()
cairo_stroke, cairo_stroke ()
cairo_stroke_extents, cairo_stroke_extents ()
cairo_stroke_preserve, cairo_stroke_preserve ()
cairo_subpixel_order_t, enum cairo_subpixel_order_t
cairo_surface_create_similar, cairo_surface_create_similar ()
cairo_surface_destroy, cairo_surface_destroy ()
cairo_surface_finish, cairo_surface_finish ()
cairo_surface_flush, cairo_surface_flush ()
cairo_surface_get_content, cairo_surface_get_content ()
cairo_surface_get_device_offset, cairo_surface_get_device_offset ()
cairo_surface_get_font_options, cairo_surface_get_font_options ()
cairo_surface_get_type, cairo_surface_get_type ()
cairo_surface_get_user_data, cairo_surface_get_user_data ()
cairo_surface_mark_dirty, cairo_surface_mark_dirty ()
cairo_surface_mark_dirty_rectangle, cairo_surface_mark_dirty_rectangle ()
cairo_surface_reference, cairo_surface_reference ()
cairo_surface_set_device_offset, cairo_surface_set_device_offset ()
cairo_surface_set_fallback_resolution, cairo_surface_set_fallback_resolution ()
cairo_surface_set_user_data, cairo_surface_set_user_data ()
cairo_surface_status, cairo_surface_status ()
cairo_surface_t, cairo_surface_t
cairo_surface_type_t, enum cairo_surface_type_t
cairo_surface_write_to_png, cairo_surface_write_to_png ()
cairo_surface_write_to_png_stream, cairo_surface_write_to_png_stream ()
cairo_svg_get_versions, cairo_svg_get_versions ()
cairo_svg_surface_create, cairo_svg_surface_create ()
cairo_svg_surface_create_for_stream, cairo_svg_surface_create_for_stream ()
cairo_svg_surface_restrict_to_version, cairo_svg_surface_restrict_to_version ()
cairo_svg_version_t, enum cairo_svg_version_t
cairo_svg_version_to_string, cairo_svg_version_to_string ()
cairo_t, cairo_t
cairo_text_extents, cairo_text_extents ()
cairo_text_extents_t, cairo_text_extents_t
cairo_text_path, cairo_text_path ()
cairo_transform, cairo_transform ()
cairo_translate, cairo_translate ()
cairo_user_data_key_t, cairo_user_data_key_t
cairo_user_to_device, cairo_user_to_device ()
cairo_user_to_device_distance, cairo_user_to_device_distance ()
CAIRO_VERSION, CAIRO_VERSION
cairo_version, cairo_version ()
CAIRO_VERSION_ENCODE, CAIRO_VERSION_ENCODE()
CAIRO_VERSION_MAJOR, CAIRO_VERSION_MAJOR
CAIRO_VERSION_MICRO, CAIRO_VERSION_MICRO
CAIRO_VERSION_MINOR, CAIRO_VERSION_MINOR
CAIRO_VERSION_STRING, CAIRO_VERSION_STRING
cairo_version_string, cairo_version_string ()
cairo_win32_font_face_create_for_hfont, cairo_win32_font_face_create_for_hfont ()
cairo_win32_font_face_create_for_logfontw, cairo_win32_font_face_create_for_logfontw ()
cairo_win32_scaled_font_done_font, cairo_win32_scaled_font_done_font ()
cairo_win32_scaled_font_get_metrics_factor, cairo_win32_scaled_font_get_metrics_factor ()
cairo_win32_scaled_font_select_font, cairo_win32_scaled_font_select_font ()
cairo_win32_surface_create, cairo_win32_surface_create ()
cairo_win32_surface_create_with_dib, cairo_win32_surface_create_with_dib ()
cairo_win32_surface_get_dc, cairo_win32_surface_get_dc ()
cairo_write_func_t, cairo_write_func_t ()
cairo_xlib_surface_create, cairo_xlib_surface_create ()
cairo_xlib_surface_create_for_bitmap, cairo_xlib_surface_create_for_bitmap ()
cairo_xlib_surface_get_depth, cairo_xlib_surface_get_depth ()
cairo_xlib_surface_get_display, cairo_xlib_surface_get_display ()
cairo_xlib_surface_get_drawable, cairo_xlib_surface_get_drawable ()
cairo_xlib_surface_get_height, cairo_xlib_surface_get_height ()
cairo_xlib_surface_get_screen, cairo_xlib_surface_get_screen ()
cairo_xlib_surface_get_visual, cairo_xlib_surface_get_visual ()
cairo_xlib_surface_get_width, cairo_xlib_surface_get_width ()
cairo_xlib_surface_set_drawable, cairo_xlib_surface_set_drawable ()
cairo_xlib_surface_set_size, cairo_xlib_surface_set_size ()

T

types
cairo_matrix, Description


Index of new symbols in 1.2

C

cairo_font_face_get_type, cairo_font_face_get_type ()
cairo_font_type_t, enum cairo_font_type_t
cairo_get_group_target, cairo_get_group_target ()
cairo_image_surface_get_data, cairo_image_surface_get_data ()
cairo_image_surface_get_format, cairo_image_surface_get_format ()
cairo_image_surface_get_stride, cairo_image_surface_get_stride ()
cairo_new_sub_path, cairo_new_sub_path ()
cairo_pattern_get_type, cairo_pattern_get_type ()
cairo_pattern_type_t, enum cairo_pattern_type_t
cairo_pdf_surface_create, cairo_pdf_surface_create ()
cairo_pdf_surface_create_for_stream, cairo_pdf_surface_create_for_stream ()
cairo_pdf_surface_set_size, cairo_pdf_surface_set_size ()
cairo_pop_group, cairo_pop_group ()
cairo_pop_group_to_source, cairo_pop_group_to_source ()
cairo_ps_surface_create, cairo_ps_surface_create ()
cairo_ps_surface_create_for_stream, cairo_ps_surface_create_for_stream ()
cairo_ps_surface_dsc_begin_page_setup, cairo_ps_surface_dsc_begin_page_setup ()
cairo_ps_surface_dsc_begin_setup, cairo_ps_surface_dsc_begin_setup ()
cairo_ps_surface_dsc_comment, cairo_ps_surface_dsc_comment ()
cairo_ps_surface_set_size, cairo_ps_surface_set_size ()
cairo_push_group, cairo_push_group ()
cairo_push_group_with_content, cairo_push_group_with_content ()
cairo_scaled_font_get_ctm, cairo_scaled_font_get_ctm ()
cairo_scaled_font_get_font_face, cairo_scaled_font_get_font_face ()
cairo_scaled_font_get_font_matrix, cairo_scaled_font_get_font_matrix ()
cairo_scaled_font_get_font_options, cairo_scaled_font_get_font_options ()
cairo_scaled_font_get_type, cairo_scaled_font_get_type ()
cairo_scaled_font_text_extents, cairo_scaled_font_text_extents ()
cairo_set_scaled_font, cairo_set_scaled_font ()
cairo_surface_get_content, cairo_surface_get_content ()
cairo_surface_get_device_offset, cairo_surface_get_device_offset ()
cairo_surface_get_type, cairo_surface_get_type ()
cairo_surface_set_fallback_resolution, cairo_surface_set_fallback_resolution ()
cairo_surface_type_t, enum cairo_surface_type_t
cairo_svg_get_versions, cairo_svg_get_versions ()
cairo_svg_surface_create, cairo_svg_surface_create ()
cairo_svg_surface_create_for_stream, cairo_svg_surface_create_for_stream ()
cairo_svg_surface_restrict_to_version, cairo_svg_surface_restrict_to_version ()
cairo_svg_version_to_string, cairo_svg_version_to_string ()
cairo_win32_surface_create_with_dib, cairo_win32_surface_create_with_dib ()
cairo_win32_surface_get_dc, cairo_win32_surface_get_dc ()
cairo_xlib_surface_get_depth, cairo_xlib_surface_get_depth ()
cairo_xlib_surface_get_display, cairo_xlib_surface_get_display ()
cairo_xlib_surface_get_drawable, cairo_xlib_surface_get_drawable ()
cairo_xlib_surface_get_height, cairo_xlib_surface_get_height ()
cairo_xlib_surface_get_screen, cairo_xlib_surface_get_screen ()
cairo_xlib_surface_get_visual, cairo_xlib_surface_get_visual ()
cairo_xlib_surface_get_width, cairo_xlib_surface_get_width ()


Appendix A. Creating a language binding for cairo

While cairo is implemented and C, and has a C API, it is expected that many users of cairo will be using it from languages other than C. The glue that connects the core cairo library to another language is known as a language binding. This appendix attempts to collect together issues that come up when creating a language bindings for cairo and present standardized solutions to promote consistency among the different language bindings.

General considerations

The naming of the central cairo_t type is a special exception. The object is “a cairo context” not “a cairo”, and names such as cairo_t rather than cairo_context_t and cairo_set_source() rather than cairo_context_set_source() are simply abbreviations to make the C API more palatable. In languages which have object-oriented syntax, this abbreviation is much less useful. In fact, if ‘Cairo’ is used as a namespace, then in many languages, you'd end up with a ridiculous type name like ‘Cairo.Cairo’. For this reason, and for inter-language consistency all object-oriented languages should name this type as if it were cairo_context_t.

The punctuation and casing of the type names and method names of cairo should be changed to match the general convention of the language. In Java, where type names are written in StudlyCaps and method names in javaCaps, cairo_font_extents_t will become FontExtents and cairo_set_source(cr,source), cr.setSource(source). As compared to changing the punctuation, and casing, much more reluctance should be used in changing the method names themselves. Even if get is usually omitted from getters in your language, you shouldn't bind cairo_get_source() as cr.source().


Prev Home Cairo: A Vector Graphics Library Next

Part I. Tutorial


Prev Home Cairo: A Vector Graphics Library Next

Part II. Reference


Utilities

cairo_matrix_t - Generic matrix operations
Error handling - Decoding cairo's status
Version Information - Compile-time and run-time version checks.
Types - Generic data types used in the cairo API


Surfaces

cairo_surface_t - Base class for surfaces
Image Surfaces - Rendering to memory buffers
PDF Surfaces - Rendering PDF documents
PNG Support - Reading and writing PNG images
PostScript Surfaces - Rendering PostScript documents
Win32 Surfaces - Microsoft Windows surface support
SVG Surfaces - Rendering SVG documents
XLib Surfaces - X Window System rendering using XLib


Bitmaps and Pixmaps

Bitmaps and Pixmaps — Offscreen drawables

Synopsis

#include <gdk/gdk.h>

struct              GdkPixmap;
GdkPixmap*          gdk_pixmap_new                      (GdkDrawable *drawable,
                                                         gint width,
                                                         gint height,
                                                         gint depth);
GdkBitmap*          gdk_bitmap_create_from_data         (GdkDrawable *drawable,
                                                         const gchar *data,
                                                         gint width,
                                                         gint height);
GdkPixmap*          gdk_pixmap_create_from_data         (GdkDrawable *drawable,
                                                         const gchar *data,
                                                         gint width,
                                                         gint height,
                                                         gint depth,
                                                         const GdkColor *fg,
                                                         const GdkColor *bg);
GdkPixmap*          gdk_pixmap_create_from_xpm          (GdkDrawable *drawable,
                                                         GdkBitmap **mask,
                                                         const GdkColor *transparent_color,
                                                         const gchar *filename);
GdkPixmap*          gdk_pixmap_colormap_create_from_xpm (GdkDrawable *drawable,
                                                         GdkColormap *colormap,
                                                         GdkBitmap **mask,
                                                         const GdkColor *transparent_color,
                                                         const gchar *filename);
GdkPixmap*          gdk_pixmap_create_from_xpm_d        (GdkDrawable *drawable,
                                                         GdkBitmap **mask,
                                                         const GdkColor *transparent_color,
                                                         gchar **data);
GdkPixmap*          gdk_pixmap_colormap_create_from_xpm_d
                                                        (GdkDrawable *drawable,
                                                         GdkColormap *colormap,
                                                         GdkBitmap **mask,
                                                         const GdkColor *transparent_color,
                                                         gchar **data);
#define             gdk_pixmap_ref
#define             gdk_pixmap_unref
struct              GdkBitmap;
#define             gdk_bitmap_ref
#define             gdk_bitmap_unref

Object Hierarchy

  GObject
   +----GdkDrawable
         +----GdkPixmap

Description

Pixmaps are offscreen drawables. They can be drawn upon with the standard drawing primitives, then copied to another drawable (such as a GdkWindow) with gdk_pixmap_draw(). The depth of a pixmap is the number of bits per pixels. Bitmaps are simply pixmaps with a depth of 1. (That is, they are monochrome bitmaps - each pixel can be either on or off).

Details

struct GdkPixmap

struct GdkPixmap;

An opaque structure representing an offscreen drawable. Pointers to structures of type GdkPixmap, GdkBitmap, and GdkWindow, can often be used interchangeably. The type GdkDrawable refers generically to any of these types.

gdk_pixmap_new ()

GdkPixmap*          gdk_pixmap_new                      (GdkDrawable *drawable,
                                                         gint width,
                                                         gint height,
                                                         gint depth);

Create a new pixmap with a given size and depth.

drawable : | A GdkDrawable, used to determine default values for the new pixmap. Can be NULL if depth is specified,
width : | The width of the new pixmap in pixels.
height : | The height of the new pixmap in pixels.
depth : | The depth (number of bits per pixel) of the new pixmap. If -1, and drawable is not NULL, the depth of the new pixmap will be equal to that of drawable.
Returns : | the GdkPixmap

gdk_bitmap_create_from_data ()

GdkBitmap*          gdk_bitmap_create_from_data         (GdkDrawable *drawable,
                                                         const gchar *data,
                                                         gint width,
                                                         gint height);

Creates a new bitmap from data in XBM format.

drawable : | a GdkDrawable, used to determine default values for the new pixmap. Can be NULL, in which case the root window is used.
data : | a pointer to the XBM data.
width : | the width of the new pixmap in pixels.
height : | the height of the new pixmap in pixels.
Returns : | the GdkBitmap

gdk_pixmap_create_from_data ()

GdkPixmap*          gdk_pixmap_create_from_data         (GdkDrawable *drawable,
                                                         const gchar *data,
                                                         gint width,
                                                         gint height,
                                                         gint depth,
                                                         const GdkColor *fg,
                                                         const GdkColor *bg);

Create a two-color pixmap from data in XBM data.

drawable : | a GdkDrawable, used to determine default values for the new pixmap. Can be NULL, if the depth is given.
data : | a pointer to the data.
width : | the width of the new pixmap in pixels.
height : | the height of the new pixmap in pixels.
depth : | the depth (number of bits per pixel) of the new pixmap.
fg : | the foreground color.
bg : | the background color.
Returns : | the GdkPixmap

gdk_pixmap_create_from_xpm ()

GdkPixmap*          gdk_pixmap_create_from_xpm          (GdkDrawable *drawable,
                                                         GdkBitmap **mask,
                                                         const GdkColor *transparent_color,
                                                         const gchar *filename);

Create a pixmap from a XPM file.

drawable : | a GdkDrawable, used to determine default values for the new pixmap.
mask : | a pointer to a place to store a bitmap representing the transparency mask of the XPM file. Can be NULL, in which case transparency will be ignored.
transparent_color : | the color to be used for the pixels that are transparent in the input file. Can be NULL, in which case a default color will be used.
filename : | the filename of a file containing XPM data.
Returns : | the GdkPixmap

gdk_pixmap_colormap_create_from_xpm ()

GdkPixmap*          gdk_pixmap_colormap_create_from_xpm (GdkDrawable *drawable,
                                                         GdkColormap *colormap,
                                                         GdkBitmap **mask,
                                                         const GdkColor *transparent_color,
                                                         const gchar *filename);

Create a pixmap from a XPM file using a particular colormap.

drawable : | a GdkDrawable, used to determine default values for the new pixmap. Can be NULL if colormap is given.
colormap : | the GdkColormap that the new pixmap will be use. If omitted, the colormap for window will be used.
mask : | a pointer to a place to store a bitmap representing the transparency mask of the XPM file. Can be NULL, in which case transparency will be ignored.
transparent_color : | the color to be used for the pixels that are transparent in the input file. Can be NULL, in which case a default color will be used.
filename : | the filename of a file containing XPM data.
Returns : | the GdkPixmap.

gdk_pixmap_create_from_xpm_d ()

GdkPixmap*          gdk_pixmap_create_from_xpm_d        (GdkDrawable *drawable,
                                                         GdkBitmap **mask,
                                                         const GdkColor *transparent_color,
                                                         gchar **data);

Create a pixmap from data in XPM format.

drawable : | a GdkDrawable, used to determine default values for the new pixmap.
mask : | Pointer to a place to store a bitmap representing the transparency mask of the XPM file. Can be NULL, in which case transparency will be ignored.
transparent_color : | This color will be used for the pixels that are transparent in the input file. Can be NULL in which case a default color will be used.
data : | Pointer to a string containing the XPM data.
Returns : | the GdkPixmap

gdk_pixmap_colormap_create_from_xpm_d ()

GdkPixmap*          gdk_pixmap_colormap_create_from_xpm_d
                                                        (GdkDrawable *drawable,
                                                         GdkColormap *colormap,
                                                         GdkBitmap **mask,
                                                         const GdkColor *transparent_color,
                                                         gchar **data);

Create a pixmap from data in XPM format using a particular colormap.

drawable : | a GdkDrawable, used to determine default values for the new pixmap. Can be NULL if colormap is given.
colormap : | the GdkColormap that the new pixmap will be use. If omitted, the colormap for window will be used.
mask : | a pointer to a place to store a bitmap representing the transparency mask of the XPM file. Can be NULL, in which case transparency will be ignored.
transparent_color : | the color to be used for the pixels that are transparent in the input file. Can be NULL, in which case a default color will be used.
data : | Pointer to a string containing the XPM data.
Returns : | the GdkPixmap.

gdk_pixmap_ref

#define gdk_pixmap_ref                 gdk_drawable_ref

Warning

gdk_pixmap_ref is deprecated and should not be used in newly-written code.

Deprecated equivalent of g_object_ref().

Returns : pixmap

gdk_pixmap_unref

#define gdk_pixmap_unref               gdk_drawable_unref

Warning

gdk_pixmap_unref is deprecated and should not be used in newly-written code.

Deprecated equivalent of g_object_unref().

struct GdkBitmap

struct GdkBitmap {
  gpointer user_data;
};

An opaque structure representing an offscreen drawable of depth 1. Pointers to structures of type GdkPixmap, GdkBitmap, and GdkWindow, can often be used interchangeably. The type GdkDrawable refers generically to any of these types.

gdk_bitmap_ref

#define gdk_bitmap_ref                 gdk_drawable_ref

Warning

gdk_bitmap_ref is deprecated and should not be used in newly-written code.

Deprecated equivalent of g_object_ref().

Returns : pixmap

gdk_bitmap_unref

#define gdk_bitmap_unref               gdk_drawable_unref

Warning

gdk_bitmap_unref is deprecated and should not be used in newly-written code.

Deprecated equivalent of g_object_unref().


Cairo Interaction

Cairo Interaction — Functions to support using Cairo

Synopsis

#include <gdk/gdk.h>

cairo_t*            gdk_cairo_create                    (GdkDrawable *drawable);
void                gdk_cairo_set_source_color          (cairo_t *cr,
                                                         GdkColor *color);
void                gdk_cairo_set_source_pixbuf         (cairo_t *cr,
                                                         GdkPixbuf *pixbuf,
                                                         double pixbuf_x,
                                                         double pixbuf_y);
void                gdk_cairo_set_source_pixmap         (cairo_t *cr,
                                                         GdkPixmap *pixmap,
                                                         double pixmap_x,
                                                         double pixmap_y);
void                gdk_cairo_rectangle                 (cairo_t *cr,
                                                         GdkRectangle *rectangle);
void                gdk_cairo_region                    (cairo_t *cr,
                                                         GdkRegion *region);

Description

Cairo is a graphics library that supports vector graphics and image compositing that can be used with GDK. Since 2.8, GTK+ does most of its drawing using Cairo.

GDK does not wrap the Cairo API, instead it allows to create Cairo contexts which can be used to draw on GDK drawables. Additional functions allow to convert GDK's rectangles and regions into Cairo paths and to use pixbufs as sources for drawing operations.

Details

gdk_cairo_create ()

cairo_t*            gdk_cairo_create                    (GdkDrawable *drawable);

Creates a Cairo context for drawing to drawable.

drawable : | a GdkDrawable
Returns : | A newly created Cairo context. Free with cairo_destroy() when you are done drawing.

Since 2.8

gdk_cairo_set_source_color ()

void                gdk_cairo_set_source_color          (cairo_t *cr,
                                                         GdkColor *color);

Sets the specified GdkColor as the source color of cr.

cr : | a cairo_t
color : | a GdkColor

Since 2.8

gdk_cairo_set_source_pixbuf ()

void                gdk_cairo_set_source_pixbuf         (cairo_t *cr,
                                                         GdkPixbuf *pixbuf,
                                                         double pixbuf_x,
                                                         double pixbuf_y);

Sets the given pixbuf as the source pattern for the Cairo context. The pattern has an extend mode of CAIRO_EXTEND_NONE and is aligned so that the origin of pixbuf is pixbuf_x, pixbuf_y

cr : | a Cairo context
pixbuf : | a GdkPixbuf
pixbuf_x : | X coordinate of location to place upper left corner of pixbuf
pixbuf_y : | Y coordinate of location to place upper left corner of pixbuf

Since 2.8

gdk_cairo_set_source_pixmap ()

void                gdk_cairo_set_source_pixmap         (cairo_t *cr,
                                                         GdkPixmap *pixmap,
                                                         double pixmap_x,
                                                         double pixmap_y);

Sets the given pixmap as the source pattern for the Cairo context. The pattern has an extend mode of CAIRO_EXTEND_NONE and is aligned so that the origin of pixbuf is pixbuf_x, pixbuf_y

cr : | a Cairo context
pixmap : | a GdkPixmap
pixmap_x : | X coordinate of location to place upper left corner of pixmap
pixmap_y : | Y coordinate of location to place upper left corner of pixmap

Since 2.10

gdk_cairo_rectangle ()

void                gdk_cairo_rectangle                 (cairo_t *cr,
                                                         GdkRectangle *rectangle);

Adds the given rectangle to the current path of cr.

cr : | a cairo_t
rectangle : | a GdkRectangle

Since 2.8

gdk_cairo_region ()

void                gdk_cairo_region                    (cairo_t *cr,
                                                         GdkRegion *region);

Adds the given region to the current path of cr.

cr : | a cairo_t
region : | a GdkRegion

Since 2.8


Colormaps and Colors

Colormaps and Colors — Manipulation of colors and colormaps

Synopsis

#include <gdk/gdk.h>

                    GdkColor;
                    GdkColormap;
GdkColormap*        gdk_colormap_new                    (GdkVisual *visual,
                                                         gboolean allocate);
GdkColormap*        gdk_colormap_ref                    (GdkColormap *cmap);
void                gdk_colormap_unref                  (GdkColormap *cmap);
GdkColormap*        gdk_colormap_get_system             (void);
gint                gdk_colormap_get_system_size        (void);
void                gdk_colormap_change                 (GdkColormap *colormap,
                                                         gint ncolors);
gint                gdk_colormap_alloc_colors           (GdkColormap *colormap,
                                                         GdkColor *colors,
                                                         gint ncolors,
                                                         gboolean writeable,
                                                         gboolean best_match,
                                                         gboolean *success);
gboolean            gdk_colormap_alloc_color            (GdkColormap *colormap,
                                                         GdkColor *color,
                                                         gboolean writeable,
                                                         gboolean best_match);
void                gdk_colormap_free_colors            (GdkColormap *colormap,
                                                         GdkColor *colors,
                                                         gint ncolors);
void                gdk_colormap_query_color            (GdkColormap *colormap,
                                                         gulong pixel,
                                                         GdkColor *result);
GdkVisual*          gdk_colormap_get_visual             (GdkColormap *colormap);
GdkScreen*          gdk_colormap_get_screen             (GdkColormap *cmap);
void                gdk_colors_store                    (GdkColormap *colormap,
                                                         GdkColor *colors,
                                                         gint ncolors);
GdkColor*           gdk_color_copy                      (const GdkColor *color);
void                gdk_color_free                      (GdkColor *color);
gint                gdk_colors_alloc                    (GdkColormap *colormap,
                                                         gboolean contiguous,
                                                         gulong *planes,
                                                         gint nplanes,
                                                         gulong *pixels,
                                                         gint npixels);
void                gdk_colors_free                     (GdkColormap *colormap,
                                                         gulong *pixels,
                                                         gint npixels,
                                                         gulong planes);
gint                gdk_color_white                     (GdkColormap *colormap,
                                                         GdkColor *color);
gint                gdk_color_black                     (GdkColormap *colormap,
                                                         GdkColor *color);
gboolean            gdk_color_parse                     (const gchar *spec,
                                                         GdkColor *color);
gint                gdk_color_alloc                     (GdkColormap *colormap,
                                                         GdkColor *color);
gint                gdk_color_change                    (GdkColormap *colormap,
                                                         GdkColor *color);
gboolean            gdk_color_equal                     (const GdkColor *colora,
                                                         const GdkColor *colorb);
guint               gdk_color_hash                      (const GdkColor *colora);

Description

These functions are used to modify colormaps. A colormap is an object that contains the mapping between the color values stored in memory and the RGB values that are used to display color values. In general, colormaps only contain significant information for pseudo-color visuals, but even for other visual types, a colormap object is required in some circumstances.

There are a couple of special colormaps that can be retrieved. The system colormap (retrieved with gdk_colormap_get_system()) is the default colormap of the system. If you are using GdkRGB, there is another colormap that is important - the colormap in which GdkRGB works, retrieved with gdk_rgb_get_cmap(). However, when using GdkRGB, it is not generally necessary to allocate colors directly.

In previous revisions of this interface, a number of functions that take a GdkColormap parameter were replaced with functions whose names began with "gdk_colormap_". This process will probably be extended somewhat in the future - gdk_color_white(), gdk_color_black(), and gdk_color_change() will probably become aliases.

Details

GdkColor

typedef struct {
  guint32 pixel;
  guint16 red;
  guint16 green;
  guint16 blue;
} GdkColor;

The GdkColor structure is used to describe an allocated or unallocated color.

guint32 pixel; | For allocated colors, the value used to draw this color on the screen.
guint16 red; | The red component of the color. This is a value between 0 and 65535, with 65535 indicating full intensitiy.
guint16 green; | The blue component of the color.
guint16 blue; | The green component of the color.

GdkColormap

typedef struct {
  gint      size;
  GdkColor *colors;
} GdkColormap;

The colormap structure contains the following public fields.

gint size; | For pseudo-color colormaps, the number of colors in the colormap.
GdkColor *colors; | An array containing the current values in the colormap. This can be used to map from pixel values back to RGB values. This is only meaningful for pseudo-color colormaps.

gdk_colormap_new ()

GdkColormap*        gdk_colormap_new                    (GdkVisual *visual,
                                                         gboolean allocate);

Creates a new colormap for the given visual.

visual : | a GdkVisual.
allocate : | if TRUE, the newly created colormap will be a private colormap, and all colors in it will be allocated for the applications use.
Returns : | the new GdkColormap.

gdk_colormap_ref ()

GdkColormap*        gdk_colormap_ref                    (GdkColormap *cmap);

Warning

gdk_colormap_ref is deprecated and should not be used in newly-written code.

Deprecated function; use g_object_ref() instead.

cmap : | a GdkColormap
Returns : | the colormap

gdk_colormap_unref ()

void                gdk_colormap_unref                  (GdkColormap *cmap);

Warning

gdk_colormap_unref is deprecated and should not be used in newly-written code.

Deprecated function; use g_object_ref() instead.

cmap : a GdkColormap

gdk_colormap_get_system ()

GdkColormap*        gdk_colormap_get_system             (void);

Gets the system's default colormap for the default screen. (See gdk_colormap_get_system_for_screen())

Returns : the default colormap.

gdk_colormap_get_system_size ()

gint                gdk_colormap_get_system_size        (void);

Warning

gdk_colormap_get_system_size is deprecated and should not be used in newly-written code.

Returns the size of the system's default colormap. (See the description of struct GdkColormap for an explanation of the size of a colormap.)

Returns : the size of the system's default colormap.

gdk_colormap_change ()

void                gdk_colormap_change                 (GdkColormap *colormap,
                                                         gint ncolors);

Warning

gdk_colormap_change is deprecated and should not be used in newly-written code.

Changes the value of the first ncolors in a private colormap to match the values in the colors array in the colormap. This function is obsolete and should not be used. See gdk_color_change().

colormap : | a GdkColormap.
ncolors : | the number of colors to change.

gdk_colormap_alloc_colors ()

gint                gdk_colormap_alloc_colors           (GdkColormap *colormap,
                                                         GdkColor *colors,
                                                         gint ncolors,
                                                         gboolean writeable,
                                                         gboolean best_match,
                                                         gboolean *success);

Allocates colors from a colormap.

colormap : | a GdkColormap.
colors : | The color values to allocate. On return, the pixel values for allocated colors will be filled in.
ncolors : | The number of colors in colors.
writeable : | If TRUE, the colors are allocated writeable (their values can later be changed using gdk_color_change()). Writeable colors cannot be shared between applications.
best_match : | If TRUE, GDK will attempt to do matching against existing colors if the colors cannot be allocated as requested.
success : | An array of length ncolors. On return, this indicates whether the corresponding color in colors was successfully allocated or not.
Returns : | The number of colors that were not successfully allocated.

gdk_colormap_alloc_color ()

gboolean            gdk_colormap_alloc_color            (GdkColormap *colormap,
                                                         GdkColor *color,
                                                         gboolean writeable,
                                                         gboolean best_match);

Allocates a single color from a colormap.

colormap : | a GdkColormap.
color : | the color to allocate. On return the pixel field will be filled in if allocation succeeds.
writeable : | If TRUE, the color is allocated writeable (their values can later be changed using gdk_color_change()). Writeable colors cannot be shared between applications.
best_match : | If TRUE, GDK will attempt to do matching against existing colors if the color cannot be allocated as requested.
Returns : | TRUE if the allocation succeeded.

gdk_colormap_free_colors ()

void                gdk_colormap_free_colors            (GdkColormap *colormap,
                                                         GdkColor *colors,
                                                         gint ncolors);

Frees previously allocated colors.

colormap : | a GdkColormap.
colors : | the colors to free.
ncolors : | the number of colors in colors.

gdk_colormap_query_color ()

void                gdk_colormap_query_color            (GdkColormap *colormap,
                                                         gulong pixel,
                                                         GdkColor *result);

Locates the RGB color in colormap corresponding to the given hardware pixel pixel. pixel must be a valid pixel in the colormap; it's a programmer error to call this function with a pixel which is not in the colormap. Hardware pixels are normally obtained from gdk_colormap_alloc_colors(), or from a GdkImage. (A GdkImage contains image data in hardware format, a GdkPixbuf contains image data in a canonical 24-bit RGB format.)

This function is rarely useful; it's used for example to implement the eyedropper feature in GtkColorSelection.

colormap : | a GdkColormap
pixel : | pixel value in hardware display format
result : | GdkColor with red, green, blue fields initialized

gdk_colormap_get_visual ()

GdkVisual*          gdk_colormap_get_visual             (GdkColormap *colormap);

Returns the visual for which a given colormap was created.

colormap : | a GdkColormap.
Returns : | the visual of the colormap.

gdk_colormap_get_screen ()

GdkScreen*          gdk_colormap_get_screen             (GdkColormap *cmap);

Gets the screen for which this colormap was created.

cmap : | a GdkColormap
Returns : | the screen for which this colormap was created.

Since 2.2

gdk_colors_store ()

void                gdk_colors_store                    (GdkColormap *colormap,
                                                         GdkColor *colors,
                                                         gint ncolors);

Warning

gdk_colors_store is deprecated and should not be used in newly-written code.

Changes the value of the first ncolors colors in a private colormap. This function is obsolete and should not be used. See gdk_color_change().

colormap : | a GdkColormap.
colors : | the new color values.
ncolors : | the number of colors to change.

gdk_color_copy ()

GdkColor*           gdk_color_copy                      (const GdkColor *color);

Makes a copy of a color structure. The result must be freed using gdk_color_free().

color : | a GdkColor.
Returns : | a copy of color.

gdk_color_free ()

void                gdk_color_free                      (GdkColor *color);

Frees a color structure created with gdk_color_copy().

color : a GdkColor.

gdk_colors_alloc ()

gint                gdk_colors_alloc                    (GdkColormap *colormap,
                                                         gboolean contiguous,
                                                         gulong *planes,
                                                         gint nplanes,
                                                         gulong *pixels,
                                                         gint npixels);

Warning

gdk_colors_alloc is deprecated and should not be used in newly-written code.

Allocates colors from a colormap. This function is obsolete. See gdk_colormap_alloc_colors(). For full documentation of the fields, see the Xlib documentation for XAllocColorCells().

colormap : | a GdkColormap.
contiguous : | if TRUE, the colors should be allocated in contiguous color cells.
planes : | an array in which to store the plane masks.
nplanes : | the number of planes to allocate. (Or zero, to indicate that the color allocation should not be planar.)
pixels : | an array into which to store allocated pixel values.
npixels : | the number of pixels in each plane to allocate.
Returns : | TRUE if the allocation was successful

gdk_colors_free ()

void                gdk_colors_free                     (GdkColormap *colormap,
                                                         gulong *pixels,
                                                         gint npixels,
                                                         gulong planes);

Warning

gdk_colors_free is deprecated and should not be used in newly-written code.

Frees colors allocated with gdk_colors_alloc(). This function is obsolete. See gdk_colormap_free_colors().

colormap : | a GdkColormap.
pixels : | the pixel values of the colors to free.
npixels : | the number of values in pixels.
planes : | the plane masks for all planes to free, OR'd together.

gdk_color_white ()

gint                gdk_color_white                     (GdkColormap *colormap,
                                                         GdkColor *color);

Warning

gdk_color_white is deprecated and should not be used in newly-written code.

Returns the white color for a given colormap. The resulting value has already allocated been allocated.

colormap : | a GdkColormap.
color : | the location to store the color.
Returns : | TRUE if the allocation succeeded.

gdk_color_black ()

gint                gdk_color_black                     (GdkColormap *colormap,
                                                         GdkColor *color);

Warning

gdk_color_black is deprecated and should not be used in newly-written code.

Returns the black color for a given colormap. The resulting value has already benn allocated.

colormap : | a GdkColormap.
color : | the location to store the color.
Returns : | TRUE if the allocation succeeded.

gdk_color_parse ()

gboolean            gdk_color_parse                     (const gchar *spec,
                                                         GdkColor *color);

Parses a textual specification of a color and fill in the red, green, and blue fields of a GdkColor structure. The color is not allocated, you must call gdk_colormap_alloc_color() yourself. The text string can be in any of the forms accepted by XParseColor; these include name for a color from rgb.txt, such as DarkSlateGray, or a hex specification such as #3050b2 or #35b.

spec : | the string specifying the color.
color : | the GdkColor to fill in
Returns : | TRUE if the parsing succeeded.

gdk_color_alloc ()

gint                gdk_color_alloc                     (GdkColormap *colormap,
                                                         GdkColor *color);

Warning

gdk_color_alloc is deprecated and should not be used in newly-written code. Use gdk_colormap_alloc_color() instead.

Allocates a single color from a colormap.

colormap : | a GdkColormap.
color : | The color to allocate. On return, the pixel field will be filled in.
Returns : | TRUE if the allocation succeeded.

gdk_color_change ()

gint                gdk_color_change                    (GdkColormap *colormap,
                                                         GdkColor *color);

Warning

gdk_color_change is deprecated and should not be used in newly-written code.

Changes the value of a color that has already been allocated. If colormap is not a private colormap, then the color must have been allocated using gdk_colormap_alloc_colors() with the writeable set to TRUE.

colormap : | a GdkColormap.
color : | a GdkColor, with the color to change in the pixel field, and the new value in the remaining fields.
Returns : | TRUE if the color was successfully changed.

gdk_color_equal ()

gboolean            gdk_color_equal                     (const GdkColor *colora,
                                                         const GdkColor *colorb);

Compares two colors.

colora : | a GdkColor.
colorb : | another GdkColor.
Returns : | TRUE if the two colors compare equal

gdk_color_hash ()

guint               gdk_color_hash                      (const GdkColor *colora);

A hash function suitable for using for a hash table that stores GdkColor's.

colora : | a GdkColor.
Returns : | The hash function appled to colora


Cursors

Cursors — Standard and pixmap cursors

Synopsis

#include <gdk/gdk.h>

                    GdkCursor;
enum                GdkCursorType;
GdkCursor*          gdk_cursor_new                      (GdkCursorType cursor_type);
GdkCursor*          gdk_cursor_new_from_pixmap          (GdkPixmap *source,
                                                         GdkPixmap *mask,
                                                         const GdkColor *fg,
                                                         const GdkColor *bg,
                                                         gint x,
                                                         gint y);
GdkCursor*          gdk_cursor_new_from_pixbuf          (GdkDisplay *display,
                                                         GdkPixbuf *pixbuf,
                                                         gint x,
                                                         gint y);
GdkCursor*          gdk_cursor_new_from_name            (GdkDisplay *display,
                                                         const gchar *name);
GdkCursor*          gdk_cursor_new_for_display          (GdkDisplay *display,
                                                         GdkCursorType cursor_type);
GdkDisplay*         gdk_cursor_get_display              (GdkCursor *cursor);
GdkPixbuf*          gdk_cursor_get_image                (GdkCursor *cursor);
GdkCursor*          gdk_cursor_ref                      (GdkCursor *cursor);
void                gdk_cursor_unref                    (GdkCursor *cursor);
#define             gdk_cursor_destroy

Description

These functions are used to create and destroy cursors. There is a number of standard cursors, but it is also possible to construct new cursors from pixmaps and pixbufs. There may be limitations as to what kinds of cursors can be constructed on a given display, see gdk_display_supports_cursor_alpha(), gdk_display_supports_cursor_color(), gdk_display_get_default_cursor_size() and gdk_display_get_maximal_cursor_size().

Cursors by themselves are not very interesting, they must be be bound to a window for users to see them. This is done with gdk_window_set_cursor() or by setting the cursor member of the GdkWindowAttr struct passed to gdk_window_new().

Details

GdkCursor

typedef struct {
  GdkCursorType type;
} GdkCursor;

A GdkCursor structure represents a cursor.

GdkCursorType type; the GdkCursorType of the cursor

enum GdkCursorType

typedef enum
{
  GDK_X_CURSOR 		  = 0,
  GDK_ARROW 		  = 2,
  GDK_BASED_ARROW_DOWN    = 4,
  GDK_BASED_ARROW_UP 	  = 6,
  GDK_BOAT 		  = 8,
  GDK_BOGOSITY 		  = 10,
  GDK_BOTTOM_LEFT_CORNER  = 12,
  GDK_BOTTOM_RIGHT_CORNER = 14,
  GDK_BOTTOM_SIDE 	  = 16,
  GDK_BOTTOM_TEE 	  = 18,
  GDK_BOX_SPIRAL 	  = 20,
  GDK_CENTER_PTR 	  = 22,
  GDK_CIRCLE 		  = 24,
  GDK_CLOCK	 	  = 26,
  GDK_COFFEE_MUG 	  = 28,
  GDK_CROSS 		  = 30,
  GDK_CROSS_REVERSE 	  = 32,
  GDK_CROSSHAIR 	  = 34,
  GDK_DIAMOND_CROSS 	  = 36,
  GDK_DOT 		  = 38,
  GDK_DOTBOX 		  = 40,
  GDK_DOUBLE_ARROW 	  = 42,
  GDK_DRAFT_LARGE 	  = 44,
  GDK_DRAFT_SMALL 	  = 46,
  GDK_DRAPED_BOX 	  = 48,
  GDK_EXCHANGE 		  = 50,
  GDK_FLEUR 		  = 52,
  GDK_GOBBLER 		  = 54,
  GDK_GUMBY 		  = 56,
  GDK_HAND1 		  = 58,
  GDK_HAND2 		  = 60,
  GDK_HEART 		  = 62,
  GDK_ICON 		  = 64,
  GDK_IRON_CROSS 	  = 66,
  GDK_LEFT_PTR 		  = 68,
  GDK_LEFT_SIDE 	  = 70,
  GDK_LEFT_TEE 		  = 72,
  GDK_LEFTBUTTON 	  = 74,
  GDK_LL_ANGLE 		  = 76,
  GDK_LR_ANGLE 	 	  = 78,
  GDK_MAN 		  = 80,
  GDK_MIDDLEBUTTON 	  = 82,
  GDK_MOUSE 		  = 84,
  GDK_PENCIL 		  = 86,
  GDK_PIRATE 		  = 88,
  GDK_PLUS 		  = 90,
  GDK_QUESTION_ARROW 	  = 92,
  GDK_RIGHT_PTR 	  = 94,
  GDK_RIGHT_SIDE 	  = 96,
  GDK_RIGHT_TEE 	  = 98,
  GDK_RIGHTBUTTON 	  = 100,
  GDK_RTL_LOGO 		  = 102,
  GDK_SAILBOAT 		  = 104,
  GDK_SB_DOWN_ARROW 	  = 106,
  GDK_SB_H_DOUBLE_ARROW   = 108,
  GDK_SB_LEFT_ARROW 	  = 110,
  GDK_SB_RIGHT_ARROW 	  = 112,
  GDK_SB_UP_ARROW 	  = 114,
  GDK_SB_V_DOUBLE_ARROW   = 116,
  GDK_SHUTTLE 		  = 118,
  GDK_SIZING 		  = 120,
  GDK_SPIDER		  = 122,
  GDK_SPRAYCAN 		  = 124,
  GDK_STAR 		  = 126,
  GDK_TARGET 		  = 128,
  GDK_TCROSS 		  = 130,
  GDK_TOP_LEFT_ARROW 	  = 132,
  GDK_TOP_LEFT_CORNER 	  = 134,
  GDK_TOP_RIGHT_CORNER 	  = 136,
  GDK_TOP_SIDE 		  = 138,
  GDK_TOP_TEE 		  = 140,
  GDK_TREK 		  = 142,
  GDK_UL_ANGLE 		  = 144,
  GDK_UMBRELLA 		  = 146,
  GDK_UR_ANGLE 		  = 148,
  GDK_WATCH 		  = 150,
  GDK_XTERM 		  = 152,
  GDK_LAST_CURSOR,
  GDK_CURSOR_IS_PIXMAP 	= -1
} GdkCursorType;

The standard cursors available.

GDK_X_CURSOR |
GDK_ARROW |
GDK_BASED_ARROW_DOWN |
GDK_BASED_ARROW_UP |
GDK_BOAT |
GDK_BOGOSITY |
GDK_BOTTOM_LEFT_CORNER |
GDK_BOTTOM_RIGHT_CORNER |
GDK_BOTTOM_SIDE |
GDK_BOTTOM_TEE |
GDK_BOX_SPIRAL |
GDK_CENTER_PTR |
GDK_CIRCLE |
GDK_CLOCK |
GDK_COFFEE_MUG |
GDK_CROSS |
GDK_CROSS_REVERSE |
GDK_CROSSHAIR |
GDK_DIAMOND_CROSS |
GDK_DOT |
GDK_DOTBOX |
GDK_DOUBLE_ARROW |
GDK_DRAFT_LARGE |
GDK_DRAFT_SMALL |
GDK_DRAPED_BOX |
GDK_EXCHANGE |
GDK_FLEUR |
GDK_GOBBLER |
GDK_GUMBY |
GDK_HAND1 |
GDK_HAND2 |
GDK_HEART |
GDK_ICON |
GDK_IRON_CROSS |
GDK_LEFT_PTR |
GDK_LEFT_SIDE |
GDK_LEFT_TEE |
GDK_LEFTBUTTON |
GDK_LL_ANGLE |
GDK_LR_ANGLE |
GDK_MAN |
GDK_MIDDLEBUTTON |
GDK_MOUSE |
GDK_PENCIL |
GDK_PIRATE |
GDK_PLUS |
GDK_QUESTION_ARROW |
GDK_RIGHT_PTR |
GDK_RIGHT_SIDE |
GDK_RIGHT_TEE |
GDK_RIGHTBUTTON |
GDK_RTL_LOGO |
GDK_SAILBOAT |
GDK_SB_DOWN_ARROW |
GDK_SB_H_DOUBLE_ARROW |
GDK_SB_LEFT_ARROW |
GDK_SB_RIGHT_ARROW |
GDK_SB_UP_ARROW |
GDK_SB_V_DOUBLE_ARROW |
GDK_SHUTTLE |
GDK_SIZING |
GDK_SPIDER |
GDK_SPRAYCAN |
GDK_STAR |
GDK_TARGET |
GDK_TCROSS |
GDK_TOP_LEFT_ARROW |
GDK_TOP_LEFT_CORNER |
GDK_TOP_RIGHT_CORNER |
GDK_TOP_SIDE |
GDK_TOP_TEE |
GDK_TREK |
GDK_UL_ANGLE |
GDK_UMBRELLA |
GDK_UR_ANGLE |
GDK_WATCH |
GDK_XTERM |
GDK_LAST_CURSOR | last cursor type
GDK_CURSOR_IS_PIXMAP | type of cursors constructed with gdk_cursor_new_from_pixmap() or gdk_cursor_new_from_pixbuf()

gdk_cursor_new ()

GdkCursor*          gdk_cursor_new                      (GdkCursorType cursor_type);

Creates a new cursor from the set of builtin cursors for the default display. See gdk_cursor_new_for_display().

To make the cursor invisible, use gdk_cursor_new_from_pixmap() to create a cursor with no pixels in it.

cursor_type : | cursor to create
Returns : | a new GdkCursor

gdk_cursor_new_from_pixmap ()

GdkCursor*          gdk_cursor_new_from_pixmap          (GdkPixmap *source,
                                                         GdkPixmap *mask,
                                                         const GdkColor *fg,
                                                         const GdkColor *bg,
                                                         gint x,
                                                         gint y);

Creates a new cursor from a given pixmap and mask. Both the pixmap and mask must have a depth of 1 (i.e. each pixel has only 2 values - on or off). The standard cursor size is 16 by 16 pixels. You can create a bitmap from inline data as in the below example.

Example 6. Creating a custom cursor

/* This data is in X bitmap format, and can be created with the 'bitmap'
   utility. */
#define cursor1_width 16
#define cursor1_height 16
static unsigned char cursor1_bits[] = {
  0x80, 0x01, 0x40, 0x02, 0x20, 0x04, 0x10, 0x08, 0x08, 0x10, 0x04, 0x20,
  0x82, 0x41, 0x41, 0x82, 0x41, 0x82, 0x82, 0x41, 0x04, 0x20, 0x08, 0x10,
  0x10, 0x08, 0x20, 0x04, 0x40, 0x02, 0x80, 0x01};

static unsigned char cursor1mask_bits[] = {
  0x80, 0x01, 0xc0, 0x03, 0x60, 0x06, 0x30, 0x0c, 0x18, 0x18, 0x8c, 0x31,
  0xc6, 0x63, 0x63, 0xc6, 0x63, 0xc6, 0xc6, 0x63, 0x8c, 0x31, 0x18, 0x18,
  0x30, 0x0c, 0x60, 0x06, 0xc0, 0x03, 0x80, 0x01};

 GdkCursor *cursor;
 GdkPixmap *source, *mask;
 GdkColor fg = { 0, 65535, 0, 0 }; /* Red. */
 GdkColor bg = { 0, 0, 0, 65535 }; /* Blue. */

 source = gdk_bitmap_create_from_data (NULL, cursor1_bits,
                                       cursor1_width, cursor1_height);
 mask = gdk_bitmap_create_from_data (NULL, cursor1mask_bits,
                                     cursor1_width, cursor1_height);
 cursor = gdk_cursor_new_from_pixmap (source, mask, &fg, &bg, 8, 8);
 gdk_pixmap_unref (source);
 gdk_pixmap_unref (mask);

 gdk_window_set_cursor (widget->window, cursor);

source : | the pixmap specifying the cursor.
mask : | the pixmap specifying the mask, which must be the same size as source.
fg : | the foreground color, used for the bits in the source which are 1. The color does not have to be allocated first.
bg : | the background color, used for the bits in the source which are 0. The color does not have to be allocated first.
x : | the horizontal offset of the 'hotspot' of the cursor.
y : | the vertical offset of the 'hotspot' of the cursor.
Returns : | a new GdkCursor.

gdk_cursor_new_from_pixbuf ()

GdkCursor*          gdk_cursor_new_from_pixbuf          (GdkDisplay *display,
                                                         GdkPixbuf *pixbuf,
                                                         gint x,
                                                         gint y);

Creates a new cursor from a pixbuf.

Not all GDK backends support RGBA cursors. If they are not
supported, a monochrome approximation will be displayed.
The functions gdk_display_supports_cursor_alpha() and
gdk_display_supports_cursor_color() can be used to determine
whether RGBA cursors are supported;
gdk_display_get_default_cursor_size() and
gdk_display_get_maximal_cursor_size() give information about
cursor sizes.

On the X backend, support for RGBA cursors requires a sufficently new version of the X Render extension.

display : | the GdkDisplay for which the cursor will be created
pixbuf : | the GdkPixbuf containing the cursor image
x : | the horizontal offset of the 'hotspot' of the cursor.
y : | the vertical offset of the 'hotspot' of the cursor.
Returns : | a new GdkCursor.

Since 2.4

gdk_cursor_new_from_name ()

GdkCursor*          gdk_cursor_new_from_name            (GdkDisplay *display,
                                                         const gchar *name);

Creates a new cursor by looking up name in the current cursor theme.

display : | the GdkDisplay for which the cursor will be created
name : | the name of the cursor
Returns : | a new GdkCursor, or NULL if there is no cursor with the given name

Since 2.8

gdk_cursor_new_for_display ()

GdkCursor*          gdk_cursor_new_for_display          (GdkDisplay *display,
                                                         GdkCursorType cursor_type);

Creates a new cursor from the set of builtin cursors. Some useful ones are:

  • GDK_RIGHT_PTR (right-facing arrow)

  • GDK_CROSSHAIR (crosshair)

  • GDK_XTERM (I-beam)

  • GDK_WATCH (busy)

  • GDK_FLEUR (for moving objects)

  • GDK_HAND1 (a right-pointing hand)

  • GDK_HAND2 (a left-pointing hand)

  • GDK_LEFT_SIDE (resize left side)

  • GDK_RIGHT_SIDE (resize right side)

  • GDK_TOP_LEFT_CORNER (resize northwest corner)

  • GDK_TOP_RIGHT_CORNER (resize northeast corner)

  • GDK_BOTTOM_LEFT_CORNER (resize southwest corner)

  • GDK_BOTTOM_RIGHT_CORNER (resize southeast corner)

  • GDK_TOP_SIDE (resize top side)

  • GDK_BOTTOM_SIDE (resize bottom side)

  • GDK_SB_H_DOUBLE_ARROW (move vertical splitter)

  • GDK_SB_V_DOUBLE_ARROW (move horizontal splitter)

To make the cursor invisible, use gdk_cursor_new_from_pixmap() to create a cursor with no pixels in it.

display : | the GdkDisplay for which the cursor will be created
cursor_type : | cursor to create
Returns : | a new GdkCursor

Since 2.2

gdk_cursor_get_display ()

GdkDisplay*         gdk_cursor_get_display              (GdkCursor *cursor);

Returns the display on which the GdkCursor is defined.

cursor : | a GdkCursor.
Returns : | the GdkDisplay associated to cursor

Since 2.2

gdk_cursor_get_image ()

GdkPixbuf*          gdk_cursor_get_image                (GdkCursor *cursor);

Returns a GdkPixbuf with the image used to display the cursor.

Note that depending on the capabilities of the windowing system and on the cursor, GDK may not be able to obtain the image data. In this case, NULL is returned.

cursor : | a GdkCursor
Returns : | a GdkPixbuf representing cursor, or NULL

Since 2.8

gdk_cursor_ref ()

GdkCursor*          gdk_cursor_ref                      (GdkCursor *cursor);

Adds a reference to cursor.

cursor : | a GdkCursor
Returns : | Same cursor that was passed in

gdk_cursor_unref ()

void                gdk_cursor_unref                    (GdkCursor *cursor);

Removes a reference from cursor, deallocating the cursor if no references remain.

cursor : a GdkCursor

gdk_cursor_destroy

#define gdk_cursor_destroy             gdk_cursor_unref

Warning

gdk_cursor_destroy is deprecated and should not be used in newly-written code.

Destroys a cursor, freeing any resources allocated for it.


Drag and Drop

Drag and Drop — Functions for controlling drag and drop handling

Synopsis

#include <gdk/gdk.h>

GdkAtom             gdk_drag_get_selection              (GdkDragContext *context);
void                gdk_drag_abort                      (GdkDragContext *context,
                                                         guint32 time_);
void                gdk_drop_reply                      (GdkDragContext *context,
                                                         gboolean ok,
                                                         guint32 time_);
GdkDragContext*     gdk_drag_context_new                (void);
void                gdk_drag_drop                       (GdkDragContext *context,
                                                         guint32 time_);
void                gdk_drag_find_window                (GdkDragContext *context,
                                                         GdkWindow *drag_window,
                                                         gint x_root,
                                                         gint y_root,
                                                         GdkWindow **dest_window,
                                                         GdkDragProtocol *protocol);
void                gdk_drag_find_window_for_screen     (GdkDragContext *context,
                                                         GdkWindow *drag_window,
                                                         GdkScreen *screen,
                                                         gint x_root,
                                                         gint y_root,
                                                         GdkWindow **dest_window,
                                                         GdkDragProtocol *protocol);
void                gdk_drag_context_ref                (GdkDragContext *context);
GdkDragContext*     gdk_drag_begin                      (GdkWindow *window,
                                                         GList *targets);
gboolean            gdk_drag_motion                     (GdkDragContext *context,
                                                         GdkWindow *dest_window,
                                                         GdkDragProtocol protocol,
                                                         gint x_root,
                                                         gint y_root,
                                                         GdkDragAction suggested_action,
                                                         GdkDragAction possible_actions,
                                                         guint32 time_);
void                gdk_drop_finish                     (GdkDragContext *context,
                                                         gboolean success,
                                                         guint32 time_);
guint32             gdk_drag_get_protocol               (guint32 xid,
                                                         GdkDragProtocol *protocol);
guint32             gdk_drag_get_protocol_for_display   (GdkDisplay *display,
                                                         guint32 xid,
                                                         GdkDragProtocol *protocol);
enum                GdkDragProtocol;
void                gdk_drag_context_unref              (GdkDragContext *context);
                    GdkDragContext;
enum                GdkDragAction;
void                gdk_drag_status                     (GdkDragContext *context,
                                                         GdkDragAction action,
                                                         guint32 time_);
gboolean            gdk_drag_drop_succeeded             (GdkDragContext *context);

Description

These functions provide a low level interface for drag and drop. The X backend of GDK supports both the Xdnd and Motif drag and drop protocols transparently, the Win32 backend supports the WM_DROPFILES protocol.

GTK+ provides a higher level abstraction based on top of these functions, and so they are not normally needed in GTK+ applications. See the Drag and Drop section of the GTK+ documentation for more information.

Details

gdk_drag_get_selection ()

GdkAtom             gdk_drag_get_selection              (GdkDragContext *context);

Returns the selection atom for the current source window.

context : | a GdkDragContext.
Returns : | the selection atom.

gdk_drag_abort ()

void                gdk_drag_abort                      (GdkDragContext *context,
                                                         guint32 time_);

Aborts a drag without dropping.

This function is called by the drag source.

context : | a GdkDragContext.
time_ : | the timestamp for this operation.

gdk_drop_reply ()

void                gdk_drop_reply                      (GdkDragContext *context,
                                                         gboolean ok,
                                                         guint32 time_);

Accepts or rejects a drop.

This function is called by the drag destination in response to a drop initiated by the drag source.

context : | a GdkDragContext.
ok : | TRUE if the drop is accepted.
time_ : | the timestamp for this operation.

gdk_drag_context_new ()

GdkDragContext*     gdk_drag_context_new                (void);

Creates a new GdkDragContext.

Returns : the newly created GdkDragContext.

gdk_drag_drop ()

void                gdk_drag_drop                       (GdkDragContext *context,
                                                         guint32 time_);

Drops on the current destination.

This function is called by the drag source.

context : | a GdkDragContext.
time_ : | the timestamp for this operation.

gdk_drag_find_window ()

void                gdk_drag_find_window                (GdkDragContext *context,
                                                         GdkWindow *drag_window,
                                                         gint x_root,
                                                         gint y_root,
                                                         GdkWindow **dest_window,
                                                         GdkDragProtocol *protocol);

Finds the destination window and DND protocol to use at the given pointer position.

This function is called by the drag source to obtain the dest_window and protocol parameters for gdk_drag_motion().

context : | a GdkDragContext.
drag_window : | a window which may be at the pointer position, but should be ignored, since it is put up by the drag source as an icon.
x_root : | the x position of the pointer in root coordinates.
y_root : | the y position of the pointer in root coordinates.
dest_window : | location to store the destination window in.
protocol : | location to store the DND protocol in.

gdk_drag_find_window_for_screen ()

void                gdk_drag_find_window_for_screen     (GdkDragContext *context,
                                                         GdkWindow *drag_window,
                                                         GdkScreen *screen,
                                                         gint x_root,
                                                         gint y_root,
                                                         GdkWindow **dest_window,
                                                         GdkDragProtocol *protocol);

Finds the destination window and DND protocol to use at the given pointer position.

This function is called by the drag source to obtain the dest_window and protocol parameters for gdk_drag_motion().

context : | a GdkDragContext
drag_window : | a window which may be at the pointer position, but should be ignored, since it is put up by the drag source as an icon.
screen : | the screen where the destination window is sought.
x_root : | the x position of the pointer in root coordinates.
y_root : | the y position of the pointer in root coordinates.
dest_window : | location to store the destination window in.
protocol : | location to store the DND protocol in.

Since 2.2

gdk_drag_context_ref ()

void                gdk_drag_context_ref                (GdkDragContext *context);

Warning

gdk_drag_context_ref is deprecated and should not be used in newly-written code.

Deprecated function; use g_object_ref() instead.

context : a GdkDragContext.

gdk_drag_begin ()

GdkDragContext*     gdk_drag_begin                      (GdkWindow *window,
                                                         GList *targets);

Starts a drag and creates a new drag context for it.

This function is called by the drag source.

window : | the source window for this drag.
targets : | the list of offered targets.
Returns : | a newly created GdkDragContext.

gdk_drag_motion ()

gboolean            gdk_drag_motion                     (GdkDragContext *context,
                                                         GdkWindow *dest_window,
                                                         GdkDragProtocol protocol,
                                                         gint x_root,
                                                         gint y_root,
                                                         GdkDragAction suggested_action,
                                                         GdkDragAction possible_actions,
                                                         guint32 time_);

Updates the drag context when the pointer moves or the set of actions changes.

This function is called by the drag source.

context : | a GdkDragContext.
dest_window : | the new destination window, obtained by gdk_drag_find_window().
protocol : | the DND protocol in use, obtained by gdk_drag_find_window().
x_root : | the x position of the pointer in root coordinates.
y_root : | the y position of the pointer in root coordinates.
suggested_action : | the suggested action.
possible_actions : | the possible actions.
time_ : | the timestamp for this operation.
Returns : | FIXME

gdk_drop_finish ()

void                gdk_drop_finish                     (GdkDragContext *context,
                                                         gboolean success,
                                                         guint32 time_);

Ends the drag operation after a drop.

This function is called by the drag destination.

context : | a GtkDragContext.
success : | TRUE if the data was successfully received.
time_ : | the timestamp for this operation.

gdk_drag_get_protocol ()

guint32             gdk_drag_get_protocol               (guint32 xid,
                                                         GdkDragProtocol *protocol);

Finds out the DND protocol supported by a window.

xid : | the X id of the destination window.
protocol : | location where the supported DND protocol is returned.
Returns : | the X id of the window where the drop should happen. This may be xid or the X id of a proxy window, or None if xid doesn't support Drag and Drop.

gdk_drag_get_protocol_for_display ()

guint32             gdk_drag_get_protocol_for_display   (GdkDisplay *display,
                                                         guint32 xid,
                                                         GdkDragProtocol *protocol);

Finds out the DND protocol supported by a window.

display : | the GdkDisplay where the destination window resides
xid : | the X id of the destination window.
protocol : | location where the supported DND protocol is returned.
Returns : | the X id of the window where the drop should happen. This may be xid or the X id of a proxy window, or None if xid doesn't support Drag and Drop.

Since 2.2

enum GdkDragProtocol

typedef enum
{
  GDK_DRAG_PROTO_MOTIF,
  GDK_DRAG_PROTO_XDND,
  GDK_DRAG_PROTO_ROOTWIN,	  /* A root window with nobody claiming
                   * drags */
  GDK_DRAG_PROTO_NONE,		  /* Not a valid drag window */
  GDK_DRAG_PROTO_WIN32_DROPFILES, /* The simple WM_DROPFILES dnd */
  GDK_DRAG_PROTO_OLE2,		  /* The complex OLE2 dnd (not implemented) */
  GDK_DRAG_PROTO_LOCAL            /* Intra-app */
} GdkDragProtocol;

Used in GdkDragContext to indicate the protocol according to which DND is done.

GDK_DRAG_PROTO_MOTIF | The Motif DND protocol.
GDK_DRAG_PROTO_XDND | The Xdnd protocol.
GDK_DRAG_PROTO_ROOTWIN | An extension to the Xdnd protocol for unclaimed root window drops.
GDK_DRAG_PROTO_NONE | no protocol.
GDK_DRAG_PROTO_WIN32_DROPFILES | The simple WM_DROPFILES protocol.
GDK_DRAG_PROTO_OLE2 | The complex OLE2 DND protocol (not implemented).
GDK_DRAG_PROTO_LOCAL | Intra-application DND.

gdk_drag_context_unref ()

void                gdk_drag_context_unref              (GdkDragContext *context);

Warning

gdk_drag_context_unref is deprecated and should not be used in newly-written code.

Deprecated function; use g_object_unref() instead.

context : a GdkDragContext.

GdkDragContext

typedef struct {
  GObject parent_instance;

  GdkDragProtocol protocol;

  gboolean is_source;

  GdkWindow *source_window;
  GdkWindow *dest_window;

  GList *targets;
  GdkDragAction actions;
  GdkDragAction suggested_action;
  GdkDragAction action;

  guint32 start_time;
} GdkDragContext;

A GdkDragContext holds information about a drag in progress. It is used on both source and destination sides.

GObject parent_instance; | the parent instance
GdkDragProtocol protocol; | the DND protocol which governs this drag.
gboolean is_source; | TRUE if the context is used on the source side.
GdkWindow *source_window; | the source of this drag.
GdkWindow *dest_window; | the destination window of this drag.
GList *targets; | a list of targets offered by the source.
GdkDragAction actions; | a bitmask of actions proposed by the source when suggested_action is GDK_ACTION_ASK.
GdkDragAction suggested_action; | the action suggested by the source.
GdkDragAction action; | the action chosen by the destination.
guint32 start_time; | a timestamp recording the start time of this drag.

enum GdkDragAction

typedef enum
{
  GDK_ACTION_DEFAULT = 1 << 0,
  GDK_ACTION_COPY    = 1 << 1,
  GDK_ACTION_MOVE    = 1 << 2,
  GDK_ACTION_LINK    = 1 << 3,
  GDK_ACTION_PRIVATE = 1 << 4,
  GDK_ACTION_ASK     = 1 << 5
} GdkDragAction;

Used in GdkDragContext to indicate what the destination should do with the dropped data.

GDK_ACTION_DEFAULT | Means nothing, and should not be used.
GDK_ACTION_COPY | Copy the data.
GDK_ACTION_MOVE | Move the data, i.e. first copy it, then delete it from the source using the DELETE target of the X selection protocol.
GDK_ACTION_LINK | Add a link to the data. Note that this is only useful if source and destination agree on what it means.
GDK_ACTION_PRIVATE | Special action which tells the source that the destination will do something that the source doesn't understand.
GDK_ACTION_ASK | Ask the user what to do with the data.

gdk_drag_status ()

void                gdk_drag_status                     (GdkDragContext *context,
                                                         GdkDragAction action,
                                                         guint32 time_);

Selects one of the actions offered by the drag source.

This function is called by the drag destination in response to gdk_drag_motion() called by the drag source.

context : | a GdkDragContext.
action : | the selected action which will be taken when a drop happens, or 0 to indicate that a drop will not be accepted.
time_ : | the timestamp for this operation.

gdk_drag_drop_succeeded ()

gboolean            gdk_drag_drop_succeeded             (GdkDragContext *context);

Returns wether the dropped data has been successfully transferred. This function is intended to be used while handling a GDK_DROP_FINISHED event, its return value is meaningless at other times.

context : | a GdkDragContext
Returns : | TRUE if the drop was successful.

Since 2.6


Drawing Primitives

Drawing Primitives — Functions for drawing points, lines, arcs, and text

Synopsis

#include <gdk/gdk.h>

                    GdkDrawable;
GdkDrawable*        gdk_drawable_ref                    (GdkDrawable *drawable);
void                gdk_drawable_unref                  (GdkDrawable *drawable);
void                gdk_drawable_set_data               (GdkDrawable *drawable,
                                                         const gchar *key,
                                                         gpointer data,
                                                         GDestroyNotify destroy_func);
gpointer            gdk_drawable_get_data               (GdkDrawable *drawable,
                                                         const gchar *key);
GdkDisplay*         gdk_drawable_get_display            (GdkDrawable *drawable);
GdkScreen*          gdk_drawable_get_screen             (GdkDrawable *drawable);
GdkVisual*          gdk_drawable_get_visual             (GdkDrawable *drawable);
void                gdk_drawable_set_colormap           (GdkDrawable *drawable,
                                                         GdkColormap *colormap);
GdkColormap*        gdk_drawable_get_colormap           (GdkDrawable *drawable);
gint                gdk_drawable_get_depth              (GdkDrawable *drawable);
void                gdk_drawable_get_size               (GdkDrawable *drawable,
                                                         gint *width,
                                                         gint *height);
GdkRegion*          gdk_drawable_get_clip_region        (GdkDrawable *drawable);
GdkRegion*          gdk_drawable_get_visible_region     (GdkDrawable *drawable);

void                gdk_draw_point                      (GdkDrawable *drawable,
                                                         GdkGC *gc,
                                                         gint x,
                                                         gint y);
void                gdk_draw_points                     (GdkDrawable *drawable,
                                                         GdkGC *gc,
                                                         GdkPoint *points,
                                                         gint npoints);
void                gdk_draw_line                       (GdkDrawable *drawable,
                                                         GdkGC *gc,
                                                         gint x1_,
                                                         gint y1_,
                                                         gint x2_,
                                                         gint y2_);
void                gdk_draw_lines                      (GdkDrawable *drawable,
                                                         GdkGC *gc,
                                                         GdkPoint *points,
                                                         gint npoints);
void                gdk_draw_pixbuf                     (GdkDrawable *drawable,
                                                         GdkGC *gc,
                                                         GdkPixbuf *pixbuf,
                                                         gint src_x,
                                                         gint src_y,
                                                         gint dest_x,
                                                         gint dest_y,
                                                         gint width,
                                                         gint height,
                                                         GdkRgbDither dither,
                                                         gint x_dither,
                                                         gint y_dither);
void                gdk_draw_segments                   (GdkDrawable *drawable,
                                                         GdkGC *gc,
                                                         GdkSegment *segs,
                                                         gint nsegs);
                    GdkSegment;
void                gdk_draw_rectangle                  (GdkDrawable *drawable,
                                                         GdkGC *gc,
                                                         gboolean filled,
                                                         gint x,
                                                         gint y,
                                                         gint width,
                                                         gint height);
void                gdk_draw_arc                        (GdkDrawable *drawable,
                                                         GdkGC *gc,
                                                         gboolean filled,
                                                         gint x,
                                                         gint y,
                                                         gint width,
                                                         gint height,
                                                         gint angle1,
                                                         gint angle2);
void                gdk_draw_polygon                    (GdkDrawable *drawable,
                                                         GdkGC *gc,
                                                         gboolean filled,
                                                         GdkPoint *points,
                                                         gint npoints);
void                gdk_draw_trapezoids                 (GdkDrawable *drawable,
                                                         GdkGC *gc,
                                                         GdkTrapezoid *trapezoids,
                                                         gint n_trapezoids);
                    GdkTrapezoid;
void                gdk_draw_glyphs                     (GdkDrawable *drawable,
                                                         GdkGC *gc,
                                                         PangoFont *font,
                                                         gint x,
                                                         gint y,
                                                         PangoGlyphString *glyphs);
void                gdk_draw_glyphs_transformed         (GdkDrawable *drawable,
                                                         GdkGC *gc,
                                                         PangoMatrix *matrix,
                                                         PangoFont *font,
                                                         gint x,
                                                         gint y,
                                                         PangoGlyphString *glyphs);
void                gdk_draw_layout_line                (GdkDrawable *drawable,
                                                         GdkGC *gc,
                                                         gint x,
                                                         gint y,
                                                         PangoLayoutLine *line);
void                gdk_draw_layout_line_with_colors    (GdkDrawable *drawable,
                                                         GdkGC *gc,
                                                         gint x,
                                                         gint y,
                                                         PangoLayoutLine *line,
                                                         const GdkColor *foreground,
                                                         const GdkColor *background);
void                gdk_draw_layout                     (GdkDrawable *drawable,
                                                         GdkGC *gc,
                                                         gint x,
                                                         gint y,
                                                         PangoLayout *layout);
void                gdk_draw_layout_with_colors         (GdkDrawable *drawable,
                                                         GdkGC *gc,
                                                         gint x,
                                                         gint y,
                                                         PangoLayout *layout,
                                                         const GdkColor *foreground,
                                                         const GdkColor *background);

void                gdk_draw_string                     (GdkDrawable *drawable,
                                                         GdkFont *font,
                                                         GdkGC *gc,
                                                         gint x,
                                                         gint y,
                                                         const gchar *string);
void                gdk_draw_text                       (GdkDrawable *drawable,
                                                         GdkFont *font,
                                                         GdkGC *gc,
                                                         gint x,
                                                         gint y,
                                                         const gchar *text,
                                                         gint text_length);
void                gdk_draw_text_wc                    (GdkDrawable *drawable,
                                                         GdkFont *font,
                                                         GdkGC *gc,
                                                         gint x,
                                                         gint y,
                                                         const GdkWChar *text,
                                                         gint text_length);

#define             gdk_draw_pixmap
void                gdk_draw_drawable                   (GdkDrawable *drawable,
                                                         GdkGC *gc,
                                                         GdkDrawable *src,
                                                         gint xsrc,
                                                         gint ysrc,
                                                         gint xdest,
                                                         gint ydest,
                                                         gint width,
                                                         gint height);
void                gdk_draw_image                      (GdkDrawable *drawable,
                                                         GdkGC *gc,
                                                         GdkImage *image,
                                                         gint xsrc,
                                                         gint ysrc,
                                                         gint xdest,
                                                         gint ydest,
                                                         gint width,
                                                         gint height);
GdkImage*           gdk_drawable_get_image              (GdkDrawable *drawable,
                                                         gint x,
                                                         gint y,
                                                         gint width,
                                                         gint height);
GdkImage*           gdk_drawable_copy_to_image          (GdkDrawable *drawable,
                                                         GdkImage *image,
                                                         gint src_x,
                                                         gint src_y,
                                                         gint dest_x,
                                                         gint dest_y,
                                                         gint width,
                                                         gint height);

Object Hierarchy

  GObject
   +----GdkDrawable
         +----GdkWindow
         +----GdkPixmap

Description

These functions provide support for drawing points, lines, arcs and text onto what are called 'drawables'. Drawables, as the name suggests, are things which support drawing onto them, and are either GdkWindow or GdkPixmap objects.

Many of the drawing operations take a GdkGC argument, which represents a graphics context. This GdkGC contains a number of drawing attributes such as foreground color, background color and line width, and is used to reduce the number of arguments needed for each drawing operation. See the Graphics Contexts section for more information.

Some of the drawing operations take Pango data structures like PangoContext, PangoLayout or PangoLayoutLine as arguments. If you're using GTK+, the ususal way to obtain these structures is via gtk_widget_create_pango_context() or gtk_widget_create_pango_layout().

Details

GdkDrawable

typedef struct _GdkDrawable GdkDrawable;

An opaque structure representing an object that can be drawn onto. This can be a GdkPixmap, a GdkBitmap, or a GdkWindow.

gdk_drawable_ref ()

GdkDrawable*        gdk_drawable_ref                    (GdkDrawable *drawable);

Warning

gdk_drawable_ref is deprecated and should not be used in newly-written code.

Deprecated equivalent of calling g_object_ref() on drawable. (Drawables were not objects in previous versions of GDK.)

drawable : | a GdkDrawable
Returns : | the same drawable passed in

gdk_drawable_unref ()

void                gdk_drawable_unref                  (GdkDrawable *drawable);

Warning

gdk_drawable_unref is deprecated and should not be used in newly-written code.

Deprecated equivalent of calling g_object_unref() on drawable.

drawable : a GdkDrawable

gdk_drawable_set_data ()

void                gdk_drawable_set_data               (GdkDrawable *drawable,
                                                         const gchar *key,
                                                         gpointer data,
                                                         GDestroyNotify destroy_func);

Warning

gdk_drawable_set_data is deprecated and should not be used in newly-written code.

This function is equivalent to g_object_set_data(), the GObject variant should be used instead.

drawable : | a GdkDrawable
key : | name to store the data under
data : | arbitrary data
destroy_func : | function to free data, or NULL

gdk_drawable_get_data ()

gpointer            gdk_drawable_get_data               (GdkDrawable *drawable,
                                                         const gchar *key);

Warning

gdk_drawable_get_data is deprecated and should not be used in newly-written code.

Equivalent to g_object_get_data(); the GObject variant should be used instead.

drawable : | a GdkDrawable
key : | name the data was stored under
Returns : | the data stored at key

gdk_drawable_get_display ()

GdkDisplay*         gdk_drawable_get_display            (GdkDrawable *drawable);

Gets the GdkDisplay associated with a GdkDrawable.

drawable : | a GdkDrawable
Returns : | the GdkDisplay associated with drawable

Since 2.2

gdk_drawable_get_screen ()

GdkScreen*          gdk_drawable_get_screen             (GdkDrawable *drawable);

Gets the GdkScreen associated with a GdkDrawable.

drawable : | a GdkDrawable
Returns : | the GdkScreen associated with drawable

Since 2.2

gdk_drawable_get_visual ()

GdkVisual*          gdk_drawable_get_visual             (GdkDrawable *drawable);

Gets the GdkVisual describing the pixel format of drawable.

drawable : | a GdkDrawable
Returns : | a GdkVisual

gdk_drawable_set_colormap ()

void                gdk_drawable_set_colormap           (GdkDrawable *drawable,
                                                         GdkColormap *colormap);

Sets the colormap associated with drawable. Normally this will happen automatically when the drawable is created; you only need to use this function if the drawable-creating function did not have a way to determine the colormap, and you then use drawable operations that require a colormap. The colormap for all drawables and graphics contexts you intend to use together should match. i.e. when using a GdkGC to draw to a drawable, or copying one drawable to another, the colormaps should match.

drawable : | a GdkDrawable
colormap : | a GdkColormap

gdk_drawable_get_colormap ()

GdkColormap*        gdk_drawable_get_colormap           (GdkDrawable *drawable);

Gets the colormap for drawable, if one is set; returns NULL otherwise.

drawable : | a GdkDrawable
Returns : | the colormap, or NULL

gdk_drawable_get_depth ()

gint                gdk_drawable_get_depth              (GdkDrawable *drawable);

Obtains the bit depth of the drawable, that is, the number of bits that make up a pixel in the drawable's visual. Examples are 8 bits per pixel, 24 bits per pixel, etc.

drawable : | a GdkDrawable
Returns : | number of bits per pixel

gdk_drawable_get_size ()

void                gdk_drawable_get_size               (GdkDrawable *drawable,
                                                         gint *width,
                                                         gint *height);

Fills *width and *height with the size of drawable. width or height can be NULL if you only want the other one.

On the X11 platform, if drawable is a GdkWindow, the returned size is the size reported in the most-recently-processed configure event, rather than the current size on the X server.

drawable : | a GdkDrawable
width : | location to store drawable's width, or NULL
height : | location to store drawable's height, or NULL

gdk_drawable_get_clip_region ()

GdkRegion*          gdk_drawable_get_clip_region        (GdkDrawable *drawable);

Computes the region of a drawable that potentially can be written to by drawing primitives. This region will not take into account the clip region for the GC, and may also not take into account other factors such as if the window is obscured by other windows, but no area outside of this region will be affected by drawing primitives.

drawable : | a GdkDrawable
Returns : | a GdkRegion. This must be freed with gdk_region_destroy() when you are done.

gdk_drawable_get_visible_region ()

GdkRegion*          gdk_drawable_get_visible_region     (GdkDrawable *drawable);

Computes the region of a drawable that is potentially visible. This does not necessarily take into account if the window is obscured by other windows, but no area outside of this region is visible.

drawable : | a GdkDrawable
Returns : | a GdkRegion. This must be freed with gdk_region_destroy() when you are done.

gdk_draw_point ()

void                gdk_draw_point                      (GdkDrawable *drawable,
                                                         GdkGC *gc,
                                                         gint x,
                                                         gint y);

Draws a point, using the foreground color and other attributes of the GdkGC.

drawable : | a GdkDrawable (a GdkWindow or a GdkPixmap).
gc : | a GdkGC.
x : | the x coordinate of the point.
y : | the y coordinate of the point.

gdk_draw_points ()

void                gdk_draw_points                     (GdkDrawable *drawable,
                                                         GdkGC *gc,
                                                         GdkPoint *points,
                                                         gint npoints);

Draws a number of points, using the foreground color and other attributes of the GdkGC.

drawable : | a GdkDrawable (a GdkWindow or a GdkPixmap).
gc : | a GdkGC.
points : | an array of GdkPoint structures.
npoints : | the number of points to be drawn.

gdk_draw_line ()

void                gdk_draw_line                       (GdkDrawable *drawable,
                                                         GdkGC *gc,
                                                         gint x1_,
                                                         gint y1_,
                                                         gint x2_,
                                                         gint y2_);

Draws a line, using the foreground color and other attributes of the GdkGC.

drawable : | a GdkDrawable (a GdkWindow or a GdkPixmap).
gc : | a GdkGC.
x1_ : | the x coordinate of the start point.
y1_ : | the y coordinate of the start point.
x2_ : | the x coordinate of the end point.
y2_ : | the y coordinate of the end point.

gdk_draw_lines ()

void                gdk_draw_lines                      (GdkDrawable *drawable,
                                                         GdkGC *gc,
                                                         GdkPoint *points,
                                                         gint npoints);

Draws a series of lines connecting the given points. The way in which joins between lines are draw is determined by the GdkCapStyle value in the GdkGC. This can be set with gdk_gc_set_line_attributes().

drawable : | a GdkDrawable (a GdkWindow or a GdkPixmap).
gc : | a GdkGC.
points : | an array of GdkPoint structures specifying the endpoints of the
npoints : | the size of the points array.

gdk_draw_pixbuf ()

void                gdk_draw_pixbuf                     (GdkDrawable *drawable,
                                                         GdkGC *gc,
                                                         GdkPixbuf *pixbuf,
                                                         gint src_x,
                                                         gint src_y,
                                                         gint dest_x,
                                                         gint dest_y,
                                                         gint width,
                                                         gint height,
                                                         GdkRgbDither dither,
                                                         gint x_dither,
                                                         gint y_dither);

Renders a rectangular portion of a pixbuf to a drawable. The destination drawable must have a colormap. All windows have a colormap, however, pixmaps only have colormap by default if they were created with a non-NULL window argument. Otherwise a colormap must be set on them with gdk_drawable_set_colormap().

On older X servers, rendering pixbufs with an alpha channel involves round trips to the X server, and may be somewhat slow.

The clip mask of gc is ignored, but clip rectangles and clip regions work fine.

drawable : | Destination drawable.
gc : | a GdkGC, used for clipping, or NULL
pixbuf : | a GdkPixbuf
src_x : | Source X coordinate within pixbuf.
src_y : | Source Y coordinates within pixbuf.
dest_x : | Destination X coordinate within drawable.
dest_y : | Destination Y coordinate within drawable.
width : | Width of region to render, in pixels, or -1 to use pixbuf width.
height : | Height of region to render, in pixels, or -1 to use pixbuf height.
dither : | Dithering mode for GdkRGB.
x_dither : | X offset for dither.
y_dither : | Y offset for dither.

Since 2.2

gdk_draw_segments ()

void                gdk_draw_segments                   (GdkDrawable *drawable,
                                                         GdkGC *gc,
                                                         GdkSegment *segs,
                                                         gint nsegs);

Draws a number of unconnected lines.

drawable : | a GdkDrawable (a GdkWindow or a GdkPixmap).
gc : | a GdkGC.
segs : | an array of GdkSegment structures specifying the start and end points of the lines to be drawn.
nsegs : | the number of line segments to draw, i.e. the size of the segs array.

GdkSegment

typedef struct {
  gint x1;
  gint y1;
  gint x2;
  gint y2;
} GdkSegment;

Specifies the start and end point of a line for use by the gdk_draw_segments() function.

gint x1; | the x coordinate of the start point.
gint y1; | the y coordinate of the start point.
gint x2; | the x coordinate of the end point.
gint y2; | the y coordinate of the end point.

gdk_draw_rectangle ()

void                gdk_draw_rectangle                  (GdkDrawable *drawable,
                                                         GdkGC *gc,
                                                         gboolean filled,
                                                         gint x,
                                                         gint y,
                                                         gint width,
                                                         gint height);

Draws a rectangular outline or filled rectangle, using the foreground color and other attributes of the GdkGC.

A rectangle drawn filled is 1 pixel smaller in both dimensions than a rectangle outlined. Calling gdk_draw_rectangle (window, gc, TRUE, 0, 0, 20, 20) results in a filled rectangle 20 pixels wide and 20 pixels high. Calling gdk_draw_rectangle (window, gc, FALSE, 0, 0, 20, 20) results in an outlined rectangle with corners at (0, 0), (0, 20), (20, 20), and (20, 0), which makes it 21 pixels wide and 21 pixels high.

Note

drawable : | a GdkDrawable (a GdkWindow or a GdkPixmap).
gc : | a GdkGC.
filled : | TRUE if the rectangle should be filled.
x : | the x coordinate of the left edge of the rectangle.
y : | the y coordinate of the top edge of the rectangle.
width : | the width of the rectangle.
height : | the height of the rectangle.

gdk_draw_arc ()

void                gdk_draw_arc                        (GdkDrawable *drawable,
                                                         GdkGC *gc,
                                                         gboolean filled,
                                                         gint x,
                                                         gint y,
                                                         gint width,
                                                         gint height,
                                                         gint angle1,
                                                         gint angle2);

Draws an arc or a filled 'pie slice'. The arc is defined by the bounding rectangle of the entire ellipse, and the start and end angles of the part of the ellipse to be drawn.

drawable : | a GdkDrawable (a GdkWindow or a GdkPixmap).
gc : | a GdkGC.
filled : | TRUE if the arc should be filled, producing a 'pie slice'.
x : | the x coordinate of the left edge of the bounding rectangle.
y : | the y coordinate of the top edge of the bounding rectangle.
width : | the width of the bounding rectangle.
height : | the height of the bounding rectangle.
angle1 : | the start angle of the arc, relative to the 3 o'clock position, counter-clockwise, in 1/64ths of a degree.
angle2 : | the end angle of the arc, relative to angle1, in 1/64ths of a degree.

gdk_draw_polygon ()

void                gdk_draw_polygon                    (GdkDrawable *drawable,
                                                         GdkGC *gc,
                                                         gboolean filled,
                                                         GdkPoint *points,
                                                         gint npoints);

Draws an outlined or filled polygon.

drawable : | a GdkDrawable (a GdkWindow or a GdkPixmap).
gc : | a GdkGC.
filled : | TRUE if the polygon should be filled. The polygon is closed automatically, connecting the last point to the first point if necessary.
points : | an array of GdkPoint structures specifying the points making up the polygon.
npoints : | the number of points.

gdk_draw_trapezoids ()

void                gdk_draw_trapezoids                 (GdkDrawable *drawable,
                                                         GdkGC *gc,
                                                         GdkTrapezoid *trapezoids,
                                                         gint n_trapezoids);

Draws a set of anti-aliased trapezoids. The trapezoids are combined using saturation addition, then drawn over the background as a set. This is low level functionality used internally to implement rotated underlines and backgrouds when rendering a PangoLayout and is likely not useful for applications.

drawable : | a GdkDrawable
gc : | a GdkGC
trapezoids : | an array of GdkTrapezoid structures
n_trapezoids : | the number of trapezoids to draw

Since 2.6

GdkTrapezoid

typedef struct {
  double y1, x11, x21, y2, x12, x22;
} GdkTrapezoid;

Specifies a trapezpoid for use by the gdk_draw_trapezoids(). The trapezoids used here have parallel, horizontal top and bottom edges.

double y1; | the y coordinate of the start point.
double x11; | the x coordinate of the top left corner
double x21; | the x coordinate of the top right corner
double y2; | the y coordinate of the end point.
double x12; | the x coordinate of the bottom left corner
double x22; | the x coordinate of the bottom right corner

gdk_draw_glyphs ()

void                gdk_draw_glyphs                     (GdkDrawable *drawable,
                                                         GdkGC *gc,
                                                         PangoFont *font,
                                                         gint x,
                                                         gint y,
                                                         PangoGlyphString *glyphs);

This is a low-level function; 99% of text rendering should be done using gdk_draw_layout() instead.

A glyph is a single image in a font. This function draws a sequence of glyphs. To obtain a sequence of glyphs you have to understand a lot about internationalized text handling, which you don't want to understand; thus, use gdk_draw_layout() instead of this function, gdk_draw_layout() handles the details.

drawable : | a GdkDrawable
gc : | a GdkGC
font : | font to be used
x : | X coordinate of baseline origin
y : | Y coordinate of baseline origin
glyphs : | the glyph string to draw

gdk_draw_glyphs_transformed ()

void                gdk_draw_glyphs_transformed         (GdkDrawable *drawable,
                                                         GdkGC *gc,
                                                         PangoMatrix *matrix,
                                                         PangoFont *font,
                                                         gint x,
                                                         gint y,
                                                         PangoGlyphString *glyphs);

Renders a PangoGlyphString onto a drawable, possibly transforming the layed-out coordinates through a transformation matrix. Note that the transformation matrix for font is not changed, so to produce correct rendering results, the font must have been loaded using a PangoContext with an identical transformation matrix to that passed in to this function.

See also gdk_draw_glyphs(), gdk_draw_layout().

drawable : | a GdkDrawable
gc : | a GdkGC
matrix : | a PangoMatrix, or NULL to use an identity transformation
font : | the font in which to draw the string
x : | the x position of the start of the string (in Pango units in user space coordinates)
y : | the y position of the baseline (in Pango units in user space coordinates)
glyphs : | the glyph string to draw

Since 2.6

gdk_draw_layout_line ()

void                gdk_draw_layout_line                (GdkDrawable *drawable,
                                                         GdkGC *gc,
                                                         gint x,
                                                         gint y,
                                                         PangoLayoutLine *line);

Render a PangoLayoutLine onto an GDK drawable

If the layout's PangoContext has a transformation matrix set, then x and y specify the position of the left edge of the baseline (left is in before-tranform user coordinates) in after-transform device coordinates.

drawable : | the drawable on which to draw the line
gc : | base graphics to use
x : | the x position of start of string (in pixels)
y : | the y position of baseline (in pixels)
line : | a PangoLayoutLine

gdk_draw_layout_line_with_colors ()

void                gdk_draw_layout_line_with_colors    (GdkDrawable *drawable,
                                                         GdkGC *gc,
                                                         gint x,
                                                         gint y,
                                                         PangoLayoutLine *line,
                                                         const GdkColor *foreground,
                                                         const GdkColor *background);

Render a PangoLayoutLine onto a GdkDrawable, overriding the layout's normal colors with foreground and/or background. foreground and background need not be allocated.

If the layout's PangoContext has a transformation matrix set, then x and y specify the position of the left edge of the baseline (left is in before-tranform user coordinates) in after-transform device coordinates.

drawable : | the drawable on which to draw the line
gc : | base graphics to use
x : | the x position of start of string (in pixels)
y : | the y position of baseline (in pixels)
line : | a PangoLayoutLine
foreground : | foreground override color, or NULL for none
background : | background override color, or NULL for none

gdk_draw_layout ()

void                gdk_draw_layout                     (GdkDrawable *drawable,
                                                         GdkGC *gc,
                                                         gint x,
                                                         gint y,
                                                         PangoLayout *layout);

Render a PangoLayout onto a GDK drawable

If the layout's PangoContext has a transformation matrix set, then x and y specify the position of the top left corner of the bounding box (in device space) of the transformed layout.

If you're using GTK+, the usual way to obtain a PangoLayout is gtk_widget_create_pango_layout().

drawable : | the drawable on which to draw string
gc : | base graphics context to use
x : | the X position of the left of the layout (in pixels)
y : | the Y position of the top of the layout (in pixels)
layout : | a PangoLayout

gdk_draw_layout_with_colors ()

void                gdk_draw_layout_with_colors         (GdkDrawable *drawable,
                                                         GdkGC *gc,
                                                         gint x,
                                                         gint y,
                                                         PangoLayout *layout,
                                                         const GdkColor *foreground,
                                                         const GdkColor *background);

Render a PangoLayout onto a GdkDrawable, overriding the layout's normal colors with foreground and/or background. foreground and background need not be allocated.

If the layout's PangoContext has a transformation matrix set, then x and y specify the position of the top left corner of the bounding box (in device space) of the transformed layout.

If you're using GTK+, the ususal way to obtain a PangoLayout is gtk_widget_create_pango_layout().

drawable : | the drawable on which to draw string
gc : | base graphics context to use
x : | the X position of the left of the layout (in pixels)
y : | the Y position of the top of the layout (in pixels)
layout : | a PangoLayout
foreground : | foreground override color, or NULL for none
background : | background override color, or NULL for none

gdk_draw_string ()

void                gdk_draw_string                     (GdkDrawable *drawable,
                                                         GdkFont *font,
                                                         GdkGC *gc,
                                                         gint x,
                                                         gint y,
                                                         const gchar *string);

Warning

gdk_draw_string is deprecated and should not be used in newly-written code. Use gdk_draw_layout() instead.

Draws a string of characters in the given font or fontset.

drawable : | a GdkDrawable (a GdkWindow or a GdkPixmap).
font : | a GdkFont.
gc : | a GdkGC.
x : | the x coordinate of the left edge of the text.
y : | the y coordinate of the baseline of the text.
string : | the string of characters to draw.

gdk_draw_text ()

void                gdk_draw_text                       (GdkDrawable *drawable,
                                                         GdkFont *font,
                                                         GdkGC *gc,
                                                         gint x,
                                                         gint y,
                                                         const gchar *text,
                                                         gint text_length);

Warning

gdk_draw_text is deprecated and should not be used in newly-written code. Use gdk_draw_layout() instead.

Draws a number of characters in the given font or fontset.

drawable : | a GdkDrawable (a GdkWindow or a GdkPixmap).
font : | a GdkFont.
gc : | a GdkGC.
x : | the x coordinate of the left edge of the text.
y : | the y coordinate of the baseline of the text.
text : | the characters to draw.
text_length : | the number of characters of text to draw.

gdk_draw_text_wc ()

void                gdk_draw_text_wc                    (GdkDrawable *drawable,
                                                         GdkFont *font,
                                                         GdkGC *gc,
                                                         gint x,
                                                         gint y,
                                                         const GdkWChar *text,
                                                         gint text_length);

Warning

gdk_draw_text_wc is deprecated and should not be used in newly-written code. Use gdk_draw_layout() instead.

Draws a number of wide characters using the given font of fontset. If the font is a 1-byte font, the string is converted into 1-byte characters (discarding the high bytes) before output.

drawable : | a GdkDrawable (a GdkWindow or a GdkPixmap).
font : | a GdkFont.
gc : | a GdkGC.
x : | the x coordinate of the left edge of the text.
y : | the y coordinate of the baseline of the text.
text : | the wide characters to draw.
text_length : | the number of characters to draw.

gdk_draw_pixmap

#define gdk_draw_pixmap                gdk_draw_drawable

Warning

gdk_draw_pixmap is deprecated and should not be used in newly-written code. Use gdk_draw_drawable() instead.

Draws a pixmap, or a part of a pixmap, onto another drawable.

gdk_draw_drawable ()

void                gdk_draw_drawable                   (GdkDrawable *drawable,
                                                         GdkGC *gc,
                                                         GdkDrawable *src,
                                                         gint xsrc,
                                                         gint ysrc,
                                                         gint xdest,
                                                         gint ydest,
                                                         gint width,
                                                         gint height);

Copies the width x height region of src at coordinates (xsrc, ysrc) to coordinates (xdest, ydest) in drawable. width and/or height may be given as -1, in which case the entire src drawable will be copied.

Most fields in gc are not used for this operation, but notably the clip mask or clip region will be honored.

The source and destination drawables must have the same visual and colormap, or errors will result. (On X11, failure to match visual/colormap results in a BadMatch error from the X server.) A common cause of this problem is an attempt to draw a bitmap to a color drawable. The way to draw a bitmap is to set the bitmap as the stipple on the GdkGC, set the fill mode to GDK_STIPPLED, and then draw the rectangle.

drawable : | a GdkDrawable
gc : | a GdkGC sharing the drawable's visual and colormap
src : | the source GdkDrawable, which may be the same as drawable
xsrc : | X position in src of rectangle to draw
ysrc : | Y position in src of rectangle to draw
xdest : | X position in drawable where the rectangle should be drawn
ydest : | Y position in drawable where the rectangle should be drawn
width : | width of rectangle to draw, or -1 for entire src width
height : | height of rectangle to draw, or -1 for entire src height

gdk_draw_image ()

void                gdk_draw_image                      (GdkDrawable *drawable,
                                                         GdkGC *gc,
                                                         GdkImage *image,
                                                         gint xsrc,
                                                         gint ysrc,
                                                         gint xdest,
                                                         gint ydest,
                                                         gint width,
                                                         gint height);

Draws a GdkImage onto a drawable. The depth of the GdkImage must match the depth of the GdkDrawable.

drawable : | a GdkDrawable (a GdkWindow or a GdkPixmap).
gc : | a GdkGC.
image : | the GdkImage to draw.
xsrc : | the left edge of the source rectangle within image.
ysrc : | the top of the source rectangle within image.
xdest : | the x coordinate of the destination within drawable.
ydest : | the y coordinate of the destination within drawable.
width : | the width of the area to be copied, or -1 to make the area extend to the right edge of image.
height : | the height of the area to be copied, or -1 to make the area extend to the bottom edge of image.

gdk_drawable_get_image ()

GdkImage*           gdk_drawable_get_image              (GdkDrawable *drawable,
                                                         gint x,
                                                         gint y,
                                                         gint width,
                                                         gint height);

A GdkImage stores client-side image data (pixels). In contrast, GdkPixmap and GdkWindow are server-side objects. gdk_drawable_get_image() obtains the pixels from a server-side drawable as a client-side GdkImage. The format of a GdkImage depends on the GdkVisual of the current display, which makes manipulating GdkImage extremely difficult; therefore, in most cases you should use gdk_pixbuf_get_from_drawable() instead of this lower-level function. A GdkPixbuf contains image data in a canonicalized RGB format, rather than a display-dependent format. Of course, there's a convenience vs. speed tradeoff here, so you'll want to think about what makes sense for your application.

x, y, width, and height define the region of drawable to obtain as an image.

You would usually copy image data to the client side if you intend to examine the values of individual pixels, for example to darken an image or add a red tint. It would be prohibitively slow to make a round-trip request to the windowing system for each pixel, so instead you get all of them at once, modify them, then copy them all back at once.

If the X server or other windowing system backend is on the local machine, this function may use shared memory to avoid copying the image data.

If the source drawable is a GdkWindow and partially offscreen or obscured, then the obscured portions of the returned image will contain undefined data.

drawable : | a GdkDrawable
x : | x coordinate on drawable
y : | y coordinate on drawable
width : | width of region to get
height : | height or region to get
Returns : | a GdkImage containing the contents of drawable

gdk_drawable_copy_to_image ()

GdkImage*           gdk_drawable_copy_to_image          (GdkDrawable *drawable,
                                                         GdkImage *image,
                                                         gint src_x,
                                                         gint src_y,
                                                         gint dest_x,
                                                         gint dest_y,
                                                         gint width,
                                                         gint height);

Copies a portion of drawable into the client side image structure image. If image is NULL, creates a new image of size width x height and copies into that. See gdk_drawable_get_image() for further details.

drawable : | a GdkDrawable
image : | a GdkDrawable, or NULL if a new image should be created.
src_x : | x coordinate on drawable
src_y : | y coordinate on drawable
dest_x : | x coordinate within image. Must be 0 if image is NULL
dest_y : | y coordinate within image. Must be 0 if image is NULL
width : | width of region to get
height : | height or region to get
Returns : | image, or a new a GdkImage containing the contents of drawable

Since 2.4


Event Structures

Event Structures — Data structures specific to each type of event

Synopsis

#include <gdk/gdk.h>

union               GdkEvent;

                    GdkEventAny;
                    GdkEventKey;
                    GdkEventButton;
                    GdkEventScroll;
                    GdkEventMotion;
                    GdkEventExpose;
                    GdkEventVisibility;
                    GdkEventCrossing;
                    GdkEventFocus;
                    GdkEventConfigure;
                    GdkEventProperty;
                    GdkEventSelection;
typedef             GdkNativeWindow;
                    GdkEventDND;
                    GdkEventProximity;
                    GdkEventClient;
                    GdkEventNoExpose;
                    GdkEventWindowState;
                    GdkEventSetting;
                    GdkEventOwnerChange;
                    GdkEventGrabBroken;

enum                GdkScrollDirection;
enum                GdkVisibilityState;
enum                GdkCrossingMode;
enum                GdkNotifyType;
enum                GdkPropertyState;
enum                GdkWindowState;
enum                GdkSettingAction;
enum                GdkOwnerChange;

Description

The event structs contain data specific to each type of event in GDK.

Note

A common mistake is to forget to set the event mask of a widget so that the required events are received. See gtk_widget_set_events().

Details

union GdkEvent

union GdkEvent
{
  GdkEventType		    type;
  GdkEventAny		    any;
  GdkEventExpose	    expose;
  GdkEventNoExpose	    no_expose;
  GdkEventVisibility	    visibility;
  GdkEventMotion	    motion;
  GdkEventButton	    button;
  GdkEventScroll            scroll;
  GdkEventKey		    key;
  GdkEventCrossing	    crossing;
  GdkEventFocus		    focus_change;
  GdkEventConfigure	    configure;
  GdkEventProperty	    property;
  GdkEventSelection	    selection;
  GdkEventOwnerChange  	    owner_change;
  GdkEventProximity	    proximity;
  GdkEventClient	    client;
  GdkEventDND               dnd;
  GdkEventWindowState       window_state;
  GdkEventSetting           setting;
  GdkEventGrabBroken        grab_broken;
};

The GdkEvent struct contains a union of all of the event structs, and allows access to the data fields in a number of ways.

The event type is always the first field in all of the event structs, and can always be accessed with the following code, no matter what type of event it is:

  GdkEvent *event;
  GdkEventType type;

  type = event->type;

To access other fields of the event structs, the pointer to the event can be cast to the appropriate event struct pointer, or the union member name can be used. For example if the event type is GDK_BUTTON_PRESS then the x coordinate of the button press can be accessed with:

  GdkEvent *event;
  gdouble x;

  x = ((GdkEventButton*)event)->x;

or:

  GdkEvent *event;
  gdouble x;

  x = event->button.x;

GdkEventAny

typedef struct {
  GdkEventType type;
  GdkWindow *window;
  gint8 send_event;
} GdkEventAny;

Contains the fields which are common to all event structs. Any event pointer can safely be cast to a pointer to a GdkEventAny to access these fields.

GdkEventType type; | the type of the event.
GdkWindow *window; | the window which received the event.
gint8 send_event; | TRUE if the event was sent explicitly (e.g. using XSendEvent).

GdkEventKey

typedef struct {
  GdkEventType type;
  GdkWindow *window;
  gint8 send_event;
  guint32 time;
  guint state;
  guint keyval;
  gint length;
  gchar *string;
  guint16 hardware_keycode;
  guint8 group;
  guint is_modifier : 1;
} GdkEventKey;

Describes a key press or key release event.

GdkEventType type; | the type of the event (GDK_KEY_PRESS or GDK_KEY_RELEASE).
GdkWindow *window; | the window which received the event.
gint8 send_event; | TRUE if the event was sent explicitly (e.g. using XSendEvent).
guint32 time; | the time of the event in milliseconds.
guint state; | a bit-mask representing the state of the modifier keys (e.g. Control, Shift and Alt) and the pointer buttons. See GdkModifierType.
guint keyval; | the key that was pressed or released. See the <gdk/gdkkeysyms.h> header file for a complete list of GDK key codes.
gint length; | the length of string.
gchar *string; | a string containing the an approximation of the text that would result from this keypress. The only correct way to handle text input of text is using input methods (see GtkIMContext), so this field is deprecated and should never be used. (gdk_unicode_to_keyval() provides a non-deprecated way of getting an approximate translation for a key.) The string is encoded in the encoding of the current locale (Note: this for backwards compatibility: strings in GTK+ and GDK are typically in UTF-8.) and NUL-terminated. In some cases, the translation of the key code will be a single NUL byte, in which case looking at length is necessary to distinguish it from the an empty translation.
guint16 hardware_keycode; | the raw code of the key that was pressed or released.
guint8 group; | the keyboard group.
guint is_modifier : 1; | a flag that indicates if hardware_keycode is mapped to a modifier. Since 2.10

GdkEventButton

typedef struct {
  GdkEventType type;
  GdkWindow *window;
  gint8 send_event;
  guint32 time;
  gdouble x;
  gdouble y;
  gdouble *axes;
  guint state;
  guint button;
  GdkDevice *device;
  gdouble x_root, y_root;
} GdkEventButton;

Used for button press and button release events. The type field will be one of GDK_BUTTON_PRESS, GDK_2BUTTON_PRESS, GDK_3BUTTON_PRESS, and GDK_BUTTON_RELEASE.

Double and triple-clicks result in a sequence of events being received. For double-clicks the order of events will be:

  1. GDK_BUTTON_PRESS

  2. GDK_BUTTON_RELEASE

  3. GDK_BUTTON_PRESS

  4. GDK_2BUTTON_PRESS

  5. GDK_BUTTON_RELEASE

Note that the first click is received just like a normal button press, while the second click results in a GDK_2BUTTON_PRESS being received just after the GDK_BUTTON_PRESS.

Triple-clicks are very similar to double-clicks, except that GDK_3BUTTON_PRESS is inserted after the third click. The order of the events is:

  1. GDK_BUTTON_PRESS

  2. GDK_BUTTON_RELEASE

  3. GDK_BUTTON_PRESS

  4. GDK_2BUTTON_PRESS

  5. GDK_BUTTON_RELEASE

  6. GDK_BUTTON_PRESS

  7. GDK_3BUTTON_PRESS

  8. GDK_BUTTON_RELEASE

For a double click to occur, the second button press must occur within 1/4 of a second of the first. For a triple click to occur, the third button press must also occur within 1/2 second of the first button press.

GdkEventType type; | the type of the event (GDK_BUTTON_PRESS, GDK_2BUTTON_PRESS, GDK_3BUTTON_PRESS or GDK_BUTTON_RELEASE).
GdkWindow *window; | the window which received the event.
gint8 send_event; | TRUE if the event was sent explicitly (e.g. using XSendEvent).
guint32 time; | the time of the event in milliseconds.
gdouble x; | the x coordinate of the pointer relative to the window.
gdouble y; | the y coordinate of the pointer relative to the window.
gdouble *axes; | x, y translated to the axes of device, or NULL if device is the mouse.
guint state; | a bit-mask representing the state of the modifier keys (e.g. Control, Shift and Alt) and the pointer buttons. See GdkModifierType.
guint button; | the button which was pressed or released, numbered from 1 to 5. Normally button 1 is the left mouse button, 2 is the middle button, and 3 is the right button. On 2-button mice, the middle button can often be simulated by pressing both mouse buttons together.
GdkDevice *device; | the device where the event originated.
gdouble x_root; | the x coordinate of the pointer relative to the root of the screen.
gdouble y_root; | the y coordinate of the pointer relative to the root of the screen.

GdkEventScroll

typedef struct {
  GdkEventType type;
  GdkWindow *window;
  gint8 send_event;
  guint32 time;
  gdouble x;
  gdouble y;
  guint state;
  GdkScrollDirection direction;
  GdkDevice *device;
  gdouble x_root, y_root;
} GdkEventScroll;

Generated from button presses for the buttons 4 to 7. Wheel mice are usually configured to generate button press events for buttons 4 and 5 when the wheel is turned.

GdkEventType type; | the type of the event (GDK_SCROLL).
GdkWindow *window; | the window which received the event.
gint8 send_event; | TRUE if the event was sent explicitly (e.g. using XSendEvent).
guint32 time; | the time of the event in milliseconds.
gdouble x; | the x coordinate of the pointer relative to the window.
gdouble y; | the y coordinate of the pointer relative to the window.
guint state; | a bit-mask representing the state of the modifier keys (e.g. Control, Shift and Alt) and the pointer buttons. See GdkModifierType.
GdkScrollDirection direction; | the direction to scroll to (one of GDK_SCROLL_UP, GDK_SCROLL_DOWN, GDK_SCROLL_LEFT and GDK_SCROLL_RIGHT).
GdkDevice *device; | the device where the event originated.
gdouble x_root; | the x coordinate of the pointer relative to the root of the screen.
gdouble y_root; | the y coordinate of the pointer relative to the root of the screen.

GdkEventMotion

typedef struct {
  GdkEventType type;
  GdkWindow *window;
  gint8 send_event;
  guint32 time;
  gdouble x;
  gdouble y;
  gdouble *axes;
  guint state;
  gint16 is_hint;
  GdkDevice *device;
  gdouble x_root, y_root;
} GdkEventMotion;

Generated when the pointer moves.

GdkEventType type; | the type of the event.
GdkWindow *window; | the window which received the event.
gint8 send_event; | TRUE if the event was sent explicitly (e.g. using XSendEvent).
guint32 time; | the time of the event in milliseconds.
gdouble x; | the x coordinate of the pointer relative to the window.
gdouble y; | the y coordinate of the pointer relative to the window.
gdouble *axes; | x, y translated to the axes of device, or NULL if device is the mouse.
guint state; | a bit-mask representing the state of the modifier keys (e.g. Control, Shift and Alt) and the pointer buttons. See GdkModifierType.
gint16 is_hint; | set to 1 if this event is just a hint, see the GDK_POINTER_MOTION_HINT_MASK value of GdkEventMask.
GdkDevice *device; | the device where the event originated.
gdouble x_root; | the x coordinate of the pointer relative to the root of the screen.
gdouble y_root; | the y coordinate of the pointer relative to the root of the screen.

GdkEventExpose

typedef struct {
  GdkEventType type;
  GdkWindow *window;
  gint8 send_event;
  GdkRectangle area;
  GdkRegion *region;
  gint count; /* If non-zero, how many more events follow. */
} GdkEventExpose;

Generated when all or part of a window becomes visible and needs to be redrawn.

GdkEventType type; | the type of the event (GDK_EXPOSE).
GdkWindow *window; | the window which received the event.
gint8 send_event; | TRUE if the event was sent explicitly (e.g. using XSendEvent).
GdkRectangle area; | bounding box of region.
GdkRegion *region; | the region that needs to be redrawn.
gint count; | the number of contiguous GDK_EXPOSE events following this one. The only use for this is "exposure compression", i.e. handling all contiguous GDK_EXPOSE events in one go, though GDK performs some exposure compression so this is not normally needed.

GdkEventVisibility

typedef struct {
  GdkEventType type;
  GdkWindow *window;
  gint8 send_event;
  GdkVisibilityState state;
} GdkEventVisibility;

Generated when the window visibility status has changed.

GdkEventType type; | the type of the event (GDK_VISIBILITY_NOTIFY).
GdkWindow *window; | the window which received the event.
gint8 send_event; | TRUE if the event was sent explicitly (e.g. using XSendEvent).
GdkVisibilityState state; | the new visibility state (GDK_VISIBILITY_FULLY_OBSCURED, GDK_VISIBILITY_PARTIAL or GDK_VISIBILITY_UNOBSCURED).

GdkEventCrossing

typedef struct {
  GdkEventType type;
  GdkWindow *window;
  gint8 send_event;
  GdkWindow *subwindow;
  guint32 time;
  gdouble x;
  gdouble y;
  gdouble x_root;
  gdouble y_root;
  GdkCrossingMode mode;
  GdkNotifyType detail;
  gboolean focus;
  guint state;
} GdkEventCrossing;

Generated when the pointer enters or leaves a window.

GdkEventType type; | the type of the event (GDK_ENTER_NOTIFY or GDK_LEAVE_NOTIFY).
GdkWindow *window; | the window which received the event.
gint8 send_event; | TRUE if the event was sent explicitly (e.g. using XSendEvent).
GdkWindow *subwindow; | the window that was entered or left.
guint32 time; | the time of the event in milliseconds.
gdouble x; | the x coordinate of the pointer relative to the window.
gdouble y; | the y coordinate of the pointer relative to the window.
gdouble x_root; | the x coordinate of the pointer relative to the root of the screen.
gdouble y_root; | the y coordinate of the pointer relative to the root of the screen.
GdkCrossingMode mode; | the crossing mode (GDK_CROSSING_NORMAL, GDK_CROSSING_GRAB or GDK_CROSSING_UNGRAB).
GdkNotifyType detail; | the kind of crossing that happened (GDK_NOTIFY_INFERIOR, GDK_NOTIFY_ANCESTOR, GDK_NOTIFY_VIRTUAL, GDK_NOTIFY_NONLINEAR or GDK_NOTIFY_NONLINEAR_VIRTUAL).
gboolean focus; | TRUE if window is the focus window or an inferior.
guint state; | a bit-mask representing the state of the modifier keys (e.g. Control, Shift and Alt) and the pointer buttons. See GdkModifierType.

GdkEventFocus

typedef struct {
  GdkEventType type;
  GdkWindow *window;
  gint8 send_event;
  gint16 in;
} GdkEventFocus;

Describes a change of keyboard focus.

GdkEventType type; | the type of the event (GDK_FOCUS_CHANGE).
GdkWindow *window; | the window which received the event.
gint8 send_event; | TRUE if the event was sent explicitly (e.g. using XSendEvent).
gint16 in; | TRUE if the window has gained the keyboard focus, FALSE if it has lost the focus.

GdkEventConfigure

typedef struct {
  GdkEventType type;
  GdkWindow *window;
  gint8 send_event;
  gint x, y;
  gint width;
  gint height;
} GdkEventConfigure;

Generated when a window size or position has changed.

GdkEventType type; | the type of the event (GDK_CONFIGURE).
GdkWindow *window; | the window which received the event.
gint8 send_event; | TRUE if the event was sent explicitly (e.g. using XSendEvent).
gint x; | the new x coordinate of the window, relative to its parent.
gint y; | the new y coordinate of the window, relative to its parent.
gint width; | the new width of the window.
gint height; | the new height of the window.

GdkEventProperty

typedef struct {
  GdkEventType type;
  GdkWindow *window;
  gint8 send_event;
  GdkAtom atom;
  guint32 time;
  guint state;
} GdkEventProperty;

Describes a property change on a window.

GdkEventType type; | the type of the event (GDK_PROPERTY_NOTIFY).
GdkWindow *window; | the window which received the event.
gint8 send_event; | TRUE if the event was sent explicitly (e.g. using XSendEvent).
GdkAtom atom; | the property that was changed.
guint32 time; | the time of the event in milliseconds.
guint state; | whether the property was changed (GDK_PROPERTY_NEW_VALUE) or deleted (GDK_PROPERTY_DELETE).

GdkEventSelection

typedef struct {
  GdkEventType type;
  GdkWindow *window;
  gint8 send_event;
  GdkAtom selection;
  GdkAtom target;
  GdkAtom property;
  guint32 time;
  GdkNativeWindow requestor;
} GdkEventSelection;

Generated when a selection is requested or ownership of a selection is taken over by another client application.

GdkEventType type; | the type of the event (GDK_SELECTION_CLEAR, GDK_SELECTION_NOTIFY or GDK_SELECTION_REQUEST).
GdkWindow *window; | the window which received the event.
gint8 send_event; | TRUE if the event was sent explicitly (e.g. using XSendEvent).
GdkAtom selection; | the selection.
GdkAtom target; | the target to which the selection should be converted.
GdkAtom property; | the property in which to place the result of the conversion.
guint32 time; | the time of the event in milliseconds.
GdkNativeWindow requestor; | the native window on which to place property.

GdkNativeWindow

Used to represent native windows (Windows for the X11 backend, HWNDs for Win32).

GdkEventDND

typedef struct {
  GdkEventType type;
  GdkWindow *window;
  gint8 send_event;
  GdkDragContext *context;

  guint32 time;
  gshort x_root, y_root;
} GdkEventDND;

Generated during DND operations.

GdkEventType type; | the type of the event (GDK_DRAG_ENTER, GDK_DRAG_LEAVE, GDK_DRAG_MOTION, GDK_DRAG_STATUS, GDK_DROP_START or GDK_DROP_FINISHED).
GdkWindow *window; | the window which received the event.
gint8 send_event; | TRUE if the event was sent explicitly (e.g. using XSendEvent).
GdkDragContext *context; | the GdkDragContext for the current DND operation.
guint32 time; | the time of the event in milliseconds.
gshort x_root; | the x coordinate of the pointer relative to the root of the screen, only set for GDK_DRAG_MOTION and GDK_DROP_START.
gshort y_root; | the y coordinate of the pointer relative to the root of the screen, only set for GDK_DRAG_MOTION and GDK_DROP_START.

GdkEventProximity

typedef struct {
  GdkEventType type;
  GdkWindow *window;
  gint8 send_event;
  guint32 time;
  GdkDevice *device;
} GdkEventProximity;

Proximity events are generated when using GDK's wrapper for the XInput extension. The XInput extension is an add-on for standard X that allows you to use nonstandard devices such as graphics tablets. A proximity event indicates that the stylus has moved in or out of contact with the tablet, or perhaps that the user's finger has moved in or out of contact with a touch screen.

GdkEventType type; | the type of the event (GDK_PROXIMITY_IN or GDK_PROXIMITY_OUT).
GdkWindow *window; | the window which received the event.
gint8 send_event; | TRUE if the event was sent explicitly (e.g. using XSendEvent).
guint32 time; | the time of the event in milliseconds.
GdkDevice *device; | the device where the event originated.

GdkEventClient

typedef struct {
  GdkEventType type;
  GdkWindow *window;
  gint8 send_event;
  GdkAtom message_type;
  gushort data_format;
  union {
    char b[20];
    short s[10];
    long l[5];
  } data;
} GdkEventClient;

An event sent by another client application.

GdkEventType type; | the type of the event (GDK_CLIENT_EVENT).
GdkWindow *window; | the window which received the event.
gint8 send_event; | TRUE if the event was sent explicitly (e.g. using XSendEvent).
GdkAtom message_type; | the type of the message, which can be defined by the application.
gushort data_format; | the format of the data, given as the number of bits in each data element, i.e. 8, 16, or 32. 8-bit data uses the b array of the data union, 16-bit data uses the s array, and 32-bit data uses the l array.

GdkEventNoExpose

typedef struct {
  GdkEventType type;
  GdkWindow *window;
  gint8 send_event;
} GdkEventNoExpose;

Generated when the area of a GdkDrawable being copied, with gdk_draw_drawable() or gdk_window_copy_area(), was completely available.

FIXME: add more here.

GdkEventType type; | the type of the event (GDK_NO_EXPOSE).
GdkWindow *window; | the window which received the event.
gint8 send_event; | TRUE if the event was sent explicitly (e.g. using XSendEvent).

GdkEventWindowState

typedef struct {
  GdkEventType type;
  GdkWindow *window;
  gint8 send_event;
  GdkWindowState changed_mask;
  GdkWindowState new_window_state;
} GdkEventWindowState;

Generated when the state of a toplevel window changes.

GdkEventType type; | the type of the event (GDK_WINDOW_STATE).
GdkWindow *window; | the window which received the event.
gint8 send_event; | TRUE if the event was sent explicitly (e.g. using XSendEvent).
GdkWindowState changed_mask; | mask specifying what flags have changed.
GdkWindowState new_window_state; | the new window state, a combination of GdkWindowState bits.

GdkEventSetting

typedef struct {
  GdkEventType type;
  GdkWindow *window;
  gint8 send_event;
  GdkSettingAction action;
  char *name;
} GdkEventSetting;

Generated when a setting is modified.

GdkEventType type; | the type of the event (GDK_SETTING).
GdkWindow *window; | the window which received the event.
gint8 send_event; | TRUE if the event was sent explicitly (e.g. using XSendEvent).
GdkSettingAction action; | what happened to the setting (GDK_SETTING_ACTION_NEW, GDK_SETTING_ACTION_CHANGED or GDK_SETTING_ACTION_DELETED).
char *name; | the name of the setting.

GdkEventOwnerChange

typedef struct {
  GdkEventType type;
  GdkWindow *window;
  gint8 send_event;
  GdkNativeWindow owner;
  GdkOwnerChange reason;
  GdkAtom selection;
  guint32 time;
  guint32 selection_time;
} GdkEventOwnerChange;

Generated when the owner of a selection changes. On X11, this information is only available if the X server supports the XFIXES extension.

GdkEventType type; | the type of the event (GDK_OWNER_CHANGE).
GdkWindow *window; | the window which received the event
gint8 send_event; | TRUE if the event was sent explicitly (e.g. using XSendEvent).
GdkNativeWindow owner; | the new owner of the selection
GdkOwnerChange reason; | the reason for the ownership change as a GdkOwnerChange value
GdkAtom selection; | the atom identifying the selection
guint32 time; | the timestamp of the event
guint32 selection_time; | the time at which the selection ownership was taken over

Since 2.6

GdkEventGrabBroken

typedef struct {
  GdkEventType type;
  GdkWindow *window;
  gint8 send_event;
  gboolean keyboard;
  gboolean implicit;
  GdkWindow *grab_window;
} GdkEventGrabBroken;

Generated when a pointer or keyboard grab is broken. On X11, this happens when the grab window becomes unviewable (i.e. it or one of its ancestors is unmapped), or if the same application grabs the pointer or keyboard again. Note that implicit grabs (which are initiated by button presses) can also cause GdkEventGrabBroken events.

GdkEventType type; | the type of the event (GDK_GRAB_BROKEN)
GdkWindow *window; | the window which received the event, i.e. the window that previously owned the grab
gint8 send_event; | TRUE if the event was sent explicitly (e.g. using XSendEvent).
gboolean keyboard; | TRUE if a keyboard grab was broken, FALSE if a pointer grab was broken
gboolean implicit; | TRUE if the broken grab was implicit
GdkWindow *grab_window; | If this event is caused by another grab in the same application, grab_window contains the new grab window. Otherwise grab_window id NULL.

Since 2.8

enum GdkScrollDirection

typedef enum
{
  GDK_SCROLL_UP,
  GDK_SCROLL_DOWN,
  GDK_SCROLL_LEFT,
  GDK_SCROLL_RIGHT
} GdkScrollDirection;

Specifies the direction for GdkEventScroll.

GDK_SCROLL_UP | the window is scrolled up.
GDK_SCROLL_DOWN | the window is scrolled down.
GDK_SCROLL_LEFT | the window is scrolled to the left.
GDK_SCROLL_RIGHT | the window is scrolled to the right.

enum GdkVisibilityState

typedef enum
{
  GDK_VISIBILITY_UNOBSCURED,
  GDK_VISIBILITY_PARTIAL,
  GDK_VISIBILITY_FULLY_OBSCURED
} GdkVisibilityState;

Specifies the visiblity status of a window for a GdkEventVisibility.

GDK_VISIBILITY_UNOBSCURED | the window is completely visible.
GDK_VISIBILITY_PARTIAL | the window is partially visible.
GDK_VISIBILITY_FULLY_OBSCURED | the window is not visible at all.

enum GdkCrossingMode

typedef enum
{
  GDK_CROSSING_NORMAL,
  GDK_CROSSING_GRAB,
  GDK_CROSSING_UNGRAB
} GdkCrossingMode;

Specifies the crossing mode for GdkEventCrossing.

GDK_CROSSING_NORMAL | crossing because of pointer motion.
GDK_CROSSING_GRAB | crossing because a grab is activated.
GDK_CROSSING_UNGRAB | crossing because a grab is deactivated.

enum GdkNotifyType

typedef enum
{
  GDK_NOTIFY_ANCESTOR		= 0,
  GDK_NOTIFY_VIRTUAL		= 1,
  GDK_NOTIFY_INFERIOR		= 2,
  GDK_NOTIFY_NONLINEAR		= 3,
  GDK_NOTIFY_NONLINEAR_VIRTUAL	= 4,
  GDK_NOTIFY_UNKNOWN		= 5
} GdkNotifyType;

Specifies the kind of crossing for GdkEventCrossing.

See the X11 protocol specification of LeaveNotify for full details of crossing event generation.

GDK_NOTIFY_ANCESTOR | the window is entered from an ancestor or left towards an ancestor.
GDK_NOTIFY_VIRTUAL | the pointer moves between an ancestor and an inferior of the window.
GDK_NOTIFY_INFERIOR | the window is entered from an inferior or left towards an inferior.
GDK_NOTIFY_NONLINEAR | the window is entered from or left towards a window which is neither an ancestor nor an inferior.
GDK_NOTIFY_NONLINEAR_VIRTUAL | the pointer moves between two windows which are not ancestors of each other and the window is part of the ancestor chain between one of these windows and their least common ancestor.
GDK_NOTIFY_UNKNOWN | an unknown type of enter/leave event occurred.

enum GdkPropertyState

typedef enum
{
  GDK_PROPERTY_NEW_VALUE,
  GDK_PROPERTY_DELETE
} GdkPropertyState;

Specifies the type of a property change for a GdkEventProperty.

GDK_PROPERTY_NEW_VALUE | the property value was changed.
GDK_PROPERTY_DELETE | the property was deleted.

enum GdkWindowState

typedef enum
{
  GDK_WINDOW_STATE_WITHDRAWN  = 1 << 0,
  GDK_WINDOW_STATE_ICONIFIED  = 1 << 1,
  GDK_WINDOW_STATE_MAXIMIZED  = 1 << 2,
  GDK_WINDOW_STATE_STICKY     = 1 << 3,
  GDK_WINDOW_STATE_FULLSCREEN = 1 << 4,
  GDK_WINDOW_STATE_ABOVE      = 1 << 5,
  GDK_WINDOW_STATE_BELOW      = 1 << 6
} GdkWindowState;

Specifies the state of a toplevel window.

GDK_WINDOW_STATE_WITHDRAWN | the window is not shown.
GDK_WINDOW_STATE_ICONIFIED | the window is minimized.
GDK_WINDOW_STATE_MAXIMIZED | the window is maximized.
GDK_WINDOW_STATE_STICKY | the window is sticky.
GDK_WINDOW_STATE_FULLSCREEN | the window is maximized without decorations.
GDK_WINDOW_STATE_ABOVE | the window is kept above other windows.
GDK_WINDOW_STATE_BELOW | the window is kept below other windows.

enum GdkSettingAction

typedef enum
{
  GDK_SETTING_ACTION_NEW,
  GDK_SETTING_ACTION_CHANGED,
  GDK_SETTING_ACTION_DELETED
} GdkSettingAction;

Specifies the kind of modification applied to a setting in a GdkEventSetting.

GDK_SETTING_ACTION_NEW | a setting was added.
GDK_SETTING_ACTION_CHANGED | a setting was changed.
GDK_SETTING_ACTION_DELETED | a setting was deleted.

enum GdkOwnerChange

typedef enum
{
  GDK_OWNER_CHANGE_NEW_OWNER,
  GDK_OWNER_CHANGE_DESTROY,
  GDK_OWNER_CHANGE_CLOSE
} GdkOwnerChange;

Specifies why a selection ownership was changed.

GDK_OWNER_CHANGE_NEW_OWNER | some other app claimed the ownership
GDK_OWNER_CHANGE_DESTROY | the window was destroyed
GDK_OWNER_CHANGE_CLOSE | the client was closed


Events

Events — Functions for handling events from the window system

Synopsis

#include <gdk/gdk.h>

enum                GdkEventType;
enum                GdkEventMask;
#define             GDK_CURRENT_TIME
#define             GDK_PRIORITY_EVENTS
#define             GDK_PRIORITY_REDRAW

gboolean            gdk_events_pending                  (void);
GdkEvent*           gdk_event_peek                      (void);
GdkEvent*           gdk_event_get                       (void);
GdkEvent*           gdk_event_get_graphics_expose       (GdkWindow *window);
void                gdk_event_put                       (GdkEvent *event);
GdkEvent*           gdk_event_new                       (GdkEventType type);
GdkEvent*           gdk_event_copy                      (GdkEvent *event);
void                gdk_event_free                      (GdkEvent *event);
guint32             gdk_event_get_time                  (GdkEvent *event);
gboolean            gdk_event_get_state                 (GdkEvent *event,
                                                         GdkModifierType *state);
gboolean            gdk_event_get_axis                  (GdkEvent *event,
                                                         GdkAxisUse axis_use,
                                                         gdouble *value);
gboolean            gdk_event_get_coords                (GdkEvent *event,
                                                         gdouble *x_win,
                                                         gdouble *y_win);
gboolean            gdk_event_get_root_coords           (GdkEvent *event,
                                                         gdouble *x_root,
                                                         gdouble *y_root);

void                gdk_event_handler_set               (GdkEventFunc func,
                                                         gpointer data,
                                                         GDestroyNotify notify);
void                (*GdkEventFunc)                     (GdkEvent *event,
                                                         gpointer data);

gboolean            gdk_event_send_client_message       (GdkEvent *event,
                                                         GdkNativeWindow winid);
gboolean            gdk_event_send_client_message_for_display
                                                        (GdkDisplay *display,
                                                         GdkEvent *event,
                                                         GdkNativeWindow winid);
void                gdk_event_send_clientmessage_toall  (GdkEvent *event);
void                gdk_add_client_message_filter       (GdkAtom message_type,
                                                         GdkFilterFunc func,
                                                         gpointer data);

gboolean            gdk_get_show_events                 (void);
void                gdk_set_show_events                 (gboolean show_events);
void                gdk_event_set_screen                (GdkEvent *event,
                                                         GdkScreen *screen);
GdkScreen*          gdk_event_get_screen                (GdkEvent *event);

gboolean            gdk_setting_get                     (const gchar *name,
                                                         GValue *value);

Description

This section describes functions dealing with events from the window system.

In GTK+ applications the events are handled automatically in gtk_main_do_event() and passed on to the appropriate widgets, so these functions are rarely needed. Though some of the fields in the Event Structures are useful.

Details

enum GdkEventType

typedef enum
{
  GDK_NOTHING		= -1,
  GDK_DELETE		= 0,
  GDK_DESTROY		= 1,
  GDK_EXPOSE		= 2,
  GDK_MOTION_NOTIFY	= 3,
  GDK_BUTTON_PRESS	= 4,
  GDK_2BUTTON_PRESS	= 5,
  GDK_3BUTTON_PRESS	= 6,
  GDK_BUTTON_RELEASE	= 7,
  GDK_KEY_PRESS		= 8,
  GDK_KEY_RELEASE	= 9,
  GDK_ENTER_NOTIFY	= 10,
  GDK_LEAVE_NOTIFY	= 11,
  GDK_FOCUS_CHANGE	= 12,
  GDK_CONFIGURE		= 13,
  GDK_MAP		= 14,
  GDK_UNMAP		= 15,
  GDK_PROPERTY_NOTIFY	= 16,
  GDK_SELECTION_CLEAR	= 17,
  GDK_SELECTION_REQUEST = 18,
  GDK_SELECTION_NOTIFY	= 19,
  GDK_PROXIMITY_IN	= 20,
  GDK_PROXIMITY_OUT	= 21,
  GDK_DRAG_ENTER        = 22,
  GDK_DRAG_LEAVE        = 23,
  GDK_DRAG_MOTION       = 24,
  GDK_DRAG_STATUS       = 25,
  GDK_DROP_START        = 26,
  GDK_DROP_FINISHED     = 27,
  GDK_CLIENT_EVENT	= 28,
  GDK_VISIBILITY_NOTIFY = 29,
  GDK_NO_EXPOSE		= 30,
  GDK_SCROLL            = 31,
  GDK_WINDOW_STATE      = 32,
  GDK_SETTING           = 33,
  GDK_OWNER_CHANGE      = 34,
  GDK_GRAB_BROKEN       = 35
} GdkEventType;

Specifies the type of the event.

Do not confuse these events with the signals that GTK+ widgets emit. Although many of these events result in corresponding signals being emitted, the events are often transformed or filtered along the way.

GDK_NOTHING | a special code to indicate a null event.
GDK_DELETE | the window manager has requested that the toplevel window be hidden or destroyed, usually when the user clicks on a special icon in the title bar.
GDK_DESTROY | the window has been destroyed.
GDK_EXPOSE | all or part of the window has become visible and needs to be redrawn.
GDK_MOTION_NOTIFY | the pointer (usually a mouse) has moved.
GDK_BUTTON_PRESS | a mouse button has been pressed.
GDK_2BUTTON_PRESS | a mouse button has been double-clicked (clicked twice within a short period of time). Note that each click also generates a GDK_BUTTON_PRESS event.
GDK_3BUTTON_PRESS | a mouse button has been clicked 3 times in a short period of time. Note that each click also generates a GDK_BUTTON_PRESS event.
GDK_BUTTON_RELEASE | a mouse button has been released.
GDK_KEY_PRESS | a key has been pressed.
GDK_KEY_RELEASE | a key has been released.
GDK_ENTER_NOTIFY | the pointer has entered the window.
GDK_LEAVE_NOTIFY | the pointer has left the window.
GDK_FOCUS_CHANGE | the keyboard focus has entered or left the window.
GDK_CONFIGURE | the size, position or stacking order of the window has changed. Note that GTK+ discards these events for GDK_WINDOW_CHILD windows.
GDK_MAP | the window has been mapped.
GDK_UNMAP | the window has been unmapped.
GDK_PROPERTY_NOTIFY | a property on the window has been changed or deleted.
GDK_SELECTION_CLEAR | the application has lost ownership of a selection.
GDK_SELECTION_REQUEST | another application has requested a selection.
GDK_SELECTION_NOTIFY | a selection has been received.
GDK_PROXIMITY_IN | an input device has moved into contact with a sensing surface (e.g. a touchscreen or graphics tablet).
GDK_PROXIMITY_OUT | an input device has moved out of contact with a sensing surface.
GDK_DRAG_ENTER | the mouse has entered the window while a drag is in progress.
GDK_DRAG_LEAVE | the mouse has left the window while a drag is in progress.
GDK_DRAG_MOTION | the mouse has moved in the window while a drag is in progress.
GDK_DRAG_STATUS | the status of the drag operation initiated by the window has changed.
GDK_DROP_START | a drop operation onto the window has started.
GDK_DROP_FINISHED | the drop operation initiated by the window has completed.
GDK_CLIENT_EVENT | a message has been received from another application.
GDK_VISIBILITY_NOTIFY | the window visibility status has changed.
GDK_NO_EXPOSE | indicates that the source region was completely available when parts of a drawable were copied. This is not very useful.
GDK_SCROLL | the scroll wheel was turned
GDK_WINDOW_STATE | the state of a window has changed. See GdkWindowState for the possible window states
GDK_SETTING | a setting has been modified.
GDK_OWNER_CHANGE | the owner of a selection has changed. This event type was added in 2.6
GDK_GRAB_BROKEN | a pointer or keyboard grab was broken. This event type was added in 2.8.

enum GdkEventMask

typedef enum
{
  GDK_EXPOSURE_MASK		= 1 << 1,
  GDK_POINTER_MOTION_MASK	= 1 << 2,
  GDK_POINTER_MOTION_HINT_MASK	= 1 << 3,
  GDK_BUTTON_MOTION_MASK	= 1 << 4,
  GDK_BUTTON1_MOTION_MASK	= 1 << 5,
  GDK_BUTTON2_MOTION_MASK	= 1 << 6,
  GDK_BUTTON3_MOTION_MASK	= 1 << 7,
  GDK_BUTTON_PRESS_MASK		= 1 << 8,
  GDK_BUTTON_RELEASE_MASK	= 1 << 9,
  GDK_KEY_PRESS_MASK		= 1 << 10,
  GDK_KEY_RELEASE_MASK		= 1 << 11,
  GDK_ENTER_NOTIFY_MASK		= 1 << 12,
  GDK_LEAVE_NOTIFY_MASK		= 1 << 13,
  GDK_FOCUS_CHANGE_MASK		= 1 << 14,
  GDK_STRUCTURE_MASK		= 1 << 15,
  GDK_PROPERTY_CHANGE_MASK	= 1 << 16,
  GDK_VISIBILITY_NOTIFY_MASK	= 1 << 17,
  GDK_PROXIMITY_IN_MASK		= 1 << 18,
  GDK_PROXIMITY_OUT_MASK	= 1 << 19,
  GDK_SUBSTRUCTURE_MASK		= 1 << 20,
  GDK_SCROLL_MASK               = 1 << 21,
  GDK_ALL_EVENTS_MASK		= 0x3FFFFE
} GdkEventMask;

A set of bit-flags to indicate which events a window is to receive. Most of these masks map onto one or more of the GdkEventType event types above.

GDK_POINTER_MOTION_HINT_MASK is a special mask which is used to reduce the number of GDK_MOTION_NOTIFY events received. Normally a GDK_MOTION_NOTIFY event is received each time the mouse moves. However, if the application spends a lot of time processing the event (updating the display, for example), it can easily lag behind the position of the mouse. When using the GDK_POINTER_MOTION_HINT_MASK the server will only send a single GDK_MOTION_NOTIFY event (which is marked as a hint) until the application asks for more, by calling gdk_window_get_pointer().

GDK_EXPOSURE_MASK | receive expose events
GDK_POINTER_MOTION_MASK | receive all pointer motion events
GDK_POINTER_MOTION_HINT_MASK | see the explanation above
GDK_BUTTON_MOTION_MASK | receive pointer motion events while any button is pressed
GDK_BUTTON1_MOTION_MASK | receive pointer motion events while 1 button is pressed
GDK_BUTTON2_MOTION_MASK | receive pointer motion events while 2 button is pressed
GDK_BUTTON3_MOTION_MASK | receive pointer motion events while 3 button is pressed
GDK_BUTTON_PRESS_MASK | receive button press events
GDK_BUTTON_RELEASE_MASK | receive button release events
GDK_KEY_PRESS_MASK | receive key press events
GDK_KEY_RELEASE_MASK | receive key release events
GDK_ENTER_NOTIFY_MASK | receive window enter events
GDK_LEAVE_NOTIFY_MASK | receive window leave events
GDK_FOCUS_CHANGE_MASK | receive focus change events
GDK_STRUCTURE_MASK | receive events about window configuration change
GDK_PROPERTY_CHANGE_MASK | receive property change events
GDK_VISIBILITY_NOTIFY_MASK | receive visibility change events
GDK_PROXIMITY_IN_MASK | receive proximity in events
GDK_PROXIMITY_OUT_MASK | receive proximity out events
GDK_SUBSTRUCTURE_MASK | receive events about window configuration changes of child windows
GDK_SCROLL_MASK | receive scroll events
GDK_ALL_EVENTS_MASK | the combination of all the above event masks.

GDK_CURRENT_TIME

#define GDK_CURRENT_TIME     0L

Represents the current time, and can be used anywhere a time is expected.

GDK_PRIORITY_EVENTS

#define             GDK_PRIORITY_EVENTS

This is the priority that events from the X server are given in the GLib Main Loop.

GDK_PRIORITY_REDRAW

#define GDK_PRIORITY_REDRAW     (G_PRIORITY_HIGH_IDLE + 20)

This is the priority that the idle handler processing window updates is given in the GLib Main Loop.

gdk_events_pending ()

gboolean            gdk_events_pending                  (void);

Checks if any events are ready to be processed for any display.

Returns : TRUE if any events are pending.

gdk_event_peek ()

GdkEvent*           gdk_event_peek                      (void);

If there is an event waiting in the event queue of some open display, returns a copy of it. See gdk_display_peek_event().

Returns : a copy of the first GdkEvent on some event queue, or NULL if no events are in any queues. The returned GdkEvent should be freed with gdk_event_free().

gdk_event_get ()

GdkEvent*           gdk_event_get                       (void);

Checks all open displays for a GdkEvent to process,to be processed on, fetching events from the windowing system if necessary. See gdk_display_get_event().

Returns : the next GdkEvent to be processed, or NULL if no events are pending. The returned GdkEvent should be freed with gdk_event_free().

gdk_event_get_graphics_expose ()

GdkEvent*           gdk_event_get_graphics_expose       (GdkWindow *window);

Waits for a GraphicsExpose or NoExpose event from the X server. This is used in the GtkText and GtkCList widgets in GTK+ to make sure any GraphicsExpose events are handled before the widget is scrolled.

window : | the GdkWindow to wait for the events for.
Returns : | a GdkEventExpose if a GraphicsExpose was received, or NULL if a NoExpose event was received.

gdk_event_put ()

void                gdk_event_put                       (GdkEvent *event);

Appends a copy of the given event onto the front of the event queue for event->any.window's display, or the default event queue if event->any.window is NULL. See gdk_display_put_event().

event : a GdkEvent.

gdk_event_new ()

GdkEvent*           gdk_event_new                       (GdkEventType type);

Creates a new event of the given type. All fields are set to 0.

type : | a GdkEventType
Returns : | a newly-allocated GdkEvent. The returned GdkEvent should be freed with gdk_event_free().

Since 2.2

gdk_event_copy ()

GdkEvent*           gdk_event_copy                      (GdkEvent *event);

Copies a GdkEvent, copying or incrementing the reference count of the resources associated with it (e.g. GdkWindow's and strings).

event : | a GdkEvent
Returns : | a copy of event. The returned GdkEvent should be freed with gdk_event_free().

gdk_event_free ()

void                gdk_event_free                      (GdkEvent *event);

Frees a GdkEvent, freeing or decrementing any resources associated with it. Note that this function should only be called with events returned from functions such as gdk_event_peek(), gdk_event_get(), gdk_event_get_graphics_expose() and gdk_event_copy().

event : a GdkEvent.

gdk_event_get_time ()

guint32             gdk_event_get_time                  (GdkEvent *event);

Returns the time stamp from event, if there is one; otherwise returns GDK_CURRENT_TIME. If event is NULL, returns GDK_CURRENT_TIME.

event : | a GdkEvent
Returns : | time stamp field from event

gdk_event_get_state ()

gboolean            gdk_event_get_state                 (GdkEvent *event,
                                                         GdkModifierType *state);

If the event contains a "state" field, puts that field in state. Otherwise stores an empty state (0). Returns TRUE if there was a state field in the event. event may be NULL, in which case it's treated as if the event had no state field.

event : | a GdkEvent or NULL
state : | return location for state
Returns : | TRUE if there was a state field in the event

gdk_event_get_axis ()

gboolean            gdk_event_get_axis                  (GdkEvent *event,
                                                         GdkAxisUse axis_use,
                                                         gdouble *value);

Extract the axis value for a particular axis use from an event structure.

event : | a GdkEvent
axis_use : | the axis use to look for
value : | location to store the value found
Returns : | TRUE if the specified axis was found, otherwise FALSE

gdk_event_get_coords ()

gboolean            gdk_event_get_coords                (GdkEvent *event,
                                                         gdouble *x_win,
                                                         gdouble *y_win);

Extract the event window relative x/y coordinates from an event.

event : | a GdkEvent
x_win : | location to put event window x coordinate
y_win : | location to put event window y coordinate
Returns : | TRUE if the event delivered event window coordinates

gdk_event_get_root_coords ()

gboolean            gdk_event_get_root_coords           (GdkEvent *event,
                                                         gdouble *x_root,
                                                         gdouble *y_root);

Extract the root window relative x/y coordinates from an event.

event : | a GdkEvent
x_root : | location to put root window x coordinate
y_root : | location to put root window y coordinate
Returns : | TRUE if the event delivered root window coordinates

gdk_event_handler_set ()

void                gdk_event_handler_set               (GdkEventFunc func,
                                                         gpointer data,
                                                         GDestroyNotify notify);

Sets the function to call to handle all events from GDK.

Note that GTK+ uses this to install its own event handler, so it is usually not useful for GTK+ applications. (Although an application can call this function then call gtk_main_do_event() to pass events to GTK+.)

func : | the function to call to handle events from GDK.
data : | user data to pass to the function.
notify : | the function to call when the handler function is removed, i.e. when gdk_event_handler_set() is called with another event handler.

GdkEventFunc ()

void                (*GdkEventFunc)                     (GdkEvent *event,
                                                         gpointer data);

Specifies the type of function passed to gdk_event_handler_set() to handle all GDK events.

event : | the GdkEvent to process.
data : | user data set when the event handler was installed with gdk_event_handler_set().

gdk_event_send_client_message ()

gboolean            gdk_event_send_client_message       (GdkEvent *event,
                                                         GdkNativeWindow winid);

Sends an X ClientMessage event to a given window (which must be on the default GdkDisplay.) This could be used for communicating between different applications, though the amount of data is limited to 20 bytes.

event : | the GdkEvent to send, which should be a GdkEventClient.
winid : | the window to send the X ClientMessage event to.
Returns : | non-zero on success.

gdk_event_send_client_message_for_display ()

gboolean            gdk_event_send_client_message_for_display
                                                        (GdkDisplay *display,
                                                         GdkEvent *event,
                                                         GdkNativeWindow winid);

On X11, sends an X ClientMessage event to a given window. On Windows, sends a message registered with the name GDK_WIN32_CLIENT_MESSAGE.

This could be used for communicating between different applications, though the amount of data is limited to 20 bytes on X11, and to just four bytes on Windows.

display : | the GdkDisplay for the window where the message is to be sent.
event : | the GdkEvent to send, which should be a GdkEventClient.
winid : | the window to send the client message to.
Returns : | non-zero on success.

Since 2.2

gdk_event_send_clientmessage_toall ()

void                gdk_event_send_clientmessage_toall  (GdkEvent *event);

Sends an X ClientMessage event to all toplevel windows on the default GdkScreen.

Toplevel windows are determined by checking for the WM_STATE property, as described in the Inter-Client Communication Conventions Manual (ICCCM). If no windows are found with the WM_STATE property set, the message is sent to all children of the root window.

event : the GdkEvent to send, which should be a GdkEventClient.

gdk_add_client_message_filter ()

void                gdk_add_client_message_filter       (GdkAtom message_type,
                                                         GdkFilterFunc func,
                                                         gpointer data);

Adds a filter to the default display to be called when X ClientMessage events are received. See gdk_display_add_client_message_filter().

message_type : | the type of ClientMessage events to receive. This will be checked against the message_type field of the XClientMessage event struct.
func : | the function to call to process the event.
data : | user data to pass to func.

gdk_get_show_events ()

gboolean            gdk_get_show_events                 (void);

Gets whether event debugging output is enabled.

Returns : TRUE if event debugging output is enabled.

gdk_set_show_events ()

void                gdk_set_show_events                 (gboolean show_events);

Sets whether a trace of received events is output. Note that GTK+ must be compiled with debugging (that is, configured using the --enable-debug option) to use this option.

show_events : TRUE to output event debugging information.

gdk_event_set_screen ()

void                gdk_event_set_screen                (GdkEvent *event,
                                                         GdkScreen *screen);

Sets the screen for event to screen. The event must have been allocated by GTK+, for instance, by gdk_event_copy().

event : | a GdkEvent
screen : | a GdkScreen

Since 2.2

gdk_event_get_screen ()

GdkScreen*          gdk_event_get_screen                (GdkEvent *event);

Returns the screen for the event. The screen is typically the screen for event->any.window, but for events such as mouse events, it is the screen where the pointer was when the event occurs - that is, the screen which has the root window to which event->motion.x_root and event->motion.y_root are relative.

event : | a GdkEvent
Returns : | the screen for the event

Since 2.2

gdk_setting_get ()

gboolean            gdk_setting_get                     (const gchar *name,
                                                         GValue *value);

Obtains a desktop-wide setting, such as the double-click time, for the default screen. See gdk_screen_get_setting().

name : | the name of the setting.
value : | location to store the value of the setting.
Returns : | : TRUE if the setting existed and a value was stored in value, FALSE otherwise.

See Also

Event Structures

The structs used for each type of event.


Fonts

Fonts — Loading and manipulating fonts

Synopsis

#include <gdk/gdk.h>

                    GdkFont;
enum                GdkFontType;
GdkFont*            gdk_font_load                       (const gchar *font_name);
GdkFont*            gdk_font_load_for_display           (GdkDisplay *display,
                                                         const gchar *font_name);
GdkFont*            gdk_fontset_load                    (const gchar *fontset_name);
GdkFont*            gdk_fontset_load_for_display        (GdkDisplay *display,
                                                         const gchar *fontset_name);
GdkFont*            gdk_font_from_description           (PangoFontDescription *font_desc);
GdkFont*            gdk_font_from_description_for_display
                                                        (GdkDisplay *display,
                                                         PangoFontDescription *font_desc);
GdkDisplay*         gdk_font_get_display                (GdkFont *font);
GdkFont*            gdk_font_ref                        (GdkFont *font);
void                gdk_font_unref                      (GdkFont *font);
gint                gdk_font_id                         (const GdkFont *font);
gboolean            gdk_font_equal                      (const GdkFont *fonta,
                                                         const GdkFont *fontb);

void                gdk_string_extents                  (GdkFont *font,
                                                         const gchar *string,
                                                         gint *lbearing,
                                                         gint *rbearing,
                                                         gint *width,
                                                         gint *ascent,
                                                         gint *descent);
void                gdk_text_extents                    (GdkFont *font,
                                                         const gchar *text,
                                                         gint text_length,
                                                         gint *lbearing,
                                                         gint *rbearing,
                                                         gint *width,
                                                         gint *ascent,
                                                         gint *descent);
void                gdk_text_extents_wc                 (GdkFont *font,
                                                         const GdkWChar *text,
                                                         gint text_length,
                                                         gint *lbearing,
                                                         gint *rbearing,
                                                         gint *width,
                                                         gint *ascent,
                                                         gint *descent);
gint                gdk_string_width                    (GdkFont *font,
                                                         const gchar *string);
gint                gdk_text_width                      (GdkFont *font,
                                                         const gchar *text,
                                                         gint text_length);
gint                gdk_text_width_wc                   (GdkFont *font,
                                                         const GdkWChar *text,
                                                         gint text_length);
gint                gdk_char_width                      (GdkFont *font,
                                                         gchar character);
gint                gdk_char_width_wc                   (GdkFont *font,
                                                         GdkWChar character);
gint                gdk_string_measure                  (GdkFont *font,
                                                         const gchar *string);
gint                gdk_text_measure                    (GdkFont *font,
                                                         const gchar *text,
                                                         gint text_length);
gint                gdk_char_measure                    (GdkFont *font,
                                                         gchar character);
gint                gdk_string_height                   (GdkFont *font,
                                                         const gchar *string);
gint                gdk_text_height                     (GdkFont *font,
                                                         const gchar *text,
                                                         gint text_length);
gint                gdk_char_height                     (GdkFont *font,
                                                         gchar character);

typedef             GdkWChar;
gchar*              gdk_wcstombs                        (const GdkWChar *src);
gint                gdk_mbstowcs                        (GdkWChar *dest,
                                                         const gchar *src,
                                                         gint dest_max);

Description

The GdkFont data type represents a font for drawing on the screen. These functions provide support for loading fonts, and also for determining the dimensions of characters and strings when drawn with a particular font.

Fonts in X are specified by a X Logical Font Description. The following description is considerably simplified. For definitive information about XLFD's see the X reference documentation. A X Logical Font Description (XLFD) consists of a sequence of fields separated (and surrounded by) '-' characters. For example, Adobe Helvetica Bold 12 pt, has the full description:

"-adobe-helvetica-bold-r-normal--12-120-75-75-p-70-iso8859-1"

The fields in the XLFD are:

Foundry | the company or organization where the font originated.
Family | the font family (a group of related font designs).
Weight | A name for the font's typographic weight For example, 'bold' or 'medium').
Slant | The slant of the font. Common values are 'R' for Roman, 'I' for italoc, and 'O' for oblique.
Set Width | A name for the width of the font. For example, 'normal' or 'condensed'.
Add Style | Additional information to distinguish a font from other fonts of the same family.
Pixel Size | The body size of the font in pixels.
Point Size | The body size of the font in 10ths of a point. (A point is 1/72.27 inch)
Resolution X | The horizontal resolution that the font was designed for.
Resolution Y | The vertical resolution that the font was designed for .
Spacing | The type of spacing for the font - can be 'p' for proportional, 'm' for monospaced or 'c' for charcell.
Average Width | The average width of a glyph in the font. For monospaced and charcell fonts, all glyphs in the font have this width
Charset Registry | The registration authority that owns the encoding for the font. Together with the Charset Encoding field, this defines the character set for the font.
Charset Encoding | An identifier for the particular character set encoding.

When specifying a font via a X logical Font Description, '*' can be used as a wildcard to match any portion of the XLFD. For instance, the above example could also be specified as

"-*-helvetica-bold-r-normal--*-120-*-*-*-*-iso8859-1"

It is generally a good idea to use wildcards for any portion of the XLFD that your program does not care about specifically, since that will improve the chances of finding a matching font.

A fontset is a list of fonts that is used for drawing international text that may contain characters from a number of different character sets. It is represented by a list of XLFD's.

The font for a given character set is determined by going through the list of XLFD's in order. For each one, if the registry and and encoding fields match the desired character set, then that font is used, otherwise if the XLFD contains wild-cards for the registry and encoding fields, the registry and encoding for the desired character set are substituted in and a lookup is done. If a match is found that font is used. Otherwise, processing continues on to the next font in the list.

The functions for determining the metrics of a string come in several varieties that can take a number of forms of string input:

8-bit string | When using functions like gdk_string_width() that take a gchar *, if the font is of type GDK_FONT_FONT and is an 8-bit font, then each gchar indexes the glyphs in the font directly.
16-bit string | For functions taking a gchar *, if the font is of type GDK_FONT_FONT, and is a 16-bit font, then the gchar * argument is interpreted as a guint16 * cast to a gchar * and each guint16 indexes the glyphs in the font directly.
Multibyte string | For functions taking a gchar *, if the font is of type GDK_FONT_FONTSET, then the input string is interpreted as a multibyte encoded according to the current locale. (A multibyte string is one in which each character may consist of one or more bytes, with different lengths for different characters in the string). They can be converted to and from wide character strings (see below) using gdk_wcstombs() and gdk_mbstowcs().) The string will be rendered using one or more different fonts from the fontset.
Wide character string | For a number of the text-measuring functions, GDK provides a variant (such as gdk_text_width_wc()) which takes a GdkWChar * instead of a gchar *. The input is then taken to be a wide character string in the encoding of the current locale. (A wide character string is a string in which each character consists of several bytes, and the width of each character in the string is constant.)

GDK provides functions to determine a number of different measurements (metrics) for a given string. (Need diagram here).

ascent | The vertical distance from the origin of the drawing opereration to the top of the drawn character.
descent | The vertical distance from the origin of the drawing opereration to the bottom of the drawn character.
left bearing | The horizontal distance from the origin of the drawing operation to the left-most part of the drawn character.
right bearing | The horizontal distance from the origin of the drawing operation to the right-most part of the drawn character.
width bearing | The horizontal distance from the origin of the drawing operation to the correct origin for drawing another string to follow the current one. Depending on the font, this could be greater than or less than the right bearing.

Details

GdkFont

typedef struct {
  GdkFontType type;
  gint ascent;
  gint descent;
} GdkFont;

Warning

GdkFont is deprecated and should not be used in newly-written code.

The GdkFont structure represents a font or fontset. It contains the following public fields. A new GdkFont structure is returned by gdk_font_load() or gdk_fontset_load(), and is reference counted with gdk_font_ref() and gdk_font_unref()

GdkFontType type; | a value of type GdkFontType which indicates whether this font is a single font or a fontset.
gint ascent; | the maximum distance that the font, when drawn, ascends above the baseline.
gint descent; | the maximum distance that the font, when drawn, descends below the baseline.

enum GdkFontType

typedef enum
{
  GDK_FONT_FONT,
  GDK_FONT_FONTSET
} GdkFontType;

Warning

GdkFontType is deprecated and should not be used in newly-written code.

Indicates the type of a font. The possible values are currently:

GDK_FONT_FONT | the font is a single font.
GDK_FONT_FONTSET | the font is a fontset.

gdk_font_load ()

GdkFont*            gdk_font_load                       (const gchar *font_name);

Warning

gdk_font_load is deprecated and should not be used in newly-written code.

Loads a font.

The font may be newly loaded or looked up the font in a cache. You should make no assumptions about the initial reference count.

font_name : | a XLFD describing the font to load.
Returns : | a GdkFont, or NULL if the font could not be loaded.

gdk_font_load_for_display ()

GdkFont*            gdk_font_load_for_display           (GdkDisplay *display,
                                                         const gchar *font_name);

Warning

gdk_font_load_for_display is deprecated and should not be used in newly-written code.

Loads a font for use on display.

The font may be newly loaded or looked up the font in a cache. You should make no assumptions about the initial reference count.

display : | a GdkDisplay
font_name : | a XLFD describing the font to load.
Returns : | a GdkFont, or NULL if the font could not be loaded.

Since 2.2

gdk_fontset_load ()

GdkFont*            gdk_fontset_load                    (const gchar *fontset_name);

Warning

gdk_fontset_load is deprecated and should not be used in newly-written code.

Loads a fontset.

The fontset may be newly loaded or looked up in a cache. You should make no assumptions about the initial reference count.

fontset_name : | a comma-separated list of XLFDs describing the component fonts of the fontset to load.
Returns : | a GdkFont, or NULL if the fontset could not be loaded.

gdk_fontset_load_for_display ()

GdkFont*            gdk_fontset_load_for_display        (GdkDisplay *display,
                                                         const gchar *fontset_name);

Warning

gdk_fontset_load_for_display is deprecated and should not be used in newly-written code.

Loads a fontset for use on display.

The fontset may be newly loaded or looked up in a cache. You should make no assumptions about the initial reference count.

display : | a GdkDisplay
fontset_name : | a comma-separated list of XLFDs describing the component fonts of the fontset to load.
Returns : | a GdkFont, or NULL if the fontset could not be loaded.

Since 2.2

gdk_font_from_description ()

GdkFont*            gdk_font_from_description           (PangoFontDescription *font_desc);

Warning

gdk_font_from_description is deprecated and should not be used in newly-written code.

Load a GdkFont based on a Pango font description. This font will only be an approximation of the Pango font, and internationalization will not be handled correctly. This function should only be used for legacy code that cannot be easily converted to use Pango. Using Pango directly will produce better results.

font_desc : | a PangoFontDescription.
Returns : | the newly loaded font, or NULL if the font cannot be loaded.

gdk_font_from_description_for_display ()

GdkFont*            gdk_font_from_description_for_display
                                                        (GdkDisplay *display,
                                                         PangoFontDescription *font_desc);

Warning

gdk_font_from_description_for_display is deprecated and should not be used in newly-written code.

Loads a GdkFont based on a Pango font description for use on display. This font will only be an approximation of the Pango font, and internationalization will not be handled correctly. This function should only be used for legacy code that cannot be easily converted to use Pango. Using Pango directly will produce better results.

display : | a GdkDisplay
font_desc : | a PangoFontDescription.
Returns : | the newly loaded font, or NULL if the font cannot be loaded.

Since 2.2

gdk_font_get_display ()

GdkDisplay*         gdk_font_get_display                (GdkFont *font);

Warning

gdk_font_get_display is deprecated and should not be used in newly-written code.

Returns the GdkDisplay for font.

font : | the GdkFont.
Returns : | the corresponding GdkDisplay.

Since 2.2

gdk_font_ref ()

GdkFont*            gdk_font_ref                        (GdkFont *font);

Warning

gdk_font_ref is deprecated and should not be used in newly-written code.

Increases the reference count of a font by one.

font : | a GdkFont
Returns : | font

gdk_font_unref ()

void                gdk_font_unref                      (GdkFont *font);

Warning

gdk_font_unref is deprecated and should not be used in newly-written code.

Decreases the reference count of a font by one. If the result is zero, destroys the font.

font : a GdkFont

gdk_font_id ()

gint                gdk_font_id                         (const GdkFont *font);

Warning

gdk_font_id is deprecated and should not be used in newly-written code.

Returns the X Font ID for the given font.

font : | a GdkFont.
Returns : | the numeric X Font ID

gdk_font_equal ()

gboolean            gdk_font_equal                      (const GdkFont *fonta,
                                                         const GdkFont *fontb);

Warning

gdk_font_equal is deprecated and should not be used in newly-written code.

Compares two fonts for equality. Single fonts compare equal if they have the same X font ID. This operation does not currently work correctly for fontsets.

fonta : | a GdkFont.
fontb : | another GdkFont.
Returns : | TRUE if the fonts are equal.

gdk_string_extents ()

void                gdk_string_extents                  (GdkFont *font,
                                                         const gchar *string,
                                                         gint *lbearing,
                                                         gint *rbearing,
                                                         gint *width,
                                                         gint *ascent,
                                                         gint *descent);

Warning

gdk_string_extents is deprecated and should not be used in newly-written code.

Gets the metrics of a nul-terminated string.

font : | a GdkFont.
string : | the nul-terminated string to measure.
lbearing : | the left bearing of the string.
rbearing : | the right bearing of the string.
width : | the width of the string.
ascent : | the ascent of the string.
descent : | the descent of the string.

gdk_text_extents ()

void                gdk_text_extents                    (GdkFont *font,
                                                         const gchar *text,
                                                         gint text_length,
                                                         gint *lbearing,
                                                         gint *rbearing,
                                                         gint *width,
                                                         gint *ascent,
                                                         gint *descent);

Warning

gdk_text_extents is deprecated and should not be used in newly-written code.

Gets the metrics of a string.

font : | a GdkFont
text : | the text to measure
text_length : | the length of the text in bytes. (If the font is a 16-bit font, this is twice the length of the text in characters.)
lbearing : | the left bearing of the string.
rbearing : | the right bearing of the string.
width : | the width of the string.
ascent : | the ascent of the string.
descent : | the descent of the string.

gdk_text_extents_wc ()

void                gdk_text_extents_wc                 (GdkFont *font,
                                                         const GdkWChar *text,
                                                         gint text_length,
                                                         gint *lbearing,
                                                         gint *rbearing,
                                                         gint *width,
                                                         gint *ascent,
                                                         gint *descent);

Warning

gdk_text_extents_wc is deprecated and should not be used in newly-written code.

Gets the metrics of a string of wide characters.

font : | a GdkFont
text : | the text to measure.
text_length : | the length of the text in character.
lbearing : | the left bearing of the string.
rbearing : | the right bearing of the string.
width : | the width of the string.
ascent : | the ascent of the string.
descent : | the descent of the string.

gdk_string_width ()

gint                gdk_string_width                    (GdkFont *font,
                                                         const gchar *string);

Warning

gdk_string_width is deprecated and should not be used in newly-written code.

Determines the width of a nul-terminated string. (The distance from the origin of the string to the point where the next string in a sequence of strings should be drawn)

font : | a GdkFont
string : | the nul-terminated string to measure
Returns : | the width of the string in pixels.

gdk_text_width ()

gint                gdk_text_width                      (GdkFont *font,
                                                         const gchar *text,
                                                         gint text_length);

Warning

gdk_text_width is deprecated and should not be used in newly-written code.

Determines the width of a given string.

font : | a GdkFont
text : | the text to measure.
text_length : | the length of the text in bytes.
Returns : | the width of the string in pixels.

gdk_text_width_wc ()

gint                gdk_text_width_wc                   (GdkFont *font,
                                                         const GdkWChar *text,
                                                         gint text_length);

Warning

gdk_text_width_wc is deprecated and should not be used in newly-written code.

Determines the width of a given wide-character string.

font : | a GdkFont
text : | the text to measure.
text_length : | the length of the text in characters.
Returns : | the width of the string in pixels.

gdk_char_width ()

gint                gdk_char_width                      (GdkFont *font,
                                                         gchar character);

Warning

gdk_char_width is deprecated and should not be used in newly-written code. Use gdk_text_extents() instead.

Determines the width of a given character.

font : | a GdkFont
character : | the character to measure.
Returns : | the width of the character in pixels.

gdk_char_width_wc ()

gint                gdk_char_width_wc                   (GdkFont *font,
                                                         GdkWChar character);

Warning

gdk_char_width_wc is deprecated and should not be used in newly-written code.

Determines the width of a given wide character. (Encoded in the wide-character encoding of the current locale).

font : | a GdkFont
character : | the character to measure.
Returns : | the width of the character in pixels.

gdk_string_measure ()

gint                gdk_string_measure                  (GdkFont *font,
                                                         const gchar *string);

Warning

gdk_string_measure is deprecated and should not be used in newly-written code.

Determines the distance from the origin to the rightmost portion of a nul-terminated string when drawn. This is not the correct value for determining the origin of the next portion when drawing text in multiple pieces. See gdk_string_width().

font : | a GdkFont
string : | the nul-terminated string to measure.
Returns : | the right bearing of the string in pixels.

gdk_text_measure ()

gint                gdk_text_measure                    (GdkFont *font,
                                                         const gchar *text,
                                                         gint text_length);

Warning

gdk_text_measure is deprecated and should not be used in newly-written code.

Determines the distance from the origin to the rightmost portion of a string when drawn. This is not the correct value for determining the origin of the next portion when drawing text in multiple pieces. See gdk_text_width().

font : | a GdkFont
text : | the text to measure.
text_length : | the length of the text in bytes.
Returns : | the right bearing of the string in pixels.

gdk_char_measure ()

gint                gdk_char_measure                    (GdkFont *font,
                                                         gchar character);

Warning

gdk_char_measure is deprecated and should not be used in newly-written code.

Determines the distance from the origin to the rightmost portion of a character when drawn. This is not the correct value for determining the origin of the next portion when drawing text in multiple pieces.

font : | a GdkFont
character : | the character to measure.
Returns : | the right bearing of the character in pixels.

gdk_string_height ()

gint                gdk_string_height                   (GdkFont *font,
                                                         const gchar *string);

Warning

gdk_string_height is deprecated and should not be used in newly-written code.

Determines the total height of a given nul-terminated string. This value is not generally useful, because you cannot determine how this total height will be drawn in relation to the baseline. See gdk_string_extents().

font : | a GdkFont
string : | the nul-terminated string to measure.
Returns : | the height of the string in pixels.

gdk_text_height ()

gint                gdk_text_height                     (GdkFont *font,
                                                         const gchar *text,
                                                         gint text_length);

Warning

gdk_text_height is deprecated and should not be used in newly-written code.

Determines the total height of a given string. This value is not generally useful, because you cannot determine how this total height will be drawn in relation to the baseline. See gdk_text_extents().

font : | a GdkFont
text : | the text to measure.
text_length : | the length of the text in bytes.
Returns : | the height of the string in pixels.

gdk_char_height ()

gint                gdk_char_height                     (GdkFont *font,
                                                         gchar character);

Warning

gdk_char_height is deprecated and should not be used in newly-written code. Use gdk_text_extents() instead.

Determines the total height of a given character. This value is not generally useful, because you cannot determine how this total height will be drawn in relation to the baseline. See gdk_text_extents().

font : | a GdkFont
character : | the character to measure.
Returns : | the height of the character in pixels.

GdkWChar

typedef guint32			    GdkWChar;

Specifies a wide character type, used to represent character codes. This is needed since some native languages have character sets which have more than 256 characters (Japanese and Chinese, for example).

Wide character values between 0 and 127 are always identical in meaning to the ASCII character codes. The wide character value 0 is often used to terminate strings of wide characters in a similar way to normal strings using the char type.

An alternative to wide characters is multi-byte characters, which extend normal char strings to cope with larger character sets. As the name suggests, multi-byte characters use a different number of bytes to store different character codes. For example codes 0-127 (i.e. the ASCII codes) often use just one byte of memory, while other codes may use 2, 3 or even 4 bytes. Multi-byte characters have the advantage that they can often be used in an application with little change, since strings are still represented as arrays of char values. However multi-byte strings are much easier to manipulate since the character are all of the same size.

Applications typically use wide characters to represent character codes internally, and multi-byte strings when saving the characters to a file. The gdk_wcstombs() and gdk_mbstowcs() functions can be used to convert from one representation to the other.

See the 'Extended Characters' section of the GNU C Library Reference Manual for more detailed information on wide and multi-byte characters.

gdk_wcstombs ()

gchar*              gdk_wcstombs                        (const GdkWChar *src);

Warning

gdk_wcstombs is deprecated and should not be used in newly-written code.

Converts a wide character string to a multi-byte string. (The function name comes from an acronym of 'Wide Character String TO Multi-Byte String').

src : | a wide character string.
Returns : | the multi-byte string corresponding to src, or NULL if the conversion failed. The returned string should be freed with g_free() when no longer needed.

gdk_mbstowcs ()

gint                gdk_mbstowcs                        (GdkWChar *dest,
                                                         const gchar *src,
                                                         gint dest_max);

Warning

gdk_mbstowcs is deprecated and should not be used in newly-written code.

Converts a multi-byte string to a wide character string. (The function name comes from an acronym of 'Multi-Byte String TO Wide Character String').

dest : | the space to place the converted wide character string into.
src : | the multi-byte string to convert, which must be nul-terminated.
dest_max : | the maximum number of wide characters to place in dest.
Returns : | the number of wide characters written into dest, or -1 if the conversion failed.


GdkRGB

GdkRGB — Renders RGB, grayscale, or indexed image data to a GdkDrawable

Synopsis

#include <gdk/gdk.h>

void                gdk_rgb_init                        (void);

void                gdk_draw_rgb_image                  (GdkDrawable *drawable,
                                                         GdkGC *gc,
                                                         gint x,
                                                         gint y,
                                                         gint width,
                                                         gint height,
                                                         GdkRgbDither dith,
                                                         guchar *rgb_buf,
                                                         gint rowstride);
void                gdk_draw_rgb_image_dithalign        (GdkDrawable *drawable,
                                                         GdkGC *gc,
                                                         gint x,
                                                         gint y,
                                                         gint width,
                                                         gint height,
                                                         GdkRgbDither dith,
                                                         guchar *rgb_buf,
                                                         gint rowstride,
                                                         gint xdith,
                                                         gint ydith);
void                gdk_draw_indexed_image              (GdkDrawable *drawable,
                                                         GdkGC *gc,
                                                         gint x,
                                                         gint y,
                                                         gint width,
                                                         gint height,
                                                         GdkRgbDither dith,
                                                         guchar *buf,
                                                         gint rowstride,
                                                         GdkRgbCmap *cmap);
void                gdk_draw_gray_image                 (GdkDrawable *drawable,
                                                         GdkGC *gc,
                                                         gint x,
                                                         gint y,
                                                         gint width,
                                                         gint height,
                                                         GdkRgbDither dith,
                                                         guchar *buf,
                                                         gint rowstride);
void                gdk_draw_rgb_32_image               (GdkDrawable *drawable,
                                                         GdkGC *gc,
                                                         gint x,
                                                         gint y,
                                                         gint width,
                                                         gint height,
                                                         GdkRgbDither dith,
                                                         guchar *buf,
                                                         gint rowstride);
void                gdk_draw_rgb_32_image_dithalign     (GdkDrawable *drawable,
                                                         GdkGC *gc,
                                                         gint x,
                                                         gint y,
                                                         gint width,
                                                         gint height,
                                                         GdkRgbDither dith,
                                                         guchar *buf,
                                                         gint rowstride,
                                                         gint xdith,
                                                         gint ydith);
enum                GdkRgbDither;

GdkRgbCmap*         gdk_rgb_cmap_new                    (guint32 *colors,
                                                         gint n_colors);
void                gdk_rgb_cmap_free                   (GdkRgbCmap *cmap);
                    GdkRgbCmap;

void                gdk_rgb_gc_set_foreground           (GdkGC *gc,
                                                         guint32 rgb);
void                gdk_rgb_gc_set_background           (GdkGC *gc,
                                                         guint32 rgb);
gulong              gdk_rgb_xpixel_from_rgb             (guint32 rgb);
void                gdk_rgb_find_color                  (GdkColormap *colormap,
                                                         GdkColor *color);

void                gdk_rgb_set_install                 (gboolean install);
void                gdk_rgb_set_min_colors              (gint min_colors);
GdkVisual*          gdk_rgb_get_visual                  (void);
GdkColormap*        gdk_rgb_get_colormap                (void);
#define             gdk_rgb_get_cmap
gboolean            gdk_rgb_ditherable                  (void);
gboolean            gdk_rgb_colormap_ditherable         (GdkColormap *cmap);
void                gdk_rgb_set_verbose                 (gboolean verbose);

Description

GdkRGB is a low-level module which renders RGB, grayscale, and indexed colormap images to a GdkDrawable. It does this as efficiently as possible, handling issues such as colormaps, visuals, dithering, temporary buffers, and so on. Most code should use the higher-level GdkPixbuf features in place of this module; for example, gdk_pixbuf_render_to_drawable() uses GdkRGB in its implementation.

GdkRGB allocates a color cube to use when rendering images. You can set the threshold for installing colormaps with gdk_rgb_set_min_colors(). The default is 5x5x5 (125). If a colorcube of this size or larger can be allocated in the default colormap, then that's done. Otherwise, GdkRGB creates its own private colormap. Setting it to 0 means that it always tries to use the default colormap, and setting it to 216 means that it always creates a private one if it cannot allocate the 6x6x6 colormap in the default. If you always want a private colormap (to avoid consuming too many colormap entries for other apps, say), you can use gdk_rgb_set_install(TRUE). Setting the value greater than 216 exercises a bug in older versions of GdkRGB. Note, however, that setting it to 0 doesn't let you get away with ignoring the colormap and visual - a colormap is always created in grayscale and direct color modes, and the visual is changed in cases where a "better" visual than the default is available.

Example 4. A simple example program using GdkRGB

#include <gtk/gtk.h>

#define IMAGE_WIDTH	256
#define IMAGE_HEIGHT	256

guchar rgbbuf[IMAGE_WIDTH * IMAGE_HEIGHT * 3];

gboolean on_darea_expose (GtkWidget *widget,
              GdkEventExpose *event,
              gpointer user_data);

int
main (int argc, char *argv[])
{
  GtkWidget *window, *darea;
  gint x, y;
  guchar *pos;

  gtk_init (&argc, &argv);

  window = gtk_window_new (GTK_WINDOW_TOPLEVEL);
  darea = gtk_drawing_area_new ();
  gtk_widget_set_size_request (darea, IMAGE_WIDTH, IMAGE_HEIGHT);
  gtk_container_add (GTK_CONTAINER (window), darea);
  gtk_signal_connect (GTK_OBJECT (darea), "expose-event",
                      GTK_SIGNAL_FUNC (on_darea_expose), NULL);
  gtk_widget_show_all (window);

  /* Set up the RGB buffer. */
  pos = rgbbuf;
  for (y = 0; y < IMAGE_HEIGHT; y++)
    {
      for (x = 0; x < IMAGE_WIDTH; x++)
    {
      *pos++ = x - x % 32;			/* Red. */
      *pos++ = (x / 32) * 4 + y - y % 32;	/* Green. */
      *pos++ = y - y % 32;			/* Blue. */
    }
    }

  gtk_main ();
  return 0;
}

gboolean
on_darea_expose (GtkWidget *widget,
         GdkEventExpose *event,
         gpointer user_data)
{
  gdk_draw_rgb_image (widget->window, widget->style->fg_gc[GTK_STATE_NORMAL],
              0, 0, IMAGE_WIDTH, IMAGE_HEIGHT,
              GDK_RGB_DITHER_MAX, rgbbuf, IMAGE_WIDTH * 3);

  return TRUE;
}

Details

gdk_rgb_init ()

void                gdk_rgb_init                        (void);

Warning

gdk_rgb_init is deprecated and should not be used in newly-written code.

This function no longer does anything at all. It's completely useless (and harmless).

gdk_draw_rgb_image ()

void                gdk_draw_rgb_image                  (GdkDrawable *drawable,
                                                         GdkGC *gc,
                                                         gint x,
                                                         gint y,
                                                         gint width,
                                                         gint height,
                                                         GdkRgbDither dith,
                                                         guchar *rgb_buf,
                                                         gint rowstride);

Draws an RGB image in the drawable. This is the core GdkRGB function, and likely the only one you will need to use.

The rowstride parameter allows for lines to be aligned more flexibly. For example, lines may be allocated to begin on 32-bit boundaries, even if the width of the rectangle is odd. Rowstride is also useful when drawing a subrectangle of a larger image in memory. Finally, to replicate the same line a number of times, the trick of setting rowstride to 0 is allowed.

In general, for 0 <= i < width and 0 <= j < height, the pixel (x + i, y + j) is colored with red value rgb_buf[j * rowstride + i * 3], green value rgb_buf[j * rowstride + i * 3 + 1], and blue value rgb_buf[j * rowstride + i * 3 + 2].

drawable : | The GdkDrawable to draw in (usually a GdkWindow).
gc : | The graphics context (all GDK drawing operations require one; its contents are ignored).
x : | The x coordinate of the top-left corner in the drawable.
y : | The y coordinate of the top-left corner in the drawable.
width : | The width of the rectangle to be drawn.
height : | The height of the rectangle to be drawn.
dith : | A GdkRgbDither value, selecting the desired dither mode.
rgb_buf : | The pixel data, represented as packed 24-bit data.
rowstride : | The number of bytes from the start of one row in rgb_buf to the start of the next.

gdk_draw_rgb_image_dithalign ()

void                gdk_draw_rgb_image_dithalign        (GdkDrawable *drawable,
                                                         GdkGC *gc,
                                                         gint x,
                                                         gint y,
                                                         gint width,
                                                         gint height,
                                                         GdkRgbDither dith,
                                                         guchar *rgb_buf,
                                                         gint rowstride,
                                                         gint xdith,
                                                         gint ydith);

Draws an RGB image in the drawable, with an adjustment for dither alignment.

This function is useful when drawing dithered images into a window that may be scrolled. Pixel (x, y) will be drawn dithered as if its actual location is (x + xdith, y + ydith). Thus, if you draw an image into a window using zero dither alignment, then scroll up one pixel, subsequent draws to the window should have ydith = 1.

Setting the dither alignment correctly allows updating of small parts of the screen while avoiding visible "seams" between the different dither textures.

drawable : | The GdkDrawable to draw in (usually a GdkWindow).
gc : | The graphics context.
x : | The x coordinate of the top-left corner in the drawable.
y : | The y coordinate of the top-left corner in the drawable.
width : | The width of the rectangle to be drawn.
height : | The height of the rectangle to be drawn.
dith : | A GdkRgbDither value, selecting the desired dither mode.
rgb_buf : | The pixel data, represented as packed 24-bit data.
rowstride : | The number of bytes from the start of one row in rgb_buf to the start of the next.
xdith : | An x offset for dither alignment.
ydith : | A y offset for dither alignment.

gdk_draw_indexed_image ()

void                gdk_draw_indexed_image              (GdkDrawable *drawable,
                                                         GdkGC *gc,
                                                         gint x,
                                                         gint y,
                                                         gint width,
                                                         gint height,
                                                         GdkRgbDither dith,
                                                         guchar *buf,
                                                         gint rowstride,
                                                         GdkRgbCmap *cmap);

Draws an indexed image in the drawable, using a GdkRgbCmap to assign actual colors to the color indices.

drawable : | The GdkDrawable to draw in (usually a GdkWindow).
gc : | The graphics context.
x : | The x coordinate of the top-left corner in the drawable.
y : | The y coordinate of the top-left corner in the drawable.
width : | The width of the rectangle to be drawn.
height : | The height of the rectangle to be drawn.
dith : | A GdkRgbDither value, selecting the desired dither mode.
buf : | The pixel data, represented as 8-bit color indices.
rowstride : | The number of bytes from the start of one row in buf to the start of the next.
cmap : | The GdkRgbCmap used to assign colors to the color indices.

gdk_draw_gray_image ()

void                gdk_draw_gray_image                 (GdkDrawable *drawable,
                                                         GdkGC *gc,
                                                         gint x,
                                                         gint y,
                                                         gint width,
                                                         gint height,
                                                         GdkRgbDither dith,
                                                         guchar *buf,
                                                         gint rowstride);

Draws a grayscale image in the drawable.

drawable : | The GdkDrawable to draw in (usually a GdkWindow).
gc : | The graphics context.
x : | The x coordinate of the top-left corner in the drawable.
y : | The y coordinate of the top-left corner in the drawable.
width : | The width of the rectangle to be drawn.
height : | The height of the rectangle to be drawn.
dith : | A GdkRgbDither value, selecting the desired dither mode.
buf : | The pixel data, represented as 8-bit gray values.
rowstride : | The number of bytes from the start of one row in buf to the start of the next.

gdk_draw_rgb_32_image ()

void                gdk_draw_rgb_32_image               (GdkDrawable *drawable,
                                                         GdkGC *gc,
                                                         gint x,
                                                         gint y,
                                                         gint width,
                                                         gint height,
                                                         GdkRgbDither dith,
                                                         guchar *buf,
                                                         gint rowstride);

Draws a padded RGB image in the drawable. The image is stored as one pixel per 32-bit word. It is laid out as a red byte, a green byte, a blue byte, and a padding byte.

It's unlikely that this function will give significant performance gains in practice. In my experience, the performance gain from having pixels aligned to 32-bit boundaries is cancelled out by the increased memory bandwidth.

drawable : | The GdkDrawable to draw in (usually a GdkWindow).
gc : | The graphics context.
x : | The x coordinate of the top-left corner in the drawable.
y : | The y coordinate of the top-left corner in the drawable.
width : | The width of the rectangle to be drawn.
height : | The height of the rectangle to be drawn.
dith : | A GdkRgbDither value, selecting the desired dither mode.
buf : | The pixel data, represented as padded 32-bit data.
rowstride : | The number of bytes from the start of one row in buf to the start of the next.

gdk_draw_rgb_32_image_dithalign ()

void                gdk_draw_rgb_32_image_dithalign     (GdkDrawable *drawable,
                                                         GdkGC *gc,
                                                         gint x,
                                                         gint y,
                                                         gint width,
                                                         gint height,
                                                         GdkRgbDither dith,
                                                         guchar *buf,
                                                         gint rowstride,
                                                         gint xdith,
                                                         gint ydith);

Like gdk_draw_rgb_32_image(), but allows you to specify the dither offsets. See gdk_draw_rgb_image_dithalign() for more details.

drawable : | a GdkDrawable
gc : | a GdkGC
x : | X coordinate on drawable where image should go
y : | Y coordinate on drawable where image should go
width : | width of area of image to draw
height : | height of area of image to draw
dith : | dithering mode
buf : | RGB image data
rowstride : | rowstride of RGB image data
xdith : | X dither offset
ydith : | Y dither offset

enum GdkRgbDither

typedef enum
{
  GDK_RGB_DITHER_NONE,
  GDK_RGB_DITHER_NORMAL,
  GDK_RGB_DITHER_MAX
} GdkRgbDither;

Selects whether or not GdkRGB applies dithering to the image on display.

Since GdkRGB currently only handles images with 8 bits per component, dithering on 24 bit per pixel displays is a moot point.

GDK_RGB_DITHER_NONE | Never use dithering.
GDK_RGB_DITHER_NORMAL | Use dithering in 8 bits per pixel (and below) only.
GDK_RGB_DITHER_MAX | Use dithering in 16 bits per pixel and below.

gdk_rgb_cmap_new ()

GdkRgbCmap*         gdk_rgb_cmap_new                    (guint32 *colors,
                                                         gint n_colors);

Creates a new GdkRgbCmap structure. The cmap maps color indexes to RGB colors. If n_colors is less than 256, then images containing color values greater than or equal to n_colors will produce undefined results, including possibly segfaults.

colors : | The colors, represented as 0xRRGGBB integer values.
n_colors : | The number of colors in the cmap.
Returns : | The newly created GdkRgbCmap

gdk_rgb_cmap_free ()

void                gdk_rgb_cmap_free                   (GdkRgbCmap *cmap);

Frees the memory associated with a GdkRgbCmap created by gdk_rgb_cmap_new().

cmap : The GdkRgbCmap to free.

GdkRgbCmap

typedef struct {
  guint32 colors[256];
  gint n_colors;
} GdkRgbCmap;

A private data structure which maps color indices to actual RGB colors. This is used only for gdk_draw_indexed_image().

gdk_rgb_gc_set_foreground ()

void                gdk_rgb_gc_set_foreground           (GdkGC *gc,
                                                         guint32 rgb);

Warning

gdk_rgb_gc_set_foreground is deprecated and should not be used in newly-written code.

Sets the foreground color in gc to the specified color (or the closest approximation, in the case of limited visuals).

gc : | The GdkGC to modify.
rgb : | The color, represented as a 0xRRGGBB integer value.

gdk_rgb_gc_set_background ()

void                gdk_rgb_gc_set_background           (GdkGC *gc,
                                                         guint32 rgb);

Warning

gdk_rgb_gc_set_background is deprecated and should not be used in newly-written code.

Sets the background color in gc to the specified color (or the closest approximation, in the case of limited visuals).

gc : | The GdkGC to modify.
rgb : | The color, represented as a 0xRRGGBB integer value.

gdk_rgb_xpixel_from_rgb ()

gulong              gdk_rgb_xpixel_from_rgb             (guint32 rgb);

Warning

gdk_rgb_xpixel_from_rgb is deprecated and should not be used in newly-written code.

Finds the X pixel closest in color to the rgb color specified. This value may be used to set the pixel field of a GdkColor struct.

rgb : | The color, represented as a 0xRRGGBB integer value.
Returns : | The X pixel value.

gdk_rgb_find_color ()

void                gdk_rgb_find_color                  (GdkColormap *colormap,
                                                         GdkColor *color);

colormap should be the colormap for the graphics context and drawable you're using to draw. If you're drawing to a GtkWidget, call gtk_widget_get_colormap().

color should have its red, green, and blue fields initialized; gdk_rgb_find_color() will fill in the pixel field with the best matching pixel from a color cube. The color is then ready to be used for drawing, e.g. you can call gdk_gc_set_foreground() which expects pixel to be initialized.

In many cases, you can avoid this whole issue by calling gdk_gc_set_rgb_fg_color() or gdk_gc_set_rgb_bg_color(), which do not expect pixel to be initialized in advance. If you use those functions, there's no need for gdk_rgb_find_color().

colormap : | a GdkColormap
color : | a GdkColor

gdk_rgb_set_install ()

void                gdk_rgb_set_install                 (gboolean install);

If install is TRUE, directs GdkRGB to always install a new "private" colormap rather than trying to find a best fit with the colors already allocated. Ordinarily, GdkRGB will install a colormap only if a sufficient cube cannot be allocated.

A private colormap has more colors, leading to better quality display, but also leads to the dreaded "colormap flashing" effect.

install : TRUE to set install mode.

gdk_rgb_set_min_colors ()

void                gdk_rgb_set_min_colors              (gint min_colors);

Sets the minimum number of colors for the color cube. Generally, GdkRGB tries to allocate the largest color cube it can. If it can't allocate a color cube at least as large as min_colors, it installs a private colormap.

min_colors : The minimum number of colors accepted.

gdk_rgb_get_visual ()

GdkVisual*          gdk_rgb_get_visual                  (void);

Gets a "preferred visual" chosen by GdkRGB for rendering image data on the default screen. In previous versions of GDK, this was the only visual GdkRGB could use for rendering. In current versions, it's simply the visual GdkRGB would have chosen as the optimal one in those previous versions. GdkRGB can now render to drawables with any visual.

Returns : The GdkVisual chosen by GdkRGB.

gdk_rgb_get_colormap ()

GdkColormap*        gdk_rgb_get_colormap                (void);

Get the preferred colormap for rendering image data. Not a very useful function; historically, GDK could only render RGB image data to one colormap and visual, but in the current version it can render to any colormap and visual. So there's no need to call this function.

Returns : the preferred colormap

gdk_rgb_get_cmap

#define gdk_rgb_get_cmap               gdk_rgb_get_colormap

Warning

gdk_rgb_get_cmap is deprecated and should not be used in newly-written code.

Gets the colormap set by GdkRGB. This colormap and the corresponding visual should be used when creating windows that will be drawn in by GdkRGB.

Returns : The GdkColormap set by GdkRGB.

gdk_rgb_ditherable ()

gboolean            gdk_rgb_ditherable                  (void);

Determines whether the preferred visual is ditherable. This function may be useful for presenting a user interface choice to the user about which dither mode is desired; if the display is not ditherable, it may make sense to gray out or hide the corresponding UI widget.

Returns : TRUE if the preferred visual is ditherable.

gdk_rgb_colormap_ditherable ()

gboolean            gdk_rgb_colormap_ditherable         (GdkColormap *cmap);

Determines whether the visual associated with cmap is ditherable. This function may be useful for presenting a user interface choice to the user about which dither mode is desired; if the display is not ditherable, it may make sense to gray out or hide the corresponding UI widget.

cmap : | a GdkColormap
Returns : | TRUE if the visual associated with cmap is ditherable.

gdk_rgb_set_verbose ()

void                gdk_rgb_set_verbose                 (gboolean verbose);

Sets the "verbose" flag. This is generally only useful for debugging.

verbose : TRUE if verbose messages are desired.

See Also

GdkColor | The underlying GDK mechanism for allocating colors.
GdkPixbuf and gdk_pixbuf_render_to_drawable() | Higher-level image handling.


General

General — Library initialization and miscellaneous functions

Synopsis

#include <gdk/gdk.h>

void                gdk_init                            (gint *argc,
                                                         gchar ***argv);
gboolean            gdk_init_check                      (gint *argc,
                                                         gchar ***argv);
void                gdk_parse_args                      (gint *argc,
                                                         gchar ***argv);
const gchar*        gdk_get_display_arg_name            (void);
gchar*              gdk_set_locale                      (void);
void                gdk_set_sm_client_id                (const gchar *sm_client_id);
void                gdk_exit                            (gint error_code);
void                gdk_notify_startup_complete         (void);

const char*         gdk_get_program_class               (void);
void                gdk_set_program_class               (const char *program_class);

gchar*              gdk_get_display                     (void);

void                gdk_flush                           (void);

gint                gdk_screen_width                    (void);
gint                gdk_screen_height                   (void);
gint                gdk_screen_width_mm                 (void);
gint                gdk_screen_height_mm                (void);

GdkGrabStatus       gdk_pointer_grab                    (GdkWindow *window,
                                                         gboolean owner_events,
                                                         GdkEventMask event_mask,
                                                         GdkWindow *confine_to,
                                                         GdkCursor *cursor,
                                                         guint32 time_);
enum                GdkGrabStatus;
void                gdk_pointer_ungrab                  (guint32 time_);
gboolean            gdk_pointer_is_grabbed              (void);
void                gdk_set_double_click_time           (guint msec);

GdkGrabStatus       gdk_keyboard_grab                   (GdkWindow *window,
                                                         gboolean owner_events,
                                                         guint32 time_);
void                gdk_keyboard_ungrab                 (guint32 time_);

void                gdk_beep                            (void);

gboolean            gdk_get_use_xshm                    (void);
void                gdk_set_use_xshm                    (gboolean use_xshm);

void                gdk_error_trap_push                 (void);
gint                gdk_error_trap_pop                  (void);

#define             GDK_WINDOWING_X11
#define             GDK_WINDOWING_WIN32
#define             GDK_WINDOWING_FB

Description

This section describes the GDK initialization functions and miscellaneous utility functions.

Details

gdk_init ()

void                gdk_init                            (gint *argc,
                                                         gchar ***argv);

Initializes the GDK library and connects to the X server. If initialization fails, a warning message is output and the application terminates with a call to exit(1).

Any arguments used by GDK are removed from the array and argc and argv are updated accordingly.

GTK+ initializes GDK in gtk_init() and so this function is not usually needed by GTK+ applications.

argc : | the number of command line arguments.
argv : | the array of command line arguments.

gdk_init_check ()

gboolean            gdk_init_check                      (gint *argc,
                                                         gchar ***argv);

Initializes the GDK library and connects to the X server, returning TRUE on success.

Any arguments used by GDK are removed from the array and argc and argv are updated accordingly.

GTK+ initializes GDK in gtk_init() and so this function is not usually needed by GTK+ applications.

argc : | the number of command line arguments.
argv : | the array of command line arguments.
Returns : | TRUE if initialization succeeded.

gdk_parse_args ()

void                gdk_parse_args                      (gint *argc,
                                                         gchar ***argv);

Parse command line arguments, and store for future use by calls to gdk_display_open().

Any arguments used by GDK are removed from the array and argc and argv are updated accordingly.

You shouldn't call this function explicitely if you are using gtk_init(), gtk_init_check(), gdk_init(), or gdk_init_check().

argc : | the number of command line arguments.
argv : | the array of command line arguments.

Since 2.2

gdk_get_display_arg_name ()

const gchar*        gdk_get_display_arg_name            (void);

Gets the display name specified in the command line arguments passed to gdk_init() or gdk_parse_args(), if any.

Returns : the display name, if specified explicitely, otherwise NULL this string is owned by GTK+ and must not be modified or freed.

Since 2.2

gdk_set_locale ()

gchar*              gdk_set_locale                      (void);

Initializes the support for internationalization by calling the setlocale() system call. This function is called by gtk_set_locale() and so GTK+ applications should use that instead.

The locale to use is determined by the LANG environment variable, so to run an application in a certain locale you can do something like this:

  export LANG="fr"
  ... run application ...

If the locale is not supported by X then it is reset to the standard "C" locale.

Returns : the resulting locale.

gdk_set_sm_client_id ()

void                gdk_set_sm_client_id                (const gchar *sm_client_id);

Sets the SM_CLIENT_ID property on the application's leader window so that the window manager can save the application's state using the X11R6 ICCCM session management protocol.

See the X Session Management Library documentation for more information on session management and the Inter-Client Communication Conventions Manual (ICCCM) for information on the WM_CLIENT_LEADER property. (Both documents are part of the X Window System distribution.)

sm_client_id : the client id assigned by the session manager when the connection was opened, or NULL to remove the property.

gdk_exit ()

void                gdk_exit                            (gint error_code);

Warning

gdk_exit is deprecated and should not be used in newly-written code.

Exits the application using the exit() system call.

This routine is provided mainly for backwards compatibility, since it used to perform tasks necessary to exit the application cleanly. Those tasks are now performed in a function which is automatically called on exit (via the use of g_atexit()).

error_code : the error code to pass to the exit() call.

gdk_notify_startup_complete ()

void                gdk_notify_startup_complete         (void);

Indicates to the GUI environment that the application has finished loading. If the applications opens windows, this function is normally called after opening the application's initial set of windows.

GTK+ will call this function automatically after opening the first GtkWindow unless gtk_window_set_auto_startup_notification() is called to disable that feature.

Since 2.2

gdk_get_program_class ()

const char*         gdk_get_program_class               (void);

Gets the program class. Unless the program class has explicitly been set with gdk_set_program_class() or with the --class commandline option, the default value is the program name (determined with g_get_prgname()) with the first character converted to uppercase.

Returns : the program class.

gdk_set_program_class ()

void                gdk_set_program_class               (const char *program_class);

Sets the program class. The X11 backend uses the program class to set the class name part of the WM_CLASS property on toplevel windows; see the ICCCM.

program_class : a string.

gdk_get_display ()

gchar*              gdk_get_display                     (void);

Gets the name of the display, which usually comes from the DISPLAY environment variable or the --display command line option.

Returns : the name of the display.

gdk_flush ()

void                gdk_flush                           (void);

Flushes the X output buffer and waits until all requests have been processed by the server. This is rarely needed by applications. It's main use is for trapping X errors with gdk_error_trap_push() and gdk_error_trap_pop().

gdk_screen_width ()

gint                gdk_screen_width                    (void);

Returns the width of the default screen in pixels.

Returns : the width of the default screen in pixels.

gdk_screen_height ()

gint                gdk_screen_height                   (void);

Returns the height of the default screen in pixels.

Returns : the height of the default screen in pixels.

gdk_screen_width_mm ()

gint                gdk_screen_width_mm                 (void);

Returns the width of the default screen in millimeters. Note that on many X servers this value will not be correct.

Returns : the width of the default screen in millimeters, though it is not always correct.

gdk_screen_height_mm ()

gint                gdk_screen_height_mm                (void);

Returns the height of the default screen in millimeters. Note that on many X servers this value will not be correct.

Returns : the height of the default screen in millimeters, though it is not always correct.

gdk_pointer_grab ()

GdkGrabStatus       gdk_pointer_grab                    (GdkWindow *window,
                                                         gboolean owner_events,
                                                         GdkEventMask event_mask,
                                                         GdkWindow *confine_to,
                                                         GdkCursor *cursor,
                                                         guint32 time_);

Grabs the pointer (usually a mouse) so that all events are passed to this application until the pointer is ungrabbed with gdk_pointer_ungrab(), or the grab window becomes unviewable. This overrides any previous pointer grab by this client.

Pointer grabs are used for operations which need complete control over mouse events, even if the mouse leaves the application. For example in GTK+ it is used for Drag and Drop, for dragging the handle in the GtkHPaned and GtkVPaned widgets, and for resizing columns in GtkCList widgets.

Note that if the event mask of an X window has selected both button press and button release events, then a button press event will cause an automatic pointer grab until the button is released. X does this automatically since most applications expect to receive button press and release events in pairs. It is equivalent to a pointer grab on the window with owner_events set to TRUE.

If you set up anything at the time you take the grab that needs to be cleaned up when the grab ends, you should handle the GdkEventGrabBroken events that are emitted when the grab ends unvoluntarily.

window : | the GdkWindow which will own the grab (the grab window).
owner_events : | if FALSE then all pointer events are reported with respect to window and are only reported if selected by event_mask. If TRUE then pointer events for this application are reported as normal, but pointer events outside this application are reported with respect to window and only if selected by event_mask. In either mode, unreported events are discarded.
event_mask : | specifies the event mask, which is used in accordance with owner_events. Note that only pointer events (i.e. button and motion events) may be selected.
confine_to : | If non-NULL, the pointer will be confined to this window during the grab. If the pointer is outside confine_to, it will automatically be moved to the closest edge of confine_to and enter and leave events will be generated as necessary.
cursor : | the cursor to display while the grab is active. If this is NULL then the normal cursors are used for window and its descendants, and the cursor for window is used for all other windows.
time_ : | the timestamp of the event which led to this pointer grab. This usually comes from a GdkEventButton struct, though GDK_CURRENT_TIME can be used if the time isn't known.
Returns : | GDK_GRAB_SUCCESS if the grab was successful.

enum GdkGrabStatus

typedef enum
{
  GDK_GRAB_SUCCESS         = 0,
  GDK_GRAB_ALREADY_GRABBED = 1,
  GDK_GRAB_INVALID_TIME    = 2,
  GDK_GRAB_NOT_VIEWABLE    = 3,
  GDK_GRAB_FROZEN          = 4
} GdkGrabStatus;

Returned by gdk_pointer_grab() and gdk_keyboard_grab() to indicate success or the reason for the failure of the grab attempt.

GDK_GRAB_SUCCESS | the resource was successfully grabbed.
GDK_GRAB_ALREADY_GRABBED | the resource is actively grabbed by another client.
GDK_GRAB_INVALID_TIME | the resource was grabbed more recently than the specified time.
GDK_GRAB_NOT_VIEWABLE | the grab window or the confine_to window are not viewable.
GDK_GRAB_FROZEN | the resource is frozen by an active grab of another client.

gdk_pointer_ungrab ()

void                gdk_pointer_ungrab                  (guint32 time_);

Ungrabs the pointer, if it is grabbed by this application.

time_ : a timestamp from a GdkEvent, or GDK_CURRENT_TIME if no timestamp is available.

gdk_pointer_is_grabbed ()

gboolean            gdk_pointer_is_grabbed              (void);

Returns TRUE if the pointer is currently grabbed by this application.

Note that this does not take the inmplicit pointer grab on button presses into account.

Returns : TRUE if the pointer is currently grabbed by this application.*

gdk_set_double_click_time ()

void                gdk_set_double_click_time           (guint msec);

Set the double click time for the default display. See gdk_display_set_double_click_time(). See also gdk_display_set_double_click_distance(). Applications should not set this, it is a global user-configured setting.

msec : double click time in milliseconds (thousandths of a second)

gdk_keyboard_grab ()

GdkGrabStatus       gdk_keyboard_grab                   (GdkWindow *window,
                                                         gboolean owner_events,
                                                         guint32 time_);

Grabs the keyboard so that all events are passed to this application until the keyboard is ungrabbed with gdk_keyboard_ungrab(). This overrides any previous keyboard grab by this client.

If you set up anything at the time you take the grab that needs to be cleaned up when the grab ends, you should handle the GdkEventGrabBroken events that are emitted when the grab ends unvoluntarily.

window : | the GdkWindow which will own the grab (the grab window).
owner_events : | if FALSE then all keyboard events are reported with respect to window. If TRUE then keyboard events for this application are reported as normal, but keyboard events outside this application are reported with respect to window. Both key press and key release events are always reported, independant of the event mask set by the application.
time_ : | a timestamp from a GdkEvent, or GDK_CURRENT_TIME if no timestamp is available.
Returns : | GDK_GRAB_SUCCESS if the grab was successful.

gdk_keyboard_ungrab ()

void                gdk_keyboard_ungrab                 (guint32 time_);

Ungrabs the keyboard, if it is grabbed by this application.

time_ : a timestamp from a GdkEvent, or GDK_CURRENT_TIME if no timestamp is available.

gdk_beep ()

void                gdk_beep                            (void);

Emits a short beep on the default display.

gdk_get_use_xshm ()

gboolean            gdk_get_use_xshm                    (void);

Warning

gdk_get_use_xshm is deprecated and should not be used in newly-written code.

Returns TRUE if GDK will attempt to use the MIT-SHM shared memory extension.

The shared memory extension is used for GdkImage, and consequently for GdkRGB. It enables much faster drawing by communicating with the X server through SYSV shared memory calls. However, it can only be used if the X client and server are on the same machine and the server supports it.

Returns : TRUE if use of the MIT shared memory extension will be attempted.

gdk_set_use_xshm ()

void                gdk_set_use_xshm                    (gboolean use_xshm);

Warning

gdk_set_use_xshm is deprecated and should not be used in newly-written code.

Sets whether the use of the MIT shared memory extension should be attempted. This function is mainly for internal use. It is only safe for an application to set this to FALSE, since if it is set to TRUE and the server does not support the extension it may cause warning messages to be output.

use_xshm : TRUE if use of the MIT shared memory extension should be attempted.

gdk_error_trap_push ()

void                gdk_error_trap_push                 (void);

This function allows X errors to be trapped instead of the normal behavior of exiting the application. It should only be used if it is not possible to avoid the X error in any other way.

Example 1. Trapping an X error

  gdk_error_trap_push ();

  /* ... Call the X function which may cause an error here ... */

  /* Flush the X queue to catch errors now. */
  gdk_flush ();

  if (gdk_error_trap_pop ())
    {
      /* ... Handle the error here ... */
    }

gdk_error_trap_pop ()

gint                gdk_error_trap_pop                  (void);

Removes the X error trap installed with gdk_error_trap_push().

Returns : the X error code, or 0 if no error occurred.

GDK_WINDOWING_X11

#define GDK_WINDOWING_X11

This macro is defined if GDK is configured to use the X backend.

GDK_WINDOWING_WIN32

#define GDK_WINDOWING_WIN32

This macro is defined if GDK is configured to use the Win32 backend.

GDK_WINDOWING_FB

#define GDK_WINDOWING_FB

This macro is defined if GDK is configured to use the Linux framebuffer backend.


Graphics Contexts

Graphics Contexts — Objects to encapsulate drawing properties

Synopsis

#include <gdk/gdk.h>

                    GdkGC;
                    GdkGCValues;
enum                GdkGCValuesMask;
enum                GdkFunction;
GdkGC*              gdk_gc_new                          (GdkDrawable *drawable);
GdkGC*              gdk_gc_new_with_values              (GdkDrawable *drawable,
                                                         GdkGCValues *values,
                                                         GdkGCValuesMask values_mask);
GdkScreen*          gdk_gc_get_screen                   (GdkGC *gc);
GdkGC*              gdk_gc_ref                          (GdkGC *gc);
void                gdk_gc_unref                        (GdkGC *gc);
#define             gdk_gc_destroy
void                gdk_gc_set_values                   (GdkGC *gc,
                                                         GdkGCValues *values,
                                                         GdkGCValuesMask values_mask);
void                gdk_gc_get_values                   (GdkGC *gc,
                                                         GdkGCValues *values);
void                gdk_gc_set_foreground               (GdkGC *gc,
                                                         const GdkColor *color);
void                gdk_gc_set_background               (GdkGC *gc,
                                                         const GdkColor *color);
void                gdk_gc_set_rgb_fg_color             (GdkGC *gc,
                                                         const GdkColor *color);
void                gdk_gc_set_rgb_bg_color             (GdkGC *gc,
                                                         const GdkColor *color);
void                gdk_gc_set_font                     (GdkGC *gc,
                                                         GdkFont *font);
void                gdk_gc_set_function                 (GdkGC *gc,
                                                         GdkFunction function);
void                gdk_gc_set_fill                     (GdkGC *gc,
                                                         GdkFill fill);
enum                GdkFill;
void                gdk_gc_set_tile                     (GdkGC *gc,
                                                         GdkPixmap *tile);
void                gdk_gc_set_stipple                  (GdkGC *gc,
                                                         GdkPixmap *stipple);
void                gdk_gc_set_ts_origin                (GdkGC *gc,
                                                         gint x,
                                                         gint y);
void                gdk_gc_set_clip_origin              (GdkGC *gc,
                                                         gint x,
                                                         gint y);
void                gdk_gc_set_clip_mask                (GdkGC *gc,
                                                         GdkBitmap *mask);
void                gdk_gc_set_clip_rectangle           (GdkGC *gc,
                                                         GdkRectangle *rectangle);
void                gdk_gc_set_clip_region              (GdkGC *gc,
                                                         GdkRegion *region);
void                gdk_gc_set_subwindow                (GdkGC *gc,
                                                         GdkSubwindowMode mode);
enum                GdkSubwindowMode;
void                gdk_gc_set_exposures                (GdkGC *gc,
                                                         gboolean exposures);
void                gdk_gc_set_line_attributes          (GdkGC *gc,
                                                         gint line_width,
                                                         GdkLineStyle line_style,
                                                         GdkCapStyle cap_style,
                                                         GdkJoinStyle join_style);
enum                GdkLineStyle;
enum                GdkCapStyle;
enum                GdkJoinStyle;
void                gdk_gc_set_dashes                   (GdkGC *gc,
                                                         gint dash_offset,
                                                         gint8 dash_list[],
                                                         gint n);
void                gdk_gc_copy                         (GdkGC *dst_gc,
                                                         GdkGC *src_gc);
void                gdk_gc_set_colormap                 (GdkGC *gc,
                                                         GdkColormap *colormap);
GdkColormap*        gdk_gc_get_colormap                 (GdkGC *gc);
void                gdk_gc_offset                       (GdkGC *gc,
                                                         gint x_offset,
                                                         gint y_offset);

Object Hierarchy

  GObject
   +----GdkGC

Description

All drawing operations in GDK take a graphics context (GC) argument. A graphics context encapsulates information about the way things are drawn, such as the foreground color or line width. By using graphics contexts, the number of arguments to each drawing call is greatly reduced, and communication overhead is minimized, since identical arguments do not need to be passed repeatedly.

Most values of a graphics context can be set at creation time by using gdk_gc_new_with_values(), or can be set one-by-one using functions such as gdk_gc_set_foreground(). A few of the values in the GC, such as the dash pattern, can only be set by the latter method.

Details

GdkGC

typedef struct _GdkGC GdkGC;

The GdkGC structure represents a graphics context. It is an opaque structure with no user-visible elements.

GdkGCValues

typedef struct {
  GdkColor	    foreground;
  GdkColor	    background;
  GdkFont	   *font;
  GdkFunction	    function;
  GdkFill	    fill;
  GdkPixmap	   *tile;
  GdkPixmap	   *stipple;
  GdkPixmap	   *clip_mask;
  GdkSubwindowMode  subwindow_mode;
  gint		    ts_x_origin;
  gint		    ts_y_origin;
  gint		    clip_x_origin;
  gint		    clip_y_origin;
  gint		    graphics_exposures;
  gint		    line_width;
  GdkLineStyle	    line_style;
  GdkCapStyle	    cap_style;
  GdkJoinStyle	    join_style;
} GdkGCValues;

The GdkGCValues structure holds a set of values used to create or modify a graphics context.

GdkColor foreground; | the foreground color. Note that gdk_gc_get_values() only sets the pixel value.
GdkColor background; | the background color. Note that gdk_gc_get_values() only sets the pixel value.
GdkFont *font; | the default font.
GdkFunction function; | the bitwise operation used when drawing.
GdkFill fill; | the fill style.
GdkPixmap *tile; | the tile pixmap.
GdkPixmap *stipple; | the stipple bitmap.
GdkPixmap *clip_mask; | the clip mask bitmap.
GdkSubwindowMode subwindow_mode; | the subwindow mode.
gint ts_x_origin; | the x origin of the tile or stipple.
gint ts_y_origin; | the y origin of the tile or stipple.
gint clip_x_origin; | the x origin of the clip mask.
gint clip_y_origin; | the y origin of the clip mask.
gint graphics_exposures; | whether graphics exposures are enabled.
gint line_width; | the line width.
GdkLineStyle line_style; | the way dashed lines are drawn.
GdkCapStyle cap_style; | the way the ends of lines are drawn.
GdkJoinStyle join_style; | the way joins between lines are drawn.

enum GdkGCValuesMask

typedef enum
{
  GDK_GC_FOREGROUND    = 1 << 0,
  GDK_GC_BACKGROUND    = 1 << 1,
  GDK_GC_FONT	       = 1 << 2,
  GDK_GC_FUNCTION      = 1 << 3,
  GDK_GC_FILL	       = 1 << 4,
  GDK_GC_TILE	       = 1 << 5,
  GDK_GC_STIPPLE       = 1 << 6,
  GDK_GC_CLIP_MASK     = 1 << 7,
  GDK_GC_SUBWINDOW     = 1 << 8,
  GDK_GC_TS_X_ORIGIN   = 1 << 9,
  GDK_GC_TS_Y_ORIGIN   = 1 << 10,
  GDK_GC_CLIP_X_ORIGIN = 1 << 11,
  GDK_GC_CLIP_Y_ORIGIN = 1 << 12,
  GDK_GC_EXPOSURES     = 1 << 13,
  GDK_GC_LINE_WIDTH    = 1 << 14,
  GDK_GC_LINE_STYLE    = 1 << 15,
  GDK_GC_CAP_STYLE     = 1 << 16,
  GDK_GC_JOIN_STYLE    = 1 << 17
} GdkGCValuesMask;

A set of bit flags used to indicate which fields GdkGCValues structure are set.

GDK_GC_FOREGROUND | the foreground is set.
GDK_GC_BACKGROUND | the background is set.
GDK_GC_FONT | the font is set.
GDK_GC_FUNCTION | the function is set.
GDK_GC_FILL | the fill is set.
GDK_GC_TILE | the tile is set.
GDK_GC_STIPPLE | the stipple is set.
GDK_GC_CLIP_MASK | the clip_mask is set.
GDK_GC_SUBWINDOW | the subwindow_mode is set.
GDK_GC_TS_X_ORIGIN | the ts_x_origin is set.
GDK_GC_TS_Y_ORIGIN | the ts_y_origin is set.
GDK_GC_CLIP_X_ORIGIN | the clip_x_origin is set.
GDK_GC_CLIP_Y_ORIGIN | the clip_y_origin is set.
GDK_GC_EXPOSURES | the graphics_exposures is set.
GDK_GC_LINE_WIDTH | the line_width is set.
GDK_GC_LINE_STYLE | the line_style is set.
GDK_GC_CAP_STYLE | the cap_style is set.
GDK_GC_JOIN_STYLE | the join_style is set.

enum GdkFunction

typedef enum
{
  GDK_COPY,
  GDK_INVERT,
  GDK_XOR,
  GDK_CLEAR,
  GDK_AND,
  GDK_AND_REVERSE,
  GDK_AND_INVERT,
  GDK_NOOP,
  GDK_OR,
  GDK_EQUIV,
  GDK_OR_REVERSE,
  GDK_COPY_INVERT,
  GDK_OR_INVERT,
  GDK_NAND,
  GDK_NOR,
  GDK_SET
} GdkFunction;

Determines how the bit values for the source pixels are combined with the bit values for destination pixels to produce the final result. The sixteen values here correspond to the 16 different possible 2x2 truth tables. Only a couple of these values are usually useful; for colored images, only GDK_COPY, GDK_XOR and GDK_INVERT are generally useful. For bitmaps, GDK_AND and GDK_OR are also useful.

gdk_gc_new ()

GdkGC*              gdk_gc_new                          (GdkDrawable *drawable);

Create a new graphics context with default values.

drawable : | a GdkDrawable. The created GC must always be used with drawables of the same depth as this one.
Returns : | the new graphics context.

gdk_gc_new_with_values ()

GdkGC*              gdk_gc_new_with_values              (GdkDrawable *drawable,
                                                         GdkGCValues *values,
                                                         GdkGCValuesMask values_mask);

Create a new GC with the given initial values.

drawable : | a GdkDrawable. The created GC must always be used with drawables of the same depth as this one.
values : | a structure containing initial values for the GC.
values_mask : | a bit mask indicating which fields in values are set.
Returns : | the new graphics context.

gdk_gc_get_screen ()

GdkScreen*          gdk_gc_get_screen                   (GdkGC *gc);

Gets the GdkScreen for which gc was created

gc : | a GdkGC.
Returns : | the GdkScreen for gc.

Since 2.2

gdk_gc_ref ()

GdkGC*              gdk_gc_ref                          (GdkGC *gc);

Warning

gdk_gc_ref is deprecated and should not be used in newly-written code.

Deprecated function; use g_object_ref() instead.

gc : | a GdkGC
Returns : | the gc.

gdk_gc_unref ()

void                gdk_gc_unref                        (GdkGC *gc);

Warning

gdk_gc_unref is deprecated and should not be used in newly-written code. Use g_object_unref() instead.

Decrement the reference count of gc.

gc : a GdkGC

gdk_gc_destroy

#define gdk_gc_destroy                 gdk_gc_unref

Warning

gdk_gc_destroy is deprecated and should not be used in newly-written code. Use g_object_unref() instead

This function is obsolete and should not be used.

gdk_gc_set_values ()

void                gdk_gc_set_values                   (GdkGC *gc,
                                                         GdkGCValues *values,
                                                         GdkGCValuesMask values_mask);

Sets attributes of a graphics context in bulk. For each flag set in values_mask, the corresponding field will be read from values and set as the new value for gc. If you're only setting a few values on gc, calling individual "setter" functions is likely more convenient.

gc : | a GdkGC
values : | struct containing the new values
values_mask : | mask indicating which struct fields are to be used

gdk_gc_get_values ()

void                gdk_gc_get_values                   (GdkGC *gc,
                                                         GdkGCValues *values);

Retrieves the current values from a graphics context. Note that only the pixel values of the values->foreground and values->background are filled, use gdk_colormap_query_color() to obtain the rgb values if you need them.

gc : | a GdkGC.
values : | the GdkGCValues structure in which to store the results.

gdk_gc_set_foreground ()

void                gdk_gc_set_foreground               (GdkGC *gc,
                                                         const GdkColor *color);

Sets the foreground color for a graphics context. Note that this function uses color->pixel, use gdk_gc_set_rgb_fg_color() to specify the foreground color as red, green, blue components.

gc : | a GdkGC.
color : | the new foreground color.

gdk_gc_set_background ()

void                gdk_gc_set_background               (GdkGC *gc,
                                                         const GdkColor *color);

Sets the background color for a graphics context. Note that this function uses color->pixel, use gdk_gc_set_rgb_bg_color() to specify the background color as red, green, blue components.

gc : | a GdkGC.
color : | the new background color.

gdk_gc_set_rgb_fg_color ()

void                gdk_gc_set_rgb_fg_color             (GdkGC *gc,
                                                         const GdkColor *color);

Set the foreground color of a GC using an unallocated color. The pixel value for the color will be determined using GdkRGB. If the colormap for the GC has not previously been initialized for GdkRGB, then for pseudo-color colormaps (colormaps with a small modifiable number of colors), a colorcube will be allocated in the colormap.

Calling this function for a GC without a colormap is an error.

gc : | a GdkGC
color : | an unallocated GdkColor.

gdk_gc_set_rgb_bg_color ()

void                gdk_gc_set_rgb_bg_color             (GdkGC *gc,
                                                         const GdkColor *color);

Set the background color of a GC using an unallocated color. The pixel value for the color will be determined using GdkRGB. If the colormap for the GC has not previously been initialized for GdkRGB, then for pseudo-color colormaps (colormaps with a small modifiable number of colors), a colorcube will be allocated in the colormap.

Calling this function for a GC without a colormap is an error.

gc : | a GdkGC
color : | an unallocated GdkColor.

gdk_gc_set_font ()

void                gdk_gc_set_font                     (GdkGC *gc,
                                                         GdkFont *font);

Warning

gdk_gc_set_font is deprecated and should not be used in newly-written code.

Sets the font for a graphics context. (Note that all text-drawing functions in GDK take a font argument; the value set here is used when that argument is NULL.)

gc : | a GdkGC.
font : | the new font.

gdk_gc_set_function ()

void                gdk_gc_set_function                 (GdkGC *gc,
                                                         GdkFunction function);

Determines how the current pixel values and the pixel values being drawn are combined to produce the final pixel values.

gc : | a GdkGC.
function : | the GdkFunction to use

gdk_gc_set_fill ()

void                gdk_gc_set_fill                     (GdkGC *gc,
                                                         GdkFill fill);

Set the fill mode for a graphics context.

gc : | a GdkGC.
fill : | the new fill mode.

enum GdkFill

typedef enum
{
  GDK_SOLID,
  GDK_TILED,
  GDK_STIPPLED,
  GDK_OPAQUE_STIPPLED
} GdkFill;

Determines how primitives are drawn.

GDK_SOLID | draw with the foreground color.
GDK_TILED | draw with a tiled pixmap.
GDK_STIPPLED | draw using the stipple bitmap. Pixels corresponding to bits in the stipple bitmap that are set will be drawn in the foreground color; pixels corresponding to bits that are not set will be left untouched.
GDK_OPAQUE_STIPPLED | draw using the stipple bitmap. Pixels corresponding to bits in the stipple bitmap that are set will be drawn in the foreground color; pixels corresponding to bits that are not set will be drawn with the background color.

gdk_gc_set_tile ()

void                gdk_gc_set_tile                     (GdkGC *gc,
                                                         GdkPixmap *tile);

Set a tile pixmap for a graphics context. This will only be used if the fill mode is GDK_TILED.

gc : | a GdkGC.
tile : | the new tile pixmap.

gdk_gc_set_stipple ()

void                gdk_gc_set_stipple                  (GdkGC *gc,
                                                         GdkPixmap *stipple);

Set the stipple bitmap for a graphics context. The stipple will only be used if the fill mode is GDK_STIPPLED or GDK_OPAQUE_STIPPLED.

gc : | a GdkGC.
stipple : | the new stipple bitmap.

gdk_gc_set_ts_origin ()

void                gdk_gc_set_ts_origin                (GdkGC *gc,
                                                         gint x,
                                                         gint y);

Set the origin when using tiles or stipples with the GC. The tile or stipple will be aligned such that the upper left corner of the tile or stipple will coincide with this point.

gc : | a GdkGC.
x : | the x-coordinate of the origin.
y : | the y-coordinate of the origin.

gdk_gc_set_clip_origin ()

void                gdk_gc_set_clip_origin              (GdkGC *gc,
                                                         gint x,
                                                         gint y);

Sets the origin of the clip mask. The coordinates are interpreted relative to the upper-left corner of the destination drawable of the current operation.

gc : | a GdkGC.
x : | the x-coordinate of the origin.
y : | the y-coordinate of the origin.

gdk_gc_set_clip_mask ()

void                gdk_gc_set_clip_mask                (GdkGC *gc,
                                                         GdkBitmap *mask);

Sets the clip mask for a graphics context from a bitmap. The clip mask is interpreted relative to the clip origin. (See gdk_gc_set_clip_origin()).

gc : | the GdkGC.
mask : | a bitmap.

gdk_gc_set_clip_rectangle ()

void                gdk_gc_set_clip_rectangle           (GdkGC *gc,
                                                         GdkRectangle *rectangle);

Sets the clip mask for a graphics context from a rectangle. The clip mask is interpreted relative to the clip origin. (See gdk_gc_set_clip_origin()).

gc : | a GdkGC.
rectangle : | the rectangle to clip to.

gdk_gc_set_clip_region ()

void                gdk_gc_set_clip_region              (GdkGC *gc,
                                                         GdkRegion *region);

Sets the clip mask for a graphics context from a region structure. The clip mask is interpreted relative to the clip origin. (See gdk_gc_set_clip_origin()).

gc : | a GdkGC.
region : | the GdkRegion.

gdk_gc_set_subwindow ()

void                gdk_gc_set_subwindow                (GdkGC *gc,
                                                         GdkSubwindowMode mode);

Sets how drawing with this GC on a window will affect child windows of that window.

gc : | a GdkGC.
mode : | the subwindow mode.

enum GdkSubwindowMode

typedef enum
{
  GDK_CLIP_BY_CHILDREN	= 0,
  GDK_INCLUDE_INFERIORS = 1
} GdkSubwindowMode;

Determines how drawing onto a window will affect child windows of that window.

GDK_CLIP_BY_CHILDREN | only draw onto the window itself.
GDK_INCLUDE_INFERIORS | draw onto the window and child windows.

gdk_gc_set_exposures ()

void                gdk_gc_set_exposures                (GdkGC *gc,
                                                         gboolean exposures);

Sets whether copying non-visible portions of a drawable using this graphics context generate exposure events for the corresponding regions of the destination drawable. (See gdk_draw_drawable()).

gc : | a GdkGC.
exposures : | if TRUE, exposure events will be generated.

gdk_gc_set_line_attributes ()

void                gdk_gc_set_line_attributes          (GdkGC *gc,
                                                         gint line_width,
                                                         GdkLineStyle line_style,
                                                         GdkCapStyle cap_style,
                                                         GdkJoinStyle join_style);

Sets various attributes of how lines are drawn. See the corresponding members of GdkGCValues for full explanations of the arguments.

gc : | a GdkGC.
line_width : | the width of lines.
line_style : | the dash-style for lines.
cap_style : | the manner in which the ends of lines are drawn.
join_style : | the in which lines are joined together.

enum GdkLineStyle

typedef enum
{
  GDK_LINE_SOLID,
  GDK_LINE_ON_OFF_DASH,
  GDK_LINE_DOUBLE_DASH
} GdkLineStyle;

Determines how lines are drawn.

GDK_LINE_SOLID | lines are drawn solid.
GDK_LINE_ON_OFF_DASH | even segments are drawn; odd segments are not drawn.
GDK_LINE_DOUBLE_DASH | even segments are normally. Odd segments are drawn in the background color if the fill style is GDK_SOLID, or in the background color masked by the stipple if the fill style is GDK_STIPPLED.

enum GdkCapStyle

typedef enum
{
  GDK_CAP_NOT_LAST,
  GDK_CAP_BUTT,
  GDK_CAP_ROUND,
  GDK_CAP_PROJECTING
} GdkCapStyle;

Determines how the end of lines are drawn.

GDK_CAP_NOT_LAST | the same as GDK_CAP_BUTT for lines of non-zero width. for zero width lines, the final point on the line will not be drawn.
GDK_CAP_BUTT | the ends of the lines are drawn squared off and extending to the coordinates of the end point.
GDK_CAP_ROUND | the ends of the lines are drawn as semicircles with the diameter equal to the line width and centered at the end point.
GDK_CAP_PROJECTING | the ends of the lines are drawn squared off and extending half the width of the line beyond the end point.

enum GdkJoinStyle

typedef enum
{
  GDK_JOIN_MITER,
  GDK_JOIN_ROUND,
  GDK_JOIN_BEVEL
} GdkJoinStyle;

Determines how the joins between segments of a polygon are drawn.

GDK_JOIN_MITER | the sides of each line are extended to meet at an angle.
GDK_JOIN_ROUND | the sides of the two lines are joined by a circular arc.
GDK_JOIN_BEVEL | the sides of the two lines are joined by a straight line which makes an equal angle with each line.

gdk_gc_set_dashes ()

void                gdk_gc_set_dashes                   (GdkGC *gc,
                                                         gint dash_offset,
                                                         gint8 dash_list[],
                                                         gint n);

Sets the way dashed-lines are drawn. Lines will be drawn with alternating on and off segments of the lengths specified in dash_list. The manner in which the on and off segments are drawn is determined by the line_style value of the GC. (This can be changed with gdk_gc_set_line_attributes().)

The dash_offset defines the phase of the pattern, specifying how many pixels into the dash-list the pattern should actually begin.

gc : | a GdkGC.
dash_offset : | the phase of the dash pattern.
dash_list : | an array of dash lengths.
n : | the number of elements in dash_list.

gdk_gc_copy ()

void                gdk_gc_copy                         (GdkGC *dst_gc,
                                                         GdkGC *src_gc);

Copy the set of values from one graphics context onto another graphics context.

dst_gc : | the destination graphics context.
src_gc : | the source graphics context.

gdk_gc_set_colormap ()

void                gdk_gc_set_colormap                 (GdkGC *gc,
                                                         GdkColormap *colormap);

Sets the colormap for the GC to the given colormap. The depth of the colormap's visual must match the depth of the drawable for which the GC was created.

gc : | a GdkGC
colormap : | a GdkColormap

gdk_gc_get_colormap ()

GdkColormap*        gdk_gc_get_colormap                 (GdkGC *gc);

Retrieves the colormap for a given GC, if it exists. A GC will have a colormap if the drawable for which it was created has a colormap, or if a colormap was set explicitely with gdk_gc_set_colormap.

gc : | a GdkGC
Returns : | the colormap of gc, or NULL if gc doesn't have one.

gdk_gc_offset ()

void                gdk_gc_offset                       (GdkGC *gc,
                                                         gint x_offset,
                                                         gint y_offset);

Offset attributes such as the clip and tile-stipple origins of the GC so that drawing at x - x_offset, y - y_offset with the offset GC has the same effect as drawing at x, y with the original GC.

gc : | a GdkGC
x_offset : | amount by which to offset the GC in the X direction
y_offset : | amount by which to offset the GC in the Y direction


Images

Images — A client-side area for bit-mapped graphics

Synopsis

#include <gdk/gdk.h>

                    GdkImage;
GdkImage*           gdk_image_new                       (GdkImageType type,
                                                         GdkVisual *visual,
                                                         gint width,
                                                         gint height);
enum                GdkImageType;
GdkImage*           gdk_image_new_bitmap                (GdkVisual *visual,
                                                         gpointer data,
                                                         gint width,
                                                         gint height);
GdkImage*           gdk_image_get                       (GdkDrawable *drawable,
                                                         gint x,
                                                         gint y,
                                                         gint width,
                                                         gint height);
GdkImage*           gdk_image_ref                       (GdkImage *image);
void                gdk_image_unref                     (GdkImage *image);
#define             gdk_image_destroy
GdkColormap*        gdk_image_get_colormap              (GdkImage *image);
void                gdk_image_set_colormap              (GdkImage *image,
                                                         GdkColormap *colormap);

void                gdk_image_put_pixel                 (GdkImage *image,
                                                         gint x,
                                                         gint y,
                                                         guint32 pixel);
guint32             gdk_image_get_pixel                 (GdkImage *image,
                                                         gint x,
                                                         gint y);

Description

The GdkImage type represents an area for drawing graphics. It has now been superceded to a large extent by the much more flexible GdkRGB functions.

To create an empty GdkImage use gdk_image_new(). To create a GdkImage from bitmap data use gdk_image_new_bitmap(). To create an image from part of a GdkWindow use gdk_drawable_get_image().

The image can be manipulated with gdk_image_get_pixel() and gdk_image_put_pixel(), or alternatively by changing the actual pixel data. Though manipulating the pixel data requires complicated code to cope with the different formats that may be used.

To draw a GdkImage in a GdkWindow or GdkPixmap use gdk_draw_image().

To destroy a GdkImage use gdk_image_destroy().

Details

GdkImage

typedef struct {
  GObject parent_instance;

  GdkImageType	type; /* read only. */
  GdkVisual    *visual;	    /* read only. visual used to create the image */
  GdkByteOrder	byte_order; /* read only. */
  gint		width; /* read only. */
  gint		height; /* read only. */
  guint16	depth; /* read only. */
  guint16	bpp;	        /* read only. bytes per pixel */
  guint16	bpl;	        /* read only. bytes per line */
  guint16       bits_per_pixel; /* read only. bits per pixel */
  gpointer	mem;

  GdkColormap  *colormap; /* read only. */
} GdkImage;

The GdkImage struct contains information on the image and the pixel data.

GObject parent_instance; | the parent instance
GdkImageType type; | the type of the image.
GdkVisual *visual; | the visual.
GdkByteOrder byte_order; | the byte order.
gint width; | the width of the image in pixels.
gint height; | the height of the image in pixels.
guint16 depth; | the depth of the image, i.e. the number of bits per pixel.
guint16 bpp; | the number of bytes per pixel.
guint16 bpl; | the number of bytes per line of the image.
guint16 bits_per_pixel; | the number of bits per pixel.
gpointer mem; | the pixel data.
GdkColormap *colormap; | the GdkColormap associated with the image

gdk_image_new ()

GdkImage*           gdk_image_new                       (GdkImageType type,
                                                         GdkVisual *visual,
                                                         gint width,
                                                         gint height);

Creates a new GdkImage.

type : | the type of the GdkImage, one of GDK_IMAGE_NORMAL, GDK_IMAGE_SHARED and GDK_IMAGE_FASTEST. GDK_IMAGE_FASTEST is probably the best choice, since it will try creating a GDK_IMAGE_SHARED image first and if that fails it will then use GDK_IMAGE_NORMAL.
visual : | the GdkVisual to use for the image.
width : | the width of the image in pixels.
height : | the height of the image in pixels.
Returns : | a new GdkImage, or NULL if the image could not be created.

enum GdkImageType

typedef enum
{
  GDK_IMAGE_NORMAL,
  GDK_IMAGE_SHARED,
  GDK_IMAGE_FASTEST
} GdkImageType;

Specifies the type of a GdkImage.

GDK_IMAGE_NORMAL | The original X image type, which is quite slow since the image has to be transferred from the client to the server to display it.
GDK_IMAGE_SHARED | A faster image type, which uses shared memory to transfer the image data between client and server. However this will only be available if client and server are on the same machine and the shared memory extension is supported by the server.
GDK_IMAGE_FASTEST | Specifies that GDK_IMAGE_SHARED should be tried first, and if that fails then GDK_IMAGE_NORMAL will be used.

gdk_image_new_bitmap ()

GdkImage*           gdk_image_new_bitmap                (GdkVisual *visual,
                                                         gpointer data,
                                                         gint width,
                                                         gint height);

Warning

gdk_image_new_bitmap is deprecated and should not be used in newly-written code.

Creates a new GdkImage with a depth of 1 from the given data.

Warning

THIS FUNCTION IS INCREDIBLY BROKEN. The passed-in data must be allocated by malloc() (NOT g_malloc()) and will be freed when the image is freed.

visual : | the GdkVisual to use for the image.
data : | the pixel data.
width : | the width of the image in pixels.
height : | the height of the image in pixels.
Returns : | a new GdkImage.

gdk_image_get ()

GdkImage*           gdk_image_get                       (GdkDrawable *drawable,
                                                         gint x,
                                                         gint y,
                                                         gint width,
                                                         gint height);

Warning

gdk_image_get is deprecated and should not be used in newly-written code.

This is a deprecated wrapper for gdk_drawable_get_image(); gdk_drawable_get_image() should be used instead. Or even better: in most cases gdk_pixbuf_get_from_drawable() is the most convenient choice.

drawable : | a GdkDrawable
x : | x coordinate in window
y : | y coordinate in window
width : | width of area in window
height : | height of area in window
Returns : | a new GdkImage or NULL

gdk_image_ref ()

GdkImage*           gdk_image_ref                       (GdkImage *image);

Warning

gdk_image_ref is deprecated and should not be used in newly-written code.

Deprecated function; use g_object_ref() instead.

image : | a GdkImage
Returns : | the image

gdk_image_unref ()

void                gdk_image_unref                     (GdkImage *image);

Warning

gdk_image_unref is deprecated and should not be used in newly-written code.

Deprecated function; use g_object_unref() instead.

image : a GdkImage

gdk_image_destroy

#define gdk_image_destroy              gdk_image_unref

Warning

gdk_image_destroy is deprecated and should not be used in newly-written code.

Destroys a GdkImage, freeing any resources allocated for it.

gdk_image_get_colormap ()

GdkColormap*        gdk_image_get_colormap              (GdkImage *image);

Retrieves the colormap for a given image, if it exists. An image will have a colormap if the drawable from which it was created has a colormap, or if a colormap was set explicitely with gdk_image_set_colormap().

image : | a GdkImage
Returns : | colormap for the image

gdk_image_set_colormap ()

void                gdk_image_set_colormap              (GdkImage *image,
                                                         GdkColormap *colormap);

Sets the colormap for the image to the given colormap. Normally there's no need to use this function, images are created with the correct colormap if you get the image from a drawable. If you create the image from scratch, use the colormap of the drawable you intend to render the image to.

image : | a GdkImage
colormap : | a GdkColormap

gdk_image_put_pixel ()

void                gdk_image_put_pixel                 (GdkImage *image,
                                                         gint x,
                                                         gint y,
                                                         guint32 pixel);

Sets a pixel in a GdkImage to a given pixel value.

image : | a GdkImage.
x : | the x coordinate of the pixel to set.
y : | the y coordinate of the pixel to set.
pixel : | the pixel value to set.

gdk_image_get_pixel ()

guint32             gdk_image_get_pixel                 (GdkImage *image,
                                                         gint x,
                                                         gint y);

Gets a pixel value at a specified position in a GdkImage.

image : | a GdkImage.
x : | the x coordinate of the pixel to get.
y : | the y coordinate of the pixel to get.
Returns : | the pixel value at the given position.

See Also

Bitmaps and Pixmaps | Graphics which are stored on the X Windows server. Since these are stored on the server they can be drawn very quickly, and all of the Drawing Primitives can be used to draw on them. Their main disadvantage is that manipulating individual pixels can be very slow.
GdkRGB | Built on top of GdkImage, this provides much more functionality, including the dithering of colors to produce better output on low-color displays.


Input

Input — Callbacks on file descriptors

Synopsis

#include <gdk/gdk.h>

gint                gdk_input_add_full                  (gint source,
                                                         GdkInputCondition condition,
                                                         GdkInputFunction function,
                                                         gpointer data,
                                                         GdkDestroyNotify destroy);
enum                GdkInputCondition;
void                (*GdkInputFunction)                 (gpointer data,
                                                         gint source,
                                                         GdkInputCondition condition);
void                (*GdkDestroyNotify)                 (gpointer data);
gint                gdk_input_add                       (gint source,
                                                         GdkInputCondition condition,
                                                         GdkInputFunction function,
                                                         gpointer data);
void                gdk_input_remove                    (gint tag);

Description

The functions in this section are used to establish callbacks when some condition becomes true for a file descriptor. They are currently just wrappers around the IO Channel facility.

Details

gdk_input_add_full ()

gint                gdk_input_add_full                  (gint source,
                                                         GdkInputCondition condition,
                                                         GdkInputFunction function,
                                                         gpointer data,
                                                         GdkDestroyNotify destroy);

Warning

gdk_input_add_full is deprecated and should not be used in newly-written code.

Establish a callback when a condition becomes true on a file descriptor.

source : | a file descriptor.
condition : | the condition.
function : | the callback function.
data : | callback data passed to function.
destroy : | callback function to call with data when the input handler is removed.
Returns : | a tag that can later be used as an argument to gdk_input_remove().

enum GdkInputCondition

typedef enum
{
  GDK_INPUT_READ       = 1 << 0,
  GDK_INPUT_WRITE      = 1 << 1,
  GDK_INPUT_EXCEPTION  = 1 << 2
} GdkInputCondition;

A set of bit flags used to specify conditions for which an input callback will be triggered. The three members of this enumeration correspond to the readfds, writefds, and exceptfds arguments to the select system call.

GDK_INPUT_READ | the file descriptor has become available for reading. (Or, as is standard in Unix, a socket or pipe was closed at the other end; this is the case if a subsequent read on the file descriptor returns a count of zero.)
GDK_INPUT_WRITE | the file descriptor has become available for writing.
GDK_INPUT_EXCEPTION | an exception was raised on the file descriptor.

GdkInputFunction ()

void                (*GdkInputFunction)                 (gpointer data,
                                                         gint source,
                                                         GdkInputCondition condition);

A callback function that will be called when some condition occurs.

data : | the user data passed to gdk_input_add() or gdk_input_add_full().
source : | the source where the condition occurred.
condition : | the triggering condition.

GdkDestroyNotify ()

void                (*GdkDestroyNotify)                 (gpointer data);

A callback function called when a piece of user data is no longer being stored by GDK. Will typically free the structure or object that data points to.

data : the user data.

gdk_input_add ()

gint                gdk_input_add                       (gint source,
                                                         GdkInputCondition condition,
                                                         GdkInputFunction function,
                                                         gpointer data);

Warning

gdk_input_add is deprecated and should not be used in newly-written code.

Establish a callback when a condition becomes true on a file descriptor.

source : | a file descriptor.
condition : | the condition.
function : | the callback function.
data : | callback data passed to function.
Returns : | a tag that can later be used as an argument to gdk_input_remove().

gdk_input_remove ()

void                gdk_input_remove                    (gint tag);

Warning

gdk_input_remove is deprecated and should not be used in newly-written code.

Remove a callback added with gdk_input_add() or gdk_input_add_full().

tag : the tag returned when the callback was set up.

See Also

GLib Main Loop | The main loop in which input callbacks run.
IO Channels | A newer and more flexible way of doing IO callbacks.


Input Devices

Input Devices — Functions for handling extended input devices

Synopsis

#include <gdk/gdk.h>

                    GdkDevice;
enum                GdkInputSource;
enum                GdkInputMode;
                    GdkDeviceKey;
                    GdkDeviceAxis;
enum                GdkAxisUse;
GList*              gdk_devices_list                    (void);
void                gdk_device_set_source               (GdkDevice *device,
                                                         GdkInputSource source);
gboolean            gdk_device_set_mode                 (GdkDevice *device,
                                                         GdkInputMode mode);
void                gdk_device_set_key                  (GdkDevice *device,
                                                         guint index_,
                                                         guint keyval,
                                                         GdkModifierType modifiers);
void                gdk_device_set_axis_use             (GdkDevice *device,
                                                         guint index_,
                                                         GdkAxisUse use);
GdkDevice*          gdk_device_get_core_pointer         (void);

void                gdk_device_get_state                (GdkDevice *device,
                                                         GdkWindow *window,
                                                         gdouble *axes,
                                                         GdkModifierType *mask);
gboolean            gdk_device_get_history              (GdkDevice *device,
                                                         GdkWindow *window,
                                                         guint32 start,
                                                         guint32 stop,
                                                         GdkTimeCoord ***events,
                                                         gint *n_events);
void                gdk_device_free_history             (GdkTimeCoord **events,
                                                         gint n_events);
                    GdkTimeCoord;
gboolean            gdk_device_get_axis                 (GdkDevice *device,
                                                         gdouble *axes,
                                                         GdkAxisUse use,
                                                         gdouble *value);

void                gdk_input_set_extension_events      (GdkWindow *window,
                                                         gint mask,
                                                         GdkExtensionMode mode);
enum                GdkExtensionMode;

Description

In addition to the normal keyboard and mouse input devices, GTK+ also contains support for extended input devices. In particular, this support is targeted at graphics tablets. Graphics tablets typically return sub-pixel positioning information and possibly information about the pressure and tilt of the stylus. Under X, the support for extended devices is done through the XInput extension.

Because handling extended input devices may involve considerable overhead, they need to be turned on for each GdkWindow individually using gdk_input_set_extension_events(). (Or, more typically, for GtkWidgets, using gtk_widget_set_extension_events()). As an additional complication, depending on the support from the windowing system, its possible that a normal mouse cursor will not be displayed for a particular extension device. If an application does not want to deal with displaying a cursor itself, it can ask only to get extension events from devices that will display a cursor, by passing the GDK_EXTENSION_EVENTS_CURSOR value to gdk_input_set_extension_events(). Otherwise, the application must retrieve the device information using gdk_devices_list(), check the has_cursor field, and, if it is FALSE, draw a cursor itself when it receives motion events.

Each pointing device is assigned a unique integer ID; events from a particular device can be identified by the deviceid field in the event structure. The events generated by pointer devices have also been extended to contain pressure, xtilt and ytilt fields which contain the extended information reported as additional valuators from the device. The pressure field is a a double value ranging from 0.0 to 1.0, while the tilt fields are double values ranging from -1.0 to 1.0. (With -1.0 representing the maximum tilt to the left or up, and 1.0 representing the maximum tilt to the right or down.)

One additional field in each event is the source field, which contains an enumeration value describing the type of device; this currently can be one of GDK_SOURCE_MOUSE, GDK_SOURCE_PEN, GDK_SOURCE_ERASER, or GDK_SOURCE_CURSOR. This field is present to allow simple applications to (for instance) delete when they detect eraser devices without having to keep track of complicated per-device settings.

Various aspects of each device may be configured. The easiest way of creating a GUI to allow the user to configure such a device is to use the GtkInputDialog widget in GTK+. However, even when using this widget, application writers will need to directly query and set the configuration parameters in order to save the state between invocations of the application. The configuration of devices is queried using gdk_devices_list(). Each device must be activated using gdk_device_set_mode(), which also controls whether the device's range is mapped to the entire screen or to a single window. The mapping of the valuators of the device onto the predefined valuator types is set using gdk_device_set_axis_use(). And the source type for each device can be set with gdk_device_set_source().

Devices may also have associated keys or macro buttons. Such keys can be globally set to map into normal X keyboard events. The mapping is set using gdk_device_set_key().

The interfaces in this section will most likely be considerably modified in the future to accomodate devices that may have different sets of additional valuators than the pressure xtilt and ytilt.

Details

GdkDevice

typedef struct {
  GObject parent_instance;
  /* All fields are read-only */

  gchar *name;
  GdkInputSource source;
  GdkInputMode mode;
  gboolean has_cursor;	     /* TRUE if the X pointer follows device motion */

  gint num_axes;
  GdkDeviceAxis *axes;

  gint num_keys;
  GdkDeviceKey *keys;
} GdkDevice;

A GdkDevice structure contains a detailed description of an extended input device. All fields are read-only; but you can use gdk_device_set_source(), gdk_device_set_mode(), gdk_device_set_key() and gdk_device_set_axis_use() to configure various aspects of the device.

GObject parent_instance; | the parent instance
gchar *name; | the name of this device.
GdkInputSource source; | the type of this device.
GdkInputMode mode; | the mode of this device
gboolean has_cursor; | TRUE if the pointer follows device motion.
gint num_axes; | the length of the axes array.
GdkDeviceAxis *axes; | an array of GdkDeviceAxis, describing the axes of this device.
gint num_keys; | the length of the keys array.
GdkDeviceKey *keys; | an array of GdkDeviceKey, describing the mapped macro buttons of this device.

enum GdkInputSource

typedef enum
{
  GDK_SOURCE_MOUSE,
  GDK_SOURCE_PEN,
  GDK_SOURCE_ERASER,
  GDK_SOURCE_CURSOR
} GdkInputSource;

An enumeration describing the type of an input device in general terms.

GDK_SOURCE_MOUSE | the device is a mouse. (This will be reported for the core pointer, even if it is something else, such as a trackball.)
GDK_SOURCE_PEN | the device is a stylus of a graphics tablet or similar device.
GDK_SOURCE_ERASER | the device is an eraser. Typically, this would be the other end of a stylus on a graphics tablet.
GDK_SOURCE_CURSOR | the device is a graphics tablet "puck" or similar device.

enum GdkInputMode

typedef enum
{
  GDK_MODE_DISABLED,
  GDK_MODE_SCREEN,
  GDK_MODE_WINDOW
} GdkInputMode;

An enumeration that describes the mode of an input device.

GDK_MODE_DISABLED | the device is disabled and will not report any events.
GDK_MODE_SCREEN | the device is enabled. The device's coordinate space maps to the entire screen.
GDK_MODE_WINDOW | the device is enabled. The device's coordinate space is mapped to a single window. The manner in which this window is chosen is undefined, but it will typically be the same way in which the focus window for key events is determined.

GdkDeviceKey

typedef struct {
  guint keyval;
  GdkModifierType modifiers;
} GdkDeviceKey;

The GdkDeviceKey structure contains information about the mapping of one device macro button onto a normal X key event. It has the following fields:

guint keyval; | the keyval to generate when the macro button is pressed. If this is 0, no keypress will be generated.
GdkModifierType modifiers; | the modifiers set for the generated key event.

GdkDeviceAxis

typedef struct {
  GdkAxisUse use;
  gdouble    min;
  gdouble    max;
} GdkDeviceAxis;

The GdkDeviceAxis structure contains information about the range and mapping of a device axis.

GdkAxisUse use; | specifies how the axis is used.
gdouble min; | the minimal value that will be reported by this axis.
gdouble max; | the maximal value that will be reported by this axis.

enum GdkAxisUse

typedef enum
{
  GDK_AXIS_IGNORE,
  GDK_AXIS_X,
  GDK_AXIS_Y,
  GDK_AXIS_PRESSURE,
  GDK_AXIS_XTILT,
  GDK_AXIS_YTILT,
  GDK_AXIS_WHEEL,
  GDK_AXIS_LAST
} GdkAxisUse;

An enumeration describing the way in which a device axis (valuator) maps onto the predefined valuator types that GTK+ understands.

GDK_AXIS_IGNORE | the axis is ignored.
GDK_AXIS_X | the axis is used as the x axis.
GDK_AXIS_Y | the axis is used as the y axis.
GDK_AXIS_PRESSURE | the axis is used for pressure information.
GDK_AXIS_XTILT | the axis is used for x tilt information.
GDK_AXIS_YTILT | the axis is used for x tilt information.
GDK_AXIS_WHEEL | the axis is used for wheel information.
GDK_AXIS_LAST | a constant equal to the numerically highest axis value.

gdk_devices_list ()

GList*              gdk_devices_list                    (void);

Returns the list of available input devices for the default display. The list is statically allocated and should not be freed.

Returns : a list of GdkDevice

gdk_device_set_source ()

void                gdk_device_set_source               (GdkDevice *device,
                                                         GdkInputSource source);

Sets the source type for an input device.

device : | a GdkDevice.
source : | the source type.

gdk_device_set_mode ()

gboolean            gdk_device_set_mode                 (GdkDevice *device,
                                                         GdkInputMode mode);

Sets a the mode of an input device. The mode controls if the device is active and whether the device's range is mapped to the entire screen or to a single window.

device : | a GdkDevice.
mode : | the input mode.
Returns : | TRUE if the mode was successfully changed.

gdk_device_set_key ()

void                gdk_device_set_key                  (GdkDevice *device,
                                                         guint index_,
                                                         guint keyval,
                                                         GdkModifierType modifiers);

Specifies the X key event to generate when a macro button of a device is pressed.

device : | a GdkDevice.
index_ : | the index of the macro button to set.
keyval : | the keyval to generate.
modifiers : | the modifiers to set.

gdk_device_set_axis_use ()

void                gdk_device_set_axis_use             (GdkDevice *device,
                                                         guint index_,
                                                         GdkAxisUse use);

Specifies how an axis of a device is used.

device : | a GdkDevice.
index_ : | the index of the axis.
use : | specifies how the axis is used.

gdk_device_get_core_pointer ()

GdkDevice*          gdk_device_get_core_pointer         (void);

Returns the core pointer device for the default display.

Returns : the core pointer device; this is owned by the display and should not be freed.

gdk_device_get_state ()

void                gdk_device_get_state                (GdkDevice *device,
                                                         GdkWindow *window,
                                                         gdouble *axes,
                                                         GdkModifierType *mask);

Gets the current state of a device.

device : | a GdkDevice.
window : | a GdkWindow.
axes : | an array of doubles to store the values of the axes of device in, or NULL.
mask : | location to store the modifiers, or NULL.

gdk_device_get_history ()

gboolean            gdk_device_get_history              (GdkDevice *device,
                                                         GdkWindow *window,
                                                         guint32 start,
                                                         guint32 stop,
                                                         GdkTimeCoord ***events,
                                                         gint *n_events);

Obtains the motion history for a device; given a starting and ending timestamp, return all events in the motion history for the device in the given range of time. Some windowing systems do not support motion history, in which case, FALSE will be returned. (This is not distinguishable from the case where motion history is supported and no events were found.)

device : | a GdkDevice
window : | the window with respect to which which the event coordinates will be reported
start : | starting timestamp for range of events to return
stop : | ending timestamp for the range of events to return
events : | location to store a newly-allocated array of GdkTimeCoord, or NULL
n_events : | location to store the length of events, or NULL
Returns : | TRUE if the windowing system supports motion history and at least one event was found.

gdk_device_free_history ()

void                gdk_device_free_history             (GdkTimeCoord **events,
                                                         gint n_events);

Frees an array of GdkTimeCoord that was returned by gdk_device_get_history().

events : | an array of GdkTimeCoord.
n_events : | the length of the array.

GdkTimeCoord

typedef struct {
  guint32 time;
  gdouble axes[GDK_MAX_TIMECOORD_AXES];
} GdkTimeCoord;

The GdkTimeCoord structure stores a single event in a motion history. It contains the following fields:

guint32 time; | The timestamp for this event.
gdouble axes[GDK_MAX_TIMECOORD_AXES]; | the values of the device's axes.

gdk_device_get_axis ()

gboolean            gdk_device_get_axis                 (GdkDevice *device,
                                                         gdouble *axes,
                                                         GdkAxisUse use,
                                                         gdouble *value);

Interprets an array of double as axis values for a given device, and locates the value in the array for a given axis use.

device : | a GdkDevice
axes : | pointer to an array of axes
use : | the use to look for
value : | location to store the found value.
Returns : | TRUE if the given axis use was found, otherwise FALSE

gdk_input_set_extension_events ()

void                gdk_input_set_extension_events      (GdkWindow *window,
                                                         gint mask,
                                                         GdkExtensionMode mode);

Turns extension events on or off for a particular window, and specifies the event mask for extension events.

window : | a GdkWindow.
mask : | the event mask
mode : | the type of extension events that are desired.

enum GdkExtensionMode

typedef enum
{
  GDK_EXTENSION_EVENTS_NONE,
  GDK_EXTENSION_EVENTS_ALL,
  GDK_EXTENSION_EVENTS_CURSOR
} GdkExtensionMode;

An enumeration used to specify which extension events are desired for a particular widget.

GDK_EXTENSION_EVENTS_NONE | no extension events are desired.
GDK_EXTENSION_EVENTS_ALL | all extension events are desired.
GDK_EXTENSION_EVENTS_CURSOR | extension events are desired only if a cursor will be displayed for the device.


Key Values

Key Values — Functions for manipulating keyboard codes

Synopsis

#include <gdk/gdk.h>

                    GdkKeymap;
                    GdkKeymapKey;
GdkKeymap*          gdk_keymap_get_default              (void);
GdkKeymap*          gdk_keymap_get_for_display          (GdkDisplay *display);
guint               gdk_keymap_lookup_key               (GdkKeymap *keymap,
                                                         const GdkKeymapKey *key);
gboolean            gdk_keymap_translate_keyboard_state (GdkKeymap *keymap,
                                                         guint hardware_keycode,
                                                         GdkModifierType state,
                                                         gint group,
                                                         guint *keyval,
                                                         gint *effective_group,
                                                         gint *level,
                                                         GdkModifierType *consumed_modifiers);
gboolean            gdk_keymap_get_entries_for_keyval   (GdkKeymap *keymap,
                                                         guint keyval,
                                                         GdkKeymapKey **keys,
                                                         gint *n_keys);
gboolean            gdk_keymap_get_entries_for_keycode  (GdkKeymap *keymap,
                                                         guint hardware_keycode,
                                                         GdkKeymapKey **keys,
                                                         guint **keyvals,
                                                         gint *n_entries);
PangoDirection      gdk_keymap_get_direction            (GdkKeymap *keymap);

gchar*              gdk_keyval_name                     (guint keyval);
guint               gdk_keyval_from_name                (const gchar *keyval_name);

void                gdk_keyval_convert_case             (guint symbol,
                                                         guint *lower,
                                                         guint *upper);
guint               gdk_keyval_to_upper                 (guint keyval);
guint               gdk_keyval_to_lower                 (guint keyval);
gboolean            gdk_keyval_is_upper                 (guint keyval);
gboolean            gdk_keyval_is_lower                 (guint keyval);

guint32             gdk_keyval_to_unicode               (guint keyval);
guint               gdk_unicode_to_keyval               (guint32 wc);

Object Hierarchy

  GObject
   +----GdkKeymap

Signals

  "direction-changed"                              : Run Last
  "keys-changed"                                   : Run Last

Description

Key values are the codes which are sent whenever a key is pressed or released. They appear in the keyval field of the GdkEventKey structure, which is passed to signal handlers for the "key-press-event" and "key-release-event" signals. The complete list of key values can be found in the <gdk/gdkkeysyms.h> header file. <gdk/gdkkeysyms.h> is not included in <gtk/gtk.h>, it must be included independently, because the file is quite large.

Key values can be converted into a string representation using gdk_keyval_name(). The reverse function, converting a string to a key value, is provided by gdk_keyval_from_name().

The case of key values can be determined using gdk_keyval_is_upper() and gdk_keyval_is_lower(). Key values can be converted to upper or lower case using gdk_keyval_to_upper() and gdk_keyval_to_lower().

When it makes sense, key values can be converted to and from Unicode characters with gdk_keyval_to_unicode() and gdk_unicode_to_keyval().

One GdkKeymap object exists for each user display. gdk_keymap_get_default() returns the GdkKeymap for the default display; to obtain keymaps for other displays, use gdk_keymap_get_for_display(). A keymap is a mapping from GdkKeymapKey to key values. You can think of a GdkKeymapKey as a representation of a symbol printed on a physical keyboard key. That is, it contains three pieces of information. First, it contains the hardware keycode; this is an identifying number for a physical key. Second, it contains the level of the key. The level indicates which symbol on the key will be used, in a vertical direction. So on a standard US keyboard, the key with the number "1" on it also has the exclamation point ("!") character on it. The level indicates whether to use the "1" or the "!" symbol. The letter keys are considered to have a lowercase letter at level 0, and an uppercase letter at level 1, though only the uppercase letter is printed. Third, the GdkKeymapKey contains a group; groups are not used on standard US keyboards, but are used in many other countries. On a keyboard with groups, there can be 3 or 4 symbols printed on a single key. The group indicates movement in a horizontal direction. Usually groups are used for two different languages. In group 0, a key might have two English characters, and in group 1 it might have two Hebrew characters. The Hebrew characters will be printed on the key next to the English characters.

In order to use a keymap to interpret a key event, it's necessary to first convert the keyboard state into an effective group and level. This is done via a set of rules that varies widely according to type of keyboard and user configuration. The function gdk_keymap_translate_keyboard_state() accepts a keyboard state -- consisting of hardware keycode pressed, active modifiers, and active group -- applies the appropriate rules, and returns the group/level to be used to index the keymap, along with the modifiers which did not affect the group and level. i.e. it returns "unconsumed modifiers." The keyboard group may differ from the effective group used for keymap lookups because some keys don't have multiple groups - e.g. the Enter key is always in group 0 regardless of keyboard state.

Note that gdk_keymap_translate_keyboard_state() also returns the keyval, i.e. it goes ahead and performs the keymap lookup in addition to telling you which effective group/level values were used for the lookup. GdkEventKey already contains this keyval, however, so you don't normally need to call gdk_keymap_translate_keyboard_state() just to get the keyval.

Details

GdkKeymap

typedef struct _GdkKeymap GdkKeymap;

A GdkKeymap defines the translation from keyboard state (including a hardware key, a modifier mask, and active keyboard group) to a keyval. This translation has two phases. The first phase is to determine the effective keyboard group and level for the keyboard state; the second phase is to look up the keycode/group/level triplet in the keymap and see what keyval it corresponds to.

GdkKeymapKey

typedef struct {
  guint keycode;
  gint  group;
  gint  level;
} GdkKeymapKey;

A GdkKeymapKey is a hardware key that can be mapped to a keyval.

guint keycode; | the hardware keycode. This is an identifying number for a physical key.
gint group; | indicates movement in a horizontal direction. Usually groups are used for two different languages. In group 0, a key might have two English characters, and in group 1 it might have two Hebrew characters. The Hebrew characters will be printed on the key next to the English characters.
gint level; | indicates which symbol on the key will be used, in a vertical direction. So on a standard US keyboard, the key with the number "1" on it also has the exclamation point ("!") character on it. The level indicates whether to use the "1" or the "!" symbol. The letter keys are considered to have a lowercase letter at level 0, and an uppercase letter at level 1, though only the uppercase letter is printed.

gdk_keymap_get_default ()

GdkKeymap*          gdk_keymap_get_default              (void);

Returns the GdkKeymap attached to the default display.

Returns : the GdkKeymap attached to the default display.

gdk_keymap_get_for_display ()

GdkKeymap*          gdk_keymap_get_for_display          (GdkDisplay *display);

Returns the GdkKeymap attached to display.

display : | the GdkDisplay.
Returns : | the GdkKeymap attached to display.

Since 2.2

gdk_keymap_lookup_key ()

guint               gdk_keymap_lookup_key               (GdkKeymap *keymap,
                                                         const GdkKeymapKey *key);

Looks up the keyval mapped to a keycode/group/level triplet. If no keyval is bound to key, returns 0. For normal user input, you want to use gdk_keymap_translate_keyboard_state() instead of this function, since the effective group/level may not be the same as the current keyboard state.

keymap : | a GdkKeymap or NULL to use the default keymap
key : | a GdkKeymapKey with keycode, group, and level initialized
Returns : | a keyval, or 0 if none was mapped to the given key

gdk_keymap_translate_keyboard_state ()

gboolean            gdk_keymap_translate_keyboard_state (GdkKeymap *keymap,
                                                         guint hardware_keycode,
                                                         GdkModifierType state,
                                                         gint group,
                                                         guint *keyval,
                                                         gint *effective_group,
                                                         gint *level,
                                                         GdkModifierType *consumed_modifiers);

Translates the contents of a GdkEventKey into a keyval, effective group, and level. Modifiers that affected the translation and are thus unavailable for application use are returned in consumed_modifiers. See gdk_keyval_get_keys() for an explanation of groups and levels. The effective_group is the group that was actually used for the translation; some keys such as Enter are not affected by the active keyboard group. The level is derived from state. For convenience, GdkEventKey already contains the translated keyval, so this function isn't as useful as you might think.

keymap : | a GdkKeymap, or NULL to use the default
hardware_keycode : |
state : | a modifier state
group : | active keyboard group
keyval : | return location for keyval
effective_group : | return location for effective group
level : | return location for level
consumed_modifiers : | return location for modifiers that were used to determine the group or level
Returns : | TRUE if there was a keyval bound to the keycode/state/group

gdk_keymap_get_entries_for_keyval ()

gboolean            gdk_keymap_get_entries_for_keyval   (GdkKeymap *keymap,
                                                         guint keyval,
                                                         GdkKeymapKey **keys,
                                                         gint *n_keys);

Obtains a list of keycode/group/level combinations that will generate keyval. Groups and levels are two kinds of keyboard mode; in general, the level determines whether the top or bottom symbol on a key is used, and the group determines whether the left or right symbol is used. On US keyboards, the shift key changes the keyboard level, and there are no groups. A group switch key might convert a keyboard between Hebrew to English modes, for example. GdkEventKey contains a group field that indicates the active keyboard group. The level is computed from the modifier mask. The returned array should be freed with g_free().

keymap : | a GdkKeymap, or NULL to use the default keymap
keyval : | a keyval, such as GDK_a, GDK_Up, GDK_Return, etc.
keys : | return location for an array of GdkKeymapKey
n_keys : | return location for number of elements in returned array
Returns : | TRUE if keys were found and returned

gdk_keymap_get_entries_for_keycode ()

gboolean            gdk_keymap_get_entries_for_keycode  (GdkKeymap *keymap,
                                                         guint hardware_keycode,
                                                         GdkKeymapKey **keys,
                                                         guint **keyvals,
                                                         gint *n_entries);

Returns the keyvals bound to hardware_keycode. The Nth GdkKeymapKey in keys is bound to the Nth keyval in keyvals. Free the returned arrays with g_free(). When a keycode is pressed by the user, the keyval from this list of entries is selected by considering the effective keyboard group and level. See gdk_keymap_translate_keyboard_state().

keymap : | a GdkKeymap or NULL to use the default keymap
hardware_keycode : | a keycode
keys : | return location for array of GdkKeymapKey, or NULL
keyvals : | return location for array of keyvals, or NULL
n_entries : | length of keys and keyvals
Returns : | TRUE if there were any entries

gdk_keymap_get_direction ()

PangoDirection      gdk_keymap_get_direction            (GdkKeymap *keymap);

Returns the direction of the keymap.

keymap : | a GdkKeymap or NULL to use the default keymap. Returns: PANGO_DIRECTION_LTR or PANGO_DIRECTION_RTL.
Returns : | the direction of the keymap.

gdk_keyval_name ()

gchar*              gdk_keyval_name                     (guint keyval);

Converts a key value into a symbolic name. The names are the same as those in the <gdk/gdkkeysyms.h> header file but without the leading "GDK_".

keyval : | a key value.
Returns : | a string containing the name of the key, or NULL if keyval is not a valid key. The string should not be modified.

gdk_keyval_from_name ()

guint               gdk_keyval_from_name                (const gchar *keyval_name);

Converts a key name to a key value.

keyval_name : | a key name.
Returns : | the corresponding key value, or GDK_VoidSymbol if the key name is not a valid key.

gdk_keyval_convert_case ()

void                gdk_keyval_convert_case             (guint symbol,
                                                         guint *lower,
                                                         guint *upper);

Obtains the upper- and lower-case versions of the keyval symbol. Examples of keyvals are GDK_a, GDK_Enter, GDK_F1, etc.

symbol : | a keyval
lower : | return location for lowercase version of symbol
upper : | return location for uppercase version of symbol

gdk_keyval_to_upper ()

guint               gdk_keyval_to_upper                 (guint keyval);

Converts a key value to upper case, if applicable.

keyval : | a key value.
Returns : | the upper case form of keyval, or keyval itself if it is already in upper case or it is not subject to case conversion.

gdk_keyval_to_lower ()

guint               gdk_keyval_to_lower                 (guint keyval);

Converts a key value to lower case, if applicable.

keyval : | a key value.
Returns : | the lower case form of keyval, or keyval itself if it is already in lower case or it is not subject to case conversion.

gdk_keyval_is_upper ()

gboolean            gdk_keyval_is_upper                 (guint keyval);

Returns TRUE if the given key value is in upper case.

keyval : | a key value.
Returns : | TRUE if keyval is in upper case, or if keyval is not subject to case conversion.

gdk_keyval_is_lower ()

gboolean            gdk_keyval_is_lower                 (guint keyval);

Returns TRUE if the given key value is in lower case.

keyval : | a key value.
Returns : | TRUE if keyval is in lower case, or if keyval is not subject to case conversion.

gdk_keyval_to_unicode ()

guint32             gdk_keyval_to_unicode               (guint keyval);

Convert from a GDK key symbol to the corresponding ISO10646 (Unicode) character.

keyval : | a GDK key symbol
Returns : | the corresponding unicode character, or 0 if there is no corresponding character.

gdk_unicode_to_keyval ()

guint               gdk_unicode_to_keyval               (guint32 wc);

Convert from a ISO10646 character to a key symbol.

wc : | a ISO10646 encoded character
Returns : | the corresponding GDK key symbol, if one exists. or, if there is no corresponding symbol, wc | 0x01000000

Signal Details

The "direction-changed" signal

void                user_function                      (GdkKeymap *keymap,
                                                        gpointer   user_data)      : Run Last

The ::direction_changed signal gets emitted when the direction of the keymap changes.

keymap : | the object on which the signal is emitted
user_data : | user data set when the signal handler was connected.

Since 2.0

The "keys-changed" signal

void                user_function                      (GdkKeymap *keymap,
                                                        gpointer   user_data)      : Run Last

The ::keys_changed signal is emitted when the mapping represented by keymap changes.

keymap : | the object on which the signal is emitted
user_data : | user data set when the signal handler was connected.

Since 2.2


Pango Interaction

Pango Interaction — Using Pango in GDK

Synopsis

#include <gdk/gdk.h>

                    GdkPangoRenderer;
                    GdkPangoRendererClass;
PangoRenderer*      gdk_pango_renderer_new              (GdkScreen *screen);
PangoRenderer*      gdk_pango_renderer_get_default      (GdkScreen *screen);
void                gdk_pango_renderer_set_drawable     (GdkPangoRenderer *gdk_renderer,
                                                         GdkDrawable *drawable);
void                gdk_pango_renderer_set_gc           (GdkPangoRenderer *gdk_renderer,
                                                         GdkGC *gc);
void                gdk_pango_renderer_set_stipple      (GdkPangoRenderer *gdk_renderer,
                                                         PangoRenderPart part,
                                                         GdkBitmap *stipple);
void                gdk_pango_renderer_set_override_color
                                                        (GdkPangoRenderer *gdk_renderer,
                                                         PangoRenderPart part,
                                                         const GdkColor *color);
PangoContext*       gdk_pango_context_get               (void);
PangoContext*       gdk_pango_context_get_for_screen    (GdkScreen *screen);
void                gdk_pango_context_set_colormap      (PangoContext *context,
                                                         GdkColormap *colormap);
                    GdkPangoAttrEmbossed;
                    GdkPangoAttrStipple;
PangoAttribute*     gdk_pango_attr_embossed_new         (gboolean embossed);
PangoAttribute*     gdk_pango_attr_stipple_new          (GdkBitmap *stipple);
GdkRegion*          gdk_pango_layout_get_clip_region    (PangoLayout *layout,
                                                         gint x_origin,
                                                         gint y_origin,
                                                         gint *index_ranges,
                                                         gint n_ranges);
GdkRegion*          gdk_pango_layout_line_get_clip_region
                                                        (PangoLayoutLine *line,
                                                         gint x_origin,
                                                         gint y_origin,
                                                         gint *index_ranges,
                                                         gint n_ranges);

Object Hierarchy

  GObject
   +----PangoRenderer
         +----GdkPangoRenderer

Properties

  "screen"                   GdkScreen             : Read / Write / Construct Only

Description

Pango is the text layout system used by GDK and GTK+. The functions and types in this section are used to render Pango objects to GDK. drawables, and also extend the set of Pango attributes to include stippling and embossing.

Creating a PangoLayout object is the first step in rendering text, and requires getting a handle to a PangoContext. For GTK+ programs, you'll usually want to use gtk_widget_get_pango_context(), or gtk_widget_create_pango_layout(), rather than using the lowlevel gdk_pango_context_get_for_screen(). Once you have a PangoLayout, you can set the text and attributes of it with Pango functions like pango_layout_set_text() and get its size with pango_layout_get_size(). (Note that Pango uses a fixed point system internally, so converting between Pango units and pixels using PANGO_SCALE or the PANGO_PIXELS() macro.)

Rendering a Pango layout is done most simply with gdk_draw_layout(); you can also draw pieces of the layout with gdk_draw_layout() or gdk_draw_glyphs(). GdkPangoRenderer is a subclass of PangoRenderer that is used internally to implement these functions. Using it directly or subclassing it can be useful in some cases. See the GdkPangoRenderer documentation for details.

Example 7. Using GdkPangoRenderer to draw transformed text

#define RADIUS 100
#define N_WORDS 10
#define FONT "Sans Bold 18"

GdkScreen *screen = gdk_drawable_get_screen (drawable);
PangoRenderer *renderer;
GdkGC *gc;

PangoMatrix matrix = PANGO_MATRIX_INIT;
PangoContext *context;
PangoLayout *layout;
PangoFontDescription *desc;

double device_radius;
int width, height;
int i;

/* Get the default renderer for the screen, and set it up for drawing  */
renderer = gdk_pango_renderer_get_default (screen);
gdk_pango_renderer_set_drawable (GDK_PANGO_RENDERER (renderer), drawable);

gc = gdk_gc_new (drawable);
gdk_pango_renderer_set_gc (GDK_PANGO_RENDERER (renderer), gc);

/* Set up a transformation matrix so that the user space coordinates for
 * where we are drawing are [-RADIUS, RADIUS], [-RADIUS, RADIUS]
 * We first center, then change the scale */
gdk_drawable_get_size (drawable, &width, &height);
device_radius = MIN (width, height) / 2.;

pango_matrix_translate (&matrix,
                        device_radius + (width - 2 * device_radius) / 2,
                        device_radius + (height - 2 * device_radius) / 2);
pango_matrix_scale (&matrix, device_radius / RADIUS, device_radius / RADIUS);

/* Create a PangoLayout, set the font and text */
context = gdk_pango_context_get_for_screen (screen);
layout = pango_layout_new (context);
pango_layout_set_text (layout, "Text", -1);
desc = pango_font_description_from_string (FONT);
pango_layout_set_font_description (layout, desc);
pango_font_description_free (desc);

/* Draw the layout N_WORDS times in a circle */
for (i = 0; i < N_WORDS; i++)
  {
    GdkColor color;
    PangoMatrix rotated_matrix = matrix;
    int width, height;
    double angle = (360. * i) / N_WORDS;

    /* Gradient from red at angle == 60 to blue at angle == 300 */
    color.red   = 65535 * (1 + cos ((angle - 60) * M_PI / 180.)) / 2;
    color.green = 0;
    color.blue  = 65535  - color.red;

    gdk_pango_renderer_set_override_color (GDK_PANGO_RENDERER (renderer),
                                           PANGO_RENDER_PART_FOREGROUND, &color);

    pango_matrix_rotate (&rotated_matrix, angle);

    pango_context_set_matrix (context, &rotated_matrix);

    /* Inform Pango to re-layout the text with the new transformation matrix */
    pango_layout_context_changed (layout);

    pango_layout_get_size (layout, &width, &height);
    pango_renderer_draw_layout (renderer, layout,
                                - width / 2, - RADIUS * PANGO_SCALE);
  }

/* Clean up default renderer, since it is shared */
gdk_pango_renderer_set_override_color (GDK_PANGO_RENDERER (renderer),
                                       PANGO_RENDER_PART_FOREGROUND, NULL);
gdk_pango_renderer_set_drawable (GDK_PANGO_RENDERER (renderer), NULL);
gdk_pango_renderer_set_gc (GDK_PANGO_RENDERER (renderer), NULL);

/* free the objects we created */
g_object_unref (layout);
g_object_unref (context);
g_object_unref (gc);

Figure 1. Output of Example 7, “Using GdkPangoRenderer to draw transformed text”

Details

GdkPangoRenderer

typedef struct _GdkPangoRenderer GdkPangoRenderer;

GdkPangoRenderer is a subclass of PangoRenderer used for rendering Pango objects into GDK drawables. The default renderer for a particular screen is obtained with gdk_pango_renderer_get_default(); Pango functions like pango_renderer_draw_layout() and pango_renderer_draw_layout_line() are then used to draw objects with the renderer.

In most simple cases, applications can just use gdk_draw_layout(), and don't need to directly use GdkPangoRenderer at all. Using the GdkPangoRenderer directly is most useful when working with a transformation such as a rotation, because the Pango drawing functions take user space coordinates (coordinates before the transformation) instead of device coordinates.

In certain cases it can be useful to subclass GdkPangoRenderer. Examples of reasons to do this are to add handling of custom attributes by overriding 'prepare_run' or to do custom drawing of embedded objects by overriding 'draw_shape'.

Since 2.6

GdkPangoRendererClass

typedef struct {
} GdkPangoRendererClass;

GdkPangoRenderer is the class structure for GdkPangoRenderer.

Since 2.6

gdk_pango_renderer_new ()

PangoRenderer*      gdk_pango_renderer_new              (GdkScreen *screen);

Creates a new PangoRenderer for screen. Normally you can use the results of gdk_pango_renderer_get_default() rather than creating a new renderer.

screen : | a GdkScreen
Returns : | a newly created PangoRenderer. Free with g_object_unref().

Since 2.6

gdk_pango_renderer_get_default ()

PangoRenderer*      gdk_pango_renderer_get_default      (GdkScreen *screen);

Gets the default PangoRenderer for a screen. This default renderer is shared by all users of the display, so properties such as the color or transformation matrix set for the renderer may be overwritten by functions such as gdk_draw_layout().

Before using the renderer, you need to call gdk_pango_renderer_set_drawable() and gdk_pango_renderer_set_gc() to set the drawable and graphics context to use for drawing.

screen : | a GdkScreen
Returns : | the default PangoRenderer for screen. The renderer is owned by GTK+ and will be kept around until the screen is closed.

Since 2.6

gdk_pango_renderer_set_drawable ()

void                gdk_pango_renderer_set_drawable     (GdkPangoRenderer *gdk_renderer,
                                                         GdkDrawable *drawable);

Sets the drawable the renderer draws to.

gdk_renderer : | a GdkPangoRenderer
drawable : | the new target drawable, or NULL

Since 2.6

gdk_pango_renderer_set_gc ()

void                gdk_pango_renderer_set_gc           (GdkPangoRenderer *gdk_renderer,
                                                         GdkGC *gc);

Sets the GC the renderer draws with. Note that the GC must not be modified until it is unset by calling the function again with NULL for the gc parameter, since GDK may make internal copies of the GC which won't be updated to follow changes to the original GC.

gdk_renderer : | a GdkPangoRenderer
gc : | the new GC to use for drawing, or NULL

Since 2.6

gdk_pango_renderer_set_stipple ()

void                gdk_pango_renderer_set_stipple      (GdkPangoRenderer *gdk_renderer,
                                                         PangoRenderPart part,
                                                         GdkBitmap *stipple);

Sets the stipple for one render part (foreground, background, underline, etc.) Note that this is overwritten when iterating through the individual styled runs of a PangoLayout or PangoLayoutLine. This function is thus only useful when you call low level functions like pango_renderer_draw_glyphs() directly, or in the 'prepare_run' virtual function of a subclass of GdkPangoRenderer.

gdk_renderer : | a GdkPangoRenderer
part : | the part to render with the stipple
stipple : | the new stipple value.

Since 2.6

gdk_pango_renderer_set_override_color ()

void                gdk_pango_renderer_set_override_color
                                                        (GdkPangoRenderer *gdk_renderer,
                                                         PangoRenderPart part,
                                                         const GdkColor *color);

Sets the color for a particular render part (foreground, background, underline, etc.), overriding any attributes on the layouts renderered with this renderer.

gdk_renderer : | a GdkPangoRenderer
part : | the part to render to set the color of
color : | the color to use, or NULL to unset a previously set override color.

Since 2.6

gdk_pango_context_get ()

PangoContext*       gdk_pango_context_get               (void);

Creates a PangoContext for the default GDK screen.

The context must be freed when you're finished with it.

When using GTK+, normally you should use gtk_widget_get_pango_context() instead of this function, to get the appropriate context for the widget you intend to render text onto.

The newly created context will have the default font options (see cairo_font_options_t) for the default screen; if these options change it will not be updated. Using gtk_widget_get_pango_context() is more convenient if you want to keep a context around and track changes to the screen's font rendering settings.

Returns : a new PangoContext for the default display

gdk_pango_context_get_for_screen ()

PangoContext*       gdk_pango_context_get_for_screen    (GdkScreen *screen);

Creates a PangoContext for screen.

The context must be freed when you're finished with it.

When using GTK+, normally you should use gtk_widget_get_pango_context() instead of this function, to get the appropriate context for the widget you intend to render text onto.

The newly created context will have the default font options (see cairo_font_options_t) for the screen; if these options change it will not be updated. Using gtk_widget_get_pango_context() is more convenient if you want to keep a context around and track changes to the screen's font rendering settings.

screen : | the GdkScreen for which the context is to be created.
Returns : | a new PangoContext for screen

Since 2.2

gdk_pango_context_set_colormap ()

void                gdk_pango_context_set_colormap      (PangoContext *context,
                                                         GdkColormap *colormap);

Warning

gdk_pango_context_set_colormap is deprecated and should not be used in newly-written code.

This function used to set the colormap to be used for drawing with context. The colormap is now always derived from the graphics context used for drawing, so calling this function is no longer necessary.

context : | a PangoContext
colormap : | a GdkColormap

GdkPangoAttrEmbossed

typedef struct {
  PangoAttribute attr;
  gboolean embossed;
} GdkPangoAttrEmbossed;

A Pango text attribute containing a embossed bitmap to be used when rendering the text.

PangoAttribute attr; | the PangoAttribute.
gboolean embossed; | the embossed bitmap.

GdkPangoAttrStipple

typedef struct {
  PangoAttribute attr;
  GdkBitmap *stipple;
} GdkPangoAttrStipple;

A Pango text attribute containing a stipple bitmap to be used when rendering the text.

PangoAttribute attr; | the PangoAttribute.
GdkBitmap *stipple; | the stipple bitmap.

gdk_pango_attr_embossed_new ()

PangoAttribute*     gdk_pango_attr_embossed_new         (gboolean embossed);

Creates a new attribute containing a embossed bitmap to be used when rendering the text.

embossed : | a bitmap to be set as embossed
Returns : | new PangoAttribute

gdk_pango_attr_stipple_new ()

PangoAttribute*     gdk_pango_attr_stipple_new          (GdkBitmap *stipple);

Creates a new attribute containing a stipple bitmap to be used when rendering the text.

stipple : | a bitmap to be set as stipple
Returns : | new PangoAttribute

gdk_pango_layout_get_clip_region ()

GdkRegion*          gdk_pango_layout_get_clip_region    (PangoLayout *layout,
                                                         gint x_origin,
                                                         gint y_origin,
                                                         gint *index_ranges,
                                                         gint n_ranges);

Obtains a clip region which contains the areas where the given ranges of text would be drawn. x_origin and y_origin are the same position you would pass to gdk_draw_layout_line(). index_ranges should contain ranges of bytes in the layout's text.

Note that the regions returned correspond to logical extents of the text ranges, not ink extents. So the drawn layout may in fact touch areas out of the clip region. The clip region is mainly useful for highlightling parts of text, such as when text is selected.

layout : | a PangoLayout
x_origin : | X pixel where you intend to draw the layout with this clip
y_origin : | Y pixel where you intend to draw the layout with this clip
index_ranges : | array of byte indexes into the layout, where even members of array are start indexes and odd elements are end indexes
n_ranges : | number of ranges in index_ranges, i.e. half the size of index_ranges
Returns : | a clip region containing the given ranges

gdk_pango_layout_line_get_clip_region ()

GdkRegion*          gdk_pango_layout_line_get_clip_region
                                                        (PangoLayoutLine *line,
                                                         gint x_origin,
                                                         gint y_origin,
                                                         gint *index_ranges,
                                                         gint n_ranges);

Obtains a clip region which contains the areas where the given ranges of text would be drawn. x_origin and y_origin are the same position you would pass to gdk_draw_layout_line(). index_ranges should contain ranges of bytes in the layout's text. The clip region will include space to the left or right of the line (to the layout bounding box) if you have indexes above or below the indexes contained inside the line. This is to draw the selection all the way to the side of the layout. However, the clip region is in line coordinates, not layout coordinates.

Note that the regions returned correspond to logical extents of the text ranges, not ink extents. So the drawn line may in fact touch areas out of the clip region. The clip region is mainly useful for highlightling parts of text, such as when text is selected.

line : | a PangoLayoutLine
x_origin : | X pixel where you intend to draw the layout line with this clip
y_origin : | baseline pixel where you intend to draw the layout line with this clip
index_ranges : | array of byte indexes into the layout, where even members of array are start indexes and odd elements are end indexes
n_ranges : | number of ranges in index_ranges, i.e. half the size of index_ranges
Returns : | a clip region containing the given ranges

Property Details

The "screen" property

  "screen"                   GdkScreen             : Read / Write / Construct Only

the GdkScreen for the renderer.


Pixbufs

Pixbufs — Functions for rendering pixbufs on drawables

Synopsis

#include <gdk/gdk.h>

void                gdk_pixbuf_render_threshold_alpha   (GdkPixbuf *pixbuf,
                                                         GdkBitmap *bitmap,
                                                         int src_x,
                                                         int src_y,
                                                         int dest_x,
                                                         int dest_y,
                                                         int width,
                                                         int height,
                                                         int alpha_threshold);
void                gdk_pixbuf_render_to_drawable       (GdkPixbuf *pixbuf,
                                                         GdkDrawable *drawable,
                                                         GdkGC *gc,
                                                         int src_x,
                                                         int src_y,
                                                         int dest_x,
                                                         int dest_y,
                                                         int width,
                                                         int height,
                                                         GdkRgbDither dither,
                                                         int x_dither,
                                                         int y_dither);
void                gdk_pixbuf_render_to_drawable_alpha (GdkPixbuf *pixbuf,
                                                         GdkDrawable *drawable,
                                                         int src_x,
                                                         int src_y,
                                                         int dest_x,
                                                         int dest_y,
                                                         int width,
                                                         int height,
                                                         GdkPixbufAlphaMode alpha_mode,
                                                         int alpha_threshold,
                                                         GdkRgbDither dither,
                                                         int x_dither,
                                                         int y_dither);
void                gdk_pixbuf_render_pixmap_and_mask   (GdkPixbuf *pixbuf,
                                                         GdkPixmap **pixmap_return,
                                                         GdkBitmap **mask_return,
                                                         int alpha_threshold);
void                gdk_pixbuf_render_pixmap_and_mask_for_colormap
                                                        (GdkPixbuf *pixbuf,
                                                         GdkColormap *colormap,
                                                         GdkPixmap **pixmap_return,
                                                         GdkBitmap **mask_return,
                                                         int alpha_threshold);
GdkPixbuf*          gdk_pixbuf_get_from_drawable        (GdkPixbuf *dest,
                                                         GdkDrawable *src,
                                                         GdkColormap *cmap,
                                                         int src_x,
                                                         int src_y,
                                                         int dest_x,
                                                         int dest_y,
                                                         int width,
                                                         int height);
GdkPixbuf*          gdk_pixbuf_get_from_image           (GdkPixbuf *dest,
                                                         GdkImage *src,
                                                         GdkColormap *cmap,
                                                         int src_x,
                                                         int src_y,
                                                         int dest_x,
                                                         int dest_y,
                                                         int width,
                                                         int height);

Description

These functions allow to render pixbufs on drawables. Pixbufs are client-side images. For details on how to create and manipulate pixbufs, see the GdkPixbuf API documentation.

Details

gdk_pixbuf_render_threshold_alpha ()

void                gdk_pixbuf_render_threshold_alpha   (GdkPixbuf *pixbuf,
                                                         GdkBitmap *bitmap,
                                                         int src_x,
                                                         int src_y,
                                                         int dest_x,
                                                         int dest_y,
                                                         int width,
                                                         int height,
                                                         int alpha_threshold);

Takes the opacity values in a rectangular portion of a pixbuf and thresholds them to produce a bi-level alpha mask that can be used as a clipping mask for a drawable.

pixbuf : | A pixbuf.
bitmap : | Bitmap where the bilevel mask will be painted to.
src_x : | Source X coordinate.
src_y : | source Y coordinate.
dest_x : | Destination X coordinate.
dest_y : | Destination Y coordinate.
width : | Width of region to threshold, or -1 to use pixbuf width
height : | Height of region to threshold, or -1 to use pixbuf height
alpha_threshold : | Opacity values below this will be painted as zero; all other values will be painted as one.

gdk_pixbuf_render_to_drawable ()

void                gdk_pixbuf_render_to_drawable       (GdkPixbuf *pixbuf,
                                                         GdkDrawable *drawable,
                                                         GdkGC *gc,
                                                         int src_x,
                                                         int src_y,
                                                         int dest_x,
                                                         int dest_y,
                                                         int width,
                                                         int height,
                                                         GdkRgbDither dither,
                                                         int x_dither,
                                                         int y_dither);

Warning

gdk_pixbuf_render_to_drawable has been deprecated since version 2.4 and should not be used in newly-written code. This function is obsolete. Use gdk_draw_pixbuf() instead.

Renders a rectangular portion of a pixbuf to a drawable while using the specified GC. This is done using GdkRGB, so the specified drawable must have the GdkRGB visual and colormap. Note that this function will ignore the opacity information for images with an alpha channel; the GC must already have the clipping mask set if you want transparent regions to show through.

For an explanation of dither offsets, see the GdkRGB documentation. In brief, the dither offset is important when re-rendering partial regions of an image to a rendered version of the full image, or for when the offsets to a base position change, as in scrolling. The dither matrix has to be shifted for consistent visual results. If you do not have any of these cases, the dither offsets can be both zero.

pixbuf : | A pixbuf.
drawable : | Destination drawable.
gc : | GC used for rendering.
src_x : | Source X coordinate within pixbuf.
src_y : | Source Y coordinate within pixbuf.
dest_x : | Destination X coordinate within drawable.
dest_y : | Destination Y coordinate within drawable.
width : | Width of region to render, in pixels, or -1 to use pixbuf width
height : | Height of region to render, in pixels, or -1 to use pixbuf height
dither : | Dithering mode for GdkRGB.
x_dither : | X offset for dither.
y_dither : | Y offset for dither.

gdk_pixbuf_render_to_drawable_alpha ()

void                gdk_pixbuf_render_to_drawable_alpha (GdkPixbuf *pixbuf,
                                                         GdkDrawable *drawable,
                                                         int src_x,
                                                         int src_y,
                                                         int dest_x,
                                                         int dest_y,
                                                         int width,
                                                         int height,
                                                         GdkPixbufAlphaMode alpha_mode,
                                                         int alpha_threshold,
                                                         GdkRgbDither dither,
                                                         int x_dither,
                                                         int y_dither);

Warning

gdk_pixbuf_render_to_drawable_alpha has been deprecated since version 2.4 and should not be used in newly-written code. This function is obsolete. Use gdk_draw_pixbuf() instead.

Renders a rectangular portion of a pixbuf to a drawable. The destination drawable must have a colormap. All windows have a colormap, however, pixmaps only have colormap by default if they were created with a non-NULL window argument. Otherwise a colormap must be set on them with gdk_drawable_set_colormap.

On older X servers, rendering pixbufs with an alpha channel involves round trips to the X server, and may be somewhat slow.

pixbuf : | A pixbuf.
drawable : | Destination drawable.
src_x : | Source X coordinate within pixbuf.
src_y : | Source Y coordinates within pixbuf.
dest_x : | Destination X coordinate within drawable.
dest_y : | Destination Y coordinate within drawable.
width : | Width of region to render, in pixels, or -1 to use pixbuf width.
height : | Height of region to render, in pixels, or -1 to use pixbuf height.
alpha_mode : | Ignored. Present for backwards compatibility.
alpha_threshold : | Ignored. Present for backwards compatibility
dither : | Dithering mode for GdkRGB.
x_dither : | X offset for dither.
y_dither : | Y offset for dither.

gdk_pixbuf_render_pixmap_and_mask ()

void                gdk_pixbuf_render_pixmap_and_mask   (GdkPixbuf *pixbuf,
                                                         GdkPixmap **pixmap_return,
                                                         GdkBitmap **mask_return,
                                                         int alpha_threshold);

Creates a pixmap and a mask bitmap which are returned in the pixmap_return and mask_return arguments, respectively, and renders a pixbuf and its corresponding thresholded alpha mask to them. This is merely a convenience function; applications that need to render pixbufs with dither offsets or to given drawables should use gdk_draw_pixbuf() and gdk_pixbuf_render_threshold_alpha().

The pixmap that is created is created for the colormap returned by gdk_rgb_get_colormap(). You normally will want to instead use the actual colormap for a widget, and use gdk_pixbuf_render_pixmap_and_mask_for_colormap().

If the pixbuf does not have an alpha channel, then *mask_return will be set to NULL.

pixbuf : | A pixbuf.
pixmap_return : | Location to store a pointer to the created pixmap, or NULL if the pixmap is not needed.
mask_return : | Location to store a pointer to the created mask, or NULL if the mask is not needed.
alpha_threshold : | Threshold value for opacity values.

gdk_pixbuf_render_pixmap_and_mask_for_colormap ()

void                gdk_pixbuf_render_pixmap_and_mask_for_colormap
                                                        (GdkPixbuf *pixbuf,
                                                         GdkColormap *colormap,
                                                         GdkPixmap **pixmap_return,
                                                         GdkBitmap **mask_return,
                                                         int alpha_threshold);

Creates a pixmap and a mask bitmap which are returned in the pixmap_return and mask_return arguments, respectively, and renders a pixbuf and its corresponding tresholded alpha mask to them. This is merely a convenience function; applications that need to render pixbufs with dither offsets or to given drawables should use gdk_draw_pixbuf(), and gdk_pixbuf_render_threshold_alpha().

The pixmap that is created uses the GdkColormap specified by colormap. This colormap must match the colormap of the window where the pixmap will eventually be used or an error will result.

If the pixbuf does not have an alpha channel, then *mask_return will be set to NULL.

pixbuf : | A pixbuf.
colormap : | A GdkColormap
pixmap_return : | Location to store a pointer to the created pixmap, or NULL if the pixmap is not needed.
mask_return : | Location to store a pointer to the created mask, or NULL if the mask is not needed.
alpha_threshold : | Threshold value for opacity values.

gdk_pixbuf_get_from_drawable ()

GdkPixbuf*          gdk_pixbuf_get_from_drawable        (GdkPixbuf *dest,
                                                         GdkDrawable *src,
                                                         GdkColormap *cmap,
                                                         int src_x,
                                                         int src_y,
                                                         int dest_x,
                                                         int dest_y,
                                                         int width,
                                                         int height);

Transfers image data from a GdkDrawable and converts it to an RGB(A) representation inside a GdkPixbuf. In other words, copies image data from a server-side drawable to a client-side RGB(A) buffer. This allows you to efficiently read individual pixels on the client side.

If the drawable src has no colormap (gdk_drawable_get_colormap() returns NULL), then a suitable colormap must be specified. Typically a GdkWindow or a pixmap created by passing a GdkWindow to gdk_pixmap_new() will already have a colormap associated with it. If the drawable has a colormap, the cmap argument will be ignored. If the drawable is a bitmap (1 bit per pixel pixmap), then a colormap is not required; pixels with a value of 1 are assumed to be white, and pixels with a value of 0 are assumed to be black. For taking screenshots, gdk_colormap_get_system() returns the correct colormap to use.

If the specified destination pixbuf dest is NULL, then this function will create an RGB pixbuf with 8 bits per channel and no alpha, with the same size specified by the width and height arguments. In this case, the dest_x and dest_y arguments must be specified as 0. If the specified destination pixbuf is not NULL and it contains alpha information, then the filled pixels will be set to full opacity (alpha = 255).

If the specified drawable is a pixmap, then the requested source rectangle must be completely contained within the pixmap, otherwise the function will return NULL. For pixmaps only (not for windows) passing -1 for width or height is allowed to mean the full width or height of the pixmap.

If the specified drawable is a window, and the window is off the screen, then there is no image data in the obscured/offscreen regions to be placed in the pixbuf. The contents of portions of the pixbuf corresponding to the offscreen region are undefined.

If the window you're obtaining data from is partially obscured by other windows, then the contents of the pixbuf areas corresponding to the obscured regions are undefined.

If the target drawable is not mapped (typically because it's iconified/minimized or not on the current workspace), then NULL will be returned.

If memory can't be allocated for the return value, NULL will be returned instead.

(In short, there are several ways this function can fail, and if it fails it returns NULL; so check the return value.)

This function calls gdk_drawable_get_image() internally and converts the resulting image to a GdkPixbuf, so the documentation for gdk_drawable_get_image() may also be relevant.

dest : | Destination pixbuf, or NULL if a new pixbuf should be created.
src : | Source drawable.
cmap : | A colormap if src doesn't have one set.
src_x : | Source X coordinate within drawable.
src_y : | Source Y coordinate within drawable.
dest_x : | Destination X coordinate in pixbuf, or 0 if dest is NULL.
dest_y : | Destination Y coordinate in pixbuf, or 0 if dest is NULL.
width : | Width in pixels of region to get.
height : | Height in pixels of region to get.
Returns : | The same pixbuf as dest if it was non-NULL, or a newly-created pixbuf with a reference count of 1 if no destination pixbuf was specified, or NULL on error

gdk_pixbuf_get_from_image ()

GdkPixbuf*          gdk_pixbuf_get_from_image           (GdkPixbuf *dest,
                                                         GdkImage *src,
                                                         GdkColormap *cmap,
                                                         int src_x,
                                                         int src_y,
                                                         int dest_x,
                                                         int dest_y,
                                                         int width,
                                                         int height);

Same as gdk_pixbuf_get_from_drawable() but gets the pixbuf from an image.

dest : | Destination pixbuf, or NULL if a new pixbuf should be created.
src : | Source GdkImage.
cmap : | A colormap, or NULL to use the one for src
src_x : | Source X coordinate within drawable.
src_y : | Source Y coordinate within drawable.
dest_x : | Destination X coordinate in pixbuf, or 0 if dest is NULL.
dest_y : | Destination Y coordinate in pixbuf, or 0 if dest is NULL.
width : | Width in pixels of region to get.
height : | Height in pixels of region to get.
Returns : | dest, newly-created pixbuf if dest was NULL, NULL on error


Points, Rectangles and Regions

Points, Rectangles and Regions — Simple graphical data types

Synopsis

#include <gdk/gdk.h>

                    GdkPoint;

                    GdkRectangle;
gboolean            gdk_rectangle_intersect             (GdkRectangle *src1,
                                                         GdkRectangle *src2,
                                                         GdkRectangle *dest);
void                gdk_rectangle_union                 (GdkRectangle *src1,
                                                         GdkRectangle *src2,
                                                         GdkRectangle *dest);

                    GdkRegion;
GdkRegion*          gdk_region_new                      (void);
GdkRegion*          gdk_region_polygon                  (GdkPoint *points,
                                                         gint npoints,
                                                         GdkFillRule fill_rule);
enum                GdkFillRule;
GdkRegion*          gdk_region_copy                     (GdkRegion *region);
GdkRegion*          gdk_region_rectangle                (GdkRectangle *rectangle);
void                gdk_region_destroy                  (GdkRegion *region);

void                gdk_region_get_clipbox              (GdkRegion *region,
                                                         GdkRectangle *rectangle);
void                gdk_region_get_rectangles           (GdkRegion *region,
                                                         GdkRectangle **rectangles,
                                                         gint *n_rectangles);
gboolean            gdk_region_empty                    (GdkRegion *region);
gboolean            gdk_region_equal                    (GdkRegion *region1,
                                                         GdkRegion *region2);
gboolean            gdk_region_point_in                 (GdkRegion *region,
                                                         int x,
                                                         int y);
GdkOverlapType      gdk_region_rect_in                  (GdkRegion *region,
                                                         GdkRectangle *rectangle);
enum                GdkOverlapType;

void                gdk_region_offset                   (GdkRegion *region,
                                                         gint dx,
                                                         gint dy);
void                gdk_region_shrink                   (GdkRegion *region,
                                                         gint dx,
                                                         gint dy);
void                gdk_region_union_with_rect          (GdkRegion *region,
                                                         GdkRectangle *rect);
void                gdk_region_intersect                (GdkRegion *source1,
                                                         GdkRegion *source2);
void                gdk_region_union                    (GdkRegion *source1,
                                                         GdkRegion *source2);
void                gdk_region_subtract                 (GdkRegion *source1,
                                                         GdkRegion *source2);
void                gdk_region_xor                      (GdkRegion *source1,
                                                         GdkRegion *source2);

                    GdkSpan;
void                (*GdkSpanFunc)                      (GdkSpan *span,
                                                         gpointer data);
void                gdk_region_spans_intersect_foreach  (GdkRegion *region,
                                                         GdkSpan *spans,
                                                         int n_spans,
                                                         gboolean sorted,
                                                         GdkSpanFunc function,
                                                         gpointer data);

Description

GDK provides the GdkPoint, GdkRectangle, GdkRegion and GdkSpan data types for representing pixels and sets of pixels on the screen.

GdkPoint is a simple structure containing an x and y coordinate of a point.

GdkRectangle is a structure holding the position and size of a rectangle. The intersection of two rectangles can be computed with gdk_rectangle_intersect(). To find the union of two rectangles use gdk_rectangle_union().

GdkRegion is an opaque data type holding a set of arbitrary pixels, and is usually used for clipping graphical operations (see gdk_gc_set_clip_region()).

GdkSpan is a structure holding a spanline. A spanline is a horizontal line that is one pixel wide. It is mainly used when rasterizing other graphics primitives. It can be intersected to regions by using gdk_region_spans_intersect_foreach().

Details

GdkPoint

typedef struct {
  gint x;
  gint y;
} GdkPoint;

Defines the x and y coordinates of a point.

gint x; | the x coordinate of the point.
gint y; | the y coordinate of the point.

GdkRectangle

typedef struct {
  gint x;
  gint y;
  gint width;
  gint height;
} GdkRectangle;

Defines the position and size of a rectangle.

gint x; | the x coordinate of the left edge of the rectangle.
gint y; | the y coordinate of the top of the rectangle.
gint width; | the width of the rectangle.
gint height; | the height of the rectangle.

gdk_rectangle_intersect ()

gboolean            gdk_rectangle_intersect             (GdkRectangle *src1,
                                                         GdkRectangle *src2,
                                                         GdkRectangle *dest);

Calculates the intersection of two rectangles. It is allowed for dest to be the same as either src1 or src2.

src1 : | a GdkRectangle
src2 : | a GdkRectangle
dest : | return location for the intersection of src1 and src2
Returns : | TRUE if the rectangles intersect.

gdk_rectangle_union ()

void                gdk_rectangle_union                 (GdkRectangle *src1,
                                                         GdkRectangle *src2,
                                                         GdkRectangle *dest);

Calculates the union of two rectangles. The union of rectangles src1 and src2 is the smallest rectangle which includes both src1 and src2 within it. It is allowed for dest to be the same as either src1 or src2.

src1 : | a GdkRectangle
src2 : | a GdkRectangle
dest : | return location for the union of src1 and src2

GdkRegion

typedef struct _GdkRegion GdkRegion;

A GdkRegion represents a set of pixels on the screen.

gdk_region_new ()

GdkRegion*          gdk_region_new                      (void);

Creates a new empty GdkRegion.

Returns : a new empty GdkRegion

gdk_region_polygon ()

GdkRegion*          gdk_region_polygon                  (GdkPoint *points,
                                                         gint npoints,
                                                         GdkFillRule fill_rule);

Creates a new GdkRegion using the polygon defined by a number of points.

points : | an array of GdkPoint structs
npoints : | the number of elements in the points array
fill_rule : | specifies which pixels are included in the region when the polygon overlaps itself.
Returns : | a new GdkRegion based on the given polygon

enum GdkFillRule

typedef enum
{
  GDK_EVEN_ODD_RULE,
  GDK_WINDING_RULE
} GdkFillRule;

The method for determining which pixels are included in a region, when creating a GdkRegion from a polygon. The fill rule is only relevant for polygons which overlap themselves.

GDK_EVEN_ODD_RULE | areas which are overlapped an odd number of times are included in the region, while areas overlapped an even number of times are not.
GDK_WINDING_RULE | overlapping areas are always included.

gdk_region_copy ()

GdkRegion*          gdk_region_copy                     (GdkRegion *region);

Copies region, creating an identical new region.

region : | a GdkRegion
Returns : | a new region identical to region

gdk_region_rectangle ()

GdkRegion*          gdk_region_rectangle                (GdkRectangle *rectangle);

Creates a new region containing the area rectangle.

rectangle : | a GdkRectangle
Returns : | a new region

gdk_region_destroy ()

void                gdk_region_destroy                  (GdkRegion *region);

Destroys a GdkRegion.

region : a GdkRegion

gdk_region_get_clipbox ()

void                gdk_region_get_clipbox              (GdkRegion *region,
                                                         GdkRectangle *rectangle);

Obtains the smallest rectangle which includes the entire GdkRegion.

region : | a GdkRegion
rectangle : | return location for the clipbox

gdk_region_get_rectangles ()

void                gdk_region_get_rectangles           (GdkRegion *region,
                                                         GdkRectangle **rectangles,
                                                         gint *n_rectangles);

Obtains the area covered by the region as a list of rectangles. The array returned in rectangles must be freed with g_free().

region : | a GdkRegion
rectangles : | return location for an array of rectangles
n_rectangles : | length of returned array

gdk_region_empty ()

gboolean            gdk_region_empty                    (GdkRegion *region);

Finds out if the GdkRegion is empty.

region : | a GdkRegion
Returns : | TRUE if region is empty.

gdk_region_equal ()

gboolean            gdk_region_equal                    (GdkRegion *region1,
                                                         GdkRegion *region2);

Finds out if the two regions are the same.

region1 : | a GdkRegion
region2 : | a GdkRegion
Returns : | TRUE if region1 and region2 are equal.

gdk_region_point_in ()

gboolean            gdk_region_point_in                 (GdkRegion *region,
                                                         int x,
                                                         int y);

Finds out if a point is in a region.

region : | a GdkRegion
x : | the x coordinate of a point
y : | the y coordinate of a point
Returns : | TRUE if the point is in region.

gdk_region_rect_in ()

GdkOverlapType      gdk_region_rect_in                  (GdkRegion *region,
                                                         GdkRectangle *rectangle);

Tests whether a rectangle is within a region.

region : | a GdkRegion.
rectangle : | a GdkRectangle.
Returns : | GDK_OVERLAP_RECTANGLE_IN, GDK_OVERLAP_RECTANGLE_OUT, or GDK_OVERLAP_RECTANGLE_PART, depending on whether the rectangle is inside, outside, or partly inside the GdkRegion, respectively.

enum GdkOverlapType

typedef enum
{
  GDK_OVERLAP_RECTANGLE_IN,
  GDK_OVERLAP_RECTANGLE_OUT,
  GDK_OVERLAP_RECTANGLE_PART
} GdkOverlapType;

Specifies the possible values returned by gdk_region_rect_in().

GDK_OVERLAP_RECTANGLE_IN | if the rectangle is inside the GdkRegion.
GDK_OVERLAP_RECTANGLE_OUT | if the rectangle is outside the GdkRegion.
GDK_OVERLAP_RECTANGLE_PART | if the rectangle is partly inside the GdkRegion.

gdk_region_offset ()

void                gdk_region_offset                   (GdkRegion *region,
                                                         gint dx,
                                                         gint dy);

Moves a region the specified distance.

region : | a GdkRegion
dx : | the distance to move the region horizontally
dy : | the distance to move the region vertically

gdk_region_shrink ()

void                gdk_region_shrink                   (GdkRegion *region,
                                                         gint dx,
                                                         gint dy);

Resizes a region by the specified amount. Positive values shrink the region. Negative values expand it.

region : | a GdkRegion
dx : | the number of pixels to shrink the region horizontally
dy : | the number of pixels to shrink the region vertically

gdk_region_union_with_rect ()

void                gdk_region_union_with_rect          (GdkRegion *region,
                                                         GdkRectangle *rect);

Sets the area of region to the union of the areas of region and rect. The resulting area is the set of pixels contained in either region or rect.

region : | a GdkRegion.
rect : | a GdkRectangle.

gdk_region_intersect ()

void                gdk_region_intersect                (GdkRegion *source1,
                                                         GdkRegion *source2);

Sets the area of source1 to the intersection of the areas of source1 and source2. The resulting area is the set of pixels contained in both source1 and source2.

source1 : | a GdkRegion
source2 : | another GdkRegion

gdk_region_union ()

void                gdk_region_union                    (GdkRegion *source1,
                                                         GdkRegion *source2);

Sets the area of source1 to the union of the areas of source1 and source2. The resulting area is the set of pixels contained in either source1 or source2.

source1 : | a GdkRegion
source2 : | a GdkRegion

gdk_region_subtract ()

void                gdk_region_subtract                 (GdkRegion *source1,
                                                         GdkRegion *source2);

Subtracts the area of source2 from the area source1. The resulting area is the set of pixels contained in source1 but not in source2.

source1 : | a GdkRegion
source2 : | another GdkRegion

gdk_region_xor ()

void                gdk_region_xor                      (GdkRegion *source1,
                                                         GdkRegion *source2);

Sets the area of source1 to the exclusive-OR of the areas of source1 and source2. The resulting area is the set of pixels contained in one or the other of the two sources but not in both.

source1 : | a GdkRegion
source2 : | another GdkRegion

GdkSpan

typedef struct {
  gint x;
  gint y;
  gint width;
} GdkSpan;

A GdkSpan represents a horizontal line of pixels starting at the pixel with coordinates x, y and ending before x + width, y.

gint x; | x coordinate of the first pixel.
gint y; | y coordinate of the first pixel.
gint width; | number of pixels in the span.

GdkSpanFunc ()

void                (*GdkSpanFunc)                      (GdkSpan *span,
                                                         gpointer data);

This defines the type of the function passed to gdk_region_spans_intersect_foreach().

span : | a GdkSpan.
data : | the user data passed to gdk_region_spans_intersect_foreach().

gdk_region_spans_intersect_foreach ()

void                gdk_region_spans_intersect_foreach  (GdkRegion *region,
                                                         GdkSpan *spans,
                                                         int n_spans,
                                                         gboolean sorted,
                                                         GdkSpanFunc function,
                                                         gpointer data);

Calls a function on each span in the intersection of region and spans.

region : | a GdkRegion
spans : | an array of GdkSpans
n_spans : | the length of spans
sorted : | TRUE if spans is sorted wrt. the y coordinate
function : | function to call on each span in the intersection
data : | data to pass to function


Properties and Atoms

Properties and Atoms — Functions to manipulate properties on windows

Synopsis

#include <gdk/gdk.h>

                    GdkAtom;
#define             GDK_ATOM_TO_POINTER                 (atom)
#define             GDK_POINTER_TO_ATOM                 (ptr)
#define             GDK_NONE
gint                gdk_text_property_to_text_list      (GdkAtom encoding,
                                                         gint format,
                                                         const guchar *text,
                                                         gint length,
                                                         gchar ***list);
gint                gdk_text_property_to_text_list_for_display
                                                        (GdkDisplay *display,
                                                         GdkAtom encoding,
                                                         gint format,
                                                         const guchar *text,
                                                         gint length,
                                                         gchar ***list);
void                gdk_free_text_list                  (gchar **list);
gint                gdk_text_property_to_utf8_list      (GdkAtom encoding,
                                                         gint format,
                                                         const guchar *text,
                                                         gint length,
                                                         gchar ***list);
gint                gdk_text_property_to_utf8_list_for_display
                                                        (GdkDisplay *display,
                                                         GdkAtom encoding,
                                                         gint format,
                                                         const guchar *text,
                                                         gint length,
                                                         gchar ***list);
gint                gdk_string_to_compound_text         (const gchar *str,
                                                         GdkAtom *encoding,
                                                         gint *format,
                                                         guchar **ctext,
                                                         gint *length);
gint                gdk_string_to_compound_text_for_display
                                                        (GdkDisplay *display,
                                                         const gchar *str,
                                                         GdkAtom *encoding,
                                                         gint *format,
                                                         guchar **ctext,
                                                         gint *length);
void                gdk_free_compound_text              (guchar *ctext);
gchar*              gdk_utf8_to_string_target           (const gchar *str);
gboolean            gdk_utf8_to_compound_text           (const gchar *str,
                                                         GdkAtom *encoding,
                                                         gint *format,
                                                         guchar **ctext,
                                                         gint *length);
gboolean            gdk_utf8_to_compound_text_for_display
                                                        (GdkDisplay *display,
                                                         const gchar *str,
                                                         GdkAtom *encoding,
                                                         gint *format,
                                                         guchar **ctext,
                                                         gint *length);
GdkAtom             gdk_atom_intern                     (const gchar *atom_name,
                                                         gboolean only_if_exists);
GdkAtom             gdk_atom_intern_static_string       (const gchar *atom_name);
gchar*              gdk_atom_name                       (GdkAtom atom);
gboolean            gdk_property_get                    (GdkWindow *window,
                                                         GdkAtom property,
                                                         GdkAtom type,
                                                         gulong offset,
                                                         gulong length,
                                                         gint pdelete,
                                                         GdkAtom *actual_property_type,
                                                         gint *actual_format,
                                                         gint *actual_length,
                                                         guchar **data);
void                gdk_property_change                 (GdkWindow *window,
                                                         GdkAtom property,
                                                         GdkAtom type,
                                                         gint format,
                                                         GdkPropMode mode,
                                                         const guchar *data,
                                                         gint nelements);
enum                GdkPropMode;
void                gdk_property_delete                 (GdkWindow *window,
                                                         GdkAtom property);

Description

Each window under X can have any number of associated properties attached to it. Properties are arbitrary chunks of data identified by atoms. (An atom is a numeric index into a string table on the X server. They are used to transfer strings efficiently between clients without having to transfer the entire string.) A property has an associated type, which is also identified using an atom.

A property has an associated format, an integer describing how many bits are in each unit of data inside the property. It must be 8, 16, or 32. When data is transferred between the server and client, if they are of different endianesses it will be byteswapped as necessary according to the format of the property. Note that on the client side, properties of format 32 will be stored with one unit per long, even if a long integer has more than 32 bits on the platform. (This decision was apparently made for Xlib to maintain compatibility with programs that assumed longs were 32 bits, at the expense of programs that knew better.)

The functions in this section are used to add, remove and change properties on windows, to convert atoms to and from strings and to manipulate some types of data commonly stored in X window properties.

Details

GdkAtom

typedef struct _GdkAtom GdkAtom;

An opaque type representing a string as an index into a table of strings on the X server.

GDK_ATOM_TO_POINTER()

#define GDK_ATOM_TO_POINTER(atom) (atom)

Converts a GdkAtom into a pointer type.

atom : a GdkAtom.

GDK_POINTER_TO_ATOM()

#define GDK_POINTER_TO_ATOM(ptr)  ((GdkAtom)(ptr))

Extracts a GdkAtom from a pointer. The GdkAtom must have been stored in the pointer with GDK_ATOM_TO_POINTER().

ptr : a pointer containing a GdkAtom.

GDK_NONE

#define GDK_NONE            _GDK_MAKE_ATOM (0)

A null value for GdkAtom, used in a similar way as None in the Xlib API.

gdk_text_property_to_text_list ()

gint                gdk_text_property_to_text_list      (GdkAtom encoding,
                                                         gint format,
                                                         const guchar *text,
                                                         gint length,
                                                         gchar ***list);

Converts a text string from the encoding as it is stored in a property into an array of strings in the encoding of the current local. (The elements of the array represent the nul-separated elements of the original text string.)

encoding : | an atom representing the encoding. The most common values for this are STRING, or COMPOUND_TEXT. This is value used as the type for the property.
format : | the format of the property.
text : | the text data.
length : | the length of the property, in items.
list : | location to store a terminated array of strings in the encoding of the current locale. This array should be freed using gdk_free_text_list().
Returns : | the number of strings stored in list, or 0, if the conversion failed.

gdk_text_property_to_text_list_for_display ()

gint                gdk_text_property_to_text_list_for_display
                                                        (GdkDisplay *display,
                                                         GdkAtom encoding,
                                                         gint format,
                                                         const guchar *text,
                                                         gint length,
                                                         gchar ***list);

Convert a text string from the encoding as it is stored in a property into an array of strings in the encoding of the current locale. (The elements of the array represent the nul-separated elements of the original text string.)

display : | The GdkDisplay where the encoding is defined.
encoding : | an atom representing the encoding. The most common values for this are STRING, or COMPOUND_TEXT. This is value used as the type for the property.
format : | the format of the property.
text : | The text data.
length : | The number of items to transform.
list : | location to store a terminated array of strings in the encoding of the current locale. This array should be freed using gdk_free_text_list().
Returns : | the number of strings stored in list, or 0, if the conversion failed.

Since 2.2

gdk_free_text_list ()

void                gdk_free_text_list                  (gchar **list);

Frees the array of strings created by gdk_text_property_to_text_list().

list : the value stored in the list parameter by a call to gdk_text_property_to_text_list().

gdk_text_property_to_utf8_list ()

gint                gdk_text_property_to_utf8_list      (GdkAtom encoding,
                                                         gint format,
                                                         const guchar *text,
                                                         gint length,
                                                         gchar ***list);

Convert a text property in the giving encoding to a list of UTF-8 strings.

encoding : | an atom representing the encoding of the text
format : | the format of the property
text : | the text to convert
length : | the length of text, in bytes
list : | location to store the list of strings or NULL. The list should be freed with g_strfreev().
Returns : | the number of strings in the resulting list.

gdk_text_property_to_utf8_list_for_display ()

gint                gdk_text_property_to_utf8_list_for_display
                                                        (GdkDisplay *display,
                                                         GdkAtom encoding,
                                                         gint format,
                                                         const guchar *text,
                                                         gint length,
                                                         gchar ***list);

Converts a text property in the given encoding to a list of UTF-8 strings.

display : | a GdkDisplay
encoding : | an atom representing the encoding of the text
format : | the format of the property
text : | the text to convert
length : | the length of text, in bytes
list : | location to store the list of strings or NULL. The list should be freed with g_strfreev().
Returns : | the number of strings in the resulting list.

Since 2.2

gdk_string_to_compound_text ()

gint                gdk_string_to_compound_text         (const gchar *str,
                                                         GdkAtom *encoding,
                                                         gint *format,
                                                         guchar **ctext,
                                                         gint *length);

Converts a string from the encoding of the current locale into a form suitable for storing in a window property.

str : | a nul-terminated string.
encoding : | location to store the encoding atom (to be used as the type for the property).
format : | location to store the format for the property.
ctext : | location to store newly allocated data for the property.
length : | location to store the length of ctext in items.
Returns : | 0 upon sucess, non-zero upon failure.

gdk_string_to_compound_text_for_display ()

gint                gdk_string_to_compound_text_for_display
                                                        (GdkDisplay *display,
                                                         const gchar *str,
                                                         GdkAtom *encoding,
                                                         gint *format,
                                                         guchar **ctext,
                                                         gint *length);

Convert a string from the encoding of the current locale into a form suitable for storing in a window property.

display : | the GdkDisplay where the encoding is defined.
str : | a nul-terminated string.
encoding : | location to store the encoding atom (to be used as the type for the property).
format : | location to store the format of the property
ctext : | location to store newly allocated data for the property.
length : | the length of text, in bytes
Returns : | 0 upon sucess, non-zero upon failure.

Since 2.2

gdk_free_compound_text ()

void                gdk_free_compound_text              (guchar *ctext);

Frees the data returned from gdk_string_to_compound_text().

ctext : The pointer stored in ctext from a call to gdk_string_to_compound_text().

gdk_utf8_to_string_target ()

gchar*              gdk_utf8_to_string_target           (const gchar *str);

Convert an UTF-8 string into the best possible representation as a STRING. The representation of characters not in STRING is not specified; it may be as pseudo-escape sequences \x{ABCD}, or it may be in some other form of approximation.

str : | a UTF-8 string
Returns : | the newly allocated string, or NULL if the conversion failed. (It should not fail for any properly formed UTF-8 string.)

gdk_utf8_to_compound_text ()

gboolean            gdk_utf8_to_compound_text           (const gchar *str,
                                                         GdkAtom *encoding,
                                                         gint *format,
                                                         guchar **ctext,
                                                         gint *length);

Convert from UTF-8 to compound text.

str : | a UTF-8 string
encoding : | location to store resulting encoding
format : | location to store format of the result
ctext : | location to store the data of the result
length : | location to store the length of the data stored in ctext
Returns : | TRUE if the conversion succeeded, otherwise false.

gdk_utf8_to_compound_text_for_display ()

gboolean            gdk_utf8_to_compound_text_for_display
                                                        (GdkDisplay *display,
                                                         const gchar *str,
                                                         GdkAtom *encoding,
                                                         gint *format,
                                                         guchar **ctext,
                                                         gint *length);

Converts from UTF-8 to compound text.

display : | a GdkDisplay
str : | a UTF-8 string
encoding : | location to store resulting encoding
format : | location to store format of the result
ctext : | location to store the data of the result
length : | location to store the length of the data stored in ctext
Returns : | TRUE if the conversion succeeded, otherwise FALSE.

Since 2.2

gdk_atom_intern ()

GdkAtom             gdk_atom_intern                     (const gchar *atom_name,
                                                         gboolean only_if_exists);

Finds or creates an atom corresponding to a given string.

atom_name : | a string.
only_if_exists : | if TRUE, GDK is allowed to not create a new atom, but just return GDK_NONE if the requested atom doesn't already exists. Currently, the flag is ignored, since checking the existance of an atom is as expensive as creating it.
Returns : | the atom corresponding to atom_name.

gdk_atom_intern_static_string ()

GdkAtom             gdk_atom_intern_static_string       (const gchar *atom_name);

Finds or creates an atom corresponding to a given string.

Note that this function is identical to gdk_atom_intern() except that if a new GdkAtom is created the string itself is used rather than a copy. This saves memory, but can only be used if the string will always exist. It can be used with statically allocated strings in the main program, but not with statically allocated memory in dynamically loaded modules, if you expect to ever unload the module again (e.g. do not use this function in GTK+ theme engines).

atom_name : | a static string
Returns : | the atom corresponding to atom_name

Since 2.10

gdk_atom_name ()

gchar*              gdk_atom_name                       (GdkAtom atom);

Determines the string corresponding to an atom.

atom : | a GdkAtom.
Returns : | a newly-allocated string containing the string corresponding to atom. When you are done with the return value, you should free it using g_free().

gdk_property_get ()

gboolean            gdk_property_get                    (GdkWindow *window,
                                                         GdkAtom property,
                                                         GdkAtom type,
                                                         gulong offset,
                                                         gulong length,
                                                         gint pdelete,
                                                         GdkAtom *actual_property_type,
                                                         gint *actual_format,
                                                         gint *actual_length,
                                                         guchar **data);

Retrieves a portion of the contents of a property. If the property does not exist, then the function returns FALSE, and GDK_NONE will be stored in actual_property_type.

Note

The XGetWindowProperty() function that gdk_property_get() uses has a very confusing and complicated set of semantics. Unfortunately, gdk_property_get() makes the situation worse instead of better (the semantics should be considered undefined), and also prints warnings to stderr in cases where it should return a useful error to the program. You are advised to use XGetWindowProperty() directly until a replacement function for gdk_property_get() is provided.

window : | a GdkWindow.
property : | the property to retrieve.
type : | the desired property type, or GDK_NONE, if any type of data is acceptable. If this does not match the actual type, then actual_format and actual_length will be filled in, a warning will be printed to stderr and no data will be returned.
offset : | the offset into the property at which to begin retrieving data, in 4 byte units.
length : | the length of the data to retrieve in bytes. Data is considered to be retrieved in 4 byte chunks, so length will be rounded up to the next highest 4 byte boundary (so be careful not to pass a value that might overflow when rounded up).
pdelete : | if TRUE, delete the property after retrieving the data.
actual_property_type : | location to store the actual type of the property.
actual_format : | location to store the actual return format of the data; either 8, 16 or 32 bits.
actual_length : | location to store the length of the retrieved data, in bytes. Data returned in the 32 bit format is stored in a long variable, so the actual number of 32 bit elements should be be calculated via actual_length/sizeof(glong) to ensure portability to 64 bit systems.
data : | location to store a pointer to the data. The retrieved data should be freed with g_free() when you are finished using it.
Returns : | TRUE if data was sucessfully received and stored in data, otherwise FALSE.

gdk_property_change ()

void                gdk_property_change                 (GdkWindow *window,
                                                         GdkAtom property,
                                                         GdkAtom type,
                                                         gint format,
                                                         GdkPropMode mode,
                                                         const guchar *data,
                                                         gint nelements);

Changes the contents of a property on a window.

window : | a GdkWindow.
property : | the property to change.
type : | the new type for the property. If mode is GDK_PROP_MODE_PREPEND or GDK_PROP_MODE_APPEND, then this must match the existing type or an error will occur.
format : | the new format for the property. If mode is GDK_PROP_MODE_PREPEND or GDK_PROP_MODE_APPEND, then this must match the existing format or an error will occur.
mode : | a value describing how the new data is to be combined with the current data.
data : | the data (a guchar * gushort *, or gulong *, depending on format), cast to a guchar *.
nelements : | the number of elements of size determined by the format, contained in data.

enum GdkPropMode

typedef enum
{
  GDK_PROP_MODE_REPLACE,
  GDK_PROP_MODE_PREPEND,
  GDK_PROP_MODE_APPEND
} GdkPropMode;

Describes how existing data is combined with new data when using gdk_property_change().

GDK_PROP_MODE_REPLACE | the new data replaces the existing data.
GDK_PROP_MODE_PREPEND | the new data is prepended to the existing data.
GDK_PROP_MODE_APPEND | the new data is appended to the existing data.

gdk_property_delete ()

void                gdk_property_delete                 (GdkWindow *window,
                                                         GdkAtom property);

Deletes a property from a window.

window : | a GdkWindow.
property : | the property to delete.


Selections

Selections — Functions for transfering data via the X selection mechanism

Synopsis

#include <gdk/gdk.h>

typedef             GdkSelection;
typedef             GdkSelectionType;
typedef             GdkTarget;
#define             GDK_SELECTION_PRIMARY
#define             GDK_SELECTION_SECONDARY
#define             GDK_SELECTION_CLIPBOARD
#define             GDK_TARGET_BITMAP
#define             GDK_TARGET_COLORMAP
#define             GDK_TARGET_DRAWABLE
#define             GDK_TARGET_PIXMAP
#define             GDK_TARGET_STRING
#define             GDK_SELECTION_TYPE_ATOM
#define             GDK_SELECTION_TYPE_BITMAP
#define             GDK_SELECTION_TYPE_COLORMAP
#define             GDK_SELECTION_TYPE_DRAWABLE
#define             GDK_SELECTION_TYPE_INTEGER
#define             GDK_SELECTION_TYPE_PIXMAP
#define             GDK_SELECTION_TYPE_WINDOW
#define             GDK_SELECTION_TYPE_STRING
gboolean            gdk_selection_owner_set             (GdkWindow *owner,
                                                         GdkAtom selection,
                                                         guint32 time_,
                                                         gboolean send_event);
gboolean            gdk_selection_owner_set_for_display (GdkDisplay *display,
                                                         GdkWindow *owner,
                                                         GdkAtom selection,
                                                         guint32 time_,
                                                         gboolean send_event);
GdkWindow*          gdk_selection_owner_get             (GdkAtom selection);
GdkWindow*          gdk_selection_owner_get_for_display (GdkDisplay *display,
                                                         GdkAtom selection);
void                gdk_selection_convert               (GdkWindow *requestor,
                                                         GdkAtom selection,
                                                         GdkAtom target,
                                                         guint32 time_);
gboolean            gdk_selection_property_get          (GdkWindow *requestor,
                                                         guchar **data,
                                                         GdkAtom *prop_type,
                                                         gint *prop_format);
void                gdk_selection_send_notify           (guint32 requestor,
                                                         GdkAtom selection,
                                                         GdkAtom target,
                                                         GdkAtom property,
                                                         guint32 time_);
void                gdk_selection_send_notify_for_display
                                                        (GdkDisplay *display,
                                                         guint32 requestor,
                                                         GdkAtom selection,
                                                         GdkAtom target,
                                                         GdkAtom property,
                                                         guint32 time_);

Description

The X selection mechanism provides a way to transfer arbitrary chunks of data between programs. A selection is a essentially a named clipboard, identified by a string interned as a GdkAtom. By claiming ownership of a selection, an application indicates that it will be responsible for supplying its contents. The most common selections are PRIMARY and CLIPBOARD.

The contents of a selection can be represented in a number of formats, called targets. Each target is identified by an atom. A list of all possible targets supported by the selection owner can be retrieved by requesting the special target TARGETS. When a selection is retrieved, the data is accompanied by a type (an atom), and a format (an integer, representing the number of bits per item). See Properties and Atoms for more information.

The functions in this section only contain the lowlevel parts of the selection protocol. A considerably more complicated implementation is needed on top of this. GTK+ contains such an implementation in the functions in gtkselection.h and programmers should use those functions instead of the ones presented here. If you plan to implement selection handling directly on top of the functions here, you should refer to the X Inter-client Communication Conventions Manual (ICCCM).

Details

GdkSelection

typedef GdkAtom GdkSelection;

Warning

GdkSelection is deprecated and should not be used in newly-written code.

The GdkSelection enumeration contains predefined atom values for several common selections.

GdkSelectionType

typedef GdkAtom GdkSelectionType;

Warning

GdkSelectionType is deprecated and should not be used in newly-written code.

The GdkSelectionType enumeration contains predefined atom values used to represent the types of data transferred in response to a request for a target. See the ICCCM for details about what data should be transferred for each of these types. Other atoms can be used, and the recommended practice for GTK+ is to to use mime types for this purpose. However, supporting these types may be useful for compatibility with older programs.

GdkTarget

typedef GdkAtom GdkTarget;

Warning

GdkTarget is deprecated and should not be used in newly-written code.

The GdkTarget enumeration contains predefined atom values which are used to describe possible targets for a selection. Other atoms can be used, and the recommended practice for GTK+ is to to use mime types for this purpose. However, supporting these types may be useful for compatibility with older programs.

GDK_SELECTION_PRIMARY

#define GDK_SELECTION_PRIMARY 		_GDK_MAKE_ATOM (1)

A GdkAtom representing the PRIMARY selection.

GDK_SELECTION_SECONDARY

#define GDK_SELECTION_SECONDARY 	_GDK_MAKE_ATOM (2)

A GdkAtom representing the SECONDARY selection.

GDK_SELECTION_CLIPBOARD

#define GDK_SELECTION_CLIPBOARD 	_GDK_MAKE_ATOM (69)

A GdkAtom representing the CLIPBOARD selection.

GDK_TARGET_BITMAP

#define GDK_TARGET_BITMAP 		_GDK_MAKE_ATOM (5)

A GdkAtom representing the BITMAP selection target.

GDK_TARGET_COLORMAP

#define GDK_TARGET_COLORMAP 		_GDK_MAKE_ATOM (7)

A GdkAtom representing the COLORMAP selection target.

GDK_TARGET_DRAWABLE

#define GDK_TARGET_DRAWABLE 		_GDK_MAKE_ATOM (17)

A GdkAtom representing the DRAWABLE selection target.

GDK_TARGET_PIXMAP

#define GDK_TARGET_PIXMAP 		_GDK_MAKE_ATOM (20)

A GdkAtom representing the PIXMAP selection target.

GDK_TARGET_STRING

#define GDK_TARGET_STRING 		_GDK_MAKE_ATOM (31)

A GdkAtom representing the STRING selection target.

GDK_SELECTION_TYPE_ATOM

#define GDK_SELECTION_TYPE_ATOM 	_GDK_MAKE_ATOM (4)

A GdkAtom representing the ATOM selection type.

GDK_SELECTION_TYPE_BITMAP

#define GDK_SELECTION_TYPE_BITMAP 	_GDK_MAKE_ATOM (5)

A GdkAtom representing the BITMAP selection type.

GDK_SELECTION_TYPE_COLORMAP

#define GDK_SELECTION_TYPE_COLORMAP 	_GDK_MAKE_ATOM (7)

A GdkAtom representing the COLORMAP selection type.

GDK_SELECTION_TYPE_DRAWABLE

#define GDK_SELECTION_TYPE_DRAWABLE 	_GDK_MAKE_ATOM (17)

A GdkAtom representing the DRAWABLE selection type.

GDK_SELECTION_TYPE_INTEGER

#define GDK_SELECTION_TYPE_INTEGER 	_GDK_MAKE_ATOM (19)

A GdkAtom representing the INTEGER selection type.

GDK_SELECTION_TYPE_PIXMAP

#define GDK_SELECTION_TYPE_PIXMAP 	_GDK_MAKE_ATOM (20)

A GdkAtom representing the PIXMAP selection type.

GDK_SELECTION_TYPE_WINDOW

#define GDK_SELECTION_TYPE_WINDOW 	_GDK_MAKE_ATOM (33)

A GdkAtom representing the WINDOW selection type.

GDK_SELECTION_TYPE_STRING

#define GDK_SELECTION_TYPE_STRING 	_GDK_MAKE_ATOM (31)

A GdkAtom representing the STRING selection type.

gdk_selection_owner_set ()

gboolean            gdk_selection_owner_set             (GdkWindow *owner,
                                                         GdkAtom selection,
                                                         guint32 time_,
                                                         gboolean send_event);

Sets the owner of the given selection.

owner : | a GdkWindow or NULL to indicate that the the owner for the given should be unset.
selection : | an atom identifying a selection.
time_ : | timestamp to use when setting the selection. If this is older than the timestamp given last time the owner was set for the given selection, the request will be ignored.
send_event : | if TRUE, and the new owner is different from the current owner, the current owner will be sent a SelectionClear event.
Returns : | TRUE if the selection owner was successfully changed to owner, otherwise FALSE.

gdk_selection_owner_set_for_display ()

gboolean            gdk_selection_owner_set_for_display (GdkDisplay *display,
                                                         GdkWindow *owner,
                                                         GdkAtom selection,
                                                         guint32 time_,
                                                         gboolean send_event);

Sets the GdkWindow owner as the current owner of the selection selection.

display : | the GdkDisplay.
owner : | a GdkWindow or NULL to indicate that the owner for the given should be unset.
selection : | an atom identifying a selection.
time_ : | timestamp to use when setting the selection. If this is older than the timestamp given last time the owner was set for the given selection, the request will be ignored.
send_event : | if TRUE, and the new owner is different from the current owner, the current owner will be sent a SelectionClear event.
Returns : | TRUE if the selection owner was successfully changed to owner, otherwise FALSE.

Since 2.2

gdk_selection_owner_get ()

GdkWindow*          gdk_selection_owner_get             (GdkAtom selection);

Determines the owner of the given selection.

selection : | an atom indentifying a selection.
Returns : | if there is a selection owner for this window, and it is a window known to the current process, the GdkWindow that owns the selection, otherwise NULL. Note that the return value may be owned by a different process if a foreign window was previously created for that window, but a new foreign window will never be created by this call.

gdk_selection_owner_get_for_display ()

GdkWindow*          gdk_selection_owner_get_for_display (GdkDisplay *display,
                                                         GdkAtom selection);

Determine the owner of the given selection.

Note that the return value may be owned by a different process if a foreign window was previously created for that window, but a new foreign window will never be created by this call.

display : | a GdkDisplay.
selection : | an atom indentifying a selection.
Returns : | if there is a selection owner for this window, and it is a window known to the current process, the GdkWindow that owns the selection, otherwise NULL.

Since 2.2

gdk_selection_convert ()

void                gdk_selection_convert               (GdkWindow *requestor,
                                                         GdkAtom selection,
                                                         GdkAtom target,
                                                         guint32 time_);

Retrieves the contents of a selection in a given form.

requestor : | a GdkWindow.
selection : | an atom identifying the selection to get the contents of.
target : | the form in which to retrieve the selection.
time_ : | the timestamp to use when retrieving the selection. The selection owner may refuse the request if it did not own the selection at the time indicated by the timestamp.

gdk_selection_property_get ()

gboolean            gdk_selection_property_get          (GdkWindow *requestor,
                                                         guchar **data,
                                                         GdkAtom *prop_type,
                                                         gint *prop_format);

Retrieves selection data that was stored by the selection data in response to a call to gdk_selection_convert(). This function will not be used by applications, who should use the GtkClipboard API instead.

requestor : | the window on which the data is stored
data : | location to store a pointer to the retrieved data. If the retrieval failed, NULL we be stored here, otherwise, it will be non-NULL and the returned data should be freed with g_free() when you are finished using it. The length of the allocated memory is one more than the length of the returned data, and the final byte will always be zero, to ensure nul-termination of strings.
prop_type : | location to store the type of the property.
prop_format : | location to store the format of the property.
Returns : | the length of the retrieved data.

gdk_selection_send_notify ()

void                gdk_selection_send_notify           (guint32 requestor,
                                                         GdkAtom selection,
                                                         GdkAtom target,
                                                         GdkAtom property,
                                                         guint32 time_);

Sends a response to SelectionRequest event.

requestor : | window to which to deliver response.
selection : | selection that was requested.
target : | target that was selected.
property : | property in which the selection owner stored the data, or GDK_NONE to indicate that the request was rejected.
time_ : | timestamp.

gdk_selection_send_notify_for_display ()

void                gdk_selection_send_notify_for_display
                                                        (GdkDisplay *display,
                                                         guint32 requestor,
                                                         GdkAtom selection,
                                                         GdkAtom target,
                                                         GdkAtom property,
                                                         guint32 time_);

Send a response to SelectionRequest event.

display : | the GdkDisplay where requestor is realized
requestor : | window to which to deliver response.
selection : | selection that was requested.
target : | target that was selected.
property : | property in which the selection owner stored the data, or GDK_NONE to indicate that the request was rejected.
time_ : | timestamp.

Since 2.2


Threads

Threads — Functions for using GDK in multi-threaded programs

Synopsis

#include <gdk/gdk.h>

#define             GDK_THREADS_ENTER                   ()
#define             GDK_THREADS_LEAVE                   ()
void                gdk_threads_init                    (void);
void                gdk_threads_enter                   (void);
void                gdk_threads_leave                   (void);
extern              GMutex *gdk_threads_mutex;
void                gdk_threads_set_lock_functions      (GCallback enter_fn,
                                                         GCallback leave_fn);

Description

For thread safety, GDK relies on the thread primitives in GLib, and on the thread-safe GLib main loop.

GLib is completely thread safe (all global data is automatically locked), but individual data structure instances are not automatically locked for performance reasons. So e.g. you must coordinate accesses to the same GHashTable from multiple threads.

GTK+ is "thread aware" but not thread safe — it provides a global lock controlled by gdk_threads_enter()/gdk_threads_leave() which protects all use of GTK+. That is, only one thread can use GTK+ at any given time.

Unfortunately the above holds with the X11 backend only. With the Win32 backend, GDK calls should not be attempted from multiple threads at all.

You must call g_thread_init() and gdk_threads_init() before executing any other GTK+ or GDK functions in a threaded GTK+ program.

Idles, timeouts, and input functions are executed outside of the main GTK+ lock. So, if you need to call GTK+ inside of such a callback, you must surround the callback with a gdk_threads_enter()/gdk_threads_leave() pair. (However, signals are still executed within the main GTK+ lock.)

In particular, this means, if you are writing widgets that might be used in threaded programs, you must surround timeouts and idle functions in this matter.

As always, you must also surround any calls to GTK+ not made within a signal handler with a gdk_threads_enter()/gdk_threads_leave() pair.

Before calling gdk_threads_leave() from a thread other than your main thread, you probably want to call gdk_flush() to send all pending commands to the windowing system. (The reason you don't need to do this from the main thread is that GDK always automatically flushes pending commands when it runs out of incoming events to process and has to sleep while waiting for more events.)

A minimal main program for a threaded GTK+ application looks like:

int
main (int argc, char *argv[])
{
  GtkWidget *window;

  g_thread_init (NULL);
  gdk_threads_init ();
  gdk_threads_enter ();

  gtk_init (&argc, &argv);

  window = create_window ();
  gtk_widget_show (window);

  gtk_main ();
  gdk_threads_leave ();

  return 0;
}

Callbacks require a bit of attention. Callbacks from GTK+ signals are made within the GTK+ lock. However callbacks from GLib (timeouts, IO callbacks, and idle functions) are made outside of the GTK+ lock. So, within a signal handler you do not need to call gdk_threads_enter(), but within the other types of callbacks, you do.

Erik Mouw contributed the following code example to illustrate how to use threads within GTK+ programs.

/*-------------------------------------------------------------------------
 * Filename:      gtk-thread.c
 * Version:       0.99.1
 * Copyright:     Copyright (C) 1999, Erik Mouw
 * Author:        Erik Mouw <J.A.K.Mouw@its.tudelft.nl>
 * Description:   GTK threads example.
 * Created at:    Sun Oct 17 21:27:09 1999
 * Modified by:   Erik Mouw <J.A.K.Mouw@its.tudelft.nl>
 * Modified at:   Sun Oct 24 17:21:41 1999
 *-----------------------------------------------------------------------*/
/*
 * Compile with:
 *
 * cc -o gtk-thread gtk-thread.c `gtk-config --cflags --libs gthread`
 *
 * Thanks to Sebastian Wilhelmi and Owen Taylor for pointing out some
 * bugs.
 *
 */

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <time.h>
#include <gtk/gtk.h>
#include <glib.h>
#include <pthread.h>

#define YES_IT_IS    (1)
#define NO_IT_IS_NOT (0)

typedef struct
{
  GtkWidget *label;
  int what;
} yes_or_no_args;

G_LOCK_DEFINE_STATIC (yes_or_no);
static volatile int yes_or_no = YES_IT_IS;

void destroy (GtkWidget *widget, gpointer data)
{
  gtk_main_quit ();
}

void *argument_thread (void *args)
{
  yes_or_no_args *data = (yes_or_no_args *)args;
  gboolean say_something;

  for (;;)
    {
      /* sleep a while */
      sleep(rand() / (RAND_MAX / 3) + 1);

      /* lock the yes_or_no_variable */
      G_LOCK(yes_or_no);

      /* do we have to say something? */
      say_something = (yes_or_no != data->what);

      if(say_something)
    {
      /* set the variable */
      yes_or_no = data->what;
    }

      /* Unlock the yes_or_no variable */
      G_UNLOCK (yes_or_no);

      if (say_something)
    {
      /* get GTK thread lock */
      gdk_threads_enter ();

      /* set label text */
      if(data->what == YES_IT_IS)
        gtk_label_set_text (GTK_LABEL (data->label), "O yes, it is!");
      else
        gtk_label_set_text (GTK_LABEL (data->label), "O no, it isn't!");

      /* release GTK thread lock */
      gdk_threads_leave ();
    }
    }

  return NULL;
}

int main (int argc, char *argv[])
{
  GtkWidget *window;
  GtkWidget *label;
  yes_or_no_args yes_args, no_args;
  pthread_t no_tid, yes_tid;

  /* init threads */
  g_thread_init (NULL);
  gdk_threads_init ();
  gdk_threads_enter ();

  /* init gtk */
  gtk_init(&argc, &argv);

  /* init random number generator */
  srand ((unsigned int) time (NULL));

  /* create a window */
  window = gtk_window_new (GTK_WINDOW_TOPLEVEL);

  gtk_signal_connect (GTK_OBJECT (window), "destroy",
              GTK_SIGNAL_FUNC (destroy), NULL);

  gtk_container_set_border_width (GTK_CONTAINER (window), 10);

  /* create a label */
  label = gtk_label_new ("And now for something completely different ...");
  gtk_container_add (GTK_CONTAINER (window), label);

  /* show everything */
  gtk_widget_show (label);
  gtk_widget_show (window);

  /* create the threads */
  yes_args.label = label;
  yes_args.what = YES_IT_IS;
  pthread_create (&yes_tid, NULL, argument_thread, &yes_args);

  no_args.label = label;
  no_args.what = NO_IT_IS_NOT;
  pthread_create (&no_tid, NULL, argument_thread, &no_args);

  /* enter the GTK main loop */
  gtk_main ();
  gdk_threads_leave ();

  return 0;
}

Details

GDK_THREADS_ENTER()

#define             GDK_THREADS_ENTER()

This macro marks the beginning of a critical section in which GDK and GTK+ functions can be called. Only one thread at a time can be in such a critial section. The macro expands to a no-op if G_THREADS_ENABLED has not been defined. Typically gdk_threads_enter() should be used instead of this macro.

GDK_THREADS_LEAVE()

#define             GDK_THREADS_LEAVE()

This macro marks the end of a critical section begun with GDK_THREADS_ENTER.

gdk_threads_init ()

void                gdk_threads_init                    (void);

Initializes GDK so that it can be used from multiple threads in conjunction with gdk_threads_enter() and gdk_threads_leave(). g_thread_init() must be called previous to this function.

This call must be made before any use of the main loop from GTK+; to be safe, call it before gtk_init().

gdk_threads_enter ()

void                gdk_threads_enter                   (void);

This macro marks the beginning of a critical section in which GDK and GTK+ functions can be called. Only one thread at a time can be in such a critial section.

gdk_threads_leave ()

void                gdk_threads_leave                   (void);

Leaves a critical region begun with gdk_threads_enter().

gdk_threads_mutex

extern GMutex *gdk_threads_mutex; /* private */

Warning

gdk_threads_mutex is deprecated and should not be used in newly-written code.

The GMutex used to implement the critical region for gdk_threads_enter()/gdk_threads_leave().

gdk_threads_set_lock_functions ()

void                gdk_threads_set_lock_functions      (GCallback enter_fn,
                                                         GCallback leave_fn);

Allows the application to replace the standard method that GDK uses to protect its data structures. Normally, GDK creates a single GMutex that is locked by gdk_threads_enter(), and released by gdk_threads_leave(); using this function an application provides, instead, a function enter_fn that is called by gdk_threads_enter() and a function leave_fn that is called by gdk_threads_leave().

The functions must provide at least same locking functionality as the default implementation, but can also do extra application specific processing.

As an example, consider an application that has its own recursive lock that when held, holds the GTK+ lock as well. When GTK+ unlocks the GTK+ lock when entering a recursive main loop, the application must temporarily release its lock as well.

Most threaded GTK+ apps won't need to use this method.

This method must be called before gdk_threads_init(), and cannot be called multiple times.

enter_fn : | function called to guard GDK
leave_fn : | function called to release the guard

Since 2.4


Visuals

Visuals — Low-level display hardware information

Synopsis

#include <gdk/gdk.h>

                    GdkVisual;
enum                GdkVisualType;
enum                GdkByteOrder;
void                gdk_query_depths                    (gint **depths,
                                                         gint *count);
void                gdk_query_visual_types              (GdkVisualType **visual_types,
                                                         gint *count);
GList*              gdk_list_visuals                    (void);
gint                gdk_visual_get_best_depth           (void);
GdkVisualType       gdk_visual_get_best_type            (void);
GdkVisual*          gdk_visual_get_system               (void);
GdkVisual*          gdk_visual_get_best                 (void);
GdkVisual*          gdk_visual_get_best_with_depth      (gint depth);
GdkVisual*          gdk_visual_get_best_with_type       (GdkVisualType visual_type);
GdkVisual*          gdk_visual_get_best_with_both       (gint depth,
                                                         GdkVisualType visual_type);
#define             gdk_visual_ref                      (v)
#define             gdk_visual_unref                    (v)
GdkScreen*          gdk_visual_get_screen               (GdkVisual *visual);

Description

A GdkVisual describes a particular video hardware display format. It includes information about the number of bits used for each color, the way the bits are translated into an RGB value for display, and the way the bits are stored in memory. For example, a piece of display hardware might support 24-bit color, 16-bit color, or 8-bit color; meaning 24/16/8-bit pixel sizes. For a given pixel size, pixels can be in different formats; for example the "red" element of an RGB pixel may be in the top 8 bits of the pixel, or may be in the lower 4 bits.

Usually you can avoid thinking about visuals in GTK+. Visuals are useful to interpret the contents of a GdkImage, but you should avoid GdkImage precisely because its contents depend on the display hardware; use GdkPixbuf instead, for all but the most low-level purposes. Also, anytime you provide a GdkColormap, the visual is implied as part of the colormap (gdk_colormap_get_visual()), so you won't have to provide a visual in addition.

There are several standard visuals. The visual returned by gdk_visual_get_system() is the system's default visual. gdk_rgb_get_visual() return the visual most suited to displaying full-color image data. If you use the calls in GdkRGB, you should create your windows using this visual (and the colormap returned by gdk_rgb_get_colormap()).

A number of functions are provided for determining the "best" available visual. For the purposes of making this determination, higher bit depths are considered better, and for visuals of the same bit depth, GDK_VISUAL_PSEUDO_COLOR is preferred at 8bpp, otherwise, the visual types are ranked in the order of (highest to lowest) GDK_VISUAL_DIRECT_COLOR, GDK_VISUAL_TRUE_COLOR, GDK_VISUAL_PSEUDO_COLOR, GDK_VISUAL_STATIC_COLOR, GDK_VISUAL_GRAYSCALE, then GDK_VISUAL_STATIC_GRAY.

Details

GdkVisual

typedef struct {
  GObject parent_instance;

  GdkVisualType type;
  gint depth;
  GdkByteOrder byte_order;
  gint colormap_size;
  gint bits_per_rgb;

  guint32 red_mask;
  gint red_shift;
  gint red_prec;

  guint32 green_mask;
  gint green_shift;
  gint green_prec;

  guint32 blue_mask;
  gint blue_shift;
  gint blue_prec;
} GdkVisual;

The GdkVisual structure contains information about a particular visual.

Example 5. Constructing a pixel value from components

guint
pixel_from_rgb (GdkVisual *visual,
                guchar r, guchar b, guchar g)
{
  return ((r >> (16 - visual->red_prec))   << visual->red_shift) |
         ((g >> (16 - visual->green_prec)) << visual->green_shift) |
         ((r >> (16 - visual->blue_prec))  << visual->blue_shift);
}

GObject parent_instance; | inherited portion from GObject
GdkVisualType type; | The type of this visual.
gint depth; | The number of bits per pixel.
GdkByteOrder byte_order; | The byte-order for this visual.
gint colormap_size; | The number of entries in the colormap, for visuals of type GDK_VISUAL_PSEUDO_COLOR or GDK_VISUAL_GRAY_SCALE. For other visual types, it is the number of possible levels per color component. If the visual has different numbers of levels for different components, the value of this field is undefined.
gint bits_per_rgb; | The number of significant bits per red, green, or blue when specifying colors for this visual. (For instance, for gdk_colormap_alloc_color())
guint32 red_mask; | A mask giving the bits in a pixel value that correspond to the red field. Significant only for GDK_VISUAL_PSEUDOCOLOR and GDK_VISUAL_DIRECTCOLOR.
gint red_shift; | The red_shift and red_prec give an alternate presentation of the information in red_mask. red_mask is a contiguous sequence of red_prec bits starting at bit number red_shift. For example, Example 5, “Constructing a pixel value from components” shows constructing a pixel value out of three 16 bit color values.
gint red_prec; | See above.
guint32 green_mask; | A mask giving the bits in a pixel value that correspond to the green field.
gint green_shift; | The green_shift and green_prec give an alternate presentation of the information in green_mask.
gint green_prec; | See above.
guint32 blue_mask; | A mask giving the bits in a pixel value that correspond to the blue field.
gint blue_shift; | The blue_shift and blue_prec give an alternate presentation of the information in blue_mask.
gint blue_prec; | See above.

enum GdkVisualType

typedef enum
{
  GDK_VISUAL_STATIC_GRAY,
  GDK_VISUAL_GRAYSCALE,
  GDK_VISUAL_STATIC_COLOR,
  GDK_VISUAL_PSEUDO_COLOR,
  GDK_VISUAL_TRUE_COLOR,
  GDK_VISUAL_DIRECT_COLOR
} GdkVisualType;

A set of values that describe the manner in which the pixel values for a visual are converted into RGB values for display.

GDK_VISUAL_STATIC_GRAY | Each pixel value indexes a grayscale value directly.
GDK_VISUAL_GRAYSCALE | Each pixel is an index into a color map that maps pixel values into grayscale values. The color map can be changed by an application.
GDK_VISUAL_STATIC_COLOR | Each pixel value is an index into a predefined, unmodifiable color map that maps pixel values into RGB values.
GDK_VISUAL_PSEUDO_COLOR | Each pixel is an index into a color map that maps pixel values into rgb values. The color map can be changed by an application.
GDK_VISUAL_TRUE_COLOR | Each pixel value directly contains red, green, and blue components. The red_mask, green_mask, and blue_mask fields of the GdkVisual structure describe how the components are assembled into a pixel value.
GDK_VISUAL_DIRECT_COLOR | Each pixel value contains red, green, and blue components as for GDK_VISUAL_TRUE_COLOR, but the components are mapped via a color table into the final output table instead of being converted directly.

enum GdkByteOrder

typedef enum
{
  GDK_LSB_FIRST,
  GDK_MSB_FIRST
} GdkByteOrder;

A set of values describing the possible byte-orders for storing pixel values in memory.

GDK_LSB_FIRST | The values are stored with the least-significant byte first. For instance, the 32-bit value 0xffeecc would be stored in memory as 0xcc, 0xee, 0xff, 0x00.
GDK_MSB_FIRST | The values are stored with the most-significant byte first. For instance, the 32-bit value 0xffeecc would be stored in memory as 0x00, 0xcc, 0xee, 0xff.

gdk_query_depths ()

void                gdk_query_depths                    (gint **depths,
                                                         gint *count);

This function returns the available bit depths for the default screen. It's equivalent to listing the visuals (gdk_list_visuals()) and then looking at the depth field in each visual, removing duplicates.

The array returned by this function should not be freed.

depths : | return location for available depths
count : | return location for number of available depths

gdk_query_visual_types ()

void                gdk_query_visual_types              (GdkVisualType **visual_types,
                                                         gint *count);

This function returns the available visual types for the default screen. It's equivalent to listing the visuals (gdk_list_visuals()) and then looking at the type field in each visual, removing duplicates.

The array returned by this function should not be freed.

visual_types : | return location for the available visual types
count : | return location for the number of available visual types

gdk_list_visuals ()

GList*              gdk_list_visuals                    (void);

Lists the available visuals for the default screen. (See gdk_screen_list_visuals()) A visual describes a hardware image data format. For example, a visual might support 24-bit color, or 8-bit color, and might expect pixels to be in a certain format.

Call g_list_free() on the return value when you're finished with it.

Returns : a list of visuals; the list must be freed, but not its contents

gdk_visual_get_best_depth ()

gint                gdk_visual_get_best_depth           (void);

Get the best available depth for the default GDK screen. "Best" means "largest," i.e. 32 preferred over 24 preferred over 8 bits per pixel.

Returns : best available depth

gdk_visual_get_best_type ()

GdkVisualType       gdk_visual_get_best_type            (void);

Return the best available visual type for the default GDK screen.

Returns : best visual type

gdk_visual_get_system ()

GdkVisual*          gdk_visual_get_system               (void);

Get the system'sdefault visual for the default GDK screen. This is the visual for the root window of the display. The return value should not be freed.

Returns : system visual

gdk_visual_get_best ()

GdkVisual*          gdk_visual_get_best                 (void);

Get the visual with the most available colors for the default GDK screen. The return value should not be freed.

Returns : best visual

gdk_visual_get_best_with_depth ()

GdkVisual*          gdk_visual_get_best_with_depth      (gint depth);

Get the best visual with depth depth for the default GDK screen. Color visuals and visuals with mutable colormaps are preferred over grayscale or fixed-colormap visuals. The return value should not be freed. NULL may be returned if no visual supports depth.

depth : | a bit depth
Returns : | best visual for the given depth

gdk_visual_get_best_with_type ()

GdkVisual*          gdk_visual_get_best_with_type       (GdkVisualType visual_type);

Get the best visual of the given visual_type for the default GDK screen. Visuals with higher color depths are considered better. The return value should not be freed. NULL may be returned if no visual has type visual_type.

visual_type : | a visual type
Returns : | best visual of the given type

gdk_visual_get_best_with_both ()

GdkVisual*          gdk_visual_get_best_with_both       (gint depth,
                                                         GdkVisualType visual_type);

Combines gdk_visual_get_best_with_depth() and gdk_visual_get_best_with_type().

depth : | a bit depth
visual_type : | a visual type
Returns : | best visual with both depth and visual_type, or NULL if none

gdk_visual_ref()

#define gdk_visual_ref(v) g_object_ref(v)

Warning

gdk_visual_ref is deprecated and should not be used in newly-written code.

Deprecated equivalent of g_object_ref().

v : | a GdkVisual
Returns : | the same visual

gdk_visual_unref()

#define gdk_visual_unref(v) g_object_unref(v)

Warning

gdk_visual_unref is deprecated and should not be used in newly-written code.

Deprecated equivalent of g_object_unref().

v : a GdkVisual

gdk_visual_get_screen ()

GdkScreen*          gdk_visual_get_screen               (GdkVisual *visual);

Gets the screen to which this visual belongs

visual : | a GdkVisual
Returns : | the screen to which this visual belongs.

Since 2.2

See Also

GdkImage, GdkColormap, GdkRGB


Windows

Windows — Onscreen display areas in the target window system

Synopsis

#include <gdk/gdk.h>

struct              GdkWindow;
enum                GdkWindowType;
enum                GdkWindowClass;
enum                GdkWindowHints;
                    GdkGeometry;
enum                GdkGravity;
enum                GdkWindowEdge;
enum                GdkWindowTypeHint;
                    GdkWindowAttr;
enum                GdkWindowAttributesType;
GdkWindow*          gdk_window_new                      (GdkWindow *parent,
                                                         GdkWindowAttr *attributes,
                                                         gint attributes_mask);
void                gdk_window_destroy                  (GdkWindow *window);
#define             gdk_window_ref
#define             gdk_window_unref
GdkWindowType       gdk_window_get_window_type          (GdkWindow *window);
GdkWindow*          gdk_window_at_pointer               (gint *win_x,
                                                         gint *win_y);
void                gdk_window_show                     (GdkWindow *window);
void                gdk_window_show_unraised            (GdkWindow *window);
void                gdk_window_hide                     (GdkWindow *window);
gboolean            gdk_window_is_visible               (GdkWindow *window);
gboolean            gdk_window_is_viewable              (GdkWindow *window);
GdkWindowState      gdk_window_get_state                (GdkWindow *window);
void                gdk_window_withdraw                 (GdkWindow *window);
void                gdk_window_iconify                  (GdkWindow *window);
void                gdk_window_deiconify                (GdkWindow *window);
void                gdk_window_stick                    (GdkWindow *window);
void                gdk_window_unstick                  (GdkWindow *window);
void                gdk_window_maximize                 (GdkWindow *window);
void                gdk_window_unmaximize               (GdkWindow *window);
void                gdk_window_fullscreen               (GdkWindow *window);
void                gdk_window_unfullscreen             (GdkWindow *window);
void                gdk_window_set_keep_above           (GdkWindow *window,
                                                         gboolean setting);
void                gdk_window_set_keep_below           (GdkWindow *window,
                                                         gboolean setting);
void                gdk_window_move                     (GdkWindow *window,
                                                         gint x,
                                                         gint y);
void                gdk_window_resize                   (GdkWindow *window,
                                                         gint width,
                                                         gint height);
void                gdk_window_move_resize              (GdkWindow *window,
                                                         gint x,
                                                         gint y,
                                                         gint width,
                                                         gint height);
void                gdk_window_scroll                   (GdkWindow *window,
                                                         gint dx,
                                                         gint dy);
void                gdk_window_move_region              (GdkWindow *window,
                                                         GdkRegion *region,
                                                         gint dx,
                                                         gint dy);
void                gdk_window_reparent                 (GdkWindow *window,
                                                         GdkWindow *new_parent,
                                                         gint x,
                                                         gint y);
void                gdk_window_clear                    (GdkWindow *window);
void                gdk_window_clear_area               (GdkWindow *window,
                                                         gint x,
                                                         gint y,
                                                         gint width,
                                                         gint height);
void                gdk_window_clear_area_e             (GdkWindow *window,
                                                         gint x,
                                                         gint y,
                                                         gint width,
                                                         gint height);
#define             gdk_window_copy_area                (drawable,gc,x,y,source_drawable,source_x,source_y,width,height)
void                gdk_window_raise                    (GdkWindow *window);
void                gdk_window_lower                    (GdkWindow *window);
void                gdk_window_focus                    (GdkWindow *window,
                                                         guint32 timestamp);
void                gdk_window_register_dnd             (GdkWindow *window);
void                gdk_window_begin_resize_drag        (GdkWindow *window,
                                                         GdkWindowEdge edge,
                                                         gint button,
                                                         gint root_x,
                                                         gint root_y,
                                                         guint32 timestamp);
void                gdk_window_begin_move_drag          (GdkWindow *window,
                                                         gint button,
                                                         gint root_x,
                                                         gint root_y,
                                                         guint32 timestamp);
void                gdk_window_constrain_size           (GdkGeometry *geometry,
                                                         guint flags,
                                                         gint width,
                                                         gint height,
                                                         gint *new_width,
                                                         gint *new_height);

void                gdk_window_begin_paint_rect         (GdkWindow *window,
                                                         GdkRectangle *rectangle);
void                gdk_window_begin_paint_region       (GdkWindow *window,
                                                         GdkRegion *region);
void                gdk_window_end_paint                (GdkWindow *window);

void                gdk_window_invalidate_rect          (GdkWindow *window,
                                                         GdkRectangle *rect,
                                                         gboolean invalidate_children);
void                gdk_window_invalidate_region        (GdkWindow *window,
                                                         GdkRegion *region,
                                                         gboolean invalidate_children);
void                gdk_window_invalidate_maybe_recurse (GdkWindow *window,
                                                         GdkRegion *region,
                                                         gboolean (*child_func) (GdkWindow *, gpointer),
                                                         gpointer user_data);
GdkRegion*          gdk_window_get_update_area          (GdkWindow *window);
void                gdk_window_freeze_updates           (GdkWindow *window);
void                gdk_window_thaw_updates             (GdkWindow *window);
void                gdk_window_process_all_updates      (void);
void                gdk_window_process_updates          (GdkWindow *window,
                                                         gboolean update_children);
void                gdk_window_set_debug_updates        (gboolean setting);
void                gdk_window_get_internal_paint_info  (GdkWindow *window,
                                                         GdkDrawable **real_drawable,
                                                         gint *x_offset,
                                                         gint *y_offset);
void                gdk_window_enable_synchronized_configure
                                                        (GdkWindow *window);
void                gdk_window_configure_finished       (GdkWindow *window);

void                gdk_window_set_user_data            (GdkWindow *window,
                                                         gpointer user_data);
void                gdk_window_set_override_redirect    (GdkWindow *window,
                                                         gboolean override_redirect);
void                gdk_window_set_accept_focus         (GdkWindow *window,
                                                         gboolean accept_focus);
void                gdk_window_set_focus_on_map         (GdkWindow *window,
                                                         gboolean focus_on_map);
void                gdk_window_add_filter               (GdkWindow *window,
                                                         GdkFilterFunc function,
                                                         gpointer data);
void                gdk_window_remove_filter            (GdkWindow *window,
                                                         GdkFilterFunc function,
                                                         gpointer data);
GdkFilterReturn     (*GdkFilterFunc)                    (GdkXEvent *xevent,
                                                         GdkEvent *event,
                                                         gpointer data);
enum                GdkFilterReturn;
typedef             GdkXEvent;
void                gdk_window_shape_combine_mask       (GdkWindow *window,
                                                         GdkBitmap *mask,
                                                         gint x,
                                                         gint y);
void                gdk_window_shape_combine_region     (GdkWindow *window,
                                                         GdkRegion *shape_region,
                                                         gint offset_x,
                                                         gint offset_y);
void                gdk_window_set_child_shapes         (GdkWindow *window);
void                gdk_window_merge_child_shapes       (GdkWindow *window);
void                gdk_window_input_shape_combine_mask (GdkWindow *window,
                                                         GdkBitmap *mask,
                                                         gint x,
                                                         gint y);
void                gdk_window_input_shape_combine_region
                                                        (GdkWindow *window,
                                                         GdkRegion *shape_region,
                                                         gint offset_x,
                                                         gint offset_y);
void                gdk_window_set_child_input_shapes   (GdkWindow *window);
void                gdk_window_merge_child_input_shapes (GdkWindow *window);
gboolean            gdk_window_set_static_gravities     (GdkWindow *window,
                                                         gboolean use_static);
void                gdk_window_set_hints                (GdkWindow *window,
                                                         gint x,
                                                         gint y,
                                                         gint min_width,
                                                         gint min_height,
                                                         gint max_width,
                                                         gint max_height,
                                                         gint flags);
void                gdk_window_set_title                (GdkWindow *window,
                                                         const gchar *title);
void                gdk_window_set_background           (GdkWindow *window,
                                                         const GdkColor *color);
void                gdk_window_set_back_pixmap          (GdkWindow *window,
                                                         GdkPixmap *pixmap,
                                                         gboolean parent_relative);
#define             GDK_PARENT_RELATIVE
void                gdk_window_set_cursor               (GdkWindow *window,
                                                         GdkCursor *cursor);
#define             gdk_window_set_colormap
void                gdk_window_get_user_data            (GdkWindow *window,
                                                         gpointer *data);
void                gdk_window_get_geometry             (GdkWindow *window,
                                                         gint *x,
                                                         gint *y,
                                                         gint *width,
                                                         gint *height,
                                                         gint *depth);
void                gdk_window_set_geometry_hints       (GdkWindow *window,
                                                         GdkGeometry *geometry,
                                                         GdkWindowHints geom_mask);
void                gdk_window_set_icon_list            (GdkWindow *window,
                                                         GList *pixbufs);
void                gdk_window_set_modal_hint           (GdkWindow *window,
                                                         gboolean modal);
void                gdk_window_set_type_hint            (GdkWindow *window,
                                                         GdkWindowTypeHint hint);
GdkWindowTypeHint   gdk_window_get_type_hint            (GdkWindow *window);
void                gdk_window_set_skip_taskbar_hint    (GdkWindow *window,
                                                         gboolean skips_taskbar);
void                gdk_window_set_skip_pager_hint      (GdkWindow *window,
                                                         gboolean skips_pager);
void                gdk_window_set_urgency_hint         (GdkWindow *window,
                                                         gboolean urgent);
void                gdk_window_get_position             (GdkWindow *window,
                                                         gint *x,
                                                         gint *y);
void                gdk_window_get_root_origin          (GdkWindow *window,
                                                         gint *x,
                                                         gint *y);
void                gdk_window_get_frame_extents        (GdkWindow *window,
                                                         GdkRectangle *rect);
#define             gdk_window_get_size
#define             gdk_window_get_visual
#define             gdk_window_get_colormap
#define             gdk_window_get_type
gint                gdk_window_get_origin               (GdkWindow *window,
                                                         gint *x,
                                                         gint *y);
gboolean            gdk_window_get_deskrelative_origin  (GdkWindow *window,
                                                         gint *x,
                                                         gint *y);
GdkWindow*          gdk_window_get_pointer              (GdkWindow *window,
                                                         gint *x,
                                                         gint *y,
                                                         GdkModifierType *mask);
enum                GdkModifierType;
GdkWindow*          gdk_window_get_parent               (GdkWindow *window);
GdkWindow*          gdk_window_get_toplevel             (GdkWindow *window);
GList*              gdk_window_get_children             (GdkWindow *window);
GList*              gdk_window_peek_children            (GdkWindow *window);
GdkEventMask        gdk_window_get_events               (GdkWindow *window);
void                gdk_window_set_events               (GdkWindow *window,
                                                         GdkEventMask event_mask);
void                gdk_window_set_icon                 (GdkWindow *window,
                                                         GdkWindow *icon_window,
                                                         GdkPixmap *pixmap,
                                                         GdkBitmap *mask);
void                gdk_window_set_icon_name            (GdkWindow *window,
                                                         const gchar *name);
void                gdk_window_set_transient_for        (GdkWindow *window,
                                                         GdkWindow *parent);
void                gdk_window_set_role                 (GdkWindow *window,
                                                         const gchar *role);
void                gdk_window_set_group                (GdkWindow *window,
                                                         GdkWindow *leader);
GdkWindow*          gdk_window_get_group                (GdkWindow *window);
void                gdk_window_set_decorations          (GdkWindow *window,
                                                         GdkWMDecoration decorations);
gboolean            gdk_window_get_decorations          (GdkWindow *window,
                                                         GdkWMDecoration *decorations);
enum                GdkWMDecoration;
void                gdk_window_set_functions            (GdkWindow *window,
                                                         GdkWMFunction functions);
enum                GdkWMFunction;
GList*              gdk_window_get_toplevels            (void);
GdkWindow*          gdk_get_default_root_window         (void);

                    GdkPointerHooks;
GdkPointerHooks*    gdk_set_pointer_hooks               (const GdkPointerHooks *new_hooks);

Object Hierarchy

  GObject
   +----GdkDrawable
         +----GdkWindow

Description

A GdkWindow is a rectangular region on the screen. It's a low-level object, used to implement high-level objects such as GtkWidget and GtkWindow on the GTK+ level. A GtkWindow is a toplevel window, the thing a user might think of as a "window" with a titlebar and so on; a GtkWindow may contain many GdkWindow. For example, each GtkButton has a GdkWindow associated with it.

Details

struct GdkWindow

struct GdkWindow;

An opaque structure representing an onscreen drawable. Pointers to structures of type GdkPixmap, GdkBitmap, and GdkWindow, can often be used interchangeably. The type GdkDrawable refers generically to any of these types.

enum GdkWindowType

typedef enum
{
  GDK_WINDOW_ROOT,
  GDK_WINDOW_TOPLEVEL,
  GDK_WINDOW_CHILD,
  GDK_WINDOW_DIALOG,
  GDK_WINDOW_TEMP,
  GDK_WINDOW_FOREIGN
} GdkWindowType;

Describes the kind of window.

GDK_WINDOW_ROOT | root window; this window has no parent, covers the entire screen, and is created by the window system
GDK_WINDOW_TOPLEVEL | toplevel window (used to implement GtkWindow)
GDK_WINDOW_CHILD | child window (used to implement e.g. GtkButton)
GDK_WINDOW_DIALOG | useless/deprecated compatibility type
GDK_WINDOW_TEMP | override redirect temporary window (used to implement GtkMenu)
GDK_WINDOW_FOREIGN | foreign window (see gdk_window_foreign_new())

enum GdkWindowClass

typedef enum
{
  GDK_INPUT_OUTPUT,
  GDK_INPUT_ONLY
} GdkWindowClass;

GDK_INPUT_OUTPUT windows are the standard kind of window you might expect. GDK_INPUT_ONLY windows are invisible; they are used to trap events, but you can't draw on them.

GDK_INPUT_OUTPUT | window for graphics and events
GDK_INPUT_ONLY | window for events only

enum GdkWindowHints

typedef enum
{
  GDK_HINT_POS	       = 1 << 0,
  GDK_HINT_MIN_SIZE    = 1 << 1,
  GDK_HINT_MAX_SIZE    = 1 << 2,
  GDK_HINT_BASE_SIZE   = 1 << 3,
  GDK_HINT_ASPECT      = 1 << 4,
  GDK_HINT_RESIZE_INC  = 1 << 5,
  GDK_HINT_WIN_GRAVITY = 1 << 6,
  GDK_HINT_USER_POS    = 1 << 7,
  GDK_HINT_USER_SIZE   = 1 << 8
} GdkWindowHints;

Used to indicate which fields of a GdkGeometry struct should be paid attention to. Also, the presence/absence of GDK_HINT_POS, GDK_HINT_USER_POS, and GDK_HINT_USER_SIZE is significant, though they don't directly refer to GdkGeometry fields. GDK_HINT_USER_POS will be set automatically by GtkWindow if you call gtk_window_move(). GDK_HINT_USER_POS and GDK_HINT_USER_SIZE should be set if the user specified a size/position using a --geometry command-line argument; gtk_window_parse_geometry() automatically sets these flags.

GDK_HINT_POS | indicates that the program has positioned the window
GDK_HINT_MIN_SIZE | min size fields are set
GDK_HINT_MAX_SIZE | max size fields are set
GDK_HINT_BASE_SIZE | base size fields are set
GDK_HINT_ASPECT | aspect ratio fields are set
GDK_HINT_RESIZE_INC | resize increment fields are set
GDK_HINT_WIN_GRAVITY | window gravity field is set
GDK_HINT_USER_POS | indicates that the window's position was explicitly set by the user
GDK_HINT_USER_SIZE | indicates that the window's size was explicitly set by the user

GdkGeometry

typedef struct {
  gint min_width;
  gint min_height;
  gint max_width;
  gint max_height;
  gint base_width;
  gint base_height;
  gint width_inc;
  gint height_inc;
  gdouble min_aspect;
  gdouble max_aspect;
  GdkGravity win_gravity;
} GdkGeometry;

The GdkGeometry struct gives the window manager information about a window's geometry constraints. Normally you would set these on the GTK+ level using gtk_window_set_geometry_hints(). GtkWindow then sets the hints on the GdkWindow it creates.

gdk_window_set_geometry_hints() expects the hints to be fully valid already and simply passes them to the window manager; in contrast, gtk_window_set_geometry_hints() performs some interpretation. For example, GtkWindow will apply the hints to the geometry widget instead of the toplevel window, if you set a geometry widget. Also, the min_width/min_height/max_width/max_height fields may be set to -1, and GtkWindow will substitute the size request of the window or geometry widget. If the minimum size hint is not provided, GtkWindow will use its requisition as the minimum size. If the minimum size is provided and a geometry widget is set, GtkWindow will take the minimum size as the minimum size of the geometry widget rather than the entire window. The base size is treated similarly.

The canonical use-case for gtk_window_set_geometry_hints() is to get a terminal widget to resize properly. Here, the terminal text area should be the geometry widget; GtkWindow will then automatically set the base size to the size of other widgets in the terminal window, such as the menubar and scrollbar. Then, the width_inc and height_inc fields should be set to the size of one character in the terminal. Finally, the base size should be set to the size of one character. The net effect is that the minimum size of the terminal will have a 1x1 character terminal area, and only terminal sizes on the "character grid" will be allowed.

Here's an example of how the terminal example would be implemented, assuming a terminal area widget called "terminal" and a toplevel window "toplevel":

    GdkGeometry hints;

    hints.base_width = terminal->char_width;
        hints.base_height = terminal->char_height;
        hints.min_width = terminal->char_width;
        hints.min_height = terminal->char_height;
        hints.width_inc = terminal->char_width;
        hints.height_inc = terminal->char_height;

    gtk_window_set_geometry_hints (GTK_WINDOW (toplevel),
                       GTK_WIDGET (terminal),
                        &hints,
                       GDK_HINT_RESIZE_INC |
                                       GDK_HINT_MIN_SIZE |
                                       GDK_HINT_BASE_SIZE);

The other useful fields are the min_aspect and max_aspect fields; these contain a width/height ratio as a floating point number. If a geometry widget is set, the aspect applies to the geometry widget rather than the entire window. The most common use of these hints is probably to set min_aspect and max_aspect to the same value, thus forcing the window to keep a constant aspect ratio.

gint min_width; | minimum width of window (or -1 to use requisition, with GtkWindow only)
gint min_height; | minimum height of window (or -1 to use requisition, with GtkWindow only)
gint max_width; | maximum width of window (or -1 to use requisition, with GtkWindow only)
gint max_height; | maximum height of window (or -1 to use requisition, with GtkWindow only)
gint base_width; | allowed window widths are base_width + width_inc * N where N is any integer (-1 allowed with GtkWindow)
gint base_height; | allowed window widths are base_height + height_inc * N where N is any integer (-1 allowed with GtkWindow)
gint width_inc; | width resize increment
gint height_inc; | height resize increment
gdouble min_aspect; | minimum width/height ratio
gdouble max_aspect; | maximum width/height ratio
GdkGravity win_gravity; | window gravity, see gtk_window_set_gravity()

enum GdkGravity

typedef enum
{
  GDK_GRAVITY_NORTH_WEST = 1,
  GDK_GRAVITY_NORTH,
  GDK_GRAVITY_NORTH_EAST,
  GDK_GRAVITY_WEST,
  GDK_GRAVITY_CENTER,
  GDK_GRAVITY_EAST,
  GDK_GRAVITY_SOUTH_WEST,
  GDK_GRAVITY_SOUTH,
  GDK_GRAVITY_SOUTH_EAST,
  GDK_GRAVITY_STATIC
} GdkGravity;

Defines the reference point of a window and the meaning of coordinates passed to gtk_window_move(). See gtk_window_move() and the "implementation notes" section of the Extended Window Manager Hints specification for more details.

GDK_GRAVITY_NORTH_WEST | the reference point is at the top left corner.
GDK_GRAVITY_NORTH | the reference point is in the middle of the top edge.
GDK_GRAVITY_NORTH_EAST | the reference point is at the top right corner.
GDK_GRAVITY_WEST | the reference point is at the middle of the left edge.
GDK_GRAVITY_CENTER | the reference point is at the center of the window.
GDK_GRAVITY_EAST | the reference point is at the middle of the right edge.
GDK_GRAVITY_SOUTH_WEST | the reference point is at the lower left corner.
GDK_GRAVITY_SOUTH | the reference point is at the middle of the lower edge.
GDK_GRAVITY_SOUTH_EAST | the reference point is at the lower right corner.
GDK_GRAVITY_STATIC | the reference point is at the top left corner of the window itself, ignoring window manager decorations.

enum GdkWindowEdge

typedef enum
{
  GDK_WINDOW_EDGE_NORTH_WEST,
  GDK_WINDOW_EDGE_NORTH,
  GDK_WINDOW_EDGE_NORTH_EAST,
  GDK_WINDOW_EDGE_WEST,
  GDK_WINDOW_EDGE_EAST,
  GDK_WINDOW_EDGE_SOUTH_WEST,
  GDK_WINDOW_EDGE_SOUTH,
  GDK_WINDOW_EDGE_SOUTH_EAST
} GdkWindowEdge;

Determines a window edge or corner.

GDK_WINDOW_EDGE_NORTH_WEST | the top left corner.
GDK_WINDOW_EDGE_NORTH | the top edge.
GDK_WINDOW_EDGE_NORTH_EAST | the top right corner.
GDK_WINDOW_EDGE_WEST | the left edge.
GDK_WINDOW_EDGE_EAST | the right edge.
GDK_WINDOW_EDGE_SOUTH_WEST | the lower left corner.
GDK_WINDOW_EDGE_SOUTH | the lower edge.
GDK_WINDOW_EDGE_SOUTH_EAST | the lower right corner.

enum GdkWindowTypeHint

typedef enum
{
  GDK_WINDOW_TYPE_HINT_NORMAL,
  GDK_WINDOW_TYPE_HINT_DIALOG,
  GDK_WINDOW_TYPE_HINT_MENU,		/* Torn off menu */
  GDK_WINDOW_TYPE_HINT_TOOLBAR,
  GDK_WINDOW_TYPE_HINT_SPLASHSCREEN,
  GDK_WINDOW_TYPE_HINT_UTILITY,
  GDK_WINDOW_TYPE_HINT_DOCK,
  GDK_WINDOW_TYPE_HINT_DESKTOP,
  GDK_WINDOW_TYPE_HINT_DROPDOWN_MENU,	/* A drop down menu (from a menubar) */
  GDK_WINDOW_TYPE_HINT_POPUP_MENU,	/* A popup menu (from right-click) */
  GDK_WINDOW_TYPE_HINT_TOOLTIP,
  GDK_WINDOW_TYPE_HINT_NOTIFICATION,
  GDK_WINDOW_TYPE_HINT_COMBO,
  GDK_WINDOW_TYPE_HINT_DND
} GdkWindowTypeHint;

These are hints for the window manager that indicate what type of function the window has. The window manager can use this when determining decoration and behaviour of the window. The hint must be set before mapping the window.

See the Extended Window Manager Hints specification for more details about window types.

GDK_WINDOW_TYPE_HINT_NORMAL | Normal toplevel window.
GDK_WINDOW_TYPE_HINT_DIALOG | Dialog window.
GDK_WINDOW_TYPE_HINT_MENU | Window used to implement a menu.
GDK_WINDOW_TYPE_HINT_TOOLBAR | Window used to implement toolbars.
GDK_WINDOW_TYPE_HINT_SPLASHSCREEN | Window used to display a splash screen during application startup.
GDK_WINDOW_TYPE_HINT_UTILITY | Utility windows which are not detached toolbars or dialogs.
GDK_WINDOW_TYPE_HINT_DOCK | Used for creating dock or panel windows.
GDK_WINDOW_TYPE_HINT_DESKTOP | Used for creating the desktop background window.
GDK_WINDOW_TYPE_HINT_DROPDOWN_MENU |
GDK_WINDOW_TYPE_HINT_POPUP_MENU |
GDK_WINDOW_TYPE_HINT_TOOLTIP |
GDK_WINDOW_TYPE_HINT_NOTIFICATION |
GDK_WINDOW_TYPE_HINT_COMBO |
GDK_WINDOW_TYPE_HINT_DND |

GdkWindowAttr

typedef struct {
  gchar *title;
  gint event_mask;
  gint x, y;
  gint width;
  gint height;
  GdkWindowClass wclass;
  GdkVisual *visual;
  GdkColormap *colormap;
  GdkWindowType window_type;
  GdkCursor *cursor;
  gchar *wmclass_name;
  gchar *wmclass_class;
  gboolean override_redirect;
} GdkWindowAttr;

Attributes to use for a newly-created window.

gchar *title; | title of the window (for toplevel windows)
gint event_mask; | event mask (see gdk_window_set_events())
gint x; | X coordinate relative to parent window (see gdk_window_move())
gint y; | Y coordinate relative to parent window (see gdk_window_move())
gint width; | width of window
gint height; | height of window
GdkWindowClass wclass; | GDK_INPUT_OUTPUT (normal window) or GDK_INPUT_ONLY (invisible window that receives events)
GdkVisual *visual; | GdkVisual for window
GdkColormap *colormap; | GdkColormap for window
GdkWindowType window_type; | type of window
GdkCursor *cursor; | cursor for the window (see gdk_window_set_cursor())
gchar *wmclass_name; | don't use (see gtk_window_set_wmclass())
gchar *wmclass_class; | don't use (see gtk_window_set_wmclass())
gboolean override_redirect; | TRUE to bypass the window manager

enum GdkWindowAttributesType

typedef enum
{
  GDK_WA_TITLE	  = 1 << 1,
  GDK_WA_X	  = 1 << 2,
  GDK_WA_Y	  = 1 << 3,
  GDK_WA_CURSOR	  = 1 << 4,
  GDK_WA_COLORMAP = 1 << 5,
  GDK_WA_VISUAL	  = 1 << 6,
  GDK_WA_WMCLASS  = 1 << 7,
  GDK_WA_NOREDIR  = 1 << 8
} GdkWindowAttributesType;

Used to indicate which fields in the GdkWindowAttr struct should be honored. For example, if you filled in the "cursor" and "x" fields of GdkWindowAttr, pass "GDK_WA_X | GDK_WA_CURSOR" to gdk_window_new(). Fields in GdkWindowAttr not covered by a bit in this enum are required; for example, the width/height, wclass, and window_type fields are required, they have no corresponding flag in GdkWindowAttributesType.

GDK_WA_TITLE | Honor the title field
GDK_WA_X | Honor the X coordinate field
GDK_WA_Y | Honor the Y coordinate field
GDK_WA_CURSOR | Honor the cursor field
GDK_WA_COLORMAP | Honor the colormap field
GDK_WA_VISUAL | Honor the visual field
GDK_WA_WMCLASS | Honor the wmclass_class and wmclass_name fields
GDK_WA_NOREDIR | Honor the override_redirect field

gdk_window_new ()

GdkWindow*          gdk_window_new                      (GdkWindow *parent,
                                                         GdkWindowAttr *attributes,
                                                         gint attributes_mask);

Creates a new GdkWindow using the attributes from attributes. See GdkWindowAttr and GdkWindowAttributesType for more details. Note: to use this on displays other than the default display, parent must be specified.

parent : | a GdkWindow, or NULL to create the window as a child of the default root window for the default display.
attributes : | attributes of the new window
attributes_mask : | mask indicating which fields in attributes are valid
Returns : | the new GdkWindow

gdk_window_destroy ()

void                gdk_window_destroy                  (GdkWindow *window);

Destroys the window system resources associated with window and decrements window's reference count. The window system resources for all children of window are also destroyed, but the children's reference counts are not decremented.

Note that a window will not be destroyed automatically when its reference count reaches zero. You must call this function yourself before that happens.

window : a GdkWindow

gdk_window_ref

#define gdk_window_ref                 gdk_drawable_ref

Warning

gdk_window_ref is deprecated and should not be used in newly-written code.

Deprecated equivalent of g_object_ref()

Returns : the window

gdk_window_unref

#define gdk_window_unref               gdk_drawable_unref

Warning

gdk_window_unref is deprecated and should not be used in newly-written code.

Deprecated equivalent of g_object_unref()

gdk_window_get_window_type ()

GdkWindowType       gdk_window_get_window_type          (GdkWindow *window);

Gets the type of the window. See GdkWindowType.

window : | a GdkWindow
Returns : | type of window

gdk_window_at_pointer ()

GdkWindow*          gdk_window_at_pointer               (gint *win_x,
                                                         gint *win_y);

Obtains the window underneath the mouse pointer, returning the location of that window in win_x, win_y. Returns NULL if the window under the mouse pointer is not known to GDK (if the window belongs to another application and a GdkWindow hasn't been created for it with gdk_window_foreign_new())

NOTE: For multihead-aware widgets or applications use gdk_display_get_window_at_pointer() instead.

win_x : | return location for origin of the window under the pointer
win_y : | return location for origin of the window under the pointer
Returns : | window under the mouse pointer

gdk_window_show ()

void                gdk_window_show                     (GdkWindow *window);

Like gdk_window_show_unraised(), but also raises the window to the top of the window stack (moves the window to the front of the Z-order).

This function maps a window so it's visible onscreen. Its opposite is gdk_window_hide().

When implementing a GtkWidget, you should call this function on the widget's GdkWindow as part of the "map" method.

window : a GdkWindow

gdk_window_show_unraised ()

void                gdk_window_show_unraised            (GdkWindow *window);

Shows a GdkWindow onscreen, but does not modify its stacking order. In contrast, gdk_window_show() will raise the window to the top of the window stack.

On the X11 platform, in Xlib terms, this function calls XMapWindow() (it also updates some internal GDK state, which means that you can't really use XMapWindow() directly on a GDK window).

window : a GdkWindow

gdk_window_hide ()

void                gdk_window_hide                     (GdkWindow *window);

For toplevel windows, withdraws them, so they will no longer be known to the window manager; for all windows, unmaps them, so they won't be displayed. Normally done automatically as part of gtk_widget_hide().

window : a GdkWindow

gdk_window_is_visible ()

gboolean            gdk_window_is_visible               (GdkWindow *window);

Checks whether the window has been mapped (with gdk_window_show() or gdk_window_show_unraised()).

window : | a GdkWindow
Returns : | TRUE if the window is mapped

gdk_window_is_viewable ()

gboolean            gdk_window_is_viewable              (GdkWindow *window);

Check if the window and all ancestors of the window are mapped. (This is not necessarily "viewable" in the X sense, since we only check as far as we have GDK window parents, not to the root window.)

window : | a GdkWindow
Returns : | TRUE if the window is viewable

gdk_window_get_state ()

GdkWindowState      gdk_window_get_state                (GdkWindow *window);

Gets the bitwise OR of the currently active window state flags, from the GdkWindowState enumeration.

window : | a GdkWindow
Returns : | window state bitfield

gdk_window_withdraw ()

void                gdk_window_withdraw                 (GdkWindow *window);

Withdraws a window (unmaps it and asks the window manager to forget about it). This function is not really useful as gdk_window_hide() automatically withdraws toplevel windows before hiding them.

window : a toplevel GdkWindow

gdk_window_iconify ()

void                gdk_window_iconify                  (GdkWindow *window);

Asks to iconify (minimize) window. The window manager may choose to ignore the request, but normally will honor it. Using gtk_window_iconify() is preferred, if you have a GtkWindow widget.

This function only makes sense when window is a toplevel window.

window : a toplevel GdkWindow

gdk_window_deiconify ()

void                gdk_window_deiconify                (GdkWindow *window);

Attempt to deiconify (unminimize) window. On X11 the window manager may choose to ignore the request to deiconify. When using GTK+, use gtk_window_deiconify() instead of the GdkWindow variant. Or better yet, you probably want to use gtk_window_present(), which raises the window, focuses it, unminimizes it, and puts it on the current desktop.

window : a toplevel GdkWindow

gdk_window_stick ()

void                gdk_window_stick                    (GdkWindow *window);

"Pins" a window such that it's on all workspaces and does not scroll with viewports, for window managers that have scrollable viewports. (When using GtkWindow, gtk_window_stick() may be more useful.)

On the X11 platform, this function depends on window manager support, so may have no effect with many window managers. However, GDK will do the best it can to convince the window manager to stick the window. For window managers that don't support this operation, there's nothing you can do to force it to happen.

window : a toplevel GdkWindow

gdk_window_unstick ()

void                gdk_window_unstick                  (GdkWindow *window);

Reverse operation for gdk_window_stick(); see gdk_window_stick(), and gtk_window_unstick().

window : a toplevel GdkWindow

gdk_window_maximize ()

void                gdk_window_maximize                 (GdkWindow *window);

Maximizes the window. If the window was already maximized, then this function does nothing.

On X11, asks the window manager to maximize window, if the window manager supports this operation. Not all window managers support this, and some deliberately ignore it or don't have a concept of "maximized"; so you can't rely on the maximization actually happening. But it will happen with most standard window managers, and GDK makes a best effort to get it to happen.

On Windows, reliably maximizes the window.

window : a toplevel GdkWindow

gdk_window_unmaximize ()

void                gdk_window_unmaximize               (GdkWindow *window);

Unmaximizes the window. If the window wasn't maximized, then this function does nothing.

On X11, asks the window manager to unmaximize window, if the window manager supports this operation. Not all window managers support this, and some deliberately ignore it or don't have a concept of "maximized"; so you can't rely on the unmaximization actually happening. But it will happen with most standard window managers, and GDK makes a best effort to get it to happen.

On Windows, reliably unmaximizes the window.

window : a toplevel GdkWindow

gdk_window_fullscreen ()

void                gdk_window_fullscreen               (GdkWindow *window);

Moves the window into fullscreen mode. This means the window covers the entire screen and is above any panels or task bars.

If the window was already fullscreen, then this function does nothing.

On X11, asks the window manager to put window in a fullscreen state, if the window manager supports this operation. Not all window managers support this, and some deliberately ignore it or don't have a concept of "fullscreen"; so you can't rely on the fullscreenification actually happening. But it will happen with most standard window managers, and GDK makes a best effort to get it to happen.

window : a toplevel GdkWindow

Since 2.2

gdk_window_unfullscreen ()

void                gdk_window_unfullscreen             (GdkWindow *window);

Moves the window out of fullscreen mode. If the window was not fullscreen, does nothing.

On X11, asks the window manager to move window out of the fullscreen state, if the window manager supports this operation. Not all window managers support this, and some deliberately ignore it or don't have a concept of "fullscreen"; so you can't rely on the unfullscreenification actually happening. But it will happen with most standard window managers, and GDK makes a best effort to get it to happen.

window : a toplevel GdkWindow

Since 2.2

gdk_window_set_keep_above ()

void                gdk_window_set_keep_above           (GdkWindow *window,
                                                         gboolean setting);

Set if window must be kept above other windows. If the window was already above, then this function does nothing.

On X11, asks the window manager to keep window above, if the window manager supports this operation. Not all window managers support this, and some deliberately ignore it or don't have a concept of "keep above"; so you can't rely on the window being kept above. But it will happen with most standard window managers, and GDK makes a best effort to get it to happen.

window : | a toplevel GdkWindow
setting : | whether to keep window above other windows

Since 2.4

gdk_window_set_keep_below ()

void                gdk_window_set_keep_below           (GdkWindow *window,
                                                         gboolean setting);

Set if window must be kept below other windows. If the window was already below, then this function does nothing.

On X11, asks the window manager to keep window below, if the window manager supports this operation. Not all window managers support this, and some deliberately ignore it or don't have a concept of "keep below"; so you can't rely on the window being kept below. But it will happen with most standard window managers, and GDK makes a best effort to get it to happen.

window : | a toplevel GdkWindow
setting : | whether to keep window below other windows

Since 2.4

gdk_window_move ()

void                gdk_window_move                     (GdkWindow *window,
                                                         gint x,
                                                         gint y);

Repositions a window relative to its parent window. For toplevel windows, window managers may ignore or modify the move; you should probably use gtk_window_move() on a GtkWindow widget anyway, instead of using GDK functions. For child windows, the move will reliably succeed.

If you're also planning to resize the window, use gdk_window_move_resize() to both move and resize simultaneously, for a nicer visual effect.

window : | a GdkWindow
x : | X coordinate relative to window's parent
y : | Y coordinate relative to window's parent

gdk_window_resize ()

void                gdk_window_resize                   (GdkWindow *window,
                                                         gint width,
                                                         gint height);

Resizes window; for toplevel windows, asks the window manager to resize the window. The window manager may not allow the resize. When using GTK+, use gtk_window_resize() instead of this low-level GDK function.

Windows may not be resized below 1x1.

If you're also planning to move the window, use gdk_window_move_resize() to both move and resize simultaneously, for a nicer visual effect.

window : | a GdkWindow
width : | new width of the window
height : | new height of the window

gdk_window_move_resize ()

void                gdk_window_move_resize              (GdkWindow *window,
                                                         gint x,
                                                         gint y,
                                                         gint width,
                                                         gint height);

Equivalent to calling gdk_window_move() and gdk_window_resize(), except that both operations are performed at once, avoiding strange visual effects. (i.e. the user may be able to see the window first move, then resize, if you don't use gdk_window_move_resize().)

window : | a GdkWindow
x : | new X position relative to window's parent
y : | new Y position relative to window's parent
width : | new width
height : | new height

gdk_window_scroll ()

void                gdk_window_scroll                   (GdkWindow *window,
                                                         gint dx,
                                                         gint dy);

Scroll the contents of its window, both pixels and children, by the given amount. Portions of the window that the scroll operation brings in from offscreen areas are invalidated.

window : | a GdkWindow
dx : | Amount to scroll in the X direction
dy : | Amount to scroll in the Y direction

gdk_window_move_region ()

void                gdk_window_move_region              (GdkWindow *window,
                                                         GdkRegion *region,
                                                         gint dx,
                                                         gint dy);

Move the part of window indicated by region by dy pixels in the Y direction and dx pixels in the X direction. The portions of region that not covered by the new position of region are invalidated.

Child windows are not moved.

window : | a GdkWindow
region : | The GdkRegion to move
dx : | Amount to move in the X direction
dy : | Amount to move in the Y direction

Since 2.8

gdk_window_reparent ()

void                gdk_window_reparent                 (GdkWindow *window,
                                                         GdkWindow *new_parent,
                                                         gint x,
                                                         gint y);

Reparents window into the given new_parent. The window being reparented will be unmapped as a side effect.

window : | a GdkWindow
new_parent : | new parent to move window into
x : | X location inside the new parent
y : | Y location inside the new parent

gdk_window_clear ()

void                gdk_window_clear                    (GdkWindow *window);

Clears an entire window to the background color or background pixmap.

window : a GdkWindow

gdk_window_clear_area ()

void                gdk_window_clear_area               (GdkWindow *window,
                                                         gint x,
                                                         gint y,
                                                         gint width,
                                                         gint height);

Clears an area of window to the background color or background pixmap.

window : | a GdkWindow
x : | x coordinate of rectangle to clear
y : | y coordinate of rectangle to clear
width : | width of rectangle to clear
height : | height of rectangle to clear

gdk_window_clear_area_e ()

void                gdk_window_clear_area_e             (GdkWindow *window,
                                                         gint x,
                                                         gint y,
                                                         gint width,
                                                         gint height);

Like gdk_window_clear_area(), but also generates an expose event for the cleared area.

This function has a stupid name because it dates back to the mists time, pre-GDK-1.0.

window : | a GdkWindow
x : | x coordinate of rectangle to clear
y : | y coordinate of rectangle to clear
width : | width of rectangle to clear
height : | height of rectangle to clear

gdk_window_copy_area()

#define             gdk_window_copy_area(drawable,gc,x,y,source_drawable,source_x,source_y,width,height)

Warning

gdk_window_copy_area is deprecated and should not be used in newly-written code.

Deprecated equivalent to gdk_draw_drawable(), see that function for docs

drawable : | a GdkDrawable
gc : | a GdkGC sharing the drawable's visual and colormap
x : | X position in drawable where the rectangle should be drawn
y : | Y position in drawable where the rectangle should be drawn
source_drawable : | the source GdkDrawable, which may be the same as drawable
source_x : | X position in src of rectangle to draw
source_y : | Y position in src of rectangle to draw
width : | width of rectangle to draw, or -1 for entire src width
height : | height of rectangle to draw, or -1 for entire src height

gdk_window_raise ()

void                gdk_window_raise                    (GdkWindow *window);

Raises window to the top of the Z-order (stacking order), so that other windows with the same parent window appear below window. This is true whether or not the windows are visible.

If window is a toplevel, the window manager may choose to deny the request to move the window in the Z-order, gdk_window_raise() only requests the restack, does not guarantee it.

window : a GdkWindow

gdk_window_lower ()

void                gdk_window_lower                    (GdkWindow *window);

Lowers window to the bottom of the Z-order (stacking order), so that other windows with the same parent window appear above window. This is true whether or not the other windows are visible.

If window is a toplevel, the window manager may choose to deny the request to move the window in the Z-order, gdk_window_lower() only requests the restack, does not guarantee it.

Note that gdk_window_show() raises the window again, so don't call this function before gdk_window_show(). (Try gdk_window_show_unraised().)

window : a GdkWindow

gdk_window_focus ()

void                gdk_window_focus                    (GdkWindow *window,
                                                         guint32 timestamp);

Sets keyboard focus to window. In most cases, gtk_window_present() should be used on a GtkWindow, rather than calling this function.

window : | a GdkWindow
timestamp : | timestamp of the event triggering the window focus

gdk_window_register_dnd ()

void                gdk_window_register_dnd             (GdkWindow *window);

Registers a window as a potential drop destination.

window : a GdkWindow.

gdk_window_begin_resize_drag ()

void                gdk_window_begin_resize_drag        (GdkWindow *window,
                                                         GdkWindowEdge edge,
                                                         gint button,
                                                         gint root_x,
                                                         gint root_y,
                                                         guint32 timestamp);

Begins a window resize operation (for a toplevel window). You might use this function to implement a "window resize grip," for example; in fact GtkStatusbar uses it. The function works best with window managers that support the Extended Window Manager Hints, but has a fallback implementation for other window managers.

window : | a toplevel GdkWindow
edge : | the edge or corner from which the drag is started
button : | the button being used to drag
root_x : | root window X coordinate of mouse click that began the drag
root_y : | root window Y coordinate of mouse click that began the drag
timestamp : | timestamp of mouse click that began the drag (use gdk_event_get_time())

gdk_window_begin_move_drag ()

void                gdk_window_begin_move_drag          (GdkWindow *window,
                                                         gint button,
                                                         gint root_x,
                                                         gint root_y,
                                                         guint32 timestamp);

Begins a window move operation (for a toplevel window). You might use this function to implement a "window move grip," for example. The function works best with window managers that support the Extended Window Manager Hints, but has a fallback implementation for other window managers.

window : | a toplevel GdkWindow
button : | the button being used to drag
root_x : | root window X coordinate of mouse click that began the drag
root_y : | root window Y coordinate of mouse click that began the drag
timestamp : | timestamp of mouse click that began the drag

gdk_window_constrain_size ()

void                gdk_window_constrain_size           (GdkGeometry *geometry,
                                                         guint flags,
                                                         gint width,
                                                         gint height,
                                                         gint *new_width,
                                                         gint *new_height);

Constrains a desired width and height according to a set of geometry hints (such as minimum and maximum size).

geometry : | a GdkGeometry structure
flags : | a mask indicating what portions of geometry are set
width : | desired width of window
height : | desired height of the window
new_width : | location to store resulting width
new_height : | location to store resulting height

gdk_window_begin_paint_rect ()

void                gdk_window_begin_paint_rect         (GdkWindow *window,
                                                         GdkRectangle *rectangle);

A convenience wrapper around gdk_window_begin_paint_region() which creates a rectangular region for you. See gdk_window_begin_paint_region() for details.

window : | a GdkWindow
rectangle : | rectangle you intend to draw to

gdk_window_begin_paint_region ()

void                gdk_window_begin_paint_region       (GdkWindow *window,
                                                         GdkRegion *region);

Indicates that you are beginning the process of redrawing region. A backing store (offscreen buffer) large enough to contain region will be created. The backing store will be initialized with the background color or background pixmap for window. Then, all drawing operations performed on window will be diverted to the backing store. When you call gdk_window_end_paint(), the backing store will be copied to window, making it visible onscreen. Only the part of window contained in region will be modified; that is, drawing operations are clipped to region.

The net result of all this is to remove flicker, because the user sees the finished product appear all at once when you call gdk_window_end_paint(). If you draw to window directly without calling gdk_window_begin_paint_region(), the user may see flicker as individual drawing operations are performed in sequence. The clipping and background-initializing features of gdk_window_begin_paint_region() are conveniences for the programmer, so you can avoid doing that work yourself.

When using GTK+, the widget system automatically places calls to gdk_window_begin_paint_region() and gdk_window_end_paint() around emissions of the expose_event signal. That is, if you're writing an expose event handler, you can assume that the exposed area in GdkEventExpose has already been cleared to the window background, is already set as the clip region, and already has a backing store. Therefore in most cases, application code need not call gdk_window_begin_paint_region(). (You can disable the automatic calls around expose events on a widget-by-widget basis by calling gtk_widget_set_double_buffered().)

If you call this function multiple times before calling the matching gdk_window_end_paint(), the backing stores are pushed onto a stack. gdk_window_end_paint() copies the topmost backing store onscreen, subtracts the topmost region from all other regions in the stack, and pops the stack. All drawing operations affect only the topmost backing store in the stack. One matching call to gdk_window_end_paint() is required for each call to gdk_window_begin_paint_region().

window : | a GdkWindow
region : | region you intend to draw to

gdk_window_end_paint ()

void                gdk_window_end_paint                (GdkWindow *window);

Indicates that the backing store created by the most recent call to gdk_window_begin_paint_region() should be copied onscreen and deleted, leaving the next-most-recent backing store or no backing store at all as the active paint region. See gdk_window_begin_paint_region() for full details. It is an error to call this function without a matching gdk_window_begin_paint_region() first.

window : a GdkWindow

gdk_window_invalidate_rect ()

void                gdk_window_invalidate_rect          (GdkWindow *window,
                                                         GdkRectangle *rect,
                                                         gboolean invalidate_children);

A convenience wrapper around gdk_window_invalidate_region() which invalidates a rectangular region. See gdk_window_invalidate_region() for details.

window : | a GdkWindow
rect : | rectangle to invalidate
invalidate_children : | whether to also invalidate child windows

gdk_window_invalidate_region ()

void                gdk_window_invalidate_region        (GdkWindow *window,
                                                         GdkRegion *region,
                                                         gboolean invalidate_children);

Adds region to the update area for window. The update area is the region that needs to be redrawn, or "dirty region." The call gdk_window_process_updates() sends one or more expose events to the window, which together cover the entire update area. An application would normally redraw the contents of window in response to those expose events.

GDK will call gdk_window_process_all_updates() on your behalf whenever your program returns to the main loop and becomes idle, so normally there's no need to do that manually, you just need to invalidate regions that you know should be redrawn.

The invalidate_children parameter controls whether the region of each child window that intersects region will also be invalidated. If FALSE, then the update area for child windows will remain unaffected. See gdk_window_invalidate_maybe_recurse if you need fine grained control over which children are invalidated.

window : | a GdkWindow
region : | a GdkRegion
invalidate_children : | TRUE to also invalidate child windows

gdk_window_invalidate_maybe_recurse ()

void                gdk_window_invalidate_maybe_recurse (GdkWindow *window,
                                                         GdkRegion *region,
                                                         gboolean (*child_func) (GdkWindow *, gpointer),
                                                         gpointer user_data);

Adds region to the update area for window. The update area is the region that needs to be redrawn, or "dirty region." The call gdk_window_process_updates() sends one or more expose events to the window, which together cover the entire update area. An application would normally redraw the contents of window in response to those expose events.

GDK will call gdk_window_process_all_updates() on your behalf whenever your program returns to the main loop and becomes idle, so normally there's no need to do that manually, you just need to invalidate regions that you know should be redrawn.

The child_func parameter controls whether the region of each child window that intersects region will also be invalidated. Only children for which child_func returns TRUE will have the area invalidated.

window : | a GdkWindow
region : | a GdkRegion
child_func : | function to use to decide if to recurse to a child, NULL means never recurse.
user_data : | data passed to child_func

gdk_window_get_update_area ()

GdkRegion*          gdk_window_get_update_area          (GdkWindow *window);

Transfers ownership of the update area from window to the caller of the function. That is, after calling this function, window will no longer have an invalid/dirty region; the update area is removed from window and handed to you. If a window has no update area, gdk_window_get_update_area() returns NULL. You are responsible for calling gdk_region_destroy() on the returned region if it's non-NULL.

window : | a GdkWindow
Returns : | the update area for window

gdk_window_freeze_updates ()

void                gdk_window_freeze_updates           (GdkWindow *window);

Temporarily freezes a window such that it won't receive expose events. The window will begin receiving expose events again when gdk_window_thaw_updates() is called. If gdk_window_freeze_updates() has been called more than once, gdk_window_thaw_updates() must be called an equal number of times to begin processing exposes.

window : a GdkWindow

gdk_window_thaw_updates ()

void                gdk_window_thaw_updates             (GdkWindow *window);

Thaws a window frozen with gdk_window_freeze_updates().

window : a GdkWindow

gdk_window_process_all_updates ()

void                gdk_window_process_all_updates      (void);

Calls gdk_window_process_updates() for all windows (see GdkWindow) in the application.

gdk_window_process_updates ()

void                gdk_window_process_updates          (GdkWindow *window,
                                                         gboolean update_children);

Sends one or more expose events to window. The areas in each expose event will cover the entire update area for the window (see gdk_window_invalidate_region() for details). Normally GDK calls gdk_window_process_all_updates() on your behalf, so there's no need to call this function unless you want to force expose events to be delivered immediately and synchronously (vs. the usual case, where GDK delivers them in an idle handler). Occasionally this is useful to produce nicer scrolling behavior, for example.

window : | a GdkWindow
update_children : | whether to also process updates for child windows

gdk_window_set_debug_updates ()

void                gdk_window_set_debug_updates        (gboolean setting);

With update debugging enabled, calls to gdk_window_invalidate_region() clear the invalidated region of the screen to a noticeable color, and GDK pauses for a short time before sending exposes to windows during gdk_window_process_updates(). The net effect is that you can see the invalid region for each window and watch redraws as they occur. This allows you to diagnose inefficiencies in your application.

In essence, because the GDK rendering model prevents all flicker, if you are redrawing the same region 400 times you may never notice, aside from noticing a speed problem. Enabling update debugging causes GTK to flicker slowly and noticeably, so you can see exactly what's being redrawn when, in what order.

The --gtk-debug=updates command line option passed to GTK+ programs enables this debug option at application startup time. That's usually more useful than calling gdk_window_set_debug_updates() yourself, though you might want to use this function to enable updates sometime after application startup time.

setting : TRUE to turn on update debugging

gdk_window_get_internal_paint_info ()

void                gdk_window_get_internal_paint_info  (GdkWindow *window,
                                                         GdkDrawable **real_drawable,
                                                         gint *x_offset,
                                                         gint *y_offset);

If you bypass the GDK layer and use windowing system primitives to draw directly onto a GdkWindow, then you need to deal with two details: there may be an offset between GDK coordinates and windowing system coordinates, and GDK may have redirected drawing to a offscreen pixmap as the result of a gdk_window_begin_paint_region() calls. This function allows retrieving the information you need to compensate for these effects.

This function exposes details of the GDK implementation, and is thus likely to change in future releases of GDK.

window : | a GdkWindow
real_drawable : | location to store the drawable to which drawing should be done.
x_offset : | location to store the X offset between coordinates in window, and the underlying window system primitive coordinates for *real_drawable.
y_offset : | location to store the Y offset between coordinates in window, and the underlying window system primitive coordinates for *real_drawable.

gdk_window_enable_synchronized_configure ()

void                gdk_window_enable_synchronized_configure
                                                        (GdkWindow *window);

Indicates that the application will cooperate with the window system in synchronizing the window repaint with the window manager during resizing operations. After an application calls this function, it must call gdk_window_configure_finished() every time it has finished all processing associated with a set of Configure events. Toplevel GTK+ windows automatically use this protocol.

On X, calling this function makes window participate in the _NET_WM_SYNC_REQUEST window manager protocol.

window : a toplevel GdkWindow

Since 2.6

gdk_window_configure_finished ()

void                gdk_window_configure_finished       (GdkWindow *window);

Signal to the window system that the application has finished handling Configure events it has received. Window Managers can use this to better synchronize the frame repaint with the application. GTK+ applications will automatically call this function when appropriate.

This function can only be called if gdk_window_enable_synchronized_configure() was called previously.

window : a toplevel GdkWindow

Since 2.6

gdk_window_set_user_data ()

void                gdk_window_set_user_data            (GdkWindow *window,
                                                         gpointer user_data);

For most purposes this function is deprecated in favor of g_object_set_data(). However, for historical reasons GTK+ stores the GtkWidget that owns a GdkWindow as user data on the GdkWindow. So, custom widget implementations should use this function for that. If GTK+ receives an event for a GdkWindow, and the user data for the window is non-NULL, GTK+ will assume the user data is a GtkWidget, and forward the event to that widget.

window : | a GdkWindow
user_data : | user data

gdk_window_set_override_redirect ()

void                gdk_window_set_override_redirect    (GdkWindow *window,
                                                         gboolean override_redirect);

An override redirect window is not under the control of the window manager. This means it won't have a titlebar, won't be minimizable, etc. - it will be entirely under the control of the application. The window manager can't see the override redirect window at all.

Override redirect should only be used for short-lived temporary windows, such as popup menus. GtkMenu uses an override redirect window in its implementation, for example.

window : | a toplevel GdkWindow
override_redirect : | TRUE if window should be override redirect

gdk_window_set_accept_focus ()

void                gdk_window_set_accept_focus         (GdkWindow *window,
                                                         gboolean accept_focus);

Setting accept_focus to FALSE hints the desktop environment that the window doesn't want to receive input focus.

On X, it is the responsibility of the window manager to interpret this hint. ICCCM-compliant window manager usually respect it.

window : | a toplevel GdkWindow
accept_focus : | TRUE if the window should receive input focus

Since 2.4

gdk_window_set_focus_on_map ()

void                gdk_window_set_focus_on_map         (GdkWindow *window,
                                                         gboolean focus_on_map);

Setting focus_on_map to FALSE hints the desktop environment that the window doesn't want to receive input focus when it is mapped. focus_on_map should be turned off for windows that aren't triggered interactively (such as popups from network activity).

On X, it is the responsibility of the window manager to interpret this hint. Window managers following the freedesktop.org window manager extension specification should respect it.

window : | a toplevel GdkWindow
focus_on_map : | TRUE if the window should receive input focus when mapped

Since 2.6

gdk_window_add_filter ()

void                gdk_window_add_filter               (GdkWindow *window,
                                                         GdkFilterFunc function,
                                                         gpointer data);

Adds an event filter to window, allowing you to intercept events before they reach GDK. This is a low-level operation and makes it easy to break GDK and/or GTK+, so you have to know what you're doing. Pass NULL for window to get all events for all windows, instead of events for a specific window.

window : | a GdkWindow
function : | filter callback
data : | data to pass to filter callback

gdk_window_remove_filter ()

void                gdk_window_remove_filter            (GdkWindow *window,
                                                         GdkFilterFunc function,
                                                         gpointer data);

Remove a filter previously added with gdk_window_add_filter().

window : | a GdkWindow
function : | previously-added filter function
data : | user data for previously-added filter function

GdkFilterFunc ()

GdkFilterReturn     (*GdkFilterFunc)                    (GdkXEvent *xevent,
                                                         GdkEvent *event,
                                                         gpointer data);

Specifies the type of function used to filter native events before they are converted to GDK events.

When a filter is called, event is unpopulated, except for event->window. The filter may translate the native event to a GDK event and store the result in event, or handle it without translation. If the filter translates the event and processing should continue, it should return GDK_FILTER_TRANSLATE.

xevent : | the native event to filter.
event : | the GDK event to which the X event will be translated.
data : | user data set when the filter was installed.
Returns : | a GdkFilterReturn value.

enum GdkFilterReturn

typedef enum {
  GDK_FILTER_CONTINUE,	  /* Event not handled, continue processesing */
  GDK_FILTER_TRANSLATE,	  /* Native event translated into a GDK event and
                             stored in the "event" structure that was
                             passed in */
  GDK_FILTER_REMOVE	  /* Terminate processing, removing event */
} GdkFilterReturn;

Specifies the result of applying a GdkFilterFunc to a native event.

GDK_FILTER_CONTINUE | event not handled, continue processing.
GDK_FILTER_TRANSLATE | native event translated into a GDK event and stored in the event structure that was passed in.
GDK_FILTER_REMOVE | event handled, terminate processing.

GdkXEvent

typedef void GdkXEvent;	  /* Can be cast to window system specific

Used to represent native events (XEvents for the X11 backend, MSGs for Win32).

gdk_window_shape_combine_mask ()

void                gdk_window_shape_combine_mask       (GdkWindow *window,
                                                         GdkBitmap *mask,
                                                         gint x,
                                                         gint y);

Applies a shape mask to window. Pixels in window corresponding to set bits in the mask will be visible; pixels in window corresponding to unset bits in the mask will be transparent. This gives a non-rectangular window.

If mask is NULL, the shape mask will be unset, and the x/y parameters are not used.

On the X11 platform, this uses an X server extension which is widely available on most common platforms, but not available on very old X servers, and occasionally the implementation will be buggy. On servers without the shape extension, this function will do nothing.

On the Win32 platform the functionality is always present.

This function works on both toplevel and child windows.

window : | a GdkWindow
mask : | shape mask
x : | X position of shape mask with respect to window
y : | Y position of shape mask with respect to window

gdk_window_shape_combine_region ()

void                gdk_window_shape_combine_region     (GdkWindow *window,
                                                         GdkRegion *shape_region,
                                                         gint offset_x,
                                                         gint offset_y);

Makes pixels in window outside shape_region be transparent, so that the window may be nonrectangular. See also gdk_window_shape_combine_mask() to use a bitmap as the mask.

If shape_region is NULL, the shape will be unset, so the whole window will be opaque again. offset_x and offset_y are ignored if shape_region is NULL.

On the X11 platform, this uses an X server extension which is widely available on most common platforms, but not available on very old X servers, and occasionally the implementation will be buggy. On servers without the shape extension, this function will do nothing.

On the Win32 platform, this functionality is always present.

This function works on both toplevel and child windows.

window : | a GdkWindow
shape_region : | region of window to be non-transparent
offset_x : | X position of shape_region in window coordinates
offset_y : | Y position of shape_region in window coordinates

gdk_window_set_child_shapes ()

void                gdk_window_set_child_shapes         (GdkWindow *window);

Sets the shape mask of window to the union of shape masks for all children of window, ignoring the shape mask of window itself. Contrast with gdk_window_merge_child_shapes() which includes the shape mask of window in the masks to be merged.

window : a GdkWindow

gdk_window_merge_child_shapes ()

void                gdk_window_merge_child_shapes       (GdkWindow *window);

Merges the shape masks for any child windows into the shape mask for window. i.e. the union of all masks for window and its children will become the new mask for window. See gdk_window_shape_combine_mask().

This function is distinct from gdk_window_set_child_shapes() because it includes window's shape mask in the set of shapes to be merged.

window : a GdkWindow

gdk_window_input_shape_combine_mask ()

void                gdk_window_input_shape_combine_mask (GdkWindow *window,
                                                         GdkBitmap *mask,
                                                         gint x,
                                                         gint y);

Like gdk_window_shape_combine_mask(), but the shape applies only to event handling. Mouse events which happen while the pointer position corresponds to an unset bit in the mask will be passed on the window below window.

An input shape is typically used with RGBA windows. The alpha channel of the window defines which pixels are invisible and allows for nicely antialiased borders, and the input shape controls where the window is "clickable".

On the X11 platform, this requires version 1.1 of the shape extension.

On the Win32 platform, this functionality is not present and the function does nothing.

window : | a GdkWindow
mask : | shape mask
x : | X position of shape mask with respect to window
y : | Y position of shape mask with respect to window

Since 2.10

gdk_window_input_shape_combine_region ()

void                gdk_window_input_shape_combine_region
                                                        (GdkWindow *window,
                                                         GdkRegion *shape_region,
                                                         gint offset_x,
                                                         gint offset_y);

Like gdk_window_shape_combine_region(), but the shape applies only to event handling. Mouse events which happen while the pointer position corresponds to an unset bit in the mask will be passed on the window below window.

An input shape is typically used with RGBA windows. The alpha channel of the window defines which pixels are invisible and allows for nicely antialiased borders, and the input shape controls where the window is "clickable".

On the X11 platform, this requires version 1.1 of the shape extension.

On the Win32 platform, this functionality is not present and the function does nothing.

window : | a GdkWindow
shape_region : | region of window to be non-transparent
offset_x : | X position of shape_region in window coordinates
offset_y : | Y position of shape_region in window coordinates

Since 2.10

gdk_window_set_child_input_shapes ()

void                gdk_window_set_child_input_shapes   (GdkWindow *window);

Sets the input shape mask of window to the union of input shape masks for all children of window, ignoring the input shape mask of window itself. Contrast with gdk_window_merge_child_input_shapes() which includes the input shape mask of window in the masks to be merged.

window : a GdkWindow

Since 2.10

gdk_window_merge_child_input_shapes ()

void                gdk_window_merge_child_input_shapes (GdkWindow *window);

Merges the input shape masks for any child windows into the input shape mask for window. i.e. the union of all input masks for window and its children will become the new input mask for window. See gdk_window_input_shape_combine_mask().

This function is distinct from gdk_window_set_child_input_shapes() because it includes window's input shape mask in the set of shapes to be merged.

window : a GdkWindow

Since 2.10

gdk_window_set_static_gravities ()

gboolean            gdk_window_set_static_gravities     (GdkWindow *window,
                                                         gboolean use_static);

Set the bit gravity of the given window to static, and flag it so all children get static subwindow gravity. This is used if you are implementing scary features that involve deep knowledge of the windowing system. Don't worry about it unless you have to.

window : | a GdkWindow
use_static : | TRUE to turn on static gravity
Returns : | TRUE if the server supports static gravity

gdk_window_set_hints ()

void                gdk_window_set_hints                (GdkWindow *window,
                                                         gint x,
                                                         gint y,
                                                         gint min_width,
                                                         gint min_height,
                                                         gint max_width,
                                                         gint max_height,
                                                         gint flags);

Warning

gdk_window_set_hints is deprecated and should not be used in newly-written code.

This function is broken and useless and you should ignore it. If using GTK+, use functions such as gtk_window_resize(), gtk_window_set_size_request(), gtk_window_move(), gtk_window_parse_geometry(), and gtk_window_set_geometry_hints(), depending on what you're trying to do.

If using GDK directly, use gdk_window_set_geometry_hints().

window : | a GdkWindow
x : | ignored field, does not matter
y : | ignored field, does not matter
min_width : | minimum width hint
min_height : | minimum height hint
max_width : | max width hint
max_height : | max height hint
flags : | logical OR of GDK_HINT_POS, GDK_HINT_MIN_SIZE, and/or GDK_HINT_MAX_SIZE

gdk_window_set_title ()

void                gdk_window_set_title                (GdkWindow *window,
                                                         const gchar *title);

Sets the title of a toplevel window, to be displayed in the titlebar. If you haven't explicitly set the icon name for the window (using gdk_window_set_icon_name()), the icon name will be set to title as well. title must be in UTF-8 encoding (as with all user-readable strings in GDK/GTK+). title may not be NULL.

window : | a toplevel GdkWindow
title : | title of window

gdk_window_set_background ()

void                gdk_window_set_background           (GdkWindow *window,
                                                         const GdkColor *color);

Sets the background color of window. (However, when using GTK+, set the background of a widget with gtk_widget_modify_bg() - if you're an application - or gtk_style_set_background() - if you're implementing a custom widget.)

The color must be allocated; gdk_rgb_find_color() is the best way to allocate a color.

See also gdk_window_set_back_pixmap().

window : | a GdkWindow
color : | an allocated GdkColor

gdk_window_set_back_pixmap ()

void                gdk_window_set_back_pixmap          (GdkWindow *window,
                                                         GdkPixmap *pixmap,
                                                         gboolean parent_relative);

Sets the background pixmap of window. May also be used to set a background of "None" on window, by setting a background pixmap of NULL. A background pixmap will be tiled, positioning the first tile at the origin of window, or if parent_relative is TRUE, the tiling will be done based on the origin of the parent window (useful to align tiles in a parent with tiles in a child).

A background pixmap of NULL means that the window will have no background. A window with no background will never have its background filled by the windowing system, instead the window will contain whatever pixels were already in the corresponding area of the display.

The windowing system will normally fill a window with its background when the window is obscured then exposed, and when you call gdk_window_clear().

window : | a GdkWindow
pixmap : | a GdkPixmap, or NULL
parent_relative : | whether the tiling origin is at the origin of window's parent

GDK_PARENT_RELATIVE

#define GDK_PARENT_RELATIVE  1L

A special value for GdkPixmap* variables, indicating that the background pixmap for a window should be inherited from the parent window.

gdk_window_set_cursor ()

void                gdk_window_set_cursor               (GdkWindow *window,
                                                         GdkCursor *cursor);

Sets the mouse pointer for a GdkWindow. Use gdk_cursor_new() or gdk_cursor_new_from_pixmap() to create the cursor. To make the cursor invisible, use gdk_cursor_new_from_pixmap() to create a cursor with no pixels in it. Passing NULL for the cursor argument to gdk_window_set_cursor() means that window will use the cursor of its parent window. Most windows should use this default.

window : | a GdkWindow
cursor : | a cursor

gdk_window_set_colormap

#define gdk_window_set_colormap        gdk_drawable_set_colormap

Warning

gdk_window_set_colormap is deprecated and should not be used in newly-written code.

Deprecated equivalent to gdk_drawable_set_colormap()

gdk_window_get_user_data ()

void                gdk_window_get_user_data            (GdkWindow *window,
                                                         gpointer *data);

Retrieves the user data for window, which is normally the widget that window belongs to. See gdk_window_set_user_data().

window : | a GdkWindow
data : | return location for user data

gdk_window_get_geometry ()

void                gdk_window_get_geometry             (GdkWindow *window,
                                                         gint *x,
                                                         gint *y,
                                                         gint *width,
                                                         gint *height,
                                                         gint *depth);

Any of the return location arguments to this function may be NULL, if you aren't interested in getting the value of that field.

The X and Y coordinates returned are relative to the parent window of window, which for toplevels usually means relative to the window decorations (titlebar, etc.) rather than relative to the root window (screen-size background window).

On the X11 platform, the geometry is obtained from the X server, so reflects the latest position of window; this may be out-of-sync with the position of window delivered in the most-recently-processed GdkEventConfigure. gdk_window_get_position() in contrast gets the position from the most recent configure event.

Note

If window is not a toplevel, it is much better to call gdk_window_get_position() and gdk_drawable_get_size() instead, because it avoids the roundtrip to the X server and because gdk_drawable_get_size() supports the full 32-bit coordinate space, whereas gdk_window_get_geometry() is restricted to the 16-bit coordinates of X11.

window : | a GdkWindow
x : | return location for X coordinate of window (relative to its parent)
y : | return location for Y coordinate of window (relative to its parent)
width : | return location for width of window
height : | return location for height of window
depth : | return location for bit depth of window

gdk_window_set_geometry_hints ()

void                gdk_window_set_geometry_hints       (GdkWindow *window,
                                                         GdkGeometry *geometry,
                                                         GdkWindowHints geom_mask);

Sets the geometry hints for window. Hints flagged in geom_mask are set, hints not flagged in geom_mask are unset. To unset all hints, use a geom_mask of 0 and a geometry of NULL.

This function provides hints to the windowing system about acceptable sizes for a toplevel window. The purpose of this is to constrain user resizing, but the windowing system will typically (but is not required to) also constrain the current size of the window to the provided values and constrain programatic resizing via gdk_window_resize() or gdk_window_move_resize().

Note that on X11, this effect has no effect on windows of type GDK_WINDOW_TEMP or windows where override redirect has been turned on via gdk_window_set_override_redirect() since these windows are not resizable by the user.

Since you can't count on the windowing system doing the constraints for programmatic resizes, you should generally call gdk_window_constrain_size() yourself to determine appropriate sizes.

window : | a toplevel GdkWindow
geometry : | geometry hints
geom_mask : | bitmask indicating fields of geometry to pay attention to

gdk_window_set_icon_list ()

void                gdk_window_set_icon_list            (GdkWindow *window,
                                                         GList *pixbufs);

Sets a list of icons for the window. One of these will be used to represent the window when it has been iconified. The icon is usually shown in an icon box or some sort of task bar. Which icon size is shown depends on the window manager. The window manager can scale the icon but setting several size icons can give better image quality since the window manager may only need to scale the icon by a small amount or not at all.

window : | The GdkWindow toplevel window to set the icon of.
pixbufs : | A list of pixbufs, of different sizes.

gdk_window_set_modal_hint ()

void                gdk_window_set_modal_hint           (GdkWindow *window,
                                                         gboolean modal);

The application can use this hint to tell the window manager that a certain window has modal behaviour. The window manager can use this information to handle modal windows in a special way.

You should only use this on windows for which you have previously called gdk_window_set_transient_for()

window : | A toplevel GdkWindow
modal : | TRUE if the window is modal, FALSE otherwise.

gdk_window_set_type_hint ()

void                gdk_window_set_type_hint            (GdkWindow *window,
                                                         GdkWindowTypeHint hint);

The application can use this call to provide a hint to the window manager about the functionality of a window. The window manager can use this information when determining the decoration and behaviour of the window.

The hint must be set before the window is mapped.

window : | A toplevel GdkWindow
hint : | A hint of the function this window will have

gdk_window_get_type_hint ()

GdkWindowTypeHint   gdk_window_get_type_hint            (GdkWindow *window);

This function returns the type hint set for a window.

window : | A toplevel GdkWindow
Returns : | The type hint set for window

Since 2.10

gdk_window_set_skip_taskbar_hint ()

void                gdk_window_set_skip_taskbar_hint    (GdkWindow *window,
                                                         gboolean skips_taskbar);

Toggles whether a window should appear in a task list or window list. If a window's semantic type as specified with gdk_window_set_type_hint() already fully describes the window, this function should not be called in addition, instead you should allow the window to be treated according to standard policy for its semantic type.

window : | a toplevel GdkWindow
skips_taskbar : | TRUE to skip the taskbar

Since 2.2

gdk_window_set_skip_pager_hint ()

void                gdk_window_set_skip_pager_hint      (GdkWindow *window,
                                                         gboolean skips_pager);

Toggles whether a window should appear in a pager (workspace switcher, or other desktop utility program that displays a small thumbnail representation of the windows on the desktop). If a window's semantic type as specified with gdk_window_set_type_hint() already fully describes the window, this function should not be called in addition, instead you should allow the window to be treated according to standard policy for its semantic type.

window : | a toplevel GdkWindow
skips_pager : | TRUE to skip the pager

Since 2.2

gdk_window_set_urgency_hint ()

void                gdk_window_set_urgency_hint         (GdkWindow *window,
                                                         gboolean urgent);

Toggles whether a window needs the user's urgent attention.

window : | a toplevel GdkWindow
urgent : | TRUE if the window is urgent

Since 2.8

gdk_window_get_position ()

void                gdk_window_get_position             (GdkWindow *window,
                                                         gint *x,
                                                         gint *y);

Obtains the position of the window as reported in the most-recently-processed GdkEventConfigure. Contrast with gdk_window_get_geometry() which queries the X server for the current window position, regardless of which events have been received or processed.

The position coordinates are relative to the window's parent window.

window : | a GdkWindow
x : | X coordinate of window
y : | Y coordinate of window

gdk_window_get_root_origin ()

void                gdk_window_get_root_origin          (GdkWindow *window,
                                                         gint *x,
                                                         gint *y);

Obtains the top-left corner of the window manager frame in root window coordinates.

window : | a toplevel GdkWindow
x : | return location for X position of window frame
y : | return location for Y position of window frame

gdk_window_get_frame_extents ()

void                gdk_window_get_frame_extents        (GdkWindow *window,
                                                         GdkRectangle *rect);

Obtains the bounding box of the window, including window manager titlebar/borders if any. The frame position is given in root window coordinates. To get the position of the window itself (rather than the frame) in root window coordinates, use gdk_window_get_origin().

window : | a GdkWindow
rect : | rectangle to fill with bounding box of the window frame

gdk_window_get_size

#define gdk_window_get_size            gdk_drawable_get_size

Warning

gdk_window_get_size is deprecated and should not be used in newly-written code.

Deprecated equivalent of gdk_drawable_get_size().

gdk_window_get_visual

#define gdk_window_get_visual          gdk_drawable_get_visual

Warning

gdk_window_get_visual is deprecated and should not be used in newly-written code.

Deprecated equivalent of gdk_drawable_get_visual().

Returns : the GdkVisual of the window

gdk_window_get_colormap

#define gdk_window_get_colormap        gdk_drawable_get_colormap

Warning

gdk_window_get_colormap is deprecated and should not be used in newly-written code.

Deprecated equivalent of gdk_drawable_get_colormap().

Returns : colormap for the window

gdk_window_get_type

#define gdk_window_get_type            gdk_window_get_window_type

Warning

gdk_window_get_type is deprecated and should not be used in newly-written code.

Deprecated equivalent of gdk_drawable_get_type().

Returns : type of drawable

gdk_window_get_origin ()

gint                gdk_window_get_origin               (GdkWindow *window,
                                                         gint *x,
                                                         gint *y);

Obtains the position of a window in root window coordinates. (Compare with gdk_window_get_position() and gdk_window_get_geometry() which return the position of a window relative to its parent window.)

window : | a GdkWindow
x : | return location for X coordinate
y : | return location for Y coordinate
Returns : | not meaningful, ignore

gdk_window_get_deskrelative_origin ()

gboolean            gdk_window_get_deskrelative_origin  (GdkWindow *window,
                                                         gint *x,
                                                         gint *y);

Warning

gdk_window_get_deskrelative_origin is deprecated and should not be used in newly-written code.

This gets the origin of a GdkWindow relative to an Enlightenment-window-manager desktop. As long as you don't assume that the user's desktop/workspace covers the entire root window (i.e. you don't assume that the desktop begins at root window coordinate 0,0) this function is not necessary. It's deprecated for that reason.

window : | a toplevel GdkWindow
x : | return location for X coordinate
y : | return location for Y coordinate
Returns : | not meaningful

gdk_window_get_pointer ()

GdkWindow*          gdk_window_get_pointer              (GdkWindow *window,
                                                         gint *x,
                                                         gint *y,
                                                         GdkModifierType *mask);

Obtains the current pointer position and modifier state. The position is given in coordinates relative to the upper left corner of window.

window : | a GdkWindow
x : | return location for X coordinate of pointer
y : | return location for Y coordinate of pointer
mask : | return location for modifier mask
Returns : | the window containing the pointer (as with gdk_window_at_pointer()), or NULL if the window containing the pointer isn't known to GDK

enum GdkModifierType

typedef enum
{
  GDK_SHIFT_MASK    = 1 << 0,
  GDK_LOCK_MASK	    = 1 << 1,
  GDK_CONTROL_MASK  = 1 << 2,
  GDK_MOD1_MASK	    = 1 << 3,
  GDK_MOD2_MASK	    = 1 << 4,
  GDK_MOD3_MASK	    = 1 << 5,
  GDK_MOD4_MASK	    = 1 << 6,
  GDK_MOD5_MASK	    = 1 << 7,
  GDK_BUTTON1_MASK  = 1 << 8,
  GDK_BUTTON2_MASK  = 1 << 9,
  GDK_BUTTON3_MASK  = 1 << 10,
  GDK_BUTTON4_MASK  = 1 << 11,
  GDK_BUTTON5_MASK  = 1 << 12,

  /* The next few modifiers are used by XKB, so we skip to the end.
   * Bits 15 - 25 are currently unused. Bit 29 is used internally.
   */

  GDK_SUPER_MASK    = 1 << 26,
  GDK_HYPER_MASK    = 1 << 27,
  GDK_META_MASK     = 1 << 28,

  GDK_RELEASE_MASK  = 1 << 30,

  GDK_MODIFIER_MASK = 0x5c001fff
} GdkModifierType;

A set of bit-flags to indicate the state of modifier keys and mouse buttons in various event types. Typical modifier keys are Shift, Control, Meta, Super, Hyper, Alt, Compose, Apple, CapsLock or ShiftLock.

Like the X Window System, GDK supports 8 modifier keys and 5 mouse buttons.

Since 2.10, GDK recognizes which of the Meta, Super or Hyper keys are mapped to Mod2 - Mod5, and indicates this by setting GDK_SUPER_MASK, GDK_HYPER_MASK or GDK_META_MASK in the state field of key events.

GDK_SHIFT_MASK | the Shift key.
GDK_LOCK_MASK | a Lock key (depending on the modifier mapping of the X server this may either be CapsLock or ShiftLock).
GDK_CONTROL_MASK | the Control key.
GDK_MOD1_MASK | the fourth modifier key (it depends on the modifier mapping of the X server which key is interpreted as this modifier, but normally it is the Alt key).
GDK_MOD2_MASK | the fifth modifier key (it depends on the modifier mapping of the X server which key is interpreted as this modifier).
GDK_MOD3_MASK | the sixth modifier key (it depends on the modifier mapping of the X server which key is interpreted as this modifier).
GDK_MOD4_MASK | the seventh modifier key (it depends on the modifier mapping of the X server which key is interpreted as this modifier).
GDK_MOD5_MASK | the eighth modifier key (it depends on the modifier mapping of the X server which key is interpreted as this modifier).
GDK_BUTTON1_MASK | the first mouse button.
GDK_BUTTON2_MASK | the second mouse button.
GDK_BUTTON3_MASK | the third mouse button.
GDK_BUTTON4_MASK | the fourth mouse button.
GDK_BUTTON5_MASK | the fifth mouse button.
GDK_SUPER_MASK | the Super modifier. Since 2.10
GDK_HYPER_MASK | the Hyper modifier. Since 2.10
GDK_META_MASK | the Meta modifier. Since 2.10
GDK_RELEASE_MASK | not used in GDK itself. GTK+ uses it to differentiate between (keyval, modifiers) pairs from key press and release events.
GDK_MODIFIER_MASK | a mask covering all modifier types.

gdk_window_get_parent ()

GdkWindow*          gdk_window_get_parent               (GdkWindow *window);

Obtains the parent of window, as known to GDK. Does not query the X server; thus this returns the parent as passed to gdk_window_new(), not the actual parent. This should never matter unless you're using Xlib calls mixed with GDK calls on the X11 platform. It may also matter for toplevel windows, because the window manager may choose to reparent them.

window : | a GdkWindow
Returns : | parent of window

gdk_window_get_toplevel ()

GdkWindow*          gdk_window_get_toplevel             (GdkWindow *window);

Gets the toplevel window that's an ancestor of window.

window : | a GdkWindow
Returns : | the toplevel window containing window

gdk_window_get_children ()

GList*              gdk_window_get_children             (GdkWindow *window);

Gets the list of children of window known to GDK. This function only returns children created via GDK, so for example it's useless when used with the root window; it only returns windows an application created itself.

The returned list must be freed, but the elements in the list need not be.

window : | a GdkWindow
Returns : | list of child windows inside window

gdk_window_peek_children ()

GList*              gdk_window_peek_children            (GdkWindow *window);

Like gdk_window_get_children(), but does not copy the list of children, so the list does not need to be freed.

window : | a GdkWindow
Returns : | a reference to the list of child windows in window

gdk_window_get_events ()

GdkEventMask        gdk_window_get_events               (GdkWindow *window);

Gets the event mask for window. See gdk_window_set_events().

window : | a GdkWindow
Returns : | event mask for window

gdk_window_set_events ()

void                gdk_window_set_events               (GdkWindow *window,
                                                         GdkEventMask event_mask);

The event mask for a window determines which events will be reported for that window. For example, an event mask including GDK_BUTTON_PRESS_MASK means the window should report button press events. The event mask is the bitwise OR of values from the GdkEventMask enumeration.

window : | a GdkWindow
event_mask : | event mask for window

gdk_window_set_icon ()

void                gdk_window_set_icon                 (GdkWindow *window,
                                                         GdkWindow *icon_window,
                                                         GdkPixmap *pixmap,
                                                         GdkBitmap *mask);

Sets the icon of window as a pixmap or window. If using GTK+, investigate gtk_window_set_default_icon_list() first, and then gtk_window_set_icon_list() and gtk_window_set_icon(). If those don't meet your needs, look at gdk_window_set_icon_list(). Only if all those are too high-level do you want to fall back to gdk_window_set_icon().

window : | a toplevel GdkWindow
icon_window : | a GdkWindow to use for the icon, or NULL to unset
pixmap : | a GdkPixmap to use as the icon, or NULL to unset
mask : | a 1-bit pixmap (GdkBitmap) to use as mask for pixmap, or NULL to have none

gdk_window_set_icon_name ()

void                gdk_window_set_icon_name            (GdkWindow *window,
                                                         const gchar *name);

Windows may have a name used while minimized, distinct from the name they display in their titlebar. Most of the time this is a bad idea from a user interface standpoint. But you can set such a name with this function, if you like.

window : | a toplevel GdkWindow
name : | name of window while iconified (minimized)

gdk_window_set_transient_for ()

void                gdk_window_set_transient_for        (GdkWindow *window,
                                                         GdkWindow *parent);

Indicates to the window manager that window is a transient dialog associated with the application window parent. This allows the window manager to do things like center window on parent and keep window above parent.

See gtk_window_set_transient_for() if you're using GtkWindow or GtkDialog.

window : | a toplevel GdkWindow
parent : | another toplevel GdkWindow

gdk_window_set_role ()

void                gdk_window_set_role                 (GdkWindow *window,
                                                         const gchar *role);

When using GTK+, typically you should use gtk_window_set_role() instead of this low-level function.

The window manager and session manager use a window's role to distinguish it from other kinds of window in the same application. When an application is restarted after being saved in a previous session, all windows with the same title and role are treated as interchangeable. So if you have two windows with the same title that should be distinguished for session management purposes, you should set the role on those windows. It doesn't matter what string you use for the role, as long as you have a different role for each non-interchangeable kind of window.

window : | a toplevel GdkWindow
role : | a string indicating its role

gdk_window_set_group ()

void                gdk_window_set_group                (GdkWindow *window,
                                                         GdkWindow *leader);

Sets the group leader window for window. By default, GDK sets the group leader for all toplevel windows to a global window implicitly created by GDK. With this function you can override this default.

The group leader window allows the window manager to distinguish all windows that belong to a single application. It may for example allow users to minimize/unminimize all windows belonging to an application at once. You should only set a non-default group window if your application pretends to be multiple applications.

window : | a toplevel GdkWindow
leader : | group leader window, or NULL to restore the default group leader window

gdk_window_get_group ()

GdkWindow*          gdk_window_get_group                (GdkWindow *window);

Returns the group leader window for window. See gdk_window_set_group().

window : | a toplevel GdkWindow
Returns : | the group leader window for window

Since 2.4

gdk_window_set_decorations ()

void                gdk_window_set_decorations          (GdkWindow *window,
                                                         GdkWMDecoration decorations);

"Decorations" are the features the window manager adds to a toplevel GdkWindow. This function sets the traditional Motif window manager hints that tell the window manager which decorations you would like your window to have. Usually you should use gtk_window_set_decorated() on a GtkWindow instead of using the GDK function directly.

The decorations argument is the logical OR of the fields in the GdkWMDecoration enumeration. If GDK_DECOR_ALL is included in the mask, the other bits indicate which decorations should be turned off. If GDK_DECOR_ALL is not included, then the other bits indicate which decorations should be turned on.

Most window managers honor a decorations hint of 0 to disable all decorations, but very few honor all possible combinations of bits.

window : | a toplevel GdkWindow
decorations : | decoration hint mask

gdk_window_get_decorations ()

gboolean            gdk_window_get_decorations          (GdkWindow *window,
                                                         GdkWMDecoration *decorations);

Returns the decorations set on the GdkWindow with gdk_window_set_decorations

window : | The toplevel GdkWindow to get the decorations from
decorations : | The window decorations will be written here
Returns : | TRUE if the window has decorations set, FALSE otherwise.

enum GdkWMDecoration

typedef enum
{
  GDK_DECOR_ALL		= 1 << 0,
  GDK_DECOR_BORDER	= 1 << 1,
  GDK_DECOR_RESIZEH	= 1 << 2,
  GDK_DECOR_TITLE	= 1 << 3,
  GDK_DECOR_MENU	= 1 << 4,
  GDK_DECOR_MINIMIZE	= 1 << 5,
  GDK_DECOR_MAXIMIZE	= 1 << 6
} GdkWMDecoration;

These are hints originally defined by the Motif toolkit. The window manager can use them when determining how to decorate the window. The hint must be set before mapping the window.

GDK_DECOR_ALL | all decorations should be applied.
GDK_DECOR_BORDER | a frame should be drawn around the window.
GDK_DECOR_RESIZEH | the frame should have resize handles.
GDK_DECOR_TITLE | a titlebar should be placed above the window.
GDK_DECOR_MENU | a button for opening a menu should be included.
GDK_DECOR_MINIMIZE | a minimize button should be included.
GDK_DECOR_MAXIMIZE | a maximize button should be included.

gdk_window_set_functions ()

void                gdk_window_set_functions            (GdkWindow *window,
                                                         GdkWMFunction functions);

Sets hints about the window management functions to make available via buttons on the window frame.

On the X backend, this function sets the traditional Motif window manager hint for this purpose. However, few window managers do anything reliable or interesting with this hint. Many ignore it entirely.

The functions argument is the logical OR of values from the GdkWMFunction enumeration. If the bitmask includes GDK_FUNC_ALL, then the other bits indicate which functions to disable; if it doesn't include GDK_FUNC_ALL, it indicates which functions to enable.

window : | a toplevel GdkWindow
functions : | bitmask of operations to allow on window

enum GdkWMFunction

typedef enum
{
  GDK_FUNC_ALL		= 1 << 0,
  GDK_FUNC_RESIZE	= 1 << 1,
  GDK_FUNC_MOVE		= 1 << 2,
  GDK_FUNC_MINIMIZE	= 1 << 3,
  GDK_FUNC_MAXIMIZE	= 1 << 4,
  GDK_FUNC_CLOSE	= 1 << 5
} GdkWMFunction;

These are hints originally defined by the Motif toolkit. The window manager can use them when determining the functions to offer for the window. The hint must be set before mapping the window.

GDK_FUNC_ALL | all functions should be offered.
GDK_FUNC_RESIZE | the window should be resizable.
GDK_FUNC_MOVE | the window should be movable.
GDK_FUNC_MINIMIZE | the window should be minimizable.
GDK_FUNC_MAXIMIZE | the window should be maximizable.
GDK_FUNC_CLOSE | the window should be closable.

gdk_window_get_toplevels ()

GList*              gdk_window_get_toplevels            (void);

Obtains a list of all toplevel windows known to GDK on the default screen (see gdk_screen_get_toplevel_windows()). A toplevel window is a child of the root window (see gdk_get_default_root_window()).

The returned list should be freed with g_list_free(), but its elements need not be freed.

Returns : list of toplevel windows, free with g_list_free()

gdk_get_default_root_window ()

GdkWindow*          gdk_get_default_root_window         (void);

Obtains the root window (parent all other windows are inside) for the default display and screen.

Returns : the default root window

GdkPointerHooks

typedef struct {
  GdkWindow* (*get_pointer)       (GdkWindow	   *window,
                       gint	           *x,
                       gint   	   *y,
                       GdkModifierType *mask);
  GdkWindow* (*window_at_pointer) (GdkScreen       *screen, /* unused */
                                   gint            *win_x,
                                   gint            *win_y);
} GdkPointerHooks;

A table of pointers to functions for getting quantities related to the current pointer position. GDK has one global table of this type, which can be set using gdk_set_pointer_hooks().

This is only useful for such low-level tools as an event recorder. Applications should never have any reason to use this facility

get_pointer () | Obtains the current pointer position and modifier state. The position is given in coordinates relative to the window containing the pointer, which is returned in window.
window_at_pointer () | Obtains the window underneath the mouse pointer, returning the location of that window in win_x, win_y. Returns NULL if the window under the mouse pointer is not known to GDK (for example, belongs to another application).

gdk_set_pointer_hooks ()

GdkPointerHooks*    gdk_set_pointer_hooks               (const GdkPointerHooks *new_hooks);

This function allows for hooking into the operation of getting the current location of the pointer. This is only useful for such low-level tools as an event recorder. Applications should never have any reason to use this facility.

This function is not multihead safe. For multihead operation, see gdk_display_set_pointer_hooks().

new_hooks : | a table of pointers to functions for getting quantities related to the current pointer position, or NULL to restore the default table.
Returns : | the previous pointer hook table


X Window System Interaction

X Window System Interaction — X backend-specific functions

Synopsis

#include <gdk/gdkx.h>

#define             GDK_ROOT_WINDOW                     ()
#define             GDK_ROOT_PARENT                     ()
#define             GDK_DISPLAY                         ()
#define             GDK_WINDOW_XDISPLAY                 (win)
#define             GDK_WINDOW_XID                      (win)
#define             GDK_PIXMAP_XDISPLAY                 (pix)
#define             GDK_PIXMAP_XID                      (pix)
#define             GDK_DISPLAY_XDISPLAY                (display)
#define             GDK_DRAWABLE_XDISPLAY               (win)
#define             GDK_DRAWABLE_XID                    (win)
#define             GDK_IMAGE_XDISPLAY                  (image)
#define             GDK_IMAGE_XIMAGE                    (image)
#define             GDK_GC_XDISPLAY                     (gc)
#define             GDK_COLORMAP_XDISPLAY               (cmap)
#define             GDK_COLORMAP_XCOLORMAP              (cmap)
#define             GDK_SCREEN_XDISPLAY                 (screen)
#define             GDK_SCREEN_XNUMBER                  (screen)
#define             GDK_SCREEN_XSCREEN                  (screen)
#define             GDK_VISUAL_XVISUAL                  (vis)
#define             GDK_FONT_XDISPLAY                   (font)
#define             GDK_FONT_XFONT                      (font)
#define             GDK_CURSOR_XCURSOR                  (cursor)
#define             GDK_CURSOR_XDISPLAY                 (cursor)
#define             GDK_GC_XGC                          (gc)
#define             GDK_GC_GET_XGC                      (gc)
#define             GDK_WINDOW_XWINDOW
GdkVisual*          gdkx_visual_get                     (VisualID xvisualid);
GdkColormap*        gdkx_colormap_get                   (Colormap xcolormap);
GdkPixmap*          gdk_pixmap_foreign_new              (GdkNativeWindow anid);
GdkPixmap*          gdk_pixmap_foreign_new_for_display  (GdkDisplay *display,
                                                         GdkNativeWindow anid);
GdkPixmap*          gdk_pixmap_foreign_new_for_screen   (GdkScreen *screen,
                                                         GdkNativeWindow anid,
                                                         gint width,
                                                         gint height,
                                                         gint depth);
GdkWindow*          gdk_window_foreign_new              (GdkNativeWindow anid);
GdkWindow*          gdk_window_foreign_new_for_display  (GdkDisplay *display,
                                                         GdkNativeWindow anid);
gpointer            gdk_xid_table_lookup                (XID xid);
gpointer            gdk_xid_table_lookup_for_display    (GdkDisplay *display,
                                                         XID xid);
GdkWindow*          gdk_window_lookup                   (GdkNativeWindow anid);
GdkWindow*          gdk_window_lookup_for_display       (GdkDisplay *display,
                                                         GdkNativeWindow anid);
GdkPixmap*          gdk_pixmap_lookup                   (GdkNativeWindow anid);
GdkPixmap*          gdk_pixmap_lookup_for_display       (GdkDisplay *display,
                                                         GdkNativeWindow anid);
#define             gdk_font_lookup                     (xid)
#define             gdk_font_lookup_for_display         (display, xid)
GdkDisplay*         gdk_x11_lookup_xdisplay             (Display *xdisplay);
guint32             gdk_x11_get_server_time             (GdkWindow *window);
gboolean            gdk_net_wm_supports                 (GdkAtom property);
gboolean            gdk_x11_screen_supports_net_wm_hint (GdkScreen *screen,
                                                         GdkAtom property);
const char*         gdk_x11_screen_get_window_manager_name
                                                        (GdkScreen *screen);
GdkVisual*          gdk_x11_screen_lookup_visual        (GdkScreen *screen,
                                                         VisualID xvisualid);
void                gdk_x11_window_set_user_time        (GdkWindow *window,
                                                         guint32 timestamp);
void                gdk_x11_window_move_to_current_desktop
                                                        (GdkWindow *window);
guint32             gdk_x11_display_get_user_time       (GdkDisplay *display);
GdkColormap*        gdk_x11_colormap_foreign_new        (GdkVisual *visual,
                                                         Colormap xcolormap);
Colormap            gdk_x11_colormap_get_xcolormap      (GdkColormap *colormap);
Display*            gdk_x11_colormap_get_xdisplay       (GdkColormap *colormap);
Cursor              gdk_x11_cursor_get_xcursor          (GdkCursor *cursor);
Display*            gdk_x11_cursor_get_xdisplay         (GdkCursor *cursor);
Display*            gdk_x11_display_get_xdisplay        (GdkDisplay *display);
void                gdk_x11_display_grab                (GdkDisplay *display);
void                gdk_x11_display_ungrab              (GdkDisplay *display);
void                gdk_x11_display_set_cursor_theme    (GdkDisplay *display,
                                                         const gchar *theme,
                                                         const gint size);
void                gdk_x11_register_standard_event_type
                                                        (GdkDisplay *display,
                                                         gint event_base,
                                                         gint n_events);
Display*            gdk_x11_drawable_get_xdisplay       (GdkDrawable *drawable);
XID                 gdk_x11_drawable_get_xid            (GdkDrawable *drawable);
const char*         gdk_x11_font_get_name               (GdkFont *font);
Display*            gdk_x11_font_get_xdisplay           (GdkFont *font);
gpointer            gdk_x11_font_get_xfont              (GdkFont *font);
Display*            gdk_x11_gc_get_xdisplay             (GdkGC *gc);
GC                  gdk_x11_gc_get_xgc                  (GdkGC *gc);
Window              gdk_x11_get_default_root_xwindow    (void);
gint                gdk_x11_get_default_screen          (void);
Display*            gdk_x11_get_default_xdisplay        (void);
void                gdk_x11_grab_server                 (void);
Display*            gdk_x11_image_get_xdisplay          (GdkImage *image);
XImage*             gdk_x11_image_get_ximage            (GdkImage *image);
int                 gdk_x11_screen_get_screen_number    (GdkScreen *screen);
Screen*             gdk_x11_screen_get_xscreen          (GdkScreen *screen);
void                gdk_x11_ungrab_server               (void);
Visual*             gdk_x11_visual_get_xvisual          (GdkVisual *visual);
Atom                gdk_x11_atom_to_xatom               (GdkAtom atom);
Atom                gdk_x11_atom_to_xatom_for_display   (GdkDisplay *display,
                                                         GdkAtom atom);
GdkAtom             gdk_x11_xatom_to_atom               (Atom xatom);
GdkAtom             gdk_x11_xatom_to_atom_for_display   (GdkDisplay *display,
                                                         Atom xatom);
Atom                gdk_x11_get_xatom_by_name           (const gchar *atom_name);
Atom                gdk_x11_get_xatom_by_name_for_display
                                                        (GdkDisplay *display,
                                                         const gchar *atom_name);
const gchar*        gdk_x11_get_xatom_name              (Atom xatom);
const gchar*        gdk_x11_get_xatom_name_for_display  (GdkDisplay *display,
                                                         Atom xatom);

Description

Details

GDK_ROOT_WINDOW()

#define GDK_ROOT_WINDOW()             (gdk_x11_get_default_root_xwindow ())

Obtains the Xlib window id of the root window of the current screen.

GDK_ROOT_PARENT()

#define GDK_ROOT_PARENT()             (gdk_get_default_root_window ())

Warning

GDK_ROOT_PARENT is deprecated and should not be used in newly-written code.

Obtains the Xlib window id of the root window of the default screen.

GDK_DISPLAY()

#define GDK_DISPLAY()                 gdk_display

The current display.

Returns : an Xlib Display*.

GDK_WINDOW_XDISPLAY()

#define             GDK_WINDOW_XDISPLAY(win)

Returns the display of a GdkWindow.

win : | a GdkWindow.
Returns : | an Xlib Display*.

GDK_WINDOW_XID()

#define             GDK_WINDOW_XID(win)

Returns the X window belonging to a GdkWindow.

win : | a GdkWindow.
Returns : | the Xlib Window of win.

GDK_PIXMAP_XDISPLAY()

#define             GDK_PIXMAP_XDISPLAY(pix)

Returns the display of a GdkPixmap.

pix : | a GdkPixmap.
Returns : | an Xlib Display*.

GDK_PIXMAP_XID()

#define             GDK_PIXMAP_XID(pix)

Returns the X pixmap belonging to a GdkPixmap.

pix : | a GdkPixmap.
Returns : | the Xlib XPixmap of win.

GDK_DISPLAY_XDISPLAY()

#define             GDK_DISPLAY_XDISPLAY(display)

Returns the display of a GdkDisplay.

display : a GdkDisplay.

GDK_DRAWABLE_XDISPLAY()

#define             GDK_DRAWABLE_XDISPLAY(win)

Returns the display of a GdkDrawable.

win : | a GdkDrawable.
Returns : | an Xlib Display*.

GDK_DRAWABLE_XID()

#define             GDK_DRAWABLE_XID(win)

Returns the X resource (window or pixmap) belonging to a GdkDrawable.

win : | a GdkDrawable.
Returns : | the ID of win's X resource.

GDK_IMAGE_XDISPLAY()

#define GDK_IMAGE_XDISPLAY(image)     (gdk_x11_image_get_xdisplay (image))

Returns the display of a GdkImage.

image : | a GdkImage.
Returns : | an Xlib Display*.

GDK_IMAGE_XIMAGE()

#define GDK_IMAGE_XIMAGE(image)       (gdk_x11_image_get_ximage (image))

Returns the X image belonging to a GdkImage.

image : | a GdkImage.
Returns : | an XImage*.

GDK_GC_XDISPLAY()

#define             GDK_GC_XDISPLAY(gc)

Returns the display of a GdkGC.

gc : | a GdkGC.
Returns : | an Xlib Display*.

GDK_COLORMAP_XDISPLAY()

#define GDK_COLORMAP_XDISPLAY(cmap)   (gdk_x11_colormap_get_xdisplay (cmap))

Returns the display of a GdkColormap.

cmap : | a GdkColormap.
Returns : | an Xlib Display*.

GDK_COLORMAP_XCOLORMAP()

#define GDK_COLORMAP_XCOLORMAP(cmap)  (gdk_x11_colormap_get_xcolormap (cmap))

Returns the X colormap belonging to a GdkColormap.

cmap : | a GdkColormap.
Returns : | an Xlib Colormap.

GDK_SCREEN_XDISPLAY()

#define             GDK_SCREEN_XDISPLAY(screen)

Returns the display of a GdkScreen.

screen : | a GdkScreen.
Returns : | an Xlib Display*.

GDK_SCREEN_XNUMBER()

#define             GDK_SCREEN_XNUMBER(screen)

Returns the index of a GdkScreen.

screen : | a GdkScreen
Returns : | the position of screen among the screens of its display.

GDK_SCREEN_XSCREEN()

#define             GDK_SCREEN_XSCREEN(screen)

Returns the screen of a GdkScreen.

screen : | a GdkScreen
Returns : | an Xlib Screen*.

GDK_VISUAL_XVISUAL()

#define             GDK_VISUAL_XVISUAL(vis)

Returns the X visual belonging to a GdkVisual.

vis : | a GdkVisual.
Returns : | an Xlib Visual*.

GDK_FONT_XDISPLAY()

#define GDK_FONT_XDISPLAY(font)       (gdk_x11_font_get_xdisplay (font))

Warning

GDK_FONT_XDISPLAY is deprecated and should not be used in newly-written code.

Returns the display of a GdkFont.

font : | a GdkFont.
Returns : | an Xlib Display*.

GDK_FONT_XFONT()

#define GDK_FONT_XFONT(font)          (gdk_x11_font_get_xfont (font))

Warning

GDK_FONT_XFONT is deprecated and should not be used in newly-written code.

Returns the X font belonging to a GdkFont.

font : | a GdkFont.
Returns : | an Xlib XFontStruct* or an XFontSet.

GDK_CURSOR_XCURSOR()

#define GDK_CURSOR_XCURSOR(cursor)    (gdk_x11_cursor_get_xcursor (cursor))

Returns the X cursor belonging to a GdkCursor.

cursor : | a GdkCursor.
Returns : | an Xlib Cursor.

GDK_CURSOR_XDISPLAY()

#define GDK_CURSOR_XDISPLAY(cursor)   (gdk_x11_cursor_get_xdisplay (cursor))

Returns the display of a GdkCursor.

cursor : | a GdkCursor.
Returns : | an Xlib Display*.

GDK_GC_XGC()

#define             GDK_GC_XGC(gc)

Returns the X GC of a GdkGC.

gc : | a GdkGC.
Returns : | an Xlib GC.

GDK_GC_GET_XGC()

#define GDK_GC_GET_XGC(gc)	      (GDK_GC_X11(gc)->dirty_mask ? _gdk_x11_gc_flush (gc) : ((GdkGCX11 *)(gc))->xgc)

Returns the X GC of a GdkGC.

gc : | a GdkGC.
Returns : | an Xlib GC.

GDK_WINDOW_XWINDOW

#define             GDK_WINDOW_XWINDOW

Another name for GDK_DRAWABLE_XID().

gdkx_visual_get ()

GdkVisual*          gdkx_visual_get                     (VisualID xvisualid);

Returns a GdkVisual corresponding to a X visual.

xvisualid : | a X visual id.
Returns : | the GdkVisual.

gdkx_colormap_get ()

GdkColormap*        gdkx_colormap_get                   (Colormap xcolormap);

Warning

gdkx_colormap_get is deprecated and should not be used in newly-written code.

Returns a GdkColormap corresponding to a X colormap; this function only works if the colormap is already known to GTK+ (a colormap created by GTK+ or the default colormap for the screen), since GTK+

Always use gdk_x11_colormap_foreign_new() instead.

xcolormap : | the XID of a colormap for the default screen.
Returns : | the existing GdkColormap object if it was already known to GTK+, otherwise warns and return NULL.

gdk_pixmap_foreign_new ()

GdkPixmap*          gdk_pixmap_foreign_new              (GdkNativeWindow anid);

Wraps a native window for the default display in a GdkPixmap. This may fail if the pixmap has been destroyed.

For example in the X backend, a native pixmap handle is an Xlib XID.

anid : | a native pixmap handle.
Returns : | the newly-created GdkPixmap wrapper for the native pixmap or NULL if the pixmap has been destroyed.

gdk_pixmap_foreign_new_for_display ()

GdkPixmap*          gdk_pixmap_foreign_new_for_display  (GdkDisplay *display,
                                                         GdkNativeWindow anid);

Wraps a native pixmap in a GdkPixmap. This may fail if the pixmap has been destroyed.

For example in the X backend, a native pixmap handle is an Xlib XID.

display : | The GdkDisplay where anid is located.
anid : | a native pixmap handle.
Returns : | the newly-created GdkPixmap wrapper for the native pixmap or NULL if the pixmap has been destroyed.

Since 2.2

gdk_pixmap_foreign_new_for_screen ()

GdkPixmap*          gdk_pixmap_foreign_new_for_screen   (GdkScreen *screen,
                                                         GdkNativeWindow anid,
                                                         gint width,
                                                         gint height,
                                                         gint depth);

Wraps a native pixmap in a GdkPixmap. This may fail if the pixmap has been destroyed.

For example in the X backend, a native pixmap handle is an Xlib XID.

This function is an alternative to gdk_pixmap_foreign_new_for_display() for cases where the dimensions of the pixmap are known. For the X backend, this avoids a roundtrip to the server.

screen : | a GdkScreen
anid : | a native pixmap handle
width : | the width of the pixmap identified by anid
height : | the height of the pixmap identified by anid
depth : | the depth of the pixmap identified by anid
Returns : | the newly-created GdkPixmap wrapper for the native pixmap or NULL if the pixmap has been destroyed.

Since 2.10

gdk_window_foreign_new ()

GdkWindow*          gdk_window_foreign_new              (GdkNativeWindow anid);

Wraps a native window for the default display in a GdkWindow. This may fail if the window has been destroyed.

For example in the X backend, a native window handle is an Xlib XID.

anid : | a native window handle.
Returns : | the newly-created GdkWindow wrapper for the native window or NULL if the window has been destroyed.

gdk_window_foreign_new_for_display ()

GdkWindow*          gdk_window_foreign_new_for_display  (GdkDisplay *display,
                                                         GdkNativeWindow anid);

Wraps a native window in a GdkWindow. This may fail if the window has been destroyed. If the window was already known to GDK, a new reference to the existing GdkWindow is returned.

For example in the X backend, a native window handle is an Xlib XID.

display : | the GdkDisplay where the window handle comes from.
anid : | a native window handle.
Returns : | a GdkWindow wrapper for the native window or NULL if the window has been destroyed. The wrapper will be newly created, if one doesn't exist already.

Since 2.2

gdk_xid_table_lookup ()

gpointer            gdk_xid_table_lookup                (XID xid);

Returns the Gdk object associated with the given X id.

xid : | an X id.
Returns : | the associated Gdk object, which may be a GdkPixmap, a GdkWindow or a GdkFont.

gdk_xid_table_lookup_for_display ()

gpointer            gdk_xid_table_lookup_for_display    (GdkDisplay *display,
                                                         XID xid);

Returns the GDK object associated with the given X id.

display : | the GdkDisplay.
xid : | an X id.
Returns : | a GDK object associated with the given X id.

Since 2.2

gdk_window_lookup ()

GdkWindow*          gdk_window_lookup                   (GdkNativeWindow anid);

Looks up the GdkWindow that wraps the given native window handle.

For example in the X backend, a native window handle is an Xlib XID.

anid : | a native window handle.
Returns : | the GdkWindow wrapper for the native window, or NULL if there is none.

gdk_window_lookup_for_display ()

GdkWindow*          gdk_window_lookup_for_display       (GdkDisplay *display,
                                                         GdkNativeWindow anid);

Looks up the GdkWindow that wraps the given native window handle.

For example in the X backend, a native window handle is an Xlib XID.

display : | the GdkDisplay corresponding to the window handle
anid : | a native window handle.
Returns : | the GdkWindow wrapper for the native window, or NULL if there is none.

Since 2.2

gdk_pixmap_lookup ()

GdkPixmap*          gdk_pixmap_lookup                   (GdkNativeWindow anid);

Looks up the GdkPixmap that wraps the given native pixmap handle.

For example in the X backend, a native pixmap handle is an Xlib XID.

anid : | a native pixmap handle.
Returns : | the GdkWindow wrapper for the native window, or NULL if there is none.

gdk_pixmap_lookup_for_display ()

GdkPixmap*          gdk_pixmap_lookup_for_display       (GdkDisplay *display,
                                                         GdkNativeWindow anid);

Looks up the GdkPixmap that wraps the given native pixmap handle.

For example in the X backend, a native pixmap handle is an Xlib XID.

display : | the GdkDisplay associated with anid
anid : | a native pixmap handle.
Returns : | the GdkPixmap wrapper for the native pixmap, or NULL if there is none.

Since 2.2

gdk_font_lookup()

#define gdk_font_lookup(xid)	   ((GdkFont*) gdk_xid_table_lookup (xid))

Warning

gdk_font_lookup is deprecated and should not be used in newly-written code.

Obtains the GdkFont for the given Xlib font ID, or NULL if no GdkFont has been created for xid.

xid : an Xlib font ID

gdk_font_lookup_for_display()

#define gdk_font_lookup_for_display(display, xid) ((GdkFont*) gdk_xid_table_lookup_for_display (display, ((xid)|XID_FONT_BIT)))

Warning

gdk_font_lookup_for_display is deprecated and should not be used in newly-written code.

Obtains the GdkFont for the given Xlib font ID on display, or NULL if no GdkFont has been created for xid.

display : | a GdkDisplay
xid : | an Xlib font ID Since: 2.2

gdk_x11_lookup_xdisplay ()

GdkDisplay*         gdk_x11_lookup_xdisplay             (Display *xdisplay);

Find the GdkDisplay corresponding to display, if any exists.

xdisplay : | a pointer to an X Display
Returns : | the GdkDisplay, if found, otherwise NULL.

Since 2.2

gdk_x11_get_server_time ()

guint32             gdk_x11_get_server_time             (GdkWindow *window);

Routine to get the current X server time stamp.

window : | a GdkWindow, used for communication with the server. The window must have GDK_PROPERTY_CHANGE_MASK in its events mask or a hang will result.
Returns : | the time stamp.

gdk_net_wm_supports ()

gboolean            gdk_net_wm_supports                 (GdkAtom property);

This function is specific to the X11 backend of GDK, and indicates whether the window manager for the default screen supports a certain hint from the Extended Window Manager Hints Specification. See gdk_x11_screen_supports_net_wm_hint() for complete details.

property : | a property atom.
Returns : | TRUE if the window manager supports property

gdk_x11_screen_supports_net_wm_hint ()

gboolean            gdk_x11_screen_supports_net_wm_hint (GdkScreen *screen,
                                                         GdkAtom property);

This function is specific to the X11 backend of GDK, and indicates whether the window manager supports a certain hint from the Extended Window Manager Hints Specification. You can find this specification on http://www.freedesktop.org.

When using this function, keep in mind that the window manager can change over time; so you shouldn't use this function in a way that impacts persistent application state. A common bug is that your application can start up before the window manager does when the user logs in, and before the window manager starts gdk_x11_screen_supports_net_wm_hint() will return FALSE for every property. You can monitor the window_manager_changed signal on GdkScreen to detect a window manager change.

screen : | the relevant GdkScreen.
property : | a property atom.
Returns : | TRUE if the window manager supports property

Since 2.2

gdk_x11_screen_get_window_manager_name ()

const char*         gdk_x11_screen_get_window_manager_name
                                                        (GdkScreen *screen);

Returns the name of the window manager for screen.

screen : | a GdkScreen
Returns : | the name of the window manager screen screen, or "unknown" if the window manager is unknown. The string is owned by GDK and should not be freed.

Since 2.2

gdk_x11_screen_lookup_visual ()

GdkVisual*          gdk_x11_screen_lookup_visual        (GdkScreen *screen,
                                                         VisualID xvisualid);

Looks up the GdkVisual for a particular screen and X Visual ID.

screen : | a GdkScreen.
xvisualid : | an X Visual ID.
Returns : | the GdkVisual (owned by the screen object), or NULL if the visual ID wasn't found.

Since 2.2

gdk_x11_window_set_user_time ()

void                gdk_x11_window_set_user_time        (GdkWindow *window,
                                                         guint32 timestamp);

The application can use this call to update the _NET_WM_USER_TIME property on a toplevel window. This property stores an Xserver time which represents the time of the last user input event received for this window. This property may be used by the window manager to alter the focus, stacking, and/or placement behavior of windows when they are mapped depending on whether the new window was created by a user action or is a "pop-up" window activated by a timer or some other event.

Note that this property is automatically updated by GDK, so this function should only be used by applications which handle input events bypassing GDK.

window : | A toplevel GdkWindow
timestamp : | An XServer timestamp to which the property should be set

Since 2.6

gdk_x11_window_move_to_current_desktop ()

void                gdk_x11_window_move_to_current_desktop
                                                        (GdkWindow *window);

Moves the window to the correct workspace when running under a window manager that supports multiple workspaces, as described in the Extended Window Manager Hints. Will not do anything if the window is already on all workspaces.

window : a GdkWindow

Since 2.8

gdk_x11_display_get_user_time ()

guint32             gdk_x11_display_get_user_time       (GdkDisplay *display);

Returns the timestamp of the last user interaction on display. The timestamp is taken from events caused by user interaction such as key presses or pointer movements. See gdk_x11_window_set_user_time().

display : | a GdkDisplay
Returns : | the timestamp of the last user interaction

Since 2.8

gdk_x11_colormap_foreign_new ()

GdkColormap*        gdk_x11_colormap_foreign_new        (GdkVisual *visual,
                                                         Colormap xcolormap);

If xcolormap refers to a colormap previously known to GTK+, returns a new reference to the existing GdkColormap object, otherwise creates a new GdkColormap object and returns that

visual : | a GdkVisual
xcolormap : | The XID of a colormap with visual visual
Returns : | the GdkColormap object for xcolormap. Free with g_object_unref(). Note that for colormap created with gdk_x11_colormap_foreign_new(), unref'ing the last reference to the object will only free the GdkColoramp object and not call XFreeColormap()

Since 2.2

gdk_x11_colormap_get_xcolormap ()

Colormap            gdk_x11_colormap_get_xcolormap      (GdkColormap *colormap);

Returns the X colormap belonging to a GdkColormap.

colormap : | a GdkColormap.
Returns : | an Xlib Colormap.

gdk_x11_colormap_get_xdisplay ()

Display*            gdk_x11_colormap_get_xdisplay       (GdkColormap *colormap);

Returns the display of a GdkColormap.

colormap : | a GdkColormap.
Returns : | an Xlib Display*.

gdk_x11_cursor_get_xcursor ()

Cursor              gdk_x11_cursor_get_xcursor          (GdkCursor *cursor);

Returns the X cursor belonging to a GdkCursor.

cursor : | a GdkCursor.
Returns : | an Xlib Cursor.

gdk_x11_cursor_get_xdisplay ()

Display*            gdk_x11_cursor_get_xdisplay         (GdkCursor *cursor);

Returns the display of a GdkCursor.

cursor : | a GdkCursor.
Returns : | an Xlib Display*.

gdk_x11_display_get_xdisplay ()

Display*            gdk_x11_display_get_xdisplay        (GdkDisplay *display);

Returns the X display of a GdkDisplay.

display : | a GdkDisplay
Returns : | an X display.

Since 2.2

gdk_x11_display_grab ()

void                gdk_x11_display_grab                (GdkDisplay *display);

Call XGrabServer() on display. To ungrab the display again, use gdk_x11_display_ungrab().

gdk_x11_display_grab()/gdk_x11_display_ungrab() calls can be nested.

display : a GdkDisplay

Since 2.2

gdk_x11_display_ungrab ()

void                gdk_x11_display_ungrab              (GdkDisplay *display);

Ungrab display after it has been grabbed with gdk_x11_display_grab().

display : a GdkDisplay

Since 2.2

gdk_x11_display_set_cursor_theme ()

void                gdk_x11_display_set_cursor_theme    (GdkDisplay *display,
                                                         const gchar *theme,
                                                         const gint size);

Sets the cursor theme from which the images for cursor should be taken.

If the windowing system supports it, existing cursors created with gdk_cursor_new(), gdk_cursor_new_for_display() and gdk_cursor_new_for_name() are updated to reflect the theme change. Custom cursors constructed with gdk_cursor_new_from_pixmap() or gdk_cursor_new_from_pixbuf() will have to be handled by the application (GTK+ applications can learn about cursor theme changes by listening for change notification for the corresponding GtkSetting).

display : | a GdkDisplay
theme : | the name of the cursor theme to use, or NULL to unset a previously set value
size : | the cursor size to use, or 0 to keep the previous size

Since 2.8

gdk_x11_register_standard_event_type ()

void                gdk_x11_register_standard_event_type
                                                        (GdkDisplay *display,
                                                         gint event_base,
                                                         gint n_events);

Registers interest in receiving extension events with type codes between event_base and event_base + n_events - 1. The registered events must have the window field in the same place as core X events (this is not the case for e.g. XKB extension events).

If an event type is registered, events of this type will go through global and window-specific filters (see gdk_window_add_filter()). Unregistered events will only go through global filters. GDK may register the events of some X extensions on its own.

This function should only be needed in unusual circumstances, e.g. when filtering XInput extension events on the root window.

display : | a GdkDisplay
event_base : | first event type code to register
n_events : | number of event type codes to register

Since 2.4

gdk_x11_drawable_get_xdisplay ()

Display*            gdk_x11_drawable_get_xdisplay       (GdkDrawable *drawable);

Returns the display of a GdkDrawable.

drawable : | a GdkDrawable.
Returns : | an Xlib Display*.

gdk_x11_drawable_get_xid ()

XID                 gdk_x11_drawable_get_xid            (GdkDrawable *drawable);

Returns the X resource (window or pixmap) belonging to a GdkDrawable.

drawable : | a GdkDrawable.
Returns : | the ID of drawable's X resource.

gdk_x11_font_get_name ()

const char*         gdk_x11_font_get_name               (GdkFont *font);

Warning

gdk_x11_font_get_name is deprecated and should not be used in newly-written code.

Return the X Logical Font Description (for font->type == GDK_FONT_FONT) or comma separated list of XLFDs (for font->type == GDK_FONT_FONTSET) that was used to load the font. If the same font was loaded via multiple names, which name is returned is undefined.

font : | a GdkFont.
Returns : | the name of the font. This string is owned by GDK and must not be modified or freed.

gdk_x11_font_get_xdisplay ()

Display*            gdk_x11_font_get_xdisplay           (GdkFont *font);

Warning

gdk_x11_font_get_xdisplay is deprecated and should not be used in newly-written code.

Returns the display of a GdkFont.

font : | a GdkFont.
Returns : | an Xlib Display*.

gdk_x11_font_get_xfont ()

gpointer            gdk_x11_font_get_xfont              (GdkFont *font);

Warning

gdk_x11_font_get_xfont is deprecated and should not be used in newly-written code.

Returns the X font belonging to a GdkFont.

font : | a GdkFont.
Returns : | an Xlib XFontStruct* or an XFontSet.

gdk_x11_gc_get_xdisplay ()

Display*            gdk_x11_gc_get_xdisplay             (GdkGC *gc);

Returns the display of a GdkGC.

gc : | a GdkGC.
Returns : | an Xlib Display*.

gdk_x11_gc_get_xgc ()

GC                  gdk_x11_gc_get_xgc                  (GdkGC *gc);

Returns the X GC of a GdkGC.

gc : | a GdkGC.
Returns : | an Xlib GC.

gdk_x11_get_default_root_xwindow ()

Window              gdk_x11_get_default_root_xwindow    (void);

Gets the root window of the default screen (see gdk_x11_get_default_screen()).

Returns : an Xlib Window.

gdk_x11_get_default_screen ()

gint                gdk_x11_get_default_screen          (void);

Gets the default GTK+ screen number.

Returns : returns the screen number specified by the --display command line option or the DISPLAY environment variable when gdk_init() calls XOpenDisplay().

gdk_x11_get_default_xdisplay ()

Display*            gdk_x11_get_default_xdisplay        (void);

Gets the default GTK+ display.

Returns : the Xlib Display* for the display specified in the --display command line option or the DISPLAY environment variable.

gdk_x11_grab_server ()

void                gdk_x11_grab_server                 (void);

Call gdk_x11_display_grab() on the default display. To ungrab the server again, use gdk_x11_ungrab_server().

gdk_x11_grab_server()/gdk_x11_ungrab_server() calls can be nested.

gdk_x11_image_get_xdisplay ()

Display*            gdk_x11_image_get_xdisplay          (GdkImage *image);

Returns the display of a GdkImage.

image : | a GdkImage.
Returns : | an Xlib Display*.

gdk_x11_image_get_ximage ()

XImage*             gdk_x11_image_get_ximage            (GdkImage *image);

Returns the X image belonging to a GdkImage.

image : | a GdkImage.
Returns : | an XImage*.

gdk_x11_screen_get_screen_number ()

int                 gdk_x11_screen_get_screen_number    (GdkScreen *screen);

Returns the index of a GdkScreen.

screen : | a GdkScreen.
Returns : | the position of screen among the screens of its display.

Since 2.2

gdk_x11_screen_get_xscreen ()

Screen*             gdk_x11_screen_get_xscreen          (GdkScreen *screen);

Returns the screen of a GdkScreen.

screen : | a GdkScreen.
Returns : | an Xlib Screen*

Since 2.2

gdk_x11_ungrab_server ()

void                gdk_x11_ungrab_server               (void);

Ungrab the default display after it has been grabbed with gdk_x11_grab_server().

gdk_x11_visual_get_xvisual ()

Visual*             gdk_x11_visual_get_xvisual          (GdkVisual *visual);

Returns the X visual belonging to a GdkVisual.

visual : | a GdkVisual.
Returns : | an Xlib Visual*.

gdk_x11_atom_to_xatom ()

Atom                gdk_x11_atom_to_xatom               (GdkAtom atom);

Converts from a GdkAtom to the X atom for the default GDK display with the same string value.

atom : | A GdkAtom
Returns : | the X atom corresponding to atom.

gdk_x11_atom_to_xatom_for_display ()

Atom                gdk_x11_atom_to_xatom_for_display   (GdkDisplay *display,
                                                         GdkAtom atom);

Converts from a GdkAtom to the X atom for a GdkDisplay with the same string value.

display : | A GdkDisplay
atom : | A GdkAtom
Returns : | the X atom corresponding to atom.

Since 2.2

gdk_x11_xatom_to_atom ()

GdkAtom             gdk_x11_xatom_to_atom               (Atom xatom);

Convert from an X atom for the default display to the corresponding GdkAtom.

xatom : | an X atom for the default GDK display
Returns : | the corresponding GdkAtom.

gdk_x11_xatom_to_atom_for_display ()

GdkAtom             gdk_x11_xatom_to_atom_for_display   (GdkDisplay *display,
                                                         Atom xatom);

Convert from an X atom for a GdkDisplay to the corresponding GdkAtom.

display : | A GdkDisplay
xatom : | an X atom
Returns : | the corresponding GdkAtom.

Since 2.2

gdk_x11_get_xatom_by_name ()

Atom                gdk_x11_get_xatom_by_name           (const gchar *atom_name);

Returns the X atom for GDK's default display corresponding to atom_name. This function caches the result, so if called repeatedly it is much faster than XInternAtom(), which is a round trip to the server each time.

atom_name : | a string
Returns : | a X atom for GDK's default display.

gdk_x11_get_xatom_by_name_for_display ()

Atom                gdk_x11_get_xatom_by_name_for_display
                                                        (GdkDisplay *display,
                                                         const gchar *atom_name);

Returns the X atom for a GdkDisplay corresponding to atom_name. This function caches the result, so if called repeatedly it is much faster than XInternAtom(), which is a round trip to the server each time.

display : | a GdkDisplay
atom_name : | a string
Returns : | a X atom for a GdkDisplay

Since 2.2

gdk_x11_get_xatom_name ()

const gchar*        gdk_x11_get_xatom_name              (Atom xatom);

Returns the name of an X atom for GDK's default display. This function is meant mainly for debugging, so for convenience, unlike XAtomName() and gdk_atom_name(), the result doesn't need to be freed. Also, this function will never return NULL, even if xatom is invalid.

xatom : | an X atom for GDK's default display
Returns : | name of the X atom; this string is owned by GTK+, so it shouldn't be modifed or freed.

gdk_x11_get_xatom_name_for_display ()

const gchar*        gdk_x11_get_xatom_name_for_display  (GdkDisplay *display,
                                                         Atom xatom);

Returns the name of an X atom for its display. This function is meant mainly for debugging, so for convenience, unlike XAtomName() and gdk_atom_name(), the result doesn't need to be freed.

display : | the GdkDisplay where xatom is defined
xatom : | an X atom
Returns : | name of the X atom; this string is owned by GDK, so it shouldn't be modifed or freed.

Since 2.2


GdkDisplay

GdkDisplay — Controls the keyboard/mouse pointer grabs and a set of GdkScreens

Synopsis

#include <gdk/gdk.h>

                    GdkDisplay;
GdkDisplay*         gdk_display_open                    (const gchar *display_name);
GdkDisplay*         gdk_display_get_default             (void);
const gchar*        gdk_display_get_name                (GdkDisplay *display);
gint                gdk_display_get_n_screens           (GdkDisplay *display);
GdkScreen*          gdk_display_get_screen              (GdkDisplay *display,
                                                         gint screen_num);
GdkScreen*          gdk_display_get_default_screen      (GdkDisplay *display);
void                gdk_display_pointer_ungrab          (GdkDisplay *display,
                                                         guint32 time_);
void                gdk_display_keyboard_ungrab         (GdkDisplay *display,
                                                         guint32 time_);
gboolean            gdk_display_pointer_is_grabbed      (GdkDisplay *display);
void                gdk_display_beep                    (GdkDisplay *display);
void                gdk_display_sync                    (GdkDisplay *display);
void                gdk_display_flush                   (GdkDisplay *display);
void                gdk_display_close                   (GdkDisplay *display);
GList*              gdk_display_list_devices            (GdkDisplay *display);
GdkEvent*           gdk_display_get_event               (GdkDisplay *display);
GdkEvent*           gdk_display_peek_event              (GdkDisplay *display);
void                gdk_display_put_event               (GdkDisplay *display,
                                                         GdkEvent *event);
void                gdk_display_add_client_message_filter
                                                        (GdkDisplay *display,
                                                         GdkAtom message_type,
                                                         GdkFilterFunc func,
                                                         gpointer data);
void                gdk_display_set_double_click_time   (GdkDisplay *display,
                                                         guint msec);
void                gdk_display_set_double_click_distance
                                                        (GdkDisplay *display,
                                                         guint distance);
void                gdk_display_get_pointer             (GdkDisplay *display,
                                                         GdkScreen **screen,
                                                         gint *x,
                                                         gint *y,
                                                         GdkModifierType *mask);
GdkWindow*          gdk_display_get_window_at_pointer   (GdkDisplay *display,
                                                         gint *win_x,
                                                         gint *win_y);
                    GdkDisplayPointerHooks;
GdkDisplayPointerHooks* gdk_display_set_pointer_hooks   (GdkDisplay *display,
                                                         const GdkDisplayPointerHooks *new_hooks);
void                gdk_display_warp_pointer            (GdkDisplay *display,
                                                         GdkScreen *screen,
                                                         gint x,
                                                         gint y);
gboolean            gdk_display_supports_cursor_color   (GdkDisplay *display);
gboolean            gdk_display_supports_cursor_alpha   (GdkDisplay *display);
guint               gdk_display_get_default_cursor_size (GdkDisplay *display);
void                gdk_display_get_maximal_cursor_size (GdkDisplay *display,
                                                         guint *width,
                                                         guint *height);
GdkWindow*          gdk_display_get_default_group       (GdkDisplay *display);
gboolean            gdk_display_supports_selection_notification
                                                        (GdkDisplay *display);
gboolean            gdk_display_request_selection_notification
                                                        (GdkDisplay *display,
                                                         GdkAtom selection);
gboolean            gdk_display_supports_clipboard_persistence
                                                        (GdkDisplay *display);
void                gdk_display_store_clipboard         (GdkDisplay *display,
                                                         GdkWindow *clipboard_window,
                                                         guint32 time_,
                                                         GdkAtom *targets,
                                                         gint n_targets);
gboolean            gdk_display_supports_shapes         (GdkDisplay *display);
gboolean            gdk_display_supports_input_shapes   (GdkDisplay *display);

Object Hierarchy

  GObject
   +----GdkDisplay

Signals

  "closed"                                         : Run Last

Description

GdkDisplay objects purpose are two fold:

  • To grab/ungrab keyboard focus and mouse pointer

  • To manage and provide information about the GdkScreen(s) available for this GdkDisplay

GdkDisplay objects are the GDK representation of the X Display which can be described as a workstation consisting of a keyboard a pointing device (such as a mouse) and one or more screens. It is used to open and keep track of various GdkScreen objects currently instanciated by the application. It is also used to grab and release the keyboard and the mouse pointer.

Details

GdkDisplay

typedef struct _GdkDisplay GdkDisplay;

The GdkDisplay struct is the GDK representation of an X display. All its fields are private and should not be accessed directly.

Since 2.2

gdk_display_open ()

GdkDisplay*         gdk_display_open                    (const gchar *display_name);

Opens a display.

display_name : | the name of the display to open
Returns : | a GdkDisplay, or NULL if the display could not be opened.

Since 2.2

gdk_display_get_default ()

GdkDisplay*         gdk_display_get_default             (void);

Gets the default GdkDisplay. This is a convenience function for:

  gdk_display_manager_get_default_display (gdk_display_manager_get ())

Returns : a GdkDisplay, or NULL if there is no default display.

Since 2.2

gdk_display_get_name ()

const gchar*        gdk_display_get_name                (GdkDisplay *display);

Gets the name of the display.

display : | a GdkDisplay
Returns : | a string representing the display name. This string is owned by GDK and should not be modified or freed.

Since 2.2

gdk_display_get_n_screens ()

gint                gdk_display_get_n_screens           (GdkDisplay *display);

Gets the number of screen managed by the display.

display : | a GdkDisplay
Returns : | number of screens.

Since 2.2

gdk_display_get_screen ()

GdkScreen*          gdk_display_get_screen              (GdkDisplay *display,
                                                         gint screen_num);

Returns a screen object for one of the screens of the display.

display : | a GdkDisplay
screen_num : | the screen number
Returns : | the GdkScreen object

Since 2.2

gdk_display_get_default_screen ()

GdkScreen*          gdk_display_get_default_screen      (GdkDisplay *display);

Get the default GdkScreen for display.

display : | a GdkDisplay
Returns : | the default GdkScreen object for display

Since 2.2

gdk_display_pointer_ungrab ()

void                gdk_display_pointer_ungrab          (GdkDisplay *display,
                                                         guint32 time_);

Release any pointer grab.

display : | a GdkDisplay.
time_ : | a timestap (e.g. GDK_CURRENT_TIME).

Since 2.2

gdk_display_keyboard_ungrab ()

void                gdk_display_keyboard_ungrab         (GdkDisplay *display,
                                                         guint32 time_);

Release any keyboard grab

display : | a GdkDisplay.
time_ : | a timestap (e.g GDK_CURRENT_TIME).

Since 2.2

gdk_display_pointer_is_grabbed ()

gboolean            gdk_display_pointer_is_grabbed      (GdkDisplay *display);

Test if the pointer is grabbed.

display : | a GdkDisplay
Returns : | TRUE if an active X pointer grab is in effect

Since 2.2

gdk_display_beep ()

void                gdk_display_beep                    (GdkDisplay *display);

Emits a short beep on display

display : a GdkDisplay

Since 2.2

gdk_display_sync ()

void                gdk_display_sync                    (GdkDisplay *display);

Flushes any requests queued for the windowing system and waits until all requests have been handled. This is often used for making sure that the display is synchronized with the current state of the program. Calling gdk_display_sync() before gdk_error_trap_pop() makes sure that any errors generated from earlier requests are handled before the error trap is removed.

This is most useful for X11. On windowing systems where requests are handled synchronously, this function will do nothing.

display : a GdkDisplay

Since 2.2

gdk_display_flush ()

void                gdk_display_flush                   (GdkDisplay *display);

Flushes any requests queued for the windowing system; this happens automatically when the main loop blocks waiting for new events, but if your application is drawing without returning control to the main loop, you may need to call this function explicitely. A common case where this function needs to be called is when an application is executing drawing commands from a thread other than the thread where the main loop is running.

This is most useful for X11. On windowing systems where requests are handled synchronously, this function will do nothing.

display : a GdkDisplay

Since 2.4

gdk_display_close ()

void                gdk_display_close                   (GdkDisplay *display);

Closes the connection to the windowing system for the given display, and cleans up associated resources.

display : a GdkDisplay

Since 2.2

gdk_display_list_devices ()

GList*              gdk_display_list_devices            (GdkDisplay *display);

Returns the list of available input devices attached to display. The list is statically allocated and should not be freed.

display : | a GdkDisplay
Returns : | a list of GdkDevice

Since 2.2

gdk_display_get_event ()

GdkEvent*           gdk_display_get_event               (GdkDisplay *display);

Gets the next GdkEvent to be processed for display, fetching events from the windowing system if necessary.

display : | a GdkDisplay
Returns : | the next GdkEvent to be processed, or NULL if no events are pending. The returned GdkEvent should be freed with gdk_event_free().

Since 2.2

gdk_display_peek_event ()

GdkEvent*           gdk_display_peek_event              (GdkDisplay *display);

Gets a copy of the first GdkEvent in the display's event queue, without removing the event from the queue. (Note that this function will not get more events from the windowing system. It only checks the events that have already been moved to the GDK event queue.)

display : | a GdkDisplay
Returns : | a copy of the first GdkEvent on the event queue, or NULL if no events are in the queue. The returned GdkEvent should be freed with gdk_event_free().

Since 2.2

gdk_display_put_event ()

void                gdk_display_put_event               (GdkDisplay *display,
                                                         GdkEvent *event);

Appends a copy of the given event onto the front of the event queue for display.

display : | a GdkDisplay
event : | a GdkEvent.

Since 2.2

gdk_display_add_client_message_filter ()

void                gdk_display_add_client_message_filter
                                                        (GdkDisplay *display,
                                                         GdkAtom message_type,
                                                         GdkFilterFunc func,
                                                         gpointer data);

Adds a filter to be called when X ClientMessage events are received.

display : | a GdkDisplay for which this message filter applies
message_type : | the type of ClientMessage events to receive. This will be checked against the message_type field of the XClientMessage event struct.
func : | the function to call to process the event.
data : | user data to pass to func.

Since 2.2

gdk_display_set_double_click_time ()

void                gdk_display_set_double_click_time   (GdkDisplay *display,
                                                         guint msec);

Sets the double click time (two clicks within this time interval count as a double click and result in a GDK_2BUTTON_PRESS event). Applications should not set this, it is a global user-configured setting.

display : | a GdkDisplay
msec : | double click time in milliseconds (thousandths of a second)

Since 2.2

gdk_display_set_double_click_distance ()

void                gdk_display_set_double_click_distance
                                                        (GdkDisplay *display,
                                                         guint distance);

Sets the double click distance (two clicks within this distance count as a double click and result in a GDK_2BUTTON_PRESS event). See also gdk_display_set_double_click_time(). Applications should not set this, it is a global user-configured setting.

display : | a GdkDisplay
distance : | distance in pixels

Since 2.4

gdk_display_get_pointer ()

void                gdk_display_get_pointer             (GdkDisplay *display,
                                                         GdkScreen **screen,
                                                         gint *x,
                                                         gint *y,
                                                         GdkModifierType *mask);

Gets the current location of the pointer and the current modifier mask for a given display.

display : | a GdkDisplay
screen : | location to store the screen that the cursor is on, or NULL.
x : | location to store root window X coordinate of pointer, or NULL.
y : | location to store root window Y coordinate of pointer, or NULL.
mask : | location to store current modifier mask, or NULL

Since 2.2

gdk_display_get_window_at_pointer ()

GdkWindow*          gdk_display_get_window_at_pointer   (GdkDisplay *display,
                                                         gint *win_x,
                                                         gint *win_y);

Obtains the window underneath the mouse pointer, returning the location of that window in win_x, win_y for screen. Returns NULL if the window under the mouse pointer is not known to GDK (for example, belongs to another application).

display : | a GdkDisplay
win_x : | return location for origin of the window under the pointer
win_y : | return location for origin of the window under the pointer
Returns : | the window under the mouse pointer, or NULL

Since 2.2

GdkDisplayPointerHooks

typedef struct {
  void (*get_pointer)              (GdkDisplay      *display,
                    GdkScreen      **screen,
                    gint            *x,
                    gint            *y,
                    GdkModifierType *mask);
  GdkWindow* (*window_get_pointer) (GdkDisplay      *display,
                    GdkWindow       *window,
                    gint            *x,
                    gint            *y,
                    GdkModifierType *mask);
  GdkWindow* (*window_at_pointer)  (GdkDisplay      *display,
                    gint            *win_x,
                    gint            *win_y);
} GdkDisplayPointerHooks;

A table of pointers to functions for getting quantities related to the current pointer position. Each GdkDisplay has a table of this type, which can be set using gdk_display_set_pointer_hooks().

This is only useful for such low-level tools as an event recorder. Applications should never have any reason to use this facility

get_pointer () | Obtains the current pointer position and modifier state. The position is given in coordinates relative to the window containing the pointer, which is returned in window.
window_get_pointer () | Obtains the window underneath the mouse pointer. Current pointer position and modifier state are returned in x, y and mask. The position is given in coordinates relative to window.
window_at_pointer () | Obtains the window underneath the mouse pointer, returning the location of that window in win_x, win_y. Returns NULL if the window under the mouse pointer is not known to GDK (for example, belongs to another application).

Since 2.2

gdk_display_set_pointer_hooks ()

GdkDisplayPointerHooks* gdk_display_set_pointer_hooks   (GdkDisplay *display,
                                                         const GdkDisplayPointerHooks *new_hooks);

This function allows for hooking into the operation of getting the current location of the pointer on a particular display. This is only useful for such low-level tools as an event recorder. Applications should never have any reason to use this facility.

display : | a GdkDisplay
new_hooks : | a table of pointers to functions for getting quantities related to the current pointer position, or NULL to restore the default table.
Returns : | the previous pointer hook table

Since 2.2

gdk_display_warp_pointer ()

void                gdk_display_warp_pointer            (GdkDisplay *display,
                                                         GdkScreen *screen,
                                                         gint x,
                                                         gint y);

Warps the pointer of display to the point x,y on the screen screen, unless the pointer is confined to a window by a grab, in which case it will be moved as far as allowed by the grab. Warping the pointer creates events as if the user had moved the mouse instantaneously to the destination.

Note that the pointer should normally be under the control of the user. This function was added to cover some rare use cases like keyboard navigation support for the color picker in the GtkColorSelectionDialog.

display : | a GdkDisplay
screen : | the screen of display to warp the pointer to
x : | the x coordinate of the destination
y : | the y coordinate of the destination

Since 2.8

gdk_display_supports_cursor_color ()

gboolean            gdk_display_supports_cursor_color   (GdkDisplay *display);

Returns TRUE if multicolored cursors are supported on display. Otherwise, cursors have only a forground and a background color.

display : | a GdkDisplay
Returns : | whether cursors can have multiple colors.

Since 2.4

gdk_display_supports_cursor_alpha ()

gboolean            gdk_display_supports_cursor_alpha   (GdkDisplay *display);

Returns TRUE if cursors can use an 8bit alpha channel on display. Otherwise, cursors are restricted to bilevel alpha (i.e. a mask).

display : | a GdkDisplay
Returns : | whether cursors can have alpha channels.

Since 2.4

gdk_display_get_default_cursor_size ()

guint               gdk_display_get_default_cursor_size (GdkDisplay *display);

Returns the default size to use for cursors on display.

display : | a GdkDisplay
Returns : | the default cursor size.

Since 2.4

gdk_display_get_maximal_cursor_size ()

void                gdk_display_get_maximal_cursor_size (GdkDisplay *display,
                                                         guint *width,
                                                         guint *height);

Gets the maximal size to use for cursors on display.

display : | a GdkDisplay
width : | the return location for the maximal cursor width
height : | the return location for the maximal cursor height

Since 2.4

gdk_display_get_default_group ()

GdkWindow*          gdk_display_get_default_group       (GdkDisplay *display);

Returns the default group leader window for all toplevel windows on display. This window is implicitly created by GDK. See gdk_window_set_group().

display : | a GdkDisplay
Returns : | The default group leader window for display

Since 2.4

gdk_display_supports_selection_notification ()

gboolean            gdk_display_supports_selection_notification
                                                        (GdkDisplay *display);

Returns whether GdkEventOwnerChange events will be sent when the owner of a selection changes.

display : | a GdkDisplay
Returns : | whether GdkEventOwnerChange events will be sent.

Since 2.6

gdk_display_request_selection_notification ()

gboolean            gdk_display_request_selection_notification
                                                        (GdkDisplay *display,
                                                         GdkAtom selection);

Request GdkEventOwnerChange events for ownership changes of the selection named by the given atom.

display : | a GdkDisplay
selection : | the GdkAtom naming the selection for which ownership change notification is requested
Returns : | whether GdkEventOwnerChange events will be sent.

Since 2.6

gdk_display_supports_clipboard_persistence ()

gboolean            gdk_display_supports_clipboard_persistence
                                                        (GdkDisplay *display);

Returns whether the speicifed display supports clipboard persistance; i.e. if it's possible to store the clipboard data after an application has quit. On X11 this checks if a clipboard daemon is running.

display : | a GdkDisplay
Returns : | TRUE if the display supports clipboard persistance.

Since 2.6

gdk_display_store_clipboard ()

void                gdk_display_store_clipboard         (GdkDisplay *display,
                                                         GdkWindow *clipboard_window,
                                                         guint32 time_,
                                                         GdkAtom *targets,
                                                         gint n_targets);

Issues a request to the clipboard manager to store the clipboard data. On X11, this is a special program that works according to the freedesktop clipboard specification, available at http://www.freedesktop.org/Standards/clipboard-manager-spec.

display : | a GdkDisplay
clipboard_window : | a GdkWindow belonging to the clipboard owner
time_ : | a timestamp
targets : | an array of targets that should be saved, or NULL if all available targets should be saved.
n_targets : | length of the targets array

Since 2.6

gdk_display_supports_shapes ()

gboolean            gdk_display_supports_shapes         (GdkDisplay *display);

Returns TRUE if gdk_window_shape_combine_mask() can be used to create shaped windows on display.

display : | a GdkDisplay
Returns : | TRUE if shaped windows are supported

Since 2.10

gdk_display_supports_input_shapes ()

gboolean            gdk_display_supports_input_shapes   (GdkDisplay *display);

Returns TRUE if gdk_window_input_shape_combine_mask() can be used to modify the input shape of windows on display.

display : | a GdkDisplay
Returns : | TRUE if windows with modified input shape are supported

Since 2.10

Signal Details

The "closed" signal

void                user_function                      (GdkDisplay *display,
                                                        gboolean    is_error,
                                                        gpointer    user_data)      : Run Last

The ::closed signal is emitted when the connection to the windowing system for display is closed.

display : | the object on which the signal is emitted
is_error : | TRUE if the display was closed due to an error
user_data : | user data set when the signal handler was connected.

Since 2.2


GdkDisplayManager

GdkDisplayManager — Maintains a list of all open GdkDisplays

Synopsis

#include <gdk/gdk.h>

                    GdkDisplayManager;
GdkDisplayManager*  gdk_display_manager_get             (void);
GdkDisplay*         gdk_display_manager_get_default_display
                                                        (GdkDisplayManager *display_manager);
void                gdk_display_manager_set_default_display
                                                        (GdkDisplayManager *display_manager,
                                                         GdkDisplay *display);
GSList*             gdk_display_manager_list_displays   (GdkDisplayManager *display_manager);
GdkDevice*          gdk_display_get_core_pointer        (GdkDisplay *display);

Object Hierarchy

  GObject
   +----GdkDisplayManager

Properties

  "default-display"          GdkDisplay            : Read / Write

Signals

  "display-opened"                                 : Run Last

Description

The purpose of the GdkDisplayManager singleton object is to offer notification when displays appear or disappear or the default display changes.

Details

GdkDisplayManager

typedef struct _GdkDisplayManager GdkDisplayManager;

The GdkDisplayManager struct has no interesting fields.

Since 2.2

gdk_display_manager_get ()

GdkDisplayManager*  gdk_display_manager_get             (void);

Returns the global GdkDisplayManager singleton; gdk_parse_pargs(), gdk_init(), or gdk_init_check() must have been called first.

Returns : the singleton GdkDisplayManager object.

Since 2.2

gdk_display_manager_get_default_display ()

GdkDisplay*         gdk_display_manager_get_default_display
                                                        (GdkDisplayManager *display_manager);

Gets the default GdkDisplay.

display_manager : | a GdkDisplayManager
Returns : | a GdkDisplay, or NULL if there is no default display.

Since 2.2

gdk_display_manager_set_default_display ()

void                gdk_display_manager_set_default_display
                                                        (GdkDisplayManager *display_manager,
                                                         GdkDisplay *display);

Sets display as the default display.

display_manager : | a GdkDisplayManager
display : | a GdkDisplay

Since 2.2

gdk_display_manager_list_displays ()

GSList*             gdk_display_manager_list_displays   (GdkDisplayManager *display_manager);

List all currently open displays.

display_manager : | a GdkDisplayManager
Returns : | a newly allocated GSList of GdkDisplay objects. Free this list with g_slist_free() when you are done with it.

Since 2.2

gdk_display_get_core_pointer ()

GdkDevice*          gdk_display_get_core_pointer        (GdkDisplay *display);

Returns the core pointer device for the given display

display : | a GdkDisplay
Returns : | the core pointer device; this is owned by the display and should not be freed.

Since 2.2

Property Details

The "default-display" property

  "default-display"          GdkDisplay            : Read / Write

The default display for GDK.

Signal Details

The "display-opened" signal

void                user_function                      (GdkDisplayManager *display_manager,
                                                        GdkDisplay        *display,
                                                        gpointer           user_data)            : Run Last

The ::display_opened signal is emitted when a display is opened.

display_manager : | the object on which the signal is emitted
display : | the opened display
user_data : | user data set when the signal handler was connected.

Since 2.2


GdkScreen

GdkScreen — Object representing a physical screen

Synopsis

#include <gdk/gdk.h>

                    GdkScreen;
GdkScreen*          gdk_screen_get_default              (void);
GdkColormap*        gdk_screen_get_default_colormap     (GdkScreen *screen);
void                gdk_screen_set_default_colormap     (GdkScreen *screen,
                                                         GdkColormap *colormap);
GdkColormap*        gdk_screen_get_system_colormap      (GdkScreen *screen);
GdkVisual*          gdk_screen_get_system_visual        (GdkScreen *screen);
GdkColormap*        gdk_screen_get_rgb_colormap         (GdkScreen *screen);
GdkVisual*          gdk_screen_get_rgb_visual           (GdkScreen *screen);
GdkColormap*        gdk_screen_get_rgba_colormap        (GdkScreen *screen);
GdkVisual*          gdk_screen_get_rgba_visual          (GdkScreen *screen);
gboolean            gdk_screen_is_composited            (GdkScreen *screen);
GdkWindow*          gdk_screen_get_root_window          (GdkScreen *screen);
GdkDisplay*         gdk_screen_get_display              (GdkScreen *screen);
gint                gdk_screen_get_number               (GdkScreen *screen);
gint                gdk_screen_get_width                (GdkScreen *screen);
gint                gdk_screen_get_height               (GdkScreen *screen);
gint                gdk_screen_get_width_mm             (GdkScreen *screen);
gint                gdk_screen_get_height_mm            (GdkScreen *screen);
GList*              gdk_screen_list_visuals             (GdkScreen *screen);
GList*              gdk_screen_get_toplevel_windows     (GdkScreen *screen);
gchar*              gdk_screen_make_display_name        (GdkScreen *screen);
gint                gdk_screen_get_n_monitors           (GdkScreen *screen);
void                gdk_screen_get_monitor_geometry     (GdkScreen *screen,
                                                         gint monitor_num,
                                                         GdkRectangle *dest);
gint                gdk_screen_get_monitor_at_point     (GdkScreen *screen,
                                                         gint x,
                                                         gint y);
gint                gdk_screen_get_monitor_at_window    (GdkScreen *screen,
                                                         GdkWindow *window);
void                gdk_screen_broadcast_client_message (GdkScreen *screen,
                                                         GdkEvent *event);
gboolean            gdk_screen_get_setting              (GdkScreen *screen,
                                                         const gchar *name,
                                                         GValue *value);
const cairo_font_options_t* gdk_screen_get_font_options (GdkScreen *screen);
void                gdk_screen_set_font_options         (GdkScreen *screen,
                                                         const cairo_font_options_t *options);
gdouble             gdk_screen_get_resolution           (GdkScreen *screen);
void                gdk_screen_set_resolution           (GdkScreen *screen,
                                                         gdouble dpi);
GdkWindow*          gdk_screen_get_active_window        (GdkScreen *screen);
GList*              gdk_screen_get_window_stack         (GdkScreen *screen);

gboolean            gdk_spawn_on_screen                 (GdkScreen *screen,
                                                         const gchar *working_directory,
                                                         gchar **argv,
                                                         gchar **envp,
                                                         GSpawnFlags flags,
                                                         GSpawnChildSetupFunc child_setup,
                                                         gpointer user_data,
                                                         gint *child_pid,
                                                         GError **error);
gboolean            gdk_spawn_on_screen_with_pipes      (GdkScreen *screen,
                                                         const gchar *working_directory,
                                                         gchar **argv,
                                                         gchar **envp,
                                                         GSpawnFlags flags,
                                                         GSpawnChildSetupFunc child_setup,
                                                         gpointer user_data,
                                                         gint *child_pid,
                                                         gint *standard_input,
                                                         gint *standard_output,
                                                         gint *standard_error,
                                                         GError **error);
gboolean            gdk_spawn_command_line_on_screen    (GdkScreen *screen,
                                                         const gchar *command_line,
                                                         GError **error);

Object Hierarchy

  GObject
   +----GdkScreen

Properties

  "font-options"             gpointer              : Read / Write
  "resolution"               gdouble               : Read / Write

Signals

  "composited-changed"                             : Run Last
  "size-changed"                                   : Run Last

Description

GdkScreen objects are the GDK representation of a physical screen. It is used throughout GDK and GTK+ to specify which screen the top level windows are to be displayed on. It is also used to query the screen specification and default settings such as the default colormap (gdk_screen_get_default_colormap()), the screen width (gdk_screen_get_width()), etc.

Note that a screen may consist of multiple monitors which are merged to form a large screen area.

Details

GdkScreen

typedef struct _GdkScreen GdkScreen;

This is a currently just a placeholder typedef for the first argument of the window_at_pointer function in GdkPointerHooks. It will be used when GDK gets multihead support.

Since 2.2

gdk_screen_get_default ()

GdkScreen*          gdk_screen_get_default              (void);

Gets the default screen for the default display. (See gdk_display_get_default()).

Returns : a GdkScreen, or NULL if there is no default display.

Since 2.2

gdk_screen_get_default_colormap ()

GdkColormap*        gdk_screen_get_default_colormap     (GdkScreen *screen);

Gets the default colormap for screen.

screen : | a GdkScreen
Returns : | the default GdkColormap.

Since 2.2

gdk_screen_set_default_colormap ()

void                gdk_screen_set_default_colormap     (GdkScreen *screen,
                                                         GdkColormap *colormap);

Sets the default colormap for screen.

screen : | a GdkScreen
colormap : | a GdkColormap

Since 2.2

gdk_screen_get_system_colormap ()

GdkColormap*        gdk_screen_get_system_colormap      (GdkScreen *screen);

Gets the system's default colormap for screen

screen : | a GdkScreen
Returns : | the default colormap for screen.

Since 2.2

gdk_screen_get_system_visual ()

GdkVisual*          gdk_screen_get_system_visual        (GdkScreen *screen);

Get the system's default visual for screen. This is the visual for the root window of the display. The return value should not be freed.

screen : | a GdkScreen.
Returns : | the system visual

Since 2.2

gdk_screen_get_rgb_colormap ()

GdkColormap*        gdk_screen_get_rgb_colormap         (GdkScreen *screen);

Gets the preferred colormap for rendering image data on screen. Not a very useful function; historically, GDK could only render RGB image data to one colormap and visual, but in the current version it can render to any colormap and visual. So there's no need to call this function.

screen : | a GdkScreen.
Returns : | the preferred colormap

Since 2.2

gdk_screen_get_rgb_visual ()

GdkVisual*          gdk_screen_get_rgb_visual           (GdkScreen *screen);

Gets a "preferred visual" chosen by GdkRGB for rendering image data on screen. In previous versions of GDK, this was the only visual GdkRGB could use for rendering. In current versions, it's simply the visual GdkRGB would have chosen as the optimal one in those previous versions. GdkRGB can now render to drawables with any visual.

screen : | a GdkScreen
Returns : | The GdkVisual chosen by GdkRGB.

Since 2.2

gdk_screen_get_rgba_colormap ()

GdkColormap*        gdk_screen_get_rgba_colormap        (GdkScreen *screen);

Gets a colormap to use for creating windows or pixmaps with an alpha channel. The windowing system on which GTK+ is running may not support this capability, in which case NULL will be returned. Even if a non-NULL value is returned, its possible that the window's alpha channel won't be honored when displaying the window on the screen: in particular, for X an appropriate windowing manager and compositing manager must be running to provide appropriate display.

screen : | a GdkScreen.
Returns : | a colormap to use for windows with an alpha channel or NULL if the capability is not available.

Since 2.8

gdk_screen_get_rgba_visual ()

GdkVisual*          gdk_screen_get_rgba_visual          (GdkScreen *screen);

Gets a visual to use for creating windows or pixmaps with an alpha channel. See the docs for gdk_screen_get_rgba_colormap() for caveats.

screen : | a GdkScreen
Returns : | a visual to use for windows with an alpha channel or NULL if the capability is not available.

Since 2.8

gdk_screen_is_composited ()

gboolean            gdk_screen_is_composited            (GdkScreen *screen);

Returns whether windows with an RGBA visual can reasonably be expected to have their alpha channel drawn correctly on the screen.

On X11 this function returns whether a compositing manager is compositing screen.

screen : | a GdkScreen
Returns : | Whether windows with RGBA visuals can reasonably be expected to have their alpha channels drawn correctly on the screen.

Since 2.10

gdk_screen_get_root_window ()

GdkWindow*          gdk_screen_get_root_window          (GdkScreen *screen);

Gets the root window of screen.

screen : | a GdkScreen
Returns : | the root window

Since 2.2

gdk_screen_get_display ()

GdkDisplay*         gdk_screen_get_display              (GdkScreen *screen);

Gets the display to which the screen belongs.

screen : | a GdkScreen
Returns : | the display to which screen belongs

Since 2.2

gdk_screen_get_number ()

gint                gdk_screen_get_number               (GdkScreen *screen);

Gets the index of screen among the screens in the display to which it belongs. (See gdk_screen_get_display())

screen : | a GdkScreen
Returns : | the index

Since 2.2

gdk_screen_get_width ()

gint                gdk_screen_get_width                (GdkScreen *screen);

Gets the width of screen in pixels

screen : | a GdkScreen
Returns : | the width of screen in pixels.

Since 2.2

gdk_screen_get_height ()

gint                gdk_screen_get_height               (GdkScreen *screen);

Gets the height of screen in pixels

screen : | a GdkScreen
Returns : | the height of screen in pixels.

Since 2.2

gdk_screen_get_width_mm ()

gint                gdk_screen_get_width_mm             (GdkScreen *screen);

Gets the width of screen in millimeters. Note that on some X servers this value will not be correct.

screen : | a GdkScreen
Returns : | the width of screen in millimeters.

Since 2.2

gdk_screen_get_height_mm ()

gint                gdk_screen_get_height_mm            (GdkScreen *screen);

Returns the height of screen in millimeters. Note that on some X servers this value will not be correct.

screen : | a GdkScreen
Returns : | the heigth of screen in millimeters.

Since 2.2

gdk_screen_list_visuals ()

GList*              gdk_screen_list_visuals             (GdkScreen *screen);

Lists the available visuals for the specified screen. A visual describes a hardware image data format. For example, a visual might support 24-bit color, or 8-bit color, and might expect pixels to be in a certain format.

Call g_list_free() on the return value when you're finished with it.

screen : | the relevant GdkScreen.
Returns : | a list of visuals; the list must be freed, but not its contents

Since 2.2

gdk_screen_get_toplevel_windows ()

GList*              gdk_screen_get_toplevel_windows     (GdkScreen *screen);

Obtains a list of all toplevel windows known to GDK on the screen screen. A toplevel window is a child of the root window (see gdk_get_default_root_window()).

The returned list should be freed with g_list_free(), but its elements need not be freed.

screen : | The GdkScreen where the toplevels are located.
Returns : | list of toplevel windows, free with g_list_free()

Since 2.2

gdk_screen_make_display_name ()

gchar*              gdk_screen_make_display_name        (GdkScreen *screen);

Determines the name to pass to gdk_display_open() to get a GdkDisplay with this screen as the default screen.

screen : | a GdkScreen
Returns : | a newly allocated string, free with g_free()

Since 2.2

gdk_screen_get_n_monitors ()

gint                gdk_screen_get_n_monitors           (GdkScreen *screen);

Returns the number of monitors which screen consists of.

screen : | a GdkScreen.
Returns : | number of monitors which screen consists of.

Since 2.2

gdk_screen_get_monitor_geometry ()

void                gdk_screen_get_monitor_geometry     (GdkScreen *screen,
                                                         gint monitor_num,
                                                         GdkRectangle *dest);

Retrieves the GdkRectangle representing the size and position of the individual monitor within the entire screen area.

Note that the size of the entire screen area can be retrieved via gdk_screen_get_width() and gdk_screen_get_height().

screen : | a GdkScreen.
monitor_num : | the monitor number.
dest : | a GdkRectangle to be filled with the monitor geometry

Since 2.2

gdk_screen_get_monitor_at_point ()

gint                gdk_screen_get_monitor_at_point     (GdkScreen *screen,
                                                         gint x,
                                                         gint y);

Returns the monitor number in which the point (x,y) is located.

screen : | a GdkScreen.
x : | the x coordinate in the virtual screen.
y : | the y coordinate in the virtual screen.
Returns : | the monitor number in which the point (x,y) lies, or a monitor close to (x,y) if the point is not in any monitor.

Since 2.2

gdk_screen_get_monitor_at_window ()

gint                gdk_screen_get_monitor_at_window    (GdkScreen *screen,
                                                         GdkWindow *window);

Returns the number of the monitor in which the largest area of the bounding rectangle of window resides.

screen : | a GdkScreen.
window : | a GdkWindow
Returns : | the monitor number in which most of window is located, or if window does not intersect any monitors, a monitor, close to window.

Since 2.2

gdk_screen_broadcast_client_message ()

void                gdk_screen_broadcast_client_message (GdkScreen *screen,
                                                         GdkEvent *event);

On X11, sends an X ClientMessage event to all toplevel windows on screen.

Toplevel windows are determined by checking for the WM_STATE property, as described in the Inter-Client Communication Conventions Manual (ICCCM). If no windows are found with the WM_STATE property set, the message is sent to all children of the root window.

On Windows, broadcasts a message registered with the name GDK_WIN32_CLIENT_MESSAGE to all top-level windows. The amount of data is limited to one long, i.e. four bytes.

screen : | the GdkScreen where the event will be broadcasted.
event : | the GdkEvent.

Since 2.2

gdk_screen_get_setting ()

gboolean            gdk_screen_get_setting              (GdkScreen *screen,
                                                         const gchar *name,
                                                         GValue *value);

Retrieves a desktop-wide setting such as double-click time for the GdkScreen screen.

FIXME needs a list of valid settings here, or a link to more information.

screen : | the GdkScreen where the setting is located
name : | the name of the setting
value : | location to store the value of the setting
Returns : | TRUE if the setting existed and a value was stored in value, FALSE otherwise.

Since 2.2

gdk_screen_get_font_options ()

const cairo_font_options_t* gdk_screen_get_font_options (GdkScreen *screen);

Gets any options previously set with gdk_screen_set_font_options().

screen : | a GdkScreen
Returns : | the current font options, or NULL if no default font options have been set.

Since 2.10

gdk_screen_set_font_options ()

void                gdk_screen_set_font_options         (GdkScreen *screen,
                                                         const cairo_font_options_t *options);

Sets the default font options for the screen. These options will be set on any PangoContext's newly created with gdk_pango_context_get_for_screen(). Changing the default set of font options does not affect contexts that have already been created.

screen : | a GdkScreen
options : | a cairo_font_options_t, or NULL to unset any previously set default font options.

Since 2.10

gdk_screen_get_resolution ()

gdouble             gdk_screen_get_resolution           (GdkScreen *screen);

Gets the resolution for font handling on the screen; see gdk_screen_set_resolution() for full details.

screen : | a GdkScreen
Returns : | the current resolution, or -1 if no resolution has been set.

Since 2.10

gdk_screen_set_resolution ()

void                gdk_screen_set_resolution           (GdkScreen *screen,
                                                         gdouble dpi);

Sets the resolution for font handling on the screen. This is a scale factor between points specified in a PangoFontDescription and cairo units. The default value is 96, meaning that a 10 point font will be 13 units high. (10 * 96. / 72. = 13.3).

screen : | a GdkScreen
dpi : | the resolution in "dots per inch". (Physical inches aren't actually involved; the terminology is conventional.)

Since 2.10

gdk_screen_get_active_window ()

GdkWindow*          gdk_screen_get_active_window        (GdkScreen *screen);

Returns the screen's currently active window.

On X11, this is done by inspecting the _NET_ACTIVE_WINDOW property on the root window, as described in the Extended Window Manager Hints. If there is no currently currently active window, or the window manager does not support the _NET_ACTIVE_WINDOW hint, this function returns NULL.

On other platforms, this function may return NULL, depending on whether it is implementable on that platform.

The returned window should be unrefed using g_object_unref() when no longer needed.

screen : | a GdkScreen
Returns : | the currently active window, or NULL.

Since 2.10

gdk_screen_get_window_stack ()

GList*              gdk_screen_get_window_stack         (GdkScreen *screen);

Returns a GList of GdkWindows representing the current window stack.

On X11, this is done by inspecting the _NET_CLIENT_LIST_STACKING property on the root window, as described in the Extended Window Manager Hints. If the window manager does not support the _NET_CLIENT_LIST_STACKING hint, this function returns NULL.

On other platforms, this function may return NULL, depending on whether it is implementable on that platform.

The returned list is newly allocated and owns references to the windows it contains, so it should be freed using g_list_free() and its windows unrefed using g_object_unref() when no longer needed.

screen : | a GdkScreen
Returns : | a list of GdkWindows for the current window stack, or NULL.

Since 2.10

gdk_spawn_on_screen ()

gboolean            gdk_spawn_on_screen                 (GdkScreen *screen,
                                                         const gchar *working_directory,
                                                         gchar **argv,
                                                         gchar **envp,
                                                         GSpawnFlags flags,
                                                         GSpawnChildSetupFunc child_setup,
                                                         gpointer user_data,
                                                         gint *child_pid,
                                                         GError **error);

Like g_spawn_async(), except the child process is spawned in such an environment that on calling gdk_display_open() it would be returned a GdkDisplay with screen as the default screen.

This is useful for applications which wish to launch an application on a specific screen.

screen : | a GdkScreen
working_directory : | child's current working directory, or NULL to inherit parent's
argv : | child's argument vector
envp : | child's environment, or NULL to inherit parent's
flags : | flags from GSpawnFlags
child_setup : | function to run in the child just before exec()
user_data : | user data for child_setup
child_pid : | return location for child process ID, or NULL
error : | return location for error
Returns : | TRUE on success, FALSE if error is set

Since 2.4

gdk_spawn_on_screen_with_pipes ()

gboolean            gdk_spawn_on_screen_with_pipes      (GdkScreen *screen,
                                                         const gchar *working_directory,
                                                         gchar **argv,
                                                         gchar **envp,
                                                         GSpawnFlags flags,
                                                         GSpawnChildSetupFunc child_setup,
                                                         gpointer user_data,
                                                         gint *child_pid,
                                                         gint *standard_input,
                                                         gint *standard_output,
                                                         gint *standard_error,
                                                         GError **error);

Like g_spawn_async_with_pipes(), except the child process is spawned in such an environment that on calling gdk_display_open() it would be returned a GdkDisplay with screen as the default screen.

This is useful for applications which wish to launch an application on a specific screen.

screen : | a GdkScreen
working_directory : | child's current working directory, or NULL to inherit parent's
argv : | child's argument vector
envp : | child's environment, or NULL to inherit parent's
flags : | flags from GSpawnFlags
child_setup : | function to run in the child just before exec()
user_data : | user data for child_setup
child_pid : | return location for child process ID, or NULL
standard_input : | return location for file descriptor to write to child's stdin, or NULL
standard_output : | return location for file descriptor to read child's stdout, or NULL
standard_error : | return location for file descriptor to read child's stderr, or NULL
error : | return location for error
Returns : | TRUE on success, FALSE if an error was set

Since 2.4

gdk_spawn_command_line_on_screen ()

gboolean            gdk_spawn_command_line_on_screen    (GdkScreen *screen,
                                                         const gchar *command_line,
                                                         GError **error);

Like g_spawn_command_line_async(), except the child process is spawned in such an environment that on calling gdk_display_open() it would be returned a GdkDisplay with screen as the default screen.

This is useful for applications which wish to launch an application on a specific screen.

screen : | a GdkScreen
command_line : | a command line
error : | return location for errors
Returns : | TRUE on success, FALSE if error is set.

Since 2.4

Property Details

The "font-options" property

  "font-options"             gpointer              : Read / Write

The default font options for the screen.

The "resolution" property

  "resolution"               gdouble               : Read / Write

The resolution for fonts on the screen.

Default value: -1

Signal Details

The "composited-changed" signal

void                user_function                      (GdkScreen *screen,
                                                        gpointer   user_data)      : Run Last

The ::composited_changed signal is emitted when the composited status of the screen changes

screen : | the object on which the signal is emitted
user_data : | user data set when the signal handler was connected.

Since 2.10

The "size-changed" signal

void                user_function                      (GdkScreen *screen,
                                                        gpointer   user_data)      : Run Last

The ::size_changed signal is emitted when the pixel width or height of a screen changes.

screen : | the object on which the signal is emitted
user_data : | user data set when the signal handler was connected.

Since 2.2


Index

G

GdkAtom, GdkAtom
GdkAxisUse, enum GdkAxisUse
GdkBitmap, struct GdkBitmap
GdkByteOrder, enum GdkByteOrder
GdkCapStyle, enum GdkCapStyle
GdkColor, GdkColor
GdkColormap, GdkColormap
GdkCrossingMode, enum GdkCrossingMode
GdkCursor, GdkCursor
GdkCursorType, enum GdkCursorType
GdkDestroyNotify, GdkDestroyNotify ()
GdkDevice, GdkDevice
GdkDeviceAxis, GdkDeviceAxis
GdkDeviceKey, GdkDeviceKey
GdkDisplay, GdkDisplay
GdkDisplay::closed, The "closed" signal
GdkDisplayManager, GdkDisplayManager
GdkDisplayManager::display-opened, The "display-opened" signal
GdkDisplayManager:default-display, The "default-display" property
GdkDisplayPointerHooks, GdkDisplayPointerHooks
GdkDragAction, enum GdkDragAction
GdkDragContext, GdkDragContext
GdkDragProtocol, enum GdkDragProtocol
GdkDrawable, GdkDrawable
GdkEvent, union GdkEvent
GdkEventAny, GdkEventAny
GdkEventButton, GdkEventButton
GdkEventClient, GdkEventClient
GdkEventConfigure, GdkEventConfigure
GdkEventCrossing, GdkEventCrossing
GdkEventDND, GdkEventDND
GdkEventExpose, GdkEventExpose
GdkEventFocus, GdkEventFocus
GdkEventFunc, GdkEventFunc ()
GdkEventGrabBroken, GdkEventGrabBroken
GdkEventKey, GdkEventKey
GdkEventMask, enum GdkEventMask
GdkEventMotion, GdkEventMotion
GdkEventNoExpose, GdkEventNoExpose
GdkEventOwnerChange, GdkEventOwnerChange
GdkEventProperty, GdkEventProperty
GdkEventProximity, GdkEventProximity
GdkEventScroll, GdkEventScroll
GdkEventSelection, GdkEventSelection
GdkEventSetting, GdkEventSetting
GdkEventType, enum GdkEventType
GdkEventVisibility, GdkEventVisibility
GdkEventWindowState, GdkEventWindowState
GdkExtensionMode, enum GdkExtensionMode
GdkFill, enum GdkFill
GdkFillRule, enum GdkFillRule
GdkFilterFunc, GdkFilterFunc ()
GdkFilterReturn, enum GdkFilterReturn
GdkFont, GdkFont
GdkFontType, enum GdkFontType
GdkFunction, enum GdkFunction
GdkGC, GdkGC
GdkGCValues, GdkGCValues
GdkGCValuesMask, enum GdkGCValuesMask
GdkGeometry, GdkGeometry
GdkGrabStatus, enum GdkGrabStatus
GdkGravity, enum GdkGravity
GdkImage, GdkImage
GdkImageType, enum GdkImageType
GdkInputCondition, enum GdkInputCondition
GdkInputFunction, GdkInputFunction ()
GdkInputMode, enum GdkInputMode
GdkInputSource, enum GdkInputSource
GdkJoinStyle, enum GdkJoinStyle
GdkKeymap, GdkKeymap
GdkKeymap::direction-changed, The "direction-changed" signal
GdkKeymap::keys-changed, The "keys-changed" signal
GdkKeymapKey, GdkKeymapKey
GdkLineStyle, enum GdkLineStyle
GdkModifierType, enum GdkModifierType
GdkNativeWindow, GdkNativeWindow
GdkNotifyType, enum GdkNotifyType
GdkOverlapType, enum GdkOverlapType
GdkOwnerChange, enum GdkOwnerChange
GdkPangoAttrEmbossed, GdkPangoAttrEmbossed
GdkPangoAttrStipple, GdkPangoAttrStipple
GdkPangoRenderer, GdkPangoRenderer
GdkPangoRenderer:screen, The "screen" property
GdkPangoRendererClass, GdkPangoRendererClass
GdkPixmap, struct GdkPixmap
GdkPoint, GdkPoint
GdkPointerHooks, GdkPointerHooks
GdkPropertyState, enum GdkPropertyState
GdkPropMode, enum GdkPropMode
GdkRectangle, GdkRectangle
GdkRegion, GdkRegion
GdkRgbCmap, GdkRgbCmap
GdkRgbDither, enum GdkRgbDither
GdkScreen, GdkScreen
GdkScreen::composited-changed, The "composited-changed" signal
GdkScreen::size-changed, The "size-changed" signal
GdkScreen:font-options, The "font-options" property
GdkScreen:resolution, The "resolution" property
GdkScrollDirection, enum GdkScrollDirection
GdkSegment, GdkSegment
GdkSelection, GdkSelection
GdkSelectionType, GdkSelectionType
GdkSettingAction, enum GdkSettingAction
GdkSpan, GdkSpan
GdkSpanFunc, GdkSpanFunc ()
GdkSubwindowMode, enum GdkSubwindowMode
GdkTarget, GdkTarget
GdkTimeCoord, GdkTimeCoord
GdkTrapezoid, GdkTrapezoid
GdkVisibilityState, enum GdkVisibilityState
GdkVisual, GdkVisual
GdkVisualType, enum GdkVisualType
GdkWChar, GdkWChar
GdkWindow, struct GdkWindow
GdkWindowAttr, GdkWindowAttr
GdkWindowAttributesType, enum GdkWindowAttributesType
GdkWindowClass, enum GdkWindowClass
GdkWindowEdge, enum GdkWindowEdge
GdkWindowHints, enum GdkWindowHints
GdkWindowState, enum GdkWindowState
GdkWindowType, enum GdkWindowType
GdkWindowTypeHint, enum GdkWindowTypeHint
GdkWMDecoration, enum GdkWMDecoration
GdkWMFunction, enum GdkWMFunction
GdkXEvent, GdkXEvent
gdkx_colormap_get, gdkx_colormap_get ()
gdkx_visual_get, gdkx_visual_get ()
gdk_add_client_message_filter, gdk_add_client_message_filter ()
gdk_atom_intern, gdk_atom_intern ()
gdk_atom_intern_static_string, gdk_atom_intern_static_string ()
gdk_atom_name, gdk_atom_name ()
GDK_ATOM_TO_POINTER, GDK_ATOM_TO_POINTER()
gdk_beep, gdk_beep ()
gdk_bitmap_create_from_data, gdk_bitmap_create_from_data ()
gdk_bitmap_ref, gdk_bitmap_ref
gdk_bitmap_unref, gdk_bitmap_unref
gdk_cairo_create, gdk_cairo_create ()
gdk_cairo_rectangle, gdk_cairo_rectangle ()
gdk_cairo_region, gdk_cairo_region ()
gdk_cairo_set_source_color, gdk_cairo_set_source_color ()
gdk_cairo_set_source_pixbuf, gdk_cairo_set_source_pixbuf ()
gdk_cairo_set_source_pixmap, gdk_cairo_set_source_pixmap ()
gdk_char_height, gdk_char_height ()
gdk_char_measure, gdk_char_measure ()
gdk_char_width, gdk_char_width ()
gdk_char_width_wc, gdk_char_width_wc ()
gdk_colormap_alloc_color, gdk_colormap_alloc_color ()
gdk_colormap_alloc_colors, gdk_colormap_alloc_colors ()
gdk_colormap_change, gdk_colormap_change ()
gdk_colormap_free_colors, gdk_colormap_free_colors ()
gdk_colormap_get_screen, gdk_colormap_get_screen ()
gdk_colormap_get_system, gdk_colormap_get_system ()
gdk_colormap_get_system_size, gdk_colormap_get_system_size ()
gdk_colormap_get_visual, gdk_colormap_get_visual ()
gdk_colormap_new, gdk_colormap_new ()
gdk_colormap_query_color, gdk_colormap_query_color ()
gdk_colormap_ref, gdk_colormap_ref ()
gdk_colormap_unref, gdk_colormap_unref ()
GDK_COLORMAP_XCOLORMAP, GDK_COLORMAP_XCOLORMAP()
GDK_COLORMAP_XDISPLAY, GDK_COLORMAP_XDISPLAY()
gdk_colors_alloc, gdk_colors_alloc ()
gdk_colors_free, gdk_colors_free ()
gdk_colors_store, gdk_colors_store ()
gdk_color_alloc, gdk_color_alloc ()
gdk_color_black, gdk_color_black ()
gdk_color_change, gdk_color_change ()
gdk_color_copy, gdk_color_copy ()
gdk_color_equal, gdk_color_equal ()
gdk_color_free, gdk_color_free ()
gdk_color_hash, gdk_color_hash ()
gdk_color_parse, gdk_color_parse ()
gdk_color_white, gdk_color_white ()
GDK_CURRENT_TIME, GDK_CURRENT_TIME
gdk_cursor_destroy, gdk_cursor_destroy
gdk_cursor_get_display, gdk_cursor_get_display ()
gdk_cursor_get_image, gdk_cursor_get_image ()
gdk_cursor_new, gdk_cursor_new ()
gdk_cursor_new_for_display, gdk_cursor_new_for_display ()
gdk_cursor_new_from_name, gdk_cursor_new_from_name ()
gdk_cursor_new_from_pixbuf, gdk_cursor_new_from_pixbuf ()
gdk_cursor_new_from_pixmap, gdk_cursor_new_from_pixmap ()
gdk_cursor_ref, gdk_cursor_ref ()
gdk_cursor_unref, gdk_cursor_unref ()
GDK_CURSOR_XCURSOR, GDK_CURSOR_XCURSOR()
GDK_CURSOR_XDISPLAY, GDK_CURSOR_XDISPLAY()
gdk_devices_list, gdk_devices_list ()
gdk_device_free_history, gdk_device_free_history ()
gdk_device_get_axis, gdk_device_get_axis ()
gdk_device_get_core_pointer, gdk_device_get_core_pointer ()
gdk_device_get_history, gdk_device_get_history ()
gdk_device_get_state, gdk_device_get_state ()
gdk_device_set_axis_use, gdk_device_set_axis_use ()
gdk_device_set_key, gdk_device_set_key ()
gdk_device_set_mode, gdk_device_set_mode ()
gdk_device_set_source, gdk_device_set_source ()
GDK_DISPLAY, GDK_DISPLAY()
gdk_display_add_client_message_filter, gdk_display_add_client_message_filter ()
gdk_display_beep, gdk_display_beep ()
gdk_display_close, gdk_display_close ()
gdk_display_flush, gdk_display_flush ()
gdk_display_get_core_pointer, gdk_display_get_core_pointer ()
gdk_display_get_default, gdk_display_get_default ()
gdk_display_get_default_cursor_size, gdk_display_get_default_cursor_size ()
gdk_display_get_default_group, gdk_display_get_default_group ()
gdk_display_get_default_screen, gdk_display_get_default_screen ()
gdk_display_get_event, gdk_display_get_event ()
gdk_display_get_maximal_cursor_size, gdk_display_get_maximal_cursor_size ()
gdk_display_get_name, gdk_display_get_name ()
gdk_display_get_n_screens, gdk_display_get_n_screens ()
gdk_display_get_pointer, gdk_display_get_pointer ()
gdk_display_get_screen, gdk_display_get_screen ()
gdk_display_get_window_at_pointer, gdk_display_get_window_at_pointer ()
gdk_display_keyboard_ungrab, gdk_display_keyboard_ungrab ()
gdk_display_list_devices, gdk_display_list_devices ()
gdk_display_manager_get, gdk_display_manager_get ()
gdk_display_manager_get_default_display, gdk_display_manager_get_default_display ()
gdk_display_manager_list_displays, gdk_display_manager_list_displays ()
gdk_display_manager_set_default_display, gdk_display_manager_set_default_display ()
gdk_display_open, gdk_display_open ()
gdk_display_peek_event, gdk_display_peek_event ()
gdk_display_pointer_is_grabbed, gdk_display_pointer_is_grabbed ()
gdk_display_pointer_ungrab, gdk_display_pointer_ungrab ()
gdk_display_put_event, gdk_display_put_event ()
gdk_display_request_selection_notification, gdk_display_request_selection_notification ()
gdk_display_set_double_click_distance, gdk_display_set_double_click_distance ()
gdk_display_set_double_click_time, gdk_display_set_double_click_time ()
gdk_display_set_pointer_hooks, gdk_display_set_pointer_hooks ()
gdk_display_store_clipboard, gdk_display_store_clipboard ()
gdk_display_supports_clipboard_persistence, gdk_display_supports_clipboard_persistence ()
gdk_display_supports_cursor_alpha, gdk_display_supports_cursor_alpha ()
gdk_display_supports_cursor_color, gdk_display_supports_cursor_color ()
gdk_display_supports_input_shapes, gdk_display_supports_input_shapes ()
gdk_display_supports_selection_notification, gdk_display_supports_selection_notification ()
gdk_display_supports_shapes, gdk_display_supports_shapes ()
gdk_display_sync, gdk_display_sync ()
gdk_display_warp_pointer, gdk_display_warp_pointer ()
GDK_DISPLAY_XDISPLAY, GDK_DISPLAY_XDISPLAY()
gdk_drag_abort, gdk_drag_abort ()
gdk_drag_begin, gdk_drag_begin ()
gdk_drag_context_new, gdk_drag_context_new ()
gdk_drag_context_ref, gdk_drag_context_ref ()
gdk_drag_context_unref, gdk_drag_context_unref ()
gdk_drag_drop, gdk_drag_drop ()
gdk_drag_drop_succeeded, gdk_drag_drop_succeeded ()
gdk_drag_find_window, gdk_drag_find_window ()
gdk_drag_find_window_for_screen, gdk_drag_find_window_for_screen ()
gdk_drag_get_protocol, gdk_drag_get_protocol ()
gdk_drag_get_protocol_for_display, gdk_drag_get_protocol_for_display ()
gdk_drag_get_selection, gdk_drag_get_selection ()
gdk_drag_motion, gdk_drag_motion ()
gdk_drag_status, gdk_drag_status ()
gdk_drawable_copy_to_image, gdk_drawable_copy_to_image ()
gdk_drawable_get_clip_region, gdk_drawable_get_clip_region ()
gdk_drawable_get_colormap, gdk_drawable_get_colormap ()
gdk_drawable_get_data, gdk_drawable_get_data ()
gdk_drawable_get_depth, gdk_drawable_get_depth ()
gdk_drawable_get_display, gdk_drawable_get_display ()
gdk_drawable_get_image, gdk_drawable_get_image ()
gdk_drawable_get_screen, gdk_drawable_get_screen ()
gdk_drawable_get_size, gdk_drawable_get_size ()
gdk_drawable_get_visible_region, gdk_drawable_get_visible_region ()
gdk_drawable_get_visual, gdk_drawable_get_visual ()
gdk_drawable_ref, gdk_drawable_ref ()
gdk_drawable_set_colormap, gdk_drawable_set_colormap ()
gdk_drawable_set_data, gdk_drawable_set_data ()
gdk_drawable_unref, gdk_drawable_unref ()
GDK_DRAWABLE_XDISPLAY, GDK_DRAWABLE_XDISPLAY()
GDK_DRAWABLE_XID, GDK_DRAWABLE_XID()
gdk_draw_arc, gdk_draw_arc ()
gdk_draw_drawable, gdk_draw_drawable ()
gdk_draw_glyphs, gdk_draw_glyphs ()
gdk_draw_glyphs_transformed, gdk_draw_glyphs_transformed ()
gdk_draw_gray_image, gdk_draw_gray_image ()
gdk_draw_image, gdk_draw_image ()
gdk_draw_indexed_image, gdk_draw_indexed_image ()
gdk_draw_layout, gdk_draw_layout ()
gdk_draw_layout_line, gdk_draw_layout_line ()
gdk_draw_layout_line_with_colors, gdk_draw_layout_line_with_colors ()
gdk_draw_layout_with_colors, gdk_draw_layout_with_colors ()
gdk_draw_line, gdk_draw_line ()
gdk_draw_lines, gdk_draw_lines ()
gdk_draw_pixbuf, gdk_draw_pixbuf ()
gdk_draw_pixmap, gdk_draw_pixmap
gdk_draw_point, gdk_draw_point ()
gdk_draw_points, gdk_draw_points ()
gdk_draw_polygon, gdk_draw_polygon ()
gdk_draw_rectangle, gdk_draw_rectangle ()
gdk_draw_rgb_32_image, gdk_draw_rgb_32_image ()
gdk_draw_rgb_32_image_dithalign, gdk_draw_rgb_32_image_dithalign ()
gdk_draw_rgb_image, gdk_draw_rgb_image ()
gdk_draw_rgb_image_dithalign, gdk_draw_rgb_image_dithalign ()
gdk_draw_segments, gdk_draw_segments ()
gdk_draw_string, gdk_draw_string ()
gdk_draw_text, gdk_draw_text ()
gdk_draw_text_wc, gdk_draw_text_wc ()
gdk_draw_trapezoids, gdk_draw_trapezoids ()
gdk_drop_finish, gdk_drop_finish ()
gdk_drop_reply, gdk_drop_reply ()
gdk_error_trap_pop, gdk_error_trap_pop ()
gdk_error_trap_push, gdk_error_trap_push ()
gdk_events_pending, gdk_events_pending ()
gdk_event_copy, gdk_event_copy ()
gdk_event_free, gdk_event_free ()
gdk_event_get, gdk_event_get ()
gdk_event_get_axis, gdk_event_get_axis ()
gdk_event_get_coords, gdk_event_get_coords ()
gdk_event_get_graphics_expose, gdk_event_get_graphics_expose ()
gdk_event_get_root_coords, gdk_event_get_root_coords ()
gdk_event_get_screen, gdk_event_get_screen ()
gdk_event_get_state, gdk_event_get_state ()
gdk_event_get_time, gdk_event_get_time ()
gdk_event_handler_set, gdk_event_handler_set ()
gdk_event_new, gdk_event_new ()
gdk_event_peek, gdk_event_peek ()
gdk_event_put, gdk_event_put ()
gdk_event_send_clientmessage_toall, gdk_event_send_clientmessage_toall ()
gdk_event_send_client_message, gdk_event_send_client_message ()
gdk_event_send_client_message_for_display, gdk_event_send_client_message_for_display ()
gdk_event_set_screen, gdk_event_set_screen ()
gdk_exit, gdk_exit ()
gdk_flush, gdk_flush ()
gdk_fontset_load, gdk_fontset_load ()
gdk_fontset_load_for_display, gdk_fontset_load_for_display ()
gdk_font_equal, gdk_font_equal ()
gdk_font_from_description, gdk_font_from_description ()
gdk_font_from_description_for_display, gdk_font_from_description_for_display ()
gdk_font_get_display, gdk_font_get_display ()
gdk_font_id, gdk_font_id ()
gdk_font_load, gdk_font_load ()
gdk_font_load_for_display, gdk_font_load_for_display ()
gdk_font_lookup, gdk_font_lookup()
gdk_font_lookup_for_display, gdk_font_lookup_for_display()
gdk_font_ref, gdk_font_ref ()
gdk_font_unref, gdk_font_unref ()
GDK_FONT_XDISPLAY, GDK_FONT_XDISPLAY()
GDK_FONT_XFONT, GDK_FONT_XFONT()
gdk_free_compound_text, gdk_free_compound_text ()
gdk_free_text_list, gdk_free_text_list ()
gdk_gc_copy, gdk_gc_copy ()
gdk_gc_destroy, gdk_gc_destroy
gdk_gc_get_colormap, gdk_gc_get_colormap ()
gdk_gc_get_screen, gdk_gc_get_screen ()
gdk_gc_get_values, gdk_gc_get_values ()
GDK_GC_GET_XGC, GDK_GC_GET_XGC()
gdk_gc_new, gdk_gc_new ()
gdk_gc_new_with_values, gdk_gc_new_with_values ()
gdk_gc_offset, gdk_gc_offset ()
gdk_gc_ref, gdk_gc_ref ()
gdk_gc_set_background, gdk_gc_set_background ()
gdk_gc_set_clip_mask, gdk_gc_set_clip_mask ()
gdk_gc_set_clip_origin, gdk_gc_set_clip_origin ()
gdk_gc_set_clip_rectangle, gdk_gc_set_clip_rectangle ()
gdk_gc_set_clip_region, gdk_gc_set_clip_region ()
gdk_gc_set_colormap, gdk_gc_set_colormap ()
gdk_gc_set_dashes, gdk_gc_set_dashes ()
gdk_gc_set_exposures, gdk_gc_set_exposures ()
gdk_gc_set_fill, gdk_gc_set_fill ()
gdk_gc_set_font, gdk_gc_set_font ()
gdk_gc_set_foreground, gdk_gc_set_foreground ()
gdk_gc_set_function, gdk_gc_set_function ()
gdk_gc_set_line_attributes, gdk_gc_set_line_attributes ()
gdk_gc_set_rgb_bg_color, gdk_gc_set_rgb_bg_color ()
gdk_gc_set_rgb_fg_color, gdk_gc_set_rgb_fg_color ()
gdk_gc_set_stipple, gdk_gc_set_stipple ()
gdk_gc_set_subwindow, gdk_gc_set_subwindow ()
gdk_gc_set_tile, gdk_gc_set_tile ()
gdk_gc_set_ts_origin, gdk_gc_set_ts_origin ()
gdk_gc_set_values, gdk_gc_set_values ()
gdk_gc_unref, gdk_gc_unref ()
GDK_GC_XDISPLAY, GDK_GC_XDISPLAY()
GDK_GC_XGC, GDK_GC_XGC()
gdk_get_default_root_window, gdk_get_default_root_window ()
gdk_get_display, gdk_get_display ()
gdk_get_display_arg_name, gdk_get_display_arg_name ()
gdk_get_program_class, gdk_get_program_class ()
gdk_get_show_events, gdk_get_show_events ()
gdk_get_use_xshm, gdk_get_use_xshm ()
gdk_image_destroy, gdk_image_destroy
gdk_image_get, gdk_image_get ()
gdk_image_get_colormap, gdk_image_get_colormap ()
gdk_image_get_pixel, gdk_image_get_pixel ()
gdk_image_new, gdk_image_new ()
gdk_image_new_bitmap, gdk_image_new_bitmap ()
gdk_image_put_pixel, gdk_image_put_pixel ()
gdk_image_ref, gdk_image_ref ()
gdk_image_set_colormap, gdk_image_set_colormap ()
gdk_image_unref, gdk_image_unref ()
GDK_IMAGE_XDISPLAY, GDK_IMAGE_XDISPLAY()
GDK_IMAGE_XIMAGE, GDK_IMAGE_XIMAGE()
gdk_init, gdk_init ()
gdk_init_check, gdk_init_check ()
gdk_input_add, gdk_input_add ()
gdk_input_add_full, gdk_input_add_full ()
gdk_input_remove, gdk_input_remove ()
gdk_input_set_extension_events, gdk_input_set_extension_events ()
gdk_keyboard_grab, gdk_keyboard_grab ()
gdk_keyboard_ungrab, gdk_keyboard_ungrab ()
gdk_keymap_get_default, gdk_keymap_get_default ()
gdk_keymap_get_direction, gdk_keymap_get_direction ()
gdk_keymap_get_entries_for_keycode, gdk_keymap_get_entries_for_keycode ()
gdk_keymap_get_entries_for_keyval, gdk_keymap_get_entries_for_keyval ()
gdk_keymap_get_for_display, gdk_keymap_get_for_display ()
gdk_keymap_lookup_key, gdk_keymap_lookup_key ()
gdk_keymap_translate_keyboard_state, gdk_keymap_translate_keyboard_state ()
gdk_keyval_convert_case, gdk_keyval_convert_case ()
gdk_keyval_from_name, gdk_keyval_from_name ()
gdk_keyval_is_lower, gdk_keyval_is_lower ()
gdk_keyval_is_upper, gdk_keyval_is_upper ()
gdk_keyval_name, gdk_keyval_name ()
gdk_keyval_to_lower, gdk_keyval_to_lower ()
gdk_keyval_to_unicode, gdk_keyval_to_unicode ()
gdk_keyval_to_upper, gdk_keyval_to_upper ()
gdk_list_visuals, gdk_list_visuals ()
gdk_mbstowcs, gdk_mbstowcs ()
gdk_net_wm_supports, gdk_net_wm_supports ()
GDK_NONE, GDK_NONE
gdk_notify_startup_complete, gdk_notify_startup_complete ()
gdk_pango_attr_embossed_new, gdk_pango_attr_embossed_new ()
gdk_pango_attr_stipple_new, gdk_pango_attr_stipple_new ()
gdk_pango_context_get, gdk_pango_context_get ()
gdk_pango_context_get_for_screen, gdk_pango_context_get_for_screen ()
gdk_pango_context_set_colormap, gdk_pango_context_set_colormap ()
gdk_pango_layout_get_clip_region, gdk_pango_layout_get_clip_region ()
gdk_pango_layout_line_get_clip_region, gdk_pango_layout_line_get_clip_region ()
gdk_pango_renderer_get_default, gdk_pango_renderer_get_default ()
gdk_pango_renderer_new, gdk_pango_renderer_new ()
gdk_pango_renderer_set_drawable, gdk_pango_renderer_set_drawable ()
gdk_pango_renderer_set_gc, gdk_pango_renderer_set_gc ()
gdk_pango_renderer_set_override_color, gdk_pango_renderer_set_override_color ()
gdk_pango_renderer_set_stipple, gdk_pango_renderer_set_stipple ()
GDK_PARENT_RELATIVE, GDK_PARENT_RELATIVE
gdk_parse_args, gdk_parse_args ()
gdk_pixbuf_get_from_drawable, gdk_pixbuf_get_from_drawable ()
gdk_pixbuf_get_from_image, gdk_pixbuf_get_from_image ()
gdk_pixbuf_render_pixmap_and_mask, gdk_pixbuf_render_pixmap_and_mask ()
gdk_pixbuf_render_pixmap_and_mask_for_colormap, gdk_pixbuf_render_pixmap_and_mask_for_colormap ()
gdk_pixbuf_render_threshold_alpha, gdk_pixbuf_render_threshold_alpha ()
gdk_pixbuf_render_to_drawable, gdk_pixbuf_render_to_drawable ()
gdk_pixbuf_render_to_drawable_alpha, gdk_pixbuf_render_to_drawable_alpha ()
gdk_pixmap_colormap_create_from_xpm, gdk_pixmap_colormap_create_from_xpm ()
gdk_pixmap_colormap_create_from_xpm_d, gdk_pixmap_colormap_create_from_xpm_d ()
gdk_pixmap_create_from_data, gdk_pixmap_create_from_data ()
gdk_pixmap_create_from_xpm, gdk_pixmap_create_from_xpm ()
gdk_pixmap_create_from_xpm_d, gdk_pixmap_create_from_xpm_d ()
gdk_pixmap_foreign_new, gdk_pixmap_foreign_new ()
gdk_pixmap_foreign_new_for_display, gdk_pixmap_foreign_new_for_display ()
gdk_pixmap_foreign_new_for_screen, gdk_pixmap_foreign_new_for_screen ()
gdk_pixmap_lookup, gdk_pixmap_lookup ()
gdk_pixmap_lookup_for_display, gdk_pixmap_lookup_for_display ()
gdk_pixmap_new, gdk_pixmap_new ()
gdk_pixmap_ref, gdk_pixmap_ref
gdk_pixmap_unref, gdk_pixmap_unref
GDK_PIXMAP_XDISPLAY, GDK_PIXMAP_XDISPLAY()
GDK_PIXMAP_XID, GDK_PIXMAP_XID()
gdk_pointer_grab, gdk_pointer_grab ()
gdk_pointer_is_grabbed, gdk_pointer_is_grabbed ()
GDK_POINTER_TO_ATOM, GDK_POINTER_TO_ATOM()
gdk_pointer_ungrab, gdk_pointer_ungrab ()
GDK_PRIORITY_EVENTS, GDK_PRIORITY_EVENTS
GDK_PRIORITY_REDRAW, GDK_PRIORITY_REDRAW
gdk_property_change, gdk_property_change ()
gdk_property_delete, gdk_property_delete ()
gdk_property_get, gdk_property_get ()
gdk_query_depths, gdk_query_depths ()
gdk_query_visual_types, gdk_query_visual_types ()
gdk_rectangle_intersect, gdk_rectangle_intersect ()
gdk_rectangle_union, gdk_rectangle_union ()
gdk_region_copy, gdk_region_copy ()
gdk_region_destroy, gdk_region_destroy ()
gdk_region_empty, gdk_region_empty ()
gdk_region_equal, gdk_region_equal ()
gdk_region_get_clipbox, gdk_region_get_clipbox ()
gdk_region_get_rectangles, gdk_region_get_rectangles ()
gdk_region_intersect, gdk_region_intersect ()
gdk_region_new, gdk_region_new ()
gdk_region_offset, gdk_region_offset ()
gdk_region_point_in, gdk_region_point_in ()
gdk_region_polygon, gdk_region_polygon ()
gdk_region_rectangle, gdk_region_rectangle ()
gdk_region_rect_in, gdk_region_rect_in ()
gdk_region_shrink, gdk_region_shrink ()
gdk_region_spans_intersect_foreach, gdk_region_spans_intersect_foreach ()
gdk_region_subtract, gdk_region_subtract ()
gdk_region_union, gdk_region_union ()
gdk_region_union_with_rect, gdk_region_union_with_rect ()
gdk_region_xor, gdk_region_xor ()
gdk_rgb_cmap_free, gdk_rgb_cmap_free ()
gdk_rgb_cmap_new, gdk_rgb_cmap_new ()
gdk_rgb_colormap_ditherable, gdk_rgb_colormap_ditherable ()
gdk_rgb_ditherable, gdk_rgb_ditherable ()
gdk_rgb_find_color, gdk_rgb_find_color ()
gdk_rgb_gc_set_background, gdk_rgb_gc_set_background ()
gdk_rgb_gc_set_foreground, gdk_rgb_gc_set_foreground ()
gdk_rgb_get_cmap, gdk_rgb_get_cmap
gdk_rgb_get_colormap, gdk_rgb_get_colormap ()
gdk_rgb_get_visual, gdk_rgb_get_visual ()
gdk_rgb_init, gdk_rgb_init ()
gdk_rgb_set_install, gdk_rgb_set_install ()
gdk_rgb_set_min_colors, gdk_rgb_set_min_colors ()
gdk_rgb_set_verbose, gdk_rgb_set_verbose ()
gdk_rgb_xpixel_from_rgb, gdk_rgb_xpixel_from_rgb ()
GDK_ROOT_PARENT, GDK_ROOT_PARENT()
GDK_ROOT_WINDOW, GDK_ROOT_WINDOW()
gdk_screen_broadcast_client_message, gdk_screen_broadcast_client_message ()
gdk_screen_get_active_window, gdk_screen_get_active_window ()
gdk_screen_get_default, gdk_screen_get_default ()
gdk_screen_get_default_colormap, gdk_screen_get_default_colormap ()
gdk_screen_get_display, gdk_screen_get_display ()
gdk_screen_get_font_options, gdk_screen_get_font_options ()
gdk_screen_get_height, gdk_screen_get_height ()
gdk_screen_get_height_mm, gdk_screen_get_height_mm ()
gdk_screen_get_monitor_at_point, gdk_screen_get_monitor_at_point ()
gdk_screen_get_monitor_at_window, gdk_screen_get_monitor_at_window ()
gdk_screen_get_monitor_geometry, gdk_screen_get_monitor_geometry ()
gdk_screen_get_number, gdk_screen_get_number ()
gdk_screen_get_n_monitors, gdk_screen_get_n_monitors ()
gdk_screen_get_resolution, gdk_screen_get_resolution ()
gdk_screen_get_rgba_colormap, gdk_screen_get_rgba_colormap ()
gdk_screen_get_rgba_visual, gdk_screen_get_rgba_visual ()
gdk_screen_get_rgb_colormap, gdk_screen_get_rgb_colormap ()
gdk_screen_get_rgb_visual, gdk_screen_get_rgb_visual ()
gdk_screen_get_root_window, gdk_screen_get_root_window ()
gdk_screen_get_setting, gdk_screen_get_setting ()
gdk_screen_get_system_colormap, gdk_screen_get_system_colormap ()
gdk_screen_get_system_visual, gdk_screen_get_system_visual ()
gdk_screen_get_toplevel_windows, gdk_screen_get_toplevel_windows ()
gdk_screen_get_width, gdk_screen_get_width ()
gdk_screen_get_width_mm, gdk_screen_get_width_mm ()
gdk_screen_get_window_stack, gdk_screen_get_window_stack ()
gdk_screen_height, gdk_screen_height ()
gdk_screen_height_mm, gdk_screen_height_mm ()
gdk_screen_is_composited, gdk_screen_is_composited ()
gdk_screen_list_visuals, gdk_screen_list_visuals ()
gdk_screen_make_display_name, gdk_screen_make_display_name ()
gdk_screen_set_default_colormap, gdk_screen_set_default_colormap ()
gdk_screen_set_font_options, gdk_screen_set_font_options ()
gdk_screen_set_resolution, gdk_screen_set_resolution ()
gdk_screen_width, gdk_screen_width ()
gdk_screen_width_mm, gdk_screen_width_mm ()
GDK_SCREEN_XDISPLAY, GDK_SCREEN_XDISPLAY()
GDK_SCREEN_XNUMBER, GDK_SCREEN_XNUMBER()
GDK_SCREEN_XSCREEN, GDK_SCREEN_XSCREEN()
GDK_SELECTION_CLIPBOARD, GDK_SELECTION_CLIPBOARD
gdk_selection_convert, gdk_selection_convert ()
gdk_selection_owner_get, gdk_selection_owner_get ()
gdk_selection_owner_get_for_display, gdk_selection_owner_get_for_display ()
gdk_selection_owner_set, gdk_selection_owner_set ()
gdk_selection_owner_set_for_display, gdk_selection_owner_set_for_display ()
GDK_SELECTION_PRIMARY, GDK_SELECTION_PRIMARY
gdk_selection_property_get, gdk_selection_property_get ()
GDK_SELECTION_SECONDARY, GDK_SELECTION_SECONDARY
gdk_selection_send_notify, gdk_selection_send_notify ()
gdk_selection_send_notify_for_display, gdk_selection_send_notify_for_display ()
GDK_SELECTION_TYPE_ATOM, GDK_SELECTION_TYPE_ATOM
GDK_SELECTION_TYPE_BITMAP, GDK_SELECTION_TYPE_BITMAP
GDK_SELECTION_TYPE_COLORMAP, GDK_SELECTION_TYPE_COLORMAP
GDK_SELECTION_TYPE_DRAWABLE, GDK_SELECTION_TYPE_DRAWABLE
GDK_SELECTION_TYPE_INTEGER, GDK_SELECTION_TYPE_INTEGER
GDK_SELECTION_TYPE_PIXMAP, GDK_SELECTION_TYPE_PIXMAP
GDK_SELECTION_TYPE_STRING, GDK_SELECTION_TYPE_STRING
GDK_SELECTION_TYPE_WINDOW, GDK_SELECTION_TYPE_WINDOW
gdk_setting_get, gdk_setting_get ()
gdk_set_double_click_time, gdk_set_double_click_time ()
gdk_set_locale, gdk_set_locale ()
gdk_set_pointer_hooks, gdk_set_pointer_hooks ()
gdk_set_program_class, gdk_set_program_class ()
gdk_set_show_events, gdk_set_show_events ()
gdk_set_sm_client_id, gdk_set_sm_client_id ()
gdk_set_use_xshm, gdk_set_use_xshm ()
gdk_spawn_command_line_on_screen, gdk_spawn_command_line_on_screen ()
gdk_spawn_on_screen, gdk_spawn_on_screen ()
gdk_spawn_on_screen_with_pipes, gdk_spawn_on_screen_with_pipes ()
gdk_string_extents, gdk_string_extents ()
gdk_string_height, gdk_string_height ()
gdk_string_measure, gdk_string_measure ()
gdk_string_to_compound_text, gdk_string_to_compound_text ()
gdk_string_to_compound_text_for_display, gdk_string_to_compound_text_for_display ()
gdk_string_width, gdk_string_width ()
GDK_TARGET_BITMAP, GDK_TARGET_BITMAP
GDK_TARGET_COLORMAP, GDK_TARGET_COLORMAP
GDK_TARGET_DRAWABLE, GDK_TARGET_DRAWABLE
GDK_TARGET_PIXMAP, GDK_TARGET_PIXMAP
GDK_TARGET_STRING, GDK_TARGET_STRING
gdk_text_extents, gdk_text_extents ()
gdk_text_extents_wc, gdk_text_extents_wc ()
gdk_text_height, gdk_text_height ()
gdk_text_measure, gdk_text_measure ()
gdk_text_property_to_text_list, gdk_text_property_to_text_list ()
gdk_text_property_to_text_list_for_display, gdk_text_property_to_text_list_for_display ()
gdk_text_property_to_utf8_list, gdk_text_property_to_utf8_list ()
gdk_text_property_to_utf8_list_for_display, gdk_text_property_to_utf8_list_for_display ()
gdk_text_width, gdk_text_width ()
gdk_text_width_wc, gdk_text_width_wc ()
GDK_THREADS_ENTER, GDK_THREADS_ENTER()
gdk_threads_enter, gdk_threads_enter ()
gdk_threads_init, gdk_threads_init ()
GDK_THREADS_LEAVE, GDK_THREADS_LEAVE()
gdk_threads_leave, gdk_threads_leave ()
gdk_threads_mutex, gdk_threads_mutex
gdk_threads_set_lock_functions, gdk_threads_set_lock_functions ()
gdk_unicode_to_keyval, gdk_unicode_to_keyval ()
gdk_utf8_to_compound_text, gdk_utf8_to_compound_text ()
gdk_utf8_to_compound_text_for_display, gdk_utf8_to_compound_text_for_display ()
gdk_utf8_to_string_target, gdk_utf8_to_string_target ()
gdk_visual_get_best, gdk_visual_get_best ()
gdk_visual_get_best_depth, gdk_visual_get_best_depth ()
gdk_visual_get_best_type, gdk_visual_get_best_type ()
gdk_visual_get_best_with_both, gdk_visual_get_best_with_both ()
gdk_visual_get_best_with_depth, gdk_visual_get_best_with_depth ()
gdk_visual_get_best_with_type, gdk_visual_get_best_with_type ()
gdk_visual_get_screen, gdk_visual_get_screen ()
gdk_visual_get_system, gdk_visual_get_system ()
gdk_visual_ref, gdk_visual_ref()
gdk_visual_unref, gdk_visual_unref()
GDK_VISUAL_XVISUAL, GDK_VISUAL_XVISUAL()
gdk_wcstombs, gdk_wcstombs ()
GDK_WINDOWING_FB, GDK_WINDOWING_FB
GDK_WINDOWING_WIN32, GDK_WINDOWING_WIN32
GDK_WINDOWING_X11, GDK_WINDOWING_X11
gdk_window_add_filter, gdk_window_add_filter ()
gdk_window_at_pointer, gdk_window_at_pointer ()
gdk_window_begin_move_drag, gdk_window_begin_move_drag ()
gdk_window_begin_paint_rect, gdk_window_begin_paint_rect ()
gdk_window_begin_paint_region, gdk_window_begin_paint_region ()
gdk_window_begin_resize_drag, gdk_window_begin_resize_drag ()
gdk_window_clear, gdk_window_clear ()
gdk_window_clear_area, gdk_window_clear_area ()
gdk_window_clear_area_e, gdk_window_clear_area_e ()
gdk_window_configure_finished, gdk_window_configure_finished ()
gdk_window_constrain_size, gdk_window_constrain_size ()
gdk_window_copy_area, gdk_window_copy_area()
gdk_window_deiconify, gdk_window_deiconify ()
gdk_window_destroy, gdk_window_destroy ()
gdk_window_enable_synchronized_configure, gdk_window_enable_synchronized_configure ()
gdk_window_end_paint, gdk_window_end_paint ()
gdk_window_focus, gdk_window_focus ()
gdk_window_foreign_new, gdk_window_foreign_new ()
gdk_window_foreign_new_for_display, gdk_window_foreign_new_for_display ()
gdk_window_freeze_updates, gdk_window_freeze_updates ()
gdk_window_fullscreen, gdk_window_fullscreen ()
gdk_window_get_children, gdk_window_get_children ()
gdk_window_get_colormap, gdk_window_get_colormap
gdk_window_get_decorations, gdk_window_get_decorations ()
gdk_window_get_deskrelative_origin, gdk_window_get_deskrelative_origin ()
gdk_window_get_events, gdk_window_get_events ()
gdk_window_get_frame_extents, gdk_window_get_frame_extents ()
gdk_window_get_geometry, gdk_window_get_geometry ()
gdk_window_get_group, gdk_window_get_group ()
gdk_window_get_internal_paint_info, gdk_window_get_internal_paint_info ()
gdk_window_get_origin, gdk_window_get_origin ()
gdk_window_get_parent, gdk_window_get_parent ()
gdk_window_get_pointer, gdk_window_get_pointer ()
gdk_window_get_position, gdk_window_get_position ()
gdk_window_get_root_origin, gdk_window_get_root_origin ()
gdk_window_get_size, gdk_window_get_size
gdk_window_get_state, gdk_window_get_state ()
gdk_window_get_toplevel, gdk_window_get_toplevel ()
gdk_window_get_toplevels, gdk_window_get_toplevels ()
gdk_window_get_type, gdk_window_get_type
gdk_window_get_type_hint, gdk_window_get_type_hint ()
gdk_window_get_update_area, gdk_window_get_update_area ()
gdk_window_get_user_data, gdk_window_get_user_data ()
gdk_window_get_visual, gdk_window_get_visual
gdk_window_get_window_type, gdk_window_get_window_type ()
gdk_window_hide, gdk_window_hide ()
gdk_window_iconify, gdk_window_iconify ()
gdk_window_input_shape_combine_mask, gdk_window_input_shape_combine_mask ()
gdk_window_input_shape_combine_region, gdk_window_input_shape_combine_region ()
gdk_window_invalidate_maybe_recurse, gdk_window_invalidate_maybe_recurse ()
gdk_window_invalidate_rect, gdk_window_invalidate_rect ()
gdk_window_invalidate_region, gdk_window_invalidate_region ()
gdk_window_is_viewable, gdk_window_is_viewable ()
gdk_window_is_visible, gdk_window_is_visible ()
gdk_window_lookup, gdk_window_lookup ()
gdk_window_lookup_for_display, gdk_window_lookup_for_display ()
gdk_window_lower, gdk_window_lower ()
gdk_window_maximize, gdk_window_maximize ()
gdk_window_merge_child_input_shapes, gdk_window_merge_child_input_shapes ()
gdk_window_merge_child_shapes, gdk_window_merge_child_shapes ()
gdk_window_move, gdk_window_move ()
gdk_window_move_region, gdk_window_move_region ()
gdk_window_move_resize, gdk_window_move_resize ()
gdk_window_new, gdk_window_new ()
gdk_window_peek_children, gdk_window_peek_children ()
gdk_window_process_all_updates, gdk_window_process_all_updates ()
gdk_window_process_updates, gdk_window_process_updates ()
gdk_window_raise, gdk_window_raise ()
gdk_window_ref, gdk_window_ref
gdk_window_register_dnd, gdk_window_register_dnd ()
gdk_window_remove_filter, gdk_window_remove_filter ()
gdk_window_reparent, gdk_window_reparent ()
gdk_window_resize, gdk_window_resize ()
gdk_window_scroll, gdk_window_scroll ()
gdk_window_set_accept_focus, gdk_window_set_accept_focus ()
gdk_window_set_background, gdk_window_set_background ()
gdk_window_set_back_pixmap, gdk_window_set_back_pixmap ()
gdk_window_set_child_input_shapes, gdk_window_set_child_input_shapes ()
gdk_window_set_child_shapes, gdk_window_set_child_shapes ()
gdk_window_set_colormap, gdk_window_set_colormap
gdk_window_set_cursor, gdk_window_set_cursor ()
gdk_window_set_debug_updates, gdk_window_set_debug_updates ()
gdk_window_set_decorations, gdk_window_set_decorations ()
gdk_window_set_events, gdk_window_set_events ()
gdk_window_set_focus_on_map, gdk_window_set_focus_on_map ()
gdk_window_set_functions, gdk_window_set_functions ()
gdk_window_set_geometry_hints, gdk_window_set_geometry_hints ()
gdk_window_set_group, gdk_window_set_group ()
gdk_window_set_hints, gdk_window_set_hints ()
gdk_window_set_icon, gdk_window_set_icon ()
gdk_window_set_icon_list, gdk_window_set_icon_list ()
gdk_window_set_icon_name, gdk_window_set_icon_name ()
gdk_window_set_keep_above, gdk_window_set_keep_above ()
gdk_window_set_keep_below, gdk_window_set_keep_below ()
gdk_window_set_modal_hint, gdk_window_set_modal_hint ()
gdk_window_set_override_redirect, gdk_window_set_override_redirect ()
gdk_window_set_role, gdk_window_set_role ()
gdk_window_set_skip_pager_hint, gdk_window_set_skip_pager_hint ()
gdk_window_set_skip_taskbar_hint, gdk_window_set_skip_taskbar_hint ()
gdk_window_set_static_gravities, gdk_window_set_static_gravities ()
gdk_window_set_title, gdk_window_set_title ()
gdk_window_set_transient_for, gdk_window_set_transient_for ()
gdk_window_set_type_hint, gdk_window_set_type_hint ()
gdk_window_set_urgency_hint, gdk_window_set_urgency_hint ()
gdk_window_set_user_data, gdk_window_set_user_data ()
gdk_window_shape_combine_mask, gdk_window_shape_combine_mask ()
gdk_window_shape_combine_region, gdk_window_shape_combine_region ()
gdk_window_show, gdk_window_show ()
gdk_window_show_unraised, gdk_window_show_unraised ()
gdk_window_stick, gdk_window_stick ()
gdk_window_thaw_updates, gdk_window_thaw_updates ()
gdk_window_unfullscreen, gdk_window_unfullscreen ()
gdk_window_unmaximize, gdk_window_unmaximize ()
gdk_window_unref, gdk_window_unref
gdk_window_unstick, gdk_window_unstick ()
gdk_window_withdraw, gdk_window_withdraw ()
GDK_WINDOW_XDISPLAY, GDK_WINDOW_XDISPLAY()
GDK_WINDOW_XID, GDK_WINDOW_XID()
GDK_WINDOW_XWINDOW, GDK_WINDOW_XWINDOW
gdk_x11_atom_to_xatom, gdk_x11_atom_to_xatom ()
gdk_x11_atom_to_xatom_for_display, gdk_x11_atom_to_xatom_for_display ()
gdk_x11_colormap_foreign_new, gdk_x11_colormap_foreign_new ()
gdk_x11_colormap_get_xcolormap, gdk_x11_colormap_get_xcolormap ()
gdk_x11_colormap_get_xdisplay, gdk_x11_colormap_get_xdisplay ()
gdk_x11_cursor_get_xcursor, gdk_x11_cursor_get_xcursor ()
gdk_x11_cursor_get_xdisplay, gdk_x11_cursor_get_xdisplay ()
gdk_x11_display_get_user_time, gdk_x11_display_get_user_time ()
gdk_x11_display_get_xdisplay, gdk_x11_display_get_xdisplay ()
gdk_x11_display_grab, gdk_x11_display_grab ()
gdk_x11_display_set_cursor_theme, gdk_x11_display_set_cursor_theme ()
gdk_x11_display_ungrab, gdk_x11_display_ungrab ()
gdk_x11_drawable_get_xdisplay, gdk_x11_drawable_get_xdisplay ()
gdk_x11_drawable_get_xid, gdk_x11_drawable_get_xid ()
gdk_x11_font_get_name, gdk_x11_font_get_name ()
gdk_x11_font_get_xdisplay, gdk_x11_font_get_xdisplay ()
gdk_x11_font_get_xfont, gdk_x11_font_get_xfont ()
gdk_x11_gc_get_xdisplay, gdk_x11_gc_get_xdisplay ()
gdk_x11_gc_get_xgc, gdk_x11_gc_get_xgc ()
gdk_x11_get_default_root_xwindow, gdk_x11_get_default_root_xwindow ()
gdk_x11_get_default_screen, gdk_x11_get_default_screen ()
gdk_x11_get_default_xdisplay, gdk_x11_get_default_xdisplay ()
gdk_x11_get_server_time, gdk_x11_get_server_time ()
gdk_x11_get_xatom_by_name, gdk_x11_get_xatom_by_name ()
gdk_x11_get_xatom_by_name_for_display, gdk_x11_get_xatom_by_name_for_display ()
gdk_x11_get_xatom_name, gdk_x11_get_xatom_name ()
gdk_x11_get_xatom_name_for_display, gdk_x11_get_xatom_name_for_display ()
gdk_x11_grab_server, gdk_x11_grab_server ()
gdk_x11_image_get_xdisplay, gdk_x11_image_get_xdisplay ()
gdk_x11_image_get_ximage, gdk_x11_image_get_ximage ()
gdk_x11_lookup_xdisplay, gdk_x11_lookup_xdisplay ()
gdk_x11_register_standard_event_type, gdk_x11_register_standard_event_type ()
gdk_x11_screen_get_screen_number, gdk_x11_screen_get_screen_number ()
gdk_x11_screen_get_window_manager_name, gdk_x11_screen_get_window_manager_name ()
gdk_x11_screen_get_xscreen, gdk_x11_screen_get_xscreen ()
gdk_x11_screen_lookup_visual, gdk_x11_screen_lookup_visual ()
gdk_x11_screen_supports_net_wm_hint, gdk_x11_screen_supports_net_wm_hint ()
gdk_x11_ungrab_server, gdk_x11_ungrab_server ()
gdk_x11_visual_get_xvisual, gdk_x11_visual_get_xvisual ()
gdk_x11_window_move_to_current_desktop, gdk_x11_window_move_to_current_desktop ()
gdk_x11_window_set_user_time, gdk_x11_window_set_user_time ()
gdk_x11_xatom_to_atom, gdk_x11_xatom_to_atom ()
gdk_x11_xatom_to_atom_for_display, gdk_x11_xatom_to_atom_for_display ()
gdk_xid_table_lookup, gdk_xid_table_lookup ()
gdk_xid_table_lookup_for_display, gdk_xid_table_lookup_for_display ()


Index of deprecated symbols

G

GdkFont, GdkFont
GdkFontType, enum GdkFontType
GdkSelection, GdkSelection
GdkSelectionType, GdkSelectionType
GdkTarget, GdkTarget
gdkx_colormap_get, gdkx_colormap_get ()
gdk_bitmap_ref, gdk_bitmap_ref
gdk_bitmap_unref, gdk_bitmap_unref
gdk_char_height, gdk_char_height ()
gdk_char_measure, gdk_char_measure ()
gdk_char_width, gdk_char_width ()
gdk_char_width_wc, gdk_char_width_wc ()
gdk_colormap_change, gdk_colormap_change ()
gdk_colormap_get_system_size, gdk_colormap_get_system_size ()
gdk_colormap_ref, gdk_colormap_ref ()
gdk_colormap_unref, gdk_colormap_unref ()
gdk_colors_alloc, gdk_colors_alloc ()
gdk_colors_free, gdk_colors_free ()
gdk_colors_store, gdk_colors_store ()
gdk_color_alloc, gdk_color_alloc ()
gdk_color_black, gdk_color_black ()
gdk_color_change, gdk_color_change ()
gdk_color_white, gdk_color_white ()
gdk_cursor_destroy, gdk_cursor_destroy
gdk_drag_context_ref, gdk_drag_context_ref ()
gdk_drag_context_unref, gdk_drag_context_unref ()
gdk_drawable_get_data, gdk_drawable_get_data ()
gdk_drawable_ref, gdk_drawable_ref ()
gdk_drawable_set_data, gdk_drawable_set_data ()
gdk_drawable_unref, gdk_drawable_unref ()
gdk_draw_pixmap, gdk_draw_pixmap
gdk_draw_string, gdk_draw_string ()
gdk_draw_text, gdk_draw_text ()
gdk_draw_text_wc, gdk_draw_text_wc ()
gdk_exit, gdk_exit ()
gdk_fontset_load, gdk_fontset_load ()
gdk_fontset_load_for_display, gdk_fontset_load_for_display ()
gdk_font_equal, gdk_font_equal ()
gdk_font_from_description, gdk_font_from_description ()
gdk_font_from_description_for_display, gdk_font_from_description_for_display ()
gdk_font_get_display, gdk_font_get_display ()
gdk_font_id, gdk_font_id ()
gdk_font_load, gdk_font_load ()
gdk_font_load_for_display, gdk_font_load_for_display ()
gdk_font_lookup, gdk_font_lookup()
gdk_font_lookup_for_display, gdk_font_lookup_for_display()
gdk_font_ref, gdk_font_ref ()
gdk_font_unref, gdk_font_unref ()
GDK_FONT_XDISPLAY, GDK_FONT_XDISPLAY()
GDK_FONT_XFONT, GDK_FONT_XFONT()
gdk_gc_destroy, gdk_gc_destroy
gdk_gc_ref, gdk_gc_ref ()
gdk_gc_set_font, gdk_gc_set_font ()
gdk_gc_unref, gdk_gc_unref ()
gdk_get_use_xshm, gdk_get_use_xshm ()
gdk_image_destroy, gdk_image_destroy
gdk_image_get, gdk_image_get ()
gdk_image_new_bitmap, gdk_image_new_bitmap ()
gdk_image_ref, gdk_image_ref ()
gdk_image_unref, gdk_image_unref ()
gdk_input_add, gdk_input_add ()
gdk_input_add_full, gdk_input_add_full ()
gdk_input_remove, gdk_input_remove ()
gdk_mbstowcs, gdk_mbstowcs ()
gdk_pango_context_set_colormap, gdk_pango_context_set_colormap ()
gdk_pixbuf_render_to_drawable, gdk_pixbuf_render_to_drawable ()
gdk_pixbuf_render_to_drawable_alpha, gdk_pixbuf_render_to_drawable_alpha ()
gdk_pixmap_ref, gdk_pixmap_ref
gdk_pixmap_unref, gdk_pixmap_unref
gdk_rgb_gc_set_background, gdk_rgb_gc_set_background ()
gdk_rgb_gc_set_foreground, gdk_rgb_gc_set_foreground ()
gdk_rgb_get_cmap, gdk_rgb_get_cmap
gdk_rgb_init, gdk_rgb_init ()
gdk_rgb_xpixel_from_rgb, gdk_rgb_xpixel_from_rgb ()
GDK_ROOT_PARENT, GDK_ROOT_PARENT()
gdk_set_use_xshm, gdk_set_use_xshm ()
gdk_string_extents, gdk_string_extents ()
gdk_string_height, gdk_string_height ()
gdk_string_measure, gdk_string_measure ()
gdk_string_width, gdk_string_width ()
gdk_text_extents, gdk_text_extents ()
gdk_text_extents_wc, gdk_text_extents_wc ()
gdk_text_height, gdk_text_height ()
gdk_text_measure, gdk_text_measure ()
gdk_text_width, gdk_text_width ()
gdk_text_width_wc, gdk_text_width_wc ()
gdk_threads_mutex, gdk_threads_mutex
gdk_visual_ref, gdk_visual_ref()
gdk_visual_unref, gdk_visual_unref()
gdk_wcstombs, gdk_wcstombs ()
gdk_window_copy_area, gdk_window_copy_area()
gdk_window_get_colormap, gdk_window_get_colormap
gdk_window_get_deskrelative_origin, gdk_window_get_deskrelative_origin ()
gdk_window_get_size, gdk_window_get_size
gdk_window_get_type, gdk_window_get_type
gdk_window_get_visual, gdk_window_get_visual
gdk_window_ref, gdk_window_ref
gdk_window_set_colormap, gdk_window_set_colormap
gdk_window_set_hints, gdk_window_set_hints ()
gdk_window_unref, gdk_window_unref
gdk_x11_font_get_name, gdk_x11_font_get_name ()
gdk_x11_font_get_xdisplay, gdk_x11_font_get_xdisplay ()
gdk_x11_font_get_xfont, gdk_x11_font_get_xfont ()


Index of new symbols in 2.2

G

GdkDisplay, GdkDisplay
GdkDisplay::closed, The "closed" signal
GdkDisplayManager, GdkDisplayManager
GdkDisplayManager::display-opened, The "display-opened" signal
GdkDisplayPointerHooks, GdkDisplayPointerHooks
GdkKeymap::keys-changed, The "keys-changed" signal
GdkScreen, GdkScreen
GdkScreen::size-changed, The "size-changed" signal
gdk_colormap_get_screen, gdk_colormap_get_screen ()
gdk_cursor_get_display, gdk_cursor_get_display ()
gdk_cursor_new_for_display, gdk_cursor_new_for_display ()
gdk_display_add_client_message_filter, gdk_display_add_client_message_filter ()
gdk_display_beep, gdk_display_beep ()
gdk_display_close, gdk_display_close ()
gdk_display_get_core_pointer, gdk_display_get_core_pointer ()
gdk_display_get_default, gdk_display_get_default ()
gdk_display_get_default_screen, gdk_display_get_default_screen ()
gdk_display_get_event, gdk_display_get_event ()
gdk_display_get_name, gdk_display_get_name ()
gdk_display_get_n_screens, gdk_display_get_n_screens ()
gdk_display_get_pointer, gdk_display_get_pointer ()
gdk_display_get_screen, gdk_display_get_screen ()
gdk_display_get_window_at_pointer, gdk_display_get_window_at_pointer ()
gdk_display_keyboard_ungrab, gdk_display_keyboard_ungrab ()
gdk_display_list_devices, gdk_display_list_devices ()
gdk_display_manager_get, gdk_display_manager_get ()
gdk_display_manager_get_default_display, gdk_display_manager_get_default_display ()
gdk_display_manager_list_displays, gdk_display_manager_list_displays ()
gdk_display_manager_set_default_display, gdk_display_manager_set_default_display ()
gdk_display_open, gdk_display_open ()
gdk_display_peek_event, gdk_display_peek_event ()
gdk_display_pointer_is_grabbed, gdk_display_pointer_is_grabbed ()
gdk_display_pointer_ungrab, gdk_display_pointer_ungrab ()
gdk_display_put_event, gdk_display_put_event ()
gdk_display_set_double_click_time, gdk_display_set_double_click_time ()
gdk_display_set_pointer_hooks, gdk_display_set_pointer_hooks ()
gdk_display_sync, gdk_display_sync ()
gdk_drag_find_window_for_screen, gdk_drag_find_window_for_screen ()
gdk_drag_get_protocol_for_display, gdk_drag_get_protocol_for_display ()
gdk_drawable_get_display, gdk_drawable_get_display ()
gdk_drawable_get_screen, gdk_drawable_get_screen ()
gdk_draw_pixbuf, gdk_draw_pixbuf ()
gdk_event_get_screen, gdk_event_get_screen ()
gdk_event_new, gdk_event_new ()
gdk_event_send_client_message_for_display, gdk_event_send_client_message_for_display ()
gdk_event_set_screen, gdk_event_set_screen ()
gdk_fontset_load_for_display, gdk_fontset_load_for_display ()
gdk_font_from_description_for_display, gdk_font_from_description_for_display ()
gdk_font_get_display, gdk_font_get_display ()
gdk_font_load_for_display, gdk_font_load_for_display ()
gdk_gc_get_screen, gdk_gc_get_screen ()
gdk_get_display_arg_name, gdk_get_display_arg_name ()
gdk_keymap_get_for_display, gdk_keymap_get_for_display ()
gdk_notify_startup_complete, gdk_notify_startup_complete ()
gdk_pango_context_get_for_screen, gdk_pango_context_get_for_screen ()
gdk_parse_args, gdk_parse_args ()
gdk_pixmap_foreign_new_for_display, gdk_pixmap_foreign_new_for_display ()
gdk_pixmap_lookup_for_display, gdk_pixmap_lookup_for_display ()
gdk_screen_broadcast_client_message, gdk_screen_broadcast_client_message ()
gdk_screen_get_default, gdk_screen_get_default ()
gdk_screen_get_default_colormap, gdk_screen_get_default_colormap ()
gdk_screen_get_display, gdk_screen_get_display ()
gdk_screen_get_height, gdk_screen_get_height ()
gdk_screen_get_height_mm, gdk_screen_get_height_mm ()
gdk_screen_get_monitor_at_point, gdk_screen_get_monitor_at_point ()
gdk_screen_get_monitor_at_window, gdk_screen_get_monitor_at_window ()
gdk_screen_get_monitor_geometry, gdk_screen_get_monitor_geometry ()
gdk_screen_get_number, gdk_screen_get_number ()
gdk_screen_get_n_monitors, gdk_screen_get_n_monitors ()
gdk_screen_get_rgb_colormap, gdk_screen_get_rgb_colormap ()
gdk_screen_get_rgb_visual, gdk_screen_get_rgb_visual ()
gdk_screen_get_root_window, gdk_screen_get_root_window ()
gdk_screen_get_setting, gdk_screen_get_setting ()
gdk_screen_get_system_colormap, gdk_screen_get_system_colormap ()
gdk_screen_get_system_visual, gdk_screen_get_system_visual ()
gdk_screen_get_toplevel_windows, gdk_screen_get_toplevel_windows ()
gdk_screen_get_width, gdk_screen_get_width ()
gdk_screen_get_width_mm, gdk_screen_get_width_mm ()
gdk_screen_list_visuals, gdk_screen_list_visuals ()
gdk_screen_make_display_name, gdk_screen_make_display_name ()
gdk_screen_set_default_colormap, gdk_screen_set_default_colormap ()
gdk_selection_owner_get_for_display, gdk_selection_owner_get_for_display ()
gdk_selection_owner_set_for_display, gdk_selection_owner_set_for_display ()
gdk_selection_send_notify_for_display, gdk_selection_send_notify_for_display ()
gdk_string_to_compound_text_for_display, gdk_string_to_compound_text_for_display ()
gdk_text_property_to_text_list_for_display, gdk_text_property_to_text_list_for_display ()
gdk_text_property_to_utf8_list_for_display, gdk_text_property_to_utf8_list_for_display ()
gdk_utf8_to_compound_text_for_display, gdk_utf8_to_compound_text_for_display ()
gdk_visual_get_screen, gdk_visual_get_screen ()
gdk_window_foreign_new_for_display, gdk_window_foreign_new_for_display ()
gdk_window_fullscreen, gdk_window_fullscreen ()
gdk_window_lookup_for_display, gdk_window_lookup_for_display ()
gdk_window_set_skip_pager_hint, gdk_window_set_skip_pager_hint ()
gdk_window_set_skip_taskbar_hint, gdk_window_set_skip_taskbar_hint ()
gdk_window_unfullscreen, gdk_window_unfullscreen ()
gdk_x11_atom_to_xatom_for_display, gdk_x11_atom_to_xatom_for_display ()
gdk_x11_colormap_foreign_new, gdk_x11_colormap_foreign_new ()
gdk_x11_display_get_xdisplay, gdk_x11_display_get_xdisplay ()
gdk_x11_display_grab, gdk_x11_display_grab ()
gdk_x11_display_ungrab, gdk_x11_display_ungrab ()
gdk_x11_get_xatom_by_name_for_display, gdk_x11_get_xatom_by_name_for_display ()
gdk_x11_get_xatom_name_for_display, gdk_x11_get_xatom_name_for_display ()
gdk_x11_lookup_xdisplay, gdk_x11_lookup_xdisplay ()
gdk_x11_screen_get_screen_number, gdk_x11_screen_get_screen_number ()
gdk_x11_screen_get_window_manager_name, gdk_x11_screen_get_window_manager_name ()
gdk_x11_screen_get_xscreen, gdk_x11_screen_get_xscreen ()
gdk_x11_screen_lookup_visual, gdk_x11_screen_lookup_visual ()
gdk_x11_screen_supports_net_wm_hint, gdk_x11_screen_supports_net_wm_hint ()
gdk_x11_xatom_to_atom_for_display, gdk_x11_xatom_to_atom_for_display ()
gdk_xid_table_lookup_for_display, gdk_xid_table_lookup_for_display ()


Index of new symbols in 2.4

G

gdk_cursor_new_from_pixbuf, gdk_cursor_new_from_pixbuf ()
gdk_display_flush, gdk_display_flush ()
gdk_display_get_default_cursor_size, gdk_display_get_default_cursor_size ()
gdk_display_get_default_group, gdk_display_get_default_group ()
gdk_display_get_maximal_cursor_size, gdk_display_get_maximal_cursor_size ()
gdk_display_set_double_click_distance, gdk_display_set_double_click_distance ()
gdk_display_supports_cursor_alpha, gdk_display_supports_cursor_alpha ()
gdk_display_supports_cursor_color, gdk_display_supports_cursor_color ()
gdk_drawable_copy_to_image, gdk_drawable_copy_to_image ()
gdk_spawn_command_line_on_screen, gdk_spawn_command_line_on_screen ()
gdk_spawn_on_screen, gdk_spawn_on_screen ()
gdk_spawn_on_screen_with_pipes, gdk_spawn_on_screen_with_pipes ()
gdk_threads_set_lock_functions, gdk_threads_set_lock_functions ()
gdk_window_get_group, gdk_window_get_group ()
gdk_window_set_accept_focus, gdk_window_set_accept_focus ()
gdk_window_set_keep_above, gdk_window_set_keep_above ()
gdk_window_set_keep_below, gdk_window_set_keep_below ()
gdk_x11_register_standard_event_type, gdk_x11_register_standard_event_type ()


Index of new symbols in 2.6

G

GdkEventOwnerChange, GdkEventOwnerChange
GdkPangoRenderer, GdkPangoRenderer
GdkPangoRendererClass, GdkPangoRendererClass
gdk_display_request_selection_notification, gdk_display_request_selection_notification ()
gdk_display_store_clipboard, gdk_display_store_clipboard ()
gdk_display_supports_clipboard_persistence, gdk_display_supports_clipboard_persistence ()
gdk_display_supports_selection_notification, gdk_display_supports_selection_notification ()
gdk_drag_drop_succeeded, gdk_drag_drop_succeeded ()
gdk_draw_glyphs_transformed, gdk_draw_glyphs_transformed ()
gdk_draw_trapezoids, gdk_draw_trapezoids ()
gdk_pango_renderer_get_default, gdk_pango_renderer_get_default ()
gdk_pango_renderer_new, gdk_pango_renderer_new ()
gdk_pango_renderer_set_drawable, gdk_pango_renderer_set_drawable ()
gdk_pango_renderer_set_gc, gdk_pango_renderer_set_gc ()
gdk_pango_renderer_set_override_color, gdk_pango_renderer_set_override_color ()
gdk_pango_renderer_set_stipple, gdk_pango_renderer_set_stipple ()
gdk_window_configure_finished, gdk_window_configure_finished ()
gdk_window_enable_synchronized_configure, gdk_window_enable_synchronized_configure ()
gdk_window_set_focus_on_map, gdk_window_set_focus_on_map ()
gdk_x11_window_set_user_time, gdk_x11_window_set_user_time ()


Index of new symbols in 2.8

G

GdkEventGrabBroken, GdkEventGrabBroken
gdk_cairo_create, gdk_cairo_create ()
gdk_cairo_rectangle, gdk_cairo_rectangle ()
gdk_cairo_region, gdk_cairo_region ()
gdk_cairo_set_source_color, gdk_cairo_set_source_color ()
gdk_cairo_set_source_pixbuf, gdk_cairo_set_source_pixbuf ()
gdk_cursor_get_image, gdk_cursor_get_image ()
gdk_cursor_new_from_name, gdk_cursor_new_from_name ()
gdk_display_warp_pointer, gdk_display_warp_pointer ()
gdk_screen_get_rgba_colormap, gdk_screen_get_rgba_colormap ()
gdk_screen_get_rgba_visual, gdk_screen_get_rgba_visual ()
gdk_window_move_region, gdk_window_move_region ()
gdk_window_set_urgency_hint, gdk_window_set_urgency_hint ()
gdk_x11_display_get_user_time, gdk_x11_display_get_user_time ()
gdk_x11_display_set_cursor_theme, gdk_x11_display_set_cursor_theme ()
gdk_x11_window_move_to_current_desktop, gdk_x11_window_move_to_current_desktop ()


Index of new symbols in 2.10

G

GdkScreen::composited-changed, The "composited-changed" signal
gdk_atom_intern_static_string, gdk_atom_intern_static_string ()
gdk_cairo_set_source_pixmap, gdk_cairo_set_source_pixmap ()
gdk_display_supports_input_shapes, gdk_display_supports_input_shapes ()
gdk_display_supports_shapes, gdk_display_supports_shapes ()
gdk_pixmap_foreign_new_for_screen, gdk_pixmap_foreign_new_for_screen ()
gdk_screen_get_active_window, gdk_screen_get_active_window ()
gdk_screen_get_font_options, gdk_screen_get_font_options ()
gdk_screen_get_resolution, gdk_screen_get_resolution ()
gdk_screen_get_window_stack, gdk_screen_get_window_stack ()
gdk_screen_is_composited, gdk_screen_is_composited ()
gdk_screen_set_font_options, gdk_screen_set_font_options ()
gdk_screen_set_resolution, gdk_screen_set_resolution ()
gdk_window_get_type_hint, gdk_window_get_type_hint ()
gdk_window_input_shape_combine_mask, gdk_window_input_shape_combine_mask ()
gdk_window_input_shape_combine_region, gdk_window_input_shape_combine_region ()
gdk_window_merge_child_input_shapes, gdk_window_merge_child_input_shapes ()
gdk_window_set_child_input_shapes, gdk_window_set_child_input_shapes ()


Multi-head Support Overview

Multi-head Support Overview — Overview of GdkDisplay and GdkScreen

Overview

Multihead support is based around two main object types:

  • GdkDisplay

  • GdkScreen

GdkDisplay objects are the GDK representation of the X Display which can be described as a workstation consisting of a keyboard a pointing device (such as a mouse) and one or more screens. It is used to open and keep track of various GdkScreen objects currently instanciated by the application. It is also used to grab and release the keyboard and the mouse pointer.

GdkScreen objects are the GDK representation of a physical screen. It is used throughout GDK and GTK+ to specify which screen the top level windows are to be displayed on. It is also used to query the screen specification and default settings such as the default colormap (gdk_screen_get_default_colormap()), the screen width (gdk_screen_get_width()), etc.

The following code samples demonstrate common usage of the objects described above.

Example 2. Testing the number of screen on the current display

gint num_screen = 0;
gchar *displayname = NULL;
GdkScreen **screen_list;
GdkDisplay *display;

gtk_init (&argc, &argv);

display = gdk_display_get_default ();
num_screen = gdk_display_get_n_screens (display);
displayname = gdk_display_get_name (display);
if (num_screen <= 1)
  {
    printf ("This Xserver (%s) manages only one screen. exiting...\n",
            displayname);
    exit (1);
  }
else
  {
    printf ("This Xserver (%s) manages %d screens.\n", displayname,
            num_screen);
  }

Example 3. Opening a second display

gchar *second_screen_name;
GdkDisplay *second_display;
GdkScreen *second_screen;
GtkWidget *window;

gtk_init (&argc, &argv);

/* screen2_name needs to be initialized before calling
/* gdk_display_new() */
second_display = gdk_display_new (&argc, &argv, second_screen_name);
if (second_display)
    second_screen = gdk_display_get_default_screen (second_display);
else
  {
    g_print ("Can't open display :\n\t%s\n\n",
          second_screen_name);
    exit (1);
  }
/* now GdkScreen can be assigned to GtkWindows */

window = gtk_window_new (GTK_WINDOW_TOPLEVEL);
gtk_window_set_screen (window, second_screen);

See Also

GdkDisplay | the GDK Object used to represent and manipulate display related data
GdkScreen | the GDK Object used to represent and query screen related data


Prev Home GDK Reference Manual Next

API Reference


Appendix A. Porting applications from Imlib to gdk-pixbuf

This appendix contains the basic steps needed to port an application that uses the Imlib library to use gdk-pixbuf instead.

Note

This appendix refers to version 1 of the Imlib library; this discussion is not relevant to Imlib 2. Also, we discuss the gdk_imlib API instead of the Xlib-based API.

Introduction

Prior to the GNOME 1.2 platform, the Imlib library was the preferred way of loading and rendering images in GNOME applications. Unfortunately, Imlib has important design limitations that make it hard to write efficient and highly modular applications.

The gdk-pixbuf library was designed as a solution to Imlib's shortcomings. It provides a simple, orthogonal API and convenience functions for the most common operations. In addition, it supports full transparency information for images, or alpha channel. More importantly, it has well-defined semantics for memory management through the use of reference counting; Imlib has an intractably complex memory management mechanism and cache that will make your head spin.


Differences between Imlib and gdk-pixbuf

Generally, applications that use Imlib do not have to be changed extensively to use gdk-pixbuf; its simple and flexible API makes things easy. This section describes the differences between Imlib and gdk-pixbuf; you should take these into account when modifying your applications to use gdk-pixbuf.

Initialization

The gdk-pixbuf library does not need to be initialized.

Note

In GNOME applications you normally don't need to initialize Imlib, as gnome_init() calls gdk_imlib_init() automatically.

Memory management

The gdk-pixbuf library provides a simple, well-defined memory management mechanism for images in the form of reference counting. This makes it very convenient to use for large-scale applications that need to share images between different parts of the program. In stark contrast, Imlib has a terribly complex mechanism of an image and pixmap cache which makes it very hard for applications to share image structures between different parts of the program. Unfortunately this mechanism makes things very prone to memory leaks and tricky bugs.

The basic principle in gdk-pixbuf is that when you obtain a new GdkPixbuf structure, it is created with an initial reference count of 1. When another part of the program wants to keep a reference to the pixbuf, it should call g_object_ref(); this will increase the reference count by 1. When some part of the program does not need to keep a reference to a pixbuf anymore and wants to release the pixbuf, it should call g_object_unref(); this will decrease the reference count by 1. When the reference count drops to zero, the pixbuf gets destroyed or finalized and its memory is freed.

For applications that need to implement a cache of loaded images, gdk-pixbuf provides a way to hook to the last unreference operation of a pixbuf; instead of finalizing the pixbuf, the user-installed hook can decide to keep it around in a cache instead.

Finally, gdk-pixbuf does not provide a cache of rendered pixmaps. This is unnecessary for most applications, since the scaling and rendering functions are quite fast and applications may need to use subtly different values each time they call these functions, for example, to take into account dithering and zooming offsets.

Most applications will simply need to call g_object_ref() when they want to keep an extra reference to a pixbuf, and then g_object_unref() when they are done with it.

The Rendering Process

The gdk-pixbuf library has the policy of always rendering pixbufs to GDK drawables you provide; it will not create them for you. This is in general more flexible than Imlib's policy of always creating a pixmap and making you use that instead.

The disadvantage of always having a pixmap created for you is that it wastes memory in the X server if you intend to copy that rendered data onto another drawable, for example, the final destination window or a temporary pixmap for drawing. This is the most common case, unfortunately, so the Imlib policy introduces unnecessary copying.

Also, Imlib can only render pixmaps that are the whole size of the source image; you cannot render just a subset region of the image. This is inconvenient for applications that need to render small portions at a time, such as applications that do scrolling. Since the whole image must be rendered at a time, this can lead to performance and memory usage problems.

The gdk-pixbuf library lets you render any rectangular region from an image onto any drawable that you provide. This lets the application have fine control the way images are rendered.


Converting Applications to gdk-pixbuf

This sections describes the actual changes you need to make in an Imlib program to make it use gdk-pixbuf instead.

Image loading and creation

The gdk-pixbuf library can load image files synchronously (i.e. with a single function call), create images from RGB data in memory, and as a convenience, it can also create images from inline XPM data.

To load an image file in a single function call, simply use gdk_pixbuf_new_from_file(). Note that this will make the program block until the whole file has been read. This function effectively replaces gdk_imlib_load_image().

If you have RGB data in memory, you can use gdk_pixbuf_new_from_data() to create a pixbuf out of it; this is a replacement for gdk_imlib_create_image_from_data(). gdk-pixbuf does not copy the image data; it is up to you to define the ownership policy by providing a destroy notification function that will be called when the image data needs to be freed. The function you provide can then free the data or do something else, as appropriate.

As a convenience, you can use the gdk_pixbuf_new_from_xpm_data() function to create a pixbuf out of inline XPM data that was compiled into your C program. This is a replacement for gdk_imlib_create_image_from_xpm_data().

After you have created a pixbuf, you can manipulate it in any way you please and then finally call g_object_unref() when you are done with it. This can be thought of as a replacement for gdk_imlib_destroy_image() but with much cleaner semantics.

Rendering Images

Applications that use Imlib must first call gdk_imlib_render() to render the whole image data onto a pixmap that Imlib creates. Then they must copy that pixmap's data into the final destination for the image.

In contrast, gdk-pixbuf provides convenience functions to render arbitrary rectangular regions of an image onto a drawable that your application provides. You can use gdk_pixbuf_render_to_drawable() or gdk_pixbuf_render_to_drawable_alpha() to do this; having your application provide the destination drawable and specify an arbitrary region means your application has complete control over the way images are rendered.

As a convenience, gdk-pixbuf also provides the gdk_pixbuf_render_pixmap_and_mask() function; this will create new pixmap and mask drawables for a whole pixbuf and render the image data onto them. Only trivially simple applications should find a use for this function, since usually you want finer control of how things are rendered.

Scaling Images

Imlib lets you render scaled image data at the time you call gdk_imlib_render(). Again, this unfortunately scales and renders the whole image onto a new pixmap.

gdk-pixbuf provides a number of functions that do scaling of arbitrary regions of a source pixbuf onto a destination one. These functions can also perform compositing operations against the data in the destination pixbuf or against a solid color or a colored checkerboard. [1]

Very simple applications may find it sufficient to use gdk_pixbuf_scale_simple() or gdk_pixbuf_composite_color_simple(). These functions scale the whole source image at a time and create a new pixbuf with the result.

More sophisticated applications will need to use gdk_pixbuf_scale(), gdk_pixbuf_composite(), or gdk_pixbuf_composite_color() instead. These functions let you scale and composite an arbitrary region of the source pixbuf onto a destination pixbuf that you provide.

Getting Image Data from a Drawable

Imlib lets you create an image by fetching a drawable's contents from the X server and converting those into RGB data. This is done with the gdk_imlib_create_image_from_drawable() function.

gdk-pixbuf provides the gdk_pixbuf_get_from_drawable() function instead. It lets you specify a destination pixbuf instead of always creating a new one for you.

[1] You can use a colored checkerboard as the background for compositing when you want to provide a visual indication that the image has partially opaque areas. This is normally used in image editing and viewing programs.

Compositing against a single solid color is actually a special case of a checkerboard; it simply uses checks of the same color.


Animations

Animations — Animated images.

Synopsis

#include <gdk-pixbuf/gdk-pixbuf.h>

                    GdkPixbufAnimation;
                    GdkPixbufAnimationIter;
GdkPixbufAnimation* gdk_pixbuf_animation_new_from_file  (const char *filename,
                                                         GError **error);
GdkPixbufAnimation* gdk_pixbuf_animation_ref            (GdkPixbufAnimation *animation);
void                gdk_pixbuf_animation_unref          (GdkPixbufAnimation *animation);
int                 gdk_pixbuf_animation_get_width      (GdkPixbufAnimation *animation);
int                 gdk_pixbuf_animation_get_height     (GdkPixbufAnimation *animation);
GdkPixbufAnimationIter* gdk_pixbuf_animation_get_iter   (GdkPixbufAnimation *animation,
                                                         const GTimeVal *start_time);
gboolean            gdk_pixbuf_animation_is_static_image
                                                        (GdkPixbufAnimation *animation);
GdkPixbuf*          gdk_pixbuf_animation_get_static_image
                                                        (GdkPixbufAnimation *animation);
gboolean            gdk_pixbuf_animation_iter_advance   (GdkPixbufAnimationIter *iter,
                                                         const GTimeVal *current_time);
int                 gdk_pixbuf_animation_iter_get_delay_time
                                                        (GdkPixbufAnimationIter *iter);
gboolean            gdk_pixbuf_animation_iter_on_currently_loading_frame
                                                        (GdkPixbufAnimationIter *iter);
GdkPixbuf*          gdk_pixbuf_animation_iter_get_pixbuf
                                                        (GdkPixbufAnimationIter *iter);

                    GdkPixbufSimpleAnim;
GdkPixbufSimpleAnim* gdk_pixbuf_simple_anim_new         (gint width,
                                                         gint height,
                                                         gfloat rate);
void                gdk_pixbuf_simple_anim_add_frame    (GdkPixbufSimpleAnim *animation,
                                                         GdkPixbuf *pixbuf);

Object Hierarchy

  GObject
   +----GdkPixbufAnimation

  GObject
   +----GdkPixbufAnimationIter

Description

The gdk-pixbuf library provides a simple mechanism to load and represent animations. An animation is conceptually a series of frames to be displayed over time. Each frame is the same size. The animation may not be represented as a series of frames internally; for example, it may be stored as a sprite and instructions for moving the sprite around a background. To display an animation you don't need to understand its representation, however; you just ask gdk-pixbuf what should be displayed at a given point in time.

Details

GdkPixbufAnimation

typedef struct _GdkPixbufAnimation GdkPixbufAnimation;

And opaque struct representing an animation.

GdkPixbufAnimationIter

typedef struct _GdkPixbufAnimationIter GdkPixbufAnimationIter;

And opaque struct representing an iterator which points to a certain position in an animation.

gdk_pixbuf_animation_new_from_file ()

GdkPixbufAnimation* gdk_pixbuf_animation_new_from_file  (const char *filename,
                                                         GError **error);

Creates a new animation by loading it from a file. The file format is detected automatically. If the file's format does not support multi-frame images, then an animation with a single frame will be created. Possible errors are in the GDK_PIXBUF_ERROR and G_FILE_ERROR domains.

filename : | Name of file to load, in the GLib file name encoding
error : | return location for error
Returns : | A newly-created animation with a reference count of 1, or NULL if any of several error conditions ocurred: the file could not be opened, there was no loader for the file's format, there was not enough memory to allocate the image buffer, or the image file contained invalid data.

gdk_pixbuf_animation_ref ()

GdkPixbufAnimation* gdk_pixbuf_animation_ref            (GdkPixbufAnimation *animation);

Warning

gdk_pixbuf_animation_ref is deprecated and should not be used in newly-written code. Use g_object_ref().

Adds a reference to an animation.

animation : | An animation.
Returns : | The same as the animation argument.

gdk_pixbuf_animation_unref ()

void                gdk_pixbuf_animation_unref          (GdkPixbufAnimation *animation);

Warning

gdk_pixbuf_animation_unref is deprecated and should not be used in newly-written code. Use g_object_unref().

Removes a reference from an animation.

animation : An animation.

gdk_pixbuf_animation_get_width ()

int                 gdk_pixbuf_animation_get_width      (GdkPixbufAnimation *animation);

Queries the width of the bounding box of a pixbuf animation.

animation : | An animation.
Returns : | Width of the bounding box of the animation.

gdk_pixbuf_animation_get_height ()

int                 gdk_pixbuf_animation_get_height     (GdkPixbufAnimation *animation);

Queries the height of the bounding box of a pixbuf animation.

animation : | An animation.
Returns : | Height of the bounding box of the animation.

gdk_pixbuf_animation_get_iter ()

GdkPixbufAnimationIter* gdk_pixbuf_animation_get_iter   (GdkPixbufAnimation *animation,
                                                         const GTimeVal *start_time);

Get an iterator for displaying an animation. The iterator provides the frames that should be displayed at a given time. It should be freed after use with g_object_unref().

start_time would normally come from g_get_current_time(), and marks the beginning of animation playback. After creating an iterator, you should immediately display the pixbuf returned by gdk_pixbuf_animation_iter_get_pixbuf(). Then, you should install a timeout (with g_timeout_add()) or by some other mechanism ensure that you'll update the image after gdk_pixbuf_animation_iter_get_delay_time() milliseconds. Each time the image is updated, you should reinstall the timeout with the new, possibly-changed delay time.

As a shortcut, if start_time is NULL, the result of g_get_current_time() will be used automatically.

To update the image (i.e. possibly change the result of gdk_pixbuf_animation_iter_get_pixbuf() to a new frame of the animation), call gdk_pixbuf_animation_iter_advance().

If you're using GdkPixbufLoader, in addition to updating the image after the delay time, you should also update it whenever you receive the area_updated signal and gdk_pixbuf_animation_iter_on_currently_loading_frame() returns TRUE. In this case, the frame currently being fed into the loader has received new data, so needs to be refreshed. The delay time for a frame may also be modified after an area_updated signal, for example if the delay time for a frame is encoded in the data after the frame itself. So your timeout should be reinstalled after any area_updated signal.

A delay time of -1 is possible, indicating "infinite."

animation : | a GdkPixbufAnimation
start_time : | time when the animation starts playing
Returns : | an iterator to move over the animation

gdk_pixbuf_animation_is_static_image ()

gboolean            gdk_pixbuf_animation_is_static_image
                                                        (GdkPixbufAnimation *animation);

If you load a file with gdk_pixbuf_animation_new_from_file() and it turns out to be a plain, unanimated image, then this function will return TRUE. Use gdk_pixbuf_animation_get_static_image() to retrieve the image.

animation : | a GdkPixbufAnimation
Returns : | TRUE if the "animation" was really just an image

gdk_pixbuf_animation_get_static_image ()

GdkPixbuf*          gdk_pixbuf_animation_get_static_image
                                                        (GdkPixbufAnimation *animation);

If an animation is really just a plain image (has only one frame), this function returns that image. If the animation is an animation, this function returns a reasonable thing to display as a static unanimated image, which might be the first frame, or something more sophisticated. If an animation hasn't loaded any frames yet, this function will return NULL.

animation : | a GdkPixbufAnimation
Returns : | unanimated image representing the animation

gdk_pixbuf_animation_iter_advance ()

gboolean            gdk_pixbuf_animation_iter_advance   (GdkPixbufAnimationIter *iter,
                                                         const GTimeVal *current_time);

Possibly advances an animation to a new frame. Chooses the frame based on the start time passed to gdk_pixbuf_animation_get_iter().

current_time would normally come from g_get_current_time(), and must be greater than or equal to the time passed to gdk_pixbuf_animation_get_iter(), and must increase or remain unchanged each time gdk_pixbuf_animation_iter_get_pixbuf() is called. That is, you can't go backward in time; animations only play forward.

As a shortcut, pass NULL for the current time and g_get_current_time() will be invoked on your behalf. So you only need to explicitly pass current_time if you're doing something odd like playing the animation at double speed.

If this function returns FALSE, there's no need to update the animation display, assuming the display had been rendered prior to advancing; if TRUE, you need to call gdk_animation_iter_get_pixbuf() and update the display with the new pixbuf.

iter : | a GdkPixbufAnimationIter
current_time : | current time
Returns : | TRUE if the image may need updating

gdk_pixbuf_animation_iter_get_delay_time ()

int                 gdk_pixbuf_animation_iter_get_delay_time
                                                        (GdkPixbufAnimationIter *iter);

Gets the number of milliseconds the current pixbuf should be displayed, or -1 if the current pixbuf should be displayed forever. g_timeout_add() conveniently takes a timeout in milliseconds, so you can use a timeout to schedule the next update.

iter : | an animation iterator
Returns : | delay time in milliseconds (thousandths of a second)

gdk_pixbuf_animation_iter_on_currently_loading_frame ()

gboolean            gdk_pixbuf_animation_iter_on_currently_loading_frame
                                                        (GdkPixbufAnimationIter *iter);

Used to determine how to respond to the area_updated signal on GdkPixbufLoader when loading an animation. area_updated is emitted for an area of the frame currently streaming in to the loader. So if you're on the currently loading frame, you need to redraw the screen for the updated area.

iter : | a GdkPixbufAnimationIter
Returns : | TRUE if the frame we're on is partially loaded, or the last frame

gdk_pixbuf_animation_iter_get_pixbuf ()

GdkPixbuf*          gdk_pixbuf_animation_iter_get_pixbuf
                                                        (GdkPixbufAnimationIter *iter);

Gets the current pixbuf which should be displayed; the pixbuf will be the same size as the animation itself (gdk_pixbuf_animation_get_width(), gdk_pixbuf_animation_get_height()). This pixbuf should be displayed for gdk_pixbuf_animation_iter_get_delay_time() milliseconds. The caller of this function does not own a reference to the returned pixbuf; the returned pixbuf will become invalid when the iterator advances to the next frame, which may happen anytime you call gdk_pixbuf_animation_iter_advance(). Copy the pixbuf to keep it (don't just add a reference), as it may get recycled as you advance the iterator.

iter : | an animation iterator
Returns : | the pixbuf to be displayed

GdkPixbufSimpleAnim

typedef struct _GdkPixbufSimpleAnim GdkPixbufSimpleAnim;

An

gdk_pixbuf_simple_anim_new ()

GdkPixbufSimpleAnim* gdk_pixbuf_simple_anim_new         (gint width,
                                                         gint height,
                                                         gfloat rate);

Creates a new, empty animation.

width : | the width of the animation
height : | the height of the animation
rate : | the speed of the animation, in frames per second
Returns : | a newly allocated GdkPixbufSimpleAnim

Since 2.8

gdk_pixbuf_simple_anim_add_frame ()

void                gdk_pixbuf_simple_anim_add_frame    (GdkPixbufSimpleAnim *animation,
                                                         GdkPixbuf *pixbuf);

Adds a new frame to animation. The pixbuf must have the dimensions specified when the animation was constructed.

animation : | a GdkPixbufSimpleAnim
pixbuf : | the pixbuf to add

Since 2.8

See Also

GdkPixbufLoader


Image Data in Memory

Image Data in Memory — Creating a pixbuf from image data that is already in memory.

Synopsis

#include <gdk-pixbuf/gdk-pixbuf.h>

GdkPixbuf*          gdk_pixbuf_new                      (GdkColorspace colorspace,
                                                         gboolean has_alpha,
                                                         int bits_per_sample,
                                                         int width,
                                                         int height);
GdkPixbuf*          gdk_pixbuf_new_from_data            (const guchar *data,
                                                         GdkColorspace colorspace,
                                                         gboolean has_alpha,
                                                         int bits_per_sample,
                                                         int width,
                                                         int height,
                                                         int rowstride,
                                                         GdkPixbufDestroyNotify destroy_fn,
                                                         gpointer destroy_fn_data);
GdkPixbuf*          gdk_pixbuf_new_from_xpm_data        (const char **data);
GdkPixbuf*          gdk_pixbuf_new_from_inline          (gint data_length,
                                                         const guint8 *data,
                                                         gboolean copy_pixels,
                                                         GError **error);
GdkPixbuf*          gdk_pixbuf_new_subpixbuf            (GdkPixbuf *src_pixbuf,
                                                         int src_x,
                                                         int src_y,
                                                         int width,
                                                         int height);
GdkPixbuf*          gdk_pixbuf_copy                     (const GdkPixbuf *pixbuf);

Description

The most basic way to create a pixbuf is to wrap an existing pixel buffer with a GdkPixbuf structure. You can use the gdk_pixbuf_new_from_data() function to do this You need to specify the destroy notification function that will be called when the data buffer needs to be freed; this will happen when a GdkPixbuf is finalized by the reference counting functions If you have a chunk of static data compiled into your application, you can pass in NULL as the destroy notification function so that the data will not be freed.

The gdk_pixbuf_new() function can be used as a convenience to create a pixbuf with an empty buffer. This is equivalent to allocating a data buffer using malloc() and then wrapping it with gdk_pixbuf_new_from_data(). The gdk_pixbuf_new() function will compute an optimal rowstride so that rendering can be performed with an efficient algorithm.

As a special case, you can use the gdk_pixbuf_new_from_xpm_data() function to create a pixbuf from inline XPM image data.

You can also copy an existing pixbuf with the gdk_pixbuf_copy() function. This is not the same as just doing a g_object_ref() on the old pixbuf; the copy function will actually duplicate the pixel data in memory and create a new GdkPixbuf structure for it.

Details

gdk_pixbuf_new ()

GdkPixbuf*          gdk_pixbuf_new                      (GdkColorspace colorspace,
                                                         gboolean has_alpha,
                                                         int bits_per_sample,
                                                         int width,
                                                         int height);

Creates a new GdkPixbuf structure and allocates a buffer for it. The buffer has an optimal rowstride. Note that the buffer is not cleared; you will have to fill it completely yourself.

colorspace : | Color space for image
has_alpha : | Whether the image should have transparency information
bits_per_sample : | Number of bits per color sample
width : | Width of image in pixels, must be > 0
height : | Height of image in pixels, must be > 0
Returns : | A newly-created GdkPixbuf with a reference count of 1, or NULL if not enough memory could be allocated for the image buffer.

gdk_pixbuf_new_from_data ()

GdkPixbuf*          gdk_pixbuf_new_from_data            (const guchar *data,
                                                         GdkColorspace colorspace,
                                                         gboolean has_alpha,
                                                         int bits_per_sample,
                                                         int width,
                                                         int height,
                                                         int rowstride,
                                                         GdkPixbufDestroyNotify destroy_fn,
                                                         gpointer destroy_fn_data);

Creates a new GdkPixbuf out of in-memory image data. Currently only RGB images with 8 bits per sample are supported.

data : | Image data in 8-bit/sample packed format
colorspace : | Colorspace for the image data
has_alpha : | Whether the data has an opacity channel
bits_per_sample : | Number of bits per sample
width : | Width of the image in pixels, must be > 0
height : | Height of the image in pixels, must be > 0
rowstride : | Distance in bytes between row starts
destroy_fn : | Function used to free the data when the pixbuf's reference count drops to zero, or NULL if the data should not be freed
destroy_fn_data : | Closure data to pass to the destroy notification function
Returns : | A newly-created GdkPixbuf structure with a reference count of 1.

gdk_pixbuf_new_from_xpm_data ()

GdkPixbuf*          gdk_pixbuf_new_from_xpm_data        (const char **data);

Creates a new pixbuf by parsing XPM data in memory. This data is commonly the result of including an XPM file into a program's C source.

data : | Pointer to inline XPM data.
Returns : | A newly-created pixbuf with a reference count of 1.

gdk_pixbuf_new_from_inline ()

GdkPixbuf*          gdk_pixbuf_new_from_inline          (gint data_length,
                                                         const guint8 *data,
                                                         gboolean copy_pixels,
                                                         GError **error);

Create a GdkPixbuf from a flat representation that is suitable for storing as inline data in a program. This is useful if you want to ship a program with images, but don't want to depend on any external files.

GTK+ ships with a program called gdk-pixbuf-csource which allows for conversion of GdkPixbufs into such a inline representation. In almost all cases, you should pass the --raw flag to gdk-pixbuf-csource. A sample invocation would be:

 gdk-pixbuf-csource --raw --name=myimage_inline myimage.png

For the typical case where the inline pixbuf is read-only static data, you don't need to copy the pixel data unless you intend to write to it, so you can pass FALSE for copy_pixels. (If you pass --rle to gdk-pixbuf-csource, a copy will be made even if copy_pixels is FALSE, so using this option is generally a bad idea.)

If you create a pixbuf from const inline data compiled into your program, it's probably safe to ignore errors and disable length checks, since things will always succeed:

pixbuf = gdk_pixbuf_new_from_inline (-1, myimage_inline, FALSE, NULL);

For non-const inline data, you could get out of memory. For untrusted inline data located at runtime, you could have corrupt inline data in addition.

data_length : | Length in bytes of the data argument or -1 to disable length checks
data : | Byte data containing a serialized GdkPixdata structure
copy_pixels : | Whether to copy the pixel data, or use direct pointers data for the resulting pixbuf
error : | GError return location, may be NULL to ignore errors
Returns : | A newly-created GdkPixbuf structure with a reference, count of 1, or NULL if an error occurred.

gdk_pixbuf_new_subpixbuf ()

GdkPixbuf*          gdk_pixbuf_new_subpixbuf            (GdkPixbuf *src_pixbuf,
                                                         int src_x,
                                                         int src_y,
                                                         int width,
                                                         int height);

Creates a new pixbuf which represents a sub-region of src_pixbuf. The new pixbuf shares its pixels with the original pixbuf, so writing to one affects both. The new pixbuf holds a reference to src_pixbuf, so src_pixbuf will not be finalized until the new pixbuf is finalized.

src_pixbuf : | a GdkPixbuf
src_x : | X coord in src_pixbuf
src_y : | Y coord in src_pixbuf
width : | width of region in src_pixbuf
height : | height of region in src_pixbuf
Returns : | a new pixbuf

gdk_pixbuf_copy ()

GdkPixbuf*          gdk_pixbuf_copy                     (const GdkPixbuf *pixbuf);

Creates a new GdkPixbuf with a copy of the information in the specified pixbuf.

pixbuf : | A pixbuf.
Returns : | A newly-created pixbuf with a reference count of 1, or NULL if not enough memory could be allocated.

See Also

gdk_pixbuf_finalize().


gdk-pixbuf-csource

gdk-pixbuf-csource — C code generation utility for GdkPixbuf images

Synopsis

gdk-pixbuf-csource [options] [image]

gdk-pixbuf-csource [options] --build-list [ [name] [image] ...]

Description

gdk-pixbuf-csource is a small utility that generates C code containing images, useful for compiling images directly into programs.

Invocation

gdk-pixbuf-csource either takes as input one image file name to generate code for, or, using the --build-list option, a list of (name, image) pairs to generate code for a list of images into named variables.

Options

--stream | Generate pixbuf data stream (a single string containing a serialized GdkPixdata structure in network byte order).
--struct | Generate GdkPixdata structure (needs the GdkPixdata structure definition from gdk-pixdata.h).
--macros | Generate *_ROWSTRIDE, *_WIDTH, *_HEIGHT, *_BYTES_PER_PIXEL and *_RLE_PIXEL_DATA or *_PIXEL_DATA macro definitions for the image.
--rle | Enables run-length encoding for the generated pixel data (default).
--raw | Disables run-length encoding for the generated pixel data.
--extern | Generate extern symbols.
--static | Generate static symbols (default).
--decoder | Provide a *_RUN_LENGTH_DECODE(image_buf, rle_data, size, bpp) macro definition to decode run-length encoded image data.
--name=identifier | Specifies the identifier name (prefix) for the generated variables or macros (useful only if --build-list was not specified).
--build-list | Enables (name, image) pair parsing mode.
-h, --help | Print brief help and exit.
-v, --version | Print version and exit.
--g-fatal-warnings | Make warnings fatal (causes the program to abort).

See also

The GdkPixbuf documentation, shipped with the Gtk+ distribution, available from www.gtk.org.

Bugs

The runlength encoder gets out of sync with the pixel boundaries, since it includes the rowstride padding in the encoded stream. Furthermore, it generates pixbufs with suboptimal rowstride in some cases.

Author

gdk-pixbuf-csource was written by Tim Janik <timj@gtk.org>.

This manual page was provided by Tim Janik <timj@gtk.org>.


File Loading

File Loading — Loading a pixbuf from a file.

Synopsis

#include <gdk-pixbuf/gdk-pixbuf.h>

GdkPixbuf*          gdk_pixbuf_new_from_file            (const char *filename,
                                                         GError **error);
GdkPixbuf*          gdk_pixbuf_new_from_file_at_size    (const char *filename,
                                                         int width,
                                                         int height,
                                                         GError **error);
GdkPixbuf*          gdk_pixbuf_new_from_file_at_scale   (const char *filename,
                                                         int width,
                                                         int height,
                                                         gboolean preserve_aspect_ratio,
                                                         GError **error);
GdkPixbufFormat*    gdk_pixbuf_get_file_info            (const gchar *filename,
                                                         gint *width,
                                                         gint *height);

Description

The gdk-pixbuf library provides a simple mechanism for loading an image from a file in synchronous fashion. This means that the library takes control of the application while the file is being loaded; from the user's point of view, the application will block until the image is done loading.

This interface can be used by applications in which blocking is acceptable while an image is being loaded. It can also be used to load small images in general. Applications that need progressive loading can use the GdkPixbufLoader functionality instead.

Details

gdk_pixbuf_new_from_file ()

GdkPixbuf*          gdk_pixbuf_new_from_file            (const char *filename,
                                                         GError **error);

Creates a new pixbuf by loading an image from a file. The file format is detected automatically. If NULL is returned, then error will be set. Possible errors are in the GDK_PIXBUF_ERROR and G_FILE_ERROR domains.

filename : | Name of file to load, in the GLib file name encoding
error : | Return location for an error
Returns : | A newly-created pixbuf with a reference count of 1, or NULL if any of several error conditions occurred: the file could not be opened, there was no loader for the file's format, there was not enough memory to allocate the image buffer, or the image file contained invalid data.

gdk_pixbuf_new_from_file_at_size ()

GdkPixbuf*          gdk_pixbuf_new_from_file_at_size    (const char *filename,
                                                         int width,
                                                         int height,
                                                         GError **error);

Creates a new pixbuf by loading an image from a file. The file format is detected automatically. If NULL is returned, then error will be set. Possible errors are in the GDK_PIXBUF_ERROR and G_FILE_ERROR domains. The image will be scaled to fit in the requested size, preserving the image's aspect ratio.

filename : | Name of file to load, in the GLib file name encoding
width : | The width the image should have or -1 to not constrain the width
height : | The height the image should have or -1 to not constrain the height
error : | Return location for an error
Returns : | A newly-created pixbuf with a reference count of 1, or NULL if any of several error conditions occurred: the file could not be opened, there was no loader for the file's format, there was not enough memory to allocate the image buffer, or the image file contained invalid data.

Since 2.4

gdk_pixbuf_new_from_file_at_scale ()

GdkPixbuf*          gdk_pixbuf_new_from_file_at_scale   (const char *filename,
                                                         int width,
                                                         int height,
                                                         gboolean preserve_aspect_ratio,
                                                         GError **error);

Creates a new pixbuf by loading an image from a file. The file format is detected automatically. If NULL is returned, then error will be set. Possible errors are in the GDK_PIXBUF_ERROR and G_FILE_ERROR domains. The image will be scaled to fit in the requested size, optionally preserving the image's aspect ratio.

When preserving the aspect ratio, a width of -1 will cause the image to be scaled to the exact given height, and a height of -1 will cause the image to be scaled to the exact given width. When not preserving aspect ratio, a width or height of -1 means to not scale the image at all in that dimension. Negative values for width and height are allowed since 2.8.

filename : | Name of file to load, in the GLib file name encoding
width : | The width the image should have or -1 to not constrain the width
height : | The height the image should have or -1 to not constrain the height
preserve_aspect_ratio : | TRUE to preserve the image's aspect ratio
error : | Return location for an error
Returns : | A newly-created pixbuf with a reference count of 1, or NULL if any of several error conditions occurred: the file could not be opened, there was no loader for the file's format, there was not enough memory to allocate the image buffer, or the image file contained invalid data.

Since 2.6

gdk_pixbuf_get_file_info ()

GdkPixbufFormat*    gdk_pixbuf_get_file_info            (const gchar *filename,
                                                         gint *width,
                                                         gint *height);

Parses an image file far enough to determine its format and size.

filename : | The name of the file to identify.
width : | Return location for the width of the image, or NULL
height : | Return location for the height of the image, or NULL
Returns : | A GdkPixbufFormat describing the image format of the file or NULL if the image format wasn't recognized. The return value is owned by GdkPixbuf and should not be freed.

Since 2.4

See Also

GdkPixbufLoader.


File saving

File saving — Saving a pixbuf to a file.

Synopsis

#include <gdk-pixbuf/gdk-pixbuf.h>

gboolean            gdk_pixbuf_savev                    (GdkPixbuf *pixbuf,
                                                         const char *filename,
                                                         const char *type,
                                                         char **option_keys,
                                                         char **option_values,
                                                         GError **error);
gboolean            gdk_pixbuf_save                     (GdkPixbuf *pixbuf,
                                                         const char *filename,
                                                         const char *type,
                                                         GError **error,
                                                         ...);
gboolean            (*GdkPixbufSaveFunc)                (const gchar *buf,
                                                         gsize count,
                                                         GError **error,
                                                         gpointer data);
gboolean            gdk_pixbuf_save_to_callback         (GdkPixbuf *pixbuf,
                                                         GdkPixbufSaveFunc save_func,
                                                         gpointer user_data,
                                                         const char *type,
                                                         GError **error,
                                                         ...);
gboolean            gdk_pixbuf_save_to_callbackv        (GdkPixbuf *pixbuf,
                                                         GdkPixbufSaveFunc save_func,
                                                         gpointer user_data,
                                                         const char *type,
                                                         char **option_keys,
                                                         char **option_values,
                                                         GError **error);
gboolean            gdk_pixbuf_save_to_buffer           (GdkPixbuf *pixbuf,
                                                         gchar **buffer,
                                                         gsize *buffer_size,
                                                         const char *type,
                                                         GError **error,
                                                         ...);
gboolean            gdk_pixbuf_save_to_bufferv          (GdkPixbuf *pixbuf,
                                                         gchar **buffer,
                                                         gsize *buffer_size,
                                                         const char *type,
                                                         char **option_keys,
                                                         char **option_values,
                                                         GError **error);

Description

These functions allow to save a GdkPixbuf in a number of file formats. The formatted data can be written to a file or to a memory buffer. gdk-pixbuf can also call a user-defined callback on the data, which allows to e.g. write the image to a socket or store it in a database.

Details

gdk_pixbuf_savev ()

gboolean            gdk_pixbuf_savev                    (GdkPixbuf *pixbuf,
                                                         const char *filename,
                                                         const char *type,
                                                         char **option_keys,
                                                         char **option_values,
                                                         GError **error);

Saves pixbuf to a file in type, which is currently "jpeg", "png", "tiff", "ico" or "bmp". If error is set, FALSE will be returned. See gdk_pixbuf_save() for more details.

pixbuf : | a GdkPixbuf.
filename : | name of file to save.
type : | name of file format.
option_keys : | name of options to set, NULL-terminated
option_values : | values for named options
error : | return location for error, or NULL
Returns : | whether an error was set

gdk_pixbuf_save ()

gboolean            gdk_pixbuf_save                     (GdkPixbuf *pixbuf,
                                                         const char *filename,
                                                         const char *type,
                                                         GError **error,
                                                         ...);

Saves pixbuf to a file in format type. By default, "jpeg", "png", "ico" and "bmp" are possible file formats to save in, but more formats may be installed. The list of all writable formats can be determined in the following way:

void add_if_writable (GdkPixbufFormat *data, GSList **list)
{
  if (gdk_pixbuf_format_is_writable (data))
    *list = g_slist_prepend (*list, data);
}

GSList *formats = gdk_pixbuf_get_formats ();
GSList *writable_formats = NULL;
g_slist_foreach (formats, add_if_writable, &writable_formats);
g_slist_free (formats);

If error is set, FALSE will be returned. Possible errors include those in the GDK_PIXBUF_ERROR domain and those in the G_FILE_ERROR domain.

The variable argument list should be NULL-terminated; if not empty, it should contain pairs of strings that modify the save parameters. For example:

gdk_pixbuf_save (pixbuf, handle, "jpeg", &error,
                 "quality", "100", NULL);

Currently only few parameters exist. JPEG images can be saved with a "quality" parameter; its value should be in the range [0,100].

Text chunks can be attached to PNG images by specifying parameters of the form "tEXt::key", where key is an ASCII string of length 1-79. The values are UTF-8 encoded strings. The PNG compression level can be specified using the "compression" parameter; it's value is in an integer in the range of [0,9].

ICO images can be saved in depth 16, 24, or 32, by using the "depth" parameter. When the ICO saver is given "x_hot" and "y_hot" parameters, it produces a CUR instead of an ICO.

pixbuf : | a GdkPixbuf.
filename : | name of file to save.
type : | name of file format.
error : | return location for error, or NULL
... : | list of key-value save options
Returns : | whether an error was set

GdkPixbufSaveFunc ()

gboolean            (*GdkPixbufSaveFunc)                (const gchar *buf,
                                                         gsize count,
                                                         GError **error,
                                                         gpointer data);

Specifies the type of the function passed to gdk_pixbuf_save_to_callback(). It is called once for each block of bytes that is "written" by gdk_pixbuf_save_to_callback(). If successful it should return TRUE. If an error occurs it should set error and return FALSE, in which case gdk_pixbuf_save_to_callback() will fail with the same error.

buf : | bytes to be written.
count : | number of bytes in buf.
error : | A location to return an error.
data : | user data passed to gdk_pixbuf_save_to_callback().
Returns : | TRUE if successful, FALSE (with error set) if failed.

Since 2.4

gdk_pixbuf_save_to_callback ()

gboolean            gdk_pixbuf_save_to_callback         (GdkPixbuf *pixbuf,
                                                         GdkPixbufSaveFunc save_func,
                                                         gpointer user_data,
                                                         const char *type,
                                                         GError **error,
                                                         ...);

Saves pixbuf in format type by feeding the produced data to a callback. Can be used when you want to store the image to something other than a file, such as an in-memory buffer or a socket. If error is set, FALSE will be returned. Possible errors include those in the GDK_PIXBUF_ERROR domain and whatever the save function generates.

See gdk_pixbuf_save() for more details.

pixbuf : | a GdkPixbuf.
save_func : | a function that is called to save each block of data that the save routine generates.
user_data : | user data to pass to the save function.
type : | name of file format.
error : | return location for error, or NULL
... : | list of key-value save options
Returns : | whether an error was set

Since 2.4

gdk_pixbuf_save_to_callbackv ()

gboolean            gdk_pixbuf_save_to_callbackv        (GdkPixbuf *pixbuf,
                                                         GdkPixbufSaveFunc save_func,
                                                         gpointer user_data,
                                                         const char *type,
                                                         char **option_keys,
                                                         char **option_values,
                                                         GError **error);

Saves pixbuf to a callback in format type, which is currently "jpeg", "png", "tiff", "ico" or "bmp". If error is set, FALSE will be returned. See gdk_pixbuf_save_to_callback() for more details.

pixbuf : | a GdkPixbuf.
save_func : | a function that is called to save each block of data that the save routine generates.
user_data : | user data to pass to the save function.
type : | name of file format.
option_keys : | name of options to set, NULL-terminated
option_values : | values for named options
error : | return location for error, or NULL
Returns : | whether an error was set

Since 2.4

gdk_pixbuf_save_to_buffer ()

gboolean            gdk_pixbuf_save_to_buffer           (GdkPixbuf *pixbuf,
                                                         gchar **buffer,
                                                         gsize *buffer_size,
                                                         const char *type,
                                                         GError **error,
                                                         ...);

Saves pixbuf to a new buffer in format type, which is currently "jpeg", "png", "tiff", "ico" or "bmp". This is a convenience function that uses gdk_pixbuf_save_to_callback() to do the real work. Note that the buffer is not nul-terminated and may contain embedded nuls. If error is set, FALSE will be returned and string will be set to NULL. Possible errors include those in the GDK_PIXBUF_ERROR domain.

See gdk_pixbuf_save() for more details.

pixbuf : | a GdkPixbuf.
buffer : | location to receive a pointer to the new buffer.
buffer_size : | location to receive the size of the new buffer.
type : | name of file format.
error : | return location for error, or NULL
... : | list of key-value save options
Returns : | whether an error was set

Since 2.4

gdk_pixbuf_save_to_bufferv ()

gboolean            gdk_pixbuf_save_to_bufferv          (GdkPixbuf *pixbuf,
                                                         gchar **buffer,
                                                         gsize *buffer_size,
                                                         const char *type,
                                                         char **option_keys,
                                                         char **option_values,
                                                         GError **error);

Saves pixbuf to a new buffer in format type, which is currently "jpeg", "tiff", "png", "ico" or "bmp". See gdk_pixbuf_save_to_buffer() for more details.

pixbuf : | a GdkPixbuf.
buffer : | location to receive a pointer to the new buffer.
buffer_size : | location to receive the size of the new buffer.
type : | name of file format.
option_keys : | name of options to set, NULL-terminated
option_values : | values for named options
error : | return location for error, or NULL
Returns : | whether an error was set

Since 2.4


The GdkPixbuf Structure

The GdkPixbuf Structure — Information that describes an image.

Synopsis

#include <gdk-pixbuf/gdk-pixbuf.h>

enum                GdkPixbufError;
#define             GDK_PIXBUF_ERROR
enum                GdkColorspace;
enum                GdkPixbufAlphaMode;
                    GdkPixbuf;
GdkColorspace       gdk_pixbuf_get_colorspace           (const GdkPixbuf *pixbuf);
int                 gdk_pixbuf_get_n_channels           (const GdkPixbuf *pixbuf);
gboolean            gdk_pixbuf_get_has_alpha            (const GdkPixbuf *pixbuf);
int                 gdk_pixbuf_get_bits_per_sample      (const GdkPixbuf *pixbuf);
guchar*             gdk_pixbuf_get_pixels               (const GdkPixbuf *pixbuf);
int                 gdk_pixbuf_get_width                (const GdkPixbuf *pixbuf);
int                 gdk_pixbuf_get_height               (const GdkPixbuf *pixbuf);
int                 gdk_pixbuf_get_rowstride            (const GdkPixbuf *pixbuf);
const gchar*        gdk_pixbuf_get_option               (GdkPixbuf *pixbuf,
                                                         const gchar *key);

Object Hierarchy

  GObject
   +----GdkPixbuf

Properties

  "bits-per-sample"          gint                  : Read / Write / Construct Only
  "colorspace"               GdkColorspace         : Read / Write / Construct Only
  "has-alpha"                gboolean              : Read / Write / Construct Only
  "height"                   gint                  : Read / Write / Construct Only
  "n-channels"               gint                  : Read / Write / Construct Only
  "pixels"                   gpointer              : Read / Write / Construct Only
  "rowstride"                gint                  : Read / Write / Construct Only
  "width"                    gint                  : Read / Write / Construct Only

Description

The GdkPixbuf structure contains information that describes an image in memory.

Image Data

Image data in a pixbuf is stored in memory in uncompressed, packed format. Rows in the image are stored top to bottom, and in each row pixels are stored from left to right. There may be padding at the end of a row. The "rowstride" value of a pixbuf, as returned by gdk_pixbuf_get_rowstride(), indicates the number of bytes between rows.

Example 1. put_pixel() example

The following code illustrates a simple put_pixel() function for RGB pixbufs with 8 bits per channel with an alpha channel. It is not included in the gdk-pixbuf library for performance reasons; rather than making several function calls for each pixel, your own code can take shortcuts.

static void
put_pixel (GdkPixbuf *pixbuf, int x, int y, guchar red, guchar green, guchar blue, guchar alpha)
{
  int width, height, rowstride, n_channels;
  guchar *pixels, *p;

  n_channels = gdk_pixbuf_get_n_channels (pixbuf);

  g_assert (gdk_pixbuf_get_colorspace (pixbuf) == GDK_COLORSPACE_RGB);
  g_assert (gdk_pixbuf_get_bits_per_sample (pixbuf) == 8);
  g_assert (gdk_pixbuf_get_has_alpha (pixbuf));
  g_assert (n_channels == 4);

  width = gdk_pixbuf_get_width (pixbuf);
  height = gdk_pixbuf_get_height (pixbuf);

  g_assert (x >= 0 && x < width);
  g_assert (y >= 0 && y < height);

  rowstride = gdk_pixbuf_get_rowstride (pixbuf);
  pixels = gdk_pixbuf_get_pixels (pixbuf);

  p = pixels + y * rowstride + x * n_channels;
  p[0] = red;
  p[1] = green;
  p[2] = blue;
  p[3] = alpha;
}

This function will not work for pixbufs with images that are other than 8 bits per sample or channel, but it will work for most of the pixbufs that GTK+ uses.

Note

If you are doing memcpy() of raw pixbuf data, note that the last row in the pixbuf may not be as wide as the full rowstride, but rather just as wide as the pixel data needs to be. That is, it is unsafe to do memcpy (dest, pixels, rowstride * height) to copy a whole pixbuf. Use gdk_pixbuf_copy() instead, or compute the width in bytes of the last row as width * ((n_channels * bits_per_sample + 7) / 8).

Details

enum GdkPixbufError

typedef enum {
        /* image data hosed */
        GDK_PIXBUF_ERROR_CORRUPT_IMAGE,
        /* no mem to load image */
        GDK_PIXBUF_ERROR_INSUFFICIENT_MEMORY,
        /* bad option passed to save routine */
        GDK_PIXBUF_ERROR_BAD_OPTION,
        /* unsupported image type (sort of an ENOSYS) */
        GDK_PIXBUF_ERROR_UNKNOWN_TYPE,
        /* unsupported operation (load, save) for image type */
        GDK_PIXBUF_ERROR_UNSUPPORTED_OPERATION,
        GDK_PIXBUF_ERROR_FAILED
} GdkPixbufError;

An error code in the GDK_PIXBUF_ERROR domain. Many gdk-pixbuf operations can cause errors in this domain, or in the G_FILE_ERROR domain.

GDK_PIXBUF_ERROR_CORRUPT_IMAGE | An image file was broken somehow.
GDK_PIXBUF_ERROR_INSUFFICIENT_MEMORY | Not enough memory.
GDK_PIXBUF_ERROR_BAD_OPTION | A bad option was passed to a pixbuf save module.
GDK_PIXBUF_ERROR_UNKNOWN_TYPE | Unknown image type.
GDK_PIXBUF_ERROR_UNSUPPORTED_OPERATION | Don't know how to perform the given operation on the type of image at hand.
GDK_PIXBUF_ERROR_FAILED | Generic failure code, something went wrong.

GDK_PIXBUF_ERROR

#define GDK_PIXBUF_ERROR gdk_pixbuf_error_quark ()

Error domain used for pixbuf operations. Indicates that the error code will be in the GdkPixbufError enumeration. See GError for information on error domains and error codes.

enum GdkColorspace

typedef enum {
    GDK_COLORSPACE_RGB
} GdkColorspace;

This enumeration defines the color spaces that are supported by the gdk-pixbuf library. Currently only RGB is supported.

GDK_COLORSPACE_RGB Indicates a red/green/blue additive color space.

enum GdkPixbufAlphaMode

typedef enum
{
        GDK_PIXBUF_ALPHA_BILEVEL,
        GDK_PIXBUF_ALPHA_FULL
} GdkPixbufAlphaMode;

These values can be passed to gdk_pixbuf_render_to_drawable_alpha() to control how the alpha channel of an image should be handled. This function can create a bilevel clipping mask (black and white) and use it while painting the image. In the future, when the X Window System gets an alpha channel extension, it will be possible to do full alpha compositing onto arbitrary drawables. For now both cases fall back to a bilevel clipping mask.

GDK_PIXBUF_ALPHA_BILEVEL | A bilevel clipping mask (black and white) will be created and used to draw the image. Pixels below 0.5 opacity will be considered fully transparent, and all others will be considered fully opaque.
GDK_PIXBUF_ALPHA_FULL | For now falls back to GDK_PIXBUF_ALPHA_BILEVEL. In the future it will do full alpha compositing.

GdkPixbuf

typedef struct _GdkPixbuf GdkPixbuf;

This is the main structure in the gdk-pixbuf library. It is used to represent images. It contains information about the image's pixel data, its color space, bits per sample, width and height, and the rowstride (the number of bytes between the start of one row and the start of the next).

gdk_pixbuf_get_colorspace ()

GdkColorspace       gdk_pixbuf_get_colorspace           (const GdkPixbuf *pixbuf);

Queries the color space of a pixbuf.

pixbuf : | A pixbuf.
Returns : | Color space.

gdk_pixbuf_get_n_channels ()

int                 gdk_pixbuf_get_n_channels           (const GdkPixbuf *pixbuf);

Queries the number of channels of a pixbuf.

pixbuf : | A pixbuf.
Returns : | Number of channels.

gdk_pixbuf_get_has_alpha ()

gboolean            gdk_pixbuf_get_has_alpha            (const GdkPixbuf *pixbuf);

Queries whether a pixbuf has an alpha channel (opacity information).

pixbuf : | A pixbuf.
Returns : | TRUE if it has an alpha channel, FALSE otherwise.

gdk_pixbuf_get_bits_per_sample ()

int                 gdk_pixbuf_get_bits_per_sample      (const GdkPixbuf *pixbuf);

Queries the number of bits per color sample in a pixbuf.

pixbuf : | A pixbuf.
Returns : | Number of bits per color sample.

gdk_pixbuf_get_pixels ()

guchar*             gdk_pixbuf_get_pixels               (const GdkPixbuf *pixbuf);

Queries a pointer to the pixel data of a pixbuf.

pixbuf : | A pixbuf.
Returns : | A pointer to the pixbuf's pixel data. Please see the section called “Image Data” for information about how the pixel data is stored in memory.

gdk_pixbuf_get_width ()

int                 gdk_pixbuf_get_width                (const GdkPixbuf *pixbuf);

Queries the width of a pixbuf.

pixbuf : | A pixbuf.
Returns : | Width in pixels.

gdk_pixbuf_get_height ()

int                 gdk_pixbuf_get_height               (const GdkPixbuf *pixbuf);

Queries the height of a pixbuf.

pixbuf : | A pixbuf.
Returns : | Height in pixels.

gdk_pixbuf_get_rowstride ()

int                 gdk_pixbuf_get_rowstride            (const GdkPixbuf *pixbuf);

Queries the rowstride of a pixbuf, which is the number of bytes between the start of a row and the start of the next row.

pixbuf : | A pixbuf.
Returns : | Distance between row starts.

gdk_pixbuf_get_option ()

const gchar*        gdk_pixbuf_get_option               (GdkPixbuf *pixbuf,
                                                         const gchar *key);

Looks up key in the list of options that may have been attached to the pixbuf when it was loaded.

pixbuf : | a GdkPixbuf
key : | a nul-terminated string.
Returns : | the value associated with key. This is a nul-terminated string that should not be freed or NULL if key was not found.

Property Details

The "bits-per-sample" property

  "bits-per-sample"          gint                  : Read / Write / Construct Only

The number of bits per sample. Currently only 8 bit per sample are supported.

Allowed values: [1,16]

Default value: 8

The "colorspace" property

  "colorspace"               GdkColorspace         : Read / Write / Construct Only

The colorspace in which the samples are interpreted.

Default value: GDK_COLORSPACE_RGB

The "has-alpha" property

  "has-alpha"                gboolean              : Read / Write / Construct Only

Whether the pixbuf has an alpha channel.

Default value: FALSE

The "height" property

  "height"                   gint                  : Read / Write / Construct Only

The number of rows of the pixbuf.

Allowed values: >= 1

Default value: 1

The "n-channels" property

  "n-channels"               gint                  : Read / Write / Construct Only

The number of samples per pixel. Currently, only 3 or 4 samples per pixel are supported.

Allowed values: >= 0

Default value: 3

The "pixels" property

  "pixels"                   gpointer              : Read / Write / Construct Only

A pointer to the pixel data of the pixbuf.

The "rowstride" property

  "rowstride"                gint                  : Read / Write / Construct Only

The number of bytes between the start of a row and the start of the next row. This number must (obviously) be at least as large as the width of the pixbuf.

Allowed values: >= 1

Default value: 1

The "width" property

  "width"                    gint                  : Read / Write / Construct Only

The number of columns of the pixbuf.

Allowed values: >= 1

Default value: 1


Drawables to Pixbufs

Drawables to Pixbufs — Getting parts of a GDK drawable's image data into a pixbuf.

Description

The functions to take the image data from a GDK drawable and dump it into a pixbuf are contained in GDK, see the Pixbufs section of the GDK documentation.


Rendering

Rendering — Rendering a pixbuf to a GDK drawable.

Description

The functions to render pixbufs to GDK drawables are contained in GDK, see the Pixbufs section of the GDK documentation.


X Drawables to Pixbufs

X Drawables to Pixbufs — Getting parts of an X drawable's image data into a pixbuf.

Synopsis

#include <gdk-pixbuf/gdk-pixbuf.h>

GdkPixbuf*          gdk_pixbuf_xlib_get_from_drawable   (GdkPixbuf *dest,
                                                         Drawable src,
                                                         Colormap cmap,
                                                         Visual *visual,
                                                         int src_x,
                                                         int src_y,
                                                         int dest_x,
                                                         int dest_y,
                                                         int width,
                                                         int height);

Description

The functions in this section allow you to take the image data from an X drawable and dump it into a GdkPixbuf. This can be used for screenshots and other special effects. Note that these operations can be expensive, since the image data has to be transferred from the X server to the client program and converted.

These functions are analogous to those for the GDK version of gdk-pixbuf.

Details

gdk_pixbuf_xlib_get_from_drawable ()

GdkPixbuf*          gdk_pixbuf_xlib_get_from_drawable   (GdkPixbuf *dest,
                                                         Drawable src,
                                                         Colormap cmap,
                                                         Visual *visual,
                                                         int src_x,
                                                         int src_y,
                                                         int dest_x,
                                                         int dest_y,
                                                         int width,
                                                         int height);

Transfers image data from a Gdk drawable and converts it to an RGB(A) representation inside a GdkPixbuf.

If the drawable src is a pixmap, then a suitable colormap must be specified, since pixmaps are just blocks of pixel data without an associated colormap. If the drawable is a window, the cmap argument will be ignored and the window's own colormap will be used instead.

If the specified destination pixbuf dest is NULL, then this function will create an RGB pixbuf with 8 bits per channel and no alpha, with the same size specified by the width and height arguments. In this case, the dest_x and dest_y arguments must be specified as 0, otherwise the function will return NULL. If the specified destination pixbuf is not NULL and it contains alpha information, then the filled pixels will be set to full opacity.

If the specified drawable is a pixmap, then the requested source rectangle must be completely contained within the pixmap, otherwise the function will return NULL.

If the specified drawable is a window, then it must be viewable, i.e. all of its ancestors up to the root window must be mapped. Also, the specified source rectangle must be completely contained within the window and within the screen. If regions of the window are obscured by noninferior windows, the contents of those regions are undefined. The contents of regions obscured by inferior windows of a different depth than that of the source window will also be undefined.

dest : | Destination pixbuf, or NULL if a new pixbuf should be created.
src : | Source drawable.
cmap : | A colormap if src is a pixmap. If it is a window, this argument will be ignored.
visual : | A visual if src is a pixmap. If it is a window, this argument will be ignored.
src_x : | Source X coordinate within drawable.
src_y : | Source Y coordinate within drawable.
dest_x : | Destination X coordinate in pixbuf, or 0 if dest is NULL.
dest_y : | Destination Y coordinate in pixbuf, or 0 if dest is NULL.
width : | Width in pixels of region to get.
height : | Height in pixels of region to get.
Returns : | The same pixbuf as dest if it was non-NULL, or a newly-created pixbuf with a reference count of 1 if no destination pixbuf was specified; in the latter case, NULL will be returned if not enough memory could be allocated for the pixbuf to be created.


gdk-pixbuf Xlib initialization

gdk-pixbuf Xlib initialization — Initializing the gdk-pixbuf Xlib library.

Synopsis

#include <gdk-pixbuf/gdk-pixbuf.h>

void                gdk_pixbuf_xlib_init                (Display *display,
                                                         int screen_num);
void                gdk_pixbuf_xlib_init_with_depth     (Display *display,
                                                         int screen_num,
                                                         int prefDepth);

Description

In addition to the normal Gdk-specific functions, the gdk-pixbuf package provides a small library that lets Xlib-only applications use GdkPixbuf structures and render them to X drawables. The functions in this section are used to initialize the gdk-pixbuf Xlib library. This library must be initialized near the beginning of the program or before calling any of the other gdk-pixbuf Xlib functions.

Details

gdk_pixbuf_xlib_init ()

void                gdk_pixbuf_xlib_init                (Display *display,
                                                         int screen_num);

Initializes the gdk-pixbuf Xlib machinery by calling xlib_rgb_init(). This function should be called near the beginning of your program, or before using any of the gdk-pixbuf-xlib functions.

display : | X display to use.
screen_num : | Screen number.

gdk_pixbuf_xlib_init_with_depth ()

void                gdk_pixbuf_xlib_init_with_depth     (Display *display,
                                                         int screen_num,
                                                         int prefDepth);

Similar to gdk_pixbuf_xlib_init(), but also lets you specify the preferred depth for XlibRGB if you do not want it to use the default depth it picks.

display : | X display to use.
screen_num : | Screen number.
prefDepth : | Preferred depth for XlibRGB.

See Also

XlibRGB


Xlib Rendering

Xlib Rendering — Rendering a pixbuf to an X drawable.

Synopsis

#include <gdk-pixbuf/gdk-pixbuf.h>

void                gdk_pixbuf_xlib_render_threshold_alpha
                                                        (GdkPixbuf *pixbuf,
                                                         Pixmap bitmap,
                                                         int src_x,
                                                         int src_y,
                                                         int dest_x,
                                                         int dest_y,
                                                         int width,
                                                         int height,
                                                         int alpha_threshold);
void                gdk_pixbuf_xlib_render_to_drawable  (GdkPixbuf *pixbuf,
                                                         Drawable drawable,
                                                         GC gc,
                                                         int src_x,
                                                         int src_y,
                                                         int dest_x,
                                                         int dest_y,
                                                         int width,
                                                         int height,
                                                         XlibRgbDither dither,
                                                         int x_dither,
                                                         int y_dither);
void                gdk_pixbuf_xlib_render_to_drawable_alpha
                                                        (GdkPixbuf *pixbuf,
                                                         Drawable drawable,
                                                         int src_x,
                                                         int src_y,
                                                         int dest_x,
                                                         int dest_y,
                                                         int width,
                                                         int height,
                                                         GdkPixbufAlphaMode alpha_mode,
                                                         int alpha_threshold,
                                                         XlibRgbDither dither,
                                                         int x_dither,
                                                         int y_dither);
void                gdk_pixbuf_xlib_render_pixmap_and_mask
                                                        (GdkPixbuf *pixbuf,
                                                         Pixmap *pixmap_return,
                                                         Pixmap *mask_return,
                                                         int alpha_threshold);

Description

The gdk-pixbuf Xlib library provides several convenience functions to render pixbufs to X drawables. It uses XlibRGB to render the image data.

These functions are analogous to those for the GDK version of gdk-pixbuf.

Details

gdk_pixbuf_xlib_render_threshold_alpha ()

void                gdk_pixbuf_xlib_render_threshold_alpha
                                                        (GdkPixbuf *pixbuf,
                                                         Pixmap bitmap,
                                                         int src_x,
                                                         int src_y,
                                                         int dest_x,
                                                         int dest_y,
                                                         int width,
                                                         int height,
                                                         int alpha_threshold);

Takes the opacity values in a rectangular portion of a pixbuf and thresholds them to produce a bi-level alpha mask that can be used as a clipping mask for a drawable.

pixbuf : | A pixbuf.
bitmap : | Bitmap where the bilevel mask will be painted to.
src_x : | Source X coordinate.
src_y : | source Y coordinate.
dest_x : | Destination X coordinate.
dest_y : | Destination Y coordinate.
width : | Width of region to threshold.
height : | Height of region to threshold.
alpha_threshold : | Opacity values below this will be painted as zero; all other values will be painted as one.

gdk_pixbuf_xlib_render_to_drawable ()

void                gdk_pixbuf_xlib_render_to_drawable  (GdkPixbuf *pixbuf,
                                                         Drawable drawable,
                                                         GC gc,
                                                         int src_x,
                                                         int src_y,
                                                         int dest_x,
                                                         int dest_y,
                                                         int width,
                                                         int height,
                                                         XlibRgbDither dither,
                                                         int x_dither,
                                                         int y_dither);

Renders a rectangular portion of a pixbuf to a drawable while using the specified GC. This is done using XlibRGB, so the specified drawable must have the XlibRGB visual and colormap. Note that this function will ignore the opacity information for images with an alpha channel; the GC must already have the clipping mask set if you want transparent regions to show through.

For an explanation of dither offsets, see the XlibRGB documentation. In brief, the dither offset is important when re-rendering partial regions of an image to a rendered version of the full image, or for when the offsets to a base position change, as in scrolling. The dither matrix has to be shifted for consistent visual results. If you do not have any of these cases, the dither offsets can be both zero.

pixbuf : | A pixbuf.
drawable : | Destination drawable.
gc : | GC used for rendering.
src_x : | Source X coordinate within pixbuf.
src_y : | Source Y coordinate within pixbuf.
dest_x : | Destination X coordinate within drawable.
dest_y : | Destination Y coordinate within drawable.
width : | Width of region to render, in pixels.
height : | Height of region to render, in pixels.
dither : | Dithering mode for XlibRGB.
x_dither : | X offset for dither.
y_dither : | Y offset for dither.

gdk_pixbuf_xlib_render_to_drawable_alpha ()

void                gdk_pixbuf_xlib_render_to_drawable_alpha
                                                        (GdkPixbuf *pixbuf,
                                                         Drawable drawable,
                                                         int src_x,
                                                         int src_y,
                                                         int dest_x,
                                                         int dest_y,
                                                         int width,
                                                         int height,
                                                         GdkPixbufAlphaMode alpha_mode,
                                                         int alpha_threshold,
                                                         XlibRgbDither dither,
                                                         int x_dither,
                                                         int y_dither);

Renders a rectangular portion of a pixbuf to a drawable. This is done using XlibRGB, so the specified drawable must have the XlibRGB visual and colormap.

When used with GDK_PIXBUF_ALPHA_BILEVEL, this function has to create a bitmap out of the thresholded alpha channel of the image and, it has to set this bitmap as the clipping mask for the GC used for drawing. This can be a significant performance penalty depending on the size and the complexity of the alpha channel of the image. If performance is crucial, consider handling the alpha channel yourself (possibly by caching it in your application) and using gdk_pixbuf_xlib_render_to_drawable() or GdkRGB directly instead.

pixbuf : | A pixbuf.
drawable : | Destination drawable.
src_x : | Source X coordinate within pixbuf.
src_y : | Source Y coordinates within pixbuf.
dest_x : | Destination X coordinate within drawable.
dest_y : | Destination Y coordinate within drawable.
width : | Width of region to render, in pixels.
height : | Height of region to render, in pixels.
alpha_mode : | If the image does not have opacity information, this is ignored. Otherwise, specifies how to handle transparency when rendering.
alpha_threshold : | If the image does have opacity information and alpha_mode is GDK_PIXBUF_ALPHA_BILEVEL, specifies the threshold value for opacity values.
dither : | Dithering mode for XlibRGB.
x_dither : | X offset for dither.
y_dither : | Y offset for dither.

gdk_pixbuf_xlib_render_pixmap_and_mask ()

void                gdk_pixbuf_xlib_render_pixmap_and_mask
                                                        (GdkPixbuf *pixbuf,
                                                         Pixmap *pixmap_return,
                                                         Pixmap *mask_return,
                                                         int alpha_threshold);

Creates a pixmap and a mask bitmap which are returned in the pixmap_return and mask_return arguments, respectively, and renders a pixbuf and its corresponding tresholded alpha mask to them. This is merely a convenience function; applications that need to render pixbufs with dither offsets or to given drawables should use gdk_pixbuf_xlib_render_to_drawable_alpha() or gdk_pixbuf_xlib_render_to_drawable(), and gdk_pixbuf_xlib_render_threshold_alpha().

If the pixbuf does not have an alpha channel, then *mask_return will be set to None.

pixbuf : | A pixbuf.
pixmap_return : | Return value for the created pixmap.
mask_return : | Return value for the created mask.
alpha_threshold : | Threshold value for opacity values.


XlibRGB

XlibRGB — Rendering RGB buffers to X drawables.

Synopsis

#include <gdk-pixbuf/gdk-pixbuf.h>

                    XlibRgbCmap;
enum                XlibRgbDither;
void                xlib_rgb_init                       (Display *display,
                                                         Screen *screen);
void                xlib_rgb_init_with_depth            (Display *display,
                                                         Screen *screen,
                                                         int prefDepth);
unsigned long       xlib_rgb_xpixel_from_rgb            (guint32 rgb);
void                xlib_rgb_gc_set_foreground          (GC gc,
                                                         guint32 rgb);
void                xlib_rgb_gc_set_background          (GC gc,
                                                         guint32 rgb);
void                xlib_draw_rgb_image                 (Drawable drawable,
                                                         GC gc,
                                                         int x,
                                                         int y,
                                                         int width,
                                                         int height,
                                                         XlibRgbDither dith,
                                                         unsigned char *rgb_buf,
                                                         int rowstride);
void                xlib_draw_rgb_image_dithalign       (Drawable drawable,
                                                         GC gc,
                                                         int x,
                                                         int y,
                                                         int width,
                                                         int height,
                                                         XlibRgbDither dith,
                                                         unsigned char *rgb_buf,
                                                         int rowstride,
                                                         int xdith,
                                                         int ydith);
void                xlib_draw_rgb_32_image              (Drawable drawable,
                                                         GC gc,
                                                         int x,
                                                         int y,
                                                         int width,
                                                         int height,
                                                         XlibRgbDither dith,
                                                         unsigned char *buf,
                                                         int rowstride);
void                xlib_draw_gray_image                (Drawable drawable,
                                                         GC gc,
                                                         int x,
                                                         int y,
                                                         int width,
                                                         int height,
                                                         XlibRgbDither dith,
                                                         unsigned char *buf,
                                                         int rowstride);
XlibRgbCmap*        xlib_rgb_cmap_new                   (guint32 *colors,
                                                         int n_colors);
void                xlib_rgb_cmap_free                  (XlibRgbCmap *cmap);
void                xlib_draw_indexed_image             (Drawable drawable,
                                                         GC gc,
                                                         int x,
                                                         int y,
                                                         int width,
                                                         int height,
                                                         XlibRgbDither dith,
                                                         unsigned char *buf,
                                                         int rowstride,
                                                         XlibRgbCmap *cmap);
Bool                xlib_rgb_ditherable                 (void);
void                xlib_rgb_set_verbose                (Bool verbose);
void                xlib_rgb_set_install                (Bool install);
void                xlib_rgb_set_min_colors             (int min_colors);
Colormap            xlib_rgb_get_cmap                   (void);
Visual*             xlib_rgb_get_visual                 (void);
XVisualInfo*        xlib_rgb_get_visual_info            (void);
int                 xlib_rgb_get_depth                  (void);
Display*            xlib_rgb_get_display                (void);
Screen*             xlib_rgb_get_screen                 (void);

Description

The XlibRGB set of functions is a port of the GdkRGB library to use plain Xlib and X drawables. You can use these functions to render RGB buffers into drawables very quickly with high-quality dithering.

Details

XlibRgbCmap

typedef struct {
  unsigned int colors[256];
  unsigned char lut[256]; /* for 8-bit modes */
} XlibRgbCmap;

FIXME: Describe this.

unsigned int colors[256]; | FIXME.
unsigned char lut[256]; | FIXME.

enum XlibRgbDither

typedef enum
{
  XLIB_RGB_DITHER_NONE,
  XLIB_RGB_DITHER_NORMAL,
  XLIB_RGB_DITHER_MAX
} XlibRgbDither;

These values are used to specify which dithering method should be used. XLIB_RGB_DITHER_NONE will use no dithering and simply map the colors in an RGB buffer to the closest colors that the display can provide. XLIB_RGB_DITHER_NORMAL will provide dithering only on pseudocolor displays. XLIB_RGB_DITHER_MAX will provide dithering on pseudocolor and 16-bit truecolor or “high color” displays.

XLIB_RGB_DITHER_NONE | Specifies no dithering.
XLIB_RGB_DITHER_NORMAL | Specifies dithering only on pseudocolor displays.
XLIB_RGB_DITHER_MAX | Specifies dithering on high color displays.

xlib_rgb_init ()

void                xlib_rgb_init                       (Display *display,
                                                         Screen *screen);

Initializes the XlibRGB machinery with the default depth. If you use this function XlibRGB will automatically pick the best visual available on your display. This function or xlib_rgb_init_with_depth() must be called before using any of the other functions in XlibRGB.

display : | X Display to use.
screen : | Screen to use.

xlib_rgb_init_with_depth ()

void                xlib_rgb_init_with_depth            (Display *display,
                                                         Screen *screen,
                                                         int prefDepth);

Initializes the XlibRGB machinery with a particular depth you specify, instead of automatically picking the best depth in the display. This function or xlib_rgb_init() must be called before using any of the other functions in XlibRGB.

display : | X display to use.
screen : | Screen to use.
prefDepth : | Visual depth to use for color substitution tables. This must be one of the supported visual depths in the specified display.

xlib_rgb_xpixel_from_rgb ()

unsigned long       xlib_rgb_xpixel_from_rgb            (guint32 rgb);

Converts an RGB triplet into the closest color that XlibRGB visual can handle.

rgb : | 32-bit representation of an RGB value, specified as 0x00RRGGBB.
Returns : | X pixel value that corresponds to the closest color in the XlibRGB visual and colormap.

xlib_rgb_gc_set_foreground ()

void                xlib_rgb_gc_set_foreground          (GC gc,
                                                         guint32 rgb);

This is a convenience function to set the foreground of a GC from an RGB triplet. It calls xlib_rgb_xpixel_from_rgb() internally and uses the returned pixel value to set the GC's foreground.

gc : | A graphic context.
rgb : | 32-bit representation of an RGB value, specified as 0x00RRGGBB.

xlib_rgb_gc_set_background ()

void                xlib_rgb_gc_set_background          (GC gc,
                                                         guint32 rgb);

This is a convenience function to set the background of a GC from an RGB triplet. It calls xlib_rgb_xpixel_from_rgb() internally and uses the returned pixel value to set the GC's background.

gc : | A graphic context.
rgb : | 32-bit representation of an RGB value, specified as 0x00RRGGBB.

xlib_draw_rgb_image ()

void                xlib_draw_rgb_image                 (Drawable drawable,
                                                         GC gc,
                                                         int x,
                                                         int y,
                                                         int width,
                                                         int height,
                                                         XlibRgbDither dith,
                                                         unsigned char *rgb_buf,
                                                         int rowstride);

Renders an RGB buffer to a drawable. Pixels are specified as RGB triplets with 8 bits per channel. An image will thus look like an RGBRGBRGBRGB sequence of 8-bit values. This function does not let you specify dither offsets; applications that need to render partial regions of a buffer to build the final image should use xlib_draw_rgb_image_dithalign() instead.

drawable : | Destination drawable.
gc : | A graphic context.
x : | Leftmost coordinate of the destination rectangle.
y : | Upper coordinate of the destination rectangle.
width : | Width of the destination rectangle, in pixels.
height : | Height of the destination rectangle, in pixels.
dith : | Dithering method to use.
rgb_buf : | Pointer to the pixel in the RGB buffer that corresponds to the upper-left corner of the rectangular region to render.
rowstride : | Offset between pixel rows in the RGB buffer, in bytes.

xlib_draw_rgb_image_dithalign ()

void                xlib_draw_rgb_image_dithalign       (Drawable drawable,
                                                         GC gc,
                                                         int x,
                                                         int y,
                                                         int width,
                                                         int height,
                                                         XlibRgbDither dith,
                                                         unsigned char *rgb_buf,
                                                         int rowstride,
                                                         int xdith,
                                                         int ydith);

Renders an RGB buffer to a drawable. Pixels are specified as RGB triplets with 8 bits per channel. An image will thus look like an RGBRGBRGBRGB sequence of 8-bit values. This function lets you specify a pair of dither offsets. It should be used when you need to render regions of an RGB buffer separately to form the final image; the dither offsets let you align the dither mask appropriately.

drawable : | Destination drawable.
gc : | A graphic context.
x : | Leftmost coordinate of the destination rectangle.
y : | Upper coordinate of the destination rectangle.
width : | Width of the destination rectangle, in pixels.
height : | Height of the destination rectangle, in pixels.
dith : | Dithering method to use.
rgb_buf : | Pointer to the pixel in the RGB buffer that corresponds to the upper-left corner of the rectangular region to render.
rowstride : | Offset between pixel rows in the RGB buffer, in bytes.
xdith : | X offset for the dither mask.
ydith : | Y offset for the dither mask.

xlib_draw_rgb_32_image ()

void                xlib_draw_rgb_32_image              (Drawable drawable,
                                                         GC gc,
                                                         int x,
                                                         int y,
                                                         int width,
                                                         int height,
                                                         XlibRgbDither dith,
                                                         unsigned char *buf,
                                                         int rowstride);

This function is analogous to xlib_draw_rgb_image(), but it lets you use 32-bit RGB buffers with pixels specified as 0xRRGGBB00. The least-significant 8 bits are actually discarded. This function can lead to faster results than xlib_draw_rgb_image() since the pixels are aligned on 32-bit boundaries.

drawable : | Destination drawable.
gc : | A graphic context.
x : | Leftmost coordinate of the destination rectangle.
y : | Upper coordinate of the destination rectangle.
width : | Width of the destination rectangle, in pixels.
height : | Height of the destination rectangle, in pixels.
dith : | Dithering method to use.
buf : | Pointer to the pixel in the RGB buffer that corresponds to the upper-left corner of the rectangular region to render.
rowstride : | Offset between pixel rows in the RGB buffer, in bytes.

xlib_draw_gray_image ()

void                xlib_draw_gray_image                (Drawable drawable,
                                                         GC gc,
                                                         int x,
                                                         int y,
                                                         int width,
                                                         int height,
                                                         XlibRgbDither dith,
                                                         unsigned char *buf,
                                                         int rowstride);

Renders a grayscale buffer to a drawable. Pixels are specified as 8-bit intensity values. An image will thus look as a GGGGGG sequence of 8-bit values.

drawable : | Destination drawable.
gc : | A graphic context.
x : | Leftmost coordinate of the destination rectangle.
y : | Upper coordinate of the destination rectangle.
width : | Width of the destination rectangle, in pixels.
height : | Height of thd destination rectangle, in pixels.
dith : | Dithering method to use.
buf : | Pointer to the pixel in the grayscale buffer that corresponds to the upper-left corner of the rectangular region to render.
rowstride : | Offset between pixel rows in the grayscale buffer, in pixels.

xlib_rgb_cmap_new ()

XlibRgbCmap*        xlib_rgb_cmap_new                   (guint32 *colors,
                                                         int n_colors);

FIXME

colors : | FIXME
n_colors : | FIXME
Returns : | FIXME

xlib_rgb_cmap_free ()

void                xlib_rgb_cmap_free                  (XlibRgbCmap *cmap);

Frees an XlibRGB colormap.

cmap : An XlibRGB colormap.

xlib_draw_indexed_image ()

void                xlib_draw_indexed_image             (Drawable drawable,
                                                         GC gc,
                                                         int x,
                                                         int y,
                                                         int width,
                                                         int height,
                                                         XlibRgbDither dith,
                                                         unsigned char *buf,
                                                         int rowstride,
                                                         XlibRgbCmap *cmap);

FIXME

drawable : | FIXME
gc : | FIXME
x : | FIXME
y : | FIXME
width : | FIXME
height : | FIXME
dith : | FIXME
buf : | FIXME
rowstride : | FIXME
cmap : | FIXME

xlib_rgb_ditherable ()

Bool                xlib_rgb_ditherable                 (void);

Queries whether XlibRGB supports dithering for its chosen visual.

Returns : TRUE if dithering can be performed for the visual that XlibRGB is using, FALSE otherwise.

xlib_rgb_set_verbose ()

void                xlib_rgb_set_verbose                (Bool verbose);

Enables/disables debug spew.

verbose : True to be verbose

xlib_rgb_set_install ()

void                xlib_rgb_set_install                (Bool install);

Sets whether we install an RGB colormap.

install : True to install a colormap

xlib_rgb_set_min_colors ()

void                xlib_rgb_set_min_colors             (int min_colors);

Sets the minimum number of colors in the color cube.

min_colors : minimum colors to use

xlib_rgb_get_cmap ()

Colormap            xlib_rgb_get_cmap                   (void);

Queries the X colormap that XlibRGB is using.

Returns : An X colormap.

xlib_rgb_get_visual ()

Visual*             xlib_rgb_get_visual                 (void);

Queries the visual that XlibRGB is using.

Returns : An X visual.

xlib_rgb_get_visual_info ()

XVisualInfo*        xlib_rgb_get_visual_info            (void);

Queries the visual info structure for the visual that XlibRGB is using.

Returns : An XVisualInfo structure.

xlib_rgb_get_depth ()

int                 xlib_rgb_get_depth                  (void);

Queries the depth of the visual that XlibRGB is using.

Returns : Bit depth.

xlib_rgb_get_display ()

Display*            xlib_rgb_get_display                (void);

Queries the X display that XlibRGB is using.

Returns : An X display.

xlib_rgb_get_screen ()

Screen*             xlib_rgb_get_screen                 (void);

Queries the screen that XlibRGB is using.

Returns : An X screen.

See Also

GdkRGB


Inline data

Inline data — Functions for inlined pixbuf handling.

Synopsis

#include <gdk-pixbuf/gdk-pixdata.h>

                    GdkPixdata;
enum                GdkPixdataType;
enum                GdkPixdataDumpType;
#define             GDK_PIXBUF_MAGIC_NUMBER
#define             GDK_PIXDATA_HEADER_LENGTH
gpointer            gdk_pixdata_from_pixbuf             (GdkPixdata *pixdata,
                                                         const GdkPixbuf *pixbuf,
                                                         gboolean use_rle);
GdkPixbuf*          gdk_pixbuf_from_pixdata             (const GdkPixdata *pixdata,
                                                         gboolean copy_pixels,
                                                         GError **error);
guint8*             gdk_pixdata_serialize               (const GdkPixdata *pixdata,
                                                         guint *stream_length_p);
gboolean            gdk_pixdata_deserialize             (GdkPixdata *pixdata,
                                                         guint stream_length,
                                                         const guint8 *stream,
                                                         GError **error);
GString*            gdk_pixdata_to_csource              (GdkPixdata *pixdata,
                                                         const gchar *name,
                                                         GdkPixdataDumpType dump_type);

Description

Using GdkPixdata, images can be compiled into an application, making it unnecessary to refer to external image files at runtime. gdk-pixbuf includes a utility named gdk-pixbuf-csource, which can be used to convert image files into GdkPixdata structures suitable for inclusion in C sources. To convert the GdkPixdata structures back into GdkPixbufs, use gdk_pixbuf_from_pixdata.

Details

GdkPixdata

typedef struct {
  guint32 magic;        /* GDK_PIXBUF_MAGIC_NUMBER */
  gint32  length;       /* <1 to disable length checks, otherwise:
             * GDK_PIXDATA_HEADER_LENGTH + pixel_data length
             */
  guint32 pixdata_type; /* GdkPixdataType */
  guint32 rowstride;
  guint32 width;
  guint32 height;
  guint8 *pixel_data;
} GdkPixdata;

A GdkPixdata contains pixbuf information in a form suitable for serialization and streaming.

guint32 magic; | magic number. A valid GdkPixdata structure must have GDK_PIXBUF_MAGIC_NUMBER here.
gint32 length; | less than 1 to disable length checks, otherwise GDK_PIXDATA_HEADER_LENGTH + length of pixel_data.
guint32 pixdata_type; | information about colorspace, sample width and encoding, in a GdkPixdataType.
guint32 rowstride; | Distance in bytes between rows.
guint32 width; | Width of the image in pixels.
guint32 height; | Height of the image in pixels.
guint8 *pixel_data; | width x height pixels, encoded according to pixdata_type and rowstride.

enum GdkPixdataType

typedef enum
{
  /* colorspace + alpha */
  GDK_PIXDATA_COLOR_TYPE_RGB    = 0x01,
  GDK_PIXDATA_COLOR_TYPE_RGBA   = 0x02,
  GDK_PIXDATA_COLOR_TYPE_MASK   = 0xff,
  /* width, support 8bits only currently */
  GDK_PIXDATA_SAMPLE_WIDTH_8    = 0x01 << 16,
  GDK_PIXDATA_SAMPLE_WIDTH_MASK = 0x0f << 16,
  /* encoding */
  GDK_PIXDATA_ENCODING_RAW      = 0x01 << 24,
  GDK_PIXDATA_ENCODING_RLE      = 0x02 << 24,
  GDK_PIXDATA_ENCODING_MASK     = 0x0f << 24
} GdkPixdataType;

An enumeration containing three sets of flags for a GdkPixdata struct: one for the used colorspace, one for the width of the samples and one for the encoding of the pixel data.

GDK_PIXDATA_COLOR_TYPE_RGB | each pixel has red, green and blue samples.
GDK_PIXDATA_COLOR_TYPE_RGBA | each pixel has red, green and blue samples and an alpha value.
GDK_PIXDATA_COLOR_TYPE_MASK | mask for the colortype flags of the enum.
GDK_PIXDATA_SAMPLE_WIDTH_8 | each sample has 8 bits.
GDK_PIXDATA_SAMPLE_WIDTH_MASK | mask for the sample width flags of the enum.
GDK_PIXDATA_ENCODING_RAW | the pixel data is in raw form.
GDK_PIXDATA_ENCODING_RLE | the pixel data is run-length encoded. Runs may be up to 127 bytes long; their length is stored in a single byte preceding the pixel data for the run. If a run is constant, its length byte has the high bit set and the pixel data consists of a single pixel which must be repeated.
GDK_PIXDATA_ENCODING_MASK | mask for the encoding flags of the enum.

enum GdkPixdataDumpType

typedef enum
{
  /* type of source to save */
  GDK_PIXDATA_DUMP_PIXDATA_STREAM	= 0,
  GDK_PIXDATA_DUMP_PIXDATA_STRUCT	= 1,
  GDK_PIXDATA_DUMP_MACROS		= 2,
  /* type of variables to use */
  GDK_PIXDATA_DUMP_GTYPES		= 0,
  GDK_PIXDATA_DUMP_CTYPES		= 1 << 8,
  GDK_PIXDATA_DUMP_STATIC		= 1 << 9,
  GDK_PIXDATA_DUMP_CONST		= 1 << 10,
  /* save RLE decoder macro? */
  GDK_PIXDATA_DUMP_RLE_DECODER		= 1 << 16
} GdkPixdataDumpType;

An enumeration which is used by gdk_pixdata_to_csource() to determine the form of C source to be generated. The three values GDK_PIXDATA_DUMP_PIXDATA_STREAM, GDK_PIXDATA_DUMP_PIXDATA_STRUCT and GDK_PIXDATA_DUMP_MACROS are mutually exclusive, as are GDK_PIXBUF_DUMP_GTYPES and GDK_PIXBUF_DUMP_CTYPES. The remaining elements are optional flags that can be freely added.

GDK_PIXDATA_DUMP_PIXDATA_STREAM | Generate pixbuf data stream (a single string containing a serialized GdkPixdata structure in network byte order).
GDK_PIXDATA_DUMP_PIXDATA_STRUCT | Generate GdkPixdata structure (needs the GdkPixdata structure definition from gdk-pixdata.h).
GDK_PIXDATA_DUMP_MACROS | Generate *_ROWSTRIDE, *_WIDTH, *_HEIGHT, *_BYTES_PER_PIXEL and *_RLE_PIXEL_DATA or *_PIXEL_DATA macro definitions for the image.
GDK_PIXDATA_DUMP_GTYPES | Generate GLib data types instead of standard C data types.
GDK_PIXDATA_DUMP_CTYPES | Generate standard C data types instead of GLib data types.
GDK_PIXDATA_DUMP_STATIC | Generate static symbols.
GDK_PIXDATA_DUMP_CONST | Generate const symbols.
GDK_PIXDATA_DUMP_RLE_DECODER | Provide a *_RUN_LENGTH_DECODE(image_buf, rle_data, size, bpp) macro definition to decode run-length encoded image data.

GDK_PIXBUF_MAGIC_NUMBER

#define GDK_PIXBUF_MAGIC_NUMBER (0x47646b50)    /* 'GdkP' */

Magic number for GdkPixdata structures.

GDK_PIXDATA_HEADER_LENGTH

#define	GDK_PIXDATA_HEADER_LENGTH	(4 + 4 + 4 + 4 + 4 + 4)

The length of a GdkPixdata structure without the pixel_data pointer.

gdk_pixdata_from_pixbuf ()

gpointer            gdk_pixdata_from_pixbuf             (GdkPixdata *pixdata,
                                                         const GdkPixbuf *pixbuf,
                                                         gboolean use_rle);

Converts a GdkPixbuf to a GdkPixdata. If use_rle is TRUE, the pixel data is run-length encoded into newly-allocated memory and a pointer to that memory is returned.

pixdata : | a GdkPixdata to fill.
pixbuf : | the data to fill pixdata with.
use_rle : | whether to use run-length encoding for the pixel data.
Returns : | If ure_rle is TRUE, a pointer to the newly-allocated memory for the run-length encoded pixel data, otherwise NULL.

gdk_pixbuf_from_pixdata ()

GdkPixbuf*          gdk_pixbuf_from_pixdata             (const GdkPixdata *pixdata,
                                                         gboolean copy_pixels,
                                                         GError **error);

Converts a GdkPixdata to a GdkPixbuf. If copy_pixels is TRUE or if the pixel data is run-length-encoded, the pixel data is copied into newly-allocated memory; otherwise it is reused.

pixdata : | a GdkPixdata to convert into a GdkPixbuf.
copy_pixels : | whether to copy raw pixel data; run-length encoded pixel data is always copied.
error : | location to store possible errors.
Returns : | a new GdkPixbuf.

gdk_pixdata_serialize ()

guint8*             gdk_pixdata_serialize               (const GdkPixdata *pixdata,
                                                         guint *stream_length_p);

Serializes a GdkPixdata structure into a byte stream. The byte stream consists of a straightforward writeout of the GdkPixdata fields in network byte order, plus the pixel_data bytes the structure points to.

pixdata : | a valid GdkPixdata structure to serialize.
stream_length_p : | location to store the resulting stream length in.
Returns : | A newly-allocated string containing the serialized GdkPixdata structure.

gdk_pixdata_deserialize ()

gboolean            gdk_pixdata_deserialize             (GdkPixdata *pixdata,
                                                         guint stream_length,
                                                         const guint8 *stream,
                                                         GError **error);

Deserializes (reconstruct) a GdkPixdata structure from a byte stream. The byte stream consists of a straightforward writeout of the GdkPixdata fields in network byte order, plus the pixel_data bytes the structure points to. The pixdata contents are reconstructed byte by byte and are checked for validity. This function may fail with GDK_PIXBUF_CORRUPT_IMAGE or GDK_PIXBUF_ERROR_UNKNOWN_TYPE.

pixdata : | a GdkPixdata structure to be filled in.
stream_length : | length of the stream used for deserialization.
stream : | stream of bytes containing a serialized GdkPixdata structure.
error : | GError location to indicate failures (maybe NULL to ignore errors).
Returns : | Upon successful deserialization TRUE is returned, FALSE otherwise.

gdk_pixdata_to_csource ()

GString*            gdk_pixdata_to_csource              (GdkPixdata *pixdata,
                                                         const gchar *name,
                                                         GdkPixdataDumpType dump_type);

Generates C source code suitable for compiling images directly into programs.

GTK+ ships with a program called gdk-pixbuf-csource which offers a command line interface to this function.

pixdata : | a GdkPixdata to convert to C source.
name : | used for naming generated data structures or macros.
dump_type : | a GdkPixdataDumpType determining the kind of C source to be generated.
Returns : | a newly-allocated string containing the C source form of pixdata.


Module Interface

Module Interface — Extending gdk-pixbuf

Synopsis

#include <gdk-pixbuf/gdk-pixbuf.h>

gboolean            gdk_pixbuf_set_option               (GdkPixbuf *pixbuf,
                                                         const gchar *key,
                                                         const gchar *value);
GSList*             gdk_pixbuf_get_formats              (void);
gchar*              gdk_pixbuf_format_get_name          (GdkPixbufFormat *format);
gchar*              gdk_pixbuf_format_get_description   (GdkPixbufFormat *format);
gchar**             gdk_pixbuf_format_get_mime_types    (GdkPixbufFormat *format);
gchar**             gdk_pixbuf_format_get_extensions    (GdkPixbufFormat *format);
gboolean            gdk_pixbuf_format_is_writable       (GdkPixbufFormat *format);
gboolean            gdk_pixbuf_format_is_scalable       (GdkPixbufFormat *format);
gboolean            gdk_pixbuf_format_is_disabled       (GdkPixbufFormat *format);
void                gdk_pixbuf_format_set_disabled      (GdkPixbufFormat *format,
                                                         gboolean disabled);
gchar*              gdk_pixbuf_format_get_license       (GdkPixbufFormat *format);
                    GdkPixbufFormat;
enum                GdkPixbufFormatFlags;
                    GdkPixbufModulePattern;
void                (*GdkPixbufModuleFillVtableFunc)    (GdkPixbufModule *module);
void                (*GdkPixbufModuleFillInfoFunc)      (GdkPixbufFormat *info);
void                (*GdkPixbufModuleSizeFunc)          (gint *width,
                                                         gint *height,
                                                         gpointer user_data);
void                (*GdkPixbufModulePreparedFunc)      (GdkPixbuf *pixbuf,
                                                         GdkPixbufAnimation *anim,
                                                         gpointer user_data);
void                (*GdkPixbufModuleUpdatedFunc)       (GdkPixbuf *pixbuf,
                                                         int x,
                                                         int y,
                                                         int width,
                                                         int height,
                                                         gpointer user_data);
                    GdkPixbufModule;

                    GdkPixbufAnimationClass;
                    GdkPixbufAnimationIterClass;

Description

If gdk-pixbuf has been compiled with GModule support, it can be extended by modules which can load (and perhaps also save) new image and animation formats. Each loadable module must export a GdkPixbufModuleFillInfoFunc function named fill_info and a GdkPixbufModuleFillVtableFunc function named fill_vtable.

In order to make format-checking work before actually loading the modules (which may require dlopening image libraries), modules export their signatures (and other information) via the fill_info function. An external utility, gdk-pixbuf-query-loaders, uses this to create a text file containing a list of all available loaders and their signatures. This file is then read at runtime by gdk-pixbuf to obtain the list of available loaders and their signatures.

Modules may only implement a subset of the functionality available via GdkPixbufModule. If a particular functionality is not implemented, the fill_vtable function will simply not set the corresponding function pointers of the GdkPixbufModule structure. If a module supports incremental loading (i.e. provides begin_load, stop_load and load_increment), it doesn't have to implement load, since gdk-pixbuf can supply a generic load implementation wrapping the incremental loading.

Installing a module is a two-step process:

  • copy the module file(s) to the loader directory (normally libdir/gtk-2.0/version/loaders, unless overridden by the environment variable GDK_PIXBUF_MODULEDIR)

  • call gdk-pixbuf-query-loaders to update the module file (normally sysconfdir/gtk-2.0/gdk-pixbuf.loaders, unless overridden by the environment variable GDK_PIXBUF_MODULE_FILE)

The gdk-pixbuf interfaces needed for implementing modules are contained in gdk-pixbuf-io.h (and gdk-pixbuf-animation.h if the module supports animations). They are not covered by the same stability guarantees as the regular gdk-pixbuf API. To underline this fact, they are protected by #ifdef GDK_PIXBUF_ENABLE_BACKEND.

Details

gdk_pixbuf_set_option ()

gboolean            gdk_pixbuf_set_option               (GdkPixbuf *pixbuf,
                                                         const gchar *key,
                                                         const gchar *value);

Attaches a key/value pair as an option to a GdkPixbuf. If key already exists in the list of options attached to pixbuf, the new value is ignored and FALSE is returned.

pixbuf : | a GdkPixbuf
key : | a nul-terminated string.
value : | a nul-terminated string.
Returns : | TRUE on success.

Since 2.2

gdk_pixbuf_get_formats ()

GSList*             gdk_pixbuf_get_formats              (void);

Obtains the available information about the image formats supported by GdkPixbuf.

Returns : A list of GdkPixbufFormats describing the supported image formats. The list should be freed when it is no longer needed, but the structures themselves are owned by GdkPixbuf and should not be freed.

Since 2.2

gdk_pixbuf_format_get_name ()

gchar*              gdk_pixbuf_format_get_name          (GdkPixbufFormat *format);

Returns the name of the format.

format : | a GdkPixbufFormat
Returns : | the name of the format.

Since 2.2

gdk_pixbuf_format_get_description ()

gchar*              gdk_pixbuf_format_get_description   (GdkPixbufFormat *format);

Returns a description of the format.

format : | a GdkPixbufFormat
Returns : | a description of the format.

Since 2.2

gdk_pixbuf_format_get_mime_types ()

gchar**             gdk_pixbuf_format_get_mime_types    (GdkPixbufFormat *format);

Returns the mime types supported by the format.

format : | a GdkPixbufFormat
Returns : | a NULL-terminated array of mime types which must be freed with g_strfreev() when it is no longer needed.

Since 2.2

gdk_pixbuf_format_get_extensions ()

gchar**             gdk_pixbuf_format_get_extensions    (GdkPixbufFormat *format);

Returns the filename extensions typically used for files in the given format.

format : | a GdkPixbufFormat
Returns : | a NULL-terminated array of filename extensions which must be freed with g_strfreev() when it is no longer needed.

Since 2.2

gdk_pixbuf_format_is_writable ()

gboolean            gdk_pixbuf_format_is_writable       (GdkPixbufFormat *format);

Returns whether pixbufs can be saved in the given format.

format : | a GdkPixbufFormat
Returns : | whether pixbufs can be saved in the given format.

Since 2.2

gdk_pixbuf_format_is_scalable ()

gboolean            gdk_pixbuf_format_is_scalable       (GdkPixbufFormat *format);

Returns whether this image format is scalable. If a file is in a scalable format, it is preferable to load it at the desired size, rather than loading it at the default size and scaling the resulting pixbuf to the desired size.

format : | a GdkPixbufFormat
Returns : | whether this image format is scalable.

Since 2.6

gdk_pixbuf_format_is_disabled ()

gboolean            gdk_pixbuf_format_is_disabled       (GdkPixbufFormat *format);

Returns whether this image format is disabled. See gdk_pixbuf_format_set_disabled().

format : | a GdkPixbufFormat
Returns : | whether this image format is disabled.

Since 2.6

gdk_pixbuf_format_set_disabled ()

void                gdk_pixbuf_format_set_disabled      (GdkPixbufFormat *format,
                                                         gboolean disabled);

Disables or enables an image format. If a format is disabled, gdk-pixbuf won't use the image loader for this format to load images. Applications can use this to avoid using image loaders with an inappropriate license, see gdk_pixbuf_format_get_license().

format : | a GdkPixbufFormat
disabled : | TRUE to disable the format format

Since 2.6

gdk_pixbuf_format_get_license ()

gchar*              gdk_pixbuf_format_get_license       (GdkPixbufFormat *format);

Returns information about the license of the image loader for the format. The returned string should be a shorthand for a wellknown license, e.g. "LGPL", "GPL", "QPL", "GPL/QPL", or "other" to indicate some other license. This string should be freed with g_free() when it's no longer needed.

format : | a GdkPixbufFormat
Returns : | a string describing the license of format.

Since 2.6

GdkPixbufFormat

typedef struct {
  gchar *name;
  GdkPixbufModulePattern *signature;
  gchar *domain;
  gchar *description;
  gchar **mime_types;
  gchar **extensions;
  guint32 flags;
  gboolean disabled;
  gchar *license;
} GdkPixbufFormat;

A GdkPixbufFormat contains information about the image format accepted by a module. Only modules should access the fields directly, applications should use the gdk_pixbuf_format_* functions.

gchar *name; | the name of the image format.
GdkPixbufModulePattern *signature; | the signature of the module.
gchar *domain; | the message domain for the description.
gchar *description; | a description of the image format.
gchar **mime_types; | a NULL-terminated array of MIME types for the image format.
gchar **extensions; | a NULL-terminated array of typical filename extensions for the image format.
guint32 flags; | a combination of GdkPixbufFormatFlags.
gboolean disabled; | a boolean determining whether the loader is disabled.
gchar *license; | a string containing license information, typically set to shorthands like "GPL", "LGPL", etc.

Since 2.2

enum GdkPixbufFormatFlags

typedef enum /*< skip >*/
{
  GDK_PIXBUF_FORMAT_WRITABLE = 1 << 0,
  GDK_PIXBUF_FORMAT_SCALABLE = 1 << 1,
  GDK_PIXBUF_FORMAT_THREADSAFE = 1 << 2
} GdkPixbufFormatFlags;

Flags which allow a module to specify further details about the supported operations.

GDK_PIXBUF_FORMAT_WRITABLE | the module can write out images in the format.
GDK_PIXBUF_FORMAT_SCALABLE | the image format is scalable
GDK_PIXBUF_FORMAT_THREADSAFE | the module is threadsafe. If this flag is not set, gdk-pixbuf will use a lock to prevent multiple threads from using this module at the same time. (Since 2.6)

Since 2.2

GdkPixbufModulePattern

typedef struct {
    char *prefix;
    char *mask;
    int relevance;
} GdkPixbufModulePattern;

The signature of a module is a set of prefixes. Prefixes are encoded as pairs of ordinary strings, where the second string, called the mask, if not NULL, must be of the same length as the first one and may contain ' ', '!', 'x', 'z', and 'n' to indicate bytes that must be matched, not matched, "don't-care"-bytes, zeros and non-zeros. Each prefix has an associated integer that describes the relevance of the prefix, with 0 meaning a mismatch and 100 a "perfect match".

Starting with gdk-pixbuf 2.8, the first byte of the mask may be '*', indicating an unanchored pattern that matches not only at the beginning, but also in the middle. Versions prior to 2.8 will interpret the '*' like an 'x'.

The signature of a module is stored as an array of GdkPixbufModulePatterns. The array is terminated by a pattern where the prefix is NULL.

GdkPixbufModulePattern *signature[] = {
  { "abcdx", " !x z", 100 },
  { "bla", NULL,  90 },
  { NULL, NULL, 0 }
};
The example matches e.g. "auud\0" with relevance 100, and "blau" with relevance 90.
char *prefix; | the prefix for this pattern
char *mask; | mask containing bytes which modify how the prefix is matched against test data
int relevance; | relevance of this pattern

Since 2.2

GdkPixbufModuleFillVtableFunc ()

void                (*GdkPixbufModuleFillVtableFunc)    (GdkPixbufModule *module);

Defines the type of the function used to set the vtable of a GdkPixbufModule when it is loaded.

module : a GdkPixbufModule.

Since 2.2

GdkPixbufModuleFillInfoFunc ()

void                (*GdkPixbufModuleFillInfoFunc)      (GdkPixbufFormat *info);

Defines the type of the function used to fill a GdkPixbufFormat structure with information about a module.

info : a GdkPixbufFormat.

Since 2.2

GdkPixbufModuleSizeFunc ()

void                (*GdkPixbufModuleSizeFunc)          (gint *width,
                                                         gint *height,
                                                         gpointer user_data);

Defines the type of the function that gets called once the size of the loaded image is known.

The function is expected to set width and height to the desired size to which the image should be scaled. If a module has no efficient way to achieve the desired scaling during the loading of the image, it may either ignore the size request, or only approximate it -- gdk-pixbuf will then perform the required scaling on the completely loaded image.

If the function sets width or height to zero, the module should interpret this as a hint that it will be closed soon and shouldn't allocate further resources. This convention is used to implement gdk_pixbuf_get_file_info() efficiently.

width : | pointer to a location containing the current image width
height : | pointer to a location containing the current image height
user_data : | the loader.

Since 2.2

GdkPixbufModulePreparedFunc ()

void                (*GdkPixbufModulePreparedFunc)      (GdkPixbuf *pixbuf,
                                                         GdkPixbufAnimation *anim,
                                                         gpointer user_data);

Defines the type of the function that gets called once the initial setup of pixbuf is done.

GdkPixbufLoader uses a function of this type to emit the "area_prepared" signal.

pixbuf : | the GdkPixbuf that is currently being loaded.
anim : | if an animation is being loaded, the GdkPixbufAnimation, else NULL.
user_data : | the loader.

Since 2.2

GdkPixbufModuleUpdatedFunc ()

void                (*GdkPixbufModuleUpdatedFunc)       (GdkPixbuf *pixbuf,
                                                         int x,
                                                         int y,
                                                         int width,
                                                         int height,
                                                         gpointer user_data);

Defines the type of the function that gets called every time a region of pixbuf is updated.

GdkPixbufLoader uses a function of this type to emit the "area_updated" signal.

pixbuf : | the GdkPixbuf that is currently being loaded.
x : | the X origin of the updated area.
y : | the Y origin of the updated area.
width : | the width of the updated area.
height : | the height of the updated area.
user_data : | the loader.

Since 2.2

GdkPixbufModule

typedef struct {
    char *module_name;
    char *module_path;
    GModule *module;
    GdkPixbufFormat *info;

        GdkPixbuf *(* load) (FILE    *f,
                             GError **error);
        GdkPixbuf *(* load_xpm_data) (const char **data);

        /* Incremental loading */

        gpointer (* begin_load)     (GdkPixbufModuleSizeFunc size_func,
                                     GdkPixbufModulePreparedFunc prepare_func,
                                     GdkPixbufModuleUpdatedFunc update_func,
                                     gpointer user_data,
                                     GError **error);
        gboolean (* stop_load)      (gpointer context,
                                     GError **error);
        gboolean (* load_increment) (gpointer      context,
                                     const guchar *buf,
                                     guint         size,
                                     GError      **error);

    /* Animation loading */
    GdkPixbufAnimation *(* load_animation) (FILE    *f,
                                                GError **error);

        /* Saving */
        gboolean (* save) (FILE      *f,
                           GdkPixbuf *pixbuf,
                           gchar    **param_keys,
                           gchar    **param_values,
                           GError   **error);

        gboolean (*save_to_callback) (GdkPixbufSaveFunc save_func,
                      gpointer user_data,
                      GdkPixbuf *pixbuf,
                      gchar **option_keys,
                      gchar **option_values,
                      GError **error);
} GdkPixbufModule;

A GdkPixbufModule contains the necessary functions to load and save images in a certain file format.

A GdkPixbufModule can be loaded dynamically from a GModule. Each loadable module must contain a GdkPixbufModuleFillVtableFunc function named fill_vtable, which will get called when the module is loaded and must set the function pointers of the GdkPixbufModule.

char *module_name; | the name of the module, usually the same as the usual file extension for images of this type, eg. "xpm", "jpeg" or "png".
char *module_path; | the path from which the module is loaded.
GModule *module; | the loaded GModule.
GdkPixbufFormat *info; | a GdkPixbufFormat holding information about the module.
load () | loads an image from a file.
load_xpm_data () | loads an image from data in memory.
begin_load () | begins an incremental load.
stop_load () | stops an incremental load.
load_increment () | continues an incremental load.
load_animation () | loads an animation from a file.
save () | saves a GdkPixbuf to a file.
save_to_callback () | saves a GdkPixbuf by calling the given GdkPixbufSaveFunc.

GdkPixbufAnimationClass

typedef struct {
        GObjectClass parent_class;

        gboolean                (*is_static_image)  (GdkPixbufAnimation *anim);

        GdkPixbuf*              (*get_static_image) (GdkPixbufAnimation *anim);

        void                    (*get_size) (GdkPixbufAnimation *anim,
                                             int                 *width,
                                             int                 *height);

        GdkPixbufAnimationIter* (*get_iter) (GdkPixbufAnimation *anim,
                                             const GTimeVal     *start_time);
} GdkPixbufAnimationClass;

Modules supporting animations must derive a type from GdkPixbufAnimation, providing suitable implementations of the virtual functions.

GObjectClass parent_class; | the parent class
is_static_image () | returns whether the given animation is just a static image.
get_static_image () | returns a static image representing the given animation.
get_size () | fills width and height with the frame size of the animation.
get_iter () | returns an iterator for the given animation.

GdkPixbufAnimationIterClass

typedef struct {
        GObjectClass parent_class;

        int        (*get_delay_time)   (GdkPixbufAnimationIter *iter);

        GdkPixbuf* (*get_pixbuf)       (GdkPixbufAnimationIter *iter);

        gboolean   (*on_currently_loading_frame) (GdkPixbufAnimationIter *iter);

        gboolean   (*advance)          (GdkPixbufAnimationIter *iter,
                                        const GTimeVal         *current_time);
} GdkPixbufAnimationIterClass;

Modules supporting animations must derive a type from GdkPixbufAnimationIter, providing suitable implementations of the virtual functions.

GObjectClass parent_class; | the parent class
get_delay_time () | returns the time in milliseconds that the current frame should be shown.
get_pixbuf () | returns the current frame.
on_currently_loading_frame () | returns whether the current frame of iter is being loaded.
advance () | advances the iterator to current_time, possibly changing the current frame.


gdk-pixbuf-query-loaders

gdk-pixbuf-query-loaders — GdkPixbuf loader registration utility

Synopsis

gdk-pixbuf-query-loaders [module...]

Description

gdk-pixbuf-query-loaders collects information about loadable modules for gdk-pixbuf and writes it to stdout.

If called without arguments, it looks for modules in the gdk-pixbuf loader directory.

If called with arguments, it looks for the specified modules. The arguments may be absolute or relative paths.

Environment

The environment variable GDK_PIXBUF_MODULEDIR can be used to specify a different loader directory. The default gdk-pixbuf loader directory is libdir/gtk-2.0/version/loaders.

Bugs

None known yet.


Reference Counting and Memory Mangement

Reference Counting and Memory Mangement — Functions for reference counting and memory management on pixbufs.

Synopsis

#include <gdk-pixbuf/gdk-pixbuf.h>

GdkPixbuf*          gdk_pixbuf_ref                      (GdkPixbuf *pixbuf);
void                gdk_pixbuf_unref                    (GdkPixbuf *pixbuf);
void                (*GdkPixbufDestroyNotify)           (guchar *pixels,
                                                         gpointer data);

Description

GdkPixbuf structures are reference counted. This means that an application can share a single pixbuf among many parts of the code. When a piece of the program needs to keep a pointer to a pixbuf, it should add a reference to it by calling g_object_ref(). When it no longer needs the pixbuf, it should subtract a reference by calling g_object_unref(). The pixbuf will be destroyed when its reference count drops to zero. Newly-created GdkPixbuf structures start with a reference count of one.

Note

As GdkPixbuf is derived from GObject now, gdk_pixbuf_ref() and gdk_pixbuf_unref() are deprecated in favour of g_object_ref() and g_object_unref() resp.

Finalizing a pixbuf means to free its pixel data and to free the GdkPixbuf structure itself. Most of the library functions that create GdkPixbuf structures create the pixel data by themselves and define the way it should be freed; you do not need to worry about those. The only function that lets you specify how to free the pixel data is gdk_pixbuf_new_from_data(). Since you pass it a pre-allocated pixel buffer, you must also specify a way to free that data. This is done with a function of type GdkPixbufDestroyNotify. When a pixbuf created with gdk_pixbuf_new_from_data() is finalized, your destroy notification function will be called, and it is its responsibility to free the pixel array.

Details

gdk_pixbuf_ref ()

GdkPixbuf*          gdk_pixbuf_ref                      (GdkPixbuf *pixbuf);

Warning

gdk_pixbuf_ref is deprecated and should not be used in newly-written code. Use g_object_ref().

Adds a reference to a pixbuf.

pixbuf : | A pixbuf.
Returns : | The same as the pixbuf argument.

gdk_pixbuf_unref ()

void                gdk_pixbuf_unref                    (GdkPixbuf *pixbuf);

Warning

gdk_pixbuf_unref is deprecated and should not be used in newly-written code. Use g_object_unref().

Removes a reference from a pixbuf.

pixbuf : A pixbuf.

GdkPixbufDestroyNotify ()

void                (*GdkPixbufDestroyNotify)           (guchar *pixels,
                                                         gpointer data);

A function of this type is responsible for freeing the pixel array of a pixbuf. The gdk_pixbuf_new_from_data() function lets you pass in a pre-allocated pixel array so that a pixbuf can be created from it; in this case you will need to pass in a function of GdkPixbufDestroyNotify so that the pixel data can be freed when the pixbuf is finalized.

pixels : | The pixel array of the pixbuf that is being finalized.
data : | User closure data.

See Also

GdkPixbuf, gdk_pixbuf_new_from_data().


Scaling

Scaling — Scaling pixbufs and scaling and compositing pixbufs

Synopsis

#include <gdk-pixbuf/gdk-pixbuf.h>

enum                GdkInterpType;
GdkPixbuf*          gdk_pixbuf_scale_simple             (const GdkPixbuf *src,
                                                         int dest_width,
                                                         int dest_height,
                                                         GdkInterpType interp_type);
void                gdk_pixbuf_scale                    (const GdkPixbuf *src,
                                                         GdkPixbuf *dest,
                                                         int dest_x,
                                                         int dest_y,
                                                         int dest_width,
                                                         int dest_height,
                                                         double offset_x,
                                                         double offset_y,
                                                         double scale_x,
                                                         double scale_y,
                                                         GdkInterpType interp_type);
GdkPixbuf*          gdk_pixbuf_composite_color_simple   (const GdkPixbuf *src,
                                                         int dest_width,
                                                         int dest_height,
                                                         GdkInterpType interp_type,
                                                         int overall_alpha,
                                                         int check_size,
                                                         guint32 color1,
                                                         guint32 color2);
void                gdk_pixbuf_composite                (const GdkPixbuf *src,
                                                         GdkPixbuf *dest,
                                                         int dest_x,
                                                         int dest_y,
                                                         int dest_width,
                                                         int dest_height,
                                                         double offset_x,
                                                         double offset_y,
                                                         double scale_x,
                                                         double scale_y,
                                                         GdkInterpType interp_type,
                                                         int overall_alpha);
void                gdk_pixbuf_composite_color          (const GdkPixbuf *src,
                                                         GdkPixbuf *dest,
                                                         int dest_x,
                                                         int dest_y,
                                                         int dest_width,
                                                         int dest_height,
                                                         double offset_x,
                                                         double offset_y,
                                                         double scale_x,
                                                         double scale_y,
                                                         GdkInterpType interp_type,
                                                         int overall_alpha,
                                                         int check_x,
                                                         int check_y,
                                                         int check_size,
                                                         guint32 color1,
                                                         guint32 color2);
enum                GdkPixbufRotation;
GdkPixbuf*          gdk_pixbuf_rotate_simple            (const GdkPixbuf *src,
                                                         GdkPixbufRotation angle);
GdkPixbuf*          gdk_pixbuf_flip                     (const GdkPixbuf *src,
                                                         gboolean horizontal);

Description

The gdk-pixbuf contains functions to scale pixbufs, to scale pixbufs and composite against an existing image, and to scale pixbufs and composite against a solid color or checkerboard. Compositing a checkerboard is a common way to show an image with an alpha channel in image-viewing and editing software.

Since the full-featured functions (gdk_pixbuf_scale(), gdk_pixbuf_composite(), and gdk_pixbuf_composite_color()) are rather complex to use and have many arguments, two simple convenience functions are provided, gdk_pixbuf_scale_simple() and gdk_pixbuf_composite_color_simple() which create a new pixbuf of a given size, scale an original image to fit, and then return the new pixbuf.

The following example demonstrates handling an expose event by rendering the appropriate area of a source image (which is scaled to fit the widget) onto the widget's window. The source image is rendered against a checkerboard, which provides a visual representation of the alpha channel if the image has one. If the image doesn't have an alpha channel, calling gdk_pixbuf_composite_color() function has exactly the same effect as calling gdk_pixbuf_scale().

Example 2. Handling an expose event.

gboolean
expose_cb (GtkWidget *widget, GdkEventExpose *event, gpointer data)
{
  GdkPixbuf *dest;

  dest = gdk_pixbuf_new (GDK_COLORSPACE_RGB, FALSE, 8, event->area.width, event->area.height);

  gdk_pixbuf_composite_color (pixbuf, dest,
                              0, 0, event->area.width, event->area.height,
                              -event->area.x, -event->area.y,
                              (double) widget->allocation.width / gdk_pixbuf_get_width (pixbuf),
                              (double) widget->allocation.height / gdk_pixbuf_get_height (pixbuf),
                              GDK_INTERP_BILINEAR, 255,
                              event->area.x, event->area.y, 16, 0xaaaaaa, 0x555555);

  gdk_pixbuf_render_to_drawable (dest, widget->window, widget->style->fg_gc[GTK_STATE_NORMAL],
                                 0, 0, event->area.x, event->area.y,
                                 event->area.width, event->area.height,
                                 GDK_RGB_DITHER_NORMAL, event->area.x, event->area.y);

  gdk_pixbuf_unref (dest);

  return TRUE;
}

Details

enum GdkInterpType

typedef enum {
    GDK_INTERP_NEAREST,
    GDK_INTERP_TILES,
    GDK_INTERP_BILINEAR,
    GDK_INTERP_HYPER
} GdkInterpType;

This enumeration describes the different interpolation modes that can be used with the scaling functions. GDK_INTERP_NEAREST is the fastest scaling method, but has horrible quality when scaling down. GDK_INTERP_BILINEAR is the best choice if you aren't sure what to choose, it has a good speed/quality balance.

Note

Cubic filtering is missing from the list; hyperbolic interpolation is just as fast and results in higher quality.

GDK_INTERP_NEAREST | Nearest neighbor sampling; this is the fastest and lowest quality mode. Quality is normally unacceptable when scaling down, but may be OK when scaling up.
GDK_INTERP_TILES | This is an accurate simulation of the PostScript image operator without any interpolation enabled. Each pixel is rendered as a tiny parallelogram of solid color, the edges of which are implemented with antialiasing. It resembles nearest neighbor for enlargement, and bilinear for reduction.
GDK_INTERP_BILINEAR | Best quality/speed balance; use this mode by default. Bilinear interpolation. For enlargement, it is equivalent to point-sampling the ideal bilinear-interpolated image. For reduction, it is equivalent to laying down small tiles and integrating over the coverage area.
GDK_INTERP_HYPER | This is the slowest and highest quality reconstruction function. It is derived from the hyperbolic filters in Wolberg's "Digital Image Warping", and is formally defined as the hyperbolic-filter sampling the ideal hyperbolic-filter interpolated image (the filter is designed to be idempotent for 1:1 pixel mapping).

gdk_pixbuf_scale_simple ()

GdkPixbuf*          gdk_pixbuf_scale_simple             (const GdkPixbuf *src,
                                                         int dest_width,
                                                         int dest_height,
                                                         GdkInterpType interp_type);

Create a new GdkPixbuf containing a copy of src scaled to dest_width x dest_height. Leaves src unaffected. interp_type should be GDK_INTERP_NEAREST if you want maximum speed (but when scaling down GDK_INTERP_NEAREST is usually unusably ugly). The default interp_type should be GDK_INTERP_BILINEAR which offers reasonable quality and speed.

You can scale a sub-portion of src by creating a sub-pixbuf pointing into src; see gdk_pixbuf_new_subpixbuf().

For more complicated scaling/compositing see gdk_pixbuf_scale() and gdk_pixbuf_composite().

src : | a GdkPixbuf
dest_width : | the width of destination image
dest_height : | the height of destination image
interp_type : | the interpolation type for the transformation.
Returns : | the new GdkPixbuf, or NULL if not enough memory could be allocated for it.

gdk_pixbuf_scale ()

void                gdk_pixbuf_scale                    (const GdkPixbuf *src,
                                                         GdkPixbuf *dest,
                                                         int dest_x,
                                                         int dest_y,
                                                         int dest_width,
                                                         int dest_height,
                                                         double offset_x,
                                                         double offset_y,
                                                         double scale_x,
                                                         double scale_y,
                                                         GdkInterpType interp_type);

Creates a transformation of the source image src by scaling by scale_x and scale_y then translating by offset_x and offset_y, then renders the rectangle (dest_x, dest_y, dest_width, dest_height) of the resulting image onto the destination image replacing the previous contents.

Try to use gdk_pixbuf_scale_simple() first, this function is the industrial-strength power tool you can fall back to if gdk_pixbuf_scale_simple() isn't powerful enough.

src : | a GdkPixbuf
dest : | the GdkPixbuf into which to render the results
dest_x : | the left coordinate for region to render
dest_y : | the top coordinate for region to render
dest_width : | the width of the region to render
dest_height : | the height of the region to render
offset_x : | the offset in the X direction (currently rounded to an integer)
offset_y : | the offset in the Y direction (currently rounded to an integer)
scale_x : | the scale factor in the X direction
scale_y : | the scale factor in the Y direction
interp_type : | the interpolation type for the transformation.

gdk_pixbuf_composite_color_simple ()

GdkPixbuf*          gdk_pixbuf_composite_color_simple   (const GdkPixbuf *src,
                                                         int dest_width,
                                                         int dest_height,
                                                         GdkInterpType interp_type,
                                                         int overall_alpha,
                                                         int check_size,
                                                         guint32 color1,
                                                         guint32 color2);

Creates a new GdkPixbuf by scaling src to dest_width x dest_height and compositing the result with a checkboard of colors color1 and color2.

src : | a GdkPixbuf
dest_width : | the width of destination image
dest_height : | the height of destination image
interp_type : | the interpolation type for the transformation.
overall_alpha : | overall alpha for source image (0..255)
check_size : | the size of checks in the checkboard (must be a power of two)
color1 : | the color of check at upper left
color2 : | the color of the other check
Returns : | the new GdkPixbuf, or NULL if not enough memory could be allocated for it.

gdk_pixbuf_composite ()

void                gdk_pixbuf_composite                (const GdkPixbuf *src,
                                                         GdkPixbuf *dest,
                                                         int dest_x,
                                                         int dest_y,
                                                         int dest_width,
                                                         int dest_height,
                                                         double offset_x,
                                                         double offset_y,
                                                         double scale_x,
                                                         double scale_y,
                                                         GdkInterpType interp_type,
                                                         int overall_alpha);

Creates a transformation of the source image src by scaling by scale_x and scale_y then translating by offset_x and offset_y. This gives an image in the coordinates of the destination pixbuf. The rectangle (dest_x, dest_y, dest_width, dest_height) is then composited onto the corresponding rectangle of the original destination image.

When the destination rectangle contains parts not in the source image, the data at the edges of the source image is replicated to infinity.

Figure 1. Compositing of pixbufs

Compositing of pixbufs

src : | a GdkPixbuf
dest : | the GdkPixbuf into which to render the results
dest_x : | the left coordinate for region to render
dest_y : | the top coordinate for region to render
dest_width : | the width of the region to render
dest_height : | the height of the region to render
offset_x : | the offset in the X direction (currently rounded to an integer)
offset_y : | the offset in the Y direction (currently rounded to an integer)
scale_x : | the scale factor in the X direction
scale_y : | the scale factor in the Y direction
interp_type : | the interpolation type for the transformation.
overall_alpha : | overall alpha for source image (0..255)

gdk_pixbuf_composite_color ()

void                gdk_pixbuf_composite_color          (const GdkPixbuf *src,
                                                         GdkPixbuf *dest,
                                                         int dest_x,
                                                         int dest_y,
                                                         int dest_width,
                                                         int dest_height,
                                                         double offset_x,
                                                         double offset_y,
                                                         double scale_x,
                                                         double scale_y,
                                                         GdkInterpType interp_type,
                                                         int overall_alpha,
                                                         int check_x,
                                                         int check_y,
                                                         int check_size,
                                                         guint32 color1,
                                                         guint32 color2);

Creates a transformation of the source image src by scaling by scale_x and scale_y then translating by offset_x and offset_y, then composites the rectangle (dest_x ,dest_y, dest_width, dest_height) of the resulting image with a checkboard of the colors color1 and color2 and renders it onto the destination image.

See gdk_pixbuf_composite_color_simple() for a simpler variant of this function suitable for many tasks.

src : | a GdkPixbuf
dest : | the GdkPixbuf into which to render the results
dest_x : | the left coordinate for region to render
dest_y : | the top coordinate for region to render
dest_width : | the width of the region to render
dest_height : | the height of the region to render
offset_x : | the offset in the X direction (currently rounded to an integer)
offset_y : | the offset in the Y direction (currently rounded to an integer)
scale_x : | the scale factor in the X direction
scale_y : | the scale factor in the Y direction
interp_type : | the interpolation type for the transformation.
overall_alpha : | overall alpha for source image (0..255)
check_x : | the X offset for the checkboard (origin of checkboard is at -check_x, -check_y)
check_y : | the Y offset for the checkboard
check_size : | the size of checks in the checkboard (must be a power of two)
color1 : | the color of check at upper left
color2 : | the color of the other check

enum GdkPixbufRotation

typedef enum {
    GDK_PIXBUF_ROTATE_NONE             =   0,
    GDK_PIXBUF_ROTATE_COUNTERCLOCKWISE =  90,
    GDK_PIXBUF_ROTATE_UPSIDEDOWN       = 180,
    GDK_PIXBUF_ROTATE_CLOCKWISE        = 270
} GdkPixbufRotation;

The possible rotations which can be passed to gdk_pixbuf_rotate_simple(). To make them easier to use, their numerical values are the actual degrees.

GDK_PIXBUF_ROTATE_NONE | No rotation.
GDK_PIXBUF_ROTATE_COUNTERCLOCKWISE | Rotate by 90 degrees.
GDK_PIXBUF_ROTATE_UPSIDEDOWN | Rotate by 180 degrees.
GDK_PIXBUF_ROTATE_CLOCKWISE | Rotate by 270 degrees.

gdk_pixbuf_rotate_simple ()

GdkPixbuf*          gdk_pixbuf_rotate_simple            (const GdkPixbuf *src,
                                                         GdkPixbufRotation angle);

Rotates a pixbuf by a multiple of 90 degrees, and returns the result in a new pixbuf.

src : | a GdkPixbuf
angle : | the angle to rotate by
Returns : | a new pixbuf

Since 2.6

gdk_pixbuf_flip ()

GdkPixbuf*          gdk_pixbuf_flip                     (const GdkPixbuf *src,
                                                         gboolean horizontal);

Flips a pixbuf horizontally or vertically and returns the result in a new pixbuf.

src : | a GdkPixbuf
horizontal : | TRUE to flip horizontally, FALSE to flip vertically
Returns : | a new pixbuf.

Since 2.6

See Also

GdkRGB.


Utilities

Utilities — Utility and miscellaneous convenience functions.

Synopsis

#include <gdk-pixbuf/gdk-pixbuf.h>

GdkPixbuf*          gdk_pixbuf_add_alpha                (const GdkPixbuf *pixbuf,
                                                         gboolean substitute_color,
                                                         guchar r,
                                                         guchar g,
                                                         guchar b);
void                gdk_pixbuf_copy_area                (const GdkPixbuf *src_pixbuf,
                                                         int src_x,
                                                         int src_y,
                                                         int width,
                                                         int height,
                                                         GdkPixbuf *dest_pixbuf,
                                                         int dest_x,
                                                         int dest_y);
void                gdk_pixbuf_saturate_and_pixelate    (const GdkPixbuf *src,
                                                         GdkPixbuf *dest,
                                                         gfloat saturation,
                                                         gboolean pixelate);
void                gdk_pixbuf_fill                     (GdkPixbuf *pixbuf,
                                                         guint32 pixel);

Description

These functions provide miscellaneous utilities for manipulating pixbufs. The pixel data in pixbufs may of course be manipulated directly by applications, but several common operations can be performed by these functions instead.

Details

gdk_pixbuf_add_alpha ()

GdkPixbuf*          gdk_pixbuf_add_alpha                (const GdkPixbuf *pixbuf,
                                                         gboolean substitute_color,
                                                         guchar r,
                                                         guchar g,
                                                         guchar b);

Takes an existing pixbuf and adds an alpha channel to it. If the existing pixbuf already had an alpha channel, the channel values are copied from the original; otherwise, the alpha channel is initialized to 255 (full opacity).

If substitute_color is TRUE, then the color specified by (r, g, b) will be assigned zero opacity. That is, if you pass (255, 255, 255) for the substitute color, all white pixels will become fully transparent.

pixbuf : | A GdkPixbuf.
substitute_color : | Whether to set a color to zero opacity. If this is FALSE, then the (r, g, b) arguments will be ignored.
r : | Red value to substitute.
g : | Green value to substitute.
b : | Blue value to substitute.
Returns : | A newly-created pixbuf with a reference count of 1.

gdk_pixbuf_copy_area ()

void                gdk_pixbuf_copy_area                (const GdkPixbuf *src_pixbuf,
                                                         int src_x,
                                                         int src_y,
                                                         int width,
                                                         int height,
                                                         GdkPixbuf *dest_pixbuf,
                                                         int dest_x,
                                                         int dest_y);

Copies a rectangular area from src_pixbuf to dest_pixbuf. Conversion of pixbuf formats is done automatically.

src_pixbuf : | Source pixbuf.
src_x : | Source X coordinate within src_pixbuf.
src_y : | Source Y coordinate within src_pixbuf.
width : | Width of the area to copy.
height : | Height of the area to copy.
dest_pixbuf : | Destination pixbuf.
dest_x : | X coordinate within dest_pixbuf.
dest_y : | Y coordinate within dest_pixbuf.

gdk_pixbuf_saturate_and_pixelate ()

void                gdk_pixbuf_saturate_and_pixelate    (const GdkPixbuf *src,
                                                         GdkPixbuf *dest,
                                                         gfloat saturation,
                                                         gboolean pixelate);

Modifies saturation and optionally pixelates src, placing the result in dest. src and dest may be the same pixbuf with no ill effects. If saturation is 1.0 then saturation is not changed. If it's less than 1.0, saturation is reduced (the image turns toward grayscale); if greater than 1.0, saturation is increased (the image gets more vivid colors). If pixelate is TRUE, then pixels are faded in a checkerboard pattern to create a pixelated image. src and dest must have the same image format, size, and rowstride.

src : | source image
dest : | place to write modified version of src
saturation : | saturation factor
pixelate : | whether to pixelate

gdk_pixbuf_fill ()

void                gdk_pixbuf_fill                     (GdkPixbuf *pixbuf,
                                                         guint32 pixel);

Clears a pixbuf to the given RGBA value, converting the RGBA value into the pixbuf's pixel format. The alpha will be ignored if the pixbuf doesn't have an alpha channel.

pixbuf : | a GdkPixbuf
pixel : | RGBA pixel to clear to (0xffffffff is opaque white, 0x00000000 transparent black)

See Also

GdkPixbuf


Initialization and Versions

Initialization and Versions — Library version numbers.

Synopsis

#include <gdk-pixbuf/gdk-pixbuf.h>

extern              const char *gdk_pixbuf_version;
extern              const guint gdk_pixbuf_major_version;
extern              const guint gdk_pixbuf_minor_version;
extern              const guint gdk_pixbuf_micro_version;
#define             GDK_PIXBUF_VERSION
#define             GDK_PIXBUF_MAJOR
#define             GDK_PIXBUF_MINOR
#define             GDK_PIXBUF_MICRO

Description

These macros and variables let you check the version of gdk-pixbuf you're linking against.

Details

gdk_pixbuf_version

extern const char *gdk_pixbuf_version;

Contains the full version of the gdk-pixbuf library as a string. This is the version currently in use by a running program.

gdk_pixbuf_major_version

extern const guint gdk_pixbuf_major_version;

The major version number of the gdk-pixbuf library. (e.g. in gdk-pixbuf version 1.2.5 this is 1.)

This variable is in the library, so represents the gdk-pixbuf library you have linked against. Contrast with the GDK_PIXBUF_MAJOR macro, which represents the major version of the gdk-pixbuf headers you have included.

gdk_pixbuf_minor_version

extern const guint gdk_pixbuf_minor_version;

The minor version number of the gdk-pixbuf library. (e.g. in gdk-pixbuf version 1.2.5 this is 2.)

This variable is in the library, so represents the gdk-pixbuf library you have linked against. Contrast with the GDK_PIXBUF_MINOR macro, which represents the minor version of the gdk-pixbuf headers you have included.

gdk_pixbuf_micro_version

extern const guint gdk_pixbuf_micro_version;

The micro version number of the gdk-pixbuf library. (e.g. in gdk-pixbuf version 1.2.5 this is 5.)

This variable is in the library, so represents the gdk-pixbuf library you have linked against. Contrast with the GDK_PIXBUF_MICRO macro, which represents the micro version of the gdk-pixbuf headers you have included.

GDK_PIXBUF_VERSION

#define GDK_PIXBUF_VERSION "2.10.11"

Contains the full version of the gdk-pixbuf header as a string. This is the version being compiled against; contrast with gdk_pixbuf_version.

GDK_PIXBUF_MAJOR

#define GDK_PIXBUF_MAJOR (2)

Major version of gdk-pixbuf library, that is the first "0" in "0.8.0" for example.

GDK_PIXBUF_MINOR

#define GDK_PIXBUF_MINOR (10)

Minor version of gdk-pixbuf library, that is the "8" in "0.8.0" for example.

GDK_PIXBUF_MICRO

#define GDK_PIXBUF_MICRO (11)

Micro version of gdk-pixbuf library, that is the last "0" in "0.8.0" for example.


GdkPixbufLoader

GdkPixbufLoader — Application-driven progressive image loading.

Synopsis

#include <gdk-pixbuf/gdk-pixbuf.h>

                    GdkPixbufLoader;
GdkPixbufLoader*    gdk_pixbuf_loader_new               (void);
GdkPixbufLoader*    gdk_pixbuf_loader_new_with_type     (const char *image_type,
                                                         GError **error);
GdkPixbufLoader*    gdk_pixbuf_loader_new_with_mime_type
                                                        (const char *mime_type,
                                                         GError **error);
GdkPixbufFormat*    gdk_pixbuf_loader_get_format        (GdkPixbufLoader *loader);
gboolean            gdk_pixbuf_loader_write             (GdkPixbufLoader *loader,
                                                         const guchar *buf,
                                                         gsize count,
                                                         GError **error);
void                gdk_pixbuf_loader_set_size          (GdkPixbufLoader *loader,
                                                         int width,
                                                         int height);
GdkPixbuf*          gdk_pixbuf_loader_get_pixbuf        (GdkPixbufLoader *loader);
GdkPixbufAnimation* gdk_pixbuf_loader_get_animation     (GdkPixbufLoader *loader);
gboolean            gdk_pixbuf_loader_close             (GdkPixbufLoader *loader,
                                                         GError **error);

Object Hierarchy

  GObject
   +----GdkPixbufLoader

Signals

  "area-prepared"                                  : Run Last
  "area-updated"                                   : Run Last
  "closed"                                         : Run Last
  "size-prepared"                                  : Run Last

Description

GdkPixbufLoader provides a way for applications to drive the process of loading an image, by letting them send the image data directly to the loader instead of having the loader read the data from a file. Applications can use this functionality instead of gdk_pixbuf_new_from_file() or gdk_pixbuf_animation_new_from_file() when they need to parse image data in small chunks. For example, it should be used when reading an image from a (potentially) slow network connection, or when loading an extremely large file.

To use GdkPixbufLoader to load an image, just create a new one, and call gdk_pixbuf_loader_write() to send the data to it. When done, gdk_pixbuf_loader_close() should be called to end the stream and finalize everything. The loader will emit three important signals throughout the process. The first, "size_prepared", will be called as soon as the image has enough information to determine the size of the image to be used. If you want to scale the image while loading it, you can call gdk_pixbuf_loader_set_size() in response to this signal.

The second signal, "area_prepared", will be called as soon as the pixbuf of the desired has been allocated. You can obtain it by calling gdk_pixbuf_loader_get_pixbuf(). If you want to use it, simply ref it. In addition, no actual information will be passed in yet, so the pixbuf can be safely filled with any temporary graphics (or an initial color) as needed. You can also call gdk_pixbuf_loader_get_pixbuf() later and get the same pixbuf.

The last signal, "area_updated" gets called every time a region is updated. This way you can update a partially completed image. Note that you do not know anything about the completeness of an image from the area updated. For example, in an interlaced image, you need to make several passes before the image is done loading.

Loading an animation

Loading an animation is almost as easy as loading an image. Once the first "area_prepared" signal has been emitted, you can call gdk_pixbuf_loader_get_animation() to get the GdkPixbufAnimation struct and gdk_pixbuf_animation_get_iter() to get an GdkPixbufAnimationIter for displaying it.

Details

GdkPixbufLoader

typedef struct _GdkPixbufLoader GdkPixbufLoader;

The GdkPixbufLoader struct contains only private fields.

gdk_pixbuf_loader_new ()

GdkPixbufLoader*    gdk_pixbuf_loader_new               (void);

Creates a new pixbuf loader object.

Returns : A newly-created pixbuf loader.

gdk_pixbuf_loader_new_with_type ()

GdkPixbufLoader*    gdk_pixbuf_loader_new_with_type     (const char *image_type,
                                                         GError **error);

Creates a new pixbuf loader object that always attempts to parse image data as if it were an image of type image_type, instead of identifying the type automatically. Useful if you want an error if the image isn't the expected type, for loading image formats that can't be reliably identified by looking at the data, or if the user manually forces a specific type.

The list of supported image formats depends on what image loaders are installed, but typically "png", "jpeg", "gif", "tiff" and "xpm" are among the supported formats. To obtain the full list of supported image formats, call gdk_pixbuf_format_get_name() on each of the GdkPixbufFormat structs returned by gdk_pixbuf_get_formats().

image_type : | name of the image format to be loaded with the image
error : | return location for an allocated GError, or NULL to ignore errors
Returns : | A newly-created pixbuf loader.

gdk_pixbuf_loader_new_with_mime_type ()

GdkPixbufLoader*    gdk_pixbuf_loader_new_with_mime_type
                                                        (const char *mime_type,
                                                         GError **error);

Creates a new pixbuf loader object that always attempts to parse image data as if it were an image of mime type mime_type, instead of identifying the type automatically. Useful if you want an error if the image isn't the expected mime type, for loading image formats that can't be reliably identified by looking at the data, or if the user manually forces a specific mime type.

The list of supported mime types depends on what image loaders are installed, but typically "image/png", "image/jpeg", "image/gif", "image/tiff" and "image/x-xpixmap" are among the supported mime types. To obtain the full list of supported mime types, call gdk_pixbuf_format_get_mime_types() on each of the GdkPixbufFormat structs returned by gdk_pixbuf_get_formats().

mime_type : | the mime type to be loaded
error : | return location for an allocated GError, or NULL to ignore errors
Returns : | A newly-created pixbuf loader.

Since 2.4

gdk_pixbuf_loader_get_format ()

GdkPixbufFormat*    gdk_pixbuf_loader_get_format        (GdkPixbufLoader *loader);

Obtains the available information about the format of the currently loading image file.

loader : | A pixbuf loader.
Returns : | A GdkPixbufFormat or NULL. The return value is owned by GdkPixbuf and should not be freed.

Since 2.2

gdk_pixbuf_loader_write ()

gboolean            gdk_pixbuf_loader_write             (GdkPixbufLoader *loader,
                                                         const guchar *buf,
                                                         gsize count,
                                                         GError **error);

This will cause a pixbuf loader to parse the next count bytes of an image. It will return TRUE if the data was loaded successfully, and FALSE if an error occurred. In the latter case, the loader will be closed, and will not accept further writes. If FALSE is returned, error will be set to an error from the GDK_PIXBUF_ERROR or G_FILE_ERROR domains.

loader : | A pixbuf loader.
buf : | Pointer to image data.
count : | Length of the buf buffer in bytes.
error : | return location for errors
Returns : | TRUE if the write was successful, or FALSE if the loader cannot parse the buffer.

gdk_pixbuf_loader_set_size ()

void                gdk_pixbuf_loader_set_size          (GdkPixbufLoader *loader,
                                                         int width,
                                                         int height);

Causes the image to be scaled while it is loaded. The desired image size can be determined relative to the original size of the image by calling gdk_pixbuf_loader_set_size() from a signal handler for the ::size_prepared signal.

Attempts to set the desired image size are ignored after the emission of the ::size_prepared signal.

loader : | A pixbuf loader.
width : | The desired width of the image being loaded.
height : | The desired height of the image being loaded.

Since 2.2

gdk_pixbuf_loader_get_pixbuf ()

GdkPixbuf*          gdk_pixbuf_loader_get_pixbuf        (GdkPixbufLoader *loader);

Queries the GdkPixbuf that a pixbuf loader is currently creating. In general it only makes sense to call this function after the "area_prepared" signal has been emitted by the loader; this means that enough data has been read to know the size of the image that will be allocated. If the loader has not received enough data via gdk_pixbuf_loader_write(), then this function returns NULL. The returned pixbuf will be the same in all future calls to the loader, so simply calling g_object_ref() should be sufficient to continue using it. Additionally, if the loader is an animation, it will return the "static image" of the animation (see gdk_pixbuf_animation_get_static_image()).

loader : | A pixbuf loader.
Returns : | The GdkPixbuf that the loader is creating, or NULL if not enough data has been read to determine how to create the image buffer.

gdk_pixbuf_loader_get_animation ()

GdkPixbufAnimation* gdk_pixbuf_loader_get_animation     (GdkPixbufLoader *loader);

Queries the GdkPixbufAnimation that a pixbuf loader is currently creating. In general it only makes sense to call this function after the "area_prepared" signal has been emitted by the loader. If the loader doesn't have enough bytes yet (hasn't emitted the "area_prepared" signal) this function will return NULL.

loader : | A pixbuf loader
Returns : | The GdkPixbufAnimation that the loader is loading, or NULL if not enough data has been read to determine the information.

gdk_pixbuf_loader_close ()

gboolean            gdk_pixbuf_loader_close             (GdkPixbufLoader *loader,
                                                         GError **error);

Informs a pixbuf loader that no further writes with gdk_pixbuf_loader_write() will occur, so that it can free its internal loading structures. Also, tries to parse any data that hasn't yet been parsed; if the remaining data is partial or corrupt, an error will be returned. If FALSE is returned, error will be set to an error from the GDK_PIXBUF_ERROR or G_FILE_ERROR domains. If you're just cancelling a load rather than expecting it to be finished, passing NULL for error to ignore it is reasonable.

loader : | A pixbuf loader.
error : | return location for a GError, or NULL to ignore errors
Returns : | TRUE if all image data written so far was successfully passed out via the update_area signal

Signal Details

The "area-prepared" signal

void                user_function                      (GdkPixbufLoader *loader,
                                                        gpointer         user_data)      : Run Last

This signal is emitted when the pixbuf loader has allocated the pixbuf in the desired size. After this signal is emitted, applications can call gdk_pixbuf_loader_get_pixbuf() to fetch the partially-loaded pixbuf.

loader : | the object which received the signal.
user_data : | user data set when the signal handler was connected.

The "area-updated" signal

void                user_function                      (GdkPixbufLoader *loader,
                                                        gint             x,
                                                        gint             y,
                                                        gint             width,
                                                        gint             height,
                                                        gpointer         user_data)      : Run Last

This signal is emitted when a significant area of the image being loaded has been updated. Normally it means that a complete scanline has been read in, but it could be a different area as well. Applications can use this signal to know when to repaint areas of an image that is being loaded.

loader : | the object which received the signal.
x : | X offset of upper-left corner of the updated area.
y : | Y offset of upper-left corner of the updated area.
width : | Width of updated area.
height : | Height of updated area.
user_data : | user data set when the signal handler was connected.

The "closed" signal

void                user_function                      (GdkPixbufLoader *loader,
                                                        gpointer         user_data)      : Run Last

This signal is emitted when gdk_pixbuf_loader_close() is called. It can be used by different parts of an application to receive notification when an image loader is closed by the code that drives it.

loader : | the object which received the signal.
user_data : | user data set when the signal handler was connected.

The "size-prepared" signal

void                user_function                      (GdkPixbufLoader *loader,
                                                        gint             width,
                                                        gint             height,
                                                        gpointer         user_data)      : Run Last

This signal is emitted when the pixbuf loader has been fed the initial amount of data that is required to figure out the size of the image that it will create. Applications can call gdk_pixbuf_loader_set_size() in response to this signal to set the desired size to which the image should be scaled.

loader : | the object which received the signal.
width : | the original width of the image
height : | the original height of the image
user_data : | user data set when the signal handler was connected.

See Also

gdk_pixbuf_new_from_file(), gdk_pixbuf_animation_new_from_file()


Index

G

GdkColorspace, enum GdkColorspace
GdkInterpType, enum GdkInterpType
GdkPixbuf, GdkPixbuf
GdkPixbuf:bits-per-sample, The "bits-per-sample" property
GdkPixbuf:colorspace, The "colorspace" property
GdkPixbuf:has-alpha, The "has-alpha" property
GdkPixbuf:height, The "height" property
GdkPixbuf:n-channels, The "n-channels" property
GdkPixbuf:pixels, The "pixels" property
GdkPixbuf:rowstride, The "rowstride" property
GdkPixbuf:width, The "width" property
GdkPixbufAlphaMode, enum GdkPixbufAlphaMode
GdkPixbufAnimation, GdkPixbufAnimation
GdkPixbufAnimationClass, GdkPixbufAnimationClass
GdkPixbufAnimationIter, GdkPixbufAnimationIter
GdkPixbufAnimationIterClass, GdkPixbufAnimationIterClass
GdkPixbufDestroyNotify, GdkPixbufDestroyNotify ()
GdkPixbufError, enum GdkPixbufError
GdkPixbufFormat, GdkPixbufFormat
GdkPixbufFormatFlags, enum GdkPixbufFormatFlags
GdkPixbufLoader, GdkPixbufLoader
GdkPixbufLoader::area-prepared, The "area-prepared" signal
GdkPixbufLoader::area-updated, The "area-updated" signal
GdkPixbufLoader::closed, The "closed" signal
GdkPixbufLoader::size-prepared, The "size-prepared" signal
GdkPixbufModule, GdkPixbufModule
GdkPixbufModuleFillInfoFunc, GdkPixbufModuleFillInfoFunc ()
GdkPixbufModuleFillVtableFunc, GdkPixbufModuleFillVtableFunc ()
GdkPixbufModulePattern, GdkPixbufModulePattern
GdkPixbufModulePreparedFunc, GdkPixbufModulePreparedFunc ()
GdkPixbufModuleSizeFunc, GdkPixbufModuleSizeFunc ()
GdkPixbufModuleUpdatedFunc, GdkPixbufModuleUpdatedFunc ()
GdkPixbufRotation, enum GdkPixbufRotation
GdkPixbufSaveFunc, GdkPixbufSaveFunc ()
GdkPixbufSimpleAnim, GdkPixbufSimpleAnim
GdkPixdata, GdkPixdata
GdkPixdataDumpType, enum GdkPixdataDumpType
GdkPixdataType, enum GdkPixdataType
gdk_pixbuf_add_alpha, gdk_pixbuf_add_alpha ()
gdk_pixbuf_animation_get_height, gdk_pixbuf_animation_get_height ()
gdk_pixbuf_animation_get_iter, gdk_pixbuf_animation_get_iter ()
gdk_pixbuf_animation_get_static_image, gdk_pixbuf_animation_get_static_image ()
gdk_pixbuf_animation_get_width, gdk_pixbuf_animation_get_width ()
gdk_pixbuf_animation_is_static_image, gdk_pixbuf_animation_is_static_image ()
gdk_pixbuf_animation_iter_advance, gdk_pixbuf_animation_iter_advance ()
gdk_pixbuf_animation_iter_get_delay_time, gdk_pixbuf_animation_iter_get_delay_time ()
gdk_pixbuf_animation_iter_get_pixbuf, gdk_pixbuf_animation_iter_get_pixbuf ()
gdk_pixbuf_animation_iter_on_currently_loading_frame, gdk_pixbuf_animation_iter_on_currently_loading_frame ()
gdk_pixbuf_animation_new_from_file, gdk_pixbuf_animation_new_from_file ()
gdk_pixbuf_animation_ref, gdk_pixbuf_animation_ref ()
gdk_pixbuf_animation_unref, gdk_pixbuf_animation_unref ()
gdk_pixbuf_composite, gdk_pixbuf_composite ()
gdk_pixbuf_composite_color, gdk_pixbuf_composite_color ()
gdk_pixbuf_composite_color_simple, gdk_pixbuf_composite_color_simple ()
gdk_pixbuf_copy, gdk_pixbuf_copy ()
gdk_pixbuf_copy_area, gdk_pixbuf_copy_area ()
GDK_PIXBUF_ERROR, GDK_PIXBUF_ERROR
gdk_pixbuf_fill, gdk_pixbuf_fill ()
gdk_pixbuf_flip, gdk_pixbuf_flip ()
gdk_pixbuf_format_get_description, gdk_pixbuf_format_get_description ()
gdk_pixbuf_format_get_extensions, gdk_pixbuf_format_get_extensions ()
gdk_pixbuf_format_get_license, gdk_pixbuf_format_get_license ()
gdk_pixbuf_format_get_mime_types, gdk_pixbuf_format_get_mime_types ()
gdk_pixbuf_format_get_name, gdk_pixbuf_format_get_name ()
gdk_pixbuf_format_is_disabled, gdk_pixbuf_format_is_disabled ()
gdk_pixbuf_format_is_scalable, gdk_pixbuf_format_is_scalable ()
gdk_pixbuf_format_is_writable, gdk_pixbuf_format_is_writable ()
gdk_pixbuf_format_set_disabled, gdk_pixbuf_format_set_disabled ()
gdk_pixbuf_from_pixdata, gdk_pixbuf_from_pixdata ()
gdk_pixbuf_get_bits_per_sample, gdk_pixbuf_get_bits_per_sample ()
gdk_pixbuf_get_colorspace, gdk_pixbuf_get_colorspace ()
gdk_pixbuf_get_file_info, gdk_pixbuf_get_file_info ()
gdk_pixbuf_get_formats, gdk_pixbuf_get_formats ()
gdk_pixbuf_get_has_alpha, gdk_pixbuf_get_has_alpha ()
gdk_pixbuf_get_height, gdk_pixbuf_get_height ()
gdk_pixbuf_get_n_channels, gdk_pixbuf_get_n_channels ()
gdk_pixbuf_get_option, gdk_pixbuf_get_option ()
gdk_pixbuf_get_pixels, gdk_pixbuf_get_pixels ()
gdk_pixbuf_get_rowstride, gdk_pixbuf_get_rowstride ()
gdk_pixbuf_get_width, gdk_pixbuf_get_width ()
gdk_pixbuf_loader_close, gdk_pixbuf_loader_close ()
gdk_pixbuf_loader_get_animation, gdk_pixbuf_loader_get_animation ()
gdk_pixbuf_loader_get_format, gdk_pixbuf_loader_get_format ()
gdk_pixbuf_loader_get_pixbuf, gdk_pixbuf_loader_get_pixbuf ()
gdk_pixbuf_loader_new, gdk_pixbuf_loader_new ()
gdk_pixbuf_loader_new_with_mime_type, gdk_pixbuf_loader_new_with_mime_type ()
gdk_pixbuf_loader_new_with_type, gdk_pixbuf_loader_new_with_type ()
gdk_pixbuf_loader_set_size, gdk_pixbuf_loader_set_size ()
gdk_pixbuf_loader_write, gdk_pixbuf_loader_write ()
GDK_PIXBUF_MAGIC_NUMBER, GDK_PIXBUF_MAGIC_NUMBER
GDK_PIXBUF_MAJOR, GDK_PIXBUF_MAJOR
gdk_pixbuf_major_version, gdk_pixbuf_major_version
GDK_PIXBUF_MICRO, GDK_PIXBUF_MICRO
gdk_pixbuf_micro_version, gdk_pixbuf_micro_version
GDK_PIXBUF_MINOR, GDK_PIXBUF_MINOR
gdk_pixbuf_minor_version, gdk_pixbuf_minor_version
gdk_pixbuf_new, gdk_pixbuf_new ()
gdk_pixbuf_new_from_data, gdk_pixbuf_new_from_data ()
gdk_pixbuf_new_from_file, gdk_pixbuf_new_from_file ()
gdk_pixbuf_new_from_file_at_scale, gdk_pixbuf_new_from_file_at_scale ()
gdk_pixbuf_new_from_file_at_size, gdk_pixbuf_new_from_file_at_size ()
gdk_pixbuf_new_from_inline, gdk_pixbuf_new_from_inline ()
gdk_pixbuf_new_from_xpm_data, gdk_pixbuf_new_from_xpm_data ()
gdk_pixbuf_new_subpixbuf, gdk_pixbuf_new_subpixbuf ()
gdk_pixbuf_ref, gdk_pixbuf_ref ()
gdk_pixbuf_rotate_simple, gdk_pixbuf_rotate_simple ()
gdk_pixbuf_saturate_and_pixelate, gdk_pixbuf_saturate_and_pixelate ()
gdk_pixbuf_save, gdk_pixbuf_save ()
gdk_pixbuf_savev, gdk_pixbuf_savev ()
gdk_pixbuf_save_to_buffer, gdk_pixbuf_save_to_buffer ()
gdk_pixbuf_save_to_bufferv, gdk_pixbuf_save_to_bufferv ()
gdk_pixbuf_save_to_callback, gdk_pixbuf_save_to_callback ()
gdk_pixbuf_save_to_callbackv, gdk_pixbuf_save_to_callbackv ()
gdk_pixbuf_scale, gdk_pixbuf_scale ()
gdk_pixbuf_scale_simple, gdk_pixbuf_scale_simple ()
gdk_pixbuf_set_option, gdk_pixbuf_set_option ()
gdk_pixbuf_simple_anim_add_frame, gdk_pixbuf_simple_anim_add_frame ()
gdk_pixbuf_simple_anim_new, gdk_pixbuf_simple_anim_new ()
gdk_pixbuf_unref, gdk_pixbuf_unref ()
gdk_pixbuf_version, gdk_pixbuf_version
GDK_PIXBUF_VERSION, GDK_PIXBUF_VERSION
gdk_pixbuf_xlib_get_from_drawable, gdk_pixbuf_xlib_get_from_drawable ()
gdk_pixbuf_xlib_init, gdk_pixbuf_xlib_init ()
gdk_pixbuf_xlib_init_with_depth, gdk_pixbuf_xlib_init_with_depth ()
gdk_pixbuf_xlib_render_pixmap_and_mask, gdk_pixbuf_xlib_render_pixmap_and_mask ()
gdk_pixbuf_xlib_render_threshold_alpha, gdk_pixbuf_xlib_render_threshold_alpha ()
gdk_pixbuf_xlib_render_to_drawable, gdk_pixbuf_xlib_render_to_drawable ()
gdk_pixbuf_xlib_render_to_drawable_alpha, gdk_pixbuf_xlib_render_to_drawable_alpha ()
gdk_pixdata_deserialize, gdk_pixdata_deserialize ()
gdk_pixdata_from_pixbuf, gdk_pixdata_from_pixbuf ()
GDK_PIXDATA_HEADER_LENGTH, GDK_PIXDATA_HEADER_LENGTH
gdk_pixdata_serialize, gdk_pixdata_serialize ()
gdk_pixdata_to_csource, gdk_pixdata_to_csource ()

X

XlibRgbCmap, XlibRgbCmap
XlibRgbDither, enum XlibRgbDither
xlib_draw_gray_image, xlib_draw_gray_image ()
xlib_draw_indexed_image, xlib_draw_indexed_image ()
xlib_draw_rgb_32_image, xlib_draw_rgb_32_image ()
xlib_draw_rgb_image, xlib_draw_rgb_image ()
xlib_draw_rgb_image_dithalign, xlib_draw_rgb_image_dithalign ()
xlib_rgb_cmap_free, xlib_rgb_cmap_free ()
xlib_rgb_cmap_new, xlib_rgb_cmap_new ()
xlib_rgb_ditherable, xlib_rgb_ditherable ()
xlib_rgb_gc_set_background, xlib_rgb_gc_set_background ()
xlib_rgb_gc_set_foreground, xlib_rgb_gc_set_foreground ()
xlib_rgb_get_cmap, xlib_rgb_get_cmap ()
xlib_rgb_get_depth, xlib_rgb_get_depth ()
xlib_rgb_get_display, xlib_rgb_get_display ()
xlib_rgb_get_screen, xlib_rgb_get_screen ()
xlib_rgb_get_visual, xlib_rgb_get_visual ()
xlib_rgb_get_visual_info, xlib_rgb_get_visual_info ()
xlib_rgb_init, xlib_rgb_init ()
xlib_rgb_init_with_depth, xlib_rgb_init_with_depth ()
xlib_rgb_set_install, xlib_rgb_set_install ()
xlib_rgb_set_min_colors, xlib_rgb_set_min_colors ()
xlib_rgb_set_verbose, xlib_rgb_set_verbose ()
xlib_rgb_xpixel_from_rgb, xlib_rgb_xpixel_from_rgb ()


Index of deprecated symbols

G

gdk_pixbuf_animation_ref, gdk_pixbuf_animation_ref ()
gdk_pixbuf_animation_unref, gdk_pixbuf_animation_unref ()
gdk_pixbuf_ref, gdk_pixbuf_ref ()
gdk_pixbuf_unref, gdk_pixbuf_unref ()


Index of new symbols in 2.2

G

GdkPixbufFormat, GdkPixbufFormat
GdkPixbufFormatFlags, enum GdkPixbufFormatFlags
GdkPixbufModuleFillInfoFunc, GdkPixbufModuleFillInfoFunc ()
GdkPixbufModuleFillVtableFunc, GdkPixbufModuleFillVtableFunc ()
GdkPixbufModulePattern, GdkPixbufModulePattern
GdkPixbufModulePreparedFunc, GdkPixbufModulePreparedFunc ()
GdkPixbufModuleSizeFunc, GdkPixbufModuleSizeFunc ()
GdkPixbufModuleUpdatedFunc, GdkPixbufModuleUpdatedFunc ()
gdk_pixbuf_format_get_description, gdk_pixbuf_format_get_description ()
gdk_pixbuf_format_get_extensions, gdk_pixbuf_format_get_extensions ()
gdk_pixbuf_format_get_mime_types, gdk_pixbuf_format_get_mime_types ()
gdk_pixbuf_format_get_name, gdk_pixbuf_format_get_name ()
gdk_pixbuf_format_is_writable, gdk_pixbuf_format_is_writable ()
gdk_pixbuf_get_formats, gdk_pixbuf_get_formats ()
gdk_pixbuf_loader_get_format, gdk_pixbuf_loader_get_format ()
gdk_pixbuf_loader_set_size, gdk_pixbuf_loader_set_size ()
gdk_pixbuf_set_option, gdk_pixbuf_set_option ()


Index of new symbols in 2.4

G

GdkPixbufSaveFunc, GdkPixbufSaveFunc ()
gdk_pixbuf_get_file_info, gdk_pixbuf_get_file_info ()
gdk_pixbuf_loader_new_with_mime_type, gdk_pixbuf_loader_new_with_mime_type ()
gdk_pixbuf_new_from_file_at_size, gdk_pixbuf_new_from_file_at_size ()
gdk_pixbuf_save_to_buffer, gdk_pixbuf_save_to_buffer ()
gdk_pixbuf_save_to_bufferv, gdk_pixbuf_save_to_bufferv ()
gdk_pixbuf_save_to_callback, gdk_pixbuf_save_to_callback ()
gdk_pixbuf_save_to_callbackv, gdk_pixbuf_save_to_callbackv ()


Index of new symbols in 2.6

G

gdk_pixbuf_flip, gdk_pixbuf_flip ()
gdk_pixbuf_format_get_license, gdk_pixbuf_format_get_license ()
gdk_pixbuf_format_is_disabled, gdk_pixbuf_format_is_disabled ()
gdk_pixbuf_format_is_scalable, gdk_pixbuf_format_is_scalable ()
gdk_pixbuf_format_set_disabled, gdk_pixbuf_format_set_disabled ()
gdk_pixbuf_new_from_file_at_scale, gdk_pixbuf_new_from_file_at_scale ()
gdk_pixbuf_rotate_simple, gdk_pixbuf_rotate_simple ()


Index of new symbols in 2.8

G

gdk_pixbuf_simple_anim_add_frame, gdk_pixbuf_simple_anim_add_frame ()
gdk_pixbuf_simple_anim_new, gdk_pixbuf_simple_anim_new ()


Appendix B. License

This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version.

This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public License for more details.

You may obtain a copy of the GNU Library General Public License from the Free Software Foundation by visiting their Web site or by writing to:

Free Software Foundation, Inc.
59 Temple Place - Suite 330
Boston, MA 02111-1307
USA


API Reference

This part presents the class and function reference for the gdk-pixbuf library. Classes are described together with their methods; individual functions are grouped by functional group.


Tools Reference

This part presents the tools which are shipped with the gdk-pixbuf library.


GLib Overview

Compiling the GLib package — How to compile GLib itself
Cross-compiling the GLib package — How to cross-compile GLib
Compiling GLib Applications — How to compile your GLib application
Running GLib Applications — How to run and debug your GLib application
Changes to GLib — Incompatible changes made between successing versions of GLib
Mailing lists and bug reports — Getting help with GLib

GLib is a general-purpose utility library, which provides many useful data types, macros, type conversions, string utilities, file utilities, a main loop abstraction, and so on. It works on many UNIX-like platforms, Windows, OS/2 and BeOS. GLib is released under the GNU Library General Public License (GNU LGPL).

The general policy of GLib is that all functions are invisibly threadsafe with the exception of data structure manipulation functions, where, if you have two threads manipulating the same data structure, they must use a lock to synchronize their operation.


Arrays

Arrays — arrays of arbitrary elements which grow automatically as elements are added.

Synopsis

#include <glib.h>

                    GArray;
GArray*             g_array_new                         (gboolean zero_terminated,
                                                         gboolean clear_,
                                                         guint element_size);
GArray*             g_array_sized_new                   (gboolean zero_terminated,
                                                         gboolean clear_,
                                                         guint element_size,
                                                         guint reserved_size);
#define             g_array_append_val                  (a,v)
GArray*             g_array_append_vals                 (GArray *array,
                                                         gconstpointer data,
                                                         guint len);
#define             g_array_prepend_val                 (a,v)
GArray*             g_array_prepend_vals                (GArray *array,
                                                         gconstpointer data,
                                                         guint len);
#define             g_array_insert_val                  (a,i,v)
GArray*             g_array_insert_vals                 (GArray *array,
                                                         guint index_,
                                                         gconstpointer data,
                                                         guint len);
GArray*             g_array_remove_index                (GArray *array,
                                                         guint index_);
GArray*             g_array_remove_index_fast           (GArray *array,
                                                         guint index_);
GArray*             g_array_remove_range                (GArray *array,
                                                         guint index_,
                                                         guint length);
void                g_array_sort                        (GArray *array,
                                                         GCompareFunc compare_func);
void                g_array_sort_with_data              (GArray *array,
                                                         GCompareDataFunc compare_func,
                                                         gpointer user_data);
#define             g_array_index                       (a,t,i)
GArray*             g_array_set_size                    (GArray *array,
                                                         guint length);
gchar*              g_array_free                        (GArray *array,
                                                         gboolean free_segment);

Description

Arrays are similar to standard C arrays, except that they grow automatically as elements are added.

Array elements can be of any size (though all elements of one array are the same size), and the array can be automatically cleared to '0's and zero-terminated.

To create a new array use g_array_new().

To add elements to an array, use g_array_append_val(), g_array_append_vals(), g_array_prepend_val(), and g_array_prepend_vals().

To access an element of an array, use g_array_index().

To set the size of an array, use g_array_set_size().

To free an array, use g_array_free().

Example 21. Using a GArray to store gint values

  GArray *garray;
  gint i;

  /* We create a new array to store gint values.
     We don't want it zero-terminated or cleared to 0's. */
  garray = g_array_new (FALSE, FALSE, sizeof (gint));
  for (i = 0; i < 10000; i++)
    g_array_append_val (garray, i);

  for (i = 0; i < 10000; i++)
    if (g_array_index (garray, gint, i) != i)
      g_print ("ERROR: got %d instead of %d\n",
               g_array_index (garray, gint, i), i);

  g_array_free (garray, TRUE);

Details

GArray

typedef struct {
  gchar *data;
  guint len;
} GArray;

Contains the public fields of an Array.

gchar *data; | a pointer to the element data. The data may be moved as elements are added to the GArray.
guint len; | the number of elements in the GArray.

g_array_new ()

GArray*             g_array_new                         (gboolean zero_terminated,
                                                         gboolean clear_,
                                                         guint element_size);

Creates a new GArray.

zero_terminated : | TRUE if the array should have an extra element at the end which is set to 0.
clear_ : | TRUE if GArray elements should be automatically cleared to 0 when they are allocated.
element_size : | the size of each element in bytes.
Returns : | the new GArray.

g_array_sized_new ()

GArray*             g_array_sized_new                   (gboolean zero_terminated,
                                                         gboolean clear_,
                                                         guint element_size,
                                                         guint reserved_size);

Creates a new GArray with reserved_size elements preallocated. This avoids frequent reallocation, if you are going to add many elements to the array. Note however that the size of the array is still 0.

zero_terminated : | TRUE if the array should have an extra element at the end with all bits cleared.
clear_ : | TRUE if all bits in the array should be cleared to 0 on allocation.
element_size : | size of each element in the array.
reserved_size : | number of elements preallocated.
Returns : | the new GArray.

g_array_append_val()

#define             g_array_append_val(a,v)

Adds the value on to the end of the array. The array will grow in size automatically if necessary.

Note

g_array_append_val() is a macro which uses a reference to the value parameter v. This means that you cannot use it with literal values such as "27". You must use variables.

a : | a GArray.
v : | the value to append to the GArray.
Returns : | the GArray.

g_array_append_vals ()

GArray*             g_array_append_vals                 (GArray *array,
                                                         gconstpointer data,
                                                         guint len);

Adds len elements onto the end of the array.

array : | a GArray.
data : | a pointer to the elements to append to the end of the array.
len : | the number of elements to append.
Returns : | the GArray.

g_array_prepend_val()

#define             g_array_prepend_val(a,v)

Adds the value on to the start of the array. The array will grow in size automatically if necessary.

This operation is slower than g_array_append_val() since the existing elements in the array have to be moved to make space for the new element.

Note

g_array_prepend_val() is a macro which uses a reference to the value parameter v. This means that you cannot use it with literal values such as "27". You must use variables.

a : | a GArray.
v : | the value to prepend to the GArray.
Returns : | the GArray.

g_array_prepend_vals ()

GArray*             g_array_prepend_vals                (GArray *array,
                                                         gconstpointer data,
                                                         guint len);

Adds len elements onto the start of the array.

This operation is slower than g_array_append_vals() since the existing elements in the array have to be moved to make space for the new elements.

array : | a GArray.
data : | a pointer to the elements to prepend to the start of the array.
len : | the number of elements to prepend.
Returns : | the GArray.

g_array_insert_val()

#define             g_array_insert_val(a,i,v)

Inserts an element into an array at the given index.

Note

g_array_insert_val() is a macro which uses a reference to the value parameter v. This means that you cannot use it with literal values such as "27". You must use variables.

a : | a GArray.
i : | the index to place the element at.
v : | the value to insert into the array.
Returns : | the GArray.

g_array_insert_vals ()

GArray*             g_array_insert_vals                 (GArray *array,
                                                         guint index_,
                                                         gconstpointer data,
                                                         guint len);

Inserts len elements into a GArray at the given index.

array : | a GArray.
index_ : | the index to place the elements at.
data : | a pointer to the elements to insert.
len : | the number of elements to insert.
Returns : | the GArray.

g_array_remove_index ()

GArray*             g_array_remove_index                (GArray *array,
                                                         guint index_);

Removes the element at the given index from a GArray. The following elements are moved down one place.

array : | a GArray.
index_ : | the index of the element to remove.
Returns : | the GArray.

g_array_remove_index_fast ()

GArray*             g_array_remove_index_fast           (GArray *array,
                                                         guint index_);

Removes the element at the given index from a GArray. The last element in the array is used to fill in the space, so this function does not preserve the order of the GArray. But it is faster than g_array_remove_index().

array : | a GArray.
index_ : | the index of the element to remove.
Returns : | the GArray.

g_array_remove_range ()

GArray*             g_array_remove_range                (GArray *array,
                                                         guint index_,
                                                         guint length);

Removes the given number of elements starting at the given index from a GArray. The following elements are moved to close the gap.

array : | a GArray.
index_ : | the index of the first element to remove.
length : | the number of elements to remove.
Returns : | the GArray.

Since 2.4

g_array_sort ()

void                g_array_sort                        (GArray *array,
                                                         GCompareFunc compare_func);

Sorts a GArray using compare_func which should be a qsort()-style comparison function (returns less than zero for first arg is less than second arg, zero for equal, greater zero if first arg is greater than second arg).

If two array elements compare equal, their order in the sorted array is undefined.

array : | a GArray.
compare_func : | comparison function.

g_array_sort_with_data ()

void                g_array_sort_with_data              (GArray *array,
                                                         GCompareDataFunc compare_func,
                                                         gpointer user_data);

Like g_array_sort(), but the comparison function receives an extra user data argument.

array : | a GArray.
compare_func : | comparison function.
user_data : | data to pass to compare_func.

g_array_index()

#define             g_array_index(a,t,i)

Returns the element of a GArray at the given index. The return value is cast to the given type.

Example 22. Getting a pointer to an element in a GArray

  EDayViewEvent *event;

  /* This gets a pointer to the 3rd element in the array of EDayViewEvent
     structs. */
  event = &g_array_index (events, EDayViewEvent, 3);

a : | a GArray.
t : | the type of the elements.
i : | the index of the element to return.
Returns : | the element of the GArray at the index given by i.

g_array_set_size ()

GArray*             g_array_set_size                    (GArray *array,
                                                         guint length);

Sets the size of the array, expanding it if necessary. If the array was created with clear_ set to TRUE, the new elements are set to 0.

array : | a GArray.
length : | the new size of the GArray.
Returns : | the GArray.

g_array_free ()

gchar*              g_array_free                        (GArray *array,
                                                         gboolean free_segment);

Frees the memory allocated for the GArray. If free_segment is TRUE it frees the memory block holding the elements as well. Pass FALSE if you want to free the GArray wrapper but preserve the underlying array for use elsewhere.

Note

If array elements contain dynamically-allocated memory, they should be freed first.

array : | a GArray.
free_segment : | if TRUE the actual element data is freed as well.
Returns : | the element data if free_segment is FALSE, otherwise NULL


Asynchronous Queues

Asynchronous Queues — asynchronous communication between threads.

Synopsis

#include <glib.h>

                    GAsyncQueue;
GAsyncQueue*        g_async_queue_new                   (void);
GAsyncQueue*        g_async_queue_ref                   (GAsyncQueue *queue);
void                g_async_queue_unref                 (GAsyncQueue *queue);
void                g_async_queue_push                  (GAsyncQueue *queue,
                                                         gpointer data);
void                g_async_queue_push_sorted           (GAsyncQueue *queue,
                                                         gpointer data,
                                                         GCompareDataFunc func,
                                                         gpointer user_data);
gpointer            g_async_queue_pop                   (GAsyncQueue *queue);
gpointer            g_async_queue_try_pop               (GAsyncQueue *queue);
gpointer            g_async_queue_timed_pop             (GAsyncQueue *queue,
                                                         GTimeVal *end_time);
gint                g_async_queue_length                (GAsyncQueue *queue);
void                g_async_queue_sort                  (GAsyncQueue *queue,
                                                         GCompareDataFunc func,
                                                         gpointer user_data);

void                g_async_queue_lock                  (GAsyncQueue *queue);
void                g_async_queue_unlock                (GAsyncQueue *queue);
void                g_async_queue_ref_unlocked          (GAsyncQueue *queue);
void                g_async_queue_unref_and_unlock      (GAsyncQueue *queue);
void                g_async_queue_push_unlocked         (GAsyncQueue *queue,
                                                         gpointer data);
void                g_async_queue_push_sorted_unlocked  (GAsyncQueue *queue,
                                                         gpointer data,
                                                         GCompareDataFunc func,
                                                         gpointer user_data);
gpointer            g_async_queue_pop_unlocked          (GAsyncQueue *queue);
gpointer            g_async_queue_try_pop_unlocked      (GAsyncQueue *queue);
gpointer            g_async_queue_timed_pop_unlocked    (GAsyncQueue *queue,
                                                         GTimeVal *end_time);
gint                g_async_queue_length_unlocked       (GAsyncQueue *queue);
void                g_async_queue_sort_unlocked         (GAsyncQueue *queue,
                                                         GCompareDataFunc func,
                                                         gpointer user_data);

Description

Often you need to communicate between different threads. In general it's safer not to do this by shared memory, but by explicit message passing. These messages only make sense asynchronously for multi-threaded applications though, as a synchronous operation could as well be done in the same thread.

Asynchronous queues are an exception from most other GLib data structures, as they can be used simultaneously from multiple threads without explicit locking and they bring their own builtin reference counting. This is because the nature of an asynchronous queue is that it will always be used by at least 2 concurrent threads.

For using an asynchronous queue you first have to create one with g_async_queue_new(). A newly-created queue will get the reference count 1. Whenever another thread is creating a new reference of (that is, pointer to) the queue, it has to increase the reference count (using g_async_queue_ref()). Also, before removing this reference, the reference count has to be decreased (using g_async_queue_unref()). After that the queue might no longer exist so you must not access it after that point.

A thread, which wants to send a message to that queue simply calls g_async_queue_push() to push the message to the queue.

A thread, which is expecting messages from an asynchronous queue simply calls g_async_queue_pop() for that queue. If no message is available in the queue at that point, the thread is now put to sleep until a message arrives. The message will be removed from the queue and returned. The functions g_async_queue_try_pop() and g_async_queue_timed_pop() can be used to only check for the presence of messages or to only wait a certain time for messages respectively.

For almost every function there exist two variants, one that locks the queue and one that doesn't. That way you can hold the queue lock (acquire it with g_async_queue_lock() and release it with g_async_queue_unlock()) over multiple queue accessing instructions. This can be necessary to ensure the integrity of the queue, but should only be used when really necessary, as it can make your life harder if used unwisely. Normally you should only use the locking function variants (those without the suffix _unlocked)

Details

GAsyncQueue

typedef struct _GAsyncQueue GAsyncQueue;

The GAsyncQueue struct is an opaque data structure, which represents an asynchronous queue. It should only be accessed through the g_async_queue_* functions.

g_async_queue_new ()

GAsyncQueue*        g_async_queue_new                   (void);

Creates a new asynchronous queue with the initial reference count of 1.

Returns : the new GAsyncQueue.

g_async_queue_ref ()

GAsyncQueue*        g_async_queue_ref                   (GAsyncQueue *queue);

Increases the reference count of the asynchronous queue by 1. You do not need to hold the lock to call this function.

queue : | a GAsyncQueue.
Returns : | the queue that was passed in (since 2.6)

g_async_queue_unref ()

void                g_async_queue_unref                 (GAsyncQueue *queue);

Decreases the reference count of the asynchronous queue by 1. If the reference count went to 0, the queue will be destroyed and the memory allocated will be freed. So you are not allowed to use the queue afterwards, as it might have disappeared. You do not need to hold the lock to call this function.

queue : a GAsyncQueue.

g_async_queue_push ()

void                g_async_queue_push                  (GAsyncQueue *queue,
                                                         gpointer data);

Pushes the data into the queue. data must not be NULL.

queue : | a GAsyncQueue.
data : | data to push into the queue.

g_async_queue_push_sorted ()

void                g_async_queue_push_sorted           (GAsyncQueue *queue,
                                                         gpointer data,
                                                         GCompareDataFunc func,
                                                         gpointer user_data);

Inserts data into queue using func to determine the new position.

This function requires that the queue is sorted before pushing on new elements.

This function will lock queue before it sorts the queue and unlock it when it is finished.

For an example of func see g_async_queue_sort().

queue : | a GAsyncQueue
data : | the data to push into the queue
func : | the GCompareDataFunc is used to sort queue. This function is passed two elements of the queue. The function should return 0 if they are equal, a negative value if the first element should be higher in the queue or a positive value if the first element should be lower in the queue than the second element.
user_data : | user data passed to func.

Since 2.10

g_async_queue_pop ()

gpointer            g_async_queue_pop                   (GAsyncQueue *queue);

Pops data from the queue. This function blocks until data become available.

queue : | a GAsyncQueue.
Returns : | data from the queue.

g_async_queue_try_pop ()

gpointer            g_async_queue_try_pop               (GAsyncQueue *queue);

Tries to pop data from the queue. If no data is available, NULL is returned.

queue : | a GAsyncQueue.
Returns : | data from the queue or NULL, when no data is available immediately.

g_async_queue_timed_pop ()

gpointer            g_async_queue_timed_pop             (GAsyncQueue *queue,
                                                         GTimeVal *end_time);

Pops data from the queue. If no data is received before end_time, NULL is returned.

To easily calculate end_time a combination of g_get_current_time() and g_time_val_add() can be used.

queue : | a GAsyncQueue.
end_time : | a GTimeVal, determining the final time.
Returns : | data from the queue or NULL, when no data is received before end_time.

g_async_queue_length ()

gint                g_async_queue_length                (GAsyncQueue *queue);

Returns the length of the queue, negative values mean waiting threads, positive values mean available entries in the queue. Actually this function returns the number of data items in the queue minus the number of waiting threads. Thus a return value of 0 could mean 'n' entries in the queue and 'n' thread waiting. That can happen due to locking of the queue or due to scheduling.

queue : | a GAsyncQueue.
Returns : | the length of the queue.

g_async_queue_sort ()

void                g_async_queue_sort                  (GAsyncQueue *queue,
                                                         GCompareDataFunc func,
                                                         gpointer user_data);

Sorts queue using func.

This function will lock queue before it sorts the queue and unlock it when it is finished.

If you were sorting a list of priority numbers to make sure the lowest priority would be at the top of the queue, you could use:

 gint32 id1;
 gint32 id2;

 id1 = GPOINTER_TO_INT (element1);
 id2 = GPOINTER_TO_INT (element2);

 return (id1 > id2 ? +1 : id1 == id2 ? 0 : -1);

queue : | a GAsyncQueue
func : | the GCompareDataFunc is used to sort queue. This function is passed two elements of the queue. The function should return 0 if they are equal, a negative value if the first element should be higher in the queue or a positive value if the first element should be lower in the queue than the second element.
user_data : | user data passed to func

Since 2.10

g_async_queue_lock ()

void                g_async_queue_lock                  (GAsyncQueue *queue);

Acquires the queue's lock. After that you can only call the g_async_queue_*_unlocked() function variants on that queue. Otherwise it will deadlock.

queue : a GAsyncQueue.

g_async_queue_unlock ()

void                g_async_queue_unlock                (GAsyncQueue *queue);

Releases the queue's lock.

queue : a GAsyncQueue.

g_async_queue_ref_unlocked ()

void                g_async_queue_ref_unlocked          (GAsyncQueue *queue);

Warning

g_async_queue_ref_unlocked is deprecated and should not be used in newly-written code.

Increases the reference count of the asynchronous queue by 1.

Deprecated: Since 2.8, reference counting is done atomically so g_async_queue_ref() can be used regardless of the queue's lock.

queue : a GAsyncQueue.

g_async_queue_unref_and_unlock ()

void                g_async_queue_unref_and_unlock      (GAsyncQueue *queue);

Warning

g_async_queue_unref_and_unlock is deprecated and should not be used in newly-written code.

Decreases the reference count of the asynchronous queue by 1 and releases the lock. This function must be called while holding the queue's lock. If the reference count went to 0, the queue will be destroyed and the memory allocated will be freed.

Deprecated: Since 2.8, reference counting is done atomically so g_async_queue_unref() can be used regardless of the queue's lock.

queue : a GAsyncQueue.

g_async_queue_push_unlocked ()

void                g_async_queue_push_unlocked         (GAsyncQueue *queue,
                                                         gpointer data);

Pushes the data into the queue. data must not be NULL. This function must be called while holding the queue's lock.

queue : | a GAsyncQueue.
data : | data to push into the queue.

g_async_queue_push_sorted_unlocked ()

void                g_async_queue_push_sorted_unlocked  (GAsyncQueue *queue,
                                                         gpointer data,
                                                         GCompareDataFunc func,
                                                         gpointer user_data);

Inserts data into queue using func to determine the new position.

This function requires that the queue is sorted before pushing on new elements.

This function is called while holding the queue's lock.

For an example of func see g_async_queue_sort().

queue : | a GAsyncQueue
data : | the data to push into the queue
func : | the GCompareDataFunc is used to sort queue. This function is passed two elements of the queue. The function should return 0 if they are equal, a negative value if the first element should be higher in the queue or a positive value if the first element should be lower in the queue than the second element.
user_data : | user data passed to func.

Since 2.10

g_async_queue_pop_unlocked ()

gpointer            g_async_queue_pop_unlocked          (GAsyncQueue *queue);

Pops data from the queue. This function blocks until data become available. This function must be called while holding the queue's lock.

queue : | a GAsyncQueue.
Returns : | data from the queue.

g_async_queue_try_pop_unlocked ()

gpointer            g_async_queue_try_pop_unlocked      (GAsyncQueue *queue);

Tries to pop data from the queue. If no data is available, NULL is returned. This function must be called while holding the queue's lock.

queue : | a GAsyncQueue.
Returns : | data from the queue or NULL, when no data is available immediately.

g_async_queue_timed_pop_unlocked ()

gpointer            g_async_queue_timed_pop_unlocked    (GAsyncQueue *queue,
                                                         GTimeVal *end_time);

Pops data from the queue. If no data is received before end_time, NULL is returned. This function must be called while holding the queue's lock.

To easily calculate end_time a combination of g_get_current_time() and g_time_val_add() can be used.

queue : | a GAsyncQueue.
end_time : | a GTimeVal, determining the final time.
Returns : | data from the queue or NULL, when no data is received before end_time.

g_async_queue_length_unlocked ()

gint                g_async_queue_length_unlocked       (GAsyncQueue *queue);

Returns the length of the queue, negative values mean waiting threads, positive values mean available entries in the queue. Actually this function returns the number of data items in the queue minus the number of waiting threads. Thus a return value of 0 could mean 'n' entries in the queue and 'n' thread waiting. That can happen due to locking of the queue or due to scheduling. This function must be called while holding the queue's lock.

queue : | a GAsyncQueue.
Returns : | the length of the queue.

g_async_queue_sort_unlocked ()

void                g_async_queue_sort_unlocked         (GAsyncQueue *queue,
                                                         GCompareDataFunc func,
                                                         gpointer user_data);

Sorts queue using func.

This function is called while holding the queue's lock.

queue : | a GAsyncQueue
func : | the GCompareDataFunc is used to sort queue. This function is passed two elements of the queue. The function should return 0 if they are equal, a negative value if the first element should be higher in the queue or a positive value if the first element should be lower in the queue than the second element.
user_data : | user data passed to func

Since 2.10


Atomic Operations

Atomic Operations — basic atomic integer and pointer operations

Synopsis

#include <glib.h>

gint                g_atomic_int_get                    (volatile gint *atomic);
void                g_atomic_int_set                    (volatile gint *atomic,
                                                         gint newval);
void                g_atomic_int_add                    (volatile gint *atomic,
                                                         gint val);
gint                g_atomic_int_exchange_and_add       (volatile gint *atomic,
                                                         gint val);
gboolean            g_atomic_int_compare_and_exchange   (volatile gint *atomic,
                                                         gint oldval,
                                                         gint newval);
gpointer            g_atomic_pointer_get                (volatile gpointer *atomic);
void                g_atomic_pointer_set                (volatile gpointer *atomic,
                                                         gpointer newval);
gboolean            g_atomic_pointer_compare_and_exchange
                                                        (volatile gpointer *atomic,
                                                         gpointer oldval,
                                                         gpointer newval);
void                g_atomic_int_inc                    (gint *atomic);
gboolean            g_atomic_int_dec_and_test           (gint *atomic);

Description

The following functions can be used to atomically access integers and pointers. They are implemented as inline assembler function on most platforms and use slower fall-backs otherwise. Using them can sometimes save you from using a performance-expensive GMutex to protect the integer or pointer.

The most important usage is reference counting. Using g_atomic_int_inc() and g_atomic_int_dec_and_test() makes reference counting a very fast operation.

Note

You must not directly read integers or pointers concurrently accessed by multiple threads, but use the atomic accessor functions instead. That is, always use g_atomic_int_get() and g_atomic_pointer_get() for read outs. They provide the neccessary synchonization mechanisms like memory barriers to access memory locations concurrently.

Note

If you are using those functions for anything apart from simple reference counting, you should really be aware of the implications of doing that. There are literally thousands of ways to shoot yourself in the foot. So if in doubt, use a GMutex. If you don't know, what memory barriers are, do not use anything but g_atomic_int_inc() and g_atomic_int_dec_and_test().

Note

It is not safe to set an integer or pointer just by assigning to it, when it is concurrently accessed by other threads with the following functions. Use g_atomic_int_compare_and_exchange() or g_atomic_pointer_compare_and_exchange() respectively.

Details

g_atomic_int_get ()

gint                g_atomic_int_get                    (volatile gint *atomic);

Reads the value of the integer pointed to by atomic. Also acts as a memory barrier.

atomic : | a pointer to an integer
Returns : | the value of *atomic

Since 2.4

g_atomic_int_set ()

void                g_atomic_int_set                    (volatile gint *atomic,
                                                         gint newval);

Sets the value of the integer pointed to by atomic. Also acts as a memory barrier.

atomic : | a pointer to an integer
newval : | the new value

Since 2.10

g_atomic_int_add ()

void                g_atomic_int_add                    (volatile gint *atomic,
                                                         gint val);

Atomically adds val to the integer pointed to by atomic. Also acts as a memory barrier.

atomic : | a pointer to an integer.
val : | the value to add to *atomic.

Since 2.4

g_atomic_int_exchange_and_add ()

gint                g_atomic_int_exchange_and_add       (volatile gint *atomic,
                                                         gint val);

Atomically adds val to the integer pointed to by atomic. It returns the value of *atomic just before the addition took place. Also acts as a memory barrier.

atomic : | a pointer to an integer.
val : | the value to add to *atomic.
Returns : | the value of *atomic before the addition.

Since 2.4

g_atomic_int_compare_and_exchange ()

gboolean            g_atomic_int_compare_and_exchange   (volatile gint *atomic,
                                                         gint oldval,
                                                         gint newval);

Compares oldval with the integer pointed to by atomic and if they are equal, atomically exchanges *atomic with newval. Also acts as a memory barrier.

atomic : | a pointer to an integer.
oldval : | the assumed old value of *atomic.
newval : | the new value of *atomic.
Returns : | TRUE, if *atomic was equal oldval. FALSE otherwise.

Since 2.4

g_atomic_pointer_get ()

gpointer            g_atomic_pointer_get                (volatile gpointer *atomic);

Reads the value of the pointer pointed to by atomic. Also acts as a memory barrier.

atomic : | a pointer to a gpointer.
Returns : | the value to add to *atomic.

Since 2.4

g_atomic_pointer_set ()

void                g_atomic_pointer_set                (volatile gpointer *atomic,
                                                         gpointer newval);

Sets the value of the pointer pointed to by atomic. Also acts as a memory barrier.

atomic : | a pointer to a gpointer
newval : | the new value

Since 2.10

g_atomic_pointer_compare_and_exchange ()

gboolean            g_atomic_pointer_compare_and_exchange
                                                        (volatile gpointer *atomic,
                                                         gpointer oldval,
                                                         gpointer newval);

Compares oldval with the pointer pointed to by atomic and if they are equal, atomically exchanges *atomic with newval. Also acts as a memory barrier.

atomic : | a pointer to a gpointer.
oldval : | the assumed old value of *atomic.
newval : | the new value of *atomic.
Returns : | TRUE, if *atomic was equal oldval. FALSE otherwise.

Since 2.4

g_atomic_int_inc ()

void                g_atomic_int_inc                    (gint *atomic);

Atomically increments the integer pointed to by atomic by 1.

atomic : a pointer to an integer.

Since 2.4

g_atomic_int_dec_and_test ()

gboolean            g_atomic_int_dec_and_test           (gint *atomic);

Atomically decrements the integer pointed to by atomic by 1.

atomic : | a pointer to an integer.
Returns : | TRUE, if the integer pointed to by atomic is 0 after decrementing it.

Since 2.4

See Also

GMutex

GLib mutual exclusions.


Automatic String Completion

Automatic String Completion — support for automatic completion using a group of target strings.

Synopsis

#include <glib.h>

                    GCompletion;
GCompletion*        g_completion_new                    (GCompletionFunc func);
gchar*              (*GCompletionFunc)                  (gpointer );
void                g_completion_add_items              (GCompletion *cmp,
                                                         GList *items);
void                g_completion_remove_items           (GCompletion *cmp,
                                                         GList *items);
void                g_completion_clear_items            (GCompletion *cmp);
GList*              g_completion_complete               (GCompletion *cmp,
                                                         const gchar *prefix,
                                                         gchar **new_prefix);
GList*              g_completion_complete_utf8          (GCompletion *cmp,
                                                         const gchar *prefix,
                                                         gchar **new_prefix);
void                g_completion_set_compare            (GCompletion *cmp,
                                                         GCompletionStrncmpFunc strncmp_func);
gint                (*GCompletionStrncmpFunc)           (const gchar *s1,
                                                         const gchar *s2,
                                                         gsize n);
void                g_completion_free                   (GCompletion *cmp);

Description

GCompletion provides support for automatic completion of a string using any group of target strings. It is typically used for file name completion as is common in many UNIX shells.

A GCompletion is created using g_completion_new(). Target items are added and removed with g_completion_add_items(), g_completion_remove_items() and g_completion_clear_items(). A completion attempt is requested with g_completion_complete() or g_completion_complete_utf8(). When no longer needed, the GCompletion is freed with g_completion_free().

Items in the completion can be simple strings (e.g. filenames), or pointers to arbitrary data structures. If data structures are used you must provide a GCompletionFunc in g_completion_new(), which retrieves the item's string from the data structure. You can change the way in which strings are compared by setting a different GCompletionStrncmpFunc in g_completion_set_compare().

Details

GCompletion

typedef struct {
  GList* items;
  GCompletionFunc func;

  gchar* prefix;
  GList* cache;
  GCompletionStrncmpFunc strncmp_func;
} GCompletion;

The data structure used for automatic completion.

GList *items; | list of target items (strings or data structures).
GCompletionFunc func; | function which is called to get the string associated with a target item. It is NULL if the target items are strings.
gchar *prefix; | the last prefix passed to g_completion_complete() or g_completion_complete_utf8().
GList *cache; | the list of items which begin with prefix.
GCompletionStrncmpFunc strncmp_func; | The function to use when comparing strings. Use g_completion_set_compare() to modify this function.

g_completion_new ()

GCompletion*        g_completion_new                    (GCompletionFunc func);

Creates a new GCompletion.

func : | the function to be called to return the string representing an item in the GCompletion, or NULL if strings are going to be used as the GCompletion items.
Returns : | the new GCompletion.

GCompletionFunc ()

gchar*              (*GCompletionFunc)                  (gpointer );

Specifies the type of the function passed to g_completion_new(). It should return the string corresponding to the given target item. This is used when you use data structures as GCompletion items.

Param1 : | the completion item.
Returns : | the string corresponding to the item.

g_completion_add_items ()

void                g_completion_add_items              (GCompletion *cmp,
                                                         GList *items);

Adds items to the GCompletion.

cmp : | the GCompletion.
items : | the list of items to add.

g_completion_remove_items ()

void                g_completion_remove_items           (GCompletion *cmp,
                                                         GList *items);

Removes items from a GCompletion.

cmp : | the GCompletion.
items : | the items to remove.

g_completion_clear_items ()

void                g_completion_clear_items            (GCompletion *cmp);

Removes all items from the GCompletion.

cmp : the GCompletion.

g_completion_complete ()

GList*              g_completion_complete               (GCompletion *cmp,
                                                         const gchar *prefix,
                                                         gchar **new_prefix);

Attempts to complete the string prefix using the GCompletion target items.

cmp : | the GCompletion.
prefix : | the prefix string, typically typed by the user, which is compared with each of the items.
new_prefix : | if non-NULL, returns the longest prefix which is common to all items that matched prefix, or NULL if no items matched prefix. This string should be freed when no longer needed.
Returns : | the list of items whose strings begin with prefix. This should not be changed.

g_completion_complete_utf8 ()

GList*              g_completion_complete_utf8          (GCompletion *cmp,
                                                         const gchar *prefix,
                                                         gchar **new_prefix);

Attempts to complete the string prefix using the GCompletion target items. In contrast to g_completion_complete(), this function returns the largest common prefix that is a valid UTF-8 string, omitting a possible common partial character.

You should use this function instead of g_completion_complete() if your items are UTF-8 strings.

cmp : | the GCompletion
prefix : | the prefix string, typically used by the user, which is compared with each of the items
new_prefix : | if non-NULL, returns the longest prefix which is common to all items that matched prefix, or NULL if no items matched prefix. This string should be freed when no longer needed.
Returns : | the list of items whose strings begin with prefix. This should not be changed.

Since 2.4

g_completion_set_compare ()

void                g_completion_set_compare            (GCompletion *cmp,
                                                         GCompletionStrncmpFunc strncmp_func);

Sets the function to use for string comparisons. The default string comparison function is strncmp().

cmp : | a GCompletion.
strncmp_func : | the string comparison function.

GCompletionStrncmpFunc ()

gint                (*GCompletionStrncmpFunc)           (const gchar *s1,
                                                         const gchar *s2,
                                                         gsize n);

Specifies the type of the function passed to g_completion_set_compare(). This is used when you use strings as GCompletion items.

s1 : | string to compare with s2.
s2 : | string to compare with s1.
n : | maximal number of bytes to compare.
Returns : | an integer less than, equal to, or greater than zero if the first n bytes of s1 is found, respectively, to be less than, to match, or to be greater than the first n bytes of s2.

g_completion_free ()

void                g_completion_free                   (GCompletion *cmp);

Frees all memory used by the GCompletion.

cmp : the GCompletion.


Balanced Binary Trees

Balanced Binary Trees — a sorted collection of key/value pairs optimized for searching and traversing in order.

Synopsis

#include <glib.h>

                    GTree;
GTree*              g_tree_new                          (GCompareFunc key_compare_func);
GTree*              g_tree_new_with_data                (GCompareDataFunc key_compare_func,
                                                         gpointer key_compare_data);
GTree*              g_tree_new_full                     (GCompareDataFunc key_compare_func,
                                                         gpointer key_compare_data,
                                                         GDestroyNotify key_destroy_func,
                                                         GDestroyNotify value_destroy_func);
void                g_tree_insert                       (GTree *tree,
                                                         gpointer key,
                                                         gpointer value);
void                g_tree_replace                      (GTree *tree,
                                                         gpointer key,
                                                         gpointer value);
gint                g_tree_nnodes                       (GTree *tree);
gint                g_tree_height                       (GTree *tree);
gpointer            g_tree_lookup                       (GTree *tree,
                                                         gconstpointer key);
gboolean            g_tree_lookup_extended              (GTree *tree,
                                                         gconstpointer lookup_key,
                                                         gpointer *orig_key,
                                                         gpointer *value);
void                g_tree_foreach                      (GTree *tree,
                                                         GTraverseFunc func,
                                                         gpointer user_data);
void                g_tree_traverse                     (GTree *tree,
                                                         GTraverseFunc traverse_func,
                                                         GTraverseType traverse_type,
                                                         gpointer user_data);
gboolean            (*GTraverseFunc)                    (gpointer key,
                                                         gpointer value,
                                                         gpointer data);
enum                GTraverseType;
gpointer            g_tree_search                       (GTree *tree,
                                                         GCompareFunc search_func,
                                                         gconstpointer user_data);
gboolean            g_tree_remove                       (GTree *tree,
                                                         gconstpointer key);
gboolean            g_tree_steal                        (GTree *tree,
                                                         gconstpointer key);
void                g_tree_destroy                      (GTree *tree);

Description

The GTree structure and its associated functions provide a sorted collection of key/value pairs optimized for searching and traversing in order.

To create a new GTree use g_tree_new().

To insert a key/value pair into a GTree use g_tree_insert().

To lookup the value corresponding to a given key, use g_tree_lookup() and g_tree_lookup_extended().

To find out the number of nodes in a GTree, use g_tree_nnodes(). To get the height of a GTree, use g_tree_height().

To traverse a GTree, calling a function for each node visited in the traversal, use g_tree_foreach().

To remove a key/value pair use g_tree_remove().

To destroy a GTree, use g_tree_destroy().

Details

GTree

typedef struct _GTree GTree;

The GTree struct is an opaque data structure representing a Balanced Binary Tree. It should be accessed only by using the following functions.

g_tree_new ()

GTree*              g_tree_new                          (GCompareFunc key_compare_func);

Creates a new GTree.

key_compare_func : | the function used to order the nodes in the GTree. It should return values similar to the standard strcmp() function - 0 if the two arguments are equal, a negative value if the first argument comes before the second, or a positive value if the first argument comes after the second.
Returns : | a new GTree.

g_tree_new_with_data ()

GTree*              g_tree_new_with_data                (GCompareDataFunc key_compare_func,
                                                         gpointer key_compare_data);

Creates a new GTree with a comparison function that accepts user data. See g_tree_new() for more details.

key_compare_func : | qsort()-style comparison function.
key_compare_data : | data to pass to comparison function.
Returns : | a new GTree.

g_tree_new_full ()

GTree*              g_tree_new_full                     (GCompareDataFunc key_compare_func,
                                                         gpointer key_compare_data,
                                                         GDestroyNotify key_destroy_func,
                                                         GDestroyNotify value_destroy_func);

Creates a new GTree like g_tree_new() and allows to specify functions to free the memory allocated for the key and value that get called when removing the entry from the GTree.

key_compare_func : | qsort()-style comparison function.
key_compare_data : | data to pass to comparison function.
key_destroy_func : | a function to free the memory allocated for the key used when removing the entry from the GTree or NULL if you don't want to supply such a function.
value_destroy_func : | a function to free the memory allocated for the value used when removing the entry from the GTree or NULL if you don't want to supply such a function.
Returns : | a new GTree.

g_tree_insert ()

void                g_tree_insert                       (GTree *tree,
                                                         gpointer key,
                                                         gpointer value);

Inserts a key/value pair into a GTree. If the given key already exists in the GTree its corresponding value is set to the new value. If you supplied a value_destroy_func when creating the GTree, the old value is freed using that function. If you supplied a key_destroy_func when creating the GTree, the passed key is freed using that function.

The tree is automatically 'balanced' as new key/value pairs are added, so that the distance from the root to every leaf is as small as possible.

tree : | a GTree.
key : | the key to insert.
value : | the value corresponding to the key.

g_tree_replace ()

void                g_tree_replace                      (GTree *tree,
                                                         gpointer key,
                                                         gpointer value);

Inserts a new key and value into a GTree similar to g_tree_insert(). The difference is that if the key already exists in the GTree, it gets replaced by the new key. If you supplied a value_destroy_func when creating the GTree, the old value is freed using that function. If you supplied a key_destroy_func when creating the GTree, the old key is freed using that function.

The tree is automatically 'balanced' as new key/value pairs are added, so that the distance from the root to every leaf is as small as possible.

tree : | a GTree.
key : | the key to insert.
value : | the value corresponding to the key.

g_tree_nnodes ()

gint                g_tree_nnodes                       (GTree *tree);

Gets the number of nodes in a GTree.

tree : | a GTree.
Returns : | the number of nodes in the GTree.

g_tree_height ()

gint                g_tree_height                       (GTree *tree);

Gets the height of a GTree.

If the GTree contains no nodes, the height is 0. If the GTree contains only one root node the height is 1. If the root node has children the height is 2, etc.

tree : | a GTree.
Returns : | the height of the GTree.

g_tree_lookup ()

gpointer            g_tree_lookup                       (GTree *tree,
                                                         gconstpointer key);

Gets the value corresponding to the given key. Since a GTree is automatically balanced as key/value pairs are added, key lookup is very fast.

tree : | a GTree.
key : | the key to look up.
Returns : | the value corresponding to the key, or NULL if the key was not found.

g_tree_lookup_extended ()

gboolean            g_tree_lookup_extended              (GTree *tree,
                                                         gconstpointer lookup_key,
                                                         gpointer *orig_key,
                                                         gpointer *value);

Looks up a key in the GTree, returning the original key and the associated value and a gboolean which is TRUE if the key was found. This is useful if you need to free the memory allocated for the original key, for example before calling g_tree_remove().

tree : | a GTree.
lookup_key : | the key to look up.
orig_key : | returns the original key.
value : | returns the value associated with the key.
Returns : | TRUE if the key was found in the GTree.

g_tree_foreach ()

void                g_tree_foreach                      (GTree *tree,
                                                         GTraverseFunc func,
                                                         gpointer user_data);

Calls the given function for each of the key/value pairs in the GTree. The function is passed the key and value of each pair, and the given data parameter. The tree is traversed in sorted order.

The tree may not be modified while iterating over it (you can't add/remove items). To remove all items matching a predicate, you need to add each item to a list in your GTraverseFunc as you walk over the tree, then walk the list and remove each item.

tree : | a GTree.
func : | the function to call for each node visited. If this function returns TRUE, the traversal is stopped.
user_data : | user data to pass to the function.

g_tree_traverse ()

void                g_tree_traverse                     (GTree *tree,
                                                         GTraverseFunc traverse_func,
                                                         GTraverseType traverse_type,
                                                         gpointer user_data);

Warning

g_tree_traverse has been deprecated since version 2.2 and should not be used in newly-written code. The order of a balanced tree is somewhat arbitrary. If you just want to visit all nodes in sorted order, use g_tree_foreach() instead. If you really need to visit nodes in a different order, consider using an N-ary Tree.

Calls the given function for each node in the GTree.

tree : | a GTree.
traverse_func : | the function to call for each node visited. If this function returns TRUE, the traversal is stopped.
traverse_type : | the order in which nodes are visited, one of G_IN_ORDER, G_PRE_ORDER and G_POST_ORDER.
user_data : | user data to pass to the function.

GTraverseFunc ()

gboolean            (*GTraverseFunc)                    (gpointer key,
                                                         gpointer value,
                                                         gpointer data);

Specifies the type of function passed to g_tree_traverse(). It is passed the key and value of each node, together with the user_data parameter passed to g_tree_traverse(). If the function returns TRUE, the traversal is stopped.

key : | a key of a GTree node.
value : | the value corresponding to the key.
data : | user data passed to g_tree_traverse().
Returns : | TRUE to stop the traversal.

enum GTraverseType

typedef enum
{
  G_IN_ORDER,
  G_PRE_ORDER,
  G_POST_ORDER,
  G_LEVEL_ORDER
} GTraverseType;

Specifies the type of traveral performed by g_tree_traverse(), g_node_traverse() and g_node_find().

G_IN_ORDER | vists a node's left child first, then the node itself, then its right child. This is the one to use if you want the output sorted according to the compare function.
G_PRE_ORDER | visits a node, then its children.
G_POST_ORDER | visits the node's children, then the node itself.
G_LEVEL_ORDER | is not implemented for Balanced Binary Trees. For N-ary Trees, it vists the root node first, then its children, then its grandchildren, and so on. Note that this is less efficient than the other orders.

g_tree_search ()

gpointer            g_tree_search                       (GTree *tree,
                                                         GCompareFunc search_func,
                                                         gconstpointer user_data);

Searches a GTree using search_func.

The search_func is called with a pointer to the key of a key/value pair in the tree, and the passed in user_data. If search_func returns 0 for a key/value pair, then g_tree_search_func() will return the value of that pair. If search_func returns -1, searching will proceed among the key/value pairs that have a smaller key; if search_func returns 1, searching will proceed among the key/value pairs that have a larger key.

tree : | a GTree.
search_func : | a function used to search the GTree.
user_data : | the data passed as the second argument to the search_func function.
Returns : | the value corresponding to the found key, or NULL if the key was not found.

g_tree_remove ()

gboolean            g_tree_remove                       (GTree *tree,
                                                         gconstpointer key);

Removes a key/value pair from a GTree.

If the GTree was created using g_tree_new_full(), the key and value are freed using the supplied destroy functions, otherwise you have to make sure that any dynamically allocated values are freed yourself. If the key does not exist in the GTree, the function does nothing.

tree : | a GTree.
key : | the key to remove.
Returns : | TRUE if the key was found (prior to 2.8, this function returned nothing)

g_tree_steal ()

gboolean            g_tree_steal                        (GTree *tree,
                                                         gconstpointer key);

Removes a key and its associated value from a GTree without calling the key and value destroy functions.

If the key does not exist in the GTree, the function does nothing.

tree : | a GTree.
key : | the key to remove.
Returns : | TRUE if the key was found (prior to 2.8, this function returned nothing)

g_tree_destroy ()

void                g_tree_destroy                      (GTree *tree);

Destroys the GTree. If keys and/or values are dynamically allocated, you should either free them first or create the GTree using g_tree_new_full(). In the latter case the destroy functions you supplied will be called on all keys and values before destroying the GTree.

tree : a GTree.


Base64 Encoding

Base64 Encoding — encodes and decodes data in Base64 format

Synopsis

#include <glib.h>

gsize               g_base64_encode_step                (const guchar *in,
                                                         gsize len,
                                                         gboolean break_lines,
                                                         gchar *out,
                                                         gint *state,
                                                         gint *save);
gsize               g_base64_encode_close               (gboolean break_lines,
                                                         gchar *out,
                                                         gint *state,
                                                         gint *save);
gchar*              g_base64_encode                     (const guchar *data,
                                                         gsize len);
gsize               g_base64_decode_step                (const gchar *in,
                                                         gsize len,
                                                         guchar *out,
                                                         gint *state,
                                                         guint *save);
guchar*             g_base64_decode                     (const gchar *text,
                                                         gsize *out_len);

Description

Base64 is an encoding that allows to encode a sequence of arbitrary bytes as a sequence of printable ASCII characters. For the definition of Base64, see RFC 1421 or RFC 2045. Base64 is most commonly used as a MIME transfer encoding for email.

GLib supports incremental encoding using g_base64_encode_step() and g_base64_encode_close(). Incremental decoding can be done with g_base64_decode_step(). To encode or decode data in one go, use g_base64_encode() or g_base64_decode().

Support for Base64 encoding has been added in GLib 2.12.

Details

g_base64_encode_step ()

gsize               g_base64_encode_step                (const guchar *in,
                                                         gsize len,
                                                         gboolean break_lines,
                                                         gchar *out,
                                                         gint *state,
                                                         gint *save);

Incrementally encode a sequence of binary data into it's Base-64 stringified representation. By calling this function multiple times you can convert data in chunks to avoid having to have the full encoded data in memory.

When all of the data has been converted you must call g_base64_encode_close() to flush the saved state.

The output buffer must be large enough to fit all the data that will be written to it. Due to the way base64 encodes you will need at least: len * 4 / 3 + 6 bytes. If you enable line-breaking you will need at least: len * 4 / 3 + len * 4 / (3 * 72) + 7 bytes.

break_lines is typically used when putting base64-encoded data in emails. It breaks the lines at 72 columns instead of putting all of the text on the same line. This avoids problems with long lines in the email system.

in : | the binary data to encode
len : | the length of in
break_lines : | whether to break long lines
out : | pointer to destination buffer
state : | Saved state between steps, initialize to 0
save : | Saved state between steps, initialize to 0
Returns : | The number of bytes of output that was written

Since 2.12

g_base64_encode_close ()

gsize               g_base64_encode_close               (gboolean break_lines,
                                                         gchar *out,
                                                         gint *state,
                                                         gint *save);

Flush the status from a sequence of calls to g_base64_encode_step().

break_lines : | whether to break long lines
out : | pointer to destination buffer
state : | Saved state from g_base64_encode_step()
save : | Saved state from g_base64_encode_step()
Returns : | The number of bytes of output that was written

Since 2.12

g_base64_encode ()

gchar*              g_base64_encode                     (const guchar *data,
                                                         gsize len);

Encode a sequence of binary data into its Base-64 stringified representation.

data : | the binary data to encode
len : | the length of data
Returns : | a newly allocated, zero-terminated Base-64 encoded string representing data.

Since 2.12

g_base64_decode_step ()

gsize               g_base64_decode_step                (const gchar *in,
                                                         gsize len,
                                                         guchar *out,
                                                         gint *state,
                                                         guint *save);

Incrementally decode a sequence of binary data from its Base-64 stringified representation. By calling this function multiple times you can convert data in chunks to avoid having to have the full encoded data in memory.

The output buffer must be large enough to fit all the data that will be written to it. Since base64 encodes 3 bytes in 4 chars you need at least: len * 3 / 4 bytes.

in : | binary input data
len : | max length of in data to decode
out : | output buffer
state : | Saved state between steps, initialize to 0
save : | Saved state between steps, initialize to 0
Returns : | The number of bytes of output that was written

Since 2.12

g_base64_decode ()

guchar*             g_base64_decode                     (const gchar *text,
                                                         gsize *out_len);

Decode a sequence of Base-64 encoded text into binary data

text : | zero-terminated string with base64 text to decode
out_len : | The length of the decoded data is written here
Returns : | a newly allocated buffer containing the binary data that text represents

Since 2.12


Basic Types

Basic Types — standard GLib types, defined for ease-of-use and portability.

Synopsis

#include <glib.h>

typedef             gboolean;
typedef             gpointer;
typedef             gconstpointer;
typedef             gchar;
typedef             guchar;

typedef             gint;
typedef             guint;
typedef             gshort;
typedef             gushort;
typedef             glong;
typedef             gulong;

typedef             gint8;
typedef             guint8;
typedef             gint16;
typedef             guint16;
typedef             gint32;
typedef             guint32;

#define             G_HAVE_GINT64
typedef             gint64;
GLIB_VAR            guint64                             ();
#define             G_GINT64_CONSTANT                   (val)
#define             G_GUINT64_CONSTANT                  (val)

typedef             gfloat;
typedef             gdouble;

typedef             gsize;
typedef             gssize;

Description

GLib defines a number of commonly used types, which can be divided into 4 groups:

  • New types which are not part of standard C - gboolean, gsize, gssize.

  • Integer types which are guaranteed to be the same size across all platforms - gint8, guint8, gint16, guint16, gint32, guint32, gint64, guint64.

  • Types which are easier to use than their standard C counterparts - gpointer, gconstpointer, guchar, guint, gushort, gulong.

  • Types which correspond exactly to standard C types, but are included for completeness - gchar, gint, gshort, glong, gfloat, gdouble.

Details

gboolean

typedef gint   gboolean;

A standard boolean type. Variables of this type should only contain the value TRUE or FALSE.

gpointer

typedef void* gpointer;

An untyped pointer. gpointer looks better and is easier to use than void*.

gconstpointer

typedef const void *gconstpointer;

An untyped pointer to constant data. The data pointed to should not be changed.

This is typically used in function prototypes to indicate that the data pointed to will not be altered by the function.

gchar

typedef char   gchar;

Corresponds to the standard C char type.

guchar

typedef unsigned char   guchar;

Corresponds to the standard C unsigned char type.

gint

typedef int    gint;

Corresponds to the standard C int type. Values of this type can range from G_MININT to G_MAXINT.

guint

typedef unsigned int    guint;

Corresponds to the standard C unsigned int type. Values of this type can range from 0 to G_MAXUINT.

gshort

typedef short  gshort;

Corresponds to the standard C short type. Values of this type can range from G_MINSHORT to G_MAXSHORT.

gushort

typedef unsigned short  gushort;

Corresponds to the standard C unsigned short type. Values of this type can range from 0 to G_MAXUSHORT.

glong

typedef long   glong;

Corresponds to the standard C long type. Values of this type can range from G_MINLONG to G_MAXLONG.

gulong

typedef unsigned long   gulong;

Corresponds to the standard C unsigned long type. Values of this type can range from 0 to G_MAXULONG.

gint8

typedef signed char gint8;

A signed integer guaranteed to be 8 bits on all platforms. Values of this type can range from -128 to 127.

guint8

typedef unsigned char guint8;

An unsigned integer guaranteed to be 8 bits on all platforms. Values of this type can range from 0 to 255.

gint16

typedef signed short gint16;

A signed integer guaranteed to be 16 bits on all platforms. Values of this type can range from -32,768 to 32,767.

guint16

typedef unsigned short guint16;

An unsigned integer guaranteed to be 16 bits on all platforms. Values of this type can range from 0 to 65,535.

gint32

typedef signed int gint32;

A signed integer guaranteed to be 32 bits on all platforms. Values of this type can range from -2,147,483,648 to 2,147,483,647.

guint32

typedef unsigned int guint32;

An unsigned integer guaranteed to be 32 bits on all platforms. Values of this type can range from 0 to 4,294,967,295.

G_HAVE_GINT64

#define G_HAVE_GINT64 1          /* deprecated, always true */

Warning

G_HAVE_GINT64 is deprecated and should not be used in newly-written code. GLib requires 64-bit integer support since version 2.0, therefore G_HAVE_GINT64 is always defined.

This macro is defined if 64-bit signed and unsigned integers are available on the platform.

gint64

G_GNUC_EXTENSION typedef signed long long gint64;

A signed integer guaranteed to be 64 bits on all platforms. Values of this type can range from -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807.

guint64 ()

GLIB_VAR            guint64                             ();

An unsigned integer guaranteed to be 64 bits on all platforms. Values of this type can range from 0 to 18,446,744,073,709,551,615.

Returns :

G_GINT64_CONSTANT()

#define G_GINT64_CONSTANT(val)	(G_GNUC_EXTENSION (val##LL))

This macro is used to insert 64-bit integer literals into the source code.

val : a literal integer value, e.g. 0x1d636b02300a7aa7U.

G_GUINT64_CONSTANT()

#define G_GUINT64_CONSTANT(val)	(G_GNUC_EXTENSION (val##ULL))

This macro is used to insert 64-bit unsigned integer literals into the source code.

val : a literal integer value, e.g. 0x1d636b02300a7aa7U.

Since 2.10

gfloat

typedef float   gfloat;

Corresponds to the standard C float type. Values of this type can range from -G_MAXFLOAT to G_MAXFLOAT.

gdouble

typedef double  gdouble;

Corresponds to the standard C double type. Values of this type can range from -G_MAXDOUBLE to G_MAXDOUBLE.

gsize

typedef unsigned int gsize;

An unsigned 32-bit integer intended to represent sizes of data structures.

gssize

typedef signed int gssize;

A signed 32-bit integer intended to represent sizes of data structures.


Bookmark file parser

Bookmark file parser — parses files containing bookmarks

Synopsis

#include <glib.h>

                    GBookmarkFile;
#define             G_BOOKMARK_FILE_ERROR
enum                GBookmarkFileError;
GBookmarkFile*      g_bookmark_file_new                 (void);
void                g_bookmark_file_free                (GBookmarkFile *bookmark);
gboolean            g_bookmark_file_load_from_file      (GBookmarkFile *bookmark,
                                                         const gchar *filename,
                                                         GError **error);
gboolean            g_bookmark_file_load_from_data      (GBookmarkFile *bookmark,
                                                         const gchar *data,
                                                         gsize length,
                                                         GError **error);
gboolean            g_bookmark_file_load_from_data_dirs (GBookmarkFile *bookmark,
                                                         const gchar *file,
                                                         gchar **full_path,
                                                         GError **error);
gchar*              g_bookmark_file_to_data             (GBookmarkFile *bookmark,
                                                         gsize *length,
                                                         GError **error);
gboolean            g_bookmark_file_to_file             (GBookmarkFile *bookmark,
                                                         const gchar *filename,
                                                         GError **error);
gboolean            g_bookmark_file_has_item            (GBookmarkFile *bookmark,
                                                         const gchar *uri);
gboolean            g_bookmark_file_has_group           (GBookmarkFile *bookmark,
                                                         const gchar *uri,
                                                         const gchar *group,
                                                         GError **error);
gboolean            g_bookmark_file_has_application     (GBookmarkFile *bookmark,
                                                         const gchar *uri,
                                                         const gchar *name,
                                                         GError **error);
gint                g_bookmark_file_get_size            (GBookmarkFile *bookmark);
gchar**             g_bookmark_file_get_uris            (GBookmarkFile *bookmark,
                                                         gsize *length);

gchar*              g_bookmark_file_get_title           (GBookmarkFile *bookmark,
                                                         const gchar *uri,
                                                         GError **error);
gchar*              g_bookmark_file_get_description     (GBookmarkFile *bookmark,
                                                         const gchar *uri,
                                                         GError **error);
gchar*              g_bookmark_file_get_mime_type       (GBookmarkFile *bookmark,
                                                         const gchar *uri,
                                                         GError **error);
gboolean            g_bookmark_file_get_is_private      (GBookmarkFile *bookmark,
                                                         const gchar *uri,
                                                         GError **error);
gboolean            g_bookmark_file_get_icon            (GBookmarkFile *bookmark,
                                                         const gchar *uri,
                                                         gchar **href,
                                                         gchar **mime_type,
                                                         GError **error);
time_t              g_bookmark_file_get_added           (GBookmarkFile *bookmark,
                                                         const gchar *uri,
                                                         GError **error);
time_t              g_bookmark_file_get_modified        (GBookmarkFile *bookmark,
                                                         const gchar *uri,
                                                         GError **error);
time_t              g_bookmark_file_get_visited         (GBookmarkFile *bookmark,
                                                         const gchar *uri,
                                                         GError **error);
gchar**             g_bookmark_file_get_groups          (GBookmarkFile *bookmark,
                                                         const gchar *uri,
                                                         gsize *length,
                                                         GError **error);
gchar**             g_bookmark_file_get_applications    (GBookmarkFile *bookmark,
                                                         const gchar *uri,
                                                         gsize *length,
                                                         GError **error);
gboolean            g_bookmark_file_get_app_info        (GBookmarkFile *bookmark,
                                                         const gchar *uri,
                                                         const gchar *name,
                                                         gchar **exec,
                                                         guint *count,
                                                         time_t *stamp,
                                                         GError **error);

void                g_bookmark_file_set_title           (GBookmarkFile *bookmark,
                                                         const gchar *uri,
                                                         const gchar *title);
void                g_bookmark_file_set_description     (GBookmarkFile *bookmark,
                                                         const gchar *uri,
                                                         const gchar *description);
void                g_bookmark_file_set_mime_type       (GBookmarkFile *bookmark,
                                                         const gchar *uri,
                                                         const gchar *mime_type);
void                g_bookmark_file_set_is_private      (GBookmarkFile *bookmark,
                                                         const gchar *uri,
                                                         gboolean is_private);
void                g_bookmark_file_set_icon            (GBookmarkFile *bookmark,
                                                         const gchar *uri,
                                                         const gchar *href,
                                                         const gchar *mime_type);
void                g_bookmark_file_set_added           (GBookmarkFile *bookmark,
                                                         const gchar *uri,
                                                         time_t added);
void                g_bookmark_file_set_groups          (GBookmarkFile *bookmark,
                                                         const gchar *uri,
                                                         const gchar **groups,
                                                         gsize length);
void                g_bookmark_file_set_modified        (GBookmarkFile *bookmark,
                                                         const gchar *uri,
                                                         time_t modified);
void                g_bookmark_file_set_visited         (GBookmarkFile *bookmark,
                                                         const gchar *uri,
                                                         time_t visited);
gboolean            g_bookmark_file_set_app_info        (GBookmarkFile *bookmark,
                                                         const gchar *uri,
                                                         const gchar *name,
                                                         const gchar *exec,
                                                         gint count,
                                                         time_t stamp,
                                                         GError **error);
void                g_bookmark_file_add_group           (GBookmarkFile *bookmark,
                                                         const gchar *uri,
                                                         const gchar *group);
void                g_bookmark_file_add_application     (GBookmarkFile *bookmark,
                                                         const gchar *uri,
                                                         const gchar *name,
                                                         const gchar *exec);
gboolean            g_bookmark_file_remove_group        (GBookmarkFile *bookmark,
                                                         const gchar *uri,
                                                         const gchar *group,
                                                         GError **error);
gboolean            g_bookmark_file_remove_application  (GBookmarkFile *bookmark,
                                                         const gchar *uri,
                                                         const gchar *name,
                                                         GError **error);
gboolean            g_bookmark_file_remove_item         (GBookmarkFile *bookmark,
                                                         const gchar *uri,
                                                         GError **error);
gboolean            g_bookmark_file_move_item           (GBookmarkFile *bookmark,
                                                         const gchar *old_uri,
                                                         const gchar *new_uri,
                                                         GError **error);

Description

GBookmarkFile lets you parse, edit or create files containing bookmarks to URI, along with some meta-data about the resource pointed by the URI like its MIME type, the application that is registering the bookmark and the icon that should be used to represent the bookmark. The data is stored using the Desktop Bookmark Specification.

The syntax of the bookmark files is described in detail inside the Desktop Bookmark Specification, here is a quick summary: bookmark files use a sub-class of the XML Bookmark Exchange Language specification, consisting of valid UTF-8 encoded XML, under the xbel root element; each bookmark is stored inside a bookmark element, using its URI: no relative paths can be used inside a bookmark file. The bookmark may have a user defined title and description, to be used instead of the URI. Under the metadata element, with its owner attribute set to http://freedesktop.org, is stored the meta-data about a resource pointed by its URI. The meta-data consists of the resource's MIME type; the applications that have registered a bookmark; the groups to which a bookmark belongs to; a visibility flag, used to set the bookmark as "private" to the applications and groups that has it registered; the URI and MIME type of an icon, to be used when displaying the bookmark inside a GUI.

<?xml version="1.0"?>
<!DOCTYPE xbel PUBLIC
  "+//IDN python.org//DTD XML Bookmark Exchange Language 1.0//EN//XML"
  "http://www.python.org/topics/xml/dtds/xbel-1.0.dtd">
<xbel version="1.0"
      xmlns:mime="http://www.freedesktop.org/standards/shared-mime-info"
      xmlns:bookmark="http://www.freedesktop.org/standards/desktop-bookmarks">
  <bookmark href="file:///home/ebassi/bookmark-spec/bookmark-spec.xml">
    <title>Desktop Bookmarks Spec</title>
    <info>
      <metadata owner="http://freedesktop.org">
        <mime:mime-type>text/xml</mime:mime-type>
    <bookmark:applications>
          <bookmark:application name="GEdit" count="2" exec="gedit %u" timestamp="1115726763"/>
          <bookmark:application name="GViM" count="7" exec="gvim %f" timestamp="1115726812"/>
    </bookmark:applications>
    <bookmark:groups>
      <bookmark:group>Editors</bookmark:group>
    </bookmark:groups>
      </metadata>
    </info>
  </bookmark>
</xbel>

A bookmark file might contain more than one bookmark; each bookmark is accessed through its URI.

The important caveat of bookmark files is that when you add a new bookmark you must also add the application that is registering it, using g_bookmark_file_add_application() or g_bookmark_file_set_app_info(). If a bookmark has no applications then it won't be dumped when creating the on disk representation, using g_bookmark_file_to_data() or g_bookmark_file_to_file().

The GBookmarkFile parser was added in GLib 2.12.

Details

GBookmarkFile

typedef struct _GBookmarkFile GBookmarkFile;

The GBookmarkFile struct contains only private data and should not be used directly.

G_BOOKMARK_FILE_ERROR

#define G_BOOKMARK_FILE_ERROR	(g_bookmark_file_error_quark ())

Error domain for bookmark file parsing. Errors in this domain will be from the GBookmarkFileError enumeration. See GError for informations on error domains.

enum GBookmarkFileError

typedef enum
{
  G_BOOKMARK_FILE_ERROR_INVALID_URI,
  G_BOOKMARK_FILE_ERROR_INVALID_VALUE,
  G_BOOKMARK_FILE_ERROR_APP_NOT_REGISTERED,
  G_BOOKMARK_FILE_ERROR_URI_NOT_FOUND,
  G_BOOKMARK_FILE_ERROR_READ,
  G_BOOKMARK_FILE_ERROR_UNKNOWN_ENCODING,
  G_BOOKMARK_FILE_ERROR_WRITE,
  G_BOOKMARK_FILE_ERROR_FILE_NOT_FOUND
} GBookmarkFileError;

Error codes returned by bookmark file parsing.

G_BOOKMARK_FILE_ERROR_INVALID_URI | URI was ill-formed
G_BOOKMARK_FILE_ERROR_INVALID_VALUE | a requested field was not found
G_BOOKMARK_FILE_ERROR_APP_NOT_REGISTERED | a requested application did not register a bookmark
G_BOOKMARK_FILE_ERROR_URI_NOT_FOUND | a requested URI was not found
G_BOOKMARK_FILE_ERROR_READ | document was ill formed
G_BOOKMARK_FILE_ERROR_UNKNOWN_ENCODING | the text being parsed was in an unknown encoding
G_BOOKMARK_FILE_ERROR_WRITE | an error occurred while writing
G_BOOKMARK_FILE_ERROR_FILE_NOT_FOUND | requested file was not found

g_bookmark_file_new ()

GBookmarkFile*      g_bookmark_file_new                 (void);

Creates a new empty GBookmarkFile object.

Use g_bookmark_file_load_from_file(), g_bookmark_file_load_from_data() or g_bookmark_file_load_from_data_dirs() to read an existing bookmark file.

Returns : an empty GBookmarkFile

Since 2.12

g_bookmark_file_free ()

void                g_bookmark_file_free                (GBookmarkFile *bookmark);

Frees a GBookmarkFile.

bookmark : a GBookmarkFile

Since 2.12

g_bookmark_file_load_from_file ()

gboolean            g_bookmark_file_load_from_file      (GBookmarkFile *bookmark,
                                                         const gchar *filename,
                                                         GError **error);

Loads a desktop bookmark file into an empty GBookmarkFile structure. If the file could not be loaded then error is set to either a GFileError or GBookmarkFileError.

bookmark : | an empty GBookmarkFile struct
filename : | the path of a filename to load, in the GLib file name encoding
error : | return location for a GError, or NULL
Returns : | TRUE if a desktop bookmark file could be loaded

Since 2.12

g_bookmark_file_load_from_data ()

gboolean            g_bookmark_file_load_from_data      (GBookmarkFile *bookmark,
                                                         const gchar *data,
                                                         gsize length,
                                                         GError **error);

Loads a bookmark file from memory into an empty GBookmarkFile structure. If the object cannot be created then error is set to a GBookmarkFileError.

bookmark : | an empty GBookmarkFile struct
data : | desktop bookmarks loaded in memory
length : | the length of data in bytes
error : | return location for a GError, or NULL
Returns : | TRUE if a desktop bookmark could be loaded.

Since 2.12

g_bookmark_file_load_from_data_dirs ()

gboolean            g_bookmark_file_load_from_data_dirs (GBookmarkFile *bookmark,
                                                         const gchar *file,
                                                         gchar **full_path,
                                                         GError **error);

This function looks for a desktop bookmark file named file in the paths returned from g_get_user_data_dir() and g_get_system_data_dirs(), loads the file into bookmark and returns the file's full path in full_path. If the file could not be loaded then an error is set to either a GFileError or GBookmarkFileError.

bookmark : | a GBookmarkFile
file : | a relative path to a filename to open and parse
full_path : | return location for a string containing the full path of the file, or NULL
error : | return location for a GError, or NULL
Returns : | TRUE if a key file could be loaded, FALSE othewise

Since 2.12

g_bookmark_file_to_data ()

gchar*              g_bookmark_file_to_data             (GBookmarkFile *bookmark,
                                                         gsize *length,
                                                         GError **error);

This function outputs bookmark as a string.

bookmark : | a GBookmarkFile
length : | return location for the length of the returned string, or NULL
error : | return location for a GError, or NULL
Returns : | a newly allocated string holding the contents of the GBookmarkFile

Since 2.12

g_bookmark_file_to_file ()

gboolean            g_bookmark_file_to_file             (GBookmarkFile *bookmark,
                                                         const gchar *filename,
                                                         GError **error);

This function outputs bookmark into a file. The write process is guaranteed to be atomic by using g_file_set_contents() internally.

bookmark : | a GBookmarkFile
filename : | path of the output file
error : | return location for a GError, or NULL
Returns : | TRUE if the file was successfully written.

Since 2.12

g_bookmark_file_has_item ()

gboolean            g_bookmark_file_has_item            (GBookmarkFile *bookmark,
                                                         const gchar *uri);

Looks whether the desktop bookmark has an item with its URI set to uri.

bookmark : | a GBookmarkFile
uri : | a valid URI
Returns : | TRUE if uri is inside bookmark, FALSE otherwise

Since 2.12

g_bookmark_file_has_group ()

gboolean            g_bookmark_file_has_group           (GBookmarkFile *bookmark,
                                                         const gchar *uri,
                                                         const gchar *group,
                                                         GError **error);

Checks whether group appears in the list of groups to which the bookmark for uri belongs to.

In the event the URI cannot be found, FALSE is returned and error is set to G_BOOKMARK_FILE_ERROR_URI_NOT_FOUND.

bookmark : | a GBookmarkFile
uri : | a valid URI
group : | the group name to be searched
error : | return location for a GError, or NULL
Returns : | TRUE if group was found.

Since 2.12

g_bookmark_file_has_application ()

gboolean            g_bookmark_file_has_application     (GBookmarkFile *bookmark,
                                                         const gchar *uri,
                                                         const gchar *name,
                                                         GError **error);

Checks whether the bookmark for uri inside bookmark has been registered by application name.

In the event the URI cannot be found, FALSE is returned and error is set to G_BOOKMARK_FILE_ERROR_URI_NOT_FOUND.

bookmark : | a GBookmarkFile
uri : | a valid URI
name : | the name of the application
error : | return location for a GError or NULL
Returns : | TRUE if the application name was found

Since 2.12

g_bookmark_file_get_size ()

gint                g_bookmark_file_get_size            (GBookmarkFile *bookmark);

Gets the number of bookmarks inside bookmark.

bookmark : | a GBookmarkFile
Returns : | the number of bookmarks

Since 2.12

g_bookmark_file_get_uris ()

gchar**             g_bookmark_file_get_uris            (GBookmarkFile *bookmark,
                                                         gsize *length);

Returns all URIs of the bookmarks in the bookmark file bookmark. The array of returned URIs will be NULL-terminated, so length may optionally be NULL.

bookmark : | a GBookmarkFile
length : | return location for the number of returned URIs, or NULL
Returns : | a newly allocated NULL-terminated array of strings. Use g_strfreev() to free it.

Since 2.12

g_bookmark_file_get_title ()

gchar*              g_bookmark_file_get_title           (GBookmarkFile *bookmark,
                                                         const gchar *uri,
                                                         GError **error);

Returns the title of the bookmark for uri.

If uri is NULL, the title of bookmark is returned.

In the event the URI cannot be found, NULL is returned and error is set to G_BOOKMARK_FILE_ERROR_URI_NOT_FOUND.

bookmark : | a GBookmarkFile
uri : | a valid URI or NULL
error : | return location for a GError, or NULL
Returns : | a newly allocated string or NULL if the specified URI cannot be found.

Since 2.12

g_bookmark_file_get_description ()

gchar*              g_bookmark_file_get_description     (GBookmarkFile *bookmark,
                                                         const gchar *uri,
                                                         GError **error);

Retrieves the description of the bookmark for uri.

In the event the URI cannot be found, NULL is returned and error is set to G_BOOKMARK_FILE_ERROR_URI_NOT_FOUND.

bookmark : | a GBookmarkFile
uri : | a valid URI
error : | return location for a GError, or NULL
Returns : | a newly allocated string or NULL if the specified URI cannot be found.

Since 2.12

g_bookmark_file_get_mime_type ()

gchar*              g_bookmark_file_get_mime_type       (GBookmarkFile *bookmark,
                                                         const gchar *uri,
                                                         GError **error);

Retrieves the MIME type of the resource pointed by uri.

In the event the URI cannot be found, NULL is returned and error is set to G_BOOKMARK_FILE_ERROR_URI_NOT_FOUND. In the event that the MIME type cannot be found, NULL is returned and error is set to G_BOOKMARK_FILE_ERROR_INVALID_VALUE.

bookmark : | a GBookmarkFile
uri : | a valid URI
error : | return location for a GError, or NULL
Returns : | a newly allocated string or NULL if the specified URI cannot be found.

Since 2.12

g_bookmark_file_get_is_private ()

gboolean            g_bookmark_file_get_is_private      (GBookmarkFile *bookmark,
                                                         const gchar *uri,
                                                         GError **error);

Gets whether the private flag of the bookmark for uri is set.

In the event the URI cannot be found, FALSE is returned and error is set to G_BOOKMARK_FILE_ERROR_URI_NOT_FOUND. In the event that the private flag cannot be found, FALSE is returned and error is set to G_BOOKMARK_FILE_ERROR_INVALID_VALUE.

bookmark : | a GBookmarkFile
uri : | a valid URI
error : | return location for a GError, or NULL
Returns : | TRUE if the private flag is set, FALSE otherwise.

Since 2.12

g_bookmark_file_get_icon ()

gboolean            g_bookmark_file_get_icon            (GBookmarkFile *bookmark,
                                                         const gchar *uri,
                                                         gchar **href,
                                                         gchar **mime_type,
                                                         GError **error);

Gets the icon of the bookmark for uri.

In the event the URI cannot be found, FALSE is returned and error is set to G_BOOKMARK_FILE_ERROR_URI_NOT_FOUND.

bookmark : | a GBookmarkFile
uri : | a valid URI
href : | return location for the icon's location or NULL
mime_type : | return location for the icon's MIME type or NULL
error : | return location for a GError or NULL
Returns : | TRUE if the icon for the bookmark for the URI was found. You should free the returned strings.

Since 2.12

g_bookmark_file_get_added ()

time_t              g_bookmark_file_get_added           (GBookmarkFile *bookmark,
                                                         const gchar *uri,
                                                         GError **error);

Gets the time the bookmark for uri was added to bookmark

In the event the URI cannot be found, -1 is returned and error is set to G_BOOKMARK_FILE_ERROR_URI_NOT_FOUND.

bookmark : | a GBookmarkFile
uri : | a valid URI
error : | return location for a GError, or NULL
Returns : | a timestamp

Since 2.12

g_bookmark_file_get_modified ()

time_t              g_bookmark_file_get_modified        (GBookmarkFile *bookmark,
                                                         const gchar *uri,
                                                         GError **error);

Gets the time when the bookmark for uri was last modified.

In the event the URI cannot be found, -1 is returned and error is set to G_BOOKMARK_FILE_ERROR_URI_NOT_FOUND.

bookmark : | a GBookmarkFile
uri : | a valid URI
error : | return location for a GError, or NULL
Returns : | a timestamp

Since 2.12

g_bookmark_file_get_visited ()

time_t              g_bookmark_file_get_visited         (GBookmarkFile *bookmark,
                                                         const gchar *uri,
                                                         GError **error);

Gets the time the bookmark for uri was last visited.

In the event the URI cannot be found, -1 is returned and error is set to G_BOOKMARK_FILE_ERROR_URI_NOT_FOUND.

bookmark : | a GBookmarkFile
uri : | a valid URI
error : | return location for a GError, or NULL
Returns : | a timestamp.

Since 2.12

g_bookmark_file_get_groups ()

gchar**             g_bookmark_file_get_groups          (GBookmarkFile *bookmark,
                                                         const gchar *uri,
                                                         gsize *length,
                                                         GError **error);

Retrieves the list of group names of the bookmark for uri.

In the event the URI cannot be found, NULL is returned and error is set to G_BOOKMARK_FILE_ERROR_URI_NOT_FOUND.

The returned array is NULL terminated, so length may optionally be NULL.

bookmark : | a GBookmarkFile
uri : | a valid URI
length : | return location for the length of the returned string, or NULL
error : | return location for a GError, or NULL
Returns : | a newly allocated NULL-terminated array of group names. Use g_strfreev() to free it.

Since 2.12

g_bookmark_file_get_applications ()

gchar**             g_bookmark_file_get_applications    (GBookmarkFile *bookmark,
                                                         const gchar *uri,
                                                         gsize *length,
                                                         GError **error);

Retrieves the names of the applications that have registered the bookmark for uri.

In the event the URI cannot be found, NULL is returned and error is set to G_BOOKMARK_FILE_ERROR_URI_NOT_FOUND.

bookmark : | a GBookmarkFile
uri : | a valid URI
length : | return location of the length of the returned list, or NULL
error : | return location for a GError, or NULL
Returns : | a newly allocated NULL-terminated array of strings. Use g_strfreev() to free it.

Since 2.12

g_bookmark_file_get_app_info ()

gboolean            g_bookmark_file_get_app_info        (GBookmarkFile *bookmark,
                                                         const gchar *uri,
                                                         const gchar *name,
                                                         gchar **exec,
                                                         guint *count,
                                                         time_t *stamp,
                                                         GError **error);

Gets the registration informations of app_name for the bookmark for uri. See g_bookmark_file_set_app_info() for more informations about the returned data.

The string returned in app_exec must be freed.

In the event the URI cannot be found, FALSE is returned and error is set to G_BOOKMARK_FILE_ERROR_URI_NOT_FOUND. In the event that no application with name app_name has registered a bookmark for uri, FALSE is returned and error is set to G_BOOKMARK_FILE_ERROR_APP_NOT_REGISTERED.

bookmark : | a GBookmarkFile
uri : | a valid URI
name : | an application's name
exec : | location for the command line of the application, or NULL
count : | return location for the registration count, or NULL
stamp : | return location for the last registration time, or NULL
error : | return location for a GError, or NULL
Returns : | TRUE on success.

Since 2.12

g_bookmark_file_set_title ()

void                g_bookmark_file_set_title           (GBookmarkFile *bookmark,
                                                         const gchar *uri,
                                                         const gchar *title);

Sets title as the title of the bookmark for uri inside the bookmark file bookmark.

If uri is NULL, the title of bookmark is set.

If a bookmark for uri cannot be found then it is created.

bookmark : | a GBookmarkFile
uri : | a valid URI or NULL
title : | a UTF-8 encoded string

Since 2.12

g_bookmark_file_set_description ()

void                g_bookmark_file_set_description     (GBookmarkFile *bookmark,
                                                         const gchar *uri,
                                                         const gchar *description);

Sets description as the description of the bookmark for uri.

If uri is NULL, the description of bookmark is set.

If a bookmark for uri cannot be found then it is created.

bookmark : | a GBookmarkFile
uri : | a valid URI or NULL
description : | a string

Since 2.12

g_bookmark_file_set_mime_type ()

void                g_bookmark_file_set_mime_type       (GBookmarkFile *bookmark,
                                                         const gchar *uri,
                                                         const gchar *mime_type);

Sets mime_type as the MIME type of the bookmark for uri.

If a bookmark for uri cannot be found then it is created.

bookmark : | a GBookmarkFile
uri : | a valid URI
mime_type : | a MIME type

Since 2.12

g_bookmark_file_set_is_private ()

void                g_bookmark_file_set_is_private      (GBookmarkFile *bookmark,
                                                         const gchar *uri,
                                                         gboolean is_private);

Sets the private flag of the bookmark for uri.

If a bookmark for uri cannot be found then it is created.

bookmark : | a GBookmarkFile
uri : | a valid URI
is_private : | TRUE if the bookmark should be marked as private

Since 2.12

g_bookmark_file_set_icon ()

void                g_bookmark_file_set_icon            (GBookmarkFile *bookmark,
                                                         const gchar *uri,
                                                         const gchar *href,
                                                         const gchar *mime_type);

Sets the icon for the bookmark for uri. If href is NULL, unsets the currently set icon.

If no bookmark for uri is found it is created.

bookmark : | a GBookmarkFile
uri : | a valid URI
href : | the URI of the icon for the bookmark, or NULL
mime_type : | the MIME type of the icon for the bookmark

Since 2.12

g_bookmark_file_set_added ()

void                g_bookmark_file_set_added           (GBookmarkFile *bookmark,
                                                         const gchar *uri,
                                                         time_t added);

Sets the time the bookmark for uri was added into bookmark.

If no bookmark for uri is found then it is created.

bookmark : | a GBookmarkFile
uri : | a valid URI
added : | a timestamp or -1 to use the current time

Since 2.12

g_bookmark_file_set_groups ()

void                g_bookmark_file_set_groups          (GBookmarkFile *bookmark,
                                                         const gchar *uri,
                                                         const gchar **groups,
                                                         gsize length);

Sets a list of group names for the item with URI uri. Each previously set group name list is removed.

If uri cannot be found then an item for it is created.

bookmark : | a GBookmarkFile
uri : | an item's URI
groups : | an array of group names, or NULL to remove all groups
length : | number of group name values in groups

Since 2.12

g_bookmark_file_set_modified ()

void                g_bookmark_file_set_modified        (GBookmarkFile *bookmark,
                                                         const gchar *uri,
                                                         time_t modified);

Sets the last time the bookmark for uri was last modified.

If no bookmark for uri is found then it is created.

The "modified" time should only be set when the bookmark's meta-data was actually changed. Every function of GBookmarkFile that modifies a bookmark also changes the modification time, except for g_bookmark_file_set_visited().

bookmark : | a GBookmarkFile
uri : | a valid URI
modified : | a timestamp or -1 to use the current time

Since 2.12

g_bookmark_file_set_visited ()

void                g_bookmark_file_set_visited         (GBookmarkFile *bookmark,
                                                         const gchar *uri,
                                                         time_t visited);

Sets the time the bookmark for uri was last visited.

If no bookmark for uri is found then it is created.

The "visited" time should only be set if the bookmark was launched, either using the command line retrieved by g_bookmark_file_get_app_info() or by the default application for the bookmark's MIME type, retrieved using g_bookmark_file_get_mime_type(). Changing the "visited" time does not affect the "modified" time.

bookmark : | a GBookmarkFile
uri : | a valid URI
visited : | a timestamp or -1 to use the current time

Since 2.12

g_bookmark_file_set_app_info ()

gboolean            g_bookmark_file_set_app_info        (GBookmarkFile *bookmark,
                                                         const gchar *uri,
                                                         const gchar *name,
                                                         const gchar *exec,
                                                         gint count,
                                                         time_t stamp,
                                                         GError **error);

Sets the meta-data of application name inside the list of applications that have registered a bookmark for uri inside bookmark.

You should rarely use this function; use g_bookmark_file_add_application() and g_bookmark_file_remove_application() instead.

name can be any UTF-8 encoded string used to identify an application. exec can have one of these two modifiers: "f", which will be expanded as the local file name retrieved from the bookmark's URI; "u", which will be expanded as the bookmark's URI. The expansion is done automatically when retrieving the stored command line using the g_bookmark_file_get_app_info() function. count is the number of times the application has registered the bookmark; if is < 0, the current registration count will be increased by one, if is 0, the application with name will be removed from the list of registered applications. stamp is the Unix time of the last registration; if it is -1, the current time will be used.

If you try to remove an application by setting its registration count to zero, and no bookmark for uri is found, FALSE is returned and error is set to G_BOOKMARK_FILE_ERROR_URI_NOT_FOUND; similarly, in the event that no application name has registered a bookmark for uri, FALSE is returned and error is set to G_BOOKMARK_FILE_ERROR_APP_NOT_REGISTERED. Otherwise, if no bookmark for uri is found, one is created.

bookmark : | a GBookmarkFile
uri : | a valid URI
name : | an application's name
exec : | an application's command line
count : | the number of registrations done for this application
stamp : | the time of the last registration for this application
error : | return location for a GError or NULL
Returns : | TRUE if the application's meta-data was successfully changed.

Since 2.12

g_bookmark_file_add_group ()

void                g_bookmark_file_add_group           (GBookmarkFile *bookmark,
                                                         const gchar *uri,
                                                         const gchar *group);

Adds group to the list of groups to which the bookmark for uri belongs to.

If no bookmark for uri is found then it is created.

bookmark : | a GBookmarkFile
uri : | a valid URI
group : | the group name to be added

Since 2.12

g_bookmark_file_add_application ()

void                g_bookmark_file_add_application     (GBookmarkFile *bookmark,
                                                         const gchar *uri,
                                                         const gchar *name,
                                                         const gchar *exec);

Adds the application with name and exec to the list of applications that have registered a bookmark for uri into bookmark.

Every bookmark inside a GBookmarkFile must have at least an application registered. Each application must provide a name, a command line useful for launching the bookmark, the number of times the bookmark has been registered by the application and the last time the application registered this bookmark.

If name is NULL, the name of the application will be the same returned by g_get_application(); if exec is NULL, the command line will be a composition of the program name as returned by g_get_prgname() and the "u" modifier, which will be expanded to the bookmark's URI.

This function will automatically take care of updating the registrations count and timestamping in case an application with the same name had already registered a bookmark for uri inside bookmark.

If no bookmark for uri is found, one is created.

bookmark : | a GBookmarkFile
uri : | a valid URI
name : | the name of the application registering the bookmark or NULL
exec : | command line to be used to launch the bookmark or NULL

Since 2.12

g_bookmark_file_remove_group ()

gboolean            g_bookmark_file_remove_group        (GBookmarkFile *bookmark,
                                                         const gchar *uri,
                                                         const gchar *group,
                                                         GError **error);

Removes group from the list of groups to which the bookmark for uri belongs to.

In the event the URI cannot be found, FALSE is returned and error is set to G_BOOKMARK_FILE_ERROR_URI_NOT_FOUND. In the event no group was defined, FALSE is returned and error is set to G_BOOKMARK_FILE_ERROR_INVALID_VALUE.

bookmark : | a GBookmarkFile
uri : | a valid URI
group : | the group name to be removed
error : | return location for a GError, or NULL
Returns : | TRUE if group was successfully removed.

Since 2.12

g_bookmark_file_remove_application ()

gboolean            g_bookmark_file_remove_application  (GBookmarkFile *bookmark,
                                                         const gchar *uri,
                                                         const gchar *name,
                                                         GError **error);

Removes application registered with name from the list of applications that have registered a bookmark for uri inside bookmark.

In the event the URI cannot be found, FALSE is returned and error is set to G_BOOKMARK_FILE_ERROR_URI_NOT_FOUND. In the event that no application with name app_name has registered a bookmark for uri, FALSE is returned and error is set to G_BOOKMARK_FILE_ERROR_APP_NOT_REGISTERED.

bookmark : | a GBookmarkFile
uri : | a valid URI
name : | the name of the application
error : | return location for a GError or NULL
Returns : | TRUE if the application was successfully removed.

Since 2.12

g_bookmark_file_remove_item ()

gboolean            g_bookmark_file_remove_item         (GBookmarkFile *bookmark,
                                                         const gchar *uri,
                                                         GError **error);

Removes the bookmark for uri from the bookmark file bookmark.

bookmark : | a GBookmarkFile
uri : | a valid URI
error : | return location for a GError, or NULL
Returns : | TRUE if the bookmark was removed successfully.

Since 2.12

g_bookmark_file_move_item ()

gboolean            g_bookmark_file_move_item           (GBookmarkFile *bookmark,
                                                         const gchar *old_uri,
                                                         const gchar *new_uri,
                                                         GError **error);

Changes the URI of a bookmark item from old_uri to new_uri. Any existing bookmark for new_uri will be overwritten. If new_uri is NULL, then the bookmark is removed.

In the event the URI cannot be found, FALSE is returned and error is set to G_BOOKMARK_FILE_ERROR_URI_NOT_FOUND.

bookmark : | a GBookmarkFile
old_uri : | a valid URI
new_uri : | a valid URI, or NULL
error : | return location for a GError or NULL
Returns : | TRUE if the URI was successfully changed

Since 2.12


Compiling the GLib package

Compiling the GLib Package — How to compile GLib itself

Building the Library on UNIX

On UNIX, GLib uses the standard GNU build system, using autoconf for package configuration and resolving portability issues, automake for building makefiles that comply with the GNU Coding Standards, and libtool for building shared libraries on multiple platforms. The normal sequence for compiling and installing the GLib library is thus:

./configure
make
make install

The standard options provided by GNU autoconf may be passed to the configure script. Please see the autoconf documentation or run ./configure --help for information about the standard options.

The GTK+ documentation contains further details about the build process and ways to influence it.

Dependencies

Before you can compile the GLib library, you need to have various other tools and libraries installed on your system. The two tools needed during the build process (as differentiated from the tools used in when creating GLib mentioned above such as autoconf) are pkg-config and GNU make.

  • pkg-config is a tool for tracking the compilation flags needed for libraries that are used by the GLib library. (For each library, a small .pc text file is installed in a standard location that contains the compilation flags needed for that library along with version number information.) The version of pkg-config needed to build GLib is mirrored in the dependencies directory on the GTK+ FTP site.

  • The GTK+ makefiles will mostly work with different versions of make, however, there tends to be a few incompatibilities, so the GTK+ team recommends installing GNU make if you don't already have it on your system and using it. (It may be called gmake rather than make.)

GLib depends on a number of other libraries.

  • The GNU libiconv library is needed to build GLib if your system doesn't have the iconv() function for doing conversion between character encodings. Most modern systems should have iconv(), however many older systems lack an iconv() implementation. On such systems, you must install the libiconv library. This can be found at: http://www.gnu.org/software/libiconv.

    If your system has an iconv() implementation but you want to use libiconv instead, you can pass the --with-libiconv option to configure. This forces libiconv to be used.

    Note that if you have libiconv installed in your default include search path (for instance, in /usr/local/), but don't enable it, you will get an error while compiling GLib because the iconv.h that libiconv installs hides the system iconv.

    If you are using the native iconv implementation on Solaris instead of libiconv, you'll need to make sure that you have the converters between locale encodings and UTF-8 installed. At a minimum you'll need the SUNWuiu8 package. You probably should also install the SUNWciu8, SUNWhiu8, SUNWjiu8, and SUNWkiu8 packages.

    The native iconv on Compaq Tru64 doesn't contain support for UTF-8, so you'll need to use GNU libiconv instead. (When using GNU libiconv for GLib, you'll need to use GNU libiconv for GNU gettext as well.) This probably applies to related operating systems as well.

  • The libintl library from the GNU gettext package is needed if your system doesn't have the gettext() functionality for handling message translation databases.

  • A thread implementation is needed, unless you want to compile GLib without thread support, which is not recommended. The thread support in GLib can be based upon several native thread implementations, e.g. POSIX threads, DCE threads or Solaris threads.

Extra Configuration Options

In addition to the normal options, the configure script in the GLib library supports these additional arguments:

configure [[--enable-debug=[no|minimum|yes]]] [[--disable-gc-friendly] | [--enable-gc-friendly]] [[--disable-mem-pools] | [--enable-mem-pools]] [[--disable-threads] | [--enable-threads]] [[--with-threads=[none|posix|dce|win32]]] [[--disable-included-printf] | [--enable-included-printf]] [[--disable-visibility] | [--enable-visibility]] [[--disable-gtk-doc] | [--enable-gtk-doc]] [[--disable-man] | [--enable-man]]

--enable-debug. Turns on various amounts of debugging support. Setting this to 'no' disables g_assert(), g_return_if_fail(), g_return_val_if_fail() and all cast checks between different object types. Setting it to 'minimum' disables only cast checks. Setting it to 'yes' enables runtime debugging. The default is 'minimum'. Note that 'no' is fast, but dangerous as it tends to destabilize even mostly bug-free software by changing the effect of many bugs from simple warnings into fatal crashes. Thus --enable-debug=no should not be used for stable releases of GLib.

--disable-gc-friendly and --enable-gc-friendly. By default, and with --disable-gc-friendly as well, Glib does not clear the memory for certain objects before they are freed. For example, Glib may decide to recycle GList nodes by putting them in a free list. However, memory profiling and debugging tools like Valgrind work better if an application does not keep dangling pointers to freed memory (even though these pointers are no longer dereferenced), or invalid pointers inside uninitialized memory. The --enable-gc-friendly option makes Glib clear memory in these situations:

  • When shrinking a GArray, Glib will clear the memory no longer available in the array: shrink an array from 10 bytes to 7, and the last 3 bytes will be cleared. This includes removals of single and multiple elements.

  • When growing a GArray, Glib will clear the new chunk of memory. Grow an array from 7 bytes to 10 bytes, and the last 3 bytes will be cleared.

  • The above applies to GPtrArray as well.

  • When freeing a node from a GHashTable, Glib will first clear the node, which used to have pointers to the key and the value stored at that node.

  • When destroying or removing a GTree node, Glib will clear the node, which used to have pointers to the node's value, and the left and right subnodes.

Since clearing the memory has a cost, --disable-gc-friendly is the default.

--disable-mem-pools and --enable-mem-pools. Many small chunks of memory are often allocated via collective pools in GLib and are cached after release to speed up reallocations. For sparse memory systems this behaviour is often inferior, so memory pools can be disabled to avoid excessive caching and force atomic maintenance of chunks through the g_malloc() and g_free() functions. Code currently affected by this:

  • GList, GSList,
GNode, GHash
allocations. The functions g_list_push_allocator(),
g_list_pop_allocator(), g_slist_push_allocator(),
g_slist_pop_allocator(), g_node_push_allocator() and
g_node_pop_allocator() are not available

  • GMemChunks become basically non-effective

  • GSignal disables all caching (potentially very slow)

  • GType doesn't honour the GTypeInfo n_preallocs field anymore

  • the GBSearchArray flag G_BSEARCH_ALIGN_POWER2 becomes non-functional

--disable-threads and --enable-threads. Do not compile GLib to be multi thread safe. GLib will be slightly faster then. This is however not recommended, as many programs rely on GLib being multi thread safe.

--with-threads. Specify a thread implementation to use.

  • 'posix' and 'dce' can be used interchangeable to mean the different versions of Posix threads. configure tries to find out, which one is installed.

  • 'none' means that GLib will be thread safe, but does not have a default thread implementation. This has to be supplied to g_thread_init() by the programmer.

--disable-included-printf and --enable-included-printf. By default the configure script will try to auto-detect whether the C library provides a suitable set of printf() functions. In detail, configure checks that the semantics of snprintf() are as specified by C99 and that positional parameters as specified in the Single Unix Specification are supported. If this not the case, GLib will include an implementation of the printf() family. These options can be used to explicitly control whether an implementation fo the printf() family should be included or not.

--disable-visibility and --enable-visibility. By default, GLib uses ELF visibility attributes to optimize PLT table entries if the compiler supports ELF visibility attributes. A side-effect of the way in which this is currently implemented is that any header change forces a full recompilation, and missing includes may go unnoticed. Therefore, it makes sense to turn this feature off while doing GLib development, even if the compiler supports ELF visibility attributes. The --disable-visibility option allows to do that.

--disable-gtk-doc and --enable-gtk-doc. By default the configure script will try to auto-detect whether the gtk-doc package is installed. If it is, then it will use it to extract and build the documentation for the GLib library. These options can be used to explicitly control whether gtk-doc should be used or not. If it is not used, the distributed, pre-generated HTML files will be installed instead of building them on your machine.

--disable-man and --enable-man. By default the configure script will try to auto-detect whether xsltproc and the necessary Docbook stylesheets are installed. If they are, then it will use them to rebuild the included man pages from the XML sources. These options can be used to explicitly control whether man pages should be rebuilt used or not. The distribution includes pre-generated man pages.


Byte Arrays

Byte Arrays — arrays of bytes, which grow automatically as elements are added.

Synopsis

#include <glib.h>

                    GByteArray;
GByteArray*         g_byte_array_new                    (void);
GByteArray*         g_byte_array_sized_new              (guint reserved_size);
GByteArray*         g_byte_array_append                 (GByteArray *array,
                                                         const guint8 *data,
                                                         guint len);
GByteArray*         g_byte_array_prepend                (GByteArray *array,
                                                         const guint8 *data,
                                                         guint len);
GByteArray*         g_byte_array_remove_index           (GByteArray *array,
                                                         guint index_);
GByteArray*         g_byte_array_remove_index_fast      (GByteArray *array,
                                                         guint index_);
GByteArray*         g_byte_array_remove_range           (GByteArray *array,
                                                         guint index_,
                                                         guint length);
void                g_byte_array_sort                   (GByteArray *array,
                                                         GCompareFunc compare_func);
void                g_byte_array_sort_with_data         (GByteArray *array,
                                                         GCompareDataFunc compare_func,
                                                         gpointer user_data);
GByteArray*         g_byte_array_set_size               (GByteArray *array,
                                                         guint length);
guint8*             g_byte_array_free                   (GByteArray *array,
                                                         gboolean free_segment);

Description

GByteArray is based on GArray, to provide arrays of bytes which grow automatically as elements are added.

To create a new GByteArray use g_byte_array_new().

To add elements to a GByteArray, use g_byte_array_append(), and g_byte_array_prepend().

To set the size of a GByteArray, use g_byte_array_set_size().

To free a GByteArray, use g_byte_array_free().

Example 24. Using a GByteArray

  GByteArray *gbarray;
  gint i;

  gbarray = g_byte_array_new ();
  for (i = 0; i < 10000; i++)
    g_byte_array_append (gbarray, (guint8*) "abcd", 4);

  for (i = 0; i < 10000; i++)
    {
      g_assert (gbarray->data[4*i] == 'a');
      g_assert (gbarray->data[4*i+1] == 'b');
      g_assert (gbarray->data[4*i+2] == 'c');
      g_assert (gbarray->data[4*i+3] == 'd');
    }

  g_byte_array_free (gbarray, TRUE);

Details

GByteArray

typedef struct {
  guint8 *data;
  guint	  len;
} GByteArray;

The GByteArray struct allows access to the public fields of a GByteArray.

guint8 *data; | a pointer to the element data. The data may be moved as elements are added to the GByteArray.
guint len; | the number of elements in the GByteArray.

g_byte_array_new ()

GByteArray*         g_byte_array_new                    (void);

Creates a new GByteArray.

Returns : the new GByteArray.

g_byte_array_sized_new ()

GByteArray*         g_byte_array_sized_new              (guint reserved_size);

Creates a new GByteArray with reserved_size bytes preallocated. This avoids frequent reallocation, if you are going to add many bytes to the array. Note however that the size of the array is still 0.

reserved_size : | number of bytes preallocated.
Returns : | the new GByteArray.

g_byte_array_append ()

GByteArray*         g_byte_array_append                 (GByteArray *array,
                                                         const guint8 *data,
                                                         guint len);

Adds the given bytes to the end of the GByteArray. The array will grow in size automatically if necessary.

array : | a GByteArray.
data : | the byte data to be added.
len : | the number of bytes to add.
Returns : | the GByteArray.

g_byte_array_prepend ()

GByteArray*         g_byte_array_prepend                (GByteArray *array,
                                                         const guint8 *data,
                                                         guint len);

Adds the given data to the start of the GByteArray. The array will grow in size automatically if necessary.

array : | a GByteArray.
data : | the byte data to be added.
len : | the number of bytes to add.
Returns : | the GByteArray.

g_byte_array_remove_index ()

GByteArray*         g_byte_array_remove_index           (GByteArray *array,
                                                         guint index_);

Removes the byte at the given index from a GByteArray. The following bytes are moved down one place.

array : | a GByteArray.
index_ : | the index of the byte to remove.
Returns : | the GByteArray.

g_byte_array_remove_index_fast ()

GByteArray*         g_byte_array_remove_index_fast      (GByteArray *array,
                                                         guint index_);

Removes the byte at the given index from a GByteArray. The last element in the array is used to fill in the space, so this function does not preserve the order of the GByteArray. But it is faster than g_byte_array_remove_index().

array : | a GByteArray.
index_ : | the index of the byte to remove.
Returns : | the GByteArray.

g_byte_array_remove_range ()

GByteArray*         g_byte_array_remove_range           (GByteArray *array,
                                                         guint index_,
                                                         guint length);

Removes the given number of bytes starting at the given index from a GByteArray. The following elements are moved to close the gap.

array : | a GByteArray.
index_ : | the index of the first byte to remove.
length : | the number of bytes to remove.
Returns : | the GByteArray.

Since 2.4

g_byte_array_sort ()

void                g_byte_array_sort                   (GByteArray *array,
                                                         GCompareFunc compare_func);

Sorts a byte array, using compare_func which should be a qsort()-style comparison function (returns less than zero for first arg is less than second arg, zero for equal, greater than zero if first arg is greater than second arg).

If two array elements compare equal, their order in the sorted array is undefined.

array : | a GByteArray.
compare_func : | comparison function.

g_byte_array_sort_with_data ()

void                g_byte_array_sort_with_data         (GByteArray *array,
                                                         GCompareDataFunc compare_func,
                                                         gpointer user_data);

Like g_byte_array_sort(), but the comparison function takes an extra user data argument.

array : | a GByteArray.
compare_func : | comparison function.
user_data : | data to pass to compare_func.

g_byte_array_set_size ()

GByteArray*         g_byte_array_set_size               (GByteArray *array,
                                                         guint length);

Sets the size of the GByteArray, expanding it if necessary.

array : | a GByteArray.
length : | the new size of the GByteArray.
Returns : | the GByteArray.

g_byte_array_free ()

guint8*             g_byte_array_free                   (GByteArray *array,
                                                         gboolean free_segment);

Frees the memory allocated by the GByteArray. If free_segment is TRUE it frees the actual byte data.

array : | a GByteArray.
free_segment : | if TRUE the actual byte data is freed as well.
Returns : | the element data if free_segment is FALSE, otherwise NULL


Byte Order Macros

Byte Order Macros — a portable way to convert between different byte orders.

Synopsis

#include <glib.h>

#define             G_BYTE_ORDER
#define             G_LITTLE_ENDIAN
#define             G_BIG_ENDIAN
#define             G_PDP_ENDIAN

#define             g_htonl                             (val)
#define             g_htons                             (val)
#define             g_ntohl                             (val)
#define             g_ntohs                             (val)

#define             GINT_FROM_BE                        (val)
#define             GINT_FROM_LE                        (val)
#define             GINT_TO_BE                          (val)
#define             GINT_TO_LE                          (val)

#define             GUINT_FROM_BE                       (val)
#define             GUINT_FROM_LE                       (val)
#define             GUINT_TO_BE                         (val)
#define             GUINT_TO_LE                         (val)

#define             GLONG_FROM_BE                       (val)
#define             GLONG_FROM_LE                       (val)
#define             GLONG_TO_BE                         (val)
#define             GLONG_TO_LE                         (val)

#define             GULONG_FROM_BE                      (val)
#define             GULONG_FROM_LE                      (val)
#define             GULONG_TO_BE                        (val)
#define             GULONG_TO_LE                        (val)

#define             GINT16_FROM_BE                      (val)
#define             GINT16_FROM_LE                      (val)
#define             GINT16_TO_BE                        (val)
#define             GINT16_TO_LE                        (val)

#define             GUINT16_FROM_BE                     (val)
#define             GUINT16_FROM_LE                     (val)
#define             GUINT16_TO_BE                       (val)
#define             GUINT16_TO_LE                       (val)

#define             GINT32_FROM_BE                      (val)
#define             GINT32_FROM_LE                      (val)
#define             GINT32_TO_BE                        (val)
#define             GINT32_TO_LE                        (val)

#define             GUINT32_FROM_BE                     (val)
#define             GUINT32_FROM_LE                     (val)
#define             GUINT32_TO_BE                       (val)
#define             GUINT32_TO_LE                       (val)

#define             GINT64_FROM_BE                      (val)
#define             GINT64_FROM_LE                      (val)
#define             GINT64_TO_BE                        (val)
#define             GINT64_TO_LE                        (val)

#define             GUINT64_FROM_BE                     (val)
#define             GUINT64_FROM_LE                     (val)
#define             GUINT64_TO_BE                       (val)
#define             GUINT64_TO_LE                       (val)

#define             GUINT16_SWAP_BE_PDP                 (val)
#define             GUINT16_SWAP_LE_BE                  (val)
#define             GUINT16_SWAP_LE_PDP                 (val)

#define             GUINT32_SWAP_BE_PDP                 (val)
#define             GUINT32_SWAP_LE_BE                  (val)
#define             GUINT32_SWAP_LE_PDP                 (val)

#define             GUINT64_SWAP_LE_BE                  (val)

Description

These macros provide a portable way to determine the host byte order and to convert values between different byte orders.

The byte order is the order in which bytes are stored to create larger data types such as the gint and glong values. The host byte order is the byte order used on the current machine.

Some processors store the most significant bytes (i.e. the bytes that hold the largest part of the value) first. These are known as big-endian processors.

Other processors (notably the x86 family) store the most significant byte last. These are known as little-endian processors.

Finally, to complicate matters, some other processors store the bytes in a rather curious order known as PDP-endian. For a 4-byte word, the 3rd most significant byte is stored first, then the 4th, then the 1st and finally the 2nd.

Obviously there is a problem when these different processors communicate with each other, for example over networks or by using binary file formats. This is where these macros come in. They are typically used to convert values into a byte order which has been agreed on for use when communicating between different processors. The Internet uses what is known as 'network byte order' as the standard byte order (which is in fact the big-endian byte order).

Note that the byte order conversion macros may evaluate their arguments multiple times, thus you should not use them with arguments which have side-effects.

Details

G_BYTE_ORDER

#define G_BYTE_ORDER G_LITTLE_ENDIAN

The host byte order. This can be either G_LITTLE_ENDIAN or G_BIG_ENDIAN (support for G_PDP_ENDIAN may be added in future.)

G_LITTLE_ENDIAN

#define G_LITTLE_ENDIAN 1234

Specifies one of the possible types of byte order. See G_BYTE_ORDER.

G_BIG_ENDIAN

#define G_BIG_ENDIAN    4321

Specifies one of the possible types of byte order. See G_BYTE_ORDER.

G_PDP_ENDIAN

#define G_PDP_ENDIAN    3412		/* unused, need specific PDP check */

Specifies one of the possible types of byte order (currently unused). See G_BYTE_ORDER.

g_htonl()

#define             g_htonl(val)

Converts a 32-bit integer value from host to network byte order.

val : | a 32-bit integer value in host byte order.
Returns : | val converted to network byte order.

g_htons()

#define             g_htons(val)

Converts a 16-bit integer value from host to network byte order.

val : | a 16-bit integer value in host byte order.
Returns : | val converted to network byte order.

g_ntohl()

#define             g_ntohl(val)

Converts a 32-bit integer value from network to host byte order.

val : | a 32-bit integer value in network byte order.
Returns : | val converted to host byte order.

g_ntohs()

#define             g_ntohs(val)

Converts a 16-bit integer value from network to host byte order.

val : | a 16-bit integer value in network byte order.
Returns : | val converted to host byte order.

GINT_FROM_BE()

#define GINT_FROM_BE(val)	(GINT_TO_BE (val))

Converts a gint value from big-endian to host byte order.

val : | a gint value in big-endian byte order.
Returns : | val converted to host byte order.

GINT_FROM_LE()

#define GINT_FROM_LE(val)	(GINT_TO_LE (val))

Converts a gint value from little-endian to host byte order.

val : | a gint value in little-endian byte order.
Returns : | val converted to host byte order.

GINT_TO_BE()

#define GINT_TO_BE(val)		((gint) GINT32_TO_BE (val))

Converts a gint value from host byte order to big-endian.

val : | a gint value in host byte order.
Returns : | val converted to big-endian byte order.

GINT_TO_LE()

#define GINT_TO_LE(val)		((gint) GINT32_TO_LE (val))

Converts a gint value from host byte order to little-endian.

val : | a gint value in host byte order.
Returns : | val converted to little-endian byte order.

GUINT_FROM_BE()

#define GUINT_FROM_BE(val)	(GUINT_TO_BE (val))

Converts a guint value from big-endian to host byte order.

val : | a guint value in big-endian byte order.
Returns : | val converted to host byte order.

GUINT_FROM_LE()

#define GUINT_FROM_LE(val)	(GUINT_TO_LE (val))

Converts a guint value from little-endian to host byte order.

val : | a guint value in little-endian byte order.
Returns : | val converted to host byte order.

GUINT_TO_BE()

#define GUINT_TO_BE(val)	((guint) GUINT32_TO_BE (val))

Converts a guint value from host byte order to big-endian.

val : | a guint value in host byte order.
Returns : | val converted to big-endian byte order.

GUINT_TO_LE()

#define GUINT_TO_LE(val)	((guint) GUINT32_TO_LE (val))

Converts a guint value from host byte order to little-endian.

val : | a guint value in host byte order.
Returns : | val converted to little-endian byte order.

GLONG_FROM_BE()

#define GLONG_FROM_BE(val)	(GLONG_TO_BE (val))

Converts a glong value from big-endian to the host byte order.

val : | a glong value in big-endian byte order.
Returns : | val converted to host byte order.

GLONG_FROM_LE()

#define GLONG_FROM_LE(val)	(GLONG_TO_LE (val))

Converts a glong value from little-endian to host byte order.

val : | a glong value in little-endian byte order.
Returns : | val converted to host byte order.

GLONG_TO_BE()

#define GLONG_TO_BE(val)	((glong) GINT32_TO_BE (val))

Converts a glong value from host byte order to big-endian.

val : | a glong value in host byte order.
Returns : | val converted to big-endian byte order.

GLONG_TO_LE()

#define GLONG_TO_LE(val)	((glong) GINT32_TO_LE (val))

Converts a glong value from host byte order to little-endian.

val : | a glong value in host byte order.
Returns : | val converted to little-endian.

GULONG_FROM_BE()

#define GULONG_FROM_BE(val)	(GULONG_TO_BE (val))

Converts a gulong value from big-endian to host byte order.

val : | a gulong value in big-endian byte order.
Returns : | val converted to host byte order.

GULONG_FROM_LE()

#define GULONG_FROM_LE(val)	(GULONG_TO_LE (val))

Converts a gulong value from little-endian to host byte order.

val : | a gulong value in little-endian byte order.
Returns : | val converted to host byte order.

GULONG_TO_BE()

#define GULONG_TO_BE(val)	((gulong) GUINT32_TO_BE (val))

Converts a gulong value from host byte order to big-endian.

val : | a gulong value in host byte order.
Returns : | val converted to big-endian.

GULONG_TO_LE()

#define GULONG_TO_LE(val)	((gulong) GUINT32_TO_LE (val))

Converts a gulong value from host byte order to little-endian.

val : | a gulong value in host byte order.
Returns : | val converted to little-endian.

GINT16_FROM_BE()

#define GINT16_FROM_BE(val)	(GINT16_TO_BE (val))

Converts a gint16 value from big-endian to host byte order.

val : | a gint16 value in big-endian byte order.
Returns : | val converted to host byte order.

GINT16_FROM_LE()

#define GINT16_FROM_LE(val)	(GINT16_TO_LE (val))

Converts a gint16 value from little-endian to host byte order.

val : | a gint16 value in little-endian byte order.
Returns : | val converted to host byte order.

GINT16_TO_BE()

#define GINT16_TO_BE(val)	((gint16) GUINT16_SWAP_LE_BE (val))

Converts a gint16 value from host byte order to big-endian.

val : | a gint16 value in host byte order.
Returns : | val converted to big-endian.

GINT16_TO_LE()

#define GINT16_TO_LE(val)	((gint16) (val))

Converts a gint16 value from host byte order to little-endian.

val : | a gint16 value in host byte order.
Returns : | val converted to little-endian.

GUINT16_FROM_BE()

#define GUINT16_FROM_BE(val)	(GUINT16_TO_BE (val))

Converts a guint16 value from big-endian to host byte order.

val : | a guint16 value in big-endian byte order.
Returns : | val converted to host byte order.

GUINT16_FROM_LE()

#define GUINT16_FROM_LE(val)	(GUINT16_TO_LE (val))

Converts a guint16 value from little-endian to host byte order.

val : | a guint16 value in little-endian byte order.
Returns : | val converted to host byte order.

GUINT16_TO_BE()

#define GUINT16_TO_BE(val)	(GUINT16_SWAP_LE_BE (val))

Converts a guint16 value from host byte order to big-endian.

val : | a guint16 value in host byte order.
Returns : | val converted to big-endian.

GUINT16_TO_LE()

#define GUINT16_TO_LE(val)	((guint16) (val))

Converts a guint16 value from host byte order to little-endian.

val : | a guint16 value in host byte order.
Returns : | val converted to little-endian.

GINT32_FROM_BE()

#define GINT32_FROM_BE(val)	(GINT32_TO_BE (val))

Converts a gint32 value from big-endian to host byte order.

val : | a gint32 value in big-endian byte order.
Returns : | val converted to host byte order.

GINT32_FROM_LE()

#define GINT32_FROM_LE(val)	(GINT32_TO_LE (val))

Converts a gint32 value from little-endian to host byte order.

val : | a gint32 value in little-endian byte order.
Returns : | val converted to host byte order.

GINT32_TO_BE()

#define GINT32_TO_BE(val)	((gint32) GUINT32_SWAP_LE_BE (val))

Converts a gint32 value from host byte order to big-endian.

val : | a gint32 value in host byte order.
Returns : | val converted to big-endian.

GINT32_TO_LE()

#define GINT32_TO_LE(val)	((gint32) (val))

Converts a gint32 value from host byte order to little-endian.

val : | a gint32 value in host byte order.
Returns : | val converted to little-endian.

GUINT32_FROM_BE()

#define GUINT32_FROM_BE(val)	(GUINT32_TO_BE (val))

Converts a guint32 value from big-endian to host byte order.

val : | a guint32 value in big-endian byte order.
Returns : | val converted to host byte order.

GUINT32_FROM_LE()

#define GUINT32_FROM_LE(val)	(GUINT32_TO_LE (val))

Converts a guint32 value from little-endian to host byte order.

val : | a guint32 value in little-endian byte order.
Returns : | val converted to host byte order.

GUINT32_TO_BE()

#define GUINT32_TO_BE(val)	(GUINT32_SWAP_LE_BE (val))

Converts a guint32 value from host byte order to big-endian.

val : | a guint32 value in host byte order.
Returns : | val converted to big-endian.

GUINT32_TO_LE()

#define GUINT32_TO_LE(val)	((guint32) (val))

Converts a guint32 value from host byte order to little-endian.

val : | a guint32 value in host byte order.
Returns : | val converted to little-endian.

GINT64_FROM_BE()

#define GINT64_FROM_BE(val)	(GINT64_TO_BE (val))

Converts a gint64 value from big-endian to host byte order.

val : | a gint64 value in big-endian byte order.
Returns : | val converted to host byte order.

GINT64_FROM_LE()

#define GINT64_FROM_LE(val)	(GINT64_TO_LE (val))

Converts a gint64 value from little-endian to host byte order.

val : | a gint64 value in little-endian byte order.
Returns : | val converted to host byte order.

GINT64_TO_BE()

#define GINT64_TO_BE(val)	((gint64) GUINT64_SWAP_LE_BE (val))

Converts a gint64 value from host byte order to big-endian.

val : | a gint64 value in host byte order.
Returns : | val converted to big-endian.

GINT64_TO_LE()

#define GINT64_TO_LE(val)	((gint64) (val))

Converts a gint64 value from host byte order to little-endian.

val : | a gint64 value in host byte order.
Returns : | val converted to little-endian.

GUINT64_FROM_BE()

#define GUINT64_FROM_BE(val)	(GUINT64_TO_BE (val))

Converts a guint64 value from big-endian to host byte order.

val : | a guint64 value in big-endian byte order.
Returns : | val converted to host byte order.

GUINT64_FROM_LE()

#define GUINT64_FROM_LE(val)	(GUINT64_TO_LE (val))

Converts a guint64 value from little-endian to host byte order.

val : | a guint64 value in little-endian byte order.
Returns : | val converted to host byte order.

GUINT64_TO_BE()

#define GUINT64_TO_BE(val)	(GUINT64_SWAP_LE_BE (val))

Converts a guint64 value from host byte order to big-endian.

val : | a guint64 value in host byte order.
Returns : | val converted to big-endian.

GUINT64_TO_LE()

#define GUINT64_TO_LE(val)	((guint64) (val))

Converts a guint64 value from host byte order to little-endian.

val : | a guint64 value in host byte order.
Returns : | val converted to little-endian.

GUINT16_SWAP_BE_PDP()

#define GUINT16_SWAP_BE_PDP(val)	(GUINT16_SWAP_LE_BE (val))

Converts a guint16 value between big-endian and pdp-endian byte order. The conversion is symmetric so it can be used both ways.

val : | a guint16 value in big-endian or pdp-endian byte order.
Returns : | val converted to the opposite byte order.

GUINT16_SWAP_LE_BE()

#define             GUINT16_SWAP_LE_BE(val)

Converts a guint16 value between little-endian and big-endian byte order. The conversion is symmetric so it can be used both ways.

val : | a guint16 value in little-endian or big-endian byte order.
Returns : | val converted to the opposite byte order.

GUINT16_SWAP_LE_PDP()

#define GUINT16_SWAP_LE_PDP(val)	((guint16) (val))

Converts a guint16 value between little-endian and pdp-endian byte order. The conversion is symmetric so it can be used both ways.

val : | a guint16 value in little-endian or pdp-endian byte order.
Returns : | val converted to the opposite byte order.

GUINT32_SWAP_BE_PDP()

#define             GUINT32_SWAP_BE_PDP(val)

Converts a guint32 value between big-endian and pdp-endian byte order. The conversion is symmetric so it can be used both ways.

val : | a guint32 value in big-endian or pdp-endian byte order.
Returns : | val converted to the opposite byte order.

GUINT32_SWAP_LE_BE()

#define             GUINT32_SWAP_LE_BE(val)

Converts a guint32 value between little-endian and big-endian byte order. The conversion is symmetric so it can be used both ways.

val : | a guint32 value in little-endian or big-endian byte order.
Returns : | val converted to the opposite byte order.

GUINT32_SWAP_LE_PDP()

#define             GUINT32_SWAP_LE_PDP(val)

Converts a guint32 value between little-endian and pdp-endian byte order. The conversion is symmetric so it can be used both ways.

val : | a guint32 value in little-endian or pdp-endian byte order.
Returns : | val converted to the opposite byte order.

GUINT64_SWAP_LE_BE()

#define             GUINT64_SWAP_LE_BE(val)

Converts a guint64 value between little-endian and big-endian byte order. The conversion is symmetric so it can be used both ways.

val : | a guint64 value in little-endian or big-endian byte order.
Returns : | val converted to the opposite byte order.


Caches

Caches — caches allow sharing of complex data structures to save resources.

Synopsis

#include <glib.h>

                    GCache;
GCache*             g_cache_new                         (GCacheNewFunc value_new_func,
                                                         GCacheDestroyFunc value_destroy_func,
                                                         GCacheDupFunc key_dup_func,
                                                         GCacheDestroyFunc key_destroy_func,
                                                         GHashFunc hash_key_func,
                                                         GHashFunc hash_value_func,
                                                         GEqualFunc key_equal_func);
gpointer            g_cache_insert                      (GCache *cache,
                                                         gpointer key);
void                g_cache_remove                      (GCache *cache,
                                                         gconstpointer value);
void                g_cache_destroy                     (GCache *cache);

void                g_cache_key_foreach                 (GCache *cache,
                                                         GHFunc func,
                                                         gpointer user_data);
void                g_cache_value_foreach               (GCache *cache,
                                                         GHFunc func,
                                                         gpointer user_data);

void                (*GCacheDestroyFunc)                (gpointer value);
gpointer            (*GCacheDupFunc)                    (gpointer value);
gpointer            (*GCacheNewFunc)                    (gpointer key);

Description

A GCache allows sharing of complex data structures, in order to save system resources.

GTK+ uses caches for GtkStyles and GdkGCs. These consume a lot of resources, so a GCache is used to see if a GtkStyle or GdkGC with the required properties already exists. If it does, then the existing object is used instead of creating a new one.

GCache uses keys and values. A GCache key describes the properties of a particular resource. A GCache value is the actual resource.

Details

GCache

typedef struct _GCache GCache;

The GCache struct is an opaque data structure containing information about a GCache. It should only be accessed via the following functions.

g_cache_new ()

GCache*             g_cache_new                         (GCacheNewFunc value_new_func,
                                                         GCacheDestroyFunc value_destroy_func,
                                                         GCacheDupFunc key_dup_func,
                                                         GCacheDestroyFunc key_destroy_func,
                                                         GHashFunc hash_key_func,
                                                         GHashFunc hash_value_func,
                                                         GEqualFunc key_equal_func);

Creates a new GCache.

value_new_func : | a function to create a new object given a key. This is called by g_cache_insert() if an object with the given key does not already exist.
value_destroy_func : | a function to destroy an object. It is called by g_cache_remove() when the object is no longer needed (i.e. its reference count drops to 0).
key_dup_func : | a function to copy a key. It is called by g_cache_insert() if the key does not already exist in the GCache.
key_destroy_func : | a function to destroy a key. It is called by g_cache_remove() when the object is no longer needed (i.e. its reference count drops to 0).
hash_key_func : | a function to create a hash value from a key.
hash_value_func : | a function to create a hash value from a value.
key_equal_func : | a function to compare two keys. It should return TRUE if the two keys are equivalent.
Returns : | a new GCache.

g_cache_insert ()

gpointer            g_cache_insert                      (GCache *cache,
                                                         gpointer key);

Gets the value corresponding to the given key, creating it if necessary. It first checks if the value already exists in the GCache, by using the key_equal_func function passed to g_cache_new(). If it does already exist it is returned, and its reference count is increased by one. If the value does not currently exist, if is created by calling the value_new_func. The key is duplicated by calling key_dup_func and the duplicated key and value are inserted into the GCache.

cache : | a GCache.
key : | a key describing a GCache object.
Returns : | a pointer to a GCache value.

g_cache_remove ()

void                g_cache_remove                      (GCache *cache,
                                                         gconstpointer value);

Decreases the reference count of the given value. If it drops to 0 then the value and its corresponding key are destroyed, using the value_destroy_func and key_destroy_func passed to g_cache_new().

cache : | a GCache.
value : | the value to remove.

g_cache_destroy ()

void                g_cache_destroy                     (GCache *cache);

Frees the memory allocated for the GCache.

Note that it does not destroy the keys and values which were contained in the GCache.

cache : a GCache.

g_cache_key_foreach ()

void                g_cache_key_foreach                 (GCache *cache,
                                                         GHFunc func,
                                                         gpointer user_data);

Calls the given function for each of the keys in the GCache.

Note

func is passed three parameters, the value and key of a cache entry and the user_data. The order of value and key is different from the order in which g_hash_table_foreach() passes key-value pairs to its callback function !

cache : | a GCache.
func : | the function to call with each GCache key.
user_data : | user data to pass to the function.

g_cache_value_foreach ()

void                g_cache_value_foreach               (GCache *cache,
                                                         GHFunc func,
                                                         gpointer user_data);

Warning

g_cache_value_foreach has been deprecated since version 2.10 and should not be used in newly-written code. The reason is that it passes pointers to internal data structures to func; use g_cache_key_foreach() instead

Calls the given function for each of the values in the GCache.

cache : | a GCache.
func : | the function to call with each GCache value.
user_data : | user data to pass to the function.

GCacheDestroyFunc ()

void                (*GCacheDestroyFunc)                (gpointer value);

Specifies the type of the value_destroy_func and key_destroy_func functions passed to g_cache_new(). The functions are passed a pointer to the GCache key or GCache value and should free any memory and other resources associated with it.

value : the GCache value to destroy.

GCacheDupFunc ()

gpointer            (*GCacheDupFunc)                    (gpointer value);

Specifies the type of the key_dup_func function passed to g_cache_new(). The function is passed a key (not a value as the prototype implies) and should return a duplicate of the key.

value : | the GCache key to destroy (not a GCache value as it seems).
Returns : | a copy of the GCache key.

GCacheNewFunc ()

gpointer            (*GCacheNewFunc)                    (gpointer key);

Specifies the type of the value_new_func function passed to g_cache_new(). It is passed a GCache key and should create the value corresponding to the key.

key : | a GCache key.
Returns : | a new GCache value corresponding to the key.


Changes to GLib

Changes to GLib — Incompatible changes made between successing versions of GLib

Incompatible changes from 2.0 to 2.2

  • GLib changed the seeding algorithm for the pseudo-random number generator Mersenne Twister, as used by GRand and GRandom. This was necessary, because some seeds would yield very bad pseudo-random streams. Also the pseudo-random integers generated by g_rand*_int_range() will have a slightly better equal distribution with the new version of GLib.

    Further information can be found at the website of the Mersenne Twister random number generator at http://www.math.keio.ac.jp/~matumoto/emt.html.

    The original seeding and generation algorithms, as found in GLib 2.0.x, can be used instead of the new ones by setting the environment variable G_RANDOM_VERSION to the value of '2.0'. Use the GLib-2.0 algorithms only if you have sequences of numbers generated with Glib-2.0 that you need to reproduce exactly.

Incompatible changes from 1.2 to 2.0

The GNOME 2.0 porting guide on http://developer.gnome.org has some more detailed discussion of porting from 1.2 to 2.0. See the section on GLib.

  • The event loop functionality GMain has extensively been revised to support multiple separate main loops in separate threads. All sources (timeouts, idle functions, etc.) are associated with a GMainContext.

    Compatibility functions exist so that most application code dealing with the main loop will continue to work. However, code that creates new custom types of sources will require modification.

    The main changes here are:

    • Sources are now exposed as GSource *, rather than simply as numeric ids.

    • New types of sources are created by structure "derivation" from GSource, so the source_data parameter to the GSource virtual functions has been replaced with a GSource *.

    • Sources are first created, then later added to a specific GMainContext.

    • Dispatching has been modified so both the callback and data are passed in to the dispatch() virtual function.

    To go along with this change, the vtable for GIOChannel has changed and add_watch() has been replaced by create_watch().

  • g_list_foreach() and g_slist_foreach() have been changed so they are now safe against removal of the current item, not the next item.

    It's not recommended to mutate the list in the callback to these functions in any case.

  • GDate now works in UTF-8, not in the current locale. If you want to use it with the encoding of the locale, you need to convert strings using g_locale_to_utf8() first.

  • g_strsplit() has been fixed to:

    • include trailing empty tokens, rather than stripping them

    • split into a maximum of max_tokens tokens, rather than max_tokens + 1

    Code depending on either of these bugs will need to be fixed.

  • Deprecated functions that got removed:
g_set_error_handler(),
g_set_warning_handler(),
g_set_message_handler(), use
g_log_set_handler() instead.


Character Set Conversion

Character Set Conversion — convert strings between different character sets using iconv().

Synopsis

#include <glib.h>

gchar*              g_convert                           (const gchar *str,
                                                         gssize len,
                                                         const gchar *to_codeset,
                                                         const gchar *from_codeset,
                                                         gsize *bytes_read,
                                                         gsize *bytes_written,
                                                         GError **error);
gchar*              g_convert_with_fallback             (const gchar *str,
                                                         gssize len,
                                                         const gchar *to_codeset,
                                                         const gchar *from_codeset,
                                                         gchar *fallback,
                                                         gsize *bytes_read,
                                                         gsize *bytes_written,
                                                         GError **error);
                    GIConv;
gchar*              g_convert_with_iconv                (const gchar *str,
                                                         gssize len,
                                                         GIConv converter,
                                                         gsize *bytes_read,
                                                         gsize *bytes_written,
                                                         GError **error);
#define             G_CONVERT_ERROR
GIConv              g_iconv_open                        (const gchar *to_codeset,
                                                         const gchar *from_codeset);
size_t              g_iconv                             (GIConv converter,
                                                         gchar **inbuf,
                                                         gsize *inbytes_left,
                                                         gchar **outbuf,
                                                         gsize *outbytes_left);
gint                g_iconv_close                       (GIConv converter);
gchar*              g_locale_to_utf8                    (const gchar *opsysstring,
                                                         gssize len,
                                                         gsize *bytes_read,
                                                         gsize *bytes_written,
                                                         GError **error);
gchar*              g_filename_to_utf8                  (const gchar *opsysstring,
                                                         gssize len,
                                                         gsize *bytes_read,
                                                         gsize *bytes_written,
                                                         GError **error);
gchar*              g_filename_from_utf8                (const gchar *utf8string,
                                                         gssize len,
                                                         gsize *bytes_read,
                                                         gsize *bytes_written,
                                                         GError **error);
gchar*              g_filename_from_uri                 (const gchar *uri,
                                                         gchar **hostname,
                                                         GError **error);
gchar*              g_filename_to_uri                   (const gchar *filename,
                                                         const gchar *hostname,
                                                         GError **error);
gboolean            g_get_filename_charsets             (G_CONST_RETURN gchar ***charsets);
gchar*              g_filename_display_name             (const gchar *filename);
gchar*              g_filename_display_basename         (const gchar *filename);
gchar**             g_uri_list_extract_uris             (const gchar *uri_list);
gchar*              g_locale_from_utf8                  (const gchar *utf8string,
                                                         gssize len,
                                                         gsize *bytes_read,
                                                         gsize *bytes_written,
                                                         GError **error);
enum                GConvertError;

gboolean            g_get_charset                       (G_CONST_RETURN char **charset);

Description

File Name Encodings

Historically, Unix has not had a defined encoding for file names: a file name is valid as long as it does not have path separators in it ("/"). However, displaying file names may require conversion: from the character set in which they were created, to the character set in which the application operates. Consider the Spanish file name "Presentación.sxi". If the application which created it uses ISO-8859-1 for its encoding, then the actual file name on disk would look like this:

Character:  P  r  e  s  e  n  t  a  c  i  ó  n  .  s  x  i
Hex code:   50 72 65 73 65 6e 74 61 63 69 f3 6e 2e 73 78 69

However, if the application use UTF-8, the actual file name on disk would look like this:

Character:  P  r  e  s  e  n  t  a  c  i  ó     n  .  s  x  i
Hex code:   50 72 65 73 65 6e 74 61 63 69 c3 b3 6e 2e 73 78 69

Glib uses UTF-8 for its strings, and GUI toolkits like GTK+ that use Glib do the same thing. If you get a file name from the file system, for example, from readdir(3) or from g_dir_read_name(), and you wish to display the file name to the user, you will need to convert it into UTF-8. The opposite case is when the user types the name of a file he wishes to save: the toolkit will give you that string in UTF-8 encoding, and you will need to convert it to the character set used for file names before you can create the file with open(2) or fopen(3).

By default, Glib assumes that file names on disk are in UTF-8 encoding. This is a valid assumption for file systems which were created relatively recently: most applications use UTF-8 encoding for their strings, and that is also what they use for the file names they create. However, older file systems may still contain file names created in "older" encodings, such as ISO-8859-1. In this case, for compatibility reasons, you may want to instruct Glib to use that particular encoding for file names rather than UTF-8. You can do this by specifying the encoding for file names in the G_FILENAME_ENCODING environment variable. For example, if your installation uses ISO-8859-1 for file names, you can put this in your ~/.profile:

export G_FILENAME_ENCODING=ISO-8859-1

Glib provides the functions g_filename_to_utf8() and g_filename_from_utf8() to perform the necessary conversions. These functions convert file names from the encoding specified in G_FILENAME_ENCODING to UTF-8 and vice-versa. Figure 2, “Conversion between File Name Encodings” illustrates how these functions are used to convert between UTF-8 and the encoding for file names in the file system.

Figure 2. Conversion between File Name Encodings

Conversion between File Name Encodings

Checklist for Application Writers

This section is a practical summary of the detailed description above. You can use this as a checklist of things to do to make sure your applications process file name encodings correctly.

  1. If you get a file name from the file system from a
function such as readdir(3) or
gtk_file_chooser_get_filename(),
you do not need to do any conversion to pass that
file name to functions like open(2),
rename(2), or
fopen(3) — those are "raw"
file names which the file system understands.

  2. If you need to display a file name, convert it to UTF-8 first by using g_filename_to_utf8(). If conversion fails, display a string like "Unknown file name". Do not convert this string back into the encoding used for file names if you wish to pass it to the file system; use the original file name instead. For example, the document window of a word processor could display "Unknown file name" in its title bar but still let the user save the file, as it would keep the raw file name internally. This can happen if the user has not set the G_FILENAME_ENCODING environment variable even though he has files whose names are not encoded in UTF-8.

  3. If your user interface lets the user type a file name for saving or renaming, convert it to the encoding used for file names in the file system by using g_filename_from_utf8(). Pass the converted file name to functions like fopen(3). If conversion fails, ask the user to enter a different file name. This can happen if the user types Japanese characters when G_FILENAME_ENCODING is set to ISO-8859-1, for example.

Details

g_convert ()

gchar*              g_convert                           (const gchar *str,
                                                         gssize len,
                                                         const gchar *to_codeset,
                                                         const gchar *from_codeset,
                                                         gsize *bytes_read,
                                                         gsize *bytes_written,
                                                         GError **error);

Converts a string from one character set to another.

Note that you should use g_iconv() for streaming conversions[2].

str : | the string to convert
len : | the length of the string, or -1 if the string is nul-terminated[1].
to_codeset : | name of character set into which to convert str
from_codeset : | character set of str.
bytes_read : | location to store the number of bytes in the input string that were successfully converted, or NULL. Even if the conversion was successful, this may be less than len if there were partial characters at the end of the input. If the error G_CONVERT_ERROR_ILLEGAL_SEQUENCE occurs, the value stored will the byte offset after the last valid input sequence.
bytes_written : | the number of bytes stored in the output buffer (not including the terminating nul).
error : | location to store the error occuring, or NULL to ignore errors. Any of the errors in GConvertError may occur.
Returns : | If the conversion was successful, a newly allocated nul-terminated string, which must be freed with g_free(). Otherwise NULL and error will be set.

g_convert_with_fallback ()

gchar*              g_convert_with_fallback             (const gchar *str,
                                                         gssize len,
                                                         const gchar *to_codeset,
                                                         const gchar *from_codeset,
                                                         gchar *fallback,
                                                         gsize *bytes_read,
                                                         gsize *bytes_written,
                                                         GError **error);

Converts a string from one character set to another, possibly including fallback sequences for characters not representable in the output. Note that it is not guaranteed that the specification for the fallback sequences in fallback will be honored. Some systems may do a approximate conversion from from_codeset to to_codeset in their iconv() functions, in which case GLib will simply return that approximate conversion.

Note that you should use g_iconv() for streaming conversions[2].

str : | the string to convert
len : | the length of the string, or -1 if the string is nul-terminated[1].
to_codeset : | name of character set into which to convert str
from_codeset : | character set of str.
fallback : | UTF-8 string to use in place of character not present in the target encoding. (The string must be representable in the target encoding). If NULL, characters not in the target encoding will be represented as Unicode escapes \uxxxx or \Uxxxxyyyy.
bytes_read : | location to store the number of bytes in the input string that were successfully converted, or NULL. Even if the conversion was successful, this may be less than len if there were partial characters at the end of the input.
bytes_written : | the number of bytes stored in the output buffer (not including the terminating nul).
error : | location to store the error occuring, or NULL to ignore errors. Any of the errors in GConvertError may occur.
Returns : | If the conversion was successful, a newly allocated nul-terminated string, which must be freed with g_free(). Otherwise NULL and error will be set.

GIConv

typedef struct _GIConv GIConv;

The GIConv struct wraps an iconv() conversion descriptor. It contains private data and should only be accessed using the following functions.

g_convert_with_iconv ()

gchar*              g_convert_with_iconv                (const gchar *str,
                                                         gssize len,
                                                         GIConv converter,
                                                         gsize *bytes_read,
                                                         gsize *bytes_written,
                                                         GError **error);

Converts a string from one character set to another.

Note that you should use g_iconv() for streaming conversions[2].

str : | the string to convert
len : | the length of the string, or -1 if the string is nul-terminated[1].
converter : | conversion descriptor from g_iconv_open()
bytes_read : | location to store the number of bytes in the input string that were successfully converted, or NULL. Even if the conversion was successful, this may be less than len if there were partial characters at the end of the input. If the error G_CONVERT_ERROR_ILLEGAL_SEQUENCE occurs, the value stored will the byte offset after the last valid input sequence.
bytes_written : | the number of bytes stored in the output buffer (not including the terminating nul).
error : | location to store the error occuring, or NULL to ignore errors. Any of the errors in GConvertError may occur.
Returns : | If the conversion was successful, a newly allocated nul-terminated string, which must be freed with g_free(). Otherwise NULL and error will be set.

G_CONVERT_ERROR

#define G_CONVERT_ERROR g_convert_error_quark()

Error domain for character set conversions. Errors in this domain will be from the GConvertError enumeration. See GError for information on error domains.

g_iconv_open ()

GIConv              g_iconv_open                        (const gchar *to_codeset,
                                                         const gchar *from_codeset);

Same as the standard UNIX routine iconv_open(), but may be implemented via libiconv on UNIX flavors that lack a native implementation.

GLib provides g_convert() and g_locale_to_utf8() which are likely more convenient than the raw iconv wrappers.

to_codeset : | destination codeset
from_codeset : | source codeset
Returns : | a "conversion descriptor", or (GIConv)-1 if opening the converter failed.

g_iconv ()

size_t              g_iconv                             (GIConv converter,
                                                         gchar **inbuf,
                                                         gsize *inbytes_left,
                                                         gchar **outbuf,
                                                         gsize *outbytes_left);

Same as the standard UNIX routine iconv(), but may be implemented via libiconv on UNIX flavors that lack a native implementation.

GLib provides g_convert() and g_locale_to_utf8() which are likely more convenient than the raw iconv wrappers.

converter : | conversion descriptor from g_iconv_open()
inbuf : | bytes to convert
inbytes_left : | inout parameter, bytes remaining to convert in inbuf
outbuf : | converted output bytes
outbytes_left : | inout parameter, bytes available to fill in outbuf
Returns : | count of non-reversible conversions, or -1 on error

g_iconv_close ()

gint                g_iconv_close                       (GIConv converter);

Same as the standard UNIX routine iconv_close(), but may be implemented via libiconv on UNIX flavors that lack a native implementation. Should be called to clean up the conversion descriptor from g_iconv_open() when you are done converting things.

GLib provides g_convert() and g_locale_to_utf8() which are likely more convenient than the raw iconv wrappers.

converter : | a conversion descriptor from g_iconv_open()
Returns : | -1 on error, 0 on success

g_locale_to_utf8 ()

gchar*              g_locale_to_utf8                    (const gchar *opsysstring,
                                                         gssize len,
                                                         gsize *bytes_read,
                                                         gsize *bytes_written,
                                                         GError **error);

Converts a string which is in the encoding used for strings by the C runtime (usually the same as that used by the operating system) in the current locale into a UTF-8 string.

opsysstring : | a string in the encoding of the current locale. On Windows this means the system codepage.
len : | the length of the string, or -1 if the string is nul-terminated[1].
bytes_read : | location to store the number of bytes in the input string that were successfully converted, or NULL. Even if the conversion was successful, this may be less than len if there were partial characters at the end of the input. If the error G_CONVERT_ERROR_ILLEGAL_SEQUENCE occurs, the value stored will the byte offset after the last valid input sequence.
bytes_written : | the number of bytes stored in the output buffer (not including the terminating nul).
error : | location to store the error occuring, or NULL to ignore errors. Any of the errors in GConvertError may occur.
Returns : | The converted string, or NULL on an error.

g_filename_to_utf8 ()

gchar*              g_filename_to_utf8                  (const gchar *opsysstring,
                                                         gssize len,
                                                         gsize *bytes_read,
                                                         gsize *bytes_written,
                                                         GError **error);

Converts a string which is in the encoding used by GLib for filenames into a UTF-8 string. Note that on Windows GLib uses UTF-8 for filenames.

opsysstring : | a string in the encoding for filenames
len : | the length of the string, or -1 if the string is nul-terminated[1].
bytes_read : | location to store the number of bytes in the input string that were successfully converted, or NULL. Even if the conversion was successful, this may be less than len if there were partial characters at the end of the input. If the error G_CONVERT_ERROR_ILLEGAL_SEQUENCE occurs, the value stored will the byte offset after the last valid input sequence.
bytes_written : | the number of bytes stored in the output buffer (not including the terminating nul).
error : | location to store the error occuring, or NULL to ignore errors. Any of the errors in GConvertError may occur.
Returns : | The converted string, or NULL on an error.

g_filename_from_utf8 ()

gchar*              g_filename_from_utf8                (const gchar *utf8string,
                                                         gssize len,
                                                         gsize *bytes_read,
                                                         gsize *bytes_written,
                                                         GError **error);

Converts a string from UTF-8 to the encoding GLib uses for filenames. Note that on Windows GLib uses UTF-8 for filenames.

utf8string : | a UTF-8 encoded string.
len : | the length of the string, or -1 if the string is nul-terminated.
bytes_read : | location to store the number of bytes in the input string that were successfully converted, or NULL. Even if the conversion was successful, this may be less than len if there were partial characters at the end of the input. If the error G_CONVERT_ERROR_ILLEGAL_SEQUENCE occurs, the value stored will the byte offset after the last valid input sequence.
bytes_written : | the number of bytes stored in the output buffer (not including the terminating nul).
error : | location to store the error occuring, or NULL to ignore errors. Any of the errors in GConvertError may occur.
Returns : | The converted string, or NULL on an error.

g_filename_from_uri ()

gchar*              g_filename_from_uri                 (const gchar *uri,
                                                         gchar **hostname,
                                                         GError **error);

Converts an escaped ASCII-encoded URI to a local filename in the encoding used for filenames.

uri : | a uri describing a filename (escaped, encoded in ASCII).
hostname : | Location to store hostname for the URI, or NULL. If there is no hostname in the URI, NULL will be stored in this location.
error : | location to store the error occuring, or NULL to ignore errors. Any of the errors in GConvertError may occur.
Returns : | a newly-allocated string holding the resulting filename, or NULL on an error.

g_filename_to_uri ()

gchar*              g_filename_to_uri                   (const gchar *filename,
                                                         const gchar *hostname,
                                                         GError **error);

Converts an absolute filename to an escaped ASCII-encoded URI, with the path component following Section 3.3. of RFC 2396.

filename : | an absolute filename specified in the GLib file name encoding, which is the on-disk file name bytes on Unix, and UTF-8 on Windows
hostname : | A UTF-8 encoded hostname, or NULL for none.
error : | location to store the error occuring, or NULL to ignore errors. Any of the errors in GConvertError may occur.
Returns : | a newly-allocated string holding the resulting URI, or NULL on an error.

g_get_filename_charsets ()

gboolean            g_get_filename_charsets             (G_CONST_RETURN gchar ***charsets);

Determines the preferred character sets used for filenames. The first character set from the charsets is the filename encoding, the subsequent character sets are used when trying to generate a displayable representation of a filename, see g_filename_display_name().

On Unix, the character sets are determined by consulting the environment variables G_FILENAME_ENCODING and G_BROKEN_FILENAMES. On Windows, the character set used in the GLib API is always UTF-8 and said environment variables have no effect.

G_FILENAME_ENCODING may be set to a comma-separated list of character set names. The special token "locale" is taken to mean the character set for the current locale. If G_FILENAME_ENCODING is not set, but G_BROKEN_FILENAMES is, the character set of the current locale is taken as the filename encoding. If neither environment variable is set, UTF-8 is taken as the filename encoding, but the character set of the current locale is also put in the list of encodings.

The returned charsets belong to GLib and must not be freed.

Note that on Unix, regardless of the locale character set or G_FILENAME_ENCODING value, the actual file names present on a system might be in any random encoding or just gibberish.

charsets : | return location for the NULL-terminated list of encoding names
Returns : | TRUE if the filename encoding is UTF-8.

Since 2.6

g_filename_display_name ()

gchar*              g_filename_display_name             (const gchar *filename);

Converts a filename into a valid UTF-8 string. The conversion is not necessarily reversible, so you should keep the original around and use the return value of this function only for display purposes. Unlike g_filename_to_utf8(), the result is guaranteed to be non-NULL even if the filename actually isn't in the GLib file name encoding.

If GLib can not make sense of the encoding of filename, as a last resort it replaces unknown characters with U+FFFD, the Unicode replacement character. You can search the result for the UTF-8 encoding of this character (which is "\357\277\275" in octal notation) to find out if filename was in an invalid encoding.

If you know the whole pathname of the file you should use g_filename_display_basename(), since that allows location-based translation of filenames.

filename : | a pathname hopefully in the GLib file name encoding
Returns : | a newly allocated string containing a rendition of the filename in valid UTF-8

Since 2.6

g_filename_display_basename ()

gchar*              g_filename_display_basename         (const gchar *filename);

Returns the display basename for the particular filename, guaranteed to be valid UTF-8. The display name might not be identical to the filename, for instance there might be problems converting it to UTF-8, and some files can be translated in the display.

If GLib can not make sense of the encoding of filename, as a last resort it replaces unknown characters with U+FFFD, the Unicode replacement character. You can search the result for the UTF-8 encoding of this character (which is "\357\277\275" in octal notation) to find out if filename was in an invalid encoding.

You must pass the whole absolute pathname to this functions so that translation of well known locations can be done.

This function is preferred over g_filename_display_name() if you know the whole path, as it allows translation.

filename : | an absolute pathname in the GLib file name encoding
Returns : | a newly allocated string containing a rendition of the basename of the filename in valid UTF-8

Since 2.6

g_uri_list_extract_uris ()

gchar**             g_uri_list_extract_uris             (const gchar *uri_list);

Splits an URI list conforming to the text/uri-list mime type defined in RFC 2483 into individual URIs, discarding any comments. The URIs are not validated.

uri_list : | an URI list
Returns : | a newly allocated NULL-terminated list of strings holding the individual URIs. The array should be freed with g_strfreev().

Since 2.6

g_locale_from_utf8 ()

gchar*              g_locale_from_utf8                  (const gchar *utf8string,
                                                         gssize len,
                                                         gsize *bytes_read,
                                                         gsize *bytes_written,
                                                         GError **error);

Converts a string from UTF-8 to the encoding used for strings by the C runtime (usually the same as that used by the operating system) in the current locale.

utf8string : | a UTF-8 encoded string
len : | the length of the string, or -1 if the string is nul-terminated[1].
bytes_read : | location to store the number of bytes in the input string that were successfully converted, or NULL. Even if the conversion was successful, this may be less than len if there were partial characters at the end of the input. If the error G_CONVERT_ERROR_ILLEGAL_SEQUENCE occurs, the value stored will the byte offset after the last valid input sequence.
bytes_written : | the number of bytes stored in the output buffer (not including the terminating nul).
error : | location to store the error occuring, or NULL to ignore errors. Any of the errors in GConvertError may occur.
Returns : | The converted string, or NULL on an error.

enum GConvertError

typedef enum
{
  G_CONVERT_ERROR_NO_CONVERSION,
  G_CONVERT_ERROR_ILLEGAL_SEQUENCE,
  G_CONVERT_ERROR_FAILED,
  G_CONVERT_ERROR_PARTIAL_INPUT,
  G_CONVERT_ERROR_BAD_URI,
  G_CONVERT_ERROR_NOT_ABSOLUTE_PATH
} GConvertError;

Error codes returned by character set conversion routines.

G_CONVERT_ERROR_NO_CONVERSION | Conversion between the requested character sets is not supported.
G_CONVERT_ERROR_ILLEGAL_SEQUENCE | Invalid byte sequence in conversion input.
G_CONVERT_ERROR_FAILED | Conversion failed for some reason.
G_CONVERT_ERROR_PARTIAL_INPUT | Partial character sequence at end of input.
G_CONVERT_ERROR_BAD_URI | URI is invalid.
G_CONVERT_ERROR_NOT_ABSOLUTE_PATH | Pathname is not an absolute path.

g_get_charset ()

gboolean            g_get_charset                       (G_CONST_RETURN char **charset);

Obtains the character set for the current locale; you might use this character set as an argument to g_convert(), to convert from the current locale's encoding to some other encoding. (Frequently g_locale_to_utf8() and g_locale_from_utf8() are nice shortcuts, though.)

The return value is TRUE if the locale's encoding is UTF-8, in that case you can perhaps avoid calling g_convert().

The string returned in charset is not allocated, and should not be freed.

charset : | return location for character set name
Returns : | TRUE if the returned charset is UTF-8

[1] Note that some encodings may allow nul bytes to occur inside strings. In that case, using -1 for the len parameter is unsafe.

[2] Despite the fact that byes_read can return information about partial characters, the g_convert_... functions are not generally suitable for streaming. If the underlying converter being used maintains internal state, then this won't be preserved across successive calls to g_convert(), g_convert_with_iconv() or g_convert_with_fallback(). (An example of this is the GNU C converter for CP1255 which does not emit a base character until it knows that the next character is not a mark that could combine with the base character.)


Commandline option parser

Commandline option parser — parses commandline options

Synopsis

#include <glib.h>

enum                GOptionError;
#define             G_OPTION_ERROR
gboolean            (*GOptionArgFunc)                   (const gchar *option_name,
                                                         const gchar *value,
                                                         gpointer data,
                                                         GError **error);
                    GOptionContext;
GOptionContext*     g_option_context_new                (const gchar *parameter_string);
void                g_option_context_set_summary        (GOptionContext *context,
                                                         const gchar *summary);
const gchar*        g_option_context_get_summary        (GOptionContext *context);
void                g_option_context_set_description    (GOptionContext *context,
                                                         const gchar *description);
const gchar*        g_option_context_get_description    (GOptionContext *context);
const gchar*        (*GTranslateFunc)                   (const gchar *str,
                                                         gpointer data);
void                g_option_context_set_translate_func (GOptionContext *context,
                                                         GTranslateFunc func,
                                                         gpointer data,
                                                         GDestroyNotify destroy_notify);
void                g_option_context_set_translation_domain
                                                        (GOptionContext *context,
                                                         const gchar *domain);
void                g_option_context_free               (GOptionContext *context);
gboolean            g_option_context_parse              (GOptionContext *context,
                                                         gint *argc,
                                                         gchar ***argv,
                                                         GError **error);
void                g_option_context_set_help_enabled   (GOptionContext *context,
                                                         gboolean help_enabled);
gboolean            g_option_context_get_help_enabled   (GOptionContext *context);
void                g_option_context_set_ignore_unknown_options
                                                        (GOptionContext *context,
                                                         gboolean ignore_unknown);
gboolean            g_option_context_get_ignore_unknown_options
                                                        (GOptionContext *context);
enum                GOptionArg;
enum                GOptionFlags;
#define             G_OPTION_REMAINING
                    GOptionEntry;
void                g_option_context_add_main_entries   (GOptionContext *context,
                                                         const GOptionEntry *entries,
                                                         const gchar *translation_domain);
                    GOptionGroup;
void                g_option_context_add_group          (GOptionContext *context,
                                                         GOptionGroup *group);
void                g_option_context_set_main_group     (GOptionContext *context,
                                                         GOptionGroup *group);
GOptionGroup*       g_option_context_get_main_group     (GOptionContext *context);
GOptionGroup*       g_option_group_new                  (const gchar *name,
                                                         const gchar *description,
                                                         const gchar *help_description,
                                                         gpointer user_data,
                                                         GDestroyNotify destroy);
void                g_option_group_free                 (GOptionGroup *group);
void                g_option_group_add_entries          (GOptionGroup *group,
                                                         const GOptionEntry *entries);
gboolean            (*GOptionParseFunc)                 (GOptionContext *context,
                                                         GOptionGroup *group,
                                                         gpointer data,
                                                         GError **error);
void                g_option_group_set_parse_hooks      (GOptionGroup *group,
                                                         GOptionParseFunc pre_parse_func,
                                                         GOptionParseFunc post_parse_func);
void                (*GOptionErrorFunc)                 (GOptionContext *context,
                                                         GOptionGroup *group,
                                                         gpointer data,
                                                         GError **error);
void                g_option_group_set_error_hook       (GOptionGroup *group,
                                                         GOptionErrorFunc error_func);
void                g_option_group_set_translate_func   (GOptionGroup *group,
                                                         GTranslateFunc func,
                                                         gpointer data,
                                                         GDestroyNotify destroy_notify);
void                g_option_group_set_translation_domain
                                                        (GOptionGroup *group,
                                                         const gchar *domain);

Description

The GOption commandline parser is intended to be a simpler replacement for the popt library. It supports short and long commandline options, as shown in the following example:

testtreemodel -r 1 --max-size 20 --rand --display=:1.0 -vb -- file1 file2

The example demonstrates a number of features of the GOption commandline parser

  • Options can be single letters, prefixed by a single dash. Multiple short options can be grouped behind a single dash.

  • Long options are prefixed by two consecutive dashes.

  • Options can have an extra argument, which can be a number, a string or a filename. For long options, the extra argument can be appended with an equals sign after the option name.

  • Non-option arguments are returned to the application as rest arguments.

  • An argument consisting solely of two dashes turns off further parsing, any remaining arguments (even those starting with a dash) are returned to the application as rest arguments.

Another important feature of GOption is that it can automatically generate nicely formatted help output. Unless it is explicitly turned off with g_option_context_set_help_enabled(), GOption will recognize the --help, -?, --help-all and --help-groupname options (where groupname is the name of a GOptionGroup) and write a text similar to the one shown in the following example to stdout.

Usage:
  testtreemodel [OPTION...] - test tree model performance

Help Options:
  -?, --help               Show help options
  --help-all               Show all help options
  --help-gtk               Show GTK+ Options

Application Options:
  -r, --repeats=N          Average over N repetitions
  -m, --max-size=M         Test up to 2^M items
  --display=DISPLAY        X display to use
  -v, --verbose            Be verbose
  -b, --beep               Beep when done
  --rand                   Randomize the data

GOption groups options in GOptionGroups, which makes it easy to incorporate options from multiple sources. The intended use for this is to let applications collect option groups from the libraries it uses, add them to their GOptionContext, and parse all options by a single call to g_option_context_parse(). See gtk_get_option_group() for an example.

If an option is declared to be of type string or filename, GOption takes care of converting it to the right encoding; strings are returned in UTF-8, filenames are returned in the GLib filename encoding.

Here is a complete example of setting up GOption to parse the example commandline above and produce the example help output.

static gint repeats = 2;
static gint max_size = 8;
static gboolean verbose = FALSE;
static gboolean beep = FALSE;
static gboolean rand = FALSE;

static GOptionEntry entries[] =
{
  { "repeats", 'r', 0, G_OPTION_ARG_INT, &repeats, "Average over N repetitions", "N" },
  { "max-size", 'm', 0, G_OPTION_ARG_INT, &max_size, "Test up to 2^M items", "M" },
  { "verbose", 'v', 0, G_OPTION_ARG_NONE, &verbose, "Be verbose", NULL },
  { "beep", 'b', 0, G_OPTION_ARG_NONE, &beep, "Beep when done", NULL },
  { "rand", 0, 0, G_OPTION_ARG_NONE, &rand, "Randomize the data", NULL },
  { NULL }
};

int
main (int argc, char *argv[])
{
  GError *error = NULL;
  GOptionContext *context;

  context = g_option_context_new ("- test tree model performance");
  g_option_context_add_main_entries (context, entries, GETTEXT_PACKAGE);
  g_option_context_add_group (context, gtk_get_option_group (TRUE));
  g_option_context_parse (context, &argc, &argv, &error);

  /* ... */

}

Details

enum GOptionError

typedef enum
{
  G_OPTION_ERROR_UNKNOWN_OPTION,
  G_OPTION_ERROR_BAD_VALUE,
  G_OPTION_ERROR_FAILED
} GOptionError;

Error codes returned by option parsing.

G_OPTION_ERROR_UNKNOWN_OPTION | An option was not known to the parser. This error will only be reported, if the parser hasn't been instructed to ignore unknown options, see g_option_context_set_ignore_unknown_options().
G_OPTION_ERROR_BAD_VALUE | A value couldn't be parsed.
G_OPTION_ERROR_FAILED | A GOptionArgFunc callback failed.

G_OPTION_ERROR

#define G_OPTION_ERROR (g_option_error_quark ())

Error domain for option parsing. Errors in this domain will be from the GOptionError enumeration. See GError for information on error domains.

GOptionArgFunc ()

gboolean            (*GOptionArgFunc)                   (const gchar *option_name,
                                                         const gchar *value,
                                                         gpointer data,
                                                         GError **error);

The type of function to be passed as callback for G_OPTION_ARG_CALLBACK options.

option_name : | The name of the option being parsed. This will be either a single dash followed by a single letter (for a short name) or two dashes followed by a long option name.
value : | The value to be parsed.
data : | User data added to the GOptionGroup containing the option when it was created with g_option_group_new()
error : | A return location for errors. The error code G_OPTION_ERROR_FAILED is intended to be used for errors in GOptionArgFunc callbacks.
Returns : | TRUE if the option was successfully parsed, FALSE if an error occurred, in which case error should be set with g_set_error()

GOptionContext

typedef struct _GOptionContext GOptionContext;

A GOptionContext struct defines which options are accepted by the commandline option parser. The struct has only private fields and should not be directly accessed.

g_option_context_new ()

GOptionContext*     g_option_context_new                (const gchar *parameter_string);

Creates a new option context.

The parameter_string can serve multiple purposes. It can be used to add descriptions for "rest" arguments, which are not parsed by the GOptionContext, typically something like "FILES" or "FILE1 FILE2...". If you are using G_OPTION_REMAINING for collecting "rest" arguments, GLib handles this automatically by using the arg_description of the corresponding GOptionEntry in the usage summary.

Another usage is to give a short summary of the program functionality, like " - frob the strings", which will be displayed in the same line as the usage. For a longer description of the program functionality that should be displayed as a paragraph below the usage line, use g_option_context_set_summary().

Note that the parameter_string is translated (see g_option_context_set_translate_func()).

parameter_string : | a string which is displayed in the first line of --help output, after the usage summary programname [OPTION...]
Returns : | a newly created GOptionContext, which must be freed with g_option_context_free() after use.

Since 2.6

g_option_context_set_summary ()

void                g_option_context_set_summary        (GOptionContext *context,
                                                         const gchar *summary);

Adds a string to be displayed in --help output before the list of options. This is typically a summary of the program functionality.

Note that the summary is translated (see g_option_context_set_translate_func()).

context : | a GOptionContext
summary : | a string to be shown in --help output before the list of options, or NULL

Since 2.12

g_option_context_get_summary ()

const gchar*        g_option_context_get_summary        (GOptionContext *context);

Returns the summary. See g_option_context_set_summary().

context : | a GOptionContext
Returns : | the summary

Since 2.12

g_option_context_set_description ()

void                g_option_context_set_description    (GOptionContext *context,
                                                         const gchar *description);

Adds a string to be displayed in --help output after the list of options. This text often includes a bug reporting address.

Note that the summary is translated (see g_option_context_set_translate_func()).

context : | a GOptionContext
description : | a string to be shown in --help output after the list of options, or NULL

Since 2.12

g_option_context_get_description ()

const gchar*        g_option_context_get_description    (GOptionContext *context);

Returns the description. See g_option_context_set_description().

context : | a GOptionContext
Returns : | the description

Since 2.12

GTranslateFunc ()

const gchar*        (*GTranslateFunc)                   (const gchar *str,
                                                         gpointer data);

The type of functions which are used to translate user-visible strings, for --help output.

str : | the untranslated string
data : | user data specified when installing the function, e.g. in g_option_group_set_translate_func()
Returns : | a translation of the string for the current locale. The returned string is owned by GLib and must not be freed.

g_option_context_set_translate_func ()

void                g_option_context_set_translate_func (GOptionContext *context,
                                                         GTranslateFunc func,
                                                         gpointer data,
                                                         GDestroyNotify destroy_notify);

Sets the function which is used to translate the contexts user-visible strings, for --help output. If func is NULL, strings are not translated.

Note that option groups have their own translation functions, this function only affects the parameter_string (see g_option_context_nex()), the summary (see g_option_context_set_summary()) and the description (see g_option_context_set_description()).

If you are using gettext(), you only need to set the translation domain, see g_context_group_set_translation_domain().

context : | a GOptionContext
func : | the GTranslateFunc, or NULL
data : | user data to pass to func, or NULL
destroy_notify : | a function which gets called to free data, or NULL

Since 2.12

g_option_context_set_translation_domain ()

void                g_option_context_set_translation_domain
                                                        (GOptionContext *context,
                                                         const gchar *domain);

A convenience function to use gettext() for translating user-visible strings.

context : | a GOptionContext
domain : | the domain to use

Since 2.12

g_option_context_free ()

void                g_option_context_free               (GOptionContext *context);

Frees context and all the groups which have been added to it.

context : a GOptionContext

Since 2.6

g_option_context_parse ()

gboolean            g_option_context_parse              (GOptionContext *context,
                                                         gint *argc,
                                                         gchar ***argv,
                                                         GError **error);

Parses the command line arguments, recognizing options which have been added to context. A side-effect of calling this function is that g_set_prgname() will be called.

If the parsing is successful, any parsed arguments are removed from the array and argc and argv are updated accordingly. A '--' option is stripped from argv unless there are unparsed options before and after it, or some of the options after it start with '-'. In case of an error, argc and argv are left unmodified.

If automatic --help support is enabled (see g_option_context_set_help_enabled()), and the argv array contains one of the recognized help options, this function will produce help output to stdout and call exit (0).

context : | a GOptionContext
argc : | a pointer to the number of command line arguments.
argv : | a pointer to the array of command line arguments.
error : | a return location for errors
Returns : | TRUE if the parsing was successful, FALSE if an error occurred

Since 2.6

g_option_context_set_help_enabled ()

void                g_option_context_set_help_enabled   (GOptionContext *context,
                                                         gboolean help_enabled);

Enables or disables automatic generation of --help output. By default, g_option_context_parse() recognizes --help, -?, --help-all and --help-groupname and creates suitable output to stdout.

context : | a GOptionContext
help_enabled : | TRUE to enable --help, FALSE to disable it

Since 2.6

g_option_context_get_help_enabled ()

gboolean            g_option_context_get_help_enabled   (GOptionContext *context);

Returns whether automatic --help generation is turned on for context. See g_option_context_set_help_enabled().

context : | a GOptionContext
Returns : | TRUE if automatic help generation is turned on.

Since 2.6

g_option_context_set_ignore_unknown_options ()

void                g_option_context_set_ignore_unknown_options
                                                        (GOptionContext *context,
                                                         gboolean ignore_unknown);

Sets whether to ignore unknown options or not. If an argument is ignored, it is left in the argv array after parsing. By default, g_option_context_parse() treats unknown options as error.

This setting does not affect non-option arguments (i.e. arguments which don't start with a dash). But note that GOption cannot reliably determine whether a non-option belongs to a preceding unknown option.

context : | a GOptionContext
ignore_unknown : | TRUE to ignore unknown options, FALSE to produce an error when unknown options are met

Since 2.6

g_option_context_get_ignore_unknown_options ()

gboolean            g_option_context_get_ignore_unknown_options
                                                        (GOptionContext *context);

Returns whether unknown options are ignored or not. See g_option_context_set_ignore_unknown_options().

context : | a GOptionContext
Returns : | TRUE if unknown options are ignored.

Since 2.6

enum GOptionArg

typedef enum
{
  G_OPTION_ARG_NONE,
  G_OPTION_ARG_STRING,
  G_OPTION_ARG_INT,
  G_OPTION_ARG_CALLBACK,
  G_OPTION_ARG_FILENAME,
  G_OPTION_ARG_STRING_ARRAY,
  G_OPTION_ARG_FILENAME_ARRAY,
  G_OPTION_ARG_DOUBLE,
  G_OPTION_ARG_INT64
} GOptionArg;

The GOptionArg enum values determine which type of extra argument the options expect to find. If an option expects an extra argument, it can be specified in several ways; with a short option: -x arg, with a long option: --name arg or combined in a single argument: --name=arg.

G_OPTION_ARG_NONE | No extra argument. This is useful for simple flags.
G_OPTION_ARG_STRING | The option takes a string argument.
G_OPTION_ARG_INT | The option takes an integer argument.
G_OPTION_ARG_CALLBACK | The option provides a callback to parse the extra argument.
G_OPTION_ARG_FILENAME | The option takes a filename as argument.
G_OPTION_ARG_STRING_ARRAY | The option takes a string argument, multiple uses of the option are collected into an array of strings.
G_OPTION_ARG_FILENAME_ARRAY | The option takes a filename as argument, multiple uses of the option are collected into an array of strings.
G_OPTION_ARG_DOUBLE | The option takes a double argument. The argument can be formatted either for the user's locale or for the "C" locale. Since 2.12
G_OPTION_ARG_INT64 | The option takes a 64-bit integer. Like G_OPTION_ARG_INT but for larger numbers. The number can be in decimal base, or in hexadecimal (when prefixed with 0x, for example, 0xffffffff). Since 2.12

enum GOptionFlags

typedef enum
{
  G_OPTION_FLAG_HIDDEN		= 1 << 0,
  G_OPTION_FLAG_IN_MAIN		= 1 << 1,
  G_OPTION_FLAG_REVERSE		= 1 << 2,
  G_OPTION_FLAG_NO_ARG		= 1 << 3,
  G_OPTION_FLAG_FILENAME	= 1 << 4,
  G_OPTION_FLAG_OPTIONAL_ARG    = 1 << 5,
  G_OPTION_FLAG_NOALIAS	        = 1 << 6
} GOptionFlags;

Flags which modify individual options.

G_OPTION_FLAG_HIDDEN | The option doesn't appear in --help output.
G_OPTION_FLAG_IN_MAIN | The option appears in the main section of the --help output, even if it is defined in a group.
G_OPTION_FLAG_REVERSE | For options of the G_OPTION_ARG_NONE kind, this flag indicates that the sense of the option is reversed.
G_OPTION_FLAG_NO_ARG | For options of the G_OPTION_ARG_CALLBACK kind, this flag indicates that the callback does not take any argument (like a G_OPTION_ARG_NONE option). Since 2.8
G_OPTION_FLAG_FILENAME | For options of the G_OPTION_ARG_CALLBACK kind, this flag indicates that the argument should be passed to the callback in the GLib filename encoding rather than UTF-8. Since 2.8
G_OPTION_FLAG_OPTIONAL_ARG | For options of the G_OPTION_ARG_CALLBACK kind, this flag indicates that the argument supply is optional. If no argument is given then data of GOptionParseFunc will be set to NULL. Since 2.8
G_OPTION_FLAG_NOALIAS | This flag turns off the automatic conflict resolution which prefixes long option names with groupname- if there is a conflict. This option should only be used in situations where aliasing is necessary to model some legacy commandline interface. It is not safe to use this option, unless all option groups are under your direct control. Since 2.8.

G_OPTION_REMAINING

#define G_OPTION_REMAINING ""

If a long option in the main group has this name, it is not treated as a regular option. Instead it collects all non-option arguments which would otherwise be left in argv. The option must be of type G_OPTION_ARG_STRING_ARRAY or G_OPTION_ARG_FILENAME_ARRAY.

Using G_OPTION_REMAINING instead of simply scanning argv for leftover arguments has the advantage that GOption takes care of necessary encoding conversions for strings or filenames.

Since 2.6

GOptionEntry

typedef struct {
  const gchar *long_name;
  gchar        short_name;
  gint         flags;

  GOptionArg   arg;
  gpointer     arg_data;

  const gchar *description;
  const gchar *arg_description;
} GOptionEntry;

A GOptionEntry defines a single option. To have an effect, they must be added to a GOptionGroup with g_option_context_add_main_entries() or g_option_group_add_entries().

const gchar *long_name; | The long name of an option can be used to specify it in a commandline as --long_name. Every option must have a long name. To resolve conflicts if multiple option groups contain the same long name, it is also possible to specify the option as --groupname-long_name.
gchar short_name; | If an option has a short name, it can be specified -short_name in a commandline. short_name must be a printable ASCII character different from '-', or zero if the option has no short name.
gint flags; | Flags from GOptionFlags.
GOptionArg arg; | The type of the option, as a GOptionArg.
gpointer arg_data; If the arg type is G_OPTION_ARG_CALLBACK, then arg_data must point to a GOptionArgFunc callback function, which will be called to handle the extra argument. Otherwise, arg_data is a pointer to a location to store the value, the required type of the location depends on the arg type:
G_OPTION_ARG_NONE | gboolean
G_OPTION_ARG_STRING | gchar*
G_OPTION_ARG_INT | gint
G_OPTION_ARG_FILENAME | gchar*
G_OPTION_ARG_STRING_ARRAY | gchar**
G_OPTION_ARG_FILENAME_ARRAY | gchar**
G_OPTION_ARG_DOUBLE | gdouble
const gchar *description; | the description for the option in --help output. The description is translated using the translate_func of the group, see g_option_group_set_translation_domain().
const gchar *arg_description; | The placeholder to use for the extra argument parsed by the option in --help output. The arg_description is translated using the translate_func of the group, see g_option_group_set_translation_domain().

g_option_context_add_main_entries ()

void                g_option_context_add_main_entries   (GOptionContext *context,
                                                         const GOptionEntry *entries,
                                                         const gchar *translation_domain);

A convenience function which creates a main group if it doesn't exist, adds the entries to it and sets the translation domain.

context : | a GOptionContext
entries : | a NULL-terminated array of GOptionEntrys
translation_domain : | a translation domain to use for translating the --help output for the options in entries with gettext(), or NULL

Since 2.6

GOptionGroup

typedef struct _GOptionGroup GOptionGroup;

A GOptionGroup struct defines the options in a single group. The struct has only private fields and should not be directly accessed.

All options in a group share the same translation function. Libaries which need to parse commandline options are expected to provide a function for getting a GOptionGroup holding their options, which the application can then add to its GOptionContext.

g_option_context_add_group ()

void                g_option_context_add_group          (GOptionContext *context,
                                                         GOptionGroup *group);

Adds a GOptionGroup to the context, so that parsing with context will recognize the options in the group. Note that the group will be freed together with the context when g_option_context_free() is called, so you must not free the group yourself after adding it to a context.

context : | a GOptionContext
group : | the group to add

Since 2.6

g_option_context_set_main_group ()

void                g_option_context_set_main_group     (GOptionContext *context,
                                                         GOptionGroup *group);

Sets a GOptionGroup as main group of the context. This has the same effect as calling g_option_context_add_group(), the only difference is that the options in the main group are treated differently when generating --help output.

context : | a GOptionContext
group : | the group to set as main group

Since 2.6

g_option_context_get_main_group ()

GOptionGroup*       g_option_context_get_main_group     (GOptionContext *context);

Returns a pointer to the main group of context.

context : | a GOptionContext
Returns : | the main group of context, or NULL if context doesn't have a main group. Note that group belongs to context and should not be modified or freed.

Since 2.6

g_option_group_new ()

GOptionGroup*       g_option_group_new                  (const gchar *name,
                                                         const gchar *description,
                                                         const gchar *help_description,
                                                         gpointer user_data,
                                                         GDestroyNotify destroy);

Creates a new GOptionGroup.

name : | the name for the option group, this is used to provide help for the options in this group with --help-name
description : | a description for this group to be shown in --help. This string is translated using the translation domain or translation function of the group
help_description : | a description for the --help-name option. This string is translated using the translation domain or translation function of the group
user_data : | user data that will be passed to the pre- and post-parse hooks, the error hook and to callbacks of G_OPTION_ARG_CALLBACK options, or NULL
destroy : | a function that will be called to free user_data, or NULL
Returns : | a newly created option group. It should be added to a GOptionContext or freed with g_option_group_free().

Since 2.6

g_option_group_free ()

void                g_option_group_free                 (GOptionGroup *group);

Frees a GOptionGroup. Note that you must not free groups which have been added to a GOptionContext.

group : a GOptionGroup

Since 2.6

g_option_group_add_entries ()

void                g_option_group_add_entries          (GOptionGroup *group,
                                                         const GOptionEntry *entries);

Adds the options specified in entries to group.

group : | a GOptionGroup
entries : | a NULL-terminated array of GOptionEntrys

Since 2.6

GOptionParseFunc ()

gboolean            (*GOptionParseFunc)                 (GOptionContext *context,
                                                         GOptionGroup *group,
                                                         gpointer data,
                                                         GError **error);

The type of function that can be called before and after parsing.

context : | The active GOptionContext
group : | The group to which the function belongs
data : | User data added to the GOptionGroup containing the option when it was created with g_option_group_new()
error : | A return location for error details
Returns : | TRUE if the function completed successfully, FALSE if an error occurred, in which case error should be set with g_set_error()

g_option_group_set_parse_hooks ()

void                g_option_group_set_parse_hooks      (GOptionGroup *group,
                                                         GOptionParseFunc pre_parse_func,
                                                         GOptionParseFunc post_parse_func);

Associates two functions with group which will be called from g_option_context_parse() before the first option is parsed and after the last option has been parsed, respectively.

Note that the user data to be passed to pre_parse_func and post_parse_func can be specified when constructing the group with g_option_group_new().

group : | a GOptionGroup
pre_parse_func : | a function to call before parsing, or NULL
post_parse_func : | a function to call after parsing, or NULL

Since 2.6

GOptionErrorFunc ()

void                (*GOptionErrorFunc)                 (GOptionContext *context,
                                                         GOptionGroup *group,
                                                         gpointer data,
                                                         GError **error);

The type of function to be used as callback when a parse error occurs.

context : | The active GOptionContext
group : | The group to which the function belongs
data : | User data added to the GOptionGroup containing the option when it was created with g_option_group_new()
error : | The GError containing details about the parse error

g_option_group_set_error_hook ()

void                g_option_group_set_error_hook       (GOptionGroup *group,
                                                         GOptionErrorFunc error_func);

Associates a function with group which will be called from g_option_context_parse() when an error occurs.

Note that the user data to be passed to pre_parse_func and post_parse_func can be specified when constructing the group with g_option_group_new().

group : | a GOptionGroup
error_func : | a function to call when an error occurs

Since 2.6

g_option_group_set_translate_func ()

void                g_option_group_set_translate_func   (GOptionGroup *group,
                                                         GTranslateFunc func,
                                                         gpointer data,
                                                         GDestroyNotify destroy_notify);

Sets the function which is used to translate user-visible strings, for --help output. Different groups can use different GTranslateFuncs. If func is NULL, strings are not translated.

If you are using gettext(), you only need to set the translation domain, see g_option_group_set_translation_domain().

group : | a GOptionGroup
func : | the GTranslateFunc, or NULL
data : | user data to pass to func, or NULL
destroy_notify : | a function which gets called to free data, or NULL

Since 2.6

g_option_group_set_translation_domain ()

void                g_option_group_set_translation_domain
                                                        (GOptionGroup *group,
                                                         const gchar *domain);

A convenience function to use gettext() for translating user-visible strings.

group : | a GOptionGroup
domain : | the domain to use

Since 2.6


Compiling GLib Applications

Compiling GLib Applications — How to compile your GLib application

Compiling GLib Applications on UNIX

To compile a GLib application, you need to tell the compiler where to find the GLib header files and libraries. This is done with the pkg-config utility.

The following interactive shell session demonstrates how pkg-config is used (the actual output on your system may be different):

$ pkg-config --cflags glib-2.0
 -I/usr/include/glib-2.0 -I/usr/lib/glib-2.0/include
$ pkg-config --libs glib-2.0
 -L/usr/lib -lm -lglib-2.0

If your application uses threads or GObject features, it must be compiled and linked with the options returned by the following pkg-config invocations:

$ pkg-config --cflags --libs gthread-2.0
$ pkg-config --cflags --libs gobject-2.0

If your application uses modules, it must be compiled and linked with the options returned by one of the following pkg-config invocations:

$ pkg-config --cflags --libs gmodule-no-export-2.0
$ pkg-config --cflags --libs gmodule-2.0

The difference between the two is that gmodule-2.0 adds --export-dynamic to the linker flags, which is often not needed.

The simplest way to compile a program is to use the "backticks" feature of the shell. If you enclose a command in backticks (not single quotes), then its output will be substituted into the command line before execution. So to compile a GLib Hello, World, you would type the following:

$ cc `pkg-config --cflags --libs glib-2.0` hello.c -o hello

If you want to make sure that your program doesn't use any deprecated functions, you can define the preprocessor symbol G_DISABLE_DEPRECATED by using the command line option -DG_DISABLE_DEPRECATED=1.


GLib Core Application Support

The Main Event Loop — manages all available sources of events.
Threads — thread abstraction; including threads, different mutexes, conditions and thread private data.
Thread Pools — pools of threads to execute work concurrently.
Asynchronous Queues — asynchronous communication between threads.
Dynamic Loading of Modules — portable method for dynamically loading 'plug-ins'.
Memory Allocation — general memory-handling.
IO Channels — portable support for using files, pipes and sockets.
Error Reporting — a system for reporting errors.
Message Output and Debugging Functions — functions to output messages and help debug applications.
Message Logging — versatile support for logging messages with different levels of importance.


Cross-compiling the GLib package

Cross-compiling the GLib Package — How to cross-compile GLib

Building the Library for a different architecture

Cross-compilation is the process of compiling a program or library on a different architecture or operating system then it will be run upon. GLib is slightly more difficult to cross-compile than many packages because much of GLib is about hiding differences between different systems.

These notes cover things specific to cross-compiling GLib; for general information about cross-compilation, see the autoconf info pages.

GLib tries to detect as much information as possible about the target system by compiling and linking programs without actually running anything; however, some information GLib needs is not available this way. This information needs to be provided to the configure script via a "cache file" or by setting the cache variables in your environment.

As an example of using a cache file, to cross compile for the "MingW32" Win32 runtine environment on a Linux system, create a file 'win32.cache' with the following contents:

glib_cv_long_long_format=I64
glib_cv_stack_grows=no

Then execute the following commands:

PATH=/path/to/mingw32-compiler/bin:$PATH
chmod a-w win32.cache   # prevent configure from changing it
./configure --cache-file=win32.cache --host=mingw32

The complete list of cache file variables follows. Most of these won't need to be set in most cases.

Cache file variables

glib_cv_long_long_format=[ll/q/I64]. Format used by printf() and scanf() for 64 bit integers. "ll" is the C99 standard, and what is used by the 'trio' library that GLib builds if your printf() is insufficiently capable. Doesn't need to be set if you are compiling using trio.

glib_cv_stack_grows=[yes/no]. Whether the stack grows up or down. Most places will want "no", A few architectures, such as PA-RISC need "yes".

glib_cv_working_bcopy=[yes/no]. Whether your bcopy() can handle overlapping copies. Only needs to be set if you don't have memmove(). (Very unlikely)

glib_cv_sane_realloc=[yes/np]. Whether your realloc() conforms to ANSI C and can handle NULL as the first argument. Defaults to "yes" and probably doesn't need to be set.

glib_cv_have_strlcpy=[yes/no]. Whether you have strlcpy() that matches OpenBSD. Defaults to "no", which is safe, since GLib uses a built-in version in that case.

glib_cv_va_val_copy=[yes/no]. Whether va_list can be copied as a pointer. If set to "no", then memcopy() will be used. Only matters if you don't have va_copy() or __va_copy(). (So, doesn't matter for GCC.) Defaults to "yes" which is slightly more common than "no".

glib_cv_rtldglobal_broken=[yes/no]. Whether you have a bug found in OSF/1 v5.0. Defaults to "no".

glib_cv_uscore=[yes/no]. Whether an underscore needs to be prepended to symbols when looking them up via dlsym(). Only needs to be set if your system uses dlopen()/dlsym().

ac_cv_func_posix_getpwuid_r=[yes/no]. Whether you have a getpwuid_r function (in your C library, not your thread library) that conforms to the POSIX spec. (Takes a 'struct passwd **' as the final argument)

ac_cv_func_nonposix_getpwuid_r=[yes/no]. Whether you have some variant of getpwuid_r() that doesn't conform to to the POSIX spec, but GLib might be able to use (or might segfault.) Only needs to be set if ac_cv_func_posix_getpwuid_r is not set. It's safest to set this to "no".

glib_cv_use_pid_surrogate=[yes/no]. Whether to use a setpriority() on the PID of the thread as a method for setting the priority of threads. This only needs to be set when using POSIX threads.

ac_cv_func_printf_unix98=[yes/no]. Whether your printf() family supports Unix98 style %N$ positional parameters. Defaults to "no".

ac_cv_func_vsnprintf_c99=[yes/no]. Whether you have a vsnprintf() with C99 semantics. (C99 semantics means returning the number of bytes that would have been written had the output buffer had enough space.) Defaults to "no".


GLib Data Types

Memory Slices — efficient way to allocate groups of equal-sized chunks of memory.
Memory Chunks — deprecated way to allocate groups of equal-sized chunks of memory.
Doubly-Linked Lists — linked lists containing integer values or pointers to data, with the ability to iterate over the list in both directions.
Singly-Linked Lists — linked lists containing integer values or pointers to data, limited to iterating over the list in one direction.
Double-ended Queues — double-ended queue data structure.
Trash Stacks — maintain a stack of unused allocated memory chunks.
Hash Tables — associations between keys and values so that given a key the value can be found quickly.
Strings — text buffers which grow automatically as text is added.
String Chunks — efficient storage of groups of strings.
Arrays — arrays of arbitrary elements which grow automatically as elements are added.
Pointer Arrays — arrays of pointers to any type of data, which grow automatically as new elements are added.
Byte Arrays — arrays of bytes, which grow automatically as elements are added.
Balanced Binary Trees — a sorted collection of key/value pairs optimized for searching and traversing in order.
N-ary Trees — trees of data with any number of branches.
Quarks — a 2-way association between a string and a unique integer identifier.
Keyed Data Lists — lists of data elements which are accessible by a string or GQuark identifier.
Datasets — associate groups of data elements with particular memory locations.
Relations and Tuples — tables of data which can be indexed on any number of fields.
Caches — caches allow sharing of complex data structures to save resources.
Memory Allocators — deprecated way to allocate chunks of memory for GList, GSList and GNode.


Datasets

Datasets — associate groups of data elements with particular memory locations.

Synopsis

#include <glib.h>

#define             g_dataset_id_set_data               (l, k, d)
void                g_dataset_id_set_data_full          (gconstpointer dataset_location,
                                                         GQuark key_id,
                                                         gpointer data,
                                                         GDestroyNotify destroy_func);
void                (*GDestroyNotify)                   (gpointer data);
gpointer            g_dataset_id_get_data               (gconstpointer dataset_location,
                                                         GQuark key_id);
#define             g_dataset_id_remove_data            (l, k)
gpointer            g_dataset_id_remove_no_notify       (gconstpointer dataset_location,
                                                         GQuark key_id);

#define             g_dataset_set_data                  (l, k, d)
#define             g_dataset_set_data_full             (l, k, d, f)
#define             g_dataset_get_data                  (l, k)
#define             g_dataset_remove_data               (l, k)
#define             g_dataset_remove_no_notify          (l, k)

void                g_dataset_foreach                   (gconstpointer dataset_location,
                                                         GDataForeachFunc func,
                                                         gpointer user_data);
void                (*GDataForeachFunc)                 (GQuark key_id,
                                                         gpointer data,
                                                         gpointer user_data);
void                g_dataset_destroy                   (gconstpointer dataset_location);

Description

Datasets associate groups of data elements with particular memory locations. These are useful if you need to associate data with a structure returned from an external library. Since you cannot modify the structure, you use its location in memory as the key into a dataset, where you can associate any number of data elements with it.

There are two forms of most of the dataset functions. The first form uses strings to identify the data elements associated with a location. The second form uses GQuark identifiers, which are created with a call to g_quark_from_string() or g_quark_from_static_string(). The second form is quicker, since it does not require looking up the string in the hash table of GQuark identifiers.

There is no function to create a dataset. It is automatically created as soon as you add elements to it.

To add data elements to a dataset use g_dataset_id_set_data(), g_dataset_id_set_data_full(), g_dataset_set_data() and g_dataset_set_data_full().

To get data elements from a dataset use g_dataset_id_get_data() and g_dataset_get_data().

To iterate over all data elements in a dataset use g_dataset_foreach() (not thread-safe).

To remove data elements from a dataset use g_dataset_id_remove_data() and g_dataset_remove_data().

To destroy a dataset, use g_dataset_destroy().

Details

g_dataset_id_set_data()

#define             g_dataset_id_set_data(l, k, d)

Sets the data element associated with the given GQuark id. Any previous data with the same key is removed, and its destroy function is called.

l : | the location identifying the dataset.
k : | the GQuark id to identify the data element.
d : | the data element.

g_dataset_id_set_data_full ()

void                g_dataset_id_set_data_full          (gconstpointer dataset_location,
                                                         GQuark key_id,
                                                         gpointer data,
                                                         GDestroyNotify destroy_func);

Sets the data element associated with the given GQuark id, and also the function to call when the data element is destroyed. Any previous data with the same key is removed, and its destroy function is called.

dataset_location : | the location identifying the dataset.
key_id : | the GQuark id to identify the data element.
data : | the data element.
destroy_func : | the function to call when the data element is removed. This function will be called with the data element and can be used to free any memory allocated for it.

GDestroyNotify ()

void                (*GDestroyNotify)                   (gpointer data);

Specifies the type of function which is called when a data element is destroyed. It is passed the pointer to the data element and should free any memory and resources allocated for it.

data : the data element.

g_dataset_id_get_data ()

gpointer            g_dataset_id_get_data               (gconstpointer dataset_location,
                                                         GQuark key_id);

Gets the data element corresponding to a GQuark.

dataset_location : | the location identifying the dataset.
key_id : | the GQuark id to identify the data element.
Returns : | the data element corresponding to the GQuark, or NULL if it is not found.

g_dataset_id_remove_data()

#define             g_dataset_id_remove_data(l, k)

Removes a data element from a dataset. The data element's destroy function is called if it has been set.

l : | the location identifying the dataset.
k : | the GQuark id identifying the data element.

g_dataset_id_remove_no_notify ()

gpointer            g_dataset_id_remove_no_notify       (gconstpointer dataset_location,
                                                         GQuark key_id);

Removes an element, without calling its destroy notification function.

dataset_location : | the location identifying the dataset.
key_id : | the GQuark ID identifying the data element.
Returns : | the data previously stored at key_id, or NULL if none.

g_dataset_set_data()

#define             g_dataset_set_data(l, k, d)

Sets the data corresponding to the given string identifier.

l : | the location identifying the dataset.
k : | the string to identify the data element.
d : | the data element.

g_dataset_set_data_full()

#define             g_dataset_set_data_full(l, k, d, f)

Sets the data corresponding to the given string identifier, and the function to call when the data element is destroyed.

l : | the location identifying the dataset.
k : | the string to identify the data element.
d : | the data element.
f : | the function to call when the data element is removed. This function will be called with the data element and can be used to free any memory allocated for it.

g_dataset_get_data()

#define             g_dataset_get_data(l, k)

Gets the data element corresponding to a string.

l : | the location identifying the dataset.
k : | the string identifying the data element.
Returns : | the data element corresponding to the string, or NULL if it is not found.

g_dataset_remove_data()

#define             g_dataset_remove_data(l, k)

Removes a data element corresponding to a string. Its destroy function is called if it has been set.

l : | the location identifying the dataset.
k : | the string identifying the data element.

g_dataset_remove_no_notify()

#define             g_dataset_remove_no_notify(l, k)

Removes an element, without calling its destroy notifier.

l : | the location identifying the dataset.
k : | the string identifying the data element.

g_dataset_foreach ()

void                g_dataset_foreach                   (gconstpointer dataset_location,
                                                         GDataForeachFunc func,
                                                         gpointer user_data);

Calls the given function for each data element which is associated with the given location. Note that this function is NOT thread-safe. So unless datalist can be protected from any modifications during invocation of this function, it should not be called.

dataset_location : | the location identifying the dataset.
func : | the function to call for each data element.
user_data : | user data to pass to the function.

GDataForeachFunc ()

void                (*GDataForeachFunc)                 (GQuark key_id,
                                                         gpointer data,
                                                         gpointer user_data);

Specifies the type of function passed to g_dataset_foreach(). It is called with each GQuark id and associated data element, together with the user_data parameter supplied to g_dataset_foreach().

key_id : | the GQuark id to identifying the data element.
data : | the data element.
user_data : | user data passed to g_dataset_foreach().

g_dataset_destroy ()

void                g_dataset_destroy                   (gconstpointer dataset_location);

Destroys the dataset, freeing all memory allocated, and calling any destroy functions set for data elements.

dataset_location : the location identifying the dataset.


Date and Time Functions

Date and Time Functions — calendrical calculations and miscellaneous time stuff.

Synopsis

#include <glib.h>

#define             G_USEC_PER_SEC
                    GTimeVal;
void                g_get_current_time                  (GTimeVal *result);
void                g_usleep                            (gulong microseconds);
void                g_time_val_add                      (GTimeVal *time_,
                                                         glong microseconds);
gboolean            g_time_val_from_iso8601             (const gchar *iso_date,
                                                         GTimeVal *time_);
gchar*              g_time_val_to_iso8601               (GTimeVal *time_);

                    GDate;
typedef             GTime;
enum                GDateDMY;
typedef             GDateDay;
enum                GDateMonth;
typedef             GDateYear;
enum                GDateWeekday;

#define             G_DATE_BAD_DAY
#define             G_DATE_BAD_JULIAN
#define             G_DATE_BAD_YEAR

GDate*              g_date_new                          (void);
GDate*              g_date_new_dmy                      (GDateDay day,
                                                         GDateMonth month,
                                                         GDateYear year);
GDate*              g_date_new_julian                   (guint32 julian_day);
void                g_date_clear                        (GDate *date,
                                                         guint n_dates);
void                g_date_free                         (GDate *date);

void                g_date_set_day                      (GDate *date,
                                                         GDateDay day);
void                g_date_set_month                    (GDate *date,
                                                         GDateMonth month);
void                g_date_set_year                     (GDate *date,
                                                         GDateYear year);
void                g_date_set_dmy                      (GDate *date,
                                                         GDateDay day,
                                                         GDateMonth month,
                                                         GDateYear y);
void                g_date_set_julian                   (GDate *date,
                                                         guint32 julian_date);
void                g_date_set_time                     (GDate *date,
                                                         GTime time_);
void                g_date_set_time_t                   (GDate *date,
                                                         time_t timet);
void                g_date_set_time_val                 (GDate *date,
                                                         GTimeVal *timeval);
void                g_date_set_parse                    (GDate *date,
                                                         const gchar *str);

void                g_date_add_days                     (GDate *date,
                                                         guint n_days);
void                g_date_subtract_days                (GDate *date,
                                                         guint n_days);
void                g_date_add_months                   (GDate *date,
                                                         guint n_months);
void                g_date_subtract_months              (GDate *date,
                                                         guint n_months);
void                g_date_add_years                    (GDate *date,
                                                         guint n_years);
void                g_date_subtract_years               (GDate *date,
                                                         guint n_years);
gint                g_date_days_between                 (const GDate *date1,
                                                         const GDate *date2);
gint                g_date_compare                      (const GDate *lhs,
                                                         const GDate *rhs);
void                g_date_clamp                        (GDate *date,
                                                         const GDate *min_date,
                                                         const GDate *max_date);
void                g_date_order                        (GDate *date1,
                                                         GDate *date2);

GDateDay            g_date_get_day                      (const GDate *date);
GDateMonth          g_date_get_month                    (const GDate *date);
GDateYear           g_date_get_year                     (const GDate *date);
guint32             g_date_get_julian                   (const GDate *date);
GDateWeekday        g_date_get_weekday                  (const GDate *date);
guint               g_date_get_day_of_year              (const GDate *date);

guint8              g_date_get_days_in_month            (GDateMonth month,
                                                         GDateYear year);
gboolean            g_date_is_first_of_month            (const GDate *date);
gboolean            g_date_is_last_of_month             (const GDate *date);
gboolean            g_date_is_leap_year                 (GDateYear year);
guint               g_date_get_monday_week_of_year      (const GDate *date);
guint8              g_date_get_monday_weeks_in_year     (GDateYear year);
guint               g_date_get_sunday_week_of_year      (const GDate *date);
guint8              g_date_get_sunday_weeks_in_year     (GDateYear year);
guint               g_date_get_iso8601_week_of_year     (const GDate *date);

gsize               g_date_strftime                     (gchar *s,
                                                         gsize slen,
                                                         const gchar *format,
                                                         const GDate *date);
void                g_date_to_struct_tm                 (const GDate *date,
                                                         struct tm *tm);

gboolean            g_date_valid                        (const GDate *date);
gboolean            g_date_valid_day                    (GDateDay day);
gboolean            g_date_valid_month                  (GDateMonth month);
gboolean            g_date_valid_year                   (GDateYear year);
gboolean            g_date_valid_dmy                    (GDateDay day,
                                                         GDateMonth month,
                                                         GDateYear year);
gboolean            g_date_valid_julian                 (guint32 julian_date);
gboolean            g_date_valid_weekday                (GDateWeekday weekday);

Description

The GDate data structure represents a day between January 1, Year 1, and sometime a few thousand years in the future (right now it will go to the year 65535 or so, but g_date_set_parse() only parses up to the year 8000 or so - just count on "a few thousand"). GDate is meant to represent everyday dates, not astronomical dates or historical dates or ISO timestamps or the like. It extrapolates the current Gregorian calendar forward and backward in time; there is no attempt to change the calendar to match time periods or locations. GDate does not store time information; it represents a day.

The GDate implementation has several nice features; it is only a 64-bit struct, so storing large numbers of dates is very efficient. It can keep both a Julian and day-month-year representation of the date, since some calculations are much easier with one representation or the other. A Julian representation is simply a count of days since some fixed day in the past; for GDate the fixed day is January 1, 1 AD. ("Julian" dates in the GDate API aren't really Julian dates in the technical sense; technically, Julian dates count from the start of the Julian period, Jan 1, 4713 BC).

GDate is simple to use. First you need a "blank" date; you can get a dynamically allocated date from g_date_new(), or you can declare an automatic variable or array and initialize it to a sane state by calling g_date_clear(). A cleared date is sane; it's safe to call g_date_set_dmy() and the other mutator functions to initialize the value of a cleared date. However, a cleared date is initially invalid, meaning that it doesn't represent a day that exists. It is undefined to call any of the date calculation routines on an invalid date. If you obtain a date from a user or other unpredictable source, you should check its validity with the g_date_valid() predicate. g_date_valid() is also used to check for errors with g_date_set_parse() and other functions that can fail. Dates can be invalidated by calling g_date_clear() again.

It is very important to use the API to access the GDate struct. Often only the day-month-year or only the Julian representation is valid. Sometimes neither is valid. Use the API.

GLib doesn't contain any time-manipulation functions; however, there is a GTime typedef and a GTimeVal struct which represents a more precise time (with microseconds). You can request the current time as a GTimeVal with g_get_current_time().

Details

G_USEC_PER_SEC

#define G_USEC_PER_SEC 1000000

Number of microseconds in one second (1 million). This macro is provided for code readability.

GTimeVal

typedef struct {
  glong tv_sec;
  glong tv_usec;
} GTimeVal;

Represents a precise time, with seconds and microseconds. Similar to the struct timeval returned by the gettimeofday() UNIX call.

glong tv_sec; | seconds.
glong tv_usec; | microseconds.

g_get_current_time ()

void                g_get_current_time                  (GTimeVal *result);

Equivalent to the UNIX gettimeofday() function, but portable.

result : GTimeVal structure in which to store current time.

g_usleep ()

void                g_usleep                            (gulong microseconds);

Pauses the current thread for the given number of microseconds. There are 1 million microseconds per second (represented by the G_USEC_PER_SEC macro). g_usleep() may have limited precision, depending on hardware and operating system; don't rely on the exact length of the sleep.

microseconds : number of microseconds to pause.

g_time_val_add ()

void                g_time_val_add                      (GTimeVal *time_,
                                                         glong microseconds);

Adds the given number of microseconds to time_. microseconds can also be negative to decrease the value of time_.

time_ : | a GTimeVal
microseconds : | number of microseconds to add to time

g_time_val_from_iso8601 ()

gboolean            g_time_val_from_iso8601             (const gchar *iso_date,
                                                         GTimeVal *time_);

Converts a string containing an ISO 8601 encoded date and time to a GTimeVal and puts it into time_.

iso_date : | a ISO 8601 encoded date string
time_ : | a GTimeVal
Returns : | TRUE if the conversion was successful.

Since 2.12

g_time_val_to_iso8601 ()

gchar*              g_time_val_to_iso8601               (GTimeVal *time_);

Converts time_ into a ISO 8601 encoded string, relative to the Coordinated Universal Time (UTC).

time_ : | a GTimeVal
Returns : | a newly allocated string containing a ISO 8601 date

Since 2.12

GDate

typedef struct {
  guint julian_days : 32; /* julian days representation - we use a
                           *  bitfield hoping that 64 bit platforms
                           *  will pack this whole struct in one big
                           *  int
                           */

  guint julian : 1;    /* julian is valid */
  guint dmy    : 1;    /* dmy is valid */

  /* DMY representation */
  guint day    : 6;
  guint month  : 4;
  guint year   : 16;
} GDate;

Represents a day between January 1, Year 1 and a few thousand years in the future. None of its members should be accessed directly. If the GDate is obtained from g_date_new(), it will be safe to mutate but invalid and thus not safe for calendrical computations. If it's declared on the stack, it will contain garbage so must be initialized with g_date_clear(). g_date_clear() makes the date invalid but sane. An invalid date doesn't represent a day, it's "empty." A date becomes valid after you set it to a Julian day or you set a day, month, and year.

guint julian_days : 32; | the Julian representation of the date
guint julian : 1; | this bit is set if julian_days is valid
guint dmy : 1; | this is set if day, month and year are valid
guint day : 6; | the day of the day-month-year representation of the date, as a number between 1 and 31
guint month : 4; | the day of the day-month-year representation of the date, as a number between 1 and 12
guint year : 16; | the day of the day-month-year representation of the date

GTime

typedef gint32  GTime;

Simply a replacement for time_t. It has been deprected since it is not equivalent to time_t on 64-bit platforms with a 64-bit time_t. Unrelated to GTimer.

Note that GTime is defined to always be a 32bit integer, unlike time_t which may be 64bit on some systems. Therefore, GTime will overflow in the year 2038, and you cannot use the address of a GTime variable as argument to the UNIX time() function. Instead, do the following:

time_t ttime;
GTime gtime;

time (&ttime);
gtime = (GTime)ttime;

enum GDateDMY

typedef enum
{
  G_DATE_DAY   = 0,
  G_DATE_MONTH = 1,
  G_DATE_YEAR  = 2
} GDateDMY;

This enumeration isn't used in the API, but may be useful if you need to mark a number as a day, month, or year.

G_DATE_DAY | a day
G_DATE_MONTH | a month
G_DATE_YEAR | a year

GDateDay

typedef guint8  GDateDay;   /* day of the month */

Integer representing a day of the month; between 1 and 31. G_DATE_BAD_DAY represents an invalid day of the month.

enum GDateMonth

typedef enum
{
  G_DATE_BAD_MONTH = 0,
  G_DATE_JANUARY   = 1,
  G_DATE_FEBRUARY  = 2,
  G_DATE_MARCH     = 3,
  G_DATE_APRIL     = 4,
  G_DATE_MAY       = 5,
  G_DATE_JUNE      = 6,
  G_DATE_JULY      = 7,
  G_DATE_AUGUST    = 8,
  G_DATE_SEPTEMBER = 9,
  G_DATE_OCTOBER   = 10,
  G_DATE_NOVEMBER  = 11,
  G_DATE_DECEMBER  = 12
} GDateMonth;

Enumeration representing a month; values are G_DATE_JANUARY, G_DATE_FEBRUARY, etc. G_DATE_BAD_MONTH is the invalid value.

G_DATE_BAD_MONTH | invalid value.
G_DATE_JANUARY | January.
G_DATE_FEBRUARY | February.
G_DATE_MARCH | March.
G_DATE_APRIL | April.
G_DATE_MAY | May.
G_DATE_JUNE | June.
G_DATE_JULY | July.
G_DATE_AUGUST | August.
G_DATE_SEPTEMBER | September.
G_DATE_OCTOBER | October.
G_DATE_NOVEMBER | November.
G_DATE_DECEMBER | December.

GDateYear

typedef guint16 GDateYear;

Integer representing a year; G_DATE_BAD_YEAR is the invalid value. The year must be 1 or higher; negative (BC) years are not allowed. The year is represented with four digits.

enum GDateWeekday

typedef enum
{
  G_DATE_BAD_WEEKDAY  = 0,
  G_DATE_MONDAY       = 1,
  G_DATE_TUESDAY      = 2,
  G_DATE_WEDNESDAY    = 3,
  G_DATE_THURSDAY     = 4,
  G_DATE_FRIDAY       = 5,
  G_DATE_SATURDAY     = 6,
  G_DATE_SUNDAY       = 7
} GDateWeekday;

Enumeration representing a day of the week; G_DATE_MONDAY, G_DATE_TUESDAY, etc. G_DATE_BAD_WEEKDAY is an invalid weekday.

G_DATE_BAD_WEEKDAY | invalid value.
G_DATE_MONDAY | Monday.
G_DATE_TUESDAY | Tuesday.
G_DATE_WEDNESDAY | Wednesday.
G_DATE_THURSDAY | Thursday.
G_DATE_FRIDAY | Friday.
G_DATE_SATURDAY | Saturday.
G_DATE_SUNDAY | Sunday.

G_DATE_BAD_DAY

#define G_DATE_BAD_DAY    0U

Represents an invalid GDateDay.

G_DATE_BAD_JULIAN

#define G_DATE_BAD_JULIAN 0U

Represents an invalid Julian day number.

G_DATE_BAD_YEAR

#define G_DATE_BAD_YEAR   0U

Represents an invalid year.

g_date_new ()

GDate*              g_date_new                          (void);

Allocates a GDate and initializes it to a sane state. The new date will be cleared (as if you'd called g_date_clear()) but invalid (it won't represent an existing day). Free the return value with g_date_free().

Returns : a newly-allocated GDate.

g_date_new_dmy ()

GDate*              g_date_new_dmy                      (GDateDay day,
                                                         GDateMonth month,
                                                         GDateYear year);

Like g_date_new(), but also sets the value of the date. Assuming the day-month-year triplet you pass in represents an existing day, the returned date will be valid.

day : | day of the month.
month : | month of the year.
year : | year
Returns : | a newly-allocated GDate initialized with day, month, and year.

g_date_new_julian ()

GDate*              g_date_new_julian                   (guint32 julian_day);

Like g_date_new(), but also sets the value of the date. Assuming the Julian day number you pass in is valid (greater than 0, less than an unreasonably large number), the returned date will be valid.

julian_day : | days since January 1, Year 1.
Returns : | a newly-allocated GDate initialized with julian_day.

g_date_clear ()

void                g_date_clear                        (GDate *date,
                                                         guint n_dates);

Initializes one or more GDate structs to a sane but invalid state. The cleared dates will not represent an existing date, but will not contain garbage. Useful to init a date declared on the stack. Validity can be tested with g_date_valid().

date : | pointer to one or more dates to clear.
n_dates : | number of dates to clear.

g_date_free ()

void                g_date_free                         (GDate *date);

Frees a GDate returned from g_date_new().

date : a GDate.

g_date_set_day ()

void                g_date_set_day                      (GDate *date,
                                                         GDateDay day);

Sets the day of the month for a GDate. If the resulting day-month-year triplet is invalid, the date will be invalid.

date : | a GDate.
day : | day to set.

g_date_set_month ()

void                g_date_set_month                    (GDate *date,
                                                         GDateMonth month);

Sets the month of the year for a GDate. If the resulting day-month-year triplet is invalid, the date will be invalid.

date : | a GDate.
month : | month to set.

g_date_set_year ()

void                g_date_set_year                     (GDate *date,
                                                         GDateYear year);

Sets the year for a GDate. If the resulting day-month-year triplet is invalid, the date will be invalid.

date : | a GDate.
year : | year to set.

g_date_set_dmy ()

void                g_date_set_dmy                      (GDate *date,
                                                         GDateDay day,
                                                         GDateMonth month,
                                                         GDateYear y);

Sets the value of a GDate from a day, month, and year. The day-month-year triplet must be valid; if you aren't sure it is, call g_date_valid_dmy() to check before you set it.

date : | a GDate.
day : | day.
month : | month.
y : | year.

g_date_set_julian ()

void                g_date_set_julian                   (GDate *date,
                                                         guint32 julian_date);

Sets the value of a GDate from a Julian day number.

date : | a GDate.
julian_date : | Julian day number (days since January 1, Year 1).

g_date_set_time ()

void                g_date_set_time                     (GDate *date,
                                                         GTime time_);

Warning

g_date_set_time is deprecated and should not be used in newly-written code.

Sets the value of a date from a GTime value.

Deprecated:2.10: Use g_date_set_time_t() instead.

date : | a GDate.
time_ : | GTime value to set.

g_date_set_time_t ()

void                g_date_set_time_t                   (GDate *date,
                                                         time_t timet);

Sets the value of a date from a time_t value.

To set the value of a date to the current day, you could write:

 g_date_set_time_t (date, time (NULL));

date : | a GDate
timet : | time_t value to set

Since 2.10

g_date_set_time_val ()

void                g_date_set_time_val                 (GDate *date,
                                                         GTimeVal *timeval);

Sets the value of a date from a GTimeVal value. Note that the tv_usec member is ignored, because GDate can't make use of the additional precision.

date : | a GDate
timeval : | GTimeVal value to set

Since 2.10

g_date_set_parse ()

void                g_date_set_parse                    (GDate *date,
                                                         const gchar *str);

Parses a user-inputted string str, and try to figure out what date it represents, taking the current locale into account. If the string is successfully parsed, the date will be valid after the call. Otherwise, it will be invalid. You should check using g_date_valid() to see whether the parsing succeeded.

This function is not appropriate for file formats and the like; it isn't very precise, and its exact behavior varies with the locale. It's intended to be a heuristic routine that guesses what the user means by a given string (and it does work pretty well in that capacity).

date : | a GDate to fill in.
str : | string to parse.

g_date_add_days ()

void                g_date_add_days                     (GDate *date,
                                                         guint n_days);

Increments a date some number of days. To move forward by weeks, add weeks*7 days. The date must be valid.

date : | a GDate to increment.
n_days : | number of days to move the date forward.

g_date_subtract_days ()

void                g_date_subtract_days                (GDate *date,
                                                         guint n_days);

Moves a date some number of days into the past. To move by weeks, just move by weeks*7 days. The date must be valid.

date : | a GDate to decrement.
n_days : | number of days to move.

g_date_add_months ()

void                g_date_add_months                   (GDate *date,
                                                         guint n_months);

Increments a date by some number of months. If the day of the month is greater than 28, this routine may change the day of the month (because the destination month may not have the current day in it). The date must be valid.

date : | a GDate to increment.
n_months : | number of months to move forward.

g_date_subtract_months ()

void                g_date_subtract_months              (GDate *date,
                                                         guint n_months);

Moves a date some number of months into the past. If the current day of the month doesn't exist in the destination month, the day of the month may change. The date must be valid.

date : | a GDate to decrement.
n_months : | number of months to move.

g_date_add_years ()

void                g_date_add_years                    (GDate *date,
                                                         guint n_years);

Increments a date by some number of years. If the date is February 29, and the destination year is not a leap year, the date will be changed to February 28. The date must be valid.

date : | a GDate to increment.
n_years : | number of years to move forward.

g_date_subtract_years ()

void                g_date_subtract_years               (GDate *date,
                                                         guint n_years);

Moves a date some number of years into the past. If the current day doesn't exist in the destination year (i.e. it's February 29 and you move to a non-leap-year) then the day is changed to February 29. The date must be valid.

date : | a GDate to decrement.
n_years : | number of years to move.

g_date_days_between ()

gint                g_date_days_between                 (const GDate *date1,
                                                         const GDate *date2);

Computes the number of days between two dates. If date2 is prior to date1, the returned value is negative. Both dates must be valid.

date1 : | the first date.
date2 : | the second date.
Returns : | the number of days between date1 and date2.

g_date_compare ()

gint                g_date_compare                      (const GDate *lhs,
                                                         const GDate *rhs);

qsort()-style comparsion function for dates. Both dates must be valid.

lhs : | first date to compare.
rhs : | second date to compare.
Returns : | 0 for equal, less than zero if lhs is less than rhs, greater than zero if lhs is greater than rhs.

g_date_clamp ()

void                g_date_clamp                        (GDate *date,
                                                         const GDate *min_date,
                                                         const GDate *max_date);

If date is prior to min_date, sets date equal to min_date. If date falls after max_date, sets date equal to max_date. Either min_date and max_date may be NULL. All non-NULL dates must be valid.

date : | a GDate to clamp.
min_date : | minimum accepted value for date.
max_date : | maximum accepted value for date.

g_date_order ()

void                g_date_order                        (GDate *date1,
                                                         GDate *date2);

Checks if date1 is less than or equal to date2, and swap the values if this is not the case.

date1 : | the first date.
date2 : | the second date.

g_date_get_day ()

GDateDay            g_date_get_day                      (const GDate *date);

Returns the day of the month. The date must be valid.

date : | a GDate to extract the day of the month from.
Returns : | day of the month.

g_date_get_month ()

GDateMonth          g_date_get_month                    (const GDate *date);

Returns the month of the year. The date must be valid.

date : | a GDate to get the month from.
Returns : | month of the year as a GDateMonth.

g_date_get_year ()

GDateYear           g_date_get_year                     (const GDate *date);

Returns the year of a GDate. The date must be valid.

date : | a GDate.
Returns : | year in which the date falls.

g_date_get_julian ()

guint32             g_date_get_julian                   (const GDate *date);

Returns the Julian day or "serial number" of the GDate. The Julian day is simply the number of days since January 1, Year 1; i.e., January 1, Year 1 is Julian day 1; January 2, Year 1 is Julian day 2, etc. The date must be valid.

date : | a GDate to extract the Julian day from.
Returns : | Julian day.

g_date_get_weekday ()

GDateWeekday        g_date_get_weekday                  (const GDate *date);

Returns the day of the week for a GDate. The date must be valid.

date : | a GDate.
Returns : | day of the week as a GDateWeekday.

g_date_get_day_of_year ()

guint               g_date_get_day_of_year              (const GDate *date);

Returns the day of the year, where Jan 1 is the first day of the year. The date must be valid.

date : | a GDate to extract day of year from.
Returns : | day of the year.

g_date_get_days_in_month ()

guint8              g_date_get_days_in_month            (GDateMonth month,
                                                         GDateYear year);

Returns the number of days in a month, taking leap years into account.

month : | month.
year : | year.
Returns : | number of days in month during the year.

g_date_is_first_of_month ()

gboolean            g_date_is_first_of_month            (const GDate *date);

Returns TRUE if the date is on the first of a month. The date must be valid.

date : | a GDate to check.
Returns : | TRUE if the date is the first of the month.

g_date_is_last_of_month ()

gboolean            g_date_is_last_of_month             (const GDate *date);

Returns TRUE if the date is the last day of the month. The date must be valid.

date : | a GDate to check.
Returns : | TRUE if the date is the last day of the month.

g_date_is_leap_year ()

gboolean            g_date_is_leap_year                 (GDateYear year);

Returns TRUE if the year is a leap year.

year : | year to check.
Returns : | TRUE if the year is a leap year.

g_date_get_monday_week_of_year ()

guint               g_date_get_monday_week_of_year      (const GDate *date);

Returns the week of the year, where weeks are understood to start on Monday. If the date is before the first Monday of the year, return 0. The date must be valid.

date : | a GDate.
Returns : | week of the year.

g_date_get_monday_weeks_in_year ()

guint8              g_date_get_monday_weeks_in_year     (GDateYear year);

Returns the number of weeks in the year, where weeks are taken to start on Monday. Will be 52 or 53. The date must be valid. (Years always have 52 7-day periods, plus 1 or 2 extra days depending on whether it's a leap year. This function is basically telling you how many Mondays are in the year, i.e. there are 53 Mondays if one of the extra days happens to be a Monday.)

year : | a year.
Returns : | number of Mondays in the year.

g_date_get_sunday_week_of_year ()

guint               g_date_get_sunday_week_of_year      (const GDate *date);

Returns the week of the year during which this date falls, if weeks are understood to being on Sunday. The date must be valid. Can return 0 if the day is before the first Sunday of the year.

date : | a GDate.
Returns : | week number.

g_date_get_sunday_weeks_in_year ()

guint8              g_date_get_sunday_weeks_in_year     (GDateYear year);

Returns the number of weeks in the year, where weeks are taken to start on Sunday. Will be 52 or 53. The date must be valid. (Years always have 52 7-day periods, plus 1 or 2 extra days depending on whether it's a leap year. This function is basically telling you how many Sundays are in the year, i.e. there are 53 Sundays if one of the extra days happens to be a Sunday.)

year : | year to count weeks in.
Returns : | number of weeks.

g_date_get_iso8601_week_of_year ()

guint               g_date_get_iso8601_week_of_year     (const GDate *date);

Returns the week of the year, where weeks are interpreted according to ISO 8601.

date : | a valid GDate
Returns : | ISO 8601 week number of the year.

Since 2.6

g_date_strftime ()

gsize               g_date_strftime                     (gchar *s,
                                                         gsize slen,
                                                         const gchar *format,
                                                         const GDate *date);

Generates a printed representation of the date, in a locale-specific way. Works just like the platform's C library strftime() function, but only accepts date-related formats; time-related formats give undefined results. Date must be valid. Unlike strftime() (which uses the locale encoding), works on a UTF-8 format string and stores a UTF-8 result.

This function does not provide any conversion specifiers in addition to those implemented by the platform's C library. For example, don't expect that using g_date_strftime() would make the F provided by the C99 strftime() work on Windows where the C library only complies to C89.

s : | destination buffer.
slen : | buffer size.
format : | format string.
date : | valid GDate.
Returns : | number of characters written to the buffer, or 0 the buffer was too small.

g_date_to_struct_tm ()

void                g_date_to_struct_tm                 (const GDate *date,
                                                         struct tm *tm);

Fills in the date-related bits of a struct tm using the date value. Initializes the non-date parts with something sane but meaningless.

date : | a GDate to set the struct tm from.
tm : | struct tm to fill.

g_date_valid ()

gboolean            g_date_valid                        (const GDate *date);

Returns TRUE if the GDate represents an existing day. The date must not contain garbage; it should have been initialized with g_date_clear() if it wasn't allocated by one of the g_date_new() variants.

date : | a GDate to check.
Returns : | Whether the date is valid.

g_date_valid_day ()

gboolean            g_date_valid_day                    (GDateDay day);

Returns TRUE if the day of the month is valid (a day is valid if it's between 1 and 31 inclusive).

day : | day to check.
Returns : | TRUE if the day is valid.

g_date_valid_month ()

gboolean            g_date_valid_month                  (GDateMonth month);

Returns TRUE if the month value is valid. The 12 GDateMonth enumeration values are the only valid months.

month : | month.
Returns : | TRUE if the month is valid.

g_date_valid_year ()

gboolean            g_date_valid_year                   (GDateYear year);

Returns TRUE if the year is valid. Any year greater than 0 is valid, though there is a 16-bit limit to what GDate will understand.

year : | year.
Returns : | TRUE if the year is valid.

g_date_valid_dmy ()

gboolean            g_date_valid_dmy                    (GDateDay day,
                                                         GDateMonth month,
                                                         GDateYear year);

Returns TRUE if the day-month-year triplet forms a valid, existing day in the range of days GDate understands (Year 1 or later, no more than a few thousand years in the future).

day : | day.
month : | month.
year : | year.
Returns : | TRUE if the date is a valid one.

g_date_valid_julian ()

gboolean            g_date_valid_julian                 (guint32 julian_date);

Returns TRUE if the Julian day is valid. Anything greater than zero is basically a valid Julian, though there is a 32-bit limit.

julian_date : | Julian day to check.
Returns : | TRUE if the Julian day is valid.

g_date_valid_weekday ()

gboolean            g_date_valid_weekday                (GDateWeekday weekday);

Returns TRUE if the weekday is valid. The 7 GDateWeekday enumeration values are the only valid weekdays.

weekday : | weekday.
Returns : | TRUE if the weekday is valid.


Double-ended Queues

Double-ended Queues — double-ended queue data structure.

Synopsis

#include <glib.h>

                    GQueue;
GQueue*             g_queue_new                         (void);
void                g_queue_free                        (GQueue *queue);
gboolean            g_queue_is_empty                    (GQueue *queue);
guint               g_queue_get_length                  (GQueue *queue);
void                g_queue_reverse                     (GQueue *queue);
GQueue*             g_queue_copy                        (GQueue *queue);
void                g_queue_foreach                     (GQueue *queue,
                                                         GFunc func,
                                                         gpointer user_data);
GList*              g_queue_find                        (GQueue *queue,
                                                         gconstpointer data);
GList*              g_queue_find_custom                 (GQueue *queue,
                                                         gconstpointer data,
                                                         GCompareFunc func);
void                g_queue_sort                        (GQueue *queue,
                                                         GCompareDataFunc compare_func,
                                                         gpointer user_data);
void                g_queue_push_head                   (GQueue *queue,
                                                         gpointer data);
void                g_queue_push_tail                   (GQueue *queue,
                                                         gpointer data);
void                g_queue_push_nth                    (GQueue *queue,
                                                         gpointer data,
                                                         gint n);
gpointer            g_queue_pop_head                    (GQueue *queue);
gpointer            g_queue_pop_tail                    (GQueue *queue);
gpointer            g_queue_pop_nth                     (GQueue *queue,
                                                         guint n);
gpointer            g_queue_peek_head                   (GQueue *queue);
gpointer            g_queue_peek_tail                   (GQueue *queue);
gpointer            g_queue_peek_nth                    (GQueue *queue,
                                                         guint n);
gint                g_queue_index                       (GQueue *queue,
                                                         gconstpointer data);
void                g_queue_remove                      (GQueue *queue,
                                                         gconstpointer data);
void                g_queue_remove_all                  (GQueue *queue,
                                                         gconstpointer data);
void                g_queue_insert_before               (GQueue *queue,
                                                         GList *sibling,
                                                         gpointer data);
void                g_queue_insert_after                (GQueue *queue,
                                                         GList *sibling,
                                                         gpointer data);
void                g_queue_insert_sorted               (GQueue *queue,
                                                         gpointer data,
                                                         GCompareDataFunc func,
                                                         gpointer user_data);
void                g_queue_push_head_link              (GQueue *queue,
                                                         GList *link_);
void                g_queue_push_tail_link              (GQueue *queue,
                                                         GList *link_);
void                g_queue_push_nth_link               (GQueue *queue,
                                                         gint n,
                                                         GList *link_);
GList*              g_queue_pop_head_link               (GQueue *queue);
GList*              g_queue_pop_tail_link               (GQueue *queue);
GList*              g_queue_pop_nth_link                (GQueue *queue,
                                                         guint n);
GList*              g_queue_peek_head_link              (GQueue *queue);
GList*              g_queue_peek_tail_link              (GQueue *queue);
GList*              g_queue_peek_nth_link               (GQueue *queue,
                                                         guint n);
gint                g_queue_link_index                  (GQueue *queue,
                                                         GList *link_);
void                g_queue_unlink                      (GQueue *queue,
                                                         GList *link_);
void                g_queue_delete_link                 (GQueue *queue,
                                                         GList *link_);

Description

The GQueue structure and its associated functions provide a standard queue data structure. Internally, GQueue uses the same data structure as GList to store elements.

The data contained in each element can be either integer values, by using one of the Type Conversion Macros, or simply pointers to any type of data.

To create a new GQueue, use g_queue_new().

To add elements, use g_queue_push_head(), g_queue_push_head_link(), g_queue_push_tail() and g_queue_push_tail_link().

To remove elements, use g_queue_pop_head() and g_queue_pop_tail().

To free the entire queue, use g_queue_free().

Details

GQueue

typedef struct {
  GList *head;
  GList *tail;
  guint  length;
} GQueue;

Contains the public fields of a Queue.

GList *head; | a pointer to the first element of the queue.
GList *tail; | a pointer to the last element of the queue.
guint length; | the number of elements in the queue.

g_queue_new ()

GQueue*             g_queue_new                         (void);

Creates a new GQueue.

Returns : a new GQueue.

g_queue_free ()

void                g_queue_free                        (GQueue *queue);

Frees the memory allocated for the GQueue.

queue : a GQueue.

g_queue_is_empty ()

gboolean            g_queue_is_empty                    (GQueue *queue);

Returns TRUE if the queue is empty.

queue : | a GQueue.
Returns : | TRUE if the queue is empty.

g_queue_get_length ()

guint               g_queue_get_length                  (GQueue *queue);

Returns the number of items in queue.

queue : | a GQueue
Returns : | The number of items in queue.

Since 2.4

g_queue_reverse ()

void                g_queue_reverse                     (GQueue *queue);

Reverses the order of the items in queue.

queue : a GQueue

Since 2.4

g_queue_copy ()

GQueue*             g_queue_copy                        (GQueue *queue);

Copies a queue. Note that is a shallow copy. If the elements in the queue consist of pointers to data, the pointers are copied, but the actual data is not.

queue : | a GQueue
Returns : | A copy of queue

Since 2.4

g_queue_foreach ()

void                g_queue_foreach                     (GQueue *queue,
                                                         GFunc func,
                                                         gpointer user_data);

Calls func for each element in the queue passing user_data to the function.

queue : | a GQueue
func : | the function to call for each element's data
user_data : | user data to pass to func

Since 2.4

g_queue_find ()

GList*              g_queue_find                        (GQueue *queue,
                                                         gconstpointer data);

Finds the first link in queue which contains data.

queue : | a GQueue
data : | data to find
Returns : | The first link in queue which contains data.

Since 2.4

g_queue_find_custom ()

GList*              g_queue_find_custom                 (GQueue *queue,
                                                         gconstpointer data,
                                                         GCompareFunc func);

Finds an element in a GQueue, using a supplied function to find the desired element. It iterates over the queue, calling the given function which should return 0 when the desired element is found. The function takes two gconstpointer arguments, the GQueue element's data as the first argument and the given user data as the second argument.

queue : | a GQueue
data : | user data passed to func
func : | a GCompareFunc to call for each element. It should return 0 when the desired element is found
Returns : | The found link, or NULL if it wasn't found

Since 2.4

g_queue_sort ()

void                g_queue_sort                        (GQueue *queue,
                                                         GCompareDataFunc compare_func,
                                                         gpointer user_data);

Sorts queue using compare_func.

queue : | a GQueue
compare_func : | the GCompareDataFunc used to sort queue. This function is passed two elements of the queue and should return 0 if they are equal, a negative value if the first comes before the second, and a positive value if the second comes before the first.
user_data : | user data passed to compare_func

Since 2.4

g_queue_push_head ()

void                g_queue_push_head                   (GQueue *queue,
                                                         gpointer data);

Adds a new element at the head of the queue.

queue : | a GQueue.
data : | the data for the new element.

g_queue_push_tail ()

void                g_queue_push_tail                   (GQueue *queue,
                                                         gpointer data);

Adds a new element at the tail of the queue.

queue : | a GQueue.
data : | the data for the new element.

g_queue_push_nth ()

void                g_queue_push_nth                    (GQueue *queue,
                                                         gpointer data,
                                                         gint n);

Inserts a new element into queue at the given position

queue : | a GQueue
data : | the data for the new element
n : | the position to insert the new element. If n is negative or larger than the number of elements in the queue, the element is added to the end of the queue.

Since 2.4

g_queue_pop_head ()

gpointer            g_queue_pop_head                    (GQueue *queue);

Removes the first element of the queue.

queue : | a GQueue.
Returns : | the data of the first element in the queue, or NULL if the queue is empty.

g_queue_pop_tail ()

gpointer            g_queue_pop_tail                    (GQueue *queue);

Removes the last element of the queue.

queue : | a GQueue.
Returns : | the data of the last element in the queue, or NULL if the queue is empty.

g_queue_pop_nth ()

gpointer            g_queue_pop_nth                     (GQueue *queue,
                                                         guint n);

Removes the n'th element of queue.

queue : | a GQueue
n : | the position of the element.
Returns : | the element's data, or NULL if n is off the end of queue.

Since 2.4

g_queue_peek_head ()

gpointer            g_queue_peek_head                   (GQueue *queue);

Returns the first element of the queue.

queue : | a GQueue.
Returns : | the data of the first element in the queue, or NULL if the queue is empty.

g_queue_peek_tail ()

gpointer            g_queue_peek_tail                   (GQueue *queue);

Returns the last element of the queue.

queue : | a GQueue.
Returns : | the data of the last element in the queue, or NULL if the queue is empty.

g_queue_peek_nth ()

gpointer            g_queue_peek_nth                    (GQueue *queue,
                                                         guint n);

Returns the n'th element of queue.

queue : | a GQueue
n : | the position of the element.
Returns : | The data for the n'th element of queue, or NULL if n is off the end of queue.

Since 2.4

g_queue_index ()

gint                g_queue_index                       (GQueue *queue,
                                                         gconstpointer data);

Returns the position of the first element in queue which contains data.

queue : | a GQueue
data : | the data to find.
Returns : | The position of the first element in queue which contains data, or -1 if no element in queue contains data.

Since 2.4

g_queue_remove ()

void                g_queue_remove                      (GQueue *queue,
                                                         gconstpointer data);

Removes the first element in queue that contains data.

queue : | a GQueue
data : | data to remove.

Since 2.4

g_queue_remove_all ()

void                g_queue_remove_all                  (GQueue *queue,
                                                         gconstpointer data);

Remove all elemeents in queue which contains data.

queue : | a GQueue
data : | data to remove

Since 2.4

g_queue_insert_before ()

void                g_queue_insert_before               (GQueue *queue,
                                                         GList *sibling,
                                                         gpointer data);

Inserts data into queue before sibling.

sibling must be part of queue.

queue : | a GQueue
sibling : | a GList link that must be part of queue
data : | the data to insert

Since 2.4

g_queue_insert_after ()

void                g_queue_insert_after                (GQueue *queue,
                                                         GList *sibling,
                                                         gpointer data);

Inserts data into queue after sibling

sibling must be part of queue

queue : | a GQueue
sibling : | a GList link that must be part of queue
data : | the data to insert

Since 2.4

g_queue_insert_sorted ()

void                g_queue_insert_sorted               (GQueue *queue,
                                                         gpointer data,
                                                         GCompareDataFunc func,
                                                         gpointer user_data);

Inserts data into queue using func to determine the new position.

queue : | a GQueue
data : | the data to insert
func : | the GCompareDataFunc used to compare elements in the queue. It is called with two elements of the queue and user_data. It should return 0 if the elements are equal, a negative value if the first element comes before the second, and a positive value if the second element comes before the first.
user_data : | user data passed to func.

Since 2.4

g_queue_push_head_link ()

void                g_queue_push_head_link              (GQueue *queue,
                                                         GList *link_);

Adds a new element at the head of the queue.

queue : | a GQueue.
link_ : | a single GList element, not a list with more than one element.

g_queue_push_tail_link ()

void                g_queue_push_tail_link              (GQueue *queue,
                                                         GList *link_);

Adds a new element at the tail of the queue.

queue : | a GQueue.
link_ : | a single GList element, not a list with more than one element.

g_queue_push_nth_link ()

void                g_queue_push_nth_link               (GQueue *queue,
                                                         gint n,
                                                         GList *link_);

Inserts link into queue at the given position.

queue : | a GQueue
n : | the position to insert the link. If this is negative or larger than the number of elements in queue, the link is added to the end of queue.
link_ : | the link to add to queue

Since 2.4

g_queue_pop_head_link ()

GList*              g_queue_pop_head_link               (GQueue *queue);

Removes the first element of the queue.

queue : | a GQueue.
Returns : | the GList element at the head of the queue, or NULL if the queue is empty.

g_queue_pop_tail_link ()

GList*              g_queue_pop_tail_link               (GQueue *queue);

Removes the last element of the queue.

queue : | a GQueue.
Returns : | the GList element at the tail of the queue, or NULL if the queue is empty.

g_queue_pop_nth_link ()

GList*              g_queue_pop_nth_link                (GQueue *queue,
                                                         guint n);

Removes and returns the link at the given position.

queue : | a GQueue
n : | the link's position
Returns : | The n'th link, or NULL if n is off the end of queue.

Since 2.4

g_queue_peek_head_link ()

GList*              g_queue_peek_head_link              (GQueue *queue);

Returns the first link in queue

queue : | a GQueue
Returns : | the first link in queue, or NULL if queue is empty

Since 2.4

g_queue_peek_tail_link ()

GList*              g_queue_peek_tail_link              (GQueue *queue);

Returns the last link queue.

queue : | a GQueue
Returns : | the last link in queue, or NULL if queue is empty

Since 2.4

g_queue_peek_nth_link ()

GList*              g_queue_peek_nth_link               (GQueue *queue,
                                                         guint n);

Returns the link at the given position

queue : | a GQueue
n : | the position of the link
Returns : | The link at the n'th position, or NULL if n is off the end of the list

Since 2.4

g_queue_link_index ()

gint                g_queue_link_index                  (GQueue *queue,
                                                         GList *link_);

Returns the position of link_ in queue.

queue : | a Gqueue
link_ : | A GList link
Returns : | The position of link_, or -1 if the link is not part of queue

Since 2.4

g_queue_unlink ()

void                g_queue_unlink                      (GQueue *queue,
                                                         GList *link_);

Unlinks link_ so that it will no longer be part of queue. The link is not freed.

link_ must be part of queue,

queue : | a GQueue
link_ : | a GList link that must be part of queue

Since 2.4

g_queue_delete_link ()

void                g_queue_delete_link                 (GQueue *queue,
                                                         GList *link_);

Removes link_ from queue and frees it.

link_ must be part of queue.

queue : | a GQueue
link_ : | a GList link that must be part of queue

Since 2.4


Doubly-Linked Lists

Doubly-Linked Lists — linked lists containing integer values or pointers to data, with the ability to iterate over the list in both directions.

Synopsis

#include <glib.h>

                    GList;

GList*              g_list_append                       (GList *list,
                                                         gpointer data);
GList*              g_list_prepend                      (GList *list,
                                                         gpointer data);
GList*              g_list_insert                       (GList *list,
                                                         gpointer data,
                                                         gint position);
GList*              g_list_insert_before                (GList *list,
                                                         GList *sibling,
                                                         gpointer data);
GList*              g_list_insert_sorted                (GList *list,
                                                         gpointer data,
                                                         GCompareFunc func);
GList*              g_list_remove                       (GList *list,
                                                         gconstpointer data);
GList*              g_list_remove_link                  (GList *list,
                                                         GList *llink);
GList*              g_list_delete_link                  (GList *list,
                                                         GList *link_);
GList*              g_list_remove_all                   (GList *list,
                                                         gconstpointer data);
void                g_list_free                         (GList *list);

GList*              g_list_alloc                        (void);
void                g_list_free_1                       (GList *list);
#define             g_list_free1

guint               g_list_length                       (GList *list);
GList*              g_list_copy                         (GList *list);
GList*              g_list_reverse                      (GList *list);
GList*              g_list_sort                         (GList *list,
                                                         GCompareFunc compare_func);
gint                (*GCompareFunc)                     (gconstpointer a,
                                                         gconstpointer b);
GList*              g_list_insert_sorted_with_data      (GList *list,
                                                         gpointer data,
                                                         GCompareDataFunc func,
                                                         gpointer user_data);
GList*              g_list_sort_with_data               (GList *list,
                                                         GCompareDataFunc compare_func,
                                                         gpointer user_data);
gint                (*GCompareDataFunc)                 (gconstpointer a,
                                                         gconstpointer b,
                                                         gpointer user_data);
GList*              g_list_concat                       (GList *list1,
                                                         GList *list2);
void                g_list_foreach                      (GList *list,
                                                         GFunc func,
                                                         gpointer user_data);
void                (*GFunc)                            (gpointer data,
                                                         gpointer user_data);

GList*              g_list_first                        (GList *list);
GList*              g_list_last                         (GList *list);
#define             g_list_previous                     (list)
#define             g_list_next                         (list)
GList*              g_list_nth                          (GList *list,
                                                         guint n);
gpointer            g_list_nth_data                     (GList *list,
                                                         guint n);
GList*              g_list_nth_prev                     (GList *list,
                                                         guint n);

GList*              g_list_find                         (GList *list,
                                                         gconstpointer data);
GList*              g_list_find_custom                  (GList *list,
                                                         gconstpointer data,
                                                         GCompareFunc func);
gint                g_list_position                     (GList *list,
                                                         GList *llink);
gint                g_list_index                        (GList *list,
                                                         gconstpointer data);

void                g_list_push_allocator               (gpointer allocator);
void                g_list_pop_allocator                (void);

Description

The GList structure and its associated functions provide a standard doubly-linked list data structure.

Each element in the list contains a piece of data, together with pointers which link to the previous and next elements in the list. Using these pointers it is possible to move through the list in both directions (unlike the Singly-Linked Lists which only allows movement through the list in the forward direction).

The data contained in each element can be either integer values, by using one of the Type Conversion Macros, or simply pointers to any type of data.

List elements are allocated from the slice allocator, which is more efficient than allocating elements individually.

Note that most of the GList functions expect to be passed a pointer to the first element in the list. The functions which insert elements return the new start of the list, which may have changed.

There is no function to create a GList. NULL is considered to be the empty list so you simply set a GList* to NULL.

To add elements, use g_list_append(), g_list_prepend(), g_list_insert() and g_list_insert_sorted().

To remove elements, use g_list_remove().

To find elements in the list use g_list_first(), g_list_last(), g_list_next(), g_list_previous(), g_list_nth(), g_list_nth_data(), g_list_find() and g_list_find_custom().

To find the index of an element use g_list_position() and g_list_index().

To call a function for each element in the list use g_list_foreach().

To free the entire list, use g_list_free().

Details

GList

typedef struct {
  gpointer data;
  GList *next;
  GList *prev;
} GList;

The GList struct is used for each element in a doubly-linked list.

gpointer data; | holds the element's data, which can be a pointer to any kind of data, or any integer value using the Type Conversion Macros.
GList *next; | contains the link to the next element in the list.
GList *prev; | contains the link to the previous element in the list.

g_list_append ()

GList*              g_list_append                       (GList *list,
                                                         gpointer data);

Adds a new element on to the end of the list.

Note

The return value is the new start of the list, which may have changed, so make sure you store the new value.

Note

Note that g_list_append() has to traverse the entire list to find the end, which is inefficient when adding multiple elements. A common idiom to avoid the inefficiency is to prepend the elements and reverse the list when all elements have been added.

  /* Notice that these are initialized to the empty list. */
  GList *list = NULL, *number_list = NULL;

  /* This is a list of strings. */
  list = g_list_append (list, "first");
  list = g_list_append (list, "second");

  /* This is a list of integers. */
  number_list = g_list_append (number_list, GINT_TO_POINTER (27));
  number_list = g_list_append (number_list, GINT_TO_POINTER (14));

list : | a pointer to a GList.
data : | the data for the new element.
Returns : | the new start of the GList.

g_list_prepend ()

GList*              g_list_prepend                      (GList *list,
                                                         gpointer data);

Adds a new element on to the start of the list.

Note

The return value is the new start of the list, which may have changed, so make sure you store the new value.

  /* Notice that it is initialized to the empty list. */
  GList *list = NULL;
  list = g_list_prepend (list, "last");
  list = g_list_prepend (list, "first");

list : | a pointer to a GList.
data : | the data for the new element.
Returns : | the new start of the GList.

g_list_insert ()

GList*              g_list_insert                       (GList *list,
                                                         gpointer data,
                                                         gint position);

Inserts a new element into the list at the given position.

list : | a pointer to a GList.
data : | the data for the new element.
position : | the position to insert the element. If this is negative, or is larger than the number of elements in the list, the new element is added on to the end of the list.
Returns : | the new start of the GList.

g_list_insert_before ()

GList*              g_list_insert_before                (GList *list,
                                                         GList *sibling,
                                                         gpointer data);

Inserts a new element into the list before the given position.

list : | a pointer to a GList.
sibling : | the list element before which the new element is inserted or NULL to insert at the end of the list.
data : | the data for the new element.
Returns : | the new start of the GList.

g_list_insert_sorted ()

GList*              g_list_insert_sorted                (GList *list,
                                                         gpointer data,
                                                         GCompareFunc func);

Inserts a new element into the list, using the given comparison function to determine its position.

list : | a pointer to a GList.
data : | the data for the new element.
func : | the function to compare elements in the list. It should return a number > 0 if the first parameter comes after the second parameter in the sort order.
Returns : | the new start of the GList.

g_list_remove ()

GList*              g_list_remove                       (GList *list,
                                                         gconstpointer data);

Removes an element from a GList. If two elements contain the same data, only the first is removed. If none of the elements contain the data, the GList is unchanged.

list : | a GList.
data : | the data of the element to remove.
Returns : | the new start of the GList.

g_list_remove_link ()

GList*              g_list_remove_link                  (GList *list,
                                                         GList *llink);

Removes an element from a GList, without freeing the element. The removed element's prev and next links are set to NULL, so that it becomes a self-contained list with one element.

list : | a GList.
llink : | an element in the GList.
Returns : | the new start of the GList, without the element.

g_list_delete_link ()

GList*              g_list_delete_link                  (GList *list,
                                                         GList *link_);

Deletes the node link_ from list.

list : | a GList.
link_ : | node to delete from list.
Returns : | the new head of list.

g_list_remove_all ()

GList*              g_list_remove_all                   (GList *list,
                                                         gconstpointer data);

Removes all list nodes with data equal to data. Returns the new head of the list. Contrast with g_list_remove() which removes only the first node matching the given data.

list : | a GList.
data : | data to remove.
Returns : | new head of list.

g_list_free ()

void                g_list_free                         (GList *list);

Frees all of the memory used by a GList. The freed elements are returned to the slice allocator.

Note

If list elements contain dynamically-allocated memory, they should be freed first.

list : a GList.

g_list_alloc ()

GList*              g_list_alloc                        (void);

Allocates space for one GList element. It is called by g_list_append(), g_list_prepend(), g_list_insert() and g_list_insert_sorted() and so is rarely used on its own.

Returns : a pointer to the newly-allocated GList element.

g_list_free_1 ()

void                g_list_free_1                       (GList *list);

Frees one GList element. It is usually used after g_list_remove_link().

list : a GList element.

g_list_free1

#define             g_list_free1

Another name for g_list_free_1().

g_list_length ()

guint               g_list_length                       (GList *list);

Gets the number of elements in a GList.

list : | a GList.
Returns : | the number of elements in the GList.

g_list_copy ()

GList*              g_list_copy                         (GList *list);

Copies a GList.

Note that this is a "shallow" copy. If the list elements consist of pointers to data, the pointers are copied but the actual data isn't.

list : | a GList.
Returns : | a copy of list.

g_list_reverse ()

GList*              g_list_reverse                      (GList *list);

Reverses a GList. It simply switches the next and prev pointers of each element.

list : | a GList.
Returns : | the start of the reversed GList.

g_list_sort ()

GList*              g_list_sort                         (GList *list,
                                                         GCompareFunc compare_func);

Sorts a GList using the given comparison function.

list : | a GList.
compare_func : | the comparison function used to sort the GList. This function is passed the data from 2 elements of the GList and should return 0 if they are equal, a negative value if the first element comes before the second, or a positive value if the first element comes after the second.
Returns : | the start of the sorted GList.

GCompareFunc ()

gint                (*GCompareFunc)                     (gconstpointer a,
                                                         gconstpointer b);

Specifies the type of a comparison function used to compare two values. The function should return a negative integer if the first value comes before the second, 0 if they are equal, or a positive integer if the first value comes after the second.

a : | a value.
b : | a value to compare with.
Returns : | negative value if a < b; zero if a = b; positive value if a > b.

g_list_insert_sorted_with_data ()

GList*              g_list_insert_sorted_with_data      (GList *list,
                                                         gpointer data,
                                                         GCompareDataFunc func,
                                                         gpointer user_data);

Inserts a new element into the list, using the given comparison function to determine its position.

list : | a pointer to a GList.
data : | the data for the new element.
func : | the function to compare elements in the list. It should return a number > 0 if the first parameter comes after the second parameter in the sort order.
user_data : | user data to pass to comparison function.
Returns : | the new start of the GList. Since 2.10

g_list_sort_with_data ()

GList*              g_list_sort_with_data               (GList *list,
                                                         GCompareDataFunc compare_func,
                                                         gpointer user_data);

Like g_list_sort(), but the comparison function accepts a user data argument.

list : | a GList.
compare_func : | comparison function.
user_data : | user data to pass to comparison function.
Returns : | the new head of list.

GCompareDataFunc ()

gint                (*GCompareDataFunc)                 (gconstpointer a,
                                                         gconstpointer b,
                                                         gpointer user_data);

Specifies the type of a comparison function used to compare two values. The function should return a negative integer if the first value comes before the second, 0 if they are equal, or a positive integer if the first value comes after the second.

a : | a value.
b : | a value to compare with.
user_data : | user data to pass to comparison function.
Returns : | negative value if a < b; zero if a = b; positive value if a > b.

g_list_concat ()

GList*              g_list_concat                       (GList *list1,
                                                         GList *list2);

Adds the second GList onto the end of the first GList. Note that the elements of the second GList are not copied. They are used directly.

list1 : | a GList.
list2 : | the GList to add to the end of the first GList.
Returns : | the start of the new GList.

g_list_foreach ()

void                g_list_foreach                      (GList *list,
                                                         GFunc func,
                                                         gpointer user_data);

Calls a function for each element of a GList.

list : | a GList.
func : | the function to call with each element's data.
user_data : | user data to pass to the function.

GFunc ()

void                (*GFunc)                            (gpointer data,
                                                         gpointer user_data);

Specifies the type of functions passed to g_list_foreach() and g_slist_foreach().

data : | the element's data.
user_data : | user data passed to g_list_foreach() or g_slist_foreach().

g_list_first ()

GList*              g_list_first                        (GList *list);

Gets the first element in a GList.

list : | a GList.
Returns : | the first element in a GList, or NULL if the GList has no elements.

g_list_last ()

GList*              g_list_last                         (GList *list);

Gets the last element in a GList.

list : | a GList.
Returns : | the last element in the GList, or NULL if the GList has no elements.

g_list_previous()

#define             g_list_previous(list)

A convenience macro to gets the previous element in a GList.

list : | an element in a GList.
Returns : | the previous element, or NULL if there are no previous elements.

g_list_next()

#define             g_list_next(list)

A convenience macro to gets the next element in a GList.

list : | an element in a GList.
Returns : | the next element, or NULL if there are no more elements.

g_list_nth ()

GList*              g_list_nth                          (GList *list,
                                                         guint n);

Gets the element at the given position in a GList.

list : | a GList.
n : | the position of the element, counting from 0.
Returns : | the element, or NULL if the position is off the end of the GList.

g_list_nth_data ()

gpointer            g_list_nth_data                     (GList *list,
                                                         guint n);

Gets the data of the element at the given position.

list : | a GList.
n : | the position of the element.
Returns : | the element's data, or NULL if the position is off the end of the GList.

g_list_nth_prev ()

GList*              g_list_nth_prev                     (GList *list,
                                                         guint n);

Gets the element n places before list.

list : | a GList.
n : | the position of the element, counting from 0.
Returns : | the element, or NULL if the position is off the end of the GList.

g_list_find ()

GList*              g_list_find                         (GList *list,
                                                         gconstpointer data);

Finds the element in a GList which contains the given data.

list : | a GList.
data : | the element data to find.
Returns : | the found GList element, or NULL if it is not found.

g_list_find_custom ()

GList*              g_list_find_custom                  (GList *list,
                                                         gconstpointer data,
                                                         GCompareFunc func);

Finds an element in a GList, using a supplied function to find the desired element. It iterates over the list, calling the given function which should return 0 when the desired element is found. The function takes two gconstpointer arguments, the GList element's data as the first argument and the given user data.

list : | a GList.
data : | user data passed to the function.
func : | the function to call for each element. It should return 0 when the desired element is found.
Returns : | the found GList element, or NULL if it is not found.

g_list_position ()

gint                g_list_position                     (GList *list,
                                                         GList *llink);

Gets the position of the given element in the GList (starting from 0).

list : | a GList.
llink : | an element in the GList.
Returns : | the position of the element in the GList, or -1 if the element is not found.

g_list_index ()

gint                g_list_index                        (GList *list,
                                                         gconstpointer data);

Gets the position of the element containing the given data (starting from 0).

list : | a GList.
data : | the data to find.
Returns : | the index of the element containing the data, or -1 if the data is not found.

g_list_push_allocator ()

void                g_list_push_allocator               (gpointer allocator);

Warning

g_list_push_allocator has been deprecated since version 2.10 and should not be used in newly-written code. It does nothing, since GList has been converted to the slice allocator

Sets the allocator to use to allocate GList elements. Use g_list_pop_allocator() to restore the previous allocator.

Note that this function is not available if GLib has been compiled with --disable-mem-pools

allocator : the GAllocator to use when allocating GList elements.

g_list_pop_allocator ()

void                g_list_pop_allocator                (void);

Warning

g_list_pop_allocator has been deprecated since version 2.10 and should not be used in newly-written code. It does nothing, since GList has been converted to the slice allocator

Restores the previous GAllocator, used when allocating GList elements.

Note that this function is not available if GLib has been compiled with --disable-mem-pools


Dynamic Loading of Modules

Dynamic Loading of Modules — portable method for dynamically loading 'plug-ins'.

Synopsis

#include <gmodule.h>

                    GModule;
gboolean            g_module_supported                  (void);
gchar*              g_module_build_path                 (const gchar *directory,
                                                         const gchar *module_name);
GModule*            g_module_open                       (const gchar *file_name,
                                                         GModuleFlags flags);
enum                GModuleFlags;
gboolean            g_module_symbol                     (GModule *module,
                                                         const gchar *symbol_name,
                                                         gpointer *symbol);
const gchar*        g_module_name                       (GModule *module);
void                g_module_make_resident              (GModule *module);
gboolean            g_module_close                      (GModule *module);
const gchar*        g_module_error                      (void);

const gchar*        (*GModuleCheckInit)                 (GModule *module);
void                (*GModuleUnload)                    (GModule *module);
#define             G_MODULE_SUFFIX
#define             G_MODULE_EXPORT
#define             G_MODULE_IMPORT

Description

These functions provide a portable way to dynamically load object files (commonly known as 'plug-ins'). The current implementation supports all systems that provide an implementation of dlopen() (e.g. Linux/Sun), as well as HP-UX via its shl_load() mechanism, and Windows platforms via DLLs.

A program which wants to use these functions must be linked to the libraries output by the command pkg-config --libs gmodule-2.0.

To use them you must first determine whether dynamic loading is supported on the platform by calling g_module_supported(). If it is, you can open a module with g_module_open(), find the module's symbols (e.g. function names) with g_module_symbol(), and later close the module with g_module_close(). g_module_name() will return the file name of a currently opened module.

If any of the above functions fail, the error status can be found with g_module_error().

The GModule implementation features reference counting for opened modules, and supports hook functions within a module which are called when the module is loaded and unloaded (see GModuleCheckInit and GModuleUnload).

If your module introduces static data to common subsystems in the running program, e.g. through calling g_quark_from_static_string ("my-module-stuff"), it must ensure that it is never unloaded, by calling g_module_make_resident().

Example 13. Calling a function defined in a GModule

/* the function signature for 'say_hello' */
typedef void (* SayHelloFunc) (const char *message);

gboolean
just_say_hello (const char *filename, GError **error)
{
  SayHelloFunc  say_hello;
  GModule      *module;

  module = g_module_open (filename, G_MODULE_BIND_LAZY);
  if (!module)
    {
      g_set_error (error, FOO_ERROR, FOO_ERROR_BLAH,
           "%s", g_module_error ());
      return FALSE;
    }

  if (!g_module_symbol (module, "say_hello", (gpointer *)&say_hello))
    {
      g_set_error (error, SAY_ERROR, SAY_ERROR_OPEN,
           "%s: %s", filename, g_module_error ());
      if (!g_module_close (module))
    g_warning ("%s: %s", filename, g_module_error ());
      return FALSE;
    }

  /* call our function in the module */
  say_hello ("Hello world!");

  if (!g_module_close (module))
    g_warning ("%s: %s", filename, g_module_error ());

  return TRUE;
}

Details

GModule

typedef struct _GModule GModule;

The GModule struct is an opaque data structure to represent a Dynamically-Loaded Module. It should only be accessed via the following functions.

g_module_supported ()

gboolean            g_module_supported                  (void);

Checks if modules are supported on the current platform.

Returns : TRUE if modules are supported.

g_module_build_path ()

gchar*              g_module_build_path                 (const gchar *directory,
                                                         const gchar *module_name);

A portable way to build the filename of a module. The platform-specific prefix and suffix are added to the filename, if needed, and the result is added to the directory, using the correct separator character.

The directory should specify the directory where the module can be found. It can be NULL or an empty string to indicate that the module is in a standard platform-specific directory, though this is not recommended since the wrong module may be found.

For example, calling g_module_build_path() on a Linux system with a directory of /lib and a module_name of "mylibrary" will return /lib/libmylibrary.so. On a Windows system, using \Windows as the directory it will return \Windows\mylibrary.dll.

directory : | the directory where the module is. This can be NULL or the empty string to indicate that the standard platform-specific directories will be used, though that is not recommended.
module_name : | the name of the module.
Returns : | the complete path of the module, including the standard library prefix and suffix. This should be freed when no longer needed.

g_module_open ()

GModule*            g_module_open                       (const gchar *file_name,
                                                         GModuleFlags flags);

Opens a module. If the module has already been opened, its reference count is incremented.

First of all g_module_open() tries to open file_name as a module. If that fails and file_name has the ".la"-suffix (and is a libtool archive) it tries to open the corresponding module. If that fails and it doesn't have the proper module suffix for the platform (G_MODULE_SUFFIX), this suffix will be appended and the corresponding module will be opended. If that fails and file_name doesn't have the ".la"-suffix, this suffix is appended and g_module_open() tries to open the corresponding module. If eventually that fails as well, NULL is returned.

file_name : | the name of the file containing the module, or NULL to obtain a GModule representing the main program itself.
flags : | the flags used for opening the module. This can be the logical OR of any of the GModuleFlags.
Returns : | a GModule on success, or NULL on failure.

enum GModuleFlags

typedef enum
{
  G_MODULE_BIND_LAZY	= 1 << 0,
  G_MODULE_BIND_LOCAL	= 1 << 1,
  G_MODULE_BIND_MASK	= 0x03
} GModuleFlags;

Flags passed to g_module_open(). Note that these flags are not supported on all platforms.

G_MODULE_BIND_LAZY | specifies that symbols are only resolved when needed. The default action is to bind all symbols when the module is loaded.
G_MODULE_BIND_LOCAL | specifies that symbols in the module should not be added to the global name space. The default action on most platforms is to place symbols in the module in the global name space, which may cause conflicts with existing symbols.
G_MODULE_BIND_MASK | mask for all flags.

g_module_symbol ()

gboolean            g_module_symbol                     (GModule *module,
                                                         const gchar *symbol_name,
                                                         gpointer *symbol);

Gets a symbol pointer from a module.

module : | a GModule.
symbol_name : | the name of the symbol to find.
symbol : | returns the pointer to the symbol value.
Returns : | TRUE on success.

g_module_name ()

const gchar*        g_module_name                       (GModule *module);

Gets the filename from a GModule.

module : | a GModule.
Returns : | the filename of the module, or "main" if the module is the main program itself.

g_module_make_resident ()

void                g_module_make_resident              (GModule *module);

Ensures that a module will never be unloaded. Any future g_module_close() calls on the module will be ignored.

module : a GModule to make permanently resident.

g_module_close ()

gboolean            g_module_close                      (GModule *module);

Closes a module.

module : | a GModule to close.
Returns : | TRUE on success.

g_module_error ()

const gchar*        g_module_error                      (void);

Gets a string describing the last module error.

Returns : a string describing the last module error.

GModuleCheckInit ()

const gchar*        (*GModuleCheckInit)                 (GModule *module);

Specifies the type of the module initialization function. If a module contains a function named g_module_check_init() it is called automatically when the module is loaded. It is passed the GModule structure and should return NULL on success or a string describing the initialization error.

module : | the GModule corresponding to the module which has just been loaded.
Returns : | NULL on success, or a string describing the initialization error.

GModuleUnload ()

void                (*GModuleUnload)                    (GModule *module);

Specifies the type of the module function called when it is unloaded. If a module contains a function named g_module_unload() it is called automatically when the module is unloaded. It is passed the GModule structure.

module : the GModule about to be unloaded.

G_MODULE_SUFFIX

#define G_MODULE_SUFFIX "so"

Expands to the proper shared library suffix for the current platform without the leading dot. For the most Unices and Linux this is "so", for some HP-UX versions this is "sl" and for Windows this is "dll".

G_MODULE_EXPORT

#define             G_MODULE_EXPORT

Used to declare functions exported by modules.

G_MODULE_IMPORT

#define	G_MODULE_IMPORT		extern

Used to declare functions imported from modules.


Error Reporting

Error Reporting — a system for reporting errors.

Synopsis

#include <glib.h>

                    GError;
GError*             g_error_new                         (GQuark domain,
                                                         gint code,
                                                         const gchar *format,
                                                         ...);
GError*             g_error_new_literal                 (GQuark domain,
                                                         gint code,
                                                         const gchar *message);
void                g_error_free                        (GError *error);
GError*             g_error_copy                        (const GError *error);
gboolean            g_error_matches                     (const GError *error,
                                                         GQuark domain,
                                                         gint code);
void                g_set_error                         (GError **err,
                                                         GQuark domain,
                                                         gint code,
                                                         const gchar *format,
                                                         ...);
void                g_propagate_error                   (GError **dest,
                                                         GError *src);
void                g_clear_error                       (GError **err);

Description

GLib provides a standard method of reporting errors from a called function to the calling code. (This is the same problem solved by exceptions in other languages.) It's important to understand that this method is both a data type (the GError object) and a set of rules. If you use GError incorrectly, then your code will not properly interoperate with other code that uses GError, and users of your API will probably get confused.

First and foremost: GError should only be used to report recoverable runtime errors, never to report programming errors. If the programmer has screwed up, then you should use g_warning(), g_return_if_fail(), g_assert(), g_error(), or some similar facility. (Incidentally, remember that the g_error() function should only be used for programming errors, it should not be used to print any error reportable via GError.)

Examples of recoverable runtime errors are "file not found" or "failed to parse input." Examples of programming errors are "NULL passed to strcmp()" or "attempted to free the same pointer twice." These two kinds of errors are fundamentally different: runtime errors should be handled or reported to the user, programming errors should be eliminated by fixing the bug in the program. This is why most functions in GLib and GTK+ do not use the GError facility.

Functions that can fail take a return location for a GError as their last argument. For example:

gboolean g_file_get_contents (const gchar *filename,
                          gchar      **contents,
                              gsize       *length,
                              GError     **error);

If you pass a non-NULL value for the error argument, it should point to a location where an error can be placed. For example:

gchar *contents;
GError *err = NULL;
g_file_get_contents ("foo.txt", &contents, NULL, &err);
g_assert ((contents == NULL && err != NULL) || (contents != NULL && err == NULL));
if (err != NULL)
  {
    /* Report error to user, and free error */
    g_assert (contents == NULL);
    fprintf (stderr, "Unable to read file: %s\n", err->message);
    g_error_free (err);
  }
else
  {
    /* Use file contents */
    g_assert (contents != NULL);
  }

Note that err != NULL in this example is a reliable indicator of whether g_file_get_contents() failed. Additionally, g_file_get_contents() returns a boolean which indicates whether it was successful.

Because g_file_get_contents() returns FALSE on failure, if you are only interested in whether it failed and don't need to display an error message, you can pass NULL for the error argument:

if (g_file_get_contents ("foo.txt", &contents, NULL, NULL)) /* ignore errors */
  /* no error occurred */ ;
else
  /* error */ ;

The GError object contains three fields: domain indicates the module the error-reporting function is located in, code indicates the specific error that occurred, and message is a user-readable error message with as many details as possible. Several functions are provided to deal with an error received from a called function: g_error_matches() returns TRUE if the error matches a given domain and code, g_propagate_error() copies an error into an error location (so the calling function will receive it), and g_clear_error() clears an error location by freeing the error and resetting the location to NULL. To display an error to the user, simply display error->message, perhaps along with additional context known only to the calling function (the file being opened, or whatever -- though in the g_file_get_contents() case, error->message already contains a filename).

When implementing a function that can report errors, the basic tool is g_set_error(). Typically, if a fatal error occurs you want to g_set_error(), then return immediately. g_set_error() does nothing if the error location passed to it is NULL. Here's an example:

gint
foo_open_file (GError **error)
{
  gint fd;

  fd = open ("file.txt", O_RDONLY);

  if (fd < 0)
    {
      g_set_error (error,
                   FOO_ERROR,                 /* error domain */
                   FOO_ERROR_BLAH,            /* error code */
                   "Failed to open file: %s", /* error message format string */
                   g_strerror (errno));
      return -1;
    }
  else
    return fd;
}

Things are somewhat more complicated if you yourself call another function that can report a GError. If the sub-function indicates fatal errors in some way other than reporting a GError, such as by returning TRUE on success, you can simply do the following:

gboolean
my_function_that_can_fail (GError **err)
{
  g_return_val_if_fail (err == NULL || *err == NULL, FALSE);

  if (!sub_function_that_can_fail (err))
    {
       /* assert that error was set by the sub-function */
       g_assert (err == NULL || *err != NULL);
       return FALSE;
    }

  /* otherwise continue, no error occurred */
  g_assert (err == NULL || *err == NULL);
}

If the sub-function does not indicate errors other than by reporting a GError, you need to create a temporary GError since the passed-in one may be NULL. g_propagate_error() is intended for use in this case.

gboolean
my_function_that_can_fail (GError **err)
{
  GError *tmp_error;

  g_return_val_if_fail (err == NULL || *err == NULL, FALSE);

  tmp_error = NULL;
  sub_function_that_can_fail (&tmp_error);

  if (tmp_error != NULL)
    {
       /* store tmp_error in err, if err != NULL,
        * otherwise call g_error_free() on tmp_error
        */
       g_propagate_error (err, tmp_error);
       return FALSE;
    }

  /* otherwise continue, no error occurred */
}

Error pileups are always a bug. For example, this code is incorrect:

gboolean
my_function_that_can_fail (GError **err)
{
  GError *tmp_error;

  g_return_val_if_fail (err == NULL || *err == NULL, FALSE);

  tmp_error = NULL;
  sub_function_that_can_fail (&tmp_error);
  other_function_that_can_fail (&tmp_error);

  if (tmp_error != NULL)
    {
       g_propagate_error (err, tmp_error);
       return FALSE;
    }
}

tmp_error should be checked immediately after sub_function_that_can_fail(), and either cleared or propagated upward. The rule is: after each error, you must either handle the error, or return it to the calling function. Note that passing NULL for the error location is the equivalent of handling an error by always doing nothing about it. So the following code is fine, assuming errors in sub_function_that_can_fail() are not fatal to my_function_that_can_fail():

gboolean
my_function_that_can_fail (GError **err)
{
  GError *tmp_error;

  g_return_val_if_fail (err == NULL || *err == NULL, FALSE);

  sub_function_that_can_fail (NULL); /* ignore errors */

  tmp_error = NULL;
  other_function_that_can_fail (&tmp_error);

  if (tmp_error != NULL)
    {
       g_propagate_error (err, tmp_error);
       return FALSE;
    }
}

Note that passing NULL for the error location ignores errors; it's equivalent to try { sub_function_that_can_fail(); } catch (...) {} in C++. It does not mean to leave errors unhandled; it means to handle them by doing nothing.

Error domains and codes are conventionally named as follows:

  • The error domain is called <NAMESPACE>_<MODULE>_ERROR, for example G_EXEC_ERROR or G_THREAD_ERROR.

  • The error codes are in an enumeration called <Namespace><Module>Error; for example, GThreadError or GSpawnError.

  • Members of the error code enumeration are called <NAMESPACE>_<MODULE>_ERROR_<CODE>, for example G_SPAWN_ERROR_FORK or G_THREAD_ERROR_AGAIN.

  • If there's a "generic" or "unknown" error code for unrecoverable errors it doesn't make sense to distinguish with specific codes, it should be called <NAMESPACE>_<MODULE>_ERROR_FAILED, for example G_SPAWN_ERROR_FAILED or G_THREAD_ERROR_FAILED.

Summary of rules for use of GError:

  • Do not report programming errors via GError.

  • The last argument of a function that returns an error should be a location where a GError can be placed (i.e. "GError** error"). If GError is used with varargs, the GError** should be the last argument before the "...".

  • The caller may pass NULL for the GError** if they are not interested in details of the exact error that occurred.

  • If NULL is passed for the GError** argument, then errors should not be returned to the caller, but your function should still abort and return if an error occurs. That is, control flow should not be affected by whether the caller wants to get a GError.

  • If a GError is reported, then your function by definition had a fatal failure and did not complete whatever it was supposed to do. If the failure was not fatal, then you handled it and you should not report it. If it was fatal, then you must report it and discontinue whatever you were doing immediately.

  • A GError* must be initialized to NULL before passing its address to a function that can report errors.

  • "Piling up" errors is always a bug. That is, if you assign a new GError to a GError* that is non-NULL, thus overwriting the previous error, it indicates that you should have aborted the operation instead of continuing. If you were able to continue, you should have cleared the previous error with g_clear_error(). g_set_error() will complain if you pile up errors.

  • By convention, if you return a boolean value indicating success then TRUE means success and FALSE means failure. If FALSE is returned, the error must be set to a non-NULL value.

  • A NULL return value is also frequently used to mean that an error occurred. You should make clear in your documentation whether NULL is a valid return value in non-error cases; if NULL is a valid value, then users must check whether an error was returned to see if the function succeeded.

  • When implementing a function that can report errors, you may want to add a check at the top of your function that the error return location is either NULL or contains a NULL error (e.g. g_return_if_fail (error == NULL || *error == NULL);).

Details

GError

typedef struct {
  GQuark       domain;
  gint         code;
  gchar       *message;
} GError;

The GError structure contains information about an error that has occurred.

GQuark domain; | error domain, e.g. G_FILE_ERROR.
gint code; | error code, e.g. G_FILE_ERROR_NOENT.
gchar *message; | human-readable informative error message.

g_error_new ()

GError*             g_error_new                         (GQuark domain,
                                                         gint code,
                                                         const gchar *format,
                                                         ...);

Creates a new GError with the given domain and code, and a message formatted with format.

domain : | error domain
code : | error code
format : | printf()-style format for error message
... : | parameters for message format
Returns : | a new GError

g_error_new_literal ()

GError*             g_error_new_literal                 (GQuark domain,
                                                         gint code,
                                                         const gchar *message);

Creates a new GError; unlike g_error_new(), message is not a printf()-style format string. Use this function if message contains text you don't have control over, that could include printf() escape sequences.

domain : | error domain
code : | error code
message : | error message
Returns : | a new GError

g_error_free ()

void                g_error_free                        (GError *error);

Frees a GError and associated resources.

error : a GError

g_error_copy ()

GError*             g_error_copy                        (const GError *error);

Makes a copy of error.

error : | a GError
Returns : | a new GError

g_error_matches ()

gboolean            g_error_matches                     (const GError *error,
                                                         GQuark domain,
                                                         gint code);

Returns TRUE if error matches domain and code, FALSE otherwise.

error : | a GError
domain : | an error domain
code : | an error code
Returns : | whether error has domain and code

g_set_error ()

void                g_set_error                         (GError **err,
                                                         GQuark domain,
                                                         gint code,
                                                         const gchar *format,
                                                         ...);

Does nothing if err is NULL; if err is non-NULL, then *err must be NULL. A new GError is created and assigned to *err.

err : | a return location for a GError, or NULL
domain : | error domain
code : | error code
format : | printf()-style format
... : | args for format

g_propagate_error ()

void                g_propagate_error                   (GError **dest,
                                                         GError *src);

If dest is NULL, free src; otherwise, moves src into *dest. *dest must be NULL.

dest : | error return location
src : | error to move into the return location

g_clear_error ()

void                g_clear_error                       (GError **err);

If err is NULL, does nothing. If err is non-NULL, calls g_error_free() on *err and sets *err to NULL.

err : a GError return location


File Utilities

File Utilities — various file-related functions.

Synopsis

#include <glib.h>
#include <glib/gstdio.h>

enum                GFileError;
#define             G_FILE_ERROR
enum                GFileTest;
GFileError          g_file_error_from_errno             (gint err_no);
gboolean            g_file_get_contents                 (const gchar *filename,
                                                         gchar **contents,
                                                         gsize *length,
                                                         GError **error);
gboolean            g_file_set_contents                 (const gchar *filename,
                                                         const gchar *contents,
                                                         gssize length,
                                                         GError **error);
gboolean            g_file_test                         (const gchar *filename,
                                                         GFileTest test);
gint                g_mkstemp                           (gchar *tmpl);
gint                g_file_open_tmp                     (const gchar *tmpl,
                                                         gchar **name_used,
                                                         GError **error);
gchar*              g_file_read_link                    (const gchar *filename,
                                                         GError **error);
int                 g_mkdir_with_parents                (const gchar *pathname,
                                                         int mode);

                    GDir;
GDir*               g_dir_open                          (const gchar *path,
                                                         guint flags,
                                                         GError **error);
const gchar*        g_dir_read_name                     (GDir *dir);
void                g_dir_rewind                        (GDir *dir);
void                g_dir_close                         (GDir *dir);

                    GMappedFile;
GMappedFile*        g_mapped_file_new                   (const gchar *filename,
                                                         gboolean writable,
                                                         GError **error);
void                g_mapped_file_free                  (GMappedFile *file);
gsize               g_mapped_file_get_length            (GMappedFile *file);
gchar*              g_mapped_file_get_contents          (GMappedFile *file);

int                 g_open                              (const gchar *filename,
                                                         int flags,
                                                         int mode);
int                 g_rename                            (const gchar *oldfilename,
                                                         const gchar *newfilename);
int                 g_mkdir                             (const gchar *filename,
                                                         int mode);
int                 g_stat                              (const gchar *filename,
                                                         struct stat *buf);
int                 g_lstat                             (const gchar *filename,
                                                         struct stat *buf);
int                 g_unlink                            (const gchar *filename);
int                 g_remove                            (const gchar *filename);
int                 g_rmdir                             (const gchar *filename);
FILE*               g_fopen                             (const gchar *filename,
                                                         const gchar *mode);
FILE*               g_freopen                           (const gchar *filename,
                                                         const gchar *mode,
                                                         FILE *stream);
int                 g_chmod                             (const gchar *filename,
                                                         int mode);
int                 g_access                            (const gchar *filename,
                                                         int mode);
int                 g_creat                             (const gchar *filename,
                                                         int mode);
int                 g_chdir                             (const gchar *path);

Description

There is a group of functions which wrap the common POSIX functions dealing with filenames (g_open(), g_rename(), g_mkdir(), g_stat(), g_unlink(), g_remove(), g_fopen(), g_freopen()). The point of these wrappers is to make it possible to handle file names with any Unicode characters in them on Windows without having to use ifdefs and the wide character API in the application code.

The pathname argument should be in the GLib file name encoding. On POSIX this is the actual on-disk encoding which might correspond to the locale settings of the process (or the G_FILENAME_ENCODING environment variable), or not.

On Windows the GLib file name encoding is UTF-8. Note that the Microsoft C library does not use UTF-8, but has separate APIs for current system code page and wide characters (UTF-16). The GLib wrappers call the wide character API if present (on modern Windows systems), otherwise convert to/from the system code page.

Another group of functions allows to open and read directories in the GLib file name encoding. These are g_dir_open(), g_dir_read_name(), g_dir_rewind(), g_dir_close().

Details

enum GFileError

typedef enum
{
  G_FILE_ERROR_EXIST,
  G_FILE_ERROR_ISDIR,
  G_FILE_ERROR_ACCES,
  G_FILE_ERROR_NAMETOOLONG,
  G_FILE_ERROR_NOENT,
  G_FILE_ERROR_NOTDIR,
  G_FILE_ERROR_NXIO,
  G_FILE_ERROR_NODEV,
  G_FILE_ERROR_ROFS,
  G_FILE_ERROR_TXTBSY,
  G_FILE_ERROR_FAULT,
  G_FILE_ERROR_LOOP,
  G_FILE_ERROR_NOSPC,
  G_FILE_ERROR_NOMEM,
  G_FILE_ERROR_MFILE,
  G_FILE_ERROR_NFILE,
  G_FILE_ERROR_BADF,
  G_FILE_ERROR_INVAL,
  G_FILE_ERROR_PIPE,
  G_FILE_ERROR_AGAIN,
  G_FILE_ERROR_INTR,
  G_FILE_ERROR_IO,
  G_FILE_ERROR_PERM,
  G_FILE_ERROR_NOSYS,
  G_FILE_ERROR_FAILED
} GFileError;

Values corresponding to errno codes returned from file operations on UNIX. Unlike errno codes, GFileError values are available on all systems, even Windows. The exact meaning of each code depends on what sort of file operation you were performing; the UNIX documentation gives more details. The following error code descriptions come from the GNU C Library manual, and are under the copyright of that manual.

It's not very portable to make detailed assumptions about exactly which errors will be returned from a given operation. Some errors don't occur on some systems, etc., sometimes there are subtle differences in when a system will report a given error, etc.

G_FILE_ERROR_EXIST | Operation not permitted; only the owner of the file (or other resource) or processes with special privileges can perform the operation.
G_FILE_ERROR_ISDIR | File is a directory; you cannot open a directory for writing, or create or remove hard links to it.
G_FILE_ERROR_ACCES | Permission denied; the file permissions do not allow the attempted operation.
G_FILE_ERROR_NAMETOOLONG | Filename too long.
G_FILE_ERROR_NOENT | No such file or directory. This is a "file doesn't exist" error for ordinary files that are referenced in contexts where they are expected to already exist.
G_FILE_ERROR_NOTDIR | A file that isn't a directory was specified when a directory is required.
G_FILE_ERROR_NXIO | No such device or address. The system tried to use the device represented by a file you specified, and it couldn't find the device. This can mean that the device file was installed incorrectly, or that the physical device is missing or not correctly attached to the computer.
G_FILE_ERROR_NODEV | This file is of a type that doesn't support mapping.
G_FILE_ERROR_ROFS | The directory containing the new link can't be modified because it's on a read-only file system.
G_FILE_ERROR_TXTBSY | Text file busy.
G_FILE_ERROR_FAULT | You passed in a pointer to bad memory. (GLib won't reliably return this, don't pass in pointers to bad memory.)
G_FILE_ERROR_LOOP | Too many levels of symbolic links were encountered in looking up a file name. This often indicates a cycle of symbolic links.
G_FILE_ERROR_NOSPC | No space left on device; write operation on a file failed because the disk is full.
G_FILE_ERROR_NOMEM | No memory available. The system cannot allocate more virtual memory because its capacity is full.
G_FILE_ERROR_MFILE | The current process has too many files open and can't open any more. Duplicate descriptors do count toward this limit.
G_FILE_ERROR_NFILE | There are too many distinct file openings in the entire system.
G_FILE_ERROR_BADF | Bad file descriptor; for example, I/O on a descriptor that has been closed or reading from a descriptor open only for writing (or vice versa).
G_FILE_ERROR_INVAL | Invalid argument. This is used to indicate various kinds of problems with passing the wrong argument to a library function.
G_FILE_ERROR_PIPE | Broken pipe; there is no process reading from the other end of a pipe. Every library function that returns this error code also generates a `SIGPIPE' signal; this signal terminates the program if not handled or blocked. Thus, your program will never actually see this code unless it has handled or blocked `SIGPIPE'.
G_FILE_ERROR_AGAIN | Resource temporarily unavailable; the call might work if you try again later.
G_FILE_ERROR_INTR | Interrupted function call; an asynchronous signal occurred and prevented completion of the call. When this happens, you should try the call again.
G_FILE_ERROR_IO | Input/output error; usually used for physical read or write errors. i.e. the disk or other physical device hardware is returning errors.
G_FILE_ERROR_PERM | Operation not permitted; only the owner of the file (or other resource) or processes with special privileges can perform the operation.
G_FILE_ERROR_NOSYS | Function not implemented; this indicates that the system is missing some functionality.
G_FILE_ERROR_FAILED | Does not correspond to a UNIX error code; this is the standard "failed for unspecified reason" error code present in all GError error code enumerations. Returned if no specific code applies.

G_FILE_ERROR

#define G_FILE_ERROR g_file_error_quark ()

Error domain for file operations. Errors in this domain will be from the GFileError enumeration. See GError for information on error domains.

enum GFileTest

typedef enum
{
  G_FILE_TEST_IS_REGULAR    = 1 << 0,
  G_FILE_TEST_IS_SYMLINK    = 1 << 1,
  G_FILE_TEST_IS_DIR        = 1 << 2,
  G_FILE_TEST_IS_EXECUTABLE = 1 << 3,
  G_FILE_TEST_EXISTS        = 1 << 4
} GFileTest;

A test to perform on a file using g_file_test().

G_FILE_TEST_IS_REGULAR | TRUE if the file is a regular file (not a symlink or directory)
G_FILE_TEST_IS_SYMLINK | TRUE if the file is a symlink.
G_FILE_TEST_IS_DIR | TRUE if the file is a directory.
G_FILE_TEST_IS_EXECUTABLE | TRUE if the file is executable.
G_FILE_TEST_EXISTS | TRUE if the file exists. It may or may not be a regular file.

g_file_error_from_errno ()

GFileError          g_file_error_from_errno             (gint err_no);

Gets a GFileError constant based on the passed-in errno. For example, if you pass in EEXIST this function returns G_FILE_ERROR_EXIST. Unlike errno values, you can portably assume that all GFileError values will exist.

Normally a GFileError value goes into a GError returned from a function that manipulates files. So you would use g_file_error_from_errno() when constructing a GError.

err_no : | an "errno" value
Returns : | GFileError corresponding to the given errno

g_file_get_contents ()

gboolean            g_file_get_contents                 (const gchar *filename,
                                                         gchar **contents,
                                                         gsize *length,
                                                         GError **error);

Reads an entire file into allocated memory, with good error checking.

If the call was successful, it returns TRUE and sets contents to the file contents and length to the length of the file contents in bytes. The string stored in contents will be nul-terminated, so for text files you can pass NULL for the length argument. If the call was not successful, it returns FALSE and sets error. The error domain is G_FILE_ERROR. Possible error codes are those in the GFileError enumeration. In the error case, contents is set to NULL and length is set to zero.

filename : | name of a file to read contents from, in the GLib file name encoding
contents : | location to store an allocated string
length : | location to store length in bytes of the contents, or NULL
error : | return location for a GError, or NULL
Returns : | TRUE on success, FALSE if an error occurred

g_file_set_contents ()

gboolean            g_file_set_contents                 (const gchar *filename,
                                                         const gchar *contents,
                                                         gssize length,
                                                         GError **error);

Writes all of contents to a file named filename, with good error checking. If a file called filename already exists it will be overwritten.

This write is atomic in the sense that it is first written to a temporary file which is then renamed to the final name. Notes:

  • On Unix, if filename already exists hard links to filename will break. Also since the file is recreated, existing permissions, access control lists, metadata etc. may be lost. If filename is a symbolic link, the link itself will be replaced, not the linked file.
  • On Windows renaming a file will not remove an existing file with the new name, so on Windows there is a race condition between the existing file being removed and the temporary file being renamed.
  • On Windows there is no way to remove a file that is open to some process, or mapped into memory. Thus, this function will fail if filename already exists and is open.

If the call was sucessful, it returns TRUE. If the call was not successful, it returns FALSE and sets error. The error domain is G_FILE_ERROR. Possible error codes are those in the GFileError enumeration.

filename : | name of a file to write contents to, in the GLib file name encoding
contents : | string to write to the file
length : | length of contents, or -1 if contents is a nul-terminated string
error : | return location for a GError, or NULL
Returns : | TRUE on success, FALSE if an error occurred

Since 2.8

g_file_test ()

gboolean            g_file_test                         (const gchar *filename,
                                                         GFileTest test);

Returns TRUE if any of the tests in the bitfield test are TRUE. For example, (G_FILE_TEST_EXISTS | G_FILE_TEST_IS_DIR) will return TRUE if the file exists; the check whether it's a directory doesn't matter since the existence test is TRUE. With the current set of available tests, there's no point passing in more than one test at a time.

Apart from G_FILE_TEST_IS_SYMLINK all tests follow symbolic links, so for a symbolic link to a regular file g_file_test() will return TRUE for both G_FILE_TEST_IS_SYMLINK and G_FILE_TEST_IS_REGULAR.

Note, that for a dangling symbolic link g_file_test() will return TRUE for G_FILE_TEST_IS_SYMLINK and FALSE for all other flags.

You should never use g_file_test() to test whether it is safe to perform an operation, because there is always the possibility of the condition changing before you actually perform the operation. For example, you might think you could use G_FILE_TEST_IS_SYMLINK to know whether it is is safe to write to a file without being tricked into writing into a different location. It doesn't work!

/* DON'T DO THIS */
 if (!g_file_test (filename, G_FILE_TEST_IS_SYMLINK)) {
   fd = g_open (filename, O_WRONLY);
   /* write to fd */
 }

Another thing to note is that G_FILE_TEST_EXISTS and G_FILE_TEST_IS_EXECUTABLE are implemented using the access() system call. This usually doesn't matter, but if your program is setuid or setgid it means that these tests will give you the answer for the real user ID and group ID, rather than the effective user ID and group ID.

On Windows, there are no symlinks, so testing for G_FILE_TEST_IS_SYMLINK will always return FALSE. Testing for G_FILE_TEST_IS_EXECUTABLE will just check that the file exists and its name indicates that it is executable, checking for well-known extensions and those listed in the PATHEXT environment variable.

filename : | a filename to test in the GLib file name encoding
test : | bitfield of GFileTest flags
Returns : | whether a test was TRUE

g_mkstemp ()

gint                g_mkstemp                           (gchar *tmpl);

Opens a temporary file. See the mkstemp() documentation on most UNIX-like systems.

The parameter is a string that should follow the rules for mkstemp() templates, i.e. contain the string "XXXXXX". g_mkstemp() is slightly more flexible than mkstemp() in that the sequence does not have to occur at the very end of the template. The X string will be modified to form the name of a file that didn't exist. The string should be in the GLib file name encoding. Most importantly, on Windows it should be in UTF-8.

tmpl : | template filename
Returns : | A file handle (as from open()) to the file opened for reading and writing. The file is opened in binary mode on platforms where there is a difference. The file handle should be closed with close(). In case of errors, -1 is returned.

g_file_open_tmp ()

gint                g_file_open_tmp                     (const gchar *tmpl,
                                                         gchar **name_used,
                                                         GError **error);

Opens a file for writing in the preferred directory for temporary files (as returned by g_get_tmp_dir()).

tmpl should be a string in the GLib file name encoding containing a sequence of six 'X' characters, as the parameter to g_mkstemp(). However, unlike these functions, the template should only be a basename, no directory components are allowed. If template is NULL, a default template is used.

Note that in contrast to g_mkstemp() (and mkstemp()) tmpl is not modified, and might thus be a read-only literal string.

The actual name used is returned in name_used if non-NULL. This string should be freed with g_free() when not needed any longer. The returned name is in the GLib file name encoding.

tmpl : | Template for file name, as in g_mkstemp(), basename only, or NULL, to a default template
name_used : | location to store actual name used
error : | return location for a GError
Returns : | A file handle (as from open()) to the file opened for reading and writing. The file is opened in binary mode on platforms where there is a difference. The file handle should be closed with close(). In case of errors, -1 is returned and error will be set.

g_file_read_link ()

gchar*              g_file_read_link                    (const gchar *filename,
                                                         GError **error);

Reads the contents of the symbolic link filename like the POSIX readlink() function. The returned string is in the encoding used for filenames. Use g_filename_to_utf8() to convert it to UTF-8.

filename : | the symbolic link
error : | return location for a GError
Returns : | A newly allocated string with the contents of the symbolic link, or NULL if an error occurred.

Since 2.4

g_mkdir_with_parents ()

int                 g_mkdir_with_parents                (const gchar *pathname,
                                                         int mode);

Create a directory if it doesn't already exist. Create intermediate parent directories as needed, too.

pathname : | a pathname in the GLib file name encoding
mode : | permissions to use for newly created directories
Returns : | 0 if the directory already exists, or was successfully created. Returns -1 if an error occurred, with errno set.

Since 2.8

GDir

typedef struct _GDir GDir;

An opaque structure representing an opened directory.

g_dir_open ()

GDir*               g_dir_open                          (const gchar *path,
                                                         guint flags,
                                                         GError **error);

Opens a directory for reading. The names of the files in the directory can then be retrieved using g_dir_read_name().

path : | the path to the directory you are interested in. On Unix in the on-disk encoding. On Windows in UTF-8
flags : | Currently must be set to 0. Reserved for future use.
error : | return location for a GError, or NULL. If non-NULL, an error will be set if and only if g_dir_open() fails.
Returns : | a newly allocated GDir on success, NULL on failure. If non-NULL, you must free the result with g_dir_close() when you are finished with it.

g_dir_read_name ()

const gchar*        g_dir_read_name                     (GDir *dir);

Retrieves the name of the next entry in the directory. The '.' and '..' entries are omitted. On Windows, the returned name is in UTF-8. On Unix, it is in the on-disk encoding.

dir : | a GDir* created by g_dir_open()
Returns : | The entry's name or NULL if there are no more entries. The return value is owned by GLib and must not be modified or freed.

g_dir_rewind ()

void                g_dir_rewind                        (GDir *dir);

Resets the given directory. The next call to g_dir_read_name() will return the first entry again.

dir : a GDir* created by g_dir_open()

g_dir_close ()

void                g_dir_close                         (GDir *dir);

Closes the directory and deallocates all related resources.

dir : a GDir* created by g_dir_open()

GMappedFile

typedef struct _GMappedFile GMappedFile;

The GMappedFile represents a file mapping created with g_mapped_file_new(). It has only private members and should not be accessed directly.

g_mapped_file_new ()

GMappedFile*        g_mapped_file_new                   (const gchar *filename,
                                                         gboolean writable,
                                                         GError **error);

Maps a file into memory. On UNIX, this is using the mmap() function.

If writable is TRUE, the mapped buffer may be modified, otherwise it is an error to modify the mapped buffer. Modifications to the buffer are not visible to other processes mapping the same file, and are not written back to the file.

Note that modifications of the underlying file might affect the contents of the GMappedFile. Therefore, mapping should only be used if the file will not be modified, or if all modifications of the file are done atomically (e.g. using g_file_set_contents()).

filename : | The path of the file to load, in the GLib filename encoding
writable : | wether the mapping should be writable
error : | return location for a GError, or NULL
Returns : | a newly allocated GMappedFile which must be freed with g_mapped_file_free(), or NULL if the mapping failed.

Since 2.8

g_mapped_file_free ()

void                g_mapped_file_free                  (GMappedFile *file);

Unmaps the buffer of file and frees it.

file : a GMappedFile

Since 2.8

g_mapped_file_get_length ()

gsize               g_mapped_file_get_length            (GMappedFile *file);

Returns the length of the contents of a GMappedFile.

file : | a GMappedFile
Returns : | the length of the contents of file.

Since 2.8

g_mapped_file_get_contents ()

gchar*              g_mapped_file_get_contents          (GMappedFile *file);

Returns the contents of a GMappedFile.

Note that the contents may not be zero-terminated, even if the GMappedFile is backed by a text file.

file : | a GMappedFile
Returns : | the contents of file.

Since 2.8

g_open ()

int                 g_open                              (const gchar *filename,
                                                         int flags,
                                                         int mode);

A wrapper for the POSIX open() function. The open() function is used to convert a pathname into a file descriptor. Note that on POSIX systems file descriptors are implemented by the operating system. On Windows, it's the C library that implements open() and file descriptors. The actual Windows API for opening files is something different.

See the C library manual for more details about open().

filename : | a pathname in the GLib file name encoding (UTF-8 on Windows)
flags : | as in open()
mode : | as in open()
Returns : | a new file descriptor, or -1 if an error occurred. The return value can be used exactly like the return value from open().

Since 2.6

g_rename ()

int                 g_rename                            (const gchar *oldfilename,
                                                         const gchar *newfilename);

A wrapper for the POSIX rename() function. The rename() function renames a file, moving it between directories if required.

See your C library manual for more details about how rename() works on your system. Note in particular that on Win9x it is not possible to rename a file if a file with the new name already exists. Also it is not possible in general on Windows to rename an open file.

oldfilename : | a pathname in the GLib file name encoding (UTF-8 on Windows)
newfilename : | a pathname in the GLib file name encoding
Returns : | 0 if the renaming succeeded, -1 if an error occurred

Since 2.6

g_mkdir ()

int                 g_mkdir                             (const gchar *filename,
                                                         int mode);

A wrapper for the POSIX mkdir() function. The mkdir() function attempts to create a directory with the given name and permissions.

See the C library manual for more details about mkdir().

filename : | a pathname in the GLib file name encoding (UTF-8 on Windows)
mode : | permissions to use for the newly created directory
Returns : | 0 if the directory was successfully created, -1 if an error occurred

Since 2.6

g_stat ()

int                 g_stat                              (const gchar *filename,
                                                         struct stat *buf);

A wrapper for the POSIX stat() function. The stat() function returns information about a file.

See the C library manual for more details about stat().

filename : | a pathname in the GLib file name encoding (UTF-8 on Windows)
buf : | a pointer to a stat struct, which will be filled with the file information
Returns : | 0 if the information was successfully retrieved, -1 if an error occurred

Since 2.6

g_lstat ()

int                 g_lstat                             (const gchar *filename,
                                                         struct stat *buf);

A wrapper for the POSIX lstat() function. The lstat() function is like stat() except that in the case of symbolic links, it returns information about the symbolic link itself and not the file that it refers to. If the system does not support symbolic links g_lstat() is identical to g_stat().

See the C library manual for more details about lstat().

filename : | a pathname in the GLib file name encoding (UTF-8 on Windows)
buf : | a pointer to a stat struct, which will be filled with the file information
Returns : | 0 if the information was successfully retrieved, -1 if an error occurred

Since 2.6

g_unlink ()

int                 g_unlink                            (const gchar *filename);

A wrapper for the POSIX unlink() function. The unlink() function deletes a name from the filesystem. If this was the last link to the file and no processes have it opened, the diskspace occupied by the file is freed.

See your C library manual for more details about unlink(). Note that on Windows, it is in general not possible to delete files that are open to some process, or mapped into memory.

filename : | a pathname in the GLib file name encoding (UTF-8 on Windows)
Returns : | 0 if the name was successfully deleted, -1 if an error occurred

Since 2.6

g_remove ()

int                 g_remove                            (const gchar *filename);

A wrapper for the POSIX remove() function. The remove() function deletes a name from the filesystem.

See your C library manual for more details about how remove() works on your system. On Unix, remove() removes also directories, as it calls unlink() for files and rmdir() for directories. On Windows, although remove() in the C library only works for files, this function tries first remove() and then if that fails rmdir(), and thus works for both files and directories. Note however, that on Windows, it is in general not possible to remove a file that is open to some process, or mapped into memory.

If this function fails on Windows you can't infer too much from the errno value. rmdir() is tried regardless of what caused remove() to fail. Any errno value set by remove() will be overwritten by that set by rmdir().

filename : | a pathname in the GLib file name encoding (UTF-8 on Windows)
Returns : | 0 if the file was successfully removed, -1 if an error occurred

Since 2.6

g_rmdir ()

int                 g_rmdir                             (const gchar *filename);

A wrapper for the POSIX rmdir() function. The rmdir() function deletes a directory from the filesystem.

See your C library manual for more details about how rmdir() works on your system.

filename : | a pathname in the GLib file name encoding (UTF-8 on Windows)
Returns : | 0 if the directory was successfully removed, -1 if an error occurred

Since 2.6

g_fopen ()

FILE*               g_fopen                             (const gchar *filename,
                                                         const gchar *mode);

A wrapper for the POSIX fopen() function. The fopen() function opens a file and associates a new stream with it.

See the C library manual for more details about fopen().

filename : | a pathname in the GLib file name encoding (UTF-8 on Windows)
mode : | a string describing the mode in which the file should be opened
Returns : | A FILE pointer if the file was successfully opened, or NULL if an error occurred

Since 2.6

g_freopen ()

FILE*               g_freopen                           (const gchar *filename,
                                                         const gchar *mode,
                                                         FILE *stream);

A wrapper for the POSIX freopen() function. The freopen() function opens a file and associates it with an existing stream.

See the C library manual for more details about freopen().

filename : | a pathname in the GLib file name encoding (UTF-8 on Windows)
mode : | a string describing the mode in which the file should be opened
stream : | an existing stream which will be reused, or NULL
Returns : | A FILE pointer if the file was successfully opened, or NULL if an error occurred.

Since 2.6

g_chmod ()

int                 g_chmod                             (const gchar *filename,
                                                         int mode);

A wrapper for the POSIX chmod() function. The chmod() function is used to set the permissions of a file system object. Note that on Windows the file protection mechanism is not at all POSIX-like, and the underlying chmod() function in the C library just sets or clears the READONLY attribute. It does not touch any ACL. Software that needs to manage file permissions on Windows exactly should use the Win32 API.

See the C library manual for more details about chmod().

filename : | a pathname in the GLib file name encoding (UTF-8 on Windows)
mode : | as in chmod()
Returns : | zero if the operation succeeded, -1 on error.

Since 2.8

g_access ()

int                 g_access                            (const gchar *filename,
                                                         int mode);

A wrapper for the POSIX access() function. This function is used to test a pathname for one or several of read, write or execute permissions, or just existence. On Windows, the underlying access() function in the C library only checks the READONLY attribute, and does not look at the ACL at all. Software that needs to handle file permissions on Windows more exactly should use the Win32 API.

See the C library manual for more details about access().

filename : | a pathname in the GLib file name encoding (UTF-8 on Windows)
mode : | as in access()
Returns : | zero if the pathname refers to an existing file system object that has all the tested permissions, or -1 otherwise or on error.

Since 2.8

g_creat ()

int                 g_creat                             (const gchar *filename,
                                                         int mode);

A wrapper for the POSIX creat() function. The creat() function is used to convert a pathname into a file descriptor, creating a file if necessar. Note that on POSIX systems file descriptors are implemented by the operating system. On Windows, it's the C library that implements creat() and file descriptors. The actual Windows API for opening files is something different.

See the C library manual for more details about creat().

filename : | a pathname in the GLib file name encoding (UTF-8 on Windows)
mode : | as in creat()
Returns : | a new file descriptor, or -1 if an error occurred. The return value can be used exactly like the return value from creat().

Since 2.8

g_chdir ()

int                 g_chdir                             (const gchar *path);

A wrapper for the POSIX chdir() function. The function changes the current directory of the process to path.

See your C library manual for more details about chdir().

path : | a pathname in the GLib file name encoding (UTF-8 on Windows)
Returns : | 0 on success, -1 if an error occurred.

Since 2.8


GLib Fundamentals

Version Information — Variables and functions to check the GLib version
Basic Types — standard GLib types, defined for ease-of-use and portability.
Limits of Basic Types — portable method of determining the limits of the standard types.
Standard Macros — commonly-used macros.
Type Conversion Macros — portably storing integers in pointer variables.
Byte Order Macros — a portable way to convert between different byte orders.
Numerical Definitions — mathematical constants, and floating point decomposition.
Miscellaneous Macros — specialized macros which are not used often.
Atomic Operations — basic atomic integer and pointer operations


glib-gettextize

glib-gettextize — gettext internationalization utility

Synopsis

glib-gettextize [option...] [directory]

Description

glib-gettextize helps to prepare a source package for being internationalized through gettext. It is a variant of the gettextize that ships with gettext.

glib-gettextize differs from gettextize in that it doesn't create an intl/ subdirectory and doesn't modify po/ChangeLog (note that newer versions of gettextize behave like this when called with the --no-changelog option).

Options

--help | print help and exit
--version | print version information and exit
-c, --copy | copy files instead of making symlinks
-f, --force | force writing of new files even if old ones exist

See also

gettextize(1)


Glob-style pattern matching

Glob-style pattern matching — matches strings against patterns containing '*' (wildcard) and '?' (joker).

Synopsis

#include <glib.h>

                    GPatternSpec;
GPatternSpec*       g_pattern_spec_new                  (const gchar *pattern);
void                g_pattern_spec_free                 (GPatternSpec *pspec);
gboolean            g_pattern_spec_equal                (GPatternSpec *pspec1,
                                                         GPatternSpec *pspec2);
gboolean            g_pattern_match                     (GPatternSpec *pspec,
                                                         guint string_length,
                                                         const gchar *string,
                                                         const gchar *string_reversed);
gboolean            g_pattern_match_string              (GPatternSpec *pspec,
                                                         const gchar *string);
gboolean            g_pattern_match_simple              (const gchar *pattern,
                                                         const gchar *string);

Description

The g_pattern_match* functions match a string against a pattern containing '*' and '?' wildcards with similar semantics as the standard glob() function: '*' matches an arbitrary, possibly empty, string, '?' matches an arbitrary character.

Note that in contrast to glob(), the '/' character can be matched by the wildcards, there are no '[...]' character ranges and '*' and '?' can not be escaped to include them literally in a pattern.

When multiple strings must be matched against the same pattern, it is better to compile the pattern to a GPatternSpec using g_pattern_spec_new() and use g_pattern_match_string() instead of g_pattern_match_simple(). This avoids the overhead of repeated pattern compilation.

Details

GPatternSpec

typedef struct _GPatternSpec GPatternSpec;

A GPatternSpec is the 'compiled' form of a pattern. This structure is opaque and its fields cannot be accessed directly.

g_pattern_spec_new ()

GPatternSpec*       g_pattern_spec_new                  (const gchar *pattern);

Compiles a pattern to a GPatternSpec.

pattern : | a zero-terminated UTF-8 encoded string.
Returns : | a newly-allocated GPatternSpec.

g_pattern_spec_free ()

void                g_pattern_spec_free                 (GPatternSpec *pspec);

Frees the memory allocated for the GPatternSpec.

pspec : a GPatternSpec.

g_pattern_spec_equal ()

gboolean            g_pattern_spec_equal                (GPatternSpec *pspec1,
                                                         GPatternSpec *pspec2);

Compares two compiled pattern specs and returns whether they will match the same set of strings.

pspec1 : | a GPatternSpec.
pspec2 : | another GPatternSpec.
Returns : | Whether the compiled patterns are equal.

g_pattern_match ()

gboolean            g_pattern_match                     (GPatternSpec *pspec,
                                                         guint string_length,
                                                         const gchar *string,
                                                         const gchar *string_reversed);

Matches a string against a compiled pattern. Passing the correct length of the string given is mandatory. The reversed string can be omitted by passing NULL, this is more efficient if the reversed version of the string to be matched is not at hand, as g_pattern_match() will only construct it if the compiled pattern requires reverse matches.

Note that, if the user code will (possibly) match a string against a multitude of patterns containing wildcards, chances are high that some patterns will require a reversed string. In this case, it's more efficient to provide the reversed string to avoid multiple constructions thereof in the various calls to g_pattern_match().

Note also that the reverse of a UTF-8 encoded string can in general not be obtained by g_strreverse(). This works only if the string doesn't contain any multibyte characters. Glib offers the g_utf_strreverse() function to reverse UTF-8 encoded strings.

pspec : | a GPatternSpec.
string_length : | the length of string.
string : | the UTF-8 encoded string to match.
string_reversed : | the reverse of string or NULL.
Returns : | TRUE if string matches pspec.

g_pattern_match_string ()

gboolean            g_pattern_match_string              (GPatternSpec *pspec,
                                                         const gchar *string);

Matches a string against a compiled pattern. If the string is to be matched against more than one pattern, consider using g_pattern_match() instead while supplying the reversed string.

pspec : | a GPatternSpec.
string : | the UTF-8 encoded string to match.
Returns : | TRUE if string matches pspec.

g_pattern_match_simple ()

gboolean            g_pattern_match_simple              (const gchar *pattern,
                                                         const gchar *string);

Matches a string against a pattern given as a string. If this function is to be called in a loop, it's more efficient to compile the pattern once with g_pattern_spec_new() and call g_pattern_match_string() repetively.

pattern : | the UTF-8 encoded pattern.
string : | the UTF-8 encoded string to match.
Returns : | TRUE if string matches pspec.


Hash Tables

Hash Tables — associations between keys and values so that given a key the value can be found quickly.

Synopsis

#include <glib.h>

                    GHashTable;
GHashTable*         g_hash_table_new                    (GHashFunc hash_func,
                                                         GEqualFunc key_equal_func);
GHashTable*         g_hash_table_new_full               (GHashFunc hash_func,
                                                         GEqualFunc key_equal_func,
                                                         GDestroyNotify key_destroy_func,
                                                         GDestroyNotify value_destroy_func);
guint               (*GHashFunc)                        (gconstpointer key);
gboolean            (*GEqualFunc)                       (gconstpointer a,
                                                         gconstpointer b);
void                g_hash_table_insert                 (GHashTable *hash_table,
                                                         gpointer key,
                                                         gpointer value);
void                g_hash_table_replace                (GHashTable *hash_table,
                                                         gpointer key,
                                                         gpointer value);
guint               g_hash_table_size                   (GHashTable *hash_table);
gpointer            g_hash_table_lookup                 (GHashTable *hash_table,
                                                         gconstpointer key);
gboolean            g_hash_table_lookup_extended        (GHashTable *hash_table,
                                                         gconstpointer lookup_key,
                                                         gpointer *orig_key,
                                                         gpointer *value);
void                g_hash_table_foreach                (GHashTable *hash_table,
                                                         GHFunc func,
                                                         gpointer user_data);
gpointer            g_hash_table_find                   (GHashTable *hash_table,
                                                         GHRFunc predicate,
                                                         gpointer user_data);
void                (*GHFunc)                           (gpointer key,
                                                         gpointer value,
                                                         gpointer user_data);
gboolean            g_hash_table_remove                 (GHashTable *hash_table,
                                                         gconstpointer key);
gboolean            g_hash_table_steal                  (GHashTable *hash_table,
                                                         gconstpointer key);
guint               g_hash_table_foreach_remove         (GHashTable *hash_table,
                                                         GHRFunc func,
                                                         gpointer user_data);
guint               g_hash_table_foreach_steal          (GHashTable *hash_table,
                                                         GHRFunc func,
                                                         gpointer user_data);
void                g_hash_table_remove_all             (GHashTable *hash_table);
void                g_hash_table_steal_all              (GHashTable *hash_table);
gboolean            (*GHRFunc)                          (gpointer key,
                                                         gpointer value,
                                                         gpointer user_data);
#define             g_hash_table_freeze                 (hash_table)
#define             g_hash_table_thaw                   (hash_table)
void                g_hash_table_destroy                (GHashTable *hash_table);
GHashTable*         g_hash_table_ref                    (GHashTable *hash_table);
void                g_hash_table_unref                  (GHashTable *hash_table);

gboolean            g_direct_equal                      (gconstpointer v1,
                                                         gconstpointer v2);
guint               g_direct_hash                       (gconstpointer v);
gboolean            g_int_equal                         (gconstpointer v1,
                                                         gconstpointer v2);
guint               g_int_hash                          (gconstpointer v);
gboolean            g_str_equal                         (gconstpointer v1,
                                                         gconstpointer v2);
guint               g_str_hash                          (gconstpointer v);

Description

A GHashTable provides associations between keys and values which is optimized so that given a key, the associated value can be found very quickly.

Note that neither keys nor values are copied when inserted into the GHashTable, so they must exist for the lifetime of the GHashTable. This means that the use of static strings is OK, but temporary strings (i.e. those created in buffers and those returned by GTK+ widgets) should be copied with g_strdup() before being inserted.

If keys or values are dynamically allocated, you must be careful to ensure that they are freed when they are removed from the GHashTable, and also when they are overwritten by new insertions into the GHashTable. It is also not advisable to mix static strings and dynamically-allocated strings in a GHashTable, because it then becomes difficult to determine whether the string should be freed.

To create a GHashTable, use g_hash_table_new().

To insert a key and value into a GHashTable, use g_hash_table_insert().

To lookup a value corresponding to a given key, use g_hash_table_lookup() and g_hash_table_lookup_extended().

To remove a key and value, use g_hash_table_remove().

To call a function for each key and value pair use g_hash_table_foreach().

To destroy a GHashTable use g_hash_table_destroy().

Details

GHashTable

typedef struct _GHashTable GHashTable;

The GHashTable struct is an opaque data structure to represent a Hash Table. It should only be accessed via the following functions.

g_hash_table_new ()

GHashTable*         g_hash_table_new                    (GHashFunc hash_func,
                                                         GEqualFunc key_equal_func);

Creates a new GHashTable with a reference count of 1.

hash_func : | a function to create a hash value from a key. Hash values are used to determine where keys are stored within the GHashTable data structure. The g_direct_hash(), g_int_hash() and g_str_hash() functions are provided for some common types of keys. If hash_func is NULL, g_direct_hash() is used.
key_equal_func : | a function to check two keys for equality. This is used when looking up keys in the GHashTable. The g_direct_equal(), g_int_equal() and g_str_equal() functions are provided for the most common types of keys. If key_equal_func is NULL, keys are compared directly in a similar fashion to g_direct_equal(), but without the overhead of a function call.
Returns : | a new GHashTable.

g_hash_table_new_full ()

GHashTable*         g_hash_table_new_full               (GHashFunc hash_func,
                                                         GEqualFunc key_equal_func,
                                                         GDestroyNotify key_destroy_func,
                                                         GDestroyNotify value_destroy_func);

Creates a new GHashTable like g_hash_table_new() with a reference count of 1 and allows to specify functions to free the memory allocated for the key and value that get called when removing the entry from the GHashTable.

hash_func : | a function to create a hash value from a key.
key_equal_func : | a function to check two keys for equality.
key_destroy_func : | a function to free the memory allocated for the key used when removing the entry from the GHashTable or NULL if you don't want to supply such a function.
value_destroy_func : | a function to free the memory allocated for the value used when removing the entry from the GHashTable or NULL if you don't want to supply such a function.
Returns : | a new GHashTable.

GHashFunc ()

guint               (*GHashFunc)                        (gconstpointer key);

Specifies the type of the hash function which is passed to g_hash_table_new() when a GHashTable is created.

The function is passed a key and should return a guint hash value. The functions g_direct_hash(), g_int_hash() and g_str_hash() provide hash functions which can be used when the key is a gpointer, gint, and gchar* respectively.

FIXME: Need more here. The hash values should be evenly distributed over a fairly large range? The modulus is taken with the hash table size (a prime number) to find the 'bucket' to place each key into. The function should also be very fast, since it is called for each key lookup.

key : | a key.
Returns : | the hash value corresponding to the key.

GEqualFunc ()

gboolean            (*GEqualFunc)                       (gconstpointer a,
                                                         gconstpointer b);

Specifies the type of a function used to test two values for equality. The function should return TRUE if both values are equal and FALSE otherwise.

a : | a value.
b : | a value to compare with.
Returns : | TRUE if a = b; FALSE otherwise.

g_hash_table_insert ()

void                g_hash_table_insert                 (GHashTable *hash_table,
                                                         gpointer key,
                                                         gpointer value);

Inserts a new key and value into a GHashTable.

If the key already exists in the GHashTable its current value is replaced with the new value. If you supplied a value_destroy_func when creating the GHashTable, the old value is freed using that function. If you supplied a key_destroy_func when creating the GHashTable, the passed key is freed using that function.

hash_table : | a GHashTable.
key : | a key to insert.
value : | the value to associate with the key.

g_hash_table_replace ()

void                g_hash_table_replace                (GHashTable *hash_table,
                                                         gpointer key,
                                                         gpointer value);

Inserts a new key and value into a GHashTable similar to g_hash_table_insert(). The difference is that if the key already exists in the GHashTable, it gets replaced by the new key. If you supplied a value_destroy_func when creating the GHashTable, the old value is freed using that function. If you supplied a key_destroy_func when creating the GHashTable, the old key is freed using that function.

hash_table : | a GHashTable.
key : | a key to insert.
value : | the value to associate with the key.

g_hash_table_size ()

guint               g_hash_table_size                   (GHashTable *hash_table);

Returns the number of elements contained in the GHashTable.

hash_table : | a GHashTable.
Returns : | the number of key/value pairs in the GHashTable.

g_hash_table_lookup ()

gpointer            g_hash_table_lookup                 (GHashTable *hash_table,
                                                         gconstpointer key);

Looks up a key in a GHashTable. Note that this function cannot distinguish between a key that is not present and one which is present and has the value NULL. If you need this distinction, use g_hash_table_lookup_extended().

hash_table : | a GHashTable.
key : | the key to look up.
Returns : | the associated value, or NULL if the key is not found.

g_hash_table_lookup_extended ()

gboolean            g_hash_table_lookup_extended        (GHashTable *hash_table,
                                                         gconstpointer lookup_key,
                                                         gpointer *orig_key,
                                                         gpointer *value);

Looks up a key in the GHashTable, returning the original key and the associated value and a gboolean which is TRUE if the key was found. This is useful if you need to free the memory allocated for the original key, for example before calling g_hash_table_remove().

hash_table : | a GHashTable.
lookup_key : | the key to look up.
orig_key : | returns the original key.
value : | returns the value associated with the key.
Returns : | TRUE if the key was found in the GHashTable.

g_hash_table_foreach ()

void                g_hash_table_foreach                (GHashTable *hash_table,
                                                         GHFunc func,
                                                         gpointer user_data);

Calls the given function for each of the key/value pairs in the GHashTable. The function is passed the key and value of each pair, and the given user_data parameter. The hash table may not be modified while iterating over it (you can't add/remove items). To remove all items matching a predicate, use g_hash_table_foreach_remove().

hash_table : | a GHashTable.
func : | the function to call for each key/value pair.
user_data : | user data to pass to the function.

g_hash_table_find ()

gpointer            g_hash_table_find                   (GHashTable *hash_table,
                                                         GHRFunc predicate,
                                                         gpointer user_data);

Calls the given function for key/value pairs in the GHashTable until predicate returns TRUE. The function is passed the key and value of each pair, and the given user_data parameter. The hash table may not be modified while iterating over it (you can't add/remove items).

hash_table : | a GHashTable.
predicate : | function to test the key/value pairs for a certain property.
user_data : | user data to pass to the function.
Returns : | The value of the first key/value pair is returned, for which func evaluates to TRUE. If no pair with the requested property is found, NULL is returned.

Since 2.4

GHFunc ()

void                (*GHFunc)                           (gpointer key,
                                                         gpointer value,
                                                         gpointer user_data);

Specifies the type of the function passed to g_hash_table_foreach(). It is called with each key/value pair, together with the user_data parameter which is passed to g_hash_table_foreach().

key : | a key.
value : | the value corresponding to the key.
user_data : | user data passed to g_hash_table_foreach().

g_hash_table_remove ()

gboolean            g_hash_table_remove                 (GHashTable *hash_table,
                                                         gconstpointer key);

Removes a key and its associated value from a GHashTable.

If the GHashTable was created using g_hash_table_new_full(), the key and value are freed using the supplied destroy functions, otherwise you have to make sure that any dynamically allocated values are freed yourself.

hash_table : | a GHashTable.
key : | the key to remove.
Returns : | TRUE if the key was found and removed from the GHashTable.

g_hash_table_steal ()

gboolean            g_hash_table_steal                  (GHashTable *hash_table,
                                                         gconstpointer key);

Removes a key and its associated value from a GHashTable without calling the key and value destroy functions.

hash_table : | a GHashTable.
key : | the key to remove.
Returns : | TRUE if the key was found and removed from the GHashTable.

g_hash_table_foreach_remove ()

guint               g_hash_table_foreach_remove         (GHashTable *hash_table,
                                                         GHRFunc func,
                                                         gpointer user_data);

Calls the given function for each key/value pair in the GHashTable. If the function returns TRUE, then the key/value pair is removed from the GHashTable. If you supplied key or value destroy functions when creating the GHashTable, they are used to free the memory allocated for the removed keys and values.

hash_table : | a GHashTable.
func : | the function to call for each key/value pair.
user_data : | user data to pass to the function.
Returns : | the number of key/value pairs removed.

g_hash_table_foreach_steal ()

guint               g_hash_table_foreach_steal          (GHashTable *hash_table,
                                                         GHRFunc func,
                                                         gpointer user_data);

Calls the given function for each key/value pair in the GHashTable. If the function returns TRUE, then the key/value pair is removed from the GHashTable, but no key or value destroy functions are called.

hash_table : | a GHashTable.
func : | the function to call for each key/value pair.
user_data : | user data to pass to the function.
Returns : | the number of key/value pairs removed.

g_hash_table_remove_all ()

void                g_hash_table_remove_all             (GHashTable *hash_table);

Removes all keys and their associated values from a GHashTable.

If the GHashTable was created using g_hash_table_new_full(), the keys and values are freed using the supplied destroy functions, otherwise you have to make sure that any dynamically allocated values are freed yourself.

hash_table : a GHashTable

Since 2.12

g_hash_table_steal_all ()

void                g_hash_table_steal_all              (GHashTable *hash_table);

Removes all keys and their associated values from a GHashTable without calling the key and value destroy functions.

hash_table : a GHashTable.

Since 2.12

GHRFunc ()

gboolean            (*GHRFunc)                          (gpointer key,
                                                         gpointer value,
                                                         gpointer user_data);

Specifies the type of the function passed to g_hash_table_foreach_remove(). It is called with each key/value pair, together with the user_data parameter passed to g_hash_table_foreach_remove(). It should return TRUE if the key/value pair should be removed from the GHashTable.

key : | a key.
value : | the value associated with the key.
user_data : | user data passed to g_hash_table_remove().
Returns : | TRUE if the key/value pair should be removed from the GHashTable.

g_hash_table_freeze()

#define             g_hash_table_freeze(hash_table)

Warning

g_hash_table_freeze is deprecated and should not be used in newly-written code.

This function is deprecated and will be removed in the next major release of GLib. It does nothing.

hash_table : a GHashTable

g_hash_table_thaw()

#define             g_hash_table_thaw(hash_table)

Warning

g_hash_table_thaw is deprecated and should not be used in newly-written code.

This function is deprecated and will be removed in the next major release of GLib. It does nothing.

hash_table : a GHashTable

g_hash_table_destroy ()

void                g_hash_table_destroy                (GHashTable *hash_table);

Destroys all keys and values in the GHashTable and decrements its reference count by 1. If keys and/or values are dynamically allocated, you should either free them first or create the GHashTable with destroy notifiers using g_hash_table_new_full(). In the latter case the destroy functions you supplied will be called on all keys and values during the destruction phase.

hash_table : a GHashTable.

g_hash_table_ref ()

GHashTable*         g_hash_table_ref                    (GHashTable *hash_table);

Atomically increments the reference count of hash_table by one. This function is MT-safe and may be called from any thread.

hash_table : | a valid GHashTable.
Returns : | the passed in GHashTable.

Since 2.10

g_hash_table_unref ()

void                g_hash_table_unref                  (GHashTable *hash_table);

Atomically decrements the reference count of hash_table by one. If the reference count drops to 0, all keys and values will be destroyed, and all memory allocated by the hash table is released. This function is MT-safe and may be called from any thread.

hash_table : a valid GHashTable.

Since 2.10

g_direct_equal ()

gboolean            g_direct_equal                      (gconstpointer v1,
                                                         gconstpointer v2);

Compares two gpointer arguments and returns TRUE if they are equal. It can be passed to g_hash_table_new() as the key_equal_func parameter, when using pointers as keys in a GHashTable.

v1 : | a key.
v2 : | a key to compare with v1.
Returns : | TRUE if the two keys match.

g_direct_hash ()

guint               g_direct_hash                       (gconstpointer v);

Converts a gpointer to a hash value. It can be passed to g_hash_table_new() as the hash_func parameter, when using pointers as keys in a GHashTable.

v : | a gpointer key
Returns : | a hash value corresponding to the key.

g_int_equal ()

gboolean            g_int_equal                         (gconstpointer v1,
                                                         gconstpointer v2);

Compares the two gint values being pointed to and returns TRUE if they are equal. It can be passed to g_hash_table_new() as the key_equal_func parameter, when using pointers to integers as keys in a GHashTable.

v1 : | a pointer to a gint key.
v2 : | a pointer to a gint key to compare with v1.
Returns : | TRUE if the two keys match.

g_int_hash ()

guint               g_int_hash                          (gconstpointer v);

Converts a pointer to a gint to a hash value. It can be passed to g_hash_table_new() as the hash_func parameter, when using pointers to integers values as keys in a GHashTable.

v : | a pointer to a gint key
Returns : | a hash value corresponding to the key.

g_str_equal ()

gboolean            g_str_equal                         (gconstpointer v1,
                                                         gconstpointer v2);

Compares two strings and returns TRUE if they are equal. It can be passed to g_hash_table_new() as the key_equal_func parameter, when using strings as keys in a GHashTable.

v1 : | a key.
v2 : | a key to compare with v1.
Returns : | TRUE if the two keys match.

g_str_hash ()

guint               g_str_hash                          (gconstpointer v);

Converts a string to a hash value. It can be passed to g_hash_table_new() as the hash_func parameter, when using strings as keys in a GHashTable.

v : | a string key.
Returns : | a hash value corresponding to the key.


Hook Functions

Hook Functions — support for manipulating lists of hook functions.

Synopsis

#include <glib.h>

                    GHookList;
void                (*GHookFinalizeFunc)                (GHookList *hook_list,
                                                         GHook *hook);
                    GHook;
void                (*GHookFunc)                        (gpointer data);
gboolean            (*GHookCheckFunc)                   (gpointer data);

void                g_hook_list_init                    (GHookList *hook_list,
                                                         guint hook_size);
void                g_hook_list_invoke                  (GHookList *hook_list,
                                                         gboolean may_recurse);
void                g_hook_list_invoke_check            (GHookList *hook_list,
                                                         gboolean may_recurse);
void                g_hook_list_marshal                 (GHookList *hook_list,
                                                         gboolean may_recurse,
                                                         GHookMarshaller marshaller,
                                                         gpointer marshal_data);
void                (*GHookMarshaller)                  (GHook *hook,
                                                         gpointer marshal_data);
void                g_hook_list_marshal_check           (GHookList *hook_list,
                                                         gboolean may_recurse,
                                                         GHookCheckMarshaller marshaller,
                                                         gpointer marshal_data);
gboolean            (*GHookCheckMarshaller)             (GHook *hook,
                                                         gpointer marshal_data);
void                g_hook_list_clear                   (GHookList *hook_list);

GHook*              g_hook_alloc                        (GHookList *hook_list);
#define             g_hook_append                       ( hook_list, hook )
void                g_hook_prepend                      (GHookList *hook_list,
                                                         GHook *hook);
void                g_hook_insert_before                (GHookList *hook_list,
                                                         GHook *sibling,
                                                         GHook *hook);
void                g_hook_insert_sorted                (GHookList *hook_list,
                                                         GHook *hook,
                                                         GHookCompareFunc func);
gint                (*GHookCompareFunc)                 (GHook *new_hook,
                                                         GHook *sibling);
gint                g_hook_compare_ids                  (GHook *new_hook,
                                                         GHook *sibling);

GHook*              g_hook_get                          (GHookList *hook_list,
                                                         gulong hook_id);
GHook*              g_hook_find                         (GHookList *hook_list,
                                                         gboolean need_valids,
                                                         GHookFindFunc func,
                                                         gpointer data);
gboolean            (*GHookFindFunc)                    (GHook *hook,
                                                         gpointer data);
GHook*              g_hook_find_data                    (GHookList *hook_list,
                                                         gboolean need_valids,
                                                         gpointer data);
GHook*              g_hook_find_func                    (GHookList *hook_list,
                                                         gboolean need_valids,
                                                         gpointer func);
GHook*              g_hook_find_func_data               (GHookList *hook_list,
                                                         gboolean need_valids,
                                                         gpointer func,
                                                         gpointer data);

GHook*              g_hook_first_valid                  (GHookList *hook_list,
                                                         gboolean may_be_in_call);
GHook*              g_hook_next_valid                   (GHookList *hook_list,
                                                         GHook *hook,
                                                         gboolean may_be_in_call);
enum                GHookFlagMask;
#define             G_HOOK_FLAGS                        (hook)
#define             G_HOOK_FLAG_USER_SHIFT

#define             G_HOOK                              (hook)
#define             G_HOOK_IS_VALID                     (hook)
#define             G_HOOK_ACTIVE                       (hook)
#define             G_HOOK_IN_CALL                      (hook)
#define             G_HOOK_IS_UNLINKED                  (hook)

GHook*              g_hook_ref                          (GHookList *hook_list,
                                                         GHook *hook);
void                g_hook_unref                        (GHookList *hook_list,
                                                         GHook *hook);
void                g_hook_free                         (GHookList *hook_list,
                                                         GHook *hook);
gboolean            g_hook_destroy                      (GHookList *hook_list,
                                                         gulong hook_id);
void                g_hook_destroy_link                 (GHookList *hook_list,
                                                         GHook *hook);

Description

The GHookList, GHook and their related functions provide support for lists of hook functions. Functions can be added and removed from the lists, and the list of hook functions can be invoked.

Details

GHookList

typedef struct {
  gulong	    seq_id;
  guint		    hook_size : 16;
  guint		    is_setup : 1;
  GHook		   *hooks;
  gpointer	    dummy3;
  GHookFinalizeFunc finalize_hook;
  gpointer	    dummy[2];
} GHookList;

The GHookList struct represents a list of hook functions.

gulong seq_id; | the next free GHook id.
guint hook_size : 16; | the size of the GHookList elements, in bytes.
guint is_setup : 1; | 1 if the GHookList has been initialized.
GHook *hooks; | the first GHook element in the list.
gpointer dummy3; |
GHookFinalizeFunc finalize_hook; | the function to call to finalize a GHook element. The default behaviour is to call the hooks destroy function.
gpointer dummy[2]; |

GHookFinalizeFunc ()

void                (*GHookFinalizeFunc)                (GHookList *hook_list,
                                                         GHook *hook);

Defines the type of function to be called when a hook in a list of hooks gets finalized.

hook_list : | a GHookList.
hook : | the hook in hook_list that gets finalized.

GHook

typedef struct {
  gpointer	 data;
  GHook		*next;
  GHook		*prev;
  guint		 ref_count;
  gulong	 hook_id;
  guint		 flags;
  gpointer	 func;
  GDestroyNotify destroy;
} GHook;

The GHook struct represents a single hook function in a GHookList.

gpointer data; | data which is passed to func when this hook is invoked.
GHook *next; | pointer to the next hook in the list.
GHook *prev; | pointer to the previous hook in the list.
guint ref_count; | the reference count of this hook.
gulong hook_id; | the id of this hook, which is unique within its list.
guint flags; | flags which are set for this hook. See GHookFlagMask for predefined flags.
gpointer func; | the function to call when this hook is invoked. The possible signatures for this function are GHookFunc and GHookCheckFunc.
GDestroyNotify destroy; | the default finalize_hook function of a GHookList calls this member of the hook that is being finalized.

GHookFunc ()

void                (*GHookFunc)                        (gpointer data);

Defines the type of a hook function that can be invoked by g_hook_list_invoke().

data : the data field of the GHook is passed to the hook function here.

GHookCheckFunc ()

gboolean            (*GHookCheckFunc)                   (gpointer data);

Defines the type of a hook function that can be invoked by g_hook_list_invoke_check().

data : | the data field of the GHook is passed to the hook function here.
Returns : | FALSE if the GHook should be destroyed.

g_hook_list_init ()

void                g_hook_list_init                    (GHookList *hook_list,
                                                         guint hook_size);

Initializes a GHookList. This must be called before the GHookList is used.

hook_list : | a GHookList.
hook_size : | the size of each element in the GHookList, typically sizeof (GHook).

g_hook_list_invoke ()

void                g_hook_list_invoke                  (GHookList *hook_list,
                                                         gboolean may_recurse);

Calls all of the GHook functions in a GHookList.

hook_list : | a GHookList.
may_recurse : | TRUE if functions which are already running (e.g. in another thread) can be called. If set to FALSE, these are skipped.

g_hook_list_invoke_check ()

void                g_hook_list_invoke_check            (GHookList *hook_list,
                                                         gboolean may_recurse);

Calls all of the GHook functions in a GHookList. Any function which returns TRUE is removed from the GHookList.

hook_list : | a GHookList.
may_recurse : | TRUE if functions which are already running (e.g. in another thread) can be called. If set to FALSE, these are skipped.

g_hook_list_marshal ()

void                g_hook_list_marshal                 (GHookList *hook_list,
                                                         gboolean may_recurse,
                                                         GHookMarshaller marshaller,
                                                         gpointer marshal_data);

Calls a function on each valid GHook.

hook_list : | a GHookList.
may_recurse : | TRUE if hooks which are currently running (e.g. in another thread) are considered valid. If set to FALSE, these are skipped.
marshaller : | the function to call for each GHook.
marshal_data : | data to pass to marshaller.

GHookMarshaller ()

void                (*GHookMarshaller)                  (GHook *hook,
                                                         gpointer marshal_data);

Defines the type of function used by g_hook_list_marshal().

hook : | a GHook.
marshal_data : | user data.

g_hook_list_marshal_check ()

void                g_hook_list_marshal_check           (GHookList *hook_list,
                                                         gboolean may_recurse,
                                                         GHookCheckMarshaller marshaller,
                                                         gpointer marshal_data);

Calls a function on each valid GHook and destroys it if the function returns FALSE.

hook_list : | a GHookList.
may_recurse : | TRUE if hooks which are currently running (e.g. in another thread) are considered valid. If set to FALSE, these are skipped.
marshaller : | the function to call for each GHook.
marshal_data : | data to pass to marshaller.

GHookCheckMarshaller ()

gboolean            (*GHookCheckMarshaller)             (GHook *hook,
                                                         gpointer marshal_data);

Defines the type of function used by g_hook_list_marshal_check().

hook : | a GHook.
marshal_data : | user data.
Returns : | FALSE if hook should be destroyed.

g_hook_list_clear ()

void                g_hook_list_clear                   (GHookList *hook_list);

Removes all the GHook elements from a GHookList.

hook_list : a GHookList.

g_hook_alloc ()

GHook*              g_hook_alloc                        (GHookList *hook_list);

Allocates space for a GHook and initializes it.

hook_list : | a GHookList.
Returns : | a new GHook.

g_hook_append()

#define             g_hook_append( hook_list, hook )

Appends a GHook onto the end of a GHookList.

hook_list : | a GHookList.
hook : | the GHook to add to the end of hook_list.

g_hook_prepend ()

void                g_hook_prepend                      (GHookList *hook_list,
                                                         GHook *hook);

Prepends a GHook on the start of a GHookList.

hook_list : | a GHookList.
hook : | the GHook to add to the start of hook_list.

g_hook_insert_before ()

void                g_hook_insert_before                (GHookList *hook_list,
                                                         GHook *sibling,
                                                         GHook *hook);

Inserts a GHook into a GHookList, before a given GHook.

hook_list : | a GHookList.
sibling : | the GHook to insert the new GHook before.
hook : | the GHook to insert.

g_hook_insert_sorted ()

void                g_hook_insert_sorted                (GHookList *hook_list,
                                                         GHook *hook,
                                                         GHookCompareFunc func);

Inserts a GHook into a GHookList, sorted by the given function.

hook_list : | a GHookList.
hook : | the GHook to insert.
func : | the comparison function used to sort the GHook elements.

GHookCompareFunc ()

gint                (*GHookCompareFunc)                 (GHook *new_hook,
                                                         GHook *sibling);

Defines the type of function used to compare GHook elements in g_hook_insert_sorted().

new_hook : | the GHook being inserted.
sibling : | the GHook to compare with new_hook.
Returns : | a value <= 0 if new_hook should be before sibling.

g_hook_compare_ids ()

gint                g_hook_compare_ids                  (GHook *new_hook,
                                                         GHook *sibling);

Compares the ids of two GHook elements, returning a negative value if the second id is greater than the first.

new_hook : | a GHook.
sibling : | a GHook to compare with new_hook.
Returns : | a value <= 0 if the id of sibling is >= the id of new_hook.

g_hook_get ()

GHook*              g_hook_get                          (GHookList *hook_list,
                                                         gulong hook_id);

Returns the GHook with the given id, or NULL if it is not found.

hook_list : | a GHookList.
hook_id : | a hook id.
Returns : | the GHook with the given id, or NULL if it is not found.

g_hook_find ()

GHook*              g_hook_find                         (GHookList *hook_list,
                                                         gboolean need_valids,
                                                         GHookFindFunc func,
                                                         gpointer data);

Finds a GHook in a GHookList using the given function to test for a match.

hook_list : | a GHookList.
need_valids : | TRUE if GHook elements which have been destroyed should be skipped.
func : | the function to call for each GHook, which should return TRUE when the GHook has been found.
data : | the data to pass to func.
Returns : | the found GHook or NULL if no matching GHook is found.

GHookFindFunc ()

gboolean            (*GHookFindFunc)                    (GHook *hook,
                                                         gpointer data);

Defines the type of the function passed to g_hook_find().

hook : | a GHook.
data : | user data passed to g_hook_find_func().
Returns : | TRUE if the required GHook has been found.

g_hook_find_data ()

GHook*              g_hook_find_data                    (GHookList *hook_list,
                                                         gboolean need_valids,
                                                         gpointer data);

Finds a GHook in a GHookList with the given data.

hook_list : | a GHookList.
need_valids : | TRUE if GHook elements which have been destroyed should be skipped.
data : | the data to find.
Returns : | the GHook with the given data or NULL if no matching GHook is found.

g_hook_find_func ()

GHook*              g_hook_find_func                    (GHookList *hook_list,
                                                         gboolean need_valids,
                                                         gpointer func);

Finds a GHook in a GHookList with the given function.

hook_list : | a GHookList.
need_valids : | TRUE if GHook elements which have been destroyed should be skipped.
func : | the function to find.
Returns : | the GHook with the given func or NULL if no matching GHook is found.

g_hook_find_func_data ()

GHook*              g_hook_find_func_data               (GHookList *hook_list,
                                                         gboolean need_valids,
                                                         gpointer func,
                                                         gpointer data);

Finds a GHook in a GHookList with the given function and data.

hook_list : | a GHookList.
need_valids : | TRUE if GHook elements which have been destroyed should be skipped.
func : | the function to find.
data : | the data to find.
Returns : | the GHook with the given func and data or NULL if no matching GHook is found.

g_hook_first_valid ()

GHook*              g_hook_first_valid                  (GHookList *hook_list,
                                                         gboolean may_be_in_call);

Returns the first GHook in a GHookList which has not been destroyed. The reference count for the GHook is incremented, so you must call g_hook_unref() to restore it when no longer needed. (Or call g_hook_next_valid() if you are stepping through the GHookList.)

hook_list : | a GHookList.
may_be_in_call : | TRUE if hooks which are currently running (e.g. in another thread) are considered valid. If set to FALSE, these are skipped.
Returns : | the first valid GHook, or NULL if none are valid.

g_hook_next_valid ()

GHook*              g_hook_next_valid                   (GHookList *hook_list,
                                                         GHook *hook,
                                                         gboolean may_be_in_call);

Returns the next GHook in a GHookList which has not been destroyed. The reference count for the GHook is incremented, so you must call g_hook_unref() to restore it when no longer needed. (Or continue to call g_hook_next_valid() until NULL is returned.)

hook_list : | a GHookList.
hook : | the current GHook.
may_be_in_call : | TRUE if hooks which are currently running (e.g. in another thread) are considered valid. If set to FALSE, these are skipped.
Returns : | the next valid GHook, or NULL if none are valid.

enum GHookFlagMask

typedef enum
{
  G_HOOK_FLAG_ACTIVE	    = 1 << 0,
  G_HOOK_FLAG_IN_CALL	    = 1 << 1,
  G_HOOK_FLAG_MASK	    = 0x0f
} GHookFlagMask;

Flags used internally in the GHook implementation.

G_HOOK_FLAG_ACTIVE | set if the hook has not been destroyed.
G_HOOK_FLAG_IN_CALL | set if the hook is currently being run.
G_HOOK_FLAG_MASK | A mask covering all bits reserved for hook flags; see G_HOOK_FLAGS_USER_SHIFT

G_HOOK_FLAGS()

#define	G_HOOK_FLAGS(hook)		(G_HOOK (hook)->flags)

Returns the flags of a hook.

hook : a GHook.

G_HOOK_FLAG_USER_SHIFT

#define G_HOOK_FLAG_USER_SHIFT	(4)

The position of the first bit which is not reserved for internal use be the GHook implementation, i.e. 1 << G_HOOK_FLAG_USER_SHIFT is the first bit which can be used for application-defined flags.

G_HOOK()

#define	G_HOOK(hook)			((GHook*) (hook))

Casts a pointer to a GHook*.

hook : a pointer.

G_HOOK_IS_VALID()

#define             G_HOOK_IS_VALID(hook)

Returns TRUE if the GHook is valid, i.e. it is in a GHookList, it is active and it has not been destroyed.

hook : | a GHook.
Returns : | TRUE if the GHook is valid.

G_HOOK_ACTIVE()

#define             G_HOOK_ACTIVE(hook)

Returns TRUE if the GHook is active, which is normally TRUE until the GHook is destroyed.

hook : | a GHook.
Returns : | TRUE if the GHook is active.

G_HOOK_IN_CALL()

#define             G_HOOK_IN_CALL(hook)

Returns TRUE if the GHook function is currently executing.

hook : | a GHook.
Returns : | TRUE if the GHook function is currently executing.

G_HOOK_IS_UNLINKED()

#define             G_HOOK_IS_UNLINKED(hook)

Returns TRUE if the GHook is not in a GHookList.

hook : | a GHook.
Returns : | TRUE if the GHook is not in a GHookList.

g_hook_ref ()

GHook*              g_hook_ref                          (GHookList *hook_list,
                                                         GHook *hook);

Increments the reference count for a GHook.

hook_list : | a GHookList.
hook : | the GHook to increment the reference count of.
Returns : | the hook that was passed in (since 2.6)

g_hook_unref ()

void                g_hook_unref                        (GHookList *hook_list,
                                                         GHook *hook);

Decrements the reference count of a GHook. If the reference count falls to 0, the GHook is removed from the GHookList and g_hook_free() is called to free it.

hook_list : | a GHookList.
hook : | the GHook to unref.

g_hook_free ()

void                g_hook_free                         (GHookList *hook_list,
                                                         GHook *hook);

Calls the GHookList hook_free function if it exists, and frees the memory allocated for the GHook.

hook_list : | a GHookList.
hook : | the GHook to free.

g_hook_destroy ()

gboolean            g_hook_destroy                      (GHookList *hook_list,
                                                         gulong hook_id);

Destroys a GHook, given its ID.

hook_list : | a GHookList.
hook_id : | a hook ID.
Returns : | TRUE if the GHook was found in the GHookList and destroyed.

g_hook_destroy_link ()

void                g_hook_destroy_link                 (GHookList *hook_list,
                                                         GHook *hook);

Removes one GHook from a GHookList, marking it inactive and calling g_hook_unref() on it.

hook_list : | a GHookList.
hook : | the GHook to remove.


Internationalization

Internationalization — gettext support macros.

Synopsis

#include <glib.h>
#include <glib/gi18n.h>

#define             _                                   (String)
#define             Q_                                  (String)
#define             N_                                  (String)
const gchar*        g_strip_context                     (const gchar *msgid,
                                                         const gchar *msgval);

const gchar* const * g_get_language_names               (void);

Description

GLib doesn't force any particular localization method upon its users. But since GLib itself is localized using the gettext() mechanism, it seems natural to offer the de-facto standard gettext() support macros in an easy-to-use form.

In order to use these macros in an application, you must include glib/gi18n.h. For use in a library, must include glib/gi18n-lib.h after defining the GETTEXT_PACKAGE macro suitably for your library:

#define GETTEXT_PACKAGE "gtk20"
#include <glib/gi18n-lib.h>

Details

_()

#define             _(String)

Marks a string for translation, gets replaced with the translated string at runtime.

String : the string to be translated

Since 2.4

Q_()

#define             Q_(String)

Like _(), but applies g_strip_context() to the translation. This has the advantage that the string can be adorned with a prefix to guarantee uniqueness and provide context to the translator.

One use case given in the gettext manual is GUI translation, where one could e.g. disambiguate two "Open" menu entries as "File|Open" and "Printer|Open". Another use case is the string "Russian" which may have to be translated differently depending on whether it's the name of a character set or a language. This could be solved by using "charset|Russian" and "language|Russian".

String : the string to be translated, with a '|'-separated prefix which must not be translated

Since 2.4

N_()

#define             N_(String)

Marks a string for translation, gets replaced with the untranslated string at runtime. This is useful in situations where the translated strings can't be directly used, e.g. in string array initializers.

     {
       static const char *messages[] = {
         N_("some very meaningful message"),
         N_("and another one")
       };
       const char *string;
       ...
       string
         = index > 1 ? _("a default message") : gettext (messages[index]);

       fputs (string);
       ...
     }
String : the string to be translated

Since 2.4

g_strip_context ()

const gchar*        g_strip_context                     (const gchar *msgid,
                                                         const gchar *msgval);

An auxiliary function for gettext() support (see Q_()).

msgid : | a string
msgval : | another string
Returns : | msgval, unless msgval is identical to msgid and contains a '|' character, in which case a pointer to the substring of msgid after the first '|' character is returned.

Since 2.4

g_get_language_names ()

const gchar* const * g_get_language_names               (void);

Computes a list of applicable locale names, which can be used to e.g. construct locale-dependent filenames or search paths. The returned list is sorted from most desirable to least desirable and always contains the default locale "C".

For example, if LANGUAGE=de:en_US, then the returned list is "de", "en_US", "en", "C".

This function consults the environment variables LANGUAGE, LC_ALL, LC_MESSAGES and LANG to find the list of locales specified by the user.

Returns : a NULL-terminated array of strings owned by GLib that must not be modified or freed.

Since 2.6

See Also

The gettext manual.


IO Channels

IO Channels — portable support for using files, pipes and sockets.

Synopsis

#include <glib.h>

                    GIOChannel;

GIOChannel*         g_io_channel_unix_new               (int fd);
gint                g_io_channel_unix_get_fd            (GIOChannel *channel);
GIOChannel*         g_io_channel_win32_new_fd           (gint fd);
GIOChannel*         g_io_channel_win32_new_socket       (gint socket);
GIOChannel*         g_io_channel_win32_new_messages     (guint hwnd);

void                g_io_channel_init                   (GIOChannel *channel);

GIOChannel*         g_io_channel_new_file               (const gchar *filename,
                                                         const gchar *mode,
                                                         GError **error);
GIOStatus           g_io_channel_read_chars             (GIOChannel *channel,
                                                         gchar *buf,
                                                         gsize count,
                                                         gsize *bytes_read,
                                                         GError **error);
GIOStatus           g_io_channel_read_unichar           (GIOChannel *channel,
                                                         gunichar *thechar,
                                                         GError **error);
GIOStatus           g_io_channel_read_line              (GIOChannel *channel,
                                                         gchar **str_return,
                                                         gsize *length,
                                                         gsize *terminator_pos,
                                                         GError **error);
GIOStatus           g_io_channel_read_line_string       (GIOChannel *channel,
                                                         GString *buffer,
                                                         gsize *terminator_pos,
                                                         GError **error);
GIOStatus           g_io_channel_read_to_end            (GIOChannel *channel,
                                                         gchar **str_return,
                                                         gsize *length,
                                                         GError **error);
GIOStatus           g_io_channel_write_chars            (GIOChannel *channel,
                                                         const gchar *buf,
                                                         gssize count,
                                                         gsize *bytes_written,
                                                         GError **error);
GIOStatus           g_io_channel_write_unichar          (GIOChannel *channel,
                                                         gunichar thechar,
                                                         GError **error);
GIOStatus           g_io_channel_flush                  (GIOChannel *channel,
                                                         GError **error);
GIOStatus           g_io_channel_seek_position          (GIOChannel *channel,
                                                         gint64 offset,
                                                         GSeekType type,
                                                         GError **error);
enum                GSeekType;
GIOStatus           g_io_channel_shutdown               (GIOChannel *channel,
                                                         gboolean flush,
                                                         GError **err);

enum                GIOStatus;
enum                GIOChannelError;
#define             G_IO_CHANNEL_ERROR
GIOChannelError     g_io_channel_error_from_errno       (gint en);

GIOChannel*         g_io_channel_ref                    (GIOChannel *channel);
void                g_io_channel_unref                  (GIOChannel *channel);

GSource*            g_io_create_watch                   (GIOChannel *channel,
                                                         GIOCondition condition);
guint               g_io_add_watch                      (GIOChannel *channel,
                                                         GIOCondition condition,
                                                         GIOFunc func,
                                                         gpointer user_data);
guint               g_io_add_watch_full                 (GIOChannel *channel,
                                                         gint priority,
                                                         GIOCondition condition,
                                                         GIOFunc func,
                                                         gpointer user_data,
                                                         GDestroyNotify notify);
enum                GIOCondition;
gboolean            (*GIOFunc)                          (GIOChannel *source,
                                                         GIOCondition condition,
                                                         gpointer data);

                    GIOFuncs;

gsize               g_io_channel_get_buffer_size        (GIOChannel *channel);
void                g_io_channel_set_buffer_size        (GIOChannel *channel,
                                                         gsize size);
GIOCondition        g_io_channel_get_buffer_condition   (GIOChannel *channel);
GIOFlags            g_io_channel_get_flags              (GIOChannel *channel);
GIOStatus           g_io_channel_set_flags              (GIOChannel *channel,
                                                         GIOFlags flags,
                                                         GError **error);
enum                GIOFlags;
const gchar*        g_io_channel_get_line_term          (GIOChannel *channel,
                                                         gint *length);
void                g_io_channel_set_line_term          (GIOChannel *channel,
                                                         const gchar *line_term,
                                                         gint length);
gboolean            g_io_channel_get_buffered           (GIOChannel *channel);
void                g_io_channel_set_buffered           (GIOChannel *channel,
                                                         gboolean buffered);
const gchar*        g_io_channel_get_encoding           (GIOChannel *channel);
GIOStatus           g_io_channel_set_encoding           (GIOChannel *channel,
                                                         const gchar *encoding,
                                                         GError **error);
gboolean            g_io_channel_get_close_on_unref     (GIOChannel *channel);
void                g_io_channel_set_close_on_unref     (GIOChannel *channel,
                                                         gboolean do_close);

GIOError            g_io_channel_read                   (GIOChannel *channel,
                                                         gchar *buf,
                                                         gsize count,
                                                         gsize *bytes_read);
enum                GIOError;
GIOError            g_io_channel_write                  (GIOChannel *channel,
                                                         const gchar *buf,
                                                         gsize count,
                                                         gsize *bytes_written);
GIOError            g_io_channel_seek                   (GIOChannel *channel,
                                                         gint64 offset,
                                                         GSeekType type);
void                g_io_channel_close                  (GIOChannel *channel);

Description

The GIOChannel data type aims to provide a portable method for using file descriptors, pipes, and sockets, and integrating them into the main event loop. Currently full support is available on UNIX platforms, support for Windows is only partially complete.

To create a new GIOChannel on UNIX systems use g_io_channel_unix_new(). This works for plain file descriptors, pipes and sockets. Alternatively, a channel can be created for a file in a system independent manner using g_io_channel_new_file().

Once a GIOChannel has been created, it can be used in a generic manner with the functions g_io_channel_read_chars(), g_io_channel_write_chars(), g_io_channel_seek_position(), and g_io_channel_shutdown().

To add a GIOChannel to the main event loop use g_io_add_watch() or g_io_add_watch_full(). Here you specify which events you are interested in on the GIOChannel, and provide a function to be called whenever these events occur.

GIOChannel instances are created with an initial reference count of 1. g_io_channel_ref() and g_io_channel_unref() can be used to increment or decrement the reference count respectively. When the reference count falls to 0, the GIOChannel is freed. (Though it isn't closed automatically, unless it was created using g_io_channel_new_from_file().) Using g_io_add_watch() or g_io_add_watch_full() increments a channel's reference count.

The new functions g_io_channel_read_chars(), g_io_channel_read_line(),
g_io_channel_read_line_string(), g_io_channel_read_to_end(),
g_io_channel_write_chars(), g_io_channel_seek_position(),
and g_io_channel_flush() should not be mixed with the
deprecated functions g_io_channel_read(), g_io_channel_write(),
and g_io_channel_seek() on the same channel.

Details

GIOChannel

typedef struct {
} GIOChannel;

A data structure representing an IO Channel. The fields should be considered private and should only be accessed with the following functions.

g_io_channel_unix_new ()

GIOChannel*         g_io_channel_unix_new               (int fd);

Creates a new GIOChannel given a file descriptor. On UNIX systems this works for plain files, pipes, and sockets.

The returned GIOChannel has a reference count of 1.

The default encoding for GIOChannel is UTF-8. If your application is reading output from a command using via pipe, you may need to set the encoding to the encoding of the current locale (see g_get_charset()) with the g_io_channel_set_encoding() function.

If you want to read raw binary data without interpretation, then call the g_io_channel_set_encoding() function with NULL for the encoding argument.

This function is available in GLib on Windows, too, but you should avoid using it on Windows. The domain of file descriptors and sockets overlap. There is no way for GLib to know which one you mean in case the argument you pass to this function happens to be both a valid file descriptor and socket. If that happens a warning is issued, and GLib assumes that it is the file descriptor you mean.

fd : | a file descriptor.
Returns : | a new GIOChannel.

g_io_channel_unix_get_fd ()

gint                g_io_channel_unix_get_fd            (GIOChannel *channel);

Returns the file descriptor of the GIOChannel.

On Windows this function returns the file descriptor or socket of the GIOChannel.

channel : | a GIOChannel, created with g_io_channel_unix_new().
Returns : | the file descriptor of the GIOChannel.

g_io_channel_win32_new_fd ()

GIOChannel*         g_io_channel_win32_new_fd           (gint fd);

Creates a new GIOChannel given a file descriptor on Windows. This works for file descriptors from the C runtime.

This function works for file descriptors as returned by the open(), creat(), pipe() and fileno() calls in the Microsoft C runtime. In order to meaningfully use this function your code should use the same C runtime as GLib uses, which is msvcrt.dll. Note that in current Microsoft compilers it is near impossible to convince it to build code that would use msvcrt.dll. The last Microsoft compiler version that supported using msvcrt.dll as the C runtime was version 6. The GNU compiler and toolchain for Windows, also known as Mingw, fully supports msvcrt.dll.

If you have created a GIOChannel for a file descriptor and started watching (polling) it, you shouldn't call read() on the file descriptor. This is because adding polling for a file descriptor is implemented in GLib on Windows by starting a thread that sits blocked in a read() from the file descriptor most of the time. All reads from the file descriptor should be done by this internal GLib thread. Your code should call only g_io_channel_read().

This function is available only in GLib on Windows.

fd : | a C library file descriptor.
Returns : | a new GIOChannel.

g_io_channel_win32_new_socket ()

GIOChannel*         g_io_channel_win32_new_socket       (gint socket);

Creates a new GIOChannel given a socket on Windows.

This function works for sockets created by Winsock. It's available only in GLib on Windows.

Polling a GSource created to watch a channel for a socket puts the socket in non-blocking mode. This is a side-effect of the implementation and unavoidable.

socket : |
Returns : | a new GIOChannel.

g_io_channel_win32_new_messages ()

GIOChannel*         g_io_channel_win32_new_messages     (guint hwnd);

Creates a new GIOChannel given a window handle on Windows.

This function creates a GIOChannel that can be used to poll for Windows messages for the window in question.

hwnd : | a window handle.
Returns : | a new GIOChannel.

g_io_channel_init ()

void                g_io_channel_init                   (GIOChannel *channel);

Initializes a GIOChannel struct. This is called by each of the above functions when creating a GIOChannel, and so is not often needed by the application programmer (unless you are creating a new type of GIOChannel).

channel : a GIOChannel.

g_io_channel_new_file ()

GIOChannel*         g_io_channel_new_file               (const gchar *filename,
                                                         const gchar *mode,
                                                         GError **error);

Open a file filename as a GIOChannel using mode mode. This channel will be closed when the last reference to it is dropped, so there is no need to call g_io_channel_close() (though doing so will not cause problems, as long as no attempt is made to access the channel after it is closed).

filename : | A string containing the name of a file.
mode : | One of "r", "w", "a", "r+", "w+", "a+". These have the same meaning as in fopen().
error : | A location to return an error of type G_FILE_ERROR.
Returns : | A GIOChannel on success, NULL on failure.

g_io_channel_read_chars ()

GIOStatus           g_io_channel_read_chars             (GIOChannel *channel,
                                                         gchar *buf,
                                                         gsize count,
                                                         gsize *bytes_read,
                                                         GError **error);

Replacement for g_io_channel_read() with the new API.

channel : | a GIOChannel
buf : | a buffer to read data into
count : | the size of the buffer. Note that the buffer may not be complelely filled even if there is data in the buffer if the remaining data is not a complete character.
bytes_read : | The number of bytes read. This may be zero even on success if count < 6 and the channel's encoding is non-NULL. This indicates that the next UTF-8 character is too wide for the buffer.
error : | A location to return an error of type GConvertError or GIOChannelError.
Returns : | the status of the operation.

g_io_channel_read_unichar ()

GIOStatus           g_io_channel_read_unichar           (GIOChannel *channel,
                                                         gunichar *thechar,
                                                         GError **error);

This function cannot be called on a channel with NULL encoding.

channel : | a GIOChannel
thechar : | a location to return a character
error : | A location to return an error of type GConvertError or GIOChannelError
Returns : | a GIOStatus

g_io_channel_read_line ()

GIOStatus           g_io_channel_read_line              (GIOChannel *channel,
                                                         gchar **str_return,
                                                         gsize *length,
                                                         gsize *terminator_pos,
                                                         GError **error);

Reads a line, including the terminating character(s), from a GIOChannel into a newly-allocated string. str_return will contain allocated memory if the return is G_IO_STATUS_NORMAL.

channel : | a GIOChannel
str_return : | The line read from the GIOChannel, including the line terminator. This data should be freed with g_free() when no longer needed. This is a nul-terminated string. If a length of zero is returned, this will be NULL instead.
length : | location to store length of the read data, or NULL
terminator_pos : | location to store position of line terminator, or NULL
error : | A location to return an error of type GConvertError or GIOChannelError
Returns : | the status of the operation.

g_io_channel_read_line_string ()

GIOStatus           g_io_channel_read_line_string       (GIOChannel *channel,
                                                         GString *buffer,
                                                         gsize *terminator_pos,
                                                         GError **error);

Reads a line from a GIOChannel, using a GString as a buffer.

channel : | a GIOChannel
buffer : | a GString into which the line will be written. If buffer already contains data, the old data will be overwritten.
terminator_pos : | location to store position of line terminator, or NULL
error : | a location to store an error of type GConvertError or GIOChannelError
Returns : | the status of the operation.

g_io_channel_read_to_end ()

GIOStatus           g_io_channel_read_to_end            (GIOChannel *channel,
                                                         gchar **str_return,
                                                         gsize *length,
                                                         GError **error);

Reads all the remaining data from the file.

channel : | a GIOChannel
str_return : | Location to store a pointer to a string holding the remaining data in the GIOChannel. This data should be freed with g_free() when no longer needed. This data is terminated by an extra nul character, but there may be other nuls in the intervening data.
length : | Location to store length of the data
error : | A location to return an error of type GConvertError or GIOChannelError
Returns : | G_IO_STATUS_NORMAL on success. This function never returns G_IO_STATUS_EOF.

g_io_channel_write_chars ()

GIOStatus           g_io_channel_write_chars            (GIOChannel *channel,
                                                         const gchar *buf,
                                                         gssize count,
                                                         gsize *bytes_written,
                                                         GError **error);

Replacement for g_io_channel_write() with the new API.

On seekable channels with encodings other than NULL or UTF-8, generic mixing of reading and writing is not allowed. A call to g_io_channel_write_chars() may only be made on a channel from which data has been read in the cases described in the documentation for g_io_channel_set_encoding().

channel : | a GIOChannel
buf : | a buffer to write data from
count : | the size of the buffer. If -1, the buffer is taken to be a nul-terminated string.
bytes_written : | The number of bytes written. This can be nonzero even if the return value is not G_IO_STATUS_NORMAL. If the return value is G_IO_STATUS_NORMAL and the channel is blocking, this will always be equal to count if count >= 0.
error : | A location to return an error of type GConvertError or GIOChannelError
Returns : | the status of the operation.

g_io_channel_write_unichar ()

GIOStatus           g_io_channel_write_unichar          (GIOChannel *channel,
                                                         gunichar thechar,
                                                         GError **error);

This function cannot be called on a channel with NULL encoding.

channel : | a GIOChannel
thechar : | a character
error : | A location to return an error of type GConvertError or GIOChannelError
Returns : | a GIOStatus

g_io_channel_flush ()

GIOStatus           g_io_channel_flush                  (GIOChannel *channel,
                                                         GError **error);

Flushes the write buffer for the GIOChannel.

channel : | a GIOChannel
error : | location to store an error of type GIOChannelError
Returns : | the status of the operation: One of G_IO_CHANNEL_NORMAL, G_IO_CHANNEL_AGAIN, or G_IO_CHANNEL_ERROR.

g_io_channel_seek_position ()

GIOStatus           g_io_channel_seek_position          (GIOChannel *channel,
                                                         gint64 offset,
                                                         GSeekType type,
                                                         GError **error);

Replacement for g_io_channel_seek() with the new API.

channel : | a GIOChannel
offset : | The offset in bytes from the position specified by type
type : | a GSeekType. The type G_SEEK_CUR is only allowed in those cases where a call to g_io_channel_set_encoding() is allowed. See the documentation for g_io_channel_set_encoding() for details.
error : | A location to return an error of type GIOChannelError
Returns : | the status of the operation.

enum GSeekType

typedef enum
{
  G_SEEK_CUR,
  G_SEEK_SET,
  G_SEEK_END
} GSeekType;

An enumeration specifying the base position for a g_io_channel_seek_position() operation.

G_SEEK_CUR | the current position in the file.
G_SEEK_SET | the start of the file.
G_SEEK_END | the end of the file.

g_io_channel_shutdown ()

GIOStatus           g_io_channel_shutdown               (GIOChannel *channel,
                                                         gboolean flush,
                                                         GError **err);

Close an IO channel. Any pending data to be written will be flushed if flush is TRUE. The channel will not be freed until the last reference is dropped using g_io_channel_unref().

channel : | a GIOChannel
flush : | if TRUE, flush pending
err : | location to store a GIOChannelError
Returns : | the status of the operation.

enum GIOStatus

typedef enum
{
  G_IO_STATUS_ERROR,
  G_IO_STATUS_NORMAL,
  G_IO_STATUS_EOF,
  G_IO_STATUS_AGAIN
} GIOStatus;

Stati returned by most of the GIOFuncs functions.

G_IO_STATUS_ERROR | An error occurred.
G_IO_STATUS_NORMAL | Success.
G_IO_STATUS_EOF | End of file.
G_IO_STATUS_AGAIN | Resource temporarily unavailable.

enum GIOChannelError

typedef enum
{
  /* Derived from errno */
  G_IO_CHANNEL_ERROR_FBIG,
  G_IO_CHANNEL_ERROR_INVAL,
  G_IO_CHANNEL_ERROR_IO,
  G_IO_CHANNEL_ERROR_ISDIR,
  G_IO_CHANNEL_ERROR_NOSPC,
  G_IO_CHANNEL_ERROR_NXIO,
  G_IO_CHANNEL_ERROR_OVERFLOW,
  G_IO_CHANNEL_ERROR_PIPE,
  /* Other */
  G_IO_CHANNEL_ERROR_FAILED
} GIOChannelError;

Error codes returned by GIOChannel operations.

G_IO_CHANNEL_ERROR_FBIG | File too large.
G_IO_CHANNEL_ERROR_INVAL | Invalid argument.
G_IO_CHANNEL_ERROR_IO | IO error.
G_IO_CHANNEL_ERROR_ISDIR | File is a directory.
G_IO_CHANNEL_ERROR_NOSPC | No space left on device.
G_IO_CHANNEL_ERROR_NXIO | No such device or address.
G_IO_CHANNEL_ERROR_OVERFLOW | Value too large for defined datatype.
G_IO_CHANNEL_ERROR_PIPE | Broken pipe.
G_IO_CHANNEL_ERROR_FAILED | Some other error.

G_IO_CHANNEL_ERROR

#define G_IO_CHANNEL_ERROR g_io_channel_error_quark()

Error domain for GIOChannel operations. Errors in this domain will be from the GIOChannelError enumeration. See GError for information on error domains.

g_io_channel_error_from_errno ()

GIOChannelError     g_io_channel_error_from_errno       (gint en);

Converts an errno error number to a GIOChannelError.

en : | an errno error number, e.g. EINVAL.
Returns : | a GIOChannelError error number, e.g. G_IO_CHANNEL_ERROR_INVAL.

g_io_channel_ref ()

GIOChannel*         g_io_channel_ref                    (GIOChannel *channel);

Increments the reference count of a GIOChannel.

channel : | a GIOChannel.
Returns : | the channel that was passed in (since 2.6)

g_io_channel_unref ()

void                g_io_channel_unref                  (GIOChannel *channel);

Decrements the reference count of a GIOChannel.

channel : a GIOChannel.

g_io_create_watch ()

GSource*            g_io_create_watch                   (GIOChannel *channel,
                                                         GIOCondition condition);

Creates a GSource that's dispatched when condition is met for the given channel. For example, if condition is G_IO_IN, the source will be dispatched when there's data available for reading. g_io_add_watch() is a simpler interface to this same functionality, for the case where you want to add the source to the default main loop at the default priority.

On Windows, polling a GSource created to watch a channel for a socket puts the socket in non-blocking mode. This is a side-effect of the implementation and unavoidable.

channel : | a GIOChannel to watch
condition : | conditions to watch for
Returns : | a new GSource

g_io_add_watch ()

guint               g_io_add_watch                      (GIOChannel *channel,
                                                         GIOCondition condition,
                                                         GIOFunc func,
                                                         gpointer user_data);

Adds the GIOChannel into the main event loop with the default priority.

channel : | a GIOChannel.
condition : | the condition to watch for.
func : | the function to call when the condition is satisfied.
user_data : | user data to pass to func.
Returns : | the event source id.

g_io_add_watch_full ()

guint               g_io_add_watch_full                 (GIOChannel *channel,
                                                         gint priority,
                                                         GIOCondition condition,
                                                         GIOFunc func,
                                                         gpointer user_data,
                                                         GDestroyNotify notify);

Adds the GIOChannel into the main event loop with the given priority.

channel : | a GIOChannel.
priority : | the priority of the GIOChannel source.
condition : | the condition to watch for.
func : | the function to call when the condition is satisfied.
user_data : | user data to pass to func.
notify : | the function to call when the source is removed.
Returns : | the event source id.

enum GIOCondition

typedef enum
{
  G_IO_IN	GLIB_SYSDEF_POLLIN,
  G_IO_OUT	GLIB_SYSDEF_POLLOUT,
  G_IO_PRI	GLIB_SYSDEF_POLLPRI,
  G_IO_ERR	GLIB_SYSDEF_POLLERR,
  G_IO_HUP	GLIB_SYSDEF_POLLHUP,
  G_IO_NVAL	GLIB_SYSDEF_POLLNVAL
} GIOCondition;

A bitwise combination representing a condition to watch for on an event source.

G_IO_IN | There is data to read.
G_IO_OUT | Data can be written (without blocking).
G_IO_PRI | There is urgent data to read.
G_IO_ERR | Error condition.
G_IO_HUP | Hung up (the connection has been broken, usually for pipes and sockets).
G_IO_NVAL | Invalid request. The file descriptor is not open.

GIOFunc ()

gboolean            (*GIOFunc)                          (GIOChannel *source,
                                                         GIOCondition condition,
                                                         gpointer data);

Specifies the type of function passed to g_io_add_watch() or g_io_add_watch_full(), which is called when the requested condition on a GIOChannel is satisfied.

source : | the GIOChannel event source.
condition : | the condition which has been satisfied.
data : | user data set in g_io_add_watch() or g_io_add_watch_full().
Returns : | the function should return FALSE if the event source should be removed.

GIOFuncs

typedef struct {
  GIOStatus (*io_read)           (GIOChannel   *channel,
                      gchar        *buf,
                  gsize         count,
                  gsize        *bytes_read,
                  GError      **err);
  GIOStatus (*io_write)          (GIOChannel   *channel,
                  const gchar  *buf,
                  gsize         count,
                  gsize        *bytes_written,
                  GError      **err);
  GIOStatus (*io_seek)           (GIOChannel   *channel,
                  gint64        offset,
                  GSeekType     type,
                  GError      **err);
  GIOStatus  (*io_close)         (GIOChannel   *channel,
                  GError      **err);
  GSource*   (*io_create_watch)  (GIOChannel   *channel,
                  GIOCondition  condition);
  void       (*io_free)          (GIOChannel   *channel);
  GIOStatus  (*io_set_flags)     (GIOChannel   *channel,
                                  GIOFlags      flags,
                  GError      **err);
  GIOFlags   (*io_get_flags)     (GIOChannel   *channel);
} GIOFuncs;

A table of functions used to handle different types of GIOChannel in a generic way.

g_io_channel_get_buffer_size ()

gsize               g_io_channel_get_buffer_size        (GIOChannel *channel);

Gets the buffer size.

channel : | a GIOChannel
Returns : | the size of the buffer.

g_io_channel_set_buffer_size ()

void                g_io_channel_set_buffer_size        (GIOChannel *channel,
                                                         gsize size);

Sets the buffer size.

channel : | a GIOChannel
size : | the size of the buffer. 0 == pick a good size

g_io_channel_get_buffer_condition ()

GIOCondition        g_io_channel_get_buffer_condition   (GIOChannel *channel);

This function returns a GIOCondition depending on whether there is data to be read/space to write data in the internal buffers in the GIOChannel. Only the flags G_IO_IN and G_IO_OUT may be set.

channel : | A GIOChannel
Returns : | A GIOCondition

g_io_channel_get_flags ()

GIOFlags            g_io_channel_get_flags              (GIOChannel *channel);

Gets the current flags for a GIOChannel, including read-only flags such as G_IO_FLAG_IS_READABLE.

The values of the flags G_IO_FLAG_IS_READABLE and G_IO_FLAG_IS_WRITEABLE are cached for internal use by the channel when it is created. If they should change at some later point (e.g. partial shutdown of a socket with the UNIX shutdown() function), the user should immediately call g_io_channel_get_flags() to update the internal values of these flags.

channel : | a GIOChannel
Returns : | the flags which are set on the channel

g_io_channel_set_flags ()

GIOStatus           g_io_channel_set_flags              (GIOChannel *channel,
                                                         GIOFlags flags,
                                                         GError **error);

Sets the (writeable) flags in channel to (flags & G_IO_CHANNEL_SET_MASK).

channel : | a GIOChannel.
flags : | the flags to set on the IO channel.
error : | A location to return an error of type GIOChannelError.
Returns : | the status of the operation.

enum GIOFlags

typedef enum
{
  G_IO_FLAG_APPEND = 1 << 0,
  G_IO_FLAG_NONBLOCK = 1 << 1,
  G_IO_FLAG_IS_READABLE = 1 << 2,	/* Read only flag */
  G_IO_FLAG_IS_WRITEABLE = 1 << 3,	/* Read only flag */
  G_IO_FLAG_IS_SEEKABLE = 1 << 4,	/* Read only flag */
  G_IO_FLAG_MASK = (1 << 5) - 1,
  G_IO_FLAG_GET_MASK = G_IO_FLAG_MASK,
  G_IO_FLAG_SET_MASK = G_IO_FLAG_APPEND | G_IO_FLAG_NONBLOCK
} GIOFlags;

Specifies properties of a GIOChannel. Some of the flags can only be read with g_io_channel_get_flags(), but not changed with g_io_channel_set_flags().

G_IO_FLAG_APPEND | turns on append mode, corresponds to O_APPEND (see the documentation of the UNIX open() syscall).
G_IO_FLAG_NONBLOCK | turns on nonblocking mode, corresponds to O_NONBLOCK/O_NDELAY (see the documentation of the UNIX open() syscall).
G_IO_FLAG_IS_READABLE | indicates that the io channel is readable. This flag can not be changed.
G_IO_FLAG_IS_WRITEABLE | indicates that the io channel is writable. This flag can not be changed.
G_IO_FLAG_IS_SEEKABLE | indicates that the io channel is seekable, i.e. that g_io_channel_seek_position() can be used on it. This flag can not be changed.
G_IO_FLAG_MASK |
G_IO_FLAG_GET_MASK |
G_IO_FLAG_SET_MASK |

g_io_channel_get_line_term ()

const gchar*        g_io_channel_get_line_term          (GIOChannel *channel,
                                                         gint *length);

This returns the string that GIOChannel uses to determine where in the file a line break occurs. A value of NULL indicates auto detection.

channel : | a GIOChannel
length : | a location to return the length of the line terminator
Returns : | The line termination string. This value is owned by GLib and must not be freed.

g_io_channel_set_line_term ()

void                g_io_channel_set_line_term          (GIOChannel *channel,
                                                         const gchar *line_term,
                                                         gint length);

This sets the string that GIOChannel uses to determine where in the file a line break occurs.

channel : | a GIOChannel
line_term : | The line termination string. Use NULL for auto detect. Auto detection breaks on "\n", "\r\n", "\r", "\0", and the Unicode paragraph separator. Auto detection should not be used for anything other than file-based channels.
length : | The length of the termination string. If -1 is passed, the string is assumed to be nul-terminated. This option allows termination strings with embeded nuls.

g_io_channel_get_buffered ()

gboolean            g_io_channel_get_buffered           (GIOChannel *channel);

Returns whether channel is buffered.

channel : | a GIOChannel.
Returns : | TRUE if the channel is buffered.

g_io_channel_set_buffered ()

void                g_io_channel_set_buffered           (GIOChannel *channel,
                                                         gboolean buffered);

The buffering state can only be set if the channel's encoding is NULL. For any other encoding, the channel must be buffered.

A buffered channel can only be set unbuffered if the channel's internal buffers have been flushed. Newly created channels or channels which have returned G_IO_STATUS_EOF not require such a flush. For write-only channels, a call to g_io_channel_flush() is sufficient. For all other channels, the buffers may be flushed by a call to g_io_channel_seek_position(). This includes the possibility of seeking with seek type G_SEEK_CUR and an offset of zero. Note that this means that socket-based channels cannot be set unbuffered once they have had data read from them.

On unbuffered channels, it is safe to mix read and write calls from the new and old APIs, if this is necessary for maintaining old code.

The default state of the channel is buffered.

channel : | a GIOChannel
buffered : | whether to set the channel buffered or unbuffered

g_io_channel_get_encoding ()

const gchar*        g_io_channel_get_encoding           (GIOChannel *channel);

Gets the encoding for the input/output of the channel. The internal encoding is always UTF-8. The encoding NULL makes the channel safe for binary data.

channel : | a GIOChannel
Returns : | A string containing the encoding, this string is owned by GLib and must not be freed.

g_io_channel_set_encoding ()

GIOStatus           g_io_channel_set_encoding           (GIOChannel *channel,
                                                         const gchar *encoding,
                                                         GError **error);

Sets the encoding for the input/output of the channel. The internal encoding is always UTF-8. The default encoding for the external file is UTF-8.

The encoding NULL is safe to use with binary data.

The encoding can only be set if one of the following conditions is true:

1. The channel was just created, and has not been written to or read from yet.

2. The channel is write-only.

3. The channel is a file, and the file pointer was just repositioned by a call to g_io_channel_seek_position(). (This flushes all the internal buffers.)

4. The current encoding is NULL or UTF-8.

5. One of the (new API) read functions has just returned G_IO_STATUS_EOF (or, in the case of g_io_channel_read_to_end(), G_IO_STATUS_NORMAL).

6. One of the functions g_io_channel_read_chars() or g_io_channel_read_unichar() has returned G_IO_STATUS_AGAIN or G_IO_STATUS_ERROR. This may be useful in the case of G_CONVERT_ERROR_ILLEGAL_SEQUENCE. Returning one of these statuses from g_io_channel_read_line(), g_io_channel_read_line_string(), or g_io_channel_read_to_end() does not guarantee that the encoding can be changed.

Channels which do not meet one of the above conditions cannot call g_io_channel_seek_position() with an offset of G_SEEK_CUR, and, if they are "seekable", cannot call g_io_channel_write_chars() after calling one of the API "read" functions.

channel : | a GIOChannel
encoding : | the encoding type
error : | location to store an error of type GConvertError.
Returns : | G_IO_STATUS_NORMAL if the encoding was successfully set.

g_io_channel_get_close_on_unref ()

gboolean            g_io_channel_get_close_on_unref     (GIOChannel *channel);

Returns whether the file/socket/whatever associated with channel will be closed when channel receives its final unref and is destroyed. The default value of this is TRUE for channels created by g_io_channel_new_file(), and FALSE for all other channels.

channel : | a GIOChannel.
Returns : | Whether the channel will be closed on the final unref of the GIOChannel data structure.

g_io_channel_set_close_on_unref ()

void                g_io_channel_set_close_on_unref     (GIOChannel *channel,
                                                         gboolean do_close);

Setting this flag to TRUE for a channel you have already closed can cause problems.

channel : | a GIOChannel
do_close : | Whether to close the channel on the final unref of the GIOChannel data structure. The default value of this is TRUE for channels created by g_io_channel_new_file(), and FALSE for all other channels.

g_io_channel_read ()

GIOError            g_io_channel_read                   (GIOChannel *channel,
                                                         gchar *buf,
                                                         gsize count,
                                                         gsize *bytes_read);

Warning

g_io_channel_read has been deprecated since version 2.2 and should not be used in newly-written code. Use g_io_channel_read_chars() instead.

Reads data from a GIOChannel.

channel : | a GIOChannel.
buf : | a buffer to read the data into (which should be at least count bytes long).
count : | the number of bytes to read from the GIOChannel.
bytes_read : | returns the number of bytes actually read.
Returns : | G_IO_ERROR_NONE if the operation was successful.

enum GIOError

typedef enum
{
  G_IO_ERROR_NONE,
  G_IO_ERROR_AGAIN,
  G_IO_ERROR_INVAL,
  G_IO_ERROR_UNKNOWN
} GIOError;

GIOError is only used by the deprecated functions g_io_channel_read(), g_io_channel_write(), and g_io_channel_seek().

G_IO_ERROR_NONE | no error
G_IO_ERROR_AGAIN | an EAGAIN error occurred
G_IO_ERROR_INVAL | an EINVAL error occurred
G_IO_ERROR_UNKNOWN | another error occurred

g_io_channel_write ()

GIOError            g_io_channel_write                  (GIOChannel *channel,
                                                         const gchar *buf,
                                                         gsize count,
                                                         gsize *bytes_written);

Warning

g_io_channel_write has been deprecated since version 2.2 and should not be used in newly-written code. Use g_io_channel_write_chars() instead.

Writes data to a GIOChannel.

channel : | a GIOChannel.
buf : | the buffer containing the data to write.
count : | the number of bytes to write.
bytes_written : | the number of bytes actually written.
Returns : | G_IO_ERROR_NONE if the operation was successful.

g_io_channel_seek ()

GIOError            g_io_channel_seek                   (GIOChannel *channel,
                                                         gint64 offset,
                                                         GSeekType type);

Warning

g_io_channel_seek has been deprecated since version 2.2 and should not be used in newly-written code. Use g_io_channel_seek_position() instead.

Sets the current position in the GIOChannel, similar to the standard library function fseek().

channel : | a GIOChannel.
offset : | an offset, in bytes, which is added to the position specified by type
type : | the position in the file, which can be G_SEEK_CUR (the current position), G_SEEK_SET (the start of the file), or G_SEEK_END (the end of the file).
Returns : | G_IO_ERROR_NONE if the operation was successful.

g_io_channel_close ()

void                g_io_channel_close                  (GIOChannel *channel);

Warning

g_io_channel_close has been deprecated since version 2.2 and should not be used in newly-written code. Use g_io_channel_shutdown() instead.

Close an IO channel. Any pending data to be written will be flushed, ignoring errors. The channel will not be freed until the last reference is dropped using g_io_channel_unref().

channel : A GIOChannel

See Also

gtk_input_add_full(), gtk_input_remove(), gdk_input_add(), gdk_input_add_full(), gdk_input_remove()

Convenience functions for creating GIOChannel instances and adding them to the main event loop.


Key-value file parser

Key-value file parser — parses .ini-like config files

Synopsis

#include <glib.h>

                    GKeyFile;
#define             G_KEY_FILE_ERROR
enum                GKeyFileError;
enum                GKeyFileFlags;
GKeyFile*           g_key_file_new                      (void);
void                g_key_file_free                     (GKeyFile *key_file);
void                g_key_file_set_list_separator       (GKeyFile *key_file,
                                                         gchar separator);
gboolean            g_key_file_load_from_file           (GKeyFile *key_file,
                                                         const gchar *file,
                                                         GKeyFileFlags flags,
                                                         GError **error);
gboolean            g_key_file_load_from_data           (GKeyFile *key_file,
                                                         const gchar *data,
                                                         gsize length,
                                                         GKeyFileFlags flags,
                                                         GError **error);
gboolean            g_key_file_load_from_data_dirs      (GKeyFile *key_file,
                                                         const gchar *file,
                                                         gchar **full_path,
                                                         GKeyFileFlags flags,
                                                         GError **error);
gchar*              g_key_file_to_data                  (GKeyFile *key_file,
                                                         gsize *length,
                                                         GError **error);
gchar*              g_key_file_get_start_group          (GKeyFile *key_file);
gchar**             g_key_file_get_groups               (GKeyFile *key_file,
                                                         gsize *length);
gchar**             g_key_file_get_keys                 (GKeyFile *key_file,
                                                         const gchar *group_name,
                                                         gsize *length,
                                                         GError **error);
gboolean            g_key_file_has_group                (GKeyFile *key_file,
                                                         const gchar *group_name);
gboolean            g_key_file_has_key                  (GKeyFile *key_file,
                                                         const gchar *group_name,
                                                         const gchar *key,
                                                         GError **error);

gchar*              g_key_file_get_value                (GKeyFile *key_file,
                                                         const gchar *group_name,
                                                         const gchar *key,
                                                         GError **error);
gchar*              g_key_file_get_string               (GKeyFile *key_file,
                                                         const gchar *group_name,
                                                         const gchar *key,
                                                         GError **error);
gchar*              g_key_file_get_locale_string        (GKeyFile *key_file,
                                                         const gchar *group_name,
                                                         const gchar *key,
                                                         const gchar *locale,
                                                         GError **error);
gboolean            g_key_file_get_boolean              (GKeyFile *key_file,
                                                         const gchar *group_name,
                                                         const gchar *key,
                                                         GError **error);
gint                g_key_file_get_integer              (GKeyFile *key_file,
                                                         const gchar *group_name,
                                                         const gchar *key,
                                                         GError **error);
gdouble             g_key_file_get_double               (GKeyFile *key_file,
                                                         const gchar *group_name,
                                                         const gchar *key,
                                                         GError **error);
gchar**             g_key_file_get_string_list          (GKeyFile *key_file,
                                                         const gchar *group_name,
                                                         const gchar *key,
                                                         gsize *length,
                                                         GError **error);
gchar**             g_key_file_get_locale_string_list   (GKeyFile *key_file,
                                                         const gchar *group_name,
                                                         const gchar *key,
                                                         const gchar *locale,
                                                         gsize *length,
                                                         GError **error);
gboolean*           g_key_file_get_boolean_list         (GKeyFile *key_file,
                                                         const gchar *group_name,
                                                         const gchar *key,
                                                         gsize *length,
                                                         GError **error);
gint*               g_key_file_get_integer_list         (GKeyFile *key_file,
                                                         const gchar *group_name,
                                                         const gchar *key,
                                                         gsize *length,
                                                         GError **error);
gdouble*            g_key_file_get_double_list          (GKeyFile *key_file,
                                                         const gchar *group_name,
                                                         const gchar *key,
                                                         gsize *length,
                                                         GError **error);
gchar*              g_key_file_get_comment              (GKeyFile *key_file,
                                                         const gchar *group_name,
                                                         const gchar *key,
                                                         GError **error);

void                g_key_file_set_value                (GKeyFile *key_file,
                                                         const gchar *group_name,
                                                         const gchar *key,
                                                         const gchar *value);
void                g_key_file_set_string               (GKeyFile *key_file,
                                                         const gchar *group_name,
                                                         const gchar *key,
                                                         const gchar *string);
void                g_key_file_set_locale_string        (GKeyFile *key_file,
                                                         const gchar *group_name,
                                                         const gchar *key,
                                                         const gchar *locale,
                                                         const gchar *string);
void                g_key_file_set_boolean              (GKeyFile *key_file,
                                                         const gchar *group_name,
                                                         const gchar *key,
                                                         gboolean value);
void                g_key_file_set_integer              (GKeyFile *key_file,
                                                         const gchar *group_name,
                                                         const gchar *key,
                                                         gint value);
void                g_key_file_set_double               (GKeyFile *key_file,
                                                         const gchar *group_name,
                                                         const gchar *key,
                                                         gdouble value);
void                g_key_file_set_string_list          (GKeyFile *key_file,
                                                         const gchar *group_name,
                                                         const gchar *key,
                                                         const gchar * const list[],
                                                         gsize length);
void                g_key_file_set_locale_string_list   (GKeyFile *key_file,
                                                         const gchar *group_name,
                                                         const gchar *key,
                                                         const gchar *locale,
                                                         const gchar * const list[],
                                                         gsize length);
void                g_key_file_set_boolean_list         (GKeyFile *key_file,
                                                         const gchar *group_name,
                                                         const gchar *key,
                                                         gboolean list[],
                                                         gsize length);
void                g_key_file_set_integer_list         (GKeyFile *key_file,
                                                         const gchar *group_name,
                                                         const gchar *key,
                                                         gint list[],
                                                         gsize length);
void                g_key_file_set_double_list          (GKeyFile *key_file,
                                                         const gchar *group_name,
                                                         const gchar *key,
                                                         gdouble list[],
                                                         gsize length);
void                g_key_file_set_comment              (GKeyFile *key_file,
                                                         const gchar *group_name,
                                                         const gchar *key,
                                                         const gchar *comment,
                                                         GError **error);
void                g_key_file_remove_group             (GKeyFile *key_file,
                                                         const gchar *group_name,
                                                         GError **error);
void                g_key_file_remove_key               (GKeyFile *key_file,
                                                         const gchar *group_name,
                                                         const gchar *key,
                                                         GError **error);
void                g_key_file_remove_comment           (GKeyFile *key_file,
                                                         const gchar *group_name,
                                                         const gchar *key,
                                                         GError **error);

Description

GKeyFile lets you parse, edit or create files containing groups of key-value pairs, which we call key files for lack of a better name. Several freedesktop.org specifications use key files now, e.g the Desktop Entry Specification and the Icon Theme Specification.

The syntax of key files is described in detail in the Desktop Entry Specification, here is a quick summary: Key files consists of groups of key-value pairs, interspersed with comments.

# this is just an example
# there can be comments before the first group

[First Group]

Name=Key File Example\tthis value shows\nescaping

# localized strings are stored in multiple key-value pairs
Welcome=Hello
Welcome[de]=Hallo
Welcome[fr]=Bonjour
Welcome[it]=Ciao

[Another Group]

Numbers=2;20;-200;0

Booleans=true;false;true;true

Lines beginning with a '#' and blank lines are considered comments.

Groups are started by a header line containing the group name enclosed in '[' and ']', and ended implicitly by the start of the next group or the end of the file. Each key-value pair must be contained in a group.

Key-value pairs generally have the form key=value, with the exception of localized strings, which have the form key[locale]=value. Space before and after the '=' character are ignored. Newline, tab, carriage return and backslash characters are escaped as \n, \t, \r, and \\, respectively. To preserve leading spaces in values, these can also be escaped as \s.

Key files can store strings (possibly with localized variants), integers, booleans and lists of these. Lists are separated by a separator character, typically ';' or ','. To use the list separator character in a value in a list, it has to be escaped by prefixing it with a backslash.

This syntax is obviously inspired by the .ini files commonly met on Windows, but there are some important differences:

  • .ini files use the ';' character to begin comments, key files use the '#' character.

  • Key files allow only comments before the first group.

  • Key files are always encoded in UTF-8.

  • Key and Group names are case-sensitive, for example a group called [GROUP] is a different group from [group].

Note that in contrast to the Desktop Entry Specification, groups in key files may contain the same key multiple times; the last entry wins. Key files may also contain multiple groups with the same name; they are merged together. Another difference is that keys and group names in key files are not restricted to ASCII characters.

Details

GKeyFile

typedef struct _GKeyFile GKeyFile;

The GKeyFile struct contains only private fields and should not be used directly.

G_KEY_FILE_ERROR

#define G_KEY_FILE_ERROR g_key_file_error_quark()

Error domain for key file parsing. Errors in this domain will be from the GKeyFileError enumeration. See GError for information on error domains.

enum GKeyFileError

typedef enum
{
  G_KEY_FILE_ERROR_UNKNOWN_ENCODING,
  G_KEY_FILE_ERROR_PARSE,
  G_KEY_FILE_ERROR_NOT_FOUND,
  G_KEY_FILE_ERROR_KEY_NOT_FOUND,
  G_KEY_FILE_ERROR_GROUP_NOT_FOUND,
  G_KEY_FILE_ERROR_INVALID_VALUE
} GKeyFileError;

Error codes returned by key file parsing.

G_KEY_FILE_ERROR_UNKNOWN_ENCODING | the text being parsed was in an unknown encoding
G_KEY_FILE_ERROR_PARSE | document was ill-formed
G_KEY_FILE_ERROR_NOT_FOUND | the file was not found
G_KEY_FILE_ERROR_KEY_NOT_FOUND | a requested key was not found
G_KEY_FILE_ERROR_GROUP_NOT_FOUND | a requested group was not found
G_KEY_FILE_ERROR_INVALID_VALUE | a value could not be parsed

enum GKeyFileFlags

typedef enum
{
  G_KEY_FILE_NONE              = 0,
  G_KEY_FILE_KEEP_COMMENTS     = 1 << 0,
  G_KEY_FILE_KEEP_TRANSLATIONS = 1 << 1
} GKeyFileFlags;

Flags which influence the parsing.

G_KEY_FILE_NONE | No flags, default behaviour
G_KEY_FILE_KEEP_COMMENTS | Use this flag if you plan to write the (possibly modified) contents of the key file back to a file; otherwise all comments will be lost when the key file is written back.
G_KEY_FILE_KEEP_TRANSLATIONS | Use this flag if you plan to write the (possibly modified) contents of the key file back to a file; otherwise only the translations for the current language will be written back.

g_key_file_new ()

GKeyFile*           g_key_file_new                      (void);

Creates a new empty GKeyFile object. Use g_key_file_load_from_file(), g_key_file_load_from_data() or g_key_file_load_from_data_dirs() to read an existing key file.

Returns : an empty GKeyFile.

Since 2.6

g_key_file_free ()

void                g_key_file_free                     (GKeyFile *key_file);

Frees a GKeyFile.

key_file : a GKeyFile

Since 2.6

g_key_file_set_list_separator ()

void                g_key_file_set_list_separator       (GKeyFile *key_file,
                                                         gchar separator);

Sets the character which is used to separate values in lists. Typically ';' or ',' are used as separators. The default list separator is ';'.

key_file : | a GKeyFile
separator : | the separator

Since 2.6

g_key_file_load_from_file ()

gboolean            g_key_file_load_from_file           (GKeyFile *key_file,
                                                         const gchar *file,
                                                         GKeyFileFlags flags,
                                                         GError **error);

Loads a key file into an empty GKeyFile structure. If the file could not be loaded then error is set to either a GFileError or GKeyFileError.

key_file : | an empty GKeyFile struct
file : | the path of a filename to load, in the GLib file name encoding
flags : | flags from GKeyFileFlags
error : | return location for a GError, or NULL
Returns : | TRUE if a key file could be loaded, FALSE othewise

Since 2.6

g_key_file_load_from_data ()

gboolean            g_key_file_load_from_data           (GKeyFile *key_file,
                                                         const gchar *data,
                                                         gsize length,
                                                         GKeyFileFlags flags,
                                                         GError **error);

Loads a key file from memory into an empty GKeyFile structure. If the object cannot be created then error is set to a GKeyFileError.

key_file : | an empty GKeyFile struct
data : | key file loaded in memory.
length : | the length of data in bytes
flags : | flags from GKeyFileFlags
error : | return location for a GError, or NULL
Returns : | TRUE if a key file could be loaded, FALSE othewise

Since 2.6

g_key_file_load_from_data_dirs ()

gboolean            g_key_file_load_from_data_dirs      (GKeyFile *key_file,
                                                         const gchar *file,
                                                         gchar **full_path,
                                                         GKeyFileFlags flags,
                                                         GError **error);

This function looks for a key file named file in the paths returned from g_get_user_data_dir() and g_get_system_data_dirs(), loads the file into key_file and returns the file's full path in full_path. If the file could not be loaded then an error is set to either a GFileError or GKeyFileError.

key_file : | an empty GKeyFile struct
file : | a relative path to a filename to open and parse
full_path : | return location for a string containing the full path of the file, or NULL
flags : | flags from GKeyFileFlags
error : | return location for a GError, or NULL
Returns : | TRUE if a key file could be loaded, FALSE othewise

Since 2.6

g_key_file_to_data ()

gchar*              g_key_file_to_data                  (GKeyFile *key_file,
                                                         gsize *length,
                                                         GError **error);

This function outputs key_file as a string.

key_file : | a GKeyFile
length : | return location for the length of the returned string, or NULL
error : | return location for a GError, or NULL
Returns : | a newly allocated string holding the contents of the GKeyFile

Since 2.6

g_key_file_get_start_group ()

gchar*              g_key_file_get_start_group          (GKeyFile *key_file);

Returns the name of the start group of the file.

key_file : | a GKeyFile
Returns : | The start group of the key file.

Since 2.6

g_key_file_get_groups ()

gchar**             g_key_file_get_groups               (GKeyFile *key_file,
                                                         gsize *length);

Returns all groups in the key file loaded with key_file. The array of returned groups will be NULL-terminated, so length may optionally be NULL.

key_file : | a GKeyFile
length : | return location for the number of returned groups, or NULL
Returns : | a newly-allocated NULL-terminated array of strings. Use g_strfreev() to free it.

Since 2.6

g_key_file_get_keys ()

gchar**             g_key_file_get_keys                 (GKeyFile *key_file,
                                                         const gchar *group_name,
                                                         gsize *length,
                                                         GError **error);

Returns all keys for the group name group_name. The array of returned keys will be NULL-terminated, so length may optionally be NULL. In the event that the group_name cannot be found, NULL is returned and error is set to G_KEY_FILE_ERROR_GROUP_NOT_FOUND.

key_file : | a GKeyFile
group_name : | a group name
length : | return location for the number of keys returned, or NULL
error : | return location for a GError, or NULL
Returns : | a newly-allocated NULL-terminated array of strings. Use g_strfreev() to free it.

Since 2.6

g_key_file_has_group ()

gboolean            g_key_file_has_group                (GKeyFile *key_file,
                                                         const gchar *group_name);

Looks whether the key file has the group group_name.

key_file : | a GKeyFile
group_name : | a group name
Returns : | TRUE if group_name is a part of key_file, FALSE otherwise.

Since 2.6

g_key_file_has_key ()

gboolean            g_key_file_has_key                  (GKeyFile *key_file,
                                                         const gchar *group_name,
                                                         const gchar *key,
                                                         GError **error);

Looks whether the key file has the key key in the group group_name.

key_file : | a GKeyFile
group_name : | a group name
key : | a key name
error : | return location for a GError
Returns : | TRUE if key is a part of group_name, FALSE otherwise.

Since 2.6

g_key_file_get_value ()

gchar*              g_key_file_get_value                (GKeyFile *key_file,
                                                         const gchar *group_name,
                                                         const gchar *key,
                                                         GError **error);

Returns the value associated with key under group_name.

In the event the key cannot be found, NULL is returned and error is set to G_KEY_FILE_ERROR_KEY_NOT_FOUND. In the event that the group_name cannot be found, NULL is returned and error is set to G_KEY_FILE_ERROR_GROUP_NOT_FOUND.

key_file : | a GKeyFile
group_name : | a group name
key : | a key
error : | return location for a GError, or NULL
Returns : | a newly allocated string or NULL if the specified key cannot be found.

Since 2.6

g_key_file_get_string ()

gchar*              g_key_file_get_string               (GKeyFile *key_file,
                                                         const gchar *group_name,
                                                         const gchar *key,
                                                         GError **error);

Returns the value associated with key under group_name.

In the event the key cannot be found, NULL is returned and error is set to G_KEY_FILE_ERROR_KEY_NOT_FOUND. In the event that the group_name cannot be found, NULL is returned and error is set to G_KEY_FILE_ERROR_GROUP_NOT_FOUND.

key_file : | a GKeyFile
group_name : | a group name
key : | a key
error : | return location for a GError, or NULL
Returns : | a newly allocated string or NULL if the specified key cannot be found.

Since 2.6

g_key_file_get_locale_string ()

gchar*              g_key_file_get_locale_string        (GKeyFile *key_file,
                                                         const gchar *group_name,
                                                         const gchar *key,
                                                         const gchar *locale,
                                                         GError **error);

Returns the value associated with key under group_name translated in the given locale if available. If locale is NULL then the current locale is assumed.

If key cannot be found then NULL is returned and error is set to G_KEY_FILE_ERROR_KEY_NOT_FOUND. If the value associated with key cannot be interpreted or no suitable translation can be found then the untranslated value is returned.

key_file : | a GKeyFile
group_name : | a group name
key : | a key
locale : | a locale or NULL
error : | return location for a GError, or NULL
Returns : | a newly allocated string or NULL if the specified key cannot be found.

Since 2.6

g_key_file_get_boolean ()

gboolean            g_key_file_get_boolean              (GKeyFile *key_file,
                                                         const gchar *group_name,
                                                         const gchar *key,
                                                         GError **error);

Returns the value associated with key under group_name as a boolean.

If key cannot be found then the return value is undefined and error is set to G_KEY_FILE_ERROR_KEY_NOT_FOUND. Likewise, if the value associated with key cannot be interpreted as a boolean then the return value is also undefined and error is set to G_KEY_FILE_ERROR_INVALID_VALUE.

key_file : | a GKeyFile
group_name : | a group name
key : | a key
error : | return location for a GError
Returns : | the value associated with the key as a boolean

Since 2.6

g_key_file_get_integer ()

gint                g_key_file_get_integer              (GKeyFile *key_file,
                                                         const gchar *group_name,
                                                         const gchar *key,
                                                         GError **error);

Returns the value associated with key under group_name as an integer. If group_name is NULL, the start_group is used.

If key cannot be found then the return value is undefined and error is set to G_KEY_FILE_ERROR_KEY_NOT_FOUND. Likewise, if the value associated with key cannot be interpreted as an integer then the return value is also undefined and error is set to G_KEY_FILE_ERROR_INVALID_VALUE.

key_file : | a GKeyFile
group_name : | a group name
key : | a key
error : | return location for a GError
Returns : | the value associated with the key as an integer.

Since 2.6

g_key_file_get_double ()

gdouble             g_key_file_get_double               (GKeyFile *key_file,
                                                         const gchar *group_name,
                                                         const gchar *key,
                                                         GError **error);

Returns the value associated with key under group_name as an integer. If group_name is NULL, the start_group is used.

If key cannot be found then the return value is undefined and error is set to G_KEY_FILE_ERROR_KEY_NOT_FOUND. Likewise, if the value associated with key cannot be interpreted as a double then the return value is also undefined and error is set to G_KEY_FILE_ERROR_INVALID_VALUE.

key_file : | a GKeyFile
group_name : | a group name
key : | a key
error : | return location for a GError
Returns : | the value associated with the key as a double.

Since 2.12

g_key_file_get_string_list ()

gchar**             g_key_file_get_string_list          (GKeyFile *key_file,
                                                         const gchar *group_name,
                                                         const gchar *key,
                                                         gsize *length,
                                                         GError **error);

Returns the values associated with key under group_name.

In the event the key cannot be found, NULL is returned and error is set to G_KEY_FILE_ERROR_KEY_NOT_FOUND. In the event that the group_name cannot be found, NULL is returned and error is set to G_KEY_FILE_ERROR_GROUP_NOT_FOUND.

key_file : | a GKeyFile
group_name : | a group name
key : | a key
length : | return location for the number of returned strings, or NULL
error : | return location for a GError, or NULL
Returns : | a NULL-terminated string array or NULL if the specified key cannot be found. The array should be freed with g_strfreev().

Since 2.6

g_key_file_get_locale_string_list ()

gchar**             g_key_file_get_locale_string_list   (GKeyFile *key_file,
                                                         const gchar *group_name,
                                                         const gchar *key,
                                                         const gchar *locale,
                                                         gsize *length,
                                                         GError **error);

Returns the values associated with key under group_name translated in the given locale if available. If locale is NULL then the current locale is assumed.

If key cannot be found then NULL is returned and error is set to G_KEY_FILE_ERROR_KEY_NOT_FOUND. If the values associated with key cannot be interpreted or no suitable translations can be found then the untranslated values are returned. The returned array is NULL-terminated, so length may optionally be NULL.

key_file : | a GKeyFile
group_name : | a group name
key : | a key
locale : | a locale
length : | return location for the number of returned strings or NULL
error : | return location for a GError or NULL
Returns : | a newly allocated NULL-terminated string array or NULL if the key isn't found. The string array should be freed with g_strfreev().

Since 2.6

g_key_file_get_boolean_list ()

gboolean*           g_key_file_get_boolean_list         (GKeyFile *key_file,
                                                         const gchar *group_name,
                                                         const gchar *key,
                                                         gsize *length,
                                                         GError **error);

Returns the values associated with key under group_name as booleans. If group_name is NULL, the start_group is used.

If key cannot be found then the return value is undefined and error is set to G_KEY_FILE_ERROR_KEY_NOT_FOUND. Likewise, if the values associated with key cannot be interpreted as booleans then the return value is also undefined and error is set to G_KEY_FILE_ERROR_INVALID_VALUE.

key_file : | a GKeyFile
group_name : | a group name
key : | a key
length : | the number of booleans returned
error : | return location for a GError
Returns : | the values associated with the key as a boolean

Since 2.6

g_key_file_get_integer_list ()

gint*               g_key_file_get_integer_list         (GKeyFile *key_file,
                                                         const gchar *group_name,
                                                         const gchar *key,
                                                         gsize *length,
                                                         GError **error);

Returns the values associated with key under group_name as integers.

If key cannot be found then the return value is undefined and error is set to G_KEY_FILE_ERROR_KEY_NOT_FOUND. Likewise, if the values associated with key cannot be interpreted as integers then the return value is also undefined and error is set to G_KEY_FILE_ERROR_INVALID_VALUE.

key_file : | a GKeyFile
group_name : | a group name
key : | a key
length : | the number of integers returned
error : | return location for a GError
Returns : | the values associated with the key as a integer

Since 2.6

g_key_file_get_double_list ()

gdouble*            g_key_file_get_double_list          (GKeyFile *key_file,
                                                         const gchar *group_name,
                                                         const gchar *key,
                                                         gsize *length,
                                                         GError **error);

Returns the values associated with key under group_name as doubles. If group_name is NULL, the start group is used.

If key cannot be found then the return value is undefined and error is set to G_KEY_FILE_ERROR_KEY_NOT_FOUND. Likewise, if the values associated with key cannot be interpreted as doubles then the return value is also undefined and error is set to G_KEY_FILE_ERROR_INVALID_VALUE.

key_file : | a GKeyFile
group_name : | a group name
key : | a key
length : | the number of doubles returned
error : | return location for a GError
Returns : | the values associated with the key as a double

Since 2.12

g_key_file_get_comment ()

gchar*              g_key_file_get_comment              (GKeyFile *key_file,
                                                         const gchar *group_name,
                                                         const gchar *key,
                                                         GError **error);

Retrieves a comment above key from group_name. group_name. If key is NULL then comment will be read from above group_name. If both key and group_name are NULL, then comment will be read from above the first group in the file.

key_file : | a GKeyFile
group_name : | a group name, or NULL
key : | a key
error : | return location for a GError
Returns : | a comment that should be freed with g_free()

Since 2.6

g_key_file_set_value ()

void                g_key_file_set_value                (GKeyFile *key_file,
                                                         const gchar *group_name,
                                                         const gchar *key,
                                                         const gchar *value);

Associates a new value with key under group_name. If key cannot be found then it is created. If group_name cannot be found then it is created.

key_file : | a GKeyFile
group_name : | a group name
key : | a key
value : | a string

Since 2.6

g_key_file_set_string ()

void                g_key_file_set_string               (GKeyFile *key_file,
                                                         const gchar *group_name,
                                                         const gchar *key,
                                                         const gchar *string);

Associates a new string value with key under group_name. If key cannot be found then it is created. If group_name cannot be found then it is created.

key_file : | a GKeyFile
group_name : | a group name
key : | a key
string : | a string

Since 2.6

g_key_file_set_locale_string ()

void                g_key_file_set_locale_string        (GKeyFile *key_file,
                                                         const gchar *group_name,
                                                         const gchar *key,
                                                         const gchar *locale,
                                                         const gchar *string);

Associates a string value for key and locale under group_name. If the translation for key cannot be found then it is created.

key_file : | a GKeyFile
group_name : | a group name
key : | a key
locale : | a locale
string : | a string

Since 2.6

g_key_file_set_boolean ()

void                g_key_file_set_boolean              (GKeyFile *key_file,
                                                         const gchar *group_name,
                                                         const gchar *key,
                                                         gboolean value);

Associates a new boolean value with key under group_name. If key cannot be found then it is created.

key_file : | a GKeyFile
group_name : | a group name
key : | a key
value : | TRUE or FALSE

Since 2.6

g_key_file_set_integer ()

void                g_key_file_set_integer              (GKeyFile *key_file,
                                                         const gchar *group_name,
                                                         const gchar *key,
                                                         gint value);

Associates a new integer value with key under group_name. If key cannot be found then it is created.

key_file : | a GKeyFile
group_name : | a group name
key : | a key
value : | an integer value

Since 2.6

g_key_file_set_double ()

void                g_key_file_set_double               (GKeyFile *key_file,
                                                         const gchar *group_name,
                                                         const gchar *key,
                                                         gdouble value);

Associates a new double value with key under group_name. If key cannot be found then it is created. If group_name is NULL, the start group is used.

key_file : | a GKeyFile
group_name : | a group name
key : | a key
value : | an double value

Since 2.12

g_key_file_set_string_list ()

void                g_key_file_set_string_list          (GKeyFile *key_file,
                                                         const gchar *group_name,
                                                         const gchar *key,
                                                         const gchar * const list[],
                                                         gsize length);

Associates a list of string values for key under group_name. If key cannot be found then it is created. If group_name cannot be found then it is created.

key_file : | a GKeyFile
group_name : | a group name
key : | a key
list : | an array of locale string values
length : | number of locale string values in list

Since 2.6

g_key_file_set_locale_string_list ()

void                g_key_file_set_locale_string_list   (GKeyFile *key_file,
                                                         const gchar *group_name,
                                                         const gchar *key,
                                                         const gchar *locale,
                                                         const gchar * const list[],
                                                         gsize length);

Associates a list of string values for key and locale under group_name. If the translation for key cannot be found then it is created.

key_file : | a GKeyFile
group_name : | a group name
key : | a key
locale : | a locale
list : | a NULL-terminated array of locale string values
length : | the length of list

Since 2.6

g_key_file_set_boolean_list ()

void                g_key_file_set_boolean_list         (GKeyFile *key_file,
                                                         const gchar *group_name,
                                                         const gchar *key,
                                                         gboolean list[],
                                                         gsize length);

Associates a list of boolean values with key under group_name. If key cannot be found then it is created. If group_name is NULL, the start_group is used.

key_file : | a GKeyFile
group_name : | a group name
key : | a key
list : | an array of boolean values
length : | length of list

Since 2.6

g_key_file_set_integer_list ()

void                g_key_file_set_integer_list         (GKeyFile *key_file,
                                                         const gchar *group_name,
                                                         const gchar *key,
                                                         gint list[],
                                                         gsize length);

Associates a list of integer values with key under group_name. If key cannot be found then it is created.

key_file : | a GKeyFile
group_name : | a group name
key : | a key
list : | an array of integer values
length : | number of integer values in list

Since 2.6

g_key_file_set_double_list ()

void                g_key_file_set_double_list          (GKeyFile *key_file,
                                                         const gchar *group_name,
                                                         const gchar *key,
                                                         gdouble list[],
                                                         gsize length);

Associates a list of double values with key under group_name. If key cannot be found then it is created. If group_name is NULL the start group is used.

key_file : | a GKeyFile
group_name : | a group name
key : | a key
list : | an array of double values
length : | number of double values in list

Since 2.12

g_key_file_set_comment ()

void                g_key_file_set_comment              (GKeyFile *key_file,
                                                         const gchar *group_name,
                                                         const gchar *key,
                                                         const gchar *comment,
                                                         GError **error);

Places a comment above key from group_name. group_name. If key is NULL then comment will be written above group_name. If both key and group_name are NULL, then comment will be written above the first group in the file.

key_file : | a GKeyFile
group_name : | a group name, or NULL
key : | a key
comment : | a comment
error : | return location for a GError

Since 2.6

g_key_file_remove_group ()

void                g_key_file_remove_group             (GKeyFile *key_file,
                                                         const gchar *group_name,
                                                         GError **error);

Removes the specified group, group_name, from the key file.

key_file : | a GKeyFile
group_name : | a group name
error : | return location for a GError or NULL

Since 2.6

g_key_file_remove_key ()

void                g_key_file_remove_key               (GKeyFile *key_file,
                                                         const gchar *group_name,
                                                         const gchar *key,
                                                         GError **error);

Removes key in group_name from the key file.

key_file : | a GKeyFile
group_name : | a group name
key : | a key name to remove
error : | return location for a GError or NULL

Since 2.6

g_key_file_remove_comment ()

void                g_key_file_remove_comment           (GKeyFile *key_file,
                                                         const gchar *group_name,
                                                         const gchar *key,
                                                         GError **error);

Removes a comment above key from group_name. group_name. If key is NULL then comment will be written above group_name. If both key and group_name are NULL, then comment will be written above the first group in the file.

key_file : | a GKeyFile
group_name : | a group name, or NULL
key : | a key
error : | return location for a GError

Since 2.6


Keyed Data Lists

Keyed Data Lists — lists of data elements which are accessible by a string or GQuark identifier.

Synopsis

#include <glib.h>

                    GData;
void                g_datalist_init                     (GData **datalist);

#define             g_datalist_id_set_data              (dl, q, d)
void                g_datalist_id_set_data_full         (GData **datalist,
                                                         GQuark key_id,
                                                         gpointer data,
                                                         GDestroyNotify destroy_func);
gpointer            g_datalist_id_get_data              (GData **datalist,
                                                         GQuark key_id);
#define             g_datalist_id_remove_data           (dl, q)
gpointer            g_datalist_id_remove_no_notify      (GData **datalist,
                                                         GQuark key_id);

#define             g_datalist_set_data                 (dl, k, d)
#define             g_datalist_set_data_full            (dl, k, d, f)
#define             g_datalist_get_data                 (dl, k)
#define             g_datalist_remove_data              (dl, k)
#define             g_datalist_remove_no_notify         (dl, k)

void                g_datalist_foreach                  (GData **datalist,
                                                         GDataForeachFunc func,
                                                         gpointer user_data);
void                g_datalist_clear                    (GData **datalist);
void                g_datalist_set_flags                (GData **datalist,
                                                         guint flags);
void                g_datalist_unset_flags              (GData **datalist,
                                                         guint flags);
guint               g_datalist_get_flags                (GData **datalist);
#define             G_DATALIST_FLAGS_MASK

Description

Keyed data lists provide lists of arbitrary data elements which can be accessed either with a string or with a GQuark corresponding to the string.

The GQuark methods are quicker, since the strings have to be converted to GQuarks anyway.

Data lists are used for associating arbitrary data with GObjects, using g_object_set_data() and related functions.

To create a datalist, use g_datalist_init().

To add data elements to a datalist use g_datalist_id_set_data(), g_datalist_id_set_data_full(), g_datalist_set_data() and g_datalist_set_data_full().

To get data elements from a datalist use g_datalist_id_get_data() and g_datalist_get_data().

To iterate over all data elements in a datalist use g_datalist_foreach() (not thread-safe).

To remove data elements from a datalist use g_datalist_id_remove_data() and g_datalist_remove_data().

To remove all data elements from a datalist, use g_datalist_clear().

Details

GData

typedef struct _GData GData;

The GData struct is an opaque data structure to represent a Keyed Data List. It should only be accessed via the following functions.

g_datalist_init ()

void                g_datalist_init                     (GData **datalist);

Resets the datalist to NULL. It does not free any memory or call any destroy functions.

datalist : a pointer to a pointer to a datalist.

g_datalist_id_set_data()

#define             g_datalist_id_set_data(dl, q, d)

Sets the data corresponding to the given GQuark id. Any previous data with the same key is removed, and its destroy function is called.

dl : | a datalist.
q : | the GQuark to identify the data element.
d : | the data element, or NULL to remove any previous element corresponding to q.

g_datalist_id_set_data_full ()

void                g_datalist_id_set_data_full         (GData **datalist,
                                                         GQuark key_id,
                                                         gpointer data,
                                                         GDestroyNotify destroy_func);

Sets the data corresponding to the given GQuark id, and the function to be called when the element is removed from the datalist. Any previous data with the same key is removed, and its destroy function is called.

datalist : | a datalist.
key_id : | the GQuark to identify the data element.
data : | the data element or NULL to remove any previous element corresponding to key_id.
destroy_func : | the function to call when the data element is removed. This function will be called with the data element and can be used to free any memory allocated for it. If data is NULL, then destroy_func must also be NULL.

g_datalist_id_get_data ()

gpointer            g_datalist_id_get_data              (GData **datalist,
                                                         GQuark key_id);

Retrieves the data element corresponding to key_id.

datalist : | a datalist.
key_id : | the GQuark identifying a data element.
Returns : | the data element, or NULL if it is not found.

g_datalist_id_remove_data()

#define             g_datalist_id_remove_data(dl, q)

Removes an element, using its GQuark identifier.

dl : | a datalist.
q : | the GQuark identifying the data element.

g_datalist_id_remove_no_notify ()

gpointer            g_datalist_id_remove_no_notify      (GData **datalist,
                                                         GQuark key_id);

Removes an element, without calling its destroy notification function.

datalist : | a datalist.
key_id : | the GQuark identifying a data element.
Returns : | the data previously stored at key_id, or NULL if none.

g_datalist_set_data()

#define             g_datalist_set_data(dl, k, d)

Sets the data element corresponding to the given string identifier.

dl : | a datalist.
k : | the string to identify the data element.
d : | the data element, or NULL to remove any previous element corresponding to k.

g_datalist_set_data_full()

#define             g_datalist_set_data_full(dl, k, d, f)

Sets the data element corresponding to the given string identifier, and the function to be called when the data element is removed.

dl : | a datalist.
k : | the string to identify the data element.
d : | the data element, or NULL to remove any previous element corresponding to k.
f : | the function to call when the data element is removed. This function will be called with the data element and can be used to free any memory allocated for it. If d is NULL, then f must also be NULL.

g_datalist_get_data()

#define             g_datalist_get_data(dl, k)

Gets a data element, using its string identifer. This is slower than g_datalist_id_get_data() because the string is first converted to a GQuark.

dl : | a datalist.
k : | the string identifying a data element.
Returns : | the data element, or NULL if it is not found.

g_datalist_remove_data()

#define             g_datalist_remove_data(dl, k)

Removes an element using its string identifier. The data element's destroy function is called if it has been set.

dl : | a datalist.
k : | the string identifying the data element.

g_datalist_remove_no_notify()

#define             g_datalist_remove_no_notify(dl, k)

Removes an element, without calling its destroy notifier.

dl : | a datalist.
k : | the string identifying the data element.

g_datalist_foreach ()

void                g_datalist_foreach                  (GData **datalist,
                                                         GDataForeachFunc func,
                                                         gpointer user_data);

Calls the given function for each data element of the datalist. The function is called with each data element's GQuark id and data, together with the given user_data parameter. Note that this function is NOT thread-safe. So unless datalist can be protected from any modifications during invocation of this function, it should not be called.

datalist : | a datalist.
func : | the function to call for each data element.
user_data : | user data to pass to the function.

g_datalist_clear ()

void                g_datalist_clear                    (GData **datalist);

Frees all the data elements of the datalist. The data elements' destroy functions are called if they have been set.

datalist : a datalist.

g_datalist_set_flags ()

void                g_datalist_set_flags                (GData **datalist,
                                                         guint flags);

Turns on flag values for a data list. This function is used to keep a small number of boolean flags in an object with a data list without using any additional space. It is not generally useful except in circumstances where space is very tight. (It is used in the base GObject type, for example.)

datalist : | pointer to the location that holds a list
flags : | the flags to turn on. The values of the flags are restricted by G_DATALIST_FLAGS_MASK (currently 3; giving two possible boolean flags). A value for flags that doesn't fit within the mask is an error.

Since 2.8

g_datalist_unset_flags ()

void                g_datalist_unset_flags              (GData **datalist,
                                                         guint flags);

Turns off flag values for a data list. See g_datalist_unset_flags()

datalist : | pointer to the location that holds a list
flags : | the flags to turn off. The values of the flags are restricted by G_DATALIST_FLAGS_MASK (currently 3: giving two possible boolean flags). A value for flags that doesn't fit within the mask is an error.

Since 2.8

g_datalist_get_flags ()

guint               g_datalist_get_flags                (GData **datalist);

Gets flags values packed in together with the datalist. See g_datalist_set_flags().

datalist : | pointer to the location that holds a list
Returns : | the flags of the datalist

Since 2.8

G_DATALIST_FLAGS_MASK

#define G_DATALIST_FLAGS_MASK 0x3

A bitmask that restricts the possible flags passed to g_datalist_set_flags(). Passing a flags value where flags & ~G_DATALIST_FLAGS_MASK != 0 is an error.


Lexical Scanner

Lexical Scanner — a general purpose lexical scanner.

Synopsis

#include <glib.h>

                    GScanner;
GScanner*           g_scanner_new                       (const GScannerConfig *config_templ);
                    GScannerConfig;

void                g_scanner_input_file                (GScanner *scanner,
                                                         gint input_fd);
void                g_scanner_sync_file_offset          (GScanner *scanner);
void                g_scanner_input_text                (GScanner *scanner,
                                                         const gchar *text,
                                                         guint text_len);
GTokenType          g_scanner_peek_next_token           (GScanner *scanner);
GTokenType          g_scanner_get_next_token            (GScanner *scanner);

guint               g_scanner_cur_line                  (GScanner *scanner);
guint               g_scanner_cur_position              (GScanner *scanner);
GTokenType          g_scanner_cur_token                 (GScanner *scanner);
GTokenValue         g_scanner_cur_value                 (GScanner *scanner);
gboolean            g_scanner_eof                       (GScanner *scanner);

guint               g_scanner_set_scope                 (GScanner *scanner,
                                                         guint scope_id);
void                g_scanner_scope_add_symbol          (GScanner *scanner,
                                                         guint scope_id,
                                                         const gchar *symbol,
                                                         gpointer value);
void                g_scanner_scope_foreach_symbol      (GScanner *scanner,
                                                         guint scope_id,
                                                         GHFunc func,
                                                         gpointer user_data);
gpointer            g_scanner_scope_lookup_symbol       (GScanner *scanner,
                                                         guint scope_id,
                                                         const gchar *symbol);
void                g_scanner_scope_remove_symbol       (GScanner *scanner,
                                                         guint scope_id,
                                                         const gchar *symbol);

#define             g_scanner_freeze_symbol_table       (scanner)
#define             g_scanner_thaw_symbol_table         (scanner)
gpointer            g_scanner_lookup_symbol             (GScanner *scanner,
                                                         const gchar *symbol);

void                g_scanner_warn                      (GScanner *scanner,
                                                         const gchar *format,
                                                         ...);
void                g_scanner_error                     (GScanner *scanner,
                                                         const gchar *format,
                                                         ...);
void                g_scanner_unexp_token               (GScanner *scanner,
                                                         GTokenType expected_token,
                                                         const gchar *identifier_spec,
                                                         const gchar *symbol_spec,
                                                         const gchar *symbol_name,
                                                         const gchar *message,
                                                         gint is_error);
void                (*GScannerMsgFunc)                  (GScanner *scanner,
                                                         gchar *message,
                                                         gboolean error);

void                g_scanner_destroy                   (GScanner *scanner);

enum                GTokenType;
union               GTokenValue;
enum                GErrorType;
#define             G_CSET_a_2_z
#define             G_CSET_A_2_Z
#define             G_CSET_DIGITS
#define             G_CSET_LATINC
#define             G_CSET_LATINS

#define             g_scanner_add_symbol                ( scanner, symbol, value )
#define             g_scanner_remove_symbol             ( scanner, symbol )
#define             g_scanner_foreach_symbol            ( scanner, func, data )

Description

The GScanner and its associated functions provide a general purpose lexical scanner.

Details

GScanner

typedef struct {
  /* unused fields */
  gpointer		user_data;
  guint			max_parse_errors;

  /* g_scanner_error() increments this field */
  guint			parse_errors;

  /* name of input stream, featured by the default message handler */
  const gchar		*input_name;

  /* quarked data */
  GData			*qdata;

  /* link into the scanner configuration */
  GScannerConfig	*config;

  /* fields filled in after g_scanner_get_next_token() */
  GTokenType		token;
  GTokenValue		value;
  guint			line;
  guint			position;

  /* fields filled in after g_scanner_peek_next_token() */
  GTokenType		next_token;
  GTokenValue		next_value;
  guint			next_line;
  guint			next_position;

  /* to be considered private */
  GHashTable		*symbol_table;
  gint			input_fd;
  const gchar		*text;
  const gchar		*text_end;
  gchar			*buffer;
  guint			scope_id;

  /* handler function for _warn and _error */
  GScannerMsgFunc	msg_handler;
} GScanner;

The data structure representing a lexical scanner.

You should set input_name after creating the scanner, since it is used by the default message handler when displaying warnings and errors. If you are scanning a file, the file name would be a good choice.

The user_data and max_parse_errors fields are not used. If you need to associate extra data with the scanner you can place them here.

If you want to use your own message handler you can set the msg_handler field. The type of the message handler function is declared by GScannerMsgFunc.

g_scanner_new ()

GScanner*           g_scanner_new                       (const GScannerConfig *config_templ);

Creates a new GScanner. The config_templ structure specifies the initial settings of the scanner, which are copied into the GScanner config field. If you pass NULL then the default settings are used.

config_templ : | the initial scanner settings.
Returns : | the new GScanner.

GScannerConfig

typedef struct {
  /* Character sets
   */
  gchar		*cset_skip_characters;		/* default: " \t\n" */
  gchar		*cset_identifier_first;
  gchar		*cset_identifier_nth;
  gchar		*cpair_comment_single;		/* default: "#\n" */

  /* Should symbol lookup work case sensitive?
   */
  guint		case_sensitive : 1;

  /* Boolean values to be adjusted "on the fly"
   * to configure scanning behaviour.
   */
  guint		skip_comment_multi : 1;		/* C like comment */
  guint		skip_comment_single : 1;	/* single line comment */
  guint		scan_comment_multi : 1;		/* scan multi line comments? */
  guint		scan_identifier : 1;
  guint		scan_identifier_1char : 1;
  guint		scan_identifier_NULL : 1;
  guint		scan_symbols : 1;
  guint		scan_binary : 1;
  guint		scan_octal : 1;
  guint		scan_float : 1;
  guint		scan_hex : 1;			/* `0x0ff0' */
  guint		scan_hex_dollar : 1;		/* `$0ff0' */
  guint		scan_string_sq : 1;		/* string: 'anything' */
  guint		scan_string_dq : 1;		/* string: "\\-escapes!\n" */
  guint		numbers_2_int : 1;		/* bin, octal, hex => int */
  guint		int_2_float : 1;		/* int => G_TOKEN_FLOAT? */
  guint		identifier_2_string : 1;
  guint		char_2_token : 1;		/* return G_TOKEN_CHAR? */
  guint		symbol_2_token : 1;
  guint		scope_0_fallback : 1;		/* try scope 0 on lookups? */
  guint		store_int64 : 1; 		/* use value.v_int64 rather than v_int */
  guint		padding_dummy;
} GScannerConfig;

Specifies the GScanner settings.

cset_skip_characters specifies which characters should be skipped by the scanner (the default is the whitespace characters: space, tab, carriage-return and line-feed).

cset_identifier_first specifies the characters which can start identifiers (the default is G_CSET_a_2_z, "_", and G_CSET_A_2_Z).

cset_identifier_nth specifies the characters which can be used in identifiers, after the first character (the default is G_CSET_a_2_z, "_0123456789", G_CSET_A_2_Z, G_CSET_LATINS, G_CSET_LATINC).

cpair_comment_single specifies the characters at the start and end of single-line comments. The default is "#\n" which means that single-line comments start with a '#' and continue until a '\n' (end of line).

case_sensitive specifies if symbols are case sensitive (the default is FALSE).

skip_comment_multi specifies if multi-line comments are skipped and not returned as tokens (the default is TRUE).

skip_comment_single specifies if single-line comments are skipped and not returned as tokens (the default is TRUE).

scan_comment_multi specifies if multi-line comments are recognized (the default is TRUE).

scan_identifier specifies if identifiers are recognized (the default is TRUE).

scan_identifier_1char specifies if single-character identifiers are recognized (the default is FALSE).

scan_identifier_NULL specifies if NULL is reported as G_TOKEN_IDENTIFIER_NULL. (the default is FALSE).

scan_symbols specifies if symbols are recognized (the default is TRUE).

scan_binary specifies if binary numbers are recognized (the default is FALSE).

scan_octal specifies if octal numbers are recognized (the default is TRUE).

scan_float specifies if floating point numbers are recognized (the default is TRUE).

scan_hex specifies if hexadecimal numbers are recognized (the default is TRUE).

scan_hex_dollar specifies if '$' is recognized as a prefix for hexadecimal numbers (the default is FALSE).

scan_string_sq specifies if strings can be enclosed in single quotes (the default is TRUE).

scan_string_dq specifies if strings can be enclosed in double quotes (the default is TRUE).

numbers_2_int specifies if binary, octal and hexadecimal numbers are reported as G_TOKEN_INT (the default is TRUE).

int_2_float specifies if all numbers are reported as G_TOKEN_FLOAT (the default is FALSE).

identifier_2_string specifies if identifiers are reported as strings (the default is FALSE).

char_2_token specifies if characters are reported by setting token = ch or as G_TOKEN_CHAR (the default is TRUE).

symbol_2_token specifies if symbols are reported by setting token = v_symbol or as G_TOKEN_SYMBOL (the default is FALSE).

scope_0_fallback specifies if a symbol is searched for in the default scope in addition to the current scope (the default is FALSE).

g_scanner_input_file ()

void                g_scanner_input_file                (GScanner *scanner,
                                                         gint input_fd);

Prepares to scan a file.

scanner : | a GScanner.
input_fd : | a file descriptor.

g_scanner_sync_file_offset ()

void                g_scanner_sync_file_offset          (GScanner *scanner);

Rewinds the filedescriptor to the current buffer position and blows the file read ahead buffer. This is useful for third party uses of the scanners filedescriptor, which hooks onto the current scanning position.

scanner : a GScanner.

g_scanner_input_text ()

void                g_scanner_input_text                (GScanner *scanner,
                                                         const gchar *text,
                                                         guint text_len);

Prepares to scan a text buffer.

scanner : | a GScanner.
text : | the text buffer to scan.
text_len : | the length of the text buffer.

g_scanner_peek_next_token ()

GTokenType          g_scanner_peek_next_token           (GScanner *scanner);

Gets the next token, without removing it from the input stream. The token data is placed in the next_token, next_value, next_line, and next_position fields of the GScanner structure.

Note that, while the token is not removed from the input stream (i.e. the next call to g_scanner_get_next_token() will return the same token), it will not be reevaluated. This can lead to surprising results when changing scope after peeking for the next token. Getting the next token after switching the scope will return whatever was peeked before, regardless of any symbols that may have been added or removed in the new scope.

scanner : | a GScanner.
Returns : | the type of the token.

g_scanner_get_next_token ()

GTokenType          g_scanner_get_next_token            (GScanner *scanner);

Gets the next token, removing it from the input stream. The token data is placed in the token, value, line, and position fields of the GScanner structure.

scanner : | a GScanner.
Returns : | the type of the token.

g_scanner_cur_line ()

guint               g_scanner_cur_line                  (GScanner *scanner);

Gets the current line in the input stream (counting from 1).

scanner : | a GScanner.
Returns : | the current line.

g_scanner_cur_position ()

guint               g_scanner_cur_position              (GScanner *scanner);

Gets the current position in the current line (counting from 0).

scanner : | a GScanner.
Returns : | the current position on the line.

g_scanner_cur_token ()

GTokenType          g_scanner_cur_token                 (GScanner *scanner);

Gets the current token type. This is simply the token field in the GScanner structure.

scanner : | a GScanner.
Returns : | the current token type.

g_scanner_cur_value ()

GTokenValue         g_scanner_cur_value                 (GScanner *scanner);

Gets the current token value. This is simply the value field in the GScanner structure.

scanner : | a GScanner.
Returns : | the current token value.

g_scanner_eof ()

gboolean            g_scanner_eof                       (GScanner *scanner);

Returns TRUE if the scanner has reached the end of the file or text buffer.

scanner : | a GScanner.
Returns : | TRUE if the scanner has reached the end of the file or text buffer.

g_scanner_set_scope ()

guint               g_scanner_set_scope                 (GScanner *scanner,
                                                         guint scope_id);

Sets the current scope.

scanner : | a GScanner.
scope_id : | the new scope id.
Returns : | the old scope id.

g_scanner_scope_add_symbol ()

void                g_scanner_scope_add_symbol          (GScanner *scanner,
                                                         guint scope_id,
                                                         const gchar *symbol,
                                                         gpointer value);

Adds a symbol to the given scope.

scanner : | a GScanner.
scope_id : | the scope id.
symbol : | the symbol to add.
value : | the value of the symbol.

g_scanner_scope_foreach_symbol ()

void                g_scanner_scope_foreach_symbol      (GScanner *scanner,
                                                         guint scope_id,
                                                         GHFunc func,
                                                         gpointer user_data);

Calls the given function for each of the symbol/value pairs in the given scope of the GScanner. The function is passed the symbol and value of each pair, and the given user_data parameter.

scanner : | a GScanner.
scope_id : | the scope id.
func : | the function to call for each symbol/value pair.
user_data : | user data to pass to the function.

g_scanner_scope_lookup_symbol ()

gpointer            g_scanner_scope_lookup_symbol       (GScanner *scanner,
                                                         guint scope_id,
                                                         const gchar *symbol);

Looks up a symbol in a scope and return its value. If the symbol is not bound in the scope, NULL is returned.

scanner : | a GScanner.
scope_id : | the scope id.
symbol : | the symbol to look up.
Returns : | the value of symbol in the given scope, or NULL if symbol is not bound in the given scope.

g_scanner_scope_remove_symbol ()

void                g_scanner_scope_remove_symbol       (GScanner *scanner,
                                                         guint scope_id,
                                                         const gchar *symbol);

Removes a symbol from a scope.

scanner : | a GScanner.
scope_id : | the scope id.
symbol : | the symbol to remove.

g_scanner_freeze_symbol_table()

#define             g_scanner_freeze_symbol_table(scanner)

Warning

g_scanner_freeze_symbol_table has been deprecated since version 2.2 and should not be used in newly-written code. This macro does nothing.

There is no reason to use this macro, since it does nothing.

scanner : a GScanner.

g_scanner_thaw_symbol_table()

#define             g_scanner_thaw_symbol_table(scanner)

Warning

g_scanner_thaw_symbol_table has been deprecated since version 2.2 and should not be used in newly-written code. This macro does nothing.

There is no reason to use this macro, since it does nothing.

scanner : a GScanner.

g_scanner_lookup_symbol ()

gpointer            g_scanner_lookup_symbol             (GScanner *scanner,
                                                         const gchar *symbol);

Looks up a symbol in the current scope and return its value. If the symbol is not bound in the current scope, NULL is returned.

scanner : | a GScanner.
symbol : | the symbol to look up.
Returns : | the value of symbol in the current scope, or NULL if symbol is not bound in the current scope.

g_scanner_warn ()

void                g_scanner_warn                      (GScanner *scanner,
                                                         const gchar *format,
                                                         ...);

Outputs a warning message, via the GScanner message handler.

scanner : | a GScanner.
format : | the message format. See the printf() documentation.
... : | the parameters to insert into the format string.

g_scanner_error ()

void                g_scanner_error                     (GScanner *scanner,
                                                         const gchar *format,
                                                         ...);

Outputs an error message, via the GScanner message handler.

scanner : | a GScanner.
format : | the message format. See the printf() documentation.
... : | the parameters to insert into the format string.

g_scanner_unexp_token ()

void                g_scanner_unexp_token               (GScanner *scanner,
                                                         GTokenType expected_token,
                                                         const gchar *identifier_spec,
                                                         const gchar *symbol_spec,
                                                         const gchar *symbol_name,
                                                         const gchar *message,
                                                         gint is_error);

Outputs a message through the scanner's msg_handler, resulting from an unexpected token in the input stream. Note that you should not call g_scanner_peek_next_token() followed by g_scanner_unexp_token() without an intermediate call to g_scanner_get_next_token(), as g_scanner_unexp_token() evaluates the scanner's current token (not the peeked token) to construct part of the message.

scanner : | a GScanner.
expected_token : | the expected token.
identifier_spec : | a string describing how the scanner's user refers to identifiers (NULL defaults to "identifier"). This is used if expected_token is G_TOKEN_IDENTIFIER or G_TOKEN_IDENTIFIER_NULL.
symbol_spec : | a string describing how the scanner's user refers to symbols (NULL defaults to "symbol"). This is used if expected_token is G_TOKEN_SYMBOL or any token value greater than G_TOKEN_LAST.
symbol_name : | the name of the symbol, if the scanner's current token is a symbol.
message : | a message string to output at the end of the warning/error, or NULL.
is_error : | if TRUE it is output as an error. If FALSE it is output as a warning.

GScannerMsgFunc ()

void                (*GScannerMsgFunc)                  (GScanner *scanner,
                                                         gchar *message,
                                                         gboolean error);

Specifies the type of the message handler function.

scanner : | a GScanner.
message : | the message.
error : | TRUE if the message signals an error, FALSE if it signals a warning.

g_scanner_destroy ()

void                g_scanner_destroy                   (GScanner *scanner);

Frees all memory used by the GScanner.

scanner : a GScanner.

enum GTokenType

typedef enum
{
  G_TOKEN_EOF			=   0,

  G_TOKEN_LEFT_PAREN		= '(',
  G_TOKEN_RIGHT_PAREN		= ')',
  G_TOKEN_LEFT_CURLY		= '{',
  G_TOKEN_RIGHT_CURLY		= '}',
  G_TOKEN_LEFT_BRACE		= '[',
  G_TOKEN_RIGHT_BRACE		= ']',
  G_TOKEN_EQUAL_SIGN		= '=',
  G_TOKEN_COMMA			= ',',

  G_TOKEN_NONE			= 256,

  G_TOKEN_ERROR,

  G_TOKEN_CHAR,
  G_TOKEN_BINARY,
  G_TOKEN_OCTAL,
  G_TOKEN_INT,
  G_TOKEN_HEX,
  G_TOKEN_FLOAT,
  G_TOKEN_STRING,

  G_TOKEN_SYMBOL,
  G_TOKEN_IDENTIFIER,
  G_TOKEN_IDENTIFIER_NULL,

  G_TOKEN_COMMENT_SINGLE,
  G_TOKEN_COMMENT_MULTI,
  G_TOKEN_LAST
} GTokenType;

The possible types of token returned from each g_scanner_get_next_token() call.

G_TOKEN_EOF | the end of the file.
G_TOKEN_LEFT_PAREN | a '(' character.
G_TOKEN_LEFT_CURLY | a '{' character.
G_TOKEN_RIGHT_CURLY | a '}' character.

union GTokenValue

union GTokenValue
{
  gpointer	v_symbol;
  gchar		*v_identifier;
  gulong	v_binary;
  gulong	v_octal;
  gulong	v_int;
  guint64       v_int64;
  gdouble	v_float;
  gulong	v_hex;
  gchar		*v_string;
  gchar		*v_comment;
  guchar	v_char;
  guint		v_error;
};

A union holding the value of the token.

enum GErrorType

typedef enum
{
  G_ERR_UNKNOWN,
  G_ERR_UNEXP_EOF,
  G_ERR_UNEXP_EOF_IN_STRING,
  G_ERR_UNEXP_EOF_IN_COMMENT,
  G_ERR_NON_DIGIT_IN_CONST,
  G_ERR_DIGIT_RADIX,
  G_ERR_FLOAT_RADIX,
  G_ERR_FLOAT_MALFORMED
} GErrorType;

The possible errors, used in the v_error field of GTokenValue, when the token is a G_TOKEN_ERROR.

G_ERR_UNKNOWN | unknown error.
G_ERR_UNEXP_EOF | unexpected end of file.
G_ERR_UNEXP_EOF_IN_STRING | unterminated string constant.
G_ERR_UNEXP_EOF_IN_COMMENT | unterminated comment.
G_ERR_NON_DIGIT_IN_CONST | non-digit character in a number.
G_ERR_DIGIT_RADIX | digit beyond radix in a number.
G_ERR_FLOAT_RADIX | non-decimal floating point number.
G_ERR_FLOAT_MALFORMED | malformed floating point number.

G_CSET_a_2_z

#define G_CSET_a_2_z	"abcdefghijklmnopqrstuvwxyz"

The set of lowercase ASCII alphabet characters. Used for specifying valid identifier characters in GScannerConfig.

G_CSET_A_2_Z

#define G_CSET_A_2_Z	"ABCDEFGHIJKLMNOPQRSTUVWXYZ"

The set of uppercase ASCII alphabet characters. Used for specifying valid identifier characters in GScannerConfig.

G_CSET_DIGITS

#define G_CSET_DIGITS	"0123456789"

The set of digits. Used for specifying valid identifier characters in GScannerConfig.

G_CSET_LATINC

#define             G_CSET_LATINC

The set of uppercase ISO 8859-1 alphabet characters which are not ASCII characters. Used for specifying valid identifier characters in GScannerConfig.

G_CSET_LATINS

#define             G_CSET_LATINS

The set of lowercase ISO 8859-1 alphabet characters which are not ASCII characters. Used for specifying valid identifier characters in GScannerConfig.

g_scanner_add_symbol()

#define             g_scanner_add_symbol( scanner, symbol, value )

Warning

g_scanner_add_symbol has been deprecated since version 2.2 and should not be used in newly-written code. Use g_scanner_scope_add_symbol() instead.

Adds a symbol to the default scope.

scanner : | a GScanner.
symbol : | the symbol to add.
value : | the value of the symbol.

g_scanner_remove_symbol()

#define             g_scanner_remove_symbol( scanner, symbol )

Warning

g_scanner_remove_symbol has been deprecated since version 2.2 and should not be used in newly-written code. Use g_scanner_scope_remove_symbol() instead.

Removes a symbol from the default scope.

scanner : | a GScanner.
symbol : | the symbol to remove.

g_scanner_foreach_symbol()

#define             g_scanner_foreach_symbol( scanner, func, data )

Warning

g_scanner_foreach_symbol has been deprecated since version 2.2 and should not be used in newly-written code. Use g_scanner_scope_foreach_symbol() instead.

Calls a function for each symbol in the default scope.

scanner : | a GScanner.
func : | the function to call with each symbol.
data : | data to pass to the function.


Limits of Basic Types

Limits of Basic Types — portable method of determining the limits of the standard types.

Synopsis

#include <glib.h>

#define             G_MININT
#define             G_MAXINT
#define             G_MAXUINT

#define             G_MINSHORT
#define             G_MAXSHORT
#define             G_MAXUSHORT

#define             G_MINLONG
#define             G_MAXLONG
#define             G_MAXULONG

#define             G_MININT8
#define             G_MAXINT8
#define             G_MAXUINT8

#define             G_MININT16
#define             G_MAXINT16
#define             G_MAXUINT16

#define             G_MININT32
#define             G_MAXINT32
#define             G_MAXUINT32

#define             G_MININT64
#define             G_MAXINT64
#define             G_MAXUINT64

#define             G_MAXSIZE

#define             G_MINFLOAT
#define             G_MAXFLOAT

#define             G_MINDOUBLE
#define             G_MAXDOUBLE

Description

These macros provide a portable method to determine the limits of some of the standard integer and floating point types.

Details

G_MININT

#define G_MININT	INT_MIN

The minimum value which can be held in a gint.

G_MAXINT

#define G_MAXINT	INT_MAX

The maximum value which can be held in a gint.

G_MAXUINT

#define G_MAXUINT	UINT_MAX

The maximum value which can be held in a guint.

G_MINSHORT

#define G_MINSHORT	SHRT_MIN

The minimum value which can be held in a gshort.

G_MAXSHORT

#define G_MAXSHORT	SHRT_MAX

The maximum value which can be held in a gshort.

G_MAXUSHORT

#define G_MAXUSHORT	USHRT_MAX

The maximum value which can be held in a gushort.

G_MINLONG

#define G_MINLONG	LONG_MIN

The minimum value which can be held in a glong.

G_MAXLONG

#define G_MAXLONG	LONG_MAX

The maximum value which can be held in a glong.

G_MAXULONG

#define G_MAXULONG	ULONG_MAX

The maximum value which can be held in a gulong.

G_MININT8

#define G_MININT8	((gint8)  0x80)

The minimum value which can be held in a gint8.

Since 2.4

G_MAXINT8

#define G_MAXINT8	((gint8)  0x7f)

The maximum value which can be held in a gint8.

Since 2.4

G_MAXUINT8

#define G_MAXUINT8	((guint8) 0xff)

The maximum value which can be held in a guint8.

Since 2.4

G_MININT16

#define G_MININT16	((gint16)  0x8000)

The minimum value which can be held in a gint16.

Since 2.4

G_MAXINT16

#define G_MAXINT16	((gint16)  0x7fff)

The maximum value which can be held in a gint16.

Since 2.4

G_MAXUINT16

#define G_MAXUINT16	((guint16) 0xffff)

The maximum value which can be held in a guint16.

Since 2.4

G_MININT32

#define G_MININT32	((gint32)  0x80000000)

The minimum value which can be held in a gint32.

Since 2.4

G_MAXINT32

#define G_MAXINT32	((gint32)  0x7fffffff)

The maximum value which can be held in a gint32.

Since 2.4

G_MAXUINT32

#define G_MAXUINT32	((guint32) 0xffffffff)

The maximum value which can be held in a guint32.

Since 2.4

G_MININT64

#define G_MININT64	((gint64) G_GINT64_CONSTANT(0x8000000000000000))

The minimum value which can be held in a gint64.

G_MAXINT64

#define G_MAXINT64	G_GINT64_CONSTANT(0x7fffffffffffffff)

The maximum value which can be held in a gint64.

G_MAXUINT64

#define G_MAXUINT64	G_GINT64_CONSTANT(0xffffffffffffffffU)

The maximum value which can be held in a guint64.

G_MAXSIZE

#define G_MAXSIZE	G_MAXUINT

The maximum value which can be held in a gsize.

Since 2.4

G_MINFLOAT

#define G_MINFLOAT	FLT_MIN

The minimum positive value which can be held in a gfloat.

If you are interested in the smallest value which can be held in a gfloat, use -G_MAX_FLOAT.

G_MAXFLOAT

#define G_MAXFLOAT	FLT_MAX

The maximum value which can be held in a gfloat.

G_MINDOUBLE

#define G_MINDOUBLE	DBL_MIN

The minimum positive value which can be held in a gdouble.

If you are interested in the smallest value which can be held in a gdouble, use -G_MAXDOUBLE.

G_MAXDOUBLE

#define G_MAXDOUBLE	DBL_MAX

The maximum value which can be held in a gdouble.


Memory Allocation

Memory Allocation — general memory-handling.

Synopsis

#include <glib.h>

#define             g_new                               (struct_type, n_structs)
#define             g_new0                              (struct_type, n_structs)
#define             g_renew                             (struct_type, mem, n_structs)
#define             g_try_new                           (struct_type, n_structs)
#define             g_try_new0                          (struct_type, n_structs)
#define             g_try_renew                         (struct_type, mem, n_structs)

gpointer            g_malloc                            (gulong n_bytes);
gpointer            g_malloc0                           (gulong n_bytes);
gpointer            g_realloc                           (gpointer mem,
                                                         gulong n_bytes);
gpointer            g_try_malloc                        (gulong n_bytes);
gpointer            g_try_malloc0                       (gulong n_bytes);
gpointer            g_try_realloc                       (gpointer mem,
                                                         gulong n_bytes);

void                g_free                              (gpointer mem);
extern              gboolean g_mem_gc_friendly;

#define             g_alloca                            (size)
#define             g_newa                              (struct_type, n_structs)

#define             g_memmove                           (dest,src,len)
gpointer            g_memdup                            (gconstpointer mem,
                                                         guint byte_size);

                    GMemVTable;
void                g_mem_set_vtable                    (GMemVTable *vtable);
gboolean            g_mem_is_system_malloc              (void);

extern              GMemVTable	*glib_mem_profiler_table;
void                g_mem_profile                       (void);

Description

These functions provide support for allocating and freeing memory.

Note

If any call to allocate memory fails, the application is terminated. This also means that there is no need to check if the call succeeded.

Details

g_new()

#define             g_new(struct_type, n_structs)

Allocates n_structs elements of type struct_type. The returned pointer is cast to a pointer to the given type. If n_structs is 0 it returns NULL.

Since the returned pointer is already casted to the right type, it is normally unnecessary to cast it explicitly, and doing so might hide memory allocation errors.

struct_type : | the type of the elements to allocate.
n_structs : | the number of elements to allocate.
Returns : | a pointer to the allocated memory, cast to a pointer to struct_type.

g_new0()

#define             g_new0(struct_type, n_structs)

Allocates n_structs elements of type struct_type, initialized to 0's. The returned pointer is cast to a pointer to the given type. If n_structs is 0 it returns NULL.

Since the returned pointer is already casted to the right type, it is normally unnecessary to cast it explicitly, and doing so might hide memory allocation errors.

struct_type : | the type of the elements to allocate.
n_structs : | the number of elements to allocate.
Returns : | a pointer to the allocated memory, cast to a pointer to struct_type.

g_renew()

#define             g_renew(struct_type, mem, n_structs)

Reallocates the memory pointed to by mem, so that it now has space for n_structs elements of type struct_type. It returns the new address of the memory, which may have been moved.

struct_type : | the type of the elements to allocate.
mem : | the currently allocated memory.
n_structs : | the number of elements to allocate.
Returns : | a pointer to the new allocated memory, cast to a pointer to struct_type.

g_try_new()

#define             g_try_new(struct_type, n_structs)

Attempts to allocate n_structs elements of type struct_type, and returns NULL on failure. Contrast with g_new(), which aborts the program on failure. The returned pointer is cast to a pointer to the given type. If n_structs is 0 it returns NULL.

struct_type : | the type of the elements to allocate.
n_structs : | the number of elements to allocate.
Returns : | a pointer to the allocated memory, cast to a pointer to struct_type.

Since 2.8

g_try_new0()

#define             g_try_new0(struct_type, n_structs)

Attempts to allocate n_structs elements of type struct_type, initialized to 0's, and returns NULL on failure. Contrast with g_new0(), which aborts the program on failure. The returned pointer is cast to a pointer to the given type. If n_counts is 0 it returns NULL.

struct_type : | the type of the elements to allocate.
n_structs : | the number of elements to allocate.
Returns : | a pointer to the allocated memory, cast to a pointer to struct_type.

Since 2.8

g_try_renew()

#define             g_try_renew(struct_type, mem, n_structs)

Attempts to reallocate the memory pointed to by mem, so that it now has space for n_structs elements of type struct_type, and returns NULL on failure. Contrast with g_renew(), which aborts the program on failure. It returns the new address of the memory, which may have been moved.

struct_type : | the type of the elements to allocate.
mem : | the currently allocated memory.
n_structs : | the number of elements to allocate.
Returns : | a pointer to the new allocated memory, cast to a pointer to struct_type.

Since 2.8

g_malloc ()

gpointer            g_malloc                            (gulong n_bytes);

Allocates n_bytes bytes of memory. If n_bytes is 0 it returns NULL.

n_bytes : | the number of bytes to allocate.
Returns : | a pointer to the allocated memory.

g_malloc0 ()

gpointer            g_malloc0                           (gulong n_bytes);

Allocates n_bytes bytes of memory, initialized to 0's. If n_bytes is 0 it returns NULL.

n_bytes : | the number of bytes to allocate.
Returns : | a pointer to the allocated memory.

g_realloc ()

gpointer            g_realloc                           (gpointer mem,
                                                         gulong n_bytes);

Reallocates the memory pointed to by mem, so that it now has space for n_bytes bytes of memory. It returns the new address of the memory, which may have been moved. mem may be NULL, in which case it's considered to have zero-length. n_bytes may be 0, in which case NULL will be returned.

mem : | the memory to reallocate.
n_bytes : | new size of the memory in bytes.
Returns : | the new address of the allocated memory.

g_try_malloc ()

gpointer            g_try_malloc                        (gulong n_bytes);

Attempts to allocate n_bytes, and returns NULL on failure. Contrast with g_malloc(), which aborts the program on failure.

n_bytes : | number of bytes to allocate.
Returns : | the allocated memory, or NULL.

g_try_malloc0 ()

gpointer            g_try_malloc0                       (gulong n_bytes);

Attempts to allocate n_bytes, initialized to 0's, and returns NULL on failure. Contrast with g_malloc0(), which aborts the program on failure.

n_bytes : | number of bytes to allocate.
Returns : | the allocated memory, or NULL.

Since 2.8

g_try_realloc ()

gpointer            g_try_realloc                       (gpointer mem,
                                                         gulong n_bytes);

Attempts to realloc mem to a new size, n_bytes, and returns NULL on failure. Contrast with g_realloc(), which aborts the program on failure. If mem is NULL, behaves the same as g_try_malloc().

mem : | previously-allocated memory, or NULL.
n_bytes : | number of bytes to allocate.
Returns : | the allocated memory, or NULL.

g_free ()

void                g_free                              (gpointer mem);

Frees the memory pointed to by mem. If mem is NULL it simply returns.

mem : the memory to free.

g_mem_gc_friendly

extern gboolean g_mem_gc_friendly;

This variable is TRUE if the G_DEBUG environment variable includes the key gc-friendly.

g_alloca()

#define             g_alloca(size)

Allocates size bytes on the stack; these bytes will be freed when the current stack frame is cleaned up. This macro essentially just wraps the alloca() function present on most UNIX variants. Thus it provides the same advantages and pitfalls as alloca():

+ alloca() is very fast, as on most systems it's implemented by just adjusting the stack pointer register.

+ It doesn't cause any memory fragmentation, within its scope, separate alloca() blocks just build up and are released together at function end.

- Allocation sizes have to fit into the current stack frame. For instance in a threaded environment on Linux, the per-thread stack size is limited to 2 Megabytes, so be sparse with alloca() uses.

- Allocation failure due to insufficient stack space is not indicated with a NULL return like e.g. with malloc(). Instead, most systems probably handle it the same way as out of stack space situations from infinite function recursion, i.e. with a segmentation fault.

- Special care has to be taken when mixing alloca() with GNU C variable sized arrays. Stack space allocated with alloca() in the same scope as a variable sized array will be freed together with the variable sized array upon exit of that scope, and not upon exit of the enclosing function scope.

size : | number of bytes to allocate.
Returns : | space for size bytes, allocated on the stack

g_newa()

#define             g_newa(struct_type, n_structs)

Wraps g_alloca() in a more typesafe manner.

struct_type : | Type of memory chunks to be allocated
n_structs : | Number of chunks to be allocated
Returns : | Pointer to stack space for n_structs chunks of type struct_type

g_memmove()

#define             g_memmove(dest,src,len)

Copies a block of memory len bytes long, from src to dest. The source and destination areas may overlap.

In order to use this function, you must include string.h yourself, because this macro will typically simply resolve to memmove() and GLib does not include string.h for you.

dest : | the destination address to copy the bytes to.
src : | the source address to copy the bytes from.
len : | the number of bytes to copy.

g_memdup ()

gpointer            g_memdup                            (gconstpointer mem,
                                                         guint byte_size);

Allocates byte_size bytes of memory, and copies byte_size bytes into it from mem. If mem is NULL it returns NULL.

mem : | the memory to copy.
byte_size : | the number of bytes to copy.
Returns : | a pointer to the newly-allocated copy of the memory, or NULL if mem is NULL.

GMemVTable

typedef struct {
  gpointer (*malloc)      (gsize    n_bytes);
  gpointer (*realloc)     (gpointer mem,
               gsize    n_bytes);
  void     (*free)        (gpointer mem);
  /* optional; set to NULL if not used ! */
  gpointer (*calloc)      (gsize    n_blocks,
               gsize    n_block_bytes);
  gpointer (*try_malloc)  (gsize    n_bytes);
  gpointer (*try_realloc) (gpointer mem,
               gsize    n_bytes);
} GMemVTable;

A set of functions used to perform memory allocation. The same GMemVTable must be used for all allocations in the same program; a call to g_mem_set_vtable(), if it exists, should be prior to any use of GLib.

malloc () | function to use for allocating memory.
realloc () | function to use for reallocating memory.
free () | function to use to free memory.
calloc () | function to use for allocating zero-filled memory.
try_malloc () | function to use for allocating memory without a default error handler.
try_realloc () | function to use for reallocating memory without a default error handler.

g_mem_set_vtable ()

void                g_mem_set_vtable                    (GMemVTable *vtable);

Sets the GMemVTable to use for memory allocation. You can use this to provide custom memory allocation routines. This function must be called before using any other GLib functions. The vtable only needs to provide malloc(), realloc(), and free() functions; GLib can provide default implementations of the others. The malloc() and realloc() implementations should return NULL on failure, GLib will handle error-checking for you. vtable is copied, so need not persist after this function has been called.

vtable : table of memory allocation routines.

g_mem_is_system_malloc ()

gboolean            g_mem_is_system_malloc              (void);

Checks whether the allocator used by g_malloc() is the system's malloc implementation. If it returns TRUE memory allocated with malloc() can be used interchangeable with memory allocated using g_malloc(). This function is useful for avoiding an extra copy of allocated memory returned by a non-GLib-based API.

A different allocator can be set using g_mem_set_vtable().

Returns : if TRUE, malloc() and g_malloc() can be mixed.

glib_mem_profiler_table

extern GMemVTable	*glib_mem_profiler_table;

A GMemVTable containing profiling variants of the memory allocation functions. Use them together with g_mem_profile() in order to get information about the memory allocation pattern of your program.

g_mem_profile ()

void                g_mem_profile                       (void);

Outputs a summary of memory usage.

It outputs the frequency of allocations of different sizes, the total number of bytes which have been allocated, the total number of bytes which have been freed, and the difference between the previous two values, i.e. the number of bytes still in use.

Note that this function will not output anything unless you have previously installed the glib_mem_profiler_table with g_mem_set_vtable().


Memory Allocators

Memory Allocators — deprecated way to allocate chunks of memory for GList, GSList and GNode.

Synopsis

#include <glib.h>

                    GAllocator;
GAllocator*         g_allocator_new                     (const gchar *name,
                                                         guint n_preallocs);
void                g_allocator_free                    (GAllocator *allocator);

Description

Prior to 2.10, GAllocator was used as an efficient way to allocate small pieces of memory for use with the GList, GSList and GNode data structures. Since 2.10, it has been completely replaced by the slice allocator and deprecated.

Details

GAllocator

typedef struct _GAllocator GAllocator;

Warning

GAllocator is deprecated and should not be used in newly-written code.

The GAllocator struct contains private data. and should only be accessed using the following functions.

g_allocator_new ()

GAllocator*         g_allocator_new                     (const gchar *name,
                                                         guint n_preallocs);

Warning

g_allocator_new has been deprecated since version 2.10 and should not be used in newly-written code. Use the slice allocator instead

Creates a new GAllocator.

name : | the name of the GAllocator. This name is used to set the name of the GMemChunk used by the GAllocator, and is only used for debugging.
n_preallocs : | the number of elements in each block of memory allocated. Larger blocks mean less calls to g_malloc(), but some memory may be wasted. (GLib uses 128 elements per block by default.) The value must be between 1 and 65535.
Returns : | a new GAllocator.

g_allocator_free ()

void                g_allocator_free                    (GAllocator *allocator);

Warning

g_allocator_free has been deprecated since version 2.10 and should not be used in newly-written code. Use the slice allocator instead

Frees all of the memory allocated by the GAllocator.

allocator : a GAllocator.


Memory Chunks

Memory Chunks — deprecated way to allocate groups of equal-sized chunks of memory.

Synopsis

#include <glib.h>

                    GMemChunk;
#define             G_ALLOC_AND_FREE
#define             G_ALLOC_ONLY

GMemChunk*          g_mem_chunk_new                     (const gchar *name,
                                                         gint atom_size,
                                                         gulong area_size,
                                                         gint type);
gpointer            g_mem_chunk_alloc                   (GMemChunk *mem_chunk);
gpointer            g_mem_chunk_alloc0                  (GMemChunk *mem_chunk);
void                g_mem_chunk_free                    (GMemChunk *mem_chunk,
                                                         gpointer mem);
void                g_mem_chunk_destroy                 (GMemChunk *mem_chunk);

#define             g_mem_chunk_create                  (type, pre_alloc, alloc_type)
#define             g_chunk_new                         (type, chunk)
#define             g_chunk_new0                        (type, chunk)
#define             g_chunk_free                        (mem, mem_chunk)

void                g_mem_chunk_reset                   (GMemChunk *mem_chunk);
void                g_mem_chunk_clean                   (GMemChunk *mem_chunk);
void                g_blow_chunks                       (void);

void                g_mem_chunk_info                    (void);
void                g_mem_chunk_print                   (GMemChunk *mem_chunk);

Description

Memory chunks provide an space-efficient way to allocate equal-sized pieces of memory, called atoms. However, due to the administrative overhead (in particular for G_ALLOC_AND_FREE, and when used from multiple threads), they are in practise often slower than direct use of g_malloc(). Therefore, memory chunks have been deprecated in favor of the slice allocator, which has been added in 2.10. All internal uses of memory chunks in GLib have been converted to the g_slice API.

There are two types of memory chunks, G_ALLOC_ONLY, and G_ALLOC_AND_FREE.

  • G_ALLOC_ONLY chunks only allow allocation of atoms. The atoms can never be freed individually. The memory chunk can only be free in its entirety.

  • G_ALLOC_AND_FREE chunks do allow atoms to be freed individually. The disadvantage of this is that the memory chunk has to keep track of which atoms have been freed. This results in more memory being used and a slight degradation in performance.

To create a memory chunk use g_mem_chunk_new() or the convenience macro g_mem_chunk_create().

To allocate a new atom use g_mem_chunk_alloc(), g_mem_chunk_alloc0(), or the convenience macros g_chunk_new() or g_chunk_new0().

To free an atom use g_mem_chunk_free(), or the convenience macro g_chunk_free(). (Atoms can only be freed if the memory chunk is created with the type set to G_ALLOC_AND_FREE.)

To free any blocks of memory which are no longer being used, use g_mem_chunk_clean(). To clean all memory chunks, use g_blow_chunks().

To reset the memory chunk, freeing all of the atoms, use g_mem_chunk_reset().

To destroy a memory chunk, use g_mem_chunk_destroy().

To help debug memory chunks, use g_mem_chunk_info() and g_mem_chunk_print().

Example 19. Using a GMemChunk

  GMemChunk *mem_chunk;
  gchar *mem[10000];
  gint i;

  /* Create a GMemChunk with atoms 50 bytes long, and memory blocks holding
     100 bytes. Note that this means that only 2 atoms fit into each memory
     block and so isn't very efficient. */
  mem_chunk = g_mem_chunk_new ("test mem chunk", 50, 100, G_ALLOC_AND_FREE);

  /* Now allocate 10000 atoms. */
  for (i = 0; i < 10000; i++)
    {
      mem[i] = g_chunk_new (gchar, mem_chunk);

      /* Fill in the atom memory with some junk. */
      for (j = 0; j < 50; j++)
    mem[i][j] = i * j;
    }

  /* Now free all of the atoms. Note that since we are going to destroy the
     GMemChunk, this wouldn't normally be used. */
  for (i = 0; i < 10000; i++)
    {
      g_mem_chunk_free (mem_chunk, mem[i]);
    }

  /* We are finished with the GMemChunk, so we destroy it. */
  g_mem_chunk_destroy (mem_chunk);

Example 20. Using a GMemChunk with data structures

  GMemChunk *array_mem_chunk;
  GRealArray *array;

  /* Create a GMemChunk to hold GRealArray structures, using the
     g_mem_chunk_create() convenience macro. We want 1024 atoms in each
     memory block, and we want to be able to free individual atoms. */
  array_mem_chunk = g_mem_chunk_create (GRealArray, 1024, G_ALLOC_AND_FREE);

  /* Allocate one atom, using the g_chunk_new() convenience macro. */
  array = g_chunk_new (GRealArray, array_mem_chunk);

  /* We can now use array just like a normal pointer to a structure. */
  array->data            = NULL;
  array->len             = 0;
  array->alloc           = 0;
  array->zero_terminated = (zero_terminated ? 1 : 0);
  array->clear           = (clear ? 1 : 0);
  array->elt_size        = elt_size;

  /* We can free the element, so it can be reused. */
  g_chunk_free (array, array_mem_chunk);

  /* We destroy the GMemChunk when we are finished with it. */
  g_mem_chunk_destroy (array_mem_chunk);

Details

GMemChunk

typedef struct _GMemChunk GMemChunk;

Warning

GMemChunk is deprecated and should not be used in newly-written code.

The GMemChunk struct is an opaque data structure representing a memory chunk. It should be accessed only through the use of the following functions.

G_ALLOC_AND_FREE

#define G_ALLOC_AND_FREE  2

Warning

G_ALLOC_AND_FREE is deprecated and should not be used in newly-written code.

Specifies the type of a GMemChunk. Used in g_mem_chunk_new() and g_mem_chunk_create() to specify that atoms will be freed individually.

G_ALLOC_ONLY

#define G_ALLOC_ONLY	  1

Warning

G_ALLOC_ONLY is deprecated and should not be used in newly-written code.

Specifies the type of a GMemChunk. Used in g_mem_chunk_new() and g_mem_chunk_create() to specify that atoms will never be freed individually.

g_mem_chunk_new ()

GMemChunk*          g_mem_chunk_new                     (const gchar *name,
                                                         gint atom_size,
                                                         gulong area_size,
                                                         gint type);

Warning

g_mem_chunk_new has been deprecated since version 2.10 and should not be used in newly-written code. Use the slice allocator instead

Creates a new GMemChunk.

name : | a string to identify the GMemChunk. It is not copied so it should be valid for the lifetime of the GMemChunk. It is only used in g_mem_chunk_print(), which is used for debugging.
atom_size : | the size, in bytes, of each element in the GMemChunk.
area_size : | the size, in bytes, of each block of memory allocated to contain the atoms.
type : | the type of the GMemChunk. G_ALLOC_AND_FREE is used if the atoms will be freed individually. G_ALLOC_ONLY should be used if atoms will never be freed individually. G_ALLOC_ONLY is quicker, since it does not need to track free atoms, but it obviously wastes memory if you no longer need many of the atoms.
Returns : | the new GMemChunk.

g_mem_chunk_alloc ()

gpointer            g_mem_chunk_alloc                   (GMemChunk *mem_chunk);

Warning

g_mem_chunk_alloc has been deprecated since version 2.10 and should not be used in newly-written code. Use g_slice_alloc() instead

Allocates an atom of memory from a GMemChunk.

mem_chunk : | a GMemChunk.
Returns : | a pointer to the allocated atom.

g_mem_chunk_alloc0 ()

gpointer            g_mem_chunk_alloc0                  (GMemChunk *mem_chunk);

Warning

g_mem_chunk_alloc0 has been deprecated since version 2.10 and should not be used in newly-written code. Use g_slice_alloc0() instead

Allocates an atom of memory from a GMemChunk, setting the memory to 0.

mem_chunk : | a GMemChunk.
Returns : | a pointer to the allocated atom.

g_mem_chunk_free ()

void                g_mem_chunk_free                    (GMemChunk *mem_chunk,
                                                         gpointer mem);

Warning

g_mem_chunk_free has been deprecated since version 2.10 and should not be used in newly-written code. Use g_slice_free1() instead

Frees an atom in a GMemChunk. This should only be called if the GMemChunk was created with G_ALLOC_AND_FREE. Otherwise it will simply return.

mem_chunk : | a GMemChunk.
mem : | a pointer to the atom to free.

g_mem_chunk_destroy ()

void                g_mem_chunk_destroy                 (GMemChunk *mem_chunk);

Warning

g_mem_chunk_destroy has been deprecated since version 2.10 and should not be used in newly-written code. Use the slice allocator instead

Frees all of the memory allocated for a GMemChunk.

mem_chunk : a GMemChunk.

g_mem_chunk_create()

#define             g_mem_chunk_create(type, pre_alloc, alloc_type)

Warning

g_mem_chunk_create has been deprecated since version 2.10 and should not be used in newly-written code. Use the slice allocator instead

A convenience macro for creating a new GMemChunk. It calls g_mem_chunk_new(), using the given type to create the GMemChunk name. The atom size is determined using sizeof(), and the area size is calculated by multiplying the pre_alloc parameter with the atom size.

type : | the type of the atoms, typically a structure name.
pre_alloc : | the number of atoms to store in each block of memory.
alloc_type : | the type of the GMemChunk. G_ALLOC_AND_FREE is used if the atoms will be freed individually. G_ALLOC_ONLY should be used if atoms will never be freed individually. G_ALLOC_ONLY is quicker, since it does not need to track free atoms, but it obviously wastes memory if you no longer need many of the atoms.
Returns : | the new GMemChunk.

g_chunk_new()

#define             g_chunk_new(type, chunk)

Warning

g_chunk_new has been deprecated since version 2.10 and should not be used in newly-written code. Use g_slice_new() instead

A convenience macro to allocate an atom of memory from a GMemChunk. It calls g_mem_chunk_alloc() and casts the returned atom to a pointer to the given type, avoiding a type cast in the source code.

type : | the type of the GMemChunk atoms, typically a structure name.
chunk : | a GMemChunk.
Returns : | a pointer to the allocated atom, cast to a pointer to type.

g_chunk_new0()

#define             g_chunk_new0(type, chunk)

Warning

g_chunk_new0 has been deprecated since version 2.10 and should not be used in newly-written code. Use g_slice_new0() instead

A convenience macro to allocate an atom of memory from a GMemChunk. It calls g_mem_chunk_alloc0() and casts the returned atom to a pointer to the given type, avoiding a type cast in the source code.

type : | the type of the GMemChunk atoms, typically a structure name.
chunk : | a GMemChunk.
Returns : | a pointer to the allocated atom, cast to a pointer to type.

g_chunk_free()

#define             g_chunk_free(mem, mem_chunk)

Warning

g_chunk_free has been deprecated since version 2.10 and should not be used in newly-written code. Use g_slice_free() instead

A convenience macro to free an atom of memory from a GMemChunk. It simply switches the arguments and calls g_mem_chunk_free() It is included simply to complement the other convenience macros, g_chunk_new() and g_chunk_new0().

mem : | a pointer to the atom to be freed.
mem_chunk : | a GMemChunk.

g_mem_chunk_reset ()

void                g_mem_chunk_reset                   (GMemChunk *mem_chunk);

Warning

g_mem_chunk_reset has been deprecated since version 2.10 and should not be used in newly-written code. Use the slice allocator instead

Resets a GMemChunk to its initial state. It frees all of the currently allocated blocks of memory.

mem_chunk : a GMemChunk.

g_mem_chunk_clean ()

void                g_mem_chunk_clean                   (GMemChunk *mem_chunk);

Warning

g_mem_chunk_clean has been deprecated since version 2.10 and should not be used in newly-written code. Use the slice allocator instead

Frees any blocks in a GMemChunk which are no longer being used.

mem_chunk : a GMemChunk.

g_blow_chunks ()

void                g_blow_chunks                       (void);

Warning

g_blow_chunks has been deprecated since version 2.10 and should not be used in newly-written code. Use the slice allocator instead

Calls g_mem_chunk_clean() on all GMemChunk objects.

g_mem_chunk_info ()

void                g_mem_chunk_info                    (void);

Warning

g_mem_chunk_info has been deprecated since version 2.10 and should not be used in newly-written code. Use the slice allocator instead

Outputs debugging information for all GMemChunk objects currently in use. It outputs the number of GMemChunk objects currently allocated, and calls g_mem_chunk_print() to output information on each one.

g_mem_chunk_print ()

void                g_mem_chunk_print                   (GMemChunk *mem_chunk);

Warning

g_mem_chunk_print has been deprecated since version 2.10 and should not be used in newly-written code. Use the slice allocator instead

Outputs debugging information for a GMemChunk. It outputs the name of the GMemChunk (set with g_mem_chunk_new()), the number of bytes used, and the number of blocks of memory allocated.

mem_chunk : a GMemChunk.


Memory Slices

Memory Slices — efficient way to allocate groups of equal-sized chunks of memory.

Synopsis

#include <glib.h>

gpointer            g_slice_alloc                       (gsize block_size);
gpointer            g_slice_alloc0                      (gsize block_size);
void                g_slice_free1                       (gsize block_size,
                                                         gpointer mem_block);
void                g_slice_free_chain_with_offset      (gsize block_size,
                                                         gpointer mem_chain,
                                                         gsize next_offset);

#define             g_slice_new                         (type)
#define             g_slice_new0                        (type)
#define             g_slice_free                        (type, mem)
#define             g_slice_free_chain                  (type, mem_chain, next)

Description

Memory slices provide a space-efficient and multi-processing scalable way to allocate equal-sized pieces of memory, just like the original GMemChunks (from GLib <= 2.8), while avoiding their excessive memory-waste, scalability and performance problems.

To achieve these goals, the slice allocator uses a sophisticated, layered design that has been inspired by Bonwick's slab allocator [5]. It uses posix_memalign() to optimize allocations of many equally-sized chunks, and has per-thread free lists (the so-called magazine layer) to quickly satisfy allocation requests of already known structure sizes. This is accompanied by extra caching logic to keep freed memory around for some time before returning it to the system. Memory that is unused due to alignment constraints is used for cache colorization (random distribution of chunk addresses) to improve CPU cache utilization. The caching layer of the slice allocator adapts itself to high lock contention to improve scalability.

The slice allocator can allocate blocks as small as two pointers, and unlike malloc(), it does not reserve extra space per block. For large block sizes, g_slice_new() and g_slice_alloc() will automatically delegate to the system malloc() implementation. For newly written code it is recommended to use the new g_slice API instead of g_malloc() and friends, as long as objects are not resized during their lifetime and the object size used at allocation time is still available when freeing.

Example 17. Using the slice allocator

  gchar *mem[10000];
  gint i;

  /* Allocate 10000 blocks. */
  for (i = 0; i < 10000; i++)
    {
      mem[i] = g_slice_alloc (50);

      /* Fill in the memory with some junk. */
      for (j = 0; j < 50; j++)
    mem[i][j] = i * j;
    }

  /* Now free all of the blocks. */
  for (i = 0; i < 10000; i++)
    {
      g_slice_free1 (50, mem[i]);
    }

Example 18. Using the slice allocator with data structures

  GRealArray *array;

  /* Allocate one block, using the g_slice_new() macro. */
  array = g_slice_new (GRealArray);

  /* We can now use array just like a normal pointer to a structure. */
  array->data            = NULL;
  array->len             = 0;
  array->alloc           = 0;
  array->zero_terminated = (zero_terminated ? 1 : 0);
  array->clear           = (clear ? 1 : 0);
  array->elt_size        = elt_size;

  /* We can free the block, so it can be reused. */
  g_slice_free (GRealArray, array);

Details

g_slice_alloc ()

gpointer            g_slice_alloc                       (gsize block_size);

Allocates a block of memory from the slice allocator. The block adress handed out is guaranteed to be aligned to at least 2 * sizeof (void*). Note that the underlying slice allocation mechanism can be changed with the G_SLICE=always-malloc environment variable.

block_size : | the number of bytes to allocate
Returns : | a pointer to the allocated memory block

Since 2.10

g_slice_alloc0 ()

gpointer            g_slice_alloc0                      (gsize block_size);

Allocates a block of memory via g_slice_alloc() and initialize the returned memory to 0. Note that the underlying slice allocation mechanism can be changed with the G_SLICE=always-malloc environment variable.

block_size : | the number of bytes to allocate
Returns : | a pointer to the allocated block

Since 2.10

g_slice_free1 ()

void                g_slice_free1                       (gsize block_size,
                                                         gpointer mem_block);

Frees a block of memory. The memory must have been allocated via g_slice_alloc() or g_slice_alloc0() and the block_size has to match the size specified upon allocation. Note that the exact release behaviour can be changed with the G_DEBUG=gc-friendly environment variable.

block_size : | the size of the block
mem_block : | a pointer to the block to free

Since 2.10

g_slice_free_chain_with_offset ()

void                g_slice_free_chain_with_offset      (gsize block_size,
                                                         gpointer mem_chain,
                                                         gsize next_offset);

Frees a linked list of memory blocks of structure type type. The memory blocks must be equal-sized, allocated via g_slice_alloc() or g_slice_alloc0() and linked together by a next pointer (similar to GSList). The offset of the next field in each block is passed as third argument. Note that the exact release behaviour can be changed with the G_DEBUG=gc-friendly environment variable.

block_size : | the size of the blocks
mem_chain : | a pointer to the first block of the chain
next_offset : | the offset of the next field in the blocks

Since 2.10

g_slice_new()

#define             g_slice_new(type)

A convenience macro to allocate a block of memory from the slice allocator. It calls g_slice_alloc() with sizeof (type) and casts the returned pointer to a pointer of the given type, avoiding a type cast in the source code. Note that the underlying slice allocation mechanism can be changed with the G_SLICE=always-malloc environment variable.

type : | the type to allocate, typically a structure name
Returns : | a pointer to the allocated block, cast to a pointer to type.

Since 2.10

g_slice_new0()

#define             g_slice_new0(type)

A convenience macro to allocate a block of memory from the slice allocator and set the memory to 0. It calls g_slice_alloc0() with sizeof (type) and casts the returned pointer to a pointer of the given type, avoiding a type cast in the source code. Note that the underlying slice allocation mechanism can be changed with the G_SLICE=always-malloc environment variable.

type : | the type to allocate, typically a structure name
Returns : | a pointer to the allocated block, cast to a pointer to type.

Since 2.10

g_slice_free()

#define             g_slice_free(type, mem)

A convenience macro to free a block of memory that has been allocated from the slice allocator. It calls g_slice_free1() using sizeof (type) as the block size. Note that the exact release behaviour can be changed with the G_DEBUG=gc-friendly environment variable.

type : | the type of the block to free, typically a structure name
mem : | a pointer to the block to free

Since 2.10

g_slice_free_chain()

#define             g_slice_free_chain(type, mem_chain, next)

Frees a linked list of memory blocks of structure type type. The memory blocks must be equal-sized, allocated via g_slice_alloc() or g_slice_alloc0() and linked together by a next pointer (similar to GSList). The name of the next field in type is passed as third argument. Note that the exact release behaviour can be changed with the G_DEBUG=gc-friendly environment variable.

type : | the type of the mem_chain blocks
mem_chain : | a pointer to the first block of the chain
next : | the field name of the next pointer in type

Since 2.10

[5] [Bonwick94] Jeff Bonwick, The slab allocator: An object-caching kernel memory allocator. USENIX 1994, and [Bonwick01] Bonwick and Jonathan Adams, Magazines and vmem: Extending the slab allocator to many cpu's and arbitrary resources. USENIX 2001


Message Logging

Message Logging — versatile support for logging messages with different levels of importance.

Synopsis

#include <glib.h>

#define             G_LOG_DOMAIN
#define             G_LOG_FATAL_MASK
#define             G_LOG_LEVEL_USER_SHIFT
void                (*GLogFunc)                         (const gchar *log_domain,
                                                         GLogLevelFlags log_level,
                                                         const gchar *message,
                                                         gpointer user_data);
enum                GLogLevelFlags;

void                g_log                               (const gchar *log_domain,
                                                         GLogLevelFlags log_level,
                                                         const gchar *format,
                                                         ...);
void                g_logv                              (const gchar *log_domain,
                                                         GLogLevelFlags log_level,
                                                         const gchar *format,
                                                         va_list args);
#define             g_message                           (...)
#define             g_warning                           (...)
#define             g_critical                          (...)
#define             g_error                             (...)
#define             g_debug                             (...)

guint               g_log_set_handler                   (const gchar *log_domain,
                                                         GLogLevelFlags log_levels,
                                                         GLogFunc log_func,
                                                         gpointer user_data);
void                g_log_remove_handler                (const gchar *log_domain,
                                                         guint handler_id);
GLogLevelFlags      g_log_set_always_fatal              (GLogLevelFlags fatal_mask);
GLogLevelFlags      g_log_set_fatal_mask                (const gchar *log_domain,
                                                         GLogLevelFlags fatal_mask);
void                g_log_default_handler               (const gchar *log_domain,
                                                         GLogLevelFlags log_level,
                                                         const gchar *message,
                                                         gpointer unused_data);
GLogFunc            g_log_set_default_handler           (GLogFunc log_func,
                                                         gpointer user_data);

Description

These functions provide support for logging error messages or messages used for debugging.

There are several built-in levels of messages, defined in GLogLevelFlags. These can be extended with user-defined levels.

Details

G_LOG_DOMAIN

#define G_LOG_DOMAIN    ((gchar*) 0)

Defines the log domain. For applications, this is typically left as the default NULL (or "") domain. Libraries should define this so that any messages which they log can be differentiated from messages from other libraries and application code. But be careful not to define it in any public header files.

For example, GTK+ uses this in its Makefile.am:

INCLUDES = -DG_LOG_DOMAIN=\"Gtk\"

G_LOG_FATAL_MASK

#define G_LOG_FATAL_MASK        (G_LOG_FLAG_RECURSION | G_LOG_LEVEL_ERROR)

GLib log levels that are considered fatal by default.

G_LOG_LEVEL_USER_SHIFT

#define G_LOG_LEVEL_USER_SHIFT  (8)

Log level shift offset for user defined log levels (0-7 are used by GLib).

GLogFunc ()

void                (*GLogFunc)                         (const gchar *log_domain,
                                                         GLogLevelFlags log_level,
                                                         const gchar *message,
                                                         gpointer user_data);

Specifies the prototype of log handler functions.

log_domain : | the log domain of the message.
log_level : | the log level of the message (including the fatal and recursion flags).
message : | the message to process.
user_data : | user data, set in g_log_set_handler().

enum GLogLevelFlags

typedef enum
{
  /* log flags */
  G_LOG_FLAG_RECURSION          = 1 << 0,
  G_LOG_FLAG_FATAL              = 1 << 1,

  /* GLib log levels */
  G_LOG_LEVEL_ERROR             = 1 << 2,       /* always fatal */
  G_LOG_LEVEL_CRITICAL          = 1 << 3,
  G_LOG_LEVEL_WARNING           = 1 << 4,
  G_LOG_LEVEL_MESSAGE           = 1 << 5,
  G_LOG_LEVEL_INFO              = 1 << 6,
  G_LOG_LEVEL_DEBUG             = 1 << 7,

  G_LOG_LEVEL_MASK              = ~(G_LOG_FLAG_RECURSION | G_LOG_FLAG_FATAL)
} GLogLevelFlags;

Flags specifying the level of log messages.

g_log ()

void                g_log                               (const gchar *log_domain,
                                                         GLogLevelFlags log_level,
                                                         const gchar *format,
                                                         ...);

Logs an error or debugging message. If the log level has been set as fatal, the abort() function is called to terminate the program.

log_domain : | the log domain, usually G_LOG_DOMAIN.
log_level : | the log level, either from GLogLevelFlags or a user-defined level.
format : | the message format. See the printf() documentation.
... : | the parameters to insert into the format string.

g_logv ()

void                g_logv                              (const gchar *log_domain,
                                                         GLogLevelFlags log_level,
                                                         const gchar *format,
                                                         va_list args);

Logs an error or debugging message. If the log level has been set as fatal, the abort() function is called to terminate the program.

log_domain : | the log domain.
log_level : | the log level.
format : | the message format. See the printf() documentation.
args : | the parameters to insert into the format string.

g_message()

#define             g_message(...)

A convenience function/macro to log a normal message.

... : format string, followed by parameters to insert into the format string (as with printf())

g_warning()

#define             g_warning(...)

A convenience function/macro to log a warning message.

You can make warnings fatal at runtime by setting the G_DEBUG environment variable (see Running GLib Applications).

... : format string, followed by parameters to insert into the format string (as with printf())

g_critical()

#define             g_critical(...)

Logs a "critical warning" (G_LOG_LEVEL_CRITICAL). It's more or less application-defined what constitutes a critical vs. a regular warning. You could call g_log_set_always_fatal() to make critical warnings exit the program, then use g_critical() for fatal errors, for example.

You can also make critical warnings fatal at runtime by setting the G_DEBUG environment variable (see Running GLib Applications).

... : format string, followed by parameters to insert into the format string (as with printf())

g_error()

#define             g_error(...)

A convenience function/macro to log an error message. Error messages are always fatal, resulting in a call to abort() to terminate the application. This function will result in a core dump; don't use it for errors you expect. Using this function indicates a bug in your program, i.e. an assertion failure.

... : format string, followed by parameters to insert into the format string (as with printf())

g_debug()

#define             g_debug(...)

A convenience function/macro to log a debug message.

... : format string, followed by parameters to insert into the format string (as with printf())

Since 2.6

g_log_set_handler ()

guint               g_log_set_handler                   (const gchar *log_domain,
                                                         GLogLevelFlags log_levels,
                                                         GLogFunc log_func,
                                                         gpointer user_data);

Sets the log handler for a domain and a set of log levels. To handle fatal and recursive messages the log_levels parameter must be combined with the G_LOG_FLAG_FATAL and G_LOG_FLAG_RECURSION bit flags.

Note that since the G_LOG_LEVEL_ERROR log level is always fatal, if you want to set a handler for this log level you must combine it with G_LOG_FLAG_FATAL.

Example 14. Adding a log handler for all warning messages in the default (application) domain

  g_log_set_handler (NULL, G_LOG_LEVEL_WARNING | G_LOG_FLAG_FATAL
                     | G_LOG_FLAG_RECURSION, my_log_handler, NULL);

Example 15. Adding a log handler for all critical messages from GTK+

  g_log_set_handler ("Gtk", G_LOG_LEVEL_CRITICAL | G_LOG_FLAG_FATAL
                     | G_LOG_FLAG_RECURSION, my_log_handler, NULL);

Example 16. Adding a log handler for all messages from GLib

  g_log_set_handler ("GLib", G_LOG_LEVEL_MASK | G_LOG_FLAG_FATAL
                     | G_LOG_FLAG_RECURSION, my_log_handler, NULL);

log_domain : | the log domain, or NULL for the default "" application domain.
log_levels : | the log levels to apply the log handler for. To handle fatal and recursive messages as well, combine the log levels with the G_LOG_FLAG_FATAL and G_LOG_FLAG_RECURSION bit flags.
log_func : | the log handler function.
user_data : | data passed to the log handler.
Returns : | the id of the new handler.

g_log_remove_handler ()

void                g_log_remove_handler                (const gchar *log_domain,
                                                         guint handler_id);

Removes the log handler.

log_domain : | the log domain.
handler_id : | the id of the handler, which was returned in g_log_set_handler().

g_log_set_always_fatal ()

GLogLevelFlags      g_log_set_always_fatal              (GLogLevelFlags fatal_mask);

Sets the message levels which are always fatal, in any log domain. When a message with any of these levels is logged the program terminates. You can only set the levels defined by GLib to be fatal. G_LOG_LEVEL_ERROR is always fatal.

You can also make some message levels fatal at runtime by setting the G_DEBUG environment variable (see Running GLib Applications).

fatal_mask : | the mask containing bits set for each level of error which is to be fatal.
Returns : | the old fatal mask.

g_log_set_fatal_mask ()

GLogLevelFlags      g_log_set_fatal_mask                (const gchar *log_domain,
                                                         GLogLevelFlags fatal_mask);

Sets the log levels which are fatal in the given domain. G_LOG_LEVEL_ERROR is always fatal.

log_domain : | the log domain.
fatal_mask : | the new fatal mask.
Returns : | the old fatal mask for the log domain.

g_log_default_handler ()

void                g_log_default_handler               (const gchar *log_domain,
                                                         GLogLevelFlags log_level,
                                                         const gchar *message,
                                                         gpointer unused_data);

The default log handler set up by GLib; g_log_set_default_handler() allows to install an alternate default log handler. This is used if no log handler has been set for the particular log domain and log level combination. It outputs the message to stderr or stdout and if the log level is fatal it calls abort().

stderr is used for levels G_LOG_LEVEL_ERROR, G_LOG_LEVEL_CRITICAL, G_LOG_LEVEL_WARNING and G_LOG_LEVEL_MESSAGE. stdout is used for the rest.

log_domain : | the log domain of the message.
log_level : | the level of the message.
message : | the message.
unused_data : | data passed from g_log() which is unused.

g_log_set_default_handler ()

GLogFunc            g_log_set_default_handler           (GLogFunc log_func,
                                                         gpointer user_data);

Installs a default log handler which is used is used if no log handler has been set for the particular log domain and log level combination. By default, GLib uses g_log_default_handler() as default log handler.

log_func : | the log handler function.
user_data : | data passed to the log handler.
Returns : | the previous default log handler

Since 2.6


Miscellaneous Macros

Miscellaneous Macros — specialized macros which are not used often.

Synopsis

#include <glib.h>

#define             G_INLINE_FUNC

#define             G_STMT_START
#define             G_STMT_END

#define             G_BEGIN_DECLS
#define             G_END_DECLS

#define             G_N_ELEMENTS                        (arr)

#define             G_VA_COPY                           (ap1,ap2)

#define             G_STRINGIFY                         (macro_or_string)

#define             G_GNUC_EXTENSION
#define             G_GNUC_CONST
#define             G_GNUC_PURE
#define             G_GNUC_MALLOC
#define             G_GNUC_DEPRECATED
#define             G_GNUC_NORETURN
#define             G_GNUC_UNUSED
#define             G_GNUC_PRINTF                       ( format_idx, arg_idx )
#define             G_GNUC_SCANF                        ( format_idx, arg_idx )
#define             G_GNUC_FORMAT                       ( arg_idx )
#define             G_GNUC_NULL_TERMINATED
#define             G_GNUC_WARN_UNUSED_RESULT
#define             G_GNUC_FUNCTION
#define             G_GNUC_PRETTY_FUNCTION
#define             G_GNUC_NO_INSTRUMENT
#define             G_HAVE_GNUC_VISIBILITY
#define             G_GNUC_INTERNAL

#define             G_LIKELY                            (expr)
#define             G_UNLIKELY                          (expr)

#define             G_STRLOC
#define             G_STRFUNC

#define             G_GINT16_MODIFIER
#define             G_GINT16_FORMAT
#define             G_GUINT16_FORMAT
#define             G_GINT32_MODIFIER
#define             G_GINT32_FORMAT
#define             G_GUINT32_FORMAT
#define             G_GINT64_MODIFIER
#define             G_GINT64_FORMAT
#define             G_GUINT64_FORMAT
#define             G_GSIZE_MODIFIER
#define             G_GSIZE_FORMAT
#define             G_GSSIZE_FORMAT

Description

These macros provide more specialized features which are not needed so often by application programmers.

Details

G_INLINE_FUNC

#define             G_INLINE_FUNC

This macro is used to export function prototypes so they can be linked with an external version when no inlining is performed. The file which implements the functions should define G_IMPLEMENTS_INLINES before including the headers which contain G_INLINE_FUNC declarations. Since inlining is very compiler-dependent using these macros correctly is very difficult. Their use is strongly discouraged.

This macro is often mistaken for a replacement for the inline keyword; inline is already declared in a portable manner in the glib headers and can be used normally.

G_STMT_START

#define             G_STMT_START

Used within multi-statement macros so that they can be used in places where only one statement is expected by the compiler.

G_STMT_END

#define             G_STMT_END

Used within multi-statement macros so that they can be used in places where only one statement is expected by the compiler.

G_BEGIN_DECLS

#define             G_BEGIN_DECLS

Used (along with G_END_DECLS) to bracket header files. If the compiler in use is a C++ compiler, adds extern "C" around the header.

G_END_DECLS

#define             G_END_DECLS

Used (along with G_BEGIN_DECLS) to bracket header files. If the compiler in use is a C++ compiler, adds extern "C" around the header.

G_N_ELEMENTS()

#define G_N_ELEMENTS(arr)		(sizeof (arr) / sizeof ((arr)[0]))

Determines the number of elements in an array. The array must be declared so the compiler knows its size at compile-time; this macro will not work on an array allocated on the heap, only static arrays or arrays on the stack.

arr : the array

G_VA_COPY()

#define             G_VA_COPY(ap1,ap2)

Portable way to copy va_list variables.

In order to use this function, you must include string.h yourself, because this macro may use memmove() and GLib does not include string.h for you.

ap1 : | the va_list variable to place a copy of ap2 in.
ap2 : | a va_list.

G_STRINGIFY()

#define G_STRINGIFY(macro_or_string)	G_STRINGIFY_ARG (macro_or_string)

Accepts a macro or a string and converts it into a string.

macro_or_string : a macro or a string.

G_GNUC_EXTENSION

#define             G_GNUC_EXTENSION

Expands to __extension__ when gcc is used as the compiler. This simply tells gcc not to warn about the following non-standard code when compiling with the -pedantic option.

G_GNUC_CONST

#define             G_GNUC_CONST

Expands to the GNU C const function attribute if the compiler is gcc. Declaring a function as const enables better optimization of calls to the function. A const function doesn't examine any values except its parameters, and has no effects except its return value. See the GNU C documentation for details.

Note

A function that has pointer arguments and examines the data pointed to must not be declared const. Likewise, a function that calls a non-const function usually must not be const. It doesn't make sense for a const function to return void.

G_GNUC_PURE

#define             G_GNUC_PURE

Expands to the GNU C pure function attribute if the compiler is gcc. Declaring a function as pure enables better optimization of calls to the function. A pure function has no effects except its return value and the return value depends only on the parameters and/or global variables. See the GNU C documentation for details.

G_GNUC_MALLOC

#define             G_GNUC_MALLOC

Expands to the GNU C malloc function attribute if the compiler is gcc. Declaring a function as malloc enables better optimization of the function. A function can have the malloc attribute if it returns a pointer which is guaranteed to not alias with any other pointer when the function returns (in practice, this means newly allocated memory). See the GNU C documentation for details.

Since 2.6

G_GNUC_DEPRECATED

#define             G_GNUC_DEPRECATED

Expands to the GNU C deprecated attribute if the compiler is gcc. It can be used to mark typedefs, variables and functions as deprecated. When called with the -Wdeprecated option, the compiler will generate warnings when deprecated interfaces are used. See the GNU C documentation for details.

Since 2.2

G_GNUC_NORETURN

#define             G_GNUC_NORETURN

Expands to the GNU C noreturn function attribute if the compiler is gcc. It is used for declaring functions which never return. It enables optimization of the function, and avoids possible compiler warnings. See the GNU C documentation for details.

G_GNUC_UNUSED

#define             G_GNUC_UNUSED

Expands to the GNU C unused function attribute if the compiler is gcc. It is used for declaring functions which may never be used. It avoids possible compiler warnings. See the GNU C documentation for details.

G_GNUC_PRINTF()

#define             G_GNUC_PRINTF( format_idx, arg_idx )

Expands to the GNU C format function attribute if the compiler is gcc. This is used for declaring functions which take a variable number of arguments, with the same syntax as printf(). It allows the compiler to type-check the arguments passed to the function. See the GNU C documentation for details.

gint g_snprintf (gchar  *string,
                 gulong       n,
                 gchar const *format,
                 ...) G_GNUC_PRINTF (3, 4);

format_idx : | the index of the argument corresponding to the format string. (The arguments are numbered from 1).
arg_idx : | the index of the first of the format arguments.

G_GNUC_SCANF()

#define             G_GNUC_SCANF( format_idx, arg_idx )

Expands to the GNU C format function attribute if the compiler is gcc. This is used for declaring functions which take a variable number of arguments, with the same syntax as scanf(). It allows the compiler to type-check the arguments passed to the function. See the GNU C documentation for details.

format_idx : | the index of the argument corresponding to the format string. (The arguments are numbered from 1).
arg_idx : | the index of the first of the format arguments.

G_GNUC_FORMAT()

#define             G_GNUC_FORMAT( arg_idx )

Expands to the GNU C format_arg function attribute if the compiler is gcc. This function attribute specifies that a function takes a format string for a printf(), scanf(), strftime() or strfmon() style function and modifies it, so that the result can be passed to a printf(), scanf(), strftime() or strfmon() style function (with the remaining arguments to the format function the same as they would have been for the unmodified string). See the GNU C documentation for details.

gchar *g_dgettext (gchar *domain_name, gchar *msgid) G_GNUC_FORMAT (2);
arg_idx : the index of the argument.

G_GNUC_NULL_TERMINATED

#define             G_GNUC_NULL_TERMINATED

Expands to the GNU C sentinel function attribute if the compiler is gcc, or "" if it isn't. This function attribute only applies to variadic functions and instructs the compiler to check that the argument list is terminated with an explicit NULL. See the GNU C documentation for details.

Since: 2.8

G_GNUC_WARN_UNUSED_RESULT

#define             G_GNUC_WARN_UNUSED_RESULT

Expands to the GNU C warn_unused_ersult function attribute if the compiler is gcc, or "" if it isn't. This function attribute makes the compiler emit a warning if the result of a function call is ignored. See the GNU C documentation for details.

Since 2.10

G_GNUC_FUNCTION

#define             G_GNUC_FUNCTION

Expands to the GNU C __FUNCTION__ variable if the compiler is gcc, or "" if it isn't. The GNU C __FUNCTION__ variable contains the name of the current function. See the GNU C documentation for details.

G_GNUC_PRETTY_FUNCTION

#define             G_GNUC_PRETTY_FUNCTION

Expands to the GNU C __PRETTY_FUNCTION__ variable if the compiler is gcc, or "" if it isn't. The GNU C __PRETTY_FUNCTION__ variable contains the name of the current function. For a C program this is the same as the __FUNCTION__ variable but for C++ it also includes extra information such as the class and function prototype. See the GNU C documentation for details.

G_GNUC_NO_INSTRUMENT

#define             G_GNUC_NO_INSTRUMENT

Expands to the GNU C no_instrument_function function attribute if the compiler is gcc. Functions with this attribute will not be instrumented for profiling, when the compiler is called with the -finstrument-functions option. See the GNU C documentation for details.

G_HAVE_GNUC_VISIBILITY

#define G_HAVE_GNUC_VISIBILITY 1

This macro is defined as 1 if the the compiler supports ELF visibility attributes (currently only gcc).

Since: 2.6

G_GNUC_INTERNAL

#define             G_GNUC_INTERNAL

Expands to the GNU C visibility(hidden) attribute if the compiler supports it (currently only gcc). This attribute can be used for marking library functions as being used internally to the lib only, to not create inefficient PLT entries. Note that static functions do not need to be marked as internal in this way. See the GNU C documentation for details.

Since: 2.6

G_LIKELY()

#define             G_LIKELY(expr)

Hints the compiler that the expression is likely to evaluate to a true value. The compiler may use this information for optimizations.

if (G_LIKELY (random () != 1))
  g_print ("not one");
expr : the expression

Since 2.2

G_UNLIKELY()

#define             G_UNLIKELY(expr)

Hints the compiler that the expression is unlikely to evaluate to a true value. The compiler may use this information for optimizations.

if (G_UNLIKELY (random () == 1))
  g_print ("a random one");
expr : the expression

Since 2.2

G_STRLOC

#define             G_STRLOC

Expands to a string identifying the current code position.

G_STRFUNC

#define             G_STRFUNC

Expands to a string identifying the current function.

Since 2.4

G_GINT16_MODIFIER

#define G_GINT16_MODIFIER "h"

The platform dependent length modifier for constructing printf() conversion specifiers for values of type gint16 or guint16. It is a string literal, but doesn't include the percent-sign, such that you can add precision and length modifiers between percent-sign and conversion specifier and append a conversion specifier.

The following example prints "0x7b";

gint16 value = 123;
g_print ("%#" G_GINT16_MODIFIER "x", value);

Since 2.4

G_GINT16_FORMAT

#define G_GINT16_FORMAT "hi"

This is the platform dependent conversion specifier for scanning and printing values of type gint16. It is a string literal, but doesn't include the percent-sign, such that you can add precision and length modifiers between percent-sign and conversion specifier.

gint16 in;
gint32 out;
sscanf ("42", "%" G_GINT16_FORMAT, &in)
out = in * 1000;
g_print ("%" G_GINT32_FORMAT, out);

G_GUINT16_FORMAT

#define G_GUINT16_FORMAT "hu"

This is the platform dependent conversion specifier for scanning and printing values of type guint16. See also G_GINT16_FORMAT.

G_GINT32_MODIFIER

#define G_GINT32_MODIFIER ""

The platform dependent length modifier for constructing printf() conversion specifiers for values of type gint32 or guint32. See also G_GINT16_MODIFIER.

Since 2.4

G_GINT32_FORMAT

#define G_GINT32_FORMAT "i"

This is the platform dependent conversion specifier for scanning and printing values of type gint32. See also G_GINT16_FORMAT.

G_GUINT32_FORMAT

#define G_GUINT32_FORMAT "u"

This is the platform dependent conversion specifier for scanning and printing values of type guint32. See also G_GINT16_FORMAT.

G_GINT64_MODIFIER

#define G_GINT64_MODIFIER "ll"

The platform dependent length modifier for constructing printf() conversion specifiers for values of type gint64 or guint64. See also G_GINT16_MODIFIER.

Note

Some platforms do not support printing 64 bit integers, even though the types are supported. On such platforms G_GINT64_MODIFIER is not defined.

Since 2.4

G_GINT64_FORMAT

#define G_GINT64_FORMAT "lli"

This is the platform dependent conversion specifier for scanning and printing values of type gint64. See also G_GINT16_FORMAT.

Note

Some platforms do not support scanning and printing 64 bit integers, even though the types are supported. On such platforms G_GINT64_FORMAT is not defined. Note that scanf() may not support 64 bit integers, even if G_GINT64_FORMAT is defined. Due to its weak error handling, scanf() is not recommended for parsing anyway; consider using g_strtoull() instead.

G_GUINT64_FORMAT

#define G_GUINT64_FORMAT "llu"

This is the platform dependent conversion specifier for scanning and printing values of type guint64. See also G_GINT16_FORMAT.

Note

Some platforms do not support scanning and printing 64 bit integers, even though the types are supported. On such platforms G_GUINT64_FORMAT is not defined. Note that scanf() may not support 64 bit integers, even if G_GINT64_FORMAT is defined. Due to its weak error handling, scanf() is not recommended for parsing anyway; consider using g_strtoull() instead.

G_GSIZE_MODIFIER

#define G_GSIZE_MODIFIER ""

The platform dependent length modifier for constructing printf() conversion specifiers for values of type gsize or gssize. See also G_GINT16_MODIFIER.

Since 2.6

G_GSIZE_FORMAT

#define G_GSIZE_FORMAT "u"

This is the platform dependent conversion specifier for scanning and printing values of type gsize. See also G_GINT16_FORMAT.

Since 2.6

G_GSSIZE_FORMAT

#define G_GSSIZE_FORMAT "i"

This is the platform dependent conversion specifier for scanning and printing values of type gssize. See also G_GINT16_FORMAT.

Since 2.6


Miscellaneous Utility Functions

Miscellaneous Utility Functions — a selection of portable utility functions.

Synopsis

#include <glib.h>

const gchar*        g_get_application_name              (void);
void                g_set_application_name              (const gchar *application_name);
gchar*              g_get_prgname                       (void);
void                g_set_prgname                       (const gchar *prgname);
const gchar*        g_getenv                            (const gchar *variable);
gboolean            g_setenv                            (const gchar *variable,
                                                         const gchar *value,
                                                         gboolean overwrite);
void                g_unsetenv                          (const gchar *variable);
gchar**             g_listenv                           (void);
const gchar*        g_get_user_name                     (void);
const gchar*        g_get_real_name                     (void);
const gchar*        g_get_user_cache_dir                (void);
const gchar*        g_get_user_data_dir                 (void);
const gchar*        g_get_user_config_dir               (void);
const gchar* const * g_get_system_data_dirs             (void);
const gchar* const * g_get_system_config_dirs           (void);

const gchar*        g_get_host_name                     (void);
const gchar*        g_get_home_dir                      (void);
const gchar*        g_get_tmp_dir                       (void);
gchar*              g_get_current_dir                   (void);
const gchar*        g_basename                          (const gchar *file_name);
#define             g_dirname
gboolean            g_path_is_absolute                  (const gchar *file_name);
const gchar*        g_path_skip_root                    (const gchar *file_name);
gchar*              g_path_get_basename                 (const gchar *file_name);
gchar*              g_path_get_dirname                  (const gchar *file_name);
gchar*              g_build_filename                    (const gchar *first_element,
                                                         ...);
gchar*              g_build_filenamev                   (gchar **args);
gchar*              g_build_path                        (const gchar *separator,
                                                         const gchar *first_element,
                                                         ...);
gchar*              g_build_pathv                       (const gchar *separator,
                                                         gchar **args);

gchar*              g_find_program_in_path              (const gchar *program);

gint                g_bit_nth_lsf                       (gulong mask,
                                                         gint nth_bit);
gint                g_bit_nth_msf                       (gulong mask,
                                                         gint nth_bit);
guint               g_bit_storage                       (gulong number);

guint               g_spaced_primes_closest             (guint num);

void                g_atexit                            (GVoidFunc func);

guint               g_parse_debug_string                (const gchar *string,
                                                         const GDebugKey *keys,
                                                         guint nkeys);
                    GDebugKey;

void                (*GVoidFunc)                        (void);
void                (*GFreeFunc)                        (gpointer data);

void                g_qsort_with_data                   (gconstpointer pbase,
                                                         gint total_elems,
                                                         gsize size,
                                                         GCompareDataFunc compare_func,
                                                         gpointer user_data);

void                g_nullify_pointer                   (gpointer *nullify_location);

Description

These are portable utility functions.

Details

g_get_application_name ()

const gchar*        g_get_application_name              (void);

Gets a human-readable name for the application, as set by g_set_application_name(). This name should be localized if possible, and is intended for display to the user. Contrast with g_get_prgname(), which gets a non-localized name. If g_set_application_name() has not been called, returns the result of g_get_prgname() (which may be NULL if g_set_prgname() has also not been called).

Returns : human-readable application name. may return NULL

Since 2.2

g_set_application_name ()

void                g_set_application_name              (const gchar *application_name);

Sets a human-readable name for the application. This name should be localized if possible, and is intended for display to the user. Contrast with g_set_prgname(), which sets a non-localized name. g_set_prgname() will be called automatically by gtk_init(), but g_set_application_name() will not.

Note that for thread safety reasons, this function can only be called once.

The application name will be used in contexts such as error messages, or when displaying an application's name in the task list.

application_name : localized name of the application

g_get_prgname ()

gchar*              g_get_prgname                       (void);

Gets the name of the program. This name should not be localized, contrast with g_get_application_name(). (If you are using GDK or GTK+ the program name is set in gdk_init(), which is called by gtk_init(). The program name is found by taking the last component of argv[0].)

Returns : the name of the program. The returned string belongs to GLib and must not be modified or freed.

g_set_prgname ()

void                g_set_prgname                       (const gchar *prgname);

Sets the name of the program. This name should not be localized, contrast with g_set_application_name(). Note that for thread-safety reasons this function can only be called once.

prgname : the name of the program.

g_getenv ()

const gchar*        g_getenv                            (const gchar *variable);

Returns the value of an environment variable. The name and value are in the GLib file name encoding. On UNIX, this means the actual bytes which might or might not be in some consistent character set and encoding. On Windows, it is in UTF-8. On Windows, in case the environment variable's value contains references to other environment variables, they are expanded.

variable : | the environment variable to get, in the GLib file name encoding.
Returns : | the value of the environment variable, or NULL if the environment variable is not found. The returned string may be overwritten by the next call to g_getenv(), g_setenv() or g_unsetenv().

g_setenv ()

gboolean            g_setenv                            (const gchar *variable,
                                                         const gchar *value,
                                                         gboolean overwrite);

Sets an environment variable. Both the variable's name and value should be in the GLib file name encoding. On UNIX, this means that they can be any sequence of bytes. On Windows, they should be in UTF-8.

Note that on some systems, when variables are overwritten, the memory used for the previous variables and its value isn't reclaimed.

variable : | the environment variable to set, must not contain '='.
value : | the value for to set the variable to.
overwrite : | whether to change the variable if it already exists.
Returns : | FALSE if the environment variable couldn't be set.

Since 2.4

g_unsetenv ()

void                g_unsetenv                          (const gchar *variable);

Removes an environment variable from the environment.

Note that on some systems, when variables are overwritten, the memory used for the previous variables and its value isn't reclaimed. Furthermore, this function can't be guaranteed to operate in a threadsafe way.

variable : the environment variable to remove, must not contain '='.

Since 2.4

g_listenv ()

gchar**             g_listenv                           (void);

Gets the names of all variables set in the environment.

Returns : a NULL-terminated list of strings which must be freed with g_strfreev(). Programs that want to be portable to Windows should typically use this function and g_getenv() instead of using the environ array from the C library directly. On Windows, the strings in the environ array are in system codepage encoding, while in most of the typical use cases for environment variables in GLib-using programs you want the UTF-8 encoding that this function and g_getenv() provide.

Since 2.8

g_get_user_name ()

const gchar*        g_get_user_name                     (void);

Gets the user name of the current user. The encoding of the returned string is system-defined. On UNIX, it might be the preferred file name encoding, or something else, and there is no guarantee that it is even consistent on a machine. On Windows, it is always UTF-8.

Returns : the user name of the current user.

g_get_real_name ()

const gchar*        g_get_real_name                     (void);

Gets the real name of the user. This usually comes from the user's entry in the passwd file. The encoding of the returned string is system-defined. (On Windows, it is, however, always UTF-8.) If the real user name cannot be determined, the string "Unknown" is returned.

Returns : the user's real name.

g_get_user_cache_dir ()

const gchar*        g_get_user_cache_dir                (void);

Returns a base directory in which to store non-essential, cached data specific to particular user.

On UNIX platforms this is determined using the mechanisms described in the XDG Base Directory Specification

Returns : a string owned by GLib that must not be modified or freed.

Since 2.6

g_get_user_data_dir ()

const gchar*        g_get_user_data_dir                 (void);

Returns a base directory in which to access application data such as icons that is customized for a particular user.

On UNIX platforms this is determined using the mechanisms described in the XDG Base Directory Specification

Returns : a string owned by GLib that must not be modified or freed.

Since 2.6

g_get_user_config_dir ()

const gchar*        g_get_user_config_dir               (void);

Returns a base directory in which to store user-specific application configuration information such as user preferences and settings.

On UNIX platforms this is determined using the mechanisms described in the XDG Base Directory Specification

Returns : a string owned by GLib that must not be modified or freed.

Since 2.6

g_get_system_data_dirs ()

const gchar* const * g_get_system_data_dirs             (void);

Returns an ordered list of base directories in which to access system-wide application data.

On UNIX platforms this is determined using the mechanisms described in the XDG Base Directory Specification

On Windows the first elements in the list are the Application Data and Documents folders for All Users. (These can be determined only on Windows 2000 or later and are not present in the list on other Windows versions.) See documentation for CSIDL_COMMON_APPDATA and CSIDL_COMMON_DOCUMENTS.

Then follows the "share" subfolder in the installation folder for the package containing the DLL that calls this function, if it can be determined.

Finally the list contains the "share" subfolder in the installation folder for GLib, and in the installation folder for the package the application's .exe file belongs to.

The installation folders above are determined by looking up the folder where the module (DLL or EXE) in question is located. If the folder's name is "bin", its parent is used, otherwise the folder itself.

Note that on Windows the returned list can vary depending on where this function is called.

Returns : a NULL-terminated array of strings owned by GLib that must not be modified or freed.

Since 2.6

g_get_system_config_dirs ()

const gchar* const * g_get_system_config_dirs           (void);

Returns an ordered list of base directories in which to access system-wide configuration information.

On UNIX platforms this is determined using the mechanisms described in the XDG Base Directory Specification

Returns : a NULL-terminated array of strings owned by GLib that must not be modified or freed.

Since 2.6

g_get_host_name ()

const gchar*        g_get_host_name                     (void);

Return a name for the machine.

The returned name is not necessarily a fully-qualified domain name, or even present in DNS or some other name service at all. It need not even be unique on your local network or site, but usually it is. Callers should not rely on the return value having any specific properties like uniqueness for security purposes. Even if the name of the machine is changed while an application is running, the return value from this function does not change. The returned string is owned by GLib and should not be modified or freed. If no name can be determined, a default fixed string "localhost" is returned.

Returns : the host name of the machine.

Since 2.8

g_get_home_dir ()

const gchar*        g_get_home_dir                      (void);

Gets the current user's home directory.

Note that in contrast to traditional UNIX tools, this function prefers passwd entries over the HOME environment variable.

Returns : the current user's home directory.

g_get_tmp_dir ()

const gchar*        g_get_tmp_dir                       (void);

Gets the directory to use for temporary files. This is found from inspecting the environment variables TMPDIR, TMP, and TEMP in that order. If none of those are defined "/tmp" is returned on UNIX and "C:\" on Windows. The encoding of the returned string is system-defined. On Windows, it is always UTF-8. The return value is never NULL.

Returns : the directory to use for temporary files.

g_get_current_dir ()

gchar*              g_get_current_dir                   (void);

Gets the current directory. The returned string should be freed when no longer needed. The encoding of the returned string is system defined. On Windows, it is always UTF-8.

Returns : the current directory.

g_basename ()

const gchar*        g_basename                          (const gchar *file_name);

Warning

g_basename has been deprecated since version 2.2 and should not be used in newly-written code. Use g_path_get_basename() instead, but notice that g_path_get_basename() allocates new memory for the returned string, unlike this function which returns a pointer into the argument.

Gets the name of the file without any leading directory components. It returns a pointer into the given file name string.

file_name : | the name of the file.
Returns : | the name of the file without any leading directory components.

g_dirname

#define             g_dirname

Warning

g_dirname is deprecated and should not be used in newly-written code.

This function is deprecated and will be removed in the next major release of GLib. Use g_path_get_dirname() instead.

Gets the directory components of a file name. If the file name has no directory components "." is returned. The returned string should be freed when no longer needed.

Returns : the directory components of the file.

g_path_is_absolute ()

gboolean            g_path_is_absolute                  (const gchar *file_name);

Returns TRUE if the given file_name is an absolute file name, i.e. it contains a full path from the root directory such as "/usr/local" on UNIX or "C:\windows" on Windows systems.

file_name : | a file name.
Returns : | TRUE if file_name is an absolute path.

g_path_skip_root ()

const gchar*        g_path_skip_root                    (const gchar *file_name);

Returns a pointer into file_name after the root component, i.e. after the "/" in UNIX or "C:\" under Windows. If file_name is not an absolute path it returns NULL.

file_name : | a file name.
Returns : | a pointer into file_name after the root component.

g_path_get_basename ()

gchar*              g_path_get_basename                 (const gchar *file_name);

Gets the last component of the filename. If file_name ends with a directory separator it gets the component before the last slash. If file_name consists only of directory separators (and on Windows, possibly a drive letter), a single separator is returned. If file_name is empty, it gets ".".

file_name : | the name of the file.
Returns : | a newly allocated string containing the last component of the filename.

g_path_get_dirname ()

gchar*              g_path_get_dirname                  (const gchar *file_name);

Gets the directory components of a file name. If the file name has no directory components "." is returned. The returned string should be freed when no longer needed.

file_name : | the name of the file.
Returns : | the directory components of the file.

g_build_filename ()

gchar*              g_build_filename                    (const gchar *first_element,
                                                         ...);

Creates a filename from a series of elements using the correct separator for filenames.

On Unix, this function behaves identically to g_build_path (G_DIR_SEPARATOR_S, first_element, ....).

On Windows, it takes into account that either the backslash (\ or slash (/) can be used as separator in filenames, but otherwise behaves as on Unix. When file pathname separators need to be inserted, the one that last previously occurred in the parameters (reading from left to right) is used.

No attempt is made to force the resulting filename to be an absolute path. If the first element is a relative path, the result will be a relative path.

first_element : | the first element in the path
... : | remaining elements in path, terminated by NULL
Returns : | a newly-allocated string that must be freed with g_free().

g_build_filenamev ()

gchar*              g_build_filenamev                   (gchar **args);

Behaves exactly like g_build_filename(), but takes the path elements as a string array, instead of varargs. This function is mainly meant for language bindings.

args : | NULL-terminated array of strings containing the path elements.
Returns : | a newly-allocated string that must be freed with g_free().

Since 2.8

g_build_path ()

gchar*              g_build_path                        (const gchar *separator,
                                                         const gchar *first_element,
                                                         ...);

Creates a path from a series of elements using separator as the separator between elements. At the boundary between two elements, any trailing occurrences of separator in the first element, or leading occurrences of separator in the second element are removed and exactly one copy of the separator is inserted.

Empty elements are ignored.

The number of leading copies of the separator on the result is the same as the number of leading copies of the separator on the first non-empty element.

The number of trailing copies of the separator on the result is the same as the number of trailing copies of the separator on the last non-empty element. (Determination of the number of trailing copies is done without stripping leading copies, so if the separator is ABA, ABABA has 1 trailing copy.)

However, if there is only a single non-empty element, and there are no characters in that element not part of the leading or trailing separators, then the result is exactly the original value of that element.

Other than for determination of the number of leading and trailing copies of the separator, elements consisting only of copies of the separator are ignored.

separator : | a string used to separator the elements of the path.
first_element : | the first element in the path
... : | remaining elements in path, terminated by NULL
Returns : | a newly-allocated string that must be freed with g_free().

g_build_pathv ()

gchar*              g_build_pathv                       (const gchar *separator,
                                                         gchar **args);

Behaves exactly like g_build_path(), but takes the path elements as a string array, instead of varargs. This function is mainly meant for language bindings.

separator : | a string used to separator the elements of the path.
args : | NULL-terminated array of strings containing the path elements.
Returns : | a newly-allocated string that must be freed with g_free().

Since 2.8

g_find_program_in_path ()

gchar*              g_find_program_in_path              (const gchar *program);

Locates the first executable named program in the user's path, in the same way that execvp() would locate it. Returns an allocated string with the absolute path name, or NULL if the program is not found in the path. If program is already an absolute path, returns a copy of program if program exists and is executable, and NULL otherwise. On Windows, if program does not have a file type suffix, tries with the suffixes .exe, .cmd, .bat and .com, and the suffixes in the PATHEXT environment variable.

On Windows, it looks for the file in the same way as CreateProcess() would. This means first in the directory where the executing program was loaded from, then in the current directory, then in the Windows 32-bit system directory, then in the Windows directory, and finally in the directories in the PATH environment variable. If the program is found, the return value contains the full name including the type suffix.

program : | a program name in the GLib file name encoding
Returns : | absolute path, or NULL

g_bit_nth_lsf ()

gint                g_bit_nth_lsf                       (gulong mask,
                                                         gint nth_bit);

Find the position of the first bit set in mask, searching from (but not including) nth_bit upwards. Bits are numbered from 0 (least significant) to sizeof(gulong) * 8 - 1 (31 or 63, usually). To start searching from the 0th bit, set nth_bit to -1.

mask : | a gulong containing flags.
nth_bit : | the index of the bit to start the search from.
Returns : | the index of the first bit set which is higher than nth_bit.

g_bit_nth_msf ()

gint                g_bit_nth_msf                       (gulong mask,
                                                         gint nth_bit);

Find the position of the first bit set in mask, searching from (but not including) nth_bit downwards. Bits are numbered from 0 (least significant) to sizeof(gulong) * 8 - 1 (31 or 63, usually). To start searching from the last bit, set nth_bit to -1 or GLIB_SIZEOF_LONG * 8.

mask : | a gulong containing flags.
nth_bit : | the index of the bit to start the search from.
Returns : | the index of the first bit set which is lower than nth_bit.

g_bit_storage ()

guint               g_bit_storage                       (gulong number);

Gets the number of bits used to hold number, e.g. if number is 4, 3 bits are needed.

number : | a guint.
Returns : | the number of bits used to hold number.

g_spaced_primes_closest ()

guint               g_spaced_primes_closest             (guint num);

Gets the smallest prime number from a built-in array of primes which is larger than num. This is used within GLib to calculate the optimum size of a GHashTable.

The built-in array of primes ranges from 11 to 13845163 such that each prime is approximately 1.5-2 times the previous prime.

num : | a guint.
Returns : | the smallest prime number from a built-in array of primes which is larger than num.

g_atexit ()

void                g_atexit                            (GVoidFunc func);

Specifies a function to be called at normal program termination.

Since GLib 2.8.2, on Windows g_atexit() actually is a preprocessor macro that maps to a call to the atexit() function in the C library. This means that in case the code that calls g_atexit(), i.e. atexit(), is in a DLL, the function will be called when the DLL is detached from the program. This typically makes more sense than that the function is called when the GLib DLL is detached, which happened earlier when g_atexit() was a function in the GLib DLL.

The behaviour of atexit() in the context of dynamically loaded modules is not formally specified and varies wildly.

On POSIX systems, calling g_atexit() (or atexit()) in a dynamically loaded module which is unloaded before the program terminates might well cause a crash at program exit.

Some POSIX systems implement atexit() like Windows, and have each dynamically loaded module maintain an own atexit chain that is called when the module is unloaded.

On other POSIX systems, before a dynamically loaded module is unloaded, the registered atexit functions (if any) residing in that module are called, regardless where the code that registered them resided. This is presumably the most robust approach.

As can be seen from the above, for portability it's best to avoid calling g_atexit() (or atexit()) except in the main executable of a program.

func : the function to call on normal program termination.

g_parse_debug_string ()

guint               g_parse_debug_string                (const gchar *string,
                                                         const GDebugKey *keys,
                                                         guint nkeys);

Parses a string containing debugging options into a guint containing bit flags. This is used within GDK and GTK+ to parse the debug options passed on the command line or through environment variables.

string : | a list of debug options separated by colons, spaces, or commas; or the string "all" to set all flags.
keys : | pointer to an array of GDebugKey which associate strings with bit flags.
nkeys : | the number of GDebugKeys in the array.
Returns : | the combined set of bit flags.

GDebugKey

typedef struct {
  gchar *key;
  guint	 value;
} GDebugKey;

Associates a string with a bit flag. Used in g_parse_debug_string().

gchar *key; | the string
guint value; | the flag

GVoidFunc ()

void                (*GVoidFunc)                        (void);

Declares a type of function which takes no arguments and has no return value. It is used to specify the type function passed to g_atexit().

GFreeFunc ()

void                (*GFreeFunc)                        (gpointer data);

Declares a type of function which takes an arbitrary data pointer argument and has no return value. It is not currently used in GLib or GTK+.

data : a data pointer.

g_qsort_with_data ()

void                g_qsort_with_data                   (gconstpointer pbase,
                                                         gint total_elems,
                                                         gsize size,
                                                         GCompareDataFunc compare_func,
                                                         gpointer user_data);

This is just like the standard C qsort() function, but the comparison routine accepts a user data argument.

pbase : | start of array to sort
total_elems : | elements in the array
size : | size of each element
compare_func : | function to compare elements
user_data : | data to pass to compare_func

g_nullify_pointer ()

void                g_nullify_pointer                   (gpointer *nullify_location);

Set the pointer at the specified location to NULL.

nullify_location : the memory address of the pointer.


N-ary Trees

N-ary Trees — trees of data with any number of branches.

Synopsis

#include <glib.h>

                    GNode;
GNode*              g_node_new                          (gpointer data);
GNode*              g_node_copy                         (GNode *node);
gpointer            (*GCopyFunc)                        (gconstpointer src,
                                                         gpointer data);
GNode*              g_node_copy_deep                    (GNode *node,
                                                         GCopyFunc copy_func,
                                                         gpointer data);

GNode*              g_node_insert                       (GNode *parent,
                                                         gint position,
                                                         GNode *node);
GNode*              g_node_insert_before                (GNode *parent,
                                                         GNode *sibling,
                                                         GNode *node);
GNode*              g_node_insert_after                 (GNode *parent,
                                                         GNode *sibling,
                                                         GNode *node);
#define             g_node_append                       (parent, node)
GNode*              g_node_prepend                      (GNode *parent,
                                                         GNode *node);

#define             g_node_insert_data                  (parent, position, data)
#define             g_node_insert_data_before           (parent, sibling, data)
#define             g_node_append_data                  (parent, data)
#define             g_node_prepend_data                 (parent, data)

void                g_node_reverse_children             (GNode *node);
void                g_node_traverse                     (GNode *root,
                                                         GTraverseType order,
                                                         GTraverseFlags flags,
                                                         gint max_depth,
                                                         GNodeTraverseFunc func,
                                                         gpointer data);
enum                GTraverseFlags;
gboolean            (*GNodeTraverseFunc)                (GNode *node,
                                                         gpointer data);
void                g_node_children_foreach             (GNode *node,
                                                         GTraverseFlags flags,
                                                         GNodeForeachFunc func,
                                                         gpointer data);
void                (*GNodeForeachFunc)                 (GNode *node,
                                                         gpointer data);

GNode*              g_node_get_root                     (GNode *node);
GNode*              g_node_find                         (GNode *root,
                                                         GTraverseType order,
                                                         GTraverseFlags flags,
                                                         gpointer data);
GNode*              g_node_find_child                   (GNode *node,
                                                         GTraverseFlags flags,
                                                         gpointer data);
gint                g_node_child_index                  (GNode *node,
                                                         gpointer data);
gint                g_node_child_position               (GNode *node,
                                                         GNode *child);
#define             g_node_first_child                  (node)
GNode*              g_node_last_child                   (GNode *node);
GNode*              g_node_nth_child                    (GNode *node,
                                                         guint n);
GNode*              g_node_first_sibling                (GNode *node);
#define             g_node_next_sibling                 (node)
#define             g_node_prev_sibling                 (node)
GNode*              g_node_last_sibling                 (GNode *node);

#define             G_NODE_IS_LEAF                      (node)
#define             G_NODE_IS_ROOT                      (node)
guint               g_node_depth                        (GNode *node);
guint               g_node_n_nodes                      (GNode *root,
                                                         GTraverseFlags flags);
guint               g_node_n_children                   (GNode *node);
gboolean            g_node_is_ancestor                  (GNode *node,
                                                         GNode *descendant);
guint               g_node_max_height                   (GNode *root);

void                g_node_unlink                       (GNode *node);
void                g_node_destroy                      (GNode *root);

void                g_node_push_allocator               (gpointer dummy);
void                g_node_pop_allocator                (void);

Description

The GNode struct and its associated functions provide a N-ary tree data structure, where nodes in the tree can contain arbitrary data.

To create a new tree use g_node_new().

To insert a node into a tree use g_node_insert(), g_node_insert_before(), g_node_append() and g_node_prepend().

To create a new node and insert it into a tree use g_node_insert_data(), g_node_insert_data_before(), g_node_append_data() and g_node_prepend_data().

To reverse the children of a node use g_node_reverse_children().

To find a node use g_node_get_root(), g_node_find(), g_node_find_child(),
g_node_child_index(), g_node_child_position(),
g_node_first_child(), g_node_last_child(),
g_node_nth_child(), g_node_first_sibling(), g_node_prev_sibling(),
g_node_next_sibling() or g_node_last_sibling().

To get information about a node or tree use G_NODE_IS_LEAF(), G_NODE_IS_ROOT(), g_node_depth(), g_node_n_nodes(), g_node_n_children(), g_node_is_ancestor() or g_node_max_height().

To traverse a tree, calling a function for each node visited in the traversal, use g_node_traverse() or g_node_children_foreach().

To remove a node or subtree from a tree use g_node_unlink() or g_node_destroy().

Details

GNode

typedef struct {
  gpointer data;
  GNode	  *next;
  GNode	  *prev;
  GNode	  *parent;
  GNode	  *children;
} GNode;

The GNode struct represents one node in a N-ary Tree. The data field contains the actual data of the node. The next and prev fields point to the node's siblings (a sibling is another GNode with the same parent). The parent field points to the parent of the GNode, or is NULL if the GNode is the root of the tree. The children field points to the first child of the GNode. The other children are accessed by using the next pointer of each child.

g_node_new ()

GNode*              g_node_new                          (gpointer data);

Creates a new GNode containing the given data. Used to create the first node in a tree.

data : | the data of the new node.
Returns : | a new GNode.

g_node_copy ()

GNode*              g_node_copy                         (GNode *node);

Recursively copies a GNode (but does not deep-copy the data inside the nodes, see g_node_copy_deep() if you need that).

node : | a GNode.
Returns : | a new GNode containing the same data pointers.

GCopyFunc ()

gpointer            (*GCopyFunc)                        (gconstpointer src,
                                                         gpointer data);

A function of this signature is used to copy the node data when doing a deep-copy of a tree.

src : | A pointer to the data which should be copied.
data : | Additional data.
Returns : | A pointer to the copy.

Since 2.4

g_node_copy_deep ()

GNode*              g_node_copy_deep                    (GNode *node,
                                                         GCopyFunc copy_func,
                                                         gpointer data);

Recursively copies a GNode and its data.

node : | a GNode
copy_func : | the function which is called to copy the data inside each node, or NULL to use the original data.
data : | data to pass to copy_func
Returns : | a new GNode containing copies of the data in node.

Since 2.4

g_node_insert ()

GNode*              g_node_insert                       (GNode *parent,
                                                         gint position,
                                                         GNode *node);

Inserts a GNode beneath the parent at the given position.

parent : | the GNode to place node under.
position : | the position to place node at, with respect to its siblings. If position is -1, node is inserted as the last child of parent.
node : | the GNode to insert.
Returns : | the inserted GNode.

g_node_insert_before ()

GNode*              g_node_insert_before                (GNode *parent,
                                                         GNode *sibling,
                                                         GNode *node);

Inserts a GNode beneath the parent before the given sibling.

parent : | the GNode to place node under.
sibling : | the sibling GNode to place node before. If sibling is NULL, the node is inserted as the last child of parent.
node : | the GNode to insert.
Returns : | the inserted GNode.

g_node_insert_after ()

GNode*              g_node_insert_after                 (GNode *parent,
                                                         GNode *sibling,
                                                         GNode *node);

Inserts a GNode beneath the parent after the given sibling.

parent : | the GNode to place node under.
sibling : | the sibling GNode to place node after. If sibling is NULL, the node is inserted as the first child of parent.
node : | the GNode to insert.
Returns : | the inserted GNode.

g_node_append()

#define             g_node_append(parent, node)

Inserts a GNode as the last child of the given parent.

parent : | the GNode to place the new GNode under.
node : | the GNode to insert.
Returns : | the inserted GNode.

g_node_prepend ()

GNode*              g_node_prepend                      (GNode *parent,
                                                         GNode *node);

Inserts a GNode as the first child of the given parent.

parent : | the GNode to place the new GNode under.
node : | the GNode to insert.
Returns : | the inserted GNode.

g_node_insert_data()

#define             g_node_insert_data(parent, position, data)

Inserts a new GNode at the given position.

parent : | the GNode to place the new GNode under.
position : | the position to place the new GNode at. If position is -1, the new GNode is inserted as the last child of parent.
data : | the data for the new GNode.
Returns : | the new GNode.

g_node_insert_data_before()

#define             g_node_insert_data_before(parent, sibling, data)

Inserts a new GNode before the given sibling.

parent : | the GNode to place the new GNode under.
sibling : | the sibling GNode to place the new GNode before.
data : | the data for the new GNode.
Returns : | the new GNode.

g_node_append_data()

#define             g_node_append_data(parent, data)

Inserts a new GNode as the last child of the given parent.

parent : | the GNode to place the new GNode under.
data : | the data for the new GNode.
Returns : | the new GNode.

g_node_prepend_data()

#define             g_node_prepend_data(parent, data)

Inserts a new GNode as the first child of the given parent.

parent : | the GNode to place the new GNode under.
data : | the data for the new GNode.
Returns : | the new GNode.

g_node_reverse_children ()

void                g_node_reverse_children             (GNode *node);

Reverses the order of the children of a GNode. (It doesn't change the order of the grandchildren.)

node : a GNode.

g_node_traverse ()

void                g_node_traverse                     (GNode *root,
                                                         GTraverseType order,
                                                         GTraverseFlags flags,
                                                         gint max_depth,
                                                         GNodeTraverseFunc func,
                                                         gpointer data);

Traverses a tree starting at the given root GNode. It calls the given function for each node visited. The traversal can be halted at any point by returning TRUE from func.

root : | the root GNode of the tree to traverse.
order : | the order in which nodes are visited - G_IN_ORDER, G_PRE_ORDER, G_POST_ORDER, or G_LEVEL_ORDER.
flags : | which types of children are to be visited, one of G_TRAVERSE_ALL, G_TRAVERSE_LEAVES and G_TRAVERSE_NON_LEAVES.
max_depth : | the maximum depth of the traversal. Nodes below this depth will not be visited. If max_depth is -1 all nodes in the tree are visited. If depth is 1, only the root is visited. If depth is 2, the root and its children are visited. And so on.
func : | the function to call for each visited GNode.
data : | user data to pass to the function.

enum GTraverseFlags

typedef enum
{
  G_TRAVERSE_LEAVES     = 1 << 0,
  G_TRAVERSE_NON_LEAVES = 1 << 1,
  G_TRAVERSE_ALL        = G_TRAVERSE_LEAVES | G_TRAVERSE_NON_LEAVES,
  G_TRAVERSE_MASK       = 0x03,
  G_TRAVERSE_LEAFS      = G_TRAVERSE_LEAVES,
  G_TRAVERSE_NON_LEAFS  = G_TRAVERSE_NON_LEAVES
} GTraverseFlags;

Specifies which nodes are visited during several of the tree functions, including g_node_traverse() and g_node_find().

G_TRAVERSE_LEAVES | only leaf nodes should be visited. This name has been introduced in 2.6, for older version use G_TRAVERSE_LEAFS.
G_TRAVERSE_NON_LEAVES | only non-leaf nodes should be visited. This name has been introduced in 2.6, for older version use G_TRAVERSE_NON_LEAFS.
G_TRAVERSE_ALL | all nodes should be visited.
G_TRAVERSE_MASK |
G_TRAVERSE_LEAFS | identical to G_TRAVERSE_LEAVES
G_TRAVERSE_NON_LEAFS | identical to G_TRAVERSE_NON_LEAVES

GNodeTraverseFunc ()

gboolean            (*GNodeTraverseFunc)                (GNode *node,
                                                         gpointer data);

Specifies the type of function passed to g_node_traverse(). The function is called with each of the nodes visited, together with the user data passed to g_node_traverse(). If the function returns TRUE, then the traversal is stopped.

node : | a GNode.
data : | user data passed to g_node_traverse().
Returns : | TRUE to stop the traversal.

g_node_children_foreach ()

void                g_node_children_foreach             (GNode *node,
                                                         GTraverseFlags flags,
                                                         GNodeForeachFunc func,
                                                         gpointer data);

Calls a function for each of the children of a GNode. Note that it doesn't descend beneath the child nodes.

node : | a GNode.
flags : | which types of children are to be visited, one of G_TRAVERSE_ALL, G_TRAVERSE_LEAVES and G_TRAVERSE_NON_LEAVES.
func : | the function to call for each visited node.
data : | user data to pass to the function.

GNodeForeachFunc ()

void                (*GNodeForeachFunc)                 (GNode *node,
                                                         gpointer data);

Specifies the type of function passed to g_node_children_foreach(). The function is called with each child node, together with the user data passed to g_node_children_foreach().

node : | a GNode.
data : | user data passed to g_node_children_foreach().

g_node_get_root ()

GNode*              g_node_get_root                     (GNode *node);

Gets the root of a tree.

node : | a GNode.
Returns : | the root of the tree.

g_node_find ()

GNode*              g_node_find                         (GNode *root,
                                                         GTraverseType order,
                                                         GTraverseFlags flags,
                                                         gpointer data);

Finds a GNode in a tree.

root : | the root GNode of the tree to search.
order : | the order in which nodes are visited - G_IN_ORDER, G_PRE_ORDER, G_POST_ORDER, or G_LEVEL_ORDER.
flags : | which types of children are to be searched, one of G_TRAVERSE_ALL, G_TRAVERSE_LEAVES and G_TRAVERSE_NON_LEAVES.
data : | the data to find.
Returns : | the found GNode, or NULL if the data is not found.

g_node_find_child ()

GNode*              g_node_find_child                   (GNode *node,
                                                         GTraverseFlags flags,
                                                         gpointer data);

Finds the first child of a GNode with the given data.

node : | a GNode.
flags : | which types of children are to be searched, one of G_TRAVERSE_ALL, G_TRAVERSE_LEAVES and G_TRAVERSE_NON_LEAVES.
data : | the data to find.
Returns : | the found child GNode, or NULL if the data is not found.

g_node_child_index ()

gint                g_node_child_index                  (GNode *node,
                                                         gpointer data);

Gets the position of the first child of a GNode which contains the given data.

node : | a GNode.
data : | the data to find.
Returns : | the index of the child of node which contains data, or -1 if the data is not found.

g_node_child_position ()

gint                g_node_child_position               (GNode *node,
                                                         GNode *child);

Gets the position of a GNode with respect to its siblings. child must be a child of node. The first child is numbered 0, the second 1, and so on.

node : | a GNode.
child : | a child of node.
Returns : | the position of child with respect to its siblings.

g_node_first_child()

#define             g_node_first_child(node)

Gets the first child of a GNode.

node : | a GNode.
Returns : | the last child of node, or NULL if node is NULL or has no children.

g_node_last_child ()

GNode*              g_node_last_child                   (GNode *node);

Gets the last child of a GNode.

node : | a GNode (must not be NULL).
Returns : | the last child of node, or NULL if node has no children.

g_node_nth_child ()

GNode*              g_node_nth_child                    (GNode *node,
                                                         guint n);

Gets a child of a GNode, using the given index. The first child is at index 0. If the index is too big, NULL is returned.

node : | a GNode.
n : | the index of the desired child.
Returns : | the child of node at index n.

g_node_first_sibling ()

GNode*              g_node_first_sibling                (GNode *node);

Gets the first sibling of a GNode. This could possibly be the node itself.

node : | a GNode.
Returns : | the first sibling of node.

g_node_next_sibling()

#define             g_node_next_sibling(node)

Gets the next sibling of a GNode.

node : | a GNode.
Returns : | the next sibling of node, or NULL if node is NULL.

g_node_prev_sibling()

#define             g_node_prev_sibling(node)

Gets the previous sibling of a GNode.

node : | a GNode.
Returns : | the previous sibling of node, or NULL if node is NULL.

g_node_last_sibling ()

GNode*              g_node_last_sibling                 (GNode *node);

Gets the last sibling of a GNode. This could possibly be the node itself.

node : | a GNode.
Returns : | the last sibling of node.

G_NODE_IS_LEAF()

#define	 G_NODE_IS_LEAF(node)	(((GNode*) (node))->children == NULL)

Returns TRUE if a GNode is a leaf node.

node : | a GNode.
Returns : | TRUE if the GNode is a leaf node (i.e. it has no children).

G_NODE_IS_ROOT()

#define             G_NODE_IS_ROOT(node)

Returns TRUE if a GNode is the root of a tree.

node : | a GNode.
Returns : | TRUE if the GNode is the root of a tree (i.e. it has no parent or siblings).

g_node_depth ()

guint               g_node_depth                        (GNode *node);

Gets the depth of a GNode.

If node is NULL the depth is 0. The root node has a depth of 1. For the children of the root node the depth is 2. And so on.

node : | a GNode.
Returns : | the depth of the GNode.

g_node_n_nodes ()

guint               g_node_n_nodes                      (GNode *root,
                                                         GTraverseFlags flags);

Gets the number of nodes in a tree.

root : | a GNode.
flags : | which types of children are to be counted, one of G_TRAVERSE_ALL, G_TRAVERSE_LEAVES and G_TRAVERSE_NON_LEAVES.
Returns : | the number of nodes in the tree.

g_node_n_children ()

guint               g_node_n_children                   (GNode *node);

Gets the number of children of a GNode.

node : | a GNode.
Returns : | the number of children of node.

g_node_is_ancestor ()

gboolean            g_node_is_ancestor                  (GNode *node,
                                                         GNode *descendant);

Returns TRUE if node is an ancestor of descendant. This is true if node is the parent of descendant, or if node is the grandparent of descendant etc.

node : | a GNode.
descendant : | a GNode.
Returns : | TRUE if node is an ancestor of descendant.

g_node_max_height ()

guint               g_node_max_height                   (GNode *root);

Gets the maximum height of all branches beneath a GNode. This is the maximum distance from the GNode to all leaf nodes.

If root is NULL, 0 is returned. If root has no children, 1 is returned. If root has children, 2 is returned. And so on.

root : | a GNode.
Returns : | the maximum height of the tree beneath root.

g_node_unlink ()

void                g_node_unlink                       (GNode *node);

Unlinks a GNode from a tree, resulting in two separate trees.

node : the GNode to unlink, which becomes the root of a new tree.

g_node_destroy ()

void                g_node_destroy                      (GNode *root);

Removes the GNode and its children from the tree, freeing any memory allocated.

root : the root of the tree/subtree to destroy.

g_node_push_allocator ()

void                g_node_push_allocator               (gpointer dummy);

Warning

g_node_push_allocator has been deprecated since version 2.10 and should not be used in newly-written code. It does nothing, since GNode has been converted to the slice allocator

Sets the allocator to use to allocate GNode elements. Use g_node_pop_allocator() to restore the previous allocator.

Note that this function is not available if GLib has been compiled with --disable-mem-pools

dummy : the GAllocator to use when allocating GNode elements.

g_node_pop_allocator ()

void                g_node_pop_allocator                (void);

Warning

g_node_pop_allocator has been deprecated since version 2.10 and should not be used in newly-written code. It does nothing, since GNode has been converted to the slice allocator

Restores the previous GAllocator, used when allocating GNode elements.

Note that this function is not available if GLib has been compiled with --disable-mem-pools


Numerical Definitions

Numerical Definitions — mathematical constants, and floating point decomposition.

Synopsis

#include <glib.h>

#define             G_IEEE754_FLOAT_BIAS
#define             G_IEEE754_DOUBLE_BIAS
union               GFloatIEEE754;
union               GDoubleIEEE754;

#define             G_E
#define             G_LN2
#define             G_LN10
#define             G_PI
#define             G_PI_2
#define             G_PI_4
#define             G_SQRT2
#define             G_LOG_2_BASE_10

Description

GLib offers mathematical constants such as G_PI for the value of pi; many platforms have these in the C library, but some don't, the GLib versions always exist.

The GFloatIEEE754 and GDoubleIEEE754 unions are used to access the sign, mantissa and exponent of IEEE floats and doubles. These unions are defined as appropriate for a given platform. IEEE floats and doubles are supported (used for storage) by at least Intel, PPC and Sparc, for reference: http://cch.loria.fr/documentation/IEEE754/numerical_comp_guide/ncg_math.doc.html

Details

G_IEEE754_FLOAT_BIAS

#define G_IEEE754_FLOAT_BIAS	(127)

See http://cch.loria.fr/documentation/IEEE754/numerical_comp_guide/ncg_math.doc.html

G_IEEE754_DOUBLE_BIAS

#define G_IEEE754_DOUBLE_BIAS	(1023)

See http://cch.loria.fr/documentation/IEEE754/numerical_comp_guide/ncg_math.doc.html

union GFloatIEEE754

union GFloatIEEE754
{
  gfloat v_float;
  struct {
    guint mantissa : 23;
    guint biased_exponent : 8;
    guint sign : 1;
  } mpn;
};

The GFloatIEEE754 and GDoubleIEEE754 unions are used to access the sign, mantissa and exponent of IEEE floats and doubles. These unions are defined as appropriate for a given platform. IEEE floats and doubles are supported (used for storage) by at least Intel, PPC and Sparc, for reference: http://cch.loria.fr/documentation/IEEE754/numerical_comp_guide/ncg_math.doc.html

union GDoubleIEEE754

union GDoubleIEEE754
{
  gdouble v_double;
  struct {
    guint mantissa_low : 32;
    guint mantissa_high : 20;
    guint biased_exponent : 11;
    guint sign : 1;
  } mpn;
};

The GFloatIEEE754 and GDoubleIEEE754 unions are used to access the sign, mantissa and exponent of IEEE floats and doubles. These unions are defined as appropriate for a given platform. IEEE floats and doubles are supported (used for storage) by at least Intel, PPC and Sparc, for reference: http://cch.loria.fr/documentation/IEEE754/numerical_comp_guide/ncg_math.doc.html

G_E

#define G_E     2.7182818284590452353602874713526624977572470937000

The base of natural logarithms.

G_LN2

#define G_LN2   0.69314718055994530941723212145817656807550013436026

The natural logarithm of 2.

G_LN10

#define G_LN10  2.3025850929940456840179914546843642076011014886288

The natural logarithm of 10.

G_PI

#define G_PI    3.1415926535897932384626433832795028841971693993751

The value of pi (ratio of circle's circumference to its diameter).

G_PI_2

#define G_PI_2  1.5707963267948966192313216916397514420985846996876

Pi divided by 2.

G_PI_4

#define G_PI_4  0.78539816339744830961566084581987572104929234984378

Pi divided by 4.

G_SQRT2

#define G_SQRT2 1.4142135623730950488016887242096980785696718753769

The square root of two.

G_LOG_2_BASE_10

#define G_LOG_2_BASE_10		(0.30102999566398119521)

Used for fooling around with float formats, see http://cch.loria.fr/documentation/IEEE754/numerical_comp_guide/ncg_math.doc.html

See Also

http://cch.loria.fr/documentation/IEEE754/numerical_comp_guide/ncg_math.doc.html


Pointer Arrays

Pointer Arrays — arrays of pointers to any type of data, which grow automatically as new elements are added.

Synopsis

#include <glib.h>

                    GPtrArray;
GPtrArray*          g_ptr_array_new                     (void);
GPtrArray*          g_ptr_array_sized_new               (guint reserved_size);
void                g_ptr_array_add                     (GPtrArray *array,
                                                         gpointer data);
gboolean            g_ptr_array_remove                  (GPtrArray *array,
                                                         gpointer data);
gpointer            g_ptr_array_remove_index            (GPtrArray *array,
                                                         guint index_);
gboolean            g_ptr_array_remove_fast             (GPtrArray *array,
                                                         gpointer data);
gpointer            g_ptr_array_remove_index_fast       (GPtrArray *array,
                                                         guint index_);
void                g_ptr_array_remove_range            (GPtrArray *array,
                                                         guint index_,
                                                         guint length);
void                g_ptr_array_sort                    (GPtrArray *array,
                                                         GCompareFunc compare_func);
void                g_ptr_array_sort_with_data          (GPtrArray *array,
                                                         GCompareDataFunc compare_func,
                                                         gpointer user_data);
void                g_ptr_array_set_size                (GPtrArray *array,
                                                         gint length);
#define             g_ptr_array_index                   (array,index_)
gpointer*           g_ptr_array_free                    (GPtrArray *array,
                                                         gboolean free_seg);
void                g_ptr_array_foreach                 (GPtrArray *array,
                                                         GFunc func,
                                                         gpointer user_data);

Description

Pointer Arrays are similar to Arrays but are used only for storing pointers.

Note

If you remove elements from the array, elements at the end of the array are moved into the space previously occupied by the removed element. This means that you should not rely on the index of particular elements remaining the same. You should also be careful when deleting elements while iterating over the array.

To create a pointer array, use g_ptr_array_new().

To add elements to a pointer array, use g_ptr_array_add().

To remove elements from a pointer array, use g_ptr_array_remove(), g_ptr_array_remove_index() or g_ptr_array_remove_index_fast().

To access an element of a pointer array, use g_ptr_array_index().

To set the size of a pointer array, use g_ptr_array_set_size().

To free a pointer array, use g_ptr_array_free().

Example 23. Using a GPtrArray

  GPtrArray *gparray;
  gchar *string1 = "one", *string2 = "two", *string3 = "three";

  gparray = g_ptr_array_new ();
  g_ptr_array_add (gparray, (gpointer) string1);
  g_ptr_array_add (gparray, (gpointer) string2);
  g_ptr_array_add (gparray, (gpointer) string3);

  if (g_ptr_array_index (gparray, 0) != (gpointer) string1)
    g_print ("ERROR: got %p instead of %p\n",
             g_ptr_array_index (gparray, 0), string1);

  g_ptr_array_free (gparray, TRUE);

Details

GPtrArray

typedef struct {
  gpointer *pdata;
  guint	    len;
} GPtrArray;

Contains the public fields of a pointer array.

gpointer *pdata; | points to the array of pointers, which may be moved when the array grows.
guint len; | number of pointers in the array.

g_ptr_array_new ()

GPtrArray*          g_ptr_array_new                     (void);

Creates a new GPtrArray.

Returns : the new GPtrArray.

g_ptr_array_sized_new ()

GPtrArray*          g_ptr_array_sized_new               (guint reserved_size);

Creates a new GPtrArray with reserved_size pointers preallocated. This avoids frequent reallocation, if you are going to add many pointers to the array. Note however that the size of the array is still 0.

reserved_size : | number of pointers preallocated.
Returns : | the new GPtrArray.

g_ptr_array_add ()

void                g_ptr_array_add                     (GPtrArray *array,
                                                         gpointer data);

Adds a pointer to the end of the pointer array. The array will grow in size automatically if necessary.

array : | a GPtrArray.
data : | the pointer to add.

g_ptr_array_remove ()

gboolean            g_ptr_array_remove                  (GPtrArray *array,
                                                         gpointer data);

Removes the first occurrence of the given pointer from the pointer array. The following elements are moved down one place.

It returns TRUE if the pointer was removed, or FALSE if the pointer was not found.

array : | a GPtrArray.
data : | the pointer to remove.
Returns : | TRUE if the pointer is removed. FALSE if the pointer is not found in the array.

g_ptr_array_remove_index ()

gpointer            g_ptr_array_remove_index            (GPtrArray *array,
                                                         guint index_);

Removes the pointer at the given index from the pointer array. The following elements are moved down one place.

array : | a GPtrArray.
index_ : | the index of the pointer to remove.
Returns : | the pointer which was removed.

g_ptr_array_remove_fast ()

gboolean            g_ptr_array_remove_fast             (GPtrArray *array,
                                                         gpointer data);

Removes the first occurrence of the given pointer from the pointer array. The last element in the array is used to fill in the space, so this function does not preserve the order of the array. But it is faster than g_ptr_array_remove().

It returns TRUE if the pointer was removed, or FALSE if the pointer was not found.

array : | a GPtrArray.
data : | the pointer to remove.
Returns : | TRUE if the pointer was found in the array.

g_ptr_array_remove_index_fast ()

gpointer            g_ptr_array_remove_index_fast       (GPtrArray *array,
                                                         guint index_);

Removes the pointer at the given index from the pointer array. The last element in the array is used to fill in the space, so this function does not preserve the order of the array. But it is faster than g_ptr_array_remove_index().

array : | a GPtrArray.
index_ : | the index of the pointer to remove.
Returns : | the pointer which was removed.

g_ptr_array_remove_range ()

void                g_ptr_array_remove_range            (GPtrArray *array,
                                                         guint index_,
                                                         guint length);

Removes the given number of pointers starting at the given index from a GPtrArray. The following elements are moved to close the gap.

array : | a GPtrArray.
index_ : | the index of the first pointer to remove.
length : | the number of pointers to remove.

Since 2.4

g_ptr_array_sort ()

void                g_ptr_array_sort                    (GPtrArray *array,
                                                         GCompareFunc compare_func);

Sorts the array, using compare_func which should be a qsort()-style comparison function (returns less than zero for first arg is less than second arg, zero for equal, greater than zero if irst arg is greater than second arg).

If two array elements compare equal, their order in the sorted array is undefined.

Note

The comparison function for g_ptr_array_sort() doesn't take the pointers from the array as arguments, it takes pointers to the pointers in the array.

array : | a GPtrArray.
compare_func : | comparison function.

g_ptr_array_sort_with_data ()

void                g_ptr_array_sort_with_data          (GPtrArray *array,
                                                         GCompareDataFunc compare_func,
                                                         gpointer user_data);

Like g_ptr_array_sort(), but the comparison function has an extra user data argument.

Note

The comparison function for g_ptr_array_sort_with_data() doesn't take the pointers from the array as arguments, it takes pointers to the pointers in the array.

array : | a GPtrArray.
compare_func : | comparison function.
user_data : | data to pass to compare_func.

g_ptr_array_set_size ()

void                g_ptr_array_set_size                (GPtrArray *array,
                                                         gint length);

Sets the size of the array, expanding it if necessary. New elements are set to NULL.

array : | a GPtrArray.
length : | the new length of the pointer array.

g_ptr_array_index()

#define             g_ptr_array_index(array,index_)

Returns the pointer at the given index of the pointer array.

array : | a GPtrArray.
index_ : | the index of the pointer to return.
Returns : | the pointer at the given index.

g_ptr_array_free ()

gpointer*           g_ptr_array_free                    (GPtrArray *array,
                                                         gboolean free_seg);

Frees all of the memory allocated for the pointer array.

array : | a GPtrArray.
free_seg : | if TRUE the array of pointers (pdata) is freed.
Returns : | NULL if free_seg is TRUE, otherwise the array of pointers (pdata) is returned.

g_ptr_array_foreach ()

void                g_ptr_array_foreach                 (GPtrArray *array,
                                                         GFunc func,
                                                         gpointer user_data);

Calls a function for each element of a GPtrArray.

array : | a GPtrArray
func : | the function to call for each array element
user_data : | user data to pass to the function

Since 2.4


Quarks

Quarks — a 2-way association between a string and a unique integer identifier.

Synopsis

#include <glib.h>

typedef             GQuark;
GQuark              g_quark_from_string                 (const gchar *string);
GQuark              g_quark_from_static_string          (const gchar *string);
const gchar*        g_quark_to_string                   (GQuark quark);
GQuark              g_quark_try_string                  (const gchar *string);
const gchar*        g_intern_string                     (const gchar *string);
const gchar*        g_intern_static_string              (const gchar *string);

Description

Quarks are associations between strings and integer identifiers. Given either the string or the GQuark identifier it is possible to retrieve the other.

Quarks are used for both Datasets and Keyed Data Lists.

To create a new quark from a string, use g_quark_from_string() or g_quark_from_static_string().

To find the string corresponding to a given GQuark, use g_quark_to_string().

To find the GQuark corresponding to a given string, use g_quark_try_string().

Another use for the string pool maintained for the quark functions is string interning, using g_intern_string() or g_intern_static_string(). An interned string is a canonical representation for a string. One important advantage of interned strings is that they can be compared for equality by a simple pointer comparision, rather than using strcmp().

Details

GQuark

typedef guint32 GQuark;

A GQuark is an integer which uniquely identifies a particular string.

g_quark_from_string ()

GQuark              g_quark_from_string                 (const gchar *string);

Gets the GQuark identifying the given string. If the string does not currently have an associated GQuark, a new GQuark is created, using a copy of the string.

string : | a string.
Returns : | the GQuark identifying the string.

g_quark_from_static_string ()

GQuark              g_quark_from_static_string          (const gchar *string);

Gets the GQuark identifying the given (static) string. If the string does not currently have an associated GQuark, a new GQuark is created, linked to the given string.

Note that this function is identical to g_quark_from_string() except that if a new GQuark is created the string itself is used rather than a copy. This saves memory, but can only be used if the string will always exist. It can be used with statically allocated strings in the main program, but not with statically allocated memory in dynamically loaded modules, if you expect to ever unload the module again (e.g. do not use this function in GTK+ theme engines).

string : | a string.
Returns : | the GQuark identifying the string.

g_quark_to_string ()

const gchar*        g_quark_to_string                   (GQuark quark);

Gets the string associated with the given GQuark.

quark : | a GQuark.
Returns : | the string associated with the GQuark.

g_quark_try_string ()

GQuark              g_quark_try_string                  (const gchar *string);

Gets the GQuark associated with the given string, or 0 if the string has no associated GQuark.

If you want the GQuark to be created if it doesn't already exist, use g_quark_from_string() or g_quark_from_static_string().

string : | a string.
Returns : | the GQuark associated with the string, or 0 if there is no GQuark associated with the string.

g_intern_string ()

const gchar*        g_intern_string                     (const gchar *string);

Returns a canonical representation for string. Interned strings can be compared for equality by comparing the pointers, instead of using strcmp().

string : | a string
Returns : | a canonical representation for the string

Since 2.10

g_intern_static_string ()

const gchar*        g_intern_static_string              (const gchar *string);

Returns a canonical representation for string. Interned strings can be compared for equality by comparing the pointers, instead of using strcmp(). g_intern_static_string() does not copy the string, therefore string must not be freed or modified.

string : | a static string
Returns : | a canonical representation for the string

Since 2.10


Random Numbers

Random Numbers — pseudo-random number generator.

Synopsis

#include <glib.h>

                    GRand;
GRand*              g_rand_new_with_seed                (guint32 seed);
GRand*              g_rand_new_with_seed_array          (const guint32 *seed,
                                                         guint seed_length);
GRand*              g_rand_new                          (void);
GRand*              g_rand_copy                         (GRand *rand_);
void                g_rand_free                         (GRand *rand_);
void                g_rand_set_seed                     (GRand *rand_,
                                                         guint32 seed);
void                g_rand_set_seed_array               (GRand *rand_,
                                                         const guint32 *seed,
                                                         guint seed_length);
#define             g_rand_boolean                      (rand_)
guint32             g_rand_int                          (GRand *rand_);
gint32              g_rand_int_range                    (GRand *rand_,
                                                         gint32 begin,
                                                         gint32 end);
gdouble             g_rand_double                       (GRand *rand_);
gdouble             g_rand_double_range                 (GRand *rand_,
                                                         gdouble begin,
                                                         gdouble end);
void                g_random_set_seed                   (guint32 seed);
#define             g_random_boolean                    ()
guint32             g_random_int                        (void);
gint32              g_random_int_range                  (gint32 begin,
                                                         gint32 end);
gdouble             g_random_double                     (void);
gdouble             g_random_double_range               (gdouble begin,
                                                         gdouble end);

Description

The following functions allow you to use a portable, fast and good pseudo-random number generator (PRNG). It uses the Mersenne Twister PRNG, which was originally developed by Makoto Matsumoto and Takuji Nishimura. Further information can be found at www.math.keio.ac.jp/~matumoto/emt.html.

If you just need a random number, you simply call the g_random_* functions, which will create a globally used GRand and use the according g_rand_* functions internally. Whenever you need a stream of reproducible random numbers, you better create a GRand yourself and use the g_rand_* functions directly, which will also be slightly faster. Initializing a GRand with a certain seed will produce exactly the same series of random numbers on all platforms. This can thus be used as a seed for e.g. games.

The g_rand*_range functions will return high quality equally distributed random numbers, whereas for example the (g_random_int()%max) approach often doesn't yield equally distributed numbers.

GLib changed the seeding algorithm for the pseudo-random number generator Mersenne Twister, as used by GRand and GRandom. This was necessary, because some seeds would yield very bad pseudo-random streams. Also the pseudo-random integers generated by g_rand*_int_range() will have a slightly better equal distribution with the new version of GLib.

The original seeding and generation algorithms, as found in GLib 2.0.x, can be used instead of the new ones by setting the environment variable G_RANDOM_VERSION to the value of '2.0'. Use the GLib-2.0 algorithms only if you have sequences of numbers generated with Glib-2.0 that you need to reproduce exactly.

Details

GRand

typedef struct _GRand GRand;

The GRand struct is an opaque data structure. It should only be accessed through the g_rand_* functions.

g_rand_new_with_seed ()

GRand*              g_rand_new_with_seed                (guint32 seed);

Creates a new random number generator initialized with seed.

seed : | a value to initialize the random number generator.
Returns : | the new GRand.

g_rand_new_with_seed_array ()

GRand*              g_rand_new_with_seed_array          (const guint32 *seed,
                                                         guint seed_length);

Creates a new random number generator initialized with seed.

seed : | an array of seeds to initialize the random number generator.
seed_length : | an array of seeds to initialize the random number generator.
Returns : | the new GRand.

Since 2.4

g_rand_new ()

GRand*              g_rand_new                          (void);

Creates a new random number generator initialized with a seed taken either from /dev/urandom (if existing) or from the current time (as a fallback).

Returns : the new GRand.

g_rand_copy ()

GRand*              g_rand_copy                         (GRand *rand_);

Copies a GRand into a new one with the same exact state as before. This way you can take a snapshot of the random number generator for replaying later.

rand_ : | a GRand.
Returns : | the new GRand.

Since 2.4

g_rand_free ()

void                g_rand_free                         (GRand *rand_);

Frees the memory allocated for the GRand.

rand_ : a GRand.

g_rand_set_seed ()

void                g_rand_set_seed                     (GRand *rand_,
                                                         guint32 seed);

Sets the seed for the random number generator GRand to seed.

rand_ : | a GRand.
seed : | a value to reinitialize the random number generator.

g_rand_set_seed_array ()

void                g_rand_set_seed_array               (GRand *rand_,
                                                         const guint32 *seed,
                                                         guint seed_length);

Initializes the random number generator by an array of longs. Array can be of arbitrary size, though only the first 624 values are taken. This function is useful if you have many low entropy seeds, or if you require more then 32bits of actual entropy for your application.

rand_ : | a GRand.
seed : | array to initialize with
seed_length : | length of array

Since 2.4

g_rand_boolean()

#define             g_rand_boolean(rand_)

Returns a random gboolean from rand_. This corresponds to a unbiased coin toss.

rand_ : | a GRand.
Returns : | a random gboolean.

g_rand_int ()

guint32             g_rand_int                          (GRand *rand_);

Returns the next random guint32 from rand_ equally distributed over the range [0..2^32-1].

rand_ : | a GRand.
Returns : | A random number.

g_rand_int_range ()

gint32              g_rand_int_range                    (GRand *rand_,
                                                         gint32 begin,
                                                         gint32 end);

Returns the next random gint32 from rand_ equally distributed over the range [begin..end-1].

rand_ : | a GRand.
begin : | lower closed bound of the interval.
end : | upper open bound of the interval.
Returns : | A random number.

g_rand_double ()

gdouble             g_rand_double                       (GRand *rand_);

Returns the next random gdouble from rand_ equally distributed over the range [0..1).

rand_ : | a GRand.
Returns : | A random number.

g_rand_double_range ()

gdouble             g_rand_double_range                 (GRand *rand_,
                                                         gdouble begin,
                                                         gdouble end);

Returns the next random gdouble from rand_ equally distributed over the range [begin..end).

rand_ : | a GRand.
begin : | lower closed bound of the interval.
end : | upper open bound of the interval.
Returns : | A random number.

g_random_set_seed ()

void                g_random_set_seed                   (guint32 seed);

Sets the seed for the global random number generator, which is used by the g_random_* functions, to seed.

seed : a value to reinitialize the global random number generator.

g_random_boolean()

#define             g_random_boolean()

Returns a random gboolean. This corresponds to a unbiased coin toss.

Returns : a random gboolean.

g_random_int ()

guint32             g_random_int                        (void);

Return a random guint32 equally distributed over the range [0..2^32-1].

Returns : A random number.

g_random_int_range ()

gint32              g_random_int_range                  (gint32 begin,
                                                         gint32 end);

Returns a random gint32 equally distributed over the range [begin..end-1].

begin : | lower closed bound of the interval.
end : | upper open bound of the interval.
Returns : | A random number.

g_random_double ()

gdouble             g_random_double                     (void);

Returns a random gdouble equally distributed over the range [0..1).

Returns : A random number.

g_random_double_range ()

gdouble             g_random_double_range               (gdouble begin,
                                                         gdouble end);

Returns a random gdouble equally distributed over the range [begin..end).

begin : | lower closed bound of the interval.
end : | upper open bound of the interval.
Returns : | A random number.


Relations and Tuples

Relations and Tuples — tables of data which can be indexed on any number of fields.

Synopsis

#include <glib.h>

                    GRelation;
GRelation*          g_relation_new                      (gint fields);
void                g_relation_index                    (GRelation *relation,
                                                         gint field,
                                                         GHashFunc hash_func,
                                                         GEqualFunc key_equal_func);
void                g_relation_insert                   (GRelation *relation,
                                                         ...);
gboolean            g_relation_exists                   (GRelation *relation,
                                                         ...);
gint                g_relation_count                    (GRelation *relation,
                                                         gconstpointer key,
                                                         gint field);
GTuples*            g_relation_select                   (GRelation *relation,
                                                         gconstpointer key,
                                                         gint field);
gint                g_relation_delete                   (GRelation *relation,
                                                         gconstpointer key,
                                                         gint field);
void                g_relation_destroy                  (GRelation *relation);

void                g_relation_print                    (GRelation *relation);

                    GTuples;
void                g_tuples_destroy                    (GTuples *tuples);
gpointer            g_tuples_index                      (GTuples *tuples,
                                                         gint index_,
                                                         gint field);

Description

A GRelation is a table of data which can be indexed on any number of fields, rather like simple database tables. A GRelation contains a number of records, called tuples. Each record contains a number of fields. Records are not ordered, so it is not possible to find the record at a particular index.

Note that GRelation tables are currently limited to 2 fields.

To create a GRelation, use g_relation_new().

To specify which fields should be indexed, use g_relation_index(). Note that this must be called before any tuples are added to the GRelation.

To add records to a GRelation use g_relation_insert().

To determine if a given record appears in a GRelation, use g_relation_exists(). Note that fields are compared directly, so pointers must point to the exact same position (i.e. different copies of the same string will not match.)

To count the number of records which have a particular value in a given field, use g_relation_count().

To get all the records which have a particular value in a given field, use g_relation_select(). To access fields of the resulting records, use g_tuples_index(). To free the resulting records use g_tuples_destroy().

To delete all records which have a particular value in a given field, use g_relation_delete().

To destroy the GRelation, use g_relation_destroy().

To help debug GRelation objects, use g_relation_print().

Details

GRelation

typedef struct _GRelation GRelation;

The GRelation struct is an opaque data structure to represent a Relation. It should only be accessed via the following functions.

g_relation_new ()

GRelation*          g_relation_new                      (gint fields);

Creates a new GRelation with the given number of fields. Note that currently the number of fields must be 2.

fields : | the number of fields.
Returns : | a new GRelation.

g_relation_index ()

void                g_relation_index                    (GRelation *relation,
                                                         gint field,
                                                         GHashFunc hash_func,
                                                         GEqualFunc key_equal_func);

Creates an index on the given field. Note that this must be called before any records are added to the GRelation.

relation : | a GRelation.
field : | the field to index, counting from 0.
hash_func : | a function to produce a hash value from the field data.
key_equal_func : | a function to compare two values of the given field.

g_relation_insert ()

void                g_relation_insert                   (GRelation *relation,
                                                         ...);

Inserts a record into a GRelation.

relation : | a GRelation.
... : | the fields of the record to add. These must match the number of fields in the GRelation, and of type gpointer or gconstpointer.

g_relation_exists ()

gboolean            g_relation_exists                   (GRelation *relation,
                                                         ...);

Returns TRUE if a record with the given values exists in a GRelation. Note that the values are compared directly, so that, for example, two copies of the same string will not match.

relation : | a GRelation.
... : | the fields of the record to compare. The number must match the number of fields in the GRelation.
Returns : | TRUE if a record matches.

g_relation_count ()

gint                g_relation_count                    (GRelation *relation,
                                                         gconstpointer key,
                                                         gint field);

Returns the number of tuples in a GRelation that have the given value in the given field.

relation : | a GRelation.
key : | the value to compare with.
field : | the field of each record to match.
Returns : | the number of matches.

g_relation_select ()

GTuples*            g_relation_select                   (GRelation *relation,
                                                         gconstpointer key,
                                                         gint field);

Returns all of the tuples which have the given key in the given field. Use g_tuples_index() to access the returned records. The returned records should be freed with g_tuples_destroy().

relation : | a GRelation.
key : | the value to compare with.
field : | the field of each record to match.
Returns : | the records (tuples) that matched.

g_relation_delete ()

gint                g_relation_delete                   (GRelation *relation,
                                                         gconstpointer key,
                                                         gint field);

Deletes any records from a GRelation that have the given key value in the given field.

relation : | a GRelation.
key : | the value to compare with.
field : | the field of each record to match.
Returns : | the number of records deleted.

g_relation_destroy ()

void                g_relation_destroy                  (GRelation *relation);

Destroys the GRelation, freeing all memory allocated. However, it does not free memory allocated for the tuple data, so you should free that first if appropriate.

relation : a GRelation.

g_relation_print ()

void                g_relation_print                    (GRelation *relation);

Outputs information about all records in a GRelation, as well as the indexes. It is for debugging.

relation : a GRelation.

GTuples

typedef struct {
  guint len;
} GTuples;

The GTuples struct is used to return records (or tuples) from the GRelation by g_relation_select(). It only contains one public member - the number of records that matched. To access the matched records, you must use g_tuples_index().

guint len; the number of records that matched.

g_tuples_destroy ()

void                g_tuples_destroy                    (GTuples *tuples);

Frees the records which were returned by g_relation_select(). This should always be called after g_relation_select() when you are finished with the records. The records are not removed from the GRelation.

tuples : the tuple data to free.

g_tuples_index ()

gpointer            g_tuples_index                      (GTuples *tuples,
                                                         gint index_,
                                                         gint field);

Gets a field from the records returned by g_relation_select(). It returns the given field of the record at the given index. The returned value should not be changed.

tuples : | the tuple data, returned by g_relation_select().
index_ : | the index of the record.
field : | the field to return.
Returns : | the field of the record.


Mailing lists and bug reports

Mailing lists and bug reports — Getting help with GLib

Filing a bug report or feature request

If you encounter a bug, misfeature, or missing feature in GLib, please file a bug report on http://bugzilla.gnome.org. We'd also appreciate reports of incomplete or misleading information in the GLib documentation; file those against the "docs" component of the "glib" product in Bugzilla.

Don't hesitate to file a bug report, even if you think we may know about it already, or aren't sure of the details. Just give us as much information as you have, and if it's already fixed or has already been discussed, we'll add a note to that effect in the report.

The bug tracker should definitely be used for feature requests, it's not only for bugs. We track all GLib development in Bugzilla, so it's the way to be sure the GLib developers won't forget about an issue.

Submitting Patches

If you develop a bugfix or enhancement for GLib, please file that in Bugzilla as well. Bugzilla allows you to attach files; please attach a patch generated by the diff utility, using the -u option to make the patch more readable. All patches must be offered under the terms of the GNU LGPL license, so be sure you are authorized to give us the patch under those terms.

If you want to discuss your patch before or after developing it, mail gtk-devel-list@gnome.org. But be sure to file the Bugzilla report as well; if the patch is only on the list and not in Bugzilla, it's likely to slip through the cracks.

Mailing lists

There are several mailing lists dedicated to GTK+ and related libraries. Discussion of GLib generally takes place on these lists. You can subscribe or view the archives of these lists on http://mail.gnome.org.

gtk-list@gnome.org | gtk-list covers general GTK+ (and GLib) topics; questions about using GLib in programs, GLib from a user standpoint, announcements of GLib-related projects would all be on-topic. The bulk of the traffic consists of GTK+ programming questions.
gtk-devel-list@gnome.org | gtk-devel-list is for discussion of work on GTK+ (and GLib) itself, it is not for asking questions about how to use GTK+ (or GLib) in applications. gtk-devel-list is appropriate for discussion of patches, bugs, proposed features, and so on.
gtk-doc-list@gnome.org | gtk-doc-list is for discussion of the gtk-doc documentation system (used to document GTK+ and Glib), and for work on the GTK+ (and GLib) documentation.


Running GLib Applications

Running GLib Applications — How to run and debug your GLib application

Running and debugging GLib Applications

Environment variables

GLib inspects a few of environment variables in addition to standard variables like LANG, PATH or HOME.

G_FILENAME_ENCODING. This environment variable can be set to a comma-separated list of character set names. GLib assumes that filenames are encoded in the first character set from that list rather than in UTF-8. The special token "@locale" can be used to specify the character set for the current locale.

G_BROKEN_FILENAMES. If this environment variable is set, GLib assumes that filenames are in the locale encoding rather than in UTF-8. G_FILENAME_ENCODING takes priority over G_BROKEN_FILENAMES.

G_MESSAGES_PREFIXED. A list of log levels for which messages should be prefixed by the program name and PID of the application. The default is to prefix everything except G_LOG_LEVEL_MESSAGE and G_LOG_LEVEL_INFO.

G_DEBUG. If GLib has been configured with --enable-debug=yes, this variable can be set to a list of debug options, which cause GLib to print out different types of debugging information.

fatal_warnings | Causes GLib to abort the program at the first call to g_warning() or g_critical(). This option is special in that it doesn't require GLib to be configured with debugging support.
fatal_criticals | Causes GLib to abort the program at the first call to g_critical(). This option is special in that it doesn't require GLib to be configured with debugging support.
gc-friendly | Newly allocated memory that isn't directly initialized, as well as memory being freed will be reset to 0. The point here is to allow memory checkers and similar programs that use bohem GC alike algorithms to produce more accurate results. This option is special in that it doesn't require GLib to be configured with debugging support.

G_SLICE. This environment variable allows reconfiguration of the #GSlice memory allocator.

always-malloc

This will cause all slices allocated through g_slice_alloc() and released by g_slice_free1() to be actually allocated via direct calls to g_malloc() and g_free(). This is most useful for memory checkers and similar programs that use bohem GC alike algorithms to produce more accurate results. It can also be in conjunction with debugging features of the system's malloc implementation such as glibc's MALLOC_CHECK_=2 to debug erroneous slice allocation code.

G_RANDOM_VERSION. If this environment variable is set to '2.0', the outdated pseudo-random number seeding and generation algorithms from GLib-2.0 are used instead of the new better ones. Use the GLib-2.0 algorithms only if you have sequences of numbers generated with Glib-2.0 that you need to reproduce exactly.

LIBCHARSET_ALIAS_DIR. Allows to specify a nonstandard location for the charset.aliases file that is used by the character set conversion routines. The default location is the libdir specified at compilation time.

G_WIN32_PRETEND_WIN9X. Setting this variable to any value forces g_win32_get_windows_version() to return a version code for Windows 9x. This is mainly an internal debugging aid for GTK+ and GLib developers, to be able to check the code paths for Windows 9x.

Traps and traces

Some code portions contain trap variables that can be set during debugging time if GLib has been configured with --enable-debug=yes. Such traps lead to immediate code halts to examine the current program state and backtrace.

Currently, the following trap variables exist:

static volatile gulong g_trap_free_size;
static volatile gulong g_trap_realloc_size;
static volatile gulong g_trap_malloc_size;

If set to a size > 0, g_free(), g_realloc() and g_malloc() will be intercepted if the size matches the size of the corresponding memory block. This will only work with g_mem_set_vtable (glib_mem_profiler_table) upon startup though, because memory profiling is required to match on the memory block sizes.

Note that many modern debuggers support conditional breakpoints, which achieve pretty much the same. E.g. in gdb, you can do

break g_malloc
condition 1 n_bytes == 20

to break only on g_malloc() calls where the size of the allocated memory block is 20.


Shell-related Utilities

Shell-related Utilities — shell-like commandline handling.

Synopsis

#include <glib.h>

enum                GShellError;
#define             G_SHELL_ERROR
gboolean            g_shell_parse_argv                  (const gchar *command_line,
                                                         gint *argcp,
                                                         gchar ***argvp,
                                                         GError **error);
gchar*              g_shell_quote                       (const gchar *unquoted_string);
gchar*              g_shell_unquote                     (const gchar *quoted_string,
                                                         GError **error);

Description

Details

enum GShellError

typedef enum
{
  /* mismatched or otherwise mangled quoting */
  G_SHELL_ERROR_BAD_QUOTING,
  /* string to be parsed was empty */
  G_SHELL_ERROR_EMPTY_STRING,
  G_SHELL_ERROR_FAILED
} GShellError;

Error codes returned by shell functions.

G_SHELL_ERROR_BAD_QUOTING | Mismatched or otherwise mangled quoting.
G_SHELL_ERROR_EMPTY_STRING | String to be parsed was empty.
G_SHELL_ERROR_FAILED | Some other error.

G_SHELL_ERROR

#define G_SHELL_ERROR g_shell_error_quark ()

Error domain for shell functions. Errors in this domain will be from the GShellError enumeration. See GError for information on error domains.

g_shell_parse_argv ()

gboolean            g_shell_parse_argv                  (const gchar *command_line,
                                                         gint *argcp,
                                                         gchar ***argvp,
                                                         GError **error);

Parses a command line into an argument vector, in much the same way the shell would, but without many of the expansions the shell would perform (variable expansion, globs, operators, filename expansion, etc. are not supported). The results are defined to be the same as those you would get from a UNIX98 /bin/sh, as long as the input contains none of the unsupported shell expansions. If the input does contain such expansions, they are passed through literally. Possible errors are those from the G_SHELL_ERROR domain. Free the returned vector with g_strfreev().

command_line : | command line to parse
argcp : | return location for number of args
argvp : | return location for array of args
error : | return location for error
Returns : | TRUE on success, FALSE if error set

g_shell_quote ()

gchar*              g_shell_quote                       (const gchar *unquoted_string);

Quotes a string so that the shell (/bin/sh) will interpret the quoted string to mean unquoted_string. If you pass a filename to the shell, for example, you should first quote it with this function. The return value must be freed with g_free(). The quoting style used is undefined (single or double quotes may be used).

unquoted_string : | a literal string
Returns : | quoted string

g_shell_unquote ()

gchar*              g_shell_unquote                     (const gchar *quoted_string,
                                                         GError **error);

Unquotes a string as the shell (/bin/sh) would. Only handles quotes; if a string contains file globs, arithmetic operators, variables, backticks, redirections, or other special-to-the-shell features, the result will be different from the result a real shell would produce (the variables, backticks, etc. will be passed through literally instead of being expanded). This function is guaranteed to succeed if applied to the result of g_shell_quote(). If it fails, it returns NULL and sets the error. The quoted_string need not actually contain quoted or escaped text; g_shell_unquote() simply goes through the string and unquotes/unescapes anything that the shell would. Both single and double quotes are handled, as are escapes including escaped newlines. The return value must be freed with g_free(). Possible errors are in the G_SHELL_ERROR domain.

Shell quoting rules are a bit strange. Single quotes preserve the literal string exactly. escape sequences are not allowed; not even \' - if you want a ' in the quoted text, you have to do something like 'foo'\''bar'. Double quotes allow $, `, ", \, and newline to be escaped with backslash. Otherwise double quotes preserve things literally.

quoted_string : | shell-quoted string
error : | error return location or NULL
Returns : | an unquoted string


Simple XML Subset Parser

Simple XML Subset Parser — parses a subset of XML.

Synopsis

#include <glib.h>

enum                GMarkupError;
#define             G_MARKUP_ERROR
enum                GMarkupParseFlags;
                    GMarkupParseContext;
                    GMarkupParser;
gchar*              g_markup_escape_text                (const gchar *text,
                                                         gssize length);
gchar*              g_markup_printf_escaped             (const char *format,
                                                         ...);
gchar*              g_markup_vprintf_escaped            (const char *format,
                                                         va_list args);
gboolean            g_markup_parse_context_end_parse    (GMarkupParseContext *context,
                                                         GError **error);
void                g_markup_parse_context_free         (GMarkupParseContext *context);
void                g_markup_parse_context_get_position (GMarkupParseContext *context,
                                                         gint *line_number,
                                                         gint *char_number);
const gchar*        g_markup_parse_context_get_element  (GMarkupParseContext *context);
GMarkupParseContext* g_markup_parse_context_new         (const GMarkupParser *parser,
                                                         GMarkupParseFlags flags,
                                                         gpointer user_data,
                                                         GDestroyNotify user_data_dnotify);
gboolean            g_markup_parse_context_parse        (GMarkupParseContext *context,
                                                         const gchar *text,
                                                         gssize text_len,
                                                         GError **error);

Description

The "GMarkup" parser is intended to parse a simple markup format that's a subset of XML. This is a small, efficient, easy-to-use parser. It should not be used if you expect to interoperate with other applications generating full-scale XML. However, it's very useful for application data files, config files, etc. where you know your application will be the only one writing the file. Full-scale XML parsers should be able to parse the subset used by GMarkup, so you can easily migrate to full-scale XML at a later time if the need arises.

GMarkup is not guaranteed to signal an error on all invalid XML; the parser may accept documents that an XML parser would not. However, XML documents which are not well-formed[4] are not considered valid GMarkup documents.

Simplifications to XML include:

  • Only UTF-8 encoding is allowed.

  • No user-defined entities.

  • Processing instructions, comments and the doctype declaration are "passed through" but are not interpreted in any way.

  • No DTD or validation.

The markup format does support:

  • Elements

  • Attributes

  • 5 standard entities: &amp; &lt; &gt; &quot; &apos;

  • Character references

  • Sections marked as CDATA

Details

enum GMarkupError

typedef enum
{
  G_MARKUP_ERROR_BAD_UTF8,
  G_MARKUP_ERROR_EMPTY,
  G_MARKUP_ERROR_PARSE,
  /* These three are primarily intended for specific GMarkupParser
   * implementations to set.
   */
  G_MARKUP_ERROR_UNKNOWN_ELEMENT,
  G_MARKUP_ERROR_UNKNOWN_ATTRIBUTE,
  G_MARKUP_ERROR_INVALID_CONTENT
} GMarkupError;

Error codes returned by markup parsing.

G_MARKUP_ERROR_BAD_UTF8 | text being parsed was not valid UTF-8
G_MARKUP_ERROR_EMPTY | document contained nothing, or only whitespace
G_MARKUP_ERROR_PARSE | document was ill-formed
G_MARKUP_ERROR_UNKNOWN_ELEMENT | error should be set by GMarkupParser functions; element wasn't known
G_MARKUP_ERROR_UNKNOWN_ATTRIBUTE | error should be set by GMarkupParser functions; attribute wasn't known
G_MARKUP_ERROR_INVALID_CONTENT | error should be set by GMarkupParser functions; something was wrong with contents of the document, e.g. invalid attribute value

G_MARKUP_ERROR

#define G_MARKUP_ERROR g_markup_error_quark ()

Error domain for markup parsing. Errors in this domain will be from the GMarkupError enumeration. See GError for information on error domains.

enum GMarkupParseFlags

typedef enum
{
  G_MARKUP_DO_NOT_USE_THIS_UNSUPPORTED_FLAG = 1 << 0,
  G_MARKUP_TREAT_CDATA_AS_TEXT              = 1 << 1
} GMarkupParseFlags;

Flags that affect the behaviour of the parser.

G_MARKUP_DO_NOT_USE_THIS_UNSUPPORTED_FLAG | flag you should not use.
G_MARKUP_TREAT_CDATA_AS_TEXT | When this flag is set, CDATA marked sections are not passed literally to the passthrough function of the parser. Instead, the content of the section (without the <![CDATA[ and ]]>) is passed to the text function. This flag was added in GLib 2.12.

GMarkupParseContext

typedef struct _GMarkupParseContext GMarkupParseContext;

A parse context is used to parse a stream of bytes that you expect to contain marked-up text. See g_markup_parse_context_new(), GMarkupParser, and so on for more details.

GMarkupParser

typedef struct {
  /* Called for open tags <foo bar="baz"> */
  void (*start_element)  (GMarkupParseContext *context,
                          const gchar         *element_name,
                          const gchar        **attribute_names,
                          const gchar        **attribute_values,
                          gpointer             user_data,
                          GError             **error);

  /* Called for close tags </foo> */
  void (*end_element)    (GMarkupParseContext *context,
                          const gchar         *element_name,
                          gpointer             user_data,
                          GError             **error);

  /* Called for character data */
  /* text is not nul-terminated */
  void (*text)           (GMarkupParseContext *context,
                          const gchar         *text,
                          gsize                text_len,
                          gpointer             user_data,
                          GError             **error);

  /* Called for strings that should be re-saved verbatim in this same
   * position, but are not otherwise interpretable.  At the moment
   * this includes comments and processing instructions.
   */
  /* text is not nul-terminated. */
  void (*passthrough)    (GMarkupParseContext *context,
                          const gchar         *passthrough_text,
                          gsize                text_len,
                          gpointer             user_data,
                          GError             **error);

  /* Called on error, including one set by other
   * methods in the vtable. The GError should not be freed.
   */
  void (*error)          (GMarkupParseContext *context,
                          GError              *error,
                          gpointer             user_data);
} GMarkupParser;

Any of the fields in GMarkupParser can be NULL, in which case they will be ignored. Except for the error function, any of these callbacks can set an error; in particular the G_MARKUP_ERROR_UNKNOWN_ELEMENT, G_MARKUP_ERROR_UNKNOWN_ATTRIBUTE, and G_MARKUP_ERROR_INVALID_CONTENT errors are intended to be set from these callbacks. If you set an error from a callback, g_markup_parse_context_parse() will report that error back to its caller.

start_element () | Callback to invoke when the opening tag of an element is seen.
end_element () | Callback to invoke when the closing tag of an element is seen. Note that this is also called for empty tags like <empty/>.
text () | Callback to invoke when some text is seen (text is always inside an element). Note that the text of an element may be spread over multiple calls of this function. If the G_MARKUP_TREAT_CDATA_AS_TEXT flag is set, this function is also called for the content of CDATA marked sections.
passthrough () | Callback to invoke for comments, processing instructions and doctype declarations; if you're re-writing the parsed document, write the passthrough text back out in the same position. If the G_MARKUP_TREAT_CDATA_AS_TEXT flag is not set, this function is also called for CDATA marked sections.
error () | Callback to invoke when an error occurs.

g_markup_escape_text ()

gchar*              g_markup_escape_text                (const gchar *text,
                                                         gssize length);

Escapes text so that the markup parser will parse it verbatim. Less than, greater than, ampersand, etc. are replaced with the corresponding entities. This function would typically be used when writing out a file to be parsed with the markup parser.

Note that this function doesn't protect whitespace and line endings from being processed according to the XML rules for normalization of line endings and attribute values.

text : | some valid UTF-8 text
length : | length of text in bytes, or -1 if the text is nul-terminated
Returns : | a newly allocated string with the escaped text

g_markup_printf_escaped ()

gchar*              g_markup_printf_escaped             (const char *format,
                                                         ...);

Formats arguments according to format, escaping all string and character arguments in the fashion of g_markup_escape_text(). This is useful when you want to insert literal strings into XML-style markup output, without having to worry that the strings might themselves contain markup.

const char *store = "Fortnum & Mason";
const char *item = "Tea";
char *output;

output = g_markup_printf_escaped ("<purchase>"
                                  "<store>%s</store>"
                                  "<item>%s</item>"
                                  "</purchase>",
                                  store, item);

format : | printf() style format string
... : | the arguments to insert in the format string
Returns : | newly allocated result from formatting operation. Free with g_free().

Since 2.4

g_markup_vprintf_escaped ()

gchar*              g_markup_vprintf_escaped            (const char *format,
                                                         va_list args);

Formats the data in args according to format, escaping all string and character arguments in the fashion of g_markup_escape_text(). See g_markup_printf_escaped().

format : | printf() style format string
args : | variable argument list, similar to vprintf()
Returns : | newly allocated result from formatting operation. Free with g_free().

Since 2.4

g_markup_parse_context_end_parse ()

gboolean            g_markup_parse_context_end_parse    (GMarkupParseContext *context,
                                                         GError **error);

Signals to the GMarkupParseContext that all data has been fed into the parse context with g_markup_parse_context_parse(). This function reports an error if the document isn't complete, for example if elements are still open.

context : | a GMarkupParseContext
error : | return location for a GError
Returns : | TRUE on success, FALSE if an error was set

g_markup_parse_context_free ()

void                g_markup_parse_context_free         (GMarkupParseContext *context);

Frees a GMarkupParseContext. Can't be called from inside one of the GMarkupParser functions.

context : a GMarkupParseContext

g_markup_parse_context_get_position ()

void                g_markup_parse_context_get_position (GMarkupParseContext *context,
                                                         gint *line_number,
                                                         gint *char_number);

Retrieves the current line number and the number of the character on that line. Intended for use in error messages; there are no strict semantics for what constitutes the "current" line number other than "the best number we could come up with for error messages."

context : | a GMarkupParseContext
line_number : | return location for a line number, or NULL
char_number : | return location for a char-on-line number, or NULL

g_markup_parse_context_get_element ()

const gchar*        g_markup_parse_context_get_element  (GMarkupParseContext *context);

Retrieves the name of the currently open element.

context : | a GMarkupParseContext
Returns : | the name of the currently open element, or NULL

Since 2.2

g_markup_parse_context_new ()

GMarkupParseContext* g_markup_parse_context_new         (const GMarkupParser *parser,
                                                         GMarkupParseFlags flags,
                                                         gpointer user_data,
                                                         GDestroyNotify user_data_dnotify);

Creates a new parse context. A parse context is used to parse marked-up documents. You can feed any number of documents into a context, as long as no errors occur; once an error occurs, the parse context can't continue to parse text (you have to free it and create a new parse context).

parser : | a GMarkupParser
flags : | one or more GMarkupParseFlags
user_data : | user data to pass to GMarkupParser functions
user_data_dnotify : | user data destroy notifier called when the parse context is freed
Returns : | a new GMarkupParseContext

g_markup_parse_context_parse ()

gboolean            g_markup_parse_context_parse        (GMarkupParseContext *context,
                                                         const gchar *text,
                                                         gssize text_len,
                                                         GError **error);

Feed some data to the GMarkupParseContext. The data need not be valid UTF-8; an error will be signaled if it's invalid. The data need not be an entire document; you can feed a document into the parser incrementally, via multiple calls to this function. Typically, as you receive data from a network connection or file, you feed each received chunk of data into this function, aborting the process if an error occurs. Once an error is reported, no further data may be fed to the GMarkupParseContext; all errors are fatal.

context : | a GMarkupParseContext
text : | chunk of text to parse
text_len : | length of text in bytes
error : | return location for a GError
Returns : | FALSE if an error occurred, TRUE on success

[ 4] XML specification


Singly-Linked Lists

Singly-Linked Lists — linked lists containing integer values or pointers to data, limited to iterating over the list in one direction.

Synopsis

#include <glib.h>

                    GSList;

GSList*             g_slist_alloc                       (void);
GSList*             g_slist_append                      (GSList *list,
                                                         gpointer data);
GSList*             g_slist_prepend                     (GSList *list,
                                                         gpointer data);
GSList*             g_slist_insert                      (GSList *list,
                                                         gpointer data,
                                                         gint position);
GSList*             g_slist_insert_before               (GSList *slist,
                                                         GSList *sibling,
                                                         gpointer data);
GSList*             g_slist_insert_sorted               (GSList *list,
                                                         gpointer data,
                                                         GCompareFunc func);
GSList*             g_slist_remove                      (GSList *list,
                                                         gconstpointer data);
GSList*             g_slist_remove_link                 (GSList *list,
                                                         GSList *link_);
GSList*             g_slist_delete_link                 (GSList *list,
                                                         GSList *link_);
GSList*             g_slist_remove_all                  (GSList *list,
                                                         gconstpointer data);
void                g_slist_free                        (GSList *list);
void                g_slist_free_1                      (GSList *list);
#define             g_slist_free1

guint               g_slist_length                      (GSList *list);
GSList*             g_slist_copy                        (GSList *list);
GSList*             g_slist_reverse                     (GSList *list);
GSList*             g_slist_insert_sorted_with_data     (GSList *list,
                                                         gpointer data,
                                                         GCompareDataFunc func,
                                                         gpointer user_data);
GSList*             g_slist_sort                        (GSList *list,
                                                         GCompareFunc compare_func);
GSList*             g_slist_sort_with_data              (GSList *list,
                                                         GCompareDataFunc compare_func,
                                                         gpointer user_data);
GSList*             g_slist_concat                      (GSList *list1,
                                                         GSList *list2);
void                g_slist_foreach                     (GSList *list,
                                                         GFunc func,
                                                         gpointer user_data);

GSList*             g_slist_last                        (GSList *list);
#define             g_slist_next                        (slist)
GSList*             g_slist_nth                         (GSList *list,
                                                         guint n);
gpointer            g_slist_nth_data                    (GSList *list,
                                                         guint n);

GSList*             g_slist_find                        (GSList *list,
                                                         gconstpointer data);
GSList*             g_slist_find_custom                 (GSList *list,
                                                         gconstpointer data,
                                                         GCompareFunc func);
gint                g_slist_position                    (GSList *list,
                                                         GSList *llink);
gint                g_slist_index                       (GSList *list,
                                                         gconstpointer data);

void                g_slist_push_allocator              (gpointer dummy);
void                g_slist_pop_allocator               (void);

Description

The GSList structure and its associated functions provide a standard singly-linked list data structure.

Each element in the list contains a piece of data, together with a pointer which links to the next element in the list. Using this pointer it is possible to move through the list in one direction only (unlike the Doubly-Linked Lists which allow movement in both directions).

The data contained in each element can be either integer values, by using one of the Type Conversion Macros, or simply pointers to any type of data.

List elements are allocated from the slice allocator, which is more efficient than allocating elements individually.

Note that most of the GSList functions expect to be passed a pointer to the first element in the list. The functions which insert elements return the new start of the list, which may have changed.

There is no function to create a GSList. NULL is considered to be the empty list so you simply set a GSList* to NULL.

To add elements, use g_slist_append(), g_slist_prepend(), g_slist_insert() and g_slist_insert_sorted().

To remove elements, use g_slist_remove().

To find elements in the list use g_slist_last(), g_slist_next(), g_slist_nth(), g_slist_nth_data(), g_slist_find() and g_slist_find_custom().

To find the index of an element use g_slist_position() and g_slist_index().

To call a function for each element in the list use g_slist_foreach().

To free the entire list, use g_slist_free().

Details

GSList

typedef struct {
  gpointer data;
  GSList *next;
} GSList;

The GSList struct is used for each element in the singly-linked list.

gpointer data; | holds the element's data, which can be a pointer to any kind of data, or any integer value using the Type Conversion Macros.
GSList *next; | contains the link to the next element in the list.

g_slist_alloc ()

GSList*             g_slist_alloc                       (void);

Allocates space for one GSList element. It is called by the g_slist_append(), g_slist_prepend(), g_slist_insert() and g_slist_insert_sorted() functions and so is rarely used on its own.

Returns : a pointer to the newly-allocated GSList element.

g_slist_append ()

GSList*             g_slist_append                      (GSList *list,
                                                         gpointer data);

Adds a new element on to the end of the list.

Note

The return value is the new start of the list, which may have changed, so make sure you store the new value.

Note

Note that g_slist_append() has to traverse the entire list to find the end, which is inefficient when adding multiple elements. A common idiom to avoid the inefficiency is to prepend the elements and reverse the list when all elements have been added.

  /* Notice that these are initialized to the empty list. */
  GSList *list = NULL, *number_list = NULL;

  /* This is a list of strings. */
  list = g_slist_append (list, "first");
  list = g_slist_append (list, "second");

  /* This is a list of integers. */
  number_list = g_slist_append (number_list, GINT_TO_POINTER (27));
  number_list = g_slist_append (number_list, GINT_TO_POINTER (14));

list : | a GSList.
data : | the data for the new element.
Returns : | the new start of the GSList.

g_slist_prepend ()

GSList*             g_slist_prepend                     (GSList *list,
                                                         gpointer data);

Adds a new element on to the start of the list.

Note

The return value is the new start of the list, which may have changed, so make sure you store the new value.

  /* Notice that it is initialized to the empty list. */
  GSList *list = NULL;
  list = g_slist_prepend (list, "last");
  list = g_slist_prepend (list, "first");

list : | a GSList.
data : | the data for the new element.
Returns : | the new start of the GSList.

g_slist_insert ()

GSList*             g_slist_insert                      (GSList *list,
                                                         gpointer data,
                                                         gint position);

Inserts a new element into the list at the given position.

list : | a GSList.
data : | the data for the new element.
position : | the position to insert the element. If this is negative, or is larger than the number of elements in the list, the new element is added on to the end of the list.
Returns : | the new start of the GSList.

g_slist_insert_before ()

GSList*             g_slist_insert_before               (GSList *slist,
                                                         GSList *sibling,
                                                         gpointer data);

Inserts a node before sibling containing data. Returns the new head of the list.

slist : | a GSList.
sibling : | node to insert data before.
data : | data to put in the newly-inserted node.
Returns : | new head of the list.

g_slist_insert_sorted ()

GSList*             g_slist_insert_sorted               (GSList *list,
                                                         gpointer data,
                                                         GCompareFunc func);

Inserts a new element into the list, using the given comparison function to determine its position.

list : | a GSList.
data : | the data for the new element.
func : | the function to compare elements in the list. It should return a number > 0 if the first parameter comes after the second parameter in the sort order.
Returns : | the new start of the GSList.

g_slist_remove ()

GSList*             g_slist_remove                      (GSList *list,
                                                         gconstpointer data);

Removes an element from a GSList. If two elements contain the same data, only the first is removed. If none of the elements contain the data, the GSList is unchanged.

list : | a GSList.
data : | the data of the element to remove.
Returns : | the new start of the GSList.

g_slist_remove_link ()

GSList*             g_slist_remove_link                 (GSList *list,
                                                         GSList *link_);

Removes an element from a GSList, without freeing the element. The removed element's next link is set to NULL, so that it becomes a self-contained list with one element.

list : | a GSList.
link_ : | an element in the GSList.
Returns : | the new start of the GSList, without the element.

g_slist_delete_link ()

GSList*             g_slist_delete_link                 (GSList *list,
                                                         GSList *link_);

Deletes a node of list. Returns the new list head.

list : | a GSList.
link_ : | node to delete.
Returns : | new head of list.

g_slist_remove_all ()

GSList*             g_slist_remove_all                  (GSList *list,
                                                         gconstpointer data);

Removes all list nodes with data equal to data. Returns the new head of the list. Contrast with g_slist_remove() which removes only the first node matching the given data.

list : | a GSList.
data : | data to remove.
Returns : | new head of list.

g_slist_free ()

void                g_slist_free                        (GSList *list);

Frees all of the memory used by a GSList. The freed elements are returned to the slice allocator.

list : a GSList.

g_slist_free_1 ()

void                g_slist_free_1                      (GSList *list);

Frees one GSList element. It is usually used after g_slist_remove_link().

list : a GSList element.

g_slist_free1

#define             g_slist_free1

A macro which does the same as g_slist_free_1().

Since 2.10

g_slist_length ()

guint               g_slist_length                      (GSList *list);

Gets the number of elements in a GSList.

list : | a GSList.
Returns : | the number of elements in the GSList.

g_slist_copy ()

GSList*             g_slist_copy                        (GSList *list);

Copies a GSList.

Note that this is a "shallow" copy. If the list elements consist of pointers to data, the pointers are copied but the actual data isn't.

list : | a GSList.
Returns : | a copy of list.

g_slist_reverse ()

GSList*             g_slist_reverse                     (GSList *list);

Reverses a GSList.

list : | a GSList.
Returns : | the start of the reversed GSList.

g_slist_insert_sorted_with_data ()

GSList*             g_slist_insert_sorted_with_data     (GSList *list,
                                                         gpointer data,
                                                         GCompareDataFunc func,
                                                         gpointer user_data);

Inserts a new element into the list, using the given comparison function to determine its position.

list : | a GSList.
data : | the data for the new element.
func : | the function to compare elements in the list. It should return a number > 0 if the first parameter comes after the second parameter in the sort order.
user_data : | data to pass to comparison function.
Returns : | the new start of the GSList. Since 2.10

g_slist_sort ()

GSList*             g_slist_sort                        (GSList *list,
                                                         GCompareFunc compare_func);

Sorts a GSList using the given comparison function.

list : | a GSList.
compare_func : | the comparison function used to sort the GSList. This function is passed the data from 2 elements of the GSList and should return 0 if they are equal, a negative value if the first element comes before the second, or a positive value if the first element comes after the second.
Returns : | the start of the sorted GSList.

g_slist_sort_with_data ()

GSList*             g_slist_sort_with_data              (GSList *list,
                                                         GCompareDataFunc compare_func,
                                                         gpointer user_data);

Like g_slist_sort(), but the sort function accepts a user data argument.

list : | a GSList
compare_func : | comparison function.
user_data : | data to pass to comparison function.
Returns : | new head of the list.

g_slist_concat ()

GSList*             g_slist_concat                      (GSList *list1,
                                                         GSList *list2);

Adds the second GSList onto the end of the first GSList. Note that the elements of the second GSList are not copied. They are used directly.

list1 : | a GSList.
list2 : | the GSList to add to the end of the first GSList.
Returns : | the start of the new GSList.

g_slist_foreach ()

void                g_slist_foreach                     (GSList *list,
                                                         GFunc func,
                                                         gpointer user_data);

Calls a function for each element of a GSList.

list : | a GSList.
func : | the function to call with each element's data.
user_data : | user data to pass to the function.

g_slist_last ()

GSList*             g_slist_last                        (GSList *list);

Gets the last element in a GSList.

list : | a GSList.
Returns : | the last element in the GSList, or NULL if the GSList has no elements.

g_slist_next()

#define             g_slist_next(slist)

A convenience macro to gets the next element in a GSList.

slist : | an element in a GSList.
Returns : | the next element, or NULL if there are no more elements.

g_slist_nth ()

GSList*             g_slist_nth                         (GSList *list,
                                                         guint n);

Gets the element at the given position in a GSList.

list : | a GSList.
n : | the position of the element, counting from 0.
Returns : | the element, or NULL if the position is off the end of the GSList.

g_slist_nth_data ()

gpointer            g_slist_nth_data                    (GSList *list,
                                                         guint n);

Gets the data of the element at the given position.

list : | a GSList.
n : | the position of the element.
Returns : | the element's data, or NULL if the position is off the end of the GSList.

g_slist_find ()

GSList*             g_slist_find                        (GSList *list,
                                                         gconstpointer data);

Finds the element in a GSList which contains the given data.

list : | a GSList.
data : | the element data to find.
Returns : | the found GSList element, or NULL if it is not found.

g_slist_find_custom ()

GSList*             g_slist_find_custom                 (GSList *list,
                                                         gconstpointer data,
                                                         GCompareFunc func);

Finds an element in a GSList, using a supplied function to find the desired element. It iterates over the list, calling the given function which should return 0 when the desired element is found. The function takes two gconstpointer arguments, the GSList element's data as the first argument and the given user data.

list : | a GSList.
data : | user data passed to the function.
func : | the function to call for each element. It should return 0 when the desired element is found.
Returns : | the found GSList element, or NULL if it is not found.

g_slist_position ()

gint                g_slist_position                    (GSList *list,
                                                         GSList *llink);

Gets the position of the given element in the GSList (starting from 0).

list : | a GSList.
llink : | an element in the GSList.
Returns : | the position of the element in the GSList, or -1 if the element is not found.

g_slist_index ()

gint                g_slist_index                       (GSList *list,
                                                         gconstpointer data);

Gets the position of the element containing the given data (starting from 0).

list : | a GSList.
data : | the data to find.
Returns : | the index of the element containing the data, or -1 if the data is not found.

g_slist_push_allocator ()

void                g_slist_push_allocator              (gpointer dummy);

Warning

g_slist_push_allocator has been deprecated since version 2.10 and should not be used in newly-written code. It does nothing, since GSList has been converted to the slice allocator

Sets the allocator to use to allocate GSList elements. Use g_slist_pop_allocator() to restore the previous allocator.

Note that this function is not available if GLib has been compiled with --disable-mem-pools

dummy : the GAllocator to use when allocating GSList elements.

g_slist_pop_allocator ()

void                g_slist_pop_allocator               (void);

Warning

g_slist_pop_allocator has been deprecated since version 2.10 and should not be used in newly-written code. It does nothing, since GSList has been converted to the slice allocator

Restores the previous GAllocator, used when allocating GSList elements.

Note that this function is not available if GLib has been compiled with --disable-mem-pools


Spawning Processes

Spawning Processes — process launching with fork()/exec().

Synopsis

#include <glib.h>

enum                GSpawnError;
#define             G_SPAWN_ERROR
enum                GSpawnFlags;
void                (*GSpawnChildSetupFunc)             (gpointer user_data);
gboolean            g_spawn_async_with_pipes            (const gchar *working_directory,
                                                         gchar **argv,
                                                         gchar **envp,
                                                         GSpawnFlags flags,
                                                         GSpawnChildSetupFunc child_setup,
                                                         gpointer user_data,
                                                         GPid *child_pid,
                                                         gint *standard_input,
                                                         gint *standard_output,
                                                         gint *standard_error,
                                                         GError **error);
gboolean            g_spawn_async                       (const gchar *working_directory,
                                                         gchar **argv,
                                                         gchar **envp,
                                                         GSpawnFlags flags,
                                                         GSpawnChildSetupFunc child_setup,
                                                         gpointer user_data,
                                                         GPid *child_pid,
                                                         GError **error);
gboolean            g_spawn_sync                        (const gchar *working_directory,
                                                         gchar **argv,
                                                         gchar **envp,
                                                         GSpawnFlags flags,
                                                         GSpawnChildSetupFunc child_setup,
                                                         gpointer user_data,
                                                         gchar **standard_output,
                                                         gchar **standard_error,
                                                         gint *exit_status,
                                                         GError **error);
gboolean            g_spawn_command_line_async          (const gchar *command_line,
                                                         GError **error);
gboolean            g_spawn_command_line_sync           (const gchar *command_line,
                                                         gchar **standard_output,
                                                         gchar **standard_error,
                                                         gint *exit_status,
                                                         GError **error);
void                g_spawn_close_pid                   (GPid pid);

Description

Details

enum GSpawnError

typedef enum
{
  G_SPAWN_ERROR_FORK,   /* fork failed due to lack of memory */
  G_SPAWN_ERROR_READ,   /* read or select on pipes failed */
  G_SPAWN_ERROR_CHDIR,  /* changing to working dir failed */
  G_SPAWN_ERROR_ACCES,  /* execv() returned EACCES */
  G_SPAWN_ERROR_PERM,   /* execv() returned EPERM */
  G_SPAWN_ERROR_2BIG,   /* execv() returned E2BIG */
  G_SPAWN_ERROR_NOEXEC, /* execv() returned ENOEXEC */
  G_SPAWN_ERROR_NAMETOOLONG, /* ""  "" ENAMETOOLONG */
  G_SPAWN_ERROR_NOENT,       /* ""  "" ENOENT */
  G_SPAWN_ERROR_NOMEM,       /* ""  "" ENOMEM */
  G_SPAWN_ERROR_NOTDIR,      /* ""  "" ENOTDIR */
  G_SPAWN_ERROR_LOOP,        /* ""  "" ELOOP   */
  G_SPAWN_ERROR_TXTBUSY,     /* ""  "" ETXTBUSY */
  G_SPAWN_ERROR_IO,          /* ""  "" EIO */
  G_SPAWN_ERROR_NFILE,       /* ""  "" ENFILE */
  G_SPAWN_ERROR_MFILE,       /* ""  "" EMFLE */
  G_SPAWN_ERROR_INVAL,       /* ""  "" EINVAL */
  G_SPAWN_ERROR_ISDIR,       /* ""  "" EISDIR */
  G_SPAWN_ERROR_LIBBAD,      /* ""  "" ELIBBAD */
  G_SPAWN_ERROR_FAILED       /* other fatal failure, error->message
                              * should explain
                              */
} GSpawnError;

Error codes returned by spawning processes.

G_SPAWN_ERROR_FORK | Fork failed due to lack of memory.
G_SPAWN_ERROR_READ | Read or select on pipes failed.
G_SPAWN_ERROR_CHDIR | Changing to working directory failed.
G_SPAWN_ERROR_ACCES | execv() returned EACCES.
G_SPAWN_ERROR_PERM | execv() returned EPERM.
G_SPAWN_ERROR_2BIG | execv() returned E2BIG.
G_SPAWN_ERROR_NOEXEC | execv() returned ENOEXEC.
G_SPAWN_ERROR_NAMETOOLONG | execv() returned ENAMETOOLONG.
G_SPAWN_ERROR_NOENT | execv() returned ENOENT.
G_SPAWN_ERROR_NOMEM | execv() returned ENOMEM.
G_SPAWN_ERROR_NOTDIR | execv() returned ENOTDIR.
G_SPAWN_ERROR_LOOP | execv() returned ELOOP.
G_SPAWN_ERROR_TXTBUSY | execv() returned ETXTBUSY.
G_SPAWN_ERROR_IO | execv() returned EIO.
G_SPAWN_ERROR_NFILE | execv() returned ENFILE.
G_SPAWN_ERROR_MFILE | execv() returned EMFILE.
G_SPAWN_ERROR_INVAL | execv() returned EINVAL.
G_SPAWN_ERROR_ISDIR | execv() returned EISDIR.
G_SPAWN_ERROR_LIBBAD | execv() returned ELIBBAD.
G_SPAWN_ERROR_FAILED | Some other fatal failure, error->message should explain.

G_SPAWN_ERROR

#define G_SPAWN_ERROR g_spawn_error_quark ()

Error domain for spawning processes. Errors in this domain will be from the GSpawnError enumeration. See GError for information on error domains.

enum GSpawnFlags

typedef enum
{
  G_SPAWN_LEAVE_DESCRIPTORS_OPEN = 1 << 0,
  G_SPAWN_DO_NOT_REAP_CHILD      = 1 << 1,
  /* look for argv[0] in the path i.e. use execvp() */
  G_SPAWN_SEARCH_PATH            = 1 << 2,
  /* Dump output to /dev/null */
  G_SPAWN_STDOUT_TO_DEV_NULL     = 1 << 3,
  G_SPAWN_STDERR_TO_DEV_NULL     = 1 << 4,
  G_SPAWN_CHILD_INHERITS_STDIN   = 1 << 5,
  G_SPAWN_FILE_AND_ARGV_ZERO     = 1 << 6
} GSpawnFlags;

Flags passed to g_spawn_sync(), g_spawn_async() and g_spawn_async_with_pipes().

G_SPAWN_LEAVE_DESCRIPTORS_OPEN | the parent's open file descriptors will be inherited by the child; otherwise all descriptors except stdin/stdout/stderr will be closed before calling exec() in the child.
G_SPAWN_DO_NOT_REAP_CHILD | the child will not be automatically reaped; you must call waitpid() or handle SIGCHLD yourself, or the child will become a zombie.
G_SPAWN_SEARCH_PATH | argv[0] need not be an absolute path, it will be looked for in the user's PATH.
G_SPAWN_STDOUT_TO_DEV_NULL | the child's standad output will be discarded, instead of going to the same location as the parent's standard output.
G_SPAWN_STDERR_TO_DEV_NULL | the child's standard error will be discarded.
G_SPAWN_CHILD_INHERITS_STDIN | the child will inherit the parent's standard input (by default, the child's standard input is attached to /dev/null).
G_SPAWN_FILE_AND_ARGV_ZERO | the first element of argv is the file to execute, while the remaining elements are the actual argument vector to pass to the file. Normally g_spawn_async_with_pipes() uses argv[0] as the file to execute, and passes all of argv to the child.

GSpawnChildSetupFunc ()

void                (*GSpawnChildSetupFunc)             (gpointer user_data);

Specifies the type of the setup function passed to g_spawn_async(), g_spawn_sync() and g_spawn_async_with_pipes(). On POSIX platforms it is called in the child after GLib has performed all the setup it plans to perform but before calling exec(). On POSIX actions taken in this function will thus only affect the child, not the parent.

On Windows the function is called in the parent. Its usefulness on Windows is thus questionable. In many cases executing the child setup function in the parent can have ill effects, and you should be very careful when porting software to Windows that uses child setup functions.

user_data : user data to pass to the function.

g_spawn_async_with_pipes ()

gboolean            g_spawn_async_with_pipes            (const gchar *working_directory,
                                                         gchar **argv,
                                                         gchar **envp,
                                                         GSpawnFlags flags,
                                                         GSpawnChildSetupFunc child_setup,
                                                         gpointer user_data,
                                                         GPid *child_pid,
                                                         gint *standard_input,
                                                         gint *standard_output,
                                                         gint *standard_error,
                                                         GError **error);

Executes a child program asynchronously (your program will not block waiting for the child to exit). The child program is specified by the only argument that must be provided, argv. argv should be a NULL-terminated array of strings, to be passed as the argument vector for the child. The first string in argv is of course the name of the program to execute. By default, the name of the program must be a full path; the PATH shell variable will only be searched if you pass the G_SPAWN_SEARCH_PATH flag.

On Windows, note that all the string or string vector arguments to this function and the other g_spawn*() functions are in UTF-8, the GLib file name encoding. Unicode characters that are not part of the system codepage passed in argument vectors will be correctly available in the spawned program only if it uses wide character API to retrieve its command line. For C programs built with Microsoft's tools it is enough to make the program have a wmain() instead of main(). wmain() has a wide character argument vector as parameter.

At least currently, mingw doesn't support wmain(), so if you use mingw to develop the spawned program, it will have to call the undocumented function __wgetmainargs() to get the wide character argument vector and environment. See gspawn-win32-helper.c in the GLib sources or init.c in the mingw runtime sources for a prototype for that function. Alternatively, you can retrieve the Win32 system level wide character command line passed to the spawned program using the GetCommandLineW() function.

On Windows the low-level child process creation API CreateProcess() doesn't use argument vectors, but a command line. The C runtime library's spawn*() family of functions (which g_spawn_async_with_pipes() eventually calls) paste the argument vector elements together into a command line, and the C runtime startup code does a corresponding reconstruction of an argument vector from the command line, to be passed to main(). Complications arise when you have argument vector elements that contain spaces of double quotes. The spawn*() functions don't do any quoting or escaping, but on the other hand the startup code does do unquoting and unescaping in order to enable receiving arguments with embedded spaces or double quotes. To work around this asymmetry, g_spawn_async_with_pipes() will do quoting and escaping on argument vector elements that need it before calling the C runtime spawn() function.

envp is a NULL-terminated array of strings, where each string has the form KEY=VALUE. This will become the child's environment. If envp is NULL, the child inherits its parent's environment.

flags should be the bitwise OR of any flags you want to affect the function's behaviour. The G_SPAWN_DO_NOT_REAP_CHILD means that the child will not automatically be reaped; you must use a GChildWatch source to be notified about the death of the child process. Eventually you must call g_spawn_close_pid() on the child_pid, in order to free resources which may be associated with the child process. (On Unix, using a GChildWatch source is equivalent to calling waitpid() or handling the SIGCHLD signal manually. On Windows, calling g_spawn_close_pid() is equivalent to calling CloseHandle() on the process handle returned in child_pid).

G_SPAWN_LEAVE_DESCRIPTORS_OPEN means that the parent's open file descriptors will be inherited by the child; otherwise all descriptors except stdin/stdout/stderr will be closed before calling exec() in the child. G_SPAWN_SEARCH_PATH means that argv[0] need not be an absolute path, it will be looked for in the user's PATH. G_SPAWN_STDOUT_TO_DEV_NULL means that the child's standard output will be discarded, instead of going to the same location as the parent's standard output. If you use this flag, standard_output must be NULL. G_SPAWN_STDERR_TO_DEV_NULL means that the child's standard error will be discarded, instead of going to the same location as the parent's standard error. If you use this flag, standard_error must be NULL. G_SPAWN_CHILD_INHERITS_STDIN means that the child will inherit the parent's standard input (by default, the child's standard input is attached to /dev/null). If you use this flag, standard_input must be NULL. G_SPAWN_FILE_AND_ARGV_ZERO means that the first element of argv is the file to execute, while the remaining elements are the actual argument vector to pass to the file. Normally g_spawn_async_with_pipes() uses argv[0] as the file to execute, and passes all of argv to the child.

child_setup and user_data are a function and user data. On POSIX platforms, the function is called in the child after GLib has performed all the setup it plans to perform (including creating pipes, closing file descriptors, etc.) but before calling exec(). That is, child_setup is called just before calling exec() in the child. Obviously actions taken in this function will only affect the child, not the parent. On Windows, there is no separate fork() and exec() functionality. Child processes are created and run with a single API call, CreateProcess(). child_setup is called in the parent process just before creating the child process. You should carefully consider what you do in child_setup if you intend your software to be portable to Windows.

If non-NULL, child_pid will on Unix be filled with the child's process ID. You can use the process ID to send signals to the child, or to waitpid() if you specified the G_SPAWN_DO_NOT_REAP_CHILD flag. On Windows, child_pid will be filled with a handle to the child process only if you specified the G_SPAWN_DO_NOT_REAP_CHILD flag. You can then access the child process using the Win32 API, for example wait for its termination with the WaitFor*() functions, or examine its exit code with GetExitCodeProcess(). You should close the handle with CloseHandle() or g_spawn_close_pid() when you no longer need it.

If non-NULL, the standard_input, standard_output, standard_error locations will be filled with file descriptors for writing to the child's standard input or reading from its standard output or standard error. The caller of g_spawn_async_with_pipes() must close these file descriptors when they are no longer in use. If these parameters are NULL, the corresponding pipe won't be created.

If standard_input is NULL, the child's standard input is attached to /dev/null unless G_SPAWN_CHILD_INHERITS_STDIN is set.

If standard_error is NULL, the child's standard error goes to the same location as the parent's standard error unless G_SPAWN_STDERR_TO_DEV_NULL is set.

If standard_output is NULL, the child's standard output goes to the same location as the parent's standard output unless G_SPAWN_STDOUT_TO_DEV_NULL is set.

error can be NULL to ignore errors, or non-NULL to report errors. If an error is set, the function returns FALSE. Errors are reported even if they occur in the child (for example if the executable in argv[0] is not found). Typically the message field of returned errors should be displayed to users. Possible errors are those from the G_SPAWN_ERROR domain.

If an error occurs, child_pid, standard_input, standard_output, and standard_error will not be filled with valid values.

If child_pid is not NULL and an error does not occur then the returned pid must be closed using g_spawn_close_pid().

working_directory : | child's current working directory, or NULL to inherit parent's, in the GLib file name encoding
argv : | child's argument vector, in the GLib file name encoding
envp : | child's environment, or NULL to inherit parent's, in the GLib file name encoding
flags : | flags from GSpawnFlags
child_setup : | function to run in the child just before exec()
user_data : | user data for child_setup
child_pid : | return location for child process ID, or NULL
standard_input : | return location for file descriptor to write to child's stdin, or NULL
standard_output : | return location for file descriptor to read child's stdout, or NULL
standard_error : | return location for file descriptor to read child's stderr, or NULL
error : | return location for error
Returns : | TRUE on success, FALSE if an error was set

g_spawn_async ()

gboolean            g_spawn_async                       (const gchar *working_directory,
                                                         gchar **argv,
                                                         gchar **envp,
                                                         GSpawnFlags flags,
                                                         GSpawnChildSetupFunc child_setup,
                                                         gpointer user_data,
                                                         GPid *child_pid,
                                                         GError **error);

See g_spawn_async_with_pipes() for a full description; this function simply calls the g_spawn_async_with_pipes() without any pipes.

working_directory : | child's current working directory, or NULL to inherit parent's
argv : | child's argument vector
envp : | child's environment, or NULL to inherit parent's
flags : | flags from GSpawnFlags
child_setup : | function to run in the child just before exec()
user_data : | user data for child_setup
child_pid : | return location for child process ID, or NULL
error : | return location for error
Returns : | TRUE on success, FALSE if error is set

g_spawn_sync ()

gboolean            g_spawn_sync                        (const gchar *working_directory,
                                                         gchar **argv,
                                                         gchar **envp,
                                                         GSpawnFlags flags,
                                                         GSpawnChildSetupFunc child_setup,
                                                         gpointer user_data,
                                                         gchar **standard_output,
                                                         gchar **standard_error,
                                                         gint *exit_status,
                                                         GError **error);

Executes a child synchronously (waits for the child to exit before returning). All output from the child is stored in standard_output and standard_error, if those parameters are non-NULL. If exit_status is non-NULL, the exit status of the child is stored there as it would be returned by waitpid(); standard UNIX macros such as WIFEXITED() and WEXITSTATUS() must be used to evaluate the exit status. If an error occurs, no data is returned in standard_output, standard_error, or exit_status.

This function calls g_spawn_async_with_pipes() internally; see that function for full details on the other parameters and details on how these functions work on Windows.

working_directory : | child's current working directory, or NULL to inherit parent's
argv : | child's argument vector
envp : | child's environment, or NULL to inherit parent's
flags : | flags from GSpawnFlags
child_setup : | function to run in the child just before exec()
user_data : | user data for child_setup
standard_output : | return location for child output
standard_error : | return location for child error messages
exit_status : | return location for child exit status, as returned by waitpid()
error : | return location for error
Returns : | TRUE on success, FALSE if an error was set.

g_spawn_command_line_async ()

gboolean            g_spawn_command_line_async          (const gchar *command_line,
                                                         GError **error);

A simple version of g_spawn_async() that parses a command line with g_shell_parse_argv() and passes it to g_spawn_async(). Runs a command line in the background. Unlike g_spawn_async(), the G_SPAWN_SEARCH_PATH flag is enabled, other flags are not. Note that G_SPAWN_SEARCH_PATH can have security implications, so consider using g_spawn_async() directly if appropriate. Possible errors are those from g_shell_parse_argv() and g_spawn_async().

The same concerns on Windows apply as for g_spawn_command_line_sync().

command_line : | a command line
error : | return location for errors
Returns : | TRUE on success, FALSE if error is set.

g_spawn_command_line_sync ()

gboolean            g_spawn_command_line_sync           (const gchar *command_line,
                                                         gchar **standard_output,
                                                         gchar **standard_error,
                                                         gint *exit_status,
                                                         GError **error);

A simple version of g_spawn_sync() with little-used parameters removed, taking a command line instead of an argument vector. See g_spawn_sync() for full details. command_line will be parsed by g_shell_parse_argv(). Unlike g_spawn_sync(), the G_SPAWN_SEARCH_PATH flag is enabled. Note that G_SPAWN_SEARCH_PATH can have security implications, so consider using g_spawn_sync() directly if appropriate. Possible errors are those from g_spawn_sync() and those from g_shell_parse_argv().

If exit_status is non-NULL, the exit status of the child is stored there as it would be returned by waitpid(); standard UNIX macros such as WIFEXITED() and WEXITSTATUS() must be used to evaluate the exit status.

On Windows, please note the implications of g_shell_parse_argv() parsing command_line. Parsing is done according to Unix shell rules, not Windows command interpreter rules. Space is a separator, and backslashes are special. Thus you cannot simply pass a command_line containing canonical Windows paths, like "c:\\program files\\app\\app.exe", as the backslashes will be eaten, and the space will act as a separator. You need to enclose such paths with single quotes, like "'c:\\program files\\app\\app.exe' 'e:\\folder\\argument.txt'".

command_line : | a command line
standard_output : | return location for child output
standard_error : | return location for child errors
exit_status : | return location for child exit status, as returned by waitpid()
error : | return location for errors
Returns : | TRUE on success, FALSE if an error was set

g_spawn_close_pid ()

void                g_spawn_close_pid                   (GPid pid);

On some platforms, notably WIN32, the GPid type represents a resource which must be closed to prevent resource leaking. g_spawn_close_pid() is provided for this purpose. It should be used on all platforms, even though it doesn't do anything under UNIX.

pid : The process identifier to close


Standard Macros

Standard Macros — commonly-used macros.

Synopsis

#include <glib.h>

#define             G_OS_WIN32
#define             G_OS_BEOS
#define             G_OS_UNIX

#define             G_DIR_SEPARATOR
#define             G_DIR_SEPARATOR_S
#define             G_IS_DIR_SEPARATOR                  (c)
#define             G_SEARCHPATH_SEPARATOR
#define             G_SEARCHPATH_SEPARATOR_S

#define             TRUE
#define             FALSE

#define             NULL

#define             MIN                                 (a, b)
#define             MAX                                 (a, b)

#define             ABS                                 (a)
#define             CLAMP                               (x, low, high)

#define             G_STRUCT_MEMBER                     (member_type, struct_p, struct_offset)
#define             G_STRUCT_MEMBER_P                   (struct_p, struct_offset)
#define             G_STRUCT_OFFSET                     (struct_type, member)

#define             G_MEM_ALIGN

#define             G_CONST_RETURN

Description

These macros provide a few commonly-used features.

Details

G_OS_WIN32

#define G_OS_WIN32

This macro is defined only on Windows. So you can bracket Windows-specific code in "#ifdef G_OS_WIN32".

G_OS_BEOS

#define G_OS_BEOS

This macro is defined only on BeOS. So you can bracket BeOS-specific code in "#ifdef G_OS_BEOS".

G_OS_UNIX

#define G_OS_UNIX

This macro is defined only on UNIX. So you can bracket UNIX-specific code in "#ifdef G_OS_UNIX".

G_DIR_SEPARATOR

#define             G_DIR_SEPARATOR

The directory separator character. This is '/' on UNIX machines and '\' under Windows.

G_DIR_SEPARATOR_S

#define             G_DIR_SEPARATOR_S

The directory separator as a string. This is "/" on UNIX machines and "\" under Windows.

G_IS_DIR_SEPARATOR()

#define             G_IS_DIR_SEPARATOR(c)

Checks whether a character is a directory separator. It returns TRUE for '/' on UNIX machines and for '\' or '/' under Windows.

c : a character

Since 2.6

G_SEARCHPATH_SEPARATOR

#define             G_SEARCHPATH_SEPARATOR

The search path separator character. This is ':' on UNIX machines and ';' under Windows.

G_SEARCHPATH_SEPARATOR_S

#define             G_SEARCHPATH_SEPARATOR_S

The search path separator as a string. This is ":" on UNIX machines and ";" under Windows.

TRUE

#define	TRUE	(!FALSE)

Defines the TRUE value for the gboolean type.

FALSE

#define	FALSE	(0)

Defines the FALSE value for the gboolean type.

NULL

#define             NULL

Defines the standard NULL pointer.

MIN()

#define MIN(a, b)  (((a) < (b)) ? (a) : (b))

Calculates the minimum of a and b.

a : | a numeric value.
b : | a numeric value.
Returns : | the minimum of a and b.

MAX()

#define MAX(a, b)  (((a) > (b)) ? (a) : (b))

Calculates the maximum of a and b.

a : | a numeric value.
b : | a numeric value.
Returns : | the maximum of a and b.

ABS()

#define ABS(a)	   (((a) < 0) ? -(a) : (a))

Calculates the absolute value of a. The absolute value is simply the number with any negative sign taken away.

For example,

  • ABS(-10) is 10.

  • ABS(10) is also 10.

a : | a numeric value.
Returns : | the absolute value of a.

CLAMP()

#define CLAMP(x, low, high)  (((x) > (high)) ? (high) : (((x) < (low)) ? (low) : (x)))

Ensures that x is between the limits set by low and high.

For example,

  • CLAMP(5, 10, 15) is 10.

  • CLAMP(15, 5, 10) is 10.

  • CLAMP(20, 15, 25) is 20.

x : | the value to clamp.
low : | the minimum value allowed.
high : | the maximum value allowed.
Returns : | the value of x clamped to the range between low and high.

G_STRUCT_MEMBER()

#define             G_STRUCT_MEMBER(member_type, struct_p, struct_offset)

Returns a member of a structure at a given offset, using the given type.

member_type : | the type of the struct field.
struct_p : | a pointer to a struct.
struct_offset : | the offset of the field from the start of the struct, in bytes.
Returns : | the struct member.

G_STRUCT_MEMBER_P()

#define             G_STRUCT_MEMBER_P(struct_p, struct_offset)

Returns an untyped pointer to a given offset of a struct.

struct_p : | a pointer to a struct.
struct_offset : | the offset from the start of the struct, in bytes.
Returns : | an untyped pointer to struct_p plus struct_offset bytes.

G_STRUCT_OFFSET()

#define             G_STRUCT_OFFSET(struct_type, member)

Returns the offset, in bytes, of a member of a struct.

struct_type : | a structure type, e.g. GtkWidget.
member : | a field in the structure, e.g. window.
Returns : | the offset of member from the start of struct_type.

G_MEM_ALIGN

#define             G_MEM_ALIGN

Indicates the number of bytes to which memory will be aligned on the current platform.

G_CONST_RETURN

#define             G_CONST_RETURN

If G_DISABLE_CONST_RETURNS is defined, this macro expands to nothing. By default, the macro expands to const. The macro should be used in place of const for functions that return a value that should not be modified. The purpose of this macro is to allow us to turn on const for returned constant strings by default, while allowing programmers who find that annoying to turn it off. This macro should only be used for return values and for out parameters, it doesn't make sense for in parameters.


String Chunks

String Chunks — efficient storage of groups of strings.

Synopsis

#include <glib.h>

                    GStringChunk;
GStringChunk*       g_string_chunk_new                  (gsize size);
gchar*              g_string_chunk_insert               (GStringChunk *chunk,
                                                         const gchar *string);
gchar*              g_string_chunk_insert_const         (GStringChunk *chunk,
                                                         const gchar *string);
gchar*              g_string_chunk_insert_len           (GStringChunk *chunk,
                                                         const gchar *string,
                                                         gssize len);
void                g_string_chunk_free                 (GStringChunk *chunk);

Description

String chunks are used to store groups of strings. Memory is allocated in blocks, and as strings are added to the GStringChunk they are copied into the next free position in a block. When a block is full a new block is allocated.

When storing a large number of strings, string chunks are more efficient than using g_strdup() since fewer calls to malloc() are needed, and less memory is wasted in memory allocation overheads.

By adding strings with g_string_chunk_insert_const() it is also possible to remove duplicates.

To create a new GStringChunk use g_string_chunk_new().

To add strings to a GStringChunk use g_string_chunk_insert().

To add strings to a GStringChunk, but without duplicating strings which are already in the GStringChunk, use g_string_chunk_insert_const().

To free the entire GStringChunk use g_string_chunk_free(). It is not possible to free individual strings.

Details

GStringChunk

typedef struct _GStringChunk GStringChunk;

An opaque data structure representing String Chunks. It should only be accessed by using the following functions.

g_string_chunk_new ()

GStringChunk*       g_string_chunk_new                  (gsize size);

Creates a new GStringChunk.

size : | the default size of the blocks of memory which are allocated to store the strings. If a particular string is larger than this default size, a larger block of memory will be allocated for it.
Returns : | a new GStringChunk.

g_string_chunk_insert ()

gchar*              g_string_chunk_insert               (GStringChunk *chunk,
                                                         const gchar *string);

Adds a copy of string to the GStringChunk. It returns a pointer to the new copy of the string in the GStringChunk. The characters in the string can be changed, if necessary, though you should not change anything after the end of the string.

Unlike g_string_chunk_insert_const(), this function does not check for duplicates. Also strings added with g_string_chunk_insert() will not be searched by g_string_chunk_insert_const() when looking for duplicates.

chunk : | a GStringChunk.
string : | the string to add.
Returns : | a pointer to the copy of string within the GStringChunk.

g_string_chunk_insert_const ()

gchar*              g_string_chunk_insert_const         (GStringChunk *chunk,
                                                         const gchar *string);

Adds a copy of string to the GStringChunk, unless the same string has already been added to the GStringChunk with g_string_chunk_insert_const().

This function is useful if you need to copy a large number of strings but do not want to waste space storing duplicates. But you must remember that there may be several pointers to the same string, and so any changes made to the strings should be done very carefully.

Note that g_string_chunk_insert_const() will not return a pointer to a string added with g_string_chunk_insert(), even if they do match.

chunk : | a GStringChunk.
string : | the string to add.
Returns : | a pointer to the new or existing copy of string within the GStringChunk.

g_string_chunk_insert_len ()

gchar*              g_string_chunk_insert_len           (GStringChunk *chunk,
                                                         const gchar *string,
                                                         gssize len);

Adds a copy of the first len bytes of string to the GStringChunk. The copy is nul-terminated.

The characters in the string can be changed, if necessary, though you should not change anything after the end of the string.

chunk : | a GStringChunk
string : | bytes to insert
len : | number of bytes of string to insert, or -1 to insert a nul-terminated string.
Returns : | a pointer to the copy of string within the GStringChunk

Since 2.4

g_string_chunk_free ()

void                g_string_chunk_free                 (GStringChunk *chunk);

Frees all memory allocated by the GStringChunk. After calling g_string_chunk_free() it is not safe to access any of the strings which were contained within it.

chunk : a GStringChunk.


String Utility Functions

String Utility Functions — various string-related functions.

Synopsis

#include <glib.h>
#include <glib/gprintf.h>

gchar*              g_strdup                            (const gchar *str);
gchar*              g_strndup                           (const gchar *str,
                                                         gsize n);
gchar**             g_strdupv                           (gchar **str_array);
gchar*              g_strnfill                          (gsize length,
                                                         gchar fill_char);
gchar*              g_stpcpy                            (gchar *dest,
                                                         const char *src);
gchar*              g_strstr_len                        (const gchar *haystack,
                                                         gssize haystack_len,
                                                         const gchar *needle);
gchar*              g_strrstr                           (const gchar *haystack,
                                                         const gchar *needle);
gchar*              g_strrstr_len                       (const gchar *haystack,
                                                         gssize haystack_len,
                                                         const gchar *needle);
gboolean            g_str_has_prefix                    (const gchar *str,
                                                         const gchar *prefix);
gboolean            g_str_has_suffix                    (const gchar *str,
                                                         const gchar *suffix);

gsize               g_strlcpy                           (gchar *dest,
                                                         const gchar *src,
                                                         gsize dest_size);
gsize               g_strlcat                           (gchar *dest,
                                                         const gchar *src,
                                                         gsize dest_size);

gchar*              g_strdup_printf                     (const gchar *format,
                                                         ...);
gchar*              g_strdup_vprintf                    (const gchar *format,
                                                         va_list args);
gint                g_printf                            (gchar const *format,
                                                         ...);
gint                g_vprintf                           (gchar const *format,
                                                         va_list args);
gint                g_fprintf                           (FILE *file,
                                                         gchar const *format,
                                                         ...);
gint                g_vfprintf                          (FILE *file,
                                                         gchar const *format,
                                                         va_list args);
gint                g_sprintf                           (gchar *string,
                                                         gchar const *format,
                                                         ...);
gint                g_vsprintf                          (gchar *string,
                                                         gchar const *format,
                                                         va_list args);
gint                g_snprintf                          (gchar *string,
                                                         gulong n,
                                                         gchar const *format,
                                                         ...);
gint                g_vsnprintf                         (gchar *string,
                                                         gulong n,
                                                         gchar const *format,
                                                         va_list args);
gint                g_vasprintf                         (gchar **string,
                                                         gchar const *format,
                                                         va_list args);
gsize               g_printf_string_upper_bound         (const gchar *format,
                                                         va_list args);

gboolean            g_ascii_isalnum                     (gchar c);
gboolean            g_ascii_isalpha                     (gchar c);
gboolean            g_ascii_iscntrl                     (gchar c);
gboolean            g_ascii_isdigit                     (gchar c);
gboolean            g_ascii_isgraph                     (gchar c);
gboolean            g_ascii_islower                     (gchar c);
gboolean            g_ascii_isprint                     (gchar c);
gboolean            g_ascii_ispunct                     (gchar c);
gboolean            g_ascii_isspace                     (gchar c);
gboolean            g_ascii_isupper                     (gchar c);
gboolean            g_ascii_isxdigit                    (gchar c);

gint                g_ascii_digit_value                 (gchar c);
gint                g_ascii_xdigit_value                (gchar c);

gint                g_ascii_strcasecmp                  (const gchar *s1,
                                                         const gchar *s2);
gint                g_ascii_strncasecmp                 (const gchar *s1,
                                                         const gchar *s2,
                                                         gsize n);

gchar*              g_ascii_strup                       (const gchar *str,
                                                         gssize len);
gchar*              g_ascii_strdown                     (const gchar *str,
                                                         gssize len);

gchar               g_ascii_tolower                     (gchar c);
gchar               g_ascii_toupper                     (gchar c);

GString*            g_string_ascii_up                   (GString *string);
GString*            g_string_ascii_down                 (GString *string);

gchar*              g_strup                             (gchar *string);
gchar*              g_strdown                           (gchar *string);

gint                g_strcasecmp                        (const gchar *s1,
                                                         const gchar *s2);
gint                g_strncasecmp                       (const gchar *s1,
                                                         const gchar *s2,
                                                         guint n);

gchar*              g_strreverse                        (gchar *string);

gint64              g_ascii_strtoll                     (const gchar *nptr,
                                                         gchar **endptr,
                                                         guint base);
guint64             g_ascii_strtoull                    (const gchar *nptr,
                                                         gchar **endptr,
                                                         guint base);
#define             G_ASCII_DTOSTR_BUF_SIZE
gdouble             g_ascii_strtod                      (const gchar *nptr,
                                                         gchar **endptr);
gchar*              g_ascii_dtostr                      (gchar *buffer,
                                                         gint buf_len,
                                                         gdouble d);
gchar*              g_ascii_formatd                     (gchar *buffer,
                                                         gint buf_len,
                                                         const gchar *format,
                                                         gdouble d);
gdouble             g_strtod                            (const gchar *nptr,
                                                         gchar **endptr);

gchar*              g_strchug                           (gchar *string);
gchar*              g_strchomp                          (gchar *string);
#define             g_strstrip                          ( string )

gchar*              g_strdelimit                        (gchar *string,
                                                         const gchar *delimiters,
                                                         gchar new_delimiter);
#define             G_STR_DELIMITERS
gchar*              g_strescape                         (const gchar *source,
                                                         const gchar *exceptions);
gchar*              g_strcompress                       (const gchar *source);
gchar*              g_strcanon                          (gchar *string,
                                                         const gchar *valid_chars,
                                                         gchar substitutor);
gchar**             g_strsplit                          (const gchar *string,
                                                         const gchar *delimiter,
                                                         gint max_tokens);
gchar**             g_strsplit_set                      (const gchar *string,
                                                         const gchar *delimiters,
                                                         gint max_tokens);
void                g_strfreev                          (gchar **str_array);
gchar*              g_strconcat                         (const gchar *string1,
                                                         ...);
gchar*              g_strjoin                           (const gchar *separator,
                                                         ...);
gchar*              g_strjoinv                          (const gchar *separator,
                                                         gchar **str_array);
guint               g_strv_length                       (gchar **str_array);

const gchar*        g_strerror                          (gint errnum);
const gchar*        g_strsignal                         (gint signum);

Description

This section describes a number of utility functions for creating, duplicating, and manipulating strings.

Note that the functions g_printf(), g_fprintf(), g_sprintf(), g_snprintf(), g_vprintf(), g_vfprintf(), g_vsprintf() and g_vsnprintf() are declared in the header gprintf.h which is not included in glib.h (otherwise using glib.h would drag in stdio.h), so you'll have to explicitly include <glib/gprintf.h> in order to use the GLib printf() functions.

While you may use the printf() functions to format UTF-8 strings, notice that the precision of a %Ns parameter is interpreted as the number of bytes, not characters to print. On top of that, the GNU libc implementation of the printf() functions has the "feature" that it checks that the string given for the %Ns parameter consists of a whole number of characters in the current encoding. So, unless you are sure you are always going to be in an UTF-8 locale or your know your text is restricted to ASCII, avoid using %Ns. If your intention is to format strings for a certain number of columns, then %Ns is not a correct solution anyway, since it fails to take wide characters (see g_unichar_iswide()) into account.

Details

g_strdup ()

gchar*              g_strdup                            (const gchar *str);

Duplicates a string. If str is NULL it returns NULL. The returned string should be freed when no longer needed.

str : | the string to duplicate.
Returns : | a newly-allocated copy of str.

g_strndup ()

gchar*              g_strndup                           (const gchar *str,
                                                         gsize n);

Duplicates the first n characters of a string, returning a newly-allocated buffer n + 1 characters long which will always be nul-terminated. If str is less than n characters long the buffer is padded with nuls. If str is NULL it returns NULL. The returned value should be freed when no longer needed.

str : | the string to duplicate part of.
n : | the maximum number of characters to copy from str.
Returns : | a newly-allocated buffer containing the first n characters of str, nul-terminated.

g_strdupv ()

gchar**             g_strdupv                           (gchar **str_array);

Copies NULL-terminated array of strings. The copy is a deep copy; the new array should be freed by first freeing each string, then the array itself. g_strfreev() does this for you. If called on a NULL value, g_strdupv() simply returns NULL.

str_array : | NULL-terminated array of strings.
Returns : | a new NULL-terminated array of strings.

g_strnfill ()

gchar*              g_strnfill                          (gsize length,
                                                         gchar fill_char);

Creates a new string length characters long filled with fill_char. The returned string should be freed when no longer needed.

length : | the length of the new string.
fill_char : | the character to fill the string with.
Returns : | a newly-allocated string filled the fill_char.

g_stpcpy ()

gchar*              g_stpcpy                            (gchar *dest,
                                                         const char *src);

Copies a nul-terminated string into the dest buffer, include the trailing nul, and return a pointer to the trailing nul byte. This is useful for concatenating multiple strings together without having to repeatedly scan for the end.

dest : | destination buffer.
src : | source string.
Returns : | a pointer to trailing nul byte.

g_strstr_len ()

gchar*              g_strstr_len                        (const gchar *haystack,
                                                         gssize haystack_len,
                                                         const gchar *needle);

Searches the string haystack for the first occurrence of the string needle, limiting the length of the search to haystack_len.

haystack : | a string.
haystack_len : | the maximum length of haystack.
needle : | the string to search for.
Returns : | a pointer to the found occurrence, or NULL if not found.

g_strrstr ()

gchar*              g_strrstr                           (const gchar *haystack,
                                                         const gchar *needle);

Searches the string haystack for the last occurrence of the string needle.

haystack : | a nul-terminated string.
needle : | the nul-terminated string to search for.
Returns : | a pointer to the found occurrence, or NULL if not found.

g_strrstr_len ()

gchar*              g_strrstr_len                       (const gchar *haystack,
                                                         gssize haystack_len,
                                                         const gchar *needle);

Searches the string haystack for the last occurrence of the string needle, limiting the length of the search to haystack_len.

haystack : | a nul-terminated string.
haystack_len : | the maximum length of haystack.
needle : | the nul-terminated string to search for.
Returns : | a pointer to the found occurrence, or NULL if not found.

g_str_has_prefix ()

gboolean            g_str_has_prefix                    (const gchar *str,
                                                         const gchar *prefix);

Looks whether the string str begins with prefix.

str : | a nul-terminated string.
prefix : | the nul-terminated prefix to look for.
Returns : | TRUE if str begins with prefix, FALSE otherwise.

Since 2.2

g_str_has_suffix ()

gboolean            g_str_has_suffix                    (const gchar *str,
                                                         const gchar *suffix);

Looks whether the string str ends with suffix.

str : | a nul-terminated string.
suffix : | the nul-terminated suffix to look for.
Returns : | TRUE if str end with suffix, FALSE otherwise.

Since 2.2

g_strlcpy ()

gsize               g_strlcpy                           (gchar *dest,
                                                         const gchar *src,
                                                         gsize dest_size);

Portability wrapper that calls strlcpy() on systems which have it, and emulates strlcpy() otherwise. Copies src to dest; dest is guaranteed to be nul-terminated; src must be nul-terminated; dest_size is the buffer size, not the number of chars to copy. Caveat: strlcpy() is supposedly more secure than strcpy() or strncpy(), but if you really want to avoid screwups, g_strdup() is an even better idea.

dest : | destination buffer
src : | source buffer
dest_size : | length of dest in bytes
Returns : | length of src

g_strlcat ()

gsize               g_strlcat                           (gchar *dest,
                                                         const gchar *src,
                                                         gsize dest_size);

Portability wrapper that calls strlcat() on systems which have it, and emulates it otherwise. Appends nul-terminated src string to dest, guaranteeing nul-termination for dest. The total size of dest won't exceed dest_size. Caveat: this is supposedly a more secure alternative to strcat() or strncat(), but for real security g_strconcat() is harder to mess up.

dest : | destination buffer, already containing one nul-terminated string
src : | source buffer
dest_size : | length of dest buffer in bytes (not length of existing string inside dest)
Returns : | length of src plus initial length of string in dest

g_strdup_printf ()

gchar*              g_strdup_printf                     (const gchar *format,
                                                         ...);

Similar to the standard C sprintf() function but safer, since it calculates the maximum space required and allocates memory to hold the result. The returned string should be freed when no longer needed.

format : | a standard printf() format string, but notice string precision pitfalls.
... : | the parameters to insert into the format string.
Returns : | a newly-allocated string holding the result.

g_strdup_vprintf ()

gchar*              g_strdup_vprintf                    (const gchar *format,
                                                         va_list args);

Similar to the standard C vsprintf() function but safer, since it calculates the maximum space required and allocates memory to hold the result. The returned string should be freed when no longer needed.

See also g_vasprintf(), which offers the same functionality, but additionally returns the length of the allocated string.

format : | a standard printf() format string, but notice string precision pitfalls.
args : | the list of parameters to insert into the format string.
Returns : | a newly-allocated string holding the result.

g_printf ()

gint                g_printf                            (gchar const *format,
                                                         ...);

An implementation of the standard printf() function which supports positional parameters, as specified in the Single Unix Specification.

format : | a standard printf() format string, but notice string precision pitfalls.
... : | the arguments to insert in the output.
Returns : | the number of characters printed.

Since 2.2

g_vprintf ()

gint                g_vprintf                           (gchar const *format,
                                                         va_list args);

An implementation of the standard vprintf() function which supports positional parameters, as specified in the Single Unix Specification.

format : | a standard printf() format string, but notice string precision pitfalls.
args : | the list of arguments to insert in the output.
Returns : | the number of characters printed.

Since 2.2

g_fprintf ()

gint                g_fprintf                           (FILE *file,
                                                         gchar const *format,
                                                         ...);

An implementation of the standard fprintf() function which supports positional parameters, as specified in the Single Unix Specification.

file : | the stream to write to.
format : | a standard printf() format string, but notice string precision pitfalls.
... : | the arguments to insert in the output.
Returns : | the number of characters printed.

Since 2.2

g_vfprintf ()

gint                g_vfprintf                          (FILE *file,
                                                         gchar const *format,
                                                         va_list args);

An implementation of the standard fprintf() function which supports positional parameters, as specified in the Single Unix Specification.

file : | the stream to write to.
format : | a standard printf() format string, but notice string precision pitfalls.
args : | the list of arguments to insert in the output.
Returns : | the number of characters printed.

Since 2.2

g_sprintf ()

gint                g_sprintf                           (gchar *string,
                                                         gchar const *format,
                                                         ...);

An implementation of the standard sprintf() function which supports positional parameters, as specified in the Single Unix Specification.

string : | the buffer to hold the output.
format : | a standard printf() format string, but notice string precision pitfalls.
... : | the arguments to insert in the output.
Returns : | the number of characters printed.

Since 2.2

g_vsprintf ()

gint                g_vsprintf                          (gchar *string,
                                                         gchar const *format,
                                                         va_list args);

An implementation of the standard vsprintf() function which supports positional parameters, as specified in the Single Unix Specification.

string : | the buffer to hold the output.
format : | a standard printf() format string, but notice string precision pitfalls.
args : | the list of arguments to insert in the output.
Returns : | the number of characters printed.

Since 2.2

g_snprintf ()

gint                g_snprintf                          (gchar *string,
                                                         gulong n,
                                                         gchar const *format,
                                                         ...);

A safer form of the standard sprintf() function. The output is guaranteed to not exceed n characters (including the terminating nul character), so it is easy to ensure that a buffer overflow cannot occur.

See also g_strdup_printf().

In versions of GLib prior to 1.2.3, this function may return -1 if the output was truncated, and the truncated string may not be nul-terminated. In versions prior to 1.3.12, this function returns the length of the output string.

The return value of g_snprintf() conforms to the snprintf() function as standardized in ISO C99. Note that this is different from traditional snprintf(), which returns the length of the output string.

The format string may contain positional parameters, as specified in the Single Unix Specification.

string : | the buffer to hold the output.
n : | the maximum number of characters to produce (including the terminating nul character).
format : | a standard printf() format string, but notice string precision pitfalls.
... : | the arguments to insert in the output.
Returns : | the number of characters which would be produced if the buffer was large enough.

g_vsnprintf ()

gint                g_vsnprintf                         (gchar *string,
                                                         gulong n,
                                                         gchar const *format,
                                                         va_list args);

A safer form of the standard vsprintf() function. The output is guaranteed to not exceed n characters (including the terminating nul character), so it is easy to ensure that a buffer overflow cannot occur.

See also g_strdup_vprintf().

In versions of GLib prior to 1.2.3, this function may return -1 if the output was truncated, and the truncated string may not be nul-terminated. In versions prior to 1.3.12, this function returns the length of the output string.

The return value of g_vsnprintf() conforms to the vsnprintf() function as standardized in ISO C99. Note that this is different from traditional vsnprintf(), which returns the length of the output string.

The format string may contain positional parameters, as specified in the Single Unix Specification.

string : | the buffer to hold the output.
n : | the maximum number of characters to produce (including the terminating nul character).
format : | a standard printf() format string, but notice string precision pitfalls.
args : | the list of arguments to insert in the output.
Returns : | the number of characters which would be produced if the buffer was large enough.

g_vasprintf ()

gint                g_vasprintf                         (gchar **string,
                                                         gchar const *format,
                                                         va_list args);

An implementation of the GNU vasprintf() function which supports positional parameters, as specified in the Single Unix Specification. This function is similar to g_vsprintf(), except that it allocates a string to hold the output, instead of putting the output in a buffer you allocate in advance.

string : | the return location for the newly-allocated string.
format : | a standard printf() format string, but notice string precision pitfalls.
args : | the list of arguments to insert in the output.
Returns : | the number of characters printed.

Since 2.4

g_printf_string_upper_bound ()

gsize               g_printf_string_upper_bound         (const gchar *format,
                                                         va_list args);

Calculates the maximum space needed to store the output of the sprintf() function.

format : | the format string. See the printf() documentation.
args : | the parameters to be inserted into the format string.
Returns : | the maximum space needed to store the formatted string.

g_ascii_isalnum ()

gboolean            g_ascii_isalnum                     (gchar c);

Determines whether a character is alphanumeric.

Unlike the standard C library isalnum() function, this only recognizes standard ASCII letters and ignores the locale, returning FALSE for all non-ASCII characters. Also unlike the standard library function, this takes a char, not an int, so don't call it on EOF but no need to cast to guchar before passing a possibly non-ASCII character in.

c : | any character
Returns : | TRUE if c is an ASCII alphanumeric character

g_ascii_isalpha ()

gboolean            g_ascii_isalpha                     (gchar c);

Determines whether a character is alphabetic (i.e. a letter).

Unlike the standard C library isalpha() function, this only recognizes standard ASCII letters and ignores the locale, returning FALSE for all non-ASCII characters. Also unlike the standard library function, this takes a char, not an int, so don't call it on EOF but no need to cast to guchar before passing a possibly non-ASCII character in.

c : | any character
Returns : | TRUE if c is an ASCII alphabetic character

g_ascii_iscntrl ()

gboolean            g_ascii_iscntrl                     (gchar c);

Determines whether a character is a control character.

Unlike the standard C library iscntrl() function, this only recognizes standard ASCII control characters and ignores the locale, returning FALSE for all non-ASCII characters. Also unlike the standard library function, this takes a char, not an int, so don't call it on EOF but no need to cast to guchar before passing a possibly non-ASCII character in.

c : | any character
Returns : | TRUE if c is an ASCII control character.

g_ascii_isdigit ()

gboolean            g_ascii_isdigit                     (gchar c);

Determines whether a character is digit (0-9).

Unlike the standard C library isdigit() function, this takes a char, not an int, so don't call it on EOF but no need to cast to guchar before passing a possibly non-ASCII character in.

c : | any character
Returns : | TRUE if c is an ASCII digit.

g_ascii_isgraph ()

gboolean            g_ascii_isgraph                     (gchar c);

Determines whether a character is a printing character and not a space.

Unlike the standard C library isgraph() function, this only recognizes standard ASCII characters and ignores the locale, returning FALSE for all non-ASCII characters. Also unlike the standard library function, this takes a char, not an int, so don't call it on EOF but no need to cast to guchar before passing a possibly non-ASCII character in.

c : | any character
Returns : | TRUE if c is an ASCII printing character other than space.

g_ascii_islower ()

gboolean            g_ascii_islower                     (gchar c);

Determines whether a character is an ASCII lower case letter.

Unlike the standard C library islower() function, this only recognizes standard ASCII letters and ignores the locale, returning FALSE for all non-ASCII characters. Also unlike the standard library function, this takes a char, not an int, so don't call it on EOF but no need to worry about casting to guchar before passing a possibly non-ASCII character in.

c : | any character
Returns : | TRUE if c is an ASCII lower case letter

g_ascii_isprint ()

gboolean            g_ascii_isprint                     (gchar c);

Determines whether a character is a printing character.

Unlike the standard C library isprint() function, this only recognizes standard ASCII characters and ignores the locale, returning FALSE for all non-ASCII characters. Also unlike the standard library function, this takes a char, not an int, so don't call it on EOF but no need to cast to guchar before passing a possibly non-ASCII character in.

c : | any character
Returns : | TRUE if c is an ASCII printing character.

g_ascii_ispunct ()

gboolean            g_ascii_ispunct                     (gchar c);

Determines whether a character is a punctuation character.

Unlike the standard C library ispunct() function, this only recognizes standard ASCII letters and ignores the locale, returning FALSE for all non-ASCII characters. Also unlike the standard library function, this takes a char, not an int, so don't call it on EOF but no need to cast to guchar before passing a possibly non-ASCII character in.

c : | any character
Returns : | TRUE if c is an ASCII punctuation character.

g_ascii_isspace ()

gboolean            g_ascii_isspace                     (gchar c);

Determines whether a character is a white-space character.

Unlike the standard C library isspace() function, this only recognizes standard ASCII white-space and ignores the locale, returning FALSE for all non-ASCII characters. Also unlike the standard library function, this takes a char, not an int, so don't call it on EOF but no need to cast to guchar before passing a possibly non-ASCII character in.

c : | any character
Returns : | TRUE if c is an ASCII white-space character

g_ascii_isupper ()

gboolean            g_ascii_isupper                     (gchar c);

Determines whether a character is an ASCII upper case letter.

Unlike the standard C library isupper() function, this only recognizes standard ASCII letters and ignores the locale, returning FALSE for all non-ASCII characters. Also unlike the standard library function, this takes a char, not an int, so don't call it on EOF but no need to worry about casting to guchar before passing a possibly non-ASCII character in.

c : | any character
Returns : | TRUE if c is an ASCII upper case letter

g_ascii_isxdigit ()

gboolean            g_ascii_isxdigit                    (gchar c);

Determines whether a character is a hexadecimal-digit character.

Unlike the standard C library isxdigit() function, this takes a char, not an int, so don't call it on EOF but no need to cast to guchar before passing a possibly non-ASCII character in.

c : | any character
Returns : | TRUE if c is an ASCII hexadecimal-digit character.

g_ascii_digit_value ()

gint                g_ascii_digit_value                 (gchar c);

Determines the numeric value of a character as a decimal digit. Differs from g_unichar_digit_value() because it takes a char, so there's no worry about sign extension if characters are signed.

c : | an ASCII character.
Returns : | If c is a decimal digit (according to g_ascii_isdigit()), its numeric value. Otherwise, -1.

g_ascii_xdigit_value ()

gint                g_ascii_xdigit_value                (gchar c);

Determines the numeric value of a character as a hexidecimal digit. Differs from g_unichar_xdigit_value() because it takes a char, so there's no worry about sign extension if characters are signed.

c : | an ASCII character.
Returns : | If c is a hex digit (according to g_ascii_isxdigit()), its numeric value. Otherwise, -1.

g_ascii_strcasecmp ()

gint                g_ascii_strcasecmp                  (const gchar *s1,
                                                         const gchar *s2);

Compare two strings, ignoring the case of ASCII characters.

Unlike the BSD strcasecmp() function, this only recognizes standard ASCII letters and ignores the locale, treating all non-ASCII bytes as if they are not letters.

This function should be used only on strings that are known to be in encodings where the bytes corresponding to ASCII letters always represent themselves. This includes UTF-8 and the ISO-8859-* charsets, but not for instance double-byte encodings like the Windows Codepage 932, where the trailing bytes of double-byte characters include all ASCII letters. If you compare two CP932 strings using this function, you will get false matches.

s1 : | string to compare with s2.
s2 : | string to compare with s1.
Returns : | 0 if the strings match, a negative value if s1 < s2, or a positive value if s1 > s2.

g_ascii_strncasecmp ()

gint                g_ascii_strncasecmp                 (const gchar *s1,
                                                         const gchar *s2,
                                                         gsize n);

Compare s1 and s2, ignoring the case of ASCII characters and any characters after the first n in each string.

Unlike the BSD strcasecmp() function, this only recognizes standard ASCII letters and ignores the locale, treating all non-ASCII characters as if they are not letters.

The same warning as in g_ascii_strcasecmp() applies: Use this function only on strings known to be in encodings where bytes corresponding to ASCII letters always represent themselves.

s1 : | string to compare with s2.
s2 : | string to compare with s1.
n : | number of characters to compare.
Returns : | 0 if the strings match, a negative value if s1 < s2, or a positive value if s1 > s2.

g_ascii_strup ()

gchar*              g_ascii_strup                       (const gchar *str,
                                                         gssize len);

Converts all lower case ASCII letters to upper case ASCII letters.

str : | a string.
len : | length of str in bytes, or -1 if str is nul-terminated.
Returns : | a newly allocated string, with all the lower case characters in str converted to upper case, with semantics that exactly match g_ascii_toupper(). (Note that this is unlike the old g_strup(), which modified the string in place.)

g_ascii_strdown ()

gchar*              g_ascii_strdown                     (const gchar *str,
                                                         gssize len);

Converts all upper case ASCII letters to lower case ASCII letters.

str : | a string.
len : | length of str in bytes, or -1 if str is nul-terminated.
Returns : | a newly-allocated string, with all the upper case characters in str converted to lower case, with semantics that exactly match g_ascii_tolower(). (Note that this is unlike the old g_strdown(), which modified the string in place.)

g_ascii_tolower ()

gchar               g_ascii_tolower                     (gchar c);

Convert a character to ASCII lower case.

Unlike the standard C library tolower() function, this only recognizes standard ASCII letters and ignores the locale, returning all non-ASCII characters unchanged, even if they are lower case letters in a particular character set. Also unlike the standard library function, this takes and returns a char, not an int, so don't call it on EOF but no need to worry about casting to guchar before passing a possibly non-ASCII character in.

c : | any character.
Returns : | the result of converting c to lower case. If c is not an ASCII upper case letter, c is returned unchanged.

g_ascii_toupper ()

gchar               g_ascii_toupper                     (gchar c);

Convert a character to ASCII upper case.

Unlike the standard C library toupper() function, this only recognizes standard ASCII letters and ignores the locale, returning all non-ASCII characters unchanged, even if they are upper case letters in a particular character set. Also unlike the standard library function, this takes and returns a char, not an int, so don't call it on EOF but no need to worry about casting to guchar before passing a possibly non-ASCII character in.

c : | any character.
Returns : | the result of converting c to upper case. If c is not an ASCII lower case letter, c is returned unchanged.

g_string_ascii_up ()

GString*            g_string_ascii_up                   (GString *string);

Converts all lower case ASCII letters to upper case ASCII letters.

string : | a GString
Returns : | passed-in string pointer, with all the lower case characters converted to upper case in place, with semantics that exactly match g_ascii_toupper.

g_string_ascii_down ()

GString*            g_string_ascii_down                 (GString *string);

Converts all upper case ASCII letters to lower case ASCII letters.

string : | a GString
Returns : | passed-in string pointer, with all the upper case characters converted to lower case in place, with semantics that exactly match g_ascii_tolower.

g_strup ()

gchar*              g_strup                             (gchar *string);

Warning

g_strup has been deprecated since version 2.2 and should not be used in newly-written code. This function is totally broken for the reasons discussed in the g_strncasecmp() docs - use g_ascii_strup() or g_utf8_strup() instead.

Converts a string to upper case.

string : | the string to convert.
Returns : | the string

g_strdown ()

gchar*              g_strdown                           (gchar *string);

Warning

g_strdown has been deprecated since version 2.2 and should not be used in newly-written code. This function is totally broken for the reasons discussed in the g_strncasecmp() docs - use g_ascii_strdown() or g_utf8_strdown() instead.

Converts a string to lower case.

string : | the string to convert.
Returns : | the string

g_strcasecmp ()

gint                g_strcasecmp                        (const gchar *s1,
                                                         const gchar *s2);

Warning

g_strcasecmp has been deprecated since version 2.2 and should not be used in newly-written code. See g_strncasecmp() for a discussion of why this function is deprecated and how to replace it.

A case-insensitive string comparison, corresponding to the standard strcasecmp() function on platforms which support it.

s1 : | a string.
s2 : | a string to compare with s1.
Returns : | 0 if the strings match, a negative value if s1 < s2, or a positive value if s1 > s2.

g_strncasecmp ()

gint                g_strncasecmp                       (const gchar *s1,
                                                         const gchar *s2,
                                                         guint n);

Warning

g_strncasecmp has been deprecated since version 2.2 and should not be used in newly-written code. The problem with g_strncasecmp() is that it does the comparison by calling toupper()/tolower(). These functions are locale-specific and operate on single bytes. However, it is impossible to handle things correctly from an I18N standpoint by operating on bytes, since characters may be multibyte. Thus g_strncasecmp() is broken if your string is guaranteed to be ASCII, since it's locale-sensitive, and it's broken if your string is localized, since it doesn't work on many encodings at all, including UTF-8, EUC-JP, etc.

There are therefore two replacement functions: g_ascii_strncasecmp(), which only works on ASCII and is not locale-sensitive, and g_utf8_casefold(), which is good for case-insensitive sorting of UTF-8.

A case-insensitive string comparison, corresponding to the standard strncasecmp() function on platforms which support it. It is similar to g_strcasecmp() except it only compares the first n characters of the strings.

s1 : | a string.
s2 : | a string to compare with s1.
n : | the maximum number of characters to compare.
Returns : | 0 if the strings match, a negative value if s1 < s2, or a positive value if s1 > s2.

g_strreverse ()

gchar*              g_strreverse                        (gchar *string);

Reverses all of the bytes in a string. For example, g_strreverse ("abcdef") will result in "fedcba".

Note that g_strreverse() doesn't work on UTF-8 strings containing multibyte characters. For that purpose, use g_utf8_strreverse().

string : | the string to reverse.
Returns : | the same pointer passed in as string.

g_ascii_strtoll ()

gint64              g_ascii_strtoll                     (const gchar *nptr,
                                                         gchar **endptr,
                                                         guint base);

Converts a string to a gint64 value. This function behaves like the standard strtoll() function does in the C locale. It does this without actually changing the current locale, since that would not be thread-safe.

This function is typically used when reading configuration files or other non-user input that should be locale independent. To handle input from the user you should normally use the locale-sensitive system strtoll() function.

If the correct value would cause overflow, G_MAXINT64 or G_MININT64 is returned, and ERANGE is stored in errno. If the base is outside the valid range, zero is returned, and EINVAL is stored in errno. If the string conversion fails, zero is returned, and endptr returns nptr (if endptr is non-NULL).

nptr : | the string to convert to a numeric value.
endptr : | if non-NULL, it returns the character after the last character used in the conversion.
base : | to be used for the conversion, 2..36 or 0
Returns : | the gint64 value or zero on error.

Since 2.12

g_ascii_strtoull ()

guint64             g_ascii_strtoull                    (const gchar *nptr,
                                                         gchar **endptr,
                                                         guint base);

Converts a string to a guint64 value. This function behaves like the standard strtoull() function does in the C locale. It does this without actually changing the current locale, since that would not be thread-safe.

This function is typically used when reading configuration files or other non-user input that should be locale independent. To handle input from the user you should normally use the locale-sensitive system strtoull() function.

If the correct value would cause overflow, G_MAXUINT64 is returned, and ERANGE is stored in errno. If the base is outside the valid range, zero is returned, and EINVAL is stored in errno. If the string conversion fails, zero is returned, and endptr returns nptr (if endptr is non-NULL).

nptr : | the string to convert to a numeric value.
endptr : | if non-NULL, it returns the character after the last character used in the conversion.
base : | to be used for the conversion, 2..36 or 0
Returns : | the guint64 value or zero on error.

Since 2.2

G_ASCII_DTOSTR_BUF_SIZE

#define G_ASCII_DTOSTR_BUF_SIZE (29 + 10)

A good size for a buffer to be passed into g_ascii_dtostr(). It is guaranteed to be enough for all output of that function on systems with 64bit IEEE-compatible doubles.

The typical usage would be something like:

  char buf[G_ASCII_DTOSTR_BUF_SIZE];

  fprintf (out, "value=%s\n", g_ascii_dtostr (buf, sizeof (buf), value));

g_ascii_strtod ()

gdouble             g_ascii_strtod                      (const gchar *nptr,
                                                         gchar **endptr);

Converts a string to a gdouble value. This function behaves like the standard strtod() function does in the C locale. It does this without actually changing the current locale, since that would not be thread-safe.

This function is typically used when reading configuration files or other non-user input that should be locale independent. To handle input from the user you should normally use the locale-sensitive system strtod() function.

To convert from a gdouble to a string in a locale-insensitive way, use g_ascii_dtostr().

If the correct value would cause overflow, plus or minus HUGE_VAL is returned (according to the sign of the value), and ERANGE is stored in errno. If the correct value would cause underflow, zero is returned and ERANGE is stored in errno.

This function resets errno before calling strtod() so that you can reliably detect overflow and underflow.

nptr : | the string to convert to a numeric value.
endptr : | if non-NULL, it returns the character after the last character used in the conversion.
Returns : | the gdouble value.

g_ascii_dtostr ()

gchar*              g_ascii_dtostr                      (gchar *buffer,
                                                         gint buf_len,
                                                         gdouble d);

Converts a gdouble to a string, using the '.' as decimal point.

This functions generates enough precision that converting the string back using g_ascii_strtod() gives the same machine-number (on machines with IEEE compatible 64bit doubles). It is guaranteed that the size of the resulting string will never be larger than G_ASCII_DTOSTR_BUF_SIZE bytes.

buffer : | A buffer to place the resulting string in
buf_len : | The length of the buffer.
d : | The gdouble to convert
Returns : | The pointer to the buffer with the converted string.

g_ascii_formatd ()

gchar*              g_ascii_formatd                     (gchar *buffer,
                                                         gint buf_len,
                                                         const gchar *format,
                                                         gdouble d);

Converts a gdouble to a string, using the '.' as decimal point. To format the number you pass in a printf()-style format string. Allowed conversion specifiers are 'e', 'E', 'f', 'F', 'g' and 'G'.

If you just want to want to serialize the value into a string, use g_ascii_dtostr().

buffer : | A buffer to place the resulting string in
buf_len : | The length of the buffer.
format : | The printf()-style format to use for the code to use for converting.
d : | The gdouble to convert
Returns : | The pointer to the buffer with the converted string.

g_strtod ()

gdouble             g_strtod                            (const gchar *nptr,
                                                         gchar **endptr);

Converts a string to a gdouble value. It calls the standard strtod() function to handle the conversion, but if the string is not completely converted it attempts the conversion again with g_ascii_strtod(), and returns the best match.

This function should seldomly be used. The normal situation when reading numbers not for human consumption is to use g_ascii_strtod(). Only when you know that you must expect both locale formatted and C formatted numbers should you use this. Make sure that you don't pass strings such as comma separated lists of values, since the commas may be interpreted as a decimal point in some locales, causing unexpected results.

nptr : | the string to convert to a numeric value.
endptr : | if non-NULL, it returns the character after the last character used in the conversion.
Returns : | the gdouble value.

g_strchug ()

gchar*              g_strchug                           (gchar *string);

Removes leading whitespace from a string, by moving the rest of the characters forward.

This function doesn't allocate or reallocate any memory; it modifies string in place. The pointer to string is returned to allow the nesting of functions.

Also see g_strchomp() and g_strstrip().

string : | a string to remove the leading whitespace from.
Returns : | string.

g_strchomp ()

gchar*              g_strchomp                          (gchar *string);

Removes trailing whitespace from a string.

This function doesn't allocate or reallocate any memory; it modifies string in place. The pointer to string is returned to allow the nesting of functions.

Also see g_strchug() and g_strstrip().

string : | a string to remove the trailing whitespace from.
Returns : | string.

g_strstrip()

#define             g_strstrip( string )

Removes leading and trailing whitespace from a string. See g_strchomp() and g_strchug().

string : a string to remove the leading and trailing whitespace from.

g_strdelimit ()

gchar*              g_strdelimit                        (gchar *string,
                                                         const gchar *delimiters,
                                                         gchar new_delimiter);

Converts any delimiter characters in string to new_delimiter. Any characters in string which are found in delimiters are changed to the new_delimiter character. Modifies string in place, and returns string itself, not a copy. The return value is to allow nesting such as g_ascii_strup (g_strdelimit (str, "abc", '?')).

string : | the string to convert.
delimiters : | a string containing the current delimiters, or NULL to use the standard delimiters defined in G_STR_DELIMITERS.
new_delimiter : | the new delimiter character.
Returns : | string.

G_STR_DELIMITERS

#define	 G_STR_DELIMITERS	"_-|> <."

The standard delimiters, used in g_strdelimit().

g_strescape ()

gchar*              g_strescape                         (const gchar *source,
                                                         const gchar *exceptions);

Escapes the special characters '\b', '\f', '\n', '\r', '\t', '\' and '"' in the string source by inserting a '\' before them. Additionally all characters in the range 0x01-0x1F (everything below SPACE) and in the range 0x7F-0xFF (all non-ASCII chars) are replaced with a '\' followed by their octal representation. Characters supplied in exceptions are not escaped.

g_strcompress() does the reverse conversion.

source : | a string to escape.
exceptions : | a string of characters not to escape in source.
Returns : | a newly-allocated copy of source with certain characters escaped. See above.

g_strcompress ()

gchar*              g_strcompress                       (const gchar *source);

Replaces all escaped characters with their one byte equivalent. It does the reverse conversion of g_strescape().

source : | a string to compress.
Returns : | a newly-allocated copy of source with all escaped character compressed.

g_strcanon ()

gchar*              g_strcanon                          (gchar *string,
                                                         const gchar *valid_chars,
                                                         gchar substitutor);

For each character in string, if the character is not in valid_chars, replaces the character with substitutor. Modifies string in place, and return string itself, not a copy. The return value is to allow nesting such as g_ascii_strup (g_strcanon (str, "abc", '?')).

string : | a nul-terminated array of bytes.
valid_chars : | bytes permitted in string.
substitutor : | replacement character for disallowed bytes.
Returns : | string.

g_strsplit ()

gchar**             g_strsplit                          (const gchar *string,
                                                         const gchar *delimiter,
                                                         gint max_tokens);

Splits a string into a maximum of max_tokens pieces, using the given delimiter. If max_tokens is reached, the remainder of string is appended to the last token.

As a special case, the result of splitting the empty string "" is an empty vector, not a vector containing a single string. The reason for this special case is that being able to represent a empty vector is typically more useful than consistent handling of empty elements. If you do need to represent empty elements, you'll need to check for the empty string before calling g_strsplit().

string : | a string to split.
delimiter : | a string which specifies the places at which to split the string. The delimiter is not included in any of the resulting strings, unless max_tokens is reached.
max_tokens : | the maximum number of pieces to split string into. If this is less than 1, the string is split completely.
Returns : | a newly-allocated NULL-terminated array of strings. Use g_strfreev() to free it.

g_strsplit_set ()

gchar**             g_strsplit_set                      (const gchar *string,
                                                         const gchar *delimiters,
                                                         gint max_tokens);

Splits string into a number of tokens not containing any of the characters in delimiter. A token is the (possibly empty) longest string that does not contain any of the characters in delimiters. If max_tokens is reached, the remainder is appended to the last token.

For example the result of g_strsplit_set ("abc:def/ghi", ":/", -1) is a NULL-terminated vector containing the three strings "abc", "def", and "ghi".

The result if g_strsplit_set (":def/ghi:", ":/", -1) is a NULL-terminated vector containing the four strings "", "def", "ghi", and "".

As a special case, the result of splitting the empty string "" is an empty vector, not a vector containing a single string. The reason for this special case is that being able to represent a empty vector is typically more useful than consistent handling of empty elements. If you do need to represent empty elements, you'll need to check for the empty string before calling g_strsplit_set().

Note that this function works on bytes not characters, so it can't be used to delimit UTF-8 strings for anything but ASCII characters.

string : | The string to be tokenized
delimiters : | A nul-terminated string containing bytes that are used to split the string.
max_tokens : | The maximum number of tokens to split string into. If this is less than 1, the string is split completely
Returns : | a newly-allocated NULL-terminated array of strings. Use g_strfreev() to free it.

Since 2.4

g_strfreev ()

void                g_strfreev                          (gchar **str_array);

Frees a NULL-terminated array of strings, and the array itself. If called on a NULL value, g_strfreev() simply returns.

str_array : a NULL-terminated array of strings to free.

g_strconcat ()

gchar*              g_strconcat                         (const gchar *string1,
                                                         ...);

Concatenates all of the given strings into one long string. The returned string should be freed when no longer needed.

Warning

The variable argument list must end with NULL. If you forget the NULL, g_strconcat() will start appending random memory junk to your string.

string1 : | The first string to add, which must not be NULL.
... : | a NULL-terminated list of strings to append to the string.
Returns : | a newly-allocated string containing all the string arguments.

g_strjoin ()

gchar*              g_strjoin                           (const gchar *separator,
                                                         ...);

Joins a number of strings together to form one long string, with the optional separator inserted between each of them.

separator : | a string to insert between each of the strings, or NULL.
... : | a NULL-terminated list of strings to join.
Returns : | a newly-allocated string containing all of the strings joined together, with separator between them.

g_strjoinv ()

gchar*              g_strjoinv                          (const gchar *separator,
                                                         gchar **str_array);

Joins a number of strings together to form one long string, with the optional separator inserted between each of them.

separator : | a string to insert between each of the strings, or NULL.
str_array : | a NULL-terminated array of strings to join.
Returns : | a newly-allocated string containing all of the strings joined together, with separator between them.

g_strv_length ()

guint               g_strv_length                       (gchar **str_array);

Returns the length of the given NULL-terminated string array str_array.

str_array : | a NULL-terminated array of strings.
Returns : | length of str_array.

Since 2.6

g_strerror ()

const gchar*        g_strerror                          (gint errnum);

Returns a string corresponding to the given error code, e.g. "no such process". This function is included since not all platforms support the strerror() function.

errnum : | the system error number. See the standard C errno documentation.
Returns : | a string describing the error code. If the error code is unknown, it returns "unknown error (<code>)". The string can only be used until the next call to g_strerror().

g_strsignal ()

const gchar*        g_strsignal                         (gint signum);

Returns a string describing the given signal, e.g. "Segmentation fault". This function is included since not all platforms support the strsignal() function.

signum : | the signal number. See the signal documentation.
Returns : | a string describing the signal. If the signal is unknown, it returns "unknown signal (<signum>)". The string can only be used until the next call to g_strsignal().


Strings

Strings — text buffers which grow automatically as text is added.

Synopsis

#include <glib.h>

                    GString;
GString*            g_string_new                        (const gchar *init);
GString*            g_string_new_len                    (const gchar *init,
                                                         gssize len);
GString*            g_string_sized_new                  (gsize dfl_size);
GString*            g_string_assign                     (GString *string,
                                                         const gchar *rval);
#define             g_string_sprintf
#define             g_string_sprintfa
void                g_string_printf                     (GString *string,
                                                         const gchar *format,
                                                         ...);
void                g_string_append_printf              (GString *string,
                                                         const gchar *format,
                                                         ...);
GString*            g_string_append                     (GString *string,
                                                         const gchar *val);
GString*            g_string_append_c                   (GString *string,
                                                         gchar c);
GString*            g_string_append_unichar             (GString *string,
                                                         gunichar wc);
GString*            g_string_append_len                 (GString *string,
                                                         const gchar *val,
                                                         gssize len);
GString*            g_string_prepend                    (GString *string,
                                                         const gchar *val);
GString*            g_string_prepend_c                  (GString *string,
                                                         gchar c);
GString*            g_string_prepend_unichar            (GString *string,
                                                         gunichar wc);
GString*            g_string_prepend_len                (GString *string,
                                                         const gchar *val,
                                                         gssize len);
GString*            g_string_insert                     (GString *string,
                                                         gssize pos,
                                                         const gchar *val);
GString*            g_string_insert_c                   (GString *string,
                                                         gssize pos,
                                                         gchar c);
GString*            g_string_insert_unichar             (GString *string,
                                                         gssize pos,
                                                         gunichar wc);
GString*            g_string_insert_len                 (GString *string,
                                                         gssize pos,
                                                         const gchar *val,
                                                         gssize len);
GString*            g_string_erase                      (GString *string,
                                                         gssize pos,
                                                         gssize len);
GString*            g_string_truncate                   (GString *string,
                                                         gsize len);
GString*            g_string_set_size                   (GString *string,
                                                         gsize len);
gchar*              g_string_free                       (GString *string,
                                                         gboolean free_segment);

GString*            g_string_up                         (GString *string);
GString*            g_string_down                       (GString *string);

guint               g_string_hash                       (const GString *str);
gboolean            g_string_equal                      (const GString *v,
                                                         const GString *v2);

Description

A GString is similar to a standard C string, except that it grows automatically as text is appended or inserted. Also, it stores the length of the string, so can be used for binary data with embedded nul bytes.

Details

GString

typedef struct {
  gchar  *str;
  gsize len;
  gsize allocated_len;
} GString;

The GString struct contains the public fields of a GString. The str field points to the character data. It may move as text is added. The len field contains the length of the string, not including the terminating nul byte.

The str field is nul-terminated and so can be used as an ordinary C string. But it may be moved when text is appended or inserted into the string.

g_string_new ()

GString*            g_string_new                        (const gchar *init);

Creates a new GString, initialized with the given string.

init : | the initial text to copy into the string.
Returns : | the new GString.

g_string_new_len ()

GString*            g_string_new_len                    (const gchar *init,
                                                         gssize len);

Creates a new GString with len bytes of the init buffer. Because a length is provided, init need not be nul-terminated, and can contain embedded nul bytes.

init : | initial contents of string.
len : | length of init to use.
Returns : | a new GString.

g_string_sized_new ()

GString*            g_string_sized_new                  (gsize dfl_size);

Creates a new GString, with enough space for dfl_size bytes. This is useful if you are going to add a lot of text to the string and don't want it to be reallocated too often.

dfl_size : | the default size of the space allocated to hold the string.
Returns : | the new GString.

g_string_assign ()

GString*            g_string_assign                     (GString *string,
                                                         const gchar *rval);

Copies the bytes from a string into a GString, destroying any previous contents. It is rather like the standard strcpy() function, except that you do not have to worry about having enough space to copy the string.

string : | the destination GString. Its current contents are destroyed.
rval : | the string to copy into string
Returns : | the destination GString.

g_string_sprintf

#define             g_string_sprintf

Warning

g_string_sprintf is deprecated and should not be used in newly-written code. This function has been renamed to g_string_printf().

Writes a formatted string into a GString. This is similar to the standard sprintf() function, except that the GString buffer automatically expands to contain the results. The previous contents of the GString are destroyed.

g_string_sprintfa

#define             g_string_sprintfa

Warning

g_string_sprintfa is deprecated and should not be used in newly-written code. This function has been renamed to g_string_append_printf().

Appends a formatted string onto the end of a GString. This function is is similar to g_string_sprintf() except that the text is appended to the GString.

g_string_printf ()

void                g_string_printf                     (GString *string,
                                                         const gchar *format,
                                                         ...);

Writes a formatted string into a GString. This is similar to the standard sprintf() function, except that the GString buffer automatically expands to contain the results. The previous contents of the GString are destroyed.

string : | a GString.
format : | the string format. See the printf() documentation.
... : | the parameters to insert into the format string.

g_string_append_printf ()

void                g_string_append_printf              (GString *string,
                                                         const gchar *format,
                                                         ...);

Appends a formatted string onto the end of a GString. This function is is similar to g_string_printf() except that the text is appended to the GString.

string : | a GString.
format : | the string format. See the printf() documentation.
... : | the parameters to insert into the format string.

g_string_append ()

GString*            g_string_append                     (GString *string,
                                                         const gchar *val);

Adds a string onto the end of a GString, expanding it if necessary.

string : | a GString.
val : | the string to append onto the end of the GString.
Returns : | the GString.

g_string_append_c ()

GString*            g_string_append_c                   (GString *string,
                                                         gchar c);

Adds a byte onto the end of a GString, expanding it if necessary.

string : | a GString.
c : | the byte to append onto the end of the GString.
Returns : | the GString.

g_string_append_unichar ()

GString*            g_string_append_unichar             (GString *string,
                                                         gunichar wc);

Converts a Unicode character into UTF-8, and appends it to the string.

string : | a GString
wc : | a Unicode character
Returns : | string

g_string_append_len ()

GString*            g_string_append_len                 (GString *string,
                                                         const gchar *val,
                                                         gssize len);

Appends len bytes of val to string. Because len is provided, val may contain embedded nuls and need not be nul-terminated.

string : | a GString.
val : | bytes to append.
len : | number of bytes of val to use.
Returns : | the GString.

g_string_prepend ()

GString*            g_string_prepend                    (GString *string,
                                                         const gchar *val);

Adds a string on to the start of a GString, expanding it if necessary.

string : | a GString.
val : | the string to prepend on the start of the GString.
Returns : | the GString.

g_string_prepend_c ()

GString*            g_string_prepend_c                  (GString *string,
                                                         gchar c);

Adds a byte onto the start of a GString, expanding it if necessary.

string : | a GString.
c : | the byte to prepend on the start of the GString.
Returns : | the GString.

g_string_prepend_unichar ()

GString*            g_string_prepend_unichar            (GString *string,
                                                         gunichar wc);

Converts a Unicode character into UTF-8, and prepends it to the string.

string : | a GString.
wc : | a Unicode character.
Returns : | string.

g_string_prepend_len ()

GString*            g_string_prepend_len                (GString *string,
                                                         const gchar *val,
                                                         gssize len);

Prepends len bytes of val to string. Because len is provided, val may contain embedded nuls and need not be nul-terminated.

string : | a GString.
val : | bytes to prepend.
len : | number of bytes in val to prepend.
Returns : | the GString passed in.

g_string_insert ()

GString*            g_string_insert                     (GString *string,
                                                         gssize pos,
                                                         const gchar *val);

Inserts a copy of a string into a GString, expanding it if necessary.

string : | a GString.
pos : | the position to insert the copy of the string.
val : | the string to insert.
Returns : | the GString.

g_string_insert_c ()

GString*            g_string_insert_c                   (GString *string,
                                                         gssize pos,
                                                         gchar c);

Inserts a byte into a GString, expanding it if necessary.

string : | a GString.
pos : | the position to insert the byte.
c : | the byte to insert.
Returns : | the GString.

g_string_insert_unichar ()

GString*            g_string_insert_unichar             (GString *string,
                                                         gssize pos,
                                                         gunichar wc);

Converts a Unicode character into UTF-8, and insert it into the string at the given position.

string : | a GString
pos : | the position at which to insert character, or -1 to append at the end of the string.
wc : | a Unicode character
Returns : | string

g_string_insert_len ()

GString*            g_string_insert_len                 (GString *string,
                                                         gssize pos,
                                                         const gchar *val,
                                                         gssize len);

Inserts len bytes of val into string at pos. Because len is provided, val may contain embedded nuls and need not be nul-terminated. If pos is -1, bytes are inserted at the end of the string.

string : | a GString.
pos : | position in string where insertion should happen, or -1 for at the end.
val : | bytes to insert.
len : | number of bytes of val to insert.
Returns : | the GString.

g_string_erase ()

GString*            g_string_erase                      (GString *string,
                                                         gssize pos,
                                                         gssize len);

Removes len bytes from a GString, starting at position pos. The rest of the GString is shifted down to fill the gap.

string : | a GString.
pos : | the position of the content to remove.
len : | the number of bytes to remove, or -1 to remove all following bytes.
Returns : | the GString.

g_string_truncate ()

GString*            g_string_truncate                   (GString *string,
                                                         gsize len);

Cuts off the end of the GString, leaving the first len bytes.

string : | a GString.
len : | the new size of the GString.
Returns : | the GString.

g_string_set_size ()

GString*            g_string_set_size                   (GString *string,
                                                         gsize len);

Sets the length of a GString. If the length is less than the current length, the string will be truncated. If the length is greater than the current length, the contents of the newly added area are undefined. (However, as always, string->str[string->len] will be a nul byte.)

string : | a GString
len : | the new length
Returns : | string

g_string_free ()

gchar*              g_string_free                       (GString *string,
                                                         gboolean free_segment);

Frees the memory allocated for the GString. If free_segment is TRUE it also frees the character data.

string : | a GString.
free_segment : | if TRUE the actual character data is freed as well.
Returns : | the character data of string (i.e. NULL if free_segment is TRUE)

g_string_up ()

GString*            g_string_up                         (GString *string);

Warning

g_string_up has been deprecated since version 2.2 and should not be used in newly-written code. This function uses the locale-specific toupper() function, which is almost never the right thing. Use g_string_ascii_up() or g_utf8_strup() instead.

Converts a GString to uppercase.

string : | a GString
Returns : | the GString

g_string_down ()

GString*            g_string_down                       (GString *string);

Warning

g_string_down has been deprecated since version 2.2 and should not be used in newly-written code. This function uses the locale-specific tolower() function, which is almost never the right thing. Use g_string_ascii_down() or g_utf8_strdown() instead.

Converts a GString to lowercase.

string : | a GString
Returns : | the GString.

g_string_hash ()

guint               g_string_hash                       (const GString *str);

Creates a hash code for str; for use with GHashTable.

str : | a string to hash.
Returns : | hash code for str.

g_string_equal ()

gboolean            g_string_equal                      (const GString *v,
                                                         const GString *v2);

Compares two strings for equality, returning TRUE if they are equal. For use with GHashTable.

v : | a GString.
v2 : | another GString.
Returns : | TRUE if they strings are the same length and contain the same bytes.


The Main Event Loop

The Main Event Loop — manages all available sources of events.

Synopsis

#include <glib.h>

                    GMainLoop;
GMainLoop*          g_main_loop_new                     (GMainContext *context,
                                                         gboolean is_running);
GMainLoop*          g_main_loop_ref                     (GMainLoop *loop);
void                g_main_loop_unref                   (GMainLoop *loop);
void                g_main_loop_run                     (GMainLoop *loop);
void                g_main_loop_quit                    (GMainLoop *loop);
gboolean            g_main_loop_is_running              (GMainLoop *loop);
GMainContext*       g_main_loop_get_context             (GMainLoop *loop);
#define             g_main_new                          (is_running)
#define             g_main_destroy                      (loop)
#define             g_main_run                          (loop)
#define             g_main_quit                         (loop)
#define             g_main_is_running                   (loop)

#define             G_PRIORITY_HIGH
#define             G_PRIORITY_DEFAULT
#define             G_PRIORITY_HIGH_IDLE
#define             G_PRIORITY_DEFAULT_IDLE
#define             G_PRIORITY_LOW

                    GMainContext;
GMainContext*       g_main_context_new                  (void);
GMainContext*       g_main_context_ref                  (GMainContext *context);
void                g_main_context_unref                (GMainContext *context);
GMainContext*       g_main_context_default              (void);
gboolean            g_main_context_iteration            (GMainContext *context,
                                                         gboolean may_block);
#define             g_main_iteration                    (may_block)
gboolean            g_main_context_pending              (GMainContext *context);
#define             g_main_pending                      ()
GSource*            g_main_context_find_source_by_id    (GMainContext *context,
                                                         guint source_id);
GSource*            g_main_context_find_source_by_user_data
                                                        (GMainContext *context,
                                                         gpointer user_data);
GSource*            g_main_context_find_source_by_funcs_user_data
                                                        (GMainContext *context,
                                                         GSourceFuncs *funcs,
                                                         gpointer user_data);
void                g_main_context_wakeup               (GMainContext *context);
gboolean            g_main_context_acquire              (GMainContext *context);
void                g_main_context_release              (GMainContext *context);
gboolean            g_main_context_is_owner             (GMainContext *context);
gboolean            g_main_context_wait                 (GMainContext *context,
                                                         GCond *cond,
                                                         GMutex *mutex);
gboolean            g_main_context_prepare              (GMainContext *context,
                                                         gint *priority);
gint                g_main_context_query                (GMainContext *context,
                                                         gint max_priority,
                                                         gint *timeout_,
                                                         GPollFD *fds,
                                                         gint n_fds);
gint                g_main_context_check                (GMainContext *context,
                                                         gint max_priority,
                                                         GPollFD *fds,
                                                         gint n_fds);
void                g_main_context_dispatch             (GMainContext *context);
void                g_main_context_set_poll_func        (GMainContext *context,
                                                         GPollFunc func);
GPollFunc           g_main_context_get_poll_func        (GMainContext *context);
gint                (*GPollFunc)                        (GPollFD *ufds,
                                                         guint nfsd,
                                                         gint timeout_);
void                g_main_context_add_poll             (GMainContext *context,
                                                         GPollFD *fd,
                                                         gint priority);
void                g_main_context_remove_poll          (GMainContext *context,
                                                         GPollFD *fd);
gint                g_main_depth                        (void);
GSource*            g_main_current_source               (void);
#define             g_main_set_poll_func                (func)

GSource*            g_timeout_source_new                (guint interval);
guint               g_timeout_add                       (guint interval,
                                                         GSourceFunc function,
                                                         gpointer data);
guint               g_timeout_add_full                  (gint priority,
                                                         guint interval,
                                                         GSourceFunc function,
                                                         gpointer data,
                                                         GDestroyNotify notify);

GSource*            g_idle_source_new                   (void);
guint               g_idle_add                          (GSourceFunc function,
                                                         gpointer data);
guint               g_idle_add_full                     (gint priority,
                                                         GSourceFunc function,
                                                         gpointer data,
                                                         GDestroyNotify notify);
gboolean            g_idle_remove_by_data               (gpointer data);

typedef             GPid;
void                (*GChildWatchFunc)                  (GPid pid,
                                                         gint status,
                                                         gpointer data);
GSource*            g_child_watch_source_new            (GPid pid);
guint               g_child_watch_add                   (GPid pid,
                                                         GChildWatchFunc function,
                                                         gpointer data);
guint               g_child_watch_add_full              (gint priority,
                                                         GPid pid,
                                                         GChildWatchFunc function,
                                                         gpointer data,
                                                         GDestroyNotify notify);

                    GPollFD;

                    GSource;
void                (*GSourceDummyMarshal)              (void);
                    GSourceFuncs;
                    GSourceCallbackFuncs;
GSource*            g_source_new                        (GSourceFuncs *source_funcs,
                                                         guint struct_size);
GSource*            g_source_ref                        (GSource *source);
void                g_source_unref                      (GSource *source);
void                g_source_set_funcs                  (GSource *source,
                                                         GSourceFuncs *funcs);
guint               g_source_attach                     (GSource *source,
                                                         GMainContext *context);
void                g_source_destroy                    (GSource *source);
gboolean            g_source_is_destroyed               (GSource *source);
void                g_source_set_priority               (GSource *source,
                                                         gint priority);
gint                g_source_get_priority               (GSource *source);
void                g_source_set_can_recurse            (GSource *source,
                                                         gboolean can_recurse);
gboolean            g_source_get_can_recurse            (GSource *source);
guint               g_source_get_id                     (GSource *source);
GMainContext*       g_source_get_context                (GSource *source);
void                g_source_set_callback               (GSource *source,
                                                         GSourceFunc func,
                                                         gpointer data,
                                                         GDestroyNotify notify);
gboolean            (*GSourceFunc)                      (gpointer data);
void                g_source_set_callback_indirect      (GSource *source,
                                                         gpointer callback_data,
                                                         GSourceCallbackFuncs *callback_funcs);
void                g_source_add_poll                   (GSource *source,
                                                         GPollFD *fd);
void                g_source_remove_poll                (GSource *source,
                                                         GPollFD *fd);
void                g_source_get_current_time           (GSource *source,
                                                         GTimeVal *timeval);
gboolean            g_source_remove                     (guint tag);
gboolean            g_source_remove_by_funcs_user_data  (GSourceFuncs *funcs,
                                                         gpointer user_data);
gboolean            g_source_remove_by_user_data        (gpointer user_data);

Description

The main event loop manages all the available sources of events for GLib and GTK+ applications. These events can come from any number of different types of sources such as file descriptors (plain files, pipes or sockets) and timeouts. New types of event sources can also be added using g_source_attach().

To allow multiple independent sets of sources to be handled in different threads, each source is associated with a GMainContext. A GMainContext can only be running in a single thread, but sources can be added to it and removed from it from other threads.

Each event source is assigned a priority. The default priority, G_PRIORITY_DEFAULT, is 0. Values less than 0 denote higher priorities. Values greater than 0 denote lower priorities. Events from high priority sources are always processed before events from lower priority sources.

Idle functions can also be added, and assigned a priority. These will be run whenever no events with a higher priority are ready to be processed.

The GMainLoop data type represents a main event loop. A GMainLoop is created with g_main_loop_new(). After adding the initial event sources, g_main_loop_run() is called. This continuously checks for new events from each of the event sources and dispatches them. Finally, the processing of an event from one of the sources leads to a call to g_main_loop_quit() to exit the main loop, and g_main_loop_run() returns.

It is possible to create new instances of GMainLoop recursively. This is often used in GTK+ applications when showing modal dialog boxes. Note that event sources are associated with a particular GMainContext, and will be checked and dispatched for all main loops associated with that GMainContext.

GTK+ contains wrappers of some of these functions, e.g. gtk_main(), gtk_main_quit() and gtk_events_pending().

Creating new sources types

One of the unusual features of the GTK+ main loop functionality is that new types of event source can be created and used in addition to the builtin type of event source. A new event source type is used for handling GDK events. A new source type is created by deriving from the GSource structure. The derived type of source is represented by a structure that has the GSource structure as a first element, and other elements specific to the new source type. To create an instance of the new source type, call g_source_new() passing in the size of the derived structure and a table of functions. These GSourceFuncs determine the behavior of the new source types.

New source types basically interact with with the main context in two ways. Their prepare function in GSourceFuncs can set a timeout to determine the maximum amount of time that the main loop will sleep before checking the source again. In addition, or as well, the source can add file descriptors to the set that the main context checks using g_source_add_poll().

Customizing the main loop iteration

Single iterations of a GMainContext can be run with g_main_context_iteration(). In some cases, more detailed control of exactly how the details of the main loop work is desired, for instance, when integrating the GMainLoop with an external main loop. In such cases, you can call the component functions of g_main_context_iteration() directly. These functions are g_main_context_prepare(), g_main_context_query(), g_main_context_check() and g_main_context_dispatch().

The operation of these functions can best be seen in terms of a state diagram, as shown in Figure 1, “States of a Main Context”.

Figure 1. States of a Main Context

States of a Main Context

Details

GMainLoop

typedef struct _GMainLoop GMainLoop;

The GMainLoop struct is an opaque data type representing the main event loop of a GLib or GTK+ application.

g_main_loop_new ()

GMainLoop*          g_main_loop_new                     (GMainContext *context,
                                                         gboolean is_running);

Creates a new GMainLoop structure.

context : | a GMainContext (if NULL, the default context will be used).
is_running : | set to TRUE to indicate that the loop is running. This is not very important since calling g_main_loop_run() will set this to TRUE anyway.
Returns : | a new GMainLoop.

g_main_loop_ref ()

GMainLoop*          g_main_loop_ref                     (GMainLoop *loop);

Increases the reference count on a GMainLoop object by one.

loop : | a GMainLoop
Returns : | loop

g_main_loop_unref ()

void                g_main_loop_unref                   (GMainLoop *loop);

Decreases the reference count on a GMainLoop object by one. If the result is zero, free the loop and free all associated memory.

loop : a GMainLoop

g_main_loop_run ()

void                g_main_loop_run                     (GMainLoop *loop);

Runs a main loop until g_main_loop_quit() is called on the loop. If this is called for the thread of the loop's GMainContext, it will process events from the loop, otherwise it will simply wait.

loop : a GMainLoop

g_main_loop_quit ()

void                g_main_loop_quit                    (GMainLoop *loop);

Stops a GMainLoop from running. Any calls to g_main_loop_run() for the loop will return.

loop : a GMainLoop

g_main_loop_is_running ()

gboolean            g_main_loop_is_running              (GMainLoop *loop);

Checks to see if the main loop is currently being run via g_main_loop_run().

loop : | a GMainLoop.
Returns : | TRUE if the mainloop is currently being run.

g_main_loop_get_context ()

GMainContext*       g_main_loop_get_context             (GMainLoop *loop);

Returns the GMainContext of loop.

loop : | a GMainLoop.
Returns : | the GMainContext of loop

g_main_new()

#define             g_main_new(is_running)

Warning

g_main_new has been deprecated since version 2.2 and should not be used in newly-written code. Use g_main_loop_new() instead.

Creates a new GMainLoop for the default main loop.

is_running : | set to TRUE to indicate that the loop is running. This is not very important since calling g_main_run() will set this to TRUE anyway.
Returns : | a new GMainLoop.

g_main_destroy()

#define             g_main_destroy(loop)

Warning

g_main_destroy has been deprecated since version 2.2 and should not be used in newly-written code. Use g_main_loop_unref() instead.

Frees the memory allocated for the GMainLoop.

loop : a GMainLoop.

g_main_run()

#define             g_main_run(loop)

Warning

g_main_run has been deprecated since version 2.2 and should not be used in newly-written code. Use g_main_loop_run() instead.

Runs a main loop until it stops running.

loop : a GMainLoop.

g_main_quit()

#define             g_main_quit(loop)

Warning

g_main_quit has been deprecated since version 2.2 and should not be used in newly-written code. Use g_main_loop_quit() instead.

Stops the GMainLoop. If g_main_run() was called to run the GMainLoop, it will now return.

loop : a GMainLoop.

g_main_is_running()

#define             g_main_is_running(loop)

Warning

g_main_is_running has been deprecated since version 2.2 and should not be used in newly-written code. USe g_main_loop_is_running() instead.

Checks if the main loop is running.

loop : | a GMainLoop.
Returns : | TRUE if the main loop is running.

G_PRIORITY_HIGH

#define G_PRIORITY_HIGH            -100

Use this for high priority event sources. It is not used within GLib or GTK+.

G_PRIORITY_DEFAULT

#define G_PRIORITY_DEFAULT          0

Use this for default priority event sources. In GLib this priority is used when adding timeout functions with g_timeout_add(). In GDK this priority is used for events from the X server.

G_PRIORITY_HIGH_IDLE

#define G_PRIORITY_HIGH_IDLE        100

Use this for high priority idle functions. GTK+ uses G_PRIORITY_HIGH_IDLE + 10 for resizing operations, and G_PRIORITY_HIGH_IDLE + 20 for redrawing operations. (This is done to ensure that any pending resizes are processed before any pending redraws, so that widgets are not redrawn twice unnecessarily.)

G_PRIORITY_DEFAULT_IDLE

#define G_PRIORITY_DEFAULT_IDLE     200

Use this for default priority idle functions. In GLib this priority is used when adding idle functions with g_idle_add().

G_PRIORITY_LOW

#define G_PRIORITY_LOW	            300

Use this for very low priority background tasks. It is not used within GLib or GTK+.

GMainContext

typedef struct _GMainContext GMainContext;

The GMainContext struct is an opaque data type representing a set of sources to be handled in a main loop.

g_main_context_new ()

GMainContext*       g_main_context_new                  (void);

Creates a new GMainContext strcuture

Returns : the new GMainContext

g_main_context_ref ()

GMainContext*       g_main_context_ref                  (GMainContext *context);

Increases the reference count on a GMainContext object by one.

context : | a GMainContext
Returns : | the context that was passed in (since 2.6)

g_main_context_unref ()

void                g_main_context_unref                (GMainContext *context);

Decreases the reference count on a GMainContext object by one. If the result is zero, free the context and free all associated memory.

context : a GMainContext

g_main_context_default ()

GMainContext*       g_main_context_default              (void);

Returns the default main context. This is the main context used for main loop functions when a main loop is not explicitly specified.

Returns : the default main context.

g_main_context_iteration ()

gboolean            g_main_context_iteration            (GMainContext *context,
                                                         gboolean may_block);

Runs a single iteration for the given main loop. This involves checking to see if any event sources are ready to be processed, then if no events sources are ready and may_block is TRUE, waiting for a source to become ready, then dispatching the highest priority events sources that are ready. Note that even when may_block is TRUE, it is still possible for g_main_context_iteration() to return FALSE, since the the wait may be interrupted for other reasons than an event source becoming ready.

context : | a GMainContext (if NULL, the default context will be used)
may_block : | whether the call may block.
Returns : | TRUE if events were dispatched.

g_main_iteration()

#define             g_main_iteration(may_block)

Warning

g_main_iteration has been deprecated since version 2.2 and should not be used in newly-written code. Use g_main_context_iteration() instead.

Runs a single iteration for the default GMainContext.

may_block : | set to TRUE if it should block (i.e. wait) until an event source becomes ready. It will return after an event source has been processed. If set to FALSE it will return immediately if no event source is ready to be processed.
Returns : | TRUE if more events are pending.

g_main_context_pending ()

gboolean            g_main_context_pending              (GMainContext *context);

Checks if any sources have pending events for the given context.

context : | a GMainContext (if NULL, the default context will be used)
Returns : | TRUE if events are pending.

g_main_pending()

#define             g_main_pending()

Warning

g_main_pending has been deprecated since version 2.2 and should not be used in newly-written code. Use g_main_context_pending() instead.

Checks if any events are pending for the default GMainContext (i.e. ready to be processed).

Returns : TRUE if any events are pending.

g_main_context_find_source_by_id ()

GSource*            g_main_context_find_source_by_id    (GMainContext *context,
                                                         guint source_id);

Finds a GSource given a pair of context and ID.

context : | a GMainContext (if NULL, the default context will be used)
source_id : | the source ID, as returned by g_source_get_id().
Returns : | the GSource if found, otherwise, NULL

g_main_context_find_source_by_user_data ()

GSource*            g_main_context_find_source_by_user_data
                                                        (GMainContext *context,
                                                         gpointer user_data);

Finds a source with the given user data for the callback. If multiple sources exist with the same user data, the first one found will be returned.

context : | a GMainContext
user_data : | the user_data for the callback.
Returns : | the source, if one was found, otherwise NULL

g_main_context_find_source_by_funcs_user_data ()

GSource*            g_main_context_find_source_by_funcs_user_data
                                                        (GMainContext *context,
                                                         GSourceFuncs *funcs,
                                                         gpointer user_data);

Finds a source with the given source functions and user data. If multiple sources exist with the same source function and user data, the first one found will be returned.

context : | a GMainContext (if NULL, the default context will be used).
funcs : | the source_funcs passed to g_source_new().
user_data : | the user data from the callback.
Returns : | the source, if one was found, otherwise NULL

g_main_context_wakeup ()

void                g_main_context_wakeup               (GMainContext *context);

If context is currently waiting in a poll(), interrupt the poll(), and continue the iteration process.

context : a GMainContext

g_main_context_acquire ()

gboolean            g_main_context_acquire              (GMainContext *context);

Tries to become the owner of the specified context. If some other context is the owner of the context, returns FALSE immediately. Ownership is properly recursive: the owner can require ownership again and will release ownership when g_main_context_release() is called as many times as g_main_context_acquire().

You must be the owner of a context before you can call g_main_context_prepare(), g_main_context_query(), g_main_context_check(), g_main_context_dispatch().

context : | a GMainContext
Returns : | TRUE if the operation succeeded, and this thread is now the owner of context.

g_main_context_release ()

void                g_main_context_release              (GMainContext *context);

Releases ownership of a context previously acquired by this thread with g_main_context_acquire(). If the context was acquired multiple times, the only release ownership when g_main_context_release() is called as many times as it was acquired.

context : a GMainContext

g_main_context_is_owner ()

gboolean            g_main_context_is_owner             (GMainContext *context);

Determines whether this thread holds the (recursive) ownership of this GMaincontext. This is useful to know before waiting on another thread that may be blocking to get ownership of context.

context : | a GMainContext
Returns : | TRUE if current thread is owner of context.

Since 2.10

g_main_context_wait ()

gboolean            g_main_context_wait                 (GMainContext *context,
                                                         GCond *cond,
                                                         GMutex *mutex);

Tries to become the owner of the specified context, as with g_main_context_acquire(). But if another thread is the owner, atomically drop mutex and wait on cond until that owner releases ownership or until cond is signaled, then try again (once) to become the owner.

context : | a GMainContext
cond : | a condition variable
mutex : | a mutex, currently held
Returns : | TRUE if the operation succeeded, and this thread is now the owner of context.

g_main_context_prepare ()

gboolean            g_main_context_prepare              (GMainContext *context,
                                                         gint *priority);

Prepares to poll sources within a main loop. The resulting information for polling is determined by calling g_main_context_query().

context : | a GMainContext
priority : | location to store priority of highest priority source already ready.
Returns : | TRUE if some source is ready to be dispatched prior to polling.

g_main_context_query ()

gint                g_main_context_query                (GMainContext *context,
                                                         gint max_priority,
                                                         gint *timeout_,
                                                         GPollFD *fds,
                                                         gint n_fds);

Determines information necessary to poll this main loop.

context : | a GMainContext
max_priority : | maximum priority source to check
timeout_ : | location to store timeout to be used in polling
fds : | location to store GPollFD records that need to be polled.
n_fds : | length of fds.
Returns : | the number of records actually stored in fds, or, if more than n_fds records need to be stored, the number of records that need to be stored.

g_main_context_check ()

gint                g_main_context_check                (GMainContext *context,
                                                         gint max_priority,
                                                         GPollFD *fds,
                                                         gint n_fds);

Passes the results of polling back to the main loop.

context : | a GMainContext
max_priority : | the maximum numerical priority of sources to check
fds : | array of GPollFD's that was passed to the last call to g_main_context_query()
n_fds : | return value of g_main_context_query()
Returns : | TRUE if some sources are ready to be dispatched.

g_main_context_dispatch ()

void                g_main_context_dispatch             (GMainContext *context);

Dispatches all pending sources.

context : a GMainContext

g_main_context_set_poll_func ()

void                g_main_context_set_poll_func        (GMainContext *context,
                                                         GPollFunc func);

Sets the function to use to handle polling of file descriptors. It will be used instead of the poll() system call (or GLib's replacement function, which is used where poll() isn't available).

This function could possibly be used to integrate the GLib event loop with an external event loop.

context : | a GMainContext
func : | the function to call to poll all file descriptors

g_main_context_get_poll_func ()

GPollFunc           g_main_context_get_poll_func        (GMainContext *context);

Gets the poll function set by g_main_context_set_poll_func().

context : | a GMainContext
Returns : | the poll function

GPollFunc ()

gint                (*GPollFunc)                        (GPollFD *ufds,
                                                         guint nfsd,
                                                         gint timeout_);

Specifies the type of function passed to g_main_context_set_poll_func(). The semantics of the function should match those of the poll() system call.

ufds : | an array of GPollFD elements.
nfsd : | the number of elements in ufds.
timeout_ : | the maximum time to wait for an event of the file descriptors. A negative value indicates an infinite timeout.
Returns : | the number of GPollFD elements which have events or errors reported, or -1 if an error occurred.

g_main_context_add_poll ()

void                g_main_context_add_poll             (GMainContext *context,
                                                         GPollFD *fd,
                                                         gint priority);

Adds a file descriptor to the set of file descriptors polled for this context. This will very seldomly be used directly. Instead a typical event source will use g_source_add_poll() instead.

context : | a GMainContext (or NULL for the default context)
fd : | a GPollFD structure holding information about a file descriptor to watch.
priority : | the priority for this file descriptor which should be the same as the priority used for g_source_attach() to ensure that the file descriptor is polled whenever the results may be needed.

g_main_context_remove_poll ()

void                g_main_context_remove_poll          (GMainContext *context,
                                                         GPollFD *fd);

Removes file descriptor from the set of file descriptors to be polled for a particular context.

context : | a GMainContext
fd : | a GPollFD descriptor previously added with g_main_context_add_poll()

g_main_depth ()

gint                g_main_depth                        (void);

Return value: The main loop recursion level in the current thread

Returns : the depth of the stack of calls to g_main_context_dispatch() on any GMainContext in the current thread. That is, when called from the toplevel, it gives 0. When called from within a callback from g_main_context_iteration() (or g_main_loop_run(), etc.) it returns 1. When called from within a callback to a recursive call to g_main_context_iterate(), it returns 2. And so forth. This function is useful in a situation like the following: Imagine an extremely simple "garbage collected" system.

Example 2.

static GList *free_list;

gpointer
allocate_memory (gsize size)
{
  gpointer result = g_malloc (size);
  free_list = g_list_prepend (free_list, result);
  return result;
}

void
free_allocated_memory (void)
{
  GList *l;
  for (l = free_list; l; l = l->next);
    g_free (l->data);
  g_list_free (free_list);
  free_list = NULL;
 }

[...]

while (TRUE);
 {
   g_main_context_iteration (NULL, TRUE);
   free_allocated_memory();
  }

This works from an application, however, if you want to do the same thing from a library, it gets more difficult, since you no longer control the main loop. You might think you can simply use an idle function to make the call to free_allocated_memory(), but that doesn't work, since the idle function could be called from a recursive callback. This can be fixed by using g_main_depth()

Example 3.

gpointer
allocate_memory (gsize size)
{
  FreeListBlock *block = g_new (FreeListBlock, 1);\
  block->mem = g_malloc (size);
  block->depth = g_main_depth();
  free_list = g_list_prepend (free_list, block);
  return block->mem;
}

void
free_allocated_memory (void)
{
  GList *l;

  int depth = g_main_depth();
  for (l = free_list; l; );
    {
      GList *next = l->next;
      FreeListBlock *block = l->data;
      if (block->depth > depth)
        {
          g_free (block->mem);
          g_free (block);
          free_list = g_list_delete_link (free_list, l);
        }

      l = next;
    }
  }

There is a temptation to use g_main_depth() to solve problems with reentrancy. For instance, while waiting for data to be received from the network in response to a menu item, the menu item might be selected again. It might seem that one could make the menu item's callback return immediately and do nothing if g_main_depth() returns a value greater than 1. However, this should be avoided since the user then sees selecting the menu item do nothing. Furthermore, you'll find yourself adding these checks all over your code, since there are doubtless many, many things that the user could do. Instead, you can use the following techniques:

  1. Use gtk_widget_set_sensitive() or modal dialogs to prevent the user from interacting with elements while the main loop is recursing.

  2. Avoid main loop recursion in situations where you can't handle arbitrary callbacks. Instead, structure your code so that you simply return to the main loop and then get called again when there is more work to do.

g_main_current_source ()

GSource*            g_main_current_source               (void);

Returns the currently firing source for this thread.

Returns : The currently firing source or NULL.

Since 2.12

g_main_set_poll_func()

#define             g_main_set_poll_func(func)

Warning

g_main_set_poll_func has been deprecated since version 2.2 and should not be used in newly-written code. Use g_main_context_set_poll_func() instead.

Sets the function to use for the handle polling of file descriptors for the default main context.

func : the function to call to poll all file descriptors.

g_timeout_source_new ()

GSource*            g_timeout_source_new                (guint interval);

Creates a new timeout source.

The source will not initially be associated with any GMainContext and must be added to one with g_source_attach() before it will be executed.

interval : | the timeout interval in milliseconds.
Returns : | the newly-created timeout source

g_timeout_add ()

guint               g_timeout_add                       (guint interval,
                                                         GSourceFunc function,
                                                         gpointer data);

Sets a function to be called at regular intervals, with the default priority, G_PRIORITY_DEFAULT. The function is called repeatedly until it returns FALSE, at which point the timeout is automatically destroyed and the function will not be called again. The first call to the function will be at the end of the first interval.

Note that timeout functions may be delayed, due to the processing of other event sources. Thus they should not be relied on for precise timing. After each call to the timeout function, the time of the next timeout is recalculated based on the current time and the given interval (it does not try to 'catch up' time lost in delays).

interval : | the time between calls to the function, in milliseconds (1/1000ths of a second)
function : | function to call
data : | data to pass to function
Returns : | the ID (greater than 0) of the event source.

g_timeout_add_full ()

guint               g_timeout_add_full                  (gint priority,
                                                         guint interval,
                                                         GSourceFunc function,
                                                         gpointer data,
                                                         GDestroyNotify notify);

Sets a function to be called at regular intervals, with the given priority. The function is called repeatedly until it returns FALSE, at which point the timeout is automatically destroyed and the function will not be called again. The notify function is called when the timeout is destroyed. The first call to the function will be at the end of the first interval.

Note that timeout functions may be delayed, due to the processing of other event sources. Thus they should not be relied on for precise timing. After each call to the timeout function, the time of the next timeout is recalculated based on the current time and the given interval (it does not try to 'catch up' time lost in delays).

priority : | the priority of the idle source. Typically this will be in the range between G_PRIORITY_DEFAULT_IDLE and G_PRIORITY_HIGH_IDLE.
interval : | the time between calls to the function, in milliseconds (1/1000ths of a second)
function : | function to call
data : | data to pass to function
notify : | function to call when the idle is removed, or NULL
Returns : | the ID (greater than 0) of the event source.

g_idle_source_new ()

GSource*            g_idle_source_new                   (void);

Creates a new idle source.

The source will not initially be associated with any GMainContext and must be added to one with g_source_attach() before it will be executed. Note that the default priority for idle sources is G_PRIORITY_DEFAULT_IDLE, as compared to other sources which have a default priority of G_PRIORITY_DEFAULT.

Returns : the newly-created idle source

g_idle_add ()

guint               g_idle_add                          (GSourceFunc function,
                                                         gpointer data);

Adds a function to be called whenever there are no higher priority events pending to the default main loop. The function is given the default idle priority, G_PRIORITY_DEFAULT_IDLE. If the function returns FALSE it is automatically removed from the list of event sources and will not be called again.

function : | function to call
data : | data to pass to function.
Returns : | the ID (greater than 0) of the event source.

g_idle_add_full ()

guint               g_idle_add_full                     (gint priority,
                                                         GSourceFunc function,
                                                         gpointer data,
                                                         GDestroyNotify notify);

Adds a function to be called whenever there are no higher priority events pending. If the function returns FALSE it is automatically removed from the list of event sources and will not be called again.

priority : | the priority of the idle source. Typically this will be in the range btweeen G_PRIORITY_DEFAULT_IDLE and G_PRIORITY_HIGH_IDLE.
function : | function to call
data : | data to pass to function
notify : | function to call when the idle is removed, or NULL
Returns : | the ID (greater than 0) of the event source.

g_idle_remove_by_data ()

gboolean            g_idle_remove_by_data               (gpointer data);

Removes the idle function with the given data.

data : | the data for the idle source's callback.
Returns : | TRUE if an idle source was found and removed.

GPid

typedef int GPid;

A type which is used to hold a process identification. On Unix, processes are identified by a process id (an integer), while Windows uses process handles (which are pointers).

GChildWatchFunc ()

void                (*GChildWatchFunc)                  (GPid pid,
                                                         gint status,
                                                         gpointer data);

The type of functions to be called when a child exists.

pid : | the process id of the child process
status : | Status information about the child process, see waitpid(2) for more information about this field
data : | user data passed to g_child_watch_add()

g_child_watch_source_new ()

GSource*            g_child_watch_source_new            (GPid pid);

Creates a new child_watch source.

The source will not initially be associated with any GMainContext and must be added to one with g_source_attach() before it will be executed.

Note that child watch sources can only be used in conjunction with g_spawn... when the G_SPAWN_DO_NOT_REAP_CHILD flag is used.

Note that on platforms where GPid must be explicitly closed (see g_spawn_close_pid()) pid must not be closed while the source is still active. Typically, you will want to call g_spawn_close_pid() in the callback function for the source.

Note further that using g_child_watch_source_new() is not compatible with calling waitpid(-1) in the application. Calling waitpid() for individual pids will still work fine.

pid : | process id of a child process to watch. On Windows, a HANDLE for the process to watch (which actually doesn't have to be a child).
Returns : | the newly-created child watch source

Since 2.4

g_child_watch_add ()

guint               g_child_watch_add                   (GPid pid,
                                                         GChildWatchFunc function,
                                                         gpointer data);

Sets a function to be called when the child indicated by pid exits, at a default priority, G_PRIORITY_DEFAULT.

Note that on platforms where GPid must be explicitly closed (see g_spawn_close_pid()) pid must not be closed while the source is still active. Typically, you will want to call g_spawn_close_pid() in the callback function for the source.

GLib supports only a single callback per process id.

pid : | process id of a child process to watch
function : | function to call
data : | data to pass to function
Returns : | the ID (greater than 0) of the event source.

Since 2.4

g_child_watch_add_full ()

guint               g_child_watch_add_full              (gint priority,
                                                         GPid pid,
                                                         GChildWatchFunc function,
                                                         gpointer data,
                                                         GDestroyNotify notify);

Sets a function to be called when the child indicated by pid exits, at a default priority, G_PRIORITY_DEFAULT.

Note that on platforms where GPid must be explicitly closed (see g_spawn_close_pid()) pid must not be closed while the source is still active. Typically, you will want to call g_spawn_close_pid() in the callback function for the source.

GLib supports only a single callback per process id.

priority : | the priority of the idle source. Typically this will be in the range between G_PRIORITY_DEFAULT_IDLE and G_PRIORITY_HIGH_IDLE.
pid : | process id of a child process to watch
function : | function to call
data : | data to pass to function
notify : | function to call when the idle is removed, or NULL
Returns : | the ID (greater than 0) of the event source.

Since 2.4

GPollFD

typedef struct {
  gint		fd;
  gushort 	events;
  gushort 	revents;
} GPollFD;

gint fd; | the file descriptor to poll (or a HANDLE on Win32 platforms).
gushort events; | a bitwise combination of flags from GIOCondition, specifying which events should be polled for. Typically for reading from a file descriptor you would use G_IO_IN | G_IO_HUP | G_IO_ERR, and for writing you would use G_IO_OUT | G_IO_ERR.
gushort revents; | a bitwise combination of flags from GIOCondition, returned from the poll() function to indicate which events occurred.

GSource

typedef struct {
} GSource;

The GSource struct is an opaque data type representing an event source.

GSourceDummyMarshal ()

void                (*GSourceDummyMarshal)              (void);

This is just a placeholder for GClosureMarshal, which cannot be used here for dependency reasons.

GSourceFuncs

typedef struct {
  gboolean (*prepare)  (GSource    *source,
            gint       *timeout_);
  gboolean (*check)    (GSource    *source);
  gboolean (*dispatch) (GSource    *source,
            GSourceFunc callback,
            gpointer    user_data);
  void     (*finalize) (GSource    *source); /* Can be NULL */

  /* For use by g_source_set_closure */
  GSourceFunc     closure_callback;
  GSourceDummyMarshal closure_marshal; /* Really is of type GClosureMarshal */
} GSourceFuncs;

The GSourceFuncs struct contains a table of functions used to handle event sources in a generic manner.

prepare | Called before all the file descriptors are polled. If the source can determine that it is ready here (without waiting for the results of the poll() call) it should return TRUE. It can also return a timeout_ value which should be the maximum timeout (in milliseconds) which should be passed to the poll() call. The actual timeout used will be -1 if all sources returned -1, or it will be the minimum of all the timeout_ values returned which were >= 0.
check | Called after all the file descriptors are polled. The source should return TRUE if it is ready to be dispatched. Note that some time may have passed since the previous prepare function was called, so the source should be checked again here.
dispatch | Called to dispatch the event source, after it has returned TRUE in either its prepare or its check function. The dispatch function is passed in a callback function and data. The callback function may be NULL if the source was never connected to a callback using g_source_set_callback(). The dispatch function should call the callback function with user_data and whatever additional parameters are needed for this type of event source.
finalize | Called when the source is finalized.

For idle sources, the prepare and check functions always return TRUE to indicate that the source is always ready to be processed. The prepare function also returns a timeout value of 0 to ensure that the poll() call doesn't block (since that would be time wasted which could have been spent running the idle function).

For timeout sources, the prepare and check functions both return TRUE if the timeout interval has expired. The prepare function also returns a timeout value to ensure that the poll() call doesn't block too long and miss the next timeout.

For file descriptor sources, the prepare function typically returns FALSE, since it must wait until poll() has been called before it knows whether any events need to be processed. It sets the returned timeout to -1 to indicate that it doesn't mind how long the poll() call blocks. In the check function, it tests the results of the poll() call to see if the required condition has been met, and returns TRUE if so.

GSourceCallbackFuncs

typedef struct {
  void (*ref)   (gpointer     cb_data);
  void (*unref) (gpointer     cb_data);
  void (*get)   (gpointer     cb_data,
         GSource     *source,
         GSourceFunc *func,
         gpointer    *data);
} GSourceCallbackFuncs;

The GSourceCallbackFuncs struct contains functions for managing callback objects.

ref () | Called when a reference is added to the callback object.
unref () | Called when a reference to the callback object is dropped.
get () | Called to extract the callback function and data from the callback object.

g_source_new ()

GSource*            g_source_new                        (GSourceFuncs *source_funcs,
                                                         guint struct_size);

Creates a new GSource structure. The size is specified to allow creating structures derived from GSource that contain additional data. The size passed in must be at least sizeof (GSource).

The source will not initially be associated with any GMainContext and must be added to one with g_source_attach() before it will be executed.

source_funcs : | structure containing functions that implement the sources behavior.
struct_size : | size of the GSource structure to create.
Returns : | the newly-created GSource.

g_source_ref ()

GSource*            g_source_ref                        (GSource *source);

Increases the reference count on a source by one.

source : | a GSource
Returns : | source

g_source_unref ()

void                g_source_unref                      (GSource *source);

Decreases the reference count of a source by one. If the resulting reference count is zero the source and associated memory will be destroyed.

source : a GSource

g_source_set_funcs ()

void                g_source_set_funcs                  (GSource *source,
                                                         GSourceFuncs *funcs);

Sets the source functions (can be used to override default implementations) of an unattached source.

source : | a GSource
funcs : | the new GSourceFuncs

Since 2.12

g_source_attach ()

guint               g_source_attach                     (GSource *source,
                                                         GMainContext *context);

Adds a GSource to a context so that it will be executed within that context.

source : | a GSource
context : | a GMainContext (if NULL, the default context will be used)
Returns : | the ID (greater than 0) for the source within the GMainContext.

g_source_destroy ()

void                g_source_destroy                    (GSource *source);

Removes a source from its GMainContext, if any, and mark it as destroyed. The source cannot be subsequently added to another context.

source : a GSource

g_source_is_destroyed ()

gboolean            g_source_is_destroyed               (GSource *source);

Returns whether source has been destroyed.

This is important when you operate upon your objects from within idle handlers, but may have freed the object before the dispatch of your idle handler.

static gboolean
idle_callback (gpointer data)
{
  SomeWidget *self = data;

  GDK_THREADS_ENTER ();
  /* do stuff with self */
  self->idle_id = 0;
  GDK_THREADS_LEAVE ();

  return FALSE;
}

static void
some_widget_do_stuff_later (SomeWidget *self)
{
  self->idle_id = g_idle_add (idle_callback, self);
}

static void
some_widget_finalize (GObject *object)
{
  SomeWidget *self = SOME_WIDGET (object);

  if (self->idle_id)
    g_source_remove (self->idle_id);

  G_OBJECT_CLASS (parent_class)->finalize (object);
}

This will fail in a multi-threaded application if the widget is destroyed before the idle handler fires due to the use after free in the callback. A solution, to this particular problem, is to check to if the source has already been destroy within the callback.

static gboolean
idle_callback (gpointer data)
{
  SomeWidget *self = data;

  GDK_THREADS_ENTER ();
  if (!g_source_is_destroyed (g_main_current_source ()))
    {
      /* do stuff with self */
    }
  GDK_THREADS_LEAVE ();

  return FALSE;
}

source : | a GSource
Returns : | TRUE if the source has been destroyed

Since 2.12

g_source_set_priority ()

void                g_source_set_priority               (GSource *source,
                                                         gint priority);

Sets the priority of a source. While the main loop is being run, a source will be dispatched if it is ready to be dispatched and no sources at a higher (numerically smaller) priority are ready to be dispatched.

source : | a GSource
priority : | the new priority.

g_source_get_priority ()

gint                g_source_get_priority               (GSource *source);

Gets the priority of a source.

source : | a GSource
Returns : | the priority of the source

g_source_set_can_recurse ()

void                g_source_set_can_recurse            (GSource *source,
                                                         gboolean can_recurse);

Sets whether a source can be called recursively. If can_recurse is TRUE, then while the source is being dispatched then this source will be processed normally. Otherwise, all processing of this source is blocked until the dispatch function returns.

source : | a GSource
can_recurse : | whether recursion is allowed for this source

g_source_get_can_recurse ()

gboolean            g_source_get_can_recurse            (GSource *source);

Checks whether a source is allowed to be called recursively. see g_source_set_can_recurse().

source : | a GSource
Returns : | whether recursion is allowed.

g_source_get_id ()

guint               g_source_get_id                     (GSource *source);

Returns the numeric ID for a particular source. The ID of a source is a positive integer which is unique within a particular main loop context. The reverse mapping from ID to source is done by g_main_context_find_source_by_id().

source : | a GSource
Returns : | the ID (greater than 0) for the source

g_source_get_context ()

GMainContext*       g_source_get_context                (GSource *source);

Gets the GMainContext with which the source is associated. Calling this function on a destroyed source is an error.

source : | a GSource
Returns : | the GMainContext with which the source is associated, or NULL if the context has not yet been added to a source.

g_source_set_callback ()

void                g_source_set_callback               (GSource *source,
                                                         GSourceFunc func,
                                                         gpointer data,
                                                         GDestroyNotify notify);

Sets the callback function for a source. The callback for a source is called from the source's dispatch function.

The exact type of func depends on the type of source; ie. you should not count on func being called with data as its first parameter.

Typically, you won't use this function. Instead use functions specific to the type of source you are using.

source : | the source
func : | a callback function
data : | the data to pass to callback function
notify : | a function to call when data is no longer in use, or NULL.

GSourceFunc ()

gboolean            (*GSourceFunc)                      (gpointer data);

Specifies the type of function passed to g_timeout_add(), g_timeout_add_full(), g_idle_add(), and g_idle_add_full().

data : | data passed to the function, set when the source was created with one of the above functions.
Returns : | it should return FALSE if the source should be removed.

g_source_set_callback_indirect ()

void                g_source_set_callback_indirect      (GSource *source,
                                                         gpointer callback_data,
                                                         GSourceCallbackFuncs *callback_funcs);

Sets the callback function storing the data as a refcounted callback "object". This is used internally. Note that calling g_source_set_callback_indirect() assumes an initial reference count on callback_data, and thus callback_funcs->unref will eventually be called once more than callback_funcs->ref.

source : | the source
callback_data : | pointer to callback data "object"
callback_funcs : | functions for reference counting callback_data and getting the callback and data

g_source_add_poll ()

void                g_source_add_poll                   (GSource *source,
                                                         GPollFD *fd);

Adds a file descriptor to the set of file descriptors polled for this source. This is usually combined with g_source_new() to add an event source. The event source's check function will typically test the revents field in the GPollFD struct and return TRUE if events need to be processed.

source : | a GSource
fd : | a GPollFD structure holding information about a file descriptor to watch.

g_source_remove_poll ()

void                g_source_remove_poll                (GSource *source,
                                                         GPollFD *fd);

Removes a file descriptor from the set of file descriptors polled for this source.

source : | a GSource
fd : | a GPollFD structure previously passed to g_source_add_poll().

g_source_get_current_time ()

void                g_source_get_current_time           (GSource *source,
                                                         GTimeVal *timeval);

Gets the "current time" to be used when checking this source. The advantage of calling this function over calling g_get_current_time() directly is that when checking multiple sources, GLib can cache a single value instead of having to repeatedly get the system time.

source : | a GSource
timeval : | GTimeVal structure in which to store current time.

g_source_remove ()

gboolean            g_source_remove                     (guint tag);

Removes the source with the given id from the default main context. The id of a GSource is given by g_source_get_id(), or will be returned by the functions g_source_attach(), g_idle_add(), g_idle_add_full(), g_timeout_add(), g_timeout_add_full(), g_child_watch_add(), g_child_watch_add_full(), g_io_add_watch(), and g_io_add_watch_full().

See also g_source_destroy().

tag : | the ID of the source to remove.
Returns : | TRUE if the source was found and removed.

g_source_remove_by_funcs_user_data ()

gboolean            g_source_remove_by_funcs_user_data  (GSourceFuncs *funcs,
                                                         gpointer user_data);

Removes a source from the default main loop context given the source functions and user data. If multiple sources exist with the same source functions and user data, only one will be destroyed.

funcs : | The source_funcs passed to g_source_new()
user_data : | the user data for the callback
Returns : | TRUE if a source was found and removed.

g_source_remove_by_user_data ()

gboolean            g_source_remove_by_user_data        (gpointer user_data);

Removes a source from the default main loop context given the user data for the callback. If multiple sources exist with the same user data, only one will be destroyed.

user_data : | the user_data for the callback.
Returns : | TRUE if a source was found and removed.


Thread Pools

Thread Pools — pools of threads to execute work concurrently.

Synopsis

#include <glib.h>

                    GThreadPool;
GThreadPool*        g_thread_pool_new                   (GFunc func,
                                                         gpointer user_data,
                                                         gint max_threads,
                                                         gboolean exclusive,
                                                         GError **error);
void                g_thread_pool_push                  (GThreadPool *pool,
                                                         gpointer data,
                                                         GError **error);
void                g_thread_pool_set_max_threads       (GThreadPool *pool,
                                                         gint max_threads,
                                                         GError **error);
gint                g_thread_pool_get_max_threads       (GThreadPool *pool);
guint               g_thread_pool_get_num_threads       (GThreadPool *pool);
guint               g_thread_pool_unprocessed           (GThreadPool *pool);
void                g_thread_pool_free                  (GThreadPool *pool,
                                                         gboolean immediate,
                                                         gboolean wait_);
void                g_thread_pool_set_max_unused_threads
                                                        (gint max_threads);
gint                g_thread_pool_get_max_unused_threads
                                                        (void);
guint               g_thread_pool_get_num_unused_threads
                                                        (void);
void                g_thread_pool_stop_unused_threads   (void);
void                g_thread_pool_set_sort_function     (GThreadPool *pool,
                                                         GCompareDataFunc func,
                                                         gpointer user_data);
void                g_thread_pool_set_max_idle_time     (guint interval);
guint               g_thread_pool_get_max_idle_time     (void);

Description

Sometimes you wish to asyncronously fork out the execution of work and continue working in your own thread. If that will happen often, the overhead of starting and destroying a thread each time might be to high. In such cases reusing already started threads seems like a good idea. And it indeed is, but implementing this can be tedious and error-prone.

Therefore GLib provides thread pools for your convenience. An added advantage is, that the threads can be shared between the different subsystems of your program, when they are using GLib.

To create a new thread pool, you use g_thread_pool_new(). It is destroyed by g_thread_pool_free().

If you want to execute a certain task within a thread pool, you call g_thread_pool_push().

To get the current number of running threads you call g_thread_pool_get_num_threads(). To get the number of still unprocessed tasks you call g_thread_pool_unprocessed(). To control the maximal number of threads for a thread pool, you use g_thread_pool_get_max_threads() and g_thread_pool_set_max_threads().

Finally you can control the number of unused threads, that are kept
alive by GLib for future use. The current number can be fetched with
g_thread_pool_get_num_unused_threads(). The maximal number can be
controlled by g_thread_pool_get_max_unused_threads() and
g_thread_pool_set_max_unused_threads(). All currently unused threads
can be stopped by calling g_thread_pool_stop_unused_threads().

Details

GThreadPool

typedef struct {
  GFunc func;
  gpointer user_data;
  gboolean exclusive;
} GThreadPool;

The GThreadPool struct represents a thread pool. It has six public read-only members, but the underlying struct is bigger, so you must not copy this struct.

GFunc func; | the function to execute in the threads of this pool
gpointer user_data; | the user data for the threads of this pool
gboolean exclusive; | are all threads exclusive to this pool

g_thread_pool_new ()

GThreadPool*        g_thread_pool_new                   (GFunc func,
                                                         gpointer user_data,
                                                         gint max_threads,
                                                         gboolean exclusive,
                                                         GError **error);

This function creates a new thread pool.

Whenever you call g_thread_pool_push(), either a new thread is created or an unused one is reused. At most max_threads threads are running concurrently for this thread pool. max_threads = -1 allows unlimited threads to be created for this thread pool. The newly created or reused thread now executes the function func with the two arguments. The first one is the parameter to g_thread_pool_push() and the second one is user_data.

The parameter exclusive determines, whether the thread pool owns all threads exclusive or whether the threads are shared globally. If exclusive is TRUE, max_threads threads are started immediately and they will run exclusively for this thread pool until it is destroyed by g_thread_pool_free(). If exclusive is FALSE, threads are created, when needed and shared between all non-exclusive thread pools. This implies that max_threads may not be -1 for exclusive thread pools.

error can be NULL to ignore errors, or non-NULL to report errors. An error can only occur when exclusive is set to TRUE and not all max_threads threads could be created.

func : | a function to execute in the threads of the new thread pool
user_data : | user data that is handed over to func every time it is called
max_threads : | the maximal number of threads to execute concurrently in the new thread pool, -1 means no limit
exclusive : | should this thread pool be exclusive?
error : | return location for error
Returns : | the new GThreadPool

g_thread_pool_push ()

void                g_thread_pool_push                  (GThreadPool *pool,
                                                         gpointer data,
                                                         GError **error);

Inserts data into the list of tasks to be executed by pool. When the number of currently running threads is lower than the maximal allowed number of threads, a new thread is started (or reused) with the properties given to g_thread_pool_new(). Otherwise data stays in the queue until a thread in this pool finishes its previous task and processes data.

error can be NULL to ignore errors, or non-NULL to report errors. An error can only occur when a new thread couldn't be created. In that case data is simply appended to the queue of work to do.

pool : | a GThreadPool
data : | a new task for pool
error : | return location for error

g_thread_pool_set_max_threads ()

void                g_thread_pool_set_max_threads       (GThreadPool *pool,
                                                         gint max_threads,
                                                         GError **error);

Sets the maximal allowed number of threads for pool. A value of -1 means, that the maximal number of threads is unlimited.

Setting max_threads to 0 means stopping all work for pool. It is effectively frozen until max_threads is set to a non-zero value again.

A thread is never terminated while calling func, as supplied by g_thread_pool_new(). Instead the maximal number of threads only has effect for the allocation of new threads in g_thread_pool_push(). A new thread is allocated, whenever the number of currently running threads in pool is smaller than the maximal number.

error can be NULL to ignore errors, or non-NULL to report errors. An error can only occur when a new thread couldn't be created.

pool : | a GThreadPool
max_threads : | a new maximal number of threads for pool
error : | return location for error

g_thread_pool_get_max_threads ()

gint                g_thread_pool_get_max_threads       (GThreadPool *pool);

Returns the maximal number of threads for pool.

pool : | a GThreadPool
Returns : | the maximal number of threads

g_thread_pool_get_num_threads ()

guint               g_thread_pool_get_num_threads       (GThreadPool *pool);

Returns the number of threads currently running in pool.

pool : | a GThreadPool
Returns : | the number of threads currently running

g_thread_pool_unprocessed ()

guint               g_thread_pool_unprocessed           (GThreadPool *pool);

Returns the number of tasks still unprocessed in pool.

pool : | a GThreadPool
Returns : | the number of unprocessed tasks

g_thread_pool_free ()

void                g_thread_pool_free                  (GThreadPool *pool,
                                                         gboolean immediate,
                                                         gboolean wait_);

Frees all resources allocated for pool.

If immediate is TRUE, no new task is processed for pool. Otherwise pool is not freed before the last task is processed. Note however, that no thread of this pool is interrupted, while processing a task. Instead at least all still running threads can finish their tasks before the pool is freed.

If wait_ is TRUE, the functions does not return before all tasks to be processed (dependent on immediate, whether all or only the currently running) are ready. Otherwise the function returns immediately.

After calling this function pool must not be used anymore.

pool : | a GThreadPool
immediate : | should pool shut down immediately?
wait_ : | should the function wait for all tasks to be finished?

g_thread_pool_set_max_unused_threads ()

void                g_thread_pool_set_max_unused_threads
                                                        (gint max_threads);

Sets the maximal number of unused threads to max_threads. If max_threads is -1, no limit is imposed on the number of unused threads.

max_threads : maximal number of unused threads

g_thread_pool_get_max_unused_threads ()

gint                g_thread_pool_get_max_unused_threads
                                                        (void);

Returns the maximal allowed number of unused threads.

Returns : the maximal number of unused threads

g_thread_pool_get_num_unused_threads ()

guint               g_thread_pool_get_num_unused_threads
                                                        (void);

Returns the number of currently unused threads.

Returns : the number of currently unused threads

g_thread_pool_stop_unused_threads ()

void                g_thread_pool_stop_unused_threads   (void);

Stops all currently unused threads. This does not change the maximal number of unused threads. This function can be used to regularly stop all unused threads e.g. from g_timeout_add().

g_thread_pool_set_sort_function ()

void                g_thread_pool_set_sort_function     (GThreadPool *pool,
                                                         GCompareDataFunc func,
                                                         gpointer user_data);

Sets the function used to sort the list of tasks. This allows the tasks to be processed by a priority determined by func, and not just in the order in which they were added to the pool.

Note, if the maximum number of threads is more than 1, the order that threads are executed can not be guranteed 100%. Threads are scheduled by the operating system and are executed at random. It cannot be assumed that threads are executed in the order they are created.

pool : | a GThreadPool
func : | the GCompareDataFunc used to sort the list of tasks. This function is passed two tasks. It should return 0 if the order in which they are handled does not matter, a negative value if the first task should be processed before the second or a positive value if the second task should be processed first.
user_data : | user data passed to func.

Since 2.10

g_thread_pool_set_max_idle_time ()

void                g_thread_pool_set_max_idle_time     (guint interval);

This function will set the maximum interval that a thread waiting in the pool for new tasks can be idle for before being stopped. This function is similar to calling g_thread_pool_stop_unused_threads() on a regular timeout, except, this is done on a per thread basis.

By setting interval to 0, idle threads will not be stopped. This function makes use of g_async_queue_timed_pop() using interval.

interval : the maximum interval (1/1000ths of a second) a thread can be idle.

Since 2.10

g_thread_pool_get_max_idle_time ()

guint               g_thread_pool_get_max_idle_time     (void);

This function will return the maximum interval that a thread will wait in the thread pool for new tasks before being stopped.

If this function returns 0, threads waiting in the thread pool for new work are not stopped.

Returns : the maximum interval to wait for new tasks in the thread pool before stopping the thread (1/1000ths of a second).

Since 2.10

See Also

GThread

GLib thread system.


Threads

Threads — thread abstraction; including threads, different mutexes, conditions and thread private data.

Synopsis

#include <glib.h>

#define             G_THREADS_ENABLED
#define             G_THREADS_IMPL_POSIX
#define             G_THREADS_IMPL_NONE

#define             G_THREAD_ERROR
enum                GThreadError;

                    GThreadFunctions;
void                g_thread_init                       (GThreadFunctions *vtable);
gboolean            g_thread_supported                  ();

gpointer            (*GThreadFunc)                      (gpointer data);
enum                GThreadPriority;
                    GThread;
GThread*            g_thread_create                     (GThreadFunc func,
                                                         gpointer data,
                                                         gboolean joinable,
                                                         GError **error);
GThread*            g_thread_create_full                (GThreadFunc func,
                                                         gpointer data,
                                                         gulong stack_size,
                                                         gboolean joinable,
                                                         gboolean bound,
                                                         GThreadPriority priority,
                                                         GError **error);
GThread*            g_thread_self                       (void);
gpointer            g_thread_join                       (GThread *thread);
void                g_thread_set_priority               (GThread *thread,
                                                         GThreadPriority priority);
void                g_thread_yield                      ();
void                g_thread_exit                       (gpointer retval);
void                g_thread_foreach                    (GFunc thread_func,
                                                         gpointer user_data);

                    GMutex;
GMutex*             g_mutex_new                         ();
void                g_mutex_lock                        (GMutex *mutex);
gboolean            g_mutex_trylock                     (GMutex *mutex);
void                g_mutex_unlock                      (GMutex *mutex);
void                g_mutex_free                        (GMutex *mutex);

                    GStaticMutex;
#define             G_STATIC_MUTEX_INIT
void                g_static_mutex_init                 (GStaticMutex *mutex);
void                g_static_mutex_lock                 (GStaticMutex *mutex);
gboolean            g_static_mutex_trylock              (GStaticMutex *mutex);
void                g_static_mutex_unlock               (GStaticMutex *mutex);
GMutex*             g_static_mutex_get_mutex            (GStaticMutex *mutex);
void                g_static_mutex_free                 (GStaticMutex *mutex);

#define             G_LOCK_DEFINE                       (name)
#define             G_LOCK_DEFINE_STATIC                (name)
#define             G_LOCK_EXTERN                       (name)
#define             G_LOCK                              (name)
#define             G_TRYLOCK                           (name)
#define             G_UNLOCK                            (name)

                    GStaticRecMutex;
#define             G_STATIC_REC_MUTEX_INIT
void                g_static_rec_mutex_init             (GStaticRecMutex *mutex);
void                g_static_rec_mutex_lock             (GStaticRecMutex *mutex);
gboolean            g_static_rec_mutex_trylock          (GStaticRecMutex *mutex);
void                g_static_rec_mutex_unlock           (GStaticRecMutex *mutex);
void                g_static_rec_mutex_lock_full        (GStaticRecMutex *mutex,
                                                         guint depth);
guint               g_static_rec_mutex_unlock_full      (GStaticRecMutex *mutex);
void                g_static_rec_mutex_free             (GStaticRecMutex *mutex);

                    GStaticRWLock;
#define             G_STATIC_RW_LOCK_INIT
void                g_static_rw_lock_init               (GStaticRWLock *lock);
void                g_static_rw_lock_reader_lock        (GStaticRWLock *lock);
gboolean            g_static_rw_lock_reader_trylock     (GStaticRWLock *lock);
void                g_static_rw_lock_reader_unlock      (GStaticRWLock *lock);
void                g_static_rw_lock_writer_lock        (GStaticRWLock *lock);
gboolean            g_static_rw_lock_writer_trylock     (GStaticRWLock *lock);
void                g_static_rw_lock_writer_unlock      (GStaticRWLock *lock);
void                g_static_rw_lock_free               (GStaticRWLock *lock);

                    GCond;
GCond*              g_cond_new                          ();
void                g_cond_signal                       (GCond *cond);
void                g_cond_broadcast                    (GCond *cond);
void                g_cond_wait                         (GCond *cond,
                                                         GMutex *mutex);
gboolean            g_cond_timed_wait                   (GCond *cond,
                                                         GMutex *mutex,
                                                         GTimeVal *abs_time);
void                g_cond_free                         (GCond *cond);

                    GPrivate;
GPrivate*           g_private_new                       (GDestroyNotify destructor);
gpointer            g_private_get                       (GPrivate *private_key);
void                g_private_set                       (GPrivate *private_key,
                                                         gpointer data);

                    GStaticPrivate;
#define             G_STATIC_PRIVATE_INIT
void                g_static_private_init               (GStaticPrivate *private_key);
gpointer            g_static_private_get                (GStaticPrivate *private_key);
void                g_static_private_set                (GStaticPrivate *private_key,
                                                         gpointer data,
                                                         GDestroyNotify notify);
void                g_static_private_free               (GStaticPrivate *private_key);

                    GOnce;
enum                GOnceStatus;
#define             G_ONCE_INIT
#define             g_once                              (once, func, arg)

Description

Threads act almost like processes, but unlike processes all threads of one process share the same memory. This is good, as it provides easy communication between the involved threads via this shared memory, and it is bad, because strange things (so called "Heisenbugs") might happen if the program is not carefully designed. In particular, due to the concurrent nature of threads, no assumptions on the order of execution of code running in different threads can be made, unless order is explicitly forced by the programmer through synchronization primitives.

The aim of the thread related functions in GLib is to provide a portable means for writing multi-threaded software. There are primitives for mutexes to protect the access to portions of memory (GMutex, GStaticMutex, G_LOCK_DEFINE, GStaticRecMutex and GStaticRWLock). There are primitives for condition variables to allow synchronization of threads (GCond). There are primitives for thread-private data - data that every thread has a private instance of (GPrivate, GStaticPrivate). Last but definitely not least there are primitives to portably create and manage threads (GThread).

You must call g_thread_init() before executing any other GLib functions in a threaded GLib program. After that, GLib is completely thread safe (all global data is automatically locked), but individual data structure instances are not automatically locked for performance reasons. So, for example you must coordinate accesses to the same GHashTable from multiple threads. The two notable exceptions from this rule are GMainLoop and GAsyncQueue, which are threadsafe and needs no further application-level locking to be accessed from multiple threads.

Details

G_THREADS_ENABLED

#define G_THREADS_ENABLED

This macro is defined if GLib was compiled with thread support. This does not necessarily mean that there is a thread implementation available, but it does mean that the infrastructure is in place and that once you provide a thread implementation to g_thread_init(), GLib will be multi-thread safe. If G_THREADS_ENABLED is not defined, then Glib is not, and cannot be, multi-thread safe.

G_THREADS_IMPL_POSIX

#define G_THREADS_IMPL_POSIX

This macro is defined if POSIX style threads are used.

G_THREADS_IMPL_NONE

#define G_THREADS_IMPL_NONE

This macro is defined if no thread implementation is used. You can, however, provide one to g_thread_init() to make GLib multi-thread safe.

G_THREAD_ERROR

#define G_THREAD_ERROR g_thread_error_quark ()

The error domain of the GLib thread subsystem.

enum GThreadError

typedef enum
{
  G_THREAD_ERROR_AGAIN /* Resource temporarily unavailable */
} GThreadError;

Possible errors of thread related functions.

G_THREAD_ERROR_AGAIN a thread couldn't be created due to resource shortage. Try again later.

GThreadFunctions

typedef struct {
  GMutex*  (*mutex_new)           (void);
  void     (*mutex_lock)          (GMutex               *mutex);
  gboolean (*mutex_trylock)       (GMutex               *mutex);
  void     (*mutex_unlock)        (GMutex               *mutex);
  void     (*mutex_free)          (GMutex               *mutex);
  GCond*   (*cond_new)            (void);
  void     (*cond_signal)         (GCond                *cond);
  void     (*cond_broadcast)      (GCond                *cond);
  void     (*cond_wait)           (GCond                *cond,
                                   GMutex               *mutex);
  gboolean (*cond_timed_wait)     (GCond                *cond,
                                   GMutex               *mutex,
                                   GTimeVal             *end_time);
  void      (*cond_free)          (GCond                *cond);
  GPrivate* (*private_new)        (GDestroyNotify        destructor);
  gpointer  (*private_get)        (GPrivate             *private_key);
  void      (*private_set)        (GPrivate             *private_key,
                                   gpointer              data);
  void      (*thread_create)      (GThreadFunc           func,
                                   gpointer              data,
                                   gulong                stack_size,
                                   gboolean              joinable,
                                   gboolean              bound,
                                   GThreadPriority       priority,
                                   gpointer              thread,
                                   GError              **error);
  void      (*thread_yield)       (void);
  void      (*thread_join)        (gpointer              thread);
  void      (*thread_exit)        (void);
  void      (*thread_set_priority)(gpointer              thread,
                                   GThreadPriority       priority);
  void      (*thread_self)        (gpointer              thread);
  gboolean  (*thread_equal)       (gpointer              thread1,
                   gpointer              thread2);
} GThreadFunctions;

This function table is used by g_thread_init() to initialize the thread system. The functions in the table are directly used by their g_* prepended counterparts (described in this document). For example, if you call g_mutex_new() then mutex_new() from the table provided to g_thread_init() will be called.

Note

Do not use this struct unless you know what you are doing.

g_thread_init ()

void                g_thread_init                       (GThreadFunctions *vtable);

If you use GLib from more than one thread, you must initialize the thread system by calling g_thread_init(). Most of the time you will only have to call g_thread_init (NULL).

Note

Do not call g_thread_init() with a non-NULL parameter unless you really know what you are doing.

Note

g_thread_init() must not be called directly or indirectly as a callback from GLib. Also no mutexes may be currently locked while calling g_thread_init().

g_thread_init() might only be called once. On the second call it will abort with an error. If you want to make sure that the thread system is initialized, you can do this:

if (!g_thread_supported ()) g_thread_init (NULL);

After that line, either the thread system is initialized or, if no thread system is available in GLib (i.e. either G_THREADS_ENABLED is not defined or G_THREADS_IMPL_NONE is defined), the program will abort.

If no thread system is available and vtable is NULL or if not all elements of vtable are non-NULL, then g_thread_init() will abort.

Note

To use g_thread_init() in your program, you have to link with the libraries that the command pkg-config --libs gthread-2.0 outputs. This is not the case for all the other thread related functions of GLib. Those can be used without having to link with the thread libraries.

vtable : a function table of type GThreadFunctions, that provides the entry points to the thread system to be used.

g_thread_supported ()

gboolean            g_thread_supported                  ();

This function returns TRUE if the thread system is initialized, and FALSE if it is not.

Note

This function is actually a macro. Apart from taking the address of it you can however use it as if it was a function.

Returns : TRUE, if the thread system is initialized.

GThreadFunc ()

gpointer            (*GThreadFunc)                      (gpointer data);

Specifies the type of the func functions passed to g_thread_create() or g_thread_create_full().

data : | data passed to the thread.
Returns : | the return value of the thread, which will be returned by g_thread_join().

enum GThreadPriority

typedef enum
{
  G_THREAD_PRIORITY_LOW,
  G_THREAD_PRIORITY_NORMAL,
  G_THREAD_PRIORITY_HIGH,
  G_THREAD_PRIORITY_URGENT
} GThreadPriority;

Specifies the priority of a thread.

Note

It is not guaranteed that threads with different priorities really behave accordingly. On some systems (e.g. Linux) there are no thread priorities. On other systems (e.g. Solaris) there doesn't seem to be different scheduling for different priorities. All in all try to avoid being dependent on priorities.

G_THREAD_PRIORITY_LOW | a priority lower than normal
G_THREAD_PRIORITY_NORMAL | the default priority
G_THREAD_PRIORITY_HIGH | a priority higher than normal
G_THREAD_PRIORITY_URGENT | the highest priority

GThread

typedef struct {
} GThread;

The GThread struct represents a running thread. It has three public read-only members, but the underlying struct is bigger, so you must not copy this struct.

Note

Resources for a joinable thread are not fully released until g_thread_join() is called for that thread.

g_thread_create ()

GThread*            g_thread_create                     (GThreadFunc func,
                                                         gpointer data,
                                                         gboolean joinable,
                                                         GError **error);

This function creates a new thread with the default priority.

If joinable is TRUE, you can wait for this threads termination calling g_thread_join(). Otherwise the thread will just disappear when it terminates.

The new thread executes the function func with the argument data. If the thread was created successfully, it is returned.

error can be NULL to ignore errors, or non-NULL to report errors. The error is set, if and only if the function returns NULL.

func : | a function to execute in the new thread.
data : | an argument to supply to the new thread.
joinable : | should this thread be joinable?
error : | return location for error.
Returns : | the new GThread on success.

g_thread_create_full ()

GThread*            g_thread_create_full                (GThreadFunc func,
                                                         gpointer data,
                                                         gulong stack_size,
                                                         gboolean joinable,
                                                         gboolean bound,
                                                         GThreadPriority priority,
                                                         GError **error);

This function creates a new thread with the priority priority. If the underlying thread implementation supports it, the thread gets a stack size of stack_size or the default value for the current platform, if stack_size is 0.

If joinable is TRUE, you can wait for this threads termination calling g_thread_join(). Otherwise the thread will just disappear when it terminates. If bound is TRUE, this thread will be scheduled in the system scope, otherwise the implementation is free to do scheduling in the process scope. The first variant is more expensive resource-wise, but generally faster. On some systems (e.g. Linux) all threads are bound.

The new thread executes the function func with the argument data. If the thread was created successfully, it is returned.

error can be NULL to ignore errors, or non-NULL to report errors. The error is set, if and only if the function returns NULL.

Note

It is not guaranteed that threads with different priorities really behave accordingly. On some systems (e.g. Linux) there are no thread priorities. On other systems (e.g. Solaris) there doesn't seem to be different scheduling for different priorities. All in all try to avoid being dependent on priorities. Use G_THREAD_PRIORITY_NORMAL here as a default.

Note

Only use g_thread_create_full() if you really can't use g_thread_create() instead. g_thread_create() does not take stack_size, bound, and priority as arguments, as they should only be used in cases in which it is unavoidable.

func : | a function to execute in the new thread.
data : | an argument to supply to the new thread.
stack_size : | a stack size for the new thread.
joinable : | should this thread be joinable?
bound : | should this thread be bound to a system thread?
priority : | a priority for the thread.
error : | return location for error.
Returns : | the new GThread on success.

g_thread_self ()

GThread*            g_thread_self                       (void);

This functions returns the GThread corresponding to the calling thread.

Returns : the current thread.

g_thread_join ()

gpointer            g_thread_join                       (GThread *thread);

Waits until thread finishes, i.e. the function func, as given to g_thread_create(), returns or g_thread_exit() is called by thread. All resources of thread including the GThread struct are released. thread must have been created with joinable=TRUE in g_thread_create(). The value returned by func or given to g_thread_exit() by thread is returned by this function.

thread : | a GThread to be waited for.
Returns : | the return value of the thread.

g_thread_set_priority ()

void                g_thread_set_priority               (GThread *thread,
                                                         GThreadPriority priority);

Changes the priority of thread to priority.

Note

It is not guaranteed that threads with different priorities really behave accordingly. On some systems (e.g. Linux) there are no thread priorities. On other systems (e.g. Solaris) there doesn't seem to be different scheduling for different priorities. All in all try to avoid being dependent on priorities.

thread : | a GThread.
priority : | a new priority for thread.

g_thread_yield ()

void                g_thread_yield                      ();

Gives way to other threads waiting to be scheduled.

This function is often used as a method to make busy wait less evil. But in most cases you will encounter, there are better methods to do that. So in general you shouldn't use this function.

g_thread_exit ()

void                g_thread_exit                       (gpointer retval);

Exits the current thread. If another thread is waiting for that thread using g_thread_join() and the current thread is joinable, the waiting thread will be woken up and get retval as the return value of g_thread_join(). If the current thread is not joinable, retval is ignored. Calling

g_thread_exit (retval);

is equivalent to calling

return retval;

in the function func, as given to g_thread_create().

Note

Never call g_thread_exit() from within a thread of a GThreadPool, as that will mess up the bookkeeping and lead to funny and unwanted results.

retval : the return value of this thread.

g_thread_foreach ()

void                g_thread_foreach                    (GFunc thread_func,
                                                         gpointer user_data);

Call thread_func on all existing GThread structures. Note that threads may decide to exit while thread_func is running, so without intimate knowledge about the lifetime of foreign threads, thread_func shouldn't access the GThread* pointer passed in as first argument. However, thread_func will not be called for threads which are known to have exited already.

Due to thread lifetime checks, this function has an execution complexity which is quadratic in the number of existing threads.

thread_func : | function to call for all GThread structures
user_data : | second argument to thread_func

Since 2.10

GMutex

typedef struct _GMutex GMutex;

The GMutex struct is an opaque data structure to represent a mutex (mutual exclusion). It can be used to protect data against shared access. Take for example the following function:

Example 4. A function which will not work in a threaded environment

  int give_me_next_number ()
  {
    static int current_number = 0;

    /* now do a very complicated calculation to calculate the new number,
       this might for example be a random number generator */
    current_number = calc_next_number (current_number);
    return current_number;
  }

It is easy to see that this won't work in a multi-threaded application. There current_number must be protected against shared access. A first naive implementation would be:

Example 5. The wrong way to write a thread-safe function

  int give_me_next_number ()
  {
    static int current_number = 0;
    int ret_val;
    static GMutex * mutex = NULL;

    if (!mutex)
      mutex = g_mutex_new ();
    g_mutex_lock (mutex);
    ret_val = current_number = calc_next_number (current_number);
    g_mutex_unlock (mutex);
    return ret_val;
  }

This looks like it would work, but there is a race condition while constructing the mutex and this code cannot work reliable. Please do not use such constructs in your own programs! One working solution is:

Example 6. A correct thread-safe function

  static GMutex *give_me_next_number_mutex = NULL;

  /* this function must be called before any call to give_me_next_number ()
     it must be called exactly once. */
  void init_give_me_next_number ()
  {
    g_assert (give_me_next_number_mutex == NULL);
    give_me_next_number_mutex = g_mutex_new ();
  }

  int give_me_next_number ()
  {
    static int current_number = 0;
    int ret_val;

    g_mutex_lock (give_me_next_number_mutex);
    ret_val = current_number = calc_next_number (current_number);
    g_mutex_unlock (give_me_next_number_mutex);
    return ret_val;
  }

GStaticMutex provides a simpler and safer way of doing this.

If you want to use a mutex, and your code should also work without calling g_thread_init() first, then you can not use a GMutex, as g_mutex_new() requires that the thread system be initialized. Use a GStaticMutex instead.

A GMutex should only be accessed via the following functions.

Note

All of the g_mutex_* functions are actually macros. Apart from taking their addresses, you can however use them as if they were functions.

g_mutex_new ()

GMutex*             g_mutex_new                         ();

Creates a new GMutex.

Note

This function will abort if g_thread_init() has not been called yet.

Returns : a new GMutex.

g_mutex_lock ()

void                g_mutex_lock                        (GMutex *mutex);

Locks mutex. If mutex is already locked by another thread, the current thread will block until mutex is unlocked by the other thread.

This function can be used even if g_thread_init() has not yet been called, and, in that case, will do nothing.

Note

GMutex is neither guaranteed to be recursive nor to be non-recursive, i.e. a thread could deadlock while calling g_mutex_lock(), if it already has locked mutex. Use GStaticRecMutex, if you need recursive mutexes.

mutex : a GMutex.

g_mutex_trylock ()

gboolean            g_mutex_trylock                     (GMutex *mutex);

Tries to lock mutex. If mutex is already locked by another thread, it immediately returns FALSE. Otherwise it locks mutex and returns TRUE.

This function can be used even if g_thread_init() has not yet been called, and, in that case, will immediately return TRUE.

Note

GMutex is neither guaranteed to be recursive nor to be non-recursive, i.e. the return value of g_mutex_trylock() could be both FALSE or TRUE, if the current thread already has locked mutex. Use GStaticRecMutex, if you need recursive mutexes.

mutex : | a GMutex.
Returns : | TRUE, if mutex could be locked.

g_mutex_unlock ()

void                g_mutex_unlock                      (GMutex *mutex);

Unlocks mutex. If another thread is blocked in a g_mutex_lock() call for mutex, it will be woken and can lock mutex itself.

This function can be used even if g_thread_init() has not yet been called, and, in that case, will do nothing.

mutex : a GMutex.

g_mutex_free ()

void                g_mutex_free                        (GMutex *mutex);

Destroys mutex.

mutex : a GMutex.

GStaticMutex

typedef struct _GStaticMutex GStaticMutex;

A GStaticMutex works like a GMutex, but it has one significant advantage. It doesn't need to be created at run-time like a GMutex, but can be defined at compile-time. Here is a shorter, easier and safer version of our give_me_next_number() example:

Example 7. Using GStaticMutex to simplify thread-safe programming

  int give_me_next_number ()
  {
    static int current_number = 0;
    int ret_val;
    static GStaticMutex mutex = G_STATIC_MUTEX_INIT;

    g_static_mutex_lock (&mutex);
    ret_val = current_number = calc_next_number (current_number);
    g_static_mutex_unlock (&mutex);
    return ret_val;
  }

Sometimes you would like to dynamically create a mutex. If you don't want to require prior calling to g_thread_init(), because your code should also be usable in non-threaded programs, you are not able to use g_mutex_new() and thus GMutex, as that requires a prior call to g_thread_init(). In theses cases you can also use a GStaticMutex. It must be initialized with g_static_mutex_init() before using it and freed with with g_static_mutex_free() when not needed anymore to free up any allocated resources.

Even though GStaticMutex is not opaque, it should only be used with the following functions, as it is defined differently on different platforms.

All of the g_static_mutex_* functions can also be used even if g_thread_init() has not yet been called.

Note

All of the g_static_mutex_* functions are actually macros. Apart from taking their addresses, you can however use them as if they were functions.

G_STATIC_MUTEX_INIT

#define G_STATIC_MUTEX_INIT

A GStaticMutex must be initialized with this macro, before it can be used. This macro can used be to initialize a variable, but it cannot be assigned to a variable. In that case you have to use g_static_mutex_init().

GStaticMutex my_mutex = G_STATIC_MUTEX_INIT;

g_static_mutex_init ()

void                g_static_mutex_init                 (GStaticMutex *mutex);

Initializes mutex. Alternatively you can initialize it with G_STATIC_MUTEX_INIT.

mutex : a GStaticMutex to be initialized.

g_static_mutex_lock ()

void                g_static_mutex_lock                 (GStaticMutex *mutex);

Works like g_mutex_lock(), but for a GStaticMutex.

mutex : a GStaticMutex.

g_static_mutex_trylock ()

gboolean            g_static_mutex_trylock              (GStaticMutex *mutex);

Works like g_mutex_trylock(), but for a GStaticMutex.

mutex : | a GStaticMutex.
Returns : | TRUE, if the GStaticMutex could be locked.

g_static_mutex_unlock ()

void                g_static_mutex_unlock               (GStaticMutex *mutex);

Works like g_mutex_unlock(), but for a GStaticMutex.

mutex : a GStaticMutex.

g_static_mutex_get_mutex ()

GMutex*             g_static_mutex_get_mutex            (GStaticMutex *mutex);

For some operations (like g_cond_wait()) you must have a GMutex instead of a GStaticMutex. This function will return the corresponding GMutex for mutex.

mutex : | a GStaticMutex.
Returns : | the GMutex corresponding to mutex.

g_static_mutex_free ()

void                g_static_mutex_free                 (GStaticMutex *mutex);

Releases all resources allocated to mutex.

You don't have to call this functions for a GStaticMutex with an unbounded lifetime, i.e. objects declared 'static', but if you have a GStaticMutex as a member of a structure and the structure is freed, you should also free the GStaticMutex.

mutex : a GStaticMutex to be freed.

G_LOCK_DEFINE()

#define             G_LOCK_DEFINE(name)

The G_LOCK_* macros provide a convenient interface to GStaticMutex with the advantage that they will expand to nothing in programs compiled against a thread-disabled GLib, saving code and memory there. G_LOCK_DEFINE defines a lock. It can appear anywhere variable definitions may appear in programs, i.e. in the first block of a function or outside of functions. The name parameter will be mangled to get the name of the GStaticMutex. This means that you can use names of existing variables as the parameter - e.g. the name of the variable you intent to protect with the lock. Look at our give_me_next_number() example using the G_LOCK_* macros:

Example 8. Using the G_LOCK_* convenience macros

G_LOCK_DEFINE (current_number);

int give_me_next_number ()
  {
    static int current_number = 0;
    int ret_val;

    G_LOCK (current_number);
    ret_val = current_number = calc_next_number (current_number);
    G_UNLOCK (current_number);
    return ret_val;
  }

name : the name of the lock.

G_LOCK_DEFINE_STATIC()

#define             G_LOCK_DEFINE_STATIC(name)

This works like G_LOCK_DEFINE, but it creates a static object.

name : the name of the lock.

G_LOCK_EXTERN()

#define             G_LOCK_EXTERN(name)

This declares a lock, that is defined with G_LOCK_DEFINE in another module.

name : the name of the lock.

G_LOCK()

#define             G_LOCK(name)

Works like g_mutex_lock(), but for a lock defined with G_LOCK_DEFINE.

name : the name of the lock.

G_TRYLOCK()

#define             G_TRYLOCK(name)

Works like g_mutex_trylock(), but for a lock defined with G_LOCK_DEFINE.

name : | the name of the lock.
Returns : | TRUE, if the lock could be locked.

G_UNLOCK()

#define             G_UNLOCK(name)

Works like g_mutex_unlock(), but for a lock defined with G_LOCK_DEFINE.

name : the name of the lock.

GStaticRecMutex

typedef struct {
} GStaticRecMutex;

A GStaticRecMutex works like a GStaticMutex, but it can be locked multiple times by one thread. If you enter it n times, you have to unlock it n times again to let other threads lock it. An exception is the function g_static_rec_mutex_unlock_full(): that allows you to unlock a GStaticRecMutex completely returning the depth, (i.e. the number of times this mutex was locked). The depth can later be used to restore the state of the GStaticRecMutex by calling g_static_rec_mutex_lock_full().

Even though GStaticRecMutex is not opaque, it should only be used with the following functions.

All of the g_static_rec_mutex_* functions can be used even if g_thread_init() has not been called.

G_STATIC_REC_MUTEX_INIT

#define G_STATIC_REC_MUTEX_INIT { G_STATIC_MUTEX_INIT }

A GStaticRecMutex must be initialized with this macro before it can be used. This macro can used be to initialize a variable, but it cannot be assigned to a variable. In that case you have to use g_static_rec_mutex_init().

GStaticRecMutex my_mutex = G_STATIC_REC_MUTEX_INIT;

g_static_rec_mutex_init ()

void                g_static_rec_mutex_init             (GStaticRecMutex *mutex);

A GStaticRecMutex must be initialized with this function before it can be used. Alternatively you can initialize it with G_STATIC_REC_MUTEX_INIT.

mutex : a GStaticRecMutex to be initialized.

g_static_rec_mutex_lock ()

void                g_static_rec_mutex_lock             (GStaticRecMutex *mutex);

Locks mutex. If mutex is already locked by another thread, the current thread will block until mutex is unlocked by the other thread. If mutex is already locked by the calling thread, this functions increases the depth of mutex and returns immediately.

mutex : a GStaticRecMutex to lock.

g_static_rec_mutex_trylock ()

gboolean            g_static_rec_mutex_trylock          (GStaticRecMutex *mutex);

Tries to lock mutex. If mutex is already locked by another thread, it immediately returns FALSE. Otherwise it locks mutex and returns TRUE. If mutex is already locked by the calling thread, this functions increases the depth of mutex and immediately returns TRUE.

mutex : | a GStaticRecMutex to lock.
Returns : | TRUE, if mutex could be locked.

g_static_rec_mutex_unlock ()

void                g_static_rec_mutex_unlock           (GStaticRecMutex *mutex);

Unlocks mutex. Another thread can will be allowed to lock mutex only when it has been unlocked as many times as it had been locked before. If mutex is completely unlocked and another thread is blocked in a g_static_rec_mutex_lock() call for mutex, it will be woken and can lock mutex itself.

mutex : a GStaticRecMutex to unlock.

g_static_rec_mutex_lock_full ()

void                g_static_rec_mutex_lock_full        (GStaticRecMutex *mutex,
                                                         guint depth);

Works like calling g_static_rec_mutex_lock() for mutex depth times.

mutex : | a GStaticRecMutex to lock.
depth : | number of times this mutex has to be unlocked to be completely unlocked.

g_static_rec_mutex_unlock_full ()

guint               g_static_rec_mutex_unlock_full      (GStaticRecMutex *mutex);

Completely unlocks mutex. If another thread is blocked in a g_static_rec_mutex_lock() call for mutex, it will be woken and can lock mutex itself. This function returns the number of times that mutex has been locked by the current thread. To restore the state before the call to g_static_rec_mutex_unlock_full() you can call g_static_rec_mutex_lock_full() with the depth returned by this function.

mutex : | a GStaticRecMutex to completely unlock.
Returns : | number of times mutex has been locked by the current thread.

g_static_rec_mutex_free ()

void                g_static_rec_mutex_free             (GStaticRecMutex *mutex);

Releases all resources allocated to a GStaticRecMutex.

You don't have to call this functions for a GStaticRecMutex with an unbounded lifetime, i.e. objects declared 'static', but if you have a GStaticRecMutex as a member of a structure and the structure is freed, you should also free the GStaticRecMutex.

mutex : a GStaticRecMutex to be freed.

GStaticRWLock

typedef struct {
} GStaticRWLock;

The GStaticRWLock struct represents a read-write lock. A read-write lock can be used for protecting data that some portions of code only read from, while others also write. In such situations it is desirable that several readers can read at once, whereas of course only one writer may write at a time. Take a look at the following example:

Example 9. An array with access functions

  GStaticRWLock rwlock = G_STATIC_RW_LOCK_INIT;

  GPtrArray *array;

  gpointer my_array_get (guint index)
  {
    gpointer retval = NULL;

    if (!array)
      return NULL;

    g_static_rw_lock_reader_lock (&rwlock);

    if (index < array->len)
      retval = g_ptr_array_index (array, index);

    g_static_rw_lock_reader_unlock (&rwlock);

    return retval;
  }

  void my_array_set (guint index, gpointer data)
  {
    g_static_rw_lock_writer_lock (&rwlock);

    if (!array)
      array = g_ptr_array_new ();

    if (index >= array->len)
      g_ptr_array_set_size (array, index+1);

    g_ptr_array_index (array, index) = data;

    g_static_rw_lock_writer_unlock (&rwlock);
  }

This example shows an array which can be accessed by many readers (the my_array_get() function) simultaneously, whereas the writers (the my_array_set() function) will only be allowed once at a time and only if no readers currently access the array. This is because of the potentially dangerous resizing of the array. Using these functions is fully multi-thread safe now.

Most of the time, writers should have precedence over readers. That means, for this implementation, that as soon as a writer wants to lock the data, no other reader is allowed to lock the data, whereas, of course, the readers that already have locked the data are allowed to finish their operation. As soon as the last reader unlocks the data, the writer will lock it.

Even though GStaticRWLock is not opaque, it should only be used with the following functions.

All of the g_static_rw_lock_* functions can be used even if g_thread_init() has not been called.

Note

A read-write lock has a higher overhead than a mutex. For example, both g_static_rw_lock_reader_lock() and g_static_rw_lock_reader_unlock() have to lock and unlock a GStaticMutex, so it takes at least twice the time to lock and unlock a GStaticRWLock that it does to lock and unlock a GStaticMutex. So only data structures that are accessed by multiple readers, and which keep the lock for a considerable time justify a GStaticRWLock. The above example most probably would fare better with a GStaticMutex.

G_STATIC_RW_LOCK_INIT

#define G_STATIC_RW_LOCK_INIT { G_STATIC_MUTEX_INIT, NULL, NULL, 0, FALSE, 0, 0 }

A GStaticRWLock must be initialized with this macro before it can be used. This macro can used be to initialize a variable, but it cannot be assigned to a variable. In that case you have to use g_static_rw_lock_init().

GStaticRWLock my_lock = G_STATIC_RW_LOCK_INIT;

g_static_rw_lock_init ()

void                g_static_rw_lock_init               (GStaticRWLock *lock);

A GStaticRWLock must be initialized with this function before it can be used. Alternatively you can initialize it with G_STATIC_RW_LOCK_INIT.

lock : a GStaticRWLock to be initialized.

g_static_rw_lock_reader_lock ()

void                g_static_rw_lock_reader_lock        (GStaticRWLock *lock);

Locks lock for reading. There may be unlimited concurrent locks for reading of a GStaticRWLock at the same time. If lock is already locked for writing by another thread or if another thread is already waiting to lock lock for writing, this function will block until lock is unlocked by the other writing thread and no other writing threads want to lock lock. This lock has to be unlocked by g_static_rw_lock_reader_unlock().

GStaticRWLock is not recursive. It might seem to be possible to recursively lock for reading, but that can result in a deadlock, due to writer preference.

lock : a GStaticRWLock to lock for reading.

g_static_rw_lock_reader_trylock ()

gboolean            g_static_rw_lock_reader_trylock     (GStaticRWLock *lock);

Tries to lock lock for reading. If lock is already locked for writing by another thread or if another thread is already waiting to lock lock for writing, immediately returns FALSE. Otherwise locks lock for reading and returns TRUE. This lock has to be unlocked by g_static_rw_lock_reader_unlock().

lock : | a GStaticRWLock to lock for reading.
Returns : | TRUE, if lock could be locked for reading.

g_static_rw_lock_reader_unlock ()

void                g_static_rw_lock_reader_unlock      (GStaticRWLock *lock);

Unlocks lock. If a thread waits to lock lock for writing and all locks for reading have been unlocked, the waiting thread is woken up and can lock lock for writing.

lock : a GStaticRWLock to unlock after reading.

g_static_rw_lock_writer_lock ()

void                g_static_rw_lock_writer_lock        (GStaticRWLock *lock);

Locks lock for writing. If lock is already locked for writing or reading by other threads, this function will block until lock is completely unlocked and then lock lock for writing. While this functions waits to lock lock, no other thread can lock lock for reading. When lock is locked for writing, no other thread can lock lock (neither for reading nor writing). This lock has to be unlocked by g_static_rw_lock_writer_unlock().

lock : a GStaticRWLock to lock for writing.

g_static_rw_lock_writer_trylock ()

gboolean            g_static_rw_lock_writer_trylock     (GStaticRWLock *lock);

Tries to lock lock for writing. If lock is already locked (for either reading or writing) by another thread, it immediately returns FALSE. Otherwise it locks lock for writing and returns TRUE. This lock has to be unlocked by g_static_rw_lock_writer_unlock().

lock : | a GStaticRWLock to lock for writing.
Returns : | TRUE, if lock could be locked for writing.

g_static_rw_lock_writer_unlock ()

void                g_static_rw_lock_writer_unlock      (GStaticRWLock *lock);

Unlocks lock. If a thread is waiting to lock lock for writing and all locks for reading have been unlocked, the waiting thread is woken up and can lock lock for writing. If no thread is waiting to lock lock for writing, and some thread or threads are waiting to lock lock for reading, the waiting threads are woken up and can lock lock for reading.

lock : a GStaticRWLock to unlock after writing.

g_static_rw_lock_free ()

void                g_static_rw_lock_free               (GStaticRWLock *lock);

Releases all resources allocated to lock.

You don't have to call this functions for a GStaticRWLock with an unbounded lifetime, i.e. objects declared 'static', but if you have a GStaticRWLock as a member of a structure, and the structure is freed, you should also free the GStaticRWLock.

lock : a GStaticRWLock to be freed.

GCond

typedef struct _GCond GCond;

The GCond struct is an opaque data structure that represents a condition. Threads can block on a GCond if they find a certain condition to be false. If other threads change the state of this condition they signal the GCond, and that causes the waiting threads to be woken up.

Example 10. Using GCond to block a thread until a condition is satisfied

GCond* data_cond = NULL;   /* Must be initialized somewhere */
GMutex* data_mutex = NULL; /* Must be initialized somewhere */
gpointer current_data = NULL;

void push_data (gpointer data)
{
  g_mutex_lock (data_mutex);
  current_data = data;
  g_cond_signal (data_cond);
  g_mutex_unlock (data_mutex);
}

gpointer pop_data ()
{
  gpointer data;

  g_mutex_lock (data_mutex);
  while (!current_data)
      g_cond_wait (data_cond, data_mutex);
  data = current_data;
  current_data = NULL;
  g_mutex_unlock (data_mutex);
  return data;
}

Whenever a thread calls pop_data() now, it will wait until current_data is non-NULL, i.e. until some other thread has called push_data().

Note

It is important to use the g_cond_wait() and g_cond_timed_wait() functions only inside a loop which checks for the condition to be true. It is not guaranteed that the waiting thread will find the condition fulfilled after it wakes up, even if the signaling thread left the condition in that state: another thread may have altered the condition before the waiting thread got the chance to be woken up, even if the condition itself is protected by a GMutex, like above.

A GCond should only be accessed via the following functions.

Note

All of the g_cond_* functions are actually macros. Apart from taking their addresses, you can however use them as if they were functions.

g_cond_new ()

GCond*              g_cond_new                          ();

Creates a new GCond. This function will abort, if g_thread_init() has not been called yet.

Returns : a new GCond.

g_cond_signal ()

void                g_cond_signal                       (GCond *cond);

If threads are waiting for cond, exactly one of them is woken up. It is good practice to hold the same lock as the waiting thread while calling this function, though not required.

This function can be used even if g_thread_init() has not yet been called, and, in that case, will do nothing.

cond : a GCond.

g_cond_broadcast ()

void                g_cond_broadcast                    (GCond *cond);

If threads are waiting for cond, all of them are woken up. It is good practice to lock the same mutex as the waiting threads, while calling this function, though not required.

This function can be used even if g_thread_init() has not yet been called, and, in that case, will do nothing.

cond : a GCond.

g_cond_wait ()

void                g_cond_wait                         (GCond *cond,
                                                         GMutex *mutex);

Waits until this thread is woken up on cond. The mutex is unlocked before falling asleep and locked again before resuming.

This function can be used even if g_thread_init() has not yet been called, and, in that case, will immediately return.

cond : | a GCond.
mutex : | a GMutex, that is currently locked.

g_cond_timed_wait ()

gboolean            g_cond_timed_wait                   (GCond *cond,
                                                         GMutex *mutex,
                                                         GTimeVal *abs_time);

Waits until this thread is woken up on cond, but not longer than until the time specified by abs_time. The mutex is unlocked before falling asleep and locked again before resuming.

If abs_time is NULL, g_cond_timed_wait() acts like g_cond_wait().

This function can be used even if g_thread_init() has not yet been called, and, in that case, will immediately return TRUE.

To easily calculate abs_time a combination of g_get_current_time() and g_time_val_add() can be used.

cond : | a GCond.
mutex : | a GMutex that is currently locked.
abs_time : | a GTimeVal, determining the final time.
Returns : | TRUE if cond was signalled, or FALSE on timeout.

g_cond_free ()

void                g_cond_free                         (GCond *cond);

Destroys the GCond.

cond : a GCond.

GPrivate

typedef struct _GPrivate GPrivate;

The GPrivate struct is an opaque data structure to represent a thread private data key. Threads can thereby obtain and set a pointer which is private to the current thread. Take our give_me_next_number() example from above. Suppose we don't want current_number to be shared between the threads, but instead to be private to each thread. This can be done as follows:

Example 11. Using GPrivate for per-thread data

  GPrivate* current_number_key = NULL; /* Must be initialized somewhere */
                                       /* with g_private_new (g_free); */

  int give_me_next_number ()
  {
    int *current_number = g_private_get (current_number_key);

    if (!current_number)
    {
      current_number = g_new (int,1);
      *current_number = 0;
      g_private_set (current_number_key, current_number);
    }
    *current_number = calc_next_number (*current_number);
    return *current_number;
  }

Here the pointer belonging to the key current_number_key is read. If it is NULL, it has not been set yet. Then get memory for an integer value, assign this memory to the pointer and write the pointer back. Now we have an integer value that is private to the current thread.

The GPrivate struct should only be accessed via the following functions.

Note

All of the g_private_* functions are actually macros. Apart from taking their addresses, you can however use them as if they were functions.

g_private_new ()

GPrivate*           g_private_new                       (GDestroyNotify destructor);

Creates a new GPrivate. If destructor is non-NULL, it is a pointer to a destructor function. Whenever a thread ends and the corresponding pointer keyed to this instance of GPrivate is non-NULL, the destructor is called with this pointer as the argument.

Note

destructor is used quite differently from notify in g_static_private_set().

Note

A GPrivate can not be freed. Reuse it instead, if you can, to avoid shortage, or use GStaticPrivate.

Note

This function will abort if g_thread_init() has not been called yet.

destructor : | a function to destroy the data keyed to GPrivate when a thread ends.
Returns : | a new GPrivate.

g_private_get ()

gpointer            g_private_get                       (GPrivate *private_key);

Returns the pointer keyed to private_key for the current thread. If g_private_set() hasn't been called for the current private_key and thread yet, this pointer will be NULL.

This function can be used even if g_thread_init() has not yet been called, and, in that case, will return the value of private_key casted to gpointer.

private_key : | a GPrivate.
Returns : | the corresponding pointer.

g_private_set ()

void                g_private_set                       (GPrivate *private_key,
                                                         gpointer data);

Sets the pointer keyed to private_key for the current thread.

This function can be used even if g_thread_init() has not yet been called, and, in that case, will set private_key to data casted to GPrivate*.

private_key : | a GPrivate.
data : | the new pointer.

GStaticPrivate

typedef struct {
} GStaticPrivate;

A GStaticPrivate works almost like a GPrivate, but it has one significant advantage. It doesn't need to be created at run-time like a GPrivate, but can be defined at compile-time. This is similar to the difference between GMutex and GStaticMutex. Now look at our give_me_next_number() example with GStaticPrivate:

Example 12. Using GStaticPrivate for per-thread data

  int give_me_next_number ()
  {
    static GStaticPrivate current_number_key = G_STATIC_PRIVATE_INIT;
    int *current_number = g_static_private_get (&current_number_key);

    if (!current_number)
    {
      current_number = g_new (int,1);
      *current_number = 0;
      g_static_private_set (&current_number_key, current_number, g_free);
    }
    *current_number = calc_next_number (*current_number);
    return *current_number;
  }

G_STATIC_PRIVATE_INIT

#define G_STATIC_PRIVATE_INIT

Every GStaticPrivate must be initialized with this macro, before it can be used.

GStaticPrivate my_private = G_STATIC_PRIVATE_INIT;

g_static_private_init ()

void                g_static_private_init               (GStaticPrivate *private_key);

Initializes private_key. Alternatively you can initialize it with G_STATIC_PRIVATE_INIT.

private_key : a GStaticPrivate to be initialized.

g_static_private_get ()

gpointer            g_static_private_get                (GStaticPrivate *private_key);

Works like g_private_get() only for a GStaticPrivate.

This function works even if g_thread_init() has not yet been called.

private_key : | a GStaticPrivate.
Returns : | the corresponding pointer.

g_static_private_set ()

void                g_static_private_set                (GStaticPrivate *private_key,
                                                         gpointer data,
                                                         GDestroyNotify notify);

Sets the pointer keyed to private_key for the current thread and the function notify to be called with that pointer (NULL or non-NULL), whenever the pointer is set again or whenever the current thread ends.

This function works even if g_thread_init() has not yet been called. If g_thread_init() is called later, the data keyed to private_key will be inherited only by the main thread, i.e. the one that called g_thread_init().

Note

notify is used quite differently from destructor in g_private_new().

private_key : | a GStaticPrivate.
data : | the new pointer.
notify : | a function to be called with the pointer whenever the current thread ends or sets this pointer again.

g_static_private_free ()

void                g_static_private_free               (GStaticPrivate *private_key);

Releases all resources allocated to private_key.

You don't have to call this functions for a GStaticPrivate with an unbounded lifetime, i.e. objects declared 'static', but if you have a GStaticPrivate as a member of a structure and the structure is freed, you should also free the GStaticPrivate.

private_key : a GStaticPrivate to be freed.

GOnce

typedef struct {
  volatile GOnceStatus status;
  volatile gpointer retval;
} GOnce;

A GOnce struct controls a one-time initialization function. Any one-time initialization function must have its own unique GOnce struct.

volatile GOnceStatus status; | the status of the GOnce
volatile gpointer retval; | the value returned by the call to the function, if status is G_ONCE_STATUS_READY

Since 2.4

enum GOnceStatus

typedef enum
{
  G_ONCE_STATUS_NOTCALLED,
  G_ONCE_STATUS_PROGRESS,
  G_ONCE_STATUS_READY
} GOnceStatus;

The possible statuses of a one-time initialization function controlled by a GOnce struct.

G_ONCE_STATUS_NOTCALLED | the function has not been called yet.
G_ONCE_STATUS_PROGRESS | the function call is currently in progress.
G_ONCE_STATUS_READY | the function has been called.

Since 2.4

G_ONCE_INIT

#define G_ONCE_INIT { G_ONCE_STATUS_NOTCALLED, NULL }

A GOnce must be initialized with this macro before it can be used.

GOnce my_once = G_ONCE_INIT;

Since 2.4

g_once()

#define             g_once(once, func, arg)

The first call to this routine by a process with a given GOnce struct calls func with the given argument. Thereafter, subsequent calls to g_once() with the same GOnce struct do not call func again, but return the stored result of the first call. On return from g_once(), the status of once will be G_ONCE_STATUS_READY.

For example, a mutex or a thread-specific data key must be created exactly once. In a threaded environment, calling g_once() ensures that the initialization is serialized across multiple threads.

Note

Calling g_once() recursively on the same GOnce struct in func will lead to a deadlock.

gpointer
get_debug_flags ()
{
  static GOnce my_once = G_ONCE_INIT;

  g_once (&my_once, parse_debug_flags, NULL);

  return my_once.retval;
}

once : | a GOnce structure
func : | the GThreadFunc function associated to once. This function is called only once, regardless of the number of times it and its associated GOnce struct are passed to g_once() .
arg : | data to be passed to func

Since 2.4

See Also

GThreadPool | Thread pools.
GAsyncQueue | Send asynchronous messages between threads.


Timers

Timers — keep track of elapsed time.

Synopsis

#include <glib.h>

                    GTimer;
GTimer*             g_timer_new                         (void);
void                g_timer_start                       (GTimer *timer);
void                g_timer_stop                        (GTimer *timer);
void                g_timer_continue                    (GTimer *timer);
gdouble             g_timer_elapsed                     (GTimer *timer,
                                                         gulong *microseconds);
void                g_timer_reset                       (GTimer *timer);
void                g_timer_destroy                     (GTimer *timer);

Description

GTimer records a start time, and counts microseconds elapsed since that time. This is done somewhat differently on different platforms, and can be tricky to get exactly right, so GTimer provides a portable/convenient interface.

Details

GTimer

typedef struct _GTimer GTimer;

Opaque datatype that records a start time.

g_timer_new ()

GTimer*             g_timer_new                         (void);

Creates a new timer, and starts timing (i.e. g_timer_start() is implicitly called for you).

Returns : a new GTimer.

g_timer_start ()

void                g_timer_start                       (GTimer *timer);

Marks a start time, so that future calls to g_timer_elapsed() will report the time since g_timer_start() was called. g_timer_new() automatically marks the start time, so no need to call g_timer_start() immediately after creating the timer.

timer : a GTimer.

g_timer_stop ()

void                g_timer_stop                        (GTimer *timer);

Marks an end time, so calls to g_timer_elapsed() will return the difference between this end time and the start time.

timer : a GTimer.

g_timer_continue ()

void                g_timer_continue                    (GTimer *timer);

Resumes a timer that has previously been stopped with g_timer_stop(). g_timer_stop() must be called before using this function.

timer : a GTimer.

Since 2.4

g_timer_elapsed ()

gdouble             g_timer_elapsed                     (GTimer *timer,
                                                         gulong *microseconds);

If timer has been started but not stopped, obtains the time since the timer was started. If timer has been stopped, obtains the elapsed time between the time it was started and the time it was stopped. The return value is the number of seconds elapsed, including any fractional part. The microseconds out parameter is essentially useless.

timer : | a GTimer.
microseconds : | return location for the fractional part of seconds elapsed, in microseconds (that is, the total number of microseconds elapsed, modulo 1000000), or NULL
Returns : | seconds elapsed as a floating point value, including any fractional part.

g_timer_reset ()

void                g_timer_reset                       (GTimer *timer);

This function is useless; it's fine to call g_timer_start() on an already-started timer to reset the start time, so g_timer_reset() serves no purpose.

timer : a GTimer.

g_timer_destroy ()

void                g_timer_destroy                     (GTimer *timer);

Destroys a timer, freeing associated resources.

timer : a GTimer to destroy.


Trash Stacks

Trash Stacks — maintain a stack of unused allocated memory chunks.

Synopsis

#include <glib.h>

                    GTrashStack;
void                g_trash_stack_push                  (GTrashStack **stack_p,
                                                         gpointer data_p);
gpointer            g_trash_stack_pop                   (GTrashStack **stack_p);
gpointer            g_trash_stack_peek                  (GTrashStack **stack_p);
guint               g_trash_stack_height                (GTrashStack **stack_p);

Description

A GTrashStack is an efficient way to keep a stack of unused allocated memory chunks. Each memory chunk is required to be large enough to hold a gpointer. This allows the stack to be maintained without any space overhead, since the stack pointers can be stored inside the memory chunks.

There is no function to create a GTrashStack. A NULL GTrashStack* is a perfectly valid empty stack.

Details

GTrashStack

typedef struct {
  GTrashStack *next;
} GTrashStack;

Each piece of memory that is pushed onto the stack is cast to a GTrashStack*.

GTrashStack *next; pointer to the previous element of the stack, gets stored in the first sizeof (gpointer) bytes of the element.

g_trash_stack_push ()

void                g_trash_stack_push                  (GTrashStack **stack_p,
                                                         gpointer data_p);

Pushes a piece of memory onto a GTrashStack.

stack_p : | a pointer to a GTrashStack.
data_p : | the piece of memory to push on the stack.

g_trash_stack_pop ()

gpointer            g_trash_stack_pop                   (GTrashStack **stack_p);

Pops a piece of memory off a GTrashStack.

stack_p : | a pointer to a GTrashStack.
Returns : | the element at the top of the stack.

g_trash_stack_peek ()

gpointer            g_trash_stack_peek                  (GTrashStack **stack_p);

Returns the element at the top of a GTrashStack which may be NULL.

stack_p : | a pointer to a GTrashStack.
Returns : | the element at the top of the stack.

g_trash_stack_height ()

guint               g_trash_stack_height                (GTrashStack **stack_p);

Returns the height of a GTrashStack. Note that execution of this function is of O(N) complexity where N denotes the number of items on the stack.

stack_p : | a pointer to a GTrashStack.
Returns : | the height of the stack.


Type Conversion Macros

Type Conversion Macros — portably storing integers in pointer variables.

Synopsis

#include <glib.h>

#define             GINT_TO_POINTER                     (i)
#define             GPOINTER_TO_INT                     (p)

#define             GUINT_TO_POINTER                    (u)
#define             GPOINTER_TO_UINT                    (p)
#define             GSIZE_TO_POINTER                    (s)
#define             GPOINTER_TO_SIZE                    (p)

Description

Many times GLib, GTK+, and other libraries allow you to pass "user data" to a callback, in the form of a void pointer. From time to time you want to pass an integer instead of a pointer. You could allocate an integer, with something like:

 int *ip = g_new (int, 1);
 *ip = 42;

But this is inconvenient, and it's annoying to have to free the memory at some later time.

Pointers are always at least 32 bits in size (on all platforms GLib intends to support). Thus you can store at least 32-bit integer values in a pointer value. Naively, you might try this, but it's incorrect:

 gpointer p;
 int i;
 p = (void*) 42;
 i = (int) p;

Again, that example was not correct, don't copy it. The problem is that on some systems you need to do this:

 gpointer p;
 int i;
 p = (void*) (long) 42;
 i = (int) (long) p;

So GPOINTER_TO_INT(), GINT_TO_POINTER(), etc. do the right thing on the current platform.

Warning

YOU MAY NOT STORE POINTERS IN INTEGERS. THIS IS NOT PORTABLE IN ANY WAY SHAPE OR FORM. These macros ONLY allow storing integers in pointers, and only preserve 32 bits of the integer; values outside the range of a 32-bit integer will be mangled.

Details

GINT_TO_POINTER()

#define GINT_TO_POINTER(i)	((gpointer)  (i))

Stuffs an integer into a pointer type.

Remember, YOU MAY NOT STORE POINTERS IN INTEGERS. THIS IS NOT PORTABLE IN ANY WAY SHAPE OR FORM. These macros ONLY allow storing integers in pointers, and only preserve 32 bits of the integer; values outside the range of a 32-bit integer will be mangled.

i : integer to stuff into a pointer.

GPOINTER_TO_INT()

#define GPOINTER_TO_INT(p)	((gint)   (p))

Extracts an integer from a pointer. The integer must have been stored in the pointer with GINT_TO_POINTER().

Remember, YOU MAY NOT STORE POINTERS IN INTEGERS. THIS IS NOT PORTABLE IN ANY WAY SHAPE OR FORM. These macros ONLY allow storing integers in pointers, and only preserve 32 bits of the integer; values outside the range of a 32-bit integer will be mangled.

p : pointer containing an integer.

GUINT_TO_POINTER()

#define GUINT_TO_POINTER(u)	((gpointer)  (u))

Stuffs an unsigned integer into a pointer type.

u : unsigned integer to stuff into the pointer.

GPOINTER_TO_UINT()

#define GPOINTER_TO_UINT(p)	((guint)  (p))

Extracts an unsigned integer from a pointer. The integer must have been stored in the pointer with GUINT_TO_POINTER().

p : pointer to extract an unsigned integer from.

GSIZE_TO_POINTER()

#define GSIZE_TO_POINTER(s)	((gpointer) (gsize) (s))

Stuffs a gsize into a pointer type.

s : gsize to stuff into the pointer.

GPOINTER_TO_SIZE()

#define GPOINTER_TO_SIZE(p)	((gsize) (p))

Extracts a gsize from a pointer. The gsize must have been stored in the pointer with GSIZE_TO_POINTER().

p : pointer to extract a gsize from.


Unicode Manipulation

Unicode Manipulation — functions operating on Unicode characters and UTF-8 strings.

Synopsis

#include <glib.h>

typedef             gunichar;
typedef             gunichar2;

gboolean            g_unichar_validate                  (gunichar ch);
gboolean            g_unichar_isalnum                   (gunichar c);
gboolean            g_unichar_isalpha                   (gunichar c);
gboolean            g_unichar_iscntrl                   (gunichar c);
gboolean            g_unichar_isdigit                   (gunichar c);
gboolean            g_unichar_isgraph                   (gunichar c);
gboolean            g_unichar_islower                   (gunichar c);
gboolean            g_unichar_isprint                   (gunichar c);
gboolean            g_unichar_ispunct                   (gunichar c);
gboolean            g_unichar_isspace                   (gunichar c);
gboolean            g_unichar_isupper                   (gunichar c);
gboolean            g_unichar_isxdigit                  (gunichar c);
gboolean            g_unichar_istitle                   (gunichar c);
gboolean            g_unichar_isdefined                 (gunichar c);
gboolean            g_unichar_iswide                    (gunichar c);
gboolean            g_unichar_iswide_cjk                (gunichar c);
gunichar            g_unichar_toupper                   (gunichar c);
gunichar            g_unichar_tolower                   (gunichar c);
gunichar            g_unichar_totitle                   (gunichar c);
gint                g_unichar_digit_value               (gunichar c);
gint                g_unichar_xdigit_value              (gunichar c);
enum                GUnicodeType;
GUnicodeType        g_unichar_type                      (gunichar c);
enum                GUnicodeBreakType;
GUnicodeBreakType   g_unichar_break_type                (gunichar c);
void                g_unicode_canonical_ordering        (gunichar *string,
                                                         gsize len);
gunichar*           g_unicode_canonical_decomposition   (gunichar ch,
                                                         gsize *result_len);
gboolean            g_unichar_get_mirror_char           (gunichar ch,
                                                         gunichar *mirrored_ch);

#define             g_utf8_next_char                    (p)
gunichar            g_utf8_get_char                     (const gchar *p);
gunichar            g_utf8_get_char_validated           (const gchar *p,
                                                         gssize max_len);
gchar*              g_utf8_offset_to_pointer            (const gchar *str,
                                                         glong offset);
glong               g_utf8_pointer_to_offset            (const gchar *str,
                                                         const gchar *pos);
gchar*              g_utf8_prev_char                    (const gchar *p);
gchar*              g_utf8_find_next_char               (const gchar *p,
                                                         const gchar *end);
gchar*              g_utf8_find_prev_char               (const gchar *str,
                                                         const gchar *p);
glong               g_utf8_strlen                       (const gchar *p,
                                                         gssize max);
gchar*              g_utf8_strncpy                      (gchar *dest,
                                                         const gchar *src,
                                                         gsize n);
gchar*              g_utf8_strchr                       (const gchar *p,
                                                         gssize len,
                                                         gunichar c);
gchar*              g_utf8_strrchr                      (const gchar *p,
                                                         gssize len,
                                                         gunichar c);
gchar*              g_utf8_strreverse                   (const gchar *str,
                                                         gssize len);
gboolean            g_utf8_validate                     (const gchar *str,
                                                         gssize max_len,
                                                         const gchar **end);

gchar*              g_utf8_strup                        (const gchar *str,
                                                         gssize len);
gchar*              g_utf8_strdown                      (const gchar *str,
                                                         gssize len);
gchar*              g_utf8_casefold                     (const gchar *str,
                                                         gssize len);
gchar*              g_utf8_normalize                    (const gchar *str,
                                                         gssize len,
                                                         GNormalizeMode mode);
enum                GNormalizeMode;
gint                g_utf8_collate                      (const gchar *str1,
                                                         const gchar *str2);
gchar*              g_utf8_collate_key                  (const gchar *str,
                                                         gssize len);
gchar*              g_utf8_collate_key_for_filename     (const gchar *str,
                                                         gssize len);

gunichar2*          g_utf8_to_utf16                     (const gchar *str,
                                                         glong len,
                                                         glong *items_read,
                                                         glong *items_written,
                                                         GError **error);
gunichar*           g_utf8_to_ucs4                      (const gchar *str,
                                                         glong len,
                                                         glong *items_read,
                                                         glong *items_written,
                                                         GError **error);
gunichar*           g_utf8_to_ucs4_fast                 (const gchar *str,
                                                         glong len,
                                                         glong *items_written);
gunichar*           g_utf16_to_ucs4                     (const gunichar2 *str,
                                                         glong len,
                                                         glong *items_read,
                                                         glong *items_written,
                                                         GError **error);
gchar*              g_utf16_to_utf8                     (const gunichar2 *str,
                                                         glong len,
                                                         glong *items_read,
                                                         glong *items_written,
                                                         GError **error);
gunichar2*          g_ucs4_to_utf16                     (const gunichar *str,
                                                         glong len,
                                                         glong *items_read,
                                                         glong *items_written,
                                                         GError **error);
gchar*              g_ucs4_to_utf8                      (const gunichar *str,
                                                         glong len,
                                                         glong *items_read,
                                                         glong *items_written,
                                                         GError **error);
gint                g_unichar_to_utf8                   (gunichar c,
                                                         gchar *outbuf);

Description

This section describes a number of functions for dealing with Unicode characters and strings. There are analogues of the traditional ctype.h character classification and case conversion functions, UTF-8 analogues of some string utility functions, functions to perform normalization, case conversion and collation on UTF-8 strings and finally functions to convert between the UTF-8, UTF-16 and UCS-4 encodings of Unicode.

The implementations of the Unicode functions in GLib are based on the Unicode Character Data tables, which are available from www.unicode.org. GLib 2.8 supports Unicode 4.0, GLib 2.10 supports Unicode 4.1, GLib 2.12 supports Unicode 5.0.

Details

gunichar

typedef guint32 gunichar;

A type which can hold any UCS-4 character code.

gunichar2

typedef guint16 gunichar2;

A type which can hold any UTF-16 code point[3].

g_unichar_validate ()

gboolean            g_unichar_validate                  (gunichar ch);

Checks whether ch is a valid Unicode character. Some possible integer values of ch will not be valid. 0 is considered a valid character, though it's normally a string terminator.

ch : | a Unicode character
Returns : | TRUE if ch is a valid Unicode character

g_unichar_isalnum ()

gboolean            g_unichar_isalnum                   (gunichar c);

Determines whether a character is alphanumeric. Given some UTF-8 text, obtain a character value with g_utf8_get_char().

c : | a Unicode character
Returns : | TRUE if c is an alphanumeric character

g_unichar_isalpha ()

gboolean            g_unichar_isalpha                   (gunichar c);

Determines whether a character is alphabetic (i.e. a letter). Given some UTF-8 text, obtain a character value with g_utf8_get_char().

c : | a Unicode character
Returns : | TRUE if c is an alphabetic character

g_unichar_iscntrl ()

gboolean            g_unichar_iscntrl                   (gunichar c);

Determines whether a character is a control character. Given some UTF-8 text, obtain a character value with g_utf8_get_char().

c : | a Unicode character
Returns : | TRUE if c is a control character

g_unichar_isdigit ()

gboolean            g_unichar_isdigit                   (gunichar c);

Determines whether a character is numeric (i.e. a digit). This covers ASCII 0-9 and also digits in other languages/scripts. Given some UTF-8 text, obtain a character value with g_utf8_get_char().

c : | a Unicode character
Returns : | TRUE if c is a digit

g_unichar_isgraph ()

gboolean            g_unichar_isgraph                   (gunichar c);

Determines whether a character is printable and not a space (returns FALSE for control characters, format characters, and spaces). g_unichar_isprint() is similar, but returns TRUE for spaces. Given some UTF-8 text, obtain a character value with g_utf8_get_char().

c : | a Unicode character
Returns : | TRUE if c is printable unless it's a space

g_unichar_islower ()

gboolean            g_unichar_islower                   (gunichar c);

Determines whether a character is a lowercase letter. Given some UTF-8 text, obtain a character value with g_utf8_get_char().

c : | a Unicode character
Returns : | TRUE if c is a lowercase letter

g_unichar_isprint ()

gboolean            g_unichar_isprint                   (gunichar c);

Determines whether a character is printable. Unlike g_unichar_isgraph(), returns TRUE for spaces. Given some UTF-8 text, obtain a character value with g_utf8_get_char().

c : | a Unicode character
Returns : | TRUE if c is printable

g_unichar_ispunct ()

gboolean            g_unichar_ispunct                   (gunichar c);

Determines whether a character is punctuation or a symbol. Given some UTF-8 text, obtain a character value with g_utf8_get_char().

c : | a Unicode character
Returns : | TRUE if c is a punctuation or symbol character

g_unichar_isspace ()

gboolean            g_unichar_isspace                   (gunichar c);

Determines whether a character is a space, tab, or line separator (newline, carriage return, etc.). Given some UTF-8 text, obtain a character value with g_utf8_get_char().

(Note: don't use this to do word breaking; you have to use Pango or equivalent to get word breaking right, the algorithm is fairly complex.)

c : | a Unicode character
Returns : | TRUE if c is a space character

g_unichar_isupper ()

gboolean            g_unichar_isupper                   (gunichar c);

Determines if a character is uppercase.

c : | a Unicode character
Returns : | TRUE if c is an uppercase character

g_unichar_isxdigit ()

gboolean            g_unichar_isxdigit                  (gunichar c);

Determines if a character is a hexidecimal digit.

c : | a Unicode character.
Returns : | TRUE if the character is a hexadecimal digit

g_unichar_istitle ()

gboolean            g_unichar_istitle                   (gunichar c);

Determines if a character is titlecase. Some characters in Unicode which are composites, such as the DZ digraph have three case variants instead of just two. The titlecase form is used at the beginning of a word where only the first letter is capitalized. The titlecase form of the DZ digraph is U+01F2 LATIN CAPITAL LETTTER D WITH SMALL LETTER Z.

c : | a Unicode character
Returns : | TRUE if the character is titlecase

g_unichar_isdefined ()

gboolean            g_unichar_isdefined                 (gunichar c);

Determines if a given character is assigned in the Unicode standard.

c : | a Unicode character
Returns : | TRUE if the character has an assigned value

g_unichar_iswide ()

gboolean            g_unichar_iswide                    (gunichar c);

Determines if a character is typically rendered in a double-width cell.

c : | a Unicode character
Returns : | TRUE if the character is wide

g_unichar_iswide_cjk ()

gboolean            g_unichar_iswide_cjk                (gunichar c);

Determines if a character is typically rendered in a double-width cell under legacy East Asian locales. If a character is wide according to g_unichar_iswide(), then it is also reported wide with this function, but the converse is not necessarily true. See the Unicode Standard Annex 11 for details.

c : | a Unicode character
Returns : | TRUE if the character is wide in legacy East Asian locales

Since 2.12

g_unichar_toupper ()

gunichar            g_unichar_toupper                   (gunichar c);

Converts a character to uppercase.

c : | a Unicode character
Returns : | the result of converting c to uppercase. If c is not an lowercase or titlecase character, or has no upper case equivalent c is returned unchanged.

g_unichar_tolower ()

gunichar            g_unichar_tolower                   (gunichar c);

Converts a character to lower case.

c : | a Unicode character.
Returns : | the result of converting c to lower case. If c is not an upperlower or titlecase character, or has no lowercase equivalent c is returned unchanged.

g_unichar_totitle ()

gunichar            g_unichar_totitle                   (gunichar c);

Converts a character to the titlecase.

c : | a Unicode character
Returns : | the result of converting c to titlecase. If c is not an uppercase or lowercase character, c is returned unchanged.

g_unichar_digit_value ()

gint                g_unichar_digit_value               (gunichar c);

Determines the numeric value of a character as a decimal digit.

c : | a Unicode character
Returns : | If c is a decimal digit (according to g_unichar_isdigit()), its numeric value. Otherwise, -1.

g_unichar_xdigit_value ()

gint                g_unichar_xdigit_value              (gunichar c);

Determines the numeric value of a character as a hexidecimal digit.

c : | a Unicode character
Returns : | If c is a hex digit (according to g_unichar_isxdigit()), its numeric value. Otherwise, -1.

enum GUnicodeType

typedef enum
{
  G_UNICODE_CONTROL,
  G_UNICODE_FORMAT,
  G_UNICODE_UNASSIGNED,
  G_UNICODE_PRIVATE_USE,
  G_UNICODE_SURROGATE,
  G_UNICODE_LOWERCASE_LETTER,
  G_UNICODE_MODIFIER_LETTER,
  G_UNICODE_OTHER_LETTER,
  G_UNICODE_TITLECASE_LETTER,
  G_UNICODE_UPPERCASE_LETTER,
  G_UNICODE_COMBINING_MARK,
  G_UNICODE_ENCLOSING_MARK,
  G_UNICODE_NON_SPACING_MARK,
  G_UNICODE_DECIMAL_NUMBER,
  G_UNICODE_LETTER_NUMBER,
  G_UNICODE_OTHER_NUMBER,
  G_UNICODE_CONNECT_PUNCTUATION,
  G_UNICODE_DASH_PUNCTUATION,
  G_UNICODE_CLOSE_PUNCTUATION,
  G_UNICODE_FINAL_PUNCTUATION,
  G_UNICODE_INITIAL_PUNCTUATION,
  G_UNICODE_OTHER_PUNCTUATION,
  G_UNICODE_OPEN_PUNCTUATION,
  G_UNICODE_CURRENCY_SYMBOL,
  G_UNICODE_MODIFIER_SYMBOL,
  G_UNICODE_MATH_SYMBOL,
  G_UNICODE_OTHER_SYMBOL,
  G_UNICODE_LINE_SEPARATOR,
  G_UNICODE_PARAGRAPH_SEPARATOR,
  G_UNICODE_SPACE_SEPARATOR
} GUnicodeType;

These are the possible character classifications. See http://www.unicode.org/Public/UNIDATA/UnicodeData.html.

g_unichar_type ()

GUnicodeType        g_unichar_type                      (gunichar c);

Classifies a Unicode character by type.

c : | a Unicode character
Returns : | the type of the character.

enum GUnicodeBreakType

typedef enum
{
  G_UNICODE_BREAK_MANDATORY,
  G_UNICODE_BREAK_CARRIAGE_RETURN,
  G_UNICODE_BREAK_LINE_FEED,
  G_UNICODE_BREAK_COMBINING_MARK,
  G_UNICODE_BREAK_SURROGATE,
  G_UNICODE_BREAK_ZERO_WIDTH_SPACE,
  G_UNICODE_BREAK_INSEPARABLE,
  G_UNICODE_BREAK_NON_BREAKING_GLUE,
  G_UNICODE_BREAK_CONTINGENT,
  G_UNICODE_BREAK_SPACE,
  G_UNICODE_BREAK_AFTER,
  G_UNICODE_BREAK_BEFORE,
  G_UNICODE_BREAK_BEFORE_AND_AFTER,
  G_UNICODE_BREAK_HYPHEN,
  G_UNICODE_BREAK_NON_STARTER,
  G_UNICODE_BREAK_OPEN_PUNCTUATION,
  G_UNICODE_BREAK_CLOSE_PUNCTUATION,
  G_UNICODE_BREAK_QUOTATION,
  G_UNICODE_BREAK_EXCLAMATION,
  G_UNICODE_BREAK_IDEOGRAPHIC,
  G_UNICODE_BREAK_NUMERIC,
  G_UNICODE_BREAK_INFIX_SEPARATOR,
  G_UNICODE_BREAK_SYMBOL,
  G_UNICODE_BREAK_ALPHABETIC,
  G_UNICODE_BREAK_PREFIX,
  G_UNICODE_BREAK_POSTFIX,
  G_UNICODE_BREAK_COMPLEX_CONTEXT,
  G_UNICODE_BREAK_AMBIGUOUS,
  G_UNICODE_BREAK_UNKNOWN,
  G_UNICODE_BREAK_NEXT_LINE,
  G_UNICODE_BREAK_WORD_JOINER,
  G_UNICODE_BREAK_HANGUL_L_JAMO,
  G_UNICODE_BREAK_HANGUL_V_JAMO,
  G_UNICODE_BREAK_HANGUL_T_JAMO,
  G_UNICODE_BREAK_HANGUL_LV_SYLLABLE,
  G_UNICODE_BREAK_HANGUL_LVT_SYLLABLE
} GUnicodeBreakType;

These are the possible line break classifications. The five Hangul types were added in Unicode 4.1, so, has been introduced in GLib 2.10. Note that new types may be added in the future. Applications should be ready to handle unknown values. They may be regarded as G_UNICODE_BREAK_UNKNOWN. See http://www.unicode.org/unicode/reports/tr14/.

g_unichar_break_type ()

GUnicodeBreakType   g_unichar_break_type                (gunichar c);

Determines the break type of c. c should be a Unicode character (to derive a character from UTF-8 encoded text, use g_utf8_get_char()). The break type is used to find word and line breaks ("text boundaries"), Pango implements the Unicode boundary resolution algorithms and normally you would use a function such as pango_break() instead of caring about break types yourself.

c : | a Unicode character
Returns : | the break type of c

g_unicode_canonical_ordering ()

void                g_unicode_canonical_ordering        (gunichar *string,
                                                         gsize len);

Computes the canonical ordering of a string in-place. This rearranges decomposed characters in the string according to their combining classes. See the Unicode manual for more information.

string : | a UCS-4 encoded string.
len : | the maximum length of string to use.

g_unicode_canonical_decomposition ()

gunichar*           g_unicode_canonical_decomposition   (gunichar ch,
                                                         gsize *result_len);

Computes the canonical decomposition of a Unicode character.

ch : | a Unicode character.
result_len : | location to store the length of the return value.
Returns : | a newly allocated string of Unicode characters. result_len is set to the resulting length of the string.

g_unichar_get_mirror_char ()

gboolean            g_unichar_get_mirror_char           (gunichar ch,
                                                         gunichar *mirrored_ch);

In Unicode, some characters are mirrored. This means that their images are mirrored horizontally in text that is laid out from right to left. For instance, "(" would become its mirror image, ")", in right-to-left text.

If ch has the Unicode mirrored property and there is another unicode character that typically has a glyph that is the mirror image of ch's glyph and mirrored_ch is set, it puts that character in the address pointed to by mirrored_ch. Otherwise the original character is put.

ch : | a Unicode character
mirrored_ch : | location to store the mirrored character
Returns : | TRUE if ch has a mirrored character, FALSE otherwise

Since 2.4

g_utf8_next_char()

#define             g_utf8_next_char(p)

Skips to the next character in a UTF-8 string. The string must be valid; this macro is as fast as possible, and has no error-checking. You would use this macro to iterate over a string character by character. The macro returns the start of the next UTF-8 character. Before using this macro, use g_utf8_validate() to validate strings that may contain invalid UTF-8.

p : Pointer to the start of a valid UTF-8 character.

g_utf8_get_char ()

gunichar            g_utf8_get_char                     (const gchar *p);

Converts a sequence of bytes encoded as UTF-8 to a Unicode character. If p does not point to a valid UTF-8 encoded character, results are undefined. If you are not sure that the bytes are complete valid Unicode characters, you should use g_utf8_get_char_validated() instead.

p : | a pointer to Unicode character encoded as UTF-8
Returns : | the resulting character

g_utf8_get_char_validated ()

gunichar            g_utf8_get_char_validated           (const gchar *p,
                                                         gssize max_len);

Convert a sequence of bytes encoded as UTF-8 to a Unicode character. This function checks for incomplete characters, for invalid characters such as characters that are out of the range of Unicode, and for overlong encodings of valid characters.

p : | a pointer to Unicode character encoded as UTF-8
max_len : | the maximum number of bytes to read, or -1, for no maximum.
Returns : | the resulting character. If p points to a partial sequence at the end of a string that could begin a valid character (or if max_len is zero), returns (gunichar)-2; otherwise, if p does not point to a valid UTF-8 encoded Unicode character, returns (gunichar)-1.

g_utf8_offset_to_pointer ()

gchar*              g_utf8_offset_to_pointer            (const gchar *str,
                                                         glong offset);

Converts from an integer character offset to a pointer to a position within the string.

Since 2.10, this function allows to pass a negative offset to step backwards. It is usually worth stepping backwards from the end instead of forwards if offset is in the last fourth of the string, since moving forward is about 3 times faster than moving backward.

str : | a UTF-8 encoded string
offset : | a character offset within str
Returns : | the resulting pointer

g_utf8_pointer_to_offset ()

glong               g_utf8_pointer_to_offset            (const gchar *str,
                                                         const gchar *pos);

Converts from a pointer to position within a string to a integer character offset.

Since 2.10, this function allows pos to be before str, and returns a negative offset in this case.

str : | a UTF-8 encoded string
pos : | a pointer to a position within str
Returns : | the resulting character offset

g_utf8_prev_char ()

gchar*              g_utf8_prev_char                    (const gchar *p);

Finds the previous UTF-8 character in the string before p.

p does not have to be at the beginning of a UTF-8 character. No check is made to see if the character found is actually valid other than it starts with an appropriate byte. If p might be the first character of the string, you must use g_utf8_find_prev_char() instead.

p : | a pointer to a position within a UTF-8 encoded string
Returns : | a pointer to the found character.

g_utf8_find_next_char ()

gchar*              g_utf8_find_next_char               (const gchar *p,
                                                         const gchar *end);

Finds the start of the next UTF-8 character in the string after p.

p does not have to be at the beginning of a UTF-8 character. No check is made to see if the character found is actually valid other than it starts with an appropriate byte.

p : | a pointer to a position within a UTF-8 encoded string
end : | a pointer to the end of the string, or NULL to indicate that the string is nul-terminated, in which case the returned value will be
Returns : | a pointer to the found character or NULL

g_utf8_find_prev_char ()

gchar*              g_utf8_find_prev_char               (const gchar *str,
                                                         const gchar *p);

Given a position p with a UTF-8 encoded string str, find the start of the previous UTF-8 character starting before p. Returns NULL if no UTF-8 characters are present in str before p.

p does not have to be at the beginning of a UTF-8 character. No check is made to see if the character found is actually valid other than it starts with an appropriate byte.

str : | pointer to the beginning of a UTF-8 encoded string
p : | pointer to some position within str
Returns : | a pointer to the found character or NULL.

g_utf8_strlen ()

glong               g_utf8_strlen                       (const gchar *p,
                                                         gssize max);

Returns the length of the string in characters.

p : | pointer to the start of a UTF-8 encoded string.
max : | the maximum number of bytes to examine. If max is less than 0, then the string is assumed to be nul-terminated. If max is 0, p will not be examined and may be NULL.
Returns : | the length of the string in characters

g_utf8_strncpy ()

gchar*              g_utf8_strncpy                      (gchar *dest,
                                                         const gchar *src,
                                                         gsize n);

Like the standard C strncpy() function, but copies a given number of characters instead of a given number of bytes. The src string must be valid UTF-8 encoded text. (Use g_utf8_validate() on all text before trying to use UTF-8 utility functions with it.)

dest : | buffer to fill with characters from src
src : | UTF-8 encoded string
n : | character count
Returns : | dest

g_utf8_strchr ()

gchar*              g_utf8_strchr                       (const gchar *p,
                                                         gssize len,
                                                         gunichar c);

Finds the leftmost occurrence of the given Unicode character in a UTF-8 encoded string, while limiting the search to len bytes. If len is -1, allow unbounded search.

p : | a nul-terminated UTF-8 encoded string
len : | the maximum length of p
c : | a Unicode character
Returns : | NULL if the string does not contain the character, otherwise, a pointer to the start of the leftmost occurrence of the character in the string.

g_utf8_strrchr ()

gchar*              g_utf8_strrchr                      (const gchar *p,
                                                         gssize len,
                                                         gunichar c);

Find the rightmost occurrence of the given Unicode character in a UTF-8 encoded string, while limiting the search to len bytes. If len is -1, allow unbounded search.

p : | a nul-terminated UTF-8 encoded string
len : | the maximum length of p
c : | a Unicode character
Returns : | NULL if the string does not contain the character, otherwise, a pointer to the start of the rightmost occurrence of the character in the string.

g_utf8_strreverse ()

gchar*              g_utf8_strreverse                   (const gchar *str,
                                                         gssize len);

Reverses a UTF-8 string. str must be valid UTF-8 encoded text. (Use g_utf8_validate() on all text before trying to use UTF-8 utility functions with it.)

Note that unlike g_strreverse(), this function returns newly-allocated memory, which should be freed with g_free() when no longer needed.

str : | a UTF-8 encoded string
len : | the maximum length of str to use. If len < 0, then the string is nul-terminated.
Returns : | a newly-allocated string which is the reverse of str.

Since 2.2

g_utf8_validate ()

gboolean            g_utf8_validate                     (const gchar *str,
                                                         gssize max_len,
                                                         const gchar **end);

Validates UTF-8 encoded text. str is the text to validate; if str is nul-terminated, then max_len can be -1, otherwise max_len should be the number of bytes to validate. If end is non-NULL, then the end of the valid range will be stored there (i.e. the start of the first invalid character if some bytes were invalid, or the end of the text being validated otherwise).

Note that g_utf8_validate() returns FALSE if max_len is positive and NUL is met before max_len bytes have been read.

Returns TRUE if all of str was valid. Many GLib and GTK+ routines require valid UTF-8 as input; so data read from a file or the network should be checked with g_utf8_validate() before doing anything else with it.

str : | a pointer to character data
max_len : | max bytes to validate, or -1 to go until NUL
end : | return location for end of valid data
Returns : | TRUE if the text was valid UTF-8

g_utf8_strup ()

gchar*              g_utf8_strup                        (const gchar *str,
                                                         gssize len);

Converts all Unicode characters in the string that have a case to uppercase. The exact manner that this is done depends on the current locale, and may result in the number of characters in the string increasing. (For instance, the German ess-zet will be changed to SS.)

str : | a UTF-8 encoded string
len : | length of str, in bytes, or -1 if str is nul-terminated.
Returns : | a newly allocated string, with all characters converted to uppercase.

g_utf8_strdown ()

gchar*              g_utf8_strdown                      (const gchar *str,
                                                         gssize len);

Converts all Unicode characters in the string that have a case to lowercase. The exact manner that this is done depends on the current locale, and may result in the number of characters in the string changing.

str : | a UTF-8 encoded string
len : | length of str, in bytes, or -1 if str is nul-terminated.
Returns : | a newly allocated string, with all characters converted to lowercase.

g_utf8_casefold ()

gchar*              g_utf8_casefold                     (const gchar *str,
                                                         gssize len);

Converts a string into a form that is independent of case. The result will not correspond to any particular case, but can be compared for equality or ordered with the results of calling g_utf8_casefold() on other strings.

Note that calling g_utf8_casefold() followed by g_utf8_collate() is only an approximation to the correct linguistic case insensitive ordering, though it is a fairly good one. Getting this exactly right would require a more sophisticated collation function that takes case sensitivity into account. GLib does not currently provide such a function.

str : | a UTF-8 encoded string
len : | length of str, in bytes, or -1 if str is nul-terminated.
Returns : | a newly allocated string, that is a case independent form of str.

g_utf8_normalize ()

gchar*              g_utf8_normalize                    (const gchar *str,
                                                         gssize len,
                                                         GNormalizeMode mode);

Converts a string into canonical form, standardizing such issues as whether a character with an accent is represented as a base character and combining accent or as a single precomposed character. You should generally call g_utf8_normalize() before comparing two Unicode strings.

The normalization mode G_NORMALIZE_DEFAULT only standardizes differences that do not affect the text content, such as the above-mentioned accent representation. G_NORMALIZE_ALL also standardizes the "compatibility" characters in Unicode, such as SUPERSCRIPT THREE to the standard forms (in this case DIGIT THREE). Formatting information may be lost but for most text operations such characters should be considered the same. For example, g_utf8_collate() normalizes with G_NORMALIZE_ALL as its first step.

G_NORMALIZE_DEFAULT_COMPOSE and G_NORMALIZE_ALL_COMPOSE are like G_NORMALIZE_DEFAULT and G_NORMALIZE_ALL, but returned a result with composed forms rather than a maximally decomposed form. This is often useful if you intend to convert the string to a legacy encoding or pass it to a system with less capable Unicode handling.

str : | a UTF-8 encoded string.
len : | length of str, in bytes, or -1 if str is nul-terminated.
mode : | the type of normalization to perform.
Returns : | a newly allocated string, that is the normalized form of str.

enum GNormalizeMode

typedef enum {
  G_NORMALIZE_DEFAULT,
  G_NORMALIZE_NFD = G_NORMALIZE_DEFAULT,
  G_NORMALIZE_DEFAULT_COMPOSE,
  G_NORMALIZE_NFC = G_NORMALIZE_DEFAULT_COMPOSE,
  G_NORMALIZE_ALL,
  G_NORMALIZE_NFKD = G_NORMALIZE_ALL,
  G_NORMALIZE_ALL_COMPOSE,
  G_NORMALIZE_NFKC = G_NORMALIZE_ALL_COMPOSE
} GNormalizeMode;

Defines how a Unicode string is transformed in a canonical form, standardizing such issues as whether a character with an accent is represented as a base character and combining accent or as a single precomposed character. Unicode strings should generally be normalized before comparing them.

G_NORMALIZE_DEFAULT | standardize differences that do not affect the text content, such as the above-mentioned accent representation.
G_NORMALIZE_NFD | another name for G_NORMALIZE_DEFAULT.
G_NORMALIZE_DEFAULT_COMPOSE | like G_NORMALIZE_DEFAULT, but with composed forms rather than a maximally decomposed form.
G_NORMALIZE_NFC | another name for G_NORMALIZE_DEFAULT_COMPOSE.
G_NORMALIZE_ALL | beyond G_NORMALIZE_DEFAULT also standardize the "compatibility" characters in Unicode, such as SUPERSCRIPT THREE to the standard forms (in this case DIGIT THREE). Formatting information may be lost but for most text operations such characters should be considered the same.
G_NORMALIZE_NFKD | another name for G_NORMALIZE_ALL.
G_NORMALIZE_ALL_COMPOSE | like G_NORMALIZE_ALL, but with composed forms rather than a maximally decomposed form.
G_NORMALIZE_NFKC | another name for G_NORMALIZE_ALL_COMPOSE.

g_utf8_collate ()

gint                g_utf8_collate                      (const gchar *str1,
                                                         const gchar *str2);

Compares two strings for ordering using the linguistically correct rules for the current locale. When sorting a large number of strings, it will be significantly faster to obtain collation keys with g_utf8_collate_key() and compare the keys with strcmp() when sorting instead of sorting the original strings.

str1 : | a UTF-8 encoded string
str2 : | a UTF-8 encoded string
Returns : | < 0 if str1 compares before str2, 0 if they compare equal, > 0 if str1 compares after str2.

g_utf8_collate_key ()

gchar*              g_utf8_collate_key                  (const gchar *str,
                                                         gssize len);

Converts a string into a collation key that can be compared with other collation keys produced by the same function using strcmp(). The results of comparing the collation keys of two strings with strcmp() will always be the same as comparing the two original keys with g_utf8_collate().

str : | a UTF-8 encoded string.
len : | length of str, in bytes, or -1 if str is nul-terminated.
Returns : | a newly allocated string. This string should be freed with g_free() when you are done with it.

g_utf8_collate_key_for_filename ()

gchar*              g_utf8_collate_key_for_filename     (const gchar *str,
                                                         gssize len);

Converts a string into a collation key that can be compared with other collation keys produced by the same function using strcmp().

In order to sort filenames correctly, this function treats the dot '.' as a special case. Most dictionary orderings seem to consider it insignificant, thus producing the ordering "event.c" "eventgenerator.c" "event.h" instead of "event.c" "event.h" "eventgenerator.c". Also, we would like to treat numbers intelligently so that "file1" "file10" "file5" is sorted as "file1" "file5" "file10".

str : | a UTF-8 encoded string.
len : | length of str, in bytes, or -1 if str is nul-terminated.
Returns : | a newly allocated string. This string should be freed with g_free() when you are done with it.

Since 2.8

g_utf8_to_utf16 ()

gunichar2*          g_utf8_to_utf16                     (const gchar *str,
                                                         glong len,
                                                         glong *items_read,
                                                         glong *items_written,
                                                         GError **error);

Convert a string from UTF-8 to UTF-16. A 0 character will be added to the result after the converted text.

str : | a UTF-8 encoded string
len : | the maximum length (number of characters) of str to use. If len < 0, then the string is nul-terminated.
items_read : | location to store number of bytes read, or NULL. If NULL, then G_CONVERT_ERROR_PARTIAL_INPUT will be returned in case str contains a trailing partial character. If an error occurs then the index of the invalid input is stored here.
items_written : | location to store number of gunichar2 written, or NULL. The value stored here does not include the trailing 0.
error : | location to store the error occuring, or NULL to ignore errors. Any of the errors in GConvertError other than G_CONVERT_ERROR_NO_CONVERSION may occur.
Returns : | a pointer to a newly allocated UTF-16 string. This value must be freed with g_free(). If an error occurs, NULL will be returned and error set.

g_utf8_to_ucs4 ()

gunichar*           g_utf8_to_ucs4                      (const gchar *str,
                                                         glong len,
                                                         glong *items_read,
                                                         glong *items_written,
                                                         GError **error);

Convert a string from UTF-8 to a 32-bit fixed width representation as UCS-4. A trailing 0 will be added to the string after the converted text.

str : | a UTF-8 encoded string
len : | the maximum length of str to use. If len < 0, then the string is nul-terminated.
items_read : | location to store number of bytes read, or NULL. If NULL, then G_CONVERT_ERROR_PARTIAL_INPUT will be returned in case str contains a trailing partial character. If an error occurs then the index of the invalid input is stored here.
items_written : | location to store number of characters written or NULL. The value here stored does not include the trailing 0 character.
error : | location to store the error occuring, or NULL to ignore errors. Any of the errors in GConvertError other than G_CONVERT_ERROR_NO_CONVERSION may occur.
Returns : | a pointer to a newly allocated UCS-4 string. This value must be freed with g_free(). If an error occurs, NULL will be returned and error set.

g_utf8_to_ucs4_fast ()

gunichar*           g_utf8_to_ucs4_fast                 (const gchar *str,
                                                         glong len,
                                                         glong *items_written);

Convert a string from UTF-8 to a 32-bit fixed width representation as UCS-4, assuming valid UTF-8 input. This function is roughly twice as fast as g_utf8_to_ucs4() but does no error checking on the input.

str : | a UTF-8 encoded string
len : | the maximum length of str to use. If len < 0, then the string is nul-terminated.
items_written : | location to store the number of characters in the result, or NULL.
Returns : | a pointer to a newly allocated UCS-4 string. This value must be freed with g_free().

g_utf16_to_ucs4 ()

gunichar*           g_utf16_to_ucs4                     (const gunichar2 *str,
                                                         glong len,
                                                         glong *items_read,
                                                         glong *items_written,
                                                         GError **error);

Convert a string from UTF-16 to UCS-4. The result will be terminated with a 0 character.

str : | a UTF-16 encoded string
len : | the maximum length (number of gunichar2) of str to use. If len < 0, then the string is terminated with a 0 character.
items_read : | location to store number of words read, or NULL. If NULL, then G_CONVERT_ERROR_PARTIAL_INPUT will be returned in case str contains a trailing partial character. If an error occurs then the index of the invalid input is stored here.
items_written : | location to store number of characters written, or NULL. The value stored here does not include the trailing 0 character.
error : | location to store the error occuring, or NULL to ignore errors. Any of the errors in GConvertError other than G_CONVERT_ERROR_NO_CONVERSION may occur.
Returns : | a pointer to a newly allocated UCS-4 string. This value must be freed with g_free(). If an error occurs, NULL will be returned and error set.

g_utf16_to_utf8 ()

gchar*              g_utf16_to_utf8                     (const gunichar2 *str,
                                                         glong len,
                                                         glong *items_read,
                                                         glong *items_written,
                                                         GError **error);

Convert a string from UTF-16 to UTF-8. The result will be terminated with a 0 byte.

Note that the input is expected to be already in native endianness, an initial byte-order-mark character is not handled specially. g_convert() can be used to convert a byte buffer of UTF-16 data of ambiguous endianess.

str : | a UTF-16 encoded string
len : | the maximum length (number of gunichar2) of str to use. If len < 0, then the string is terminated with a 0 character.
items_read : | location to store number of words read, or NULL. If NULL, then G_CONVERT_ERROR_PARTIAL_INPUT will be returned in case str contains a trailing partial character. If an error occurs then the index of the invalid input is stored here.
items_written : | location to store number of bytes written, or NULL. The value stored here does not include the trailing 0 byte.
error : | location to store the error occuring, or NULL to ignore errors. Any of the errors in GConvertError other than G_CONVERT_ERROR_NO_CONVERSION may occur.
Returns : | a pointer to a newly allocated UTF-8 string. This value must be freed with g_free(). If an error occurs, NULL will be returned and error set.

g_ucs4_to_utf16 ()

gunichar2*          g_ucs4_to_utf16                     (const gunichar *str,
                                                         glong len,
                                                         glong *items_read,
                                                         glong *items_written,
                                                         GError **error);

Convert a string from UCS-4 to UTF-16. A 0 character will be added to the result after the converted text.

str : | a UCS-4 encoded string
len : | the maximum length (number of characters) of str to use. If len < 0, then the string is terminated with a 0 character.
items_read : | location to store number of bytes read, or NULL. If an error occurs then the index of the invalid input is stored here.
items_written : | location to store number of gunichar2 written, or NULL. The value stored here does not include the trailing 0.
error : | location to store the error occuring, or NULL to ignore errors. Any of the errors in GConvertError other than G_CONVERT_ERROR_NO_CONVERSION may occur.
Returns : | a pointer to a newly allocated UTF-16 string. This value must be freed with g_free(). If an error occurs, NULL will be returned and error set.

g_ucs4_to_utf8 ()

gchar*              g_ucs4_to_utf8                      (const gunichar *str,
                                                         glong len,
                                                         glong *items_read,
                                                         glong *items_written,
                                                         GError **error);

Convert a string from a 32-bit fixed width representation as UCS-4. to UTF-8. The result will be terminated with a 0 byte.

str : | a UCS-4 encoded string
len : | the maximum length (number of characters) of str to use. If len < 0, then the string is terminated with a 0 character.
items_read : | location to store number of characters read, or NULL.
items_written : | location to store number of bytes written or NULL. The value here stored does not include the trailing 0 byte.
error : | location to store the error occuring, or NULL to ignore errors. Any of the errors in GConvertError other than G_CONVERT_ERROR_NO_CONVERSION may occur.
Returns : | a pointer to a newly allocated UTF-8 string. This value must be freed with g_free(). If an error occurs, NULL will be returned and error set. In that case, items_read will be set to the position of the first invalid input character.

g_unichar_to_utf8 ()

gint                g_unichar_to_utf8                   (gunichar c,
                                                         gchar *outbuf);

Converts a single character to UTF-8.

c : | a Unicode character code
outbuf : | output buffer, must have at least 6 bytes of space. If NULL, the length will be computed and returned and nothing will be written to outbuf.
Returns : | number of bytes written

See Also

g_locale_to_utf8(), g_locale_from_utf8()

Convenience functions for converting between UTF-8 and the locale encoding.

[3] surrogate pairs


GLib Utilities

String Utility Functions — various string-related functions.
Character Set Conversion — convert strings between different character sets using iconv().
Unicode Manipulation — functions operating on Unicode characters and UTF-8 strings.
Base64 Encoding — encodes and decodes data in Base64 format
Internationalization — gettext support macros.
Date and Time Functions — calendrical calculations and miscellaneous time stuff.
Random Numbers — pseudo-random number generator.
Hook Functions — support for manipulating lists of hook functions.
Miscellaneous Utility Functions — a selection of portable utility functions.
Lexical Scanner — a general purpose lexical scanner.
Automatic String Completion — support for automatic completion using a group of target strings.
Timers — keep track of elapsed time.
Spawning Processes — process launching with fork()/exec().
File Utilities — various file-related functions.
Shell-related Utilities — shell-like commandline handling.
Commandline option parser — parses commandline options
Glob-style pattern matching — matches strings against patterns containing '*' (wildcard) and '?' (joker).
Simple XML Subset Parser — parses a subset of XML.
Key-value file parser — parses .ini-like config files
Bookmark file parser — parses files containing bookmarks
Windows Compatibility Functions — UNIX emulation on Windows.


Version Information

Version Information — Variables and functions to check the GLib version

Synopsis

#include <glib.h>

extern              const guint glib_major_version;
extern              const guint glib_minor_version;
extern              const guint glib_micro_version;
extern              const guint glib_binary_age;
extern              const guint glib_interface_age;
const gchar*        glib_check_version                  (guint required_major,
                                                         guint required_minor,
                                                         guint required_micro);

#define             GLIB_MAJOR_VERSION
#define             GLIB_MINOR_VERSION
#define             GLIB_MICRO_VERSION
#define             GLIB_CHECK_VERSION                  (major,minor,micro)

Description

GLib provides version information, primarily useful in configure checks for builds that have a configure script. Applications will not typically use the features described here.

Details

glib_major_version

extern const guint glib_major_version;

The major version number of the GLib library. (e.g. in GLib version 1.2.5 this is 1.)

This variable is in the library, so represents the GLib library you have linked against. Contrast with the GLIB_MAJOR_VERSION macro, which represents the major version of the GLib headers you have included.

glib_minor_version

extern const guint glib_minor_version;

The minor version number of the GLib library. (e.g. in GLib version 1.2.5 this is 2.)

This variable is in the library, so represents the GLib library you have linked against. Contrast with the GLIB_MINOR_VERSION macro, which represents the minor version of the GLib headers you have included.

glib_micro_version

extern const guint glib_micro_version;

The micro version number of the GLib library. (e.g. in GLib version 1.2.5 this is 5.)

This variable is in the library, so represents the GLib library you have linked against. Contrast with the GLIB_MICRO_VERSION macro, which represents the micro version of the GLib headers you have included.

glib_binary_age

extern const guint glib_binary_age;

This is the binary age passed to libtool. If libtool means nothing to you, don't worry about it. ;-)

glib_interface_age

extern const guint glib_interface_age;

This is the interface age passed to libtool. If libtool means nothing to you, don't worry about it. ;-)

glib_check_version ()

const gchar*        glib_check_version                  (guint required_major,
                                                         guint required_minor,
                                                         guint required_micro);

Checks that the GLib library in use is compatible with the given version. Generally you would pass in the constants GLIB_MAJOR_VERSION, GLIB_MINOR_VERSION, GLIB_MICRO_VERSION as the three arguments to this function; that produces a check that the library in use is compatible with the version of GLib the application or module was compiled against.

Compatibility is defined by two things: first the version of the running library is newer than the version required_major.required_minor.required_micro. Second the running library must be binary compatible with the version required_major.required_minor.required_micro (same major version.)

required_major : | the required major version.
required_minor : | the required minor version.
required_micro : | the required micro version.
Returns : | NULL if the GLib library is compatible with the given version, or a string describing the version mismatch. The returned string is owned by GLib and must not be modified or freed.

Since 2.6

GLIB_MAJOR_VERSION

#define GLIB_MAJOR_VERSION 2

The major version number of the GLib library. Like glib_major_version, but from the headers used at application compile time, rather than from the library linked against at application run time.

GLIB_MINOR_VERSION

#define GLIB_MINOR_VERSION 12

The minor version number of the GLib library. Like gtk_minor_version, but from the headers used at application compile time, rather than from the library linked against at application run time.

GLIB_MICRO_VERSION

#define GLIB_MICRO_VERSION 11

The micro version number of the GLib library. Like gtk_micro_version, but from the headers used at application compile time, rather than from the library linked against at application run time.

GLIB_CHECK_VERSION()

#define             GLIB_CHECK_VERSION(major,minor,micro)

Checks the version of the GLib library. Returns TRUE if the version of the GLib header files is the same as or newer than the passed-in version.

Example 1. Checking the version of the GLib library

  if (!GLIB_CHECK_VERSION (1, 2, 0))
    g_error ("GLib version 1.2.0 or above is needed");

major : | the major version number.
minor : | the minor version number.
micro : | the micro version number.


Message Output and Debugging Functions

Message Output and Debugging Functions — functions to output messages and help debug applications.

Synopsis

#include <glib.h>

void                g_print                             (const gchar *format,
                                                         ...);
GPrintFunc          g_set_print_handler                 (GPrintFunc func);
void                (*GPrintFunc)                       (const gchar *string);

void                g_printerr                          (const gchar *format,
                                                         ...);
GPrintFunc          g_set_printerr_handler              (GPrintFunc func);

#define             g_return_if_fail                    (expr)
#define             g_return_val_if_fail                (expr,val)
#define             g_return_if_reached                 ()
#define             g_return_val_if_reached             (val)

#define             g_assert                            (expr)
#define             g_assert_not_reached                ()

void                g_on_error_query                    (const gchar *prg_name);
void                g_on_error_stack_trace              (const gchar *prg_name);

#define             G_BREAKPOINT                        ()

Description

These functions provide support for outputting messages.

Details

g_print ()

void                g_print                             (const gchar *format,
                                                         ...);

Outputs a formatted message via the print handler. The default print handler simply outputs the message to stdout.

g_print() should not be used from within libraries for debugging messages, since it may be redirected by applications to special purpose message windows or even files. Instead, libraries should use g_log(), or the convenience functions g_message(), g_warning() and g_error().

format : | the message format. See the printf() documentation.
... : | the parameters to insert into the format string.

g_set_print_handler ()

GPrintFunc          g_set_print_handler                 (GPrintFunc func);

Sets the print handler. Any messages passed to g_print() will be output via the new handler. The default handler simply outputs the message to stdout. By providing your own handler you can redirect the output, to a GTK+ widget or a log file for example.

func : | the new print handler.
Returns : | the old print handler.

GPrintFunc ()

void                (*GPrintFunc)                       (const gchar *string);

Specifies the type of the print handler functions. These are called with the complete formatted string to output.

string : the message to be output.

g_printerr ()

void                g_printerr                          (const gchar *format,
                                                         ...);

Outputs a formatted message via the error message handler. The default handler simply outputs the message to stderr.

g_printerr() should not be used from within libraries. Instead g_log() should be used, or the convenience functions g_message(), g_warning() and g_error().

format : | the message format. See the printf() documentation.
... : | the parameters to insert into the format string.

g_set_printerr_handler ()

GPrintFunc          g_set_printerr_handler              (GPrintFunc func);

Sets the handler for printing error messages. Any messages passed to g_printerr() will be output via the new handler. The default handler simply outputs the message to stderr. By providing your own handler you can redirect the output, to a GTK+ widget or a log file for example.

func : | the new error message handler.
Returns : | the old error message handler.

g_return_if_fail()

#define             g_return_if_fail(expr)

Returns from the current function if the expression is not true. If the expression evaluates to FALSE, a critical message is logged and the function returns. This can only be used in functions which do not return a value.

expr : the expression to check.

g_return_val_if_fail()

#define             g_return_val_if_fail(expr,val)

Returns from the current function, returning the value val, if the expression is not true. If the expression evaluates to FALSE, a critical message is logged and val is returned.

expr : | the expression to check.
val : | the value to return from the current function if the expression is not true.

g_return_if_reached()

#define             g_return_if_reached()

Logs a critical message and returns from the current function. This can only be used in functions which do not return a value.

g_return_val_if_reached()

#define             g_return_val_if_reached(val)

Logs a critical message and returns val.

val : the value to return from the current function.

g_assert()

#define             g_assert(expr)

Debugging macro to terminate the application if the assertion fails. If the assertion fails (i.e. the expression is not true), an error message is logged and the application is terminated.

The macro can be turned off in final releases of code by defining G_DISABLE_ASSERT when compiling the application.

expr : the expression to check.

g_assert_not_reached()

#define             g_assert_not_reached()

Debugging macro to terminate the application if it is ever reached. If it is reached, an error message is logged and the application is terminated.

The macro can be turned off in final releases of code by defining G_DISABLE_ASSERT when compiling the application.

g_on_error_query ()

void                g_on_error_query                    (const gchar *prg_name);

Prompts the user with [E]xit, [H]alt, show [S]tack trace or [P]roceed. This function is intended to be used for debugging use only. The following example shows how it can be used together with the g_log() functions.

#include <glib.h>

static void
log_handler (const gchar   *log_domain,
         GLogLevelFlags log_level,
         const gchar   *message,
         gpointer       user_data)
{
  g_log_default_handler (log_domain, log_level, message, user_data);

  g_on_error_query (MY_PROGRAM_NAME);
}

int main (int argc, char *argv[])
{
  g_log_set_handler (MY_LOG_DOMAIN,
             G_LOG_LEVEL_WARNING |
                     G_LOG_LEVEL_ERROR |
                     G_LOG_LEVEL_CRITICAL,
             log_handler,
             NULL);

 /* ... */

If [E]xit is selected, the application terminates with a call to _exit(0).

If [H]alt is selected, the application enters an infinite loop. The infinite loop can only be stopped by killing the application, or by setting glib_on_error_halt to FALSE (possibly via a debugger).

If [S]tack trace is selected, g_on_error_stack_trace() is called. This invokes gdb, which attaches to the current process and shows a stack trace. The prompt is then shown again.

If [P]roceed is selected, the function returns.

This function may cause different actions on non-UNIX platforms.

prg_name : the program name, needed by gdb for the [S]tack trace option. If prg_name is NULL, g_get_prgname() is called to get the program name (which will work correctly if gdk_init() or gtk_init() has been called).

g_on_error_stack_trace ()

void                g_on_error_stack_trace              (const gchar *prg_name);

Invokes gdb, which attaches to the current process and shows a stack trace. Called by g_on_error_query() when the [S]tack trace option is selected.

This function may cause different actions on non-UNIX platforms.

prg_name : the program name, needed by gdb for the [S]tack trace option. If prg_name is NULL, g_get_prgname() is called to get the program name (which will work correctly if gdk_init() or gtk_init() has been called).

G_BREAKPOINT()

#define             G_BREAKPOINT()

Inserts a breakpoint instruction into the code (on x86 machines only).


Windows Compatibility Functions

Windows Compatibility Functions — UNIX emulation on Windows.

Synopsis

#include <glib.h>

#define             MAXPATHLEN
#define             pipe                                (phandles)
gchar*              g_win32_error_message               (gint error);
gchar*              g_win32_getlocale                   (void);
gchar*              g_win32_get_package_installation_directory
                                                        (gchar *package,
                                                         gchar *dll_name);
gchar*              g_win32_get_package_installation_subdirectory
                                                        (gchar *package,
                                                         gchar *dll_name,
                                                         gchar *subdir);
guint               g_win32_get_windows_version         (void);
gchar*              g_win32_locale_filename_from_utf8   (const gchar *utf8filename);
#define             G_WIN32_DLLMAIN_FOR_DLL_NAME        (static, dll_name)
#define             G_WIN32_HAVE_WIDECHAR_API           ()
#define             G_WIN32_IS_NT_BASED                 ()

Description

These functions provide some level of UNIX emulation on the Windows platform. If your application really needs the POSIX APIs, we suggest you try the Cygwin project.

Details

MAXPATHLEN

#define MAXPATHLEN 1024

Provided for UNIX emulation on Windows; equivalent to UNIX macro MAXPATHLEN, which is the maximum length of a filename (including full path).

pipe()

#define pipe(phandles)	_pipe (phandles, 4096, _O_BINARY)

Provided for UNIX emulation on Windows; see documentation for pipe() in any UNIX manual.

phandles : file descriptors, the first one for reading, the second one for writing.

g_win32_error_message ()

gchar*              g_win32_error_message               (gint error);

Translate a Win32 error code (as returned by GetLastError()) into the corresponding message. The message is either language neutral, or in the thread's language, or the user's language, the system's language, or US English (see docs for FormatMessage()). The returned string is in UTF-8. It should be deallocated with g_free().

error : | error code.
Returns : | newly-allocated error message

g_win32_getlocale ()

gchar*              g_win32_getlocale                   (void);

The setlocale() function in the Microsoft C library uses locale names of the form "English_United States.1252" etc. We want the UNIXish standard form "en_US", "zh_TW" etc. This function gets the current thread locale from Windows - without any encoding info - and returns it as a string of the above form for use in forming file names etc. The returned string should be deallocated with g_free().

Returns : newly-allocated locale name.

g_win32_get_package_installation_directory ()

gchar*              g_win32_get_package_installation_directory
                                                        (gchar *package,
                                                         gchar *dll_name);

Try to determine the installation directory for a software package. Typically used by GNU software packages.

package should be a short identifier for the package. Typically it is the same identifier as used for GETTEXT_PACKAGE in software configured according to GNU standards. The function first looks in the Windows Registry for the value #InstallationDirectory in the key #HKLM\Software\package, and if that value exists and is a string, returns that.

If package is NULL, or the above value isn't found in the Registry, but dll_name is non-NULL, it should name a DLL loaded into the current process. Typically that would be the name of the DLL calling this function, looking for its installation directory. The function then asks Windows what directory that DLL was loaded from. If that directory's last component is "bin" or "lib", the parent directory is returned, otherwise the directory itself. If that DLL isn't loaded, the function proceeds as if dll_name was NULL.

If both package and dll_name are NULL, the directory from where the main executable of the process was loaded is used instead in the same way as above.

package : | An identifier for a software package, or NULL, in UTF-8
dll_name : | The name of a DLL that a package provides, or NULL, in UTF-8
Returns : | a string containing the installation directory for package. The string is in the GLib file name encoding, i.e. UTF-8 on Windows. The return value should be freed with g_free() when not needed any longer.

g_win32_get_package_installation_subdirectory ()

gchar*              g_win32_get_package_installation_subdirectory
                                                        (gchar *package,
                                                         gchar *dll_name,
                                                         gchar *subdir);

Returns a newly-allocated string containing the path of the subdirectory subdir in the return value from calling g_win32_get_package_installation_directory() with the package and dll_name parameters.

package : | An identifier for a software package, in UTF-8, or NULL
dll_name : | The name of a DLL that a package provides, in UTF-8, or NULL
subdir : | A subdirectory of the package installation directory, also in UTF-8
Returns : | a string containing the complete path to subdir inside the installation directory of package. The returned string is in the GLib file name encoding, i.e. UTF-8 on Windows. The return value should be freed with g_free() when no longer needed.

g_win32_get_windows_version ()

guint               g_win32_get_windows_version         (void);

Returns version information for the Windows operating system the code is running on. See MSDN documentation for the GetVersion() function. To summarize, the most significant bit is one on Win9x, and zero on NT-based systems. The least significant byte is 4 on Windows NT 4, 5 on Windows XP. Software that needs really detailled version and feature information should use Win32 API like GetVersionEx() and VerifyVersionInfo().

If there is an environment variable G_WIN32_PRETEND_WIN9X defined (with any value), this function always returns a version code for Windows 9x. This is mainly an internal debugging aid for GTK+ and GLib developers, to be able to check the code paths for Windows 9x.

Returns : The version information.

Since 2.6

g_win32_locale_filename_from_utf8 ()

gchar*              g_win32_locale_filename_from_utf8   (const gchar *utf8filename);

Converts a filename from UTF-8 to the system codepage.

On NT-based Windows, on NTFS file systems, file names are in Unicode. It is quite possible that Unicode file names contain characters not representable in the system codepage. (For instance, Greek or Cyrillic characters on Western European or US Windows installations, or various less common CJK characters on CJK Windows installations.)

In such a case, and if the filename refers to an existing file, and the file system stores alternate short (8.3) names for directory entries, the short form of the filename is returned. Note that the "short" name might in fact be longer than the Unicode name if the Unicode name has very short pathname components containing non-ASCII characters. If no system codepage name for the file is possible, NULL is returned.

The return value is dynamically allocated and should be freed with g_free() when no longer needed.

utf8filename : | a UTF-8 encoded filename.
Returns : | The converted filename, or NULL on conversion failure and lack of short names.

Since 2.8

G_WIN32_DLLMAIN_FOR_DLL_NAME()

#define             G_WIN32_DLLMAIN_FOR_DLL_NAME(static, dll_name)

On Windows, this macro defines a DllMain() function that stores the actual DLL name that the code being compiled will be included in.

On non-Windows platforms, expands to nothing.

static : | empty or "static".
dll_name : | the name of the (pointer to the) char array where the DLL name will be stored. If this is used, you must also include windows.h. If you need a more complex DLL entry point function, you cannot use this.

G_WIN32_HAVE_WIDECHAR_API()

#define G_WIN32_HAVE_WIDECHAR_API() (G_WIN32_IS_NT_BASED ())

On Windows, this macro defines an expression which evaluates to TRUE if the code is running on a version of Windows where the wide character versions of the Win32 API functions, and the wide chaacter versions of the C library functions work. (They are always present in the DLLs, but don't work on Windows 9x and Me.)

On non-Windows platforms, it is not defined.

Since 2.6

G_WIN32_IS_NT_BASED()

#define G_WIN32_IS_NT_BASED() (g_win32_get_windows_version () < 0x80000000)

On Windows, this macro defines an expression which evaluates to TRUE if the code is running on an NT-based Windows operating system.

On non-Windows platforms, it is not defined.

Since 2.6


Index

Symbols

_, _()

A

ABS, ABS()

C

CLAMP, CLAMP()

F

FALSE, FALSE

G

GAllocator, GAllocator
GArray, GArray
GAsyncQueue, GAsyncQueue
GBookmarkFile, GBookmarkFile
GBookmarkFileError, enum GBookmarkFileError
gboolean, gboolean
GByteArray, GByteArray
GCache, GCache
GCacheDestroyFunc, GCacheDestroyFunc ()
GCacheDupFunc, GCacheDupFunc ()
GCacheNewFunc, GCacheNewFunc ()
gchar, gchar
GChildWatchFunc, GChildWatchFunc ()
GCompareDataFunc, GCompareDataFunc ()
GCompareFunc, GCompareFunc ()
GCompletion, GCompletion
GCompletionFunc, GCompletionFunc ()
GCompletionStrncmpFunc, GCompletionStrncmpFunc ()
GCond, GCond
gconstpointer, gconstpointer
GConvertError, enum GConvertError
GCopyFunc, GCopyFunc ()
GData, GData
GDataForeachFunc, GDataForeachFunc ()
GDate, GDate
GDateDay, GDateDay
GDateDMY, enum GDateDMY
GDateMonth, enum GDateMonth
GDateWeekday, enum GDateWeekday
GDateYear, GDateYear
GDebugKey, GDebugKey
GDestroyNotify, GDestroyNotify ()
GDir, GDir
gdouble, gdouble
GDoubleIEEE754, union GDoubleIEEE754
GEqualFunc, GEqualFunc ()
GError, GError
GErrorType, enum GErrorType
GFileError, enum GFileError
GFileTest, enum GFileTest
gfloat, gfloat
GFloatIEEE754, union GFloatIEEE754
GFreeFunc, GFreeFunc ()
GFunc, GFunc ()
GHashFunc, GHashFunc ()
GHashTable, GHashTable
GHFunc, GHFunc ()
GHook, GHook
GHookCheckFunc, GHookCheckFunc ()
GHookCheckMarshaller, GHookCheckMarshaller ()
GHookCompareFunc, GHookCompareFunc ()
GHookFinalizeFunc, GHookFinalizeFunc ()
GHookFindFunc, GHookFindFunc ()
GHookFlagMask, enum GHookFlagMask
GHookFunc, GHookFunc ()
GHookList, GHookList
GHookMarshaller, GHookMarshaller ()
GHRFunc, GHRFunc ()
GIConv, GIConv
gint, gint
gint16, gint16
GINT16_FROM_BE, GINT16_FROM_BE()
GINT16_FROM_LE, GINT16_FROM_LE()
GINT16_TO_BE, GINT16_TO_BE()
GINT16_TO_LE, GINT16_TO_LE()
gint32, gint32
GINT32_FROM_BE, GINT32_FROM_BE()
GINT32_FROM_LE, GINT32_FROM_LE()
GINT32_TO_BE, GINT32_TO_BE()
GINT32_TO_LE, GINT32_TO_LE()
gint64, gint64
GINT64_FROM_BE, GINT64_FROM_BE()
GINT64_FROM_LE, GINT64_FROM_LE()
GINT64_TO_BE, GINT64_TO_BE()
GINT64_TO_LE, GINT64_TO_LE()
gint8, gint8
GINT_FROM_BE, GINT_FROM_BE()
GINT_FROM_LE, GINT_FROM_LE()
GINT_TO_BE, GINT_TO_BE()
GINT_TO_LE, GINT_TO_LE()
GINT_TO_POINTER, GINT_TO_POINTER()
GIOChannel, GIOChannel
GIOChannelError, enum GIOChannelError
GIOCondition, enum GIOCondition
GIOError, enum GIOError
GIOFlags, enum GIOFlags
GIOFunc, GIOFunc ()
GIOFuncs, GIOFuncs
GIOStatus, enum GIOStatus
GKeyFile, GKeyFile
GKeyFileError, enum GKeyFileError
GKeyFileFlags, enum GKeyFileFlags
glib_binary_age, glib_binary_age
glib_check_version, glib_check_version ()
GLIB_CHECK_VERSION, GLIB_CHECK_VERSION()
glib_interface_age, glib_interface_age
glib_major_version, glib_major_version
GLIB_MAJOR_VERSION, GLIB_MAJOR_VERSION
glib_mem_profiler_table, glib_mem_profiler_table
glib_micro_version, glib_micro_version
GLIB_MICRO_VERSION, GLIB_MICRO_VERSION
glib_minor_version, glib_minor_version
GLIB_MINOR_VERSION, GLIB_MINOR_VERSION
GList, GList
GLogFunc, GLogFunc ()
GLogLevelFlags, enum GLogLevelFlags
glong, glong
GLONG_FROM_BE, GLONG_FROM_BE()
GLONG_FROM_LE, GLONG_FROM_LE()
GLONG_TO_BE, GLONG_TO_BE()
GLONG_TO_LE, GLONG_TO_LE()
GMainContext, GMainContext
GMainLoop, GMainLoop
GMappedFile, GMappedFile
GMarkupError, enum GMarkupError
GMarkupParseContext, GMarkupParseContext
GMarkupParseFlags, enum GMarkupParseFlags
GMarkupParser, GMarkupParser
GMemChunk, GMemChunk
GMemVTable, GMemVTable
GModule, GModule
GModuleCheckInit, GModuleCheckInit ()
GModuleFlags, enum GModuleFlags
GModuleUnload, GModuleUnload ()
GMutex, GMutex
GNode, GNode
GNodeForeachFunc, GNodeForeachFunc ()
GNodeTraverseFunc, GNodeTraverseFunc ()
GNormalizeMode, enum GNormalizeMode
GOnce, GOnce
GOnceStatus, enum GOnceStatus
GOptionArg, enum GOptionArg
GOptionArgFunc, GOptionArgFunc ()
GOptionContext, GOptionContext
GOptionEntry, GOptionEntry
GOptionError, enum GOptionError
GOptionErrorFunc, GOptionErrorFunc ()
GOptionFlags, enum GOptionFlags
GOptionGroup, GOptionGroup
GOptionParseFunc, GOptionParseFunc ()
GPatternSpec, GPatternSpec
GPid, GPid
gpointer, gpointer
GPOINTER_TO_INT, GPOINTER_TO_INT()
GPOINTER_TO_SIZE, GPOINTER_TO_SIZE()
GPOINTER_TO_UINT, GPOINTER_TO_UINT()
GPollFD, GPollFD
GPollFunc, GPollFunc ()
GPrintFunc, GPrintFunc ()
GPrivate, GPrivate
GPtrArray, GPtrArray
GQuark, GQuark
GQueue, GQueue
GRand, GRand
GRelation, GRelation
GScanner, GScanner
GScannerConfig, GScannerConfig
GScannerMsgFunc, GScannerMsgFunc ()
GSeekType, enum GSeekType
GShellError, enum GShellError
gshort, gshort
gsize, gsize
GSIZE_TO_POINTER, GSIZE_TO_POINTER()
GSList, GSList
GSource, GSource
GSourceCallbackFuncs, GSourceCallbackFuncs
GSourceDummyMarshal, GSourceDummyMarshal ()
GSourceFunc, GSourceFunc ()
GSourceFuncs, GSourceFuncs
GSpawnChildSetupFunc, GSpawnChildSetupFunc ()
GSpawnError, enum GSpawnError
GSpawnFlags, enum GSpawnFlags
gssize, gssize
GStaticMutex, GStaticMutex
GStaticPrivate, GStaticPrivate
GStaticRecMutex, GStaticRecMutex
GStaticRWLock, GStaticRWLock
GString, GString
GStringChunk, GStringChunk
GThread, GThread
GThreadError, enum GThreadError
GThreadFunc, GThreadFunc ()
GThreadFunctions, GThreadFunctions
GThreadPool, GThreadPool
GThreadPriority, enum GThreadPriority
GTime, GTime
GTimer, GTimer
GTimeVal, GTimeVal
GTokenType, enum GTokenType
GTokenValue, union GTokenValue
GTranslateFunc, GTranslateFunc ()
GTrashStack, GTrashStack
GTraverseFlags, enum GTraverseFlags
GTraverseFunc, GTraverseFunc ()
GTraverseType, enum GTraverseType
GTree, GTree
GTuples, GTuples
guchar, guchar
guint, guint
guint16, guint16
GUINT16_FROM_BE, GUINT16_FROM_BE()
GUINT16_FROM_LE, GUINT16_FROM_LE()
GUINT16_SWAP_BE_PDP, GUINT16_SWAP_BE_PDP()
GUINT16_SWAP_LE_BE, GUINT16_SWAP_LE_BE()
GUINT16_SWAP_LE_PDP, GUINT16_SWAP_LE_PDP()
GUINT16_TO_BE, GUINT16_TO_BE()
GUINT16_TO_LE, GUINT16_TO_LE()
guint32, guint32
GUINT32_FROM_BE, GUINT32_FROM_BE()
GUINT32_FROM_LE, GUINT32_FROM_LE()
GUINT32_SWAP_BE_PDP, GUINT32_SWAP_BE_PDP()
GUINT32_SWAP_LE_BE, GUINT32_SWAP_LE_BE()
GUINT32_SWAP_LE_PDP, GUINT32_SWAP_LE_PDP()
GUINT32_TO_BE, GUINT32_TO_BE()
GUINT32_TO_LE, GUINT32_TO_LE()
guint64, guint64 ()
GUINT64_FROM_BE, GUINT64_FROM_BE()
GUINT64_FROM_LE, GUINT64_FROM_LE()
GUINT64_SWAP_LE_BE, GUINT64_SWAP_LE_BE()
GUINT64_TO_BE, GUINT64_TO_BE()
GUINT64_TO_LE, GUINT64_TO_LE()
guint8, guint8
GUINT_FROM_BE, GUINT_FROM_BE()
GUINT_FROM_LE, GUINT_FROM_LE()
GUINT_TO_BE, GUINT_TO_BE()
GUINT_TO_LE, GUINT_TO_LE()
GUINT_TO_POINTER, GUINT_TO_POINTER()
gulong, gulong
GULONG_FROM_BE, GULONG_FROM_BE()
GULONG_FROM_LE, GULONG_FROM_LE()
GULONG_TO_BE, GULONG_TO_BE()
GULONG_TO_LE, GULONG_TO_LE()
gunichar, gunichar
gunichar2, gunichar2
GUnicodeBreakType, enum GUnicodeBreakType
GUnicodeType, enum GUnicodeType
gushort, gushort
GVoidFunc, GVoidFunc ()
g_access, g_access ()
g_alloca, g_alloca()
g_allocator_free, g_allocator_free ()
g_allocator_new, g_allocator_new ()
G_ALLOC_AND_FREE, G_ALLOC_AND_FREE
G_ALLOC_ONLY, G_ALLOC_ONLY
g_array_append_val, g_array_append_val()
g_array_append_vals, g_array_append_vals ()
g_array_free, g_array_free ()
g_array_index, g_array_index()
g_array_insert_val, g_array_insert_val()
g_array_insert_vals, g_array_insert_vals ()
g_array_new, g_array_new ()
g_array_prepend_val, g_array_prepend_val()
g_array_prepend_vals, g_array_prepend_vals ()
g_array_remove_index, g_array_remove_index ()
g_array_remove_index_fast, g_array_remove_index_fast ()
g_array_remove_range, g_array_remove_range ()
g_array_set_size, g_array_set_size ()
g_array_sized_new, g_array_sized_new ()
g_array_sort, g_array_sort ()
g_array_sort_with_data, g_array_sort_with_data ()
g_ascii_digit_value, g_ascii_digit_value ()
g_ascii_dtostr, g_ascii_dtostr ()
G_ASCII_DTOSTR_BUF_SIZE, G_ASCII_DTOSTR_BUF_SIZE
g_ascii_formatd, g_ascii_formatd ()
g_ascii_isalnum, g_ascii_isalnum ()
g_ascii_isalpha, g_ascii_isalpha ()
g_ascii_iscntrl, g_ascii_iscntrl ()
g_ascii_isdigit, g_ascii_isdigit ()
g_ascii_isgraph, g_ascii_isgraph ()
g_ascii_islower, g_ascii_islower ()
g_ascii_isprint, g_ascii_isprint ()
g_ascii_ispunct, g_ascii_ispunct ()
g_ascii_isspace, g_ascii_isspace ()
g_ascii_isupper, g_ascii_isupper ()
g_ascii_isxdigit, g_ascii_isxdigit ()
g_ascii_strcasecmp, g_ascii_strcasecmp ()
g_ascii_strdown, g_ascii_strdown ()
g_ascii_strncasecmp, g_ascii_strncasecmp ()
g_ascii_strtod, g_ascii_strtod ()
g_ascii_strtoll, g_ascii_strtoll ()
g_ascii_strtoull, g_ascii_strtoull ()
g_ascii_strup, g_ascii_strup ()
g_ascii_tolower, g_ascii_tolower ()
g_ascii_toupper, g_ascii_toupper ()
g_ascii_xdigit_value, g_ascii_xdigit_value ()
g_assert, g_assert()
g_assert_not_reached, g_assert_not_reached()
g_async_queue_length, g_async_queue_length ()
g_async_queue_length_unlocked, g_async_queue_length_unlocked ()
g_async_queue_lock, g_async_queue_lock ()
g_async_queue_new, g_async_queue_new ()
g_async_queue_pop, g_async_queue_pop ()
g_async_queue_pop_unlocked, g_async_queue_pop_unlocked ()
g_async_queue_push, g_async_queue_push ()
g_async_queue_push_sorted, g_async_queue_push_sorted ()
g_async_queue_push_sorted_unlocked, g_async_queue_push_sorted_unlocked ()
g_async_queue_push_unlocked, g_async_queue_push_unlocked ()
g_async_queue_ref, g_async_queue_ref ()
g_async_queue_ref_unlocked, g_async_queue_ref_unlocked ()
g_async_queue_sort, g_async_queue_sort ()
g_async_queue_sort_unlocked, g_async_queue_sort_unlocked ()
g_async_queue_timed_pop, g_async_queue_timed_pop ()
g_async_queue_timed_pop_unlocked, g_async_queue_timed_pop_unlocked ()
g_async_queue_try_pop, g_async_queue_try_pop ()
g_async_queue_try_pop_unlocked, g_async_queue_try_pop_unlocked ()
g_async_queue_unlock, g_async_queue_unlock ()
g_async_queue_unref, g_async_queue_unref ()
g_async_queue_unref_and_unlock, g_async_queue_unref_and_unlock ()
g_atexit, g_atexit ()
g_atomic_int_add, g_atomic_int_add ()
g_atomic_int_compare_and_exchange, g_atomic_int_compare_and_exchange ()
g_atomic_int_dec_and_test, g_atomic_int_dec_and_test ()
g_atomic_int_exchange_and_add, g_atomic_int_exchange_and_add ()
g_atomic_int_get, g_atomic_int_get ()
g_atomic_int_inc, g_atomic_int_inc ()
g_atomic_int_set, g_atomic_int_set ()
g_atomic_pointer_compare_and_exchange, g_atomic_pointer_compare_and_exchange ()
g_atomic_pointer_get, g_atomic_pointer_get ()
g_atomic_pointer_set, g_atomic_pointer_set ()
g_base64_decode, g_base64_decode ()
g_base64_decode_step, g_base64_decode_step ()
g_base64_encode, g_base64_encode ()
g_base64_encode_close, g_base64_encode_close ()
g_base64_encode_step, g_base64_encode_step ()
g_basename, g_basename ()
G_BEGIN_DECLS, G_BEGIN_DECLS
G_BIG_ENDIAN, G_BIG_ENDIAN
g_bit_nth_lsf, g_bit_nth_lsf ()
g_bit_nth_msf, g_bit_nth_msf ()
g_bit_storage, g_bit_storage ()
g_blow_chunks, g_blow_chunks ()
g_bookmark_file_add_application, g_bookmark_file_add_application ()
g_bookmark_file_add_group, g_bookmark_file_add_group ()
G_BOOKMARK_FILE_ERROR, G_BOOKMARK_FILE_ERROR
g_bookmark_file_free, g_bookmark_file_free ()
g_bookmark_file_get_added, g_bookmark_file_get_added ()
g_bookmark_file_get_applications, g_bookmark_file_get_applications ()
g_bookmark_file_get_app_info, g_bookmark_file_get_app_info ()
g_bookmark_file_get_description, g_bookmark_file_get_description ()
g_bookmark_file_get_groups, g_bookmark_file_get_groups ()
g_bookmark_file_get_icon, g_bookmark_file_get_icon ()
g_bookmark_file_get_is_private, g_bookmark_file_get_is_private ()
g_bookmark_file_get_mime_type, g_bookmark_file_get_mime_type ()
g_bookmark_file_get_modified, g_bookmark_file_get_modified ()
g_bookmark_file_get_size, g_bookmark_file_get_size ()
g_bookmark_file_get_title, g_bookmark_file_get_title ()
g_bookmark_file_get_uris, g_bookmark_file_get_uris ()
g_bookmark_file_get_visited, g_bookmark_file_get_visited ()
g_bookmark_file_has_application, g_bookmark_file_has_application ()
g_bookmark_file_has_group, g_bookmark_file_has_group ()
g_bookmark_file_has_item, g_bookmark_file_has_item ()
g_bookmark_file_load_from_data, g_bookmark_file_load_from_data ()
g_bookmark_file_load_from_data_dirs, g_bookmark_file_load_from_data_dirs ()
g_bookmark_file_load_from_file, g_bookmark_file_load_from_file ()
g_bookmark_file_move_item, g_bookmark_file_move_item ()
g_bookmark_file_new, g_bookmark_file_new ()
g_bookmark_file_remove_application, g_bookmark_file_remove_application ()
g_bookmark_file_remove_group, g_bookmark_file_remove_group ()
g_bookmark_file_remove_item, g_bookmark_file_remove_item ()
g_bookmark_file_set_added, g_bookmark_file_set_added ()
g_bookmark_file_set_app_info, g_bookmark_file_set_app_info ()
g_bookmark_file_set_description, g_bookmark_file_set_description ()
g_bookmark_file_set_groups, g_bookmark_file_set_groups ()
g_bookmark_file_set_icon, g_bookmark_file_set_icon ()
g_bookmark_file_set_is_private, g_bookmark_file_set_is_private ()
g_bookmark_file_set_mime_type, g_bookmark_file_set_mime_type ()
g_bookmark_file_set_modified, g_bookmark_file_set_modified ()
g_bookmark_file_set_title, g_bookmark_file_set_title ()
g_bookmark_file_set_visited, g_bookmark_file_set_visited ()
g_bookmark_file_to_data, g_bookmark_file_to_data ()
g_bookmark_file_to_file, g_bookmark_file_to_file ()
G_BREAKPOINT, G_BREAKPOINT()
g_build_filename, g_build_filename ()
g_build_filenamev, g_build_filenamev ()
g_build_path, g_build_path ()
g_build_pathv, g_build_pathv ()
g_byte_array_append, g_byte_array_append ()
g_byte_array_free, g_byte_array_free ()
g_byte_array_new, g_byte_array_new ()
g_byte_array_prepend, g_byte_array_prepend ()
g_byte_array_remove_index, g_byte_array_remove_index ()
g_byte_array_remove_index_fast, g_byte_array_remove_index_fast ()
g_byte_array_remove_range, g_byte_array_remove_range ()
g_byte_array_set_size, g_byte_array_set_size ()
g_byte_array_sized_new, g_byte_array_sized_new ()
g_byte_array_sort, g_byte_array_sort ()
g_byte_array_sort_with_data, g_byte_array_sort_with_data ()
G_BYTE_ORDER, G_BYTE_ORDER
g_cache_destroy, g_cache_destroy ()
g_cache_insert, g_cache_insert ()
g_cache_key_foreach, g_cache_key_foreach ()
g_cache_new, g_cache_new ()
g_cache_remove, g_cache_remove ()
g_cache_value_foreach, g_cache_value_foreach ()
g_chdir, g_chdir ()
g_child_watch_add, g_child_watch_add ()
g_child_watch_add_full, g_child_watch_add_full ()
g_child_watch_source_new, g_child_watch_source_new ()
g_chmod, g_chmod ()
g_chunk_free, g_chunk_free()
g_chunk_new, g_chunk_new()
g_chunk_new0, g_chunk_new0()
g_clear_error, g_clear_error ()
g_completion_add_items, g_completion_add_items ()
g_completion_clear_items, g_completion_clear_items ()
g_completion_complete, g_completion_complete ()
g_completion_complete_utf8, g_completion_complete_utf8 ()
g_completion_free, g_completion_free ()
g_completion_new, g_completion_new ()
g_completion_remove_items, g_completion_remove_items ()
g_completion_set_compare, g_completion_set_compare ()
g_cond_broadcast, g_cond_broadcast ()
g_cond_free, g_cond_free ()
g_cond_new, g_cond_new ()
g_cond_signal, g_cond_signal ()
g_cond_timed_wait, g_cond_timed_wait ()
g_cond_wait, g_cond_wait ()
G_CONST_RETURN, G_CONST_RETURN
g_convert, g_convert ()
G_CONVERT_ERROR, G_CONVERT_ERROR
g_convert_with_fallback, g_convert_with_fallback ()
g_convert_with_iconv, g_convert_with_iconv ()
g_creat, g_creat ()
g_critical, g_critical()
G_CSET_a_2_z, G_CSET_a_2_z
G_CSET_A_2_Z, G_CSET_A_2_Z
G_CSET_DIGITS, G_CSET_DIGITS
G_CSET_LATINC, G_CSET_LATINC
G_CSET_LATINS, G_CSET_LATINS
g_datalist_clear, g_datalist_clear ()
G_DATALIST_FLAGS_MASK, G_DATALIST_FLAGS_MASK
g_datalist_foreach, g_datalist_foreach ()
g_datalist_get_data, g_datalist_get_data()
g_datalist_get_flags, g_datalist_get_flags ()
g_datalist_id_get_data, g_datalist_id_get_data ()
g_datalist_id_remove_data, g_datalist_id_remove_data()
g_datalist_id_remove_no_notify, g_datalist_id_remove_no_notify ()
g_datalist_id_set_data, g_datalist_id_set_data()
g_datalist_id_set_data_full, g_datalist_id_set_data_full ()
g_datalist_init, g_datalist_init ()
g_datalist_remove_data, g_datalist_remove_data()
g_datalist_remove_no_notify, g_datalist_remove_no_notify()
g_datalist_set_data, g_datalist_set_data()
g_datalist_set_data_full, g_datalist_set_data_full()
g_datalist_set_flags, g_datalist_set_flags ()
g_datalist_unset_flags, g_datalist_unset_flags ()
g_dataset_destroy, g_dataset_destroy ()
g_dataset_foreach, g_dataset_foreach ()
g_dataset_get_data, g_dataset_get_data()
g_dataset_id_get_data, g_dataset_id_get_data ()
g_dataset_id_remove_data, g_dataset_id_remove_data()
g_dataset_id_remove_no_notify, g_dataset_id_remove_no_notify ()
g_dataset_id_set_data, g_dataset_id_set_data()
g_dataset_id_set_data_full, g_dataset_id_set_data_full ()
g_dataset_remove_data, g_dataset_remove_data()
g_dataset_remove_no_notify, g_dataset_remove_no_notify()
g_dataset_set_data, g_dataset_set_data()
g_dataset_set_data_full, g_dataset_set_data_full()
g_date_add_days, g_date_add_days ()
g_date_add_months, g_date_add_months ()
g_date_add_years, g_date_add_years ()
G_DATE_BAD_DAY, G_DATE_BAD_DAY
G_DATE_BAD_JULIAN, G_DATE_BAD_JULIAN
G_DATE_BAD_YEAR, G_DATE_BAD_YEAR
g_date_clamp, g_date_clamp ()
g_date_clear, g_date_clear ()
g_date_compare, g_date_compare ()
g_date_days_between, g_date_days_between ()
g_date_free, g_date_free ()
g_date_get_day, g_date_get_day ()
g_date_get_days_in_month, g_date_get_days_in_month ()
g_date_get_day_of_year, g_date_get_day_of_year ()
g_date_get_iso8601_week_of_year, g_date_get_iso8601_week_of_year ()
g_date_get_julian, g_date_get_julian ()
g_date_get_monday_weeks_in_year, g_date_get_monday_weeks_in_year ()
g_date_get_monday_week_of_year, g_date_get_monday_week_of_year ()
g_date_get_month, g_date_get_month ()
g_date_get_sunday_weeks_in_year, g_date_get_sunday_weeks_in_year ()
g_date_get_sunday_week_of_year, g_date_get_sunday_week_of_year ()
g_date_get_weekday, g_date_get_weekday ()
g_date_get_year, g_date_get_year ()
g_date_is_first_of_month, g_date_is_first_of_month ()
g_date_is_last_of_month, g_date_is_last_of_month ()
g_date_is_leap_year, g_date_is_leap_year ()
g_date_new, g_date_new ()
g_date_new_dmy, g_date_new_dmy ()
g_date_new_julian, g_date_new_julian ()
g_date_order, g_date_order ()
g_date_set_day, g_date_set_day ()
g_date_set_dmy, g_date_set_dmy ()
g_date_set_julian, g_date_set_julian ()
g_date_set_month, g_date_set_month ()
g_date_set_parse, g_date_set_parse ()
g_date_set_time, g_date_set_time ()
g_date_set_time_t, g_date_set_time_t ()
g_date_set_time_val, g_date_set_time_val ()
g_date_set_year, g_date_set_year ()
g_date_strftime, g_date_strftime ()
g_date_subtract_days, g_date_subtract_days ()
g_date_subtract_months, g_date_subtract_months ()
g_date_subtract_years, g_date_subtract_years ()
g_date_to_struct_tm, g_date_to_struct_tm ()
g_date_valid, g_date_valid ()
g_date_valid_day, g_date_valid_day ()
g_date_valid_dmy, g_date_valid_dmy ()
g_date_valid_julian, g_date_valid_julian ()
g_date_valid_month, g_date_valid_month ()
g_date_valid_weekday, g_date_valid_weekday ()
g_date_valid_year, g_date_valid_year ()
g_debug, g_debug()
g_direct_equal, g_direct_equal ()
g_direct_hash, g_direct_hash ()
g_dirname, g_dirname
g_dir_close, g_dir_close ()
g_dir_open, g_dir_open ()
g_dir_read_name, g_dir_read_name ()
g_dir_rewind, g_dir_rewind ()
G_DIR_SEPARATOR, G_DIR_SEPARATOR
G_DIR_SEPARATOR_S, G_DIR_SEPARATOR_S
G_E, G_E
G_END_DECLS, G_END_DECLS
g_error, g_error()
g_error_copy, g_error_copy ()
g_error_free, g_error_free ()
g_error_matches, g_error_matches ()
g_error_new, g_error_new ()
g_error_new_literal, g_error_new_literal ()
g_filename_display_basename, g_filename_display_basename ()
g_filename_display_name, g_filename_display_name ()
g_filename_from_uri, g_filename_from_uri ()
g_filename_from_utf8, g_filename_from_utf8 ()
g_filename_to_uri, g_filename_to_uri ()
g_filename_to_utf8, g_filename_to_utf8 ()
G_FILE_ERROR, G_FILE_ERROR
g_file_error_from_errno, g_file_error_from_errno ()
g_file_get_contents, g_file_get_contents ()
g_file_open_tmp, g_file_open_tmp ()
g_file_read_link, g_file_read_link ()
g_file_set_contents, g_file_set_contents ()
g_file_test, g_file_test ()
g_find_program_in_path, g_find_program_in_path ()
g_fopen, g_fopen ()
g_fprintf, g_fprintf ()
g_free, g_free ()
g_freopen, g_freopen ()
g_getenv, g_getenv ()
g_get_application_name, g_get_application_name ()
g_get_charset, g_get_charset ()
g_get_current_dir, g_get_current_dir ()
g_get_current_time, g_get_current_time ()
g_get_filename_charsets, g_get_filename_charsets ()
g_get_home_dir, g_get_home_dir ()
g_get_host_name, g_get_host_name ()
g_get_language_names, g_get_language_names ()
g_get_prgname, g_get_prgname ()
g_get_real_name, g_get_real_name ()
g_get_system_config_dirs, g_get_system_config_dirs ()
g_get_system_data_dirs, g_get_system_data_dirs ()
g_get_tmp_dir, g_get_tmp_dir ()
g_get_user_cache_dir, g_get_user_cache_dir ()
g_get_user_config_dir, g_get_user_config_dir ()
g_get_user_data_dir, g_get_user_data_dir ()
g_get_user_name, g_get_user_name ()
G_GINT16_FORMAT, G_GINT16_FORMAT
G_GINT16_MODIFIER, G_GINT16_MODIFIER
G_GINT32_FORMAT, G_GINT32_FORMAT
G_GINT32_MODIFIER, G_GINT32_MODIFIER
G_GINT64_CONSTANT, G_GINT64_CONSTANT()
G_GINT64_FORMAT, G_GINT64_FORMAT
G_GINT64_MODIFIER, G_GINT64_MODIFIER
G_GNUC_CONST, G_GNUC_CONST
G_GNUC_DEPRECATED, G_GNUC_DEPRECATED
G_GNUC_EXTENSION, G_GNUC_EXTENSION
G_GNUC_FORMAT, G_GNUC_FORMAT()
G_GNUC_FUNCTION, G_GNUC_FUNCTION
G_GNUC_INTERNAL, G_GNUC_INTERNAL
G_GNUC_MALLOC, G_GNUC_MALLOC
G_GNUC_NORETURN, G_GNUC_NORETURN
G_GNUC_NO_INSTRUMENT, G_GNUC_NO_INSTRUMENT
G_GNUC_NULL_TERMINATED, G_GNUC_NULL_TERMINATED
G_GNUC_PRETTY_FUNCTION, G_GNUC_PRETTY_FUNCTION
G_GNUC_PRINTF, G_GNUC_PRINTF()
G_GNUC_PURE, G_GNUC_PURE
G_GNUC_SCANF, G_GNUC_SCANF()
G_GNUC_UNUSED, G_GNUC_UNUSED
G_GNUC_WARN_UNUSED_RESULT, G_GNUC_WARN_UNUSED_RESULT
G_GSIZE_FORMAT, G_GSIZE_FORMAT
G_GSIZE_MODIFIER, G_GSIZE_MODIFIER
G_GSSIZE_FORMAT, G_GSSIZE_FORMAT
G_GUINT16_FORMAT, G_GUINT16_FORMAT
G_GUINT32_FORMAT, G_GUINT32_FORMAT
G_GUINT64_CONSTANT, G_GUINT64_CONSTANT()
G_GUINT64_FORMAT, G_GUINT64_FORMAT
g_hash_table_destroy, g_hash_table_destroy ()
g_hash_table_find, g_hash_table_find ()
g_hash_table_foreach, g_hash_table_foreach ()
g_hash_table_foreach_remove, g_hash_table_foreach_remove ()
g_hash_table_foreach_steal, g_hash_table_foreach_steal ()
g_hash_table_freeze, g_hash_table_freeze()
g_hash_table_insert, g_hash_table_insert ()
g_hash_table_lookup, g_hash_table_lookup ()
g_hash_table_lookup_extended, g_hash_table_lookup_extended ()
g_hash_table_new, g_hash_table_new ()
g_hash_table_new_full, g_hash_table_new_full ()
g_hash_table_ref, g_hash_table_ref ()
g_hash_table_remove, g_hash_table_remove ()
g_hash_table_remove_all, g_hash_table_remove_all ()
g_hash_table_replace, g_hash_table_replace ()
g_hash_table_size, g_hash_table_size ()
g_hash_table_steal, g_hash_table_steal ()
g_hash_table_steal_all, g_hash_table_steal_all ()
g_hash_table_thaw, g_hash_table_thaw()
g_hash_table_unref, g_hash_table_unref ()
G_HAVE_GINT64, G_HAVE_GINT64
G_HAVE_GNUC_VISIBILITY, G_HAVE_GNUC_VISIBILITY
G_HOOK, G_HOOK()
G_HOOK_ACTIVE, G_HOOK_ACTIVE()
g_hook_alloc, g_hook_alloc ()
g_hook_append, g_hook_append()
g_hook_compare_ids, g_hook_compare_ids ()
g_hook_destroy, g_hook_destroy ()
g_hook_destroy_link, g_hook_destroy_link ()
g_hook_find, g_hook_find ()
g_hook_find_data, g_hook_find_data ()
g_hook_find_func, g_hook_find_func ()
g_hook_find_func_data, g_hook_find_func_data ()
g_hook_first_valid, g_hook_first_valid ()
G_HOOK_FLAGS, G_HOOK_FLAGS()
G_HOOK_FLAG_USER_SHIFT, G_HOOK_FLAG_USER_SHIFT
g_hook_free, g_hook_free ()
g_hook_get, g_hook_get ()
g_hook_insert_before, g_hook_insert_before ()
g_hook_insert_sorted, g_hook_insert_sorted ()
G_HOOK_IN_CALL, G_HOOK_IN_CALL()
G_HOOK_IS_UNLINKED, G_HOOK_IS_UNLINKED()
G_HOOK_IS_VALID, G_HOOK_IS_VALID()
g_hook_list_clear, g_hook_list_clear ()
g_hook_list_init, g_hook_list_init ()
g_hook_list_invoke, g_hook_list_invoke ()
g_hook_list_invoke_check, g_hook_list_invoke_check ()
g_hook_list_marshal, g_hook_list_marshal ()
g_hook_list_marshal_check, g_hook_list_marshal_check ()
g_hook_next_valid, g_hook_next_valid ()
g_hook_prepend, g_hook_prepend ()
g_hook_ref, g_hook_ref ()
g_hook_unref, g_hook_unref ()
g_htonl, g_htonl()
g_htons, g_htons()
g_iconv, g_iconv ()
g_iconv_close, g_iconv_close ()
g_iconv_open, g_iconv_open ()
g_idle_add, g_idle_add ()
g_idle_add_full, g_idle_add_full ()
g_idle_remove_by_data, g_idle_remove_by_data ()
g_idle_source_new, g_idle_source_new ()
G_IEEE754_DOUBLE_BIAS, G_IEEE754_DOUBLE_BIAS
G_IEEE754_FLOAT_BIAS, G_IEEE754_FLOAT_BIAS
G_INLINE_FUNC, G_INLINE_FUNC
g_intern_static_string, g_intern_static_string ()
g_intern_string, g_intern_string ()
g_int_equal, g_int_equal ()
g_int_hash, g_int_hash ()
g_io_add_watch, g_io_add_watch ()
g_io_add_watch_full, g_io_add_watch_full ()
g_io_channel_close, g_io_channel_close ()
G_IO_CHANNEL_ERROR, G_IO_CHANNEL_ERROR
g_io_channel_error_from_errno, g_io_channel_error_from_errno ()
g_io_channel_flush, g_io_channel_flush ()
g_io_channel_get_buffered, g_io_channel_get_buffered ()
g_io_channel_get_buffer_condition, g_io_channel_get_buffer_condition ()
g_io_channel_get_buffer_size, g_io_channel_get_buffer_size ()
g_io_channel_get_close_on_unref, g_io_channel_get_close_on_unref ()
g_io_channel_get_encoding, g_io_channel_get_encoding ()
g_io_channel_get_flags, g_io_channel_get_flags ()
g_io_channel_get_line_term, g_io_channel_get_line_term ()
g_io_channel_init, g_io_channel_init ()
g_io_channel_new_file, g_io_channel_new_file ()
g_io_channel_read, g_io_channel_read ()
g_io_channel_read_chars, g_io_channel_read_chars ()
g_io_channel_read_line, g_io_channel_read_line ()
g_io_channel_read_line_string, g_io_channel_read_line_string ()
g_io_channel_read_to_end, g_io_channel_read_to_end ()
g_io_channel_read_unichar, g_io_channel_read_unichar ()
g_io_channel_ref, g_io_channel_ref ()
g_io_channel_seek, g_io_channel_seek ()
g_io_channel_seek_position, g_io_channel_seek_position ()
g_io_channel_set_buffered, g_io_channel_set_buffered ()
g_io_channel_set_buffer_size, g_io_channel_set_buffer_size ()
g_io_channel_set_close_on_unref, g_io_channel_set_close_on_unref ()
g_io_channel_set_encoding, g_io_channel_set_encoding ()
g_io_channel_set_flags, g_io_channel_set_flags ()
g_io_channel_set_line_term, g_io_channel_set_line_term ()
g_io_channel_shutdown, g_io_channel_shutdown ()
g_io_channel_unix_get_fd, g_io_channel_unix_get_fd ()
g_io_channel_unix_new, g_io_channel_unix_new ()
g_io_channel_unref, g_io_channel_unref ()
g_io_channel_win32_new_fd, g_io_channel_win32_new_fd ()
g_io_channel_win32_new_messages, g_io_channel_win32_new_messages ()
g_io_channel_win32_new_socket, g_io_channel_win32_new_socket ()
g_io_channel_write, g_io_channel_write ()
g_io_channel_write_chars, g_io_channel_write_chars ()
g_io_channel_write_unichar, g_io_channel_write_unichar ()
g_io_create_watch, g_io_create_watch ()
G_IS_DIR_SEPARATOR, G_IS_DIR_SEPARATOR()
G_KEY_FILE_ERROR, G_KEY_FILE_ERROR
g_key_file_free, g_key_file_free ()
g_key_file_get_boolean, g_key_file_get_boolean ()
g_key_file_get_boolean_list, g_key_file_get_boolean_list ()
g_key_file_get_comment, g_key_file_get_comment ()
g_key_file_get_double, g_key_file_get_double ()
g_key_file_get_double_list, g_key_file_get_double_list ()
g_key_file_get_groups, g_key_file_get_groups ()
g_key_file_get_integer, g_key_file_get_integer ()
g_key_file_get_integer_list, g_key_file_get_integer_list ()
g_key_file_get_keys, g_key_file_get_keys ()
g_key_file_get_locale_string, g_key_file_get_locale_string ()
g_key_file_get_locale_string_list, g_key_file_get_locale_string_list ()
g_key_file_get_start_group, g_key_file_get_start_group ()
g_key_file_get_string, g_key_file_get_string ()
g_key_file_get_string_list, g_key_file_get_string_list ()
g_key_file_get_value, g_key_file_get_value ()
g_key_file_has_group, g_key_file_has_group ()
g_key_file_has_key, g_key_file_has_key ()
g_key_file_load_from_data, g_key_file_load_from_data ()
g_key_file_load_from_data_dirs, g_key_file_load_from_data_dirs ()
g_key_file_load_from_file, g_key_file_load_from_file ()
g_key_file_new, g_key_file_new ()
g_key_file_remove_comment, g_key_file_remove_comment ()
g_key_file_remove_group, g_key_file_remove_group ()
g_key_file_remove_key, g_key_file_remove_key ()
g_key_file_set_boolean, g_key_file_set_boolean ()
g_key_file_set_boolean_list, g_key_file_set_boolean_list ()
g_key_file_set_comment, g_key_file_set_comment ()
g_key_file_set_double, g_key_file_set_double ()
g_key_file_set_double_list, g_key_file_set_double_list ()
g_key_file_set_integer, g_key_file_set_integer ()
g_key_file_set_integer_list, g_key_file_set_integer_list ()
g_key_file_set_list_separator, g_key_file_set_list_separator ()
g_key_file_set_locale_string, g_key_file_set_locale_string ()
g_key_file_set_locale_string_list, g_key_file_set_locale_string_list ()
g_key_file_set_string, g_key_file_set_string ()
g_key_file_set_string_list, g_key_file_set_string_list ()
g_key_file_set_value, g_key_file_set_value ()
g_key_file_to_data, g_key_file_to_data ()
G_LIKELY, G_LIKELY()
g_listenv, g_listenv ()
g_list_alloc, g_list_alloc ()
g_list_append, g_list_append ()
g_list_concat, g_list_concat ()
g_list_copy, g_list_copy ()
g_list_delete_link, g_list_delete_link ()
g_list_find, g_list_find ()
g_list_find_custom, g_list_find_custom ()
g_list_first, g_list_first ()
g_list_foreach, g_list_foreach ()
g_list_free, g_list_free ()
g_list_free1, g_list_free1
g_list_free_1, g_list_free_1 ()
g_list_index, g_list_index ()
g_list_insert, g_list_insert ()
g_list_insert_before, g_list_insert_before ()
g_list_insert_sorted, g_list_insert_sorted ()
g_list_insert_sorted_with_data, g_list_insert_sorted_with_data ()
g_list_last, g_list_last ()
g_list_length, g_list_length ()
g_list_next, g_list_next()
g_list_nth, g_list_nth ()
g_list_nth_data, g_list_nth_data ()
g_list_nth_prev, g_list_nth_prev ()
g_list_pop_allocator, g_list_pop_allocator ()
g_list_position, g_list_position ()
g_list_prepend, g_list_prepend ()
g_list_previous, g_list_previous()
g_list_push_allocator, g_list_push_allocator ()
g_list_remove, g_list_remove ()
g_list_remove_all, g_list_remove_all ()
g_list_remove_link, g_list_remove_link ()
g_list_reverse, g_list_reverse ()
g_list_sort, g_list_sort ()
g_list_sort_with_data, g_list_sort_with_data ()
G_LITTLE_ENDIAN, G_LITTLE_ENDIAN
G_LN10, G_LN10
G_LN2, G_LN2
g_locale_from_utf8, g_locale_from_utf8 ()
g_locale_to_utf8, g_locale_to_utf8 ()
G_LOCK, G_LOCK()
G_LOCK_DEFINE, G_LOCK_DEFINE()
G_LOCK_DEFINE_STATIC, G_LOCK_DEFINE_STATIC()
G_LOCK_EXTERN, G_LOCK_EXTERN()
g_log, g_log ()
g_logv, g_logv ()
G_LOG_2_BASE_10, G_LOG_2_BASE_10
g_log_default_handler, g_log_default_handler ()
G_LOG_DOMAIN, G_LOG_DOMAIN
G_LOG_FATAL_MASK, G_LOG_FATAL_MASK
G_LOG_LEVEL_USER_SHIFT, G_LOG_LEVEL_USER_SHIFT
g_log_remove_handler, g_log_remove_handler ()
g_log_set_always_fatal, g_log_set_always_fatal ()
g_log_set_default_handler, g_log_set_default_handler ()
g_log_set_fatal_mask, g_log_set_fatal_mask ()
g_log_set_handler, g_log_set_handler ()
g_lstat, g_lstat ()
g_main_context_acquire, g_main_context_acquire ()
g_main_context_add_poll, g_main_context_add_poll ()
g_main_context_check, g_main_context_check ()
g_main_context_default, g_main_context_default ()
g_main_context_dispatch, g_main_context_dispatch ()
g_main_context_find_source_by_funcs_user_data, g_main_context_find_source_by_funcs_user_data ()
g_main_context_find_source_by_id, g_main_context_find_source_by_id ()
g_main_context_find_source_by_user_data, g_main_context_find_source_by_user_data ()
g_main_context_get_poll_func, g_main_context_get_poll_func ()
g_main_context_is_owner, g_main_context_is_owner ()
g_main_context_iteration, g_main_context_iteration ()
g_main_context_new, g_main_context_new ()
g_main_context_pending, g_main_context_pending ()
g_main_context_prepare, g_main_context_prepare ()
g_main_context_query, g_main_context_query ()
g_main_context_ref, g_main_context_ref ()
g_main_context_release, g_main_context_release ()
g_main_context_remove_poll, g_main_context_remove_poll ()
g_main_context_set_poll_func, g_main_context_set_poll_func ()
g_main_context_unref, g_main_context_unref ()
g_main_context_wait, g_main_context_wait ()
g_main_context_wakeup, g_main_context_wakeup ()
g_main_current_source, g_main_current_source ()
g_main_depth, g_main_depth ()
g_main_destroy, g_main_destroy()
g_main_is_running, g_main_is_running()
g_main_iteration, g_main_iteration()
g_main_loop_get_context, g_main_loop_get_context ()
g_main_loop_is_running, g_main_loop_is_running ()
g_main_loop_new, g_main_loop_new ()
g_main_loop_quit, g_main_loop_quit ()
g_main_loop_ref, g_main_loop_ref ()
g_main_loop_run, g_main_loop_run ()
g_main_loop_unref, g_main_loop_unref ()
g_main_new, g_main_new()
g_main_pending, g_main_pending()
g_main_quit, g_main_quit()
g_main_run, g_main_run()
g_main_set_poll_func, g_main_set_poll_func()
g_malloc, g_malloc ()
g_malloc0, g_malloc0 ()
g_mapped_file_free, g_mapped_file_free ()
g_mapped_file_get_contents, g_mapped_file_get_contents ()
g_mapped_file_get_length, g_mapped_file_get_length ()
g_mapped_file_new, g_mapped_file_new ()
G_MARKUP_ERROR, G_MARKUP_ERROR
g_markup_escape_text, g_markup_escape_text ()
g_markup_parse_context_end_parse, g_markup_parse_context_end_parse ()
g_markup_parse_context_free, g_markup_parse_context_free ()
g_markup_parse_context_get_element, g_markup_parse_context_get_element ()
g_markup_parse_context_get_position, g_markup_parse_context_get_position ()
g_markup_parse_context_new, g_markup_parse_context_new ()
g_markup_parse_context_parse, g_markup_parse_context_parse ()
g_markup_printf_escaped, g_markup_printf_escaped ()
g_markup_vprintf_escaped, g_markup_vprintf_escaped ()
G_MAXDOUBLE, G_MAXDOUBLE
G_MAXFLOAT, G_MAXFLOAT
G_MAXINT, G_MAXINT
G_MAXINT16, G_MAXINT16
G_MAXINT32, G_MAXINT32
G_MAXINT64, G_MAXINT64
G_MAXINT8, G_MAXINT8
G_MAXLONG, G_MAXLONG
G_MAXSHORT, G_MAXSHORT
G_MAXSIZE, G_MAXSIZE
G_MAXUINT, G_MAXUINT
G_MAXUINT16, G_MAXUINT16
G_MAXUINT32, G_MAXUINT32
G_MAXUINT64, G_MAXUINT64
G_MAXUINT8, G_MAXUINT8
G_MAXULONG, G_MAXULONG
G_MAXUSHORT, G_MAXUSHORT
g_memdup, g_memdup ()
g_memmove, g_memmove()
G_MEM_ALIGN, G_MEM_ALIGN
g_mem_chunk_alloc, g_mem_chunk_alloc ()
g_mem_chunk_alloc0, g_mem_chunk_alloc0 ()
g_mem_chunk_clean, g_mem_chunk_clean ()
g_mem_chunk_create, g_mem_chunk_create()
g_mem_chunk_destroy, g_mem_chunk_destroy ()
g_mem_chunk_free, g_mem_chunk_free ()
g_mem_chunk_info, g_mem_chunk_info ()
g_mem_chunk_new, g_mem_chunk_new ()
g_mem_chunk_print, g_mem_chunk_print ()
g_mem_chunk_reset, g_mem_chunk_reset ()
g_mem_gc_friendly, g_mem_gc_friendly
g_mem_is_system_malloc, g_mem_is_system_malloc ()
g_mem_profile, g_mem_profile ()
g_mem_set_vtable, g_mem_set_vtable ()
g_message, g_message()
G_MINDOUBLE, G_MINDOUBLE
G_MINFLOAT, G_MINFLOAT
G_MININT, G_MININT
G_MININT16, G_MININT16
G_MININT32, G_MININT32
G_MININT64, G_MININT64
G_MININT8, G_MININT8
G_MINLONG, G_MINLONG
G_MINSHORT, G_MINSHORT
g_mkdir, g_mkdir ()
g_mkdir_with_parents, g_mkdir_with_parents ()
g_mkstemp, g_mkstemp ()
g_module_build_path, g_module_build_path ()
g_module_close, g_module_close ()
g_module_error, g_module_error ()
G_MODULE_EXPORT, G_MODULE_EXPORT
G_MODULE_IMPORT, G_MODULE_IMPORT
g_module_make_resident, g_module_make_resident ()
g_module_name, g_module_name ()
g_module_open, g_module_open ()
G_MODULE_SUFFIX, G_MODULE_SUFFIX
g_module_supported, g_module_supported ()
g_module_symbol, g_module_symbol ()
g_mutex_free, g_mutex_free ()
g_mutex_lock, g_mutex_lock ()
g_mutex_new, g_mutex_new ()
g_mutex_trylock, g_mutex_trylock ()
g_mutex_unlock, g_mutex_unlock ()
g_new, g_new()
g_new0, g_new0()
g_newa, g_newa()
g_node_append, g_node_append()
g_node_append_data, g_node_append_data()
g_node_children_foreach, g_node_children_foreach ()
g_node_child_index, g_node_child_index ()
g_node_child_position, g_node_child_position ()
g_node_copy, g_node_copy ()
g_node_copy_deep, g_node_copy_deep ()
g_node_depth, g_node_depth ()
g_node_destroy, g_node_destroy ()
g_node_find, g_node_find ()
g_node_find_child, g_node_find_child ()
g_node_first_child, g_node_first_child()
g_node_first_sibling, g_node_first_sibling ()
g_node_get_root, g_node_get_root ()
g_node_insert, g_node_insert ()
g_node_insert_after, g_node_insert_after ()
g_node_insert_before, g_node_insert_before ()
g_node_insert_data, g_node_insert_data()
g_node_insert_data_before, g_node_insert_data_before()
g_node_is_ancestor, g_node_is_ancestor ()
G_NODE_IS_LEAF, G_NODE_IS_LEAF()
G_NODE_IS_ROOT, G_NODE_IS_ROOT()
g_node_last_child, g_node_last_child ()
g_node_last_sibling, g_node_last_sibling ()
g_node_max_height, g_node_max_height ()
g_node_new, g_node_new ()
g_node_next_sibling, g_node_next_sibling()
g_node_nth_child, g_node_nth_child ()
g_node_n_children, g_node_n_children ()
g_node_n_nodes, g_node_n_nodes ()
g_node_pop_allocator, g_node_pop_allocator ()
g_node_prepend, g_node_prepend ()
g_node_prepend_data, g_node_prepend_data()
g_node_prev_sibling, g_node_prev_sibling()
g_node_push_allocator, g_node_push_allocator ()
g_node_reverse_children, g_node_reverse_children ()
g_node_traverse, g_node_traverse ()
g_node_unlink, g_node_unlink ()
g_ntohl, g_ntohl()
g_ntohs, g_ntohs()
g_nullify_pointer, g_nullify_pointer ()
G_N_ELEMENTS, G_N_ELEMENTS()
g_once, g_once()
G_ONCE_INIT, G_ONCE_INIT
g_on_error_query, g_on_error_query ()
g_on_error_stack_trace, g_on_error_stack_trace ()
g_open, g_open ()
g_option_context_add_group, g_option_context_add_group ()
g_option_context_add_main_entries, g_option_context_add_main_entries ()
g_option_context_free, g_option_context_free ()
g_option_context_get_description, g_option_context_get_description ()
g_option_context_get_help_enabled, g_option_context_get_help_enabled ()
g_option_context_get_ignore_unknown_options, g_option_context_get_ignore_unknown_options ()
g_option_context_get_main_group, g_option_context_get_main_group ()
g_option_context_get_summary, g_option_context_get_summary ()
g_option_context_new, g_option_context_new ()
g_option_context_parse, g_option_context_parse ()
g_option_context_set_description, g_option_context_set_description ()
g_option_context_set_help_enabled, g_option_context_set_help_enabled ()
g_option_context_set_ignore_unknown_options, g_option_context_set_ignore_unknown_options ()
g_option_context_set_main_group, g_option_context_set_main_group ()
g_option_context_set_summary, g_option_context_set_summary ()
g_option_context_set_translate_func, g_option_context_set_translate_func ()
g_option_context_set_translation_domain, g_option_context_set_translation_domain ()
G_OPTION_ERROR, G_OPTION_ERROR
g_option_group_add_entries, g_option_group_add_entries ()
g_option_group_free, g_option_group_free ()
g_option_group_new, g_option_group_new ()
g_option_group_set_error_hook, g_option_group_set_error_hook ()
g_option_group_set_parse_hooks, g_option_group_set_parse_hooks ()
g_option_group_set_translate_func, g_option_group_set_translate_func ()
g_option_group_set_translation_domain, g_option_group_set_translation_domain ()
G_OPTION_REMAINING, G_OPTION_REMAINING
G_OS_BEOS, G_OS_BEOS
G_OS_UNIX, G_OS_UNIX
G_OS_WIN32, G_OS_WIN32
g_parse_debug_string, g_parse_debug_string ()
g_path_get_basename, g_path_get_basename ()
g_path_get_dirname, g_path_get_dirname ()
g_path_is_absolute, g_path_is_absolute ()
g_path_skip_root, g_path_skip_root ()
g_pattern_match, g_pattern_match ()
g_pattern_match_simple, g_pattern_match_simple ()
g_pattern_match_string, g_pattern_match_string ()
g_pattern_spec_equal, g_pattern_spec_equal ()
g_pattern_spec_free, g_pattern_spec_free ()
g_pattern_spec_new, g_pattern_spec_new ()
G_PDP_ENDIAN, G_PDP_ENDIAN
G_PI, G_PI
G_PI_2, G_PI_2
G_PI_4, G_PI_4
g_print, g_print ()
g_printerr, g_printerr ()
g_printf, g_printf ()
g_printf_string_upper_bound, g_printf_string_upper_bound ()
G_PRIORITY_DEFAULT, G_PRIORITY_DEFAULT
G_PRIORITY_DEFAULT_IDLE, G_PRIORITY_DEFAULT_IDLE
G_PRIORITY_HIGH, G_PRIORITY_HIGH
G_PRIORITY_HIGH_IDLE, G_PRIORITY_HIGH_IDLE
G_PRIORITY_LOW, G_PRIORITY_LOW
g_private_get, g_private_get ()
g_private_new, g_private_new ()
g_private_set, g_private_set ()
g_propagate_error, g_propagate_error ()
g_ptr_array_add, g_ptr_array_add ()
g_ptr_array_foreach, g_ptr_array_foreach ()
g_ptr_array_free, g_ptr_array_free ()
g_ptr_array_index, g_ptr_array_index()
g_ptr_array_new, g_ptr_array_new ()
g_ptr_array_remove, g_ptr_array_remove ()
g_ptr_array_remove_fast, g_ptr_array_remove_fast ()
g_ptr_array_remove_index, g_ptr_array_remove_index ()
g_ptr_array_remove_index_fast, g_ptr_array_remove_index_fast ()
g_ptr_array_remove_range, g_ptr_array_remove_range ()
g_ptr_array_set_size, g_ptr_array_set_size ()
g_ptr_array_sized_new, g_ptr_array_sized_new ()
g_ptr_array_sort, g_ptr_array_sort ()
g_ptr_array_sort_with_data, g_ptr_array_sort_with_data ()
g_qsort_with_data, g_qsort_with_data ()
g_quark_from_static_string, g_quark_from_static_string ()
g_quark_from_string, g_quark_from_string ()
g_quark_to_string, g_quark_to_string ()
g_quark_try_string, g_quark_try_string ()
g_queue_copy, g_queue_copy ()
g_queue_delete_link, g_queue_delete_link ()
g_queue_find, g_queue_find ()
g_queue_find_custom, g_queue_find_custom ()
g_queue_foreach, g_queue_foreach ()
g_queue_free, g_queue_free ()
g_queue_get_length, g_queue_get_length ()
g_queue_index, g_queue_index ()
g_queue_insert_after, g_queue_insert_after ()
g_queue_insert_before, g_queue_insert_before ()
g_queue_insert_sorted, g_queue_insert_sorted ()
g_queue_is_empty, g_queue_is_empty ()
g_queue_link_index, g_queue_link_index ()
g_queue_new, g_queue_new ()
g_queue_peek_head, g_queue_peek_head ()
g_queue_peek_head_link, g_queue_peek_head_link ()
g_queue_peek_nth, g_queue_peek_nth ()
g_queue_peek_nth_link, g_queue_peek_nth_link ()
g_queue_peek_tail, g_queue_peek_tail ()
g_queue_peek_tail_link, g_queue_peek_tail_link ()
g_queue_pop_head, g_queue_pop_head ()
g_queue_pop_head_link, g_queue_pop_head_link ()
g_queue_pop_nth, g_queue_pop_nth ()
g_queue_pop_nth_link, g_queue_pop_nth_link ()
g_queue_pop_tail, g_queue_pop_tail ()
g_queue_pop_tail_link, g_queue_pop_tail_link ()
g_queue_push_head, g_queue_push_head ()
g_queue_push_head_link, g_queue_push_head_link ()
g_queue_push_nth, g_queue_push_nth ()
g_queue_push_nth_link, g_queue_push_nth_link ()
g_queue_push_tail, g_queue_push_tail ()
g_queue_push_tail_link, g_queue_push_tail_link ()
g_queue_remove, g_queue_remove ()
g_queue_remove_all, g_queue_remove_all ()
g_queue_reverse, g_queue_reverse ()
g_queue_sort, g_queue_sort ()
g_queue_unlink, g_queue_unlink ()
g_random_boolean, g_random_boolean()
g_random_double, g_random_double ()
g_random_double_range, g_random_double_range ()
g_random_int, g_random_int ()
g_random_int_range, g_random_int_range ()
g_random_set_seed, g_random_set_seed ()
g_rand_boolean, g_rand_boolean()
g_rand_copy, g_rand_copy ()
g_rand_double, g_rand_double ()
g_rand_double_range, g_rand_double_range ()
g_rand_free, g_rand_free ()
g_rand_int, g_rand_int ()
g_rand_int_range, g_rand_int_range ()
g_rand_new, g_rand_new ()
g_rand_new_with_seed, g_rand_new_with_seed ()
g_rand_new_with_seed_array, g_rand_new_with_seed_array ()
g_rand_set_seed, g_rand_set_seed ()
g_rand_set_seed_array, g_rand_set_seed_array ()
g_realloc, g_realloc ()
g_relation_count, g_relation_count ()
g_relation_delete, g_relation_delete ()
g_relation_destroy, g_relation_destroy ()
g_relation_exists, g_relation_exists ()
g_relation_index, g_relation_index ()
g_relation_insert, g_relation_insert ()
g_relation_new, g_relation_new ()
g_relation_print, g_relation_print ()
g_relation_select, g_relation_select ()
g_remove, g_remove ()
g_rename, g_rename ()
g_renew, g_renew()
g_return_if_fail, g_return_if_fail()
g_return_if_reached, g_return_if_reached()
g_return_val_if_fail, g_return_val_if_fail()
g_return_val_if_reached, g_return_val_if_reached()
g_rmdir, g_rmdir ()
g_scanner_add_symbol, g_scanner_add_symbol()
g_scanner_cur_line, g_scanner_cur_line ()
g_scanner_cur_position, g_scanner_cur_position ()
g_scanner_cur_token, g_scanner_cur_token ()
g_scanner_cur_value, g_scanner_cur_value ()
g_scanner_destroy, g_scanner_destroy ()
g_scanner_eof, g_scanner_eof ()
g_scanner_error, g_scanner_error ()
g_scanner_foreach_symbol, g_scanner_foreach_symbol()
g_scanner_freeze_symbol_table, g_scanner_freeze_symbol_table()
g_scanner_get_next_token, g_scanner_get_next_token ()
g_scanner_input_file, g_scanner_input_file ()
g_scanner_input_text, g_scanner_input_text ()
g_scanner_lookup_symbol, g_scanner_lookup_symbol ()
g_scanner_new, g_scanner_new ()
g_scanner_peek_next_token, g_scanner_peek_next_token ()
g_scanner_remove_symbol, g_scanner_remove_symbol()
g_scanner_scope_add_symbol, g_scanner_scope_add_symbol ()
g_scanner_scope_foreach_symbol, g_scanner_scope_foreach_symbol ()
g_scanner_scope_lookup_symbol, g_scanner_scope_lookup_symbol ()
g_scanner_scope_remove_symbol, g_scanner_scope_remove_symbol ()
g_scanner_set_scope, g_scanner_set_scope ()
g_scanner_sync_file_offset, g_scanner_sync_file_offset ()
g_scanner_thaw_symbol_table, g_scanner_thaw_symbol_table()
g_scanner_unexp_token, g_scanner_unexp_token ()
g_scanner_warn, g_scanner_warn ()
G_SEARCHPATH_SEPARATOR, G_SEARCHPATH_SEPARATOR
G_SEARCHPATH_SEPARATOR_S, G_SEARCHPATH_SEPARATOR_S
g_setenv, g_setenv ()
g_set_application_name, g_set_application_name ()
g_set_error, g_set_error ()
g_set_prgname, g_set_prgname ()
g_set_printerr_handler, g_set_printerr_handler ()
g_set_print_handler, g_set_print_handler ()
G_SHELL_ERROR, G_SHELL_ERROR
g_shell_parse_argv, g_shell_parse_argv ()
g_shell_quote, g_shell_quote ()
g_shell_unquote, g_shell_unquote ()
g_slice_alloc, g_slice_alloc ()
g_slice_alloc0, g_slice_alloc0 ()
g_slice_free, g_slice_free()
g_slice_free1, g_slice_free1 ()
g_slice_free_chain, g_slice_free_chain()
g_slice_free_chain_with_offset, g_slice_free_chain_with_offset ()
g_slice_new, g_slice_new()
g_slice_new0, g_slice_new0()
g_slist_alloc, g_slist_alloc ()
g_slist_append, g_slist_append ()
g_slist_concat, g_slist_concat ()
g_slist_copy, g_slist_copy ()
g_slist_delete_link, g_slist_delete_link ()
g_slist_find, g_slist_find ()
g_slist_find_custom, g_slist_find_custom ()
g_slist_foreach, g_slist_foreach ()
g_slist_free, g_slist_free ()
g_slist_free1, g_slist_free1
g_slist_free_1, g_slist_free_1 ()
g_slist_index, g_slist_index ()
g_slist_insert, g_slist_insert ()
g_slist_insert_before, g_slist_insert_before ()
g_slist_insert_sorted, g_slist_insert_sorted ()
g_slist_insert_sorted_with_data, g_slist_insert_sorted_with_data ()
g_slist_last, g_slist_last ()
g_slist_length, g_slist_length ()
g_slist_next, g_slist_next()
g_slist_nth, g_slist_nth ()
g_slist_nth_data, g_slist_nth_data ()
g_slist_pop_allocator, g_slist_pop_allocator ()
g_slist_position, g_slist_position ()
g_slist_prepend, g_slist_prepend ()
g_slist_push_allocator, g_slist_push_allocator ()
g_slist_remove, g_slist_remove ()
g_slist_remove_all, g_slist_remove_all ()
g_slist_remove_link, g_slist_remove_link ()
g_slist_reverse, g_slist_reverse ()
g_slist_sort, g_slist_sort ()
g_slist_sort_with_data, g_slist_sort_with_data ()
g_snprintf, g_snprintf ()
g_source_add_poll, g_source_add_poll ()
g_source_attach, g_source_attach ()
g_source_destroy, g_source_destroy ()
g_source_get_can_recurse, g_source_get_can_recurse ()
g_source_get_context, g_source_get_context ()
g_source_get_current_time, g_source_get_current_time ()
g_source_get_id, g_source_get_id ()
g_source_get_priority, g_source_get_priority ()
g_source_is_destroyed, g_source_is_destroyed ()
g_source_new, g_source_new ()
g_source_ref, g_source_ref ()
g_source_remove, g_source_remove ()
g_source_remove_by_funcs_user_data, g_source_remove_by_funcs_user_data ()
g_source_remove_by_user_data, g_source_remove_by_user_data ()
g_source_remove_poll, g_source_remove_poll ()
g_source_set_callback, g_source_set_callback ()
g_source_set_callback_indirect, g_source_set_callback_indirect ()
g_source_set_can_recurse, g_source_set_can_recurse ()
g_source_set_funcs, g_source_set_funcs ()
g_source_set_priority, g_source_set_priority ()
g_source_unref, g_source_unref ()
g_spaced_primes_closest, g_spaced_primes_closest ()
g_spawn_async, g_spawn_async ()
g_spawn_async_with_pipes, g_spawn_async_with_pipes ()
g_spawn_close_pid, g_spawn_close_pid ()
g_spawn_command_line_async, g_spawn_command_line_async ()
g_spawn_command_line_sync, g_spawn_command_line_sync ()
G_SPAWN_ERROR, G_SPAWN_ERROR
g_spawn_sync, g_spawn_sync ()
g_sprintf, g_sprintf ()
G_SQRT2, G_SQRT2
g_stat, g_stat ()
g_static_mutex_free, g_static_mutex_free ()
g_static_mutex_get_mutex, g_static_mutex_get_mutex ()
G_STATIC_MUTEX_INIT, G_STATIC_MUTEX_INIT
g_static_mutex_init, g_static_mutex_init ()
g_static_mutex_lock, g_static_mutex_lock ()
g_static_mutex_trylock, g_static_mutex_trylock ()
g_static_mutex_unlock, g_static_mutex_unlock ()
g_static_private_free, g_static_private_free ()
g_static_private_get, g_static_private_get ()
G_STATIC_PRIVATE_INIT, G_STATIC_PRIVATE_INIT
g_static_private_init, g_static_private_init ()
g_static_private_set, g_static_private_set ()
g_static_rec_mutex_free, g_static_rec_mutex_free ()
G_STATIC_REC_MUTEX_INIT, G_STATIC_REC_MUTEX_INIT
g_static_rec_mutex_init, g_static_rec_mutex_init ()
g_static_rec_mutex_lock, g_static_rec_mutex_lock ()
g_static_rec_mutex_lock_full, g_static_rec_mutex_lock_full ()
g_static_rec_mutex_trylock, g_static_rec_mutex_trylock ()
g_static_rec_mutex_unlock, g_static_rec_mutex_unlock ()
g_static_rec_mutex_unlock_full, g_static_rec_mutex_unlock_full ()
g_static_rw_lock_free, g_static_rw_lock_free ()
G_STATIC_RW_LOCK_INIT, G_STATIC_RW_LOCK_INIT
g_static_rw_lock_init, g_static_rw_lock_init ()
g_static_rw_lock_reader_lock, g_static_rw_lock_reader_lock ()
g_static_rw_lock_reader_trylock, g_static_rw_lock_reader_trylock ()
g_static_rw_lock_reader_unlock, g_static_rw_lock_reader_unlock ()
g_static_rw_lock_writer_lock, g_static_rw_lock_writer_lock ()
g_static_rw_lock_writer_trylock, g_static_rw_lock_writer_trylock ()
g_static_rw_lock_writer_unlock, g_static_rw_lock_writer_unlock ()
G_STMT_END, G_STMT_END
G_STMT_START, G_STMT_START
g_stpcpy, g_stpcpy ()
g_strcanon, g_strcanon ()
g_strcasecmp, g_strcasecmp ()
g_strchomp, g_strchomp ()
g_strchug, g_strchug ()
g_strcompress, g_strcompress ()
g_strconcat, g_strconcat ()
g_strdelimit, g_strdelimit ()
g_strdown, g_strdown ()
g_strdup, g_strdup ()
g_strdupv, g_strdupv ()
g_strdup_printf, g_strdup_printf ()
g_strdup_vprintf, g_strdup_vprintf ()
g_strerror, g_strerror ()
g_strescape, g_strescape ()
g_strfreev, g_strfreev ()
G_STRFUNC, G_STRFUNC
G_STRINGIFY, G_STRINGIFY()
g_string_append, g_string_append ()
g_string_append_c, g_string_append_c ()
g_string_append_len, g_string_append_len ()
g_string_append_printf, g_string_append_printf ()
g_string_append_unichar, g_string_append_unichar ()
g_string_ascii_down, g_string_ascii_down ()
g_string_ascii_up, g_string_ascii_up ()
g_string_assign, g_string_assign ()
g_string_chunk_free, g_string_chunk_free ()
g_string_chunk_insert, g_string_chunk_insert ()
g_string_chunk_insert_const, g_string_chunk_insert_const ()
g_string_chunk_insert_len, g_string_chunk_insert_len ()
g_string_chunk_new, g_string_chunk_new ()
g_string_down, g_string_down ()
g_string_equal, g_string_equal ()
g_string_erase, g_string_erase ()
g_string_free, g_string_free ()
g_string_hash, g_string_hash ()
g_string_insert, g_string_insert ()
g_string_insert_c, g_string_insert_c ()
g_string_insert_len, g_string_insert_len ()
g_string_insert_unichar, g_string_insert_unichar ()
g_string_new, g_string_new ()
g_string_new_len, g_string_new_len ()
g_string_prepend, g_string_prepend ()
g_string_prepend_c, g_string_prepend_c ()
g_string_prepend_len, g_string_prepend_len ()
g_string_prepend_unichar, g_string_prepend_unichar ()
g_string_printf, g_string_printf ()
g_string_set_size, g_string_set_size ()
g_string_sized_new, g_string_sized_new ()
g_string_sprintf, g_string_sprintf
g_string_sprintfa, g_string_sprintfa
g_string_truncate, g_string_truncate ()
g_string_up, g_string_up ()
g_strip_context, g_strip_context ()
g_strjoin, g_strjoin ()
g_strjoinv, g_strjoinv ()
g_strlcat, g_strlcat ()
g_strlcpy, g_strlcpy ()
G_STRLOC, G_STRLOC
g_strncasecmp, g_strncasecmp ()
g_strndup, g_strndup ()
g_strnfill, g_strnfill ()
g_strreverse, g_strreverse ()
g_strrstr, g_strrstr ()
g_strrstr_len, g_strrstr_len ()
g_strsignal, g_strsignal ()
g_strsplit, g_strsplit ()
g_strsplit_set, g_strsplit_set ()
g_strstrip, g_strstrip()
g_strstr_len, g_strstr_len ()
g_strtod, g_strtod ()
G_STRUCT_MEMBER, G_STRUCT_MEMBER()
G_STRUCT_MEMBER_P, G_STRUCT_MEMBER_P()
G_STRUCT_OFFSET, G_STRUCT_OFFSET()
g_strup, g_strup ()
g_strv_length, g_strv_length ()
G_STR_DELIMITERS, G_STR_DELIMITERS
g_str_equal, g_str_equal ()
g_str_hash, g_str_hash ()
g_str_has_prefix, g_str_has_prefix ()
g_str_has_suffix, g_str_has_suffix ()
G_THREADS_ENABLED, G_THREADS_ENABLED
G_THREADS_IMPL_NONE, G_THREADS_IMPL_NONE
G_THREADS_IMPL_POSIX, G_THREADS_IMPL_POSIX
g_thread_create, g_thread_create ()
g_thread_create_full, g_thread_create_full ()
G_THREAD_ERROR, G_THREAD_ERROR
g_thread_exit, g_thread_exit ()
g_thread_foreach, g_thread_foreach ()
g_thread_init, g_thread_init ()
g_thread_join, g_thread_join ()
g_thread_pool_free, g_thread_pool_free ()
g_thread_pool_get_max_idle_time, g_thread_pool_get_max_idle_time ()
g_thread_pool_get_max_threads, g_thread_pool_get_max_threads ()
g_thread_pool_get_max_unused_threads, g_thread_pool_get_max_unused_threads ()
g_thread_pool_get_num_threads, g_thread_pool_get_num_threads ()
g_thread_pool_get_num_unused_threads, g_thread_pool_get_num_unused_threads ()
g_thread_pool_new, g_thread_pool_new ()
g_thread_pool_push, g_thread_pool_push ()
g_thread_pool_set_max_idle_time, g_thread_pool_set_max_idle_time ()
g_thread_pool_set_max_threads, g_thread_pool_set_max_threads ()
g_thread_pool_set_max_unused_threads, g_thread_pool_set_max_unused_threads ()
g_thread_pool_set_sort_function, g_thread_pool_set_sort_function ()
g_thread_pool_stop_unused_threads, g_thread_pool_stop_unused_threads ()
g_thread_pool_unprocessed, g_thread_pool_unprocessed ()
g_thread_self, g_thread_self ()
g_thread_set_priority, g_thread_set_priority ()
g_thread_supported, g_thread_supported ()
g_thread_yield, g_thread_yield ()
g_timeout_add, g_timeout_add ()
g_timeout_add_full, g_timeout_add_full ()
g_timeout_source_new, g_timeout_source_new ()
g_timer_continue, g_timer_continue ()
g_timer_destroy, g_timer_destroy ()
g_timer_elapsed, g_timer_elapsed ()
g_timer_new, g_timer_new ()
g_timer_reset, g_timer_reset ()
g_timer_start, g_timer_start ()
g_timer_stop, g_timer_stop ()
g_time_val_add, g_time_val_add ()
g_time_val_from_iso8601, g_time_val_from_iso8601 ()
g_time_val_to_iso8601, g_time_val_to_iso8601 ()
g_trap_free_size, Traps and traces
g_trap_malloc_size, Traps and traces
g_trap_realloc_size, Traps and traces
g_trash_stack_height, g_trash_stack_height ()
g_trash_stack_peek, g_trash_stack_peek ()
g_trash_stack_pop, g_trash_stack_pop ()
g_trash_stack_push, g_trash_stack_push ()
g_tree_destroy, g_tree_destroy ()
g_tree_foreach, g_tree_foreach ()
g_tree_height, g_tree_height ()
g_tree_insert, g_tree_insert ()
g_tree_lookup, g_tree_lookup ()
g_tree_lookup_extended, g_tree_lookup_extended ()
g_tree_new, g_tree_new ()
g_tree_new_full, g_tree_new_full ()
g_tree_new_with_data, g_tree_new_with_data ()
g_tree_nnodes, g_tree_nnodes ()
g_tree_remove, g_tree_remove ()
g_tree_replace, g_tree_replace ()
g_tree_search, g_tree_search ()
g_tree_steal, g_tree_steal ()
g_tree_traverse, g_tree_traverse ()
G_TRYLOCK, G_TRYLOCK()
g_try_malloc, g_try_malloc ()
g_try_malloc0, g_try_malloc0 ()
g_try_new, g_try_new()
g_try_new0, g_try_new0()
g_try_realloc, g_try_realloc ()
g_try_renew, g_try_renew()
g_tuples_destroy, g_tuples_destroy ()
g_tuples_index, g_tuples_index ()
g_ucs4_to_utf16, g_ucs4_to_utf16 ()
g_ucs4_to_utf8, g_ucs4_to_utf8 ()
g_unichar_break_type, g_unichar_break_type ()
g_unichar_digit_value, g_unichar_digit_value ()
g_unichar_get_mirror_char, g_unichar_get_mirror_char ()
g_unichar_isalnum, g_unichar_isalnum ()
g_unichar_isalpha, g_unichar_isalpha ()
g_unichar_iscntrl, g_unichar_iscntrl ()
g_unichar_isdefined, g_unichar_isdefined ()
g_unichar_isdigit, g_unichar_isdigit ()
g_unichar_isgraph, g_unichar_isgraph ()
g_unichar_islower, g_unichar_islower ()
g_unichar_isprint, g_unichar_isprint ()
g_unichar_ispunct, g_unichar_ispunct ()
g_unichar_isspace, g_unichar_isspace ()
g_unichar_istitle, g_unichar_istitle ()
g_unichar_isupper, g_unichar_isupper ()
g_unichar_iswide, g_unichar_iswide ()
g_unichar_iswide_cjk, g_unichar_iswide_cjk ()
g_unichar_isxdigit, g_unichar_isxdigit ()
g_unichar_tolower, g_unichar_tolower ()
g_unichar_totitle, g_unichar_totitle ()
g_unichar_toupper, g_unichar_toupper ()
g_unichar_to_utf8, g_unichar_to_utf8 ()
g_unichar_type, g_unichar_type ()
g_unichar_validate, g_unichar_validate ()
g_unichar_xdigit_value, g_unichar_xdigit_value ()
g_unicode_canonical_decomposition, g_unicode_canonical_decomposition ()
g_unicode_canonical_ordering, g_unicode_canonical_ordering ()
G_UNLIKELY, G_UNLIKELY()
g_unlink, g_unlink ()
G_UNLOCK, G_UNLOCK()
g_unsetenv, g_unsetenv ()
g_uri_list_extract_uris, g_uri_list_extract_uris ()
G_USEC_PER_SEC, G_USEC_PER_SEC
g_usleep, g_usleep ()
g_utf16_to_ucs4, g_utf16_to_ucs4 ()
g_utf16_to_utf8, g_utf16_to_utf8 ()
g_utf8_casefold, g_utf8_casefold ()
g_utf8_collate, g_utf8_collate ()
g_utf8_collate_key, g_utf8_collate_key ()
g_utf8_collate_key_for_filename, g_utf8_collate_key_for_filename ()
g_utf8_find_next_char, g_utf8_find_next_char ()
g_utf8_find_prev_char, g_utf8_find_prev_char ()
g_utf8_get_char, g_utf8_get_char ()
g_utf8_get_char_validated, g_utf8_get_char_validated ()
g_utf8_next_char, g_utf8_next_char()
g_utf8_normalize, g_utf8_normalize ()
g_utf8_offset_to_pointer, g_utf8_offset_to_pointer ()
g_utf8_pointer_to_offset, g_utf8_pointer_to_offset ()
g_utf8_prev_char, g_utf8_prev_char ()
g_utf8_strchr, g_utf8_strchr ()
g_utf8_strdown, g_utf8_strdown ()
g_utf8_strlen, g_utf8_strlen ()
g_utf8_strncpy, g_utf8_strncpy ()
g_utf8_strrchr, g_utf8_strrchr ()
g_utf8_strreverse, g_utf8_strreverse ()
g_utf8_strup, g_utf8_strup ()
g_utf8_to_ucs4, g_utf8_to_ucs4 ()
g_utf8_to_ucs4_fast, g_utf8_to_ucs4_fast ()
g_utf8_to_utf16, g_utf8_to_utf16 ()
g_utf8_validate, g_utf8_validate ()
g_vasprintf, g_vasprintf ()
G_VA_COPY, G_VA_COPY()
g_vfprintf, g_vfprintf ()
g_vprintf, g_vprintf ()
g_vsnprintf, g_vsnprintf ()
g_vsprintf, g_vsprintf ()
g_warning, g_warning()
G_WIN32_DLLMAIN_FOR_DLL_NAME, G_WIN32_DLLMAIN_FOR_DLL_NAME()
g_win32_error_message, g_win32_error_message ()
g_win32_getlocale, g_win32_getlocale ()
g_win32_get_package_installation_directory, g_win32_get_package_installation_directory ()
g_win32_get_package_installation_subdirectory, g_win32_get_package_installation_subdirectory ()
g_win32_get_windows_version, g_win32_get_windows_version ()
G_WIN32_HAVE_WIDECHAR_API, G_WIN32_HAVE_WIDECHAR_API()
G_WIN32_IS_NT_BASED, G_WIN32_IS_NT_BASED()
g_win32_locale_filename_from_utf8, g_win32_locale_filename_from_utf8 ()

M

MAX, MAX()
MAXPATHLEN, MAXPATHLEN
MIN, MIN()

N

NULL, NULL
N_, N_()

P

pipe, pipe()

Q

Q_, Q_()

T

TRUE, TRUE


Index of deprecated symbols

Symbols

G

GAllocator, GAllocator
GMemChunk, GMemChunk
g_allocator_free, g_allocator_free ()
g_allocator_new, g_allocator_new ()
G_ALLOC_AND_FREE, G_ALLOC_AND_FREE
G_ALLOC_ONLY, G_ALLOC_ONLY
g_async_queue_ref_unlocked, g_async_queue_ref_unlocked ()
g_async_queue_unref_and_unlock, g_async_queue_unref_and_unlock ()
g_basename, g_basename ()
g_blow_chunks, g_blow_chunks ()
g_cache_value_foreach, g_cache_value_foreach ()
g_chunk_free, g_chunk_free()
g_chunk_new, g_chunk_new()
g_chunk_new0, g_chunk_new0()
g_date_set_time, g_date_set_time ()
g_dirname, g_dirname
g_hash_table_freeze, g_hash_table_freeze()
g_hash_table_thaw, g_hash_table_thaw()
G_HAVE_GINT64, G_HAVE_GINT64
g_io_channel_close, g_io_channel_close ()
g_io_channel_read, g_io_channel_read ()
g_io_channel_seek, g_io_channel_seek ()
g_io_channel_write, g_io_channel_write ()
g_list_pop_allocator, g_list_pop_allocator ()
g_list_push_allocator, g_list_push_allocator ()
g_main_destroy, g_main_destroy()
g_main_is_running, g_main_is_running()
g_main_iteration, g_main_iteration()
g_main_new, g_main_new()
g_main_pending, g_main_pending()
g_main_quit, g_main_quit()
g_main_run, g_main_run()
g_main_set_poll_func, g_main_set_poll_func()
g_mem_chunk_alloc, g_mem_chunk_alloc ()
g_mem_chunk_alloc0, g_mem_chunk_alloc0 ()
g_mem_chunk_clean, g_mem_chunk_clean ()
g_mem_chunk_create, g_mem_chunk_create()
g_mem_chunk_destroy, g_mem_chunk_destroy ()
g_mem_chunk_free, g_mem_chunk_free ()
g_mem_chunk_info, g_mem_chunk_info ()
g_mem_chunk_new, g_mem_chunk_new ()
g_mem_chunk_print, g_mem_chunk_print ()
g_mem_chunk_reset, g_mem_chunk_reset ()
g_node_pop_allocator, g_node_pop_allocator ()
g_node_push_allocator, g_node_push_allocator ()
g_scanner_add_symbol, g_scanner_add_symbol()
g_scanner_foreach_symbol, g_scanner_foreach_symbol()
g_scanner_freeze_symbol_table, g_scanner_freeze_symbol_table()
g_scanner_remove_symbol, g_scanner_remove_symbol()
g_scanner_thaw_symbol_table, g_scanner_thaw_symbol_table()
g_slist_pop_allocator, g_slist_pop_allocator ()
g_slist_push_allocator, g_slist_push_allocator ()
g_strcasecmp, g_strcasecmp ()
g_strdown, g_strdown ()
g_string_down, g_string_down ()
g_string_sprintf, g_string_sprintf
g_string_sprintfa, g_string_sprintfa
g_string_up, g_string_up ()
g_strncasecmp, g_strncasecmp ()
g_strup, g_strup ()
g_tree_traverse, g_tree_traverse ()


Index of new symbols in 2.2

Symbols

G

g_ascii_strtoull, g_ascii_strtoull ()
g_fprintf, g_fprintf ()
g_get_application_name, g_get_application_name ()
G_GNUC_DEPRECATED, G_GNUC_DEPRECATED
G_LIKELY, G_LIKELY()
g_markup_parse_context_get_element, g_markup_parse_context_get_element ()
g_printf, g_printf ()
g_sprintf, g_sprintf ()
g_str_has_prefix, g_str_has_prefix ()
g_str_has_suffix, g_str_has_suffix ()
G_UNLIKELY, G_UNLIKELY()
g_utf8_strreverse, g_utf8_strreverse ()
g_vfprintf, g_vfprintf ()
g_vprintf, g_vprintf ()
g_vsprintf, g_vsprintf ()


Index of new symbols in 2.4

Symbols

_, _()

G

GCopyFunc, GCopyFunc ()
GOnce, GOnce
GOnceStatus, enum GOnceStatus
g_array_remove_range, g_array_remove_range ()
g_atomic_int_add, g_atomic_int_add ()
g_atomic_int_compare_and_exchange, g_atomic_int_compare_and_exchange ()
g_atomic_int_dec_and_test, g_atomic_int_dec_and_test ()
g_atomic_int_exchange_and_add, g_atomic_int_exchange_and_add ()
g_atomic_int_get, g_atomic_int_get ()
g_atomic_int_inc, g_atomic_int_inc ()
g_atomic_pointer_compare_and_exchange, g_atomic_pointer_compare_and_exchange ()
g_atomic_pointer_get, g_atomic_pointer_get ()
g_byte_array_remove_range, g_byte_array_remove_range ()
g_child_watch_add, g_child_watch_add ()
g_child_watch_add_full, g_child_watch_add_full ()
g_child_watch_source_new, g_child_watch_source_new ()
g_completion_complete_utf8, g_completion_complete_utf8 ()
g_file_read_link, g_file_read_link ()
G_GINT16_MODIFIER, G_GINT16_MODIFIER
G_GINT32_MODIFIER, G_GINT32_MODIFIER
G_GINT64_MODIFIER, G_GINT64_MODIFIER
g_hash_table_find, g_hash_table_find ()
g_markup_printf_escaped, g_markup_printf_escaped ()
g_markup_vprintf_escaped, g_markup_vprintf_escaped ()
G_MAXINT16, G_MAXINT16
G_MAXINT32, G_MAXINT32
G_MAXINT8, G_MAXINT8
G_MAXSIZE, G_MAXSIZE
G_MAXUINT16, G_MAXUINT16
G_MAXUINT32, G_MAXUINT32
G_MAXUINT8, G_MAXUINT8
G_MININT16, G_MININT16
G_MININT32, G_MININT32
G_MININT8, G_MININT8
g_node_copy_deep, g_node_copy_deep ()
g_once, g_once()
G_ONCE_INIT, G_ONCE_INIT
g_ptr_array_foreach, g_ptr_array_foreach ()
g_ptr_array_remove_range, g_ptr_array_remove_range ()
g_queue_copy, g_queue_copy ()
g_queue_delete_link, g_queue_delete_link ()
g_queue_find, g_queue_find ()
g_queue_find_custom, g_queue_find_custom ()
g_queue_foreach, g_queue_foreach ()
g_queue_get_length, g_queue_get_length ()
g_queue_index, g_queue_index ()
g_queue_insert_after, g_queue_insert_after ()
g_queue_insert_before, g_queue_insert_before ()
g_queue_insert_sorted, g_queue_insert_sorted ()
g_queue_link_index, g_queue_link_index ()
g_queue_peek_head_link, g_queue_peek_head_link ()
g_queue_peek_nth, g_queue_peek_nth ()
g_queue_peek_nth_link, g_queue_peek_nth_link ()
g_queue_peek_tail_link, g_queue_peek_tail_link ()
g_queue_pop_nth, g_queue_pop_nth ()
g_queue_pop_nth_link, g_queue_pop_nth_link ()
g_queue_push_nth, g_queue_push_nth ()
g_queue_push_nth_link, g_queue_push_nth_link ()
g_queue_remove, g_queue_remove ()
g_queue_remove_all, g_queue_remove_all ()
g_queue_reverse, g_queue_reverse ()
g_queue_sort, g_queue_sort ()
g_queue_unlink, g_queue_unlink ()
g_rand_copy, g_rand_copy ()
g_rand_new_with_seed_array, g_rand_new_with_seed_array ()
g_rand_set_seed_array, g_rand_set_seed_array ()
g_setenv, g_setenv ()
G_STRFUNC, G_STRFUNC
g_string_chunk_insert_len, g_string_chunk_insert_len ()
g_strip_context, g_strip_context ()
g_strsplit_set, g_strsplit_set ()
g_timer_continue, g_timer_continue ()
g_unichar_get_mirror_char, g_unichar_get_mirror_char ()
g_unsetenv, g_unsetenv ()
g_vasprintf, g_vasprintf ()

N

N_, N_()

Q

Q_, Q_()


Index of new symbols in 2.6

Symbols

G

glib_check_version, glib_check_version ()
g_date_get_iso8601_week_of_year, g_date_get_iso8601_week_of_year ()
g_debug, g_debug()
g_filename_display_basename, g_filename_display_basename ()
g_filename_display_name, g_filename_display_name ()
g_fopen, g_fopen ()
g_freopen, g_freopen ()
g_get_filename_charsets, g_get_filename_charsets ()
g_get_language_names, g_get_language_names ()
g_get_system_config_dirs, g_get_system_config_dirs ()
g_get_system_data_dirs, g_get_system_data_dirs ()
g_get_user_cache_dir, g_get_user_cache_dir ()
g_get_user_config_dir, g_get_user_config_dir ()
g_get_user_data_dir, g_get_user_data_dir ()
G_GNUC_MALLOC, G_GNUC_MALLOC
G_GSIZE_FORMAT, G_GSIZE_FORMAT
G_GSIZE_MODIFIER, G_GSIZE_MODIFIER
G_GSSIZE_FORMAT, G_GSSIZE_FORMAT
G_IS_DIR_SEPARATOR, G_IS_DIR_SEPARATOR()
g_key_file_free, g_key_file_free ()
g_key_file_get_boolean, g_key_file_get_boolean ()
g_key_file_get_boolean_list, g_key_file_get_boolean_list ()
g_key_file_get_comment, g_key_file_get_comment ()
g_key_file_get_groups, g_key_file_get_groups ()
g_key_file_get_integer, g_key_file_get_integer ()
g_key_file_get_integer_list, g_key_file_get_integer_list ()
g_key_file_get_keys, g_key_file_get_keys ()
g_key_file_get_locale_string, g_key_file_get_locale_string ()
g_key_file_get_locale_string_list, g_key_file_get_locale_string_list ()
g_key_file_get_start_group, g_key_file_get_start_group ()
g_key_file_get_string, g_key_file_get_string ()
g_key_file_get_string_list, g_key_file_get_string_list ()
g_key_file_get_value, g_key_file_get_value ()
g_key_file_has_group, g_key_file_has_group ()
g_key_file_has_key, g_key_file_has_key ()
g_key_file_load_from_data, g_key_file_load_from_data ()
g_key_file_load_from_data_dirs, g_key_file_load_from_data_dirs ()
g_key_file_load_from_file, g_key_file_load_from_file ()
g_key_file_new, g_key_file_new ()
g_key_file_remove_comment, g_key_file_remove_comment ()
g_key_file_remove_group, g_key_file_remove_group ()
g_key_file_remove_key, g_key_file_remove_key ()
g_key_file_set_boolean, g_key_file_set_boolean ()
g_key_file_set_boolean_list, g_key_file_set_boolean_list ()
g_key_file_set_comment, g_key_file_set_comment ()
g_key_file_set_integer, g_key_file_set_integer ()
g_key_file_set_integer_list, g_key_file_set_integer_list ()
g_key_file_set_list_separator, g_key_file_set_list_separator ()
g_key_file_set_locale_string, g_key_file_set_locale_string ()
g_key_file_set_locale_string_list, g_key_file_set_locale_string_list ()
g_key_file_set_string, g_key_file_set_string ()
g_key_file_set_string_list, g_key_file_set_string_list ()
g_key_file_set_value, g_key_file_set_value ()
g_key_file_to_data, g_key_file_to_data ()
g_log_set_default_handler, g_log_set_default_handler ()
g_lstat, g_lstat ()
g_mkdir, g_mkdir ()
g_open, g_open ()
g_option_context_add_group, g_option_context_add_group ()
g_option_context_add_main_entries, g_option_context_add_main_entries ()
g_option_context_free, g_option_context_free ()
g_option_context_get_help_enabled, g_option_context_get_help_enabled ()
g_option_context_get_ignore_unknown_options, g_option_context_get_ignore_unknown_options ()
g_option_context_get_main_group, g_option_context_get_main_group ()
g_option_context_new, g_option_context_new ()
g_option_context_parse, g_option_context_parse ()
g_option_context_set_help_enabled, g_option_context_set_help_enabled ()
g_option_context_set_ignore_unknown_options, g_option_context_set_ignore_unknown_options ()
g_option_context_set_main_group, g_option_context_set_main_group ()
g_option_group_add_entries, g_option_group_add_entries ()
g_option_group_free, g_option_group_free ()
g_option_group_new, g_option_group_new ()
g_option_group_set_error_hook, g_option_group_set_error_hook ()
g_option_group_set_parse_hooks, g_option_group_set_parse_hooks ()
g_option_group_set_translate_func, g_option_group_set_translate_func ()
g_option_group_set_translation_domain, g_option_group_set_translation_domain ()
G_OPTION_REMAINING, G_OPTION_REMAINING
g_remove, g_remove ()
g_rename, g_rename ()
g_rmdir, g_rmdir ()
g_stat, g_stat ()
g_strv_length, g_strv_length ()
g_unlink, g_unlink ()
g_uri_list_extract_uris, g_uri_list_extract_uris ()
g_win32_get_windows_version, g_win32_get_windows_version ()
G_WIN32_HAVE_WIDECHAR_API, G_WIN32_HAVE_WIDECHAR_API()
G_WIN32_IS_NT_BASED, G_WIN32_IS_NT_BASED()


Index of new symbols in 2.8

Symbols

G

g_access, g_access ()
g_build_filenamev, g_build_filenamev ()
g_build_pathv, g_build_pathv ()
g_chdir, g_chdir ()
g_chmod, g_chmod ()
g_creat, g_creat ()
g_datalist_get_flags, g_datalist_get_flags ()
g_datalist_set_flags, g_datalist_set_flags ()
g_datalist_unset_flags, g_datalist_unset_flags ()
g_file_set_contents, g_file_set_contents ()
g_get_host_name, g_get_host_name ()
g_listenv, g_listenv ()
g_mapped_file_free, g_mapped_file_free ()
g_mapped_file_get_contents, g_mapped_file_get_contents ()
g_mapped_file_get_length, g_mapped_file_get_length ()
g_mapped_file_new, g_mapped_file_new ()
g_mkdir_with_parents, g_mkdir_with_parents ()
g_try_malloc0, g_try_malloc0 ()
g_try_new, g_try_new()
g_try_new0, g_try_new0()
g_try_renew, g_try_renew()
g_utf8_collate_key_for_filename, g_utf8_collate_key_for_filename ()
g_win32_locale_filename_from_utf8, g_win32_locale_filename_from_utf8 ()


Index of new symbols in 2.10

Symbols

G

g_async_queue_push_sorted, g_async_queue_push_sorted ()
g_async_queue_push_sorted_unlocked, g_async_queue_push_sorted_unlocked ()
g_async_queue_sort, g_async_queue_sort ()
g_async_queue_sort_unlocked, g_async_queue_sort_unlocked ()
g_atomic_int_set, g_atomic_int_set ()
g_atomic_pointer_set, g_atomic_pointer_set ()
g_date_set_time_t, g_date_set_time_t ()
g_date_set_time_val, g_date_set_time_val ()
G_GNUC_WARN_UNUSED_RESULT, G_GNUC_WARN_UNUSED_RESULT
G_GUINT64_CONSTANT, G_GUINT64_CONSTANT()
g_hash_table_ref, g_hash_table_ref ()
g_hash_table_unref, g_hash_table_unref ()
g_intern_static_string, g_intern_static_string ()
g_intern_string, g_intern_string ()
g_main_context_is_owner, g_main_context_is_owner ()
g_slice_alloc, g_slice_alloc ()
g_slice_alloc0, g_slice_alloc0 ()
g_slice_free, g_slice_free()
g_slice_free1, g_slice_free1 ()
g_slice_free_chain, g_slice_free_chain()
g_slice_free_chain_with_offset, g_slice_free_chain_with_offset ()
g_slice_new, g_slice_new()
g_slice_new0, g_slice_new0()
g_slist_free1, g_slist_free1
g_thread_foreach, g_thread_foreach ()
g_thread_pool_get_max_idle_time, g_thread_pool_get_max_idle_time ()
g_thread_pool_set_max_idle_time, g_thread_pool_set_max_idle_time ()
g_thread_pool_set_sort_function, g_thread_pool_set_sort_function ()


Index of new symbols in 2.12

Symbols

G

g_ascii_strtoll, g_ascii_strtoll ()
g_base64_decode, g_base64_decode ()
g_base64_decode_step, g_base64_decode_step ()
g_base64_encode, g_base64_encode ()
g_base64_encode_close, g_base64_encode_close ()
g_base64_encode_step, g_base64_encode_step ()
g_bookmark_file_add_application, g_bookmark_file_add_application ()
g_bookmark_file_add_group, g_bookmark_file_add_group ()
g_bookmark_file_free, g_bookmark_file_free ()
g_bookmark_file_get_added, g_bookmark_file_get_added ()
g_bookmark_file_get_applications, g_bookmark_file_get_applications ()
g_bookmark_file_get_app_info, g_bookmark_file_get_app_info ()
g_bookmark_file_get_description, g_bookmark_file_get_description ()
g_bookmark_file_get_groups, g_bookmark_file_get_groups ()
g_bookmark_file_get_icon, g_bookmark_file_get_icon ()
g_bookmark_file_get_is_private, g_bookmark_file_get_is_private ()
g_bookmark_file_get_mime_type, g_bookmark_file_get_mime_type ()
g_bookmark_file_get_modified, g_bookmark_file_get_modified ()
g_bookmark_file_get_size, g_bookmark_file_get_size ()
g_bookmark_file_get_title, g_bookmark_file_get_title ()
g_bookmark_file_get_uris, g_bookmark_file_get_uris ()
g_bookmark_file_get_visited, g_bookmark_file_get_visited ()
g_bookmark_file_has_application, g_bookmark_file_has_application ()
g_bookmark_file_has_group, g_bookmark_file_has_group ()
g_bookmark_file_has_item, g_bookmark_file_has_item ()
g_bookmark_file_load_from_data, g_bookmark_file_load_from_data ()
g_bookmark_file_load_from_data_dirs, g_bookmark_file_load_from_data_dirs ()
g_bookmark_file_load_from_file, g_bookmark_file_load_from_file ()
g_bookmark_file_move_item, g_bookmark_file_move_item ()
g_bookmark_file_new, g_bookmark_file_new ()
g_bookmark_file_remove_application, g_bookmark_file_remove_application ()
g_bookmark_file_remove_group, g_bookmark_file_remove_group ()
g_bookmark_file_remove_item, g_bookmark_file_remove_item ()
g_bookmark_file_set_added, g_bookmark_file_set_added ()
g_bookmark_file_set_app_info, g_bookmark_file_set_app_info ()
g_bookmark_file_set_description, g_bookmark_file_set_description ()
g_bookmark_file_set_groups, g_bookmark_file_set_groups ()
g_bookmark_file_set_icon, g_bookmark_file_set_icon ()
g_bookmark_file_set_is_private, g_bookmark_file_set_is_private ()
g_bookmark_file_set_mime_type, g_bookmark_file_set_mime_type ()
g_bookmark_file_set_modified, g_bookmark_file_set_modified ()
g_bookmark_file_set_title, g_bookmark_file_set_title ()
g_bookmark_file_set_visited, g_bookmark_file_set_visited ()
g_bookmark_file_to_data, g_bookmark_file_to_data ()
g_bookmark_file_to_file, g_bookmark_file_to_file ()
g_hash_table_remove_all, g_hash_table_remove_all ()
g_hash_table_steal_all, g_hash_table_steal_all ()
g_key_file_get_double, g_key_file_get_double ()
g_key_file_get_double_list, g_key_file_get_double_list ()
g_key_file_set_double, g_key_file_set_double ()
g_key_file_set_double_list, g_key_file_set_double_list ()
g_main_current_source, g_main_current_source ()
g_option_context_get_description, g_option_context_get_description ()
g_option_context_get_summary, g_option_context_get_summary ()
g_option_context_set_description, g_option_context_set_description ()
g_option_context_set_summary, g_option_context_set_summary ()
g_option_context_set_translate_func, g_option_context_set_translate_func ()
g_option_context_set_translation_domain, g_option_context_set_translation_domain ()
g_source_is_destroyed, g_source_is_destroyed ()
g_source_set_funcs, g_source_set_funcs ()
g_time_val_from_iso8601, g_time_val_from_iso8601 ()
g_time_val_to_iso8601, g_time_val_to_iso8601 ()
g_unichar_iswide_cjk, g_unichar_iswide_cjk ()


GLib Tools

glib-gettextize — gettext internationalization utility


Background

Data types and programming
Exporting a C API

GObject, and its lower-level type system, GType, are used by GTK+ and most Gnome libraries to provide:

  • object-oriented C-based APIs and

  • automatic transparent API bindings to other compiled or interpreted languages.

A lot of programmers are used to work with compiled-only or dynamically interpreted-only languages and do not understand the challenges associated with cross-language interoperability. This introduction tries to provide an insight into these challenges. describes briefly the solution choosen by GLib.

The following chapters go into greater detail into how GType and GObject work and how you can use them as a C programmer. It is useful to keep in mind that allowing access to C objects from other interpreted languages was one of the major design goals: this can often explain the sometimes rather convoluted APIs and features present in this library.

Data types and programming

One could say (I have seen such definitions used in some textbooks on programming language theory) that a programming language is merely a way to create data types and manipulate them. Most languages provide a number of language-native types and a few primitives to create more complex types based on these primitive types.

In C, the language provides types such as char, long, pointer. During compilation of C code, the compiler maps these language types to the compiler's target architecture machine types. If you are using a C interpreter (I have never seen one myself but it is possible :), the interpreter (the program which interprets the source code and executes it) maps the language types to the machine types of the target machine at runtime, during the program execution (or just before execution if it uses a Just In Time compiler engine).

Perl and Python which are interpreted languages do not really provide type definitions similar to those used by C. Perl and Python programmers manipulate variables and the type of the variables is decided only upon the first assignment or upon the first use which forces a type on the variable. The interpreter also often provides a lot of automatic conversions from one type to the other. For example, in Perl, a variable which holds an integer can be automatically converted to a string given the required context:

my $tmp = 10;
print "this is an integer converted to a string:" . $tmp . "\n";

Of course, it is also often possible to explicitely specify conversions when the default conversions provided by the language are not intuitive.


Exporting a C API

C APIs are defined by a set of functions and global variables which are usually exported from a binary. C functions have an arbitrary number of arguments and one return value. Each function is thus uniquely identified by the function name and the set of C types which describe the function arguments and return value. The global variables exported by the API are similarly identified by their name and their type.

A C API is thus merely defined by a set of names to which a set of types are associated. If you know the function calling convention and the mapping of the C types to the machine types used by the platform you are on, you can resolve the name of each function to find where the code associated to this function is located in memory, and then construct a valid argument list for the function. Finally, all you have to do is triger a call to the target C function with the argument list.

For the sake of discussion, here is a sample C function and the associated 32 bit x86 assembly code generated by gcc on my linux box:

static void function_foo (int foo)
{}

int main (int argc, char *argv[])
{

        function_foo (10);

        return 0;
}

push   $0xa
call   0x80482f4 <function_foo>

The assembly code shown above is pretty straightforward: the first instruction pushes the hexadecimal value 0xa (decimal value 10) as a 32 bit integer on the stack and calls function_foo. As you can see, C function calls are implemented by gcc by native function calls (this is probably the fastest implementation possible).

Now, let's say we want to call the C function function_foo from a python program. To do this, the python interpreter needs to:

  • Find where the function is located. This means probably find the binary generated by the C compiler which exports this functions.

  • Load the code of the function in executable memory.

  • Convert the python parameters to C-compatible parameters before calling the function.

  • Call the function with the right calling convention

  • Convert the return values of the C function to python-compatible variables to return them to the python code.

The process described above is pretty complex and there are a lot of ways to make it entirely automatic and transparent to the C and the Python programmers:

  • The first solution is to write by hand a lot of glue code, once for each function exported or imported, which does the python to C parameter conversion and the C to python return value conversion. This glue code is then linked with the interpreter which allows python programs to call a python functions which delegates the work to the C function.

  • Another nicer solution is to automatically generate the glue code, once for each function exported or imported, with a special compiler which reads the original function signature.

  • The solution used by GLib is to use the GType library which holds at runtime a description of all the objects manipulated by the programmer. This so-called dynamic type[1] library is then used by special generic glue code to automatically convert function parameters and function calling conventions between different runtime domains.

The greatest advantage of the solution implemented by GType is that the glue code sitting at the runtime domain boundaries is written once: the figure below states this more clearly.

Figure 1.

Currently, there exist at least Python and Perl generic glue code which makes it possible to use C objects written with GType directly in Python or Perl, with a minimum amount of work: there is no need to generate huge amounts of glue code either automatically or by hand.

Although that goal was arguably laudable, its pursuit has had a major influence on the whole GType/GObject library. C programmers are likely to be puzzled at the complexity of the features exposed in the following chapters if they forget that the GType/GObject library was not only designed to offer OO-like features to C programmers but also transparent cross-language interoperability.

[1] There are numerous different implementations of dynamic type systems: all C++ compilers have one, Java and .NET have one too. A dynamic type system allows you to get information about every instantiated object at runtime. It can be implemented by a process-specific database: every new object created registers the characteristics of its associated type in the type system. It can also be implemented by introspection interfaces. The common point between all these different type systems and implementations is that they all allow you to query for object metadata at runtime.


The Glib Dynamic Type System

Copy functions
Conventions
Non-Instantiable non-classed fundamental types
Instantiable classed types: objects
Non-instantiable classed types: Interfaces.
Interface Initialization
Interface Destruction

A type, as manipulated by the Glib type system, is much more generic than what is usually understood as an Object type. It is best explained by looking at the structure and the functions used to register new types in the type system.

typedef struct _GTypeInfo               GTypeInfo;
struct _GTypeInfo
{
  /* interface types, classed types, instantiated types */
  guint16                class_size;

  GBaseInitFunc          base_init;
  GBaseFinalizeFunc      base_finalize;

  /* classed types, instantiated types */
  GClassInitFunc         class_init;
  GClassFinalizeFunc     class_finalize;
  gconstpointer          class_data;

  /* instantiated types */
  guint16                instance_size;
  guint16                n_preallocs;
  GInstanceInitFunc      instance_init;

  /* value handling */
  const GTypeValueTable *value_table;
};
GType g_type_register_static (GType             parent_type,
                              const gchar      *type_name,
                              const GTypeInfo  *info,
                              GTypeFlags        flags);
GType g_type_register_fundamental (GType                       type_id,
                                   const gchar                *type_name,
                                   const GTypeInfo            *info,
                                   const GTypeFundamentalInfo *finfo,
                                   GTypeFlags                  flags);

g_type_register_static and g_type_register_fundamental are the C functions, defined in gtype.h and implemented in gtype.c which you should use to register a new GType in the program's type system. It is not likely you will ever need to use g_type_register_fundamental (you have to be Tim Janik to do that) but in case you want to, the last chapter explains how to create new fundamental types. [2]

Fundamental types are top-level types which do not derive from any other type while other non-fundamental types derive from other types. Upon initialization by g_type_init, the type system not only initializes its internal data structures but it also registers a number of core types: some of these are fundamental types. Others are types derived from these fundamental types.

Fundamental and non-Fundamental types are defined by:

  • class size: the class_size field in GTypeInfo.

  • class initialization functions (C++ constructor): the base_init and class_init fields in GTypeInfo.

  • class destruction functions (C++ destructor): the base_finalize and class_finalize fields in GTypeInfo.

  • instance size (C++ parameter to new): the instance_size field in GTypeInfo.

  • instanciation policy (C++ type of new operator): the n_preallocs field in GTypeInfo.

  • copy functions (C++ copy operators): the value_table field in GTypeInfo.

  • type characteristic flags: GTypeFlags.

Fundamental types are also defined by a set of GTypeFundamentalFlags which are stored in a GTypeFundamentalInfo. Non-Fundamental types are furthermore defined by the type of their parent which is passed as the parent_type parameter to g_type_register_static and g_type_register_dynamic.

Copy functions

The major common point between all glib types (fundamental and non-fundamental, classed and non-classed, instantiable and non-instantiable) is that they can all be manipulated through a single API to copy/assign them.

The GValue structure is used as an abstract container for all of these types. Its simplistic API (defined in gobject/gvalue.h) can be used to invoke the value_table functions registered during type registration: for example g_value_copy copies the content of a GValue to another GValue. This is similar to a C++ assignment which invokes the C++ copy operator to modify the default bit-by-bit copy semantics of C++/C structures/classes.

The following code shows how you can copy around a 64 bit integer, as well as a GObject instance pointer (sample code for this is located in the source tarball for this document in sample/gtype/test.c):

static void test_int (void)
{
  GValue a_value = {0, };
  GValue b_value = {0, };
  guint64 a, b;

  a = 0xdeadbeaf;

  g_value_init (&a_value, G_TYPE_UINT64);
  g_value_set_uint64 (&a_value, a);

  g_value_init (&b_value, G_TYPE_UINT64);
  g_value_copy (&a_value, &b_value);

  b = g_value_get_uint64 (&b_value);

  if (a == b) {
    g_print ("Yay !! 10 lines of code to copy around a uint64.\n");
  } else {
    g_print ("Are you sure this is not a Z80 ?\n");
  }
}

static void test_object (void)
{
  GObject *obj;
  GValue obj_vala = {0, };
  GValue obj_valb = {0, };
  obj = g_object_new (MAMAN_BAR_TYPE, NULL);

  g_value_init (&obj_vala, MAMAN_BAR_TYPE);
  g_value_set_object (&obj_vala, obj);

  g_value_init (&obj_valb, G_TYPE_OBJECT);

  /* g_value_copy's semantics for G_TYPE_OBJECT types is to copy the reference.
     This function thus calls g_object_ref.
     It is interesting to note that the assignment works here because
     MAMAN_BAR_TYPE is a G_TYPE_OBJECT.
   */
  g_value_copy (&obj_vala, &obj_valb);

  g_object_unref (G_OBJECT (obj));
  g_object_unref (G_OBJECT (obj));
}

The important point about the above code is that the exact semantic of the copy calls is undefined since they depend on the implementation of the copy function. Certain copy functions might decide to allocate a new chunk of memory and then to copy the data from the source to the destination. Others might want to simply increment the reference count of the instance and copy the reference to the new GValue.

The value_table used to specify these assignment functions is defined in gtype.h and is thoroughly described in the API documentation provided with GObject (for once ;-) which is why we will not detail its exact semantics.

typedef struct _GTypeValueTable         GTypeValueTable;
struct _GTypeValueTable
{
  void     (*value_init)         (GValue       *value);
  void     (*value_free)         (GValue       *value);
  void     (*value_copy)         (const GValue *src_value,
                  GValue       *dest_value);
  /* varargs functionality (optional) */
  gpointer (*value_peek_pointer) (const GValue *value);
  gchar	    *collect_format;
  gchar*   (*collect_value)      (GValue       *value,
                  guint         n_collect_values,
                  GTypeCValue  *collect_values,
                  guint		collect_flags);
  gchar	    *lcopy_format;
  gchar*   (*lcopy_value)        (const GValue *value,
                  guint         n_collect_values,
                  GTypeCValue  *collect_values,
                  guint		collect_flags);
};

Interestingly, it is also very unlikely you will ever need to specify a value_table during type registration because these value_tables are inherited from the parent types for non-fundamental types which means that unless you want to write a fundamental type (not a great idea !), you will not need to provide a new value_table since you will inherit the value_table structure from your parent type.

[2] Please, note that there exist another registration function: the g_type_register_dynamic. We will not discuss this function here since its use is very similar to the _static version.


Interface definition prerequisites

To specify that an interface requires the presence of other interfaces when implemented, GObject introduces the concept of prerequisites: it is possible to associate a list of prerequisite interfaces to an interface. For example, if object A wishes to implement interface I1, and if interface I1 has a prerequisite on interface I2, A has to implement both I1 and I2.

The mechanism described above is, in practice, very similar to Java's interface I1 extends interface I2. The example below shows the GObject equivalent:

  type = g_type_register_static (G_TYPE_INTERFACE, "MamanIbar", &info, 0);
  /* Make the MamanIbar interface require MamanIbaz interface. */
  g_type_interface_add_prerequisite (type, MAMAN_TYPE_IBAZ);

The code shown above adds the MamanIbaz interface to the list of prerequisites of MamanIbar while the code below shows how an implementation can implement both interfaces and register their implementations:

static void ibar_do_another_action (MamanBar *self)
{
  g_print ("Bar implementation of IBar interface Another Action: 0x%x.\n", self->instance_member);
}

static void
ibar_interface_init (gpointer   g_iface,
                     gpointer   iface_data)
{
  MamanIbarInterface *iface = (MamanIbarInterface *)g_iface;
  iface->do_another_action = (void (*) (MamanIbar *self))ibar_do_another_action;
}

static void ibaz_do_action (MamanBar *self)
{
  g_print ("Bar implementation of IBaz interface Action: 0x%x.\n", self->instance_member);
}

static void
ibaz_interface_init (gpointer   g_iface,
                    gpointer   iface_data)
{
  MamanIbazInterface *iface = (MamanIbazInterface *)g_iface;
  iface->do_action = (void (*) (MamanIbaz *self))ibaz_do_action;
}

static void
bar_instance_init (GTypeInstance   *instance,
                   gpointer         g_class)
{
  MamanBar *self = (MamanBar *)instance;
  self->instance_member = 0x666;
}

GType
maman_bar_get_type (void)
{
  static GType type = 0;
  if (type == 0) {
    static const GTypeInfo info = {
      sizeof (MamanBarClass),
      NULL,   /* base_init */
      NULL,   /* base_finalize */
      NULL,   /* class_init */
      NULL,   /* class_finalize */
      NULL,   /* class_data */
      sizeof (MamanBar),
      0,      /* n_preallocs */
      bar_instance_init    /* instance_init */
    };
    static const GInterfaceInfo ibar_info = {
      (GInterfaceInitFunc) ibar_interface_init,   /* interface_init */
      NULL,                                       /* interface_finalize */
      NULL                                        /* interface_data */
    };
    static const GInterfaceInfo ibaz_info = {
      (GInterfaceInitFunc) ibaz_interface_init,   /* interface_init */
      NULL,                                       /* interface_finalize */
      NULL                                        /* interface_data */
    };
    type = g_type_register_static (G_TYPE_OBJECT,
                                   "MamanBarType",
                                   &info, 0);
    g_type_add_interface_static (type,
                                 MAMAN_TYPE_IBAZ,
                                 &ibaz_info);
    g_type_add_interface_static (type,
                                 MAMAN_TYPE_IBAR,
                                 &ibar_info);
  }
  return type;
}

It is very important to notice that the order in which interface implementations are added to the main object is not random: g_type_add_interface_static must be invoked first on the interfaces which have no prerequisites and then on the others.

Complete source code showing how to define the MamanIbar interface which requires MamanIbaz and how to implement the MamanIbar interface is located in sample/interface/maman-ibar.{h|c} and sample/interface/maman-bar.{h|c}.


How to provide more flexibility to users?

The previous implementation does the job but the signal facility of GObject can be used to provide even more flexibility to this file change notification mechanism. One of the key ideas is to make the process of writing data to the file part of the signal emission process to allow users to be notified either before or after the data is written to the file.

To integrate the process of writing the data to the file into the signal emission mechanism, we can register a default class closure for this signal which will be invoked during the signal emission, just like any other user-connected signal handler.

The first step to implement this idea is to change the signature of the signal: we need to pass around the buffer to write and its size. To do this, we use our own marshaller which will be generated through glib's genmarshall tool. We thus create a file named marshall.list which contains the following single line:

VOID:POINTER,UINT

and use the Makefile provided in sample/signal/Makefile to generate the file named maman-file-complex-marshall.c. This C file is finally included in maman-file-complex.c.

Once the marshaller is present, we register the signal and its marshaller in the class_init function of the object MamanFileComplex (full source for this object is included in sample/signal/maman-file-complex.{h|c}):

GClosure *default_closure;
GType param_types[2];

default_closure = g_cclosure_new (G_CALLBACK (default_write_signal_handler),
                                  (gpointer)0xdeadbeaf /* user_data */,
                                  NULL /* destroy_data */);

param_types[0] = G_TYPE_POINTER;
param_types[1] = G_TYPE_UINT;
klass->write_signal_id =
  g_signal_newv ("write",
                 G_TYPE_FROM_CLASS (g_class),
                 G_SIGNAL_RUN_LAST | G_SIGNAL_NO_RECURSE | G_SIGNAL_NO_HOOKS,
                 default_closure /* class closure */,
                 NULL /* accumulator */,
                 NULL /* accu_data */,
                 maman_file_complex_VOID__POINTER_UINT,
                 G_TYPE_NONE /* return_type */,
                 2     /* n_params */,
                 param_types /* param_types */);

The code shown above first creates the closure which contains the code to complete the file write. This closure is registered as the default class_closure of the newly created signal.

Of course, you need to implement completely the code for the default closure since I just provided a skeleton:

static void
default_write_signal_handler (GObject *obj, guint8 *buffer, guint size, gpointer user_data)
{
  g_assert (user_data == (gpointer)0xdeadbeaf);
  /* Here, we trigger the real file write. */
  g_print ("default signal handler: 0x%x %u\n", buffer, size);
}

Finally, the client code must invoke the maman_file_complex_write function which triggers the signal emission:

void maman_file_complex_write (MamanFileComplex *self, guint8 *buffer, guint size)
{
  /* trigger event */
  g_signal_emit (self,
                 MAMAN_FILE_COMPLEX_GET_CLASS (self)->write_signal_id,
                 0, /* details */
                 buffer, size);
}

The client code (as shown in sample/signal/test.c and below) can now connect signal handlers before and after the file write is completed: since the default signal handler which does the write itself runs during the RUN_LAST phase of the signal emission, it will run after all handlers connected with g_signal_connect and before all handlers connected with g_signal_connect_after. If you intent to write a GObject which emits signals, I would thus urge you to create all your signals with the G_SIGNAL_RUN_LAST such that your users have a maximum of flexibility as to when to get the event. Here, we combined it with G_SIGNAL_NO_RECURSE and G_SIGNAL_NO_HOOKS to ensure our users will not try to do really weird things with our GObject. I strongly advise you to do the same unless you really know why (in which case you really know the inner workings of GSignal by heart and you are not reading this).

static void complex_write_event_before (GObject *file, guint8 *buffer, guint size, gpointer user_data)
{
  g_assert (user_data == NULL);
  g_print ("Complex Write event before: 0x%x, %u\n", buffer, size);
}

static void complex_write_event_after (GObject *file, guint8 *buffer, guint size, gpointer user_data)
{
  g_assert (user_data == NULL);
  g_print ("Complex Write event after: 0x%x, %u\n", buffer, size);
}

static void test_file_complex (void)
{
  guint8 buffer[100];
  GObject *file;

  file = g_object_new (MAMAN_FILE_COMPLEX_TYPE, NULL);

  g_signal_connect (G_OBJECT (file), "write",
                    (GCallback)complex_write_event_before,
                    NULL);

  g_signal_connect_after (G_OBJECT (file), "write",
                          (GCallback)complex_write_event_after,
                          NULL);

  maman_file_complex_write (MAMAN_FILE_COMPLEX (file), buffer, 50);

  g_object_unref (G_OBJECT (file));
}

The code above generates the following output on my machine:

Complex Write event before: 0xbfffe280, 50
default signal handler: 0xbfffe280 50
Complex Write event after: 0xbfffe280, 50

How most people do the same thing with less code

For many historic reasons related to how the ancestor of GObject used to work in GTK+ 1.x versions, there is a much simpler [16] way to create a signal with a default handler than to create a closure by hand and to use the g_signal_newv.

For example, g_signal_new can be used to create a signal which uses a default handler which is stored in the class structure of the object. More specifically, the class structure contains a function pointer which is accessed during signal emission to invoke the default handler and the user is expected to provide to g_signal_new the offset from the start of the class structure to the function pointer. [17]

The following code shows the declaration of the MamanFileSimple class structure which contains the write function pointer.

struct _MamanFileSimpleClass {
  GObjectClass parent;

  guint write_signal_id;

  /* signal default handlers */
  void (*write) (MamanFileSimple *self, guint8 *buffer, guint size);
};

The write function pointer is initialied in the class_init function of the object to default_write_signal_handler:

static void
maman_file_simple_class_init (gpointer g_class,
                               gpointer g_class_data)
{
  GObjectClass *gobject_class = G_OBJECT_CLASS (g_class);
  MamanFileSimpleClass *klass = MAMAN_FILE_SIMPLE_CLASS (g_class);

  klass->write = default_write_signal_handler;

Finally, the signal is created with g_signal_new in the same class_init function:

klass->write_signal_id =
 g_signal_new ("write",
               G_TYPE_FROM_CLASS (g_class),
               G_SIGNAL_RUN_LAST | G_SIGNAL_NO_RECURSE | G_SIGNAL_NO_HOOKS,
               G_STRUCT_OFFSET (MamanFileSimpleClass, write),
               NULL /* accumulator */,
               NULL /* accu_data */,
               maman_file_complex_VOID__POINTER_UINT,
               G_TYPE_NONE /* return_type */,
               2     /* n_params */,
               G_TYPE_POINTER,
               G_TYPE_UINT);

Of note, here, is the 4th argument to the function: it is an integer calculated by the G_STRUCT_OFFSET macro which indicates the offset of the member write from the start of the MamanFileSimpleClass class structure. [18]

While the complete code for this type of default handler looks less clutered as shown in sample/signal/maman-file-simple.{h|c}, it contains numerous subtleties. The main subtle point which everyone must be aware of is that the signature of the default handler created that way does not have a user_data argument: default_write_signal_handler is different in sample/signal/maman-file-complex.c and in sample/signal/maman-file-simple.c.

If you have doubts about which method to use, I would advise you to use the second one which involves g_signal_new rather than g_signal_newv: it is better to write code which looks like the vast majority of other GTK+/Gobject code than to do it your own way. However, now, you know why.

[16] I personally think that this method is horribly mind-twisting: it adds a new indirection which unecessarily complicates the overall code path. However, because this method is widely used by all of GTK+ and GObject code, readers need to understand it. The reason why this is done that way in most of GTK+ is related to the fact that the ancestor of GObject did not provide any other way to create a signal with a default handler than this one. Some people have tried to justify that it is done that way because it is better, faster (I am extremly doubtfull about the faster bit. As a matter of fact, the better bit also mystifies me ;-). I have the feeling no one really knows and everyone does it because they copy/pasted code from code which did the same. It is probably better to leave this specific trivia to hacker legends domain...

[17] I would like to point out here that the reason why the default handler of a signal is named everywhere a class_closure is probably related to the fact that it used to be really a function pointer stored in the class structure.

[18] GSignal uses this offset to create a special wrapper closure which first retrieves the target function pointer before calling it.


How users can abuse signals (and why some think it is good)

Now that you know how to create signals to which the users can connect easily and at any point in the signal emission process thanks to g_signal_connect, g_signal_connect_after and G_SIGNAL_RUN_LAST, it is time to look into how your users can and will screw you. This is also interesting to know how you too, can screw other people. This will make you feel good and eleet.

The users can:

  • stop the emission of the signal at anytime

  • override the default handler of the signal if it is stored as a function pointer in the class structure (which is the prefered way to create a default signal handler, as discussed in the previous section).

In both cases, the original programmer should be as careful as possible to write code which is resistant to the fact that the default handler of the signal might not able to run. This is obviously not the case in the example used in the previous sections since the write to the file depends on whether or not the default handler runs (however, this might be your goal: to allow the user to prevent the file write if he wishes to).

If all you want to do is to stop the signal emission from one of the callbacks you connected yourself, you can call g_signal_stop_by_name. Its use is very simple which is why I won't detail it further.

If the signal's default handler is just a class function pointer, it is also possible to override it yourself from the class_init function of a type which derives from the parent. That way, when the signal is emitted, the parent class will use the function provided by the child as a signal default handler. Of course, it is also possible (and recommended) to chain up from the child to the parent's default signal handler to ensure the integrity of the parent object.

Overriding a class method and chaining up was demonstrated in the section called “Object methods” which is why I won't bother to show exactly how to do it here again.


The GObject base class

Object instanciation
Object memory management
Reference count
Weak References
Reference counts and cycles
Object properties
Accessing multiple properties at once

The two previous chapters discussed the details of Glib's Dynamic Type System and its signal control system. The GObject library also contains an implementation for a base fundamental type named GObject.

GObject is a fundamental classed instantiable type. It implements:

  • Memory management with reference counting

  • Construction/Destruction of instances

  • Generic per-object properties with set/get function pairs

  • Easy use of signals

All the GTK+ objects and all of the objects in Gnome libraries which use the GLib type system inherit from GObject which is why it is important to understand the details of how it works.

Object instanciation

The g_object_new family of functions can be used to instantiate any GType which inherits from the GObject base type. All these functions make sure the class and instance structures have been correctly initialized by glib's type system and then invoke at one point or another the constructor class method which is used to:

  • Allocate and clear memory through g_type_create_instance,

  • Initialize the object' instance with the construction properties.

Although one can expect all class and instance members (except the fields pointing to the parents) to be set to zero, some consider it good practice to explicitly set them.

Objects which inherit from GObject are allowed to override this constructor class method: they should however chain to their parent constructor method before doing so:

  GObject*   (*constructor)     (GType                  type,
                                 guint                  n_construct_properties,
                                 GObjectConstructParam *construct_properties);

The example below shows how MamanBar overrides the parent's constructor:

#define MAMAN_TYPE_BAR		  (maman_bar_get_type ())
#define MAMAN_BAR(obj)		  (G_TYPE_CHECK_INSTANCE_CAST ((obj), MAMAN_TYPE_BAR, MamanBar))
#define MAMAN_BAR_CLASS(klass)	  (G_TYPE_CHECK_CLASS_CAST ((klass), MAMAN_TYPE_BAR, MamanBarClass))
#define MAMAN_IS_BAR(obj)	  (G_TYPE_CHECK_INSTANCE_TYPE ((obj), MAMAN_TYPE_BAR))
#define MAMAN_IS_BAR_CLASS(klass) (G_TYPE_CHECK_CLASS_TYPE ((klass), MAMAN_TYPE_BAR))
#define MAMAN_BAR_GET_CLASS(obj)  (G_TYPE_INSTANCE_GET_CLASS ((obj), MAMAN_TYPE_BAR, MamanBarClass))

typedef struct _MamanBar MamanBar;
typedef struct _MamanBarClass MamanBarClass;

struct _MamanBar {
  GObject parent;
  /* instance members */
};

struct _MamanBarClass {
  GObjectClass parent;

  /* class members */
};

/* used by MAMAN_TYPE_BAR */
GType maman_bar_get_type (void);

static GObject *
maman_bar_constructor (GType                  type,
                       guint                  n_construct_properties,
                       GObjectConstructParam *construct_properties)
{
  GObject *obj;

  {
    /* Invoke parent constructor. */
    MamanBarClass *klass;
    GObjectClass *parent_class;
    klass = MAMAN_BAR_CLASS (g_type_class_peek (MAMAN_TYPE_BAR));
    parent_class = G_OBJECT_CLASS (g_type_class_peek_parent (klass));
    obj = parent_class->constructor (type,
                                     n_construct_properties,
                                     construct_properties);
  }

  /* do stuff. */

  return obj;
}

static void
maman_bar_instance_init (GTypeInstance   *instance,
                         gpointer         g_class)
{
  MamanBar *self = (MamanBar *)instance;
  /* do stuff */
}

static void
maman_bar_class_init (gpointer g_class,
                      gpointer g_class_data)
{
  GObjectClass *gobject_class = G_OBJECT_CLASS (g_class);
  MamanBarClass *klass = MAMAN_BAR_CLASS (g_class);

  gobject_class->constructor = maman_bar_constructor;
}

GType maman_bar_get_type (void)
{
  static GType type = 0;
  if (type == 0) {
    static const GTypeInfo info = {
      sizeof (MamanBarClass),
      NULL,   /* base_init */
      NULL,   /* base_finalize */
      maman_bar_class_init,   /* class_init */
      NULL,   /* class_finalize */
      NULL,   /* class_data */
      sizeof (MamanBar),
      0,      /* n_preallocs */
      maman_bar_instance_init    /* instance_init */
    };
    type = g_type_register_static (G_TYPE_OBJECT,
                                   "MamanBarType",
                                   &info, 0);
  }
  return type;
}

If the user instantiates an object MamanBar with:

MamanBar *bar = g_object_new (MAMAN_TYPE_BAR, NULL);

If this is the first instantiation of such an object, the maman_b_class_init function will be invoked after any maman_b_base_class_init function. This will make sure the class structure of this new object is correctly initialized. Here, maman_bar_class_init is expected to override the object's class methods and setup the class' own methods. In the example above, the constructor method is the only overridden method: it is set to maman_bar_constructor.

Once g_object_new has obtained a reference to an initialized class structure, it invokes its constructor method to create an instance of the new object. Since it has just been overridden by maman_bar_class_init to maman_bar_constructor, the latter is called and, because it was implemented correctly, it chains up to its parent's constructor. The problem here is how we can find the parent constructor. An approach (used in GTK+ source code) would be to save the original constructor in a static variable from maman_bar_class_init and then to re-use it from maman_bar_constructor. This is clearly possible and very simple but I was told it was not nice and the prefered way is to use the g_type_class_peek and g_type_class_peek_parent functions.

Finally, at one point or another, g_object_constructor is invoked by the last constructor in the chain. This function allocates the object's instance' buffer through g_type_create_instance which means that the instance_init function is invoked at this point if one was registered. After instance_init returns, the object is fully initialized and should be ready to answer any user-request. When g_type_create_instance returns, g_object_constructor sets the construction properties (ie: the properties which were given to g_object_new) and returns to the user's constructor which is then allowed to do useful instance initialization...

The process described above might seem a bit complicated (it is actually overly complicated in my opinion..) but it can be summarized easily by the table below which lists the functions invoked by g_object_new and their order of invocation.

The array below lists the functions invoked by g_object_new and their order of invocation:

Table 4. g_object_new

Invocation time | Function Invoked | Function's parameters | Remark
First call to g_object_new for target type | target type's base_init function | On the inheritance tree of classes from fundamental type to target type. base_init is invoked once for each class structure. | I have no real idea on how this can be used. If you have a good real-life example of how a class' base_init can be used, please, let me know.
First call to g_object_new for target type | target type's class_init function | On target type's class structure | Here, you should make sure to initialize or override class methods (that is, assign to each class' method its function pointer) and create the signals and the properties associated to your object.
First call to g_object_new for target type | interface' base_init function | On interface' vtable |
First call to g_object_new for target type | interface' interface_init function | On interface' vtable |
Each call to g_object_new for target type | target type's class constructor method: GObjectClass->constructor | On object's instance | If you need to complete the object initialization after all the construction properties are set, override the constructor method and make sure to chain up to the object's parent class before doing your own initialization. In doubt, do not override the constructor method.
Each call to g_object_new for target type | type's instance_init function | On the inheritance tree of classes from fundamental type to target type. the instance_init provided for each type is invoked once for each instance structure. | Provide an instance_init function to initialize your object before its construction properties are set. This is the preferred way to initialize a GObject instance. This function is equivalent to C++ constructors.

Readers should feel concerned about one little twist in the order in which functions are invoked: while, technically, the class' constructor method is called before the GType's instance_init function (since g_type_create_instance which calls instance_init is called by g_object_constructor which is the top-level class constructor method and to which users are expected to chain to), the user's code which runs in a user-provided constructor will always run after GType's instance_init function since the user-provided constructor must (you've been warned) chain up before doing anything useful.


The GObject messaging system

Closures
C Closures
non-C closures (for the fearless).
Signals
Signal registration
Signal connection
Signal emission
The detail argument

Closures

Closures are central to the concept of asynchronous signal delivery which is widely used throughout GTK+ and Gnome applications. A Closure is an abstraction, a generic representation of a callback. It is a small structure which contains three objects:

  • a function pointer (the callback itself) whose prototype looks like:

    return_type function_callback (... , gpointer user_data);

  • the user_data pointer which is passed to the callback upon invocation of the closure

  • a function pointer which represents the destructor of the closure: whenever the closure's refcount reaches zero, this function will be called before the closure structure is freed.

The GClosure structure represents the common functionality of all closure implementations: there exists a different Closure implementation for each separate runtime which wants to use the GObject type system. [7] The GObject library provides a simple GCClosure type which is a specific implementation of closures to be used with C/C++ callbacks.

A GClosure provides simple services:

  • Invocation (g_closure_invoke): this is what closures were created for: they hide the details of callback invocation from the callback invocator.

  • Notification: the closure notifies listeners of certain events such as closure invocation, closure invalidation and closure finalization. Listeners can be registered with g_closure_add_finalize_notifier (finalization notification), g_closure_add_invalidate_notifier (invalidation notification) and g_closure_add_marshal_guards (invocation notification). There exist symmetric de-registration functions for finalization and invalidation events (g_closure_remove_finalize_notifier and g_closure_remove_invalidate_notifier) but not for the invocation process. [8]

C Closures

If you are using C or C++ to connect a callback to a given event, you will either use the simple GCClosures which have a pretty minimal API or the even simpler g_signal_connect functions (which will be presented a bit later :).

GClosure* g_cclosure_new (GCallback        callback_func,
                          gpointer         user_data,
                          GClosureNotify   destroy_data);
GClosure* g_cclosure_new_swap (GCallback        callback_func,
                               gpointer         user_data,
                               GClosureNotify   destroy_data);
GClosure* g_signal_type_cclosure_new (GType  itype,
                                      guint  struct_offset);

g_cclosure_new will create a new closure which can invoke the user-provided callback_func with the user-provided user_data as last parameter. When the closure is finalized (second stage of the destruction process), it will invoke the destroy_data function if the user has supplied one.

g_cclosure_new_swap will create a new closure which can invoke the user-provided callback_func with the user-provided user_data as first parameter (instead of being the last parameter as with g_cclosure_new). When the closure is finalized (second stage of the destruction process), it will invoke the destroy_data function if the user has supplied one.

non-C closures (for the fearless).

As was explained above, Closures hide the details of callback invocation. In C, callback invocation is just like function invocation: it is a matter of creating the correct stack frame for the called function and executing a call assembly instruction.

C closure marshallers transform the array of GValues which represent the parameters to the target function into a C-style function parameter list, invoke the user-supplied C function with this new parameter list, get the return value of the function, transform it into a GValue and return this GValue to the marshaller caller.

The following code implements a simple marshaller in C for a C function which takes an integer as first parameter and returns void.

g_cclosure_marshal_VOID__INT (GClosure     *closure,
                              GValue       *return_value,
                              guint         n_param_values,
                              const GValue *param_values,
                              gpointer      invocation_hint,
                              gpointer      marshal_data)
{
  typedef void (*GMarshalFunc_VOID__INT) (gpointer     data1,
                                          gint         arg_1,
                                          gpointer     data2);
  register GMarshalFunc_VOID__INT callback;
  register GCClosure *cc = (GCClosure*) closure;
  register gpointer data1, data2;

  g_return_if_fail (n_param_values == 2);

  data1 = g_value_peek_pointer (param_values + 0);
  data2 = closure->data;

  callback = (GMarshalFunc_VOID__INT) (marshal_data ? marshal_data : cc->callback);

  callback (data1,
            g_marshal_value_peek_int (param_values + 1),
            data2);
}

Of course, there exist other kinds of marshallers. For example, James Henstridge wrote a generic Python marshaller which is used by all python Closures (a python closure is used to have python-based callback be invoked by the closure invocation process). This python marshaller transforms the input GValue list representing the function parameters into a Python tupple which is the equivalent structure in python (you can look in pyg_closure_marshal in pygtype.c in the pygtk module in Gnome cvs server).

[7] In Practice, Closures sit at the boundary of language runtimes: if you are writing python code and one of your Python callback receives a signal from one of GTK+ widgets, the C code in GTK+ needs to execute your Python code. The Closure invoked by the GTK+ object invokes the Python callback: it behaves as a normal C object for GTK+ and as a normal Python object for python code.

[8] Closures are refcounted and notify listeners of their destruction in a two-stage process: the invalidation notifiers are invoked before the finalization notifiers.


glib-genmarshal

glib-genmarshal — C code marshaller generation utility for GLib closures

Synopsis

glib-genmarshal [options...] [files...]

Description

glib-genmarshal is a small utility that generates C code marshallers for callback functions of the GClosure mechanism in the GObject sublibrary of GLib. The marshaller functions have a standard signature, they get passed in the invoking closure, an array of value structures holding the callback function parameters and a value structure for the return value of the callback. The marshaller is then responsible to call the respective C code function of the closure with all the parameters on the stack and to collect its return value.

Invocation

glib-genmarshal takes a list of marshallers to generate as input. The marshaller list is either read from standard input or from files passed as additional arguments on the command line.

Options

--header | Generate header file contents of the marshallers.
--body | Generate C code file contents of the marshallers.
--prefix=string, --prefix string | Specify marshaller prefix. The default prefix is `g_cclosure_marshal'.
--skip-source | Skip source location remarks in generated comments.
--nostdinc | Do not use the standard marshallers of the GObject library, and skip gmarshal.h include directive in generated header files.
--g-fatal-warnings | Make warnings fatal, that is, exit immediately once a warning occurs.
-h, --help | Print brief help and exit.
-v, --version | Print version and exit.

Marshaller list format

The marshaller lists are processed line by line, a line can contain a comment in the form of

# this is a comment

or a marshaller specification of the form

RTYPE:PTYPE
RTYPE:PTYPE,PTYPE
RTYPE:PTYPE,PTYPE,PTYPE

(up to 16 PTYPEs may be present).

The RTYPE part specifies the callback's return type and the PTYPEs right to the colon specify the callback's parameter list, except for the first and the last arguments which are always pointers.

Parameter types

Currently, the following types are supported:

VOID | indicates no return type, or no extra parameters. If VOID is used as the parameter list, no additional parameters may be present.
BOOLEAN | for boolean types (gboolean)
CHAR | for signed char types (gchar)
UCHAR | for unsigned char types (guchar)
INT | for signed integer types (gint)
UINT | for unsigned integer types (guint)
LONG | for signed long integer types (glong)
ULONG | for unsigned long integer types (gulong)
INT64 | for signed 64bit integer types (gint64)
UINT64 | for unsigned 64bit integer types (guint64)
ENUM | for enumeration types (gint)
FLAGS | for flag enumeration types (guint)
FLOAT | for single-precision float types (gfloat)
DOUBLE | for double-precision float types (gdouble)
STRING | for string types (gchar*)
BOXED | for boxed (anonymous but reference counted) types (GBoxed*)
PARAM | for GParamSpec or derived types (GParamSpec*)
POINTER | for anonymous pointer types (gpointer)
OBJECT | for GObject or derived types (GObject*)
NONE | deprecated alias for VOID
BOOL | deprecated alias for BOOLEAN

Example

To generate marshallers for the following callback functions:

void   foo (gpointer data1,
            gpointer data2);
void   bar (gpointer data1,
            gint     param1,
            gpointer data2);
gfloat baz (gpointer data1,
            gboolean param1,
            guchar   param2,
            gpointer data2);

The marshaller list has to look like this:

VOID:VOID
VOID:INT
FLOAT:BOOLEAN,UCHAR

The generated marshallers have the arguments encoded in their function name. For this particular list, they are

g_cclosure_marshal_VOID__VOID(),
g_cclosure_marshal_VOID__INT(),
g_cclosure_marshal_FLOAT__BOOLEAN_UCHAR().

They can be used directly for GClosures or be passed in as the GSignalCMarshaller c_marshaller; argument upon creation of signals:

GClosure *cc_foo, *cc_bar, *cc_baz;

cc_foo = g_cclosure_new (NULL, foo, NULL);
g_closure_set_marshal (cc_foo, g_cclosure_marshal_VOID__VOID);
cc_bar = g_cclosure_new (NULL, bar, NULL);
g_closure_set_marshal (cc_bar, g_cclosure_marshal_VOID__INT);
cc_baz = g_cclosure_new (NULL, baz, NULL);
g_closure_set_marshal (cc_baz, g_cclosure_marshal_FLOAT__BOOLEAN_UCHAR);

See also

glib-mkenums(1)

Bugs

None known yet.

Author

glib-genmarshal has been written by Tim Janik <timj@gtk.org>.

This manual page was provided by Tim Janik <timj@gtk.org>.


glib-mkenums

glib-mkenums — C language enum description generation utility

Synopsis

glib-mkenums [options...] [files...]

Description

glib-mkenums is a small perl-script utility that parses C code to extract enum definitions and produces enum descriptions based on text templates specified by the user. Most frequently this script is used to produce C code that contains enum values as strings so programs can provide value name strings for introspection.

Invocation

glib-mkenums takes a list of valid C code files as input. The options specified control the text that is output, certain substitutions are performed on the text templates for keywords enclosed in @ characters.

Options

--fhead text

Put out text prior to processing input files.

--fprod text

Put out text everytime a new input file is being processed.

--ftail text

Put out text after all input files have been processed.

--eprod text

Put out text everytime an enum is encountered in the input files.

--vhead text

Put out text before iterating over the set of values of an enum.

--vprod text

Put out text for every value of an enum.

--vtail text

Put out text after iterating over all values of an enum.

--comments text

Template for auto-generated comments, the default (for C code generations) is "/* @comment@ */".

--template file

Read templates from the given file. The templates are enclosed in specially-formatted C comments

/*** BEGIN section ***/
/*** END section ***/

where section may be file-header, file-production, file-tail, enumeration-production, value-header, value-production, value-tail or comment.

--help

Print brief help and exit.

--version

Print version and exit.

Production text substitutions

Certain keywords enclosed in @ characters will be substituted in the emitted text. For the substitution examples of the keywords below, the following example enum definition is assumed:

typedef enum
{
  PREFIX_THE_XVALUE    = 1 << 3,
  PREFIX_ANOTHER_VALUE = 1 << 4
} PrefixTheXEnum;

@EnumName@ | The name of the enum currently being processed, enum names are assumed to be properly namespaced and to use mixed capitalization to separate words (e.g. PrefixTheXEnum).
@enum_name@ | The enum name with words lowercase and word-separated by underscores (e.g. prefix_the_xenum).
@ENUMNAME@ | The enum name with words uppercase and word-separated by underscores (e.g. PREFIX_THE_XENUM).
@ENUMSHORT@ | The enum name with words uppercase and word-separated by underscores, prefix stripped (e.g. THE_XENUM).
@VALUENAME@ | The enum value name currently being processed with words uppercase and word-separated by underscores, this is the assumed literal notation of enum values in the C sources (e.g. PREFIX_THE_XVALUE).
@valuenick@ | A nick name for the enum value currently being processed, this is usually generated by stripping common prefix words of all the enum values of the current enum, the words are lowercase and underscores are substituted by a minus (e.g. the-xvalue).
@type@ | This is substituted either by "enum" or "flags", depending on whether the enum value definitions contained bit-shift operators or not (e.g. flags).
@Type@ | The same as @type@ with the first letter capitalized (e.g. Flags).
@TYPE@ | The same as @type@ with all letters uppercased (e.g. FLAGS).
@filename@ | The name of the input file currently being processed (e.g. foo.h).

Trigraph extensions

Some C comments are treated specially in the parsed enum definitions, such comments start out with the trigraph sequence /*< and end with the trigraph sequence >*/. Per enum definition, the options "skip" and "flags" can be specified, to indicate this enum definition to be skipped, or for it to be treated as a flags definition, or to specify the common prefix to be stripped from all values to generate value nicknames, respectively. The "lowercase_name" option can be used to specify the word separation used in the *_get_type() function. For instance, /*< lowercase_name=gnome_vfs_uri_hide_options >*/.

Per value definition, the options "skip" and "nick" are supported. The former causes the value to be skipped, and the latter can be used to specify the otherwise auto-generated nickname. Examples:

typedef enum /*< skip >*/
{
  PREFIX_FOO
} PrefixThisEnumWillBeSkipped;
typedef enum /*< flags,prefix=PREFIX >*/
{
  PREFIX_THE_ZEROTH_VALUE,	/*< skip >*/
  PREFIX_THE_FIRST_VALUE,
  PREFIX_THE_SECOND_VALUE,
  PREFIX_THE_THIRD_VALUE,	/*< nick=the-last-value >*/
} PrefixTheFlagsEnum;

See also

glib-genmarshal(1)


GBoxed

GBoxed — A mechanism to wrap opaque C structures registered by the type system

Synopsis

#include <glib-object.h>

gpointer            (*GBoxedCopyFunc)                   (gpointer boxed);
void                (*GBoxedFreeFunc)                   (gpointer boxed);
gpointer            g_boxed_copy                        (GType boxed_type,
                                                         gconstpointer src_boxed);
void                g_boxed_free                        (GType boxed_type,
                                                         gpointer boxed);
GType               g_boxed_type_register_static        (const gchar *name,
                                                         GBoxedCopyFunc boxed_copy,
                                                         GBoxedFreeFunc boxed_free);
GType               g_pointer_type_register_static      (const gchar *name);

#define             G_TYPE_HASH_TABLE
#define             G_TYPE_DATE
#define             G_TYPE_GSTRING
#define             G_TYPE_STRV
typedef             GStrv;

Description

GBoxed is a generic wrapper mechanism for arbitrary C structures. The only thing the type system needs to know about the structures is how to copy and free them, beyond that they are treated as opaque chunks of memory.

Boxed types are useful for simple value-holder structures like rectangles or points. They can also be used for wrapping structures defined in non-GObject based libraries.

Details

GBoxedCopyFunc ()

gpointer            (*GBoxedCopyFunc)                   (gpointer boxed);

This function is provided by the user and should produce a copy of the passed in boxed structure.

boxed : | The boxed structure to be copied.
Returns : | The newly created copy of the boxed structure.

GBoxedFreeFunc ()

void                (*GBoxedFreeFunc)                   (gpointer boxed);

This function is provided by the user and should free the boxed structure passed.

boxed : The boxed structure to be freed.

g_boxed_copy ()

gpointer            g_boxed_copy                        (GType boxed_type,
                                                         gconstpointer src_boxed);

Provide a copy of a boxed structure src_boxed which is of type boxed_type.

boxed_type : | The type of src_boxed.
src_boxed : | The boxed structure to be copied.
Returns : | The newly created copy of the boxed structure.

g_boxed_free ()

void                g_boxed_free                        (GType boxed_type,
                                                         gpointer boxed);

Free the boxed structure boxed which is of type boxed_type.

boxed_type : | The type of boxed.
boxed : | The boxed structure to be freed.

g_boxed_type_register_static ()

GType               g_boxed_type_register_static        (const gchar *name,
                                                         GBoxedCopyFunc boxed_copy,
                                                         GBoxedFreeFunc boxed_free);

This function creates a new G_TYPE_BOXED derived type id for a new boxed type with name name. Boxed type handling functions have to be provided to copy and free opaque boxed structures of this type.

name : | Name of the new boxed type.
boxed_copy : | Boxed structure copy function.
boxed_free : | Boxed structure free function.
Returns : | New G_TYPE_BOXED derived type id for name.

g_pointer_type_register_static ()

GType               g_pointer_type_register_static      (const gchar *name);

Creates a new G_TYPE_POINTER derived type id for a new pointer type with name name.

name : | the name of the new pointer type.
Returns : | a new G_TYPE_POINTER derived type id for name.

G_TYPE_HASH_TABLE

#define	G_TYPE_HASH_TABLE	(g_hash_table_get_type ())

The GType for a boxed type holding a GHashTable reference.

Since 2.10

G_TYPE_DATE

#define	G_TYPE_DATE	        (g_date_get_type ())

The GType for GDate.

G_TYPE_GSTRING

#define	G_TYPE_GSTRING		(g_gstring_get_type ())

The GType for GString.

G_TYPE_STRV

#define	G_TYPE_STRV	        (g_strv_get_type ())

The GType for a boxed type holding a NULL-terminated array of strings.

The code fragments in the following example show the use of a property of type G_TYPE_STRV with g_object_class_install_property(), g_object_set() and g_object_get().

g_object_class_install_property (object_class,
                                 PROP_AUTHORS,
                                 g_param_spec_boxed ("authors",
                                                     _("Authors"),
                                                     _("List of authors"),
                                                     G_TYPE_STRV,
                                                     G_PARAM_READWRITE));

gchar *authors[] = { "Owen", "Tim", NULL };
g_object_set (obj, "authors", authors, NULL);

gchar *writers[];
g_object_get (obj, "authors", &writers, NULL);
/* do something with writers */
g_strfreev (writers);

Since 2.4

GStrv

typedef gchar** GStrv;

A C representable type name for G_TYPE_STRV.

See Also

GParamSpecBoxed, g_param_spec_boxed()


Closures

Closures — Functions as first-class objects

Synopsis

#include <glib-object.h>

#define             G_CLOSURE_NEEDS_MARSHAL             (closure)
#define             G_CLOSURE_N_NOTIFIERS               (cl)
#define             G_CCLOSURE_SWAP_DATA                (cclosure)
#define             G_CALLBACK                          (f)
void                (*GCallback)                        (void);
                    GClosure;
#define             G_TYPE_CLOSURE
                    GCClosure;
void                (*GClosureMarshal)                  (GClosure *closure,
                                                         GValue *return_value,
                                                         guint n_param_values,
                                                         const GValue *param_values,
                                                         gpointer invocation_hint,
                                                         gpointer marshal_data);
void                (*GClosureNotify)                   (gpointer data,
                                                         GClosure *closure);
GClosure*           g_cclosure_new                      (GCallback callback_func,
                                                         gpointer user_data,
                                                         GClosureNotify destroy_data);
GClosure*           g_cclosure_new_swap                 (GCallback callback_func,
                                                         gpointer user_data,
                                                         GClosureNotify destroy_data);
GClosure*           g_cclosure_new_object               (GCallback callback_func,
                                                         GObject *object);
GClosure*           g_cclosure_new_object_swap          (GCallback callback_func,
                                                         GObject *object);
GClosure*           g_closure_new_object                (guint sizeof_closure,
                                                         GObject *object);
GClosure*           g_closure_ref                       (GClosure *closure);
void                g_closure_sink                      (GClosure *closure);
void                g_closure_unref                     (GClosure *closure);
void                g_closure_invoke                    (GClosure *closure,
                                                         GValue *return_value,
                                                         guint n_param_values,
                                                         const GValue *param_values,
                                                         gpointer invocation_hint);
void                g_closure_invalidate                (GClosure *closure);
void                g_closure_add_finalize_notifier     (GClosure *closure,
                                                         gpointer notify_data,
                                                         GClosureNotify notify_func);
void                g_closure_add_invalidate_notifier   (GClosure *closure,
                                                         gpointer notify_data,
                                                         GClosureNotify notify_func);
void                g_closure_remove_finalize_notifier  (GClosure *closure,
                                                         gpointer notify_data,
                                                         GClosureNotify notify_func);
void                g_closure_remove_invalidate_notifier
                                                        (GClosure *closure,
                                                         gpointer notify_data,
                                                         GClosureNotify notify_func);
GClosure*           g_closure_new_simple                (guint sizeof_closure,
                                                         gpointer data);
void                g_closure_set_marshal               (GClosure *closure,
                                                         GClosureMarshal marshal);
void                g_closure_add_marshal_guards        (GClosure *closure,
                                                         gpointer pre_marshal_data,
                                                         GClosureNotify pre_marshal_notify,
                                                         gpointer post_marshal_data,
                                                         GClosureNotify post_marshal_notify);
void                g_closure_set_meta_marshal          (GClosure *closure,
                                                         gpointer marshal_data,
                                                         GClosureMarshal meta_marshal);
void                g_source_set_closure                (GSource *source,
                                                         GClosure *closure);
#define             G_TYPE_IO_CHANNEL
#define             G_TYPE_IO_CONDITION

void                g_cclosure_marshal_VOID__VOID       (GClosure *closure,
                                                         GValue *return_value,
                                                         guint n_param_values,
                                                         const GValue *param_values,
                                                         gpointer invocation_hint,
                                                         gpointer marshal_data);
void                g_cclosure_marshal_VOID__BOOLEAN    (GClosure *closure,
                                                         GValue *return_value,
                                                         guint n_param_values,
                                                         const GValue *param_values,
                                                         gpointer invocation_hint,
                                                         gpointer marshal_data);
void                g_cclosure_marshal_VOID__CHAR       (GClosure *closure,
                                                         GValue *return_value,
                                                         guint n_param_values,
                                                         const GValue *param_values,
                                                         gpointer invocation_hint,
                                                         gpointer marshal_data);
void                g_cclosure_marshal_VOID__UCHAR      (GClosure *closure,
                                                         GValue *return_value,
                                                         guint n_param_values,
                                                         const GValue *param_values,
                                                         gpointer invocation_hint,
                                                         gpointer marshal_data);
void                g_cclosure_marshal_VOID__INT        (GClosure *closure,
                                                         GValue *return_value,
                                                         guint n_param_values,
                                                         const GValue *param_values,
                                                         gpointer invocation_hint,
                                                         gpointer marshal_data);
void                g_cclosure_marshal_VOID__UINT       (GClosure *closure,
                                                         GValue *return_value,
                                                         guint n_param_values,
                                                         const GValue *param_values,
                                                         gpointer invocation_hint,
                                                         gpointer marshal_data);
void                g_cclosure_marshal_VOID__LONG       (GClosure *closure,
                                                         GValue *return_value,
                                                         guint n_param_values,
                                                         const GValue *param_values,
                                                         gpointer invocation_hint,
                                                         gpointer marshal_data);
void                g_cclosure_marshal_VOID__ULONG      (GClosure *closure,
                                                         GValue *return_value,
                                                         guint n_param_values,
                                                         const GValue *param_values,
                                                         gpointer invocation_hint,
                                                         gpointer marshal_data);
void                g_cclosure_marshal_VOID__ENUM       (GClosure *closure,
                                                         GValue *return_value,
                                                         guint n_param_values,
                                                         const GValue *param_values,
                                                         gpointer invocation_hint,
                                                         gpointer marshal_data);
void                g_cclosure_marshal_VOID__FLAGS      (GClosure *closure,
                                                         GValue *return_value,
                                                         guint n_param_values,
                                                         const GValue *param_values,
                                                         gpointer invocation_hint,
                                                         gpointer marshal_data);
void                g_cclosure_marshal_VOID__FLOAT      (GClosure *closure,
                                                         GValue *return_value,
                                                         guint n_param_values,
                                                         const GValue *param_values,
                                                         gpointer invocation_hint,
                                                         gpointer marshal_data);
void                g_cclosure_marshal_VOID__DOUBLE     (GClosure *closure,
                                                         GValue *return_value,
                                                         guint n_param_values,
                                                         const GValue *param_values,
                                                         gpointer invocation_hint,
                                                         gpointer marshal_data);
void                g_cclosure_marshal_VOID__STRING     (GClosure *closure,
                                                         GValue *return_value,
                                                         guint n_param_values,
                                                         const GValue *param_values,
                                                         gpointer invocation_hint,
                                                         gpointer marshal_data);
void                g_cclosure_marshal_VOID__PARAM      (GClosure *closure,
                                                         GValue *return_value,
                                                         guint n_param_values,
                                                         const GValue *param_values,
                                                         gpointer invocation_hint,
                                                         gpointer marshal_data);
void                g_cclosure_marshal_VOID__BOXED      (GClosure *closure,
                                                         GValue *return_value,
                                                         guint n_param_values,
                                                         const GValue *param_values,
                                                         gpointer invocation_hint,
                                                         gpointer marshal_data);
void                g_cclosure_marshal_VOID__POINTER    (GClosure *closure,
                                                         GValue *return_value,
                                                         guint n_param_values,
                                                         const GValue *param_values,
                                                         gpointer invocation_hint,
                                                         gpointer marshal_data);
void                g_cclosure_marshal_VOID__OBJECT     (GClosure *closure,
                                                         GValue *return_value,
                                                         guint n_param_values,
                                                         const GValue *param_values,
                                                         gpointer invocation_hint,
                                                         gpointer marshal_data);
void                g_cclosure_marshal_STRING__OBJECT_POINTER
                                                        (GClosure *closure,
                                                         GValue *return_value,
                                                         guint n_param_values,
                                                         const GValue *param_values,
                                                         gpointer invocation_hint,
                                                         gpointer marshal_data);
void                g_cclosure_marshal_VOID__UINT_POINTER
                                                        (GClosure *closure,
                                                         GValue *return_value,
                                                         guint n_param_values,
                                                         const GValue *param_values,
                                                         gpointer invocation_hint,
                                                         gpointer marshal_data);
void                g_cclosure_marshal_BOOLEAN__FLAGS   (GClosure *closure,
                                                         GValue *return_value,
                                                         guint n_param_values,
                                                         const GValue *param_values,
                                                         gpointer invocation_hint,
                                                         gpointer marshal_data);
#define             g_cclosure_marshal_BOOL__FLAGS

Description

A GClosure represents a callback supplied by the programmer. It will generally comprise a function of some kind and a marshaller used to call it. It is the reponsibility of the marshaller to convert the arguments for the invocation from GValues into a suitable form, perform the callback on the converted arguments, and transform the return value back into a GValue.

In the case of C programs, a closure usually just holds a pointer to a function and maybe a data argument, and the marshaller converts between GValue and native C types. The GObject library provides the GCClosure type for this purpose. Bindings for other languages need marshallers which convert between GValues and suitable representations in the runtime of the language in order to use functions written in that languages as callbacks.

Within GObject, closures play an important role in the implementation of signals. When a signal is registered, the c_marshaller argument to g_signal_new() specifies the default C marshaller for any closure which is connected to this signal. GObject provides a number of C marshallers for this purpose, see the g_cclosure_marshal_*() functions. Additional C marshallers can be generated with the glib-genmarshal utility. Closures can be explicitly connected to signals with g_signal_connect_closure(), but it usually more convenient to let GObject create a closure automatically by using one of the g_signal_connect_*() functions which take a callback function/user data pair.

Using closures has a number of important advantages over a simple callback function/data pointer combination:

  • Closures allow the callee to get the types of the callback parameters, which means that language bindings don't have to write individual glue for each callback type.

  • The reference counting of GClosure makes it easy to handle reentrancy right; if a callback is removed while it is being invoked, the closure and it's parameters won't be freed until the invocation finishes.

  • g_closure_invalidate() and invalidation notifiers allow callbacks to be automatically removed when the objects they point to go away.

Details

G_CLOSURE_NEEDS_MARSHAL()

#define	G_CLOSURE_NEEDS_MARSHAL(closure) (((GClosure*) (closure))->marshal == NULL)

Returns TRUE if a GClosureMarshal marshaller has not yet been set on closure. See g_closure_set_marshal().

closure : a GClosure

G_CLOSURE_N_NOTIFIERS()

#define             G_CLOSURE_N_NOTIFIERS(cl)

Returns the total number of notifiers connected with the closure cl. The count includes the meta marshaller, the finalize and invalidate notifiers and the marshal guards. Note that each guard counts as two notifiers. See g_closure_set_meta_marshal(), g_closure_add_finalize_notifier(), g_closure_add_invalidate_notifier() and g_closure_add_marshal_guards().

cl : a GClosure

G_CCLOSURE_SWAP_DATA()

#define	G_CCLOSURE_SWAP_DATA(cclosure)	 (((GClosure*) (closure))->derivative_flag)

Returns whether the user data of the GCClosure should be passed as the first parameter to the callback. See g_cclosure_new_swap().

cclosure : a GCClosure

G_CALLBACK()

#define	G_CALLBACK(f)			 ((GCallback) (f))

Cast a function pointer to a GCallback.

f : a function pointer.

GCallback ()

void                (*GCallback)                        (void);

The type used for callback functions in structure definitions and function signatures. This doesn't mean that all callback functions must take no parameters and return void. The required signature of a callback function is determined by the context in which is used (e.g. the signal to which it is connected). Use G_CALLBACK() to cast the callback function to a GCallback.

GClosure

typedef struct {
  volatile       	guint	 in_marshal : 1;
  volatile       	guint	 is_invalid : 1;
} GClosure;

A GClosure represents a callback supplied by the programmer.

volatile guint in_marshal : 1; | Indicates whether the closure is currently being invoked with g_closure_invoke()
volatile guint is_invalid : 1; | Indicates whether the closure has been invalidated by g_closure_invalidate()

G_TYPE_CLOSURE

#define	G_TYPE_CLOSURE		(g_closure_get_type ())

The GType for GClosure.

GCClosure

typedef struct {
  GClosure	closure;
  gpointer	callback;
} GCClosure;

A GCClosure is a specialization of GClosure for C function callbacks.

GClosure closure; | the GClosure
gpointer callback; | the callback function

GClosureMarshal ()

void                (*GClosureMarshal)                  (GClosure *closure,
                                                         GValue *return_value,
                                                         guint n_param_values,
                                                         const GValue *param_values,
                                                         gpointer invocation_hint,
                                                         gpointer marshal_data);

The type used for marshaller functions.

closure : | the GClosure to which the marshaller belongs
return_value : | a GValue to store the return value. May be NULL if the callback of closure doesn't return a value.
n_param_values : | the length of the param_values array
param_values : | an array of GValues holding the arguments on which to invoke the callback of closure
invocation_hint : | the invocation hint given as the the last argument to g_closure_invoke()
marshal_data : | additional data specified when registering the marshaller, see g_closure_set_marshal() and g_closure_set_meta_marshal()

GClosureNotify ()

void                (*GClosureNotify)                   (gpointer data,
                                                         GClosure *closure);

The type used for the various notification callbacks which can be registered on closures.

data : | data specified when registering the notification callback
closure : | the GClosure on which the notification is emitted

g_cclosure_new ()

GClosure*           g_cclosure_new                      (GCallback callback_func,
                                                         gpointer user_data,
                                                         GClosureNotify destroy_data);

Creates a new closure which invokes callback_func with user_data as the last parameter.

callback_func : | the function to invoke
user_data : | user data to pass to callback_func
destroy_data : | destroy notify to be called when user_data is no longer used
Returns : | a new GCClosure

g_cclosure_new_swap ()

GClosure*           g_cclosure_new_swap                 (GCallback callback_func,
                                                         gpointer user_data,
                                                         GClosureNotify destroy_data);

Creates a new closure which invokes callback_func with user_data as the first parameter.

callback_func : | the function to invoke
user_data : | user data to pass to callback_func
destroy_data : | destroy notify to be called when user_data is no longer used
Returns : | a new GCClosure

g_cclosure_new_object ()

GClosure*           g_cclosure_new_object               (GCallback callback_func,
                                                         GObject *object);

A variant of g_cclosure_new() which uses object as user_data and calls g_object_watch_closure() on object and the created closure. This function is useful when you have a callback closely associated with a GObject, and want the callback to no longer run after the object is is freed.

callback_func : | the function to invoke
object : | a GObject pointer to pass to callback_func
Returns : | a new GCClosure

g_cclosure_new_object_swap ()

GClosure*           g_cclosure_new_object_swap          (GCallback callback_func,
                                                         GObject *object);

A variant of g_cclosure_new_swap() which uses object as user_data and calls g_object_watch_closure() on object and the created closure. This function is useful when you have a callback closely associated with a GObject, and want the callback to no longer run after the object is is freed.

callback_func : | the function to invoke
object : | a GObject pointer to pass to callback_func
Returns : | a new GCClosure

g_closure_new_object ()

GClosure*           g_closure_new_object                (guint sizeof_closure,
                                                         GObject *object);

A variant of g_closure_new_simple() which stores object in the data field of the closure and calls g_object_watch_closure() on object and the created closure. This function is mainly useful when implementing new types of closures.

sizeof_closure : | the size of the structure to allocate, must be at least sizeof (GClosure)
object : | a GObject pointer to store in the data field of the newly allocated GClosure
Returns : | a newly allocated GClosure

g_closure_ref ()

GClosure*           g_closure_ref                       (GClosure *closure);

Increments the reference count on a closure to force it staying alive while the caller holds a pointer to it.

closure : | GClosure to increment the reference count on
Returns : | The closure passed in, for convenience

g_closure_sink ()

void                g_closure_sink                      (GClosure *closure);

Takes over the initial ownership of a closure. Each closure is initially created in afloating state, which means that the initial reference count is not owned by any caller. g_closure_sink() checks to see if the object is still floating, and if so, unsets the floating state and decreases the reference count. If the closure is not floating, g_closure_sink() does nothing. The reason for the existance of the floating state is to prevent cumbersome code sequences like:

closure = g_cclosure_new (cb_func, cb_data);
g_source_set_closure (source, closure);
g_closure_unref (closure); /* XXX GObject doesn't really need this */

Because g_source_set_closure() (and similar functions) take ownership of the initial reference count, if it is unowned, we instead can write:

g_source_set_closure (source, g_cclosure_new (cb_func, cb_data));

Generally, this function is used together with g_closure_ref(). Ane example of storing a closure for later notification looks like:

static GClosure *notify_closure = NULL;
void
foo_notify_set_closure (GClosure *closure)
{
  if (notify_closure)
    g_closure_unref (notify_closure);
  notify_closure = closure;
  if (notify_closure)
    {
      g_closure_ref (notify_closure);
      g_closure_sink (notify_closure);
    }
}

Because g_closure_sink() may decrement the reference count of a closure (if it hasn't been called on closure yet) just like g_closure_unref(), g_closure_ref() should be called prior to this function.

closure : GClosure to decrement the initial reference count on, if it's still being held

g_closure_unref ()

void                g_closure_unref                     (GClosure *closure);

Decrements the reference count of a closure after it was previously incremented by the same caller. If no other callers are using the closure, then the closure will be destroyed and freed.

closure : GClosure to decrement the reference count on

g_closure_invoke ()

void                g_closure_invoke                    (GClosure *closure,
                                                         GValue *return_value,
                                                         guint n_param_values,
                                                         const GValue *param_values,
                                                         gpointer invocation_hint);

Invokes the closure, i.e. executes the callback represented by the closure.

closure : | a GClosure
return_value : | a GValue to store the return value. May be NULL if the callback of closure doesn't return a value.
n_param_values : | the length of the param_values array
param_values : | an array of GValues holding the arguments on which to invoke the callback of closure
invocation_hint : | a context-dependent invocation hint

g_closure_invalidate ()

void                g_closure_invalidate                (GClosure *closure);

Sets a flag on the closure to indicate that it's calling environment has become invalid, and thus causes any future invocations of g_closure_invoke() on this closure to be ignored. Also, invalidation notifiers installed on the closure will be called at this point. Note that unless you are holding a reference to the closure yourself, the invalidation notifiers may unref the closure and cause it to be destroyed, so if you need to access the closure after calling g_closure_invalidate(), make sure that you've previously called g_closure_ref().

Note that g_closure_invalidate() will also be called when the reference count of a closure drops to zero (unless it has already been invalidated before).

closure : GClosure to invalidate

g_closure_add_finalize_notifier ()

void                g_closure_add_finalize_notifier     (GClosure *closure,
                                                         gpointer notify_data,
                                                         GClosureNotify notify_func);

Registers a finalization notifier which will be called when the reference count of closure goes down to 0. Multiple finalization notifiers on a single closure are invoked in unspecified order. If a single call to g_closure_unref() results in the closure being both invalidated and finalized, then the invalidate notifiers will be run before the finalize notifiers.

closure : | a GClosure
notify_data : | data to pass to notify_func
notify_func : | the callback function to register

g_closure_add_invalidate_notifier ()

void                g_closure_add_invalidate_notifier   (GClosure *closure,
                                                         gpointer notify_data,
                                                         GClosureNotify notify_func);

Registers an invalidation notifier which will be called when the closure is invalidated with g_closure_invalidate(). Invalidation notifiers are invoked before finalization notifiers, in an unspecified order.

closure : | a GClosure
notify_data : | data to pass to notify_func
notify_func : | the callback function to register

g_closure_remove_finalize_notifier ()

void                g_closure_remove_finalize_notifier  (GClosure *closure,
                                                         gpointer notify_data,
                                                         GClosureNotify notify_func);

Removes a finalization notifier. Notifiers are automatically removed after they are run.

closure : | a GClosure
notify_data : | data which was passed to g_closure_add_finalize_notifier() when registering notify_func
notify_func : | the callback function to remove

g_closure_remove_invalidate_notifier ()

void                g_closure_remove_invalidate_notifier
                                                        (GClosure *closure,
                                                         gpointer notify_data,
                                                         GClosureNotify notify_func);

Removes a invalidation notifier. Notifiers are automatically removed after they are run.

closure : | a GClosure
notify_data : | data which was passed to g_closure_add_invalidate_notifier() when registering notify_func
notify_func : | the callback function to remove

g_closure_new_simple ()

GClosure*           g_closure_new_simple                (guint sizeof_closure,
                                                         gpointer data);

Allocates a struct of the given size and initializes the initial part as a GClosure. This function is mainly useful when implementing new types of closures.

typedef struct _MyClosure MyClosure;
struct _MyClosure
{
  GClosure closure;
  /* extra data goes here */
};

static void
my_closure_finalize (gpointer  notify_data,
                     GClosure *closure)
{
  MyClosure *my_closure = (MyClosure *)closure;

  /* free extra data here */
}

MyClosure *my_closure_new (gpointer data)
{
  GClosure *closure;
  MyClosure *my_closure;

  closure = g_closure_new_simple (sizeof (MyClosure), data);
  my_closure = (MyClosure *) closure;

  / initialize extra data here */

  g_closure_add_finalize_notifier (closure, notify_data,
                                   my_closure_finalize);
  return my_closure;
}

sizeof_closure : | the size of the structure to allocate, must be at least sizeof (GClosure)
data : | data to store in the data field of the newly allocated GClosure
Returns : | a newly allocated GClosure

g_closure_set_marshal ()

void                g_closure_set_marshal               (GClosure *closure,
                                                         GClosureMarshal marshal);

Sets the marshaller of closure. The marshal_data provides a way for a meta marshaller to provide additional information to the marshaller. (See g_closure_set_meta_marshal().) For GObject's C predefined marshallers (the g_cclosure_marshal_*() functions), what it provides is a callback function to use instead of closure->callback.

closure : | a GClosure
marshal : | a GClosureMarshal function

g_closure_add_marshal_guards ()

void                g_closure_add_marshal_guards        (GClosure *closure,
                                                         gpointer pre_marshal_data,
                                                         GClosureNotify pre_marshal_notify,
                                                         gpointer post_marshal_data,
                                                         GClosureNotify post_marshal_notify);

Adds a pair of notifiers which get invoked before and after the closure callback, respectively. This is typically used to protect the extra arguments for the duration of the callback. See g_object_watch_closure() for an example of marshal guards.

closure : | a GClosure
pre_marshal_data : | data to pass to pre_marshal_notify
pre_marshal_notify : | a function to call before the closure callback
post_marshal_data : | data to pass to post_marshal_notify
post_marshal_notify : | a function to call after the closure callback

g_closure_set_meta_marshal ()

void                g_closure_set_meta_marshal          (GClosure *closure,
                                                         gpointer marshal_data,
                                                         GClosureMarshal meta_marshal);

Sets the meta marshaller of closure. A meta marshaller wraps closure->marshal and modifies the way it is called in some fashion. The most common use of this facility is for C callbacks. The same marshallers (generated by glib-genmarshal) are used everywhere, but the way that we get the callback function differs. In most cases we want to use closure->callback, but in other cases we want to use use some different technique to retrieve the callbakc function.

For example, class closures for signals (see g_signal_type_cclosure_new()) retrieve the callback function from a fixed offset in the class structure. The meta marshaller retrieves the right callback and passes it to the marshaller as the marshal_data argument.

closure : | a GClosure
marshal_data : | context-dependent data to pass to meta_marshal
meta_marshal : | a GClosureMarshal function

g_source_set_closure ()

void                g_source_set_closure                (GSource *source,
                                                         GClosure *closure);

Set the callback for a source as a GClosure.

If the source is not one of the standard GLib types, the closure_callback and closure_marshal fields of the GSourceFuncs structure must have been filled in with pointers to appropriate functions.

source : | the source
closure : | a GClosure

G_TYPE_IO_CHANNEL

#define G_TYPE_IO_CHANNEL (g_io_channel_get_type ())

The GType for GIOChannel.

G_TYPE_IO_CONDITION

#define G_TYPE_IO_CONDITION (g_io_condition_get_type ())

The GType for GIOCondition.

g_cclosure_marshal_VOID__VOID ()

void                g_cclosure_marshal_VOID__VOID       (GClosure *closure,
                                                         GValue *return_value,
                                                         guint n_param_values,
                                                         const GValue *param_values,
                                                         gpointer invocation_hint,
                                                         gpointer marshal_data);

A marshaller for a GCClosure with a callback of type void (*callback) (gpointer instance, gpointer user_data).

closure : | the GClosure to which the marshaller belongs
return_value : | ignored
n_param_values : | 1
param_values : | a GValue array holding only the instance
invocation_hint : | the invocation hint given as the the last argument to g_closure_invoke()
marshal_data : | additional data specified when registering the marshaller

g_cclosure_marshal_VOID__BOOLEAN ()

void                g_cclosure_marshal_VOID__BOOLEAN    (GClosure *closure,
                                                         GValue *return_value,
                                                         guint n_param_values,
                                                         const GValue *param_values,
                                                         gpointer invocation_hint,
                                                         gpointer marshal_data);

A marshaller for a GCClosure with a callback of type void (*callback) (gpointer instance, gboolean arg1, gpointer user_data).

closure : | the GClosure to which the marshaller belongs
return_value : | ignored
n_param_values : | 2
param_values : | a GValue array holding the instance and the gboolean parameter
invocation_hint : | the invocation hint given as the the last argument to g_closure_invoke()
marshal_data : | additional data specified when registering the marshaller

g_cclosure_marshal_VOID__CHAR ()

void                g_cclosure_marshal_VOID__CHAR       (GClosure *closure,
                                                         GValue *return_value,
                                                         guint n_param_values,
                                                         const GValue *param_values,
                                                         gpointer invocation_hint,
                                                         gpointer marshal_data);

A marshaller for a GCClosure with a callback of type void (*callback) (gpointer instance, gchar arg1, gpointer user_data).

closure : | the GClosure to which the marshaller belongs
return_value : | ignored
n_param_values : | 2
param_values : | a GValue array holding the instance and the gchar parameter
invocation_hint : | the invocation hint given as the the last argument to g_closure_invoke()
marshal_data : | additional data specified when registering the marshaller

g_cclosure_marshal_VOID__UCHAR ()

void                g_cclosure_marshal_VOID__UCHAR      (GClosure *closure,
                                                         GValue *return_value,
                                                         guint n_param_values,
                                                         const GValue *param_values,
                                                         gpointer invocation_hint,
                                                         gpointer marshal_data);

A marshaller for a GCClosure with a callback of type void (*callback) (gpointer instance, guchar arg1, gpointer user_data).

closure : | the GClosure to which the marshaller belongs
return_value : | ignored
n_param_values : | 2
param_values : | a GValue array holding the instance and the guchar parameter
invocation_hint : | the invocation hint given as the the last argument to g_closure_invoke()
marshal_data : | additional data specified when registering the marshaller

g_cclosure_marshal_VOID__INT ()

void                g_cclosure_marshal_VOID__INT        (GClosure *closure,
                                                         GValue *return_value,
                                                         guint n_param_values,
                                                         const GValue *param_values,
                                                         gpointer invocation_hint,
                                                         gpointer marshal_data);

A marshaller for a GCClosure with a callback of type void (*callback) (gpointer instance, gint arg1, gpointer user_data).

closure : | the GClosure to which the marshaller belongs
return_value : | ignored
n_param_values : | 2
param_values : | a GValue array holding the instance and the gint parameter
invocation_hint : | the invocation hint given as the the last argument to g_closure_invoke()
marshal_data : | additional data specified when registering the marshaller

g_cclosure_marshal_VOID__UINT ()

void                g_cclosure_marshal_VOID__UINT       (GClosure *closure,
                                                         GValue *return_value,
                                                         guint n_param_values,
                                                         const GValue *param_values,
                                                         gpointer invocation_hint,
                                                         gpointer marshal_data);

A marshaller for a GCClosure with a callback of type void (*callback) (gpointer instance, guint arg1, gpointer user_data).

closure : | the GClosure to which the marshaller belongs
return_value : | ignored
n_param_values : | 2
param_values : | a GValue array holding the instance and the guint parameter
invocation_hint : | the invocation hint given as the the last argument to g_closure_invoke()
marshal_data : | additional data specified when registering the marshaller

g_cclosure_marshal_VOID__LONG ()

void                g_cclosure_marshal_VOID__LONG       (GClosure *closure,
                                                         GValue *return_value,
                                                         guint n_param_values,
                                                         const GValue *param_values,
                                                         gpointer invocation_hint,
                                                         gpointer marshal_data);

A marshaller for a GCClosure with a callback of type void (*callback) (gpointer instance, glong arg1, gpointer user_data).

closure : | the GClosure to which the marshaller belongs
return_value : | ignored
n_param_values : | 2
param_values : | a GValue array holding the instance and the glong parameter
invocation_hint : | the invocation hint given as the the last argument to g_closure_invoke()
marshal_data : | additional data specified when registering the marshaller

g_cclosure_marshal_VOID__ULONG ()

void                g_cclosure_marshal_VOID__ULONG      (GClosure *closure,
                                                         GValue *return_value,
                                                         guint n_param_values,
                                                         const GValue *param_values,
                                                         gpointer invocation_hint,
                                                         gpointer marshal_data);

A marshaller for a GCClosure with a callback of type void (*callback) (gpointer instance, gulong arg1, gpointer user_data).

closure : | the GClosure to which the marshaller belongs
return_value : | ignored
n_param_values : | 2
param_values : | a GValue array holding the instance and the gulong parameter
invocation_hint : | the invocation hint given as the the last argument to g_closure_invoke()
marshal_data : | additional data specified when registering the marshaller

g_cclosure_marshal_VOID__ENUM ()

void                g_cclosure_marshal_VOID__ENUM       (GClosure *closure,
                                                         GValue *return_value,
                                                         guint n_param_values,
                                                         const GValue *param_values,
                                                         gpointer invocation_hint,
                                                         gpointer marshal_data);

A marshaller for a GCClosure with a callback of type void (*callback) (gpointer instance, gint arg1, gpointer user_data) where the gint parameter denotes an enumeration type..

closure : | the GClosure to which the marshaller belongs
return_value : | ignored
n_param_values : | 2
param_values : | a GValue array holding the instance and the enumeration parameter
invocation_hint : | the invocation hint given as the the last argument to g_closure_invoke()
marshal_data : | additional data specified when registering the marshaller

g_cclosure_marshal_VOID__FLAGS ()

void                g_cclosure_marshal_VOID__FLAGS      (GClosure *closure,
                                                         GValue *return_value,
                                                         guint n_param_values,
                                                         const GValue *param_values,
                                                         gpointer invocation_hint,
                                                         gpointer marshal_data);

A marshaller for a GCClosure with a callback of type void (*callback) (gpointer instance, gint arg1, gpointer user_data) where the gint parameter denotes a flags type denotes a flags type.

closure : | the GClosure to which the marshaller belongs
return_value : | ignored
n_param_values : | 2
param_values : | a GValue array holding the instance and the flags parameter
invocation_hint : | the invocation hint given as the the last argument to g_closure_invoke()
marshal_data : | additional data specified when registering the marshaller

g_cclosure_marshal_VOID__FLOAT ()

void                g_cclosure_marshal_VOID__FLOAT      (GClosure *closure,
                                                         GValue *return_value,
                                                         guint n_param_values,
                                                         const GValue *param_values,
                                                         gpointer invocation_hint,
                                                         gpointer marshal_data);

A marshaller for a GCClosure with a callback of type void (*callback) (gpointer instance, gfloat arg1, gpointer user_data).

closure : | the GClosure to which the marshaller belongs
return_value : | ignored
n_param_values : | 2
param_values : | a GValue array holding the instance and the gfloat parameter
invocation_hint : | the invocation hint given as the the last argument to g_closure_invoke()
marshal_data : | additional data specified when registering the marshaller

g_cclosure_marshal_VOID__DOUBLE ()

void                g_cclosure_marshal_VOID__DOUBLE     (GClosure *closure,
                                                         GValue *return_value,
                                                         guint n_param_values,
                                                         const GValue *param_values,
                                                         gpointer invocation_hint,
                                                         gpointer marshal_data);

A marshaller for a GCClosure with a callback of type void (*callback) (gpointer instance, gdouble arg1, gpointer user_data).

closure : | the GClosure to which the marshaller belongs
return_value : | ignored
n_param_values : | 2
param_values : | a GValue array holding the instance and the gdouble parameter
invocation_hint : | the invocation hint given as the the last argument to g_closure_invoke()
marshal_data : | additional data specified when registering the marshaller

g_cclosure_marshal_VOID__STRING ()

void                g_cclosure_marshal_VOID__STRING     (GClosure *closure,
                                                         GValue *return_value,
                                                         guint n_param_values,
                                                         const GValue *param_values,
                                                         gpointer invocation_hint,
                                                         gpointer marshal_data);

A marshaller for a GCClosure with a callback of type void (*callback) (gpointer instance, const gchar *arg1, gpointer user_data).

closure : | the GClosure to which the marshaller belongs
return_value : | ignored
n_param_values : | 2
param_values : | a GValue array holding the instance and the gchar* parameter
invocation_hint : | the invocation hint given as the the last argument to g_closure_invoke()
marshal_data : | additional data specified when registering the marshaller

g_cclosure_marshal_VOID__PARAM ()

void                g_cclosure_marshal_VOID__PARAM      (GClosure *closure,
                                                         GValue *return_value,
                                                         guint n_param_values,
                                                         const GValue *param_values,
                                                         gpointer invocation_hint,
                                                         gpointer marshal_data);

A marshaller for a GCClosure with a callback of type void (*callback) (gpointer instance, GParamSpec *arg1, gpointer user_data).

closure : | the GClosure to which the marshaller belongs
return_value : | ignored
n_param_values : | 2
param_values : | a GValue array holding the instance and the GParamSpec* parameter
invocation_hint : | the invocation hint given as the the last argument to g_closure_invoke()
marshal_data : | additional data specified when registering the marshaller

g_cclosure_marshal_VOID__BOXED ()

void                g_cclosure_marshal_VOID__BOXED      (GClosure *closure,
                                                         GValue *return_value,
                                                         guint n_param_values,
                                                         const GValue *param_values,
                                                         gpointer invocation_hint,
                                                         gpointer marshal_data);

A marshaller for a GCClosure with a callback of type void (*callback) (gpointer instance, GBoxed *arg1, gpointer user_data).

closure : | the GClosure to which the marshaller belongs
return_value : | ignored
n_param_values : | 2
param_values : | a GValue array holding the instance and the GBoxed* parameter
invocation_hint : | the invocation hint given as the the last argument to g_closure_invoke()
marshal_data : | additional data specified when registering the marshaller

g_cclosure_marshal_VOID__POINTER ()

void                g_cclosure_marshal_VOID__POINTER    (GClosure *closure,
                                                         GValue *return_value,
                                                         guint n_param_values,
                                                         const GValue *param_values,
                                                         gpointer invocation_hint,
                                                         gpointer marshal_data);

A marshaller for a GCClosure with a callback of type void (*callback) (gpointer instance, gpointer arg1, gpointer user_data).

closure : | the GClosure to which the marshaller belongs
return_value : | ignored
n_param_values : | 2
param_values : | a GValue array holding the instance and the gpointer parameter
invocation_hint : | the invocation hint given as the the last argument to g_closure_invoke()
marshal_data : | additional data specified when registering the marshaller

g_cclosure_marshal_VOID__OBJECT ()

void                g_cclosure_marshal_VOID__OBJECT     (GClosure *closure,
                                                         GValue *return_value,
                                                         guint n_param_values,
                                                         const GValue *param_values,
                                                         gpointer invocation_hint,
                                                         gpointer marshal_data);

A marshaller for a GCClosure with a callback of type void (*callback) (gpointer instance, GOBject *arg1, gpointer user_data).

closure : | the GClosure to which the marshaller belongs
return_value : | ignored
n_param_values : | 2
param_values : | a GValue array holding the instance and the GObject* parameter
invocation_hint : | the invocation hint given as the the last argument to g_closure_invoke()
marshal_data : | additional data specified when registering the marshaller

g_cclosure_marshal_STRING__OBJECT_POINTER ()

void                g_cclosure_marshal_STRING__OBJECT_POINTER
                                                        (GClosure *closure,
                                                         GValue *return_value,
                                                         guint n_param_values,
                                                         const GValue *param_values,
                                                         gpointer invocation_hint,
                                                         gpointer marshal_data);

A marshaller for a GCClosure with a callback of type void (*callback) (gpointer instance, GObject *arg1, gpointer arg2, gpointer user_data).

closure : | the GClosure to which the marshaller belongs
return_value : | ignored
n_param_values : | 3
param_values : | a GValue array holding instance, arg1 and arg2
invocation_hint : | the invocation hint given as the the last argument to g_closure_invoke()
marshal_data : | additional data specified when registering the marshaller

g_cclosure_marshal_VOID__UINT_POINTER ()

void                g_cclosure_marshal_VOID__UINT_POINTER
                                                        (GClosure *closure,
                                                         GValue *return_value,
                                                         guint n_param_values,
                                                         const GValue *param_values,
                                                         gpointer invocation_hint,
                                                         gpointer marshal_data);

A marshaller for a GCClosure with a callback of type void (*callback) (gpointer instance, guint arg1, gpointer arg2, gpointer user_data).

closure : | the GClosure to which the marshaller belongs
return_value : | ignored
n_param_values : | 3
param_values : | a GValue array holding instance, arg1 and arg2
invocation_hint : | the invocation hint given as the the last argument to g_closure_invoke()
marshal_data : | additional data specified when registering the marshaller

g_cclosure_marshal_BOOLEAN__FLAGS ()

void                g_cclosure_marshal_BOOLEAN__FLAGS   (GClosure *closure,
                                                         GValue *return_value,
                                                         guint n_param_values,
                                                         const GValue *param_values,
                                                         gpointer invocation_hint,
                                                         gpointer marshal_data);

A marshaller for a GCClosure with a callback of type gboolean (*callback) (gpointer instance, gint arg1, gpointer user_data) where the gint parameter denotes a flags type.

closure : | the GClosure to which the marshaller belongs
return_value : | a GValue which can store the returned gboolean
n_param_values : | 2
param_values : | a GValue array holding instance and arg1
invocation_hint : | the invocation hint given as the the last argument to g_closure_invoke()
marshal_data : | additional data specified when registering the marshaller

g_cclosure_marshal_BOOL__FLAGS

#define             g_cclosure_marshal_BOOL__FLAGS

Another name for g_cclosure_marshal_BOOLEAN__FLAGS().


Enums and Flags

Enums and Flags — Enumeration and flags types

Synopsis

#include <glib-object.h>

                    GEnumClass;
                    GFlagsClass;
#define             G_ENUM_CLASS_TYPE                   (class)
#define             G_ENUM_CLASS_TYPE_NAME              (class)
#define             G_TYPE_IS_ENUM                      (type)
#define             G_ENUM_CLASS                        (class)
#define             G_IS_ENUM_CLASS                     (class)
#define             G_TYPE_IS_FLAGS                     (type)
#define             G_FLAGS_CLASS                       (class)
#define             G_IS_FLAGS_CLASS                    (class)
#define             G_FLAGS_CLASS_TYPE                  (class)
#define             G_FLAGS_CLASS_TYPE_NAME             (class)
                    GEnumValue;
                    GFlagsValue;
GEnumValue*         g_enum_get_value                    (GEnumClass *enum_class,
                                                         gint value);
GEnumValue*         g_enum_get_value_by_name            (GEnumClass *enum_class,
                                                         const gchar *name);
GEnumValue*         g_enum_get_value_by_nick            (GEnumClass *enum_class,
                                                         const gchar *nick);
GFlagsValue*        g_flags_get_first_value             (GFlagsClass *flags_class,
                                                         guint value);
GFlagsValue*        g_flags_get_value_by_name           (GFlagsClass *flags_class,
                                                         const gchar *name);
GFlagsValue*        g_flags_get_value_by_nick           (GFlagsClass *flags_class,
                                                         const gchar *nick);
GType               g_enum_register_static              (const gchar *name,
                                                         const GEnumValue *const _static_values);
GType               g_flags_register_static             (const gchar *name,
                                                         const GFlagsValue *const _static_values);
void                g_enum_complete_type_info           (GType g_enum_type,
                                                         GTypeInfo *info,
                                                         const GEnumValue *const _values);
void                g_flags_complete_type_info          (GType g_flags_type,
                                                         GTypeInfo *info,
                                                         const GFlagsValue *const _values);

Description

The GLib type system provides fundamental types for enumeration and flags types. (Flags types are like enumerations, but allow their values to be combined by bitwise or). A registered enumeration or flags type associates a name and a nickname with each allowed value, and the methods g_enum_get_value_by_name(), g_enum_get_value_by_nick(), g_flags_get_value_by_name() and g_flags_get_value_by_nick() can look up values by their name or nickname. When an enumeration or flags type is registered with the GLib type system, it can be used as value type for object properties, using g_param_spec_enum() or g_param_spec_flags().

GObject ships with a utility called glib-mkenums that can construct suitable type registration functions from C enumeration definitions.

Details

GEnumClass

typedef struct {
  GTypeClass  g_type_class;

  gint	      minimum;
  gint	      maximum;
  guint	      n_values;
  GEnumValue *values;
} GEnumClass;

The class of an enumeration type holds information about its possible values.

GTypeClass g_type_class; | the parent class
gint minimum; | the smallest possible value.
gint maximum; | the largest possible value.
guint n_values; | the number of possible values.
GEnumValue *values; | an array of GEnumValue structs describing the individual values.

GFlagsClass

typedef struct {
  GTypeClass   g_type_class;

  guint	       mask;
  guint	       n_values;
  GFlagsValue *values;
} GFlagsClass;

The class of a flags type holds information about its possible values.

GTypeClass g_type_class; | the parent class
guint mask; | a mask covering all possible values.
guint n_values; | the number of possible values.
GFlagsValue *values; | an array of GFlagsValue structs describing the individual values.

G_ENUM_CLASS_TYPE()

#define G_ENUM_CLASS_TYPE(class)       (G_TYPE_FROM_CLASS (class))

Returns the type identifier from a given GEnumClass structure.

class : a GEnumClass

G_ENUM_CLASS_TYPE_NAME()

#define G_ENUM_CLASS_TYPE_NAME(class)  (g_type_name (G_ENUM_CLASS_TYPE (class)))

Returns the static type name from a given GEnumClass structure.

class : a GEnumClass

G_TYPE_IS_ENUM()

#define G_TYPE_IS_ENUM(type)	       (G_TYPE_FUNDAMENTAL (type) == G_TYPE_ENUM)

Returns whether type "is a" G_TYPE_ENUM.

type : a GType ID.

G_ENUM_CLASS()

#define G_ENUM_CLASS(class)	       (G_TYPE_CHECK_CLASS_CAST ((class), G_TYPE_ENUM, GEnumClass))

Casts a derived GEnumClass structure into a GEnumClass structure.

class : a valid GEnumClass

G_IS_ENUM_CLASS()

#define G_IS_ENUM_CLASS(class)	       (G_TYPE_CHECK_CLASS_TYPE ((class), G_TYPE_ENUM))

Checks whether class "is a" valid GEnumClass structure of type G_TYPE_ENUM or derived.

class : a GEnumClass

G_TYPE_IS_FLAGS()

#define G_TYPE_IS_FLAGS(type)	       (G_TYPE_FUNDAMENTAL (type) == G_TYPE_FLAGS)

Returns whether type "is a" G_TYPE_FLAGS.

type : a GType ID.

G_FLAGS_CLASS()

#define G_FLAGS_CLASS(class)	       (G_TYPE_CHECK_CLASS_CAST ((class), G_TYPE_FLAGS, GFlagsClass))

Casts a derived GFlagsClass structure into a GFlagsClass structure.

class : a valid GFlagsClass

G_IS_FLAGS_CLASS()

#define G_IS_FLAGS_CLASS(class)        (G_TYPE_CHECK_CLASS_TYPE ((class), G_TYPE_FLAGS))

Checks whether class "is a" valid GFlagsClass structure of type G_TYPE_FLAGS or derived.

class : a GFlagsClass

G_FLAGS_CLASS_TYPE()

#define G_FLAGS_CLASS_TYPE(class)      (G_TYPE_FROM_CLASS (class))

Returns the type identifier from a given GFlagsClass structure.

class : a GFlagsClass

G_FLAGS_CLASS_TYPE_NAME()

#define G_FLAGS_CLASS_TYPE_NAME(class) (g_type_name (G_FLAGS_CLASS_TYPE (class)))

Returns the static type name from a given GFlagsClass structure.

class : a GFlagsClass

GEnumValue

typedef struct {
  gint	 value;
  const gchar *value_name;
  const gchar *value_nick;
} GEnumValue;

A structure which contains a single enum value, it's name, and it's nickname.

gint value; | the enum value
const gchar *value_name; | the name of the value
const gchar *value_nick; | the nickname of the value

GFlagsValue

typedef struct {
  guint	 value;
  const gchar *value_name;
  const gchar *value_nick;
} GFlagsValue;

A structure which contains a single flags value, it's name, and it's nickname.

guint value; | the flags value
const gchar *value_name; | the name of the value
const gchar *value_nick; | the nickname of the value

g_enum_get_value ()

GEnumValue*         g_enum_get_value                    (GEnumClass *enum_class,
                                                         gint value);

Returns the GEnumValue for a value.

enum_class : | a GEnumClass
value : | the value to look up
Returns : | the GEnumValue for value, or NULL if value is not a member of the enumeration

g_enum_get_value_by_name ()

GEnumValue*         g_enum_get_value_by_name            (GEnumClass *enum_class,
                                                         const gchar *name);

Looks up a GEnumValue by name.

enum_class : | a GEnumClass
name : | the name to look up
Returns : | the GEnumValue with name name, or NULL if the enumeration doesn' t have a member with that name

g_enum_get_value_by_nick ()

GEnumValue*         g_enum_get_value_by_nick            (GEnumClass *enum_class,
                                                         const gchar *nick);

Looks up a GEnumValue by nickname.

enum_class : | a GEnumClass
nick : | the nickname to look up
Returns : | the GEnumValue with nickname nick, or NULL if the enumeration doesn' t have a member with that nickname

g_flags_get_first_value ()

GFlagsValue*        g_flags_get_first_value             (GFlagsClass *flags_class,
                                                         guint value);

Returns the first GFlagsValue which is set in value.

flags_class : | a GFlagsClass
value : | the value
Returns : | the first GFlagsValue which is set in value, or NULL if none is set

g_flags_get_value_by_name ()

GFlagsValue*        g_flags_get_value_by_name           (GFlagsClass *flags_class,
                                                         const gchar *name);

Looks up a GFlagsValue by name.

flags_class : | a GFlagsClass
name : | the name to look up
Returns : | the GFlagsValue with name name, or NULL if there is no flag with that name

g_flags_get_value_by_nick ()

GFlagsValue*        g_flags_get_value_by_nick           (GFlagsClass *flags_class,
                                                         const gchar *nick);

Looks up a GFlagsValue by nickname.

flags_class : | a GFlagsClass
nick : | the nickname to look up
Returns : | the GFlagsValue with nickname nick, or NULL if there is no flag with that nickname

g_enum_register_static ()

GType               g_enum_register_static              (const gchar *name,
                                                         const GEnumValue *const _static_values);

Registers a new static enumeration type with the name name.

It is normally more convenient to let glib-mkenums generate a my_enum_get_type() function from a usual C enumeration definition than to write one yourself using g_enum_register_static().

name : | A nul-terminated string used as the name of the new type.
_static_values : |
Returns : | The new type identifier.

g_flags_register_static ()

GType               g_flags_register_static             (const gchar *name,
                                                         const GFlagsValue *const _static_values);

Registers a new static flags type with the name name.

It is normally more convenient to let glib-mkenums generate a my_flags_get_type() function from a usual C enumeration definition than to write one yourself using g_flags_register_static().

name : | A nul-terminated string used as the name of the new type.
_static_values : |
Returns : | The new type identifier.

g_enum_complete_type_info ()

void                g_enum_complete_type_info           (GType g_enum_type,
                                                         GTypeInfo *info,
                                                         const GEnumValue *const _values);

This function is meant to be called from the complete_type_info() function of a GTypePlugin implementation, as in the following example:

static void
my_enum_complete_type_info (GTypePlugin     *plugin,
                            GType            g_type,
                            GTypeInfo       *info,
                            GTypeValueTable *value_table)
{
  static const GEnumValue values[] = {
    { MY_ENUM_FOO, "MY_ENUM_FOO", "foo" },
    { MY_ENUM_BAR, "MY_ENUM_BAR", "bar" },
    { 0, NULL, NULL }
  };

  g_enum_complete_type_info (type, info, values);
}

g_enum_type : | the type identifier of the type being completed
info : | the GTypeInfo struct to be filled in
_values : |

g_flags_complete_type_info ()

void                g_flags_complete_type_info          (GType g_flags_type,
                                                         GTypeInfo *info,
                                                         const GFlagsValue *const _values);

This function is meant to be called from the complete_type_info() function of a GTypePlugin implementation, see the example for g_enumeration_complete_type_info() above.

g_flags_type : | the type identifier of the type being completed
info : | the GTypeInfo struct to be filled in
_values : |

See Also

GParamSpecEnum, GParamSpecFlags, g_param_spec_enum(), g_param_spec_flags(), glib-mkenums


Generic Values

Generic Values — A polymorphic type that can hold values of any other type

Synopsis

#include <glib-object.h>

#define             G_VALUE_HOLDS                       (value,type)
#define             G_VALUE_TYPE                        (value)
#define             G_VALUE_TYPE_NAME                   (value)
#define             G_TYPE_IS_VALUE                     (type)
#define             G_TYPE_IS_VALUE_ABSTRACT            (type)
#define             G_IS_VALUE                          (value)
                    GValue;
#define             G_TYPE_VALUE
#define             G_TYPE_VALUE_ARRAY
GValue*             g_value_init                        (GValue *value,
                                                         GType g_type);
void                g_value_copy                        (const GValue *src_value,
                                                         GValue *dest_value);
GValue*             g_value_reset                       (GValue *value);
void                g_value_unset                       (GValue *value);
void                g_value_set_instance                (GValue *value,
                                                         gpointer instance);
gboolean            g_value_fits_pointer                (const GValue *value);
gpointer            g_value_peek_pointer                (const GValue *value);
gboolean            g_value_type_compatible             (GType src_type,
                                                         GType dest_type);
gboolean            g_value_type_transformable          (GType src_type,
                                                         GType dest_type);
gboolean            g_value_transform                   (const GValue *src_value,
                                                         GValue *dest_value);
void                (*GValueTransform)                  (const GValue *src_value,
                                                         GValue *dest_value);
void                g_value_register_transform_func     (GType src_type,
                                                         GType dest_type,
                                                         GValueTransform transform_func);
gchar*              g_strdup_value_contents             (const GValue *value);

Description

The GValue structure is basically a variable container that consists of a type identifier and a specific value of that type. The type identifier within a GValue structure always determines the type of the associated value. To create a undefined GValue structure, simply create a zero-filled GValue structure. To initialize the GValue, use the g_value_init() function. A GValue cannot be used until it is initialized. The basic type operations (such as freeing and copying) are determined by the GTypeValueTable associated with the type ID stored in the GValue. Other GValue operations (such as converting values between types) are provided by this interface.

Details

G_VALUE_HOLDS()

#define G_VALUE_HOLDS(value,type)	(G_TYPE_CHECK_VALUE_TYPE ((value), (type)))

Returns TRUE if value holds (or contains) a value of type. This macro will also check for value != NULL and issue a warning if the check fails.

value : | A GValue structure.
type : | A GType value.

G_VALUE_TYPE()

#define	G_VALUE_TYPE(value)		(((GValue*) (value))->g_type)

Returns the type identifier of value.

value : A GValue structure.

G_VALUE_TYPE_NAME()

#define	G_VALUE_TYPE_NAME(value)	(g_type_name (G_VALUE_TYPE (value)))

Returns the type name of value.

value : A GValue structure.

G_TYPE_IS_VALUE()

#define	G_TYPE_IS_VALUE(type)		(g_type_check_is_value_type (type))

Return whether the passed in type ID can be used for g_value_init(). That is, this macro checks whether this type provides an implementation of the GTypeValueTable functions required for a type to create a GValue of.

type : | A GType value.
Returns : | Whether type is suitable as a GValue type.

G_TYPE_IS_VALUE_ABSTRACT()

#define G_TYPE_IS_VALUE_ABSTRACT(type)          (g_type_test_flags ((type), G_TYPE_FLAG_VALUE_ABSTRACT))

Returns TRUE if type is an abstract value type. An abstract value type introduces a value table, but can't be used for g_value_init() and is normally used as an abstract base type for derived value types.

type : A GType value.

G_IS_VALUE()

#define	G_IS_VALUE(value)		(G_TYPE_CHECK_VALUE (value))

Returns TRUE if value is a valid and initialized GValue structure.

value : A GValue structure.

GValue

typedef struct {
} GValue;

An opaque structure used to hold different types of values. The data within the structure has protected scope: it is accessible only to functions within a GTypeValueTable structure, or implementations of the g_value_*() API. That is, code portions which implement new fundamental types. GValue users can not make any assumptions about how data is stored within the 2 element data union, and the g_type member should only be accessed through the G_VALUE_TYPE() macro.

G_TYPE_VALUE

#define	G_TYPE_VALUE		(g_value_get_type ())

Returns the type ID of the "GValue" type which is a boxed type, used to pass around pointers to GValues.

G_TYPE_VALUE_ARRAY

#define	G_TYPE_VALUE_ARRAY	(g_value_array_get_type ())

Returns the type ID of the "GValueArray" type which is a boxed type, used to pass around pointers to GValueArrays.

g_value_init ()

GValue*             g_value_init                        (GValue *value,
                                                         GType g_type);

Initializes value with the default value of type.

value : | A zero-filled (uninitialized) GValue structure.
g_type : | Type the GValue should hold values of.
Returns : | the GValue structure that has been passed in

g_value_copy ()

void                g_value_copy                        (const GValue *src_value,
                                                         GValue *dest_value);

Copies the value of src_value into dest_value.

src_value : | An initialized GValue structure.
dest_value : | An initialized GValue structure of the same type as src_value.

g_value_reset ()

GValue*             g_value_reset                       (GValue *value);

Clears the current value in value and resets it to the default value (as if the value had just been initialized).

value : | An initialized GValue structure.
Returns : | the GValue structure that has been passed in

g_value_unset ()

void                g_value_unset                       (GValue *value);

Clears the current value in value and "unsets" the type, this releases all resources associated with this GValue. An unset value is the same as an uninitialized (zero-filled) GValue structure.

value : An initialized GValue structure.

g_value_set_instance ()

void                g_value_set_instance                (GValue *value,
                                                         gpointer instance);

Sets value from an instantiatable type via the value_table's collect_value() function.

value : | An initialized GValue structure.
instance : | the instance

g_value_fits_pointer ()

gboolean            g_value_fits_pointer                (const GValue *value);

Determines if value will fit inside the size of a pointer value. This is an internal function introduced mainly for C marshallers.

value : | An initialized GValue structure.
Returns : | TRUE if value will fit inside a pointer value.

g_value_peek_pointer ()

gpointer            g_value_peek_pointer                (const GValue *value);

Return the value contents as pointer. This function asserts that g_value_fits_pointer() returned TRUE for the passed in value. This is an internal function introduced mainly for C marshallers.

value : | An initialized GValue structure.
Returns : | TRUE if value will fit inside a pointer value.

g_value_type_compatible ()

gboolean            g_value_type_compatible             (GType src_type,
                                                         GType dest_type);

Returns whether a GValue of type src_type can be copied into a GValue of type dest_type.

src_type : | source type to be copied.
dest_type : | destination type for copying.
Returns : | TRUE if g_value_copy() is possible with src_type and dest_type.

g_value_type_transformable ()

gboolean            g_value_type_transformable          (GType src_type,
                                                         GType dest_type);

Check whether g_value_transform() is able to transform values of type src_type into values of type dest_type.

src_type : | Source type.
dest_type : | Target type.
Returns : | TRUE if the transformation is possible, FALSE otherwise.

g_value_transform ()

gboolean            g_value_transform                   (const GValue *src_value,
                                                         GValue *dest_value);

Tries to cast the contents of src_value into a type appropriate to store in dest_value, e.g. to transform a G_TYPE_INT value into a G_TYPE_FLOAT value. Performing transformations between value types might incur precision lossage. Especially transformations into strings might reveal seemingly arbitrary results and shouldn't be relied upon for production code (such as rcfile value or object property serialization).

src_value : | Source value.
dest_value : | Target value.
Returns : | Whether a transformation rule was found and could be applied. Upon failing transformations, dest_value is left untouched.

GValueTransform ()

void                (*GValueTransform)                  (const GValue *src_value,
                                                         GValue *dest_value);

The type of value transformation functions which can be registered with g_value_register_transform_func().

src_value : | Source value.
dest_value : | Target value.

g_value_register_transform_func ()

void                g_value_register_transform_func     (GType src_type,
                                                         GType dest_type,
                                                         GValueTransform transform_func);

Registers a value transformation function for use in g_value_transform(). A previously registered transformation function for src_type and dest_type will be replaced.

src_type : | Source type.
dest_type : | Target type.
transform_func : | a function which transforms values of type src_type into value of type dest_type

g_strdup_value_contents ()

gchar*              g_strdup_value_contents             (const GValue *value);

Return a newly allocated string, which describes the contents of a GValue. The main purpose of this function is to describe GValue contents for debugging output, the way in which the contents are described may change between different GLib versions.

value : | GValue which contents are to be described.
Returns : | Newly allocated string.

See Also

The fundamental types which all support GValue operations and thus can be used as a type initializer for g_value_init() are defined by a separate interface. See the Standard Values API for details.


GParamSpec

GParamSpec — Metadata for parameter specifications

Synopsis

#include <glib-object.h>

#define             G_TYPE_IS_PARAM                     (type)
#define             G_PARAM_SPEC                        (pspec)
#define             G_IS_PARAM_SPEC                     (pspec)
#define             G_PARAM_SPEC_CLASS                  (pclass)
#define             G_IS_PARAM_SPEC_CLASS               (pclass)
#define             G_PARAM_SPEC_GET_CLASS              (pspec)
#define             G_PARAM_SPEC_TYPE                   (pspec)
#define             G_PARAM_SPEC_TYPE_NAME              (pspec)
#define             G_PARAM_SPEC_VALUE_TYPE             (pspec)
                    GParamSpec;
                    GParamSpecClass;
enum                GParamFlags;
#define             G_PARAM_READWRITE
#define             G_PARAM_MASK
#define             G_PARAM_USER_SHIFT
GParamSpec*         g_param_spec_ref                    (GParamSpec *pspec);
void                g_param_spec_unref                  (GParamSpec *pspec);
void                g_param_spec_sink                   (GParamSpec *pspec);
GParamSpec*         g_param_spec_ref_sink               (GParamSpec *pspec);
void                g_param_value_set_default           (GParamSpec *pspec,
                                                         GValue *value);
gboolean            g_param_value_defaults              (GParamSpec *pspec,
                                                         GValue *value);
gboolean            g_param_value_validate              (GParamSpec *pspec,
                                                         GValue *value);
gboolean            g_param_value_convert               (GParamSpec *pspec,
                                                         const GValue *src_value,
                                                         GValue *dest_value,
                                                         gboolean strict_validation);
gint                g_param_values_cmp                  (GParamSpec *pspec,
                                                         const GValue *value1,
                                                         const GValue *value2);
const gchar*        g_param_spec_get_name               (GParamSpec *pspec);
const gchar*        g_param_spec_get_nick               (GParamSpec *pspec);
const gchar*        g_param_spec_get_blurb              (GParamSpec *pspec);
gpointer            g_param_spec_get_qdata              (GParamSpec *pspec,
                                                         GQuark quark);
void                g_param_spec_set_qdata              (GParamSpec *pspec,
                                                         GQuark quark,
                                                         gpointer data);
void                g_param_spec_set_qdata_full         (GParamSpec *pspec,
                                                         GQuark quark,
                                                         gpointer data,
                                                         GDestroyNotify destroy);
gpointer            g_param_spec_steal_qdata            (GParamSpec *pspec,
                                                         GQuark quark);
GParamSpec*         g_param_spec_get_redirect_target    (GParamSpec *pspec);
gpointer            g_param_spec_internal               (GType param_type,
                                                         const gchar *name,
                                                         const gchar *nick,
                                                         const gchar *blurb,
                                                         GParamFlags flags);
                    GParamSpecTypeInfo;
GType               g_param_type_register_static        (const gchar *name,
                                                         const GParamSpecTypeInfo *pspec_info);
                    GParamSpecPool;
GParamSpecPool*     g_param_spec_pool_new               (gboolean type_prefixing);
void                g_param_spec_pool_insert            (GParamSpecPool *pool,
                                                         GParamSpec *pspec,
                                                         GType owner_type);
void                g_param_spec_pool_remove            (GParamSpecPool *pool,
                                                         GParamSpec *pspec);
GParamSpec*         g_param_spec_pool_lookup            (GParamSpecPool *pool,
                                                         const gchar *param_name,
                                                         GType owner_type,
                                                         gboolean walk_ancestors);
GParamSpec**        g_param_spec_pool_list              (GParamSpecPool *pool,
                                                         GType owner_type,
                                                         guint *n_pspecs_p);
GList*              g_param_spec_pool_list_owned        (GParamSpecPool *pool,
                                                         GType owner_type);

Description

GParamSpec is an object structure that encapsulates the metadata required to specify parameters, such as e.g. GObject properties.

Parameter names need to start with a letter (a-z or A-Z). Subsequent characters can be letters, numbers or a '-'. All other characters are replaced by a '-' during construction.

Details

G_TYPE_IS_PARAM()

#define G_TYPE_IS_PARAM(type)		(G_TYPE_FUNDAMENTAL (type) == G_TYPE_PARAM)

Returns whether type "is a" G_TYPE_PARAM.

type : a GType ID

G_PARAM_SPEC()

#define G_PARAM_SPEC(pspec)		(G_TYPE_CHECK_INSTANCE_CAST ((pspec), G_TYPE_PARAM, GParamSpec))

Casts a derived GParamSpec object (e.g. of type GParamSpecInt) into a GParamSpec object.

pspec : a valid GParamSpec

G_IS_PARAM_SPEC()

#define G_IS_PARAM_SPEC(pspec)		(G_TYPE_CHECK_INSTANCE_TYPE ((pspec), G_TYPE_PARAM))

Checks whether pspec "is a" valid GParamSpec structure of type G_TYPE_PARAM or derived.

pspec : a GParamSpec

G_PARAM_SPEC_CLASS()

#define G_PARAM_SPEC_CLASS(pclass)      (G_TYPE_CHECK_CLASS_CAST ((pclass), G_TYPE_PARAM, GParamSpecClass))

Casts a derived GParamSpecClass structure into a GParamSpecClass structure.

pclass : a valid GParamSpecClass

G_IS_PARAM_SPEC_CLASS()

#define G_IS_PARAM_SPEC_CLASS(pclass)   (G_TYPE_CHECK_CLASS_TYPE ((pclass), G_TYPE_PARAM))

Checks whether pclass "is a" valid GParamSpecClass structure of type G_TYPE_PARAM or derived.

pclass : a GParamSpecClass

G_PARAM_SPEC_GET_CLASS()

#define G_PARAM_SPEC_GET_CLASS(pspec)	(G_TYPE_INSTANCE_GET_CLASS ((pspec), G_TYPE_PARAM, GParamSpecClass))

Retrieves the GParamSpecClass of a GParamSpec.

pspec : a valid GParamSpec

G_PARAM_SPEC_TYPE()

#define G_PARAM_SPEC_TYPE(pspec)	(G_TYPE_FROM_INSTANCE (pspec))

Retrieves the GType of this pspec.

pspec : a valid GParamSpec

G_PARAM_SPEC_TYPE_NAME()

#define G_PARAM_SPEC_TYPE_NAME(pspec)	(g_type_name (G_PARAM_SPEC_TYPE (pspec)))

Retrieves the GType name of this pspec.

pspec : a valid GParamSpec

G_PARAM_SPEC_VALUE_TYPE()

#define	G_PARAM_SPEC_VALUE_TYPE(pspec)	(G_PARAM_SPEC (pspec)->value_type)

Retrieves the GType to initialize a GValue for this parameter.

pspec : a valid GParamSpec

GParamSpec

typedef struct {
  GTypeInstance  g_type_instance;

  gchar         *name;
  GParamFlags    flags;
  GType		 value_type;
  GType		 owner_type;	/* class or interface using this property */
} GParamSpec;

All fields of the GParamSpec struct are private and should not be used directly, except for the following:

GTypeInstance g_type_instance; | private GTypeInstance portion
gchar *name; | name of this parameter
GParamFlags flags; | GParamFlags flags for this parameter
GType value_type; | the GValue type for this parameter
GType owner_type; | GType type that uses (introduces) this paremeter

GParamSpecClass

typedef struct {
  GTypeClass      g_type_class;

  GType		  value_type;

  void	        (*finalize)		(GParamSpec   *pspec);

  /* GParam methods */
  void          (*value_set_default)    (GParamSpec   *pspec,
                     GValue       *value);
  gboolean      (*value_validate)       (GParamSpec   *pspec,
                     GValue       *value);
  gint          (*values_cmp)           (GParamSpec   *pspec,
                     const GValue *value1,
                     const GValue *value2);
} GParamSpecClass;

The class structure for the GParamSpec type. Normally, GParamSpec classes are filled by g_param_type_register_static().

GTypeClass g_type_class; | the parent class
GType value_type; | the GValue type for this parameter
finalize () | The instance finalization function (optional), should chain up to the finalize method of the parent class.
value_set_default () | Resets a value to the default value for this type (recommended, the default is g_value_reset()), see g_param_value_set_default().
value_validate () | Ensures that the contents of value comply with the specifications set out by this type (optional), see g_param_value_set_validate().
values_cmp () | Compares value1 with value2 according to this type (recommended, the default is memcmp()), see g_param_values_cmp().

enum GParamFlags

typedef enum
{
  G_PARAM_READABLE            = 1 << 0,
  G_PARAM_WRITABLE            = 1 << 1,
  G_PARAM_CONSTRUCT	      = 1 << 2,
  G_PARAM_CONSTRUCT_ONLY      = 1 << 3,
  G_PARAM_LAX_VALIDATION      = 1 << 4,
  G_PARAM_STATIC_NAME	      = 1 << 5,
#ifndef G_DISABLE_DEPRECATED
  G_PARAM_PRIVATE	      = G_PARAM_STATIC_NAME,
#endif
  G_PARAM_STATIC_NICK	      = 1 << 6,
  G_PARAM_STATIC_BLURB	      = 1 << 7
} GParamFlags;

Through the GParamFlags flag values, certain aspects of parameters can be configured.

G_PARAM_READABLE | the parameter is readable
G_PARAM_WRITABLE | the parameter is writable
G_PARAM_CONSTRUCT | the parameter will be set upon object construction
G_PARAM_CONSTRUCT_ONLY | the parameter will only be set upon object construction
G_PARAM_LAX_VALIDATION | upon parameter conversion (see g_param_value_convert()) strict validation is not required
G_PARAM_STATIC_NAME | the string used as name when constructing the parameter is guaranteed to remain valid and unmodified for the lifetime of the parameter. Since 2.8
G_PARAM_STATIC_BLURB | the string used as blurb when constructing the parameter is guaranteed to remain valid and unmodified for the lifetime of the parameter. Since 2.8

G_PARAM_READWRITE

#define	G_PARAM_READWRITE	(G_PARAM_READABLE | G_PARAM_WRITABLE)

GParamFlags value alias for G_PARAM_READABLE | G_PARAM_WRITABLE.

G_PARAM_MASK

#define	G_PARAM_MASK		(0x000000ff)

Mask containing the bits of GParamSpec.flags which are reserved for GLib.

G_PARAM_USER_SHIFT

#define	G_PARAM_USER_SHIFT	(8)

Minimum shift count to be used for user defined flags, to be stored in GParamSpec.flags.

g_param_spec_ref ()

GParamSpec*         g_param_spec_ref                    (GParamSpec *pspec);

Increments the reference count of pspec.

pspec : | a valid GParamSpec
Returns : | the GParamSpec that was passed into this function

g_param_spec_unref ()

void                g_param_spec_unref                  (GParamSpec *pspec);

Decrements the reference count of a pspec.

pspec : a valid GParamSpec

g_param_spec_sink ()

void                g_param_spec_sink                   (GParamSpec *pspec);

The initial reference count of a newly created GParamSpec is 1, even though no one has explicitly called g_param_spec_ref() on it yet. So the initial reference count is flagged as "floating", until someone calls g_param_spec_ref (pspec); g_param_spec_sink (pspec); in sequence on it, taking over the initial reference count (thus ending up with a pspec that has a reference count of 1 still, but is not flagged "floating" anymore).

pspec : a valid GParamSpec

g_param_spec_ref_sink ()

GParamSpec*         g_param_spec_ref_sink               (GParamSpec *pspec);

Convenience function to ref and sink a GParamSpec.

pspec : | a valid GParamSpec
Returns : | the GParamSpec that was passed into this function

Since 2.10

g_param_value_set_default ()

void                g_param_value_set_default           (GParamSpec *pspec,
                                                         GValue *value);

Sets value to its default value as specified in pspec.

pspec : | a valid GParamSpec
value : | a GValue of correct type for pspec

g_param_value_defaults ()

gboolean            g_param_value_defaults              (GParamSpec *pspec,
                                                         GValue *value);

Checks whether value contains the default value as specified in pspec.

pspec : | a valid GParamSpec
value : | a GValue of correct type for pspec
Returns : | whether value contains the canonical defualt for this pspec

g_param_value_validate ()

gboolean            g_param_value_validate              (GParamSpec *pspec,
                                                         GValue *value);

Ensures that the contents of value comply with the specifications set out by pspec. For example, a GParamSpecInt might require that integers stored in value may not be smaller than -42 and not be greater than +42. If value contains an integer outside of this range, it is modified accordingly, so the resulting value will fit into the range -42 .. +42.

pspec : | a valid GParamSpec
value : | a GValue of correct type for pspec
Returns : | whether modifying value was necessary to ensure validity

g_param_value_convert ()

gboolean            g_param_value_convert               (GParamSpec *pspec,
                                                         const GValue *src_value,
                                                         GValue *dest_value,
                                                         gboolean strict_validation);

Transforms src_value into dest_value if possible, and then validates dest_value, in order for it to conform to pspec. If strict_validation is TRUE this function will only succeed if the transformed dest_value complied to pspec without modifications. See also g_value_type_transformable(), g_value_transform() and g_param_value_validate().

pspec : | a valid GParamSpec
src_value : | souce GValue
dest_value : | destination GValue of correct type for pspec
strict_validation : | TRUE requires dest_value to conform to pspec without modifications
Returns : | TRUE if transformation and validation were successful, FALSE otherwise and dest_value is left untouched.

g_param_values_cmp ()

gint                g_param_values_cmp                  (GParamSpec *pspec,
                                                         const GValue *value1,
                                                         const GValue *value2);

Compares value1 with value2 according to pspec, and return -1, 0 or +1, if value1 is found to be less than, equal to or greater than value2, respectively.

pspec : | a valid GParamSpec
value1 : | a GValue of correct type for pspec
value2 : | a GValue of correct type for pspec
Returns : | -1, 0 or +1, for a less than, equal to or greater than result

g_param_spec_get_name ()

const gchar*        g_param_spec_get_name               (GParamSpec *pspec);

Returns the name of a GParamSpec.

pspec : | a valid GParamSpec
Returns : | the name of pspec.

g_param_spec_get_nick ()

const gchar*        g_param_spec_get_nick               (GParamSpec *pspec);

Returns the nickname of a GParamSpec.

pspec : | a valid GParamSpec
Returns : | the nickname of pspec.

g_param_spec_get_blurb ()

const gchar*        g_param_spec_get_blurb              (GParamSpec *pspec);

Returns the short description of a GParamSpec.

pspec : | a valid GParamSpec
Returns : | the short description of pspec.

g_param_spec_get_qdata ()

gpointer            g_param_spec_get_qdata              (GParamSpec *pspec,
                                                         GQuark quark);

Gets back user data pointers stored via g_param_spec_set_qdata().

pspec : | a valid GParamSpec
quark : | a GQuark, naming the user data pointer
Returns : | the user data pointer set, or NULL

g_param_spec_set_qdata ()

void                g_param_spec_set_qdata              (GParamSpec *pspec,
                                                         GQuark quark,
                                                         gpointer data);

Sets an opaque, named pointer on a GParamSpec. The name is specified through a GQuark (retrieved e.g. via g_quark_from_static_string()), and the pointer can be gotten back from the pspec with g_param_spec_get_qdata(). Setting a previously set user data pointer, overrides (frees) the old pointer set, using NULL as pointer essentially removes the data stored.

pspec : | the GParamSpec to set store a user data pointer
quark : | a GQuark, naming the user data pointer
data : | an opaque user data pointer

g_param_spec_set_qdata_full ()

void                g_param_spec_set_qdata_full         (GParamSpec *pspec,
                                                         GQuark quark,
                                                         gpointer data,
                                                         GDestroyNotify destroy);

This function works like g_param_spec_set_qdata(), but in addition, a void (*destroy) (gpointer) function may be specified which is called with data as argument when the pspec is finalized, or the data is being overwritten by a call to g_param_spec_set_qdata() with the same quark.

pspec : | the GParamSpec to set store a user data pointer
quark : | a GQuark, naming the user data pointer
data : | an opaque user data pointer
destroy : | function to invoke with data as argument, when data needs to be freed

g_param_spec_steal_qdata ()

gpointer            g_param_spec_steal_qdata            (GParamSpec *pspec,
                                                         GQuark quark);

Gets back user data pointers stored via g_param_spec_set_qdata() and removes the data from pspec without invoking it's destroy() function (if any was set). Usually, calling this function is only required to update user data pointers with a destroy notifier.

pspec : | the GParamSpec to get a stored user data pointer from
quark : | a GQuark, naming the user data pointer
Returns : | the user data pointer set, or NULL

g_param_spec_get_redirect_target ()

GParamSpec*         g_param_spec_get_redirect_target    (GParamSpec *pspec);

If the paramspec redirects operations to another paramspec, returns that paramspec. Redirect is used typically for providing a new implementation of a property in a derived type while preserving all the properties from the parent type. Redirection is established by creating a property of type GParamSpecOverride. See g_object_override_property() for an example of the use of this capability.

pspec : | a GParamSpec
Returns : | paramspec to which requests on this paramspec should be redirected, or NULL if none.

Since 2.4

g_param_spec_internal ()

gpointer            g_param_spec_internal               (GType param_type,
                                                         const gchar *name,
                                                         const gchar *nick,
                                                         const gchar *blurb,
                                                         GParamFlags flags);

Creates a new GParamSpec instance.

A property name consists of segments consisting of ASCII letters and digits, separated by either the '-' or '_' character. The first character of a property name must be a letter. Names which violate these rules lead to undefined behaviour.

When creating and looking up a GParamSpec, either separator can be used, but they cannot be mixed. Using '-' is considerably more efficient and in fact required when using property names as detail strings for signals.

param_type : | the GType for the property; must be derived from G_TYPE_PARAM
name : | the canonical name of the property
nick : | the nickname of the property
blurb : | a short description of the property
flags : | a combination of GParamFlags
Returns : | a newly allocated GParamSpec instance

GParamSpecTypeInfo

typedef struct {
  /* type system portion */
  guint16         instance_size;                               /* obligatory */
  guint16         n_preallocs;                                 /* optional */
  void		(*instance_init)	(GParamSpec   *pspec); /* optional */

  /* class portion */
  GType           value_type;				       /* obligatory */
  void          (*finalize)             (GParamSpec   *pspec); /* optional */
  void          (*value_set_default)    (GParamSpec   *pspec,  /* recommended */
                     GValue       *value);
  gboolean      (*value_validate)       (GParamSpec   *pspec,  /* optional */
                     GValue       *value);
  gint          (*values_cmp)           (GParamSpec   *pspec,  /* recommended */
                     const GValue *value1,
                     const GValue *value2);
} GParamSpecTypeInfo;

This structure is used to provide the type system with the information required to initialize and destruct (finalize) a parameter's class and instances thereof. The initialized structure is passed to the g_param_type_register_static() The type system will perform a deep copy of this structure, so it's memory does not need to be persistent across invocation of g_param_type_register_static().

guint16 instance_size; | Size of the instance (object) structure.
guint16 n_preallocs; | Prior to GLib 2.10, it specified the number of pre-allocated (cached) instances to reserve memory for (0 indicates no caching). Since GLib 2.10, it is ignored, since instances are allocated with the slice allocator now.
instance_init () | Location of the instance initialization function (optional).
GType value_type; | The GType of values conforming to this GParamSpec
finalize () | The instance finalization function (optional).
value_set_default () | Resets a value to the default value for pspec (recommended, the default is g_value_reset()), see g_param_value_set_default().
value_validate () | Ensures that the contents of value comply with the specifications set out by pspec (optional), see g_param_value_set_validate().
values_cmp () | Compares value1 with value2 according to pspec (recommended, the default is memcmp()), see g_param_values_cmp().

g_param_type_register_static ()

GType               g_param_type_register_static        (const gchar *name,
                                                         const GParamSpecTypeInfo *pspec_info);

Registers name as the name of a new static type derived from G_TYPE_PARAM. The type system uses the information contained in the GParamSpecTypeInfo structure pointed to by info to manage the GParamSpec type and its instances.

name : | 0-terminated string used as the name of the new GParamSpec type.
pspec_info : | The GParamSpecTypeInfo for this GParamSpec type.
Returns : | The new type identifier.

GParamSpecPool

typedef struct _GParamSpecPool GParamSpecPool;

A GParamSpecPool maintains a collection of GParamSpecs which can be quickly accessed by owner and name. The implementation of the GObject property system uses such a pool to store the GParamSpecs of the properties all object types.

g_param_spec_pool_new ()

GParamSpecPool*     g_param_spec_pool_new               (gboolean type_prefixing);

Creates a new GParamSpecPool.

If type_prefixing is TRUE, lookups in the newly created pool will allow to specify the owner as a colon-separated prefix of the property name, like "GtkContainer:border-width". This feature is deprecated, so you should always set type_prefixing to FALSE.

type_prefixing : | Whether the pool will support type-prefixed property names.
Returns : | a newly allocated GParamSpecPool.

g_param_spec_pool_insert ()

void                g_param_spec_pool_insert            (GParamSpecPool *pool,
                                                         GParamSpec *pspec,
                                                         GType owner_type);

Inserts a GParamSpec in the pool.

pool : | a GParamSpecPool.
pspec : | the GParamSpec to insert
owner_type : | a GType identifying the owner of pspec

g_param_spec_pool_remove ()

void                g_param_spec_pool_remove            (GParamSpecPool *pool,
                                                         GParamSpec *pspec);

Removes a GParamSpec from the pool.

pool : | a GParamSpecPool
pspec : | the GParamSpec to remove

g_param_spec_pool_lookup ()

GParamSpec*         g_param_spec_pool_lookup            (GParamSpecPool *pool,
                                                         const gchar *param_name,
                                                         GType owner_type,
                                                         gboolean walk_ancestors);

Looks up a GParamSpec in the pool.

pool : | a GParamSpecPool
param_name : | the name to look for
owner_type : | the owner to look for
walk_ancestors : | If TRUE, also try to find a GParamSpec with param_name owned by an ancestor of owner_type.
Returns : | The found GParamSpec, or NULL if no matching GParamSpec was found.

g_param_spec_pool_list ()

GParamSpec**        g_param_spec_pool_list              (GParamSpecPool *pool,
                                                         GType owner_type,
                                                         guint *n_pspecs_p);

Gets an array of all GParamSpecs owned by owner_type in the pool.

pool : | a GParamSpecPool
owner_type : | the owner to look for
n_pspecs_p : | return location for the length of the returned array
Returns : | a newly allocated array containing pointers to all GParamSpecs owned by owner_type in the pool

g_param_spec_pool_list_owned ()

GList*              g_param_spec_pool_list_owned        (GParamSpecPool *pool,
                                                         GType owner_type);

Gets an GList of all GParamSpecs owned by owner_type in the pool.

pool : | a GParamSpecPool
owner_type : | the owner to look for
Returns : | a GList of all GParamSpecs owned by owner_type in the poolGParamSpecs.

See Also

g_object_class_install_property(), g_object_set(), g_object_get(), g_object_set_property(), g_object_get_property(), g_value_register_transform_func()


Object memory management

The memory-management API for GObjects is a bit complicated but the idea behind it is pretty simple: the goal is to provide a flexible model based on reference counting which can be integrated in applications which use or require different memory management models (such as garbage collection, aso...). The methods which are used to manipulate this reference count are described below.

/*
  Refcounting
*/
gpointer    g_object_ref                      (gpointer        object);
void        g_object_unref                    (gpointer        object);

/*
  Weak References
*/
typedef void (*GWeakNotify)		(gpointer      data,
                     GObject      *where_the_object_was);
void	    g_object_weak_ref		      (GObject	      *object,
                           GWeakNotify     notify,
                           gpointer	       data);
void	    g_object_weak_unref		      (GObject	      *object,
                           GWeakNotify     notify,
                           gpointer	       data);
void        g_object_add_weak_pointer         (GObject        *object,
                                               gpointer       *weak_pointer_location);
void        g_object_remove_weak_pointer      (GObject        *object,
                                               gpointer       *weak_pointer_location);
/*
  Cycle handling
*/
void        g_object_run_dispose	      (GObject	      *object);

Reference count

The functions g_object_ref/g_object_unref respectively increase and decrease the reference count.These functions are thread-safe as of GLib 2.8. The reference count is, unsurprisingly, initialized to one by g_object_new which means that the caller is currenly the sole owner of the newly-created reference. When the reference count reaches zero, that is, when g_object_unref is called by the last client holding a reference to the object, the dispose and the finalize class methods are invoked.

Finally, after finalize is invoked, g_type_free_instance is called to free the object instance. Depending on the memory allocation policy decided when the type was registered (through one of the g_type_register_* functions), the object's instance memory will be freed or returned to the object pool for this type. Once the object has been freed, if it was the last instance of the type, the type's class will be destroyed as described in the section called “Instantiable classed types: objects” and the section called “Non-instantiable classed types: Interfaces.”.

The table below summarizes the destruction process of a GObject:

Table 5. g_object_unref

Invocation time | Function Invoked | Function's parameters | Remark
Last call to g_object_unref for an instance of target type | target type's dispose class function | GObject instance | When dispose ends, the object should not hold any reference to any other member object. The object is also expected to be able to answer client method invocations (with possibly an error code but no memory violation) until finalize is executed. dispose can be executed more than once. dispose should chain up to its parent implementation just before returning to the caller.
Last call to g_object_unref for an instance of target type | target type's finalize class function | GObject instance | Finalize is expected to complete the destruction process initiated by dispose. It should complete the object's destruction. finalize will be executed only once. finalize should chain up to its parent implementation just before returning to the caller. The reason why the destruction process is split is two different phases is explained in the section called “Reference counts and cycles”.
Last call to g_object_unref for the last instance of target type | interface' interface_finalize function | On interface' vtable | Never used in practice. Unlikely you will need it.
Last call to g_object_unreffor the last instance of target type | interface' base_finalize function | On interface' vtable | Never used in practice. Unlikely you will need it.
Last call to g_object_unref for the last instance of target type | target type's class_finalize function | On target type's class structure | Never used in practice. Unlikely you will need it.
Last call to g_object_unref for the last instance of target type | type's base_finalize function | On the inheritance tree of classes from fundamental type to target type. base_init is invoked once for each class structure. | Never used in practice. Unlikely you will need it.

Weak References

Weak References are used to monitor object finalization: g_object_weak_ref adds a monitoring callback which does not hold a reference to the object but which is invoked when the object runs its dispose method. As such, each weak ref can be invoked more than once upon object finalization (since dispose can run more than once during object finalization).

g_object_weak_unref can be used to remove a monitoring callback from the object.

Weak References are also used to implement g_object_add_weak_pointer and g_object_remove_weak_pointer. These functions add a weak reference to the object they are applied to which makes sure to nullify the pointer given by the user when object is finalized.

Reference counts and cycles

Note: the following section was inspired by James Henstridge. I guess this means that all praise and all curses will be directly forwarded to him.

GObject's memory management model was designed to be easily integrated in existing code using garbage collection. This is why the destruction process is split in two phases: the first phase, executed in the dispose handler is supposed to release all references to other member objects. The second phase, executed by the finalize handler is supposed to complete the object's destruction process. Object methods should be able to run without program error (that is, without segfault :) in-between the two phases.

This two-step destruction process is very useful to break reference counting cycles. While the detection of the cycles is up to the external code, once the cycles have been detected, the external code can invoke g_object_dispose which will indeed break any existing cycles since it will run the dispose handler associated to the object and thus release all references to other objects.

Attentive readers might now have understood one of the rules about the dispose handler we stated a bit sooner: the dispose handler can be invoked multiple times. Let's say we have a reference count cycle: object A references B which itself references object A. Let's say we have detected the cycle and we want to destroy the two objects. One way to do this would be to invoke g_object_dispose on one of the objects.

If object A releases all its references to all objects, this means it releases its reference to object B. If object B was not owned by anyone else, this is its last reference count which means this last unref runs B's dispose handler which, in turn, releases B's reference on object A. If this is A's last reference count, this last unref runs A's dispose handler which is running for the second time before A's finalize handler is invoked !

The above example, which might seem a bit contrived can really happen if your GObject's are being handled by language bindings. I would thus suggest the rules stated above for object destruction are closely followed. Otherwise, Bad Bad Things will happen.


Object properties

One of GObject's nice features is its generic get/set mechanism for object properties. When an object is instanciated, the object's class_init handler should be used to register the object's properties with g_object_class_install_property (implemented in gobject.c).

The best way to understand how object properties work is by looking at a real example on how it is used:

/************************************************/
/* Implementation                               */
/************************************************/

enum {
  MAMAN_BAR_CONSTRUCT_NAME = 1,
  MAMAN_BAR_PAPA_NUMBER,
};

static void
maman_bar_instance_init (GTypeInstance   *instance,
                         gpointer         g_class)
{
  MamanBar *self = (MamanBar *)instance;
}

static void
maman_bar_set_property (GObject      *object,
                        guint         property_id,
                        const GValue *value,
                        GParamSpec   *pspec)
{
  MamanBar *self = (MamanBar *) object;

  switch (property_id) {
  case MAMAN_BAR_CONSTRUCT_NAME: {
    g_free (self->priv->name);
    self->priv->name = g_value_dup_string (value);
    g_print ("maman: %s\n",self->priv->name);
  }
    break;
  case MAMAN_BAR_PAPA_NUMBER: {
    self->priv->papa_number = g_value_get_uchar (value);
    g_print ("papa: %u\n",self->priv->papa_number);
  }
    break;
  default:
    /* We don't have any other property... */
    G_OBJECT_WARN_INVALID_PROPERTY_ID(object,property_id,pspec);
    break;
  }
}

static void
maman_bar_get_property (GObject      *object,
                        guint         property_id,
                        GValue       *value,
                        GParamSpec   *pspec)
{
  MamanBar *self = (MamanBar *) object;

  switch (property_id) {
  case MAMAN_BAR_CONSTRUCT_NAME: {
    g_value_set_string (value, self->priv->name);
  }
    break;
  case MAMAN_BAR_PAPA_NUMBER: {
    g_value_set_uchar (value, self->priv->papa_number);
  }
    break;
  default:
    /* We don't have any other property... */
    G_OBJECT_WARN_INVALID_PROPERTY_ID(object,property_id,pspec);
    break;
  }
}

static void
maman_bar_class_init (gpointer g_class,
                      gpointer g_class_data)
{
  GObjectClass *gobject_class = G_OBJECT_CLASS (g_class);
  MamanBarClass *klass = MAMAN_BAR_CLASS (g_class);
  GParamSpec *pspec;

  gobject_class->set_property = maman_bar_set_property;
  gobject_class->get_property = maman_bar_get_property;

  pspec = g_param_spec_string ("maman-name",
                               "Maman construct prop",
                               "Set maman's name",
                               "no-name-set" /* default value */,
                               G_PARAM_CONSTRUCT_ONLY | G_PARAM_READWRITE);
  g_object_class_install_property (gobject_class,
                                   MAMAN_BAR_CONSTRUCT_NAME,
                                   pspec);

  pspec = g_param_spec_uchar ("papa-number",
                              "Number of current Papa",
                              "Set/Get papa's number",
                              0  /* minimum value */,
                              10 /* maximum value */,
                              2  /* default value */,
                              G_PARAM_READWRITE);
  g_object_class_install_property (gobject_class,
                                   MAMAN_BAR_PAPA_NUMBER,
                                   pspec);
}

/************************************************/
/* Use                                          */
/************************************************/

GObject *bar;
GValue val = {0,};
bar = g_object_new (MAMAN_TYPE_SUBBAR, NULL);
g_value_init (&val, G_TYPE_CHAR);
g_value_set_char (&val, 11);
g_object_set_property (G_OBJECT (bar), "papa-number", &val);

The client code just above looks simple but a lot of things happen under the hood:

g_object_set_property first ensures a property with this name was registered in bar's class_init handler. If so, it calls object_set_property which first walks the class hierarchy, from bottom, most derived type, to top, fundamental type to find the class which registered that property. It then tries to convert the user-provided GValue into a GValue whose type if that of the associated property.

If the user provides a signed char GValue, as is shown here, and if the object's property was registered as an unsigned int, g_value_transform will try to transform the input signed char into an unsigned int. Of course, the success of the transformation depends on the availability of the required transform function. In practice, there will almost always be a transformation [5] which matches and conversion will be caried out if needed.

After transformation, the GValue is validated by g_param_value_validate which makes sure the user's data stored in the GValue matches the characteristics specified by the property's GParamSpec. Here, the GParamSpec we provided in class_init has a validation function which makes sure that the GValue contains a value which respects the minimum and maximum bounds of the GParamSpec. In the example above, the client's GValue does not respect these constraints (it is set to 11, while the maximum is 10). As such, the g_object_set_property function will return with an error.

If the user's GValue had been set to a valid value, g_object_set_property would have proceeded with calling the object's set_property class method. Here, since our implementation of Foo did override this method, the code path would jump to foo_set_property after having retrieved from the GParamSpec the param_id [6] which had been stored by g_object_class_install_property.

Once the property has been set by the object's set_property class method, the code path returns to g_object_set_property which calls g_object_notify_queue_thaw. This function makes sure that the "notify" signal is emitted on the object's instance with the changed property as parameter unless notifications were frozen by g_object_freeze_notify.

g_object_thaw_notify can be used to re-enable notification of property modifications through the "notify" signal. It is important to remember that even if properties are changed while property change notification is frozen, the "notify" signal will be emitted once for each of these changed properties as soon as the property change notification is thawn: no property change is lost for the "notify" signal. Signal can only be delayed by the notification freezing mechanism.

Accessing multiple properties at once

It is interesting to note that the g_object_set and g_object_set_valist (vararg version) functions can be used to set multiple properties at once. The client code shown above can then be re-written as:

MamanBar *foo;
foo = /* */;
g_object_set (G_OBJECT (foo),
              "papa-number", 2,
              "maman-name", "test",
              NULL);

The code above will trigger one notify signal emission for each property modified.

Of course, the _get versions are also available: g_object_get and g_object_get_valist (vararg version) can be used to get numerous properties at once.

Really attentive readers now understand how g_object_new, g_object_newv and g_object_new_valist work: they parse the user-provided variable number of parameters and invoke g_object_set on each pair of parameters only after the object has been successfully constructed. Of course, the "notify" signal will be emitted for each property set.

[5] Its behaviour might not be what you expect but it is up to you to actually avoid relying on these transformations.

[6] It should be noted that the param_id used here need only to uniquely identify each GParamSpec within the FooClass such that the switch used in the set and get methods actually works. Of course, this locally-unique integer is purely an optimization: it would have been possible to use a set of if (strcmp (a, b) == 0) {} else if (strcmp (a, b) == 0) {} statements.


gobject-query

gobject-query — display a tree of types

Synopsis

gobject-query froots [options...]

gobject-query tree [options...]

Description

gobject-query is a small utility that draws a tree of types.

Invocation

gobject-query takes a mandatory argument that specifies whether it should iterate over the fundamental types or print a type tree.

Options

froots | iterate over fundamental roots
tree | print type tree
-r type | specify the root type
-n | don't descend type tree
-b string | specify indent string
-i string | specify incremental indent string
-s number | specify line spacing
-h, --help | Print brief help and exit.
-v, --version | Print version and exit.


Signals

Signals — A means for customization of object behaviour and a general purpose notification mechanism

Synopsis

#include <glib-object.h>

                    GSignalInvocationHint;
gboolean            (*GSignalAccumulator)               (GSignalInvocationHint *ihint,
                                                         GValue *return_accu,
                                                         const GValue *handler_return,
                                                         gpointer data);
typedef             GSignalCMarshaller;
gboolean            (*GSignalEmissionHook)              (GSignalInvocationHint *ihint,
                                                         guint n_param_values,
                                                         const GValue *param_values,
                                                         gpointer data);
enum                GSignalFlags;
enum                GSignalMatchType;
                    GSignalQuery;
#define             G_SIGNAL_TYPE_STATIC_SCOPE
#define             G_SIGNAL_MATCH_MASK
#define             G_SIGNAL_FLAGS_MASK
guint               g_signal_new                        (const gchar *signal_name,
                                                         GType itype,
                                                         GSignalFlags signal_flags,
                                                         guint class_offset,
                                                         GSignalAccumulator accumulator,
                                                         gpointer accu_data,
                                                         GSignalCMarshaller c_marshaller,
                                                         GType return_type,
                                                         guint n_params,
                                                         ...);
guint               g_signal_newv                       (const gchar *signal_name,
                                                         GType itype,
                                                         GSignalFlags signal_flags,
                                                         GClosure *class_closure,
                                                         GSignalAccumulator accumulator,
                                                         gpointer accu_data,
                                                         GSignalCMarshaller c_marshaller,
                                                         GType return_type,
                                                         guint n_params,
                                                         GType *param_types);
guint               g_signal_new_valist                 (const gchar *signal_name,
                                                         GType itype,
                                                         GSignalFlags signal_flags,
                                                         GClosure *class_closure,
                                                         GSignalAccumulator accumulator,
                                                         gpointer accu_data,
                                                         GSignalCMarshaller c_marshaller,
                                                         GType return_type,
                                                         guint n_params,
                                                         va_list args);
void                g_signal_query                      (guint signal_id,
                                                         GSignalQuery *query);
guint               g_signal_lookup                     (const gchar *name,
                                                         GType itype);
const gchar*        g_signal_name                       (guint signal_id);
guint*              g_signal_list_ids                   (GType itype,
                                                         guint *n_ids);
void                g_signal_emit                       (gpointer instance,
                                                         guint signal_id,
                                                         GQuark detail,
                                                         ...);
void                g_signal_emit_by_name               (gpointer instance,
                                                         const gchar *detailed_signal,
                                                         ...);
void                g_signal_emitv                      (const GValue *instance_and_params,
                                                         guint signal_id,
                                                         GQuark detail,
                                                         GValue *return_value);
void                g_signal_emit_valist                (gpointer instance,
                                                         guint signal_id,
                                                         GQuark detail,
                                                         va_list var_args);
#define             g_signal_connect                    (instance, detailed_signal, c_handler, data)
#define             g_signal_connect_after              (instance, detailed_signal, c_handler, data)
#define             g_signal_connect_swapped            (instance, detailed_signal, c_handler, data)
gulong              g_signal_connect_object             (gpointer instance,
                                                         const gchar *detailed_signal,
                                                         GCallback c_handler,
                                                         gpointer gobject,
                                                         GConnectFlags connect_flags);
enum                GConnectFlags;
gulong              g_signal_connect_data               (gpointer instance,
                                                         const gchar *detailed_signal,
                                                         GCallback c_handler,
                                                         gpointer data,
                                                         GClosureNotify destroy_data,
                                                         GConnectFlags connect_flags);
gulong              g_signal_connect_closure            (gpointer instance,
                                                         const gchar *detailed_signal,
                                                         GClosure *closure,
                                                         gboolean after);
gulong              g_signal_connect_closure_by_id      (gpointer instance,
                                                         guint signal_id,
                                                         GQuark detail,
                                                         GClosure *closure,
                                                         gboolean after);
void                g_signal_handler_block              (gpointer instance,
                                                         gulong handler_id);
void                g_signal_handler_unblock            (gpointer instance,
                                                         gulong handler_id);
void                g_signal_handler_disconnect         (gpointer instance,
                                                         gulong handler_id);
gulong              g_signal_handler_find               (gpointer instance,
                                                         GSignalMatchType mask,
                                                         guint signal_id,
                                                         GQuark detail,
                                                         GClosure *closure,
                                                         gpointer func,
                                                         gpointer data);
guint               g_signal_handlers_block_matched     (gpointer instance,
                                                         GSignalMatchType mask,
                                                         guint signal_id,
                                                         GQuark detail,
                                                         GClosure *closure,
                                                         gpointer func,
                                                         gpointer data);
guint               g_signal_handlers_unblock_matched   (gpointer instance,
                                                         GSignalMatchType mask,
                                                         guint signal_id,
                                                         GQuark detail,
                                                         GClosure *closure,
                                                         gpointer func,
                                                         gpointer data);
guint               g_signal_handlers_disconnect_matched
                                                        (gpointer instance,
                                                         GSignalMatchType mask,
                                                         guint signal_id,
                                                         GQuark detail,
                                                         GClosure *closure,
                                                         gpointer func,
                                                         gpointer data);
gboolean            g_signal_handler_is_connected       (gpointer instance,
                                                         gulong handler_id);
#define             g_signal_handlers_block_by_func     (instance, func, data)
#define             g_signal_handlers_unblock_by_func   (instance, func, data)
#define             g_signal_handlers_disconnect_by_func(instance, func, data)
gboolean            g_signal_has_handler_pending        (gpointer instance,
                                                         guint signal_id,
                                                         GQuark detail,
                                                         gboolean may_be_blocked);
void                g_signal_stop_emission              (gpointer instance,
                                                         guint signal_id,
                                                         GQuark detail);
void                g_signal_stop_emission_by_name      (gpointer instance,
                                                         const gchar *detailed_signal);
void                g_signal_override_class_closure     (guint signal_id,
                                                         GType instance_type,
                                                         GClosure *class_closure);
void                g_signal_chain_from_overridden      (const GValue *instance_and_params,
                                                         GValue *return_value);
gulong              g_signal_add_emission_hook          (guint signal_id,
                                                         GQuark detail,
                                                         GSignalEmissionHook hook_func,
                                                         gpointer hook_data,
                                                         GDestroyNotify data_destroy);
void                g_signal_remove_emission_hook       (guint signal_id,
                                                         gulong hook_id);
gboolean            g_signal_parse_name                 (const gchar *detailed_signal,
                                                         GType itype,
                                                         guint *signal_id_p,
                                                         GQuark *detail_p,
                                                         gboolean force_detail_quark);
GSignalInvocationHint* g_signal_get_invocation_hint     (gpointer instance);
GClosure*           g_signal_type_cclosure_new          (GType itype,
                                                         guint struct_offset);
gboolean            g_signal_accumulator_true_handled   (GSignalInvocationHint *ihint,
                                                         GValue *return_accu,
                                                         const GValue *handler_return,
                                                         gpointer dummy);

Description

The basic concept of the signal system is that of the emission of a signal. Signals are introduced per-type and are identified through strings. Signals introduced for a parent type are available in derived types as well, so basically they are a per-type facility that is inherited. A signal emission mainly involves invocation of a certain set of callbacks in precisely defined manner. There are two main categories of such callbacks, per-object [11] ones and user provided ones. The per-object callbacks are most often referred to as "object method handler" or "default (signal) handler", while user provided callbacks are usually just called "signal handler". The object method handler is provided at signal creation time (this most frequently happens at the end of an object class' creation), while user provided handlers are frequently connected and disconnected to/from a certain signal on certain object instances.

A signal emission consists of five stages, unless prematurely stopped:

1 - Invocation of the object method handler for G_SIGNAL_RUN_FIRST signals

2 - Invocation of normal user-provided signal handlers (after flag FALSE)

3 - Invocation of the object method handler for G_SIGNAL_RUN_LAST signals

4 - Invocation of user provided signal handlers, connected with an after flag of TRUE

5 - Invocation of the object method handler for G_SIGNAL_RUN_CLEANUP signals

The user-provided signal handlers are called in the order they were connected in. All handlers may prematurely stop a signal emission, and any number of handlers may be connected, disconnected, blocked or unblocked during a signal emission. There are certain criteria for skipping user handlers in stages 2 and 4 of a signal emission. First, user handlers may be blocked, blocked handlers are omitted during callback invocation, to return from the "blocked" state, a handler has to get unblocked exactly the same amount of times it has been blocked before. Second, upon emission of a G_SIGNAL_DETAILED signal, an additional "detail" argument passed in to g_signal_emit() has to match the detail argument of the signal handler currently subject to invocation. Specification of no detail argument for signal handlers (omission of the detail part of the signal specification upon connection) serves as a wildcard and matches any detail argument passed in to emission.

Details

GSignalInvocationHint

typedef struct {
  guint		signal_id;
  GQuark	detail;
  GSignalFlags	run_type;
} GSignalInvocationHint;

The GSignalInvocationHint structure is used to pass on additional information to callbacks during a signal emission.

guint signal_id; | The signal id of the signal invoking the callback
GQuark detail; | The detail passed on for this emission
GSignalFlags run_type; | The stage the signal emission is currently in, this field will contain one of G_SIGNAL_RUN_FIRST, G_SIGNAL_RUN_LAST or G_SIGNAL_RUN_CLEANUP.

GSignalAccumulator ()

gboolean            (*GSignalAccumulator)               (GSignalInvocationHint *ihint,
                                                         GValue *return_accu,
                                                         const GValue *handler_return,
                                                         gpointer data);

The signal accumulator is a special callback function that can be used to collect return values of the various callbacks that are called during a signal emission. The signal accumulator is specified at signal creation time, if it is left NULL, no accumulation of callback return values is performed. The return value of signal emissions is then the value returned by the last callback.

ihint : | Signal invocation hint, see GSignalInvocationHint.
return_accu : | Accumulator to collect callback return values in, this is the return value of the current signal emission.
handler_return : | A GValue holding the return value of the signal handler.
data : | Callback data that was specified when creating the signal.
Returns : | The accumulator function returns whether the signal emission should be aborted. Returning FALSE means to abort the current emission and TRUE is returned for continuation.

GSignalCMarshaller

typedef GClosureMarshal			 GSignalCMarshaller;

This is the signature of marshaller functions, required to marshall arrays of parameter values to signal emissions into C language callback invocations. It is merely an alias to GClosureMarshal since the GClosure mechanism takes over responsibility of actual function invocation for the signal system.

GSignalEmissionHook ()

gboolean            (*GSignalEmissionHook)              (GSignalInvocationHint *ihint,
                                                         guint n_param_values,
                                                         const GValue *param_values,
                                                         gpointer data);

A simple function pointer to get invoked when the signal is emitted. This allows you to tie a hook to the signal type, so that it will trap all emissions of that signal, from any object.

You may not attach these to signals created with the G_SIGNAL_NO_HOOKS flag.

ihint : | Signal invocation hint, see GSignalInvocationHint.
n_param_values : | the number of parameters to the function, including the instance on which the signal was emitted.
param_values : | the instance on which the signal was emitted, followed by the parameters of the emission.
data : | user data associated with the hook.
Returns : | whether it wants to stay connected. If it returns FALSE, the signal hook is disconnected (and destroyed).

enum GSignalFlags

typedef enum
{
  G_SIGNAL_RUN_FIRST	= 1 << 0,
  G_SIGNAL_RUN_LAST	= 1 << 1,
  G_SIGNAL_RUN_CLEANUP	= 1 << 2,
  G_SIGNAL_NO_RECURSE	= 1 << 3,
  G_SIGNAL_DETAILED	= 1 << 4,
  G_SIGNAL_ACTION	= 1 << 5,
  G_SIGNAL_NO_HOOKS	= 1 << 6
} GSignalFlags;

The signal flags are used to specify a signal's behaviour, the overall signal description outlines how especially the RUN flags control the stages of a signal emission.

G_SIGNAL_RUN_FIRST | Invoke the object method handler in the first emission stage.
G_SIGNAL_RUN_LAST | Invoke the object method handler in the third emission stage.
G_SIGNAL_RUN_CLEANUP | Invoke the object method handler in the last emission stage.
G_SIGNAL_NO_RECURSE | Signals being emitted for an object while currently being in emission for this very object will not be emitted recursively, but instead cause the first emission to be restarted.
G_SIGNAL_DETAILED | This signal supports "::detail" appendices to the signal name upon handler connections and emissions.
G_SIGNAL_ACTION | Action signals are signals that may freely be emitted on alive objects from user code via g_signal_emit() and friends, without the need of being embedded into extra code that performs pre or post emission adjustments on the object. They can also be thought of as object methods which can be called generically by third-party code.
G_SIGNAL_NO_HOOKS | No emissions hooks are supported for this signal.

enum GSignalMatchType

typedef enum
{
  G_SIGNAL_MATCH_ID	   = 1 << 0,
  G_SIGNAL_MATCH_DETAIL	   = 1 << 1,
  G_SIGNAL_MATCH_CLOSURE   = 1 << 2,
  G_SIGNAL_MATCH_FUNC	   = 1 << 3,
  G_SIGNAL_MATCH_DATA	   = 1 << 4,
  G_SIGNAL_MATCH_UNBLOCKED = 1 << 5
} GSignalMatchType;

The match types specify what g_signal_handlers_block_matched(), g_signal_handlers_unblock_matched() and g_signal_handlers_disconnect_matched() match signals by.

G_SIGNAL_MATCH_ID | The signal id must be equal.
G_SIGNAL_MATCH_DETAIL | The signal detail be equal.
G_SIGNAL_MATCH_CLOSURE | The closure must be the same.
G_SIGNAL_MATCH_FUNC | The C closure callback must be the same.
G_SIGNAL_MATCH_DATA | The closure data must be the same.
G_SIGNAL_MATCH_UNBLOCKED | Only unblocked signals may matched.

GSignalQuery

typedef struct {
  guint		signal_id;
  const gchar  *signal_name;
  GType		itype;
  GSignalFlags	signal_flags;
  GType		return_type; /* mangled with G_SIGNAL_TYPE_STATIC_SCOPE flag */
  guint		n_params;
  const GType  *param_types; /* mangled with G_SIGNAL_TYPE_STATIC_SCOPE flag */
} GSignalQuery;

A structure holding in-depth information for a specific signal. It is filled in by the g_signal_query() function.

guint signal_id; | The signal id of the signal being queried, or 0 if the signal to be queried was unknown.
const gchar *signal_name; | The signal name.
GType itype; | The interface/instance type that this signal can be emitted for.
GSignalFlags signal_flags; | The signal flags as passed in to g_signal_new().
GType return_type; | The return type for user callbacks.
guint n_params; | The number of parameters that user callbacks take.
const GType *param_types; The individual parameter types for user callbacks, note that the effective callback signature is:
@return_type callback (gpointer     data1,
                      [param_types param_names,]
                       gpointer     data2);

G_SIGNAL_TYPE_STATIC_SCOPE

#define	G_SIGNAL_TYPE_STATIC_SCOPE (G_TYPE_FLAG_RESERVED_ID_BIT)

This macro flags signal argument types for which the signal system may assume that instances thereof remain persistent across all signal emissions they are used in. This is only useful for non ref-counted, value-copy types.

To flag a signal argument in this way, add | G_SIGNAL_TYPE_STATIC_SCOPE to the corresponding argument of g_signal_new().

    g_signal_new ("size_request",
          G_TYPE_FROM_CLASS (gobject_class),
          G_SIGNAL_RUN_FIRST,
          G_STRUCT_OFFSET (GtkWidgetClass, size_request),
          NULL, NULL,
          _gtk_marshal_VOID__BOXED,
          G_TYPE_NONE, 1,
          GTK_TYPE_REQUISITION | G_SIGNAL_TYPE_STATIC_SCOPE);

G_SIGNAL_MATCH_MASK

#define G_SIGNAL_MATCH_MASK  0x3f

A mask for all GSignalMatchType bits.

G_SIGNAL_FLAGS_MASK

#define G_SIGNAL_FLAGS_MASK  0x7f

A mask for all GSignalFlags bits.

g_signal_new ()

guint               g_signal_new                        (const gchar *signal_name,
                                                         GType itype,
                                                         GSignalFlags signal_flags,
                                                         guint class_offset,
                                                         GSignalAccumulator accumulator,
                                                         gpointer accu_data,
                                                         GSignalCMarshaller c_marshaller,
                                                         GType return_type,
                                                         guint n_params,
                                                         ...);

Creates a new signal. (This is usually done in the class initializer.)

A signal name consists of segments consisting of ASCII letters and digits, separated by either the '-' or '_' character. The first character of a signal name must be a letter. Names which violate these rules lead to undefined behaviour of the GSignal system.

When registering a signal and looking up a signal, either separator can be used, but they cannot be mixed.

signal_name : | the name for the signal
itype : | the type this signal pertains to. It will also pertain to types which are derived from this type.
signal_flags : | a combination of GSignalFlags specifying detail of when the default handler is to be invoked. You should at least specify G_SIGNAL_RUN_FIRST or G_SIGNAL_RUN_LAST.
class_offset : | The offset of the function pointer in the class structure for this type. Used to invoke a class method generically. Pass 0 to not associate a class method with this signal.
accumulator : | the accumulator for this signal; may be NULL.
accu_data : | user data for the accumulator.
c_marshaller : | the function to translate arrays of parameter values to signal emissions into C language callback invocations.
return_type : | the type of return value, or G_TYPE_NONE for a signal without a return value.
n_params : | the number of parameter types to follow.
... : | a list of types, one for each parameter.
Returns : | the signal id

g_signal_newv ()

guint               g_signal_newv                       (const gchar *signal_name,
                                                         GType itype,
                                                         GSignalFlags signal_flags,
                                                         GClosure *class_closure,
                                                         GSignalAccumulator accumulator,
                                                         gpointer accu_data,
                                                         GSignalCMarshaller c_marshaller,
                                                         GType return_type,
                                                         guint n_params,
                                                         GType *param_types);

Creates a new signal. (This is usually done in the class initializer.)

See g_signal_new() for details on allowed signal names.

signal_name : | the name for the signal
itype : | the type this signal pertains to. It will also pertain to types which are derived from this type.
signal_flags : | a combination of GSignalFlags specifying detail of when the default handler is to be invoked. You should at least specify G_SIGNAL_RUN_FIRST or G_SIGNAL_RUN_LAST.
class_closure : | The closure to invoke on signal emission; may be NULL.
accumulator : | the accumulator for this signal; may be NULL.
accu_data : | user data for the accumulator.
c_marshaller : | the function to translate arrays of parameter values to signal emissions into C language callback invocations.
return_type : | the type of return value, or G_TYPE_NONE for a signal without a return value.
n_params : | the length of param_types.
param_types : | an array types, one for each parameter.
Returns : | the signal id

g_signal_new_valist ()

guint               g_signal_new_valist                 (const gchar *signal_name,
                                                         GType itype,
                                                         GSignalFlags signal_flags,
                                                         GClosure *class_closure,
                                                         GSignalAccumulator accumulator,
                                                         gpointer accu_data,
                                                         GSignalCMarshaller c_marshaller,
                                                         GType return_type,
                                                         guint n_params,
                                                         va_list args);

Creates a new signal. (This is usually done in the class initializer.)

See g_signal_new() for details on allowed signal names.

signal_name : | the name for the signal
itype : | the type this signal pertains to. It will also pertain to types which are derived from this type.
signal_flags : | a combination of GSignalFlags specifying detail of when the default handler is to be invoked. You should at least specify G_SIGNAL_RUN_FIRST or G_SIGNAL_RUN_LAST.
class_closure : | The closure to invoke on signal emission; may be NULL.
accumulator : | the accumulator for this signal; may be NULL.
accu_data : | user data for the accumulator.
c_marshaller : | the function to translate arrays of parameter values to signal emissions into C language callback invocations.
return_type : | the type of return value, or G_TYPE_NONE for a signal without a return value.
n_params : | the number of parameter types in args.
args : | va_list of GType, one for each parameter.
Returns : | the signal id

g_signal_query ()

void                g_signal_query                      (guint signal_id,
                                                         GSignalQuery *query);

Queries the signal system for in-depth information about a specific signal. This function will fill in a user-provided structure to hold signal-specific information. If an invalid signal id is passed in, the signal_id member of the GSignalQuery is 0. All members filled into the GSignalQuery structure should be considered constant and have to be left untouched.

signal_id : | The signal id of the signal to query information for.
query : | A user provided structure that is filled in with constant values upon success.

g_signal_lookup ()

guint               g_signal_lookup                     (const gchar *name,
                                                         GType itype);

Given the name of the signal and the type of object it connects to, gets the signal's identifying integer. Emitting the signal by number is somewhat faster than using the name each time.

Also tries the ancestors of the given type.

See g_signal_new() for details on allowed signal names.

name : | the signal's name.
itype : | the type that the signal operates on.
Returns : | the signal's identifying number, or 0 if no signal was found.

g_signal_name ()

const gchar*        g_signal_name                       (guint signal_id);

Given the signal's identifier, finds its name.

Two different signals may have the same name, if they have differing types.

signal_id : | the signal's identifying number.
Returns : | the signal name, or NULL if the signal number was invalid.

g_signal_list_ids ()

guint*              g_signal_list_ids                   (GType itype,
                                                         guint *n_ids);

Lists the signals by id that a certain instance or interface type created. Further information about the signals can be acquired through g_signal_query().

itype : | Instance or interface type.
n_ids : | Location to store the number of signal ids for itype.
Returns : | Newly allocated array of signal IDs.

g_signal_emit ()

void                g_signal_emit                       (gpointer instance,
                                                         guint signal_id,
                                                         GQuark detail,
                                                         ...);

Emits a signal.

Note that g_signal_emit() resets the return value to the default if no handlers are connected, in contrast to g_signal_emitv().

instance : | the instance the signal is being emitted on.
signal_id : | the signal id
detail : | the detail
... : | parameters to be passed to the signal, followed by a location for the return value. If the return type of the signal is G_TYPE_NONE, the return value location can be omitted.

g_signal_emit_by_name ()

void                g_signal_emit_by_name               (gpointer instance,
                                                         const gchar *detailed_signal,
                                                         ...);

Emits a signal.

Note that g_signal_emit_by_name() resets the return value to the default if no handlers are connected, in contrast to g_signal_emitv().

instance : | the instance the signal is being emitted on.
detailed_signal : | a string of the form "signal-name::detail".
... : | parameters to be passed to the signal, followed by a location for the return value. If the return type of the signal is G_TYPE_NONE, the return value location can be omitted.

g_signal_emitv ()

void                g_signal_emitv                      (const GValue *instance_and_params,
                                                         guint signal_id,
                                                         GQuark detail,
                                                         GValue *return_value);

Emits a signal.

Note that g_signal_emitv() doesn't change return_value if no handlers are connected, in contrast to g_signal_emit() and g_signal_emit_valist().

instance_and_params : | argument list for the signal emission. The first element in the array is a GValue for the instance the signal is being emitted on. The rest are any arguments to be passed to the signal.
signal_id : | the signal id
detail : | the detail
return_value : | Location to store the return value of the signal emission.

g_signal_emit_valist ()

void                g_signal_emit_valist                (gpointer instance,
                                                         guint signal_id,
                                                         GQuark detail,
                                                         va_list var_args);

Emits a signal.

Note that g_signal_emit_valist() resets the return value to the default if no handlers are connected, in contrast to g_signal_emitv().

instance : | the instance the signal is being emitted on.
signal_id : | the signal id
detail : | the detail
var_args : | a list of parameters to be passed to the signal, followed by a location for the return value. If the return type of the signal is G_TYPE_NONE, the return value location can be omitted.

g_signal_connect()

#define             g_signal_connect(instance, detailed_signal, c_handler, data)

Connects a GCallback function to a signal for a particular object.

The handler will be called before the default handler of the signal.

instance : | the instance to connect to.
detailed_signal : | a string of the form "signal-name::detail".
c_handler : | the GCallback to connect.
data : | data to pass to c_handler calls.
Returns : | the handler id

g_signal_connect_after()

#define             g_signal_connect_after(instance, detailed_signal, c_handler, data)

Connects a GCallback function to a signal for a particular object.

The handler will be called after the default handler of the signal.

instance : | the instance to connect to.
detailed_signal : | a string of the form "signal-name::detail".
c_handler : | the GCallback to connect.
data : | data to pass to c_handler calls.
Returns : | the handler id

g_signal_connect_swapped()

#define             g_signal_connect_swapped(instance, detailed_signal, c_handler, data)

Connects a GCallback function to a signal for a particular object.

The instance on which the signal is emitted and data will be swapped when calling the handler.

instance : | the instance to connect to.
detailed_signal : | a string of the form "signal-name::detail".
c_handler : | the GCallback to connect.
data : | data to pass to c_handler calls.
Returns : | the handler id

g_signal_connect_object ()

gulong              g_signal_connect_object             (gpointer instance,
                                                         const gchar *detailed_signal,
                                                         GCallback c_handler,
                                                         gpointer gobject,
                                                         GConnectFlags connect_flags);

This is similar to g_signal_connect_data(), but uses a closure which ensures that the gobject stays alive during the call to c_handler by temporarily adding a reference count to gobject.

Note that there is a bug in GObject that makes this function much less useful than it might seem otherwise. Once gobject is disposed, the callback will no longer be called, but, the signal handler is not currently disconnected. If the instance is itself being freed at the same time than this doesn't matter, since the signal will automatically be removed, but if instance persists, then the signal handler will leak. You should not remove the signal yourself because in a future versions of GObject, the handler will automatically be disconnected.

It's possible to work around this problem in a way that will continue to work with future versions of GObject by checking that the signal handler is still connected before disconnected it:

 if (g_signal_handler_is_connected (instance, id))
   g_signal_handler_disconnect (instance, id);

instance : | the instance to connect to.
detailed_signal : | a string of the form "signal-name::detail".
c_handler : | the GCallback to connect.
gobject : | the object to pass as data to c_handler.
connect_flags : | a combination of GConnnectFlags.
Returns : | the handler id.

enum GConnectFlags

typedef enum
{
  G_CONNECT_AFTER	= 1 << 0,
  G_CONNECT_SWAPPED	= 1 << 1
} GConnectFlags;

The connection flags are used to specify the behaviour of a signal's connection.

G_CONNECT_AFTER | whether the handler should be called before or after the default handler of the signal.
G_CONNECT_SWAPPED | whether the instance and data should be swapped when calling the handler.

g_signal_connect_data ()

gulong              g_signal_connect_data               (gpointer instance,
                                                         const gchar *detailed_signal,
                                                         GCallback c_handler,
                                                         gpointer data,
                                                         GClosureNotify destroy_data,
                                                         GConnectFlags connect_flags);

Connects a GCallback function to a signal for a particular object. Similar to g_signal_connect(), but allows to provide a GDestroyNotify for the data which will be called when the signal handler is disconnected and no longer used. Specify connect_flags if you need ..._after() pr ..._swapped() variants of this function.

instance : | the instance to connect to.
detailed_signal : | a string of the form "signal-name::detail".
c_handler : | the GCallback to connect.
data : | data to pass to c_handler calls.
destroy_data : | a GDestroyNotify for data.
connect_flags : | a combination of GConnectFlags.
Returns : | the handler id

g_signal_connect_closure ()

gulong              g_signal_connect_closure            (gpointer instance,
                                                         const gchar *detailed_signal,
                                                         GClosure *closure,
                                                         gboolean after);

Connects a closure to a signal for a particular object.

instance : | the instance to connect to.
detailed_signal : | a string of the form "signal-name::detail".
closure : | the closure to connect.
after : | whether the handler should be called before or after the default handler of the signal.
Returns : | the handler id

g_signal_connect_closure_by_id ()

gulong              g_signal_connect_closure_by_id      (gpointer instance,
                                                         guint signal_id,
                                                         GQuark detail,
                                                         GClosure *closure,
                                                         gboolean after);

Connects a closure to a signal for a particular object.

instance : | the instance to connect to.
signal_id : | the id of the signal.
detail : | the detail.
closure : | the closure to connect.
after : | whether the handler should be called before or after the default handler of the signal.
Returns : | the handler id

g_signal_handler_block ()

void                g_signal_handler_block              (gpointer instance,
                                                         gulong handler_id);

Blocks a handler of an instance so it will not be called during any signal emissions unless it is unblocked again. Thus "blocking" a signal handler means to temporarily deactive it, a signal handler has to be unblocked exactly the same amount of times it has been blocked before to become active again.

The handler_id has to be a valid signal handler id, connected to a signal of instance.

instance : | The instance to block the signal handler of.
handler_id : | Handler id of the handler to be blocked.

g_signal_handler_unblock ()

void                g_signal_handler_unblock            (gpointer instance,
                                                         gulong handler_id);

Undoes the effect of a previous g_signal_handler_block() call. A blocked handler is skipped during signal emissions and will not be invoked, unblocking it (for exactly the amount of times it has been blocked before) reverts its "blocked" state, so the handler will be recognized by the signal system and is called upon future or currently ongoing signal emissions (since the order in which handlers are called during signal emissions is deterministic, whether the unblocked handler in question is called as part of a currently ongoing emission depends on how far that emission has proceeded yet).

The handler_id has to be a valid id of a signal handler that is connected to a signal of instance and is currently blocked.

instance : | The instance to unblock the signal handler of.
handler_id : | Handler id of the handler to be unblocked.

g_signal_handler_disconnect ()

void                g_signal_handler_disconnect         (gpointer instance,
                                                         gulong handler_id);

Disconnects a handler from an instance so it will not be called during any future or currently ongoing emissions of the signal it has been connected to. The handler_id becomes invalid and may be reused.

The handler_id has to be a valid signal handler id, connected to a signal of instance.

instance : | The instance to remove the signal handler from.
handler_id : | Handler id of the handler to be disconnected.

g_signal_handler_find ()

gulong              g_signal_handler_find               (gpointer instance,
                                                         GSignalMatchType mask,
                                                         guint signal_id,
                                                         GQuark detail,
                                                         GClosure *closure,
                                                         gpointer func,
                                                         gpointer data);

Finds the first signal handler that matches certain selection criteria. The criteria mask is passed as an OR-ed combination of GSignalMatchType flags, and the criteria values are passed as arguments. The match mask has to be non-0 for successful matches. If no handler was found, 0 is returned.

instance : | The instance owning the signal handler to be found.
mask : | Mask indicating which of signal_id, detail, closure, func and/or data the handler has to match.
signal_id : | Signal the handler has to be connected to.
detail : | Signal detail the handler has to be connected to.
closure : | The closure the handler will invoke.
func : | The C closure callback of the handler (useless for non-C closures).
data : | The closure data of the handler's closure.
Returns : | A valid non-0 signal handler id for a successful match.

g_signal_handlers_block_matched ()

guint               g_signal_handlers_block_matched     (gpointer instance,
                                                         GSignalMatchType mask,
                                                         guint signal_id,
                                                         GQuark detail,
                                                         GClosure *closure,
                                                         gpointer func,
                                                         gpointer data);

Blocks all handlers on an instance that match a certain selection criteria. The criteria mask is passed as an OR-ed combination of GSignalMatchType flags, and the criteria values are passed as arguments. Passing at least one of the G_SIGNAL_MATCH_CLOSURE, G_SIGNAL_MATCH_FUNC or G_SIGNAL_MATCH_DATA match flags is required for successful matches. If no handlers were found, 0 is returned, the number of blocked handlers otherwise.

instance : | The instance to block handlers from.
mask : | Mask indicating which of signal_id, detail, closure, func and/or data the handlers have to match.
signal_id : | Signal the handlers have to be connected to.
detail : | Signal detail the handlers have to be connected to.
closure : | The closure the handlers will invoke.
func : | The C closure callback of the handlers (useless for non-C closures).
data : | The closure data of the handlers' closures.
Returns : | The amount of handlers that got blocked.

g_signal_handlers_unblock_matched ()

guint               g_signal_handlers_unblock_matched   (gpointer instance,
                                                         GSignalMatchType mask,
                                                         guint signal_id,
                                                         GQuark detail,
                                                         GClosure *closure,
                                                         gpointer func,
                                                         gpointer data);

Unblocks all handlers on an instance that match a certain selection criteria. The criteria mask is passed as an OR-ed combination of GSignalMatchType flags, and the criteria values are passed as arguments. Passing at least one of the G_SIGNAL_MATCH_CLOSURE, G_SIGNAL_MATCH_FUNC or G_SIGNAL_MATCH_DATA match flags is required for successful matches. If no handlers were found, 0 is returned, the number of unblocked handlers otherwise. The match criteria should not apply to any handlers that are not currently blocked.

instance : | The instance to unblock handlers from.
mask : | Mask indicating which of signal_id, detail, closure, func and/or data the handlers have to match.
signal_id : | Signal the handlers have to be connected to.
detail : | Signal detail the handlers have to be connected to.
closure : | The closure the handlers will invoke.
func : | The C closure callback of the handlers (useless for non-C closures).
data : | The closure data of the handlers' closures.
Returns : | The amount of handlers that got unblocked.

g_signal_handlers_disconnect_matched ()

guint               g_signal_handlers_disconnect_matched
                                                        (gpointer instance,
                                                         GSignalMatchType mask,
                                                         guint signal_id,
                                                         GQuark detail,
                                                         GClosure *closure,
                                                         gpointer func,
                                                         gpointer data);

Disconnects all handlers on an instance that match a certain selection criteria. The criteria mask is passed as an OR-ed combination of GSignalMatchType flags, and the criteria values are passed as arguments. Passing at least one of the G_SIGNAL_MATCH_CLOSURE, G_SIGNAL_MATCH_FUNC or G_SIGNAL_MATCH_DATA match flags is required for successful matches. If no handlers were found, 0 is returned, the number of disconnected handlers otherwise.

instance : | The instance to remove handlers from.
mask : | Mask indicating which of signal_id, detail, closure, func and/or data the handlers have to match.
signal_id : | Signal the handlers have to be connected to.
detail : | Signal detail the handlers have to be connected to.
closure : | The closure the handlers will invoke.
func : | The C closure callback of the handlers (useless for non-C closures).
data : | The closure data of the handlers' closures.
Returns : | The amount of handlers that got disconnected.

g_signal_handler_is_connected ()

gboolean            g_signal_handler_is_connected       (gpointer instance,
                                                         gulong handler_id);

Returns whether handler_id is the id of a handler connected to instance.

instance : | The instance where a signal handler is sought.
handler_id : | the handler id.
Returns : | whether handler_id identifies a handler connected to instance.

g_signal_handlers_block_by_func()

#define             g_signal_handlers_block_by_func(instance, func, data)

Blocks all handlers on an instance that match func and data.

instance : | The instance to block handlers from.
func : | The C closure callback of the handlers (useless for non-C closures).
data : | The closure data of the handlers' closures.
Returns : | The number of handlers that got blocked.

g_signal_handlers_unblock_by_func()

#define             g_signal_handlers_unblock_by_func(instance, func, data)

Unblocks all handlers on an instance that match func and data.

instance : | The instance to unblock handlers from.
func : | The C closure callback of the handlers (useless for non-C closures).
data : | The closure data of the handlers' closures.
Returns : | The number of handlers that got unblocked.

g_signal_handlers_disconnect_by_func()

#define             g_signal_handlers_disconnect_by_func(instance, func, data)

Disconnects all handlers on an instance that match func and data.

instance : | The instance to remove handlers from.
func : | The C closure callback of the handlers (useless for non-C closures).
data : | The closure data of the handlers' closures.
Returns : | The number of handlers that got disconnected.

g_signal_has_handler_pending ()

gboolean            g_signal_has_handler_pending        (gpointer instance,
                                                         guint signal_id,
                                                         GQuark detail,
                                                         gboolean may_be_blocked);

Returns whether there are any handlers connected to instance for the given signal id and detail.

One example of when you might use this is when the arguments to the signal are difficult to compute. A class implementor may opt to not emit the signal if no one is attached anyway, thus saving the cost of building the arguments.

instance : | the object whose signal handlers are sought.
signal_id : | the signal id.
detail : | the detail.
may_be_blocked : | whether blocked handlers should count as match.
Returns : | TRUE if a handler is connected to the signal, FALSE otherwise.

g_signal_stop_emission ()

void                g_signal_stop_emission              (gpointer instance,
                                                         guint signal_id,
                                                         GQuark detail);

Stops a signal's current emission.

This will prevent the default method from running, if the signal was G_SIGNAL_RUN_LAST and you connected normally (i.e. without the "after" flag).

Prints a warning if used on a signal which isn't being emitted.

instance : | the object whose signal handlers you wish to stop.
signal_id : | the signal identifier, as returned by g_signal_lookup().
detail : | the detail which the signal was emitted with.

g_signal_stop_emission_by_name ()

void                g_signal_stop_emission_by_name      (gpointer instance,
                                                         const gchar *detailed_signal);

Stops a signal's current emission.

This is just like g_signal_stop_emission() except it will look up the signal id for you.

instance : | the object whose signal handlers you wish to stop.
detailed_signal : | a string of the form "signal-name::detail".

g_signal_override_class_closure ()

void                g_signal_override_class_closure     (guint signal_id,
                                                         GType instance_type,
                                                         GClosure *class_closure);

Overrides the class closure (i.e. the default handler) for the given signal for emissions on instances of instance_type. instance_type must be derived from the type to which the signal belongs.

signal_id : | the signal id
instance_type : | the instance type on which to override the class closure for the signal.
class_closure : | the closure.

g_signal_chain_from_overridden ()

void                g_signal_chain_from_overridden      (const GValue *instance_and_params,
                                                         GValue *return_value);

Calls the original class closure of a signal. This function should only be called from an overridden class closure; see g_signal_override_class_closure().

instance_and_params : | the argument list of the signal emission. The first element in the array is a GValue for the instance the signal is being emitted on. The rest are any arguments to be passed to the signal.
return_value : | Location for the return value.

g_signal_add_emission_hook ()

gulong              g_signal_add_emission_hook          (guint signal_id,
                                                         GQuark detail,
                                                         GSignalEmissionHook hook_func,
                                                         gpointer hook_data,
                                                         GDestroyNotify data_destroy);

Adds an emission hook for a signal, which will get called for any emission of that signal, independent of the instance. This is possible only for signals which don't have G_SIGNAL_NO_HOOKS flag set.

signal_id : | the signal identifier, as returned by g_signal_lookup().
detail : | the detail on which to call the hook.
hook_func : | a GSignalEmissionHook function.
hook_data : | user data for hook_func.
data_destroy : | a GDestroyNotify for hook_data.
Returns : | the hook id, for later use with g_signal_remove_emission_hook().

g_signal_remove_emission_hook ()

void                g_signal_remove_emission_hook       (guint signal_id,
                                                         gulong hook_id);

Deletes an emission hook.

signal_id : | the id of the signal
hook_id : | the id of the emission hook, as returned by g_signal_add_emission_hook()

g_signal_parse_name ()

gboolean            g_signal_parse_name                 (const gchar *detailed_signal,
                                                         GType itype,
                                                         guint *signal_id_p,
                                                         GQuark *detail_p,
                                                         gboolean force_detail_quark);

Internal function to parse a signal name into its signal_id and detail quark.

detailed_signal : | a string of the form "signal-name::detail".
itype : | The interface/instance type that introduced "signal-name".
signal_id_p : | Location to store the signal id.
detail_p : | Location to store the detail quark.
force_detail_quark : | TRUE forces creation of a GQuark for the detail.
Returns : | Whether the signal name could successfully be parsed and signal_id_p and detail_p contain valid return values.

g_signal_get_invocation_hint ()

GSignalInvocationHint* g_signal_get_invocation_hint     (gpointer instance);

Returns the invocation hint of the innermost signal emission of instance.

instance : | the instance to query
Returns : | the invocation hint of the innermost signal emission.

g_signal_type_cclosure_new ()

GClosure*           g_signal_type_cclosure_new          (GType itype,
                                                         guint struct_offset);

Creates a new closure which invokes the function found at the offset struct_offset in the class structure of the interface or classed type identified by itype.

itype : | the GType identifier of an interface or classed type
struct_offset : | the offset of the member function of itype's class structure which is to be invoked by the new closure
Returns : | a new GCClosure

g_signal_accumulator_true_handled ()

gboolean            g_signal_accumulator_true_handled   (GSignalInvocationHint *ihint,
                                                         GValue *return_accu,
                                                         const GValue *handler_return,
                                                         gpointer dummy);

A predefined GSignalAccumulator for signals that return a boolean values. The behavior that this accumulator gives is that a return of TRUE stops the signal emission: no further callbacks will be invoked, while a return of FALSE allows the emission to coninue. The idea here is that a TRUE return indicates that the callback handled the signal, and no further handling is needed.

ihint : | standard GSignalAccumulator parameter
return_accu : | standard GSignalAccumulator parameter
handler_return : | standard GSignalAccumulator parameter
dummy : | standard GSignalAccumulator parameter
Returns : | standard GSignalAccumulator result

Since 2.4

[11] Although signals can deal with any kind of instantiatable type, i'm referring to those types as "object types" in the following, simply because that is the context most users will encounter signals in.


Parameters and Values

Parameters and Values — Standard Parameter and Value Types

Synopsis

#include <glib-object.h>

#define             G_IS_PARAM_SPEC_BOOLEAN             (pspec)
#define             G_PARAM_SPEC_BOOLEAN                (pspec)
#define             G_VALUE_HOLDS_BOOLEAN               (value)
#define             G_TYPE_PARAM_BOOLEAN
                    GParamSpecBoolean;
GParamSpec*         g_param_spec_boolean                (const gchar *name,
                                                         const gchar *nick,
                                                         const gchar *blurb,
                                                         gboolean default_value,
                                                         GParamFlags flags);
void                g_value_set_boolean                 (GValue *value,
                                                         gboolean v_boolean);
gboolean            g_value_get_boolean                 (const GValue *value);

#define             G_IS_PARAM_SPEC_CHAR                (pspec)
#define             G_PARAM_SPEC_CHAR                   (pspec)
#define             G_VALUE_HOLDS_CHAR                  (value)
#define             G_TYPE_PARAM_CHAR
                    GParamSpecChar;
GParamSpec*         g_param_spec_char                   (const gchar *name,
                                                         const gchar *nick,
                                                         const gchar *blurb,
                                                         gint8 minimum,
                                                         gint8 maximum,
                                                         gint8 default_value,
                                                         GParamFlags flags);
void                g_value_set_char                    (GValue *value,
                                                         gchar v_char);
gchar               g_value_get_char                    (const GValue *value);

#define             G_IS_PARAM_SPEC_UCHAR               (pspec)
#define             G_PARAM_SPEC_UCHAR                  (pspec)
#define             G_VALUE_HOLDS_UCHAR                 (value)
#define             G_TYPE_PARAM_UCHAR
                    GParamSpecUChar;
GParamSpec*         g_param_spec_uchar                  (const gchar *name,
                                                         const gchar *nick,
                                                         const gchar *blurb,
                                                         guint8 minimum,
                                                         guint8 maximum,
                                                         guint8 default_value,
                                                         GParamFlags flags);
void                g_value_set_uchar                   (GValue *value,
                                                         guchar v_uchar);
guchar              g_value_get_uchar                   (const GValue *value);

#define             G_IS_PARAM_SPEC_INT                 (pspec)
#define             G_PARAM_SPEC_INT                    (pspec)
#define             G_VALUE_HOLDS_INT                   (value)
#define             G_TYPE_PARAM_INT
                    GParamSpecInt;
GParamSpec*         g_param_spec_int                    (const gchar *name,
                                                         const gchar *nick,
                                                         const gchar *blurb,
                                                         gint minimum,
                                                         gint maximum,
                                                         gint default_value,
                                                         GParamFlags flags);
void                g_value_set_int                     (GValue *value,
                                                         gint v_int);
gint                g_value_get_int                     (const GValue *value);

#define             G_IS_PARAM_SPEC_UINT                (pspec)
#define             G_PARAM_SPEC_UINT                   (pspec)
#define             G_VALUE_HOLDS_UINT                  (value)
#define             G_TYPE_PARAM_UINT
                    GParamSpecUInt;
GParamSpec*         g_param_spec_uint                   (const gchar *name,
                                                         const gchar *nick,
                                                         const gchar *blurb,
                                                         guint minimum,
                                                         guint maximum,
                                                         guint default_value,
                                                         GParamFlags flags);
void                g_value_set_uint                    (GValue *value,
                                                         guint v_uint);
guint               g_value_get_uint                    (const GValue *value);

#define             G_IS_PARAM_SPEC_LONG                (pspec)
#define             G_PARAM_SPEC_LONG                   (pspec)
#define             G_VALUE_HOLDS_LONG                  (value)
#define             G_TYPE_PARAM_LONG
                    GParamSpecLong;
GParamSpec*         g_param_spec_long                   (const gchar *name,
                                                         const gchar *nick,
                                                         const gchar *blurb,
                                                         glong minimum,
                                                         glong maximum,
                                                         glong default_value,
                                                         GParamFlags flags);
void                g_value_set_long                    (GValue *value,
                                                         glong v_long);
glong               g_value_get_long                    (const GValue *value);

#define             G_IS_PARAM_SPEC_ULONG               (pspec)
#define             G_PARAM_SPEC_ULONG                  (pspec)
#define             G_VALUE_HOLDS_ULONG                 (value)
#define             G_TYPE_PARAM_ULONG
                    GParamSpecULong;
GParamSpec*         g_param_spec_ulong                  (const gchar *name,
                                                         const gchar *nick,
                                                         const gchar *blurb,
                                                         gulong minimum,
                                                         gulong maximum,
                                                         gulong default_value,
                                                         GParamFlags flags);
void                g_value_set_ulong                   (GValue *value,
                                                         gulong v_ulong);
gulong              g_value_get_ulong                   (const GValue *value);

#define             G_IS_PARAM_SPEC_INT64               (pspec)
#define             G_PARAM_SPEC_INT64                  (pspec)
#define             G_VALUE_HOLDS_INT64                 (value)
#define             G_TYPE_PARAM_INT64
                    GParamSpecInt64;
GParamSpec*         g_param_spec_int64                  (const gchar *name,
                                                         const gchar *nick,
                                                         const gchar *blurb,
                                                         gint64 minimum,
                                                         gint64 maximum,
                                                         gint64 default_value,
                                                         GParamFlags flags);
void                g_value_set_int64                   (GValue *value,
                                                         gint64 v_int64);
gint64              g_value_get_int64                   (const GValue *value);

#define             G_IS_PARAM_SPEC_UINT64              (pspec)
#define             G_PARAM_SPEC_UINT64                 (pspec)
#define             G_VALUE_HOLDS_UINT64                (value)
#define             G_TYPE_PARAM_UINT64
                    GParamSpecUInt64;
GParamSpec*         g_param_spec_uint64                 (const gchar *name,
                                                         const gchar *nick,
                                                         const gchar *blurb,
                                                         guint64 minimum,
                                                         guint64 maximum,
                                                         guint64 default_value,
                                                         GParamFlags flags);
void                g_value_set_uint64                  (GValue *value,
                                                         guint64 v_uint64);
guint64             g_value_get_uint64                  (const GValue *value);

#define             G_IS_PARAM_SPEC_FLOAT               (pspec)
#define             G_PARAM_SPEC_FLOAT                  (pspec)
#define             G_VALUE_HOLDS_FLOAT                 (value)
#define             G_TYPE_PARAM_FLOAT
                    GParamSpecFloat;
GParamSpec*         g_param_spec_float                  (const gchar *name,
                                                         const gchar *nick,
                                                         const gchar *blurb,
                                                         gfloat minimum,
                                                         gfloat maximum,
                                                         gfloat default_value,
                                                         GParamFlags flags);
void                g_value_set_float                   (GValue *value,
                                                         gfloat v_float);
gfloat              g_value_get_float                   (const GValue *value);

#define             G_IS_PARAM_SPEC_DOUBLE              (pspec)
#define             G_PARAM_SPEC_DOUBLE                 (pspec)
#define             G_VALUE_HOLDS_DOUBLE                (value)
#define             G_TYPE_PARAM_DOUBLE
                    GParamSpecDouble;
GParamSpec*         g_param_spec_double                 (const gchar *name,
                                                         const gchar *nick,
                                                         const gchar *blurb,
                                                         gdouble minimum,
                                                         gdouble maximum,
                                                         gdouble default_value,
                                                         GParamFlags flags);
void                g_value_set_double                  (GValue *value,
                                                         gdouble v_double);
gdouble             g_value_get_double                  (const GValue *value);

#define             G_IS_PARAM_SPEC_ENUM                (pspec)
#define             G_PARAM_SPEC_ENUM                   (pspec)
#define             G_VALUE_HOLDS_ENUM                  (value)
#define             G_TYPE_PARAM_ENUM
                    GParamSpecEnum;
GParamSpec*         g_param_spec_enum                   (const gchar *name,
                                                         const gchar *nick,
                                                         const gchar *blurb,
                                                         GType enum_type,
                                                         gint default_value,
                                                         GParamFlags flags);
void                g_value_set_enum                    (GValue *value,
                                                         gint v_enum);
gint                g_value_get_enum                    (const GValue *value);

#define             G_IS_PARAM_SPEC_FLAGS               (pspec)
#define             G_PARAM_SPEC_FLAGS                  (pspec)
#define             G_VALUE_HOLDS_FLAGS                 (value)
#define             G_TYPE_PARAM_FLAGS
                    GParamSpecFlags;
GParamSpec*         g_param_spec_flags                  (const gchar *name,
                                                         const gchar *nick,
                                                         const gchar *blurb,
                                                         GType flags_type,
                                                         guint default_value,
                                                         GParamFlags flags);
void                g_value_set_flags                   (GValue *value,
                                                         guint v_flags);
guint               g_value_get_flags                   (const GValue *value);

#define             G_IS_PARAM_SPEC_STRING              (pspec)
#define             G_PARAM_SPEC_STRING                 (pspec)
#define             G_VALUE_HOLDS_STRING                (value)
#define             G_TYPE_PARAM_STRING
                    GParamSpecString;
typedef             gchararray;
GParamSpec*         g_param_spec_string                 (const gchar *name,
                                                         const gchar *nick,
                                                         const gchar *blurb,
                                                         const gchar *default_value,
                                                         GParamFlags flags);
void                g_value_set_string                  (GValue *value,
                                                         const gchar *v_string);
void                g_value_set_static_string           (GValue *value,
                                                         const gchar *v_string);
void                g_value_take_string                 (GValue *value,
                                                         gchar *v_string);
void                g_value_set_string_take_ownership   (GValue *value,
                                                         gchar *v_string);
const gchar*        g_value_get_string                  (const GValue *value);
gchar*              g_value_dup_string                  (const GValue *value);

#define             G_IS_PARAM_SPEC_PARAM               (pspec)
#define             G_PARAM_SPEC_PARAM                  (pspec)
#define             G_VALUE_HOLDS_PARAM                 (value)
#define             G_TYPE_PARAM_PARAM
                    GParamSpecParam;
GParamSpec*         g_param_spec_param                  (const gchar *name,
                                                         const gchar *nick,
                                                         const gchar *blurb,
                                                         GType param_type,
                                                         GParamFlags flags);
void                g_value_set_param                   (GValue *value,
                                                         GParamSpec *param);
void                g_value_take_param                  (GValue *value,
                                                         GParamSpec *param);
void                g_value_set_param_take_ownership    (GValue *value,
                                                         GParamSpec *param);
GParamSpec*         g_value_get_param                   (const GValue *value);
GParamSpec*         g_value_dup_param                   (const GValue *value);

#define             G_IS_PARAM_SPEC_BOXED               (pspec)
#define             G_PARAM_SPEC_BOXED                  (pspec)
#define             G_VALUE_HOLDS_BOXED                 (value)
#define             G_TYPE_PARAM_BOXED
                    GParamSpecBoxed;
GParamSpec*         g_param_spec_boxed                  (const gchar *name,
                                                         const gchar *nick,
                                                         const gchar *blurb,
                                                         GType boxed_type,
                                                         GParamFlags flags);
void                g_value_set_boxed                   (GValue *value,
                                                         gconstpointer v_boxed);
void                g_value_set_static_boxed            (GValue *value,
                                                         gconstpointer v_boxed);
void                g_value_take_boxed                  (GValue *value,
                                                         gconstpointer v_boxed);
void                g_value_set_boxed_take_ownership    (GValue *value,
                                                         gconstpointer v_boxed);
gpointer            g_value_get_boxed                   (const GValue *value);
gpointer            g_value_dup_boxed                   (const GValue *value);

#define             G_IS_PARAM_SPEC_POINTER             (pspec)
#define             G_PARAM_SPEC_POINTER                (pspec)
#define             G_VALUE_HOLDS_POINTER               (value)
#define             G_TYPE_PARAM_POINTER
                    GParamSpecPointer;
GParamSpec*         g_param_spec_pointer                (const gchar *name,
                                                         const gchar *nick,
                                                         const gchar *blurb,
                                                         GParamFlags flags);
void                g_value_set_pointer                 (GValue *value,
                                                         gpointer v_pointer);
gpointer            g_value_get_pointer                 (const GValue *value);

#define             G_IS_PARAM_SPEC_OBJECT              (pspec)
#define             G_PARAM_SPEC_OBJECT                 (pspec)
#define             G_VALUE_HOLDS_OBJECT                (value)
#define             G_TYPE_PARAM_OBJECT
                    GParamSpecObject;
GParamSpec*         g_param_spec_object                 (const gchar *name,
                                                         const gchar *nick,
                                                         const gchar *blurb,
                                                         GType object_type,
                                                         GParamFlags flags);
void                g_value_set_object                  (GValue *value,
                                                         gpointer v_object);
void                g_value_take_object                 (GValue *value,
                                                         gpointer v_object);
void                g_value_set_object_take_ownership   (GValue *value,
                                                         gpointer v_object);
gpointer            g_value_get_object                  (const GValue *value);
GObject*            g_value_dup_object                  (const GValue *value);

#define             G_IS_PARAM_SPEC_UNICHAR             (pspec)
#define             G_PARAM_SPEC_UNICHAR                (pspec)
#define             G_TYPE_PARAM_UNICHAR
                    GParamSpecUnichar;
GParamSpec*         g_param_spec_unichar                (const gchar *name,
                                                         const gchar *nick,
                                                         const gchar *blurb,
                                                         gunichar default_value,
                                                         GParamFlags flags);

#define             G_IS_PARAM_SPEC_VALUE_ARRAY         (pspec)
#define             G_PARAM_SPEC_VALUE_ARRAY            (pspec)
#define             G_TYPE_PARAM_VALUE_ARRAY
                    GParamSpecValueArray;
GParamSpec*         g_param_spec_value_array            (const gchar *name,
                                                         const gchar *nick,
                                                         const gchar *blurb,
                                                         GParamSpec *element_spec,
                                                         GParamFlags flags);

#define             G_IS_PARAM_SPEC_OVERRIDE            (pspec)
#define             G_PARAM_SPEC_OVERRIDE               (pspec)
#define             G_TYPE_PARAM_OVERRIDE
                    GParamSpecOverride;
GParamSpec*         g_param_spec_override               (const gchar *name,
                                                         GParamSpec *overridden);

#define             G_IS_PARAM_SPEC_GTYPE               (pspec)
#define             G_PARAM_SPEC_GTYPE                  (pspec)
#define             G_VALUE_HOLDS_GTYPE                 (value)
#define             G_TYPE_PARAM_GTYPE
                    GParamSpecGType;
GParamSpec*         g_param_spec_gtype                  (const gchar *name,
                                                         const gchar *nick,
                                                         const gchar *blurb,
                                                         GType is_a_type,
                                                         GParamFlags flags);
GType               g_value_get_gtype                   (const GValue *value);
void                g_value_set_gtype                   (GValue *value,
                                                         GType v_gtype);

Description

GValue provides an abstract container structure which can be copied, transformed and compared while holding a value of any (derived) type, which is registered as a GType with a GTypeValueTable in its GTypeInfo structure. Parameter specifications for most value types can be created as GParamSpec derived instances, to implement e.g. GObject properties which operate on GValue containers.

Parameter names need to start with a letter (a-z or A-Z). Subsequent characters can be letters, numbers or a '-'. All other characters are replaced by a '-' during construction.

Details

G_IS_PARAM_SPEC_BOOLEAN()

#define G_IS_PARAM_SPEC_BOOLEAN(pspec)     (G_TYPE_CHECK_INSTANCE_TYPE ((pspec), G_TYPE_PARAM_BOOLEAN))

Return whether the given GParamSpec is of type G_TYPE_PARAM_BOOLEAN.

pspec : a valid GParamSpec instance

G_PARAM_SPEC_BOOLEAN()

#define G_PARAM_SPEC_BOOLEAN(pspec)        (G_TYPE_CHECK_INSTANCE_CAST ((pspec), G_TYPE_PARAM_BOOLEAN, GParamSpecBoolean))

Cast a GParamSpec instance into a GParamSpecBoolean.

pspec : a valid GParamSpec instance

G_VALUE_HOLDS_BOOLEAN()

#define G_VALUE_HOLDS_BOOLEAN(value)	 (G_TYPE_CHECK_VALUE_TYPE ((value), G_TYPE_BOOLEAN))

Return whether the given GValue can hold values of type G_TYPE_BOOLEAN.

value : a valid GValue structure

G_TYPE_PARAM_BOOLEAN

#define	G_TYPE_PARAM_BOOLEAN		   (g_param_spec_types[2])

The GType of GParamSpecBoolean.

GParamSpecBoolean

typedef struct {
  GParamSpec    parent_instance;

  gboolean      default_value;
} GParamSpecBoolean;

A GParamSpec derived structure that contains the meta data for boolean properties.

GParamSpec parent_instance; | private GParamSpec portion
gboolean default_value; | default value for the property specified

g_param_spec_boolean ()

GParamSpec*         g_param_spec_boolean                (const gchar *name,
                                                         const gchar *nick,
                                                         const gchar *blurb,
                                                         gboolean default_value,
                                                         GParamFlags flags);

Creates a new GParamSpecBoolean instance specifying a G_TYPE_BOOLEAN property.

See g_param_spec_internal() for details on property names.

name : | canonical name of the property specified
nick : | nick name for the property specified
blurb : | description of the property specified
default_value : | default value for the property specified
flags : | flags for the property specified
Returns : | a newly created parameter specification

g_value_set_boolean ()

void                g_value_set_boolean                 (GValue *value,
                                                         gboolean v_boolean);

Set the contents of a G_TYPE_BOOLEAN GValue to v_boolean.

value : | a valid GValue of type G_TYPE_BOOLEAN
v_boolean : | boolean value to be set

g_value_get_boolean ()

gboolean            g_value_get_boolean                 (const GValue *value);

Get the contents of a G_TYPE_BOOLEAN GValue.

value : | a valid GValue of type G_TYPE_BOOLEAN
Returns : | boolean contents of value

G_IS_PARAM_SPEC_CHAR()

#define G_IS_PARAM_SPEC_CHAR(pspec)        (G_TYPE_CHECK_INSTANCE_TYPE ((pspec), G_TYPE_PARAM_CHAR))

Return whether the given GParamSpec is of type G_TYPE_PARAM_CHAR.

pspec : a valid GParamSpec instance

G_PARAM_SPEC_CHAR()

#define G_PARAM_SPEC_CHAR(pspec)           (G_TYPE_CHECK_INSTANCE_CAST ((pspec), G_TYPE_PARAM_CHAR, GParamSpecChar))

Cast a GParamSpec instance into a GParamSpecChar.

pspec : a valid GParamSpec instance

G_VALUE_HOLDS_CHAR()

#define G_VALUE_HOLDS_CHAR(value)	 (G_TYPE_CHECK_VALUE_TYPE ((value), G_TYPE_CHAR))

Return whether the given GValue can hold values of type G_TYPE_CHAR.

value : a valid GValue structure

G_TYPE_PARAM_CHAR

#define	G_TYPE_PARAM_CHAR		   (g_param_spec_types[0])

The GType of GParamSpecChar.

GParamSpecChar

typedef struct {
  GParamSpec    parent_instance;

  gint8         minimum;
  gint8         maximum;
  gint8         default_value;
} GParamSpecChar;

A GParamSpec derived structure that contains the meta data for character properties.

GParamSpec parent_instance; | private GParamSpec portion
gint8 minimum; | minimum value for the property specified
gint8 maximum; | maximum value for the property specified
gint8 default_value; | default value for the property specified

g_param_spec_char ()

GParamSpec*         g_param_spec_char                   (const gchar *name,
                                                         const gchar *nick,
                                                         const gchar *blurb,
                                                         gint8 minimum,
                                                         gint8 maximum,
                                                         gint8 default_value,
                                                         GParamFlags flags);

Creates a new GParamSpecChar instance specifying a G_TYPE_CHAR property.

name : | canonical name of the property specified
nick : | nick name for the property specified
blurb : | description of the property specified
minimum : | minimum value for the property specified
maximum : | maximum value for the property specified
default_value : | default value for the property specified
flags : | flags for the property specified
Returns : | a newly created parameter specification

g_value_set_char ()

void                g_value_set_char                    (GValue *value,
                                                         gchar v_char);

Set the contents of a G_TYPE_CHAR GValue to v_char.

value : | a valid GValue of type G_TYPE_CHAR
v_char : | character value to be set

g_value_get_char ()

gchar               g_value_get_char                    (const GValue *value);

Get the contents of a G_TYPE_CHAR GValue.

value : | a valid GValue of type G_TYPE_CHAR
Returns : | character contents of value

G_IS_PARAM_SPEC_UCHAR()

#define G_IS_PARAM_SPEC_UCHAR(pspec)       (G_TYPE_CHECK_INSTANCE_TYPE ((pspec), G_TYPE_PARAM_UCHAR))

Return whether the given GParamSpec is of type G_TYPE_PARAM_UCHAR.

pspec : a valid GParamSpec instance

G_PARAM_SPEC_UCHAR()

#define G_PARAM_SPEC_UCHAR(pspec)          (G_TYPE_CHECK_INSTANCE_CAST ((pspec), G_TYPE_PARAM_UCHAR, GParamSpecUChar))

Cast a GParamSpec instance into a GParamSpecUChar.

pspec : a valid GParamSpec instance

G_VALUE_HOLDS_UCHAR()

#define G_VALUE_HOLDS_UCHAR(value)	 (G_TYPE_CHECK_VALUE_TYPE ((value), G_TYPE_UCHAR))

Return whether the given GValue can hold values of type G_TYPE_UCHAR.

value : a valid GValue structure

G_TYPE_PARAM_UCHAR

#define	G_TYPE_PARAM_UCHAR		   (g_param_spec_types[1])

The GType of GParamSpecUChar.

GParamSpecUChar

typedef struct {
  GParamSpec    parent_instance;

  guint8        minimum;
  guint8        maximum;
  guint8        default_value;
} GParamSpecUChar;

A GParamSpec derived structure that contains the meta data for unsigned character properties.

GParamSpec parent_instance; | private GParamSpec portion
guint8 minimum; | minimum value for the property specified
guint8 maximum; | maximum value for the property specified
guint8 default_value; | default value for the property specified

g_param_spec_uchar ()

GParamSpec*         g_param_spec_uchar                  (const gchar *name,
                                                         const gchar *nick,
                                                         const gchar *blurb,
                                                         guint8 minimum,
                                                         guint8 maximum,
                                                         guint8 default_value,
                                                         GParamFlags flags);

Creates a new GParamSpecUChar instance specifying a G_TYPE_UCHAR property.

name : | canonical name of the property specified
nick : | nick name for the property specified
blurb : | description of the property specified
minimum : | minimum value for the property specified
maximum : | maximum value for the property specified
default_value : | default value for the property specified
flags : | flags for the property specified
Returns : | a newly created parameter specification

g_value_set_uchar ()

void                g_value_set_uchar                   (GValue *value,
                                                         guchar v_uchar);

Set the contents of a G_TYPE_UCHAR GValue to v_uchar.

value : | a valid GValue of type G_TYPE_UCHAR
v_uchar : | unsigned character value to be set

g_value_get_uchar ()

guchar              g_value_get_uchar                   (const GValue *value);

Get the contents of a G_TYPE_UCHAR GValue.

value : | a valid GValue of type G_TYPE_UCHAR
Returns : | unsigned character contents of value

G_IS_PARAM_SPEC_INT()

#define G_IS_PARAM_SPEC_INT(pspec)         (G_TYPE_CHECK_INSTANCE_TYPE ((pspec), G_TYPE_PARAM_INT))

Return whether the given GParamSpec is of type G_TYPE_PARAM_INT.

pspec : a valid GParamSpec instance

G_PARAM_SPEC_INT()

#define G_PARAM_SPEC_INT(pspec)            (G_TYPE_CHECK_INSTANCE_CAST ((pspec), G_TYPE_PARAM_INT, GParamSpecInt))

Cast a GParamSpec instance into a GParamSpecInt.

pspec : a valid GParamSpec instance

G_VALUE_HOLDS_INT()

#define G_VALUE_HOLDS_INT(value)	 (G_TYPE_CHECK_VALUE_TYPE ((value), G_TYPE_INT))

Return whether the given GValue can hold values of type G_TYPE_INT.

value : a valid GValue structure

G_TYPE_PARAM_INT

#define	G_TYPE_PARAM_INT		   (g_param_spec_types[3])

The GType of GParamSpecInt.

GParamSpecInt

typedef struct {
  GParamSpec    parent_instance;

  gint          minimum;
  gint          maximum;
  gint          default_value;
} GParamSpecInt;

A GParamSpec derived structure that contains the meta data for integer properties.

GParamSpec parent_instance; | private GParamSpec portion
gint minimum; | minimum value for the property specified
gint maximum; | maximum value for the property specified
gint default_value; | default value for the property specified

g_param_spec_int ()

GParamSpec*         g_param_spec_int                    (const gchar *name,
                                                         const gchar *nick,
                                                         const gchar *blurb,
                                                         gint minimum,
                                                         gint maximum,
                                                         gint default_value,
                                                         GParamFlags flags);

Creates a new GParamSpecInt instance specifying a G_TYPE_INT property.

See g_param_spec_internal() for details on property names.

name : | canonical name of the property specified
nick : | nick name for the property specified
blurb : | description of the property specified
minimum : | minimum value for the property specified
maximum : | maximum value for the property specified
default_value : | default value for the property specified
flags : | flags for the property specified
Returns : | a newly created parameter specification

g_value_set_int ()

void                g_value_set_int                     (GValue *value,
                                                         gint v_int);

Set the contents of a G_TYPE_INT GValue to v_int.

value : | a valid GValue of type G_TYPE_INT
v_int : | integer value to be set

g_value_get_int ()

gint                g_value_get_int                     (const GValue *value);

Get the contents of a G_TYPE_INT GValue.

value : | a valid GValue of type G_TYPE_INT
Returns : | integer contents of value

G_IS_PARAM_SPEC_UINT()

#define G_IS_PARAM_SPEC_UINT(pspec)        (G_TYPE_CHECK_INSTANCE_TYPE ((pspec), G_TYPE_PARAM_UINT))

Return whether the given GParamSpec is of type G_TYPE_PARAM_UINT.

pspec : a valid GParamSpec instance

G_PARAM_SPEC_UINT()

#define G_PARAM_SPEC_UINT(pspec)           (G_TYPE_CHECK_INSTANCE_CAST ((pspec), G_TYPE_PARAM_UINT, GParamSpecUInt))

Cast a GParamSpec instance into a GParamSpecUInt.

pspec : a valid GParamSpec instance

G_VALUE_HOLDS_UINT()

#define G_VALUE_HOLDS_UINT(value)	 (G_TYPE_CHECK_VALUE_TYPE ((value), G_TYPE_UINT))

Return whether the given GValue can hold values of type G_TYPE_UINT.

value : a valid GValue structure

G_TYPE_PARAM_UINT

#define	G_TYPE_PARAM_UINT		   (g_param_spec_types[4])

The GType of GParamSpecUInt.

GParamSpecUInt

typedef struct {
  GParamSpec    parent_instance;

  guint         minimum;
  guint         maximum;
  guint         default_value;
} GParamSpecUInt;

A GParamSpec derived structure that contains the meta data for unsigned integer properties.

GParamSpec parent_instance; | private GParamSpec portion
guint minimum; | minimum value for the property specified
guint maximum; | maximum value for the property specified
guint default_value; | default value for the property specified

g_param_spec_uint ()

GParamSpec*         g_param_spec_uint                   (const gchar *name,
                                                         const gchar *nick,
                                                         const gchar *blurb,
                                                         guint minimum,
                                                         guint maximum,
                                                         guint default_value,
                                                         GParamFlags flags);

Creates a new GParamSpecUInt instance specifying a G_TYPE_UINT property.

See g_param_spec_internal() for details on property names.

name : | canonical name of the property specified
nick : | nick name for the property specified
blurb : | description of the property specified
minimum : | minimum value for the property specified
maximum : | maximum value for the property specified
default_value : | default value for the property specified
flags : | flags for the property specified
Returns : | a newly created parameter specification

g_value_set_uint ()

void                g_value_set_uint                    (GValue *value,
                                                         guint v_uint);

Set the contents of a G_TYPE_UINT GValue to v_uint.

value : | a valid GValue of type G_TYPE_UINT
v_uint : | unsigned integer value to be set

g_value_get_uint ()

guint               g_value_get_uint                    (const GValue *value);

Get the contents of a G_TYPE_UINT GValue.

value : | a valid GValue of type G_TYPE_UINT
Returns : | unsigned integer contents of value

G_IS_PARAM_SPEC_LONG()

#define G_IS_PARAM_SPEC_LONG(pspec)        (G_TYPE_CHECK_INSTANCE_TYPE ((pspec), G_TYPE_PARAM_LONG))

Return whether the given GParamSpec is of type G_TYPE_PARAM_LONG.

pspec : a valid GParamSpec instance

G_PARAM_SPEC_LONG()

#define G_PARAM_SPEC_LONG(pspec)           (G_TYPE_CHECK_INSTANCE_CAST ((pspec), G_TYPE_PARAM_LONG, GParamSpecLong))

Cast a GParamSpec instance into a GParamSpecLong.

pspec : a valid GParamSpec instance

G_VALUE_HOLDS_LONG()

#define G_VALUE_HOLDS_LONG(value)	 (G_TYPE_CHECK_VALUE_TYPE ((value), G_TYPE_LONG))

Return whether the given GValue can hold values of type G_TYPE_LONG.

value : a valid GValue structure

G_TYPE_PARAM_LONG

#define	G_TYPE_PARAM_LONG		   (g_param_spec_types[5])

The GType of GParamSpecLong.

GParamSpecLong

typedef struct {
  GParamSpec    parent_instance;

  glong         minimum;
  glong         maximum;
  glong         default_value;
} GParamSpecLong;

A GParamSpec derived structure that contains the meta data for long integer properties.

GParamSpec parent_instance; | private GParamSpec portion
glong minimum; | minimum value for the property specified
glong maximum; | maximum value for the property specified
glong default_value; | default value for the property specified

g_param_spec_long ()

GParamSpec*         g_param_spec_long                   (const gchar *name,
                                                         const gchar *nick,
                                                         const gchar *blurb,
                                                         glong minimum,
                                                         glong maximum,
                                                         glong default_value,
                                                         GParamFlags flags);

Creates a new GParamSpecLong instance specifying a G_TYPE_LONG property.

See g_param_spec_internal() for details on property names.

name : | canonical name of the property specified
nick : | nick name for the property specified
blurb : | description of the property specified
minimum : | minimum value for the property specified
maximum : | maximum value for the property specified
default_value : | default value for the property specified
flags : | flags for the property specified
Returns : | a newly created parameter specification

g_value_set_long ()

void                g_value_set_long                    (GValue *value,
                                                         glong v_long);

Set the contents of a G_TYPE_LONG GValue to v_long.

value : | a valid GValue of type G_TYPE_LONG
v_long : | long integer value to be set

g_value_get_long ()

glong               g_value_get_long                    (const GValue *value);

Get the contents of a G_TYPE_LONG GValue.

value : | a valid GValue of type G_TYPE_LONG
Returns : | long integer contents of value

G_IS_PARAM_SPEC_ULONG()

#define G_IS_PARAM_SPEC_ULONG(pspec)       (G_TYPE_CHECK_INSTANCE_TYPE ((pspec), G_TYPE_PARAM_ULONG))

Return whether the given GParamSpec is of type G_TYPE_PARAM_ULONG.

pspec : a valid GParamSpec instance

G_PARAM_SPEC_ULONG()

#define G_PARAM_SPEC_ULONG(pspec)          (G_TYPE_CHECK_INSTANCE_CAST ((pspec), G_TYPE_PARAM_ULONG, GParamSpecULong))

Cast a GParamSpec instance into a GParamSpecULong.

pspec : a valid GParamSpec instance

G_VALUE_HOLDS_ULONG()

#define G_VALUE_HOLDS_ULONG(value)	 (G_TYPE_CHECK_VALUE_TYPE ((value), G_TYPE_ULONG))

Return whether the given GValue can hold values of type G_TYPE_ULONG.

value : a valid GValue structure

G_TYPE_PARAM_ULONG

#define	G_TYPE_PARAM_ULONG		   (g_param_spec_types[6])

The GType of GParamSpecULong.

GParamSpecULong

typedef struct {
  GParamSpec    parent_instance;

  gulong        minimum;
  gulong        maximum;
  gulong        default_value;
} GParamSpecULong;

A GParamSpec derived structure that contains the meta data for unsigned long integer properties.

GParamSpec parent_instance; | private GParamSpec portion
gulong minimum; | minimum value for the property specified
gulong maximum; | maximum value for the property specified
gulong default_value; | default value for the property specified

g_param_spec_ulong ()

GParamSpec*         g_param_spec_ulong                  (const gchar *name,
                                                         const gchar *nick,
                                                         const gchar *blurb,
                                                         gulong minimum,
                                                         gulong maximum,
                                                         gulong default_value,
                                                         GParamFlags flags);

Creates a new GParamSpecULong instance specifying a G_TYPE_ULONG property.

See g_param_spec_internal() for details on property names.

name : | canonical name of the property specified
nick : | nick name for the property specified
blurb : | description of the property specified
minimum : | minimum value for the property specified
maximum : | maximum value for the property specified
default_value : | default value for the property specified
flags : | flags for the property specified
Returns : | a newly created parameter specification

g_value_set_ulong ()

void                g_value_set_ulong                   (GValue *value,
                                                         gulong v_ulong);

Set the contents of a G_TYPE_ULONG GValue to v_ulong.

value : | a valid GValue of type G_TYPE_ULONG
v_ulong : | unsigned long integer value to be set

g_value_get_ulong ()

gulong              g_value_get_ulong                   (const GValue *value);

Get the contents of a G_TYPE_ULONG GValue.

value : | a valid GValue of type G_TYPE_ULONG
Returns : | unsigned long integer contents of value

G_IS_PARAM_SPEC_INT64()

#define G_IS_PARAM_SPEC_INT64(pspec)       (G_TYPE_CHECK_INSTANCE_TYPE ((pspec), G_TYPE_PARAM_INT64))

Return whether the given GParamSpec is of type G_TYPE_PARAM_INT64.

pspec : a valid GParamSpec instance

G_PARAM_SPEC_INT64()

#define G_PARAM_SPEC_INT64(pspec)          (G_TYPE_CHECK_INSTANCE_CAST ((pspec), G_TYPE_PARAM_INT64, GParamSpecInt64))

Cast a GParamSpec instance into a GParamSpecInt64.

pspec : a valid GParamSpec instance

G_VALUE_HOLDS_INT64()

#define G_VALUE_HOLDS_INT64(value)	 (G_TYPE_CHECK_VALUE_TYPE ((value), G_TYPE_INT64))

Return whether the given GValue can hold values of type G_TYPE_INT64.

value : a valid GValue structure

G_TYPE_PARAM_INT64

#define	G_TYPE_PARAM_INT64		   (g_param_spec_types[7])

The GType of GParamSpecInt64.

GParamSpecInt64

typedef struct {
  GParamSpec    parent_instance;

  gint64        minimum;
  gint64        maximum;
  gint64        default_value;
} GParamSpecInt64;

A GParamSpec derived structure that contains the meta data for 64bit integer properties.

GParamSpec parent_instance; | private GParamSpec portion
gint64 minimum; | minimum value for the property specified
gint64 maximum; | maximum value for the property specified
gint64 default_value; | default value for the property specified

g_param_spec_int64 ()

GParamSpec*         g_param_spec_int64                  (const gchar *name,
                                                         const gchar *nick,
                                                         const gchar *blurb,
                                                         gint64 minimum,
                                                         gint64 maximum,
                                                         gint64 default_value,
                                                         GParamFlags flags);

Creates a new GParamSpecInt64 instance specifying a G_TYPE_INT64 property.

See g_param_spec_internal() for details on property names.

name : | canonical name of the property specified
nick : | nick name for the property specified
blurb : | description of the property specified
minimum : | minimum value for the property specified
maximum : | maximum value for the property specified
default_value : | default value for the property specified
flags : | flags for the property specified
Returns : | a newly created parameter specification

g_value_set_int64 ()

void                g_value_set_int64                   (GValue *value,
                                                         gint64 v_int64);

Set the contents of a G_TYPE_INT64 GValue to v_int64.

value : | a valid GValue of type G_TYPE_INT64
v_int64 : | 64bit integer value to be set

g_value_get_int64 ()

gint64              g_value_get_int64                   (const GValue *value);

Get the contents of a G_TYPE_INT64 GValue.

value : | a valid GValue of type G_TYPE_INT64
Returns : | 64bit integer contents of value

G_IS_PARAM_SPEC_UINT64()

#define G_IS_PARAM_SPEC_UINT64(pspec)      (G_TYPE_CHECK_INSTANCE_TYPE ((pspec), G_TYPE_PARAM_UINT64))

Return whether the given GParamSpec is of type G_TYPE_PARAM_UINT64.

pspec : a valid GParamSpec instance

G_PARAM_SPEC_UINT64()

#define G_PARAM_SPEC_UINT64(pspec)         (G_TYPE_CHECK_INSTANCE_CAST ((pspec), G_TYPE_PARAM_UINT64, GParamSpecUInt64))

Cast a GParamSpec instance into a GParamSpecUInt64.

pspec : a valid GParamSpec instance

G_VALUE_HOLDS_UINT64()

#define G_VALUE_HOLDS_UINT64(value)	 (G_TYPE_CHECK_VALUE_TYPE ((value), G_TYPE_UINT64))

Return whether the given GValue can hold values of type G_TYPE_UINT64.

value : a valid GValue structure

G_TYPE_PARAM_UINT64

#define	G_TYPE_PARAM_UINT64		   (g_param_spec_types[8])

The GType of GParamSpecUInt64.

GParamSpecUInt64

typedef struct {
  GParamSpec    parent_instance;

  guint64       minimum;
  guint64       maximum;
  guint64       default_value;
} GParamSpecUInt64;

A GParamSpec derived structure that contains the meta data for unsigned 64bit integer properties.

GParamSpec parent_instance; | private GParamSpec portion
guint64 minimum; | minimum value for the property specified
guint64 maximum; | maximum value for the property specified
guint64 default_value; | default value for the property specified

g_param_spec_uint64 ()

GParamSpec*         g_param_spec_uint64                 (const gchar *name,
                                                         const gchar *nick,
                                                         const gchar *blurb,
                                                         guint64 minimum,
                                                         guint64 maximum,
                                                         guint64 default_value,
                                                         GParamFlags flags);

Creates a new GParamSpecUInt64 instance specifying a G_TYPE_UINT64 property.

See g_param_spec_internal() for details on property names.

name : | canonical name of the property specified
nick : | nick name for the property specified
blurb : | description of the property specified
minimum : | minimum value for the property specified
maximum : | maximum value for the property specified
default_value : | default value for the property specified
flags : | flags for the property specified
Returns : | a newly created parameter specification

g_value_set_uint64 ()

void                g_value_set_uint64                  (GValue *value,
                                                         guint64 v_uint64);

Set the contents of a G_TYPE_UINT64 GValue to v_uint64.

value : | a valid GValue of type G_TYPE_UINT64
v_uint64 : | unsigned 64bit integer value to be set

g_value_get_uint64 ()

guint64             g_value_get_uint64                  (const GValue *value);

Get the contents of a G_TYPE_UINT64 GValue.

value : | a valid GValue of type G_TYPE_UINT64
Returns : | unsigned 64bit integer contents of value

G_IS_PARAM_SPEC_FLOAT()

#define G_IS_PARAM_SPEC_FLOAT(pspec)       (G_TYPE_CHECK_INSTANCE_TYPE ((pspec), G_TYPE_PARAM_FLOAT))

Return whether the given GParamSpec is of type G_TYPE_PARAM_FLOAT.

pspec : a valid GParamSpec instance

G_PARAM_SPEC_FLOAT()

#define G_PARAM_SPEC_FLOAT(pspec)          (G_TYPE_CHECK_INSTANCE_CAST ((pspec), G_TYPE_PARAM_FLOAT, GParamSpecFloat))

Cast a GParamSpec instance into a GParamSpecFloat.

pspec : a valid GParamSpec instance

G_VALUE_HOLDS_FLOAT()

#define G_VALUE_HOLDS_FLOAT(value)	 (G_TYPE_CHECK_VALUE_TYPE ((value), G_TYPE_FLOAT))

Return whether the given GValue can hold values of type G_TYPE_FLOAT.

value : a valid GValue structure

G_TYPE_PARAM_FLOAT

#define	G_TYPE_PARAM_FLOAT		   (g_param_spec_types[12])

The GType of GParamSpecFloat.

GParamSpecFloat

typedef struct {
  GParamSpec    parent_instance;

  gfloat        minimum;
  gfloat        maximum;
  gfloat        default_value;
  gfloat        epsilon;
} GParamSpecFloat;

A GParamSpec derived structure that contains the meta data for float properties.

GParamSpec parent_instance; | private GParamSpec portion
gfloat minimum; | minimum value for the property specified
gfloat maximum; | maximum value for the property specified
gfloat default_value; | default value for the property specified
gfloat epsilon; | values closer than epsilon will be considered identical by g_param_values_cmp(); the default value is 1e-30.

g_param_spec_float ()

GParamSpec*         g_param_spec_float                  (const gchar *name,
                                                         const gchar *nick,
                                                         const gchar *blurb,
                                                         gfloat minimum,
                                                         gfloat maximum,
                                                         gfloat default_value,
                                                         GParamFlags flags);

Creates a new GParamSpecFloat instance specifying a G_TYPE_FLOAT property.

See g_param_spec_internal() for details on property names.

name : | canonical name of the property specified
nick : | nick name for the property specified
blurb : | description of the property specified
minimum : | minimum value for the property specified
maximum : | maximum value for the property specified
default_value : | default value for the property specified
flags : | flags for the property specified
Returns : | a newly created parameter specification

g_value_set_float ()

void                g_value_set_float                   (GValue *value,
                                                         gfloat v_float);

Set the contents of a G_TYPE_FLOAT GValue to v_float.

value : | a valid GValue of type G_TYPE_FLOAT
v_float : | float value to be set

g_value_get_float ()

gfloat              g_value_get_float                   (const GValue *value);

Get the contents of a G_TYPE_FLOAT GValue.

value : | a valid GValue of type G_TYPE_FLOAT
Returns : | float contents of value

G_IS_PARAM_SPEC_DOUBLE()

#define G_IS_PARAM_SPEC_DOUBLE(pspec)      (G_TYPE_CHECK_INSTANCE_TYPE ((pspec), G_TYPE_PARAM_DOUBLE))

Return whether the given GParamSpec is of type G_TYPE_PARAM_DOUBLE.

pspec : a valid GParamSpec instance

G_PARAM_SPEC_DOUBLE()

#define G_PARAM_SPEC_DOUBLE(pspec)         (G_TYPE_CHECK_INSTANCE_CAST ((pspec), G_TYPE_PARAM_DOUBLE, GParamSpecDouble))

Cast a GParamSpec instance into a GParamSpecDouble.

pspec : a valid GParamSpec instance

G_VALUE_HOLDS_DOUBLE()

#define G_VALUE_HOLDS_DOUBLE(value)	 (G_TYPE_CHECK_VALUE_TYPE ((value), G_TYPE_DOUBLE))

Return whether the given GValue can hold values of type G_TYPE_DOUBLE.

value : a valid GValue structure

G_TYPE_PARAM_DOUBLE

#define	G_TYPE_PARAM_DOUBLE		   (g_param_spec_types[13])

The GType of GParamSpecDouble.

GParamSpecDouble

typedef struct {
  GParamSpec    parent_instance;

  gdouble       minimum;
  gdouble       maximum;
  gdouble       default_value;
  gdouble       epsilon;
} GParamSpecDouble;

A GParamSpec derived structure that contains the meta data for double properties.

GParamSpec parent_instance; | private GParamSpec portion
gdouble minimum; | minimum value for the property specified
gdouble maximum; | maximum value for the property specified
gdouble default_value; | default value for the property specified
gdouble epsilon; | values closer than epsilon will be considered identical by g_param_values_cmp(); the default value is 1e-90.

g_param_spec_double ()

GParamSpec*         g_param_spec_double                 (const gchar *name,
                                                         const gchar *nick,
                                                         const gchar *blurb,
                                                         gdouble minimum,
                                                         gdouble maximum,
                                                         gdouble default_value,
                                                         GParamFlags flags);

Creates a new GParamSpecDouble instance specifying a G_TYPE_DOUBLE property.

See g_param_spec_internal() for details on property names.

name : | canonical name of the property specified
nick : | nick name for the property specified
blurb : | description of the property specified
minimum : | minimum value for the property specified
maximum : | maximum value for the property specified
default_value : | default value for the property specified
flags : | flags for the property specified
Returns : | a newly created parameter specification

g_value_set_double ()

void                g_value_set_double                  (GValue *value,
                                                         gdouble v_double);

Set the contents of a G_TYPE_DOUBLE GValue to v_double.

value : | a valid GValue of type G_TYPE_DOUBLE
v_double : | double value to be set

g_value_get_double ()

gdouble             g_value_get_double                  (const GValue *value);

Get the contents of a G_TYPE_DOUBLE GValue.

value : | a valid GValue of type G_TYPE_DOUBLE
Returns : | double contents of value

G_IS_PARAM_SPEC_ENUM()

#define G_IS_PARAM_SPEC_ENUM(pspec)        (G_TYPE_CHECK_INSTANCE_TYPE ((pspec), G_TYPE_PARAM_ENUM))

Returns whether the given GParamSpec is of type G_TYPE_PARAM_ENUM.

pspec : a valid GParamSpec instance

G_PARAM_SPEC_ENUM()

#define G_PARAM_SPEC_ENUM(pspec)           (G_TYPE_CHECK_INSTANCE_CAST ((pspec), G_TYPE_PARAM_ENUM, GParamSpecEnum))

Cast a GParamSpec instance into a GParamSpecEnum.

pspec : a valid GParamSpec instance

G_VALUE_HOLDS_ENUM()

#define G_VALUE_HOLDS_ENUM(value)      (G_TYPE_CHECK_VALUE_TYPE ((value), G_TYPE_ENUM))

Return whether the given GValue can hold values derived from type G_TYPE_ENUM.

value : a valid GValue structure

G_TYPE_PARAM_ENUM

#define	G_TYPE_PARAM_ENUM		   (g_param_spec_types[10])

The GType of GParamSpecEnum.

GParamSpecEnum

typedef struct {
  GParamSpec    parent_instance;

  GEnumClass   *enum_class;
  gint          default_value;
} GParamSpecEnum;

A GParamSpec derived structure that contains the meta data for enum properties.

GParamSpec parent_instance; | private GParamSpec portion
GEnumClass *enum_class; | the GEnumClass for the enum
gint default_value; | default value for the property specified

g_param_spec_enum ()

GParamSpec*         g_param_spec_enum                   (const gchar *name,
                                                         const gchar *nick,
                                                         const gchar *blurb,
                                                         GType enum_type,
                                                         gint default_value,
                                                         GParamFlags flags);

Creates a new GParamSpecEnum instance specifying a G_TYPE_ENUM property.

See g_param_spec_internal() for details on property names.

name : | canonical name of the property specified
nick : | nick name for the property specified
blurb : | description of the property specified
enum_type : | a GType derived from G_TYPE_ENUM
default_value : | default value for the property specified
flags : | flags for the property specified
Returns : | a newly created parameter specification

g_value_set_enum ()

void                g_value_set_enum                    (GValue *value,
                                                         gint v_enum);

Set the contents of a G_TYPE_ENUM GValue to v_enum.

value : | a valid GValue whose type is derived from G_TYPE_ENUM
v_enum : | enum value to be set

g_value_get_enum ()

gint                g_value_get_enum                    (const GValue *value);

Get the contents of a G_TYPE_ENUM GValue.

value : | a valid GValue whose type is derived from G_TYPE_ENUM
Returns : | enum contents of value

G_IS_PARAM_SPEC_FLAGS()

#define G_IS_PARAM_SPEC_FLAGS(pspec)       (G_TYPE_CHECK_INSTANCE_TYPE ((pspec), G_TYPE_PARAM_FLAGS))

Returns whether the given GParamSpec is of type G_TYPE_PARAM_FLAGS.

pspec : a valid GParamSpec instance

G_PARAM_SPEC_FLAGS()

#define G_PARAM_SPEC_FLAGS(pspec)          (G_TYPE_CHECK_INSTANCE_CAST ((pspec), G_TYPE_PARAM_FLAGS, GParamSpecFlags))

Cast a GParamSpec instance into a GParamSpecFlags.

pspec : a valid GParamSpec instance

G_VALUE_HOLDS_FLAGS()

#define G_VALUE_HOLDS_FLAGS(value)     (G_TYPE_CHECK_VALUE_TYPE ((value), G_TYPE_FLAGS))

Returns whether the given GValue can hold values derived from type G_TYPE_FLAGS.

value : a valid GValue structure

G_TYPE_PARAM_FLAGS

#define	G_TYPE_PARAM_FLAGS		   (g_param_spec_types[11])

The GType of GParamSpecFlags.

GParamSpecFlags

typedef struct {
  GParamSpec    parent_instance;

  GFlagsClass  *flags_class;
  guint         default_value;
} GParamSpecFlags;

A GParamSpec derived structure that contains the meta data for flags properties.

GParamSpec parent_instance; | private GParamSpec portion
GFlagsClass *flags_class; | the GFlagsClass for the flags
guint default_value; | default value for the property specified

g_param_spec_flags ()

GParamSpec*         g_param_spec_flags                  (const gchar *name,
                                                         const gchar *nick,
                                                         const gchar *blurb,
                                                         GType flags_type,
                                                         guint default_value,
                                                         GParamFlags flags);

Creates a new GParamSpecEnum instance specifying a G_TYPE_FLAGS property.

See g_param_spec_internal() for details on property names.

name : | canonical name of the property specified
nick : | nick name for the property specified
blurb : | description of the property specified
flags_type : | a GType derived from G_TYPE_FLAGS
default_value : | default value for the property specified
flags : | flags for the property specified
Returns : | a newly created parameter specification

g_value_set_flags ()

void                g_value_set_flags                   (GValue *value,
                                                         guint v_flags);

Set the contents of a G_TYPE_FLAGS GValue to v_flags.

value : | a valid GValue whose type is derived from G_TYPE_FLAGS
v_flags : | flags value to be set

g_value_get_flags ()

guint               g_value_get_flags                   (const GValue *value);

Get the contents of a G_TYPE_FLAGS GValue.

value : | a valid GValue whose type is derived from G_TYPE_FLAGS
Returns : | flags contents of value

G_IS_PARAM_SPEC_STRING()

#define G_IS_PARAM_SPEC_STRING(pspec)      (G_TYPE_CHECK_INSTANCE_TYPE ((pspec), G_TYPE_PARAM_STRING))

Returns whether the given GParamSpec is of type G_TYPE_PARAM_STRING.

pspec : a valid GParamSpec instance

G_PARAM_SPEC_STRING()

#define G_PARAM_SPEC_STRING(pspec)         (G_TYPE_CHECK_INSTANCE_CAST ((pspec), G_TYPE_PARAM_STRING, GParamSpecString))

Casts a GParamSpec instance into a GParamSpecString.

pspec : a valid GParamSpec instance

G_VALUE_HOLDS_STRING()

#define G_VALUE_HOLDS_STRING(value)	 (G_TYPE_CHECK_VALUE_TYPE ((value), G_TYPE_STRING))

Return whether the given GValue can hold values of type G_TYPE_STRING.

value : a valid GValue structure

G_TYPE_PARAM_STRING

#define	G_TYPE_PARAM_STRING		   (g_param_spec_types[14])

The GType of GParamSpecString.

GParamSpecString

typedef struct {
  GParamSpec    parent_instance;

  gchar        *default_value;
  gchar        *cset_first;
  gchar        *cset_nth;
  gchar         substitutor;
  guint         null_fold_if_empty : 1;
  guint         ensure_non_null : 1;
} GParamSpecString;

A GParamSpec derived structure that contains the meta data for string properties.

GParamSpec parent_instance; | private GParamSpec portion
gchar *default_value; | default value for the property specified
gchar *cset_first; | a string containing the allowed values for the first byte
gchar *cset_nth; | a string containing the allowed values for the subsequent bytes
gchar substitutor; | the replacement byte for bytes which don't match cset_first or cset_nth.
guint null_fold_if_empty : 1; | replace empty string by NULL
guint ensure_non_null : 1; | replace NULL strings by an empty string

gchararray

typedef gchar* gchararray;

A C representable type name for G_TYPE_STRING.

g_param_spec_string ()

GParamSpec*         g_param_spec_string                 (const gchar *name,
                                                         const gchar *nick,
                                                         const gchar *blurb,
                                                         const gchar *default_value,
                                                         GParamFlags flags);

Creates a new GParamSpecString instance.

See g_param_spec_internal() for details on property names.

name : | canonical name of the property specified
nick : | nick name for the property specified
blurb : | description of the property specified
default_value : | default value for the property specified
flags : | flags for the property specified
Returns : | a newly created parameter specification

g_value_set_string ()

void                g_value_set_string                  (GValue *value,
                                                         const gchar *v_string);

Set the contents of a G_TYPE_STRING GValue to v_string.

value : | a valid GValue of type G_TYPE_STRING
v_string : | string to be set

g_value_set_static_string ()

void                g_value_set_static_string           (GValue *value,
                                                         const gchar *v_string);

Set the contents of a G_TYPE_STRING GValue to v_string. The string is assumed to be static, and is thus not duplicated when setting the GValue.

value : | a valid GValue of type G_TYPE_STRING
v_string : | static string to be set

g_value_take_string ()

void                g_value_take_string                 (GValue *value,
                                                         gchar *v_string);

Sets the contents of a G_TYPE_STRING GValue to v_string.

value : | a valid GValue of type G_TYPE_STRING
v_string : | duplicated unowned string to be set

Since 2.4

g_value_set_string_take_ownership ()

void                g_value_set_string_take_ownership   (GValue *value,
                                                         gchar *v_string);

Warning

g_value_set_string_take_ownership has been deprecated since version 2.4 and should not be used in newly-written code. Use g_value_take_string() instead.

This is an internal function introduced mainly for C marshallers.

value : | a valid GValue of type G_TYPE_STRING
v_string : | duplicated unowned string to be set

g_value_get_string ()

const gchar*        g_value_get_string                  (const GValue *value);

Get the contents of a G_TYPE_STRING GValue.

value : | a valid GValue of type G_TYPE_STRING
Returns : | string content of value

g_value_dup_string ()

gchar*              g_value_dup_string                  (const GValue *value);

Get a copy the contents of a G_TYPE_STRING GValue.

value : | a valid GValue of type G_TYPE_STRING
Returns : | a newly allocated copy of the string content of value

G_IS_PARAM_SPEC_PARAM()

#define G_IS_PARAM_SPEC_PARAM(pspec)       (G_TYPE_CHECK_INSTANCE_TYPE ((pspec), G_TYPE_PARAM_PARAM))

Returns whether the given GParamSpec is of type G_TYPE_PARAM_PARAM.

pspec : a valid GParamSpec instance

G_PARAM_SPEC_PARAM()

#define G_PARAM_SPEC_PARAM(pspec)          (G_TYPE_CHECK_INSTANCE_CAST ((pspec), G_TYPE_PARAM_PARAM, GParamSpecParam))

Casts a GParamSpec instance into a GParamSpecParam.

pspec : a valid GParamSpec instance

G_VALUE_HOLDS_PARAM()

#define G_VALUE_HOLDS_PARAM(value)	(G_TYPE_CHECK_VALUE_TYPE ((value), G_TYPE_PARAM))

Return whether the given GValue can hold values derived from type G_TYPE_PARAM.

value : a valid GValue structure

G_TYPE_PARAM_PARAM

#define	G_TYPE_PARAM_PARAM		   (g_param_spec_types[15])

The GType of GParamSpecParam.

GParamSpecParam

typedef struct {
  GParamSpec    parent_instance;
} GParamSpecParam;

A GParamSpec derived structure that contains the meta data for G_TYPE_PARAM properties.

GParamSpec parent_instance; private GParamSpec portion

g_param_spec_param ()

GParamSpec*         g_param_spec_param                  (const gchar *name,
                                                         const gchar *nick,
                                                         const gchar *blurb,
                                                         GType param_type,
                                                         GParamFlags flags);

Creates a new GParamSpecParam instance specifying a G_TYPE_PARAM property.

See g_param_spec_internal() for details on property names.

name : | canonical name of the property specified
nick : | nick name for the property specified
blurb : | description of the property specified
param_type : | a GType derived from G_TYPE_PARAM
flags : | flags for the property specified
Returns : | a newly created parameter specification

g_value_set_param ()

void                g_value_set_param                   (GValue *value,
                                                         GParamSpec *param);

Set the contents of a G_TYPE_PARAM GValue to param.

value : | a valid GValue of type G_TYPE_PARAM
param : | the GParamSpec to be set

g_value_take_param ()

void                g_value_take_param                  (GValue *value,
                                                         GParamSpec *param);

Sets the contents of a G_TYPE_PARAM GValue to param and takes over the ownership of the callers reference to param; the caller doesn't have to unref it any more.

value : | a valid GValue of type G_TYPE_PARAM
param : | the GParamSpec to be set

Since 2.4

g_value_set_param_take_ownership ()

void                g_value_set_param_take_ownership    (GValue *value,
                                                         GParamSpec *param);

Warning

g_value_set_param_take_ownership has been deprecated since version 2.4 and should not be used in newly-written code. Use g_value_take_param() instead.

This is an internal function introduced mainly for C marshallers.

value : | a valid GValue of type G_TYPE_PARAM
param : | the GParamSpec to be set

g_value_get_param ()

GParamSpec*         g_value_get_param                   (const GValue *value);

Get the contents of a G_TYPE_PARAM GValue.

value : | a valid GValue whose type is derived from G_TYPE_PARAM
Returns : | GParamSpec content of value

g_value_dup_param ()

GParamSpec*         g_value_dup_param                   (const GValue *value);

Get the contents of a G_TYPE_PARAM GValue, increasing its reference count.

value : | a valid GValue whose type is derived from G_TYPE_PARAM
Returns : | GParamSpec content of value, should be unreferenced when no longer needed.

G_IS_PARAM_SPEC_BOXED()

#define G_IS_PARAM_SPEC_BOXED(pspec)       (G_TYPE_CHECK_INSTANCE_TYPE ((pspec), G_TYPE_PARAM_BOXED))

Return whether the given GParamSpec is of type G_TYPE_PARAM_BOXED.

pspec : a valid GParamSpec instance

G_PARAM_SPEC_BOXED()

#define G_PARAM_SPEC_BOXED(pspec)          (G_TYPE_CHECK_INSTANCE_CAST ((pspec), G_TYPE_PARAM_BOXED, GParamSpecBoxed))

Cast a GParamSpec instance into a GParamSpecBoxed.

pspec : a valid GParamSpec instance

G_VALUE_HOLDS_BOXED()

#define G_VALUE_HOLDS_BOXED(value) (G_TYPE_CHECK_VALUE_TYPE ((value), G_TYPE_BOXED))

Return whether the given GValue can hold values derived from type G_TYPE_BOXED.

value : a valid GValue structure

G_TYPE_PARAM_BOXED

#define	G_TYPE_PARAM_BOXED		   (g_param_spec_types[16])

The GType of GParamSpecBoxed.

GParamSpecBoxed

typedef struct {
  GParamSpec    parent_instance;
} GParamSpecBoxed;

A GParamSpec derived structure that contains the meta data for boxed properties.

GParamSpec parent_instance; private GParamSpec portion

g_param_spec_boxed ()

GParamSpec*         g_param_spec_boxed                  (const gchar *name,
                                                         const gchar *nick,
                                                         const gchar *blurb,
                                                         GType boxed_type,
                                                         GParamFlags flags);

Creates a new GParamSpecBoxed instance specifying a G_TYPE_BOXED derived property.

See g_param_spec_internal() for details on property names.

name : | canonical name of the property specified
nick : | nick name for the property specified
blurb : | description of the property specified
boxed_type : | G_TYPE_BOXED derived type of this property
flags : | flags for the property specified
Returns : | a newly created parameter specification

g_value_set_boxed ()

void                g_value_set_boxed                   (GValue *value,
                                                         gconstpointer v_boxed);

Set the contents of a G_TYPE_BOXED derived GValue to v_boxed.

value : | a valid GValue of G_TYPE_BOXED derived type
v_boxed : | boxed value to be set

g_value_set_static_boxed ()

void                g_value_set_static_boxed            (GValue *value,
                                                         gconstpointer v_boxed);

Set the contents of a G_TYPE_BOXED derived GValue to v_boxed. The boxed value is assumed to be static, and is thus not duplicated when setting the GValue.

value : | a valid GValue of G_TYPE_BOXED derived type
v_boxed : | static boxed value to be set

g_value_take_boxed ()

void                g_value_take_boxed                  (GValue *value,
                                                         gconstpointer v_boxed);

Sets the contents of a G_TYPE_BOXED derived GValue to v_boxed and takes over the ownership of the callers reference to v_boxed; the caller doesn't have to unref it any more.

value : | a valid GValue of G_TYPE_BOXED derived type
v_boxed : | duplicated unowned boxed value to be set

Since 2.4

g_value_set_boxed_take_ownership ()

void                g_value_set_boxed_take_ownership    (GValue *value,
                                                         gconstpointer v_boxed);

Warning

g_value_set_boxed_take_ownership has been deprecated since version 2.4 and should not be used in newly-written code. Use g_value_take_boxed() instead.

This is an internal function introduced mainly for C marshallers.

value : | a valid GValue of G_TYPE_BOXED derived type
v_boxed : | duplicated unowned boxed value to be set

g_value_get_boxed ()

gpointer            g_value_get_boxed                   (const GValue *value);

Get the contents of a G_TYPE_BOXED derived GValue.

value : | a valid GValue of G_TYPE_BOXED derived type
Returns : | boxed contents of value

g_value_dup_boxed ()

gpointer            g_value_dup_boxed                   (const GValue *value);

Get the contents of a G_TYPE_BOXED derived GValue. Upon getting, the boxed value is duplicated and needs to be later freed with g_boxed_free(), e.g. like: g_boxed_free (G_VALUE_TYPE (value), return_value);

value : | a valid GValue of G_TYPE_BOXED derived type
Returns : | boxed contents of value

G_IS_PARAM_SPEC_POINTER()

#define G_IS_PARAM_SPEC_POINTER(pspec)     (G_TYPE_CHECK_INSTANCE_TYPE ((pspec), G_TYPE_PARAM_POINTER))

Returns whether the given GParamSpec is of type G_TYPE_PARAM_POINTER.

pspec : a valid GParamSpec instance

G_PARAM_SPEC_POINTER()

#define G_PARAM_SPEC_POINTER(pspec)        (G_TYPE_CHECK_INSTANCE_CAST ((pspec), G_TYPE_PARAM_POINTER, GParamSpecPointer))

Casts a GParamSpec instance into a GParamSpecPointer.

pspec : a valid GParamSpec instance

G_VALUE_HOLDS_POINTER()

#define G_VALUE_HOLDS_POINTER(value)	 (G_TYPE_CHECK_VALUE_TYPE ((value), G_TYPE_POINTER))

Return whether the given GValue can hold values of type G_TYPE_POINTER.

value : a valid GValue structure

G_TYPE_PARAM_POINTER

#define	G_TYPE_PARAM_POINTER		   (g_param_spec_types[17])

The GType of GParamSpecPointer.

GParamSpecPointer

typedef struct {
  GParamSpec    parent_instance;
} GParamSpecPointer;

A GParamSpec derived structure that contains the meta data for pointer properties.

GParamSpec parent_instance; private GParamSpec portion

g_param_spec_pointer ()

GParamSpec*         g_param_spec_pointer                (const gchar *name,
                                                         const gchar *nick,
                                                         const gchar *blurb,
                                                         GParamFlags flags);

Creates a new GParamSpecPoiner instance specifying a pointer property.

See g_param_spec_internal() for details on property names.

name : | canonical name of the property specified
nick : | nick name for the property specified
blurb : | description of the property specified
flags : | flags for the property specified
Returns : | a newly created parameter specification

g_value_set_pointer ()

void                g_value_set_pointer                 (GValue *value,
                                                         gpointer v_pointer);

Set the contents of a pointer GValue to v_pointer.

value : | a valid GValue of G_TYPE_POINTER
v_pointer : | pointer value to be set

g_value_get_pointer ()

gpointer            g_value_get_pointer                 (const GValue *value);

Get the contents of a pointer GValue.

value : | a valid GValue of G_TYPE_POINTER
Returns : | pointer contents of value

G_IS_PARAM_SPEC_OBJECT()

#define G_IS_PARAM_SPEC_OBJECT(pspec)      (G_TYPE_CHECK_INSTANCE_TYPE ((pspec), G_TYPE_PARAM_OBJECT))

Returns whether the given GParamSpec is of type G_TYPE_PARAM_OBJECT.

pspec : a valid GParamSpec instance

G_PARAM_SPEC_OBJECT()

#define G_PARAM_SPEC_OBJECT(pspec)         (G_TYPE_CHECK_INSTANCE_CAST ((pspec), G_TYPE_PARAM_OBJECT, GParamSpecObject))

Casts a GParamSpec instance into a GParamSpecObject.

pspec : a valid GParamSpec instance

G_VALUE_HOLDS_OBJECT()

#define G_VALUE_HOLDS_OBJECT(value) (G_TYPE_CHECK_VALUE_TYPE ((value), G_TYPE_OBJECT))

Return whether the given GValue can hold values derived from type G_TYPE_OBJECT.

value : a valid GValue structure

G_TYPE_PARAM_OBJECT

#define	G_TYPE_PARAM_OBJECT		   (g_param_spec_types[19])

The GType of GParamSpecObject.

GParamSpecObject

typedef struct {
  GParamSpec    parent_instance;
} GParamSpecObject;

A GParamSpec derived structure that contains the meta data for object properties.

GParamSpec parent_instance; private GParamSpec portion

g_param_spec_object ()

GParamSpec*         g_param_spec_object                 (const gchar *name,
                                                         const gchar *nick,
                                                         const gchar *blurb,
                                                         GType object_type,
                                                         GParamFlags flags);

Creates a new GParamSpecBoxed instance specifying a G_TYPE_OBJECT derived property.

See g_param_spec_internal() for details on property names.

name : | canonical name of the property specified
nick : | nick name for the property specified
blurb : | description of the property specified
object_type : | G_TYPE_OBJECT derived type of this property
flags : | flags for the property specified
Returns : | a newly created parameter specification

g_value_set_object ()

void                g_value_set_object                  (GValue *value,
                                                         gpointer v_object);

Set the contents of a G_TYPE_OBJECT derived GValue to v_object.

value : | a valid GValue of G_TYPE_OBJECT derived type
v_object : | object value to be set

g_value_take_object ()

void                g_value_take_object                 (GValue *value,
                                                         gpointer v_object);

Sets the contents of a G_TYPE_OBJECT derived GValue to v_object and takes over the ownership of the callers reference to v_object; the caller doesn't have to unref it any more.

value : | a valid GValue of G_TYPE_OBJECT derived type
v_object : | object value to be set

Since 2.4

g_value_set_object_take_ownership ()

void                g_value_set_object_take_ownership   (GValue *value,
                                                         gpointer v_object);

Warning

g_value_set_object_take_ownership has been deprecated since version 2.4 and should not be used in newly-written code. Use g_value_take_object() instead.

This is an internal function introduced mainly for C marshallers.

value : | a valid GValue of G_TYPE_OBJECT derived type
v_object : | object value to be set

g_value_get_object ()

gpointer            g_value_get_object                  (const GValue *value);

Get the contents of a G_TYPE_OBJECT derived GValue.

value : | a valid GValue of G_TYPE_OBJECT derived type
Returns : | object contents of value

g_value_dup_object ()

GObject*            g_value_dup_object                  (const GValue *value);

Get the contents of a G_TYPE_OBJECT derived GValue, increasing its reference count.

value : | a valid GValue whose type is derived from G_TYPE_OBJECT
Returns : | object content of value, should be unreferenced when no longer needed.

G_IS_PARAM_SPEC_UNICHAR()

#define G_IS_PARAM_SPEC_UNICHAR(pspec)     (G_TYPE_CHECK_INSTANCE_TYPE ((pspec), G_TYPE_PARAM_UNICHAR))

Return whether the given GParamSpec is of type G_TYPE_PARAM_UNICHAR.

pspec : a valid GParamSpec instance

G_PARAM_SPEC_UNICHAR()

#define G_PARAM_SPEC_UNICHAR(pspec)        (G_TYPE_CHECK_INSTANCE_CAST ((pspec), G_TYPE_PARAM_UNICHAR, GParamSpecUnichar))

Cast a GParamSpec instance into a GParamSpecUnichar.

pspec : a valid GParamSpec instance

G_TYPE_PARAM_UNICHAR

#define	G_TYPE_PARAM_UNICHAR		   (g_param_spec_types[9])

The GType of GParamSpecUnichar.

GParamSpecUnichar

typedef struct {
  GParamSpec    parent_instance;

  gunichar      default_value;
} GParamSpecUnichar;

A GParamSpec derived structure that contains the meta data for unichar (unsigned integer) properties.

GParamSpec parent_instance; | private GParamSpec portion
gunichar default_value; | default value for the property specified

g_param_spec_unichar ()

GParamSpec*         g_param_spec_unichar                (const gchar *name,
                                                         const gchar *nick,
                                                         const gchar *blurb,
                                                         gunichar default_value,
                                                         GParamFlags flags);

Creates a new GParamSpecUnichar instance specifying a G_TYPE_UINT property. GValue structures for this property can be accessed with g_value_set_uint() and g_value_get_uint().

See g_param_spec_internal() for details on property names.

name : | canonical name of the property specified
nick : | nick name for the property specified
blurb : | description of the property specified
default_value : | default value for the property specified
flags : | flags for the property specified
Returns : | a newly created parameter specification

G_IS_PARAM_SPEC_VALUE_ARRAY()

#define G_IS_PARAM_SPEC_VALUE_ARRAY(pspec) (G_TYPE_CHECK_INSTANCE_TYPE ((pspec), G_TYPE_PARAM_VALUE_ARRAY))

Return whether the given GParamSpec is of type G_TYPE_PARAM_VALUE_ARRAY.

pspec : a valid GParamSpec instance

G_PARAM_SPEC_VALUE_ARRAY()

#define G_PARAM_SPEC_VALUE_ARRAY(pspec)    (G_TYPE_CHECK_INSTANCE_CAST ((pspec), G_TYPE_PARAM_VALUE_ARRAY, GParamSpecValueArray))

Cast a GParamSpec instance into a GParamSpecValueArray.

pspec : a valid GParamSpec instance

G_TYPE_PARAM_VALUE_ARRAY

#define	G_TYPE_PARAM_VALUE_ARRAY	   (g_param_spec_types[18])

The GType of GParamSpecValueArray.

GParamSpecValueArray

typedef struct {
  GParamSpec    parent_instance;
  GParamSpec   *element_spec;
  guint		fixed_n_elements;
} GParamSpecValueArray;

A GParamSpec derived structure that contains the meta data for GValueArray properties.

GParamSpec parent_instance; | private GParamSpec portion
GParamSpec *element_spec; | a GParamSpec describing the elements contained in arrays of this property, may be NULL
guint fixed_n_elements; | if greater than 0, arrays of this property will always have this many elements

g_param_spec_value_array ()

GParamSpec*         g_param_spec_value_array            (const gchar *name,
                                                         const gchar *nick,
                                                         const gchar *blurb,
                                                         GParamSpec *element_spec,
                                                         GParamFlags flags);

Creates a new GParamSpecValueArray instance specifying a G_TYPE_VALUE_ARRAY property. G_TYPE_VALUE_ARRAY is a G_TYPE_BOXED type, as such, GValue structures for this property can be accessed with g_value_set_boxed() and g_value_get_boxed().

See g_param_spec_internal() for details on property names.

name : | canonical name of the property specified
nick : | nick name for the property specified
blurb : | description of the property specified
element_spec : | a GParamSpec describing the elements contained in arrays of this property, may be NULL
flags : | flags for the property specified
Returns : | a newly created parameter specification

G_IS_PARAM_SPEC_OVERRIDE()

#define G_IS_PARAM_SPEC_OVERRIDE(pspec)    (G_TYPE_CHECK_INSTANCE_TYPE ((pspec), G_TYPE_PARAM_OVERRIDE))

Returns whether the given GParamSpec is of type G_TYPE_PARAM_OVERRIDE.

pspec : a GParamSpec

Since 2.4

G_PARAM_SPEC_OVERRIDE()

#define G_PARAM_SPEC_OVERRIDE(pspec)       (G_TYPE_CHECK_INSTANCE_CAST ((pspec), G_TYPE_PARAM_OVERRIDE, GParamSpecOverride))

Casts a GParamSpec into a GParamSpecOverride.

pspec : a GParamSpec

Since 2.4

G_TYPE_PARAM_OVERRIDE

#define	G_TYPE_PARAM_OVERRIDE		   (g_param_spec_types[20])

The GType of GParamSpecOverride.

Since 2.4

GParamSpecOverride

typedef struct {
} GParamSpecOverride;

This is a type of GParamSpec type that simply redirects operations to another paramspec. All operations other than getting or setting the value are redirected, including accessing the nick and blurb, validating a value, and so forth. See g_param_spec_get_redirect_target() for retrieving the overidden property. GParamSpecOverride is used in implementing g_object_class_override_property(), and will not be directly useful unless you are implementing a new base type similar to GObject.

Since 2.4

g_param_spec_override ()

GParamSpec*         g_param_spec_override               (const gchar *name,
                                                         GParamSpec *overridden);

Creates a new property of type GParamSpecOverride. This is used to direct operations to another paramspec, and will not be directly useful unless you are implementing a new base type similar to GObject.

name : | the name of the property.
overridden : | The property that is being overridden
Returns : | the newly created GParamSpec

Since 2.4

G_IS_PARAM_SPEC_GTYPE()

#define G_IS_PARAM_SPEC_GTYPE(pspec)       (G_TYPE_CHECK_INSTANCE_TYPE ((pspec), G_TYPE_PARAM_GTYPE))

Returns whether the given GParamSpec is of type G_TYPE_PARAM_GTYPE.

pspec : a GParamSpec

Since 2.10

G_PARAM_SPEC_GTYPE()

#define G_PARAM_SPEC_GTYPE(pspec)          (G_TYPE_CHECK_INSTANCE_CAST ((pspec), G_TYPE_PARAM_GTYPE, GParamSpecGType))

Casts a GParamSpec into a GParamSpecGType.

pspec : a GParamSpec

Since 2.10

G_VALUE_HOLDS_GTYPE()

#define G_VALUE_HOLDS_GTYPE(value)	 (G_TYPE_CHECK_VALUE_TYPE ((value), G_TYPE_GTYPE))

Returns whether the given GValue can hold values of type G_TYPE_GTYPE.

value : a valid GValue structure

Since 2.12

G_TYPE_PARAM_GTYPE

#define	G_TYPE_PARAM_GTYPE		   (g_param_spec_types[21])

The GType of GParamSpecGType.

Since 2.10

GParamSpecGType

typedef struct {
  GParamSpec    parent_instance;
  GType         is_a_type;
} GParamSpecGType;

A GParamSpec derived structure that contains the meta data for GType properties.

GParamSpec parent_instance; | private GParamSpec portion
GType is_a_type; | a GType whose subtypes can occur as values

Since 2.10

g_param_spec_gtype ()

GParamSpec*         g_param_spec_gtype                  (const gchar *name,
                                                         const gchar *nick,
                                                         const gchar *blurb,
                                                         GType is_a_type,
                                                         GParamFlags flags);

Creates a new GParamSpecGType instance specifying a G_TYPE_GTYPE property.

See g_param_spec_internal() for details on property names.

name : | canonical name of the property specified
nick : | nick name for the property specified
blurb : | description of the property specified
is_a_type : | a GType whose subtypes are allowed as values of the property (use G_TYPE_NONE for any type)
flags : | flags for the property specified
Returns : | a newly created parameter specification

Since 2.10

g_value_get_gtype ()

GType               g_value_get_gtype                   (const GValue *value);

Get the contents of a G_TYPE_GTYPE GValue.

value : | a valid GValue of type G_TYPE_GTYPE
Returns : | the GType stored in value

Since 2.12

g_value_set_gtype ()

void                g_value_set_gtype                   (GValue *value,
                                                         GType v_gtype);

Set the contents of a G_TYPE_GTYPE GValue to v_gtype.

value : | a valid GValue of type G_TYPE_GTYPE
v_gtype : | GType to be set

Since 2.12

See Also

GParamSpec, GValue, g_object_class_install_property().


GObject

GObject — The base object type

Synopsis

#include <glib-object.h>

                    GObject;
                    GObjectClass;
                    GObjectConstructParam;
void                (*GObjectGetPropertyFunc)           (GObject *object,
                                                         guint property_id,
                                                         GValue *value,
                                                         GParamSpec *pspec);
void                (*GObjectSetPropertyFunc)           (GObject *object,
                                                         guint property_id,
                                                         const GValue *value,
                                                         GParamSpec *pspec);
void                (*GObjectFinalizeFunc)              (GObject *object);
#define             G_TYPE_IS_OBJECT                    (type)
#define             G_OBJECT                            (object)
#define             G_IS_OBJECT                         (object)
#define             G_OBJECT_CLASS                      (class)
#define             G_IS_OBJECT_CLASS                   (class)
#define             G_OBJECT_GET_CLASS                  (object)
#define             G_OBJECT_TYPE                       (object)
#define             G_OBJECT_TYPE_NAME                  (object)
#define             G_OBJECT_CLASS_TYPE                 (class)
#define             G_OBJECT_CLASS_NAME                 (class)
void                g_object_class_install_property     (GObjectClass *oclass,
                                                         guint property_id,
                                                         GParamSpec *pspec);
GParamSpec*         g_object_class_find_property        (GObjectClass *oclass,
                                                         const gchar *property_name);
GParamSpec**        g_object_class_list_properties      (GObjectClass *oclass,
                                                         guint *n_properties);
void                g_object_class_override_property    (GObjectClass *oclass,
                                                         guint property_id,
                                                         const gchar *name);
void                g_object_interface_install_property (gpointer g_iface,
                                                         GParamSpec *pspec);
GParamSpec*         g_object_interface_find_property    (gpointer g_iface,
                                                         const gchar *property_name);
GParamSpec**        g_object_interface_list_properties  (gpointer g_iface,
                                                         guint *n_properties_p);
gpointer            g_object_new                        (GType object_type,
                                                         const gchar *first_property_name,
                                                         ...);
gpointer            g_object_newv                       (GType object_type,
                                                         guint n_parameters,
                                                         GParameter *parameters);
                    GParameter;
gpointer            g_object_ref                        (gpointer object);
void                g_object_unref                      (gpointer object);
gpointer            g_object_ref_sink                   (gpointer object);
typedef             GInitiallyUnowned;
typedef             GInitiallyUnownedClass;
#define             G_TYPE_INITIALLY_UNOWNED
gboolean            g_object_is_floating                (gpointer object);
void                g_object_force_floating             (GObject *object);
void                (*GWeakNotify)                      (gpointer data,
                                                         GObject *where_the_object_was);
void                g_object_weak_ref                   (GObject *object,
                                                         GWeakNotify notify,
                                                         gpointer data);
void                g_object_weak_unref                 (GObject *object,
                                                         GWeakNotify notify,
                                                         gpointer data);
void                g_object_add_weak_pointer           (GObject *object,
                                                         gpointer *weak_pointer_location);
void                g_object_remove_weak_pointer        (GObject *object,
                                                         gpointer *weak_pointer_location);
void                (*GToggleNotify)                    (gpointer data,
                                                         GObject *object,
                                                         gboolean is_last_ref);
void                g_object_add_toggle_ref             (GObject *object,
                                                         GToggleNotify notify,
                                                         gpointer data);
void                g_object_remove_toggle_ref          (GObject *object,
                                                         GToggleNotify notify,
                                                         gpointer data);
gpointer            g_object_connect                    (gpointer object,
                                                         const gchar *signal_spec,
                                                         ...);
void                g_object_disconnect                 (gpointer object,
                                                         const gchar *signal_spec,
                                                         ...);
void                g_object_set                        (gpointer object,
                                                         const gchar *first_property_name,
                                                         ...);
void                g_object_get                        (gpointer object,
                                                         const gchar *first_property_name,
                                                         ...);
void                g_object_notify                     (GObject *object,
                                                         const gchar *property_name);
void                g_object_freeze_notify              (GObject *object);
void                g_object_thaw_notify                (GObject *object);
gpointer            g_object_get_data                   (GObject *object,
                                                         const gchar *key);
void                g_object_set_data                   (GObject *object,
                                                         const gchar *key,
                                                         gpointer data);
void                g_object_set_data_full              (GObject *object,
                                                         const gchar *key,
                                                         gpointer data,
                                                         GDestroyNotify destroy);
gpointer            g_object_steal_data                 (GObject *object,
                                                         const gchar *key);
gpointer            g_object_get_qdata                  (GObject *object,
                                                         GQuark quark);
void                g_object_set_qdata                  (GObject *object,
                                                         GQuark quark,
                                                         gpointer data);
void                g_object_set_qdata_full             (GObject *object,
                                                         GQuark quark,
                                                         gpointer data,
                                                         GDestroyNotify destroy);
gpointer            g_object_steal_qdata                (GObject *object,
                                                         GQuark quark);
void                g_object_set_property               (GObject *object,
                                                         const gchar *property_name,
                                                         const GValue *value);
void                g_object_get_property               (GObject *object,
                                                         const gchar *property_name,
                                                         GValue *value);
GObject*            g_object_new_valist                 (GType object_type,
                                                         const gchar *first_property_name,
                                                         va_list var_args);
void                g_object_set_valist                 (GObject *object,
                                                         const gchar *first_property_name,
                                                         va_list var_args);
void                g_object_get_valist                 (GObject *object,
                                                         const gchar *first_property_name,
                                                         va_list var_args);
void                g_object_watch_closure              (GObject *object,
                                                         GClosure *closure);
void                g_object_run_dispose                (GObject *object);
#define             G_OBJECT_WARN_INVALID_PROPERTY_ID   (object, property_id, pspec)

Object Hierarchy

  GObject
   +----GTypeModule

Signals

  "notify"                                         : Run First / No Recursion / Has Details / Action / No Hooks

Description

GObject is the fundamental type providing the common attributes and methods for all object types in GTK+, Pango and other libraries based on GObject. The GObject class provides methods for object construction and destruction, property access methods, and signal support. Signals are described in detail in Signals(3).

GInitiallyUnowned is derived from GObject. The only difference between the two is that the initial reference of a GInitiallyUnowned is flagged as a floating reference. This means that it is not specifically claimed to be "owned" by any code portion. The main motivation for providing floating references is C convenience. In particular, it allows code to be written as:

Example 1.

  container = create_container();
  container_add_child (container, create_child());

If container_add_child() will g_object_ref_sink() the passed in child, no reference of the newly created child is leaked. Without floating references, container_add_child() can only g_object_ref() the new child, so to implement this code without reference leaks, it would have to be written as:

Example 2.

  Child *child;
  container = create_container();
  child = create_child();
  container_add_child (container, child);
  g_object_unref (child);

The floating reference can be converted into an ordinary reference by calling g_object_ref_sink(). For already sunken objects (objects that don't have a floating reference anymore), g_object_ref_sink() is equivalent to g_object_ref() and returns a new reference. Since floating references are useful almost exclusively for C convenience, language bindings that provide automated reference and memory ownership maintenance (such as smart pointers or garbage collection) therefore don't need to expose floating references in their API.

Some object implementations may need to save an objects floating state across certain code portions (an example is GtkMenu), to achive this, the following sequence can be used:

Example 3.

  /* save floating state */
  gboolean was_floating = g_object_is_floating (object);
  g_object_ref_sink (object);
  /* protected code portion */
  ...;
  /* restore floating state */
  if (was_floating)
    g_object_force_floating (object);
  g_obejct_unref (object); /* release previously acquired reference */

Details

GObject

typedef struct _GObject GObject;

All the fields in the GObject structure are private to the GObject implementation and should never be accessed directly.

GObjectClass

typedef struct {
  GTypeClass   g_type_class;

  /* overridable methods */
  GObject*   (*constructor)     (GType                  type,
                                 guint                  n_construct_properties,
                                 GObjectConstructParam *construct_properties);
  void       (*set_property)		(GObject        *object,
                                         guint           property_id,
                                         const GValue   *value,
                                         GParamSpec     *pspec);
  void       (*get_property)		(GObject        *object,
                                         guint           property_id,
                                         GValue         *value,
                                         GParamSpec     *pspec);
  void       (*dispose)			(GObject        *object);
  void       (*finalize)		(GObject        *object);

  /* seldomly overidden */
  void       (*dispatch_properties_changed) (GObject      *object,
                         guint	   n_pspecs,
                         GParamSpec  **pspecs);

  /* signals */
  void	     (*notify)			(GObject	*object,
                     GParamSpec	*pspec);
} GObjectClass;

The class structure for the GObject type.

Example 4. Implementing singletons using a constructor

static MySingleton *the_singleton = NULL;

static GObject*
my_singleton_constructor (GType                  type,
                          guint                  n_construct_params,
                          GObjectConstructParam *construct_params)
{
  GObject *object;

  if (!the_singleton)
    {
      object = G_OBJECT_CLASS (parent_class)->constructor (type,
                                                           n_construct_params,
                                                           construct_params);
      the_singleton = MY_SINGLETON (object);
    }
  else
    object = g_object_ref (G_OBJECT (the_singleton));

  return object;
}

GTypeClass g_type_class; | the parent class
constructor () | the constructor function is called by g_object_new() to complete the object initialization after all the construction properties are set. The first thing a constructor implementation must do is chain up to the constructor of the parent class. Overriding constructor should be rarely needed, e.g. to handle construct properties, or to implement singletons.
set_property () | the generic setter for all properties of this type. Should be overridden for every type with properties. Implementations of set_property don't need to emit property change notification explicitly, this is handled by the type system.
get_property () | the generic getter for all properties of this type. Should be overridden for every type with properties.
dispose () | the dispose function is supposed to drop all references to other objects, but keep the instance otherwise intact, so that client method invocations still work. It may be run multiple times (due to reference loops). Before returning, dispose should chain up to the dispose method of the parent class.
finalize () | instance finalization function, should finish the finalization of the instance begun in dispose and chain up to the finalize method of the parent class.
dispatch_properties_changed () | emits property change notification for a bunch of properties. Overriding dispatch_properties_changed should be rarely needed.
notify () | the class closure for the notify signal

GObjectConstructParam

typedef struct {
  GParamSpec *pspec;
  GValue     *value;
} GObjectConstructParam;

The GObjectConstructParam struct is an auxiliary structure used to hand GParamSpec/GValue pairs to the constructor of a GObjectClass.

GParamSpec *pspec; | the GParamSpec of the construct parameter
GValue *value; | the value to set the parameter to

GObjectGetPropertyFunc ()

void                (*GObjectGetPropertyFunc)           (GObject *object,
                                                         guint property_id,
                                                         GValue *value,
                                                         GParamSpec *pspec);

The type of the get_property function of GObjectClass.

object : | a GObject
property_id : | the numeric id under which the property was registered with g_object_class_install_property().
value : | a GValue to return the property value in
pspec : | the GParamSpec describing the property

GObjectSetPropertyFunc ()

void                (*GObjectSetPropertyFunc)           (GObject *object,
                                                         guint property_id,
                                                         const GValue *value,
                                                         GParamSpec *pspec);

The type of the set_property function of GObjectClass.

object : | a GObject
property_id : | the numeric id under which the property was registered with g_object_class_install_property().
value : | the new value for the property
pspec : | the GParamSpec describing the property

GObjectFinalizeFunc ()

void                (*GObjectFinalizeFunc)              (GObject *object);

The type of the finalize function of GObjectClass.

object : the GObject being finalized

G_TYPE_IS_OBJECT()

#define G_TYPE_IS_OBJECT(type)      (G_TYPE_FUNDAMENTAL (type) == G_TYPE_OBJECT)

Returns a boolean value of FALSE or TRUE indicating whether the passed in type id is a G_TYPE_OBJECT or derived from it.

type : | Type id to check for is a G_TYPE_OBJECT relationship.
Returns : | FALSE or TRUE, indicating whether type is a G_TYPE_OBJECT.

G_OBJECT()

#define G_OBJECT(object)            (G_TYPE_CHECK_INSTANCE_CAST ((object), G_TYPE_OBJECT, GObject))

Casts a GObject or derived pointer into a (GObject*) pointer. Depending on the current debugging level, this function may invoke certain runtime checks to identify invalid casts.

object : Object which is subject to casting.

G_IS_OBJECT()

#define G_IS_OBJECT(object)         (G_TYPE_CHECK_INSTANCE_TYPE ((object), G_TYPE_OBJECT))

Checks whether a valid GTypeInstance pointer is of type G_TYPE_OBJECT.

object : Instance to check for being a G_TYPE_OBJECT.

G_OBJECT_CLASS()

#define G_OBJECT_CLASS(class)       (G_TYPE_CHECK_CLASS_CAST ((class), G_TYPE_OBJECT, GObjectClass))

Casts a derived GObjectClass structure into a GObjectClass structure.

class : a valid GObjectClass

G_IS_OBJECT_CLASS()

#define G_IS_OBJECT_CLASS(class)    (G_TYPE_CHECK_CLASS_TYPE ((class), G_TYPE_OBJECT))

Checks whether class "is a" valid GObjectClass structure of type G_TYPE_OBJECT or derived.

class : a GObjectClass

G_OBJECT_GET_CLASS()

#define G_OBJECT_GET_CLASS(object)  (G_TYPE_INSTANCE_GET_CLASS ((object), G_TYPE_OBJECT, GObjectClass))

Returns the class structure associated to a GObject instance.

object : a GObject instance.

G_OBJECT_TYPE()

#define G_OBJECT_TYPE(object)       (G_TYPE_FROM_INSTANCE (object))

Return the type id of an object.

object : | Object to return the type id for.
Returns : | Type id of object.

G_OBJECT_TYPE_NAME()

#define G_OBJECT_TYPE_NAME(object)  (g_type_name (G_OBJECT_TYPE (object)))

Returns the name of an object's type.

object : | Object to return the type name for.
Returns : | Type name of object. The string is owned by the type system and should not be freed.

G_OBJECT_CLASS_TYPE()

#define G_OBJECT_CLASS_TYPE(class)  (G_TYPE_FROM_CLASS (class))

Return the type id of a class structure.

class : | a valid GObjectClass
Returns : | Type id of class.

G_OBJECT_CLASS_NAME()

#define G_OBJECT_CLASS_NAME(class)  (g_type_name (G_OBJECT_CLASS_TYPE (class)))

Return the name of a class structure's type.

class : | a valid GObjectClass
Returns : | Type name of class. The string is owned by the type system and should not be freed.

g_object_class_install_property ()

void                g_object_class_install_property     (GObjectClass *oclass,
                                                         guint property_id,
                                                         GParamSpec *pspec);

Installs a new property. This is usually done in the class initializer.

oclass : | a GObjectClass
property_id : | the id for the new property
pspec : | the GParamSpec for the new property

g_object_class_find_property ()

GParamSpec*         g_object_class_find_property        (GObjectClass *oclass,
                                                         const gchar *property_name);

Looks up the GParamSpec for a property of a class.

oclass : | a GObjectClass
property_name : | the name of the property to look up
Returns : | the GParamSpec for the property, or NULL if the class doesn't have a property of that name

g_object_class_list_properties ()

GParamSpec**        g_object_class_list_properties      (GObjectClass *oclass,
                                                         guint *n_properties);

Returns an array of GParamSpec* for all properties of a class.

oclass : | a GObjectClass
n_properties : | return location for the length of the returned array
Returns : | an array of GParamSpec* which should be freed after use

g_object_class_override_property ()

void                g_object_class_override_property    (GObjectClass *oclass,
                                                         guint property_id,
                                                         const gchar *name);

Registers property_id as referring to a property with the name name in a parent class or in an interface implemented by oclass. This allows this class to override a property implementation in a parent class or to provide the implementation of a property from an interface.

Note

Internally, overriding is implemented by creating a property of type GParamSpecOverride; generally operations that query the properties of the object class, such as g_object_class_find_property() or g_object_class_list_properties() will return the overridden property. However, in one case, the construct_properties argument of the constructor virtual function, the GParamSpecOverride is passed instead, so that the param_id field of the GParamSpec will be correct. For virtually all uses, this makes no difference. If you need to get the overridden property, you can call g_param_spec_get_redirect_target().

oclass : | a GObjectClass
property_id : | the new property ID
name : | the name of a property registered in a parent class or in an interface of this class.

g_object_interface_install_property ()

void                g_object_interface_install_property (gpointer g_iface,
                                                         GParamSpec *pspec);

Add a property to an interface; this is only useful for interfaces that are added to GObject-derived types. Adding a property to an interface forces all objects classes with that interface to have a compatible property. The compatible property could be a newly created GParamSpec, but normally g_object_class_override_property() will be used so that the object class only needs to provide an implementation and inherits the property description, default value, bounds, and so forth from the interface property.

This function is meant to be called from the interface's default vtable initialization function (the class_init member of GTypeInfo.) It must not be called after after class_init has been called for any object types implementing this interface.

g_iface : | any interface vtable for the interface, or the default vtable for the interface.
pspec : | the GParamSpec for the new property

Since 2.4

g_object_interface_find_property ()

GParamSpec*         g_object_interface_find_property    (gpointer g_iface,
                                                         const gchar *property_name);

Find the GParamSpec with the given name for an interface. Generally, the interface vtable passed in as g_iface will be the default vtable from g_type_default_interface_ref(), or, if you know the interface has already been loaded, g_type_default_interface_peek().

g_iface : | any interface vtable for the interface, or the default vtable for the interface
property_name : | name of a property to lookup.
Returns : | the GParamSpec for the property of the interface with the name property_name, or NULL if no such property exists.

Since 2.4

g_object_interface_list_properties ()

GParamSpec**        g_object_interface_list_properties  (gpointer g_iface,
                                                         guint *n_properties_p);

Lists the properties of an interface.Generally, the interface vtable passed in as g_iface will be the default vtable from g_type_default_interface_ref(), or, if you know the interface has already been loaded, g_type_default_interface_peek().

g_iface : | any interface vtable for the interface, or the default vtable for the interface
n_properties_p : | location to store number of properties returned.
Returns : | a pointer to an array of pointers to GParamSpec structures. The paramspecs are owned by GLib, but the array should be freed with g_free() when you are done with it.

Since 2.4

g_object_new ()

gpointer            g_object_new                        (GType object_type,
                                                         const gchar *first_property_name,
                                                         ...);

Creates a new instance of a GObject subtype and sets its properties.

Construction parameters (see G_PARAM_CONSTRUCT, G_PARAM_CONSTRUCT_ONLY) which are not explicitly specified are set to their default values.

object_type : | the type id of the GObject subtype to instantiate
first_property_name : | the name of the first property
... : | the value of the first property, followed optionally by more name/value pairs, followed by NULL
Returns : | a new instance of object_type

g_object_newv ()

gpointer            g_object_newv                       (GType object_type,
                                                         guint n_parameters,
                                                         GParameter *parameters);

Creates a new instance of a GObject subtype and sets its properties.

Construction parameters (see G_PARAM_CONSTRUCT, G_PARAM_CONSTRUCT_ONLY) which are not explicitly specified are set to their default values.

object_type : | the type id of the GObject subtype to instantiate
n_parameters : | the length of the parameters array
parameters : | an array of GParameter
Returns : | a new instance of object_type

GParameter

typedef struct {
  const gchar *name;
  GValue       value;
} GParameter;

The GParameter struct is an auxiliary structure used to hand parameter name/value pairs to g_object_newv().

const gchar *name; | the parameter name
GValue value; | the parameter value

g_object_ref ()

gpointer            g_object_ref                        (gpointer object);

Increases the reference count of object.

object : | a GObject
Returns : | the same object

g_object_unref ()

void                g_object_unref                      (gpointer object);

Decreases the reference count of object. When its reference count drops to 0, the object is finalized (i.e. its memory is freed).

object : a GObject

g_object_ref_sink ()

gpointer            g_object_ref_sink                   (gpointer object);

Increase the reference count of object, and possibly remove the floating reference, if object has a floating reference.

In other words, if the object is floating, then this call "assumes ownership" of the floating reference, converting it to a normal reference by clearing the floating flag while leaving the reference count unchanged. If the object is not floating, then this call adds a new normal reference increasing the reference count by one.

object : | a GObject
Returns : | object

Since 2.10

GInitiallyUnowned

typedef struct _GObject                  GInitiallyUnowned;

All the fields in the GInitiallyUnowned structure are private to the GInitiallyUnowned implementation and should never be accessed directly.

GInitiallyUnownedClass

typedef struct _GObjectClass             GInitiallyUnownedClass;

The class structure for the GInitiallyUnowned type.

G_TYPE_INITIALLY_UNOWNED

#define G_TYPE_INITIALLY_UNOWNED	      (g_initially_unowned_get_type())

The type for GInitiallyUnowned.

g_object_is_floating ()

gboolean            g_object_is_floating                (gpointer object);

Checks wether object has a floating reference.

object : | a GObject
Returns : | TRUE if object has a floating reference

Since 2.10

g_object_force_floating ()

void                g_object_force_floating             (GObject *object);

This function is intended for GObject implementations to re-enforce a floating object reference. Doing this is seldomly required, all GInitiallyUnowneds are created with a floating reference which usually just needs to be sunken by calling g_object_ref_sink().

object : a GObject

Since 2.10

GWeakNotify ()

void                (*GWeakNotify)                      (gpointer data,
                                                         GObject *where_the_object_was);

A GWeakNotify function can be added to an object as a callback that gets triggered when the object is finalized. Since the object is already being finalized when the GWeakNotify is called, there's not much you could do with the object, apart from e.g. using its adress as hash-index or the like.

data : | data that was provided when the weak reference was established
where_the_object_was : | the object being finalized

g_object_weak_ref ()

void                g_object_weak_ref                   (GObject *object,
                                                         GWeakNotify notify,
                                                         gpointer data);

Adds a weak reference callback to an object. Weak references are used for notification when an object is finalized. They are called "weak references" because they allow you to safely hold a pointer to an object without calling g_object_ref() (g_object_ref() adds a strong reference, that is, forces the object to stay alive).

object : | GObject to reference weakly
notify : | callback to invoke before the object is freed
data : | extra data to pass to notify

g_object_weak_unref ()

void                g_object_weak_unref                 (GObject *object,
                                                         GWeakNotify notify,
                                                         gpointer data);

Removes a weak reference callback to an object.

object : | GObject to remove a weak reference from
notify : | callback to search for
data : | data to search for

g_object_add_weak_pointer ()

void                g_object_add_weak_pointer           (GObject *object,
                                                         gpointer *weak_pointer_location);

Adds a weak reference from weak_pointer to object to indicate that the pointer located at weak_pointer_location is only valid during the lifetime of object. When the object is finalized, weak_pointer will be set to NULL.

object : | The object that should be weak referenced.
weak_pointer_location : | The memory address of a pointer.

g_object_remove_weak_pointer ()

void                g_object_remove_weak_pointer        (GObject *object,
                                                         gpointer *weak_pointer_location);

Removes a weak reference from object that was previously added using g_object_add_weak_pointer(). The weak_pointer_location has to match the one used with g_object_add_weak_pointer().

object : | The object that is weak referenced.
weak_pointer_location : | The memory address of a pointer.

GToggleNotify ()

void                (*GToggleNotify)                    (gpointer data,
                                                         GObject *object,
                                                         gboolean is_last_ref);

A callback function used for notification when the state of a toggle reference changes. See g_object_add_toggle_ref().

data : | Callback data passed to g_object_add_toggle_ref()
object : | The object on which g_object_add_toggle_ref() was called.
is_last_ref : | TRUE if the toggle reference is now the last reference to the object. FALSE if the toggle reference was the last reference and there are now other references.

g_object_add_toggle_ref ()

void                g_object_add_toggle_ref             (GObject *object,
                                                         GToggleNotify notify,
                                                         gpointer data);

Increases the reference count of the object by one and sets a callback to be called when all other references to the object are dropped, or when this is already the last reference to the object and another reference is established.

This functionality is intended for binding object to a proxy object managed by another memory manager. This is done with two paired references: the strong reference added by g_object_add_toggle_ref() and a reverse reference to the proxy object which is either a strong reference or weak reference.

The setup is that when there are no other references to object, only a weak reference is held in the reverse direction from object to the proxy object, but when there are other references held to object, a strong reference is held. The notify callback is called when the reference from object to the proxy object should be toggled from strong to weak (is_last_ref true) or weak to strong (is_last_ref false).

Since a (normal) reference must be held to the object before calling g_object_toggle_ref(), the initial state of the reverse link is always strong.

Multiple toggle references may be added to the same gobject, however if there are multiple toggle references to an object, none of them will ever be notified until all but one are removed. For this reason, you should only ever use a toggle reference if there is important state in the proxy object.

object : | a GObject
notify : | a function to call when this reference is the last reference to the object, or is no longer the last reference.
data : | data to pass to notify

Since 2.8

g_object_remove_toggle_ref ()

void                g_object_remove_toggle_ref          (GObject *object,
                                                         GToggleNotify notify,
                                                         gpointer data);

Removes a reference added with g_object_add_toggle_ref(). The reference count of the object is decreased by one.

object : | a GObject
notify : | a function to call when this reference is the last reference to the object, or is no longer the last reference.
data : | data to pass to notify

Since 2.8

g_object_connect ()

gpointer            g_object_connect                    (gpointer object,
                                                         const gchar *signal_spec,
                                                         ...);

A convenience function to connect multiple signals at once.

The signal specs expected by this function have the form "modifier::signal_name", where modifier can be one of the following:

signal | equivalent to g_signal_connect_data (...)
object_signal, object-signal | equivalent to g_signal_connect_object (...)
swapped_signal, swapped-signal | equivalent to g_signal_connect_data (..., G_CONNECT_SWAPPED)
swapped_object_signal, swapped-object-signal | equivalent to g_signal_connect_object (..., G_CONNECT_SWAPPED)
signal_after, signal-after | equivalent to g_signal_connect_data (..., G_CONNECT_AFTER)
object_signal_after, object-signal-after | equivalent to g_signal_connect_object (..., G_CONNECT_AFTER)
swapped_signal_after, swapped-signal-after | equivalent to g_signal_connect_data (..., G_CONNECT_SWAPPED | G_CONNECT_AFTER)
swapped_object_signal_after, swapped-object-signal-after | equivalent to g_signal_connect_object (..., G_CONNECT_SWAPPED | G_CONNECT_AFTER)

  menu->toplevel = g_object_connect (g_object_new (GTK_TYPE_WINDOW,
                           "type", GTK_WINDOW_POPUP,
                           "child", menu,
                           NULL),
                     "signal::event", gtk_menu_window_event, menu,
                     "signal::size_request", gtk_menu_window_size_request, menu,
                     "signal::destroy", gtk_widget_destroyed, &menu->toplevel,
                     NULL);

object : | a GObject
signal_spec : | the spec for the first signal
... : | GCallback for the first signal, followed by data for the first signal, followed optionally by more signal spec/callback/data triples, followed by NULL
Returns : | object

g_object_disconnect ()

void                g_object_disconnect                 (gpointer object,
                                                         const gchar *signal_spec,
                                                         ...);

A convenience function to disconnect multiple signals at once.

The signal specs expected by this function have the form "any_signal", which means to disconnect any signal with matching callback and data, or "any_signal::signal_name", which only disconnects the signal named "signal_name".

object : | a GObject
signal_spec : | the spec for the first signal
... : | GCallback for the first signal, followed by data for the first signal, followed optionally by more signal spec/callback/data triples, followed by NULL

g_object_set ()

void                g_object_set                        (gpointer object,
                                                         const gchar *first_property_name,
                                                         ...);

Sets properties on an object.

object : | a GObject
first_property_name : | name of the first property to set
... : | value for the first property, followed optionally by more name/value pairs, followed by NULL

g_object_get ()

void                g_object_get                        (gpointer object,
                                                         const gchar *first_property_name,
                                                         ...);

Gets properties of an object.

In general, a copy is made of the property contents and the caller is responsible for freeing the memory in the appropriate manner for the type, for instance by calling g_free() or g_object_unref().

Example 5. Using g_object_get()

An example of using g_object_get() to get the contents of three properties - one of type G_TYPE_INT, one of type G_TYPE_STRING, and one of type G_TYPE_OBJECT:

 gint intval;
 gchar *strval;
 GObject *objval;

 g_object_get (my_object,
               "intproperty", &intval,
               "strproperty", &strval,
               "objproperty", &objval,
               NULL);

 /* Do something with intval, strval, objval */

 g_free (strval);
 g_object_unref (objval);

object : | a GObject
first_property_name : | name of the first property to get
... : | return location for the first property, followed optionally by more name/return location pairs, followed by NULL

g_object_notify ()

void                g_object_notify                     (GObject *object,
                                                         const gchar *property_name);

Emits a "notify" signal for the property property_name on object.

object : | a GObject
property_name : | the name of a property installed on the class of object.

g_object_freeze_notify ()

void                g_object_freeze_notify              (GObject *object);

Stops emission of "notify" signals on object. The signals are queued until g_object_thaw_notify() is called on object.

This is necessary for accessors that modify multiple properties to prevent premature notification while the object is still being modified.

object : a GObject

g_object_thaw_notify ()

void                g_object_thaw_notify                (GObject *object);

Reverts the effect of a previous call to g_object_freeze_notify(). This causes all queued "notify" signals on object to be emitted.

object : a GObject

g_object_get_data ()

gpointer            g_object_get_data                   (GObject *object,
                                                         const gchar *key);

Gets a named field from the objects table of associations (see g_object_set_data()).

object : | GObject containing the associations
key : | name of the key for that association
Returns : | the data if found, or NULL if no such data exists.

g_object_set_data ()

void                g_object_set_data                   (GObject *object,
                                                         const gchar *key,
                                                         gpointer data);

Each object carries around a table of associations from strings to pointers. This function lets you set an association.

If the object already had an association with that name, the old association will be destroyed.

object : | GObject containing the associations.
key : | name of the key
data : | data to associate with that key

g_object_set_data_full ()

void                g_object_set_data_full              (GObject *object,
                                                         const gchar *key,
                                                         gpointer data,
                                                         GDestroyNotify destroy);

Like g_object_set_data() except it adds notification for when the association is destroyed, either by setting it to a different value or when the object is destroyed.

object : | GObject containing the associations
key : | name of the key
data : | data to associate with that key
destroy : | function to call when the association is destroyed

g_object_steal_data ()

gpointer            g_object_steal_data                 (GObject *object,
                                                         const gchar *key);

Remove a specified datum from the object's data associations, without invoking the association's destroy handler.

object : | GObject containing the associations
key : | name of the key
Returns : | the data if found, or NULL if no such data exists.

g_object_get_qdata ()

gpointer            g_object_get_qdata                  (GObject *object,
                                                         GQuark quark);

This function gets back user data pointers stored via g_object_set_qdata().

object : | The GObject to get a stored user data pointer from
quark : | A GQuark, naming the user data pointer
Returns : | The user data pointer set, or NULL

g_object_set_qdata ()

void                g_object_set_qdata                  (GObject *object,
                                                         GQuark quark,
                                                         gpointer data);

This sets an opaque, named pointer on an object. The name is specified through a GQuark (retrived e.g. via g_quark_from_static_string()), and the pointer can be gotten back from the object with g_object_get_qdata() until the object is finalized. Setting a previously set user data pointer, overrides (frees) the old pointer set, using NULL as pointer essentially removes the data stored.

object : | The GObject to set store a user data pointer
quark : | A GQuark, naming the user data pointer
data : | An opaque user data pointer

g_object_set_qdata_full ()

void                g_object_set_qdata_full             (GObject *object,
                                                         GQuark quark,
                                                         gpointer data,
                                                         GDestroyNotify destroy);

This function works like g_object_set_qdata(), but in addition, a void (*destroy) (gpointer) function may be specified which is called with data as argument when the object is finalized, or the data is being overwritten by a call to g_object_set_qdata() with the same quark.

object : | The GObject to set store a user data pointer
quark : | A GQuark, naming the user data pointer
data : | An opaque user data pointer
destroy : | Function to invoke with data as argument, when data needs to be freed

g_object_steal_qdata ()

gpointer            g_object_steal_qdata                (GObject *object,
                                                         GQuark quark);

This function gets back user data pointers stored via g_object_set_qdata() and removes the data from object without invoking it's destroy() function (if any was set). Usually, calling this function is only required to update user data pointers with a destroy notifier, for example:

void
object_add_to_user_list (GObject     *object,
                         const gchar *new_string)
{
  /* the quark, naming the object data */
  GQuark quark_string_list = g_quark_from_static_string ("my-string-list");
  /* retrive the old string list */
  GList *list = g_object_steal_qdata (object, quark_string_list);

  /* prepend new string */
  list = g_list_prepend (list, g_strdup (new_string));
  /* this changed 'list', so we need to set it again */
  g_object_set_qdata_full (object, quark_string_list, list, free_string_list);
}
static void
free_string_list (gpointer data)
{
  GList *node, *list = data;

  for (node = list; node; node = node->next)
    g_free (node->data);
  g_list_free (list);
}

Using g_object_get_qdata() in the above example, instead of g_object_steal_qdata() would have left the destroy function set, and thus the partial string list would have been freed upon g_object_set_qdata_full().

object : | The GObject to get a stored user data pointer from
quark : | A GQuark, naming the user data pointer
Returns : | The user data pointer set, or NULL

g_object_set_property ()

void                g_object_set_property               (GObject *object,
                                                         const gchar *property_name,
                                                         const GValue *value);

Sets a property on an object.

object : | a GObject
property_name : | the name of the property to set
value : | the value

g_object_get_property ()

void                g_object_get_property               (GObject *object,
                                                         const gchar *property_name,
                                                         GValue *value);

Gets a property of an object.

In general, a copy is made of the property contents and the caller is responsible for freeing the memory by calling g_value_unset().

Note that g_object_get_property() is really intended for language bindings, g_object_get() is much more convenient for C programming.

object : | a GObject
property_name : | the name of the property to get
value : | return location for the property value

g_object_new_valist ()

GObject*            g_object_new_valist                 (GType object_type,
                                                         const gchar *first_property_name,
                                                         va_list var_args);

Creates a new instance of a GObject subtype and sets its properties.

Construction parameters (see G_PARAM_CONSTRUCT, G_PARAM_CONSTRUCT_ONLY) which are not explicitly specified are set to their default values.

object_type : | the type id of the GObject subtype to instantiate
first_property_name : | the name of the first property
var_args : | the value of the first property, followed optionally by more name/value pairs, followed by NULL
Returns : | a new instance of object_type

g_object_set_valist ()

void                g_object_set_valist                 (GObject *object,
                                                         const gchar *first_property_name,
                                                         va_list var_args);

Sets properties on an object.

object : | a GObject
first_property_name : | name of the first property to set
var_args : | value for the first property, followed optionally by more name/value pairs, followed by NULL

g_object_get_valist ()

void                g_object_get_valist                 (GObject *object,
                                                         const gchar *first_property_name,
                                                         va_list var_args);

Gets properties of an object.

In general, a copy is made of the property contents and the caller is responsible for freeing the memory in the appropriate manner for the type, for instance by calling g_free() or g_object_unref().

See g_object_get().

object : | a GObject
first_property_name : | name of the first property to get
var_args : | return location for the first property, followed optionally by more name/return location pairs, followed by NULL

g_object_watch_closure ()

void                g_object_watch_closure              (GObject *object,
                                                         GClosure *closure);

This function essentially limits the life time of the closure to the life time of the object. That is, when the object is finalized, the closure is invalidated by calling g_closure_invalidate() on it, in order to prevent invocations of the closure with a finalized (nonexisting) object. Also, g_object_ref() and g_object_unref() are added as marshal guards to the closure, to ensure that an extra reference count is held on object during invocation of the closure. Usually, this function will be called on closures that use this object as closure data.

object : | GObject restricting lifetime of closure
closure : | GClosure to watch

g_object_run_dispose ()

void                g_object_run_dispose                (GObject *object);

Releases all references to other objects. This can be used to break reference cycles.

Note

This functions should only be called from object system implementations.

object : a GObject

G_OBJECT_WARN_INVALID_PROPERTY_ID()

#define             G_OBJECT_WARN_INVALID_PROPERTY_ID(object, property_id, pspec)

This macros should be used to emit a standard warning about unexpected properties in set_property() and get_property() implementations.

object : | the GObject on which set_property() or get_property() was called
property_id : | the numeric id of the property
pspec : | the GParamSpec of the property

Signal Details

The "notify" signal

void                user_function                      (GObject    *gobject,
                                                        GParamSpec *arg1,
                                                        gpointer    user_data)      : Run First / No Recursion / Has Details / Action / No Hooks

The notify signal is emitted on an object when one of its properties has been changed. Note that getting this signal doesn't guarantee that the value of the property has actually changed, it may also be emitted when the setter for the property is called to reinstate the previous value.

pspec : | the GParamSpec of the property which changed
gobject : | the object which received the signal.
user_data : | user data set when the signal handler was connected.

See Also

GParamSpecObject, g_param_spec_object()


GType

GType — The GLib Runtime type identification and management system

Synopsis

#include <glib-object.h>

typedef             GType;
#define             G_TYPE_FUNDAMENTAL                  (type)
#define             G_TYPE_FUNDAMENTAL_MAX
#define             G_TYPE_MAKE_FUNDAMENTAL             (x)
#define             G_TYPE_IS_ABSTRACT                  (type)
#define             G_TYPE_IS_DERIVED                   (type)
#define             G_TYPE_IS_FUNDAMENTAL               (type)
#define             G_TYPE_IS_VALUE_TYPE                (type)
#define             G_TYPE_HAS_VALUE_TABLE              (type)
#define             G_TYPE_IS_CLASSED                   (type)
#define             G_TYPE_IS_INSTANTIATABLE            (type)
#define             G_TYPE_IS_DERIVABLE                 (type)
#define             G_TYPE_IS_DEEP_DERIVABLE            (type)
#define             G_TYPE_IS_INTERFACE                 (type)
                    GTypeInterface;
                    GTypeInstance;
                    GTypeClass;
                    GTypeInfo;
                    GTypeFundamentalInfo;
                    GInterfaceInfo;
                    GTypeValueTable;
#define             G_TYPE_FROM_INSTANCE                (instance)
#define             G_TYPE_FROM_CLASS                   (g_class)
#define             G_TYPE_FROM_INTERFACE               (g_iface)
#define             G_TYPE_INSTANCE_GET_CLASS           (instance, g_type, c_type)
#define             G_TYPE_INSTANCE_GET_INTERFACE       (instance, g_type, c_type)
#define             G_TYPE_INSTANCE_GET_PRIVATE         (instance, g_type, c_type)
#define             G_TYPE_CHECK_INSTANCE               (instance)
#define             G_TYPE_CHECK_INSTANCE_CAST          (instance, g_type, c_type)
#define             G_TYPE_CHECK_INSTANCE_TYPE          (instance, g_type)
#define             G_TYPE_CHECK_CLASS_CAST             (g_class, g_type, c_type)
#define             G_TYPE_CHECK_CLASS_TYPE             (g_class, g_type)
#define             G_TYPE_CHECK_VALUE                  (value)
#define             G_TYPE_CHECK_VALUE_TYPE             (value, g_type)
#define             G_TYPE_FLAG_RESERVED_ID_BIT
void                g_type_init                         (void);
enum                GTypeDebugFlags;
void                g_type_init_with_debug_flags        (GTypeDebugFlags debug_flags);
const gchar*        g_type_name                         (GType type);
GQuark              g_type_qname                        (GType type);
GType               g_type_from_name                    (const gchar *name);
GType               g_type_parent                       (GType type);
guint               g_type_depth                        (GType type);
GType               g_type_next_base                    (GType leaf_type,
                                                         GType root_type);
gboolean            g_type_is_a                         (GType type,
                                                         GType is_a_type);
gpointer            g_type_class_ref                    (GType type);
gpointer            g_type_class_peek                   (GType type);
gpointer            g_type_class_peek_static            (GType type);
void                g_type_class_unref                  (gpointer g_class);
gpointer            g_type_class_peek_parent            (gpointer g_class);
void                g_type_class_add_private            (gpointer g_class,
                                                         gsize private_size);
gpointer            g_type_interface_peek               (gpointer instance_class,
                                                         GType iface_type);
gpointer            g_type_interface_peek_parent        (gpointer g_iface);
gpointer            g_type_default_interface_ref        (GType g_type);
gpointer            g_type_default_interface_peek       (GType g_type);
void                g_type_default_interface_unref      (gpointer g_iface);
GType*              g_type_children                     (GType type,
                                                         guint *n_children);
GType*              g_type_interfaces                   (GType type,
                                                         guint *n_interfaces);
GType*              g_type_interface_prerequisites      (GType interface_type,
                                                         guint *n_prerequisites);
void                g_type_set_qdata                    (GType type,
                                                         GQuark quark,
                                                         gpointer data);
gpointer            g_type_get_qdata                    (GType type,
                                                         GQuark quark);
void                g_type_query                        (GType type,
                                                         GTypeQuery *query);
                    GTypeQuery;
void                (*GBaseInitFunc)                    (gpointer g_class);
void                (*GBaseFinalizeFunc)                (gpointer g_class);
void                (*GClassInitFunc)                   (gpointer g_class,
                                                         gpointer class_data);
void                (*GClassFinalizeFunc)               (gpointer g_class,
                                                         gpointer class_data);
void                (*GInstanceInitFunc)                (GTypeInstance *instance,
                                                         gpointer g_class);
void                (*GInterfaceInitFunc)               (gpointer g_iface,
                                                         gpointer iface_data);
void                (*GInterfaceFinalizeFunc)           (gpointer g_iface,
                                                         gpointer iface_data);
gboolean            (*GTypeClassCacheFunc)              (gpointer cache_data,
                                                         GTypeClass *g_class);
enum                GTypeFlags;
enum                GTypeFundamentalFlags;
GType               g_type_register_static              (GType parent_type,
                                                         const gchar *type_name,
                                                         const GTypeInfo *info,
                                                         GTypeFlags flags);
GType               g_type_register_static_simple       (GType parent_type,
                                                         const gchar *type_name,
                                                         guint class_size,
                                                         GClassInitFunc class_init,
                                                         guint instance_size,
                                                         GInstanceInitFunc instance_init,
                                                         GTypeFlags flags);
GType               g_type_register_dynamic             (GType parent_type,
                                                         const gchar *type_name,
                                                         GTypePlugin *plugin,
                                                         GTypeFlags flags);
GType               g_type_register_fundamental         (GType type_id,
                                                         const gchar *type_name,
                                                         const GTypeInfo *info,
                                                         const GTypeFundamentalInfo *finfo,
                                                         GTypeFlags flags);
void                g_type_add_interface_static         (GType instance_type,
                                                         GType interface_type,
                                                         const GInterfaceInfo *info);
void                g_type_add_interface_dynamic        (GType instance_type,
                                                         GType interface_type,
                                                         GTypePlugin *plugin);
void                g_type_interface_add_prerequisite   (GType interface_type,
                                                         GType prerequisite_type);
GTypePlugin*        g_type_get_plugin                   (GType type);
GTypePlugin*        g_type_interface_get_plugin         (GType instance_type,
                                                         GType interface_type);
GType               g_type_fundamental_next             (void);
GType               g_type_fundamental                  (GType type_id);
GTypeInstance*      g_type_create_instance              (GType type);
void                g_type_free_instance                (GTypeInstance *instance);
void                g_type_add_class_cache_func         (gpointer cache_data,
                                                         GTypeClassCacheFunc cache_func);
void                g_type_remove_class_cache_func      (gpointer cache_data,
                                                         GTypeClassCacheFunc cache_func);
void                g_type_class_unref_uncached         (gpointer g_class);
void                g_type_add_interface_check          (gpointer check_data,
                                                         GTypeInterfaceCheckFunc check_func);
void                g_type_remove_interface_check       (gpointer check_data,
                                                         GTypeInterfaceCheckFunc check_func);
void                (*GTypeInterfaceCheckFunc)          (gpointer check_data,
                                                         gpointer g_iface);
GTypeValueTable*    g_type_value_table_peek             (GType type);
#define             G_DEFINE_TYPE                       (TN, t_n, T_P)
#define             G_DEFINE_TYPE_WITH_CODE             (TN, t_n, T_P, _C_)
#define             G_DEFINE_ABSTRACT_TYPE              (TN, t_n, T_P)
#define             G_DEFINE_ABSTRACT_TYPE_WITH_CODE    (TN, t_n, T_P, _C_)
#define             G_IMPLEMENT_INTERFACE               (TYPE_IFACE, iface_init)
#define             G_DEFINE_TYPE_EXTENDED              (TN, t_n, T_P, _f_, _C_)

#define             G_TYPE_INVALID
#define             G_TYPE_NONE
#define             G_TYPE_INTERFACE
#define             G_TYPE_CHAR
#define             G_TYPE_UCHAR
#define             G_TYPE_BOOLEAN
#define             G_TYPE_INT
#define             G_TYPE_UINT
#define             G_TYPE_LONG
#define             G_TYPE_ULONG
#define             G_TYPE_INT64
#define             G_TYPE_UINT64
#define             G_TYPE_ENUM
#define             G_TYPE_FLAGS
#define             G_TYPE_FLOAT
#define             G_TYPE_DOUBLE
#define             G_TYPE_STRING
#define             G_TYPE_POINTER
#define             G_TYPE_BOXED
#define             G_TYPE_PARAM
#define             G_TYPE_OBJECT
#define             G_TYPE_GTYPE

#define             G_TYPE_RESERVED_GLIB_FIRST
#define             G_TYPE_RESERVED_GLIB_LAST
#define             G_TYPE_RESERVED_BSE_FIRST
#define             G_TYPE_RESERVED_BSE_LAST
#define             G_TYPE_RESERVED_USER_FIRST

Description

The GType API is the foundation of the GObject system. It provides the facilities for registering and managing all fundamental data types, user-defined object and interface types. Before using any GType or GObject functions, g_type_init() must be called to initialize the type system.

For type creation and registration purposes, all types fall into one of two categories: static or dynamic. Static types are never loaded or unloaded at run-time as dynamic types may be. Static types are created with g_type_register_static() that gets type specific information passed in via a GTypeInfo structure. Dynamic types are created with g_type_register_dynamic() which takes a GTypePlugin structure instead. The remaining type information (the GTypeInfo structure) is retrieved during runtime through GTypePlugin and the g_type_plugin_*() API. These registration functions are usually called only once from a function whose only purpose is to return the type identifier for a specific class. Once the type (or class or interface) is registered, it may be instantiated, inherited, or implemented depending on exactly what sort of type it is. There is also a third registration function for registering fundamental types called g_type_register_fundamental() which requires both a GTypeInfo structure and a GTypeFundamentalInfo structure but it is seldom used since most fundamental types are predefined rather than user-defined.

A final word about type names. Such an identifier needs to be at least three characters long. There is no upper length limit. The first character needs to be a letter (a-z or A-Z) or an underscore '_'. Subsequent characters can be letters, numbers or any of '-_+'.

Details

GType

A numerical value which represents the unique identifier of a registered type.

G_TYPE_FUNDAMENTAL()

#define G_TYPE_FUNDAMENTAL(type)	(g_type_fundamental (type))

Returns the fundamental type which is the ancestor of type. Fundamental types are types that serve as ultimate bases for the derived types, thus they are the roots of distinct inheritance hierarchies.

type : A GType value.

G_TYPE_FUNDAMENTAL_MAX

#define	G_TYPE_FUNDAMENTAL_MAX		(255 << G_TYPE_FUNDAMENTAL_SHIFT)

An integer constant that represents the number of identifiers reserved for types that are assigned at compile-time.

G_TYPE_MAKE_FUNDAMENTAL()

#define	G_TYPE_MAKE_FUNDAMENTAL(x)	((GType) ((x) << G_TYPE_FUNDAMENTAL_SHIFT))

Returns the type ID for the fundamental type number x. Use g_type_fundamental_next() instead of this macro to create new fundamental types.

x : the fundamental type number.

G_TYPE_IS_ABSTRACT()

#define G_TYPE_IS_ABSTRACT(type)                (g_type_test_flags ((type), G_TYPE_FLAG_ABSTRACT))

Returns TRUE if type is an abstract type. An abstract type can not be instantiated and is normally used as an abstract base class for derived classes.

type : A GType value.

G_TYPE_IS_DERIVED()

#define G_TYPE_IS_DERIVED(type)                 ((type) > G_TYPE_FUNDAMENTAL_MAX)

Returns TRUE if type is derived (or in object-oriented terminology: inherited) from another type (this holds true for all non-fundamental types).

type : A GType value.

G_TYPE_IS_FUNDAMENTAL()

#define G_TYPE_IS_FUNDAMENTAL(type)             ((type) <= G_TYPE_FUNDAMENTAL_MAX)

Returns TRUE if type is a fundamental type.

type : A GType value.

G_TYPE_IS_VALUE_TYPE()

#define G_TYPE_IS_VALUE_TYPE(type)              (g_type_check_is_value_type (type))

Returns TRUE if type is a value type and can be used with g_value_init().

type : A GType value.

G_TYPE_HAS_VALUE_TABLE()

#define G_TYPE_HAS_VALUE_TABLE(type)            (g_type_value_table_peek (type) != NULL)

Returns TRUE if type has a GTypeValueTable.

type : A GType value.

G_TYPE_IS_CLASSED()

#define G_TYPE_IS_CLASSED(type)                 (g_type_test_flags ((type), G_TYPE_FLAG_CLASSED))

Returns TRUE if type is a classed type.

type : A GType value.

G_TYPE_IS_INSTANTIATABLE()

#define G_TYPE_IS_INSTANTIATABLE(type)          (g_type_test_flags ((type), G_TYPE_FLAG_INSTANTIATABLE))

Returns TRUE if type can be instantiated. Instantiation is the process of creating an instance (object) of this type.

type : A GType value.

G_TYPE_IS_DERIVABLE()

#define G_TYPE_IS_DERIVABLE(type)               (g_type_test_flags ((type), G_TYPE_FLAG_DERIVABLE))

Returns TRUE if type is a derivable type. A derivable type can be used as the base class of a flat (single-level) class hierarchy.

type : A GType value.

G_TYPE_IS_DEEP_DERIVABLE()

#define G_TYPE_IS_DEEP_DERIVABLE(type)          (g_type_test_flags ((type), G_TYPE_FLAG_DEEP_DERIVABLE))

Returns TRUE if type is a deep derivable type. A deep derivable type can be used as the base class of a deep (multi-level) class hierarchy.

type : A GType value.

G_TYPE_IS_INTERFACE()

#define G_TYPE_IS_INTERFACE(type)               (G_TYPE_FUNDAMENTAL (type) == G_TYPE_INTERFACE)

Returns TRUE if type is an interface type. An interface type provides a pure API, the implementation of which is provided by another type (which is then said to conform to the interface). GLib interfaces are somewhat analogous to Java interfaces and C++ classes containing only pure virtual functions, with the difference that GType interfaces are not derivable (but see g_type_interface_add_prerequisite() for an alternative).

type : A GType value.

GTypeInterface

typedef struct {
} GTypeInterface;

An opaque structure used as the base of all interface types.

GTypeInstance

typedef struct {
} GTypeInstance;

An opaque structure used as the base of all type instances.

GTypeClass

typedef struct {
} GTypeClass;

An opaque structure used as the base of all classes.

GTypeInfo

typedef struct {
  /* interface types, classed types, instantiated types */
  guint16                class_size;

  GBaseInitFunc          base_init;
  GBaseFinalizeFunc      base_finalize;

  /* interface types, classed types, instantiated types */
  GClassInitFunc         class_init;
  GClassFinalizeFunc     class_finalize;
  gconstpointer          class_data;

  /* instantiated types */
  guint16                instance_size;
  guint16                n_preallocs;
  GInstanceInitFunc      instance_init;

  /* value handling */
  const GTypeValueTable	*value_table;
} GTypeInfo;

This structure is used to provide the type system with the information required to initialize and destruct (finalize) a type's class and its instances. The initialized structure is passed to the g_type_register_static() function (or is copied into the provided GTypeInfo structure in the g_type_plugin_complete_type_info()). The type system will perform a deep copy of this structure, so its memory does not need to be persistent across invocation of g_type_register_static().

guint16 class_size; | Size of the class structure (required for interface, classed and instantiatable types).
GBaseInitFunc base_init; | Location of the base initialization function (optional).
GBaseFinalizeFunc base_finalize; | Location of the base finalization function (optional).
GClassInitFunc class_init; | Location of the class initialization function for classed and types. Location of the default vtable inititalization function for interface types. (optional) This function is used both to fill in virtual functions in the class or default vtable, and to do type-specific setup such as registering signals and object properties.
GClassFinalizeFunc class_finalize; | Location of the class finalization function for classed and types. Location fo the default vtable finalization function for interface types. (optional)
gconstpointer class_data; | User-supplied data passed to the class init/finalize functions.
guint16 instance_size; | Size of the instance (object) structure (required for instantiatable types only).
guint16 n_preallocs; | Prior to GLib 2.10, it specified the number of pre-allocated (cached) instances to reserve memory for (0 indicates no caching). Since GLib 2.10, it is ignored, since instances are allocated with the slice allocator now.
GInstanceInitFunc instance_init; | Location of the instance initialization function (optional, for instantiatable types only).
const GTypeValueTable *value_table; | A GTypeValueTable function table for generic handling of GValues of this type (usually only useful for fundamental types).

GTypeFundamentalInfo

typedef struct {
  GTypeFundamentalFlags  type_flags;
} GTypeFundamentalInfo;

A structure that provides information to the type system which is used specifically for managing fundamental types.

GTypeFundamentalFlags type_flags; GTypeFundamentalFlags describing the characteristics of the fundamental type

GInterfaceInfo

typedef struct {
  GInterfaceInitFunc     interface_init;
  GInterfaceFinalizeFunc interface_finalize;
  gpointer               interface_data;
} GInterfaceInfo;

A structure that provides information to the type system which is used specifically for managing interface types.

GInterfaceInitFunc interface_init; | location of the interface initialization function
GInterfaceFinalizeFunc interface_finalize; | location of the interface finalization function
gpointer interface_data; | user-supplied data passed to the interface init/finalize functions

GTypeValueTable

typedef struct {
  void     (*value_init)         (GValue       *value);
  void     (*value_free)         (GValue       *value);
  void     (*value_copy)         (const GValue *src_value,
                  GValue       *dest_value);
  /* varargs functionality (optional) */
  gpointer (*value_peek_pointer) (const GValue *value);
  gchar	    *collect_format;
  gchar*   (*collect_value)      (GValue       *value,
                  guint         n_collect_values,
                  GTypeCValue  *collect_values,
                  guint		collect_flags);
  gchar	    *lcopy_format;
  gchar*   (*lcopy_value)        (const GValue *value,
                  guint         n_collect_values,
                  GTypeCValue  *collect_values,
                  guint		collect_flags);
} GTypeValueTable;

The GTypeValueTable provides the functions required by the GValue implementation, to serve as a container for values of a type.

value_init () Default initialize values contents by poking values directly into the value->data array. The data array of the GValue passed into this function was zero-filled with memset(), so no care has to be taken to free any old contents. E.g. for the implementation of a string value that may never be NULL, the implementation might look like:
{
  value->data[0].v_pointer = g_strdup ("");
}
value_free () Free any old contents that might be left in the data array of the passed in value. No resources may remain allocated through the GValue contents after this function returns. E.g. for our above string type:
{
  /* only free strings without a specific flag for static storage */
  if (!(value->data[1].v_uint & G_VALUE_NOCOPY_CONTENTS))
    g_free (value->data[0].v_pointer);
}
value_copy () dest_value is a GValue with zero-filled data section and src_value is a properly setup GValue of same or derived type. The purpose of this function is to copy the contents of src_value into dest_value in a way, that even after src_value has been freed, the contents of dest_value remain valid. String type example:
{
  dest_value->data[0].v_pointer = g_strdup (src_value->data[0].v_pointer);
}
value_peek_pointer () If the value contents fit into a pointer, such as objects or strings, return this pointer, so the caller can peek at the current contents. To extend on our above string example:
{
  return value->data[0].v_pointer;
}
gchar *collect_format; A string format describing how to collect the contents of this value bit-by-bit. Each character in the format represents an argument to be collected, and the characters themselves indicate the type of the argument. Currently supported arguments are:

'i' - Integers. passed as collect_values[].v_int.

'l' - Longs. passed as collect_values[].v_long.

'd' - Doubles. passed as collect_values[].v_double.

'p' - Pointers. passed as collect_values[].v_pointer.

It should be noted that for variable argument list construction, ANSI C promotes every type smaller than an integer to an int, and floats to doubles. So for collection of short int or char, 'i' needs to be used, and for collection of floats 'd'.
collect_value () The collect_value() function is responsible for converting the values collected from a variable argument list into contents suitable for storage in a GValue. This function should setup value similar to value_init(); e.g. for a string value that does not allow NULL pointers, it needs to either spew an error, or do an implicit conversion by storing an empty string. The value passed in to this function has a zero-filled data array, so just like for value_init() it is guaranteed to not contain any old contents that might need freeing. n_collect_values is exactly the string length of collect_format, and collect_values is an array of unions GTypeCValue with length n_collect_values, containing the collected values according to collect_format. collect_flags is an argument provided as a hint by the caller. It may contain the flag G_VALUE_NOCOPY_CONTENTS indicating, that the collected value contents may be considered "static" for the duration of the value lifetime. Thus an extra copy of the contents stored in collect_values is not required for assignment to value. For our above string example, we continue with:
{
  if (!collect_values[0].v_pointer)
    value->data[0].v_pointer = g_strdup ("");
  else if (collect_flags & G_VALUE_NOCOPY_CONTENTS)
    {
      value->data[0].v_pointer = collect_values[0].v_pointer;
      /* keep a flag for the value_free() implementation to not free this string */
      value->data[1].v_uint = G_VALUE_NOCOPY_CONTENTS;
    }
  else
    value->data[0].v_pointer = g_strdup (collect_values[0].v_pointer);

  return NULL;
}
It should be noted, that it is generally a bad idea to follow the G_VALUE_NOCOPY_CONTENTS hint for reference counted types. Due to reentrancy requirements and reference count assertions performed by the GSignal code, reference counts should always be incremented for reference counted contents stored in the value->data array. To deviate from our string example for a moment, and taking a look at an exemplary implementation for collect_value() of GObject:
{
  if (collect_values[0].v_pointer)
    {
      GObject *object = G_OBJECT (collect_values[0].v_pointer);

      /* never honour G_VALUE_NOCOPY_CONTENTS for ref-counted types */
      value->data[0].v_pointer = g_object_ref (object);
      return NULL;
    }
  else
    return g_strdup_printf ("Object passed as invalid NULL pointer");
}
The reference count for valid objects is always incremented, regardless of collect_flags. For invalid objects, the example returns a newly allocated string without altering value. Upon success, collect_value() needs to return NULL. If, however, an error condition occurred, collect_value() may spew an error by returning a newly allocated non-NULL string, giving a suitable description of the error condition. The calling code makes no assumptions about the value contents being valid upon error returns, value is simply thrown away without further freeing. As such, it is a good idea to not allocate GValue contents, prior to returning an error, however, collect_values() is not obliged to return a correctly setup value for error returns, simply because any non-NULL return is considered a fatal condition so further program behaviour is undefined.
gchar *lcopy_format; Format description of the arguments to collect for lcopy_value, analogous to collect_format. Usually, lcopy_format string consists only of 'p's to provide lcopy_value() with pointers to storage locations.
lcopy_value () This function is responsible for storing the value contents into arguments passed through a variable argument list which got collected into collect_values according to lcopy_format. n_collect_values equals the string length of lcopy_format, and collect_flags may contain G_VALUE_NOCOPY_CONTENTS. In contrast to collect_value(), lcopy_value() is obliged to always properly support G_VALUE_NOCOPY_CONTENTS. Similar to collect_value() the function may prematurely abort by returning a newly allocated string describing an error condition. To complete the string example:
{
  gchar **string_p = collect_values[0].v_pointer;

  if (!string_p)
    return g_strdup_printf ("string location passed as NULL");

  if (collect_flags & G_VALUE_NOCOPY_CONTENTS)
    *string_p = value->data[0].v_pointer;
  else
    *string_p = g_strdup (value->data[0].v_pointer);

}
And an illustrative version of lcopy_value() for reference-counted types:
{
  GObject **object_p = collect_values[0].v_pointer;

  if (!object_p)
    return g_strdup_printf ("object location passed as NULL");
  if (!value->data[0].v_pointer)
    *object_p = NULL;
  else if (collect_flags & G_VALUE_NOCOPY_CONTENTS) /* always honour */
    *object_p = value->data[0].v_pointer;
  else
    *object_p = g_object_ref (value->data[0].v_pointer);
  return NULL;
}

G_TYPE_FROM_INSTANCE()

#define G_TYPE_FROM_INSTANCE(instance)                          (G_TYPE_FROM_CLASS (((GTypeInstance*) (instance))->g_class))

Returns the type identifier from a given instance structure.

This macro should only be used in type implementations.

instance : Location of a valid GTypeInstance structure.

G_TYPE_FROM_CLASS()

#define G_TYPE_FROM_CLASS(g_class)                              (((GTypeClass*) (g_class))->g_type)

Returns the type identifier from a given class structure.

This macro should only be used in type implementations.

g_class : Location of a valid GTypeClass structure.

G_TYPE_FROM_INTERFACE()

#define G_TYPE_FROM_INTERFACE(g_iface)                          (((GTypeInterface*) (g_iface))->g_type)

Returns the type identifier from a given interface structure.

This macro should only be used in type implementations.

g_iface : Location of a valid GTypeInterface structure.

G_TYPE_INSTANCE_GET_CLASS()

#define G_TYPE_INSTANCE_GET_CLASS(instance, g_type, c_type)     (_G_TYPE_IGC ((instance), (g_type), c_type))

Returns the class structure of a given instance, casted to a specified ancestor type g_type of the instance.

Warning

Note that while calling a GInstanceInitFunc(), the class pointer gets modified, so it might not always return the expected pointer.

This macro should only be used in type implementations.

instance : | Location of the GTypeInstance structure.
g_type : | The anchestor type of the class to be returned.
c_type : | The corresponding C type of g_type.

G_TYPE_INSTANCE_GET_INTERFACE()

#define G_TYPE_INSTANCE_GET_INTERFACE(instance, g_type, c_type) (_G_TYPE_IGI ((instance), (g_type), c_type))

Returns the interface structure for interface g_type of a given instance.

This macro should only be used in type implementations.

instance : | Location of the GTypeInstance structure.
g_type : | The interface type to be returned.
c_type : | The corresponding C type of g_type.

G_TYPE_INSTANCE_GET_PRIVATE()

#define G_TYPE_INSTANCE_GET_PRIVATE(instance, g_type, c_type)   ((c_type*) g_type_instance_get_private ((GTypeInstance*) (instance), (g_type)))

Gets the private structure for a particular type. The private structure must have been registered in the class_init function with g_type_class_add_private().

This macro should only be used in type implementations.

instance : | the instance of a type deriving from private_type.
g_type : | the type identifying which private data to retrieve.
c_type : | The C type for the private structure.

Since 2.4

G_TYPE_CHECK_INSTANCE()

#define G_TYPE_CHECK_INSTANCE(instance)				(_G_TYPE_CHI ((GTypeInstance*) (instance)))

Returns TRUE if instance is a valid GTypeInstance structure, otherwise emits a warning and returns FALSE.

This macro should only be used in type implementations.

instance : Location of a GTypeInstance structure.

G_TYPE_CHECK_INSTANCE_CAST()

#define G_TYPE_CHECK_INSTANCE_CAST(instance, g_type, c_type)    (_G_TYPE_CIC ((instance), (g_type), c_type))

Checks that instance is an instance of the type identified by g_type and emits a warning if this is not the case. Returns instance casted to a pointer to c_type.

This macro should only be used in type implementations.

instance : | Location of a GTypeInstance structure.
g_type : | The type to be returned.
c_type : | The corresponding C type of g_type.

G_TYPE_CHECK_INSTANCE_TYPE()

#define G_TYPE_CHECK_INSTANCE_TYPE(instance, g_type)            (_G_TYPE_CIT ((instance), (g_type)))

Returns TRUE if instance is an instance of the type identified by g_type. Otherwise emits a warning and returns FALSE.

This macro should only be used in type implementations.

instance : | Location of a GTypeInstance structure.
g_type : | The type to be checked

G_TYPE_CHECK_CLASS_CAST()

#define G_TYPE_CHECK_CLASS_CAST(g_class, g_type, c_type)        (_G_TYPE_CCC ((g_class), (g_type), c_type))

Checks that g_class is a class structure of the type identified by g_type and emits a warning if this is not the case. Returns g_class casted to a pointer to c_type.

This macro should only be used in type implementations.

g_class : | Location of a GTypeClass structure.
g_type : | The type to be returned.
c_type : | The corresponding C type of class structure of g_type.

G_TYPE_CHECK_CLASS_TYPE()

#define G_TYPE_CHECK_CLASS_TYPE(g_class, g_type)                (_G_TYPE_CCT ((g_class), (g_type)))

Returns TRUE if g_class is a class structure of the type identified by g_type. Otherwise emits a warning and returns FALSE.

This macro should only be used in type implementations.

g_class : | Location of a GTypeClass structure.
g_type : | The type to be checked.

G_TYPE_CHECK_VALUE()

#define G_TYPE_CHECK_VALUE(value)				(_G_TYPE_CHV ((value)))

Returns TRUE if value has been initialized to hold values of a value type.

This macro should only be used in type implementations.

value : a GValue

G_TYPE_CHECK_VALUE_TYPE()

#define G_TYPE_CHECK_VALUE_TYPE(value, g_type)			(_G_TYPE_CVH ((value), (g_type)))

Returns TRUE if value has been initialized to hold values of type g_type.

This macro should only be used in type implementations.

value : | a GValue
g_type : | The type to be checked.

G_TYPE_FLAG_RESERVED_ID_BIT

#define	G_TYPE_FLAG_RESERVED_ID_BIT	((GType) (1 << 0))

A bit in the type number that's supposed to be left untouched.

g_type_init ()

void                g_type_init                         (void);

Prior to any use of the type system, g_type_init() has to be called to initialize the type system and assorted other code portions (such as the various fundamental type implementations or the signal system).

enum GTypeDebugFlags

typedef enum	/*< skip >*/
{
  G_TYPE_DEBUG_NONE	= 0,
  G_TYPE_DEBUG_OBJECTS	= 1 << 0,
  G_TYPE_DEBUG_SIGNALS	= 1 << 1,
  G_TYPE_DEBUG_MASK	= 0x03
} GTypeDebugFlags;

The GTypeDebugFlags enumeration values can be passed to g_type_init_with_debug_flags() to trigger debugging messages during runtime. Note that the messages can also be triggered by setting the GOBJECT_DEBUG environment variable to a ':'-separated list of "objects" and "signals".

G_TYPE_DEBUG_NONE | Print no messages.
G_TYPE_DEBUG_OBJECTS | Print messages about object bookkeeping.
G_TYPE_DEBUG_SIGNALS | Print messages about signal emissions.
G_TYPE_DEBUG_MASK | Mask covering all debug flags.

g_type_init_with_debug_flags ()

void                g_type_init_with_debug_flags        (GTypeDebugFlags debug_flags);

Similar to g_type_init(), but additionally sets debug flags.

debug_flags : Bitwise combination of GTypeDebugFlags values for debugging purposes.

g_type_name ()

const gchar*        g_type_name                         (GType type);

Returns the unique name that is assigned to a type ID (this is the preferred method to find out whether a specific type has been registered for the passed in ID yet).

type : | Type to return name for.
Returns : | Static type name or NULL.

g_type_qname ()

GQuark              g_type_qname                        (GType type);

Return the corresponding quark of the type IDs name.

type : | Type to return quark of type name for.
Returns : | The type names quark or 0.

g_type_from_name ()

GType               g_type_from_name                    (const gchar *name);

Lookup the type ID from a given type name, returning 0 if no type has been registered under this name (this is the preferred method to find out by name whether a specific type has been registered yet).

name : | Type name to lookup.
Returns : | Corresponding type ID or 0.

g_type_parent ()

GType               g_type_parent                       (GType type);

Return the direct parent type of the passed in type. If the passed in type has no parent, i.e. is a fundamental type, 0 is returned.

type : | The derived type.
Returns : | The parent type.

g_type_depth ()

guint               g_type_depth                        (GType type);

Returns the length of the ancestry of the passed in type. This includes the type itself, so that e.g. a fundamental type has depth 1.

type : | A GType value.
Returns : | The depth of type.

g_type_next_base ()

GType               g_type_next_base                    (GType leaf_type,
                                                         GType root_type);

Given a leaf_type and a root_type which is contained in its anchestry, return the type that root_type is the immediate parent of. In other words, this function determines the type that is derived directly from root_type which is also a base class of leaf_type. Given a root type and a leaf type, this function can be used to determine the types and order in which the leaf type is descended from the root type.

leaf_type : | Descendant of root_type and the type to be returned.
root_type : | Immediate parent of the returned type.
Returns : | Immediate child of root_type and anchestor of leaf_type.

g_type_is_a ()

gboolean            g_type_is_a                         (GType type,
                                                         GType is_a_type);

If is_a_type is a derivable type, check whether type is a descendant of is_a_type. If is_a_type is an interface, check whether type conforms to it.

type : | Type to check anchestry for.
is_a_type : | Possible anchestor of type or interface type could conform to.
Returns : | TRUE if type is_a is_a_type holds true.

g_type_class_ref ()

gpointer            g_type_class_ref                    (GType type);

Increments the reference count of the class structure belonging to type. This function will demand-create the class if it doesn't exist already.

type : | Type ID of a classed type.
Returns : | The GTypeClass structure for the given type ID.

g_type_class_peek ()

gpointer            g_type_class_peek                   (GType type);

This function is essentially the same as g_type_class_ref(), except that the classes reference count isn't incremented. As a consequence, this function may return NULL if the class of the type passed in does not currently exist (hasn't been referenced before).

type : | Type ID of a classed type.
Returns : | The GTypeClass structure for the given type ID or NULL if the class does not currently exist.

g_type_class_peek_static ()

gpointer            g_type_class_peek_static            (GType type);

A more efficient version of g_type_class_peek() which works only for static types.

type : | Type ID of a classed type.
Returns : | The GTypeClass structure for the given type ID or NULL if the class does not currently exist or is dynamically loaded.

Since 2.4

g_type_class_unref ()

void                g_type_class_unref                  (gpointer g_class);

Decrements the reference count of the class structure being passed in. Once the last reference count of a class has been released, classes may be finalized by the type system, so further dereferencing of a class pointer after g_type_class_unref() are invalid.

g_class : The GTypeClass structure to unreference.

g_type_class_peek_parent ()

gpointer            g_type_class_peek_parent            (gpointer g_class);

This is a convenience function often needed in class initializers. It returns the class structure of the immediate parent type of the class passed in. Since derived classes hold a reference count on their parent classes as long as they are instantiated, the returned class will always exist. This function is essentially equivalent to:

g_type_class_peek (g_type_parent (G_TYPE_FROM_CLASS (g_class)));

g_class : | The GTypeClass structure to retrieve the parent class for.
Returns : | The parent class of g_class.

g_type_class_add_private ()

void                g_type_class_add_private            (gpointer g_class,
                                                         gsize private_size);

Registers a private structure for a instantiatable type; when an object is allocated, the private structures for the type and and all of its parent types are allocated sequentially in the same memory block as the public structures. This function should be called in the type's class_init() function. The private structure can be retrieved using the G_TYPE_INSTANCE_GET_PRIVATE() macro. The following example shows attaching a private structure MyObjectPrivate to an object MyObject defined in the standard GObject fashion.

typedef struct _MyObjectPrivate MyObjectPrivate;

struct _MyObjectPrivate {
  int some_field;
};

#define MY_OBJECT_GET_PRIVATE(o)  \
   (G_TYPE_INSTANCE_GET_PRIVATE ((o), MY_TYPE_OBJECT, MyObjectPrivate))

static void
my_object_class_init (MyObjectClass *klass)
{
  g_type_class_add_private (klass, sizeof (MyObjectPrivate));
}

static int
my_object_get_some_field (MyObject *my_object)
{
  MyObjectPrivate *priv = MY_OBJECT_GET_PRIVATE (my_object);

  return priv->some_field;
}

g_class : | class structure for an instantiatable type
private_size : | size of private structure.

Since 2.4

g_type_interface_peek ()

gpointer            g_type_interface_peek               (gpointer instance_class,
                                                         GType iface_type);

Returns the GTypeInterface structure of an interface to which the passed in class conforms.

instance_class : | A GTypeClass structure.
iface_type : | An interface ID which this class conforms to.
Returns : | The GTypeInterface structure of iface_type if implemented by instance_class, NULL otherwise

g_type_interface_peek_parent ()

gpointer            g_type_interface_peek_parent        (gpointer g_iface);

Returns the corresponding GTypeInterface structure of the parent type of the instance type to which g_iface belongs. This is useful when deriving the implementation of an interface from the parent type and then possibly overriding some methods.

g_iface : | A GTypeInterface structure.
Returns : | The corresponding GTypeInterface structure of the parent type of the instance type to which g_iface belongs, or NULL if the parent type doesn't conform to the interface.

g_type_default_interface_ref ()

gpointer            g_type_default_interface_ref        (GType g_type);

Increments the reference count for the interface type g_type, and returns the default interface vtable for the type.

If the type is not currently in use, then the default vtable for the type will be created and initalized by calling the base interface init and default vtable init functions for the type (the @base_init and class_init members of GTypeInfo). Calling g_type_default_interface_ref() is useful when you want to make sure that signals and properties for an interface have been installed.

g_type : | an interface type
Returns : | the default vtable for the interface; call g_type_default_interface_unref() when you are done using the interface.

Since 2.4

g_type_default_interface_peek ()

gpointer            g_type_default_interface_peek       (GType g_type);

If the interface type g_type is currently in use, returns its default interface vtable.

g_type : | an interface type
Returns : | the default vtable for the interface, or NULL if the type is not currently in use.

Since 2.4

g_type_default_interface_unref ()

void                g_type_default_interface_unref      (gpointer g_iface);

Decrements the reference count for the type corresponding to the interface default vtable g_iface. If the type is dynamic, then when no one is using the interface and all references have been released, the finalize function for the interface's default vtable (the class_finalize member of GTypeInfo) will be called.

g_iface : the default vtable structure for a interface, as returned by g_type_default_interface_ref()

Since 2.4

g_type_children ()

GType*              g_type_children                     (GType type,
                                                         guint *n_children);

Return a newly allocated and 0-terminated array of type IDs, listing the child types of type. The return value has to be g_free()ed after use.

type : | The parent type.
n_children : | Optional guint pointer to contain the number of child types.
Returns : | Newly allocated and 0-terminated array of child types.

g_type_interfaces ()

GType*              g_type_interfaces                   (GType type,
                                                         guint *n_interfaces);

Return a newly allocated and 0-terminated array of type IDs, listing the interface types that type conforms to. The return value has to be g_free()ed after use.

type : | The type to list interface types for.
n_interfaces : | Optional guint pointer to contain the number of interface types.
Returns : | Newly allocated and 0-terminated array of interface types.

g_type_interface_prerequisites ()

GType*              g_type_interface_prerequisites      (GType interface_type,
                                                         guint *n_prerequisites);

Returns the prerequisites of an interfaces type.

interface_type : | an interface type
n_prerequisites : | location to return the number of prerequisites, or NULL
Returns : | a newly-allocated zero-terminated array of GType containing the prerequisites of interface_type

Since 2.2

g_type_set_qdata ()

void                g_type_set_qdata                    (GType type,
                                                         GQuark quark,
                                                         gpointer data);

Attaches arbitrary data to a type.

type : | a GType
quark : | a GQuark id to identify the data
data : | the data

g_type_get_qdata ()

gpointer            g_type_get_qdata                    (GType type,
                                                         GQuark quark);

Obtains data which has previously been attached to type with g_type_set_qdata().

type : | a GType
quark : | a GQuark id to identify the data
Returns : | the data, or NULL if no data was found

g_type_query ()

void                g_type_query                        (GType type,
                                                         GTypeQuery *query);

Queries the type system for information about a specific type. This function will fill in a user-provided structure to hold type-specific information. If an invalid GType is passed in, the type member of the GTypeQuery is 0. All members filled into the GTypeQuery structure should be considered constant and have to be left untouched.

type : | the GType value of a static, classed type.
query : | A user provided structure that is filled in with constant values upon success.

GTypeQuery

typedef struct {
  GType		type;
  const gchar  *type_name;
  guint		class_size;
  guint		instance_size;
} GTypeQuery;

A structure holding information for a specific type. It is filled in by the g_type_query() function.

GType type; | the GType value of the type.
const gchar *type_name; | the name of the type.
guint class_size; | the size of the class structure.
guint instance_size; | the size of the instance structure.

GBaseInitFunc ()

void                (*GBaseInitFunc)                    (gpointer g_class);

A callback function used by the type system to do base initialization of the class structures of derived types. It is called as part of the initialization process of all derived classes and should reallocate or reset all dynamic class members copied over from the parent class. For example, class members (such as strings) that are not sufficiently handled by a plain memory copy of the parent class into the derived class have to be altered. See GClassInitFunc() for a discussion of the class intialization process.

g_class : The GTypeClass structure to initialize.

GBaseFinalizeFunc ()

void                (*GBaseFinalizeFunc)                (gpointer g_class);

A callback function used by the type system to finalize those portions of a derived types class structure that were setup from the corresponding GBaseInitFunc() function. Class finalization basically works the inverse way in which class intialization is performed. See GClassInitFunc() for a discussion of the class intialization process.

g_class : The GTypeClass structure to finalize.

GClassInitFunc ()

void                (*GClassInitFunc)                   (gpointer g_class,
                                                         gpointer class_data);

A callback function used by the type system to initialize the class of a specific type. This function should initialize all static class members. The initialization process of a class involves:

1 - Copying common members from the parent class over to the derived class structure.

2 - Zero initialization of the remaining members not copied over from the parent class.

3 - Invocation of the GBaseInitFunc() initializers of all parent types and the class' type.

4 - Invocation of the class' GClassInitFunc() initializer.

Since derived classes are partially initialized through a memory copy of the parent class, the general rule is that GBaseInitFunc() and GBaseFinalizeFunc() should take care of necessary reinitialization and release of those class members that were introduced by the type that specified these GBaseInitFunc()/GBaseFinalizeFunc(). GClassInitFunc() should only care about initializing static class members, while dynamic class members (such as allocated strings or reference counted resources) are better handled by a GBaseInitFunc() for this type, so proper initialization of the dynamic class members is performed for class initialization of derived types as well. An example may help to correspond the intend of the different class initializers:

typedef struct {
  GObjectClass parent_class;
  gint         static_integer;
  gchar       *dynamic_string;
} TypeAClass;
static void
type_a_base_class_init (TypeAClass *class)
{
  class->dynamic_string = g_strdup ("some string");
}
static void
type_a_base_class_finalize (TypeAClass *class)
{
  g_free (class->dynamic_string);
}
static void
type_a_class_init (TypeAClass *class)
{
  class->static_integer = 42;
}

typedef struct {
  TypeAClass   parent_class;
  gfloat       static_float;
  GString     *dynamic_gstring;
} TypeBClass;
static void
type_b_base_class_init (TypeBClass *class)
{
  class->dynamic_gstring = g_string_new ("some other string");
}
static void
type_b_base_class_finalize (TypeBClass *class)
{
  g_string_free (class->dynamic_gstring);
}
static void
type_b_class_init (TypeBClass *class)
{
  class->static_float = 3.14159265358979323846;
}

Initialization of TypeBClass will first cause initialization of TypeAClass (derived classes reference their parent classes, see g_type_class_ref() on this). Initialization of TypeAClass roughly involves zero-initializing its fields, then calling its GBaseInitFunc() type_a_base_class_init() to allocate its dynamic members (dynamic_string), and finally calling its GClassInitFunc() type_a_class_init() to initialize its static members (static_integer). The first step in the initialization process of TypeBClass is then a plain memory copy of the contents of TypeAClass into TypeBClass and zero-initialization of the remaining fields in TypeBClass. The dynamic members of TypeAClass within TypeBClass now need reinitialization which is performed by calling type_a_base_class_init() with an argument of TypeBClass. After that, the GBaseInitFunc() of TypeBClass, type_b_base_class_init() is called to allocate the dynamic members of TypeBClass (dynamic_gstring), and finally the GClassInitFunc() of TypeBClass, type_b_class_init(), is called to complete the initialization process with the static members (static_float). Corresponding finalization counter parts to the GBaseInitFunc() functions have to be provided to release allocated resources at class finalization time.

g_class : | The GTypeClass structure to initialize.
class_data : | The class_data member supplied via the GTypeInfo structure.

GClassFinalizeFunc ()

void                (*GClassFinalizeFunc)               (gpointer g_class,
                                                         gpointer class_data);

A callback function used by the type system to finalize a class. This function is rarely needed, as dynamically allocated class resources should be handled by GBaseInitFunc() and GBaseFinalizeFunc(). Also, specification of a GClassFinalizeFunc() in the GTypeInfo structure of a static type is invalid, because classes of static types will never be finalized (they are artificially kept alive when their reference count drops to zero).

g_class : | The GTypeClass structure to finalize.
class_data : | The class_data member supplied via the GTypeInfo structure.

GInstanceInitFunc ()

void                (*GInstanceInitFunc)                (GTypeInstance *instance,
                                                         gpointer g_class);

A callback function used by the type system to initialize a new instance of a type. This function initializes all instance members and allocates any resources required by it. Initialization of a derived instance involves calling all its parent types instance initializers, so the class member of the instance is altered during its initialization to always point to the class that belongs to the type the current initializer was introduced for.

instance : | The instance to initialize.
g_class : | The class of the type the instance is created for.

GInterfaceInitFunc ()

void                (*GInterfaceInitFunc)               (gpointer g_iface,
                                                         gpointer iface_data);

A callback function used by the type system to initialize a new interface. This function should initialize all internal data and allocate any resources required by the interface.

g_iface : | The interface structure to initialize.
iface_data : | The class_data supplied via the GTypeInfo structure.

GInterfaceFinalizeFunc ()

void                (*GInterfaceFinalizeFunc)           (gpointer g_iface,
                                                         gpointer iface_data);

A callback function used by the type system to finalize an interface. This function should destroy any internal data and release any resources allocated by the corresponding GInterfaceInitFunc() function.

g_iface : | The interface structure to finalize.
iface_data : | The class_data supplied via the GTypeInfo structure.

GTypeClassCacheFunc ()

gboolean            (*GTypeClassCacheFunc)              (gpointer cache_data,
                                                         GTypeClass *g_class);

A callback function which is called when the reference count of a class drops to zero. It may use g_type_class_ref() to prevent the class from being freed. You should not call g_type_class_unref() from a GTypeClassCacheFunc function to prevent infinite recursion, use g_type_class_unref_uncached() instead.

The functions have to check the class id passed in to figure whether they actually want to cache the class of this type, since all classes are routed through the same GTypeClassCacheFunc chain.

cache_data : | data that was given to the g_type_add_class_cache_func() call
g_class : | The GTypeClass structure which is unreferenced
Returns : | TRUE to stop further GTypeClassCacheFuncs from being called, FALSE to continue.

enum GTypeFlags

typedef enum    /*< skip >*/
{
  G_TYPE_FLAG_ABSTRACT		= (1 << 4),
  G_TYPE_FLAG_VALUE_ABSTRACT	= (1 << 5)
} GTypeFlags;

Bit masks used to check or determine characteristics of a type.

G_TYPE_FLAG_ABSTRACT | Indicates an abstract type. No instances can be created for an abstract type.
G_TYPE_FLAG_VALUE_ABSTRACT | Indicates an abstract value type, i.e. a type that introduces a value table, but can't be used for g_value_init().

enum GTypeFundamentalFlags

typedef enum    /*< skip >*/
{
  G_TYPE_FLAG_CLASSED           = (1 << 0),
  G_TYPE_FLAG_INSTANTIATABLE    = (1 << 1),
  G_TYPE_FLAG_DERIVABLE         = (1 << 2),
  G_TYPE_FLAG_DEEP_DERIVABLE    = (1 << 3)
} GTypeFundamentalFlags;

Bit masks used to check or determine specific characteristics of a fundamental type.

G_TYPE_FLAG_CLASSED | Indicates a classed type.
G_TYPE_FLAG_INSTANTIATABLE | Indicates an instantiable type (implies classed).
G_TYPE_FLAG_DERIVABLE | Indicates a flat derivable type.
G_TYPE_FLAG_DEEP_DERIVABLE | Indicates a deep derivable type (implies derivable).

g_type_register_static ()

GType               g_type_register_static              (GType parent_type,
                                                         const gchar *type_name,
                                                         const GTypeInfo *info,
                                                         GTypeFlags flags);

Registers type_name as the name of a new static type derived from parent_type. The type system uses the information contained in the GTypeInfo structure pointed to by info to manage the type and its instances (if not abstract). The value of flags determines the nature (e.g. abstract or not) of the type.

parent_type : | Type from which this type will be derived.
type_name : | 0-terminated string used as the name of the new type.
info : | The GTypeInfo structure for this type.
flags : | Bitwise combination of GTypeFlags values.
Returns : | The new type identifier.

g_type_register_static_simple ()

GType               g_type_register_static_simple       (GType parent_type,
                                                         const gchar *type_name,
                                                         guint class_size,
                                                         GClassInitFunc class_init,
                                                         guint instance_size,
                                                         GInstanceInitFunc instance_init,
                                                         GTypeFlags flags);

Registers type_name as the name of a new static type derived from parent_type. The value of flags determines the nature (e.g. abstract or not) of the type. It works by filling a GTypeInfo struct and calling g_type_info_register_static().

parent_type : | Type from which this type will be derived.
type_name : | 0-terminated string used as the name of the new type.
class_size : | Size of the class structure (see GTypeInfo)
class_init : | Location of the class initialization function (see GTypeInfo)
instance_size : | Size of the instance structure (see GTypeInfo)
instance_init : | Location of the instance initialization function (see GTypeInfo)
flags : | Bitwise combination of GTypeFlags values.
Returns : | The new type identifier.

Since 2.12

g_type_register_dynamic ()

GType               g_type_register_dynamic             (GType parent_type,
                                                         const gchar *type_name,
                                                         GTypePlugin *plugin,
                                                         GTypeFlags flags);

Registers type_name as the name of a new dynamic type derived from parent_type. The type system uses the information contained in the GTypePlugin structure pointed to by plugin to manage the type and its instances (if not abstract). The value of flags determines the nature (e.g. abstract or not) of the type.

parent_type : | Type from which this type will be derived.
type_name : | 0-terminated string used as the name of the new type.
plugin : | The GTypePlugin structure to retrieve the GTypeInfo from.
flags : | Bitwise combination of GTypeFlags values.
Returns : | The new type identifier or G_TYPE_INVALID if registration failed.

g_type_register_fundamental ()

GType               g_type_register_fundamental         (GType type_id,
                                                         const gchar *type_name,
                                                         const GTypeInfo *info,
                                                         const GTypeFundamentalInfo *finfo,
                                                         GTypeFlags flags);

Registers type_id as the predefined identifier and type_name as the name of a fundamental type. The type system uses the information contained in the GTypeInfo structure pointed to by info and the GTypeFundamentalInfo structure pointed to by finfo to manage the type and its instances. The value of flags determines additional characteristics of the fundamental type.

type_id : | A predefined GTypeFundamentals value.
type_name : | 0-terminated string used as the name of the new type.
info : | The GTypeInfo structure for this type.
finfo : | The GTypeFundamentalInfo structure for this type.
flags : | Bitwise combination of GTypeFlags values.
Returns : | The predefined type identifier.

g_type_add_interface_static ()

void                g_type_add_interface_static         (GType instance_type,
                                                         GType interface_type,
                                                         const GInterfaceInfo *info);

Adds the static interface_type to instantiable_type. The information contained in the GTypeInterfaceInfo structure pointed to by info is used to manage the relationship.

instance_type : | GType value of an instantiable type.
interface_type : | GType value of an interface type.
info : | The GInterfaceInfo structure for this (instance_type, interface_type) combination.

g_type_add_interface_dynamic ()

void                g_type_add_interface_dynamic        (GType instance_type,
                                                         GType interface_type,
                                                         GTypePlugin *plugin);

Adds the dynamic interface_type to instantiable_type. The information contained in the GTypePlugin structure pointed to by plugin is used to manage the relationship.

instance_type : | the GType value of an instantiable type.
interface_type : | the GType value of an interface type.
plugin : | the GTypePlugin structure to retrieve the GInterfaceInfo from.

g_type_interface_add_prerequisite ()

void                g_type_interface_add_prerequisite   (GType interface_type,
                                                         GType prerequisite_type);

Adds prerequisite_type to the list of prerequisites of interface_type. This means that any type implementing interface_type must also implement prerequisite_type. Prerequisites can be thought of as an alternative to interface derivation (which GType doesn't support). An interface can have at most one instantiatable prerequisite type.

interface_type : | GType value of an interface type.
prerequisite_type : | GType value of an interface or instantiatable type.

g_type_get_plugin ()

GTypePlugin*        g_type_get_plugin                   (GType type);

Returns the GTypePlugin structure for type or NULL if type does not have a GTypePlugin structure.

type : | The GType to retrieve the plugin for.
Returns : | The corresponding plugin if type is a dynamic type, NULL otherwise.

g_type_interface_get_plugin ()

GTypePlugin*        g_type_interface_get_plugin         (GType instance_type,
                                                         GType interface_type);

Returns the GTypePlugin structure for the dynamic interface interface_type which has been added to instance_type, or NULL if interface_type has not been added to instance_type or does not have a GTypePlugin structure. See g_type_add_interface_dynamic().

instance_type : | the GType value of an instantiatable type.
interface_type : | the GType value of an interface type.
Returns : | the GTypePlugin for the dynamic interface interface_type of instance_type.

g_type_fundamental_next ()

GType               g_type_fundamental_next             (void);

Returns the next free fundamental type id which can be used to register a new fundamental type with g_type_register_fundamental(). The returned type ID represents the highest currently registered fundamental type identifier.

Returns : The nextmost fundamental type ID to be registered, or 0 if the type system ran out of fundamental type IDs.

g_type_fundamental ()

GType               g_type_fundamental                  (GType type_id);

Internal function, used to extract the fundamental type ID portion. use G_TYPE_FUNDAMENTAL() instead.

type_id : | valid type ID
Returns : | fundamental type ID

g_type_create_instance ()

GTypeInstance*      g_type_create_instance              (GType type);

Creates and initializes an instance of type if type is valid and can be instantiated. The type system only performs basic allocation and structure setups for instances: actual instance creation should happen through functions supplied by the type's fundamental type implementation. So use of g_type_create_instance() is reserved for implementators of fundamental types only. E.g. instances of the GObject hierarchy should be created via g_object_new() and never directly through g_type_create_instance() which doesn't handle things like singleton objects or object construction. Note: Do not use this function, unless you're implementing a fundamental type. Also language bindings should not use this function but g_object_new() instead.

type : | An instantiatable type to create an instance for.
Returns : | An allocated and initialized instance, subject to further treatment by the fundamental type implementation.

g_type_free_instance ()

void                g_type_free_instance                (GTypeInstance *instance);

Frees an instance of a type, returning it to the instance pool for the type, if there is one.

Like g_type_create_instance(), this function is reserved for implementors of fundamental types.

instance : an instance of a type.

g_type_add_class_cache_func ()

void                g_type_add_class_cache_func         (gpointer cache_data,
                                                         GTypeClassCacheFunc cache_func);

Adds a GTypeClassCacheFunc to be called before the reference count of a class goes from one to zero. This can be used to prevent premature class destruction. All installed GTypeClassCacheFunc functions will be chained until one of them returns TRUE. The functions have to check the class id passed in to figure whether they actually want to cache the class of this type, since all classes are routed through the same GTypeClassCacheFunc chain.

cache_data : | data to be passed to cache_func
cache_func : | a GTypeClassCacheFunc

g_type_remove_class_cache_func ()

void                g_type_remove_class_cache_func      (gpointer cache_data,
                                                         GTypeClassCacheFunc cache_func);

Removes a previously installed GTypeClassCacheFunc. The cache maintained by cache_func has to be empty when calling g_type_remove_class_cache_func() to avoid leaks.

cache_data : | data that was given when adding cache_func
cache_func : | a GTypeClassCacheFunc

g_type_class_unref_uncached ()

void                g_type_class_unref_uncached         (gpointer g_class);

A variant of g_type_class_unref() for use in GTypeClassCacheFunc implementations. It unreferences a class without consulting the chain of GTypeClassCacheFuncs, avoiding the recursion which would occur otherwise.

g_class : The GTypeClass structure to unreference.

g_type_add_interface_check ()

void                g_type_add_interface_check          (gpointer check_data,
                                                         GTypeInterfaceCheckFunc check_func);

Adds a function to be called after an interface vtable is initialized for any class (i.e. after the interface_init member of GInterfaceInfo has been called).

This function is useful when you want to check an invariant that depends on the interfaces of a class. For instance, the implementation of GObject uses this facility to check that an object implements all of the properties that are defined on its interfaces.

check_data : | data to pass to check_func
check_func : | function to be called after each interface is initialized.

Since 2.4

g_type_remove_interface_check ()

void                g_type_remove_interface_check       (gpointer check_data,
                                                         GTypeInterfaceCheckFunc check_func);

Removes an interface check function added with g_type_add_interface_check().

check_data : | callback data passed to g_type_add_interface_check()
check_func : | callback function passed to g_type_add_interface_check()

Since 2.4

GTypeInterfaceCheckFunc ()

void                (*GTypeInterfaceCheckFunc)          (gpointer check_data,
                                                         gpointer g_iface);

A callback called after an interface vtable is initialized. See g_type_add_interface_check().

check_data : | data passed to g_type_add_interface_check().
g_iface : | the interface that has been initialized

Since 2.4

g_type_value_table_peek ()

GTypeValueTable*    g_type_value_table_peek             (GType type);

Returns the location of the GTypeValueTable associated with type. Note that this function should only be used from source code that implements or has internal knowledge of the implementation of type.

type : | A GType value.
Returns : | Location of the GTypeValueTable associated with type or NULL if there is no GTypeValueTable associated with type.

G_DEFINE_TYPE()

#define G_DEFINE_TYPE(TN, t_n, T_P)			    G_DEFINE_TYPE_EXTENDED (TN, t_n, T_P, 0, {})

A convenience macro for type implementations, which declares a class initialization function, an instance initialization function (see GTypeInfo for information about these) and a static variable named t_n_parent_class pointing to the parent class. Furthermore, it defines a *_get_type() function. See G_DEFINE_TYPE_EXTENDED() for an example.

TN : | The name of the new type, in Camel case.
t_n : | The name of the new type, in lowercase, with words separated by '_'.
T_P : | The GType of the parent type.

Since 2.4

G_DEFINE_TYPE_WITH_CODE()

#define G_DEFINE_TYPE_WITH_CODE(TN, t_n, T_P, _C_)	    _G_DEFINE_TYPE_EXTENDED_BEGIN (TN, t_n, T_P, 0) {_C_;} _G_DEFINE_TYPE_EXTENDED_END()

A convenience macro for type implementations. Similar to G_DEFINE_TYPE(), but allows to insert custom code into the *_get_type() function, e.g. interface implementations via G_IMPLEMENT_INTERFACE(). See G_DEFINE_TYPE_EXTENDED() for an example.

TN : | The name of the new type, in Camel case.
t_n : | The name of the new type in lowercase, with words separated by '_'.
T_P : | The GType of the parent type.
_C_ : | Custom code that gets inserted in the *_get_type() function.

Since 2.4

G_DEFINE_ABSTRACT_TYPE()

#define G_DEFINE_ABSTRACT_TYPE(TN, t_n, T_P)		    G_DEFINE_TYPE_EXTENDED (TN, t_n, T_P, G_TYPE_FLAG_ABSTRACT, {})

A convenience macro for type implementations. Similar to G_DEFINE_TYPE(), but defines an abstract type. See G_DEFINE_TYPE_EXTENDED() for an example.

TN : | The name of the new type, in Camel case.
t_n : | The name of the new type, in lowercase, with words separated by '_'.
T_P : | The GType of the parent type.

Since 2.4

G_DEFINE_ABSTRACT_TYPE_WITH_CODE()

#define G_DEFINE_ABSTRACT_TYPE_WITH_CODE(TN, t_n, T_P, _C_) _G_DEFINE_TYPE_EXTENDED_BEGIN (TN, t_n, T_P, G_TYPE_FLAG_ABSTRACT) {_C_;} _G_DEFINE_TYPE_EXTENDED_END()

A convenience macro for type implementations. Similar to G_DEFINE_TYPE_WITH_CODE(), but defines an abstract type and allows to insert custom code into the *_get_type() function, e.g. interface implementations via G_IMPLEMENT_INTERFACE(). See G_DEFINE_TYPE_EXTENDED() for an example.

TN : | The name of the new type, in Camel case.
t_n : | The name of the new type, in lowercase, with words separated by '_'.
T_P : | The GType of the parent type.
_C_ : | Custom code that gets inserted in the @type_name_get_type() function.

Since 2.4

G_IMPLEMENT_INTERFACE()

#define             G_IMPLEMENT_INTERFACE(TYPE_IFACE, iface_init)

A convenience macro to ease interface addition in the _C_ section of G_DEFINE_TYPE_WITH_CODE() or G_DEFINE_ABSTRACT_TYPE_WITH_CODE(). See G_DEFINE_TYPE_EXTENDED() for an example.

Note that this macro can only be used together with the G_DEFINE_TYPE_* macros, since it depends on variable names from those macros.

TYPE_IFACE : | The GType of the interface to add
iface_init : | The interface init function

Since 2.4

G_DEFINE_TYPE_EXTENDED()

#define G_DEFINE_TYPE_EXTENDED(TN, t_n, T_P, _f_, _C_)	    _G_DEFINE_TYPE_EXTENDED_BEGIN (TN, t_n, T_P, _f_) {_C_;} _G_DEFINE_TYPE_EXTENDED_END()

The most general convenience macro for type implementations, on which G_DEFINE_TYPE(), etc are based.

G_DEFINE_TYPE_EXTENDED (GtkGadget,
                        gtk_gadget,
                        GTK_TYPE_WIDGET,
                        0,
                        G_IMPLEMENT_INTERFACE (TYPE_GIZMO,
                                               gtk_gadget_gizmo_init));
expands to
static void     gtk_gadget_init       (GtkGadget      *self);
static void     gtk_gadget_class_init (GtkGadgetClass *klass);
static gpointer gtk_gadget_parent_class = NULL;
static void     gtk_gadget_class_intern_init (gpointer klass)
{
  gtk_gadget_parent_class = g_type_class_peek_parent (klass);
  gtk_gadget_class_init ((GtkGadgetClass*) klass);
}

GType
gtk_gadget_get_type (void)
{
  static GType g_define_type_id = 0;
  if (G_UNLIKELY (g_define_type_id == 0))
    {
      static const GTypeInfo g_define_type_info = {
        sizeof (GtkGadgetClass),
        (GBaseInitFunc) NULL,
        (GBaseFinalizeFunc) NULL,
        (GClassInitFunc) gtk_gadget_class_intern_init,
        (GClassFinalizeFunc) NULL,
        NULL,   /* class_data */
        sizeof (GtkGadget),
        0,      /* n_preallocs */
        (GInstanceInitFunc) gtk_gadget_init,
      };
      g_define_type_id = g_type_register_static (GTK_TYPE_WIDGET, "GtkGadget", &g_define_type_info, 0);
      {
        static const GInterfaceInfo g_implement_interface_info = {
          (GInterfaceInitFunc) gtk_gadget_gizmo_init
        };
        g_type_add_interface_static (g_define_type_id, TYPE_GIZMO, &g_implement_interface_info);
      }
    }
  return g_define_type_id;
}
The only pieces which have to be manually provided are the definitions of the instance and class structure and the definitions of the instance and class init functions.
TN :
t_n :
T_P :
_f_ :
_C_ :

Since 2.4

G_TYPE_INVALID

#define G_TYPE_INVALID			G_TYPE_MAKE_FUNDAMENTAL (0)

An invalid GType used as error return value in some functions which return a GType.

G_TYPE_NONE

#define G_TYPE_NONE			G_TYPE_MAKE_FUNDAMENTAL (1)

A fundamental type which is used as a replacement for the C void return type.

G_TYPE_INTERFACE

#define G_TYPE_INTERFACE		G_TYPE_MAKE_FUNDAMENTAL (2)

The fundamental type from which all interfaces are derived.

G_TYPE_CHAR

#define G_TYPE_CHAR			G_TYPE_MAKE_FUNDAMENTAL (3)

The fundamental type corresponding to gchar. The type designated by G_TYPE_CHAR is unconditionally an 8-bit signed integer. This may or may not be the same type a the C type "gchar".

G_TYPE_UCHAR

#define G_TYPE_UCHAR			G_TYPE_MAKE_FUNDAMENTAL (4)

The fundamental type corresponding to guchar.

G_TYPE_BOOLEAN

#define G_TYPE_BOOLEAN			G_TYPE_MAKE_FUNDAMENTAL (5)

The fundamental type corresponding to gboolean.

G_TYPE_INT

#define G_TYPE_INT			G_TYPE_MAKE_FUNDAMENTAL (6)

The fundamental type corresponding to gint.

G_TYPE_UINT

#define G_TYPE_UINT			G_TYPE_MAKE_FUNDAMENTAL (7)

The fundamental type corresponding to guint.

G_TYPE_LONG

#define G_TYPE_LONG			G_TYPE_MAKE_FUNDAMENTAL (8)

The fundamental type corresponding to glong.

G_TYPE_ULONG

#define G_TYPE_ULONG			G_TYPE_MAKE_FUNDAMENTAL (9)

The fundamental type corresponding to gulong.

G_TYPE_INT64

#define G_TYPE_INT64			G_TYPE_MAKE_FUNDAMENTAL (10)

The fundamental type corresponding to gint64.

G_TYPE_UINT64

#define G_TYPE_UINT64			G_TYPE_MAKE_FUNDAMENTAL (11)

The fundamental type corresponding to guint64.

G_TYPE_ENUM

#define G_TYPE_ENUM			G_TYPE_MAKE_FUNDAMENTAL (12)

The fundamental type from which all enumeration types are derived.

G_TYPE_FLAGS

#define G_TYPE_FLAGS			G_TYPE_MAKE_FUNDAMENTAL (13)

The fundamental type from which all flags types are derived.

G_TYPE_FLOAT

#define G_TYPE_FLOAT			G_TYPE_MAKE_FUNDAMENTAL (14)

The fundamental type corresponding to gfloat.

G_TYPE_DOUBLE

#define G_TYPE_DOUBLE			G_TYPE_MAKE_FUNDAMENTAL (15)

The fundamental type corresponding to gdouble.

G_TYPE_STRING

#define G_TYPE_STRING			G_TYPE_MAKE_FUNDAMENTAL (16)

The fundamental type corresponding to nul-terminated C strings.

G_TYPE_POINTER

#define G_TYPE_POINTER			G_TYPE_MAKE_FUNDAMENTAL (17)

The fundamental type corresponding to gpointer.

G_TYPE_BOXED

#define G_TYPE_BOXED			G_TYPE_MAKE_FUNDAMENTAL (18)

The fundamental type from which all boxed types are derived.

G_TYPE_PARAM

#define G_TYPE_PARAM			G_TYPE_MAKE_FUNDAMENTAL (19)

The fundamental type from which all GParamSpec types are derived.

G_TYPE_OBJECT

#define G_TYPE_OBJECT			G_TYPE_MAKE_FUNDAMENTAL (20)

The fundamental type for GObject.

G_TYPE_GTYPE

#define	G_TYPE_GTYPE			 (g_gtype_get_type())

The type for GType.

G_TYPE_RESERVED_GLIB_FIRST

#define G_TYPE_RESERVED_GLIB_FIRST	(21)

First fundamental type number to create a new fundamental type id with G_TYPE_MAKE_FUNDAMENTAL() reserved for GLib.

G_TYPE_RESERVED_GLIB_LAST

#define G_TYPE_RESERVED_GLIB_LAST	(31)

Last fundamental type number reserved for GLib.

G_TYPE_RESERVED_BSE_FIRST

#define G_TYPE_RESERVED_BSE_FIRST	(32)

First fundamental type number to create a new fundamental type id with G_TYPE_MAKE_FUNDAMENTAL() reserved for BSE.

G_TYPE_RESERVED_BSE_LAST

#define G_TYPE_RESERVED_BSE_LAST	(48)

Last fundamental type number reserved for BSE.

G_TYPE_RESERVED_USER_FIRST

#define G_TYPE_RESERVED_USER_FIRST	(49)

First available fundamental type number to create new fundamental type id with G_TYPE_MAKE_FUNDAMENTAL().


Value arrays

Value arrays — A container structure to maintain an array of generic values

Synopsis

#include <glib-object.h>

                    GValueArray;
GValue*             g_value_array_get_nth               (GValueArray *value_array,
                                                         guint index_);
GValueArray*        g_value_array_new                   (guint n_prealloced);
GValueArray*        g_value_array_copy                  (const GValueArray *value_array);
void                g_value_array_free                  (GValueArray *value_array);
GValueArray*        g_value_array_append                (GValueArray *value_array,
                                                         const GValue *value);
GValueArray*        g_value_array_prepend               (GValueArray *value_array,
                                                         const GValue *value);
GValueArray*        g_value_array_insert                (GValueArray *value_array,
                                                         guint index_,
                                                         const GValue *value);
GValueArray*        g_value_array_remove                (GValueArray *value_array,
                                                         guint index_);
GValueArray*        g_value_array_sort                  (GValueArray *value_array,
                                                         GCompareFunc compare_func);
GValueArray*        g_value_array_sort_with_data        (GValueArray *value_array,
                                                         GCompareDataFunc compare_func,
                                                         gpointer user_data);

Description

The prime purpose of a GValueArray is for it to be used as an object property that holds an array of values. A GValueArray wraps an array of GValue elements in order for it to be used as a boxed type through G_TYPE_VALUE_ARRAY.

Details

GValueArray

typedef struct {
  guint   n_values;
  GValue *values;
} GValueArray;

A GValueArray contains an array of GValue elements.

guint n_values; | number of values contained in the array
GValue *values; | array of values

g_value_array_get_nth ()

GValue*             g_value_array_get_nth               (GValueArray *value_array,
                                                         guint index_);

Return a pointer to the value at index_ containd in value_array.

value_array : | GValueArray to get a value from
index_ : | index of the value of interest
Returns : | pointer to a value at index_ in value_array

g_value_array_new ()

GValueArray*        g_value_array_new                   (guint n_prealloced);

Allocate and initialize a new GValueArray, optionally preserve space for n_prealloced elements. New arrays always contain 0 elements, regardless of the value of n_prealloced.

n_prealloced : | number of values to preallocate space for
Returns : | a newly allocated GValueArray with 0 values

g_value_array_copy ()

GValueArray*        g_value_array_copy                  (const GValueArray *value_array);

Construct an exact copy of a GValueArray by duplicating all its contents.

value_array : | GValueArray to copy
Returns : | Newly allocated copy of GValueArray

g_value_array_free ()

void                g_value_array_free                  (GValueArray *value_array);

Free a GValueArray including its contents.

value_array : GValueArray to free

g_value_array_append ()

GValueArray*        g_value_array_append                (GValueArray *value_array,
                                                         const GValue *value);

Insert a copy of value as last element of value_array.

value_array : | GValueArray to add an element to
value : | GValue to copy into GValueArray
Returns : | the GValueArray passed in as value_array

g_value_array_prepend ()

GValueArray*        g_value_array_prepend               (GValueArray *value_array,
                                                         const GValue *value);

Insert a copy of value as first element of value_array.

value_array : | GValueArray to add an element to
value : | GValue to copy into GValueArray
Returns : | the GValueArray passed in as value_array

g_value_array_insert ()

GValueArray*        g_value_array_insert                (GValueArray *value_array,
                                                         guint index_,
                                                         const GValue *value);

Insert a copy of value at specified position into value_array.

value_array : | GValueArray to add an element to
index_ : | insertion position, must be <= value_array->n_values
value : | GValue to copy into GValueArray
Returns : | the GValueArray passed in as value_array

g_value_array_remove ()

GValueArray*        g_value_array_remove                (GValueArray *value_array,
                                                         guint index_);

Remove the value at position index_ from value_array.

value_array : | GValueArray to remove an element from
index_ : | position of value to remove, must be < value_array->n_values
Returns : | the GValueArray passed in as value_array

g_value_array_sort ()

GValueArray*        g_value_array_sort                  (GValueArray *value_array,
                                                         GCompareFunc compare_func);

Sort value_array using compare_func to compare the elements accoring to the semantics of GCompareFunc.

The current implementation uses Quick-Sort as sorting algorithm.

value_array : | GValueArray to sort
compare_func : | function to compare elements
Returns : | the GValueArray passed in as value_array

g_value_array_sort_with_data ()

GValueArray*        g_value_array_sort_with_data        (GValueArray *value_array,
                                                         GCompareDataFunc compare_func,
                                                         gpointer user_data);

Sort value_array using compare_func to compare the elements accoring to the semantics of GCompareDataFunc.

The current implementation uses Quick-Sort as sorting algorithm.

value_array : | GValueArray to sort
compare_func : | function to compare elements
user_data : | extra data argument provided for compare_func
Returns : | the GValueArray passed in as value_array

See Also

GValue, GParamSpecValueArray, g_param_spec_value_array()


Varargs Value Collection

Varargs Value Collection — Converting varargs to generic values

Synopsis

#include <glib-object.h>
#include <gobject/gvaluecollector.h>

union               GTypeCValue;
#define             G_VALUE_COLLECT                     (value, var_args, flags, __error)
#define             G_VALUE_LCOPY                       (value, var_args, flags, __error)
#define             G_VALUE_COLLECT_FORMAT_MAX_LENGTH

Description

The macros in this section provide the varargs parsing support needed in variadic GObject functions such as g_object_new() or g_object_set(). They currently support the collection of integral types, floating point types and pointers.

Details

union GTypeCValue

union GTypeCValue
{
  gint     v_int;
  glong    v_long;
  gint64   v_int64;
  gdouble  v_double;
  gpointer v_pointer;
};

A union holding one collected value.

G_VALUE_COLLECT()

#define             G_VALUE_COLLECT(value, var_args, flags, __error)

Collects a variable argument value from a va_list. We have to implement the varargs collection as a macro, because on some systems va_list variables cannot be passed by reference.

value : | a GValue return location. value is supposed to be initialized according to the value type to be collected
var_args : | the va_list variable; it may be evaluated multiple times
flags : | flags which are passed on to the collect_value() function of the GTypeValueTable of value.
__error : | a gchar** variable that will be modified to hold a g_new() allocated error messages if something fails

G_VALUE_LCOPY()

#define             G_VALUE_LCOPY(value, var_args, flags, __error)

Collects a value's variable argument locations from a va_list.

value : | a GValue return location. value is supposed to be initialized according to the value type to be collected
var_args : | the va_list variable; it may be evaluated multiple times
flags : | flags which are passed on to the lcopy_value() function of the GTypeValueTable of value.
__error : | a gchar** variable that will be modified to hold a g_new() allocated error messages if something fails

G_VALUE_COLLECT_FORMAT_MAX_LENGTH

#define	G_VALUE_COLLECT_FORMAT_MAX_LENGTH	(8)

The maximal number of GTypeCValues which can be collected for a single GValue.

See Also

GValueTable


Conventions

There are a number of conventions users are expected to follow when creating new types which are to be exported in a header file:

  • Use the object_method pattern for function names: to invoke the method named foo on an instance of object type bar, call bar_foo.

  • Use prefixing to avoid namespace conflicts with other projects. If your library (or application) is named Maman, prefix all your function names with maman_. For example: maman_object_method.

  • Create a macro named PREFIX_OBJECT_TYPE which always returns the Gtype for the associated object type. For an object of type Bar in a libray prefixed by maman, use: MAMAN_BAR_TYPE. It is common although not a convention to implement this macro using either a global static variable or a function named prefix_object_get_type. We will follow the function pattern wherever possible in this document.

  • Create a macro named PREFIX_OBJECT (obj) which returns a pointer of type PrefixObject. This macro is used to enforce static type safety by doing explicit casts wherever needed. It also enforces dynamic type safety by doing runtime checks. It is possible to disable the dynamic type checks in production builds (see building glib). For example, we would create MAMAN_BAR (obj) to keep the previous example.

  • If the type is classed, create a macro named PREFIX_OBJECT_CLASS (klass). This macro is strictly equivalent to the previous casting macro: it does static casting with dynamic type checking of class structures. It is expected to return a pointer to a class structure of type PrefixObjectClass. Again, an example is: MAMAN_BAR_CLASS.

  • Create a macro named PREFIX_IS_BAR (obj): this macro is expected to return a gboolean which indicates whether or not the input object instance pointer of type BAR.

  • If the type is classed, create a macro named PREFIX_IS_OBJECT_CLASS (klass) which, as above, returns a boolean if the input class pointer is a pointer to a class of type OBJECT.

  • If the type is classed, create a macro named PREFIX_OBJECT_GET_CLASS (obj) which returns the class pointer associated to an instance of a given type. This macro is used for static and dynamic type safety purposes (just like the previous casting macros).

The implementation of these macros is pretty straightforward: a number of simple-to-use macros are provided in gtype.h. For the example we used above, we would write the following trivial code to declare the macros:

#define MAMAN_BAR_TYPE		  (maman_bar_get_type ())
#define MAMAN_BAR(obj)		  (G_TYPE_CHECK_INSTANCE_CAST ((obj), MAMAN_BAR_TYPE, MamanBar))
#define MAMAN_BAR_CLASS(klass)	  (G_TYPE_CHECK_CLASS_CAST ((klass), MAMAN_BAR_TYPE, MamanBarClass))
#define MAMAN_IS_BAR(obj)	  (G_TYPE_CHECK_INSTANCE_TYPE ((obj), MAMAN_BAR_TYPE))
#define MAMAN_IS_BAR_CLASS(klass) (G_TYPE_CHECK_CLASS_TYPE ((klass), MAMAN_BAR_TYPE))
#define MAMAN_BAR_GET_CLASS(obj)  (G_TYPE_INSTANCE_GET_CLASS ((obj), MAMAN_BAR_TYPE, MamanBarClass))

Note

Stick to the naming klass as class is a registered c++ keyword.

The following code shows how to implement the maman_bar_get_type function:

GType maman_bar_get_type (void)
{
  static GType type = 0;
  if (type == 0) {
    static const GTypeInfo info = {
      /* You fill this structure. */
    };
    type = g_type_register_static (G_TYPE_OBJECT,
                                   "MamanBarType",
                                   &info, 0);
  }
  return type;
}


Instantiable classed types: objects

Types which are registered with a class and are declared instantiable are what most closely resembles an object. Although GObjects (detailed in The GObject base class) are the most well known type of instantiable classed types, other kinds of similar objects used as the base of an inheritance hierarchy have been externally developped and they are all built on the fundamental features described below.

For example, the code below shows how you could register such a fundamental object type in the type system:

typedef struct {
  GObject parent;
  /* instance members */
  int field_a;
} MamanBar;

typedef struct {
  GObjectClass parent;
  /* class members */
  void (*do_action_public_virtual) (MamanBar *self, guint8 i);

  void (*do_action_public_pure_virtual) (MamanBar *self, guint8 i);
} MamanBarClass;

#define MAMAN_BAR_TYPE (maman_bar_get_type ())

GType
maman_bar_get_type (void)
{
  static GType type = 0;
  if (type == 0) {
    static const GTypeInfo info = {
      sizeof (MamanBarClass),
      NULL,           /* base_init */
      NULL,           /* base_finalize */
      (GClassInitFunc) foo_class_init,
      NULL,           /* class_finalize */
      NULL,           /* class_data */
      sizeof (MamanBar),
      0,              /* n_preallocs */
      (GInstanceInitFunc) NULL /* instance_init */
    };
    type = g_type_register_static (G_TYPE_OBJECT,
                                   "BarType",
                                   &info, 0);
  }
  return type;
}

Upon the first call to maman_bar_get_type, the type named BarType will be registered in the type system as inheriting from the type G_TYPE_OBJECT.

Every object must define two structures: its class structure and its instance structure. All class structures must contain as first member a GTypeClass structure. All instance structures must contain as first member a GTypeInstance structure. The declaration of these C types, coming from gtype.h is shown below:

struct _GTypeClass
{
  GType g_type;
};
struct _GTypeInstance
{
  GTypeClass *g_class;
};

These constraints allow the type system to make sure that every object instance (identified by a pointer to the object's instance structure) contains in its first bytes a pointer to the object's class structure.

This relationship is best explained by an example: let's take object B which inherits from object A:

/* A definitions */
typedef struct {
  GTypeInstance parent;
  int field_a;
  int field_b;
} A;
typedef struct {
  GTypeClass parent_class;
  void (*method_a) (void);
  void (*method_b) (void);
} AClass;

/* B definitions. */
typedef struct {
  A parent;
  int field_c;
  int field_d;
} B;
typedef struct {
  AClass parent_class;
  void (*method_c) (void);
  void (*method_d) (void);
} BClass;

The C standard mandates that the first field of a C structure is stored starting in the first byte of the buffer used to hold the structure's fields in memory. This means that the first field of an instance of an object B is A's first field which in turn is GTypeInstance's first field which in turn is g_class, a pointer to B's class structure.

Thanks to these simple conditions, it is possible to detect the type of every object instance by doing:

B *b;
b->parent.parent.g_class->g_type

or, more quickly:

B *b;
((GTypeInstance*)b)->g_class->g_type

Instanciation of these types can be done with g_type_create_instance:

GTypeInstance* g_type_create_instance (GType          type);
void           g_type_free_instance   (GTypeInstance *instance);

g_type_create_instance will lookup the type information structure associated to the type requested. Then, the instance size and instanciation policy (if the n_preallocs field is set to a non-zero value, the type system allocates the object's instance structures in chunks rather than mallocing for every instance) declared by the user are used to get a buffer to hold the object's instance structure.

If this is the first instance of the object ever created, the type system must create a class structure: it allocates a buffer to hold the object's class structure and initializes it. It first copies the parent's class structure over this structure (if there is no parent, it initializes it to zero). It then invokes the base_class_initialization functions (GBaseInitFunc) from topmost fundamental object to bottom-most most derived object. The object's class_init (GClassInitFunc) function is invoked afterwards to complete initialization of the class structure. Finally, the object's interfaces are initialized (we will discuss interface initialization in more detail later). [3]

Once the type system has a pointer to an initialized class structure, it sets the object's instance class pointer to the object's class structure and invokes the object's instance_init (GInstanceInitFunc)functions, from top-most fundamental type to bottom-most most derived type.

Object instance destruction through g_type_free_instance is very simple: the instance structure is returned to the instance pool if there is one and if this was the last living instance of the object, the class is destroyed.

Class destruction [4] (the concept of destruction is sometimes partly refered to as finalization in Gtype) is the symmetric process of the initialization: interfaces are destroyed first. Then, the most derived class_finalize (ClassFinalizeFunc) function is invoked. The base_class_finalize (GBaseFinalizeFunc) functions are Finally invoked from bottom-most most-derived type to top-most fundamental type and the class structure is freed.

As many readers have now understood it, the base initialization/finalization process is very similar to the C++ Constructor/Destructor paradigm. The practical details are quite different though and it is important not to get confused by the superficial similarities. Typically, what most users have grown to know as a C++ constructor (that is, a list of object methods invoked on the object instance once for each type of the inheritance hierachy) does not exist in GType and must be built on top of the facilities offered by GType. Similarly, GTypes have no instance destruction mechanism. It is the user's responsibility to implement correct destruction semantics on top of the existing GType code. (this is what GObject does. See The GObject base class)

For example, if the object B which derives from A is instantiated, GType will only invoke the instance_init callback of object B while a C++ runtime will invoke the constructor of the object type A first and then of the object type B. Furthermore, the C++ code equivalent to the base_init and class_init callbacks of GType is usually not needed because C++ cannot really create object types at runtime.

The instanciation/finalization process can be summarized as follows:

Table 1. GType Instantiation/Finalization

Invocation time | Function Invoked | Function's parameters
First call to g_type_create_instance for target type | type's base_init function | On the inheritance tree of classes from fundamental type to target type. base_init is invoked once for each class structure.
First call to g_type_create_instance for target type | target type's class_init function | On target type's class structure
First call to g_type_create_instance for target type | interface initialization, see the section called “Interface Initialization” |
Each call to g_type_create_instance for target type | target type's instance_init function | On object's instance
Last call to g_type_free_instance for target type | interface destruction, see the section called “Interface Destruction” |
Last call to g_type_free_instance for target type | target type's class_finalize function | On target type's class structure
Last call to g_type_free_instance for target type | type's base_finalize function | On the inheritance tree of classes from fundamental type to target type. base_finalize is invoked once for each class structure.

[3] The class initialization process is entirely implemented in type_class_init_Wm in gtype.c.

[4] It is implemented in type_data_finalize_class_U (in gtype.c.


Non-Instantiable non-classed fundamental types

A lot of types are not instantiable by the type system and do not have a class. Most of these types are fundamental trivial types such as gchar, registered in g_value_types_init (in gvaluetypes.c).

To register such a type in the type system, you just need to fill the GTypeInfo structure with zeros since these types are also most of the time fundamental:

  GTypeInfo info = {
    0,				/* class_size */
    NULL,			/* base_init */
    NULL,			/* base_destroy */
    NULL,			/* class_init */
    NULL,			/* class_destroy */
    NULL,			/* class_data */
    0,				/* instance_size */
    0,				/* n_preallocs */
    NULL,			/* instance_init */
    NULL,			/* value_table */
  };
  static const GTypeValueTable value_table = {
    value_init_long0,		/* value_init */
    NULL,			/* value_free */
    value_copy_long0,		/* value_copy */
    NULL,			/* value_peek_pointer */
    "i",			/* collect_format */
    value_collect_int,	/* collect_value */
    "p",			/* lcopy_format */
    value_lcopy_char,		/* lcopy_value */
  };
  info.value_table = &value_table;
  type = g_type_register_fundamental (G_TYPE_CHAR, "gchar", &info, &finfo, 0);

Having non-instantiable types might seem a bit useless: what good is a type if you cannot instanciate an instance of that type ? Most of these types are used in conjunction with GValues: a GValue is initialized with an integer or a string and it is passed around by using the registered type's value_table. GValues (and by extension these trivial fundamental types) are most useful when used in conjunction with object properties and signals.


Non-instantiable classed types: Interfaces.

GType's Interfaces are very similar to Java's interfaces. To declare one of these you have to register a non-instantiable classed type which derives from GTypeInterface. The following piece of code declares such an interface.

#define MAMAN_IBAZ_TYPE                (maman_ibaz_get_type ())
#define MAMAN_IBAZ(obj)                (G_TYPE_CHECK_INSTANCE_CAST ((obj), MAMAN_IBAZ_TYPE, MamanIbaz))
#define MAMAN_IS_IBAZ(obj)             (G_TYPE_CHECK_INSTANCE_TYPE ((obj), MAMAN_IBAZ_TYPE))
#define MAMAN_IBAZ_GET_INTERFACE(inst) (G_TYPE_INSTANCE_GET_INTERFACE ((inst), MAMAN_IBAZ_TYPE, MamanIbazInterface))

typedef struct _MamanIbaz MamanIbaz; /* dummy object */
typedef struct _MamanIbazInterface MamanIbazInterface;

struct _MamanIbazInterface {
  GTypeInterface parent;

  void (*do_action) (MamanIbaz *self);
};

GType maman_ibaz_get_type (void);

void maman_ibaz_do_action (MamanIbaz *self);

The interface function, maman_ibaz_do_action is implemented in a pretty simple way:

void maman_ibaz_do_action (MamanIbaz *self)
{
  MAMAN_IBAZ_GET_INTERFACE (self)->do_action (self);
}

maman_ibaz_get_type registers a type named MamanIBaz which inherits from G_TYPE_INTERFACE. All interfaces must be children of G_TYPE_INTERFACE in the inheritance tree.

An interface is defined by only one structure which must contain as first member a GTypeInterface structure. The interface structure is expected to contain the function pointers of the interface methods. It is good style to define helper functions for each of the interface methods which simply call the interface' method directly: maman_ibaz_do_action is one of these.

Once an interface type is registered, you must register implementations for these interfaces. The function named maman_baz_get_type registers a new GType named MamanBaz which inherits from GObject and which implements the interface MamanIBaz.

static void maman_baz_do_action (MamanIbaz *self)
{
  g_print ("Baz implementation of IBaz interface Action.\n");
}

static void
baz_interface_init (gpointer         g_iface,
                    gpointer         iface_data)
{
  MamanIbazInterface *iface = (MamanIbazInterface *)g_iface;
  iface->do_action = maman_baz_do_action;
}

GType
maman_baz_get_type (void)
{
  static GType type = 0;
  if (type == 0) {
    static const GTypeInfo info = {
      sizeof (MamanBazInterface),
      NULL,   /* base_init */
      NULL,   /* base_finalize */
      NULL,   /* class_init */
      NULL,   /* class_finalize */
      NULL,   /* class_data */
      sizeof (MamanBaz),
      0,      /* n_preallocs */
      NULL    /* instance_init */
    };
    static const GInterfaceInfo ibaz_info = {
      (GInterfaceInitFunc) baz_interface_init,    /* interface_init */
      NULL,               /* interface_finalize */
      NULL          /* interface_data */
    };
    type = g_type_register_static (G_TYPE_OBJECT,
                                   "MamanBazType",
                                   &info, 0);
    g_type_add_interface_static (type,
                                 MAMAN_IBAZ_TYPE,
                                 &ibaz_info);
  }
  return type;
}

g_type_add_interface_static records in the type system that a given type implements also FooInterface (foo_interface_get_type returns the type of FooInterface). The GInterfaceInfo structure holds information about the implementation of the interface:

struct _GInterfaceInfo
{
  GInterfaceInitFunc     interface_init;
  GInterfaceFinalizeFunc interface_finalize;
  gpointer               interface_data;
};

Interface Initialization

When an instantiable classed type which registered an interface implementation is created for the first time, its class structure is initialized following the process described in the section called “Instantiable classed types: objects”. Once the class structure is initialized,the function type_class_init_Wm (implemented in gtype.c) initializes the interface implementations associated with that type by calling type_iface_vtable_init_Wm for each interface.

First a memory buffer is allocated to hold the interface structure. The parent's interface structure is then copied over to the new interface structure (the parent interface is already initialized at that point). If there is no parent interface, the interface structure is initialized with zeros. The g_type and the g_instance_type fields are then initialized: g_type is set to the type of the most-derived interface and g_instance_type is set to the type of the most derived type which implements this interface.

Finally, the interface' most-derived base_init function and then the implementation's interface_init function are invoked. It is important to understand that if there are multiple implementations of an interface the base_init and interface_init functions will be invoked once for each implementation initialized.

It is thus common for base_init functions to hold a local static boolean variable which makes sure that the interface type is initialized only once even if there are multiple implementations of the interface:

static void
maman_ibaz_base_init (gpointer g_iface)
{
  static gboolean initialized = FALSE;

  if (!initialized) {
    /* create interface signals here. */
    initialized = TRUE;
  }
}

If you have found the stuff about interface hairy, you are right: it is hairy but there is not much I can do about it. What I can do is summarize what you need to know about interfaces:

The above process can be summarized as follows:

Table 2. Interface Initialization

Invocation time | Function Invoked | Function's parameters | Remark
First call to g_type_create_instance for type implementing interface | interface' base_init function | On interface' vtable | Register interface' signals here (use a local static boolean variable as described above to make sure not to register them twice.).
First call to g_type_create_instance for type implementing interface | interface' interface_init function | On interface' vtable | Initialize interface' implementation. That is, initialize the interface method pointers in the interface structure to the function's implementation.

It is highly unlikely (ie: I do not know of anyone who actually used it) you will ever need other more fancy things such as the ones described in the following section (the section called “Interface Destruction”).

Interface Destruction

When the last instance of an instantiable type which registered an interface implementation is destroyed, the interface's implementations associated to the type are destroyed by type_iface_vtable_finalize_Wm (in gtype.c).

type_iface_vtable_finalize_Wm invokes first the implementation's interface_finalize function and then the interface's most-derived base_finalize function.

Again, it is important to understand, as in the section called “Interface Initialization”, that both interface_finalize and base_finalize are invoked exactly once for the destruction of each implementation of an interface. Thus, if you were to use one of these functions, you would need to use a static integer variable which would hold the number of instances of implementations of an interface such that the interface's class is destroyed only once (when the integer variable reaches zero).

The above process can be summarized as follows:

Table 3. Interface Finalization

Invocation time | Function Invoked | Function's parameters
Last call to g_type_free_instance for type implementing interface | interface' interface_finalize function | On interface' vtable
Last call to g_type_free_instancefor type implementing interface | interface' base_finalize function | On interface' vtable

Now that you have read this section, you can forget about it. Please, forget it as soon as possible.


GTypeModule

GTypeModule — Type loading modules

Synopsis

#include <glib-object.h>

                    GTypeModule;
                    GTypeModuleClass;
gboolean            g_type_module_use                   (GTypeModule *module);
void                g_type_module_unuse                 (GTypeModule *module);
void                g_type_module_set_name              (GTypeModule *module,
                                                         const gchar *name);
GType               g_type_module_register_type         (GTypeModule *module,
                                                         GType parent_type,
                                                         const gchar *type_name,
                                                         const GTypeInfo *type_info,
                                                         GTypeFlags flags);
void                g_type_module_add_interface         (GTypeModule *module,
                                                         GType instance_type,
                                                         GType interface_type,
                                                         const GInterfaceInfo *interface_info);
GType               g_type_module_register_enum         (GTypeModule *module,
                                                         const gchar *name,
                                                         const GEnumValue *const _static_values);
GType               g_type_module_register_flags        (GTypeModule *module,
                                                         const gchar *name,
                                                         const GFlagsValue *const _static_values);

Object Hierarchy

  GObject
   +----GTypeModule

Implemented Interfaces

GTypeModule implements GTypePlugin.

Description

GTypeModule provides a simple implementation of the GTypePlugin interface. The model of GTypeModule is a dynamically loaded module which implements some number of types and interface implementations. When the module is loaded, it registers its types and interfaces using g_type_module_register_type() and g_type_module_add_interface(). As long as any instances of these types and interface implementations are in use, the module is kept loaded. When the types and interfaces are gone, the module may be unloaded. If the types and interfaces become used again, the module will be reloaded. Note that the last unref can not happen in module code, since that would lead to the caller's code being unloaded before g_object_unref() returns to it.

Keeping track of whether the module should be loaded or not is done by using a use count - it starts at zero, and whenever it is greater than zero, the module is loaded. The use count is maintained internally by the type system, but also can be explicitly controlled by g_type_module_use() and g_type_module_unuse(). Typically, when loading a module for the first type, g_type_module_use() will be used to load it so that it can initialize its types. At some later point, when the module no longer needs to be loaded except for the type implementations it contains, g_type_module_unuse() is called.

GTypeModule does not actually provide any implementation of module loading and unloading. To create a particular module type you must derive from GTypeModule and implement the load and unload functions in GTypeModuleClass.

Details

GTypeModule

typedef struct {
  gchar *name;
} GTypeModule;

The members of the GTypeModule structure should not be accessed directly, except for the name field.

gchar *name; the name of the module

GTypeModuleClass

typedef struct {
  GObjectClass parent_class;

  gboolean (* load)   (GTypeModule *module);
  void     (* unload) (GTypeModule *module);
} GTypeModuleClass;

In order to implement dynamic loading of types based on GTypeModule, the load and unload functions in GTypeModuleClass must be implemented.

GObjectClass parent_class; | the parent class
load () | loads the module and registers one or more types using g_type_module_register_type().
unload () | unloads the module

g_type_module_use ()

gboolean            g_type_module_use                   (GTypeModule *module);

Increases the use count of a GTypeModule by one. If the use count was zero before, the plugin will be loaded.

module : | a GTypeModule
Returns : | FALSE if the plugin needed to be loaded and loading the plugin failed.

g_type_module_unuse ()

void                g_type_module_unuse                 (GTypeModule *module);

Decreases the use count of a GTypeModule by one. If the result is zero, the module will be unloaded. (However, the GTypeModule will not be freed, and types associated with the GTypeModule are not unregistered. Once a GTypeModule is initialized, it must exist forever.)

module : a GTypeModule

g_type_module_set_name ()

void                g_type_module_set_name              (GTypeModule *module,
                                                         const gchar *name);

Sets the name for a GTypeModule

module : | a GTypeModule.
name : | a human-readable name to use in error messages.

g_type_module_register_type ()

GType               g_type_module_register_type         (GTypeModule *module,
                                                         GType parent_type,
                                                         const gchar *type_name,
                                                         const GTypeInfo *type_info,
                                                         GTypeFlags flags);

Looks up or registers a type that is implemented with a particular type plugin. If a type with name type_name was previously registered, the GType identifier for the type is returned, otherwise the type is newly registered, and the resulting GType identifier returned.

When reregistering a type (typically because a module is unloaded then reloaded, and reinitialized), module and parent_type must be the same as they were previously.

As long as any instances of the type exist, the type plugin will not be unloaded.

module : | a GTypeModule
parent_type : | the type for the parent class
type_name : | name for the type
type_info : | type information structure
flags : | flags field providing details about the type
Returns : | the new or existing type ID

g_type_module_add_interface ()

void                g_type_module_add_interface         (GTypeModule *module,
                                                         GType instance_type,
                                                         GType interface_type,
                                                         const GInterfaceInfo *interface_info);

Registers an additional interface for a type, whose interface lives in the given type plugin. If the interface was already registered for the type in this plugin, nothing will be done.

As long as any instances of the type exist, the type plugin will not be unloaded.

module : | a GTypeModule
instance_type : | type to which to add the interface.
interface_type : | interface type to add
interface_info : | type information structure

g_type_module_register_enum ()

GType               g_type_module_register_enum         (GTypeModule *module,
                                                         const gchar *name,
                                                         const GEnumValue *const _static_values);

Looks up or registers an enumeration that is implemented with a particular type plugin. If a type with name type_name was previously registered, the GType identifier for the type is returned, otherwise the type is newly registered, and the resulting GType identifier returned.

As long as any instances of the type exist, the type plugin will not be unloaded.

module : | a GTypeModule
name : | name for the type
_static_values : |
Returns : | the new or existing type ID

Since 2.6

g_type_module_register_flags ()

GType               g_type_module_register_flags        (GTypeModule *module,
                                                         const gchar *name,
                                                         const GFlagsValue *const _static_values);

Looks up or registers a flags type that is implemented with a particular type plugin. If a type with name type_name was previously registered, the GType identifier for the type is returned, otherwise the type is newly registered, and the resulting GType identifier returned.

As long as any instances of the type exist, the type plugin will not be unloaded.

module : | a GTypeModule
name : | name for the type
_static_values : |
Returns : | the new or existing type ID

Since 2.6

See Also

GTypePlugin | The abstract type loader interface.
GModule | Portable mechanism for dynamically loaded modules.


GTypePlugin

GTypePlugin — An interface for dynamically loadable types

Synopsis

#include <glib-object.h>

                    GTypePlugin;
                    GTypePluginClass;
void                (*GTypePluginUse)                   (GTypePlugin *plugin);
void                (*GTypePluginUnuse)                 (GTypePlugin *plugin);
void                (*GTypePluginCompleteTypeInfo)      (GTypePlugin *plugin,
                                                         GType g_type,
                                                         GTypeInfo *info,
                                                         GTypeValueTable *value_table);
void                (*GTypePluginCompleteInterfaceInfo) (GTypePlugin *plugin,
                                                         GType instance_type,
                                                         GType interface_type,
                                                         GInterfaceInfo *info);
void                g_type_plugin_use                   (GTypePlugin *plugin);
void                g_type_plugin_unuse                 (GTypePlugin *plugin);
void                g_type_plugin_complete_type_info    (GTypePlugin *plugin,
                                                         GType g_type,
                                                         GTypeInfo *info,
                                                         GTypeValueTable *value_table);
void                g_type_plugin_complete_interface_info
                                                        (GTypePlugin *plugin,
                                                         GType instance_type,
                                                         GType interface_type,
                                                         GInterfaceInfo *info);

Object Hierarchy

  GInterface
   +----GTypePlugin

Known Implementations

GTypePlugin is implemented by GTypeModule.

Description

The GObject type system supports dynamic loading of types. The GTypePlugin interface is used to handle the lifecycle of dynamically loaded types. It goes as follows:

  1. The type is initially introduced (usually upon loading the module the first time, or by your main application that knows what modules introduces what types), like this: new_type_id = g_type_register_dynamic (parent_type_id, "TypeName", new_type_plugin, type_flags); where new_type_plugin is an implementation of the GTypePlugin interface.

  2. The type's implementation is referenced, e.g. through g_type_class_ref() or through g_type_create_instance() (this is being called by g_object_new()) or through one of the above done on a type derived from new_type_id.

  3. This causes the type system to load the type's implementation by calling g_type_plugin_use() and g_type_plugin_complete_type_info() on new_type_plugin.

  4. At some point the type's implementation isn't required anymore, e.g. after g_type_class_unref() or g_type_free_instance() (called when the reference count of an instance drops to zero).

  5. This causes the type system to throw away the information retrieved from g_type_plugin_complete_type_info() and then it calls g_type_plugin_unuse() on new_type_plugin.

  6. Things may repeat from the second step.

So basically, you need to implement a GTypePlugin type that carries a use_count, once use_count goes from zero to one, you need to load the implementation to successfully handle the upcoming g_type_plugin_complete_type_info() call. Later, maybe after succeeding use/unuse calls, once use_count drops to zero, you can unload the implementation again. The type system makes sure to call g_type_plugin_use() and g_type_plugin_complete_type_info() again when the type is needed again.

GTypeModule is an implementation of GTypePlugin that already implements most of this except for the actual module loading and unloading. It even handles multiple registered types per module.

Details

GTypePlugin

typedef struct _GTypePlugin GTypePlugin;

The GTypePlugin typedef is used as a placeholder for objects that implement the GTypePlugin interface.

GTypePluginClass

typedef struct {
  GTypePluginUse		   use_plugin;
  GTypePluginUnuse		   unuse_plugin;
  GTypePluginCompleteTypeInfo	   complete_type_info;
  GTypePluginCompleteInterfaceInfo complete_interface_info;
} GTypePluginClass;

The GTypePlugin interface is used by the type system in order to handle the lifecycle of dynamically loaded types.

GTypePluginUse use_plugin; | Increases the use count of the plugin.
GTypePluginUnuse unuse_plugin; | Decreases the use count of the plugin.
GTypePluginCompleteTypeInfo complete_type_info; | Fills in the GTypeInfo and GTypeValueTable structs for the type. The structs are initialized with memset(s, 0, sizeof (s)) before calling this function.
GTypePluginCompleteInterfaceInfo complete_interface_info; | Fills in missing parts of the GInterfaceInfo for the interface. The structs is initialized with memset(s, 0, sizeof (s)) before calling this function.

GTypePluginUse ()

void                (*GTypePluginUse)                   (GTypePlugin *plugin);

The type of the use_plugin function of GTypePluginClass, which gets called to increase the use count of plugin.

plugin : the GTypePlugin whose use count should be increased

GTypePluginUnuse ()

void                (*GTypePluginUnuse)                 (GTypePlugin *plugin);

The type of the unuse_plugin function of GTypePluginClass.

plugin : the GTypePlugin whose use count should be decreased

GTypePluginCompleteTypeInfo ()

void                (*GTypePluginCompleteTypeInfo)      (GTypePlugin *plugin,
                                                         GType g_type,
                                                         GTypeInfo *info,
                                                         GTypeValueTable *value_table);

The type of the complete_type_info function of GTypePluginClass.

plugin : | the GTypePlugin
g_type : | the GType whose info is completed
info : | the GTypeInfo struct to fill in
value_table : | the GTypeValueTable to fill in

GTypePluginCompleteInterfaceInfo ()

void                (*GTypePluginCompleteInterfaceInfo) (GTypePlugin *plugin,
                                                         GType instance_type,
                                                         GType interface_type,
                                                         GInterfaceInfo *info);

The type of the complete_interface_info function of GTypePluginClass.

plugin : | the GTypePlugin
instance_type : | the GType of an instantiable type to which the interface is added
interface_type : | the GType of the interface whose info is completed
info : | the GInterfaceInfo to fill in

g_type_plugin_use ()

void                g_type_plugin_use                   (GTypePlugin *plugin);

Calls the use_plugin function from the GTypePluginClass of plugin. There should be no need to use this function outside of the GObject type system itself.

plugin : a GTypePlugin

g_type_plugin_unuse ()

void                g_type_plugin_unuse                 (GTypePlugin *plugin);

Calls the unuse_plugin function from the GTypePluginClass of plugin. There should be no need to use this function outside of the GObject type system itself.

plugin : a GTypePlugin

g_type_plugin_complete_type_info ()

void                g_type_plugin_complete_type_info    (GTypePlugin *plugin,
                                                         GType g_type,
                                                         GTypeInfo *info,
                                                         GTypeValueTable *value_table);

Calls the complete_type_info function from the GTypePluginClass of plugin. There should be no need to use this function outside of the GObject type system itself.

plugin : | a GTypePlugin
g_type : | the GType whose info is completed
info : | the GTypeInfo struct to fill in
value_table : | the GTypeValueTable to fill in

g_type_plugin_complete_interface_info ()

void                g_type_plugin_complete_interface_info
                                                        (GTypePlugin *plugin,
                                                         GType instance_type,
                                                         GType interface_type,
                                                         GInterfaceInfo *info);

Calls the complete_interface_info function from the GTypePluginClass of plugin. There should be no need to use this function outside of the GObject type system itself.

plugin : | the GTypePlugin
instance_type : | the GType of an instantiable type to which the interface is added
interface_type : | the GType of the interface whose info is completed
info : | the GInterfaceInfo to fill in

See Also

GTypeModule and g_type_register_dynamic().


How To define and implement a new GObject?

Boilerplate header code
Boilerplate code
Object Construction
Object Destruction
Object methods
Non-virtual public methods
Virtual public methods
Virtual private Methods
Chaining up

Clearly, this is one of the most common question people ask: they just want to crank code and implement a subclass of a GObject. Sometimes because they want to create their own class hierarchy, sometimes because they want to subclass one of GTK+'s widget. This chapter will focus on the implementation of a subtype of GObject. The sample source code associated to this section can be found in the documentation's source tarball, in the sample/gobject directory:

  • maman-bar.{h|c}: this is the source for a object which derives from GObject and which shows how to declare different types of methods on the object.

  • maman-subbar.{h|c}: this is the source for a object which derives from MamanBar and which shows how to override some of its parent's methods.

  • maman-foo.{h|c}: this is the source for an object which derives from GObject and which declares a signal.

  • test.c: this is the main source which instantiates an instance of type and exercises their API.

Boilerplate header code

The first step before writing the code for your GObject is to write the type's header which contains the needed type, function and macro definitions. Each of these elements is nothing but a convention which is followed not only by GTK+'s code but also by most users of GObject. If you feel the need not to obey the rules stated below, think about it twice:

  • If your users are a bit accustomed to GTK+ code or any Glib code, they will be a bit surprised and getting used to the conventions you decided upon will take time (money) and will make them grumpy (not a good thing)

  • You must assess the fact that these conventions might have been designed by both smart and experienced people: maybe they were at least partly right. Try to put your ego aside.

Pick a name convention for your headers and source code and stick to it:

  • use a dash to separate the prefix from the typename: maman-bar.h and maman-bar.c (this is the convention used by Nautilus and most Gnome libraries).

  • use an underscore to separate the prefix from the typename: maman_bar.h and maman_bar.c.

  • Do not separate the prefix from the typename: mamanbar.h and mamanbar.c. (this is the convention used by GTK+)

I personally like the first solution better: it makes reading file names easier for those with poor eyesight like me.

When you need some private (internal) declarations in several (sub)classes, you can define them in a private header file which is often named by appending the private keyword to the public header name. For example, one could use maman-bar-private.h, maman_bar_private.h or mamanbarprivate.h. Typically, such private header files are not installed.

The basic conventions for any header which exposes a GType are described in the section called “Conventions”. Most GObject-based code also obeys onf of the following conventions: pick one and stick to it.

  • If you want to declare a type named bar with prefix maman, name the type instance MamanBar and its class MamanBarClass (name is case-sensitive). It is customary to declare them with code similar to the following:

    /*
 * Copyright/Licensing information.
 */

#ifndef MAMAN_BAR_H
#define MAMAN_BAR_H

/*
 * Potentially, include other headers on which this header depends.
 */

/*
 * Type macros.
 */

typedef struct _MamanBar MamanBar;
typedef struct _MamanBarClass MamanBarClass;

struct _MamanBar {
  GObject parent;
  /* instance members */
};

struct _MamanBarClass {
  GObjectClass parent;
  /* class members */
};

/* used by MAMAN_BAR_TYPE */
GType maman_bar_get_type (void);

/*
 * Method definitions.
 */

#endif

  • Most GTK+ types declare their private fields in the public header with a /* private */ comment, relying on their user's intelligence not to try to play with these fields. Fields not marked private are considered public by default. The /* protected */ comment (same semantics as those of C++) is also used, mainly in the GType library, in code written by Tim Janik.

    struct _MamanBar {
  GObject parent;

  /* private */
  int hsize;
};

  • All of Nautilus code and a lot of Gnome libraries use private indirection members, as described by Herb Sutter in his Pimpl articles (see Compilation Firewalls and The Fast Pimpl Idiom : he summarizes the different issues better than I will).

    typedef struct _MamanBarPrivate MamanBarPrivate;
struct _MamanBar {
  GObject parent;

  /* private */
  MamanBarPrivate *priv;
};

    Note

    Do not call this private, as that is a registered c++ keyword.

    The private structure is then defined in the .c file, instantiated in the object's init function and destroyed in the object's finalize function.

    static void
maman_bar_finalize (GObject *object) {
  MamanBar *self = MAMAN_BAR (object);
  /* do stuff */
  g_free (self->priv);
}

static void
maman_bar_init (GTypeInstance *instance, gpointer g_class) {
  MamanBar *self = MAMAN_BAR (instance);
  self->priv = g_new0 (MamanBarPrivate,1);
  /* do stuff */
}

  • A similar alternative, available since Glib version 2.4, is to define a private structure in the .c file, declare it as a private structure in maman_bar_class_init using g_type_class_add_private. Instead of allocating memory in maman_bar_init a pointer to the private memory area is stored in the instance to allow convenient access to this structure. A private structure will then be attached to each newly created object by the GObject system. You dont need to free or allocate the private structure, only the objects or pointers that it may contain. Another advantage of this to the previous version is that is lessens memory fragmentation, as the public and private parts of the instance memory are allocated at once.

    typedef struct _MamanBarPrivate MamanBarPrivate;

struct _MamanBarPrivate {
  int private_field;
};

static void
maman_bar_class_init (MamanBarClass *klass)
{
  ...
  g_type_class_add_private (klass, sizeof (MamanBarPrivate));
  ...
}

static void
maman_bar_init (GTypeInstance *instance, gpointer g_class) {
  MamanBar *self = MAMAN_BAR (instance);
  self->priv = G_TYPE_INSTANCE_GET_PRIVATE (self, MAMAN_BAR_TYPE, MamanBarPrivate);
  /* do stuff */
}

Finally, there are different header include conventions. Again, pick one and stick to it. I personally use indifferently any of the two, depending on the codebase I work on: the rule is consistency.

  • Some people add at the top of their headers a number of #include directives to pull in all the headers needed to compile client code. This allows client code to simply #include "maman-bar.h".

  • Other do not #include anything and expect the client to #include themselves the headers they need before including your header. This speeds up compilation because it minimizes the amount of pre-processor work. This can be used in conjunction with the re-declaration of certain unused types in the client code to minimize compile-time dependencies and thus speed up compilation.


Chaining up

Chaining up is often loosely defined by the following set of conditions:

  • Parent class A defines a public virtual method named foo and provides a default implementation.

  • Child class B re-implements method foo.

  • In the method B::foo, the child class B calls its parent class method A::foo.

There are many uses to this idiom:

  • You need to change the behaviour of a class without modifying its code. You create a subclass to inherit its implementation, re-implement a public virtual method to modify the behaviour slightly and chain up to ensure that the previous behaviour is not really modifed, just extended.

  • You are lazy, you have access to the source code of the parent class but you don't want to modify it to add method calls to new specialized method calls: it is faster to hack the child class to chain up than to modify the parent to call down.

  • You need to implement the Chain Of Responsability pattern: each object of the inheritance tree chains up to its parent (typically, at the begining or the end of the method) to ensure that they each handler is run in turn.

I am personally not really convinced any of the last two uses are really a good idea but since this programming idiom is often used, this section attemps to explain how to implement it.

To explicitely chain up to the implementation of the virtual method in the parent class, you first need a handle to the original parent class structure. This pointer can then be used to access the original class function pointer and invoke it directly. [12]

The function g_type_class_peek_parent is used to access the original parent class structure. Its input is a pointer to the class of the derived object and it returns a pointer to the original parent class structure. The code below shows how you could use it:

static void
b_method_to_call (B *obj, int a)
{
  BClass *klass;
  AClass *parent_class;
  klass = B_GET_CLASS (obj);
  parent_class = g_type_class_peek_parent (klass);

  /* do stuff before chain up */
  parent_class->method_to_call (obj, a);
  /* do stuff after chain up */
}

A lot of people who use this idiom in GTK+ store the parent class structure pointer in a global static variable to avoid the costly call to g_type_class_peek_parent for each function call. Typically, the class_init callback initializes the global static variable. gtk/gtkhscale.c does this.

[12] The original adjective used in this sentence is not innocuous. To fully understand its meaning, you need to recall how class structures are initialized: for each object type, the class structure associated to this object is created by first copying the class structure of its parent type (a simple memcpy) and then by invoking the class_init callback on the resulting class structure. Since the class_init callback is responsible for overwriting the class structure with the user re-implementations of the class methods, we cannot merely use the modified copy of the parent class structure stored in our derived instance. We want to get a copy of the class structure of an instance of the parent class.


Boilerplate code

In your code, the first step is to #include the needed headers: depending on your header include strategy, this can be as simple as #include "maman-bar.h" or as complicated as tens of #include lines ending with #include "maman-bar.h":

/*
 * Copyright information
 */

#include "maman-bar.h"

/* If you use Pimpls, include the private structure
 * definition here. Some people create a maman-bar-private.h header
 * which is included by the maman-bar.c file and which contains the
 * definition for this private structure.
 */
struct _MamanBarPrivate {
  int member_1;
  /* stuff */
};

/*
 * forward definitions
 */

Implement maman_bar_get_type and make sure the code compiles:

GType
maman_bar_get_type (void)
{
  static GType type = 0;
  if (type == 0) {
    static const GTypeInfo info = {
      sizeof (MamanBarClass),
      NULL,   /* base_init */
      NULL,   /* base_finalize */
      NULL,   /* class_init */
      NULL,   /* class_finalize */
      NULL,   /* class_data */
      sizeof (MamanBar),
      0,      /* n_preallocs */
      NULL    /* instance_init */
      };
      type = g_type_register_static (G_TYPE_OBJECT,
                                     "MamanBarType",
                                     &info, 0);
    }
    return type;
}


Object Construction

People often get confused when trying to construct their GObjects because of the sheer number of different ways to hook into the objects's construction process: it is difficult to figure which is the correct, recommended way.

Table 4, “g_object_new” shows what user-provided functions are invoked during object instanciation and in which order they are invoked. A user looking for the equivalent of the simple C++ constructor function should use the instance_init method. It will be invoked after all the parent's instance_init functions have been invoked. It cannot take arbitrary construction parameters (as in C++) but if your object needs arbitrary parameters to complete initialization, you can use construction properties.

Construction properties will be set only after all instance_init functions have run. No object reference will be returned to the client of g_object_new> until all the construction properties have been set.

As such, I would recommend writing the following code first:

static void
maman_bar_init (GTypeInstance   *instance,
                gpointer         g_class)
{
  MamanBar *self = (MamanBar *)instance;
  self->private = g_new0 (MamanBarPrivate, 1);

  /* initialize all public and private members to reasonable default values. */
  /* If you need specific consruction properties to complete initialization,
   * delay initialization completion until the property is set.
   */
}

And make sure that you set maman_bar_init as the type's instance_init function in maman_bar_get_type. Make sure the code builds and runs: create an instance of the object and make sure maman_bar_init is called (add a g_print call in it).

Now, if you need special construction properties, install the properties in the class_init function, override the set and get methods and implement the get and set methods as described in the section called “Object properties”. Make sure that these properties use a construct only GParamSpec by setting the param spec's flag field to G_PARAM_CONSTRUCT_ONLY: this helps GType ensure that these properties are not set again later by malicious user code.

static void
bar_class_init (MamanBarClass *klass)
{
  GObjectClass *gobject_class = G_OBJECT_CLASS (klass);
  GParamSpec *maman_param_spec;

  gobject_class->set_property = bar_set_property;
  gobject_class->get_property = bar_get_property;

  maman_param_spec = g_param_spec_string ("maman",
                                          "Maman construct prop",
                                          "Set maman's name",
                                          "no-name-set" /* default value */,
                                          G_PARAM_CONSTRUCT_ONLY |G_PARAM_READWRITE);

  g_object_class_install_property (gobject_class,
                                   PROP_MAMAN,
                                   maman_param_spec);
}

If you need this, make sure you can build and run code similar to the code shown above. Make sure your construct properties can set correctly during construction, make sure you cannot set them afterwards and make sure that if your users do not call g_object_new with the required construction properties, these will be initialized with the default values.

I consider good taste to halt program execution if a construction property is set its default value. This allows you to catch client code which does not give a reasonable value to the construction properties. Of course, you are free to disagree but you should have a good reason to do so.

Some people sometimes need to construct their object but only after the construction properties have been set. This is possible through the use of the constructor class method as described in the section called “Object instanciation”. However, I have yet to see any reasonable use of this feature. As such, to initialize your object instances, use by default the base_init function and construction properties.


Object Destruction

Again, it is often difficult to figure out which mechanism to use to hook into the object's destruction process: when the last g_object_unref function call is made, a lot of things happen as described in Table 5, “g_object_unref”.

The destruction process of your object must be split is two different phases: you must override both the dispose and the finalize class methods.

struct _MamanBarPrivate {
  gboolean dispose_has_run;
};

static GObjectClass parent_class = NULL;

static void
bar_dispose (GObject *obj)
{
  MamanBar *self = (MamanBar *)obj;

  if (self->private->dispose_has_run) {
   /* If dispose did already run, return. */
    return;
  }
  /* Make sure dispose does not run twice. */
  object->private->dispose_has_run = TRUE;

  /*
   * In dispose, you are supposed to free all types referenced from this
   * object which might themselves hold a reference to self. Generally,
   * the most simple solution is to unref all members on which you own a
   * reference.
   */

   /* Chain up to the parent class */
   G_OBJECT_CLASS (parent_class)->dispose (obj);
}

static void
bar_finalize (GObject *obj)
{
  MamanBar *self = (MamanBar *)obj;

  /*
   * Here, complete object destruction.
   * You might not need to do much...
   */
  g_free (self->private);

   /* Chain up to the parent class */
   G_OBJECT_CLASS (parent_class)->finalize (obj);
}

static void
bar_class_init (BarClass *klass)
{
  GObjectClass *gobject_class = G_OBJECT_CLASS (klass);

  gobject_class->dispose = bar_dispose;
  gobject_class->finalize = bar_finalize;
}

static void
maman_bar_init (GTypeInstance   *instance,
                gpointer         g_class)
{
  MamanBar *self = (MamanBar *)instance;
  self->private = g_new0 (MamanBarPrivate, 1);
  self->private->dispose_has_run = FALSE;

  parent_class = g_type_class_peek_parent (klass);
}

Add similar code to your GObject, make sure the code still builds and runs: dispose and finalize must be called during the last unref. It is possible that object methods might be invoked after dispose is run and before finalize runs. GObject does not consider this to be a program error: you must gracefully detect this and neither crash nor warn the user. To do this, you need something like the following code at the start of each object method, to make sure the object's data is still valid before manipulating it:

if (self->private->dispose_has_run) {
  /* Dispose has run. Data is not valid anymore. */
  return;
}


Object methods

Just as with C++, there are many different ways to define object methods and extend them: the following list and sections draw on C++ vocabulary. (Readers are expected to know basic C++ buzzwords. Those who have not had to write C++ code recently can refer to e.g. http://www.cplusplus.com/doc/tutorial/ to refresh their memories.)

  • non-virtual public methods,

  • virtual public methods and

  • virtual private methods

Non-virtual public methods

These are the simplest: you want to provide a simple method which can act on your object. All you need to do is to provide a function prototype in the header and an implementation of that prototype in the source file.

/* declaration in the header. */
void maman_bar_do_action (MamanBar *self, /* parameters */);
/* implementation in the source file */
void maman_bar_do_action (MamanBar *self, /* parameters */)
{
  /* do stuff here. */
}

There is really nothing scary about this.

Virtual public methods

This is the preferred way to create polymorphic GObjects. All you need to do is to define the common method and its class function in the public header, implement the common method in the source file and re-implement the class function in each object which inherits from you.

/* declaration in maman-bar.h. */
struct _MamanBarClass {
  GObjectClass parent;

  /* stuff */
  void (*do_action) (MamanBar *self, /* parameters */);
};
void maman_bar_do_action (MamanBar *self, /* parameters */);
/* implementation in maman-bar.c */
void maman_bar_do_action (MamanBar *self, /* parameters */)
{
  MAMAN_BAR_GET_CLASS (self)->do_action (self, /* parameters */);
}

The code above simply redirects the do_action call to the relevant class function. Some users, concerned about performance, do not provide the maman_bar_do_action wrapper function and require users to dereference the class pointer themselves. This is not such a great idea in terms of encapsulation and makes it difficult to change the object's implementation afterwards, should this be needed.

Other users, also concerned by performance issues, declare the maman_bar_do_action function inline in the header file. This, however, makes it difficult to change the object's implementation later (although easier than requiring users to directly dereference the class function) and is often difficult to write in a portable way (the inline keyword is not part of the C standard).

In doubt, unless a user shows you hard numbers about the performance cost of the function call, just maman_bar_do_action in the source file.

Please, note that it is possible for you to provide a default implementation for this class method in the object's class_init function: initialize the klass->do_action field to a pointer to the actual implementation. You can also make this class method pure virtual by initializing the klass->do_action field to NULL:

static void
maman_bar_real_do_action_two (MamanBar *self, /* parameters */)
{
  /* Default implementation for the virtual method. */
}

static void
maman_bar_class_init (BarClass *klass)
{
  /* pure virtual method: mandates implementation in children. */
  klass->do_action_one = NULL;
  /* merely virtual method. */
  klass->do_action_two = maman_bar_real_do_action_two;
}

void maman_bar_do_action_one (MamanBar *self, /* parameters */)
{
  MAMAN_BAR_GET_CLASS (self)->do_action_one (self, /* parameters */);
}
void maman_bar_do_action_two (MamanBar *self, /* parameters */)
{
  MAMAN_BAR_GET_CLASS (self)->do_action_two (self, /* parameters */);
}

Virtual private Methods

These are very similar to Virtual Public methods. They just don't have a public function to call the function directly. The header file contains only a declaration of the class function:

/* declaration in maman-bar.h. */
struct _MamanBarClass {
  GObjectClass parent;

  /* stuff */
  void (*helper_do_specific_action) (MamanBar *self, /* parameters */);
};
void maman_bar_do_any_action (MamanBar *self, /* parameters */);

These class functions are often used to delegate part of the job to child classes:

/* this accessor function is static: it is not exported outside of this file. */
static void
maman_bar_do_specific_action (MamanBar *self, /* parameters */)
{
  MAMAN_BAR_GET_CLASS (self)->do_specific_action (self, /* parameters */);
}

void maman_bar_do_any_action (MamanBar *self, /* parameters */)
{
  /* random code here */

  /*
   * Try to execute the requested action. Maybe the requested action cannot be implemented
   * here. So, we delegate its implementation to the child class:
   */
  maman_bar_do_specific_action (self, /* parameters */);

  /* other random code here */
}

Again, it is possible to provide a default implementation for this private virtual class function:

static void
maman_bar_class_init (MamanBarClass *klass)
{
  /* pure virtual method: mandates implementation in children. */
  klass->do_specific_action_one = NULL;
  /* merely virtual method. */
  klass->do_specific_action_two = maman_bar_real_do_specific_action_two;
}

Children can then implement the subclass with code such as:

static void
maman_bar_subtype_class_init (MamanBarSubTypeClass *klass)
{
  MamanBarClass *bar_class = MAMAN_BAR_CLASS (klass);
  /* implement pure virtual class function. */
  bar_class->do_specific_action_one = maman_bar_subtype_do_specific_action_one;
}


How To define and implement Interfaces?

How To define Interfaces?
How To define implement an Interface?
Interface definition prerequisites
Interface Properties

How To define Interfaces?

The bulk of interface definition has already been shown in the section called “Non-instantiable classed types: Interfaces.” but I feel it is needed to show exactly how to create an interface. The sample source code associated to this section can be found in the documentation's source tarball, in the sample/interface/maman-ibaz.{h|c} file.

As above, the first step is to get the header right:

#ifndef MAMAN_IBAZ_H
#define MAMAN_IBAZ_H

#include <glib-object.h>

#define MAMAN_TYPE_IBAZ                (maman_ibaz_get_type ())
#define MAMAN_IBAZ(obj)                (G_TYPE_CHECK_INSTANCE_CAST ((obj), MAMAN_TYPE_IBAZ, MamanIbaz))
#define MAMAN_IS_IBAZ(obj)             (G_TYPE_CHECK_INSTANCE_TYPE ((obj), MAMAN_TYPE_IBAZ))
#define MAMAN_IBAZ_GET_INTERFACE(inst) (G_TYPE_INSTANCE_GET_INTERFACE ((inst), MAMAN_TYPE_IBAZ, MamanIbazInterface))

typedef struct _MamanIbaz MamanIbaz; /* dummy object */
typedef struct _MamanIbazInterface MamanIbazInterface;

struct _MamanIbazInterface {
  GTypeInterface parent;

  void (*do_action) (MamanIbaz *self);
};

GType maman_ibaz_get_type (void);

void maman_ibaz_do_action (MamanIbaz *self);

#endif /*MAMAN_IBAZ_H*/

This code is the same as the code for a normal GType which derives from a GObject except for a few details:

  • The _GET_CLASS macro is called _GET_INTERFACE and not implemented with G_TYPE_INSTANCE_GET_CLASS but with G_TYPE_INSTANCE_GET_INTERFACE.

  • The instance type, MamanIbaz is not fully defined: it is used merely as an abstract type which represents an instance of whatever object which implements the interface.

The implementation of the MamanIbaz type itself is trivial:

  • maman_ibaz_get_type registers the type in the type system.

  • maman_ibaz_base_init is expected to register the interface's signals if there are any (we will see a bit (later how to use them). Make sure to use a static local boolean variable to make sure not to run the initialization code twice (as described in the section called “Interface Initialization”, base_init is run once for each interface implementation instanciation)

  • maman_ibaz_do_action dereferences the class structure to access its associated class function and calls it.

static void
maman_ibaz_base_init (gpointer g_class)
{
  static gboolean initialized = FALSE;

  if (!initialized) {
    /* create interface signals here. */
    initialized = TRUE;
  }
}

GType
maman_ibaz_get_type (void)
{
  static GType type = 0;
  if (type == 0) {
    static const GTypeInfo info = {
      sizeof (MamanIbazInterface),
      maman_ibaz_base_init,   /* base_init */
      NULL,   /* base_finalize */
      NULL,   /* class_init */
      NULL,   /* class_finalize */
      NULL,   /* class_data */
      0,
      0,      /* n_preallocs */
      NULL    /* instance_init */
    };
    type = g_type_register_static (G_TYPE_INTERFACE, "MamanIbaz", &info, 0);
  }
  return type;
}

void maman_ibaz_do_action (MamanIbaz *self)
{
  MAMAN_IBAZ_GET_INTERFACE (self)->do_action (self);
}


How To define implement an Interface?

Once the interface is defined, implementing it is rather trivial. Source code showing how to do this for the IBaz interface defined in the previous section is located in sample/interface/maman-baz.{h|c}.

The first step is to define a normal GType. Here, we have decided to use a GType which derives from GObject. Its name is MamanBaz:

#ifndef MAMAN_BAZ_H
#define MAMAN_BAZ_H

#include <glib-object.h>

#define MAMAN_TYPE_BAZ             (maman_baz_get_type ())
#define MAMAN_BAZ(obj)             (G_TYPE_CHECK_INSTANCE_CAST ((obj), MAMAN_TYPE_BAZ, Mamanbaz))
#define MAMAN_BAZ_CLASS(vtable)    (G_TYPE_CHECK_CLASS_CAST ((vtable), MAMAN_TYPE_BAZ, MamanbazClass))
#define MAMAN_IS_BAZ(obj)          (G_TYPE_CHECK_INSTANCE_TYPE ((obj), MAMAN_TYPE_BAZ))
#define MAMAN_IS_BAZ_CLASS(vtable) (G_TYPE_CHECK_CLASS_TYPE ((vtable), MAMAN_TYPE_BAZ))
#define MAMAN_BAZ_GET_CLASS(inst)  (G_TYPE_INSTANCE_GET_CLASS ((inst), MAMAN_TYPE_BAZ, MamanbazClass))

typedef struct _MamanBaz MamanBaz;
typedef struct _MamanBazClass MamanBazClass;

struct _MamanBaz {
  GObject parent;
  int instance_member;
};

struct _MamanBazClass {
  GObjectClass parent;
};

GType maman_baz_get_type (void);

#endif //MAMAN_BAZ_H

There is clearly nothing specifically weird or scary about this header: it does not define any weird API or derives from a weird type.

The second step is to implement maman_baz_get_type:

GType
maman_baz_get_type (void)
{
  static GType type = 0;
  if (type == 0) {
    static const GTypeInfo info = {
      sizeof (MamanBazClass),
      NULL,   /* base_init */
      NULL,   /* base_finalize */
      NULL,   /* class_init */
      NULL,   /* class_finalize */
      NULL,   /* class_data */
      sizeof (MamanBaz),
      0,      /* n_preallocs */
      baz_instance_init    /* instance_init */
    };
    static const GInterfaceInfo ibaz_info = {
      (GInterfaceInitFunc) baz_interface_init,    /* interface_init */
      NULL,               /* interface_finalize */
      NULL                /* interface_data */
    };
    type = g_type_register_static (G_TYPE_OBJECT,
                                   "MamanBazType",
                                   &info, 0);
    g_type_add_interface_static (type,
                                 MAMAN_TYPE_IBAZ,
                                 &ibaz_info);
  }
  return type;
}

This function is very much like all the similar functions we looked at previously. The only interface-specific code present here is the call to g_type_add_interface_static which is used to inform the type system that this just-registered GType also implements the interface MAMAN_TYPE_IBAZ.

baz_interface_init, the interface initialization function, is also pretty simple:

static void baz_do_action (MamanBaz *self)
{
  g_print ("Baz implementation of IBaz interface Action: 0x%x.\n", self->instance_member);
}
static void
baz_interface_init (gpointer   g_iface,
                    gpointer   iface_data)
{
  MamanIbazInteface *iface = (MamanIbazInteface *)g_iface;
  iface->do_action = (void (*) (MamanIbaz *self))baz_do_action;
}
static void
baz_instance_init (GTypeInstance   *instance,
                   gpointer         g_class)
{
  MamanBaz *self = MAMAN_BAZ(instance);
  self->instance_member = 0xdeadbeaf;
}

baz_interface_init merely initializes the interface methods to the implementations defined by MamanBaz: maman_baz_do_action does nothing very useful but it could :)


Interface Properties

Starting from version 2.4 of glib, gobject interfaces can also have properties. Declaration of the interface properties is similar to declaring the properties of ordinary gobject types as explained in the section called “Object properties”, except that g_object_interface_install_property is used to declare the properties instead of g_object_class_install_property.

To include a property named 'name' of type string in the maman_ibaz interface example code above, we only need to add one [13] line in the maman_ibaz_base_init [14] as shown below:

static void
maman_ibaz_base_init (gpointer g_iface)
{
  static gboolean initialized = FALSE;

  if (!initialized) {
    /* create interface signals here. */

    g_object_interface_install_property (g_iface,
                g_param_spec_string ("name",
                    "maman_ibaz_name",
                    "Name of the MamanIbaz",
                    "maman",
                    G_PARAM_READWRITE));
    initialized = TRUE;
  }
}

One point worth noting is that the declared property wasn't assigned an integer ID. The reason being that integer IDs of properities are utilized only inside the get and set methods and since interfaces do not implement properties, there is no need to assign integer IDs to interface properties.

The story for the implementers of the interface is also quite trivial. An implementer shall declare and define it's properties in the usual way as explained in the section called “Object properties”, except for one small change: it shall declare the properties of the interface it implements using g_object_class_override_property instead of g_object_class_install_property. The following code snipet shows the modifications needed in the MamanBaz declaration and implementation above:

struct _MamanBaz {
  GObject parent;
  gint instance_member;
  gchar *name;		/* placeholder for property */
};

enum
{
  ARG_0,
  ARG_NAME
};

GType
maman_baz_get_type (void)
{
  static GType type = 0;
  if (type == 0) {
    static const GTypeInfo info = {
      sizeof (MamanBazClass),
      NULL,   /* base_init */
      NULL,   /* base_finalize */
      baz_class_init, /* class_init */
      NULL,   /* class_finalize */
      NULL,   /* class_data */
      sizeof (MamanBaz),
      0,      /* n_preallocs */
      baz_instance_init    /* instance_init */
    };
    static const GInterfaceInfo ibaz_info = {
      (GInterfaceInitFunc) baz_interface_init,    /* interface_init */
      NULL,               /* interface_finalize */
      NULL                /* interface_data */
    };
    type = g_type_register_static (G_TYPE_OBJECT,
                                   "MamanBazType",
                                   &info, 0);
    g_type_add_interface_static (type,
                                 MAMAN_TYPE_IBAZ,
                                 &ibaz_info);
  }
  return type;
}

static void
maman_baz_class_init (MamanBazClass * klass)
{
  GObjectClass *gobject_class;

  gobject_class = (GObjectClass *) klass;

  parent_class = g_type_class_ref (G_TYPE_OBJECT);

  gobject_class->set_property = maman_baz_set_property;
  gobject_class->get_property = maman_baz_get_property;

  g_object_class_override_property (gobject_class, ARG_NAME, "name");
}

static void
maman_baz_set_property (GObject * object, guint prop_id,
                        const GValue * value, GParamSpec * pspec)
{
  MamanBaz *baz;
  GObject *obj;

  /* it's not null if we got it, but it might not be ours */
  g_return_if_fail (G_IS_MAMAN_BAZ (object));

  baz = MAMAN_BAZ (object);

  switch (prop_id) {
    case ARG_NAME:
      baz->name = g_value_get_string (value);
      break;
    default:
      G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
      break;
  }
}

static void
maman_baz_get_property (GObject * object, guint prop_id,
                        GValue * value, GParamSpec * pspec)
{
  MamanBaz *baz;

  /* it's not null if we got it, but it might not be ours */
  g_return_if_fail (G_IS_TEXT_PLUGIN (object));

  baz = MAMAN_BAZ (object);

  switch (prop_id) {
    case ARG_NAME:
      g_value_set_string (value, baz->name);
      break;
    default:
      G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
      break;
  }
}

[13] That really is one line extended to six for the sake of clarity

[14] The g_object_interface_install_property can also be called from class_init but it must not be called after that point.


Howto create and use signals

Simple use of signals
How to provide more flexibility to users?
How most people do the same thing with less code
How users can abuse signals (and why some think it is good)

The signal system which was built in GType is pretty complex and flexible: it is possible for its users to connect at runtime any number of callbacks (implemented in any language for which a binding exists) [15] to any signal and to stop the emission of any signal at any state of the signal emission process. This flexibility makes it possible to use GSignal for much more than just emit events which can be received by numerous clients.

Simple use of signals

The most basic use of signals is to implement simple event notification: for example, if we have a MamanFile object, and if this object has a write method, we might wish to be notified whenever someone uses this method. The code below shows how the user can connect a callback to the write signal. Full code for this simple example is located in sample/signal/maman-file.{h|c} and in sample/signal/test.c

file = g_object_new (MAMAN_FILE_TYPE, NULL);

g_signal_connect (G_OBJECT (file), "write",
                  (GCallback)write_event,
                  NULL);

maman_file_write (file, buffer, 50);

The MamanFile signal is registered in the class_init function:

klass->write_signal_id =
  g_signal_newv ("write",
                 G_TYPE_FROM_CLASS (g_class),
                 G_SIGNAL_RUN_LAST | G_SIGNAL_NO_RECURSE | G_SIGNAL_NO_HOOKS,
                 NULL /* class closure */,
                 NULL /* accumulator */,
                 NULL /* accu_data */,
                 g_cclosure_marshal_VOID__VOID,
                 G_TYPE_NONE /* return_type */,
                 0     /* n_params */,
                 NULL  /* param_types */);

and the signal is emited in maman_file_write:

void maman_file_write (MamanFile *self, guint8 *buffer, guint32 size)
{
  /* First write data. */
  /* Then, notify user of data written. */
  g_signal_emit (self, MAMAN_FILE_GET_CLASS (self)->write_signal_id,
                 0 /* details */,
                 NULL);
}

As shown above, you can safely set the details parameter to zero if you do not know what it can be used for. For a discussion of what you could used it for, see the section called “The detail argument”

The signature of the signal handler in the above example is defined as g_cclosure_marshal_VOID__VOID. Its name follows a simple convention which encodes the function parameter and return value types in the function name. Specifically, the value infront of the double underscore is the type of the return value, while the value(s) after the double underscore denote the parameter types. The header gobject/gmarshal.h defines a set of commonly needed closures that one can use.

[15] A python callback can be connected to any signal on any C-based GObject.


Index

G

GBaseFinalizeFunc, GBaseFinalizeFunc ()
GBaseInitFunc, GBaseInitFunc ()
GBoxedCopyFunc, GBoxedCopyFunc ()
GBoxedFreeFunc, GBoxedFreeFunc ()
GCallback, GCallback ()
GCClosure, GCClosure
gchararray, gchararray
GClassFinalizeFunc, GClassFinalizeFunc ()
GClassInitFunc, GClassInitFunc ()
GClosure, GClosure
GClosureMarshal, GClosureMarshal ()
GClosureNotify, GClosureNotify ()
GConnectFlags, enum GConnectFlags
GEnumClass, GEnumClass
GEnumValue, GEnumValue
GFlagsClass, GFlagsClass
GFlagsValue, GFlagsValue
GInitiallyUnowned, GInitiallyUnowned
GInitiallyUnownedClass, GInitiallyUnownedClass
GInstanceInitFunc, GInstanceInitFunc ()
GInterfaceFinalizeFunc, GInterfaceFinalizeFunc ()
GInterfaceInfo, GInterfaceInfo
GInterfaceInitFunc, GInterfaceInitFunc ()
GObject, GObject
GObject::notify, The "notify" signal
GObjectClass, GObjectClass
GObjectConstructParam, GObjectConstructParam
GObjectFinalizeFunc, GObjectFinalizeFunc ()
GObjectGetPropertyFunc, GObjectGetPropertyFunc ()
GObjectSetPropertyFunc, GObjectSetPropertyFunc ()
GParameter, GParameter
GParamFlags, enum GParamFlags
GParamSpec, GParamSpec
GParamSpecBoolean, GParamSpecBoolean
GParamSpecBoxed, GParamSpecBoxed
GParamSpecChar, GParamSpecChar
GParamSpecClass, GParamSpecClass
GParamSpecDouble, GParamSpecDouble
GParamSpecEnum, GParamSpecEnum
GParamSpecFlags, GParamSpecFlags
GParamSpecFloat, GParamSpecFloat
GParamSpecGType, GParamSpecGType
GParamSpecInt, GParamSpecInt
GParamSpecInt64, GParamSpecInt64
GParamSpecLong, GParamSpecLong
GParamSpecObject, GParamSpecObject
GParamSpecOverride, GParamSpecOverride
GParamSpecParam, GParamSpecParam
GParamSpecPointer, GParamSpecPointer
GParamSpecPool, GParamSpecPool
GParamSpecString, GParamSpecString
GParamSpecTypeInfo, GParamSpecTypeInfo
GParamSpecUChar, GParamSpecUChar
GParamSpecUInt, GParamSpecUInt
GParamSpecUInt64, GParamSpecUInt64
GParamSpecULong, GParamSpecULong
GParamSpecUnichar, GParamSpecUnichar
GParamSpecValueArray, GParamSpecValueArray
GSignalAccumulator, GSignalAccumulator ()
GSignalCMarshaller, GSignalCMarshaller
GSignalEmissionHook, GSignalEmissionHook ()
GSignalFlags, enum GSignalFlags
GSignalInvocationHint, GSignalInvocationHint
GSignalMatchType, enum GSignalMatchType
GSignalQuery, GSignalQuery
GStrv, GStrv
GToggleNotify, GToggleNotify ()
GType, GType
GTypeClass, GTypeClass
GTypeClassCacheFunc, GTypeClassCacheFunc ()
GTypeCValue, union GTypeCValue
GTypeDebugFlags, enum GTypeDebugFlags
GTypeFlags, enum GTypeFlags
GTypeFundamentalFlags, enum GTypeFundamentalFlags
GTypeFundamentalInfo, GTypeFundamentalInfo
GTypeInfo, GTypeInfo
GTypeInstance, GTypeInstance
GTypeInterface, GTypeInterface
GTypeInterfaceCheckFunc, GTypeInterfaceCheckFunc ()
GTypeModule, GTypeModule
GTypeModuleClass, GTypeModuleClass
GTypePlugin, GTypePlugin
GTypePluginClass, GTypePluginClass
GTypePluginCompleteInterfaceInfo, GTypePluginCompleteInterfaceInfo ()
GTypePluginCompleteTypeInfo, GTypePluginCompleteTypeInfo ()
GTypePluginUnuse, GTypePluginUnuse ()
GTypePluginUse, GTypePluginUse ()
GTypeQuery, GTypeQuery
GTypeValueTable, GTypeValueTable
GValue, GValue
GValueArray, GValueArray
GValueTransform, GValueTransform ()
GWeakNotify, GWeakNotify ()
g_boxed_copy, g_boxed_copy ()
g_boxed_free, g_boxed_free ()
g_boxed_type_register_static, g_boxed_type_register_static ()
G_CALLBACK, G_CALLBACK()
g_cclosure_marshal_BOOLEAN__FLAGS, g_cclosure_marshal_BOOLEAN__FLAGS ()
g_cclosure_marshal_BOOL__FLAGS, g_cclosure_marshal_BOOL__FLAGS
g_cclosure_marshal_STRING__OBJECT_POINTER, g_cclosure_marshal_STRING__OBJECT_POINTER ()
g_cclosure_marshal_VOID__BOOLEAN, g_cclosure_marshal_VOID__BOOLEAN ()
g_cclosure_marshal_VOID__BOXED, g_cclosure_marshal_VOID__BOXED ()
g_cclosure_marshal_VOID__CHAR, g_cclosure_marshal_VOID__CHAR ()
g_cclosure_marshal_VOID__DOUBLE, g_cclosure_marshal_VOID__DOUBLE ()
g_cclosure_marshal_VOID__ENUM, g_cclosure_marshal_VOID__ENUM ()
g_cclosure_marshal_VOID__FLAGS, g_cclosure_marshal_VOID__FLAGS ()
g_cclosure_marshal_VOID__FLOAT, g_cclosure_marshal_VOID__FLOAT ()
g_cclosure_marshal_VOID__INT, g_cclosure_marshal_VOID__INT ()
g_cclosure_marshal_VOID__LONG, g_cclosure_marshal_VOID__LONG ()
g_cclosure_marshal_VOID__OBJECT, g_cclosure_marshal_VOID__OBJECT ()
g_cclosure_marshal_VOID__PARAM, g_cclosure_marshal_VOID__PARAM ()
g_cclosure_marshal_VOID__POINTER, g_cclosure_marshal_VOID__POINTER ()
g_cclosure_marshal_VOID__STRING, g_cclosure_marshal_VOID__STRING ()
g_cclosure_marshal_VOID__UCHAR, g_cclosure_marshal_VOID__UCHAR ()
g_cclosure_marshal_VOID__UINT, g_cclosure_marshal_VOID__UINT ()
g_cclosure_marshal_VOID__UINT_POINTER, g_cclosure_marshal_VOID__UINT_POINTER ()
g_cclosure_marshal_VOID__ULONG, g_cclosure_marshal_VOID__ULONG ()
g_cclosure_marshal_VOID__VOID, g_cclosure_marshal_VOID__VOID ()
g_cclosure_new, g_cclosure_new ()
g_cclosure_new_object, g_cclosure_new_object ()
g_cclosure_new_object_swap, g_cclosure_new_object_swap ()
g_cclosure_new_swap, g_cclosure_new_swap ()
G_CCLOSURE_SWAP_DATA, G_CCLOSURE_SWAP_DATA()
g_closure_add_finalize_notifier, g_closure_add_finalize_notifier ()
g_closure_add_invalidate_notifier, g_closure_add_invalidate_notifier ()
g_closure_add_marshal_guards, g_closure_add_marshal_guards ()
g_closure_invalidate, g_closure_invalidate ()
g_closure_invoke, g_closure_invoke ()
G_CLOSURE_NEEDS_MARSHAL, G_CLOSURE_NEEDS_MARSHAL()
g_closure_new_object, g_closure_new_object ()
g_closure_new_simple, g_closure_new_simple ()
G_CLOSURE_N_NOTIFIERS, G_CLOSURE_N_NOTIFIERS()
g_closure_ref, g_closure_ref ()
g_closure_remove_finalize_notifier, g_closure_remove_finalize_notifier ()
g_closure_remove_invalidate_notifier, g_closure_remove_invalidate_notifier ()
g_closure_set_marshal, g_closure_set_marshal ()
g_closure_set_meta_marshal, g_closure_set_meta_marshal ()
g_closure_sink, g_closure_sink ()
g_closure_unref, g_closure_unref ()
G_DEFINE_ABSTRACT_TYPE, G_DEFINE_ABSTRACT_TYPE()
G_DEFINE_ABSTRACT_TYPE_WITH_CODE, G_DEFINE_ABSTRACT_TYPE_WITH_CODE()
G_DEFINE_TYPE, G_DEFINE_TYPE()
G_DEFINE_TYPE_EXTENDED, G_DEFINE_TYPE_EXTENDED()
G_DEFINE_TYPE_WITH_CODE, G_DEFINE_TYPE_WITH_CODE()
G_ENUM_CLASS, G_ENUM_CLASS()
G_ENUM_CLASS_TYPE, G_ENUM_CLASS_TYPE()
G_ENUM_CLASS_TYPE_NAME, G_ENUM_CLASS_TYPE_NAME()
g_enum_complete_type_info, g_enum_complete_type_info ()
g_enum_get_value, g_enum_get_value ()
g_enum_get_value_by_name, g_enum_get_value_by_name ()
g_enum_get_value_by_nick, g_enum_get_value_by_nick ()
g_enum_register_static, g_enum_register_static ()
G_FLAGS_CLASS, G_FLAGS_CLASS()
G_FLAGS_CLASS_TYPE, G_FLAGS_CLASS_TYPE()
G_FLAGS_CLASS_TYPE_NAME, G_FLAGS_CLASS_TYPE_NAME()
g_flags_complete_type_info, g_flags_complete_type_info ()
g_flags_get_first_value, g_flags_get_first_value ()
g_flags_get_value_by_name, g_flags_get_value_by_name ()
g_flags_get_value_by_nick, g_flags_get_value_by_nick ()
g_flags_register_static, g_flags_register_static ()
G_IMPLEMENT_INTERFACE, G_IMPLEMENT_INTERFACE()
G_IS_ENUM_CLASS, G_IS_ENUM_CLASS()
G_IS_FLAGS_CLASS, G_IS_FLAGS_CLASS()
G_IS_OBJECT, G_IS_OBJECT()
G_IS_OBJECT_CLASS, G_IS_OBJECT_CLASS()
G_IS_PARAM_SPEC, G_IS_PARAM_SPEC()
G_IS_PARAM_SPEC_BOOLEAN, G_IS_PARAM_SPEC_BOOLEAN()
G_IS_PARAM_SPEC_BOXED, G_IS_PARAM_SPEC_BOXED()
G_IS_PARAM_SPEC_CHAR, G_IS_PARAM_SPEC_CHAR()
G_IS_PARAM_SPEC_CLASS, G_IS_PARAM_SPEC_CLASS()
G_IS_PARAM_SPEC_DOUBLE, G_IS_PARAM_SPEC_DOUBLE()
G_IS_PARAM_SPEC_ENUM, G_IS_PARAM_SPEC_ENUM()
G_IS_PARAM_SPEC_FLAGS, G_IS_PARAM_SPEC_FLAGS()
G_IS_PARAM_SPEC_FLOAT, G_IS_PARAM_SPEC_FLOAT()
G_IS_PARAM_SPEC_GTYPE, G_IS_PARAM_SPEC_GTYPE()
G_IS_PARAM_SPEC_INT, G_IS_PARAM_SPEC_INT()
G_IS_PARAM_SPEC_INT64, G_IS_PARAM_SPEC_INT64()
G_IS_PARAM_SPEC_LONG, G_IS_PARAM_SPEC_LONG()
G_IS_PARAM_SPEC_OBJECT, G_IS_PARAM_SPEC_OBJECT()
G_IS_PARAM_SPEC_OVERRIDE, G_IS_PARAM_SPEC_OVERRIDE()
G_IS_PARAM_SPEC_PARAM, G_IS_PARAM_SPEC_PARAM()
G_IS_PARAM_SPEC_POINTER, G_IS_PARAM_SPEC_POINTER()
G_IS_PARAM_SPEC_STRING, G_IS_PARAM_SPEC_STRING()
G_IS_PARAM_SPEC_UCHAR, G_IS_PARAM_SPEC_UCHAR()
G_IS_PARAM_SPEC_UINT, G_IS_PARAM_SPEC_UINT()
G_IS_PARAM_SPEC_UINT64, G_IS_PARAM_SPEC_UINT64()
G_IS_PARAM_SPEC_ULONG, G_IS_PARAM_SPEC_ULONG()
G_IS_PARAM_SPEC_UNICHAR, G_IS_PARAM_SPEC_UNICHAR()
G_IS_PARAM_SPEC_VALUE_ARRAY, G_IS_PARAM_SPEC_VALUE_ARRAY()
G_IS_VALUE, G_IS_VALUE()
G_OBJECT, G_OBJECT()
g_object_add_toggle_ref, g_object_add_toggle_ref ()
g_object_add_weak_pointer, g_object_add_weak_pointer ()
G_OBJECT_CLASS, G_OBJECT_CLASS()
g_object_class_find_property, g_object_class_find_property ()
g_object_class_install_property, g_object_class_install_property ()
g_object_class_list_properties, g_object_class_list_properties ()
G_OBJECT_CLASS_NAME, G_OBJECT_CLASS_NAME()
g_object_class_override_property, g_object_class_override_property ()
G_OBJECT_CLASS_TYPE, G_OBJECT_CLASS_TYPE()
g_object_connect, g_object_connect ()
g_object_disconnect, g_object_disconnect ()
g_object_force_floating, g_object_force_floating ()
g_object_freeze_notify, g_object_freeze_notify ()
g_object_get, g_object_get ()
G_OBJECT_GET_CLASS, G_OBJECT_GET_CLASS()
g_object_get_data, g_object_get_data ()
g_object_get_property, g_object_get_property ()
g_object_get_qdata, g_object_get_qdata ()
g_object_get_valist, g_object_get_valist ()
g_object_interface_find_property, g_object_interface_find_property ()
g_object_interface_install_property, g_object_interface_install_property ()
g_object_interface_list_properties, g_object_interface_list_properties ()
g_object_is_floating, g_object_is_floating ()
g_object_new, g_object_new ()
g_object_newv, g_object_newv ()
g_object_new_valist, g_object_new_valist ()
g_object_notify, g_object_notify ()
g_object_ref, g_object_ref ()
g_object_ref_sink, g_object_ref_sink ()
g_object_remove_toggle_ref, g_object_remove_toggle_ref ()
g_object_remove_weak_pointer, g_object_remove_weak_pointer ()
g_object_run_dispose, g_object_run_dispose ()
g_object_set, g_object_set ()
g_object_set_data, g_object_set_data ()
g_object_set_data_full, g_object_set_data_full ()
g_object_set_property, g_object_set_property ()
g_object_set_qdata, g_object_set_qdata ()
g_object_set_qdata_full, g_object_set_qdata_full ()
g_object_set_valist, g_object_set_valist ()
g_object_steal_data, g_object_steal_data ()
g_object_steal_qdata, g_object_steal_qdata ()
g_object_thaw_notify, g_object_thaw_notify ()
G_OBJECT_TYPE, G_OBJECT_TYPE()
G_OBJECT_TYPE_NAME, G_OBJECT_TYPE_NAME()
g_object_unref, g_object_unref ()
G_OBJECT_WARN_INVALID_PROPERTY_ID, G_OBJECT_WARN_INVALID_PROPERTY_ID()
g_object_watch_closure, g_object_watch_closure ()
g_object_weak_ref, g_object_weak_ref ()
g_object_weak_unref, g_object_weak_unref ()
G_PARAM_MASK, G_PARAM_MASK
G_PARAM_READWRITE, G_PARAM_READWRITE
G_PARAM_SPEC, G_PARAM_SPEC()
G_PARAM_SPEC_BOOLEAN, G_PARAM_SPEC_BOOLEAN()
g_param_spec_boolean, g_param_spec_boolean ()
G_PARAM_SPEC_BOXED, G_PARAM_SPEC_BOXED()
g_param_spec_boxed, g_param_spec_boxed ()
G_PARAM_SPEC_CHAR, G_PARAM_SPEC_CHAR()
g_param_spec_char, g_param_spec_char ()
G_PARAM_SPEC_CLASS, G_PARAM_SPEC_CLASS()
G_PARAM_SPEC_DOUBLE, G_PARAM_SPEC_DOUBLE()
g_param_spec_double, g_param_spec_double ()
G_PARAM_SPEC_ENUM, G_PARAM_SPEC_ENUM()
g_param_spec_enum, g_param_spec_enum ()
G_PARAM_SPEC_FLAGS, G_PARAM_SPEC_FLAGS()
g_param_spec_flags, g_param_spec_flags ()
G_PARAM_SPEC_FLOAT, G_PARAM_SPEC_FLOAT()
g_param_spec_float, g_param_spec_float ()
g_param_spec_get_blurb, g_param_spec_get_blurb ()
G_PARAM_SPEC_GET_CLASS, G_PARAM_SPEC_GET_CLASS()
g_param_spec_get_name, g_param_spec_get_name ()
g_param_spec_get_nick, g_param_spec_get_nick ()
g_param_spec_get_qdata, g_param_spec_get_qdata ()
g_param_spec_get_redirect_target, g_param_spec_get_redirect_target ()
G_PARAM_SPEC_GTYPE, G_PARAM_SPEC_GTYPE()
g_param_spec_gtype, g_param_spec_gtype ()
G_PARAM_SPEC_INT, G_PARAM_SPEC_INT()
g_param_spec_int, g_param_spec_int ()
G_PARAM_SPEC_INT64, G_PARAM_SPEC_INT64()
g_param_spec_int64, g_param_spec_int64 ()
g_param_spec_internal, g_param_spec_internal ()
G_PARAM_SPEC_LONG, G_PARAM_SPEC_LONG()
g_param_spec_long, g_param_spec_long ()
G_PARAM_SPEC_OBJECT, G_PARAM_SPEC_OBJECT()
g_param_spec_object, g_param_spec_object ()
G_PARAM_SPEC_OVERRIDE, G_PARAM_SPEC_OVERRIDE()
g_param_spec_override, g_param_spec_override ()
G_PARAM_SPEC_PARAM, G_PARAM_SPEC_PARAM()
g_param_spec_param, g_param_spec_param ()
G_PARAM_SPEC_POINTER, G_PARAM_SPEC_POINTER()
g_param_spec_pointer, g_param_spec_pointer ()
g_param_spec_pool_insert, g_param_spec_pool_insert ()
g_param_spec_pool_list, g_param_spec_pool_list ()
g_param_spec_pool_list_owned, g_param_spec_pool_list_owned ()
g_param_spec_pool_lookup, g_param_spec_pool_lookup ()
g_param_spec_pool_new, g_param_spec_pool_new ()
g_param_spec_pool_remove, g_param_spec_pool_remove ()
g_param_spec_ref, g_param_spec_ref ()
g_param_spec_ref_sink, g_param_spec_ref_sink ()
g_param_spec_set_qdata, g_param_spec_set_qdata ()
g_param_spec_set_qdata_full, g_param_spec_set_qdata_full ()
g_param_spec_sink, g_param_spec_sink ()
g_param_spec_steal_qdata, g_param_spec_steal_qdata ()
G_PARAM_SPEC_STRING, G_PARAM_SPEC_STRING()
g_param_spec_string, g_param_spec_string ()
G_PARAM_SPEC_TYPE, G_PARAM_SPEC_TYPE()
G_PARAM_SPEC_TYPE_NAME, G_PARAM_SPEC_TYPE_NAME()
G_PARAM_SPEC_UCHAR, G_PARAM_SPEC_UCHAR()
g_param_spec_uchar, g_param_spec_uchar ()
G_PARAM_SPEC_UINT, G_PARAM_SPEC_UINT()
g_param_spec_uint, g_param_spec_uint ()
G_PARAM_SPEC_UINT64, G_PARAM_SPEC_UINT64()
g_param_spec_uint64, g_param_spec_uint64 ()
G_PARAM_SPEC_ULONG, G_PARAM_SPEC_ULONG()
g_param_spec_ulong, g_param_spec_ulong ()
G_PARAM_SPEC_UNICHAR, G_PARAM_SPEC_UNICHAR()
g_param_spec_unichar, g_param_spec_unichar ()
g_param_spec_unref, g_param_spec_unref ()
G_PARAM_SPEC_VALUE_ARRAY, G_PARAM_SPEC_VALUE_ARRAY()
g_param_spec_value_array, g_param_spec_value_array ()
G_PARAM_SPEC_VALUE_TYPE, G_PARAM_SPEC_VALUE_TYPE()
g_param_type_register_static, g_param_type_register_static ()
G_PARAM_USER_SHIFT, G_PARAM_USER_SHIFT
g_param_values_cmp, g_param_values_cmp ()
g_param_value_convert, g_param_value_convert ()
g_param_value_defaults, g_param_value_defaults ()
g_param_value_set_default, g_param_value_set_default ()
g_param_value_validate, g_param_value_validate ()
g_pointer_type_register_static, g_pointer_type_register_static ()
g_signal_accumulator_true_handled, g_signal_accumulator_true_handled ()
g_signal_add_emission_hook, g_signal_add_emission_hook ()
g_signal_chain_from_overridden, g_signal_chain_from_overridden ()
g_signal_connect, g_signal_connect()
g_signal_connect_after, g_signal_connect_after()
g_signal_connect_closure, g_signal_connect_closure ()
g_signal_connect_closure_by_id, g_signal_connect_closure_by_id ()
g_signal_connect_data, g_signal_connect_data ()
g_signal_connect_object, g_signal_connect_object ()
g_signal_connect_swapped, g_signal_connect_swapped()
g_signal_emit, g_signal_emit ()
g_signal_emitv, g_signal_emitv ()
g_signal_emit_by_name, g_signal_emit_by_name ()
g_signal_emit_valist, g_signal_emit_valist ()
G_SIGNAL_FLAGS_MASK, G_SIGNAL_FLAGS_MASK
g_signal_get_invocation_hint, g_signal_get_invocation_hint ()
g_signal_handlers_block_by_func, g_signal_handlers_block_by_func()
g_signal_handlers_block_matched, g_signal_handlers_block_matched ()
g_signal_handlers_disconnect_by_func, g_signal_handlers_disconnect_by_func()
g_signal_handlers_disconnect_matched, g_signal_handlers_disconnect_matched ()
g_signal_handlers_unblock_by_func, g_signal_handlers_unblock_by_func()
g_signal_handlers_unblock_matched, g_signal_handlers_unblock_matched ()
g_signal_handler_block, g_signal_handler_block ()
g_signal_handler_disconnect, g_signal_handler_disconnect ()
g_signal_handler_find, g_signal_handler_find ()
g_signal_handler_is_connected, g_signal_handler_is_connected ()
g_signal_handler_unblock, g_signal_handler_unblock ()
g_signal_has_handler_pending, g_signal_has_handler_pending ()
g_signal_list_ids, g_signal_list_ids ()
g_signal_lookup, g_signal_lookup ()
G_SIGNAL_MATCH_MASK, G_SIGNAL_MATCH_MASK
g_signal_name, g_signal_name ()
g_signal_new, g_signal_new ()
g_signal_newv, g_signal_newv ()
g_signal_new_valist, g_signal_new_valist ()
g_signal_override_class_closure, g_signal_override_class_closure ()
g_signal_parse_name, g_signal_parse_name ()
g_signal_query, g_signal_query ()
g_signal_remove_emission_hook, g_signal_remove_emission_hook ()
g_signal_stop_emission, g_signal_stop_emission ()
g_signal_stop_emission_by_name, g_signal_stop_emission_by_name ()
g_signal_type_cclosure_new, g_signal_type_cclosure_new ()
G_SIGNAL_TYPE_STATIC_SCOPE, G_SIGNAL_TYPE_STATIC_SCOPE
g_source_set_closure, g_source_set_closure ()
g_strdup_value_contents, g_strdup_value_contents ()
g_trap_object_ref, Debugging reference count problems
g_type_add_class_cache_func, g_type_add_class_cache_func ()
g_type_add_interface_check, g_type_add_interface_check ()
g_type_add_interface_dynamic, g_type_add_interface_dynamic ()
g_type_add_interface_static, g_type_add_interface_static ()
G_TYPE_BOOLEAN, G_TYPE_BOOLEAN
G_TYPE_BOXED, G_TYPE_BOXED
G_TYPE_CHAR, G_TYPE_CHAR
G_TYPE_CHECK_CLASS_CAST, G_TYPE_CHECK_CLASS_CAST()
G_TYPE_CHECK_CLASS_TYPE, G_TYPE_CHECK_CLASS_TYPE()
G_TYPE_CHECK_INSTANCE, G_TYPE_CHECK_INSTANCE()
G_TYPE_CHECK_INSTANCE_CAST, G_TYPE_CHECK_INSTANCE_CAST()
G_TYPE_CHECK_INSTANCE_TYPE, G_TYPE_CHECK_INSTANCE_TYPE()
G_TYPE_CHECK_VALUE, G_TYPE_CHECK_VALUE()
G_TYPE_CHECK_VALUE_TYPE, G_TYPE_CHECK_VALUE_TYPE()
g_type_children, g_type_children ()
g_type_class_add_private, g_type_class_add_private ()
g_type_class_peek, g_type_class_peek ()
g_type_class_peek_parent, g_type_class_peek_parent ()
g_type_class_peek_static, g_type_class_peek_static ()
g_type_class_ref, g_type_class_ref ()
g_type_class_unref, g_type_class_unref ()
g_type_class_unref_uncached, g_type_class_unref_uncached ()
G_TYPE_CLOSURE, G_TYPE_CLOSURE
g_type_create_instance, g_type_create_instance ()
G_TYPE_DATE, G_TYPE_DATE
g_type_default_interface_peek, g_type_default_interface_peek ()
g_type_default_interface_ref, g_type_default_interface_ref ()
g_type_default_interface_unref, g_type_default_interface_unref ()
g_type_depth, g_type_depth ()
G_TYPE_DOUBLE, G_TYPE_DOUBLE
G_TYPE_ENUM, G_TYPE_ENUM
G_TYPE_FLAGS, G_TYPE_FLAGS
G_TYPE_FLAG_RESERVED_ID_BIT, G_TYPE_FLAG_RESERVED_ID_BIT
G_TYPE_FLOAT, G_TYPE_FLOAT
g_type_free_instance, g_type_free_instance ()
G_TYPE_FROM_CLASS, G_TYPE_FROM_CLASS()
G_TYPE_FROM_INSTANCE, G_TYPE_FROM_INSTANCE()
G_TYPE_FROM_INTERFACE, G_TYPE_FROM_INTERFACE()
g_type_from_name, g_type_from_name ()
G_TYPE_FUNDAMENTAL, G_TYPE_FUNDAMENTAL()
g_type_fundamental, g_type_fundamental ()
G_TYPE_FUNDAMENTAL_MAX, G_TYPE_FUNDAMENTAL_MAX
g_type_fundamental_next, g_type_fundamental_next ()
g_type_get_plugin, g_type_get_plugin ()
g_type_get_qdata, g_type_get_qdata ()
G_TYPE_GSTRING, G_TYPE_GSTRING
G_TYPE_GTYPE, G_TYPE_GTYPE
G_TYPE_HASH_TABLE, G_TYPE_HASH_TABLE
G_TYPE_HAS_VALUE_TABLE, G_TYPE_HAS_VALUE_TABLE()
g_type_init, g_type_init ()
G_TYPE_INITIALLY_UNOWNED, G_TYPE_INITIALLY_UNOWNED
g_type_init_with_debug_flags, g_type_init_with_debug_flags ()
G_TYPE_INSTANCE_GET_CLASS, G_TYPE_INSTANCE_GET_CLASS()
G_TYPE_INSTANCE_GET_INTERFACE, G_TYPE_INSTANCE_GET_INTERFACE()
G_TYPE_INSTANCE_GET_PRIVATE, G_TYPE_INSTANCE_GET_PRIVATE()
G_TYPE_INT, G_TYPE_INT
G_TYPE_INT64, G_TYPE_INT64
G_TYPE_INTERFACE, G_TYPE_INTERFACE
g_type_interfaces, g_type_interfaces ()
g_type_interface_add_prerequisite, g_type_interface_add_prerequisite ()
g_type_interface_get_plugin, g_type_interface_get_plugin ()
g_type_interface_peek, g_type_interface_peek ()
g_type_interface_peek_parent, g_type_interface_peek_parent ()
g_type_interface_prerequisites, g_type_interface_prerequisites ()
G_TYPE_INVALID, G_TYPE_INVALID
G_TYPE_IO_CHANNEL, G_TYPE_IO_CHANNEL
G_TYPE_IO_CONDITION, G_TYPE_IO_CONDITION
g_type_is_a, g_type_is_a ()
G_TYPE_IS_ABSTRACT, G_TYPE_IS_ABSTRACT()
G_TYPE_IS_CLASSED, G_TYPE_IS_CLASSED()
G_TYPE_IS_DEEP_DERIVABLE, G_TYPE_IS_DEEP_DERIVABLE()
G_TYPE_IS_DERIVABLE, G_TYPE_IS_DERIVABLE()
G_TYPE_IS_DERIVED, G_TYPE_IS_DERIVED()
G_TYPE_IS_ENUM, G_TYPE_IS_ENUM()
G_TYPE_IS_FLAGS, G_TYPE_IS_FLAGS()
G_TYPE_IS_FUNDAMENTAL, G_TYPE_IS_FUNDAMENTAL()
G_TYPE_IS_INSTANTIATABLE, G_TYPE_IS_INSTANTIATABLE()
G_TYPE_IS_INTERFACE, G_TYPE_IS_INTERFACE()
G_TYPE_IS_OBJECT, G_TYPE_IS_OBJECT()
G_TYPE_IS_PARAM, G_TYPE_IS_PARAM()
G_TYPE_IS_VALUE, G_TYPE_IS_VALUE()
G_TYPE_IS_VALUE_ABSTRACT, G_TYPE_IS_VALUE_ABSTRACT()
G_TYPE_IS_VALUE_TYPE, G_TYPE_IS_VALUE_TYPE()
G_TYPE_LONG, G_TYPE_LONG
G_TYPE_MAKE_FUNDAMENTAL, G_TYPE_MAKE_FUNDAMENTAL()
g_type_module_add_interface, g_type_module_add_interface ()
g_type_module_register_enum, g_type_module_register_enum ()
g_type_module_register_flags, g_type_module_register_flags ()
g_type_module_register_type, g_type_module_register_type ()
g_type_module_set_name, g_type_module_set_name ()
g_type_module_unuse, g_type_module_unuse ()
g_type_module_use, g_type_module_use ()
g_type_name, g_type_name ()
g_type_next_base, g_type_next_base ()
G_TYPE_NONE, G_TYPE_NONE
G_TYPE_OBJECT, G_TYPE_OBJECT
G_TYPE_PARAM, G_TYPE_PARAM
G_TYPE_PARAM_BOOLEAN, G_TYPE_PARAM_BOOLEAN
G_TYPE_PARAM_BOXED, G_TYPE_PARAM_BOXED
G_TYPE_PARAM_CHAR, G_TYPE_PARAM_CHAR
G_TYPE_PARAM_DOUBLE, G_TYPE_PARAM_DOUBLE
G_TYPE_PARAM_ENUM, G_TYPE_PARAM_ENUM
G_TYPE_PARAM_FLAGS, G_TYPE_PARAM_FLAGS
G_TYPE_PARAM_FLOAT, G_TYPE_PARAM_FLOAT
G_TYPE_PARAM_GTYPE, G_TYPE_PARAM_GTYPE
G_TYPE_PARAM_INT, G_TYPE_PARAM_INT
G_TYPE_PARAM_INT64, G_TYPE_PARAM_INT64
G_TYPE_PARAM_LONG, G_TYPE_PARAM_LONG
G_TYPE_PARAM_OBJECT, G_TYPE_PARAM_OBJECT
G_TYPE_PARAM_OVERRIDE, G_TYPE_PARAM_OVERRIDE
G_TYPE_PARAM_PARAM, G_TYPE_PARAM_PARAM
G_TYPE_PARAM_POINTER, G_TYPE_PARAM_POINTER
G_TYPE_PARAM_STRING, G_TYPE_PARAM_STRING
G_TYPE_PARAM_UCHAR, G_TYPE_PARAM_UCHAR
G_TYPE_PARAM_UINT, G_TYPE_PARAM_UINT
G_TYPE_PARAM_UINT64, G_TYPE_PARAM_UINT64
G_TYPE_PARAM_ULONG, G_TYPE_PARAM_ULONG
G_TYPE_PARAM_UNICHAR, G_TYPE_PARAM_UNICHAR
G_TYPE_PARAM_VALUE_ARRAY, G_TYPE_PARAM_VALUE_ARRAY
g_type_parent, g_type_parent ()
g_type_plugin_complete_interface_info, g_type_plugin_complete_interface_info ()
g_type_plugin_complete_type_info, g_type_plugin_complete_type_info ()
g_type_plugin_unuse, g_type_plugin_unuse ()
g_type_plugin_use, g_type_plugin_use ()
G_TYPE_POINTER, G_TYPE_POINTER
g_type_qname, g_type_qname ()
g_type_query, g_type_query ()
g_type_register_dynamic, g_type_register_dynamic ()
g_type_register_fundamental, g_type_register_fundamental ()
g_type_register_static, g_type_register_static ()
g_type_register_static_simple, g_type_register_static_simple ()
g_type_remove_class_cache_func, g_type_remove_class_cache_func ()
g_type_remove_interface_check, g_type_remove_interface_check ()
G_TYPE_RESERVED_BSE_FIRST, G_TYPE_RESERVED_BSE_FIRST
G_TYPE_RESERVED_BSE_LAST, G_TYPE_RESERVED_BSE_LAST
G_TYPE_RESERVED_GLIB_FIRST, G_TYPE_RESERVED_GLIB_FIRST
G_TYPE_RESERVED_GLIB_LAST, G_TYPE_RESERVED_GLIB_LAST
G_TYPE_RESERVED_USER_FIRST, G_TYPE_RESERVED_USER_FIRST
g_type_set_qdata, g_type_set_qdata ()
G_TYPE_STRING, G_TYPE_STRING
G_TYPE_STRV, G_TYPE_STRV
G_TYPE_UCHAR, G_TYPE_UCHAR
G_TYPE_UINT, G_TYPE_UINT
G_TYPE_UINT64, G_TYPE_UINT64
G_TYPE_ULONG, G_TYPE_ULONG
G_TYPE_VALUE, G_TYPE_VALUE
G_TYPE_VALUE_ARRAY, G_TYPE_VALUE_ARRAY
g_type_value_table_peek, g_type_value_table_peek ()
g_value_array_append, g_value_array_append ()
g_value_array_copy, g_value_array_copy ()
g_value_array_free, g_value_array_free ()
g_value_array_get_nth, g_value_array_get_nth ()
g_value_array_insert, g_value_array_insert ()
g_value_array_new, g_value_array_new ()
g_value_array_prepend, g_value_array_prepend ()
g_value_array_remove, g_value_array_remove ()
g_value_array_sort, g_value_array_sort ()
g_value_array_sort_with_data, g_value_array_sort_with_data ()
G_VALUE_COLLECT, G_VALUE_COLLECT()
G_VALUE_COLLECT_FORMAT_MAX_LENGTH, G_VALUE_COLLECT_FORMAT_MAX_LENGTH
g_value_copy, g_value_copy ()
g_value_dup_boxed, g_value_dup_boxed ()
g_value_dup_object, g_value_dup_object ()
g_value_dup_param, g_value_dup_param ()
g_value_dup_string, g_value_dup_string ()
g_value_fits_pointer, g_value_fits_pointer ()
g_value_get_boolean, g_value_get_boolean ()
g_value_get_boxed, g_value_get_boxed ()
g_value_get_char, g_value_get_char ()
g_value_get_double, g_value_get_double ()
g_value_get_enum, g_value_get_enum ()
g_value_get_flags, g_value_get_flags ()
g_value_get_float, g_value_get_float ()
g_value_get_gtype, g_value_get_gtype ()
g_value_get_int, g_value_get_int ()
g_value_get_int64, g_value_get_int64 ()
g_value_get_long, g_value_get_long ()
g_value_get_object, g_value_get_object ()
g_value_get_param, g_value_get_param ()
g_value_get_pointer, g_value_get_pointer ()
g_value_get_string, g_value_get_string ()
g_value_get_uchar, g_value_get_uchar ()
g_value_get_uint, g_value_get_uint ()
g_value_get_uint64, g_value_get_uint64 ()
g_value_get_ulong, g_value_get_ulong ()
G_VALUE_HOLDS, G_VALUE_HOLDS()
G_VALUE_HOLDS_BOOLEAN, G_VALUE_HOLDS_BOOLEAN()
G_VALUE_HOLDS_BOXED, G_VALUE_HOLDS_BOXED()
G_VALUE_HOLDS_CHAR, G_VALUE_HOLDS_CHAR()
G_VALUE_HOLDS_DOUBLE, G_VALUE_HOLDS_DOUBLE()
G_VALUE_HOLDS_ENUM, G_VALUE_HOLDS_ENUM()
G_VALUE_HOLDS_FLAGS, G_VALUE_HOLDS_FLAGS()
G_VALUE_HOLDS_FLOAT, G_VALUE_HOLDS_FLOAT()
G_VALUE_HOLDS_GTYPE, G_VALUE_HOLDS_GTYPE()
G_VALUE_HOLDS_INT, G_VALUE_HOLDS_INT()
G_VALUE_HOLDS_INT64, G_VALUE_HOLDS_INT64()
G_VALUE_HOLDS_LONG, G_VALUE_HOLDS_LONG()
G_VALUE_HOLDS_OBJECT, G_VALUE_HOLDS_OBJECT()
G_VALUE_HOLDS_PARAM, G_VALUE_HOLDS_PARAM()
G_VALUE_HOLDS_POINTER, G_VALUE_HOLDS_POINTER()
G_VALUE_HOLDS_STRING, G_VALUE_HOLDS_STRING()
G_VALUE_HOLDS_UCHAR, G_VALUE_HOLDS_UCHAR()
G_VALUE_HOLDS_UINT, G_VALUE_HOLDS_UINT()
G_VALUE_HOLDS_UINT64, G_VALUE_HOLDS_UINT64()
G_VALUE_HOLDS_ULONG, G_VALUE_HOLDS_ULONG()
g_value_init, g_value_init ()
G_VALUE_LCOPY, G_VALUE_LCOPY()
g_value_peek_pointer, g_value_peek_pointer ()
g_value_register_transform_func, g_value_register_transform_func ()
g_value_reset, g_value_reset ()
g_value_set_boolean, g_value_set_boolean ()
g_value_set_boxed, g_value_set_boxed ()
g_value_set_boxed_take_ownership, g_value_set_boxed_take_ownership ()
g_value_set_char, g_value_set_char ()
g_value_set_double, g_value_set_double ()
g_value_set_enum, g_value_set_enum ()
g_value_set_flags, g_value_set_flags ()
g_value_set_float, g_value_set_float ()
g_value_set_gtype, g_value_set_gtype ()
g_value_set_instance, g_value_set_instance ()
g_value_set_int, g_value_set_int ()
g_value_set_int64, g_value_set_int64 ()
g_value_set_long, g_value_set_long ()
g_value_set_object, g_value_set_object ()
g_value_set_object_take_ownership, g_value_set_object_take_ownership ()
g_value_set_param, g_value_set_param ()
g_value_set_param_take_ownership, g_value_set_param_take_ownership ()
g_value_set_pointer, g_value_set_pointer ()
g_value_set_static_boxed, g_value_set_static_boxed ()
g_value_set_static_string, g_value_set_static_string ()
g_value_set_string, g_value_set_string ()
g_value_set_string_take_ownership, g_value_set_string_take_ownership ()
g_value_set_uchar, g_value_set_uchar ()
g_value_set_uint, g_value_set_uint ()
g_value_set_uint64, g_value_set_uint64 ()
g_value_set_ulong, g_value_set_ulong ()
g_value_take_boxed, g_value_take_boxed ()
g_value_take_object, g_value_take_object ()
g_value_take_param, g_value_take_param ()
g_value_take_string, g_value_take_string ()
g_value_transform, g_value_transform ()
G_VALUE_TYPE, G_VALUE_TYPE()
g_value_type_compatible, g_value_type_compatible ()
G_VALUE_TYPE_NAME, G_VALUE_TYPE_NAME()
g_value_type_transformable, g_value_type_transformable ()
g_value_unset, g_value_unset ()


Index of deprecated symbols

G

g_value_set_boxed_take_ownership, g_value_set_boxed_take_ownership ()
g_value_set_object_take_ownership, g_value_set_object_take_ownership ()
g_value_set_param_take_ownership, g_value_set_param_take_ownership ()
g_value_set_string_take_ownership, g_value_set_string_take_ownership ()


Index of new symbols in 2.2

G

g_type_interface_prerequisites, g_type_interface_prerequisites ()


Index of new symbols in 2.4

G

GParamSpecOverride, GParamSpecOverride
GTypeInterfaceCheckFunc, GTypeInterfaceCheckFunc ()
G_DEFINE_ABSTRACT_TYPE, G_DEFINE_ABSTRACT_TYPE()
G_DEFINE_ABSTRACT_TYPE_WITH_CODE, G_DEFINE_ABSTRACT_TYPE_WITH_CODE()
G_DEFINE_TYPE, G_DEFINE_TYPE()
G_DEFINE_TYPE_EXTENDED, G_DEFINE_TYPE_EXTENDED()
G_DEFINE_TYPE_WITH_CODE, G_DEFINE_TYPE_WITH_CODE()
G_IMPLEMENT_INTERFACE, G_IMPLEMENT_INTERFACE()
G_IS_PARAM_SPEC_OVERRIDE, G_IS_PARAM_SPEC_OVERRIDE()
g_object_interface_find_property, g_object_interface_find_property ()
g_object_interface_install_property, g_object_interface_install_property ()
g_object_interface_list_properties, g_object_interface_list_properties ()
g_param_spec_get_redirect_target, g_param_spec_get_redirect_target ()
G_PARAM_SPEC_OVERRIDE, G_PARAM_SPEC_OVERRIDE()
g_param_spec_override, g_param_spec_override ()
g_signal_accumulator_true_handled, g_signal_accumulator_true_handled ()
g_type_add_interface_check, g_type_add_interface_check ()
g_type_class_add_private, g_type_class_add_private ()
g_type_class_peek_static, g_type_class_peek_static ()
g_type_default_interface_peek, g_type_default_interface_peek ()
g_type_default_interface_ref, g_type_default_interface_ref ()
g_type_default_interface_unref, g_type_default_interface_unref ()
G_TYPE_INSTANCE_GET_PRIVATE, G_TYPE_INSTANCE_GET_PRIVATE()
G_TYPE_PARAM_OVERRIDE, G_TYPE_PARAM_OVERRIDE
g_type_remove_interface_check, g_type_remove_interface_check ()
G_TYPE_STRV, G_TYPE_STRV
g_value_take_boxed, g_value_take_boxed ()
g_value_take_object, g_value_take_object ()
g_value_take_param, g_value_take_param ()
g_value_take_string, g_value_take_string ()


Index of new symbols in 2.6

G

g_type_module_register_enum, g_type_module_register_enum ()
g_type_module_register_flags, g_type_module_register_flags ()


Index of new symbols in 2.8

G

g_object_add_toggle_ref, g_object_add_toggle_ref ()
g_object_remove_toggle_ref, g_object_remove_toggle_ref ()


Index of new symbols in 2.10

G

GParamSpecGType, GParamSpecGType
G_IS_PARAM_SPEC_GTYPE, G_IS_PARAM_SPEC_GTYPE()
g_object_force_floating, g_object_force_floating ()
g_object_is_floating, g_object_is_floating ()
g_object_ref_sink, g_object_ref_sink ()
G_PARAM_SPEC_GTYPE, G_PARAM_SPEC_GTYPE()
g_param_spec_gtype, g_param_spec_gtype ()
g_param_spec_ref_sink, g_param_spec_ref_sink ()
G_TYPE_HASH_TABLE, G_TYPE_HASH_TABLE
G_TYPE_PARAM_GTYPE, G_TYPE_PARAM_GTYPE


Index of new symbols in 2.12

G

g_type_register_static_simple, g_type_register_static_simple ()
g_value_get_gtype, g_value_get_gtype ()
G_VALUE_HOLDS_GTYPE, G_VALUE_HOLDS_GTYPE()
g_value_set_gtype, g_value_set_gtype ()


Introduction

Most modern programming languages come with their own native object systems and additional fundamental algorithmic language constructs. Just as GLib serves as an implementation of such fundamental types and algorithms (linked lists, hash tables and so forth), the GLib Object System provides the required implementations of a flexible extensible and intentionally easy to map (into other languages) object oriented framework for C. The substantial elements that are provided can be summarized as:

  • A generic type system to register arbitrary single-inherited flat and deep derived types as well as interfaces for structured types. It takes care of creation, initialization and memory management of the assorted object and class structures, maintains parent/child relationships and deals with dynamic implementations of such types. That is, their type specific implementations are relocatable/unloadable during runtime.

  • A collection of fundamental type implementations, such as integers, doubles, enums and structured types, to name a few.

  • A sample fundamental type implementation to base object hierarchies upon - the GObject fundamental type.

  • A signal system that allows very flexible user customization of virtual/overridable object methods and can serve as a powerful notification mechanism.

  • An extensible parameter/value system, supporting all the provided fundamental types that can be used to generically handle object properties or otherwise parameterized types.


Prev Home GObject Reference Manual Next

Part I. Concepts


Part IV. Tutorial

This chapter tries to answer the real-life questions of users and presents the most common scenario use-cases I could come up with. The use-cases are presented from most likely to less likely.


Part V. Related Tools

Several useful developer tools have been build around GObject technology. The next sections briefly introduce them and link to the respective project pages.


Prev Home GObject Reference Manual Next

API Reference


Prev Home GObject Reference Manual Next

Tools Reference


Signals

GObject's signals have nothing to do with standard UNIX signals: they connect arbitrary application-specific events with any number of listeners. For example, in GTK+, every user event (keystroke or mouse move) is received from the X server and generates a GTK+ event under the form of a signal emission on a given object instance.

Each signal is registered in the type system together with the type on which it can be emitted: users of the type are said to connect to the signal on a given type instance when they register a closure to be invoked upon the signal emission. Users can also emit the signal by themselves or stop the emission of the signal from within one of the closures connected to the signal.

When a signal is emitted on a given type instance, all the closures connected to this signal on this type instance will be invoked. All the closures connected to such a signal represent callbacks whose signature looks like:

return_type function_callback (gpointer instance, ... , gpointer user_data);

Signal registration

To register a new signal on an existing type, we can use any of g_signal_newv, g_signal_new_valist or g_signal_new functions:

guint                 g_signal_newv         (const gchar        *signal_name,
                                             GType               itype,
                                             GSignalFlags        signal_flags,
                                             GClosure           *class_closure,
                                             GSignalAccumulator  accumulator,
                                             gpointer            accu_data,
                                             GSignalCMarshaller  c_marshaller,
                                             GType               return_type,
                                             guint               n_params,
                                             GType              *param_types);

The number of parameters to these functions is a bit intimidating but they are relatively simple:

  • signal_name: is a string which can be used to uniquely identify a given signal.

  • itype: is the instance type on which this signal can be emitted.

  • signal_flags: partly defines the order in which closures which were connected to the signal are invoked.

  • class_closure: this is the default closure for the signal: if it is not NULL upon the signal emission, it will be invoked upon this emission of the signal. The moment where this closure is invoked compared to other closures connected to that signal depends partly on the signal_flags.

  • accumulator: this is a function pointer which is invoked after each closure has been invoked. If it returns FALSE, signal emission is stopped. If it returns TRUE, signal emission proceeds normally. It is also used to compute the return value of the signal based on the return value of all the invoked closures.

  • accumulator_data: this pointer will be passed down to each invocation of the accumulator during emission.

  • c_marshaller: this is the default C marshaller for any closure which is connected to this signal.

  • return_type: this is the type of the return value of the signal.

  • n_params: this is the number of parameters this signal takes.

  • param_types: this is an array of GTypes which indicate the type of each parameter of the signal. The length of this array is indicated by n_params.

As you can see from the above definition, a signal is basically a description of the closures which can be connected to this signal and a description of the order in which the closures connected to this signal will be invoked.

Signal connection

If you want to connect to a signal with a closure, you have three possibilities:

  • You can register a class closure at signal registration: this is a system-wide operation. i.e.: the class_closure will be invoked during each emission of a given signal on all the instances of the type which supports that signal.

  • You can use g_signal_override_class_closure which overrides the class_closure of a given type. It is possible to call this function only on a derived type of the type on which the signal was registered. This function is of use only to language bindings.

  • You can register a closure with the g_signal_connect family of functions. This is an instance-specific operation: the closure will be invoked only during emission of a given signal on a given instance.

It is also possible to connect a different kind of callback on a given signal: emission hooks are invoked whenever a given signal is emitted whatever the instance on which it is emitted. Emission hooks are used for example to get all mouse_clicked emissions in an application to be able to emit the small mouse click sound. Emission hooks are connected with g_signal_add_emission_hook and removed with g_signal_remove_emission_hook.

Signal emission

Signal emission is done through the use of the g_signal_emit family of functions.

void                  g_signal_emitv        (const GValue       *instance_and_params,
                         guint               signal_id,
                         GQuark              detail,
                         GValue             *return_value);

  • The instance_and_params array of GValues contains the list of input parameters to the signal. The first element of the array is the instance pointer on which to invoke the signal. The following elements of the array contain the list of parameters to the signal.

  • signal_id identifies the signal to invoke.

  • detail identifies the specific detail of the signal to invoke. A detail is a kind of magic token/argument which is passed around during signal emission and which is used by closures connected to the signal to filter out unwanted signal emissions. In most cases, you can safely set this value to zero. See the section called “The detail argument” for more details about this parameter.

  • return_value holds the return value of the last closure invoked during emission if no accumulator was specified. If an accumulator was specified during signal creation, this accumulator is used to calculate the return_value as a function of the return values of all the closures invoked during emission. [9] If no closure is invoked during emission, the return_value is nonetheless initialized to zero/null.

Internally, the GValue array is passed to the emission function proper, signal_emit_unlocked_R (implemented in gsignal.c). Signal emission can be decomposed in 5 steps:

  • RUN_FIRST: if the G_SIGNAL_RUN_FIRST flag was used during signal registration and if there exist a class_closure for this signal, the class_closure is invoked. Jump to EMISSION_HOOK state.

  • EMISSION_HOOK: if any emission hook was added to the signal, they are invoked from first to last added. Accumulate return values and jump to HANDLER_RUN_FIRST state.

  • HANDLER_RUN_FIRST: if any closure were connected with the g_signal_connect family of functions, and if they are not blocked (with the g_signal_handler_block family of functions) they are run here, from first to last connected. Jump to RUN_LAST state.

  • RUN_LAST: if the G_SIGNAL_RUN_LAST flag was set during registration and if a class_closure was set, it is invoked here. Jump to HANDLER_RUN_LAST state.

  • HANDLER_RUN_LAST: if any closure were connected with the g_signal_connect_after family of functions, if they were not invoked during HANDLER_RUN_FIRST and if they are not blocked, they are run here, from first to last connected. Jump to RUN_CLEANUP state.

  • RUN_CLEANUP: if the G_SIGNAL_RUN_CLEANUP flag was set during registration and if a class_closure was set, it is invoked here. Signal emission is completed here.

If, at any point during emission (except in RUN_CLEANUP state), one of the closures or emission hook stops the signal emission with g_signal_stop, emission jumps to CLEANUP state.

If, at any point during emission, one of the closures or emission hook emits the same signal on the same instance, emission is restarted from the RUN_FIRST state.

The accumulator function is invoked in all states, after invocation of each closure (except in EMISSION_HOOK and CLEANUP). It accumulates the closure return value into the signal return value and returns TRUE or FALSE. If, at any point, it does not return TRUE, emission jumps to CLEANUP state.

If no accumulator function was provided, the value returned by the last handler run will be returned by g_signal_emit.

The detail argument

All the functions related to signal emission or signal connection have a parameter named the detail. Sometimes, this parameter is hidden by the API but it is always there, under one form or another.

Of the three main connection functions, only one has an explicit detail parameter as a GQuark [10]:

gulong	 g_signal_connect_closure_by_id	      (gpointer		  instance,
                           guint		  signal_id,
                           GQuark		  detail,
                           GClosure		 *closure,
                           gboolean		  after);

The two other functions hide the detail parameter in the signal name identification:

gulong	 g_signal_connect_closure	      (gpointer		  instance,
                           const gchar       *detailed_signal,
                           GClosure		 *closure,
                           gboolean		  after);
gulong	 g_signal_connect_data		      (gpointer		  instance,
                           const gchar	 *detailed_signal,
                           GCallback	  c_handler,
                           gpointer		  data,
                           GClosureNotify	  destroy_data,
                           GConnectFlags	  connect_flags);

Their detailed_signal parameter is a string which identifies the name of the signal to connect to. However, the format of this string is structured to look like signal_name::detail_name. Connecting to the signal named notify::cursor_position will actually connect to the signal named notify with the cursor_position name. Internally, the detail string is transformed to a GQuark if it is present.

Of the four main signal emission functions, three have an explicit detail parameter as a GQuark again:

void                  g_signal_emitv        (const GValue       *instance_and_params,
                         guint               signal_id,
                         GQuark              detail,
                         GValue             *return_value);
void                  g_signal_emit_valist  (gpointer            instance,
                         guint               signal_id,
                         GQuark              detail,
                         va_list             var_args);
void                  g_signal_emit         (gpointer            instance,
                         guint               signal_id,
                         GQuark              detail,
                         ...);

The fourth function hides it in its signal name parameter:

void                  g_signal_emit_by_name (gpointer            instance,
                         const gchar        *detailed_signal,
                         ...);

The format of the detailed_signal parameter is exactly the same as the format used by the g_signal_connect functions: signal_name::detail_name.

If a detail is provided by the user to the emission function, it is used during emission to match against the closures which also provide a detail. The closures which provided a detail will not be invoked (even though they are connected to a signal which is being emitted) if their detail does not match the detail provided by the user.

This completely optional filtering mechanism is mainly used as an optimization for signals which are often emitted for many different reasons: the clients can filter out which events they are interested into before the closure's marshalling code runs. For example, this is used extensively by the notify signal of GObject: whenever a property is modified on a GObject, instead of just emitting the notify signal, GObject associates as a detail to this signal emission the name of the property modified. This allows clients who wish to be notified of changes to only one property to filter most events before receiving them.

As a simple rule, users can and should set the detail parameter to zero: this will disable completely this optional filtering.

[9] James (again!!) gives a few non-trivial examples of accumulators: “ For instance, you may have an accumulator that ignores NULL returns from closures, and only accumulates the non-NULL ones. Another accumulator may try to return the list of values returned by the closures. ”

[10] A GQuark is an integer which uniquely represents a string. It is possible to transform back and forth between the integer and string representations with the functions g_quark_from_string and g_quark_to_string.


Graphical inspection of Gobjects

Yet another tool that you may find helpful when working with GObjects is G-Inspector. It is able to display Glib/Gtk+ objects and their properties.


GObject builder

Writing gobjects can be a tedious task. It requires a lot of typing and just doing a copy/paste requires a great deal of care. One obvious idea is to use some sort of templates for the class skeletons. and then run them through a special tool to generate the real C files. GOB/ (or GOB2) is such a tool. It is a preprocessor which can be used to build GObjects with inline C code so that there is no need to edit the generated C code. The syntax is inspired by Java and Yacc or Lex. The implementation is intentionally kept simple: the inline C code provided by the user is not parsed.


Writing API docs

The API documentation for most of the Glib, GObject, GTK+ and GNOME libraries is built with a combination of complex tools. Typically, the part of the documentation which describes the behavior of each function is extracted from the specially-formatted source code comments by a tool named gtk-doc which generates docbook xml and merges this docbook xml with a set of master xml docbook files. These xml docbook files are finally processed with xsltproc (a small program part of the libxslt library) to generate the final html output. Other tools can be used to generate pdf output from the source xml. The following code excerpt shows what these comments look like.

/**
 * gtk_widget_freeze_child_notify:
 * @widget: a #GtkWidget
 *
 * Stops emission of "child-notify" signals on @widget. The signals are
 * queued until gtk_widget_thaw_child_notify() is called on @widget.
 *
 * This is the analogue of g_object_freeze_notify() for child properties.
 **/
void
gtk_widget_freeze_child_notify (GtkWidget *widget)
{
...

The great thoroughful documentation on how to setup and use gtk-doc in your project is provided on the gnome developer website.


Debugging reference count problems

The reference counting scheme used by GObject does solve quite a few memory management problems but also introduces new sources of bugs. In large applications, finding the exact spot where the reference count of an Object is not properly handled can be very difficult. Hopefully, there exist a tool named refdbg/ which can be used to automate the task of tracking down the location of invalid code with regard to reference counting. This application intercepts the reference counting calls and tries to detect invalid behavior. It suports a filter-rule mechanism to let you trace only the objects you are interested in and it can be used together with gdb.

Note that if GObject has been compiled with --enable-debug=yes, it exports a trap variable

static volatile GObject *g_trap_object_ref;

If set to a non-NULL value, g_object_ref() and g_object_unref() will be intercepted when called with that value.


Abstract Base Classes

GtkBin — A container with just one child
GtkBox — Base class for box containers
GtkButtonBox — Base class for GtkHButtonBox and GtkVButtonBox
GtkContainer — Base class for widgets which contain other widgets
GtkItem — Abstract base class for GtkMenuItem, GtkListItem and GtkTreeItem
GtkMisc — Base class for widgets with alignments and padding
GtkObject — The base class of the GTK+ type hierarchy
GtkPaned — Base class for widgets with two adjustable panes
GtkRange — Base class for widgets which visualize an adjustment
GtkScale — Base class for GtkHScale and GtkVScale
GtkScrollbar — Base class for GtkHScrollbar and GtkVScrollbar
GtkSeparator — Base class for GtkHSeparator and GtkVSeparator
GtkWidget — Base class for all widgets
GtkIMContext — Base class for input method contexts


Action-based menus and toolbars

GtkUIManager — Constructing menus and toolbars from an XML description
GtkActionGroup — A group of actions
GtkAction — An action which can be triggered by a menu or toolbar item
GtkToggleAction — An action which can be toggled between two states
GtkRadioAction — An action of which only one in a group can be active


Buttons and Toggles

GtkButton — A widget that creates a signal when clicked on
GtkCheckButton — Create widgets with a discrete toggle button
GtkRadioButton — A choice from multiple check buttons
GtkToggleButton — Create buttons which retain their state
GtkLinkButton — Create buttons bound to a URL


Object Hierarchy

    GObject
        GInitiallyUnowned
            GtkObject
                GtkWidget
                    GtkContainer
                        GtkBin
                            GtkWindow
                                GtkDialog
                                    GtkAboutDialog
                                    GtkColorSelectionDialog
                                    GtkFileChooserDialog
                                    GtkFileSelection
                                    GtkFontSelectionDialog
                                    GtkInputDialog
                                    GtkMessageDialog
                                    GtkPageSetupUnixDialog
                                    GtkPrintUnixDialog
                                    GtkRecentChooserDialog
                                GtkAssistant
                                GtkPlug
                            GtkAlignment
                            GtkFrame
                                GtkAspectFrame
                            GtkButton
                                GtkToggleButton
                                    GtkCheckButton
                                        GtkRadioButton
                                GtkColorButton
                                GtkFontButton
                                GtkLinkButton
                                GtkOptionMenu
                            GtkItem
                                GtkMenuItem
                                    GtkCheckMenuItem
                                        GtkRadioMenuItem
                                    GtkImageMenuItem
                                    GtkSeparatorMenuItem
                                    GtkTearoffMenuItem
                                GtkListItem
                                GtkTreeItem
                            GtkComboBox
                                GtkComboBoxEntry
                            GtkEventBox
                            GtkExpander
                            GtkHandleBox
                            GtkToolItem
                                GtkToolButton
                                    GtkMenuToolButton
                                    GtkToggleToolButton
                                        GtkRadioToolButton
                                GtkSeparatorToolItem
                            GtkScrolledWindow
                            GtkViewport
                        GtkBox
                            GtkButtonBox
                                GtkHButtonBox
                                GtkVButtonBox
                            GtkVBox
                                GtkColorSelection
                                GtkFileChooserWidget
                                GtkFontSelection
                                GtkGammaCurve
                                GtkRecentChooserWidget
                            GtkHBox
                                GtkCombo
                                GtkFileChooserButton
                                GtkStatusbar
                        GtkCList
                            GtkCTree
                        GtkFixed
                        GtkPaned
                            GtkHPaned
                            GtkVPaned
                        GtkIconView
                        GtkLayout
                        GtkList
                        GtkMenuShell
                            GtkMenuBar
                            GtkMenu
                                GtkRecentChooserMenu
                        GtkNotebook
                        GtkSocket
                        GtkTable
                        GtkTextView
                        GtkToolbar
                        GtkTree
                        GtkTreeView
                    GtkMisc
                        GtkLabel
                            GtkAccelLabel
                            GtkTipsQuery
                        GtkArrow
                        GtkImage
                        GtkPixmap
                    GtkCalendar
                    GtkCellView
                    GtkDrawingArea
                        GtkCurve
                    GtkEntry
                        GtkSpinButton
                    GtkRuler
                        GtkHRuler
                        GtkVRuler
                    GtkRange
                        GtkScale
                            GtkHScale
                            GtkVScale
                        GtkScrollbar
                            GtkHScrollbar
                            GtkVScrollbar
                    GtkSeparator
                        GtkHSeparator
                        GtkVSeparator
                    GtkInvisible
                    GtkOldEditable
                        GtkText
                    GtkPreview
                    GtkProgress
                        GtkProgressBar
                GtkAdjustment
                GtkCellRenderer
                    GtkCellRendererText
                        GtkCellRendererAccel
                        GtkCellRendererCombo
                        GtkCellRendererSpin
                    GtkCellRendererPixbuf
                    GtkCellRendererProgress
                    GtkCellRendererToggle
                GtkFileFilter
                GtkItemFactory
                GtkTooltips
                GtkTreeViewColumn
                GtkRecentFilter
        GtkAccelGroup
        GtkAccelMap
        AtkObject
            GtkAccessible
        GtkAction
            GtkToggleAction
                GtkRadioAction
        GtkActionGroup
        GtkClipboard
        GtkEntryCompletion
        GtkIconFactory
        GtkIconTheme
        GtkIMContext
            GtkIMContextSimple
            GtkIMMulticontext
        GtkListStore
        GtkPageSetup
        GtkPrinter
        GtkPrintContext
        GtkPrintJob
        GtkPrintOperation
        GtkPrintSettings
        GtkRcStyle
        GtkRecentManager
        GtkSettings
        GtkSizeGroup
        GtkStatusIcon
        GtkStyle
        GtkTextBuffer
        GtkTextChildAnchor
        GtkTextMark
        GtkTextTag
        GtkTextTagTable
        GtkTreeModelFilter
        GtkTreeModelSort
        GtkTreeSelection
        GtkTreeStore
        GtkUIManager
        GtkWindowGroup
        GtkPrintBackend
    GInterface
        GtkCellEditable
        GtkCellLayout
        GtkEditable
        GtkFileChooser
        GtkTreeModel
        GtkTreeDragSource
        GtkTreeDragDest
        GtkTreeSortable
        GtkPrintOperationPreview
        GtkRecentChooser


Prev Up Home GTK+ Reference Manual Next

Widget Gallery


Use GdkEventExpose.region

Why. The region field of GdkEventExpose allows you to redraw less than the traditional GdkEventRegion.area.

In GTK+ 1.x, the GdkEventExpose structure only had an area field to let you determine the region that you needed to redraw. In GTK+ 2.x, this field exists for compatibility and as a simple interface. However, there is also a region field which contains a fine-grained region. The area field is simply the bounding rectangle of the region.

Widgets that are very expensive to re-render, such as an image editor, may prefer to use the GdkEventExpose.region field to paint as little as possible. Widgets that just use a few drawing primitives, such as labels and buttons, may prefer to use the traditional GdkEventExpose.area field for simplicity.

Regions have an internal representation that is accessible as a list of rectangles. To turn the GdkEventExpose.region field into such a list, use gdk_region_get_rectangles():

static gboolean
my_widget_expose_event_handler (GtkWidget *widget, GdkEventExpose *event)
{
  GdkRectangle *rects;
  int n_rects;
  int i;

  gdk_region_get_rectangles (event->region, &rects, &n_rects);

  for (i = 0; i < n_rects; i++)
    {
      /* Repaint rectangle: (rects[i].x, rects[i].y),
       *                    (rects[i].width, rects[i].height)
       */
    }

  g_free (rects);

  return FALSE;
}


Test for modifier keys correctly

Why. With gtk_accelerator_get_default_mod_mask() you can test for modifier keys reliably; this way your key event handlers will work correctly even if NumLock or CapsLock are activated.

In a GdkEventKey, the state field is a bit mask which indicates the modifier state at the time the key was pressed. Modifiers are keys like Control and NumLock. When implementing a GtkWidget::key_press_event handler, you should use gtk_accelerator_get_default_mod_mask() to test against modifier keys. This function returns a bit mask which encompasses all the modifiers which the user may be actively pressing, such as Control, Shift, and Alt, but ignores "inocuous" modifiers such as NumLock and CapsLock.

Say you want to see if Control-F10 was pressed. Doing a simple test like event->keysym == GDK_F10 && event->state == GDK_CONTROL_MASK is not enough. If CapsLock is pressed, then event->state will be equal to GDK_CONTROL_MASK | GDK_LOCK_MASK, and the simple test will fail. By taking the logical-and of event->state and gtk_accelerator_get_default_mod_mask(), you can ignore the modifiers which are not actively pressed by the user at the same time as the base key.

The following example correctly tests for Control-F10 being pressed.

static gboolean
my_widget_key_press_event_handler (GtkWidget *widget, GdkEventKey *event)
{
  guint modifiers;

  modifiers = gtk_accelerator_get_default_mod_mask ();

  if (event->keysym == GDK_F10
      && (event->state & modifiers) == GDK_CONTROL_MASK)
    {
      g_print ("Control-F10 was pressed\n");
      return TRUE;
    }

  return FALSE;
}


Use named icons

Why. Named icons automatically adapt to theme changes, giving your application a much more integrated appearance.

Since GTK+ 2.6, named icons can be used for window icons (see gtk_window_set_icon_name()) and images (see gtk_image_set_icon_name()). In GTK+ 2.8, you can also use named icons for drag-and-drop (see gtk_drag_source_set_icon_name()) and in treeview cells (see the icon_name property of GtkCellRendererPixbuf).


Decorating the assistant pages

To decorate your assistant pages, GtkAssistant provides similar functions to GnomeDruid, so you have to transform code like this:

gnome_druid_page_edge_set_title (GNOME_DRUID_PAGE_EDGE (page), "Welcome");
gnome_druid_page_edge_set_logo (GNOME_DRUID_PAGE_EDGE (page), logo_pixbuf);
gnome_druid_page_edge_set_watermark (GNOME_DRUID_PAGE_EDGE (page), watermark_pixbuf);

Into this:

gtk_assistant_set_page_title (GTK_ASSISTANT (assistant), page_widget, "Welcome");
gtk_assistant_set_page_header_image (GTK_ASSISTANT (assistant), page_widget, logo_pixbuf);
gtk_assistant_set_page_side_image (GTK_ASSISTANT (assistant), page_widget, watermark_pixbuf);

Where page_widget is the widget used as a page.


Deprecated

GtkCList — A multi-columned scrolling list widget
GtkCTree — A widget displaying a hierarchical tree
GtkCombo — A text entry field with a dropdown list
GtkItemFactory — A factory for menus
GtkList — Widget for packing a list of selectable items
GtkListItem — An item in a GtkList
GtkOldEditable — Base class for text-editing widgets
GtkOptionMenu — A widget used to choose from a list of valid choices
GtkPixmap — A widget displaying a graphical image or icon
GtkPreview — A widget to display RGB or grayscale data
GtkProgress — Base class for GtkProgressBar
GtkText — A text widget
GtkTipsQuery — Displays help about widgets in the user interface
GtkTree — A tree widget
GtkTreeItem — The widget used for items in a GtkTree


Display Widgets

GtkAccelLabel — A label which displays an accelerator key on the right of the text
GtkImage — A widget displaying an image
GtkLabel — A widget that displays a small to medium amount of text
GtkProgressBar — A widget which indicates progress visually
GtkStatusbar — Report messages of minor importance to the user
GtkStatusIcon — Display an icon in the system tray


Glossary

allocation

The final size of a widget within its parent. For example, a widget may request a minimum size of 20×20 pixels, but its parent may decide to allocate 50×20 pixels for it instead.

See Also requisition .

bin

A container that can hold at most one child widget. The base class for bins is GtkBin.

See Also container .

child

A container's child is a widget contained inside it.

column

GTK+ contains several widgets which display data in columns, e.g. the GtkTreeView. These view columns in the tree view are represented by GtkTreeViewColumn objects inside GTK+. They should not be confused with model columns which are used to organize the data in tree models.

See Also model-view widget.

container

A widget that contains other widgets; in that case, the container is the parent of the child widgets. Some containers don't draw anything on their own, but rather just organize their children's geometry; for example, GtkVBox lays out its children vertically without painting anything on its own. Other containers include decorative elements; for example, GtkFrame contains the frame's child and a label in addition to the shaded frame it draws. The base class for containers is GtkContainer.

See Also widget geometry .

display

GDK inherited the concept of display from the X window system, which considers a display to be the combination of a keyboard, a pointing device and one or more screens. Applications open a display to show windows and interact with the user. In GDK, a display is represented by a GdkDisplay.

event

Events are the way in which GDK informs GTK+ about external events like pointer motion, button clicks, key presses, etc.

geometry

A widget's position and size. Within its parent, this is called the widget's allocation.

mapping

This is the step in a widget's life cycle where it actually shows the GdkWindows it created when it was realized. When a widget is mapped, it must turn on its GTK_MAPPED flag.

Note that due to the asynchronous nature of the X window system, a widget's window may not appear on the screen immediatly after one calls gdk_window_show(): you must wait for the corresponding map event to be received. You can do this with the GtkWidget::map-event signal.

model column

A column in a tree model, holding data of a certain type. The types which can be stored in the columns of a model have to be specified when the model is constructed, see e.g. gtk_list_store_new().

See Also view column .

model-view widget

These widgets follow the well-known model-view pattern, which separates the data (the model) to be displayed from the component which does the actual visualization (the view). Examples of this pattern in GTK+ are the GtkTreeView/GtkTreeModel and GtkTextView/GtkTextBuffer

One important advantage of this pattern is that it is possible to display the same model in multiple views; another one that the separation of the model allows a great deal of flexibility, as demonstrated by e.g. GtkTreeModelSort or GtkTreeModelFilter.

no-window widget

A widget that does not have a GdkWindow of its own on which to draw its contents, but rather shares its parent's. Such a widget has the GTK_NO_WINDOW flag set, and can be tested with the GTK_WIDGET_NO_WINDOW() macro.

parent

A widget's parent is the container inside which it resides.

realization

This is the step in a widget's life cycle where it creates its own GdkWindow, or otherwise associates itself with its parent's GdkWindow. If the widget has its own window, then it must also attach a style to it. A widget becomes unrealized by destroying its associated GdkWindow. When a widget is realized, it must turn on its GTK_REALIZED flag.

Widgets that don't own the GdkWindow on which they draw are called no-window widgets. This can be tested with the GTK_WIDGET_NO_WINDOW() macro. Normally, these widgets draw on their parent's GdkWindow.

Note that when a widget creates a window in its ::realize() handler, it does not actually show the window. That is, the window's structure is just created in memory. The widget actually shows the window when it gets mapped.

requisition

The size requisition of a widget is the minimum amount of space it requests from its parent. Once the parent computes the widget's final size, it gives it its size allocation.

See Also allocation .

screen

GDK inherited the concept of screen from the X window system, which considers a screen to be a rectangular area, on which applications may place their windows. Screens under X may have quite dissimilar visuals. Each screen can stretch across multiple physical monitors.

In GDK, screens are represented by GdkScreen objects.

style

A style encapsulates what GTK+ needs to know in order to draw a widget. Styles can be modified with resource files.

toplevel

A widget that does not require a parent container. The only toplevel widgets in GTK+ are GtkWindow and widgets derived from it.

See Also container .

unmap

See mapping.

unrealize

See realization.

view column

A displayed column in a tree view, represented by a GtkTreeViewColumn object.

See Also model column .

visual

A visual describes how color information is stored in pixels. A screen may support multiple visuals. On modern hardware, the most common visuals are truecolor visuals, which store a fixed number of bits (typically 8) for the red, green and blue components of a color.

On ancient hardware, one may still meet indexed visuals, which store color information as an index into a color map, or even monochrome visuals.

widget

A control in a graphical user interface. Widgets can draw themselves and process events from the mouse and keyboard. Widget types include buttons, menus, text entry lines, and lists. Widgets can be arranged into containers, and these take care of assigning the geometry of the widgets: every widget thus has a parent except those widgets which are toplevels. The base class for widgets is GtkWidget.

See Also container .


Part I. GTK+ Overview

GTK+ is a library for creating graphical user interfaces. It works on many UNIX-like platforms, Windows, and on framebuffer devices. GTK+ is released under the GNU Library General Public License (GNU LGPL), which allows for flexible licensing of client applications. GTK+ has a C-based object-oriented architecture that allows for maximum flexibility. Bindings for other languages have been written, including C++, Objective-C, Guile/Scheme, Perl, Python, TOM, Ada95, Free Pascal, and Eiffel.

GTK+ depends on the following libraries:

GLib | A general-purpose utility library, not specific to graphical user interfaces. GLib provides many useful data types, macros, type conversions, string utilities, file utilities, a main loop abstraction, and so on.
Pango | Pango is a library for internationalized text handling. It centers around the PangoLayout object, representing a paragraph of text. Pango provides the engine for GtkTextView, GtkLabel, GtkEntry, and other widgets that display text.
ATK | ATK is the Accessibility Toolkit. It provides a set of generic interfaces allowing accessibility technologies to interact with a graphical user interface. For example, a screen reader uses ATK to discover the text in an interface and read it to blind users. GTK+ widgets have built-in support for accessibility using the ATK framework.
GdkPixbuf | This is a small library which allows you to create GdkPixbuf ("pixel buffer") objects from image data or image files. Use a GdkPixbuf in combination with GtkImage to display images.
GDK | GDK is the abstraction layer that allows GTK+ to support multiple windowing systems. GDK provides drawing and window system facilities on X11, Windows, and the Linux framebuffer device.
GTK+ | The GTK+ library itself contains widgets, that is, GUI components such as GtkButton or GtkTextView.


Accelerator Maps

Accelerator Maps — Loadable keyboard accelerator specifications

Synopsis

#include <gtk/gtk.h>

                    GtkAccelMap;
void                (*GtkAccelMapForeach)               (gpointer data,
                                                         const gchar *accel_path,
                                                         guint accel_key,
                                                         GdkModifierType accel_mods,
                                                         gboolean changed);
void                gtk_accel_map_add_entry             (const gchar *accel_path,
                                                         guint accel_key,
                                                         GdkModifierType accel_mods);
gboolean            gtk_accel_map_lookup_entry          (const gchar *accel_path,
                                                         GtkAccelKey *key);
gboolean            gtk_accel_map_change_entry          (const gchar *accel_path,
                                                         guint accel_key,
                                                         GdkModifierType accel_mods,
                                                         gboolean replace);
void                gtk_accel_map_load                  (const gchar *file_name);
void                gtk_accel_map_save                  (const gchar *file_name);
void                gtk_accel_map_foreach               (gpointer data,
                                                         GtkAccelMapForeach foreach_func);
void                gtk_accel_map_load_fd               (gint fd);
void                gtk_accel_map_save_fd               (gint fd);
void                gtk_accel_map_load_scanner          (GScanner *scanner);
void                gtk_accel_map_add_filter            (const gchar *filter_pattern);
void                gtk_accel_map_foreach_unfiltered    (gpointer data,
                                                         GtkAccelMapForeach foreach_func);
GtkAccelMap*        gtk_accel_map_get                   (void);
void                gtk_accel_map_lock_path             (const gchar *accel_path);
void                gtk_accel_map_unlock_path           (const gchar *accel_path);

Object Hierarchy

  GObject
   +----GtkAccelMap

Signals

  "changed"                                        : Run Last / Has Details

Description

Details

GtkAccelMap

typedef struct _GtkAccelMap GtkAccelMap;

GtkAccelMapForeach ()

void                (*GtkAccelMapForeach)               (gpointer data,
                                                         const gchar *accel_path,
                                                         guint accel_key,
                                                         GdkModifierType accel_mods,
                                                         gboolean changed);

data :
accel_path :
accel_key :
accel_mods :
changed :

gtk_accel_map_add_entry ()

void                gtk_accel_map_add_entry             (const gchar *accel_path,
                                                         guint accel_key,
                                                         GdkModifierType accel_mods);

Registers a new accelerator with the global accelerator map. This function should only be called once per accel_path with the canonical accel_key and accel_mods for this path. To change the accelerator during runtime programatically, use gtk_accel_map_change_entry(). The accelerator path must consist of "<WINDOWTYPE>/Category1/Category2/.../Action", where <WINDOWTYPE> should be a unique application-specific identifier, that corresponds to the kind of window the accelerator is being used in, e.g. "Gimp-Image", "Abiword-Document" or "Gnumeric-Settings". The Category1/.../Action portion is most appropriately chosen by the action the accelerator triggers, i.e. for accelerators on menu items, choose the item's menu path, e.g. "File/Save As", "Image/View/Zoom" or "Edit/Select All". So a full valid accelerator path may look like: "<Gimp-Toolbox>/File/Dialogs/Tool Options...".

accel_path : | valid accelerator path
accel_key : | the accelerator key
accel_mods : | the accelerator modifiers

gtk_accel_map_lookup_entry ()

gboolean            gtk_accel_map_lookup_entry          (const gchar *accel_path,
                                                         GtkAccelKey *key);

Looks up the accelerator entry for accel_path and fills in key.

accel_path : | a valid accelerator path
key : | the accelerator key to be filled in (optional)
Returns : | TRUE if accel_path is known, FALSE otherwise

gtk_accel_map_change_entry ()

gboolean            gtk_accel_map_change_entry          (const gchar *accel_path,
                                                         guint accel_key,
                                                         GdkModifierType accel_mods,
                                                         gboolean replace);

Changes the accel_key and accel_mods currently associated with accel_path. Due to conflicts with other accelerators, a change may not always be possible, replace indicates whether other accelerators may be deleted to resolve such conflicts. A change will only occur if all conflicts could be resolved (which might not be the case if conflicting accelerators are locked). Successful changes are indicated by a TRUE return value.

accel_path : | a valid accelerator path
accel_key : | the new accelerator key
accel_mods : | the new accelerator modifiers
replace : | TRUE if other accelerators may be deleted upon conflicts
Returns : | TRUE if the accelerator could be changed, FALSE otherwise

gtk_accel_map_load ()

void                gtk_accel_map_load                  (const gchar *file_name);

Parses a file previously saved with gtk_accel_map_save() for accelerator specifications, and propagates them accordingly.

file_name : a file containing accelerator specifications, in the GLib file name encoding

gtk_accel_map_save ()

void                gtk_accel_map_save                  (const gchar *file_name);

Saves current accelerator specifications (accelerator path, key and modifiers) to file_name. The file is written in a format suitable to be read back in by gtk_accel_map_load().

file_name : the name of the file to contain accelerator specifications, in the GLib file name encoding

gtk_accel_map_foreach ()

void                gtk_accel_map_foreach               (gpointer data,
                                                         GtkAccelMapForeach foreach_func);

Loops over the entries in the accelerator map whose accel path doesn't match any of the filters added with gtk_accel_map_add_filter(), and execute foreach_func on each. The signature of foreach_func is that of GtkAccelMapForeach, the changed parameter indicates whether this accelerator was changed during runtime (thus, would need saving during an accelerator map dump).

data : | data to be passed into foreach_func
foreach_func : | function to be executed for each accel map entry which is not filtered out

gtk_accel_map_load_fd ()

void                gtk_accel_map_load_fd               (gint fd);

Filedescriptor variant of gtk_accel_map_load().

Note that the file descriptor will not be closed by this function.

fd : a valid readable file descriptor

gtk_accel_map_save_fd ()

void                gtk_accel_map_save_fd               (gint fd);

Filedescriptor variant of gtk_accel_map_save().

Note that the file descriptor will not be closed by this function.

fd : a valid writable file descriptor

gtk_accel_map_load_scanner ()

void                gtk_accel_map_load_scanner          (GScanner *scanner);

GScanner variant of gtk_accel_map_load().

scanner : a GScanner which has already been provided with an input file

gtk_accel_map_add_filter ()

void                gtk_accel_map_add_filter            (const gchar *filter_pattern);

Adds a filter to the global list of accel path filters.

Accel map entries whose accel path matches one of the filters are skipped by gtk_accel_map_foreach().

This function is intended for GTK+ modules that create their own menus, but don't want them to be saved into the applications accelerator map dump.

filter_pattern : a pattern (see GPatternSpec)

gtk_accel_map_foreach_unfiltered ()

void                gtk_accel_map_foreach_unfiltered    (gpointer data,
                                                         GtkAccelMapForeach foreach_func);

Loops over all entries in the accelerator map, and execute foreach_func on each. The signature of foreach_func is that of GtkAccelMapForeach, the changed parameter indicates whether this accelerator was changed during runtime (thus, would need saving during an accelerator map dump).

data : | data to be passed into foreach_func
foreach_func : | function to be executed for each accel map entry

gtk_accel_map_get ()

GtkAccelMap*        gtk_accel_map_get                   (void);

Gets the singleton global GtkAccelMap object. This object is useful only for notification of changes to the accelerator map via the ::changed signal; it isn't a parameter to the other accelerator map functions.

Returns : the global GtkAccelMap object

Since 2.4

gtk_accel_map_lock_path ()

void                gtk_accel_map_lock_path             (const gchar *accel_path);

Locks the given accelerator path. If the accelerator map doesn't yet contain an entry for accel_path, a new one is created.

Locking an accelerator path prevents its accelerator from being changed during runtime. A locked accelerator path can be unlocked by gtk_accel_map_unlock_path(). Refer to gtk_accel_map_change_entry() for information about runtime accelerator changes.

If called more than once, accel_path remains locked until gtk_accel_map_unlock_path() has been called an equivalent number of times.

Note that locking of individual accelerator paths is independent from locking the GtkAccelGroup containing them. For runtime accelerator changes to be possible both the accelerator path and its GtkAccelGroup have to be unlocked.

accel_path : a valid accelerator path

Since 2.4

gtk_accel_map_unlock_path ()

void                gtk_accel_map_unlock_path           (const gchar *accel_path);

Undoes the last call to gtk_accel_map_lock_path() on this accel_path. Refer to gtk_accel_map_lock_path() for information about accelerator path locking.

accel_path : a valid accelerator path

Since 2.4

Signal Details

The "changed" signal

void                user_function                      (GtkAccelMap    *object,
                                                        gchar          *accel_path,
                                                        guint           accel_key,
                                                        GdkModifierType accel_mods,
                                                        gpointer        user_data)       : Run Last / Has Details

Notifies of a change in the global accelerator map. The path is also used as the detail for the signal, so it is possible to connect to changed::accel_path.

object : | the global accel map object
accel_path : | the path of the accelerator that changed
accel_key : | the key value for the new accelerator
accel_mods : | the modifier mask for the new accelerator
user_data : | user data set when the signal handler was connected.

Since 2.4


Bindings

Bindings — Key bindings for individual widgets

Synopsis

#include <gtk/gtk.h>

                    GtkBindingSet;
                    GtkBindingEntry;
                    GtkBindingSignal;
                    GtkBindingArg;
GtkBindingSet*      gtk_binding_set_new                 (const gchar *set_name);
GtkBindingSet*      gtk_binding_set_by_class            (gpointer object_class);
GtkBindingSet*      gtk_binding_set_find                (const gchar *set_name);
gboolean            gtk_bindings_activate               (GtkObject *object,
                                                         guint keyval,
                                                         GdkModifierType modifiers);
gboolean            gtk_bindings_activate_event         (GtkObject *object,
                                                         GdkEventKey *event);
gboolean            gtk_binding_set_activate            (GtkBindingSet *binding_set,
                                                         guint keyval,
                                                         GdkModifierType modifiers,
                                                         GtkObject *object);
#define             gtk_binding_entry_add
void                gtk_binding_entry_clear             (GtkBindingSet *binding_set,
                                                         guint keyval,
                                                         GdkModifierType modifiers);
void                gtk_binding_entry_add_signal        (GtkBindingSet *binding_set,
                                                         guint keyval,
                                                         GdkModifierType modifiers,
                                                         const gchar *signal_name,
                                                         guint n_args,
                                                         ...);
void                gtk_binding_set_add_path            (GtkBindingSet *binding_set,
                                                         GtkPathType path_type,
                                                         const gchar *path_pattern,
                                                         GtkPathPriorityType priority);
void                gtk_binding_entry_remove            (GtkBindingSet *binding_set,
                                                         guint keyval,
                                                         GdkModifierType modifiers);
void                gtk_binding_entry_add_signall       (GtkBindingSet *binding_set,
                                                         guint keyval,
                                                         GdkModifierType modifiers,
                                                         const gchar *signal_name,
                                                         GSList *binding_args);
guint               gtk_binding_parse_binding           (GScanner *scanner);

Description

Details

GtkBindingSet

typedef struct {
  gchar			*set_name;
  gint			 priority;
  GSList		*widget_path_pspecs;
  GSList		*widget_class_pspecs;
  GSList		*class_branch_pspecs;
  GtkBindingEntry	*entries;
  GtkBindingEntry	*current;
  guint                  parsed : 1; /* From RC content */
} GtkBindingSet;

GtkBindingEntry

typedef struct {
  /* key portion
   */
  guint			 keyval;
  GdkModifierType	 modifiers;

  GtkBindingSet		*binding_set;
  guint			destroyed : 1;
  guint			in_emission : 1;
  GtkBindingEntry	*set_next;
  GtkBindingEntry	*hash_next;
  GtkBindingSignal	*signals;
} GtkBindingEntry;

GtkBindingSignal

typedef struct {
  GtkBindingSignal	*next;
  gchar 		*signal_name;
  guint			 n_args;
  GtkBindingArg		*args;
} GtkBindingSignal;

GtkBindingArg

typedef struct {
  GType		 arg_type;
  union {
    glong	 long_data;
    gdouble	 double_data;
    gchar	*string_data;
  } d;
} GtkBindingArg;

gtk_binding_set_new ()

GtkBindingSet*      gtk_binding_set_new                 (const gchar *set_name);

set_name :
Returns :

gtk_binding_set_by_class ()

GtkBindingSet*      gtk_binding_set_by_class            (gpointer object_class);

object_class :
Returns :

gtk_binding_set_find ()

GtkBindingSet*      gtk_binding_set_find                (const gchar *set_name);

set_name :
Returns :

gtk_bindings_activate ()

gboolean            gtk_bindings_activate               (GtkObject *object,
                                                         guint keyval,
                                                         GdkModifierType modifiers);

object :
keyval :
modifiers :
Returns :

gtk_bindings_activate_event ()

gboolean            gtk_bindings_activate_event         (GtkObject *object,
                                                         GdkEventKey *event);

Looks up key bindings for object to find one matching event, and if one was found, activate it.

object : | a GtkObject (generally must be a widget)
event : | a GdkEventKey
Returns : | TRUE if a matching key binding was found

gtk_binding_set_activate ()

gboolean            gtk_binding_set_activate            (GtkBindingSet *binding_set,
                                                         guint keyval,
                                                         GdkModifierType modifiers,
                                                         GtkObject *object);

binding_set :
keyval :
modifiers :
object :
Returns :

gtk_binding_entry_add

#define	 gtk_binding_entry_add		gtk_binding_entry_clear

gtk_binding_entry_clear ()

void                gtk_binding_entry_clear             (GtkBindingSet *binding_set,
                                                         guint keyval,
                                                         GdkModifierType modifiers);

binding_set :
keyval :
modifiers :

gtk_binding_entry_add_signal ()

void                gtk_binding_entry_add_signal        (GtkBindingSet *binding_set,
                                                         guint keyval,
                                                         GdkModifierType modifiers,
                                                         const gchar *signal_name,
                                                         guint n_args,
                                                         ...);

binding_set :
keyval :
modifiers :
signal_name :
n_args :
... :

gtk_binding_set_add_path ()

void                gtk_binding_set_add_path            (GtkBindingSet *binding_set,
                                                         GtkPathType path_type,
                                                         const gchar *path_pattern,
                                                         GtkPathPriorityType priority);

binding_set :
path_type :
path_pattern :
priority :

gtk_binding_entry_remove ()

void                gtk_binding_entry_remove            (GtkBindingSet *binding_set,
                                                         guint keyval,
                                                         GdkModifierType modifiers);

binding_set :
keyval :
modifiers :

gtk_binding_entry_add_signall ()

void                gtk_binding_entry_add_signall       (GtkBindingSet *binding_set,
                                                         guint keyval,
                                                         GdkModifierType modifiers,
                                                         const gchar *signal_name,
                                                         GSList *binding_args);

binding_set :
keyval :
modifiers :
signal_name :
binding_args :

gtk_binding_parse_binding ()

guint               gtk_binding_parse_binding           (GScanner *scanner);

scanner :
Returns :


Compiling the GTK+ libraries

Compiling the GTK+ Libraries — How to compile GTK+ itself

Building GTK+ on UNIX-like systems

This chapter covers building and installing GTK+ on UNIX and UNIX-like systems such as Linux. Compiling GTK+ on Microsoft Windows is different in detail and somewhat more difficult to get going since the necessary tools aren't included with the operating system.

Before we get into the details of how to compile GTK+, we should mention that in many cases, binary packages of GTK+ prebuilt for your operating system will be available, either from your operating system vendor or from independent sources. If such a set of packages is available, installing it will get you programming wih GTK+ much faster than building it yourself. In fact, you may well already have GTK+ installed on your system already.

On UNIX-like systems GTK+ uses the standard GNU build system, using autoconf for package configuration and resolving portability issues, automake for building makefiles that comply with the GNU Coding Standards, and libtool for building shared libraries on multiple platforms.

If you are building GTK+ from the distributed source packages, then won't need these tools installed; the necessary pieces of the tools are already included in the source packages. But it's useful to know a bit about how packages that use these tools work. A source package is distributed as a tar.gz file which you unpack into a directory full of the source files as follows:

      tar xvfz gtk+-2.0.0.tar.gz

In the toplevel of the directory that is created, there will be a shell script called configure which you then run to take the template makefiles called Makefile.in in the package and create makefiles customized for your operating system. The configure script can be passed various command line arguments to determine how the package is built and installed. The most commonly useful argument is the --prefix argument which determines where the package is installed. To install a package in /opt/gtk you would run configure as:

      ./configure --prefix=/opt/gtk

A full list of options can be found by running configure with the --help argument. In general, the defaults are right and should be trusted. After you've run configure, you then run the make command to build the package and install it.

      make
      make install

If you don't have permission to write to the directory you are installing in, you may have to change to root temporarily before running make install. Also, if you are installing in a system directory, on some systems (such as Linux), you will need to run ldconfig after make install so that the newly installed libraries will be found.

Several environment variables are useful to pass to set before running configure. CPPFLAGS contains options to pass to the C compiler, and is used to tell the compiler where to look for include files. The LDFLAGS variable is used in a similar fashion for the linker. Finally the PKG_CONFIG_PATH environment variable contains a search path that pkg-config (see below) uses when looking for for file describing how to compile programs using different libraries. If you were installing GTK+ and it's dependencies into /opt/gtk, you might want to set these variables as:

      CPPFLAGS="-I/opt/gtk/include"
      LDFLAGS="-L/opt/gtk/lib"
      PKG_CONFIG_PATH="/opt/gtk/lib/pkgconfig"
      export CPPFLAGS LDFLAGS PKG_CONFIG_PATH

You may also need to set the LD_LIBRARY_PATH environment variable so the systems dynamic linker can find the newly installed libraries, and the PATH environment program so that utility binaries installed by the various libraries will be found.

      LD_LIBRARY_PATH="/opt/gtk/lib"
      PATH="/opt/gtk/bin:$PATH"
      export LD_LIBRARY_PATH PATH

Dependencies

Before you can compile the GTK+ widget toolkit, you need to have various other tools and libraries installed on your system. The two tools needed during the build process (as differentiated from the tools used in when creating GTK+ mentioned above such as autoconf) are pkg-config and GNU make.

  • pkg-config is a tool for tracking the compilation flags needed for libraries that are used by the GTK+ libraries. (For each library, a small .pc text file is installed in a standard location that contains the compilation flags needed for that library along with version number information.) The version of pkg-config needed to build GTK+ is mirrored in the dependencies directory on the GTK+ FTP site.

  • The GTK+ makefiles will mostly work with different versions of make, however, there tends to be a few incompatibilities, so the GTK+ team recommends installing GNU make if you don't already have it on your system and using it. (It may be called gmake rather than make.)

Three of the libraries that GTK+ depends on are maintained by by the GTK+ team: GLib, Pango, and ATK. Other libraries are maintained separately.

  • The GLib library provides core non-graphical functionality such as high level data types, Unicode manipulation, and an object and type system to C programs. It is available from the GTK+ FTP site.

  • Pango is a library for internationalized text handling. It is available from the GTK+ FTP site..

  • ATK is the Accessibility Toolkit. It provides a set of generic interfaces allowing accessibility technologies such as screen readers to interact with a graphical user interface. It is available from the GTK+ FTP site.

  • The GNU libiconv library is needed to build GLib if your system doesn't have the iconv() function for doing conversion between character encodings. Most modern systems should have iconv().

  • The libintl library from the GNU gettext package is needed if your system doesn't have the gettext() functionality for handling message translation databases.

  • The JPEG, PNG, and TIFF image loading libraries are needed to compile GTK+. You probably already have these libraries installed, but if not, the versions you need are available in the dependencies directory on the the GTK+ FTP site.. (Before installing these libraries from source, you should check if your operating system vendor has prebuilt packages of these libraries that you don't have installed.)

  • The libraries from the X window system are needed to build Pango and GTK+. You should already have these installed on your system, but it's possible that you'll need to install the development environment for these libraries that your operating system vendor provides.

  • The fontconfig library provides Pango with a standard way of locating fonts and matching them against font names.

  • Cairo is a graphics library that supports vector graphics and image compositing. Both Pango and GTK+ use cairo for much of their drawing.

Building and testing GTK+

First make sure that you have the necessary external dependencies installed: pkg-config, GNU make, the JPEG, PNG, and TIFF libraries, FreeType, and, if necessary, libiconv and libintl. To get detailed information about building these packages, see the documentation provided with the individual packages. On a Linux system, it's quite likely you'll have all of these installed already except for pkg-config.

Then build and install the GTK+ libraries in the order: GLib, Pango, ATK, then GTK+. For each library, follow the steps of configure, make, make install mentioned above. If you're lucky, this will all go smoothly, and you'll be ready to start compiling your own GTK+ applications. You can test your GTK+ installation by running the gtk-demo program that GTK+ installs.

If one of the configure scripts fails or running make fails, look closely at the error messages printed; these will often provide useful information as to what went wrong. When configure fails, extra information, such as errors that a test compilation ran into, is found in the file config.log. Looking at the last couple of hundred lines in this file will frequently make clear what went wrong. If all else fails, you can ask for help on the gtk-list mailing list. See Mailing lists and bug reports(3) for more information.

Extra Configuration Options

In addition to the normal options, the configure script for the GTK+ library supports a number of additional arguments. (Command line arguments for the other GTK+ libraries are described in the documentation distributed with the those libraries.)

configure [[--disable-modules] | [--enable-modules]] [[--with-included-loaders==LOADER1,LOADER2,...]] [[--enable-debug=[no|minimum|yes]]] [[--disable-visibility] | [--enable-visibility]] [[--disable-shm] | [--enable-shm]] [[--disable-xim] | [--enable-xim]] [[--disable-xim-inst] | [--enable-xim-inst]] [[--disable-xkb] | [--enable-xkb]] [[--disable-gtk-doc] | [--enable-gtk-doc]] [[--with-xinput=[no|yes]]] [[--with-gdktarget=[x11|linux-fb|win32]]] [[--disable-shadowfb] | [--enable-shadowfb]]

--disable-modules and --enable-modules. Normally GTK+ will try to build the GdkPixbuf image file format loaders as little shared libraries that are loaded on demand. The --disable-modules argument indicates that they should all be built statically into the GTK+ library instead. This is useful for people who need to produce statically-linked binaries. If neither --disable-modules nor --enable-modules is specified, then the configure script will try to auto-detect whether shared modules work on your system.

--with-included-loaders. This option allows you to specify which image loaders you want to include; for example, you might include only the PNG loader to create a smaller GdkPixbuf binary.

--enable-debug. Turns on various amounts of debugging support. Setting this to 'no' disables g_assert(), g_return_if_fail(), g_return_val_if_fail() and all cast checks between different object types. Setting it to 'minimum' disables only cast checks. Setting it to 'yes' enables runtime debugging. The default is 'minimum'. Note that 'no' is fast, but dangerous as it tends to destabilize even mostly bug-free software by changing the effect of many bugs from simple warnings into fatal crashes. Thus --enable-debug=no should not be used for stable releases of GTK+.

--disable-visibility and --enable-visibility. The option --disable-visibility turns off the use of ELF visibility attributes for linking optimizations. This makes sense while changing GTK+ itself, since the way in which GTK+ uses visibility attributes forces a full rebuild of all source files for any header modification.

--enable-explicit-deps and --disable-explicit-deps. If --enable-explicit-deps is specified then GTK+ will write the full set of libraries that GTK+ depends upon into its .pc files to be used when programs depending on GTK+ are linked. Otherwise, GTK+ only will include the GTK+ libraries themselves, and will depend on system library dependency facilities to bring in the other libraries. By default GTK+ will disable explicit dependencies unless it detects that they are needed on the system. (If you specify --enable-static to force building of static libraries, then explicit dependencies will be written since library dependencies don't work for static libraries.) Specifying --enable-explicit-deps or --enable-static can cause compatibility problems when libraries that GTK+ depends upon change their versions, and should be avoided if possible.

--disable-shm and --enable-shm. These options can be used to control whether GTK+ will use shared memory to communicate with the X server when possible. The default is 'yes'.

--disable-xim and --enable-xim. These options can be used to control whether GTK+ will be compiled with support for XIM. (The X Input Method extension, used for Japanese input.) The default is yes.

--disable-xim-inst and --enable-xim-inst. These options determine whether GTK+ will use the XIM instantiate callback. The default is 'yes', unless the host system is Solaris, where XRegisterIMInstantiateCallback() seems to cause a segfault.

--disable-xkb and --enable-xkb. By default the configure script will try to auto-detect whether the XKB extension is supported by the X libraries GTK+ is linked with. These options can be used to explicitly control whether GTK+ will support the XKB extension.

--disable-gtk-doc and --enable-gtk-doc. The gtk-doc package is used to generate the reference documentation included with GTK+. By default support for gtk-doc is disabled because it requires various extra dependencies to be installed. If you have gtk-doc installed and are modifying GTK+, you may want to enable gtk-doc support by passing in --enable-gtk-doc. If not enabled, pre-generated HTML files distributed with GTK+ will be installed.

--with-xinput. Controls whether GTK+ is built with support for the XInput extension. The XInput extension provides an interface to extended input devices such as graphics tablets. When this support is compiled in, specially written GTK+ programs can get access to subpixel positions, multiple simultaneous input devices, and extra "axes" provided by the device such as pressure and tilt information. This is only known to work well on XFree86 systems, though other systems do have this extension.

--with-gdktarget. Toggles between the supported backends for GDK. The default is x11, unless the platform is Windows, in which case the default is win32.

--disable-shadowfb and --enable-shadowfb. Toggles shadow framebuffer support for the linux-fb target, if selected.


Changes from 1.0 to 1.2

Changes from 1.0 to 1.2 — Incompatible changes made between version 1.0 and version 1.2

Incompatible changes from 1.0 to 1.2

  • GtkAcceleratorTable has been replaced with GtkAccelGroup.

  • GtkMenuFactory has been replaced with GtkItemFactory, although a version of GtkMenuFactory is currently still provided to ease the migration phase.

  • The GtkTypeInfo structures used in the gtk_*_type_init() functions have changed a bit, the old format:

          GtkTypeInfo bin_info =
      {
        "GtkBin",
        sizeof (GtkBin),
        sizeof (GtkBinClass),
        (GtkClassInitFunc) gtk_bin_class_init,
        (GtkObjectInitFunc) gtk_bin_init,
        (GtkArgSetFunc) NULL,
        (GtkArgGetFunc) NULL,
      };

    needs to be converted to:

          static const GtkTypeInfo bin_info =
      {
        "GtkBin",
        sizeof (GtkBin),
        sizeof (GtkBinClass),
        (GtkClassInitFunc) gtk_bin_class_init,
        (GtkObjectInitFunc) gtk_bin_init,
        /* reserved_1 */ NULL,
        /* reserved_2 */ NULL,
        (GtkClassInitFunc) NULL,
      };

    the GtkArgSetFunc and GtkArgGetFunc functions are not supported from the type system anymore, and you should make sure that your code only fills in these fields with NULL and doesn't use the deprecated function typedefs (GtkArgSetFunc) and (GtkArgGetFunc) anymore.

  • A number of GTK+ functions were renamed. For compatibility, gtkcompat.h #define's the old 1.0.x function names in terms of the new names. To assure your GTK+ program doesn't rely on outdated function variants, compile your program with -DGTK_DISABLE_COMPAT_H to disable the compatibility aliases. Here is the list of the old names and replacements:

    Old | Replacement
    gtk_accel_label_accelerator_width | gtk_accel_label_get_accel_width
    gtk_check_menu_item_set_state | gtk_check_menu_item_set_active
    gtk_container_border_width | gtk_container_set_border_width
    gtk_label_set | gtk_label_set_text
    gtk_notebook_current_page | gtk_notebook_get_current_page
    gtk_packer_configure | gtk_packer_set_child_packing
    gtk_paned_gutter_size | gtk_paned_set_gutter_size
    gtk_paned_handle_size | gtk_paned_set_handle_size
    gtk_scale_value_width | gtk_scale_get_value_width
    gtk_style_apply_default_pixmap | gtk_style_apply_default_background
    gtk_toggle_button_set_state | gtk_toggle_button_set_active
    gtk_window_position | gtk_window_set_position

    Note that gtk_style_apply_default_background() has an additional argument, set_bg. This parameter should be FALSE if the background is being set for a NO_WINDOW widget, otherwise TRUE.

  • During the development phase of the 1.1.x line of GTK+ certain functions were deprecated and later removed. Functions affected are:

    Removed | Replacement
    gtk_clist_set_border | gtk_clist_set_shadow_type
    gtk_container_block_resize | gtk_container_set_resize_mode
    gtk_container_unblock_resize | gtk_container_set_resize_mode
    gtk_container_need_resize | gtk_container_check_resize
    gtk_ctree_show_stub | gtk_ctree_set_show_stub
    gtk_ctree_set_reorderable | gtk_clist_set_reorderable
    gtk_ctree_set_use_drag_icons | gtk_clist_set_use_drag_icons
    gtk_entry_adjust_scroll -
    gtk_object_class_add_user_signal | gtk_object_class_user_signal_new
    gtk_preview_put_row | gtk_preview_put
    gtk_progress_bar_construct | gtk_progress_set_adjustment
    gtk_scrolled_window_construct | gtk_scrolled_window_set_{h|v}adjustment
    gtk_spin_button_construct | gtk_spin_button_configure
    gtk_widget_thaw_accelerators | gtk_widget_unlock_accelerators
    gtk_widget_freeze_accelerators | gtk_widget_lock_accelerators

    Note that gtk_entry_adjust_scroll() is no longer needed as GtkEntry should automatically keep the scroll adjusted properly.

  • Additionally, all gtk_*_interp() functions were removed. gtk_*_full() versions were provided as of GTK+ 1.0 and should be used instead.

  • GtkButton has been changed to derive from GtkBin. To access a button's child, use GTK_BIN (button)->child, instead of the old GTK_BUTTON (button)->child.

  • The selection API has been slightly modified: gtk_selection_add_handler() and gtk_selection_add_handler_full() have been removed. To supply the selection, one now registers the targets one is interested in with:

      void gtk_selection_add_target (GtkWidget           *widget,
                           GdkAtom              selection,
                     GdkAtom              target,
                     guint                info);

    or:

      void gtk_selection_add_targets (GtkWidget           *widget,
                    GdkAtom              selection,
                  GtkTargetEntry      *targets,
                  guint                ntargets);

    When a request for a selection is received, the new "selection_get" signal will be called:

       void  "selection_get"           (GtkWidget          *widget,
                    GtkSelectionData   *selection_data,
                    guint               info,
                    guint               time);

    A "time" parameter has also been added to the "selection_received" signal.

      void  "selection_received"       (GtkWidget          *widget,
                    GtkSelectionData   *selection_data,
                    guint               time);

  • The old drag and drop API has been completely removed and replaced. See the reference documentation for details on the new API.

  • Support for Themes has been added. In general, this does not affect application code, however, a few new rules should be observed:

    • To set a shape for a window, you must use gtk_widget_shape_combine_mask() instead of gdk_window_shape_combine_mask(), or the shape will be reset when switching themes.

    • It is no longer permissable to draw directly on an arbitrary widget, or to set an arbitrary widget's background pixmap. If you need to do that, use a GtkDrawingArea or (for a toplevel) a GtkWindow where gtk_widget_set_app_paintable() has been called.

  • The GtkScrolledWindow widget no longer creates a GtkViewport automatically. Instead, it has been generalized to accept any "self-scrolling" widget.

    The self-scrolling widgets in the GTK+ core are GtkViewport, GtkCList, GtkCTree, GtkText, and GtkLayout. All of these widgets can be added to a scrolled window as normal children with gtk_container_add() and scrollbars will be set up automatically.

    To add scrollbars to a non self-scrolling widget, (such as a GtkList), first add it to a viewport, then add the viewport to a scrolled window. The scrolled window code provides a convenience function to do this:

      void gtk_scrolled_window_add_with_viewport (GtkScrolledWindow *scrollwin,
                          GtkWidget         *child);

    This does exactly what it says - it creates a viewport, adds the child widget to it, then adds the viewport to the scrolled window.

    The scrollbars have been removed from the GtkCList and GtkCTree, because they are now scrolled by simply adding them to a scrolled window. The scrollbar policy is set on the scrolled window with gtk_scrolled_window_set_policy() and not on the child widgets (e.g. GtkCList's gtk_clist_set_policy() was removed).

  • The "main loop" of GTK+ has been moved to GLib. This should not affect existing programs, since compatibility functions have been provided. However, you may want to consider migrating your code to use the GLib main loop directly.

  • the GTK_BASIC flag was removed, and with it the corresponding macro and function GTK_WIDGET_BASIC() and gtk_widget_basic().

  • All freeze/thaw methods are now recursive - that is, if you freeze a widget n times, you must also thaw it n times. Therefore, if you have code like:

      gboolean frozen;
  frozen = GTK_CLIST_FROZEN (clist);
  gtk_clist_freeze (clist);
  [...]
  if (!frozen)
    gtk_clist_thaw (clist);

    it will not work anymore. It must be, simply:

      gtk_clist_freeze (clist);
  [...]
  gtk_clist_thaw (clist);

  • The thread safety in GTK+ 1.2 is slightly different than that which appeared in early versions in the 1.1 development track. The main difference is that it relies on the thread primitives in GLib, and on the thread-safe GLib main loop.

    This means:

    • You must call g_thread_init() before executing any other GTK+ or GDK functions in a threaded GTK+ program.

    • Idles, timeouts, and input functions are executed outside of the main GTK+ lock. So, if you need to call GTK+ inside of such a callback, you must surround the callback with a gdk_threads_enter()/gdk_threads_leave() pair.

      However, signals are still executed within the main GTK+ lock.

      In particular, this means, if you are writing widgets that might be used in threaded programs, you must surround timeouts and idle functions in this matter.

      As always, you must also surround any calls to GTK+ not made within a signal handler with a gdk_threads_enter()/gdk_threads_leave() pair.

    • There is no longer a special --with-threads configure option for GTK+. To use threads in a GTK+ program, you must:

      1. If you want to use the native thread implementation, make sure GLib found this in configuration, otherwise, call you must provide a thread implementation to g_thread_init().

      2. Link with the libraries returned by gtk-config --libs gthread and use the cflags from gtk-config --cflags gthread. You can get these CFLAGS and LIBS by passing gthread as the fourth parameter to the AM_PATH_GTK automake macro.

  • Prior to GTK+ 1.2, there were two conflicting interpretations of widget->requisition. It was either taken to be the size that the widget requested, or that size modified by calls to gtk_widget_set_usize(). In GTK+ 1.2, it is always interpreted the first way.

    Container widgets are affected in two ways by this:

    1. Container widgets should not pass widget->requisition as the second parameter to gtk_widget_size_request(). Instead they should call it like:

                GtkRequisition child_requisition;
          gtk_widget_size_request (widget, &child_requisition);

    2. Container widgets should not access child->requisition directly. Either they should use the values returned by gtk_widget_size_request(), or they should call the new function:

          void gtk_widget_get_child_requisition (GtkWidget      *widget,
                       GtkRequisition *requisition);

      which returns the requisition of the given widget, modified by calls to gtk_widget_set_usize().


Changes from 1.2 to 2.0

Changes from 1.2 to 2.0 — Incompatible changes made between version 1.2 and version 2.0

Incompatible changes from 1.2 to 2.0

The GNOME 2.0 porting guide on http://developer.gnome.org has some more detailed discussion of porting from 1.2 to 2.0. See the sections on GLib and GTK+.

GTK+ changed fairly substantially from version 1.2 to 2.0, much more so than from 1.0 to 1.2. Subsequent updates (possibilities are 2.0 to 2.2, 2.2 to 2.4, then to 3.0) will almost certainly be much, much smaller. Nonetheless, most programs written for 1.2 compile against 2.0 with few changes. The bulk of changes listed below are to obscure features or very specialized features, and compatibility interfaces exist whenever possible.

  • gtk_container_get_toplevels() was removed and replaced with gtk_window_list_toplevels(), which has different memory management on the return value (gtk_window_list_toplevels() copies the GList and also references each widget in the list, so you have to g_list_free() the list after first unref'ing each list member).

  • The gdk_time* functions have been removed. This functionality has been unused since the main loop was moved into GLib prior to 1.2.

  • The signature for GtkPrintFunc (used for gtk_item_factory_dump_items()) has been changed to take a const gchar * instead of gchar *, to match what we do for GLib, and other similar cases.

  • The detail arguments in the GtkStyleClass structure are now const gchar *.

  • gtk_paned_set_gutter_size() has been removed, since the small handle tab has been changed to include the entire area previously occupied by the gutter.

  • gtk_paned_set_handle_size() has been removed, in favor of a style property, since this is an option that only makes sense for themes to adjust.

  • GDK no longer selects OwnerGrabButtonMask for button presses. This means that the automatic grab that occurs when the user presses a button will have owner_events = FALSE, so all events are redirected to the grab window, even events that would normally go to other windows of the window's owner.

  • GtkColorSelectionDialog has now been moved into it's own set of files, gtkcolorseldialog.c and gtkcolorseldialog.h.

  • gtk_widget_shape_combine_mask() now keeps a reference count on the mask pixmap that is passed in.

  • The GtkPatternSpec has been moved to GLib as GPatternSpec, the pattern arguments to gtk_item_factory_dump_items() and gtk_item_factory_dump_rc() have thusly been changed to take a GPatternSpec instead of a GtkPatternSpec.

  • Type system changes:

    • GTK_TYPE_OBJECT is not a fundamental type anymore. Type checks of the style (GTK_FUNDAMENTAL_TYPE (some_type) == GTK_TYPE_OBJECT) will not work anymore. As a replacement, (GTK_TYPE_IS_OBJECT (some_type)) can be used now.

    • The following types vanished: GTK_TYPE_ARGS, GTK_TYPE_CALLBACK, GTK_TYPE_C_CALLBACK, GTK_TYPE_FOREIGN. The corresponding GtkArg fields and field access macros are also gone.

    • The following type aliases vanished: GTK_TYPE_FLAT_FIRST, GTK_TYPE_FLAT_LAST, GTK_TYPE_STRUCTURED_FIRST, GTK_TYPE_STRUCTURED_LAST.

    • The type macros GTK_TYPE_MAKE() and GTK_TYPE_SEQNO() vanished, use of GTK_FUNDAMENTAL_TYPE() is discouraged. Instead, the corresponding GType API should be used: G_TYPE_FUNDAMENTAL(), G_TYPE_DERIVE_ID(), G_TYPE_BRANCH_SEQNO(). Note that the GLib type system doesn't build new type ids based on a global incremental sequential number anymore, but numbers new type ids sequentially per fundamental type branch.

    • The following type functions vanished/were replaced:

      Old Function | Replacement
      gtk_type_query() | being investigated
      gtk_type_set_varargs_type() -
      gtk_type_get_varargs_type() -
      gtk_type_check_object_cast() | g_type_check_instance_cast()
      gtk_type_check_class_cast() | g_type_check_class_cast()
      gtk_type_describe_tree() -
      gtk_type_describe_heritage() -
      gtk_type_free() -
      gtk_type_children_types() | g_type_children()
      gtk_type_set_chunk_alloc() | GTypeInfo.n_preallocs
      gtk_type_register_enum() | g_enum_register_static()
      gtk_type_register_flags() | g_flags_register_static()
      gtk_type_parent_class() | g_type_parent()/g_type_class_peek_parent()

      Use of g_type_class_ref()/g_type_class_unref() and g_type_class_peek()
is recommended over usage of gtk_type_class().
Use of g_type_register_static()/g_type_register_dynamic() is recommended
over usage of gtk_type_unique().

  • Object system changes: GtkObject derives from GObject, so is not the basic object type anymore. This imposes the following source incompatible changes:

    • GtkObject has no klass field anymore, an object's class can be retrieved with the object's coresponding GTK_<OBJECT>_GET_CLASS (object) macro.

    • GtkObjectClass has no type field anymore, a class's type can be retrived with the GTK_CLASS_TYPE (class) macro.

    • GtkObjectClass does not introduce the finalize() and shutdown() methods anymore. While shutdown() is intended for GTK+ internal use only, finalize() is required by a variety of object implementations. GObjectClass.finalize should be overriden here, e.g.:

          static void gtk_label_finalize (GObject *gobject)
    {
      GtkLabel *label = GTK_LABEL (gobject);

      G_OBJECT_CLASS (parent_class)->finalize (object);
    }
    static void gtk_label_class_init (GtkLabelClass *class)
    {
      GObjectClass *gobject_class = G_OBJECT_CLASS (class);

      gobject_class->finalize = gtk_label_finalize;
    }

  • The GtkObject::destroy signal can now be emitted multiple times on an object. ::destroy implementations should check that make sure that they take this into account, by checking to make sure that resources are there before freeing them. For example:

        if (object->foo_data)
      {
        g_free (object->foo_data);
        object->foo_data = NULL;
      }

    Also, ::destroy implementations have to release object references that the object holds. Code in finalize implementations such as:

        if (object->adjustment)
      {
        gtk_object_unref (object->adjustment);
        object->adjustment = NULL;
      }

    have to be moved into the ::destroy implementations. The reason for doing this is that all object reference cycles should be broken at destruction time. Because the ::destroy signal can be emitted multiple times, it no longer makes sense to check if a widget has been destroyed using the GTK_OBJECT_DESTROYED() macro, and this macro has been removed. If catching destruction is still needed, it can be done with a signal connection to ::destroy.

  • Signal system changes: The GTK+ 2.0 signal system merely proxies the GSignal system now. For future usage, direct use of the GSignal API is recommended, this avoids significant performance hits where GtkArg structures have to be converted into GValues. For language bindings, GSignal+GClosure provide a much more flexible and convenient mechanism to hook into signal emissions or install class default handlers, so the old GtkSignal API for language bindings is not supported anymore.

    Functions that got removed in the GTK+ signal API: gtk_signal_n_emissions(), gtk_signal_n_emissions_by_name(), gtk_signal_set_funcs(), gtk_signal_handler_pending_by_id(), gtk_signal_add_emission_hook(), gtk_signal_add_emission_hook_full(), gtk_signal_remove_emission_hook(), gtk_signal_query(). Also, the GtkCallbackMarshal argument to gtk_signal_connect_full() is not supported anymore. For many of the removed functions, similar variants are available in the g_signal_* namespace. The GSignal system performs emissions in a slightly different manner than the old GtkSignal code. Signal handlers that are connected to signal "foo" on object "bar" while "foo" is being emitted, will not be called anymore during the emission they were connected within.

  • Inserting and deleting text in GtkEntry though functions such as gtk_entry_insert_text() now leave the cursor at its original position in the text instead of moving it to the location of the insertion/deletion.

  • The label field of GtkFrame widgets has been removed (as part of a change to allow arbitrary widgets in the title position). The text can now be retrieved with the new function gtk_frame_get_text().

  • The 'font' and 'font_set' declarations in RC files are now ignored. There is a new 'font_name' field that holds the string form of a Pango font.

  • A number of types in GDK have become subclasses of GObject. For the most part, this should not break anyone's code. However, it's now possible/encouraged to use g_object_ref()/g_object_unref() and other GObject features with these GDK types. The converted types are: GdkWindow, GdkDrawable, GdkPixmap, GdkImage, GdkGC, GdkDragContext, GdkColormap.

  • All drawables including pixmaps used to have a type tag, the GdkWindowType enumeration, which included GDK_WINDOW_PIXMAP. GdkWindowType is now a property of GdkWindow only, and there is no GDK_WINDOW_PIXMAP. You can use the GDK_IS_PIXMAP() macro to see if you have a pixmap, if you need to know that.

  • GtkStyle and GtkRcStyle are now subclasses of GObject as well. This requires fairly extensive changes to theme engines, but shouldn't affect most other code.

  • xthickness and ythickness have moved from GtkStyleClass to GtkStyle (from class to instance). This gives themes a bit more flexibility and is generally more of the Right Thing. You can trivially fix your code with s/style->klass->xthickness/style->xthickness/g and same for ythickness.

  • Some GtkStyle draw_* methods have been removed (cross, oval, ramp) and others have been added (expander, layout). This will require changes to theme engines.

  • If you were using private GDK types, they have been rearranged significantly. You shouldn't use private types. ;-)

  • The visual for a widget, and also the default visual is now derived from the colormap for the widget and the default colormap. gtk_widget_set_visual(), gtk_widget_set_default_visual(), gtk_widget_push_visual() and gtk_widget_pop_visual() now do nothing. Since the visual always had to match that of the colormap, it is safe to simply delete all references to these functions.

  • A number of functions in GDK have been renamed for consistency and clarity. #defines to provide backwards compatibility have been included, but can be disabled by defining GDK_DISABLE_DEPRECATED.

    Old function | Defined As
    gdk_draw_pixmap | gdk_draw_drawable
    gdk_draw_bitmap | gdk_draw_drawable
    gdk_window_get_size | gdk_drawable_get_size
    gdk_window_get_type | gdk_window_get_window_type
    gdk_window_get_colormap | gdk_drawable_get_colormap
    gdk_window_set_colormap | gdk_drawable_set_colormap
    gdk_window_get_visual | gdk_drawable_get_visual
    gdk_window_ref | gdk_drawable_ref
    gdk_window_unref | gdk_drawable_unref
    gdk_bitmap_ref | gdk_drawable_ref
    gdk_bitmap_unref | gdk_drawable_unref
    gdk_pixmap_ref | gdk_drawable_ref
    gdk_pixmap_unref | gdk_drawable_unref
    gdk_gc_destroy | gdk_gc_unref
    gdk_image_destroy | gdk_image_unref
    gdk_cursor_destroy | gdk_cursor_unref
    gdk_window_copy_area(drawable,gc,x,y,source_drawable,source_x,source_y,width,height) | gdk_draw_pixmap(drawable,gc,source_drawable,source_x,source_y,x,y,width,height)
    gdk_rgb_get_cmap | gdk_rgb_get_colormap

    (Note that g_object_ref() and g_object_unref() may be used for all of the above ref and unref functions.) gtk_widget_popup() was removed, it was only usable for GtkWindows, and there the same effect can be achieved by gtk_window_move() and gtk_widget_show().

  • gdk_pixmap_foreign_new() no longer calls XFreePixmap() on the pixmap when the GdkPixmap is finalized. This change corresponds to the behavior of gdk_window_foreign_new(), and fixes a lot of problems with code where the pixmap wasn't supposed to be freed. If XFreePixmap() is needed, it can be done using the destroy-notification facilities of g_object_set_data().

  • GtkProgress/GtkProgressBar had serious problems in GTK+ 1.2.

    • Only 3 or 4 functions are really needed for 95% of progress interfaces; GtkProgress/GtkProgressBar had about 25 functions, and didn't even include these 3 or 4.

    • In activity mode, the API involves setting the adjustment to any random value, just to have the side effect of calling the progress bar update function - the adjustment is totally ignored in activity mode.

    • You set the activity step as a pixel value, which means to set the activity step you basically need to connect to size_allocate.

    • There are ctree_set_expander_style()-functions, to randomly change look-and-feel for no good reason.

    • The split between GtkProgress and GtkProgressBar makes no sense to me whatsoever.

    This was a big wart on GTK+ and made people waste lots of time, both learning and using the interface. So, we have added what we feel is the correct API, and marked all the rest deprecated. However, the changes are 100% backward-compatible and should break no existing code. The following 5 functions are the new programming interface and you should consider changing your code to use them:

      void       gtk_progress_bar_pulse                (GtkProgressBar *pbar);
  void       gtk_progress_bar_set_text             (GtkProgressBar *pbar,
                                                    const gchar    *text);
  void       gtk_progress_bar_set_fraction         (GtkProgressBar *pbar,
                                                    gfloat          fraction);

  void       gtk_progress_bar_set_pulse_step       (GtkProgressBar *pbar,
                                                    gfloat          fraction);
  void       gtk_progress_bar_set_orientation      (GtkProgressBar *pbar,
                            GtkProgressBarOrientation orientation);

  • The GtkNotebookPage structure has been removed from the public header files; this was never meant to be a public structure, and all functionality that could be done by accessing the struct fields of this structure should be accessible otherwise.

  • Negative values of the position parameter to gtk_notebook_reorder_child() now cause the page to be appended, not inserted at the beginning. (This gives consistency with gtk_box_reorder_child(), gtk_menu_reorder_child().)

  • GtkMenuPositionFunc has a new parameter push_in which controls how menus placed outside the screen is handled. If this is set to TRUE and part of the menu is outside the screen then GTK+ pushes it into the visible area. Otherwise the menu is cut of at the end of the visible screen area.

    Regardless of what happens to the size of the menu, the result is always that the items are placed in the same place as if the menu was placed outside the screen, using menu scrolling if necessary.

  • The "draw" signal and virtual method on GtkWidget has been removed. All drawing should now occur by invalidating a region of the widget (call gdk_window_invalidate_rect() or gtk_widget_queue_draw() for example to invalidate a region). GTK+ merges all invalid regions, and sends expose events to the widget in an idle handler for the invalid regions. gtk_widget_draw() is deprecated but still works; it adds the passed-in area to the invalid region and immediately sends expose events for the current invalid region. Most widgets will work fine if you just delete their "draw" implementation, since they will already have working expose_event implementations. The draw method was rarely called in practice anyway.

  • The GdkExposeEvent has a new region field. This can be used instead of the area field if you want a more exact representation of the area to update.

  • Sending synthetic exposes using gtk_widget_event() is no longer allowed. If you just need an expose call you should use gdk_window_invalidate_rect() or gdk_window_invalidate_region() instead. For the case of container widgets that need to propagate expose events to NO_WINDOW children you can either use gtk_container_propagate_expose(), or chain to the default container expose handler.

  • The draw_default and draw_focus methods/signals on GtkWidget are gone; simply draw things in your expose handler. gtk_widget_draw_focus() and gtk_widget_draw_default() wrapper functions are also gone; just queue a draw on the widget, or the part affected by the focus/default anyway. Also, GtkWidget now has default implementations for focus_in_event and focus_out_event. These set/unset GTK_HAS_FOCUS, and queue a draw. So if your focus in/out handler just does that, you can delete it.

  • GtkText and GtkTree are buggy and broken. We don't recommend using them, and changing old code to avoid them is a good idea. The recommended alternatives are GtkTextView and GtkTreeView. The broken widgets are not declared in the headers by default; to use them, define the symbol GTK_ENABLE_BROKEN during compilation. In some future release, these widgets will be removed from GTK+.

  • GdkColorContext is gone; you probably weren't using it anyway. Use GdkColormap and the gdk_rgb_* functions instead.

  • GtkMenuBar now draws the GtkContainer::border_width space outside the frame, not inside the frame.

  • In GTK+ 1.2, if an event handler returned TRUE it prevented propagation of that event to parent widgets. That is, the event signal would not be emitted on parent widgets. In GTK+ 2.0, if an event handler returns TRUE, the current signal emission on the current widget is immediately stopped. That is, other callbacks connected to the signal will not be invoked.

  • gtk_toolbar_new() no longer has arguments. This function was broken because the default GtkToolbarStyle (icons, text, both) is now a user preference, which is overridden when you call gtk_toolbar_set_style(). The constructor forced everyone to override the preference, which was undesirable. So to port your app, decide if you want to force the toolbar style or conform to the user's global defaults; if you want to force it, call gtk_toolbar_set_style().

    The orientation arg was removed from gtk_toolbar_new() as well, just because it wasn't very useful and we were breaking the function anyway so had an opportunity to lose it. Call gtk_toolbar_set_orientation() to set toolbar orientation.

  • GtkRange/GtkScrollbar/GtkScale were rewritten; this means that most theme engines won't draw them properly, and any custom subclasses of these widgets will need a rewrite (though if you could figure out how to subclass the old version of GtkRange, you have our respect). Also, GtkTroughType is gone.

    Here are some notable changes:

    • stepper_size style property is the height for vertical ranges, width for horizontal; the other dimension matches the trough size.

    • Added the ability to do NeXT-style steppers (and several other styles that don't make any sense).

    • Added min_slider_length, fixed_slider_length properties to GtkScrollbar.

    • Cleaned some private (or at least useless) functions out of gtkscale.h, e.g. gtk_scale_value_width.

    • Moved bindings from subclasses to GtkScale, even arrow keys, since blind users don't know scale orientation.

    • Changed move_slider action signal to use new GtkScrollType, remove GtkTroughType argument.

    • Digits rounds the values a range will input to the given number of decimals, but will not try to force adjustment values set by other controllers. That is, we no longer modify adjustment->value inside a value_changed handler.

    • Added getters for GtkScale setters.

    • Middle-click begins a slider drag.

  • The GtkContainer::focus signal/virtual function and
  gtk_container_focus() call were replaced by
  GtkWidget::focus and gtk_widget_child_focus().
  The semantics are the same, so you should be able to just
  replace container_class->focus = mywidget_focus with
  widget_class->focus = mywidget_focus and replace
  gtk_container_focus() calls with
  gtk_widget_child_focus() calls.

    The purpose of this change was to allow non-containers to have focusable elements.

  • gtk_rc_set_image_loader() and gtk_rc_load_image() have been removed, now that GTK+ includes decent image loading capabilities itself.

  • An extra GtkSettings argument has been added to gtk_rc_find_pixmap_in_path(). This function is only actually useful from a theme engine during parsing, at which point the GtkSettings is provided.

  • The child argument facility in gtkcontainer.c has been converted to a child property facility using GParamSpec and other facilities for GObject.

  • The set_child_arg() and get_child_arg() virtual methods have been replaced with set_child_property()/get_child_property(), which work similar to GObject->set_property/get_property.

  • Other removed GtkContainer functions with the replacements:

    Old function | Replacement
    gtk_container_add_child_arg_type | gtk_container_class_install_child_property
    gtk_container_query_child_args | gtk_container_class_list_child_properties
    gtk_container_child_getv | gtk_container_child_set_property
    gtk_container_child_setv | gtk_container_child_get_property
    gtk_container_add_with_args | gtk_container_add_with_properties
    gtk_container_addv | gtk_container_add/gtk_container_child_set_property

  • gdk_image_get() (or rather its replacement, gdk_drawable_get_image()) now handles errors properly by returning NULL, previously it would crash. Also, a window being offscreen is no longer considered an error; instead, the area contains undefined contents for the offscreen areas. In most cases, code using gdk_image_get() should really be ported to gdk_pixbuf_get_from_drawable().

  • gtk_widget_set_usize() has been renamed to gtk_widget_set_size_request(), however the old name still exists unless you define GTK_DISABLE_DEPRECATED.

  • gtk_widget_set_uposition() is deprecated; use
  gtk_window_move(),
  gtk_fixed_put(), or gtk_layout_put()
  instead.

  • gtk_window_set_policy() is deprecated. To get the effect of "allow_shrink", call gtk_widget_set_size_request (window, 0, 0). To get the effect of "allow_grow", call gtk_window_set_resizable (window, TRUE). You didn't want the effect of "auto_shrink", it made no sense. But maybe if you were using it you want to use gtk_window_resize (window, 1, 1) to snap a window back to its minimum size (the 1, 1 will be rounded up to the minimum window size).

  • The core GTK+ now takes care of handling mapping, unmapping and realizing the child widgets of containers in gtk_widget_set_parent(). In most cases, this allows container implementations to be simplified by removing the code in add() methods to map and realize children. However, there are a couple of things to watch out for here:

  • If the parent is realized before the add() happens,
     gtk_widget_set_parent_window() must be called before
     gtk_widget_set_parent(), since
     gtk_widget_set_parent() will realize the child.

  • If a container depended on its children not being mapped unless it did so itself (for example, GtkNotebook only mapped the current page), then the new function gtk_widget_set_child_visible() must be called to keep widgets that should not be mapped not mapped.

    As part of this change, most containers also will no longer need custom implementations of the map() and unmap() virtual functions. The only cases where this is necessary are:

    • For !NO_WINDOW widgets, if you create children of widget->window and don't map them in realize() then you must map them in map(). [ In almost all cases, you can simply map the windows in realize(). ]

    • For NO_WINDOW widgets, if you create windows in your realize() method, you must map then in map() and unmap them in unmap().

  • gtk_widget_set_default_style(), gtk_widget_push_style(), and gtk_widget_pop_style() have been removed, since they did not work properly with themes and there were better alternatives for modifying the appearance of widgets. You should generally use gtk_widget_modify_*() instead.

  • gtk_image_new() now takes no arguments and creates an empty GtkImage widget. To create a GtkImage widget from a GdkImage (the least common usage of GdkImage), use gtk_image_new_from_image().

  • GTK_SELECTION_EXTENDED is now deprecated, and neither the GtkList/GtkTree nor the GtkCList/GtkCTree support GTK_SELECTION_EXTENDED anymore. However, the old extended behavior replaces MULTIPLE behavior.

  • The following variables are no longer exported from GDK. (Other variables are also no longer exported; the following are the ones found used externally in a large sample of GTK+ code.)

    Variable | Replacement
    gdk_null_window_warnings | None - did nothing in GTK+ 1.2
    gdk_leader_window | None - private variable
    gdk_screen | gdk_x11_get_default_screen ()
    gdk_root_window | gdk_x11_get_default_root_xwindow ()
    gdk_root_parent | gdk_get_default_root_window ()
    gdk_error_code | gdk_error_trap_push ()/pop ()
    gdk_error_warnings | gdk_error_trap_push ()/pop ()
    gdk_display_name | gdk_get_display ()
    gdk_wm_delete_window | gdk_atom_intern ("WM_DELETE_WINDOW", FALSE)
    gdk_wm_take_focus | gdk_atom_intern ("WM_TAKE_FOCUS", FALSE)
    gdk_wm_protocols | gdk_atom_intern ("WM_PROTOCOLS", FALSE)

  • The handling of colormaps and widgets has been changed:

    • The default colormap for widgets is now the GdkRGB colormap, not the system default colormap. If you try to use resources created for a widget (e.g., widget->style) with a window using the system colormap, errors will result on some machines.

    • gtk_widget_push()/gtk_widget_pop_colormap() only cause the colormap to be explicitly set on toplevel widgets, not on all widgets. The colormap for other widgets (when not set using gtk_widget_set_colormap()), is determined by finding the nearest ancestor with a colormap set on it explicitly, or if that fails, the default colormap.

  • The default selected day for GtkCalendar is now the current day in the month, not the first day in the month. The current month and year were already used.

  • GDK is no longer put into threaded mode automatically when g_thread_init() has been called. In order to use the global GDK thread mutex with gdk_threads_enter() and gdk_threads_leave(), you must call gdk_threads_init() explicitly. If you aren't using GDK and GTK+ functions from multiple threads, there is no reason to call gdk_threads_init().

  • The GtkPreviewInfo struct has had its visual and colormap fields removed. Also, gtk_preview_get_cmap() and gtk_preview_get_visual() are deprecated, as GdkRGB works on any colormap and visual. You no longer need to gtk_widget_push_cmap (gtk_preview_get_cmap ()) in your code.

  • The GtkBox, GtkTable, and GtkAlignment widgets now call gtk_widget_set_redraw_on_allocate (widget, FALSE); on themselves. If you want to actually draw contents in a widget derived from one of these widgets, you'll probably want to change this in your init() function.

  • A number of widgets are now NO_WINDOW widgets (most importantly GtkButton, but also GtkRange and GtkNotebook) This has a couple of effects:

    • If you are deriving from one of these widgets, you need to adapt your code appropriately -- for instance, drawing coordinates start from widget->allocation.x, widget->allocation.y.

    • If you are embedding one of these widgets in a custom widget, you must make sure you call gtk_container_propagate_expose() correctly, as you must for any NO_WINDOW widgets.

    GtkFixed is a little special; it is now created by default as a NO_WINDOW widget, but if you do

        gtk_fixed_set_has_window (fixed, TRUE);

    after creating a fixed widget, it will create a window and handle it properly.

  • GtkLayout no longer has the xoffset, yoffset fields, which used to store the difference between world and window coordinates for layout->bin_window. These coordinate systems are now always the same.

  • gtk_paint_focus(), gtk_draw_focus() and GtkStyle::draw_focus() have been changed a bit:

    • A GtkStateType argument has been added to gtk_paint_focus().

    • The default implementation of the GtkStyle::draw_focus() virtual function now draws a focus rectangle whose width is determined by the GtkWidget::focus-width style property.

    • The rectangle passed in is the bounding box, instead of the rectangle used in the gdk_draw_rectangle() call, so it is no longer necessary to subtract 1 from the width and height.


Clipboards

Clipboards — Storing data on clipboards

Synopsis

#include <gtk/gtk.h>

                    GtkClipboard;
void                (*GtkClipboardReceivedFunc)         (GtkClipboard *clipboard,
                                                         GtkSelectionData *selection_data,
                                                         gpointer data);
void                (*GtkClipboardTextReceivedFunc)     (GtkClipboard *clipboard,
                                                         const gchar *text,
                                                         gpointer data);
void                (*GtkClipboardImageReceivedFunc)    (GtkClipboard *clipboard,
                                                         GdkPixbuf *pixbuf,
                                                         gpointer data);
void                (*GtkClipboardTargetsReceivedFunc)  (GtkClipboard *clipboard,
                                                         GdkAtom *atoms,
                                                         gint n_atoms,
                                                         gpointer data);
void                (*GtkClipboardRichTextReceivedFunc) (GtkClipboard *clipboard,
                                                         GdkAtom format,
                                                         const guint8 *text,
                                                         gsize length,
                                                         gpointer data);
void                (*GtkClipboardGetFunc)              (GtkClipboard *clipboard,
                                                         GtkSelectionData *selection_data,
                                                         guint info,
                                                         gpointer user_data_or_owner);
void                (*GtkClipboardClearFunc)            (GtkClipboard *clipboard,
                                                         gpointer user_data_or_owner);
GtkClipboard*       gtk_clipboard_get                   (GdkAtom selection);
GtkClipboard*       gtk_clipboard_get_for_display       (GdkDisplay *display,
                                                         GdkAtom selection);
GdkDisplay*         gtk_clipboard_get_display           (GtkClipboard *clipboard);
gboolean            gtk_clipboard_set_with_data         (GtkClipboard *clipboard,
                                                         const GtkTargetEntry *targets,
                                                         guint n_targets,
                                                         GtkClipboardGetFunc get_func,
                                                         GtkClipboardClearFunc clear_func,
                                                         gpointer user_data);
gboolean            gtk_clipboard_set_with_owner        (GtkClipboard *clipboard,
                                                         const GtkTargetEntry *targets,
                                                         guint n_targets,
                                                         GtkClipboardGetFunc get_func,
                                                         GtkClipboardClearFunc clear_func,
                                                         GObject *owner);
GObject*            gtk_clipboard_get_owner             (GtkClipboard *clipboard);
void                gtk_clipboard_clear                 (GtkClipboard *clipboard);
void                gtk_clipboard_set_text              (GtkClipboard *clipboard,
                                                         const gchar *text,
                                                         gint len);
void                gtk_clipboard_set_image             (GtkClipboard *clipboard,
                                                         GdkPixbuf *pixbuf);
void                gtk_clipboard_request_contents      (GtkClipboard *clipboard,
                                                         GdkAtom target,
                                                         GtkClipboardReceivedFunc callback,
                                                         gpointer user_data);
void                gtk_clipboard_request_text          (GtkClipboard *clipboard,
                                                         GtkClipboardTextReceivedFunc callback,
                                                         gpointer user_data);
void                gtk_clipboard_request_image         (GtkClipboard *clipboard,
                                                         GtkClipboardImageReceivedFunc callback,
                                                         gpointer user_data);
void                gtk_clipboard_request_targets       (GtkClipboard *clipboard,
                                                         GtkClipboardTargetsReceivedFunc callback,
                                                         gpointer user_data);
void                gtk_clipboard_request_rich_text     (GtkClipboard *clipboard,
                                                         GtkTextBuffer *buffer,
                                                         GtkClipboardRichTextReceivedFunc callback,
                                                         gpointer user_data);
GtkSelectionData*   gtk_clipboard_wait_for_contents     (GtkClipboard *clipboard,
                                                         GdkAtom target);
gchar*              gtk_clipboard_wait_for_text         (GtkClipboard *clipboard);
GdkPixbuf*          gtk_clipboard_wait_for_image        (GtkClipboard *clipboard);
guint8*             gtk_clipboard_wait_for_rich_text    (GtkClipboard *clipboard,
                                                         GtkTextBuffer *buffer,
                                                         GdkAtom *format,
                                                         gsize *length);
gboolean            gtk_clipboard_wait_is_text_available
                                                        (GtkClipboard *clipboard);
gboolean            gtk_clipboard_wait_is_image_available
                                                        (GtkClipboard *clipboard);
gboolean            gtk_clipboard_wait_is_rich_text_available
                                                        (GtkClipboard *clipboard,
                                                         GtkTextBuffer *buffer);
gboolean            gtk_clipboard_wait_for_targets      (GtkClipboard *clipboard,
                                                         GdkAtom **targets,
                                                         gint *n_targets);
gboolean            gtk_clipboard_wait_is_target_available
                                                        (GtkClipboard *clipboard,
                                                         GdkAtom target);
void                gtk_clipboard_set_can_store         (GtkClipboard *clipboard,
                                                         const GtkTargetEntry *targets,
                                                         gint n_targets);
void                gtk_clipboard_store                 (GtkClipboard *clipboard);

Object Hierarchy

  GObject
   +----GtkClipboard

Signals

  "owner-change"                                   : Run First

Description

The GtkClipboard object represents a clipboard of data shared between different processes or between different widgets in the same process. Each clipboard is identified by a name encoded as a GdkAtom. (Conversion to and from strings can be done with gdk_atom_intern() and gdk_atom_name().) The default clipboard corresponds to the "CLIPBOARD" atom; another commonly used clipboard is the "PRIMARY" clipboard, which, in X, traditionally contains the currently selected text.

To support having a number of different formats on the clipboard at the same time, the clipboard mechanism allows providing callbacks instead of the actual data. When you set the contents of the clipboard, you can either supply the data directly (via functions like gtk_clipboard_set_text()), or you can supply a callback to be called at a later time when the data is needed (via gtk_clipboard_set_with_data() or gtk_clipboard_set_with_owner().) Providing a callback also avoids having to make copies of the data when it is not needed.

gtk_clipboard_set_with_data() and gtk_clipboard_set_with_owner() are quite similar; the choice between the two depends mostly on which is more convenient in a particular situation. The former is most useful when you want to have a blob of data with callbacks to convert it into the various data types that you advertise. When the clear_func you provided is called, you simply free the data blob. The latter is more useful when the contents of clipboard reflect the internal state of a GObject (As an example, for the PRIMARY clipboard, when an entry widget provides the clipboard's contents the contents are simply the text within the selected region.) If the contents change, the entry widget can call gtk_clipboard_set_with_owner() to update the timestamp for clipboard ownership, without having to worry about clear_func being called.

Requesting the data from the clipboard is essentially asynchronous. If the contents of the clipboard are provided within the same process, then a direct function call will be made to retrieve the data, but if they are provided by another process, then the data needs to be retrieved from the other process, which may take some time. To avoid blocking the user interface, the call to request the selection, gtk_clipboard_request_contents() takes a callback that will be called when the contents are received (or when the request fails.) If you don't want to deal with providing a separate callback, you can also use gtk_clipboard_wait_for_contents(). What this does is run the GLib main loop recursively waiting for the contents. This can simplify the code flow, but you still have to be aware that other callbacks in your program can be called while this recursive mainloop is running.

Along with the functions to get the clipboard contents as an arbitrary data chunk, there are also functions to retrieve it as text, gtk_clipboard_request_text() and gtk_clipboard_wait_for_text(). These functions take care of determining which formats are advertised by the clipboard provider, asking for the clipboard in the best available format and converting the results into the UTF-8 encoding. (The standard form for representing strings in GTK+.)

Details

GtkClipboard

typedef struct _GtkClipboard GtkClipboard;

GtkClipboardReceivedFunc ()

void                (*GtkClipboardReceivedFunc)         (GtkClipboard *clipboard,
                                                         GtkSelectionData *selection_data,
                                                         gpointer data);

A function to be called when the results of gtk_clipboard_request_contents() are received, or when the request fails.

clipboard : | the GtkClipboard
selection_data : | a GtkSelectionData containing the data was received. If retrieving the data failed, then then length field of selection_data will be negative.
data : | the user_data supplied to gtk_clipboard_request_contents().

GtkClipboardTextReceivedFunc ()

void                (*GtkClipboardTextReceivedFunc)     (GtkClipboard *clipboard,
                                                         const gchar *text,
                                                         gpointer data);

A function to be called when the results of gtk_clipboard_request_text() are received, or when the request fails.

clipboard : | the GtkClipboard
text : | the text received, as a UTF-8 encoded string, or NULL if retrieving the data failed.
data : | the user_data supplied to gtk_clipboard_request_text().

GtkClipboardImageReceivedFunc ()

void                (*GtkClipboardImageReceivedFunc)    (GtkClipboard *clipboard,
                                                         GdkPixbuf *pixbuf,
                                                         gpointer data);

A function to be called when the results of gtk_clipboard_request_image() are received, or when the request fails.

clipboard : | the GtkClipboard
pixbuf : | the received image
data : | the user_data supplied to gtk_clipboard_request_image().

Since 2.6

GtkClipboardTargetsReceivedFunc ()

void                (*GtkClipboardTargetsReceivedFunc)  (GtkClipboard *clipboard,
                                                         GdkAtom *atoms,
                                                         gint n_atoms,
                                                         gpointer data);

A function to be called when the results of gtk_clipboard_request_targets() are received, or when the request fails.

clipboard : | the GtkClipboard
atoms : | the supported targets, as array of GdkAtom, or NULL if retrieving the data failed.
n_atoms : | the length of the atoms array.
data : | the user_data supplied to gtk_clipboard_request_targets().

Since 2.4

GtkClipboardRichTextReceivedFunc ()

void                (*GtkClipboardRichTextReceivedFunc) (GtkClipboard *clipboard,
                                                         GdkAtom format,
                                                         const guint8 *text,
                                                         gsize length,
                                                         gpointer data);

clipboard :
format :
text :
length :
data :

GtkClipboardGetFunc ()

void                (*GtkClipboardGetFunc)              (GtkClipboard *clipboard,
                                                         GtkSelectionData *selection_data,
                                                         guint info,
                                                         gpointer user_data_or_owner);

A function that will be called to provide the contents of the selection. If multiple types of data were advertised, the requested type can be determined from the info parameter or by checking the target field of selection_data. If the data could successfully be converted into then it should be stored into the selection_data object by calling gtk_selection_data_set() (or related functions such as gtk_selection_data_set_text()). If no data is set, the requestor will be informed that the attempt to get the data failed.

clipboard : | the GtkClipboard
selection_data : | a GtkSelectionData argument in which the requested data should be stored.
info : | the info field corresponding to the requested target from the GtkTargetEntry array passed to gtk_clipboard_set_with_data() or gtk_clipboard_set_with_owner().
user_data_or_owner : | the user_data argument passed to gtk_clipboard_set_with_data(), or the owner argument passed to gtk_clipboard_set_with_owner()

GtkClipboardClearFunc ()

void                (*GtkClipboardClearFunc)            (GtkClipboard *clipboard,
                                                         gpointer user_data_or_owner);

A function that will be called when the contents of the clipboard are changed or cleared. Once this has called, the user_data_or_owner argument will not be used again.

clipboard : | the GtkClipboard
user_data_or_owner : | the user_data argument passed to gtk_clipboard_set_with_data(), or the owner argument passed to gtk_clipboard_set_with_owner()

gtk_clipboard_get ()

GtkClipboard*       gtk_clipboard_get                   (GdkAtom selection);

Returns the clipboard object for the given selection. See gtk_clipboard_get_for_display() for complete details.

selection : | a GdkAtom which identifies the clipboard to use.
Returns : | the appropriate clipboard object. If no clipboard already exists, a new one will be created. Once a clipboard object has been created, it is persistent and, since it is owned by GTK+, must not be freed or unrefd.

gtk_clipboard_get_for_display ()

GtkClipboard*       gtk_clipboard_get_for_display       (GdkDisplay *display,
                                                         GdkAtom selection);

Returns the clipboard object for the given selection. Cut/copy/paste menu items and keyboard shortcuts should use the default clipboard, returned by passing GDK_SELECTION_CLIPBOARD for selection. (GDK_NONE is supported as a synonym for GDK_SELECTION_CLIPBOARD for backwards compatibility reasons.) The currently-selected object or text should be provided on the clipboard identified by GDK_SELECTION_PRIMARY. Cut/copy/paste menu items conceptually copy the contents of the GDK_SELECTION_PRIMARY clipboard to the default clipboard, i.e. they copy the selection to what the user sees as the clipboard.

(Passing GDK_NONE is the same as using gdk_atom_intern ("CLIPBOARD", FALSE). See http://www.freedesktop.org/Standards/clipboards-spec for a detailed discussion of the "CLIPBOARD" vs. "PRIMARY" selections under the X window system. On Win32 the GDK_SELECTION_PRIMARY clipboard is essentially ignored.)

It's possible to have arbitrary named clipboards; if you do invent new clipboards, you should prefix the selection name with an underscore (because the ICCCM requires that nonstandard atoms are underscore-prefixed), and namespace it as well. For example, if your application called "Foo" has a special-purpose clipboard, you might call it "_FOO_SPECIAL_CLIPBOARD".

display : | the display for which the clipboard is to be retrieved or created
selection : | a GdkAtom which identifies the clipboard to use.
Returns : | the appropriate clipboard object. If no clipboard already exists, a new one will be created. Once a clipboard object has been created, it is persistent and, since it is owned by GTK+, must not be freed or unrefd.

Since 2.2

gtk_clipboard_get_display ()

GdkDisplay*         gtk_clipboard_get_display           (GtkClipboard *clipboard);

Gets the GdkDisplay associated with clipboard

clipboard : | a GtkClipboard
Returns : | the GdkDisplay associated with clipboard

Since 2.2

gtk_clipboard_set_with_data ()

gboolean            gtk_clipboard_set_with_data         (GtkClipboard *clipboard,
                                                         const GtkTargetEntry *targets,
                                                         guint n_targets,
                                                         GtkClipboardGetFunc get_func,
                                                         GtkClipboardClearFunc clear_func,
                                                         gpointer user_data);

Virtually sets the contents of the specified clipboard by providing a list of supported formats for the clipboard data and a function to call to get the actual data when it is requested.

clipboard : | a GtkClipboard
targets : | array containing information about the available forms for the clipboard data
n_targets : | number of elements in targets
get_func : | function to call to get the actual clipboard data
clear_func : | when the clipboard contents are set again, this function will be called, and get_func will not be subsequently called.
user_data : | user data to pass to get_func and clear_func.
Returns : | TRUE if setting the clipboard data succeeded. If setting the clipboard data failed the provided callback functions will be ignored.

gtk_clipboard_set_with_owner ()

gboolean            gtk_clipboard_set_with_owner        (GtkClipboard *clipboard,
                                                         const GtkTargetEntry *targets,
                                                         guint n_targets,
                                                         GtkClipboardGetFunc get_func,
                                                         GtkClipboardClearFunc clear_func,
                                                         GObject *owner);

Virtually sets the contents of the specified clipboard by providing a list of supported formats for the clipboard data and a function to call to get the actual data when it is requested.

The difference between this function and gtk_clipboard_set_with_data() is that instead of an generic user_data pointer, a GObject is passed in.

clipboard : | a GtkClipboard
targets : | array containing information about the available forms for the clipboard data
n_targets : | number of elements in targets
get_func : | function to call to get the actual clipboard data
clear_func : | when the clipboard contents are set again, this function will be called, and get_func will not be subsequently called.
owner : | an object that "owns" the data. This object will be passed to the callbacks when called.
Returns : | TRUE if setting the clipboard data succeeded. If setting the clipboard data failed the provided callback functions will be ignored.

gtk_clipboard_get_owner ()

GObject*            gtk_clipboard_get_owner             (GtkClipboard *clipboard);

If the clipboard contents callbacks were set with gtk_clipboard_set_with_owner(), and the gtk_clipboard_set_with_data() or gtk_clipboard_clear() has not subsequently called, returns the owner set by gtk_clipboard_set_with_owner().

clipboard : | a GtkClipboard
Returns : | the owner of the clipboard, if any; otherwise NULL.

gtk_clipboard_clear ()

void                gtk_clipboard_clear                 (GtkClipboard *clipboard);

Clears the contents of the clipboard. Generally this should only be called between the time you call gtk_clipboard_set_with_owner() or gtk_clipboard_set_with_data(), and when the clear_func you supplied is called. Otherwise, the clipboard may be owned by someone else.

clipboard : a GtkClipboard

gtk_clipboard_set_text ()

void                gtk_clipboard_set_text              (GtkClipboard *clipboard,
                                                         const gchar *text,
                                                         gint len);

Sets the contents of the clipboard to the given UTF-8 string. GTK+ will make a copy of the text and take responsibility for responding for requests for the text, and for converting the text into the requested format.

clipboard : | a GtkClipboard object
text : | a UTF-8 string.
len : | length of text, in bytes, or -1, in which case the length will be determined with strlen().

gtk_clipboard_set_image ()

void                gtk_clipboard_set_image             (GtkClipboard *clipboard,
                                                         GdkPixbuf *pixbuf);

Sets the contents of the clipboard to the given GdkPixbuf. GTK+ will take responsibility for responding for requests for the image, and for converting the image into the requested format.

clipboard : | a GtkClipboard object
pixbuf : | a GdkPixbuf

Since 2.6

gtk_clipboard_request_contents ()

void                gtk_clipboard_request_contents      (GtkClipboard *clipboard,
                                                         GdkAtom target,
                                                         GtkClipboardReceivedFunc callback,
                                                         gpointer user_data);

Requests the contents of clipboard as the given target. When the results of the result are later received the supplied callback will be called.

clipboard : | a GtkClipboard
target : | an atom representing the form into which the clipboard owner should convert the selection.
callback : | A function to call when the results are received (or the retrieval fails). If the retrieval fails the length field of selection_data will be negative.
user_data : | user data to pass to callback

gtk_clipboard_request_text ()

void                gtk_clipboard_request_text          (GtkClipboard *clipboard,
                                                         GtkClipboardTextReceivedFunc callback,
                                                         gpointer user_data);

Requests the contents of the clipboard as text. When the text is later received, it will be converted to UTF-8 if necessary, and callback will be called.

The text parameter to callback will contain the resulting text if the request succeeded, or NULL if it failed. This could happen for various reasons, in particular if the clipboard was empty or if the contents of the clipboard could not be converted into text form.

clipboard : | a GtkClipboard
callback : | a function to call when the text is received, or the retrieval fails. (It will always be called one way or the other.)
user_data : | user data to pass to callback.

gtk_clipboard_request_image ()

void                gtk_clipboard_request_image         (GtkClipboard *clipboard,
                                                         GtkClipboardImageReceivedFunc callback,
                                                         gpointer user_data);

Requests the contents of the clipboard as image. When the image is later received, it will be converted to a GdkPixbuf, and callback will be called.

The pixbuf parameter to callback will contain the resulting GdkPixbuf if the request succeeded, or NULL if it failed. This could happen for various reasons, in particular if the clipboard was empty or if the contents of the clipboard could not be converted into an image.

clipboard : | a GtkClipboard
callback : | a function to call when the image is received, or the retrieval fails. (It will always be called one way or the other.)
user_data : | user data to pass to callback.

Since 2.6

gtk_clipboard_request_targets ()

void                gtk_clipboard_request_targets       (GtkClipboard *clipboard,
                                                         GtkClipboardTargetsReceivedFunc callback,
                                                         gpointer user_data);

Requests the contents of the clipboard as list of supported targets. When the list is later received, callback will be called.

The targets parameter to callback will contain the resulting targets if the request succeeded, or NULL if it failed.

clipboard : | a GtkClipboard
callback : | a function to call when the targets are received, or the retrieval fails. (It will always be called one way or the other.)
user_data : | user data to pass to callback.

Since 2.4

gtk_clipboard_request_rich_text ()

void                gtk_clipboard_request_rich_text     (GtkClipboard *clipboard,
                                                         GtkTextBuffer *buffer,
                                                         GtkClipboardRichTextReceivedFunc callback,
                                                         gpointer user_data);

Requests the contents of the clipboard as rich text. When the rich text is later received, callback will be called.

The text parameter to callback will contain the resulting rich text if the request succeeded, or NULL if it failed. The length parameter will contain text's length. This function can fail for various reasons, in particular if the clipboard was empty or if the contents of the clipboard could not be converted into rich text form.

clipboard : | a GtkClipboard
buffer : | a GtkTextBuffer
callback : | a function to call when the text is received, or the retrieval fails. (It will always be called one way or the other.)
user_data : | user data to pass to callback.

Since 2.10

gtk_clipboard_wait_for_contents ()

GtkSelectionData*   gtk_clipboard_wait_for_contents     (GtkClipboard *clipboard,
                                                         GdkAtom target);

Requests the contents of the clipboard using the given target. This function waits for the data to be received using the main loop, so events, timeouts, etc, may be dispatched during the wait.

clipboard : | a GtkClipboard
target : | an atom representing the form into which the clipboard owner should convert the selection.
Returns : | a newly-allocated GtkSelectionData object or NULL if retrieving the given target failed. If non-NULL, this value must be freed with gtk_selection_data_free() when you are finished with it.

gtk_clipboard_wait_for_text ()

gchar*              gtk_clipboard_wait_for_text         (GtkClipboard *clipboard);

Requests the contents of the clipboard as text and converts the result to UTF-8 if necessary. This function waits for the data to be received using the main loop, so events, timeouts, etc, may be dispatched during the wait.

clipboard : | a GtkClipboard
Returns : | a newly-allocated UTF-8 string which must be freed with g_free(), or NULL if retrieving the selection data failed. (This could happen for various reasons, in particular if the clipboard was empty or if the contents of the clipboard could not be converted into text form.)

gtk_clipboard_wait_for_image ()

GdkPixbuf*          gtk_clipboard_wait_for_image        (GtkClipboard *clipboard);

Requests the contents of the clipboard as image and converts the result to a GdkPixbuf. This function waits for the data to be received using the main loop, so events, timeouts, etc, may be dispatched during the wait.

clipboard : | a GtkClipboard
Returns : | a newly-allocated GdkPixbuf object which must be disposed with g_object_unref(), or NULL if retrieving the selection data failed. (This could happen for various reasons, in particular if the clipboard was empty or if the contents of the clipboard could not be converted into an image.)

Since 2.6

gtk_clipboard_wait_for_rich_text ()

guint8*             gtk_clipboard_wait_for_rich_text    (GtkClipboard *clipboard,
                                                         GtkTextBuffer *buffer,
                                                         GdkAtom *format,
                                                         gsize *length);

Requests the contents of the clipboard as rich text. This function waits for the data to be received using the main loop, so events, timeouts, etc, may be dispatched during the wait.

clipboard : | a GtkClipboard
buffer : | a GtkTextBuffer
format : | return location for the format of the returned data
length : | return location for the length of the returned data
Returns : | a newly-allocated binary block of data which must be freed with g_free(), or NULL if retrieving the selection data failed. (This could happen for various reasons, in particular if the clipboard was empty or if the contents of the clipboard could not be converted into text form.)

Since 2.10

gtk_clipboard_wait_is_text_available ()

gboolean            gtk_clipboard_wait_is_text_available
                                                        (GtkClipboard *clipboard);

Test to see if there is text available to be pasted This is done by requesting the TARGETS atom and checking if it contains any of the supported text targets. This function waits for the data to be received using the main loop, so events, timeouts, etc, may be dispatched during the wait.

This function is a little faster than calling gtk_clipboard_wait_for_text() since it doesn't need to retrieve the actual text.

clipboard : | a GtkClipboard
Returns : | TRUE is there is text available, FALSE otherwise.

gtk_clipboard_wait_is_image_available ()

gboolean            gtk_clipboard_wait_is_image_available
                                                        (GtkClipboard *clipboard);

Test to see if there is an image available to be pasted This is done by requesting the TARGETS atom and checking if it contains any of the supported image targets. This function waits for the data to be received using the main loop, so events, timeouts, etc, may be dispatched during the wait.

This function is a little faster than calling gtk_clipboard_wait_for_image() since it doesn't need to retrieve the actual image data.

clipboard : | a GtkClipboard
Returns : | TRUE is there is an image available, FALSE otherwise.

Since 2.6

gtk_clipboard_wait_is_rich_text_available ()

gboolean            gtk_clipboard_wait_is_rich_text_available
                                                        (GtkClipboard *clipboard,
                                                         GtkTextBuffer *buffer);

Test to see if there is rich text available to be pasted This is done by requesting the TARGETS atom and checking if it contains any of the supported rich text targets. This function waits for the data to be received using the main loop, so events, timeouts, etc, may be dispatched during the wait.

This function is a little faster than calling gtk_clipboard_wait_for_rich_text() since it doesn't need to retrieve the actual text.

clipboard : | a GtkClipboard
buffer : | a GtkTextBuffer
Returns : | TRUE is there is rich text available, FALSE otherwise.

Since 2.10

gtk_clipboard_wait_for_targets ()

gboolean            gtk_clipboard_wait_for_targets      (GtkClipboard *clipboard,
                                                         GdkAtom **targets,
                                                         gint *n_targets);

Returns a list of targets that are present on the clipboard, or NULL if there aren't any targets available. The returned list must be freed with g_free(). This function waits for the data to be received using the main loop, so events, timeouts, etc, may be dispatched during the wait.

clipboard : | a GtkClipboard
targets : | location to store an array of targets. The result stored here must be freed with g_free().
n_targets : | location to store number of items in targets.
Returns : | TRUE if any targets are present on the clipboard, otherwise FALSE.

Since 2.4

gtk_clipboard_wait_is_target_available ()

gboolean            gtk_clipboard_wait_is_target_available
                                                        (GtkClipboard *clipboard,
                                                         GdkAtom target);

Checks if a clipboard supports pasting data of a given type. This function can be used to determine if a "Paste" menu item should be insensitive or not.

If you want to see if there's text available on the clipboard, use gtk_clipboard_wait_is_text_available() instead.

clipboard : | a GtkClipboard
target : | A GdkAtom indicating which target to look for.
Returns : | TRUE if the target is available, FALSE otherwise.

Since 2.6

gtk_clipboard_set_can_store ()

void                gtk_clipboard_set_can_store         (GtkClipboard *clipboard,
                                                         const GtkTargetEntry *targets,
                                                         gint n_targets);

Hints that the clipboard data should be stored somewhere when the application exits or when gtk_clipboard_store() is called.

This value is reset when the clipboard owner changes. Where the clipboard data is stored is platform dependent, see gdk_display_store_clipboard() for more information.

clipboard : | a GtkClipboard
targets : | array containing information about which forms should be stored or NULL to indicate that all forms should be stored.
n_targets : | number of elements in targets

Since 2.6

gtk_clipboard_store ()

void                gtk_clipboard_store                 (GtkClipboard *clipboard);

Stores the current clipboard data somewhere so that it will stay around after the application has quit.

clipboard : a GtkClipboard

Since 2.6

Signal Details

The "owner-change" signal

void                user_function                      (GtkClipboard *clipboard,
                                                        GdkEvent     *event,
                                                        gpointer      user_data)      : Run First

clipboard : | the object which received the signal.
event : |
user_data : | user data set when the signal handler was connected.

See Also

GtkSelection

GtkClipboard provides a high-level wrapper around the lower level routines that deal with X selections. It is also possibly to directly manipulate the X selections, though it is seldom necessary to do so.


Compiling GTK+ Applications

Compiling GTK+ Applications — How to compile your GTK+ application

Compiling GTK+ Applications on UNIX

To compile a GTK+ application, you need to tell the compiler where to find the GTK+ header files and libraries. This is done with the pkg-config utility.

The following interactive shell session demonstrates how pkg-config is used (the actual output on your system may be different):

$ pkg-config --cflags gtk+-2.0
 -I/usr/include/gtk-2.0 -I/usr/lib/gtk-2.0/include -I/usr/include/glib-2.0 -I/usr/lib/glib-2.0/include -I/usr/include/pango-1.0 -I/usr/X11R6/include -I/usr/include/freetype2 -I/usr/include/atk-1.0
$ pkg-config --libs gtk+-2.0
 -L/usr/lib -L/usr/X11R6/lib -lgtk-x11-2.0 -lgdk-x11-2.0 -lXi -lgdk_pixbuf-2.0 -lm -lpangox -lpangoxft -lXft -lXrender -lXext -lX11 -lfreetype -lpango -latk -lgobject-2.0 -lgmodule-2.0 -ldl -lglib-2.0

The simplest way to compile a program is to use the "backticks" feature of the shell. If you enclose a command in backticks (not single quotes), then its output will be substituted into the command line before execution. So to compile a GTK+ Hello, World, you would type the following:

$ cc `pkg-config --cflags --libs gtk+-2.0` hello.c -o hello

To compile a GTK+ program for the framebuffer, use the "gtk+-linux-fb-2.0" package name instead of "gtk+-2.0":

$ cc `pkg-config --cflags --libs gtk+-linux-fb-2.0` hello.c -o hello

If you want to make sure that your program doesn't use any deprecated functions, you can define the preprocessor symbol GTK_DISABLE_DEPRECATED by using the command line option -DGTK_DISABLE_DEPRECATED=1. There are similar symbols GDK_DISABLE_DEPRECATED, GDK_PIXBUF_DISABLE_DEPRECATED and G_DISABLE_DEPRECATED for GDK, GdkPixbuf and GLib.

If you want to make sure that your program doesn't use any functions which may be problematic in a multihead setting, you can define the preprocessor symbol GDK_MULTIHEAD_SAFE by using the command line option -DGTK_MULTIHEAD_SAFE=1.


Using GTK+ on DirectFB

Using GTK+ on DirectFB — DirectFB-specific aspects of using GTK+

Using GTK+ on DirectFB

The DirectFB port of GTK+ is an implementation of GDK (and therefore GTK+) on top of the DirectFB libraries.

Like the obsolete linux-fb port of GTK+, it runs on the Linux framebuffer, but the DirectFB libraries provide additional features like hardware graphics acceleration, input device handling and abstraction and an integrated windowing system.

Build requirements

Beyond the usual GTK+ build requirements, the DirectFB backend (obviously) needs the DirectFB libraries (at least 0.9.21) and Cairo compiled with DirectFB support.


Drag and Drop

Drag and Drop — Functions for controlling drag and drop handling

Synopsis

#include <gtk/gtk.h>

enum                GtkDestDefaults;
enum                GtkTargetFlags;

void                gtk_drag_dest_set                   (GtkWidget *widget,
                                                         GtkDestDefaults flags,
                                                         const GtkTargetEntry *targets,
                                                         gint n_targets,
                                                         GdkDragAction actions);
void                gtk_drag_dest_set_proxy             (GtkWidget *widget,
                                                         GdkWindow *proxy_window,
                                                         GdkDragProtocol protocol,
                                                         gboolean use_coordinates);
void                gtk_drag_dest_unset                 (GtkWidget *widget);
GdkAtom             gtk_drag_dest_find_target           (GtkWidget *widget,
                                                         GdkDragContext *context,
                                                         GtkTargetList *target_list);
GtkTargetList*      gtk_drag_dest_get_target_list       (GtkWidget *widget);
void                gtk_drag_dest_set_target_list       (GtkWidget *widget,
                                                         GtkTargetList *target_list);
void                gtk_drag_dest_add_text_targets      (GtkWidget *widget);
void                gtk_drag_dest_add_image_targets     (GtkWidget *widget);
void                gtk_drag_dest_add_uri_targets       (GtkWidget *widget);
void                gtk_drag_dest_set_track_motion      (GtkWidget *widget,
                                                         gboolean track_motion);
gboolean            gtk_drag_dest_get_track_motion      (GtkWidget *widget);
void                gtk_drag_finish                     (GdkDragContext *context,
                                                         gboolean success,
                                                         gboolean del,
                                                         guint32 time_);
void                gtk_drag_get_data                   (GtkWidget *widget,
                                                         GdkDragContext *context,
                                                         GdkAtom target,
                                                         guint32 time_);
GtkWidget*          gtk_drag_get_source_widget          (GdkDragContext *context);
void                gtk_drag_highlight                  (GtkWidget *widget);
void                gtk_drag_unhighlight                (GtkWidget *widget);

GdkDragContext*     gtk_drag_begin                      (GtkWidget *widget,
                                                         GtkTargetList *targets,
                                                         GdkDragAction actions,
                                                         gint button,
                                                         GdkEvent *event);
void                gtk_drag_set_icon_widget            (GdkDragContext *context,
                                                         GtkWidget *widget,
                                                         gint hot_x,
                                                         gint hot_y);
void                gtk_drag_set_icon_pixmap            (GdkDragContext *context,
                                                         GdkColormap *colormap,
                                                         GdkPixmap *pixmap,
                                                         GdkBitmap *mask,
                                                         gint hot_x,
                                                         gint hot_y);
void                gtk_drag_set_icon_pixbuf            (GdkDragContext *context,
                                                         GdkPixbuf *pixbuf,
                                                         gint hot_x,
                                                         gint hot_y);
void                gtk_drag_set_icon_stock             (GdkDragContext *context,
                                                         const gchar *stock_id,
                                                         gint hot_x,
                                                         gint hot_y);
void                gtk_drag_set_icon_name              (GdkDragContext *context,
                                                         const gchar *icon_name,
                                                         gint hot_x,
                                                         gint hot_y);
void                gtk_drag_set_icon_default           (GdkDragContext *context);
void                gtk_drag_set_default_icon           (GdkColormap *colormap,
                                                         GdkPixmap *pixmap,
                                                         GdkBitmap *mask,
                                                         gint hot_x,
                                                         gint hot_y);
gboolean            gtk_drag_check_threshold            (GtkWidget *widget,
                                                         gint start_x,
                                                         gint start_y,
                                                         gint current_x,
                                                         gint current_y);
void                gtk_drag_source_set                 (GtkWidget *widget,
                                                         GdkModifierType start_button_mask,
                                                         const GtkTargetEntry *targets,
                                                         gint n_targets,
                                                         GdkDragAction actions);
void                gtk_drag_source_set_icon            (GtkWidget *widget,
                                                         GdkColormap *colormap,
                                                         GdkPixmap *pixmap,
                                                         GdkBitmap *mask);
void                gtk_drag_source_set_icon_pixbuf     (GtkWidget *widget,
                                                         GdkPixbuf *pixbuf);
void                gtk_drag_source_set_icon_stock      (GtkWidget *widget,
                                                         const gchar *stock_id);
void                gtk_drag_source_set_icon_name       (GtkWidget *widget,
                                                         const gchar *icon_name);
void                gtk_drag_source_unset               (GtkWidget *widget);
void                gtk_drag_source_set_target_list     (GtkWidget *widget,
                                                         GtkTargetList *target_list);
GtkTargetList*      gtk_drag_source_get_target_list     (GtkWidget *widget);
void                gtk_drag_source_add_text_targets    (GtkWidget *widget);
void                gtk_drag_source_add_image_targets   (GtkWidget *widget);
void                gtk_drag_source_add_uri_targets     (GtkWidget *widget);

Description

GTK+ has a rich set of functions for doing inter-process communication via the drag-and-drop metaphor. GTK+ can do drag-and-drop (DND) via multiple protocols. The currently supported protocols are the Xdnd and Motif protocols. As well as the functions listed here, applications may need to use some facilities provided for Selections. Also, the Drag and Drop API makes use of signals in the GtkWidget class.

Details

enum GtkDestDefaults

typedef enum {
  GTK_DEST_DEFAULT_MOTION     = 1 << 0, /* respond to "drag_motion" */
  GTK_DEST_DEFAULT_HIGHLIGHT  = 1 << 1, /* auto-highlight */
  GTK_DEST_DEFAULT_DROP       = 1 << 2, /* respond to "drag_drop" */
  GTK_DEST_DEFAULT_ALL        = 0x07
} GtkDestDefaults;

The GtkDestDefaults enumeration specifies the various types of action that will be taken on behalf of the user for a drag destination site.

GTK_DEST_DEFAULT_MOTION | If set for a widget, GTK+, during a drag over this widget will check if the drag matches this widget's list of possible targets and actions. GTK+ will then call gdk_drag_status() as appropriate.
GTK_DEST_DEFAULT_HIGHLIGHT | If set for a widget, GTK+ will draw a highlight on this widget as long as a drag is over this widget and the widget drag format and action are acceptable.
GTK_DEST_DEFAULT_DROP | If set for a widget, when a drop occurs, GTK+ will will check if the drag matches this widget's list of possible targets and actions. If so, GTK+ will call gtk_drag_get_data() on behalf of the widget. Whether or not the drop is successful, GTK+ will call gtk_drag_finish(). If the action was a move, then if the drag was successful, then TRUE will be passed for the delete parameter to gtk_drag_finish().
GTK_DEST_DEFAULT_ALL | If set, specifies that all default actions should be taken.

enum GtkTargetFlags

typedef enum {
  GTK_TARGET_SAME_APP = 1 << 0,    /*< nick=same-app >*/
  GTK_TARGET_SAME_WIDGET = 1 << 1  /*< nick=same-widget >*/
} GtkTargetFlags;

The GtkTargetFlags enumeration is used to specify constraints on an entry in a GtkTargetTable.

GTK_TARGET_SAME_APP | If this is set, the target will only be selected for drags within a single application.
GTK_TARGET_SAME_WIDGET | If this is set, the target will only be selected for drags within a single widget.

gtk_drag_dest_set ()

void                gtk_drag_dest_set                   (GtkWidget *widget,
                                                         GtkDestDefaults flags,
                                                         const GtkTargetEntry *targets,
                                                         gint n_targets,
                                                         GdkDragAction actions);

Sets a widget as a potential drop destination.

widget : | a GtkWidget
flags : | the flags that specify what actions GTK+ should take on behalf of a widget for drops onto that widget. The targets and actions fields only are used if GTK_DEST_DEFAULT_MOTION or GTK_DEST_DEFAULT_DROP are given.
targets : | a pointer to an array of GtkTargetEntrys indicating the drop types that this widget will accept.
n_targets : | the number of entries in targets.
actions : | a bitmask of possible actions for a drop onto this widget.

gtk_drag_dest_set_proxy ()

void                gtk_drag_dest_set_proxy             (GtkWidget *widget,
                                                         GdkWindow *proxy_window,
                                                         GdkDragProtocol protocol,
                                                         gboolean use_coordinates);

Sets this widget as a proxy for drops to another window.

widget : | a GtkWidget
proxy_window : | the window to which to forward drag events
protocol : | the drag protocol which the proxy_window accepts (You can use gdk_drag_get_protocol() to determine this)
use_coordinates : | If TRUE, send the same coordinates to the destination, because it is an embedded subwindow.

gtk_drag_dest_unset ()

void                gtk_drag_dest_unset                 (GtkWidget *widget);

Clears information about a drop destination set with gtk_drag_dest_set(). The widget will no longer receive notification of drags.

widget : a GtkWidget

gtk_drag_dest_find_target ()

GdkAtom             gtk_drag_dest_find_target           (GtkWidget *widget,
                                                         GdkDragContext *context,
                                                         GtkTargetList *target_list);

Looks for a match between context->targets and the dest_target_list, returning the first matching target, otherwise returning GDK_NONE. dest_target_list should usually be the return value from gtk_drag_dest_get_target_list(), but some widgets may have different valid targets for different parts of the widget; in that case, they will have to implement a drag_motion handler that passes the correct target list to this function.

widget : | drag destination widget
context : | drag context
target_list : | list of droppable targets, or NULL to use gtk_drag_dest_get_target_list (widget).
Returns : | first target that the source offers and the dest can accept, or GDK_NONE

gtk_drag_dest_get_target_list ()

GtkTargetList*      gtk_drag_dest_get_target_list       (GtkWidget *widget);

Returns the list of targets this widget can accept from drag-and-drop.

widget : | a GtkWidget
Returns : | the GtkTargetList, or NULL if none

gtk_drag_dest_set_target_list ()

void                gtk_drag_dest_set_target_list       (GtkWidget *widget,
                                                         GtkTargetList *target_list);

Sets the target types that this widget can accept from drag-and-drop. The widget must first be made into a drag destination with gtk_drag_dest_set().

widget : | a GtkWidget that's a drag destination
target_list : | list of droppable targets, or NULL for none

gtk_drag_dest_add_text_targets ()

void                gtk_drag_dest_add_text_targets      (GtkWidget *widget);

Add the text targets supported by GtkSelection to the target list of the drag destination. The targets are added with info = 0. If you need another value, use gtk_target_list_add_text_targets() and gtk_drag_dest_set_target_list().

widget : a GtkWidget that's a drag destination

Since 2.6

gtk_drag_dest_add_image_targets ()

void                gtk_drag_dest_add_image_targets     (GtkWidget *widget);

Add the image targets supported by GtkSelection to the target list of the drag destination. The targets are added with info = 0. If you need another value, use gtk_target_list_add_image_targets() and gtk_drag_dest_set_target_list().

widget : a GtkWidget that's a drag destination

Since 2.6

gtk_drag_dest_add_uri_targets ()

void                gtk_drag_dest_add_uri_targets       (GtkWidget *widget);

Add the URI targets supported by GtkSelection to the target list of the drag destination. The targets are added with info = 0. If you need another value, use gtk_target_list_add_uri_targets() and gtk_drag_dest_set_target_list().

widget : a GtkWidget that's a drag destination

Since 2.6

gtk_drag_dest_set_track_motion ()

void                gtk_drag_dest_set_track_motion      (GtkWidget *widget,
                                                         gboolean track_motion);

Tells the widget to emit ::drag-motion and ::drag-leave events regardless of the targets and the GTK_DEST_DEFAULT_MOTION flag.

This may be used when a widget wants to do generic actions regardless of the targets that the source offers.

widget : | a GtkWidget that's a drag destination
track_motion : | whether to accept all targets

Since 2.10

gtk_drag_dest_get_track_motion ()

gboolean            gtk_drag_dest_get_track_motion      (GtkWidget *widget);

Returns whether the widget has been configured to always emit ::drag-motion signals.

widget : | a GtkWidget that's a drag destination
Returns : | TRUE if the widget always emits ::drag-motion events

Since 2.10

gtk_drag_finish ()

void                gtk_drag_finish                     (GdkDragContext *context,
                                                         gboolean success,
                                                         gboolean del,
                                                         guint32 time_);

Informs the drag source that the drop is finished, and that the data of the drag will no longer be required.

context : | the drag context.
success : | a flag indicating whether the drop was successful
del : | a flag indicating whether the source should delete the original data. (This should be TRUE for a move)
time_ : | the timestamp from the "drag_data_drop" signal.

gtk_drag_get_data ()

void                gtk_drag_get_data                   (GtkWidget *widget,
                                                         GdkDragContext *context,
                                                         GdkAtom target,
                                                         guint32 time_);

Gets the data associated with a drag. When the data is received or the retrieval fails, GTK+ will emit a "drag_data_received" signal. Failure of the retrieval is indicated by the length field of the selection_data signal parameter being negative. However, when gtk_drag_get_data() is called implicitely because the GTK_DEST_DEFAULT_DROP was set, then the widget will not receive notification of failed drops.

widget : | the widget that will receive the "drag_data_received" signal.
context : | the drag context
target : | the target (form of the data) to retrieve.
time_ : | a timestamp for retrieving the data. This will generally be the time received in a "drag_data_motion" or "drag_data_drop" signal.

gtk_drag_get_source_widget ()

GtkWidget*          gtk_drag_get_source_widget          (GdkDragContext *context);

Determines the source widget for a drag.

context : | a (destination side) drag context.
Returns : | if the drag is occurring within a single application, a pointer to the source widget. Otherwise, NULL.

gtk_drag_highlight ()

void                gtk_drag_highlight                  (GtkWidget *widget);

Draws a highlight around a widget. This will attach handlers to "expose_event" and "draw", so the highlight will continue to be displayed until gtk_drag_unhighlight() is called.

widget : a widget to highlight

gtk_drag_unhighlight ()

void                gtk_drag_unhighlight                (GtkWidget *widget);

Removes a highlight set by gtk_drag_highlight() from a widget.

widget : a widget to remove the highlight from.

gtk_drag_begin ()

GdkDragContext*     gtk_drag_begin                      (GtkWidget *widget,
                                                         GtkTargetList *targets,
                                                         GdkDragAction actions,
                                                         gint button,
                                                         GdkEvent *event);

Initiates a drag on the source side. The function only needs to be used when the application is starting drags itself, and is not needed when gtk_drag_source_set() is used.

widget : | the source widget.
targets : | The targets (data formats) in which the source can provide the data.
actions : | A bitmask of the allowed drag actions for this drag.
button : | The button the user clicked to start the drag.
event : | The event that triggered the start of the drag.
Returns : | the context for this drag.

gtk_drag_set_icon_widget ()

void                gtk_drag_set_icon_widget            (GdkDragContext *context,
                                                         GtkWidget *widget,
                                                         gint hot_x,
                                                         gint hot_y);

Changes the icon for a widget to a given widget. GTK+ will not destroy the icon, so if you don't want it to persist, you should connect to the "drag_end" signal and destroy it yourself.

context : | the context for a drag. (This must be called with a context for the source side of a drag)
widget : | a toplevel window to use as an icon.
hot_x : | the X offset within widget of the hotspot.
hot_y : | the Y offset within widget of the hotspot.

gtk_drag_set_icon_pixmap ()

void                gtk_drag_set_icon_pixmap            (GdkDragContext *context,
                                                         GdkColormap *colormap,
                                                         GdkPixmap *pixmap,
                                                         GdkBitmap *mask,
                                                         gint hot_x,
                                                         gint hot_y);

Sets pixmap as the icon for a given drag. GTK+ retains references for the arguments, and will release them when they are no longer needed. In general, gtk_drag_set_icon_pixbuf() will be more convenient to use.

context : | the context for a drag. (This must be called with a context for the source side of a drag)
colormap : | the colormap of the icon
pixmap : | the image data for the icon
mask : | the transparency mask for the icon
hot_x : | the X offset within pixmap of the hotspot.
hot_y : | the Y offset within pixmap of the hotspot.

gtk_drag_set_icon_pixbuf ()

void                gtk_drag_set_icon_pixbuf            (GdkDragContext *context,
                                                         GdkPixbuf *pixbuf,
                                                         gint hot_x,
                                                         gint hot_y);

Sets pixbuf as the icon for a given drag.

context : | the context for a drag. (This must be called with a context for the source side of a drag)
pixbuf : | the GdkPixbuf to use as the drag icon.
hot_x : | the X offset within widget of the hotspot.
hot_y : | the Y offset within widget of the hotspot.

gtk_drag_set_icon_stock ()

void                gtk_drag_set_icon_stock             (GdkDragContext *context,
                                                         const gchar *stock_id,
                                                         gint hot_x,
                                                         gint hot_y);

Sets the icon for a given drag from a stock ID.

context : | the context for a drag. (This must be called with a context for the source side of a drag)
stock_id : | the ID of the stock icon to use for the drag.
hot_x : | the X offset within the icon of the hotspot.
hot_y : | the Y offset within the icon of the hotspot.

gtk_drag_set_icon_name ()

void                gtk_drag_set_icon_name              (GdkDragContext *context,
                                                         const gchar *icon_name,
                                                         gint hot_x,
                                                         gint hot_y);

Sets the icon for a given drag from a named themed icon. See the docs for GtkIconTheme for more details. Note that the size of the icon depends on the icon theme (the icon is loaded at the symbolic size GTK_ICON_SIZE_DND), thus hot_x and hot_y have to be used with care.

context : | the context for a drag. (This must be called with a context for the source side of a drag)
icon_name : | name of icon to use
hot_x : | the X offset of the hotspot within the icon
hot_y : | the Y offset of the hotspot within the icon

Since 2.8

gtk_drag_set_icon_default ()

void                gtk_drag_set_icon_default           (GdkDragContext *context);

Sets the icon for a particular drag to the default icon.

context : the context for a drag. (This must be called with a context for the source side of a drag)

gtk_drag_set_default_icon ()

void                gtk_drag_set_default_icon           (GdkColormap *colormap,
                                                         GdkPixmap *pixmap,
                                                         GdkBitmap *mask,
                                                         gint hot_x,
                                                         gint hot_y);

Warning

gtk_drag_set_default_icon is deprecated and should not be used in newly-written code.

Changes the default drag icon. GTK+ retains references for the arguments, and will release them when they are no longer needed. This function is obsolete. The default icon should now be changed via the stock system by changing the stock pixbuf for GTK_STOCK_DND.

colormap : | the colormap of the icon
pixmap : | the image data for the icon
mask : | the transparency mask for an image.
hot_x : | The X offset within widget of the hotspot.
hot_y : | The Y offset within widget of the hotspot.

gtk_drag_check_threshold ()

gboolean            gtk_drag_check_threshold            (GtkWidget *widget,
                                                         gint start_x,
                                                         gint start_y,
                                                         gint current_x,
                                                         gint current_y);

Checks to see if a mouse drag starting at (start_x, start_y) and ending at (current_x, current_y) has passed the GTK+ drag threshold, and thus should trigger the beginning of a drag-and-drop operation.

widget : | a GtkWidget
start_x : | X coordinate of start of drag
start_y : | Y coordinate of start of drag
current_x : | current X coordinate
current_y : | current Y coordinate
Returns : | TRUE if the drag threshold has been passed.

gtk_drag_source_set ()

void                gtk_drag_source_set                 (GtkWidget *widget,
                                                         GdkModifierType start_button_mask,
                                                         const GtkTargetEntry *targets,
                                                         gint n_targets,
                                                         GdkDragAction actions);

Sets up a widget so that GTK+ will start a drag operation when the user clicks and drags on the widget. The widget must have a window.

widget : | a GtkWidget
start_button_mask : | the bitmask of buttons that can start the drag
targets : | the table of targets that the drag will support
n_targets : | the number of items in targets
actions : | the bitmask of possible actions for a drag from this widget.

gtk_drag_source_set_icon ()

void                gtk_drag_source_set_icon            (GtkWidget *widget,
                                                         GdkColormap *colormap,
                                                         GdkPixmap *pixmap,
                                                         GdkBitmap *mask);

Sets the icon that will be used for drags from a particular widget from a pixmap/mask. GTK+ retains references for the arguments, and will release them when they are no longer needed. Use gtk_drag_source_set_icon_pixbuf() instead.

widget : | a GtkWidget
colormap : | the colormap of the icon
pixmap : | the image data for the icon
mask : | the transparency mask for an image.

gtk_drag_source_set_icon_pixbuf ()

void                gtk_drag_source_set_icon_pixbuf     (GtkWidget *widget,
                                                         GdkPixbuf *pixbuf);

Sets the icon that will be used for drags from a particular widget from a GdkPixbuf. GTK+ retains a reference for pixbuf and will release it when it is no longer needed.

widget : | a GtkWidget
pixbuf : | the GdkPixbuf for the drag icon

gtk_drag_source_set_icon_stock ()

void                gtk_drag_source_set_icon_stock      (GtkWidget *widget,
                                                         const gchar *stock_id);

Sets the icon that will be used for drags from a particular source to a stock icon.

widget : | a GtkWidget
stock_id : | the ID of the stock icon to use

gtk_drag_source_set_icon_name ()

void                gtk_drag_source_set_icon_name       (GtkWidget *widget,
                                                         const gchar *icon_name);

Sets the icon that will be used for drags from a particular source to a themed icon. See the docs for GtkIconTheme for more details.

widget : | a GtkWidget
icon_name : | name of icon to use

Since 2.8

gtk_drag_source_unset ()

void                gtk_drag_source_unset               (GtkWidget *widget);

Undoes the effects of gtk_drag_source_set().

widget : a GtkWidget

gtk_drag_source_set_target_list ()

void                gtk_drag_source_set_target_list     (GtkWidget *widget,
                                                         GtkTargetList *target_list);

Changes the target types that this widget offers for drag-and-drop. The widget must first be made into a drag source with gtk_drag_source_set().

widget : | a GtkWidget that's a drag source
target_list : | list of draggable targets, or NULL for none

Since 2.4

gtk_drag_source_get_target_list ()

GtkTargetList*      gtk_drag_source_get_target_list     (GtkWidget *widget);

Gets the list of targets this widget can provide for drag-and-drop.

widget : | a GtkWidget
Returns : | the GtkTargetList, or NULL if none

Since 2.4

gtk_drag_source_add_text_targets ()

void                gtk_drag_source_add_text_targets    (GtkWidget *widget);

Add the text targets supported by GtkSelection to the target list of the drag source. The targets are added with info = 0. If you need another value, use gtk_target_list_add_text_targets() and gtk_drag_source_set_target_list().

widget : a GtkWidget that's is a drag source

Since 2.6

gtk_drag_source_add_image_targets ()

void                gtk_drag_source_add_image_targets   (GtkWidget *widget);

Add the writable image targets supported by GtkSelection to the target list of the drag source. The targets are added with info = 0. If you need another value, use gtk_target_list_add_image_targets() and gtk_drag_source_set_target_list().

widget : a GtkWidget that's is a drag source

Since 2.6

gtk_drag_source_add_uri_targets ()

void                gtk_drag_source_add_uri_targets     (GtkWidget *widget);

Add the URI targets supported by GtkSelection to the target list of the drag source. The targets are added with info = 0. If you need another value, use gtk_target_list_add_uri_targets() and gtk_drag_source_set_target_list().

widget : a GtkWidget that's is a drag source

Since 2.6


Version Information

Version Information — Variables and functions to check the GTK+ version

Synopsis

#include <gtk/gtk.h>

extern              const guint gtk_major_version;
extern              const guint gtk_minor_version;
extern              const guint gtk_micro_version;
extern              const guint gtk_binary_age;
extern              const guint gtk_interface_age;
gchar*              gtk_check_version                   (guint required_major,
                                                         guint required_minor,
                                                         guint required_micro);

#define             GTK_MAJOR_VERSION
#define             GTK_MINOR_VERSION
#define             GTK_MICRO_VERSION
#define             GTK_BINARY_AGE
#define             GTK_INTERFACE_AGE
#define             GTK_CHECK_VERSION                   (major,minor,micro)

Description

GTK+ provides version information, primarily useful in configure checks for builds that have a configure script. Applications will not typically use the features described here.

Details

gtk_major_version

extern const guint gtk_major_version;

The major version number of the GTK+ library. (e.g. in GTK+ version 1.2.5 this is 1.)

This variable is in the library, so represents the GTK+ library you have linked against. Contrast with the GTK_MAJOR_VERSION macro, which represents the major version of the GTK+ headers you have included.

gtk_minor_version

extern const guint gtk_minor_version;

The minor version number of the GTK+ library. (e.g. in GTK+ version 1.2.5 this is 2.)

This variable is in the library, so represents the GTK+ library you have linked against. Contrast with the GTK_MINOR_VERSION macro, which represents the minor version of the GTK+ headers you have included.

gtk_micro_version

extern const guint gtk_micro_version;

The micro version number of the GTK+ library. (e.g. in GTK+ version 1.2.5 this is 5.)

This variable is in the library, so represents the GTK+ library you have linked against. Contrast with the GTK_MICRO_VERSION macro, which represents the micro version of the GTK+ headers you have included.

gtk_binary_age

extern const guint gtk_binary_age;

This is the binary age passed to libtool. If libtool means nothing to you, don't worry about it. ;-)

gtk_interface_age

extern const guint gtk_interface_age;

This is the interface age passed to libtool. If libtool means nothing to you, don't worry about it. ;-)

gtk_check_version ()

gchar*              gtk_check_version                   (guint required_major,
                                                         guint required_minor,
                                                         guint required_micro);

Checks that the GTK+ library in use is compatible with the given version. Generally you would pass in the constants GTK_MAJOR_VERSION, GTK_MINOR_VERSION, GTK_MICRO_VERSION as the three arguments to this function; that produces a check that the library in use is compatible with the version of GTK+ the application or module was compiled against.

Compatibility is defined by two things: first the version of the running library is newer than the version required_major.required_minor.required_micro. Second the running library must be binary compatible with the version required_major.required_minor.required_micro (same major version.)

This function is primarily for GTK+ modules; the module can call this function to check that it wasn't loaded into an incompatible version of GTK+. However, such a a check isn't completely reliable, since the module may be linked against an old version of GTK+ and calling the old version of gtk_check_version(), but still get loaded into an application using a newer version of GTK+.

required_major : | the required major version.
required_minor : | the required major version.
required_micro : | the required major version.
Returns : | NULL if the GTK+ library is compatible with the given version, or a string describing the version mismatch. The returned string is owned by GTK+ and should not be modified or freed.

GTK_MAJOR_VERSION

#define GTK_MAJOR_VERSION				(2)

Like gtk_major_version, but from the headers used at application compile time, rather than from the library linked against at application run time.

GTK_MINOR_VERSION

#define GTK_MINOR_VERSION				(10)

Like gtk_minor_version, but from the headers used at application compile time, rather than from the library linked against at application run time.

GTK_MICRO_VERSION

#define GTK_MICRO_VERSION				(11)

Like gtk_micro_version, but from the headers used at application compile time, rather than from the library linked against at application run time.

GTK_BINARY_AGE

#define GTK_BINARY_AGE					(1011)

Like gtk_binary_age, but from the headers used at application compile time, rather than from the library linked against at application run time.

GTK_INTERFACE_AGE

#define GTK_INTERFACE_AGE				(11)

Like gtk_interface_age, but from the headers used at application compile time, rather than from the library linked against at application run time.

GTK_CHECK_VERSION()

#define             GTK_CHECK_VERSION(major,minor,micro)

Returns TRUE if the version of the GTK+ header files is the same as or newer than the passed-in version.

major : | major version (e.g. 1 for version 1.2.5)
minor : | minor version (e.g. 2 for version 1.2.5)
micro : | micro version (e.g. 5 for version 1.2.5)


Using GTK+ on the Framebuffer

Using GTK+ on the Framebuffer — Linux framebuffer aspects of using GTK+

GTK+ for the Linux Framebuffer

Note

The linux-fb GDK target is unmaintained and may not work or even compile. The information below may still be helpful; also there are several patches in bugzilla which may help with making the linux-fb code compilable.

The linux-fb port of GTK+, also known as GtkFB is an implementation of GDK (and therefore GTK+) that runs on the Linux framebuffer. It runs in a single process that doesn't need X. It should run most GTK+ programs without any changes to the source.

Build requirements

You need GTK+ 2.0; the 1.2.x series does not have framebuffer support. To compile GTK+ with framebuffer support you will need FreeType 2; we recommend FreeType 2.0.1 or later, as there was some problems with freetype-config in 2.0. Make sure that you install FreeType before Pango, since Pango also needs it. FreeType can be found at ftp://ftp.freetype.org. You also need fontconfig in order to properly use the FreeType 2 backend in Pango. Fontconfig depends on FreeType as well. Fontconfig can be found at http://fontconfig.org.

Hardware requirements

You need a graphics card with an available framebuffer driver that can run in 8, 16, 24 or 32 bpp, such as matroxfb or vesafb. You also need a supported mouse. GTK+ currently supports the ps2 mouse, ms serial mouse and fidmour touchscreen. Additional hardware support should be simple to add.

Building and installing

First build and install GLib, ATK and Pango as usual, in that order. Then configure GTK+ by running configure (or autogen.sh if running from CVS) with --with-gdktarget=linux-fb.

Then compile as usual: make; make install

Fonts

Since GtkFB uses FreeType 2 to render fonts it can render TrueType and Postscript type 1 antialiased fonts.

GtkFB uses fontconfig for configuration of font information, including directories and aliases. Make sure that you have your fonts.conf file configured with where your TrueType and Type1 fonts are. Please refer to the fontconfig documentation for more information.

Running

To run a program you should only need to start it, but there are some things that can cause problems, and some things that can be controlled by environment variables. Try gtk-demo distributed with GTK+ to test if things work.

If you use a ps2 mouse, make sure that /dev/psaux is readable and writable.

Make sure gpm is not running.

If you don't specify anything GtkFB will start up in the current virtual console in the current resolution and bit-depth. This can be changed by specifying environment variables:

GDK_VT:
 unset means open on the current VT.
 0-9: open on the specified VT. Make sure you have read/write rights
      there.
 new: Allocate a new VT after the last currently used one.

GDK_DISPLAY_MODE:
 Specifies the name of a mode in /etc/fb.modes that you
 want to use.

GDK_DISPLAY_DEPTH:
 Specify the desired bit depth of the framebuffer.

GDK_DISPLAY_WIDTH:
 Specify the desired width of the framebuffer.

GDK_DISPLAY_HEIGHT:
 Specify the desired height of the framebuffer.

GDK_DISPLAY:
 Specify the framebuffer device to use. Default is /dev/fb0.

GDK_MOUSE_TYPE:
 Specify mouse type. Currently supported is:
  ps2 - PS/2 mouse
  imps2 - PS/2 intellimouse (wheelmouse)
  ms - Microsoft serial mouse
  fidmour - touch screen
 Default is ps2.

GDK_KEYBOARD_TYPE:
 Specify keyboard type. Currently supported is
  xlate - normal tty mode keyboard.
    Quite limited, cannot detect key up/key down events. Doesn't
    handle ctrl/alt/shift for all keys. This is the default driver,
    but should not be used in "production" use.
  raw - read from the tty in RAW mode.
    Sets the keyboard in RAW mode and handles all the keycodes. This
    gives correct handling of modifiers and key up/down events. You
    must be root to use this. If you use this for development or
    debugging it is recommended to enable magic sysrq handling in the
    kernel. Then you can use ALT-SysRQ-r to turn the keyboard back to
    normal mode.
 Default is xlate.

Debug features

Pressing Ctrl-Alt-Return repaints the whole screen. Unfortunately this cannot be pressed when using the xlate keyboard driver, so instead you can use shift-F1 instead when using this driver.

Pressing Ctrl-Alt-BackSpace kills the GtkFB program. (This can't be pressed in the xlate driver, so instead you can use shift-F8.)


Main loop and Events

Main loop and Events — Library initialization, main event loop, and events

Synopsis

#include <gtk/gtk.h>

gchar*              gtk_set_locale                      (void);
void                gtk_disable_setlocale               (void);
PangoLanguage*      gtk_get_default_language            (void);
gboolean            gtk_parse_args                      (int *argc,
                                                         char ***argv);
void                gtk_init                            (int *argc,
                                                         char ***argv);
gboolean            gtk_init_check                      (int *argc,
                                                         char ***argv);
gboolean            gtk_init_with_args                  (int *argc,
                                                         char ***argv,
                                                         char *parameter_string,
                                                         GOptionEntry *entries,
                                                         char *translation_domain,
                                                         GError **error);
GOptionGroup*       gtk_get_option_group                (gboolean open_default_display);
void                gtk_exit                            (gint error_code);
gboolean            gtk_events_pending                  (void);
void                gtk_main                            (void);
guint               gtk_main_level                      (void);
void                gtk_main_quit                       (void);
gboolean            gtk_main_iteration                  (void);
gboolean            gtk_main_iteration_do               (gboolean blocking);
void                gtk_main_do_event                   (GdkEvent *event);
void                (*GtkModuleInitFunc)                (gint *argc,
                                                         gchar ***argv);
void                (*GtkModuleDisplayInitFunc)         (GdkDisplay *display);

gboolean            gtk_true                            (void);
gboolean            gtk_false                           (void);

void                gtk_grab_add                        (GtkWidget *widget);
GtkWidget*          gtk_grab_get_current                (void);
void                gtk_grab_remove                     (GtkWidget *widget);

void                gtk_init_add                        (GtkFunction function,
                                                         gpointer data);
void                gtk_quit_add_destroy                (guint main_level,
                                                         GtkObject *object);
guint               gtk_quit_add                        (guint main_level,
                                                         GtkFunction function,
                                                         gpointer data);
guint               gtk_quit_add_full                   (guint main_level,
                                                         GtkFunction function,
                                                         GtkCallbackMarshal marshal,
                                                         gpointer data,
                                                         GtkDestroyNotify destroy);
void                gtk_quit_remove                     (guint quit_handler_id);
void                gtk_quit_remove_by_data             (gpointer data);

guint               gtk_timeout_add_full                (guint32 interval,
                                                         GtkFunction function,
                                                         GtkCallbackMarshal marshal,
                                                         gpointer data,
                                                         GtkDestroyNotify destroy);
guint               gtk_timeout_add                     (guint32 interval,
                                                         GtkFunction function,
                                                         gpointer data);
void                gtk_timeout_remove                  (guint timeout_handler_id);

guint               gtk_idle_add                        (GtkFunction function,
                                                         gpointer data);
guint               gtk_idle_add_priority               (gint priority,
                                                         GtkFunction function,
                                                         gpointer data);
guint               gtk_idle_add_full                   (gint priority,
                                                         GtkFunction function,
                                                         GtkCallbackMarshal marshal,
                                                         gpointer data,
                                                         GtkDestroyNotify destroy);
void                gtk_idle_remove                     (guint idle_handler_id);
void                gtk_idle_remove_by_data             (gpointer data);

guint               gtk_input_add_full                  (gint source,
                                                         GdkInputCondition condition,
                                                         GdkInputFunction function,
                                                         GtkCallbackMarshal marshal,
                                                         gpointer data,
                                                         GtkDestroyNotify destroy);
void                gtk_input_remove                    (guint input_handler_id);

#define             GTK_PRIORITY_REDRAW
#define             GTK_PRIORITY_RESIZE
#define             GTK_PRIORITY_HIGH
#define             GTK_PRIORITY_INTERNAL
#define             GTK_PRIORITY_DEFAULT
#define             GTK_PRIORITY_LOW

guint               gtk_key_snooper_install             (GtkKeySnoopFunc snooper,
                                                         gpointer func_data);
gint                (*GtkKeySnoopFunc)                  (GtkWidget *grab_widget,
                                                         GdkEventKey *event,
                                                         gpointer func_data);
void                gtk_key_snooper_remove              (guint snooper_handler_id);

GdkEvent*           gtk_get_current_event               (void);
guint32             gtk_get_current_event_time          (void);
gboolean            gtk_get_current_event_state         (GdkModifierType *state);
GtkWidget*          gtk_get_event_widget                (GdkEvent *event);
void                gtk_propagate_event                 (GtkWidget *widget,
                                                         GdkEvent *event);

Description

Before using GTK+, you need to initialize it; initialization connects to the window system display, and parses some standard command line arguments. The gtk_init() function initializes GTK+. gtk_init() exits the application if errors occur; to avoid this, use gtk_init_check(). gtk_init_check() allows you to recover from a failed GTK+ initialization - you might start up your application in text mode instead.

Like all GUI toolkits, GTK+ uses an event-driven programming model. When the user is doing nothing, GTK+ sits in the main loop and waits for input. If the user performs some action - say, a mouse click - then the main loop "wakes up" and delivers an event to GTK+. GTK+ forwards the event to one or more widgets.

When widgets receive an event, they frequently emit one or more signals. Signals notify your program that "something interesting happened" by invoking functions you've connected to the signal with g_signal_connect(). Functions connected to a signal are often termed callbacks.

When your callbacks are invoked, you would typically take some action - for example, when an Open button is clicked you might display a GtkFileSelectionDialog. After a callback finishes, GTK+ will return to the main loop and await more user input.

Example 1. Typical main function for a GTK+ application

int
main (int argc, char **argv)
{
  /* Initialize i18n support */
  gtk_set_locale ();

  /* Initialize the widget set */
  gtk_init (&argc, &argv);

  /* Create the main window */
  mainwin = gtk_window_new (GTK_WINDOW_TOPLEVEL);

  /* Set up our GUI elements */
  ...

  /* Show the application window */
  gtk_widget_show_all (mainwin);

  /* Enter the main event loop, and wait for user interaction */
  gtk_main ();

  /* The user lost interest */
  return 0;
}

It's OK to use the GLib main loop directly instead of gtk_main(), though it involves slightly more typing. See GMainLoop in the GLib documentation.

Details

gtk_set_locale ()

gchar*              gtk_set_locale                      (void);

Initializes internationalization support for GTK+. gtk_init() automatically does this, so there is typically no point in calling this function.

If you are calling this function because you changed the locale after GTK+ is was initialized, then calling this function may help a bit. (Note, however, that changing the locale after GTK+ is initialized may produce inconsistent results and is not really supported.)

In detail - sets the current locale according to the program environment. This is the same as calling the C library function setlocale (LC_ALL, "") but also takes care of the locale specific setup of the windowing system used by GDK.

Returns : a string corresponding to the locale set, typically in the form lang_COUNTRY, where lang is an ISO-639 language code, and COUNTRY is an ISO-3166 country code. On Unix, this form matches the result of the setlocale(); it is also used on other machines, such as Windows, where the C library returns a different result. The string is owned by GTK+ and should not be modified or freed.

gtk_disable_setlocale ()

void                gtk_disable_setlocale               (void);

Prevents gtk_init(), gtk_init_check(), gtk_init_with_args() and gtk_parse_args() from automatically calling setlocale (LC_ALL, ""). You would want to use this function if you wanted to set the locale for your program to something other than the user's locale, or if you wanted to set different values for different locale categories.

Most programs should not need to call this function.

gtk_get_default_language ()

PangoLanguage*      gtk_get_default_language            (void);

Returns the PangoLanguage for the default language currently in effect. (Note that this can change over the life of an application.) The default language is derived from the current locale. It determines, for example, whether GTK+ uses the right-to-left or left-to-right text direction. See _gtk_get_lc_ctype() for notes on behaviour on Windows.

Returns : the default language as a PangoLanguage, must not be freed

gtk_parse_args ()

gboolean            gtk_parse_args                      (int *argc,
                                                         char ***argv);

Parses command line arguments, and initializes global attributes of GTK+, but does not actually open a connection to a display. (See gdk_display_open(), gdk_get_display_arg_name())

Any arguments used by GTK+ or GDK are removed from the array and argc and argv are updated accordingly.

You shouldn't call this function explicitely if you are using gtk_init(), or gtk_init_check().

argc : | a pointer to the number of command line arguments.
argv : | a pointer to the array of command line arguments.
Returns : | TRUE if initialization succeeded, otherwise FALSE.

gtk_init ()

void                gtk_init                            (int *argc,
                                                         char ***argv);

Call this function before using any other GTK+ functions in your GUI applications. It will initialize everything needed to operate the toolkit and parses some standard command line options. argc and argv are adjusted accordingly so your own code will never see those standard arguments.

Note that there are some alternative ways to initialize GTK+: if you are calling gtk_parse_args(), gtk_init_check(), gtk_init_with_args() or g_option_context_parse() with the option group returned by gtk_get_option_group(), you don't have to call gtk_init().

Note

This function will terminate your program if it was unable to initialize the GUI for some reason. If you want your program to fall back to a textual interface you want to call gtk_init_check() instead.

Note

argc : | Address of the argc parameter of your main() function. Changed if any arguments were handled.
argv : | Address of the argv parameter of main(). Any parameters understood by gtk_init() are stripped before return.

gtk_init_check ()

gboolean            gtk_init_check                      (int *argc,
                                                         char ***argv);

This function does the same work as gtk_init() with only a single change: It does not terminate the program if the GUI can't be initialized. Instead it returns FALSE on failure.

This way the application can fall back to some other means of communication with the user - for example a curses or command line interface.

argc : | Address of the argc parameter of your main() function. Changed if any arguments were handled.
argv : | Address of the argv parameter of main(). Any parameters understood by gtk_init() are stripped before return.
Returns : | TRUE if the GUI has been successfully initialized, FALSE otherwise.

gtk_init_with_args ()

gboolean            gtk_init_with_args                  (int *argc,
                                                         char ***argv,
                                                         char *parameter_string,
                                                         GOptionEntry *entries,
                                                         char *translation_domain,
                                                         GError **error);

This function does the same work as gtk_init_check(). Additionally, it allows you to add your own commandline options, and it automatically generates nicely formatted --help output. Note that your program will be terminated after writing out the help output.

argc : | a pointer to the number of command line arguments.
argv : | a pointer to the array of command line arguments.
parameter_string : | a string which is displayed in the first line of --help output, after programname [OPTION...]
entries : | a NULL-terminated array of GOptionEntrys describing the options of your program
translation_domain : | a translation domain to use for translating the --help output for the options in entries with gettext(), or NULL
error : | a return location for errors
Returns : | TRUE if the GUI has been successfully initialized, FALSE otherwise.

Since 2.6

gtk_get_option_group ()

GOptionGroup*       gtk_get_option_group                (gboolean open_default_display);

Returns a GOptionGroup for the commandline arguments recognized by GTK+ and GDK. You should add this group to your GOptionContext with g_option_context_add_group(), if you are using g_option_context_parse() to parse your commandline arguments.

open_default_display : | whether to open the default display when parsing the commandline arguments
Returns : | a GOptionGroup for the commandline arguments recognized by GTK+

Since 2.6

gtk_exit ()

void                gtk_exit                            (gint error_code);

Warning

gtk_exit is deprecated and should not be used in newly-written code. Use the standard exit() function instead.

Terminates the program and returns the given exit code to the caller. This function will shut down the GUI and free all resources allocated for GTK+.

error_code : Return value to pass to the caller. This is dependent on the target system but at least on Unix systems 0 means success.

gtk_events_pending ()

gboolean            gtk_events_pending                  (void);

Checks if any events are pending. This can be used to update the GUI and invoke timeouts etc. while doing some time intensive computation.

Example 2. Updating the GUI during a long computation.

    /* computation going on */
...
        while (gtk_events_pending ())
      gtk_main_iteration ();
...
    /* computation continued */

Returns : TRUE if any events are pending, FALSE otherwise.

gtk_main ()

void                gtk_main                            (void);

Runs the main loop until gtk_main_quit() is called. You can nest calls to gtk_main(). In that case gtk_main_quit() will make the innermost invocation of the main loop return.

gtk_main_level ()

guint               gtk_main_level                      (void);

Asks for the current nesting level of the main loop. This can be useful when calling gtk_quit_add().

Returns : the nesting level of the current invocation of the main loop.

gtk_main_quit ()

void                gtk_main_quit                       (void);

Makes the innermost invocation of the main loop return when it regains control.

gtk_main_iteration ()

gboolean            gtk_main_iteration                  (void);

Runs a single iteration of the mainloop. If no events are waiting to be processed GTK+ will block until the next event is noticed. If you don't want to block look at gtk_main_iteration_do() or check if any events are pending with gtk_events_pending() first.

Returns : TRUE if gtk_main_quit() has been called for the innermost mainloop.

gtk_main_iteration_do ()

gboolean            gtk_main_iteration_do               (gboolean blocking);

Runs a single iteration of the mainloop. If no events are available either return or block dependent on the value of blocking.

blocking : | TRUE if you want GTK+ to block if no events are pending.
Returns : | TRUE if gtk_main_quit() has been called for the innermost mainloop.

gtk_main_do_event ()

void                gtk_main_do_event                   (GdkEvent *event);

Processes a single GDK event. This is public only to allow filtering of events between GDK and GTK+. You will not usually need to call this function directly.

While you should not call this function directly, you might want to know how exactly events are handled. So here is what this function does with the event:

  1. Compress enter/leave notify events. If the event passed build an enter/leave pair together with the next event (peeked from GDK) both events are thrown away. This is to avoid a backlog of (de-)highlighting widgets crossed by the pointer.

  2. Find the widget which got the event. If the widget can't be determined the event is thrown away unless it belongs to a INCR transaction. In that case it is passed to gtk_selection_incr_event().

  3. Then the event is passed on a stack so you can query the currently handled event with gtk_get_current_event().

  4. The event is sent to a widget. If a grab is active all events for widgets that are not in the contained in the grab widget are sent to the latter with a few exceptions:

    • Deletion and destruction events are still sent to the event widget for obvious reasons.

    • Events which directly relate to the visual representation of the event widget.

    • Leave events are delivered to the event widget if there was an enter event delivered to it before without the paired leave event.

    • Drag events are not redirected because it is unclear what the semantics of that would be.

    Another point of interest might be that all key events are first passed through the key snooper functions if there are any. Read the description of gtk_key_snooper_install() if you need this feature.

  5. After finishing the delivery the event is popped from the event stack.

event : An event to process (normally) passed by GDK.

GtkModuleInitFunc ()

void                (*GtkModuleInitFunc)                (gint *argc,
                                                         gchar ***argv);

Each GTK+ module must have a function gtk_module_init() with this prototype. This function is called after loading the module with the argc and argv cleaned from any arguments that GTK+ handles itself.

argc : | Pointer to the number of arguments remaining after gtk_init().
argv : | Points to the argument vector.

GtkModuleDisplayInitFunc ()

void                (*GtkModuleDisplayInitFunc)         (GdkDisplay *display);

display :

Since 2.2

gtk_true ()

gboolean            gtk_true                            (void);

All this function does it to return TRUE. This can be useful for example if you want to inhibit the deletion of a window. Of course you should not do this as the user expects a reaction from clicking the close icon of the window...

Example 3. A persistent window

##include <gtk/gtk.h>

int
main (int argc, char **argv)
{
  GtkWidget     *win, *but;

  gtk_init( &argc, &argv );

  win = gtk_window_new (GTK_WINDOW_TOPLEVEL);
  g_signal_connect (win, "delete-event",
                    G_CALLBACK (gtk_true), NULL);
  g_signal_connect (win, "destroy",
            G_CALLBACK (gtk_main_quit), NULL);

  but = gtk_button_new_with_label ("Close yourself. I mean it!");
  g_signal_connect_swapped (but, "clicked",
          G_CALLBACK (gtk_object_destroy), win);
  gtk_container_add (GTK_CONTAINER (win), but);

  gtk_widget_show_all (win);
  gtk_main ();
  return 0;
}

Returns : TRUE

gtk_false ()

gboolean            gtk_false                           (void);

Analogical to gtk_true() this function does nothing but always returns FALSE.

Returns : FALSE

gtk_grab_add ()

void                gtk_grab_add                        (GtkWidget *widget);

Makes widget the current grabbed widget. This means that interaction with other widgets in the same application is blocked and mouse as well as keyboard events are delivered to this widget.

widget : The widget that grabs keyboard and pointer events.

gtk_grab_get_current ()

GtkWidget*          gtk_grab_get_current                (void);

Queries the current grab of the default window group.

Returns : The widget which currently has the grab or NULL if no grab is active.

gtk_grab_remove ()

void                gtk_grab_remove                     (GtkWidget *widget);

Removes the grab from the given widget. You have to pair calls to gtk_grab_add() and gtk_grab_remove().

widget : The widget which gives up the grab.

gtk_init_add ()

void                gtk_init_add                        (GtkFunction function,
                                                         gpointer data);

Registers a function to be called when the mainloop is started.

function : | Function to invoke when gtk_main() is called next.
data : | Data to pass to that function.

gtk_quit_add_destroy ()

void                gtk_quit_add_destroy                (guint main_level,
                                                         GtkObject *object);

Trigger destruction of object in case the mainloop at level main_level is quit.

main_level : | Level of the mainloop which shall trigger the destruction.
object : | Object to be destroyed.

gtk_quit_add ()

guint               gtk_quit_add                        (guint main_level,
                                                         GtkFunction function,
                                                         gpointer data);

Registers a function to be called when an instance of the mainloop is left.

main_level : | Level at which termination the function shall be called. You can pass 0 here to have the function run at the termination of the current mainloop.
function : | The function to call. This should return 0 to be removed from the list of quit handlers. Otherwise the function might be called again.
data : | Pointer to pass when calling function.
Returns : | A handle for this quit handler (you need this for gtk_quit_remove()) or 0 if you passed a NULL pointer in function.

gtk_quit_add_full ()

guint               gtk_quit_add_full                   (guint main_level,
                                                         GtkFunction function,
                                                         GtkCallbackMarshal marshal,
                                                         gpointer data,
                                                         GtkDestroyNotify destroy);

Registers a function to be called when an instance of the mainloop is left. In comparison to gtk_quit_add() this function adds the possibility to pass a marshaller and a function to be called when the quit handler is freed.

The former can be used to run interpreted code instead of a compiled function while the latter can be used to free the information stored in data (while you can do this in function as well)... So this function will mostly be used by GTK+ wrappers for languages other than C.

main_level : | Level at which termination the function shall be called. You can pass 0 here to have the function run at the termination of the current mainloop.
function : | The function to call. This should return 0 to be removed from the list of quit handlers. Otherwise the function might be called again.
marshal : | The marshaller to be used. If this is non-NULL, function is ignored.
data : | Pointer to pass when calling function.
destroy : | Function to call to destruct data. Gets data as argument.
Returns : | A handle for this quit handler (you need this for gtk_quit_remove()) or 0 if you passed a NULL pointer in function.

gtk_quit_remove ()

void                gtk_quit_remove                     (guint quit_handler_id);

Removes a quit handler by its identifier.

quit_handler_id : Identifier for the handler returned when installing it.

gtk_quit_remove_by_data ()

void                gtk_quit_remove_by_data             (gpointer data);

Removes a quit handler identified by its data field.

data : The pointer passed as data to gtk_quit_add() or gtk_quit_add_full().

gtk_timeout_add_full ()

guint               gtk_timeout_add_full                (guint32 interval,
                                                         GtkFunction function,
                                                         GtkCallbackMarshal marshal,
                                                         gpointer data,
                                                         GtkDestroyNotify destroy);

Warning

gtk_timeout_add_full has been deprecated since version 2.4 and should not be used in newly-written code. Use g_timeout_add_full() instead.

Registers a function to be called periodically. The function will be called repeatedly after interval milliseconds until it returns FALSE at which point the timeout is destroyed and will not be called again.

interval : | The time between calls to the function, in milliseconds (1/1000ths of a second.)
function : | The function to call periodically.
marshal : | The marshaller to use instead of the function (if non-NULL).
data : | The data to pass to the function.
destroy : | Function to call when the timeout is destroyed or NULL.
Returns : | A unique id for the event source.

gtk_timeout_add ()

guint               gtk_timeout_add                     (guint32 interval,
                                                         GtkFunction function,
                                                         gpointer data);

Warning

gtk_timeout_add has been deprecated since version 2.4 and should not be used in newly-written code. Use g_timeout_add() instead.

Registers a function to be called periodically. The function will be called repeatedly after interval milliseconds until it returns FALSE at which point the timeout is destroyed and will not be called again.

interval : | The time between calls to the function, in milliseconds (1/1000ths of a second.)
function : | The function to call periodically.
data : | The data to pass to the function.
Returns : | A unique id for the event source.

gtk_timeout_remove ()

void                gtk_timeout_remove                  (guint timeout_handler_id);

Warning

gtk_timeout_remove has been deprecated since version 2.4 and should not be used in newly-written code. Use g_source_remove() instead.

Removes the given timeout destroying all information about it.

timeout_handler_id : The identifier returned when installing the timeout.

gtk_idle_add ()

guint               gtk_idle_add                        (GtkFunction function,
                                                         gpointer data);

Warning

gtk_idle_add has been deprecated since version 2.4 and should not be used in newly-written code. Use g_idle_add() instead.

Causes the mainloop to call the given function whenever no events with higher priority are to be processed. The default priority is GTK_PRIORITY_DEFAULT, which is rather low.

function : | The function to call.
data : | The information to pass to the function.
Returns : | a unique handle for this registration.

gtk_idle_add_priority ()

guint               gtk_idle_add_priority               (gint priority,
                                                         GtkFunction function,
                                                         gpointer data);

Warning

gtk_idle_add_priority has been deprecated since version 2.4 and should not be used in newly-written code. Use g_idle_add_full() instead.

Like gtk_idle_add() this function allows you to have a function called when the event loop is idle. The difference is that you can give a priority different from GTK_PRIORITY_DEFAULT to the idle function.

priority : | The priority which should not be above G_PRIORITY_HIGH_IDLE. Note that you will interfere with GTK+ if you use a priority above GTK_PRIORITY_RESIZE.
function : | The function to call.
data : | Data to pass to that function.
Returns : | A unique id for the event source.

gtk_idle_add_full ()

guint               gtk_idle_add_full                   (gint priority,
                                                         GtkFunction function,
                                                         GtkCallbackMarshal marshal,
                                                         gpointer data,
                                                         GtkDestroyNotify destroy);

Warning

gtk_idle_add_full has been deprecated since version 2.4 and should not be used in newly-written code. Use g_idle_add_full() instead.

Like gtk_idle_add() this function allows you to have a function called when the event loop is idle. The difference is that you can give a priority different from GTK_PRIORITY_DEFAULT to the idle function.

priority : | The priority which should not be above G_PRIORITY_HIGH_IDLE. Note that you will interfere with GTK+ if you use a priority above GTK_PRIORITY_RESIZE.
function : | The function to call.
marshal : | The marshaller to use instead of the function (if non-NULL).
data : | Data to pass to that function.
destroy : | Function to call when the timeout is destroyed or NULL.
Returns : | A unique id for the event source.

gtk_idle_remove ()

void                gtk_idle_remove                     (guint idle_handler_id);

Warning

gtk_idle_remove has been deprecated since version 2.4 and should not be used in newly-written code. Use g_source_remove() instead.

Removes the idle function with the given id.

idle_handler_id : Identifies the idle function to remove.

gtk_idle_remove_by_data ()

void                gtk_idle_remove_by_data             (gpointer data);

Warning

gtk_idle_remove_by_data has been deprecated since version 2.4 and should not be used in newly-written code. Use g_idle_remove_by_data() instead.

Removes the idle function identified by the user data.

data : remove the idle function which was registered with this user data.

gtk_input_add_full ()

guint               gtk_input_add_full                  (gint source,
                                                         GdkInputCondition condition,
                                                         GdkInputFunction function,
                                                         GtkCallbackMarshal marshal,
                                                         gpointer data,
                                                         GtkDestroyNotify destroy);

Warning

gtk_input_add_full has been deprecated since version 2.4 and should not be used in newly-written code. Use g_io_add_watch_full() instead.

Registers a function to be called when a condition becomes true on a file descriptor.

source : | a file descriptor.
condition : | the condition.
function : | The function to call.
marshal : | The marshaller to use instead of the function (if non-NULL).
data : | callback data passed to function.
destroy : | callback function to call with data when the input handler is removed, or NULL.
Returns : | A unique id for the event source; to be used with gtk_input_remove().

gtk_input_remove ()

void                gtk_input_remove                    (guint input_handler_id);

Warning

gtk_input_remove has been deprecated since version 2.4 and should not be used in newly-written code. Use g_source_remove() instead.

Removes the function with the given id.

input_handler_id : Identifies the function to remove.

GTK_PRIORITY_REDRAW

#define GTK_PRIORITY_REDRAW     (G_PRIORITY_HIGH_IDLE + 20)

Warning

GTK_PRIORITY_REDRAW has been deprecated since version 2.4 and should not be used in newly-written code. This macro is deprecated. You should use GDK_PRIORITY_REDRAW instead.

Use this priority for redrawing related stuff. It is used internally by GTK+ to do pending redraws. This priority is lower than GTK_PRIORITY_RESIZE to avoid redrawing a widget just before resizing (and therefore redrawing it again).

GTK_PRIORITY_RESIZE

#define GTK_PRIORITY_RESIZE     (G_PRIORITY_HIGH_IDLE + 10)

Use this priority for resizing related stuff. It is used internally by GTK+ to compute the sizes of widgets. This priority is higher than GTK_PRIORITY_REDRAW to avoid resizing a widget which was just redrawn.

GTK_PRIORITY_HIGH

#define GTK_PRIORITY_HIGH       G_PRIORITY_HIGH

Warning

GTK_PRIORITY_HIGH has been deprecated since version 2.4 and should not be used in newly-written code. This macro is deprecated. You should use G_PRIORITY_HIGH instead.

Use this for high priority timeouts. This priority is never used inside GTK+ so everything running at this priority will be running before anything inside the toolkit.

GTK_PRIORITY_INTERNAL

#define GTK_PRIORITY_INTERNAL   GTK_PRIORITY_REDRAW

Warning

GTK_PRIORITY_INTERNAL is deprecated and should not be used in newly-written code.

This priority is for GTK+ internal stuff. Don't use it in your applications.

GTK_PRIORITY_DEFAULT

#define GTK_PRIORITY_DEFAULT	G_PRIORITY_DEFAULT_IDLE

Warning

GTK_PRIORITY_DEFAULT has been deprecated since version 2.4 and should not be used in newly-written code. This macro is deprecated. You should use G_PRIORITY_DEFAULT_IDLE instead.

Default priority for idle functions.

GTK_PRIORITY_LOW

#define GTK_PRIORITY_LOW	G_PRIORITY_LOW

Warning

GTK_PRIORITY_LOW has been deprecated since version 2.4 and should not be used in newly-written code. This macro is deprecated. You should use G_PRIORITY_LOW instead.

Priority for very unimportant background tasks.

gtk_key_snooper_install ()

guint               gtk_key_snooper_install             (GtkKeySnoopFunc snooper,
                                                         gpointer func_data);

Installs a key snooper function, which will get called on all key events before delivering them normally.

snooper : | a GtkKeySnoopFunc.
func_data : | data to pass to snooper.
Returns : | a unique id for this key snooper for use with gtk_key_snooper_remove().

GtkKeySnoopFunc ()

gint                (*GtkKeySnoopFunc)                  (GtkWidget *grab_widget,
                                                         GdkEventKey *event,
                                                         gpointer func_data);

Key snooper functions are called before normal event delivery. They can be used to implement custom key event handling.

grab_widget : | the widget to which the event will be delivered.
event : | the key event.
func_data : | the func_data supplied to gtk_key_snooper_install().
Returns : | TRUE to stop further processing of event, FALSE to continue.

gtk_key_snooper_remove ()

void                gtk_key_snooper_remove              (guint snooper_handler_id);

Removes the key snooper function with the given id.

snooper_handler_id : Identifies the key snooper to remove.

gtk_get_current_event ()

GdkEvent*           gtk_get_current_event               (void);

Obtains a copy of the event currently being processed by GTK+. For example, if you get a "clicked" signal from GtkButton, the current event will be the GdkEventButton that triggered the "clicked" signal. The returned event must be freed with gdk_event_free(). If there is no current event, the function returns NULL.

Returns : a copy of the current event, or NULL if no current event.

gtk_get_current_event_time ()

guint32             gtk_get_current_event_time          (void);

If there is a current event and it has a timestamp, return that timestamp, otherwise return GDK_CURRENT_TIME.

Returns : the timestamp from the current event, or GDK_CURRENT_TIME.

gtk_get_current_event_state ()

gboolean            gtk_get_current_event_state         (GdkModifierType *state);

If there is a current event and it has a state field, place that state field in state and return TRUE, otherwise return FALSE.

state : | a location to store the state of the current event
Returns : | TRUE if there was a current event and it had a state field

gtk_get_event_widget ()

GtkWidget*          gtk_get_event_widget                (GdkEvent *event);

If event is NULL or the event was not associated with any widget, returns NULL, otherwise returns the widget that received the event originally.

event : | a GdkEvent
Returns : | the widget that originally received event, or NULL

gtk_propagate_event ()

void                gtk_propagate_event                 (GtkWidget *widget,
                                                         GdkEvent *event);

Sends an event to a widget, propagating the event to parent widgets if the event remains unhandled. Events received by GTK+ from GDK normally begin in gtk_main_do_event(). Depending on the type of event, existence of modal dialogs, grabs, etc., the event may be propagated; if so, this function is used. gtk_propagate_event() calls gtk_widget_event() on each widget it decides to send the event to. So gtk_widget_event() is the lowest-level function; it simply emits the "event" and possibly an event-specific signal on a widget. gtk_propagate_event() is a bit higher-level, and gtk_main_do_event() is the highest level.

All that said, you most likely don't want to use any of these functions; synthesizing events is rarely needed. Consider asking on the mailing list for better ways to achieve your goals. For example, use gdk_window_invalidate_rect() or gtk_widget_queue_draw() instead of making up expose events.

widget : | a GtkWidget
event : | an event

See Also

See the GLib manual, especially GMainLoop and signal-related functions such as g_signal_connect().


Graphics Contexts

Graphics Contexts — A shared pool of GdkGC objects

Synopsis

#include <gtk/gtk.h>

GdkGC*              gtk_gc_get                          (gint depth,
                                                         GdkColormap *colormap,
                                                         GdkGCValues *values,
                                                         GdkGCValuesMask values_mask);
void                gtk_gc_release                      (GdkGC *gc);

Description

These functions provide access to a shared pool of GdkGC objects. When a new GdkGC is needed, gtk_gc_get() is called with the required depth, colormap and GdkGCValues. If a GdkGC with the required properties already exists then that is returned. If not, a new GdkGC is created. When the GdkGC is no longer needed, gtk_gc_release() should be called.

Details

gtk_gc_get ()

GdkGC*              gtk_gc_get                          (gint depth,
                                                         GdkColormap *colormap,
                                                         GdkGCValues *values,
                                                         GdkGCValuesMask values_mask);

Gets a GdkGC with the given depth, colormap and GdkGCValues. If a GdkGC with the given properties already exists then it is returned, otherwise a new GdkGC is created. The returned GdkGC should be released with gtk_gc_release() when it is no longer needed.

depth : | the depth of the GdkGC to create.
colormap : | the GdkColormap (FIXME: I don't know why this is needed).
values : | a GdkGCValues struct containing settings for the GdkGC.
values_mask : | a set of flags indicating which of the fields in values has been set.
Returns : | a GdkGC.

gtk_gc_release ()

void                gtk_gc_release                      (GdkGC *gc);

Releases a GdkGC allocated using gtk_gc_get().

gc : a GdkGC.


GtkFileFilter

GtkFileFilter — A filter for selecting a file subset

Synopsis

#include <gtk/gtk.h>

                    GtkFileFilter;
                    GtkFileFilterInfo;
enum                GtkFileFilterFlags;
gboolean            (*GtkFileFilterFunc)                (const GtkFileFilterInfo *filter_info,
                                                         gpointer data);
GtkFileFilter*      gtk_file_filter_new                 (void);
void                gtk_file_filter_set_name            (GtkFileFilter *filter,
                                                         const gchar *name);
const gchar*        gtk_file_filter_get_name            (GtkFileFilter *filter);
void                gtk_file_filter_add_mime_type       (GtkFileFilter *filter,
                                                         const gchar *mime_type);
void                gtk_file_filter_add_pattern         (GtkFileFilter *filter,
                                                         const gchar *pattern);
void                gtk_file_filter_add_pixbuf_formats  (GtkFileFilter *filter);
void                gtk_file_filter_add_custom          (GtkFileFilter *filter,
                                                         GtkFileFilterFlags needed,
                                                         GtkFileFilterFunc func,
                                                         gpointer data,
                                                         GDestroyNotify notify);
GtkFileFilterFlags  gtk_file_filter_get_needed          (GtkFileFilter *filter);
gboolean            gtk_file_filter_filter              (GtkFileFilter *filter,
                                                         const GtkFileFilterInfo *filter_info);

Object Hierarchy

  GObject
   +----GInitiallyUnowned
         +----GtkObject
               +----GtkFileFilter

Description

A GtkFileFilter can be used to restrict the files being shown in a GtkFileChooser. Files can be filtered based on their name (with gtk_file_filter_add_pattern()), on their mime type (with gtk_file_filter_add_mime_type()), or by a custom filter function (with gtk_file_filter_add_custom()).

Filtering by mime types handles aliasing and subclassing of mime types; e.g. a filter for text/plain also matches a file with mime type application/rtf, since application/rtf is a subclass of text/plain. Note that GtkFileFilter allows wildcards for the subtype of a mime type, so you can e.g. filter for image/*.

Normally, filters are used by adding them to a GtkFileChooser, see gtk_file_chooser_add_filter(), but it is also possible to manually use a filter on a file with gtk_file_filter_filter().

Details

GtkFileFilter

typedef struct _GtkFileFilter GtkFileFilter;

The GtkFileFilter struct contains only private fields and should not be directly accessed.

GtkFileFilterInfo

typedef struct {
  GtkFileFilterFlags contains;

  const gchar *filename;
  const gchar *uri;
  const gchar *display_name;
  const gchar *mime_type;
} GtkFileFilterInfo;

A GtkFileFilterInfo struct is used to pass information about the tested file to gtk_file_filter_filter().

GtkFileFilterFlags contains; | Flags indicating which of the following fields need are filled
const gchar *filename; | the filename of the file being tested
const gchar *uri; | the URI for the file being tested
const gchar *display_name; | the string that will be used to display the file in the file chooser
const gchar *mime_type; | the mime type of the file

enum GtkFileFilterFlags

typedef enum {
  GTK_FILE_FILTER_FILENAME     = 1 << 0,
  GTK_FILE_FILTER_URI          = 1 << 1,
  GTK_FILE_FILTER_DISPLAY_NAME = 1 << 2,
  GTK_FILE_FILTER_MIME_TYPE    = 1 << 3
} GtkFileFilterFlags;

These flags indicate what parts of a GtkFileFilterInfo struct are filled or need to be filled.

GTK_FILE_FILTER_FILENAME | the filename of the file being tested
GTK_FILE_FILTER_URI | the URI for the file being tested
GTK_FILE_FILTER_DISPLAY_NAME | the string that will be used to display the file in the file chooser
GTK_FILE_FILTER_MIME_TYPE | the mime type of the file

GtkFileFilterFunc ()

gboolean            (*GtkFileFilterFunc)                (const GtkFileFilterInfo *filter_info,
                                                         gpointer data);

The type of function that is used with custom filters, see gtk_file_filter_add_custom().

filter_info : | a GtkFileFilterInfo that is filled according to the needed flags passed to gtk_file_filter_add_custom()
data : | user data passed to gtk_file_filter_add_custom()
Returns : | TRUE if the file should be displayed

gtk_file_filter_new ()

GtkFileFilter*      gtk_file_filter_new                 (void);

Creates a new GtkFileFilter with no rules added to it. Such a filter doesn't accept any files, so is not particularly useful until you add rules with gtk_file_filter_add_mime_type(), gtk_file_filter_add_pattern(), or gtk_file_filter_add_custom(). To create a filter that accepts any file, use:

GtkFileFilter *filter = gtk_file_filter_new ();
gtk_file_filter_add_pattern (filter, "*");

Returns : a new GtkFileFilter

Since 2.4

gtk_file_filter_set_name ()

void                gtk_file_filter_set_name            (GtkFileFilter *filter,
                                                         const gchar *name);

Sets the human-readable name of the filter; this is the string that will be displayed in the file selector user interface if there is a selectable list of filters.

filter : | a GtkFileFilter
name : | the human-readable-name for the filter, or NULL to remove any existing name.

Since 2.4

gtk_file_filter_get_name ()

const gchar*        gtk_file_filter_get_name            (GtkFileFilter *filter);

Gets the human-readable name for the filter. See gtk_file_filter_set_name().

filter : | a GtkFileFilter
Returns : | The human-readable name of the filter, or NULL. This value is owned by GTK+ and must not be modified or freed.

Since 2.4

gtk_file_filter_add_mime_type ()

void                gtk_file_filter_add_mime_type       (GtkFileFilter *filter,
                                                         const gchar *mime_type);

Adds a rule allowing a given mime type to filter.

filter : | A GtkFileFilter
mime_type : | name of a MIME type

Since 2.4

gtk_file_filter_add_pattern ()

void                gtk_file_filter_add_pattern         (GtkFileFilter *filter,
                                                         const gchar *pattern);

Adds a rule allowing a shell style glob to a filter.

filter : | a GtkFileFilter
pattern : | a shell style glob

Since 2.4

gtk_file_filter_add_pixbuf_formats ()

void                gtk_file_filter_add_pixbuf_formats  (GtkFileFilter *filter);

Adds a rule allowing image files in the formats supported by GdkPixbuf.

filter : a GtkFileFilter

Since 2.6

gtk_file_filter_add_custom ()

void                gtk_file_filter_add_custom          (GtkFileFilter *filter,
                                                         GtkFileFilterFlags needed,
                                                         GtkFileFilterFunc func,
                                                         gpointer data,
                                                         GDestroyNotify notify);

Adds rule to a filter that allows files based on a custom callback function. The bitfield needed which is passed in provides information about what sorts of information that the filter function needs; this allows GTK+ to avoid retrieving expensive information when it isn't needed by the filter.

filter : | a GtkFileFilter
needed : | bitfield of flags indicating the information that the custom filter function needs.
func : | callback function; if the function returns TRUE, then the file will be displayed.
data : | data to pass to func
notify : | function to call to free data when it is no longer needed.

Since 2.4

gtk_file_filter_get_needed ()

GtkFileFilterFlags  gtk_file_filter_get_needed          (GtkFileFilter *filter);

Gets the fields that need to be filled in for the structure passed to gtk_file_filter_filter()

This function will not typically be used by applications; it is intended principally for use in the implementation of GtkFileChooser.

filter : | a GtkFileFilter
Returns : | bitfield of flags indicating needed fields when calling gtk_file_filter_filter()

Since 2.4

gtk_file_filter_filter ()

gboolean            gtk_file_filter_filter              (GtkFileFilter *filter,
                                                         const GtkFileFilterInfo *filter_info);

Tests whether a file should be displayed according to filter. The GtkFileFilterInfo structure filter_info should include the fields returned from gtk_file_filter_get_needed().

This function will not typically be used by applications; it is intended principally for use in the implementation of GtkFileChooser.

filter : | a GtkFileFilter
filter_info : | a GtkFileFilterInfo structure containing information about a file.
Returns : | TRUE if the file should be displayed

Since 2.4

See Also

GtkFileChooser


GtkPaperSize

GtkPaperSize — Support for named paper sizes

Synopsis

#include <gtk/gtk.h>

                    GtkPaperSize;
enum                GtkUnit;
#define             GTK_PAPER_NAME_A3
#define             GTK_PAPER_NAME_A4
#define             GTK_PAPER_NAME_A5
#define             GTK_PAPER_NAME_B5
#define             GTK_PAPER_NAME_LETTER
#define             GTK_PAPER_NAME_EXECUTIVE
#define             GTK_PAPER_NAME_LEGAL
GtkPaperSize*       gtk_paper_size_new                  (const gchar *name);
GtkPaperSize*       gtk_paper_size_new_from_ppd         (const gchar *ppd_name,
                                                         const gchar *ppd_display_name,
                                                         gdouble width,
                                                         gdouble height);
GtkPaperSize*       gtk_paper_size_new_custom           (const gchar *name,
                                                         const gchar *display_name,
                                                         gdouble width,
                                                         gdouble height,
                                                         GtkUnit unit);
GtkPaperSize*       gtk_paper_size_copy                 (GtkPaperSize *other);
void                gtk_paper_size_free                 (GtkPaperSize *size);
gboolean            gtk_paper_size_is_equal             (GtkPaperSize *size1,
                                                         GtkPaperSize *size2);
const gchar*        gtk_paper_size_get_name             (GtkPaperSize *size);
const gchar*        gtk_paper_size_get_display_name     (GtkPaperSize *size);
const gchar*        gtk_paper_size_get_ppd_name         (GtkPaperSize *size);
gdouble             gtk_paper_size_get_width            (GtkPaperSize *size,
                                                         GtkUnit unit);
gdouble             gtk_paper_size_get_height           (GtkPaperSize *size,
                                                         GtkUnit unit);
gboolean            gtk_paper_size_is_custom            (GtkPaperSize *size);
void                gtk_paper_size_set_size             (GtkPaperSize *size,
                                                         gdouble width,
                                                         gdouble height,
                                                         GtkUnit unit);
gdouble             gtk_paper_size_get_default_top_margin
                                                        (GtkPaperSize *size,
                                                         GtkUnit unit);
gdouble             gtk_paper_size_get_default_bottom_margin
                                                        (GtkPaperSize *size,
                                                         GtkUnit unit);
gdouble             gtk_paper_size_get_default_left_margin
                                                        (GtkPaperSize *size,
                                                         GtkUnit unit);
gdouble             gtk_paper_size_get_default_right_margin
                                                        (GtkPaperSize *size,
                                                         GtkUnit unit);
const gchar*        gtk_paper_size_get_default          (void);

Description

GtkPaperSize handles paper sizes. It uses the standard called "PWG 5101.1-2002 PWG: Standard for Media Standardized Names" to name the paper sizes (and to get the data for the page sizes). In addition to standard paper sizes, GtkPaperSize allows to construct custom paper sizes with arbitrary dimensions.

The GtkPaperSize object stores not only the dimensions (width and height) of a paper size and its name, it also provides default print margins.

Printing support has been added in GTK+ 2.10.

Details

GtkPaperSize

typedef struct _GtkPaperSize GtkPaperSize;

enum GtkUnit

typedef enum {
  GTK_UNIT_PIXEL,
  GTK_UNIT_POINTS,
  GTK_UNIT_INCH,
  GTK_UNIT_MM
} GtkUnit;

GTK_PAPER_NAME_A3

#define GTK_PAPER_NAME_A3 "iso_a3"

Name for the A4 paper size.

GTK_PAPER_NAME_A4

#define GTK_PAPER_NAME_A4 "iso_a4"

Name for the A4 paper size.

GTK_PAPER_NAME_A5

#define GTK_PAPER_NAME_A5 "iso_a5"

Name for the A5 paper size.

GTK_PAPER_NAME_B5

#define GTK_PAPER_NAME_B5 "iso_b5"

Name for the B5 paper size.

GTK_PAPER_NAME_LETTER

#define GTK_PAPER_NAME_LETTER "na_letter"

Name for the Letter paper size.

GTK_PAPER_NAME_EXECUTIVE

#define GTK_PAPER_NAME_EXECUTIVE "na_executive"

Name for the Executive paper size.

GTK_PAPER_NAME_LEGAL

#define GTK_PAPER_NAME_LEGAL "na_legal"

Name for the Legal paper size.

gtk_paper_size_new ()

GtkPaperSize*       gtk_paper_size_new                  (const gchar *name);

Creates a new GtkPaperSize object by parsing a PWG 5101.1-2002 PWG paper name.

If name is NULL, the default paper size is returned, see gtk_paper_size_get_default().

name : | a paper size name, or NULL
Returns : | a new GtkPaperSize, use gtk_paper_size_free() to free it

Since 2.10

gtk_paper_size_new_from_ppd ()

GtkPaperSize*       gtk_paper_size_new_from_ppd         (const gchar *ppd_name,
                                                         const gchar *ppd_display_name,
                                                         gdouble width,
                                                         gdouble height);

Creates a new GtkPaperSize object by using PPD information.

If ppd_name is not a recognized PPD paper name, ppd_display_name, width and height are used to construct a custom GtkPaperSize object.

ppd_name : | a PPD paper name
ppd_display_name : | the corresponding human-readable name
width : | the paper width, in points
height : | the paper height in points
Returns : | a new GtkPaperSize, use gtk_paper_size_free() to free it

Since 2.10

gtk_paper_size_new_custom ()

GtkPaperSize*       gtk_paper_size_new_custom           (const gchar *name,
                                                         const gchar *display_name,
                                                         gdouble width,
                                                         gdouble height,
                                                         GtkUnit unit);

Creates a new GtkPaperSize object with the given parameters.

name : | the paper name
display_name : | the human-readable name
width : | the paper width, in units of unit
height : | the paper height, in units of unit
unit : | the unit for width and height
Returns : | a new GtkPaperSize object, use gtk_paper_size_free() to free it

Since 2.10

gtk_paper_size_copy ()

GtkPaperSize*       gtk_paper_size_copy                 (GtkPaperSize *other);

Copies an existing GtkPaperSize.

other : | a GtkPaperSize
Returns : | a copy of other

Since 2.10

gtk_paper_size_free ()

void                gtk_paper_size_free                 (GtkPaperSize *size);

Free the given GtkPaperSize object.

size : a GtkPaperSize

Since 2.10

gtk_paper_size_is_equal ()

gboolean            gtk_paper_size_is_equal             (GtkPaperSize *size1,
                                                         GtkPaperSize *size2);

Compares two GtkPaperSize objects.

size1 : | a GtkPaperSize object
size2 : | another GtkPaperSize object
Returns : | TRUE, if size1 and size2 represent the same paper size

Since 2.10

gtk_paper_size_get_name ()

const gchar*        gtk_paper_size_get_name             (GtkPaperSize *size);

Gets the name of the GtkPaperSize.

size : | a GtkPaperSize object
Returns : | the name of size

Since 2.10

gtk_paper_size_get_display_name ()

const gchar*        gtk_paper_size_get_display_name     (GtkPaperSize *size);

Gets the human-readable name of the GtkPaperSize.

size : | a GtkPaperSize object
Returns : | the human-readable name of size

Since 2.10

gtk_paper_size_get_ppd_name ()

const gchar*        gtk_paper_size_get_ppd_name         (GtkPaperSize *size);

Gets the PPD name of the GtkPaperSize, which may be NULL.

size : | a GtkPaperSize object
Returns : | the PPD name of size

Since 2.10

gtk_paper_size_get_width ()

gdouble             gtk_paper_size_get_width            (GtkPaperSize *size,
                                                         GtkUnit unit);

Gets the paper width of the GtkPaperSize, in units of unit.

size : | a GtkPaperSize object
unit : | the unit for the return value
Returns : | the paper width

Since 2.10

gtk_paper_size_get_height ()

gdouble             gtk_paper_size_get_height           (GtkPaperSize *size,
                                                         GtkUnit unit);

Gets the paper height of the GtkPaperSize, in units of unit.

size : | a GtkPaperSize object
unit : | the unit for the return value
Returns : | the paper height

Since 2.10

gtk_paper_size_is_custom ()

gboolean            gtk_paper_size_is_custom            (GtkPaperSize *size);

Returns TRUE if size is not a standard paper size.

size : | a GtkPaperSize object
Returns : | whether size is a custom paper size.

gtk_paper_size_set_size ()

void                gtk_paper_size_set_size             (GtkPaperSize *size,
                                                         gdouble width,
                                                         gdouble height,
                                                         GtkUnit unit);

Changes the dimensions of a size to width x height.

size : | a custom GtkPaperSize object
width : | the new width in units of unit
height : | the new height in units of unit
unit : | the unit for width and height

Since 2.10

gtk_paper_size_get_default_top_margin ()

gdouble             gtk_paper_size_get_default_top_margin
                                                        (GtkPaperSize *size,
                                                         GtkUnit unit);

Gets the default top margin for the GtkPaperSize.

size : | a GtkPaperSize object
unit : | the unit for the return value
Returns : | the default top margin

Since 2.10

gtk_paper_size_get_default_bottom_margin ()

gdouble             gtk_paper_size_get_default_bottom_margin
                                                        (GtkPaperSize *size,
                                                         GtkUnit unit);

Gets the default bottom margin for the GtkPaperSize.

size : | a GtkPaperSize object
unit : | the unit for the return value
Returns : | the default bottom margin

Since 2.10

gtk_paper_size_get_default_left_margin ()

gdouble             gtk_paper_size_get_default_left_margin
                                                        (GtkPaperSize *size,
                                                         GtkUnit unit);

Gets the default left margin for the GtkPaperSize.

size : | a GtkPaperSize object
unit : | the unit for the return value
Returns : | the default left margin

Since 2.10

gtk_paper_size_get_default_right_margin ()

gdouble             gtk_paper_size_get_default_right_margin
                                                        (GtkPaperSize *size,
                                                         GtkUnit unit);

Gets the default right margin for the GtkPaperSize.

size : | a GtkPaperSize object
unit : | the unit for the return value
Returns : | the default right margin

Since 2.10

gtk_paper_size_get_default ()

const gchar*        gtk_paper_size_get_default          (void);

Returns the name of the default paper size, which depends on the current locale.

Returns : the name of the default paper size. The string is owned by GTK+ and should not be modified.

Since 2.10

See Also

GtkPageSetup


GtkTextIter

GtkTextIter — Text buffer iterator

Synopsis

#include <gtk/gtk.h>

                    GtkTextIter;
GtkTextBuffer*      gtk_text_iter_get_buffer            (const GtkTextIter *iter);
GtkTextIter*        gtk_text_iter_copy                  (const GtkTextIter *iter);
void                gtk_text_iter_free                  (GtkTextIter *iter);
gint                gtk_text_iter_get_offset            (const GtkTextIter *iter);
gint                gtk_text_iter_get_line              (const GtkTextIter *iter);
gint                gtk_text_iter_get_line_offset       (const GtkTextIter *iter);
gint                gtk_text_iter_get_line_index        (const GtkTextIter *iter);
gint                gtk_text_iter_get_visible_line_index
                                                        (const GtkTextIter *iter);
gint                gtk_text_iter_get_visible_line_offset
                                                        (const GtkTextIter *iter);
gunichar            gtk_text_iter_get_char              (const GtkTextIter *iter);
gchar*              gtk_text_iter_get_slice             (const GtkTextIter *start,
                                                         const GtkTextIter *end);
gchar*              gtk_text_iter_get_text              (const GtkTextIter *start,
                                                         const GtkTextIter *end);
gchar*              gtk_text_iter_get_visible_slice     (const GtkTextIter *start,
                                                         const GtkTextIter *end);
gchar*              gtk_text_iter_get_visible_text      (const GtkTextIter *start,
                                                         const GtkTextIter *end);
GdkPixbuf*          gtk_text_iter_get_pixbuf            (const GtkTextIter *iter);
GSList*             gtk_text_iter_get_marks             (const GtkTextIter *iter);
GSList*             gtk_text_iter_get_toggled_tags      (const GtkTextIter *iter,
                                                         gboolean toggled_on);
GtkTextChildAnchor* gtk_text_iter_get_child_anchor      (const GtkTextIter *iter);
gboolean            gtk_text_iter_begins_tag            (const GtkTextIter *iter,
                                                         GtkTextTag *tag);
gboolean            gtk_text_iter_ends_tag              (const GtkTextIter *iter,
                                                         GtkTextTag *tag);
gboolean            gtk_text_iter_toggles_tag           (const GtkTextIter *iter,
                                                         GtkTextTag *tag);
gboolean            gtk_text_iter_has_tag               (const GtkTextIter *iter,
                                                         GtkTextTag *tag);
GSList*             gtk_text_iter_get_tags              (const GtkTextIter *iter);
gboolean            gtk_text_iter_editable              (const GtkTextIter *iter,
                                                         gboolean default_setting);
gboolean            gtk_text_iter_can_insert            (const GtkTextIter *iter,
                                                         gboolean default_editability);
gboolean            gtk_text_iter_starts_word           (const GtkTextIter *iter);
gboolean            gtk_text_iter_ends_word             (const GtkTextIter *iter);
gboolean            gtk_text_iter_inside_word           (const GtkTextIter *iter);
gboolean            gtk_text_iter_starts_line           (const GtkTextIter *iter);
gboolean            gtk_text_iter_ends_line             (const GtkTextIter *iter);
gboolean            gtk_text_iter_starts_sentence       (const GtkTextIter *iter);
gboolean            gtk_text_iter_ends_sentence         (const GtkTextIter *iter);
gboolean            gtk_text_iter_inside_sentence       (const GtkTextIter *iter);
gboolean            gtk_text_iter_is_cursor_position    (const GtkTextIter *iter);
gint                gtk_text_iter_get_chars_in_line     (const GtkTextIter *iter);
gint                gtk_text_iter_get_bytes_in_line     (const GtkTextIter *iter);
gboolean            gtk_text_iter_get_attributes        (const GtkTextIter *iter,
                                                         GtkTextAttributes *values);
PangoLanguage*      gtk_text_iter_get_language          (const GtkTextIter *iter);
gboolean            gtk_text_iter_is_end                (const GtkTextIter *iter);
gboolean            gtk_text_iter_is_start              (const GtkTextIter *iter);
gboolean            gtk_text_iter_forward_char          (GtkTextIter *iter);
gboolean            gtk_text_iter_backward_char         (GtkTextIter *iter);
gboolean            gtk_text_iter_forward_chars         (GtkTextIter *iter,
                                                         gint count);
gboolean            gtk_text_iter_backward_chars        (GtkTextIter *iter,
                                                         gint count);
gboolean            gtk_text_iter_forward_line          (GtkTextIter *iter);
gboolean            gtk_text_iter_backward_line         (GtkTextIter *iter);
gboolean            gtk_text_iter_forward_lines         (GtkTextIter *iter,
                                                         gint count);
gboolean            gtk_text_iter_backward_lines        (GtkTextIter *iter,
                                                         gint count);
gboolean            gtk_text_iter_forward_word_ends     (GtkTextIter *iter,
                                                         gint count);
gboolean            gtk_text_iter_backward_word_starts  (GtkTextIter *iter,
                                                         gint count);
gboolean            gtk_text_iter_forward_word_end      (GtkTextIter *iter);
gboolean            gtk_text_iter_backward_word_start   (GtkTextIter *iter);
gboolean            gtk_text_iter_forward_cursor_position
                                                        (GtkTextIter *iter);
gboolean            gtk_text_iter_backward_cursor_position
                                                        (GtkTextIter *iter);
gboolean            gtk_text_iter_forward_cursor_positions
                                                        (GtkTextIter *iter,
                                                         gint count);
gboolean            gtk_text_iter_backward_cursor_positions
                                                        (GtkTextIter *iter,
                                                         gint count);
gboolean            gtk_text_iter_backward_sentence_start
                                                        (GtkTextIter *iter);
gboolean            gtk_text_iter_backward_sentence_starts
                                                        (GtkTextIter *iter,
                                                         gint count);
gboolean            gtk_text_iter_forward_sentence_end  (GtkTextIter *iter);
gboolean            gtk_text_iter_forward_sentence_ends (GtkTextIter *iter,
                                                         gint count);
gboolean            gtk_text_iter_forward_visible_word_ends
                                                        (GtkTextIter *iter,
                                                         gint count);
gboolean            gtk_text_iter_backward_visible_word_starts
                                                        (GtkTextIter *iter,
                                                         gint count);
gboolean            gtk_text_iter_forward_visible_word_end
                                                        (GtkTextIter *iter);
gboolean            gtk_text_iter_backward_visible_word_start
                                                        (GtkTextIter *iter);
gboolean            gtk_text_iter_forward_visible_cursor_position
                                                        (GtkTextIter *iter);
gboolean            gtk_text_iter_backward_visible_cursor_position
                                                        (GtkTextIter *iter);
gboolean            gtk_text_iter_forward_visible_cursor_positions
                                                        (GtkTextIter *iter,
                                                         gint count);
gboolean            gtk_text_iter_backward_visible_cursor_positions
                                                        (GtkTextIter *iter,
                                                         gint count);
gboolean            gtk_text_iter_forward_visible_line  (GtkTextIter *iter);
gboolean            gtk_text_iter_backward_visible_line (GtkTextIter *iter);
gboolean            gtk_text_iter_forward_visible_lines (GtkTextIter *iter,
                                                         gint count);
gboolean            gtk_text_iter_backward_visible_lines
                                                        (GtkTextIter *iter,
                                                         gint count);
void                gtk_text_iter_set_offset            (GtkTextIter *iter,
                                                         gint char_offset);
void                gtk_text_iter_set_line              (GtkTextIter *iter,
                                                         gint line_number);
void                gtk_text_iter_set_line_offset       (GtkTextIter *iter,
                                                         gint char_on_line);
void                gtk_text_iter_set_line_index        (GtkTextIter *iter,
                                                         gint byte_on_line);
void                gtk_text_iter_set_visible_line_index
                                                        (GtkTextIter *iter,
                                                         gint byte_on_line);
void                gtk_text_iter_set_visible_line_offset
                                                        (GtkTextIter *iter,
                                                         gint char_on_line);
void                gtk_text_iter_forward_to_end        (GtkTextIter *iter);
gboolean            gtk_text_iter_forward_to_line_end   (GtkTextIter *iter);
gboolean            gtk_text_iter_forward_to_tag_toggle (GtkTextIter *iter,
                                                         GtkTextTag *tag);
gboolean            gtk_text_iter_backward_to_tag_toggle
                                                        (GtkTextIter *iter,
                                                         GtkTextTag *tag);
gboolean            (*GtkTextCharPredicate)             (gunichar ch,
                                                         gpointer user_data);
gboolean            gtk_text_iter_forward_find_char     (GtkTextIter *iter,
                                                         GtkTextCharPredicate pred,
                                                         gpointer user_data,
                                                         const GtkTextIter *limit);
gboolean            gtk_text_iter_backward_find_char    (GtkTextIter *iter,
                                                         GtkTextCharPredicate pred,
                                                         gpointer user_data,
                                                         const GtkTextIter *limit);
enum                GtkTextSearchFlags;
gboolean            gtk_text_iter_forward_search        (const GtkTextIter *iter,
                                                         const gchar *str,
                                                         GtkTextSearchFlags flags,
                                                         GtkTextIter *match_start,
                                                         GtkTextIter *match_end,
                                                         const GtkTextIter *limit);
gboolean            gtk_text_iter_backward_search       (const GtkTextIter *iter,
                                                         const gchar *str,
                                                         GtkTextSearchFlags flags,
                                                         GtkTextIter *match_start,
                                                         GtkTextIter *match_end,
                                                         const GtkTextIter *limit);
gboolean            gtk_text_iter_equal                 (const GtkTextIter *lhs,
                                                         const GtkTextIter *rhs);
gint                gtk_text_iter_compare               (const GtkTextIter *lhs,
                                                         const GtkTextIter *rhs);
gboolean            gtk_text_iter_in_range              (const GtkTextIter *iter,
                                                         const GtkTextIter *start,
                                                         const GtkTextIter *end);
void                gtk_text_iter_order                 (GtkTextIter *first,
                                                         GtkTextIter *second);

Description

You may wish to begin by reading the text widget conceptual overview which gives an overview of all the objects and data types related to the text widget and how they work together.

Details

GtkTextIter

typedef struct {
  /* GtkTextIter is an opaque datatype; ignore all these fields.
   * Initialize the iter with gtk_text_buffer_get_iter_*
   * functions
   */
} GtkTextIter;

gtk_text_iter_get_buffer ()

GtkTextBuffer*      gtk_text_iter_get_buffer            (const GtkTextIter *iter);

Returns the GtkTextBuffer this iterator is associated with.

iter : | an iterator
Returns : | the buffer

gtk_text_iter_copy ()

GtkTextIter*        gtk_text_iter_copy                  (const GtkTextIter *iter);

Creates a dynamically-allocated copy of an iterator. This function is not useful in applications, because iterators can be copied with a simple assignment (GtkTextIter i = j;). The function is used by language bindings.

iter : | an iterator
Returns : | a copy of the iter, free with gtk_text_iter_free()

gtk_text_iter_free ()

void                gtk_text_iter_free                  (GtkTextIter *iter);

Free an iterator allocated on the heap. This function is intended for use in language bindings, and is not especially useful for applications, because iterators can simply be allocated on the stack.

iter : a dynamically-allocated iterator

gtk_text_iter_get_offset ()

gint                gtk_text_iter_get_offset            (const GtkTextIter *iter);

Returns the character offset of an iterator. Each character in a GtkTextBuffer has an offset, starting with 0 for the first character in the buffer. Use gtk_text_buffer_get_iter_at_offset() to convert an offset back into an iterator.

iter : | an iterator
Returns : | a character offset

gtk_text_iter_get_line ()

gint                gtk_text_iter_get_line              (const GtkTextIter *iter);

Returns the line number containing the iterator. Lines in a GtkTextBuffer are numbered beginning with 0 for the first line in the buffer.

iter : | an iterator
Returns : | a line number

gtk_text_iter_get_line_offset ()

gint                gtk_text_iter_get_line_offset       (const GtkTextIter *iter);

Returns the character offset of the iterator, counting from the start of a newline-terminated line. The first character on the line has offset 0.

iter : | an iterator
Returns : | offset from start of line

gtk_text_iter_get_line_index ()

gint                gtk_text_iter_get_line_index        (const GtkTextIter *iter);

Returns the byte index of the iterator, counting from the start of a newline-terminated line. Remember that GtkTextBuffer encodes text in UTF-8, and that characters can require a variable number of bytes to represent.

iter : | an iterator
Returns : | distance from start of line, in bytes

gtk_text_iter_get_visible_line_index ()

gint                gtk_text_iter_get_visible_line_index
                                                        (const GtkTextIter *iter);

Returns the number of bytes from the start of the line to the given iter, not counting bytes that are invisible due to tags with the "invisible" flag toggled on.

iter : | a GtkTextIter
Returns : | byte index of iter with respect to the start of the line

gtk_text_iter_get_visible_line_offset ()

gint                gtk_text_iter_get_visible_line_offset
                                                        (const GtkTextIter *iter);

Returns the offset in characters from the start of the line to the given iter, not counting characters that are invisible due to tags with the "invisible" flag toggled on.

iter : | a GtkTextIter
Returns : | offset in visible characters from the start of the line

gtk_text_iter_get_char ()

gunichar            gtk_text_iter_get_char              (const GtkTextIter *iter);

Returns the Unicode character at this iterator. (Equivalent to operator* on a C++ iterator.) If the element at this iterator is a non-character element, such as an image embedded in the buffer, the Unicode "unknown" character 0xFFFC is returned. If invoked on the end iterator, zero is returned; zero is not a valid Unicode character. So you can write a loop which ends when gtk_text_iter_get_char() returns 0.

iter : | an iterator
Returns : | a Unicode character, or 0 if iter is not dereferenceable

gtk_text_iter_get_slice ()

gchar*              gtk_text_iter_get_slice             (const GtkTextIter *start,
                                                         const GtkTextIter *end);

Returns the text in the given range. A "slice" is an array of characters encoded in UTF-8 format, including the Unicode "unknown" character 0xFFFC for iterable non-character elements in the buffer, such as images. Because images are encoded in the slice, byte and character offsets in the returned array will correspond to byte offsets in the text buffer. Note that 0xFFFC can occur in normal text as well, so it is not a reliable indicator that a pixbuf or widget is in the buffer.

start : | iterator at start of a range
end : | iterator at end of a range
Returns : | slice of text from the buffer

gtk_text_iter_get_text ()

gchar*              gtk_text_iter_get_text              (const GtkTextIter *start,
                                                         const GtkTextIter *end);

Returns text in the given range. If the range contains non-text elements such as images, the character and byte offsets in the returned string will not correspond to character and byte offsets in the buffer. If you want offsets to correspond, see gtk_text_iter_get_slice().

start : | iterator at start of a range
end : | iterator at end of a range
Returns : | array of characters from the buffer

gtk_text_iter_get_visible_slice ()

gchar*              gtk_text_iter_get_visible_slice     (const GtkTextIter *start,
                                                         const GtkTextIter *end);

Like gtk_text_iter_get_slice(), but invisible text is not included. Invisible text is usually invisible because a GtkTextTag with the "invisible" attribute turned on has been applied to it.

start : | iterator at start of range
end : | iterator at end of range
Returns : | slice of text from the buffer

gtk_text_iter_get_visible_text ()

gchar*              gtk_text_iter_get_visible_text      (const GtkTextIter *start,
                                                         const GtkTextIter *end);

Like gtk_text_iter_get_text(), but invisible text is not included. Invisible text is usually invisible because a GtkTextTag with the "invisible" attribute turned on has been applied to it.

start : | iterator at start of range
end : | iterator at end of range
Returns : | string containing visible text in the range

gtk_text_iter_get_pixbuf ()

GdkPixbuf*          gtk_text_iter_get_pixbuf            (const GtkTextIter *iter);

If the element at iter is a pixbuf, the pixbuf is returned (with no new reference count added). Otherwise, NULL is returned.

iter : | an iterator
Returns : | the pixbuf at iter

gtk_text_iter_get_marks ()

GSList*             gtk_text_iter_get_marks             (const GtkTextIter *iter);

Returns a list of all GtkTextMark at this location. Because marks are not iterable (they don't take up any "space" in the buffer, they are just marks in between iterable locations), multiple marks can exist in the same place. The returned list is not in any meaningful order.

iter : | an iterator
Returns : | list of GtkTextMark

gtk_text_iter_get_toggled_tags ()

GSList*             gtk_text_iter_get_toggled_tags      (const GtkTextIter *iter,
                                                         gboolean toggled_on);

Returns a list of GtkTextTag that are toggled on or off at this point. (If toggled_on is TRUE, the list contains tags that are toggled on.) If a tag is toggled on at iter, then some non-empty range of characters following iter has that tag applied to it. If a tag is toggled off, then some non-empty range following iter does not have the tag applied to it.

iter : | an iterator
toggled_on : | TRUE to get toggled-on tags
Returns : | tags toggled at this point

gtk_text_iter_get_child_anchor ()

GtkTextChildAnchor* gtk_text_iter_get_child_anchor      (const GtkTextIter *iter);

If the location at iter contains a child anchor, the anchor is returned (with no new reference count added). Otherwise, NULL is returned.

iter : | an iterator
Returns : | the anchor at iter

gtk_text_iter_begins_tag ()

gboolean            gtk_text_iter_begins_tag            (const GtkTextIter *iter,
                                                         GtkTextTag *tag);

Returns TRUE if tag is toggled on at exactly this point. If tag is NULL, returns TRUE if any tag is toggled on at this point. Note that the gtk_text_iter_begins_tag() returns TRUE if iter is the start of the tagged range; gtk_text_iter_has_tag() tells you whether an iterator is within a tagged range.

iter : | an iterator
tag : | a GtkTextTag, or NULL
Returns : | whether iter is the start of a range tagged with tag

gtk_text_iter_ends_tag ()

gboolean            gtk_text_iter_ends_tag              (const GtkTextIter *iter,
                                                         GtkTextTag *tag);

Returns TRUE if tag is toggled off at exactly this point. If tag is NULL, returns TRUE if any tag is toggled off at this point. Note that the gtk_text_iter_ends_tag() returns TRUE if iter is the end of the tagged range; gtk_text_iter_has_tag() tells you whether an iterator is within a tagged range.

iter : | an iterator
tag : | a GtkTextTag, or NULL
Returns : | whether iter is the end of a range tagged with tag

gtk_text_iter_toggles_tag ()

gboolean            gtk_text_iter_toggles_tag           (const GtkTextIter *iter,
                                                         GtkTextTag *tag);

This is equivalent to (gtk_text_iter_begins_tag() || gtk_text_iter_ends_tag()), i.e. it tells you whether a range with tag applied to it begins or ends at iter.

iter : | an iterator
tag : | a GtkTextTag, or NULL
Returns : | whether tag is toggled on or off at iter

gtk_text_iter_has_tag ()

gboolean            gtk_text_iter_has_tag               (const GtkTextIter *iter,
                                                         GtkTextTag *tag);

Returns TRUE if iter is within a range tagged with tag.

iter : | an iterator
tag : | a GtkTextTag
Returns : | whether iter is tagged with tag

gtk_text_iter_get_tags ()

GSList*             gtk_text_iter_get_tags              (const GtkTextIter *iter);

Returns a list of tags that apply to iter, in ascending order of priority (highest-priority tags are last). The GtkTextTag in the list don't have a reference added, but you have to free the list itself.

iter : | a GtkTextIter
Returns : | list of GtkTextTag

gtk_text_iter_editable ()

gboolean            gtk_text_iter_editable              (const GtkTextIter *iter,
                                                         gboolean default_setting);

Returns whether the character at iter is within an editable region of text. Non-editable text is "locked" and can't be changed by the user via GtkTextView. This function is simply a convenience wrapper around gtk_text_iter_get_attributes(). If no tags applied to this text affect editability, default_setting will be returned.

You don't want to use this function to decide whether text can be inserted at iter, because for insertion you don't want to know whether the char at iter is inside an editable range, you want to know whether a new character inserted at iter would be inside an editable range. Use gtk_text_iter_can_insert() to handle this case.

iter : | an iterator
default_setting : | TRUE if text is editable by default
Returns : | whether iter is inside an editable range

gtk_text_iter_can_insert ()

gboolean            gtk_text_iter_can_insert            (const GtkTextIter *iter,
                                                         gboolean default_editability);

Considering the default editability of the buffer, and tags that affect editability, determines whether text inserted at iter would be editable. If text inserted at iter would be editable then the user should be allowed to insert text at iter. gtk_text_buffer_insert_interactive() uses this function to decide whether insertions are allowed at a given position.

iter : | an iterator
default_editability : | TRUE if text is editable by default
Returns : | whether text inserted at iter would be editable

gtk_text_iter_starts_word ()

gboolean            gtk_text_iter_starts_word           (const GtkTextIter *iter);

Determines whether iter begins a natural-language word. Word breaks are determined by Pango and should be correct for nearly any language (if not, the correct fix would be to the Pango word break algorithms).

iter : | a GtkTextIter
Returns : | TRUE if iter is at the start of a word

gtk_text_iter_ends_word ()

gboolean            gtk_text_iter_ends_word             (const GtkTextIter *iter);

Determines whether iter ends a natural-language word. Word breaks are determined by Pango and should be correct for nearly any language (if not, the correct fix would be to the Pango word break algorithms).

iter : | a GtkTextIter
Returns : | TRUE if iter is at the end of a word

gtk_text_iter_inside_word ()

gboolean            gtk_text_iter_inside_word           (const GtkTextIter *iter);

Determines whether iter is inside a natural-language word (as opposed to say inside some whitespace). Word breaks are determined by Pango and should be correct for nearly any language (if not, the correct fix would be to the Pango word break algorithms).

iter : | a GtkTextIter
Returns : | TRUE if iter is inside a word

gtk_text_iter_starts_line ()

gboolean            gtk_text_iter_starts_line           (const GtkTextIter *iter);

Returns TRUE if iter begins a paragraph, i.e. if gtk_text_iter_get_line_offset() would return 0. However this function is potentially more efficient than gtk_text_iter_get_line_offset() because it doesn't have to compute the offset, it just has to see whether it's 0.

iter : | an iterator
Returns : | whether iter begins a line

gtk_text_iter_ends_line ()

gboolean            gtk_text_iter_ends_line             (const GtkTextIter *iter);

Returns TRUE if iter points to the start of the paragraph delimiter characters for a line (delimiters will be either a newline, a carriage return, a carriage return followed by a newline, or a Unicode paragraph separator character). Note that an iterator pointing to the \n of a \r\n pair will not be counted as the end of a line, the line ends before the \r. The end iterator is considered to be at the end of a line, even though there are no paragraph delimiter chars there.

iter : | an iterator
Returns : | whether iter is at the end of a line

gtk_text_iter_starts_sentence ()

gboolean            gtk_text_iter_starts_sentence       (const GtkTextIter *iter);

Determines whether iter begins a sentence. Sentence boundaries are determined by Pango and should be correct for nearly any language (if not, the correct fix would be to the Pango text boundary algorithms).

iter : | a GtkTextIter
Returns : | TRUE if iter is at the start of a sentence.

gtk_text_iter_ends_sentence ()

gboolean            gtk_text_iter_ends_sentence         (const GtkTextIter *iter);

Determines whether iter ends a sentence. Sentence boundaries are determined by Pango and should be correct for nearly any language (if not, the correct fix would be to the Pango text boundary algorithms).

iter : | a GtkTextIter
Returns : | TRUE if iter is at the end of a sentence.

gtk_text_iter_inside_sentence ()

gboolean            gtk_text_iter_inside_sentence       (const GtkTextIter *iter);

Determines whether iter is inside a sentence (as opposed to in between two sentences, e.g. after a period and before the first letter of the next sentence). Sentence boundaries are determined by Pango and should be correct for nearly any language (if not, the correct fix would be to the Pango text boundary algorithms).

iter : | a GtkTextIter
Returns : | TRUE if iter is inside a sentence.

gtk_text_iter_is_cursor_position ()

gboolean            gtk_text_iter_is_cursor_position    (const GtkTextIter *iter);

See gtk_text_iter_forward_cursor_position() or PangoLogAttr or pango_break() for details on what a cursor position is.

iter : | a GtkTextIter
Returns : | TRUE if the cursor can be placed at iter

gtk_text_iter_get_chars_in_line ()

gint                gtk_text_iter_get_chars_in_line     (const GtkTextIter *iter);

Returns the number of characters in the line containing iter, including the paragraph delimiters.

iter : | an iterator
Returns : | number of characters in the line

gtk_text_iter_get_bytes_in_line ()

gint                gtk_text_iter_get_bytes_in_line     (const GtkTextIter *iter);

Returns the number of bytes in the line containing iter, including the paragraph delimiters.

iter : | an iterator
Returns : | number of bytes in the line

gtk_text_iter_get_attributes ()

gboolean            gtk_text_iter_get_attributes        (const GtkTextIter *iter,
                                                         GtkTextAttributes *values);

Computes the effect of any tags applied to this spot in the text. The values parameter should be initialized to the default settings you wish to use if no tags are in effect. You'd typically obtain the defaults from gtk_text_view_get_default_attributes().

gtk_text_iter_get_attributes() will modify values, applying the effects of any tags present at iter. If any tags affected values, the function returns TRUE.

iter : | an iterator
values : | a GtkTextAttributes to be filled in
Returns : | TRUE if values was modified

gtk_text_iter_get_language ()

PangoLanguage*      gtk_text_iter_get_language          (const GtkTextIter *iter);

A convenience wrapper around gtk_text_iter_get_attributes(), which returns the language in effect at iter. If no tags affecting language apply to iter, the return value is identical to that of gtk_get_default_language().

iter : | an iterator
Returns : | language in effect at iter

gtk_text_iter_is_end ()

gboolean            gtk_text_iter_is_end                (const GtkTextIter *iter);

Returns TRUE if iter is the end iterator, i.e. one past the last dereferenceable iterator in the buffer. gtk_text_iter_is_end() is the most efficient way to check whether an iterator is the end iterator.

iter : | an iterator
Returns : | whether iter is the end iterator

gtk_text_iter_is_start ()

gboolean            gtk_text_iter_is_start              (const GtkTextIter *iter);

Returns TRUE if iter is the first iterator in the buffer, that is if iter has a character offset of 0.

iter : | an iterator
Returns : | whether iter is the first in the buffer

gtk_text_iter_forward_char ()

gboolean            gtk_text_iter_forward_char          (GtkTextIter *iter);

Moves iter forward by one character offset. Note that images embedded in the buffer occupy 1 character slot, so gtk_text_iter_forward_char() may actually move onto an image instead of a character, if you have images in your buffer. If iter is the end iterator or one character before it, iter will now point at the end iterator, and gtk_text_iter_forward_char() returns FALSE for convenience when writing loops.

iter : | an iterator
Returns : | whether iter moved and is dereferenceable

gtk_text_iter_backward_char ()

gboolean            gtk_text_iter_backward_char         (GtkTextIter *iter);

Moves backward by one character offset. Returns TRUE if movement was possible; if iter was the first in the buffer (character offset 0), gtk_text_iter_backward_char() returns FALSE for convenience when writing loops.

iter : | an iterator
Returns : | whether movement was possible

gtk_text_iter_forward_chars ()

gboolean            gtk_text_iter_forward_chars         (GtkTextIter *iter,
                                                         gint count);

Moves count characters if possible (if count would move past the start or end of the buffer, moves to the start or end of the buffer). The return value indicates whether the new position of iter is different from its original position, and dereferenceable (the last iterator in the buffer is not dereferenceable). If count is 0, the function does nothing and returns FALSE.

iter : | an iterator
count : | number of characters to move, may be negative
Returns : | whether iter moved and is dereferenceable

gtk_text_iter_backward_chars ()

gboolean            gtk_text_iter_backward_chars        (GtkTextIter *iter,
                                                         gint count);

Moves count characters backward, if possible (if count would move past the start or end of the buffer, moves to the start or end of the buffer). The return value indicates whether the iterator moved onto a dereferenceable position; if the iterator didn't move, or moved onto the end iterator, then FALSE is returned. If count is 0, the function does nothing and returns FALSE.

iter : | an iterator
count : | number of characters to move
Returns : | whether iter moved and is dereferenceable

gtk_text_iter_forward_line ()

gboolean            gtk_text_iter_forward_line          (GtkTextIter *iter);

Moves iter to the start of the next line. Returns TRUE if there was a next line to move to, and FALSE if iter was simply moved to the end of the buffer and is now not dereferenceable, or if iter was already at the end of the buffer.

iter : | an iterator
Returns : | whether iter can be dereferenced

gtk_text_iter_backward_line ()

gboolean            gtk_text_iter_backward_line         (GtkTextIter *iter);

Moves iter to the start of the previous line. Returns TRUE if iter could be moved; i.e. if iter was at character offset 0, this function returns FALSE. Therefore if iter was already on line 0, but not at the start of the line, iter is snapped to the start of the line and the function returns TRUE. (Note that this implies that in a loop calling this function, the line number may not change on every iteration, if your first iteration is on line 0.)

iter : | an iterator
Returns : | whether iter moved

gtk_text_iter_forward_lines ()

gboolean            gtk_text_iter_forward_lines         (GtkTextIter *iter,
                                                         gint count);

Moves count lines forward, if possible (if count would move past the start or end of the buffer, moves to the start or end of the buffer). The return value indicates whether the iterator moved onto a dereferenceable position; if the iterator didn't move, or moved onto the end iterator, then FALSE is returned. If count is 0, the function does nothing and returns FALSE. If count is negative, moves backward by 0 - count lines.

iter : | a GtkTextIter
count : | number of lines to move forward
Returns : | whether iter moved and is dereferenceable

gtk_text_iter_backward_lines ()

gboolean            gtk_text_iter_backward_lines        (GtkTextIter *iter,
                                                         gint count);

Moves count lines backward, if possible (if count would move past the start or end of the buffer, moves to the start or end of the buffer). The return value indicates whether the iterator moved onto a dereferenceable position; if the iterator didn't move, or moved onto the end iterator, then FALSE is returned. If count is 0, the function does nothing and returns FALSE. If count is negative, moves forward by 0 - count lines.

iter : | a GtkTextIter
count : | number of lines to move backward
Returns : | whether iter moved and is dereferenceable

gtk_text_iter_forward_word_ends ()

gboolean            gtk_text_iter_forward_word_ends     (GtkTextIter *iter,
                                                         gint count);

Calls gtk_text_iter_forward_word_end() up to count times.

iter : | a GtkTextIter
count : | number of times to move
Returns : | TRUE if iter moved and is not the end iterator

gtk_text_iter_backward_word_starts ()

gboolean            gtk_text_iter_backward_word_starts  (GtkTextIter *iter,
                                                         gint count);

Calls gtk_text_iter_backward_word_start() up to count times.

iter : | a GtkTextIter
count : | number of times to move
Returns : | TRUE if iter moved and is not the end iterator

gtk_text_iter_forward_word_end ()

gboolean            gtk_text_iter_forward_word_end      (GtkTextIter *iter);

Moves forward to the next word end. (If iter is currently on a word end, moves forward to the next one after that.) Word breaks are determined by Pango and should be correct for nearly any language (if not, the correct fix would be to the Pango word break algorithms).

iter : | a GtkTextIter
Returns : | TRUE if iter moved and is not the end iterator

gtk_text_iter_backward_word_start ()

gboolean            gtk_text_iter_backward_word_start   (GtkTextIter *iter);

Moves backward to the previous word start. (If iter is currently on a word start, moves backward to the next one after that.) Word breaks are determined by Pango and should be correct for nearly any language (if not, the correct fix would be to the Pango word break algorithms).

iter : | a GtkTextIter
Returns : | TRUE if iter moved and is not the end iterator

gtk_text_iter_forward_cursor_position ()

gboolean            gtk_text_iter_forward_cursor_position
                                                        (GtkTextIter *iter);

Moves iter forward by a single cursor position. Cursor positions are (unsurprisingly) positions where the cursor can appear. Perhaps surprisingly, there may not be a cursor position between all characters. The most common example for European languages would be a carriage return/newline sequence. For some Unicode characters, the equivalent of say the letter "a" with an accent mark will be represented as two characters, first the letter then a "combining mark" that causes the accent to be rendered; so the cursor can't go between those two characters. See also the PangoLogAttr structure and pango_break() function.

iter : | a GtkTextIter
Returns : | TRUE if we moved and the new position is dereferenceable

gtk_text_iter_backward_cursor_position ()

gboolean            gtk_text_iter_backward_cursor_position
                                                        (GtkTextIter *iter);

Like gtk_text_iter_forward_cursor_position(), but moves backward.

iter : | a GtkTextIter
Returns : | TRUE if we moved

gtk_text_iter_forward_cursor_positions ()

gboolean            gtk_text_iter_forward_cursor_positions
                                                        (GtkTextIter *iter,
                                                         gint count);

Moves up to count cursor positions. See gtk_text_iter_forward_cursor_position() for details.

iter : | a GtkTextIter
count : | number of positions to move
Returns : | TRUE if we moved and the new position is dereferenceable

gtk_text_iter_backward_cursor_positions ()

gboolean            gtk_text_iter_backward_cursor_positions
                                                        (GtkTextIter *iter,
                                                         gint count);

Moves up to count cursor positions. See gtk_text_iter_forward_cursor_position() for details.

iter : | a GtkTextIter
count : | number of positions to move
Returns : | TRUE if we moved and the new position is dereferenceable

gtk_text_iter_backward_sentence_start ()

gboolean            gtk_text_iter_backward_sentence_start
                                                        (GtkTextIter *iter);

Moves backward to the previous sentence start; if iter is already at the start of a sentence, moves backward to the next one. Sentence boundaries are determined by Pango and should be correct for nearly any language (if not, the correct fix would be to the Pango text boundary algorithms).

iter : | a GtkTextIter
Returns : | TRUE if iter moved and is not the end iterator

gtk_text_iter_backward_sentence_starts ()

gboolean            gtk_text_iter_backward_sentence_starts
                                                        (GtkTextIter *iter,
                                                         gint count);

Calls gtk_text_iter_backward_sentence_start() up to count times, or until it returns FALSE. If count is negative, moves forward instead of backward.

iter : | a GtkTextIter
count : | number of sentences to move
Returns : | TRUE if iter moved and is not the end iterator

gtk_text_iter_forward_sentence_end ()

gboolean            gtk_text_iter_forward_sentence_end  (GtkTextIter *iter);

Moves forward to the next sentence end. (If iter is at the end of a sentence, moves to the next end of sentence.) Sentence boundaries are determined by Pango and should be correct for nearly any language (if not, the correct fix would be to the Pango text boundary algorithms).

iter : | a GtkTextIter
Returns : | TRUE if iter moved and is not the end iterator

gtk_text_iter_forward_sentence_ends ()

gboolean            gtk_text_iter_forward_sentence_ends (GtkTextIter *iter,
                                                         gint count);

Calls gtk_text_iter_forward_sentence_end() count times (or until gtk_text_iter_forward_sentence_end() returns FALSE). If count is negative, moves backward instead of forward.

iter : | a GtkTextIter
count : | number of sentences to move
Returns : | TRUE if iter moved and is not the end iterator

gtk_text_iter_forward_visible_word_ends ()

gboolean            gtk_text_iter_forward_visible_word_ends
                                                        (GtkTextIter *iter,
                                                         gint count);

Calls gtk_text_iter_forward_visible_word_end() up to count times.

iter : | a GtkTextIter
count : | number of times to move
Returns : | TRUE if iter moved and is not the end iterator

Since 2.4

gtk_text_iter_backward_visible_word_starts ()

gboolean            gtk_text_iter_backward_visible_word_starts
                                                        (GtkTextIter *iter,
                                                         gint count);

Calls gtk_text_iter_backward_visible_word_start() up to count times.

iter : | a GtkTextIter
count : | number of times to move
Returns : | TRUE if iter moved and is not the end iterator

Since 2.4

gtk_text_iter_forward_visible_word_end ()

gboolean            gtk_text_iter_forward_visible_word_end
                                                        (GtkTextIter *iter);

Moves forward to the next visible word end. (If iter is currently on a word end, moves forward to the next one after that.) Word breaks are determined by Pango and should be correct for nearly any language (if not, the correct fix would be to the Pango word break algorithms).

iter : | a GtkTextIter
Returns : | TRUE if iter moved and is not the end iterator

Since 2.4

gtk_text_iter_backward_visible_word_start ()

gboolean            gtk_text_iter_backward_visible_word_start
                                                        (GtkTextIter *iter);

Moves backward to the previous visible word start. (If iter is currently on a word start, moves backward to the next one after that.) Word breaks are determined by Pango and should be correct for nearly any language (if not, the correct fix would be to the Pango word break algorithms).

iter : | a GtkTextIter
Returns : | TRUE if iter moved and is not the end iterator

Since 2.4

gtk_text_iter_forward_visible_cursor_position ()

gboolean            gtk_text_iter_forward_visible_cursor_position
                                                        (GtkTextIter *iter);

Moves iter forward to the next visible cursor position. See gtk_text_iter_forward_cursor_position() for details.

iter : | a GtkTextIter
Returns : | TRUE if we moved and the new position is dereferenceable

Since 2.4

gtk_text_iter_backward_visible_cursor_position ()

gboolean            gtk_text_iter_backward_visible_cursor_position
                                                        (GtkTextIter *iter);

Moves iter forward to the previous visible cursor position. See gtk_text_iter_backward_cursor_position() for details.

iter : | a GtkTextIter
Returns : | TRUE if we moved and the new position is dereferenceable

Since 2.4

gtk_text_iter_forward_visible_cursor_positions ()

gboolean            gtk_text_iter_forward_visible_cursor_positions
                                                        (GtkTextIter *iter,
                                                         gint count);

Moves up to count visible cursor positions. See gtk_text_iter_forward_cursor_position() for details.

iter : | a GtkTextIter
count : | number of positions to move
Returns : | TRUE if we moved and the new position is dereferenceable

Since 2.4

gtk_text_iter_backward_visible_cursor_positions ()

gboolean            gtk_text_iter_backward_visible_cursor_positions
                                                        (GtkTextIter *iter,
                                                         gint count);

Moves up to count visible cursor positions. See gtk_text_iter_backward_cursor_position() for details.

iter : | a GtkTextIter
count : | number of positions to move
Returns : | TRUE if we moved and the new position is dereferenceable

Since 2.4

gtk_text_iter_forward_visible_line ()

gboolean            gtk_text_iter_forward_visible_line  (GtkTextIter *iter);

Moves iter to the start of the next visible line. Returns TRUE if there was a next line to move to, and FALSE if iter was simply moved to the end of the buffer and is now not dereferenceable, or if iter was already at the end of the buffer.

iter : | an iterator
Returns : | whether iter can be dereferenced

Since 2.8

gtk_text_iter_backward_visible_line ()

gboolean            gtk_text_iter_backward_visible_line (GtkTextIter *iter);

Moves iter to the start of the previous visible line. Returns TRUE if iter could be moved; i.e. if iter was at character offset 0, this function returns FALSE. Therefore if iter was already on line 0, but not at the start of the line, iter is snapped to the start of the line and the function returns TRUE. (Note that this implies that in a loop calling this function, the line number may not change on every iteration, if your first iteration is on line 0.)

iter : | an iterator
Returns : | whether iter moved

Since 2.8

gtk_text_iter_forward_visible_lines ()

gboolean            gtk_text_iter_forward_visible_lines (GtkTextIter *iter,
                                                         gint count);

Moves count visible lines forward, if possible (if count would move past the start or end of the buffer, moves to the start or end of the buffer). The return value indicates whether the iterator moved onto a dereferenceable position; if the iterator didn't move, or moved onto the end iterator, then FALSE is returned. If count is 0, the function does nothing and returns FALSE. If count is negative, moves backward by 0 - count lines.

iter : | a GtkTextIter
count : | number of lines to move forward
Returns : | whether iter moved and is dereferenceable

Since 2.8

gtk_text_iter_backward_visible_lines ()

gboolean            gtk_text_iter_backward_visible_lines
                                                        (GtkTextIter *iter,
                                                         gint count);

Moves count visible lines backward, if possible (if count would move past the start or end of the buffer, moves to the start or end of the buffer). The return value indicates whether the iterator moved onto a dereferenceable position; if the iterator didn't move, or moved onto the end iterator, then FALSE is returned. If count is 0, the function does nothing and returns FALSE. If count is negative, moves forward by 0 - count lines.

iter : | a GtkTextIter
count : | number of lines to move backward
Returns : | whether iter moved and is dereferenceable

Since 2.8

gtk_text_iter_set_offset ()

void                gtk_text_iter_set_offset            (GtkTextIter *iter,
                                                         gint char_offset);

Sets iter to point to char_offset. char_offset counts from the start of the entire text buffer, starting with 0.

iter : | a GtkTextIter
char_offset : | a character number

gtk_text_iter_set_line ()

void                gtk_text_iter_set_line              (GtkTextIter *iter,
                                                         gint line_number);

Moves iterator iter to the start of the line line_number. If line_number is negative or larger than the number of lines in the buffer, moves iter to the start of the last line in the buffer.

iter : | a GtkTextIter
line_number : | line number (counted from 0)

gtk_text_iter_set_line_offset ()

void                gtk_text_iter_set_line_offset       (GtkTextIter *iter,
                                                         gint char_on_line);

Moves iter within a line, to a new character (not byte) offset. The given character offset must be less than or equal to the number of characters in the line; if equal, iter moves to the start of the next line. See gtk_text_iter_set_line_index() if you have a byte index rather than a character offset.

iter : | a GtkTextIter
char_on_line : | a character offset relative to the start of iter's current line

gtk_text_iter_set_line_index ()

void                gtk_text_iter_set_line_index        (GtkTextIter *iter,
                                                         gint byte_on_line);

Same as gtk_text_iter_set_line_offset(), but works with a byte index. The given byte index must be at the start of a character, it can't be in the middle of a UTF-8 encoded character.

iter : | a GtkTextIter
byte_on_line : | a byte index relative to the start of iter's current line

gtk_text_iter_set_visible_line_index ()

void                gtk_text_iter_set_visible_line_index
                                                        (GtkTextIter *iter,
                                                         gint byte_on_line);

Like gtk_text_iter_set_line_index(), but the index is in visible bytes, i.e. text with a tag making it invisible is not counted in the index.

iter : | a GtkTextIter
byte_on_line : | a byte index

gtk_text_iter_set_visible_line_offset ()

void                gtk_text_iter_set_visible_line_offset
                                                        (GtkTextIter *iter,
                                                         gint char_on_line);

Like gtk_text_iter_set_line_offset(), but the offset is in visible characters, i.e. text with a tag making it invisible is not counted in the offset.

iter : | a GtkTextIter
char_on_line : | a character offset

gtk_text_iter_forward_to_end ()

void                gtk_text_iter_forward_to_end        (GtkTextIter *iter);

Moves iter forward to the "end iterator," which points one past the last valid character in the buffer. gtk_text_iter_get_char() called on the end iterator returns 0, which is convenient for writing loops.

iter : a GtkTextIter

gtk_text_iter_forward_to_line_end ()

gboolean            gtk_text_iter_forward_to_line_end   (GtkTextIter *iter);

Moves the iterator to point to the paragraph delimiter characters, which will be either a newline, a carriage return, a carriage return/newline in sequence, or the Unicode paragraph separator character. If the iterator is already at the paragraph delimiter characters, moves to the paragraph delimiter characters for the next line. If iter is on the last line in the buffer, which does not end in paragraph delimiters, moves to the end iterator (end of the last line), and returns FALSE.

iter : | a GtkTextIter
Returns : | TRUE if we moved and the new location is not the end iterator

gtk_text_iter_forward_to_tag_toggle ()

gboolean            gtk_text_iter_forward_to_tag_toggle (GtkTextIter *iter,
                                                         GtkTextTag *tag);

Moves forward to the next toggle (on or off) of the GtkTextTag tag, or to the next toggle of any tag if tag is NULL. If no matching tag toggles are found, returns FALSE, otherwise TRUE. Does not return toggles located at iter, only toggles after iter. Sets iter to the location of the toggle, or to the end of the buffer if no toggle is found.

iter : | a GtkTextIter
tag : | a GtkTextTag, or NULL
Returns : | whether we found a tag toggle after iter

gtk_text_iter_backward_to_tag_toggle ()

gboolean            gtk_text_iter_backward_to_tag_toggle
                                                        (GtkTextIter *iter,
                                                         GtkTextTag *tag);

Moves backward to the next toggle (on or off) of the GtkTextTag tag, or to the next toggle of any tag if tag is NULL. If no matching tag toggles are found, returns FALSE, otherwise TRUE. Does not return toggles located at iter, only toggles before iter. Sets iter to the location of the toggle, or the start of the buffer if no toggle is found.

iter : | a GtkTextIter
tag : | a GtkTextTag, or NULL
Returns : | whether we found a tag toggle before iter

GtkTextCharPredicate ()

gboolean            (*GtkTextCharPredicate)             (gunichar ch,
                                                         gpointer user_data);

ch :
user_data :
Returns :

gtk_text_iter_forward_find_char ()

gboolean            gtk_text_iter_forward_find_char     (GtkTextIter *iter,
                                                         GtkTextCharPredicate pred,
                                                         gpointer user_data,
                                                         const GtkTextIter *limit);

Advances iter, calling pred on each character. If pred returns TRUE, returns TRUE and stops scanning. If pred never returns TRUE, iter is set to limit if limit is non-NULL, otherwise to the end iterator.

iter : | a GtkTextIter
pred : | a function to be called on each character
user_data : | user data for pred
limit : | search limit, or NULL for none
Returns : | whether a match was found

gtk_text_iter_backward_find_char ()

gboolean            gtk_text_iter_backward_find_char    (GtkTextIter *iter,
                                                         GtkTextCharPredicate pred,
                                                         gpointer user_data,
                                                         const GtkTextIter *limit);

Same as gtk_text_iter_forward_find_char(), but goes backward from iter.

iter : | a GtkTextIter
pred : | function to be called on each character
user_data : | user data for pred
limit : | search limit, or NULL for none
Returns : | whether a match was found

enum GtkTextSearchFlags

typedef enum {
  GTK_TEXT_SEARCH_VISIBLE_ONLY = 1 << 0,
  GTK_TEXT_SEARCH_TEXT_ONLY    = 1 << 1
  /* Possible future plans: SEARCH_CASE_INSENSITIVE, SEARCH_REGEXP */
} GtkTextSearchFlags;

gtk_text_iter_forward_search ()

gboolean            gtk_text_iter_forward_search        (const GtkTextIter *iter,
                                                         const gchar *str,
                                                         GtkTextSearchFlags flags,
                                                         GtkTextIter *match_start,
                                                         GtkTextIter *match_end,
                                                         const GtkTextIter *limit);

Searches forward for str. Any match is returned by setting match_start to the first character of the match and match_end to the first character after the match. The search will not continue past limit. Note that a search is a linear or O(n) operation, so you may wish to use limit to avoid locking up your UI on large buffers.

If the GTK_TEXT_SEARCH_VISIBLE_ONLY flag is present, the match may have invisible text interspersed in str. i.e. str will be a possibly-noncontiguous subsequence of the matched range. similarly, if you specify GTK_TEXT_SEARCH_TEXT_ONLY, the match may have pixbufs or child widgets mixed inside the matched range. If these flags are not given, the match must be exact; the special 0xFFFC character in str will match embedded pixbufs or child widgets.

iter : | start of search
str : | a search string
flags : | flags affecting how the search is done
match_start : | return location for start of match, or NULL
match_end : | return location for end of match, or NULL
limit : | bound for the search, or NULL for the end of the buffer
Returns : | whether a match was found

gtk_text_iter_backward_search ()

gboolean            gtk_text_iter_backward_search       (const GtkTextIter *iter,
                                                         const gchar *str,
                                                         GtkTextSearchFlags flags,
                                                         GtkTextIter *match_start,
                                                         GtkTextIter *match_end,
                                                         const GtkTextIter *limit);

Same as gtk_text_iter_forward_search(), but moves backward.

iter : | a GtkTextIter where the search begins
str : | search string
flags : | bitmask of flags affecting the search
match_start : | return location for start of match, or NULL
match_end : | return location for end of match, or NULL
limit : | location of last possible match_start, or NULL for start of buffer
Returns : | whether a match was found

gtk_text_iter_equal ()

gboolean            gtk_text_iter_equal                 (const GtkTextIter *lhs,
                                                         const GtkTextIter *rhs);

Tests whether two iterators are equal, using the fastest possible mechanism. This function is very fast; you can expect it to perform better than e.g. getting the character offset for each iterator and comparing the offsets yourself. Also, it's a bit faster than gtk_text_iter_compare().

lhs : | a GtkTextIter
rhs : | another GtkTextIter
Returns : | TRUE if the iterators point to the same place in the buffer

gtk_text_iter_compare ()

gint                gtk_text_iter_compare               (const GtkTextIter *lhs,
                                                         const GtkTextIter *rhs);

A qsort()-style function that returns negative if lhs is less than rhs, positive if lhs is greater than rhs, and 0 if they're equal. Ordering is in character offset order, i.e. the first character in the buffer is less than the second character in the buffer.

lhs : | a GtkTextIter
rhs : | another GtkTextIter
Returns : | -1 if lhs is less than rhs, 1 if lhs is greater, 0 if they are equal

gtk_text_iter_in_range ()

gboolean            gtk_text_iter_in_range              (const GtkTextIter *iter,
                                                         const GtkTextIter *start,
                                                         const GtkTextIter *end);

Checks whether iter falls in the range [start, end). start and end must be in ascending order.

iter : | a GtkTextIter
start : | start of range
end : | end of range
Returns : | TRUE if iter is in the range

gtk_text_iter_order ()

void                gtk_text_iter_order                 (GtkTextIter *first,
                                                         GtkTextIter *second);

Swaps the value of first and second if second comes before first in the buffer. That is, ensures that first and second are in sequence. Most text buffer functions that take a range call this automatically on your behalf, so there's no real reason to call it yourself in those cases. There are some exceptions, such as gtk_text_iter_in_range(), that expect a pre-sorted range.

first : | a GtkTextIter
second : | another GtkTextIter


GtkTreeView drag-and-drop

GtkTreeView drag-and-drop — Interfaces for drag-and-drop support in GtkTreeView

Synopsis

#include <gtk/gtk.h>

                    GtkTreeDragSource;
                    GtkTreeDragSourceIface;
gboolean            gtk_tree_drag_source_drag_data_delete
                                                        (GtkTreeDragSource *drag_source,
                                                         GtkTreePath *path);
gboolean            gtk_tree_drag_source_drag_data_get  (GtkTreeDragSource *drag_source,
                                                         GtkTreePath *path,
                                                         GtkSelectionData *selection_data);
gboolean            gtk_tree_drag_source_row_draggable  (GtkTreeDragSource *drag_source,
                                                         GtkTreePath *path);
                    GtkTreeDragDest;
                    GtkTreeDragDestIface;
gboolean            gtk_tree_drag_dest_drag_data_received
                                                        (GtkTreeDragDest *drag_dest,
                                                         GtkTreePath *dest,
                                                         GtkSelectionData *selection_data);
gboolean            gtk_tree_drag_dest_row_drop_possible
                                                        (GtkTreeDragDest *drag_dest,
                                                         GtkTreePath *dest_path,
                                                         GtkSelectionData *selection_data);
gboolean            gtk_tree_set_row_drag_data          (GtkSelectionData *selection_data,
                                                         GtkTreeModel *tree_model,
                                                         GtkTreePath *path);
gboolean            gtk_tree_get_row_drag_data          (GtkSelectionData *selection_data,
                                                         GtkTreeModel **tree_model,
                                                         GtkTreePath **path);

Object Hierarchy

  GInterface
   +----GtkTreeDragSource

  GInterface
   +----GtkTreeDragDest

Known Implementations

GtkTreeDragSource is implemented by GtkTreeModelSort, GtkTreeStore, GtkListStore and GtkTreeModelFilter.

GtkTreeDragDest is implemented by GtkTreeStore and GtkListStore.

Description

GTK+ supports Drag-and-Drop in tree views with a high-level and a low-level API.

The low-level API consists of the GTK+ DND API, augmented by some treeview utility functions: gtk_tree_view_set_drag_dest_row(), gtk_tree_view_get_drag_dest_row(), gtk_tree_view_get_dest_row_at_pos(), gtk_tree_view_create_row_drag_icon(), gtk_tree_set_row_drag_data() and gtk_tree_get_row_drag_data(). This API leaves a lot of flexibility, but nothing is done automatically, and implementing advanced features like hover-to-open-rows or autoscrolling on top of this API is a lot of work.

On the other hand, if you write to the high-level API, then all the bookkeeping of rows is done for you, as well as things like hover-to-open and auto-scroll, but your models have to implement the GtkTreeDragSource and GtkTreeDragDest interfaces.

Details

GtkTreeDragSource

typedef struct _GtkTreeDragSource GtkTreeDragSource;

GtkTreeDragSourceIface

typedef struct {
  GTypeInterface g_iface;

  /* VTable - not signals */

  gboolean     (* row_draggable)        (GtkTreeDragSource   *drag_source,
                                         GtkTreePath         *path);

  gboolean     (* drag_data_get)        (GtkTreeDragSource   *drag_source,
                                         GtkTreePath         *path,
                                         GtkSelectionData    *selection_data);

  gboolean     (* drag_data_delete)     (GtkTreeDragSource *drag_source,
                                         GtkTreePath       *path);
} GtkTreeDragSourceIface;

gtk_tree_drag_source_drag_data_delete ()

gboolean            gtk_tree_drag_source_drag_data_delete
                                                        (GtkTreeDragSource *drag_source,
                                                         GtkTreePath *path);

Asks the GtkTreeDragSource to delete the row at path, because it was moved somewhere else via drag-and-drop. Returns FALSE if the deletion fails because path no longer exists, or for some model-specific reason. Should robustly handle a path no longer found in the model!

drag_source : | a GtkTreeDragSource
path : | row that was being dragged
Returns : | TRUE if the row was successfully deleted

gtk_tree_drag_source_drag_data_get ()

gboolean            gtk_tree_drag_source_drag_data_get  (GtkTreeDragSource *drag_source,
                                                         GtkTreePath *path,
                                                         GtkSelectionData *selection_data);

Asks the GtkTreeDragSource to fill in selection_data with a representation of the row at path. selection_data->target gives the required type of the data. Should robustly handle a path no longer found in the model!

drag_source : | a GtkTreeDragSource
path : | row that was dragged
selection_data : | a GtkSelectionData to fill with data from the dragged row
Returns : | TRUE if data of the required type was provided

gtk_tree_drag_source_row_draggable ()

gboolean            gtk_tree_drag_source_row_draggable  (GtkTreeDragSource *drag_source,
                                                         GtkTreePath *path);

Asks the GtkTreeDragSource whether a particular row can be used as the source of a DND operation. If the source doesn't implement this interface, the row is assumed draggable.

drag_source : | a GtkTreeDragSource
path : | row on which user is initiating a drag
Returns : | TRUE if the row can be dragged

GtkTreeDragDest

typedef struct _GtkTreeDragDest GtkTreeDragDest;

GtkTreeDragDestIface

typedef struct {
  GTypeInterface g_iface;

  /* VTable - not signals */

  gboolean     (* drag_data_received) (GtkTreeDragDest   *drag_dest,
                                       GtkTreePath       *dest,
                                       GtkSelectionData  *selection_data);

  gboolean     (* row_drop_possible)  (GtkTreeDragDest   *drag_dest,
                                       GtkTreePath       *dest_path,
                       GtkSelectionData  *selection_data);
} GtkTreeDragDestIface;

gtk_tree_drag_dest_drag_data_received ()

gboolean            gtk_tree_drag_dest_drag_data_received
                                                        (GtkTreeDragDest *drag_dest,
                                                         GtkTreePath *dest,
                                                         GtkSelectionData *selection_data);

Asks the GtkTreeDragDest to insert a row before the path dest, deriving the contents of the row from selection_data. If dest is outside the tree so that inserting before it is impossible, FALSE will be returned. Also, FALSE may be returned if the new row is not created for some model-specific reason. Should robustly handle a dest no longer found in the model!

drag_dest : | a GtkTreeDragDest
dest : | row to drop in front of
selection_data : | data to drop
Returns : | whether a new row was created before position dest

gtk_tree_drag_dest_row_drop_possible ()

gboolean            gtk_tree_drag_dest_row_drop_possible
                                                        (GtkTreeDragDest *drag_dest,
                                                         GtkTreePath *dest_path,
                                                         GtkSelectionData *selection_data);

Determines whether a drop is possible before the given dest_path, at the same depth as dest_path. i.e., can we drop the data in selection_data at that location. dest_path does not have to exist; the return value will almost certainly be FALSE if the parent of dest_path doesn't exist, though.

drag_dest : | a GtkTreeDragDest
dest_path : | destination row
selection_data : | the data being dragged
Returns : | TRUE if a drop is possible before dest_path

gtk_tree_set_row_drag_data ()

gboolean            gtk_tree_set_row_drag_data          (GtkSelectionData *selection_data,
                                                         GtkTreeModel *tree_model,
                                                         GtkTreePath *path);

Sets selection data of target type GTK_TREE_MODEL_ROW. Normally used in a drag_data_get handler.

selection_data : | some GtkSelectionData
tree_model : | a GtkTreeModel
path : | a row in tree_model
Returns : | TRUE if the GtkSelectionData had the proper target type to allow us to set a tree row

gtk_tree_get_row_drag_data ()

gboolean            gtk_tree_get_row_drag_data          (GtkSelectionData *selection_data,
                                                         GtkTreeModel **tree_model,
                                                         GtkTreePath **path);

Obtains a tree_model and path from selection data of target type GTK_TREE_MODEL_ROW. Normally called from a drag_data_received handler. This function can only be used if selection_data originates from the same process that's calling this function, because a pointer to the tree model is being passed around. If you aren't in the same process, then you'll get memory corruption. In the GtkTreeDragDest drag_data_received handler, you can assume that selection data of type GTK_TREE_MODEL_ROW is in from the current process. The returned path must be freed with gtk_tree_path_free().

selection_data : | a GtkSelectionData
tree_model : | a GtkTreeModel
path : | row in tree_model
Returns : | TRUE if selection_data had target type GTK_TREE_MODEL_ROW and is otherwise valid


GtkPrintOperation

GtkPrintOperation — High-level Printing API

Synopsis

#include <gtk/gtk.h>

                    GtkPrintOperation;
enum                GtkPrintStatus;
enum                GtkPrintOperationAction;
enum                GtkPrintOperationResult;
enum                GtkPrintError;
#define             GTK_PRINT_ERROR
GtkPrintOperation*  gtk_print_operation_new             (void);
void                gtk_print_operation_set_allow_async (GtkPrintOperation *op,
                                                         gboolean allow_async);
void                gtk_print_operation_get_error       (GtkPrintOperation *op,
                                                         GError **error);
void                gtk_print_operation_set_default_page_setup
                                                        (GtkPrintOperation *op,
                                                         GtkPageSetup *default_page_setup);
GtkPageSetup*       gtk_print_operation_get_default_page_setup
                                                        (GtkPrintOperation *op);
void                gtk_print_operation_set_print_settings
                                                        (GtkPrintOperation *op,
                                                         GtkPrintSettings *print_settings);
GtkPrintSettings*   gtk_print_operation_get_print_settings
                                                        (GtkPrintOperation *op);
void                gtk_print_operation_set_job_name    (GtkPrintOperation *op,
                                                         const gchar *job_name);
void                gtk_print_operation_set_n_pages     (GtkPrintOperation *op,
                                                         gint n_pages);
void                gtk_print_operation_set_current_page
                                                        (GtkPrintOperation *op,
                                                         gint current_page);
void                gtk_print_operation_set_use_full_page
                                                        (GtkPrintOperation *op,
                                                         gboolean full_page);
void                gtk_print_operation_set_unit        (GtkPrintOperation *op,
                                                         GtkUnit unit);
void                gtk_print_operation_set_export_filename
                                                        (GtkPrintOperation *op,
                                                         const gchar *filename);
void                gtk_print_operation_set_show_progress
                                                        (GtkPrintOperation *op,
                                                         gboolean show_progress);
void                gtk_print_operation_set_track_print_status
                                                        (GtkPrintOperation *op,
                                                         gboolean track_status);
void                gtk_print_operation_set_custom_tab_label
                                                        (GtkPrintOperation *op,
                                                         const gchar *label);
GtkPrintOperationResult gtk_print_operation_run         (GtkPrintOperation *op,
                                                         GtkPrintOperationAction action,
                                                         GtkWindow *parent,
                                                         GError **error);
void                gtk_print_operation_cancel          (GtkPrintOperation *op);
GtkPrintStatus      gtk_print_operation_get_status      (GtkPrintOperation *op);
const gchar*        gtk_print_operation_get_status_string
                                                        (GtkPrintOperation *op);
gboolean            gtk_print_operation_is_finished     (GtkPrintOperation *op);
void                gtk_print_operation_get_error       (GtkPrintOperation *op,
                                                         GError **error);
GtkPageSetup*       gtk_print_run_page_setup_dialog     (GtkWindow *parent,
                                                         GtkPageSetup *page_setup,
                                                         GtkPrintSettings *settings);
void                (*GtkPageSetupDoneFunc)             (GtkPageSetup *page_setup,
                                                         gpointer data);
void                gtk_print_run_page_setup_dialog_async
                                                        (GtkWindow *parent,
                                                         GtkPageSetup *page_setup,
                                                         GtkPrintSettings *settings,
                                                         GtkPageSetupDoneFunc done_cb,
                                                         gpointer data);

                    GtkPrintOperationPreview;
void                gtk_print_operation_preview_end_preview
                                                        (GtkPrintOperationPreview *preview);
gboolean            gtk_print_operation_preview_is_selected
                                                        (GtkPrintOperationPreview *preview,
                                                         gint page_nr);
void                gtk_print_operation_preview_render_page
                                                        (GtkPrintOperationPreview *preview,
                                                         gint page_nr);

Object Hierarchy

  GObject
   +----GtkPrintOperation

  GInterface
   +----GtkPrintOperationPreview

Prerequisites

GtkPrintOperationPreview requires GObject.

Implemented Interfaces

GtkPrintOperation implements GtkPrintOperationPreview.

Known Implementations

GtkPrintOperationPreview is implemented by GtkPrintOperation.

Properties

  "allow-async"              gboolean              : Read / Write
  "current-page"             gint                  : Read / Write
  "custom-tab-label"         gchararray            : Read / Write
  "default-page-setup"       GtkPageSetup          : Read / Write
  "export-filename"          gchararray            : Read / Write
  "job-name"                 gchararray            : Read / Write
  "n-pages"                  gint                  : Read / Write
  "print-settings"           GtkPrintSettings      : Read / Write
  "show-progress"            gboolean              : Read / Write
  "status"                   GtkPrintStatus        : Read
  "status-string"            gchararray            : Read
  "track-print-status"       gboolean              : Read / Write
  "unit"                     GtkUnit               : Read / Write
  "use-full-page"            gboolean              : Read / Write

Signals

  "begin-print"                                    : Run Last
  "create-custom-widget"                           : Run Last
  "custom-widget-apply"                            : Run Last
  "done"                                           : Run Last
  "draw-page"                                      : Run Last
  "end-print"                                      : Run Last
  "paginate"                                       : Run Last
  "preview"                                        : Run Last
  "request-page-setup"                             : Run Last
  "status-changed"                                 : Run Last

Description

GtkPrintOperation is the high-level, portable printing API. It looks a bit different than other GTK+ dialogs such as the GtkFileChooser, since some platforms don't expose enough infrastructure to implement a good print dialog. On such platforms, GtkPrintOperation uses the native print dialog. On platforms which do not provide a native print dialog, GTK+ uses its own, see GtkPrintUnixDialog.

The typical way to use the high-level printing API is to create a GtkPrintOperation object with gtk_print_operation_new() when the user selects to print. Then you set some properties on it, e.g. the page size, any GtkPrintSettings from previous print operations, the number of pages, the current page, etc.

Then you start the print operation by calling gtk_print_operation_run(). It will then show a dialog, let the user select a printer and options. When the user finished the dialog various signals will be emitted on the GtkPrintOperation, the main one being ::draw-page, which you are supposed to catch and render the page on the provided GtkPrintContext using Cairo.

Example 30. The high-level printing API

static GtkPrintSettings *settings = NULL;

static void
do_print (void)
{
  GtkPrintOperation *print;
  GtkPrintOperationResult res;

  print = gtk_print_operation_new ();

  if (settings != NULL)
    gtk_print_operation_set_print_settings (print, settings);

  g_signal_connect (print, "begin_print", G_CALLBACK (begin_print), NULL);
  g_signal_connect (print, "draw_page", G_CALLBACK (draw_page), NULL);

  res = gtk_print_operation_run (print, GTK_PRINT_OPERATION_ACTION_PRINT_DIALOG,
                                 GTK_WINDOW (main_window), NULL);

  if (res == GTK_PRINT_OPERATION_RESULT_APPLY)
    {
      if (settings != NULL)
        g_object_unref (settings);
      settings = g_object_ref (gtk_print_operation_get_print_settings (print));
    }

  g_object_unref (print);
}

By default GtkPrintOperation uses an external application to do print preview. To implement a custom print preview, an application must connect to the preview signal. The functions gtk_print_operation_print_preview_render_page(), gtk_print_operation_preview_end_preview() and gtk_print_operation_preview_is_selected() are useful when implementing a print preview.

Printing support was added in GTK+ 2.10.

Details

GtkPrintOperation

typedef struct _GtkPrintOperation GtkPrintOperation;

enum GtkPrintStatus

typedef enum {
  GTK_PRINT_STATUS_INITIAL,
  GTK_PRINT_STATUS_PREPARING,
  GTK_PRINT_STATUS_GENERATING_DATA,
  GTK_PRINT_STATUS_SENDING_DATA,
  GTK_PRINT_STATUS_PENDING,
  GTK_PRINT_STATUS_PENDING_ISSUE,
  GTK_PRINT_STATUS_PRINTING,
  GTK_PRINT_STATUS_FINISHED,
  GTK_PRINT_STATUS_FINISHED_ABORTED
} GtkPrintStatus;

The status gives a rough indication of the completion of a running print operation.

GTK_PRINT_STATUS_INITIAL | The printing has not started yet; this status is set initially, and while the print dialog is shown.
GTK_PRINT_STATUS_PREPARING | This status is set while the begin-print signal is emitted and during pagination.
GTK_PRINT_STATUS_GENERATING_DATA | This status is set while the pages are being rendered.
GTK_PRINT_STATUS_SENDING_DATA | The print job is being sent off to the printer.
GTK_PRINT_STATUS_PENDING | The print job has been sent to the printer, but is not printed for some reason, e.g. the printer may be stopped.
GTK_PRINT_STATUS_PENDING_ISSUE | Some problem has occurred during printing, e.g. a paper jam.
GTK_PRINT_STATUS_PRINTING | The printer is processing the print job.
GTK_PRINT_STATUS_FINISHED | The printing has been completed successfully.
GTK_PRINT_STATUS_FINISHED_ABORTED | The printing has been aborted.

enum GtkPrintOperationAction

typedef enum {
  GTK_PRINT_OPERATION_ACTION_PRINT_DIALOG,
  GTK_PRINT_OPERATION_ACTION_PRINT,
  GTK_PRINT_OPERATION_ACTION_PREVIEW,
  GTK_PRINT_OPERATION_ACTION_EXPORT
} GtkPrintOperationAction;

The action parameter to gtk_print_operation_run() determines what action the print operation should perform.

GTK_PRINT_OPERATION_ACTION_PRINT_DIALOG | Show the print dialog.
GTK_PRINT_OPERATION_ACTION_PRINT | Start to print without showing the print dialog, based on the current print settings.
GTK_PRINT_OPERATION_ACTION_PREVIEW | Show the print preview.
GTK_PRINT_OPERATION_ACTION_EXPORT | Export to a file. This requires the export-filename property to be set.

enum GtkPrintOperationResult

typedef enum {
  GTK_PRINT_OPERATION_RESULT_ERROR,
  GTK_PRINT_OPERATION_RESULT_APPLY,
  GTK_PRINT_OPERATION_RESULT_CANCEL,
  GTK_PRINT_OPERATION_RESULT_IN_PROGRESS
} GtkPrintOperationResult;

A value of this type is returned by gtk_print_operation_run().

GTK_PRINT_OPERATION_RESULT_ERROR | An error has occured.
GTK_PRINT_OPERATION_RESULT_APPLY | The print settings should be stored.
GTK_PRINT_OPERATION_RESULT_CANCEL | The print operation has been canceled, the print settings should not be stored.
GTK_PRINT_OPERATION_RESULT_IN_PROGRESS | The print operation is complete yet. This value will only be returned when running asynchronously.

enum GtkPrintError

typedef enum
{
  GTK_PRINT_ERROR_GENERAL,
  GTK_PRINT_ERROR_INTERNAL_ERROR,
  GTK_PRINT_ERROR_NOMEM
} GtkPrintError;

GTK_PRINT_ERROR

#define GTK_PRINT_ERROR gtk_print_error_quark ()

The GQuark used for GtkPrintError errors.

gtk_print_operation_new ()

GtkPrintOperation*  gtk_print_operation_new             (void);

Creates a new GtkPrintOperation.

Returns : a new GtkPrintOperation

Since 2.10

gtk_print_operation_set_allow_async ()

void                gtk_print_operation_set_allow_async (GtkPrintOperation *op,
                                                         gboolean allow_async);

Sets whether the gtk_print_operation_run() may return before the print operation is completed. Note that some platforms may not allow asynchronous operation.

op : | a GtkPrintOperation
allow_async : | TRUE to allow asynchronous operation

Since 2.10

gtk_print_operation_get_error ()

void                gtk_print_operation_get_error       (GtkPrintOperation *op,
                                                         GError **error);

Call this when the result of a print operation is GTK_PRINT_OPERATION_RESULT_ERROR, either as returned by gtk_print_operation_run(), or in the ::done signal handler. The returned GError will contain more details on what went wrong.

op : | a GtkPrintOperation
error : | return location for the error

Since 2.10

gtk_print_operation_set_default_page_setup ()

void                gtk_print_operation_set_default_page_setup
                                                        (GtkPrintOperation *op,
                                                         GtkPageSetup *default_page_setup);

Makes default_page_setup the default page setup for op.

This page setup will be used by gtk_print_operation_run(), but it can be overridden on a per-page basis by connecting to the ::request-page-setup signal.

op : | a GtkPrintOperation
default_page_setup : | a GtkPageSetup, or NULL

Since 2.10

gtk_print_operation_get_default_page_setup ()

GtkPageSetup*       gtk_print_operation_get_default_page_setup
                                                        (GtkPrintOperation *op);

Returns the default page setup, see gtk_print_operation_set_default_page_setup().

op : | a GtkPrintOperation
Returns : | the default page setup

Since 2.10

gtk_print_operation_set_print_settings ()

void                gtk_print_operation_set_print_settings
                                                        (GtkPrintOperation *op,
                                                         GtkPrintSettings *print_settings);

Sets the print settings for op. This is typically used to re-establish print settings from a previous print operation, see gtk_print_operation_run().

op : | a GtkPrintOperation
print_settings : | GtkPrintSettings, or NULL

Since 2.10

gtk_print_operation_get_print_settings ()

GtkPrintSettings*   gtk_print_operation_get_print_settings
                                                        (GtkPrintOperation *op);

Returns the current print settings.

Note that the return value is NULL until either gtk_print_operation_set_print_settings() or gtk_print_operation_run() have been called.

op : | a GtkPrintOperation
Returns : | the current print settings of op.

Since 2.10

gtk_print_operation_set_job_name ()

void                gtk_print_operation_set_job_name    (GtkPrintOperation *op,
                                                         const gchar *job_name);

Sets the name of the print job. The name is used to identify the job (e.g. in monitoring applications like eggcups).

If you don't set a job name, GTK+ picks a default one by numbering successive print jobs.

op : | a GtkPrintOperation
job_name : | a string that identifies the print job

Since 2.10

gtk_print_operation_set_n_pages ()

void                gtk_print_operation_set_n_pages     (GtkPrintOperation *op,
                                                         gint n_pages);

Sets the number of pages in the document.

This must be set to a positive number before the rendering starts. It may be set in a ::begin-print signal hander.

Note that the page numbers passed to the ::request-page-setup and ::draw-page signals are 0-based, i.e. if the user chooses to print all pages, the last ::draw-page signal will be for page n_pages - 1.

op : | a GtkPrintOperation
n_pages : | the number of pages

Since 2.10

gtk_print_operation_set_current_page ()

void                gtk_print_operation_set_current_page
                                                        (GtkPrintOperation *op,
                                                         gint current_page);

Sets the current page.

If this is called before gtk_print_operation_run(), the user will be able to select to print only the current page.

Note that this only makes sense for pre-paginated documents.

op : | a GtkPrintOperation
current_page : | the current page, 0-based

Since 2.10

gtk_print_operation_set_use_full_page ()

void                gtk_print_operation_set_use_full_page
                                                        (GtkPrintOperation *op,
                                                         gboolean full_page);

If full_page is TRUE, the transformation for the cairo context obtained from GtkPrintContext puts the origin at the top left corner of the page (which may not be the top left corner of the sheet, depending on page orientation and the number of pages per sheet). Otherwise, the origin is at the top left corner of the imageable area (i.e. inside the margins).

op : | a GtkPrintOperation
full_page : | TRUE to set up the GtkPrintContext for the full page

Since 2.10

gtk_print_operation_set_unit ()

void                gtk_print_operation_set_unit        (GtkPrintOperation *op,
                                                         GtkUnit unit);

Sets up the transformation for the cairo context obtained from GtkPrintContext in such a way that distances are measured in units of unit.

op : | a GtkPrintOperation
unit : | the unit to use

Since 2.10

gtk_print_operation_set_export_filename ()

void                gtk_print_operation_set_export_filename
                                                        (GtkPrintOperation *op,
                                                         const gchar *filename);

Sets up the GtkPrintOperation to generate a file instead of showing the print dialog. The indended use of this function is for implementing "Export to PDF" actions. Currently, PDF is the only supported format.

"Print to PDF" support is independent of this and is done by letting the user pick the "Print to PDF" item from the list of printers in the print dialog.

op : | a GtkPrintOperation
filename : | the filename for the exported file

Since 2.10

gtk_print_operation_set_show_progress ()

void                gtk_print_operation_set_show_progress
                                                        (GtkPrintOperation *op,
                                                         gboolean show_progress);

If show_progress is TRUE, the print operation will show a progress dialog during the print operation.

op : | a GtkPrintOperation
show_progress : | TRUE to show a progress dialog

Since 2.10

gtk_print_operation_set_track_print_status ()

void                gtk_print_operation_set_track_print_status
                                                        (GtkPrintOperation *op,
                                                         gboolean track_status);

If track_status is TRUE, the print operation will try to continue report on the status of the print job in the printer queues and printer. This can allow your application to show things like "out of paper" issues, and when the print job actually reaches the printer.

This function is often implemented using some form of polling, so it should not be enabled unless needed.

op : | a GtkPrintOperation
track_status : | TRUE to track status after printing

Since 2.10

gtk_print_operation_set_custom_tab_label ()

void                gtk_print_operation_set_custom_tab_label
                                                        (GtkPrintOperation *op,
                                                         const gchar *label);

Sets the label for the tab holding custom widgets.

op : | a GtkPrintOperation
label : | the label to use, or NULL to use the default label

Since 2.10

gtk_print_operation_run ()

GtkPrintOperationResult gtk_print_operation_run         (GtkPrintOperation *op,
                                                         GtkPrintOperationAction action,
                                                         GtkWindow *parent,
                                                         GError **error);

Runs the print operation, by first letting the user modify print settings in the print dialog, and then print the document.

Normally that this function does not return until the rendering of all pages is complete. You can connect to the ::status-changed signal on op to obtain some information about the progress of the print operation. Furthermore, it may use a recursive mainloop to show the print dialog.

If you call gtk_print_operation_set_allow_async() or set the allow-async property the operation will run asyncronously if this is supported on the platform. The ::done signal will be emitted with the operation results when the operation is done (i.e. when the dialog is canceled, or when the print succeeds or fails).

if (settings != NULL)
  gtk_print_operation_set_print_settings (print, settings);

if (page_setup != NULL)
  gtk_print_operation_set_default_page_setup (print, page_setup);

g_signal_connect (print, "begin-print",
                  G_CALLBACK (begin_print), &data);
g_signal_connect (print, "draw-page",
                  G_CALLBACK (draw_page), &data);

res = gtk_print_operation_run (print, GTK_PRINT_OPERATION_ACTION_PRINT_DIALOG, parent, &error);

if (res == GTK_PRINT_OPERATION_RESULT_ERROR)
 {
   error_dialog = gtk_message_dialog_new (GTK_WINDOW (parent),
                                   GTK_DIALOG_DESTROY_WITH_PARENT,
                         GTK_MESSAGE_ERROR,
                         GTK_BUTTONS_CLOSE,
                         "Error printing file:\n%s",
                         error->message);
   g_signal_connect (error_dialog, "response",
                     G_CALLBACK (gtk_widget_destroy), NULL);
   gtk_widget_show (error_dialog);
   g_error_free (error);
 }
else if (res == GTK_PRINT_OPERATION_RESULT_APPLY)
 {
   if (settings != NULL)
g_object_unref (settings);
   settings = g_object_ref (gtk_print_operation_get_print_settings (print));
 }

op : | a GtkPrintOperation
action : | the action to start
parent : | Transient parent of the dialog, or NULL
error : | Return location for errors, or NULL
Returns : | the result of the print operation. A return value of GTK_PRINT_OPERATION_RESULT_APPLY indicates that the printing was completed successfully. In this case, it is a good idea to obtain the used print settings with gtk_print_operation_get_print_settings() and store them for reuse with the next print operation. A value of GTK_PRINT_OPERATION_RESULT_IN_PROGRESS means the operation is running asynchronously, and will emit the ::done signal when done.

Since 2.10

gtk_print_operation_cancel ()

void                gtk_print_operation_cancel          (GtkPrintOperation *op);

Cancels a running print operation. This function may be called from a begin-print, paginate or draw-page signal handler to stop the currently running print operation.

op : a GtkPrintOperation

Since 2.10

gtk_print_operation_get_status ()

GtkPrintStatus      gtk_print_operation_get_status      (GtkPrintOperation *op);

Returns the status of the print operation. Also see gtk_print_operation_get_status_string().

op : | a GtkPrintOperation
Returns : | the status of the print operation

Since 2.10

gtk_print_operation_get_status_string ()

const gchar*        gtk_print_operation_get_status_string
                                                        (GtkPrintOperation *op);

Returns a string representation of the status of the print operation. The string is translated and suitable for displaying the print status e.g. in a GtkStatusbar.

Use gtk_print_operation_get_status() to obtain a status value that is suitable for programmatic use.

op : | a GtkPrintOperation
Returns : | a string representation of the status of the print operation

Since 2.10

gtk_print_operation_is_finished ()

gboolean            gtk_print_operation_is_finished     (GtkPrintOperation *op);

A convenience function to find out if the print operation is finished, either successfully (GTK_PRINT_STATUS_FINISHED) or unsuccessfully (GTK_PRINT_STATUS_FINISHED_ABORTED).

Note: when you enable print status tracking the print operation can be in a non-finished state even after done has been called, as the operation status then tracks the print job status on the printer.

op : | a GtkPrintOperation
Returns : | TRUE, if the print operation is finished.

Since 2.10

gtk_print_operation_get_error ()

void                gtk_print_operation_get_error       (GtkPrintOperation *op,
                                                         GError **error);

Call this when the result of a print operation is GTK_PRINT_OPERATION_RESULT_ERROR, either as returned by gtk_print_operation_run(), or in the ::done signal handler. The returned GError will contain more details on what went wrong.

op : | a GtkPrintOperation
error : | return location for the error

Since 2.10

gtk_print_run_page_setup_dialog ()

GtkPageSetup*       gtk_print_run_page_setup_dialog     (GtkWindow *parent,
                                                         GtkPageSetup *page_setup,
                                                         GtkPrintSettings *settings);

Runs a page setup dialog, letting the user modify the values from page_setup. If the user cancels the dialog, the returned GtkPageSetup is identical to the passed in page_setup, otherwise it contains the modifications done in the dialog.

Note that this function may use a recursive mainloop to show the page setup dialog. See gtk_print_run_page_setup_dialog_async() if this is a problem.

parent : | transient parent, or NULL
page_setup : | an existing GtkPageSetup, or NULL
settings : | a GtkPrintSettings
Returns : | a new GtkPageSetup

Since 2.10

GtkPageSetupDoneFunc ()

void                (*GtkPageSetupDoneFunc)             (GtkPageSetup *page_setup,
                                                         gpointer data);

The type of function that is passed to gtk_print_run_page_setup_dialog_async(). This function will be called when the page setup dialog is dismissed, and also serves as destroy notify for data.

page_setup : | the GtkPageSetup that has been
data : | user data that has been passed to gtk_print_run_page_setup_dialog_async().

gtk_print_run_page_setup_dialog_async ()

void                gtk_print_run_page_setup_dialog_async
                                                        (GtkWindow *parent,
                                                         GtkPageSetup *page_setup,
                                                         GtkPrintSettings *settings,
                                                         GtkPageSetupDoneFunc done_cb,
                                                         gpointer data);

Runs a page setup dialog, letting the user modify the values from page_setup.

In contrast to gtk_print_run_page_setup_dialog(), this function returns after showing the page setup dialog on platforms that support this, and calls done_cb from a signal handler for the ::response signal of the dialog.

parent : | transient parent, or NULL
page_setup : | an existing GtkPageSetup, or NULL
settings : | a GtkPrintSettings
done_cb : | a function to call when the user saves the modified page setup
data : | user data to pass to done_cb

Since 2.10

GtkPrintOperationPreview

typedef struct _GtkPrintOperationPreview GtkPrintOperationPreview;

gtk_print_operation_preview_end_preview ()

void                gtk_print_operation_preview_end_preview
                                                        (GtkPrintOperationPreview *preview);

Ends a preview.

This function must be called to finish a custom print preview.

preview : a GtkPrintOperationPreview

Since 2.10

gtk_print_operation_preview_is_selected ()

gboolean            gtk_print_operation_preview_is_selected
                                                        (GtkPrintOperationPreview *preview,
                                                         gint page_nr);

Returns whether the given page is included in the set of pages that have been selected for printing.

preview : | a GtkPrintOperationPreview
page_nr : | a page number
Returns : | TRUE if the page has been selected for printing

Since 2.10

gtk_print_operation_preview_render_page ()

void                gtk_print_operation_preview_render_page
                                                        (GtkPrintOperationPreview *preview,
                                                         gint page_nr);

Renders a page to the preview, using the print context that was passed to the GtkPrintOperation::preview handler together with preview.

Note that this function requires a suitable cairo context to be associated with the print context.

preview : | a GtkPrintOperationPreview
page_nr : | the page to render

Since 2.10

Property Details

The "allow-async" property

  "allow-async"              gboolean              : Read / Write

Determines whether the print operation may run asynchronously or not.

Some systems don't support asynchronous printing, but those that do will return GTK_PRINT_OPERATION_RESULT_IN_PROGRESS as the status, and emit the done signal when the operation is actually done.

The Windows port does not support asynchronous operation at all (this is unlikely to change). On other platforms, all actions except for GTK_PRINT_OPERATION_ACTION_EXPORT support asynchronous operation.

Default value: FALSE

Since 2.10

The "current-page" property

  "current-page"             gint                  : Read / Write

The current page in the document.

If this is set before gtk_print_operation_run(), the user will be able to select to print only the current page.

Note that this only makes sense for pre-paginated documents.

Allowed values: >= -1

Default value: -1

Since 2.10

The "custom-tab-label" property

  "custom-tab-label"         gchararray            : Read / Write

Used as the label of the tab containing custom widgets. Note that this property may be ignored on some platforms.

If this is NULL, GTK+ uses a default label.

Default value: NULL

Since 2.10

The "default-page-setup" property

  "default-page-setup"       GtkPageSetup          : Read / Write

The GtkPageSetup used by default.

This page setup will be used by gtk_print_operation_run(), but it can be overridden on a per-page basis by connecting to the ::request-page-setup signal.

Since 2.10

The "export-filename" property

  "export-filename"          gchararray            : Read / Write

The name of a file file to generate instead of showing the print dialog. Currently, PDF is the only supported format.

The intended use of this property is for implementing "Export to PDF" actions.

"Print to PDF" support is independent of this and is done by letting the user pick the "Print to PDF" item from the list of printers in the print dialog.

Default value: NULL

Since 2.10

The "job-name" property

  "job-name"                 gchararray            : Read / Write

A string used to identify the job (e.g. in monitoring applications like eggcups).

If you don't set a job name, GTK+ picks a default one by numbering successive print jobs.

Default value: ""

Since 2.10

The "n-pages" property

  "n-pages"                  gint                  : Read / Write

The number of pages in the document.

This must be set to a positive number before the rendering starts. It may be set in a ::begin-print signal hander.

Note that the page numbers passed to the ::request-page-setup and ::draw-page signals are 0-based, i.e. if the user chooses to print all pages, the last ::draw-page signal will be for page n_pages - 1.

Allowed values: >= -1

Default value: -1

Since 2.10

The "print-settings" property

  "print-settings"           GtkPrintSettings      : Read / Write

The GtkPrintSettings used for initializing the dialog.

Setting this property is typically used to re-establish print settings from a previous print operation, see gtk_print_operation_run().

Since 2.10

The "show-progress" property

  "show-progress"            gboolean              : Read / Write

Determines whether to show a progress dialog during the print operation.

Default value: FALSE

Since 2.10

The "status" property

  "status"                   GtkPrintStatus        : Read

The status of the print operation.

Default value: GTK_PRINT_STATUS_INITIAL

Since 2.10

The "status-string" property

  "status-string"            gchararray            : Read

A string representation of the status of the print operation. The string is translated and suitable for displaying the print status e.g. in a GtkStatusbar.

See the ::status property for a status value that is suitable for programmatic use.

Default value: ""

Since 2.10

The "track-print-status" property

  "track-print-status"       gboolean              : Read / Write

If TRUE, the print operation will try to continue report on the status of the print job in the printer queues and printer. This can allow your application to show things like "out of paper" issues, and when the print job actually reaches the printer. However, this is often implemented using polling, and should not be enabled unless needed.

Default value: FALSE

Since 2.10

The "unit" property

  "unit"                     GtkUnit               : Read / Write

The transformation for the cairo context obtained from GtkPrintContext is set up in such a way that distances are measured in units of unit.

Default value: GTK_UNIT_PIXEL

Since 2.10

The "use-full-page" property

  "use-full-page"            gboolean              : Read / Write

If TRUE, the transformation for the cairo context obtained from GtkPrintContext puts the origin at the top left corner of the page (which may not be the top left corner of the sheet, depending on page orientation and the number of pages per sheet). Otherwise, the origin is at the top left corner of the imageable area (i.e. inside the margins).

Default value: FALSE

Since 2.10

Signal Details

The "begin-print" signal

void                user_function                      (GtkPrintOperation *operation,
                                                        GtkPrintContext   *context,
                                                        gpointer           user_data)      : Run Last

Emitted after the user has finished changing print settings in the dialog, before the actual rendering starts.

A typical use for this signal is to use the parameters from the GtkPrintContext and paginate the document accordingly, and then set the number of pages with gtk_print_operation_set_n_pages().

operation : | the GtkPrintOperation on which the signal was emitted
context : | the GtkPrintContext for the current operation
user_data : | user data set when the signal handler was connected.

Since 2.10

The "create-custom-widget" signal

GObject*            user_function                      (GtkPrintOperation *operation,
                                                        gpointer           user_data)      : Run Last

Emitted when displaying the print dialog. If you return a widget in a handler for this signal it will be added to a custom tab in the print dialog. You typically return a container widget with multiple widgets in it.

The print dialog owns the returned widget, and its lifetime isn't controlled by the app. However, the widget is guaranteed to stay around until the custom-widget-apply signal is emitted on the operation. Then you can read out any information you need from the widgets.

operation : | the GtkPrintOperation on which the signal was emitted
user_data : | user data set when the signal handler was connected.
Returns : | A custom widget that gets embedded in the print dialog, or NULL

Since 2.10

The "custom-widget-apply" signal

void                user_function                      (GtkPrintOperation *operation,
                                                        GtkWidget         *widget,
                                                        gpointer           user_data)      : Run Last

Emitted right before begin-print if you added a custom widget in the create-custom-widget handler. When you get this signal you should read the information from the custom widgets, as the widgets are not guaraneed to be around at a later time.

operation : | the GtkPrintOperation on which the signal was emitted
widget : | the custom widget added in create-custom-widget
user_data : | user data set when the signal handler was connected.

Since 2.10

The "done" signal

void                user_function                      (GtkPrintOperation      *operation,
                                                        GtkPrintOperationResult result,
                                                        gpointer                user_data)      : Run Last

Emitted when the print operation run has finished doing everything required for printing. result gives you information about what happened during the run. If result is GTK_PRINT_OPERATION_RESULT_ERROR then you can call gtk_print_operation_get_error() for more information.

If you enabled print status tracking then gtk_print_operation_is_finished() may still return FALSE after this was emitted.

operation : | the GtkPrintOperation on which the signal was emitted
result : | the result of the print operation
user_data : | user data set when the signal handler was connected.

Since 2.10

The "draw-page" signal

void                user_function                      (GtkPrintOperation *operation,
                                                        GtkPrintContext   *context,
                                                        gint               page_nr,
                                                        gpointer           user_data)      : Run Last

Emitted for every page that is printed. The signal handler must render the page_nr's page onto the cairo context obtained from context using gtk_print_context_get_cairo_context().

static void
draw_page (GtkPrintOperation *operation,
           GtkPrintContext   *context,
           gint               page_nr,
           gpointer           user_data)
{
  cairo_t *cr;
  PangoLayout *layout;
  gdouble width, text_height;
  gint layout_height;
  PangoFontDescription *desc;

  cr = gtk_print_context_get_cairo_context (context);
  width = gtk_print_context_get_width (context);

  cairo_rectangle (cr, 0, 0, width, HEADER_HEIGHT);

  cairo_set_source_rgb (cr, 0.8, 0.8, 0.8);
  cairo_fill (cr);

  layout = gtk_print_context_create_pango_layout (context);

  desc = pango_font_description_from_string ("sans 14");
  pango_layout_set_font_description (layout, desc);
  pango_font_description_free (desc);

  pango_layout_set_text (layout, "some text", -1);
  pango_layout_set_width (layout, width);
  pango_layout_set_alignment (layout, PANGO_ALIGN_CENTER);

  pango_layout_get_size (layout, NULL, &layout_height);
  text_height = (gdouble)layout_height / PANGO_SCALE;

  cairo_move_to (cr, width / 2,  (HEADER_HEIGHT - text_height) / 2);
  pango_cairo_show_layout (cr, layout);

  g_object_unref (layout);
}

Use gtk_print_operation_set_use_full_page() and gtk_print_operation_set_unit() before starting the print operation to set up the transformation of the cairo context according to your needs.

operation : | the GtkPrintOperation on which the signal was emitted
context : | the GtkPrintContext for the current operation
page_nr : | the number of the currently printed page
user_data : | user data set when the signal handler was connected.

Since 2.10

The "end-print" signal

void                user_function                      (GtkPrintOperation *operation,
                                                        GtkPrintContext   *context,
                                                        gpointer           user_data)      : Run Last

Emitted after all pages have been rendered. A handler for this signal can clean up any resources that have been allocated in the ::begin-print handler.

operation : | the GtkPrintOperation on which the signal was emitted
context : | the GtkPrintContext for the current operation
user_data : | user data set when the signal handler was connected.

Since 2.10

The "paginate" signal

gboolean            user_function                      (GtkPrintOperation *operation,
                                                        GtkPrintContext   *context,
                                                        gpointer           user_data)      : Run Last

Emitted after the begin-print signal, but before the actual rendering starts. It keeps getting emitted until it returns FALSE.

This signal is intended to be used for paginating the document in small chunks, to avoid blocking the user interface for a long time. The signal handler should update the number of pages using gtk_print_operation_set_n_pages(), and return TRUE if the document has been completely paginated.

If you don't need to do pagination in chunks, you can simply do it all in the begin-print handler, and set the number of pages from there.

operation : | the GtkPrintOperation on which the signal was emitted
context : | the GtkPrintContext for the current operation
user_data : | user data set when the signal handler was connected.
Returns : | TRUE if pagination is complete

Since 2.10

The "preview" signal

gboolean            user_function                      (GtkPrintOperation        *operation,
                                                        GtkPrintOperationPreview *preview,
                                                        GtkPrintContext          *context,
                                                        GtkWindow                *parent,
                                                        gpointer                  user_data)      : Run Last

Gets emitted when a preview is requested from the native dialog.

The default handler for this signal uses an external viewer application to preview.

To implement a custom print preview, an application must return TRUE from its handler for this signal. In order to use the provided context for the preview implementation, it must be given a suitable cairo context with gtk_print_context_set_cairo_context().

The custom preview implementation can use gtk_print_operation_preview_is_selected() and gtk_print_operation_preview_render_page() to find pages which are selected for print and render them. The preview must be finished by calling gtk_print_operation_preview_end_preview() (typically in response to the user clicking a close button).

operation : | the GtkPrintOperation on which the signal was emitted
preview : | the GtkPrintPreviewOperation for the current operation
context : | the GtkPrintContext that will be used
parent : | the GtkWindow to use as window parent, or NULL
user_data : | user data set when the signal handler was connected.
Returns : | TRUE if the listener wants to take over control of the preview

Since 2.10

The "request-page-setup" signal

void                user_function                      (GtkPrintOperation *operation,
                                                        GtkPrintContext   *context,
                                                        gint               page_nr,
                                                        GtkPageSetup      *setup,
                                                        gpointer           user_data)      : Run Last

Emitted once for every page that is printed, to give the application a chance to modify the page setup. Any changes done to setup will be in force only for printing this page.

operation : | the GtkPrintOperation on which the signal was emitted
context : | the GtkPrintContext for the current operation
page_nr : | the number of the currently printed page
setup : | the GtkPageSetup
user_data : | user data set when the signal handler was connected.

Since 2.10

The "status-changed" signal

void                user_function                      (GtkPrintOperation *operation,
                                                        gpointer           user_data)      : Run Last

Emitted at between the various phases of the print operation. See GtkPrintStatus for the phases that are being discriminated. Use gtk_print_operation_get_status() to find out the current status.

operation : | the GtkPrintOperation on which the signal was emitted
user_data : | user data set when the signal handler was connected.

Since 2.10

See Also

GtkPrintContext, GtkPrintUnixDialog


Accelerator Groups

Accelerator Groups — Groups of global keyboard accelerators for an entire GtkWindow

Synopsis

#include <gtk/gtk.h>

                    GtkAccelGroup;
GtkAccelGroup*      gtk_accel_group_new                 (void);
#define             gtk_accel_group_ref
#define             gtk_accel_group_unref
void                gtk_accel_group_connect             (GtkAccelGroup *accel_group,
                                                         guint accel_key,
                                                         GdkModifierType accel_mods,
                                                         GtkAccelFlags accel_flags,
                                                         GClosure *closure);
void                gtk_accel_group_connect_by_path     (GtkAccelGroup *accel_group,
                                                         const gchar *accel_path,
                                                         GClosure *closure);
gboolean            (*GtkAccelGroupActivate)            (GtkAccelGroup *accel_group,
                                                         GObject *acceleratable,
                                                         guint keyval,
                                                         GdkModifierType modifier);
gboolean            (*GtkAccelGroupFindFunc)            (GtkAccelKey *key,
                                                         GClosure *closure,
                                                         gpointer data);
gboolean            gtk_accel_group_disconnect          (GtkAccelGroup *accel_group,
                                                         GClosure *closure);
gboolean            gtk_accel_group_disconnect_key      (GtkAccelGroup *accel_group,
                                                         guint accel_key,
                                                         GdkModifierType accel_mods);
GtkAccelGroupEntry* gtk_accel_group_query               (GtkAccelGroup *accel_group,
                                                         guint accel_key,
                                                         GdkModifierType accel_mods,
                                                         guint *n_entries);
gboolean            gtk_accel_group_activate            (GtkAccelGroup *accel_group,
                                                         GQuark accel_quark,
                                                         GObject *acceleratable,
                                                         guint accel_key,
                                                         GdkModifierType accel_mods);
void                gtk_accel_group_lock                (GtkAccelGroup *accel_group);
void                gtk_accel_group_unlock              (GtkAccelGroup *accel_group);
GtkAccelGroup*      gtk_accel_group_from_accel_closure  (GClosure *closure);
gboolean            gtk_accel_groups_activate           (GObject *object,
                                                         guint accel_key,
                                                         GdkModifierType accel_mods);
GSList*             gtk_accel_groups_from_object        (GObject *object);
GtkAccelKey*        gtk_accel_group_find                (GtkAccelGroup *accel_group,
                                                         GtkAccelGroupFindFunc find_func,
                                                         gpointer data);
                    GtkAccelKey;
gboolean            gtk_accelerator_valid               (guint keyval,
                                                         GdkModifierType modifiers);
void                gtk_accelerator_parse               (const gchar *accelerator,
                                                         guint *accelerator_key,
                                                         GdkModifierType *accelerator_mods);
gchar*              gtk_accelerator_name                (guint accelerator_key,
                                                         GdkModifierType accelerator_mods);
gchar*              gtk_accelerator_get_label           (guint accelerator_key,
                                                         GdkModifierType accelerator_mods);
void                gtk_accelerator_set_default_mod_mask
                                                        (GdkModifierType default_mod_mask);
guint               gtk_accelerator_get_default_mod_mask
                                                        (void);

Object Hierarchy

  GObject
   +----GtkAccelGroup

Signals

  "accel-activate"                                 : Has Details
  "accel-changed"                                  : Run First / Has Details

Description

A GtkAccelGroup represents a group of keyboard accelerators, typically attached to a toplevel GtkWindow (with gtk_window_add_accel_group()). Usually you won't need to create a GtkAccelGroup directly; instead, when using GtkItemFactory, GTK+ automatically sets up the accelerators for your menus in the item factory's GtkAccelGroup.

Note that accelerators are different from mnemonics. Accelerators are shortcuts for activating a menu item; they appear alongside the menu item they're a shortcut for. For example "Ctrl+Q" might appear alongside the "Quit" menu item. Mnemonics are shortcuts for GUI elements such as text entries or buttons; they appear as underlined characters. See gtk_label_new_with_mnemonic(). Menu items can have both accelerators and mnemonics, of course.

Details

GtkAccelGroup

typedef struct _GtkAccelGroup GtkAccelGroup;

An object representing and maintaining a group of accelerators.

gtk_accel_group_new ()

GtkAccelGroup*      gtk_accel_group_new                 (void);

Creates a new GtkAccelGroup.

Returns : a new GtkAccelGroup object

gtk_accel_group_ref

#define	gtk_accel_group_ref	g_object_ref

Warning

gtk_accel_group_ref is deprecated and should not be used in newly-written code.

Deprecated equivalent of g_object_ref().

Returns : the accel group that was passed in

gtk_accel_group_unref

#define	gtk_accel_group_unref	g_object_unref

Warning

gtk_accel_group_unref is deprecated and should not be used in newly-written code.

Deprecated equivalent of g_object_unref().

gtk_accel_group_connect ()

void                gtk_accel_group_connect             (GtkAccelGroup *accel_group,
                                                         guint accel_key,
                                                         GdkModifierType accel_mods,
                                                         GtkAccelFlags accel_flags,
                                                         GClosure *closure);

Installs an accelerator in this group. When accel_group is being activated in response to a call to gtk_accel_groups_activate(), closure will be invoked if the accel_key and accel_mods from gtk_accel_groups_activate() match those of this connection.

The signature used for the closure is that of GtkAccelGroupActivate.

Note that, due to implementation details, a single closure can only be connected to one accelerator group.

accel_group : | the accelerator group to install an accelerator in
accel_key : | key value of the accelerator
accel_mods : | modifier combination of the accelerator
accel_flags : | a flag mask to configure this accelerator
closure : | closure to be executed upon accelerator activation

gtk_accel_group_connect_by_path ()

void                gtk_accel_group_connect_by_path     (GtkAccelGroup *accel_group,
                                                         const gchar *accel_path,
                                                         GClosure *closure);

Installs an accelerator in this group, using an accelerator path to look up the appropriate key and modifiers (see gtk_accel_map_add_entry()). When accel_group is being activated in response to a call to gtk_accel_groups_activate(), closure will be invoked if the accel_key and accel_mods from gtk_accel_groups_activate() match the key and modifiers for the path.

The signature used for the closure is that of GtkAccelGroupActivate.

accel_group : | the accelerator group to install an accelerator in
accel_path : | path used for determining key and modifiers.
closure : | closure to be executed upon accelerator activation

GtkAccelGroupActivate ()

gboolean            (*GtkAccelGroupActivate)            (GtkAccelGroup *accel_group,
                                                         GObject *acceleratable,
                                                         guint keyval,
                                                         GdkModifierType modifier);

accel_group :
acceleratable :
keyval :
modifier :
Returns :

GtkAccelGroupFindFunc ()

gboolean            (*GtkAccelGroupFindFunc)            (GtkAccelKey *key,
                                                         GClosure *closure,
                                                         gpointer data);

key :
closure :
data :
Returns :

Since 2.2

gtk_accel_group_disconnect ()

gboolean            gtk_accel_group_disconnect          (GtkAccelGroup *accel_group,
                                                         GClosure *closure);

Removes an accelerator previously installed through gtk_accel_group_connect().

accel_group : | the accelerator group to remove an accelerator from
closure : | the closure to remove from this accelerator group
Returns : | TRUE if the closure was found and got disconnected

gtk_accel_group_disconnect_key ()

gboolean            gtk_accel_group_disconnect_key      (GtkAccelGroup *accel_group,
                                                         guint accel_key,
                                                         GdkModifierType accel_mods);

Removes an accelerator previously installed through gtk_accel_group_connect().

accel_group : | the accelerator group to install an accelerator in
accel_key : | key value of the accelerator
accel_mods : | modifier combination of the accelerator
Returns : | TRUE if there was an accelerator which could be removed, FALSE otherwise

gtk_accel_group_query ()

GtkAccelGroupEntry* gtk_accel_group_query               (GtkAccelGroup *accel_group,
                                                         guint accel_key,
                                                         GdkModifierType accel_mods,
                                                         guint *n_entries);

Queries an accelerator group for all entries matching accel_key and accel_mods.

accel_group : | the accelerator group to query
accel_key : | key value of the accelerator
accel_mods : | modifier combination of the accelerator
n_entries : | location to return the number of entries found, or NULL
Returns : | an array of n_entries GtkAccelGroupEntry elements, or NULL. The array is owned by GTK+ and must not be freed.

gtk_accel_group_activate ()

gboolean            gtk_accel_group_activate            (GtkAccelGroup *accel_group,
                                                         GQuark accel_quark,
                                                         GObject *acceleratable,
                                                         guint accel_key,
                                                         GdkModifierType accel_mods);

accel_group :
accel_quark :
acceleratable :
accel_key :
accel_mods :
Returns :

gtk_accel_group_lock ()

void                gtk_accel_group_lock                (GtkAccelGroup *accel_group);

Locks the given accelerator group.

Locking an acelerator group prevents the accelerators contained within it to be changed during runtime. Refer to gtk_accel_map_change_entry() about runtime accelerator changes.

If called more than once, accel_group remains locked until gtk_accel_group_unlock() has been called an equivalent number of times.

accel_group : a GtkAccelGroup

gtk_accel_group_unlock ()

void                gtk_accel_group_unlock              (GtkAccelGroup *accel_group);

Undoes the last call to gtk_accel_group_lock() on this accel_group.

accel_group : a GtkAccelGroup

gtk_accel_group_from_accel_closure ()

GtkAccelGroup*      gtk_accel_group_from_accel_closure  (GClosure *closure);

Finds the GtkAccelGroup to which closure is connected; see gtk_accel_group_connect().

closure : | a GClosure
Returns : | the GtkAccelGroup to which closure is connected, or NULL.

gtk_accel_groups_activate ()

gboolean            gtk_accel_groups_activate           (GObject *object,
                                                         guint accel_key,
                                                         GdkModifierType accel_mods);

Finds the first accelerator in any GtkAccelGroup attached to object that matches accel_key and accel_mods, and activates that accelerator. If an accelerator was activated and handled this keypress, TRUE is returned.

object : | the GObject, usually a GtkWindow, on which to activate the accelerator.
accel_key : | accelerator keyval from a key event
accel_mods : | keyboard state mask from a key event
Returns : | TRUE if the accelerator was handled, FALSE otherwise

gtk_accel_groups_from_object ()

GSList*             gtk_accel_groups_from_object        (GObject *object);

Gets a list of all accel groups which are attached to object.

object : | a GObject, usually a GtkWindow
Returns : | a list of all accel groups which are attached to object

gtk_accel_group_find ()

GtkAccelKey*        gtk_accel_group_find                (GtkAccelGroup *accel_group,
                                                         GtkAccelGroupFindFunc find_func,
                                                         gpointer data);

Finds the first entry in an accelerator group for which find_func returns TRUE and returns its GtkAccelKey.

accel_group : | a GtkAccelGroup
find_func : | a function to filter the entries of accel_group with
data : | data to pass to find_func
Returns : | the key of the first entry passing find_func. The key is owned by GTK+ and must not be freed.

GtkAccelKey

typedef struct {
  guint           accel_key;
  GdkModifierType accel_mods;
  guint           accel_flags : 16;
} GtkAccelKey;

gtk_accelerator_valid ()

gboolean            gtk_accelerator_valid               (guint keyval,
                                                         GdkModifierType modifiers);

Determines whether a given keyval and modifier mask constitute a valid keyboard accelerator. For example, the GDK_a keyval plus GDK_CONTROL_MASK is valid - this is a "Ctrl+a" accelerator. But, you can't, for instance, use the GDK_Control_L keyval as an accelerator.

keyval : | a GDK keyval
modifiers : | modifier mask
Returns : | TRUE if the accelerator is valid

gtk_accelerator_parse ()

void                gtk_accelerator_parse               (const gchar *accelerator,
                                                         guint *accelerator_key,
                                                         GdkModifierType *accelerator_mods);

Parses a string representing an accelerator. The format looks like "<Control>a" or "<Shift><Alt>F1" or "<Release>z" (the last one is for key release). The parser is fairly liberal and allows lower or upper case, and also abbreviations such as "<Ctl>" and "<Ctrl>".

If the parse fails, accelerator_key and accelerator_mods will be set to 0 (zero).

accelerator : | string representing an accelerator
accelerator_key : | return location for accelerator keyval
accelerator_mods : | return location for accelerator modifier mask

gtk_accelerator_name ()

gchar*              gtk_accelerator_name                (guint accelerator_key,
                                                         GdkModifierType accelerator_mods);

Converts an accelerator keyval and modifier mask into a string parseable by gtk_accelerator_parse(). For example, if you pass in GDK_q and GDK_CONTROL_MASK, this function returns "<Control>q".

If you need to display accelerators in the user interface, see gtk_accelerator_get_label().

accelerator_key : | accelerator keyval
accelerator_mods : | accelerator modifier mask
Returns : | a newly-allocated accelerator name

gtk_accelerator_get_label ()

gchar*              gtk_accelerator_get_label           (guint accelerator_key,
                                                         GdkModifierType accelerator_mods);

Converts an accelerator keyval and modifier mask into a string which can be used to represent the accelerator to the user.

accelerator_key : | accelerator keyval
accelerator_mods : | accelerator modifier mask
Returns : | a newly-allocated string representing the accelerator.

Since 2.6

gtk_accelerator_set_default_mod_mask ()

void                gtk_accelerator_set_default_mod_mask
                                                        (GdkModifierType default_mod_mask);

Sets the modifiers that will be considered significant for keyboard accelerators. The default mod mask is GDK_CONTROL_MASK | GDK_SHIFT_MASK | GDK_MOD1_MASK | GDK_SUPER_MASK | GDK_HYPER_MASK | GDK_META_MASK, that is, Control, Shift, Alt, Super, Hyper and Meta. Other modifiers will by default be ignored by GtkAccelGroup. You must include at least the three modifiers Control, Shift and Alt in any value you pass to this function.

The default mod mask should be changed on application startup, before using any accelerator groups.

default_mod_mask : accelerator modifier mask

gtk_accelerator_get_default_mod_mask ()

guint               gtk_accelerator_get_default_mod_mask
                                                        (void);

Gets the value set by gtk_accelerator_set_default_mod_mask().

Returns : the default accelerator modifier mask

Signal Details

The "accel-activate" signal

gboolean            user_function                      (GtkAccelGroup  *accel_group,
                                                        GObject        *acceleratable,
                                                        guint           keyval,
                                                        GdkModifierType modifier,
                                                        gpointer        user_data)          : Has Details

The accel-activate signal is an implementation detail of GtkAccelGroup and not meant to be used by applications.

accel_group : | the GtkAccelGroup which received the signal
acceleratable : | the object on which the accelerator was activated
keyval : | the accelerator keyval
modifier : | the modifier combination of the accelerator
user_data : | user data set when the signal handler was connected.
Returns : | TRUE if the accelerator was activated

The "accel-changed" signal

void                user_function                      (GtkAccelGroup  *accel_group,
                                                        guint           keyval,
                                                        GdkModifierType modifier,
                                                        GClosure       *accel_closure,
                                                        gpointer        user_data)          : Run First / Has Details

The accel-changed signal is emitted when a GtkAccelGroupEntry is added to or removed from the accel group.

Widgets like GtkAccelLabel which display an associated accelerator should connect to this signal, and rebuild their visual representation if the accel_closure is theirs.

accel_group : | the GtkAccelGroup which received the signal
keyval : | the accelerator keyval
modifier : | the modifier combination of the accelerator
accel_closure : | the GClosure of the accelerator
user_data : | user data set when the signal handler was connected.

See Also

gtk_window_add_accel_group(), gtk_accel_map_change_entry(), gtk_item_factory_new(), gtk_label_new_with_mnemonic()


Migration Checklist

Implement GtkWidget::popup_menu
Use GdkEventExpose.region
Test for modifier keys correctly
Use named icons

This chapter includes a checklist of things you need to do to ensure that your programs are good citizens in the GTK+ world. By paying attention to the points in the checklist, you ensure that many automatic features of GTK+ will work correctly in your program.

Implement GtkWidget::popup_menu

Why. By handling this signal, you let widgets have context-sensitive menus that can be invoked with the standard key bindings.

The GtkWidget::popup_menu signal instructs the widget for which it is emitted to create a context-sensitive popup menu. By default, the key binding mechanism is set to emit this signal when the Shift-F10 or Menu keys are pressed while a widget has the focus. If a widget in your application shows a popup menu when you press a mouse button, you can make it work as well through the normal key binding mechanism in the following fahion:

  1. Write a function to create and show a popup menu. This function needs to know the button number and the event's time to pass them to gtk_menu_popup(). You can implement such a function like this:

    static void
do_popup_menu (GtkWidget *my_widget, GdkEventButton *event)
{
  GtkWidget *menu;
  int button, event_time;

  menu = gtk_menu_new ();
  g_signal_connect (menu, "deactivate",
                    G_CALLBACK (gtk_widget_destroy), NULL);

  /* ... add menu items ... */

  if (event)
    {
      button = event->button;
      event_time = event->time;
    }
  else
    {
      button = 0;
      event_time = gtk_get_current_event_time ();
    }

  gtk_menu_attach_to_widget (GTK_MENU (menu), my_widget, NULL);
  gtk_menu_popup (GTK_MENU (menu), NULL, NULL, NULL, NULL,
                  button, event_time);
}

  2. In your button_press handler, call this function when you need to pop up a menu:

    static gboolean
my_widget_button_press_event_handler (GtkWidget *widget, GdkEventButton *event)
{
  /* Ignore double-clicks and triple-clicks */
  if (event->button == 3 && event->type == GDK_BUTTON_PRESS)
    {
      do_popup_menu (widget, event);
      return TRUE;
    }

  return FALSE;
}

  3. Implement a handler for the popup_menu signal:

    static gboolean
my_widget_popup_menu_handler (GtkWidget *widget)
{
  do_popup_menu (widget, NULL);
  return TRUE;
}

Note

If you do not pass a positioning function to gtk_menu_popup(), it will show the menu at the mouse position by default. This is what you usually want when the menu is shown as a result of pressing a mouse button. However, if you press the Shift-F10 or Menu keys while the widget is focused, the mouse cursor may not be near the widget at all. In the example above, you may want to provide your own menu-positioning function in the case where the event is NULL. This function should compute the desired position for a menu when it is invoked through the keyboard. For example, GtkEntry aligns the top edge of its popup menu with the bottom edge of the entry.

Note

For the standard key bindings to work, your widget must be able to take the keyboard focus. In general, widgets should be fully usable through the keyboard and not just the mouse. The very first step of this is to ensure that your widget turns on the GTK_CAN_FOCUS flag.


Migrating from GnomeAbout to GtkAboutDialog

Since version 2.6, GTK+ provides the GtkAboutDialog widget as a replacement for the GnomeAbout dialog in the libgnomeui library.

GtkAboutDialog supports all features found in GnomeAbout. The GtkAboutDialog API is bigger, since it follows the GTK+ policy to have getters and setters for all widget properties, but it isn't much more complex than GnomeAbout.

To convert an application that uses GnomeAbout to GtkAboutDialog, as a first step, replace calls like

    const gchar *documentors[] = {
      "Documenter 1",
      "Documenter 2",
      NULL
    };

    const gchar *documentors[] = {
      "Author 1",
      "Author 2",
      NULL
    };

    GtkWidget *about = gnome_about_new ("GNOME Test Program", VERSION,
                    "(C) 1998-2001 The Free Software Foundation",
                    "Program to display GNOME functions.",
                    authors,
                    documenters,
                    _("translator-credits"),
                    "logo.png");

by something like

    GdkPixbuf *logo = gdk_pixbuf_new_from_file ("logo.png", NULL);
    GtkWidget *about = g_object_new (GTK_TYPE_ABOUT_DIALOG,
                                     "name", "GNOME Test Program",
                                     "version", VERSION,
                         "copyright", "(C) 1998-2001 The Free Software Foundation",
                     "comments", "Program to display GNOME functions.",
                         "authors", authors,
                         "documenters", documenters,
                         "translator-credits", _("translator-credits"),
                     "logo", logo,
                                     NULL);
    g_object_unref (pixbuf);

If the g_object_new() construction scares you, you can also use gtk_about_dialog_new() to construct the dialog and then use the setters for the individual properties.

Once you are done with the initial conversion, you may want to look into using some of the features of GtkAboutDialog which are not present in GnomeAbout.

  • You can specify license information with the license property

  • You can add separate credits for artists with the artists property

  • You can add a pointer to the website of your application, using the website and website-label properties.

  • If your credits contain email addresses or URLs, you can turn them into clickable links using gtk_about_dialog_set_email_hook() and gtk_about_dialog_set_url_hook().


Migrating from old menu and toolbar systems to GtkAction

Federico Mena-Quintero

<federicoximian.com>

Actions and Action Groups
User Interface Manager Object
Migrating from GnomeUIInfo

Prior to GTK+ 2.4, there were several APIs in use to create menus and toolbars. GTK+ itself included GtkItemFactory, which was historically used in the GIMP; libgnomeui provided the gnome-ui set of macros; libbonoboui provided a complex mechanism to do menu merging across embedded components. GTK+ 2.4 includes a system for creating menus and toolbars, with merging of items, based around the GtkAction mechanism.

Actions and Action Groups

A GtkAction represents an operation that the user can perform from the menus and toolbars of an application. It is similar to "verbs" in other menu systems. A GtkAction has a name, which is its identifier, and it can have several widgets that represent it in the user interface. For example, an action for EditCopy can have a menu item as well as a toolbar button associated to it. If there is nothing selected in the document, the application can simply de-sensitize the EditCopy action; this will cause both the menu item and the toolbar button to be de-sensitized automatically. Similarly, whenever the user selects the menu item or the toolbar button associated to the EditCopy action, the corresponding GtkAction object will emit an "activate" signal.

GtkActionGroup is simply a group of GtkAction objects. An application may want to have several groups: one for global actions such as "new document", "about", and "exit"; then one group for each open document with actions specific to the document, such as "cut", "copy", "paste", and "print".

Normal actions are simply commands, such as FileSave or EditCopy. Toggle actions can be active or inactive, such as FormatBold or ViewShowRulers. Radio actions define a set of items for which one and only one can be active at a time, for example, { ViewHighQuality, ViewNormalQuality, ViewLowQuality }.


Migrating from GnomeDruid to GtkAssistant

Carlos Garnacho

<carlosggnome.org>

Inserting pages
Decorating the assistant pages
Setting the page flow

Since version 2.10, GTK+ provides the GtkAssistant widget as a replacement for the GnomeDruid widget in the libgnomeui library.

Conceptually, both GtkAssistant and GnomeDruid do the same task, but there are several areas where the API has been completely redesigned, so this chapter covers the main changes between both widgets.

Inserting pages

GnomeDruid was implemented as a container for GnomeDruidPage abstract objects, which are implemented by the GnomeDruidPageEdge and GnomeDruidPageStandard widgets. Instead, GtkAssistant allows any widget to be a page, and implements per-page settings (such as page type or title) as child properties. So instead of:

/* Page 1 */
page = gnome_druid_page_edge_new (GNOME_EDGE_START);
gnome_druid_page_edge_set_test (GNOME_DRUID_PAGE_EDGE (page),
                                "Welcome to the assistant, it will make your life easier");
gtk_widget_show (page);
gnome_druid_append_page (GNOME_DRUID (druid), GNOME_DRUID_PAGE (page));

/* Page 2 */
page = gnome_druid_page_standard_new ();
gtk_container_add (GTK_CONTAINER (GNOME_DRUID_PAGE_STANDARD (page)->vbox,
                   create_page1 ());
gtk_widget_show_all (page);
gnome_druid_append_page (GNOME_DRUID (druid), GNOME_DRUID_PAGE (page));

/* Page 3 */
page = gnome_druid_page_edge_new (GNOME_EDGE_FINISH);
gnome_druid_page_edge_set_test (GNOME_DRUID_PAGE_EDGE (page),
                                "Now you are done, your life is easier");
gtk_widget_show (page);
gnome_druid_append_page (GNOME_DRUID (druid), GNOME_DRUID_PAGE (page));

You have to write:

gtk_assistant_append_page (GTK_ASSISTANT (assistant),
                           gtk_label_new ("Welcome to the assistant, it will make your life easier"));
gtk_assistant_append_page (GTK_ASSISTANT (assistant),
                           create_page1 ());
gtk_assistant_append_page (GTK_ASSISTANT (assistant),
                           gtk_label_new ("Now you are done, your life is easier");


Migrating from GnomeColorPicker to GtkColorButton

Since version 2.6, GTK+ provides the GtkColorButton widget as a replacement for the GnomeColorPicker widget in the libgnomeui library.

Porting an application from GnomeColorPicker to GtkColorButton is very simple. GtkColorButton doesn't support dithering (since it is rarely needed on modern hardware), and it doesn't have setters and getters to set the color from floating point or integer components. So instead of

   guint red, green, blue, alpha;
   /* ... */
   gnome_color_picker_set_i8 (color_picker, red, green, blue, alpha);

you have to write

   GdkColor color;

   color.red = red << 8;
   color.green = green << 8;
   color.blue = blue << 8;
   gtk_color_button_set_color (color_picker, &color);
   gtk_color_button_set_alpha (color_picker, alpha << 8);

and similarly for the setters taking other number formats. For gnome_color_picker_set_i16() no conversion is needed, for gnome_color_picker_set_d(), you need to convert the color components like this:

   color.red = (guint16) (red * 65535.0 + 0.5);
   color.green = (guint16) (green * 65535.0 + 0.5);
   color.blue = (guint16) (blue * 65535.0 + 0.5);


Migrating from GtkOptionMenu and GtkCombo to GtkComboBox and GtkComboBoxEntry

Migrating from GtkOptionMenu to GtkComboBox
Migrating from GtkCombo to GtkComboBoxEntry
New features

Prior to 2.4, GTK+ offered two widgets for the task of selecting one item from a list of options. GtkOptionMenu presents the list of options as a menu while GtkCombo presents them in a Windows-style list popup. The only difference between the two is that a GtkCombo allows to manually edit the selected value, while the GtkOptionMenu does not.

In GTK+ 2.4, a unified API for list selection was introduced, with GtkComboBox for the non-editable case and GtkComboBoxEntry for the editable case. The selection of the display style — menu or list — is no longer done at the API level, but has been made themeable via the style property GtkComboBox::appearance.

Migrating from GtkOptionMenu to GtkComboBox

Here is an example of a simple, but typical use of GtkOptionMenu:

GtkWidget *option_menu, *menu, *menu_item;

option_menu = gtk_option_menu_new ();
menu = gtk_menu_new ();

menu_item = gtk_menu_item_new_with_label ("First Item");
gtk_menu_shell_append (GTK_MENU_SHELL (menu), menu_item);
gtk_widget_show (menu_item);
menu_item = gtk_menu_item_new_with_label ("Second Item");
gtk_menu_shell_append (GTK_MENU_SHELL (menu), menu_item);
gtk_widget_show (menu_item);
menu_item = gtk_menu_item_new_with_label ("Third Item");
gtk_menu_shell_append (GTK_MENU_SHELL (menu), menu_item);
gtk_widget_show (menu_item);

gtk_option_menu_set_menu (GTK_OPTION_MENU (option_menu), menu);

In order to react to the user's selection, connect to the "changed" signal on the option menu and use gtk_option_menu_get_history() to retrieve the index of the selected item.

And here is how it would be done with a GtkComboBox:

GtkWidget *combo_box;

combo_box = gtk_combo_box_new_text ();

gtk_combo_box_append_text (GTK_COMBO_BOX (combo_box), "First Item");
gtk_combo_box_append_text (GTK_COMBO_BOX (combo_box), "Second Item");
gtk_combo_box_append_text (GTK_COMBO_BOX (combo_box), "Third Item");

In order to react to the user's selection, connect to the "changed" signal on the combo box and use gtk_combo_box_get_active() to retrieve the index of the selected item.

A slightly more complex example involving images:

GtkWidget *option_menu, *menu, *menu_item;

option_menu = gtk_option_menu_new ();
menu = gtk_menu_new ();

menu_item = gtk_image_menu_item_new_with_label ("First Item");
gtk_image_menu_item_set_image (gtk_image_new_from_pixbuf (pixbuf1));
gtk_menu_shell_append (GTK_MENU_SHELL (menu), menu_item);
gtk_widget_show (menu_item);
menu_item = gtk_image_menu_item_new_with_label ("Second Item");
gtk_image_menu_item_set_image (gtk_image_new_from_pixbuf (pixbuf2));
gtk_menu_shell_append (GTK_MENU_SHELL (menu), menu_item);
gtk_widget_show (menu_item);
menu_item = gtk_image_menu_item_new_with_label ("Third Item");
gtk_image_menu_item_set_image (gtk_image_new_from_pixbuf (pixbuf3));
gtk_menu_shell_append (GTK_MENU_SHELL (menu), menu_item);
gtk_widget_show (menu_item);

gtk_option_menu_set_menu (GTK_OPTION_MENU (option_menu), menu);

can be done using a GtkComboBox as follows:

GtkListStore *store;
GtkTreeIter iter;
GtkCellRenderer *renderer;
GtkWidget *combo_box;

store = gtk_list_store_new (2, GDK_TYPE_PIXBUF, G_TYPE_STRING);

gtk_list_store_append (store, &iter);
gtk_list_store_set (store, &iter, 0, pixbuf1, 1, "First Item", -1);
gtk_list_store_append (store, &iter);
gtk_list_store_set (store, &iter, 0, pixbuf2, 1, "Second Item", -1);
gtk_list_store_append (store, &iter);
gtk_list_store_set (store, &iter, 0, pixbuf3, 1, "Third Item", -1);

combo_box = gtk_combo_box_new_with_model (GTK_TREE_MODEL (store));

renderer = gtk_cell_renderer_pixbuf_new ();
gtk_cell_layout_pack_start (GTK_CELL_LAYOUT (combo_box), renderer, FALSE);
gtk_cell_layout_set_attributes (GTK_CELL_LAYOUT (combo_box), renderer,
                                "pixbuf", 0,
                                NULL);

renderer = gtk_cell_renderer_text_new ();
gtk_cell_layout_pack_start (GTK_CELL_LAYOUT (combo_box), renderer, TRUE);
gtk_cell_layout_set_attributes (GTK_CELL_LAYOUT (combo_box), renderer,
                                "text", 1,
                                NULL);


Migrating from GtkFileSelection to GtkFileChooser

Federico Mena-Quintero

<federicoximian.com>

Creating a GtkFileChooserDialog
Selection Modes
Installing a Preview widget
Installing Extra Widgets
New features

GtkFileChooser, starting with GTK+ 2.4, is the new set of APIs for file selection widgets and dialogs. Previous versions of GTK+ used GtkFileSelection, which has numerous problems.

GtkFileChooser is an abstract interface that can be implemented by widgets that perform file selection tasks. Two widgets in GTK+ implement this interface: GtkFileChooserDialog and GtkFileChooserWidget. Most applications simply need to use GtkFileChooserDialog, which is a dialog box that allows the user to select existing files for opening them, or to pick new filenames for saving documents. GtkFileChooserWidget is for special applications that need to embed a file selection widget inside a larger window. In the context of GTK+, GtkFileChooserDialog is simply a GtkDialog box with a GtkFileChooserWidget. inside.

Creating a GtkFileChooserDialog

To create a GtkFileChooserDialog, you simply call gtk_file_chooser_dialog_new(). This function is similar to gtk_dialog_new() in that it takes parameters for the title of the dialog box and its transient parent, as well as its buttons. In addition, it takes in an argument that determines whether the file chooser dialog will be used for opening existing files or for saving to a possibly new file.

Please see Example 29, “Typical usage” for how to create a simple file chooser dialog and extract the selected filename from it.


Migrating from GnomeIconList to GtkIconView

Since version 2.6, GTK+ provides the GtkIconView widget. It is similar in functionality to the GnomeIconList widget in the libgnomeui library, both widgets provide a way to lay out named icons in a grid. The distinctive feature of the GTK+ widget is that it follows the model-view pattern, allowing it to share the actual data (i.e. the names and images of the icons) with other views.

GtkIconView currently doesn't support some features found in GnomeIconList. Icons can not be positioned freely, the spacing is not customizable, and it is not possible to edit the names of icons.

To convert an application that uses GnomeIconList to GtkIconView, the first step is to organize your data in a GtkTreeModel. GnomeIconList lets you directly insert data with gnome_icon_list_insert() and gnome_icon_list_insert_pixbuf() and their append variants. So, if you previously had a function to fill your icon list similar to this one:

      void
      fill_icon_list (GnomeIconList *icon_list)
      {
        gnome_icon_list_append (icon_list, "file1.png", "Icon 1");
        gnome_icon_list_append (icon_list, "file2.png", "Icon 2");

        /* more icons ... */
      }

you will have to create a tree model, attach your icon view to it, and fill the model:

      enum {
        PIXBUF_COLUMN,
        TEXT_COLUMN,

        /* you can have more columns here, e.g */

        DATA_COLUMN
      };

      void
      fill_model (GtkListStore *store)
      {
        GtkTreeIter iter;
        GdkPixbuf *pixbuf;

        gtk_list_store_append (store, &iter);
        pixbuf = gdk_pixbuf_new_from_file ("file1.png", NULL);
        gtk_list_store_set (store, &iter, PIXBUF_COLUMN, pixbuf, TEXT_COLUMN, "Icon 1", -1);
        g_object_unref (pixbuf);

        gtk_list_store_append (store, &iter);
        pixbuf = gdk_pixbuf_new_from_file ("file2.png", NULL);
        gtk_list_store_set (store, &iter, PIXBUF_COLUMN, pixbuf, TEXT_COLUMN, "Icon 2", -1);
        g_object_unref (pixbuf);

        /* more icons ... */
      }

      int
      main (int argc, char *argv[])
      {
        GtkWidget *icon_view;
        GtkListStore *store;

        gtk_init (&argc, &argv);

        /* do other initialization... */

        /* construct the GtkIconView */
        icon_view = gtk_icon_view_new ();
        store = gtk_list_store_new (3, GDK_TYPE_PIXBUF, G_TYPE_STRING, G_TYPE_POINTER);

        gtk_icon_view_set_pixbuf_column (GTK_ICON_VIEW (icon_view), PIXBUF_COLUMN);
        gtk_icon_view_set_text_column (GTK_ICON_VIEW (icon_view), TEXT_COLUMN);
        gtk_icon_view_set_model (GTK_ICON_VIEW (icon_view), GTK_TREE_MODEL (store));

        fill_model (store);

        /* ... */
      }

This example uses a GtkListStore as model, but part of the elegance of the model-view pattern is that you can easily use another tree model implementation, or even write your own custom tree model.

Your application may make use of extra data attached to the icons in the GnomeIconList via gnome_icon_list_set_icon_data() and gnome_icon_list_get_icon_data(). With GtkIconView such data is most conveniently stored in an extra column in the tree model, so you would call a function like

    void
    set_icon_data (GtkIconView *icon_view,
                   gint         idx,
                   gpointer     data)
    {
       GtkTreeModel *model;
       GtkTreeIter iter;

       model = gtk_icon_view_get_model (icon_view);

       if (gtk_tree_model_iter_nth_child (model, &iter, NULL, idx))
         gtk_list_store_set (GTK_LIST_STORE (model), &iter,
                             DATA_COLUMN, data, -1);
    }

assuming that your tree model has a DATA_COLUMN of type G_TYPE_POINTER.

There is a number of minor API differences between GnomeIconList and GtkIconView:

  • <typename>GnomeIconListMode</typename> is replaced by the orientation property of GtkIconView

  • GtkIconView can not be frozen in the same way as GnomeIconList can with gnome_icon_list_freeze() and gnome_icon_list_thaw(). Instead you can replace the whole model of a GtkIconView, instead of doing many small changes to the existing model.


Migrating from GnomeHRef to GtkLinkButton

Since version 2.10, GTK+ provides the GtkLinkButton widget as a replacement for the GnomeHRef widget in the libgnomeui library.

Porting an application from GnomeHRef to GtkLinkButton is very simple. GtkLinkButton does not have a default action for "clicked" signal. So instead of simply creating the widget

      GtkWidget *button;

      button = gnome_href_new (url, "");

you will have to handle the activation of the GtkLinkButton, using the "clicked" signal for instance

      static void
      link_button_clicked_cb (GtkWidget *widget,
                              gpointer   data)
      {
        const gchar *link;

    link = gtk_link_button_get_uri (GTK_LINK_BUTTON (widget));
    open_browser_at_url (link);
      }

      /* ... */

        GtkWidget *button;

    button = gtk_link_button_new (url);
    g_signal_connect (button, "clicked",
                      G_CALLBACK (link_button_clicked_cb), NULL);

If you have more than one GtkLinkButton instead of connecting a signal to each one, you can use a "hook function" which will be called whenever a user activates a link button

      static void
      link_button_hook (GtkLinkButton *button,
                        const gchar   *link,
            gpointer       user_data)

      {
        open_browser_at_url (link);
      }

      /* ... */

        GtkWidget *button1 = gtk_link_button_new (uri1);
    GtkWidget *button2 = gtk_link_button_new (uri2);

        gtk_link_button_set_uri_hook (link_button_hook, NULL, NULL);


Migrating from EggRecent to GtkRecentChooser

Emmanuele

<ebassigmail.com>

Managing the Recently Used Documents
Displaying the Recently Used Documents
Advanced usage

Since version 2.10, GTK+ provides a way of handling the recently used documents. It is similar to the code that has lived inside the libegg library and has been incorporated by many applications. The GTK+ version aims to completely replace that code, and offers many distinctive features that improve the registration and visualization of the recently used documents, such as:

  • Better performances while reading and writing the list of recently used files

  • More meta-data available for each recent document, like the applications that have registered a document inside the list, the last time and the number of times the same application did register a document inside the list, an optional user readable name and description of the document

  • Improved the ability to sort and filter the documents, also using custom sorting and filtering functions

  • New widgets for displaying the list, and better integration with current GtkFileChooser and GtkUIManager widgets

Managing the Recently Used Documents

GtkRecentManager is used to manage the Recently Used Documents. To create a new GtkRecentManager, you simply call gtk_recent_manager_new(). Like the EggRecentModel inside EggRecent, the GtkRecentManager loads the list of the recent documents and notifies you of changes inside the list.

Usually, instead of creating a new GtkRecentManager each time you need it, you'll want to use the gtk_recent_manager_get_default() function.

To add a document to the list, you can use gtk_recent_manager_add_item(), like:

        GtkRecentManager *manager;

    manager = gtk_recent_manager_new ();

    if (!gtk_recent_manager_add_item (manager, document_uri))
      {
        /* warn about the error */
      }

    g_object_unref (manager);

The gtk_recent_manager_add_item() function will try and guess some of the meta-data associated to a URI. If you know some of meta-data about the document yourself, set the desired fields of a GtkRecentData structure and pass it to the gtk_recent_manager_add_full() function instead:

        GtkRecentManager *manager;
        GtkRecentData *recent_data;

    manager = gtk_recent_manager_new ();

    recent_data = g_new0 (GtkRecentData, 1);
    /* the user visible name of the document (maybe its title); should
     * be preferred when displaying the item into the list
     */
        recent_data->display_name = document_name;

    /* the MIME type is mandatory */
    recent_data->mime_type = document_mime_type;

    /* the name of the application that is registering the document
     * (also mandatory); usually, the same name you used with
     * the g_set_application_name () function.
     */
    recent_data-&app_name = APP_NAME;

    /* the command to open a file; the %u string will be automagically
     * expanded to the document's URI when getting the application's
     * command line from the GtkRecentInfo object with
     * gtk_recent_info_get_application_info ()
     */
    recent_data-&app_exec = g_strjoin (" ", g_get_prgname (), "--open-file", "%u", NULL);

    if (!gtk_recent_manager_add_full (manager, document_uri, recent_data))
      {
        /* warn about the error */
      }

    g_free (recent_data->app_exec);
    g_free (recent_data);
    g_object_unref (manager);

Getting the list of items is also similar to EggRecentModel; the GtkRecentInfo data is allocated at look up time in order not to waste memory keeping it around, so you must remember to free the data inside the list and then the list itself when you are done using it:

        GtkRecentManager *manager;
        GList *recent_items, *l;

    manager = gtk_recent_manager_get_default();

    recent_items = gtk_recent_manager_get_items (manager);
    for (l = recent_items; l != NULL; l = l->next)
      {
        GtkRecentInfo *recent_info = l->data;

        do_something_with_the_item (recent_info);
      }

    /* free everything and the list */
    g_list_foreach (recent_items, (GFunc) gtk_recent_info_unref, NULL);
    g_list_free (recent_items);

You can also look up a single item:

        GtkRecentInfo *recent_info;
    GError *error = NULL;

    recent_info = gtk_recent_manager_lookup_item (manager, document_uri, &error);
    if (error)
      {
        display_error (error);

        g_error_free (error);
      }
    else
      {
        do_something_with_the_item (recent_info);

        gtk_recent_info_unref (recent_info);
      }

The GtkRecentInfo is a reference counted boxed type, and it holds all the meta-data of a recently used document, like its display name, its description, the list of each application that has registered the document or the list of groups to which the document belong.


Using GTK+ on Mac OS X

Using GTK+ on Mac OS X — OS X-specific aspects of using GTK+

Using GTK+ on Mac OS X

The Mac OS X port of GTK+ is an implementation of GDK (and therefore GTK+) on top of the Quarz API.

Currently, the Mac OS X port does not use any additional commandline options or environment variables.

For up-to-date information about the current status of this port, see the project page.


gtk-query-immodules-2.0

gtk-query-immodules-2.0 — Input method module registration utility

Synopsis

gtk-query-immodules-2.0 [module...]

Description

gtk-query-immodules-2.0 collects information about loadable input method modules for GTK+ and writes it to stdout.

If called without arguments, it looks for modules in the GTK+ input method module path.

If called with arguments, it looks for the specified modules. The arguments may be absolute or relative paths.

Environment

The environment variable GTK_PATH can be used to prepend directories to the input method module path.

Bugs

None known yet.


Common Questions

Common Questions — Find answers to common questions in the GTK+ manual

Questions and Answers

This is an "index" of the reference manual organized by common "How do I..." questions. If you aren't sure which documentation to read for the question you have, this list is a good place to start.

1. General
1.1.

How do I get started with GTK+?

The GTK+ website offers a tutorial and a FAQ. More documentation ranging from whitepapers to online books can be found at the GNOME developer's site. After studying these materials you should be well prepared to come back to this reference manual for details.

1.2.

Where can I get help with GTK+, submit a bug report, or make a feature request?

See the documentation on this topic.

1.3.

How do I port from one GTK+ version to another?

See the list of incompatible changes from 1.2 to 2.0. Also, the GNOME 2.0 porting guide on http://developer.gnome.org has some more detailed discussion of porting from 1.2 to 2.0. You may also find useful information in the documentation for specific widgets and functions.

If you have a question not covered in the manual, feel free to ask on the mailing lists and please file a bug report against the documentation.

1.4.

How does memory management work in GTK+? Should I free data returned from functions?

See the documentation for GObject and GtkObject. For GObject note specifically g_object_ref() and g_object_unref(). GtkObject is a subclass of GObject so the same points apply, except that it has a "floating" state (explained in its documentation).

For strings returned from functions, they will be declared "const" (using G_CONST_RETURN) if they should not be freed. Non-const strings should be freed with g_free(). Arrays follow the same rule. (If you find an exception to the rules, please report a bug to http://bugzilla.gnome.org.)

1.5.

Why does my program leak memory, if I destroy a widget immediately after creating it ?

If GtkFoo isn't a toplevel window, then

 foo = gtk_foo_new ();
 gtk_widget_destroy (foo);

is a memory leak, because no one assumed the initial floating reference. If you are using a widget and you aren't immediately packing it into a container, then you probably want standard reference counting, not floating reference counting.

To to get this, you must acquire a reference to the widget and drop the floating reference (“ref and sink” in GTK+ parlance) after creating it:

 foo = gtk_foo_new ();
 g_object_ref (foo);
 gtk_object_sink (GTK_OBJECT (foo));

When you want to get rid of the widget, you must call gtk_widget_destroy() to break any external connections to the widget before dropping your reference:

 gtk_widget_destroy (foo);
 g_object_unref (foo);

When you immediately add a widget to a container, it takes care of assuming the initial floating reference and you don't have to worry about reference counting at all ... just call gtk_widget_destroy() to get rid of the widget.

1.6.

How do I use GTK+ with threads?

This is covered in the GDK threads documentation. See also the GThread documentation for portable threading primitives.

1.7.

How do I internationalize a GTK+ program?

Most people use GNU gettext, already required in order to install GLib. On a UNIX or Linux system with gettext installed, type info gettext to read the documentation.

The short checklist on how to use gettext is: call bindtextdomain() so gettext can find the files containing your translations, call textdomain() to set the default translation domain, then call gettext() to look up each string to be translated in the default domain. Conventionally, people define macros as follows for convenience:

  #define  _(x)  gettext (x)
  #define N_(x)  x

You use N_() (N stands for no-op) to mark a string for translation in a context where a function call to gettext() is not allowed, such as in an array initializer. You eventually have to call gettext() on the string to actually fetch the translation. _() both marks the string for translation and actually translates it.

Nowadays, GLib provides the common shorthand macros in the header file gi18n.h, so you don't have to define them yourself, just include that header.

Code using these macros ends up looking like this:

 #include <gi18n.h>

 static const char *global_variable = N_("Translate this string");

 static void
 make_widgets (void)
 {
    GtkWidget *label1;
    GtkWidget *label2;

    label1 = gtk_label_new (_("Another string to translate"));
    label2 = gtk_label_new (_(global_variable));
...

Libraries using gettext should use dgettext() instead of gettext(), which allows them to specify the translation domain each time they ask for a translation. Libraries should also avoid calling textdomain(), since they'll be specifying the domain instead of using the default.For dgettext() the _() macro can be defined as:

  #define _(x) dgettext ("MyDomain", x)

Again, GLib comes with the gi18n-lib.h, saving you the trouble of defining the macros by hand. The macros in that header expect the translation domain to be specified by the GETTEXT_PACKAGE macro.

1.8.

How do I use non-ASCII characters in GTK+ programs ?

GTK+ uses Unicode (more exactly UTF-8) for all text. UTF-8 encodes each Unicode codepoint as a sequence of one to six bytes and has a number of nice properties which make it a good choice for working with Unicode text in C programs:

  • ASCII characters are encoded by their familiar ASCII codepoints.

  • ASCII characters never appear as part of any other character.

  • The zero byte doesn't occur as part of a character, so that UTF-8 strings can be manipulated with the usual C library functions for handling zero-terminated strings.

More information about Unicode and UTF-8 can be found in the UTF-8 and Unicode FAQ for Unix/Linux. GLib provides functions for converting strings between UTF-8 and other encodings, see g_locale_to_utf8() and g_convert().

Text coming from external sources (e.g. files or user input), has to be converted to UTF-8 before being handed over to GTK+. The following example writes the content of a IS0-8859-1 encoded text file to stdout:

gchar *text, *utf8_text;
gsize length;
GError *error = NULL;

if (g_file_get_contents (filename, &text, &length, NULL))
  {
     utf8_text = g_convert (text, length, "UTF-8", "ISO-8859-1",
                            NULL, NULL, &error);
     if (error != NULL)
       {
         fprintf ("Couldn't convert file %s to UTF-8\n", filename);
         g_error_free (error);
       }
     else
       g_print (utf8_text);
  }
else
  fprintf (stderr, "Unable to read file %s\n", filename);

For string literals in the source code, there are several alternatives for handling non-ASCII content:

direct UTF-8 | If your editor and compiler are capable of handling UTF-8 encoded sources, it is very convenient to simply use UTF-8 for string literals, since it allows you to edit the strings in "wysiwyg". Note that choosing this option may reduce the portability of your code.
escaped UTF-8 | Even if your toolchain can't handle UTF-8 directly, you can still encode string literals in UTF-8 by using octal or hexadecimal escapes like \212 or \xa8 to encode each byte. This is portable, but modifying the escaped strings is not very convenient. Be careful when mixing hexadecimal escapes with ordinary text; "\xa8abcd" is a string of length 1 !
runtime conversion | If the string literals can be represented in an encoding which your toolchain can handle (e.g. IS0-8859-1), you can write your source files in that encoding and use g_convert() to convert the strings to UTF-8 at runtime. Note that this has some runtime overhead, so you may want to move the conversion out of inner loops.

Here is an example showing the three approaches using the copyright sign © which has Unicode and ISO-8859-1 codepoint 169 and is represented in UTF-8 by the two bytes 194, 169:

g_print ("direct UTF-8: ©");
g_print ("escaped UTF-8: \302\251");
text = g_convert ("runtime conversion: ©", -1, "ISO-8859-1", "UTF-8", NULL, NULL, NULL);
g_print(text);
g_free (text);

1.9.

How do I use GTK+ with C++?

There are two ways to approach this. The GTK+ header files use the subset of C that's also valid C++, so you can simply use the normal GTK+ API in a C++ program. Alternatively, you can use a "C++ binding" such as gtkmm which provides a C++-native API.

When using GTK+ directly, keep in mind that only functions can be connected to signals, not methods. So you will need to use global functions or "static" class functions for signal connections.

Another common issue when using GTK+ directly is that C++ will not implicitly convert an integer to an enumeration. This comes up when using bitfields; in C you can write the following code:

  gdk_window_set_events (gdk_window,
                         GDK_BUTTON_PRESS_MASK | GDK_BUTTON_RELEASE_MASK);

while in C++ you must write:

  gdk_window_set_events (gdk_window,
                         (GdkEventMask) GDK_BUTTON_PRESS_MASK | GDK_BUTTON_RELEASE_MASK);

There are very few functions that require this cast, however.

1.10.

How do I use GTK+ with other non-C languages?

See the list of language bindings on http://www.gtk.org.

1.11.

How do I load an image or animation from a file?

To load an image file straight into a display widget, use gtk_image_new_from_file() [1]. To load an image for another purpose, use gdk_pixbuf_new_from_file(). To load an animation, use gdk_pixbuf_animation_new_from_file(). gdk_pixbuf_animation_new_from_file() can also load non-animated images, so use it in combination with gdk_pixbuf_animation_is_static_image() to load a file of unknown type.

To load an image or animation file asynchronously (without blocking), use GdkPixbufLoader.

1.12.

How do I draw text ?

To draw a piece of text, use a Pango layout and gdk_draw_layout(), using code like the following:

 layout = gtk_widget_create_pango_layout (widget, text);
 fontdesc = pango_font_description_from_string ("Luxi Mono 12");
 pango_layout_set_font_description (layout, fontdesc);
 gdk_draw_layout (..., layout);
 pango_font_description_free (fontdesc);
 g_object_unref (layout);

Do not use the deprecated GdkFont and gdk_draw_text().

See also the "Text Handling in GTK 2" section of Porting applications to the GNOME 2.0 platform.

1.13.

How do I measure the size of a piece of text ?

To obtain the size of a piece of text, use a Pango layout and pango_layout_get_pixel_size(), using code like the following:

 layout = gtk_widget_create_pango_layout (widget, text);
 fontdesc = pango_font_description_from_string ("Luxi Mono 12");
 pango_layout_set_font_description (layout, fontdesc);
 pango_layout_get_pixel_size (layout, &width, &height);
 pango_font_description_free (fontdesc);
 g_object_unref (layout);

Do not use the deprecated function gdk_text_width().

See also the "Text Handling in GTK 2" section of Porting applications to the GNOME 2.0 platform.

1.14.

Why are types not registered if I use their GTK_TYPE_BLAH macro ?

The GTK_TYPE_BLAH macros are defined as calls to gtk_blah_get_type(), and the _get_type() functions are declared as G_GNUC_CONST which allows the compiler to optimize the call away if it appears that the value is not being used.

A common workaround for this problem is to store the result in a volatile variable, which keeps the compiler from optimizing the call away.

volatile GType dummy = GTK_TYPE_BLAH;

1.15.

How do I create a transparent toplevel window ?

To make a window transparent, it needs to use a visual which supports that. This is done by getting the RGBA colormap of the screen with gdk_screen_get_rgba_colormap() and setting it on the window. Note that gdk_screen_get_rgba_colormap() will return NULL if transparent windows are not supported on the screen; also note that this may change from screen to screen, so it needs to be repeated whenever the window is moved to a different screen.

GdkColormap *colormap;

colormap = gdk_screen_get_rgba_colormap (screen);
if (!colormap)
  colormap = gtk_screen_get_rgb_colormap (screen);

gtk_widget_set_colormap (widget, colormap);

One possibility to fill the alpha channel on the window is to use gdk_draw_rgb_32_image().

Note that the presence of an RGBA visual is no guarantee that the window will actually appear transparent on screen. On X11, this requires a compositing manager to be running. See gtk_widget_is_composited() for a way to find out if the alpha channel will be respected.

2. Which widget should I use...
2.1.

...for lists and trees?

See tree widget overview — you should use the GtkTreeView widget. (A list is just a tree with no branches, so the tree widget is used for lists as well.) Do not use the deprecated widgets GtkTree or GtkCList/GtkCTree in newly-written code, they are less flexible and result in an inferior user interface.

2.2.

...for multi-line text display or editing?

See text widget overview — you should use the GtkTextView widget. Do not use the deprecated widget GtkText in newly-written code, it has a number of problems that are best avoided.

If you only have a small amount of text, GtkLabel may also be appropriate of course. It can be made selectable with gtk_label_set_selectable(). For a single-line text entry, see GtkEntry.

2.3.

...to display an image or animation?

GtkImage can display images in just about any format GTK+ understands. You can also use GtkDrawingArea if you need to do something more complex, such as draw text or graphics over the top of the image.

2.4.

...for presenting a set of mutually-exclusive choices, where Windows would use a combo box?

With GTK+, a GtkComboBox is the recommended widget to use for this use case. This widget looks like either a combo box or the current option menu, depending on the current theme. If you need an editable text entry, use GtkComboBoxEntry.

3. GtkWidget
3.1.

How do I change the color of a widget?

See gtk_widget_modify_fg(), gtk_widget_modify_bg(), gtk_widget_modify_base(), and gtk_widget_modify_text(). See GTK+ resource files for more discussion. You can also change widget color by installing a resource file and parsing it with gtk_rc_add_default_file(). The advantage of a resource file is that users can then override the color you've chosen.

To change the background color for widgets such as GtkLabel that have no background, place them in a GtkEventBox and set the background of the event box.

3.2.

How do I change the font of a widget?

This has several possible answers, depending on what exactly you want to achieve. One option is gtk_widget_modify_font(). Note that this function can be used to change only the font size, as in the following example:

 PangoFontDesc *font_desc = pango_font_description_new ();
 pango_font_description_set_size (font_desc, 40);
 gtk_widget_modify_font (widget, font);
 pango_font_description_free (font_desc);

If you want to make the text of a label larger, you can use gtk_label_set_markup():

gtk_label_set_markup (label, "<big>big text</big>");

This is preferred for many apps because it's a relative size to the user's chosen font size. See g_markup_escape_text() if you are constructing such strings on the fly.

You can also change the font of a widget by putting

 gtk-font-name = "Sans 30"

in a resource file and parsing it with gtk_rc_add_default_file(). The advantage of a resource file is that users can then override the font you've chosen. See GTK+ resource files for more discussion.

3.3.

How do I disable/ghost/desensitize a widget?

In GTK+ a disabled widget is termed "insensitive." See gtk_widget_set_sensitive().

4. GtkTextView
4.1.

How do I get the contents of the entire text widget as a string?

See gtk_text_buffer_get_bounds() and gtk_text_buffer_get_text() or gtk_text_iter_get_text().

  GtkTextIter start, end;
  GtkTextBuffer *buffer;
  char *text;

  buffer = gtk_text_view_get_buffer (GTK_TEXT_VIEW (text_view));
  gtk_text_buffer_get_bounds (buffer, &start, &end);
  text = gtk_text_iter_get_text (&start, &end);
  /* use text */
  g_free (text);

4.2.

How do I make a text widget display its complete contents in a specific font?

If you use gtk_text_buffer_insert_with_tags() with appropriate tags to select the font, the inserted text will have the desired appearance, but text typed in by the user before or after the tagged block will appear in the default style.

To ensure that all text has the desired appearance, use gtk_widget_modify_font() to change the default font for the widget.

4.3.

How do I make a text view scroll to the end of the buffer automatically ?

A good way to keep a text buffer scrolled to the end is to place a mark at the end of the buffer, and give it right gravity. The gravity has the effect that text inserted at the mark gets inserted before, keeping the mark at the end.

To ensure that the end of the buffer remains visible, use gtk_text_view_scroll_to_mark() to scroll to the mark after inserting new text.

The gtk-demo application contains an example of this technique.

5. GtkTreeView
5.1.

How do I associate some data with a row in the tree?

Remember that the GtkTreeModel columns don't necessarily have to be displayed. So you can put non-user-visible data in your model just like any other data, and retrieve it with gtk_tree_model_get(). See the tree widget overview.

5.2.

What's the GtkTreeView equivalent of gtk_clist_find_row_from_data()?

As there is no separate data column in the GtkTreeModel, there's no built in function to find the iter from data. You can write a custom searching function to walk the tree and find the data, or use gtk_tree_model_foreach().

5.3.

How do I put an image and some text in the same column?

You can pack more than one GtkCellRenderer into a single GtkTreeViewColumn using gtk_tree_view_column_pack_start() or gtk_tree_view_column_pack_end(). So pack both a GtkCellRendererPixbuf and a GtkCellRendererText into the column.

5.4.

I can set data easily on my GtkTreeStore/GtkListStore models using gtk_list_store_set() and gtk_tree_store_set(), but can't read it back?

Both the GtkTreeStore and the GtkListStore implement the GtkTreeModel interface. Consequentially, the can use any function this interface implements. The easiest way to read a set of data back is to use gtk_tree_model_get().

5.5.

How do I change the way that numbers are formatted by GtkTreeView?

Use gtk_tree_view_insert_column_with_data_func() or gtk_tree_view_column_set_cell_data_func() and do the conversion from number to string yourself (with, say, g_strdup_printf()).

The following example demonstrates this:

enum
{
  DOUBLE_COLUMN,
  N_COLUMNS
};

GtkListStore *mycolumns;
GtkTreeView *treeview;

void
my_cell_double_to_text (GtkTreeViewColumn *tree_column,
                    GtkCellRenderer   *cell,
                        GtkTreeModel      *tree_model,
                    GtkTreeIter       *iter,
                        gpointer           data)
{
  GtkCellRendererText *cell_text = (GtkCellRendererText *)cell;
  gdouble d;
  gchar *text;

  /* Get the double value from the model. */
  gtk_tree_model_get (tree_model, iter, (gint)data, &d, -1);
  /* Now we can format the value ourselves. */
  text = g_strdup_printf ("%.2f", d);
  g_object_set (cell, "text", text, NULL);
  g_free (text);
}

void
set_up_new_columns (GtkTreeView *myview)
{
  GtkCellRendererText *renderer;
  GtkTreeViewColumn *column;
  GtkListStore *mycolumns;

  /* Create the data model and associate it with the given TreeView */
  mycolumns = gtk_list_store_new (N_COLUMNS, G_TYPE_DOUBLE);
  gtk_tree_view_set_model (myview, GTK_TREE_MODEL (mycolumns));

  /* Create a GtkCellRendererText */
  renderer = gtk_cell_renderer_text_new ();

  /* Create a new column that has a title ("Example column"),
   * uses the above created renderer that will render the double
   * value into text from the associated model's rows.
   */
  column = gtk_tree_view_column_new ();
  gtk_tree_view_column_set_title  (column, "Example column");
  renderer = gtk_cell_renderer_text_new ();
  gtk_tree_view_column_pack_start (column, renderer, TRUE);

  /* Append the new column after the GtkTreeView's previous columns. */
  gtk_tree_view_append_column (GTK_TREE_VIEW (myview), column);
  /* Since we created the column by hand, we can set it up for our
   * needs, e.g. set its minimum and maximum width, etc.
   */
  /* Set up a custom function that will be called when the column content
   * is rendered. We use the func_data pointer as an index into our
   * model. This is convenient when using multi column lists.
   */
  gtk_tree_view_column_set_cell_data_func (column, renderer,
                                       my_cell_double_to_text,
                                           (gpointer)DOUBLE_COLUMN, NULL);
}

5.6.

How do I hide the expander arrows in my tree view ?

Set the expander-column property of the tree view to a hidden column. See gtk_tree_view_set_expander_column() and gtk_tree_view_column_set_visible().

6. Using cairo with GTK+
6.1.

How do I use cairo to draw in GTK+ applications ?

USe gdk_cairo_create() to obtain a cairo context for drawing on a GDK window or pixmap. See Cairo Interaction for some more useful functions.

6.2.

I have created a cairo context with gdk_cairo_create(), but when I later use it, my drawing does not show up. Why is that ?

All drawing in GTK+ is normally done in an expose handler, and GTK+ creates a temporary pixmap for double-buffering the drawing. If you create a cairo context outside the expose handler, it is backed by the GDK window itself, not the double-buffering pixmap. Consequently, any drawing you do with that cairo context gets overwritten at the end of the expose handler, when the double-buffering pixmap is copied back.

Possible solutions to this problem are:

  • Turn off double-buffering, with gtk_widget_set_double_buffered(). This is not ideal, since it can cause some flickering.

  • Create the cairo context inside the expose handler. If you do this, gdk_create_cairo() arranges for it to be backed by the double-buffering pixmap. This is the preferred solution, and is used throughout GTK+ itself.

6.3.

Can I improve the performance of my application by using the Glitz backend of cairo ?

No. The GDK X11 backend uses the cairo X backend (and the other GDK backends use their respective native cairo backends). The GTK+ developers believe that the best way to improving the GDK drawing performance is to optimize the cairo X backend and the relevant code paths in the X server that is uses (mostly the Render extension).

6.4.

Can I use cairo to draw on a GdkPixbuf ?

No, at least not yet. The cairo image surface does not support the pixel format used by GdkPixbuf.

[1] If the file load fails, gtk_image_new_from_file() will display no image graphic — to detect a failed load yourself, use gdk_pixbuf_new_from_file() directly, then gtk_image_new_from_pixbuf().


Resource Files

Resource Files — Routines for handling resource files

Synopsis

#include <gtk/gtk.h>

                    GtkRcStyle;
enum                GtkRcFlags;
enum                GtkRcTokenType;
GScanner*           gtk_rc_scanner_new                  (void);
GtkStyle*           gtk_rc_get_style                    (GtkWidget *widget);
GtkStyle*           gtk_rc_get_style_by_paths           (GtkSettings *settings,
                                                         const char *widget_path,
                                                         const char *class_path,
                                                         GType type);
void                gtk_rc_add_widget_name_style        (GtkRcStyle *rc_style,
                                                         const gchar *pattern);
void                gtk_rc_add_widget_class_style       (GtkRcStyle *rc_style,
                                                         const gchar *pattern);
void                gtk_rc_add_class_style              (GtkRcStyle *rc_style,
                                                         const gchar *pattern);
void                gtk_rc_parse                        (const gchar *filename);
void                gtk_rc_parse_string                 (const gchar *rc_string);
gboolean            gtk_rc_reparse_all                  (void);
gboolean            gtk_rc_reparse_all_for_settings     (GtkSettings *settings,
                                                         gboolean force_load);
void                gtk_rc_reset_styles                 (GtkSettings *settings);
void                gtk_rc_add_default_file             (const gchar *filename);
gchar**             gtk_rc_get_default_files            (void);
void                gtk_rc_set_default_files            (gchar **filenames);
guint               gtk_rc_parse_color                  (GScanner *scanner,
                                                         GdkColor *color);
guint               gtk_rc_parse_state                  (GScanner *scanner,
                                                         GtkStateType *state);
guint               gtk_rc_parse_priority               (GScanner *scanner,
                                                         GtkPathPriorityType *priority);
gchar*              gtk_rc_find_module_in_path          (const gchar *module_file);
gchar*              gtk_rc_find_pixmap_in_path          (GtkSettings *settings,
                                                         GScanner *scanner,
                                                         const gchar *pixmap_file);
gchar*              gtk_rc_get_module_dir               (void);
gchar*              gtk_rc_get_im_module_path           (void);
gchar*              gtk_rc_get_im_module_file           (void);
gchar*              gtk_rc_get_theme_dir                (void);
GtkRcStyle*         gtk_rc_style_new                    (void);
GtkRcStyle*         gtk_rc_style_copy                   (GtkRcStyle *orig);
void                gtk_rc_style_ref                    (GtkRcStyle *rc_style);
void                gtk_rc_style_unref                  (GtkRcStyle *rc_style);

Object Hierarchy

  GObject
   +----GtkRcStyle

Description

GTK+ provides resource file mechanism for configuring various aspects of the operation of a GTK+ program at runtime.

Default files

An application can cause GTK+ to parse a specific RC file by calling gtk_rc_parse(). In addition to this, certain files will be read at the end of gtk_init(). Unless modified, the files looked for will be <SYSCONFDIR>/gtk-2.0/gtkrc and .gtkrc-2.0 in the users home directory. (<SYSCONFDIR> defaults to /usr/local/etc. It can be changed with the --prefix or --sysconfdir options when configuring GTK+.) Note that although the filenames contain the version number 2.0, all 2.x versions of GTK+ look for these files.

The set of these default files can be retrieved with gtk_rc_get_default_files() and modified with gtk_rc_add_default_file() and gtk_rc_set_default_files(). Additionally, the GTK2_RC_FILES environment variable can be set to a G_SEARCHPATH_SEPARATOR_S-separated list of files in order to overwrite the set of default files at runtime.

For each RC file, in addition to the file itself, GTK+ will look for a locale-specific file that will be parsed after the main file. For instance, if LANG is set to ja_JP.ujis, when loading the default file ~/.gtkrc then GTK+ looks for ~/.gtkrc.ja_JP and ~/.gtkrc.ja, and parses the first of those that exists.

Pathnames and patterns

A resource file defines a number of styles and key bindings and attaches them to particular widgets. The attachment is done by the widget, widget_class, and class declarations. As an example of such a statement:

widget "mywindow.*.GtkEntry" style "my-entry-class"

attaches the style "my-entry-class" to all widgets whose widget path matches the pattern "mywindow.*.GtkEntry". That is, all GtkEntry widgets which are part of a GtkWindow named "mywindow".

The patterns here are given in the standard shell glob syntax. The "?" wildcard matches any character, while "*" matches zero or more of any character. The three types of matching are against the widget path, the class path and the class hierarchy. Both the widget path and the class path consist of a "." separated list of all the parents of the widget and the widget itself from outermost to innermost. The difference is that in the widget path, the name assigned by gtk_widget_set_name() is used if present, otherwise the class name of the widget, while for the class path, the class name is always used.

Since GTK+ 2.10,widget_class paths can also contain <classname> substrings, which are matching the class with the given name and any derived classes. For instance,

widget_class "*<GtkMenuItem>.GtkLabel" style "my-style"

will match GtkLabel widgets which are contained in any kind of menu item.

So, if you have a GtkEntry named "myentry", inside of a horizontal box in a window named "mywindow", then the widget path is: "mywindow.GtkHBox.myentry" while the class path is: "GtkWindow.GtkHBox.GtkEntry".

Matching against class is a little different. The pattern match is done against all class names in the widgets class hierarchy (not the layout hierarchy) in sequence, so the pattern:

class "GtkButton" style "my-style"

will match not just GtkButton widgets, but also GtkToggleButton and GtkCheckButton widgets, since those classes derive from GtkButton.

Additionally, a priority can be specified for each pattern, and styles override other styles first by priority, then by pattern type and then by order of specification (later overrides earlier). The priorities that can be specified are (highest to lowest):

highest
rc
theme
application
gtk
lowest

rc is the default for styles read from an RC file, theme is the default for styles read from theme RC files, application should be used for styles an application sets up, and gtk is used for styles that GTK+ creates internally.

Optimizing RC Style Matches

Everytime a widget is created and added to the layout hierarchy of a GtkWindow ("anchored" to be exact), a list of matching RC styles out of all RC styles read in so far is composed. For this, every RC style is matched against the widgets class path, the widgets name path and widgets inheritance hierarchy. As a consequence, significant slowdown can be caused by utilization of many RC styles and by using RC style patterns that are slow or complicated to match against a given widget. The following ordered list provides a number of advices (prioritized by effectiveness) to reduce the performance overhead associated with RC style matches:

  1. Move RC styles for specific applications into RC files dedicated to those applications and parse application specific RC files only from applications that are affected by them. This reduces the overall amount of RC styles that have to be considered for a match across a group of applications.

  2. Merge multiple styles which use the same matching rule, for instance:

         style "Foo" { foo_content }
     class "X" style "Foo"
     style "Bar" { bar_content }
     class "X" style "Bar"

    is faster to match as:

         style "FooBar" { foo_content bar_content }
     class "X" style "FooBar"

  3. Use of wildcards should be avoided, this can reduce the individual RC style match to a single integer comparison in most cases.

  4. To avoid complex recursive matching, specification of full class names (for class matches) or full path names (for widget and widget_class matches) is to be preferred over shortened names containing "*" or "?".

  5. If at all necessary, wildcards should only be used at the tail or head of a pattern. This reduces the match complexity to a string comparison per RC style.

  6. When using wildcards, use of "?" should be preferred over "*". This can reduce the matching complexity from O(n^2) to O(n). For example "Gtk*Box" can be turned into "Gtk?Box" and will still match GtkHBox and GtkVBox.

  7. The use of "*" wildcards should be restricted as much as possible, because matching "A*B*C*RestString" can result in matching complexities of O(n^2) worst case.

Toplevel declarations

An RC file is a text file which is composed of a sequence of declarations. '#' characters delimit comments and the portion of a line after a '#' is ignored when parsing an RC file.

The possible toplevel declarations are:

binding name { ... } | Declares a binding set.
class pattern [ style | binding ][ : priority ] name | Specifies a style or binding set for a particular branch of the inheritance hierarchy.
include filename | Parses another file at this point. If filename is not an absolute filename, it is searched in the directories of the currently open RC files. GTK+ also tries to load a locale-specific variant of the included file.
module_path path | Sets a path (a list of directories separated by colons) that will be searched for theme engines referenced in RC files.
pixmap_path path | Sets a path (a list of directories separated by colons) that will be searched for pixmaps referenced in RC files.
im_module_file pathname | Sets the pathname for the IM modules file. Setting this from RC files is deprecated; you should use the environment variable GTK_IM_MODULE_FILE instead.
style name [ = parent ] { ... } | Declares a style.
widget pattern [ style | binding ][ : priority ] name | Specifies a style or binding set for a particular group of widgets by matching on the widget pathname.
widget_class pattern [ style | binding ][ : priority ] name | Specifies a style or binding set for a particular group of widgets by matching on the class pathname.
setting = value | Specifies a value for a setting. Note that settings in RC files are overwritten by system-wide settings (which are managed by an XSettings manager on X11).

Styles

A RC style is specified by a style declaration in a RC file, and then bound to widgets with a widget, widget_class, or class declaration. All styles applying to a particular widget are composited together with widget declarations overriding widget_class declarations which, in turn, override class declarations. Within each type of declaration, later declarations override earlier ones.

Within a style declaration, the possible elements are:

bg[state] = color | Sets the color used for the background of most widgets.
fg[state] = color | Sets the color used for the foreground of most widgets.
base[state] = color | Sets the color used for the background of widgets displaying editable text. This color is used for the background of, among others, GtkText, GtkEntry, GtkList, and GtkCList.
text[state] = color | Sets the color used for foreground of widgets using base for the background color.
xthickness = number | Sets the xthickness, which is used for various horizontal padding values in GTK+.
ythickness = number | Sets the ythickness, which is used for various vertical padding values in GTK+.
bg_pixmap[state] = pixmap | Sets a background pixmap to be used in place of the bg color (or for GtkText, in place of the base color. The special value "<parent>" may be used to indicate that the widget should use the same background pixmap as its parent. The special value "<none>" may be used to indicate no background pixmap.
font = font | Starting with GTK+ 2.0, the "font" and "fontset" declarations are ignored; use "font_name" declarations instead.
fontset = font | Starting with GTK+ 2.0, the "font" and "fontset" declarations are ignored; use "font_name" declarations instead.
font_name = font | Sets the font for a widget. font must be a Pango font name, e.g. "Sans Italic 10". For details about Pango font names, see pango_font_description_from_string().
stock["stock-id"] = { icon source specifications } | Defines the icon for a stock item.
color["color-name"] = color specification | Since 2.10, this element can be used to defines symbolic colors. See below for the syntax of color specifications.
engine "engine" { engine-specific settings } | Defines the engine to be used when drawing with this style.
class::property = value | Sets a style property for a widget class.

The colors and background pixmaps are specified as a function of the state of the widget. The states are:

NORMAL | A color used for a widget in its normal state.
ACTIVE | A variant of the NORMAL color used when the widget is in the GTK_STATE_ACTIVE state, and also for the trough of a ScrollBar, tabs of a NoteBook other than the current tab and similar areas. Frequently, this should be a darker variant of the NORMAL color.
PRELIGHT | A color used for widgets in the GTK_STATE_PRELIGHT state. This state is the used for Buttons and MenuItems that have the mouse cursor over them, and for their children.
SELECTED | A color used to highlight data selected by the user. for instance, the selected items in a list widget, and the selection in an editable widget.
INSENSITIVE | A color used for the background of widgets that have been set insensitive with gtk_widget_set_sensitive().

Colors can be specified as a string containing a color name (GTK+ knows all names from the X color database /usr/lib/X11/rgb.txt), in one of the hexadecimal forms #rrrrggggbbbb, #rrrgggbbb, #rrggbb, or #rgb, where r, g and b are hex digits, or they can be specified as a triplet { r, g, b}, where r, g and b are either integers in the range 0-65535 or floats in the range 0.0-1.0.

Since 2.10, colors can also be specified by refering to a symbolic color, as follows: @color-name, or by using expressions to combine colors. The following expressions are currently supported:

mix (factor, color1, color2) | Computes a new color by mixing color1 and color2. The factor determines how close the new color is to color1. A factor of 1.0 gives pure color1, a factor of 0.0 gives pure color2.
shade (factor, color) | Computes a lighter or darker variant of color. A factor of 1.0 leaves the color unchanged, smaller factors yield darker colors, larger factors yield lighter colors.
lighter (color) | This is an abbreviation for shade (1.3, color).
darker (color) | This is an abbreviation for shade (0.7, color).

Here are some examples of color expressions:

 mix (0.5, "red", "blue")
 shade (1.5, mix (0.3, "#0abbc0", { 0.3, 0.5, 0.9 }))
 lighter (@foreground)

In a stock definition, icon sources are specified as a 4-tuple of image filename or icon name, text direction, widget state, and size, in that order. Each icon source specifies an image filename or icon name to use with a given direction, state, and size. Filenames are specified as a string such as "itemltr.png", while icon names (looked up in the current icon theme), are specified with a leading @, such as @"item-ltr". The * character can be used as a wildcard, and if direction/state/size are omitted they default to *. So for example, the following specifies different icons to use for left-to-right and right-to-left languages:

stock["my-stock-item"] =
{
  { "itemltr.png", LTR, *, * },
  { "itemrtl.png", RTL, *, * }
}

This could be abbreviated as follows:

stock["my-stock-item"] =
{
  { "itemltr.png", LTR },
  { "itemrtl.png", RTL }
}

You can specify custom icons for specific sizes, as follows:

stock["my-stock-item"] =
{
  { "itemmenusize.png", *, *, "gtk-menu" },
  { "itemtoolbarsize.png", *, *, "gtk-large-toolbar" }
  { "itemgeneric.png" } /* implicit *, *, * as a fallback */
}

The sizes that come with GTK+ itself are "gtk-menu", "gtk-small-toolbar", "gtk-large-toolbar", "gtk-button", "gtk-dialog". Applications can define other sizes.

It's also possible to use custom icons for a given state, for example:

stock["my-stock-item"] =
{
  { "itemprelight.png", *, PRELIGHT },
  { "iteminsensitive.png", *, INSENSITIVE },
  { "itemgeneric.png" } /* implicit *, *, * as a fallback */
}

When selecting an icon source to use, GTK+ will consider text direction most important, state second, and size third. It will select the best match based on those criteria. If an attribute matches exactly (e.g. you specified PRELIGHT or specified the size), GTK+ won't modify the image; if the attribute matches with a wildcard, GTK+ will scale or modify the image to match the state and size the user requested.

Key bindings

Key bindings allow the user to specify actions to be taken on particular key presses. The form of a binding set declaration is:

binding name {
  bind key {
    signalname (param, ...)
    ...
  }
  ...
}

key is a string consisting of a series of modifiers followed by the name of a key. The modifiers can be:

<alt>
<ctl>
<control>
<meta>
<hyper>
<super>
<mod1>
<mod2>
<mod3>
<mod4>
<mod5>
<release>
<shft>
<shift>

<shft> is an alias for <shift>, <ctl> is an alias for <control>, and <alt> is an alias for <mod1>.

The action that is bound to the key is a sequence of signal names (strings) followed by parameters for each signal. The signals must be action signals. (See g_signal_new()). Each parameter can be a float, integer, string, or unquoted string representing an enumeration value. The types of the parameters specified must match the types of the parameters of the signal.

Binding sets are connected to widgets in the same manner as styles, with one difference: Binding sets override other binding sets first by pattern type, then by priority and then by order of specification. The priorities that can be specified and their default values are the same as for styles.

Details

GtkRcStyle

typedef struct {
  gchar *name;
  gchar *bg_pixmap_name[5];
  PangoFontDescription *font_desc;

  GtkRcFlags color_flags[5];
  GdkColor   fg[5];
  GdkColor   bg[5];
  GdkColor   text[5];
  GdkColor   base[5];

  gint xthickness;
  gint ythickness;
} GtkRcStyle;

The GtkRcStyle structure is used to represent a set of information about the appearance of a widget. This can later be composited together with other GtkRcStyle structures to form a GtkStyle.

enum GtkRcFlags

typedef enum
{
  GTK_RC_FG		= 1 << 0,
  GTK_RC_BG		= 1 << 1,
  GTK_RC_TEXT		= 1 << 2,
  GTK_RC_BASE		= 1 << 3
} GtkRcFlags;

The GtkRcFlags enumeration is used as a bitmask to specify which fields of a GtkRcStyle have been set for each state.

GTK_RC_FG | If present, the foreground color has been set for this state.
GTK_RC_BG | If present, the background color has been set for this state.
GTK_RC_TEXT | If present, the text color has been set for this state.
GTK_RC_BASE | If present, the base color has been set for this state.

enum GtkRcTokenType

typedef enum {
  GTK_RC_TOKEN_INVALID = G_TOKEN_LAST,
  GTK_RC_TOKEN_INCLUDE,
  GTK_RC_TOKEN_NORMAL,
  GTK_RC_TOKEN_ACTIVE,
  GTK_RC_TOKEN_PRELIGHT,
  GTK_RC_TOKEN_SELECTED,
  GTK_RC_TOKEN_INSENSITIVE,
  GTK_RC_TOKEN_FG,
  GTK_RC_TOKEN_BG,
  GTK_RC_TOKEN_TEXT,
  GTK_RC_TOKEN_BASE,
  GTK_RC_TOKEN_XTHICKNESS,
  GTK_RC_TOKEN_YTHICKNESS,
  GTK_RC_TOKEN_FONT,
  GTK_RC_TOKEN_FONTSET,
  GTK_RC_TOKEN_FONT_NAME,
  GTK_RC_TOKEN_BG_PIXMAP,
  GTK_RC_TOKEN_PIXMAP_PATH,
  GTK_RC_TOKEN_STYLE,
  GTK_RC_TOKEN_BINDING,
  GTK_RC_TOKEN_BIND,
  GTK_RC_TOKEN_WIDGET,
  GTK_RC_TOKEN_WIDGET_CLASS,
  GTK_RC_TOKEN_CLASS,
  GTK_RC_TOKEN_LOWEST,
  GTK_RC_TOKEN_GTK,
  GTK_RC_TOKEN_APPLICATION,
  GTK_RC_TOKEN_THEME,
  GTK_RC_TOKEN_RC,
  GTK_RC_TOKEN_HIGHEST,
  GTK_RC_TOKEN_ENGINE,
  GTK_RC_TOKEN_MODULE_PATH,
  GTK_RC_TOKEN_IM_MODULE_PATH,
  GTK_RC_TOKEN_IM_MODULE_FILE,
  GTK_RC_TOKEN_STOCK,
  GTK_RC_TOKEN_LTR,
  GTK_RC_TOKEN_RTL,
  GTK_RC_TOKEN_COLOR,
  GTK_RC_TOKEN_LAST
} GtkRcTokenType;

The GtkRcTokenType enumeration represents the tokens in the RC file. It is exposed so that theme engines can reuse these tokens when parsing the theme-engine specific portions of a RC file.

gtk_rc_scanner_new ()

GScanner*           gtk_rc_scanner_new                  (void);

Returns :

gtk_rc_get_style ()

GtkStyle*           gtk_rc_get_style                    (GtkWidget *widget);

Finds all matching RC styles for a given widget, composites them together, and then creates a GtkStyle representing the composite appearance. (GTK+ actually keeps a cache of previously created styles, so a new style may not be created.)

widget : | a GtkWidget
Returns : | the resulting style. No refcount is added to the returned style, so if you want to save this style around, you should add a reference yourself.

gtk_rc_get_style_by_paths ()

GtkStyle*           gtk_rc_get_style_by_paths           (GtkSettings *settings,
                                                         const char *widget_path,
                                                         const char *class_path,
                                                         GType type);

Creates up a GtkStyle from styles defined in a RC file by providing the raw components used in matching. This function may be useful when creating pseudo-widgets that should be themed like widgets but don't actually have corresponding GTK+ widgets. An example of this would be items inside a GNOME canvas widget.

The action of gtk_rc_get_style() is similar to:

 gtk_widget_path (widget, NULL, &path, NULL);
 gtk_widget_class_path (widget, NULL, &class_path, NULL);
 gtk_rc_get_style_by_paths (gtk_widget_get_settings (widget), path, class_path,
                            G_OBJECT_TYPE (widget));

settings : | a GtkSettings object
widget_path : | the widget path to use when looking up the style, or NULL if no matching against the widget path should be done
class_path : | the class path to use when looking up the style, or NULL if no matching against the class path should be done.
type : | a type that will be used along with parent types of this type when matching against class styles, or G_TYPE_NONE
Returns : | A style created by matching with the supplied paths, or NULL if nothing matching was specified and the default style should be used. The returned value is owned by GTK+ as part of an internal cache, so you must call g_object_ref() on the returned value if you want to keep a reference to it.

gtk_rc_add_widget_name_style ()

void                gtk_rc_add_widget_name_style        (GtkRcStyle *rc_style,
                                                         const gchar *pattern);

Warning

gtk_rc_add_widget_name_style is deprecated and should not be used in newly-written code.

Adds a GtkRcStyle that will be looked up by a match against the widget's pathname. This is equivalent to a: widget PATTERN style STYLE statement in a RC file.

rc_style : | the GtkRcStyle to use for widgets matching pattern
pattern : | the pattern

gtk_rc_add_widget_class_style ()

void                gtk_rc_add_widget_class_style       (GtkRcStyle *rc_style,
                                                         const gchar *pattern);

Warning

gtk_rc_add_widget_class_style is deprecated and should not be used in newly-written code.

Adds a GtkRcStyle that will be looked up by a match against the widget's class pathname. This is equivalent to a: widget_class PATTERN style STYLE statement in a RC file.

rc_style : | the GtkRcStyle to use for widgets matching pattern
pattern : | the pattern

gtk_rc_add_class_style ()

void                gtk_rc_add_class_style              (GtkRcStyle *rc_style,
                                                         const gchar *pattern);

Warning

gtk_rc_add_class_style is deprecated and should not be used in newly-written code.

Adds a GtkRcStyle that will be looked up by a matching against the class hierarchy of the widget. This is equivalent to a: class PATTERN style STYLE statement in a RC file.

rc_style : | the GtkRcStyle to use for widgets deriving from pattern
pattern : | the pattern

gtk_rc_parse ()

void                gtk_rc_parse                        (const gchar *filename);

Parses a given resource file.

filename : the filename of a file to parse. If filename is not absolute, it is searched in the current directory.

gtk_rc_parse_string ()

void                gtk_rc_parse_string                 (const gchar *rc_string);

Parses resource information directly from a string.

rc_string : a string to parse.

gtk_rc_reparse_all ()

gboolean            gtk_rc_reparse_all                  (void);

If the modification time on any previously read file for the default GtkSettings has changed, discard all style information and then reread all previously read RC files.

Returns : TRUE if the files were reread.

gtk_rc_reparse_all_for_settings ()

gboolean            gtk_rc_reparse_all_for_settings     (GtkSettings *settings,
                                                         gboolean force_load);

If the modification time on any previously read file for the given GtkSettings has changed, discard all style information and then reread all previously read RC files.

settings : | a GtkSettings
force_load : | load whether or not anything changed
Returns : | TRUE if the files were reread.

gtk_rc_reset_styles ()

void                gtk_rc_reset_styles                 (GtkSettings *settings);

This function recomputes the styles for all widgets that use a particular GtkSettings object. (There is one GtkSettings object per GdkScreen, see gtk_settings_get_for_screen()); It is useful when some global parameter has changed that affects the appearance of all widgets, because when a widget gets a new style, it will both redraw and recompute any cached information about its appearance. As an example, it is used when the default font size set by the operating system changes. Note that this function doesn't affect widgets that have a style set explicitely on them with gtk_widget_set_style().

settings : a GtkSettings

Since 2.4

gtk_rc_add_default_file ()

void                gtk_rc_add_default_file             (const gchar *filename);

Adds a file to the list of files to be parsed at the end of gtk_init().

filename : the pathname to the file. If filename is not absolute, it is searched in the current directory.

gtk_rc_get_default_files ()

gchar**             gtk_rc_get_default_files            (void);

Retrieves the current list of RC files that will be parsed at the end of gtk_init().

Returns : A NULL-terminated array of filenames. This memory is owned by GTK+ and must not be freed by the application. If you want to store this information, you should make a copy.

gtk_rc_set_default_files ()

void                gtk_rc_set_default_files            (gchar **filenames);

Sets the list of files that GTK+ will read at the end of gtk_init().

filenames : A NULL-terminated list of filenames.

gtk_rc_parse_color ()

guint               gtk_rc_parse_color                  (GScanner *scanner,
                                                         GdkColor *color);

Parses a color in the format expected in a RC file.

scanner : | a GtkScanner
color : | a pointer to a GtkColor structure in which to store the result
Returns : | G_TOKEN_NONE if parsing succeeded, otherwise the token that was expected but not found.

gtk_rc_parse_state ()

guint               gtk_rc_parse_state                  (GScanner *scanner,
                                                         GtkStateType *state);

Parses a GtkStateType variable from the format expected in a RC file.

scanner : | a GtkScanner (must be initialized for parsing an RC file)
state : | A pointer to a GtkStateType variable in which to store the result.
Returns : | G_TOKEN_NONE if parsing succeeded, otherwise the token that was expected but not found.

gtk_rc_parse_priority ()

guint               gtk_rc_parse_priority               (GScanner *scanner,
                                                         GtkPathPriorityType *priority);

Parses a GtkPathPriorityType variable from the format expected in a RC file.

scanner : | a GtkScanner (must be initialized for parsing an RC file)
priority : | A pointer to GtkPathPriorityType variable in which to store the result.
Returns : | G_TOKEN_NONE if parsing succeeded, otherwise the token that was expected but not found.

gtk_rc_find_module_in_path ()

gchar*              gtk_rc_find_module_in_path          (const gchar *module_file);

Searches for a theme engine in the GTK+ search path. This function is not useful for applications and should not be used.

module_file : | name of a theme engine
Returns : | The filename, if found (must be freed with g_free()), otherwise NULL.

gtk_rc_find_pixmap_in_path ()

gchar*              gtk_rc_find_pixmap_in_path          (GtkSettings *settings,
                                                         GScanner *scanner,
                                                         const gchar *pixmap_file);

Looks up a file in pixmap path for the specified GtkSettings. If the file is not found, it outputs a warning message using g_warning() and returns NULL.

settings : | a GtkSettings
scanner : | Scanner used to get line number information for the warning message, or NULL
pixmap_file : | name of the pixmap file to locate.
Returns : | the filename.

gtk_rc_get_module_dir ()

gchar*              gtk_rc_get_module_dir               (void);

Returns a directory in which GTK+ looks for theme engines. For full information about the search for theme engines, see the docs for GTK_PATH in Running GTK+ Applications(3).

Returns : the directory. (Must be freed with g_free())

gtk_rc_get_im_module_path ()

gchar*              gtk_rc_get_im_module_path           (void);

Obtains the path in which to look for IM modules. See the documentation of the GTK_PATH environment variable for more details about looking up modules. This function is useful solely for utilities supplied with GTK+ and should not be used by applications under normal circumstances.

Returns : a newly-allocated string containing the path in which to look for IM modules.

gtk_rc_get_im_module_file ()

gchar*              gtk_rc_get_im_module_file           (void);

Obtains the path to the IM modules file. See the documentation of the GTK_IM_MODULE_FILE environment variable for more details.

Returns : a newly-allocated string containing the name of the file listing the IM modules available for loading

gtk_rc_get_theme_dir ()

gchar*              gtk_rc_get_theme_dir                (void);

Returns the standard directory in which themes should be installed. (GTK+ does not actually use this directory itself.)

Returns : The directory (must be freed with g_free()).

gtk_rc_style_new ()

GtkRcStyle*         gtk_rc_style_new                    (void);

Creates a new GtkRcStyle with no fields set and a reference count of 1.

Returns : the newly-created GtkRcStyle

gtk_rc_style_copy ()

GtkRcStyle*         gtk_rc_style_copy                   (GtkRcStyle *orig);

Makes a copy of the specified GtkRcStyle. This function will correctly copy an RC style that is a member of a class derived from GtkRcStyle.

orig : | the style to copy
Returns : | the resulting GtkRcStyle

gtk_rc_style_ref ()

void                gtk_rc_style_ref                    (GtkRcStyle *rc_style);

Increments the reference count of a GtkRcStyle.

rc_style : a GtkRcStyle

gtk_rc_style_unref ()

void                gtk_rc_style_unref                  (GtkRcStyle *rc_style);

Decrements the reference count of a GtkRcStyle and frees if the result is 0.

rc_style : a GtkRcStyle


Mailing lists and bug reports

Mailing lists and bug reports — Getting help with GTK+

Filing a bug report or feature request

If you encounter a bug, misfeature, or missing feature in GTK+, please file a bug report on http://bugzilla.gnome.org. We'd also appreciate reports of incomplete or misleading information in the GTK+ documentation; file those against the "docs" component of the "gtk+" product in Bugzilla.

Don't hesitate to file a bug report, even if you think we may know about it already, or aren't sure of the details. Just give us as much information as you have, and if it's already fixed or has already been discussed, we'll add a note to that effect in the report.

The bug tracker should definitely be used for feature requests, it's not only for bugs. We track all GTK+ development in Bugzilla, so it's the way to be sure the GTK+ developers won't forget about an issue.

Submitting Patches

If you develop a bugfix or enhancement for GTK+, please file that in Bugzilla as well. Bugzilla allows you to attach files; please attach a patch generated by the diff utility, using the -u option to make the patch more readable. All patches must be offered under the terms of the GNU LGPL license, so be sure you are authorized to give us the patch under those terms.

If you want to discuss your patch before or after developing it, mail gtk-devel-list@gnome.org. But be sure to file the Bugzilla report as well; if the patch is only on the list and not in Bugzilla, it's likely to slip through the cracks.

Mailing lists

There are several mailing lists dedicated to GTK+ and related libraries. Discussion of GLib, Pango, and ATK in addition to GTK+ proper is welcome on these lists. You can subscribe or view the archives of these lists on http://mail.gnome.org. If you aren't subscribed to the list, any message you post to the list will be held for manual moderation, which might take some days to happen.

gtk-list@gnome.org | gtk-list covers general GTK+ topics; questions about using GTK+ in programs, GTK+ from a user standpoint, announcements of GTK+-related projects such as themes or GTK+ modules would all be on-topic. The bulk of the traffic consists of GTK+ programming questions.
gtk-app-devel-list@gnome.org | gtk-app-devel-list covers writing applications in GTK+. It's narrower in scope than gtk-list, but the two lists overlap quite a bit. gtk-app-devel-list is a good place to ask questions about GTK+ programming.
gtk-devel-list@gnome.org | gtk-devel-list is for discussion of work on GTK+ itself, it is not for asking questions about how to use GTK+ in applications. gtk-devel-list is appropriate for discussion of patches, bugs, proposed features, and so on.
gtk-i18n-list@gnome.org | gtk-i18n-list is for discussion of internationalization in GTK+; Pango is the main focus of the list. Questions about the details of using Pango, and discussion of proposed Pango patches or features, are all on topic.
gtk-doc-list@gnome.org | gtk-doc-list is for discussion of the gtk-doc documentation system (used to document GTK+), and for work on the GTK+ documentation.


Running GTK+ Applications

Running GTK+ Applications — How to run and debug your GTK+ application

Running and debugging GTK+ Applications

Common commandline options

All GTK+ applications support a number of standard commandline options. These are removed from argv by gtk_init(). Modules may parse and remove further options. The X11 and Windows GDK backends parse some additional commandline options.

--gtk-module module. A list of modules to load in addition to those specified in the GTK_MODULES environment variable and the gtk-modules setting.

--g-fatal-warnings. Make GTK+ abort on all warnings. This is useful to stop on the first warning in a debugger, if your application is printing multiple warnings. It's almost always best to start debugging with the first warning that occurs.

--gtk-debug options. A list of debug options to turn on in addition to those specified in the GTK_DEBUG environment variable. This option is only available if GTK+ has been configured with --enable-debug=yes.

--gtk-no-debug options. A list of debug options to turn off. This option is only available if GTK+ has been configured with --enable-debug=yes.

The following options are really used by GDK, not by GTK+, but we list them here for completeness nevertheless.

--class class. Sets the program class; see gdk_set_program_class().

--name name. Sets the program name.

--gdk-debug options. A list of debug options to turn on in addition to those specified in the GDK_DEBUG environment variable. This option is only available if GTK+ has been configured with --enable-debug=yes.

--gdk-no-debug options. A list of debug options to turn off. This option is only available if GTK+ has been configured with --enable-debug=yes.

Environment variables

GTK+ inspects a number of environment variables in addition to standard variables like LANG, PATH, HOME or DISPLAY; mostly to determine paths to look for certain files. The X11, Windows and Framebuffer GDK backends use some additional environment variables.

GTK_DEBUG. If GTK+ has been configured with --enable-debug=yes, this variable can be set to a list of debug options, which cause GTK+ to print out different types of debugging information.

misc | Miscellaneous information
plugsocket | Cross-process embedding
text | Text widget internals
tree | Tree widget internals
updates | Visual feedback about window updates
keybindings | Keybindings
multihead | Working on multiple displays
modules | Loading of modules
geometry | Size allocation
icontheme | Icon themes
printing | Printing support

The special value all can be used to turn on all debug options.

GTK_MODULES. A list of modules to load.

GTK_PATH. Specifies a list of directories to search when GTK+ is looking for dynamically loaded objects such as the modules specified by GTK_MODULES, theme engines, and input method modules. If the path to the dynamically loaded object is given as an absolute path name, then GTK+ loads it directly. Otherwise, GTK+ goes in turn through the directories in GTK_PATH, followed by the directory .gtk-2.0 in the user's home directory, followed by the system default directory, which is libdir/gtk-2.0/modules. (If GTK_EXE_PREFIX is defined, libdir is $GTK_EXE_PREFIX/lib. Otherwise it is the libdir specified when GTK+ was configured, usually /usr/lib, or /usr/local/lib.) For each directory in this list, GTK+ actually looks in a subdirectory directory/version/host/type Where version is derived from the version of GTK+ (use pkg-config --variable=gtk_binary_version gtk+-2.0 to determine this from a script), host is the architecture on which GTK+ was built. (use pkg-config --variable=gtk_host gtk+-2.0 to determine this from a script), and type is a directory specific to the type of modules; currently it can be modules, engines or immodules corresponding to the three types of modules above. Either version, host, or both may be omitted. GTK+ looks first in the most specific directory, then in directories with fewer components. The components of GTK_PATH are separated by the ':' character on Linux and Unix, and the ';' character on Windows.

GTK_IM_MODULE. Specifies an IM module to use in preference to the one determined from the locale.

GTK_IM_MODULE_FILE. Specifies the file listing the IM modules to load. This environment variable overrides the im_module_file specified in the RC files, which in turn overrides the default value sysconfdir/gtk-2.0/gtk.immodules (sysconfdir is the sysconfdir specified when GTK+ was configured, usually /usr/local/etc.)

GTK2_RC_FILES. Specifies a list of RC files to parse instead of the default ones; see Resource Files.

GTK_EXE_PREFIX. If set, GTK+ uses $GTK_EXE_PREFIX/lib instead of the libdir configured when GTK+ was compiled.

GTK_DATA_PREFIX. If set, makes GTK+ use $GTK_DATA_PREFIX instead of the prefix configured when GTK+ was compiled.

The following environment variables are used by GdkPixbuf, GDK or Pango, not by GTK+ itself, but we list them here for completeness nevertheless.

GDK_PIXBUF_MODULE_FILE. Specifies the file listing the GdkPixbuf loader modules to load. This environment variable overrides the default value sysconfdir/gtk-2.0/gdk-pixbuf.loaders (sysconfdir is the sysconfdir specified when GTK+ was configured, usually /usr/local/etc.)

GDK_DEBUG. If GTK+ has been configured with --enable-debug=yes, this variable can be set to a list of debug options, which cause GDK to print out different types of debugging information.

misc | Miscellaneous information
events | Show all events received by GDK
dnd | Information about drag-and-drop
xim | Information about XIM support

The special value all can be used to turn on all debug options.

XDG_DATA_HOME, XDG_DATA_DIRS. GTK+ uses these environment variables to locate icon themes and MIME information. For more information, see Icon Theme Specification, the Shared MIME-info Database and the Base Directory Specification.


Selections

Selections — Functions for handling inter-process communication via selections

Synopsis

#include <gtk/gtk.h>

                    GtkTargetEntry;
                    GtkTargetList;
                    GtkTargetPair;
GtkTargetList*      gtk_target_list_new                 (const GtkTargetEntry *targets,
                                                         guint ntargets);
GtkTargetList*      gtk_target_list_ref                 (GtkTargetList *list);
void                gtk_target_list_unref               (GtkTargetList *list);
void                gtk_target_list_add                 (GtkTargetList *list,
                                                         GdkAtom target,
                                                         guint flags,
                                                         guint info);
void                gtk_target_list_add_table           (GtkTargetList *list,
                                                         const GtkTargetEntry *targets,
                                                         guint ntargets);
void                gtk_target_list_add_text_targets    (GtkTargetList *list,
                                                         guint info);
void                gtk_target_list_add_image_targets   (GtkTargetList *list,
                                                         guint info,
                                                         gboolean writable);
void                gtk_target_list_add_uri_targets     (GtkTargetList *list,
                                                         guint info);
void                gtk_target_list_add_rich_text_targets
                                                        (GtkTargetList *list,
                                                         guint info,
                                                         gboolean deserializable,
                                                         GtkTextBuffer *buffer);
void                gtk_target_list_remove              (GtkTargetList *list,
                                                         GdkAtom target);
gboolean            gtk_target_list_find                (GtkTargetList *list,
                                                         GdkAtom target,
                                                         guint *info);
void                gtk_target_table_free               (GtkTargetEntry *targets,
                                                         gint n_targets);
GtkTargetEntry*     gtk_target_table_new_from_list      (GtkTargetList *list,
                                                         gint *n_targets);
gboolean            gtk_selection_owner_set             (GtkWidget *widget,
                                                         GdkAtom selection,
                                                         guint32 time_);
gboolean            gtk_selection_owner_set_for_display (GdkDisplay *display,
                                                         GtkWidget *widget,
                                                         GdkAtom selection,
                                                         guint32 time_);
void                gtk_selection_add_target            (GtkWidget *widget,
                                                         GdkAtom selection,
                                                         GdkAtom target,
                                                         guint info);
void                gtk_selection_add_targets           (GtkWidget *widget,
                                                         GdkAtom selection,
                                                         const GtkTargetEntry *targets,
                                                         guint ntargets);
void                gtk_selection_clear_targets         (GtkWidget *widget,
                                                         GdkAtom selection);
gboolean            gtk_selection_convert               (GtkWidget *widget,
                                                         GdkAtom selection,
                                                         GdkAtom target,
                                                         guint32 time_);
void                gtk_selection_data_set              (GtkSelectionData *selection_data,
                                                         GdkAtom type,
                                                         gint format,
                                                         const guchar *data,
                                                         gint length);
gboolean            gtk_selection_data_set_text         (GtkSelectionData *selection_data,
                                                         const gchar *str,
                                                         gint len);
guchar*             gtk_selection_data_get_text         (GtkSelectionData *selection_data);
gboolean            gtk_selection_data_set_pixbuf       (GtkSelectionData *selection_data,
                                                         GdkPixbuf *pixbuf);
GdkPixbuf*          gtk_selection_data_get_pixbuf       (GtkSelectionData *selection_data);
gboolean            gtk_selection_data_set_uris         (GtkSelectionData *selection_data,
                                                         gchar **uris);
gchar**             gtk_selection_data_get_uris         (GtkSelectionData *selection_data);
gboolean            gtk_selection_data_get_targets      (GtkSelectionData *selection_data,
                                                         GdkAtom **targets,
                                                         gint *n_atoms);
gboolean            gtk_selection_data_targets_include_image
                                                        (GtkSelectionData *selection_data,
                                                         gboolean writable);
gboolean            gtk_selection_data_targets_include_text
                                                        (GtkSelectionData *selection_data);
gboolean            gtk_selection_data_targets_include_uri
                                                        (GtkSelectionData *selection_data);
gboolean            gtk_selection_data_targets_include_rich_text
                                                        (GtkSelectionData *selection_data,
                                                         GtkTextBuffer *buffer);
gboolean            gtk_targets_include_image           (GdkAtom *targets,
                                                         gint n_targets,
                                                         gboolean writable);
gboolean            gtk_targets_include_text            (GdkAtom *targets,
                                                         gint n_targets);
gboolean            gtk_targets_include_uri             (GdkAtom *targets,
                                                         gint n_targets);
gboolean            gtk_targets_include_rich_text       (GdkAtom *targets,
                                                         gint n_targets,
                                                         GtkTextBuffer *buffer);
void                gtk_selection_remove_all            (GtkWidget *widget);
gboolean            gtk_selection_clear                 (GtkWidget *widget,
                                                         GdkEventSelection *event);
GtkSelectionData*   gtk_selection_data_copy             (GtkSelectionData *data);
void                gtk_selection_data_free             (GtkSelectionData *data);

Description

The selection mechanism provides the basis for different types of communication between processes. In particular, drag and drop and GtkClipboard work via selections. You will very seldom or never need to use most of the functions in this section directly; GtkClipboard provides a nicer interface to the same functionality.

Some of the datatypes defined this section are used in the GtkClipboard and drag-and-drop API's as well. The GtkTargetEntry structure and GtkTargetList objects represent lists of data types that are supported when sending or receiving data. The GtkSelectionData object is used to store a chunk of data along with the data type and other associated information.

Details

GtkTargetEntry

typedef struct {
  gchar *target;
  guint  flags;
  guint  info;
} GtkTargetEntry;

A GtkTargetEntry structure represents a single type of data than can be supplied for by a widget for a selection or for supplied or received during drag-and-drop. It contains a string representing the drag type, a flags field (used only for drag and drop - see GtkTargetFlags), and an application assigned integer ID. The integer ID will later be passed as a signal parameter for signals like "selection_get". It allows the application to identify the target type without extensive string compares.

GtkTargetList

typedef struct {
  GList *list;
  guint ref_count;
} GtkTargetList;

A GtkTargetList structure is a reference counted list of GtkTargetPair. It is used to represent the same information as a table of GtkTargetEntry, but in an efficient form. This structure should be treated as opaque.

GtkTargetPair

typedef struct {
  GdkAtom   target;
  guint     flags;
  guint     info;
} GtkTargetPair;

Internally used structure in the drag-and-drop and selection handling code.

gtk_target_list_new ()

GtkTargetList*      gtk_target_list_new                 (const GtkTargetEntry *targets,
                                                         guint ntargets);

Creates a new GtkTargetList from an array of GtkTargetEntry.

targets : | Pointer to an array of GtkTargetEntry
ntargets : | number of entries in targets.
Returns : | the new GtkTargetList.

gtk_target_list_ref ()

GtkTargetList*      gtk_target_list_ref                 (GtkTargetList *list);

Increases the reference count of a GtkTargetList by one.

list : | a GtkTargetList
Returns : | the passed in GtkTargetList.

gtk_target_list_unref ()

void                gtk_target_list_unref               (GtkTargetList *list);

Decreases the reference count of a GtkTargetList by one. If the resulting reference count is zero, frees the list.

list : a GtkTargetList

gtk_target_list_add ()

void                gtk_target_list_add                 (GtkTargetList *list,
                                                         GdkAtom target,
                                                         guint flags,
                                                         guint info);

Appends another target to a GtkTargetList.

list : | a GtkTargetList
target : | the interned atom representing the target
flags : | the flags for this target
info : | an ID that will be passed back to the application

gtk_target_list_add_table ()

void                gtk_target_list_add_table           (GtkTargetList *list,
                                                         const GtkTargetEntry *targets,
                                                         guint ntargets);

Prepends a table of GtkTargetEntry to a target list.

list : | a GtkTargetList
targets : | the table of GtkTargetEntry
ntargets : | number of targets in the table

gtk_target_list_add_text_targets ()

void                gtk_target_list_add_text_targets    (GtkTargetList *list,
                                                         guint info);

Appends the text targets supported by GtkSelection to the target list. All targets are added with the same info.

list : | a GtkTargetList
info : | an ID that will be passed back to the application

Since 2.6

gtk_target_list_add_image_targets ()

void                gtk_target_list_add_image_targets   (GtkTargetList *list,
                                                         guint info,
                                                         gboolean writable);

Appends the image targets supported by GtkSelection to the target list. All targets are added with the same info.

list : | a GtkTargetList
info : | an ID that will be passed back to the application
writable : | whether to add only targets for which GTK+ knows how to convert a pixbuf into the format

Since 2.6

gtk_target_list_add_uri_targets ()

void                gtk_target_list_add_uri_targets     (GtkTargetList *list,
                                                         guint info);

Appends the URI targets supported by GtkSelection to the target list. All targets are added with the same info.

list : | a GtkTargetList
info : | an ID that will be passed back to the application

Since 2.6

gtk_target_list_add_rich_text_targets ()

void                gtk_target_list_add_rich_text_targets
                                                        (GtkTargetList *list,
                                                         guint info,
                                                         gboolean deserializable,
                                                         GtkTextBuffer *buffer);

Appends the rich text targets registered with gtk_text_buffer_register_serialize_format() or gtk_text_buffer_register_deserialize_format() to the target list. All targets are added with the same info.

list : | a GtkTargetList
info : | an ID that will be passed back to the application
deserializable : | if TRUE, then deserializable rich text formats will be added, serializable formats otherwise.
buffer : | a GtkTextBuffer.

Since 2.10

gtk_target_list_remove ()

void                gtk_target_list_remove              (GtkTargetList *list,
                                                         GdkAtom target);

Removes a target from a target list.

list : | a GtkTargetList
target : | the interned atom representing the target

gtk_target_list_find ()

gboolean            gtk_target_list_find                (GtkTargetList *list,
                                                         GdkAtom target,
                                                         guint *info);

Looks up a given target in a GtkTargetList.

list : | a GtkTargetList
target : | an interned atom representing the target to search for
info : | a pointer to the location to store application info for target
Returns : | TRUE if the target was found, otherwise FALSE

gtk_target_table_free ()

void                gtk_target_table_free               (GtkTargetEntry *targets,
                                                         gint n_targets);

This function frees a target table as returned by gtk_target_table_new_from_list()

targets : | a GtkTargetEntry array
n_targets : | the number of entries in the array

Since 2.10

gtk_target_table_new_from_list ()

GtkTargetEntry*     gtk_target_table_new_from_list      (GtkTargetList *list,
                                                         gint *n_targets);

This function creates an GtkTargetEntry array that contains the same targets as the passed list. The returned table is newly allocated and should be freed using gtk_target_table_free() when no longer needed.

list : | a GtkTargetList
n_targets : | return location for the number ot targets in the table
Returns : | the new table.

Since 2.10

gtk_selection_owner_set ()

gboolean            gtk_selection_owner_set             (GtkWidget *widget,
                                                         GdkAtom selection,
                                                         guint32 time_);

Claims ownership of a given selection for a particular widget, or, if widget is NULL, release ownership of the selection.

widget : | a GtkWidget, or NULL.
selection : | an interned atom representing the selection to claim
time_ : | timestamp with which to claim the selection
Returns : | TRUE if the operation succeeded

gtk_selection_owner_set_for_display ()

gboolean            gtk_selection_owner_set_for_display (GdkDisplay *display,
                                                         GtkWidget *widget,
                                                         GdkAtom selection,
                                                         guint32 time_);

Claim ownership of a given selection for a particular widget, or, if widget is NULL, release ownership of the selection.

display : | the Gdkdisplay where the selection is set
widget : | new selection owner (a GdkWidget), or NULL.
selection : | an interned atom representing the selection to claim.
time_ : | timestamp with which to claim the selection
Returns : | TRUE if the operation succeeded

Since 2.2

gtk_selection_add_target ()

void                gtk_selection_add_target            (GtkWidget *widget,
                                                         GdkAtom selection,
                                                         GdkAtom target,
                                                         guint info);

Appends a specified target to the list of supported targets for a given widget and selection.

widget : | a GtkTarget
selection : | the selection
target : | target to add.
info : | A unsigned integer which will be passed back to the application.

gtk_selection_add_targets ()

void                gtk_selection_add_targets           (GtkWidget *widget,
                                                         GdkAtom selection,
                                                         const GtkTargetEntry *targets,
                                                         guint ntargets);

Prepends a table of targets to the list of supported targets for a given widget and selection.

widget : | a GtkWidget
selection : | the selection
targets : | a table of targets to add
ntargets : | number of entries in targets

gtk_selection_clear_targets ()

void                gtk_selection_clear_targets         (GtkWidget *widget,
                                                         GdkAtom selection);

Remove all targets registered for the given selection for the widget.

widget : | a GtkWidget
selection : | an atom representing a selection

gtk_selection_convert ()

gboolean            gtk_selection_convert               (GtkWidget *widget,
                                                         GdkAtom selection,
                                                         GdkAtom target,
                                                         guint32 time_);

Requests the contents of a selection. When received, a "selection_received" signal will be generated.

widget : | The widget which acts as requestor
selection : | Which selection to get
target : | Form of information desired (e.g., STRING)
time_ : | Time of request (usually of triggering event) In emergency, you could use GDK_CURRENT_TIME
Returns : | TRUE if requested succeeded. FALSE if we could not process request. (e.g., there was already a request in process for this widget).

gtk_selection_data_set ()

void                gtk_selection_data_set              (GtkSelectionData *selection_data,
                                                         GdkAtom type,
                                                         gint format,
                                                         const guchar *data,
                                                         gint length);

Stores new data into a GtkSelectionData object. Should only be called from a selection handler callback. Zero-terminates the stored data.

selection_data : | a pointer to a GtkSelectionData structure.
type : | the type of selection data
format : | format (number of bits in a unit)
data : | pointer to the data (will be copied)
length : | length of the data

gtk_selection_data_set_text ()

gboolean            gtk_selection_data_set_text         (GtkSelectionData *selection_data,
                                                         const gchar *str,
                                                         gint len);

Sets the contents of the selection from a UTF-8 encoded string. The string is converted to the form determined by selection_data->target.

selection_data : | a GtkSelectionData
str : | a UTF-8 string
len : | the length of str, or -1 if str is nul-terminated.
Returns : | TRUE if the selection was successfully set, otherwise FALSE.

gtk_selection_data_get_text ()

guchar*             gtk_selection_data_get_text         (GtkSelectionData *selection_data);

Gets the contents of the selection data as a UTF-8 string.

selection_data : | a GtkSelectionData
Returns : | if the selection data contained a recognized text type and it could be converted to UTF-8, a newly allocated string containing the converted text, otherwise NULL. If the result is non-NULL it must be freed with g_free().

gtk_selection_data_set_pixbuf ()

gboolean            gtk_selection_data_set_pixbuf       (GtkSelectionData *selection_data,
                                                         GdkPixbuf *pixbuf);

Sets the contents of the selection from a GdkPixbuf The pixbuf is converted to the form determined by selection_data->target.

selection_data : | a GtkSelectionData
pixbuf : | a GdkPixbuf
Returns : | TRUE if the selection was successfully set, otherwise FALSE.

Since 2.6

gtk_selection_data_get_pixbuf ()

GdkPixbuf*          gtk_selection_data_get_pixbuf       (GtkSelectionData *selection_data);

Gets the contents of the selection data as a GdkPixbuf.

selection_data : | a GtkSelectionData
Returns : | if the selection data contained a recognized image type and it could be converted to a GdkPixbuf, a newly allocated pixbuf is returned, otherwise NULL. If the result is non-NULL it must be freed with g_object_unref().

Since 2.6

gtk_selection_data_set_uris ()

gboolean            gtk_selection_data_set_uris         (GtkSelectionData *selection_data,
                                                         gchar **uris);

Sets the contents of the selection from a list of URIs. The string is converted to the form determined by selection_data->target.

selection_data : | a GtkSelectionData
uris : | a NULL-terminated array of strings hilding URIs
Returns : | TRUE if the selection was successfully set, otherwise FALSE.

Since 2.6

gtk_selection_data_get_uris ()

gchar**             gtk_selection_data_get_uris         (GtkSelectionData *selection_data);

Gets the contents of the selection data as array of URIs.

selection_data : | a GtkSelectionData
Returns : | if the selection data contains a list of URIs, a newly allocated NULL-terminated string array containing the URIs, otherwise NULL. If the result is non-NULL it must be freed with g_strfreev().

Since 2.6

gtk_selection_data_get_targets ()

gboolean            gtk_selection_data_get_targets      (GtkSelectionData *selection_data,
                                                         GdkAtom **targets,
                                                         gint *n_atoms);

Gets the contents of selection_data as an array of targets. This can be used to interpret the results of getting the standard TARGETS target that is always supplied for any selection.

selection_data : | a GtkSelectionData object
targets : | location to store an array of targets. The result stored here must be freed with g_free().
n_atoms : | location to store number of items in targets.
Returns : | TRUE if selection_data contains a valid array of targets, otherwise FALSE.

gtk_selection_data_targets_include_image ()

gboolean            gtk_selection_data_targets_include_image
                                                        (GtkSelectionData *selection_data,
                                                         gboolean writable);

Given a GtkSelectionData object holding a list of targets, determines if any of the targets in targets can be used to provide a GdkPixbuf.

selection_data : | a GtkSelectionData object
writable : | whether to accept only targets for which GTK+ knows how to convert a pixbuf into the format
Returns : | TRUE if selection_data holds a list of targets, and a suitable target for images is included, otherwise FALSE.

Since 2.6

gtk_selection_data_targets_include_text ()

gboolean            gtk_selection_data_targets_include_text
                                                        (GtkSelectionData *selection_data);

Given a GtkSelectionData object holding a list of targets, determines if any of the targets in targets can be used to provide text.

selection_data : | a GtkSelectionData object
Returns : | TRUE if selection_data holds a list of targets, and a suitable target for text is included, otherwise FALSE.

gtk_selection_data_targets_include_uri ()

gboolean            gtk_selection_data_targets_include_uri
                                                        (GtkSelectionData *selection_data);

Given a GtkSelectionData object holding a list of targets, determines if any of the targets in targets can be used to provide a list or URIs.

selection_data : | a GtkSelectionData object
Returns : | TRUE if selection_data holds a list of targets, and a suitable target for text is included, otherwise FALSE.

Since 2.10

gtk_selection_data_targets_include_rich_text ()

gboolean            gtk_selection_data_targets_include_rich_text
                                                        (GtkSelectionData *selection_data,
                                                         GtkTextBuffer *buffer);

Given a GtkSelectionData object holding a list of targets, determines if any of the targets in targets can be used to provide rich text.

selection_data : | a GtkSelectionData object
buffer : | a GtkTextBuffer
Returns : | TRUE if selection_data holds a list of targets, and a suitable target for rich text is included, otherwise FALSE.

Since 2.10

gtk_targets_include_image ()

gboolean            gtk_targets_include_image           (GdkAtom *targets,
                                                         gint n_targets,
                                                         gboolean writable);

Determines if any of the targets in targets can be used to provide a GdkPixbuf.

targets : | an array of GdkAtoms
n_targets : | the length of targets
writable : | whether to accept only targets for which GTK+ knows how to convert a pixbuf into the format
Returns : | TRUE if targets include a suitable target for images, otherwise FALSE.

Since 2.10

gtk_targets_include_text ()

gboolean            gtk_targets_include_text            (GdkAtom *targets,
                                                         gint n_targets);

Determines if any of the targets in targets can be used to provide text.

targets : | an array of GdkAtoms
n_targets : | the length of targets
Returns : | TRUE if targets include a suitable target for text, otherwise FALSE.

Since 2.10

gtk_targets_include_uri ()

gboolean            gtk_targets_include_uri             (GdkAtom *targets,
                                                         gint n_targets);

Determines if any of the targets in targets can be used to provide an uri list.

targets : | an array of GdkAtoms
n_targets : | the length of targets
Returns : | TRUE if targets include a suitable target for uri lists, otherwise FALSE.

Since 2.10

gtk_targets_include_rich_text ()

gboolean            gtk_targets_include_rich_text       (GdkAtom *targets,
                                                         gint n_targets,
                                                         GtkTextBuffer *buffer);

Determines if any of the targets in targets can be used to provide rich text.

targets : | an array of GdkAtoms
n_targets : | the length of targets
buffer : | a GtkTextBuffer
Returns : | TRUE if targets include a suitable target for rich text, otherwise FALSE.

Since 2.10

gtk_selection_remove_all ()

void                gtk_selection_remove_all            (GtkWidget *widget);

Removes all handlers and unsets ownership of all selections for a widget. Called when widget is being destroyed. This function will not generally be called by applications.

widget : a GtkWidget

gtk_selection_clear ()

gboolean            gtk_selection_clear                 (GtkWidget *widget,
                                                         GdkEventSelection *event);

Warning

gtk_selection_clear has been deprecated since version 2.4 and should not be used in newly-written code. Instead of calling this function, chain up from your selection_clear_event handler. Calling this function from any other context is illegal.

The default handler for the GtkWidget::selection_clear_event signal.

widget : | a GtkWidget
event : | the event
Returns : | TRUE if the event was handled, otherwise false

Since 2.2

gtk_selection_data_copy ()

GtkSelectionData*   gtk_selection_data_copy             (GtkSelectionData *data);

Makes a copy of a GtkSelectionData structure and its data.

data : | a pointer to a GtkSelectionData structure.
Returns : | a pointer to a copy of data.

gtk_selection_data_free ()

void                gtk_selection_data_free             (GtkSelectionData *data);

Frees a GtkSelectionData structure returned from gtk_selection_data_copy().

data : a pointer to a GtkSelectionData structure.

See Also

GtkWidget

Much of the operation of selections happens via signals for GtkWidget. In particular, if you are using the functions in this section, you may need to pay attention to ::selection_get, ::selection_received, and :selection_clear_event signals.


Signals

Signals — Object methods and callbacks

Synopsis

#include <gtk/gtk.h>

#define             GTK_SIGNAL_OFFSET
enum                GtkSignalRunType;
guint               gtk_signal_new                      (const gchar *name,
                                                         GtkSignalRunType signal_flags,
                                                         GtkType object_type,
                                                         guint function_offset,
                                                         GtkSignalMarshaller marshaller,
                                                         GtkType return_val,
                                                         guint n_args,
                                                         ...);
guint               gtk_signal_newv                     (const gchar *name,
                                                         GtkSignalRunType signal_flags,
                                                         GtkType object_type,
                                                         guint function_offset,
                                                         GtkSignalMarshaller marshaller,
                                                         GtkType return_val,
                                                         guint n_args,
                                                         GtkType *args);
#define             gtk_signal_lookup                   (name,object_type)
#define             gtk_signal_name                     (signal_id)
void                gtk_signal_emit                     (GtkObject *object,
                                                         guint signal_id,
                                                         ...);
void                gtk_signal_emit_by_name             (GtkObject *object,
                                                         const gchar *name,
                                                         ...);
void                gtk_signal_emitv                    (GtkObject *object,
                                                         guint signal_id,
                                                         GtkArg *args);
void                gtk_signal_emitv_by_name            (GtkObject *object,
                                                         const gchar *name,
                                                         GtkArg *args);
#define             gtk_signal_emit_stop                (object,signal_id)
void                gtk_signal_emit_stop_by_name        (GtkObject *object,
                                                         const gchar *name);
#define             gtk_signal_connect                  (object,name,func,func_data)
#define             gtk_signal_connect_after            (object,name,func,func_data)
#define             gtk_signal_connect_object           (object,name,func,slot_object)
#define             gtk_signal_connect_object_after     (object,name,func,slot_object)
gulong              gtk_signal_connect_full             (GtkObject *object,
                                                         const gchar *name,
                                                         GtkSignalFunc func,
                                                         GtkCallbackMarshal unsupported,
                                                         gpointer data,
                                                         GtkDestroyNotify destroy_func,
                                                         gint object_signal,
                                                         gint after);
void                gtk_signal_connect_while_alive      (GtkObject *object,
                                                         const gchar *name,
                                                         GtkSignalFunc func,
                                                         gpointer func_data,
                                                         GtkObject *alive_object);
void                gtk_signal_connect_object_while_alive
                                                        (GtkObject *object,
                                                         const gchar *name,
                                                         GtkSignalFunc func,
                                                         GtkObject *alive_object);
#define             gtk_signal_disconnect               (object,handler_id)
#define             gtk_signal_disconnect_by_func       (object,func,data)
#define             gtk_signal_disconnect_by_data       (object,data)
#define             gtk_signal_handler_block            (object,handler_id)
#define             gtk_signal_handler_block_by_func    (object,func,data)
#define             gtk_signal_handler_block_by_data    (object,data)
#define             gtk_signal_handler_unblock          (object,handler_id)
#define             gtk_signal_handler_unblock_by_func  (object,func,data)
#define             gtk_signal_handler_unblock_by_data  (object,data)
#define             gtk_signal_handler_pending          (object,signal_id,may_be_blocked)
#define             gtk_signal_handler_pending_by_func  (object,signal_id,may_be_blocked,func,data)
#define             gtk_signal_default_marshaller

Description

The GTK+ signal system merely proxies the GLib signal system now. For future usage, direct use of the GSignal API is recommended, this avoids significant performance hits where GtkArg structures have to be converted into GValues.

What are signals?

Signals are a way to get notification when something happens and to customize object behavior according to the user's needs. Every signal is uniquely identified by a name, "class_name::signal_name", where signal_name might be something like "clicked" and class_name might be "GtkButton". Note that some other class may also define a "clicked" callback, so long as it doesn't derive from GtkButton.

When they are created, they are also assigned a unique positive integer, the signal id (1 is the first signal id- 0 is used to flag an error). Each is also tied to an array of types that describes the prototype of the function pointer(s) (handlers) you may connect to the signal. Finally, every signal has a default handler that is given by a function pointer in its class structure: it is run by default whenever the signal is emitted. (It is possible that a signal will be emitted and a user-defined handler will prevent the default handler from being run.)

Signals are used by everyone, but they are only created on a per class basis -- so you should not call call gtk_signal_new() unless you are writing a new GtkObject type. However, if you want to make a new signal for an existing type, you may use gtk_object_class_user_signal_new() to create a signal that doesn't correspond to a class's builtin methods.

How are signals used?

There are two basic actions in the signal handling game. If you want notification of an event, you must connect a function pointer and a data pointer to that signal; the data pointer will be passed as the last argument to the function (so long as you are using the default marshalling functions). You will receive a connection id, a unique positive integer corresponding to that attachment.

Functions that want to notify the user of certain actions, emit signals.

Basic Terminology

signal | A class method, e.g. GtkButton::clicked. More precisely it is a unique class-branch/signal-name pair. This means you may not define a signal handler for a class which derives from GtkButton that is called clicked, but it is okay to share signals names if they are separate in the class tree.
default handler | The object's internal method which is invoked when the signal is emitted.
user-defined handler | A function pointer and data connected to a signal (for a particular object). There are really two types: those which are connected normally, and those which are connected by one of the connect_after functions. The connect_after handlers are always run after the default handler. Many toolkits refer to these as callbacks.
emission | the whole process of emitting a signal, including the invocation of all the different handler types mentioned above.
signal id | The unique positive (nonzero) integer used to identify a signal. It can be used instead of a name to many functions for a slight performance improvement.
connection id | The unique positive (nonzero) integer used to identify the connection of a user-defined handler to a signal. Notice that it is allowed to connect the same function-pointer/user-data pair twice, so there is no guarantee that a function-pointer/user-data maps to a unique connection id.

A brief note on how they work.

The functions responsible for translating an array of GtkArgs to your C compiler's normal semantics are called Marshallers. They are identified by gtk_marshal_return_value__parameter_list() for example a C function returning a gboolean and taking a gint can be invoked by using gtk_marshal_BOOL__INT(). Not all possibly combinations of return/params are available, of course, so if you are writing a GtkObject with parameters you might have to write a marshaller.

Details

GTK_SIGNAL_OFFSET

#define GTK_SIGNAL_OFFSET	                      GTK_STRUCT_OFFSET

Warning

GTK_SIGNAL_OFFSET is deprecated and should not be used in newly-written code.

Use in place of offsetof(), which is used if it exists.

enum GtkSignalRunType

typedef enum			/*< flags >*/
{
  GTK_RUN_FIRST      = G_SIGNAL_RUN_FIRST,
  GTK_RUN_LAST       = G_SIGNAL_RUN_LAST,
  GTK_RUN_BOTH       = (GTK_RUN_FIRST | GTK_RUN_LAST),
  GTK_RUN_NO_RECURSE = G_SIGNAL_NO_RECURSE,
  GTK_RUN_ACTION     = G_SIGNAL_ACTION,
  GTK_RUN_NO_HOOKS   = G_SIGNAL_NO_HOOKS
} GtkSignalRunType;

Warning

GtkSignalRunType is deprecated and should not be used in newly-written code.

These configure the signal's emission. They control whether the signal can be emitted recursively on an object and whether to run the default method before or after the user-defined handlers.

GTK_RUN_FIRST

Run the default handler before the connected user-defined handlers.

GTK_RUN_LAST

Run the default handler after the connected user-defined handlers. (Handlers registered as "after" always run after the default handler though)

GTK_RUN_BOTH

Run the default handler twice, once before the user-defined handlers, and once after.

GTK_RUN_NO_RECURSE

Whether to prevent a handler or hook from reemitting the signal from within itself. Attempts to emit the signal while it is running will result in the signal emission being restarted once it is done with the current processing.

You must be careful to avoid having two handlers endlessly reemitting signals, gtk_signal_n_emissions() can be helpful.

GTK_RUN_ACTION

The signal is an action you can invoke without any particular setup or cleanup. The signal is treated no differently, but some other code can determine if the signal is appropriate to delegate to user control. For example, key binding sets only allow bindings of ACTION signals to keystrokes.

GTK_RUN_NO_HOOKS

This prevents the connection of emission hooks to the signal.

gtk_signal_new ()

guint               gtk_signal_new                      (const gchar *name,
                                                         GtkSignalRunType signal_flags,
                                                         GtkType object_type,
                                                         guint function_offset,
                                                         GtkSignalMarshaller marshaller,
                                                         GtkType return_val,
                                                         guint n_args,
                                                         ...);

Warning

gtk_signal_new is deprecated and should not be used in newly-written code. Use g_signal_new() instead.

Creates a new signal type. (This is usually done in the class initializer.)

name : | the event name for the signal, e.g. "clicked".
signal_flags : | a combination of GTK_RUN flags specifying detail of when the default handler is to be invoked. You should at least specify GTK_RUN_FIRST or GTK_RUN_LAST.
object_type : | the type of object this signal pertains to. It will also pertain to derivers of this type automatically.
function_offset : | How many bytes the function pointer is in the class structure for this type. Used to invoke a class method generically.
marshaller : | the function to translate between an array of GtkArgs and the native calling convention. Usually they are identified just by the type of arguments they take: for example, gtk_marshal_BOOL__STRING() describes a marshaller which takes a string and returns a boolean value.
return_val : | the type of return value, or GTK_TYPE_NONE for a signal without a return value.
n_args : | the number of parameter the handlers may take.
... : | a list of GTK_TYPE_*, one for each parameter.
Returns : | the signal id.

gtk_signal_newv ()

guint               gtk_signal_newv                     (const gchar *name,
                                                         GtkSignalRunType signal_flags,
                                                         GtkType object_type,
                                                         guint function_offset,
                                                         GtkSignalMarshaller marshaller,
                                                         GtkType return_val,
                                                         guint n_args,
                                                         GtkType *args);

Warning

gtk_signal_newv is deprecated and should not be used in newly-written code. Use g_signal_newv() instead.

Creates a new signal type. (This is usually done in a class initializer.)

This function take the types as an array, instead of a list following the arguments. Otherwise the same as gtk_signal_new().

name : | the name of the signal to create.
signal_flags : | see gtk_signal_new().
object_type : | the type of GtkObject to associate the signal with.
function_offset : | how many bytes the function pointer is in the class structure for this type.
marshaller : |
return_val : | the type of the return value, or GTK_TYPE_NONE if you don't want a return value.
n_args : | the number of parameters to the user-defined handlers.
args : | an array of GtkTypes, describing the prototype to the callbacks.
Returns : | the signal id.

gtk_signal_lookup()

#define             gtk_signal_lookup(name,object_type)

Warning

gtk_signal_lookup is deprecated and should not be used in newly-written code. Use g_signal_lookup() instead.

Given the name of the signal and the type of object it connects to, get the signal's identifying integer. Emitting the signal by number is somewhat faster than using the name each time.

It also tries the ancestors of the given type.

name : | the signal's name, e.g. clicked.
object_type : | the type that the signal operates on, e.g. GTK_TYPE_BUTTON.
Returns : | the signal's identifying number, or 0 if no signal was found.

gtk_signal_name()

#define             gtk_signal_name(signal_id)

Warning

gtk_signal_name is deprecated and should not be used in newly-written code. Use g_signal_name() instead.

Given the signal's identifier, finds its name.

Two different signals may have the same name, if they have differing types.

signal_id : | the signal's identifying number.
Returns : | the signal name, or NULL if the signal number was invalid.

gtk_signal_emit ()

void                gtk_signal_emit                     (GtkObject *object,
                                                         guint signal_id,
                                                         ...);

Warning

gtk_signal_emit is deprecated and should not be used in newly-written code. Use g_signal_emit() instead.

Emits a signal. This causes the default handler and user-defined handlers to be run.

Here is what gtk_signal_emit() does:

1. Calls the default handler and the user-connected handlers. The default handler will be called first if GTK_RUN_FIRST is set, and last if GTK_RUN_LAST is set.

2. Calls all handlers connected with the "after" flag set.

object : | the object that emits the signal.
signal_id : | the signal identifier.
... : | the parameters to the function, followed by a pointer to the return type, if any.

gtk_signal_emit_by_name ()

void                gtk_signal_emit_by_name             (GtkObject *object,
                                                         const gchar *name,
                                                         ...);

Warning

gtk_signal_emit_by_name is deprecated and should not be used in newly-written code. Use g_signal_emit_by_name() instead.

Emits a signal. This causes the default handler and user-connected handlers to be run.

object : | the object that emits the signal.
name : | the name of the signal.
... : | the parameters to the function, followed by a pointer to the return type, if any.

gtk_signal_emitv ()

void                gtk_signal_emitv                    (GtkObject *object,
                                                         guint signal_id,
                                                         GtkArg *args);

Warning

gtk_signal_emitv is deprecated and should not be used in newly-written code. Use g_signal_emitv() instead.

Emits a signal. This causes the default handler and user-connected handlers to be run. This differs from gtk_signal_emit() by taking an array of GtkArgs instead of using C's varargs mechanism.

object : | the object to emit the signal to.
signal_id : | the signal identifier.
args : | an array of GtkArgs, one for each parameter, followed by one which is a pointer to the return type.

gtk_signal_emitv_by_name ()

void                gtk_signal_emitv_by_name            (GtkObject *object,
                                                         const gchar *name,
                                                         GtkArg *args);

Warning

gtk_signal_emitv_by_name is deprecated and should not be used in newly-written code. Use g_signal_emitv() and g_signal_lookup() instead.

Emits a signal by name. This causes the default handler and user-connected handlers to be run. This differs from gtk_signal_emit() by taking an array of GtkArgs instead of using C's varargs mechanism.

object : | the object to emit the signal to.
name : | the name of the signal.
args : | an array of GtkArgs, one for each parameter, followed by one which is a pointer to the return type.

gtk_signal_emit_stop()

#define             gtk_signal_emit_stop(object,signal_id)

Warning

gtk_signal_emit_stop is deprecated and should not be used in newly-written code. Use g_signal_stop_emission() instead.

This function aborts a signal's current emission.

It will prevent the default method from running, if the signal was GTK_RUN_LAST and you connected normally (i.e. without the "after" flag).

It will print a warning if used on a signal which isn't being emitted.

object : | the object whose signal handlers you wish to stop.
signal_id : | the signal identifier, as returned by g_signal_lookup().

gtk_signal_emit_stop_by_name ()

void                gtk_signal_emit_stop_by_name        (GtkObject *object,
                                                         const gchar *name);

Warning

gtk_signal_emit_stop_by_name is deprecated and should not be used in newly-written code. Use g_signal_stop_emission_by_name() instead.

This function aborts a signal's current emission.

It is just like gtk_signal_emit_stop() except it will lookup the signal id for you.

object : | the object whose signal handlers you wish to stop.
name : | the name of the signal you wish to stop.

gtk_signal_connect()

#define             gtk_signal_connect(object,name,func,func_data)

Warning

gtk_signal_connect is deprecated and should not be used in newly-written code. Use g_signal_connect() instead.

Attaches a function pointer and user data to a signal for a particular object.

The GtkSignalFunction takes a GtkObject as its first parameter. It will be the same object as the one you're connecting the hook to. The func_data will be passed as the last parameter to the hook.

All else being equal, signal handlers are invoked in the order connected (see gtk_signal_emit() for the other details of which order things are called in).

Here is how one passes an integer as user data, for when you just want to specify a constant int as parameter to your function:

static void button_clicked_int (GtkButton* button, gpointer func_data)
{
    g_print ("button pressed: %d\n", GPOINTER_TO_INT (func_data));
}

/* By calling this function, you will make the g_print above
 * execute, printing the number passed as `to_print'. */
static void attach_print_signal (GtkButton* button, gint to_print)
{
    gtk_signal_connect (GTK_OBJECT (button), "clicked",
        GTK_SIGNAL_FUNC (button_clicked_int),
        GINT_TO_POINTER (to_print));
}

object : | the object associated with the signal, e.g. if a button is getting pressed, this is that button.
name : | name of the signal.
func : | function pointer to attach to the signal.
func_data : | value to pass as to your function (through the marshaller).
Returns : | the connection id.

gtk_signal_connect_after()

#define             gtk_signal_connect_after(object,name,func,func_data)

Warning

gtk_signal_connect_after is deprecated and should not be used in newly-written code. Use g_signal_connect_after() instead.

Attaches a function pointer and user data to a signal so that this handler will be called after the other handlers.

object : | the object associated with the signal.
name : | name of the signal.
func : | function pointer to attach to the signal.
func_data : | value to pass as to your function (through the marshaller).
Returns : | the unique identifier for this attachment: the connection id.

gtk_signal_connect_object()

#define             gtk_signal_connect_object(object,name,func,slot_object)

Warning

gtk_signal_connect_object is deprecated and should not be used in newly-written code. Use g_signal_connect_swapped() instead.

This function is for registering a callback that will call another object's callback. That is, instead of passing the object which is responsible for the event as the first parameter of the callback, it is switched with the user data (so the object which emits the signal will be the last parameter, which is where the user data usually is).

This is useful for passing a standard function in as a callback. For example, if you wanted a button's press to gtk_widget_show() some widget, you could write:

gtk_signal_connect_object (button, "clicked", gtk_widget_show, window);

object : | the object which emits the signal.
name : | the name of the signal.
func : | the function to callback.
slot_object : | the object to pass as the first parameter to func. (Though it pretends to take an object, you can really pass any gpointer as the slot_object .)
Returns : | the connection id.

gtk_signal_connect_object_after()

#define             gtk_signal_connect_object_after(object,name,func,slot_object)

Warning

gtk_signal_connect_object_after is deprecated and should not be used in newly-written code. Use g_signal_connect_data() instead, passing G_CONNECT_AFTER|G_CONNECT_SWAPPED as connect_flags.

Attaches a signal hook to a signal, passing in an alternate object as the first parameter, and guaranteeing that the default handler and all normal handlers are called first.

object : | the object associated with the signal.
name : | name of the signal.
func : | function pointer to attach to the signal.
slot_object : | the object to pass as the first parameter to func.
Returns : | the connection id.

gtk_signal_connect_full ()

gulong              gtk_signal_connect_full             (GtkObject *object,
                                                         const gchar *name,
                                                         GtkSignalFunc func,
                                                         GtkCallbackMarshal unsupported,
                                                         gpointer data,
                                                         GtkDestroyNotify destroy_func,
                                                         gint object_signal,
                                                         gint after);

Warning

gtk_signal_connect_full is deprecated and should not be used in newly-written code. Use g_signal_connect_data() instead.

Attaches a function pointer and user data to a signal with more control.

object : | the object which emits the signal. For example, a button in the button press signal.
name : | the name of the signal.
func : | function pointer to attach to the signal.
unsupported : |
data : | the user data associated with the function.
destroy_func : | function to call when this particular hook is disconnected.
object_signal : | whether this is an object signal-- basically an "object signal" is one that wants its user_data and object fields switched, which is useful for calling functions which operate on another object primarily.
after : | whether to invoke the user-defined handler after the signal, or to let the signal's default behavior preside (i.e. depending on GTK_RUN_FIRST and GTK_RUN_LAST).
Returns : | the connection id.

gtk_signal_connect_while_alive ()

void                gtk_signal_connect_while_alive      (GtkObject *object,
                                                         const gchar *name,
                                                         GtkSignalFunc func,
                                                         gpointer func_data,
                                                         GtkObject *alive_object);

Warning

gtk_signal_connect_while_alive is deprecated and should not be used in newly-written code. Use g_signal_connect_object() instead.

Attaches a function pointer and another GtkObject to a signal.

This function takes an object whose "destroy" signal should be trapped. That way, you don't have to clean up the signal handler when you destroy the object. It is a little less efficient though.

(Instead you may call gtk_signal_disconnect_by_data(), if you want to explicitly delete all attachments to this object. This is perhaps not recommended since it could be confused with an integer masquerading as a pointer (through GINT_TO_POINTER()).)

object : | the object that emits the signal.
name : | name of the signal.
func : | function pointer to attach to the signal.
func_data : | pointer to pass to func.
alive_object : | object whose death should cause the handler connection to be destroyed.

gtk_signal_connect_object_while_alive ()

void                gtk_signal_connect_object_while_alive
                                                        (GtkObject *object,
                                                         const gchar *name,
                                                         GtkSignalFunc func,
                                                         GtkObject *alive_object);

Warning

gtk_signal_connect_object_while_alive is deprecated and should not be used in newly-written code. Use g_signal_connect_object() instead, passing G_CONNECT_SWAPPED as connect_flags.

These signal connectors are for signals which refer to objects, so they must not be called after the object is deleted.

Unlike gtk_signal_connect_while_alive(), this swaps the object and user data, making it suitable for use with functions which primarily operate on the user data.

This function acts just like gtk_signal_connect_object() except it traps the "destroy" signal to prevent you from having to clean up the handler.

object : | the object associated with the signal.
name : | name of the signal.
func : | function pointer to attach to the signal.
alive_object : | the user data, which must be an object, whose destruction should signal the removal of this signal.

gtk_signal_disconnect()

#define             gtk_signal_disconnect(object,handler_id)

Warning

gtk_signal_disconnect is deprecated and should not be used in newly-written code. Use g_signal_handler_disconnect() instead.

Destroys a user-defined handler connection.

object : | the object which the handler pertains to.
handler_id : | the connection id.

gtk_signal_disconnect_by_func()

#define             gtk_signal_disconnect_by_func(object,func,data)

Warning

gtk_signal_disconnect_by_func is deprecated and should not be used in newly-written code. Use g_signal_handlers_disconnect_by_func() instead.

Destroys all connections for a particular object, with the given function-pointer and user-data.

object : | the object which emits the signal.
func : | the function pointer to search for.
data : | the user data to search for.

gtk_signal_disconnect_by_data()

#define             gtk_signal_disconnect_by_data(object,data)

Warning

gtk_signal_disconnect_by_data is deprecated and should not be used in newly-written code. Use g_signal_handlers_disconnect_matched() instead.

Destroys all connections for a particular object, with the given user-data.

object : | the object which emits the signal.
data : | the user data to search for.

gtk_signal_handler_block()

#define             gtk_signal_handler_block(object,handler_id)

Warning

gtk_signal_handler_block is deprecated and should not be used in newly-written code. Use g_signal_handler_block() instead.

Prevents a user-defined handler from being invoked. All other signal processing will go on as normal, but this particular handler will ignore it.

object : | the object which emits the signal to block.
handler_id : | the connection id.

gtk_signal_handler_block_by_func()

#define             gtk_signal_handler_block_by_func(object,func,data)

Warning

gtk_signal_handler_block_by_func is deprecated and should not be used in newly-written code. Use g_signal_handlers_block_by_func() instead.

Prevents a user-defined handler from being invoked, by reference to the user-defined handler's function pointer and user data. (It may result in multiple hooks being blocked, if you've called connect multiple times.)

object : | the object which emits the signal to block.
func : | the function pointer of the handler to block.
data : | the user data of the handler to block.

gtk_signal_handler_block_by_data()

#define             gtk_signal_handler_block_by_data(object,data)

Warning

gtk_signal_handler_block_by_data is deprecated and should not be used in newly-written code. Use g_signal_handlers_block_matched() instead.

Prevents all user-defined handlers with a certain user data from being invoked.

object : | the object which emits the signal we want to block.
data : | the user data of the handlers to block.

gtk_signal_handler_unblock()

#define             gtk_signal_handler_unblock(object,handler_id)

Warning

gtk_signal_handler_unblock is deprecated and should not be used in newly-written code. Use g_signal_handler_unblock() instead.

Undoes a block, by connection id. Note that undoing a block doesn't necessarily make the hook callable, because if you block a hook twice, you must unblock it twice.

object : | the object which emits the signal we want to unblock.
handler_id : | the emission handler identifier, as returned by gtk_signal_connect(), etc.

gtk_signal_handler_unblock_by_func()

#define             gtk_signal_handler_unblock_by_func(object,func,data)

Warning

gtk_signal_handler_unblock_by_func is deprecated and should not be used in newly-written code. Use g_signal_handlers_unblock_by_func() instead.

Undoes a block, by function pointer and data. Note that undoing a block doesn't necessarily make the hook callable, because if you block a hook twice, you must unblock it twice.

object : | the object which emits the signal we want to unblock.
func : | the function pointer to search for.
data : | the user data to search for.

gtk_signal_handler_unblock_by_data()

#define             gtk_signal_handler_unblock_by_data(object,data)

Warning

gtk_signal_handler_unblock_by_data is deprecated and should not be used in newly-written code. Use g_signal_handlers_unblock_matched() instead.

Undoes block(s), to all signals for a particular object with a particular user-data pointer

object : | the object which emits the signal we want to unblock.
data : | the user data to search for.

gtk_signal_handler_pending()

#define             gtk_signal_handler_pending(object,signal_id,may_be_blocked)

Warning

gtk_signal_handler_pending is deprecated and should not be used in newly-written code. Use g_signal_has_handler_pending() instead.

Returns a connection id corresponding to a given signal id and object.

One example of when you might use this is when the arguments to the signal are difficult to compute. A class implementor may opt to not emit the signal if no one is attached anyway, thus saving the cost of building the arguments.

object : | the object to search for the desired user-defined handler.
signal_id : | the number of the signal to search for.
may_be_blocked : | whether it is acceptable to return a blocked handler.
Returns : | the connection id, if a connection was found. 0 otherwise.

gtk_signal_handler_pending_by_func()

#define             gtk_signal_handler_pending_by_func(object,signal_id,may_be_blocked,func,data)

Warning

gtk_signal_handler_pending_by_func is deprecated and should not be used in newly-written code.

Returns a connection id corresponding to a given signal id, object, function pointer and user data.

object : | the object to search for the desired handler.
signal_id : | the number of the signal to search for.
may_be_blocked : | whether it is acceptable to return a blocked handler.
func : | the function pointer to search for.
data : | the user data to search for.
Returns : | the connection id, if a handler was found. 0 otherwise.

gtk_signal_default_marshaller

#define	gtk_signal_default_marshaller	g_cclosure_marshal_VOID__VOID

Warning

gtk_signal_default_marshaller is deprecated and should not be used in newly-written code.

A marshaller that returns void and takes no extra parameters.

See Also

GtkObject | The base class for things which emit signals.
GSignal | The GLib signal system.


Standard Enumerations

Standard Enumerations — Public enumerated types used throughout GTK+

Synopsis

#include <gtk/gtk.h>

enum                GtkAccelFlags;
enum                GtkAnchorType;
enum                GtkArrowType;
enum                GtkAttachOptions;
enum                GtkButtonBoxStyle;
enum                GtkCornerType;
enum                GtkCurveType;
enum                GtkDeleteType;
enum                GtkDirectionType;
enum                GtkExpanderStyle;
enum                GtkIMPreeditStyle;
enum                GtkIMStatusStyle;
enum                GtkJustification;
enum                GtkMatchType;
enum                GtkMetricType;
enum                GtkMovementStep;
enum                GtkOrientation;
enum                GtkPackType;
enum                GtkPathPriorityType;
enum                GtkPathType;
enum                GtkPolicyType;
enum                GtkPositionType;
enum                GtkPreviewType;
enum                GtkReliefStyle;
enum                GtkResizeMode;
enum                GtkScrollStep;
enum                GtkScrollType;
enum                GtkSelectionMode;
enum                GtkShadowType;
enum                GtkSideType;
enum                GtkStateType;
enum                GtkSubmenuDirection;
enum                GtkSubmenuPlacement;
enum                GtkToolbarStyle;
enum                GtkUpdateType;
enum                GtkVisibility;
enum                GtkWindowPosition;
enum                GtkWindowType;
enum                GtkSortType;

Description

Details

enum GtkAccelFlags

typedef enum
{
  GTK_ACCEL_VISIBLE        = 1 << 0,	/* display in GtkAccelLabel? */
  GTK_ACCEL_LOCKED         = 1 << 1,	/* is it removable? */
  GTK_ACCEL_MASK           = 0x07
} GtkAccelFlags;

enum GtkAnchorType

typedef enum
{
  GTK_ANCHOR_CENTER,
  GTK_ANCHOR_NORTH,
  GTK_ANCHOR_NORTH_WEST,
  GTK_ANCHOR_NORTH_EAST,
  GTK_ANCHOR_SOUTH,
  GTK_ANCHOR_SOUTH_WEST,
  GTK_ANCHOR_SOUTH_EAST,
  GTK_ANCHOR_WEST,
  GTK_ANCHOR_EAST,
  GTK_ANCHOR_N		= GTK_ANCHOR_NORTH,
  GTK_ANCHOR_NW		= GTK_ANCHOR_NORTH_WEST,
  GTK_ANCHOR_NE		= GTK_ANCHOR_NORTH_EAST,
  GTK_ANCHOR_S		= GTK_ANCHOR_SOUTH,
  GTK_ANCHOR_SW		= GTK_ANCHOR_SOUTH_WEST,
  GTK_ANCHOR_SE		= GTK_ANCHOR_SOUTH_EAST,
  GTK_ANCHOR_W		= GTK_ANCHOR_WEST,
  GTK_ANCHOR_E		= GTK_ANCHOR_EAST
} GtkAnchorType;

enum GtkArrowType

typedef enum
{
  GTK_ARROW_UP,
  GTK_ARROW_DOWN,
  GTK_ARROW_LEFT,
  GTK_ARROW_RIGHT,
  GTK_ARROW_NONE
} GtkArrowType;

Used to indicate the direction in which a GtkArrow should point.

GTK_ARROW_UP | Represents an upward pointing arrow.
GTK_ARROW_DOWN | Represents a downward pointing arrow.
GTK_ARROW_LEFT | Represents a left pointing arrow.
GTK_ARROW_RIGHT | Represents a right pointing arrow.
GTK_ARROW_NONE | No arrow. Since 2.10.

enum GtkAttachOptions

typedef enum
{
  GTK_EXPAND = 1 << 0,
  GTK_SHRINK = 1 << 1,
  GTK_FILL   = 1 << 2
} GtkAttachOptions;

Denotes the expansion properties that a widget will have when it (or its parent) is resized.

GTK_EXPAND | the widget should expand to take up any extra space in its container that has been allocated.
GTK_SHRINK | the widget should shrink as and when possible.
GTK_FILL | the widget should fill the space allocated to it.

enum GtkButtonBoxStyle

typedef enum
{
  GTK_BUTTONBOX_DEFAULT_STYLE,
  GTK_BUTTONBOX_SPREAD,
  GTK_BUTTONBOX_EDGE,
  GTK_BUTTONBOX_START,
  GTK_BUTTONBOX_END
} GtkButtonBoxStyle;

Used to dictate the style that a GtkButtonBox uses to layout the buttons it contains. (See also: GtkVButtonBox and GtkHButtonBox).

GTK_BUTTONBOX_DEFAULT_STYLE | Default packing.
GTK_BUTTONBOX_SPREAD | Buttons are evenly spread across the ButtonBox.
GTK_BUTTONBOX_EDGE | Buttons are placed at the edges of the ButtonBox.
GTK_BUTTONBOX_START | Buttons are grouped towards the start of box, (on the left for a HBox, or the top for a VBox).
GTK_BUTTONBOX_END | Buttons are grouped towards the end of a box, (on the right for a HBox, or the bottom for a VBox).

enum GtkCornerType

typedef enum
{
  GTK_CORNER_TOP_LEFT,
  GTK_CORNER_BOTTOM_LEFT,
  GTK_CORNER_TOP_RIGHT,
  GTK_CORNER_BOTTOM_RIGHT
} GtkCornerType;

Specifies which corner a child widget should be placed in when packed into a GtkScrolledWindow. This is effectively the opposite of where the scroll bars are placed.

GTK_CORNER_TOP_LEFT | Place the scrollbars on the right and bottom of the widget (default behaviour).
GTK_CORNER_BOTTOM_LEFT | Place the scrollbars on the top and right of the widget.
GTK_CORNER_TOP_RIGHT | Place the scrollbars on the left and bottom of the widget.
GTK_CORNER_BOTTOM_RIGHT | Place the scrollbars on the top and left of the widget.

enum GtkCurveType

typedef enum
{
  GTK_CURVE_TYPE_LINEAR,       /* linear interpolation */
  GTK_CURVE_TYPE_SPLINE,       /* spline interpolation */
  GTK_CURVE_TYPE_FREE          /* free form curve */
} GtkCurveType;

enum GtkDeleteType

typedef enum {
  GTK_DELETE_CHARS,
  GTK_DELETE_WORD_ENDS,           /* delete only the portion of the word to the
                                   * left/right of cursor if we're in the middle
                                   * of a word */
  GTK_DELETE_WORDS,
  GTK_DELETE_DISPLAY_LINES,
  GTK_DELETE_DISPLAY_LINE_ENDS,
  GTK_DELETE_PARAGRAPH_ENDS,      /* like C-k in Emacs (or its reverse) */
  GTK_DELETE_PARAGRAPHS,          /* C-k in pico, kill whole line */
  GTK_DELETE_WHITESPACE           /* M-\ in Emacs */
} GtkDeleteType;

enum GtkDirectionType

typedef enum
{
  GTK_DIR_TAB_FORWARD,
  GTK_DIR_TAB_BACKWARD,
  GTK_DIR_UP,
  GTK_DIR_DOWN,
  GTK_DIR_LEFT,
  GTK_DIR_RIGHT
} GtkDirectionType;

enum GtkExpanderStyle

typedef enum
{
  GTK_EXPANDER_COLLAPSED,
  GTK_EXPANDER_SEMI_COLLAPSED,
  GTK_EXPANDER_SEMI_EXPANDED,
  GTK_EXPANDER_EXPANDED
} GtkExpanderStyle;

Used to specify the style of the expanders drawn by a GtkTreeView.

GTK_EXPANDER_COLLAPSED | The style used for a collapsed subtree.
GTK_EXPANDER_SEMI_COLLAPSED | Intermediate style used during animation.
GTK_EXPANDER_SEMI_EXPANDED | Intermediate style used during animation.
GTK_EXPANDER_EXPANDED | The style used for an expanded subtree.

enum GtkIMPreeditStyle

typedef enum
{
  GTK_IM_PREEDIT_NOTHING,
  GTK_IM_PREEDIT_CALLBACK,
  GTK_IM_PREEDIT_NONE
} GtkIMPreeditStyle;

enum GtkIMStatusStyle

typedef enum
{
  GTK_IM_STATUS_NOTHING,
  GTK_IM_STATUS_CALLBACK,
  GTK_IM_STATUS_NONE
} GtkIMStatusStyle;

enum GtkJustification

typedef enum
{
  GTK_JUSTIFY_LEFT,
  GTK_JUSTIFY_RIGHT,
  GTK_JUSTIFY_CENTER,
  GTK_JUSTIFY_FILL
} GtkJustification;

Used for justifying the text inside a GtkLabel widget. (See also GtkAlignment).

GTK_JUSTIFY_LEFT | The text is placed at the left edge of the label.
GTK_JUSTIFY_RIGHT | The text is placed at the right edge of the label.
GTK_JUSTIFY_CENTER | The text is placed in the center of the label.
GTK_JUSTIFY_FILL | The text is placed is distributed across the label.

enum GtkMatchType

typedef enum
{
  GTK_MATCH_ALL,       /* "*A?A*" */
  GTK_MATCH_ALL_TAIL,  /* "*A?AA" */
  GTK_MATCH_HEAD,      /* "AAAA*" */
  GTK_MATCH_TAIL,      /* "*AAAA" */
  GTK_MATCH_EXACT,     /* "AAAAA" */
  GTK_MATCH_LAST
} GtkMatchType;

Warning

GtkMatchType is deprecated and should not be used in newly-written code.

enum GtkMetricType

typedef enum
{
  GTK_PIXELS,
  GTK_INCHES,
  GTK_CENTIMETERS
} GtkMetricType;

Used to indicate which metric is used by a GtkRuler.

GTK_PIXELS | Pixels.
GTK_INCHES | Inches.
GTK_CENTIMETERS | Centimeters.

enum GtkMovementStep

typedef enum
{
  GTK_MOVEMENT_LOGICAL_POSITIONS, /* move by forw/back graphemes */
  GTK_MOVEMENT_VISUAL_POSITIONS,  /* move by left/right graphemes */
  GTK_MOVEMENT_WORDS,             /* move by forward/back words */
  GTK_MOVEMENT_DISPLAY_LINES,     /* move up/down lines (wrapped lines) */
  GTK_MOVEMENT_DISPLAY_LINE_ENDS, /* move up/down lines (wrapped lines) */
  GTK_MOVEMENT_PARAGRAPHS,        /* move up/down paragraphs (newline-ended lines) */
  GTK_MOVEMENT_PARAGRAPH_ENDS,    /* move to either end of a paragraph */
  GTK_MOVEMENT_PAGES,	          /* move by pages */
  GTK_MOVEMENT_BUFFER_ENDS,       /* move to ends of the buffer */
  GTK_MOVEMENT_HORIZONTAL_PAGES   /* move horizontally by pages */
} GtkMovementStep;

enum GtkOrientation

typedef enum
{
  GTK_ORIENTATION_HORIZONTAL,
  GTK_ORIENTATION_VERTICAL
} GtkOrientation;

Represents the orientation of widgets which can be switched between horizontal and vertical orientation on the fly, like GtkToolbar.

GTK_ORIENTATION_HORIZONTAL | The widget is in horizontal orientation.
GTK_ORIENTATION_VERTICAL | The widget is in vertical orientation.

enum GtkPackType

typedef enum
{
  GTK_PACK_START,
  GTK_PACK_END
} GtkPackType;

Represents the packing location GtkBox children. (See: GtkVBox, GtkHBox, and GtkButtonBox).

GTK_PACK_START | The child is packed into the start of the box
GTK_PACK_END | The child is packed into the end of the box

enum GtkPathPriorityType

typedef enum
{
  GTK_PATH_PRIO_LOWEST      = 0,
  GTK_PATH_PRIO_GTK	    = 4,
  GTK_PATH_PRIO_APPLICATION = 8,
  GTK_PATH_PRIO_THEME       = 10,
  GTK_PATH_PRIO_RC          = 12,
  GTK_PATH_PRIO_HIGHEST     = 15
} GtkPathPriorityType;

enum GtkPathType

typedef enum
{
  GTK_PATH_WIDGET,
  GTK_PATH_WIDGET_CLASS,
  GTK_PATH_CLASS
} GtkPathType;

enum GtkPolicyType

typedef enum
{
  GTK_POLICY_ALWAYS,
  GTK_POLICY_AUTOMATIC,
  GTK_POLICY_NEVER
} GtkPolicyType;

Determines when a scroll bar will be visible.

GTK_POLICY_ALWAYS | The scrollbar is always visible.
GTK_POLICY_AUTOMATIC | The scrollbar will appear and disappear as necessary. For example, when all of a GtkCList can not be seen.
GTK_POLICY_NEVER | The scrollbar will never appear.

enum GtkPositionType

typedef enum
{
  GTK_POS_LEFT,
  GTK_POS_RIGHT,
  GTK_POS_TOP,
  GTK_POS_BOTTOM
} GtkPositionType;

Describes which edge of a widget a certain feature is positioned at, e.g. the tabs of a GtkNotebook, the handle of a GtkHandleBox or the label of a GtkScale.

GTK_POS_LEFT | The feature is at the left edge.
GTK_POS_RIGHT | The feature is at the right edge.
GTK_POS_TOP | The feature is at the top edge.
GTK_POS_BOTTOM | The feature is at the bottom edge.

enum GtkPreviewType

typedef enum
{
  GTK_PREVIEW_COLOR,
  GTK_PREVIEW_GRAYSCALE
} GtkPreviewType;

Warning

GtkPreviewType is deprecated and should not be used in newly-written code.

An enumeration which describes whether a preview contains grayscale or red-green-blue data.

GTK_PREVIEW_COLOR | the preview contains red-green-blue data.
GTK_PREVIEW_GRAYSCALE | The preview contains grayscale data.

enum GtkReliefStyle

typedef enum
{
  GTK_RELIEF_NORMAL,
  GTK_RELIEF_HALF,
  GTK_RELIEF_NONE
} GtkReliefStyle;

Indicated the relief to be drawn around a GtkButton.

GTK_RELIEF_NORMAL | Draw a normal relief.
GTK_RELIEF_HALF | A half relief.
GTK_RELIEF_NONE | No relief.

enum GtkResizeMode

typedef enum
{
  GTK_RESIZE_PARENT,		/* Pass resize request to the parent */
  GTK_RESIZE_QUEUE,		/* Queue resizes on this widget */
  GTK_RESIZE_IMMEDIATE		/* Perform the resizes now */
} GtkResizeMode;

GTK_RESIZE_PARENT |
GTK_RESIZE_QUEUE |
GTK_RESIZE_IMMEDIATE | Deprecated.

enum GtkScrollStep

typedef enum
{
  GTK_SCROLL_STEPS,
  GTK_SCROLL_PAGES,
  GTK_SCROLL_ENDS,
  GTK_SCROLL_HORIZONTAL_STEPS,
  GTK_SCROLL_HORIZONTAL_PAGES,
  GTK_SCROLL_HORIZONTAL_ENDS
} GtkScrollStep;

enum GtkScrollType

typedef enum
{
  GTK_SCROLL_NONE,
  GTK_SCROLL_JUMP,
  GTK_SCROLL_STEP_BACKWARD,
  GTK_SCROLL_STEP_FORWARD,
  GTK_SCROLL_PAGE_BACKWARD,
  GTK_SCROLL_PAGE_FORWARD,
  GTK_SCROLL_STEP_UP,
  GTK_SCROLL_STEP_DOWN,
  GTK_SCROLL_PAGE_UP,
  GTK_SCROLL_PAGE_DOWN,
  GTK_SCROLL_STEP_LEFT,
  GTK_SCROLL_STEP_RIGHT,
  GTK_SCROLL_PAGE_LEFT,
  GTK_SCROLL_PAGE_RIGHT,
  GTK_SCROLL_START,
  GTK_SCROLL_END
} GtkScrollType;

enum GtkSelectionMode

typedef enum
{
  GTK_SELECTION_NONE,                             /* Nothing can be selected */
  GTK_SELECTION_SINGLE,
  GTK_SELECTION_BROWSE,
  GTK_SELECTION_MULTIPLE,
  GTK_SELECTION_EXTENDED = GTK_SELECTION_MULTIPLE /* Deprecated */
} GtkSelectionMode;

Used to control what selections users are allowed to make.

GTK_SELECTION_NONE | No selection is possible.
GTK_SELECTION_SINGLE | Zero or one element may be selected.
GTK_SELECTION_BROWSE | Exactly one element is selected. In some circumstances, such as initially or during a search operation, it's possible for no element to be selected with GTK_SELECTION_BROWSE. What is really enforced is that the user can't deselect a currently selected element except by selecting another element.
GTK_SELECTION_MULTIPLE | Any number of elements may be selected. Clicks toggle the state of an item. Any number of elements may be selected. The Ctrl key may be used to enlarge the selection, and Shift key to select between the focus and the child pointed to. Some widgets may also allow Click-drag to select a range of elements.
GTK_SELECTION_EXTENDED | Deprecated, behaves identical to GTK_SELECTION_MULTIPLE.

enum GtkShadowType

typedef enum
{
  GTK_SHADOW_NONE,
  GTK_SHADOW_IN,
  GTK_SHADOW_OUT,
  GTK_SHADOW_ETCHED_IN,
  GTK_SHADOW_ETCHED_OUT
} GtkShadowType;

Used to change the appearance of an outline typically provided by a GtkFrame.

GTK_SHADOW_NONE | No outline.
GTK_SHADOW_IN | The outline is bevelled inwards.
GTK_SHADOW_OUT | The outline is bevelled outwards like a button.
GTK_SHADOW_ETCHED_IN | The outline has a sunken 3d appearance.
GTK_SHADOW_ETCHED_OUT | The outline has a raised 3d appearance

enum GtkSideType

typedef enum
{
  GTK_SIDE_TOP,
  GTK_SIDE_BOTTOM,
  GTK_SIDE_LEFT,
  GTK_SIDE_RIGHT
} GtkSideType;

Warning

GtkSideType is deprecated and should not be used in newly-written code.

enum GtkStateType

typedef enum
{
  GTK_STATE_NORMAL,
  GTK_STATE_ACTIVE,
  GTK_STATE_PRELIGHT,
  GTK_STATE_SELECTED,
  GTK_STATE_INSENSITIVE
} GtkStateType;

This type indicates the current state of a widget; the state determines how the widget is drawn. The GtkStateType enumeration is also used to identify different colors in a GtkStyle for drawing, so states can be used for subparts of a widget as well as entire widgets.

GTK_STATE_NORMAL | State during normal operation.
GTK_STATE_ACTIVE | State of a currently active widget, such as a depressed button.
GTK_STATE_PRELIGHT | State indicating that the mouse pointer is over the widget and the widget will respond to mouse clicks.
GTK_STATE_SELECTED | State of a selected item, such the selected row in a list.
GTK_STATE_INSENSITIVE | State indicating that the widget is unresponsive to user actions.

enum GtkSubmenuDirection

typedef enum
{
  GTK_DIRECTION_LEFT,
  GTK_DIRECTION_RIGHT
} GtkSubmenuDirection;

Warning

GtkSubmenuDirection is deprecated and should not be used in newly-written code.

Indicates the direction a sub-menu will appear.

GTK_DIRECTION_LEFT | A sub-menu will appear
GTK_DIRECTION_RIGHT |

enum GtkSubmenuPlacement

typedef enum
{
  GTK_TOP_BOTTOM,
  GTK_LEFT_RIGHT
} GtkSubmenuPlacement;

Warning

GtkSubmenuPlacement is deprecated and should not be used in newly-written code.

enum GtkToolbarStyle

typedef enum
{
  GTK_TOOLBAR_ICONS,
  GTK_TOOLBAR_TEXT,
  GTK_TOOLBAR_BOTH,
  GTK_TOOLBAR_BOTH_HORIZ
} GtkToolbarStyle;

Used to customize the appearance of a GtkToolbar. Note that setting the toolbar style overrides the user's preferences for the default toolbar style. Note that if the button has only a label set and GTK_TOOLBAR_ICONS is used, the label will be visible, and vice versa.

GTK_TOOLBAR_ICONS | Buttons display only icons in the toolbar.
GTK_TOOLBAR_TEXT | Buttons display only text labels in the toolbar.
GTK_TOOLBAR_BOTH | Buttons display text and icons in the toolbar.
GTK_TOOLBAR_BOTH_HORIZ | Buttons display icons and text alongside each other, rather than vertically stacked

enum GtkUpdateType

typedef enum
{
  GTK_UPDATE_CONTINUOUS,
  GTK_UPDATE_DISCONTINUOUS,
  GTK_UPDATE_DELAYED
} GtkUpdateType;

enum GtkVisibility

typedef enum
{
  GTK_VISIBILITY_NONE,
  GTK_VISIBILITY_PARTIAL,
  GTK_VISIBILITY_FULL
} GtkVisibility;

Used by GtkCList and GtkCTree to indicate whether a row is visible.

GTK_VISIBILITY_NONE | The row is not visible.
GTK_VISIBILITY_PARTIAL | The row is partially visible.
GTK_VISIBILITY_FULL | The row is fully visible.

enum GtkWindowPosition

typedef enum
{
  GTK_WIN_POS_NONE,
  GTK_WIN_POS_CENTER,
  GTK_WIN_POS_MOUSE,
  GTK_WIN_POS_CENTER_ALWAYS,
  GTK_WIN_POS_CENTER_ON_PARENT
} GtkWindowPosition;

Window placement can be influenced using this enumeration.

GTK_WIN_POS_NONE | No influence is made on placement.
GTK_WIN_POS_CENTER | Windows should be placed in the center of the screen.
GTK_WIN_POS_MOUSE | Windows should be placed at the current mouse position.
GTK_WIN_POS_CENTER_ALWAYS | Keep window centered as it changes size, etc.
GTK_WIN_POS_CENTER_ON_PARENT | Center the window on its transient parent (see gtk_window_set_transient_for()).

enum GtkWindowType

typedef enum
{
  GTK_WINDOW_TOPLEVEL,
  GTK_WINDOW_POPUP
} GtkWindowType;

A GtkWindow can be one of these types. Most things you'd consider a "window" should have type GTK_WINDOW_TOPLEVEL; windows with this type are managed by the window manager and have a frame by default (call gtk_window_set_decorated() to toggle the frame). Windows with type GTK_WINDOW_POPUP are ignored by the window manager; window manager keybindings won't work on them, the window manager won't decorate the window with a frame, many GTK+ features that rely on the window manager will not work (e.g. resize grips and maximization/minimization). GTK_WINDOW_POPUP is used to implement widgets such as GtkMenu or tooltips that you normally don't think of as windows per se. Nearly all windows should be GTK_WINDOW_TOPLEVEL. In particular, do not use GTK_WINDOW_POPUP just to turn off the window borders; use gtk_window_set_decorated() for that.

GTK_WINDOW_TOPLEVEL | A regular window, such as a dialog.
GTK_WINDOW_POPUP | A special window such as a tooltip.

enum GtkSortType

typedef enum
{
  GTK_SORT_ASCENDING,
  GTK_SORT_DESCENDING
} GtkSortType;

Determines the direction of a sort.

GTK_SORT_ASCENDING | Sorting is in ascending order.
GTK_SORT_DESCENDING | Sorting is in descending order.


Stock Items

Stock Items — Prebuilt common menu/toolbar items and corresponding icons

Synopsis

#include <gtk/gtk.h>

                    GtkStockItem;
void                gtk_stock_add                       (const GtkStockItem *items,
                                                         guint n_items);
void                gtk_stock_add_static                (const GtkStockItem *items,
                                                         guint n_items);
GtkStockItem*       gtk_stock_item_copy                 (const GtkStockItem *item);
void                gtk_stock_item_free                 (GtkStockItem *item);
GSList*             gtk_stock_list_ids                  (void);
gboolean            gtk_stock_lookup                    (const gchar *stock_id,
                                                         GtkStockItem *item);
void                gtk_stock_set_translate_func        (const gchar *domain,
                                                         GtkTranslateFunc func,
                                                         gpointer data,
                                                         GtkDestroyNotify notify);

#define             GTK_STOCK_ABOUT
#define             GTK_STOCK_ADD
#define             GTK_STOCK_APPLY
#define             GTK_STOCK_BOLD
#define             GTK_STOCK_CANCEL
#define             GTK_STOCK_CDROM
#define             GTK_STOCK_CLEAR
#define             GTK_STOCK_CLOSE
#define             GTK_STOCK_COLOR_PICKER
#define             GTK_STOCK_CONVERT
#define             GTK_STOCK_CONNECT
#define             GTK_STOCK_COPY
#define             GTK_STOCK_CUT
#define             GTK_STOCK_DELETE
#define             GTK_STOCK_DIALOG_AUTHENTICATION
#define             GTK_STOCK_DIALOG_ERROR
#define             GTK_STOCK_DIALOG_INFO
#define             GTK_STOCK_DIALOG_QUESTION
#define             GTK_STOCK_DIALOG_WARNING
#define             GTK_STOCK_DIRECTORY
#define             GTK_STOCK_DISCONNECT
#define             GTK_STOCK_DND
#define             GTK_STOCK_DND_MULTIPLE
#define             GTK_STOCK_EDIT
#define             GTK_STOCK_EXECUTE
#define             GTK_STOCK_FILE
#define             GTK_STOCK_FIND
#define             GTK_STOCK_FIND_AND_REPLACE
#define             GTK_STOCK_FLOPPY
#define             GTK_STOCK_FULLSCREEN
#define             GTK_STOCK_GOTO_BOTTOM
#define             GTK_STOCK_GOTO_FIRST
#define             GTK_STOCK_GOTO_LAST
#define             GTK_STOCK_GOTO_TOP
#define             GTK_STOCK_GO_BACK
#define             GTK_STOCK_GO_DOWN
#define             GTK_STOCK_GO_FORWARD
#define             GTK_STOCK_GO_UP
#define             GTK_STOCK_HARDDISK
#define             GTK_STOCK_HELP
#define             GTK_STOCK_HOME
#define             GTK_STOCK_INDENT
#define             GTK_STOCK_INDEX
#define             GTK_STOCK_INFO
#define             GTK_STOCK_ITALIC
#define             GTK_STOCK_JUMP_TO
#define             GTK_STOCK_JUSTIFY_CENTER
#define             GTK_STOCK_JUSTIFY_FILL
#define             GTK_STOCK_JUSTIFY_LEFT
#define             GTK_STOCK_JUSTIFY_RIGHT
#define             GTK_STOCK_LEAVE_FULLSCREEN
#define             GTK_STOCK_MEDIA_FORWARD
#define             GTK_STOCK_MEDIA_NEXT
#define             GTK_STOCK_MEDIA_PAUSE
#define             GTK_STOCK_MEDIA_PLAY
#define             GTK_STOCK_MEDIA_PREVIOUS
#define             GTK_STOCK_MEDIA_RECORD
#define             GTK_STOCK_MEDIA_REWIND
#define             GTK_STOCK_MEDIA_STOP
#define             GTK_STOCK_MISSING_IMAGE
#define             GTK_STOCK_NETWORK
#define             GTK_STOCK_NEW
#define             GTK_STOCK_NO
#define             GTK_STOCK_OK
#define             GTK_STOCK_OPEN
#define             GTK_STOCK_ORIENTATION_LANDSCAPE
#define             GTK_STOCK_ORIENTATION_PORTRAIT
#define             GTK_STOCK_ORIENTATION_REVERSE_LANDSCAPE
#define             GTK_STOCK_ORIENTATION_REVERSE_PORTRAIT
#define             GTK_STOCK_PASTE
#define             GTK_STOCK_PREFERENCES
#define             GTK_STOCK_PRINT
#define             GTK_STOCK_PRINT_PREVIEW
#define             GTK_STOCK_PROPERTIES
#define             GTK_STOCK_QUIT
#define             GTK_STOCK_REDO
#define             GTK_STOCK_REFRESH
#define             GTK_STOCK_REMOVE
#define             GTK_STOCK_REVERT_TO_SAVED
#define             GTK_STOCK_SAVE
#define             GTK_STOCK_SAVE_AS
#define             GTK_STOCK_SELECT_ALL
#define             GTK_STOCK_SELECT_COLOR
#define             GTK_STOCK_SELECT_FONT
#define             GTK_STOCK_SORT_ASCENDING
#define             GTK_STOCK_SORT_DESCENDING
#define             GTK_STOCK_SPELL_CHECK
#define             GTK_STOCK_STOP
#define             GTK_STOCK_STRIKETHROUGH
#define             GTK_STOCK_UNDELETE
#define             GTK_STOCK_UNDERLINE
#define             GTK_STOCK_UNDO
#define             GTK_STOCK_UNINDENT
#define             GTK_STOCK_YES
#define             GTK_STOCK_ZOOM_100
#define             GTK_STOCK_ZOOM_FIT
#define             GTK_STOCK_ZOOM_IN
#define             GTK_STOCK_ZOOM_OUT

Description

Stock items represent commonly-used menu or toolbar items such as "Open" or "Exit". Each stock item is identified by a stock ID; stock IDs are just strings, but macros such as GTK_STOCK_OPEN are provided to avoid typing mistakes in the strings. Applications can register their own stock items in addition to those built-in to GTK+.

Each stock ID can be associated with a GtkStockItem, which contains the user-visible label, keyboard accelerator, and translation domain of the menu or toolbar item; and/or with an icon stored in a GtkIconFactory. See GtkIconFactory for more information on stock icons. The connection between a GtkStockItem and stock icons is purely conventional (by virtue of using the same stock ID); it's possible to register a stock item but no icon, and vice versa. Stock icons may have a RTL variant which gets used for right-to-left locales.

Details

GtkStockItem

typedef struct {
  gchar *stock_id;
  gchar *label;
  GdkModifierType modifier;
  guint keyval;
  gchar *translation_domain;
} GtkStockItem;

gtk_stock_add ()

void                gtk_stock_add                       (const GtkStockItem *items,
                                                         guint n_items);

Registers each of the stock items in items. If an item already exists with the same stock ID as one of the items, the old item gets replaced. The stock items are copied, so GTK+ does not hold any pointer into items and items can be freed. Use gtk_stock_add_static() if items is persistent and GTK+ need not copy the array.

items : | a GtkStockItem or array of items
n_items : | number of GtkStockItem in items

gtk_stock_add_static ()

void                gtk_stock_add_static                (const GtkStockItem *items,
                                                         guint n_items);

Same as gtk_stock_add(), but doesn't copy items, so items must persist until application exit.

items : | a GtkStockItem or array of GtkStockItem
n_items : | number of items

gtk_stock_item_copy ()

GtkStockItem*       gtk_stock_item_copy                 (const GtkStockItem *item);

Copies a stock item, mostly useful for language bindings and not in applications.

item : | a GtkStockItem
Returns : | a new GtkStockItem

gtk_stock_item_free ()

void                gtk_stock_item_free                 (GtkStockItem *item);

Frees a stock item allocated on the heap, such as one returned by gtk_stock_item_copy(). Also frees the fields inside the stock item, if they are not NULL.

item : a GtkStockItem

gtk_stock_list_ids ()

GSList*             gtk_stock_list_ids                  (void);

Retrieves a list of all known stock IDs added to a GtkIconFactory or registered with gtk_stock_add(). The list must be freed with g_slist_free(), and each string in the list must be freed with g_free().

Returns : a list of known stock IDs

gtk_stock_lookup ()

gboolean            gtk_stock_lookup                    (const gchar *stock_id,
                                                         GtkStockItem *item);

Fills item with the registered values for stock_id, returning TRUE if stock_id was known.

stock_id : | a stock item name
item : | stock item to initialize with values
Returns : | TRUE if item was initialized

gtk_stock_set_translate_func ()

void                gtk_stock_set_translate_func        (const gchar *domain,
                                                         GtkTranslateFunc func,
                                                         gpointer data,
                                                         GtkDestroyNotify notify);

Sets a function to be used for translating the label of a stock item.

If no function is registered for a translation domain, dgettext() is used.

domain : | the translation domain for which func shall be used
func : | a GtkTranslateFunc
data : | data to pass to func
notify : | a GtkDestroyNotify that is called when data is no longer needed

Since 2.8

GTK_STOCK_ABOUT

#define GTK_STOCK_ABOUT            "gtk-about"

The "About" item.

Since 2.6

GTK_STOCK_ADD

#define GTK_STOCK_ADD              "gtk-add"

The "Add" item.

GTK_STOCK_APPLY

#define GTK_STOCK_APPLY            "gtk-apply"

The "Apply" item.

GTK_STOCK_BOLD

#define GTK_STOCK_BOLD             "gtk-bold"

The "Bold" item.

GTK_STOCK_CANCEL

#define GTK_STOCK_CANCEL           "gtk-cancel"

The "Cancel" item.

GTK_STOCK_CDROM

#define GTK_STOCK_CDROM            "gtk-cdrom"

The "CD-Rom" item.

GTK_STOCK_CLEAR

#define GTK_STOCK_CLEAR            "gtk-clear"

The "Clear" item.

GTK_STOCK_CLOSE

#define GTK_STOCK_CLOSE            "gtk-close"

The "Close" item.

GTK_STOCK_COLOR_PICKER

#define GTK_STOCK_COLOR_PICKER     "gtk-color-picker"

The "Color Picker" item.

Since 2.2

GTK_STOCK_CONVERT

#define GTK_STOCK_CONVERT          "gtk-convert"

The "Convert" item.

GTK_STOCK_CONNECT

#define GTK_STOCK_CONNECT          "gtk-connect"

The "Connect" icon.

Since 2.6

GTK_STOCK_COPY

#define GTK_STOCK_COPY             "gtk-copy"

The "Copy" item.

GTK_STOCK_CUT

#define GTK_STOCK_CUT              "gtk-cut"

The "Cut" item.

GTK_STOCK_DELETE

#define GTK_STOCK_DELETE           "gtk-delete"

The "Delete" item.

GTK_STOCK_DIALOG_AUTHENTICATION

#define             GTK_STOCK_DIALOG_AUTHENTICATION

The "Authentication" item.

Since 2.4

GTK_STOCK_DIALOG_ERROR

#define GTK_STOCK_DIALOG_ERROR     "gtk-dialog-error"

The "Error" item.

GTK_STOCK_DIALOG_INFO

#define GTK_STOCK_DIALOG_INFO      "gtk-dialog-info"

The "Information" item.

GTK_STOCK_DIALOG_QUESTION

#define GTK_STOCK_DIALOG_QUESTION  "gtk-dialog-question"

The "Question" item.

GTK_STOCK_DIALOG_WARNING

#define GTK_STOCK_DIALOG_WARNING   "gtk-dialog-warning"

The "Warning" item.

GTK_STOCK_DIRECTORY

#define GTK_STOCK_DIRECTORY        "gtk-directory"

The "Directory" icon.

Since 2.6

GTK_STOCK_DISCONNECT

#define GTK_STOCK_DISCONNECT       "gtk-disconnect"

The "Disconnect" icon.

Since 2.6

GTK_STOCK_DND

#define GTK_STOCK_DND              "gtk-dnd"

The "Drag-And-Drop" icon.

GTK_STOCK_DND_MULTIPLE

#define GTK_STOCK_DND_MULTIPLE     "gtk-dnd-multiple"

The "Drag-And-Drop multiple" icon.

GTK_STOCK_EDIT

#define GTK_STOCK_EDIT             "gtk-edit"

The "Edit" item.

Since 2.6

GTK_STOCK_EXECUTE

#define GTK_STOCK_EXECUTE          "gtk-execute"

The "Execute" item.

GTK_STOCK_FILE

#define GTK_STOCK_FILE             "gtk-file"

The "File" icon.

Since 2.6

GTK_STOCK_FIND

#define GTK_STOCK_FIND             "gtk-find"

The "Find" item.

GTK_STOCK_FIND_AND_REPLACE

#define GTK_STOCK_FIND_AND_REPLACE "gtk-find-and-replace"

The "Find and Replace" item.

GTK_STOCK_FLOPPY

#define GTK_STOCK_FLOPPY           "gtk-floppy"

The "Floppy" item.

GTK_STOCK_FULLSCREEN

#define GTK_STOCK_FULLSCREEN       "gtk-fullscreen"

The "Fullscreen" item.

Since 2.8

GTK_STOCK_GOTO_BOTTOM

#define GTK_STOCK_GOTO_BOTTOM      "gtk-goto-bottom"

The "Bottom" item.

GTK_STOCK_GOTO_FIRST

#define GTK_STOCK_GOTO_FIRST       "gtk-goto-first"

The "First" item. RTL variant

GTK_STOCK_GOTO_LAST

#define GTK_STOCK_GOTO_LAST        "gtk-goto-last"

The "Last" item. RTL variant

GTK_STOCK_GOTO_TOP

#define GTK_STOCK_GOTO_TOP         "gtk-goto-top"

The "Top" item.

GTK_STOCK_GO_BACK

#define GTK_STOCK_GO_BACK          "gtk-go-back"

The "Back" item. RTL variant

GTK_STOCK_GO_DOWN

#define GTK_STOCK_GO_DOWN          "gtk-go-down"

The "Down" item.

GTK_STOCK_GO_FORWARD

#define GTK_STOCK_GO_FORWARD       "gtk-go-forward"

The "Forward" item. RTL variant

GTK_STOCK_GO_UP

#define GTK_STOCK_GO_UP            "gtk-go-up"

The "Up" item.

GTK_STOCK_HARDDISK

#define GTK_STOCK_HARDDISK         "gtk-harddisk"

The "Harddisk" item.

Since 2.4

GTK_STOCK_HELP

#define GTK_STOCK_HELP             "gtk-help"

The "Help" item.

GTK_STOCK_HOME

#define GTK_STOCK_HOME             "gtk-home"

The "Home" item.

GTK_STOCK_INDENT

#define GTK_STOCK_INDENT           "gtk-indent"

The "Indent" item. RTL variant

Since 2.4

GTK_STOCK_INDEX

#define GTK_STOCK_INDEX            "gtk-index"

The "Index" item.

GTK_STOCK_INFO

#define GTK_STOCK_INFO             "gtk-info"

The "Info" item.

Since 2.8

GTK_STOCK_ITALIC

#define GTK_STOCK_ITALIC           "gtk-italic"

The "Italic" item.

GTK_STOCK_JUMP_TO

#define GTK_STOCK_JUMP_TO          "gtk-jump-to"

The "Jump to" item. RTL-variant

GTK_STOCK_JUSTIFY_CENTER

#define GTK_STOCK_JUSTIFY_CENTER   "gtk-justify-center"

The "Center" item.

GTK_STOCK_JUSTIFY_FILL

#define GTK_STOCK_JUSTIFY_FILL     "gtk-justify-fill"

The "Fill" item.

GTK_STOCK_JUSTIFY_LEFT

#define GTK_STOCK_JUSTIFY_LEFT     "gtk-justify-left"

The "Left" item.

GTK_STOCK_JUSTIFY_RIGHT

#define GTK_STOCK_JUSTIFY_RIGHT    "gtk-justify-right"

The "Right" item.

GTK_STOCK_LEAVE_FULLSCREEN

#define GTK_STOCK_LEAVE_FULLSCREEN "gtk-leave-fullscreen"

The "Leave Fullscreen" item.

Since 2.8

GTK_STOCK_MEDIA_FORWARD

#define GTK_STOCK_MEDIA_FORWARD    "gtk-media-forward"

The "Media Forward" item. RTL variant

Since 2.6

GTK_STOCK_MEDIA_NEXT

#define GTK_STOCK_MEDIA_NEXT       "gtk-media-next"

The "Media Next" item. RTL variant

Since 2.6

GTK_STOCK_MEDIA_PAUSE

#define GTK_STOCK_MEDIA_PAUSE      "gtk-media-pause"

The "Media Pause" item.

Since 2.6

GTK_STOCK_MEDIA_PLAY

#define GTK_STOCK_MEDIA_PLAY       "gtk-media-play"

The "Media Play" item. RTL variant

Since 2.6

GTK_STOCK_MEDIA_PREVIOUS

#define GTK_STOCK_MEDIA_PREVIOUS   "gtk-media-previous"

The "Media Previous" item. RTL variant

Since 2.6

GTK_STOCK_MEDIA_RECORD

#define GTK_STOCK_MEDIA_RECORD     "gtk-media-record"

The "Media Record" item.

Since 2.6

GTK_STOCK_MEDIA_REWIND

#define GTK_STOCK_MEDIA_REWIND     "gtk-media-rewind"

The "Media Rewind" item. RTL variant

Since 2.6

GTK_STOCK_MEDIA_STOP

#define GTK_STOCK_MEDIA_STOP       "gtk-media-stop"

The "Media Stop" item.

Since 2.6

GTK_STOCK_MISSING_IMAGE

#define GTK_STOCK_MISSING_IMAGE    "gtk-missing-image"

The "Missing image" icon.

GTK_STOCK_NETWORK

#define GTK_STOCK_NETWORK          "gtk-network"

The "Network" item.

Since 2.4

GTK_STOCK_NEW

#define GTK_STOCK_NEW              "gtk-new"

The "New" item.

GTK_STOCK_NO

#define GTK_STOCK_NO               "gtk-no"

The "No" item.

GTK_STOCK_OK

#define GTK_STOCK_OK               "gtk-ok"

The "OK" item.

GTK_STOCK_OPEN

#define GTK_STOCK_OPEN             "gtk-open"

The "Open" item.

GTK_STOCK_ORIENTATION_LANDSCAPE

#define GTK_STOCK_ORIENTATION_LANDSCAPE "gtk-orientation-landscape"

The "Landscape Orientation" item.

Since 2.10

GTK_STOCK_ORIENTATION_PORTRAIT

#define GTK_STOCK_ORIENTATION_PORTRAIT "gtk-orientation-portrait"

The "Portrait Orientation" item.

Since 2.10

GTK_STOCK_ORIENTATION_REVERSE_LANDSCAPE

#define GTK_STOCK_ORIENTATION_REVERSE_LANDSCAPE "gtk-orientation-reverse-landscape"

The "Reverse Landscape Orientation" item.

Since 2.10

GTK_STOCK_ORIENTATION_REVERSE_PORTRAIT

#define GTK_STOCK_ORIENTATION_REVERSE_PORTRAIT "gtk-orientation-reverse-portrait"

The "Reverse Portrait Orientation" item.

Since 2.10

GTK_STOCK_PASTE

#define GTK_STOCK_PASTE            "gtk-paste"

The "Paste" item.

GTK_STOCK_PREFERENCES

#define GTK_STOCK_PREFERENCES      "gtk-preferences"

The "Preferences" item.

GTK_STOCK_PRINT

#define GTK_STOCK_PRINT            "gtk-print"

The "Print" item.

GTK_STOCK_PRINT_PREVIEW

#define GTK_STOCK_PRINT_PREVIEW    "gtk-print-preview"

The "Print Preview" item.

GTK_STOCK_PROPERTIES

#define GTK_STOCK_PROPERTIES       "gtk-properties"

The "Properties" item.

GTK_STOCK_QUIT

#define GTK_STOCK_QUIT             "gtk-quit"

The "Quit" item.

GTK_STOCK_REDO

#define GTK_STOCK_REDO             "gtk-redo"

The "Redo" item. RTL variant

GTK_STOCK_REFRESH

#define GTK_STOCK_REFRESH          "gtk-refresh"

The "Refresh" item.

GTK_STOCK_REMOVE

#define GTK_STOCK_REMOVE           "gtk-remove"

The "Remove" item.

GTK_STOCK_REVERT_TO_SAVED

#define GTK_STOCK_REVERT_TO_SAVED  "gtk-revert-to-saved"

The "Revert" item. RTL variant

GTK_STOCK_SAVE

#define GTK_STOCK_SAVE             "gtk-save"

The "Save" item.

GTK_STOCK_SAVE_AS

#define GTK_STOCK_SAVE_AS          "gtk-save-as"

The "Save As" item.

GTK_STOCK_SELECT_ALL

#define GTK_STOCK_SELECT_ALL       "gtk-select-all"

The "Select All" item.

Since 2.10

GTK_STOCK_SELECT_COLOR

#define GTK_STOCK_SELECT_COLOR     "gtk-select-color"

The "Color" item.

GTK_STOCK_SELECT_FONT

#define GTK_STOCK_SELECT_FONT      "gtk-select-font"

The "Font" item.

GTK_STOCK_SORT_ASCENDING

#define GTK_STOCK_SORT_ASCENDING   "gtk-sort-ascending"

The "Ascending" item.

GTK_STOCK_SORT_DESCENDING

#define GTK_STOCK_SORT_DESCENDING  "gtk-sort-descending"

The "Descending" item.

GTK_STOCK_SPELL_CHECK

#define GTK_STOCK_SPELL_CHECK      "gtk-spell-check"

The "Spell Check" item.

GTK_STOCK_STOP

#define GTK_STOCK_STOP             "gtk-stop"

The "Stop" item.

GTK_STOCK_STRIKETHROUGH

#define GTK_STOCK_STRIKETHROUGH    "gtk-strikethrough"

The "Strikethrough" item.

GTK_STOCK_UNDELETE

#define GTK_STOCK_UNDELETE         "gtk-undelete"

The "Undelete" item. RTL variant

GTK_STOCK_UNDERLINE

#define GTK_STOCK_UNDERLINE        "gtk-underline"

The "Underline" item.

GTK_STOCK_UNDO

#define GTK_STOCK_UNDO             "gtk-undo"

The "Undo" item. RTL variant

GTK_STOCK_UNINDENT

#define GTK_STOCK_UNINDENT         "gtk-unindent"

The "Unindent" item. RTL variant

Since 2.4

GTK_STOCK_YES

#define GTK_STOCK_YES              "gtk-yes"

The "Yes" item.

GTK_STOCK_ZOOM_100

#define GTK_STOCK_ZOOM_100         "gtk-zoom-100"

The "Zoom 100%" item.

GTK_STOCK_ZOOM_FIT

#define GTK_STOCK_ZOOM_FIT         "gtk-zoom-fit"

The "Zoom to Fit" item.

GTK_STOCK_ZOOM_IN

#define GTK_STOCK_ZOOM_IN          "gtk-zoom-in"

The "Zoom In" item.

GTK_STOCK_ZOOM_OUT

#define GTK_STOCK_ZOOM_OUT         "gtk-zoom-out"

The "Zoom Out" item.


Themeable Stock Images

Themeable Stock Images — Manipulating stock icons

Synopsis

#include <gtk/gtk.h>

                    GtkIconSource;
                    GtkIconFactory;
                    GtkIconSet;
enum                GtkIconSize;
GtkIconSource*      gtk_icon_source_copy                (const GtkIconSource *source);
void                gtk_icon_source_free                (GtkIconSource *source);
void                gtk_icon_factory_add                (GtkIconFactory *factory,
                                                         const gchar *stock_id,
                                                         GtkIconSet *icon_set);
void                gtk_icon_factory_add_default        (GtkIconFactory *factory);
GtkIconSet*         gtk_icon_factory_lookup             (GtkIconFactory *factory,
                                                         const gchar *stock_id);
GtkIconSet*         gtk_icon_factory_lookup_default     (const gchar *stock_id);
GtkIconFactory*     gtk_icon_factory_new                (void);
void                gtk_icon_factory_remove_default     (GtkIconFactory *factory);
void                gtk_icon_set_add_source             (GtkIconSet *icon_set,
                                                         const GtkIconSource *source);
GtkIconSet*         gtk_icon_set_copy                   (GtkIconSet *icon_set);
GtkIconSet*         gtk_icon_set_new                    (void);
GtkIconSet*         gtk_icon_set_new_from_pixbuf        (GdkPixbuf *pixbuf);
GtkIconSet*         gtk_icon_set_ref                    (GtkIconSet *icon_set);
GdkPixbuf*          gtk_icon_set_render_icon            (GtkIconSet *icon_set,
                                                         GtkStyle *style,
                                                         GtkTextDirection direction,
                                                         GtkStateType state,
                                                         GtkIconSize size,
                                                         GtkWidget *widget,
                                                         const char *detail);
void                gtk_icon_set_unref                  (GtkIconSet *icon_set);
gboolean            gtk_icon_size_lookup                (GtkIconSize size,
                                                         gint *width,
                                                         gint *height);
gboolean            gtk_icon_size_lookup_for_settings   (GtkSettings *settings,
                                                         GtkIconSize size,
                                                         gint *width,
                                                         gint *height);
GtkIconSize         gtk_icon_size_register              (const gchar *name,
                                                         gint width,
                                                         gint height);
void                gtk_icon_size_register_alias        (const gchar *alias,
                                                         GtkIconSize target);
GtkIconSize         gtk_icon_size_from_name             (const gchar *name);
const gchar*        gtk_icon_size_get_name              (GtkIconSize size);
void                gtk_icon_set_get_sizes              (GtkIconSet *icon_set,
                                                         GtkIconSize **sizes,
                                                         gint *n_sizes);
GtkTextDirection    gtk_icon_source_get_direction       (const GtkIconSource *source);
gboolean            gtk_icon_source_get_direction_wildcarded
                                                        (const GtkIconSource *source);
const gchar*        gtk_icon_source_get_filename        (const GtkIconSource *source);
GdkPixbuf*          gtk_icon_source_get_pixbuf          (const GtkIconSource *source);
const gchar*        gtk_icon_source_get_icon_name       (const GtkIconSource *source);
GtkIconSize         gtk_icon_source_get_size            (const GtkIconSource *source);
gboolean            gtk_icon_source_get_size_wildcarded (const GtkIconSource *source);
GtkStateType        gtk_icon_source_get_state           (const GtkIconSource *source);
gboolean            gtk_icon_source_get_state_wildcarded
                                                        (const GtkIconSource *source);
GtkIconSource*      gtk_icon_source_new                 (void);
void                gtk_icon_source_set_direction       (GtkIconSource *source,
                                                         GtkTextDirection direction);
void                gtk_icon_source_set_direction_wildcarded
                                                        (GtkIconSource *source,
                                                         gboolean setting);
void                gtk_icon_source_set_filename        (GtkIconSource *source,
                                                         const gchar *filename);
void                gtk_icon_source_set_pixbuf          (GtkIconSource *source,
                                                         GdkPixbuf *pixbuf);
void                gtk_icon_source_set_icon_name       (GtkIconSource *source,
                                                         const gchar *icon_name);
void                gtk_icon_source_set_size            (GtkIconSource *source,
                                                         GtkIconSize size);
void                gtk_icon_source_set_size_wildcarded (GtkIconSource *source,
                                                         gboolean setting);
void                gtk_icon_source_set_state           (GtkIconSource *source,
                                                         GtkStateType state);
void                gtk_icon_source_set_state_wildcarded
                                                        (GtkIconSource *source,
                                                         gboolean setting);

Object Hierarchy

  GObject
   +----GtkIconFactory

Description

Browse the available stock icons in the list of stock IDs found here. You can also use the gtk-demo application for this purpose.

An icon factory manages a collection of GtkIconSet; a GtkIconSet manages a set of variants of a particular icon (i.e. a GtkIconSet contains variants for different sizes and widget states). Icons in an icon factory are named by a stock ID, which is a simple string identifying the icon. Each GtkStyle has a list of GtkIconFactory derived from the current theme; those icon factories are consulted first when searching for an icon. If the theme doesn't set a particular icon, GTK+ looks for the icon in a list of default icon factories, maintained by gtk_icon_factory_add_default() and gtk_icon_factory_remove_default(). Applications with icons should add a default icon factory with their icons, which will allow themes to override the icons for the application.

To display an icon, always use gtk_style_lookup_icon_set() on the widget that will display the icon, or the convenience function gtk_widget_render_icon(). These functions take the theme into account when looking up the icon to use for a given stock ID.

Details

GtkIconSource

typedef struct _GtkIconSource GtkIconSource;

GtkIconFactory

typedef struct _GtkIconFactory GtkIconFactory;

GtkIconSet

typedef struct _GtkIconSet GtkIconSet;

enum GtkIconSize

typedef enum
{
  GTK_ICON_SIZE_INVALID,
  GTK_ICON_SIZE_MENU,
  GTK_ICON_SIZE_SMALL_TOOLBAR,
  GTK_ICON_SIZE_LARGE_TOOLBAR,
  GTK_ICON_SIZE_BUTTON,
  GTK_ICON_SIZE_DND,
  GTK_ICON_SIZE_DIALOG
} GtkIconSize;

gtk_icon_source_copy ()

GtkIconSource*      gtk_icon_source_copy                (const GtkIconSource *source);

Creates a copy of source; mostly useful for language bindings.

source : | a GtkIconSource
Returns : | a new GtkIconSource

gtk_icon_source_free ()

void                gtk_icon_source_free                (GtkIconSource *source);

Frees a dynamically-allocated icon source, along with its filename, size, and pixbuf fields if those are not NULL.

source : a GtkIconSource

gtk_icon_factory_add ()

void                gtk_icon_factory_add                (GtkIconFactory *factory,
                                                         const gchar *stock_id,
                                                         GtkIconSet *icon_set);

Adds the given icon_set to the icon factory, under the name stock_id. stock_id should be namespaced for your application, e.g. "myapp-whatever-icon". Normally applications create a GtkIconFactory, then add it to the list of default factories with gtk_icon_factory_add_default(). Then they pass the stock_id to widgets such as GtkImage to display the icon. Themes can provide an icon with the same name (such as "myapp-whatever-icon") to override your application's default icons. If an icon already existed in factory for stock_id, it is unreferenced and replaced with the new icon_set.

factory : | a GtkIconFactory
stock_id : | icon name
icon_set : | icon set

gtk_icon_factory_add_default ()

void                gtk_icon_factory_add_default        (GtkIconFactory *factory);

Adds an icon factory to the list of icon factories searched by gtk_style_lookup_icon_set(). This means that, for example, gtk_image_new_from_stock() will be able to find icons in factory. There will normally be an icon factory added for each library or application that comes with icons. The default icon factories can be overridden by themes.

factory : a GtkIconFactory

gtk_icon_factory_lookup ()

GtkIconSet*         gtk_icon_factory_lookup             (GtkIconFactory *factory,
                                                         const gchar *stock_id);

Looks up stock_id in the icon factory, returning an icon set if found, otherwise NULL. For display to the user, you should use gtk_style_lookup_icon_set() on the GtkStyle for the widget that will display the icon, instead of using this function directly, so that themes are taken into account.

factory : | a GtkIconFactory
stock_id : | an icon name
Returns : | icon set of stock_id.

gtk_icon_factory_lookup_default ()

GtkIconSet*         gtk_icon_factory_lookup_default     (const gchar *stock_id);

Looks for an icon in the list of default icon factories. For display to the user, you should use gtk_style_lookup_icon_set() on the GtkStyle for the widget that will display the icon, instead of using this function directly, so that themes are taken into account.

stock_id : | an icon name
Returns : | a GtkIconSet, or NULL

gtk_icon_factory_new ()

GtkIconFactory*     gtk_icon_factory_new                (void);

Creates a new GtkIconFactory. An icon factory manages a collection of GtkIconSets; a GtkIconSet manages a set of variants of a particular icon (i.e. a GtkIconSet contains variants for different sizes and widget states). Icons in an icon factory are named by a stock ID, which is a simple string identifying the icon. Each GtkStyle has a list of GtkIconFactorys derived from the current theme; those icon factories are consulted first when searching for an icon. If the theme doesn't set a particular icon, GTK+ looks for the icon in a list of default icon factories, maintained by gtk_icon_factory_add_default() and gtk_icon_factory_remove_default(). Applications with icons should add a default icon factory with their icons, which will allow themes to override the icons for the application.

Returns : a new GtkIconFactory

gtk_icon_factory_remove_default ()

void                gtk_icon_factory_remove_default     (GtkIconFactory *factory);

Removes an icon factory from the list of default icon factories. Not normally used; you might use it for a library that can be unloaded or shut down.

factory : a GtkIconFactory previously added with gtk_icon_factory_add_default()

gtk_icon_set_add_source ()

void                gtk_icon_set_add_source             (GtkIconSet *icon_set,
                                                         const GtkIconSource *source);

Icon sets have a list of GtkIconSource, which they use as base icons for rendering icons in different states and sizes. Icons are scaled, made to look insensitive, etc. in gtk_icon_set_render_icon(), but GtkIconSet needs base images to work with. The base images and when to use them are described by a GtkIconSource.

This function copies source, so you can reuse the same source immediately without affecting the icon set.

An example of when you'd use this function: a web browser's "Back to Previous Page" icon might point in a different direction in Hebrew and in English; it might look different when insensitive; and it might change size depending on toolbar mode (small/large icons). So a single icon set would contain all those variants of the icon, and you might add a separate source for each one.

You should nearly always add a "default" icon source with all fields wildcarded, which will be used as a fallback if no more specific source matches. GtkIconSet always prefers more specific icon sources to more generic icon sources. The order in which you add the sources to the icon set does not matter.

gtk_icon_set_new_from_pixbuf() creates a new icon set with a default icon source based on the given pixbuf.

icon_set : | a GtkIconSet
source : | a GtkIconSource

gtk_icon_set_copy ()

GtkIconSet*         gtk_icon_set_copy                   (GtkIconSet *icon_set);

Copies icon_set by value.

icon_set : | a GtkIconSet
Returns : | a new GtkIconSet identical to the first.

gtk_icon_set_new ()

GtkIconSet*         gtk_icon_set_new                    (void);

Creates a new GtkIconSet. A GtkIconSet represents a single icon in various sizes and widget states. It can provide a GdkPixbuf for a given size and state on request, and automatically caches some of the rendered GdkPixbuf objects.

Normally you would use gtk_widget_render_icon() instead of using GtkIconSet directly. The one case where you'd use GtkIconSet is to create application-specific icon sets to place in a GtkIconFactory.

Returns : a new GtkIconSet

gtk_icon_set_new_from_pixbuf ()

GtkIconSet*         gtk_icon_set_new_from_pixbuf        (GdkPixbuf *pixbuf);

Creates a new GtkIconSet with pixbuf as the default/fallback source image. If you don't add any additional GtkIconSource to the icon set, all variants of the icon will be created from pixbuf, using scaling, pixelation, etc. as required to adjust the icon size or make the icon look insensitive/prelighted.

pixbuf : | a GdkPixbuf
Returns : | a new GtkIconSet

gtk_icon_set_ref ()

GtkIconSet*         gtk_icon_set_ref                    (GtkIconSet *icon_set);

Increments the reference count on icon_set.

icon_set : | a GtkIconSet.
Returns : | icon_set.

gtk_icon_set_render_icon ()

GdkPixbuf*          gtk_icon_set_render_icon            (GtkIconSet *icon_set,
                                                         GtkStyle *style,
                                                         GtkTextDirection direction,
                                                         GtkStateType state,
                                                         GtkIconSize size,
                                                         GtkWidget *widget,
                                                         const char *detail);

Renders an icon using gtk_style_render_icon(). In most cases, gtk_widget_render_icon() is better, since it automatically provides most of the arguments from the current widget settings. This function never returns NULL; if the icon can't be rendered (perhaps because an image file fails to load), a default "missing image" icon will be returned instead.

icon_set : | a GtkIconSet
style : | a GtkStyle associated with widget, or NULL
direction : | text direction
state : | widget state
size : | icon size. A size of (GtkIconSize)-1 means render at the size of the source and don't scale.
widget : | widget that will display the icon, or NULL. The only use that is typically made of this is to determine the appropriate GdkScreen.
detail : | detail to pass to the theme engine, or NULL. Note that passing a detail of anything but NULL will disable caching.
Returns : | a GdkPixbuf to be displayed

gtk_icon_set_unref ()

void                gtk_icon_set_unref                  (GtkIconSet *icon_set);

Decrements the reference count on icon_set, and frees memory if the reference count reaches 0.

icon_set : a GtkIconSet

gtk_icon_size_lookup ()

gboolean            gtk_icon_size_lookup                (GtkIconSize size,
                                                         gint *width,
                                                         gint *height);

Obtains the pixel size of a semantic icon size, possibly modified by user preferences for the default GtkSettings. (See gtk_icon_size_lookup_for_settings().) Normally size would be GTK_ICON_SIZE_MENU, GTK_ICON_SIZE_BUTTON, etc. This function isn't normally needed, gtk_widget_render_icon() is the usual way to get an icon for rendering, then just look at the size of the rendered pixbuf. The rendered pixbuf may not even correspond to the width/height returned by gtk_icon_size_lookup(), because themes are free to render the pixbuf however they like, including changing the usual size.

size : | an icon size
width : | location to store icon width
height : | location to store icon height
Returns : | TRUE if size was a valid size

gtk_icon_size_lookup_for_settings ()

gboolean            gtk_icon_size_lookup_for_settings   (GtkSettings *settings,
                                                         GtkIconSize size,
                                                         gint *width,
                                                         gint *height);

Obtains the pixel size of a semantic icon size, possibly modified by user preferences for a particular GtkSettings. Normally size would be GTK_ICON_SIZE_MENU, GTK_ICON_SIZE_BUTTON, etc. This function isn't normally needed, gtk_widget_render_icon() is the usual way to get an icon for rendering, then just look at the size of the rendered pixbuf. The rendered pixbuf may not even correspond to the width/height returned by gtk_icon_size_lookup(), because themes are free to render the pixbuf however they like, including changing the usual size.

settings : | a GtkSettings object, used to determine which set of user preferences to used.
size : | an icon size
width : | location to store icon width
height : | location to store icon height
Returns : | TRUE if size was a valid size

Since 2.2

gtk_icon_size_register ()

GtkIconSize         gtk_icon_size_register              (const gchar *name,
                                                         gint width,
                                                         gint height);

Registers a new icon size, along the same lines as GTK_ICON_SIZE_MENU, etc. Returns the integer value for the size.

name : | name of the icon size
width : | the icon width
height : | the icon height
Returns : | integer value representing the size

gtk_icon_size_register_alias ()

void                gtk_icon_size_register_alias        (const gchar *alias,
                                                         GtkIconSize target);

Registers alias as another name for target. So calling gtk_icon_size_from_name() with alias as argument will return target.

alias : | an alias for target
target : | an existing icon size

gtk_icon_size_from_name ()

GtkIconSize         gtk_icon_size_from_name             (const gchar *name);

Looks up the icon size associated with name.

name : | the name to look up.
Returns : | the icon size with the given name.

gtk_icon_size_get_name ()

const gchar*        gtk_icon_size_get_name              (GtkIconSize size);

Gets the canonical name of the given icon size. The returned string is statically allocated and should not be freed.

size : | a GtkIconSize.
Returns : | the name of the given icon size.

gtk_icon_set_get_sizes ()

void                gtk_icon_set_get_sizes              (GtkIconSet *icon_set,
                                                         GtkIconSize **sizes,
                                                         gint *n_sizes);

Obtains a list of icon sizes this icon set can render. The returned array must be freed with g_free().

icon_set : | a GtkIconSet
sizes : | return location for array of sizes
n_sizes : | location to store number of elements in returned array

gtk_icon_source_get_direction ()

GtkTextDirection    gtk_icon_source_get_direction       (const GtkIconSource *source);

Obtains the text direction this icon source applies to. The return value is only useful/meaningful if the text direction is not wildcarded.

source : | a GtkIconSource
Returns : | text direction this source matches

gtk_icon_source_get_direction_wildcarded ()

gboolean            gtk_icon_source_get_direction_wildcarded
                                                        (const GtkIconSource *source);

Gets the value set by gtk_icon_source_set_direction_wildcarded().

source : | a GtkIconSource
Returns : | TRUE if this icon source is a base for any text direction variant

gtk_icon_source_get_filename ()

const gchar*        gtk_icon_source_get_filename        (const GtkIconSource *source);

Retrieves the source filename, or NULL if none is set. The filename is not a copy, and should not be modified or expected to persist beyond the lifetime of the icon source.

source : | a GtkIconSource
Returns : | image filename. This string must not be modified or freed.

gtk_icon_source_get_pixbuf ()

GdkPixbuf*          gtk_icon_source_get_pixbuf          (const GtkIconSource *source);

Retrieves the source pixbuf, or NULL if none is set. In addition, if a filename source is in use, this function in some cases will return the pixbuf from loaded from the filename. This is, for example, true for the GtkIconSource passed to the GtkStyle::render_icon() virtual function. The reference count on the pixbuf is not incremented.

source : | a GtkIconSource
Returns : | source pixbuf

gtk_icon_source_get_icon_name ()

const gchar*        gtk_icon_source_get_icon_name       (const GtkIconSource *source);

Retrieves the source icon name, or NULL if none is set. The icon_name is not a copy, and should not be modified or expected to persist beyond the lifetime of the icon source.

source : | a GtkIconSource
Returns : | icon name. This string must not be modified or freed.

gtk_icon_source_get_size ()

GtkIconSize         gtk_icon_source_get_size            (const GtkIconSource *source);

Obtains the icon size this source applies to. The return value is only useful/meaningful if the icon size is not wildcarded.

source : | a GtkIconSource
Returns : | icon size this source matches.

gtk_icon_source_get_size_wildcarded ()

gboolean            gtk_icon_source_get_size_wildcarded (const GtkIconSource *source);

Gets the value set by gtk_icon_source_set_size_wildcarded().

source : | a GtkIconSource
Returns : | TRUE if this icon source is a base for any icon size variant

gtk_icon_source_get_state ()

GtkStateType        gtk_icon_source_get_state           (const GtkIconSource *source);

Obtains the widget state this icon source applies to. The return value is only useful/meaningful if the widget state is not wildcarded.

source : | a GtkIconSource
Returns : | widget state this source matches

gtk_icon_source_get_state_wildcarded ()

gboolean            gtk_icon_source_get_state_wildcarded
                                                        (const GtkIconSource *source);

Gets the value set by gtk_icon_source_set_state_wildcarded().

source : | a GtkIconSource
Returns : | TRUE if this icon source is a base for any widget state variant

gtk_icon_source_new ()

GtkIconSource*      gtk_icon_source_new                 (void);

Creates a new GtkIconSource. A GtkIconSource contains a GdkPixbuf (or image filename) that serves as the base image for one or more of the icons in a GtkIconSet, along with a specification for which icons in the icon set will be based on that pixbuf or image file. An icon set contains a set of icons that represent "the same" logical concept in different states, different global text directions, and different sizes.

So for example a web browser's "Back to Previous Page" icon might point in a different direction in Hebrew and in English; it might look different when insensitive; and it might change size depending on toolbar mode (small/large icons). So a single icon set would contain all those variants of the icon. GtkIconSet contains a list of GtkIconSource from which it can derive specific icon variants in the set.

In the simplest case, GtkIconSet contains one source pixbuf from which it derives all variants. The convenience function gtk_icon_set_new_from_pixbuf() handles this case; if you only have one source pixbuf, just use that function.

If you want to use a different base pixbuf for different icon variants, you create multiple icon sources, mark which variants they'll be used to create, and add them to the icon set with gtk_icon_set_add_source().

By default, the icon source has all parameters wildcarded. That is, the icon source will be used as the base icon for any desired text direction, widget state, or icon size.

Returns : a new GtkIconSource

gtk_icon_source_set_direction ()

void                gtk_icon_source_set_direction       (GtkIconSource *source,
                                                         GtkTextDirection direction);

Sets the text direction this icon source is intended to be used with.

Setting the text direction on an icon source makes no difference if the text direction is wildcarded. Therefore, you should usually call gtk_icon_source_set_direction_wildcarded() to un-wildcard it in addition to calling this function.

source : | a GtkIconSource
direction : | text direction this source applies to

gtk_icon_source_set_direction_wildcarded ()

void                gtk_icon_source_set_direction_wildcarded
                                                        (GtkIconSource *source,
                                                         gboolean setting);

If the text direction is wildcarded, this source can be used as the base image for an icon in any GtkTextDirection. If the text direction is not wildcarded, then the text direction the icon source applies to should be set with gtk_icon_source_set_direction(), and the icon source will only be used with that text direction.

GtkIconSet prefers non-wildcarded sources (exact matches) over wildcarded sources, and will use an exact match when possible.

source : | a GtkIconSource
setting : | TRUE to wildcard the text direction

gtk_icon_source_set_filename ()

void                gtk_icon_source_set_filename        (GtkIconSource *source,
                                                         const gchar *filename);

Sets the name of an image file to use as a base image when creating icon variants for GtkIconSet. The filename must be absolute.

source : | a GtkIconSource
filename : | image file to use

gtk_icon_source_set_pixbuf ()

void                gtk_icon_source_set_pixbuf          (GtkIconSource *source,
                                                         GdkPixbuf *pixbuf);

Sets a pixbuf to use as a base image when creating icon variants for GtkIconSet.

source : | a GtkIconSource
pixbuf : | pixbuf to use as a source

gtk_icon_source_set_icon_name ()

void                gtk_icon_source_set_icon_name       (GtkIconSource *source,
                                                         const gchar *icon_name);

Sets the name of an icon to look up in the current icon theme to use as a base image when creating icon variants for GtkIconSet.

source : | a GtkIconSource
icon_name : | name of icon to use

gtk_icon_source_set_size ()

void                gtk_icon_source_set_size            (GtkIconSource *source,
                                                         GtkIconSize size);

Sets the icon size this icon source is intended to be used with.

Setting the icon size on an icon source makes no difference if the size is wildcarded. Therefore, you should usually call gtk_icon_source_set_size_wildcarded() to un-wildcard it in addition to calling this function.

source : | a GtkIconSource
size : | icon size this source applies to

gtk_icon_source_set_size_wildcarded ()

void                gtk_icon_source_set_size_wildcarded (GtkIconSource *source,
                                                         gboolean setting);

If the icon size is wildcarded, this source can be used as the base image for an icon of any size. If the size is not wildcarded, then the size the source applies to should be set with gtk_icon_source_set_size() and the icon source will only be used with that specific size.

GtkIconSet prefers non-wildcarded sources (exact matches) over wildcarded sources, and will use an exact match when possible.

GtkIconSet will normally scale wildcarded source images to produce an appropriate icon at a given size, but will not change the size of source images that match exactly.

source : | a GtkIconSource
setting : | TRUE to wildcard the widget state

gtk_icon_source_set_state ()

void                gtk_icon_source_set_state           (GtkIconSource *source,
                                                         GtkStateType state);

Sets the widget state this icon source is intended to be used with.

Setting the widget state on an icon source makes no difference if the state is wildcarded. Therefore, you should usually call gtk_icon_source_set_state_wildcarded() to un-wildcard it in addition to calling this function.

source : | a GtkIconSource
state : | widget state this source applies to

gtk_icon_source_set_state_wildcarded ()

void                gtk_icon_source_set_state_wildcarded
                                                        (GtkIconSource *source,
                                                         gboolean setting);

If the widget state is wildcarded, this source can be used as the base image for an icon in any GtkStateType. If the widget state is not wildcarded, then the state the source applies to should be set with gtk_icon_source_set_state() and the icon source will only be used with that specific state.

GtkIconSet prefers non-wildcarded sources (exact matches) over wildcarded sources, and will use an exact match when possible.

GtkIconSet will normally transform wildcarded source images to produce an appropriate icon for a given state, for example lightening an image on prelight, but will not modify source images that match exactly.

source : | a GtkIconSource
setting : | TRUE to wildcard the widget state


Types

Types — Handle run-time type creation

Synopsis

#include <gtk/gtk.h>

typedef             GtkType;
typedef             GtkFundamentalType;
#define             GTK_CLASS_NAME                      (class)
#define             GTK_CLASS_TYPE                      (class)
#define             GTK_TYPE_IS_OBJECT                  (type)
#define             GTK_TYPE_FUNDAMENTAL_LAST
#define             GTK_TYPE_FUNDAMENTAL_MAX
#define             GTK_STRUCT_OFFSET
#define             GTK_CHECK_CAST
#define             GTK_CHECK_CLASS_CAST
#define             GTK_CHECK_TYPE
#define             GTK_CHECK_CLASS_TYPE
#define             GTK_CHECK_GET_CLASS
#define             GTK_FUNDAMENTAL_TYPE
#define             GTK_SIGNAL_FUNC                     (f)
typedef             GtkClassInitFunc;
typedef             GtkObjectInitFunc;
void                (*GtkSignalFunc)                    (void);
gboolean            (*GtkFunction)                      (gpointer data);
void                (*GtkDestroyNotify)                 (gpointer data);
void                (*GtkCallbackMarshal)               (GtkObject *object,
                                                         gpointer data,
                                                         guint n_args,
                                                         GtkArg *args);
typedef             GtkSignalMarshaller;
typedef             GtkTypeObject;
                    GtkArg;
#define             GTK_VALUE_CHAR                      (a)
#define             GTK_VALUE_UCHAR                     (a)
#define             GTK_VALUE_BOOL                      (a)
#define             GTK_VALUE_INT                       (a)
#define             GTK_VALUE_UINT                      (a)
#define             GTK_VALUE_LONG                      (a)
#define             GTK_VALUE_ULONG                     (a)
#define             GTK_VALUE_FLOAT                     (a)
#define             GTK_VALUE_DOUBLE                    (a)
#define             GTK_VALUE_STRING                    (a)
#define             GTK_VALUE_ENUM                      (a)
#define             GTK_VALUE_FLAGS                     (a)
#define             GTK_VALUE_BOXED                     (a)
#define             GTK_VALUE_POINTER                   (a)
#define             GTK_VALUE_OBJECT                    (a)
#define             GTK_VALUE_SIGNAL                    (a)
#define             GTK_RETLOC_CHAR                     (a)
#define             GTK_RETLOC_UCHAR                    (a)
#define             GTK_RETLOC_BOOL                     (a)
#define             GTK_RETLOC_INT                      (a)
#define             GTK_RETLOC_UINT                     (a)
#define             GTK_RETLOC_LONG                     (a)
#define             GTK_RETLOC_ULONG                    (a)
#define             GTK_RETLOC_FLOAT                    (a)
#define             GTK_RETLOC_DOUBLE                   (a)
#define             GTK_RETLOC_STRING                   (a)
#define             GTK_RETLOC_ENUM                     (a)
#define             GTK_RETLOC_FLAGS                    (a)
#define             GTK_RETLOC_BOXED                    (a)
#define             GTK_RETLOC_POINTER                  (a)
#define             GTK_RETLOC_OBJECT                   (a)
                    GtkTypeInfo;
typedef             GtkTypeClass;
typedef             GtkEnumValue;
typedef             GtkFlagValue;
void                gtk_type_init                       (GTypeDebugFlags debug_flags);
GtkType             gtk_type_unique                     (GtkType parent_type,
                                                         const GtkTypeInfo *gtkinfo);
#define             gtk_type_name                       (type)
#define             gtk_type_from_name                  (name)
#define             gtk_type_parent                     (type)
gpointer            gtk_type_class                      (GtkType type);
gpointer            gtk_type_new                        (GtkType type);
#define             gtk_type_is_a                       (type, is_a_type)
GtkEnumValue*       gtk_type_enum_get_values            (GtkType enum_type);
GtkFlagValue*       gtk_type_flags_get_values           (GtkType flags_type);
GtkEnumValue*       gtk_type_enum_find_value            (GtkType enum_type,
                                                         const gchar *value_name);
GtkFlagValue*       gtk_type_flags_find_value           (GtkType flags_type,
                                                         const gchar *value_name);

Description

The GTK+ type system is extensible. Because of that, types have to be managed at runtime.

Details

GtkType

typedef GType			GtkType;

GtkType is unique integer identifying the type. The guts of the information about the type is held in a private struct named GtkTypeNode.

GtkFundamentalType

typedef GType GtkFundamentalType;

Warning

GtkFundamentalType is deprecated and should not be used in newly-written code.

GtkFundamentalType is an enumerated type which lists all the possible fundamental types (e.g. char, uchar, int, long, float, etc).

GTK_CLASS_NAME()

#define GTK_CLASS_NAME(class)		(g_type_name (G_TYPE_FROM_CLASS (class)))

Warning

GTK_CLASS_NAME is deprecated and should not be used in newly-written code. Use g_type_name() and G_TYPE_FROM_CLASS() instead.

Returns the type name of class.

class : a GtkTypeClass.

GTK_CLASS_TYPE()

#define GTK_CLASS_TYPE(class)		(G_TYPE_FROM_CLASS (class))

Warning

GTK_CLASS_TYPE is deprecated and should not be used in newly-written code. Use G_TYPE_FROM_CLASS() instead.

Returns the type of class.

class : a GtkTypeClass.

GTK_TYPE_IS_OBJECT()

#define GTK_TYPE_IS_OBJECT(type)	(g_type_is_a ((type), GTK_TYPE_OBJECT))

Warning

GTK_TYPE_IS_OBJECT is deprecated and should not be used in newly-written code. Use G_TYPE_IS_OBJECT() instead.

Returns TRUE if type is a GTK_TYPE_OBJECT.

type : a GtkType.

GTK_TYPE_FUNDAMENTAL_LAST

#define	GTK_TYPE_FUNDAMENTAL_LAST        (G_TYPE_LAST_RESERVED_FUNDAMENTAL - 1)

Warning

GTK_TYPE_FUNDAMENTAL_LAST is deprecated and should not be used in newly-written code. Use G_TYPE_LAST_RESERVED_FUNDAMENTAL - 1 instead.

The highest-numbered structured or flat enumerated type value.

GTK_TYPE_FUNDAMENTAL_MAX

#define	GTK_TYPE_FUNDAMENTAL_MAX         (G_TYPE_FUNDAMENTAL_MAX)

Warning

GTK_TYPE_FUNDAMENTAL_MAX is deprecated and should not be used in newly-written code. Use G_TYPE_FUNDAMENTAL_MAX instead.

The maximum fundamental enumerated type value.

GTK_STRUCT_OFFSET

#define GTK_STRUCT_OFFSET	G_STRUCT_OFFSET

Warning

GTK_STRUCT_OFFSET is deprecated and should not be used in newly-written code. Use G_STRUCT_OFFSET() instead.

Use in place of offsetof(), which is used if it exists.

GTK_CHECK_CAST

#define	GTK_CHECK_CAST		G_TYPE_CHECK_INSTANCE_CAST

Casts the object in tobj into cast. If G_DISABLE_CAST_CHECKS is defined, just cast it. Otherwise, check to see if we can cast tobj into a cast.

GTK_CHECK_CLASS_CAST

#define	GTK_CHECK_CLASS_CAST	G_TYPE_CHECK_CLASS_CAST

Casts the object in tobj into cast. If G_DISABLE_CAST_CHECKS is defined, just cast it. Otherwise, check to see if we can cast tobj into a cast.

GTK_CHECK_TYPE

#define	GTK_CHECK_TYPE		G_TYPE_CHECK_INSTANCE_TYPE

Determines whether type_object is a type of otype.

GTK_CHECK_CLASS_TYPE

#define	GTK_CHECK_CLASS_TYPE	G_TYPE_CHECK_CLASS_TYPE

Determines whether type_class is a type of otype.

GTK_CHECK_GET_CLASS

#define GTK_CHECK_GET_CLASS	G_TYPE_INSTANCE_GET_CLASS

Gets the class of tobj.

GTK_FUNDAMENTAL_TYPE

#define	GTK_FUNDAMENTAL_TYPE	G_TYPE_FUNDAMENTAL

Warning

GTK_FUNDAMENTAL_TYPE is deprecated and should not be used in newly-written code.

Converts a GTK+ type into a fundamental type.

GTK_SIGNAL_FUNC()

#define GTK_SIGNAL_FUNC(f)	    ((GtkSignalFunc) (f))

Just a macroized cast into a GtkSignalFunc.

f :

GtkClassInitFunc

typedef GBaseInitFunc		GtkClassInitFunc;

Warning

GtkClassInitFunc is deprecated and should not be used in newly-written code.

Defines a function pointer.

GtkObjectInitFunc

typedef GInstanceInitFunc	GtkObjectInitFunc;

Warning

GtkObjectInitFunc is deprecated and should not be used in newly-written code.

Defines a function pointer.

GtkSignalFunc ()

void                (*GtkSignalFunc)                    (void);

Defines a function pointer.

GtkFunction ()

gboolean            (*GtkFunction)                      (gpointer data);

Defines a function pointer.

data : | gpointer
Returns : | gint

GtkDestroyNotify ()

void                (*GtkDestroyNotify)                 (gpointer data);

Defines a function pointer.

data : gpointer

GtkCallbackMarshal ()

void                (*GtkCallbackMarshal)               (GtkObject *object,
                                                         gpointer data,
                                                         guint n_args,
                                                         GtkArg *args);

Defines a function pointer.

object : | GtkObject*
data : | gpointer
n_args : | guint
args : | GtkArg*

GtkSignalMarshaller

typedef GSignalCMarshaller          GtkSignalMarshaller;

Warning

GtkSignalMarshaller is deprecated and should not be used in newly-written code.

Defines a function pointer.

GtkTypeObject

typedef GTypeInstance		GtkTypeObject;

Warning

GtkTypeObject is deprecated and should not be used in newly-written code.

A GtkTypeObject defines the minimum structure requirements for type instances. Type instances returned from gtk_type_new() and initialized through a GtkObjectInitFunc need to directly inherit from this structure or at least copy its fields one by one.

GtkArg

typedef struct {
  GtkType type;
  gchar *name;

  /* this union only defines the required storage types for
   * the possibile values, thus there is no gint enum_data field,
   * because that would just be a mere alias for gint int_data.
   * use the GTK_VALUE_*() and GTK_RETLOC_*() macros to access
   * the discrete memebers.
   */
  union {
    /* flat values */
    gchar char_data;
    guchar uchar_data;
    gboolean bool_data;
    gint int_data;
    guint uint_data;
    glong long_data;
    gulong ulong_data;
    gfloat float_data;
    gdouble double_data;
    gchar *string_data;
    GtkObject *object_data;
    gpointer pointer_data;

    /* structured values */
    struct {
      GtkSignalFunc f;
      gpointer d;
    } signal_data;
  } d;
} GtkArg;

Warning

GtkArg is deprecated and should not be used in newly-written code.

This is a structure that we use to pass in typed values (and names).

GTK_VALUE_CHAR()

#define GTK_VALUE_CHAR(a)	((a).d.char_data)

Warning

GTK_VALUE_CHAR is deprecated and should not be used in newly-written code.

Gets the value of a GtkArg whose GtkType is GTK_TYPE_CHAR.

a : a GtkArg.

GTK_VALUE_UCHAR()

#define GTK_VALUE_UCHAR(a)	((a).d.uchar_data)

Warning

GTK_VALUE_UCHAR is deprecated and should not be used in newly-written code.

Gets the value of a GtkArg whose GtkType is GTK_TYPE_UCHAR.

a : a GtkArg.

GTK_VALUE_BOOL()

#define GTK_VALUE_BOOL(a)	((a).d.bool_data)

Warning

GTK_VALUE_BOOL is deprecated and should not be used in newly-written code.

Gets the value of a GtkArg whose GtkType is GTK_TYPE_BOOL.

a : a GtkArg.

GTK_VALUE_INT()

#define GTK_VALUE_INT(a)	((a).d.int_data)

Warning

GTK_VALUE_INT is deprecated and should not be used in newly-written code.

Gets the value of a GtkArg whose GtkType is GTK_TYPE_INT.

a : a GtkArg.

GTK_VALUE_UINT()

#define GTK_VALUE_UINT(a)	((a).d.uint_data)

Warning

GTK_VALUE_UINT is deprecated and should not be used in newly-written code.

Gets the value of a GtkArg whose GtkType is GTK_TYPE_UINT.

a : a GtkArg.

GTK_VALUE_LONG()

#define GTK_VALUE_LONG(a)	((a).d.long_data)

Warning

GTK_VALUE_LONG is deprecated and should not be used in newly-written code.

Gets the value of a GtkArg whose GtkType is GTK_TYPE_LONG.

a : a GtkArg.

GTK_VALUE_ULONG()

#define GTK_VALUE_ULONG(a)	((a).d.ulong_data)

Warning

GTK_VALUE_ULONG is deprecated and should not be used in newly-written code.

Gets the value of a GtkArg whose GtkType is GTK_TYPE_ULONG.

a : a GtkArg.

GTK_VALUE_FLOAT()

#define GTK_VALUE_FLOAT(a)	((a).d.float_data)

Warning

GTK_VALUE_FLOAT is deprecated and should not be used in newly-written code.

Gets the value of a GtkArg whose GtkType is GTK_TYPE_FLOAT.

a : a GtkArg.

GTK_VALUE_DOUBLE()

#define GTK_VALUE_DOUBLE(a)	((a).d.double_data)

Warning

GTK_VALUE_DOUBLE is deprecated and should not be used in newly-written code.

Gets the value of a GtkArg whose GtkType is GTK_TYPE_DOUBLE.

a : a GtkArg.

GTK_VALUE_STRING()

#define GTK_VALUE_STRING(a)	((a).d.string_data)

Warning

GTK_VALUE_STRING is deprecated and should not be used in newly-written code.

Gets the value of a GtkArg whose GtkType is GTK_TYPE_STRING.

a : a GtkArg.

GTK_VALUE_ENUM()

#define GTK_VALUE_ENUM(a)	((a).d.int_data)

Warning

GTK_VALUE_ENUM is deprecated and should not be used in newly-written code.

Gets the value of a GtkArg whose GtkType is GTK_TYPE_ENUM.

a : a GtkArg.

GTK_VALUE_FLAGS()

#define GTK_VALUE_FLAGS(a)	((a).d.uint_data)

Warning

GTK_VALUE_FLAGS is deprecated and should not be used in newly-written code.

Gets the value of a GtkArg whose GtkType is GTK_TYPE_FLAGS.

a : a GtkArg.

GTK_VALUE_BOXED()

#define GTK_VALUE_BOXED(a)	((a).d.pointer_data)

Warning

GTK_VALUE_BOXED is deprecated and should not be used in newly-written code.

Gets the value of a GtkArg whose GtkType is GTK_TYPE_BOXED.

a : a GtkArg.

GTK_VALUE_POINTER()

#define GTK_VALUE_POINTER(a)	((a).d.pointer_data)

Warning

GTK_VALUE_POINTER is deprecated and should not be used in newly-written code.

Gets the value of a GtkArg whose GtkType is GTK_TYPE_POINTER.

a : a GtkArg.

GTK_VALUE_OBJECT()

#define GTK_VALUE_OBJECT(a)	((a).d.object_data)

Warning

GTK_VALUE_OBJECT is deprecated and should not be used in newly-written code.

Gets the value of a GtkArg whose GtkType is GTK_TYPE_OBJECT.

a : a GtkArg.

GTK_VALUE_SIGNAL()

#define GTK_VALUE_SIGNAL(a)	((a).d.signal_data)

Warning

GTK_VALUE_SIGNAL is deprecated and should not be used in newly-written code.

Gets the value of a GtkArg whose GtkType is GTK_TYPE_SIGNAL.

a : a GtkArg.

GTK_RETLOC_CHAR()

#define GTK_RETLOC_CHAR(a)	((gchar*)	(a).d.pointer_data)

Warning

GTK_RETLOC_CHAR is deprecated and should not be used in newly-written code.

If the GtkArg contains a pointer to the value, this macro will be a pointer to a GTK_TYPE_CHAR.

a : a GtkArg.

GTK_RETLOC_UCHAR()

#define GTK_RETLOC_UCHAR(a)	((guchar*)	(a).d.pointer_data)

Warning

GTK_RETLOC_UCHAR is deprecated and should not be used in newly-written code.

If the GtkArg contains a pointer to the value, this macro will be a pointer to a GTK_TYPE_UCHAR.

a : a GtkArg.

GTK_RETLOC_BOOL()

#define GTK_RETLOC_BOOL(a)	((gboolean*)	(a).d.pointer_data)

Warning

GTK_RETLOC_BOOL is deprecated and should not be used in newly-written code.

If the GtkArg contains a pointer to the value, this macro will be a pointer to a GTK_TYPE_BOOL.

a : a GtkArg.

GTK_RETLOC_INT()

#define GTK_RETLOC_INT(a)	((gint*)	(a).d.pointer_data)

Warning

GTK_RETLOC_INT is deprecated and should not be used in newly-written code.

If the GtkArg contains a pointer to the value, this macro will be a pointer to a GTK_TYPE_INT.

a : a GtkArg.

GTK_RETLOC_UINT()

#define GTK_RETLOC_UINT(a)	((guint*)	(a).d.pointer_data)

Warning

GTK_RETLOC_UINT is deprecated and should not be used in newly-written code.

If the GtkArg contains a pointer to the value, this macro will be a pointer to a GTK_TYPE_UINT.

a : a GtkArg.

GTK_RETLOC_LONG()

#define GTK_RETLOC_LONG(a)	((glong*)	(a).d.pointer_data)

Warning

GTK_RETLOC_LONG is deprecated and should not be used in newly-written code.

If the GtkArg contains a pointer to the value, this macro will be a pointer to a GTK_TYPE_LONG.

a : a GtkArg.

GTK_RETLOC_ULONG()

#define GTK_RETLOC_ULONG(a)	((gulong*)	(a).d.pointer_data)

Warning

GTK_RETLOC_ULONG is deprecated and should not be used in newly-written code.

If the GtkArg contains a pointer to the value, this macro will be a pointer to a GTK_TYPE_ULONG.

a : a GtkArg.

GTK_RETLOC_FLOAT()

#define GTK_RETLOC_FLOAT(a)	((gfloat*)	(a).d.pointer_data)

Warning

GTK_RETLOC_FLOAT is deprecated and should not be used in newly-written code.

If the GtkArg contains a pointer to the value, this macro will be a pointer to a GTK_TYPE_FLOAT.

a : a GtkArg.

GTK_RETLOC_DOUBLE()

#define GTK_RETLOC_DOUBLE(a)	((gdouble*)	(a).d.pointer_data)

Warning

GTK_RETLOC_DOUBLE is deprecated and should not be used in newly-written code.

If the GtkArg contains a pointer to the value, this macro will be a pointer to a GTK_TYPE_DOUBLE.

a : a GtkArg.

GTK_RETLOC_STRING()

#define GTK_RETLOC_STRING(a)	((gchar**)	(a).d.pointer_data)

Warning

GTK_RETLOC_STRING is deprecated and should not be used in newly-written code.

If the GtkArg contains a pointer to the value, this macro will be a pointer to a GTK_TYPE_STRING.

a : a GtkArg.

GTK_RETLOC_ENUM()

#define GTK_RETLOC_ENUM(a)	((gint*)	(a).d.pointer_data)

Warning

GTK_RETLOC_ENUM is deprecated and should not be used in newly-written code.

If the GtkArg contains a pointer to the value, this macro will be a pointer to a GTK_TYPE_ENUM.

a : a GtkArg.

GTK_RETLOC_FLAGS()

#define GTK_RETLOC_FLAGS(a)	((guint*)	(a).d.pointer_data)

Warning

GTK_RETLOC_FLAGS is deprecated and should not be used in newly-written code.

If the GtkArg contains a pointer to the value, this macro will be a pointer to a GTK_TYPE_FLAGS.

a : a GtkArg.

GTK_RETLOC_BOXED()

#define GTK_RETLOC_BOXED(a)	((gpointer*)	(a).d.pointer_data)

Warning

GTK_RETLOC_BOXED is deprecated and should not be used in newly-written code.

If the GtkArg contains a pointer to the value, this macro will be a pointer to a GTK_TYPE_BOXED.

a : a GtkArg.

GTK_RETLOC_POINTER()

#define GTK_RETLOC_POINTER(a)	((gpointer*)	(a).d.pointer_data)

Warning

GTK_RETLOC_POINTER is deprecated and should not be used in newly-written code.

If the GtkArg contains a pointer to the value, this macro will be a pointer to a GTK_TYPE_POINTER.

a : a GtkArg.

GTK_RETLOC_OBJECT()

#define GTK_RETLOC_OBJECT(a)	((GtkObject**)	(a).d.pointer_data)

Warning

GTK_RETLOC_OBJECT is deprecated and should not be used in newly-written code.

If the GtkArg contains a pointer to the value, this macro will be a pointer to a GTK_TYPE_OBJECT.

a : a GtkArg.

GtkTypeInfo

typedef struct {
  gchar			*type_name;
  guint			 object_size;
  guint			 class_size;
  GtkClassInitFunc	 class_init_func;
  GtkObjectInitFunc	 object_init_func;
  gpointer		 reserved_1;
  gpointer		 reserved_2;
  GtkClassInitFunc	 base_class_init_func;
} GtkTypeInfo;

Warning

GtkTypeInfo is deprecated and should not be used in newly-written code.

Holds information about the type. gtk_type_name() returns the name. object_size is somehow set to the number of bytes that an instance of the object will occupy. class_init_func holds the type's initialization function. object_init_func holds the initialization function for an instance of the object. reserved_1 is used for GtkEnumValue to hold the enumerated values.

GtkTypeClass

typedef GTypeClass		GtkTypeClass;

Warning

GtkTypeClass is deprecated and should not be used in newly-written code.

The base structure for a GTK+ type. Every type inherits this as a base structure.

GtkEnumValue

typedef GEnumValue  GtkEnumValue;

Warning

GtkEnumValue is deprecated and should not be used in newly-written code.

A structure which contains a single enum value, and its name, and its nickname.

GtkFlagValue

typedef GFlagsValue GtkFlagValue;

Warning

GtkFlagValue is deprecated and should not be used in newly-written code.

gtk_type_init ()

void                gtk_type_init                       (GTypeDebugFlags debug_flags);

Warning

gtk_type_init is deprecated and should not be used in newly-written code.

Initializes the data structures associated with GTK+ types.

debug_flags :

gtk_type_unique ()

GtkType             gtk_type_unique                     (GtkType parent_type,
                                                         const GtkTypeInfo *gtkinfo);

Warning

gtk_type_unique is deprecated and should not be used in newly-written code.

Creates a new, unique type.

parent_type : | if zero, a fundamental type is created.
gtkinfo : |
Returns : | the new GtkType.

gtk_type_name()

#define	gtk_type_name(type)		 g_type_name (type)

Warning

gtk_type_name is deprecated and should not be used in newly-written code.

Returns a pointer to the name of a type, or NULL if it has none.

type : | a GtkType.
Returns : | a pointer to the name of a type, or NULL if it has none.

gtk_type_from_name()

#define	gtk_type_from_name(name)	 g_type_from_name (name)

Warning

gtk_type_from_name is deprecated and should not be used in newly-written code.

Gets the internal representation of a type, given its name.

name : | the name of a GTK+ type
Returns : | a GtkType.

gtk_type_parent()

#define	gtk_type_parent(type)		 g_type_parent (type)

Warning

gtk_type_parent is deprecated and should not be used in newly-written code.

Returns the parent type of a GtkType.

type : | a GtkType.
Returns : | the GtkType of the parent.

gtk_type_class ()

gpointer            gtk_type_class                      (GtkType type);

Returns a pointer pointing to the class of type or NULL if there was any trouble identifying type. Initializes the class if necessary.

type : | a GtkType.
Returns : | pointer to the class.

gtk_type_new ()

gpointer            gtk_type_new                        (GtkType type);

Warning

gtk_type_new is deprecated and should not be used in newly-written code.

Creates a new object of a given type, and return a pointer to it. Returns NULL if you give it an invalid type. It allocates the object out of the type's memory chunk if there is a memory chunk. The object has all the proper initializers called.

type : | a GtkType.
Returns : | pointer to a GtkTypeObject.

gtk_type_is_a()

#define	gtk_type_is_a(type, is_a_type)	 g_type_is_a ((type), (is_a_type))

Warning

gtk_type_is_a is deprecated and should not be used in newly-written code.

Looks in the type hierarchy to see if type has is_a_type among its ancestors. Do so with a simple lookup, not a loop.

type : | a GtkType.
is_a_type : | another GtkType.
Returns : | TRUE if type is a is_a_type.

gtk_type_enum_get_values ()

GtkEnumValue*       gtk_type_enum_get_values            (GtkType enum_type);

Warning

gtk_type_enum_get_values is deprecated and should not be used in newly-written code.

If enum_type has values, then return a pointer to all of them.

enum_type : | a GtkType.
Returns : | GtkEnumValue*

gtk_type_flags_get_values ()

GtkFlagValue*       gtk_type_flags_get_values           (GtkType flags_type);

Warning

gtk_type_flags_get_values is deprecated and should not be used in newly-written code.

If flags_type has values, then return a pointer to all of them.

flags_type : | a GtkType.
Returns : | GtkFlagValue*

gtk_type_enum_find_value ()

GtkEnumValue*       gtk_type_enum_find_value            (GtkType enum_type,
                                                         const gchar *value_name);

Warning

gtk_type_enum_find_value is deprecated and should not be used in newly-written code.

Returns a pointer to one of enum_type's GtkEnumValues's whose name (or nickname) matches value_name.

enum_type : | a GtkType.
value_name : | the name to look for.
Returns : | GtkEnumValue*

gtk_type_flags_find_value ()

GtkFlagValue*       gtk_type_flags_find_value           (GtkType flags_type,
                                                         const gchar *value_name);

Warning

gtk_type_flags_find_value is deprecated and should not be used in newly-written code.

Returns a pointer to one of flag_type's GtkFlagValue's whose name (or nickname) matches value_name.

flags_type : | a GtkType.
value_name : | the name to look for.
Returns : | GtkFlagValue*


gtk-update-icon-cache

gtk-update-icon-cache — Icon theme caching utility

Synopsis

gtk-update-icon-cache [--force] [--ignore-theme-index] [--index-only] [--source[name]] [--quiet] {iconpath}

Description

gtk-update-icon-cache creates mmap()able cache files for icon themes.

It expects to be given the path to a icon theme directory containing an index.theme, e.g. /usr/share/icons/hicolor, and writes a icon-theme.cache containing cached information about the icons in the directory tree below the given directory.

GTK+ can use the cache files created by gtk-update-icon-cache to avoid a lot of system call and disk seek overhead when the application starts. Since the format of the cache files allows them to be mmap()ed shared between multiple applications, the overall memory consumption is reduced as well.

Options

--force, -f | Overwrite an existing cache file even if it appears to be uptodate.
--ignore-theme-index, -t | Don't check for the existence of 'index.theme' in the icon theme directory. Without this option, gtk-update-icon-cache refuses to create an icon cache in a directory which does not appear to be the toplevel directory of an icon theme.
--index-only, -i | Don't include image data in the cache.
--source, -c | Output a C header file declaring a constant name with the contents of the icon cache.
--quiet, -q | Turn off verbose output.

Bugs

None known yet.


Using GTK+ on Windows

Using GTK+ on Windows — Windows-specific aspects of using GTK+

Using GTK+ on Windows

The Windows port of GTK+ is an implementation of GDK (and therefore GTK+) on top of the Win32 API.

Windows-specific commandline options

The Windows GDK backend can be influenced with some additional command line arguments.

--sync. Don't batch GDI requests. This is a useful option for debugging, but it will slow down the performance considerably.

--no-wintab, --ignore-wintab. Don't use the Wintab API for tablet support. This is the default.

--use-wintab. Use the Wintab API for tablet support, if GTK+ has been compiled with the --with-wintab option.

--max-colors number. In 256 color mode, restrict the size of the color palette to the specified number of colors.

Windows-specific environment variables

The Win32 GDK backend can be influenced with some additional environment variables.

GDK_IGNORE_WINTAB. If this variable is set, GTK+ doesn't use the Wintab API for tablet support. This is the default.

GDK_USE_WINTAB. If this variable is set, GTK+ uses the Wintab API for tablet support, if GTK+ has been compiled with the --with-wintab option.

GDK_WIN32_MAX_COLORS. Specifies the size of the color palette used in 256 color mode.

G_WIN32_PRETEND_WIN9X. Only use the Windows 9x API.


Using GTK+ on the X Window System

Using GTK+ on the X Window System — X11 aspects of using GTK+

GTK+ for the X Window System

On UNIX, the X backend is the default build for GTK+. So you don't need to do anything special when compiling it, and everything should "just work."

To mix low-level Xlib routines into a GTK program, see GDK X Window System interaction in the GDK manual.

X11-specific commandline options

The X backend understands some additional command line arguments.

--display display. The name of the X display to open instead of the one specified in the DISPLAY environment variable.

--screen screen_number. The number of the screen within the default display. This overrides any screen number specified in the display name specified by by he --display command line option or the DISPLAY environment variable. If this screen cannot be opened, then GTK+ will fall back to the screen specified in the display name. This option is not useful interactively; the intended purposes is that when a program registers its command line with a session manager for later restarting, it can save the screen it is on, without having to worry if it might be restarted on a different display.

--sync. Makes all X requests synchronously. This is a useful option for debugging, but it will slow down the performance considerably.

--gxid-host host. The host to contact the gxid daemon on; overrides the GXID_HOST environment variable.

--gxid-port port. The port for the connection to gxid; overrides the GXID_PORT environment variable. This option is only available if GTK+ has been configured with --gdk-target=x11.

X11-specific environment variables

The X backend can be influenced with some additional environment variables.

GXID_HOST, GXID_PORT. The host and port to contact the gxid daemon on. gxid is only necessary on X servers which don't support using the pointer and extension devices at once, and is only built if GTK+ is configured with --with-xinput=gxi. The XFree86 and Xorg X servers don't have this restriction.

GDK_USE_XFT. If this variable is set to 1, GTK+ will use the Pango Xft backend instead of the X backend when possible (i.e. when the X server supports the XRender extension and Pango has been built with Xft support).

Understanding the X11 architecture

People coming from a Windows or MacOS background often find certain aspects of the X Window System surprising. This section introduces some basic X concepts at a high level. For more details, the book most people use is called the Xlib Programming Manual by Adrian Nye; this book is volume one in the O'Reilly X Window System series.

Standards are another important resource if you're poking in low-level X11 details, in particular the ICCCM and the Extended Window Manager Hints specifications. freedesktop.org has links to many relevant specifications.

The GDK manual covers using Xlib in a GTK program.

Server, client, window manager

Other window systems typically put all their functionality in the application itself. With X, each application involves three different programs: the X server, the application (called a client because it's a client of the X server), and a special client called the window manager.

The X server is in charge of managing resources, processing drawing requests, and dispatching events such as keyboard and mouse events to interested applications. So client applications can ask the X server to create a window, draw a circle, or move windows around.

The window manager is in charge of rendering the frame or borders around windows; it also has final say on the size of each window, and window states such as minimized, maximized, and so forth. On Windows and MacOS the application handles most of this. On X11, if you wish to modify the window's state, or change its frame, you must ask the window manager to do so on your behalf, using an established convention.

GTK+ has functions for asking the window manager to do various things; see for example gtk_window_iconify() or gtk_window_maximize() or gtk_window_set_decorated(). Keep in mind that gtk_window_move() and window sizing are ultimately controlled by the window manager as well and most window managers will ignore certain requests from time to time, in the interests of good user interface.


GtkAboutDialog

GtkAboutDialog — Display information about an application

Synopsis

#include <gtk/gtk.h>

                    GtkAboutDialog;
GtkWidget*          gtk_about_dialog_new                (void);
const gchar*        gtk_about_dialog_get_name           (GtkAboutDialog *about);
void                gtk_about_dialog_set_name           (GtkAboutDialog *about,
                                                         const gchar *name);
const gchar*        gtk_about_dialog_get_version        (GtkAboutDialog *about);
void                gtk_about_dialog_set_version        (GtkAboutDialog *about,
                                                         const gchar *version);
const gchar*        gtk_about_dialog_get_copyright      (GtkAboutDialog *about);
void                gtk_about_dialog_set_copyright      (GtkAboutDialog *about,
                                                         const gchar *copyright);
const gchar*        gtk_about_dialog_get_comments       (GtkAboutDialog *about);
void                gtk_about_dialog_set_comments       (GtkAboutDialog *about,
                                                         const gchar *comments);
const gchar*        gtk_about_dialog_get_license        (GtkAboutDialog *about);
void                gtk_about_dialog_set_license        (GtkAboutDialog *about,
                                                         const gchar *license);
gboolean            gtk_about_dialog_get_wrap_license   (GtkAboutDialog *about);
void                gtk_about_dialog_set_wrap_license   (GtkAboutDialog *about,
                                                         gboolean wrap_license);
const gchar*        gtk_about_dialog_get_website        (GtkAboutDialog *about);
void                gtk_about_dialog_set_website        (GtkAboutDialog *about,
                                                         const gchar *website);
const gchar*        gtk_about_dialog_get_website_label  (GtkAboutDialog *about);
void                gtk_about_dialog_set_website_label  (GtkAboutDialog *about,
                                                         const gchar *website_label);
const gchar* const * gtk_about_dialog_get_authors       (GtkAboutDialog *about);
void                gtk_about_dialog_set_authors        (GtkAboutDialog *about,
                                                         const gchar **authors);
const gchar* const * gtk_about_dialog_get_artists       (GtkAboutDialog *about);
void                gtk_about_dialog_set_artists        (GtkAboutDialog *about,
                                                         const gchar **artists);
const gchar* const * gtk_about_dialog_get_documenters   (GtkAboutDialog *about);
void                gtk_about_dialog_set_documenters    (GtkAboutDialog *about,
                                                         const gchar **documenters);
const gchar*        gtk_about_dialog_get_translator_credits
                                                        (GtkAboutDialog *about);
void                gtk_about_dialog_set_translator_credits
                                                        (GtkAboutDialog *about,
                                                         const gchar *translator_credits);
GdkPixbuf*          gtk_about_dialog_get_logo           (GtkAboutDialog *about);
void                gtk_about_dialog_set_logo           (GtkAboutDialog *about,
                                                         GdkPixbuf *logo);
const gchar*        gtk_about_dialog_get_logo_icon_name (GtkAboutDialog *about);
void                gtk_about_dialog_set_logo_icon_name (GtkAboutDialog *about,
                                                         const gchar *icon_name);
void                (*GtkAboutDialogActivateLinkFunc)   (GtkAboutDialog *about,
                                                         const gchar *link,
                                                         gpointer data);
GtkAboutDialogActivateLinkFunc gtk_about_dialog_set_email_hook
                                                        (GtkAboutDialogActivateLinkFunc func,
                                                         gpointer data,
                                                         GDestroyNotify destroy);
GtkAboutDialogActivateLinkFunc gtk_about_dialog_set_url_hook
                                                        (GtkAboutDialogActivateLinkFunc func,
                                                         gpointer data,
                                                         GDestroyNotify destroy);
void                gtk_show_about_dialog               (GtkWindow *parent,
                                                         const gchar *first_property_name,
                                                         ...);

Object Hierarchy

  GObject
   +----GInitiallyUnowned
         +----GtkObject
               +----GtkWidget
                     +----GtkContainer
                           +----GtkBin
                                 +----GtkWindow
                                       +----GtkDialog
                                             +----GtkAboutDialog

Implemented Interfaces

GtkAboutDialog implements AtkImplementorIface.

Properties

  "artists"                  GStrv                 : Read / Write
  "authors"                  GStrv                 : Read / Write
  "comments"                 gchararray            : Read / Write
  "copyright"                gchararray            : Read / Write
  "documenters"              GStrv                 : Read / Write
  "license"                  gchararray            : Read / Write
  "logo"                     GdkPixbuf             : Read / Write
  "logo-icon-name"           gchararray            : Read / Write
  "name"                     gchararray            : Read / Write
  "translator-credits"       gchararray            : Read / Write
  "version"                  gchararray            : Read / Write
  "website"                  gchararray            : Read / Write
  "website-label"            gchararray            : Read / Write
  "wrap-license"             gboolean              : Read / Write

Description

The GtkAboutDialog offers a simple way to display information about a program like its logo, name, copyright, website and license. It is also possible to give credits to the authors, documenters, translators and artists who have worked on the program. An about dialog is typically opened when the user selects the About option from the Help menu. All parts of the dialog are optional.

About dialog often contain links and email addresses. GtkAboutDialog supports this by offering global hooks, which are called when the user clicks on a link or email address, see gtk_about_dialog_set_email_hook() and gtk_about_dialog_set_url_hook(). Email addresses in the authors, documenters and artists properties are recognized by looking for <user@host>, URLs are recognized by looking for http://url, with url extending to the next space, tab or line break.

To make constructing a GtkAboutDialog as convenient as possible, you can use the function gtk_show_about_dialog() which constructs and shows a dialog and keeps it around so that it can be shown again.

Details

GtkAboutDialog

typedef struct _GtkAboutDialog GtkAboutDialog;

The GtkAboutDialog struct contains only private fields and should not be directly accessed.

gtk_about_dialog_new ()

GtkWidget*          gtk_about_dialog_new                (void);

Creates a new GtkAboutDialog.

Returns : a newly created GtkAboutDialog

Since 2.6

gtk_about_dialog_get_name ()

const gchar*        gtk_about_dialog_get_name           (GtkAboutDialog *about);

Returns the program name displayed in the about dialog.

about : | a GtkAboutDialog
Returns : | The program name. The string is owned by the about dialog and must not be modified.

Since 2.6

gtk_about_dialog_set_name ()

void                gtk_about_dialog_set_name           (GtkAboutDialog *about,
                                                         const gchar *name);

Sets the name to display in the about dialog. If this is not set, it defaults to g_get_application_name().

about : | a GtkAboutDialog
name : | the program name

Since 2.6

gtk_about_dialog_get_version ()

const gchar*        gtk_about_dialog_get_version        (GtkAboutDialog *about);

Returns the version string.

about : | a GtkAboutDialog
Returns : | The version string. The string is owned by the about dialog and must not be modified.

Since 2.6

gtk_about_dialog_set_version ()

void                gtk_about_dialog_set_version        (GtkAboutDialog *about,
                                                         const gchar *version);

Sets the version string to display in the about dialog.

about : | a GtkAboutDialog
version : | the version string

Since 2.6

gtk_about_dialog_get_copyright ()

const gchar*        gtk_about_dialog_get_copyright      (GtkAboutDialog *about);

Returns the copyright string.

about : | a GtkAboutDialog
Returns : | The copyright string. The string is owned by the about dialog and must not be modified.

Since 2.6

gtk_about_dialog_set_copyright ()

void                gtk_about_dialog_set_copyright      (GtkAboutDialog *about,
                                                         const gchar *copyright);

Sets the copyright string to display in the about dialog. This should be a short string of one or two lines.

about : | a GtkAboutDialog
copyright : | the copyright string

Since 2.6

gtk_about_dialog_get_comments ()

const gchar*        gtk_about_dialog_get_comments       (GtkAboutDialog *about);

Returns the comments string.

about : | a GtkAboutDialog
Returns : | The comments. The string is owned by the about dialog and must not be modified.

Since 2.6

gtk_about_dialog_set_comments ()

void                gtk_about_dialog_set_comments       (GtkAboutDialog *about,
                                                         const gchar *comments);

Sets the comments string to display in the about dialog. This should be a short string of one or two lines.

about : | a GtkAboutDialog
comments : | a comments string

Since 2.6

gtk_about_dialog_get_license ()

const gchar*        gtk_about_dialog_get_license        (GtkAboutDialog *about);

Returns the license information.

about : | a GtkAboutDialog
Returns : | The license information. The string is owned by the about dialog and must not be modified.

Since 2.6

gtk_about_dialog_set_license ()

void                gtk_about_dialog_set_license        (GtkAboutDialog *about,
                                                         const gchar *license);

Sets the license information to be displayed in the secondary license dialog. If license is NULL, the license button is hidden.

about : | a GtkAboutDialog
license : | the license information or NULL

Since 2.6

gtk_about_dialog_get_wrap_license ()

gboolean            gtk_about_dialog_get_wrap_license   (GtkAboutDialog *about);

Returns whether the license text in about is automatically wrapped.

about : | a GtkAboutDialog
Returns : | TRUE if the license text is wrapped

Since 2.8

gtk_about_dialog_set_wrap_license ()

void                gtk_about_dialog_set_wrap_license   (GtkAboutDialog *about,
                                                         gboolean wrap_license);

Sets whether the license text in about is automatically wrapped.

about : | a GtkAboutDialog
wrap_license : | whether to wrap the license

Since 2.8

gtk_about_dialog_get_website ()

const gchar*        gtk_about_dialog_get_website        (GtkAboutDialog *about);

Returns the website URL.

about : | a GtkAboutDialog
Returns : | The website URL. The string is owned by the about dialog and must not be modified.

Since 2.6

gtk_about_dialog_set_website ()

void                gtk_about_dialog_set_website        (GtkAboutDialog *about,
                                                         const gchar *website);

Sets the URL to use for the website link.

about : | a GtkAboutDialog
website : | a URL string starting with "http://"

Since 2.6

gtk_about_dialog_get_website_label ()

const gchar*        gtk_about_dialog_get_website_label  (GtkAboutDialog *about);

Returns the label used for the website link.

about : | a GtkAboutDialog
Returns : | The label used for the website link. The string is owned by the about dialog and must not be modified.

Since 2.6

gtk_about_dialog_set_website_label ()

void                gtk_about_dialog_set_website_label  (GtkAboutDialog *about,
                                                         const gchar *website_label);

Sets the label to be used for the website link. It defaults to the website URL.

about : | a GtkAboutDialog
website_label : | the label used for the website link

Since 2.6

gtk_about_dialog_get_authors ()

const gchar* const * gtk_about_dialog_get_authors       (GtkAboutDialog *about);

Returns the string which are displayed in the authors tab of the secondary credits dialog.

about : | a GtkAboutDialog
Returns : | A NULL-terminated string array containing the authors. The array is owned by the about dialog and must not be modified.

Since 2.6

gtk_about_dialog_set_authors ()

void                gtk_about_dialog_set_authors        (GtkAboutDialog *about,
                                                         const gchar **authors);

Sets the strings which are displayed in the authors tab of the secondary credits dialog.

about : | a GtkAboutDialog
authors : | a NULL-terminated array of strings

Since 2.6

gtk_about_dialog_get_artists ()

const gchar* const * gtk_about_dialog_get_artists       (GtkAboutDialog *about);

Returns the string which are displayed in the artists tab of the secondary credits dialog.

about : | a GtkAboutDialog
Returns : | A NULL-terminated string array containing the artists. The array is owned by the about dialog and must not be modified.

Since 2.6

gtk_about_dialog_set_artists ()

void                gtk_about_dialog_set_artists        (GtkAboutDialog *about,
                                                         const gchar **artists);

Sets the strings which are displayed in the artists tab of the secondary credits dialog.

about : | a GtkAboutDialog
artists : | a NULL-terminated array of strings

Since 2.6

gtk_about_dialog_get_documenters ()

const gchar* const * gtk_about_dialog_get_documenters   (GtkAboutDialog *about);

Returns the string which are displayed in the documenters tab of the secondary credits dialog.

about : | a GtkAboutDialog
Returns : | A NULL-terminated string array containing the documenters. The array is owned by the about dialog and must not be modified.

Since 2.6

gtk_about_dialog_set_documenters ()

void                gtk_about_dialog_set_documenters    (GtkAboutDialog *about,
                                                         const gchar **documenters);

Sets the strings which are displayed in the documenters tab of the secondary credits dialog.

about : | a GtkAboutDialog
documenters : | a NULL-terminated array of strings

Since 2.6

gtk_about_dialog_get_translator_credits ()

const gchar*        gtk_about_dialog_get_translator_credits
                                                        (GtkAboutDialog *about);

Returns the translator credits string which is displayed in the translators tab of the secondary credits dialog.

about : | a GtkAboutDialog
Returns : | The translator credits string. The string is owned by the about dialog and must not be modified.

Since 2.6

gtk_about_dialog_set_translator_credits ()

void                gtk_about_dialog_set_translator_credits
                                                        (GtkAboutDialog *about,
                                                         const gchar *translator_credits);

Sets the translator credits string which is displayed in the translators tab of the secondary credits dialog.

The intended use for this string is to display the translator of the language which is currently used in the user interface. Using gettext(), a simple way to achieve that is to mark the string for translation:

 gtk_about_dialog_set_translator_credits (about, _("translator-credits"));

It is a good idea to use the customary msgid "translator-credits" for this purpose, since translators will already know the purpose of that msgid, and since GtkAboutDialog will detect if "translator-credits" is untranslated and hide the tab.

about : | a GtkAboutDialog
translator_credits : | the translator credits

Since 2.6

gtk_about_dialog_get_logo ()

GdkPixbuf*          gtk_about_dialog_get_logo           (GtkAboutDialog *about);

Returns the pixbuf displayed as logo in the about dialog.

about : | a GtkAboutDialog
Returns : | the pixbuf displayed as logo. The pixbuf is owned by the about dialog. If you want to keep a reference to it, you have to call g_object_ref() on it.

Since 2.6

gtk_about_dialog_set_logo ()

void                gtk_about_dialog_set_logo           (GtkAboutDialog *about,
                                                         GdkPixbuf *logo);

Sets the pixbuf to be displayed as logo in the about dialog. If it is NULL, the default window icon set with gtk_window_set_default_icon() will be used.

about : | a GtkAboutDialog
logo : | a GdkPixbuf, or NULL

Since 2.6

gtk_about_dialog_get_logo_icon_name ()

const gchar*        gtk_about_dialog_get_logo_icon_name (GtkAboutDialog *about);

Returns the icon name displayed as logo in the about dialog.

about : | a GtkAboutDialog
Returns : | the icon name displayed as logo. The string is owned by the dialog. If you want to keep a reference to it, you have to call g_strdup() on it.

Since 2.6

gtk_about_dialog_set_logo_icon_name ()

void                gtk_about_dialog_set_logo_icon_name (GtkAboutDialog *about,
                                                         const gchar *icon_name);

Sets the pixbuf to be displayed as logo in the about dialog. If it is NULL, the default window icon set with gtk_window_set_default_icon() will be used.

about : | a GtkAboutDialog
icon_name : | an icon name, or NULL

Since 2.6

GtkAboutDialogActivateLinkFunc ()

void                (*GtkAboutDialogActivateLinkFunc)   (GtkAboutDialog *about,
                                                         const gchar *link,
                                                         gpointer data);

The type of a function which is called when a URL or email link is activated.

about : | the GtkAboutDialog in which the link was activated
link : | the URL or email address to whiche the activated link points
data : | user data that was passed when the function was registered with gtk_about_dialog_set_email_hook() or gtk_about_dialog_set_url_hook()

gtk_about_dialog_set_email_hook ()

GtkAboutDialogActivateLinkFunc gtk_about_dialog_set_email_hook
                                                        (GtkAboutDialogActivateLinkFunc func,
                                                         gpointer data,
                                                         GDestroyNotify destroy);

Installs a global function to be called whenever the user activates an email link in an about dialog.

func : | a function to call when an email link is activated.
data : | data to pass to func
destroy : | GDestroyNotify for data
Returns : | the previous email hook.

Since 2.6

gtk_about_dialog_set_url_hook ()

GtkAboutDialogActivateLinkFunc gtk_about_dialog_set_url_hook
                                                        (GtkAboutDialogActivateLinkFunc func,
                                                         gpointer data,
                                                         GDestroyNotify destroy);

Installs a global function to be called whenever the user activates a URL link in an about dialog.

func : | a function to call when a URL link is activated.
data : | data to pass to func
destroy : | GDestroyNotify for data
Returns : | the previous URL hook.

Since 2.6

gtk_show_about_dialog ()

void                gtk_show_about_dialog               (GtkWindow *parent,
                                                         const gchar *first_property_name,
                                                         ...);

This is a convenience function for showing an application's about box. The constructed dialog is associated with the parent window and reused for future invocations of this function.

parent : | transient parent, or NULL for none
first_property_name : | the name of the first property
... : | value of first property, followed by more properties, NULL-terminated

Since 2.6

Property Details

The "artists" property

  "artists"                  GStrv                 : Read / Write

The people who contributed artwork to the program, as a NULL-terminated array of strings. Each string may contain email addresses and URLs, which will be displayed as links, see the introduction for more details.

Since 2.6

The "authors" property

  "authors"                  GStrv                 : Read / Write

The authors of the program, as a NULL-terminated array of strings. Each string may contain email addresses and URLs, which will be displayed as links, see the introduction for more details.

Since 2.6

The "comments" property

  "comments"                 gchararray            : Read / Write

Comments about the program. This string is displayed in a label in the main dialog, thus it should be a short explanation of the main purpose of the program, not a detailed list of features.

Default value: NULL

Since 2.6

The "copyright" property

  "copyright"                gchararray            : Read / Write

Copyright information for the program.

Default value: NULL

Since 2.6

The "documenters" property

  "documenters"              GStrv                 : Read / Write

The people documenting the program, as a NULL-terminated array of strings. Each string may contain email addresses and URLs, which will be displayed as links, see the introduction for more details.

Since 2.6

The "license" property

  "license"                  gchararray            : Read / Write

The license of the program. This string is displayed in a text view in a secondary dialog, therefore it is fine to use a long multi-paragraph text. Note that the text is only wrapped in the text view if the "wrap-license" property is set to TRUE; otherwise the text itself must contain the intended linebreaks.

Default value: NULL

Since 2.6

The "logo" property

  "logo"                     GdkPixbuf             : Read / Write

A logo for the about box. If this is not set, it defaults to gtk_window_get_default_icon_list().

Since 2.6

The "logo-icon-name" property

  "logo-icon-name"           gchararray            : Read / Write

A named icon to use as the logo for the about box. This property overrides the logo property.

Default value: NULL

Since 2.6

The "name" property

  "name"                     gchararray            : Read / Write

The name of the program. If this is not set, it defaults to g_get_application_name().

Default value: NULL

Since 2.6

The "translator-credits" property

  "translator-credits"       gchararray            : Read / Write

Credits to the translators. This string should be marked as translatable. The string may contain email addresses and URLs, which will be displayed as links, see the introduction for more details.

Default value: NULL

Since 2.6

The "version" property

  "version"                  gchararray            : Read / Write

The version of the program.

Default value: NULL

Since 2.6

The "website" property

  "website"                  gchararray            : Read / Write

The URL for the link to the website of the program. This should be a string starting with "http://.

Default value: NULL

Since 2.6

The "website-label" property

  "website-label"            gchararray            : Read / Write

The label for the link to the website of the program. If this is not set, it defaults to the URL specified in the website property.

Default value: NULL

Since 2.6

The "wrap-license" property

  "wrap-license"             gboolean              : Read / Write

Whether to wrap the text in the license dialog.

Default value: FALSE

Since 2.8

See Also

GTK_STOCK_ABOUT


GtkAccelLabel

GtkAccelLabel — A label which displays an accelerator key on the right of the text

Synopsis

#include <gtk/gtk.h>

                    GtkAccelLabel;
GtkWidget*          gtk_accel_label_new                 (const gchar *string);
void                gtk_accel_label_set_accel_closure   (GtkAccelLabel *accel_label,
                                                         GClosure *accel_closure);
GtkWidget*          gtk_accel_label_get_accel_widget    (GtkAccelLabel *accel_label);
void                gtk_accel_label_set_accel_widget    (GtkAccelLabel *accel_label,
                                                         GtkWidget *accel_widget);
guint               gtk_accel_label_get_accel_width     (GtkAccelLabel *accel_label);
gboolean            gtk_accel_label_refetch             (GtkAccelLabel *accel_label);

Object Hierarchy

  GObject
   +----GInitiallyUnowned
         +----GtkObject
               +----GtkWidget
                     +----GtkMisc
                           +----GtkLabel
                                 +----GtkAccelLabel

Implemented Interfaces

GtkAccelLabel implements AtkImplementorIface.

Properties

  "accel-closure"            GClosure              : Read / Write
  "accel-widget"             GtkWidget             : Read / Write

Description

The GtkAccelLabel widget is a subclass of GtkLabel that also displays an accelerator key on the right of the label text, e.g. 'Ctl+S'. It is commonly used in menus to show the keyboard short-cuts for commands.

The accelerator key to display is not set explicitly. Instead, the GtkAccelLabel displays the accelerators which have been added to a particular widget. This widget is set by calling gtk_accel_label_set_accel_widget().

For example, a GtkMenuItem widget may have an accelerator added to emit the "activate" signal when the 'Ctl+S' key combination is pressed. A GtkAccelLabel is created and added to the GtkMenuItem, and gtk_accel_label_set_accel_widget() is called with the GtkMenuItem as the second argument. The GtkAccelLabel will now display 'Ctl+S' after its label.

Note that creating a GtkMenuItem with gtk_menu_item_new_with_label() (or one of the similar functions for GtkCheckMenuItem and GtkRadioMenuItem) automatically adds a GtkAccelLabel to the GtkMenuItem and calls gtk_accel_label_set_accel_widget() to set it up for you.

A GtkAccelLabel will only display accelerators which have GTK_ACCEL_VISIBLE set (see GtkAccelFlags). A GtkAccelLabel can display multiple accelerators and even signal names, though it is almost always used to display just one accelerator key.

Example 7. Creating a simple menu item with an accelerator key.

  GtkWidget *save_item;
  GtkAccelGroup *accel_group;

  /* Create a GtkAccelGroup and add it to the window. */
  accel_group = gtk_accel_group_new ();
  gtk_window_add_accel_group (GTK_WINDOW (window), accel_group);

  /* Create the menu item using the convenience function. */
  save_item = gtk_menu_item_new_with_label ("Save");
  gtk_widget_show (save_item);
  gtk_container_add (GTK_CONTAINER (menu), save_item);

  /* Now add the accelerator to the GtkMenuItem. Note that since we called
     gtk_menu_item_new_with_label() to create the GtkMenuItem the
     GtkAccelLabel is automatically set up to display the GtkMenuItem
     accelerators. We just need to make sure we use GTK_ACCEL_VISIBLE here. */
  gtk_widget_add_accelerator (save_item, "activate", accel_group,
                              GDK_s, GDK_CONTROL_MASK, GTK_ACCEL_VISIBLE);

Details

GtkAccelLabel

typedef struct _GtkAccelLabel GtkAccelLabel;

The GtkAccelLabel struct contains private data only, and should be accessed using the functions below.

gtk_accel_label_new ()

GtkWidget*          gtk_accel_label_new                 (const gchar *string);

Creates a new GtkAccelLabel.

string : | the label string. Must be non-NULL.
Returns : | a new GtkAccelLabel.

gtk_accel_label_set_accel_closure ()

void                gtk_accel_label_set_accel_closure   (GtkAccelLabel *accel_label,
                                                         GClosure *accel_closure);

Sets the closure to be monitored by this accelerator label. The closure must be connected to an accelerator group; see gtk_accel_group_connect().

accel_label : | a GtkAccelLabel
accel_closure : | the closure to monitor for accelerator changes.

gtk_accel_label_get_accel_widget ()

GtkWidget*          gtk_accel_label_get_accel_widget    (GtkAccelLabel *accel_label);

Fetches the widget monitored by this accelerator label. See gtk_accel_label_set_accel_widget().

accel_label : | a GtkAccelLabel
Returns : | the object monitored by the accelerator label, or NULL.

gtk_accel_label_set_accel_widget ()

void                gtk_accel_label_set_accel_widget    (GtkAccelLabel *accel_label,
                                                         GtkWidget *accel_widget);

Sets the widget to be monitored by this accelerator label.

accel_label : | a GtkAccelLabel
accel_widget : | the widget to be monitored.

gtk_accel_label_get_accel_width ()

guint               gtk_accel_label_get_accel_width     (GtkAccelLabel *accel_label);

Returns the width needed to display the accelerator key(s). This is used by menus to align all of the GtkMenuItem widgets, and shouldn't be needed by applications.

accel_label : | a GtkAccelLabel.
Returns : | the width needed to display the accelerator key(s).

gtk_accel_label_refetch ()

gboolean            gtk_accel_label_refetch             (GtkAccelLabel *accel_label);

Recreates the string representing the accelerator keys. This should not be needed since the string is automatically updated whenever accelerators are added or removed from the associated widget.

accel_label : | a GtkAccelLabel.
Returns : | always returns FALSE.

Property Details

The "accel-closure" property

  "accel-closure"            GClosure              : Read / Write

The closure to be monitored for accelerator changes.

The "accel-widget" property

  "accel-widget"             GtkWidget             : Read / Write

The widget to be monitored for accelerator changes.

See Also

Keyboard Accelerators | installing and using keyboard short-cuts.
GtkItemFactory | an easier way to create menus.


GtkAccessible

GtkAccessible — Accessibility support for widgets

Synopsis

#include <gtk/gtk.h>

                    GtkAccessible;
void                gtk_accessible_connect_widget_destroyed
                                                        (GtkAccessible *accessible);

Object Hierarchy

  GObject
   +----AtkObject
         +----GtkAccessible

Description

Details

GtkAccessible

typedef struct _GtkAccessible GtkAccessible;

gtk_accessible_connect_widget_destroyed ()

void                gtk_accessible_connect_widget_destroyed
                                                        (GtkAccessible *accessible);

This function specifies the callback function to be called when the widget corresponding to a GtkAccessible is destroyed.

accessible : a GtkAccessible


GtkAction

GtkAction — An action which can be triggered by a menu or toolbar item

Synopsis

#include <gtk/gtk.h>

                    GtkAction;
GtkAction*          gtk_action_new                      (const gchar *name,
                                                         const gchar *label,
                                                         const gchar *tooltip,
                                                         const gchar *stock_id);
const gchar*        gtk_action_get_name                 (GtkAction *action);
gboolean            gtk_action_is_sensitive             (GtkAction *action);
gboolean            gtk_action_get_sensitive            (GtkAction *action);
void                gtk_action_set_sensitive            (GtkAction *action,
                                                         gboolean sensitive);
gboolean            gtk_action_is_visible               (GtkAction *action);
gboolean            gtk_action_get_visible              (GtkAction *action);
void                gtk_action_set_visible              (GtkAction *action,
                                                         gboolean visible);
void                gtk_action_activate                 (GtkAction *action);
GtkWidget*          gtk_action_create_icon              (GtkAction *action,
                                                         GtkIconSize icon_size);
GtkWidget*          gtk_action_create_menu_item         (GtkAction *action);
GtkWidget*          gtk_action_create_tool_item         (GtkAction *action);
void                gtk_action_connect_proxy            (GtkAction *action,
                                                         GtkWidget *proxy);
void                gtk_action_disconnect_proxy         (GtkAction *action,
                                                         GtkWidget *proxy);
GSList*             gtk_action_get_proxies              (GtkAction *action);
void                gtk_action_connect_accelerator      (GtkAction *action);
void                gtk_action_disconnect_accelerator   (GtkAction *action);
void                gtk_action_block_activate_from      (GtkAction *action,
                                                         GtkWidget *proxy);
void                gtk_action_unblock_activate_from    (GtkAction *action,
                                                         GtkWidget *proxy);
const gchar*        gtk_action_get_accel_path           (GtkAction *action);
void                gtk_action_set_accel_path           (GtkAction *action,
                                                         const gchar *accel_path);
GClosure*           gtk_action_get_accel_closure        (GtkAction *action);
void                gtk_action_set_accel_group          (GtkAction *action,
                                                         GtkAccelGroup *accel_group);

Object Hierarchy

  GObject
   +----GtkAction
         +----GtkToggleAction

Properties

  "action-group"             GtkActionGroup        : Read / Write
  "hide-if-empty"            gboolean              : Read / Write
  "icon-name"                gchararray            : Read / Write
  "is-important"             gboolean              : Read / Write
  "label"                    gchararray            : Read / Write
  "name"                     gchararray            : Read / Write / Construct Only
  "sensitive"                gboolean              : Read / Write
  "short-label"              gchararray            : Read / Write
  "stock-id"                 gchararray            : Read / Write
  "tooltip"                  gchararray            : Read / Write
  "visible"                  gboolean              : Read / Write
  "visible-horizontal"       gboolean              : Read / Write
  "visible-overflown"        gboolean              : Read / Write
  "visible-vertical"         gboolean              : Read / Write

Signals

  "activate"                                       : Run First / No Recursion

Description

Actions represent operations that the user can be perform, along with some information how it should be presented in the interface. Each action provides methods to create icons, menu items and toolbar items representing itself.

As well as the callback that is called when the action gets activated, the following also gets associated with the action:

  • a name (not translated, for path lookup)

  • a label (translated, for display)

  • an accelerator

  • whether label indicates a stock id

  • a tooltip (optional, translated)

  • a toolbar label (optional, shorter than label)

The action will also have some state information:

  • visible (shown/hidden)

  • sensitive (enabled/disabled)

Apart from regular actions, there are toggle actions, which can be toggled between two states and radio actions, of which only one in a group can be in the "active" state. Other actions can be implemented as GtkAction subclasses.

Each action can have one or more proxy menu item, toolbar button or other proxy widgets. Proxies mirror the state of the action (text label, tooltip, icon, visible, sensitive, etc), and should change when the action's state changes. When the proxy is activated, it should activate its action.

Details

GtkAction

typedef struct _GtkAction GtkAction;

The GtkAction struct contains only private members and should not be accessed directly.

gtk_action_new ()

GtkAction*          gtk_action_new                      (const gchar *name,
                                                         const gchar *label,
                                                         const gchar *tooltip,
                                                         const gchar *stock_id);

Creates a new GtkAction object. To add the action to a GtkActionGroup and set the accelerator for the action, call gtk_action_group_add_action_with_accel(). See the section called “UI Definitions” for information on allowed action names.

name : | A unique name for the action
label : | the label displayed in menu items and on buttons
tooltip : | a tooltip for the action
stock_id : | the stock icon to display in widgets representing the action
Returns : | a new GtkAction

Since 2.4

gtk_action_get_name ()

const gchar*        gtk_action_get_name                 (GtkAction *action);

Returns the name of the action.

action : | the action object
Returns : | the name of the action. The string belongs to GTK+ and should not be freed.

Since 2.4

gtk_action_is_sensitive ()

gboolean            gtk_action_is_sensitive             (GtkAction *action);

Returns whether the action is effectively sensitive.

action : | the action object
Returns : | TRUE if the action and its associated action group are both sensitive.

Since 2.4

gtk_action_get_sensitive ()

gboolean            gtk_action_get_sensitive            (GtkAction *action);

Returns whether the action itself is sensitive. Note that this doesn't necessarily mean effective sensitivity. See gtk_action_is_sensitive() for that.

action : | the action object
Returns : | TRUE if the action itself is sensitive.

Since 2.4

gtk_action_set_sensitive ()

void                gtk_action_set_sensitive            (GtkAction *action,
                                                         gboolean sensitive);

Sets the ::sensitive property of the action to sensitive. Note that this doesn't necessarily mean effective sensitivity. See gtk_action_is_sensitive() for that.

action : | the action object
sensitive : | TRUE to make the action sensitive

Since 2.6

gtk_action_is_visible ()

gboolean            gtk_action_is_visible               (GtkAction *action);

Returns whether the action is effectively visible.

action : | the action object
Returns : | TRUE if the action and its associated action group are both visible.

Since 2.4

gtk_action_get_visible ()

gboolean            gtk_action_get_visible              (GtkAction *action);

Returns whether the action itself is visible. Note that this doesn't necessarily mean effective visibility. See gtk_action_is_sensitive() for that.

action : | the action object
Returns : | TRUE if the action itself is visible.

Since 2.4

gtk_action_set_visible ()

void                gtk_action_set_visible              (GtkAction *action,
                                                         gboolean visible);

Sets the ::visible property of the action to visible. Note that this doesn't necessarily mean effective visibility. See gtk_action_is_visible() for that.

action : | the action object
visible : | TRUE to make the action visible

Since 2.6

gtk_action_activate ()

void                gtk_action_activate                 (GtkAction *action);

Emits the "activate" signal on the specified action, if it isn't insensitive. This gets called by the proxy widgets when they get activated.

It can also be used to manually activate an action.

action : the action object

Since 2.4

gtk_action_create_icon ()

GtkWidget*          gtk_action_create_icon              (GtkAction *action,
                                                         GtkIconSize icon_size);

This function is intended for use by action implementations to create icons displayed in the proxy widgets.

action : | the action object
icon_size : | the size of the icon that should be created.
Returns : | a widget that displays the icon for this action.

Since 2.4

gtk_action_create_menu_item ()

GtkWidget*          gtk_action_create_menu_item         (GtkAction *action);

Creates a menu item widget that proxies for the given action.

action : | the action object
Returns : | a menu item connected to the action.

Since 2.4

gtk_action_create_tool_item ()

GtkWidget*          gtk_action_create_tool_item         (GtkAction *action);

Creates a toolbar item widget that proxies for the given action.

action : | the action object
Returns : | a toolbar item connected to the action.

Since 2.4

gtk_action_connect_proxy ()

void                gtk_action_connect_proxy            (GtkAction *action,
                                                         GtkWidget *proxy);

Connects a widget to an action object as a proxy. Synchronises various properties of the action with the widget (such as label text, icon, tooltip, etc), and attaches a callback so that the action gets activated when the proxy widget does.

If the widget is already connected to an action, it is disconnected first.

action : | the action object
proxy : | the proxy widget

Since 2.4

gtk_action_disconnect_proxy ()

void                gtk_action_disconnect_proxy         (GtkAction *action,
                                                         GtkWidget *proxy);

Disconnects a proxy widget from an action. Does not destroy the widget, however.

action : | the action object
proxy : | the proxy widget

Since 2.4

gtk_action_get_proxies ()

GSList*             gtk_action_get_proxies              (GtkAction *action);

Returns the proxy widgets for an action. See also gtk_widget_get_action().

action : | the action object
Returns : | a GSList of proxy widgets. The list is owned by GTK+ and must not be modified.

Since 2.4

gtk_action_connect_accelerator ()

void                gtk_action_connect_accelerator      (GtkAction *action);

Installs the accelerator for action if action has an accel path and group. See gtk_action_set_accel_path() and gtk_action_set_accel_group()

Since multiple proxies may independently trigger the installation of the accelerator, the action counts the number of times this function has been called and doesn't remove the accelerator until gtk_action_disconnect_accelerator() has been called as many times.

action : a GtkAction

Since 2.4

gtk_action_disconnect_accelerator ()

void                gtk_action_disconnect_accelerator   (GtkAction *action);

Undoes the effect of one call to gtk_action_connect_accelerator().

action : a GtkAction

Since 2.4

gtk_action_block_activate_from ()

void                gtk_action_block_activate_from      (GtkAction *action,
                                                         GtkWidget *proxy);

Disables calls to the gtk_action_activate() function by signals on the given proxy widget. This is used to break notification loops for things like check or radio actions.

This function is intended for use by action implementations.

action : | the action object
proxy : | a proxy widget

Since 2.4

gtk_action_unblock_activate_from ()

void                gtk_action_unblock_activate_from    (GtkAction *action,
                                                         GtkWidget *proxy);

Re-enables calls to the gtk_action_activate() function by signals on the given proxy widget. This undoes the blocking done by gtk_action_block_activate_from().

This function is intended for use by action implementations.

action : | the action object
proxy : | a proxy widget

Since 2.4

gtk_action_get_accel_path ()

const gchar*        gtk_action_get_accel_path           (GtkAction *action);

Returns the accel path for this action.

action : | the action object
Returns : | the accel path for this action, or NULL if none is set. The returned string is owned by GTK+ and must not be freed or modified.

Since 2.6

gtk_action_set_accel_path ()

void                gtk_action_set_accel_path           (GtkAction *action,
                                                         const gchar *accel_path);

Sets the accel path for this action. All proxy widgets associated with the action will have this accel path, so that their accelerators are consistent.

action : | the action object
accel_path : | the accelerator path

Since 2.4

gtk_action_get_accel_closure ()

GClosure*           gtk_action_get_accel_closure        (GtkAction *action);

Returns the accel closure for this action.

action : | the action object
Returns : | the accel closure for this action. The returned closure is owned by GTK+ and must not be unreffed or modified.

Since 2.8

gtk_action_set_accel_group ()

void                gtk_action_set_accel_group          (GtkAction *action,
                                                         GtkAccelGroup *accel_group);

Sets the GtkAccelGroup in which the accelerator for this action will be installed.

action : | the action object
accel_group : | a GtkAccelGroup or NULL

Since 2.4

Property Details

The "action-group" property

  "action-group"             GtkActionGroup        : Read / Write

The GtkActionGroup this GtkAction is associated with, or NULL (for internal use).

The "hide-if-empty" property

  "hide-if-empty"            gboolean              : Read / Write

When TRUE, empty menu proxies for this action are hidden.

Default value: TRUE

The "icon-name" property

  "icon-name"                gchararray            : Read / Write

The name of the icon from the icon theme. Note that the stock icon is preferred, if the ::stock-id property holds the id of an existing stock icon.

Default value: NULL

Since 2.10

The "is-important" property

  "is-important"             gboolean              : Read / Write

Whether the action is considered important. When TRUE, toolitem proxies for this action show text in GTK_TOOLBAR_BOTH_HORIZ mode.

Default value: FALSE

The "label" property

  "label"                    gchararray            : Read / Write

The label used for menu items and buttons that activate this action.

Default value: NULL

The "name" property

  "name"                     gchararray            : Read / Write / Construct Only

A unique name for the action.

Default value: NULL

The "sensitive" property

  "sensitive"                gboolean              : Read / Write

Whether the action is enabled.

Default value: TRUE

The "short-label" property

  "short-label"              gchararray            : Read / Write

A shorter label that may be used on toolbar buttons.

Default value: NULL

The "stock-id" property

  "stock-id"                 gchararray            : Read / Write

The stock icon displayed in widgets representing this action.

Default value: NULL

The "tooltip" property

  "tooltip"                  gchararray            : Read / Write

A tooltip for this action.

Default value: NULL

The "visible" property

  "visible"                  gboolean              : Read / Write

Whether the action is visible.

Default value: TRUE

The "visible-horizontal" property

  "visible-horizontal"       gboolean              : Read / Write

Whether the toolbar item is visible when the toolbar is in a horizontal orientation.

Default value: TRUE

The "visible-overflown" property

  "visible-overflown"        gboolean              : Read / Write

When TRUE, toolitem proxies for this action are represented in the toolbar overflow menu.

Default value: TRUE

Since 2.6

The "visible-vertical" property

  "visible-vertical"         gboolean              : Read / Write

Whether the toolbar item is visible when the toolbar is in a vertical orientation.

Default value: TRUE

Signal Details

The "activate" signal

void                user_function                      (GtkAction *action,
                                                        gpointer   user_data)      : Run First / No Recursion

The "activate" signal is emitted when the action is activated.

action : | the GtkAction
user_data : | user data set when the signal handler was connected.

Since 2.4

See Also

GtkActionGroup, GtkUIManager


GtkActionGroup

GtkActionGroup — A group of actions

Synopsis

#include <gtk/gtk.h>

                    GtkActionGroup;
GtkActionGroup*     gtk_action_group_new                (const gchar *name);
const gchar*        gtk_action_group_get_name           (GtkActionGroup *action_group);
gboolean            gtk_action_group_get_sensitive      (GtkActionGroup *action_group);
void                gtk_action_group_set_sensitive      (GtkActionGroup *action_group,
                                                         gboolean sensitive);
gboolean            gtk_action_group_get_visible        (GtkActionGroup *action_group);
void                gtk_action_group_set_visible        (GtkActionGroup *action_group,
                                                         gboolean visible);
GtkAction*          gtk_action_group_get_action         (GtkActionGroup *action_group,
                                                         const gchar *action_name);
GList*              gtk_action_group_list_actions       (GtkActionGroup *action_group);
void                gtk_action_group_add_action         (GtkActionGroup *action_group,
                                                         GtkAction *action);
void                gtk_action_group_add_action_with_accel
                                                        (GtkActionGroup *action_group,
                                                         GtkAction *action,
                                                         const gchar *accelerator);
void                gtk_action_group_remove_action      (GtkActionGroup *action_group,
                                                         GtkAction *action);
                    GtkActionEntry;
void                gtk_action_group_add_actions        (GtkActionGroup *action_group,
                                                         const GtkActionEntry *entries,
                                                         guint n_entries,
                                                         gpointer user_data);
void                gtk_action_group_add_actions_full   (GtkActionGroup *action_group,
                                                         const GtkActionEntry *entries,
                                                         guint n_entries,
                                                         gpointer user_data,
                                                         GDestroyNotify destroy);
                    GtkToggleActionEntry;
void                gtk_action_group_add_toggle_actions (GtkActionGroup *action_group,
                                                         const GtkToggleActionEntry *entries,
                                                         guint n_entries,
                                                         gpointer user_data);
void                gtk_action_group_add_toggle_actions_full
                                                        (GtkActionGroup *action_group,
                                                         const GtkToggleActionEntry *entries,
                                                         guint n_entries,
                                                         gpointer user_data,
                                                         GDestroyNotify destroy);
                    GtkRadioActionEntry;
void                gtk_action_group_add_radio_actions  (GtkActionGroup *action_group,
                                                         const GtkRadioActionEntry *entries,
                                                         guint n_entries,
                                                         gint value,
                                                         GCallback on_change,
                                                         gpointer user_data);
void                gtk_action_group_add_radio_actions_full
                                                        (GtkActionGroup *action_group,
                                                         const GtkRadioActionEntry *entries,
                                                         guint n_entries,
                                                         gint value,
                                                         GCallback on_change,
                                                         gpointer user_data,
                                                         GDestroyNotify destroy);
void                gtk_action_group_set_translate_func (GtkActionGroup *action_group,
                                                         GtkTranslateFunc func,
                                                         gpointer data,
                                                         GtkDestroyNotify notify);
void                gtk_action_group_set_translation_domain
                                                        (GtkActionGroup *action_group,
                                                         const gchar *domain);
const gchar*        gtk_action_group_translate_string   (GtkActionGroup *action_group,
                                                         const gchar *string);

Object Hierarchy

  GObject
   +----GtkActionGroup

Properties

  "name"                     gchararray            : Read / Write / Construct Only
  "sensitive"                gboolean              : Read / Write
  "visible"                  gboolean              : Read / Write

Signals

  "connect-proxy"
  "disconnect-proxy"
  "post-activate"
  "pre-activate"

Description

Actions are organised into groups. An action group is essentially a map from names to GtkAction objects.

All actions that would make sense to use in a particular context should be in a single group. Multiple action groups may be used for a particular user interface. In fact, it is expected that most nontrivial applications will make use of multiple groups. For example, in an application that can edit multiple documents, one group holding global actions (e.g. quit, about, new), and one group per document holding actions that act on that document (eg. save, cut/copy/paste, etc). Each window's menus would be constructed from a combination of two action groups.

Accelerators are handled by the GTK+ accelerator map. All actions are assigned an accelerator path (which normally has the form <Actions>/group-name/action-name) and a shortcut is associated with this accelerator path. All menuitems and toolitems take on this accelerator path. The GTK+ accelerator map code makes sure that the correct shortcut is displayed next to the menu item.

Details

GtkActionGroup

typedef struct _GtkActionGroup GtkActionGroup;

The GtkActionGroup struct contains only private members and should not be accessed directly.

gtk_action_group_new ()

GtkActionGroup*     gtk_action_group_new                (const gchar *name);

Creates a new GtkActionGroup object. The name of the action group is used when associating keybindings with the actions.

name : | the name of the action group.
Returns : | the new GtkActionGroup

Since 2.4

gtk_action_group_get_name ()

const gchar*        gtk_action_group_get_name           (GtkActionGroup *action_group);

Gets the name of the action group.

action_group : | the action group
Returns : | the name of the action group.

Since 2.4

gtk_action_group_get_sensitive ()

gboolean            gtk_action_group_get_sensitive      (GtkActionGroup *action_group);

Returns TRUE if the group is sensitive. The constituent actions can only be logically sensitive (see gtk_action_is_sensitive()) if they are sensitive (see gtk_action_get_sensitive()) and their group is sensitive.

action_group : | the action group
Returns : | TRUE if the group is sensitive.

Since 2.4

gtk_action_group_set_sensitive ()

void                gtk_action_group_set_sensitive      (GtkActionGroup *action_group,
                                                         gboolean sensitive);

Changes the sensitivity of action_group

action_group : | the action group
sensitive : | new sensitivity

Since 2.4

gtk_action_group_get_visible ()

gboolean            gtk_action_group_get_visible        (GtkActionGroup *action_group);

Returns TRUE if the group is visible. The constituent actions can only be logically visible (see gtk_action_is_visible()) if they are visible (see gtk_action_get_visible()) and their group is visible.

action_group : | the action group
Returns : | TRUE if the group is visible.

Since 2.4

gtk_action_group_set_visible ()

void                gtk_action_group_set_visible        (GtkActionGroup *action_group,
                                                         gboolean visible);

Changes the visible of action_group.

action_group : | the action group
visible : | new visiblity

Since 2.4

gtk_action_group_get_action ()

GtkAction*          gtk_action_group_get_action         (GtkActionGroup *action_group,
                                                         const gchar *action_name);

Looks up an action in the action group by name.

action_group : | the action group
action_name : | the name of the action
Returns : | the action, or NULL if no action by that name exists

Since 2.4

gtk_action_group_list_actions ()

GList*              gtk_action_group_list_actions       (GtkActionGroup *action_group);

Lists the actions in the action group.

action_group : | the action group
Returns : | an allocated list of the action objects in the action group

Since 2.4

gtk_action_group_add_action ()

void                gtk_action_group_add_action         (GtkActionGroup *action_group,
                                                         GtkAction *action);

Adds an action object to the action group. Note that this function does not set up the accel path of the action, which can lead to problems if a user tries to modify the accelerator of a menuitem associated with the action. Therefore you must either set the accel path yourself with gtk_action_set_accel_path(), or use gtk_action_group_add_action_with_accel (..., NULL).

action_group : | the action group
action : | an action

Since 2.4

gtk_action_group_add_action_with_accel ()

void                gtk_action_group_add_action_with_accel
                                                        (GtkActionGroup *action_group,
                                                         GtkAction *action,
                                                         const gchar *accelerator);

Adds an action object to the action group and sets up the accelerator.

If accelerator is NULL, attempts to use the accelerator associated with the stock_id of the action.

Accel paths are set to <Actions>/group-name/action-name.

action_group : | the action group
action : | the action to add
accelerator : | the accelerator for the action, in the format understood by gtk_accelerator_parse(), or "" for no accelerator, or NULL to use the stock accelerator

Since 2.4

gtk_action_group_remove_action ()

void                gtk_action_group_remove_action      (GtkActionGroup *action_group,
                                                         GtkAction *action);

Removes an action object from the action group.

action_group : | the action group
action : | an action

Since 2.4

GtkActionEntry

typedef struct {
  const gchar     *name;
  const gchar     *stock_id;
  const gchar     *label;
  const gchar     *accelerator;
  const gchar     *tooltip;
  GCallback  callback;
} GtkActionEntry;

GtkActionEntry structs are used with gtk_action_group_add_actions() to construct actions.

const gchar *name; | The name of the action.
const gchar *stock_id; | The stock id for the action, or the name of an icon from the icon theme.
const gchar *label; | The label for the action. This field should typically be marked for translation, see gtk_action_group_set_translation_domain().
const gchar *accelerator; | The accelerator for the action, in the format understood by gtk_accelerator_parse().
const gchar *tooltip; | The tooltip for the action. This field should typically be marked for translation, see gtk_action_group_set_translation_domain().
GCallback callback; | The function to call when the action is activated.

gtk_action_group_add_actions ()

void                gtk_action_group_add_actions        (GtkActionGroup *action_group,
                                                         const GtkActionEntry *entries,
                                                         guint n_entries,
                                                         gpointer user_data);

This is a convenience function to create a number of actions and add them to the action group.

The "activate" signals of the actions are connected to the callbacks and their accel paths are set to <Actions>/group-name/action-name.

action_group : | the action group
entries : | an array of action descriptions
n_entries : | the number of entries
user_data : | data to pass to the action callbacks

Since 2.4

gtk_action_group_add_actions_full ()

void                gtk_action_group_add_actions_full   (GtkActionGroup *action_group,
                                                         const GtkActionEntry *entries,
                                                         guint n_entries,
                                                         gpointer user_data,
                                                         GDestroyNotify destroy);

This variant of gtk_action_group_add_actions() adds a GDestroyNotify callback for user_data.

action_group : | the action group
entries : | an array of action descriptions
n_entries : | the number of entries
user_data : | data to pass to the action callbacks
destroy : | destroy notification callback for user_data

Since 2.4

GtkToggleActionEntry

typedef struct {
  const gchar     *name;
  const gchar     *stock_id;
  const gchar     *label;
  const gchar     *accelerator;
  const gchar     *tooltip;
  GCallback  callback;
  gboolean   is_active;
} GtkToggleActionEntry;

GtkToggleActionEntry structs are used with gtk_action_group_add_toggle_actions() to construct toggle actions.

const gchar *name; | The name of the action.
const gchar *stock_id; | The stock id for the action, or the name of an icon from the icon theme.
const gchar *label; | The label for the action. This field should typically be marked for translation, see gtk_action_group_set_translation_domain().
const gchar *accelerator; | The accelerator for the action, in the format understood by gtk_accelerator_parse().
const gchar *tooltip; | The tooltip for the action. This field should typically be marked for translation, see gtk_action_group_set_translation_domain().
GCallback callback; | The function to call when the action is activated.
gboolean is_active; | The initial state of the toggle action.

gtk_action_group_add_toggle_actions ()

void                gtk_action_group_add_toggle_actions (GtkActionGroup *action_group,
                                                         const GtkToggleActionEntry *entries,
                                                         guint n_entries,
                                                         gpointer user_data);

This is a convenience function to create a number of toggle actions and add them to the action group.

The "activate" signals of the actions are connected to the callbacks and their accel paths are set to <Actions>/group-name/action-name.

action_group : | the action group
entries : | an array of toggle action descriptions
n_entries : | the number of entries
user_data : | data to pass to the action callbacks

Since 2.4

gtk_action_group_add_toggle_actions_full ()

void                gtk_action_group_add_toggle_actions_full
                                                        (GtkActionGroup *action_group,
                                                         const GtkToggleActionEntry *entries,
                                                         guint n_entries,
                                                         gpointer user_data,
                                                         GDestroyNotify destroy);

This variant of gtk_action_group_add_toggle_actions() adds a GDestroyNotify callback for user_data.

action_group : | the action group
entries : | an array of toggle action descriptions
n_entries : | the number of entries
user_data : | data to pass to the action callbacks
destroy : | destroy notification callback for user_data

Since 2.4

GtkRadioActionEntry

typedef struct {
  const gchar *name;
  const gchar *stock_id;
  const gchar *label;
  const gchar *accelerator;
  const gchar *tooltip;
  gint   value;
} GtkRadioActionEntry;

GtkRadioActionEntry structs are used with gtk_action_group_add_radio_actions() to construct groups of radio actions.

const gchar *name; | The name of the action.
const gchar *stock_id; | The stock id for the action, or the name of an icon from the icon theme.
const gchar *label; | The label for the action. This field should typically be marked for translation, see gtk_action_group_set_translation_domain().
const gchar *accelerator; | The accelerator for the action, in the format understood by gtk_accelerator_parse().
const gchar *tooltip; | The tooltip for the action. This field should typically be marked for translation, see gtk_action_group_set_translation_domain().
gint value; | The value to set on the radio action. See gtk_radio_action_get_current_value().

gtk_action_group_add_radio_actions ()

void                gtk_action_group_add_radio_actions  (GtkActionGroup *action_group,
                                                         const GtkRadioActionEntry *entries,
                                                         guint n_entries,
                                                         gint value,
                                                         GCallback on_change,
                                                         gpointer user_data);

This is a convenience routine to create a group of radio actions and add them to the action group.

The "changed" signal of the first radio action is connected to the on_change callback and the accel paths of the actions are set to <Actions>/group-name/action-name.

action_group : | the action group
entries : | an array of radio action descriptions
n_entries : | the number of entries
value : | the value of the action to activate initially, or -1 if no action should be activated
on_change : | the callback to connect to the changed signal
user_data : | data to pass to the action callbacks

Since 2.4

gtk_action_group_add_radio_actions_full ()

void                gtk_action_group_add_radio_actions_full
                                                        (GtkActionGroup *action_group,
                                                         const GtkRadioActionEntry *entries,
                                                         guint n_entries,
                                                         gint value,
                                                         GCallback on_change,
                                                         gpointer user_data,
                                                         GDestroyNotify destroy);

This variant of gtk_action_group_add_radio_actions() adds a GDestroyNotify callback for user_data.

action_group : | the action group
entries : | an array of radio action descriptions
n_entries : | the number of entries
value : | the value of the action to activate initially, or -1 if no action should be activated
on_change : | the callback to connect to the changed signal
user_data : | data to pass to the action callbacks
destroy : | destroy notification callback for user_data

Since 2.4

gtk_action_group_set_translate_func ()

void                gtk_action_group_set_translate_func (GtkActionGroup *action_group,
                                                         GtkTranslateFunc func,
                                                         gpointer data,
                                                         GtkDestroyNotify notify);

Sets a function to be used for translating the label and tooltip of GtkActionGroupEntrys added by gtk_action_group_add_actions().

If you're using gettext(), it is enough to set the translation domain with gtk_action_group_set_translation_domain().

action_group : | a GtkActionGroup
func : | a GtkTranslateFunc
data : | data to be passed to func and notify
notify : | a GtkDestroyNotify function to be called when action_group is destroyed and when the translation function is changed again

Since 2.4

gtk_action_group_set_translation_domain ()

void                gtk_action_group_set_translation_domain
                                                        (GtkActionGroup *action_group,
                                                         const gchar *domain);

Sets the translation domain and uses dgettext() for translating the label and tooltip of GtkActionEntrys added by gtk_action_group_add_actions().

If you're not using gettext() for localization, see gtk_action_group_set_translate_func().

action_group : | a GtkActionGroup
domain : | the translation domain to use for dgettext() calls

Since 2.4

gtk_action_group_translate_string ()

const gchar*        gtk_action_group_translate_string   (GtkActionGroup *action_group,
                                                         const gchar *string);

Translates a string using the specified translate_func(). This is mainly intended for language bindings.

action_group : | a GtkActionGroup
string : | a string
Returns : | the translation of string

Since 2.6

Property Details

The "name" property

  "name"                     gchararray            : Read / Write / Construct Only

A name for the action group.

Default value: NULL

The "sensitive" property

  "sensitive"                gboolean              : Read / Write

Whether the action group is enabled.

Default value: TRUE

The "visible" property

  "visible"                  gboolean              : Read / Write

Whether the action group is visible.

Default value: TRUE

Signal Details

The "connect-proxy" signal

void                user_function                      (GtkActionGroup *action_group,
                                                        GtkAction      *action,
                                                        GtkWidget      *proxy,
                                                        gpointer        user_data)

The connect_proxy signal is emitted after connecting a proxy to an action in the group. Note that the proxy may have been connected to a different action before.

This is intended for simple customizations for which a custom action class would be too clumsy, e.g. showing tooltips for menuitems in the statusbar.

GtkUIManager proxies the signal and provides global notification just before any action is connected to a proxy, which is probably more convenient to use.

action_group : | the group
action : | the action
proxy : | the proxy
user_data : | user data set when the signal handler was connected.

Since 2.4

The "disconnect-proxy" signal

void                user_function                      (GtkActionGroup *action_group,
                                                        GtkAction      *action,
                                                        GtkWidget      *proxy,
                                                        gpointer        user_data)

The disconnect_proxy signal is emitted after disconnecting a proxy from an action in the group.

GtkUIManager proxies the signal and provides global notification just before any action is connected to a proxy, which is probably more convenient to use.

action_group : | the group
action : | the action
proxy : | the proxy
user_data : | user data set when the signal handler was connected.

Since 2.4

The "post-activate" signal

void                user_function                      (GtkActionGroup *action_group,
                                                        GtkAction      *action,
                                                        gpointer        user_data)

The post_activate signal is emitted just after the action in the action_group is activated

This is intended for GtkUIManager to proxy the signal and provide global notification just after any action is activated.

action_group : | the group
action : | the action
user_data : | user data set when the signal handler was connected.

Since 2.4

The "pre-activate" signal

void                user_function                      (GtkActionGroup *action_group,
                                                        GtkAction      *action,
                                                        gpointer        user_data)

The pre_activate signal is emitted just before the action in the action_group is activated

This is intended for GtkUIManager to proxy the signal and provide global notification just before any action is activated.

action_group : | the group
action : | the action
user_data : | user data set when the signal handler was connected.

Since 2.4


GtkAdjustment

GtkAdjustment — A GtkObject representing an adjustable bounded value

Synopsis

#include <gtk/gtk.h>

                    GtkAdjustment;
GtkObject*          gtk_adjustment_new                  (gdouble value,
                                                         gdouble lower,
                                                         gdouble upper,
                                                         gdouble step_increment,
                                                         gdouble page_increment,
                                                         gdouble page_size);
gdouble             gtk_adjustment_get_value            (GtkAdjustment *adjustment);
void                gtk_adjustment_set_value            (GtkAdjustment *adjustment,
                                                         gdouble value);
void                gtk_adjustment_clamp_page           (GtkAdjustment *adjustment,
                                                         gdouble lower,
                                                         gdouble upper);
void                gtk_adjustment_changed              (GtkAdjustment *adjustment);
void                gtk_adjustment_value_changed        (GtkAdjustment *adjustment);

Object Hierarchy

  GObject
   +----GInitiallyUnowned
         +----GtkObject
               +----GtkAdjustment

Properties

  "lower"                    gdouble               : Read / Write
  "page-increment"           gdouble               : Read / Write
  "page-size"                gdouble               : Read / Write
  "step-increment"           gdouble               : Read / Write
  "upper"                    gdouble               : Read / Write
  "value"                    gdouble               : Read / Write

Signals

  "changed"                                        : Run First / No Recursion
  "value-changed"                                  : Run First / No Recursion

Description

The GtkAdjustment object represents a value which has an associated lower and upper bound, together with step and page increments, and a page size. It is used within several GTK+ widgets, including GtkSpinButton, GtkViewport, and GtkRange (which is a base class for GtkHScrollbar, GtkVScrollbar, GtkHScale, and GtkVScale).

The GtkAdjustment object does not update the value itself. Instead it is left up to the owner of the GtkAdjustment to control the value.

The owner of the GtkAdjustment typically calls the gtk_adjustment_value_changed() and gtk_adjustment_changed() functions after changing the value and its bounds. This results in the emission of the "value_changed" or "changed" signal respectively.

Details

GtkAdjustment

typedef struct _GtkAdjustment GtkAdjustment;

The GtkAdjustment struct contains the following fields.

gdouble lower; | the minimum value.
gdouble upper; | the maximum value.
gdouble value; | the current value.
gdouble step_increment; | the increment to use to make minor changes to the value. In a GtkScrollbar this increment is used when the mouse is clicked on the arrows at the top and bottom of the scrollbar, to scroll by a small amount.
gdouble page_increment; | the increment to use to make major changes to the value. In a GtkScrollbar this increment is used when the mouse is clicked in the trough, to scroll by a large amount.
gdouble page_size; | the page size. In a GtkScrollbar this is the size of the area which is currently visible.

gtk_adjustment_new ()

GtkObject*          gtk_adjustment_new                  (gdouble value,
                                                         gdouble lower,
                                                         gdouble upper,
                                                         gdouble step_increment,
                                                         gdouble page_increment,
                                                         gdouble page_size);

Creates a new GtkAdjustment.

value : | the initial value.
lower : | the minimum value.
upper : | the maximum value.
step_increment : | the step increment.
page_increment : | the page increment.
page_size : | the page size.
Returns : | a new GtkAdjustment.

gtk_adjustment_get_value ()

gdouble             gtk_adjustment_get_value            (GtkAdjustment *adjustment);

Gets the current value of the adjustment. See gtk_adjustment_set_value().

adjustment : | a GtkAdjustment
Returns : | The current value of the adjustment.

gtk_adjustment_set_value ()

void                gtk_adjustment_set_value            (GtkAdjustment *adjustment,
                                                         gdouble value);

Sets the GtkAdjustment value. The value is clamped to lie between adjustment->lower and adjustment->upper.

Note that for adjustments which are used in a GtkScrollbar, the effective range of allowed values goes from adjustment->lower to adjustment->upper - adjustment->page_size.

adjustment : | a GtkAdjustment.
value : | the new value.

gtk_adjustment_clamp_page ()

void                gtk_adjustment_clamp_page           (GtkAdjustment *adjustment,
                                                         gdouble lower,
                                                         gdouble upper);

Updates the GtkAdjustment value to ensure that the range between lower and upper is in the current page (i.e. between value and value + page_size). If the range is larger than the page size, then only the start of it will be in the current page. A "changed" signal will be emitted if the value is changed.

adjustment : | a GtkAdjustment.
lower : | the lower value.
upper : | the upper value.

gtk_adjustment_changed ()

void                gtk_adjustment_changed              (GtkAdjustment *adjustment);

Emits a "changed" signal from the GtkAdjustment. This is typically called by the owner of the GtkAdjustment after it has changed any of the GtkAdjustment fields other than the value.

adjustment : a GtkAdjustment

gtk_adjustment_value_changed ()

void                gtk_adjustment_value_changed        (GtkAdjustment *adjustment);

Emits a "value_changed" signal from the GtkAdjustment. This is typically called by the owner of the GtkAdjustment after it has changed the GtkAdjustment value field.

adjustment : a GtkAdjustment

Property Details

The "lower" property

  "lower"                    gdouble               : Read / Write

The minimum value of the adjustment.

Default value: 0

Since 2.4

The "page-increment" property

  "page-increment"           gdouble               : Read / Write

The page increment of the adjustment.

Default value: 0

Since 2.4

The "page-size" property

  "page-size"                gdouble               : Read / Write

The page size of the adjustment. Note that the page-size is irrelevant and should be set to zero if the adjustment is used for a simple scalar value, e.g. in a GtkSpinButton.

Default value: 0

Since 2.4

The "step-increment" property

  "step-increment"           gdouble               : Read / Write

The step increment of the adjustment.

Default value: 0

Since 2.4

The "upper" property

  "upper"                    gdouble               : Read / Write

The maximum value of the adjustment. Note that values will be restricted by upper - page-size if the page-size property is nonzero.

Default value: 0

Since 2.4

The "value" property

  "value"                    gdouble               : Read / Write

The value of the adjustment.

Default value: 0

Since 2.4

Signal Details

The "changed" signal

void                user_function                      (GtkAdjustment *adjustment,
                                                        gpointer       user_data)       : Run First / No Recursion

Emitted when one or more of the GtkAdjustment fields have been changed, other than the value field.

adjustment : | the object which received the signal.
user_data : | user data set when the signal handler was connected.

The "value-changed" signal

void                user_function                      (GtkAdjustment *adjustment,
                                                        gpointer       user_data)       : Run First / No Recursion

Emitted when the GtkAdjustment value field has been changed.

adjustment : | the object which received the signal.
user_data : | user data set when the signal handler was connected.


GtkAlignment

GtkAlignment — A widget which controls the alignment and size of its child

Synopsis

#include <gtk/gtk.h>

                    GtkAlignment;
GtkWidget*          gtk_alignment_new                   (gfloat xalign,
                                                         gfloat yalign,
                                                         gfloat xscale,
                                                         gfloat yscale);
void                gtk_alignment_set                   (GtkAlignment *alignment,
                                                         gfloat xalign,
                                                         gfloat yalign,
                                                         gfloat xscale,
                                                         gfloat yscale);
void                gtk_alignment_get_padding           (GtkAlignment *alignment,
                                                         guint *padding_top,
                                                         guint *padding_bottom,
                                                         guint *padding_left,
                                                         guint *padding_right);
void                gtk_alignment_set_padding           (GtkAlignment *alignment,
                                                         guint padding_top,
                                                         guint padding_bottom,
                                                         guint padding_left,
                                                         guint padding_right);

Object Hierarchy

  GObject
   +----GInitiallyUnowned
         +----GtkObject
               +----GtkWidget
                     +----GtkContainer
                           +----GtkBin
                                 +----GtkAlignment

Implemented Interfaces

GtkAlignment implements AtkImplementorIface.

Properties

  "bottom-padding"           guint                 : Read / Write
  "left-padding"             guint                 : Read / Write
  "right-padding"            guint                 : Read / Write
  "top-padding"              guint                 : Read / Write
  "xalign"                   gfloat                : Read / Write
  "xscale"                   gfloat                : Read / Write
  "yalign"                   gfloat                : Read / Write
  "yscale"                   gfloat                : Read / Write

Description

The GtkAlignment widget controls the alignment and size of its child widget. It has four settings: xscale, yscale, xalign, and yalign.

The scale settings are used to specify how much the child widget should expand to fill the space allocated to the GtkAlignment. The values can range from 0 (meaning the child doesn't expand at all) to 1 (meaning the child expands to fill all of the available space).

The align settings are used to place the child widget within the available area. The values range from 0 (top or left) to 1 (bottom or right). Of course, if the scale settings are both set to 1, the alignment settings have no effect.

Details

GtkAlignment

typedef struct _GtkAlignment GtkAlignment;

The GtkAlignment struct contains private data only, and should be accessed using the functions below.

gtk_alignment_new ()

GtkWidget*          gtk_alignment_new                   (gfloat xalign,
                                                         gfloat yalign,
                                                         gfloat xscale,
                                                         gfloat yscale);

Creates a new GtkAlignment.

xalign : | the horizontal alignment of the child widget, from 0 (left) to 1 (right).
yalign : | the vertical alignment of the child widget, from 0 (top) to 1 (bottom).
xscale : | the amount that the child widget expands horizontally to fill up unused space, from 0 to 1. A value of 0 indicates that the child widget should never expand. A value of 1 indicates that the child widget will expand to fill all of the space allocated for the GtkAlignment.
yscale : | the amount that the child widget expands vertically to fill up unused space, from 0 to 1. The values are similar to xscale.
Returns : | the new GtkAlignment.

gtk_alignment_set ()

void                gtk_alignment_set                   (GtkAlignment *alignment,
                                                         gfloat xalign,
                                                         gfloat yalign,
                                                         gfloat xscale,
                                                         gfloat yscale);

Sets the GtkAlignment values.

alignment : | a GtkAlignment.
xalign : | the horizontal alignment of the child widget, from 0 (left) to 1 (right).
yalign : | the vertical alignment of the child widget, from 0 (top) to 1 (bottom).
xscale : | the amount that the child widget expands horizontally to fill up unused space, from 0 to 1. A value of 0 indicates that the child widget should never expand. A value of 1 indicates that the child widget will expand to fill all of the space allocated for the GtkAlignment.
yscale : | the amount that the child widget expands vertically to fill up unused space, from 0 to 1. The values are similar to xscale.

gtk_alignment_get_padding ()

void                gtk_alignment_get_padding           (GtkAlignment *alignment,
                                                         guint *padding_top,
                                                         guint *padding_bottom,
                                                         guint *padding_left,
                                                         guint *padding_right);

Gets the padding on the different sides of the widget. See gtk_alignment_set_padding().

alignment : | a GtkAlignment
padding_top : | location to store the padding for the top of the widget, or NULL
padding_bottom : | location to store the padding for the bottom of the widget, or NULL
padding_left : | location to store the padding for the left of the widget, or NULL
padding_right : | location to store the padding for the right of the widget, or NULL

Since 2.4

gtk_alignment_set_padding ()

void                gtk_alignment_set_padding           (GtkAlignment *alignment,
                                                         guint padding_top,
                                                         guint padding_bottom,
                                                         guint padding_left,
                                                         guint padding_right);

Sets the padding on the different sides of the widget. The padding adds blank space to the sides of the widget. For instance, this can be used to indent the child widget towards the right by adding padding on the left.

alignment : | a GtkAlignment
padding_top : | the padding at the top of the widget
padding_bottom : | the padding at the bottom of the widget
padding_left : | the padding at the left of the widget
padding_right : | the padding at the right of the widget.

Since 2.4

Property Details

The "bottom-padding" property

  "bottom-padding"           guint                 : Read / Write

The padding to insert at the bottom of the widget.

Allowed values: <= G_MAXINT

Default value: 0

Since 2.4

The "left-padding" property

  "left-padding"             guint                 : Read / Write

The padding to insert at the left of the widget.

Allowed values: <= G_MAXINT

Default value: 0

Since 2.4

The "right-padding" property

  "right-padding"            guint                 : Read / Write

The padding to insert at the right of the widget.

Allowed values: <= G_MAXINT

Default value: 0

Since 2.4

The "top-padding" property

  "top-padding"              guint                 : Read / Write

The padding to insert at the top of the widget.

Allowed values: <= G_MAXINT

Default value: 0

Since 2.4

The "xalign" property

  "xalign"                   gfloat                : Read / Write

Horizontal position of child in available space. 0.0 is left aligned, 1.0 is right aligned.

Allowed values: [0,1]

Default value: 0.5

The "xscale" property

  "xscale"                   gfloat                : Read / Write

If available horizontal space is bigger than needed for the child, how much of it to use for the child. 0.0 means none, 1.0 means all.

Allowed values: [0,1]

Default value: 1

The "yalign" property

  "yalign"                   gfloat                : Read / Write

Vertical position of child in available space. 0.0 is top aligned, 1.0 is bottom aligned.

Allowed values: [0,1]

Default value: 0.5

The "yscale" property

  "yscale"                   gfloat                : Read / Write

If available vertical space is bigger than needed for the child, how much of it to use for the child. 0.0 means none, 1.0 means all.

Allowed values: [0,1]

Default value: 1


GtkArrow

GtkArrow — Displays an arrow

Synopsis

#include <gtk/gtk.h>

                    GtkArrow;
GtkWidget*          gtk_arrow_new                       (GtkArrowType arrow_type,
                                                         GtkShadowType shadow_type);
void                gtk_arrow_set                       (GtkArrow *arrow,
                                                         GtkArrowType arrow_type,
                                                         GtkShadowType shadow_type);

Object Hierarchy

  GObject
   +----GInitiallyUnowned
         +----GtkObject
               +----GtkWidget
                     +----GtkMisc
                           +----GtkArrow

Implemented Interfaces

GtkArrow implements AtkImplementorIface.

Properties

  "arrow-type"               GtkArrowType          : Read / Write
  "shadow-type"              GtkShadowType         : Read / Write

Description

GtkArrow should be used to draw simple arrows that need to point in one of the four cardinal directions (up, down, left, or right). The style of the arrow can be one of shadow in, shadow out, etched in, or etched out. Note that these directions and style types may be ammended in versions of Gtk to come.

GtkArrow will fill any space alloted to it, but since it is inherited from GtkMisc, it can be padded and/or aligned, to fill exactly the space the programmer desires.

Arrows are created with a call to gtk_arrow_new(). The direction or style of an arrow can be changed after creation by using gtk_arrow_set().

Details

GtkArrow

typedef struct _GtkArrow GtkArrow;

The GtkArrow struct containes the following fields. (These fields should be considered read-only. They should never be set by an application.)

gtk_arrow_new ()

GtkWidget*          gtk_arrow_new                       (GtkArrowType arrow_type,
                                                         GtkShadowType shadow_type);

Creates a new arrow widget.

arrow_type : | a valid GtkArrowType.
shadow_type : | a valid GtkShadowType.
Returns : | the new GtkArrow widget.

gtk_arrow_set ()

void                gtk_arrow_set                       (GtkArrow *arrow,
                                                         GtkArrowType arrow_type,
                                                         GtkShadowType shadow_type);

Sets the direction and style of the GtkArrow, arrow.

arrow : | a widget of type GtkArrow.
arrow_type : | a valid GtkArrowType.
shadow_type : | a valid GtkShadowType.

Property Details

The "arrow-type" property

  "arrow-type"               GtkArrowType          : Read / Write

The direction the arrow should point.

Default value: GTK_ARROW_RIGHT

The "shadow-type" property

  "shadow-type"              GtkShadowType         : Read / Write

Appearance of the shadow surrounding the arrow.

Default value: GTK_SHADOW_OUT

See Also

gtk_paint_arrow()

the function used internally to paint the arrow.


GtkAspectFrame

GtkAspectFrame — A frame that constrains its child to a particular aspect ratio

Synopsis

#include <gtk/gtk.h>

                    GtkAspectFrame;
GtkWidget*          gtk_aspect_frame_new                (const gchar *label,
                                                         gfloat xalign,
                                                         gfloat yalign,
                                                         gfloat ratio,
                                                         gboolean obey_child);
void                gtk_aspect_frame_set                (GtkAspectFrame *aspect_frame,
                                                         gfloat xalign,
                                                         gfloat yalign,
                                                         gfloat ratio,
                                                         gboolean obey_child);

Object Hierarchy

  GObject
   +----GInitiallyUnowned
         +----GtkObject
               +----GtkWidget
                     +----GtkContainer
                           +----GtkBin
                                 +----GtkFrame
                                       +----GtkAspectFrame

Implemented Interfaces

GtkAspectFrame implements AtkImplementorIface.

Properties

  "obey-child"               gboolean              : Read / Write
  "ratio"                    gfloat                : Read / Write
  "xalign"                   gfloat                : Read / Write
  "yalign"                   gfloat                : Read / Write

Description

The GtkAspectFrame is useful when you want pack a widget so that it can resize but always retains the same aspect ratio. For instance, one might be drawing a small preview of a larger image. GtkAspectFrame derives from GtkFrame, so it can draw a label and a frame around the child. The frame will be "shrink-wrapped" to the size of the child.

Details

GtkAspectFrame

typedef struct _GtkAspectFrame GtkAspectFrame;

gtk_aspect_frame_new ()

GtkWidget*          gtk_aspect_frame_new                (const gchar *label,
                                                         gfloat xalign,
                                                         gfloat yalign,
                                                         gfloat ratio,
                                                         gboolean obey_child);

Create a new GtkAspectFrame.

label : | Label text.
xalign : | Horizontal alignment of the child within the allocation of the GtkAspectFrame. This ranges from 0.0 (left aligned) to 1.0 (right aligned)
yalign : | Vertical alignment of the child within the allocation of the GtkAspectFrame. This ranges from 0.0 (left aligned) to 1.0 (right aligned)
ratio : | The desired aspect ratio.
obey_child : | If TRUE, ratio is ignored, and the aspect ratio is taken from the requistion of the child.
Returns : | the new GtkAspectFrame.

gtk_aspect_frame_set ()

void                gtk_aspect_frame_set                (GtkAspectFrame *aspect_frame,
                                                         gfloat xalign,
                                                         gfloat yalign,
                                                         gfloat ratio,
                                                         gboolean obey_child);

Set parameters for an existing GtkAspectFrame.

aspect_frame : | a GtkAspectFrame
xalign : | Horizontal alignment of the child within the allocation of the GtkAspectFrame. This ranges from 0.0 (left aligned) to 1.0 (right aligned)
yalign : | Vertical alignment of the child within the allocation of the GtkAspectFrame. This ranges from 0.0 (left aligned) to 1.0 (right aligned)
ratio : | The desired aspect ratio.
obey_child : | If TRUE, ratio is ignored, and the aspect ratio is taken from the requistion of the child.

Property Details

The "obey-child" property

  "obey-child"               gboolean              : Read / Write

Force aspect ratio to match that of the frame's child.

Default value: TRUE

The "ratio" property

  "ratio"                    gfloat                : Read / Write

Aspect ratio if obey_child is FALSE.

Allowed values: [1e-04,10000]

Default value: 0.5

The "xalign" property

  "xalign"                   gfloat                : Read / Write

X alignment of the child.

Allowed values: [0,1]

Default value: 0.5

The "yalign" property

  "yalign"                   gfloat                : Read / Write

Y alignment of the child.

Allowed values: [0,1]

Default value: 0.5


GtkAssistant

GtkAssistant — A widget used to guide users through multi-step operations

Synopsis

#include <gtk/gtk.h>

                    GtkAssistant;
GtkWidget*          gtk_assistant_new                   (void);
gint                gtk_assistant_get_current_page      (GtkAssistant *assistant);
void                gtk_assistant_set_current_page      (GtkAssistant *assistant,
                                                         gint page_num);
gint                gtk_assistant_get_n_pages           (GtkAssistant *assistant);
GtkWidget*          gtk_assistant_get_nth_page          (GtkAssistant *assistant,
                                                         gint page_num);
gint                gtk_assistant_prepend_page          (GtkAssistant *assistant,
                                                         GtkWidget *page);
gint                gtk_assistant_append_page           (GtkAssistant *assistant,
                                                         GtkWidget *page);
gint                gtk_assistant_insert_page           (GtkAssistant *assistant,
                                                         GtkWidget *page,
                                                         gint position);
gint                (*GtkAssistantPageFunc)             (gint current_page,
                                                         gpointer data);
void                gtk_assistant_set_forward_page_func (GtkAssistant *assistant,
                                                         GtkAssistantPageFunc page_func,
                                                         gpointer data,
                                                         GDestroyNotify destroy);
enum                GtkAssistantPageType;
void                gtk_assistant_set_page_type         (GtkAssistant *assistant,
                                                         GtkWidget *page,
                                                         GtkAssistantPageType type);
GtkAssistantPageType gtk_assistant_get_page_type        (GtkAssistant *assistant,
                                                         GtkWidget *page);
void                gtk_assistant_set_page_title        (GtkAssistant *assistant,
                                                         GtkWidget *page,
                                                         const gchar *title);
const gchar*        gtk_assistant_get_page_title        (GtkAssistant *assistant,
                                                         GtkWidget *page);
void                gtk_assistant_set_page_header_image (GtkAssistant *assistant,
                                                         GtkWidget *page,
                                                         GdkPixbuf *pixbuf);
GdkPixbuf*          gtk_assistant_get_page_header_image (GtkAssistant *assistant,
                                                         GtkWidget *page);
void                gtk_assistant_set_page_side_image   (GtkAssistant *assistant,
                                                         GtkWidget *page,
                                                         GdkPixbuf *pixbuf);
GdkPixbuf*          gtk_assistant_get_page_side_image   (GtkAssistant *assistant,
                                                         GtkWidget *page);
void                gtk_assistant_set_page_complete     (GtkAssistant *assistant,
                                                         GtkWidget *page,
                                                         gboolean complete);
gboolean            gtk_assistant_get_page_complete     (GtkAssistant *assistant,
                                                         GtkWidget *page);
void                gtk_assistant_add_action_widget     (GtkAssistant *assistant,
                                                         GtkWidget *child);
void                gtk_assistant_remove_action_widget  (GtkAssistant *assistant,
                                                         GtkWidget *child);
void                gtk_assistant_update_buttons_state  (GtkAssistant *assistant);

Object Hierarchy

  GObject
   +----GInitiallyUnowned
         +----GtkObject
               +----GtkWidget
                     +----GtkContainer
                           +----GtkBin
                                 +----GtkWindow
                                       +----GtkAssistant

Implemented Interfaces

GtkAssistant implements AtkImplementorIface.

Child Properties

  "complete"                 gboolean              : Read / Write
  "header-image"             GdkPixbuf             : Read / Write
  "page-type"                GtkAssistantPageType  : Read / Write
  "sidebar-image"            GdkPixbuf             : Read / Write
  "title"                    gchararray            : Read / Write

Style Properties

  "content-padding"          gint                  : Read
  "header-padding"           gint                  : Read

Signals

  "apply"                                          : Run Last
  "cancel"                                         : Run Last
  "close"                                          : Run Last
  "prepare"                                        : Run Last

Description

A GtkAssistant is a widget used to represent a generally complex operation splitted in several steps, guiding the user through its pages and controlling the page flow to collect the necessary data.

Details

GtkAssistant

typedef struct _GtkAssistant GtkAssistant;

gtk_assistant_new ()

GtkWidget*          gtk_assistant_new                   (void);

Creates a new GtkAssistant.

Returns : a newly created GtkAssistant

Since 2.10

gtk_assistant_get_current_page ()

gint                gtk_assistant_get_current_page      (GtkAssistant *assistant);

Returns the page number of the current page

assistant : | a GtkAssistant
Returns : | The index (starting from 0) of the current page in the assistant, if the assistant has no pages, -1 will be returned

Since 2.10

gtk_assistant_set_current_page ()

void                gtk_assistant_set_current_page      (GtkAssistant *assistant,
                                                         gint page_num);

Switches the page to page_num. Note that this will only be necessary in custom buttons, as the assistant flow can be set with gtk_assistant_set_forward_page_func().

assistant : | a GtkAssistant
page_num : | index of the page to switch to, starting from 0. If negative, the last page will be used. If greater than the number of pages in the assistant, nothing will be done.

Since 2.10

gtk_assistant_get_n_pages ()

gint                gtk_assistant_get_n_pages           (GtkAssistant *assistant);

Returns the number of pages in the assistant

assistant : | a GtkAssistant
Returns : | The number of pages in the assistant.

Since 2.10

gtk_assistant_get_nth_page ()

GtkWidget*          gtk_assistant_get_nth_page          (GtkAssistant *assistant,
                                                         gint page_num);

Returns the child widget contained in page number page_num.

assistant : | a GtkAssistant
page_num : | The index of a page in the assistant, or -1 to get the last page;
Returns : | The child widget, or NULL if page_num is out of bounds.

Since 2.10

gtk_assistant_prepend_page ()

gint                gtk_assistant_prepend_page          (GtkAssistant *assistant,
                                                         GtkWidget *page);

Prepends a page to the assistant.

assistant : | a GtkAssistant
page : | a GtkWidget
Returns : | the index (starting at 0) of the inserted page

Since 2.10

gtk_assistant_append_page ()

gint                gtk_assistant_append_page           (GtkAssistant *assistant,
                                                         GtkWidget *page);

Appends a page to the assistant.

assistant : | a GtkAssistant
page : | a GtkWidget
Returns : | the index (starting at 0) of the inserted page

Since 2.10

gtk_assistant_insert_page ()

gint                gtk_assistant_insert_page           (GtkAssistant *assistant,
                                                         GtkWidget *page,
                                                         gint position);

Inserts a page in the assistant at a given position.

assistant : | a GtkAssistant
page : | a GtkWidget
position : | the index (starting at 0) at which to insert the page, or -1 to append the page to the assistant
Returns : | the index (starting from 0) of the inserted page

Since 2.10

GtkAssistantPageFunc ()

gint                (*GtkAssistantPageFunc)             (gint current_page,
                                                         gpointer data);

A function used by gtk_assistant_set_forward_page_func() to know which is the next page given a current one. It's called both for computing the next page when the user presses the "forward" button and for handling the behavior of the "last" button.

current_page : | The page number used to calculate the next page.
data : | user data.
Returns : | The next page number.

gtk_assistant_set_forward_page_func ()

void                gtk_assistant_set_forward_page_func (GtkAssistant *assistant,
                                                         GtkAssistantPageFunc page_func,
                                                         gpointer data,
                                                         GDestroyNotify destroy);

Sets the page forwarding function to be page_func, this function will be used to determine what will be the next page when the user presses the forward button. Setting page_func to NULL will make the assistant to use the default forward function, which just goes to the next visible page.

assistant : | a GtkAssistant
page_func : | the GtkAssistantPageFunc, or NULL to use the default one
data : | user data for page_func
destroy : | destroy notifier for data

Since 2.10

enum GtkAssistantPageType

typedef enum
{
  GTK_ASSISTANT_PAGE_CONTENT,
  GTK_ASSISTANT_PAGE_INTRO,
  GTK_ASSISTANT_PAGE_CONFIRM,
  GTK_ASSISTANT_PAGE_SUMMARY,
  GTK_ASSISTANT_PAGE_PROGRESS
} GtkAssistantPageType;

An enum for determining the page role inside the GtkAssistant. It's used to handle buttons sensitivity and visibility.

Note that an assistant needs to end its page flow with a page of type GTK_ASSISTANT_PAGE_CONFIRM or GTK_ASSISTANT_PAGE_SUMMARY to be correct.

GTK_ASSISTANT_PAGE_CONTENT | The page has regular contents.
GTK_ASSISTANT_PAGE_INTRO | The page contains an introduction to the assistant task.
GTK_ASSISTANT_PAGE_CONFIRM | The page lets the user confirm or deny the changes.
GTK_ASSISTANT_PAGE_SUMMARY | The page informs the user of the changes done.
GTK_ASSISTANT_PAGE_PROGRESS | Used for tasks that take a long time to complete, blocks the assistant until the page is marked as complete.

gtk_assistant_set_page_type ()

void                gtk_assistant_set_page_type         (GtkAssistant *assistant,
                                                         GtkWidget *page,
                                                         GtkAssistantPageType type);

Sets the page type for page. The page type determines the page behavior in the assistant.

assistant : | a GtkAssistant
page : | a page of assistant
type : | the new type for page

Since 2.10

gtk_assistant_get_page_type ()

GtkAssistantPageType gtk_assistant_get_page_type        (GtkAssistant *assistant,
                                                         GtkWidget *page);

Gets the page type of page.

assistant : | a GtkAssistant
page : | a page of assistant
Returns : | the page type of page.

Since 2.10

gtk_assistant_set_page_title ()

void                gtk_assistant_set_page_title        (GtkAssistant *assistant,
                                                         GtkWidget *page,
                                                         const gchar *title);

Sets a title for page. The title is displayed in the header area of the assistant when page is the current page.

assistant : | a GtkAssistant
page : | a page of assistant
title : | the new title for page

Since 2.10

gtk_assistant_get_page_title ()

const gchar*        gtk_assistant_get_page_title        (GtkAssistant *assistant,
                                                         GtkWidget *page);

Gets the title for page.

assistant : | a GtkAssistant
page : | a page of assistant
Returns : | the title for page.

Since 2.10

gtk_assistant_set_page_header_image ()

void                gtk_assistant_set_page_header_image (GtkAssistant *assistant,
                                                         GtkWidget *page,
                                                         GdkPixbuf *pixbuf);

Sets a header image for page. This image is displayed in the header area of the assistant when page is the current page.

assistant : | a GtkAssistant
page : | a page of assistant
pixbuf : | the new header image page

Since 2.10

gtk_assistant_get_page_header_image ()

GdkPixbuf*          gtk_assistant_get_page_header_image (GtkAssistant *assistant,
                                                         GtkWidget *page);

Gets the header image for page.

assistant : | a GtkAssistant
page : | a page of assistant
Returns : | the header image for page, or NULL if there's no header image for the page.

Since 2.10

gtk_assistant_set_page_side_image ()

void                gtk_assistant_set_page_side_image   (GtkAssistant *assistant,
                                                         GtkWidget *page,
                                                         GdkPixbuf *pixbuf);

Sets a header image for page. This image is displayed in the side area of the assistant when page is the current page.

assistant : | a GtkAssistant
page : | a page of assistant
pixbuf : | the new header image page

Since 2.10

gtk_assistant_get_page_side_image ()

GdkPixbuf*          gtk_assistant_get_page_side_image   (GtkAssistant *assistant,
                                                         GtkWidget *page);

Gets the header image for page.

assistant : | a GtkAssistant
page : | a page of assistant
Returns : | the side image for page, or NULL if there's no side image for the page.

Since 2.10

gtk_assistant_set_page_complete ()

void                gtk_assistant_set_page_complete     (GtkAssistant *assistant,
                                                         GtkWidget *page,
                                                         gboolean complete);

Sets whether page contents are complete. This will make assistant update the buttons state to be able to continue the task.

assistant : | a GtkAssistant
page : | a page of assistant
complete : | the completeness status of the page

Since 2.10

gtk_assistant_get_page_complete ()

gboolean            gtk_assistant_get_page_complete     (GtkAssistant *assistant,
                                                         GtkWidget *page);

Gets whether page is complete..

assistant : | a GtkAssistant
page : | a page of assistant
Returns : | TRUE if page is complete.

Since 2.10

gtk_assistant_add_action_widget ()

void                gtk_assistant_add_action_widget     (GtkAssistant *assistant,
                                                         GtkWidget *child);

Adds a widget to the action area of a GtkAssistant.

assistant : | a GtkAssistant
child : | a GtkWidget

Since 2.10

gtk_assistant_remove_action_widget ()

void                gtk_assistant_remove_action_widget  (GtkAssistant *assistant,
                                                         GtkWidget *child);

Removes a widget from the action area of a GtkAssistant.

assistant : | a GtkAssistant
child : | a GtkWidget

Since 2.10

gtk_assistant_update_buttons_state ()

void                gtk_assistant_update_buttons_state  (GtkAssistant *assistant);

Forces assistant to recompute the buttons state.

GTK+ automatically takes care of this in most situations, e.g. when the user goes to a different page, or when the visibility or completeness of a page changes.

One situation where it can be necessary to call this function is when changing a value on the current page affects the future page flow of the assistant.

assistant : a GtkAssistant

Since 2.10

Child Property Details

The "complete" child property

  "complete"                 gboolean              : Read / Write

Setting the "complete" child property to TRUE marks a page as complete (i.e.: all the required fields are filled out). GTK+ uses this information to control the sensitivity of the navigation buttons.

Default value: FALSE

Since 2.10

The "header-image" child property

  "header-image"             GdkPixbuf             : Read / Write

The image that is displayed next to the page.

Set this to NULL to make the sidebar disappear.

Since 2.10

The "page-type" child property

  "page-type"                GtkAssistantPageType  : Read / Write

The type of the assistant page.

Default value: GTK_ASSISTANT_PAGE_CONTENT

Since 2.10

The "sidebar-image" child property

  "sidebar-image"            GdkPixbuf             : Read / Write

Sidebar image for the assistant page.

The "title" child property

  "title"                    gchararray            : Read / Write

The title that is displayed in the page header.

If title and header-image are both NULL, no header is displayed.

Default value: NULL

Since 2.10

Style Property Details

The "content-padding" style property

  "content-padding"          gint                  : Read

Number of pixels around the content pages.

Allowed values: >= 0

Default value: 1

The "header-padding" style property

  "header-padding"           gint                  : Read

Number of pixels around the header.

Allowed values: >= 0

Default value: 6

Signal Details

The "apply" signal

void                user_function                      (GtkAssistant *assistant,
                                                        gpointer      user_data)      : Run Last

The ::apply signal is emitted when the apply button is clicked. The default behavior of the GtkAssistant is to switch to the page after the current page, unless the current page is the last one.

A handler for the ::apply signal should carry out the actions for which the wizard has collected data. If the action takes a long time to complete, you might consider to put a page of type GTK_ASSISTANT_PAGE_PROGRESS after the confirmation page and handle this operation within the ::prepare signal of the progress page.

assistant : | the GtkAssistant
user_data : | user data set when the signal handler was connected.

Since 2.10

The "cancel" signal

void                user_function                      (GtkAssistant *assistant,
                                                        gpointer      user_data)      : Run Last

The ::cancel signal is emitted when then the cancel button is clicked.

assistant : | the GtkAssistant
user_data : | user data set when the signal handler was connected.

Since 2.10

The "close" signal

void                user_function                      (GtkAssistant *assistant,
                                                        gpointer      user_data)      : Run Last

The ::close signal is emitted either when the close button of a summary page is clicked, or when the apply button in the last page in the flow (of type GTK_ASSISTANT_PAGE_CONFIRM) is clicked.

assistant : | the GtkAssistant
user_data : | user data set when the signal handler was connected.

Since 2.10

The "prepare" signal

void                user_function                      (GtkAssistant *assistant,
                                                        GtkWidget    *page,
                                                        gpointer      user_data)      : Run Last

The ::prepared signal is emitted when a new page is set as the assistant's current page, before making the new page visible. A handler for this signal can do any preparation which are necessary before showing page.

assistant : | the GtkAssistant
page : | the current page
user_data : | user data set when the signal handler was connected.

Since 2.10


Prev Home GTK+ Reference Manual Next

Part II. GTK+ Core Reference


GtkBin

GtkBin — A container with just one child

Synopsis

#include <gtk/gtk.h>

                    GtkBin;
GtkWidget*          gtk_bin_get_child                   (GtkBin *bin);

Object Hierarchy

  GObject
   +----GInitiallyUnowned
         +----GtkObject
               +----GtkWidget
                     +----GtkContainer
                           +----GtkBin
                                 +----GtkWindow
                                 +----GtkAlignment
                                 +----GtkFrame
                                 +----GtkButton
                                 +----GtkItem
                                 +----GtkComboBox
                                 +----GtkEventBox
                                 +----GtkExpander
                                 +----GtkHandleBox
                                 +----GtkToolItem
                                 +----GtkScrolledWindow
                                 +----GtkViewport

Implemented Interfaces

GtkBin implements AtkImplementorIface.

Description

The GtkBin widget is a container with just one child. It is not very useful itself, but it is useful for deriving subclasses, since it provides common code needed for handling a single child widget.

Many GTK+ widgets are subclasses of GtkBin, including GtkWindow, GtkButton, GtkFrame, GtkHandleBox, and GtkScrolledWindow.

Details

GtkBin

typedef struct _GtkBin GtkBin;

The GtkBin struct contains the following fields. (These fields should be considered read-only. They should never be set by an application.)

GtkWidget *child; the child widget.

gtk_bin_get_child ()

GtkWidget*          gtk_bin_get_child                   (GtkBin *bin);

Gets the child of the GtkBin, or NULL if the bin contains no child widget. The returned widget does not have a reference added, so you do not need to unref it.

bin : | a GtkBin
Returns : | pointer to child of the GtkBin


GtkBox

GtkBox — Base class for box containers

Synopsis

#include <gtk/gtk.h>

                    GtkBox;
                    GtkBoxChild;
void                gtk_box_pack_start                  (GtkBox *box,
                                                         GtkWidget *child,
                                                         gboolean expand,
                                                         gboolean fill,
                                                         guint padding);
void                gtk_box_pack_end                    (GtkBox *box,
                                                         GtkWidget *child,
                                                         gboolean expand,
                                                         gboolean fill,
                                                         guint padding);
void                gtk_box_pack_start_defaults         (GtkBox *box,
                                                         GtkWidget *widget);
void                gtk_box_pack_end_defaults           (GtkBox *box,
                                                         GtkWidget *widget);
gboolean            gtk_box_get_homogeneous             (GtkBox *box);
void                gtk_box_set_homogeneous             (GtkBox *box,
                                                         gboolean homogeneous);
gint                gtk_box_get_spacing                 (GtkBox *box);
void                gtk_box_set_spacing                 (GtkBox *box,
                                                         gint spacing);
void                gtk_box_reorder_child               (GtkBox *box,
                                                         GtkWidget *child,
                                                         gint position);
void                gtk_box_query_child_packing         (GtkBox *box,
                                                         GtkWidget *child,
                                                         gboolean *expand,
                                                         gboolean *fill,
                                                         guint *padding,
                                                         GtkPackType *pack_type);
void                gtk_box_set_child_packing           (GtkBox *box,
                                                         GtkWidget *child,
                                                         gboolean expand,
                                                         gboolean fill,
                                                         guint padding,
                                                         GtkPackType pack_type);

Object Hierarchy

  GObject
   +----GInitiallyUnowned
         +----GtkObject
               +----GtkWidget
                     +----GtkContainer
                           +----GtkBox
                                 +----GtkButtonBox
                                 +----GtkVBox
                                 +----GtkHBox

Implemented Interfaces

GtkBox implements AtkImplementorIface.

Properties

  "homogeneous"              gboolean              : Read / Write
  "spacing"                  gint                  : Read / Write

Child Properties

  "expand"                   gboolean              : Read / Write
  "fill"                     gboolean              : Read / Write
  "pack-type"                GtkPackType           : Read / Write
  "padding"                  guint                 : Read / Write
  "position"                 gint                  : Read / Write

Description

GtkBox is an abstract widget which encapsulates functionallity for a particular kind of container, one that organizes a variable number of widgets into a rectangular area. GtkBox currently has two derived classes, GtkHBox and GtkVBox.

The rectangular area of a GtkBox is organized into either a single row or a single column of child widgets depending upon whether the box is of type GtkHBox or GtkVBox, respectively. Thus, all children of a GtkBox are allocated one dimension in common, which is the height of a row, or the width of a column.

GtkBox uses a notion of packing. Packing refers to adding widgets with reference to a particular position in a GtkContainer. For a GtkBox, there are two reference positions: the start and the end of the box. For a GtkVBox, the start is defined as the top of the box and the end is defined as the bottom. For a GtkHBox the start is defined as the left side and the end is defined as the right side.

Use repeated calls to gtk_box_pack_start() to pack widgets into a GtkBox from start to end. Use gtk_box_pack_end() to add widgets from end to start. You may intersperse these calls and add widgets from both ends of the same GtkBox.

Use gtk_box_pack_start_defaults() or gtk_box_pack_end_defaults() to pack widgets into a GtkBox if you do not need to specify the expand, fill, or padding attributes of the child to be added.

Because GtkBox is a GtkContainer, you may also use gtk_container_add() to insert widgets into the box, and they will be packed as if with gtk_box_pack_start_defaults(). Use gtk_container_remove() to remove widgets from the GtkBox.

Use gtk_box_set_homogeneous() to specify whether or not all children of the GtkBox are forced to get the same amount of space.

Use gtk_box_set_spacing() to determine how much space will be minimally placed between all children in the GtkBox.

Use gtk_box_reorder_child() to move a GtkBox child to a different place in the box.

Use gtk_box_set_child_packing() to reset the expand, fill, and padding attributes of any GtkBox child. Use gtk_box_query_child_packing() to query these fields.

Details

GtkBox

typedef struct {
  GList *children;
  gint16 spacing;
  guint homogeneous : 1;
} GtkBox;

The GtkBox describes an instance of GtkBox and contains the following fields. (These fields should be considered read-only. They should never be set by an application.)

GList * children; | a list of children belonging the GtkBox. The data is a list of structures of type GtkBoxChild.
gint16 spacing; | the number of pixels to put between children of the GtkBox, zero by default. Use gtk_box_set_spacing() to set this field.
guint homogeneous; | a flag that if TRUE forces all children to get equal space in the GtkBox; FALSE by default. Use gtk_box_set_homogeneous() to set this field.

GtkBoxChild

typedef struct {
  GtkWidget *widget;
  guint16 padding;
  guint expand : 1;
  guint fill : 1;
  guint pack : 1;
  guint is_secondary : 1;
} GtkBoxChild;

The GtkBoxChild holds a child widget of GtkBox and describes how the child is to be packed into the GtkBox. Use gtk_box_query_child_packing() and gtk_box_set_child_packing() to query and reset the padding, expand, fill, and pack fields.

GtkBoxChild contains the following fields. (These fields should be considered read-only. They should never be directly set by an application.)

GtkWidget * widget; | the child widget, packed into the GtkBox.
guint16 padding; | the number of extra pixels to put between this child and its neighbors, set when packed, zero by default.
guint expand; | flag indicates whether extra space should be given to this child. Any extra space given to the parent GtkBox is divided up among all children with this attribute set to TRUE; set when packed, TRUE by default.
guint fill; | flag indicates whether any extra space given to this child due to its expand attribute being set is actually allocated to the child, rather than being used as padding around the widget; set when packed, TRUE by default.
guint pack; | one of GtkPackType indicating whether the child is packed with reference to the start (top/left) or end (bottom/right) of the GtkBox.

gtk_box_pack_start ()

void                gtk_box_pack_start                  (GtkBox *box,
                                                         GtkWidget *child,
                                                         gboolean expand,
                                                         gboolean fill,
                                                         guint padding);

Adds child to box, packed with reference to the start of box. The child is packed after any other child packed with reference to the start of box.

box : | a GtkBox.
child : | the GtkWidget to be added to box.
expand : | TRUE if the new child is to be given extra space allocated to box. The extra space will be divided evenly between all children of box that use this option.
fill : | TRUE if space given to child by the expand option is actually allocated to child, rather than just padding it. This parameter has no effect if expand is set to FALSE. A child is always allocated the full height of a GtkHBox and the full width of a GtkVBox. This option affects the other dimension.
padding : | extra space in pixels to put between this child and its neighbors, over and above the global amount specified by spacing in GtkBox. If child is a widget at one of the reference ends of box, then padding pixels are also put between child and the reference edge of box.

gtk_box_pack_end ()

void                gtk_box_pack_end                    (GtkBox *box,
                                                         GtkWidget *child,
                                                         gboolean expand,
                                                         gboolean fill,
                                                         guint padding);

Adds child to box, packed with reference to the end of box. The child is packed after (away from end of) any other child packed with reference to the end of box.

box : | a GtkBox.
child : | the GtkWidget to be added to box.
expand : | TRUE if the new child is to be given extra space allocated to box. The extra space will be divided evenly between all children of box that use this option.
fill : | TRUE if space given to child by the expand option is actually allocated to child, rather than just padding it. This parameter has no effect if expand is set to FALSE. A child is always allocated the full height of a GtkHBox and the full width of a GtkVBox. This option affects the other dimension.
padding : | extra space in pixels to put between this child and its neighbors, over and above the global amount specified by spacing in GtkBox. If child is a widget at one of the reference ends of box, then padding pixels are also put between child and the reference edge of box.

gtk_box_pack_start_defaults ()

void                gtk_box_pack_start_defaults         (GtkBox *box,
                                                         GtkWidget *widget);

Adds widget to box, packed with reference to the start of box. The child is packed after any other child packed with reference to the start of box.

Parameters for how to pack the child widget, expand, fill, and padding in GtkBoxChild, are given their default values, TRUE, TRUE, and 0, respectively.

box : | a GtkBox.
widget : | the GtkWidget to be added to box.

gtk_box_pack_end_defaults ()

void                gtk_box_pack_end_defaults           (GtkBox *box,
                                                         GtkWidget *widget);

Adds widget to box, packed with reference to the end of box. The child is packed after (away from end of) any other child packed with reference to the end of box.

Parameters for how to pack the child widget, expand, fill, and padding in GtkBoxChild, are given their default values, TRUE, TRUE, and 0, respectively.

box : | a GtkBox.
widget : | the GtkWidget to be added to box.

gtk_box_get_homogeneous ()

gboolean            gtk_box_get_homogeneous             (GtkBox *box);

Returns whether the box is homogeneous (all children are the same size). See gtk_box_set_homogeneous().

box : | a GtkBox
Returns : | TRUE if the box is homogeneous.

gtk_box_set_homogeneous ()

void                gtk_box_set_homogeneous             (GtkBox *box,
                                                         gboolean homogeneous);

Sets the homogeneous field of GtkBox, controlling whether or not all children of box are given equal space in the box.

box : | a GtkBox.
homogeneous : | a boolean value, TRUE to create equal allotments, FALSE for variable allotments.

gtk_box_get_spacing ()

gint                gtk_box_get_spacing                 (GtkBox *box);

Gets the value set by gtk_box_set_spacing().

box : | a GtkBox
Returns : | spacing between children

gtk_box_set_spacing ()

void                gtk_box_set_spacing                 (GtkBox *box,
                                                         gint spacing);

Sets the spacing field of GtkBox, which is the number of pixels to place between children of box.

box : | a GtkBox.
spacing : | the number of pixels to put between children.

gtk_box_reorder_child ()

void                gtk_box_reorder_child               (GtkBox *box,
                                                         GtkWidget *child,
                                                         gint position);

Moves child to a new position in the list of box children. The list is the children field of GtkBox, and contains both widgets packed GTK_PACK_START as well as widgets packed GTK_PACK_END, in the order that these widgets were added to box.

A widget's position in the box children list determines where the widget is packed into box. A child widget at some position in the list will be packed just after all other widgets of the same packing type that appear earlier in the list.

box : | a GtkBox.
child : | the GtkWidget to move.
position : | the new position for child in the children list of GtkBox, starting from 0. If negative, indicates the end of the list.

gtk_box_query_child_packing ()

void                gtk_box_query_child_packing         (GtkBox *box,
                                                         GtkWidget *child,
                                                         gboolean *expand,
                                                         gboolean *fill,
                                                         guint *padding,
                                                         GtkPackType *pack_type);

Returns information about how child is packed into box.

box : | a GtkBox.
child : | the GtkWidget of the child to query.
expand : | the returned value of the expand field in GtkBoxChild.
fill : | the returned value of the fill field in GtkBoxChild.
padding : | the returned value of the padding field in GtkBoxChild.
pack_type : | the returned value of the pack field in GtkBoxChild.

gtk_box_set_child_packing ()

void                gtk_box_set_child_packing           (GtkBox *box,
                                                         GtkWidget *child,
                                                         gboolean expand,
                                                         gboolean fill,
                                                         guint padding,
                                                         GtkPackType pack_type);

Sets the way child is packed into box.

box : | a GtkBox.
child : | the GtkWidget of the child to set.
expand : | the new value of the expand field in GtkBoxChild.
fill : | the new value of the fill field in GtkBoxChild.
padding : | the new value of the padding field in GtkBoxChild.
pack_type : | the new value of the pack field in GtkBoxChild.

Property Details

The "homogeneous" property

  "homogeneous"              gboolean              : Read / Write

Whether the children should all be the same size.

Default value: FALSE

The "spacing" property

  "spacing"                  gint                  : Read / Write

The amount of space between children.

Allowed values: >= 0

Default value: 0

Child Property Details

The "expand" child property

  "expand"                   gboolean              : Read / Write

Whether the child should receive extra space when the parent grows.

Default value: TRUE

The "fill" child property

  "fill"                     gboolean              : Read / Write

Whether extra space given to the child should be allocated to the child or used as padding.

Default value: TRUE

The "pack-type" child property

  "pack-type"                GtkPackType           : Read / Write

A GtkPackType indicating whether the child is packed with reference to the start or end of the parent.

Default value: GTK_PACK_START

The "padding" child property

  "padding"                  guint                 : Read / Write

Extra space to put between the child and its neighbors, in pixels.

Allowed values: <= G_MAXINT

Default value: 0

The "position" child property

  "position"                 gint                  : Read / Write

The index of the child in the parent.

Allowed values: >= -1

Default value: 0

See Also

GtkHBox | a derived class that organizes widgets into a row.
GtkVBox | a derived class that organizes widgets into a column.
GtkFrame | a GtkWidget useful for drawing a border around a GtkBox.
GtkTable | a GtkContainer for organizing widgets into a grid, rather than independent rows or columns.
GtkLayout | a GtkContainer for organizing widgets into arbitrary layouts.


GtkButton

GtkButton — A widget that creates a signal when clicked on

Synopsis

#include <gtk/gtk.h>

                    GtkButton;
GtkWidget*          gtk_button_new                      (void);
GtkWidget*          gtk_button_new_with_label           (const gchar *label);
GtkWidget*          gtk_button_new_with_mnemonic        (const gchar *label);
GtkWidget*          gtk_button_new_from_stock           (const gchar *stock_id);
void                gtk_button_pressed                  (GtkButton *button);
void                gtk_button_released                 (GtkButton *button);
void                gtk_button_clicked                  (GtkButton *button);
void                gtk_button_enter                    (GtkButton *button);
void                gtk_button_leave                    (GtkButton *button);
void                gtk_button_set_relief               (GtkButton *button,
                                                         GtkReliefStyle newstyle);
GtkReliefStyle      gtk_button_get_relief               (GtkButton *button);
const gchar*        gtk_button_get_label                (GtkButton *button);
void                gtk_button_set_label                (GtkButton *button,
                                                         const gchar *label);
gboolean            gtk_button_get_use_stock            (GtkButton *button);
void                gtk_button_set_use_stock            (GtkButton *button,
                                                         gboolean use_stock);
gboolean            gtk_button_get_use_underline        (GtkButton *button);
void                gtk_button_set_use_underline        (GtkButton *button,
                                                         gboolean use_underline);
void                gtk_button_set_focus_on_click       (GtkButton *button,
                                                         gboolean focus_on_click);
gboolean            gtk_button_get_focus_on_click       (GtkButton *button);
void                gtk_button_set_alignment            (GtkButton *button,
                                                         gfloat xalign,
                                                         gfloat yalign);
void                gtk_button_get_alignment            (GtkButton *button,
                                                         gfloat *xalign,
                                                         gfloat *yalign);
void                gtk_button_set_image                (GtkButton *button,
                                                         GtkWidget *image);
GtkWidget*          gtk_button_get_image                (GtkButton *button);
void                gtk_button_set_image_position       (GtkButton *button,
                                                         GtkPositionType position);
GtkPositionType     gtk_button_get_image_position       (GtkButton *button);

Object Hierarchy

  GObject
   +----GInitiallyUnowned
         +----GtkObject
               +----GtkWidget
                     +----GtkContainer
                           +----GtkBin
                                 +----GtkButton
                                       +----GtkToggleButton
                                       +----GtkColorButton
                                       +----GtkFontButton
                                       +----GtkLinkButton
                                       +----GtkOptionMenu

Implemented Interfaces

GtkButton implements AtkImplementorIface.

Properties

  "focus-on-click"           gboolean              : Read / Write
  "image"                    GtkWidget             : Read / Write
  "image-position"           GtkPositionType       : Read / Write
  "label"                    gchararray            : Read / Write / Construct
  "relief"                   GtkReliefStyle        : Read / Write
  "use-stock"                gboolean              : Read / Write / Construct
  "use-underline"            gboolean              : Read / Write / Construct
  "xalign"                   gfloat                : Read / Write
  "yalign"                   gfloat                : Read / Write

Style Properties

  "child-displacement-x"     gint                  : Read
  "child-displacement-y"     gint                  : Read
  "default-border"           GtkBorder             : Read
  "default-outside-border"   GtkBorder             : Read
  "displace-focus"           gboolean              : Read
  "image-spacing"            gint                  : Read
  "inner-border"             GtkBorder             : Read

Signals

  "activate"                                       : Run First / Action
  "clicked"                                        : Run First / Action
  "enter"                                          : Run First
  "leave"                                          : Run First
  "pressed"                                        : Run First
  "released"                                       : Run First

Description

The GtkButton widget is generally used to attach a function to that is called when the button is pressed. The various signals and how to use them are outlined below.

The GtkButton widget can hold any valid child widget. That is it can hold most any other standard GtkWidget. The most commonly used child is the GtkLabel.

Details

GtkButton

typedef struct _GtkButton GtkButton;

This should not be accessed directly. Use the accessor functions below.

gtk_button_new ()

GtkWidget*          gtk_button_new                      (void);

Creates a new GtkButton widget. To add a child widget to the button, use gtk_container_add().

Returns : The newly created GtkButton widget.

gtk_button_new_with_label ()

GtkWidget*          gtk_button_new_with_label           (const gchar *label);

Creates a GtkButton widget with a GtkLabel child containing the given text.

label : | The text you want the GtkLabel to hold.
Returns : | The newly created GtkButton widget.

gtk_button_new_with_mnemonic ()

GtkWidget*          gtk_button_new_with_mnemonic        (const gchar *label);

Creates a new GtkButton containing a label. If characters in label are preceded by an underscore, they are underlined. If you need a literal underscore character in a label, use '__' (two underscores). The first underlined character represents a keyboard accelerator called a mnemonic. Pressing Alt and that key activates the button.

label : | The text of the button, with an underscore in front of the mnemonic character
Returns : | a new GtkButton

gtk_button_new_from_stock ()

GtkWidget*          gtk_button_new_from_stock           (const gchar *stock_id);

Creates a new GtkButton containing the image and text from a stock item. Some stock ids have preprocessor macros like GTK_STOCK_OK and GTK_STOCK_APPLY.

If stock_id is unknown, then it will be treated as a mnemonic label (as for gtk_button_new_with_mnemonic()).

stock_id : | the name of the stock item
Returns : | a new GtkButton

gtk_button_pressed ()

void                gtk_button_pressed                  (GtkButton *button);

Emits a GtkButton::pressed signal to the given GtkButton.

button : The GtkButton you want to send the signal to.

gtk_button_released ()

void                gtk_button_released                 (GtkButton *button);

Emits a GtkButton::released signal to the given GtkButton.

button : The GtkButton you want to send the signal to.

gtk_button_clicked ()

void                gtk_button_clicked                  (GtkButton *button);

Emits a GtkButton::clicked signal to the given GtkButton.

button : The GtkButton you want to send the signal to.

gtk_button_enter ()

void                gtk_button_enter                    (GtkButton *button);

Emits a GtkButton::enter signal to the given GtkButton.

button : The GtkButton you want to send the signal to.

gtk_button_leave ()

void                gtk_button_leave                    (GtkButton *button);

Emits a GtkButton::leave signal to the given GtkButton.

button : The GtkButton you want to send the signal to.

gtk_button_set_relief ()

void                gtk_button_set_relief               (GtkButton *button,
                                                         GtkReliefStyle newstyle);

Sets the relief style of the edges of the given GtkButton widget. Three styles exist, GTK_RELIEF_NORMAL, GTK_RELIEF_HALF, GTK_RELIEF_NONE. The default style is, as one can guess, GTK_RELIEF_NORMAL.

button : | The GtkButton you want to set relief styles of.
newstyle : | The GtkReliefStyle as described above.

gtk_button_get_relief ()

GtkReliefStyle      gtk_button_get_relief               (GtkButton *button);

Returns the current relief style of the given GtkButton.

button : | The GtkButton you want the GtkReliefStyle from.
Returns : | The current GtkReliefStyle

gtk_button_get_label ()

const gchar*        gtk_button_get_label                (GtkButton *button);

Fetches the text from the label of the button, as set by gtk_button_set_label(). If the label text has not been set the return value will be NULL. This will be the case if you create an empty button with gtk_button_new() to use as a container.

button : | a GtkButton
Returns : | The text of the label widget. This string is owned by the widget and must not be modified or freed.

gtk_button_set_label ()

void                gtk_button_set_label                (GtkButton *button,
                                                         const gchar *label);

Sets the text of the label of the button to str. This text is also used to select the stock item if gtk_button_set_use_stock() is used.

This will also clear any previously set labels.

button : | a GtkButton
label : | a string

gtk_button_get_use_stock ()

gboolean            gtk_button_get_use_stock            (GtkButton *button);

Returns whether the button label is a stock item.

button : | a GtkButton
Returns : | TRUE if the button label is used to select a stock item instead of being used directly as the label text.

gtk_button_set_use_stock ()

void                gtk_button_set_use_stock            (GtkButton *button,
                                                         gboolean use_stock);

If true, the label set on the button is used as a stock id to select the stock item for the button.

button : | a GtkButton
use_stock : | TRUE if the button should use a stock item

gtk_button_get_use_underline ()

gboolean            gtk_button_get_use_underline        (GtkButton *button);

Returns whether an embedded underline in the button label indicates a mnemonic. See gtk_button_set_use_underline().

button : | a GtkButton
Returns : | TRUE if an embedded underline in the button label indicates the mnemonic accelerator keys.

gtk_button_set_use_underline ()

void                gtk_button_set_use_underline        (GtkButton *button,
                                                         gboolean use_underline);

If true, an underline in the text of the button label indicates the next character should be used for the mnemonic accelerator key.

button : | a GtkButton
use_underline : | TRUE if underlines in the text indicate mnemonics

gtk_button_set_focus_on_click ()

void                gtk_button_set_focus_on_click       (GtkButton *button,
                                                         gboolean focus_on_click);

Sets whether the button will grab focus when it is clicked with the mouse. Making mouse clicks not grab focus is useful in places like toolbars where you don't want the keyboard focus removed from the main area of the application.

button : | a GtkButton
focus_on_click : | whether the button grabs focus when clicked with the mouse

Since 2.4

gtk_button_get_focus_on_click ()

gboolean            gtk_button_get_focus_on_click       (GtkButton *button);

Returns whether the button grabs focus when it is clicked with the mouse. See gtk_button_set_focus_on_click().

button : | a GtkButton
Returns : | TRUE if the button grabs focus when it is clicked with the mouse.

Since 2.4

gtk_button_set_alignment ()

void                gtk_button_set_alignment            (GtkButton *button,
                                                         gfloat xalign,
                                                         gfloat yalign);

Sets the alignment of the child. This property has no effect unless the child is a GtkMisc or a GtkAligment.

button : | a GtkButton
xalign : | the horizontal position of the child, 0.0 is left aligned, 1.0 is right aligned
yalign : | the vertical position of the child, 0.0 is top aligned, 1.0 is bottom aligned

Since 2.4

gtk_button_get_alignment ()

void                gtk_button_get_alignment            (GtkButton *button,
                                                         gfloat *xalign,
                                                         gfloat *yalign);

Gets the alignment of the child in the button.

button : | a GtkButton
xalign : | return location for horizontal alignment
yalign : | return location for vertical alignment

Since 2.4

gtk_button_set_image ()

void                gtk_button_set_image                (GtkButton *button,
                                                         GtkWidget *image);

Set the image of button to the given widget. Note that it depends on the gtk-button-images setting whether the image will be displayed or not, you don't have to call gtk_widget_show() on image yourself.

button : | a GtkButton
image : | a widget to set as the image for the button

Since 2.6

gtk_button_get_image ()

GtkWidget*          gtk_button_get_image                (GtkButton *button);

Gets the widget that is currenty set as the image of button. This may have been explicitly set by gtk_button_set_image() or constructed by gtk_button_new_from_stock().

button : | a GtkButton
Returns : | a GtkWidget or NULL in case there is no image

Since 2.6

gtk_button_set_image_position ()

void                gtk_button_set_image_position       (GtkButton *button,
                                                         GtkPositionType position);

Sets the position of the image relative to the text inside the button.

button : | a GtkButton
position : | the position

Since 2.10

gtk_button_get_image_position ()

GtkPositionType     gtk_button_get_image_position       (GtkButton *button);

Gets the position of the image relative to the text inside the button.

button : | a GtkButton
Returns : | the position

Since 2.10

Property Details

The "focus-on-click" property

  "focus-on-click"           gboolean              : Read / Write

Whether the button grabs focus when it is clicked with the mouse.

Default value: TRUE

The "image" property

  "image"                    GtkWidget             : Read / Write

Child widget to appear next to the button text.

The "image-position" property

  "image-position"           GtkPositionType       : Read / Write

The position of the image relative to the text inside the button.

Default value: GTK_POS_LEFT

Since 2.10

The "label" property

  "label"                    gchararray            : Read / Write / Construct

Text of the label widget inside the button, if the button contains a label widget.

Default value: NULL

The "relief" property

  "relief"                   GtkReliefStyle        : Read / Write

The border relief style.

Default value: GTK_RELIEF_NORMAL

The "use-stock" property

  "use-stock"                gboolean              : Read / Write / Construct

If set, the label is used to pick a stock item instead of being displayed.

Default value: FALSE

The "use-underline" property

  "use-underline"            gboolean              : Read / Write / Construct

If set, an underline in the text indicates the next character should be used for the mnemonic accelerator key.

Default value: FALSE

The "xalign" property

  "xalign"                   gfloat                : Read / Write

If the child of the button is a GtkMisc or GtkAlignment, this property can be used to control it's horizontal alignment. 0.0 is left aligned, 1.0 is right aligned.

Allowed values: [0,1]

Default value: 0.5

Since 2.4

The "yalign" property

  "yalign"                   gfloat                : Read / Write

If the child of the button is a GtkMisc or GtkAlignment, this property can be used to control it's vertical alignment. 0.0 is top aligned, 1.0 is bottom aligned.

Allowed values: [0,1]

Default value: 0.5

Since 2.4

Style Property Details

The "child-displacement-x" style property

  "child-displacement-x"     gint                  : Read

How far in the x direction to move the child when the button is depressed.

Default value: 0

The "child-displacement-y" style property

  "child-displacement-y"     gint                  : Read

How far in the y direction to move the child when the button is depressed.

Default value: 0

The "default-border" style property

  "default-border"           GtkBorder             : Read

Extra space to add for CAN_DEFAULT buttons.

The "default-outside-border" style property

  "default-outside-border"   GtkBorder             : Read

Extra space to add for CAN_DEFAULT buttons that is always drawn outside the border.

The "displace-focus" style property

  "displace-focus"           gboolean              : Read

Whether the child_displacement_x/child_displacement_y properties should also affect the focus rectangle.

Default value: FALSE

Since 2.6

The "image-spacing" style property

  "image-spacing"            gint                  : Read

Spacing in pixels between the image and label.

Allowed values: >= 0

Default value: 2

The "inner-border" style property

  "inner-border"             GtkBorder             : Read

Sets the border between the button edges and child.

Since 2.10

Signal Details

The "activate" signal

void                user_function                      (GtkButton *widget,
                                                        gpointer   user_data)      : Run First / Action

The "activate" signal on GtkButton is an action signal and emitting it causes the button to animate press then release. Applications should never connect to this signal, but use the "clicked" signal.

widget : | the object which received the signal.
user_data : | user data set when the signal handler was connected.

The "clicked" signal

void                user_function                      (GtkButton *button,
                                                        gpointer   user_data)      : Run First / Action

Emitted when the button has been activated (pressed and released).

button : | the object that received the signal
user_data : | user data set when the signal handler was connected.

The "enter" signal

void                user_function                      (GtkButton *button,
                                                        gpointer   user_data)      : Run First

Emitted when the pointer enters the button.

Deprecated: Use the GtkWidget::enter-notify-event signal.

button : | the object that received the signal
user_data : | user data set when the signal handler was connected.

The "leave" signal

void                user_function                      (GtkButton *button,
                                                        gpointer   user_data)      : Run First

Emitted when the pointer leaves the button.

Deprecated: Use the GtkWidget::leave-notify-event signal.

button : | the object that received the signal
user_data : | user data set when the signal handler was connected.

The "pressed" signal

void                user_function                      (GtkButton *button,
                                                        gpointer   user_data)      : Run First

Emitted when the button is pressed.

Deprecated: Use the GtkWidget::button-press-event signal.

button : | the object that received the signal
user_data : | user data set when the signal handler was connected.

The "released" signal

void                user_function                      (GtkButton *button,
                                                        gpointer   user_data)      : Run First

Emitted when the button is released.

Deprecated: Use the GtkWidget::button-release-event signal.

button : | the object that received the signal
user_data : | user data set when the signal handler was connected.


GtkButtonBox

GtkButtonBox — Base class for GtkHButtonBox and GtkVButtonBox

Synopsis

#include <gtk/gtk.h>

                    GtkButtonBox;
#define             GTK_BUTTONBOX_DEFAULT
#define             gtk_button_box_get_spacing          (b)
GtkButtonBoxStyle   gtk_button_box_get_layout           (GtkButtonBox *widget);
void                gtk_button_box_get_child_size       (GtkButtonBox *widget,
                                                         gint *min_width,
                                                         gint *min_height);
void                gtk_button_box_get_child_ipadding   (GtkButtonBox *widget,
                                                         gint *ipad_x,
                                                         gint *ipad_y);
gboolean            gtk_button_box_get_child_secondary  (GtkButtonBox *widget,
                                                         GtkWidget *child);
#define             gtk_button_box_set_spacing          (b,s)
void                gtk_button_box_set_layout           (GtkButtonBox *widget,
                                                         GtkButtonBoxStyle layout_style);
void                gtk_button_box_set_child_size       (GtkButtonBox *widget,
                                                         gint min_width,
                                                         gint min_height);
void                gtk_button_box_set_child_ipadding   (GtkButtonBox *widget,
                                                         gint ipad_x,
                                                         gint ipad_y);
void                gtk_button_box_set_child_secondary  (GtkButtonBox *widget,
                                                         GtkWidget *child,
                                                         gboolean is_secondary);

Object Hierarchy

  GObject
   +----GInitiallyUnowned
         +----GtkObject
               +----GtkWidget
                     +----GtkContainer
                           +----GtkBox
                                 +----GtkButtonBox
                                       +----GtkHButtonBox
                                       +----GtkVButtonBox

Implemented Interfaces

GtkButtonBox implements AtkImplementorIface.

Properties

  "layout-style"             GtkButtonBoxStyle     : Read / Write

Child Properties

  "secondary"                gboolean              : Read / Write

Style Properties

  "child-internal-pad-x"     gint                  : Read
  "child-internal-pad-y"     gint                  : Read
  "child-min-height"         gint                  : Read
  "child-min-width"          gint                  : Read

Description

The primary purpose of this class is to keep track of the various properties of GtkHButtonBox and GtkVButtonBox widgets.

gtk_button_box_get_child_size() retrieves the minimum width and height for widgets in a given button box. gtk_button_box_set_child_size() allows those properties to be changed.

The internal padding of buttons can be retrieved and changed per button box using gtk_button_box_get_child_ipadding() and gtk_button_box_set_child_ipadding() respectively.

gtk_button_box_get_spacing() and gtk_button_box_set_spacing() retrieve and change default number of pixels between buttons, respectively.

gtk_button_box_get_layout() and gtk_button_box_set_layout() retrieve and alter the method used to spread the buttons in a button box across the container, respectively.

The main purpose of GtkButtonBox is to make sure the children have all the same size. Therefore it ignores the homogeneous property which it inherited from GtkBox, and always behaves as if homogeneous was TRUE.

Details

GtkButtonBox

typedef struct _GtkButtonBox GtkButtonBox;

This is a read-only struct; no members should be modified directly.

GTK_BUTTONBOX_DEFAULT

#define GTK_BUTTONBOX_DEFAULT -1

Used internally only.

gtk_button_box_get_spacing()

#define gtk_button_box_get_spacing(b)   gtk_box_get_spacing (GTK_BOX (b))

Warning

gtk_button_box_get_spacing is deprecated and should not be used in newly-written code.

Retrieves how much space a button box is placing between each child button.

b : | a GtkButtonBox
Returns : | the current spacing applied to the buttons in widget.

gtk_button_box_get_layout ()

GtkButtonBoxStyle   gtk_button_box_get_layout           (GtkButtonBox *widget);

Retrieves the method being used to arrange the buttons in a button box.

widget : | a GtkButtonBox.
Returns : | the method used to layout buttons in widget.

gtk_button_box_get_child_size ()

void                gtk_button_box_get_child_size       (GtkButtonBox *widget,
                                                         gint *min_width,
                                                         gint *min_height);

Warning

gtk_button_box_get_child_size is deprecated and should not be used in newly-written code. Use the style properties "child-min-width/-height" instead.

Retrieves the current width and height of all child widgets in a button box. min_width and min_height are filled with those values, respectively.

widget : | a GtkButtonBox.
min_width : | the width of the buttons contained by widget.
min_height : | the height of the buttons contained by widget.

gtk_button_box_get_child_ipadding ()

void                gtk_button_box_get_child_ipadding   (GtkButtonBox *widget,
                                                         gint *ipad_x,
                                                         gint *ipad_y);

Warning

gtk_button_box_get_child_ipadding is deprecated and should not be used in newly-written code. Use the style properties "child-internal-pad-x/-y" instead.

Gets the default number of pixels that pad the buttons in a given button box.

widget : | a GtkButtonBox.
ipad_x : | the horizontal padding used by buttons in widget.
ipad_y : | the vertical padding used by buttons in widget.

gtk_button_box_get_child_secondary ()

gboolean            gtk_button_box_get_child_secondary  (GtkButtonBox *widget,
                                                         GtkWidget *child);

Returns whether child should appear in a secondary group of children.

widget : | a GtkButtonBox
child : | a child of widget
Returns : | whether child should appear in a secondary group of children.

Since 2.4

gtk_button_box_set_spacing()

#define gtk_button_box_set_spacing(b,s) gtk_box_set_spacing (GTK_BOX (b), s)

Warning

gtk_button_box_set_spacing is deprecated and should not be used in newly-written code.

Sets the amount of spacing between buttons in a given button box.

b : | a GtkButtonBox.
s : | the number of pixels of spacing.

gtk_button_box_set_layout ()

void                gtk_button_box_set_layout           (GtkButtonBox *widget,
                                                         GtkButtonBoxStyle layout_style);

Changes the way buttons are arranged in their container.

widget : | a GtkButtonBox.
layout_style : | the new layout style.

gtk_button_box_set_child_size ()

void                gtk_button_box_set_child_size       (GtkButtonBox *widget,
                                                         gint min_width,
                                                         gint min_height);

Warning

gtk_button_box_set_child_size is deprecated and should not be used in newly-written code. Use the style properties "child-min-width/-height" instead.

Sets a new default size for the children of a given button box.

widget : | a GtkButtonBox.
min_width : | a default width for buttons in widget.
min_height : | a default height for buttons in widget.

gtk_button_box_set_child_ipadding ()

void                gtk_button_box_set_child_ipadding   (GtkButtonBox *widget,
                                                         gint ipad_x,
                                                         gint ipad_y);

Warning

gtk_button_box_set_child_ipadding is deprecated and should not be used in newly-written code. Use the style properties "child-internal-pad-x/-y" instead.

Changes the amount of internal padding used by all buttons in a given button box.

widget : | a GtkButtonBox.
ipad_x : | the horizontal padding that should be used by each button in widget.
ipad_y : | the vertical padding that should be used by each button in widget.

gtk_button_box_set_child_secondary ()

void                gtk_button_box_set_child_secondary  (GtkButtonBox *widget,
                                                         GtkWidget *child,
                                                         gboolean is_secondary);

Sets whether child should appear in a secondary group of children. A typical use of a secondary child is the help button in a dialog.

This group appears after the other children if the style is GTK_BUTTONBOX_START, GTK_BUTTONBOX_SPREAD or GTK_BUTTONBOX_EDGE, and before the other children if the style is GTK_BUTTONBOX_END. For horizontal button boxes, the definition of before/after depends on direction of the widget (see gtk_widget_set_direction()). If the style is GTK_BUTTONBOX_START or GTK_BUTTONBOX_END, then the secondary children are aligned at the other end of the button box from the main children. For the other styles, they appear immediately next to the main children.

widget : | a GtkButtonBox
child : | a child of widget
is_secondary : | if TRUE, the child appears in a secondary group of the button box.

Property Details

The "layout-style" property

  "layout-style"             GtkButtonBoxStyle     : Read / Write

How to layout the buttons in the box. Possible values are default, spread, edge, start and end.

Default value: GTK_BUTTONBOX_DEFAULT_STYLE

Child Property Details

The "secondary" child property

  "secondary"                gboolean              : Read / Write

If TRUE, the child appears in a secondary group of children, suitable for, e.g., help buttons.

Default value: FALSE

Style Property Details

The "child-internal-pad-x" style property

  "child-internal-pad-x"     gint                  : Read

Amount to increase child's size on either side.

Allowed values: >= 0

Default value: 4

The "child-internal-pad-y" style property

  "child-internal-pad-y"     gint                  : Read

Amount to increase child's size on the top and bottom.

Allowed values: >= 0

Default value: 0

The "child-min-height" style property

  "child-min-height"         gint                  : Read

Minimum height of buttons inside the box.

Allowed values: >= 0

Default value: 27

The "child-min-width" style property

  "child-min-width"          gint                  : Read

Minimum width of buttons inside the box.

Allowed values: >= 0

Default value: 85

See Also

GtkVButtonBox | Vertical sub-class of GtkButtonBox.
GtkHButtonBox | Horizontal sub-class of GtkButtonBox.


GtkCalendar

GtkCalendar — Displays a calendar and allows the user to select a date

Synopsis

#include <gtk/gtk.h>

                    GtkCalendar;
enum                GtkCalendarDisplayOptions;
GtkWidget*          gtk_calendar_new                    (void);
gboolean            gtk_calendar_select_month           (GtkCalendar *calendar,
                                                         guint month,
                                                         guint year);
void                gtk_calendar_select_day             (GtkCalendar *calendar,
                                                         guint day);
gboolean            gtk_calendar_mark_day               (GtkCalendar *calendar,
                                                         guint day);
gboolean            gtk_calendar_unmark_day             (GtkCalendar *calendar,
                                                         guint day);
void                gtk_calendar_clear_marks            (GtkCalendar *calendar);
GtkCalendarDisplayOptions gtk_calendar_get_display_options
                                                        (GtkCalendar *calendar);
void                gtk_calendar_set_display_options    (GtkCalendar *calendar,
                                                         GtkCalendarDisplayOptions flags);
void                gtk_calendar_display_options        (GtkCalendar *calendar,
                                                         GtkCalendarDisplayOptions flags);
void                gtk_calendar_get_date               (GtkCalendar *calendar,
                                                         guint *year,
                                                         guint *month,
                                                         guint *day);
void                gtk_calendar_freeze                 (GtkCalendar *calendar);
void                gtk_calendar_thaw                   (GtkCalendar *calendar);

Object Hierarchy

  GObject
   +----GInitiallyUnowned
         +----GtkObject
               +----GtkWidget
                     +----GtkCalendar

Implemented Interfaces

GtkCalendar implements AtkImplementorIface.

Properties

  "day"                      gint                  : Read / Write
  "month"                    gint                  : Read / Write
  "no-month-change"          gboolean              : Read / Write
  "show-day-names"           gboolean              : Read / Write
  "show-heading"             gboolean              : Read / Write
  "show-week-numbers"        gboolean              : Read / Write
  "year"                     gint                  : Read / Write

Signals

  "day-selected"                                   : Run First
  "day-selected-double-click"                      : Run First
  "month-changed"                                  : Run First
  "next-month"                                     : Run First
  "next-year"                                      : Run First
  "prev-month"                                     : Run First
  "prev-year"                                      : Run First

Description

GtkCalendar is a widget that displays a calendar, one month at a time. It can be created with gtk_calendar_new().

The month and year currently displayed can be altered with gtk_calendar_select_month(). The exact day can be selected from the displayed month using gtk_calendar_select_day().

To place a visual marker on a particular day, use gtk_calendar_mark_day() and to remove the marker, gtk_calendar_unmark_day(). Alternative, all marks can be cleared with gtk_calendar_clear_marks().

The way in which the calendar itself is displayed can be altered using gtk_calendar_set_display_options().

The selected date can be retrieved from a GtkCalendar using gtk_calendar_get_date().

Details

GtkCalendar

typedef struct _GtkCalendar GtkCalendar;

num_marked_dates is an integer containing the number of days that have a mark over them.

marked_date is an array containing the day numbers that currently have a mark over them.

month, year, and selected_day contain the currently visible month, year, and selected day respectively.

All of these fields should be considered read only, and everything in this struct should only be modified using the functions provided below.

Note

Note that month is zero-based (i.e it allowed values are 0-11) while selected_day is one-based (i.e. allowed values are 1-31).

enum GtkCalendarDisplayOptions

typedef enum
{
  GTK_CALENDAR_SHOW_HEADING		= 1 << 0,
  GTK_CALENDAR_SHOW_DAY_NAMES		= 1 << 1,
  GTK_CALENDAR_NO_MONTH_CHANGE		= 1 << 2,
  GTK_CALENDAR_SHOW_WEEK_NUMBERS	= 1 << 3,
  GTK_CALENDAR_WEEK_START_MONDAY	= 1 << 4
} GtkCalendarDisplayOptions;

These options can be used to influence the display and behaviour of a GtkCalendar.

GTK_CALENDAR_SHOW_HEADING | Specifies that the month and year should be displayed.
GTK_CALENDAR_SHOW_DAY_NAMES | Specifies that three letter day descriptions should be present.
GTK_CALENDAR_NO_MONTH_CHANGE | Prevents the user from switching months with the calendar.
GTK_CALENDAR_SHOW_WEEK_NUMBERS | Displays each week numbers of the current year, down the left side of the calendar.
GTK_CALENDAR_WEEK_START_MONDAY | Since GTK+ 2.4, this option is deprecated and ignored by GTK+. The information on which day the calendar week starts is derived from the locale.

gtk_calendar_new ()

GtkWidget*          gtk_calendar_new                    (void);

Creates a new calendar, with the current date being selected.

Returns : a newly GtkCalendar widget

gtk_calendar_select_month ()

gboolean            gtk_calendar_select_month           (GtkCalendar *calendar,
                                                         guint month,
                                                         guint year);

Shifts the calendar to a different month.

calendar : | a GtkCalendar
month : | a month number between 0 and 11.
year : | the year the month is in.
Returns : | TRUE, always

gtk_calendar_select_day ()

void                gtk_calendar_select_day             (GtkCalendar *calendar,
                                                         guint day);

Selects a day from the current month.

calendar : | a GtkCalendar.
day : | the day number between 1 and 31, or 0 to unselect the currently selected day.

gtk_calendar_mark_day ()

gboolean            gtk_calendar_mark_day               (GtkCalendar *calendar,
                                                         guint day);

Places a visual marker on a particular day.

calendar : | a GtkCalendar
day : | the day number to mark between 1 and 31.
Returns : | TRUE, always

gtk_calendar_unmark_day ()

gboolean            gtk_calendar_unmark_day             (GtkCalendar *calendar,
                                                         guint day);

Removes the visual marker from a particular day.

calendar : | a GtkCalendar.
day : | the day number to unmark between 1 and 31.
Returns : | TRUE, always

gtk_calendar_clear_marks ()

void                gtk_calendar_clear_marks            (GtkCalendar *calendar);

Remove all visual markers.

calendar : a GtkCalendar

gtk_calendar_get_display_options ()

GtkCalendarDisplayOptions gtk_calendar_get_display_options
                                                        (GtkCalendar *calendar);

Returns the current display options of calendar.

calendar : | a GtkCalendar
Returns : | the display options.

Since 2.4

gtk_calendar_set_display_options ()

void                gtk_calendar_set_display_options    (GtkCalendar *calendar,
                                                         GtkCalendarDisplayOptions flags);

Sets display options (whether to display the heading and the month headings).

calendar : | a GtkCalendar
flags : | the display options to set

Since 2.4

gtk_calendar_display_options ()

void                gtk_calendar_display_options        (GtkCalendar *calendar,
                                                         GtkCalendarDisplayOptions flags);

Warning

gtk_calendar_display_options is deprecated and should not be used in newly-written code.

Sets display options (whether to display the heading and the month headings).

calendar : | a GtkCalendar.
flags : | the display options to set.

gtk_calendar_get_date ()

void                gtk_calendar_get_date               (GtkCalendar *calendar,
                                                         guint *year,
                                                         guint *month,
                                                         guint *day);

Obtains the selected date from a GtkCalendar.

calendar : | a GtkCalendar
year : | location to store the year number, or NULL
month : | location to store the month number (between 0 and 11), or NULL
day : | location to store the day number (between 1 and 31), or NULL

gtk_calendar_freeze ()

void                gtk_calendar_freeze                 (GtkCalendar *calendar);

Warning

gtk_calendar_freeze has been deprecated since version 2.8 and should not be used in newly-written code.

Does nothing. Previously locked the display of the calendar until it was thawed with gtk_calendar_thaw().

calendar : a GtkCalendar

gtk_calendar_thaw ()

void                gtk_calendar_thaw                   (GtkCalendar *calendar);

Warning

gtk_calendar_thaw has been deprecated since version 2.8 and should not be used in newly-written code.

Does nothing. Previously defrosted a calendar; all the changes made since the last gtk_calendar_freeze() were displayed.

calendar : a GtkCalendar

Property Details

The "day" property

  "day"                      gint                  : Read / Write

The selected day (as a number between 1 and 31, or 0 to unselect the currently selected day).

Allowed values: [0,31]

Default value: 0

The "month" property

  "month"                    gint                  : Read / Write

The selected month (as a number between 0 and 11).

Allowed values: [0,11]

Default value: 0

The "no-month-change" property

  "no-month-change"          gboolean              : Read / Write

Determines whether the selected month can be changed.

Default value: FALSE

Since 2.4

The "show-day-names" property

  "show-day-names"           gboolean              : Read / Write

Determines whether day names are displayed.

Default value: TRUE

Since 2.4

The "show-heading" property

  "show-heading"             gboolean              : Read / Write

Determines whether a heading is displayed.

Default value: TRUE

Since 2.4

The "show-week-numbers" property

  "show-week-numbers"        gboolean              : Read / Write

Determines whether week numbers are displayed.

Default value: FALSE

Since 2.4

The "year" property

  "year"                     gint                  : Read / Write

The selected year.

Allowed values: >= 0

Default value: 0

Signal Details

The "day-selected" signal

void                user_function                      (GtkCalendar *calendar,
                                                        gpointer     user_data)      : Run First

Emitted when the user selects a day.

calendar : | the object which received the signal.
user_data : | user data set when the signal handler was connected.

The "day-selected-double-click" signal

void                user_function                      (GtkCalendar *calendar,
                                                        gpointer     user_data)      : Run First

calendar : | the object which received the signal.
user_data : | user data set when the signal handler was connected.

The "month-changed" signal

void                user_function                      (GtkCalendar *calendar,
                                                        gpointer     user_data)      : Run First

Emitted when the user clicks a button to change the selected month on a calendar.

calendar : | the object which received the signal.
user_data : | user data set when the signal handler was connected.

The "next-month" signal

void                user_function                      (GtkCalendar *calendar,
                                                        gpointer     user_data)      : Run First

calendar : | the object which received the signal.
user_data : | user data set when the signal handler was connected.

The "next-year" signal

void                user_function                      (GtkCalendar *calendar,
                                                        gpointer     user_data)      : Run First

calendar : | the object which received the signal.
user_data : | user data set when the signal handler was connected.

The "prev-month" signal

void                user_function                      (GtkCalendar *calendar,
                                                        gpointer     user_data)      : Run First

calendar : | the object which received the signal.
user_data : | user data set when the signal handler was connected.

The "prev-year" signal

void                user_function                      (GtkCalendar *calendar,
                                                        gpointer     user_data)      : Run First

calendar : | the object which received the signal.
user_data : | user data set when the signal handler was connected.


GtkCellEditable

GtkCellEditable — Interface for widgets which can are used for editing cells

Synopsis

#include <gtk/gtk.h>

                    GtkCellEditable;
                    GtkCellEditableIface;
void                gtk_cell_editable_start_editing     (GtkCellEditable *cell_editable,
                                                         GdkEvent *event);
void                gtk_cell_editable_editing_done      (GtkCellEditable *cell_editable);
void                gtk_cell_editable_remove_widget     (GtkCellEditable *cell_editable);

Object Hierarchy

  GInterface
   +----GtkCellEditable

Prerequisites

GtkCellEditable requires GtkWidget.

Known Implementations

GtkCellEditable is implemented by GtkEntry, GtkComboBox, GtkSpinButton and GtkComboBoxEntry.

Signals

  "editing-done"                                   : Run Last
  "remove-widget"                                  : Run Last

Description

The GtkCellEditable interface must be implemented for widgets to be usable when editing the contents of a GtkTreeView cell.

Details

GtkCellEditable

typedef struct _GtkCellEditable GtkCellEditable;

GtkCellEditableIface

typedef struct {
  GTypeInterface g_iface;

  /* signals */
  void (* editing_done)  (GtkCellEditable *cell_editable);
  void (* remove_widget) (GtkCellEditable *cell_editable);

  /* virtual table */
  void (* start_editing) (GtkCellEditable *cell_editable,
              GdkEvent        *event);
} GtkCellEditableIface;

gtk_cell_editable_start_editing ()

void                gtk_cell_editable_start_editing     (GtkCellEditable *cell_editable,
                                                         GdkEvent *event);

Begins editing on a cell_editable. event is the GdkEvent that began the editing process. It may be NULL, in the instance that editing was initiated through programatic means.

cell_editable : | A GtkCellEditable
event : | A GdkEvent, or NULL

gtk_cell_editable_editing_done ()

void                gtk_cell_editable_editing_done      (GtkCellEditable *cell_editable);

Emits the "editing_done" signal. This signal is a sign for the cell renderer to update its value from the cell.

cell_editable : A GtkTreeEditable

gtk_cell_editable_remove_widget ()

void                gtk_cell_editable_remove_widget     (GtkCellEditable *cell_editable);

Emits the "remove_widget" signal. This signal is meant to indicate that the cell is finished editing, and the widget may now be destroyed.

cell_editable : A GtkTreeEditable

Signal Details

The "editing-done" signal

void                user_function                      (GtkCellEditable *celleditable,
                                                        gpointer         user_data)         : Run Last

celleditable : | the object which received the signal.
user_data : | user data set when the signal handler was connected.

The "remove-widget" signal

void                user_function                      (GtkCellEditable *celleditable,
                                                        gpointer         user_data)         : Run Last

celleditable : | the object which received the signal.
user_data : | user data set when the signal handler was connected.


GtkCellLayout

GtkCellLayout — An interface for packing cells

Synopsis

#include <gtk/gtk.h>

                    GtkCellLayout;
                    GtkCellLayoutIface;
void                (*GtkCellLayoutDataFunc)            (GtkCellLayout *cell_layout,
                                                         GtkCellRenderer *cell,
                                                         GtkTreeModel *tree_model,
                                                         GtkTreeIter *iter,
                                                         gpointer data);
void                gtk_cell_layout_pack_start          (GtkCellLayout *cell_layout,
                                                         GtkCellRenderer *cell,
                                                         gboolean expand);
void                gtk_cell_layout_pack_end            (GtkCellLayout *cell_layout,
                                                         GtkCellRenderer *cell,
                                                         gboolean expand);
void                gtk_cell_layout_reorder             (GtkCellLayout *cell_layout,
                                                         GtkCellRenderer *cell,
                                                         gint position);
void                gtk_cell_layout_clear               (GtkCellLayout *cell_layout);
void                gtk_cell_layout_set_attributes      (GtkCellLayout *cell_layout,
                                                         GtkCellRenderer *cell,
                                                         ...);
void                gtk_cell_layout_add_attribute       (GtkCellLayout *cell_layout,
                                                         GtkCellRenderer *cell,
                                                         const gchar *attribute,
                                                         gint column);
void                gtk_cell_layout_set_cell_data_func  (GtkCellLayout *cell_layout,
                                                         GtkCellRenderer *cell,
                                                         GtkCellLayoutDataFunc func,
                                                         gpointer func_data,
                                                         GDestroyNotify destroy);
void                gtk_cell_layout_clear_attributes    (GtkCellLayout *cell_layout,
                                                         GtkCellRenderer *cell);

Object Hierarchy

  GInterface
   +----GtkCellLayout

Prerequisites

GtkCellLayout requires GObject.

Known Implementations

GtkCellLayout is implemented by GtkCellView, GtkEntryCompletion, GtkTreeViewColumn, GtkComboBox, GtkIconView and GtkComboBoxEntry.

Description

GtkCellLayout is an interface to be implemented by all objects which want to provide a GtkTreeViewColumn-like API for packing cells, setting attributes and data funcs.

One of the notable features provided by implementations of GtkCellLayout are attributes. Attributes let you set the properties in flexible ways. They can just be set to constant values like regular properties. But they can also be mapped to a column of the underlying tree model with gtk_cell_layout_set_attributes(), which means that the value of the attribute can change from cell to cell as they are rendered by the cell renderer. Finally, it is possible to specify a function with gtk_cell_layout_set_cell_data_func() that is called to determine the value of the attribute for each cell that is rendered.

Details

GtkCellLayout

typedef struct _GtkCellLayout GtkCellLayout;

GtkCellLayoutIface

typedef struct {
  GTypeInterface g_iface;

  /* Virtual Table */
  void (* pack_start)         (GtkCellLayout         *cell_layout,
                               GtkCellRenderer       *cell,
                               gboolean               expand);
  void (* pack_end)           (GtkCellLayout         *cell_layout,
                               GtkCellRenderer       *cell,
                               gboolean               expand);
  void (* clear)              (GtkCellLayout         *cell_layout);
  void (* add_attribute)      (GtkCellLayout         *cell_layout,
                               GtkCellRenderer       *cell,
                               const gchar           *attribute,
                               gint                   column);
  void (* set_cell_data_func) (GtkCellLayout         *cell_layout,
                               GtkCellRenderer       *cell,
                               GtkCellLayoutDataFunc  func,
                               gpointer               func_data,
                               GDestroyNotify         destroy);
  void (* clear_attributes)   (GtkCellLayout         *cell_layout,
                               GtkCellRenderer       *cell);
  void (* reorder)            (GtkCellLayout         *cell_layout,
                               GtkCellRenderer       *cell,
                               gint                   position);
} GtkCellLayoutIface;

GtkCellLayoutDataFunc ()

void                (*GtkCellLayoutDataFunc)            (GtkCellLayout *cell_layout,
                                                         GtkCellRenderer *cell,
                                                         GtkTreeModel *tree_model,
                                                         GtkTreeIter *iter,
                                                         gpointer data);

A function which should set the value of cell_layout's cell renderer(s) as appropriate.

cell_layout : | a GtkCellLayout
cell : | the cell renderer whose value is to be set
tree_model : | the model
iter : | a GtkTreeIter indicating the row to set the value for
data : | user data passed to gtk_cell_layout_set_cell_data_func()

gtk_cell_layout_pack_start ()

void                gtk_cell_layout_pack_start          (GtkCellLayout *cell_layout,
                                                         GtkCellRenderer *cell,
                                                         gboolean expand);

Packs the cell into the beginning of cell_layout. If expand is FALSE, then the cell is allocated no more space than it needs. Any unused space is divided evenly between cells for which expand is TRUE.

Note that reusing the same cell renderer is not supported.

cell_layout : | A GtkCellLayout.
cell : | A GtkCellRenderer.
expand : | TRUE if cell is to be given extra space allocated to cell_layout.

Since 2.4

gtk_cell_layout_pack_end ()

void                gtk_cell_layout_pack_end            (GtkCellLayout *cell_layout,
                                                         GtkCellRenderer *cell,
                                                         gboolean expand);

Adds the cell to the end of cell_layout. If expand is FALSE, then the cell is allocated no more space than it needs. Any unused space is divided evenly between cells for which expand is TRUE.

Note that reusing the same cell renderer is not supported.

cell_layout : | A GtkCellLayout.
cell : | A GtkCellRenderer.
expand : | TRUE if cell is to be given extra space allocated to cell_layout.

Since 2.4

gtk_cell_layout_reorder ()

void                gtk_cell_layout_reorder             (GtkCellLayout *cell_layout,
                                                         GtkCellRenderer *cell,
                                                         gint position);

Re-inserts cell at position. Note that cell has already to be packed into cell_layout for this to function properly.

cell_layout : | A GtkCellLayout.
cell : | A GtkCellRenderer to reorder.
position : | New position to insert cell at.

Since 2.4

gtk_cell_layout_clear ()

void                gtk_cell_layout_clear               (GtkCellLayout *cell_layout);

Unsets all the mappings on all renderers on cell_layout and removes all renderers from cell_layout.

cell_layout : A GtkCellLayout.

Since 2.4

gtk_cell_layout_set_attributes ()

void                gtk_cell_layout_set_attributes      (GtkCellLayout *cell_layout,
                                                         GtkCellRenderer *cell,
                                                         ...);

Sets the attributes in list as the attributes of cell_layout. The attributes should be in attribute/column order, as in gtk_cell_layout_add_attribute(). All existing attributes are removed, and replaced with the new attributes.

cell_layout : | A GtkCellLayout.
cell : | A GtkCellRenderer.
... : | A NULL-terminated list of attributes.

Since 2.4

gtk_cell_layout_add_attribute ()

void                gtk_cell_layout_add_attribute       (GtkCellLayout *cell_layout,
                                                         GtkCellRenderer *cell,
                                                         const gchar *attribute,
                                                         gint column);

Adds an attribute mapping to the list in cell_layout. The column is the column of the model to get a value from, and the attribute is the parameter on cell to be set from the value. So for example if column 2 of the model contains strings, you could have the "text" attribute of a GtkCellRendererText get its values from column 2.

cell_layout : | A GtkCellLayout.
cell : | A GtkCellRenderer.
attribute : | An attribute on the renderer.
column : | The column position on the model to get the attribute from.

Since 2.4

gtk_cell_layout_set_cell_data_func ()

void                gtk_cell_layout_set_cell_data_func  (GtkCellLayout *cell_layout,
                                                         GtkCellRenderer *cell,
                                                         GtkCellLayoutDataFunc func,
                                                         gpointer func_data,
                                                         GDestroyNotify destroy);

Sets the GtkCellLayoutDataFunc to use for cell_layout. This function is used instead of the standard attributes mapping for setting the column value, and should set the value of cell_layout's cell renderer(s) as appropriate. func may be NULL to remove and older one.

cell_layout : | A GtkCellLayout.
cell : | A GtkCellRenderer.
func : | The GtkCellLayoutDataFunc to use.
func_data : | The user data for func.
destroy : | The destroy notification for func_data.

Since 2.4

gtk_cell_layout_clear_attributes ()

void                gtk_cell_layout_clear_attributes    (GtkCellLayout *cell_layout,
                                                         GtkCellRenderer *cell);

Clears all existing attributes previously set with gtk_cell_layout_set_attributes().

cell_layout : | A GtkCellLayout.
cell : | A GtkCellRenderer to clear the attribute mapping on.

Since 2.4


GtkCellRenderer

GtkCellRenderer — An object for rendering a single cell on a GdkDrawable

Synopsis

#include <gtk/gtk.h>

enum                GtkCellRendererState;
enum                GtkCellRendererMode;
                    GtkCellRenderer;
void                gtk_cell_renderer_get_size          (GtkCellRenderer *cell,
                                                         GtkWidget *widget,
                                                         GdkRectangle *cell_area,
                                                         gint *x_offset,
                                                         gint *y_offset,
                                                         gint *width,
                                                         gint *height);
void                gtk_cell_renderer_render            (GtkCellRenderer *cell,
                                                         GdkWindow *window,
                                                         GtkWidget *widget,
                                                         GdkRectangle *background_area,
                                                         GdkRectangle *cell_area,
                                                         GdkRectangle *expose_area,
                                                         GtkCellRendererState flags);
gboolean            gtk_cell_renderer_activate          (GtkCellRenderer *cell,
                                                         GdkEvent *event,
                                                         GtkWidget *widget,
                                                         const gchar *path,
                                                         GdkRectangle *background_area,
                                                         GdkRectangle *cell_area,
                                                         GtkCellRendererState flags);
GtkCellEditable*    gtk_cell_renderer_start_editing     (GtkCellRenderer *cell,
                                                         GdkEvent *event,
                                                         GtkWidget *widget,
                                                         const gchar *path,
                                                         GdkRectangle *background_area,
                                                         GdkRectangle *cell_area,
                                                         GtkCellRendererState flags);
void                gtk_cell_renderer_editing_canceled  (GtkCellRenderer *cell);
void                gtk_cell_renderer_stop_editing      (GtkCellRenderer *cell,
                                                         gboolean canceled);
void                gtk_cell_renderer_get_fixed_size    (GtkCellRenderer *cell,
                                                         gint *width,
                                                         gint *height);
void                gtk_cell_renderer_set_fixed_size    (GtkCellRenderer *cell,
                                                         gint width,
                                                         gint height);

Object Hierarchy

  GObject
   +----GInitiallyUnowned
         +----GtkObject
               +----GtkCellRenderer
                     +----GtkCellRendererText
                     +----GtkCellRendererPixbuf
                     +----GtkCellRendererProgress
                     +----GtkCellRendererToggle

Properties

  "cell-background"          gchararray            : Write
  "cell-background-gdk"      GdkColor              : Read / Write
  "cell-background-set"      gboolean              : Read / Write
  "height"                   gint                  : Read / Write
  "is-expanded"              gboolean              : Read / Write
  "is-expander"              gboolean              : Read / Write
  "mode"                     GtkCellRendererMode   : Read / Write
  "sensitive"                gboolean              : Read / Write
  "visible"                  gboolean              : Read / Write
  "width"                    gint                  : Read / Write
  "xalign"                   gfloat                : Read / Write
  "xpad"                     guint                 : Read / Write
  "yalign"                   gfloat                : Read / Write
  "ypad"                     guint                 : Read / Write

Signals

  "editing-canceled"                               : Run First
  "editing-started"                                : Run First

Description

The GtkCellRenderer is a base class of a set of objects used for rendering a cell to a GdkDrawable. These objects are used primarily by the GtkTreeView widget, though they aren't tied to them in any specific way. It is worth noting that GtkCellRenderer is not a GtkWidget and cannot be treated as such.

The primary use of a GtkCellRenderer is for drawing a certain graphical elements on a GdkDrawable. Typically, one cell renderer is used to draw many cells on the screen. To this extent, it isn't expected that a CellRenderer keep any permanent state around. Instead, any state is set just prior to use using GObjects property system. Then, the cell is measured using gtk_cell_renderer_get_size(). Finally, the cell is rendered in the correct location using gtk_cell_renderer_render().

There are a number of rules that must be followed when writing a new GtkCellRenderer. First and formost, it's important that a certain set of properties will always yield a cell renderer of the same size, barring a GtkStyle change. The GtkCellRenderer also has a number of generic properties that are expected to be honored by all children.

Beyond merely rendering a cell, cell renderers can optionally provide active user interface elements. A cell renderer can be activatable like GtkCellRendererToggle, which toggles when it gets activated by a mouse click, or it can be editable like GtkCellRendererText, which allows the user to edit the text using a GtkEntry. To make a cell renderer activatable or editable, you have to implement the activate or start_editing virtual functions, respectively.

Details

enum GtkCellRendererState

typedef enum
{
  GTK_CELL_RENDERER_SELECTED    = 1 << 0,
  GTK_CELL_RENDERER_PRELIT      = 1 << 1,
  GTK_CELL_RENDERER_INSENSITIVE = 1 << 2,
  /* this flag means the cell is in the sort column/row */
  GTK_CELL_RENDERER_SORTED      = 1 << 3,
  GTK_CELL_RENDERER_FOCUSED     = 1 << 4
} GtkCellRendererState;

Tells how a cell is to be rendererd.

GTK_CELL_RENDERER_SELECTED | The cell is currently selected, and probably has a selection colored background to render to.
GTK_CELL_RENDERER_PRELIT | The mouse is hovering over the cell.
GTK_CELL_RENDERER_INSENSITIVE | The cell is drawn in an insensitive manner
GTK_CELL_RENDERER_SORTED | The cell is in a sorted row
GTK_CELL_RENDERER_FOCUSED |

enum GtkCellRendererMode

typedef enum
{
  GTK_CELL_RENDERER_MODE_INERT,
  GTK_CELL_RENDERER_MODE_ACTIVATABLE,
  GTK_CELL_RENDERER_MODE_EDITABLE
} GtkCellRendererMode;

Identifies how the user can interact with a particular cell.

GTK_CELL_RENDERER_MODE_INERT | The cell is just for display and cannot be interacted with. Note that this doesn't mean that eg. the row being drawn can't be selected -- just that a particular element of it cannot be individually modified.
GTK_CELL_RENDERER_MODE_ACTIVATABLE | The cell can be clicked.
GTK_CELL_RENDERER_MODE_EDITABLE | The cell can be edited or otherwise modified.

GtkCellRenderer

typedef struct _GtkCellRenderer GtkCellRenderer;

gtk_cell_renderer_get_size ()

void                gtk_cell_renderer_get_size          (GtkCellRenderer *cell,
                                                         GtkWidget *widget,
                                                         GdkRectangle *cell_area,
                                                         gint *x_offset,
                                                         gint *y_offset,
                                                         gint *width,
                                                         gint *height);

Obtains the width and height needed to render the cell. Used by view widgets to determine the appropriate size for the cell_area passed to gtk_cell_renderer_render(). If cell_area is not NULL, fills in the x and y offsets (if set) of the cell relative to this location. Please note that the values set in width and height, as well as those in x_offset and y_offset are inclusive of the xpad and ypad properties.

cell : | a GtkCellRenderer
widget : | the widget the renderer is rendering to
cell_area : | The area a cell will be allocated, or NULL
x_offset : | location to return x offset of cell relative to cell_area, or NULL
y_offset : | location to return y offset of cell relative to cell_area, or NULL
width : | location to return width needed to render a cell, or NULL
height : | location to return height needed to render a cell, or NULL

gtk_cell_renderer_render ()

void                gtk_cell_renderer_render            (GtkCellRenderer *cell,
                                                         GdkWindow *window,
                                                         GtkWidget *widget,
                                                         GdkRectangle *background_area,
                                                         GdkRectangle *cell_area,
                                                         GdkRectangle *expose_area,
                                                         GtkCellRendererState flags);

Invokes the virtual render function of the GtkCellRenderer. The three passed-in rectangles are areas of window. Most renderers will draw within cell_area; the xalign, yalign, xpad, and ypad fields of the GtkCellRenderer should be honored with respect to cell_area. background_area includes the blank space around the cell, and also the area containing the tree expander; so the background_area rectangles for all cells tile to cover the entire window. expose_area is a clip rectangle.

cell : | a GtkCellRenderer
window : | a GdkDrawable to draw to
widget : | the widget owning window
background_area : | entire cell area (including tree expanders and maybe padding on the sides)
cell_area : | area normally rendered by a cell renderer
expose_area : | area that actually needs updating
flags : | flags that affect rendering

gtk_cell_renderer_activate ()

gboolean            gtk_cell_renderer_activate          (GtkCellRenderer *cell,
                                                         GdkEvent *event,
                                                         GtkWidget *widget,
                                                         const gchar *path,
                                                         GdkRectangle *background_area,
                                                         GdkRectangle *cell_area,
                                                         GtkCellRendererState flags);

Passes an activate event to the cell renderer for possible processing. Some cell renderers may use events; for example, GtkCellRendererToggle toggles when it gets a mouse click.

cell : | a GtkCellRenderer
event : | a GdkEvent
widget : | widget that received the event
path : | widget-dependent string representation of the event location; e.g. for GtkTreeView, a string representation of GtkTreePath
background_area : | background area as passed to gtk_cell_renderer_render
cell_area : | cell area as passed to gtk_cell_renderer_render
flags : | render flags
Returns : | TRUE if the event was consumed/handled

gtk_cell_renderer_start_editing ()

GtkCellEditable*    gtk_cell_renderer_start_editing     (GtkCellRenderer *cell,
                                                         GdkEvent *event,
                                                         GtkWidget *widget,
                                                         const gchar *path,
                                                         GdkRectangle *background_area,
                                                         GdkRectangle *cell_area,
                                                         GtkCellRendererState flags);

Passes an activate event to the cell renderer for possible processing.

cell : | a GtkCellRenderer
event : | a GdkEvent
widget : | widget that received the event
path : | widget-dependent string representation of the event location; e.g. for GtkTreeView, a string representation of GtkTreePath
background_area : | background area as passed to gtk_cell_renderer_render
cell_area : | cell area as passed to gtk_cell_renderer_render
flags : | render flags
Returns : | A new GtkCellEditable, or NULL

gtk_cell_renderer_editing_canceled ()

void                gtk_cell_renderer_editing_canceled  (GtkCellRenderer *cell);

Warning

gtk_cell_renderer_editing_canceled has been deprecated since version 2.6 and should not be used in newly-written code. Use gtk_cell_renderer_stop_editing() instead

Causes the cell renderer to emit the "editing-canceled" signal. This function is for use only by implementations of cell renderers that need to notify the client program that an editing process was canceled and the changes were not committed.

cell : A GtkCellRenderer

Since 2.4

gtk_cell_renderer_stop_editing ()

void                gtk_cell_renderer_stop_editing      (GtkCellRenderer *cell,
                                                         gboolean canceled);

Informs the cell renderer that the editing is stopped. If canceled is TRUE, the cell renderer will emit the "editing-canceled" signal. This function should be called by cell renderer implementations in response to the "editing-done" signal of GtkCellEditable.

cell : | A GtkCellRenderer
canceled : | TRUE if the editing has been canceled

Since 2.6

gtk_cell_renderer_get_fixed_size ()

void                gtk_cell_renderer_get_fixed_size    (GtkCellRenderer *cell,
                                                         gint *width,
                                                         gint *height);

Fills in width and height with the appropriate size of cell.

cell : | A GtkCellRenderer
width : | location to fill in with the fixed width of the widget, or NULL
height : | location to fill in with the fixed height of the widget, or NULL

gtk_cell_renderer_set_fixed_size ()

void                gtk_cell_renderer_set_fixed_size    (GtkCellRenderer *cell,
                                                         gint width,
                                                         gint height);

Sets the renderer size to be explicit, independent of the properties set.

cell : | A GtkCellRenderer
width : | the width of the cell renderer, or -1
height : | the height of the cell renderer, or -1

Property Details

The "cell-background" property

  "cell-background"          gchararray            : Write

Cell background color as a string.

Default value: NULL

The "cell-background-gdk" property

  "cell-background-gdk"      GdkColor              : Read / Write

Cell background color as a GdkColor.

The "cell-background-set" property

  "cell-background-set"      gboolean              : Read / Write

Whether this tag affects the cell background color.

Default value: FALSE

The "height" property

  "height"                   gint                  : Read / Write

The fixed height.

Allowed values: >= -1

Default value: -1

The "is-expanded" property

  "is-expanded"              gboolean              : Read / Write

Row is an expander row, and is expanded.

Default value: FALSE

The "is-expander" property

  "is-expander"              gboolean              : Read / Write

Row has children.

Default value: FALSE

The "mode" property

  "mode"                     GtkCellRendererMode   : Read / Write

Editable mode of the CellRenderer.

Default value: GTK_CELL_RENDERER_MODE_INERT

The "sensitive" property

  "sensitive"                gboolean              : Read / Write

Display the cell sensitive.

Default value: TRUE

The "visible" property

  "visible"                  gboolean              : Read / Write

Display the cell.

Default value: TRUE

The "width" property

  "width"                    gint                  : Read / Write

The fixed width.

Allowed values: >= -1

Default value: -1

The "xalign" property

  "xalign"                   gfloat                : Read / Write

The x-align.

Allowed values: [0,1]

Default value: 0.5

The "xpad" property

  "xpad"                     guint                 : Read / Write

The xpad.

Default value: 0

The "yalign" property

  "yalign"                   gfloat                : Read / Write

The y-align.

Allowed values: [0,1]

Default value: 0.5

The "ypad" property

  "ypad"                     guint                 : Read / Write

The ypad.

Default value: 0

Signal Details

The "editing-canceled" signal

void                user_function                      (GtkCellRenderer *renderer,
                                                        gpointer         user_data)      : Run First

This signal gets emitted when the user cancels the process of editing a cell. For example, an editable cell renderer could be written to cancel editing when the user presses Escape.

See also: gtk_cell_renderer_editing_canceled()

renderer : | the object which received the signal
user_data : | user data set when the signal handler was connected.

Since 2.4

The "editing-started" signal

void                user_function                      (GtkCellRenderer *renderer,
                                                        GtkCellEditable *editable,
                                                        gchar           *path,
                                                        gpointer         user_data)      : Run First

This signal gets emitted when a cell starts to be edited. The indended use of this signal is to do special setup on editable, e.g. adding a GtkEntryCompletion or setting up additional columns in a GtkComboBox.

Note that GTK+ doesn't guarantee that cell renderers will continue to use the same kind of widget for editing in future releases, therefore you should check the type of editable before doing any specific setup, as in the following example:

static void
text_editing_started (GtkCellRenderer *cell,
                      GtkCellEditable *editable,
                      const gchar     *path,
                      gpointer         data)
{
  if (GTK_IS_ENTRY (editable))
    {
      GtkEntry *entry = GTK_ENTRY (editable);

      /* ... create a GtkEntryCompletion */

      gtk_entry_set_completion (entry, completion);
    }
}

renderer : | the object which received the signal
editable : | the GtkCellEditable
path : | the path identifying the edited cell
user_data : | user data set when the signal handler was connected.

Since 2.6

See Also

GtkCellRendererText,GtkCellRendererPixbuf,GtkCellRendererToggle


GtkCellRendererAccel

GtkCellRendererAccel — Renders a keyboard accelerator in a cell

Synopsis

#include <gtk/gtk.h>

                    GtkCellRendererAccel;
enum                GtkCellRendererAccelMode;
GtkCellRenderer*    gtk_cell_renderer_accel_new         (void);

Object Hierarchy

  GObject
   +----GInitiallyUnowned
         +----GtkObject
               +----GtkCellRenderer
                     +----GtkCellRendererText
                           +----GtkCellRendererAccel

Properties

  "accel-key"                guint                 : Read / Write
  "accel-mode"               GtkCellRendererAccelMode  : Read / Write
  "accel-mods"               GdkModifierType       : Read / Write
  "keycode"                  guint                 : Read / Write

Signals

  "accel-cleared"                                  : Run Last
  "accel-edited"                                   : Run Last

Description

GtkCellRendererAccel displays a keyboard accelerator (i.e. a key combination like <Control>-a). If the cell renderer is editable, the accelerator can be changed by simply typing the new combination.

The GtkCellRendererAccel cell renderer was added in GTK+ 2.10.

Details

GtkCellRendererAccel

typedef struct _GtkCellRendererAccel GtkCellRendererAccel;

enum GtkCellRendererAccelMode

typedef enum
{
  GTK_CELL_RENDERER_ACCEL_MODE_GTK,
  GTK_CELL_RENDERER_ACCEL_MODE_OTHER
} GtkCellRendererAccelMode;

gtk_cell_renderer_accel_new ()

GtkCellRenderer*    gtk_cell_renderer_accel_new         (void);

Creates a new GtkCellRendererAccel.

Returns : the new cell renderer

Since 2.10

Property Details

The "accel-key" property

  "accel-key"                guint                 : Read / Write

The keyval of the accelerator.

Allowed values: <= G_MAXINT

Default value: 0

Since 2.10

The "accel-mode" property

  "accel-mode"               GtkCellRendererAccelMode  : Read / Write

Determines if the edited accelerators are GTK+ accelerators. If they are, consumed modifiers are suppressed, only accelerators accepted by GTK+ are allowed, and the accelerators are rendered in the same way as they are in menus.

Default value: GTK_CELL_RENDERER_ACCEL_MODE_GTK

Since 2.10

The "accel-mods" property

  "accel-mods"               GdkModifierType       : Read / Write

The modifier mask of the accelerator.

Since 2.10

The "keycode" property

  "keycode"                  guint                 : Read / Write

The hardware keycode of the accelerator. Note that the hardware keycode is only relevant if the key does not have a keyval. Normally, the keyboard configuration should assign keyvals to all keys.

Allowed values: <= G_MAXINT

Default value: 0

Since 2.10

Signal Details

The "accel-cleared" signal

void                user_function                      (GtkCellRendererAccel *accel,
                                                        gchar                *path_string,
                                                        gpointer              user_data)        : Run Last

Gets emitted when the user has removed the accelerator.

accel : | the object reveiving the signal
path_string : | the path identifying the row of the edited cell
user_data : | user data set when the signal handler was connected.

Since 2.10

The "accel-edited" signal

void                user_function                      (GtkCellRendererAccel *accel,
                                                        gchar                *path_string,
                                                        guint                 accel_key,
                                                        GdkModifierType       accel_mods,
                                                        guint                 hardware_keycode,
                                                        gpointer              user_data)             : Run Last

Gets emitted when the user has selected a new accelerator.

accel : | the object reveiving the signal
path_string : | the path identifying the row of the edited cell
accel_key : | the new accelerator keyval
accel_mods : | the new acclerator modifier mask
hardware_keycode : | the keycode of the new accelerator
user_data : | user data set when the signal handler was connected.

Since 2.10


GtkCellRendererCombo

GtkCellRendererCombo — Renders a combobox in a cell

Synopsis

#include <gtk/gtk.h>

                    GtkCellRendererCombo;
GtkCellRenderer*    gtk_cell_renderer_combo_new         (void);

Object Hierarchy

  GObject
   +----GInitiallyUnowned
         +----GtkObject
               +----GtkCellRenderer
                     +----GtkCellRendererText
                           +----GtkCellRendererCombo

Properties

  "has-entry"                gboolean              : Read / Write
  "model"                    GtkTreeModel          : Read / Write
  "text-column"              gint                  : Read / Write

Description

GtkCellRendererCombo renders text in a cell like GtkCellRendererText from which it is derived. But while GtkCellRendererText offers a simple entry to edit the text, GtkCellRendererCombo offers a GtkComboBox or GtkComboBoxEntry widget to edit the text. The values to display in the combo box are taken from the tree model specified in the model property.

The combo cell renderer takes care of adding a text cell renderer to the combo box and sets it to display the column specified by its text-column property. Further properties of the comnbo box can be set in a handler for the editing-started signal.

The GtkCellRendererCombo cell renderer was added in GTK+ 2.6.

Details

GtkCellRendererCombo

typedef struct _GtkCellRendererCombo GtkCellRendererCombo;

gtk_cell_renderer_combo_new ()

GtkCellRenderer*    gtk_cell_renderer_combo_new         (void);

Creates a new GtkCellRendererCombo. Adjust how text is drawn using object properties. Object properties can be set globally (with g_object_set()). Also, with GtkTreeViewColumn, you can bind a property to a value in a GtkTreeModel. For example, you can bind the "text" property on the cell renderer to a string value in the model, thus rendering a different string in each row of the GtkTreeView.

Returns : the new cell renderer

Since 2.6

Property Details

The "has-entry" property

  "has-entry"                gboolean              : Read / Write

If TRUE, the cell renderer will include an entry and allow to enter values other than the ones in the popup list.

Default value: TRUE

Since 2.6

The "model" property

  "model"                    GtkTreeModel          : Read / Write

Holds a tree model containing the possible values for the combo box. Use the text_column property to specify the column holding the values.

Since 2.6

The "text-column" property

  "text-column"              gint                  : Read / Write

Specifies the model column which holds the possible values for the combo box. Note that this refers to the model specified in the model property, not the model backing the tree view to which this cell renderer is attached.

GtkCellRendererCombo automatically adds a text cell renderer for this column to its combo box.

Allowed values: >= -1

Default value: -1

Since 2.6


GtkCellRendererPixbuf

GtkCellRendererPixbuf — Renders a pixbuf in a cell

Synopsis

#include <gtk/gtk.h>

                    GtkCellRendererPixbuf;
GtkCellRenderer*    gtk_cell_renderer_pixbuf_new        (void);

Object Hierarchy

  GObject
   +----GInitiallyUnowned
         +----GtkObject
               +----GtkCellRenderer
                     +----GtkCellRendererPixbuf

Properties

  "follow-state"             gboolean              : Read / Write
  "icon-name"                gchararray            : Read / Write
  "pixbuf"                   GdkPixbuf             : Read / Write
  "pixbuf-expander-closed"   GdkPixbuf             : Read / Write
  "pixbuf-expander-open"     GdkPixbuf             : Read / Write
  "stock-detail"             gchararray            : Read / Write
  "stock-id"                 gchararray            : Read / Write
  "stock-size"               guint                 : Read / Write

Description

A GtkCellRendererPixbuf can be used to render an image in a cell. It allows to render either a given GdkPixbuf (set via the pixbuf property) or a stock icon (set via the stock-id property).

To support the tree view, GtkCellRendererPixbuf also supports rendering two alternative pixbufs, when the is-expander property is TRUE. If the is-expanded property is TRUE and the pixbuf-expander-open property is set to a pixbuf, it renders that pixbuf, if the is-expanded property is FALSE and the pixbuf-expander-closed property is set to a pixbuf, it renders that one.

Details

GtkCellRendererPixbuf

typedef struct _GtkCellRendererPixbuf GtkCellRendererPixbuf;

gtk_cell_renderer_pixbuf_new ()

GtkCellRenderer*    gtk_cell_renderer_pixbuf_new        (void);

Creates a new GtkCellRendererPixbuf. Adjust rendering parameters using object properties. Object properties can be set globally (with g_object_set()). Also, with GtkTreeViewColumn, you can bind a property to a value in a GtkTreeModel. For example, you can bind the "pixbuf" property on the cell renderer to a pixbuf value in the model, thus rendering a different image in each row of the GtkTreeView.

Returns : the new cell renderer

Property Details

The "follow-state" property

  "follow-state"             gboolean              : Read / Write

Specifies whether the rendered pixbuf should be colorized according to the GtkCellRendererState.

Default value: FALSE

Since 2.8

The "icon-name" property

  "icon-name"                gchararray            : Read / Write

The name of the themed icon to display. This property only has an effect if not overridden by "stock_id" or "pixbuf" properties.

Default value: NULL

Since 2.8

The "pixbuf" property

  "pixbuf"                   GdkPixbuf             : Read / Write

The pixbuf to render.

The "pixbuf-expander-closed" property

  "pixbuf-expander-closed"   GdkPixbuf             : Read / Write

Pixbuf for closed expander.

The "pixbuf-expander-open" property

  "pixbuf-expander-open"     GdkPixbuf             : Read / Write

Pixbuf for open expander.

The "stock-detail" property

  "stock-detail"             gchararray            : Read / Write

Render detail to pass to the theme engine.

Default value: NULL

The "stock-id" property

  "stock-id"                 gchararray            : Read / Write

The stock ID of the stock icon to render.

Default value: NULL

The "stock-size" property

  "stock-size"               guint                 : Read / Write

The GtkIconSize value that specifies the size of the rendered icon.

Default value: 1


GtkCellRendererProgress

GtkCellRendererProgress — Renders numbers as progress bars

Synopsis

#include <gtk/gtk.h>

                    GtkCellRendererProgress;
GtkCellRenderer*    gtk_cell_renderer_progress_new      (void);

Object Hierarchy

  GObject
   +----GInitiallyUnowned
         +----GtkObject
               +----GtkCellRenderer
                     +----GtkCellRendererProgress

Properties

  "text"                     gchararray            : Read / Write
  "value"                    gint                  : Read / Write

Description

GtkCellRendererProgress renders a numeric value as a progress par in a cell. Additionally, it can display a text on top of the progress bar.

The GtkCellRendererProgress cell renderer was added in GTK+ 2.6.

Details

GtkCellRendererProgress

typedef struct _GtkCellRendererProgress GtkCellRendererProgress;

gtk_cell_renderer_progress_new ()

GtkCellRenderer*    gtk_cell_renderer_progress_new      (void);

Creates a new GtkCellRendererProgress.

Returns : the new cell renderer

Since 2.6

Property Details

The "text" property

  "text"                     gchararray            : Read / Write

The "text" property determines the label which will be drawn over the progress bar. Setting this property to NULL causes the default label to be displayed. Setting this property to an empty string causes no label to be displayed.

Default value: NULL

Since 2.6

The "value" property

  "value"                    gint                  : Read / Write

The "value" property determines the percentage to which the progress bar will be "filled in".

Allowed values: [0,100]

Default value: 0

Since 2.6


GtkCellRendererSpin

GtkCellRendererSpin — Renders a spin button in a cell

Synopsis

#include <gtk/gtk.h>

                    GtkCellRendererSpin;
GtkCellRenderer*    gtk_cell_renderer_spin_new          (void);

Object Hierarchy

  GObject
   +----GInitiallyUnowned
         +----GtkObject
               +----GtkCellRenderer
                     +----GtkCellRendererText
                           +----GtkCellRendererSpin

Properties

  "adjustment"               GtkAdjustment         : Read / Write
  "climb-rate"               gdouble               : Read / Write
  "digits"                   guint                 : Read / Write

Description

GtkCellRendererSpin renders text in a cell like GtkCellRendererText from which it is derived. But while GtkCellRendererText offers a simple entry to edit the text, GtkCellRendererSpin offers a GtkSpinButton widget. Of course, that means that the text has to be parseable as a floating point number.

The range of the spinbutton is taken from the adjustment property of the cell renderer, which can be set explicitly or mapped to a column in the tree model, like all properties of cell renders. GtkCellRendererSpin also has properties for the climb rate and the number of digits to display. Other GtkSpinButton properties can be set in a handler for the start-editing signal.

The GtkCellRendererSpin cell renderer was added in GTK+ 2.10.

Details

GtkCellRendererSpin

typedef struct _GtkCellRendererSpin GtkCellRendererSpin;

gtk_cell_renderer_spin_new ()

GtkCellRenderer*    gtk_cell_renderer_spin_new          (void);

Creates a new GtkCellRendererSpin.

Returns : a new GtkCellRendererSpin

Since 2.10

Property Details

The "adjustment" property

  "adjustment"               GtkAdjustment         : Read / Write

The adjustment that holds the value of the spinbutton. This must be non-NULL for the cell renderer to be editable.

Since 2.10

The "climb-rate" property

  "climb-rate"               gdouble               : Read / Write

The acceleration rate when you hold down a button.

Allowed values: >= 0

Default value: 0

Since 2.10

The "digits" property

  "digits"                   guint                 : Read / Write

The number of decimal places to display.

Allowed values: <= 20

Default value: 0

Since 2.10

See Also

GtkCellRendererText, GtkSpinButton


GtkCellRendererText

GtkCellRendererText — Renders text in a cell

Synopsis

#include <gtk/gtk.h>

                    GtkCellRendererText;
GtkCellRenderer*    gtk_cell_renderer_text_new          (void);
void                gtk_cell_renderer_text_set_fixed_height_from_font
                                                        (GtkCellRendererText *renderer,
                                                         gint number_of_rows);

Object Hierarchy

  GObject
   +----GInitiallyUnowned
         +----GtkObject
               +----GtkCellRenderer
                     +----GtkCellRendererText
                           +----GtkCellRendererAccel
                           +----GtkCellRendererCombo
                           +----GtkCellRendererSpin

Properties

  "alignment"                PangoAlignment        : Read / Write
  "attributes"               PangoAttrList         : Read / Write
  "background"               gchararray            : Write
  "background-gdk"           GdkColor              : Read / Write
  "background-set"           gboolean              : Read / Write
  "editable"                 gboolean              : Read / Write
  "editable-set"             gboolean              : Read / Write
  "ellipsize"                PangoEllipsizeMode    : Read / Write
  "ellipsize-set"            gboolean              : Read / Write
  "family"                   gchararray            : Read / Write
  "family-set"               gboolean              : Read / Write
  "font"                     gchararray            : Read / Write
  "font-desc"                PangoFontDescription  : Read / Write
  "foreground"               gchararray            : Write
  "foreground-gdk"           GdkColor              : Read / Write
  "foreground-set"           gboolean              : Read / Write
  "language"                 gchararray            : Read / Write
  "language-set"             gboolean              : Read / Write
  "markup"                   gchararray            : Write
  "rise"                     gint                  : Read / Write
  "rise-set"                 gboolean              : Read / Write
  "scale"                    gdouble               : Read / Write
  "scale-set"                gboolean              : Read / Write
  "single-paragraph-mode"    gboolean              : Read / Write
  "size"                     gint                  : Read / Write
  "size-points"              gdouble               : Read / Write
  "size-set"                 gboolean              : Read / Write
  "stretch"                  PangoStretch          : Read / Write
  "stretch-set"              gboolean              : Read / Write
  "strikethrough"            gboolean              : Read / Write
  "strikethrough-set"        gboolean              : Read / Write
  "style"                    PangoStyle            : Read / Write
  "style-set"                gboolean              : Read / Write
  "text"                     gchararray            : Read / Write
  "underline"                PangoUnderline        : Read / Write
  "underline-set"            gboolean              : Read / Write
  "variant"                  PangoVariant          : Read / Write
  "variant-set"              gboolean              : Read / Write
  "weight"                   gint                  : Read / Write
  "weight-set"               gboolean              : Read / Write
  "width-chars"              gint                  : Read / Write
  "wrap-mode"                PangoWrapMode         : Read / Write
  "wrap-width"               gint                  : Read / Write

Signals

  "edited"                                         : Run Last

Description

A GtkCellRendererText renders a given text in its cell, using the font, color and style information provided by its properties. The text will be ellipsized if it is too long and the ellipsize property allows it.

If the mode is GTK_CELL_RENDERER_MODE_EDITABLE, the GtkCellRendererText allows to edit its text using an entry.

Details

GtkCellRendererText

typedef struct _GtkCellRendererText GtkCellRendererText;

gtk_cell_renderer_text_new ()

GtkCellRenderer*    gtk_cell_renderer_text_new          (void);

Creates a new GtkCellRendererText. Adjust how text is drawn using object properties. Object properties can be set globally (with g_object_set()). Also, with GtkTreeViewColumn, you can bind a property to a value in a GtkTreeModel. For example, you can bind the "text" property on the cell renderer to a string value in the model, thus rendering a different string in each row of the GtkTreeView

Returns : the new cell renderer

gtk_cell_renderer_text_set_fixed_height_from_font ()

void                gtk_cell_renderer_text_set_fixed_height_from_font
                                                        (GtkCellRendererText *renderer,
                                                         gint number_of_rows);

Sets the height of a renderer to explicitly be determined by the "font" and "y_pad" property set on it. Further changes in these properties do not affect the height, so they must be accompanied by a subsequent call to this function. Using this function is unflexible, and should really only be used if calculating the size of a cell is too slow (ie, a massive number of cells displayed). If number_of_rows is -1, then the fixed height is unset, and the height is determined by the properties again.

renderer : | A GtkCellRendererText
number_of_rows : | Number of rows of text each cell renderer is allocated, or -1

Property Details

The "alignment" property

  "alignment"                PangoAlignment        : Read / Write

Specifies how to align the lines of text with respect to each other.

Note that this property describes how to align the lines of text in case there are several of them. The "xalign" property of GtkCellRenderer, on the other hand, sets the horizontal alignment of the whole text.

Default value: PANGO_ALIGN_LEFT

Since 2.10

The "attributes" property

  "attributes"               PangoAttrList         : Read / Write

A list of style attributes to apply to the text of the renderer.

The "background" property

  "background"               gchararray            : Write

Background color as a string.

Default value: NULL

The "background-gdk" property

  "background-gdk"           GdkColor              : Read / Write

Background color as a GdkColor.

The "background-set" property

  "background-set"           gboolean              : Read / Write

Whether this tag affects the background color.

Default value: FALSE

The "editable" property

  "editable"                 gboolean              : Read / Write

Whether the text can be modified by the user.

Default value: FALSE

The "editable-set" property

  "editable-set"             gboolean              : Read / Write

Whether this tag affects text editability.

Default value: FALSE

The "ellipsize" property

  "ellipsize"                PangoEllipsizeMode    : Read / Write

Specifies the preferred place to ellipsize the string, if the cell renderer does not have enough room to display the entire string. Setting it to PANGO_ELLIPSIZE_NONE turns off ellipsizing. See the wrap-width property for another way of making the text fit into a given width.

Default value: PANGO_ELLIPSIZE_NONE

Since 2.6

The "ellipsize-set" property

  "ellipsize-set"            gboolean              : Read / Write

Whether this tag affects the ellipsize mode.

Default value: FALSE

The "family" property

  "family"                   gchararray            : Read / Write

Name of the font family, e.g. Sans, Helvetica, Times, Monospace.

Default value: NULL

The "family-set" property

  "family-set"               gboolean              : Read / Write

Whether this tag affects the font family.

Default value: FALSE

The "font" property

  "font"                     gchararray            : Read / Write

Font description as a string, e.g. "Sans Italic 12".

Default value: NULL

The "font-desc" property

  "font-desc"                PangoFontDescription  : Read / Write

Font description as a PangoFontDescription struct.

The "foreground" property

  "foreground"               gchararray            : Write

Foreground color as a string.

Default value: NULL

The "foreground-gdk" property

  "foreground-gdk"           GdkColor              : Read / Write

Foreground color as a GdkColor.

The "foreground-set" property

  "foreground-set"           gboolean              : Read / Write

Whether this tag affects the foreground color.

Default value: FALSE

The "language" property

  "language"                 gchararray            : Read / Write

The language this text is in, as an ISO code. Pango can use this as a hint when rendering the text. If you don't understand this parameter, you probably don't need it.

Default value: NULL

The "language-set" property

  "language-set"             gboolean              : Read / Write

Whether this tag affects the language the text is rendered as.

Default value: FALSE

The "markup" property

  "markup"                   gchararray            : Write

Marked up text to render.

Default value: NULL

The "rise" property

  "rise"                     gint                  : Read / Write

Offset of text above the baseline (below the baseline if rise is negative).

Allowed values: >= -2147483647

Default value: 0

The "rise-set" property

  "rise-set"                 gboolean              : Read / Write

Whether this tag affects the rise.

Default value: FALSE

The "scale" property

  "scale"                    gdouble               : Read / Write

Font scaling factor.

Allowed values: >= 0

Default value: 1

The "scale-set" property

  "scale-set"                gboolean              : Read / Write

Whether this tag scales the font size by a factor.

Default value: FALSE

The "single-paragraph-mode" property

  "single-paragraph-mode"    gboolean              : Read / Write

Whether or not to keep all text in a single paragraph.

Default value: FALSE

The "size" property

  "size"                     gint                  : Read / Write

Font size.

Allowed values: >= 0

Default value: 0

The "size-points" property

  "size-points"              gdouble               : Read / Write

Font size in points.

Allowed values: >= 0

Default value: 0

The "size-set" property

  "size-set"                 gboolean              : Read / Write

Whether this tag affects the font size.

Default value: FALSE

The "stretch" property

  "stretch"                  PangoStretch          : Read / Write

Font stretch.

Default value: PANGO_STRETCH_NORMAL

The "stretch-set" property

  "stretch-set"              gboolean              : Read / Write

Whether this tag affects the font stretch.

Default value: FALSE

The "strikethrough" property

  "strikethrough"            gboolean              : Read / Write

Whether to strike through the text.

Default value: FALSE

The "strikethrough-set" property

  "strikethrough-set"        gboolean              : Read / Write

Whether this tag affects strikethrough.

Default value: FALSE

The "style" property

  "style"                    PangoStyle            : Read / Write

Font style.

Default value: PANGO_STYLE_NORMAL

The "style-set" property

  "style-set"                gboolean              : Read / Write

Whether this tag affects the font style.

Default value: FALSE

The "text" property

  "text"                     gchararray            : Read / Write

Text to render.

Default value: NULL

The "underline" property

  "underline"                PangoUnderline        : Read / Write

Style of underline for this text.

Default value: PANGO_UNDERLINE_NONE

The "underline-set" property

  "underline-set"            gboolean              : Read / Write

Whether this tag affects underlining.

Default value: FALSE

The "variant" property

  "variant"                  PangoVariant          : Read / Write

Font variant.

Default value: PANGO_VARIANT_NORMAL

The "variant-set" property

  "variant-set"              gboolean              : Read / Write

Whether this tag affects the font variant.

Default value: FALSE

The "weight" property

  "weight"                   gint                  : Read / Write

Font weight.

Allowed values: >= 0

Default value: 400

The "weight-set" property

  "weight-set"               gboolean              : Read / Write

Whether this tag affects the font weight.

Default value: FALSE

The "width-chars" property

  "width-chars"              gint                  : Read / Write

The desired width of the cell, in characters. If this property is set to -1, the width will be calculated automatically, otherwise the cell will request either 3 characters or the property value, whichever is greater.

Allowed values: >= -1

Default value: -1

Since 2.6

The "wrap-mode" property

  "wrap-mode"                PangoWrapMode         : Read / Write

Specifies how to break the string into multiple lines, if the cell renderer does not have enough room to display the entire string. This property has no effect unless the wrap-width property is set.

Default value: PANGO_WRAP_CHAR

Since 2.8

The "wrap-width" property

  "wrap-width"               gint                  : Read / Write

Specifies the width at which the text is wrapped. The wrap-mode property can be used to influence at what character positions the line breaks can be placed. Setting wrap-width to -1 turns wrapping off.

Allowed values: >= -1

Default value: -1

Since 2.8

Signal Details

The "edited" signal

void                user_function                      (GtkCellRendererText *renderer,
                                                        gchar               *path,
                                                        gchar               *new_text,
                                                        gpointer             user_data)      : Run Last

This signal is emitted after renderer has been edited.

renderer : | the object which received the signal.
path : | the path identifying the edited cell.
new_text : | the new text.
user_data : | user data set when the signal handler was connected.


GtkCellRendererToggle

GtkCellRendererToggle — Renders a toggle button in a cell

Synopsis

#include <gtk/gtk.h>

                    GtkCellRendererToggle;
GtkCellRenderer*    gtk_cell_renderer_toggle_new        (void);
gboolean            gtk_cell_renderer_toggle_get_radio  (GtkCellRendererToggle *toggle);
void                gtk_cell_renderer_toggle_set_radio  (GtkCellRendererToggle *toggle,
                                                         gboolean radio);
gboolean            gtk_cell_renderer_toggle_get_active (GtkCellRendererToggle *toggle);
void                gtk_cell_renderer_toggle_set_active (GtkCellRendererToggle *toggle,
                                                         gboolean setting);

Object Hierarchy

  GObject
   +----GInitiallyUnowned
         +----GtkObject
               +----GtkCellRenderer
                     +----GtkCellRendererToggle

Properties

  "activatable"              gboolean              : Read / Write
  "active"                   gboolean              : Read / Write
  "inconsistent"             gboolean              : Read / Write
  "indicator-size"           gint                  : Read / Write
  "radio"                    gboolean              : Read / Write

Signals

  "toggled"                                        : Run Last

Description

GtkCellRendererToggle renders a toggle button in a cell. The button is drawn as a radio- or checkbutton, depending on the radio property. When activated, it emits the toggled signal.

Details

GtkCellRendererToggle

typedef struct _GtkCellRendererToggle GtkCellRendererToggle;

gtk_cell_renderer_toggle_new ()

GtkCellRenderer*    gtk_cell_renderer_toggle_new        (void);

Creates a new GtkCellRendererToggle. Adjust rendering parameters using object properties. Object properties can be set globally (with g_object_set()). Also, with GtkTreeViewColumn, you can bind a property to a value in a GtkTreeModel. For example, you can bind the "active" property on the cell renderer to a boolean value in the model, thus causing the check button to reflect the state of the model.

Returns : the new cell renderer

gtk_cell_renderer_toggle_get_radio ()

gboolean            gtk_cell_renderer_toggle_get_radio  (GtkCellRendererToggle *toggle);

Returns whether we're rendering radio toggles rather than checkboxes.

toggle : | a GtkCellRendererToggle
Returns : | TRUE if we're rendering radio toggles rather than checkboxes

gtk_cell_renderer_toggle_set_radio ()

void                gtk_cell_renderer_toggle_set_radio  (GtkCellRendererToggle *toggle,
                                                         gboolean radio);

If radio is TRUE, the cell renderer renders a radio toggle (i.e. a toggle in a group of mutually-exclusive toggles). If FALSE, it renders a check toggle (a standalone boolean option). This can be set globally for the cell renderer, or changed just before rendering each cell in the model (for GtkTreeView, you set up a per-row setting using GtkTreeViewColumn to associate model columns with cell renderer properties).

toggle : | a GtkCellRendererToggle
radio : | TRUE to make the toggle look like a radio button

gtk_cell_renderer_toggle_get_active ()

gboolean            gtk_cell_renderer_toggle_get_active (GtkCellRendererToggle *toggle);

Returns whether the cell renderer is active. See gtk_cell_renderer_toggle_set_active().

toggle : | a GtkCellRendererToggle
Returns : | TRUE if the cell renderer is active.

gtk_cell_renderer_toggle_set_active ()

void                gtk_cell_renderer_toggle_set_active (GtkCellRendererToggle *toggle,
                                                         gboolean setting);

Activates or deactivates a cell renderer.

toggle : | a GtkCellRendererToggle.
setting : | the value to set.

Property Details

The "activatable" property

  "activatable"              gboolean              : Read / Write

The toggle button can be activated.

Default value: TRUE

The "active" property

  "active"                   gboolean              : Read / Write

The toggle state of the button.

Default value: FALSE

The "inconsistent" property

  "inconsistent"             gboolean              : Read / Write

The inconsistent state of the button.

Default value: FALSE

The "indicator-size" property

  "indicator-size"           gint                  : Read / Write

Size of check or radio indicator.

Allowed values: >= 0

Default value: 12

The "radio" property

  "radio"                    gboolean              : Read / Write

Draw the toggle button as a radio button.

Default value: FALSE

Signal Details

The "toggled" signal

void                user_function                      (GtkCellRendererToggle *cell_renderer,
                                                        gchar                 *path,
                                                        gpointer               user_data)          : Run Last

The ::toggled signal is emitted when the cell is toggled.

cell_renderer : | the object which received the signal
path : | string representation of GtkTreePath describing the event location
user_data : | user data set when the signal handler was connected.


GtkCellView

GtkCellView — A widget displaying a single row of a GtkTreeModel

Synopsis

#include <gtk/gtk.h>

                    GtkCellView;
GtkWidget*          gtk_cell_view_new                   (void);
GtkWidget*          gtk_cell_view_new_with_text         (const gchar *text);
GtkWidget*          gtk_cell_view_new_with_markup       (const gchar *markup);
GtkWidget*          gtk_cell_view_new_with_pixbuf       (GdkPixbuf *pixbuf);
void                gtk_cell_view_set_model             (GtkCellView *cell_view,
                                                         GtkTreeModel *model);
void                gtk_cell_view_set_displayed_row     (GtkCellView *cell_view,
                                                         GtkTreePath *path);
GtkTreePath*        gtk_cell_view_get_displayed_row     (GtkCellView *cell_view);
gboolean            gtk_cell_view_get_size_of_row       (GtkCellView *cell_view,
                                                         GtkTreePath *path,
                                                         GtkRequisition *requisition);
void                gtk_cell_view_set_background_color  (GtkCellView *cell_view,
                                                         const GdkColor *color);
GList*              gtk_cell_view_get_cell_renderers    (GtkCellView *cell_view);

Object Hierarchy

  GObject
   +----GInitiallyUnowned
         +----GtkObject
               +----GtkWidget
                     +----GtkCellView

Implemented Interfaces

GtkCellView implements AtkImplementorIface and GtkCellLayout.

Properties

  "background"               gchararray            : Write
  "background-gdk"           GdkColor              : Read / Write
  "background-set"           gboolean              : Read / Write
  "model"                    GtkTreeModel          : Read / Write

Description

A GtkCellView displays a single row of a GtkTreeModel, using cell renderers just like GtkTreeView. GtkCellView doesn't support some of the more complex features of GtkTreeView, like cell editing and drag and drop.

Details

GtkCellView

typedef struct _GtkCellView GtkCellView;

gtk_cell_view_new ()

GtkWidget*          gtk_cell_view_new                   (void);

Creates a new GtkCellView widget.

Returns : A newly created GtkCellView widget.

Since 2.6

gtk_cell_view_new_with_text ()

GtkWidget*          gtk_cell_view_new_with_text         (const gchar *text);

Creates a new GtkCellView widget, adds a GtkCellRendererText to it, and makes its show text.

text : | the text to display in the cell view
Returns : | A newly created GtkCellView widget.

Since 2.6

gtk_cell_view_new_with_markup ()

GtkWidget*          gtk_cell_view_new_with_markup       (const gchar *markup);

Creates a new GtkCellView widget, adds a GtkCellRendererText to it, and makes its show markup. The text can text can be marked up with the Pango text markup language.

markup : | the text to display in the cell view
Returns : | A newly created GtkCellView widget.

Since 2.6

gtk_cell_view_new_with_pixbuf ()

GtkWidget*          gtk_cell_view_new_with_pixbuf       (GdkPixbuf *pixbuf);

Creates a new GtkCellView widget, adds a GtkCellRendererPixbuf to it, and makes its show pixbuf.

pixbuf : | the image to display in the cell view
Returns : | A newly created GtkCellView widget.

Since 2.6

gtk_cell_view_set_model ()

void                gtk_cell_view_set_model             (GtkCellView *cell_view,
                                                         GtkTreeModel *model);

Sets the model for cell_view. If cell_view already has a model set, it will remove it before setting the new model. If model is NULL, then it will unset the old model.

cell_view : | a GtkCellView
model : | a GtkTreeModel

Since 2.6

gtk_cell_view_set_displayed_row ()

void                gtk_cell_view_set_displayed_row     (GtkCellView *cell_view,
                                                         GtkTreePath *path);

Sets the row of the model that is currently displayed by the GtkCellView. If the path is unset, then the contents of the cellview "stick" at their last value; this is not normally a desired result, but may be a needed intermediate state if say, the model for the GtkCellView becomes temporarily empty.

cell_view : | a GtkCellView
path : | a GtkTreePath or NULL to unset.

Since 2.6

gtk_cell_view_get_displayed_row ()

GtkTreePath*        gtk_cell_view_get_displayed_row     (GtkCellView *cell_view);

Returns a GtkTreePath referring to the currently displayed row. If no row is currently displayed, NULL is returned.

cell_view : | a GtkCellView
Returns : | the currently displayed row or NULL

Since 2.6

gtk_cell_view_get_size_of_row ()

gboolean            gtk_cell_view_get_size_of_row       (GtkCellView *cell_view,
                                                         GtkTreePath *path,
                                                         GtkRequisition *requisition);

Sets requisition to the size needed by cell_view to display the model row pointed to by path.

cell_view : | a GtkCellView
path : | a GtkTreePath
requisition : | return location for the size
Returns : | TRUE

Since 2.6

gtk_cell_view_set_background_color ()

void                gtk_cell_view_set_background_color  (GtkCellView *cell_view,
                                                         const GdkColor *color);

Sets the background color of view.

cell_view : | a GtkCellView
color : | the new background color

Since 2.6

gtk_cell_view_get_cell_renderers ()

GList*              gtk_cell_view_get_cell_renderers    (GtkCellView *cell_view);

Returns the cell renderers which have been added to cell_view.

cell_view : | a GtkCellView
Returns : | a list of cell renderers. The list, but not the renderers has been newly allocated and should be freed with g_list_free() when no longer needed.

Since 2.6

Property Details

The "background" property

  "background"               gchararray            : Write

Background color as a string.

Default value: NULL

The "background-gdk" property

  "background-gdk"           GdkColor              : Read / Write

Background color as a GdkColor.

The "background-set" property

  "background-set"           gboolean              : Read / Write

Whether this tag affects the background color.

Default value: FALSE

The "model" property

  "model"                    GtkTreeModel          : Read / Write

The model for cell view

since 2.10


GtkCheckButton

GtkCheckButton — Create widgets with a discrete toggle button

Synopsis

#include <gtk/gtk.h>

                    GtkCheckButton;
GtkWidget*          gtk_check_button_new                (void);
GtkWidget*          gtk_check_button_new_with_label     (const gchar *label);
GtkWidget*          gtk_check_button_new_with_mnemonic  (const gchar *label);

Object Hierarchy

  GObject
   +----GInitiallyUnowned
         +----GtkObject
               +----GtkWidget
                     +----GtkContainer
                           +----GtkBin
                                 +----GtkButton
                                       +----GtkToggleButton
                                             +----GtkCheckButton
                                                   +----GtkRadioButton

Implemented Interfaces

GtkCheckButton implements AtkImplementorIface.

Style Properties

  "indicator-size"           gint                  : Read
  "indicator-spacing"        gint                  : Read

Description

A GtkCheckButton places a discrete GtkToggleButton next to a widget, (usually a GtkLabel). See the section on GtkToggleButton widgets for more information about toggle/check buttons.

The important signal ('toggled') is also inherited from GtkToggleButton.

Details

GtkCheckButton

typedef struct _GtkCheckButton GtkCheckButton;

toggle_button is a GtkToggleButton representing the actual toggle button that composes the check button.

gtk_check_button_new ()

GtkWidget*          gtk_check_button_new                (void);

Creates a new GtkCheckButton.

Returns : a GtkWidget.

gtk_check_button_new_with_label ()

GtkWidget*          gtk_check_button_new_with_label     (const gchar *label);

Creates a new GtkCheckButton with a GtkLabel to the right of it.

label : | the text for the check button.
Returns : | a GtkWidget.

gtk_check_button_new_with_mnemonic ()

GtkWidget*          gtk_check_button_new_with_mnemonic  (const gchar *label);

Creates a new GtkCheckButton containing a label. The label will be created using gtk_label_new_with_mnemonic(), so underscores in label indicate the mnemonic for the check button.

label : | The text of the button, with an underscore in front of the mnemonic character
Returns : | a new GtkCheckButton

Style Property Details

The "indicator-size" style property

  "indicator-size"           gint                  : Read

Size of check or radio indicator.

Allowed values: >= 0

Default value: 13

The "indicator-spacing" style property

  "indicator-spacing"        gint                  : Read

Spacing around check or radio indicator.

Allowed values: >= 0

Default value: 2

See Also

GtkCheckMenuItem | add check buttons to your menus.
GtkButton | a more general button.
GtkToggleButton | GtkCheckButton's parent.
GtkRadioButton | group check buttons together.


GtkCheckMenuItem

GtkCheckMenuItem — A menu item with a check box

Synopsis

#include <gtk/gtk.h>

                    GtkCheckMenuItem;
GtkWidget*          gtk_check_menu_item_new             (void);
GtkWidget*          gtk_check_menu_item_new_with_label  (const gchar *label);
GtkWidget*          gtk_check_menu_item_new_with_mnemonic
                                                        (const gchar *label);
#define             gtk_check_menu_item_set_state
gboolean            gtk_check_menu_item_get_active      (GtkCheckMenuItem *check_menu_item);
void                gtk_check_menu_item_set_active      (GtkCheckMenuItem *check_menu_item,
                                                         gboolean is_active);
void                gtk_check_menu_item_set_show_toggle (GtkCheckMenuItem *menu_item,
                                                         gboolean always);
void                gtk_check_menu_item_toggled         (GtkCheckMenuItem *check_menu_item);
gboolean            gtk_check_menu_item_get_inconsistent
                                                        (GtkCheckMenuItem *check_menu_item);
void                gtk_check_menu_item_set_inconsistent
                                                        (GtkCheckMenuItem *check_menu_item,
                                                         gboolean setting);
void                gtk_check_menu_item_set_draw_as_radio
                                                        (GtkCheckMenuItem *check_menu_item,
                                                         gboolean draw_as_radio);
gboolean            gtk_check_menu_item_get_draw_as_radio
                                                        (GtkCheckMenuItem *check_menu_item);

Object Hierarchy

  GObject
   +----GInitiallyUnowned
         +----GtkObject
               +----GtkWidget
                     +----GtkContainer
                           +----GtkBin
                                 +----GtkItem
                                       +----GtkMenuItem
                                             +----GtkCheckMenuItem
                                                   +----GtkRadioMenuItem

Implemented Interfaces

GtkCheckMenuItem implements AtkImplementorIface.

Properties

  "active"                   gboolean              : Read / Write
  "draw-as-radio"            gboolean              : Read / Write
  "inconsistent"             gboolean              : Read / Write

Style Properties

  "indicator-size"           gint                  : Read

Signals

  "toggled"                                        : Run First

Description

A GtkCheckMenuItem is a menu item that maintains the state of a boolean value in addition to a GtkMenuItem's usual role in activating application code.

A check box indicating the state of the boolean value is displayed at the left side of the GtkMenuItem. Activating the GtkMenuItem toggles the value.

Details

GtkCheckMenuItem

typedef struct _GtkCheckMenuItem GtkCheckMenuItem;

The GtkCheckMenuItem struct contains the following fields. (These fields should be considered read-only. They should never be set by an application.)

guint active; TRUE if the check box is active.

gtk_check_menu_item_new ()

GtkWidget*          gtk_check_menu_item_new             (void);

Creates a new GtkCheckMenuItem.

Returns : a new GtkCheckMenuItem.

gtk_check_menu_item_new_with_label ()

GtkWidget*          gtk_check_menu_item_new_with_label  (const gchar *label);

Creates a new GtkCheckMenuItem with a label.

label : | the string to use for the label.
Returns : | a new GtkCheckMenuItem.

gtk_check_menu_item_new_with_mnemonic ()

GtkWidget*          gtk_check_menu_item_new_with_mnemonic
                                                        (const gchar *label);

Creates a new GtkCheckMenuItem containing a label. The label will be created using gtk_label_new_with_mnemonic(), so underscores in label indicate the mnemonic for the menu item.

label : | The text of the button, with an underscore in front of the mnemonic character
Returns : | a new GtkCheckMenuItem

gtk_check_menu_item_set_state

#define	gtk_check_menu_item_set_state		gtk_check_menu_item_set_active

Warning

gtk_check_menu_item_set_state is deprecated and should not be used in newly-written code.

This macro is provided to preserve compatibility with older code. New code should use gtk_check_menu_item_set_active() function instead.

gtk_check_menu_item_get_active ()

gboolean            gtk_check_menu_item_get_active      (GtkCheckMenuItem *check_menu_item);

Returns whether the check menu item is active. See gtk_check_menu_item_set_active().

check_menu_item : | a GtkCheckMenuItem
Returns : | TRUE if the menu item is checked.

gtk_check_menu_item_set_active ()

void                gtk_check_menu_item_set_active      (GtkCheckMenuItem *check_menu_item,
                                                         gboolean is_active);

Sets the active state of the menu item's check box.

check_menu_item : | a GtkCheckMenuItem.
is_active : | boolean value indicating whether the check box is active.

gtk_check_menu_item_set_show_toggle ()

void                gtk_check_menu_item_set_show_toggle (GtkCheckMenuItem *menu_item,
                                                         gboolean always);

Warning

gtk_check_menu_item_set_show_toggle is deprecated and should not be used in newly-written code.

Controls whether the check box is shown at all times. Normally the check box is shown only when it is active or while the menu item is selected.

menu_item : | a GtkCheckMenuItem.
always : | boolean value indicating whether to always show the check box.

gtk_check_menu_item_toggled ()

void                gtk_check_menu_item_toggled         (GtkCheckMenuItem *check_menu_item);

Emits the GtkCheckMenuItem::toggled signal.

check_menu_item : a GtkCheckMenuItem.

gtk_check_menu_item_get_inconsistent ()

gboolean            gtk_check_menu_item_get_inconsistent
                                                        (GtkCheckMenuItem *check_menu_item);

Retrieves the value set by gtk_check_menu_item_set_inconsistent().

check_menu_item : | a GtkCheckMenuItem
Returns : | TRUE if inconsistent

gtk_check_menu_item_set_inconsistent ()

void                gtk_check_menu_item_set_inconsistent
                                                        (GtkCheckMenuItem *check_menu_item,
                                                         gboolean setting);

If the user has selected a range of elements (such as some text or spreadsheet cells) that are affected by a boolean setting, and the current values in that range are inconsistent, you may want to display the check in an "in between" state. This function turns on "in between" display. Normally you would turn off the inconsistent state again if the user explicitly selects a setting. This has to be done manually, gtk_check_menu_item_set_inconsistent() only affects visual appearance, it doesn't affect the semantics of the widget.

check_menu_item : | a GtkCheckMenuItem
setting : | TRUE to display an "inconsistent" third state check

gtk_check_menu_item_set_draw_as_radio ()

void                gtk_check_menu_item_set_draw_as_radio
                                                        (GtkCheckMenuItem *check_menu_item,
                                                         gboolean draw_as_radio);

Sets whether check_menu_item is drawn like a GtkRadioMenuItem

check_menu_item : | a GtkCheckMenuItem
draw_as_radio : | whether check_menu_item is drawn like a GtkRadioMenuItem

Since 2.4

gtk_check_menu_item_get_draw_as_radio ()

gboolean            gtk_check_menu_item_get_draw_as_radio
                                                        (GtkCheckMenuItem *check_menu_item);

Returns whether check_menu_item looks like a GtkRadioMenuItem

check_menu_item : | a GtkCheckMenuItem
Returns : | Whether check_menu_item looks like a GtkRadioMenuItem

Since 2.4

Property Details

The "active" property

  "active"                   gboolean              : Read / Write

Whether the menu item is checked.

Default value: FALSE

The "draw-as-radio" property

  "draw-as-radio"            gboolean              : Read / Write

Whether the menu item looks like a radio menu item.

Default value: FALSE

The "inconsistent" property

  "inconsistent"             gboolean              : Read / Write

Whether to display an "inconsistent" state.

Default value: FALSE

Style Property Details

The "indicator-size" style property

  "indicator-size"           gint                  : Read

Size of check or radio indicator.

Allowed values: >= 0

Default value: 12

Signal Details

The "toggled" signal

void                user_function                      (GtkCheckMenuItem *checkmenuitem,
                                                        gpointer          user_data)          : Run First

This signal is emitted when the state of the check box is changed.

A signal handler can examine the active field of the GtkCheckMenuItem struct to discover the new state.

checkmenuitem : | the object which received the signal.
user_data : | user data set when the signal handler was connected.


GtkCList

GtkCList — A multi-columned scrolling list widget

Synopsis

#include <gtk/gtk.h>

                    GtkCList;
enum                GtkCellType;
enum                GtkButtonAction;
#define             GTK_CLIST_FLAGS                     (clist)
#define             GTK_CLIST_SET_FLAG                  (clist,flag)
#define             GTK_CLIST_UNSET_FLAG                (clist,flag)
#define             GTK_CLIST_IN_DRAG                   (clist)
#define             GTK_CLIST_ROW_HEIGHT_SET            (clist)
#define             GTK_CLIST_SHOW_TITLES               (clist)
#define             GTK_CLIST_ADD_MODE                  (clist)
#define             GTK_CLIST_AUTO_SORT                 (clist)
#define             GTK_CLIST_AUTO_RESIZE_BLOCKED       (clist)
#define             GTK_CLIST_REORDERABLE               (clist)
#define             GTK_CLIST_USE_DRAG_ICONS            (clist)
#define             GTK_CLIST_DRAW_DRAG_LINE            (clist)
#define             GTK_CLIST_DRAW_DRAG_RECT            (clist)
#define             GTK_CLIST_ROW                       (_glist_)
#define             GTK_CELL_TEXT                       (cell)
#define             GTK_CELL_PIXMAP                     (cell)
#define             GTK_CELL_PIXTEXT                    (cell)
#define             GTK_CELL_WIDGET                     (cell)
gint                (*GtkCListCompareFunc)              (GtkCList *clist,
                                                         gconstpointer ptr1,
                                                         gconstpointer ptr2);
                    GtkCListColumn;
                    GtkCListRow;
                    GtkCellText;
                    GtkCellPixmap;
                    GtkCellPixText;
                    GtkCellWidget;
                    GtkCell;
                    GtkCListCellInfo;
                    GtkCListDestInfo;
enum                GtkCListDragPos;
GtkWidget*          gtk_clist_new                       (gint columns);
GtkWidget*          gtk_clist_new_with_titles           (gint columns,
                                                         gchar *titles[]);
void                gtk_clist_set_shadow_type           (GtkCList *clist,
                                                         GtkShadowType type);
void                gtk_clist_set_selection_mode        (GtkCList *clist,
                                                         GtkSelectionMode mode);
void                gtk_clist_freeze                    (GtkCList *clist);
void                gtk_clist_thaw                      (GtkCList *clist);
void                gtk_clist_column_titles_show        (GtkCList *clist);
void                gtk_clist_column_titles_hide        (GtkCList *clist);
void                gtk_clist_column_title_active       (GtkCList *clist,
                                                         gint column);
void                gtk_clist_column_title_passive      (GtkCList *clist,
                                                         gint column);
void                gtk_clist_column_titles_active      (GtkCList *clist);
void                gtk_clist_column_titles_passive     (GtkCList *clist);
void                gtk_clist_set_column_title          (GtkCList *clist,
                                                         gint column,
                                                         const gchar *title);
void                gtk_clist_set_column_widget         (GtkCList *clist,
                                                         gint column,
                                                         GtkWidget *widget);
void                gtk_clist_set_column_justification  (GtkCList *clist,
                                                         gint column,
                                                         GtkJustification justification);
void                gtk_clist_set_column_visibility     (GtkCList *clist,
                                                         gint column,
                                                         gboolean visible);
void                gtk_clist_set_column_resizeable     (GtkCList *clist,
                                                         gint column,
                                                         gboolean resizeable);
void                gtk_clist_set_column_auto_resize    (GtkCList *clist,
                                                         gint column,
                                                         gboolean auto_resize);
gint                gtk_clist_optimal_column_width      (GtkCList *clist,
                                                         gint column);
void                gtk_clist_set_column_width          (GtkCList *clist,
                                                         gint column,
                                                         gint width);
void                gtk_clist_set_column_min_width      (GtkCList *clist,
                                                         gint column,
                                                         gint min_width);
void                gtk_clist_set_column_max_width      (GtkCList *clist,
                                                         gint column,
                                                         gint max_width);
void                gtk_clist_set_row_height            (GtkCList *clist,
                                                         guint height);
void                gtk_clist_moveto                    (GtkCList *clist,
                                                         gint row,
                                                         gint column,
                                                         gfloat row_align,
                                                         gfloat col_align);
GtkVisibility       gtk_clist_row_is_visible            (GtkCList *clist,
                                                         gint row);
GtkCellType         gtk_clist_get_cell_type             (GtkCList *clist,
                                                         gint row,
                                                         gint column);
void                gtk_clist_set_text                  (GtkCList *clist,
                                                         gint row,
                                                         gint column,
                                                         const gchar *text);
gint                gtk_clist_get_text                  (GtkCList *clist,
                                                         gint row,
                                                         gint column,
                                                         gchar **text);
void                gtk_clist_set_pixmap                (GtkCList *clist,
                                                         gint row,
                                                         gint column,
                                                         GdkPixmap *pixmap,
                                                         GdkBitmap *mask);
gint                gtk_clist_get_pixmap                (GtkCList *clist,
                                                         gint row,
                                                         gint column,
                                                         GdkPixmap **pixmap,
                                                         GdkBitmap **mask);
void                gtk_clist_set_pixtext               (GtkCList *clist,
                                                         gint row,
                                                         gint column,
                                                         const gchar *text,
                                                         guint8 spacing,
                                                         GdkPixmap *pixmap,
                                                         GdkBitmap *mask);
gint                gtk_clist_get_pixtext               (GtkCList *clist,
                                                         gint row,
                                                         gint column,
                                                         gchar **text,
                                                         guint8 *spacing,
                                                         GdkPixmap **pixmap,
                                                         GdkBitmap **mask);
void                gtk_clist_set_foreground            (GtkCList *clist,
                                                         gint row,
                                                         const GdkColor *color);
void                gtk_clist_set_background            (GtkCList *clist,
                                                         gint row,
                                                         const GdkColor *color);
void                gtk_clist_set_cell_style            (GtkCList *clist,
                                                         gint row,
                                                         gint column,
                                                         GtkStyle *style);
GtkStyle*           gtk_clist_get_cell_style            (GtkCList *clist,
                                                         gint row,
                                                         gint column);
void                gtk_clist_set_row_style             (GtkCList *clist,
                                                         gint row,
                                                         GtkStyle *style);
GtkStyle*           gtk_clist_get_row_style             (GtkCList *clist,
                                                         gint row);
void                gtk_clist_set_shift                 (GtkCList *clist,
                                                         gint row,
                                                         gint column,
                                                         gint vertical,
                                                         gint horizontal);
void                gtk_clist_set_selectable            (GtkCList *clist,
                                                         gint row,
                                                         gboolean selectable);
gboolean            gtk_clist_get_selectable            (GtkCList *clist,
                                                         gint row);
gint                gtk_clist_prepend                   (GtkCList *clist,
                                                         gchar *text[]);
gint                gtk_clist_append                    (GtkCList *clist,
                                                         gchar *text[]);
gint                gtk_clist_insert                    (GtkCList *clist,
                                                         gint row,
                                                         gchar *text[]);
void                gtk_clist_remove                    (GtkCList *clist,
                                                         gint row);
void                gtk_clist_set_row_data              (GtkCList *clist,
                                                         gint row,
                                                         gpointer data);
void                gtk_clist_set_row_data_full         (GtkCList *clist,
                                                         gint row,
                                                         gpointer data,
                                                         GtkDestroyNotify destroy);
gpointer            gtk_clist_get_row_data              (GtkCList *clist,
                                                         gint row);
gint                gtk_clist_find_row_from_data        (GtkCList *clist,
                                                         gpointer data);
void                gtk_clist_select_row                (GtkCList *clist,
                                                         gint row,
                                                         gint column);
void                gtk_clist_unselect_row              (GtkCList *clist,
                                                         gint row,
                                                         gint column);
void                gtk_clist_undo_selection            (GtkCList *clist);
void                gtk_clist_clear                     (GtkCList *clist);
gint                gtk_clist_get_selection_info        (GtkCList *clist,
                                                         gint x,
                                                         gint y,
                                                         gint *row,
                                                         gint *column);
void                gtk_clist_select_all                (GtkCList *clist);
void                gtk_clist_unselect_all              (GtkCList *clist);
void                gtk_clist_swap_rows                 (GtkCList *clist,
                                                         gint row1,
                                                         gint row2);
void                gtk_clist_set_compare_func          (GtkCList *clist,
                                                         GtkCListCompareFunc cmp_func);
void                gtk_clist_set_sort_column           (GtkCList *clist,
                                                         gint column);
void                gtk_clist_set_sort_type             (GtkCList *clist,
                                                         GtkSortType sort_type);
void                gtk_clist_sort                      (GtkCList *clist);
void                gtk_clist_set_auto_sort             (GtkCList *clist,
                                                         gboolean auto_sort);
gint                gtk_clist_columns_autosize          (GtkCList *clist);
gchar*              gtk_clist_get_column_title          (GtkCList *clist,
                                                         gint column);
GtkWidget*          gtk_clist_get_column_widget         (GtkCList *clist,
                                                         gint column);
GtkAdjustment*      gtk_clist_get_hadjustment           (GtkCList *clist);
GtkAdjustment*      gtk_clist_get_vadjustment           (GtkCList *clist);
void                gtk_clist_row_move                  (GtkCList *clist,
                                                         gint source_row,
                                                         gint dest_row);
void                gtk_clist_set_button_actions        (GtkCList *clist,
                                                         guint button,
                                                         guint8 button_actions);
void                gtk_clist_set_hadjustment           (GtkCList *clist,
                                                         GtkAdjustment *adjustment);
void                gtk_clist_set_reorderable           (GtkCList *clist,
                                                         gboolean reorderable);
void                gtk_clist_set_use_drag_icons        (GtkCList *clist,
                                                         gboolean use_icons);
void                gtk_clist_set_vadjustment           (GtkCList *clist,
                                                         GtkAdjustment *adjustment);

Object Hierarchy

  GObject
   +----GInitiallyUnowned
         +----GtkObject
               +----GtkWidget
                     +----GtkContainer
                           +----GtkCList
                                 +----GtkCTree

Implemented Interfaces

GtkCList implements AtkImplementorIface.

Properties

  "n-columns"                guint                 : Read / Write / Construct Only
  "reorderable"              gboolean              : Read / Write
  "row-height"               guint                 : Read / Write
  "selection-mode"           GtkSelectionMode      : Read / Write
  "shadow-type"              GtkShadowType         : Read / Write
  "sort-type"                GtkSortType           : Read / Write
  "titles-active"            gboolean              : Read / Write
  "use-drag-icons"           gboolean              : Read / Write

Signals

  "abort-column-resize"                            : Run Last / Action
  "click-column"                                   : Run First
  "end-selection"                                  : Run Last / Action
  "extend-selection"                               : Run Last / Action
  "resize-column"                                  : Run Last
  "row-move"                                       : Run Last
  "scroll-horizontal"                              : Run Last / Action
  "scroll-vertical"                                : Run Last / Action
  "select-all"                                     : Run Last / Action
  "select-row"                                     : Run First
  "set-scroll-adjustments"                         : Run Last
  "start-selection"                                : Run Last / Action
  "toggle-add-mode"                                : Run Last / Action
  "toggle-focus-row"                               : Run Last / Action
  "undo-selection"                                 : Run Last / Action
  "unselect-all"                                   : Run Last / Action
  "unselect-row"                                   : Run First

Description

The GtkCList widget is a very useful multi-columned scrolling list. It can display data in nicely aligned vertical columns, with titles at the top of the list.

GtkCList has been deprecated since GTK+ 2.0 and should not be used in newly written code. Use GtkTreeView instead.

Details

GtkCList

typedef struct _GtkCList GtkCList;

Warning

GtkCList is deprecated and should not be used in newly-written code.

This is the embodiment of the GtkCList widget. This structure contains only private data, and should be accessed only via the CList API.

enum GtkCellType

typedef enum
{
  GTK_CELL_EMPTY,
  GTK_CELL_TEXT,
  GTK_CELL_PIXMAP,
  GTK_CELL_PIXTEXT,
  GTK_CELL_WIDGET
} GtkCellType;

Warning

GtkCellType is deprecated and should not be used in newly-written code.

Identifies the type of element in the current cell of the CList. Cells can contain text, pixmaps, or both. Unfortunately support for GTK_CELL_WIDGET was never completed.

enum GtkButtonAction

typedef enum
{
  GTK_BUTTON_IGNORED = 0,
  GTK_BUTTON_SELECTS = 1 << 0,
  GTK_BUTTON_DRAGS   = 1 << 1,
  GTK_BUTTON_EXPANDS = 1 << 2
} GtkButtonAction;

Warning

GtkButtonAction is deprecated and should not be used in newly-written code.

Values for specifying what mouse button events a CList will react to.

GTK_CLIST_FLAGS()

#define GTK_CLIST_FLAGS(clist)             (GTK_CLIST (clist)->flags)

Warning

GTK_CLIST_FLAGS is deprecated and should not be used in newly-written code.

Reads the current flags of the specified CList.

clist : The GtkCList widget from which to get the flags

GTK_CLIST_SET_FLAG()

#define GTK_CLIST_SET_FLAG(clist,flag)     (GTK_CLIST_FLAGS (clist) |= (GTK_ ## flag))

Warning

GTK_CLIST_SET_FLAG is deprecated and should not be used in newly-written code.

A macro to set a particular flag for the specified CList.

clist : | The GtkCList widget to affect.
flag : | A single GtkCList flag to set. NOTE: Do not add the GTK_ prefix.

GTK_CLIST_UNSET_FLAG()

#define GTK_CLIST_UNSET_FLAG(clist,flag)   (GTK_CLIST_FLAGS (clist) &= ~(GTK_ ## flag))

Warning

GTK_CLIST_UNSET_FLAG is deprecated and should not be used in newly-written code.

A macro to clear a particular flag for the specified CList.

clist : | The GtkCList widget to affect.
flag : | A single GtkCList flag to clear. NOTE: Do not add the GTK_ prefix.

GTK_CLIST_IN_DRAG()

#define GTK_CLIST_IN_DRAG(clist)           (GTK_CLIST_FLAGS (clist) & GTK_CLIST_IN_DRAG)

Warning

GTK_CLIST_IN_DRAG is deprecated and should not be used in newly-written code.

A macro to check whether the GtkCList is in "drag mode."

clist : The GtkCList to check.

GTK_CLIST_ROW_HEIGHT_SET()

#define GTK_CLIST_ROW_HEIGHT_SET(clist)    (GTK_CLIST_FLAGS (clist) & GTK_CLIST_ROW_HEIGHT_SET)

Warning

GTK_CLIST_ROW_HEIGHT_SET is deprecated and should not be used in newly-written code.

A macro to check whether the GtkCList's row height is set.

clist : The GtkCList to check.

GTK_CLIST_SHOW_TITLES()

#define GTK_CLIST_SHOW_TITLES(clist)       (GTK_CLIST_FLAGS (clist) & GTK_CLIST_SHOW_TITLES)

Warning

GTK_CLIST_SHOW_TITLES is deprecated and should not be used in newly-written code.

A macro to check whether the flag for showing the widget's column titles is set.

clist : The GtkCList widget to check.

GTK_CLIST_ADD_MODE()

#define GTK_CLIST_ADD_MODE(clist)          (GTK_CLIST_FLAGS (clist) & GTK_CLIST_ADD_MODE)

Warning

GTK_CLIST_ADD_MODE is deprecated and should not be used in newly-written code.

A macro to test whether the CList is in "add mode."

clist : The GtkCList widget to check.

GTK_CLIST_AUTO_SORT()

#define GTK_CLIST_AUTO_SORT(clist)         (GTK_CLIST_FLAGS (clist) & GTK_CLIST_AUTO_SORT)

Warning

GTK_CLIST_AUTO_SORT is deprecated and should not be used in newly-written code.

A macro to test whether the CList has automatic sorting switched on.

clist : The GtkCList widget to check.

GTK_CLIST_AUTO_RESIZE_BLOCKED()

#define GTK_CLIST_AUTO_RESIZE_BLOCKED(clist) (GTK_CLIST_FLAGS (clist) & GTK_CLIST_AUTO_RESIZE_BLOCKED)

Warning

GTK_CLIST_AUTO_RESIZE_BLOCKED is deprecated and should not be used in newly-written code.

A macro to check if automatic resizing of columns is blocked.

clist : The GtkCList widget to check.

GTK_CLIST_REORDERABLE()

#define GTK_CLIST_REORDERABLE(clist)       (GTK_CLIST_FLAGS (clist) & GTK_CLIST_REORDERABLE)

Warning

GTK_CLIST_REORDERABLE is deprecated and should not be used in newly-written code.

A macro to test if the CList's columns are re-orderable

clist : The GtkCList widget to check.

GTK_CLIST_USE_DRAG_ICONS()

#define GTK_CLIST_USE_DRAG_ICONS(clist)    (GTK_CLIST_FLAGS (clist) & GTK_CLIST_USE_DRAG_ICONS)

Warning

GTK_CLIST_USE_DRAG_ICONS is deprecated and should not be used in newly-written code.

A macro to check if the USE_DRAG_ICONS property is enabled.

clist : The GtkCList widget to check.

GTK_CLIST_DRAW_DRAG_LINE()

#define GTK_CLIST_DRAW_DRAG_LINE(clist)    (GTK_CLIST_FLAGS (clist) & GTK_CLIST_DRAW_DRAG_LINE)

Warning

GTK_CLIST_DRAW_DRAG_LINE is deprecated and should not be used in newly-written code.

A macro to check if the DRAW_DRAG_LINE property is enabled.

clist : The GtkCList widget to check.

GTK_CLIST_DRAW_DRAG_RECT()

#define GTK_CLIST_DRAW_DRAG_RECT(clist)    (GTK_CLIST_FLAGS (clist) & GTK_CLIST_DRAW_DRAG_RECT)

Warning

GTK_CLIST_DRAW_DRAG_RECT is deprecated and should not be used in newly-written code.

A macro to check if the DRAW_DRAG_RECT property is enabled.

clist : The GtkCList widget to check.

GTK_CLIST_ROW()

#define GTK_CLIST_ROW(_glist_) ((GtkCListRow *)((_glist_)->data))

Warning

GTK_CLIST_ROW is deprecated and should not be used in newly-written code.

A macro to cast a GList element to a CListRow pointer.

_glist_ : The GList element to convert.

GTK_CELL_TEXT()

#define GTK_CELL_TEXT(cell)     (((GtkCellText *) &(cell)))

Warning

GTK_CELL_TEXT is deprecated and should not be used in newly-written code.

A macro to cast a generic GtkCList cell item to a GtkCellText pointer.

cell : The GtkCList cell item to convert.

GTK_CELL_PIXMAP()

#define GTK_CELL_PIXMAP(cell)   (((GtkCellPixmap *) &(cell)))

Warning

GTK_CELL_PIXMAP is deprecated and should not be used in newly-written code.

A macro to cast a generic GtkCList cell item to a GtkCellPixmap pointer.

cell : The GtkCList cell item to convert.

GTK_CELL_PIXTEXT()

#define GTK_CELL_PIXTEXT(cell)  (((GtkCellPixText *) &(cell)))

Warning

GTK_CELL_PIXTEXT is deprecated and should not be used in newly-written code.

A macro to cast a generic GtkCList cell item to a GtkCellPixText pointer.

cell : The GtkCList cell item to convert.

GTK_CELL_WIDGET()

#define GTK_CELL_WIDGET(cell)   (((GtkCellWidget *) &(cell)))

Warning

GTK_CELL_WIDGET is deprecated and should not be used in newly-written code.

A macro to cast a generic GtkCList cell item to a GtkCellWidget pointer.

cell : The GtkCList cell item to convert.

GtkCListCompareFunc ()

gint                (*GtkCListCompareFunc)              (GtkCList *clist,
                                                         gconstpointer ptr1,
                                                         gconstpointer ptr2);

Warning

GtkCListCompareFunc is deprecated and should not be used in newly-written code.

Function prototype for the compare function callback.

clist : | The GtkCList that is affected.
ptr1 : | A gconstpointer to the first node to compare.
ptr2 : | A gconstpointer to the second node to compare.
Returns : | 0 if the nodes are equal, less than 0 if the first node should come before the second, and greater than 1 if the second come before the first.

GtkCListColumn

typedef struct {
  gchar *title;
  GdkRectangle area;

  GtkWidget *button;
  GdkWindow *window;

  gint width;
  gint min_width;
  gint max_width;
  GtkJustification justification;

  guint visible        : 1;
  guint width_set      : 1;
  guint resizeable     : 1;
  guint auto_resize    : 1;
  guint button_passive : 1;
} GtkCListColumn;

Warning

GtkCListColumn is deprecated and should not be used in newly-written code.

A structure that the GtkCList widget uses to keep track of information about its columns.

GtkCListRow

typedef struct {
  GtkCell *cell;
  GtkStateType state;

  GdkColor foreground;
  GdkColor background;

  GtkStyle *style;

  gpointer data;
  GtkDestroyNotify destroy;

  guint fg_set     : 1;
  guint bg_set     : 1;
  guint selectable : 1;
} GtkCListRow;

Warning

GtkCListRow is deprecated and should not be used in newly-written code.

A structure that the GtkCList widget uses to keep track of information about its rows.

GtkCellText

typedef struct {
  GtkCellType type;

  gint16 vertical;
  gint16 horizontal;

  GtkStyle *style;

  gchar *text;
} GtkCellText;

Warning

GtkCellText is deprecated and should not be used in newly-written code.

A structure that the GtkCList widget uses to keep track of GtkCList cells that contain text.

GtkCellPixmap

typedef struct {
  GtkCellType type;

  gint16 vertical;
  gint16 horizontal;

  GtkStyle *style;

  GdkPixmap *pixmap;
  GdkBitmap *mask;
} GtkCellPixmap;

Warning

GtkCellPixmap is deprecated and should not be used in newly-written code.

A structure that the GtkCList widget uses to keep track of GtkCList cells that contain a GdkPixmap.

GtkCellPixText

typedef struct {
  GtkCellType type;

  gint16 vertical;
  gint16 horizontal;

  GtkStyle *style;

  gchar *text;
  guint8 spacing;
  GdkPixmap *pixmap;
  GdkBitmap *mask;
} GtkCellPixText;

Warning

GtkCellPixText is deprecated and should not be used in newly-written code.

A structure that the GtkCList widget uses to keep track of GtkCList cells that contain a combination of text and a GdkPixmap.

GtkCellWidget

typedef struct {
  GtkCellType type;

  gint16 vertical;
  gint16 horizontal;

  GtkStyle *style;

  GtkWidget *widget;
} GtkCellWidget;

Warning

GtkCellWidget is deprecated and should not be used in newly-written code.

A structure that the GtkCList widget uses to keep track of GtkCList cells that contain another widget.

GtkCell

typedef struct {
  GtkCellType type;

  gint16 vertical;
  gint16 horizontal;

  GtkStyle *style;

  union {
    gchar *text;

    struct {
      GdkPixmap *pixmap;
      GdkBitmap *mask;
    } pm;

    struct {
      gchar *text;
      guint8 spacing;
      GdkPixmap *pixmap;
      GdkBitmap *mask;
    } pt;

    GtkWidget *widget;
  } u;
} GtkCell;

Warning

GtkCell is deprecated and should not be used in newly-written code.

A generic structure that the GtkCList widget uses to keep track of the contents of each of its cells.

GtkCListCellInfo

typedef struct {
  gint row;
  gint column;
} GtkCListCellInfo;

Warning

GtkCListCellInfo is deprecated and should not be used in newly-written code.

A simple structure that the GtkCList widget uses to keep track of the location of a cell.

GtkCListDestInfo

typedef struct {
  GtkCListCellInfo cell;
  GtkCListDragPos  insert_pos;
} GtkCListDestInfo;

Warning

GtkCListDestInfo is deprecated and should not be used in newly-written code.

A simple structure that the GtkCList widget uses to track a cell for a drag operation.

enum GtkCListDragPos

typedef enum
{
  GTK_CLIST_DRAG_NONE,
  GTK_CLIST_DRAG_BEFORE,
  GTK_CLIST_DRAG_INTO,
  GTK_CLIST_DRAG_AFTER
} GtkCListDragPos;

Warning

GtkCListDragPos is deprecated and should not be used in newly-written code.

An enumeration for drag operations.

gtk_clist_new ()

GtkWidget*          gtk_clist_new                       (gint columns);

Warning

gtk_clist_new is deprecated and should not be used in newly-written code.

Creates a new GtkCList widget for use.

columns : | The number of columns the GtkCList should have.
Returns : | A pointer to a new GtkCList object.

gtk_clist_new_with_titles ()

GtkWidget*          gtk_clist_new_with_titles           (gint columns,
                                                         gchar *titles[]);

Warning

gtk_clist_new_with_titles is deprecated and should not be used in newly-written code.

Creates a new GtkCList widget with column titles for use.

columns : | The number of columns the GtkCList should have.
titles : | A string array of titles for the widget. There should be enough strings in the array for the specified number of columns.
Returns : | A pointer to a new GtkCList object.

gtk_clist_set_shadow_type ()

void                gtk_clist_set_shadow_type           (GtkCList *clist,
                                                         GtkShadowType type);

Warning

gtk_clist_set_shadow_type is deprecated and should not be used in newly-written code.

Sets the shadow type for the specified CList. Changing this value will cause the GtkCList to update its visuals.

clist : | The GtkCList to affect.
type : | The GtkShadowType desired.

gtk_clist_set_selection_mode ()

void                gtk_clist_set_selection_mode        (GtkCList *clist,
                                                         GtkSelectionMode mode);

Warning

gtk_clist_set_selection_mode is deprecated and should not be used in newly-written code.

Sets the selection mode for the specified CList. This allows you to set whether only one or more than one item can be selected at a time in the widget. Note that setting the widget's selection mode to one of GTK_SELECTION_BROWSE or GTK_SELECTION_SINGLE will cause all the items in the GtkCList to become deselected.

clist : | The GtkCList to affect.
mode : | The GtkSelectionMode type to set for this CList.

gtk_clist_freeze ()

void                gtk_clist_freeze                    (GtkCList *clist);

Warning

gtk_clist_freeze is deprecated and should not be used in newly-written code.

Causes the GtkCList to stop updating its visuals until a matching call to gtk_clist_thaw() is made. This function is useful if a lot of changes will be made to the widget that may cause a lot of visual updating to occur. Note that calls to gtk_clist_freeze() can be nested.

clist : The GtkCList to freeze.

gtk_clist_thaw ()

void                gtk_clist_thaw                      (GtkCList *clist);

Warning

gtk_clist_thaw is deprecated and should not be used in newly-written code.

Causes the specified GtkCList to allow visual updates.

clist : The GtkCList to thaw.

gtk_clist_column_titles_show ()

void                gtk_clist_column_titles_show        (GtkCList *clist);

Warning

gtk_clist_column_titles_show is deprecated and should not be used in newly-written code.

This function causes the GtkCList to show its column titles, if they are not already showing.

clist : The GtkCList to affect.

gtk_clist_column_titles_hide ()

void                gtk_clist_column_titles_hide        (GtkCList *clist);

Warning

gtk_clist_column_titles_hide is deprecated and should not be used in newly-written code.

Causes the GtkCList to hide its column titles, if they are currently showing.

clist : The GtkCList to affect.

gtk_clist_column_title_active ()

void                gtk_clist_column_title_active       (GtkCList *clist,
                                                         gint column);

Warning

gtk_clist_column_title_active is deprecated and should not be used in newly-written code.

Sets the specified column in the GtkCList to become selectable. You can then respond to events from the user clicking on a title button, and take appropriate action.

clist : | The GtkCList to affect.
column : | The column to make active, counting from 0.

gtk_clist_column_title_passive ()

void                gtk_clist_column_title_passive      (GtkCList *clist,
                                                         gint column);

Warning

gtk_clist_column_title_passive is deprecated and should not be used in newly-written code.

Causes the specified column title button to become passive, i.e., does not respond to events, such as the user clicking on it.

clist : | The GtkCList to affect.
column : | The column to make passive, counting from 0.

gtk_clist_column_titles_active ()

void                gtk_clist_column_titles_active      (GtkCList *clist);

Warning

gtk_clist_column_titles_active is deprecated and should not be used in newly-written code.

Causes all column title buttons to become active. This is the same as calling gtk_clist_column_title_active() for each column.

clist : The GtkCList to affect.

gtk_clist_column_titles_passive ()

void                gtk_clist_column_titles_passive     (GtkCList *clist);

Warning

gtk_clist_column_titles_passive is deprecated and should not be used in newly-written code.

Causes all column title buttons to become passive. This is the same as calling gtk_clist_column_title_passive() for each column.

clist : The GtkCList to affect.

gtk_clist_set_column_title ()

void                gtk_clist_set_column_title          (GtkCList *clist,
                                                         gint column,
                                                         const gchar *title);

Warning

gtk_clist_set_column_title is deprecated and should not be used in newly-written code.

Sets the title for the specified column.

clist : | The GtkCList to affect.
column : | The column whose title should be changed.
title : | A string to be the column's title.

gtk_clist_set_column_widget ()

void                gtk_clist_set_column_widget         (GtkCList *clist,
                                                         gint column,
                                                         GtkWidget *widget);

Warning

gtk_clist_set_column_widget is deprecated and should not be used in newly-written code.

Sets a widget to be used as the specified column's title. This can be used to place a pixmap or something else as the column title, instead of the standard text.

clist : | The GtkCList to affect.
column : | The column whose title should be a widget.
widget : | A pointer to a previously create widget.

gtk_clist_set_column_justification ()

void                gtk_clist_set_column_justification  (GtkCList *clist,
                                                         gint column,
                                                         GtkJustification justification);

Warning

gtk_clist_set_column_justification is deprecated and should not be used in newly-written code.

Sets the justification to be used for all text in the specified column.

clist : | The GtkCList to affect.
column : | The column which should be affected.
justification : | A GtkJustification value for the column.

gtk_clist_set_column_visibility ()

void                gtk_clist_set_column_visibility     (GtkCList *clist,
                                                         gint column,
                                                         gboolean visible);

Warning

gtk_clist_set_column_visibility is deprecated and should not be used in newly-written code.

Allows you to set whether a specified column in the GtkCList should be hidden or shown. Note that at least one column must always be showing, so attempting to hide the last visible column will be ignored.

clist : | The GtkCList to affect.
column : | The column to set visibility.
visible : | TRUE or FALSE.

gtk_clist_set_column_resizeable ()

void                gtk_clist_set_column_resizeable     (GtkCList *clist,
                                                         gint column,
                                                         gboolean resizeable);

Warning

gtk_clist_set_column_resizeable is deprecated and should not be used in newly-written code.

Lets you specify whether a specified column should be resizeable by the user. Note that turning on resizeability for the column will automatically shut off auto-resizing, but turning off resizeability will NOT turn on auto-resizing. This must be done manually via a call to gtk_clist_set_column_auto_resize().

clist : | The GtkCList to affect.
column : | The column on which to set resizeability.
resizeable : | TRUE or FALSE.

gtk_clist_set_column_auto_resize ()

void                gtk_clist_set_column_auto_resize    (GtkCList *clist,
                                                         gint column,
                                                         gboolean auto_resize);

Warning

gtk_clist_set_column_auto_resize is deprecated and should not be used in newly-written code.

Lets you specify whether a column should be automatically resized by the widget when data is added or removed. Enabling auto-resize on a column explicity disallows user-resizing of the column.

clist : | The GtkCList to affect.
column : | The column on which to set auto-resizing.
auto_resize : | TRUE or FALSE.

gtk_clist_optimal_column_width ()

gint                gtk_clist_optimal_column_width      (GtkCList *clist,
                                                         gint column);

Warning

gtk_clist_optimal_column_width is deprecated and should not be used in newly-written code.

Gets the required width in pixels that is needed to show everything in the specified column.

clist : | The GtkCList to check.
column : | The column to check.
Returns : | The required width in pixels for the column.

gtk_clist_set_column_width ()

void                gtk_clist_set_column_width          (GtkCList *clist,
                                                         gint column,
                                                         gint width);

Warning

gtk_clist_set_column_width is deprecated and should not be used in newly-written code.

Causes the column specified for the GtkCList to be set to a specified width.

clist : | The GtkCList to affect.
column : | The column to set the width.
width : | The width, in pixels.

gtk_clist_set_column_min_width ()

void                gtk_clist_set_column_min_width      (GtkCList *clist,
                                                         gint column,
                                                         gint min_width);

Warning

gtk_clist_set_column_min_width is deprecated and should not be used in newly-written code.

Causes the column specified to have a minimum width, preventing the user from resizing it smaller than that specified.

clist : | The GtkCList to affect.
column : | The column to set the minimum width.
min_width : | The width, in pixels.

gtk_clist_set_column_max_width ()

void                gtk_clist_set_column_max_width      (GtkCList *clist,
                                                         gint column,
                                                         gint max_width);

Warning

gtk_clist_set_column_max_width is deprecated and should not be used in newly-written code.

Causes the column specified to have a maximum width, preventing the user from resizing it larger than that specified.

clist : | The GtkCList to affect.
column : | The column to set the maximum width.
max_width : | The width, in pixels.

gtk_clist_set_row_height ()

void                gtk_clist_set_row_height            (GtkCList *clist,
                                                         guint height);

Warning

gtk_clist_set_row_height is deprecated and should not be used in newly-written code.

Causes the GtkCList to have a specified height for its rows. Setting the row height to 0 allows the GtkCList to adjust automatically to data in the row.

clist : | The GtkCList to affect.
height : | The height, in pixels.

gtk_clist_moveto ()

void                gtk_clist_moveto                    (GtkCList *clist,
                                                         gint row,
                                                         gint column,
                                                         gfloat row_align,
                                                         gfloat col_align);

Warning

gtk_clist_moveto is deprecated and should not be used in newly-written code.

Tells the CList widget to visually move to the specified row and column.

clist : | The GtkCList to affect.
row : | The row to which to move.
column : | The column to which to move.
row_align : | A value between 0 and 1 that describes the positioning of the row in relation to the viewable area of the CList's contents.
col_align : | A value between 0 and 1 that describes the positioning of the column in relation to the viewable area of the CList's contents.

gtk_clist_row_is_visible ()

GtkVisibility       gtk_clist_row_is_visible            (GtkCList *clist,
                                                         gint row);

Warning

gtk_clist_row_is_visible is deprecated and should not be used in newly-written code.

Checks how the specified row is visible.

clist : | The GtkCList to affect.
row : | The row to query.
Returns : | A GtkVisibility value that tells you how the row is visible.

gtk_clist_get_cell_type ()

GtkCellType         gtk_clist_get_cell_type             (GtkCList *clist,
                                                         gint row,
                                                         gint column);

Warning

gtk_clist_get_cell_type is deprecated and should not be used in newly-written code.

Checks the type of cell at the location specified.

clist : | The GtkCList to affect.
row : | The row of the cell.
column : | The column of the cell.
Returns : | A GtkCellType value describing the cell.

gtk_clist_set_text ()

void                gtk_clist_set_text                  (GtkCList *clist,
                                                         gint row,
                                                         gint column,
                                                         const gchar *text);

Warning

gtk_clist_set_text is deprecated and should not be used in newly-written code.

Sets the displayed text in the specified cell.

clist : | The GtkCList to affect.
row : | The row of the cell.
column : | The column of the cell.
text : | The text to set in the cell.

gtk_clist_get_text ()

gint                gtk_clist_get_text                  (GtkCList *clist,
                                                         gint row,
                                                         gint column,
                                                         gchar **text);

Warning

gtk_clist_get_text is deprecated and should not be used in newly-written code.

Gets the text for the specified cell.

clist : | The GtkCList to affect.
row : | The row to query.
column : | The column to query.
text : | A pointer to a pointer to store the text.
Returns : | 1 if the cell's text could be retrieved, 0 otherwise.

gtk_clist_set_pixmap ()

void                gtk_clist_set_pixmap                (GtkCList *clist,
                                                         gint row,
                                                         gint column,
                                                         GdkPixmap *pixmap,
                                                         GdkBitmap *mask);

Warning

gtk_clist_set_pixmap is deprecated and should not be used in newly-written code.

Sets a pixmap for the specified cell.

clist : | The GtkCList to affect.
row : | The row of the cell.
column : | The column of the cell.
pixmap : | A pointer to a GdkPixmap to place in the cell.
mask : | A pointer to a GdkBitmap mask for the cell.

gtk_clist_get_pixmap ()

gint                gtk_clist_get_pixmap                (GtkCList *clist,
                                                         gint row,
                                                         gint column,
                                                         GdkPixmap **pixmap,
                                                         GdkBitmap **mask);

Warning

gtk_clist_get_pixmap is deprecated and should not be used in newly-written code.

Gets the pixmap and bitmap mask of the specified cell. The returned mask value can be NULL.

clist : | The GtkCList to affect.
row : | The row of the cell.
column : | The column of the cell.
pixmap : | A pointer to a pointer to store the cell's GdkPixmap.
mask : | A pointer to a pointer to store the cell's GdkBitmap mask.
Returns : | 1 if the cell's pixmap could be retrieved, 0 otherwise.

gtk_clist_set_pixtext ()

void                gtk_clist_set_pixtext               (GtkCList *clist,
                                                         gint row,
                                                         gint column,
                                                         const gchar *text,
                                                         guint8 spacing,
                                                         GdkPixmap *pixmap,
                                                         GdkBitmap *mask);

Warning

gtk_clist_set_pixtext is deprecated and should not be used in newly-written code.

Sets text and a pixmap/bitmap on the specified cell.

clist : | The GtkCList to affect.
row : | The row of the cell.
column : | The column of the cell.
text : | The text to set in the cell.
spacing : | The spacing between the cell's text and pixmap.
pixmap : | A pointer to a GdkPixmap for the cell.
mask : | A pointer to a GdkBitmap mask for the cell.

gtk_clist_get_pixtext ()

gint                gtk_clist_get_pixtext               (GtkCList *clist,
                                                         gint row,
                                                         gint column,
                                                         gchar **text,
                                                         guint8 *spacing,
                                                         GdkPixmap **pixmap,
                                                         GdkBitmap **mask);

Warning

gtk_clist_get_pixtext is deprecated and should not be used in newly-written code.

Gets the text, pixmap and bitmap mask for the specified cell.

clist : | The GtkCList to affect.
row : | The row to query.
column : | The column to query.
text : | A pointer to a pointer to store the text.
spacing : | A pointer to a guint8 to store the spacing.
pixmap : | A pointer to a GdkPixmap pointer to store the cell's pixmap.
mask : | A pointer to a GdkBitmap pointer to store the cell's bitmap mask.
Returns : | 1 if the retrieval was successful, 0 otherwise.

gtk_clist_set_foreground ()

void                gtk_clist_set_foreground            (GtkCList *clist,
                                                         gint row,
                                                         const GdkColor *color);

Warning

gtk_clist_set_foreground is deprecated and should not be used in newly-written code.

Sets the foreground color for the specified row.

clist : | The GtkCList to affect.
row : | The row to affect.
color : | A pointer to a GdkColor structure.

gtk_clist_set_background ()

void                gtk_clist_set_background            (GtkCList *clist,
                                                         gint row,
                                                         const GdkColor *color);

Warning

gtk_clist_set_background is deprecated and should not be used in newly-written code.

Sets the background color for the specified row.

clist : | The GtkCList to affect.
row : | The row to affect.
color : | A pointer to a GdkColor structure.

gtk_clist_set_cell_style ()

void                gtk_clist_set_cell_style            (GtkCList *clist,
                                                         gint row,
                                                         gint column,
                                                         GtkStyle *style);

Warning

gtk_clist_set_cell_style is deprecated and should not be used in newly-written code.

Sets the style for the specified cell.

clist : | The GtkCList to affect.
row : | The row of the cell.
column : | The column of the cell.
style : | A pointer to a GtkStyle structure.

gtk_clist_get_cell_style ()

GtkStyle*           gtk_clist_get_cell_style            (GtkCList *clist,
                                                         gint row,
                                                         gint column);

Warning

gtk_clist_get_cell_style is deprecated and should not be used in newly-written code.

Gets the current style of the specified cell.

clist : | The GtkCList to affect.
row : | The row of the cell.
column : | The column of the cell.
Returns : | A GtkStyle object.

gtk_clist_set_row_style ()

void                gtk_clist_set_row_style             (GtkCList *clist,
                                                         gint row,
                                                         GtkStyle *style);

Warning

gtk_clist_set_row_style is deprecated and should not be used in newly-written code.

Sets the style for all cells in the specified row.

clist : | The GtkCList to affect.
row : | The row to affect.
style : | A pointer to a GtkStyle to set.

gtk_clist_get_row_style ()

GtkStyle*           gtk_clist_get_row_style             (GtkCList *clist,
                                                         gint row);

Warning

gtk_clist_get_row_style is deprecated and should not be used in newly-written code.

Gets the style set for the specified row.

clist : | The GtkCList to affect.
row : | The row to query.
Returns : | The GtkStyle of the row.

gtk_clist_set_shift ()

void                gtk_clist_set_shift                 (GtkCList *clist,
                                                         gint row,
                                                         gint column,
                                                         gint vertical,
                                                         gint horizontal);

Warning

gtk_clist_set_shift is deprecated and should not be used in newly-written code.

Sets the vertical and horizontal shift of the specified cell.

clist : | The GtkCList to affect.
row : | The row of the cell.
column : | The column of the cell.
vertical : | The value to set for the vertical shift.
horizontal : | The value to set for the vertical shift.

gtk_clist_set_selectable ()

void                gtk_clist_set_selectable            (GtkCList *clist,
                                                         gint row,
                                                         gboolean selectable);

Warning

gtk_clist_set_selectable is deprecated and should not be used in newly-written code.

Sets whether the specified row is selectable or not.

clist : | The GtkCList to affect.
row : | The row to affect.
selectable : | TRUE or FALSE.

gtk_clist_get_selectable ()

gboolean            gtk_clist_get_selectable            (GtkCList *clist,
                                                         gint row);

Warning

gtk_clist_get_selectable is deprecated and should not be used in newly-written code.

Gets whether the specified row is selectable or not.

clist : | The GtkCList to affect.
row : | The row to query.
Returns : | A gboolean value.

gtk_clist_prepend ()

gint                gtk_clist_prepend                   (GtkCList *clist,
                                                         gchar *text[]);

Warning

gtk_clist_prepend is deprecated and should not be used in newly-written code.

Adds a row to the CList at the top.

clist : | The GtkCList to affect.
text : | An array of strings to add.
Returns : | The number of the row added.

gtk_clist_append ()

gint                gtk_clist_append                    (GtkCList *clist,
                                                         gchar *text[]);

Warning

gtk_clist_append is deprecated and should not be used in newly-written code.

Adds a row to the CList at the bottom.

clist : | The GtkCList to affect.
text : | An array of strings to add.
Returns : | The number of the row added.

gtk_clist_insert ()

gint                gtk_clist_insert                    (GtkCList *clist,
                                                         gint row,
                                                         gchar *text[]);

Warning

gtk_clist_insert is deprecated and should not be used in newly-written code.

Adds a row of text to the CList at the specified position.

clist : | The GtkCList to affect.
row : | The row where the text should be inserted.
text : | An array of string to add.
Returns : | The number of the row added.

gtk_clist_remove ()

void                gtk_clist_remove                    (GtkCList *clist,
                                                         gint row);

Warning

gtk_clist_remove is deprecated and should not be used in newly-written code.

Removes the specified row from the CList.

clist : | The GtkCList to affect.
row : | The row to remove.

gtk_clist_set_row_data ()

void                gtk_clist_set_row_data              (GtkCList *clist,
                                                         gint row,
                                                         gpointer data);

Warning

gtk_clist_set_row_data is deprecated and should not be used in newly-written code.

Sets data for the specified row. This is the same as calling gtk_clist_set_row_data_full(clist, row, data, NULL).

clist : | The GtkCList to affect.
row : | The row to affect.
data : | The data to set for the row.

gtk_clist_set_row_data_full ()

void                gtk_clist_set_row_data_full         (GtkCList *clist,
                                                         gint row,
                                                         gpointer data,
                                                         GtkDestroyNotify destroy);

Warning

gtk_clist_set_row_data_full is deprecated and should not be used in newly-written code.

Sets the data for specified row, with a callback when the row is destroyed.

clist : | The GtkCList to affect.
row : | The row to affect.
data : | The data to set for the row.
destroy : | A GtkDestroyNotify function to be called when the row is destroyed.

gtk_clist_get_row_data ()

gpointer            gtk_clist_get_row_data              (GtkCList *clist,
                                                         gint row);

Warning

gtk_clist_get_row_data is deprecated and should not be used in newly-written code.

Gets the currently set data for the specified row.

clist : | The GtkCList to affect.
row : | The row to query.
Returns : | The data set for the row.

gtk_clist_find_row_from_data ()

gint                gtk_clist_find_row_from_data        (GtkCList *clist,
                                                         gpointer data);

Warning

gtk_clist_find_row_from_data is deprecated and should not be used in newly-written code.

Searches the CList for the row with the specified data.

clist : | The GtkCList to search.
data : | The data to search for a match.
Returns : | The number of the matching row, or -1 if no match could be found.

gtk_clist_select_row ()

void                gtk_clist_select_row                (GtkCList *clist,
                                                         gint row,
                                                         gint column);

Warning

gtk_clist_select_row is deprecated and should not be used in newly-written code.

Selects the specified row. Causes the "select-row" signal to be emitted for the specified row and column.

clist : | The GtkCList to affect.
row : | The row to select.
column : | The column to select.

gtk_clist_unselect_row ()

void                gtk_clist_unselect_row              (GtkCList *clist,
                                                         gint row,
                                                         gint column);

Warning

gtk_clist_unselect_row is deprecated and should not be used in newly-written code.

Unselects the specified row. Causes the "unselect-row" signal to be emitted for the specified row and column.

clist : | The GtkCList to affect.
row : | The row to select.
column : | The column to select.

gtk_clist_undo_selection ()

void                gtk_clist_undo_selection            (GtkCList *clist);

Warning

gtk_clist_undo_selection is deprecated and should not be used in newly-written code.

Undoes the last selection for an "extended selection mode" CList.

clist : The GtkCList to affect.

gtk_clist_clear ()

void                gtk_clist_clear                     (GtkCList *clist);

Warning

gtk_clist_clear is deprecated and should not be used in newly-written code.

Removes all the CList's rows.

clist : The GtkCList to affect.

gtk_clist_get_selection_info ()

gint                gtk_clist_get_selection_info        (GtkCList *clist,
                                                         gint x,
                                                         gint y,
                                                         gint *row,
                                                         gint *column);

Warning

gtk_clist_get_selection_info is deprecated and should not be used in newly-written code.

Gets the row and column at the specified pixel position in the CList.

clist : | The GtkCList to affect.
x : | The horizontal pixel position to check.
y : | The vertical pixel position to check..
row : | Pointer to a gint to store the row value.
column : | Pointer to a gint to store the column value.
Returns : | 1 if row/column is returned and in range, 0 otherwise.

gtk_clist_select_all ()

void                gtk_clist_select_all                (GtkCList *clist);

Warning

gtk_clist_select_all is deprecated and should not be used in newly-written code.

Selects all rows in the CList. This function has no affect for a CList in "single" or "browse" selection mode.

clist : The GtkCList to affect.

gtk_clist_unselect_all ()

void                gtk_clist_unselect_all              (GtkCList *clist);

Warning

gtk_clist_unselect_all is deprecated and should not be used in newly-written code.

Unselects all rows in the CList.

clist : The GtkCList to affect.

gtk_clist_swap_rows ()

void                gtk_clist_swap_rows                 (GtkCList *clist,
                                                         gint row1,
                                                         gint row2);

Warning

gtk_clist_swap_rows is deprecated and should not be used in newly-written code.

Swaps the two specified rows with each other.

clist : | The GtkCList to affect.
row1 : | Number of the first row.
row2 : | Number of the second row.

gtk_clist_set_compare_func ()

void                gtk_clist_set_compare_func          (GtkCList *clist,
                                                         GtkCListCompareFunc cmp_func);

Warning

gtk_clist_set_compare_func is deprecated and should not be used in newly-written code.

Sets the compare function of the GtkClist to cmp_func. If cmp_func is NULL, then the default compare function is used. The default compare function sorts ascending or with the type set by gtk_clist_set_sort_type() by the column set by gtk_clist_set_sort_column().

clist : | The GtkCList to affect.
cmp_func : | The GtkCompareFunction to use.

gtk_clist_set_sort_column ()

void                gtk_clist_set_sort_column           (GtkCList *clist,
                                                         gint column);

Warning

gtk_clist_set_sort_column is deprecated and should not be used in newly-written code.

Sets the sort column of the clist. The sort column is used by the default compare function to determine which column to sort by.

clist : | The GtkCList to affect.
column : | The column to sort by

gtk_clist_set_sort_type ()

void                gtk_clist_set_sort_type             (GtkCList *clist,
                                                         GtkSortType sort_type);

Warning

gtk_clist_set_sort_type is deprecated and should not be used in newly-written code.

Sets the sort type of the GtkClist. This is either GTK_SORT_ASCENDING for ascening sort or GTK_SORT_DESCENDING for descending sort.

clist : | The GtkCList to affect.
sort_type : | the GtkSortType to use

gtk_clist_sort ()

void                gtk_clist_sort                      (GtkCList *clist);

Warning

gtk_clist_sort is deprecated and should not be used in newly-written code.

Sorts the GtkClist according to the current compare function, which can be set with the gtk_clist_set_compare_func() function.

clist : The GtkCList to sort.

gtk_clist_set_auto_sort ()

void                gtk_clist_set_auto_sort             (GtkCList *clist,
                                                         gboolean auto_sort);

Warning

gtk_clist_set_auto_sort is deprecated and should not be used in newly-written code.

Turns on or off auto sort of the GtkCList. If auto sort is on, then the CList will be resorted when a row is inserted into the CList.

clist : | The GtkCList to affect.
auto_sort : | whether auto sort should be on or off

gtk_clist_columns_autosize ()

gint                gtk_clist_columns_autosize          (GtkCList *clist);

Warning

gtk_clist_columns_autosize is deprecated and should not be used in newly-written code.

Auto-sizes all columns in the CList and returns the total width of the CList.

clist : | The GtkCList to affect.
Returns : | The total width of the CList.

gtk_clist_get_column_title ()

gchar*              gtk_clist_get_column_title          (GtkCList *clist,
                                                         gint column);

Warning

gtk_clist_get_column_title is deprecated and should not be used in newly-written code.

Gets the current title of the specified column

clist : | The GtkCList to affect.
column : | The column to query.
Returns : | The title of the column.

gtk_clist_get_column_widget ()

GtkWidget*          gtk_clist_get_column_widget         (GtkCList *clist,
                                                         gint column);

Warning

gtk_clist_get_column_widget is deprecated and should not be used in newly-written code.

Gets the widget in the column header for the specified column.

clist : | The GtkCList to affect.
column : | The column to query.
Returns : | Pointer to a GtkWidget for the column header.

gtk_clist_get_hadjustment ()

GtkAdjustment*      gtk_clist_get_hadjustment           (GtkCList *clist);

Warning

gtk_clist_get_hadjustment is deprecated and should not be used in newly-written code.

Gets the GtkAdjustment currently being used for the horizontal aspect.

clist : | The GtkCList to check.
Returns : | A GtkAdjustment object, or NULL if none is currently being used.

gtk_clist_get_vadjustment ()

GtkAdjustment*      gtk_clist_get_vadjustment           (GtkCList *clist);

Warning

gtk_clist_get_vadjustment is deprecated and should not be used in newly-written code.

Gets the GtkAdjustment currently being used for the vertical aspect.

clist : | The GtkCList to check.
Returns : | A GtkAdjustment object, or NULL if none is currently being used.

gtk_clist_row_move ()

void                gtk_clist_row_move                  (GtkCList *clist,
                                                         gint source_row,
                                                         gint dest_row);

Warning

gtk_clist_row_move is deprecated and should not be used in newly-written code.

Allows you to move a row from one position to another in the list.

clist : | The GtkCList to affect.
source_row : | The original position of the row to move.
dest_row : | The position to which the row should be moved.

gtk_clist_set_button_actions ()

void                gtk_clist_set_button_actions        (GtkCList *clist,
                                                         guint button,
                                                         guint8 button_actions);

Warning

gtk_clist_set_button_actions is deprecated and should not be used in newly-written code.

Sets the action(s) that the specified mouse button will have on the CList.

clist : | The GtkCList to affect.
button : | The mouse button to set. The values here, unlike in the rest of GTK+ start from 0. For instance, the right mouse button, which is 3 elsewhere, should be given as 2 here.
button_actions : | A logically OR'd value of GtkButtonAction values for the button.

gtk_clist_set_hadjustment ()

void                gtk_clist_set_hadjustment           (GtkCList *clist,
                                                         GtkAdjustment *adjustment);

Warning

gtk_clist_set_hadjustment is deprecated and should not be used in newly-written code.

Allows you to set the GtkAdjustment to be used for the horizontal aspect of the GtkCList widget.

clist : | The GtkCList to affect.
adjustment : | A pointer to a GtkAdjustment widget, or NULL.

gtk_clist_set_reorderable ()

void                gtk_clist_set_reorderable           (GtkCList *clist,
                                                         gboolean reorderable);

Warning

gtk_clist_set_reorderable is deprecated and should not be used in newly-written code.

Sets whether the CList's rows are re-orderable using drag-and-drop.

clist : | The GtkCList to affect.
reorderable : | TRUE or FALSE.

gtk_clist_set_use_drag_icons ()

void                gtk_clist_set_use_drag_icons        (GtkCList *clist,
                                                         gboolean use_icons);

Warning

gtk_clist_set_use_drag_icons is deprecated and should not be used in newly-written code.

Determines whether the GtkClist should use icons when doing drag-and-drop operations.

clist : | The GtkCList to affect.
use_icons : | TRUE or FALSE.

gtk_clist_set_vadjustment ()

void                gtk_clist_set_vadjustment           (GtkCList *clist,
                                                         GtkAdjustment *adjustment);

Warning

gtk_clist_set_vadjustment is deprecated and should not be used in newly-written code.

Allows you to set the GtkAdjustment to be used for the vertical aspect of the GtkCList widget.

clist : | The GtkCList to affect.
adjustment : | A pointer to a GtkAdjustment widget, or NULL.

Property Details

The "n-columns" property

  "n-columns"                guint                 : Read / Write / Construct Only

An integer value for a column.

Default value: 0

The "reorderable" property

  "reorderable"              gboolean              : Read / Write

A boolean value for determining if the user can re-order the CList's columns.

Default value: FALSE

The "row-height" property

  "row-height"               guint                 : Read / Write

An integer value representing the height of a row in pixels.

Default value: 0

The "selection-mode" property

  "selection-mode"           GtkSelectionMode      : Read / Write

Sets the type of selection mode for the CList.

Default value: GTK_SELECTION_NONE

The "shadow-type" property

  "shadow-type"              GtkShadowType         : Read / Write

Sets the shadowing for the CList.

Default value: GTK_SHADOW_NONE

The "sort-type" property

  "sort-type"                GtkSortType           : Read / Write

Default value: GTK_SORT_ASCENDING

The "titles-active" property

  "titles-active"            gboolean              : Read / Write

A boolean value for setting whether the column titles can be clicked.

Default value: FALSE

The "use-drag-icons" property

  "use-drag-icons"           gboolean              : Read / Write

A boolean value for setting whether to use icons during drag operations.

Default value: FALSE

Signal Details

The "abort-column-resize" signal

void                user_function                      (GtkCList *clist,
                                                        gpointer  user_data)      : Run Last / Action

This signal is emitted when a column resize is aborted.

clist : | the object which received the signal.
user_data : | user data set when the signal handler was connected.

The "click-column" signal

void                user_function                      (GtkCList *clist,
                                                        gint      column,
                                                        gpointer  user_data)      : Run First

This signal is emitted when a column title is clicked.

clist : | The object which received the signal.
column : | The number of the column.
user_data : | user data set when the signal handler was connected.

The "end-selection" signal

void                user_function                      (GtkCList *clist,
                                                        gpointer  user_data)      : Run Last / Action

This signal is emitted when a selection ends in a multiple selection CList.

clist : | the object which received the signal.
user_data : | user data set when the signal handler was connected.

The "extend-selection" signal

void                user_function                      (GtkCList     *clist,
                                                        GtkScrollType scroll_type,
                                                        gfloat        position,
                                                        gboolean      auto_start_selection,
                                                        gpointer      user_data)                 : Run Last / Action

This signal is emitted when the selection is extended.

clist : | the object which received the signal.
scroll_type : | A GtkScrollType value of any scrolling operation the occured during the selection.
position : | A value between 0.0 and 1.0.
auto_start_selection : | TRUE or FALSE.
user_data : | user data set when the signal handler was connected.

The "resize-column" signal

void                user_function                      (GtkCList *clist,
                                                        gint      column,
                                                        gint      width,
                                                        gpointer  user_data)      : Run Last

This signal is emitted when a column is resized.

clist : | The object which received the signal.
column : | The number of the column
width : | The new width of the column.
user_data : | user data set when the signal handler was connected.

The "row-move" signal

void                user_function                      (GtkCList *clist,
                                                        gint      arg1,
                                                        gint      arg2,
                                                        gpointer  user_data)      : Run Last

This signal is emitted when a row is moved.

clist : | The object which received the signal.
arg1 : | The source position of the row.
arg2 : | The destination position of the row.
user_data : | user data set when the signal handler was connected.

The "scroll-horizontal" signal

void                user_function                      (GtkCList     *clist,
                                                        GtkScrollType scroll_type,
                                                        gfloat        position,
                                                        gpointer      user_data)        : Run Last / Action

This signal is emitted when the CList is scrolled horizontally.

clist : | the object which received the signal.
scroll_type : | A GtkScrollType value of how the scroll operation occured.
position : | a value between 0.0 and 1.0.
user_data : | user data set when the signal handler was connected.

The "scroll-vertical" signal

void                user_function                      (GtkCList     *clist,
                                                        GtkScrollType scroll_type,
                                                        gfloat        position,
                                                        gpointer      user_data)        : Run Last / Action

This signal is emitted when the CList is scrolled vertically.

clist : | the object which received the signal.
scroll_type : | A GtkScrollType value of how the scroll operation occured.
position : | A value between 0.0 and 1.0.
user_data : | user data set when the signal handler was connected.

The "select-all" signal

void                user_function                      (GtkCList *clist,
                                                        gpointer  user_data)      : Run Last / Action

This signal is emitted when all the rows are selected in a CList.

clist : | the object which received the signal.
user_data : | user data set when the signal handler was connected.

The "select-row" signal

void                user_function                      (GtkCList       *clist,
                                                        gint            row,
                                                        gint            column,
                                                        GdkEventButton *event,
                                                        gpointer        user_data)      : Run First

This signal is emitted when the user selects a row in the list. It is emitted for every row that is selected in a multi-selection or by calling gtk_clist_select_all().

clist : | The object which received the signal.
row : | The row selected.
column : | The column where the selection occured.
event : | A GdkEvent structure for the selection.
user_data : | user data set when the signal handler was connected.

The "set-scroll-adjustments" signal

void                user_function                      (GtkCList      *clist,
                                                        GtkAdjustment *arg1,
                                                        GtkAdjustment *arg2,
                                                        gpointer       user_data)      : Run Last

clist : | the object which received the signal.
arg1 : |
arg2 : |
user_data : | user data set when the signal handler was connected.

The "start-selection" signal

void                user_function                      (GtkCList *clist,
                                                        gpointer  user_data)      : Run Last / Action

This signal is emitted when a drag-selection is started in a multiple-selection CList.

clist : | the object which received the signal.
user_data : | user data set when the signal handler was connected.

The "toggle-add-mode" signal

void                user_function                      (GtkCList *clist,
                                                        gpointer  user_data)      : Run Last / Action

This signal is emitted when "add mode" is toggled.

clist : | the object which received the signal.
user_data : | user data set when the signal handler was connected.

The "toggle-focus-row" signal

void                user_function                      (GtkCList *clist,
                                                        gpointer  user_data)      : Run Last / Action

clist : | The object which received the signal.
user_data : | user data set when the signal handler was connected.

The "undo-selection" signal

void                user_function                      (GtkCList *clist,
                                                        gpointer  user_data)      : Run Last / Action

This signal is emitted when an undo selection occurs in the CList, probably via calling gtk_clist_undo_selection().

clist : | the object which received the signal.
user_data : | user data set when the signal handler was connected.

The "unselect-all" signal

void                user_function                      (GtkCList *clist,
                                                        gpointer  user_data)      : Run Last / Action

This signal is emitted when all rows are unselected in a CList.

clist : | the object which received the signal.
user_data : | user data set when the signal handler was connected.

The "unselect-row" signal

void                user_function                      (GtkCList       *clist,
                                                        gint            row,
                                                        gint            column,
                                                        GdkEventButton *event,
                                                        gpointer        user_data)      : Run First

This signal is emitted when the user unselects a row in the list. It is emitted for every row that is unselected in a multi-selection or by calling gtk_clist_unselect_all(). It is also emitted for the previously selected row in a "single" or "browse" mode CList.

clist : | The object which received the signal.
row : | The selected row
column : | The column where the selection occured.
event : |
user_data : | user data set when the signal handler was connected.


GtkColorButton

GtkColorButton — A button to launch a color selection dialog

Synopsis

#include <gtk/gtk.h>

                    GtkColorButton;
GtkWidget*          gtk_color_button_new                (void);
GtkWidget*          gtk_color_button_new_with_color     (const GdkColor *color);
void                gtk_color_button_set_color          (GtkColorButton *color_button,
                                                         const GdkColor *color);
void                gtk_color_button_get_color          (GtkColorButton *color_button,
                                                         GdkColor *color);
void                gtk_color_button_set_alpha          (GtkColorButton *color_button,
                                                         guint16 alpha);
guint16             gtk_color_button_get_alpha          (GtkColorButton *color_button);
void                gtk_color_button_set_use_alpha      (GtkColorButton *color_button,
                                                         gboolean use_alpha);
gboolean            gtk_color_button_get_use_alpha      (GtkColorButton *color_button);
void                gtk_color_button_set_title          (GtkColorButton *color_button,
                                                         const gchar *title);
const gchar*        gtk_color_button_get_title          (GtkColorButton *color_button);

Object Hierarchy

  GObject
   +----GInitiallyUnowned
         +----GtkObject
               +----GtkWidget
                     +----GtkContainer
                           +----GtkBin
                                 +----GtkButton
                                       +----GtkColorButton

Implemented Interfaces

GtkColorButton implements AtkImplementorIface.

Properties

  "alpha"                    guint                 : Read / Write
  "color"                    GdkColor              : Read / Write
  "title"                    gchararray            : Read / Write
  "use-alpha"                gboolean              : Read / Write

Signals

  "color-set"                                      : Run First

Description

The GtkColorButton is a button which displays the currently selected color an allows to open a color selection dialog to change the color. It is suitable widget for selecting a color in a preference dialog.

Details

GtkColorButton

typedef struct _GtkColorButton GtkColorButton;

The GtkColorButton struct has only private fields and should not be used directly.

gtk_color_button_new ()

GtkWidget*          gtk_color_button_new                (void);

Creates a new color button. This returns a widget in the form of a small button containing a swatch representing the current selected color. When the button is clicked, a color-selection dialog will open, allowing the user to select a color. The swatch will be updated to reflect the new color when the user finishes.

Returns : a new color button.

Since 2.4

gtk_color_button_new_with_color ()

GtkWidget*          gtk_color_button_new_with_color     (const GdkColor *color);

Creates a new color button.

color : | A GdkColor to set the current color with.
Returns : | a new color button.

Since 2.4

gtk_color_button_set_color ()

void                gtk_color_button_set_color          (GtkColorButton *color_button,
                                                         const GdkColor *color);

Sets the current color to be color.

color_button : | a GtkColorButton.
color : | A GdkColor to set the current color with.

Since 2.4

gtk_color_button_get_color ()

void                gtk_color_button_get_color          (GtkColorButton *color_button,
                                                         GdkColor *color);

Sets color to be the current color in the GtkColorButton widget.

color_button : | a GtkColorButton.
color : | a GdkColor to fill in with the current color.

Since 2.4

gtk_color_button_set_alpha ()

void                gtk_color_button_set_alpha          (GtkColorButton *color_button,
                                                         guint16 alpha);

Sets the current opacity to be alpha.

color_button : | a GtkColorButton.
alpha : | an integer between 0 and 65535.

Since 2.4

gtk_color_button_get_alpha ()

guint16             gtk_color_button_get_alpha          (GtkColorButton *color_button);

Returns the current alpha value.

color_button : | a GtkColorButton.
Returns : | an integer between 0 and 65535.

Since 2.4

gtk_color_button_set_use_alpha ()

void                gtk_color_button_set_use_alpha      (GtkColorButton *color_button,
                                                         gboolean use_alpha);

Sets whether or not the color button should use the alpha channel.

color_button : | a GtkColorButton.
use_alpha : | TRUE if color button should use alpha channel, FALSE if not.

Since 2.4

gtk_color_button_get_use_alpha ()

gboolean            gtk_color_button_get_use_alpha      (GtkColorButton *color_button);

Does the color selection dialog use the alpha channel?

color_button : | a GtkColorButton.
Returns : | TRUE if the color sample uses alpha channel, FALSE if not.

Since 2.4

gtk_color_button_set_title ()

void                gtk_color_button_set_title          (GtkColorButton *color_button,
                                                         const gchar *title);

Sets the title for the color selection dialog.

color_button : | a GtkColorButton
title : | String containing new window title.

Since 2.4

gtk_color_button_get_title ()

const gchar*        gtk_color_button_get_title          (GtkColorButton *color_button);

Gets the title of the color selection dialog.

color_button : | a GtkColorButton
Returns : | An internal string, do not free the return value

Since 2.4

Property Details

The "alpha" property

  "alpha"                    guint                 : Read / Write

The selected opacity value (0 fully transparent, 65535 fully opaque).

Allowed values: <= 65535

Default value: 65535

Since 2.4

The "color" property

  "color"                    GdkColor              : Read / Write

The selected color.

Since 2.4

The "title" property

  "title"                    gchararray            : Read / Write

The title of the color selection dialog

Default value: "Pick a Color"

Since 2.4

The "use-alpha" property

  "use-alpha"                gboolean              : Read / Write

If this property is set to TRUE, the color swatch on the button is rendered against a checkerboard background to show its opacity and the opacity slider is displayed in the color selection dialog.

Default value: FALSE

Since 2.4

Signal Details

The "color-set" signal

void                user_function                      (GtkColorButton *widget,
                                                        gpointer        user_data)      : Run First

The ::color-set signal is emitted when the user selects a color. When handling this signal, use gtk_color_button_get_color() and gtk_color_button_get_alpha() to find out which color was just selected.

Note that this signal is only emitted when the user changes the color. If you need to react to programmatic color changes as well, use the notify::color signal.

widget : | the object which received the signal.
user_data : | user data set when the signal handler was connected.

Since 2.4

See Also

GtkColorSelectionDialog, GtkFontButton


GtkColorSelection

GtkColorSelection — A widget used to select a color

Synopsis

#include <gtk/gtk.h>

                    GtkColorSelection;
GtkWidget*          gtk_color_selection_new             (void);
void                gtk_color_selection_set_update_policy
                                                        (GtkColorSelection *colorsel,
                                                         GtkUpdateType policy);
void                gtk_color_selection_set_has_opacity_control
                                                        (GtkColorSelection *colorsel,
                                                         gboolean has_opacity);
gboolean            gtk_color_selection_get_has_opacity_control
                                                        (GtkColorSelection *colorsel);
void                gtk_color_selection_set_has_palette (GtkColorSelection *colorsel,
                                                         gboolean has_palette);
gboolean            gtk_color_selection_get_has_palette (GtkColorSelection *colorsel);
guint16             gtk_color_selection_get_current_alpha
                                                        (GtkColorSelection *colorsel);
void                gtk_color_selection_set_current_alpha
                                                        (GtkColorSelection *colorsel,
                                                         guint16 alpha);
void                gtk_color_selection_get_current_color
                                                        (GtkColorSelection *colorsel,
                                                         GdkColor *color);
void                gtk_color_selection_set_current_color
                                                        (GtkColorSelection *colorsel,
                                                         const GdkColor *color);
guint16             gtk_color_selection_get_previous_alpha
                                                        (GtkColorSelection *colorsel);
void                gtk_color_selection_set_previous_alpha
                                                        (GtkColorSelection *colorsel,
                                                         guint16 alpha);
void                gtk_color_selection_get_previous_color
                                                        (GtkColorSelection *colorsel,
                                                         GdkColor *color);
void                gtk_color_selection_set_previous_color
                                                        (GtkColorSelection *colorsel,
                                                         const GdkColor *color);
gboolean            gtk_color_selection_is_adjusting    (GtkColorSelection *colorsel);
gboolean            gtk_color_selection_palette_from_string
                                                        (const gchar *str,
                                                         GdkColor **colors,
                                                         gint *n_colors);
gchar*              gtk_color_selection_palette_to_string
                                                        (const GdkColor *colors,
                                                         gint n_colors);
GtkColorSelectionChangePaletteFunc gtk_color_selection_set_change_palette_hook
                                                        (GtkColorSelectionChangePaletteFunc func);
void                (*GtkColorSelectionChangePaletteFunc)
                                                        (const GdkColor *colors,
                                                         gint n_colors);
GtkColorSelectionChangePaletteWithScreenFunc gtk_color_selection_set_change_palette_with_screen_hook
                                                        (GtkColorSelectionChangePaletteWithScreenFunc func);
void                (*GtkColorSelectionChangePaletteWithScreenFunc)
                                                        (GdkScreen *screen,
                                                         const GdkColor *colors,
                                                         gint n_colors);
void                gtk_color_selection_set_color       (GtkColorSelection *colorsel,
                                                         gdouble *color);
void                gtk_color_selection_get_color       (GtkColorSelection *colorsel,
                                                         gdouble *color);

Object Hierarchy

  GObject
   +----GInitiallyUnowned
         +----GtkObject
               +----GtkWidget
                     +----GtkContainer
                           +----GtkBox
                                 +----GtkVBox
                                       +----GtkColorSelection

Implemented Interfaces

GtkColorSelection implements AtkImplementorIface.

Properties

  "current-alpha"            guint                 : Read / Write
  "current-color"            GdkColor              : Read / Write
  "has-opacity-control"      gboolean              : Read / Write
  "has-palette"              gboolean              : Read / Write

Signals

  "color-changed"                                  : Run First

Description

The GtkColorSelection is a widget that is used to select a color. It consists of a color wheel and number of sliders and entry boxes for color parameters such as hue, saturation, value, red, green, blue, and opacity. It is found on the standard color selection dialog box GtkColorSelectionDialog.

Details

GtkColorSelection

typedef struct _GtkColorSelection GtkColorSelection;

The GtkColorSelection struct contains private data only, and should be accessed using the functions below.

gtk_color_selection_new ()

GtkWidget*          gtk_color_selection_new             (void);

Creates a new GtkColorSelection.

Returns : a new GtkColorSelection

gtk_color_selection_set_update_policy ()

void                gtk_color_selection_set_update_policy
                                                        (GtkColorSelection *colorsel,
                                                         GtkUpdateType policy);

Warning

gtk_color_selection_set_update_policy is deprecated and should not be used in newly-written code.

Sets the policy controlling when the color_changed signals are emitted. The available policies are:

  • GTK_UPDATE_CONTINUOUS - signals are sent continuously as the color selection changes.

  • GTK_UPDATE_DISCONTINUOUS - signals are sent only when the mouse button is released.

  • GTK_UPDATE_DELAYED - signals are sent when the mouse button is released or when the mouse has been motionless for a period of time.

colorsel : | a GtkColorSelection.
policy : | a GtkUpdateType value indicating the desired policy.

gtk_color_selection_set_has_opacity_control ()

void                gtk_color_selection_set_has_opacity_control
                                                        (GtkColorSelection *colorsel,
                                                         gboolean has_opacity);

Sets the colorsel to use or not use opacity.

colorsel : | a GtkColorSelection.
has_opacity : | TRUE if colorsel can set the opacity, FALSE otherwise.

gtk_color_selection_get_has_opacity_control ()

gboolean            gtk_color_selection_get_has_opacity_control
                                                        (GtkColorSelection *colorsel);

Determines whether the colorsel has an opacity control.

colorsel : | a GtkColorSelection.
Returns : | TRUE if the colorsel has an opacity control. FALSE if it does't.

gtk_color_selection_set_has_palette ()

void                gtk_color_selection_set_has_palette (GtkColorSelection *colorsel,
                                                         gboolean has_palette);

Shows and hides the palette based upon the value of has_palette.

colorsel : | a GtkColorSelection.
has_palette : | TRUE if palette is to be visible, FALSE otherwise.

gtk_color_selection_get_has_palette ()

gboolean            gtk_color_selection_get_has_palette (GtkColorSelection *colorsel);

Determines whether the color selector has a color palette.

colorsel : | a GtkColorSelection.
Returns : | TRUE if the selector has a palette. FALSE if it hasn't.

gtk_color_selection_get_current_alpha ()

guint16             gtk_color_selection_get_current_alpha
                                                        (GtkColorSelection *colorsel);

Returns the current alpha value.

colorsel : | a GtkColorSelection.
Returns : | an integer between 0 and 65535.

gtk_color_selection_set_current_alpha ()

void                gtk_color_selection_set_current_alpha
                                                        (GtkColorSelection *colorsel,
                                                         guint16 alpha);

Sets the current opacity to be alpha. The first time this is called, it will also set the original opacity to be alpha too.

colorsel : | a GtkColorSelection.
alpha : | an integer between 0 and 65535.

gtk_color_selection_get_current_color ()

void                gtk_color_selection_get_current_color
                                                        (GtkColorSelection *colorsel,
                                                         GdkColor *color);

Sets color to be the current color in the GtkColorSelection widget.

colorsel : | a GtkColorSelection.
color : | a GdkColor to fill in with the current color.

gtk_color_selection_set_current_color ()

void                gtk_color_selection_set_current_color
                                                        (GtkColorSelection *colorsel,
                                                         const GdkColor *color);

Sets the current color to be color. The first time this is called, it will also set the original color to be color too.

colorsel : | a GtkColorSelection.
color : | A GdkColor to set the current color with.

gtk_color_selection_get_previous_alpha ()

guint16             gtk_color_selection_get_previous_alpha
                                                        (GtkColorSelection *colorsel);

Returns the previous alpha value.

colorsel : | a GtkColorSelection.
Returns : | an integer between 0 and 65535.

gtk_color_selection_set_previous_alpha ()

void                gtk_color_selection_set_previous_alpha
                                                        (GtkColorSelection *colorsel,
                                                         guint16 alpha);

Sets the 'previous' alpha to be alpha. This function should be called with some hesitations, as it might seem confusing to have that alpha change.

colorsel : | a GtkColorSelection.
alpha : | an integer between 0 and 65535.

gtk_color_selection_get_previous_color ()

void                gtk_color_selection_get_previous_color
                                                        (GtkColorSelection *colorsel,
                                                         GdkColor *color);

Fills color in with the original color value.

colorsel : | a GtkColorSelection.
color : | a GdkColor to fill in with the original color value.

gtk_color_selection_set_previous_color ()

void                gtk_color_selection_set_previous_color
                                                        (GtkColorSelection *colorsel,
                                                         const GdkColor *color);

Sets the 'previous' color to be color. This function should be called with some hesitations, as it might seem confusing to have that color change. Calling gtk_color_selection_set_current_color() will also set this color the first time it is called.

colorsel : | a GtkColorSelection.
color : | a GdkColor to set the previous color with.

gtk_color_selection_is_adjusting ()

gboolean            gtk_color_selection_is_adjusting    (GtkColorSelection *colorsel);

Gets the current state of the colorsel.

colorsel : | a GtkColorSelection.
Returns : | TRUE if the user is currently dragging a color around, and FALSE if the selection has stopped.

gtk_color_selection_palette_from_string ()

gboolean            gtk_color_selection_palette_from_string
                                                        (const gchar *str,
                                                         GdkColor **colors,
                                                         gint *n_colors);

Parses a color palette string; the string is a colon-separated list of color names readable by gdk_color_parse().

str : | a string encoding a color palette.
colors : | return location for allocated array of GdkColor.
n_colors : | return location for length of array.
Returns : | TRUE if a palette was successfully parsed.

gtk_color_selection_palette_to_string ()

gchar*              gtk_color_selection_palette_to_string
                                                        (const GdkColor *colors,
                                                         gint n_colors);

Encodes a palette as a string, useful for persistent storage.

colors : | an array of colors.
n_colors : | length of the array.
Returns : | allocated string encoding the palette.

gtk_color_selection_set_change_palette_hook ()

GtkColorSelectionChangePaletteFunc gtk_color_selection_set_change_palette_hook
                                                        (GtkColorSelectionChangePaletteFunc func);

Warning

gtk_color_selection_set_change_palette_hook is deprecated and should not be used in newly-written code. This function is deprecated in favor of gtk_color_selection_set_change_palette_with_screen_hook(), and does not work in multihead environments.

Installs a global function to be called whenever the user tries to modify the palette in a color selection. This function should save the new palette contents, and update the GtkSettings property "gtk-color-palette" so all GtkColorSelection widgets will be modified.

func : | a function to call when the custom palette needs saving.
Returns : | the previous change palette hook (that was replaced).

GtkColorSelectionChangePaletteFunc ()

void                (*GtkColorSelectionChangePaletteFunc)
                                                        (const GdkColor *colors,
                                                         gint n_colors);

colors :
n_colors :

gtk_color_selection_set_change_palette_with_screen_hook ()

GtkColorSelectionChangePaletteWithScreenFunc gtk_color_selection_set_change_palette_with_screen_hook
                                                        (GtkColorSelectionChangePaletteWithScreenFunc func);

Installs a global function to be called whenever the user tries to modify the palette in a color selection. This function should save the new palette contents, and update the GtkSettings property "gtk-color-palette" so all GtkColorSelection widgets will be modified.

func : | a function to call when the custom palette needs saving.
Returns : | the previous change palette hook (that was replaced).

Since 2.2

GtkColorSelectionChangePaletteWithScreenFunc ()

void                (*GtkColorSelectionChangePaletteWithScreenFunc)
                                                        (GdkScreen *screen,
                                                         const GdkColor *colors,
                                                         gint n_colors);

screen :
colors :
n_colors :

Since 2.2

gtk_color_selection_set_color ()

void                gtk_color_selection_set_color       (GtkColorSelection *colorsel,
                                                         gdouble *color);

Warning

gtk_color_selection_set_color is deprecated and should not be used in newly-written code. Use gtk_color_selection_set_current_color() instead.

Sets the current color to be color. The first time this is called, it will also set the original color to be color too.

colorsel : | a GtkColorSelection.
color : | an array of 4 doubles specifying the red, green, blue and opacity to set the current color to.

gtk_color_selection_get_color ()

void                gtk_color_selection_get_color       (GtkColorSelection *colorsel,
                                                         gdouble *color);

Warning

gtk_color_selection_get_color is deprecated and should not be used in newly-written code.

Sets color to be the current color in the GtkColorSelection widget.

This function is deprecated, use gtk_color_selection_get_current_color() instead.

colorsel : | a GtkColorSelection.
color : | an array of 4 gdouble to fill in with the current color.

Property Details

The "current-alpha" property

  "current-alpha"            guint                 : Read / Write

The current opacity value (0 fully transparent, 65535 fully opaque).

Allowed values: <= 65535

Default value: 65535

The "current-color" property

  "current-color"            GdkColor              : Read / Write

The current color.

The "has-opacity-control" property

  "has-opacity-control"      gboolean              : Read / Write

Whether the color selector should allow setting opacity.

Default value: FALSE

The "has-palette" property

  "has-palette"              gboolean              : Read / Write

Whether a palette should be used.

Default value: FALSE

Signal Details

The "color-changed" signal

void                user_function                      (GtkColorSelection *colorselection,
                                                        gpointer           user_data)           : Run First

This signal is emitted when the color changes in the GtkColorSelection according to its update policy.

colorselection : | the object which received the signal.
user_data : | user data set when the signal handler was connected.


GtkColorSelectionDialog

GtkColorSelectionDialog — A standard dialog box for selecting a color

Synopsis

#include <gtk/gtk.h>

                    GtkColorSelectionDialog;
GtkWidget*          gtk_color_selection_dialog_new      (const gchar *title);

Object Hierarchy

  GObject
   +----GInitiallyUnowned
         +----GtkObject
               +----GtkWidget
                     +----GtkContainer
                           +----GtkBin
                                 +----GtkWindow
                                       +----GtkDialog
                                             +----GtkColorSelectionDialog

Implemented Interfaces

GtkColorSelectionDialog implements AtkImplementorIface.

Description

The GtkColorSelectionDialog provides a standard dialog which allows the user to select a color much like the GtkFileSelection provides a standard dialog for file selection.

Details

GtkColorSelectionDialog

typedef struct _GtkColorSelectionDialog GtkColorSelectionDialog;

The GtkColorSelectionDialog struct contains the following fields. (These fields should be considered read-only. They should never be set by an application.)

GtkWidget *colorsel; | The GtkColorSelection widget contained within the dialog. Use this widget and its gtk_color_selection_get_current_color() function to gain access to the selected color. Connect a handler for this widget's color_changed signal to be notified when the color changes.
GtkWidget *ok_button; | The OK button widget contained within the dialog. Connect a handler for the clicked event.
GtkWidget *cancel_button; | The cancel button widget contained within the dialog. Connect a handler for the clicked event.
GtkWidget *help_button; | The help button widget contained within the dialog. Connect a handler for the clicked event.

gtk_color_selection_dialog_new ()

GtkWidget*          gtk_color_selection_dialog_new      (const gchar *title);

Creates a new GtkColorSelectionDialog.

title : | a string containing the title text for the dialog.
Returns : | a GtkColorSelectionDialog.


GtkCombo

GtkCombo — A text entry field with a dropdown list

Synopsis

#include <gtk/gtk.h>

                    GtkCombo;
GtkWidget*          gtk_combo_new                       (void);
void                gtk_combo_set_popdown_strings       (GtkCombo *combo,
                                                         GList *strings);
void                gtk_combo_set_value_in_list         (GtkCombo *combo,
                                                         gboolean val,
                                                         gboolean ok_if_empty);
void                gtk_combo_set_use_arrows            (GtkCombo *combo,
                                                         gboolean val);
void                gtk_combo_set_use_arrows_always     (GtkCombo *combo,
                                                         gboolean val);
void                gtk_combo_set_case_sensitive        (GtkCombo *combo,
                                                         gboolean val);
void                gtk_combo_set_item_string           (GtkCombo *combo,
                                                         GtkItem *item,
                                                         const gchar *item_value);
void                gtk_combo_disable_activate          (GtkCombo *combo);

Object Hierarchy

  GObject
   +----GInitiallyUnowned
         +----GtkObject
               +----GtkWidget
                     +----GtkContainer
                           +----GtkBox
                                 +----GtkHBox
                                       +----GtkCombo

Implemented Interfaces

GtkCombo implements AtkImplementorIface.

Properties

  "allow-empty"              gboolean              : Read / Write
  "case-sensitive"           gboolean              : Read / Write
  "enable-arrow-keys"        gboolean              : Read / Write
  "enable-arrows-always"     gboolean              : Read / Write
  "value-in-list"            gboolean              : Read / Write

Description

The GtkCombo widget consists of a single-line text entry field and a drop-down list. The drop-down list is displayed when the user clicks on a small arrow button to the right of the entry field.

The drop-down list is a GtkList widget and can be accessed using the list member of the GtkCombo. List elements can contain arbitrary widgets, but if an element is not a plain label, then you must use the gtk_list_set_item_string() function. This sets the string which will be placed in the text entry field when the item is selected.

By default, the user can step through the items in the list using the arrow (cursor) keys, though this behaviour can be turned off with gtk_combo_set_use_arrows().

As of GTK+ 2.4, GtkCombo has been deprecated in favor of GtkComboBox.

Example 38. Creating a GtkCombo widget with simple text items.

  GtkWidget *combo;
  GList *items = NULL;

  items = g_list_append (items, "First Item");
  items = g_list_append (items, "Second Item");
  items = g_list_append (items, "Third Item");
  items = g_list_append (items, "Fourth Item");
  items = g_list_append (items, "Fifth Item");

  combo = gtk_combo_new ();
  gtk_combo_set_popdown_strings (GTK_COMBO (combo), items);

Example 39. Creating a GtkCombo widget with a complex item.

  GtkWidget *combo, *item, *hbox, *arrow, *label;

  combo = gtk_combo_new ();

  item = gtk_list_item_new ();
  gtk_widget_show (item);

  /* You can put almost anything into the GtkListItem widget. Here we will use
     a horizontal box with an arrow and a label in it. */
  hbox = gtk_hbox_new (FALSE, 3);
  gtk_container_add (GTK_CONTAINER (item), hbox);
  gtk_widget_show (hbox);

  arrow = gtk_arrow_new (GTK_ARROW_RIGHT, GTK_SHADOW_OUT);
  gtk_widget_show (arrow);
  gtk_box_pack_start (GTK_BOX (hbox), arrow, FALSE, FALSE, 0);

  label = gtk_label_new ("First Item");
  gtk_widget_show (label);
  gtk_box_pack_start (GTK_BOX (hbox), label, FALSE, FALSE, 0);

  /* You must set the string to display in the entry field when the item is
     selected. */
  gtk_combo_set_item_string (GTK_COMBO (combo), GTK_ITEM (item), "1st Item");

  /* Now we simply add the item to the combo's list. */
  gtk_container_add (GTK_CONTAINER (GTK_COMBO (combo)->list), item);

Details

GtkCombo

typedef struct {
    GtkWidget *entry;

    GtkWidget *list;
} GtkCombo;

Warning

GtkCombo has been deprecated since version 2.4 and should not be used in newly-written code. Use GtkComboBox instead.

The GtkFixedChild struct contains the following fields. (These fields should be considered read-only. They should never be set by an application.)

GtkWidget *entry; | the text entry field.
GtkWidget *list; | the list shown in the drop-down window.

gtk_combo_new ()

GtkWidget*          gtk_combo_new                       (void);

Warning

gtk_combo_new has been deprecated since version 2.4 and should not be used in newly-written code. Use GtkComboBox instead.

Creates a new GtkCombo.

Returns : a new GtkCombo.

gtk_combo_set_popdown_strings ()

void                gtk_combo_set_popdown_strings       (GtkCombo *combo,
                                                         GList *strings);

Warning

gtk_combo_set_popdown_strings has been deprecated since version 2.4 and should not be used in newly-written code. Use GtkComboBox instead.

Convenience function to set all of the items in the popup list. (See the example above.)

combo : | a GtkCombo.
strings : | a list of strings, or NULL to clear the popup list

gtk_combo_set_value_in_list ()

void                gtk_combo_set_value_in_list         (GtkCombo *combo,
                                                         gboolean val,
                                                         gboolean ok_if_empty);

Warning

gtk_combo_set_value_in_list has been deprecated since version 2.4 and should not be used in newly-written code. Use GtkComboBox instead.

Specifies whether the value entered in the text entry field must match one of the values in the list. If this is set then the user will not be able to perform any other action until a valid value has been entered.

If an empty field is acceptable, the ok_if_empty parameter should be TRUE.

combo : | a GtkCombo.
val : | TRUE if the value entered must match one of the values in the list.
ok_if_empty : | TRUE if an empty value is considered valid.

gtk_combo_set_use_arrows ()

void                gtk_combo_set_use_arrows            (GtkCombo *combo,
                                                         gboolean val);

Warning

gtk_combo_set_use_arrows has been deprecated since version 2.4 and should not be used in newly-written code. Use GtkComboBox instead.

Specifies if the arrow (cursor) keys can be used to step through the items in the list. This is on by default.

combo : | a GtkCombo.
val : | TRUE if the arrow keys can be used to step through the items in the list.

gtk_combo_set_use_arrows_always ()

void                gtk_combo_set_use_arrows_always     (GtkCombo *combo,
                                                         gboolean val);

Warning

gtk_combo_set_use_arrows_always has been deprecated since version 2.4 and should not be used in newly-written code. Use GtkComboBox instead.

Obsolete function, does nothing.

combo : | a GtkCombo.
val : | unused

gtk_combo_set_case_sensitive ()

void                gtk_combo_set_case_sensitive        (GtkCombo *combo,
                                                         gboolean val);

Warning

gtk_combo_set_case_sensitive has been deprecated since version 2.4 and should not be used in newly-written code. Use GtkComboBox instead.

Specifies whether the text entered into the GtkEntry field and the text in the list items is case sensitive.

This may be useful, for example, when you have called gtk_combo_set_value_in_list() to limit the values entered, but you are not worried about differences in case.

combo : | a GtkCombo.
val : | TRUE if the text in the list items is case sensitive.

gtk_combo_set_item_string ()

void                gtk_combo_set_item_string           (GtkCombo *combo,
                                                         GtkItem *item,
                                                         const gchar *item_value);

Warning

gtk_combo_set_item_string has been deprecated since version 2.4 and should not be used in newly-written code. Use GtkComboBox instead.

Sets the string to place in the GtkEntry field when a particular list item is selected. This is needed if the list item is not a simple label.

combo : | a GtkCombo.
item : | a GtkItem.
item_value : | the string to place in the GtkEntry when item is selected.

gtk_combo_disable_activate ()

void                gtk_combo_disable_activate          (GtkCombo *combo);

Warning

gtk_combo_disable_activate has been deprecated since version 2.4 and should not be used in newly-written code. Use GtkComboBox instead.

Stops the GtkCombo widget from showing the popup list when the GtkEntry emits the "activate" signal, i.e. when the Return key is pressed. This may be useful if, for example, you want the Return key to close a dialog instead.

combo : a GtkCombo.

Property Details

The "allow-empty" property

  "allow-empty"              gboolean              : Read / Write

Whether an empty value may be entered in this field.

Default value: TRUE

The "case-sensitive" property

  "case-sensitive"           gboolean              : Read / Write

Whether list item matching is case sensitive.

Default value: FALSE

The "enable-arrow-keys" property

  "enable-arrow-keys"        gboolean              : Read / Write

Whether the arrow keys move through the list of items.

Default value: TRUE

The "enable-arrows-always" property

  "enable-arrows-always"     gboolean              : Read / Write

Obsolete property, ignored.

Default value: TRUE

The "value-in-list" property

  "value-in-list"            gboolean              : Read / Write

Whether entered values must already be present in the list.

Default value: FALSE


GtkComboBox

GtkComboBox — A widget used to choose from a list of items

Synopsis

#include <gtk/gtk.h>

                    GtkComboBox;
GtkWidget*          gtk_combo_box_new                   (void);
GtkWidget*          gtk_combo_box_new_with_model        (GtkTreeModel *model);
gint                gtk_combo_box_get_wrap_width        (GtkComboBox *combo_box);
void                gtk_combo_box_set_wrap_width        (GtkComboBox *combo_box,
                                                         gint width);
gint                gtk_combo_box_get_row_span_column   (GtkComboBox *combo_box);
void                gtk_combo_box_set_row_span_column   (GtkComboBox *combo_box,
                                                         gint row_span);
gint                gtk_combo_box_get_column_span_column
                                                        (GtkComboBox *combo_box);
void                gtk_combo_box_set_column_span_column
                                                        (GtkComboBox *combo_box,
                                                         gint column_span);
gint                gtk_combo_box_get_active            (GtkComboBox *combo_box);
void                gtk_combo_box_set_active            (GtkComboBox *combo_box,
                                                         gint index_);
gboolean            gtk_combo_box_get_active_iter       (GtkComboBox *combo_box,
                                                         GtkTreeIter *iter);
void                gtk_combo_box_set_active_iter       (GtkComboBox *combo_box,
                                                         GtkTreeIter *iter);
GtkTreeModel*       gtk_combo_box_get_model             (GtkComboBox *combo_box);
void                gtk_combo_box_set_model             (GtkComboBox *combo_box,
                                                         GtkTreeModel *model);
GtkWidget*          gtk_combo_box_new_text              (void);
void                gtk_combo_box_append_text           (GtkComboBox *combo_box,
                                                         const gchar *text);
void                gtk_combo_box_insert_text           (GtkComboBox *combo_box,
                                                         gint position,
                                                         const gchar *text);
void                gtk_combo_box_prepend_text          (GtkComboBox *combo_box,
                                                         const gchar *text);
void                gtk_combo_box_remove_text           (GtkComboBox *combo_box,
                                                         gint position);
gchar*              gtk_combo_box_get_active_text       (GtkComboBox *combo_box);
void                gtk_combo_box_popup                 (GtkComboBox *combo_box);
void                gtk_combo_box_popdown               (GtkComboBox *combo_box);
AtkObject*          gtk_combo_box_get_popup_accessible  (GtkComboBox *combo_box);
GtkTreeViewRowSeparatorFunc gtk_combo_box_get_row_separator_func
                                                        (GtkComboBox *combo_box);
void                gtk_combo_box_set_row_separator_func
                                                        (GtkComboBox *combo_box,
                                                         GtkTreeViewRowSeparatorFunc func,
                                                         gpointer data,
                                                         GtkDestroyNotify destroy);
void                gtk_combo_box_set_add_tearoffs      (GtkComboBox *combo_box,
                                                         gboolean add_tearoffs);
gboolean            gtk_combo_box_get_add_tearoffs      (GtkComboBox *combo_box);
void                gtk_combo_box_set_title             (GtkComboBox *combo_box,
                                                         const gchar *title);
const gchar*        gtk_combo_box_get_title             (GtkComboBox *combo_box);
void                gtk_combo_box_set_focus_on_click    (GtkComboBox *combo,
                                                         gboolean focus_on_click);
gboolean            gtk_combo_box_get_focus_on_click    (GtkComboBox *combo);

Object Hierarchy

  GObject
   +----GInitiallyUnowned
         +----GtkObject
               +----GtkWidget
                     +----GtkContainer
                           +----GtkBin
                                 +----GtkComboBox
                                       +----GtkComboBoxEntry

Implemented Interfaces

GtkComboBox implements AtkImplementorIface, GtkCellEditable and GtkCellLayout.

Properties

  "active"                   gint                  : Read / Write
  "add-tearoffs"             gboolean              : Read / Write
  "column-span-column"       gint                  : Read / Write
  "focus-on-click"           gboolean              : Read / Write
  "has-frame"                gboolean              : Read / Write
  "model"                    GtkTreeModel          : Read / Write
  "popup-shown"              gboolean              : Read
  "row-span-column"          gint                  : Read / Write
  "tearoff-title"            gchararray            : Read / Write
  "wrap-width"               gint                  : Read / Write

Style Properties

  "appears-as-list"          gboolean              : Read

Signals

  "changed"                                        : Run Last

Description

A GtkComboBox is a widget that allows the user to choose from a list of valid choices. The GtkComboBox displays the selected choice. When activated, the GtkComboBox displays a popup which allows the user to make a new choice. The style in which the selected value is displayed, and the style of the popup is determined by the current theme. It may be similar to a GtkOptionMenu, or similar to a Windows-style combo box.

Unlike its predecessors GtkCombo and GtkOptionMenu, the GtkComboBox uses the model-view pattern; the list of valid choices is specified in the form of a tree model, and the display of the choices can be adapted to the data in the model by using cell renderers, as you would in a tree view. This is possible since GtkComboBox implements the GtkCellLayout interface. The tree model holding the valid choices is not restricted to a flat list, it can be a real tree, and the popup will reflect the tree structure.

In addition to the model-view API, GtkComboBox offers a simple API which is suitable for text-only combo boxes, and hides the complexity of managing the data in a model. It consists of the functions gtk_combo_box_new_text(), gtk_combo_box_append_text(), gtk_combo_box_insert_text(), gtk_combo_box_prepend_text(), gtk_combo_box_remove_text() and gtk_combo_box_get_active_text().

Details

GtkComboBox

typedef struct _GtkComboBox GtkComboBox;

gtk_combo_box_new ()

GtkWidget*          gtk_combo_box_new                   (void);

Creates a new empty GtkComboBox.

Returns : A new GtkComboBox.

Since 2.4

gtk_combo_box_new_with_model ()

GtkWidget*          gtk_combo_box_new_with_model        (GtkTreeModel *model);

Creates a new GtkComboBox with the model initialized to model.

model : | A GtkTreeModel.
Returns : | A new GtkComboBox.

Since 2.4

gtk_combo_box_get_wrap_width ()

gint                gtk_combo_box_get_wrap_width        (GtkComboBox *combo_box);

Returns the wrap width which is used to determine the number of columns for the popup menu. If the wrap width is larger than 1, the combo box is in table mode.

combo_box : | A GtkComboBox.
Returns : | the wrap width.

Since 2.6

gtk_combo_box_set_wrap_width ()

void                gtk_combo_box_set_wrap_width        (GtkComboBox *combo_box,
                                                         gint width);

Sets the wrap width of combo_box to be width. The wrap width is basically the preferred number of columns when you want the popup to be layed out in a table.

combo_box : | A GtkComboBox.
width : | Preferred number of columns.

Since 2.4

gtk_combo_box_get_row_span_column ()

gint                gtk_combo_box_get_row_span_column   (GtkComboBox *combo_box);

Returns the column with row span information for combo_box.

combo_box : | A GtkComboBox.
Returns : | the row span column.

Since 2.6

gtk_combo_box_set_row_span_column ()

void                gtk_combo_box_set_row_span_column   (GtkComboBox *combo_box,
                                                         gint row_span);

Sets the column with row span information for combo_box to be row_span. The row span column contains integers which indicate how many rows an item should span.

combo_box : | A GtkComboBox.
row_span : | A column in the model passed during construction.

Since 2.4

gtk_combo_box_get_column_span_column ()

gint                gtk_combo_box_get_column_span_column
                                                        (GtkComboBox *combo_box);

Returns the column with column span information for combo_box.

combo_box : | A GtkComboBox.
Returns : | the column span column.

Since 2.6

gtk_combo_box_set_column_span_column ()

void                gtk_combo_box_set_column_span_column
                                                        (GtkComboBox *combo_box,
                                                         gint column_span);

Sets the column with column span information for combo_box to be column_span. The column span column contains integers which indicate how many columns an item should span.

combo_box : | A GtkComboBox.
column_span : | A column in the model passed during construction.

Since 2.4

gtk_combo_box_get_active ()

gint                gtk_combo_box_get_active            (GtkComboBox *combo_box);

Returns the index of the currently active item, or -1 if there's no active item. If the model is a non-flat treemodel, and the active item is not an immediate child of the root of the tree, this function returns gtk_tree_path_get_indices (path)[0], where path is the GtkTreePath of the active item.

combo_box : | A GtkComboBox.
Returns : | An integer which is the index of the currently active item, or -1 if there's no active item.

Since 2.4

gtk_combo_box_set_active ()

void                gtk_combo_box_set_active            (GtkComboBox *combo_box,
                                                         gint index_);

Sets the active item of combo_box to be the item at index.

combo_box : | A GtkComboBox.
index_ : | An index in the model passed during construction, or -1 to have no active item.

Since 2.4

gtk_combo_box_get_active_iter ()

gboolean            gtk_combo_box_get_active_iter       (GtkComboBox *combo_box,
                                                         GtkTreeIter *iter);

Sets iter to point to the current active item, if it exists.

combo_box : | A GtkComboBox
iter : | The uninitialized GtkTreeIter.
Returns : | TRUE, if iter was set

Since 2.4

gtk_combo_box_set_active_iter ()

void                gtk_combo_box_set_active_iter       (GtkComboBox *combo_box,
                                                         GtkTreeIter *iter);

Sets the current active item to be the one referenced by iter. iter must correspond to a path of depth one.

combo_box : | A GtkComboBox
iter : | The GtkTreeIter.

Since 2.4

gtk_combo_box_get_model ()

GtkTreeModel*       gtk_combo_box_get_model             (GtkComboBox *combo_box);

Returns the GtkTreeModel which is acting as data source for combo_box.

combo_box : | A GtkComboBox.
Returns : | A GtkTreeModel which was passed during construction.

Since 2.4

gtk_combo_box_set_model ()

void                gtk_combo_box_set_model             (GtkComboBox *combo_box,
                                                         GtkTreeModel *model);

Sets the model used by combo_box to be model. Will unset a previously set model (if applicable). If model is NULL, then it will unset the model.

Note that this function does not clear the cell renderers, you have to call gtk_combo_box_cell_layout_clear() yourself if you need to set up different cell renderers for the new model.

combo_box : | A GtkComboBox.
model : | A GtkTreeModel.

Since 2.4

gtk_combo_box_new_text ()

GtkWidget*          gtk_combo_box_new_text              (void);

Convenience function which constructs a new text combo box, which is a GtkComboBox just displaying strings. If you use this function to create a text combo box, you should only manipulate its data source with the following convenience functions: gtk_combo_box_append_text(), gtk_combo_box_insert_text(), gtk_combo_box_prepend_text() and gtk_combo_box_remove_text().

Returns : A new text combo box.

Since 2.4

gtk_combo_box_append_text ()

void                gtk_combo_box_append_text           (GtkComboBox *combo_box,
                                                         const gchar *text);

Appends string to the list of strings stored in combo_box. Note that you can only use this function with combo boxes constructed with gtk_combo_box_new_text().

combo_box : | A GtkComboBox constructed using gtk_combo_box_new_text().
text : | A string.

Since 2.4

gtk_combo_box_insert_text ()

void                gtk_combo_box_insert_text           (GtkComboBox *combo_box,
                                                         gint position,
                                                         const gchar *text);

Inserts string at position in the list of strings stored in combo_box. Note that you can only use this function with combo boxes constructed with gtk_combo_box_new_text().

combo_box : | A GtkComboBox constructed using gtk_combo_box_new_text().
position : | An index to insert text.
text : | A string.

Since 2.4

gtk_combo_box_prepend_text ()

void                gtk_combo_box_prepend_text          (GtkComboBox *combo_box,
                                                         const gchar *text);

Prepends string to the list of strings stored in combo_box. Note that you can only use this function with combo boxes constructed with gtk_combo_box_new_text().

combo_box : | A GtkComboBox constructed with gtk_combo_box_new_text().
text : | A string.

Since 2.4

gtk_combo_box_remove_text ()

void                gtk_combo_box_remove_text           (GtkComboBox *combo_box,
                                                         gint position);

Removes the string at position from combo_box. Note that you can only use this function with combo boxes constructed with gtk_combo_box_new_text().

combo_box : | A GtkComboBox constructed with gtk_combo_box_new_text().
position : | Index of the item to remove.

Since 2.4

gtk_combo_box_get_active_text ()

gchar*              gtk_combo_box_get_active_text       (GtkComboBox *combo_box);

Returns the currently active string in combo_box or NULL if none is selected. Note that you can only use this function with combo boxes constructed with gtk_combo_box_new_text() and with GtkComboBoxEntrys.

combo_box : | A GtkComboBox constructed with gtk_combo_box_new_text().
Returns : | a newly allocated string containing the currently active text.

Since 2.6

gtk_combo_box_popup ()

void                gtk_combo_box_popup                 (GtkComboBox *combo_box);

Pops up the menu or dropdown list of combo_box.

This function is mostly intended for use by accessibility technologies; applications should have little use for it.

combo_box : a GtkComboBox

Since 2.4

gtk_combo_box_popdown ()

void                gtk_combo_box_popdown               (GtkComboBox *combo_box);

Hides the menu or dropdown list of combo_box.

This function is mostly intended for use by accessibility technologies; applications should have little use for it.

combo_box : a GtkComboBox

Since 2.4

gtk_combo_box_get_popup_accessible ()

AtkObject*          gtk_combo_box_get_popup_accessible  (GtkComboBox *combo_box);

Gets the accessible object corresponding to the combo box's popup.

This function is mostly intended for use by accessibility technologies; applications should have little use for it.

combo_box : | a GtkComboBox
Returns : | the accessible object corresponding to the combo box's popup.

Since 2.6

gtk_combo_box_get_row_separator_func ()

GtkTreeViewRowSeparatorFunc gtk_combo_box_get_row_separator_func
                                                        (GtkComboBox *combo_box);

Returns the current row separator function.

combo_box : | a GtkComboBox
Returns : | the current row separator function.

Since 2.6

gtk_combo_box_set_row_separator_func ()

void                gtk_combo_box_set_row_separator_func
                                                        (GtkComboBox *combo_box,
                                                         GtkTreeViewRowSeparatorFunc func,
                                                         gpointer data,
                                                         GtkDestroyNotify destroy);

Sets the row separator function, which is used to determine whether a row should be drawn as a separator. If the row separator function is NULL, no separators are drawn. This is the default value.

combo_box : | a GtkComboBox
func : | a GtkTreeViewRowSeparatorFunc
data : | user data to pass to func, or NULL
destroy : | destroy notifier for data, or NULL

Since 2.6

gtk_combo_box_set_add_tearoffs ()

void                gtk_combo_box_set_add_tearoffs      (GtkComboBox *combo_box,
                                                         gboolean add_tearoffs);

Sets whether the popup menu should have a tearoff menu item.

combo_box : | a GtkComboBox
add_tearoffs : | TRUE to add tearoff menu items

Since 2.6

gtk_combo_box_get_add_tearoffs ()

gboolean            gtk_combo_box_get_add_tearoffs      (GtkComboBox *combo_box);

Gets the current value of the :add-tearoffs property.

combo_box : | a GtkComboBox
Returns : | the current value of the :add-tearoffs property.

gtk_combo_box_set_title ()

void                gtk_combo_box_set_title             (GtkComboBox *combo_box,
                                                         const gchar *title);

Sets the menu's title in tearoff mode.

combo_box : | a GtkComboBox
title : | a title for the menu in tearoff mode.

Since 2.10

gtk_combo_box_get_title ()

const gchar*        gtk_combo_box_get_title             (GtkComboBox *combo_box);

Gets the current title of the menu in tearoff mode. See gtk_combo_box_set_add_tearoffs().

combo_box : | a GtkComboBox
Returns : | the menu's title in tearoff mode. This is an internal copy of the string which must not be freed.

Since 2.10

gtk_combo_box_set_focus_on_click ()

void                gtk_combo_box_set_focus_on_click    (GtkComboBox *combo,
                                                         gboolean focus_on_click);

Sets whether the combo box will grab focus when it is clicked with the mouse. Making mouse clicks not grab focus is useful in places like toolbars where you don't want the keyboard focus removed from the main area of the application.

combo : | a GtkComboBox
focus_on_click : | whether the combo box grabs focus when clicked with the mouse

Since 2.6

gtk_combo_box_get_focus_on_click ()

gboolean            gtk_combo_box_get_focus_on_click    (GtkComboBox *combo);

Returns whether the combo box grabs focus when it is clicked with the mouse. See gtk_combo_box_set_focus_on_click().

combo : | a GtkComboBox
Returns : | TRUE if the combo box grabs focus when it is clicked with the mouse.

Since 2.6

Property Details

The "active" property

  "active"                   gint                  : Read / Write

The item which is currently active. If the model is a non-flat treemodel, and the active item is not an immediate child of the root of the tree, this property has the value gtk_tree_path_get_indices (path)[0], where path is the GtkTreePath of the active item.

Allowed values: >= -1

Default value: -1

Since 2.4

The "add-tearoffs" property

  "add-tearoffs"             gboolean              : Read / Write

The add-tearoffs property controls whether generated menus have tearoff menu items.

Note that this only affects menu style combo boxes.

Default value: FALSE

Since 2.6

The "column-span-column" property

  "column-span-column"       gint                  : Read / Write

If this is set to a non-negative value, it must be the index of a column of type G_TYPE_INT in the model.

The values of that column are used to determine how many columns a value in the list will span.

Allowed values: >= -1

Default value: -1

Since 2.4

The "focus-on-click" property

  "focus-on-click"           gboolean              : Read / Write

Whether the combo box grabs focus when it is clicked with the mouse.

Default value: TRUE

The "has-frame" property

  "has-frame"                gboolean              : Read / Write

The has-frame property controls whether a frame is drawn around the entry.

Default value: TRUE

Since 2.6

The "model" property

  "model"                    GtkTreeModel          : Read / Write

The model from which the combo box takes the values shown in the list.

Since 2.4

The "popup-shown" property

  "popup-shown"              gboolean              : Read

Whether the combo boxes dropdown is popped up. Note that this property is mainly useful, because it allows you to connect to notify::popup-shown.

Default value: FALSE

Since 2.10

The "row-span-column" property

  "row-span-column"          gint                  : Read / Write

If this is set to a non-negative value, it must be the index of a column of type G_TYPE_INT in the model.

The values of that column are used to determine how many rows a value in the list will span. Therefore, the values in the model column pointed to by this property must be greater than zero and not larger than wrap-width.

Allowed values: >= -1

Default value: -1

Since 2.4

The "tearoff-title" property

  "tearoff-title"            gchararray            : Read / Write

A title that may be displayed by the window manager when the popup is torn-off.

Default value: ""

Since 2.10

The "wrap-width" property

  "wrap-width"               gint                  : Read / Write

If wrap-width is set to a positive value, the list will be displayed in multiple columns, the number of columns is determined by wrap-width.

Allowed values: >= 0

Default value: 0

Since 2.4

Style Property Details

The "appears-as-list" style property

  "appears-as-list"          gboolean              : Read

Whether dropdowns should look like lists rather than menus.

Default value: FALSE

Signal Details

The "changed" signal

void                user_function                      (GtkComboBox *widget,
                                                        gpointer     user_data)      : Run Last

The changed signal is emitted when the active item is changed. The can be due to the user selecting a different item from the list, or due to a call to gtk_combo_box_set_active_iter(). It will also be emitted while typing into a GtkComboBoxEntry, as well as when selecting an item from the GtkComboBoxEntry's list.

widget : | the object which received the signal
user_data : | user data set when the signal handler was connected.

Since 2.4

See Also

GtkComboBoxEntry, GtkTreeModel, GtkCellRenderer


GtkComboBoxEntry

GtkComboBoxEntry — A text entry field with a dropdown list

Synopsis

#include <gtk/gtk.h>

                    GtkComboBoxEntry;
GtkWidget*          gtk_combo_box_entry_new             (void);
GtkWidget*          gtk_combo_box_entry_new_with_model  (GtkTreeModel *model,
                                                         gint text_column);
GtkWidget*          gtk_combo_box_entry_new_text        (void);
void                gtk_combo_box_entry_set_text_column (GtkComboBoxEntry *entry_box,
                                                         gint text_column);
gint                gtk_combo_box_entry_get_text_column (GtkComboBoxEntry *entry_box);

Object Hierarchy

  GObject
   +----GInitiallyUnowned
         +----GtkObject
               +----GtkWidget
                     +----GtkContainer
                           +----GtkBin
                                 +----GtkComboBox
                                       +----GtkComboBoxEntry

Implemented Interfaces

GtkComboBoxEntry implements AtkImplementorIface, GtkCellEditable and GtkCellLayout.

Properties

  "text-column"              gint                  : Read / Write

Description

A GtkComboBoxEntry is a widget that allows the user to choose from a list of valid choices or enter a different value. It is very similar to a GtkComboBox, but it displays the selected value in an entry to allow modifying it.

In contrast to a GtkComboBox, the underlying model of a GtkComboBoxEntry must always have a text column (see gtk_combo_box_entry_set_text_column()), and the entry will show the content of the text column in the selected row. To get the text from the entry, use gtk_combo_box_get_active_text().

The changed signal will be emitted while typing into a GtkComboBoxEntry, as well as when selecting an item from the GtkComboBoxEntry's list. Use gtk_combo_box_get_active() or gtk_combo_box_get_active_iter() to discover whether an item was actually selected from the list.

Connect to the activate signal of the GtkEntry (use gtk_bin_get_child()) to detect when the user actually finishes entering text.

The convenience API to construct simple text-only GtkComboBoxes can also be used with GtkComboBoxEntrys which have been constructed with gtk_combo_box_entry_new_text().

Details

GtkComboBoxEntry

typedef struct _GtkComboBoxEntry GtkComboBoxEntry;

gtk_combo_box_entry_new ()

GtkWidget*          gtk_combo_box_entry_new             (void);

Creates a new GtkComboBoxEntry which has a GtkEntry as child. After construction, you should set a model using gtk_combo_box_set_model() and a text_column * using gtk_combo_box_entry_set_text_column().

Returns : A new GtkComboBoxEntry.

Since 2.4

gtk_combo_box_entry_new_with_model ()

GtkWidget*          gtk_combo_box_entry_new_with_model  (GtkTreeModel *model,
                                                         gint text_column);

Creates a new GtkComboBoxEntry which has a GtkEntry as child and a list of strings as popup. You can get the GtkEntry from a GtkComboBoxEntry using GTK_ENTRY (GTK_BIN (combo_box_entry)->child). To add and remove strings from the list, just modify model using its data manipulation API.

model : | A GtkTreeModel.
text_column : | A column in model to get the strings from.
Returns : | A new GtkComboBoxEntry.

Since 2.4

gtk_combo_box_entry_new_text ()

GtkWidget*          gtk_combo_box_entry_new_text        (void);

Convenience function which constructs a new editable text combo box, which is a GtkComboBoxEntry just displaying strings. If you use this function to create a text combo box, you should only manipulate its data source with the following convenience functions: gtk_combo_box_append_text(), gtk_combo_box_insert_text(), gtk_combo_box_prepend_text() and gtk_combo_box_remove_text().

Returns : A new text GtkComboBoxEntry.

Since 2.4

gtk_combo_box_entry_set_text_column ()

void                gtk_combo_box_entry_set_text_column (GtkComboBoxEntry *entry_box,
                                                         gint text_column);

Sets the model column which entry_box should use to get strings from to be text_column.

entry_box : | A GtkComboBoxEntry.
text_column : | A column in model to get the strings from.

Since 2.4

gtk_combo_box_entry_get_text_column ()

gint                gtk_combo_box_entry_get_text_column (GtkComboBoxEntry *entry_box);

Returns the column which entry_box is using to get the strings from.

entry_box : | A GtkComboBoxEntry.
Returns : | A column in the data source model of entry_box.

Since 2.4

Property Details

The "text-column" property

  "text-column"              gint                  : Read / Write

A column in the data source model to get the strings from.

Allowed values: >= -1

Default value: -1

See Also

GtkComboBox


GtkContainer

GtkContainer — Base class for widgets which contain other widgets

Synopsis

#include <gtk/gtk.h>

                    GtkContainer;
#define             GTK_IS_RESIZE_CONTAINER             (widget)
#define             GTK_CONTAINER_WARN_INVALID_CHILD_PROPERTY_ID(object, property_id, pspec)
#define             gtk_container_border_width
void                gtk_container_add                   (GtkContainer *container,
                                                         GtkWidget *widget);
void                gtk_container_remove                (GtkContainer *container,
                                                         GtkWidget *widget);
void                gtk_container_add_with_properties   (GtkContainer *container,
                                                         GtkWidget *widget,
                                                         const gchar *first_prop_name,
                                                         ...);
GtkResizeMode       gtk_container_get_resize_mode       (GtkContainer *container);
void                gtk_container_set_resize_mode       (GtkContainer *container,
                                                         GtkResizeMode resize_mode);
void                gtk_container_check_resize          (GtkContainer *container);
void                gtk_container_foreach               (GtkContainer *container,
                                                         GtkCallback callback,
                                                         gpointer callback_data);
void                gtk_container_foreach_full          (GtkContainer *container,
                                                         GtkCallback callback,
                                                         GtkCallbackMarshal marshal,
                                                         gpointer callback_data,
                                                         GtkDestroyNotify notify);
#define             gtk_container_children
GList*              gtk_container_get_children          (GtkContainer *container);
void                gtk_container_set_reallocate_redraws
                                                        (GtkContainer *container,
                                                         gboolean needs_redraws);
void                gtk_container_set_focus_child       (GtkContainer *container,
                                                         GtkWidget *child);
GtkAdjustment*      gtk_container_get_focus_vadjustment (GtkContainer *container);
void                gtk_container_set_focus_vadjustment (GtkContainer *container,
                                                         GtkAdjustment *adjustment);
GtkAdjustment*      gtk_container_get_focus_hadjustment (GtkContainer *container);
void                gtk_container_set_focus_hadjustment (GtkContainer *container,
                                                         GtkAdjustment *adjustment);
void                gtk_container_resize_children       (GtkContainer *container);
GType               gtk_container_child_type            (GtkContainer *container);
void                gtk_container_child_get             (GtkContainer *container,
                                                         GtkWidget *child,
                                                         const gchar *first_prop_name,
                                                         ...);
void                gtk_container_child_set             (GtkContainer *container,
                                                         GtkWidget *child,
                                                         const gchar *first_prop_name,
                                                         ...);
void                gtk_container_child_get_property    (GtkContainer *container,
                                                         GtkWidget *child,
                                                         const gchar *property_name,
                                                         GValue *value);
void                gtk_container_child_set_property    (GtkContainer *container,
                                                         GtkWidget *child,
                                                         const gchar *property_name,
                                                         const GValue *value);
void                gtk_container_child_get_valist      (GtkContainer *container,
                                                         GtkWidget *child,
                                                         const gchar *first_property_name,
                                                         va_list var_args);
void                gtk_container_child_set_valist      (GtkContainer *container,
                                                         GtkWidget *child,
                                                         const gchar *first_property_name,
                                                         va_list var_args);
void                gtk_container_forall                (GtkContainer *container,
                                                         GtkCallback callback,
                                                         gpointer callback_data);
guint               gtk_container_get_border_width      (GtkContainer *container);
void                gtk_container_set_border_width      (GtkContainer *container,
                                                         guint border_width);
void                gtk_container_propagate_expose      (GtkContainer *container,
                                                         GtkWidget *child,
                                                         GdkEventExpose *event);
gboolean            gtk_container_get_focus_chain       (GtkContainer *container,
                                                         GList **focusable_widgets);
void                gtk_container_set_focus_chain       (GtkContainer *container,
                                                         GList *focusable_widgets);
void                gtk_container_unset_focus_chain     (GtkContainer *container);
GParamSpec*         gtk_container_class_find_child_property
                                                        (GObjectClass *cclass,
                                                         const gchar *property_name);
void                gtk_container_class_install_child_property
                                                        (GtkContainerClass *cclass,
                                                         guint property_id,
                                                         GParamSpec *pspec);
GParamSpec**        gtk_container_class_list_child_properties
                                                        (GObjectClass *cclass,
                                                         guint *n_properties);

Object Hierarchy

  GObject
   +----GInitiallyUnowned
         +----GtkObject
               +----GtkWidget
                     +----GtkContainer
                           +----GtkBin
                           +----GtkBox
                           +----GtkCList
                           +----GtkFixed
                           +----GtkPaned
                           +----GtkIconView
                           +----GtkLayout
                           +----GtkList
                           +----GtkMenuShell
                           +----GtkNotebook
                           +----GtkSocket
                           +----GtkTable
                           +----GtkTextView
                           +----GtkToolbar
                           +----GtkTree
                           +----GtkTreeView

Implemented Interfaces

GtkContainer implements AtkImplementorIface.

Properties

  "border-width"             guint                 : Read / Write
  "child"                    GtkWidget             : Write
  "resize-mode"              GtkResizeMode         : Read / Write

Signals

  "add"                                            : Run First
  "check-resize"                                   : Run Last
  "remove"                                         : Run First
  "set-focus-child"                                : Run First

Description

A GTK+ user interface is constructed by nesting widgets inside widgets. Container widgets are the inner nodes in the resulting tree of widgets: they contain other widgets. So, for example, you might have a GtkWindow containing a GtkFrame containing a GtkLabel. If you wanted an image instead of a textual label inside the frame, you might replace the GtkLabel widget with a GtkImage widget.

There are two major kinds of container widgets in GTK+. Both are subclasses of the abstract GtkContainer base class.

The first type of container widget has a single child widget and derives from GtkBin. These containers are decorators, which add some kind of functionality to the child. For example, a GtkButton makes its child into a clickable button; a GtkFrame draws a frame around its child and a GtkWindow places its child widget inside a top-level window.

The second type of container can have more than one child; its purpose is to manage layout. This means that these containers assign sizes and positions to their children. For example, a GtkHBox arranges its children in a horizontal row, and a GtkTable arranges the widgets it contains in a two-dimensional grid.

To fulfill its task, a layout container must negotiate the size requirements with its parent and its children. This negotiation is carried out in two phases, size requisition and size allocation.

Size Requisition

The size requisition of a widget is it's desired width and height. This is represented by a GtkRequisition.

How a widget determines its desired size depends on the widget. A GtkLabel, for example, requests enough space to display all its text. Container widgets generally base their size request on the requisitions of their children.

The size requisition phase of the widget layout process operates top-down. It starts at a top-level widget, typically a GtkWindow. The top-level widget asks its child for its size requisition by calling gtk_widget_size_request(). To determine its requisition, the child asks its own children for their requisitions and so on. Finally, the top-level widget will get a requisition back from its child.

Size Allocation

When the top-level widget has determined how much space its child would like to have, the second phase of the size negotiation, size allocation, begins. Depending on its configuration (see gtk_window_set_resizable()), the top-level widget may be able to expand in order to satisfy the size request or it may have to ignore the size request and keep its fixed size. It then tells its child widget how much space it gets by calling gtk_widget_size_allocate(). The child widget divides the space among its children and tells each child how much space it got, and so on. Under normal circumstances, a GtkWindow will always give its child the amount of space the child requested.

A child's size allocation is represented by a GtkAllocation. This struct contains not only a width and height, but also a position (i.e. X and Y coordinates), so that containers can tell their children not only how much space they have gotten, but also where they are positioned inside the space available to the container.

Widgets are required to honor the size allocation they receive; a size request is only a request, and widgets must be able to cope with any size.

Child properties

GtkContainer introduces child properties - these are object properties that are not specific to either the container or the contained widget, but rather to their relation. Typical examples of child properties are the position or pack-type of a widget which is contained in a GtkBox.

Use gtk_container_class_install_child_property() to install child properties for a container class and gtk_container_class_find_child_property() or gtk_container_class_list_child_properties() to get information about existing child properties.

To set the value of a child property, use gtk_container_child_set_property(), gtk_container_child_set() or gtk_container_child_set_valist(). To obtain the value of a child property, use gtk_container_child_get_property(), gtk_container_child_get() or gtk_container_child_get_valist(). To emit notification about child property changes, use gtk_widget_child_notify().

Details

GtkContainer

typedef struct _GtkContainer GtkContainer;

GTK_IS_RESIZE_CONTAINER()

#define GTK_IS_RESIZE_CONTAINER(widget) (GTK_IS_CONTAINER (widget) && ((GtkContainer*) (widget))->resize_mode != GTK_RESIZE_PARENT)

widget :

GTK_CONTAINER_WARN_INVALID_CHILD_PROPERTY_ID()

#define             GTK_CONTAINER_WARN_INVALID_CHILD_PROPERTY_ID(object, property_id, pspec)

object :
property_id :
pspec :

gtk_container_border_width

#define	gtk_container_border_width		gtk_container_set_border_width

Warning

gtk_container_border_width is deprecated and should not be used in newly-written code. Use gtk_container_set_border_width() instead.

Does the same as gtk_container_set_border_width().

gtk_container_add ()

void                gtk_container_add                   (GtkContainer *container,
                                                         GtkWidget *widget);

Adds widget to container. Typically used for simple containers such as GtkWindow, GtkFrame, or GtkButton; for more complicated layout containers such as GtkBox or GtkTable, this function will pick default packing parameters that may not be correct. So consider functions such as gtk_box_pack_start() and gtk_table_attach() as an alternative to gtk_container_add() in those cases. A widget may be added to only one container at a time; you can't place the same widget inside two different containers.

container : | a GtkContainer
widget : | a widget to be placed inside container

gtk_container_remove ()

void                gtk_container_remove                (GtkContainer *container,
                                                         GtkWidget *widget);

Removes widget from container. widget must be inside container. Note that container will own a reference to widget, and that this may be the last reference held; so removing a widget from its container can destroy that widget. If you want to use widget again, you need to add a reference to it while it's not inside a container, using g_object_ref(). If you don't want to use widget again it's usually more efficient to simply destroy it directly using gtk_widget_destroy() since this will remove it from the container and help break any circular reference count cycles.

container : | a GtkContainer
widget : | a current child of container

gtk_container_add_with_properties ()

void                gtk_container_add_with_properties   (GtkContainer *container,
                                                         GtkWidget *widget,
                                                         const gchar *first_prop_name,
                                                         ...);

Adds widget to container, setting child properties at the same time. See gtk_container_add() and gtk_container_child_set() for more details.

container : | a GtkContainer
widget : | a widget to be placed inside container
first_prop_name : | the name of the first child property to set
... : | a NULL-terminated list of property names and values, starting with first_prop_name.

gtk_container_get_resize_mode ()

GtkResizeMode       gtk_container_get_resize_mode       (GtkContainer *container);

Returns the resize mode for the container. See gtk_container_set_resize_mode().

container : | a GtkContainer
Returns : | the current resize mode

gtk_container_set_resize_mode ()

void                gtk_container_set_resize_mode       (GtkContainer *container,
                                                         GtkResizeMode resize_mode);

Sets the resize mode for the container.

The resize mode of a container determines whether a resize request will be passed to the container's parent, queued for later execution or executed immediately.

container : | a GtkContainer.
resize_mode : | the new resize mode.

gtk_container_check_resize ()

void                gtk_container_check_resize          (GtkContainer *container);

container :

gtk_container_foreach ()

void                gtk_container_foreach               (GtkContainer *container,
                                                         GtkCallback callback,
                                                         gpointer callback_data);

Invokes callback on each non-internal child of container. See gtk_container_forall() for details on what constitutes an "internal" child. Most applications should use gtk_container_foreach(), rather than gtk_container_forall().

container : | a GtkContainer
callback : | a callback
callback_data : | callback user data

gtk_container_foreach_full ()

void                gtk_container_foreach_full          (GtkContainer *container,
                                                         GtkCallback callback,
                                                         GtkCallbackMarshal marshal,
                                                         gpointer callback_data,
                                                         GtkDestroyNotify notify);

Warning

gtk_container_foreach_full is deprecated and should not be used in newly-written code. Use gtk_container_foreach() instead.

container :
callback :
marshal :
callback_data :
notify :

gtk_container_children

#define gtk_container_children gtk_container_get_children

Warning

gtk_container_children is deprecated and should not be used in newly-written code. Use gtk_container_get_children() instead.

Does the same as gtk_container_get_children().

gtk_container_get_children ()

GList*              gtk_container_get_children          (GtkContainer *container);

Returns the container's non-internal children. See gtk_container_forall() for details on what constitutes an "internal" child.

container : | a GtkContainer.
Returns : | a newly-allocated list of the container's non-internal children.

gtk_container_set_reallocate_redraws ()

void                gtk_container_set_reallocate_redraws
                                                        (GtkContainer *container,
                                                         gboolean needs_redraws);

Sets the reallocate_redraws flag of the container to the given value.

Containers requesting reallocation redraws get automatically redrawn if any of their children changed allocation.

container : | a GtkContainer.
needs_redraws : | the new value for the container's reallocate_redraws flag.

gtk_container_set_focus_child ()

void                gtk_container_set_focus_child       (GtkContainer *container,
                                                         GtkWidget *child);

container :
child :

gtk_container_get_focus_vadjustment ()

GtkAdjustment*      gtk_container_get_focus_vadjustment (GtkContainer *container);

Retrieves the vertical focus adjustment for the container. See gtk_container_set_focus_vadjustment().

container : | a GtkContainer
Returns : | the vertical focus adjustment, or NULL if none has been set.

gtk_container_set_focus_vadjustment ()

void                gtk_container_set_focus_vadjustment (GtkContainer *container,
                                                         GtkAdjustment *adjustment);

Hooks up an adjustment to focus handling in a container, so when a child of the container is focused, the adjustment is scrolled to show that widget. This function sets the vertical alignment. See gtk_scrolled_window_get_vadjustment() for a typical way of obtaining the adjustment and gtk_container_set_focus_hadjustment() for setting the horizontal adjustment.

The adjustments have to be in pixel units and in the same coordinate system as the allocation for immediate children of the container.

container : | a GtkContainer
adjustment : | an adjustment which should be adjusted when the focus is moved among the descendents of container

gtk_container_get_focus_hadjustment ()

GtkAdjustment*      gtk_container_get_focus_hadjustment (GtkContainer *container);

Retrieves the horizontal focus adjustment for the container. See gtk_container_set_focus_hadjustment().

container : | a GtkContainer
Returns : | the horizontal focus adjustment, or NULL if none has been set.

gtk_container_set_focus_hadjustment ()

void                gtk_container_set_focus_hadjustment (GtkContainer *container,
                                                         GtkAdjustment *adjustment);

Hooks up an adjustment to focus handling in a container, so when a child of the container is focused, the adjustment is scrolled to show that widget. This function sets the horizontal alignment. See gtk_scrolled_window_get_hadjustment() for a typical way of obtaining the adjustment and gtk_container_set_focus_vadjustment() for setting the vertical adjustment.

The adjustments have to be in pixel units and in the same coordinate system as the allocation for immediate children of the container.

container : | a GtkContainer
adjustment : | an adjustment which should be adjusted when the focus is moved among the descendents of container

gtk_container_resize_children ()

void                gtk_container_resize_children       (GtkContainer *container);

container :

gtk_container_child_type ()

GType               gtk_container_child_type            (GtkContainer *container);

Returns the type of the children supported by the container.

Note that this may return G_TYPE_NONE to indicate that no more children can be added, e.g. for a GtkPaned which already has two children.

container : | a GtkContainer.
Returns : | a GType.

gtk_container_child_get ()

void                gtk_container_child_get             (GtkContainer *container,
                                                         GtkWidget *child,
                                                         const gchar *first_prop_name,
                                                         ...);

Gets the values of one or more child properties for child and container.

container : | a GtkContainer
child : | a widget which is a child of container
first_prop_name : | the name of the first property to get
... : | a NULL-terminated list of property names and GValue*, starting with first_prop_name.

gtk_container_child_set ()

void                gtk_container_child_set             (GtkContainer *container,
                                                         GtkWidget *child,
                                                         const gchar *first_prop_name,
                                                         ...);

Sets one or more child properties for child and container.

container : | a GtkContainer
child : | a widget which is a child of container
first_prop_name : | the name of the first property to set
... : | a NULL-terminated list of property names and values, starting with first_prop_name.

gtk_container_child_get_property ()

void                gtk_container_child_get_property    (GtkContainer *container,
                                                         GtkWidget *child,
                                                         const gchar *property_name,
                                                         GValue *value);

Gets the value of a child property for child and container.

container : | a GtkContainer
child : | a widget which is a child of container
property_name : | the name of the property to get
value : | a location to return the value

gtk_container_child_set_property ()

void                gtk_container_child_set_property    (GtkContainer *container,
                                                         GtkWidget *child,
                                                         const gchar *property_name,
                                                         const GValue *value);

Sets a child property for child and container.

container : | a GtkContainer
child : | a widget which is a child of container
property_name : | the name of the property to set
value : | the value to set the property to

gtk_container_child_get_valist ()

void                gtk_container_child_get_valist      (GtkContainer *container,
                                                         GtkWidget *child,
                                                         const gchar *first_property_name,
                                                         va_list var_args);

Gets the values of one or more child properties for child and container.

container : | a GtkContainer
child : | a widget which is a child of container
first_property_name : | the name of the first property to get
var_args : | a NULL-terminated list of property names and GValue*, starting with first_prop_name.

gtk_container_child_set_valist ()

void                gtk_container_child_set_valist      (GtkContainer *container,
                                                         GtkWidget *child,
                                                         const gchar *first_property_name,
                                                         va_list var_args);

Sets one or more child properties for child and container.

container : | a GtkContainer
child : | a widget which is a child of container
first_property_name : | the name of the first property to set
var_args : | a NULL-terminated list of property names and values, starting with first_prop_name.

gtk_container_forall ()

void                gtk_container_forall                (GtkContainer *container,
                                                         GtkCallback callback,
                                                         gpointer callback_data);

Invokes callback on each child of container, including children that are considered "internal" (implementation details of the container). "Internal" children generally weren't added by the user of the container, but were added by the container implementation itself. Most applications should use gtk_container_foreach(), rather than gtk_container_forall().

container : | a GtkContainer
callback : | a callback
callback_data : | callback user data

gtk_container_get_border_width ()

guint               gtk_container_get_border_width      (GtkContainer *container);

Retrieves the border width of the container. See gtk_container_set_border_width().

container : | a GtkContainer
Returns : | the current border width

gtk_container_set_border_width ()

void                gtk_container_set_border_width      (GtkContainer *container,
                                                         guint border_width);

Sets the border width of the container.

The border width of a container is the amount of space to leave around the outside of the container. The only exception to this is GtkWindow; because toplevel windows can't leave space outside, they leave the space inside. The border is added on all sides of the container. To add space to only one side, one approach is to create a GtkAlignment widget, call gtk_widget_set_usize() to give it a size, and place it on the side of the container as a spacer.

container : | a GtkContainer
border_width : | amount of blank space to leave outside the container. Valid values are in the range 0-65535 pixels.

gtk_container_propagate_expose ()

void                gtk_container_propagate_expose      (GtkContainer *container,
                                                         GtkWidget *child,
                                                         GdkEventExpose *event);

When a container receives an expose event, it must send synthetic expose events to all children that don't have their own GdkWindows. This function provides a convenient way of doing this. A container, when it receives an expose event, calls gtk_container_propagate_expose() once for each child, passing in the event the container received.

gtk_container_propagate_expose() takes care of deciding whether an expose event needs to be sent to the child, intersecting the event's area with the child area, and sending the event.

In most cases, a container can simply either simply inherit the ::expose implementation from GtkContainer, or, do some drawing and then chain to the ::expose implementation from GtkContainer.

container : | a GtkContainer
child : | a child of container
event : | a expose event sent to container

gtk_container_get_focus_chain ()

gboolean            gtk_container_get_focus_chain       (GtkContainer *container,
                                                         GList **focusable_widgets);

Retrieves the focus chain of the container, if one has been set explicitly. If no focus chain has been explicitly set, GTK+ computes the focus chain based on the positions of the children. In that case, GTK+ stores NULL in focusable_widgets and returns FALSE.

container : | a GtkContainer
focusable_widgets : | location to store the focus chain of the container, or NULL. You should free this list using g_list_free() when you are done with it, however no additional reference count is added to the individual widgets in the focus chain.
Returns : | TRUE if the focus chain of the container has been set explicitly.

gtk_container_set_focus_chain ()

void                gtk_container_set_focus_chain       (GtkContainer *container,
                                                         GList *focusable_widgets);

Sets a focus chain, overriding the one computed automatically by GTK+.

In principle each widget in the chain should be a descendant of the container, but this is not enforced by this method, since it's allowed to set the focus chain before you pack the widgets, or have a widget in the chain that isn't always packed. The necessary checks are done when the focus chain is actually traversed.

container : | a GtkContainer.
focusable_widgets : | the new focus chain.

gtk_container_unset_focus_chain ()

void                gtk_container_unset_focus_chain     (GtkContainer *container);

Removes a focus chain explicitly set with gtk_container_set_focus_chain().

container : a GtkContainer.

gtk_container_class_find_child_property ()

GParamSpec*         gtk_container_class_find_child_property
                                                        (GObjectClass *cclass,
                                                         const gchar *property_name);

Finds a child property of a container class by name.

cclass : | a GtkContainerClass
property_name : | the name of the child property to find
Returns : | the GParamSpec of the child property or NULL if class has no child property with that name.

gtk_container_class_install_child_property ()

void                gtk_container_class_install_child_property
                                                        (GtkContainerClass *cclass,
                                                         guint property_id,
                                                         GParamSpec *pspec);

Installs a child property on a container class.

cclass : | a GtkContainerClass
property_id : | the id for the property
pspec : | the GParamSpec for the property

gtk_container_class_list_child_properties ()

GParamSpec**        gtk_container_class_list_child_properties
                                                        (GObjectClass *cclass,
                                                         guint *n_properties);

Returns all child properties of a container class.

cclass : | a GtkContainerClass
n_properties : | location to return the number of child properties found
Returns : | a newly allocated array of GParamSpec*. The array must be freed with g_free().

Property Details

The "border-width" property

  "border-width"             guint                 : Read / Write

The width of the empty border outside the containers children.

Allowed values: <= G_MAXINT

Default value: 0

The "child" property

  "child"                    GtkWidget             : Write

Can be used to add a new child to the container.

The "resize-mode" property

  "resize-mode"              GtkResizeMode         : Read / Write

Specify how resize events are handled.

Default value: GTK_RESIZE_PARENT

Signal Details

The "add" signal

void                user_function                      (GtkContainer *container,
                                                        GtkWidget    *widget,
                                                        gpointer      user_data)      : Run First

container : | the object which received the signal.
widget : |
user_data : | user data set when the signal handler was connected.

The "check-resize" signal

void                user_function                      (GtkContainer *container,
                                                        gpointer      user_data)      : Run Last

container : | the object which received the signal.
user_data : | user data set when the signal handler was connected.

The "remove" signal

void                user_function                      (GtkContainer *container,
                                                        GtkWidget    *widget,
                                                        gpointer      user_data)      : Run First

container : | the object which received the signal.
widget : |
user_data : | user data set when the signal handler was connected.

The "set-focus-child" signal

void                user_function                      (GtkContainer *container,
                                                        GtkWidget    *widget,
                                                        gpointer      user_data)      : Run First

container : | the object which received the signal.
widget : |
user_data : | user data set when the signal handler was connected.


GtkCTree

GtkCTree — A widget displaying a hierarchical tree

Synopsis

#include <gtk/gtk.h>

                    GtkCTree;
#define             GTK_CTREE_ROW                       (_node_)
#define             GTK_CTREE_NODE                      (_node_)
#define             GTK_CTREE_NODE_NEXT                 (_nnode_)
#define             GTK_CTREE_NODE_PREV                 (_pnode_)
#define             GTK_CTREE_FUNC                      (_func_)
enum                GtkCTreePos;
enum                GtkCTreeLineStyle;
enum                GtkCTreeExpanderStyle;
enum                GtkCTreeExpansionType;
void                (*GtkCTreeFunc)                     (GtkCTree *ctree,
                                                         GtkCTreeNode *node,
                                                         gpointer data);
gboolean            (*GtkCTreeGNodeFunc)                (GtkCTree *ctree,
                                                         guint depth,
                                                         GNode *gnode,
                                                         GtkCTreeNode *cnode,
                                                         gpointer data);
gboolean            (*GtkCTreeCompareDragFunc)          (GtkCTree *ctree,
                                                         GtkCTreeNode *source_node,
                                                         GtkCTreeNode *new_parent,
                                                         GtkCTreeNode *new_sibling);
                    GtkCTreeRow;
                    GtkCTreeNode;
#define             GTK_TYPE_CTREE_NODE
GtkWidget*          gtk_ctree_new_with_titles           (gint columns,
                                                         gint tree_column,
                                                         gchar *titles[]);
GtkWidget*          gtk_ctree_new                       (gint columns,
                                                         gint tree_column);
GtkCTreeNode*       gtk_ctree_insert_node               (GtkCTree *ctree,
                                                         GtkCTreeNode *parent,
                                                         GtkCTreeNode *sibling,
                                                         gchar *text[],
                                                         guint8 spacing,
                                                         GdkPixmap *pixmap_closed,
                                                         GdkBitmap *mask_closed,
                                                         GdkPixmap *pixmap_opened,
                                                         GdkBitmap *mask_opened,
                                                         gboolean is_leaf,
                                                         gboolean expanded);
void                gtk_ctree_remove_node               (GtkCTree *ctree,
                                                         GtkCTreeNode *node);
GtkCTreeNode*       gtk_ctree_insert_gnode              (GtkCTree *ctree,
                                                         GtkCTreeNode *parent,
                                                         GtkCTreeNode *sibling,
                                                         GNode *gnode,
                                                         GtkCTreeGNodeFunc func,
                                                         gpointer data);
GNode*              gtk_ctree_export_to_gnode           (GtkCTree *ctree,
                                                         GNode *parent,
                                                         GNode *sibling,
                                                         GtkCTreeNode *node,
                                                         GtkCTreeGNodeFunc func,
                                                         gpointer data);
void                gtk_ctree_post_recursive            (GtkCTree *ctree,
                                                         GtkCTreeNode *node,
                                                         GtkCTreeFunc func,
                                                         gpointer data);
void                gtk_ctree_post_recursive_to_depth   (GtkCTree *ctree,
                                                         GtkCTreeNode *node,
                                                         gint depth,
                                                         GtkCTreeFunc func,
                                                         gpointer data);
void                gtk_ctree_pre_recursive             (GtkCTree *ctree,
                                                         GtkCTreeNode *node,
                                                         GtkCTreeFunc func,
                                                         gpointer data);
void                gtk_ctree_pre_recursive_to_depth    (GtkCTree *ctree,
                                                         GtkCTreeNode *node,
                                                         gint depth,
                                                         GtkCTreeFunc func,
                                                         gpointer data);
gboolean            gtk_ctree_is_viewable               (GtkCTree *ctree,
                                                         GtkCTreeNode *node);
GtkCTreeNode*       gtk_ctree_last                      (GtkCTree *ctree,
                                                         GtkCTreeNode *node);
GtkCTreeNode*       gtk_ctree_find_node_ptr             (GtkCTree *ctree,
                                                         GtkCTreeRow *ctree_row);
gboolean            gtk_ctree_find                      (GtkCTree *ctree,
                                                         GtkCTreeNode *node,
                                                         GtkCTreeNode *child);
gboolean            gtk_ctree_is_ancestor               (GtkCTree *ctree,
                                                         GtkCTreeNode *node,
                                                         GtkCTreeNode *child);
GtkCTreeNode*       gtk_ctree_find_by_row_data          (GtkCTree *ctree,
                                                         GtkCTreeNode *node,
                                                         gpointer data);
GList*              gtk_ctree_find_all_by_row_data      (GtkCTree *ctree,
                                                         GtkCTreeNode *node,
                                                         gpointer data);
GtkCTreeNode*       gtk_ctree_find_by_row_data_custom   (GtkCTree *ctree,
                                                         GtkCTreeNode *node,
                                                         gpointer data,
                                                         GCompareFunc func);
GList*              gtk_ctree_find_all_by_row_data_custom
                                                        (GtkCTree *ctree,
                                                         GtkCTreeNode *node,
                                                         gpointer data,
                                                         GCompareFunc func);
gboolean            gtk_ctree_is_hot_spot               (GtkCTree *ctree,
                                                         gint x,
                                                         gint y);
void                gtk_ctree_move                      (GtkCTree *ctree,
                                                         GtkCTreeNode *node,
                                                         GtkCTreeNode *new_parent,
                                                         GtkCTreeNode *new_sibling);
void                gtk_ctree_expand                    (GtkCTree *ctree,
                                                         GtkCTreeNode *node);
void                gtk_ctree_expand_recursive          (GtkCTree *ctree,
                                                         GtkCTreeNode *node);
void                gtk_ctree_expand_to_depth           (GtkCTree *ctree,
                                                         GtkCTreeNode *node,
                                                         gint depth);
void                gtk_ctree_collapse                  (GtkCTree *ctree,
                                                         GtkCTreeNode *node);
void                gtk_ctree_collapse_recursive        (GtkCTree *ctree,
                                                         GtkCTreeNode *node);
void                gtk_ctree_collapse_to_depth         (GtkCTree *ctree,
                                                         GtkCTreeNode *node,
                                                         gint depth);
void                gtk_ctree_toggle_expansion          (GtkCTree *ctree,
                                                         GtkCTreeNode *node);
void                gtk_ctree_toggle_expansion_recursive
                                                        (GtkCTree *ctree,
                                                         GtkCTreeNode *node);
void                gtk_ctree_select                    (GtkCTree *ctree,
                                                         GtkCTreeNode *node);
void                gtk_ctree_select_recursive          (GtkCTree *ctree,
                                                         GtkCTreeNode *node);
void                gtk_ctree_unselect                  (GtkCTree *ctree,
                                                         GtkCTreeNode *node);
void                gtk_ctree_unselect_recursive        (GtkCTree *ctree,
                                                         GtkCTreeNode *node);
void                gtk_ctree_real_select_recursive     (GtkCTree *ctree,
                                                         GtkCTreeNode *node,
                                                         gint state);
void                gtk_ctree_node_set_text             (GtkCTree *ctree,
                                                         GtkCTreeNode *node,
                                                         gint column,
                                                         const gchar *text);
void                gtk_ctree_node_set_pixmap           (GtkCTree *ctree,
                                                         GtkCTreeNode *node,
                                                         gint column,
                                                         GdkPixmap *pixmap,
                                                         GdkBitmap *mask);
void                gtk_ctree_node_set_pixtext          (GtkCTree *ctree,
                                                         GtkCTreeNode *node,
                                                         gint column,
                                                         const gchar *text,
                                                         guint8 spacing,
                                                         GdkPixmap *pixmap,
                                                         GdkBitmap *mask);
void                gtk_ctree_set_node_info             (GtkCTree *ctree,
                                                         GtkCTreeNode *node,
                                                         const gchar *text,
                                                         guint8 spacing,
                                                         GdkPixmap *pixmap_closed,
                                                         GdkBitmap *mask_closed,
                                                         GdkPixmap *pixmap_opened,
                                                         GdkBitmap *mask_opened,
                                                         gboolean is_leaf,
                                                         gboolean expanded);
void                gtk_ctree_node_set_shift            (GtkCTree *ctree,
                                                         GtkCTreeNode *node,
                                                         gint column,
                                                         gint vertical,
                                                         gint horizontal);
void                gtk_ctree_node_set_selectable       (GtkCTree *ctree,
                                                         GtkCTreeNode *node,
                                                         gboolean selectable);
gboolean            gtk_ctree_node_get_selectable       (GtkCTree *ctree,
                                                         GtkCTreeNode *node);
GtkCellType         gtk_ctree_node_get_cell_type        (GtkCTree *ctree,
                                                         GtkCTreeNode *node,
                                                         gint column);
gboolean            gtk_ctree_node_get_text             (GtkCTree *ctree,
                                                         GtkCTreeNode *node,
                                                         gint column,
                                                         gchar **text);
gboolean            gtk_ctree_node_get_pixmap           (GtkCTree *ctree,
                                                         GtkCTreeNode *node,
                                                         gint column,
                                                         GdkPixmap **pixmap,
                                                         GdkBitmap **mask);
gboolean            gtk_ctree_node_get_pixtext          (GtkCTree *ctree,
                                                         GtkCTreeNode *node,
                                                         gint column,
                                                         gchar **text,
                                                         guint8 *spacing,
                                                         GdkPixmap **pixmap,
                                                         GdkBitmap **mask);
gboolean            gtk_ctree_get_node_info             (GtkCTree *ctree,
                                                         GtkCTreeNode *node,
                                                         gchar **text,
                                                         guint8 *spacing,
                                                         GdkPixmap **pixmap_closed,
                                                         GdkBitmap **mask_closed,
                                                         GdkPixmap **pixmap_opened,
                                                         GdkBitmap **mask_opened,
                                                         gboolean *is_leaf,
                                                         gboolean *expanded);
void                gtk_ctree_node_set_row_style        (GtkCTree *ctree,
                                                         GtkCTreeNode *node,
                                                         GtkStyle *style);
GtkStyle*           gtk_ctree_node_get_row_style        (GtkCTree *ctree,
                                                         GtkCTreeNode *node);
void                gtk_ctree_node_set_cell_style       (GtkCTree *ctree,
                                                         GtkCTreeNode *node,
                                                         gint column,
                                                         GtkStyle *style);
GtkStyle*           gtk_ctree_node_get_cell_style       (GtkCTree *ctree,
                                                         GtkCTreeNode *node,
                                                         gint column);
void                gtk_ctree_node_set_foreground       (GtkCTree *ctree,
                                                         GtkCTreeNode *node,
                                                         const GdkColor *color);
void                gtk_ctree_node_set_background       (GtkCTree *ctree,
                                                         GtkCTreeNode *node,
                                                         const GdkColor *color);
void                gtk_ctree_node_set_row_data         (GtkCTree *ctree,
                                                         GtkCTreeNode *node,
                                                         gpointer data);
void                gtk_ctree_node_set_row_data_full    (GtkCTree *ctree,
                                                         GtkCTreeNode *node,
                                                         gpointer data,
                                                         GtkDestroyNotify destroy);
gpointer            gtk_ctree_node_get_row_data         (GtkCTree *ctree,
                                                         GtkCTreeNode *node);
void                gtk_ctree_node_moveto               (GtkCTree *ctree,
                                                         GtkCTreeNode *node,
                                                         gint column,
                                                         gfloat row_align,
                                                         gfloat col_align);
GtkVisibility       gtk_ctree_node_is_visible           (GtkCTree *ctree,
                                                         GtkCTreeNode *node);
void                gtk_ctree_set_indent                (GtkCTree *ctree,
                                                         gint indent);
void                gtk_ctree_set_spacing               (GtkCTree *ctree,
                                                         gint spacing);
#define             gtk_ctree_set_reorderable           (t,r)
void                gtk_ctree_set_line_style            (GtkCTree *ctree,
                                                         GtkCTreeLineStyle line_style);
void                gtk_ctree_set_expander_style        (GtkCTree *ctree,
                                                         GtkCTreeExpanderStyle expander_style);
void                gtk_ctree_set_drag_compare_func     (GtkCTree *ctree,
                                                         GtkCTreeCompareDragFunc cmp_func);
void                gtk_ctree_sort_node                 (GtkCTree *ctree,
                                                         GtkCTreeNode *node);
void                gtk_ctree_sort_recursive            (GtkCTree *ctree,
                                                         GtkCTreeNode *node);
GtkCTreeNode*       gtk_ctree_node_nth                  (GtkCTree *ctree,
                                                         guint row);
void                gtk_ctree_set_show_stub             (GtkCTree *ctree,
                                                         gboolean show_stub);

Object Hierarchy

  GObject
   +----GInitiallyUnowned
         +----GtkObject
               +----GtkWidget
                     +----GtkContainer
                           +----GtkCList
                                 +----GtkCTree

Implemented Interfaces

GtkCTree implements AtkImplementorIface.

Properties

  "expander-style"           GtkCTreeExpanderStyle  : Read / Write
  "indent"                   guint                 : Read / Write
  "line-style"               GtkCTreeLineStyle     : Read / Write
  "n-columns"                guint                 : Read / Write / Construct Only
  "show-stub"                gboolean              : Read / Write
  "spacing"                  guint                 : Read / Write
  "tree-column"              guint                 : Read / Write / Construct Only

Signals

  "change-focus-row-expansion"                     : Run Last / Action
  "tree-collapse"                                  : Run Last
  "tree-expand"                                    : Run Last
  "tree-move"                                      : Run Last
  "tree-select-row"                                : Run First
  "tree-unselect-row"                              : Run First

Description

The GtkCTree widget is used for showing a hierarchical tree to the user, for example a directory tree.

The tree is internally represented as a set of GtkCTreeNode structures.

The interface has much in common with the GtkCList widget: rows (nodes) can be selected by the user etc.

Positions in the tree are often indicated by two arguments, a parent and a sibling, both GtkCTreeNode pointers. If the parent is NULL, the position is at the root of the tree and if the sibling is NULL, it will be the last child of parent, otherwise it will be inserted just before the sibling.

GtkCTree has been deprecated since GTK+ 2.0 and should not be used in newly written code. Use GtkTreeView instead.

Details

GtkCTree

typedef struct _GtkCTree GtkCTree;

Warning

GtkCTree is deprecated and should not be used in newly-written code.

The GtkCTree contains the following user-accessible fields. These fields should be considered read-only; to set the values, use the methods below.

gint tree_indent; | The number of pixels each successive level of the tree is indented in the display.
gint tree_spacing; | The space in pixels between the graphical tree and the text in the node.
gint tree_column; | The index of the column for which the tree graphics is drawn.
GtkCTreeLineStyle line_style; | The style in which the lines in the tree graphics are drawn.
GtkCTreeExpanderStyle expander_style; | The style in which the expander buttons are drawn.
GtkCTreeExpanderStyle expander_style; | FIXME.

GTK_CTREE_ROW()

#define GTK_CTREE_ROW(_node_) ((GtkCTreeRow *)(((GList *)(_node_))->data))

Warning

GTK_CTREE_ROW is deprecated and should not be used in newly-written code.

Used to get the GtkCTreeRow structure corresponding to the given GtkCTreeNode.

_node_ :

GTK_CTREE_NODE()

#define GTK_CTREE_NODE(_node_) ((GtkCTreeNode *)((_node_)))

Warning

GTK_CTREE_NODE is deprecated and should not be used in newly-written code.

_node_ :

GTK_CTREE_NODE_NEXT()

#define GTK_CTREE_NODE_NEXT(_nnode_) ((GtkCTreeNode *)(((GList *)(_nnode_))->next))

Warning

GTK_CTREE_NODE_NEXT is deprecated and should not be used in newly-written code.

FIXME

_nnode_ :

GTK_CTREE_NODE_PREV()

#define GTK_CTREE_NODE_PREV(_pnode_) ((GtkCTreeNode *)(((GList *)(_pnode_))->prev))

Warning

GTK_CTREE_NODE_PREV is deprecated and should not be used in newly-written code.

FIXME

_pnode_ :

GTK_CTREE_FUNC()

#define GTK_CTREE_FUNC(_func_) ((GtkCTreeFunc)(_func_))

Warning

GTK_CTREE_FUNC is deprecated and should not be used in newly-written code.

_func_ :

enum GtkCTreePos

typedef enum
{
  GTK_CTREE_POS_BEFORE,
  GTK_CTREE_POS_AS_CHILD,
  GTK_CTREE_POS_AFTER
} GtkCTreePos;

Warning

GtkCTreePos is deprecated and should not be used in newly-written code.

A value specifying the position of a new node relative to an old one.

GTK_CTREE_POS_BEFORE | As a sibling, before the specified node.
GTK_CTREE_POS_AS_CHILD | As a child of the specified node.
GTK_CTREE_POS_AFTER | As a sibling, after the specified node.

enum GtkCTreeLineStyle

typedef enum
{
  GTK_CTREE_LINES_NONE,
  GTK_CTREE_LINES_SOLID,
  GTK_CTREE_LINES_DOTTED,
  GTK_CTREE_LINES_TABBED
} GtkCTreeLineStyle;

Warning

GtkCTreeLineStyle is deprecated and should not be used in newly-written code.

The appearance of the lines in the tree graphics.

GTK_CTREE_LINES_NONE | No lines.
GTK_CTREE_LINES_SOLID | Solid lines.
GTK_CTREE_LINES_DOTTED | Dotted lines.
GTK_CTREE_LINES_TABBED | FIXME.

enum GtkCTreeExpanderStyle

typedef enum
{
  GTK_CTREE_EXPANDER_NONE,
  GTK_CTREE_EXPANDER_SQUARE,
  GTK_CTREE_EXPANDER_TRIANGLE,
  GTK_CTREE_EXPANDER_CIRCULAR
} GtkCTreeExpanderStyle;

Warning

GtkCTreeExpanderStyle is deprecated and should not be used in newly-written code.

The appearance of the expander buttons, i.e. the small buttons which expand or contract parts of the tree when pressed.

GTK_CTREE_EXPANDER_NONE | No expanders.
GTK_CTREE_EXPANDER_SQUARE | Square expanders.
GTK_CTREE_EXPANDER_TRIANGLE | Triangular expanders.
GTK_CTREE_EXPANDER_CIRCULAR | Round expanders.

enum GtkCTreeExpansionType

typedef enum
{
  GTK_CTREE_EXPANSION_EXPAND,
  GTK_CTREE_EXPANSION_EXPAND_RECURSIVE,
  GTK_CTREE_EXPANSION_COLLAPSE,
  GTK_CTREE_EXPANSION_COLLAPSE_RECURSIVE,
  GTK_CTREE_EXPANSION_TOGGLE,
  GTK_CTREE_EXPANSION_TOGGLE_RECURSIVE
} GtkCTreeExpansionType;

Warning

GtkCTreeExpansionType is deprecated and should not be used in newly-written code.

How to expand or collapse a part of a tree.

GTK_CTREE_EXPANSION_EXPAND | Expand this node.
GTK_CTREE_EXPANSION_EXPAND_RECURSIVE | Expand this node and everything below it in the hierarchy.
GTK_CTREE_EXPANSION_COLLAPSE | Collapse this node.
GTK_CTREE_EXPANSION_COLLAPSE_RECURSIVE | Collapse this node and everything below it in the hierarchy.
GTK_CTREE_EXPANSION_TOGGLE | Toggle this node (i.e. expand if collapsed and vice versa).
GTK_CTREE_EXPANSION_TOGGLE_RECURSIVE | Toggle this node and everything below it in the hierarchy.

GtkCTreeFunc ()

void                (*GtkCTreeFunc)                     (GtkCTree *ctree,
                                                         GtkCTreeNode *node,
                                                         gpointer data);

Warning

GtkCTreeFunc is deprecated and should not be used in newly-written code.

A generic callback type to do something with a particular node.

ctree : | The GtkCTree object.
node : | The GtkCTreeNode in the tree.
data : | The user data associated with the node.

GtkCTreeGNodeFunc ()

gboolean            (*GtkCTreeGNodeFunc)                (GtkCTree *ctree,
                                                         guint depth,
                                                         GNode *gnode,
                                                         GtkCTreeNode *cnode,
                                                         gpointer data);

Warning

GtkCTreeGNodeFunc is deprecated and should not be used in newly-written code.

FIXME

ctree :
depth :
gnode :
cnode :
data :
Returns :

GtkCTreeCompareDragFunc ()

gboolean            (*GtkCTreeCompareDragFunc)          (GtkCTree *ctree,
                                                         GtkCTreeNode *source_node,
                                                         GtkCTreeNode *new_parent,
                                                         GtkCTreeNode *new_sibling);

Warning

GtkCTreeCompareDragFunc is deprecated and should not be used in newly-written code.

FIXME

ctree :
source_node :
new_parent :
new_sibling :
Returns :

GtkCTreeRow

typedef struct {
  GtkCListRow row;

  GtkCTreeNode *parent;
  GtkCTreeNode *sibling;
  GtkCTreeNode *children;

  GdkPixmap *pixmap_closed;
  GdkBitmap *mask_closed;
  GdkPixmap *pixmap_opened;
  GdkBitmap *mask_opened;

  guint16 level;

  guint is_leaf  : 1;
  guint expanded : 1;
} GtkCTreeRow;

Warning

GtkCTreeRow is deprecated and should not be used in newly-written code.

A structure representing a single row in the tree graph. The values inside the structure should be considered read-only. This structure is derived from the GtkCListRow structure.

GtkCTreeNode *parent; | The parent node of the node corresponding to this row.
GtkCTreeNode *sibling; | The next sibling node of the node corresponding to this row.
GtkCTreeNode *children; | The first child node corresponding to this row; to access the other children, just use the siblings of that node.
GdkPixmap *pixmap_closed; | The pixmap to be shown when the node is collapsed.
GdkBitmap *mask_closed; | The mask for the above pixmap.
GdkPixmap *pixmap_opened; | The pixmap to be shown when the node is expanded.
GdkBitmap *mask_opened; | The mask for the above pixmap.
guint16 level; | The level of this node in the tree.
guint is_leaf : 1; | Whether this row is a leaf.
guint expanded : 1; | Whether the children of this row are visible.

GtkCTreeNode

typedef struct {
  GList list;
} GtkCTreeNode;

Warning

GtkCTreeNode is deprecated and should not be used in newly-written code.

This structure is opaque - you should use the macros GTK_CTREE_ROW, GTK_CTREE_NODE_NEXT etc. as well as the functions below to access it.

GTK_TYPE_CTREE_NODE

#define GTK_TYPE_CTREE_NODE (gtk_ctree_node_get_type ())

Warning

GTK_TYPE_CTREE_NODE is deprecated and should not be used in newly-written code.

gtk_ctree_new_with_titles ()

GtkWidget*          gtk_ctree_new_with_titles           (gint columns,
                                                         gint tree_column,
                                                         gchar *titles[]);

Warning

gtk_ctree_new_with_titles is deprecated and should not be used in newly-written code.

Create a new GtkCTree widget with the given titles for the columns.

columns : | Number of columns.
tree_column : | Which column has the tree graphic; 0 = leftmost.
titles : | The titles for the columns.
Returns : | The GtkCTree widget.

gtk_ctree_new ()

GtkWidget*          gtk_ctree_new                       (gint columns,
                                                         gint tree_column);

Warning

gtk_ctree_new is deprecated and should not be used in newly-written code.

Create a new GtkCTree widget.

columns : | Number of columns.
tree_column : | Which columns has the tree graphic.
Returns : | The new GtkCTree widget.

gtk_ctree_insert_node ()

GtkCTreeNode*       gtk_ctree_insert_node               (GtkCTree *ctree,
                                                         GtkCTreeNode *parent,
                                                         GtkCTreeNode *sibling,
                                                         gchar *text[],
                                                         guint8 spacing,
                                                         GdkPixmap *pixmap_closed,
                                                         GdkBitmap *mask_closed,
                                                         GdkPixmap *pixmap_opened,
                                                         GdkBitmap *mask_opened,
                                                         gboolean is_leaf,
                                                         gboolean expanded);

Warning

gtk_ctree_insert_node is deprecated and should not be used in newly-written code.

Insert a new node to the tree. The position is specified through the parent-sibling notation, as explained in the introduction above.

ctree : | The GtkCTree widget.
parent : | The parent node to be.
sibling : | The sibling node to be.
text : | The texts to be shown in each column.
spacing : | The extra space between the pixmap and the text.
pixmap_closed : | The pixmap to be used when the node is collapsed. Can be NULL.
mask_closed : | The mask for the above pixmap. Can be NULL.
pixmap_opened : | The pixmap to be used when the children are visible. Can be NULL.
mask_opened : | The mask for the above pixmap. Can be NULL.
is_leaf : | Whether this node is going to be a leaf.
expanded : | Whether this node should start out expanded or not.
Returns : |

gtk_ctree_remove_node ()

void                gtk_ctree_remove_node               (GtkCTree *ctree,
                                                         GtkCTreeNode *node);

Warning

gtk_ctree_remove_node is deprecated and should not be used in newly-written code.

Remove the node and all nodes underneath it from the tree.

ctree : | The widget.
node : | The node to be removed.

gtk_ctree_insert_gnode ()

GtkCTreeNode*       gtk_ctree_insert_gnode              (GtkCTree *ctree,
                                                         GtkCTreeNode *parent,
                                                         GtkCTreeNode *sibling,
                                                         GNode *gnode,
                                                         GtkCTreeGNodeFunc func,
                                                         gpointer data);

Warning

gtk_ctree_insert_gnode is deprecated and should not be used in newly-written code.

FIXME

ctree :
parent :
sibling :
gnode :
func :
data :
Returns :

gtk_ctree_export_to_gnode ()

GNode*              gtk_ctree_export_to_gnode           (GtkCTree *ctree,
                                                         GNode *parent,
                                                         GNode *sibling,
                                                         GtkCTreeNode *node,
                                                         GtkCTreeGNodeFunc func,
                                                         gpointer data);

Warning

gtk_ctree_export_to_gnode is deprecated and should not be used in newly-written code.

FIXME

ctree :
parent :
sibling :
node :
func :
data :
Returns :

gtk_ctree_post_recursive ()

void                gtk_ctree_post_recursive            (GtkCTree *ctree,
                                                         GtkCTreeNode *node,
                                                         GtkCTreeFunc func,
                                                         gpointer data);

Warning

gtk_ctree_post_recursive is deprecated and should not be used in newly-written code.

Recursively apply a function to all nodes of the tree at or below a certain node. The function is called for each node after it has been called for that node's children.

ctree : |
node : | The node where to start. NULL means to start at the root.
func : | The function to apply to each node.
data : | A closure argument given to each invocation of the function.

gtk_ctree_post_recursive_to_depth ()

void                gtk_ctree_post_recursive_to_depth   (GtkCTree *ctree,
                                                         GtkCTreeNode *node,
                                                         gint depth,
                                                         GtkCTreeFunc func,
                                                         gpointer data);

Warning

gtk_ctree_post_recursive_to_depth is deprecated and should not be used in newly-written code.

Recursively apply a function to nodes up to a certain depth. The function is called for each node after it has been called for that node's children.

ctree : |
node : | The node where to start.
depth : | The maximum absolute depth for applying the function. If depth is negative, this function just calls gtk_ctree_post_recursive.
func : | The function to apply to each node.
data : | A closure argument given to each invocation of the function.

gtk_ctree_pre_recursive ()

void                gtk_ctree_pre_recursive             (GtkCTree *ctree,
                                                         GtkCTreeNode *node,
                                                         GtkCTreeFunc func,
                                                         gpointer data);

Warning

gtk_ctree_pre_recursive is deprecated and should not be used in newly-written code.

Recursively apply a function to all nodes of the tree at or below a certain node. The function is called for each node after it has been called for its parent.

ctree : |
node : | The node where to start. NULL means to start at the root.
func : | The function to apply to each node.
data : | A closure argument given to each invocation of the function.

gtk_ctree_pre_recursive_to_depth ()

void                gtk_ctree_pre_recursive_to_depth    (GtkCTree *ctree,
                                                         GtkCTreeNode *node,
                                                         gint depth,
                                                         GtkCTreeFunc func,
                                                         gpointer data);

Warning

gtk_ctree_pre_recursive_to_depth is deprecated and should not be used in newly-written code.

Recursively apply a function to nodes up to a certain depth. The function is called for each node after it has been called for that node's children.

ctree : |
node : | The node where to start.
depth : | The maximum absolute depth for applying the function. If depth is negative, this function just calls gtk_ctree_post_recursive.
func : | The function to apply to each node.
data : | A closure argument given to each invocation of the function.

gtk_ctree_is_viewable ()

gboolean            gtk_ctree_is_viewable               (GtkCTree *ctree,
                                                         GtkCTreeNode *node);

Warning

gtk_ctree_is_viewable is deprecated and should not be used in newly-written code.

This function checks whether the given node is viewable i.e. so that all of its parent nodes are expanded. This is different from being actually visible: the node can be viewable but outside the scrolling area of the window.

ctree : |
node : |
Returns : | Whether the node is viewable.

gtk_ctree_last ()

GtkCTreeNode*       gtk_ctree_last                      (GtkCTree *ctree,
                                                         GtkCTreeNode *node);

Warning

gtk_ctree_last is deprecated and should not be used in newly-written code.

Returns the last child of the last child of the last child... of the given node.

ctree :
node :
Returns :

gtk_ctree_find_node_ptr ()

GtkCTreeNode*       gtk_ctree_find_node_ptr             (GtkCTree *ctree,
                                                         GtkCTreeRow *ctree_row);

Warning

gtk_ctree_find_node_ptr is deprecated and should not be used in newly-written code.

Finds the node pointer given a GtkCTreeRow structure.

ctree : |
ctree_row : |
Returns : | The node pointer.

gtk_ctree_find ()

gboolean            gtk_ctree_find                      (GtkCTree *ctree,
                                                         GtkCTreeNode *node,
                                                         GtkCTreeNode *child);

Warning

gtk_ctree_find is deprecated and should not be used in newly-written code.

ctree : |
node : | The node to start searching from. May be NULL.
child : |
Returns : | True if child is on some level a child (grandchild...) of the node.

gtk_ctree_is_ancestor ()

gboolean            gtk_ctree_is_ancestor               (GtkCTree *ctree,
                                                         GtkCTreeNode *node,
                                                         GtkCTreeNode *child);

Warning

gtk_ctree_is_ancestor is deprecated and should not be used in newly-written code.

ctree : |
node : |
child : |
Returns : | True is node is an ancestor of child.

gtk_ctree_find_by_row_data ()

GtkCTreeNode*       gtk_ctree_find_by_row_data          (GtkCTree *ctree,
                                                         GtkCTreeNode *node,
                                                         gpointer data);

Warning

gtk_ctree_find_by_row_data is deprecated and should not be used in newly-written code.

Finds a node in the tree under node that has the given user data pointer.

ctree : |
node : |
data : |
Returns : | The node, or NULL if not found.

gtk_ctree_find_all_by_row_data ()

GList*              gtk_ctree_find_all_by_row_data      (GtkCTree *ctree,
                                                         GtkCTreeNode *node,
                                                         gpointer data);

Warning

gtk_ctree_find_all_by_row_data is deprecated and should not be used in newly-written code.

Finds all nodes in the tree under node that have the given user data pointer.

ctree : |
node : |
data : |
Returns : | A list of nodes that have the given data pointer.

gtk_ctree_find_by_row_data_custom ()

GtkCTreeNode*       gtk_ctree_find_by_row_data_custom   (GtkCTree *ctree,
                                                         GtkCTreeNode *node,
                                                         gpointer data,
                                                         GCompareFunc func);

Warning

gtk_ctree_find_by_row_data_custom is deprecated and should not be used in newly-written code.

Find the first node under node whose row data pointer fulfills a custom criterion.

ctree : |
node : | The node where to start searching.
data : | User data for the criterion function.
func : | The criterion function.
Returns : | The first node found.

gtk_ctree_find_all_by_row_data_custom ()

GList*              gtk_ctree_find_all_by_row_data_custom
                                                        (GtkCTree *ctree,
                                                         GtkCTreeNode *node,
                                                         gpointer data,
                                                         GCompareFunc func);

Warning

gtk_ctree_find_all_by_row_data_custom is deprecated and should not be used in newly-written code.

Find all nodes under node whose row data pointer fulfills a custom criterion.

ctree : |
node : | The node where to start searching.
data : | User data for the criterion function.
func : | The criterion function.
Returns : | A list of all nodes found.

gtk_ctree_is_hot_spot ()

gboolean            gtk_ctree_is_hot_spot               (GtkCTree *ctree,
                                                         gint x,
                                                         gint y);

Warning

gtk_ctree_is_hot_spot is deprecated and should not be used in newly-written code.

ctree : |
x : |
y : |
Returns : | True if the given coordinates lie on an expander button.

gtk_ctree_move ()

void                gtk_ctree_move                      (GtkCTree *ctree,
                                                         GtkCTreeNode *node,
                                                         GtkCTreeNode *new_parent,
                                                         GtkCTreeNode *new_sibling);

Warning

gtk_ctree_move is deprecated and should not be used in newly-written code.

Move a node in the tree to another location.

ctree : |
node : | The node to be moved.
new_parent : | The new parent-to-be of the node.
new_sibling : | The new sibling-to-be of the node.

gtk_ctree_expand ()

void                gtk_ctree_expand                    (GtkCTree *ctree,
                                                         GtkCTreeNode *node);

Warning

gtk_ctree_expand is deprecated and should not be used in newly-written code.

Expand one node.

ctree :
node :

gtk_ctree_expand_recursive ()

void                gtk_ctree_expand_recursive          (GtkCTree *ctree,
                                                         GtkCTreeNode *node);

Warning

gtk_ctree_expand_recursive is deprecated and should not be used in newly-written code.

Expand one node and all nodes underneath.

ctree :
node :

gtk_ctree_expand_to_depth ()

void                gtk_ctree_expand_to_depth           (GtkCTree *ctree,
                                                         GtkCTreeNode *node,
                                                         gint depth);

Warning

gtk_ctree_expand_to_depth is deprecated and should not be used in newly-written code.

Expand a node and its children up to the depth given.

ctree : |
node : |
depth : | The (absolute) depth up to which to expand nodes.

gtk_ctree_collapse ()

void                gtk_ctree_collapse                  (GtkCTree *ctree,
                                                         GtkCTreeNode *node);

Warning

gtk_ctree_collapse is deprecated and should not be used in newly-written code.

Collapse one node.

ctree :
node :

gtk_ctree_collapse_recursive ()

void                gtk_ctree_collapse_recursive        (GtkCTree *ctree,
                                                         GtkCTreeNode *node);

Warning

gtk_ctree_collapse_recursive is deprecated and should not be used in newly-written code.

Collapse one node and all its subnodes.

ctree :
node :

gtk_ctree_collapse_to_depth ()

void                gtk_ctree_collapse_to_depth         (GtkCTree *ctree,
                                                         GtkCTreeNode *node,
                                                         gint depth);

Warning

gtk_ctree_collapse_to_depth is deprecated and should not be used in newly-written code.

Collapse a node and its children up to the depth given.

ctree : |
node : |
depth : | The (absolute) depth up to which to collapse nodes.

gtk_ctree_toggle_expansion ()

void                gtk_ctree_toggle_expansion          (GtkCTree *ctree,
                                                         GtkCTreeNode *node);

Warning

gtk_ctree_toggle_expansion is deprecated and should not be used in newly-written code.

Toggle a node, i.e. if it is collapsed, expand it and vice versa.

ctree :
node :

gtk_ctree_toggle_expansion_recursive ()

void                gtk_ctree_toggle_expansion_recursive
                                                        (GtkCTree *ctree,
                                                         GtkCTreeNode *node);

Warning

gtk_ctree_toggle_expansion_recursive is deprecated and should not be used in newly-written code.

Toggle the expansion of a node and all its children.

ctree :
node :

gtk_ctree_select ()

void                gtk_ctree_select                    (GtkCTree *ctree,
                                                         GtkCTreeNode *node);

Warning

gtk_ctree_select is deprecated and should not be used in newly-written code.

Cause the given node to be selected and emit the appropriate signal.

ctree :
node :

gtk_ctree_select_recursive ()

void                gtk_ctree_select_recursive          (GtkCTree *ctree,
                                                         GtkCTreeNode *node);

Warning

gtk_ctree_select_recursive is deprecated and should not be used in newly-written code.

Cause the given node and its subnodes to be selected and emit the appropriate signal(s).

ctree :
node :

gtk_ctree_unselect ()

void                gtk_ctree_unselect                  (GtkCTree *ctree,
                                                         GtkCTreeNode *node);

Warning

gtk_ctree_unselect is deprecated and should not be used in newly-written code.

Unselect the given node and emit the appropriate signal.

ctree :
node :

gtk_ctree_unselect_recursive ()

void                gtk_ctree_unselect_recursive        (GtkCTree *ctree,
                                                         GtkCTreeNode *node);

Warning

gtk_ctree_unselect_recursive is deprecated and should not be used in newly-written code.

Unselect the given node and its subnodes and emit the appropriate signal(s).

ctree :
node :

gtk_ctree_real_select_recursive ()

void                gtk_ctree_real_select_recursive     (GtkCTree *ctree,
                                                         GtkCTreeNode *node,
                                                         gint state);

Warning

gtk_ctree_real_select_recursive is deprecated and should not be used in newly-written code.

The function that implements both gtk_ctree_select_recursive and gtk_ctree_unselect_recursive.

ctree : |
node : |
state : | True for selecting, false for unselecting.

gtk_ctree_node_set_text ()

void                gtk_ctree_node_set_text             (GtkCTree *ctree,
                                                         GtkCTreeNode *node,
                                                         gint column,
                                                         const gchar *text);

Warning

gtk_ctree_node_set_text is deprecated and should not be used in newly-written code.

Set the text in a node.

ctree : |
node : |
column : | The column whose text to change.
text : | The new text.

gtk_ctree_node_set_pixmap ()

void                gtk_ctree_node_set_pixmap           (GtkCTree *ctree,
                                                         GtkCTreeNode *node,
                                                         gint column,
                                                         GdkPixmap *pixmap,
                                                         GdkBitmap *mask);

Warning

gtk_ctree_node_set_pixmap is deprecated and should not be used in newly-written code.

FIXME

ctree :
node :
column :
pixmap :
mask :

gtk_ctree_node_set_pixtext ()

void                gtk_ctree_node_set_pixtext          (GtkCTree *ctree,
                                                         GtkCTreeNode *node,
                                                         gint column,
                                                         const gchar *text,
                                                         guint8 spacing,
                                                         GdkPixmap *pixmap,
                                                         GdkBitmap *mask);

Warning

gtk_ctree_node_set_pixtext is deprecated and should not be used in newly-written code.

FIXME

ctree :
node :
column :
text :
spacing :
pixmap :
mask :

gtk_ctree_set_node_info ()

void                gtk_ctree_set_node_info             (GtkCTree *ctree,
                                                         GtkCTreeNode *node,
                                                         const gchar *text,
                                                         guint8 spacing,
                                                         GdkPixmap *pixmap_closed,
                                                         GdkBitmap *mask_closed,
                                                         GdkPixmap *pixmap_opened,
                                                         GdkBitmap *mask_opened,
                                                         gboolean is_leaf,
                                                         gboolean expanded);

Warning

gtk_ctree_set_node_info is deprecated and should not be used in newly-written code.

Change the information. Most parameters correspond to the parameters of gtk_ctree_insert_node.

ctree : |
node : |
text : | The text to be in the tree column.
spacing : |
pixmap_closed : |
mask_closed : |
pixmap_opened : |
mask_opened : |
is_leaf : |
expanded : |

gtk_ctree_node_set_shift ()

void                gtk_ctree_node_set_shift            (GtkCTree *ctree,
                                                         GtkCTreeNode *node,
                                                         gint column,
                                                         gint vertical,
                                                         gint horizontal);

Warning

gtk_ctree_node_set_shift is deprecated and should not be used in newly-written code.

Shift the given cell the given amounts in pixels.

ctree :
node :
column :
vertical :
horizontal :

gtk_ctree_node_set_selectable ()

void                gtk_ctree_node_set_selectable       (GtkCTree *ctree,
                                                         GtkCTreeNode *node,
                                                         gboolean selectable);

Warning

gtk_ctree_node_set_selectable is deprecated and should not be used in newly-written code.

ctree : |
node : |
selectable : | Whether this node can be selected by the user.

gtk_ctree_node_get_selectable ()

gboolean            gtk_ctree_node_get_selectable       (GtkCTree *ctree,
                                                         GtkCTreeNode *node);

Warning

gtk_ctree_node_get_selectable is deprecated and should not be used in newly-written code.

ctree : |
node : |
Returns : | Whether this node can be selected by the user.

gtk_ctree_node_get_cell_type ()

GtkCellType         gtk_ctree_node_get_cell_type        (GtkCTree *ctree,
                                                         GtkCTreeNode *node,
                                                         gint column);

Warning

gtk_ctree_node_get_cell_type is deprecated and should not be used in newly-written code.

ctree : |
node : |
column : |
Returns : | The type of the given cell.

gtk_ctree_node_get_text ()

gboolean            gtk_ctree_node_get_text             (GtkCTree *ctree,
                                                         GtkCTreeNode *node,
                                                         gint column,
                                                         gchar **text);

Warning

gtk_ctree_node_get_text is deprecated and should not be used in newly-written code.

ctree : |
node : |
column : |
text : | If nonnull, the pointer to the text string is assigned to *text.
Returns : | True if the given cell has text in it.

gtk_ctree_node_get_pixmap ()

gboolean            gtk_ctree_node_get_pixmap           (GtkCTree *ctree,
                                                         GtkCTreeNode *node,
                                                         gint column,
                                                         GdkPixmap **pixmap,
                                                         GdkBitmap **mask);

Warning

gtk_ctree_node_get_pixmap is deprecated and should not be used in newly-written code.

ctree : |
node : |
column : |
pixmap : | If nonnull, the pointer to the pixmap is returned through this.
mask : | If nonnull, the pointer to the mask is returned through this.
Returns : | True if the given cell contains a pixmap.

gtk_ctree_node_get_pixtext ()

gboolean            gtk_ctree_node_get_pixtext          (GtkCTree *ctree,
                                                         GtkCTreeNode *node,
                                                         gint column,
                                                         gchar **text,
                                                         guint8 *spacing,
                                                         GdkPixmap **pixmap,
                                                         GdkBitmap **mask);

Warning

gtk_ctree_node_get_pixtext is deprecated and should not be used in newly-written code.

Get the parameters of a cell containing both a pixmap and text.

ctree :
node :
column :
text :
spacing :
pixmap :
mask :
Returns :

gtk_ctree_get_node_info ()

gboolean            gtk_ctree_get_node_info             (GtkCTree *ctree,
                                                         GtkCTreeNode *node,
                                                         gchar **text,
                                                         guint8 *spacing,
                                                         GdkPixmap **pixmap_closed,
                                                         GdkBitmap **mask_closed,
                                                         GdkPixmap **pixmap_opened,
                                                         GdkBitmap **mask_opened,
                                                         gboolean *is_leaf,
                                                         gboolean *expanded);

Warning

gtk_ctree_get_node_info is deprecated and should not be used in newly-written code.

Get information corresponding to a node. Any of the return parameters can be null.

ctree :
node :
text :
spacing :
pixmap_closed :
mask_closed :
pixmap_opened :
mask_opened :
is_leaf :
expanded :
Returns :

gtk_ctree_node_set_row_style ()

void                gtk_ctree_node_set_row_style        (GtkCTree *ctree,
                                                         GtkCTreeNode *node,
                                                         GtkStyle *style);

Warning

gtk_ctree_node_set_row_style is deprecated and should not be used in newly-written code.

Set the style of a row.

ctree :
node :
style :

gtk_ctree_node_get_row_style ()

GtkStyle*           gtk_ctree_node_get_row_style        (GtkCTree *ctree,
                                                         GtkCTreeNode *node);

Warning

gtk_ctree_node_get_row_style is deprecated and should not be used in newly-written code.

Get the style of a row.

ctree :
node :
Returns :

gtk_ctree_node_set_cell_style ()

void                gtk_ctree_node_set_cell_style       (GtkCTree *ctree,
                                                         GtkCTreeNode *node,
                                                         gint column,
                                                         GtkStyle *style);

Warning

gtk_ctree_node_set_cell_style is deprecated and should not be used in newly-written code.

Set the style of an individual cell.

ctree :
node :
column :
style :

gtk_ctree_node_get_cell_style ()

GtkStyle*           gtk_ctree_node_get_cell_style       (GtkCTree *ctree,
                                                         GtkCTreeNode *node,
                                                         gint column);

Warning

gtk_ctree_node_get_cell_style is deprecated and should not be used in newly-written code.

Get the style of an individual cell.

ctree :
node :
column :
Returns :

gtk_ctree_node_set_foreground ()

void                gtk_ctree_node_set_foreground       (GtkCTree *ctree,
                                                         GtkCTreeNode *node,
                                                         const GdkColor *color);

Warning

gtk_ctree_node_set_foreground is deprecated and should not be used in newly-written code.

ctree :
node :
color :

gtk_ctree_node_set_background ()

void                gtk_ctree_node_set_background       (GtkCTree *ctree,
                                                         GtkCTreeNode *node,
                                                         const GdkColor *color);

Warning

gtk_ctree_node_set_background is deprecated and should not be used in newly-written code.

ctree :
node :
color :

gtk_ctree_node_set_row_data ()

void                gtk_ctree_node_set_row_data         (GtkCTree *ctree,
                                                         GtkCTreeNode *node,
                                                         gpointer data);

Warning

gtk_ctree_node_set_row_data is deprecated and should not be used in newly-written code.

Set the custom data associated with a node.

ctree :
node :
data :

gtk_ctree_node_set_row_data_full ()

void                gtk_ctree_node_set_row_data_full    (GtkCTree *ctree,
                                                         GtkCTreeNode *node,
                                                         gpointer data,
                                                         GtkDestroyNotify destroy);

Warning

gtk_ctree_node_set_row_data_full is deprecated and should not be used in newly-written code.

This is the full interface to setting row data, so that a destructor can be given for the data.

ctree : |
node : |
data : |
destroy : | The routine to be called when data is no longer needed.

gtk_ctree_node_get_row_data ()

gpointer            gtk_ctree_node_get_row_data         (GtkCTree *ctree,
                                                         GtkCTreeNode *node);

Warning

gtk_ctree_node_get_row_data is deprecated and should not be used in newly-written code.

ctree :
node :
Returns :

gtk_ctree_node_moveto ()

void                gtk_ctree_node_moveto               (GtkCTree *ctree,
                                                         GtkCTreeNode *node,
                                                         gint column,
                                                         gfloat row_align,
                                                         gfloat col_align);

Warning

gtk_ctree_node_moveto is deprecated and should not be used in newly-written code.

This function makes the given column of the given node visible by scrolling.

ctree : |
node : | The node to be made visible.
column : | The column to be made visible.
row_align : | Where in the window the row should appear.
col_align : | Where in the window the column should appear.

gtk_ctree_node_is_visible ()

GtkVisibility       gtk_ctree_node_is_visible           (GtkCTree *ctree,
                                                         GtkCTreeNode *node);

Warning

gtk_ctree_node_is_visible is deprecated and should not be used in newly-written code.

ctree : |
node : |
Returns : | True if the node is currently inside the bounds of the window. Note that this function can return true even if the node is not viewable, if the node's ancestor is visible.

gtk_ctree_set_indent ()

void                gtk_ctree_set_indent                (GtkCTree *ctree,
                                                         gint indent);

Warning

gtk_ctree_set_indent is deprecated and should not be used in newly-written code.

ctree : |
indent : | The number of pixels to shift the levels of the tree.

gtk_ctree_set_spacing ()

void                gtk_ctree_set_spacing               (GtkCTree *ctree,
                                                         gint spacing);

Warning

gtk_ctree_set_spacing is deprecated and should not be used in newly-written code.

The spacing between the tree graphic and the actual node content.

ctree :
spacing :

gtk_ctree_set_reorderable()

#define gtk_ctree_set_reorderable(t,r)                    gtk_clist_set_reorderable((GtkCList*) (t),(r))

Warning

gtk_ctree_set_reorderable is deprecated and should not be used in newly-written code.

t :
r :

gtk_ctree_set_line_style ()

void                gtk_ctree_set_line_style            (GtkCTree *ctree,
                                                         GtkCTreeLineStyle line_style);

Warning

gtk_ctree_set_line_style is deprecated and should not be used in newly-written code.

ctree :
line_style :

gtk_ctree_set_expander_style ()

void                gtk_ctree_set_expander_style        (GtkCTree *ctree,
                                                         GtkCTreeExpanderStyle expander_style);

Warning

gtk_ctree_set_expander_style is deprecated and should not be used in newly-written code.

ctree :
expander_style :

gtk_ctree_set_drag_compare_func ()

void                gtk_ctree_set_drag_compare_func     (GtkCTree *ctree,
                                                         GtkCTreeCompareDragFunc cmp_func);

Warning

gtk_ctree_set_drag_compare_func is deprecated and should not be used in newly-written code.

FIXME

ctree :
cmp_func :

gtk_ctree_sort_node ()

void                gtk_ctree_sort_node                 (GtkCTree *ctree,
                                                         GtkCTreeNode *node);

Warning

gtk_ctree_sort_node is deprecated and should not be used in newly-written code.

Sort the children of a node. See GtkCList for how to set the sorting criteria etc.

ctree :
node :

gtk_ctree_sort_recursive ()

void                gtk_ctree_sort_recursive            (GtkCTree *ctree,
                                                         GtkCTreeNode *node);

Warning

gtk_ctree_sort_recursive is deprecated and should not be used in newly-written code.

Sort the descendants of a node. See GtkCList for how to set the sorting criteria etc.

ctree :
node :

gtk_ctree_node_nth ()

GtkCTreeNode*       gtk_ctree_node_nth                  (GtkCTree *ctree,
                                                         guint row);

Warning

gtk_ctree_node_nth is deprecated and should not be used in newly-written code.

ctree : |
row : |
Returns : | The node corresponding to the row th row.

gtk_ctree_set_show_stub ()

void                gtk_ctree_set_show_stub             (GtkCTree *ctree,
                                                         gboolean show_stub);

Warning

gtk_ctree_set_show_stub is deprecated and should not be used in newly-written code.

ctree :
show_stub :

Property Details

The "expander-style" property

  "expander-style"           GtkCTreeExpanderStyle  : Read / Write

The style of the expander buttons.

Default value: GTK_CTREE_EXPANDER_NONE

The "indent" property

  "indent"                   guint                 : Read / Write

The number of pixels to indent the tree levels.

Default value: 0

The "line-style" property

  "line-style"               GtkCTreeLineStyle     : Read / Write

The style of the lines in the tree graphic.

Default value: GTK_CTREE_LINES_NONE

The "n-columns" property

  "n-columns"                guint                 : Read / Write / Construct Only

The number of columns in the tree.

Default value: 0

The "show-stub" property

  "show-stub"                gboolean              : Read / Write

Default value: FALSE

The "spacing" property

  "spacing"                  guint                 : Read / Write

The number of pixels between the tree and the columns.

Default value: 0

The "tree-column" property

  "tree-column"              guint                 : Read / Write / Construct Only

The column in which the actual tree graphic appears.

Default value: 0

Signal Details

The "change-focus-row-expansion" signal

void                user_function                      (GtkCTree             *ctree,
                                                        GtkCTreeExpansionType expansion,
                                                        gpointer              user_data)      : Run Last / Action

The row which has the focus is either collapsed or expanded or toggled.

ctree : | the object which received the signal.
expansion : | What is being done.
user_data : | user data set when the signal handler was connected.

The "tree-collapse" signal

void                user_function                      (GtkCTree     *ctree,
                                                        GtkCTreeNode *node,
                                                        gpointer      user_data)      : Run Last

Emitted when a node is collapsed.

ctree : | the object which received the signal.
node : |
user_data : | user data set when the signal handler was connected.

The "tree-expand" signal

void                user_function                      (GtkCTree     *ctree,
                                                        GtkCTreeNode *node,
                                                        gpointer      user_data)      : Run Last

Emitted when a node is expanded.

ctree : | the object which received the signal.
node : |
user_data : | user data set when the signal handler was connected.

The "tree-move" signal

void                user_function                      (GtkCTree     *ctree,
                                                        GtkCTreeNode *node,
                                                        GtkCTreeNode *new_parent,
                                                        GtkCTreeNode *new_sibling,
                                                        gpointer      user_data)        : Run Last

Emitted when a node is moved.

ctree : | the object which received the signal.
node : | The node that is moved.
new_parent : | The new parent of the node.
new_sibling : | The new sibling of the node.
user_data : | user data set when the signal handler was connected.

The "tree-select-row" signal

void                user_function                      (GtkCTree     *ctree,
                                                        GtkCTreeNode *node,
                                                        gint          column,
                                                        gpointer      user_data)      : Run First

Emitted when a row is selected.

ctree : | the object which received the signal.
node : | The node corresponding to the selected row.
column : | The column which was selected.
user_data : | user data set when the signal handler was connected.

The "tree-unselect-row" signal

void                user_function                      (GtkCTree     *ctree,
                                                        GtkCTreeNode *node,
                                                        gint          column,
                                                        gpointer      user_data)      : Run First

Emitted when a node is unselected.

ctree : | the object which received the signal.
node : | The node corresponding to the selected row.
column : |
user_data : | user data set when the signal handler was connected.


GtkCurve

GtkCurve — Allows direct editing of a curve

Synopsis

#include <gtk/gtk.h>

                    GtkCurve;
GtkWidget*          gtk_curve_new                       (void);
void                gtk_curve_reset                     (GtkCurve *curve);
void                gtk_curve_set_gamma                 (GtkCurve *curve,
                                                         gfloat gamma_);
void                gtk_curve_set_range                 (GtkCurve *curve,
                                                         gfloat min_x,
                                                         gfloat max_x,
                                                         gfloat min_y,
                                                         gfloat max_y);
void                gtk_curve_get_vector                (GtkCurve *curve,
                                                         int veclen,
                                                         gfloat vector[]);
void                gtk_curve_set_vector                (GtkCurve *curve,
                                                         int veclen,
                                                         gfloat vector[]);
void                gtk_curve_set_curve_type            (GtkCurve *curve,
                                                         GtkCurveType type);

Object Hierarchy

  GObject
   +----GInitiallyUnowned
         +----GtkObject
               +----GtkWidget
                     +----GtkDrawingArea
                           +----GtkCurve

Implemented Interfaces

GtkCurve implements AtkImplementorIface.

Properties

  "curve-type"               GtkCurveType          : Read / Write
  "max-x"                    gfloat                : Read / Write
  "max-y"                    gfloat                : Read / Write
  "min-x"                    gfloat                : Read / Write
  "min-y"                    gfloat                : Read / Write

Signals

  "curve-type-changed"                             : Run First

Description

Note

This widget is considered too specialized/little-used for GTK+, and will in the future be moved to some other package. If your application needs this widget, feel free to use it, as the widget does work and is useful in some applications; it's just not of general interest. However, we are not accepting new features for the widget, and it will eventually move out of the GTK+ distribution.

The GtkCurve widget allows the user to edit a curve covering a range of values. It is typically used to fine-tune color balances in graphics applications like the Gimp.

The GtkCurve widget has 3 modes of operation - spline, linear and free. In spline mode the user places points on the curve which are automatically connected together into a smooth curve. In linear mode the user places points on the curve which are connected by straight lines. In free mode the user can draw the points of the curve freely, and they are not connected at all.

Details

GtkCurve

typedef struct _GtkCurve GtkCurve;

The GtkCurve struct contains private data only, and should be accessed using the functions below.

gtk_curve_new ()

GtkWidget*          gtk_curve_new                       (void);

Creates a new GtkCurve.

Returns : a new GtkCurve.

gtk_curve_reset ()

void                gtk_curve_reset                     (GtkCurve *curve);

Resets the curve to a straight line from the minimum x and y values to the maximum x and y values (i.e. from the bottom-left to the top-right corners). The curve type is not changed.

curve : a GtkCurve.

gtk_curve_set_gamma ()

void                gtk_curve_set_gamma                 (GtkCurve *curve,
                                                         gfloat gamma_);

Recomputes the entire curve using the given gamma value. A gamma value of 1 results in a straight line. Values greater than 1 result in a curve above the straight line. Values less than 1 result in a curve below the straight line. The curve type is changed to GTK_CURVE_TYPE_FREE. FIXME: Needs a more precise definition of gamma.

curve : | a GtkCurve.
gamma_ : | the gamma value.

gtk_curve_set_range ()

void                gtk_curve_set_range                 (GtkCurve *curve,
                                                         gfloat min_x,
                                                         gfloat max_x,
                                                         gfloat min_y,
                                                         gfloat max_y);

Sets the minimum and maximum x and y values of the curve. The curve is also reset with a call to gtk_curve_reset().

curve : | a GtkCurve.
min_x : | the minimum x value.
max_x : | the maximum x value.
min_y : | the minimum y value.
max_y : | the maximum y value.

gtk_curve_get_vector ()

void                gtk_curve_get_vector                (GtkCurve *curve,
                                                         int veclen,
                                                         gfloat vector[]);

Returns a vector of points representing the curve.

curve : | a GtkCurve.
veclen : | the number of points to calculate.
vector : | returns the points.

gtk_curve_set_vector ()

void                gtk_curve_set_vector                (GtkCurve *curve,
                                                         int veclen,
                                                         gfloat vector[]);

Sets the vector of points on the curve. The curve type is set to GTK_CURVE_TYPE_FREE.

curve : | a GtkCurve.
veclen : | the number of points.
vector : | the points on the curve.

gtk_curve_set_curve_type ()

void                gtk_curve_set_curve_type            (GtkCurve *curve,
                                                         GtkCurveType type);

Sets the type of the curve. The curve will remain unchanged except when changing from a free curve to a linear or spline curve, in which case the curve will be changed as little as possible.

curve : | a GtkCurve.
type : | the type of the curve.

Property Details

The "curve-type" property

  "curve-type"               GtkCurveType          : Read / Write

Is this curve linear, spline interpolated, or free-form.

Default value: GTK_CURVE_TYPE_LINEAR

The "max-x" property

  "max-x"                    gfloat                : Read / Write

Maximum possible X value.

Default value: 1

The "max-y" property

  "max-y"                    gfloat                : Read / Write

Maximum possible value for Y.

Default value: 1

The "min-x" property

  "min-x"                    gfloat                : Read / Write

Minimum possible value for X.

Default value: 0

The "min-y" property

  "min-y"                    gfloat                : Read / Write

Minimum possible value for Y.

Default value: 0

Signal Details

The "curve-type-changed" signal

void                user_function                      (GtkCurve *curve,
                                                        gpointer  user_data)      : Run First

Emitted when the curve type has been changed. The curve type can be changed explicitly with a call to gtk_curve_set_curve_type(). It is also changed as a side-effect of calling gtk_curve_reset() or gtk_curve_set_gamma().

curve : | the object which received the signal.
user_data : | user data set when the signal handler was connected.

See Also

GtkGammaCurve

a subclass for editing gamma curves.


GtkDialog

GtkDialog — Create popup windows

Synopsis

#include <gtk/gtk.h>

                    GtkDialog;
enum                GtkDialogFlags;
enum                GtkResponseType;
GtkWidget*          gtk_dialog_new                      (void);
GtkWidget*          gtk_dialog_new_with_buttons         (const gchar *title,
                                                         GtkWindow *parent,
                                                         GtkDialogFlags flags,
                                                         const gchar *first_button_text,
                                                         ...);
gint                gtk_dialog_run                      (GtkDialog *dialog);
void                gtk_dialog_response                 (GtkDialog *dialog,
                                                         gint response_id);
GtkWidget*          gtk_dialog_add_button               (GtkDialog *dialog,
                                                         const gchar *button_text,
                                                         gint response_id);
void                gtk_dialog_add_buttons              (GtkDialog *dialog,
                                                         const gchar *first_button_text,
                                                         ...);
void                gtk_dialog_add_action_widget        (GtkDialog *dialog,
                                                         GtkWidget *child,
                                                         gint response_id);
gboolean            gtk_dialog_get_has_separator        (GtkDialog *dialog);
void                gtk_dialog_set_default_response     (GtkDialog *dialog,
                                                         gint response_id);
void                gtk_dialog_set_has_separator        (GtkDialog *dialog,
                                                         gboolean setting);
void                gtk_dialog_set_response_sensitive   (GtkDialog *dialog,
                                                         gint response_id,
                                                         gboolean setting);
gint                gtk_dialog_get_response_for_widget  (GtkDialog *dialog,
                                                         GtkWidget *widget);

gboolean            gtk_alternative_dialog_button_order (GdkScreen *screen);
void                gtk_dialog_set_alternative_button_order
                                                        (GtkDialog *dialog,
                                                         gint first_response_id,
                                                         ...);
void                gtk_dialog_set_alternative_button_order_from_array
                                                        (GtkDialog *dialog,
                                                         gint n_params,
                                                         gint *new_order);

Object Hierarchy

  GObject
   +----GInitiallyUnowned
         +----GtkObject
               +----GtkWidget
                     +----GtkContainer
                           +----GtkBin
                                 +----GtkWindow
                                       +----GtkDialog
                                             +----GtkAboutDialog
                                             +----GtkColorSelectionDialog
                                             +----GtkFileChooserDialog
                                             +----GtkFileSelection
                                             +----GtkFontSelectionDialog
                                             +----GtkInputDialog
                                             +----GtkMessageDialog
                                             +----GtkPageSetupUnixDialog
                                             +----GtkPrintUnixDialog
                                             +----GtkRecentChooserDialog

Implemented Interfaces

GtkDialog implements AtkImplementorIface.

Properties

  "has-separator"            gboolean              : Read / Write

Style Properties

  "action-area-border"       gint                  : Read
  "button-spacing"           gint                  : Read
  "content-area-border"      gint                  : Read

Signals

  "close"                                          : Run Last / Action
  "response"                                       : Run Last

Description

Dialog boxes are a convenient way to prompt the user for a small amount of input, e.g. to display a message, ask a question, or anything else that does not require extensive effort on the user's part.

GTK+ treats a dialog as a window split vertically. The top section is a GtkVBox, and is where widgets such as a GtkLabel or a GtkEntry should be packed. The bottom area is known as the action_area. This is generally used for packing buttons into the dialog which may perform functions such as cancel, ok, or apply. The two areas are separated by a GtkHSeparator.

GtkDialog boxes are created with a call to gtk_dialog_new() or gtk_dialog_new_with_buttons(). gtk_dialog_new_with_buttons() is recommended; it allows you to set the dialog title, some convenient flags, and add simple buttons.

If 'dialog' is a newly created dialog, the two primary areas of the window can be accessed as GTK_DIALOG(dialog)->vbox and GTK_DIALOG(dialog)->action_area, as can be seen from the example, below.

A 'modal' dialog (that is, one which freezes the rest of the application from user input), can be created by calling gtk_window_set_modal() on the dialog. Use the GTK_WINDOW() macro to cast the widget returned from gtk_dialog_new() into a GtkWindow. When using gtk_dialog_new_with_buttons() you can also pass the GTK_DIALOG_MODAL flag to make a dialog modal.

If you add buttons to GtkDialog using gtk_dialog_new_with_buttons(), gtk_dialog_add_button(), gtk_dialog_add_buttons(), or gtk_dialog_add_action_widget(), clicking the button will emit a signal called "response" with a response ID that you specified. GTK+ will never assign a meaning to positive response IDs; these are entirely user-defined. But for convenience, you can use the response IDs in the GtkResponseType enumeration (these all have values less than zero). If a dialog receives a delete event, the "response" signal will be emitted with a response ID of GTK_RESPONSE_DELETE_EVENT.

If you want to block waiting for a dialog to return before returning control flow to your code, you can call gtk_dialog_run(). This function enters a recursive main loop and waits for the user to respond to the dialog, returning the response ID corresponding to the button the user clicked.

For the simple dialog in the following example, in reality you'd probably use GtkMessageDialog to save yourself some effort. But you'd need to create the dialog contents manually if you had more than a simple message in the dialog.

Example 4. Simple GtkDialog usage.

/* Function to open a dialog box displaying the message provided. */

void quick_message (gchar *message) {

   GtkWidget *dialog, *label;

   /* Create the widgets */

   dialog = gtk_dialog_new_with_buttons ("Message",
                                         main_application_window,
                                         GTK_DIALOG_DESTROY_WITH_PARENT,
                                         GTK_STOCK_OK,
                                         GTK_RESPONSE_NONE,
                                         NULL);
   label = gtk_label_new (message);

   /* Ensure that the dialog box is destroyed when the user responds. */

   g_signal_connect_swapped (dialog,
                             "response",
                             G_CALLBACK (gtk_widget_destroy),
                             dialog);

   /* Add the label, and show everything we've added to the dialog. */

   gtk_container_add (GTK_CONTAINER (GTK_DIALOG(dialog)->vbox),
                      label);
   gtk_widget_show_all (dialog);
}

Details

GtkDialog

typedef struct {
  GtkWidget *vbox;
  GtkWidget *action_area;
} GtkDialog;

vbox is a GtkVBox - the main part of the dialog box.

action_area is a GtkHButtonBox packed below the dividing GtkHSeparator in the dialog. It is treated exactly the same as any other GtkHButtonBox.

enum GtkDialogFlags

typedef enum
{
  GTK_DIALOG_MODAL               = 1 << 0, /* call gtk_window_set_modal (win, TRUE) */
  GTK_DIALOG_DESTROY_WITH_PARENT = 1 << 1, /* call gtk_window_set_destroy_with_parent () */
  GTK_DIALOG_NO_SEPARATOR        = 1 << 2  /* no separator bar above buttons */
} GtkDialogFlags;

Flags used to influence dialog construction.

GTK_DIALOG_MODAL | Make the constructed dialog modal, see gtk_widget_set_modal().
GTK_DIALOG_DESTROY_WITH_PARENT | Destroy the dialog when its parent is destroyed, see gtk_window_set_destroy_with_parent().
GTK_DIALOG_NO_SEPARATOR | Don't put a separator between the action area and the dialog content.

enum GtkResponseType

typedef enum
{
  /* GTK returns this if a response widget has no response_id,
   * or if the dialog gets programmatically hidden or destroyed.
   */
  GTK_RESPONSE_NONE = -1,

  /* GTK won't return these unless you pass them in
   * as the response for an action widget. They are
   * for your convenience.
   */
  GTK_RESPONSE_REJECT = -2,
  GTK_RESPONSE_ACCEPT = -3,

  /* If the dialog is deleted. */
  GTK_RESPONSE_DELETE_EVENT = -4,

  /* These are returned from GTK dialogs, and you can also use them
   * yourself if you like.
   */
  GTK_RESPONSE_OK     = -5,
  GTK_RESPONSE_CANCEL = -6,
  GTK_RESPONSE_CLOSE  = -7,
  GTK_RESPONSE_YES    = -8,
  GTK_RESPONSE_NO     = -9,
  GTK_RESPONSE_APPLY  = -10,
  GTK_RESPONSE_HELP   = -11
} GtkResponseType;

Predefined values for use as response ids in gtk_dialog_add_button(). All predefined values are negative, GTK+ leaves positive values for application-defined response ids.

GTK_RESPONSE_NONE | Returned if an action widget has no response id, or if the dialog gets programmatically hidden or destroyed.
GTK_RESPONSE_REJECT | Generic response id, not used by GTK+ dialogs.
GTK_RESPONSE_ACCEPT | Generic response id, not used by GTK+ dialogs.
GTK_RESPONSE_DELETE_EVENT | Returned if the dialog is deleted.
GTK_RESPONSE_OK | Returned by OK buttons in GTK+ dialogs.
GTK_RESPONSE_CANCEL | Returned by Cancel buttons in GTK+ dialogs.
GTK_RESPONSE_CLOSE | Returned by Close buttons in GTK+ dialogs.
GTK_RESPONSE_YES | Returned by Yes buttons in GTK+ dialogs.
GTK_RESPONSE_NO | Returned by No buttons in GTK+ dialogs.
GTK_RESPONSE_APPLY | Returned by Apply buttons in GTK+ dialogs.
GTK_RESPONSE_HELP | Returned by Help buttons in GTK+ dialogs.

gtk_dialog_new ()

GtkWidget*          gtk_dialog_new                      (void);

Creates a new dialog box. Widgets should not be packed into this GtkWindow directly, but into the vbox and action_area, as described above.

Returns : a new GtkDialog.

gtk_dialog_new_with_buttons ()

GtkWidget*          gtk_dialog_new_with_buttons         (const gchar *title,
                                                         GtkWindow *parent,
                                                         GtkDialogFlags flags,
                                                         const gchar *first_button_text,
                                                         ...);

Creates a new GtkDialog with title title (or NULL for the default title; see gtk_window_set_title()) and transient parent parent (or NULL for none; see gtk_window_set_transient_for()). The flags argument can be used to make the dialog modal (GTK_DIALOG_MODAL) and/or to have it destroyed along with its transient parent (GTK_DIALOG_DESTROY_WITH_PARENT). After flags, button text/response ID pairs should be listed, with a NULL pointer ending the list. Button text can be either a stock ID such as GTK_STOCK_OK, or some arbitrary text. A response ID can be any positive number, or one of the values in the GtkResponseType enumeration. If the user clicks one of these dialog buttons, GtkDialog will emit the "response" signal with the corresponding response ID. If a GtkDialog receives the "delete_event" signal, it will emit "response" with a response ID of GTK_RESPONSE_DELETE_EVENT. However, destroying a dialog does not emit the "response" signal; so be careful relying on "response" when using the GTK_DIALOG_DESTROY_WITH_PARENT flag. Buttons are from left to right, so the first button in the list will be the leftmost button in the dialog.

Here's a simple example:

 GtkWidget *dialog = gtk_dialog_new_with_buttons ("My dialog",
                                                  main_app_window,
                                                  GTK_DIALOG_MODAL | GTK_DIALOG_DESTROY_WITH_PARENT,
                                                  GTK_STOCK_OK,
                                                  GTK_RESPONSE_ACCEPT,
                                                  GTK_STOCK_CANCEL,
                                                  GTK_RESPONSE_REJECT,
                                                  NULL);

title : | Title of the dialog, or NULL
parent : | Transient parent of the dialog, or NULL
flags : | from GtkDialogFlags
first_button_text : | stock ID or text to go in first button, or NULL
... : | response ID for first button, then additional buttons, ending with NULL
Returns : | a new GtkDialog

gtk_dialog_run ()

gint                gtk_dialog_run                      (GtkDialog *dialog);

Blocks in a recursive main loop until the dialog either emits the response signal, or is destroyed. If the dialog is destroyed during the call to gtk_dialog_run(), gtk_dialog_returns GTK_RESPONSE_NONE. Otherwise, it returns the response ID from the "response" signal emission. Before entering the recursive main loop, gtk_dialog_run() calls gtk_widget_show() on the dialog for you. Note that you still need to show any children of the dialog yourself.

During gtk_dialog_run(), the default behavior of "delete_event" is disabled; if the dialog receives "delete_event", it will not be destroyed as windows usually are, and gtk_dialog_run() will return GTK_RESPONSE_DELETE_EVENT. Also, during gtk_dialog_run() the dialog will be modal. You can force gtk_dialog_run() to return at any time by calling gtk_dialog_response() to emit the "response" signal. Destroying the dialog during gtk_dialog_run() is a very bad idea, because your post-run code won't know whether the dialog was destroyed or not.

After gtk_dialog_run() returns, you are responsible for hiding or destroying the dialog if you wish to do so.

Typical usage of this function might be:

  gint result = gtk_dialog_run (GTK_DIALOG (dialog));
  switch (result)
    {
      case GTK_RESPONSE_ACCEPT:
         do_application_specific_something ();
         break;
      default:
         do_nothing_since_dialog_was_cancelled ();
         break;
    }
  gtk_widget_destroy (dialog);

Note that even though the recursive main loop gives the effect of a modal dialog (it prevents the user from interacting with other windows in the same window group while the dialog is run), callbacks such as timeouts, IO channel watches, DND drops, etc, will be triggered during a gtk_dialog_run() call.

dialog : | a GtkDialog
Returns : | response ID

gtk_dialog_response ()

void                gtk_dialog_response                 (GtkDialog *dialog,
                                                         gint response_id);

Emits the "response" signal with the given response ID. Used to indicate that the user has responded to the dialog in some way; typically either you or gtk_dialog_run() will be monitoring the "response" signal and take appropriate action.

dialog : | a GtkDialog
response_id : | response ID

gtk_dialog_add_button ()

GtkWidget*          gtk_dialog_add_button               (GtkDialog *dialog,
                                                         const gchar *button_text,
                                                         gint response_id);

Adds a button with the given text (or a stock button, if button_text is a stock ID) and sets things up so that clicking the button will emit the "response" signal with the given response_id. The button is appended to the end of the dialog's action area. The button widget is returned, but usually you don't need it.

dialog : | a GtkDialog
button_text : | text of button, or stock ID
response_id : | response ID for the button
Returns : | the button widget that was added

gtk_dialog_add_buttons ()

void                gtk_dialog_add_buttons              (GtkDialog *dialog,
                                                         const gchar *first_button_text,
                                                         ...);

Adds more buttons, same as calling gtk_dialog_add_button() repeatedly. The variable argument list should be NULL-terminated as with gtk_dialog_new_with_buttons(). Each button must have both text and response ID.

dialog : | a GtkDialog
first_button_text : | button text or stock ID
... : | response ID for first button, then more text-response_id pairs

gtk_dialog_add_action_widget ()

void                gtk_dialog_add_action_widget        (GtkDialog *dialog,
                                                         GtkWidget *child,
                                                         gint response_id);

Adds an activatable widget to the action area of a GtkDialog, connecting a signal handler that will emit the "response" signal on the dialog when the widget is activated. The widget is appended to the end of the dialog's action area. If you want to add a non-activatable widget, simply pack it into the action_area field of the GtkDialog struct.

dialog : | a GtkDialog
child : | an activatable widget
response_id : | response ID for child

gtk_dialog_get_has_separator ()

gboolean            gtk_dialog_get_has_separator        (GtkDialog *dialog);

Accessor for whether the dialog has a separator.

dialog : | a GtkDialog
Returns : | TRUE if the dialog has a separator

gtk_dialog_set_default_response ()

void                gtk_dialog_set_default_response     (GtkDialog *dialog,
                                                         gint response_id);

Sets the last widget in the dialog's action area with the given response_id as the default widget for the dialog. Pressing "Enter" normally activates the default widget.

dialog : | a GtkDialog
response_id : | a response ID

gtk_dialog_set_has_separator ()

void                gtk_dialog_set_has_separator        (GtkDialog *dialog,
                                                         gboolean setting);

Sets whether the dialog has a separator above the buttons. TRUE by default.

dialog : | a GtkDialog
setting : | TRUE to have a separator

gtk_dialog_set_response_sensitive ()

void                gtk_dialog_set_response_sensitive   (GtkDialog *dialog,
                                                         gint response_id,
                                                         gboolean setting);

Calls gtk_widget_set_sensitive (widget, setting) for each widget in the dialog's action area with the given response_id. A convenient way to sensitize/desensitize dialog buttons.

dialog : | a GtkDialog
response_id : | a response ID
setting : | TRUE for sensitive

gtk_dialog_get_response_for_widget ()

gint                gtk_dialog_get_response_for_widget  (GtkDialog *dialog,
                                                         GtkWidget *widget);

Gets the response id of a widget in the action area of a dialog.

dialog : | a GtkDialog
widget : | a widget in the action area of dialog
Returns : | the response id of widget, or GTK_RESPONSE_NONE if widget doesn't have a response id set.

Since 2.8

gtk_alternative_dialog_button_order ()

gboolean            gtk_alternative_dialog_button_order (GdkScreen *screen);

Returns TRUE if dialogs are expected to use an alternative button order on the screen screen. See gtk_dialog_set_alternative_button_order() for more details about alternative button order.

If you need to use this function, you should probably connect to the ::notify:gtk-alternative-button-order signal on the GtkSettings object associated to screen, in order to be notified if the button order setting changes.

screen : | a GdkScreen, or NULL to use the default screen
Returns : | Whether the alternative button order should be used

Since 2.6

gtk_dialog_set_alternative_button_order ()

void                gtk_dialog_set_alternative_button_order
                                                        (GtkDialog *dialog,
                                                         gint first_response_id,
                                                         ...);

Sets an alternative button order. If the gtk-alternative-button-order setting is set to TRUE, the dialog buttons are reordered according to the order of the response ids passed to this function.

By default, GTK+ dialogs use the button order advocated by the Gnome Human Interface Guidelines with the affirmative button at the far right, and the cancel button left of it. But the builtin GTK+ dialogs and GtkMessageDialogs do provide an alternative button order, which is more suitable on some platforms, e.g. Windows.

Use this function after adding all the buttons to your dialog, as the following example shows:

cancel_button = gtk_dialog_add_button (GTK_DIALOG (dialog),
                                       GTK_STOCK_CANCEL,
                                       GTK_RESPONSE_CANCEL);

ok_button = gtk_dialog_add_button (GTK_DIALOG (dialog),
                                   GTK_STOCK_OK,
                                   GTK_RESPONSE_OK);

gtk_widget_grab_default (ok_button);

help_button = gtk_dialog_add_button (GTK_DIALOG (dialog),
                                     GTK_STOCK_HELP,
                                     GTK_RESPONSE_HELP);

gtk_dialog_set_alternative_button_order (GTK_DIALOG (dialog),
                                         GTK_RESPONSE_OK,
                                         GTK_RESPONSE_CANCEL,
                                         GTK_RESPONSE_HELP,
                                         -1);

dialog : | a GtkDialog
first_response_id : | a response id used by one dialog's buttons
... : | a list of more response ids of dialog's buttons, terminated by -1

Since 2.6

gtk_dialog_set_alternative_button_order_from_array ()

void                gtk_dialog_set_alternative_button_order_from_array
                                                        (GtkDialog *dialog,
                                                         gint n_params,
                                                         gint *new_order);

Sets an alternative button order. If the gtk-alternative-button-order setting is set to TRUE, the dialog buttons are reordered according to the order of the response ids in new_order.

See gtk_dialog_set_alternative_button_order() for more information.

This function is for use by language bindings.

dialog : | a GtkDialog
n_params : | the number of response ids in new_order
new_order : | an array of response ids of dialog's buttons

Since 2.6

Property Details

The "has-separator" property

  "has-separator"            gboolean              : Read / Write

The dialog has a separator bar above its buttons.

Default value: TRUE

Style Property Details

The "action-area-border" style property

  "action-area-border"       gint                  : Read

Width of border around the button area at the bottom of the dialog.

Allowed values: >= 0

Default value: 5

The "button-spacing" style property

  "button-spacing"           gint                  : Read

Spacing between buttons.

Allowed values: >= 0

Default value: 6

The "content-area-border" style property

  "content-area-border"      gint                  : Read

Width of border around the main dialog area.

Allowed values: >= 0

Default value: 2

Signal Details

The "close" signal

void                user_function                      (GtkDialog *dialog,
                                                        gpointer   user_data)      : Run Last / Action

dialog : | the object which received the signal.
user_data : | user data set when the signal handler was connected.

The "response" signal

void                user_function                      (GtkDialog *dialog,
                                                        gint       arg1,
                                                        gpointer   user_data)      : Run Last

Emitted when an action widget is clicked, the dialog receives a delete event, or the application programmer calls gtk_dialog_response(). On a delete event, the response ID is GTK_RESPONSE_NONE. Otherwise, it depends on which action widget was clicked.

dialog : | the object which received the signal.
arg1 : | the response ID
user_data : | user data set when the signal handler was connected.

See Also

GtkVBox | Pack widgets vertically.
GtkWindow | Alter the properties of your dialog box.
GtkButton | Add them to the action_area to get a response from the user.


GtkDrawingArea

GtkDrawingArea — A widget for custom user interface elements

Synopsis

#include <gtk/gtk.h>

                    GtkDrawingArea;
GtkWidget*          gtk_drawing_area_new                (void);
void                gtk_drawing_area_size               (GtkDrawingArea *darea,
                                                         gint width,
                                                         gint height);

Object Hierarchy

  GObject
   +----GInitiallyUnowned
         +----GtkObject
               +----GtkWidget
                     +----GtkDrawingArea
                           +----GtkCurve

Implemented Interfaces

GtkDrawingArea implements AtkImplementorIface.

Description

The GtkDrawingArea widget is used for creating custom user interface elements. It's essentially a blank widget; you can draw on widget->window. After creating a drawing area, the application may want to connect to:

  • Mouse and button press signals to respond to input from the user. (Use gtk_widget_add_events() to enable events you wish to receive.)

  • The "realize" signal to take any necessary actions when the widget is instantiated on a particular display. (Create GDK resources in response to this signal.)

  • The "configure_event" signal to take any necessary actions when the widget changes size.

  • The "expose_event" signal to handle redrawing the contents of the widget.

The following code portion demonstrates using a drawing area to display a circle in the normal widget foreground color. Note that GDK automatically clears the exposed area to the background color before sending the expose event, and that drawing is implicitly clipped to the exposed area.

Example 33. Simple GtkDrawingArea usage.

gboolean
expose_event_callback (GtkWidget *widget, GdkEventExpose *event, gpointer data)
{
  gdk_draw_arc (widget->window,
                widget->style->fg_gc[GTK_WIDGET_STATE (widget)],
                TRUE,
                0, 0, widget->allocation.width, widget->allocation.height,
                0, 64 * 360);

  return TRUE;
}
[...]
  GtkWidget *drawing_area = gtk_drawing_area_new ();
  gtk_widget_set_size_request (drawing_area, 100, 100);
  g_signal_connect (G_OBJECT (drawing_area), "expose_event",
                    G_CALLBACK (expose_event_callback), NULL);

Expose events are normally delivered when a drawing area first comes onscreen, or when it's covered by another window and then uncovered (exposed). You can also force an expose event by adding to the "damage region" of the drawing area's window; gtk_widget_queue_draw_area() and gdk_window_invalidate_rect() are equally good ways to do this. You'll then get an expose event for the invalid region.

The available routines for drawing are documented on the GDK Drawing Primitives page. See also gdk_pixbuf_render_to_drawable() for drawing a GdkPixbuf.

To receive mouse events on a drawing area, you will need to enable them with gtk_widget_add_events(). To receive keyboard events, you will need to set the GTK_CAN_FOCUS flag on the drawing area, and should probably draw some user-visible indication that the drawing area is focused. Use the GTK_HAS_FOCUS() macro in your expose event handler to decide whether to draw the focus indicator. See gtk_paint_focus() for one way to draw focus.

Details

GtkDrawingArea

typedef struct _GtkDrawingArea GtkDrawingArea;

The GtkDrawingArea struct contains private data only, and should be accessed using the functions below.

gtk_drawing_area_new ()

GtkWidget*          gtk_drawing_area_new                (void);

Creates a new drawing area.

Returns : a new GtkDrawingArea

gtk_drawing_area_size ()

void                gtk_drawing_area_size               (GtkDrawingArea *darea,
                                                         gint width,
                                                         gint height);

Warning

gtk_drawing_area_size is deprecated and should not be used in newly-written code.

(Use gtk_widget_set_size_request() instead.) Sets the size that the drawing area will request in response to a "size_request" signal. The drawing area may actually be allocated a size larger than this depending on how it is packed within the enclosing containers.

darea : | a GtkDrawingArea.
width : | the width to request.
height : | the height to request.

See Also

Sometimes GtkImage is a useful alternative to a drawing area. You can put a GdkPixmap in the GtkImage and draw to the GdkPixmap, calling gtk_widget_queue_draw() on the GtkImage when you want to refresh to the screen.


GtkEditable

GtkEditable — Interface for text-editing widgets

Synopsis

#include <gtk/gtk.h>

                    GtkEditable;
void                gtk_editable_select_region          (GtkEditable *editable,
                                                         gint start,
                                                         gint end);
gboolean            gtk_editable_get_selection_bounds   (GtkEditable *editable,
                                                         gint *start,
                                                         gint *end);
void                gtk_editable_insert_text            (GtkEditable *editable,
                                                         const gchar *new_text,
                                                         gint new_text_length,
                                                         gint *position);
void                gtk_editable_delete_text            (GtkEditable *editable,
                                                         gint start_pos,
                                                         gint end_pos);
gchar*              gtk_editable_get_chars              (GtkEditable *editable,
                                                         gint start_pos,
                                                         gint end_pos);
void                gtk_editable_cut_clipboard          (GtkEditable *editable);
void                gtk_editable_copy_clipboard         (GtkEditable *editable);
void                gtk_editable_paste_clipboard        (GtkEditable *editable);
void                gtk_editable_delete_selection       (GtkEditable *editable);
void                gtk_editable_set_position           (GtkEditable *editable,
                                                         gint position);
gint                gtk_editable_get_position           (GtkEditable *editable);
void                gtk_editable_set_editable           (GtkEditable *editable,
                                                         gboolean is_editable);
gboolean            gtk_editable_get_editable           (GtkEditable *editable);

Object Hierarchy

  GInterface
   +----GtkEditable

Known Implementations

GtkEditable is implemented by GtkEntry, GtkOldEditable, GtkSpinButton and GtkText.

Signals

  "changed"                                        : Run Last
  "delete-text"                                    : Run Last
  "insert-text"                                    : Run Last

Description

The GtkEditable interface is an interface which should be implemented by text editing widgets, such as GtkEntry and GtkText. It contains functions for generically manipulating an editable widget, a large number of action signals used for key bindings, and several signals that an application can connect to to modify the behavior of a widget.

As an example of the latter usage, by connecting the following handler to "insert_text", an application can convert all entry into a widget into uppercase.

Example 13. Forcing entry to uppercase.

#include <ctype.h>

void
insert_text_handler (GtkEditable *editable,
                     const gchar *text,
                     gint         length,
                     gint        *position,
                     gpointer     data)
{
  int i;
  gchar *result = g_utf8_strup (text, length);

  g_signal_handlers_block_by_func (editable,
                   (gpointer) insert_text_handler, data);
  gtk_editable_insert_text (editable, result, length, position);
  g_signal_handlers_unblock_by_func (editable,
                                     (gpointer) insert_text_handler, data);

  g_signal_stop_emission_by_name (editable, "insert_text");

  g_free (result);
}

Details

GtkEditable

typedef struct _GtkEditable GtkEditable;

The GtkEditable structure contains the following fields. (These fields should be considered read-only. They should never be set by an application.)

guint selection_start; | the starting position of the selected characters in the widget.
guint selection_end; | the end position of the selected characters in the widget.
guint editable; | a flag indicating whether or not the widget is editable by the user.

gtk_editable_select_region ()

void                gtk_editable_select_region          (GtkEditable *editable,
                                                         gint start,
                                                         gint end);

Selects a region of text. The characters that are selected are those characters at positions from start_pos up to, but not including end_pos. If end_pos is negative, then the the characters selected will be those characters from start_pos to the end of the text.

editable : | a GtkEditable widget.
start : | the starting position.
end : | the end position.

gtk_editable_get_selection_bounds ()

gboolean            gtk_editable_get_selection_bounds   (GtkEditable *editable,
                                                         gint *start,
                                                         gint *end);

Gets the current selection bounds, if there is a selection.

editable : | a GtkEditable widget.
start : | location to store the starting position, or NULL.
end : | location to store the end position, or NULL.
Returns : | TRUE if there is a selection.

gtk_editable_insert_text ()

void                gtk_editable_insert_text            (GtkEditable *editable,
                                                         const gchar *new_text,
                                                         gint new_text_length,
                                                         gint *position);

Inserts text at a given position.

editable : | a GtkEditable widget.
new_text : | the text to insert.
new_text_length : | the length of the text to insert, in bytes
position : | an inout parameter. The caller initializes it to the position at which to insert the text. After the call it points at the position after the newly inserted text.

gtk_editable_delete_text ()

void                gtk_editable_delete_text            (GtkEditable *editable,
                                                         gint start_pos,
                                                         gint end_pos);

Deletes a sequence of characters. The characters that are deleted are those characters at positions from start_pos up to, but not including end_pos. If end_pos is negative, then the the characters deleted will be those characters from start_pos to the end of the text.

editable : | a GtkEditable widget.
start_pos : | the starting position.
end_pos : | the end position.

gtk_editable_get_chars ()

gchar*              gtk_editable_get_chars              (GtkEditable *editable,
                                                         gint start_pos,
                                                         gint end_pos);

Retrieves a sequence of characters. The characters that are retrieved are those characters at positions from start_pos up to, but not including end_pos. If end_pos is negative, then the the characters retrieved will be those characters from start_pos to the end of the text.

editable : | a GtkEditable widget.
start_pos : | the starting position.
end_pos : | the end position.
Returns : | the characters in the indicated region. The result must be freed with g_free() when the application is finished with it.

gtk_editable_cut_clipboard ()

void                gtk_editable_cut_clipboard          (GtkEditable *editable);

Causes the characters in the current selection to be copied to the clipboard and then deleted from the widget.

editable : a GtkEditable widget.

gtk_editable_copy_clipboard ()

void                gtk_editable_copy_clipboard         (GtkEditable *editable);

Causes the characters in the current selection to be copied to the clipboard.

editable : a GtkEditable widget.

gtk_editable_paste_clipboard ()

void                gtk_editable_paste_clipboard        (GtkEditable *editable);

Causes the contents of the clipboard to be pasted into the given widget at the current cursor position.

editable : a GtkEditable widget.

gtk_editable_delete_selection ()

void                gtk_editable_delete_selection       (GtkEditable *editable);

Deletes the current contents of the widgets selection and disclaims the selection.

editable : a GtkEditable widget.

gtk_editable_set_position ()

void                gtk_editable_set_position           (GtkEditable *editable,
                                                         gint position);

Sets the cursor position.

editable : | a GtkEditable widget.
position : | the position of the cursor. The cursor is displayed before the character with the given (base 0) index in the widget. The value must be less than or equal to the number of characters in the widget. A value of -1 indicates that the position should be set after the last character in the entry. Note that this position is in characters, not in bytes.

gtk_editable_get_position ()

gint                gtk_editable_get_position           (GtkEditable *editable);

Retrieves the current cursor position.

editable : | a GtkEditable widget.
Returns : | the position of the cursor. The cursor is displayed before the character with the given (base 0) index in the widget. The value will be less than or equal to the number of characters in the widget. Note that this position is in characters, not in bytes.

gtk_editable_set_editable ()

void                gtk_editable_set_editable           (GtkEditable *editable,
                                                         gboolean is_editable);

Determines if the user can edit the text in the editable widget or not.

editable : | a GtkEditable widget.
is_editable : | TRUE if the user is allowed to edit the text in the widget.

gtk_editable_get_editable ()

gboolean            gtk_editable_get_editable           (GtkEditable *editable);

Retrieves whether editable is editable. See gtk_editable_set_editable().

editable : | a GtkEditable
Returns : | TRUE if editable is editable.

Signal Details

The "changed" signal

void                user_function                      (GtkEditable *editable,
                                                        gpointer     user_data)      : Run Last

Indicates that the user has changed the contents of the widget.

editable : | the object which received the signal.
user_data : | user data set when the signal handler was connected.

The "delete-text" signal

void                user_function                      (GtkEditable *editable,
                                                        gint         start_pos,
                                                        gint         end_pos,
                                                        gpointer     user_data)      : Run Last

This signal is emitted when text is deleted from the widget by the user. The default handler for this signal will normally be responsible for inserting the text, so by connecting to this signal and then stopping the signal with gtk_signal_emit_stop(), it is possible to modify the inserted text, or prevent it from being inserted entirely. The start_pos and end_pos parameters are interpreted as for gtk_editable_delete_text()

editable : | the object which received the signal.
start_pos : | the starting position.
end_pos : | the end position.
user_data : | user data set when the signal handler was connected.

The "insert-text" signal

void                user_function                      (GtkEditable *editable,
                                                        gchar       *new_text,
                                                        gint         new_text_length,
                                                        gint        *position,
                                                        gpointer     user_data)            : Run Last

This signal is emitted when text is inserted into the widget by the user. The default handler for this signal will normally be responsible for inserting the text, so by connecting to this signal and then stopping the signal with gtk_signal_emit_stop(), it is possible to modify the inserted text, or prevent it from being inserted entirely.

editable : | the object which received the signal.
new_text : | the new text to insert.
new_text_length : | the length of the new text, in bytes, or -1 if new_text is nul-terminated
position : | the position, in characters, at which to insert the new text. this is an in-out parameter. After the signal emission is finished, it should point after the newly inserted text.
user_data : | user data set when the signal handler was connected.


GtkEntry

GtkEntry — A single line text entry field

Synopsis

#include <gtk/gtk.h>

                    GtkEntry;
GtkWidget*          gtk_entry_new                       (void);
GtkWidget*          gtk_entry_new_with_max_length       (gint max);
void                gtk_entry_set_text                  (GtkEntry *entry,
                                                         const gchar *text);
void                gtk_entry_append_text               (GtkEntry *entry,
                                                         const gchar *text);
void                gtk_entry_prepend_text              (GtkEntry *entry,
                                                         const gchar *text);
void                gtk_entry_set_position              (GtkEntry *entry,
                                                         gint position);
const gchar*        gtk_entry_get_text                  (GtkEntry *entry);
void                gtk_entry_select_region             (GtkEntry *entry,
                                                         gint start,
                                                         gint end);
void                gtk_entry_set_visibility            (GtkEntry *entry,
                                                         gboolean visible);
void                gtk_entry_set_invisible_char        (GtkEntry *entry,
                                                         gunichar ch);
void                gtk_entry_set_editable              (GtkEntry *entry,
                                                         gboolean editable);
void                gtk_entry_set_max_length            (GtkEntry *entry,
                                                         gint max);
gboolean            gtk_entry_get_activates_default     (GtkEntry *entry);
gboolean            gtk_entry_get_has_frame             (GtkEntry *entry);
const GtkBorder*    gtk_entry_get_inner_border          (GtkEntry *entry);
gint                gtk_entry_get_width_chars           (GtkEntry *entry);
void                gtk_entry_set_activates_default     (GtkEntry *entry,
                                                         gboolean setting);
void                gtk_entry_set_has_frame             (GtkEntry *entry,
                                                         gboolean setting);
void                gtk_entry_set_inner_border          (GtkEntry *entry,
                                                         const GtkBorder *border);
void                gtk_entry_set_width_chars           (GtkEntry *entry,
                                                         gint n_chars);
gunichar            gtk_entry_get_invisible_char        (GtkEntry *entry);
void                gtk_entry_set_alignment             (GtkEntry *entry,
                                                         gfloat xalign);
gfloat              gtk_entry_get_alignment             (GtkEntry *entry);
PangoLayout*        gtk_entry_get_layout                (GtkEntry *entry);
void                gtk_entry_get_layout_offsets        (GtkEntry *entry,
                                                         gint *x,
                                                         gint *y);
gint                gtk_entry_layout_index_to_text_index
                                                        (GtkEntry *entry,
                                                         gint layout_index);
gint                gtk_entry_text_index_to_layout_index
                                                        (GtkEntry *entry,
                                                         gint text_index);
gint                gtk_entry_get_max_length            (GtkEntry *entry);
gboolean            gtk_entry_get_visibility            (GtkEntry *entry);
void                gtk_entry_set_completion            (GtkEntry *entry,
                                                         GtkEntryCompletion *completion);
GtkEntryCompletion* gtk_entry_get_completion            (GtkEntry *entry);

Object Hierarchy

  GObject
   +----GInitiallyUnowned
         +----GtkObject
               +----GtkWidget
                     +----GtkEntry
                           +----GtkSpinButton

Implemented Interfaces

GtkEntry implements AtkImplementorIface, GtkCellEditable and GtkEditable.

Properties

  "activates-default"        gboolean              : Read / Write
  "cursor-position"          gint                  : Read
  "editable"                 gboolean              : Read / Write
  "has-frame"                gboolean              : Read / Write
  "inner-border"             GtkBorder             : Read / Write
  "invisible-char"           guint                 : Read / Write
  "max-length"               gint                  : Read / Write
  "scroll-offset"            gint                  : Read
  "selection-bound"          gint                  : Read
  "text"                     gchararray            : Read / Write
  "truncate-multiline"       gboolean              : Read / Write
  "visibility"               gboolean              : Read / Write
  "width-chars"              gint                  : Read / Write
  "xalign"                   gfloat                : Read / Write

Style Properties

  "inner-border"             GtkBorder             : Read

Signals

  "activate"                                       : Run Last / Action
  "backspace"                                      : Run Last / Action
  "copy-clipboard"                                 : Run Last / Action
  "cut-clipboard"                                  : Run Last / Action
  "delete-from-cursor"                             : Run Last / Action
  "insert-at-cursor"                               : Run Last / Action
  "move-cursor"                                    : Run Last / Action
  "paste-clipboard"                                : Run Last / Action
  "populate-popup"                                 : Run Last
  "toggle-overwrite"                               : Run Last / Action

Description

The GtkEntry widget is a single line text entry widget. A fairly large set of key bindings are supported by default. If the entered text is longer than the allocation of the widget, the widget will scroll so that the cursor position is visible.

Details

GtkEntry

typedef struct _GtkEntry GtkEntry;

The GtkEntry struct contains only private data.

gtk_entry_new ()

GtkWidget*          gtk_entry_new                       (void);

Creates a new entry.

Returns : a new GtkEntry.

gtk_entry_new_with_max_length ()

GtkWidget*          gtk_entry_new_with_max_length       (gint max);

Warning

gtk_entry_new_with_max_length is deprecated and should not be used in newly-written code.

Creates a new GtkEntry widget with the given maximum length.

Note: the existence of this function is inconsistent with the rest of the GTK+ API. The normal setup would be to just require the user to make an extra call to gtk_entry_set_max_length() instead. It is not expected that this function will be removed, but it would be better practice not to use it.

max : | the maximum length of the entry, or 0 for no maximum. (other than the maximum length of entries.) The value passed in will be clamped to the range 0-65536.
Returns : | a new GtkEntry.

gtk_entry_set_text ()

void                gtk_entry_set_text                  (GtkEntry *entry,
                                                         const gchar *text);

Sets the text in the widget to the given value, replacing the current contents.

entry : | a GtkEntry.
text : | the new text.

gtk_entry_append_text ()

void                gtk_entry_append_text               (GtkEntry *entry,
                                                         const gchar *text);

Warning

gtk_entry_append_text is deprecated and should not be used in newly-written code.

Appends the given text to the contents of the widget.

entry : | a GtkEntry.
text : | the text to append.

gtk_entry_prepend_text ()

void                gtk_entry_prepend_text              (GtkEntry *entry,
                                                         const gchar *text);

Warning

gtk_entry_prepend_text is deprecated and should not be used in newly-written code.

Prepends the given text to the contents of th ewidget.

entry : | a GtkEntry.
text : | the text to prepend.

gtk_entry_set_position ()

void                gtk_entry_set_position              (GtkEntry *entry,
                                                         gint position);

Warning

gtk_entry_set_position is deprecated and should not be used in newly-written code.

Sets the cursor position in an entry to the given value. This function is obsolete. You should use gtk_editable_set_position() instead.

entry : | a GtkEntry.
position : | the position of the cursor. The cursor is displayed before the character with the given (base 0) index in the widget. The value must be less than or equal to the number of characters in the widget. A value of -1 indicates that the position should be set after the last character in the entry. Note that this position is in characters, not in bytes.

gtk_entry_get_text ()

const gchar*        gtk_entry_get_text                  (GtkEntry *entry);

Retrieves the contents of the entry widget. See also gtk_editable_get_chars().

entry : | a GtkEntry
Returns : | a pointer to the contents of the widget as a string. This string points to internally allocated storage in the widget and must not be freed, modified or stored.

gtk_entry_select_region ()

void                gtk_entry_select_region             (GtkEntry *entry,
                                                         gint start,
                                                         gint end);

Warning

gtk_entry_select_region is deprecated and should not be used in newly-written code.

Selects a region of text. The characters that are selected are those characters at positions from start_pos up to, but not including end_pos. If end_pos is negative, then the the characters selected will be those characters from start_pos to the end of the text. This function is obsolete. You should use gtk_editable_select_region() instead.

entry : | a GtkEntry.
start : | the starting position.
end : | the end position.

gtk_entry_set_visibility ()

void                gtk_entry_set_visibility            (GtkEntry *entry,
                                                         gboolean visible);

Sets whether the contents of the entry are visible or not. When visibility is set to FALSE, characters are displayed as the invisible char, and will also appear that way when the text in the entry widget is copied elsewhere.

The default invisible char is the asterisk '*', but it can be changed with gtk_entry_set_invisible_char().

entry : | a GtkEntry.
visible : | TRUE if the contents of the entry are displayed as plaintext.

gtk_entry_set_invisible_char ()

void                gtk_entry_set_invisible_char        (GtkEntry *entry,
                                                         gunichar ch);

Sets the character to use in place of the actual text when gtk_entry_set_visibility() has been called to set text visibility to FALSE. i.e. this is the character used in "password mode" to show the user how many characters have been typed. The default invisible char is an asterisk ('*'). If you set the invisible char to 0, then the user will get no feedback at all; there will be no text on the screen as they type.

entry : | a GtkEntry
ch : | a Unicode character

gtk_entry_set_editable ()

void                gtk_entry_set_editable              (GtkEntry *entry,
                                                         gboolean editable);

Warning

gtk_entry_set_editable is deprecated and should not be used in newly-written code.

Determines if the user can edit the text in the editable widget or not. This function is obsolete. You should use gtk_editable_set_editable() instead.

entry : | a GtkEntry.
editable : | TRUE if the user is allowed to edit the text in the widget.

gtk_entry_set_max_length ()

void                gtk_entry_set_max_length            (GtkEntry *entry,
                                                         gint max);

Sets the maximum allowed length of the contents of the widget. If the current contents are longer than the given length, then they will be truncated to fit.

entry : | a GtkEntry.
max : | the maximum length of the entry, or 0 for no maximum. (other than the maximum length of entries.) The value passed in will be clamped to the range 0-65536.

gtk_entry_get_activates_default ()

gboolean            gtk_entry_get_activates_default     (GtkEntry *entry);

Retrieves the value set by gtk_entry_set_activates_default().

entry : | a GtkEntry
Returns : | TRUE if the entry will activate the default widget

gtk_entry_get_has_frame ()

gboolean            gtk_entry_get_has_frame             (GtkEntry *entry);

Gets the value set by gtk_entry_set_has_frame().

entry : | a GtkEntry
Returns : | whether the entry has a beveled frame

gtk_entry_get_inner_border ()

const GtkBorder*    gtk_entry_get_inner_border          (GtkEntry *entry);

This function returns the entry's inner-border property. See gtk_entry_set_inner_border() for more information.

entry : | a GtkEntry
Returns : | the entry's GtkBorder, or NULL if none was set.

Since 2.10

gtk_entry_get_width_chars ()

gint                gtk_entry_get_width_chars           (GtkEntry *entry);

Gets the value set by gtk_entry_set_width_chars().

entry : | a GtkEntry
Returns : | number of chars to request space for, or negative if unset

gtk_entry_set_activates_default ()

void                gtk_entry_set_activates_default     (GtkEntry *entry,
                                                         gboolean setting);

If setting is TRUE, pressing Enter in the entry will activate the default widget for the window containing the entry. This usually means that the dialog box containing the entry will be closed, since the default widget is usually one of the dialog buttons.

(For experts: if setting is TRUE, the entry calls gtk_window_activate_default() on the window containing the entry, in the default handler for the "activate" signal.)

entry : | a GtkEntry
setting : | TRUE to activate window's default widget on Enter keypress

gtk_entry_set_has_frame ()

void                gtk_entry_set_has_frame             (GtkEntry *entry,
                                                         gboolean setting);

Sets whether the entry has a beveled frame around it.

entry : | a GtkEntry
setting : | new value

gtk_entry_set_inner_border ()

void                gtk_entry_set_inner_border          (GtkEntry *entry,
                                                         const GtkBorder *border);

Sets entry's inner-border property to border, or clears it if NULL is passed. The inner-border is the area around the entry's text, but inside its frame.

If set, this property overrides the inner-border style property. Overriding the style-provided border is useful when you want to do in-place editing of some text in a canvas or list widget, where pixel-exact positioning of the entry is important.

entry : | a GtkEntry
border : | a GtkBorder, or NULL

Since 2.10

gtk_entry_set_width_chars ()

void                gtk_entry_set_width_chars           (GtkEntry *entry,
                                                         gint n_chars);

Changes the size request of the entry to be about the right size for n_chars characters. Note that it changes the size request, the size can still be affected by how you pack the widget into containers. If n_chars is -1, the size reverts to the default entry size.

entry : | a GtkEntry
n_chars : | width in chars

gtk_entry_get_invisible_char ()

gunichar            gtk_entry_get_invisible_char        (GtkEntry *entry);

Retrieves the character displayed in place of the real characters for entries with visisbility set to false. See gtk_entry_set_invisible_char().

entry : | a GtkEntry
Returns : | the current invisible char, or 0, if the entry does not show invisible text at all.

gtk_entry_set_alignment ()

void                gtk_entry_set_alignment             (GtkEntry *entry,
                                                         gfloat xalign);

Sets the alignment for the contents of the entry. This controls the horizontal positioning of the contents when the displayed text is shorter than the width of the entry.

entry : | a GtkEntry
xalign : | The horizontal alignment, from 0 (left) to 1 (right). Reversed for RTL layouts

Since 2.4

gtk_entry_get_alignment ()

gfloat              gtk_entry_get_alignment             (GtkEntry *entry);

Gets the value set by gtk_entry_set_alignment().

entry : | a GtkEntry
Returns : | the alignment

Since 2.4

gtk_entry_get_layout ()

PangoLayout*        gtk_entry_get_layout                (GtkEntry *entry);

Gets the PangoLayout used to display the entry. The layout is useful to e.g. convert text positions to pixel positions, in combination with gtk_entry_get_layout_offsets(). The returned layout is owned by the entry and must not be modified or freed by the caller.

Keep in mind that the layout text may contain a preedit string, so gtk_entry_layout_index_to_text_index() and gtk_entry_text_index_to_layout_index() are needed to convert byte indices in the layout to byte indices in the entry contents.

entry : | a GtkEntry
Returns : | the PangoLayout for this entry

gtk_entry_get_layout_offsets ()

void                gtk_entry_get_layout_offsets        (GtkEntry *entry,
                                                         gint *x,
                                                         gint *y);

Obtains the position of the PangoLayout used to render text in the entry, in widget coordinates. Useful if you want to line up the text in an entry with some other text, e.g. when using the entry to implement editable cells in a sheet widget.

Also useful to convert mouse events into coordinates inside the PangoLayout, e.g. to take some action if some part of the entry text is clicked.

Note that as the user scrolls around in the entry the offsets will change; you'll need to connect to the "notify::scroll-offset" signal to track this. Remember when using the PangoLayout functions you need to convert to and from pixels using PANGO_PIXELS() or PANGO_SCALE.

Keep in mind that the layout text may contain a preedit string, so gtk_entry_layout_index_to_text_index() and gtk_entry_text_index_to_layout_index() are needed to convert byte indices in the layout to byte indices in the entry contents.

entry : | a GtkEntry
x : | location to store X offset of layout, or NULL
y : | location to store Y offset of layout, or NULL

gtk_entry_layout_index_to_text_index ()

gint                gtk_entry_layout_index_to_text_index
                                                        (GtkEntry *entry,
                                                         gint layout_index);

Converts from a position in the entry contents (returned by gtk_entry_get_text()) to a position in the entry's PangoLayout (returned by gtk_entry_get_layout(), with text retrieved via pango_layout_get_text()).

entry : | a GtkEntry
layout_index : | byte index into the entry layout text
Returns : | byte index into the entry contents

gtk_entry_text_index_to_layout_index ()

gint                gtk_entry_text_index_to_layout_index
                                                        (GtkEntry *entry,
                                                         gint text_index);

Converts from a position in the entry's PangoLayout (returned by gtk_entry_get_layout()) to a position in the entry contents (returned by gtk_entry_get_text()).

entry : | a GtkEntry
text_index : | byte index into the entry contents
Returns : | byte index into the entry layout text

gtk_entry_get_max_length ()

gint                gtk_entry_get_max_length            (GtkEntry *entry);

Retrieves the maximum allowed length of the text in entry. See gtk_entry_set_max_length().

entry : | a GtkEntry
Returns : | the maximum allowed number of characters in GtkEntry, or 0 if there is no maximum.

gtk_entry_get_visibility ()

gboolean            gtk_entry_get_visibility            (GtkEntry *entry);

Retrieves whether the text in entry is visible. See gtk_entry_set_visibility().

entry : | a GtkEntry
Returns : | TRUE if the text is currently visible

gtk_entry_set_completion ()

void                gtk_entry_set_completion            (GtkEntry *entry,
                                                         GtkEntryCompletion *completion);

Sets completion to be the auxiliary completion object to use with entry. All further configuration of the completion mechanism is done on completion using the GtkEntryCompletion API. Completion is disabled if completion is set to NULL.

entry : | A GtkEntry.
completion : | The GtkEntryCompletion or NULL.

Since 2.4

gtk_entry_get_completion ()

GtkEntryCompletion* gtk_entry_get_completion            (GtkEntry *entry);

Returns the auxiliary completion object currently in use by entry.

entry : | A GtkEntry.
Returns : | The auxiliary completion object currently in use by entry.

Since 2.4

Property Details

The "activates-default" property

  "activates-default"        gboolean              : Read / Write

Whether to activate the default widget (such as the default button in a dialog) when Enter is pressed.

Default value: FALSE

The "cursor-position" property

  "cursor-position"          gint                  : Read

The current position of the insertion cursor in chars.

Allowed values: [0,65535]

Default value: 0

The "editable" property

  "editable"                 gboolean              : Read / Write

Whether the entry contents can be edited.

Default value: TRUE

The "has-frame" property

  "has-frame"                gboolean              : Read / Write

FALSE removes outside bevel from entry.

Default value: TRUE

The "inner-border" property

  "inner-border"             GtkBorder             : Read / Write

Sets the text area's border between the text and the frame

Since 2.10

The "invisible-char" property

  "invisible-char"           guint                 : Read / Write

The character to use when masking entry contents (in "password mode").

Default value: '*'

The "max-length" property

  "max-length"               gint                  : Read / Write

Maximum number of characters for this entry. Zero if no maximum.

Allowed values: [0,65535]

Default value: 0

The "scroll-offset" property

  "scroll-offset"            gint                  : Read

Number of pixels of the entry scrolled off the screen to the left.

Allowed values: >= 0

Default value: 0

The "selection-bound" property

  "selection-bound"          gint                  : Read

The position of the opposite end of the selection from the cursor in chars.

Allowed values: [0,65535]

Default value: 0

The "text" property

  "text"                     gchararray            : Read / Write

The contents of the entry.

Default value: ""

The "truncate-multiline" property

  "truncate-multiline"       gboolean              : Read / Write

When TRUE, pasted multi-line text is truncated to the first line.

Default value: FALSE

Since 2.10

The "visibility" property

  "visibility"               gboolean              : Read / Write

FALSE displays the "invisible char" instead of the actual text (password mode).

Default value: TRUE

The "width-chars" property

  "width-chars"              gint                  : Read / Write

Number of characters to leave space for in the entry.

Allowed values: >= -1

Default value: -1

The "xalign" property

  "xalign"                   gfloat                : Read / Write

The horizontal alignment, from 0 (left) to 1 (right). Reversed for RTL layouts.

Creates a new GtkEntry widget.

Allowed values: [0,1]

Default value: 0

Since 2.4

Style Property Details

The "inner-border" style property

  "inner-border"             GtkBorder             : Read

Sets the text area's border between the text and the frame

Since 2.10

Signal Details

The "activate" signal

void                user_function                      (GtkEntry *entry,
                                                        gpointer  user_data)      : Run Last / Action

entry : | the object which received the signal.
user_data : | user data set when the signal handler was connected.

The "backspace" signal

void                user_function                      (GtkEntry *entry,
                                                        gpointer  user_data)      : Run Last / Action

entry : | the object which received the signal.
user_data : | user data set when the signal handler was connected.

The "copy-clipboard" signal

void                user_function                      (GtkEntry *entry,
                                                        gpointer  user_data)      : Run Last / Action

entry : | the object which received the signal.
user_data : | user data set when the signal handler was connected.

The "cut-clipboard" signal

void                user_function                      (GtkEntry *entry,
                                                        gpointer  user_data)      : Run Last / Action

entry : | the object which received the signal.
user_data : | user data set when the signal handler was connected.

The "delete-from-cursor" signal

void                user_function                      (GtkEntry     *entry,
                                                        GtkDeleteType arg1,
                                                        gint          arg2,
                                                        gpointer      user_data)      : Run Last / Action

entry : | the object which received the signal.
arg1 : |
arg2 : |
user_data : | user data set when the signal handler was connected.

The "insert-at-cursor" signal

void                user_function                      (GtkEntry *entry,
                                                        gchar    *arg1,
                                                        gpointer  user_data)      : Run Last / Action

entry : | the object which received the signal.
arg1 : |
user_data : | user data set when the signal handler was connected.

The "move-cursor" signal

void                user_function                      (GtkEntry       *entry,
                                                        GtkMovementStep arg1,
                                                        gint            arg2,
                                                        gboolean        arg3,
                                                        gpointer        user_data)      : Run Last / Action

entry : | the object which received the signal.
arg1 : |
arg2 : |
arg3 : |
user_data : | user data set when the signal handler was connected.

The "paste-clipboard" signal

void                user_function                      (GtkEntry *entry,
                                                        gpointer  user_data)      : Run Last / Action

entry : | the object which received the signal.
user_data : | user data set when the signal handler was connected.

The "populate-popup" signal

void                user_function                      (GtkEntry *entry,
                                                        GtkMenu  *arg1,
                                                        gpointer  user_data)      : Run Last

entry : | the object which received the signal.
arg1 : |
user_data : | user data set when the signal handler was connected.

The "toggle-overwrite" signal

void                user_function                      (GtkEntry *entry,
                                                        gpointer  user_data)      : Run Last / Action

entry : | the object which received the signal.
user_data : | user data set when the signal handler was connected.

See Also

GtkTextView

a widget for handling multi-line text entry.


GtkEntryCompletion

GtkEntryCompletion — Completion functionality for GtkEntry

Synopsis

#include <gtk/gtk.h>

                    GtkEntryCompletion;
gboolean            (*GtkEntryCompletionMatchFunc)      (GtkEntryCompletion *completion,
                                                         const gchar *key,
                                                         GtkTreeIter *iter,
                                                         gpointer user_data);
GtkEntryCompletion* gtk_entry_completion_new            (void);
GtkWidget*          gtk_entry_completion_get_entry      (GtkEntryCompletion *completion);
void                gtk_entry_completion_set_model      (GtkEntryCompletion *completion,
                                                         GtkTreeModel *model);
GtkTreeModel*       gtk_entry_completion_get_model      (GtkEntryCompletion *completion);
void                gtk_entry_completion_set_match_func (GtkEntryCompletion *completion,
                                                         GtkEntryCompletionMatchFunc func,
                                                         gpointer func_data,
                                                         GDestroyNotify func_notify);
void                gtk_entry_completion_set_minimum_key_length
                                                        (GtkEntryCompletion *completion,
                                                         gint length);
gint                gtk_entry_completion_get_minimum_key_length
                                                        (GtkEntryCompletion *completion);
void                gtk_entry_completion_complete       (GtkEntryCompletion *completion);
void                gtk_entry_completion_insert_prefix  (GtkEntryCompletion *completion);
void                gtk_entry_completion_insert_action_text
                                                        (GtkEntryCompletion *completion,
                                                         gint index_,
                                                         const gchar *text);
void                gtk_entry_completion_insert_action_markup
                                                        (GtkEntryCompletion *completion,
                                                         gint index_,
                                                         const gchar *markup);
void                gtk_entry_completion_delete_action  (GtkEntryCompletion *completion,
                                                         gint index_);
void                gtk_entry_completion_set_text_column
                                                        (GtkEntryCompletion *completion,
                                                         gint column);
gint                gtk_entry_completion_get_text_column
                                                        (GtkEntryCompletion *completion);
void                gtk_entry_completion_set_inline_completion
                                                        (GtkEntryCompletion *completion,
                                                         gboolean inline_completion);
gboolean            gtk_entry_completion_get_inline_completion
                                                        (GtkEntryCompletion *completion);
void                gtk_entry_completion_set_popup_completion
                                                        (GtkEntryCompletion *completion,
                                                         gboolean popup_completion);
gboolean            gtk_entry_completion_get_popup_completion
                                                        (GtkEntryCompletion *completion);
void                gtk_entry_completion_set_popup_set_width
                                                        (GtkEntryCompletion *completion,
                                                         gboolean popup_set_width);
gboolean            gtk_entry_completion_get_popup_set_width
                                                        (GtkEntryCompletion *completion);
void                gtk_entry_completion_set_popup_single_match
                                                        (GtkEntryCompletion *completion,
                                                         gboolean popup_single_match);
gboolean            gtk_entry_completion_get_popup_single_match
                                                        (GtkEntryCompletion *completion);

Object Hierarchy

  GObject
   +----GtkEntryCompletion

Implemented Interfaces

GtkEntryCompletion implements GtkCellLayout.

Properties

  "inline-completion"        gboolean              : Read / Write
  "minimum-key-length"       gint                  : Read / Write
  "model"                    GtkTreeModel          : Read / Write
  "popup-completion"         gboolean              : Read / Write
  "popup-set-width"          gboolean              : Read / Write
  "popup-single-match"       gboolean              : Read / Write
  "text-column"              gint                  : Read / Write

Signals

  "action-activated"                               : Run Last
  "insert-prefix"                                  : Run Last
  "match-selected"                                 : Run Last

Description

GtkEntryCompletion is an auxiliary object to be used in conjunction with GtkEntry to provide the completion functionality. It implements the GtkCellLayout interface, to allow the user to add extra cells to the GtkTreeView with completion matches.

"Completion functionality" means that when the user modifies the text in the entry, GtkEntryCompletion checks which rows in the model match the current content of the entry, and displays a list of matches. By default, the matching is done by comparing the entry text case-insensitively against the text column of the model (see gtk_entry_completion_set_text_column()), but this can be overridden with a custom match function (see gtk_entry_completion_set_match_func()).

When the user selects a completion, the content of the entry is updated. By default, the content of the entry is replaced by the text column of the model, but this can be overridden by connecting to the ::match-selected signal and updating the entry in the signal handler. Note that you should return TRUE from the signal handler to suppress the default behaviour.

To add completion functionality to an entry, use gtk_entry_set_completion().

In addition to regular completion matches, which will be inserted into the entry when they are selected, GtkEntryCompletion also allows to display "actions" in the popup window. Their appearance is similar to menuitems, to differentiate them clearly from completion strings. When an action is selected, the ::action-activated signal is emitted.

Details

GtkEntryCompletion

typedef struct _GtkEntryCompletion GtkEntryCompletion;

The GtkEntryCompletion struct contains only private data.

GtkEntryCompletionMatchFunc ()

gboolean            (*GtkEntryCompletionMatchFunc)      (GtkEntryCompletion *completion,
                                                         const gchar *key,
                                                         GtkTreeIter *iter,
                                                         gpointer user_data);

A function which decides whether the row indicated by iter matches a given key, and should be displayed as a possible completion for key. Note that key is normalized and case-folded (see g_utf8_normalize() and g_utf8_casefold()). If this is not appropriate, match functions have access to the unmodified key via gtk_entry_get_text (GTK_ENTRY (gtk_entry_completion_get_entry ())).

completion : | the GtkEntryCompletion
key : | the string to match, normalized and case-folded
iter : | a GtkTreeIter indicating the row to match
user_data : | user data given to gtk_entry_completion_set_match_func()
Returns : | TRUE if iter should be displayed as a possible completion for key

gtk_entry_completion_new ()

GtkEntryCompletion* gtk_entry_completion_new            (void);

Creates a new GtkEntryCompletion object.

Returns : A newly created GtkEntryCompletion object.

Since 2.4

gtk_entry_completion_get_entry ()

GtkWidget*          gtk_entry_completion_get_entry      (GtkEntryCompletion *completion);

Gets the entry completion has been attached to.

completion : | A GtkEntryCompletion.
Returns : | The entry completion has been attached to.

Since 2.4

gtk_entry_completion_set_model ()

void                gtk_entry_completion_set_model      (GtkEntryCompletion *completion,
                                                         GtkTreeModel *model);

Sets the model for a GtkEntryCompletion. If completion already has a model set, it will remove it before setting the new model. If model is NULL, then it will unset the model.

completion : | A GtkEntryCompletion.
model : | The GtkTreeModel.

Since 2.4

gtk_entry_completion_get_model ()

GtkTreeModel*       gtk_entry_completion_get_model      (GtkEntryCompletion *completion);

Returns the model the GtkEntryCompletion is using as data source. Returns NULL if the model is unset.

completion : | A GtkEntryCompletion.
Returns : | A GtkTreeModel, or NULL if none is currently being used.

Since 2.4

gtk_entry_completion_set_match_func ()

void                gtk_entry_completion_set_match_func (GtkEntryCompletion *completion,
                                                         GtkEntryCompletionMatchFunc func,
                                                         gpointer func_data,
                                                         GDestroyNotify func_notify);

Sets the match function for completion to be func. The match function is used to determine if a row should or should not be in the completion list.

completion : | A GtkEntryCompletion.
func : | The GtkEntryCompletionMatchFunc to use.
func_data : | The user data for func.
func_notify : | Destroy notifier for func_data.

Since 2.4

gtk_entry_completion_set_minimum_key_length ()

void                gtk_entry_completion_set_minimum_key_length
                                                        (GtkEntryCompletion *completion,
                                                         gint length);

Requires the length of the search key for completion to be at least length. This is useful for long lists, where completing using a small key takes a lot of time and will come up with meaningless results anyway (ie, a too large dataset).

completion : | A GtkEntryCompletion.
length : | The minimum length of the key in order to start completing.

Since 2.4

gtk_entry_completion_get_minimum_key_length ()

gint                gtk_entry_completion_get_minimum_key_length
                                                        (GtkEntryCompletion *completion);

Returns the minimum key length as set for completion.

completion : | A GtkEntryCompletion.
Returns : | The currently used minimum key length.

Since 2.4

gtk_entry_completion_complete ()

void                gtk_entry_completion_complete       (GtkEntryCompletion *completion);

Requests a completion operation, or in other words a refiltering of the current list with completions, using the current key. The completion list view will be updated accordingly.

completion : A GtkEntryCompletion.

Since 2.4

gtk_entry_completion_insert_prefix ()

void                gtk_entry_completion_insert_prefix  (GtkEntryCompletion *completion);

Requests a prefix insertion.

completion : a GtkEntryCompletion

Since 2.6

gtk_entry_completion_insert_action_text ()

void                gtk_entry_completion_insert_action_text
                                                        (GtkEntryCompletion *completion,
                                                         gint index_,
                                                         const gchar *text);

Inserts an action in completion's action item list at position index_ with text text. If you want the action item to have markup, use gtk_entry_completion_insert_action_markup().

completion : | A GtkEntryCompletion.
index_ : | The index of the item to insert.
text : | Text of the item to insert.

Since 2.4

gtk_entry_completion_insert_action_markup ()

void                gtk_entry_completion_insert_action_markup
                                                        (GtkEntryCompletion *completion,
                                                         gint index_,
                                                         const gchar *markup);

Inserts an action in completion's action item list at position index_ with markup markup.

completion : | A GtkEntryCompletion.
index_ : | The index of the item to insert.
markup : | Markup of the item to insert.

Since 2.4

gtk_entry_completion_delete_action ()

void                gtk_entry_completion_delete_action  (GtkEntryCompletion *completion,
                                                         gint index_);

Deletes the action at index_ from completion's action list.

completion : | A GtkEntryCompletion.
index_ : | The index of the item to Delete.

Since 2.4

gtk_entry_completion_set_text_column ()

void                gtk_entry_completion_set_text_column
                                                        (GtkEntryCompletion *completion,
                                                         gint column);

Convenience function for setting up the most used case of this code: a completion list with just strings. This function will set up completion to have a list displaying all (and just) strings in the completion list, and to get those strings from column in the model of completion.

This functions creates and adds a GtkCellRendererText for the selected column. If you need to set the text column, but don't want the cell renderer, use g_object_set() to set the ::text_column property directly.

completion : | A GtkEntryCompletion.
column : | The column in the model of completion to get strings from.

Since 2.4

gtk_entry_completion_get_text_column ()

gint                gtk_entry_completion_get_text_column
                                                        (GtkEntryCompletion *completion);

Returns the column in the model of completion to get strings from.

completion : | a GtkEntryCompletion
Returns : | the column containing the strings

Since 2.6

gtk_entry_completion_set_inline_completion ()

void                gtk_entry_completion_set_inline_completion
                                                        (GtkEntryCompletion *completion,
                                                         gboolean inline_completion);

Sets whether the common prefix of the possible completions should be automatically inserted in the entry.

completion : | a GtkEntryCompletion
inline_completion : | TRUE to do inline completion

Since 2.6

gtk_entry_completion_get_inline_completion ()

gboolean            gtk_entry_completion_get_inline_completion
                                                        (GtkEntryCompletion *completion);

Returns whether the common prefix of the possible completions should be automatically inserted in the entry.

completion : | a GtkEntryCompletion
Returns : | TRUE if inline completion is turned on

Since 2.6

gtk_entry_completion_set_popup_completion ()

void                gtk_entry_completion_set_popup_completion
                                                        (GtkEntryCompletion *completion,
                                                         gboolean popup_completion);

Sets whether the completions should be presented in a popup window.

completion : | a GtkEntryCompletion
popup_completion : | TRUE to do popup completion

Since 2.6

gtk_entry_completion_get_popup_completion ()

gboolean            gtk_entry_completion_get_popup_completion
                                                        (GtkEntryCompletion *completion);

Returns whether the completions should be presented in a popup window.

completion : | a GtkEntryCompletion
Returns : | TRUE if popup completion is turned on

Since 2.6

gtk_entry_completion_set_popup_set_width ()

void                gtk_entry_completion_set_popup_set_width
                                                        (GtkEntryCompletion *completion,
                                                         gboolean popup_set_width);

Sets whether the completion popup window will be resized to be the same width as the entry.

completion : | a GtkEntryCompletion
popup_set_width : | TRUE to make the width of the popup the same as the entry

Since 2.8

gtk_entry_completion_get_popup_set_width ()

gboolean            gtk_entry_completion_get_popup_set_width
                                                        (GtkEntryCompletion *completion);

Returns whether the completion popup window will be resized to the width of the entry.

completion : | a GtkEntryCompletion
Returns : | TRUE if the popup window will be resized to the width of the entry

Since 2.8

gtk_entry_completion_set_popup_single_match ()

void                gtk_entry_completion_set_popup_single_match
                                                        (GtkEntryCompletion *completion,
                                                         gboolean popup_single_match);

Sets whether the completion popup window will appear even if there is only a single match. You may want to set this to FALSE if you are using inline completion.

completion : | a GtkEntryCompletion
popup_single_match : | TRUE if the popup should appear even for a single match

Since 2.8

gtk_entry_completion_get_popup_single_match ()

gboolean            gtk_entry_completion_get_popup_single_match
                                                        (GtkEntryCompletion *completion);

Returns whether the completion popup window will appear even if there is only a single match.

completion : | a GtkEntryCompletion
Returns : | TRUE if the popup window will appear regardless of the number of matches.

Since 2.8

Property Details

The "inline-completion" property

  "inline-completion"        gboolean              : Read / Write

Determines whether the common prefix of the possible completions should be inserted automatically in the entry. Note that this requires text-column to be set, even if you are using a custom match function.

Default value: FALSE

Since 2.6

The "minimum-key-length" property

  "minimum-key-length"       gint                  : Read / Write

Minimum length of the search key in order to look up matches.

Allowed values: >= 0

Default value: 1

The "model" property

  "model"                    GtkTreeModel          : Read / Write

The model to find matches in.

The "popup-completion" property

  "popup-completion"         gboolean              : Read / Write

Determines whether the possible completions should be shown in a popup window.

Default value: TRUE

Since 2.6

The "popup-set-width" property

  "popup-set-width"          gboolean              : Read / Write

Determines whether the completions popup window will be resized to the width of the entry.

Default value: TRUE

Since 2.8

The "popup-single-match" property

  "popup-single-match"       gboolean              : Read / Write

Determines whether the completions popup window will shown for a single possible completion. You probably want to set this to FALSE if you are using inline completion.

Default value: TRUE

Since 2.8

The "text-column" property

  "text-column"              gint                  : Read / Write

The column of the model containing the strings.

Allowed values: >= -1

Default value: -1

Since 2.6

Signal Details

The "action-activated" signal

void                user_function                      (GtkEntryCompletion *widget,
                                                        gint                index,
                                                        gpointer            user_data)      : Run Last

Gets emitted when an action is activated.

widget : | the object which received the signal
index : | the index of the activated action
user_data : | user data set when the signal handler was connected.

Since 2.4

The "insert-prefix" signal

gboolean            user_function                      (GtkEntryCompletion *widget,
                                                        gchar              *prefix,
                                                        gpointer            user_data)      : Run Last

Gets emitted when the inline autocompletion is triggered. The default behaviour is to make the entry display the whole prefix and select the newly inserted part.

Applications may connect to this signal in order to insert only a smaller part of the prefix into the entry - e.g. the entry used in the GtkFileChooser inserts only the part of the prefix up to the next '/'.

widget : | the object which received the signal
prefix : | the common prefix of all possible completions
user_data : | user data set when the signal handler was connected.
Returns : | TRUE if the signal has been handled

Since 2.6

The "match-selected" signal

gboolean            user_function                      (GtkEntryCompletion *widget,
                                                        GtkTreeModel       *model,
                                                        GtkTreeIter        *iter,
                                                        gpointer            user_data)      : Run Last

Gets emitted when a match from the list is selected. The default behaviour is to replace the contents of the entry with the contents of the text column in the row pointed to by iter.

widget : | the object which received the signal
model : | the GtkTreeModel containing the matches
iter : | a GtkTreeIter positioned at the selected match
user_data : | user data set when the signal handler was connected.
Returns : | TRUE if the signal has been handled

Since 2.4


GtkEventBox

GtkEventBox — A widget used to catch events for widgets which do not have their own window

Synopsis

#include <gtk/gtk.h>

                    GtkEventBox;
GtkWidget*          gtk_event_box_new                   (void);
void                gtk_event_box_set_above_child       (GtkEventBox *event_box,
                                                         gboolean above_child);
gboolean            gtk_event_box_get_above_child       (GtkEventBox *event_box);
void                gtk_event_box_set_visible_window    (GtkEventBox *event_box,
                                                         gboolean visible_window);
gboolean            gtk_event_box_get_visible_window    (GtkEventBox *event_box);

Object Hierarchy

  GObject
   +----GInitiallyUnowned
         +----GtkObject
               +----GtkWidget
                     +----GtkContainer
                           +----GtkBin
                                 +----GtkEventBox

Implemented Interfaces

GtkEventBox implements AtkImplementorIface.

Properties

  "above-child"              gboolean              : Read / Write
  "visible-window"           gboolean              : Read / Write

Description

The GtkEventBox widget is a subclass of GtkBin which also has its own window. It is useful since it allows you to catch events for widgets which do not have their own window.

Details

GtkEventBox

typedef struct _GtkEventBox GtkEventBox;

The GtkEventBox struct contains private data only, and should be accessed using the functions below.

gtk_event_box_new ()

GtkWidget*          gtk_event_box_new                   (void);

Creates a new GtkEventBox.

Returns : a new GtkEventBox.

gtk_event_box_set_above_child ()

void                gtk_event_box_set_above_child       (GtkEventBox *event_box,
                                                         gboolean above_child);

Set whether the event box window is positioned above the windows of its child, as opposed to below it. If the window is above, all events inside the event box will go to the event box. If the window is below, events in windows of child widgets will first got to that widget, and then to its parents.

The default is to keep the window below the child.

event_box : | a GtkEventBox
above_child : | TRUE if the event box window is above the windows of its child

Since 2.4

gtk_event_box_get_above_child ()

gboolean            gtk_event_box_get_above_child       (GtkEventBox *event_box);

Returns whether the event box window is above or below the windows of its child. See gtk_event_box_set_above_child() for details.

event_box : | a GtkEventBox
Returns : | TRUE if the event box window is above the window of its child.

Since 2.4

gtk_event_box_set_visible_window ()

void                gtk_event_box_set_visible_window    (GtkEventBox *event_box,
                                                         gboolean visible_window);

Set whether the event box uses a visible or invisible child window. The default is to use visible windows.

In an invisible window event box, the window that that the event box creates is a GDK_INPUT_ONLY window, which means that it is invisible and only serves to receive events.

A visible window event box creates a visible (GDK_INPUT_OUTPUT) window that acts as the parent window for all the widgets contained in the event box.

You should generally make your event box invisible if you just want to trap events. Creating a visible window may cause artifacts that are visible to the user, especially if the user is using a theme with gradients or pixmaps.

The main reason to create a non input-only event box is if you want to set the background to a different color or draw on it.

Note

There is one unexpected issue for an invisible event box that has its window below the child. (See gtk_event_box_set_above_child().) Since the input-only window is not an ancestor window of any windows that descendent widgets of the event box create, events on these windows aren't propagated up by the windowing system, but only by GTK+. The practical effect of this is if an event isn't in the event mask for the descendant window (see gtk_widget_add_events()), it won't be received by the event box.

This problem doesn't occur for visible event boxes, because in that case, the event box window is actually the ancestor of the descendant windows, not just at the same place on the screen.

event_box : | a GtkEventBox
visible_window : | boolean value

Since 2.4

gtk_event_box_get_visible_window ()

gboolean            gtk_event_box_get_visible_window    (GtkEventBox *event_box);

Returns whether the event box has a visible window. See gtk_event_box_set_visible_window() for details.

event_box : | a GtkEventBox
Returns : | TRUE if the event box window is visible

Since 2.4

Property Details

The "above-child" property

  "above-child"              gboolean              : Read / Write

Whether the event-trapping window of the eventbox is above the window of the child widget as opposed to below it.

Default value: FALSE

The "visible-window" property

  "visible-window"           gboolean              : Read / Write

Whether the event box is visible, as opposed to invisible and only used to trap events.

Default value: TRUE


GtkExpander

GtkExpander — A container which can hide its child

Synopsis

#include <gtk/gtk.h>

                    GtkExpander;
GtkWidget*          gtk_expander_new                    (const gchar *label);
GtkWidget*          gtk_expander_new_with_mnemonic      (const gchar *label);
void                gtk_expander_set_expanded           (GtkExpander *expander,
                                                         gboolean expanded);
gboolean            gtk_expander_get_expanded           (GtkExpander *expander);
void                gtk_expander_set_spacing            (GtkExpander *expander,
                                                         gint spacing);
gint                gtk_expander_get_spacing            (GtkExpander *expander);
void                gtk_expander_set_label              (GtkExpander *expander,
                                                         const gchar *label);
const gchar*        gtk_expander_get_label              (GtkExpander *expander);
void                gtk_expander_set_use_underline      (GtkExpander *expander,
                                                         gboolean use_underline);
gboolean            gtk_expander_get_use_underline      (GtkExpander *expander);
void                gtk_expander_set_use_markup         (GtkExpander *expander,
                                                         gboolean use_markup);
gboolean            gtk_expander_get_use_markup         (GtkExpander *expander);
void                gtk_expander_set_label_widget       (GtkExpander *expander,
                                                         GtkWidget *label_widget);
GtkWidget*          gtk_expander_get_label_widget       (GtkExpander *expander);

Object Hierarchy

  GObject
   +----GInitiallyUnowned
         +----GtkObject
               +----GtkWidget
                     +----GtkContainer
                           +----GtkBin
                                 +----GtkExpander

Implemented Interfaces

GtkExpander implements AtkImplementorIface.

Properties

  "expanded"                 gboolean              : Read / Write / Construct
  "label"                    gchararray            : Read / Write / Construct
  "label-widget"             GtkWidget             : Read / Write
  "spacing"                  gint                  : Read / Write
  "use-markup"               gboolean              : Read / Write / Construct
  "use-underline"            gboolean              : Read / Write / Construct

Style Properties

  "expander-size"            gint                  : Read
  "expander-spacing"         gint                  : Read

Signals

  "activate"                                       : Run Last / Action

Description

A GtkExpander allows the user to hide or show its child by clicking on an expander triangle similar to the triangles used in a GtkTreeView.

Normally you use an expander as you would use any other descendant of GtkBin; you create the child widget and use gtk_container_add() to add it to the expander. When the expander is toggled, it will take care of showing and hiding the child automatically.

Special Usage

There are situations in which you may prefer to show and hide the expanded widget yourself, such as when you want to actually create the widget at expansion time. In this case, create a GtkExpander but do not add a child to it. The expander widget has an expanded property which can be used to monitor its expansion state. You should watch this property with a signal connection as follows:

expander = gtk_expander_new_with_mnemonic ("_More Options");
g_signal_connect (expander, "notify::expanded",
                  G_CALLBACK (expander_callback), NULL);

...

static void
expander_callback (GObject    *object,
                   GParamSpec *param_spec,
                   gpointer    user_data)
{
  GtkExpander *expander;

  expander = GTK_EXPANDER (object);

  if (gtk_expander_get_expanded (expander))
    {
      /* Show or create widgets */
    }
  else
    {
      /* Hide or destroy widgets */
    }
}

Details

GtkExpander

typedef struct _GtkExpander GtkExpander;

gtk_expander_new ()

GtkWidget*          gtk_expander_new                    (const gchar *label);

Creates a new expander using label as the text of the label.

label : | the text of the label
Returns : | a new GtkExpander widget.

Since 2.4

gtk_expander_new_with_mnemonic ()

GtkWidget*          gtk_expander_new_with_mnemonic      (const gchar *label);

Creates a new expander using label as the text of the label. If characters in label are preceded by an underscore, they are underlined. If you need a literal underscore character in a label, use '__' (two underscores). The first underlined character represents a keyboard accelerator called a mnemonic. Pressing Alt and that key activates the button.

label : | the text of the label with an underscore in front of the mnemonic character
Returns : | a new GtkExpander widget.

Since 2.4

gtk_expander_set_expanded ()

void                gtk_expander_set_expanded           (GtkExpander *expander,
                                                         gboolean expanded);

Sets the state of the expander. Set to TRUE, if you want the child widget to be revealed, and FALSE if you want the child widget to be hidden.

expander : | a GtkExpander
expanded : | whether the child widget is revealed

Since 2.4

gtk_expander_get_expanded ()

gboolean            gtk_expander_get_expanded           (GtkExpander *expander);

Queries a GtkExpander and returns its current state. Returns TRUE if the child widget is revealed.

See gtk_expander_set_expanded().

expander : | a GtkExpander
Returns : | the current state of the expander.

Since 2.4

gtk_expander_set_spacing ()

void                gtk_expander_set_spacing            (GtkExpander *expander,
                                                         gint spacing);

Sets the spacing field of expander, which is the number of pixels to place between expander and the child.

expander : | a GtkExpander
spacing : | distance between the expander and child in pixels.

Since 2.4

gtk_expander_get_spacing ()

gint                gtk_expander_get_spacing            (GtkExpander *expander);

Gets the value set by gtk_expander_set_spacing().

expander : | a GtkExpander
Returns : | spacing between the expander and child.

Since 2.4

gtk_expander_set_label ()

void                gtk_expander_set_label              (GtkExpander *expander,
                                                         const gchar *label);

Sets the text of the label of the expander to label.

This will also clear any previously set labels.

expander : | a GtkExpander
label : | a string

Since 2.4

gtk_expander_get_label ()

const gchar*        gtk_expander_get_label              (GtkExpander *expander);

Fetches the text from the label of the expander, as set by gtk_expander_set_label(). If the label text has not been set the return value will be NULL. This will be the case if you create an empty button with gtk_button_new() to use as a container.

expander : | a GtkExpander
Returns : | The text of the label widget. This string is owned by the widget and must not be modified or freed.

Since 2.4

gtk_expander_set_use_underline ()

void                gtk_expander_set_use_underline      (GtkExpander *expander,
                                                         gboolean use_underline);

If true, an underline in the text of the expander label indicates the next character should be used for the mnemonic accelerator key.

expander : | a GtkExpander
use_underline : | TRUE if underlines in the text indicate mnemonics

Since 2.4

gtk_expander_get_use_underline ()

gboolean            gtk_expander_get_use_underline      (GtkExpander *expander);

Returns whether an embedded underline in the expander label indicates a mnemonic. See gtk_expander_set_use_underline().

expander : | a GtkExpander
Returns : | TRUE if an embedded underline in the expander label indicates the mnemonic accelerator keys.

Since 2.4

gtk_expander_set_use_markup ()

void                gtk_expander_set_use_markup         (GtkExpander *expander,
                                                         gboolean use_markup);

Sets whether the text of the label contains markup in Pango's text markup language. See gtk_label_set_markup().

expander : | a GtkExpander
use_markup : | TRUE if the label's text should be parsed for markup

Since 2.4

gtk_expander_get_use_markup ()

gboolean            gtk_expander_get_use_markup         (GtkExpander *expander);

Returns whether the label's text is interpreted as marked up with the Pango text markup language. See gtk_expander_set_use_markup().

expander : | a GtkExpander
Returns : | TRUE if the label's text will be parsed for markup

Since 2.4

gtk_expander_set_label_widget ()

void                gtk_expander_set_label_widget       (GtkExpander *expander,
                                                         GtkWidget *label_widget);

Set the label widget for the expander. This is the widget that will appear embedded alongside the expander arrow.

expander : | a GtkExpander
label_widget : | the new label widget

Since 2.4

gtk_expander_get_label_widget ()

GtkWidget*          gtk_expander_get_label_widget       (GtkExpander *expander);

Retrieves the label widget for the frame. See gtk_expander_set_label_widget().

expander : | a GtkExpander
Returns : | the label widget, or NULL if there is none.

Since 2.4

Property Details

The "expanded" property

  "expanded"                 gboolean              : Read / Write / Construct

Whether the expander has been opened to reveal the child widget.

Default value: FALSE

The "label" property

  "label"                    gchararray            : Read / Write / Construct

Text of the expander's label.

Default value: NULL

The "label-widget" property

  "label-widget"             GtkWidget             : Read / Write

A widget to display in place of the usual expander label.

The "spacing" property

  "spacing"                  gint                  : Read / Write

Space to put between the label and the child.

Allowed values: >= 0

Default value: 0

The "use-markup" property

  "use-markup"               gboolean              : Read / Write / Construct

The text of the label includes XML markup. See pango_parse_markup().

Default value: FALSE

The "use-underline" property

  "use-underline"            gboolean              : Read / Write / Construct

If set, an underline in the text indicates the next character should be used for the mnemonic accelerator key.

Default value: FALSE

Style Property Details

The "expander-size" style property

  "expander-size"            gint                  : Read

Size of the expander arrow.

Allowed values: >= 0

Default value: 10

The "expander-spacing" style property

  "expander-spacing"         gint                  : Read

Spacing around expander arrow.

Allowed values: >= 0

Default value: 2

Signal Details

The "activate" signal

void                user_function                      (GtkExpander *expander,
                                                        gpointer     user_data)      : Run Last / Action

expander : | the object which received the signal.
user_data : | user data set when the signal handler was connected.


GtkFileChooser

GtkFileChooser — File chooser interface used by GtkFileChooserWidget and GtkFileChooserDialog

Synopsis

#include <gtk/gtk.h>

                    GtkFileChooser;
enum                GtkFileChooserAction;
enum                GtkFileChooserConfirmation;
#define             GTK_FILE_CHOOSER_ERROR
enum                GtkFileChooserError;
void                gtk_file_chooser_set_action         (GtkFileChooser *chooser,
                                                         GtkFileChooserAction action);
GtkFileChooserAction gtk_file_chooser_get_action        (GtkFileChooser *chooser);
void                gtk_file_chooser_set_local_only     (GtkFileChooser *chooser,
                                                         gboolean local_only);
gboolean            gtk_file_chooser_get_local_only     (GtkFileChooser *chooser);
void                gtk_file_chooser_set_select_multiple
                                                        (GtkFileChooser *chooser,
                                                         gboolean select_multiple);
gboolean            gtk_file_chooser_get_select_multiple
                                                        (GtkFileChooser *chooser);
void                gtk_file_chooser_set_show_hidden    (GtkFileChooser *chooser,
                                                         gboolean show_hidden);
gboolean            gtk_file_chooser_get_show_hidden    (GtkFileChooser *chooser);
void                gtk_file_chooser_set_do_overwrite_confirmation
                                                        (GtkFileChooser *chooser,
                                                         gboolean do_overwrite_confirmation);
gboolean            gtk_file_chooser_get_do_overwrite_confirmation
                                                        (GtkFileChooser *chooser);
void                gtk_file_chooser_set_current_name   (GtkFileChooser *chooser,
                                                         const gchar *name);
gchar*              gtk_file_chooser_get_filename       (GtkFileChooser *chooser);
gboolean            gtk_file_chooser_set_filename       (GtkFileChooser *chooser,
                                                         const char *filename);
gboolean            gtk_file_chooser_select_filename    (GtkFileChooser *chooser,
                                                         const char *filename);
void                gtk_file_chooser_unselect_filename  (GtkFileChooser *chooser,
                                                         const char *filename);
void                gtk_file_chooser_select_all         (GtkFileChooser *chooser);
void                gtk_file_chooser_unselect_all       (GtkFileChooser *chooser);
GSList*             gtk_file_chooser_get_filenames      (GtkFileChooser *chooser);
gboolean            gtk_file_chooser_set_current_folder (GtkFileChooser *chooser,
                                                         const gchar *filename);
gchar*              gtk_file_chooser_get_current_folder (GtkFileChooser *chooser);
gchar*              gtk_file_chooser_get_uri            (GtkFileChooser *chooser);
gboolean            gtk_file_chooser_set_uri            (GtkFileChooser *chooser,
                                                         const char *uri);
gboolean            gtk_file_chooser_select_uri         (GtkFileChooser *chooser,
                                                         const char *uri);
void                gtk_file_chooser_unselect_uri       (GtkFileChooser *chooser,
                                                         const char *uri);
GSList*             gtk_file_chooser_get_uris           (GtkFileChooser *chooser);
gboolean            gtk_file_chooser_set_current_folder_uri
                                                        (GtkFileChooser *chooser,
                                                         const gchar *uri);
gchar*              gtk_file_chooser_get_current_folder_uri
                                                        (GtkFileChooser *chooser);
void                gtk_file_chooser_set_preview_widget (GtkFileChooser *chooser,
                                                         GtkWidget *preview_widget);
GtkWidget*          gtk_file_chooser_get_preview_widget (GtkFileChooser *chooser);
void                gtk_file_chooser_set_preview_widget_active
                                                        (GtkFileChooser *chooser,
                                                         gboolean active);
gboolean            gtk_file_chooser_get_preview_widget_active
                                                        (GtkFileChooser *chooser);
void                gtk_file_chooser_set_use_preview_label
                                                        (GtkFileChooser *chooser,
                                                         gboolean use_label);
gboolean            gtk_file_chooser_get_use_preview_label
                                                        (GtkFileChooser *chooser);
char*               gtk_file_chooser_get_preview_filename
                                                        (GtkFileChooser *chooser);
char*               gtk_file_chooser_get_preview_uri    (GtkFileChooser *chooser);
void                gtk_file_chooser_set_extra_widget   (GtkFileChooser *chooser,
                                                         GtkWidget *extra_widget);
GtkWidget*          gtk_file_chooser_get_extra_widget   (GtkFileChooser *chooser);
void                gtk_file_chooser_add_filter         (GtkFileChooser *chooser,
                                                         GtkFileFilter *filter);
void                gtk_file_chooser_remove_filter      (GtkFileChooser *chooser,
                                                         GtkFileFilter *filter);
GSList*             gtk_file_chooser_list_filters       (GtkFileChooser *chooser);
void                gtk_file_chooser_set_filter         (GtkFileChooser *chooser,
                                                         GtkFileFilter *filter);
GtkFileFilter*      gtk_file_chooser_get_filter         (GtkFileChooser *chooser);
gboolean            gtk_file_chooser_add_shortcut_folder
                                                        (GtkFileChooser *chooser,
                                                         const char *folder,
                                                         GError **error);
gboolean            gtk_file_chooser_remove_shortcut_folder
                                                        (GtkFileChooser *chooser,
                                                         const char *folder,
                                                         GError **error);
GSList*             gtk_file_chooser_list_shortcut_folders
                                                        (GtkFileChooser *chooser);
gboolean            gtk_file_chooser_add_shortcut_folder_uri
                                                        (GtkFileChooser *chooser,
                                                         const char *uri,
                                                         GError **error);
gboolean            gtk_file_chooser_remove_shortcut_folder_uri
                                                        (GtkFileChooser *chooser,
                                                         const char *uri,
                                                         GError **error);
GSList*             gtk_file_chooser_list_shortcut_folder_uris
                                                        (GtkFileChooser *chooser);

Object Hierarchy

  GInterface
   +----GtkFileChooser

Prerequisites

GtkFileChooser requires GtkWidget.

Known Implementations

GtkFileChooser is implemented by GtkFileChooserWidget, GtkFileChooserButton and GtkFileChooserDialog.

Signals

  "confirm-overwrite"                              : Run Last
  "current-folder-changed"                         : Run Last
  "file-activated"                                 : Run Last
  "selection-changed"                              : Run Last
  "update-preview"                                 : Run Last

Description

GtkFileChooser is an interface that can be implemented by file selection widgets. In GTK+, the main objects that implement this interface are GtkFileChooserWidget, GtkFileChooserDialog, and GtkFileChooserButton. You do not need to write an object that implements the GtkFileChooser interface unless you are trying to adapt an existing file selector to expose a standard programming interface.

GtkFileChooser allows for shortcuts to various places in the filesystem. In the default implementation these are displayed in the left pane. It may be a bit confusing at first taht these shortcuts come from various sources and in various flavours, so lets explain the terminology here:

Bookmarks | are created by the user, by dragging folders from the right pane to the left pane, or by using the "Add". Bookmarks can be renamed and deleted by the user.
Shortcuts | can be provided by the application or by the underlying filesystem abstraction (e.g. both the gnome-vfs and the Windows filesystems provide "Desktop" shortcuts). Shortcuts cannot be modified by the user.
Volumes | are provided by the underlying filesystem abstraction. They are the "roots" of the filesystem.

File Names and Encodings

When the user is finished selecting files in a GtkFileChooser, your program can get the selected names either as filenames or as URIs. For URIs, the normal escaping rules are applied if the URI contains non-ASCII characters. However, filenames are always returned in the character set specified by the G_FILENAME_ENCODING environment variable. Please see the Glib documentation for more details about this variable.

Important

This means that while you can pass the result of gtk_file_chooser_get_filename() to open(2) or fopen(3), you may not be able to directly set it as the text of a GtkLabel widget unless you convert it first to UTF-8, which all GTK+ widgets expect. You should use g_filename_to_utf8() to convert filenames into strings that can be passed to GTK+ widgets.

Adding a Preview Widget

You can add a custom preview widget to a file chooser and then get notification about when the preview needs to be updated. To install a preview widget, use gtk_file_chooser_set_preview_widget(). Then, connect to the GtkFileChooser::update-preview signal to get notified when you need to update the contents of the preview.

Your callback should use gtk_file_chooser_get_preview_filename() to see what needs previewing. Once you have generated the preview for the corresponding file, you must call gtk_file_chooser_set_preview_widget_active() with a boolean flag that indicates whether your callback could successfully generate a preview.

Example 24. Sample Usage

{
  GtkImage *preview;

  ...

  preview = gtk_image_new ();

  gtk_file_chooser_set_preview_widget (my_file_chooser, preview);
  g_signal_connect (my_file_chooser, "update-preview",
            G_CALLBACK (update_preview_cb), preview);
}

static void
update_preview_cb (GtkFileChooser *file_chooser, gpointer data)
{
  GtkWidget *preview;
  char *filename;
  GdkPixbuf *pixbuf;
  gboolean have_preview;

  preview = GTK_WIDGET (data);
  filename = gtk_file_chooser_get_preview_filename (file_chooser);

  pixbuf = gdk_pixbuf_new_from_file_at_size (filename, 128, 128, NULL);
  have_preview = (pixbuf != NULL);
  g_free (filename);

  gtk_image_set_from_pixbuf (GTK_IMAGE (preview), pixbuf);
  if (pixbuf)
    gobject_unref (pixbuf);

  gtk_file_chooser_set_preview_widget_active (file_chooser, have_preview);
}

Adding Extra Widgets

You can add extra widgets to a file chooser to provide options that are not present in the default design. For example, you can add a toggle button to give the user the option to open a file in read-only mode. You can use gtk_file_chooser_set_extra_widget() to insert additional widgets in a file chooser.

Example 25. Sample Usage

{
  GtkWidget *toggle;

  ...

  toggle = gtk_check_button_new_with_label ("Open file read-only");
  gtk_widget_show (toggle);
  gtk_file_chooser_set_extra_widget (my_file_chooser, toggle);
}

Note

If you want to set more than one extra widget in the file chooser, you can a container such as a GtkVBox or a GtkTable and include your widgets in it. Then, set the container as the whole extra widget.

Key Bindings

Internally, GTK+ implements a file chooser's graphical user interface with the private GtkFileChooserDefaultClass. This widget has several key bindings and their associated signals. This section describes the available key binding signals.

Example 26. GtkFileChooser key binding example

The default keys that activate the key-binding signals in GtkFileChooserDefaultClass are as follows:

Signal name | Default key combinations
location-popup | Control-L (empty path); / (path of "/")[a]; ~ (path of "~")
up-folder | Alt-Up[b] ; Backspace
down-folder | Alt-Down
home-folder | Alt-Home
desktop-folder | Alt-D
quick-bookmark | Alt-1 through Alt-0
[a] Both the individual / key and the numeric keypad's "divide" key are supported. [b] Both the individual Up key and the numeric keypad's Up key are supported.

You can change these defaults to something else. For example, to add a Shift modifier to a few of the default bindings, you can include the following fragment in your .gtkrc-2.0 file:

binding "my-own-gtkfilechooser-bindings" {
    bind "<Alt><Shift>Up" {
        "up-folder" ()
    }
    bind "<Alt><Shift>Down" {
        "down-folder" ()
    }
    bind "<Alt><Shift>Home" {
        "home-folder" ()
    }
}

class "GtkFileChooserDefault" binding "my-own-gtkfilechooser-bindings"

The "GtkFileChooserDefault::location-popup" signal

          void user_function (GtkFileChooserDefault *chooser,
                              const char            *path,
                              gpointer user_data);

This is used to make the file chooser show a "Location" dialog which the user can use to manually type the name of the file he wishes to select. The path argument is a string that gets put in the text entry for the file name. By default this is bound to Control-L with a path string of "" (the empty string). It is also bound to / with a path string of "/" (a slash): this lets you type / and immediately type a path name. On Unix systems, this is bound to ~ (tilde) with a path string of "~" itself for access to home directories.

chooser : | the object which received the signal.
path : | default contents for the text entry for the file name
user_data : | user data set when the signal handler was connected.

Tip

You can create your own bindings for the location-popup signal with custom path strings, and have a crude form of easily-to-type bookmarks. For example, say you access the path /home/username/misc very frequently. You could then create an Alt-M shortcut by including the following in your .gtkrc-2.0:

binding "misc-shortcut" {
    bind "<Alt>M" {
        "location-popup" ("/home/username/misc")
    }
}

class "GtkFileChooserDefault" binding "misc-shortcut"

The "GtkFileChooserDefault::up-folder" signal

          void user_function (GtkFileChooserDefault *chooser,
                              gpointer user_data);

This is used to make the file chooser go to the parent of the current folder in the file hierarchy. By default this is bound to Backspace and Alt-Up (the Up key in the numeric keypad also works).

chooser : | the object which received the signal.
user_data : | user data set when the signal handler was connected.

The "GtkFileChooserDefault::down-folder" signal

          void user_function (GtkFileChooserDefault *chooser,
                              gpointer user_data);

This is used to make the file chooser go to a child of the current folder in the file hierarchy. The subfolder that will be used is displayed in the path bar widget of the file chooser. For example, if the path bar is showing "/foo/bar/baz", then this will cause the file chooser to switch to the "baz" subfolder. By default this is bound to Alt-Down (the Down key in the numeric keypad also works).

chooser : | the object which received the signal.
user_data : | user data set when the signal handler was connected.

The "GtkFileChooserDefault::home-folder" signal

          void user_function (GtkFileChooserDefault *chooser,
                              gpointer user_data);

This is used to make the file chooser show the user's home folder in the file list. By default this is bound to Alt-Home (the Home key in the numeric keypad also works).

chooser : | the object which received the signal.
user_data : | user data set when the signal handler was connected.

The "GtkFileChooserDefault::desktop-folder" signal

          void user_function (GtkFileChooserDefault *chooser,
                              gpointer user_data);

This is used to make the file chooser show the user's Desktop folder in the file list. By default this is bound to Alt-D.

chooser : | the object which received the signal.
user_data : | user data set when the signal handler was connected.

The "GtkFileChooserDefault::quick-bookmark" signal

          void user_function (GtkFileChooserDefault *chooser,
                              gint bookmark_index,
                              gpointer user_data);

This is used to make the file chooser switch to the bookmark specified in the bookmark_index parameter. For example, if you have three bookmarks, you can pass 0, 1, 2 to this signal to switch to each of them, respectively. By default this is bound to Alt-1, Alt-2, etc. until Alt-0. Note that in the default binding, that Alt-1 is actually defined to switch to the bookmark at index 0, and so on successively; Alt-0 is defined to switch to the bookmark at index 10.

chooser : | the object which received the signal.
bookmark_indes : | index of the bookmark to switch to; the indices start at 0.
user_data : | user data set when the signal handler was connected.

Details

GtkFileChooser

typedef struct _GtkFileChooser GtkFileChooser;

enum GtkFileChooserAction

typedef enum
{
  GTK_FILE_CHOOSER_ACTION_OPEN,
  GTK_FILE_CHOOSER_ACTION_SAVE,
  GTK_FILE_CHOOSER_ACTION_SELECT_FOLDER,
  GTK_FILE_CHOOSER_ACTION_CREATE_FOLDER
} GtkFileChooserAction;

Describes whether a GtkFileChooser is being used to open existing files or to save to a possibly new file.

GTK_FILE_CHOOSER_ACTION_OPEN | Indicates open mode. The file chooser will only let the user pick an existing file.
GTK_FILE_CHOOSER_ACTION_SAVE | Indicates save mode. The file chooser will let the user pick an existing file, or type in a new filename.
GTK_FILE_CHOOSER_ACTION_SELECT_FOLDER | Indicates an Open mode for selecting folders. The file chooser will let the user pick an existing folder.
GTK_FILE_CHOOSER_ACTION_CREATE_FOLDER | Indicates a mode for creating a new folder. The file chooser will let the user name an existing or new folder.

enum GtkFileChooserConfirmation

typedef enum
{
  GTK_FILE_CHOOSER_CONFIRMATION_CONFIRM,
  GTK_FILE_CHOOSER_CONFIRMATION_ACCEPT_FILENAME,
  GTK_FILE_CHOOSER_CONFIRMATION_SELECT_AGAIN
} GtkFileChooserConfirmation;

Used as a return value of handlers for the confirm-overwrite signal of a GtkFileChooser. This value determines whether the file chooser will present the stock confirmation dialog, accept the user's choice of a filename, or let the user choose another filename.

GTK_FILE_CHOOSER_CONFIRMATION_CONFIRM | The file chooser will present its stock dialog to confirm about overwriting an existing file.
GTK_FILE_CHOOSER_CONFIRMATION_ACCEPT_FILENAME | The file chooser will terminate and accept the user's choice of a file name.
GTK_FILE_CHOOSER_CONFIRMATION_SELECT_AGAIN | The file chooser will continue running, so as to let the user select another file name. Since 2.8

GTK_FILE_CHOOSER_ERROR

#define GTK_FILE_CHOOSER_ERROR (gtk_file_chooser_error_quark ())

Used to get the GError quark for GtkFileChooser errors.

enum GtkFileChooserError

typedef enum {
  GTK_FILE_CHOOSER_ERROR_NONEXISTENT,
  GTK_FILE_CHOOSER_ERROR_BAD_FILENAME,
  GTK_FILE_CHOOSER_ERROR_ALREADY_EXISTS
} GtkFileChooserError;

These identify the various errors that can occur while calling GtkFileChooser functions.

GTK_FILE_CHOOSER_ERROR_NONEXISTENT | Indicates that a file does not exist.
GTK_FILE_CHOOSER_ERROR_BAD_FILENAME | Indicates a malformed filename.
GTK_FILE_CHOOSER_ERROR_ALREADY_EXISTS |

gtk_file_chooser_set_action ()

void                gtk_file_chooser_set_action         (GtkFileChooser *chooser,
                                                         GtkFileChooserAction action);

Sets the type of operation that the chooser is performing; the user interface is adapted to suit the selected action. For example, an option to create a new folder might be shown if the action is GTK_FILE_CHOOSER_ACTION_SAVE but not if the action is GTK_FILE_CHOOSER_ACTION_OPEN.

chooser : | a GtkFileChooser
action : | the action that the file selector is performing

Since 2.4

gtk_file_chooser_get_action ()

GtkFileChooserAction gtk_file_chooser_get_action        (GtkFileChooser *chooser);

Gets the type of operation that the file chooser is performing; see gtk_file_chooser_set_action().

chooser : | a GtkFileChooser
Returns : | the action that the file selector is performing

Since 2.4

gtk_file_chooser_set_local_only ()

void                gtk_file_chooser_set_local_only     (GtkFileChooser *chooser,
                                                         gboolean local_only);

Sets whether only local files can be selected in the file selector. If local_only is TRUE (the default), then the selected file are files are guaranteed to be accessible through the operating systems native file file system and therefore the application only needs to worry about the filename functions in GtkFileChooser, like gtk_file_chooser_get_filename(), rather than the URI functions like gtk_file_chooser_get_uri(),

chooser : | a GtkFileChooser
local_only : | TRUE if only local files can be selected

Since 2.4

gtk_file_chooser_get_local_only ()

gboolean            gtk_file_chooser_get_local_only     (GtkFileChooser *chooser);

Gets whether only local files can be selected in the file selector. See gtk_file_chooser_set_local_only()

chooser : | a GtkFileChoosre
Returns : | TRUE if only local files can be selected.

Since 2.4

gtk_file_chooser_set_select_multiple ()

void                gtk_file_chooser_set_select_multiple
                                                        (GtkFileChooser *chooser,
                                                         gboolean select_multiple);

Sets whether multiple files can be selected in the file selector. This is only relevant if the action is set to be GTK_FILE_CHOOSER_ACTION_OPEN or GTK_FILE_CHOOSER_ACTION_SELECT_FOLDER.

chooser : | a GtkFileChooser
select_multiple : | TRUE if multiple files can be selected.

Since 2.4

gtk_file_chooser_get_select_multiple ()

gboolean            gtk_file_chooser_get_select_multiple
                                                        (GtkFileChooser *chooser);

Gets whether multiple files can be selected in the file selector. See gtk_file_chooser_set_select_multiple().

chooser : | a GtkFileChooser
Returns : | TRUE if multiple files can be selected.

Since 2.4

gtk_file_chooser_set_show_hidden ()

void                gtk_file_chooser_set_show_hidden    (GtkFileChooser *chooser,
                                                         gboolean show_hidden);

Sets whether hidden files and folders are displayed in the file selector.

chooser : | a GtkFileChooser
show_hidden : | TRUE if hidden files and folders should be displayed.

Since 2.6

gtk_file_chooser_get_show_hidden ()

gboolean            gtk_file_chooser_get_show_hidden    (GtkFileChooser *chooser);

Gets whether hidden files and folders are displayed in the file selector. See gtk_file_chooser_set_show_hidden().

chooser : | a GtkFileChooser
Returns : | TRUE if hidden files and folders are displayed.

Since 2.6

gtk_file_chooser_set_do_overwrite_confirmation ()

void                gtk_file_chooser_set_do_overwrite_confirmation
                                                        (GtkFileChooser *chooser,
                                                         gboolean do_overwrite_confirmation);

Sets whether a file chooser in GTK_FILE_CHOOSER_ACTION_SAVE mode will present a confirmation dialog if the user types a file name that already exists. This is FALSE by default.

Regardless of this setting, the chooser will emit the "confirm-overwrite" signal when appropriate.

If all you need is the stock confirmation dialog, set this property to TRUE. You can override the way confirmation is done by actually handling the "confirm-overwrite" signal; please refer to its documentation for the details.

chooser : | a GtkFileChooser
do_overwrite_confirmation : | whether to confirm overwriting in save mode

Since 2.8

gtk_file_chooser_get_do_overwrite_confirmation ()

gboolean            gtk_file_chooser_get_do_overwrite_confirmation
                                                        (GtkFileChooser *chooser);

Queries whether a file chooser is set to confirm for overwriting when the user types a file name that already exists.

chooser : | a GtkFileChooser
Returns : | TRUE if the file chooser will present a confirmation dialog; FALSE otherwise.

Since 2.8

gtk_file_chooser_set_current_name ()

void                gtk_file_chooser_set_current_name   (GtkFileChooser *chooser,
                                                         const gchar *name);

Sets the current name in the file selector, as if entered by the user. Note that the name passed in here is a UTF-8 string rather than a filename. This function is meant for such uses as a suggested name in a "Save As..." dialog.

If you want to preselect a particular existing file, you should use gtk_file_chooser_set_filename() or gtk_file_chooser_set_uri() instead. Please see the documentation for those functions for an example of using gtk_file_chooser_set_current_name() as well.

chooser : | a GtkFileChooser
name : | the filename to use, as a UTF-8 string

Since 2.4

gtk_file_chooser_get_filename ()

gchar*              gtk_file_chooser_get_filename       (GtkFileChooser *chooser);

Gets the filename for the currently selected file in the file selector. If multiple files are selected, one of the filenames will be returned at random.

If the file chooser is in folder mode, this function returns the selected folder.

chooser : | a GtkFileChooser
Returns : | The currently selected filename, or NULL if no file is selected, or the selected file can't be represented with a local filename. Free with g_free().

Since 2.4

gtk_file_chooser_set_filename ()

gboolean            gtk_file_chooser_set_filename       (GtkFileChooser *chooser,
                                                         const char *filename);

Sets filename as the current filename for the file chooser, by changing to the file's parent folder and actually selecting the file in list. If the chooser is in GTK_FILE_CHOOSER_ACTION_SAVE mode, the file's base name will also appear in the dialog's file name entry.

If the file name isn't in the current folder of chooser, then the current folder of chooser will be changed to the folder containing filename. This is equivalent to a sequence of gtk_file_chooser_unselect_all() followed by gtk_file_chooser_select_filename().

Note that the file must exist, or nothing will be done except for the directory change.

If you are implementing a File/Save As... dialog, you should use this function if you already have a file name to which the user may save; for example, when the user opens an existing file and then does File/Save As... on it. If you don't have a file name already — for example, if the user just created a new file and is saving it for the first time, do not call this function. Instead, use something similar to this:

if (document_is_new)
  {
    /* the user just created a new document */
    gtk_file_chooser_set_current_folder (chooser, default_folder_for_saving);
    gtk_file_chooser_set_current_name (chooser, "Untitled document");
  }
else
  {
    /* the user edited an existing document */
    gtk_file_chooser_set_filename (chooser, existing_filename);
  }

chooser : | a GtkFileChooser
filename : | the filename to set as current
Returns : | TRUE if both the folder could be changed and the file was selected successfully, FALSE otherwise.

Since 2.4

gtk_file_chooser_select_filename ()

gboolean            gtk_file_chooser_select_filename    (GtkFileChooser *chooser,
                                                         const char *filename);

Selects a filename. If the file name isn't in the current folder of chooser, then the current folder of chooser will be changed to the folder containing filename.

chooser : | a GtkFileChooser
filename : | the filename to select
Returns : | TRUE if both the folder could be changed and the file was selected successfully, FALSE otherwise.

Since 2.4

gtk_file_chooser_unselect_filename ()

void                gtk_file_chooser_unselect_filename  (GtkFileChooser *chooser,
                                                         const char *filename);

Unselects a currently selected filename. If the filename is not in the current directory, does not exist, or is otherwise not currently selected, does nothing.

chooser : | a GtkFileChooser
filename : | the filename to unselect

Since 2.4

gtk_file_chooser_select_all ()

void                gtk_file_chooser_select_all         (GtkFileChooser *chooser);

Selects all the files in the current folder of a file chooser.

chooser : a GtkFileChooser

Since 2.4

gtk_file_chooser_unselect_all ()

void                gtk_file_chooser_unselect_all       (GtkFileChooser *chooser);

Unselects all the files in the current folder of a file chooser.

chooser : a GtkFileChooser

Since 2.4

gtk_file_chooser_get_filenames ()

GSList*             gtk_file_chooser_get_filenames      (GtkFileChooser *chooser);

Lists all the selected files and subfolders in the current folder of chooser. The returned names are full absolute paths. If files in the current folder cannot be represented as local filenames they will be ignored. (See gtk_file_chooser_get_uris())

chooser : | a GtkFileChooser
Returns : | a GSList containing the filenames of all selected files and subfolders in the current folder. Free the returned list with g_slist_free(), and the filenames with g_free().

Since 2.4

gtk_file_chooser_set_current_folder ()

gboolean            gtk_file_chooser_set_current_folder (GtkFileChooser *chooser,
                                                         const gchar *filename);

Sets the current folder for chooser from a local filename. The user will be shown the full contents of the current folder, plus user interface elements for navigating to other folders.

chooser : | a GtkFileChooser
filename : | the full path of the new current folder
Returns : | TRUE if the folder could be changed successfully, FALSE otherwise.

Since 2.4

gtk_file_chooser_get_current_folder ()

gchar*              gtk_file_chooser_get_current_folder (GtkFileChooser *chooser);

Gets the current folder of chooser as a local filename. See gtk_file_chooser_set_current_folder().

Note that this is the folder that the file chooser is currently displaying (e.g. "/home/username/Documents"), which is not the same as the currently-selected folder if the chooser is in GTK_FILE_CHOOSER_SELECT_FOLDER mode (e.g. "/home/username/Documents/selected-folder/". To get the currently-selected folder in that mode, use gtk_file_chooser_get_uri() as the usual way to get the selection.

chooser : | a GtkFileChooser
Returns : | the full path of the current folder, or NULL if the current path cannot be represented as a local filename. Free with g_free(). This function will also return NULL if the file chooser was unable to load the last folder that was requested from it; for example, as would be for calling gtk_file_chooser_set_current_folder() on a nonexistent folder.

Since 2.4

gtk_file_chooser_get_uri ()

gchar*              gtk_file_chooser_get_uri            (GtkFileChooser *chooser);

Gets the URI for the currently selected file in the file selector. If multiple files are selected, one of the filenames will be returned at random.

If the file chooser is in folder mode, this function returns the selected folder.

chooser : | a GtkFileChooser
Returns : | The currently selected URI, or NULL if no file is selected. Free with g_free()

Since 2.4

gtk_file_chooser_set_uri ()

gboolean            gtk_file_chooser_set_uri            (GtkFileChooser *chooser,
                                                         const char *uri);

Sets the file referred to by uri as the current file for the file chooser, by changing to the URI's parent folder and actually selecting the URI in the list. If the chooser is GTK_FILE_CHOOSER_ACTION_SAVE mode, the URI's base name will also appear in the dialog's file name entry.

If the URI isn't in the current folder of chooser, then the current folder of chooser will be changed to the folder containing uri. This is equivalent to a sequence of gtk_file_chooser_unselect_all() followed by gtk_file_chooser_select_uri().

Note that the URI must exist, or nothing will be done except for the directory change. If you are implementing a File/Save As... dialog, you should use this function if you already have a file name to which the user may save; for example, when the user opens an existing file and then does File/Save As... on it. If you don't have a file name already — for example, if the user just created a new file and is saving it for the first time, do not call this function. Instead, use something similar to this:

if (document_is_new)
  {
    /* the user just created a new document */
    gtk_file_chooser_set_current_folder_uri (chooser, default_folder_for_saving);
    gtk_file_chooser_set_current_name (chooser, "Untitled document");
  }
else
  {
    /* the user edited an existing document */
    gtk_file_chooser_set_uri (chooser, existing_uri);
  }

chooser : | a GtkFileChooser
uri : | the URI to set as current
Returns : | TRUE if both the folder could be changed and the URI was selected successfully, FALSE otherwise.

Since 2.4

gtk_file_chooser_select_uri ()

gboolean            gtk_file_chooser_select_uri         (GtkFileChooser *chooser,
                                                         const char *uri);

Selects the file to by uri. If the URI doesn't refer to a file in the current folder of chooser, then the current folder of chooser will be changed to the folder containing filename.

chooser : | a GtkFileChooser
uri : | the URI to select
Returns : | TRUE if both the folder could be changed and the URI was selected successfully, FALSE otherwise.

Since 2.4

gtk_file_chooser_unselect_uri ()

void                gtk_file_chooser_unselect_uri       (GtkFileChooser *chooser,
                                                         const char *uri);

Unselects the file referred to by uri. If the file is not in the current directory, does not exist, or is otherwise not currently selected, does nothing.

chooser : | a GtkFileChooser
uri : | the URI to unselect

Since 2.4

gtk_file_chooser_get_uris ()

GSList*             gtk_file_chooser_get_uris           (GtkFileChooser *chooser);

Lists all the selected files and subfolders in the current folder of chooser. The returned names are full absolute URIs.

chooser : | a GtkFileChooser
Returns : | a GSList containing the URIs of all selected files and subfolders in the current folder. Free the returned list with g_slist_free(), and the filenames with g_free().

Since 2.4

gtk_file_chooser_set_current_folder_uri ()

gboolean            gtk_file_chooser_set_current_folder_uri
                                                        (GtkFileChooser *chooser,
                                                         const gchar *uri);

Sets the current folder for chooser from an URI. The user will be shown the full contents of the current folder, plus user interface elements for navigating to other folders.

chooser : | a GtkFileChooser
uri : | the URI for the new current folder
Returns : | TRUE if the folder could be changed successfully, FALSE otherwise.

Since 2.4

gtk_file_chooser_get_current_folder_uri ()

gchar*              gtk_file_chooser_get_current_folder_uri
                                                        (GtkFileChooser *chooser);

Gets the current folder of chooser as an URI. See gtk_file_chooser_set_current_folder_uri().

Note that this is the folder that the file chooser is currently displaying (e.g. "file:///home/username/Documents"), which is not the same as the currently-selected folder if the chooser is in GTK_FILE_CHOOSER_SELECT_FOLDER mode (e.g. "file:///home/username/Documents/selected-folder/". To get the currently-selected folder in that mode, use gtk_file_chooser_get_uri() as the usual way to get the selection.

chooser : | a GtkFileChooser
Returns : | the URI for the current folder. Free with g_free(). This function will also return NULL if the file chooser was unable to load the last folder that was requested from it; for example, as would be for calling gtk_file_chooser_set_current_folder_uri() on a nonexistent folder.

Since 2.4

gtk_file_chooser_set_preview_widget ()

void                gtk_file_chooser_set_preview_widget (GtkFileChooser *chooser,
                                                         GtkWidget *preview_widget);

Sets an application-supplied widget to use to display a custom preview of the currently selected file. To implement a preview, after setting the preview widget, you connect to the ::update-preview signal, and call gtk_file_chooser_get_preview_filename() or gtk_file_chooser_get_preview_uri() on each change. If you can display a preview of the new file, update your widget and set the preview active using gtk_file_chooser_set_preview_widget_active(). Otherwise, set the preview inactive.

When there is no application-supplied preview widget, or the application-supplied preview widget is not active, the file chooser may display an internally generated preview of the current file or it may display no preview at all.

chooser : | a GtkFileChooser
preview_widget : | widget for displaying preview.

Since 2.4

gtk_file_chooser_get_preview_widget ()

GtkWidget*          gtk_file_chooser_get_preview_widget (GtkFileChooser *chooser);

Gets the current preview widget; see gtk_file_chooser_set_preview_widget().

chooser : | a GtkFileChooser
Returns : | the current preview widget, or NULL

Since 2.4

gtk_file_chooser_set_preview_widget_active ()

void                gtk_file_chooser_set_preview_widget_active
                                                        (GtkFileChooser *chooser,
                                                         gboolean active);

Sets whether the preview widget set by gtk_file_chooser_set_preview_widget() should be shown for the current filename. When active is set to false, the file chooser may display an internally generated preview of the current file or it may display no preview at all. See gtk_file_chooser_set_preview_widget() for more details.

chooser : | a GtkFileChooser
active : | whether to display the user-specified preview widget

Since 2.4

gtk_file_chooser_get_preview_widget_active ()

gboolean            gtk_file_chooser_get_preview_widget_active
                                                        (GtkFileChooser *chooser);

Gets whether the preview widget set by gtk_file_chooser_set_preview_widget() should be shown for the current filename. See gtk_file_chooser_set_preview_widget_active().

chooser : | a GtkFileChooser
Returns : | TRUE if the preview widget is active for the current filename.

Since 2.4

gtk_file_chooser_set_use_preview_label ()

void                gtk_file_chooser_set_use_preview_label
                                                        (GtkFileChooser *chooser,
                                                         gboolean use_label);

Sets whether the file chooser should display a stock label with the name of the file that is being previewed; the default is TRUE. Applications that want to draw the whole preview area themselves should set this to FALSE and display the name themselves in their preview widget.

See also: gtk_file_chooser_set_preview_widget()

chooser : | a GtkFileChooser
use_label : | whether to display a stock label with the name of the previewed file

Since 2.4

gtk_file_chooser_get_use_preview_label ()

gboolean            gtk_file_chooser_get_use_preview_label
                                                        (GtkFileChooser *chooser);

Gets whether a stock label should be drawn with the name of the previewed file. See gtk_file_chooser_set_use_preview_label().

chooser : | a GtkFileChooser
Returns : | TRUE if the file chooser is set to display a label with the name of the previewed file, FALSE otherwise.

gtk_file_chooser_get_preview_filename ()

char*               gtk_file_chooser_get_preview_filename
                                                        (GtkFileChooser *chooser);

Gets the filename that should be previewed in a custom preview widget. See gtk_file_chooser_set_preview_widget().

chooser : | a GtkFileChooser
Returns : | the filename to preview, or NULL if no file is selected, or if the selected file cannot be represented as a local filename. Free with g_free()

Since 2.4

gtk_file_chooser_get_preview_uri ()

char*               gtk_file_chooser_get_preview_uri    (GtkFileChooser *chooser);

Gets the URI that should be previewed in a custom preview widget. See gtk_file_chooser_set_preview_widget().

chooser : | a GtkFileChooser
Returns : | the URI for the file to preview, or NULL if no file is selected. Free with g_free().

Since 2.4

gtk_file_chooser_set_extra_widget ()

void                gtk_file_chooser_set_extra_widget   (GtkFileChooser *chooser,
                                                         GtkWidget *extra_widget);

Sets an application-supplied widget to provide extra options to the user.

chooser : | a GtkFileChooser
extra_widget : | widget for extra options

Since 2.4

gtk_file_chooser_get_extra_widget ()

GtkWidget*          gtk_file_chooser_get_extra_widget   (GtkFileChooser *chooser);

Gets the current preview widget; see gtk_file_chooser_set_extra_widget().

chooser : | a GtkFileChooser
Returns : | the current extra widget, or NULL

Since 2.4

gtk_file_chooser_add_filter ()

void                gtk_file_chooser_add_filter         (GtkFileChooser *chooser,
                                                         GtkFileFilter *filter);

Adds filter to the list of filters that the user can select between. When a filter is selected, only files that are passed by that filter are displayed.

Note that the chooser takes ownership of the filter, so you have to ref and sink it if you want to keep a reference.

chooser : | a GtkFileChooser
filter : | a GtkFileFilter

Since 2.4

gtk_file_chooser_remove_filter ()

void                gtk_file_chooser_remove_filter      (GtkFileChooser *chooser,
                                                         GtkFileFilter *filter);

Removes filter from the list of filters that the user can select between.

chooser : | a GtkFileChooser
filter : | a GtkFileFilter

Since 2.4

gtk_file_chooser_list_filters ()

GSList*             gtk_file_chooser_list_filters       (GtkFileChooser *chooser);

Lists the current set of user-selectable filters; see gtk_file_chooser_add_filter(), gtk_file_chooser_remove_filter().

chooser : | a GtkFileChooser
Returns : | a GSList containing the current set of user selectable filters. The contents of the list are owned by GTK+, but you must free the list itself with g_slist_free() when you are done with it.

Since 2.4

gtk_file_chooser_set_filter ()

void                gtk_file_chooser_set_filter         (GtkFileChooser *chooser,
                                                         GtkFileFilter *filter);

Sets the current filter; only the files that pass the filter will be displayed. If the user-selectable list of filters is non-empty, then the filter should be one of the filters in that list. Setting the current filter when the list of filters is empty is useful if you want to restrict the displayed set of files without letting the user change it.

chooser : | a GtkFileChooser
filter : | a GtkFileFilter

Since 2.4

gtk_file_chooser_get_filter ()

GtkFileFilter*      gtk_file_chooser_get_filter         (GtkFileChooser *chooser);

Gets the current filter; see gtk_file_chooser_set_filter().

chooser : | a GtkFileChooser
Returns : | the current filter, or NULL

Since 2.4

gtk_file_chooser_add_shortcut_folder ()

gboolean            gtk_file_chooser_add_shortcut_folder
                                                        (GtkFileChooser *chooser,
                                                         const char *folder,
                                                         GError **error);

Adds a folder to be displayed with the shortcut folders in a file chooser. Note that shortcut folders do not get saved, as they are provided by the application. For example, you can use this to add a "/usr/share/mydrawprogram/Clipart" folder to the volume list.

chooser : | a GtkFileChooser
folder : | filename of the folder to add
error : | location to store error, or NULL
Returns : | TRUE if the folder could be added successfully, FALSE otherwise. In the latter case, the error will be set as appropriate.

Since 2.4

gtk_file_chooser_remove_shortcut_folder ()

gboolean            gtk_file_chooser_remove_shortcut_folder
                                                        (GtkFileChooser *chooser,
                                                         const char *folder,
                                                         GError **error);

Removes a folder from a file chooser's list of shortcut folders.

chooser : | a GtkFileChooser
folder : | filename of the folder to remove
error : | location to store error, or NULL
Returns : | TRUE if the operation succeeds, FALSE otherwise. In the latter case, the error will be set as appropriate. See also: gtk_file_chooser_add_shortcut_folder()

Since 2.4

gtk_file_chooser_list_shortcut_folders ()

GSList*             gtk_file_chooser_list_shortcut_folders
                                                        (GtkFileChooser *chooser);

Queries the list of shortcut folders in the file chooser, as set by gtk_file_chooser_add_shortcut_folder().

chooser : | a GtkFileChooser
Returns : | A list of folder filenames, or NULL if there are no shortcut folders. Free the returned list with g_slist_free(), and the filenames with g_free().

Since 2.4

gtk_file_chooser_add_shortcut_folder_uri ()

gboolean            gtk_file_chooser_add_shortcut_folder_uri
                                                        (GtkFileChooser *chooser,
                                                         const char *uri,
                                                         GError **error);

Adds a folder URI to be displayed with the shortcut folders in a file chooser. Note that shortcut folders do not get saved, as they are provided by the application. For example, you can use this to add a "file:///usr/share/mydrawprogram/Clipart" folder to the volume list.

chooser : | a GtkFileChooser
uri : | URI of the folder to add
error : | location to store error, or NULL
Returns : | TRUE if the folder could be added successfully, FALSE otherwise. In the latter case, the error will be set as appropriate.

Since 2.4

gtk_file_chooser_remove_shortcut_folder_uri ()

gboolean            gtk_file_chooser_remove_shortcut_folder_uri
                                                        (GtkFileChooser *chooser,
                                                         const char *uri,
                                                         GError **error);

Removes a folder URI from a file chooser's list of shortcut folders.

chooser : | a GtkFileChooser
uri : | URI of the folder to remove
error : | location to store error, or NULL
Returns : | TRUE if the operation succeeds, FALSE otherwise. In the latter case, the error will be set as appropriate. See also: gtk_file_chooser_add_shortcut_folder_uri()

Since 2.4

gtk_file_chooser_list_shortcut_folder_uris ()

GSList*             gtk_file_chooser_list_shortcut_folder_uris
                                                        (GtkFileChooser *chooser);

Queries the list of shortcut folders in the file chooser, as set by gtk_file_chooser_add_shortcut_folder_uri().

chooser : | a GtkFileChooser
Returns : | A list of folder URIs, or NULL if there are no shortcut folders. Free the returned list with g_slist_free(), and the URIs with g_free().

Since 2.4

Signal Details

The "confirm-overwrite" signal

GtkFileChooserConfirmationuser_function                      (GtkFileChooser *filechooser,
                                                        gpointer        user_data)        : Run Last

This signal gets emitted whenever it is appropriate to present a confirmation dialog when the user has selected a file name that already exists. The signal only gets emitted when the file chooser is in GTK_FILE_CHOOSER_ACTION_SAVE mode.

Most applications just need to turn on the do-overwrite-confirmation property (or call the gtk_file_chooser_set_do_overwrite_confirmation() function), and they will automatically get a stock confirmation dialog. Applications which need to customize this behavior should do that, and also connect to the confirm-overwrite signal.

A signal handler for this signal must return a GtkFileChooserConfirmation value, which indicates the action to take. If the handler determines that the user wants to select a different filename, it should return GTK_FILE_CHOOSER_CONFIRMATION_SELECT_AGAIN. If it determines that the user is satisfied with his choice of file name, it should return GTK_FILE_CHOOSER_CONFIRMATION_ACCEPT_FILENAME. On the other hand, if it determines that the stock confirmation dialog should be used, it should return GTK_FILE_CHOOSER_CONFIRMATION_CONFIRM. The following example illustrates this.

Example 27. Custom confirmation

static GtkFileChooserConfirmation
confirm_overwrite_callback (GtkFileChooser *chooser, gpointer data)
{
  char *uri;

  uri = gtk_file_chooser_get_uri (chooser);

  if (is_uri_read_only (uri))
    {
      if (user_wants_to_replace_read_only_file (uri))
        return GTK_FILE_CHOOSER_CONFIRMATION_ACCEPT_FILENAME;
      else
        return GTK_FILE_CHOOSER_CONFIRMATION_SELECT_AGAIN;
    } else
      return GTK_FILE_CHOOSER_CONFIRMATION_CONFIRM; /* fall back to the default dialog */
}

...

chooser = gtk_file_chooser_dialog_new (...);

gtk_file_chooser_set_do_overwrite_confirmation (GTK_FILE_CHOOSER (dialog), TRUE);
g_signal_connect (chooser, "confirm-overwrite",
                  G_CALLBACK (confirm_overwrite_callback), NULL);

if (gtk_dialog_run (chooser) == GTK_RESPONSE_ACCEPT)
        save_to_file (gtk_file_chooser_get_filename (GTK_FILE_CHOOSER (chooser));

gtk_widget_destroy (chooser);

filechooser : | the object which received the signal.
user_data : | user data set when the signal handler was connected.
Returns : | GtkFileChooserConfirmation value that indicates which action to take after emitting the signal. Since 2.8

The "current-folder-changed" signal

void                user_function                      (GtkFileChooser *chooser,
                                                        gpointer        user_data)      : Run Last

This signal is emitted when the current folder in a GtkFileChooser changes. This can happen due to the user performing some action that changes folders, such as selecting a bookmark or visiting a folder on the file list. It can also happen as a result of calling a function to explicitly change the current folder in a file chooser.

Normally you do not need to connect to this signal, unless you need to keep track of which folder a file chooser is showing.

See also:  gtk_file_chooser_set_current_folder(),
gtk_file_chooser_get_current_folder(),
gtk_file_chooser_set_current_folder_uri(),
gtk_file_chooser_get_current_folder_uri().

chooser : | the object which received the signal.
user_data : | user data set when the signal handler was connected.

The "file-activated" signal

void                user_function                      (GtkFileChooser *chooser,
                                                        gpointer        user_data)      : Run Last

This signal is emitted when the user "activates" a file in the file chooser. This can happen by double-clicking on a file in the file list, or by pressing Enter.

Normally you do not need to connect to this signal. It is used internally by GtkFileChooserDialog to know when to activate the default button in the dialog.

See also: gtk_file_chooser_get_filename(),
gtk_file_chooser_get_filenames(), gtk_file_chooser_get_uri(),
gtk_file_chooser_get_uris().

chooser : | the object which received the signal.
user_data : | user data set when the signal handler was connected.

The "selection-changed" signal

void                user_function                      (GtkFileChooser *chooser,
                                                        gpointer        user_data)      : Run Last

This signal is emitted when there is a change in the set of selected files in a GtkFileChooser. This can happen when the user modifies the selection with the mouse or the keyboard, or when explicitly calling functions to change the selection.

Normally you do not need to connect to this signal, as it is easier to wait for the file chooser to finish running, and then to get the list of selected files using the functions mentioned below.

See also: gtk_file_chooser_select_filename(),
gtk_file_chooser_unselect_filename(), gtk_file_chooser_get_filename(),
gtk_file_chooser_get_filenames(), gtk_file_chooser_select_uri(),
gtk_file_chooser_unselect_uri(), gtk_file_chooser_get_uri(),
gtk_file_chooser_get_uris().

chooser : | the object which received the signal.
user_data : | user data set when the signal handler was connected.

The "update-preview" signal

void                user_function                      (GtkFileChooser *chooser,
                                                        gpointer        user_data)      : Run Last

This signal is emitted when the preview in a file chooser should be regenerated. For example, this can happen when the currently selected file changes. You should use this signal if you want your file chooser to have a preview widget.

Once you have installed a preview widget with gtk_file_chooser_set_preview_widget(), you should update it when this signal is emitted. You can use the functions gtk_file_chooser_get_preview_filename() or gtk_file_chooser_get_preview_uri() to get the name of the file to preview. Your widget may not be able to preview all kinds of files; your callback must call gtk_file_chooser_set_preview_wiget_active() to inform the file chooser about whether the preview was generated successfully or not.

Please see the example code in the section called “Adding a Preview Widget”.

See also: gtk_file_chooser_set_preview_widget(),
gtk_file_chooser_set_preview_widget_active(),
gtk_file_chooser_set_use_preview_label(),
gtk_file_chooser_get_preview_filename(),
gtk_file_chooser_get_preview_uri().

chooser : | the object which received the signal.
user_data : | user data set when the signal handler was connected.

See Also

GtkFileChooserDialog, GtkFileChooserWidget, GtkFileChooserButton


Installing Extra Widgets

Some applications need to install extra widgets in a file chooser. For example, an application may want to provide a toggle button to give the user the option of opening a file read-only.

Please see the section on creating extra widgets for more information.


Installing a Preview widget

Many applications need to have a preview facility within their file chooser dialogs. Previous to GTK+ 2.4, one needed to access the GtkFileSelection widget hierarchy directly to hook in a preview widget. With GtkFileChooser, there is a dedicated API to do this.

Please see the section on creating preview widgets for more information.


New features

New features in GtkFileChooser include the following:

  • Ability to select URIs rather than just local files. You must use a GtkFileSystem implementation that supports this, for example the gnome-vfs backend.

  • Present a list of application-specific shortcut folders. For example, a paint program may want to add a shortcut for its /usr/share/paint_program/Clipart folder.

  • Define custom filters so that not all the files in a folder are listed. For example, you could filter out backup files, or show only image files.

To see how to use these features, please consult the GtkFileChooser reference documentation.


Selection Modes

GtkFileChooser can be used in two modes, to select a single file at a time or to select a set of more than one file. To set this, use gtk_file_chooser_set_select_multiple(). In single-selection mode, you can use gtk_file_chooser_get_filename() to get a file name from the local file system or gtk_file_chooser_get_uri() to get a full-formed URI. In multiple-selection mode, you can use gtk_file_chooser_get_filenames() to get a GSList of filename strings, or gtk_file_chooser_get_uris() to get a list of URI strings.

Also, you can configure GtkFileChooser to select files or folders. Consider a backup program that needs to let the user select a folder that will be backed up along with its subfolders. To configure whether GtkFileChooser is used to select files or folders, use gtk_file_chooser_set_action(). In addition, this lets you configure whether the file chooser will be used to select existing files or folders (e.g. for "File/Open"), or to type in new filenames (for "File/Save As...").


GtkFileChooserButton

GtkFileChooserButton — A button to launch a file selection dialog

Synopsis

#include <gtk/gtk.h>

                    GtkFileChooserButton;
GtkWidget*          gtk_file_chooser_button_new         (const gchar *title,
                                                         GtkFileChooserAction action);
GtkWidget*          gtk_file_chooser_button_new_with_backend
                                                        (const gchar *title,
                                                         GtkFileChooserAction action,
                                                         const gchar *backend);
GtkWidget*          gtk_file_chooser_button_new_with_dialog
                                                        (GtkWidget *dialog);
const gchar*        gtk_file_chooser_button_get_title   (GtkFileChooserButton *button);
void                gtk_file_chooser_button_set_title   (GtkFileChooserButton *button,
                                                         const gchar *title);
gint                gtk_file_chooser_button_get_width_chars
                                                        (GtkFileChooserButton *button);
void                gtk_file_chooser_button_set_width_chars
                                                        (GtkFileChooserButton *button,
                                                         gint n_chars);
gboolean            gtk_file_chooser_button_get_focus_on_click
                                                        (GtkFileChooserButton *button);
void                gtk_file_chooser_button_set_focus_on_click
                                                        (GtkFileChooserButton *button,
                                                         gboolean focus_on_click);

Object Hierarchy

  GObject
   +----GInitiallyUnowned
         +----GtkObject
               +----GtkWidget
                     +----GtkContainer
                           +----GtkBox
                                 +----GtkHBox
                                       +----GtkFileChooserButton

Implemented Interfaces

GtkFileChooserButton implements GtkFileChooser and AtkImplementorIface.

Properties

  "dialog"                   GtkFileChooser        : Write / Construct Only
  "focus-on-click"           gboolean              : Read / Write
  "title"                    gchararray            : Read / Write
  "width-chars"              gint                  : Read / Write

Description

The GtkFileChooserButton is a widget that lets the user select a file. It implements the GtkFileChooser interface. Visually, it is a file name with a button to bring up a GtkFileChooserDialog. The user can then use that dialog to change the file associated with that button. This widget does not support setting the "select-multiple" property to TRUE.

Example 28. Create a button to let the user select a file in /etc

{
  GtkWidget *button;

  button = gtk_file_chooser_button_new (_("Select a file"),
                                        GTK_FILE_CHOOSER_ACTION_OPEN);
  gtk_file_chooser_set_current_folder (GTK_FILE_CHOOSER (button),
                                       "/etc");
}

The GtkFileChooserButton supports the GtkFileChooserActions GTK_FILE_CHOOSER_ACTION_OPEN and GTK_FILE_CHOOSER_ACTION_SELECT_FOLDER.

Important

The GtkFileChooserButton will ellipsize the label, and thus will thus request little horizontal space. To give the button more space, you should call gtk_widget_size_request(), gtk_file_chooser_button_set_width_chars(), or pack the button in such a way that other interface elements give space to the widget.

Details

GtkFileChooserButton

typedef struct _GtkFileChooserButton GtkFileChooserButton;

This should not be accessed directly. Use the accessor functions below.

gtk_file_chooser_button_new ()

GtkWidget*          gtk_file_chooser_button_new         (const gchar *title,
                                                         GtkFileChooserAction action);

Creates a new file-selecting button widget.

title : | the title of the browse dialog.
action : | the open mode for the widget.
Returns : | a new button widget.

Since 2.6

gtk_file_chooser_button_new_with_backend ()

GtkWidget*          gtk_file_chooser_button_new_with_backend
                                                        (const gchar *title,
                                                         GtkFileChooserAction action,
                                                         const gchar *backend);

Creates a new file-selecting button widget using backend.

title : | the title of the browse dialog.
action : | the open mode for the widget.
backend : | the name of the GtkFileSystem backend to use.
Returns : | a new button widget.

Since 2.6

gtk_file_chooser_button_new_with_dialog ()

GtkWidget*          gtk_file_chooser_button_new_with_dialog
                                                        (GtkWidget *dialog);

Creates a GtkFileChooserButton widget which uses dialog as it's file-picking window. Note that dialog must be a GtkDialog (or subclass) which implements the GtkFileChooser interface and must not have GTK_DIALOG_DESTROY_WITH_PARENT set.

dialog : | the widget to use as dialog
Returns : | a new button widget.

Since 2.6

gtk_file_chooser_button_get_title ()

const gchar*        gtk_file_chooser_button_get_title   (GtkFileChooserButton *button);

Retrieves the title of the browse dialog used by button. The returned value should not be modified or freed.

button : | the button widget to examine.
Returns : | a pointer to the browse dialog's title.

Since 2.6

gtk_file_chooser_button_set_title ()

void                gtk_file_chooser_button_set_title   (GtkFileChooserButton *button,
                                                         const gchar *title);

Modifies the title of the browse dialog used by button.

button : | the button widget to modify.
title : | the new browse dialog title.

Since 2.6

gtk_file_chooser_button_get_width_chars ()

gint                gtk_file_chooser_button_get_width_chars
                                                        (GtkFileChooserButton *button);

Retrieves the width in characters of the button widget's entry and/or label.

button : | the button widget to examine.
Returns : | an integer width (in characters) that the button will use to size itself.

Since 2.6

gtk_file_chooser_button_set_width_chars ()

void                gtk_file_chooser_button_set_width_chars
                                                        (GtkFileChooserButton *button,
                                                         gint n_chars);

Sets the width (in characters) that button will use to n_chars.

button : | the button widget to examine.
n_chars : | the new width, in characters.

Since 2.6

gtk_file_chooser_button_get_focus_on_click ()

gboolean            gtk_file_chooser_button_get_focus_on_click
                                                        (GtkFileChooserButton *button);

Returns whether the button grabs focus when it is clicked with the mouse. See gtk_file_chooser_button_set_focus_on_click().

button : | a GtkFileChooserButton
Returns : | TRUE if the button grabs focus when it is clicked with the mouse.

Since 2.10

gtk_file_chooser_button_set_focus_on_click ()

void                gtk_file_chooser_button_set_focus_on_click
                                                        (GtkFileChooserButton *button,
                                                         gboolean focus_on_click);

Sets whether the button will grab focus when it is clicked with the mouse. Making mouse clicks not grab focus is useful in places like toolbars where you don't want the keyboard focus removed from the main area of the application.

button : | a GtkFileChooserButton
focus_on_click : | whether the button grabs focus when clicked with the mouse

Since 2.10

Property Details

The "dialog" property

  "dialog"                   GtkFileChooser        : Write / Construct Only

Instance of the GtkFileChooserDialog associated with the button.

Since 2.6

The "focus-on-click" property

  "focus-on-click"           gboolean              : Read / Write

Whether the GtkFileChooserButton button grabs focus when it is clicked with the mouse.

Default value: TRUE

Since 2.10

The "title" property

  "title"                    gchararray            : Read / Write

Title to put on the GtkFileChooserDialog associated with the button.

Default value: "Select A File"

Since 2.6

The "width-chars" property

  "width-chars"              gint                  : Read / Write

The width of the entry and label inside the button, in characters.

Allowed values: >= -1

Default value: -1

Since 2.6

See Also

GtkFileChooserDialog


GtkFileChooserDialog

GtkFileChooserDialog — A file chooser dialog, suitable for "File/Open" or "File/Save" commands

Synopsis

#include <gtk/gtk.h>

                    GtkFileChooserDialog;
GtkWidget*          gtk_file_chooser_dialog_new         (const gchar *title,
                                                         GtkWindow *parent,
                                                         GtkFileChooserAction action,
                                                         const gchar *first_button_text,
                                                         ...);
GtkWidget*          gtk_file_chooser_dialog_new_with_backend
                                                        (const gchar *title,
                                                         GtkWindow *parent,
                                                         GtkFileChooserAction action,
                                                         const gchar *backend,
                                                         const gchar *first_button_text,
                                                         ...);

Object Hierarchy

  GObject
   +----GInitiallyUnowned
         +----GtkObject
               +----GtkWidget
                     +----GtkContainer
                           +----GtkBin
                                 +----GtkWindow
                                       +----GtkDialog
                                             +----GtkFileChooserDialog

Implemented Interfaces

GtkFileChooserDialog implements GtkFileChooser and AtkImplementorIface.

Description

GtkFileChooserDialog is a dialog box suitable for use with "File/Open" or "File/Save as" commands. This widget works by putting a GtkFileChooserWidget inside a GtkDialog. It exposes the GtkFileChooserIface interface, so you can use all of the GtkFileChooser functions on the file chooser dialog as well as those for GtkDialog.

Note that GtkFileChooserDialog does not have any methods of its own. Instead, you should use the functions that work on a GtkFileChooser.

Example 29. Typical usage

In the simplest of cases, you can the following code to use GtkFileChooserDialog to select a file for opening:

GtkWidget *dialog;

dialog = gtk_file_chooser_dialog_new ("Open File",
                      parent_window,
                      GTK_FILE_CHOOSER_ACTION_OPEN,
                      GTK_STOCK_CANCEL, GTK_RESPONSE_CANCEL,
                      GTK_STOCK_OPEN, GTK_RESPONSE_ACCEPT,
                      NULL);

if (gtk_dialog_run (GTK_DIALOG (dialog)) == GTK_RESPONSE_ACCEPT)
  {
    char *filename;

    filename = gtk_file_chooser_get_filename (GTK_FILE_CHOOSER (dialog));
    open_file (filename);
    g_free (filename);
  }

gtk_widget_destroy (dialog);

To use a dialog for saving, you can use this:

GtkWidget *dialog;

dialog = gtk_file_chooser_dialog_new ("Save File",
                      parent_window,
                      GTK_FILE_CHOOSER_ACTION_SAVE,
                      GTK_STOCK_CANCEL, GTK_RESPONSE_CANCEL,
                      GTK_STOCK_SAVE, GTK_RESPONSE_ACCEPT,
                      NULL);
gtk_file_chooser_set_do_overwrite_confirmation (GTK_FILE_CHOOSER (dialog), TRUE);

if (user_edited_a_new_document)
  {
    gtk_file_chooser_set_current_folder (GTK_FILE_CHOOSER (dialog), default_folder_for_saving);
    gtk_file_chooser_set_current_name (GTK_FILE_CHOOSER (dialog), "Untitled document");
  }
else
  gtk_file_chooser_set_filename (GTK_FILE_CHOOSER (dialog), filename_for_existing_document);

if (gtk_dialog_run (GTK_DIALOG (dialog)) == GTK_RESPONSE_ACCEPT)
  {
    char *filename;

    filename = gtk_file_chooser_get_filename (GTK_FILE_CHOOSER (dialog));
    save_to_file (filename);
    g_free (filename);
  }

gtk_widget_destroy (dialog);

Response Codes

GtkFileChooserDialog inherits from GtkDialog, so buttons that go in its action area have response codes such as GTK_RESPONSE_ACCEPT and GTK_RESPONSE_CANCEL. For example, you could call gtk_file_chooser_dialog_new() as follows:

GtkWidget *dialog;

dialog = gtk_file_chooser_dialog_new ("Open File",
                      parent_window,
                      GTK_FILE_CHOOSER_ACTION_OPEN,
                      GTK_STOCK_CANCEL, GTK_RESPONSE_CANCEL,
                      GTK_STOCK_OPEN, GTK_RESPONSE_ACCEPT,
                      NULL);

This will create buttons for "Cancel" and "Open" that use stock response identifiers from GtkResponseType. For most dialog boxes you can use your own custom response codes rather than the ones in GtkResponseType, but GtkFileChooserDialog assumes that its "accept"-type action, e.g. an "Open" or "Save" button, will have one of the following response codes:

GTK_RESPONSE_ACCEPT
GTK_RESPONSE_OK
GTK_RESPONSE_YES
GTK_RESPONSE_APPLY

This is because GtkFileChooserDialog must intercept responses and switch to folders if appropriate, rather than letting the dialog terminate — the implementation uses these known response codes to know which responses can be blocked if appropriate.

Note

To summarize, make sure you use a stock response code when you use GtkFileChooserDialog to ensure proper operation.

Details

GtkFileChooserDialog

typedef struct _GtkFileChooserDialog GtkFileChooserDialog;

gtk_file_chooser_dialog_new ()

GtkWidget*          gtk_file_chooser_dialog_new         (const gchar *title,
                                                         GtkWindow *parent,
                                                         GtkFileChooserAction action,
                                                         const gchar *first_button_text,
                                                         ...);

Creates a new GtkFileChooserDialog. This function is analogous to gtk_dialog_new_with_buttons().

title : | Title of the dialog, or NULL
parent : | Transient parent of the dialog, or NULL
action : | Open or save mode for the dialog
first_button_text : | stock ID or text to go in the first button, or NULL
... : | response ID for the first button, then additional (button, id) pairs, ending with NULL
Returns : | a new GtkFileChooserDialog

Since 2.4

gtk_file_chooser_dialog_new_with_backend ()

GtkWidget*          gtk_file_chooser_dialog_new_with_backend
                                                        (const gchar *title,
                                                         GtkWindow *parent,
                                                         GtkFileChooserAction action,
                                                         const gchar *backend,
                                                         const gchar *first_button_text,
                                                         ...);

Creates a new GtkFileChooserDialog with a specified backend. This is especially useful if you use gtk_file_chooser_set_local_only() to allow non-local files and you use a more expressive vfs, such as gnome-vfs, to load files.

title : | Title of the dialog, or NULL
parent : | Transient parent of the dialog, or NULL
action : | Open or save mode for the dialog
backend : | The name of the specific filesystem backend to use.
first_button_text : | stock ID or text to go in the first button, or NULL
... : | response ID for the first button, then additional (button, id) pairs, ending with NULL
Returns : | a new GtkFileChooserDialog

Since 2.4

See Also

GtkFileChooser, GtkDialog


GtkFileChooserWidget

GtkFileChooserWidget — File chooser widget that can be embedded in other widgets

Synopsis

#include <gtk/gtk.h>

                    GtkFileChooserWidget;
GtkWidget*          gtk_file_chooser_widget_new         (GtkFileChooserAction action);
GtkWidget*          gtk_file_chooser_widget_new_with_backend
                                                        (GtkFileChooserAction action,
                                                         const gchar *backend);

Object Hierarchy

  GObject
   +----GInitiallyUnowned
         +----GtkObject
               +----GtkWidget
                     +----GtkContainer
                           +----GtkBox
                                 +----GtkVBox
                                       +----GtkFileChooserWidget

Implemented Interfaces

GtkFileChooserWidget implements GtkFileChooser, AtkImplementorIface and GtkFileChooserEmbed.

Description

GtkFileChooserWidget is a widget suitable for selecting files. It is the main building block of a GtkFileChooserDialog. Most applications will only need to use the latter; you can use GtkFileChooserWidget as part of a larger window if you have special needs.

Note that GtkFileChooserWidget does not have any methods of its own. Instead, you should use the functions that work on a GtkFileChooser.

Details

GtkFileChooserWidget

typedef struct _GtkFileChooserWidget GtkFileChooserWidget;

gtk_file_chooser_widget_new ()

GtkWidget*          gtk_file_chooser_widget_new         (GtkFileChooserAction action);

Creates a new GtkFileChooserWidget. This is a file chooser widget that can be embedded in custom windows, and it is the same widget that is used by GtkFileChooserDialog.

action : | Open or save mode for the widget
Returns : | a new GtkFileChooserWidget

Since 2.4

gtk_file_chooser_widget_new_with_backend ()

GtkWidget*          gtk_file_chooser_widget_new_with_backend
                                                        (GtkFileChooserAction action,
                                                         const gchar *backend);

Creates a new GtkFileChooserWidget with a specified backend. This is especially useful if you use gtk_file_chooser_set_local_only() to allow non-local files. This is a file chooser widget that can be embedded in custom windows and it is the same widget that is used by GtkFileChooserDialog.

action : | Open or save mode for the widget
backend : | The name of the specific filesystem backend to use.
Returns : | a new GtkFileChooserWidget

Since 2.4

See Also

GtkFileChooser, GtkFileChooserDialog


GtkFileSelection

GtkFileSelection — Prompt the user for a file or directory name

Synopsis

#include <gtk/gtk.h>

                    GtkFileSelection;
GtkWidget*          gtk_file_selection_new              (const gchar *title);
void                gtk_file_selection_set_filename     (GtkFileSelection *filesel,
                                                         const gchar *filename);
const gchar*        gtk_file_selection_get_filename     (GtkFileSelection *filesel);
void                gtk_file_selection_complete         (GtkFileSelection *filesel,
                                                         const gchar *pattern);
void                gtk_file_selection_show_fileop_buttons
                                                        (GtkFileSelection *filesel);
void                gtk_file_selection_hide_fileop_buttons
                                                        (GtkFileSelection *filesel);
gchar**             gtk_file_selection_get_selections   (GtkFileSelection *filesel);
void                gtk_file_selection_set_select_multiple
                                                        (GtkFileSelection *filesel,
                                                         gboolean select_multiple);
gboolean            gtk_file_selection_get_select_multiple
                                                        (GtkFileSelection *filesel);

Object Hierarchy

  GObject
   +----GInitiallyUnowned
         +----GtkObject
               +----GtkWidget
                     +----GtkContainer
                           +----GtkBin
                                 +----GtkWindow
                                       +----GtkDialog
                                             +----GtkFileSelection

Implemented Interfaces

GtkFileSelection implements AtkImplementorIface.

Properties

  "filename"                 gchararray            : Read / Write
  "select-multiple"          gboolean              : Read / Write
  "show-fileops"             gboolean              : Read / Write

Description

GtkFileSelection should be used to retrieve file or directory names from the user. It will create a new dialog window containing a directory list, and a file list corresponding to the current working directory. The filesystem can be navigated using the directory list or the drop-down history menu. Alternatively, the TAB key can be used to navigate using filename completion - common in text based editors such as emacs and jed.

File selection dialogs are created with a call to gtk_file_selection_new().

The default filename can be set using gtk_file_selection_set_filename() and the selected filename retrieved using gtk_file_selection_get_filename().

Use gtk_file_selection_complete() to display files and directories that match a given pattern. This can be used for example, to show only *.txt files, or only files beginning with gtk*.

Simple file operations; create directory, delete file, and rename file, are available from buttons at the top of the dialog. These can be hidden using gtk_file_selection_hide_fileop_buttons() and shown again using gtk_file_selection_show_fileop_buttons().

Example 23. Getting a filename from the user.

/* The file selection widget and the string to store the chosen filename */

void store_filename (GtkWidget *widget, gpointer user_data) {
   GtkWidget *file_selector = GTK_WIDGET (user_data);
   const gchar *selected_filename;

   selected_filename = gtk_file_selection_get_filename (GTK_FILE_SELECTION (file_selector));
   g_print ("Selected filename: %s\n", selected_filename);
}

void create_file_selection (void) {

   GtkWidget *file_selector;

   /* Create the selector */

   file_selector = gtk_file_selection_new ("Please select a file for editing.");

   g_signal_connect (GTK_FILE_SELECTION (file_selector)->ok_button,
                     "clicked",
                     G_CALLBACK (store_filename),
                     file_selector);

   /* Ensure that the dialog box is destroyed when the user clicks a button. */

   g_signal_connect_swapped (GTK_FILE_SELECTION (file_selector)->ok_button,
                             "clicked",
                             G_CALLBACK (gtk_widget_destroy),
                             file_selector);

   g_signal_connect_swapped (GTK_FILE_SELECTION (file_selector)->cancel_button,
                             "clicked",
                             G_CALLBACK (gtk_widget_destroy),
                             file_selector);

   /* Display that dialog */

   gtk_widget_show (file_selector);
}

Details

GtkFileSelection

typedef struct {
  GtkWidget *dir_list;
  GtkWidget *file_list;
  GtkWidget *selection_entry;
  GtkWidget *selection_text;
  GtkWidget *main_vbox;
  GtkWidget *ok_button;
  GtkWidget *cancel_button;
  GtkWidget *help_button;
  GtkWidget *history_pulldown;
  GtkWidget *history_menu;
  GList     *history_list;
  GtkWidget *fileop_dialog;
  GtkWidget *fileop_entry;
  gchar     *fileop_file;
  gpointer   cmpl_state;

  GtkWidget *fileop_c_dir;
  GtkWidget *fileop_del_file;
  GtkWidget *fileop_ren_file;

  GtkWidget *button_area;
  GtkWidget *action_area;
} GtkFileSelection;

The GtkFileSelection struct contains the following GtkWidget fields:

*fileop_dialog; | the dialog box used to display the GtkFileSelection. It can be customized by adding/removing widgets from it using the standard GtkDialog functions.
*ok_button, *cancel_button; | the two main buttons that signals should be connected to in order to perform an action when the user hits either OK or Cancel.
*history_pulldown; | the GtkOptionMenu used to create the drop-down directory history.
*fileop_c_dir, *fileop_del_file, *fileop_ren_file; | the buttons that appear at the top of the file selection dialog. These "operation buttons" can be hidden and redisplayed with gtk_file_selection_hide_fileop_buttons() and gtk_file_selection_show_fileop_buttons() respectively.

gtk_file_selection_new ()

GtkWidget*          gtk_file_selection_new              (const gchar *title);

Creates a new file selection dialog box. By default it will contain a GtkTreeView of the application's current working directory, and a file listing. Operation buttons that allow the user to create a directory, delete files and rename files, are also present.

title : | a message that will be placed in the file requestor's titlebar.
Returns : | the new file selection.

gtk_file_selection_set_filename ()

void                gtk_file_selection_set_filename     (GtkFileSelection *filesel,
                                                         const gchar *filename);

Sets a default path for the file requestor. If filename includes a directory path, then the requestor will open with that path as its current working directory.

This has the consequence that in order to open the requestor with a working directory and an empty filename, filename must have a trailing directory separator.

The encoding of filename is preferred GLib file name encoding, which may not be UTF-8. See g_filename_from_utf8().

filesel : | a GtkFileSelection.
filename : | a string to set as the default file name.

gtk_file_selection_get_filename ()

const gchar*        gtk_file_selection_get_filename     (GtkFileSelection *filesel);

This function returns the selected filename in the GLib file name encoding. To convert to UTF-8, call g_filename_to_utf8(). The returned string points to a statically allocated buffer and should be copied if you plan to keep it around.

If no file is selected then the selected directory path is returned.

filesel : | a GtkFileSelection
Returns : | currently-selected filename in the on-disk encoding.

gtk_file_selection_complete ()

void                gtk_file_selection_complete         (GtkFileSelection *filesel,
                                                         const gchar *pattern);

Will attempt to match pattern to a valid filenames or subdirectories in the current directory. If a match can be made, the matched filename will appear in the text entry field of the file selection dialog. If a partial match can be made, the "Files" list will contain those file names which have been partially matched, and the "Folders" list those directories which have been partially matched.

filesel : | a GtkFileSelection.
pattern : | a string of characters which may or may not match any filenames in the current directory.

gtk_file_selection_show_fileop_buttons ()

void                gtk_file_selection_show_fileop_buttons
                                                        (GtkFileSelection *filesel);

Shows the file operation buttons, if they have previously been hidden. The rest of the widgets in the dialog will be resized accordingly.

filesel : a GtkFileSelection.

gtk_file_selection_hide_fileop_buttons ()

void                gtk_file_selection_hide_fileop_buttons
                                                        (GtkFileSelection *filesel);

Hides the file operation buttons that normally appear at the top of the dialog. Useful if you wish to create a custom file selector, based on GtkFileSelection.

filesel : a GtkFileSelection.

gtk_file_selection_get_selections ()

gchar**             gtk_file_selection_get_selections   (GtkFileSelection *filesel);

Retrieves the list of file selections the user has made in the dialog box. This function is intended for use when the user can select multiple files in the file list.

The filenames are in the GLib file name encoding. To convert to UTF-8, call g_filename_to_utf8() on each string.

filesel : | a GtkFileSelection
Returns : | a newly-allocated NULL-terminated array of strings. Use g_strfreev() to free it.

gtk_file_selection_set_select_multiple ()

void                gtk_file_selection_set_select_multiple
                                                        (GtkFileSelection *filesel,
                                                         gboolean select_multiple);

Sets whether the user is allowed to select multiple files in the file list. Use gtk_file_selection_get_selections() to get the list of selected files.

filesel : | a GtkFileSelection
select_multiple : | whether or not the user is allowed to select multiple files in the file list.

gtk_file_selection_get_select_multiple ()

gboolean            gtk_file_selection_get_select_multiple
                                                        (GtkFileSelection *filesel);

Determines whether or not the user is allowed to select multiple files in the file list. See gtk_file_selection_set_select_multiple().

filesel : | a GtkFileSelection
Returns : | TRUE if the user is allowed to select multiple files in the file list

Property Details

The "filename" property

  "filename"                 gchararray            : Read / Write

The currently selected filename.

Default value: NULL

The "select-multiple" property

  "select-multiple"          gboolean              : Read / Write

Whether to allow multiple files to be selected.

Default value: FALSE

The "show-fileops" property

  "show-fileops"             gboolean              : Read / Write

Whether buttons for creating/manipulating files should be displayed.

Default value: FALSE

See Also

GtkDialog

Add your own widgets into the GtkFileSelection.


GtkFixed

GtkFixed — A container which allows you to position widgets at fixed coordinates

Synopsis

#include <gtk/gtk.h>

                    GtkFixed;
                    GtkFixedChild;
GtkWidget*          gtk_fixed_new                       (void);
void                gtk_fixed_put                       (GtkFixed *fixed,
                                                         GtkWidget *widget,
                                                         gint x,
                                                         gint y);
void                gtk_fixed_move                      (GtkFixed *fixed,
                                                         GtkWidget *widget,
                                                         gint x,
                                                         gint y);
gboolean            gtk_fixed_get_has_window            (GtkFixed *fixed);
void                gtk_fixed_set_has_window            (GtkFixed *fixed,
                                                         gboolean has_window);

Object Hierarchy

  GObject
   +----GInitiallyUnowned
         +----GtkObject
               +----GtkWidget
                     +----GtkContainer
                           +----GtkFixed

Implemented Interfaces

GtkFixed implements AtkImplementorIface.

Child Properties

  "x"                        gint                  : Read / Write
  "y"                        gint                  : Read / Write

Description

The GtkFixed widget is a container which can place child widgets at fixed positions and with fixed sizes, given in pixels. GtkFixed performs no automatic layout management.

For most applications, you should not use this container! It keeps you from having to learn about the other GTK+ containers, but it results in broken applications. With GtkFixed, the following things will result in truncated text, overlapping widgets, and other display bugs:

  • Themes, which may change widget sizes.

  • Fonts other than the one you used to write the app will of course change the size of widgets containing text; keep in mind that users may use a larger font because of difficulty reading the default, or they may be using Windows or the framebuffer port of GTK+, where different fonts are available.

  • Translation of text into other languages changes its size. Also, display of non-English text will use a different font in many cases.

In addition, the fixed widget can't properly be mirrored in right-to-left languages such as Hebrew and Arabic. i.e. normally GTK+ will flip the interface to put labels to the right of the thing they label, but it can't do that with GtkFixed. So your application will not be usable in right-to-left languages.

Finally, fixed positioning makes it kind of annoying to add/remove GUI elements, since you have to reposition all the other elements. This is a long-term maintenance problem for your application.

If you know none of these things are an issue for your application, and prefer the simplicity of GtkFixed, by all means use the widget. But you should be aware of the tradeoffs.

Details

GtkFixed

typedef struct _GtkFixed GtkFixed;

The GtkFixed struct contains the following fields. (These fields should be considered read-only. They should never be set by an application.)

GList *children; a list of GtkFixedChild elements, containing the child widgets and their positions.

GtkFixedChild

typedef struct {
  GtkWidget *widget;
  gint x;
  gint y;
} GtkFixedChild;

The GtkFixedChild struct contains the following fields. (These fields should be considered read-only. They should never be set by an application.)

GtkWidget *widget; | the child GtkWidget.
gint x; | the horizontal position of the widget within the GtkFixed container.
gint y; | the vertical position of the widget within the GtkFixed container.

gtk_fixed_new ()

GtkWidget*          gtk_fixed_new                       (void);

Creates a new GtkFixed.

Returns : a new GtkFixed.

gtk_fixed_put ()

void                gtk_fixed_put                       (GtkFixed *fixed,
                                                         GtkWidget *widget,
                                                         gint x,
                                                         gint y);

Adds a widget to a GtkFixed container at the given position.

fixed : | a GtkFixed.
widget : | the widget to add.
x : | the horizontal position to place the widget at.
y : | the vertical position to place the widget at.

gtk_fixed_move ()

void                gtk_fixed_move                      (GtkFixed *fixed,
                                                         GtkWidget *widget,
                                                         gint x,
                                                         gint y);

Moves a child of a GtkFixed container to the given position.

fixed : | a GtkFixed.
widget : | the child widget.
x : | the horizontal position to move the widget to.
y : | the vertical position to move the widget to.

gtk_fixed_get_has_window ()

gboolean            gtk_fixed_get_has_window            (GtkFixed *fixed);

Gets whether the GtkFixed has its own GdkWindow. See gdk_fixed_set_has_window().

fixed : | a GtkWidget
Returns : | TRUE if fixed has its own window.

gtk_fixed_set_has_window ()

void                gtk_fixed_set_has_window            (GtkFixed *fixed,
                                                         gboolean has_window);

Sets whether a GtkFixed widget is created with a separate GdkWindow for widget->window or not. (By default, it will be created with no separate GdkWindow). This function must be called while the GtkFixed is not realized, for instance, immediately after the window is created.

This function was added to provide an easy migration path for older applications which may expect GtkFixed to have a separate window.

fixed : | a GtkFixed
has_window : | TRUE if a separate window should be created

Child Property Details

The "x" child property

  "x"                        gint                  : Read / Write

X position of child widget.

Default value: 0

The "y" child property

  "y"                        gint                  : Read / Write

Y position of child widget.

Default value: 0


GtkFontButton

GtkFontButton — A button to launch a font selection dialog

Synopsis

#include <gtk/gtk.h>

                    GtkFontButton;
GtkWidget*          gtk_font_button_new                 (void);
GtkWidget*          gtk_font_button_new_with_font       (const gchar *fontname);
gboolean            gtk_font_button_set_font_name       (GtkFontButton *font_button,
                                                         const gchar *fontname);
const gchar*        gtk_font_button_get_font_name       (GtkFontButton *font_button);
void                gtk_font_button_set_show_style      (GtkFontButton *font_button,
                                                         gboolean show_style);
gboolean            gtk_font_button_get_show_style      (GtkFontButton *font_button);
void                gtk_font_button_set_show_size       (GtkFontButton *font_button,
                                                         gboolean show_size);
gboolean            gtk_font_button_get_show_size       (GtkFontButton *font_button);
void                gtk_font_button_set_use_font        (GtkFontButton *font_button,
                                                         gboolean use_font);
gboolean            gtk_font_button_get_use_font        (GtkFontButton *font_button);
void                gtk_font_button_set_use_size        (GtkFontButton *font_button,
                                                         gboolean use_size);
gboolean            gtk_font_button_get_use_size        (GtkFontButton *font_button);
void                gtk_font_button_set_title           (GtkFontButton *font_button,
                                                         const gchar *title);
const gchar*        gtk_font_button_get_title           (GtkFontButton *font_button);

Object Hierarchy

  GObject
   +----GInitiallyUnowned
         +----GtkObject
               +----GtkWidget
                     +----GtkContainer
                           +----GtkBin
                                 +----GtkButton
                                       +----GtkFontButton

Implemented Interfaces

GtkFontButton implements AtkImplementorIface.

Properties

  "font-name"                gchararray            : Read / Write
  "show-size"                gboolean              : Read / Write
  "show-style"               gboolean              : Read / Write
  "title"                    gchararray            : Read / Write
  "use-font"                 gboolean              : Read / Write
  "use-size"                 gboolean              : Read / Write

Signals

  "font-set"                                       : Run First

Description

The GtkFontButton is a button which displays the currently selected font an allows to open a font selection dialog to change the font. It is suitable widget for selecting a font in a preference dialog.

Details

GtkFontButton

typedef struct _GtkFontButton GtkFontButton;

The GtkFontButton struct has only private members and should not be used directly.

gtk_font_button_new ()

GtkWidget*          gtk_font_button_new                 (void);

Creates a new font picker widget.

Returns : a new font picker widget.

Since 2.4

gtk_font_button_new_with_font ()

GtkWidget*          gtk_font_button_new_with_font       (const gchar *fontname);

Creates a new font picker widget.

fontname : | Name of font to display in font selection dialog
Returns : | a new font picker widget.

Since 2.4

gtk_font_button_set_font_name ()

gboolean            gtk_font_button_set_font_name       (GtkFontButton *font_button,
                                                         const gchar *fontname);

Sets or updates the currently-displayed font in font picker dialog.

font_button : | a GtkFontButton
fontname : | Name of font to display in font selection dialog
Returns : | Return value of gtk_font_selection_dialog_set_font_name() if the font selection dialog exists, otherwise FALSE.

Since 2.4

gtk_font_button_get_font_name ()

const gchar*        gtk_font_button_get_font_name       (GtkFontButton *font_button);

Retrieves the name of the currently selected font.

font_button : | a GtkFontButton
Returns : | an internal copy of the font name which must not be freed.

Since 2.4

gtk_font_button_set_show_style ()

void                gtk_font_button_set_show_style      (GtkFontButton *font_button,
                                                         gboolean show_style);

If show_style is TRUE, the font style will be displayed along with name of the selected font.

font_button : | a GtkFontButton
show_style : | TRUE if font style should be displayed in label.

Since 2.4

gtk_font_button_get_show_style ()

gboolean            gtk_font_button_get_show_style      (GtkFontButton *font_button);

Returns whether the name of the font style will be shown in the label.

font_button : | a GtkFontButton
Returns : | whether the font style will be shown in the label.

Since 2.4

gtk_font_button_set_show_size ()

void                gtk_font_button_set_show_size       (GtkFontButton *font_button,
                                                         gboolean show_size);

If show_size is TRUE, the font size will be displayed along with the name of the selected font.

font_button : | a GtkFontButton
show_size : | TRUE if font size should be displayed in dialog.

Since 2.4

gtk_font_button_get_show_size ()

gboolean            gtk_font_button_get_show_size       (GtkFontButton *font_button);

Returns whether the font size will be shown in the label.

font_button : | a GtkFontButton
Returns : | whether the font size will be shown in the label.

Since 2.4

gtk_font_button_set_use_font ()

void                gtk_font_button_set_use_font        (GtkFontButton *font_button,
                                                         gboolean use_font);

If use_font is TRUE, the font name will be written using the selected font.

font_button : | a GtkFontButton
use_font : | If TRUE, font name will be written using font chosen.

Since 2.4

gtk_font_button_get_use_font ()

gboolean            gtk_font_button_get_use_font        (GtkFontButton *font_button);

Returns whether the selected font is used in the label.

font_button : | a GtkFontButton
Returns : | whether the selected font is used in the label.

Since 2.4

gtk_font_button_set_use_size ()

void                gtk_font_button_set_use_size        (GtkFontButton *font_button,
                                                         gboolean use_size);

If use_size is TRUE, the font name will be written using the selected size.

font_button : | a GtkFontButton
use_size : | If TRUE, font name will be written using the selected size.

Since 2.4

gtk_font_button_get_use_size ()

gboolean            gtk_font_button_get_use_size        (GtkFontButton *font_button);

Returns whether the selected size is used in the label.

font_button : | a GtkFontButton
Returns : | whether the selected size is used in the label.

Since 2.4

gtk_font_button_set_title ()

void                gtk_font_button_set_title           (GtkFontButton *font_button,
                                                         const gchar *title);

Sets the title for the font selection dialog.

font_button : | a GtkFontButton
title : | a string containing the font selection dialog title

Since 2.4

gtk_font_button_get_title ()

const gchar*        gtk_font_button_get_title           (GtkFontButton *font_button);

Retrieves the title of the font selection dialog.

font_button : | a GtkFontButton
Returns : | an internal copy of the title string which must not be freed.

Since 2.4

Property Details

The "font-name" property

  "font-name"                gchararray            : Read / Write

The name of the currently selected font.

Default value: "Sans 12"

Since 2.4

The "show-size" property

  "show-size"                gboolean              : Read / Write

If this property is set to TRUE, the selected font size will be shown in the label. For a more WYSIWYG way to show the selected size, see the ::use-size property.

Default value: TRUE

Since 2.4

The "show-style" property

  "show-style"               gboolean              : Read / Write

If this property is set to TRUE, the name of the selected font style will be shown in the label. For a more WYSIWYG way to show the selected style, see the ::use-font property.

Default value: TRUE

Since 2.4

The "title" property

  "title"                    gchararray            : Read / Write

The title of the font selection dialog.

Default value: "Pick a Font"

Since 2.4

The "use-font" property

  "use-font"                 gboolean              : Read / Write

If this property is set to TRUE, the label will be drawn in the selected font.

Default value: FALSE

Since 2.4

The "use-size" property

  "use-size"                 gboolean              : Read / Write

If this property is set to TRUE, the label will be drawn with the selected font size.

Default value: FALSE

Since 2.4

Signal Details

The "font-set" signal

void                user_function                      (GtkFontButton *widget,
                                                        gpointer       user_data)      : Run First

The ::font-set signal is emitted when the user selects a font. When handling this signal, use gtk_font_button_get_font_name() to find out which font was just selected.

Note that this signal is only emitted when the user changes the font. If you need to react to programmatic font changes as well, use the notify::font-name signal.

widget : | the object which received the signal.
user_data : | user data set when the signal handler was connected.

Since 2.4

See Also

GtkFontSelectionDialog, GtkColorButton.


GtkFontSelection

GtkFontSelection — A widget for selecting fonts

Synopsis

#include <gtk/gtk.h>

                    GtkFontSelection;
GtkWidget*          gtk_font_selection_new              (void);
GdkFont*            gtk_font_selection_get_font         (GtkFontSelection *fontsel);
gchar*              gtk_font_selection_get_font_name    (GtkFontSelection *fontsel);
gboolean            gtk_font_selection_set_font_name    (GtkFontSelection *fontsel,
                                                         const gchar *fontname);
const gchar*        gtk_font_selection_get_preview_text (GtkFontSelection *fontsel);
void                gtk_font_selection_set_preview_text (GtkFontSelection *fontsel,
                                                         const gchar *text);

Object Hierarchy

  GObject
   +----GInitiallyUnowned
         +----GtkObject
               +----GtkWidget
                     +----GtkContainer
                           +----GtkBox
                                 +----GtkVBox
                                       +----GtkFontSelection

Implemented Interfaces

GtkFontSelection implements AtkImplementorIface.

Properties

  "font"                     GdkFont               : Read
  "font-name"                gchararray            : Read / Write
  "preview-text"             gchararray            : Read / Write

Description

The GtkFontSelection widget lists the available fonts, styles and sizes, allowing the user to select a font. It is used in the GtkFontSelectionDialog widget to provide a dialog box for selecting fonts.

To set the font which is initially selected, use gtk_font_selection_set_font_name().

To get the selected font use gtk_font_selection_get_font_name().

To change the text which is shown in the preview area, use gtk_font_selection_set_preview_text().

Details

GtkFontSelection

typedef struct _GtkFontSelection GtkFontSelection;

The GtkFontSelection struct contains private data only, and should only be accessed using the functions below.

gtk_font_selection_new ()

GtkWidget*          gtk_font_selection_new              (void);

Creates a new GtkFontSelection.

Returns : a new GtkFontSelection.

gtk_font_selection_get_font ()

GdkFont*            gtk_font_selection_get_font         (GtkFontSelection *fontsel);

Warning

gtk_font_selection_get_font is deprecated and should not be used in newly-written code.

Gets the currently-selected font.

fontsel : | a GtkFontSelection.
Returns : | the currently-selected font, or NULL if no font is selected.

gtk_font_selection_get_font_name ()

gchar*              gtk_font_selection_get_font_name    (GtkFontSelection *fontsel);

Gets the currently-selected font name. Note that this can be a different string than what you set with gtk_font_selection_set_font_name(), as the font selection widget may normalize font names and thus return a string with a different structure. For example, "Helvetica Italic Bold 12" could be normalized to "Helvetica Bold Italic 12". Use pango_font_description_equal() if you want to compare two font descriptions.

fontsel : | a GtkFontSelection
Returns : | A string with the name of the current font, or NULL if no font is selected. You must free this string with g_free().

gtk_font_selection_set_font_name ()

gboolean            gtk_font_selection_set_font_name    (GtkFontSelection *fontsel,
                                                         const gchar *fontname);

Sets the currently-selected font. Note that the fontsel needs to know the screen in which it will appear for this to work; this can be guaranteed by simply making sure that the fontsel is inserted in a toplevel window before you call this function.

fontsel : | a GtkFontSelection
fontname : | a font name like "Helvetica 12" or "Times Bold 18"
Returns : | TRUE if the font could be set successfully; FALSE if no such font exists or if the fontsel doesn't belong to a particular screen yet.

gtk_font_selection_get_preview_text ()

const gchar*        gtk_font_selection_get_preview_text (GtkFontSelection *fontsel);

Gets the text displayed in the preview area.

fontsel : | a GtkFontSelection.
Returns : | the text displayed in the preview area. This string is owned by the widget and should not be modified or freed.

gtk_font_selection_set_preview_text ()

void                gtk_font_selection_set_preview_text (GtkFontSelection *fontsel,
                                                         const gchar *text);

Sets the text displayed in the preview area.

fontsel : | a GtkFontSelection.
text : | the text to display in the preview area.

Property Details

The "font" property

  "font"                     GdkFont               : Read

The GdkFont that is currently selected.

The "font-name" property

  "font-name"                gchararray            : Read / Write

The X string that represents this font.

Default value: NULL

The "preview-text" property

  "preview-text"             gchararray            : Read / Write

The text to display in order to demonstrate the selected font.

Default value: "abcdefghijk ABCDEFGHIJK"

See Also

GtkFontSelectionDialog

a dialog box which uses GtkFontSelection.


GtkFontSelectionDialog

GtkFontSelectionDialog — A dialog box for selecting fonts

Synopsis

#include <gtk/gtk.h>

                    GtkFontSelectionDialog;
GtkWidget*          gtk_font_selection_dialog_new       (const gchar *title);
GdkFont*            gtk_font_selection_dialog_get_font  (GtkFontSelectionDialog *fsd);
gchar*              gtk_font_selection_dialog_get_font_name
                                                        (GtkFontSelectionDialog *fsd);
gboolean            gtk_font_selection_dialog_set_font_name
                                                        (GtkFontSelectionDialog *fsd,
                                                         const gchar *fontname);
const gchar*        gtk_font_selection_dialog_get_preview_text
                                                        (GtkFontSelectionDialog *fsd);
void                gtk_font_selection_dialog_set_preview_text
                                                        (GtkFontSelectionDialog *fsd,
                                                         const gchar *text);

Object Hierarchy

  GObject
   +----GInitiallyUnowned
         +----GtkObject
               +----GtkWidget
                     +----GtkContainer
                           +----GtkBin
                                 +----GtkWindow
                                       +----GtkDialog
                                             +----GtkFontSelectionDialog

Implemented Interfaces

GtkFontSelectionDialog implements AtkImplementorIface.

Description

The GtkFontSelectionDialog widget is a dialog box for selecting a font.

To set the font which is initially selected, use gtk_font_selection_dialog_set_font_name().

To get the selected font use gtk_font_selection_dialog_get_font_name().

To change the text which is shown in the preview area, use gtk_font_selection_dialog_set_preview_text().

Details

GtkFontSelectionDialog

typedef struct {
  GtkWidget *ok_button;
  GtkWidget *apply_button;
  GtkWidget *cancel_button;
} GtkFontSelectionDialog;

GtkWidget *ok_button; | The OK button of the dialog
GtkWidget *apply_button; | The Apply button of the dialog. This button is hidden by default but you can show/hide it
GtkWidget *cancel_button; | The Cancel button of the dialog

gtk_font_selection_dialog_new ()

GtkWidget*          gtk_font_selection_dialog_new       (const gchar *title);

Creates a new GtkFontSelectionDialog.

title : | the title of the dialog box.
Returns : | a new GtkFontSelectionDialog.

gtk_font_selection_dialog_get_font ()

GdkFont*            gtk_font_selection_dialog_get_font  (GtkFontSelectionDialog *fsd);

Warning

gtk_font_selection_dialog_get_font is deprecated and should not be used in newly-written code.

Gets the currently-selected font.

fsd : | a GtkFontSelectionDialog.
Returns : | the currently-selected font, or NULL if no font is selected.

gtk_font_selection_dialog_get_font_name ()

gchar*              gtk_font_selection_dialog_get_font_name
                                                        (GtkFontSelectionDialog *fsd);

Gets the currently-selected font name. Note that this can be a different string than what you set with gtk_font_selection_dialog_set_font_name(), as the font selection widget may normalize font names and thus return a string with a different structure. For example, "Helvetica Italic Bold 12" could be normalized to "Helvetica Bold Italic 12". Use pango_font_description_equal() if you want to compare two font descriptions.

fsd : | a GtkFontSelectionDialog
Returns : | A string with the name of the current font, or NULL if no font is selected. You must free this string with g_free().

gtk_font_selection_dialog_set_font_name ()

gboolean            gtk_font_selection_dialog_set_font_name
                                                        (GtkFontSelectionDialog *fsd,
                                                         const gchar *fontname);

Sets the currently-selected font.

fsd : | a GtkFontSelectionDialog.
fontname : | a fontname.
Returns : | TRUE if the font was found.

gtk_font_selection_dialog_get_preview_text ()

const gchar*        gtk_font_selection_dialog_get_preview_text
                                                        (GtkFontSelectionDialog *fsd);

Gets the text displayed in the preview area.

fsd : | a GtkFontSelectionDialog.
Returns : | the text displayed in the preview area. This string is owned by the widget and should not be modified or freed.

gtk_font_selection_dialog_set_preview_text ()

void                gtk_font_selection_dialog_set_preview_text
                                                        (GtkFontSelectionDialog *fsd,
                                                         const gchar *text);

Sets the text displayed in the preview area.

fsd : | a GtkFontSelectionDialog.
text : | the text to display in the preview area.

See Also

GtkFontSelection, GtkDialog

the underlying widget for selecting fonts.

the parent class of GtkFontSelectionDialog


GtkFrame

GtkFrame — A bin with a decorative frame and optional label

Synopsis

#include <gtk/gtk.h>

                    GtkFrame;
GtkWidget*          gtk_frame_new                       (const gchar *label);
void                gtk_frame_set_label                 (GtkFrame *frame,
                                                         const gchar *label);
void                gtk_frame_set_label_widget          (GtkFrame *frame,
                                                         GtkWidget *label_widget);
void                gtk_frame_set_label_align           (GtkFrame *frame,
                                                         gfloat xalign,
                                                         gfloat yalign);
void                gtk_frame_set_shadow_type           (GtkFrame *frame,
                                                         GtkShadowType type);
const gchar*        gtk_frame_get_label                 (GtkFrame *frame);
void                gtk_frame_get_label_align           (GtkFrame *frame,
                                                         gfloat *xalign,
                                                         gfloat *yalign);
GtkWidget*          gtk_frame_get_label_widget          (GtkFrame *frame);
GtkShadowType       gtk_frame_get_shadow_type           (GtkFrame *frame);

Object Hierarchy

  GObject
   +----GInitiallyUnowned
         +----GtkObject
               +----GtkWidget
                     +----GtkContainer
                           +----GtkBin
                                 +----GtkFrame
                                       +----GtkAspectFrame

Implemented Interfaces

GtkFrame implements AtkImplementorIface.

Properties

  "label"                    gchararray            : Read / Write
  "label-widget"             GtkWidget             : Read / Write
  "label-xalign"             gfloat                : Read / Write
  "label-yalign"             gfloat                : Read / Write
  "shadow"                   GtkShadowType         : Read / Write
  "shadow-type"              GtkShadowType         : Read / Write

Description

The frame widget is a Bin that surrounds its child with a decorative frame and an optional label. If present, the label is drawn in a gap in the top side of the frame. The position of the label can be controlled with gtk_frame_set_label_align().

Details

GtkFrame

typedef struct _GtkFrame GtkFrame;

gtk_frame_new ()

GtkWidget*          gtk_frame_new                       (const gchar *label);

Creates a new GtkFrame, with optional label label. If label is NULL, the label is omitted.

label : | the text to use as the label of the frame
Returns : | a new GtkFrame widget

gtk_frame_set_label ()

void                gtk_frame_set_label                 (GtkFrame *frame,
                                                         const gchar *label);

Sets the text of the label. If label is NULL, the current label is removed.

frame : | a GtkFrame
label : | the text to use as the label of the frame

gtk_frame_set_label_widget ()

void                gtk_frame_set_label_widget          (GtkFrame *frame,
                                                         GtkWidget *label_widget);

Sets the label widget for the frame. This is the widget that will appear embedded in the top edge of the frame as a title.

frame : | a GtkFrame
label_widget : | the new label widget

gtk_frame_set_label_align ()

void                gtk_frame_set_label_align           (GtkFrame *frame,
                                                         gfloat xalign,
                                                         gfloat yalign);

Sets the alignment of the frame widget's label. The default values for a newly created frame are 0.0 and 0.5.

frame : | a GtkFrame
xalign : | The position of the label along the top edge of the widget. A value of 0.0 represents left alignment; 1.0 represents right alignment.
yalign : | The y alignment of the label. A value of 0.0 aligns under the frame; 1.0 aligns above the frame.

gtk_frame_set_shadow_type ()

void                gtk_frame_set_shadow_type           (GtkFrame *frame,
                                                         GtkShadowType type);

Sets the shadow type for frame.

frame : | a GtkFrame
type : | the new GtkShadowType

gtk_frame_get_label ()

const gchar*        gtk_frame_get_label                 (GtkFrame *frame);

If the frame's label widget is a GtkLabel, returns the text in the label widget. (The frame will have a GtkLabel for the label widget if a non-NULL argument was passed to gtk_frame_new().)

frame : | a GtkFrame
Returns : | the text in the label, or NULL if there was no label widget or the lable widget was not a GtkLabel. This string is owned by GTK+ and must not be modified or freed.

gtk_frame_get_label_align ()

void                gtk_frame_get_label_align           (GtkFrame *frame,
                                                         gfloat *xalign,
                                                         gfloat *yalign);

Retrieves the X and Y alignment of the frame's label. See gtk_frame_set_label_align().

frame : | a GtkFrame
xalign : | location to store X alignment of frame's label, or NULL
yalign : | location to store X alignment of frame's label, or NULL

gtk_frame_get_label_widget ()

GtkWidget*          gtk_frame_get_label_widget          (GtkFrame *frame);

Retrieves the label widget for the frame. See gtk_frame_set_label_widget().

frame : | a GtkFrame
Returns : | the label widget, or NULL if there is none.

gtk_frame_get_shadow_type ()

GtkShadowType       gtk_frame_get_shadow_type           (GtkFrame *frame);

Retrieves the shadow type of the frame. See gtk_frame_set_shadow_type().

frame : | a GtkFrame
Returns : | the current shadow type of the frame.

Property Details

The "label" property

  "label"                    gchararray            : Read / Write

Text of the frame's label.

Default value: NULL

The "label-widget" property

  "label-widget"             GtkWidget             : Read / Write

A widget to display in place of the usual frame label.

The "label-xalign" property

  "label-xalign"             gfloat                : Read / Write

The horizontal alignment of the label.

Allowed values: [0,1]

Default value: 0.5

The "label-yalign" property

  "label-yalign"             gfloat                : Read / Write

The vertical alignment of the label.

Allowed values: [0,1]

Default value: 0.5

The "shadow" property

  "shadow"                   GtkShadowType         : Read / Write

Deprecated property, use shadow_type instead.

Default value: GTK_SHADOW_ETCHED_IN

The "shadow-type" property

  "shadow-type"              GtkShadowType         : Read / Write

Appearance of the frame border.

Default value: GTK_SHADOW_ETCHED_IN


GtkGammaCurve

GtkGammaCurve — a subclass of GtkCurve for editing gamma curves.

Synopsis

#include <gtk/gtk.h>

                    GtkGammaCurve;
GtkWidget*          gtk_gamma_curve_new                 (void);

Object Hierarchy

  GObject
   +----GInitiallyUnowned
         +----GtkObject
               +----GtkWidget
                     +----GtkContainer
                           +----GtkBox
                                 +----GtkVBox
                                       +----GtkGammaCurve

Implemented Interfaces

GtkGammaCurve implements AtkImplementorIface.

Description

Note

This widget is considered too specialized/little-used for GTK+, and will in the future be moved to some other package. If your application needs this widget, feel free to use it, as the widget does work and is useful in some applications; it's just not of general interest. However, we are not accepting new features for the widget, and it will eventually move out of the GTK+ distribution.

The GtkGammaCurve widget is a variant of GtkCurve specifically for editing gamma curves, which are used in graphics applications such as the Gimp.

The GtkGammaCurve widget shows a curve which the user can edit with the mouse just like a GtkCurve widget. On the right of the curve it also displays 5 buttons, 3 of which change between the 3 curve modes (spline, linear and free), and the other 2 set the curve to a particular gamma value, or reset it to a straight line.

Details

GtkGammaCurve

typedef struct _GtkGammaCurve GtkGammaCurve;

The GtkGammaCurve struct contains private data only, and should be accessed using the functions below.

gtk_gamma_curve_new ()

GtkWidget*          gtk_gamma_curve_new                 (void);

Creates a new GtkGammaCurve.

Returns : a new GtkGammaCurve.


GtkHandleBox

GtkHandleBox — a widget for detachable window portions

Synopsis

#include <gtk/gtk.h>

                    GtkHandleBox;
GtkWidget*          gtk_handle_box_new                  (void);
void                gtk_handle_box_set_shadow_type      (GtkHandleBox *handle_box,
                                                         GtkShadowType type);
void                gtk_handle_box_set_handle_position  (GtkHandleBox *handle_box,
                                                         GtkPositionType position);
void                gtk_handle_box_set_snap_edge        (GtkHandleBox *handle_box,
                                                         GtkPositionType edge);
GtkPositionType     gtk_handle_box_get_handle_position  (GtkHandleBox *handle_box);
GtkShadowType       gtk_handle_box_get_shadow_type      (GtkHandleBox *handle_box);
GtkPositionType     gtk_handle_box_get_snap_edge        (GtkHandleBox *handle_box);

Object Hierarchy

  GObject
   +----GInitiallyUnowned
         +----GtkObject
               +----GtkWidget
                     +----GtkContainer
                           +----GtkBin
                                 +----GtkHandleBox

Implemented Interfaces

GtkHandleBox implements AtkImplementorIface.

Properties

  "handle-position"          GtkPositionType       : Read / Write
  "shadow"                   GtkShadowType         : Read / Write
  "shadow-type"              GtkShadowType         : Read / Write
  "snap-edge"                GtkPositionType       : Read / Write
  "snap-edge-set"            gboolean              : Read / Write

Signals

  "child-attached"                                 : Run First
  "child-detached"                                 : Run First

Description

The GtkHandleBox widget allows a portion of a window to be "torn off". It is a bin widget which displays its child and a handle that the user can drag to tear off a separate window (the float window) containing the child widget. A thin ghost is drawn in the original location of the handlebox. By dragging the separate window back to its original location, it can be reattached.

When reattaching, the ghost and float window, must be aligned along one of the edges, the snap edge. This either can be specified by the application programmer explicitely, or GTK+ will pick a reasonable default based on the handle position.

To make detaching and reattaching the handlebox as minimally confusing as possible to the user, it is important to set the snap edge so that the snap edge does not move when the handlebox is deattached. For instance, if the handlebox is packed at the bottom of a VBox, then when the handlebox is detached, the bottom edge of the handlebox's allocation will remain fixed as the height of the handlebox shrinks, so the snap edge should be set to GTK_POS_BOTTOM.

Details

GtkHandleBox

typedef struct _GtkHandleBox GtkHandleBox;

The GtkHandleBox struct contains the following fields. (These fields should be considered read-only. They should never be set by an application.)

GtkShadowType shadow_type; | The shadow type for the entry. (See gtk_handle_box_set_shadow_type()).
GtkPositionType handle_position; | The position of the handlebox's handle with respect to the child. (See gtk_handle_box_set_handle_position())
gint snap_edge; | A value of type GtkPosition type indicating snap edge for the widget. (See gtk_handle_box_set_snap_edge). The value of -1 indicates that this value has not been set.
gboolean child_detached; | A boolean value indicating whether the handlebox's child is attached or detached.

gtk_handle_box_new ()

GtkWidget*          gtk_handle_box_new                  (void);

Create a new handle box.

Returns : a new GtkHandleBox.

gtk_handle_box_set_shadow_type ()

void                gtk_handle_box_set_shadow_type      (GtkHandleBox *handle_box,
                                                         GtkShadowType type);

Sets the type of shadow to be drawn around the border of the handle box.

handle_box : | a GtkHandleBox
type : | the shadow type.

gtk_handle_box_set_handle_position ()

void                gtk_handle_box_set_handle_position  (GtkHandleBox *handle_box,
                                                         GtkPositionType position);

Sets the side of the handlebox where the handle is drawn.

handle_box : | a GtkHandleBox
position : | the side of the handlebox where the handle should be drawn.

gtk_handle_box_set_snap_edge ()

void                gtk_handle_box_set_snap_edge        (GtkHandleBox *handle_box,
                                                         GtkPositionType edge);

Sets the snap edge of a handlebox. The snap edge is the edge of the detached child that must be aligned with the corresponding edge of the "ghost" left behind when the child was detached to reattach the torn-off window. Usually, the snap edge should be chosen so that it stays in the same place on the screen when the handlebox is torn off.

If the snap edge is not set, then an appropriate value will be guessed from the handle position. If the handle position is GTK_POS_RIGHT or GTK_POS_LEFT, then the snap edge will be GTK_POS_TOP, otherwise it will be GTK_POS_LEFT.

handle_box : | a GtkHandleBox
edge : | the snap edge, or -1 to unset the value; in which case GTK+ will try to guess an appropriate value in the future.

gtk_handle_box_get_handle_position ()

GtkPositionType     gtk_handle_box_get_handle_position  (GtkHandleBox *handle_box);

Gets the handle position of the handle box. See gtk_handle_box_set_handle_position().

handle_box : | a GtkHandleBox
Returns : | the current handle position.

gtk_handle_box_get_shadow_type ()

GtkShadowType       gtk_handle_box_get_shadow_type      (GtkHandleBox *handle_box);

Gets the type of shadow drawn around the handle box. See gtk_handle_box_set_shadow_type().

handle_box : | a GtkHandleBox
Returns : | the type of shadow currently drawn around the handle box.

gtk_handle_box_get_snap_edge ()

GtkPositionType     gtk_handle_box_get_snap_edge        (GtkHandleBox *handle_box);

Gets the edge used for determining reattachment of the handle box. See gtk_handle_box_set_snap_edge().

handle_box : | a GtkHandleBox
Returns : | the edge used for determining reattachment, or (GtkPositionType)-1 if this is determined (as per default) from the handle position.

Property Details

The "handle-position" property

  "handle-position"          GtkPositionType       : Read / Write

Position of the handle relative to the child widget.

Default value: GTK_POS_LEFT

The "shadow" property

  "shadow"                   GtkShadowType         : Read / Write

Deprecated property, use shadow_type instead.

Default value: GTK_SHADOW_ETCHED_OUT

The "shadow-type" property

  "shadow-type"              GtkShadowType         : Read / Write

Appearance of the shadow that surrounds the container.

Default value: GTK_SHADOW_ETCHED_OUT

The "snap-edge" property

  "snap-edge"                GtkPositionType       : Read / Write

Side of the handlebox that's lined up with the docking point to dock the handlebox.

Default value: GTK_POS_TOP

The "snap-edge-set" property

  "snap-edge-set"            gboolean              : Read / Write

Whether to use the value from the snap_edge property or a value derived from handle_position.

Default value: FALSE

Signal Details

The "child-attached" signal

void                user_function                      (GtkHandleBox *handlebox,
                                                        GtkWidget    *widget,
                                                        gpointer      user_data)      : Run First

This signal is emitted when the contents of the handlebox are reattached to the main window.

handlebox : | the object which received the signal.
widget : | the child widget of the handlebox. (this argument provides no extra information and is here only for backwards-compatibility)
user_data : | user data set when the signal handler was connected.

The "child-detached" signal

void                user_function                      (GtkHandleBox *handlebox,
                                                        GtkWidget    *widget,
                                                        gpointer      user_data)      : Run First

This signal is emitted when the contents of the handlebox are detached from the main window.

handlebox : | the object which received the signal.
widget : | the child widget of the handlebox. (this argument provides no extra information and is here only for backwards-compatibility)
user_data : | user data set when the signal handler was connected.


GtkHBox

GtkHBox — A horizontal container box

Synopsis

#include <gtk/gtk.h>

                    GtkHBox;
GtkWidget*          gtk_hbox_new                        (gboolean homogeneous,
                                                         gint spacing);

Object Hierarchy

  GObject
   +----GInitiallyUnowned
         +----GtkObject
               +----GtkWidget
                     +----GtkContainer
                           +----GtkBox
                                 +----GtkHBox
                                       +----GtkCombo
                                       +----GtkFileChooserButton
                                       +----GtkStatusbar

Implemented Interfaces

GtkHBox implements AtkImplementorIface.

Description

GtkHBox is a container that organizes child widgets into a single row.

Use the GtkBox packing interface to determine the arrangement, spacing, width, and alignment of GtkHBox children.

All children are allocated the same height.

Details

GtkHBox

typedef struct _GtkHBox GtkHBox;

gtk_hbox_new ()

GtkWidget*          gtk_hbox_new                        (gboolean homogeneous,
                                                         gint spacing);

Creates a new GtkHBox.

homogeneous : | TRUE if all children are to be given equal space allotments.
spacing : | the number of pixels to place by default between children.
Returns : | a new GtkHBox.

See Also

GtkVBox

a sister class that organizes widgets into a column.


GtkHButtonBox

GtkHButtonBox — A container for arranging buttons horizontally

Synopsis

#include <gtk/gtk.h>

                    GtkHButtonBox;
GtkWidget*          gtk_hbutton_box_new                 (void);
gint                gtk_hbutton_box_get_spacing_default (void);
GtkButtonBoxStyle   gtk_hbutton_box_get_layout_default  (void);
void                gtk_hbutton_box_set_spacing_default (gint spacing);
void                gtk_hbutton_box_set_layout_default  (GtkButtonBoxStyle layout);

Object Hierarchy

  GObject
   +----GInitiallyUnowned
         +----GtkObject
               +----GtkWidget
                     +----GtkContainer
                           +----GtkBox
                                 +----GtkButtonBox
                                       +----GtkHButtonBox

Implemented Interfaces

GtkHButtonBox implements AtkImplementorIface.

Description

A button box should be used to provide a consistent layout of buttons throughout your application. The layout/spacing can be altered by the programmer, or if desired, by the user to alter the 'feel' of a program to a small degree.

A GtkHButtonBox is created with gtk_hbutton_box_new(). Buttons are packed into a button box the same way widgets are added to any other container, using gtk_container_add(). You can also use gtk_box_pack_start() or gtk_box_pack_end(), but for button boxes both these functions work just like gtk_container_add(), ie., they pack the button in a way that depends on the current layout style and on whether the button has had gtk_button_box_set_child_secondary() called on it.

The spacing between buttons can be set with gtk_box_set_spacing(). The arrangement and layout of the buttons can be changed with gtk_button_box_set_layout().

Details

GtkHButtonBox

typedef struct _GtkHButtonBox GtkHButtonBox;

GtkHButtonBox does not contain any public fields.

gtk_hbutton_box_new ()

GtkWidget*          gtk_hbutton_box_new                 (void);

Creates a new horizontal button box.

Returns : a new button box GtkWidget.

gtk_hbutton_box_get_spacing_default ()

gint                gtk_hbutton_box_get_spacing_default (void);

Warning

gtk_hbutton_box_get_spacing_default is deprecated and should not be used in newly-written code.

Retrieves the current default spacing for horizontal button boxes. This is the number of pixels to be placed between the buttons when they are arranged.

Returns : the default number of pixels between buttons.

gtk_hbutton_box_get_layout_default ()

GtkButtonBoxStyle   gtk_hbutton_box_get_layout_default  (void);

Warning

gtk_hbutton_box_get_layout_default is deprecated and should not be used in newly-written code.

Retrieves the current layout used to arrange buttons in button box widgets.

Returns : the current GtkButtonBoxStyle.

gtk_hbutton_box_set_spacing_default ()

void                gtk_hbutton_box_set_spacing_default (gint spacing);

Warning

gtk_hbutton_box_set_spacing_default is deprecated and should not be used in newly-written code.

Changes the default spacing that is placed between widgets in an horizontal button box.

spacing : an integer value.

gtk_hbutton_box_set_layout_default ()

void                gtk_hbutton_box_set_layout_default  (GtkButtonBoxStyle layout);

Warning

gtk_hbutton_box_set_layout_default is deprecated and should not be used in newly-written code.

Sets a new layout mode that will be used by all button boxes.

layout : a new GtkButtonBoxStyle.

See Also

GtkBox | Used to pack widgets into button boxes.
GtkButtonBox | Provides functions for controlling button boxes.
GtkVButtonBox | Pack buttons vertically


GtkHPaned

GtkHPaned — A container with two panes arranged horizontally

Synopsis

#include <gtk/gtk.h>

                    GtkHPaned;
GtkWidget*          gtk_hpaned_new                      (void);

Object Hierarchy

  GObject
   +----GInitiallyUnowned
         +----GtkObject
               +----GtkWidget
                     +----GtkContainer
                           +----GtkPaned
                                 +----GtkHPaned

Implemented Interfaces

GtkHPaned implements AtkImplementorIface.

Description

The HPaned widget is a container widget with two children arranged horizontally. The division between the two panes is adjustable by the user by dragging a handle. See GtkPaned for details.

Details

GtkHPaned

typedef struct _GtkHPaned GtkHPaned;

gtk_hpaned_new ()

GtkWidget*          gtk_hpaned_new                      (void);

Create a new GtkHPaned

Returns : the new GtkHPaned


GtkHRuler

GtkHRuler — A horizontal ruler.

Synopsis

#include <gtk/gtk.h>

                    GtkHRuler;
GtkWidget*          gtk_hruler_new                      (void);

Object Hierarchy

  GObject
   +----GInitiallyUnowned
         +----GtkObject
               +----GtkWidget
                     +----GtkRuler
                           +----GtkHRuler

Implemented Interfaces

GtkHRuler implements AtkImplementorIface.

Description

Note

This widget is considered too specialized/little-used for GTK+, and will in the future be moved to some other package. If your application needs this widget, feel free to use it, as the widget does work and is useful in some applications; it's just not of general interest. However, we are not accepting new features for the widget, and it will eventually move out of the GTK+ distribution.

The HRuler widget is a widget arranged horizontally creating a ruler that is utilized around other widgets such as a text widget. The ruler is used to show the location of the mouse on the window and to show the size of the window in specified units. The available units of measurement are GTK_PIXELS, GTK_INCHES and GTK_CENTIMETERS. GTK_PIXELS is the default. rulers.

Details

GtkHRuler

typedef struct _GtkHRuler GtkHRuler;

The GtkHRuler struct contains private data and should be accessed with the functions below.

gtk_hruler_new ()

GtkWidget*          gtk_hruler_new                      (void);

Creates a new horizontal ruler.

Returns : a new GtkHRuler.


GtkHScale

GtkHScale — A horizontal slider widget for selecting a value from a range

Synopsis

#include <gtk/gtk.h>

                    GtkHScale;
GtkWidget*          gtk_hscale_new                      (GtkAdjustment *adjustment);
GtkWidget*          gtk_hscale_new_with_range           (gdouble min,
                                                         gdouble max,
                                                         gdouble step);

Object Hierarchy

  GObject
   +----GInitiallyUnowned
         +----GtkObject
               +----GtkWidget
                     +----GtkRange
                           +----GtkScale
                                 +----GtkHScale

Implemented Interfaces

GtkHScale implements AtkImplementorIface.

Description

The GtkHScale widget is used to allow the user to select a value using a horizontal slider. To create one, use gtk_hscale_new_with_range().

The position to show the current value, and the number of decimal places shown can be set using the parent GtkScale class's functions.

Details

GtkHScale

typedef struct _GtkHScale GtkHScale;

The GtkHScale struct contains private data only, and should be accessed using the functions below.

gtk_hscale_new ()

GtkWidget*          gtk_hscale_new                      (GtkAdjustment *adjustment);

Creates a new GtkHScale.

adjustment : | the GtkAdjustment which sets the range of the scale.
Returns : | a new GtkHScale.

gtk_hscale_new_with_range ()

GtkWidget*          gtk_hscale_new_with_range           (gdouble min,
                                                         gdouble max,
                                                         gdouble step);

Creates a new horizontal scale widget that lets the user input a number between min and max (including min and max) with the increment step. step must be nonzero; it's the distance the slider moves when using the arrow keys to adjust the scale value.

Note that the way in which the precision is derived works best if step is a power of ten. If the resulting precision is not suitable for your needs, use gtk_scale_set_digits() to correct it.

min : | minimum value
max : | maximum value
step : | step increment (tick size) used with keyboard shortcuts
Returns : | a new GtkHScale


GtkHScrollbar

GtkHScrollbar — A horizontal scrollbar

Synopsis

#include <gtk/gtk.h>

                    GtkHScrollbar;
GtkWidget*          gtk_hscrollbar_new                  (GtkAdjustment *adjustment);

Object Hierarchy

  GObject
   +----GInitiallyUnowned
         +----GtkObject
               +----GtkWidget
                     +----GtkRange
                           +----GtkScrollbar
                                 +----GtkHScrollbar

Implemented Interfaces

GtkHScrollbar implements AtkImplementorIface.

Description

The GtkHScrollbar widget is a widget arranged horizontally creating a scrollbar. See GtkScrollbar for details on scrollbars. GtkAdjustment pointers may be added to handle the adjustment of the scrollbar or it may be left NULL in which case one will be created for you. See GtkAdjustment for details.

Details

GtkHScrollbar

typedef struct _GtkHScrollbar GtkHScrollbar;

The GtkHScrollbar struct contains private data and should be accessed using the functions below.

gtk_hscrollbar_new ()

GtkWidget*          gtk_hscrollbar_new                  (GtkAdjustment *adjustment);

Creates a new horizontal scrollbar.

adjustment : | the GtkAdjustment to use, or NULL to create a new adjustment.
Returns : | the new GtkHScrollbar.

See Also

GtkScrollbar, GtkScrolledWindow


GtkHSeparator

GtkHSeparator — A horizontal separator

Synopsis

#include <gtk/gtk.h>

                    GtkHSeparator;
GtkWidget*          gtk_hseparator_new                  (void);

Object Hierarchy

  GObject
   +----GInitiallyUnowned
         +----GtkObject
               +----GtkWidget
                     +----GtkSeparator
                           +----GtkHSeparator

Implemented Interfaces

GtkHSeparator implements AtkImplementorIface.

Description

The GtkHSeparator widget is a horizontal separator, used to group the widgets within a window. It displays a horizontal line with a shadow to make it appear sunken into the interface.

Note

The GtkHSeparator widget is not used as a separator within menus. To create a separator in a menu create an empty GtkSeparatorMenuItem widget using gtk_separator_menu_item_new() and add it to the menu with gtk_menu_shell_append().

Details

GtkHSeparator

typedef struct _GtkHSeparator GtkHSeparator;

The GtkHSeparator struct contains private data only, and should be accessed using the functions below.

gtk_hseparator_new ()

GtkWidget*          gtk_hseparator_new                  (void);

Creates a new GtkHSeparator.

Returns : a new GtkHSeparator.

See Also

GtkVSeparator

a vertical separator.


GtkIconTheme

GtkIconTheme — Looking up icons by name

Synopsis

#include <gtk/gtk.h>

                    GtkIconInfo;
                    GtkIconTheme;
enum                GtkIconLookupFlags;
#define             GTK_ICON_THEME_ERROR
enum                GtkIconThemeError;
GtkIconTheme*       gtk_icon_theme_new                  (void);
GtkIconTheme*       gtk_icon_theme_get_default          (void);
GtkIconTheme*       gtk_icon_theme_get_for_screen       (GdkScreen *screen);
void                gtk_icon_theme_set_screen           (GtkIconTheme *icon_theme,
                                                         GdkScreen *screen);
void                gtk_icon_theme_set_search_path      (GtkIconTheme *icon_theme,
                                                         const gchar *path[],
                                                         gint n_elements);
void                gtk_icon_theme_get_search_path      (GtkIconTheme *icon_theme,
                                                         gchar **path[],
                                                         gint *n_elements);
void                gtk_icon_theme_append_search_path   (GtkIconTheme *icon_theme,
                                                         const gchar *path);
void                gtk_icon_theme_prepend_search_path  (GtkIconTheme *icon_theme,
                                                         const gchar *path);
void                gtk_icon_theme_set_custom_theme     (GtkIconTheme *icon_theme,
                                                         const gchar *theme_name);
gboolean            gtk_icon_theme_has_icon             (GtkIconTheme *icon_theme,
                                                         const gchar *icon_name);
GtkIconInfo*        gtk_icon_theme_lookup_icon          (GtkIconTheme *icon_theme,
                                                         const gchar *icon_name,
                                                         gint size,
                                                         GtkIconLookupFlags flags);
GdkPixbuf*          gtk_icon_theme_load_icon            (GtkIconTheme *icon_theme,
                                                         const gchar *icon_name,
                                                         gint size,
                                                         GtkIconLookupFlags flags,
                                                         GError **error);
GList*              gtk_icon_theme_list_icons           (GtkIconTheme *icon_theme,
                                                         const gchar *context);
gint*               gtk_icon_theme_get_icon_sizes       (GtkIconTheme *icon_theme,
                                                         const gchar *icon_name);
char*               gtk_icon_theme_get_example_icon_name
                                                        (GtkIconTheme *icon_theme);
gboolean            gtk_icon_theme_rescan_if_needed     (GtkIconTheme *icon_theme);
void                gtk_icon_theme_add_builtin_icon     (const gchar *icon_name,
                                                         gint size,
                                                         GdkPixbuf *pixbuf);
GtkIconInfo*        gtk_icon_info_copy                  (GtkIconInfo *icon_info);
void                gtk_icon_info_free                  (GtkIconInfo *icon_info);
gint                gtk_icon_info_get_base_size         (GtkIconInfo *icon_info);
const gchar*        gtk_icon_info_get_filename          (GtkIconInfo *icon_info);
GdkPixbuf*          gtk_icon_info_get_builtin_pixbuf    (GtkIconInfo *icon_info);
GdkPixbuf*          gtk_icon_info_load_icon             (GtkIconInfo *icon_info,
                                                         GError **error);
void                gtk_icon_info_set_raw_coordinates   (GtkIconInfo *icon_info,
                                                         gboolean raw_coordinates);
gboolean            gtk_icon_info_get_embedded_rect     (GtkIconInfo *icon_info,
                                                         GdkRectangle *rectangle);
gboolean            gtk_icon_info_get_attach_points     (GtkIconInfo *icon_info,
                                                         GdkPoint **points,
                                                         gint *n_points);
const gchar*        gtk_icon_info_get_display_name      (GtkIconInfo *icon_info);

Object Hierarchy

  GObject
   +----GtkIconTheme

Signals

  "changed"                                        : Run Last

Description

GtkIconTheme provides a facility for looking up icons by name and size. The main reason for using a name rather than simply providing a filename is to allow different icons to be used depending on what icon theme is selecetd by the user. The operation of icon themes on Linux and Unix follows the Icon Theme Specification. There is a default icon theme, named hicolor where applications should install their icons, but more additional application themes can be installed as operating system vendors and users choose.

Named icons are similar to the Themeable Stock Images(3) facility, and the distinction between the two may be a bit confusing. A few things to keep in mind:

  • Stock images usually are used in conjunction with Stock Items(3)., such as GTK_STOCK_OK or GTK_STOCK_OPEN. Named icons are easier to set up and therefore are more useful for new icons that an application wants to add, such as application icons or window icons.

  • Stock images can only be loaded at the symbolic sizes defined by the GtkIconSize enumeration, or by custom sizes defined by gtk_icon_size_register(), while named icons are more flexible and any pixel size can be specified.

  • Because stock images are closely tied to stock items, and thus to actions in the user interface, stock images may come in multiple variants for different widget states or writing directions.

A good rule of thumb is that if there is a stock image for what you want to use, use it, otherwise use a named icon. It turns out that internally stock images are generally defined in terms of one or more named icons. (An example of the more than one case is icons that depend on writing direction; GTK_STOCK_GO_FORWARD uses the two themed icons "gtk-stock-go-forward-ltr" and "gtk-stock-go-forward-rtl".)

In many cases, named themes are used indirectly, via GtkImage or stock items, rather than directly, but looking up icons directly is also simple. The GtkIconTheme object acts as a database of all the icons in the current theme. You can create new GtkIconTheme objects, but its much more efficient to use the standard icon theme for the GdkScreen so that the icon information is shared with other people looking up icons. In the case where the default screen is being used, looking up an icon can be as simple as:

GError *error = NULL;
GtkIconTheme *icon_theme;
GdkPixbuf *pixbuf;

icon_theme = gtk_icon_theme_get_default ();
pixbuf = gtk_icon_theme_load_icon (icon_theme,
                                   "my-icon-name", /* icon name */
                                   48, /* size */
                                   0,  /* flags */
                                   &error);
if (!pixbuf)
  {
    g_warning ("Couldn't load icon: %s", error->message);
    g_error_free (error);
  }
else
  {
    /* Use the pixbuf */
    g_object_unref (pixbuf);
  }

Details

GtkIconInfo

typedef struct _GtkIconInfo GtkIconInfo;

Contains information found when looking up an icon in an icon theme.

GtkIconTheme

typedef struct _GtkIconTheme GtkIconTheme;

Acts as a database of information about an icon theme. Normally, you retrieve the icon theme for a particular screen using gtk_icon_theme_get_for_screen() and it will contain information about current icon theme for that screen, but you can also create a new GtkIconTheme object and set the icon theme name explicitely using gtk_icon_theme_set_custom_theme().

enum GtkIconLookupFlags

typedef enum
{
  GTK_ICON_LOOKUP_NO_SVG = 1 << 0,
  GTK_ICON_LOOKUP_FORCE_SVG = 1 << 1,
  GTK_ICON_LOOKUP_USE_BUILTIN = 1 << 2
} GtkIconLookupFlags;

Used to specify options for gtk_icon_theme_lookup_icon()

GTK_ICON_LOOKUP_NO_SVG | Never return SVG icons, even if gdk-pixbuf supports them. Cannot be used together with GTK_ICON_LOOKUP_FORCE_SVG.
GTK_ICON_LOOKUP_FORCE_SVG | Return SVG icons, even if gdk-pixbuf doesn't support them. Cannot be used together with GTK_ICON_LOOKUP_NO_SVG.
GTK_ICON_LOOKUP_USE_BUILTIN | When passed to gtk_icon_theme_lookup_icon() includes builtin icons as well as files. For a builtin icon, gtk_icon_info_get_filename() returns NULL and you need to call gtk_icon_info_get_builtin_pixbuf().

GTK_ICON_THEME_ERROR

#define GTK_ICON_THEME_ERROR gtk_icon_theme_error_quark ()

The GQuark used for GtkIconThemeError errors.

enum GtkIconThemeError

typedef enum {
  GTK_ICON_THEME_NOT_FOUND,
  GTK_ICON_THEME_FAILED
} GtkIconThemeError;

Error codes for GtkIconTheme operations.

GTK_ICON_THEME_NOT_FOUND | The icon specified does not exist in the theme
GTK_ICON_THEME_FAILED | An unspecified error occurred.

gtk_icon_theme_new ()

GtkIconTheme*       gtk_icon_theme_new                  (void);

Creates a new icon theme object. Icon theme objects are used to lookup up an icon by name in a particular icon theme. Usually, you'll want to use gtk_icon_theme_get_default() or gtk_icon_theme_get_for_screen() rather than creating a new icon theme object for scratch.

Returns : the newly created GtkIconTheme object.

Since 2.4

gtk_icon_theme_get_default ()

GtkIconTheme*       gtk_icon_theme_get_default          (void);

Gets the icon theme for the default screen. See gtk_icon_theme_get_for_screen().

Returns : A unique GtkIconTheme associated with the default screen. This icon theme is associated with the screen and can be used as long as the screen is open. Do not ref or unref it.

Since 2.4

gtk_icon_theme_get_for_screen ()

GtkIconTheme*       gtk_icon_theme_get_for_screen       (GdkScreen *screen);

Gets the icon theme object associated with screen; if this function has not previously been called for the given screen, a new icon theme object will be created and associated with the screen. Icon theme objects are fairly expensive to create, so using this function is usually a better choice than calling than gtk_icon_theme_new() and setting the screen yourself; by using this function a single icon theme object will be shared between users.

screen : | a GdkScreen
Returns : | A unique GtkIconTheme associated with the given screen. This icon theme is associated with the screen and can be used as long as the screen is open. Do not ref or unref it.

Since 2.4

gtk_icon_theme_set_screen ()

void                gtk_icon_theme_set_screen           (GtkIconTheme *icon_theme,
                                                         GdkScreen *screen);

Sets the screen for an icon theme; the screen is used to track the user's currently configured icon theme, which might be different for different screens.

icon_theme : | a GtkIconTheme
screen : | a GdkScreen

Since 2.4

gtk_icon_theme_set_search_path ()

void                gtk_icon_theme_set_search_path      (GtkIconTheme *icon_theme,
                                                         const gchar *path[],
                                                         gint n_elements);

Sets the search path for the icon theme object. When looking for an icon theme, GTK+ will search for a subdirectory of one or more of the directories in path with the same name as the icon theme. (Themes from multiple of the path elements are combined to allow themes to be extended by adding icons in the user's home directory.)

In addition if an icon found isn't found either in the current icon theme or the default icon theme, and an image file with the right name is found directly in one of the elements of path, then that image will be used for the icon name. (This is legacy feature, and new icons should be put into the default icon theme, which is called DEFAULT_THEME_NAME, rather than directly on the icon path.)

icon_theme : | a GtkIconTheme
path : | array of directories that are searched for icon themes
n_elements : | number of elements in path.

Since 2.4

gtk_icon_theme_get_search_path ()

void                gtk_icon_theme_get_search_path      (GtkIconTheme *icon_theme,
                                                         gchar **path[],
                                                         gint *n_elements);

Gets the current search path. See gtk_icon_theme_set_search_path().

icon_theme : | a GtkIconTheme
path : | location to store a list of icon theme path directories or NULL The stored value should be freed with g_strfreev().
n_elements : | location to store number of elements in path, or NULL

Since 2.4

gtk_icon_theme_append_search_path ()

void                gtk_icon_theme_append_search_path   (GtkIconTheme *icon_theme,
                                                         const gchar *path);

Appends a directory to the search path. See gtk_icon_theme_set_search_path().

icon_theme : | a GtkIconTheme
path : | directory name to append to the icon path

Since 2.4

gtk_icon_theme_prepend_search_path ()

void                gtk_icon_theme_prepend_search_path  (GtkIconTheme *icon_theme,
                                                         const gchar *path);

Prepends a directory to the search path. See gtk_icon_theme_set_search_path().

icon_theme : | a GtkIconTheme
path : | directory name to prepend to the icon path

Since 2.4

gtk_icon_theme_set_custom_theme ()

void                gtk_icon_theme_set_custom_theme     (GtkIconTheme *icon_theme,
                                                         const gchar *theme_name);

Sets the name of the icon theme that the GtkIconTheme object uses overriding system configuration. This function cannot be called on the icon theme objects returned from gtk_icon_theme_get_default() and gtk_icon_theme_get_for_screen().

icon_theme : | a GtkIconTheme
theme_name : | name of icon theme to use instead of configured theme, or NULL to unset a previously set custom theme

Since 2.4

gtk_icon_theme_has_icon ()

gboolean            gtk_icon_theme_has_icon             (GtkIconTheme *icon_theme,
                                                         const gchar *icon_name);

Checks whether an icon theme includes an icon for a particular name.

icon_theme : | a GtkIconTheme
icon_name : | the name of an icon
Returns : | TRUE if icon_theme includes an icon for icon_name.

Since 2.4

gtk_icon_theme_lookup_icon ()

GtkIconInfo*        gtk_icon_theme_lookup_icon          (GtkIconTheme *icon_theme,
                                                         const gchar *icon_name,
                                                         gint size,
                                                         GtkIconLookupFlags flags);

Looks up a named icon and returns a structure containing information such as the filename of the icon. The icon can then be rendered into a pixbuf using gtk_icon_info_load_icon(). (gtk_icon_theme_load_icon() combines these two steps if all you need is the pixbuf.)

icon_theme : | a GtkIconTheme
icon_name : | the name of the icon to lookup
size : | desired icon size
flags : | flags modifying the behavior of the icon lookup
Returns : | a GtkIconInfo structure containing information about the icon, or NULL if the icon wasn't found. Free with gtk_icon_info_free()

Since 2.4

gtk_icon_theme_load_icon ()

GdkPixbuf*          gtk_icon_theme_load_icon            (GtkIconTheme *icon_theme,
                                                         const gchar *icon_name,
                                                         gint size,
                                                         GtkIconLookupFlags flags,
                                                         GError **error);

Looks up an icon in an icon theme, scales it to the given size and renders it into a pixbuf. This is a convenience function; if more details about the icon are needed, use gtk_icon_theme_lookup_icon() followed by gtk_icon_info_load_icon().

Note that you probably want to listen for icon theme changes and update the icon. This is usually done by connecting to the GtkWidget::style-set signal. If for some reason you do not want to update the icon when the icon theme changes, you should consider using gdk_pixbuf_copy() to make a private copy of the pixbuf returned by this function. Otherwise GTK+ may need to keep the old icon theme loaded, which would be a waste of memory.

icon_theme : | a GtkIconTheme
icon_name : | the name of the icon to lookup
size : | the desired icon size. The resulting icon may not be exactly this size; see gtk_icon_info_load_icon().
flags : | flags modifying the behavior of the icon lookup
error : | Location to store error information on failure, or NULL.
Returns : | the rendered icon; this may be a newly created icon or a new reference to an internal icon, so you must not modify the icon. Use g_object_unref() to release your reference to the icon. NULL if the icon isn't found.

Since 2.4

gtk_icon_theme_list_icons ()

GList*              gtk_icon_theme_list_icons           (GtkIconTheme *icon_theme,
                                                         const gchar *context);

Lists the icons in the current icon theme. Only a subset of the icons can be listed by providing a context string. The set of values for the context string is system dependent, but will typically include such values as "Applications" and "MimeTypes".

icon_theme : | a GtkIconTheme
context : | a string identifying a particular type of icon, or NULL to list all icons.
Returns : | a GList list holding the names of all the icons in the theme. You must first free each element in the list with g_free(), then free the list itself with g_list_free().

Since 2.4

gtk_icon_theme_get_icon_sizes ()

gint*               gtk_icon_theme_get_icon_sizes       (GtkIconTheme *icon_theme,
                                                         const gchar *icon_name);

Returns an array of integers describing the sizes at which the icon is available without scaling. A size of -1 means that the icon is available in a scalable format. The array is zero-terminated.

icon_theme : | a GtkIconTheme
icon_name : | the name of an icon
Returns : | An newly allocated array describing the sizes at which the icon is available. The array should be freed with g_free() when it is no longer needed.

Since 2.6

gtk_icon_theme_get_example_icon_name ()

char*               gtk_icon_theme_get_example_icon_name
                                                        (GtkIconTheme *icon_theme);

Gets the name of an icon that is representative of the current theme (for instance, to use when presenting a list of themes to the user.)

icon_theme : | a GtkIconTheme
Returns : | the name of an example icon or NULL. Free with g_free().

Since 2.4

gtk_icon_theme_rescan_if_needed ()

gboolean            gtk_icon_theme_rescan_if_needed     (GtkIconTheme *icon_theme);

Checks to see if the icon theme has changed; if it has, any currently cached information is discarded and will be reloaded next time icon_theme is accessed.

icon_theme : | a GtkIconTheme
Returns : | TRUE if the icon theme has changed and needed to be reloaded.

Since 2.4

gtk_icon_theme_add_builtin_icon ()

void                gtk_icon_theme_add_builtin_icon     (const gchar *icon_name,
                                                         gint size,
                                                         GdkPixbuf *pixbuf);

Registers a built-in icon for icon theme lookups. The idea of built-in icons is to allow an application or library that uses themed icons to function requiring files to be present in the file system. For instance, the default images for all of GTK+'s stock icons are registered as built-icons.

In general, if you use gtk_icon_theme_add_builtin_icon() you should also install the icon in the icon theme, so that the icon is generally available.

This function will generally be used with pixbufs loaded via gdk_pixbuf_new_from_inline().

icon_name : | the name of the icon to register
size : | the size at which to register the icon (different images can be registered for the same icon name at different sizes.)
pixbuf : | GdkPixbuf that contains the image to use for icon_name.

Since 2.4

gtk_icon_info_copy ()

GtkIconInfo*        gtk_icon_info_copy                  (GtkIconInfo *icon_info);

Make a copy of a GtkIconInfo.

icon_info : | a GtkIconInfo
Returns : | the new GtkIconInfo

Since 2.4

gtk_icon_info_free ()

void                gtk_icon_info_free                  (GtkIconInfo *icon_info);

Free a GtkIconInfo and associated information

icon_info : a GtkIconInfo

Since 2.4

gtk_icon_info_get_base_size ()

gint                gtk_icon_info_get_base_size         (GtkIconInfo *icon_info);

Gets the base size for the icon. The base size is a size for the icon that was specified by the icon theme creator. This may be different than the actual size of image; an example of this is small emblem icons that can be attached to a larger icon. These icons will be given the same base size as the larger icons to which they are attached.

icon_info : | a GtkIconInfo
Returns : | the base size, or 0, if no base size is known for the icon.

Since 2.4

gtk_icon_info_get_filename ()

const gchar*        gtk_icon_info_get_filename          (GtkIconInfo *icon_info);

Gets the filename for the icon. If the GTK_ICON_LOOKUP_USE_BUILTIN flag was passed to gtk_icon_theme_lookup_icon(), there may be no filename if a builtin icon is returned; in this case, you should use gtk_icon_info_get_builtin_pixbuf().

icon_info : | a GtkIconInfo
Returns : | the filename for the icon, or NULL if gtk_icon_info_get_builtin_pixbuf() should be used instead. The return value is owned by GTK+ and should not be modified or freed.

Since 2.4

gtk_icon_info_get_builtin_pixbuf ()

GdkPixbuf*          gtk_icon_info_get_builtin_pixbuf    (GtkIconInfo *icon_info);

Gets the built-in image for this icon, if any. To allow GTK+ to use built in icon images, you must pass the GTK_ICON_LOOKUP_USE_BUILTIN to gtk_icon_theme_lookup_icon().

icon_info : | a GtkIconInfo structure
Returns : | the built-in image pixbuf, or NULL. No extra reference is added to the returned pixbuf, so if you want to keep it around, you must use g_object_ref(). The returned image must not be modified.

Since 2.4

gtk_icon_info_load_icon ()

GdkPixbuf*          gtk_icon_info_load_icon             (GtkIconInfo *icon_info,
                                                         GError **error);

Renders an icon previously looked up in an icon theme using gtk_icon_theme_lookup_icon(); the size will be based on the size passed to gtk_icon_theme_lookup_icon(). Note that the resulting pixbuf may not be exactly this size; an icon theme may have icons that differ slightly from their nominal sizes, and in addition GTK+ will avoid scaling icons that it considers sufficiently close to the requested size or for which the source image would have to be scaled up too far. (This maintains sharpness.)

icon_info : | a GtkIconInfo structure from gtk_icon_theme_lookup_icon()
error : | location to store error information on failure, or NULL.
Returns : | the rendered icon; this may be a newly created icon or a new reference to an internal icon, so you must not modify the icon. Use g_object_unref() to release your reference to the icon.

Since 2.4

gtk_icon_info_set_raw_coordinates ()

void                gtk_icon_info_set_raw_coordinates   (GtkIconInfo *icon_info,
                                                         gboolean raw_coordinates);

Sets whether the coordinates returned by gtk_icon_info_get_embedded_rect() and gtk_icon_info_get_attach_points() should be returned in their original form as specified in the icon theme, instead of scaled appropriately for the pixbuf returned by gtk_icon_info_load_icon().

Raw coordinates are somewhat strange; they are specified to be with respect to the unscaled pixmap for PNG and XPM icons, but for SVG icons, they are in a 1000x1000 coordinate space that is scaled to the final size of the icon. You can determine if the icon is an SVG icon by using gtk_icon_info_get_filename(), and seeing if it is non-NULL and ends in '.svg'.

This function is provided primarily to allow compatibility wrappers for older API's, and is not expected to be useful for applications.

icon_info : | a GtkIconInfo
raw_coordinates : | whether the coordinates of embedded rectangles and attached points should be returned in their original (unscaled) form.

Since 2.4

gtk_icon_info_get_embedded_rect ()

gboolean            gtk_icon_info_get_embedded_rect     (GtkIconInfo *icon_info,
                                                         GdkRectangle *rectangle);

Gets the coordinates of a rectangle within the icon that can be used for display of information such as a preview of the contents of a text file. See gtk_icon_info_set_raw_coordinates() for further information about the coordinate system.

icon_info : | a GtkIconInfo
rectangle : | GdkRectangle in which to store embedded rectangle coordinates; coordinates are only stored when this function returns TRUE.
Returns : | TRUE if the icon has an embedded rectangle

Since 2.4

gtk_icon_info_get_attach_points ()

gboolean            gtk_icon_info_get_attach_points     (GtkIconInfo *icon_info,
                                                         GdkPoint **points,
                                                         gint *n_points);

Fetches the set of attach points for an icon. An attach point is a location in the icon that can be used as anchor points for attaching emblems or overlays to the icon.

icon_info : | a GtkIconInfo
points : | location to store pointer to an array of points, or NULL free the array of points with g_free().
n_points : | location to store the number of points in points, or NULL
Returns : | TRUE if there are any attach points for the icon.

Since 2.4

gtk_icon_info_get_display_name ()

const gchar*        gtk_icon_info_get_display_name      (GtkIconInfo *icon_info);

Gets the display name for an icon. A display name is a string to be used in place of the icon name in a user visible context like a list of icons.

icon_info : | a GtkIconInfo
Returns : | the display name for the icon or NULL, if the icon doesn't have a specified display name. This value is owned icon_info and must not be modified or free.

Since 2.4

Signal Details

The "changed" signal

void                user_function                      (GtkIconTheme *icon_theme,
                                                        gpointer      user_data)       : Run Last

Emitted when the current icon theme is switched or GTK+ detects that a change has occurred in the contents of the current icon theme.

icon_theme : | the icon theme
user_data : | user data set when the signal handler was connected.


GtkIconView

GtkIconView — A widget which displays a list of icons in a grid

Synopsis

#include <gtk/gtk.h>

                    GtkIconView;
void                (*GtkIconViewForeachFunc)           (GtkIconView *icon_view,
                                                         GtkTreePath *path,
                                                         gpointer data);
GtkWidget*          gtk_icon_view_new                   (void);
GtkWidget*          gtk_icon_view_new_with_model        (GtkTreeModel *model);
void                gtk_icon_view_set_model             (GtkIconView *icon_view,
                                                         GtkTreeModel *model);
GtkTreeModel*       gtk_icon_view_get_model             (GtkIconView *icon_view);
void                gtk_icon_view_set_text_column       (GtkIconView *icon_view,
                                                         gint column);
gint                gtk_icon_view_get_text_column       (GtkIconView *icon_view);
void                gtk_icon_view_set_markup_column     (GtkIconView *icon_view,
                                                         gint column);
gint                gtk_icon_view_get_markup_column     (GtkIconView *icon_view);
void                gtk_icon_view_set_pixbuf_column     (GtkIconView *icon_view,
                                                         gint column);
gint                gtk_icon_view_get_pixbuf_column     (GtkIconView *icon_view);
GtkTreePath*        gtk_icon_view_get_path_at_pos       (GtkIconView *icon_view,
                                                         gint x,
                                                         gint y);
gboolean            gtk_icon_view_get_item_at_pos       (GtkIconView *icon_view,
                                                         gint x,
                                                         gint y,
                                                         GtkTreePath **path,
                                                         GtkCellRenderer **cell);
void                gtk_icon_view_set_cursor            (GtkIconView *icon_view,
                                                         GtkTreePath *path,
                                                         GtkCellRenderer *cell,
                                                         gboolean start_editing);
gboolean            gtk_icon_view_get_cursor            (GtkIconView *icon_view,
                                                         GtkTreePath **path,
                                                         GtkCellRenderer **cell);
void                gtk_icon_view_selected_foreach      (GtkIconView *icon_view,
                                                         GtkIconViewForeachFunc func,
                                                         gpointer data);
void                gtk_icon_view_set_selection_mode    (GtkIconView *icon_view,
                                                         GtkSelectionMode mode);
GtkSelectionMode    gtk_icon_view_get_selection_mode    (GtkIconView *icon_view);
void                gtk_icon_view_set_orientation       (GtkIconView *icon_view,
                                                         GtkOrientation orientation);
GtkOrientation      gtk_icon_view_get_orientation       (GtkIconView *icon_view);
void                gtk_icon_view_set_columns           (GtkIconView *icon_view,
                                                         gint columns);
gint                gtk_icon_view_get_columns           (GtkIconView *icon_view);
void                gtk_icon_view_set_item_width        (GtkIconView *icon_view,
                                                         gint item_width);
gint                gtk_icon_view_get_item_width        (GtkIconView *icon_view);
void                gtk_icon_view_set_spacing           (GtkIconView *icon_view,
                                                         gint spacing);
gint                gtk_icon_view_get_spacing           (GtkIconView *icon_view);
void                gtk_icon_view_set_row_spacing       (GtkIconView *icon_view,
                                                         gint row_spacing);
gint                gtk_icon_view_get_row_spacing       (GtkIconView *icon_view);
void                gtk_icon_view_set_column_spacing    (GtkIconView *icon_view,
                                                         gint column_spacing);
gint                gtk_icon_view_get_column_spacing    (GtkIconView *icon_view);
void                gtk_icon_view_set_margin            (GtkIconView *icon_view,
                                                         gint margin);
gint                gtk_icon_view_get_margin            (GtkIconView *icon_view);
void                gtk_icon_view_select_path           (GtkIconView *icon_view,
                                                         GtkTreePath *path);
void                gtk_icon_view_unselect_path         (GtkIconView *icon_view,
                                                         GtkTreePath *path);
gboolean            gtk_icon_view_path_is_selected      (GtkIconView *icon_view,
                                                         GtkTreePath *path);
GList*              gtk_icon_view_get_selected_items    (GtkIconView *icon_view);
void                gtk_icon_view_select_all            (GtkIconView *icon_view);
void                gtk_icon_view_unselect_all          (GtkIconView *icon_view);
void                gtk_icon_view_item_activated        (GtkIconView *icon_view,
                                                         GtkTreePath *path);
void                gtk_icon_view_scroll_to_path        (GtkIconView *icon_view,
                                                         GtkTreePath *path,
                                                         gboolean use_align,
                                                         gfloat row_align,
                                                         gfloat col_align);
gboolean            gtk_icon_view_get_visible_range     (GtkIconView *icon_view,
                                                         GtkTreePath **start_path,
                                                         GtkTreePath **end_path);

enum                GtkIconViewDropPosition;
void                gtk_icon_view_enable_model_drag_source
                                                        (GtkIconView *icon_view,
                                                         GdkModifierType start_button_mask,
                                                         const GtkTargetEntry *targets,
                                                         gint n_targets,
                                                         GdkDragAction actions);
void                gtk_icon_view_enable_model_drag_dest
                                                        (GtkIconView *icon_view,
                                                         const GtkTargetEntry *targets,
                                                         gint n_targets,
                                                         GdkDragAction actions);
void                gtk_icon_view_unset_model_drag_source
                                                        (GtkIconView *icon_view);
void                gtk_icon_view_unset_model_drag_dest (GtkIconView *icon_view);
void                gtk_icon_view_set_reorderable       (GtkIconView *icon_view,
                                                         gboolean reorderable);
gboolean            gtk_icon_view_get_reorderable       (GtkIconView *icon_view);
void                gtk_icon_view_set_drag_dest_item    (GtkIconView *icon_view,
                                                         GtkTreePath *path,
                                                         GtkIconViewDropPosition pos);
void                gtk_icon_view_get_drag_dest_item    (GtkIconView *icon_view,
                                                         GtkTreePath **path,
                                                         GtkIconViewDropPosition *pos);
gboolean            gtk_icon_view_get_dest_item_at_pos  (GtkIconView *icon_view,
                                                         gint drag_x,
                                                         gint drag_y,
                                                         GtkTreePath **path,
                                                         GtkIconViewDropPosition *pos);
GdkPixmap*          gtk_icon_view_create_drag_icon      (GtkIconView *icon_view,
                                                         GtkTreePath *path);

Object Hierarchy

  GObject
   +----GInitiallyUnowned
         +----GtkObject
               +----GtkWidget
                     +----GtkContainer
                           +----GtkIconView

Implemented Interfaces

GtkIconView implements AtkImplementorIface and GtkCellLayout.

Properties

  "column-spacing"           gint                  : Read / Write
  "columns"                  gint                  : Read / Write
  "item-width"               gint                  : Read / Write
  "margin"                   gint                  : Read / Write
  "markup-column"            gint                  : Read / Write
  "model"                    GtkTreeModel          : Read / Write
  "orientation"              GtkOrientation        : Read / Write
  "pixbuf-column"            gint                  : Read / Write
  "reorderable"              gboolean              : Read / Write
  "row-spacing"              gint                  : Read / Write
  "selection-mode"           GtkSelectionMode      : Read / Write
  "spacing"                  gint                  : Read / Write
  "text-column"              gint                  : Read / Write

Style Properties

  "selection-box-alpha"      guchar                : Read
  "selection-box-color"      GdkColor              : Read

Signals

  "activate-cursor-item"                           : Run Last / Action
  "item-activated"                                 : Run Last
  "move-cursor"                                    : Run Last / Action
  "select-all"                                     : Run Last / Action
  "select-cursor-item"                             : Run Last / Action
  "selection-changed"                              : Run First
  "set-scroll-adjustments"                         : Run Last
  "toggle-cursor-item"                             : Run Last / Action
  "unselect-all"                                   : Run Last / Action

Description

GtkIconView provides an alternative view on a list model. It displays the model as a grid of icons with labels. Like GtkTreeView, it allows to select one or multiple items (depending on the selection mode, see gtk_icon_view_set_selection_mode()). In addition to selection with the arrow keys, GtkIconView supports rubberband selection, which is controlled by dragging the pointer.

Details

GtkIconView

typedef struct _GtkIconView GtkIconView;

The GtkIconView struct contains only private fields and should not be directly accessed.

GtkIconViewForeachFunc ()

void                (*GtkIconViewForeachFunc)           (GtkIconView *icon_view,
                                                         GtkTreePath *path,
                                                         gpointer data);

A function used by gtk_icon_view_selected_foreach() to map all selected rows. It will be called on every selected row in the view.

icon_view : | a GtkIconView
path : | The GtkTreePath of a selected row
data : | user data

gtk_icon_view_new ()

GtkWidget*          gtk_icon_view_new                   (void);

Creates a new GtkIconView widget

Returns : A newly created GtkIconView widget

Since 2.6

gtk_icon_view_new_with_model ()

GtkWidget*          gtk_icon_view_new_with_model        (GtkTreeModel *model);

Creates a new GtkIconView widget with the model model.

model : | The model.
Returns : | A newly created GtkIconView widget.

Since 2.6

gtk_icon_view_set_model ()

void                gtk_icon_view_set_model             (GtkIconView *icon_view,
                                                         GtkTreeModel *model);

Sets the model for a GtkIconView. If the icon_view already has a model set, it will remove it before setting the new model. If model is NULL, then it will unset the old model.

icon_view : | A GtkIconView.
model : | The model.

Since 2.6

gtk_icon_view_get_model ()

GtkTreeModel*       gtk_icon_view_get_model             (GtkIconView *icon_view);

Returns the model the GtkIconView is based on. Returns NULL if the model is unset.

icon_view : | a GtkIconView
Returns : | A GtkTreeModel, or NULL if none is currently being used.

Since 2.6

gtk_icon_view_set_text_column ()

void                gtk_icon_view_set_text_column       (GtkIconView *icon_view,
                                                         gint column);

Sets the column with text for icon_view to be column. The text column must be of type G_TYPE_STRING.

icon_view : | A GtkIconView.
column : | A column in the currently used model.

Since 2.6

gtk_icon_view_get_text_column ()

gint                gtk_icon_view_get_text_column       (GtkIconView *icon_view);

Returns the column with text for icon_view.

icon_view : | A GtkIconView.
Returns : | the text column, or -1 if it's unset.

Since 2.6

gtk_icon_view_set_markup_column ()

void                gtk_icon_view_set_markup_column     (GtkIconView *icon_view,
                                                         gint column);

Sets the column with markup information for icon_view to be column. The markup column must be of type G_TYPE_STRING. If the markup column is set to something, it overrides the text column set by gtk_icon_view_set_text_column().

icon_view : | A GtkIconView.
column : | A column in the currently used model.

Since 2.6

gtk_icon_view_get_markup_column ()

gint                gtk_icon_view_get_markup_column     (GtkIconView *icon_view);

Returns the column with markup text for icon_view.

icon_view : | A GtkIconView.
Returns : | the markup column, or -1 if it's unset.

Since 2.6

gtk_icon_view_set_pixbuf_column ()

void                gtk_icon_view_set_pixbuf_column     (GtkIconView *icon_view,
                                                         gint column);

Sets the column with pixbufs for icon_view to be column. The pixbuf column must be of type GDK_TYPE_PIXBUF

icon_view : | A GtkIconView.
column : | A column in the currently used model.

Since 2.6

gtk_icon_view_get_pixbuf_column ()

gint                gtk_icon_view_get_pixbuf_column     (GtkIconView *icon_view);

Returns the column with pixbufs for icon_view.

icon_view : | A GtkIconView.
Returns : | the pixbuf column, or -1 if it's unset.

Since 2.6

gtk_icon_view_get_path_at_pos ()

GtkTreePath*        gtk_icon_view_get_path_at_pos       (GtkIconView *icon_view,
                                                         gint x,
                                                         gint y);

Finds the path at the point (x, y), relative to widget coordinates. See gtk_icon_view_get_item_at_pos(), if you are also interested in the cell at the specified position.

icon_view : | A GtkIconView.
x : | The x position to be identified
y : | The y position to be identified
Returns : | The GtkTreePath corresponding to the icon or NULL if no icon exists at that position.

Since 2.6

gtk_icon_view_get_item_at_pos ()

gboolean            gtk_icon_view_get_item_at_pos       (GtkIconView *icon_view,
                                                         gint x,
                                                         gint y,
                                                         GtkTreePath **path,
                                                         GtkCellRenderer **cell);

Finds the path at the point (x, y), relative to widget coordinates. In contrast to gtk_icon_view_get_path_at_pos(), this function also obtains the cell at the specified position. The returned path should be freed with gtk_tree_path_free().

icon_view : | A GtkIconView.
x : | The x position to be identified
y : | The y position to be identified
path : | Return location for the path, or NULL
cell : | Return location for the renderer responsible for the cell at (x, y), or NULL
Returns : | TRUE if an item exists at the specified position

Since 2.8

gtk_icon_view_set_cursor ()

void                gtk_icon_view_set_cursor            (GtkIconView *icon_view,
                                                         GtkTreePath *path,
                                                         GtkCellRenderer *cell,
                                                         gboolean start_editing);

Sets the current keyboard focus to be at path, and selects it. This is useful when you want to focus the user's attention on a particular item. If cell is not NULL, then focus is given to the cell specified by it. Additionally, if start_editing is TRUE, then editing should be started in the specified cell.

This function is often followed by gtk_widget_grab_focus (icon_view) in order to give keyboard focus to the widget. Please note that editing can only happen when the widget is realized.

icon_view : | A GtkIconView
path : | A GtkTreePath
cell : | One of the cell renderers of icon_view, or NULL
start_editing : | TRUE if the specified cell should start being edited.

Since 2.8

gtk_icon_view_get_cursor ()

gboolean            gtk_icon_view_get_cursor            (GtkIconView *icon_view,
                                                         GtkTreePath **path,
                                                         GtkCellRenderer **cell);

Fills in path and cell with the current cursor path and cell. If the cursor isn't currently set, then *path will be NULL. If no cell currently has focus, then *cell will be NULL.

The returned GtkTreePath must be freed with gtk_tree_path_free().

icon_view : | A GtkIconView
path : | Return location for the current cursor path, or NULL
cell : | Return location the current focus cell, or NULL
Returns : | TRUE if the cursor is set.

Since 2.8

gtk_icon_view_selected_foreach ()

void                gtk_icon_view_selected_foreach      (GtkIconView *icon_view,
                                                         GtkIconViewForeachFunc func,
                                                         gpointer data);

Calls a function for each selected icon. Note that the model or selection cannot be modified from within this function.

icon_view : | A GtkIconView.
func : | The funcion to call for each selected icon.
data : | User data to pass to the function.

Since 2.6

gtk_icon_view_set_selection_mode ()

void                gtk_icon_view_set_selection_mode    (GtkIconView *icon_view,
                                                         GtkSelectionMode mode);

Sets the selection mode of the icon_view.

icon_view : | A GtkIconView.
mode : | The selection mode

Since 2.6

gtk_icon_view_get_selection_mode ()

GtkSelectionMode    gtk_icon_view_get_selection_mode    (GtkIconView *icon_view);

Gets the selection mode of the icon_view.

icon_view : | A GtkIconView.
Returns : | the current selection mode

Since 2.6

gtk_icon_view_set_orientation ()

void                gtk_icon_view_set_orientation       (GtkIconView *icon_view,
                                                         GtkOrientation orientation);

Sets the ::orientation property which determines whether the labels are drawn beside the icons instead of below.

icon_view : | a GtkIconView
orientation : | the relative position of texts and icons

Since 2.6

gtk_icon_view_get_orientation ()

GtkOrientation      gtk_icon_view_get_orientation       (GtkIconView *icon_view);

Returns the value of the ::orientation property which determines whether the labels are drawn beside the icons instead of below.

icon_view : | a GtkIconView
Returns : | the relative position of texts and icons

Since 2.6

gtk_icon_view_set_columns ()

void                gtk_icon_view_set_columns           (GtkIconView *icon_view,
                                                         gint columns);

Sets the ::columns property which determines in how many columns the icons are arranged. If columns is -1, the number of columns will be chosen automatically to fill the available area.

icon_view : | a GtkIconView
columns : | the number of columns

Since 2.6

gtk_icon_view_get_columns ()

gint                gtk_icon_view_get_columns           (GtkIconView *icon_view);

Returns the value of the ::columns property.

icon_view : | a GtkIconView
Returns : | the number of columns, or -1

Since 2.6

gtk_icon_view_set_item_width ()

void                gtk_icon_view_set_item_width        (GtkIconView *icon_view,
                                                         gint item_width);

Sets the ::item-width property which specifies the width to use for each item. If it is set to -1, the icon view will automatically determine a suitable item size.

icon_view : | a GtkIconView
item_width : | the width for each item

Since 2.6

gtk_icon_view_get_item_width ()

gint                gtk_icon_view_get_item_width        (GtkIconView *icon_view);

Returns the value of the ::item-width property.

icon_view : | a GtkIconView
Returns : | the width of a single item, or -1

Since 2.6

gtk_icon_view_set_spacing ()

void                gtk_icon_view_set_spacing           (GtkIconView *icon_view,
                                                         gint spacing);

Sets the ::spacing property which specifies the space which is inserted between the cells (i.e. the icon and the text) of an item.

icon_view : | a GtkIconView
spacing : | the spacing

Since 2.6

gtk_icon_view_get_spacing ()

gint                gtk_icon_view_get_spacing           (GtkIconView *icon_view);

Returns the value of the ::spacing property.

icon_view : | a GtkIconView
Returns : | the space between cells

Since 2.6

gtk_icon_view_set_row_spacing ()

void                gtk_icon_view_set_row_spacing       (GtkIconView *icon_view,
                                                         gint row_spacing);

Sets the ::row-spacing property which specifies the space which is inserted between the rows of the icon view.

icon_view : | a GtkIconView
row_spacing : | the row spacing

Since 2.6

gtk_icon_view_get_row_spacing ()

gint                gtk_icon_view_get_row_spacing       (GtkIconView *icon_view);

Returns the value of the ::row-spacing property.

icon_view : | a GtkIconView
Returns : | the space between rows

Since 2.6

gtk_icon_view_set_column_spacing ()

void                gtk_icon_view_set_column_spacing    (GtkIconView *icon_view,
                                                         gint column_spacing);

Sets the ::column-spacing property which specifies the space which is inserted between the columns of the icon view.

icon_view : | a GtkIconView
column_spacing : | the column spacing

Since 2.6

gtk_icon_view_get_column_spacing ()

gint                gtk_icon_view_get_column_spacing    (GtkIconView *icon_view);

Returns the value of the ::column-spacing property.

icon_view : | a GtkIconView
Returns : | the space between columns

Since 2.6

gtk_icon_view_set_margin ()

void                gtk_icon_view_set_margin            (GtkIconView *icon_view,
                                                         gint margin);

Sets the ::margin property which specifies the space which is inserted at the top, bottom, left and right of the icon view.

icon_view : | a GtkIconView
margin : | the margin

Since 2.6

gtk_icon_view_get_margin ()

gint                gtk_icon_view_get_margin            (GtkIconView *icon_view);

Returns the value of the ::margin property.

icon_view : | a GtkIconView
Returns : | the space at the borders

Since 2.6

gtk_icon_view_select_path ()

void                gtk_icon_view_select_path           (GtkIconView *icon_view,
                                                         GtkTreePath *path);

Selects the row at path.

icon_view : | A GtkIconView.
path : | The GtkTreePath to be selected.

Since 2.6

gtk_icon_view_unselect_path ()

void                gtk_icon_view_unselect_path         (GtkIconView *icon_view,
                                                         GtkTreePath *path);

Unselects the row at path.

icon_view : | A GtkIconView.
path : | The GtkTreePath to be unselected.

Since 2.6

gtk_icon_view_path_is_selected ()

gboolean            gtk_icon_view_path_is_selected      (GtkIconView *icon_view,
                                                         GtkTreePath *path);

Returns TRUE if the icon pointed to by path is currently selected. If icon does not point to a valid location, FALSE is returned.

icon_view : | A GtkIconView.
path : | A GtkTreePath to check selection on.
Returns : | TRUE if path is selected.

Since 2.6

gtk_icon_view_get_selected_items ()

GList*              gtk_icon_view_get_selected_items    (GtkIconView *icon_view);

Creates a list of paths of all selected items. Additionally, if you are planning on modifying the model after calling this function, you may want to convert the returned list into a list of GtkTreeRowReferences. To do this, you can use gtk_tree_row_reference_new().

To free the return value, use:

g_list_foreach (list, gtk_tree_path_free, NULL);
g_list_free (list);

icon_view : | A GtkIconView.
Returns : | A GList containing a GtkTreePath for each selected row.

Since 2.6

gtk_icon_view_select_all ()

void                gtk_icon_view_select_all            (GtkIconView *icon_view);

Selects all the icons. icon_view must has its selection mode set to GTK_SELECTION_MULTIPLE.

icon_view : A GtkIconView.

Since 2.6

gtk_icon_view_unselect_all ()

void                gtk_icon_view_unselect_all          (GtkIconView *icon_view);

Unselects all the icons.

icon_view : A GtkIconView.

Since 2.6

gtk_icon_view_item_activated ()

void                gtk_icon_view_item_activated        (GtkIconView *icon_view,
                                                         GtkTreePath *path);

Activates the item determined by path.

icon_view : | A GtkIconView
path : | The GtkTreePath to be activated

Since 2.6

gtk_icon_view_scroll_to_path ()

void                gtk_icon_view_scroll_to_path        (GtkIconView *icon_view,
                                                         GtkTreePath *path,
                                                         gboolean use_align,
                                                         gfloat row_align,
                                                         gfloat col_align);

Moves the alignments of icon_view to the position specified by path. row_align determines where the row is placed, and col_align determines where column is placed. Both are expected to be between 0.0 and 1.0. 0.0 means left/top alignment, 1.0 means right/bottom alignment, 0.5 means center.

If use_align is FALSE, then the alignment arguments are ignored, and the tree does the minimum amount of work to scroll the item onto the screen. This means that the item will be scrolled to the edge closest to its current position. If the item is currently visible on the screen, nothing is done.

This function only works if the model is set, and path is a valid row on the model. If the model changes before the icon_view is realized, the centered path will be modified to reflect this change.

icon_view : | A GtkIconView.
path : | The path of the item to move to.
use_align : | whether to use alignment arguments, or FALSE.
row_align : | The vertical alignment of the item specified by path.
col_align : | The horizontal alignment of the item specified by path.

Since 2.8

gtk_icon_view_get_visible_range ()

gboolean            gtk_icon_view_get_visible_range     (GtkIconView *icon_view,
                                                         GtkTreePath **start_path,
                                                         GtkTreePath **end_path);

Sets start_path and end_path to be the first and last visible path. Note that there may be invisible paths in between.

Both paths should be freed with gtk_tree_path_free() after use.

icon_view : | A GtkIconView
start_path : | Return location for start of region, or NULL
end_path : | Return location for end of region, or NULL
Returns : | TRUE, if valid paths were placed in start_path and end_path

Since 2.8

enum GtkIconViewDropPosition

typedef enum
{
  GTK_ICON_VIEW_NO_DROP,
  GTK_ICON_VIEW_DROP_INTO,
  GTK_ICON_VIEW_DROP_LEFT,
  GTK_ICON_VIEW_DROP_RIGHT,
  GTK_ICON_VIEW_DROP_ABOVE,
  GTK_ICON_VIEW_DROP_BELOW
} GtkIconViewDropPosition;

An enum for determining where a dropped item goes.

GTK_ICON_VIEW_NO_DROP | no drop possible
GTK_ICON_VIEW_DROP_INTO | dropped item replaces the item
GTK_ICON_VIEW_DROP_LEFT | droppped item is inserted to the left
GTK_ICON_VIEW_DROP_RIGHT | dropped item is inserted to the right
GTK_ICON_VIEW_DROP_ABOVE | dropped item is inserted above
GTK_ICON_VIEW_DROP_BELOW | dropped item is inserted below

gtk_icon_view_enable_model_drag_source ()

void                gtk_icon_view_enable_model_drag_source
                                                        (GtkIconView *icon_view,
                                                         GdkModifierType start_button_mask,
                                                         const GtkTargetEntry *targets,
                                                         gint n_targets,
                                                         GdkDragAction actions);

Turns icon_view into a drag source for automatic DND.

icon_view : | a GtkIconTreeView
start_button_mask : | Mask of allowed buttons to start drag
targets : | the table of targets that the drag will support
n_targets : | the number of items in targets
actions : | the bitmask of possible actions for a drag from this widget

Since 2.8

gtk_icon_view_enable_model_drag_dest ()

void                gtk_icon_view_enable_model_drag_dest
                                                        (GtkIconView *icon_view,
                                                         const GtkTargetEntry *targets,
                                                         gint n_targets,
                                                         GdkDragAction actions);

Turns icon_view into a drop destination for automatic DND.

icon_view : | a GtkIconView
targets : | the table of targets that the drag will support
n_targets : | the number of items in targets
actions : | the bitmask of possible actions for a drag to this widget

Since 2.8

gtk_icon_view_unset_model_drag_source ()

void                gtk_icon_view_unset_model_drag_source
                                                        (GtkIconView *icon_view);

Undoes the effect of gtk_icon_view_enable_model_drag_source().

icon_view : a GtkIconView

Since 2.8

gtk_icon_view_unset_model_drag_dest ()

void                gtk_icon_view_unset_model_drag_dest (GtkIconView *icon_view);

Undoes the effect of gtk_icon_view_enable_model_drag_dest().

icon_view : a GtkIconView

Since 2.8

gtk_icon_view_set_reorderable ()

void                gtk_icon_view_set_reorderable       (GtkIconView *icon_view,
                                                         gboolean reorderable);

This function is a convenience function to allow you to reorder models that support the GtkTreeDragSourceIface and the GtkTreeDragDestIface. Both GtkTreeStore and GtkListStore support these. If reorderable is TRUE, then the user can reorder the model by dragging and dropping rows. The developer can listen to these changes by connecting to the model's row_inserted and row_deleted signals.

This function does not give you any degree of control over the order -- any reordering is allowed. If more control is needed, you should probably handle drag and drop manually.

icon_view : | A GtkIconView.
reorderable : | TRUE, if the list of items can be reordered.

Since 2.8

gtk_icon_view_get_reorderable ()

gboolean            gtk_icon_view_get_reorderable       (GtkIconView *icon_view);

Retrieves whether the user can reorder the list via drag-and-drop. See gtk_icon_view_set_reorderable().

icon_view : | a GtkIconView
Returns : | TRUE if the list can be reordered.

Since 2.8

gtk_icon_view_set_drag_dest_item ()

void                gtk_icon_view_set_drag_dest_item    (GtkIconView *icon_view,
                                                         GtkTreePath *path,
                                                         GtkIconViewDropPosition pos);

Sets the item that is highlighted for feedback.

icon_view : | a GtkIconView
path : | The path of the item to highlight, or NULL.
pos : | Specifies where to drop, relative to the item

Since 2.8

gtk_icon_view_get_drag_dest_item ()

void                gtk_icon_view_get_drag_dest_item    (GtkIconView *icon_view,
                                                         GtkTreePath **path,
                                                         GtkIconViewDropPosition *pos);

Gets information about the item that is highlighted for feedback.

icon_view : | a GtkIconView
path : | Return location for the path of the highlighted item, or NULL.
pos : | Return location for the drop position, or NULL

Since 2.8

gtk_icon_view_get_dest_item_at_pos ()

gboolean            gtk_icon_view_get_dest_item_at_pos  (GtkIconView *icon_view,
                                                         gint drag_x,
                                                         gint drag_y,
                                                         GtkTreePath **path,
                                                         GtkIconViewDropPosition *pos);

Determines the destination item for a given position.

icon_view : | a GtkIconView
drag_x : | the position to determine the destination item for
drag_y : | the position to determine the destination item for
path : | Return location for the path of the item, or NULL.
pos : | Return location for the drop position, or NULL
Returns : | whether there is an item at the given position.

Since 2.8

gtk_icon_view_create_drag_icon ()

GdkPixmap*          gtk_icon_view_create_drag_icon      (GtkIconView *icon_view,
                                                         GtkTreePath *path);

Creates a GdkPixmap representation of the item at path. This image is used for a drag icon.

icon_view : | a GtkIconView
path : | a GtkTreePath in icon_view
Returns : | a newly-allocated pixmap of the drag icon.

Since 2.8

Property Details

The "column-spacing" property

  "column-spacing"           gint                  : Read / Write

The column-spacing property specifies the space which is inserted between the columns of the icon view.

Allowed values: >= 0

Default value: 6

Since 2.6

The "columns" property

  "columns"                  gint                  : Read / Write

The columns property contains the number of the columns in which the items should be displayed. If it is -1, the number of columns will be chosen automatically to fill the available area.

Allowed values: >= -1

Default value: -1

Since 2.6

The "item-width" property

  "item-width"               gint                  : Read / Write

The item-width property specifies the width to use for each item. If it is set to -1, the icon view will automatically determine a suitable item size.

Allowed values: >= -1

Default value: -1

Since 2.6

The "margin" property

  "margin"                   gint                  : Read / Write

The margin property specifies the space which is inserted at the edges of the icon view.

Allowed values: >= 0

Default value: 6

Since 2.6

The "markup-column" property

  "markup-column"            gint                  : Read / Write

The ::markup-column property contains the number of the model column containing markup information to be displayed. The markup column must be of type G_TYPE_STRING. If this property and the :text-column property are both set to column numbers, it overrides the text column. If both are set to -1, no texts are displayed.

Allowed values: >= -1

Default value: -1

Since 2.6

The "model" property

  "model"                    GtkTreeModel          : Read / Write

The model for the icon view.

The "orientation" property

  "orientation"              GtkOrientation        : Read / Write

The orientation property specifies how the cells (i.e. the icon and the text) of the item are positioned relative to each other.

Default value: GTK_ORIENTATION_VERTICAL

Since 2.6

The "pixbuf-column" property

  "pixbuf-column"            gint                  : Read / Write

The ::pixbuf-column property contains the number of the model column containing the pixbufs which are displayed. The pixbuf column must be of type GDK_TYPE_PIXBUF. Setting this property to -1 turns off the display of pixbufs.

Allowed values: >= -1

Default value: -1

Since 2.6

The "reorderable" property

  "reorderable"              gboolean              : Read / Write

The reorderable property specifies if the items can be reordered by DND.

Default value: FALSE

Since 2.8

The "row-spacing" property

  "row-spacing"              gint                  : Read / Write

The row-spacing property specifies the space which is inserted between the rows of the icon view.

Allowed values: >= 0

Default value: 6

Since 2.6

The "selection-mode" property

  "selection-mode"           GtkSelectionMode      : Read / Write

The ::selection-mode property specifies the selection mode of icon view. If the mode is GTK_SELECTION_MULTIPLE, rubberband selection is enabled, for the other modes, only keyboard selection is possible.

Default value: GTK_SELECTION_SINGLE

Since 2.6

The "spacing" property

  "spacing"                  gint                  : Read / Write

The spacing property specifies the space which is inserted between the cells (i.e. the icon and the text) of an item.

Allowed values: >= 0

Default value: 0

Since 2.6

The "text-column" property

  "text-column"              gint                  : Read / Write

The ::text-column property contains the number of the model column containing the texts which are displayed. The text column must be of type G_TYPE_STRING. If this property and the :markup-column property are both set to -1, no texts are displayed.

Allowed values: >= -1

Default value: -1

Since 2.6

Style Property Details

The "selection-box-alpha" style property

  "selection-box-alpha"      guchar                : Read

Opacity of the selection box.

Default value: 64

The "selection-box-color" style property

  "selection-box-color"      GdkColor              : Read

Color of the selection box.

Signal Details

The "activate-cursor-item" signal

gboolean            user_function                      (GtkIconView *iconview,
                                                        gpointer     user_data)      : Run Last / Action

iconview : | the object which received the signal.
user_data : | user data set when the signal handler was connected.
Returns : |

The "item-activated" signal

void                user_function                      (GtkIconView *iconview,
                                                        GtkTreePath *arg1,
                                                        gpointer     user_data)      : Run Last

iconview : | the object which received the signal.
arg1 : |
user_data : | user data set when the signal handler was connected.

The "move-cursor" signal

gboolean            user_function                      (GtkIconView    *iconview,
                                                        GtkMovementStep arg1,
                                                        gint            arg2,
                                                        gpointer        user_data)      : Run Last / Action

iconview : | the object which received the signal.
arg1 : |
arg2 : |
user_data : | user data set when the signal handler was connected.
Returns : |

The "select-all" signal

void                user_function                      (GtkIconView *iconview,
                                                        gpointer     user_data)      : Run Last / Action

iconview : | the object which received the signal.
user_data : | user data set when the signal handler was connected.

The "select-cursor-item" signal

void                user_function                      (GtkIconView *iconview,
                                                        gpointer     user_data)      : Run Last / Action

iconview : | the object which received the signal.
user_data : | user data set when the signal handler was connected.

The "selection-changed" signal

void                user_function                      (GtkIconView *iconview,
                                                        gpointer     user_data)      : Run First

iconview : | the object which received the signal.
user_data : | user data set when the signal handler was connected.

The "set-scroll-adjustments" signal

void                user_function                      (GtkIconView   *iconview,
                                                        GtkAdjustment *arg1,
                                                        GtkAdjustment *arg2,
                                                        gpointer       user_data)      : Run Last

iconview : | the object which received the signal.
arg1 : |
arg2 : |
user_data : | user data set when the signal handler was connected.

The "toggle-cursor-item" signal

void                user_function                      (GtkIconView *iconview,
                                                        gpointer     user_data)      : Run Last / Action

iconview : | the object which received the signal.
user_data : | user data set when the signal handler was connected.

The "unselect-all" signal

void                user_function                      (GtkIconView *iconview,
                                                        gpointer     user_data)      : Run Last / Action

iconview : | the object which received the signal.
user_data : | user data set when the signal handler was connected.


GtkImage

GtkImage — A widget displaying an image

Synopsis

#include <gtk/gtk.h>

                    GtkImage;
enum                GtkImageType;
void                gtk_image_get_icon_set              (GtkImage *image,
                                                         GtkIconSet **icon_set,
                                                         GtkIconSize *size);
void                gtk_image_get_image                 (GtkImage *image,
                                                         GdkImage **gdk_image,
                                                         GdkBitmap **mask);
GdkPixbuf*          gtk_image_get_pixbuf                (GtkImage *image);
void                gtk_image_get_pixmap                (GtkImage *image,
                                                         GdkPixmap **pixmap,
                                                         GdkBitmap **mask);
void                gtk_image_get_stock                 (GtkImage *image,
                                                         gchar **stock_id,
                                                         GtkIconSize *size);
GdkPixbufAnimation* gtk_image_get_animation             (GtkImage *image);
void                gtk_image_get_icon_name             (GtkImage *image,
                                                         G_CONST_RETURN gchar **icon_name,
                                                         GtkIconSize *size);
GtkImageType        gtk_image_get_storage_type          (GtkImage *image);
GtkWidget*          gtk_image_new_from_file             (const gchar *filename);
GtkWidget*          gtk_image_new_from_icon_set         (GtkIconSet *icon_set,
                                                         GtkIconSize size);
GtkWidget*          gtk_image_new_from_image            (GdkImage *image,
                                                         GdkBitmap *mask);
GtkWidget*          gtk_image_new_from_pixbuf           (GdkPixbuf *pixbuf);
GtkWidget*          gtk_image_new_from_pixmap           (GdkPixmap *pixmap,
                                                         GdkBitmap *mask);
GtkWidget*          gtk_image_new_from_stock            (const gchar *stock_id,
                                                         GtkIconSize size);
GtkWidget*          gtk_image_new_from_animation        (GdkPixbufAnimation *animation);
GtkWidget*          gtk_image_new_from_icon_name        (const gchar *icon_name,
                                                         GtkIconSize size);
void                gtk_image_set_from_file             (GtkImage *image,
                                                         const gchar *filename);
void                gtk_image_set_from_icon_set         (GtkImage *image,
                                                         GtkIconSet *icon_set,
                                                         GtkIconSize size);
void                gtk_image_set_from_image            (GtkImage *image,
                                                         GdkImage *gdk_image,
                                                         GdkBitmap *mask);
void                gtk_image_set_from_pixbuf           (GtkImage *image,
                                                         GdkPixbuf *pixbuf);
void                gtk_image_set_from_pixmap           (GtkImage *image,
                                                         GdkPixmap *pixmap,
                                                         GdkBitmap *mask);
void                gtk_image_set_from_stock            (GtkImage *image,
                                                         const gchar *stock_id,
                                                         GtkIconSize size);
void                gtk_image_set_from_animation        (GtkImage *image,
                                                         GdkPixbufAnimation *animation);
void                gtk_image_set_from_icon_name        (GtkImage *image,
                                                         const gchar *icon_name,
                                                         GtkIconSize size);
void                gtk_image_clear                     (GtkImage *image);
GtkWidget*          gtk_image_new                       (void);
void                gtk_image_set                       (GtkImage *image,
                                                         GdkImage *val,
                                                         GdkBitmap *mask);
void                gtk_image_get                       (GtkImage *image,
                                                         GdkImage **val,
                                                         GdkBitmap **mask);
void                gtk_image_set_pixel_size            (GtkImage *image,
                                                         gint pixel_size);
gint                gtk_image_get_pixel_size            (GtkImage *image);

Object Hierarchy

  GObject
   +----GInitiallyUnowned
         +----GtkObject
               +----GtkWidget
                     +----GtkMisc
                           +----GtkImage

Implemented Interfaces

GtkImage implements AtkImplementorIface.

Properties

  "file"                     gchararray            : Read / Write
  "icon-name"                gchararray            : Read / Write
  "icon-set"                 GtkIconSet            : Read / Write
  "icon-size"                gint                  : Read / Write
  "image"                    GdkImage              : Read / Write
  "mask"                     GdkPixmap             : Read / Write
  "pixbuf"                   GdkPixbuf             : Read / Write
  "pixbuf-animation"         GdkPixbufAnimation    : Read / Write
  "pixel-size"               gint                  : Read / Write
  "pixmap"                   GdkPixmap             : Read / Write
  "stock"                    gchararray            : Read / Write
  "storage-type"             GtkImageType          : Read

Description

The GtkImage widget displays an image. Various kinds of object can be displayed as an image; most typically, you would load a GdkPixbuf ("pixel buffer") from a file, and then display that. There's a convenience function to do this, gtk_image_new_from_file(), used as follows:

  GtkWidget *image;
  image = gtk_image_new_from_file ("myfile.png");

If the file isn't loaded successfully, the image will contain a "broken image" icon similar to that used in many web browsers. If you want to handle errors in loading the file yourself, for example by displaying an error message, then load the image with gdk_pixbuf_new_from_file(), then create the GtkImage with gtk_image_new_from_pixbuf().

The image file may contain an animation, if so the GtkImage will display an animation (GdkPixbufAnimation) instead of a static image.

GtkImage is a subclass of GtkMisc, which implies that you can align it (center, left, right) and add padding to it, using GtkMisc methods.

GtkImage is a "no window" widget (has no GdkWindow of its own), so by default does not receive events. If you want to receive events on the image, such as button clicks, place the image inside a GtkEventBox, then connect to the event signals on the event box.

Example 8. Handling button press events on a GtkImage.

  static gboolean
  button_press_callback (GtkWidget      *event_box,
                         GdkEventButton *event,
                         gpointer        data)
  {
    g_print ("Event box clicked at coordinates %f,%f\n",
             event->x, event->y);

    /* Returning TRUE means we handled the event, so the signal
     * emission should be stopped (don't call any further
     * callbacks that may be connected). Return FALSE
     * to continue invoking callbacks.
     */
    return TRUE;
  }

  static GtkWidget*
  create_image (void)
  {
    GtkWidget *image;
    GtkWidget *event_box;

    image = gtk_image_new_from_file ("myfile.png");

    event_box = gtk_event_box_new ();

    gtk_container_add (GTK_CONTAINER (event_box), image);

    g_signal_connect (G_OBJECT (event_box),
                      "button_press_event",
                      G_CALLBACK (button_press_callback),
                      image);

    return image;
  }

When handling events on the event box, keep in mind that coordinates in the image may be different from event box coordinates due to the alignment and padding settings on the image (see GtkMisc). The simplest way to solve this is to set the alignment to 0.0 (left/top), and set the padding to zero. Then the origin of the image will be the same as the origin of the event box.

Sometimes an application will want to avoid depending on external data files, such as image files. GTK+ comes with a program to avoid this, called gdk-pixbuf-csource. This program allows you to convert an image into a C variable declaration, which can then be loaded into a GdkPixbuf using gdk_pixbuf_new_from_inline().

Details

GtkImage

typedef struct _GtkImage GtkImage;

This struct contain private data only and should be accessed by the functions below.

enum GtkImageType

typedef enum
{
  GTK_IMAGE_EMPTY,
  GTK_IMAGE_PIXMAP,
  GTK_IMAGE_IMAGE,
  GTK_IMAGE_PIXBUF,
  GTK_IMAGE_STOCK,
  GTK_IMAGE_ICON_SET,
  GTK_IMAGE_ANIMATION,
  GTK_IMAGE_ICON_NAME
} GtkImageType;

Describes the image data representation used by a GtkImage. If you want to get the image from the widget, you can only get the currently-stored representation. e.g. if the gtk_image_get_storage_type() returns GTK_IMAGE_PIXBUF, then you can call gtk_image_get_pixbuf() but not gtk_image_get_stock(). For empty images, you can request any storage type (call any of the "get" functions), but they will all return NULL values.

GTK_IMAGE_EMPTY | there is no image displayed by the widget
GTK_IMAGE_PIXMAP | the widget contains a GdkPixmap
GTK_IMAGE_IMAGE | the widget contains a GdkImage
GTK_IMAGE_PIXBUF | the widget contains a GdkPixbuf
GTK_IMAGE_STOCK | the widget contains a stock icon name (see Stock Items(3))
GTK_IMAGE_ICON_SET | the widget contains a GtkIconSet
GTK_IMAGE_ANIMATION | the widget contains a GdkPixbufAnimation
GTK_IMAGE_ICON_NAME | the widget contains a named icon. This image type was added in GTK+ 2.6

gtk_image_get_icon_set ()

void                gtk_image_get_icon_set              (GtkImage *image,
                                                         GtkIconSet **icon_set,
                                                         GtkIconSize *size);

Gets the icon set and size being displayed by the GtkImage. The storage type of the image must be GTK_IMAGE_EMPTY or GTK_IMAGE_ICON_SET (see gtk_image_get_storage_type()).

image : | a GtkImage
icon_set : | location to store a GtkIconSet
size : | location to store a stock icon size

gtk_image_get_image ()

void                gtk_image_get_image                 (GtkImage *image,
                                                         GdkImage **gdk_image,
                                                         GdkBitmap **mask);

Gets the GdkImage and mask being displayed by the GtkImage. The storage type of the image must be GTK_IMAGE_EMPTY or GTK_IMAGE_IMAGE (see gtk_image_get_storage_type()). The caller of this function does not own a reference to the returned image and mask.

image : | a GtkImage
gdk_image : | return location for a GtkImage
mask : | return location for a GdkBitmap

gtk_image_get_pixbuf ()

GdkPixbuf*          gtk_image_get_pixbuf                (GtkImage *image);

Gets the GdkPixbuf being displayed by the GtkImage. The storage type of the image must be GTK_IMAGE_EMPTY or GTK_IMAGE_PIXBUF (see gtk_image_get_storage_type()). The caller of this function does not own a reference to the returned pixbuf.

image : | a GtkImage
Returns : | the displayed pixbuf, or NULL if the image is empty

gtk_image_get_pixmap ()

void                gtk_image_get_pixmap                (GtkImage *image,
                                                         GdkPixmap **pixmap,
                                                         GdkBitmap **mask);

Gets the pixmap and mask being displayed by the GtkImage. The storage type of the image must be GTK_IMAGE_EMPTY or GTK_IMAGE_PIXMAP (see gtk_image_get_storage_type()). The caller of this function does not own a reference to the returned pixmap and mask.

image : | a GtkImage
pixmap : | location to store the pixmap, or NULL
mask : | location to store the mask, or NULL

gtk_image_get_stock ()

void                gtk_image_get_stock                 (GtkImage *image,
                                                         gchar **stock_id,
                                                         GtkIconSize *size);

Gets the stock icon name and size being displayed by the GtkImage. The storage type of the image must be GTK_IMAGE_EMPTY or GTK_IMAGE_STOCK (see gtk_image_get_storage_type()). The returned string is owned by the GtkImage and should not be freed.

image : | a GtkImage
stock_id : | place to store a stock icon name
size : | place to store a stock icon size

gtk_image_get_animation ()

GdkPixbufAnimation* gtk_image_get_animation             (GtkImage *image);

Gets the GdkPixbufAnimation being displayed by the GtkImage. The storage type of the image must be GTK_IMAGE_EMPTY or GTK_IMAGE_ANIMATION (see gtk_image_get_storage_type()). The caller of this function does not own a reference to the returned animation.

image : | a GtkImage
Returns : | the displayed animation, or NULL if the image is empty

gtk_image_get_icon_name ()

void                gtk_image_get_icon_name             (GtkImage *image,
                                                         G_CONST_RETURN gchar **icon_name,
                                                         GtkIconSize *size);

Gets the icon name and size being displayed by the GtkImage. The storage type of the image must be GTK_IMAGE_EMPTY or GTK_IMAGE_ICON_NAME (see gtk_image_get_storage_type()). The returned string is owned by the GtkImage and should not be freed.

image : | a GtkImage
icon_name : | place to store an icon name
size : | place to store an icon size

Since 2.6

gtk_image_get_storage_type ()

GtkImageType        gtk_image_get_storage_type          (GtkImage *image);

Gets the type of representation being used by the GtkImage to store image data. If the GtkImage has no image data, the return value will be GTK_IMAGE_EMPTY.

image : | a GtkImage
Returns : | image representation being used

gtk_image_new_from_file ()

GtkWidget*          gtk_image_new_from_file             (const gchar *filename);

Creates a new GtkImage displaying the file filename. If the file isn't found or can't be loaded, the resulting GtkImage will display a "broken image" icon. This function never returns NULL, it always returns a valid GtkImage widget.

If the file contains an animation, the image will contain an animation.

If you need to detect failures to load the file, use gdk_pixbuf_new_from_file() to load the file yourself, then create the GtkImage from the pixbuf. (Or for animations, use gdk_pixbuf_animation_new_from_file()).

The storage type (gtk_image_get_storage_type()) of the returned image is not defined, it will be whatever is appropriate for displaying the file.

filename : | a filename
Returns : | a new GtkImage

gtk_image_new_from_icon_set ()

GtkWidget*          gtk_image_new_from_icon_set         (GtkIconSet *icon_set,
                                                         GtkIconSize size);

Creates a GtkImage displaying an icon set. Sample stock sizes are GTK_ICON_SIZE_MENU, GTK_ICON_SIZE_SMALL_TOOLBAR. Instead of using this function, usually it's better to create a GtkIconFactory, put your icon sets in the icon factory, add the icon factory to the list of default factories with gtk_icon_factory_add_default(), and then use gtk_image_new_from_stock(). This will allow themes to override the icon you ship with your application.

The GtkImage does not assume a reference to the icon set; you still need to unref it if you own references. GtkImage will add its own reference rather than adopting yours.

icon_set : | a GtkIconSet
size : | a stock icon size
Returns : | a new GtkImage

gtk_image_new_from_image ()

GtkWidget*          gtk_image_new_from_image            (GdkImage *image,
                                                         GdkBitmap *mask);

Creates a GtkImage widget displaying a image with a mask. A GdkImage is a client-side image buffer in the pixel format of the current display. The GtkImage does not assume a reference to the image or mask; you still need to unref them if you own references. GtkImage will add its own reference rather than adopting yours.

image : | a GdkImage, or NULL
mask : | a GdkBitmap, or NULL
Returns : | a new GtkImage

gtk_image_new_from_pixbuf ()

GtkWidget*          gtk_image_new_from_pixbuf           (GdkPixbuf *pixbuf);

Creates a new GtkImage displaying pixbuf. The GtkImage does not assume a reference to the pixbuf; you still need to unref it if you own references. GtkImage will add its own reference rather than adopting yours.

Note that this function just creates an GtkImage from the pixbuf. The GtkImage created will not react to state changes. Should you want that, you should use gtk_image_new_from_icon_set().

pixbuf : | a GdkPixbuf, or NULL
Returns : | a new GtkImage

gtk_image_new_from_pixmap ()

GtkWidget*          gtk_image_new_from_pixmap           (GdkPixmap *pixmap,
                                                         GdkBitmap *mask);

Creates a GtkImage widget displaying pixmap with a mask. A GdkPixmap is a server-side image buffer in the pixel format of the current display. The GtkImage does not assume a reference to the pixmap or mask; you still need to unref them if you own references. GtkImage will add its own reference rather than adopting yours.

pixmap : | a GdkPixmap, or NULL
mask : | a GdkBitmap, or NULL
Returns : | a new GtkImage

gtk_image_new_from_stock ()

GtkWidget*          gtk_image_new_from_stock            (const gchar *stock_id,
                                                         GtkIconSize size);

Creates a GtkImage displaying a stock icon. Sample stock icon names are GTK_STOCK_OPEN, GTK_STOCK_QUIT. Sample stock sizes are GTK_ICON_SIZE_MENU, GTK_ICON_SIZE_SMALL_TOOLBAR. If the stock icon name isn't known, the image will be empty. You can register your own stock icon names, see gtk_icon_factory_add_default() and gtk_icon_factory_add().

stock_id : | a stock icon name
size : | a stock icon size
Returns : | a new GtkImage displaying the stock icon

gtk_image_new_from_animation ()

GtkWidget*          gtk_image_new_from_animation        (GdkPixbufAnimation *animation);

Creates a GtkImage displaying the given animation. The GtkImage does not assume a reference to the animation; you still need to unref it if you own references. GtkImage will add its own reference rather than adopting yours.

Note that the animation frames are shown using a timeout with G_PRIORITY_DEFAULT. When using animations to indicate busyness, keep in mind that the animation will only be shown if the main loop is not busy with something that has a higher priority.

animation : | an animation
Returns : | a new GtkImage widget

gtk_image_new_from_icon_name ()

GtkWidget*          gtk_image_new_from_icon_name        (const gchar *icon_name,
                                                         GtkIconSize size);

Creates a GtkImage displaying an icon from the current icon theme. If the icon name isn't known, a "broken image" icon will be displayed instead. If the current icon theme is changed, the icon will be updated appropriately.

icon_name : | an icon name
size : | a stock icon size
Returns : | a new GtkImage displaying the themed icon

Since 2.6

gtk_image_set_from_file ()

void                gtk_image_set_from_file             (GtkImage *image,
                                                         const gchar *filename);

See gtk_image_new_from_file() for details.

image : | a GtkImage
filename : | a filename or NULL

gtk_image_set_from_icon_set ()

void                gtk_image_set_from_icon_set         (GtkImage *image,
                                                         GtkIconSet *icon_set,
                                                         GtkIconSize size);

See gtk_image_new_from_icon_set() for details.

image : | a GtkImage
icon_set : | a GtkIconSet
size : | a stock icon size

gtk_image_set_from_image ()

void                gtk_image_set_from_image            (GtkImage *image,
                                                         GdkImage *gdk_image,
                                                         GdkBitmap *mask);

See gtk_image_new_from_image() for details.

image : | a GtkImage
gdk_image : | a GdkImage or NULL
mask : | a GdkBitmap or NULL

gtk_image_set_from_pixbuf ()

void                gtk_image_set_from_pixbuf           (GtkImage *image,
                                                         GdkPixbuf *pixbuf);

See gtk_image_new_from_pixbuf() for details.

image : | a GtkImage
pixbuf : | a GdkPixbuf or NULL

gtk_image_set_from_pixmap ()

void                gtk_image_set_from_pixmap           (GtkImage *image,
                                                         GdkPixmap *pixmap,
                                                         GdkBitmap *mask);

See gtk_image_new_from_pixmap() for details.

image : | a GtkImage
pixmap : | a GdkPixmap or NULL
mask : | a GdkBitmap or NULL

gtk_image_set_from_stock ()

void                gtk_image_set_from_stock            (GtkImage *image,
                                                         const gchar *stock_id,
                                                         GtkIconSize size);

See gtk_image_new_from_stock() for details.

image : | a GtkImage
stock_id : | a stock icon name
size : | a stock icon size

gtk_image_set_from_animation ()

void                gtk_image_set_from_animation        (GtkImage *image,
                                                         GdkPixbufAnimation *animation);

Causes the GtkImage to display the given animation (or display nothing, if you set the animation to NULL).

image : | a GtkImage
animation : | the GdkPixbufAnimation

gtk_image_set_from_icon_name ()

void                gtk_image_set_from_icon_name        (GtkImage *image,
                                                         const gchar *icon_name,
                                                         GtkIconSize size);

See gtk_image_new_from_icon_name() for details.

image : | a GtkImage
icon_name : | an icon name
size : | an icon size

Since 2.6

gtk_image_clear ()

void                gtk_image_clear                     (GtkImage *image);

Resets the image to be empty.

image : a GtkImage

Since 2.8

gtk_image_new ()

GtkWidget*          gtk_image_new                       (void);

Creates a new empty GtkImage widget.

Returns : a newly created GtkImage widget.

gtk_image_set ()

void                gtk_image_set                       (GtkImage *image,
                                                         GdkImage *val,
                                                         GdkBitmap *mask);

Warning

gtk_image_set is deprecated and should not be used in newly-written code.

Sets the GtkImage.

image : | a GtkImage
val : | a GdkImage
mask : | a GdkBitmap that indicates which parts of the image should be transparent.

gtk_image_get ()

void                gtk_image_get                       (GtkImage *image,
                                                         GdkImage **val,
                                                         GdkBitmap **mask);

Warning

gtk_image_get is deprecated and should not be used in newly-written code.

Gets the GtkImage.

image : | a GtkImage
val : | return location for a GdkImage
mask : | a GdkBitmap that indicates which parts of the image should be transparent.

gtk_image_set_pixel_size ()

void                gtk_image_set_pixel_size            (GtkImage *image,
                                                         gint pixel_size);

Sets the pixel size to use for named icons. If the pixel size is set to a value != -1, it is used instead of the icon size set by gtk_image_set_from_icon_name().

image : | a GtkImage
pixel_size : | the new pixel size

Since 2.6

gtk_image_get_pixel_size ()

gint                gtk_image_get_pixel_size            (GtkImage *image);

Gets the pixel size used for named icons.

image : | a GtkImage
Returns : | the pixel size used for named icons.

Since 2.6

Property Details

The "file" property

  "file"                     gchararray            : Read / Write

Filename to load and display.

Default value: NULL

The "icon-name" property

  "icon-name"                gchararray            : Read / Write

The name of the icon in the icon theme. If the icon theme is changed, the image will be updated automatically.

Default value: NULL

Since 2.6

The "icon-set" property

  "icon-set"                 GtkIconSet            : Read / Write

Icon set to display.

The "icon-size" property

  "icon-size"                gint                  : Read / Write

Symbolic size to use for stock icon, icon set or named icon.

Allowed values: >= 0

Default value: 4

The "image" property

  "image"                    GdkImage              : Read / Write

A GdkImage to display.

The "mask" property

  "mask"                     GdkPixmap             : Read / Write

Mask bitmap to use with GdkImage or GdkPixmap.

The "pixbuf" property

  "pixbuf"                   GdkPixbuf             : Read / Write

A GdkPixbuf to display.

The "pixbuf-animation" property

  "pixbuf-animation"         GdkPixbufAnimation    : Read / Write

GdkPixbufAnimation to display.

The "pixel-size" property

  "pixel-size"               gint                  : Read / Write

The :pixel-size property can be used to specify a fixed size overriding the :icon-size property for images of type GTK_IMAGE_ICON_NAME.

Allowed values: >= -1

Default value: -1

Since 2.6

The "pixmap" property

  "pixmap"                   GdkPixmap             : Read / Write

A GdkPixmap to display.

The "stock" property

  "stock"                    gchararray            : Read / Write

Stock ID for a stock image to display.

Default value: NULL

The "storage-type" property

  "storage-type"             GtkImageType          : Read

The representation being used for image data.

Default value: GTK_IMAGE_EMPTY

See Also

GdkPixbuf


GtkImageMenuItem

GtkImageMenuItem — A menu item with an icon

Synopsis

#include <gtk/gtk.h>

                    GtkImageMenuItem;
void                gtk_image_menu_item_set_image       (GtkImageMenuItem *image_menu_item,
                                                         GtkWidget *image);
GtkWidget*          gtk_image_menu_item_get_image       (GtkImageMenuItem *image_menu_item);
GtkWidget*          gtk_image_menu_item_new             (void);
GtkWidget*          gtk_image_menu_item_new_from_stock  (const gchar *stock_id,
                                                         GtkAccelGroup *accel_group);
GtkWidget*          gtk_image_menu_item_new_with_label  (const gchar *label);
GtkWidget*          gtk_image_menu_item_new_with_mnemonic
                                                        (const gchar *label);

Object Hierarchy

  GObject
   +----GInitiallyUnowned
         +----GtkObject
               +----GtkWidget
                     +----GtkContainer
                           +----GtkBin
                                 +----GtkItem
                                       +----GtkMenuItem
                                             +----GtkImageMenuItem

Implemented Interfaces

GtkImageMenuItem implements AtkImplementorIface.

Properties

  "image"                    GtkWidget             : Read / Write

Description

A GtkImageMenuItem is a menu item which has an icon next to the text label.

Note that the user can disable display of menu icons, so make sure to still fill in the text label.

Details

GtkImageMenuItem

typedef struct _GtkImageMenuItem GtkImageMenuItem;

gtk_image_menu_item_set_image ()

void                gtk_image_menu_item_set_image       (GtkImageMenuItem *image_menu_item,
                                                         GtkWidget *image);

Sets the image of image_menu_item to the given widget. Note that it depends on the show-menu-images setting whether the image will be displayed or not.

image_menu_item : | a GtkImageMenuItem.
image : | a widget to set as the image for the menu item.

gtk_image_menu_item_get_image ()

GtkWidget*          gtk_image_menu_item_get_image       (GtkImageMenuItem *image_menu_item);

Gets the widget that is currently set as the image of image_menu_item. See gtk_image_menu_item_set_image().

image_menu_item : | a GtkImageMenuItem.
Returns : | the widget set as image of image_menu_item.

gtk_image_menu_item_new ()

GtkWidget*          gtk_image_menu_item_new             (void);

Creates a new GtkImageMenuItem with an empty label.

Returns : a new GtkImageMenuItem.

gtk_image_menu_item_new_from_stock ()

GtkWidget*          gtk_image_menu_item_new_from_stock  (const gchar *stock_id,
                                                         GtkAccelGroup *accel_group);

Creates a new GtkImageMenuItem containing the image and text from a stock item. Some stock ids have preprocessor macros like GTK_STOCK_OK and GTK_STOCK_APPLY.

If you want this menu item to have changeable accelerators, then pass in NULL for accel_group. Next call gtk_menu_item_set_accel_path() with an appropriate path for the menu item, use gtk_stock_lookup() to look up the standard accelerator for the stock item, and if one is found, call gtk_accel_map_add_entry() to register it.

stock_id : | the name of the stock item.
accel_group : | the GtkAccelGroup to add the menu items accelerator to, or NULL.
Returns : | a new GtkImageMenuItem.

gtk_image_menu_item_new_with_label ()

GtkWidget*          gtk_image_menu_item_new_with_label  (const gchar *label);

Creates a new GtkImageMenuItem containing a label.

label : | the text of the menu item.
Returns : | a new GtkImageMenuItem.

gtk_image_menu_item_new_with_mnemonic ()

GtkWidget*          gtk_image_menu_item_new_with_mnemonic
                                                        (const gchar *label);

Creates a new GtkImageMenuItem containing a label. The label will be created using gtk_label_new_with_mnemonic(), so underscores in label indicate the mnemonic for the menu item.

label : | the text of the menu item, with an underscore in front of the mnemonic character
Returns : | a new GtkImageMenuItem

Property Details

The "image" property

  "image"                    GtkWidget             : Read / Write

Child widget to appear next to the menu text.


GtkIMContext

GtkIMContext — Base class for input method contexts

Synopsis

#include <gtk/gtk.h>

                    GtkIMContext;
void                gtk_im_context_set_client_window    (GtkIMContext *context,
                                                         GdkWindow *window);
void                gtk_im_context_get_preedit_string   (GtkIMContext *context,
                                                         gchar **str,
                                                         PangoAttrList **attrs,
                                                         gint *cursor_pos);
gboolean            gtk_im_context_filter_keypress      (GtkIMContext *context,
                                                         GdkEventKey *event);
void                gtk_im_context_focus_in             (GtkIMContext *context);
void                gtk_im_context_focus_out            (GtkIMContext *context);
void                gtk_im_context_reset                (GtkIMContext *context);
void                gtk_im_context_set_cursor_location  (GtkIMContext *context,
                                                         GdkRectangle *area);
void                gtk_im_context_set_use_preedit      (GtkIMContext *context,
                                                         gboolean use_preedit);
void                gtk_im_context_set_surrounding      (GtkIMContext *context,
                                                         const gchar *text,
                                                         gint len,
                                                         gint cursor_index);
gboolean            gtk_im_context_get_surrounding      (GtkIMContext *context,
                                                         gchar **text,
                                                         gint *cursor_index);
gboolean            gtk_im_context_delete_surrounding   (GtkIMContext *context,
                                                         gint offset,
                                                         gint n_chars);

Object Hierarchy

  GObject
   +----GtkIMContext
         +----GtkIMContextSimple
         +----GtkIMMulticontext

Signals

  "commit"                                         : Run Last
  "delete-surrounding"                             : Run Last
  "preedit-changed"                                : Run Last
  "preedit-end"                                    : Run Last
  "preedit-start"                                  : Run Last
  "retrieve-surrounding"                           : Run Last

Description

Details

GtkIMContext

typedef struct _GtkIMContext GtkIMContext;

gtk_im_context_set_client_window ()

void                gtk_im_context_set_client_window    (GtkIMContext *context,
                                                         GdkWindow *window);

Set the client window for the input context; this is the GdkWindow in which the input appears. This window is used in order to correctly position status windows, and may also be used for purposes internal to the input method.

context : | a GtkIMContext
window : | the client window. This may be NULL to indicate that the previous client window no longer exists.

gtk_im_context_get_preedit_string ()

void                gtk_im_context_get_preedit_string   (GtkIMContext *context,
                                                         gchar **str,
                                                         PangoAttrList **attrs,
                                                         gint *cursor_pos);

Retrieve the current preedit string for the input context, and a list of attributes to apply to the string. This string should be displayed inserted at the insertion point.

context : | a GtkIMContext
str : | location to store the retrieved string. The string retrieved must be freed with g_free().
attrs : | location to store the retrieved attribute list. When you are done with this list, you must unreference it with pango_attr_list_unref().
cursor_pos : | location to store position of cursor (in characters) within the preedit string.

gtk_im_context_filter_keypress ()

gboolean            gtk_im_context_filter_keypress      (GtkIMContext *context,
                                                         GdkEventKey *event);

Allow an input method to internally handle key press and release events. If this function returns TRUE, then no further processing should be done for this key event.

context : | a GtkIMContext
event : | the key event
Returns : | TRUE if the input method handled the key event.

gtk_im_context_focus_in ()

void                gtk_im_context_focus_in             (GtkIMContext *context);

Notify the input method that the widget to which this input context corresponds has gained focus. The input method may, for example, change the displayed feedback to reflect this change.

context : a GtkIMContext

gtk_im_context_focus_out ()

void                gtk_im_context_focus_out            (GtkIMContext *context);

Notify the input method that the widget to which this input context corresponds has lost focus. The input method may, for example, change the displayed feedback or reset the contexts state to reflect this change.

context : a GtkIMContext

gtk_im_context_reset ()

void                gtk_im_context_reset                (GtkIMContext *context);

Notify the input method that a change such as a change in cursor position has been made. This will typically cause the input method to clear the preedit state.

context : a GtkIMContext

gtk_im_context_set_cursor_location ()

void                gtk_im_context_set_cursor_location  (GtkIMContext *context,
                                                         GdkRectangle *area);

Notify the input method that a change in cursor position has been made. The location is relative to the client window.

context : | a GtkIMContext
area : | new location

gtk_im_context_set_use_preedit ()

void                gtk_im_context_set_use_preedit      (GtkIMContext *context,
                                                         gboolean use_preedit);

Sets whether the IM context should use the preedit string to display feedback. If use_preedit is FALSE (default is TRUE), then the IM context may use some other method to display feedback, such as displaying it in a child of the root window.

context : | a GtkIMContext
use_preedit : | whether the IM context should use the preedit string.

gtk_im_context_set_surrounding ()

void                gtk_im_context_set_surrounding      (GtkIMContext *context,
                                                         const gchar *text,
                                                         gint len,
                                                         gint cursor_index);

Sets surrounding context around the insertion point and preedit string. This function is expected to be called in response to the GtkIMContext::retrieve_surrounding signal, and will likely have no effect if called at other times.

context : | a GtkIMContext
text : | text surrounding the insertion point, as UTF-8. the preedit string should not be included within text.
len : | the length of text, or -1 if text is nul-terminated
cursor_index : | the byte index of the insertion cursor within text.

gtk_im_context_get_surrounding ()

gboolean            gtk_im_context_get_surrounding      (GtkIMContext *context,
                                                         gchar **text,
                                                         gint *cursor_index);

Retrieves context around the insertion point. Input methods typically want context in order to constrain input text based on existing text; this is important for languages such as Thai where only some sequences of characters are allowed.

This function is implemented by emitting the GtkIMContext::retrieve_surrounding signal on the input method; in response to this signal, a widget should provide as much context as is available, up to an entire paragraph, by calling gtk_im_context_set_surrounding(). Note that there is no obligation for a widget to respond to the ::retrieve_surrounding signal, so input methods must be prepared to function without context.

context : | a GtkIMContext
text : | location to store a UTF-8 encoded string of text holding context around the insertion point. If the function returns TRUE, then you must free the result stored in this location with g_free().
cursor_index : | location to store byte index of the insertion cursor within text.
Returns : | TRUE if surrounding text was provided; in this case you must free the result stored in *text.

gtk_im_context_delete_surrounding ()

gboolean            gtk_im_context_delete_surrounding   (GtkIMContext *context,
                                                         gint offset,
                                                         gint n_chars);

Asks the widget that the input context is attached to to delete characters around the cursor position by emitting the GtkIMContext::delete_surrounding signal. Note that offset and n_chars are in characters not in bytes which differs from the usage other places in GtkIMContext.

In order to use this function, you should first call gtk_im_context_get_surrounding() to get the current context, and call this function immediately afterwards to make sure that you know what you are deleting. You should also account for the fact that even if the signal was handled, the input context might not have deleted all the characters that were requested to be deleted.

This function is used by an input method that wants to make subsitutions in the existing text in response to new input. It is not useful for applications.

context : | a GtkIMContext
offset : | offset from cursor position in chars; a negative value means start before the cursor.
n_chars : | number of characters to delete.
Returns : | TRUE if the signal was handled.

Signal Details

The "commit" signal

void                user_function                      (GtkIMContext *imcontext,
                                                        gchar        *arg1,
                                                        gpointer      user_data)      : Run Last

imcontext : | the object which received the signal.
arg1 : |
user_data : | user data set when the signal handler was connected.

The "delete-surrounding" signal

gboolean            user_function                      (GtkIMContext *imcontext,
                                                        gint          arg1,
                                                        gint          arg2,
                                                        gpointer      user_data)      : Run Last

imcontext : | the object which received the signal.
arg1 : |
arg2 : |
user_data : | user data set when the signal handler was connected.
Returns : |

The "preedit-changed" signal

void                user_function                      (GtkIMContext *imcontext,
                                                        gpointer      user_data)      : Run Last

imcontext : | the object which received the signal.
user_data : | user data set when the signal handler was connected.

The "preedit-end" signal

void                user_function                      (GtkIMContext *imcontext,
                                                        gpointer      user_data)      : Run Last

imcontext : | the object which received the signal.
user_data : | user data set when the signal handler was connected.

The "preedit-start" signal

void                user_function                      (GtkIMContext *imcontext,
                                                        gpointer      user_data)      : Run Last

imcontext : | the object which received the signal.
user_data : | user data set when the signal handler was connected.

The "retrieve-surrounding" signal

gboolean            user_function                      (GtkIMContext *imcontext,
                                                        gpointer      user_data)      : Run Last

imcontext : | the object which received the signal.
user_data : | user data set when the signal handler was connected.
Returns : |


GtkIMContextSimple

GtkIMContextSimple — An input method context supporting table-based input methods

Synopsis

#include <gtk/gtk.h>

                    GtkIMContextSimple;
GtkIMContext*       gtk_im_context_simple_new           (void);
void                gtk_im_context_simple_add_table     (GtkIMContextSimple *context_simple,
                                                         guint16 *data,
                                                         gint max_seq_len,
                                                         gint n_seqs);
#define             GTK_MAX_COMPOSE_LEN

Object Hierarchy

  GObject
   +----GtkIMContext
         +----GtkIMContextSimple

Description

Details

GtkIMContextSimple

typedef struct _GtkIMContextSimple GtkIMContextSimple;

gtk_im_context_simple_new ()

GtkIMContext*       gtk_im_context_simple_new           (void);

Creates a new GtkIMContextSimple.

Returns : a new GtkIMContextSimple.

gtk_im_context_simple_add_table ()

void                gtk_im_context_simple_add_table     (GtkIMContextSimple *context_simple,
                                                         guint16 *data,
                                                         gint max_seq_len,
                                                         gint n_seqs);

Adds an additional table to search to the input context. Each row of the table consists of max_seq_len key symbols followed by two guint16 interpreted as the high and low words of a gunicode value. Tables are searched starting from the last added.

The table must be sorted in dictionary order on the numeric value of the key symbol fields. (Values beyond the length of the sequence should be zero.)

context_simple : | A GtkIMContextSimple
data : | the table
max_seq_len : | Maximum length of a sequence in the table (cannot be greater than GTK_MAX_COMPOSE_LEN)
n_seqs : | number of sequences in the table

GTK_MAX_COMPOSE_LEN

#define GTK_MAX_COMPOSE_LEN 7

The maximum length of sequences in compose tables.


GtkIMMulticontext

GtkIMMulticontext — An input method context supporting multiple, loadable input methods

Synopsis

#include <gtk/gtk.h>

                    GtkIMMulticontext;
GtkIMContext*       gtk_im_multicontext_new             (void);
void                gtk_im_multicontext_append_menuitems
                                                        (GtkIMMulticontext *context,
                                                         GtkMenuShell *menushell);

Object Hierarchy

  GObject
   +----GtkIMContext
         +----GtkIMMulticontext

Description

Details

GtkIMMulticontext

typedef struct _GtkIMMulticontext GtkIMMulticontext;

gtk_im_multicontext_new ()

GtkIMContext*       gtk_im_multicontext_new             (void);

Creates a new GtkIMMulticontext.

Returns : a new GtkIMMulticontext.

gtk_im_multicontext_append_menuitems ()

void                gtk_im_multicontext_append_menuitems
                                                        (GtkIMMulticontext *context,
                                                         GtkMenuShell *menushell);

Add menuitems for various available input methods to a menu; the menuitems, when selected, will switch the input method for the context and the global default input method.

context : | a GtkIMMultiContext
menushell : | a GtkMenuShell


GtkInputDialog

GtkInputDialog — Configure devices for the XInput extension

Synopsis

#include <gtk/gtk.h>

                    GtkInputDialog;
GtkWidget*          gtk_input_dialog_new                (void);

Object Hierarchy

  GObject
   +----GInitiallyUnowned
         +----GtkObject
               +----GtkWidget
                     +----GtkContainer
                           +----GtkBin
                                 +----GtkWindow
                                       +----GtkDialog
                                             +----GtkInputDialog

Implemented Interfaces

GtkInputDialog implements AtkImplementorIface.

Signals

  "disable-device"                                 : Run Last
  "enable-device"                                  : Run Last

Description

NOTE this widget is considered too specialized/little-used for GTK+, and will in the future be moved to some other package. If your application needs this widget, feel free to use it, as the widget does work and is useful in some applications; it's just not of general interest. However, we are not accepting new features for the widget, and it will eventually move out of the GTK+ distribution.

GtkInputDialog displays a dialog which allows the user to configure XInput extension devices. For each device, they can control the mode of the device (disabled, screen-relative, or window-relative), the mapping of axes to coordinates, and the mapping of the devices macro keys to key press events.

GtkInputDialog contains two buttons to which the application can connect; one for closing the dialog, and one for saving the changes. No actions are bound to these by default. The changes that the user makes take effect immediately.

Details

GtkInputDialog

typedef struct _GtkInputDialog GtkInputDialog;

gtk_input_dialog_new ()

GtkWidget*          gtk_input_dialog_new                (void);

Creates a new GtkInputDialog.

Returns : the new GtkInputDialog.

Signal Details

The "disable-device" signal

void                user_function                      (GtkInputDialog *inputdialog,
                                                        GdkDevice      *deviceid,
                                                        gpointer        user_data)        : Run Last

This signal is emitted when the user changes the mode of a device from a GDK_MODE_SCREEN or GDK_MODE_WINDOW to GDK_MODE_ENABLED.

inputdialog : | the object which received the signal.
deviceid : | The ID of the newly disabled device.
user_data : | user data set when the signal handler was connected.

The "enable-device" signal

void                user_function                      (GtkInputDialog *inputdialog,
                                                        GdkDevice      *deviceid,
                                                        gpointer        user_data)        : Run Last

This signal is emitted when the user changes the mode of a device from GDK_MODE_DISABLED to a GDK_MODE_SCREEN or GDK_MODE_WINDOW.

inputdialog : | the object which received the signal.
deviceid : | The ID of the newly enabled device.
user_data : | user data set when the signal handler was connected.


GtkInvisible

GtkInvisible — A widget which is not displayed

Synopsis

#include <gtk/gtk.h>

                    GtkInvisible;
GtkWidget*          gtk_invisible_new                   (void);
GtkWidget*          gtk_invisible_new_for_screen        (GdkScreen *screen);
void                gtk_invisible_set_screen            (GtkInvisible *invisible,
                                                         GdkScreen *screen);
GdkScreen*          gtk_invisible_get_screen            (GtkInvisible *invisible);

Object Hierarchy

  GObject
   +----GInitiallyUnowned
         +----GtkObject
               +----GtkWidget
                     +----GtkInvisible

Implemented Interfaces

GtkInvisible implements AtkImplementorIface.

Properties

  "screen"                   GdkScreen             : Read / Write

Description

The GtkInvisible widget is used internally in GTK+, and is probably not very useful for application developers.

It is used for reliable pointer grabs and selection handling in the code for drag-and-drop.

Details

GtkInvisible

typedef struct _GtkInvisible GtkInvisible;

The GtkInvisible struct contains no public fields.

gtk_invisible_new ()

GtkWidget*          gtk_invisible_new                   (void);

Creates a new GtkInvisible.

Returns : a new GtkInvisible.

gtk_invisible_new_for_screen ()

GtkWidget*          gtk_invisible_new_for_screen        (GdkScreen *screen);

Creates a new GtkInvisible object for a specified screen

screen : | a GdkScreen which identifies on which the new GtkInvisible will be created.
Returns : | a newly created GtkInvisible object

Since 2.2

gtk_invisible_set_screen ()

void                gtk_invisible_set_screen            (GtkInvisible *invisible,
                                                         GdkScreen *screen);

Sets the GdkScreen where the GtkInvisible object will be displayed.

invisible : | a GtkInvisible.
screen : | a GdkScreen.

Since 2.2

gtk_invisible_get_screen ()

GdkScreen*          gtk_invisible_get_screen            (GtkInvisible *invisible);

Returns the GdkScreen object associated with invisible

invisible : | a GtkInvisible.
Returns : | the associated GdkScreen.

Since 2.2

Property Details

The "screen" property

  "screen"                   GdkScreen             : Read / Write

The screen where this window will be displayed.


GtkItem

GtkItem — Abstract base class for GtkMenuItem, GtkListItem and GtkTreeItem

Synopsis

#include <gtk/gtk.h>

                    GtkItem;
void                gtk_item_select                     (GtkItem *item);
void                gtk_item_deselect                   (GtkItem *item);
void                gtk_item_toggle                     (GtkItem *item);

Object Hierarchy

  GObject
   +----GInitiallyUnowned
         +----GtkObject
               +----GtkWidget
                     +----GtkContainer
                           +----GtkBin
                                 +----GtkItem
                                       +----GtkMenuItem
                                       +----GtkListItem
                                       +----GtkTreeItem

Implemented Interfaces

GtkItem implements AtkImplementorIface.

Signals

  "deselect"                                       : Run First
  "select"                                         : Run First
  "toggle"                                         : Run First

Description

The GtkItem widget is an abstract base class for GtkMenuItem, GtkListItem and GtkTreeItem.

Details

GtkItem

typedef struct _GtkItem GtkItem;

The GtkItem struct contains private data only, and should be accessed using the functions below.

gtk_item_select ()

void                gtk_item_select                     (GtkItem *item);

Emits the "select" signal on the given item.

item : a GtkItem.

gtk_item_deselect ()

void                gtk_item_deselect                   (GtkItem *item);

Emits the "deselect" signal on the given item.

item : a GtkItem.

gtk_item_toggle ()

void                gtk_item_toggle                     (GtkItem *item);

Emits the "toggle" signal on the given item.

item : a GtkItem.

Signal Details

The "deselect" signal

void                user_function                      (GtkItem *item,
                                                        gpointer user_data)      : Run First

Emitted when the item is deselected.

item : | the object which received the signal.
user_data : | user data set when the signal handler was connected.

The "select" signal

void                user_function                      (GtkItem *item,
                                                        gpointer user_data)      : Run First

Emitted when the item is selected.

item : | the object which received the signal.
user_data : | user data set when the signal handler was connected.

The "toggle" signal

void                user_function                      (GtkItem *item,
                                                        gpointer user_data)      : Run First

Emitted when the item is toggled.

item : | the object which received the signal.
user_data : | user data set when the signal handler was connected.


GtkItemFactory

GtkItemFactory — A factory for menus

Synopsis

#include <gtk/gtk.h>

                    GtkItemFactory;
void                (*GtkPrintFunc)                     (gpointer func_data,
                                                         const gchar *str);
gchar*              (*GtkTranslateFunc)                 (const gchar *path,
                                                         gpointer func_data);
void                (*GtkItemFactoryCallback)           ();
void                (*GtkItemFactoryCallback1)          (gpointer callback_data,
                                                         guint callback_action,
                                                         GtkWidget *widget);
void                (*GtkItemFactoryCallback2)          (GtkWidget *widget,
                                                         gpointer callback_data,
                                                         guint callback_action);
                    GtkItemFactoryEntry;
                    GtkItemFactoryItem;
GtkItemFactory*     gtk_item_factory_new                (GType container_type,
                                                         const gchar *path,
                                                         GtkAccelGroup *accel_group);
void                gtk_item_factory_construct          (GtkItemFactory *ifactory,
                                                         GType container_type,
                                                         const gchar *path,
                                                         GtkAccelGroup *accel_group);
void                gtk_item_factory_add_foreign        (GtkWidget *accel_widget,
                                                         const gchar *full_path,
                                                         GtkAccelGroup *accel_group,
                                                         guint keyval,
                                                         GdkModifierType modifiers);
GtkItemFactory*     gtk_item_factory_from_widget        (GtkWidget *widget);
const gchar*        gtk_item_factory_path_from_widget   (GtkWidget *widget);
GtkWidget*          gtk_item_factory_get_item           (GtkItemFactory *ifactory,
                                                         const gchar *path);
GtkWidget*          gtk_item_factory_get_widget         (GtkItemFactory *ifactory,
                                                         const gchar *path);
GtkWidget*          gtk_item_factory_get_widget_by_action
                                                        (GtkItemFactory *ifactory,
                                                         guint action);
GtkWidget*          gtk_item_factory_get_item_by_action (GtkItemFactory *ifactory,
                                                         guint action);
void                gtk_item_factory_create_item        (GtkItemFactory *ifactory,
                                                         GtkItemFactoryEntry *entry,
                                                         gpointer callback_data,
                                                         guint callback_type);
void                gtk_item_factory_create_items       (GtkItemFactory *ifactory,
                                                         guint n_entries,
                                                         GtkItemFactoryEntry *entries,
                                                         gpointer callback_data);
void                gtk_item_factory_create_items_ac    (GtkItemFactory *ifactory,
                                                         guint n_entries,
                                                         GtkItemFactoryEntry *entries,
                                                         gpointer callback_data,
                                                         guint callback_type);
void                gtk_item_factory_delete_item        (GtkItemFactory *ifactory,
                                                         const gchar *path);
void                gtk_item_factory_delete_entry       (GtkItemFactory *ifactory,
                                                         GtkItemFactoryEntry *entry);
void                gtk_item_factory_delete_entries     (GtkItemFactory *ifactory,
                                                         guint n_entries,
                                                         GtkItemFactoryEntry *entries);
void                gtk_item_factory_popup              (GtkItemFactory *ifactory,
                                                         guint x,
                                                         guint y,
                                                         guint mouse_button,
                                                         guint32 time_);
void                gtk_item_factory_popup_with_data    (GtkItemFactory *ifactory,
                                                         gpointer popup_data,
                                                         GtkDestroyNotify destroy,
                                                         guint x,
                                                         guint y,
                                                         guint mouse_button,
                                                         guint32 time_);
gpointer            gtk_item_factory_popup_data         (GtkItemFactory *ifactory);
gpointer            gtk_item_factory_popup_data_from_widget
                                                        (GtkWidget *widget);
GtkItemFactory*     gtk_item_factory_from_path          (const gchar *path);
void                gtk_item_factory_create_menu_entries
                                                        (guint n_entries,
                                                         GtkMenuEntry *entries);
void                gtk_item_factories_path_delete      (const gchar *ifactory_path,
                                                         const gchar *path);
void                gtk_item_factory_set_translate_func (GtkItemFactory *ifactory,
                                                         GtkTranslateFunc func,
                                                         gpointer data,
                                                         GtkDestroyNotify notify);

Object Hierarchy

  GObject
   +----GInitiallyUnowned
         +----GtkObject
               +----GtkItemFactory

Description

As of GTK+ 2.4, GtkItemFactory has been deprecated in favour of GtkUIManager.

Details

GtkItemFactory

typedef struct _GtkItemFactory GtkItemFactory;

Warning

GtkItemFactory is deprecated and should not be used in newly-written code.

GtkPrintFunc ()

void                (*GtkPrintFunc)                     (gpointer func_data,
                                                         const gchar *str);

Warning

GtkPrintFunc is deprecated and should not be used in newly-written code.

func_data :
str :

GtkTranslateFunc ()

gchar*              (*GtkTranslateFunc)                 (const gchar *path,
                                                         gpointer func_data);

The function used to translate messages in e.g. GtkIconFactory and GtkActionGroup.

path : | The id of the message. In GtkItemFactory this will be a path from a GtkItemFactoryEntry, in GtkActionGroup, it will be a label or tooltip from a GtkActionEntry.
func_data : | user data passed in when registering the function
Returns : | the translated message

GtkItemFactoryCallback ()

void                (*GtkItemFactoryCallback)           ();

Warning

GtkItemFactoryCallback is deprecated and should not be used in newly-written code.

GtkItemFactoryCallback1 ()

void                (*GtkItemFactoryCallback1)          (gpointer callback_data,
                                                         guint callback_action,
                                                         GtkWidget *widget);

Warning

GtkItemFactoryCallback1 is deprecated and should not be used in newly-written code.

callback_data :
callback_action :
widget :

GtkItemFactoryCallback2 ()

void                (*GtkItemFactoryCallback2)          (GtkWidget *widget,
                                                         gpointer callback_data,
                                                         guint callback_action);

Warning

GtkItemFactoryCallback2 is deprecated and should not be used in newly-written code.

widget :
callback_data :
callback_action :

GtkItemFactoryEntry

typedef struct {
  gchar *path;
  gchar *accelerator;

  GtkItemFactoryCallback callback;
  guint			 callback_action;

  /* possible values:
   * NULL		-> "<Item>"
   * ""			-> "<Item>"
   * "<Title>"		-> create a title item
   * "<Item>"		-> create a simple item
   * "<ImageItem>"	-> create an item holding an image
   * "<StockItem>"	-> create an item holding a stock image
   * "<CheckItem>"	-> create a check item
   * "<ToggleItem>"	-> create a toggle item
   * "<RadioItem>"	-> create a radio item
   * <path>		-> path of a radio item to link against
   * "<Separator>"	-> create a separator
   * "<Tearoff>"	-> create a tearoff separator
   * "<Branch>"		-> create an item to hold sub items
   * "<LastBranch>"	-> create a right justified item to hold sub items
   */
  gchar		 *item_type;

  /* Extra data for some item types:
   *  ImageItem  -> pointer to inlined pixbuf stream
   *  StockItem  -> name of stock item
   */
  gconstpointer extra_data;
} GtkItemFactoryEntry;

Warning

GtkItemFactoryEntry is deprecated and should not be used in newly-written code.

GtkItemFactoryItem

typedef struct {
  gchar *path;
  GSList *widgets;
} GtkItemFactoryItem;

Warning

GtkItemFactoryItem is deprecated and should not be used in newly-written code.

gtk_item_factory_new ()

GtkItemFactory*     gtk_item_factory_new                (GType container_type,
                                                         const gchar *path,
                                                         GtkAccelGroup *accel_group);

Warning

gtk_item_factory_new has been deprecated since version 2.4 and should not be used in newly-written code.

Creates a new GtkItemFactory.

Beware that the returned object does not have a floating reference.

container_type : | the kind of menu to create; can be GTK_TYPE_MENU_BAR, GTK_TYPE_MENU or GTK_TYPE_OPTION_MENU
path : | the factory path of the new item factory, a string of the form "<name>"
accel_group : | a GtkAccelGroup to which the accelerators for the menu items will be added, or NULL to create a new one
Returns : | a new GtkItemFactory

gtk_item_factory_construct ()

void                gtk_item_factory_construct          (GtkItemFactory *ifactory,
                                                         GType container_type,
                                                         const gchar *path,
                                                         GtkAccelGroup *accel_group);

Warning

gtk_item_factory_construct has been deprecated since version 2.4 and should not be used in newly-written code.

Initializes an item factory.

ifactory : | a GtkItemFactory
container_type : | the kind of menu to create; can be GTK_TYPE_MENU_BAR, GTK_TYPE_MENU or GTK_TYPE_OPTION_MENU
path : | the factory path of ifactory, a string of the form "<name>"
accel_group : | a GtkAccelGroup to which the accelerators for the menu items will be added, or NULL to create a new one

gtk_item_factory_add_foreign ()

void                gtk_item_factory_add_foreign        (GtkWidget *accel_widget,
                                                         const gchar *full_path,
                                                         GtkAccelGroup *accel_group,
                                                         guint keyval,
                                                         GdkModifierType modifiers);

Warning

gtk_item_factory_add_foreign has been deprecated since version 2.4 and should not be used in newly-written code. The recommended API for this purpose are the functions gtk_menu_item_set_accel_path() and gtk_widget_set_accel_path(); don't use gtk_item_factory_add_foreign() in new code, since it is likely to be removed in the future.

Installs an accelerator for accel_widget in accel_group, that causes the ::activate signal to be emitted if the accelerator is activated.

This function can be used to make widgets participate in the accel saving/restoring functionality provided by gtk_accel_map_save() and gtk_accel_map_load(), even if they haven't been created by an item factory.

accel_widget : | widget to install an accelerator on
full_path : | the full path for the accel_widget
accel_group : | the accelerator group to install the accelerator in
keyval : | key value of the accelerator
modifiers : | modifier combination of the accelerator

gtk_item_factory_from_widget ()

GtkItemFactory*     gtk_item_factory_from_widget        (GtkWidget *widget);

Warning

gtk_item_factory_from_widget is deprecated and should not be used in newly-written code. 2.4

Obtains the item factory from which a widget was created.

widget : | a widget
Returns : | the item factory from which widget was created, or NULL

gtk_item_factory_path_from_widget ()

const gchar*        gtk_item_factory_path_from_widget   (GtkWidget *widget);

Warning

gtk_item_factory_path_from_widget has been deprecated since version 2.4 and should not be used in newly-written code.

If widget has been created by an item factory, returns the full path to it. (The full path of a widget is the concatenation of the factory path specified in gtk_item_factory_new() with the path specified in the GtkItemFactoryEntry from which the widget was created.)

widget : | a widget
Returns : | the full path to widget if it has been created by an item factory, NULL otherwise. This value is owned by GTK+ and must not be modified or freed.

gtk_item_factory_get_item ()

GtkWidget*          gtk_item_factory_get_item           (GtkItemFactory *ifactory,
                                                         const gchar *path);

Warning

gtk_item_factory_get_item has been deprecated since version 2.4 and should not be used in newly-written code.

Obtains the menu item which corresponds to path.

If the widget corresponding to path is a menu item which opens a submenu, then the item is returned. If you are interested in the submenu, use gtk_item_factory_get_widget() instead.

ifactory : | a GtkItemFactory
path : | the path to the menu item
Returns : | the menu item for the given path, or NULL if path doesn't lead to a menu item

gtk_item_factory_get_widget ()

GtkWidget*          gtk_item_factory_get_widget         (GtkItemFactory *ifactory,
                                                         const gchar *path);

Warning

gtk_item_factory_get_widget has been deprecated since version 2.4 and should not be used in newly-written code.

Obtains the widget which corresponds to path.

If the widget corresponding to path is a menu item which opens a submenu, then the submenu is returned. If you are interested in the menu item, use gtk_item_factory_get_item() instead.

ifactory : | a GtkItemFactory
path : | the path to the widget
Returns : | the widget for the given path, or NULL if path doesn't lead to a widget

gtk_item_factory_get_widget_by_action ()

GtkWidget*          gtk_item_factory_get_widget_by_action
                                                        (GtkItemFactory *ifactory,
                                                         guint action);

Warning

gtk_item_factory_get_widget_by_action has been deprecated since version 2.4 and should not be used in newly-written code.

Obtains the widget which was constructed from the GtkItemFactoryEntry with the given action.

If there are multiple items with the same action, the result is undefined.

ifactory : | a GtkItemFactory
action : | an action as specified in the callback_action field of GtkItemFactoryEntry
Returns : | the widget which corresponds to the given action, or NULL if no widget was found

gtk_item_factory_get_item_by_action ()

GtkWidget*          gtk_item_factory_get_item_by_action (GtkItemFactory *ifactory,
                                                         guint action);

Warning

gtk_item_factory_get_item_by_action has been deprecated since version 2.4 and should not be used in newly-written code.

Obtains the menu item which was constructed from the first GtkItemFactoryEntry with the given action.

ifactory : | a GtkItemFactory
action : | an action as specified in the callback_action field of GtkItemFactoryEntry
Returns : | the menu item which corresponds to the given action, or NULL if no menu item was found

gtk_item_factory_create_item ()

void                gtk_item_factory_create_item        (GtkItemFactory *ifactory,
                                                         GtkItemFactoryEntry *entry,
                                                         gpointer callback_data,
                                                         guint callback_type);

Warning

gtk_item_factory_create_item has been deprecated since version 2.4 and should not be used in newly-written code.

Creates an item for entry.

ifactory : | a GtkItemFactory
entry : | the GtkItemFactoryEntry to create an item for
callback_data : | data passed to the callback function of entry
callback_type : | 1 if the callback function of entry is of type GtkItemFactoryCallback1, 2 if it is of type GtkItemFactoryCallback2

gtk_item_factory_create_items ()

void                gtk_item_factory_create_items       (GtkItemFactory *ifactory,
                                                         guint n_entries,
                                                         GtkItemFactoryEntry *entries,
                                                         gpointer callback_data);

Warning

gtk_item_factory_create_items has been deprecated since version 2.4 and should not be used in newly-written code.

Creates the menu items from the entries.

ifactory : | a GtkItemFactory
n_entries : | the length of entries
entries : | an array of GtkItemFactoryEntrys whose callback members must by of type GtkItemFactoryCallback1
callback_data : | data passed to the callback functions of all entries

gtk_item_factory_create_items_ac ()

void                gtk_item_factory_create_items_ac    (GtkItemFactory *ifactory,
                                                         guint n_entries,
                                                         GtkItemFactoryEntry *entries,
                                                         gpointer callback_data,
                                                         guint callback_type);

Warning

gtk_item_factory_create_items_ac has been deprecated since version 2.4 and should not be used in newly-written code.

Creates the menu items from the entries.

ifactory : | a GtkItemFactory
n_entries : | the length of entries
entries : | an array of GtkItemFactoryEntrys
callback_data : | data passed to the callback functions of all entries
callback_type : | 1 if the callback functions in entries are of type GtkItemFactoryCallback1, 2 if they are of type GtkItemFactoryCallback2

gtk_item_factory_delete_item ()

void                gtk_item_factory_delete_item        (GtkItemFactory *ifactory,
                                                         const gchar *path);

Warning

gtk_item_factory_delete_item has been deprecated since version 2.4 and should not be used in newly-written code.

Deletes the menu item which was created for path by the given item factory.

ifactory : | a GtkItemFactory
path : | a path

gtk_item_factory_delete_entry ()

void                gtk_item_factory_delete_entry       (GtkItemFactory *ifactory,
                                                         GtkItemFactoryEntry *entry);

Warning

gtk_item_factory_delete_entry has been deprecated since version 2.4 and should not be used in newly-written code.

Deletes the menu item which was created from entry by the given item factory.

ifactory : | a GtkItemFactory
entry : | a GtkItemFactoryEntry

gtk_item_factory_delete_entries ()

void                gtk_item_factory_delete_entries     (GtkItemFactory *ifactory,
                                                         guint n_entries,
                                                         GtkItemFactoryEntry *entries);

Warning

gtk_item_factory_delete_entries has been deprecated since version 2.4 and should not be used in newly-written code.

Deletes the menu items which were created from the entries by the given item factory.

ifactory : | a GtkItemFactory
n_entries : | the length of entries
entries : | an array of GtkItemFactoryEntrys

gtk_item_factory_popup ()

void                gtk_item_factory_popup              (GtkItemFactory *ifactory,
                                                         guint x,
                                                         guint y,
                                                         guint mouse_button,
                                                         guint32 time_);

Warning

gtk_item_factory_popup has been deprecated since version 2.4 and should not be used in newly-written code.

Pops up the menu constructed from the item factory at (x, y).

The mouse_button parameter should be the mouse button pressed to initiate the menu popup. If the menu popup was initiated by something other than a mouse button press, such as a mouse button release or a keypress, mouse_button should be 0.

The time_ parameter should be the time stamp of the event that initiated the popup. If such an event is not available, use gtk_get_current_event_time() instead.

The operation of the mouse_button and the time_ parameter is the same as the button and activation_time parameters for gtk_menu_popup().

ifactory : | a GtkItemFactory of type GTK_TYPE_MENU (see gtk_item_factory_new())
x : | the x position
y : | the y position
mouse_button : | the mouse button which was pressed to initiate the popup
time_ : | the time at which the activation event occurred

gtk_item_factory_popup_with_data ()

void                gtk_item_factory_popup_with_data    (GtkItemFactory *ifactory,
                                                         gpointer popup_data,
                                                         GtkDestroyNotify destroy,
                                                         guint x,
                                                         guint y,
                                                         guint mouse_button,
                                                         guint32 time_);

Warning

gtk_item_factory_popup_with_data has been deprecated since version 2.4 and should not be used in newly-written code.

Pops up the menu constructed from the item factory at (x, y). Callbacks can access the popup_data while the menu is posted via gtk_item_factory_popup_data() and gtk_item_factory_popup_data_from_widget().

The mouse_button parameter should be the mouse button pressed to initiate the menu popup. If the menu popup was initiated by something other than a mouse button press, such as a mouse button release or a keypress, mouse_button should be 0.

The time_ parameter should be the time stamp of the event that initiated the popup. If such an event is not available, use gtk_get_current_event_time() instead.

The operation of the mouse_button and the time_ parameters is the same as the button and activation_time parameters for gtk_menu_popup().

ifactory : | a GtkItemFactory of type GTK_TYPE_MENU (see gtk_item_factory_new())
popup_data : | data available for callbacks while the menu is posted
destroy : | a GtkDestroyNotify function to be called on popup_data when the menu is unposted
x : | the x position
y : | the y position
mouse_button : | the mouse button which was pressed to initiate the popup
time_ : | the time at which the activation event occurred

gtk_item_factory_popup_data ()

gpointer            gtk_item_factory_popup_data         (GtkItemFactory *ifactory);

Warning

gtk_item_factory_popup_data has been deprecated since version 2.4 and should not be used in newly-written code.

Obtains the popup_data which was passed to gtk_item_factory_popup_with_data(). This data is available until the menu is popped down again.

ifactory : | a GtkItemFactory
Returns : | popup_data associated with ifactory

gtk_item_factory_popup_data_from_widget ()

gpointer            gtk_item_factory_popup_data_from_widget
                                                        (GtkWidget *widget);

Warning

gtk_item_factory_popup_data_from_widget has been deprecated since version 2.4 and should not be used in newly-written code.

Obtains the popup_data which was passed to gtk_item_factory_popup_with_data(). This data is available until the menu is popped down again.

widget : | a widget
Returns : | popup_data associated with the item factory from which widget was created, or NULL if widget wasn't created by an item factory

gtk_item_factory_from_path ()

GtkItemFactory*     gtk_item_factory_from_path          (const gchar *path);

Warning

gtk_item_factory_from_path has been deprecated since version 2.4 and should not be used in newly-written code.

Finds an item factory which has been constructed using the "<name>" prefix of path as the path argument for gtk_item_factory_new().

path : | a string starting with a factory path of the form "<name>"
Returns : | the GtkItemFactory created for the given factory path, or NULL

gtk_item_factory_create_menu_entries ()

void                gtk_item_factory_create_menu_entries
                                                        (guint n_entries,
                                                         GtkMenuEntry *entries);

Warning

gtk_item_factory_create_menu_entries has been deprecated since version 2.4 and should not be used in newly-written code.

Creates the menu items from the entries.

n_entries : | the length of entries
entries : | an array of GtkMenuEntrys

gtk_item_factories_path_delete ()

void                gtk_item_factories_path_delete      (const gchar *ifactory_path,
                                                         const gchar *path);

Warning

gtk_item_factories_path_delete has been deprecated since version 2.4 and should not be used in newly-written code.

Deletes all widgets constructed from the specified path.

ifactory_path : | a factory path to prepend to path. May be NULL if path starts with a factory path
path : | a path

gtk_item_factory_set_translate_func ()

void                gtk_item_factory_set_translate_func (GtkItemFactory *ifactory,
                                                         GtkTranslateFunc func,
                                                         gpointer data,
                                                         GtkDestroyNotify notify);

Warning

gtk_item_factory_set_translate_func has been deprecated since version 2.4 and should not be used in newly-written code.

Sets a function to be used for translating the path elements before they are displayed.

ifactory : | a GtkItemFactory
func : | the GtkTranslateFunc function to be used to translate path elements
data : | data to pass to func and notify
notify : | a GtkDestroyNotify function to be called when ifactory is destroyed and when the translation function is changed again


GtkLabel

GtkLabel — A widget that displays a small to medium amount of text

Synopsis

#include <gtk/gtk.h>

                    GtkLabel;
GtkWidget*          gtk_label_new                       (const gchar *str);
void                gtk_label_set_text                  (GtkLabel *label,
                                                         const gchar *str);
void                gtk_label_set_attributes            (GtkLabel *label,
                                                         PangoAttrList *attrs);
void                gtk_label_set_markup                (GtkLabel *label,
                                                         const gchar *str);
void                gtk_label_set_markup_with_mnemonic  (GtkLabel *label,
                                                         const gchar *str);
void                gtk_label_set_pattern               (GtkLabel *label,
                                                         const gchar *pattern);
void                gtk_label_set_justify               (GtkLabel *label,
                                                         GtkJustification jtype);
void                gtk_label_set_ellipsize             (GtkLabel *label,
                                                         PangoEllipsizeMode mode);
void                gtk_label_set_width_chars           (GtkLabel *label,
                                                         gint n_chars);
void                gtk_label_set_max_width_chars       (GtkLabel *label,
                                                         gint n_chars);
void                gtk_label_get                       (GtkLabel *label,
                                                         gchar **str);
guint               gtk_label_parse_uline               (GtkLabel *label,
                                                         const gchar *string);
void                gtk_label_set_line_wrap             (GtkLabel *label,
                                                         gboolean wrap);
void                gtk_label_set_line_wrap_mode        (GtkLabel *label,
                                                         PangoWrapMode wrap_mode);
#define             gtk_label_set
void                gtk_label_get_layout_offsets        (GtkLabel *label,
                                                         gint *x,
                                                         gint *y);
guint               gtk_label_get_mnemonic_keyval       (GtkLabel *label);
gboolean            gtk_label_get_selectable            (GtkLabel *label);
const gchar*        gtk_label_get_text                  (GtkLabel *label);
GtkWidget*          gtk_label_new_with_mnemonic         (const gchar *str);
void                gtk_label_select_region             (GtkLabel *label,
                                                         gint start_offset,
                                                         gint end_offset);
void                gtk_label_set_mnemonic_widget       (GtkLabel *label,
                                                         GtkWidget *widget);
void                gtk_label_set_selectable            (GtkLabel *label,
                                                         gboolean setting);
void                gtk_label_set_text_with_mnemonic    (GtkLabel *label,
                                                         const gchar *str);
PangoAttrList*      gtk_label_get_attributes            (GtkLabel *label);
GtkJustification    gtk_label_get_justify               (GtkLabel *label);
PangoEllipsizeMode  gtk_label_get_ellipsize             (GtkLabel *label);
gint                gtk_label_get_width_chars           (GtkLabel *label);
gint                gtk_label_get_max_width_chars       (GtkLabel *label);
const gchar*        gtk_label_get_label                 (GtkLabel *label);
PangoLayout*        gtk_label_get_layout                (GtkLabel *label);
gboolean            gtk_label_get_line_wrap             (GtkLabel *label);
PangoWrapMode       gtk_label_get_line_wrap_mode        (GtkLabel *label);
GtkWidget*          gtk_label_get_mnemonic_widget       (GtkLabel *label);
gboolean            gtk_label_get_selection_bounds      (GtkLabel *label,
                                                         gint *start,
                                                         gint *end);
gboolean            gtk_label_get_use_markup            (GtkLabel *label);
gboolean            gtk_label_get_use_underline         (GtkLabel *label);
gboolean            gtk_label_get_single_line_mode      (GtkLabel *label);
gdouble             gtk_label_get_angle                 (GtkLabel *label);
void                gtk_label_set_label                 (GtkLabel *label,
                                                         const gchar *str);
void                gtk_label_set_use_markup            (GtkLabel *label,
                                                         gboolean setting);
void                gtk_label_set_use_underline         (GtkLabel *label,
                                                         gboolean setting);
void                gtk_label_set_single_line_mode      (GtkLabel *label,
                                                         gboolean single_line_mode);
void                gtk_label_set_angle                 (GtkLabel *label,
                                                         gdouble angle);

Object Hierarchy

  GObject
   +----GInitiallyUnowned
         +----GtkObject
               +----GtkWidget
                     +----GtkMisc
                           +----GtkLabel
                                 +----GtkAccelLabel
                                 +----GtkTipsQuery

Implemented Interfaces

GtkLabel implements AtkImplementorIface.

Properties

  "angle"                    gdouble               : Read / Write
  "attributes"               PangoAttrList         : Read / Write
  "cursor-position"          gint                  : Read
  "ellipsize"                PangoEllipsizeMode    : Read / Write
  "justify"                  GtkJustification      : Read / Write
  "label"                    gchararray            : Read / Write
  "max-width-chars"          gint                  : Read / Write
  "mnemonic-keyval"          guint                 : Read
  "mnemonic-widget"          GtkWidget             : Read / Write
  "pattern"                  gchararray            : Write
  "selectable"               gboolean              : Read / Write
  "selection-bound"          gint                  : Read
  "single-line-mode"         gboolean              : Read / Write
  "use-markup"               gboolean              : Read / Write
  "use-underline"            gboolean              : Read / Write
  "width-chars"              gint                  : Read / Write
  "wrap"                     gboolean              : Read / Write
  "wrap-mode"                PangoWrapMode         : Read / Write

Signals

  "copy-clipboard"                                 : Run Last / Action
  "move-cursor"                                    : Run Last / Action
  "populate-popup"                                 : Run Last

Description

The GtkLabel widget displays a small amount of text. As the name implies, most labels are used to label another widget such as a GtkButton, a GtkMenuItem, or a GtkOptionMenu.

Mnemonics

Labels may contain mnemonics. Mnemonics are underlined characters in the label, used for keyboard navigation. Mnemonics are created by providing a string with an underscore before the mnemonic character, such as "_File", to the functions gtk_label_new_with_mnemonic() or gtk_label_set_text_with_mnemonic().

Mnemonics automatically activate any activatable widget the label is inside, such as a GtkButton; if the label is not inside the mnemonic's target widget, you have to tell the label about the target using gtk_label_set_mnemonic_widget(). Here's a simple example where the label is inside a button:

  /* Pressing Alt+H will activate this button */
  button = gtk_button_new ();
  label = gtk_label_new_with_mnemonic ("_Hello");
  gtk_container_add (GTK_CONTAINER (button), label);

There's a convenience function to create buttons with a mnemonic label already inside:

  /* Pressing Alt+H will activate this button */
  button = gtk_button_new_with_mnemonic ("_Hello");

To create a mnemonic for a widget alongside the label, such as a GtkEntry, you have to point the label at the entry with gtk_label_set_mnemonic_widget():

  /* Pressing Alt+H will focus the entry */
  entry = gtk_entry_new ();
  label = gtk_label_new_with_mnemonic ("_Hello");
  gtk_label_set_mnemonic_widget (GTK_LABEL (label), entry);

Markup (styled text)

To make it easy to format text in a label (changing colors, fonts, etc.), label text can be provided in a simple markup format. Here's how to create a label with a small font:

  label = gtk_label_new (NULL);
  gtk_label_set_markup (GTK_LABEL (label), "<small>Small text</small>");

(See complete documentation of available tags in the Pango manual.)

The markup passed to gtk_label_set_markup() must be valid; for example, literal </>/& characters must be escaped as &lt;, &gt;, and &amp;. If you pass text obtained from the user, file, or a network to gtk_label_set_markup(), you'll want to escape it with g_markup_escape_text() or g_markup_printf_escaped().

Markup strings are just a convenient way to set the PangoAttrList on a label; gtk_label_set_attributes() may be a simpler way to set attributes in some cases. Be careful though; PangoAttrList tends to cause internationalization problems, unless you're applying attributes to the entire string (i.e. unless you set the range of each attribute to [0, G_MAXINT)). The reason is that specifying the start_index and end_index for a PangoAttribute requires knowledge of the exact string being displayed, so translations will cause problems.

Selectable labels

Labels can be made selectable with gtk_label_set_selectable(). Selectable labels allow the user to copy the label contents to the clipboard. Only labels that contain useful-to-copy information — such as error messages — should be made selectable.

Text layout

A label can contain any number of paragraphs, but will have performance problems if it contains more than a small number. Paragraphs are separated by newlines or other paragraph separators understood by Pango.

Labels can automatically wrap text if you call gtk_label_set_line_wrap().

gtk_label_set_justify() sets how the lines in a label align with one another. If you want to set how the label as a whole aligns in its available space, see gtk_misc_set_alignment().

Details

GtkLabel

typedef struct _GtkLabel GtkLabel;

This should not be accessed directly. Use the accessor functions as described below.

gtk_label_new ()

GtkWidget*          gtk_label_new                       (const gchar *str);

Creates a new label with the given text inside it. You can pass NULL to get an empty label widget.

str : | The text of the label
Returns : | the new GtkLabel

gtk_label_set_text ()

void                gtk_label_set_text                  (GtkLabel *label,
                                                         const gchar *str);

Sets the text within the GtkLabel widget. It overwrites any text that was there before.

This will also clear any previously set mnemonic accelerators.

label : | a GtkLabel
str : | The text you want to set.

gtk_label_set_attributes ()

void                gtk_label_set_attributes            (GtkLabel *label,
                                                         PangoAttrList *attrs);

Sets a PangoAttrList; the attributes in the list are applied to the label text. The attributes set with this function will be ignored if the "use_underline" property or the "use_markup" property is TRUE.

label : | a GtkLabel
attrs : | a PangoAttrList

gtk_label_set_markup ()

void                gtk_label_set_markup                (GtkLabel *label,
                                                         const gchar *str);

Parses str which is marked up with the Pango text markup language, setting the label's text and attribute list based on the parse results. If the str is external data, you may need to escape it with g_markup_escape_text() or g_markup_printf_escaped():

char *markup;

markup = g_markup_printf_escaped ("<span style=\"italic\">%s</span>", str);
gtk_label_set_markup (GTK_LABEL (label), markup);
g_free (markup);

label : | a GtkLabel
str : | a markup string (see Pango markup format)

gtk_label_set_markup_with_mnemonic ()

void                gtk_label_set_markup_with_mnemonic  (GtkLabel *label,
                                                         const gchar *str);

Parses str which is marked up with the Pango text markup language, setting the label's text and attribute list based on the parse results. If characters in str are preceded by an underscore, they are underlined indicating that they represent a keyboard accelerator called a mnemonic.

The mnemonic key can be used to activate another widget, chosen automatically, or explicitly using gtk_label_set_mnemonic_widget().

label : | a GtkLabel
str : | a markup string (see Pango markup format)

gtk_label_set_pattern ()

void                gtk_label_set_pattern               (GtkLabel *label,
                                                         const gchar *pattern);

The pattern of underlines you want under the existing text within the GtkLabel widget. For example if the current text of the label says "FooBarBaz" passing a pattern of "___ ___" will underline "Foo" and "Baz" but not "Bar".

label : | The GtkLabel you want to set the pattern to.
pattern : | The pattern as described above.

gtk_label_set_justify ()

void                gtk_label_set_justify               (GtkLabel *label,
                                                         GtkJustification jtype);

Sets the alignment of the lines in the text of the label relative to each other. GTK_JUSTIFY_LEFT is the default value when the widget is first created with gtk_label_new(). If you instead want to set the alignment of the label as a whole, use gtk_misc_set_alignment() instead. gtk_label_set_justify() has no effect on labels containing only a single line.

label : | a GtkLabel
jtype : | a GtkJustification

gtk_label_set_ellipsize ()

void                gtk_label_set_ellipsize             (GtkLabel *label,
                                                         PangoEllipsizeMode mode);

Sets the mode used to ellipsize (add an ellipsis: "...") to the text if there is not enough space to render the entire string.

label : | a GtkLabel
mode : | a PangoEllipsizeMode

Since 2.6

gtk_label_set_width_chars ()

void                gtk_label_set_width_chars           (GtkLabel *label,
                                                         gint n_chars);

Sets the desired width in characters of label to n_chars.

label : | a GtkLabel
n_chars : | the new desired width, in characters.

Since 2.6

gtk_label_set_max_width_chars ()

void                gtk_label_set_max_width_chars       (GtkLabel *label,
                                                         gint n_chars);

Sets the desired maximum width in characters of label to n_chars.

label : | a GtkLabel
n_chars : | the new desired maximum width, in characters.

Since 2.6

gtk_label_get ()

void                gtk_label_get                       (GtkLabel *label,
                                                         gchar **str);

Warning

gtk_label_get is deprecated and should not be used in newly-written code.

Gets the current string of text within the GtkLabel and writes it to the given str argument. It does not make a copy of this string so you must not write to it.

label : | The GtkLabel widget you want to get the text from.
str : | The reference to the pointer you want to point to the text.

gtk_label_parse_uline ()

guint               gtk_label_parse_uline               (GtkLabel *label,
                                                         const gchar *string);

Warning

gtk_label_parse_uline is deprecated and should not be used in newly-written code.

Parses the given string for underscores and converts the next character to an underlined character. The last character that was underlined will have its lower-cased accelerator keyval returned (i.e. "_File" would return the keyval for "f". This is probably only used within the Gtk+ library itself for menu items and such.

label : | The GtkLabel you want to affect.
string : | The string you want to parse for underlines.
Returns : | The lowercase keyval of the last character underlined.

gtk_label_set_line_wrap ()

void                gtk_label_set_line_wrap             (GtkLabel *label,
                                                         gboolean wrap);

Toggles line wrapping within the GtkLabel widget. TRUE makes it break lines if text exceeds the widget's size. FALSE lets the text get cut off by the edge of the widget if it exceeds the widget size.

Note that setting line wrapping to TRUE does not make the label wrap at its parent container's width, because GTK+ widgets conceptually can't make their requisition depend on the parent container's size. For a label that wraps at a specific position, set the label's width using gtk_widget_set_size_request().

label : | a GtkLabel
wrap : | the setting

gtk_label_set_line_wrap_mode ()

void                gtk_label_set_line_wrap_mode        (GtkLabel *label,
                                                         PangoWrapMode wrap_mode);

If line wrapping is on (see gtk_label_set_line_wrap()) this controls how the line wrapping is done. The default is PANGO_WRAP_WORD which means wrap on word boundaries.

label : | a GtkLabel
wrap_mode : | the line wrapping mode

Since 2.10

gtk_label_set

#define  gtk_label_set           gtk_label_set_text

Warning

gtk_label_set is deprecated and should not be used in newly-written code.

Aliases gtk_label_set_text(). Probably used for backward compatibility with Gtk+ 1.0.x.

gtk_label_get_layout_offsets ()

void                gtk_label_get_layout_offsets        (GtkLabel *label,
                                                         gint *x,
                                                         gint *y);

Obtains the coordinates where the label will draw the PangoLayout representing the text in the label; useful to convert mouse events into coordinates inside the PangoLayout, e.g. to take some action if some part of the label is clicked. Of course you will need to create a GtkEventBox to receive the events, and pack the label inside it, since labels are a GTK_NO_WINDOW widget. Remember when using the PangoLayout functions you need to convert to and from pixels using PANGO_PIXELS() or PANGO_SCALE.

label : | a GtkLabel
x : | location to store X offset of layout, or NULL
y : | location to store Y offset of layout, or NULL

gtk_label_get_mnemonic_keyval ()

guint               gtk_label_get_mnemonic_keyval       (GtkLabel *label);

If the label has been set so that it has an mnemonic key this function returns the keyval used for the mnemonic accelerator. If there is no mnemonic set up it returns GDK_VoidSymbol.

label : | a GtkLabel
Returns : | GDK keyval usable for accelerators, or GDK_VoidSymbol

gtk_label_get_selectable ()

gboolean            gtk_label_get_selectable            (GtkLabel *label);

Gets the value set by gtk_label_set_selectable().

label : | a GtkLabel
Returns : | TRUE if the user can copy text from the label

gtk_label_get_text ()

const gchar*        gtk_label_get_text                  (GtkLabel *label);

Fetches the text from a label widget, as displayed on the screen. This does not include any embedded underlines indicating mnemonics or Pango markup. (See gtk_label_get_label())

label : | a GtkLabel
Returns : | the text in the label widget. This is the internal string used by the label, and must not be modified.

gtk_label_new_with_mnemonic ()

GtkWidget*          gtk_label_new_with_mnemonic         (const gchar *str);

Creates a new GtkLabel, containing the text in str.

If characters in str are preceded by an underscore, they are underlined. If you need a literal underscore character in a label, use '__' (two underscores). The first underlined character represents a keyboard accelerator called a mnemonic. The mnemonic key can be used to activate another widget, chosen automatically, or explicitly using gtk_label_set_mnemonic_widget().

If gtk_label_set_mnemonic_widget() is not called, then the first activatable ancestor of the GtkLabel will be chosen as the mnemonic widget. For instance, if the label is inside a button or menu item, the button or menu item will automatically become the mnemonic widget and be activated by the mnemonic.

str : | The text of the label, with an underscore in front of the mnemonic character
Returns : | the new GtkLabel

gtk_label_select_region ()

void                gtk_label_select_region             (GtkLabel *label,
                                                         gint start_offset,
                                                         gint end_offset);

Selects a range of characters in the label, if the label is selectable. See gtk_label_set_selectable(). If the label is not selectable, this function has no effect. If start_offset or end_offset are -1, then the end of the label will be substituted.

label : | a GtkLabel
start_offset : | start offset (in characters not bytes)
end_offset : | end offset (in characters not bytes)

gtk_label_set_mnemonic_widget ()

void                gtk_label_set_mnemonic_widget       (GtkLabel *label,
                                                         GtkWidget *widget);

If the label has been set so that it has an mnemonic key (using i.e. gtk_label_set_markup_with_mnemonic(), gtk_label_set_text_with_mnemonic(), gtk_label_new_with_mnemonic() or the "use_underline" property) the label can be associated with a widget that is the target of the mnemonic. When the label is inside a widget (like a GtkButton or a GtkNotebook tab) it is automatically associated with the correct widget, but sometimes (i.e. when the target is a GtkEntry next to the label) you need to set it explicitly using this function.

The target widget will be accelerated by emitting "mnemonic_activate" on it. The default handler for this signal will activate the widget if there are no mnemonic collisions and toggle focus between the colliding widgets otherwise.

label : | a GtkLabel
widget : | the target GtkWidget

gtk_label_set_selectable ()

void                gtk_label_set_selectable            (GtkLabel *label,
                                                         gboolean setting);

Selectable labels allow the user to select text from the label, for copy-and-paste.

label : | a GtkLabel
setting : | TRUE to allow selecting text in the label

gtk_label_set_text_with_mnemonic ()

void                gtk_label_set_text_with_mnemonic    (GtkLabel *label,
                                                         const gchar *str);

Sets the label's text from the string str. If characters in str are preceded by an underscore, they are underlined indicating that they represent a keyboard accelerator called a mnemonic. The mnemonic key can be used to activate another widget, chosen automatically, or explicitly using gtk_label_set_mnemonic_widget().

label : | a GtkLabel
str : | a string

gtk_label_get_attributes ()

PangoAttrList*      gtk_label_get_attributes            (GtkLabel *label);

Gets the attribute list that was set on the label using gtk_label_set_attributes(), if any. This function does not reflect attributes that come from the labels markup (see gtk_label_set_markup()). If you want to get the effective attributes for the label, use pango_layout_get_attribute (gtk_label_get_layout (label)).

label : | a GtkLabel
Returns : | the attribute list, or NULL if none was set.

gtk_label_get_justify ()

GtkJustification    gtk_label_get_justify               (GtkLabel *label);

Returns the justification of the label. See gtk_label_set_justify().

label : | a GtkLabel
Returns : | GtkJustification

gtk_label_get_ellipsize ()

PangoEllipsizeMode  gtk_label_get_ellipsize             (GtkLabel *label);

Returns the ellipsizing position of the label. See gtk_label_set_ellipsize().

label : | a GtkLabel
Returns : | PangoEllipsizeMode

Since 2.6

gtk_label_get_width_chars ()

gint                gtk_label_get_width_chars           (GtkLabel *label);

Retrieves the desired width of label, in characters. See gtk_label_set_width_chars().

label : | a GtkLabel
Returns : | the width of the label in characters.

Since 2.6

gtk_label_get_max_width_chars ()

gint                gtk_label_get_max_width_chars       (GtkLabel *label);

Retrieves the desired maximum width of label, in characters. See gtk_label_set_width_chars().

label : | a GtkLabel
Returns : | the maximum width of the label in characters.

Since 2.6

gtk_label_get_label ()

const gchar*        gtk_label_get_label                 (GtkLabel *label);

Fetches the text from a label widget including any embedded underlines indicating mnemonics and Pango markup. (See gtk_label_get_text()).

label : | a GtkLabel
Returns : | the text of the label widget. This string is owned by the widget and must not be modified or freed.

gtk_label_get_layout ()

PangoLayout*        gtk_label_get_layout                (GtkLabel *label);

Gets the PangoLayout used to display the label. The layout is useful to e.g. convert text positions to pixel positions, in combination with gtk_label_get_layout_offsets(). The returned layout is owned by the label so need not be freed by the caller.

label : | a GtkLabel
Returns : | the PangoLayout for this label

gtk_label_get_line_wrap ()

gboolean            gtk_label_get_line_wrap             (GtkLabel *label);

Returns whether lines in the label are automatically wrapped. See gtk_label_set_line_wrap().

label : | a GtkLabel
Returns : | TRUE if the lines of the label are automatically wrapped.

gtk_label_get_line_wrap_mode ()

PangoWrapMode       gtk_label_get_line_wrap_mode        (GtkLabel *label);

Returns line wrap mode used by the label. See gtk_label_set_line_wrap_mode().

label : | a GtkLabel
Returns : | TRUE if the lines of the label are automatically wrapped.

Since 2.10

gtk_label_get_mnemonic_widget ()

GtkWidget*          gtk_label_get_mnemonic_widget       (GtkLabel *label);

Retrieves the target of the mnemonic (keyboard shortcut) of this label. See gtk_label_set_mnemonic_widget().

label : | a GtkLabel
Returns : | the target of the label's mnemonic, or NULL if none has been set and the default algorithm will be used.

gtk_label_get_selection_bounds ()

gboolean            gtk_label_get_selection_bounds      (GtkLabel *label,
                                                         gint *start,
                                                         gint *end);

Gets the selected range of characters in the label, returning TRUE if there's a selection.

label : | a GtkLabel
start : | return location for start of selection, as a character offset
end : | return location for end of selection, as a character offset
Returns : | TRUE if selection is non-empty

gtk_label_get_use_markup ()

gboolean            gtk_label_get_use_markup            (GtkLabel *label);

Returns whether the label's text is interpreted as marked up with the Pango text markup language. See gtk_label_set_use_markup().

label : | a GtkLabel
Returns : | TRUE if the label's text will be parsed for markup.

gtk_label_get_use_underline ()

gboolean            gtk_label_get_use_underline         (GtkLabel *label);

Returns whether an embedded underline in the label indicates a mnemonic. See gtk_label_set_use_underline().

label : | a GtkLabel
Returns : | TRUE whether an embedded underline in the label indicates the mnemonic accelerator keys.

gtk_label_get_single_line_mode ()

gboolean            gtk_label_get_single_line_mode      (GtkLabel *label);

Returns whether the label is in single line mode.

label : | a GtkLabel
Returns : | TRUE when the label is in single line mode.

Since 2.6

gtk_label_get_angle ()

gdouble             gtk_label_get_angle                 (GtkLabel *label);

Gets the angle of rotation for the label. See gtk_label_set_angle.

label : | a GtkLabel
Returns : | the angle of rotation for the label

Since 2.6

gtk_label_set_label ()

void                gtk_label_set_label                 (GtkLabel *label,
                                                         const gchar *str);

Sets the text of the label. The label is interpreted as including embedded underlines and/or Pango markup depending on the values of label->use_underline and label->use_markup.

label : | a GtkLabel
str : | the new text to set for the label

gtk_label_set_use_markup ()

void                gtk_label_set_use_markup            (GtkLabel *label,
                                                         gboolean setting);

Sets whether the text of the label contains markup in Pango's text markup language. See gtk_label_set_markup().

label : | a GtkLabel
setting : | TRUE if the label's text should be parsed for markup.

gtk_label_set_use_underline ()

void                gtk_label_set_use_underline         (GtkLabel *label,
                                                         gboolean setting);

If true, an underline in the text indicates the next character should be used for the mnemonic accelerator key.

label : | a GtkLabel
setting : | TRUE if underlines in the text indicate mnemonics

gtk_label_set_single_line_mode ()

void                gtk_label_set_single_line_mode      (GtkLabel *label,
                                                         gboolean single_line_mode);

Sets whether the label is in single line mode.

label : | a GtkLabel
single_line_mode : | TRUE if the label should be in single line mode

Since 2.6

gtk_label_set_angle ()

void                gtk_label_set_angle                 (GtkLabel *label,
                                                         gdouble angle);

Sets the angle of rotation for the label. An angle of 90 reads from from bottom to top, an angle of 270, from top to bottom. The angle setting for the label is ignored if the label is selectable, wrapped, or ellipsized.

label : | a GtkLabel
angle : | the angle that the baseline of the label makes with the horizontal, in degrees, measured counterclockwise

Since 2.6

Property Details

The "angle" property

  "angle"                    gdouble               : Read / Write

The angle that the baseline of the label makes with the horizontal, in degrees, measured counterclockwise. An angle of 90 reads from from bottom to top, an angle of 270, from top to bottom. Ignored if the label is selectable, wrapped, or ellipsized.

Allowed values: [0,360]

Default value: 0

Since 2.6

The "attributes" property

  "attributes"               PangoAttrList         : Read / Write

A list of style attributes to apply to the text of the label.

The "cursor-position" property

  "cursor-position"          gint                  : Read

The current position of the insertion cursor in chars.

Allowed values: >= 0

Default value: 0

The "ellipsize" property

  "ellipsize"                PangoEllipsizeMode    : Read / Write

The preferred place to ellipsize the string, if the label does not have enough room to display the entire string, specified as a PangoEllisizeMode.

Note that setting this property to a value other than PANGO_ELLIPSIZE_NONE has the side-effect that the label requests only enough space to display the ellipsis "...". In particular, this means that ellipsizing labels don't work well in notebook tabs, unless the tab's ::tab-expand property is set to TRUE. Other means to set a label's width are gtk_widget_set_size_request() and gtk_label_set_width_chars().

Default value: PANGO_ELLIPSIZE_NONE

Since 2.6

The "justify" property

  "justify"                  GtkJustification      : Read / Write

The alignment of the lines in the text of the label relative to each other. This does NOT affect the alignment of the label within its allocation. See GtkMisc::xalign for that.

Default value: GTK_JUSTIFY_LEFT

The "label" property

  "label"                    gchararray            : Read / Write

The text of the label.

Default value: NULL

The "max-width-chars" property

  "max-width-chars"          gint                  : Read / Write

The desired maximum width of the label, in characters. If this property is set to -1, the width will be calculated automatically, otherwise the label will request space for no more than the requested number of characters. If the width-chars property is set to a positive value, then the max-width-chars property is ignored.

Allowed values: >= -1

Default value: -1

Since 2.6

The "mnemonic-keyval" property

  "mnemonic-keyval"          guint                 : Read

The mnemonic accelerator key for this label.

Default value: 16777215

The "mnemonic-widget" property

  "mnemonic-widget"          GtkWidget             : Read / Write

The widget to be activated when the label's mnemonic key is pressed.

The "pattern" property

  "pattern"                  gchararray            : Write

A string with _ characters in positions correspond to characters in the text to underline.

Default value: NULL

The "selectable" property

  "selectable"               gboolean              : Read / Write

Whether the label text can be selected with the mouse.

Default value: FALSE

The "selection-bound" property

  "selection-bound"          gint                  : Read

The position of the opposite end of the selection from the cursor in chars.

Allowed values: >= 0

Default value: 0

The "single-line-mode" property

  "single-line-mode"         gboolean              : Read / Write

Whether the label is in single line mode. In single line mode, the height of the label does not depend on the actual text, it is always set to ascent + descent of the font. This can be an advantage in situations where resizing the label because of text changes would be distracting, e.g. in a statusbar.

Default value: FALSE

Since 2.6

The "use-markup" property

  "use-markup"               gboolean              : Read / Write

The text of the label includes XML markup. See pango_parse_markup().

Default value: FALSE

The "use-underline" property

  "use-underline"            gboolean              : Read / Write

If set, an underline in the text indicates the next character should be used for the mnemonic accelerator key.

Default value: FALSE

The "width-chars" property

  "width-chars"              gint                  : Read / Write

The desired width of the label, in characters. If this property is set to -1, the width will be calculated automatically, otherwise the label will request either 3 characters or the property value, whichever is greater. If the width-chars property is set to a positive value, then the max-width-chars property is ignored.

Allowed values: >= -1

Default value: -1

Since 2.6

The "wrap" property

  "wrap"                     gboolean              : Read / Write

If set, wrap lines if the text becomes too wide.

Default value: FALSE

The "wrap-mode" property

  "wrap-mode"                PangoWrapMode         : Read / Write

If line wrapping is on (see the wrap property) this controls how the line wrapping is done. The default is PANGO_WRAP_WORD which means wrap on word boundaries.

Default value: PANGO_WRAP_WORD

Since 2.10

Signal Details

The "copy-clipboard" signal

void                user_function                      (GtkLabel *label,
                                                        gpointer  user_data)      : Run Last / Action

label : | the object which received the signal.
user_data : | user data set when the signal handler was connected.

The "move-cursor" signal

void                user_function                      (GtkLabel       *label,
                                                        GtkMovementStep arg1,
                                                        gint            arg2,
                                                        gboolean        arg3,
                                                        gpointer        user_data)      : Run Last / Action

label : | the object which received the signal.
arg1 : |
arg2 : |
arg3 : |
user_data : | user data set when the signal handler was connected.

The "populate-popup" signal

void                user_function                      (GtkLabel *label,
                                                        GtkMenu  *arg1,
                                                        gpointer  user_data)      : Run Last

label : | the object which received the signal.
arg1 : |
user_data : | user data set when the signal handler was connected.


GtkLayout

GtkLayout — Infinite scrollable area containing child widgets and/or custom drawing

Synopsis

#include <gtk/gtk.h>

                    GtkLayout;
GtkWidget*          gtk_layout_new                      (GtkAdjustment *hadjustment,
                                                         GtkAdjustment *vadjustment);
void                gtk_layout_put                      (GtkLayout *layout,
                                                         GtkWidget *child_widget,
                                                         gint x,
                                                         gint y);
void                gtk_layout_move                     (GtkLayout *layout,
                                                         GtkWidget *child_widget,
                                                         gint x,
                                                         gint y);
void                gtk_layout_set_size                 (GtkLayout *layout,
                                                         guint width,
                                                         guint height);
void                gtk_layout_get_size                 (GtkLayout *layout,
                                                         guint *width,
                                                         guint *height);
void                gtk_layout_freeze                   (GtkLayout *layout);
void                gtk_layout_thaw                     (GtkLayout *layout);
GtkAdjustment*      gtk_layout_get_hadjustment          (GtkLayout *layout);
GtkAdjustment*      gtk_layout_get_vadjustment          (GtkLayout *layout);
void                gtk_layout_set_hadjustment          (GtkLayout *layout,
                                                         GtkAdjustment *adjustment);
void                gtk_layout_set_vadjustment          (GtkLayout *layout,
                                                         GtkAdjustment *adjustment);

Object Hierarchy

  GObject
   +----GInitiallyUnowned
         +----GtkObject
               +----GtkWidget
                     +----GtkContainer
                           +----GtkLayout

Implemented Interfaces

GtkLayout implements AtkImplementorIface.

Properties

  "hadjustment"              GtkAdjustment         : Read / Write
  "height"                   guint                 : Read / Write
  "vadjustment"              GtkAdjustment         : Read / Write
  "width"                    guint                 : Read / Write

Child Properties

  "x"                        gint                  : Read / Write
  "y"                        gint                  : Read / Write

Signals

  "set-scroll-adjustments"                         : Run Last / Action

Description

GtkLayout is similar to GtkDrawingArea in that it's a "blank slate" and doesn't do anything but paint a blank background by default. It's different in that it supports scrolling natively (you can add it to a GtkScrolledWindow), and it can contain child widgets, since it's a GtkContainer. However if you're just going to draw, a GtkDrawingArea is a better choice since it has lower overhead.

When handling expose events on a GtkLayout, you must draw to GTK_LAYOUT (layout)->bin_window, rather than to GTK_WIDGET (layout)->window, as you would for a drawing area.

Details

GtkLayout

typedef struct {
  GdkWindow *bin_window;
} GtkLayout;

gtk_layout_new ()

GtkWidget*          gtk_layout_new                      (GtkAdjustment *hadjustment,
                                                         GtkAdjustment *vadjustment);

Creates a new GtkLayout. Unless you have a specific adjustment you'd like the layout to use for scrolling, pass NULL for hadjustment and vadjustment.

hadjustment : | horizontal scroll adjustment, or NULL
vadjustment : | vertical scroll adjustment, or NULL
Returns : | a new GtkLayout

gtk_layout_put ()

void                gtk_layout_put                      (GtkLayout *layout,
                                                         GtkWidget *child_widget,
                                                         gint x,
                                                         gint y);

Adds child_widget to layout, at position (x,y). layout becomes the new parent container of child_widget.

layout : | a GtkLayout
child_widget : | child widget
x : | X position of child widget
y : | Y position of child widget

gtk_layout_move ()

void                gtk_layout_move                     (GtkLayout *layout,
                                                         GtkWidget *child_widget,
                                                         gint x,
                                                         gint y);

Moves a current child of layout to a new position.

layout : | a GtkLayout
child_widget : | a current child of layout
x : | X position to move to
y : | Y position to move to

gtk_layout_set_size ()

void                gtk_layout_set_size                 (GtkLayout *layout,
                                                         guint width,
                                                         guint height);

Sets the size of the scrollable area of the layout.

layout : | a GtkLayout
width : | width of entire scrollable area
height : | height of entire scrollable area

gtk_layout_get_size ()

void                gtk_layout_get_size                 (GtkLayout *layout,
                                                         guint *width,
                                                         guint *height);

Gets the size that has been set on the layout, and that determines the total extents of the layout's scrollbar area. See gtk_layout_set_size().

layout : | a GtkLayout
width : | location to store the width set on layout, or NULL
height : | location to store the height set on layout, or NULL

gtk_layout_freeze ()

void                gtk_layout_freeze                   (GtkLayout *layout);

Warning

gtk_layout_freeze is deprecated and should not be used in newly-written code.

This is a deprecated function, it doesn't do anything useful.

layout : a GtkLayout

gtk_layout_thaw ()

void                gtk_layout_thaw                     (GtkLayout *layout);

Warning

gtk_layout_thaw is deprecated and should not be used in newly-written code.

This is a deprecated function, it doesn't do anything useful.

layout : a GtkLayout

gtk_layout_get_hadjustment ()

GtkAdjustment*      gtk_layout_get_hadjustment          (GtkLayout *layout);

This function should only be called after the layout has been placed in a GtkScrolledWindow or otherwise configured for scrolling. It returns the GtkAdjustment used for communication between the horizontal scrollbar and layout.

See GtkScrolledWindow, GtkScrollbar, GtkAdjustment for details.

layout : | a GtkLayout
Returns : | horizontal scroll adjustment

gtk_layout_get_vadjustment ()

GtkAdjustment*      gtk_layout_get_vadjustment          (GtkLayout *layout);

This function should only be called after the layout has been placed in a GtkScrolledWindow or otherwise configured for scrolling. It returns the GtkAdjustment used for communication between the vertical scrollbar and layout.

See GtkScrolledWindow, GtkScrollbar, GtkAdjustment for details.

layout : | a GtkLayout
Returns : | vertical scroll adjustment

gtk_layout_set_hadjustment ()

void                gtk_layout_set_hadjustment          (GtkLayout *layout,
                                                         GtkAdjustment *adjustment);

Sets the horizontal scroll adjustment for the layout.

See GtkScrolledWindow, GtkScrollbar, GtkAdjustment for details.

layout : | a GtkLayout
adjustment : | new scroll adjustment

gtk_layout_set_vadjustment ()

void                gtk_layout_set_vadjustment          (GtkLayout *layout,
                                                         GtkAdjustment *adjustment);

Sets the vertical scroll adjustment for the layout.

See GtkScrolledWindow, GtkScrollbar, GtkAdjustment for details.

layout : | a GtkLayout
adjustment : | new scroll adjustment

Property Details

The "hadjustment" property

  "hadjustment"              GtkAdjustment         : Read / Write

The GtkAdjustment for the horizontal position.

The "height" property

  "height"                   guint                 : Read / Write

The height of the layout.

Allowed values: <= G_MAXINT

Default value: 100

The "vadjustment" property

  "vadjustment"              GtkAdjustment         : Read / Write

The GtkAdjustment for the vertical position.

The "width" property

  "width"                    guint                 : Read / Write

The width of the layout.

Allowed values: <= G_MAXINT

Default value: 100

Child Property Details

The "x" child property

  "x"                        gint                  : Read / Write

X position of child widget.

Default value: 0

The "y" child property

  "y"                        gint                  : Read / Write

Y position of child widget.

Default value: 0

Signal Details

The "set-scroll-adjustments" signal

void                user_function                      (GtkLayout     *layout,
                                                        GtkAdjustment *arg1,
                                                        GtkAdjustment *arg2,
                                                        gpointer       user_data)      : Run Last / Action

layout : | the object which received the signal.
arg1 : |
arg2 : |
user_data : | user data set when the signal handler was connected.

See Also

GtkDrawingArea, GtkScrolledWindow


GtkLinkButton

GtkLinkButton — Create buttons bound to a URL

Synopsis

#include <gtk/gtk.h>

                    GtkLinkButton;
GtkWidget*          gtk_link_button_new                 (const gchar *uri);
GtkWidget*          gtk_link_button_new_with_label      (const gchar *uri,
                                                         const gchar *label);
const gchar*        gtk_link_button_get_uri             (GtkLinkButton *link_button);
void                gtk_link_button_set_uri             (GtkLinkButton *link_button,
                                                         const gchar *uri);
void                (*GtkLinkButtonUriFunc)             (GtkLinkButton *button,
                                                         const gchar *link,
                                                         gpointer user_data);
GtkLinkButtonUriFunc gtk_link_button_set_uri_hook       (GtkLinkButtonUriFunc func,
                                                         gpointer data,
                                                         GDestroyNotify destroy);

Object Hierarchy

  GObject
   +----GInitiallyUnowned
         +----GtkObject
               +----GtkWidget
                     +----GtkContainer
                           +----GtkBin
                                 +----GtkButton
                                       +----GtkLinkButton

Implemented Interfaces

GtkLinkButton implements AtkImplementorIface.

Properties

  "uri"                      gchararray            : Read / Write

Description

A GtkLinkButton is a GtkButton with a hyperlink, similar to the one used by web browsers, which triggers an action when clicked. It is useful to show quick links to resources.

A link button is created by calling either gtk_link_button_new() or gtk_link_button_new_with_label(). If using the former, the URI you pass to the constructor is used as a label for the widget.

The URI bound to a GtkLinkButton can be set specifically using gtk_link_button_set_uri(), and retrieved using gtk_link_button_get_uri().

GtkLinkButton offers a global hook, which is called when the used clicks on it: see gtk_link_button_set_uri_hook().

GtkLinkButton was added in GTK+ 2.10.

Details

GtkLinkButton

typedef struct _GtkLinkButton GtkLinkButton;

The GtkLinkButton struct contains private data only, and should be manipulated using the functions below.

gtk_link_button_new ()

GtkWidget*          gtk_link_button_new                 (const gchar *uri);

Creates a new GtkLinkButton with the URI as its text.

uri : | a valid URI
Returns : | a new link button widget.

Since 2.10

gtk_link_button_new_with_label ()

GtkWidget*          gtk_link_button_new_with_label      (const gchar *uri,
                                                         const gchar *label);

Creates a new GtkLinkButton containing a label.

uri : | a valid URI
label : | the text of the button
Returns : | a new link button widget.

Since 2.10

gtk_link_button_get_uri ()

const gchar*        gtk_link_button_get_uri             (GtkLinkButton *link_button);

Retrieves the URI set using gtk_link_button_set_uri().

link_button : | a GtkLinkButton
Returns : | a valid URI. The returned string is owned by the link button and should not be modified or freed.

Since 2.10

gtk_link_button_set_uri ()

void                gtk_link_button_set_uri             (GtkLinkButton *link_button,
                                                         const gchar *uri);

Sets uri as the URI where the GtkLinkButton points.

link_button : | a GtkLinkButton
uri : | a valid URI

Since 2.10

GtkLinkButtonUriFunc ()

void                (*GtkLinkButtonUriFunc)             (GtkLinkButton *button,
                                                         const gchar *link,
                                                         gpointer user_data);

The type of a function which is called when the GtkLinkButton is clicked.

button : | the GtkLinkButton which was clicked
link : | the URI to which the clicked GtkLinkButton points
user_data : |

gtk_link_button_set_uri_hook ()

GtkLinkButtonUriFunc gtk_link_button_set_uri_hook       (GtkLinkButtonUriFunc func,
                                                         gpointer data,
                                                         GDestroyNotify destroy);

Sets func as the function that should be invoked every time a user clicks a GtkLinkButton. This function is called before every callback registered for the "clicked" signal.

func : | a function called each time a GtkLinkButton is clicked, or NULL
data : | user data to be passed to func, or NULL
destroy : | a GDestroyNotify that gets called when data is no longer needed, or NULL
Returns : | the previously set hook function.

Since 2.10

Property Details

The "uri" property

  "uri"                      gchararray            : Read / Write

The URI bound to this button.

Default value: "http://www.gtk.org"

Since 2.10

See Also

GtkButton


GtkList

GtkList — Widget for packing a list of selectable items

Synopsis

#include <gtk/gtk.h>

                    GtkList;
GtkWidget*          gtk_list_new                        (void);
void                gtk_list_insert_items               (GtkList *list,
                                                         GList *items,
                                                         gint position);
void                gtk_list_append_items               (GtkList *list,
                                                         GList *items);
void                gtk_list_prepend_items              (GtkList *list,
                                                         GList *items);
void                gtk_list_remove_items               (GtkList *list,
                                                         GList *items);
void                gtk_list_remove_items_no_unref      (GtkList *list,
                                                         GList *items);
void                gtk_list_clear_items                (GtkList *list,
                                                         gint start,
                                                         gint end);
void                gtk_list_select_item                (GtkList *list,
                                                         gint item);
void                gtk_list_unselect_item              (GtkList *list,
                                                         gint item);
void                gtk_list_select_child               (GtkList *list,
                                                         GtkWidget *child);
void                gtk_list_unselect_child             (GtkList *list,
                                                         GtkWidget *child);
gint                gtk_list_child_position             (GtkList *list,
                                                         GtkWidget *child);
void                gtk_list_set_selection_mode         (GtkList *list,
                                                         GtkSelectionMode mode);
void                gtk_list_extend_selection           (GtkList *list,
                                                         GtkScrollType scroll_type,
                                                         gfloat position,
                                                         gboolean auto_start_selection);
void                gtk_list_start_selection            (GtkList *list);
void                gtk_list_end_selection              (GtkList *list);
void                gtk_list_select_all                 (GtkList *list);
void                gtk_list_unselect_all               (GtkList *list);
void                gtk_list_scroll_horizontal          (GtkList *list,
                                                         GtkScrollType scroll_type,
                                                         gfloat position);
void                gtk_list_scroll_vertical            (GtkList *list,
                                                         GtkScrollType scroll_type,
                                                         gfloat position);
void                gtk_list_toggle_add_mode            (GtkList *list);
void                gtk_list_toggle_focus_row           (GtkList *list);
void                gtk_list_toggle_row                 (GtkList *list,
                                                         GtkWidget *item);
void                gtk_list_undo_selection             (GtkList *list);
void                gtk_list_end_drag_selection         (GtkList *list);

Object Hierarchy

  GObject
   +----GInitiallyUnowned
         +----GtkObject
               +----GtkWidget
                     +----GtkContainer
                           +----GtkList

Implemented Interfaces

GtkList implements AtkImplementorIface.

Properties

  "selection-mode"           GtkSelectionMode      : Read / Write

Signals

  "select-child"                                   : Run First
  "selection-changed"                              : Run First
  "unselect-child"                                 : Run First

Description

The GtkList widget is a container whose children are displayed vertically in order, and can be selected. The list has many selection modes, which are programmer selective and depend on how many elements are able to be selected at the same time.

GtkList has been deprecated since GTK+ 2.0 and should not be used in newly written code. Use GtkTreeView instead.

Details

GtkList

typedef struct _GtkList GtkList;

Warning

GtkList is deprecated and should not be used in newly-written code.

gtk_list_new ()

GtkWidget*          gtk_list_new                        (void);

Warning

gtk_list_new is deprecated and should not be used in newly-written code.

Creates a new GtkList.

Returns : the newly-created GtkList

gtk_list_insert_items ()

void                gtk_list_insert_items               (GtkList *list,
                                                         GList *items,
                                                         gint position);

Warning

gtk_list_insert_items is deprecated and should not be used in newly-written code.

Inserts items into the list at the position position. The GList items must not be freed after.

list : | the list widget.
items : | the items.
position : | the position to insert items, starting at 0.

gtk_list_append_items ()

void                gtk_list_append_items               (GtkList *list,
                                                         GList *items);

Warning

gtk_list_append_items is deprecated and should not be used in newly-written code.

Adds items to the end of the list.

list : | the list widget.
items : | the items.

gtk_list_prepend_items ()

void                gtk_list_prepend_items              (GtkList *list,
                                                         GList *items);

Warning

gtk_list_prepend_items is deprecated and should not be used in newly-written code.

Inserts items at the beginning of the list.

list : | the list widget.
items : | the items.

gtk_list_remove_items ()

void                gtk_list_remove_items               (GtkList *list,
                                                         GList *items);

Warning

gtk_list_remove_items is deprecated and should not be used in newly-written code.

Removes the items from the list.

list : | the list widget.
items : | the items to remove.

gtk_list_remove_items_no_unref ()

void                gtk_list_remove_items_no_unref      (GtkList *list,
                                                         GList *items);

Warning

gtk_list_remove_items_no_unref is deprecated and should not be used in newly-written code.

Removes the items from the list, without unreferencing them. It may be useful if you want to move the items from one list to another.

list : | the list widget.
items : | the items.

gtk_list_clear_items ()

void                gtk_list_clear_items                (GtkList *list,
                                                         gint start,
                                                         gint end);

Warning

gtk_list_clear_items is deprecated and should not be used in newly-written code.

Removes the items between index start (included) and end (excluded) from the list. If end is negative, or greater than the number of children of list, it's assumed to be exactly the number of elements. If start is greater than or equal to end, nothing is done.

list : | the list widget.
start : | the index of the first item to remove.
end : | the index of the lest item to remove plus one.

gtk_list_select_item ()

void                gtk_list_select_item                (GtkList *list,
                                                         gint item);

Warning

gtk_list_select_item is deprecated and should not be used in newly-written code.

Selects the child number item of the list. Nothing happens if item is out of bounds. The signal GtkList::select-child will be emitted.

list : | the list widget.
item : | the index of the child to select.

gtk_list_unselect_item ()

void                gtk_list_unselect_item              (GtkList *list,
                                                         gint item);

Warning

gtk_list_unselect_item is deprecated and should not be used in newly-written code.

Unselects the child number item of the list. Nothing happens if item is out of bounds. The signal GtkList::unselect-child will be emitted.

list : | the list widget.
item : | the index of the child to unselect.

gtk_list_select_child ()

void                gtk_list_select_child               (GtkList *list,
                                                         GtkWidget *child);

Warning

gtk_list_select_child is deprecated and should not be used in newly-written code.

Selects the given child. The signal GtkList::select-child will be emitted.

list : | the list widget
child : | the child to select.

gtk_list_unselect_child ()

void                gtk_list_unselect_child             (GtkList *list,
                                                         GtkWidget *child);

Warning

gtk_list_unselect_child is deprecated and should not be used in newly-written code.

Unselects the given child. The signal GtkList::unselect-child will be emitted.

list : | the list widget.
child : | the child to unselect.

gtk_list_child_position ()

gint                gtk_list_child_position             (GtkList *list,
                                                         GtkWidget *child);

Warning

gtk_list_child_position is deprecated and should not be used in newly-written code.

Searches the children of list for the index of child.

list : | the list widget.
child : | the child to look for.
Returns : | the index of the child, -1 if not found.

gtk_list_set_selection_mode ()

void                gtk_list_set_selection_mode         (GtkList *list,
                                                         GtkSelectionMode mode);

Warning

gtk_list_set_selection_mode is deprecated and should not be used in newly-written code.

Set the list selection mode. The selection mode can be any value in GtkSelectionMode:

GTK_SELECTION_SINGLE | Zero or one element may be selected.
GTK_SELECTION_BROWSE | Exactly one element is always selected (this can be false after you have changed the selection mode).
GTK_SELECTION_MULTIPLE | Any number of elements may be selected. Clicks toggle the state of an item.
GTK_SELECTION_EXTENDED | Any number of elements may be selected. Click-drag selects a range of elements; the Ctrl key may be used to enlarge the selection, and Shift key to select between the focus and the child pointed to.

list : | the list widget.
mode : | the new selection mode.

gtk_list_extend_selection ()

void                gtk_list_extend_selection           (GtkList *list,
                                                         GtkScrollType scroll_type,
                                                         gfloat position,
                                                         gboolean auto_start_selection);

Warning

gtk_list_extend_selection is deprecated and should not be used in newly-written code.

Extends the selection by moving the anchor according to scroll_type. Only in GTK_SELECTION_EXTENDED.

list : | the list widget.
scroll_type : | the direction and length.
position : | the position if scroll_type is GTK_SCROLL_JUMP.
auto_start_selection : | if TRUE, gtk_list_start_selection() is automatically carried out before extending the selection.

gtk_list_start_selection ()

void                gtk_list_start_selection            (GtkList *list);

Warning

gtk_list_start_selection is deprecated and should not be used in newly-written code.

Starts a selection (or part of selection) at the focused child. Only in GTK_SELECTION_EXTENDED mode.

list : the list widget.

gtk_list_end_selection ()

void                gtk_list_end_selection              (GtkList *list);

Warning

gtk_list_end_selection is deprecated and should not be used in newly-written code.

Ends the selection. Used with gtk_list_extend_selection() and gtk_list_start_selection(). Only in GTK_SELECTION_EXTENDED mode.

list : the list widget.

gtk_list_select_all ()

void                gtk_list_select_all                 (GtkList *list);

Warning

gtk_list_select_all is deprecated and should not be used in newly-written code.

Selects all children of list. A signal will be emitted for each newly selected child.

list : the list widget.

gtk_list_unselect_all ()

void                gtk_list_unselect_all               (GtkList *list);

Warning

gtk_list_unselect_all is deprecated and should not be used in newly-written code.

Unselects all children of list. A signal will be emitted for each newly unselected child.

list : the list widget.

gtk_list_scroll_horizontal ()

void                gtk_list_scroll_horizontal          (GtkList *list,
                                                         GtkScrollType scroll_type,
                                                         gfloat position);

Warning

gtk_list_scroll_horizontal is deprecated and should not be used in newly-written code.

Scrolls list horizontaly. This supposes that the list is packed into a scrolled window or something similar, and adjustments are well set. Step and page increment are those from the horizontal adjustment of list. Backward means to the left, and forward to the right. Out of bounds values are truncated. scroll_type may be any valid GtkScrollType. If scroll_type is GTK_SCROLL_NONE, nothing is done. If it's GTK_SCROLL_JUMP, the list scrolls to the ratio position: 0 is full left, 1 is full right.

list : | the list widget.
scroll_type : | the scrolling type.
position : | the position if scroll_type is GTK_SCROLL_JUMP

gtk_list_scroll_vertical ()

void                gtk_list_scroll_vertical            (GtkList *list,
                                                         GtkScrollType scroll_type,
                                                         gfloat position);

Warning

gtk_list_scroll_vertical is deprecated and should not be used in newly-written code.

Scrolls list vertically. This supposes that the list is packed into a scrolled window or something similar, and adjustments are well set. Step and page increment are those from the vertical adjustment of list. Backward means up, and forward down. Out of bounds values are truncated. scroll_type may be any valid GtkScrollType. If scroll_type is GTK_SCROLL_NONE, nothing is done. If it's GTK_SCROLL_JUMP, the list scrolls to the ratio position: 0 is top, 1 is bottom.

list : | the list widget.
scroll_type : | the scrolling type.
position : | the position if scroll_type is GTK_SCROLL_JUMP

gtk_list_toggle_add_mode ()

void                gtk_list_toggle_add_mode            (GtkList *list);

Warning

gtk_list_toggle_add_mode is deprecated and should not be used in newly-written code.

Toggles between adding to the selection and beginning a new selection. Only in GTK_SELECTION_EXTENDED. Useful with gtk_list_extend_selection().

list : the list widget.

gtk_list_toggle_focus_row ()

void                gtk_list_toggle_focus_row           (GtkList *list);

Warning

gtk_list_toggle_focus_row is deprecated and should not be used in newly-written code.

Toggles the focus row. If the focus row is selected, it's unselected. If the focus row is unselected, it's selected. If the selection mode of list is GTK_SELECTION_BROWSE, this has no effect, as the selection is always at the focus row.

list : the list widget.

gtk_list_toggle_row ()

void                gtk_list_toggle_row                 (GtkList *list,
                                                         GtkWidget *item);

Warning

gtk_list_toggle_row is deprecated and should not be used in newly-written code.

Toggles the child item of list. If the selection mode of list is GTK_SELECTION_BROWSE, the item is selected, and the others are unselected.

list : | the list widget.
item : | the child to toggle.

gtk_list_undo_selection ()

void                gtk_list_undo_selection             (GtkList *list);

Warning

gtk_list_undo_selection is deprecated and should not be used in newly-written code.

Restores the selection in the last state, only if selection mode is GTK_SELECTION_EXTENDED. If this function is called twice, the selection is cleared. This function sometimes gives stranges "last states".

list : the list widget.

gtk_list_end_drag_selection ()

void                gtk_list_end_drag_selection         (GtkList *list);

Warning

gtk_list_end_drag_selection is deprecated and should not be used in newly-written code.

Stops the drag selection mode and ungrabs the pointer. This has no effect if a drag selection is not active.

list : the list widget.

Property Details

The "selection-mode" property

  "selection-mode"           GtkSelectionMode      : Read / Write

Default value: GTK_SELECTION_NONE

Signal Details

The "select-child" signal

void                user_function                      (GtkList   *list,
                                                        GtkWidget *widget,
                                                        gpointer   user_data)      : Run First

The child widget has just been selected.

list : | the object which received the signal.
widget : | the newly selected child.
user_data : | user data set when the signal handler was connected.

The "selection-changed" signal

void                user_function                      (GtkList *list,
                                                        gpointer user_data)      : Run First

The selection of the widget has just changed.

list : | the object which received the signal.
user_data : | user data set when the signal handler was connected.

The "unselect-child" signal

void                user_function                      (GtkList   *list,
                                                        GtkWidget *widget,
                                                        gpointer   user_data)      : Run First

The child widget has just been unselected.

list : | the object which received the signal.
widget : | the newly unselected child.
user_data : | user data set when the signal handler was connected.

See Also

GtkContainer | For functions that apply to every GtkContainer (like GtkList).
GtkListitem | Children of a GtkList widget must be of this type.


GtkListItem

GtkListItem — An item in a GtkList

Synopsis

#include <gtk/gtk.h>

                    GtkListItem;
GtkWidget*          gtk_list_item_new                   (void);
GtkWidget*          gtk_list_item_new_with_label        (const gchar *label);
void                gtk_list_item_select                (GtkListItem *list_item);
void                gtk_list_item_deselect              (GtkListItem *list_item);

Object Hierarchy

  GObject
   +----GInitiallyUnowned
         +----GtkObject
               +----GtkWidget
                     +----GtkContainer
                           +----GtkBin
                                 +----GtkItem
                                       +----GtkListItem

Implemented Interfaces

GtkListItem implements AtkImplementorIface.

Signals

  "end-selection"                                  : Run Last / Action
  "extend-selection"                               : Run Last / Action
  "scroll-horizontal"                              : Run Last / Action
  "scroll-vertical"                                : Run Last / Action
  "select-all"                                     : Run Last / Action
  "start-selection"                                : Run Last / Action
  "toggle-add-mode"                                : Run Last / Action
  "toggle-focus-row"                               : Run Last / Action
  "undo-selection"                                 : Run Last / Action
  "unselect-all"                                   : Run Last / Action

Description

The GtkListItem widget is used for each item in a GtkList.

GtkList has has been deprecated since GTK+ 2.0 and should not be used in newly written code. Use GtkTreeView instead.

Details

GtkListItem

typedef struct _GtkListItem GtkListItem;

Warning

GtkListItem is deprecated and should not be used in newly-written code.

The GtkListItem struct contains private data only, and should only be accessed using the functions below.

gtk_list_item_new ()

GtkWidget*          gtk_list_item_new                   (void);

Warning

gtk_list_item_new is deprecated and should not be used in newly-written code.

Creates a new GtkListitem.

Returns : a new GtkListItem.

gtk_list_item_new_with_label ()

GtkWidget*          gtk_list_item_new_with_label        (const gchar *label);

Warning

gtk_list_item_new_with_label is deprecated and should not be used in newly-written code.

Creates a new GtkListItem with a child label containing the given string.

label : | the string to use for the child label.
Returns : | a new GtkListItem with a child GtkLabel with the text set to label.

gtk_list_item_select ()

void                gtk_list_item_select                (GtkListItem *list_item);

Warning

gtk_list_item_select is deprecated and should not be used in newly-written code.

Selects the item, by emitting the item's "select" signal. Depending on the selection mode of the list, this may cause other items to be deselected.

list_item : a GtkListItem.

gtk_list_item_deselect ()

void                gtk_list_item_deselect              (GtkListItem *list_item);

Warning

gtk_list_item_deselect is deprecated and should not be used in newly-written code.

Deselects the item, by emitting the item's "deselect" signal.

list_item : a GtkListItem.

Signal Details

The "end-selection" signal

void                user_function                      (GtkListItem *listitem,
                                                        gpointer     user_data)      : Run Last / Action

listitem : | the object which received the signal.
user_data : | user data set when the signal handler was connected.

The "extend-selection" signal

void                user_function                      (GtkListItem  *listitem,
                                                        GtkScrollType scroll_type,
                                                        gfloat        position,
                                                        gboolean      auto_start_selection,
                                                        gpointer      user_data)                 : Run Last / Action

listitem : | the object which received the signal.
scroll_type : |
position : |
auto_start_selection : |
user_data : | user data set when the signal handler was connected.

The "scroll-horizontal" signal

void                user_function                      (GtkListItem  *listitem,
                                                        GtkScrollType scroll_type,
                                                        gfloat        position,
                                                        gpointer      user_data)        : Run Last / Action

listitem : | the object which received the signal.
scroll_type : |
position : |
user_data : | user data set when the signal handler was connected.

The "scroll-vertical" signal

void                user_function                      (GtkListItem  *listitem,
                                                        GtkScrollType scroll_type,
                                                        gfloat        position,
                                                        gpointer      user_data)        : Run Last / Action

listitem : | the object which received the signal.
scroll_type : |
position : |
user_data : | user data set when the signal handler was connected.

The "select-all" signal

void                user_function                      (GtkListItem *listitem,
                                                        gpointer     user_data)      : Run Last / Action

listitem : | the object which received the signal.
user_data : | user data set when the signal handler was connected.

The "start-selection" signal

void                user_function                      (GtkListItem *listitem,
                                                        gpointer     user_data)      : Run Last / Action

listitem : | the object which received the signal.
user_data : | user data set when the signal handler was connected.

The "toggle-add-mode" signal

void                user_function                      (GtkListItem *listitem,
                                                        gpointer     user_data)      : Run Last / Action

listitem : | the object which received the signal.
user_data : | user data set when the signal handler was connected.

The "toggle-focus-row" signal

void                user_function                      (GtkListItem *listitem,
                                                        gpointer     user_data)      : Run Last / Action

listitem : | the object which received the signal.
user_data : | user data set when the signal handler was connected.

The "undo-selection" signal

void                user_function                      (GtkListItem *listitem,
                                                        gpointer     user_data)      : Run Last / Action

listitem : | the object which received the signal.
user_data : | user data set when the signal handler was connected.

The "unselect-all" signal

void                user_function                      (GtkListItem *listitem,
                                                        gpointer     user_data)      : Run Last / Action

listitem : | the object which received the signal.
user_data : | user data set when the signal handler was connected.

See Also

GtkList

the parent list widget.


GtkListStore

GtkListStore — A list-like data structure that can be used with the GtkTreeView

Synopsis

#include <gtk/gtk.h>

                    GtkListStore;
GtkListStore*       gtk_list_store_new                  (gint n_columns,
                                                         ...);
GtkListStore*       gtk_list_store_newv                 (gint n_columns,
                                                         GType *types);
void                gtk_list_store_set_column_types     (GtkListStore *list_store,
                                                         gint n_columns,
                                                         GType *types);
void                gtk_list_store_set                  (GtkListStore *list_store,
                                                         GtkTreeIter *iter,
                                                         ...);
void                gtk_list_store_set_valist           (GtkListStore *list_store,
                                                         GtkTreeIter *iter,
                                                         va_list var_args);
void                gtk_list_store_set_value            (GtkListStore *list_store,
                                                         GtkTreeIter *iter,
                                                         gint column,
                                                         GValue *value);
gboolean            gtk_list_store_remove               (GtkListStore *list_store,
                                                         GtkTreeIter *iter);
void                gtk_list_store_insert               (GtkListStore *list_store,
                                                         GtkTreeIter *iter,
                                                         gint position);
void                gtk_list_store_insert_before        (GtkListStore *list_store,
                                                         GtkTreeIter *iter,
                                                         GtkTreeIter *sibling);
void                gtk_list_store_insert_after         (GtkListStore *list_store,
                                                         GtkTreeIter *iter,
                                                         GtkTreeIter *sibling);
void                gtk_list_store_insert_with_values   (GtkListStore *list_store,
                                                         GtkTreeIter *iter,
                                                         gint position,
                                                         ...);
void                gtk_list_store_insert_with_valuesv  (GtkListStore *list_store,
                                                         GtkTreeIter *iter,
                                                         gint position,
                                                         gint *columns,
                                                         GValue *values,
                                                         gint n_values);
void                gtk_list_store_prepend              (GtkListStore *list_store,
                                                         GtkTreeIter *iter);
void                gtk_list_store_append               (GtkListStore *list_store,
                                                         GtkTreeIter *iter);
void                gtk_list_store_clear                (GtkListStore *list_store);
gboolean            gtk_list_store_iter_is_valid        (GtkListStore *list_store,
                                                         GtkTreeIter *iter);
void                gtk_list_store_reorder              (GtkListStore *store,
                                                         gint *new_order);
void                gtk_list_store_swap                 (GtkListStore *store,
                                                         GtkTreeIter *a,
                                                         GtkTreeIter *b);
void                gtk_list_store_move_before          (GtkListStore *store,
                                                         GtkTreeIter *iter,
                                                         GtkTreeIter *position);
void                gtk_list_store_move_after           (GtkListStore *store,
                                                         GtkTreeIter *iter,
                                                         GtkTreeIter *position);

Object Hierarchy

  GObject
   +----GtkListStore

Implemented Interfaces

GtkListStore implements GtkTreeModel, GtkTreeDragSource, GtkTreeDragDest and GtkTreeSortable.

Description

The GtkListStore object is a list model for use with a GtkTreeView widget. It implements the GtkTreeModel interface, and consequentialy, can use all of the methods available there. It also implements the GtkTreeSortable interface so it can be sorted by the view. Finally, it also implements the tree drag and drop interfaces.

The GtkListStore can accept most GObject types as a column type, though it can't accept all custom types. Internally, it will keep a copy of data passed in (such as a string or a boxed pointer). Columns that accept GObjects are handled a little differently. The GtkListStore will keep a reference to the object instead of copying the value. As a result, if the object is modified, it is up to the application writer to call gtk_tree_model_row_changed to emit the "row_changed" signal. This most commonly affects lists with GdkPixbufs stored.

Example 18. Creating a simple list store.

enum {
  COLUMN_STRING,
  COLUMN_INT,
  COLUMN_BOOLEAN,
  N_COLUMNS
};

{
  GtkListStore *list_store;
  GtkTreePath *path;
  GtkTreeIter iter;
  gint i;

  list_store = gtk_list_store_new (N_COLUMNS,
                                   G_TYPE_STRING,
                                   G_TYPE_INT,
                                   G_TYPE_BOOLEAN);

  for (i = 0; i < 10; i++)
    {
      gchar *some_data;

      some_data = get_some_data (i);

      /* Add a new row to the model */
      gtk_list_store_append (list_store, &iter);
      gtk_list_store_set (list_store, &iter,
                          COLUMN_STRING, some_data,
                          COLUMN_INT, i,
                          COLUMN_BOOLEAN,  FALSE,
                          -1);

      /* As the store will keep a copy of the string internally, we
       * free some_data.
       */
      g_free (some_data);
    }

  /* Modify a particular row */
  path = gtk_tree_path_new_from_string ("4");
  gtk_tree_model_get_iter (GTK_TREE_MODEL (list_store),
                           &iter,
                           path);
  gtk_tree_path_free (path);
  gtk_list_store_set (list_store, &iter,
                      COLUMN_BOOLEAN, TRUE,
                      -1);
}

Performance Considerations

Internally, the GtkListStore was implemented with a linked list with a tail pointer prior to GTK+ 2.6. As a result, it was fast at data insertion and deletion, and not fast at random data access. The GtkListStore sets the GTK_TREE_MODEL_ITERS_PERSIST flag, which means that GtkTreeIters can be cached while the row exists. Thus, if access to a particular row is needed often and your code is expected to run on older versions of GTK+, it is worth keeping the iter around.

Atomic Operations

It is important to note that only the methods gtk_list_store_insert_with_values and gtk_list_store_insert_with_valuesv are atomic, in the sense that the row is being appended to the store and the values filled in in a single operation with regard to GtkTreeModel signaling. In contrast, using e.g. gtk_list_store_append and then gtk_list_store_set will first create a row, which triggers the "row_inserted" GtkTreeModel signal on GtkListStore. The row, however, is still empty, and any signal handler connecting to "row_inserted" on this particular store should be prepared for the situation that the row might be empty. This is especially important if you are wrapping the GtkListStore inside a GtkTreeModelFilter and are using a GtkTreeModelFilterVisibleFunc. Using any of the non-atomic operations to append rows to the GtkListStore will cause the GtkTreeModelFilterVisibleFunc to be visited with an empty row first; the function must be prepared for that.

Details

GtkListStore

typedef struct _GtkListStore GtkListStore;

gtk_list_store_new ()

GtkListStore*       gtk_list_store_new                  (gint n_columns,
                                                         ...);

Creates a new list store as with n_columns columns each of the types passed in. Note that only types derived from standard GObject fundamental types are supported.

As an example, gtk_tree_store_new (3, G_TYPE_INT, G_TYPE_STRING, GDK_TYPE_PIXBUF); will create a new GtkListStore with three columns, of type int, string and GdkPixbuf respectively.

n_columns : | number of columns in the list store
... : | all GType types for the columns, from first to last
Returns : | a new GtkListStore

gtk_list_store_newv ()

GtkListStore*       gtk_list_store_newv                 (gint n_columns,
                                                         GType *types);

Non-vararg creation function. Used primarily by language bindings.

n_columns : | number of columns in the list store
types : | an array of GType types for the columns, from first to last
Returns : | a new GtkListStore

gtk_list_store_set_column_types ()

void                gtk_list_store_set_column_types     (GtkListStore *list_store,
                                                         gint n_columns,
                                                         GType *types);

This function is meant primarily for GObjects that inherit from GtkListStore, and should only be used when constructing a new GtkListStore. It will not function after a row has been added, or a method on the GtkTreeModel interface is called.

list_store : | A GtkListStore
n_columns : | Number of columns for the list store
types : | An array length n of GTypes

gtk_list_store_set ()

void                gtk_list_store_set                  (GtkListStore *list_store,
                                                         GtkTreeIter *iter,
                                                         ...);

Sets the value of one or more cells in the row referenced by iter. The variable argument list should contain integer column numbers, each column number followed by the value to be set. The list is terminated by a -1. For example, to set column 0 with type G_TYPE_STRING to "Foo", you would write gtk_list_store_set (store, iter, 0, "Foo", -1).

list_store : | a GtkListStore
iter : | row iterator
... : | pairs of column number and value, terminated with -1

gtk_list_store_set_valist ()

void                gtk_list_store_set_valist           (GtkListStore *list_store,
                                                         GtkTreeIter *iter,
                                                         va_list var_args);

See gtk_list_store_set(); this version takes a va_list for use by language bindings.

list_store : | A GtkListStore
iter : | A valid GtkTreeIter for the row being modified
var_args : | va_list of column/value pairs

gtk_list_store_set_value ()

void                gtk_list_store_set_value            (GtkListStore *list_store,
                                                         GtkTreeIter *iter,
                                                         gint column,
                                                         GValue *value);

Sets the data in the cell specified by iter and column. The type of value must be convertible to the type of the column.

list_store : | A GtkListStore
iter : | A valid GtkTreeIter for the row being modified
column : | column number to modify
value : | new value for the cell

gtk_list_store_remove ()

gboolean            gtk_list_store_remove               (GtkListStore *list_store,
                                                         GtkTreeIter *iter);

Removes the given row from the list store. After being removed, iter is set to be the next valid row, or invalidated if it pointed to the last row in list_store.

list_store : | A GtkListStore
iter : | A valid GtkTreeIter
Returns : | TRUE if iter is valid, FALSE if not.

gtk_list_store_insert ()

void                gtk_list_store_insert               (GtkListStore *list_store,
                                                         GtkTreeIter *iter,
                                                         gint position);

Creates a new row at position. iter will be changed to point to this new row. If position is larger than the number of rows on the list, then the new row will be appended to the list. The row will be empty after this function is called. To fill in values, you need to call gtk_list_store_set() or gtk_list_store_set_value().

list_store : | A GtkListStore
iter : | An unset GtkTreeIter to set to the new row
position : | position to insert the new row

gtk_list_store_insert_before ()

void                gtk_list_store_insert_before        (GtkListStore *list_store,
                                                         GtkTreeIter *iter,
                                                         GtkTreeIter *sibling);

Inserts a new row before sibling. If sibling is NULL, then the row will be appended to the end of the list. iter will be changed to point to this new row. The row will be empty after this function is called. To fill in values, you need to call gtk_list_store_set() or gtk_list_store_set_value().

list_store : | A GtkListStore
iter : | An unset GtkTreeIter to set to the new row
sibling : | A valid GtkTreeIter, or NULL

gtk_list_store_insert_after ()

void                gtk_list_store_insert_after         (GtkListStore *list_store,
                                                         GtkTreeIter *iter,
                                                         GtkTreeIter *sibling);

Inserts a new row after sibling. If sibling is NULL, then the row will be prepended to the beginning of the list. iter will be changed to point to this new row. The row will be empty after this function is called. To fill in values, you need to call gtk_list_store_set() or gtk_list_store_set_value().

list_store : | A GtkListStore
iter : | An unset GtkTreeIter to set to the new row
sibling : | A valid GtkTreeIter, or NULL

gtk_list_store_insert_with_values ()

void                gtk_list_store_insert_with_values   (GtkListStore *list_store,
                                                         GtkTreeIter *iter,
                                                         gint position,
                                                         ...);

Creates a new row at position. iter will be changed to point to this new row. If position is larger than the number of rows on the list, then the new row will be appended to the list. The row will be filled with the values given to this function.

Calling gtk_list_store_insert_with_values(list_store, iter, position...) has the same effect as calling

gtk_list_store_insert (list_store, iter, position);
gtk_list_store_set (list_store, iter, ...);

with the difference that the former will only emit a row_inserted signal, while the latter will emit row_inserted, row_changed and, if the list store is sorted, rows_reordered. Since emitting the rows_reordered signal repeatedly can affect the performance of the program, gtk_list_store_insert_with_values() should generally be preferred when inserting rows in a sorted list store.

list_store : | A GtkListStore
iter : | An unset GtkTreeIter to set to the new row, or NULL.
position : | position to insert the new row
... : | pairs of column number and value, terminated with -1

Since 2.6

gtk_list_store_insert_with_valuesv ()

void                gtk_list_store_insert_with_valuesv  (GtkListStore *list_store,
                                                         GtkTreeIter *iter,
                                                         gint position,
                                                         gint *columns,
                                                         GValue *values,
                                                         gint n_values);

A variant of gtk_list_store_insert_with_values() which takes the columns and values as two arrays, instead of varargs. This function is mainly intended for language-bindings.

list_store : | A GtkListStore
iter : | An unset GtkTreeIter to set to the new row, or NULL.
position : | position to insert the new row
columns : | an array of column numbers
values : | an array of GValues
n_values : | the length of the columns and values arrays

Since 2.6

gtk_list_store_prepend ()

void                gtk_list_store_prepend              (GtkListStore *list_store,
                                                         GtkTreeIter *iter);

Prepends a new row to list_store. iter will be changed to point to this new row. The row will be empty after this function is called. To fill in values, you need to call gtk_list_store_set() or gtk_list_store_set_value().

list_store : | A GtkListStore
iter : | An unset GtkTreeIter to set to the prepend row

gtk_list_store_append ()

void                gtk_list_store_append               (GtkListStore *list_store,
                                                         GtkTreeIter *iter);

Appends a new row to list_store. iter will be changed to point to this new row. The row will be empty after this function is called. To fill in values, you need to call gtk_list_store_set() or gtk_list_store_set_value().

list_store : | A GtkListStore
iter : | An unset GtkTreeIter to set to the appended row

gtk_list_store_clear ()

void                gtk_list_store_clear                (GtkListStore *list_store);

Removes all rows from the list store.

list_store : a GtkListStore.

gtk_list_store_iter_is_valid ()

gboolean            gtk_list_store_iter_is_valid        (GtkListStore *list_store,
                                                         GtkTreeIter *iter);

Warning

This function is slow. Only use it for debugging and/or testing purposes.

Checks if the given iter is a valid iter for this GtkListStore.

list_store : | A GtkListStore.
iter : | A GtkTreeIter.
Returns : | TRUE if the iter is valid, FALSE if the iter is invalid.

Since 2.2

gtk_list_store_reorder ()

void                gtk_list_store_reorder              (GtkListStore *store,
                                                         gint *new_order);

Reorders store to follow the order indicated by new_order. Note that this function only works with unsorted stores.

store : | A GtkListStore.
new_order : | an array of integers mapping the new position of each child to its old position before the re-ordering, i.e. new_order[newpos] = oldpos.

Since 2.2

gtk_list_store_swap ()

void                gtk_list_store_swap                 (GtkListStore *store,
                                                         GtkTreeIter *a,
                                                         GtkTreeIter *b);

Swaps a and b in store. Note that this function only works with unsorted stores.

store : | A GtkListStore.
a : | A GtkTreeIter.
b : | Another GtkTreeIter.

Since 2.2

gtk_list_store_move_before ()

void                gtk_list_store_move_before          (GtkListStore *store,
                                                         GtkTreeIter *iter,
                                                         GtkTreeIter *position);

Moves iter in store to the position before position. Note that this function only works with unsorted stores. If position is NULL, iter will be moved to the end of the list.

store : | A GtkListStore.
iter : | A GtkTreeIter.
position : | A GtkTreeIter, or NULL.

Since 2.2

gtk_list_store_move_after ()

void                gtk_list_store_move_after           (GtkListStore *store,
                                                         GtkTreeIter *iter,
                                                         GtkTreeIter *position);

Moves iter in store to the position after position. Note that this function only works with unsorted stores. If position is NULL, iter will be moved to the start of the list.

store : | A GtkListStore.
iter : | A GtkTreeIter.
position : | A GtkTreeIter or NULL.

Since 2.2

See Also

GtkTreeModel, GtkTreeStore


GtkMenu

GtkMenu — A menu widget

Synopsis

#include <gtk/gtk.h>

                    GtkMenu;
GtkWidget*          gtk_menu_new                        (void);
void                gtk_menu_set_screen                 (GtkMenu *menu,
                                                         GdkScreen *screen);
#define             gtk_menu_append                     (menu,child)
#define             gtk_menu_prepend                    (menu,child)
#define             gtk_menu_insert                     (menu,child,pos)
void                gtk_menu_reorder_child              (GtkMenu *menu,
                                                         GtkWidget *child,
                                                         gint position);
void                gtk_menu_attach                     (GtkMenu *menu,
                                                         GtkWidget *child,
                                                         guint left_attach,
                                                         guint right_attach,
                                                         guint top_attach,
                                                         guint bottom_attach);
void                gtk_menu_popup                      (GtkMenu *menu,
                                                         GtkWidget *parent_menu_shell,
                                                         GtkWidget *parent_menu_item,
                                                         GtkMenuPositionFunc func,
                                                         gpointer data,
                                                         guint button,
                                                         guint32 activate_time);
void                gtk_menu_set_accel_group            (GtkMenu *menu,
                                                         GtkAccelGroup *accel_group);
GtkAccelGroup*      gtk_menu_get_accel_group            (GtkMenu *menu);
void                gtk_menu_set_accel_path             (GtkMenu *menu,
                                                         const gchar *accel_path);
void                gtk_menu_set_title                  (GtkMenu *menu,
                                                         const gchar *title);
gboolean            gtk_menu_get_tearoff_state          (GtkMenu *menu);
const gchar*        gtk_menu_get_title                  (GtkMenu *menu);

void                gtk_menu_popdown                    (GtkMenu *menu);
void                gtk_menu_reposition                 (GtkMenu *menu);
GtkWidget*          gtk_menu_get_active                 (GtkMenu *menu);
void                gtk_menu_set_active                 (GtkMenu *menu,
                                                         guint index_);
void                gtk_menu_set_tearoff_state          (GtkMenu *menu,
                                                         gboolean torn_off);
void                gtk_menu_attach_to_widget           (GtkMenu *menu,
                                                         GtkWidget *attach_widget,
                                                         GtkMenuDetachFunc detacher);
void                gtk_menu_detach                     (GtkMenu *menu);
GtkWidget*          gtk_menu_get_attach_widget          (GtkMenu *menu);
GList*              gtk_menu_get_for_attach_widget      (GtkWidget *widget);
void                (*GtkMenuPositionFunc)              (GtkMenu *menu,
                                                         gint *x,
                                                         gint *y,
                                                         gboolean *push_in,
                                                         gpointer user_data);
void                (*GtkMenuDetachFunc)                (GtkWidget *attach_widget,
                                                         GtkMenu *menu);
void                gtk_menu_set_monitor                (GtkMenu *menu,
                                                         gint monitor_num);

Object Hierarchy

  GObject
   +----GInitiallyUnowned
         +----GtkObject
               +----GtkWidget
                     +----GtkContainer
                           +----GtkMenuShell
                                 +----GtkMenu
                                       +----GtkRecentChooserMenu

Implemented Interfaces

GtkMenu implements AtkImplementorIface.

Properties

  "tearoff-state"            gboolean              : Read / Write
  "tearoff-title"            gchararray            : Read / Write

Child Properties

  "bottom-attach"            gint                  : Read / Write
  "left-attach"              gint                  : Read / Write
  "right-attach"             gint                  : Read / Write
  "top-attach"               gint                  : Read / Write

Style Properties

  "double-arrows"            gboolean              : Read
  "horizontal-offset"        gint                  : Read
  "horizontal-padding"       gint                  : Read
  "vertical-offset"          gint                  : Read
  "vertical-padding"         gint                  : Read

Signals

  "move-scroll"                                    : Run Last / Action

Description

A GtkMenu is a GtkMenuShell that implements a drop down menu consisting of a list of GtkMenuItem objects which can be navigated and activated by the user to perform application functions.

A GtkMenu is most commonly dropped down by activating a GtkMenuItem in a GtkMenuBar or popped up by activating a GtkMenuItem in another GtkMenu.

A GtkMenu can also be popped up by activating a GtkOptionMenu. Other composite widgets such as the GtkNotebook can pop up a GtkMenu as well.

Applications can display a GtkMenu as a popup menu by calling the gtk_menu_popup() function. The example below shows how an application can pop up a menu when the 3rd mouse button is pressed.

Example 19. Connecting the popup signal handler.

    /* connect our handler which will popup the menu */
    g_signal_connect_swapped (window, "button_press_event",
    G_CALLBACK (my_popup_handler), menu);

Example 20. Signal handler which displays a popup menu.

static gint
my_popup_handler (GtkWidget *widget, GdkEvent *event)
{
  GtkMenu *menu;
  GdkEventButton *event_button;

  g_return_val_if_fail (widget != NULL, FALSE);
  g_return_val_if_fail (GTK_IS_MENU (widget), FALSE);
  g_return_val_if_fail (event != NULL, FALSE);

  /* The "widget" is the menu that was supplied when
   * g_signal_connect_swapped() was called.
   */
  menu = GTK_MENU (widget);

  if (event->type == GDK_BUTTON_PRESS)
    {
      event_button = (GdkEventButton *) event;
      if (event_button->button == 3)
    {
      gtk_menu_popup (menu, NULL, NULL, NULL, NULL,
              event_button->button, event_button->time);
      return TRUE;
    }
    }

  return FALSE;
}

Details

GtkMenu

typedef struct _GtkMenu GtkMenu;

The GtkMenu struct contains private data only, and should be accessed using the functions below.

gtk_menu_new ()

GtkWidget*          gtk_menu_new                        (void);

Creates a new GtkMenu.

Returns : a new GtkMenu.

gtk_menu_set_screen ()

void                gtk_menu_set_screen                 (GtkMenu *menu,
                                                         GdkScreen *screen);

Sets the GdkScreen on which the menu will be displayed.

menu : | a GtkMenu.
screen : | a GdkScreen, or NULL if the screen should be determined by the widget the menu is attached to.

Since 2.2

gtk_menu_append()

#define gtk_menu_append(menu,child)	gtk_menu_shell_append  ((GtkMenuShell *)(menu),(child))

Warning

gtk_menu_append is deprecated and should not be used in newly-written code. Use gtk_menu_shell_append() instead.

Adds a new GtkMenuItem to the end of the menu's item list.

menu : | a GtkMenu.
child : | The GtkMenuItem to add.

gtk_menu_prepend()

#define gtk_menu_prepend(menu,child)    gtk_menu_shell_prepend ((GtkMenuShell *)(menu),(child))

Warning

gtk_menu_prepend is deprecated and should not be used in newly-written code. Use gtk_menu_shell_prepend() instead.

Adds a new GtkMenuItem to the beginning of the menu's item list.

menu : | a GtkMenu.
child : | The GtkMenuItem to add.

gtk_menu_insert()

#define gtk_menu_insert(menu,child,pos)	gtk_menu_shell_insert ((GtkMenuShell *)(menu),(child),(pos))

Warning

gtk_menu_insert is deprecated and should not be used in newly-written code. Use gtk_menu_shell_insert() instead.

Adds a new GtkMenuItem to the menu's item list at the position indicated by position.

menu : | a GtkMenu.
child : | The GtkMenuItem to add.
pos : | The position in the item list where child is added. Positions are numbered from 0 to n-1.

gtk_menu_reorder_child ()

void                gtk_menu_reorder_child              (GtkMenu *menu,
                                                         GtkWidget *child,
                                                         gint position);

Moves a GtkMenuItem to a new position within the GtkMenu.

menu : | a GtkMenu.
child : | the GtkMenuItem to move.
position : | the new position to place child. Positions are numbered from 0 to n-1.

gtk_menu_attach ()

void                gtk_menu_attach                     (GtkMenu *menu,
                                                         GtkWidget *child,
                                                         guint left_attach,
                                                         guint right_attach,
                                                         guint top_attach,
                                                         guint bottom_attach);

Adds a new GtkMenuItem to a (table) menu. The number of 'cells' that an item will occupy is specified by left_attach, right_attach, top_attach and bottom_attach. These each represent the leftmost, rightmost, uppermost and lower column and row numbers of the table. (Columns and rows are indexed from zero).

Note that this function is not related to gtk_menu_detach().

menu : | a GtkMenu.
child : | a GtkMenuItem.
left_attach : | The column number to attach the left side of the item to.
right_attach : | The column number to attach the right side of the item to.
top_attach : | The row number to attach the top of the item to.
bottom_attach : | The row number to attach the bottom of the item to.

Since 2.4

gtk_menu_popup ()

void                gtk_menu_popup                      (GtkMenu *menu,
                                                         GtkWidget *parent_menu_shell,
                                                         GtkWidget *parent_menu_item,
                                                         GtkMenuPositionFunc func,
                                                         gpointer data,
                                                         guint button,
                                                         guint32 activate_time);

Displays a menu and makes it available for selection. Applications can use this function to display context-sensitive menus, and will typically supply NULL for the parent_menu_shell, parent_menu_item, func and data parameters. The default menu positioning function will position the menu at the current mouse cursor position.

The button parameter should be the mouse button pressed to initiate the menu popup. If the menu popup was initiated by something other than a mouse button press, such as a mouse button release or a keypress, button should be 0.

The activate_time parameter should be the time stamp of the event that initiated the popup. If such an event is not available, use gtk_get_current_event_time() instead.

menu : | a GtkMenu.
parent_menu_shell : | the menu shell containing the triggering menu item, or NULL
parent_menu_item : | the menu item whose activation triggered the popup, or NULL
func : | a user supplied function used to position the menu, or NULL
data : | user supplied data to be passed to func.
button : | the mouse button which was pressed to initiate the event.
activate_time : | the time at which the activation event occurred.

gtk_menu_set_accel_group ()

void                gtk_menu_set_accel_group            (GtkMenu *menu,
                                                         GtkAccelGroup *accel_group);

Set the GtkAccelGroup which holds global accelerators for the menu. This accelerator group needs to also be added to all windows that this menu is being used in with gtk_window_add_accel_group(), in order for those windows to support all the accelerators contained in this group.

menu : | a GtkMenu.
accel_group : | the GtkAccelGroup to be associated with the menu.

gtk_menu_get_accel_group ()

GtkAccelGroup*      gtk_menu_get_accel_group            (GtkMenu *menu);

Gets the GtkAccelGroup which holds global accelerators for the menu. See gtk_menu_set_accel_group().

menu : | a GtkMenu.
Returns : | the GtkAccelGroup associated with the menu.

gtk_menu_set_accel_path ()

void                gtk_menu_set_accel_path             (GtkMenu *menu,
                                                         const gchar *accel_path);

Sets an accelerator path for this menu from which accelerator paths for its immediate children, its menu items, can be constructed. The main purpose of this function is to spare the programmer the inconvenience of having to call gtk_menu_item_set_accel_path() on each menu item that should support runtime user changable accelerators. Instead, by just calling gtk_menu_set_accel_path() on their parent, each menu item of this menu, that contains a label describing its purpose, automatically gets an accel path assigned. For example, a menu containing menu items "New" and "Exit", will, after gtk_menu_set_accel_path (menu, "<Gnumeric-Sheet>/File"); has been called, assign its items the accel paths: "<Gnumeric-Sheet>/File/New" and "<Gnumeric-Sheet>/File/Exit". Assigning accel paths to menu items then enables the user to change their accelerators at runtime. More details about accelerator paths and their default setups can be found at gtk_accel_map_add_entry().

menu : | a valid GtkMenu
accel_path : | a valid accelerator path

gtk_menu_set_title ()

void                gtk_menu_set_title                  (GtkMenu *menu,
                                                         const gchar *title);

Sets the title string for the menu. The title is displayed when the menu is shown as a tearoff menu. If title is NULL, the menu will see if it is attached to a parent menu item, and if so it will try to use the same text as that menu item's label.

menu : | a GtkMenu
title : | a string containing the title for the menu.

gtk_menu_get_tearoff_state ()

gboolean            gtk_menu_get_tearoff_state          (GtkMenu *menu);

Returns whether the menu is torn off. See gtk_menu_set_tearoff_state().

menu : | a GtkMenu
Returns : | TRUE if the menu is currently torn off.

gtk_menu_get_title ()

const gchar*        gtk_menu_get_title                  (GtkMenu *menu);

Returns the title of the menu. See gtk_menu_set_title().

menu : | a GtkMenu
Returns : | the title of the menu, or NULL if the menu has no title set on it. This string is owned by the widget and should not be modified or freed.

gtk_menu_popdown ()

void                gtk_menu_popdown                    (GtkMenu *menu);

Removes the menu from the screen.

menu : a GtkMenu.

gtk_menu_reposition ()

void                gtk_menu_reposition                 (GtkMenu *menu);

Repositions the menu according to its position function.

menu : a GtkMenu.

gtk_menu_get_active ()

GtkWidget*          gtk_menu_get_active                 (GtkMenu *menu);

Returns the selected menu item from the menu. This is used by the GtkOptionMenu.

menu : | a GtkMenu.
Returns : | the GtkMenuItem that was last selected in the menu. If a selection has not yet been made, the first menu item is selected.

gtk_menu_set_active ()

void                gtk_menu_set_active                 (GtkMenu *menu,
                                                         guint index_);

Selects the specified menu item within the menu. This is used by the GtkOptionMenu and should not be used by anyone else.

menu : | a GtkMenu.
index_ : | the index of the menu item to select. Index values are from 0 to n-1.

gtk_menu_set_tearoff_state ()

void                gtk_menu_set_tearoff_state          (GtkMenu *menu,
                                                         gboolean torn_off);

Changes the tearoff state of the menu. A menu is normally displayed as drop down menu which persists as long as the menu is active. It can also be displayed as a tearoff menu which persists until it is closed or reattached.

menu : | a GtkMenu.
torn_off : | If TRUE, menu is displayed as a tearoff menu.

gtk_menu_attach_to_widget ()

void                gtk_menu_attach_to_widget           (GtkMenu *menu,
                                                         GtkWidget *attach_widget,
                                                         GtkMenuDetachFunc detacher);

Attaches the menu to the widget and provides a callback function that will be invoked when the menu calls gtk_menu_detach() during its destruction.

menu : | a GtkMenu.
attach_widget : | the GtkWidget that the menu will be attached to.
detacher : | the user supplied callback function that will be called when the menu calls gtk_menu_detach().

gtk_menu_detach ()

void                gtk_menu_detach                     (GtkMenu *menu);

Detaches the menu from the widget to which it had been attached. This function will call the callback function, detacher, provided when the gtk_menu_attach_to_widget() function was called.

menu : a GtkMenu.

gtk_menu_get_attach_widget ()

GtkWidget*          gtk_menu_get_attach_widget          (GtkMenu *menu);

Returns the GtkWidget that the menu is attached to.

menu : | a GtkMenu.
Returns : | the GtkWidget that the menu is attached to.

gtk_menu_get_for_attach_widget ()

GList*              gtk_menu_get_for_attach_widget      (GtkWidget *widget);

Returns a list of the menus which are attached to this widget. This list is owned by GTK+ and must not be modified.

widget : | a GtkWidget
Returns : | the list of menus attached to his widget.

Since 2.6

GtkMenuPositionFunc ()

void                (*GtkMenuPositionFunc)              (GtkMenu *menu,
                                                         gint *x,
                                                         gint *y,
                                                         gboolean *push_in,
                                                         gpointer user_data);

A user function supplied when calling gtk_menu_popup() which controls the positioning of the menu when it is displayed. The function sets the x and y parameters to the coordinates where the menu is to be drawn.

menu : | a GtkMenu.
x : | address of the gint representing the horizontal position where the menu shall be drawn. This is an output parameter.
y : | address of the gint representing the vertical position where the menu shall be drawn. This is an output parameter.
push_in : | whether the menu should be pushed in to be completely inside the screen instead of just clamped to the size to the screen.
user_data : | the data supplied by the user in the gtk_menu_popup() data parameter.

GtkMenuDetachFunc ()

void                (*GtkMenuDetachFunc)                (GtkWidget *attach_widget,
                                                         GtkMenu *menu);

A user function supplied when calling gtk_menu_attach_to_widget() which will be called when the menu is later detached from the widget.

attach_widget : | the GtkWidget that the menu is being detached from.
menu : | the GtkMenu being detached.

gtk_menu_set_monitor ()

void                gtk_menu_set_monitor                (GtkMenu *menu,
                                                         gint monitor_num);

Informs GTK+ on which monitor a menu should be popped up. See gdk_screen_get_monitor_geometry().

This function should be called from a GtkMenuPositionFunc if the menu should not appear on the same monitor as the pointer. This information can't be reliably inferred from the coordinates returned by a GtkMenuPositionFunc, since, for very long menus, these coordinates may extend beyond the monitor boundaries or even the screen boundaries.

menu : | a GtkMenu
monitor_num : | the number of the monitor on which the menu should be popped up

Since 2.4

Property Details

The "tearoff-state" property

  "tearoff-state"            gboolean              : Read / Write

A boolean that indicates whether the menu is torn-off.

Default value: FALSE

Since 2.6

The "tearoff-title" property

  "tearoff-title"            gchararray            : Read / Write

A title that may be displayed by the window manager when this menu is torn-off.

Default value: ""

Child Property Details

The "bottom-attach" child property

  "bottom-attach"            gint                  : Read / Write

The row number to attach the bottom of the child to.

Allowed values: >= -1

Default value: -1

The "left-attach" child property

  "left-attach"              gint                  : Read / Write

The column number to attach the left side of the child to.

Allowed values: >= -1

Default value: -1

The "right-attach" child property

  "right-attach"             gint                  : Read / Write

The column number to attach the right side of the child to.

Allowed values: >= -1

Default value: -1

The "top-attach" child property

  "top-attach"               gint                  : Read / Write

The row number to attach the top of the child to.

Allowed values: >= -1

Default value: -1

Style Property Details

The "double-arrows" style property

  "double-arrows"            gboolean              : Read

When scrolling, always show both arrows.

Default value: TRUE

The "horizontal-offset" style property

  "horizontal-offset"        gint                  : Read

When the menu is a submenu, position it this number of pixels offset horizontally.

Default value: -2

The "horizontal-padding" style property

  "horizontal-padding"       gint                  : Read

Extra space at the left and right edges of the menu.

Allowed values: >= 0

Default value: 0

The "vertical-offset" style property

  "vertical-offset"          gint                  : Read

When the menu is a submenu, position it this number of pixels offset vertically.

Default value: 0

The "vertical-padding" style property

  "vertical-padding"         gint                  : Read

Extra space at the top and bottom of the menu.

Allowed values: >= 0

Default value: 1

Signal Details

The "move-scroll" signal

void                user_function                      (GtkMenu      *menu,
                                                        GtkScrollType arg1,
                                                        gpointer      user_data)      : Run Last / Action

menu : | the object which received the signal.
arg1 : |
user_data : | user data set when the signal handler was connected.


GtkMenuBar

GtkMenuBar — A subclass widget for GtkMenuShell which holds GtkMenuItem widgets

Synopsis

#include <gtk/gtk.h>

                    GtkMenuBar;
GtkWidget*          gtk_menu_bar_new                    (void);
#define             gtk_menu_bar_append                 (menu,child)
#define             gtk_menu_bar_prepend                (menu,child)
#define             gtk_menu_bar_insert                 (menu,child,pos)
enum                GtkPackDirection;
void                gtk_menu_bar_set_pack_direction     (GtkMenuBar *menubar,
                                                         GtkPackDirection pack_dir);
GtkPackDirection    gtk_menu_bar_get_pack_direction     (GtkMenuBar *menubar);
void                gtk_menu_bar_set_child_pack_direction
                                                        (GtkMenuBar *menubar,
                                                         GtkPackDirection child_pack_dir);
GtkPackDirection    gtk_menu_bar_get_child_pack_direction
                                                        (GtkMenuBar *menubar);

Object Hierarchy

  GObject
   +----GInitiallyUnowned
         +----GtkObject
               +----GtkWidget
                     +----GtkContainer
                           +----GtkMenuShell
                                 +----GtkMenuBar

Implemented Interfaces

GtkMenuBar implements AtkImplementorIface.

Properties

  "child-pack-direction"     GtkPackDirection      : Read / Write
  "pack-direction"           GtkPackDirection      : Read / Write

Style Properties

  "internal-padding"         gint                  : Read
  "shadow-type"              GtkShadowType         : Read

Description

The GtkMenuBar is a subclass of GtkMenuShell which contains one to many GtkMenuItem. The result is a standard menu bar which can hold many menu items. GtkMenuBar allows for a shadow type to be set for aesthetic purposes. The shadow types are defined in the gtk_menu_bar_set_shadow_type function.

Details

GtkMenuBar

typedef struct _GtkMenuBar GtkMenuBar;

The GtkMenuBar struct contains the following fields. (These fields should be considered read-only. They should never be set by an application.)

gtk_menu_bar_new ()

GtkWidget*          gtk_menu_bar_new                    (void);

Creates the new GtkMenuBar

Returns : the GtkMenuBar

gtk_menu_bar_append()

#define gtk_menu_bar_append(menu,child)	    gtk_menu_shell_append  ((GtkMenuShell *)(menu),(child))

Warning

gtk_menu_bar_append is deprecated and should not be used in newly-written code. Use gtk_menu_shell_append() instead.

Adds a new GtkMenuItem to the end of the GtkMenuBar

menu : | a GtkMenuBar
child : | the GtkMenuItem to add

gtk_menu_bar_prepend()

#define gtk_menu_bar_prepend(menu,child)    gtk_menu_shell_prepend ((GtkMenuShell *)(menu),(child))

Warning

gtk_menu_bar_prepend is deprecated and should not be used in newly-written code. Use gtk_menu_shell_prepend() instead.

Adds a new GtkMenuItem to the beginning of the GtkMenuBar

menu : | a GtkMenuBar
child : | the GtkMenuItem to add

gtk_menu_bar_insert()

#define gtk_menu_bar_insert(menu,child,pos) gtk_menu_shell_insert ((GtkMenuShell *)(menu),(child),(pos))

Warning

gtk_menu_bar_insert is deprecated and should not be used in newly-written code. Use gtk_menu_shell_insert() instead.

Adds a new GtkMenuItem to the GtkMenuBar at the position defined by position

menu : | a GtkMenuBar
child : | the GtkMenuItem to add
pos : | the position in the item list where the child is added.

enum GtkPackDirection

typedef enum
{
  GTK_PACK_DIRECTION_LTR,
  GTK_PACK_DIRECTION_RTL,
  GTK_PACK_DIRECTION_TTB,
  GTK_PACK_DIRECTION_BTT
} GtkPackDirection;

gtk_menu_bar_set_pack_direction ()

void                gtk_menu_bar_set_pack_direction     (GtkMenuBar *menubar,
                                                         GtkPackDirection pack_dir);

Sets how items should be packed inside a menubar.

menubar : | a GtkMenuBar.
pack_dir : | a new GtkPackDirection.

Since 2.8

gtk_menu_bar_get_pack_direction ()

GtkPackDirection    gtk_menu_bar_get_pack_direction     (GtkMenuBar *menubar);

Retrieves the current pack direction of the menubar. See gtk_menu_bar_set_pack_direction().

menubar : | a GtkMenuBar
Returns : | the pack direction

Since 2.8

gtk_menu_bar_set_child_pack_direction ()

void                gtk_menu_bar_set_child_pack_direction
                                                        (GtkMenuBar *menubar,
                                                         GtkPackDirection child_pack_dir);

Sets how widgets should be packed inside the children of a menubar.

menubar : | a GtkMenuBar.
child_pack_dir : | a new GtkPackDirection.

Since 2.8

gtk_menu_bar_get_child_pack_direction ()

GtkPackDirection    gtk_menu_bar_get_child_pack_direction
                                                        (GtkMenuBar *menubar);

Retrieves the current child pack direction of the menubar. See gtk_menu_bar_set_child_pack_direction().

menubar : | a GtkMenuBar
Returns : | the child pack direction

Since 2.8

Property Details

The "child-pack-direction" property

  "child-pack-direction"     GtkPackDirection      : Read / Write

The pack direction of the menubar. It determines how the widgets contained in child menuitems are arranged.

Default value: GTK_PACK_DIRECTION_LTR

Since 2.8

The "pack-direction" property

  "pack-direction"           GtkPackDirection      : Read / Write

The pack direction of the menubar. It determines how menuitems are arranged in the menubar.

Default value: GTK_PACK_DIRECTION_LTR

Since 2.8

Style Property Details

The "internal-padding" style property

  "internal-padding"         gint                  : Read

Amount of border space between the menubar shadow and the menu items.

Allowed values: >= 0

Default value: 1

The "shadow-type" style property

  "shadow-type"              GtkShadowType         : Read

Style of bevel around the menubar.

Default value: GTK_SHADOW_OUT

See Also

GtkMenuShell, GtkMenu, GtkMenuItem


GtkMenuItem

GtkMenuItem — The widget used for item in menus

Synopsis

#include <gtk/gtk.h>

                    GtkMenuItem;
GtkWidget*          gtk_menu_item_new                   (void);
GtkWidget*          gtk_menu_item_new_with_label        (const gchar *label);
GtkWidget*          gtk_menu_item_new_with_mnemonic     (const gchar *label);
void                gtk_menu_item_set_right_justified   (GtkMenuItem *menu_item,
                                                         gboolean right_justified);
void                gtk_menu_item_set_submenu           (GtkMenuItem *menu_item,
                                                         GtkWidget *submenu);
void                gtk_menu_item_set_accel_path        (GtkMenuItem *menu_item,
                                                         const gchar *accel_path);
void                gtk_menu_item_remove_submenu        (GtkMenuItem *menu_item);
void                gtk_menu_item_select                (GtkMenuItem *menu_item);
void                gtk_menu_item_deselect              (GtkMenuItem *menu_item);
void                gtk_menu_item_activate              (GtkMenuItem *menu_item);
void                gtk_menu_item_toggle_size_request   (GtkMenuItem *menu_item,
                                                         gint *requisition);
void                gtk_menu_item_toggle_size_allocate  (GtkMenuItem *menu_item,
                                                         gint allocation);
#define             gtk_menu_item_right_justify         (menu_item)
gboolean            gtk_menu_item_get_right_justified   (GtkMenuItem *menu_item);
GtkWidget*          gtk_menu_item_get_submenu           (GtkMenuItem *menu_item);

Object Hierarchy

  GObject
   +----GInitiallyUnowned
         +----GtkObject
               +----GtkWidget
                     +----GtkContainer
                           +----GtkBin
                                 +----GtkItem
                                       +----GtkMenuItem
                                             +----GtkCheckMenuItem
                                             +----GtkImageMenuItem
                                             +----GtkSeparatorMenuItem
                                             +----GtkTearoffMenuItem

Implemented Interfaces

GtkMenuItem implements AtkImplementorIface.

Style Properties

  "arrow-spacing"            gint                  : Read
  "horizontal-padding"       gint                  : Read
  "selected-shadow-type"     GtkShadowType         : Read
  "toggle-spacing"           gint                  : Read

Signals

  "activate"                                       : Run First / Action
  "activate-item"                                  : Run First
  "toggle-size-allocate"                           : Run First
  "toggle-size-request"                            : Run First

Description

The GtkMenuItem widget and the derived widgets are the only valid childs for menus. Their function is to correctly handle highlighting, alignment, events and submenus.

As it derives from GtkBin it can hold any valid child widget, altough only a few are really useful.

Details

GtkMenuItem

typedef struct _GtkMenuItem GtkMenuItem;

gtk_menu_item_new ()

GtkWidget*          gtk_menu_item_new                   (void);

Creates a new GtkMenuItem.

Returns : the newly created GtkMenuItem

gtk_menu_item_new_with_label ()

GtkWidget*          gtk_menu_item_new_with_label        (const gchar *label);

Creates a new GtkMenuItem whose child is a GtkLabel.

label : | the text for the label
Returns : | the newly created GtkMenuItem

gtk_menu_item_new_with_mnemonic ()

GtkWidget*          gtk_menu_item_new_with_mnemonic     (const gchar *label);

Creates a new GtkMenuItem containing a label. The label will be created using gtk_label_new_with_mnemonic(), so underscores in label indicate the mnemonic for the menu item.

label : | The text of the button, with an underscore in front of the mnemonic character
Returns : | a new GtkMenuItem

gtk_menu_item_set_right_justified ()

void                gtk_menu_item_set_right_justified   (GtkMenuItem *menu_item,
                                                         gboolean right_justified);

Sets whether the menu item appears justified at the right side of a menu bar. This was traditionally done for "Help" menu items, but is now considered a bad idea. (If the widget layout is reversed for a right-to-left language like Hebrew or Arabic, right-justified-menu-items appear at the left.)

menu_item : | a GtkMenuItem.
right_justified : | if TRUE the menu item will appear at the far right if added to a menu bar.

gtk_menu_item_set_submenu ()

void                gtk_menu_item_set_submenu           (GtkMenuItem *menu_item,
                                                         GtkWidget *submenu);

Sets the widget submenu, or changes it.

menu_item : | the menu item widget
submenu : | the submenu

gtk_menu_item_set_accel_path ()

void                gtk_menu_item_set_accel_path        (GtkMenuItem *menu_item,
                                                         const gchar *accel_path);

Set the accelerator path on menu_item, through which runtime changes of the menu item's accelerator caused by the user can be identified and saved to persistent storage (see gtk_accel_map_save() on this). To setup a default accelerator for this menu item, call gtk_accel_map_add_entry() with the same accel_path. See also gtk_accel_map_add_entry() on the specifics of accelerator paths, and gtk_menu_set_accel_path() for a more convenient variant of this function.

This function is basically a convenience wrapper that handles calling gtk_widget_set_accel_path() with the appropriate accelerator group for the menu item.

Note that you do need to set an accelerator on the parent menu with gtk_menu_set_accel_group() for this to work.

menu_item : | a valid GtkMenuItem
accel_path : | accelerator path, corresponding to this menu item's functionality, or NULL to unset the current path.

gtk_menu_item_remove_submenu ()

void                gtk_menu_item_remove_submenu        (GtkMenuItem *menu_item);

Removes the widget's submenu.

menu_item : the menu item widget

gtk_menu_item_select ()

void                gtk_menu_item_select                (GtkMenuItem *menu_item);

Emits the "select" signal on the given item. Behaves exactly like gtk_item_select.

menu_item : the menu item

gtk_menu_item_deselect ()

void                gtk_menu_item_deselect              (GtkMenuItem *menu_item);

Emits the "deselect" signal on the given item. Behaves exactly like gtk_item_deselect.

menu_item : the menu item

gtk_menu_item_activate ()

void                gtk_menu_item_activate              (GtkMenuItem *menu_item);

Emits the "activate" signal on the given item

menu_item : the menu item

gtk_menu_item_toggle_size_request ()

void                gtk_menu_item_toggle_size_request   (GtkMenuItem *menu_item,
                                                         gint *requisition);

Emits the "toggle_size_request" signal on the given item.

menu_item : | the menu item
requisition : | the requisition to use as signal data.

gtk_menu_item_toggle_size_allocate ()

void                gtk_menu_item_toggle_size_allocate  (GtkMenuItem *menu_item,
                                                         gint allocation);

Emits the "toggle_size_allocate" signal on the given item.

menu_item : | the menu item.
allocation : | the allocation to use as signal data.

gtk_menu_item_right_justify()

#define gtk_menu_item_right_justify(menu_item) gtk_menu_item_set_right_justified ((menu_item), TRUE)

Warning

gtk_menu_item_right_justify is deprecated and should not be used in newly-written code.

Sets the menu item to be right-justified. Only useful for menu bars.

menu_item : the menu item

gtk_menu_item_get_right_justified ()

gboolean            gtk_menu_item_get_right_justified   (GtkMenuItem *menu_item);

Gets whether the menu item appears justified at the right side of the menu bar.

menu_item : | a GtkMenuItem
Returns : | TRUE if the menu item will appear at the far right if added to a menu bar.

gtk_menu_item_get_submenu ()

GtkWidget*          gtk_menu_item_get_submenu           (GtkMenuItem *menu_item);

Gets the submenu underneath this menu item, if any. See gtk_menu_item_set_submenu().

menu_item : | a GtkMenuItem
Returns : | submenu for this menu item, or NULL if none.

Style Property Details

The "arrow-spacing" style property

  "arrow-spacing"            gint                  : Read

Space between label and arrow.

Allowed values: >= 0

Default value: 10

The "horizontal-padding" style property

  "horizontal-padding"       gint                  : Read

Padding to left and right of the menu item.

Allowed values: >= 0

Default value: 3

The "selected-shadow-type" style property

  "selected-shadow-type"     GtkShadowType         : Read

Shadow type when item is selected.

Default value: GTK_SHADOW_NONE

The "toggle-spacing" style property

  "toggle-spacing"           gint                  : Read

Space between icon and label.

Allowed values: >= 0

Default value: 5

Signal Details

The "activate" signal

void                user_function                      (GtkMenuItem *menuitem,
                                                        gpointer     user_data)      : Run First / Action

Emitted when the item is activated.

menuitem : | the object which received the signal.
user_data : | user data set when the signal handler was connected.

The "activate-item" signal

void                user_function                      (GtkMenuItem *menuitem,
                                                        gpointer     user_data)      : Run First

Emitted when the item is activated, but also if the menu item has a submenu. For normal applications, the relevant signal is "activate".

menuitem : | the object which received the signal.
user_data : | user data set when the signal handler was connected.

The "toggle-size-allocate" signal

void                user_function                      (GtkMenuItem *menuitem,
                                                        gint         arg1,
                                                        gpointer     user_data)      : Run First

menuitem : | the object which received the signal.
arg1 : |
user_data : | user data set when the signal handler was connected.

The "toggle-size-request" signal

void                user_function                      (GtkMenuItem *menuitem,
                                                        gpointer     arg1,
                                                        gpointer     user_data)      : Run First

menuitem : | the object which received the signal.
arg1 : |
user_data : | user data set when the signal handler was connected.

See Also

GtkBin | for how to handle the child.
GtkItem | is the abstract class for all sorts of items.
GtkMenuShell | is always the parent of GtkMenuItem.


GtkMenuShell

GtkMenuShell — A base class for menu objects

Synopsis

#include <gtk/gtk.h>

                    GtkMenuShell;
void                gtk_menu_shell_append               (GtkMenuShell *menu_shell,
                                                         GtkWidget *child);
void                gtk_menu_shell_prepend              (GtkMenuShell *menu_shell,
                                                         GtkWidget *child);
void                gtk_menu_shell_insert               (GtkMenuShell *menu_shell,
                                                         GtkWidget *child,
                                                         gint position);
void                gtk_menu_shell_deactivate           (GtkMenuShell *menu_shell);
void                gtk_menu_shell_select_item          (GtkMenuShell *menu_shell,
                                                         GtkWidget *menu_item);
void                gtk_menu_shell_select_first         (GtkMenuShell *menu_shell,
                                                         gboolean search_sensitive);
void                gtk_menu_shell_deselect             (GtkMenuShell *menu_shell);
void                gtk_menu_shell_activate_item        (GtkMenuShell *menu_shell,
                                                         GtkWidget *menu_item,
                                                         gboolean force_deactivate);
void                gtk_menu_shell_cancel               (GtkMenuShell *menu_shell);
void                gtk_menu_shell_set_take_focus       (GtkMenuShell *menu_shell,
                                                         gboolean take_focus);
gboolean            gtk_menu_shell_get_take_focus       (GtkMenuShell *menu_shell);
enum                GtkMenuDirectionType;

Object Hierarchy

  GObject
   +----GInitiallyUnowned
         +----GtkObject
               +----GtkWidget
                     +----GtkContainer
                           +----GtkMenuShell
                                 +----GtkMenuBar
                                 +----GtkMenu

Implemented Interfaces

GtkMenuShell implements AtkImplementorIface.

Properties

  "take-focus"               gboolean              : Read / Write

Signals

  "activate-current"                               : Run Last / Action
  "cancel"                                         : Run Last / Action
  "cycle-focus"                                    : Run Last / Action
  "deactivate"                                     : Run First
  "move-current"                                   : Run Last / Action
  "selection-done"                                 : Run First

Description

A GtkMenuShell is the abstract base class used to derive the GtkMenu and GtkMenuBar subclasses.

A GtkMenuShell is a container of GtkMenuItem objects arranged in a list which can be navigated, selected, and activated by the user to perform application functions. A GtkMenuItem can have a submenu associated with it, allowing for nested hierarchical menus.

Details

GtkMenuShell

typedef struct _GtkMenuShell GtkMenuShell;

The GtkMenuShell struct contains the following fields. (These fields should be considered read-only. They should never be set by an application.)

GList *children; The list of GtkMenuItem objects contained by this GtkMenuShell.

gtk_menu_shell_append ()

void                gtk_menu_shell_append               (GtkMenuShell *menu_shell,
                                                         GtkWidget *child);

Adds a new GtkMenuItem to the end of the menu shell's item list.

menu_shell : | a GtkMenuShell.
child : | The GtkMenuItem to add.

gtk_menu_shell_prepend ()

void                gtk_menu_shell_prepend              (GtkMenuShell *menu_shell,
                                                         GtkWidget *child);

Adds a new GtkMenuItem to the beginning of the menu shell's item list.

menu_shell : | a GtkMenuShell.
child : | The GtkMenuItem to add.

gtk_menu_shell_insert ()

void                gtk_menu_shell_insert               (GtkMenuShell *menu_shell,
                                                         GtkWidget *child,
                                                         gint position);

Adds a new GtkMenuItem to the menu shell's item list at the position indicated by position.

menu_shell : | a GtkMenuShell.
child : | The GtkMenuItem to add.
position : | The position in the item list where child is added. Positions are numbered from 0 to n-1.

gtk_menu_shell_deactivate ()

void                gtk_menu_shell_deactivate           (GtkMenuShell *menu_shell);

Deactivates the menu shell. Typically this results in the menu shell being erased from the screen.

menu_shell : a GtkMenuShell.

gtk_menu_shell_select_item ()

void                gtk_menu_shell_select_item          (GtkMenuShell *menu_shell,
                                                         GtkWidget *menu_item);

Selects the menu item from the menu shell.

menu_shell : | a GtkMenuShell.
menu_item : | The GtkMenuItem to select.

gtk_menu_shell_select_first ()

void                gtk_menu_shell_select_first         (GtkMenuShell *menu_shell,
                                                         gboolean search_sensitive);

Select the first visible or selectable child of the menu shell; don't select tearoff items unless the only item is a tearoff item.

menu_shell : | a GtkMenuShell
search_sensitive : | if TRUE, search for the first selectable menu item, otherwise select nothing if the first item isn't sensitive. This should be FALSE if the menu is being popped up initially.

Since 2.2

gtk_menu_shell_deselect ()

void                gtk_menu_shell_deselect             (GtkMenuShell *menu_shell);

Deselects the currently selected item from the menu shell, if any.

menu_shell : a GtkMenuShell.

gtk_menu_shell_activate_item ()

void                gtk_menu_shell_activate_item        (GtkMenuShell *menu_shell,
                                                         GtkWidget *menu_item,
                                                         gboolean force_deactivate);

Activates the menu item within the menu shell.

menu_shell : | a GtkMenuShell.
menu_item : | The GtkMenuItem to activate.
force_deactivate : | If TRUE, force the deactivation of the menu shell after the menu item is activated.

gtk_menu_shell_cancel ()

void                gtk_menu_shell_cancel               (GtkMenuShell *menu_shell);

Cancels the selection within the menu shell.

menu_shell : a GtkMenuShell

Since 2.4

gtk_menu_shell_set_take_focus ()

void                gtk_menu_shell_set_take_focus       (GtkMenuShell *menu_shell,
                                                         gboolean take_focus);

If take_focus is TRUE (the default) the menu shell will take the keyboard focus so that it will receive all keyboard events which is needed to enable keyboard navigation in menus.

Setting take_focus to FALSE is useful only for special applications like virtual keyboard implementations which should not take keyboard focus.

The take_focus state of a menu or menu bar is automatically propagated to submenus whenever a submenu is popped up, so you don't have to worry about recursively setting it for your entire menu hierarchy. Only when programmatically picking a submenu and popping it up manually, the take_focus property of the submenu needs to be set explicitely.

Note that setting it to FALSE has side-effects:

If the focus is in some other app, it keeps the focus and keynav in the menu doesn't work. Consequently, keynav on the menu will only work if the focus is on some toplevel owned by the onscreen keyboard.

To avoid confusing the user, menus with take_focus set to FALSE should not display mnemonics or accelerators, since it cannot be guaranteed that they will work.

See also gdk_keyboard_grab()

menu_shell : | a GtkMenuShell
take_focus : | TRUE if the menu shell should take the keyboard focus on popup.

Since 2.8

gtk_menu_shell_get_take_focus ()

gboolean            gtk_menu_shell_get_take_focus       (GtkMenuShell *menu_shell);

Returns TRUE if the menu shell will take the keyboard focus on popup.

menu_shell : | a GtkMenuShell
Returns : | TRUE if the menu shell will take the keyboard focus on popup.

Since 2.8

enum GtkMenuDirectionType

typedef enum
{
  GTK_MENU_DIR_PARENT,
  GTK_MENU_DIR_CHILD,
  GTK_MENU_DIR_NEXT,
  GTK_MENU_DIR_PREV
} GtkMenuDirectionType;

An enumeration representing directional movements within a menu.

GTK_MENU_DIR_PARENT | To the parent menu shell.
GTK_MENU_DIR_CHILD | To the submenu, if any, associated with the item.
GTK_MENU_DIR_NEXT | To the next menu item.
GTK_MENU_DIR_PREV | To the previous menu item.

Property Details

The "take-focus" property

  "take-focus"               gboolean              : Read / Write

A boolean that determines whether the menu and its submenus grab the keyboard focus. See gtk_menu_shell_set_take_focus() and gtk_menu_shell_get_take_focus().

Default value: TRUE

Since 2.8

Signal Details

The "activate-current" signal

void                user_function                      (GtkMenuShell *menushell,
                                                        gboolean      force_hide,
                                                        gpointer      user_data)       : Run Last / Action

An action signal that activates the current menu item within the menu shell.

menushell : | the object which received the signal.
force_hide : | if TRUE, hide the menu after activating the menu item.
user_data : | user data set when the signal handler was connected.

The "cancel" signal

void                user_function                      (GtkMenuShell *menushell,
                                                        gpointer      user_data)      : Run Last / Action

An action signal which cancels the selection within the menu shell. Causes the GtkMenuShell::selection-done signal to be emitted.

menushell : | the object which received the signal.
user_data : | user data set when the signal handler was connected.

The "cycle-focus" signal

void                user_function                      (GtkMenuShell    *menushell,
                                                        GtkDirectionType arg1,
                                                        gpointer         user_data)      : Run Last / Action

menushell : | the object which received the signal.
arg1 : |
user_data : | user data set when the signal handler was connected.

The "deactivate" signal

void                user_function                      (GtkMenuShell *menushell,
                                                        gpointer      user_data)      : Run First

This signal is emitted when a menu shell is deactivated.

menushell : | the object which received the signal.
user_data : | user data set when the signal handler was connected.

The "move-current" signal

void                user_function                      (GtkMenuShell        *menushell,
                                                        GtkMenuDirectionType direction,
                                                        gpointer             user_data)      : Run Last / Action

An action signal which moves the current menu item in the direction specified by direction.

menushell : | the object which received the signal.
direction : | the direction to move.
user_data : | user data set when the signal handler was connected.

The "selection-done" signal

void                user_function                      (GtkMenuShell *menushell,
                                                        gpointer      user_data)      : Run First

This signal is emitted when a selection has been completed within a menu shell.

menushell : | the object which received the signal.
user_data : | user data set when the signal handler was connected.


GtkMenuToolButton

GtkMenuToolButton — A GtkToolItem containing a button with an additional dropdown menu

Synopsis

#include <gtk/gtk.h>

                    GtkMenuToolButton;
GtkToolItem*        gtk_menu_tool_button_new            (GtkWidget *icon_widget,
                                                         const gchar *label);
GtkToolItem*        gtk_menu_tool_button_new_from_stock (const gchar *stock_id);
void                gtk_menu_tool_button_set_menu       (GtkMenuToolButton *button,
                                                         GtkWidget *menu);
GtkWidget*          gtk_menu_tool_button_get_menu       (GtkMenuToolButton *button);
void                gtk_menu_tool_button_set_arrow_tooltip
                                                        (GtkMenuToolButton *button,
                                                         GtkTooltips *tooltips,
                                                         const gchar *tip_text,
                                                         const gchar *tip_private);

Object Hierarchy

  GObject
   +----GInitiallyUnowned
         +----GtkObject
               +----GtkWidget
                     +----GtkContainer
                           +----GtkBin
                                 +----GtkToolItem
                                       +----GtkToolButton
                                             +----GtkMenuToolButton

Implemented Interfaces

GtkMenuToolButton implements AtkImplementorIface.

Properties

  "menu"                     GtkMenu               : Read / Write

Signals

  "show-menu"                                      : Run First

Description

A GtkMenuToolButton is a GtkToolItem that contains a button and a small additional button with an arrow. When clicked, the arrow button pops up a dropdown menu.

Use gtk_menu_tool_button_new() to create a new GtkMenuToolButton. Use gtk_menu_tool_button_new_from_stock() to create a new GtkMenuToolButton containing a stock item.

Details

GtkMenuToolButton

typedef struct _GtkMenuToolButton GtkMenuToolButton;

The GtkMenuToolButton struct contains only private data and should only be accessed through the functions described below.

gtk_menu_tool_button_new ()

GtkToolItem*        gtk_menu_tool_button_new            (GtkWidget *icon_widget,
                                                         const gchar *label);

Creates a new GtkMenuToolButton using icon_widget as icon and label as label.

icon_widget : | a widget that will be used as icon widget, or NULL
label : | a string that will be used as label, or NULL
Returns : | the new GtkMenuToolButton

Since 2.6

gtk_menu_tool_button_new_from_stock ()

GtkToolItem*        gtk_menu_tool_button_new_from_stock (const gchar *stock_id);

Creates a new GtkMenuToolButton. The new GtkMenuToolButton will contain an icon and label from the stock item indicated by stock_id.

stock_id : | the name of a stock item
Returns : | the new GtkMenuToolButton

Since 2.6

gtk_menu_tool_button_set_menu ()

void                gtk_menu_tool_button_set_menu       (GtkMenuToolButton *button,
                                                         GtkWidget *menu);

Sets the GtkMenu that is popped up when the user clicks on the arrow. If menu is NULL, the arrow button becomes insensitive.

button : | a GtkMenuToolButton
menu : | the GtkMenu associated with GtkMenuToolButton

Since 2.6

gtk_menu_tool_button_get_menu ()

GtkWidget*          gtk_menu_tool_button_get_menu       (GtkMenuToolButton *button);

Gets the GtkMenu associated with GtkMenuToolButton.

button : | a GtkMenuToolButton
Returns : | the GtkMenu associated with GtkMenuToolButton

Since 2.6

gtk_menu_tool_button_set_arrow_tooltip ()

void                gtk_menu_tool_button_set_arrow_tooltip
                                                        (GtkMenuToolButton *button,
                                                         GtkTooltips *tooltips,
                                                         const gchar *tip_text,
                                                         const gchar *tip_private);

Sets the GtkTooltips object to be used for arrow button which pops up the menu. See gtk_tool_item_set_tooltip() for setting a tooltip on the whole GtkMenuToolButton.

button : | a GtkMenuToolButton
tooltips : | the GtkTooltips object to be used
tip_text : | text to be used as tooltip text for tool_item
tip_private : | text to be used as private tooltip text

Since 2.6

Property Details

The "menu" property

  "menu"                     GtkMenu               : Read / Write

The dropdown menu.

Signal Details

The "show-menu" signal

void                user_function                      (GtkMenuToolButton *menutoolbutton,
                                                        gpointer           user_data)           : Run First

menutoolbutton : | the object which received the signal.
user_data : | user data set when the signal handler was connected.

See Also

GtkToolbar, GtkToolButton

The toolbar widget

The parent class of GtkMenuToolButton. The properties "label_widget", "label", "icon_widget", and "stock_id" on GtkToolButton determine the label and icon used on GtkMenuToolButtons.


GtkMessageDialog

GtkMessageDialog — A convenient message window

Synopsis

#include <gtk/gtk.h>

                    GtkMessageDialog;
enum                GtkMessageType;
enum                GtkButtonsType;
GtkWidget*          gtk_message_dialog_new              (GtkWindow *parent,
                                                         GtkDialogFlags flags,
                                                         GtkMessageType type,
                                                         GtkButtonsType buttons,
                                                         const gchar *message_format,
                                                         ...);
GtkWidget*          gtk_message_dialog_new_with_markup  (GtkWindow *parent,
                                                         GtkDialogFlags flags,
                                                         GtkMessageType type,
                                                         GtkButtonsType buttons,
                                                         const gchar *message_format,
                                                         ...);
void                gtk_message_dialog_set_markup       (GtkMessageDialog *message_dialog,
                                                         const gchar *str);
void                gtk_message_dialog_set_image        (GtkMessageDialog *dialog,
                                                         GtkWidget *image);
void                gtk_message_dialog_format_secondary_text
                                                        (GtkMessageDialog *message_dialog,
                                                         const gchar *message_format,
                                                         ...);
void                gtk_message_dialog_format_secondary_markup
                                                        (GtkMessageDialog *message_dialog,
                                                         const gchar *message_format,
                                                         ...);

Object Hierarchy

  GObject
   +----GInitiallyUnowned
         +----GtkObject
               +----GtkWidget
                     +----GtkContainer
                           +----GtkBin
                                 +----GtkWindow
                                       +----GtkDialog
                                             +----GtkMessageDialog

Implemented Interfaces

GtkMessageDialog implements AtkImplementorIface.

Properties

  "buttons"                  GtkButtonsType        : Write / Construct Only
  "image"                    GtkWidget             : Read / Write
  "message-type"             GtkMessageType        : Read / Write / Construct
  "secondary-text"           gchararray            : Read / Write
  "secondary-use-markup"     gboolean              : Read / Write
  "text"                     gchararray            : Read / Write
  "use-markup"               gboolean              : Read / Write

Style Properties

  "message-border"           gint                  : Read
  "use-separator"            gboolean              : Read

Description

GtkMessageDialog presents a dialog with an image representing the type of message (Error, Question, etc.) alongside some message text. It's simply a convenience widget; you could construct the equivalent of GtkMessageDialog from GtkDialog without too much effort, but GtkMessageDialog saves typing.

The easiest way to do a modal message dialog is to use gtk_dialog_run(), though you can also pass in the GTK_DIALOG_MODAL flag, gtk_dialog_run() automatically makes the dialog modal and waits for the user to respond to it. gtk_dialog_run() returns when any dialog button is clicked.

Example 5. A modal dialog.

 dialog = gtk_message_dialog_new (main_application_window,
                                  GTK_DIALOG_DESTROY_WITH_PARENT,
                                  GTK_MESSAGE_ERROR,
                                  GTK_BUTTONS_CLOSE,
                                  "Error loading file '%s': %s",
                                  filename, g_strerror (errno));
 gtk_dialog_run (GTK_DIALOG (dialog));
 gtk_widget_destroy (dialog);

You might do a non-modal GtkMessageDialog as follows:

Example 6. A non-modal dialog.

 dialog = gtk_message_dialog_new (main_application_window,
                                  GTK_DIALOG_DESTROY_WITH_PARENT,
                                  GTK_MESSAGE_ERROR,
                                  GTK_BUTTONS_CLOSE,
                                  "Error loading file '%s': %s",
                                  filename, g_strerror (errno));

 /* Destroy the dialog when the user responds to it (e.g. clicks a button) */
 g_signal_connect_swapped (dialog, "response",
                           G_CALLBACK (gtk_widget_destroy),
                           dialog);

Details

GtkMessageDialog

typedef struct _GtkMessageDialog GtkMessageDialog;

enum GtkMessageType

typedef enum
{
  GTK_MESSAGE_INFO,
  GTK_MESSAGE_WARNING,
  GTK_MESSAGE_QUESTION,
  GTK_MESSAGE_ERROR,
  GTK_MESSAGE_OTHER
} GtkMessageType;

The type of message being displayed in the dialog.

GTK_MESSAGE_INFO | Informational message
GTK_MESSAGE_WARNING | Nonfatal warning message
GTK_MESSAGE_QUESTION | Question requiring a choice
GTK_MESSAGE_ERROR | Fatal error message
GTK_MESSAGE_OTHER |

enum GtkButtonsType

typedef enum
{
  GTK_BUTTONS_NONE,
  GTK_BUTTONS_OK,
  GTK_BUTTONS_CLOSE,
  GTK_BUTTONS_CANCEL,
  GTK_BUTTONS_YES_NO,
  GTK_BUTTONS_OK_CANCEL
} GtkButtonsType;

Prebuilt sets of buttons for the dialog. If none of these choices are appropriate, simply use GTK_BUTTONS_NONE then call gtk_dialog_add_buttons().

GTK_BUTTONS_NONE | no buttons at all
GTK_BUTTONS_OK | an OK button
GTK_BUTTONS_CLOSE | a Close button
GTK_BUTTONS_CANCEL | a Cancel button
GTK_BUTTONS_YES_NO | Yes and No buttons
GTK_BUTTONS_OK_CANCEL | OK and Cancel buttons

gtk_message_dialog_new ()

GtkWidget*          gtk_message_dialog_new              (GtkWindow *parent,
                                                         GtkDialogFlags flags,
                                                         GtkMessageType type,
                                                         GtkButtonsType buttons,
                                                         const gchar *message_format,
                                                         ...);

Creates a new message dialog, which is a simple dialog with an icon indicating the dialog type (error, warning, etc.) and some text the user may want to see. When the user clicks a button a "response" signal is emitted with response IDs from GtkResponseType. See GtkDialog for more details.

parent : | transient parent, or NULL for none
flags : | flags
type : | type of message
buttons : | set of buttons to use
message_format : | printf()-style format string, or NULL
... : | arguments for message_format
Returns : | a new GtkMessageDialog

gtk_message_dialog_new_with_markup ()

GtkWidget*          gtk_message_dialog_new_with_markup  (GtkWindow *parent,
                                                         GtkDialogFlags flags,
                                                         GtkMessageType type,
                                                         GtkButtonsType buttons,
                                                         const gchar *message_format,
                                                         ...);

Creates a new message dialog, which is a simple dialog with an icon indicating the dialog type (error, warning, etc.) and some text which is marked up with the Pango text markup language. When the user clicks a button a "response" signal is emitted with response IDs from GtkResponseType. See GtkDialog for more details.

Special XML characters in the printf() arguments passed to this function will automatically be escaped as necessary. (See g_markup_printf_escaped() for how this is implemented.) Usually this is what you want, but if you have an existing Pango markup string that you want to use literally as the label, then you need to use gtk_message_dialog_set_markup() instead, since you can't pass the markup string either as the format (it might contain '%' characters) or as a string argument.

 GtkWidget *dialog;
 dialog = gtk_message_dialog_new (main_application_window,
                                  GTK_DIALOG_DESTROY_WITH_PARENT,
                                  GTK_MESSAGE_ERROR,
                                  GTK_BUTTONS_CLOSE,
                                  NULL);
 gtk_message_dialog_set_markup (GTK_MESSAGE_DIALOG (dialog),
                                markup);

parent : | transient parent, or NULL for none
flags : | flags
type : | type of message
buttons : | set of buttons to use
message_format : | printf()-style format string, or NULL
... : | arguments for message_format
Returns : | a new GtkMessageDialog

Since 2.4

gtk_message_dialog_set_markup ()

void                gtk_message_dialog_set_markup       (GtkMessageDialog *message_dialog,
                                                         const gchar *str);

Sets the text of the message dialog to be str, which is marked up with the Pango text markup language.

message_dialog : | a GtkMessageDialog
str : | markup string (see Pango markup format)

Since 2.4

gtk_message_dialog_set_image ()

void                gtk_message_dialog_set_image        (GtkMessageDialog *dialog,
                                                         GtkWidget *image);

Sets the dialog's image to image.

dialog : | a GtkMessageDialog
image : | the image

Since 2.10

gtk_message_dialog_format_secondary_text ()

void                gtk_message_dialog_format_secondary_text
                                                        (GtkMessageDialog *message_dialog,
                                                         const gchar *message_format,
                                                         ...);

Sets the secondary text of the message dialog to be message_format (with printf()-style).

Note that setting a secondary text makes the primary text become bold, unless you have provided explicit markup.

message_dialog : | a GtkMessageDialog
message_format : | printf()-style format string, or NULL
... : | arguments for message_format

Since 2.6

gtk_message_dialog_format_secondary_markup ()

void                gtk_message_dialog_format_secondary_markup
                                                        (GtkMessageDialog *message_dialog,
                                                         const gchar *message_format,
                                                         ...);

Sets the secondary text of the message dialog to be message_format (with printf()-style), which is marked up with the Pango text markup language.

Note that setting a secondary text makes the primary text become bold, unless you have provided explicit markup.

Due to an oversight, this function does not escape special XML characters like gtk_message_dialog_new_with_markup() does. Thus, if the arguments may contain special XML characters, you should use g_markup_printf_escaped() to escape it.

gchar *msg;

msg = g_markup_printf_escaped (message_format, ...);
gtk_message_dialog_format_secondary_markup (message_dialog, "%s", msg);
g_free (msg);

message_dialog : | a GtkMessageDialog
message_format : | printf()-style markup string (see Pango markup format), or NULL
... : | arguments for message_format

Since 2.6

Property Details

The "buttons" property

  "buttons"                  GtkButtonsType        : Write / Construct Only

The buttons shown in the message dialog.

Default value: GTK_BUTTONS_NONE

The "image" property

  "image"                    GtkWidget             : Read / Write

The image for this dialog.

Since 2.10

The "message-type" property

  "message-type"             GtkMessageType        : Read / Write / Construct

The type of the message. The type is used to determine the image that is shown in the dialog, unless the image is explicitly set by the ::image property.

Default value: GTK_MESSAGE_INFO

The "secondary-text" property

  "secondary-text"           gchararray            : Read / Write

The secondary text of the message dialog.

Default value: NULL

Since 2.10

The "secondary-use-markup" property

  "secondary-use-markup"     gboolean              : Read / Write

TRUE if the secondary text of the dialog includes Pango markup. See pango_parse_markup().

Default value: FALSE

Since 2.10

The "text" property

  "text"                     gchararray            : Read / Write

The primary text of the message dialog. If the dialog has a secondary text, this will appear as the title.

Default value: NULL

Since 2.10

The "use-markup" property

  "use-markup"               gboolean              : Read / Write

TRUE if the primary text of the dialog includes Pango markup. See pango_parse_markup().

Default value: FALSE

Since 2.10

Style Property Details

The "message-border" style property

  "message-border"           gint                  : Read

Width of border around the label and image in the message dialog.

Allowed values: >= 0

Default value: 12

The "use-separator" style property

  "use-separator"            gboolean              : Read

Whether to draw a separator line between the message label and the buttons in the dialog.

Default value: FALSE

Since 2.4

See Also

GtkDialog


GtkMisc

GtkMisc — Base class for widgets with alignments and padding

Synopsis

#include <gtk/gtk.h>

                    GtkMisc;
void                gtk_misc_set_alignment              (GtkMisc *misc,
                                                         gfloat xalign,
                                                         gfloat yalign);
void                gtk_misc_set_padding                (GtkMisc *misc,
                                                         gint xpad,
                                                         gint ypad);
void                gtk_misc_get_alignment              (GtkMisc *misc,
                                                         gfloat *xalign,
                                                         gfloat *yalign);
void                gtk_misc_get_padding                (GtkMisc *misc,
                                                         gint *xpad,
                                                         gint *ypad);

Object Hierarchy

  GObject
   +----GInitiallyUnowned
         +----GtkObject
               +----GtkWidget
                     +----GtkMisc
                           +----GtkLabel
                           +----GtkArrow
                           +----GtkImage
                           +----GtkPixmap

Implemented Interfaces

GtkMisc implements AtkImplementorIface.

Properties

  "xalign"                   gfloat                : Read / Write
  "xpad"                     gint                  : Read / Write
  "yalign"                   gfloat                : Read / Write
  "ypad"                     gint                  : Read / Write

Description

The GtkMisc widget is an abstract widget which is not useful itself, but is used to derive subclasses which have alignment and padding attributes.

The horizontal and vertical padding attributes allows extra space to be added around the widget.

The horizontal and vertical alignment attributes enable the widget to be positioned within its allocated area. Note that if the widget is added to a container in such a way that it expands automatically to fill its allocated area, the alignment settings will not alter the widgets position.

Details

GtkMisc

typedef struct _GtkMisc GtkMisc;

The GtkMisc struct contains the following fields. (These fields should be considered read-only. They should never be set by an application.)

gfloat xalign; | the horizontal alignment, from 0 (left) to 1 (right).
gfloat yalign; | the vertical alignment, from 0 (top) to 1 (bottom).
guint16 xpad; | the amount of space to add on the left and right of the widget, in pixels.
guint16 ypad; | the amount of space to add on the top and bottom of the widget, in pixels.

gtk_misc_set_alignment ()

void                gtk_misc_set_alignment              (GtkMisc *misc,
                                                         gfloat xalign,
                                                         gfloat yalign);

Sets the alignment of the widget.

misc : | a GtkMisc.
xalign : | the horizontal alignment, from 0 (left) to 1 (right).
yalign : | the vertical alignment, from 0 (top) to 1 (bottom).

gtk_misc_set_padding ()

void                gtk_misc_set_padding                (GtkMisc *misc,
                                                         gint xpad,
                                                         gint ypad);

Sets the amount of space to add around the widget.

misc : | a GtkMisc.
xpad : | the amount of space to add on the left and right of the widget, in pixels.
ypad : | the amount of space to add on the top and bottom of the widget, in pixels.

gtk_misc_get_alignment ()

void                gtk_misc_get_alignment              (GtkMisc *misc,
                                                         gfloat *xalign,
                                                         gfloat *yalign);

Gets the X and Y alignment of the widget within its allocation. See gtk_misc_set_alignment().

misc : | a GtkMisc
xalign : | location to store X alignment of misc, or NULL
yalign : | location to store Y alignment of misc, or NULL

gtk_misc_get_padding ()

void                gtk_misc_get_padding                (GtkMisc *misc,
                                                         gint *xpad,
                                                         gint *ypad);

Gets the padding in the X and Y directions of the widget. See gtk_misc_set_padding().

misc : | a GtkMisc
xpad : | location to store padding in the X direction, or NULL
ypad : | location to store padding in the Y direction, or NULL

Property Details

The "xalign" property

  "xalign"                   gfloat                : Read / Write

The horizontal alignment, from 0 (left) to 1 (right). Reversed for RTL layouts.

Allowed values: [0,1]

Default value: 0.5

The "xpad" property

  "xpad"                     gint                  : Read / Write

The amount of space to add on the left and right of the widget, in pixels.

Allowed values: >= 0

Default value: 0

The "yalign" property

  "yalign"                   gfloat                : Read / Write

The vertical alignment, from 0 (top) to 1 (bottom).

Allowed values: [0,1]

Default value: 0.5

The "ypad" property

  "ypad"                     gint                  : Read / Write

The amount of space to add on the top and bottom of the widget, in pixels.

Allowed values: >= 0

Default value: 0


GtkNotebook

GtkNotebook — A tabbed notebook container

Synopsis

#include <gtk/gtk.h>

                    GtkNotebook;
                    GtkNotebookPage;
GtkWidget*          gtk_notebook_new                    (void);
gint                gtk_notebook_append_page            (GtkNotebook *notebook,
                                                         GtkWidget *child,
                                                         GtkWidget *tab_label);
gint                gtk_notebook_append_page_menu       (GtkNotebook *notebook,
                                                         GtkWidget *child,
                                                         GtkWidget *tab_label,
                                                         GtkWidget *menu_label);
gint                gtk_notebook_prepend_page           (GtkNotebook *notebook,
                                                         GtkWidget *child,
                                                         GtkWidget *tab_label);
gint                gtk_notebook_prepend_page_menu      (GtkNotebook *notebook,
                                                         GtkWidget *child,
                                                         GtkWidget *tab_label,
                                                         GtkWidget *menu_label);
gint                gtk_notebook_insert_page            (GtkNotebook *notebook,
                                                         GtkWidget *child,
                                                         GtkWidget *tab_label,
                                                         gint position);
gint                gtk_notebook_insert_page_menu       (GtkNotebook *notebook,
                                                         GtkWidget *child,
                                                         GtkWidget *tab_label,
                                                         GtkWidget *menu_label,
                                                         gint position);
void                gtk_notebook_remove_page            (GtkNotebook *notebook,
                                                         gint page_num);
#define             gtk_notebook_current_page
gint                gtk_notebook_page_num               (GtkNotebook *notebook,
                                                         GtkWidget *child);
#define             gtk_notebook_set_page
void                gtk_notebook_next_page              (GtkNotebook *notebook);
void                gtk_notebook_prev_page              (GtkNotebook *notebook);
void                gtk_notebook_reorder_child          (GtkNotebook *notebook,
                                                         GtkWidget *child,
                                                         gint position);
void                gtk_notebook_set_tab_pos            (GtkNotebook *notebook,
                                                         GtkPositionType pos);
void                gtk_notebook_set_show_tabs          (GtkNotebook *notebook,
                                                         gboolean show_tabs);
void                gtk_notebook_set_show_border        (GtkNotebook *notebook,
                                                         gboolean show_border);
void                gtk_notebook_set_scrollable         (GtkNotebook *notebook,
                                                         gboolean scrollable);
void                gtk_notebook_set_tab_border         (GtkNotebook *notebook,
                                                         guint border_width);
void                gtk_notebook_popup_enable           (GtkNotebook *notebook);
void                gtk_notebook_popup_disable          (GtkNotebook *notebook);
gint                gtk_notebook_get_current_page       (GtkNotebook *notebook);
GtkWidget*          gtk_notebook_get_menu_label         (GtkNotebook *notebook,
                                                         GtkWidget *child);
GtkWidget*          gtk_notebook_get_nth_page           (GtkNotebook *notebook,
                                                         gint page_num);
gint                gtk_notebook_get_n_pages            (GtkNotebook *notebook);
GtkWidget*          gtk_notebook_get_tab_label          (GtkNotebook *notebook,
                                                         GtkWidget *child);
void                gtk_notebook_query_tab_label_packing
                                                        (GtkNotebook *notebook,
                                                         GtkWidget *child,
                                                         gboolean *expand,
                                                         gboolean *fill,
                                                         GtkPackType *pack_type);
void                gtk_notebook_set_homogeneous_tabs   (GtkNotebook *notebook,
                                                         gboolean homogeneous);
void                gtk_notebook_set_menu_label         (GtkNotebook *notebook,
                                                         GtkWidget *child,
                                                         GtkWidget *menu_label);
void                gtk_notebook_set_menu_label_text    (GtkNotebook *notebook,
                                                         GtkWidget *child,
                                                         const gchar *menu_text);
void                gtk_notebook_set_tab_hborder        (GtkNotebook *notebook,
                                                         guint tab_hborder);
void                gtk_notebook_set_tab_label          (GtkNotebook *notebook,
                                                         GtkWidget *child,
                                                         GtkWidget *tab_label);
void                gtk_notebook_set_tab_label_packing  (GtkNotebook *notebook,
                                                         GtkWidget *child,
                                                         gboolean expand,
                                                         gboolean fill,
                                                         GtkPackType pack_type);
void                gtk_notebook_set_tab_label_text     (GtkNotebook *notebook,
                                                         GtkWidget *child,
                                                         const gchar *tab_text);
void                gtk_notebook_set_tab_vborder        (GtkNotebook *notebook,
                                                         guint tab_vborder);
void                gtk_notebook_set_tab_reorderable    (GtkNotebook *notebook,
                                                         GtkWidget *child,
                                                         gboolean reorderable);
void                gtk_notebook_set_tab_detachable     (GtkNotebook *notebook,
                                                         GtkWidget *child,
                                                         gboolean detachable);
const gchar*        gtk_notebook_get_menu_label_text    (GtkNotebook *notebook,
                                                         GtkWidget *child);
gboolean            gtk_notebook_get_scrollable         (GtkNotebook *notebook);
gboolean            gtk_notebook_get_show_border        (GtkNotebook *notebook);
gboolean            gtk_notebook_get_show_tabs          (GtkNotebook *notebook);
const gchar*        gtk_notebook_get_tab_label_text     (GtkNotebook *notebook,
                                                         GtkWidget *child);
GtkPositionType     gtk_notebook_get_tab_pos            (GtkNotebook *notebook);
gboolean            gtk_notebook_get_tab_reorderable    (GtkNotebook *notebook,
                                                         GtkWidget *child);
gboolean            gtk_notebook_get_tab_detachable     (GtkNotebook *notebook,
                                                         GtkWidget *child);
void                gtk_notebook_set_current_page       (GtkNotebook *notebook,
                                                         gint page_num);
void                gtk_notebook_set_group_id           (GtkNotebook *notebook,
                                                         gint group_id);
gint                gtk_notebook_get_group_id           (GtkNotebook *notebook);
GtkNotebook*        (*GtkNotebookWindowCreationFunc)    (GtkNotebook *source,
                                                         GtkWidget *page,
                                                         gint x,
                                                         gint y,
                                                         gpointer data);
void                gtk_notebook_set_window_creation_hook
                                                        (GtkNotebookWindowCreationFunc func,
                                                         gpointer data,
                                                         GDestroyNotify destroy);

Object Hierarchy

  GObject
   +----GInitiallyUnowned
         +----GtkObject
               +----GtkWidget
                     +----GtkContainer
                           +----GtkNotebook

Implemented Interfaces

GtkNotebook implements AtkImplementorIface.

Properties

  "enable-popup"             gboolean              : Read / Write
  "group-id"                 gint                  : Read / Write
  "homogeneous"              gboolean              : Read / Write
  "page"                     gint                  : Read / Write
  "scrollable"               gboolean              : Read / Write
  "show-border"              gboolean              : Read / Write
  "show-tabs"                gboolean              : Read / Write
  "tab-border"               guint                 : Write
  "tab-hborder"              guint                 : Read / Write
  "tab-pos"                  GtkPositionType       : Read / Write
  "tab-vborder"              guint                 : Read / Write

Child Properties

  "detachable"               gboolean              : Read / Write
  "menu-label"               gchararray            : Read / Write
  "position"                 gint                  : Read / Write
  "reorderable"              gboolean              : Read / Write
  "tab-expand"               gboolean              : Read / Write
  "tab-fill"                 gboolean              : Read / Write
  "tab-label"                gchararray            : Read / Write
  "tab-pack"                 GtkPackType           : Read / Write

Style Properties

  "arrow-spacing"            gint                  : Read
  "has-backward-stepper"     gboolean              : Read
  "has-forward-stepper"      gboolean              : Read
  "has-secondary-backward-stepper" gboolean              : Read
  "has-secondary-forward-stepper" gboolean              : Read
  "tab-curvature"            gint                  : Read
  "tab-overlap"              gint                  : Read

Signals

  "change-current-page"                            : Run Last / Action
  "focus-tab"                                      : Run Last / Action
  "move-focus-out"                                 : Run Last / Action
  "page-added"                                     : Run Last
  "page-removed"                                   : Run Last
  "page-reordered"                                 : Run Last
  "reorder-tab"                                    : Run Last / Action
  "select-page"                                    : Run Last / Action
  "switch-page"                                    : Run Last

Description

The GtkNotebook widget is a GtkContainer whose children are pages that can be switched between using tab labels along one edge.

There are many configuration options for GtkNotebook. Among other things, you can choose on which edge the tabs appear (see gtk_notebook_set_tab_pos()), whether, if there are too many tabs to fit the noteobook should be made bigger or scrolling arrows added (see gtk_notebook_set_scrollable), and whether there will be a popup menu allowing the users to switch pages. (see gtk_notebook_enable_popup(), gtk_noteobook_disable_popup())

Details

GtkNotebook

typedef struct _GtkNotebook GtkNotebook;

GtkNotebookPage

typedef struct _GtkNotebookPage GtkNotebookPage;

The GtkNotebookPage is an opaque implementation detail of GtkNotebook.

gtk_notebook_new ()

GtkWidget*          gtk_notebook_new                    (void);

Creates a new GtkNotebook widget with no pages.

Returns : the newly created GtkNotebook

gtk_notebook_append_page ()

gint                gtk_notebook_append_page            (GtkNotebook *notebook,
                                                         GtkWidget *child,
                                                         GtkWidget *tab_label);

Appends a page to notebook.

notebook : | a GtkNotebook
child : | the GtkWidget to use as the contents of the page.
tab_label : | the GtkWidget to be used as the label for the page, or NULL to use the default label, 'page N'.
Returns : | the index (starting from 0) of the appended page in the notebook, or -1 if function fails

gtk_notebook_append_page_menu ()

gint                gtk_notebook_append_page_menu       (GtkNotebook *notebook,
                                                         GtkWidget *child,
                                                         GtkWidget *tab_label,
                                                         GtkWidget *menu_label);

Appends a page to notebook, specifying the widget to use as the label in the popup menu.

notebook : | a GtkNotebook
child : | the GtkWidget to use as the contents of the page.
tab_label : | the GtkWidget to be used as the label for the page, or NULL to use the default label, 'page N'.
menu_label : | the widget to use as a label for the page-switch menu, if that is enabled. If NULL, and tab_label is a GtkLabel or NULL, then the menu label will be a newly created label with the same text as tab_label; If tab_label is not a GtkLabel, menu_label must be specified if the page-switch menu is to be used.
Returns : | the index (starting from 0) of the appended page in the notebook, or -1 if function fails

gtk_notebook_prepend_page ()

gint                gtk_notebook_prepend_page           (GtkNotebook *notebook,
                                                         GtkWidget *child,
                                                         GtkWidget *tab_label);

Prepends a page to notebook.

notebook : | a GtkNotebook
child : | the GtkWidget to use as the contents of the page.
tab_label : | the GtkWidget to be used as the label for the page, or NULL to use the default label, 'page N'.
Returns : | the index (starting from 0) of the prepended page in the notebook, or -1 if function fails

gtk_notebook_prepend_page_menu ()

gint                gtk_notebook_prepend_page_menu      (GtkNotebook *notebook,
                                                         GtkWidget *child,
                                                         GtkWidget *tab_label,
                                                         GtkWidget *menu_label);

Prepends a page to notebook, specifying the widget to use as the label in the popup menu.

notebook : | a GtkNotebook
child : | the GtkWidget to use as the contents of the page.
tab_label : | the GtkWidget to be used as the label for the page, or NULL to use the default label, 'page N'.
menu_label : | the widget to use as a label for the page-switch menu, if that is enabled. If NULL, and tab_label is a GtkLabel or NULL, then the menu label will be a newly created label with the same text as tab_label; If tab_label is not a GtkLabel, menu_label must be specified if the page-switch menu is to be used.
Returns : | the index (starting from 0) of the prepended page in the notebook, or -1 if function fails

gtk_notebook_insert_page ()

gint                gtk_notebook_insert_page            (GtkNotebook *notebook,
                                                         GtkWidget *child,
                                                         GtkWidget *tab_label,
                                                         gint position);

Insert a page into notebook at the given position.

notebook : | a GtkNotebook
child : | the GtkWidget to use as the contents of the page.
tab_label : | the GtkWidget to be used as the label for the page, or NULL to use the default label, 'page N'.
position : | the index (starting at 0) at which to insert the page, or -1 to append the page after all other pages.
Returns : | the index (starting from 0) of the inserted page in the notebook, or -1 if function fails

gtk_notebook_insert_page_menu ()

gint                gtk_notebook_insert_page_menu       (GtkNotebook *notebook,
                                                         GtkWidget *child,
                                                         GtkWidget *tab_label,
                                                         GtkWidget *menu_label,
                                                         gint position);

Insert a page into notebook at the given position, specifying the widget to use as the label in the popup menu.

notebook : | a GtkNotebook
child : | the GtkWidget to use as the contents of the page.
tab_label : | the GtkWidget to be used as the label for the page, or NULL to use the default label, 'page N'.
menu_label : | the widget to use as a label for the page-switch menu, if that is enabled. If NULL, and tab_label is a GtkLabel or NULL, then the menu label will be a newly created label with the same text as tab_label; If tab_label is not a GtkLabel, menu_label must be specified if the page-switch menu is to be used.
position : | the index (starting at 0) at which to insert the page, or -1 to append the page after all other pages.
Returns : | the index (starting from 0) of the inserted page in the notebook

gtk_notebook_remove_page ()

void                gtk_notebook_remove_page            (GtkNotebook *notebook,
                                                         gint page_num);

Removes a page from the notebook given its index in the notebook.

notebook : | a GtkNotebook.
page_num : | the index of a notebook page, starting from 0. If -1, the last page will be removed.

gtk_notebook_current_page

#define	gtk_notebook_current_page               gtk_notebook_get_current_page

Warning

gtk_notebook_current_page is deprecated and should not be used in newly-written code.

Deprecated compatibility macro. Use gtk_notebook_get_current_page() instead.

gtk_notebook_page_num ()

gint                gtk_notebook_page_num               (GtkNotebook *notebook,
                                                         GtkWidget *child);

Finds the index of the page which contains the given child widget.

notebook : | a GtkNotebook
child : | a GtkWidget
Returns : | the index of the page containing child, or -1 if child is not in the notebook.

gtk_notebook_set_page

#define gtk_notebook_set_page                   gtk_notebook_set_current_page

Warning

gtk_notebook_set_page is deprecated and should not be used in newly-written code.

Deprecated compatibility macro. Use gtk_notebook_set_current_page() instead.

gtk_notebook_next_page ()

void                gtk_notebook_next_page              (GtkNotebook *notebook);

Switches to the next page. Nothing happens if the current page is the last page.

notebook : a GtkNotebook

gtk_notebook_prev_page ()

void                gtk_notebook_prev_page              (GtkNotebook *notebook);

Switches to the previous page. Nothing happens if the current page is the first page.

notebook : a GtkNotebook

gtk_notebook_reorder_child ()

void                gtk_notebook_reorder_child          (GtkNotebook *notebook,
                                                         GtkWidget *child,
                                                         gint position);

Reorders the page containing child, so that it appears in position position. If position is greater than or equal to the number of children in the list or negative, child will be moved to the end of the list.

notebook : | a GtkNotebook
child : | the child to move
position : | the new position, or -1 to move to the end

gtk_notebook_set_tab_pos ()

void                gtk_notebook_set_tab_pos            (GtkNotebook *notebook,
                                                         GtkPositionType pos);

Sets the edge at which the tabs for switching pages in the notebook are drawn.

notebook : | a GtkNotebook.
pos : | the edge to draw the tabs at.

gtk_notebook_set_show_tabs ()

void                gtk_notebook_set_show_tabs          (GtkNotebook *notebook,
                                                         gboolean show_tabs);

Sets whether to show the tabs for the notebook or not.

notebook : | a GtkNotebook
show_tabs : | TRUE if the tabs should be shown.

gtk_notebook_set_show_border ()

void                gtk_notebook_set_show_border        (GtkNotebook *notebook,
                                                         gboolean show_border);

Sets whether a bevel will be drawn around the notebook pages. This only has a visual effect when the tabs are not shown. See gtk_notebook_set_show_tabs().

notebook : | a GtkNotebook
show_border : | TRUE if a bevel should be drawn around the notebook.

gtk_notebook_set_scrollable ()

void                gtk_notebook_set_scrollable         (GtkNotebook *notebook,
                                                         gboolean scrollable);

Sets whether the tab label area will have arrows for scrolling if there are too many tabs to fit in the area.

notebook : | a GtkNotebook
scrollable : | TRUE if scroll arrows should be added

gtk_notebook_set_tab_border ()

void                gtk_notebook_set_tab_border         (GtkNotebook *notebook,
                                                         guint border_width);

Warning

gtk_notebook_set_tab_border is deprecated and should not be used in newly-written code.

Sets the width the border around the tab labels in a notebook. This is equivalent to calling gtk_notebook_set_tab_hborder (notebook, border_width) followed by gtk_notebook_set_tab_vborder (notebook, border_width).

notebook : | a GtkNotebook
border_width : | width of the border around the tab labels.

gtk_notebook_popup_enable ()

void                gtk_notebook_popup_enable           (GtkNotebook *notebook);

Enables the popup menu: if the user clicks with the right mouse button on the bookmarks, a menu with all the pages will be popped up.

notebook : a GtkNotebook

gtk_notebook_popup_disable ()

void                gtk_notebook_popup_disable          (GtkNotebook *notebook);

Disables the popup menu.

notebook : a GtkNotebook

gtk_notebook_get_current_page ()

gint                gtk_notebook_get_current_page       (GtkNotebook *notebook);

Returns the page number of the current page.

notebook : | a GtkNotebook
Returns : | the index (starting from 0) of the current page in the notebook. If the notebook has no pages, then -1 will be returned.

gtk_notebook_get_menu_label ()

GtkWidget*          gtk_notebook_get_menu_label         (GtkNotebook *notebook,
                                                         GtkWidget *child);

Retrieves the menu label widget of the page containing child.

notebook : | a GtkNotebook
child : | a widget contained in a page of notebook
Returns : | the menu label, or NULL if the notebook page does not have a menu label other than the default (the tab label).

gtk_notebook_get_nth_page ()

GtkWidget*          gtk_notebook_get_nth_page           (GtkNotebook *notebook,
                                                         gint page_num);

Returns the child widget contained in page number page_num.

notebook : | a GtkNotebook
page_num : | the index of a page in the noteobok, or -1 to get the last page.
Returns : | the child widget, or NULL if page_num is out of bounds.

gtk_notebook_get_n_pages ()

gint                gtk_notebook_get_n_pages            (GtkNotebook *notebook);

Gets the number of pages in a notebook.

notebook : | a GtkNotebook
Returns : | the number of pages in the notebook.

Since 2.2

gtk_notebook_get_tab_label ()

GtkWidget*          gtk_notebook_get_tab_label          (GtkNotebook *notebook,
                                                         GtkWidget *child);

Returns the tab label widget for the page child. NULL is returned if child is not in notebook or if no tab label has specifically been set for child.

notebook : | a GtkNotebook
child : | the page
Returns : | the tab label

gtk_notebook_query_tab_label_packing ()

void                gtk_notebook_query_tab_label_packing
                                                        (GtkNotebook *notebook,
                                                         GtkWidget *child,
                                                         gboolean *expand,
                                                         gboolean *fill,
                                                         GtkPackType *pack_type);

Query the packing attributes for the tab label of the page containing child.

notebook : | a GtkNotebook
child : | the page
expand : | location to store the expand value (or NULL)
fill : | location to store the fill value (or NULL)
pack_type : | location to store the pack_type (or NULL)

gtk_notebook_set_homogeneous_tabs ()

void                gtk_notebook_set_homogeneous_tabs   (GtkNotebook *notebook,
                                                         gboolean homogeneous);

Warning

gtk_notebook_set_homogeneous_tabs is deprecated and should not be used in newly-written code.

Sets whether the tabs must have all the same size or not.

notebook : | a GtkNotebook
homogeneous : | TRUE if all tabs should be the same size.

gtk_notebook_set_menu_label ()

void                gtk_notebook_set_menu_label         (GtkNotebook *notebook,
                                                         GtkWidget *child,
                                                         GtkWidget *menu_label);

Changes the menu label for the page containing child.

notebook : | a GtkNotebook
child : | the child widget
menu_label : | the menu label, or NULL for default

gtk_notebook_set_menu_label_text ()

void                gtk_notebook_set_menu_label_text    (GtkNotebook *notebook,
                                                         GtkWidget *child,
                                                         const gchar *menu_text);

Creates a new label and sets it as the menu label of child.

notebook : | a GtkNotebook
child : | the child widget
menu_text : | the label text

gtk_notebook_set_tab_hborder ()

void                gtk_notebook_set_tab_hborder        (GtkNotebook *notebook,
                                                         guint tab_hborder);

Warning

gtk_notebook_set_tab_hborder is deprecated and should not be used in newly-written code.

Sets the width of the horizontal border of tab labels.

notebook : | a GtkNotebook
tab_hborder : | width of the horizontal border of tab labels.

gtk_notebook_set_tab_label ()

void                gtk_notebook_set_tab_label          (GtkNotebook *notebook,
                                                         GtkWidget *child,
                                                         GtkWidget *tab_label);

Changes the tab label for child. If NULL is specified for tab_label, then the page will have the label 'page N'.

notebook : | a GtkNotebook
child : | the page
tab_label : | the tab label widget to use, or NULL for default tab label.

gtk_notebook_set_tab_label_packing ()

void                gtk_notebook_set_tab_label_packing  (GtkNotebook *notebook,
                                                         GtkWidget *child,
                                                         gboolean expand,
                                                         gboolean fill,
                                                         GtkPackType pack_type);

Sets the packing parameters for the tab label of the page containing child. See gtk_box_pack_start() for the exact meaning of the parameters.

notebook : | a GtkNotebook
child : | the child widget
expand : | whether to expand the bookmark or not
fill : | whether the bookmark should fill the allocated area or not
pack_type : | the position of the bookmark

gtk_notebook_set_tab_label_text ()

void                gtk_notebook_set_tab_label_text     (GtkNotebook *notebook,
                                                         GtkWidget *child,
                                                         const gchar *tab_text);

Creates a new label and sets it as the tab label for the page containing child.

notebook : | a GtkNotebook
child : | the page
tab_text : | the label text

gtk_notebook_set_tab_vborder ()

void                gtk_notebook_set_tab_vborder        (GtkNotebook *notebook,
                                                         guint tab_vborder);

Warning

gtk_notebook_set_tab_vborder is deprecated and should not be used in newly-written code.

Sets the width of the vertical border of tab labels.

notebook : | a GtkNotebook
tab_vborder : | width of the vertical border of tab labels.

gtk_notebook_set_tab_reorderable ()

void                gtk_notebook_set_tab_reorderable    (GtkNotebook *notebook,
                                                         GtkWidget *child,
                                                         gboolean reorderable);

Sets whether the notebook tab can be reordered via drag and drop or not.

notebook : | a GtkNotebook
child : | a child GtkWidget
reorderable : | whether the tab is reorderable or not.

Since 2.10

gtk_notebook_set_tab_detachable ()

void                gtk_notebook_set_tab_detachable     (GtkNotebook *notebook,
                                                         GtkWidget *child,
                                                         gboolean detachable);

Sets whether the tab can be detached from notebook to another notebook or widget.

Note that 2 notebooks must share a common group identificator (see gtk_notebook_set_group_id()) to allow automatic tabs interchange between them.

If you want a widget to interact with a notebook through DnD (i.e.: accept dragged tabs from it) it must be set as a drop destination and accept the target "GTK_NOTEBOOK_TAB". The notebook will fill the selection with a GtkWidget** pointing to the child widget that corresponds to the dropped tab.

 static void
 on_drop_zone_drag_data_received (GtkWidget        *widget,
                                  GdkDragContext   *context,
                                  gint              x,
                                  gint              y,
                                  GtkSelectionData *selection_data,
                                  guint             info,
                                  guint             time,
                                  gpointer          user_data)
 {
   GtkWidget *notebook;
   GtkWidget **child;

   notebook = gtk_drag_get_source_widget (context);
   child = (void*) selection_data->data;

   process_widget (*child);
   gtk_container_remove (GTK_CONTAINER (notebook), *child);
 }

If you want a notebook to accept drags from other widgets, you will have to set your own DnD code to do it.

notebook : | a GtkNotebook
child : | a child GtkWidget
detachable : | whether the tab is detachable or not

Since 2.10

gtk_notebook_get_menu_label_text ()

const gchar*        gtk_notebook_get_menu_label_text    (GtkNotebook *notebook,
                                                         GtkWidget *child);

Retrieves the text of the menu label for the page containing child.

notebook : | a GtkNotebook
child : | the child widget of a page of the notebook.
Returns : | value: the text of the tab label, or NULL if the widget does not have a menu label other than the default menu label, or the menu label widget is not a GtkLabel. The string is owned by the widget and must not be freed.

gtk_notebook_get_scrollable ()

gboolean            gtk_notebook_get_scrollable         (GtkNotebook *notebook);

Returns whether the tab label area has arrows for scrolling. See gtk_notebook_set_scrollable().

notebook : | a GtkNotebook
Returns : | TRUE if arrows for scrolling are present

gtk_notebook_get_show_border ()

gboolean            gtk_notebook_get_show_border        (GtkNotebook *notebook);

Returns whether a bevel will be drawn around the notebook pages. See gtk_notebook_set_show_border().

notebook : | a GtkNotebook
Returns : | TRUE if the bevel is drawn

gtk_notebook_get_show_tabs ()

gboolean            gtk_notebook_get_show_tabs          (GtkNotebook *notebook);

Returns whether the tabs of the notebook are shown. See gtk_notebook_set_show_tabs().

notebook : | a GtkNotebook
Returns : | TRUE if the tabs are shown

gtk_notebook_get_tab_label_text ()

const gchar*        gtk_notebook_get_tab_label_text     (GtkNotebook *notebook,
                                                         GtkWidget *child);

Retrieves the text of the tab label for the page containing child.

notebook : | a GtkNotebook
child : | a widget contained in a page of notebook
Returns : | value: the text of the tab label, or NULL if the tab label widget is not a GtkLabel. The string is owned by the widget and must not be freed.

gtk_notebook_get_tab_pos ()

GtkPositionType     gtk_notebook_get_tab_pos            (GtkNotebook *notebook);

Gets the edge at which the tabs for switching pages in the notebook are drawn.

notebook : | a GtkNotebook
Returns : | the edge at which the tabs are drawn

gtk_notebook_get_tab_reorderable ()

gboolean            gtk_notebook_get_tab_reorderable    (GtkNotebook *notebook,
                                                         GtkWidget *child);

Gets whether the tab can be reordered via drag and drop or not.

notebook : | a GtkNotebook
child : | a child GtkWidget
Returns : | TRUE if the tab is reorderable.

Since 2.10

gtk_notebook_get_tab_detachable ()

gboolean            gtk_notebook_get_tab_detachable     (GtkNotebook *notebook,
                                                         GtkWidget *child);

Returns whether the tab contents can be detached from notebook.

notebook : | a GtkNotebook
child : | a child GtkWidget
Returns : | TRUE if the tab is detachable.

Since 2.10

gtk_notebook_set_current_page ()

void                gtk_notebook_set_current_page       (GtkNotebook *notebook,
                                                         gint page_num);

Switches to the page number page_num.

Note that due to historical reasons, GtkNotebook refuses to switch to a page unless the child widget is visible. Therefore, it is recommended to show child widgets before adding them to a notebook.

notebook : | a GtkNotebook
page_num : | index of the page to switch to, starting from 0. If negative, the last page will be used. If greater than the number of pages in the notebook, nothing will be done.

gtk_notebook_set_group_id ()

void                gtk_notebook_set_group_id           (GtkNotebook *notebook,
                                                         gint group_id);

Sets an group identificator for notebook, notebooks sharing the same group identificator will be able to exchange tabs via drag and drop. A notebook with group identificator -1 will not be able to exchange tabs with any other notebook.

notebook : | a GtkNotebook
group_id : | a group identificator, or -1 to unset it

Since 2.10

gtk_notebook_get_group_id ()

gint                gtk_notebook_get_group_id           (GtkNotebook *notebook);

Gets the current group identificator for notebook.

notebook : | a GtkNotebook
Returns : | the group identificator, or -1 if none is set.

Since 2.10

GtkNotebookWindowCreationFunc ()

GtkNotebook*        (*GtkNotebookWindowCreationFunc)    (GtkNotebook *source,
                                                         GtkWidget *page,
                                                         gint x,
                                                         gint y,
                                                         gpointer data);

A function used by GtkNotebook when a detachable tab is dropped in the root window, it's used to create a window containing a notebook where the tab will be attached. This function will also be responsible of moving/resizing the window and adding the necessary properties to the notebook (i.e.: group-id). If the function returns NULL, the drag will be cancelled.

source : | The source GtkNotebook of the drag operation
page : | the child GtkWidget affected
x : | the X coordinate where the drop happens
y : | the Y coordinate where the drop happens
data : | user data
Returns : | The created GtkNotebook where the tab will be attached, or NULL to cancel the drag

gtk_notebook_set_window_creation_hook ()

void                gtk_notebook_set_window_creation_hook
                                                        (GtkNotebookWindowCreationFunc func,
                                                         gpointer data,
                                                         GDestroyNotify destroy);

Installs a global function used to create a window when a detached tab is dropped in an empty area.

func : | the GtkNotebookWindowCreationFunc, or NULL
data : | user data for func
destroy : | Destroy notifier for data, or NULL

Since 2.10

Property Details

The "enable-popup" property

  "enable-popup"             gboolean              : Read / Write

If TRUE, pressing the right mouse button on the notebook pops up a menu that you can use to go to a page.

Default value: FALSE

The "group-id" property

  "group-id"                 gint                  : Read / Write

Group ID for tabs drag and drop.

Allowed values: >= -1

Default value: -1

The "homogeneous" property

  "homogeneous"              gboolean              : Read / Write

Whether tabs should have homogeneous sizes.

Default value: FALSE

The "page" property

  "page"                     gint                  : Read / Write

The index of the current page.

Allowed values: >= 0

Default value: 0

The "scrollable" property

  "scrollable"               gboolean              : Read / Write

If TRUE, scroll arrows are added if there are too many tabs to fit.

Default value: FALSE

The "show-border" property

  "show-border"              gboolean              : Read / Write

Whether the border should be shown or not.

Default value: TRUE

The "show-tabs" property

  "show-tabs"                gboolean              : Read / Write

Whether tabs should be shown or not.

Default value: TRUE

The "tab-border" property

  "tab-border"               guint                 : Write

Width of the border around the tab labels.

Default value: 2

The "tab-hborder" property

  "tab-hborder"              guint                 : Read / Write

Width of the horizontal border of tab labels.

Default value: 2

The "tab-pos" property

  "tab-pos"                  GtkPositionType       : Read / Write

Which side of the notebook holds the tabs.

Default value: GTK_POS_TOP

The "tab-vborder" property

  "tab-vborder"              guint                 : Read / Write

Width of the vertical border of tab labels.

Default value: 2

Child Property Details

The "detachable" child property

  "detachable"               gboolean              : Read / Write

Whether the tab is detachable.

Default value: FALSE

The "menu-label" child property

  "menu-label"               gchararray            : Read / Write

The string displayed in the child's menu entry.

Default value: NULL

The "position" child property

  "position"                 gint                  : Read / Write

The index of the child in the parent.

Allowed values: >= -1

Default value: 0

The "reorderable" child property

  "reorderable"              gboolean              : Read / Write

Whether the tab is reorderable by user action or not.

Default value: FALSE

The "tab-expand" child property

  "tab-expand"               gboolean              : Read / Write

Whether to expand the child's tab or not.

Default value: TRUE

The "tab-fill" child property

  "tab-fill"                 gboolean              : Read / Write

Whether the child's tab should fill the allocated area or not.

Default value: TRUE

The "tab-label" child property

  "tab-label"                gchararray            : Read / Write

The string displayed on the child's tab label.

Default value: NULL

The "tab-pack" child property

  "tab-pack"                 GtkPackType           : Read / Write

A GtkPackType indicating whether the child is packed with reference to the start or end of the parent.

Default value: GTK_PACK_START

Style Property Details

The "arrow-spacing" style property

  "arrow-spacing"            gint                  : Read

The "arrow-size" property defines the spacing between the scroll arrows and the tabs.

Allowed values: >= 0

Default value: 0

Since 2.10

The "has-backward-stepper" style property

  "has-backward-stepper"     gboolean              : Read

The "has-backward-stepper" property determines whether the standard backward arrow button is displayed.

Default value: TRUE

Since 2.4

The "has-forward-stepper" style property

  "has-forward-stepper"      gboolean              : Read

The "has-forward-stepper" property determines whether the standard forward arrow button is displayed.

Default value: TRUE

Since 2.4

The "has-secondary-backward-stepper" style property

  "has-secondary-backward-stepper" gboolean              : Read

The "has-secondary-backward-stepper" property determines whether a second backward arrow button is displayed on the opposite end of the tab area.

Default value: FALSE

Since 2.4

The "has-secondary-forward-stepper" style property

  "has-secondary-forward-stepper" gboolean              : Read

The "has-secondary-forward-stepper" property determines whether a second forward arrow button is displayed on the opposite end of the tab area.

Default value: FALSE

Since 2.4

The "tab-curvature" style property

  "tab-curvature"            gint                  : Read

The "tab-curvature" property defines size of tab curvature.

Allowed values: >= 0

Default value: 1

Since 2.10

The "tab-overlap" style property

  "tab-overlap"              gint                  : Read

The "tab-overlap" property defines size of tab overlap area.

Default value: 2

Since 2.10

Signal Details

The "change-current-page" signal

gboolean            user_function                      (GtkNotebook *notebook,
                                                        gint         arg1,
                                                        gpointer     user_data)      : Run Last / Action

notebook : | the object which received the signal.
arg1 : |
user_data : | user data set when the signal handler was connected.
Returns : |

The "focus-tab" signal

gboolean            user_function                      (GtkNotebook   *notebook,
                                                        GtkNotebookTab arg1,
                                                        gpointer       user_data)      : Run Last / Action

notebook : | the object which received the signal.
arg1 : |
user_data : | user data set when the signal handler was connected.
Returns : |

The "move-focus-out" signal

void                user_function                      (GtkNotebook     *notebook,
                                                        GtkDirectionType arg1,
                                                        gpointer         user_data)      : Run Last / Action

notebook : | the object which received the signal.
arg1 : |
user_data : | user data set when the signal handler was connected.

The "page-added" signal

void                user_function                      (GtkNotebook *notebook,
                                                        GtkWidget   *child,
                                                        guint        page_num,
                                                        gpointer     user_data)      : Run Last

the ::page-added signal is emitted in the notebook right after a page is added to the notebook.

notebook : | the GtkNotebook
child : | the child GtkWidget affected
page_num : | the new page number for child
user_data : | user data set when the signal handler was connected.

Since 2.10

The "page-removed" signal

void                user_function                      (GtkNotebook *notebook,
                                                        GtkWidget   *child,
                                                        guint        page_num,
                                                        gpointer     user_data)      : Run Last

the ::page-removed signal is emitted in the notebook right after a page is removed from the notebook.

notebook : | the GtkNotebook
child : | the child GtkWidget affected
page_num : | the child page number
user_data : | user data set when the signal handler was connected.

Since 2.10

The "page-reordered" signal

void                user_function                      (GtkNotebook *notebook,
                                                        GtkWidget   *child,
                                                        guint        page_num,
                                                        gpointer     user_data)      : Run Last

the ::page-reordered signal is emitted in the notebook right after a page has been reordered.

notebook : | the GtkNotebook
child : | the child GtkWidget affected
page_num : | the new page number for child
user_data : | user data set when the signal handler was connected.

Since 2.10

The "reorder-tab" signal

gboolean            user_function                      (GtkNotebook     *notebook,
                                                        GtkDirectionType arg1,
                                                        gboolean         arg2,
                                                        gpointer         user_data)      : Run Last / Action

notebook : | the object which received the signal.
arg1 : |
Param3 : |
user_data : | user data set when the signal handler was connected.
Returns : |

The "select-page" signal

gboolean            user_function                      (GtkNotebook *notebook,
                                                        gboolean     arg1,
                                                        gpointer     user_data)      : Run Last / Action

notebook : | the object which received the signal.
arg1 : |
user_data : | user data set when the signal handler was connected.
Returns : |

The "switch-page" signal

void                user_function                      (GtkNotebook     *notebook,
                                                        GtkNotebookPage *page,
                                                        guint            page_num,
                                                        gpointer         user_data)      : Run Last

Emitted when the user or a function changes the current page.

notebook : | the object which received the signal.
page : | the new current page
page_num : | the index of the page
user_data : | user data set when the signal handler was connected.

See Also

GtkContainer

For functions that apply to every GtkContainer (like GtkList).


GtkObject

GtkObject — The base class of the GTK+ type hierarchy

Synopsis

#include <gtk/gtk.h>

                    GtkObject;
#define             GTK_OBJECT_TYPE                     (object)
#define             GTK_OBJECT_TYPE_NAME                (object)
enum                GtkObjectFlags;
#define             GTK_OBJECT_FLAGS                    (obj)
#define             GTK_OBJECT_FLOATING                 (obj)
enum                GtkArgFlags;
GtkObject*          gtk_object_new                      (GtkType type,
                                                         const gchar *first_property_name,
                                                         ...);
void                gtk_object_sink                     (GtkObject *object);
GtkObject*          gtk_object_ref                      (GtkObject *object);
void                gtk_object_unref                    (GtkObject *object);
void                gtk_object_weakref                  (GtkObject *object,
                                                         GtkDestroyNotify notify,
                                                         gpointer data);
void                gtk_object_weakunref                (GtkObject *object,
                                                         GtkDestroyNotify notify,
                                                         gpointer data);
void                gtk_object_destroy                  (GtkObject *object);
void                gtk_object_get                      (GtkObject *object,
                                                         const gchar *first_property_name,
                                                         ...);
void                gtk_object_set                      (GtkObject *object,
                                                         const gchar *first_property_name,
                                                         ...);
void                gtk_object_set_data                 (GtkObject *object,
                                                         const gchar *key,
                                                         gpointer data);
void                gtk_object_set_data_full            (GtkObject *object,
                                                         const gchar *key,
                                                         gpointer data,
                                                         GtkDestroyNotify destroy);
void                gtk_object_remove_data              (GtkObject *object,
                                                         const gchar *key);
gpointer            gtk_object_get_data                 (GtkObject *object,
                                                         const gchar *key);
void                gtk_object_remove_no_notify         (GtkObject *object,
                                                         const gchar *key);
void                gtk_object_set_user_data            (GtkObject *object,
                                                         gpointer data);
gpointer            gtk_object_get_user_data            (GtkObject *object);
void                gtk_object_add_arg_type             (const gchar *arg_name,
                                                         GtkType arg_type,
                                                         guint arg_flags,
                                                         guint arg_id);
void                gtk_object_set_data_by_id           (GtkObject *object,
                                                         GQuark data_id,
                                                         gpointer data);
void                gtk_object_set_data_by_id_full      (GtkObject *object,
                                                         GQuark data_id,
                                                         gpointer data,
                                                         GtkDestroyNotify destroy);
gpointer            gtk_object_get_data_by_id           (GtkObject *object,
                                                         GQuark data_id);
void                gtk_object_remove_data_by_id        (GtkObject *object,
                                                         GQuark data_id);
void                gtk_object_remove_no_notify_by_id   (GtkObject *object,
                                                         GQuark key_id);
#define             gtk_object_data_try_key
#define             gtk_object_data_force_id

Object Hierarchy

  GObject
   +----GInitiallyUnowned
         +----GtkObject
               +----GtkWidget
               +----GtkAdjustment
               +----GtkCellRenderer
               +----GtkFileFilter
               +----GtkItemFactory
               +----GtkTooltips
               +----GtkTreeViewColumn
               +----GtkRecentFilter

Known Derived Interfaces

GtkObject is required by GtkRecentChooser.

Properties

  "user-data"                gpointer              : Read / Write

Signals

  "destroy"                                        : Cleanup / No Recursion / No Hooks

Description

Description

GtkObject is the base class for all widgets, and for a few non-widget objects such as GtkAdjustment. GtkObject predates GObject; non-widgets that derive from GtkObject rather than GObject do so for backward compatibility reasons.

GtkObjects are created with a "floating" reference count. This means that the initial reference is not owned by anyone. Calling g_object_unref() on a newly-created GtkObject is incorrect, the floating reference has to be removed first. This can be done by anyone at any time, by calling g_object_ref_sink() to convert the floating reference into a regular reference. g_object_ref_sink() returns a new reference if an object is already sunk (has no floating reference).

When you add a widget to its parent container, the parent container will do this:

  g_object_ref_sink (G_OBJECT (child_widget));

This means that the container now owns a reference to the child widget and the child widget has no floating reference.

The purpose of the floating reference is to keep the child widget alive until you add it to a parent container:

   button = gtk_button_new ();
   /* button has one floating reference to keep it alive */
   gtk_container_add (GTK_CONTAINER (container), button);
   /* button has one non-floating reference owned by the container */

GtkWindow is a special case, because GTK+ itself will ref/sink it on creation. That is, after calling gtk_window_new(), the GtkWindow will have one reference which is owned by GTK+, and no floating references.

One more factor comes into play: the "destroy" signal, emitted by the gtk_object_destroy() method. The "destroy" signal asks all code owning a reference to an object to release said reference. So, for example, if you call gtk_object_destroy() on a GtkWindow, GTK+ will release the reference count that it owns; if you call gtk_object_destroy() on a GtkButton, then the button will be removed from its parent container and the parent container will release its reference to the button. Because these references are released, calling gtk_object_destroy() should result in freeing all memory associated with an object, unless some buggy code fails to release its references in response to the "destroy" signal. Freeing memory (referred to as finalization only happens if the reference count reaches zero.

Some simple rules for handling GtkObject:

  • Never call g_object_unref() unless you have previously called g_object_ref(), even if you created the GtkObject. (Note: this is not true for GObject; for GObject, the creator of the object owns a reference.)

  • Call gtk_object_destroy() to get rid of most objects in most cases. In particular, widgets are almost always destroyed in this way.

  • Because of the floating reference count, you don't need to worry about reference counting for widgets and toplevel windows, unless you explicitly call g_object_ref() yourself.

Details

GtkObject

typedef struct _GtkObject GtkObject;

The object itself. You should never use these members directly - use the accessing macros instead.

GTK_OBJECT_TYPE()

#define GTK_OBJECT_TYPE(object)		  (G_TYPE_FROM_INSTANCE (object))

Gets the type of an object.

object : a GtkObject.

GTK_OBJECT_TYPE_NAME()

#define GTK_OBJECT_TYPE_NAME(object)	  (g_type_name (GTK_OBJECT_TYPE (object)))

Gets the name of an objects type.

object : a GtkObject.

enum GtkObjectFlags

typedef enum
{
  GTK_IN_DESTRUCTION	= 1 << 0, /* Used internally during dispose */
#if !defined (GTK_DISABLE_DEPRECATED) || defined (GTK_COMPILATION)
  GTK_FLOATING		= 1 << 1,
#endif
  GTK_RESERVED_1	= 1 << 2,
  GTK_RESERVED_2	= 1 << 3
} GtkObjectFlags;

Tells about the state of the object.

GTK_IN_DESTRUCTION | the object is currently being destroyed. This is used internally by GTK+ to prevent reinvokations during destruction.
GTK_RESERVED_2 | reserved for future use

GTK_OBJECT_FLAGS()

#define GTK_OBJECT_FLAGS(obj)		  (GTK_OBJECT (obj)->flags)

Gets the GtkObjectFlags for an object without directly accessing its members.

obj : the object whose flags are returned.

GTK_OBJECT_FLOATING()

#define GTK_OBJECT_FLOATING(obj)	  (g_object_is_floating (obj))

Warning

GTK_OBJECT_FLOATING is deprecated and should not be used in newly-written code.

Evaluates to TRUE if the object still has its floating reference count. See the overview documentation for GtkObject.

obj : the object to examine.

enum GtkArgFlags

typedef enum
{
  GTK_ARG_READABLE	 = G_PARAM_READABLE,
  GTK_ARG_WRITABLE	 = G_PARAM_WRITABLE,
  GTK_ARG_CONSTRUCT	 = G_PARAM_CONSTRUCT,
  GTK_ARG_CONSTRUCT_ONLY = G_PARAM_CONSTRUCT_ONLY,
  GTK_ARG_CHILD_ARG	 = 1 << 4
} GtkArgFlags;

Warning

GtkArgFlags is deprecated and should not be used in newly-written code. Use corresponding GParamSpec features instead

Possible flags indicating how an argument should be treated.

GTK_ARG_READABLE | the argument is readable. (i.e. can be queried)
GTK_ARG_WRITABLE | the argument is writable. (i.e. settable)
GTK_ARG_CONSTRUCT | the argument needs construction.
GTK_ARG_CONSTRUCT_ONLY | the argument needs construction (and will be set once during object creation), but is otherwise cannot be set. Hence this flag is not allowed with GTK_ARG_WRITABLE, and is redundant with GTK_ARG_CONSTRUCT.
GTK_ARG_CHILD_ARG | an argument type that applies to (and may be different for) each child. Used by GtkContainer.

gtk_object_new ()

GtkObject*          gtk_object_new                      (GtkType type,
                                                         const gchar *first_property_name,
                                                         ...);

Warning

gtk_object_new is deprecated and should not be used in newly-written code. Use g_object_new() instead.

Constructs an object given its arguments, enumerated in the call to the function.

type : | the type identifying this object. Returned by gtk_type_unique() (although for a properly-written object it should be accessible through a GTK_TYPE_FOO macro.)
first_property_name : | name of the first property to set when constructing the object.
... : | the first argument's value, followed by any number of name/argument-value pairs, terminated with NULL.
Returns : | the new GtkObject.

gtk_object_sink ()

void                gtk_object_sink                     (GtkObject *object);

Warning

gtk_object_sink has been deprecated since version 2.10 and should not be used in newly-written code. Use g_object_ref_sink() instead

Removes the floating reference from a GtkObject, if it exists; otherwise does nothing. See the GtkObject overview documentation at the top of the page.

object : the object to sink.

gtk_object_ref ()

GtkObject*          gtk_object_ref                      (GtkObject *object);

Warning

gtk_object_ref is deprecated and should not be used in newly-written code. Use g_object_ref() instead.

Increases the reference count of the object.

object : | the object to reference.
Returns : | object.

gtk_object_unref ()

void                gtk_object_unref                    (GtkObject *object);

Warning

gtk_object_unref is deprecated and should not be used in newly-written code. Use g_object_unref() instead.

Decreases the reference count of an object. When its reference count drops to 0, the object is finalized (i.e. its memory is freed).

object : the object to dereference.

gtk_object_weakref ()

void                gtk_object_weakref                  (GtkObject *object,
                                                         GtkDestroyNotify notify,
                                                         gpointer data);

Warning

gtk_object_weakref is deprecated and should not be used in newly-written code. Use g_object_weak_ref() instead.

Adds a weak reference callback to an object. Weak references are used for notification when an object is finalized. They are called "weak references" because they allow you to safely hold a pointer to an object without calling g_object_ref() (g_object_ref() adds a strong reference, that is, forces the object to stay alive).

object : | object to weakly reference.
notify : | callback to invoke before the object is freed.
data : | extra data to pass to notify.

gtk_object_weakunref ()

void                gtk_object_weakunref                (GtkObject *object,
                                                         GtkDestroyNotify notify,
                                                         gpointer data);

Warning

gtk_object_weakunref is deprecated and should not be used in newly-written code. Use g_object_weak_unref() instead.

Removes a weak reference callback to an object.

object : | object stop weakly referencing.
notify : | callback to search for.
data : | data to search for.

gtk_object_destroy ()

void                gtk_object_destroy                  (GtkObject *object);

Emits the "destroy" signal notifying all reference holders that they should release the GtkObject. See the overview documentation at the top of the page for more details.

The memory for the object itself won't be deleted until its reference count actually drops to 0; gtk_object_destroy() merely asks reference holders to release their references, it does not free the object.

object : the object to destroy.

gtk_object_get ()

void                gtk_object_get                      (GtkObject *object,
                                                         const gchar *first_property_name,
                                                         ...);

Warning

gtk_object_get is deprecated and should not be used in newly-written code. Use g_object_get() instead.

Gets properties of an object.

object : | a GtkObject.
first_property_name : | name of first property to get the value for.
... : | NULL-terminated list of name-return location pairs.

gtk_object_set ()

void                gtk_object_set                      (GtkObject *object,
                                                         const gchar *first_property_name,
                                                         ...);

Warning

gtk_object_set is deprecated and should not be used in newly-written code. Use g_object_set() instead.

Sets properties on an object.

void set_box_properties (GtkBox* box)
{
  gtk_object_set (GTK_OBJECT (box), "homogeneous", TRUE,
                                    "spacing", 8,
                    NULL);
}

object : | a GtkObject.
first_property_name : | name of the first property to set
... : | the value of the first argument, followed optionally by more name/value pairs, followed by NULL.

gtk_object_set_data ()

void                gtk_object_set_data                 (GtkObject *object,
                                                         const gchar *key,
                                                         gpointer data);

Warning

gtk_object_set_data is deprecated and should not be used in newly-written code. Use g_object_set_data() instead.

Each object carries around a table of associations from strings to pointers. This function lets you set an association.

If the object already had an association with that name, the old association will be destroyed.

object : | object containing the associations.
key : | name of the key.
data : | data to associate with that key.

gtk_object_set_data_full ()

void                gtk_object_set_data_full            (GtkObject *object,
                                                         const gchar *key,
                                                         gpointer data,
                                                         GtkDestroyNotify destroy);

Warning

gtk_object_set_data_full is deprecated and should not be used in newly-written code. Use g_object_set_data_full() instead.

Like gtk_object_set_data() except it adds notification for when the association is destroyed, either by gtk_object_remove_data() or when the object is destroyed.

object : | object containing the associations.
key : | name of the key.
data : | data to associate with that key.
destroy : | function to call when the association is destroyed.

gtk_object_remove_data ()

void                gtk_object_remove_data              (GtkObject *object,
                                                         const gchar *key);

Warning

gtk_object_remove_data is deprecated and should not be used in newly-written code. Use g_object_set_data() to set the object data to NULL instead.

Removes a specified datum from the object's data associations (the object_data). Subsequent calls to gtk_object_get_data() will return NULL.

If you specified a destroy handler with gtk_object_set_data_full(), it will be invoked.

object : | the object maintaining the association.
key : | name of the key for that association.

gtk_object_get_data ()

gpointer            gtk_object_get_data                 (GtkObject *object,
                                                         const gchar *key);

Warning

gtk_object_get_data is deprecated and should not be used in newly-written code. Use g_object_get_data() instead.

Get a named field from the object's table of associations (the object_data).

object : | the object maintaining the associations.
key : | name of the key for that association.
Returns : | the data if found, or NULL if no such data exists.

gtk_object_remove_no_notify ()

void                gtk_object_remove_no_notify         (GtkObject *object,
                                                         const gchar *key);

Warning

gtk_object_remove_no_notify is deprecated and should not be used in newly-written code. Use g_object_steal_data() instead.

Remove a specified datum from the object's data associations (the object_data), without invoking the association's destroy handler.

Just like gtk_object_remove_data() except that any destroy handler will be ignored. Therefore this only affects data set using gtk_object_set_data_full().

object : | the object maintaining the association.
key : | name of the key for that association.

gtk_object_set_user_data ()

void                gtk_object_set_user_data            (GtkObject *object,
                                                         gpointer data);

Warning

gtk_object_set_user_data is deprecated and should not be used in newly-written code. Use g_object_set_data() instead.

For convenience, every object offers a generic user data pointer. This function sets it.

object : | the object whose user data should be set.
data : | the new value for the user data.

gtk_object_get_user_data ()

gpointer            gtk_object_get_user_data            (GtkObject *object);

Warning

gtk_object_get_user_data is deprecated and should not be used in newly-written code. Use g_object_get_data() instead.

Get the object's user data pointer.

This is intended to be a pointer for your convenience in writing applications.

object : | the object.
Returns : | the user data field for object.

gtk_object_add_arg_type ()

void                gtk_object_add_arg_type             (const gchar *arg_name,
                                                         GtkType arg_type,
                                                         guint arg_flags,
                                                         guint arg_id);

Warning

gtk_object_add_arg_type is deprecated and should not be used in newly-written code.

Deprecated in favor of the GObject property system including GParamSpec. Add a new type of argument to an object class. Usually this is called when registering a new type of object.

arg_name : | fully qualify object name, for example GtkObject::user_data.
arg_type : | type of the argument.
arg_flags : | bitwise-OR of the GtkArgFlags enum. (Whether the argument is settable or gettable, whether it is set when the object is constructed.)
arg_id : | an internal number, passed in from here to the "set_arg" and "get_arg" handlers of the object.

gtk_object_set_data_by_id ()

void                gtk_object_set_data_by_id           (GtkObject *object,
                                                         GQuark data_id,
                                                         gpointer data);

Warning

gtk_object_set_data_by_id is deprecated and should not be used in newly-written code. Use g_object_set_qdata() instead.

Just like gtk_object_set_data() except that it takes a GQuark instead of a string, so it is slightly faster.

Use gtk_object_data_try_key() and gtk_object_data_force_id() to get an id from a string.

object : | object containing the associations.
data_id : | quark of the key.
data : | data to associate with that key.

gtk_object_set_data_by_id_full ()

void                gtk_object_set_data_by_id_full      (GtkObject *object,
                                                         GQuark data_id,
                                                         gpointer data,
                                                         GtkDestroyNotify destroy);

Warning

gtk_object_set_data_by_id_full is deprecated and should not be used in newly-written code. Use g_object_set_qdata_full() instead.

Just like gtk_object_set_data_full() except that it takes a GQuark instead of a string, so it is slightly faster.

Use gtk_object_data_try_key() and gtk_object_data_force_id() to get an id from a string.

object : | object containing the associations.
data_id : | quark of the key.
data : | data to associate with that key.
destroy : | function to call when the association is destroyed.

gtk_object_get_data_by_id ()

gpointer            gtk_object_get_data_by_id           (GtkObject *object,
                                                         GQuark data_id);

Warning

gtk_object_get_data_by_id is deprecated and should not be used in newly-written code. Use g_object_get_qdata() instead.

Just like gtk_object_get_data() except that it takes a GQuark instead of a string, so it is slightly faster.

Use gtk_object_data_try_key() and gtk_object_data_force_id() to get an id from a string.

object : | object containing the associations.
data_id : | quark of the key.
Returns : | the data if found, or NULL if no such data exists.

gtk_object_remove_data_by_id ()

void                gtk_object_remove_data_by_id        (GtkObject *object,
                                                         GQuark data_id);

Warning

gtk_object_remove_data_by_id is deprecated and should not be used in newly-written code. Use g_object_set_qdata() with data of NULL instead.

Just like gtk_object_remove_data() except that it takes a GQuark instead of a string, so it is slightly faster.

Remove a specified datum from the object's data associations. Subsequent calls to gtk_object_get_data() will return NULL.

Use gtk_object_data_try_key() and gtk_object_data_force_id() to get an id from a string.

object : | object containing the associations.
data_id : | quark of the key.

gtk_object_remove_no_notify_by_id ()

void                gtk_object_remove_no_notify_by_id   (GtkObject *object,
                                                         GQuark key_id);

Warning

gtk_object_remove_no_notify_by_id is deprecated and should not be used in newly-written code. Use g_object_steal_qdata() instead.

Just like gtk_object_remove_no_notify() except that it takes a GQuark instead of a string, so it is slightly faster.

Use gtk_object_data_try_key() and gtk_object_data_force_id() to get an id from a string.

object : | object containing the associations.
key_id : | quark of the key.

gtk_object_data_try_key

#define	gtk_object_data_try_key	    g_quark_try_string

Warning

gtk_object_data_try_key is deprecated and should not be used in newly-written code.

Useless deprecated macro. Ignore it.

gtk_object_data_force_id

#define	gtk_object_data_force_id    g_quark_from_string

Warning

gtk_object_data_force_id is deprecated and should not be used in newly-written code.

Useless deprecated macro. Ignore it.

Property Details

The "user-data" property

  "user-data"                gpointer              : Read / Write

Anonymous User Data Pointer.

Signal Details

The "destroy" signal

void                user_function                      (GtkObject *object,
                                                        gpointer   user_data)      : Cleanup / No Recursion / No Hooks

Signals that all holders of a reference to the GtkObject should release the reference that they hold. May result in finalization of the object if all references are released.

object : | the object which received the signal.
user_data : | user data set when the signal handler was connected.

See Also

GObject


Prev Home GTK+ Reference Manual Next

Part III. GTK+ Widgets and Objects


GtkOldEditable

GtkOldEditable — Base class for text-editing widgets

Synopsis

#include <gtk/gtk.h>

                    GtkOldEditable;
void                (*GtkTextFunction)                  (GtkOldEditable *editable,
                                                         guint32 time_);
void                gtk_old_editable_claim_selection    (GtkOldEditable *old_editable,
                                                         gboolean claim,
                                                         guint32 time_);
void                gtk_old_editable_changed            (GtkOldEditable *old_editable);

Object Hierarchy

  GObject
   +----GInitiallyUnowned
         +----GtkObject
               +----GtkWidget
                     +----GtkOldEditable
                           +----GtkText

Implemented Interfaces

GtkOldEditable implements AtkImplementorIface and GtkEditable.

Properties

  "editable"                 gboolean              : Read / Write
  "text-position"            gint                  : Read / Write

Signals

  "activate"                                       : Run Last / Action
  "copy-clipboard"                                 : Run Last / Action
  "cut-clipboard"                                  : Run Last / Action
  "kill-char"                                      : Run Last / Action
  "kill-line"                                      : Run Last / Action
  "kill-word"                                      : Run Last / Action
  "move-cursor"                                    : Run Last / Action
  "move-page"                                      : Run Last / Action
  "move-to-column"                                 : Run Last / Action
  "move-to-row"                                    : Run Last / Action
  "move-word"                                      : Run Last / Action
  "paste-clipboard"                                : Run Last / Action
  "set-editable"                                   : Run Last / Action

Description

GtkOldEditable has been deprecated since GTK+ 2.0 and should not be used in newly written code. Use the GtkEditable interface instead.

Details

GtkOldEditable

typedef struct {
  guint      current_pos;

  guint      selection_start_pos;
  guint      selection_end_pos;
  guint      has_selection : 1;
} GtkOldEditable;

Warning

GtkOldEditable is deprecated and should not be used in newly-written code.

GtkTextFunction ()

void                (*GtkTextFunction)                  (GtkOldEditable *editable,
                                                         guint32 time_);

Warning

GtkTextFunction is deprecated and should not be used in newly-written code.

editable :
time_ :

gtk_old_editable_claim_selection ()

void                gtk_old_editable_claim_selection    (GtkOldEditable *old_editable,
                                                         gboolean claim,
                                                         guint32 time_);

Warning

gtk_old_editable_claim_selection is deprecated and should not be used in newly-written code.

Claims or gives up ownership of the selection.

old_editable : | a GtkOldEditable
claim : | if TRUE, claim ownership of the selection, if FALSE, give up ownership
time_ : | timestamp for this operation

gtk_old_editable_changed ()

void                gtk_old_editable_changed            (GtkOldEditable *old_editable);

Warning

gtk_old_editable_changed is deprecated and should not be used in newly-written code.

Emits the ::changed signal on old_editable.

old_editable : a GtkOldEditable

Property Details

The "editable" property

  "editable"                 gboolean              : Read / Write

Default value: FALSE

The "text-position" property

  "text-position"            gint                  : Read / Write

Default value: 0

Signal Details

The "activate" signal

void                user_function                      (GtkOldEditable *oldeditable,
                                                        gpointer        user_data)        : Run Last / Action

oldeditable : | the object which received the signal.
user_data : | user data set when the signal handler was connected.

The "copy-clipboard" signal

void                user_function                      (GtkOldEditable *oldeditable,
                                                        gpointer        user_data)        : Run Last / Action

oldeditable : | the object which received the signal.
user_data : | user data set when the signal handler was connected.

The "cut-clipboard" signal

void                user_function                      (GtkOldEditable *oldeditable,
                                                        gpointer        user_data)        : Run Last / Action

oldeditable : | the object which received the signal.
user_data : | user data set when the signal handler was connected.

The "kill-char" signal

void                user_function                      (GtkOldEditable *oldeditable,
                                                        gint            arg1,
                                                        gpointer        user_data)        : Run Last / Action

oldeditable : | the object which received the signal.
arg1 : |
user_data : | user data set when the signal handler was connected.

The "kill-line" signal

void                user_function                      (GtkOldEditable *oldeditable,
                                                        gint            arg1,
                                                        gpointer        user_data)        : Run Last / Action

oldeditable : | the object which received the signal.
arg1 : |
user_data : | user data set when the signal handler was connected.

The "kill-word" signal

void                user_function                      (GtkOldEditable *oldeditable,
                                                        gint            arg1,
                                                        gpointer        user_data)        : Run Last / Action

oldeditable : | the object which received the signal.
arg1 : |
user_data : | user data set when the signal handler was connected.

The "move-cursor" signal

void                user_function                      (GtkOldEditable *oldeditable,
                                                        gint            arg1,
                                                        gint            arg2,
                                                        gpointer        user_data)        : Run Last / Action

oldeditable : | the object which received the signal.
arg1 : |
arg2 : |
user_data : | user data set when the signal handler was connected.

The "move-page" signal

void                user_function                      (GtkOldEditable *oldeditable,
                                                        gint            arg1,
                                                        gint            arg2,
                                                        gpointer        user_data)        : Run Last / Action

oldeditable : | the object which received the signal.
arg1 : |
arg2 : |
user_data : | user data set when the signal handler was connected.

The "move-to-column" signal

void                user_function                      (GtkOldEditable *oldeditable,
                                                        gint            arg1,
                                                        gpointer        user_data)        : Run Last / Action

oldeditable : | the object which received the signal.
arg1 : |
user_data : | user data set when the signal handler was connected.

The "move-to-row" signal

void                user_function                      (GtkOldEditable *oldeditable,
                                                        gint            arg1,
                                                        gpointer        user_data)        : Run Last / Action

oldeditable : | the object which received the signal.
arg1 : |
user_data : | user data set when the signal handler was connected.

The "move-word" signal

void                user_function                      (GtkOldEditable *oldeditable,
                                                        gint            arg1,
                                                        gpointer        user_data)        : Run Last / Action

oldeditable : | the object which received the signal.
arg1 : |
user_data : | user data set when the signal handler was connected.

The "paste-clipboard" signal

void                user_function                      (GtkOldEditable *oldeditable,
                                                        gpointer        user_data)        : Run Last / Action

oldeditable : | the object which received the signal.
user_data : | user data set when the signal handler was connected.

The "set-editable" signal

void                user_function                      (GtkOldEditable *oldeditable,
                                                        gboolean        arg1,
                                                        gpointer        user_data)        : Run Last / Action

oldeditable : | the object which received the signal.
arg1 : |
user_data : | user data set when the signal handler was connected.


GtkOptionMenu

GtkOptionMenu — A widget used to choose from a list of valid choices

Synopsis

#include <gtk/gtk.h>

                    GtkOptionMenu;
GtkWidget*          gtk_option_menu_new                 (void);
GtkWidget*          gtk_option_menu_get_menu            (GtkOptionMenu *option_menu);
void                gtk_option_menu_set_menu            (GtkOptionMenu *option_menu,
                                                         GtkWidget *menu);
void                gtk_option_menu_remove_menu         (GtkOptionMenu *option_menu);
void                gtk_option_menu_set_history         (GtkOptionMenu *option_menu,
                                                         guint index_);
gint                gtk_option_menu_get_history         (GtkOptionMenu *option_menu);

Object Hierarchy

  GObject
   +----GInitiallyUnowned
         +----GtkObject
               +----GtkWidget
                     +----GtkContainer
                           +----GtkBin
                                 +----GtkButton
                                       +----GtkOptionMenu

Implemented Interfaces

GtkOptionMenu implements AtkImplementorIface.

Properties

  "menu"                     GtkMenu               : Read / Write

Style Properties

  "indicator-size"           GtkRequisition        : Read
  "indicator-spacing"        GtkBorder             : Read

Signals

  "changed"                                        : Run Last

Description

A GtkOptionMenu is a widget that allows the user to choose from a list of valid choices. The GtkOptionMenu displays the selected choice. When activated the GtkOptionMenu displays a popup GtkMenu which allows the user to make a new choice.

Using a GtkOptionMenu is simple; build a GtkMenu, by calling gtk_menu_new(), then appending menu items to it with gtk_menu_shell_append(). Set that menu on the option menu with gtk_option_menu_set_menu(). Set the selected menu item with gtk_option_menu_set_history(); connect to the "changed" signal on the option menu; in the "changed" signal, check the new selected menu item with gtk_option_menu_get_history().

As of GTK+ 2.4, GtkOptionMenu has been deprecated in favor of GtkComboBox.

Details

GtkOptionMenu

typedef struct _GtkOptionMenu GtkOptionMenu;

Warning

GtkOptionMenu has been deprecated since version 2.4 and should not be used in newly-written code. Use GtkComboBox instead.

The GtkOptionMenu struct contains private data only, and should be accessed using the functions below.

gtk_option_menu_new ()

GtkWidget*          gtk_option_menu_new                 (void);

Warning

gtk_option_menu_new has been deprecated since version 2.4 and should not be used in newly-written code. Use GtkComboBox instead.

Creates a new GtkOptionMenu.

Returns : a new GtkOptionMenu.

gtk_option_menu_get_menu ()

GtkWidget*          gtk_option_menu_get_menu            (GtkOptionMenu *option_menu);

Warning

gtk_option_menu_get_menu has been deprecated since version 2.4 and should not be used in newly-written code. Use GtkComboBox instead.

Returns the GtkMenu associated with the GtkOptionMenu.

option_menu : | a GtkOptionMenu.
Returns : | the GtkMenu associated with the GtkOptionMenu.

gtk_option_menu_set_menu ()

void                gtk_option_menu_set_menu            (GtkOptionMenu *option_menu,
                                                         GtkWidget *menu);

Warning

gtk_option_menu_set_menu has been deprecated since version 2.4 and should not be used in newly-written code. Use GtkComboBox instead.

Provides the GtkMenu that is popped up to allow the user to choose a new value. You should provide a simple menu avoiding the use of tearoff menu items, submenus, and accelerators.

option_menu : | a GtkOptionMenu.
menu : | the GtkMenu to associate with the GtkOptionMenu.

gtk_option_menu_remove_menu ()

void                gtk_option_menu_remove_menu         (GtkOptionMenu *option_menu);

Warning

gtk_option_menu_remove_menu has been deprecated since version 2.4 and should not be used in newly-written code. Use GtkComboBox instead.

Removes the menu from the option menu.

option_menu : a GtkOptionMenu.

gtk_option_menu_set_history ()

void                gtk_option_menu_set_history         (GtkOptionMenu *option_menu,
                                                         guint index_);

Warning

gtk_option_menu_set_history has been deprecated since version 2.4 and should not be used in newly-written code. Use GtkComboBox instead.

Selects the menu item specified by index_ making it the newly selected value for the option menu.

option_menu : | a GtkOptionMenu.
index_ : | the index of the menu item to select. Index values are from 0 to n-1.

gtk_option_menu_get_history ()

gint                gtk_option_menu_get_history         (GtkOptionMenu *option_menu);

Warning

gtk_option_menu_get_history has been deprecated since version 2.4 and should not be used in newly-written code. Use GtkComboBox instead.

Retrieves the index of the currently selected menu item. The menu items are numbered from top to bottom, starting with 0.

option_menu : | a GtkOptionMenu
Returns : | index of the selected menu item, or -1 if there are no menu items

Property Details

The "menu" property

  "menu"                     GtkMenu               : Read / Write

The menu of options.

Style Property Details

The "indicator-size" style property

  "indicator-size"           GtkRequisition        : Read

Size of dropdown indicator.

The "indicator-spacing" style property

  "indicator-spacing"        GtkBorder             : Read

Spacing around indicator.

Signal Details

The "changed" signal

void                user_function                      (GtkOptionMenu *optionmenu,
                                                        gpointer       user_data)       : Run Last

optionmenu : | the object which received the signal.
user_data : | user data set when the signal handler was connected.


GtkPageSetup

GtkPageSetup — Stores page setup information

Synopsis

#include <gtk/gtk.h>

                    GtkPageSetup;
GtkPageSetup*       gtk_page_setup_new                  (void);
GtkPageSetup*       gtk_page_setup_copy                 (GtkPageSetup *other);
GtkPageOrientation  gtk_page_setup_get_orientation      (GtkPageSetup *setup);
void                gtk_page_setup_set_orientation      (GtkPageSetup *setup,
                                                         GtkPageOrientation orientation);
GtkPaperSize*       gtk_page_setup_get_paper_size       (GtkPageSetup *setup);
void                gtk_page_setup_set_paper_size       (GtkPageSetup *setup,
                                                         GtkPaperSize *size);
gdouble             gtk_page_setup_get_top_margin       (GtkPageSetup *setup,
                                                         GtkUnit unit);
void                gtk_page_setup_set_top_margin       (GtkPageSetup *setup,
                                                         gdouble margin,
                                                         GtkUnit unit);
gdouble             gtk_page_setup_get_bottom_margin    (GtkPageSetup *setup,
                                                         GtkUnit unit);
void                gtk_page_setup_set_bottom_margin    (GtkPageSetup *setup,
                                                         gdouble margin,
                                                         GtkUnit unit);
gdouble             gtk_page_setup_get_left_margin      (GtkPageSetup *setup,
                                                         GtkUnit unit);
void                gtk_page_setup_set_left_margin      (GtkPageSetup *setup,
                                                         gdouble margin,
                                                         GtkUnit unit);
gdouble             gtk_page_setup_get_right_margin     (GtkPageSetup *setup,
                                                         GtkUnit unit);
void                gtk_page_setup_set_right_margin     (GtkPageSetup *setup,
                                                         gdouble margin,
                                                         GtkUnit unit);
void                gtk_page_setup_set_paper_size_and_default_margins
                                                        (GtkPageSetup *setup,
                                                         GtkPaperSize *size);
gdouble             gtk_page_setup_get_paper_width      (GtkPageSetup *setup,
                                                         GtkUnit unit);
gdouble             gtk_page_setup_get_paper_height     (GtkPageSetup *setup,
                                                         GtkUnit unit);
gdouble             gtk_page_setup_get_page_width       (GtkPageSetup *setup,
                                                         GtkUnit unit);
gdouble             gtk_page_setup_get_page_height      (GtkPageSetup *setup,
                                                         GtkUnit unit);

Object Hierarchy

  GObject
   +----GtkPageSetup

Description

A GtkPageSetup object stores the page size, orientation and margins. The idea is that you can get one of these from the page setup dialog and then pass it to the GtkPrintOperation when printing. The benefit of splitting this out of the GtkPrintSettings is that these affect the actual layout of the page, and thus need to be set long before user prints.

The margins specified in this object are the "print margins", i.e. the parts of the page that the printer cannot print on. These are different from the layout margins that a word processor uses; they are typically used to determine the minimal size for the layout margins.

To obtain a GtkPageSetup use gtk_page_setup_new() to get the defaults, or use gtk_print_run_page_setup_dialog() to show the page setup dialog and receive the resulting page setup.

Example 32. A page setup dialog

static GtkPrintSettings *settings = NULL;
static GtkPageSetup *page_setup = NULL;

static void
do_page_setup (void)
{
  GtkPageSetup *new_page_setup;

  if (settings == NULL)
    settings = gtk_print_settings_new ();

  new_page_setup = gtk_print_run_page_setup_dialog (GTK_WINDOW (main_window),
                                                    page_setup, settings);

  if (page_setup)
    g_object_unref (page_setup);

  page_setup = new_page_setup;
}

Printing support was added in GTK+ 2.10.

Details

GtkPageSetup

typedef struct _GtkPageSetup GtkPageSetup;

gtk_page_setup_new ()

GtkPageSetup*       gtk_page_setup_new                  (void);

Creates a new GtkPageSetup.

Returns : a new GtkPageSetup.

Since 2.10

gtk_page_setup_copy ()

GtkPageSetup*       gtk_page_setup_copy                 (GtkPageSetup *other);

Copies a GtkPageSetup.

other : | the GtkPageSetup to copy
Returns : | a copy of other

Since 2.10

gtk_page_setup_get_orientation ()

GtkPageOrientation  gtk_page_setup_get_orientation      (GtkPageSetup *setup);

Gets the page orientation of the GtkPageSetup.

setup : | a GtkPageSetup
Returns : | the page orientation

Since 2.10

gtk_page_setup_set_orientation ()

void                gtk_page_setup_set_orientation      (GtkPageSetup *setup,
                                                         GtkPageOrientation orientation);

Sets the page orientation of the GtkPageSetup.

setup : | a GtkPageSetup
orientation : | a GtkPageOrientation value

Since 2.10

gtk_page_setup_get_paper_size ()

GtkPaperSize*       gtk_page_setup_get_paper_size       (GtkPageSetup *setup);

Gets the paper size of the GtkPageSetup.

setup : | a GtkPageSetup
Returns : | the paper size

Since 2.10

gtk_page_setup_set_paper_size ()

void                gtk_page_setup_set_paper_size       (GtkPageSetup *setup,
                                                         GtkPaperSize *size);

Sets the paper size of the GtkPageSetup without changing the margins. See gtk_page_setup_set_paper_size_and_default_margins().

setup : | a GtkPageSetup
size : | a GtkPaperSize

Since 2.10

gtk_page_setup_get_top_margin ()

gdouble             gtk_page_setup_get_top_margin       (GtkPageSetup *setup,
                                                         GtkUnit unit);

Gets the top margin in units of unit.

setup : | a GtkPageSetup
unit : | the unit for the return value
Returns : | the top margin

Since 2.10

gtk_page_setup_set_top_margin ()

void                gtk_page_setup_set_top_margin       (GtkPageSetup *setup,
                                                         gdouble margin,
                                                         GtkUnit unit);

Sets the top margin of the GtkPageSetup.

setup : | a GtkPageSetup
margin : | the new top margin in units of unit
unit : | the units for margin

Since 2.10

gtk_page_setup_get_bottom_margin ()

gdouble             gtk_page_setup_get_bottom_margin    (GtkPageSetup *setup,
                                                         GtkUnit unit);

Gets the bottom margin in units of unit.

setup : | a GtkPageSetup
unit : | the unit for the return value
Returns : | the bottom margin

Since 2.10

gtk_page_setup_set_bottom_margin ()

void                gtk_page_setup_set_bottom_margin    (GtkPageSetup *setup,
                                                         gdouble margin,
                                                         GtkUnit unit);

Sets the bottom margin of the GtkPageSetup.

setup : | a GtkPageSetup
margin : | the new bottom margin in units of unit
unit : | the units for margin

Since 2.10

gtk_page_setup_get_left_margin ()

gdouble             gtk_page_setup_get_left_margin      (GtkPageSetup *setup,
                                                         GtkUnit unit);

Gets the left margin in units of unit.

setup : | a GtkPageSetup
unit : | the unit for the return value
Returns : | the left margin

Since 2.10

gtk_page_setup_set_left_margin ()

void                gtk_page_setup_set_left_margin      (GtkPageSetup *setup,
                                                         gdouble margin,
                                                         GtkUnit unit);

Sets the left margin of the GtkPageSetup.

setup : | a GtkPageSetup
margin : | the new left margin in units of unit
unit : | the units for margin

Since 2.10

gtk_page_setup_get_right_margin ()

gdouble             gtk_page_setup_get_right_margin     (GtkPageSetup *setup,
                                                         GtkUnit unit);

Gets the right margin in units of unit.

setup : | a GtkPageSetup
unit : | the unit for the return value
Returns : | the right margin

Since 2.10

gtk_page_setup_set_right_margin ()

void                gtk_page_setup_set_right_margin     (GtkPageSetup *setup,
                                                         gdouble margin,
                                                         GtkUnit unit);

Sets the right margin of the GtkPageSetup.

setup : | a GtkPageSetup
margin : | the new right margin in units of unit
unit : | the units for margin

Since 2.10

gtk_page_setup_set_paper_size_and_default_margins ()

void                gtk_page_setup_set_paper_size_and_default_margins
                                                        (GtkPageSetup *setup,
                                                         GtkPaperSize *size);

Sets the paper size of the GtkPageSetup and modifies the margins according to the new paper size.

setup : | a GtkPageSetup
size : | a GtkPaperSize

Since 2.10

gtk_page_setup_get_paper_width ()

gdouble             gtk_page_setup_get_paper_width      (GtkPageSetup *setup,
                                                         GtkUnit unit);

Returns the paper width in units of unit.

Note that this function takes orientation, but not margins into consideration. See gtk_page_setup_get_page_width().

setup : | a GtkPageSetup
unit : | the unit for the return value
Returns : | the paper width.

Since 2.10

gtk_page_setup_get_paper_height ()

gdouble             gtk_page_setup_get_paper_height     (GtkPageSetup *setup,
                                                         GtkUnit unit);

Returns the paper height in units of unit.

Note that this function takes orientation, but not margins into consideration. See gtk_page_setup_get_page_height().

setup : | a GtkPageSetup
unit : | the unit for the return value
Returns : | the paper height.

Since 2.10

gtk_page_setup_get_page_width ()

gdouble             gtk_page_setup_get_page_width       (GtkPageSetup *setup,
                                                         GtkUnit unit);

Returns the page width in units of unit.

Note that this function takes orientation and margins into consideration. See gtk_page_setup_get_paper_width().

setup : | a GtkPageSetup
unit : | the unit for the return value
Returns : | the page width.

Since 2.10

gtk_page_setup_get_page_height ()

gdouble             gtk_page_setup_get_page_height      (GtkPageSetup *setup,
                                                         GtkUnit unit);

Returns the page height in units of unit.

Note that this function takes orientation and margins into consideration. See gtk_page_setup_get_paper_height().

setup : | a GtkPageSetup
unit : | the unit for the return value
Returns : | the page height.

Since 2.10


GtkPageSetupUnixDialog

GtkPageSetupUnixDialog — A page setup dialog

Synopsis

#include <gtk/gtkpagesetupunixdialog.h>

                    GtkPageSetupUnixDialog;
GtkWidget*          gtk_page_setup_unix_dialog_new      (const gchar *title,
                                                         GtkWindow *parent);
void                gtk_page_setup_unix_dialog_set_page_setup
                                                        (GtkPageSetupUnixDialog *dialog,
                                                         GtkPageSetup *page_setup);
GtkPageSetup*       gtk_page_setup_unix_dialog_get_page_setup
                                                        (GtkPageSetupUnixDialog *dialog);
void                gtk_page_setup_unix_dialog_set_print_settings
                                                        (GtkPageSetupUnixDialog *dialog,
                                                         GtkPrintSettings *print_settings);
GtkPrintSettings*   gtk_page_setup_unix_dialog_get_print_settings
                                                        (GtkPageSetupUnixDialog *dialog);

Object Hierarchy

  GObject
   +----GInitiallyUnowned
         +----GtkObject
               +----GtkWidget
                     +----GtkContainer
                           +----GtkBin
                                 +----GtkWindow
                                       +----GtkDialog
                                             +----GtkPageSetupUnixDialog

Implemented Interfaces

GtkPageSetupUnixDialog implements AtkImplementorIface.

Description

GtkPageSetupUnixDialog implements a page setup dialog for platforms which don't provide a native page setup dialog, like Unix. It can be used very much like any other GTK+ dialog, at the cost of the portability offered by the high-level printing API

Printing support was added in GTK+ 2.10.

Details

GtkPageSetupUnixDialog

typedef struct _GtkPageSetupUnixDialog GtkPageSetupUnixDialog;

gtk_page_setup_unix_dialog_new ()

GtkWidget*          gtk_page_setup_unix_dialog_new      (const gchar *title,
                                                         GtkWindow *parent);

Creates a new page setup dialog.

title : | the title of the dialog, or NULL
parent : | transient parent of the dialog, or NULL
Returns : | the new GtkPageSetupUnixDialog

Since 2.10

gtk_page_setup_unix_dialog_set_page_setup ()

void                gtk_page_setup_unix_dialog_set_page_setup
                                                        (GtkPageSetupUnixDialog *dialog,
                                                         GtkPageSetup *page_setup);

Sets the GtkPageSetup from which the page setup dialog takes its values.

dialog : | a GtkPageSetupUnixDialog
page_setup : | a GtkPageSetup

Since 2.10

gtk_page_setup_unix_dialog_get_page_setup ()

GtkPageSetup*       gtk_page_setup_unix_dialog_get_page_setup
                                                        (GtkPageSetupUnixDialog *dialog);

Gets the currently selected page setup from the dialog.

dialog : | a GtkPageSetupUnixDialog
Returns : | the current page setup

Since 2.10

gtk_page_setup_unix_dialog_set_print_settings ()

void                gtk_page_setup_unix_dialog_set_print_settings
                                                        (GtkPageSetupUnixDialog *dialog,
                                                         GtkPrintSettings *print_settings);

Sets the GtkPrintSettings from which the page setup dialog takes its values.

dialog : | a GtkPageSetupUnixDialog
print_settings : | a GtkPrintSettings

Since 2.10

gtk_page_setup_unix_dialog_get_print_settings ()

GtkPrintSettings*   gtk_page_setup_unix_dialog_get_print_settings
                                                        (GtkPageSetupUnixDialog *dialog);

Gets the current print settings from the dialog.

dialog : | a GtkPageSetupUnixDialog
Returns : | the current print settings

Since 2.10


GtkPaned

GtkPaned — Base class for widgets with two adjustable panes

Synopsis

#include <gtk/gtk.h>

                    GtkPaned;
void                gtk_paned_add1                      (GtkPaned *paned,
                                                         GtkWidget *child);
void                gtk_paned_add2                      (GtkPaned *paned,
                                                         GtkWidget *child);
#define             gtk_paned_gutter_size               (p,s)
void                gtk_paned_pack1                     (GtkPaned *paned,
                                                         GtkWidget *child,
                                                         gboolean resize,
                                                         gboolean shrink);
void                gtk_paned_pack2                     (GtkPaned *paned,
                                                         GtkWidget *child,
                                                         gboolean resize,
                                                         gboolean shrink);
GtkWidget*          gtk_paned_get_child1                (GtkPaned *paned);
GtkWidget*          gtk_paned_get_child2                (GtkPaned *paned);
#define             gtk_paned_set_gutter_size           (p,s)
void                gtk_paned_set_position              (GtkPaned *paned,
                                                         gint position);
gint                gtk_paned_get_position              (GtkPaned *paned);

Object Hierarchy

  GObject
   +----GInitiallyUnowned
         +----GtkObject
               +----GtkWidget
                     +----GtkContainer
                           +----GtkPaned
                                 +----GtkHPaned
                                 +----GtkVPaned

Implemented Interfaces

GtkPaned implements AtkImplementorIface.

Properties

  "max-position"             gint                  : Read
  "min-position"             gint                  : Read
  "position"                 gint                  : Read / Write
  "position-set"             gboolean              : Read / Write

Child Properties

  "resize"                   gboolean              : Read / Write
  "shrink"                   gboolean              : Read / Write

Style Properties

  "handle-size"              gint                  : Read

Signals

  "accept-position"                                : Run Last / Action
  "cancel-position"                                : Run Last / Action
  "cycle-child-focus"                              : Run Last / Action
  "cycle-handle-focus"                             : Run Last / Action
  "move-handle"                                    : Run Last / Action
  "toggle-handle-focus"                            : Run Last / Action

Description

GtkPaned is the base class for widgets with two panes, arranged either horizontally (GtkHPaned) or vertically (GtkVPaned). Child widgets are added to the panes of the widget with gtk_paned_pack1() and gtk_paned_pack2(). The division beween the two children is set by default from the size requests of the children, but it can be adjusted by the user.

A paned widget draws a separator between the two child widgets and a small handle that the user can drag to adjust the division. It does not draw any relief around the children or around the separator. (The space in which the separator is called the gutter.) Often, it is useful to put each child inside a GtkFrame with the shadow type set to GTK_SHADOW_IN so that the gutter appears as a ridge.

Each child has two options that can be set, resize and shrink. If resize is true, then when the GtkPaned is resized, that child will expand or shrink along with the paned widget. If shrink is true, then when that child can be made smaller than its requisition by the user. Setting shrink to FALSE allows the application to set a minimum size. If resize is false for both children, then this is treated as if resize is true for both children.

The application can set the position of the slider as if it were set by the user, by calling gtk_paned_set_position().

Example 35. Creating a paned widget with minimum sizes.

GtkWidget *hpaned = gtk_hpaned_new ();
GtkWidget *frame1 = gtk_frame_new (NULL);
GtkWidget *frame2 = gtk_frame_new (NULL);
gtk_frame_set_shadow_type (GTK_FRAME (frame1), GTK_SHADOW_IN);
gtk_frame_set_shadow_type (GTK_FRAME (frame2), GTK_SHADOW_IN);

gtk_widget_set_size_request (hpaned, 200 + GTK_PANED (hpaned)->gutter_size, -1);

gtk_paned_pack1 (GTK_PANED (hpaned), frame1, TRUE, FALSE);
gtk_widget_set_size_request (frame1, 50, -1);

gtk_paned_pack2 (GTK_PANED (hpaned), frame2, FALSE, FALSE);
gtk_widget_set_size_request (frame2, 50, -1);

Details

GtkPaned

typedef struct _GtkPaned GtkPaned;

gtk_paned_add1 ()

void                gtk_paned_add1                      (GtkPaned *paned,
                                                         GtkWidget *child);

Adds a child to the top or left pane with default parameters. This is equivalent to gtk_paned_pack1 (paned, child, FALSE, TRUE).

paned : | a paned widget
child : | the child to add

gtk_paned_add2 ()

void                gtk_paned_add2                      (GtkPaned *paned,
                                                         GtkWidget *child);

Adds a child to the bottom or right pane with default parameters. This is equivalent to gtk_paned_pack2 (paned, child, TRUE, TRUE).

paned : | a paned widget
child : | the child to add

gtk_paned_gutter_size()

#define	gtk_paned_gutter_size(p,s)		(void) 0

Warning

gtk_paned_gutter_size is deprecated and should not be used in newly-written code.

Old name for gtk_paned_set_gutter_size().

p : | a paned widget
s : | the width of the gutter in pixels

gtk_paned_pack1 ()

void                gtk_paned_pack1                     (GtkPaned *paned,
                                                         GtkWidget *child,
                                                         gboolean resize,
                                                         gboolean shrink);

Adds a child to the top or left pane.

paned : | a paned widget
child : | the child to add
resize : | should this child expand when the paned widget is resized.
shrink : | can this child be made smaller than its requisition.

gtk_paned_pack2 ()

void                gtk_paned_pack2                     (GtkPaned *paned,
                                                         GtkWidget *child,
                                                         gboolean resize,
                                                         gboolean shrink);

Adds a child to the bottom or right pane.

paned : | a paned widget
child : | the child to add
resize : | should this child expand when the paned widget is resized.
shrink : | can this child be made smaller than its requisition.

gtk_paned_get_child1 ()

GtkWidget*          gtk_paned_get_child1                (GtkPaned *paned);

Obtains the first child of the paned widget.

paned : | a GtkPaned widget
Returns : | first child, or NULL if it is not set.

Since 2.4

gtk_paned_get_child2 ()

GtkWidget*          gtk_paned_get_child2                (GtkPaned *paned);

Obtains the second child of the paned widget.

paned : | a GtkPaned widget
Returns : | second child, or NULL if it is not set.

Since 2.4

gtk_paned_set_gutter_size()

#define	gtk_paned_set_gutter_size(p,s)		(void) 0

Warning

gtk_paned_set_gutter_size is deprecated and should not be used in newly-written code.

In older versions of GTK+, this function used to set the width of the gutter (the area between the two panes). It does nothing now.

p : | a paned widget
s : | the width of the gutter in pixels

gtk_paned_set_position ()

void                gtk_paned_set_position              (GtkPaned *paned,
                                                         gint position);

Sets the position of the divider between the two panes.

paned : | a GtkPaned widget
position : | pixel position of divider, a negative value means that the position is unset.

gtk_paned_get_position ()

gint                gtk_paned_get_position              (GtkPaned *paned);

Obtains the position of the divider between the two panes.

paned : | a GtkPaned widget
Returns : | position of the divider

Property Details

The "max-position" property

  "max-position"             gint                  : Read

The largest possible value for the position property. This property is derived from the size and shrinkability of the widget's children.

Allowed values: >= 0

Default value: 2147483647

Since 2.4

The "min-position" property

  "min-position"             gint                  : Read

The smallest possible value for the position property. This property is derived from the size and shrinkability of the widget's children.

Allowed values: >= 0

Default value: 0

Since 2.4

The "position" property

  "position"                 gint                  : Read / Write

Position of paned separator in pixels (0 means all the way to the left/top).

Allowed values: >= 0

Default value: 0

The "position-set" property

  "position-set"             gboolean              : Read / Write

TRUE if the Position property should be used.

Default value: FALSE

Child Property Details

The "resize" child property

  "resize"                   gboolean              : Read / Write

The "resize" child property determines whether the child expands and shrinks along with the paned widget.

Default value: TRUE

Since 2.4

The "shrink" child property

  "shrink"                   gboolean              : Read / Write

The "shrink" child property determines whether the child can be made smaller than its requisition.

Default value: TRUE

Since 2.4

Style Property Details

The "handle-size" style property

  "handle-size"              gint                  : Read

Width of handle.

Allowed values: >= 0

Default value: 5

Signal Details

The "accept-position" signal

gboolean            user_function                      (GtkPaned *paned,
                                                        gpointer  user_data)      : Run Last / Action

paned : | the object which received the signal.
user_data : | user data set when the signal handler was connected.
Returns : |

The "cancel-position" signal

gboolean            user_function                      (GtkPaned *paned,
                                                        gpointer  user_data)      : Run Last / Action

paned : | the object which received the signal.
user_data : | user data set when the signal handler was connected.
Returns : |

The "cycle-child-focus" signal

gboolean            user_function                      (GtkPaned *paned,
                                                        gboolean  arg1,
                                                        gpointer  user_data)      : Run Last / Action

paned : | the object which received the signal.
arg1 : |
user_data : | user data set when the signal handler was connected.
Returns : |

The "cycle-handle-focus" signal

gboolean            user_function                      (GtkPaned *paned,
                                                        gboolean  arg1,
                                                        gpointer  user_data)      : Run Last / Action

paned : | the object which received the signal.
arg1 : |
user_data : | user data set when the signal handler was connected.
Returns : |

The "move-handle" signal

gboolean            user_function                      (GtkPaned     *paned,
                                                        GtkScrollType arg1,
                                                        gpointer      user_data)      : Run Last / Action

paned : | the object which received the signal.
arg1 : |
user_data : | user data set when the signal handler was connected.
Returns : |

The "toggle-handle-focus" signal

gboolean            user_function                      (GtkPaned *paned,
                                                        gpointer  user_data)      : Run Last / Action

paned : | the object which received the signal.
user_data : | user data set when the signal handler was connected.
Returns : |


GtkPixmap

GtkPixmap — A widget displaying a graphical image or icon

Synopsis

#include <gtk/gtk.h>

                    GtkPixmap;
GtkWidget*          gtk_pixmap_new                      (GdkPixmap *pixmap,
                                                         GdkBitmap *mask);
void                gtk_pixmap_set                      (GtkPixmap *pixmap,
                                                         GdkPixmap *val,
                                                         GdkBitmap *mask);
void                gtk_pixmap_get                      (GtkPixmap *pixmap,
                                                         GdkPixmap **val,
                                                         GdkBitmap **mask);
void                gtk_pixmap_set_build_insensitive    (GtkPixmap *pixmap,
                                                         gboolean build);

Object Hierarchy

  GObject
   +----GInitiallyUnowned
         +----GtkObject
               +----GtkWidget
                     +----GtkMisc
                           +----GtkPixmap

Implemented Interfaces

GtkPixmap implements AtkImplementorIface.

Description

The GtkPixmap widget displays a graphical image or icon. The icon is typically created using gdk_pixmap_colormap_create_from_xpm() or gdk_pixmap_colormap_create_from_xpm_d().

The pixels in a GtkPixmap cannot be manipulated by the application after creation, since under the X Window system the pixel data is stored on the X server and so is not available to the client application. If you want to create graphical images which can be manipulated by the application, look at GtkImage and GdkRGB.

GtkPixmap has been deprecated since GTK+ 2.0 and should not be used in newly written code. Use GtkImage instead.

Details

GtkPixmap

typedef struct _GtkPixmap GtkPixmap;

Warning

GtkPixmap is deprecated and should not be used in newly-written code.

The GtkPixmap struct contains private data only, and should be accessed using the functions below.

gtk_pixmap_new ()

GtkWidget*          gtk_pixmap_new                      (GdkPixmap *pixmap,
                                                         GdkBitmap *mask);

Warning

gtk_pixmap_new is deprecated and should not be used in newly-written code.

Creates a new GtkPixmap, using the given GDK pixmap and mask.

pixmap : | a GDKPixmap.
mask : | a GDKBitmap which indicates which parts of the pixmap should be transparent.
Returns : | a new GtkPixmap.

gtk_pixmap_set ()

void                gtk_pixmap_set                      (GtkPixmap *pixmap,
                                                         GdkPixmap *val,
                                                         GdkBitmap *mask);

Warning

gtk_pixmap_set is deprecated and should not be used in newly-written code.

Sets the GdkPixmap and GdkBitmap mask.

pixmap : | a GtkPixmap.
val : | a GdkPixmap.
mask : | a GdkBitmap, which indicates which parts of the pixmap should be transparent. This can be NULL, in which case none of the pixmap is transparent.

gtk_pixmap_get ()

void                gtk_pixmap_get                      (GtkPixmap *pixmap,
                                                         GdkPixmap **val,
                                                         GdkBitmap **mask);

Warning

gtk_pixmap_get is deprecated and should not be used in newly-written code.

Gets the current GdkPixmap and GdkBitmap mask.

pixmap : | a GtkPixmap.
val : | returns the current GdkPixmap.
mask : | returns the current GdkBitmap mask.

gtk_pixmap_set_build_insensitive ()

void                gtk_pixmap_set_build_insensitive    (GtkPixmap *pixmap,
                                                         gboolean build);

Warning

gtk_pixmap_set_build_insensitive is deprecated and should not be used in newly-written code.

Sets wether an extra pixmap should be automatically created and used when the pixmap is insensitive. The default value is TRUE.

pixmap : | a GtkPixmap.
build : | set to TRUE if an extra pixmap should be automatically created to use when the pixmap is insensitive.


GtkPlug

GtkPlug — Toplevel for embedding into other processes

Synopsis

#include <gtk/gtk.h>

                    GtkPlug;
void                gtk_plug_construct                  (GtkPlug *plug,
                                                         GdkNativeWindow socket_id);
void                gtk_plug_construct_for_display      (GtkPlug *plug,
                                                         GdkDisplay *display,
                                                         GdkNativeWindow socket_id);
GtkWidget*          gtk_plug_new                        (GdkNativeWindow socket_id);
GtkWidget*          gtk_plug_new_for_display            (GdkDisplay *display,
                                                         GdkNativeWindow socket_id);
GdkNativeWindow     gtk_plug_get_id                     (GtkPlug *plug);

Object Hierarchy

  GObject
   +----GInitiallyUnowned
         +----GtkObject
               +----GtkWidget
                     +----GtkContainer
                           +----GtkBin
                                 +----GtkWindow
                                       +----GtkPlug

Implemented Interfaces

GtkPlug implements AtkImplementorIface.

Signals

  "embedded"                                       : Run Last

Description

Together with GtkSocket, GtkPlug provides the ability to embed widgets from one process into another process in a fashion that is transparent to the user. One process creates a GtkSocket widget and, passes the ID of that widgets window to the other process, which then creates a GtkPlug with that window ID. Any widgets contained in the GtkPlug then will appear inside the first applications window.

Note

The GtkPlug and GtkSocket widgets are currently not available on all platforms supported by GTK+.

Details

GtkPlug

typedef struct _GtkPlug GtkPlug;

gtk_plug_construct ()

void                gtk_plug_construct                  (GtkPlug *plug,
                                                         GdkNativeWindow socket_id);

Finish the initialization of plug for a given GtkSocket identified by socket_id. This function will generally only be used by classes deriving from GtkPlug.

plug : | a GtkPlug.
socket_id : | the XID of the socket's window.

gtk_plug_construct_for_display ()

void                gtk_plug_construct_for_display      (GtkPlug *plug,
                                                         GdkDisplay *display,
                                                         GdkNativeWindow socket_id);

Finish the initialization of plug for a given GtkSocket identified by socket_id which is currently displayed on display. This function will generally only be used by classes deriving from GtkPlug.

plug : | a GtkPlug.
display : | the GdkDisplay associated with socket_id's GtkSocket.
socket_id : | the XID of the socket's window.

Since 2.2

gtk_plug_new ()

GtkWidget*          gtk_plug_new                        (GdkNativeWindow socket_id);

Creates a new plug widget inside the GtkSocket identified by socket_id. If socket_id is 0, the plug is left "unplugged" and can later be plugged into a GtkSocket by gtk_socket_add_id().

socket_id : | the window ID of the socket, or 0.
Returns : | the new GtkPlug widget.

gtk_plug_new_for_display ()

GtkWidget*          gtk_plug_new_for_display            (GdkDisplay *display,
                                                         GdkNativeWindow socket_id);

Create a new plug widget inside the GtkSocket identified by socket_id.

display : | the GdkDisplay on which socket_id is displayed
socket_id : | the XID of the socket's window.
Returns : | the new GtkPlug widget.

Since 2.2

gtk_plug_get_id ()

GdkNativeWindow     gtk_plug_get_id                     (GtkPlug *plug);

Gets the window ID of a GtkPlug widget, which can then be used to embed this window inside another window, for instance with gtk_socket_add_id().

plug : | a GtkPlug.
Returns : | the window ID for the plug

Signal Details

The "embedded" signal

void                user_function                      (GtkPlug *plug,
                                                        gpointer user_data)      : Run Last

plug : | the object which received the signal.
user_data : | user data set when the signal handler was connected.

See Also

GtkSocket

the widget that a GtkPlug plugs into.


GtkPreview

GtkPreview — A widget to display RGB or grayscale data

Synopsis

#include <gtk/gtk.h>

                    GtkPreview;
                    GtkPreviewInfo;
union               GtkDitherInfo;
void                gtk_preview_uninit                  (void);
GtkWidget*          gtk_preview_new                     (GtkPreviewType type);
void                gtk_preview_size                    (GtkPreview *preview,
                                                         gint width,
                                                         gint height);
void                gtk_preview_put                     (GtkPreview *preview,
                                                         GdkWindow *window,
                                                         GdkGC *gc,
                                                         gint srcx,
                                                         gint srcy,
                                                         gint destx,
                                                         gint desty,
                                                         gint width,
                                                         gint height);
void                gtk_preview_draw_row                (GtkPreview *preview,
                                                         guchar *data,
                                                         gint x,
                                                         gint y,
                                                         gint w);
void                gtk_preview_set_expand              (GtkPreview *preview,
                                                         gboolean expand);
void                gtk_preview_set_gamma               (double gamma_);
void                gtk_preview_set_color_cube          (guint nred_shades,
                                                         guint ngreen_shades,
                                                         guint nblue_shades,
                                                         guint ngray_shades);
void                gtk_preview_set_install_cmap        (gint install_cmap);
void                gtk_preview_set_reserved            (gint nreserved);
void                gtk_preview_set_dither              (GtkPreview *preview,
                                                         GdkRgbDither dither);
GdkVisual*          gtk_preview_get_visual              (void);
GdkColormap*        gtk_preview_get_cmap                (void);
GtkPreviewInfo*     gtk_preview_get_info                (void);
void                gtk_preview_reset                   (void);

Object Hierarchy

  GObject
   +----GInitiallyUnowned
         +----GtkObject
               +----GtkWidget
                     +----GtkPreview

Implemented Interfaces

GtkPreview implements AtkImplementorIface.

Properties

  "expand"                   gboolean              : Read / Write

Description

The GtkPreview widget provides a simple interface used to display images as RGB or grayscale data. It's deprecated; just use a GdkPixbuf displayed by a GtkImage, or perhaps a GtkDrawingArea. GtkPreview has no advantage over those approaches.

Details

GtkPreview

typedef struct _GtkPreview GtkPreview;

Warning

GtkPreview is deprecated and should not be used in newly-written code.

The GtkPreview struct contains private data only, and should be accessed using the functions below.

GtkPreviewInfo

typedef struct {
  guchar *lookup;

  gdouble gamma;
} GtkPreviewInfo;

Warning

GtkPreviewInfo is deprecated and should not be used in newly-written code.

Contains information about global properties of preview widgets. The GtkPreviewInfo struct contains the following fields. (These fields should be considered read-only. They should never be set by an application.)

GdkVisual *visual; | the visual used by all previews.
GdkColormap *cmap; | the colormap used by all previews.
gdouble gamma; | the gamma correction value used by all previews (See gtk_preview_set_gamma()).

union GtkDitherInfo

union GtkDitherInfo
{
  gushort s[2];
  guchar c[4];
};

Warning

GtkDitherInfo is deprecated and should not be used in newly-written code.

This union not used in GTK+.

gtk_preview_uninit ()

void                gtk_preview_uninit                  (void);

Warning

gtk_preview_uninit is deprecated and should not be used in newly-written code.

This function is deprecated and does nothing.

gtk_preview_new ()

GtkWidget*          gtk_preview_new                     (GtkPreviewType type);

Warning

gtk_preview_new is deprecated and should not be used in newly-written code.

Create a new preview widget.

type : | the type data contained by the widget. (Grayscale or RGB)
Returns : | a new GtkPreview

gtk_preview_size ()

void                gtk_preview_size                    (GtkPreview *preview,
                                                         gint width,
                                                         gint height);

Warning

gtk_preview_size is deprecated and should not be used in newly-written code.

Set the size that the preview widget will request in response to a "size_request" signal. The drawing area may actually be allocated a size larger than this depending on how it is packed within the enclosing containers. The effect of this is determined by whether the preview is set to expand or not (see gtk_preview_expand())

preview : | a GtkPreview.
width : | the new width.
height : | the new height.

gtk_preview_put ()

void                gtk_preview_put                     (GtkPreview *preview,
                                                         GdkWindow *window,
                                                         GdkGC *gc,
                                                         gint srcx,
                                                         gint srcy,
                                                         gint destx,
                                                         gint desty,
                                                         gint width,
                                                         gint height);

Warning

gtk_preview_put is deprecated and should not be used in newly-written code.

Takes a portion of the contents of a preview widget and draws it onto the given drawable, window.

preview : | a GtkPreview.
window : | a window or pixmap.
gc : | The graphics context for the operation. Only the clip mask for this GC matters.
srcx : | the x coordinate of the upper left corner in the source image.
srcy : | the y coordinate of the upper left corner in the source image.
destx : | the x coordinate of the upper left corner in the destination image.
desty : | the y coordinate of the upper left corner in the destination image.
width : | the width of the rectangular portion to draw.
height : | the height of the rectangular portion to draw.

gtk_preview_draw_row ()

void                gtk_preview_draw_row                (GtkPreview *preview,
                                                         guchar *data,
                                                         gint x,
                                                         gint y,
                                                         gint w);

Warning

gtk_preview_draw_row is deprecated and should not be used in newly-written code.

Sets the data for a portion of a row.

preview : | a GtkPreview.
data : | the new data for the portion. It should contain w bytes of data if the preview is of type GTK_TYPE_GRAYSCALE, and 3*w bytes of data if the preview is of type GTK_TYPE_COLOR.
x : | the starting value on the row to set.
y : | the row to change.
w : | the number of pixels in the row to change.

gtk_preview_set_expand ()

void                gtk_preview_set_expand              (GtkPreview *preview,
                                                         gboolean expand);

Warning

gtk_preview_set_expand is deprecated and should not be used in newly-written code.

Determines the way that the the preview widget behaves when the size it is allocated is larger than the requested size. If expand is FALSE, then the preview's window and buffer will be no larger than the size set with gtk_preview_size(), and the data set will be centered in the allocation if it is larger. If expand is TRUE then the window and buffer will expand with the allocation; the application is responsible for catching the "size_allocate" signal and providing the data appropriate for this size.

preview : | a GtkPreview.
expand : | whether the preview's window should expand or not.

gtk_preview_set_gamma ()

void                gtk_preview_set_gamma               (double gamma_);

Warning

gtk_preview_set_gamma is deprecated and should not be used in newly-written code.

Set the gamma-correction value for all preview widgets. (This function will eventually be replaced with a function that sets a per-preview-widget gamma value). The resulting intensity is given by: destination_value * pow (source_value/255, 1/gamma). The gamma value is applied when the data is set with gtk_preview_draw_row() so changing this value will not affect existing data in preview widgets.

gamma_ : the new gamma value.

gtk_preview_set_color_cube ()

void                gtk_preview_set_color_cube          (guint nred_shades,
                                                         guint ngreen_shades,
                                                         guint nblue_shades,
                                                         guint ngray_shades);

Warning

gtk_preview_set_color_cube is deprecated and should not be used in newly-written code.

This function is deprecated and does nothing. GdkRGB automatically picks an optimium color cube for the display.

nred_shades : | ignored
ngreen_shades : | ignored
nblue_shades : | ignored
ngray_shades : | ignored

gtk_preview_set_install_cmap ()

void                gtk_preview_set_install_cmap        (gint install_cmap);

Warning

gtk_preview_set_install_cmap is deprecated and should not be used in newly-written code.

This function is deprecated and does nothing. GdkRGB will automatically pick a private colormap if it cannot allocate sufficient colors.

install_cmap : ignored.

gtk_preview_set_reserved ()

void                gtk_preview_set_reserved            (gint nreserved);

Warning

gtk_preview_set_reserved is deprecated and should not be used in newly-written code.

This function is deprecated and does nothing.

nreserved : ignored.

gtk_preview_set_dither ()

void                gtk_preview_set_dither              (GtkPreview *preview,
                                                         GdkRgbDither dither);

Warning

gtk_preview_set_dither is deprecated and should not be used in newly-written code.

Set the dithering mode for the display.

preview : | a GtkPreview.
dither : | the dithering mode.

gtk_preview_get_visual ()

GdkVisual*          gtk_preview_get_visual              (void);

Warning

gtk_preview_get_visual is deprecated and should not be used in newly-written code.

Returns the visual used by preview widgets. This function is deprecated, and you should use gdk_rgb_get_visual() instead.

Returns : the visual for previews.

gtk_preview_get_cmap ()

GdkColormap*        gtk_preview_get_cmap                (void);

Warning

gtk_preview_get_cmap is deprecated and should not be used in newly-written code.

Returns the colormap used by preview widgets. This function is deprecated, and you should use gdk_rgb_get_cmap() instead.

Returns : the colormap for previews.

gtk_preview_get_info ()

GtkPreviewInfo*     gtk_preview_get_info                (void);

Warning

gtk_preview_get_info is deprecated and should not be used in newly-written code.

Return a GtkPreviewInfo structure containing global information about preview widgets.

Returns : a GtkPreviewInfo structure. The return value belongs to GTK+ and must not be modified or freed.

gtk_preview_reset ()

void                gtk_preview_reset                   (void);

Warning

gtk_preview_reset is deprecated and should not be used in newly-written code.

This function is deprecated and does nothing. It was once used for changing the colormap and visual on the fly.

Property Details

The "expand" property

  "expand"                   gboolean              : Read / Write

Whether the preview widget should take up the entire space it is allocated.

Default value: FALSE

See Also

GdkRGB

the backend used by GtkPreview.


GtkPrintContext

GtkPrintContext — Encapsulates context for drawing pages

Synopsis

#include <gtk/gtk.h>

                    GtkPrintContext;
cairo_t*            gtk_print_context_get_cairo_context (GtkPrintContext *context);
void                gtk_print_context_set_cairo_context (GtkPrintContext *context,
                                                         cairo_t *cr,
                                                         double dpi_x,
                                                         double dpi_y);
GtkPageSetup*       gtk_print_context_get_page_setup    (GtkPrintContext *context);
gdouble             gtk_print_context_get_width         (GtkPrintContext *context);
gdouble             gtk_print_context_get_height        (GtkPrintContext *context);
gdouble             gtk_print_context_get_dpi_x         (GtkPrintContext *context);
gdouble             gtk_print_context_get_dpi_y         (GtkPrintContext *context);
PangoFontMap*       gtk_print_context_get_pango_fontmap (GtkPrintContext *context);
PangoContext*       gtk_print_context_create_pango_context
                                                        (GtkPrintContext *context);
PangoLayout*        gtk_print_context_create_pango_layout
                                                        (GtkPrintContext *context);

Object Hierarchy

  GObject
   +----GtkPrintContext

Description

A GtkPrintContext encapsulates context information that is required when drawing pages for printing, such as the cairo context and important parameters like page size and resolution. It also lets you easily create PangoLayout and PangoContext objects that match the font metrics of the cairo surface.

GtkPrintContext objects gets passed to the ::begin-print, ::end-print, ::request-page-setup and ::draw-page signals on the GtkPrintOperation.

Example 31. Using GtkPrintContext in a ::draw-page callback

static void
draw_page (GtkPrintOperation *operation,
       GtkPrintContext   *context,
       int                page_nr)
{
  cairo_t *cr;
  PangoLayout *layout;
  PangoFontDescription *desc;

  cr = gtk_print_context_get_cairo_context (context);

  /* Draw a red rectangle, as wide as the paper (inside the margins) */
  cairo_set_source_rgb (cr, 1.0, 0, 0);
  cairo_rectangle (cr, 0, 0, gtk_print_context_get_width (context), 50);

  cairo_fill (cr);

  /* Draw some lines */
  cairo_move_to (cr, 20, 10);
  cairo_line_to (cr, 40, 20);
  cairo_arc (cr, 60, 60, 20, 0, M_PI);
  cairo_line_to (cr, 80, 20);

  cairo_set_source_rgb (cr, 0, 0, 0);
  cairo_set_line_width (cr, 5);
  cairo_set_line_cap (cr, CAIRO_LINE_CAP_ROUND);
  cairo_set_line_join (cr, CAIRO_LINE_JOIN_ROUND);

  cairo_stroke (cr);

  /* Draw some text */
  layout = gtk_print_context_create_layout (context);
  pango_layout_set_text (layout, "Hello World! Printing is easy", -1);
  desc = pango_font_description_from_string ("sans 28");
  pango_layout_set_font_description (layout, desc);
  pango_font_description_free (desc);

  cairo_move_to (cr, 30, 20);
  pango_cairo_layout_path (cr, layout);

  /* Font Outline */
  cairo_set_source_rgb (cr, 0.93, 1.0, 0.47);
  cairo_set_line_width (cr, 0.5);
  cairo_stroke_preserve (cr);

  /* Font Fill */
  cairo_set_source_rgb (cr, 0, 0.0, 1.0);
  cairo_fill (cr);

  g_object_unref (layout);
}

Printing support was added in GTK+ 2.10.

Details

GtkPrintContext

typedef struct _GtkPrintContext GtkPrintContext;

gtk_print_context_get_cairo_context ()

cairo_t*            gtk_print_context_get_cairo_context (GtkPrintContext *context);

Obtains the cairo context that is associated with the GtkPrintContext.

context : | a GtkPrintContext
Returns : | the cairo context of context

Since 2.10

gtk_print_context_set_cairo_context ()

void                gtk_print_context_set_cairo_context (GtkPrintContext *context,
                                                         cairo_t *cr,
                                                         double dpi_x,
                                                         double dpi_y);

Sets a new cairo context on a print context.

This function is intended to be used when implementing an internal print preview, it is not needed for printing, since GTK+ itself creates a suitable cairo context in that case.

context : | a GtkPrintContext
cr : | the cairo context
dpi_x : | the horizontal resolution to use with cr
dpi_y : | the vertical resolution to use with cr

Since 2.10

gtk_print_context_get_page_setup ()

GtkPageSetup*       gtk_print_context_get_page_setup    (GtkPrintContext *context);

Obtains the GtkPageSetup that determines the page dimensions of the GtkPrintContext.

context : | a GtkPrintContext
Returns : | the page setup of context

Since 2.10

gtk_print_context_get_width ()

gdouble             gtk_print_context_get_width         (GtkPrintContext *context);

Obtains the width of the GtkPrintContext, in pixels.

context : | a GtkPrintContext
Returns : | the width of context

Since 2.10

gtk_print_context_get_height ()

gdouble             gtk_print_context_get_height        (GtkPrintContext *context);

Obtains the height of the GtkPrintContext, in pixels.

context : | a GtkPrintContext
Returns : | the height of context

Since 2.10

gtk_print_context_get_dpi_x ()

gdouble             gtk_print_context_get_dpi_x         (GtkPrintContext *context);

Obtains the horizontal resolution of the GtkPrintContext, in dots per inch.

context : | a GtkPrintContext
Returns : | the horizontal resolution of context

Since 2.10

gtk_print_context_get_dpi_y ()

gdouble             gtk_print_context_get_dpi_y         (GtkPrintContext *context);

Obtains the vertical resolution of the GtkPrintContext, in dots per inch.

context : | a GtkPrintContext
Returns : | the vertical resolution of context

Since 2.10

gtk_print_context_get_pango_fontmap ()

PangoFontMap*       gtk_print_context_get_pango_fontmap (GtkPrintContext *context);

Returns a PangoFontMap that is suitable for use with the GtkPrintContext.

context : | a GtkPrintContext
Returns : | the font map of context

Since 2.10

gtk_print_context_create_pango_context ()

PangoContext*       gtk_print_context_create_pango_context
                                                        (GtkPrintContext *context);

Creates a new PangoContext that can be used with the GtkPrintContext.

context : | a GtkPrintContext
Returns : | a new Pango context for context

Since 2.10

gtk_print_context_create_pango_layout ()

PangoLayout*        gtk_print_context_create_pango_layout
                                                        (GtkPrintContext *context);

Creates a new PangoLayout that is suitable for use with the GtkPrintContext.

context : | a GtkPrintContext
Returns : | a new Pango layout for context

Since 2.10


GtkPrinter

GtkPrinter — Represents a printer

Synopsis

#include <gtk/gtk.h>

                    GtkPrinter;
                    GtkPrintBackend;
GtkPrinter*         gtk_printer_new                     (const gchar *name,
                                                         GtkPrintBackend *backend,
                                                         gboolean virtual_);
GtkPrintBackend*    gtk_printer_get_backend             (GtkPrinter *printer);
const gchar*        gtk_printer_get_name                (GtkPrinter *printer);
const gchar*        gtk_printer_get_state_message       (GtkPrinter *printer);
const gchar*        gtk_printer_get_description         (GtkPrinter *printer);
const gchar*        gtk_printer_get_location            (GtkPrinter *printer);
const gchar*        gtk_printer_get_icon_name           (GtkPrinter *printer);
gint                gtk_printer_get_job_count           (GtkPrinter *printer);
gboolean            gtk_printer_is_active               (GtkPrinter *printer);
gboolean            gtk_printer_is_virtual              (GtkPrinter *printer);
gboolean            gtk_printer_is_default              (GtkPrinter *printer);
gboolean            gtk_printer_accepts_ps              (GtkPrinter *printer);
gboolean            gtk_printer_accepts_pdf             (GtkPrinter *printer);
gint                gtk_printer_compare                 (GtkPrinter *a,
                                                         GtkPrinter *b);
gboolean            (*GtkPrinterFunc)                   (GtkPrinter *printer,
                                                         gpointer data);
void                gtk_enumerate_printers              (GtkPrinterFunc func,
                                                         gpointer data,
                                                         GDestroyNotify destroy,
                                                         gboolean wait);

Object Hierarchy

  GObject
   +----GtkPrinter

  GObject
   +----GtkPrintBackend

Properties

  "accepts-pdf"              gboolean              : Read / Write / Construct Only
  "accepts-ps"               gboolean              : Read / Write / Construct Only
  "backend"                  GtkPrintBackend       : Read / Write / Construct Only
  "icon-name"                gchararray            : Read
  "is-virtual"               gboolean              : Read / Write / Construct Only
  "job-count"                gint                  : Read
  "location"                 gchararray            : Read
  "name"                     gchararray            : Read / Write / Construct Only
  "state-message"            gchararray            : Read

Signals

  "details-acquired"                               : Run Last

Description

A GtkPrinter object represents a printer. You only need to deal directly with printers if you use the non-portable GtkPrintUnixDialog API.

A GtkPrinter allows to get status information about the printer, such as its description, its location, the number of queued jobs, etc. Most importantly, a GtkPrinter object can be used to create a GtkPrintJob object, which lets you print to the printer.

Printing support was added in GTK+ 2.10.

Details

GtkPrinter

typedef struct _GtkPrinter GtkPrinter;

GtkPrintBackend

typedef struct _GtkPrintBackend GtkPrintBackend;

gtk_printer_new ()

GtkPrinter*         gtk_printer_new                     (const gchar *name,
                                                         GtkPrintBackend *backend,
                                                         gboolean virtual_);

Creates a new GtkPrinter.

name : | the name of the printer
backend : | a GtkPrintBackend
virtual_ : | whether the printer is virtual
Returns : | a new GtkPrinter

Since 2.10

gtk_printer_get_backend ()

GtkPrintBackend*    gtk_printer_get_backend             (GtkPrinter *printer);

Returns the backend of the printer.

printer : | a GtkPrinter
Returns : | the backend of printer

Since 2.10

gtk_printer_get_name ()

const gchar*        gtk_printer_get_name                (GtkPrinter *printer);

Returns the name of the printer.

printer : | a GtkPrinter
Returns : | the name of printer

Since 2.10

gtk_printer_get_state_message ()

const gchar*        gtk_printer_get_state_message       (GtkPrinter *printer);

Returns the state message describing the current state of the printer.

printer : | a GtkPrinter
Returns : | the state message of printer

Since 2.10

gtk_printer_get_description ()

const gchar*        gtk_printer_get_description         (GtkPrinter *printer);

Gets the description of the printer.

printer : | a GtkPrinter
Returns : | the description of printer

Since 2.10

gtk_printer_get_location ()

const gchar*        gtk_printer_get_location            (GtkPrinter *printer);

Returns a description of the location of the printer.

printer : | a GtkPrinter
Returns : | the location of printer

Since 2.10

gtk_printer_get_icon_name ()

const gchar*        gtk_printer_get_icon_name           (GtkPrinter *printer);

Gets the name of the icon to use for the printer.

printer : | a GtkPrinter
Returns : | the icon name for printer

Since 2.10

gtk_printer_get_job_count ()

gint                gtk_printer_get_job_count           (GtkPrinter *printer);

Gets the number of jobs currently queued on the printer.

printer : | a GtkPrinter
Returns : | the number of jobs on printer

Since 2.10

gtk_printer_is_active ()

gboolean            gtk_printer_is_active               (GtkPrinter *printer);

Returns whether the printer is currently active (i.e. accepts new jobs).

printer : | a GtkPrinter
Returns : | TRUE if printer is active

Since 2.10

gtk_printer_is_virtual ()

gboolean            gtk_printer_is_virtual              (GtkPrinter *printer);

Returns whether the printer is virtual (i.e. does not represent actual printer hardware, but something like a CUPS class).

printer : | a GtkPrinter
Returns : | TRUE if printer is virtual

Since 2.10

gtk_printer_is_default ()

gboolean            gtk_printer_is_default              (GtkPrinter *printer);

Returns whether the printer is the default printer.

printer : | a GtkPrinter
Returns : | TRUE if printer is the default

Since 2.10

gtk_printer_accepts_ps ()

gboolean            gtk_printer_accepts_ps              (GtkPrinter *printer);

Returns whether the printer accepts input in PostScript format.

printer : | a GtkPrinter
Returns : | TRUE if printer accepts PostScript

Since 2.10

gtk_printer_accepts_pdf ()

gboolean            gtk_printer_accepts_pdf             (GtkPrinter *printer);

Returns whether the printer accepts input in PDF format.

printer : | a GtkPrinter
Returns : | TRUE if printer accepts PDF

Since 2.10

gtk_printer_compare ()

gint                gtk_printer_compare                 (GtkPrinter *a,
                                                         GtkPrinter *b);

Compares two printers.

a : | a GtkPrinter
b : | another GtkPrinter
Returns : | 0 if the printer match, a negative value if a < b, or a positive value if a > b

Since 2.10

GtkPrinterFunc ()

gboolean            (*GtkPrinterFunc)                   (GtkPrinter *printer,
                                                         gpointer data);

The type of function passed to gtk_enumerate_printers(). Note that you need to ref printer, if you want to keep a reference to it after the function has returned.

printer : | a GtkPrinter
data : | user data passed to gtk_enumerate_printers()
Returns : | TRUE to stop the enumeration, FALSE to continue

gtk_enumerate_printers ()

void                gtk_enumerate_printers              (GtkPrinterFunc func,
                                                         gpointer data,
                                                         GDestroyNotify destroy,
                                                         gboolean wait);

Calls a function for all GtkPrinters. If func returns TRUE, the enumeration is stopped.

func : | a function to call for each printer
data : | user data to pass to func
destroy : | function to call if data is no longer needed
wait : | if TRUE, wait in a recursive mainloop until all printers are enumerated; otherwise return early

Since 2.10

Property Details

The "accepts-pdf" property

  "accepts-pdf"              gboolean              : Read / Write / Construct Only

TRUE if this printer can accept PDF.

Default value: TRUE

The "accepts-ps" property

  "accepts-ps"               gboolean              : Read / Write / Construct Only

TRUE if this printer can accept PostScript.

Default value: TRUE

The "backend" property

  "backend"                  GtkPrintBackend       : Read / Write / Construct Only

Backend for the printer.

The "icon-name" property

  "icon-name"                gchararray            : Read

The icon name to use for the printer.

Default value: NULL

The "is-virtual" property

  "is-virtual"               gboolean              : Read / Write / Construct Only

FALSE if this represents a real hardware printer.

Default value: FALSE

The "job-count" property

  "job-count"                gint                  : Read

Number of jobs queued in the printer.

Allowed values: >= 0

Default value: 0

The "location" property

  "location"                 gchararray            : Read

The location of the printer.

Default value: NULL

The "name" property

  "name"                     gchararray            : Read / Write / Construct Only

Name of the printer.

Default value: NULL

The "state-message" property

  "state-message"            gchararray            : Read

String giving the current state of the printer.

Default value: NULL

Signal Details

The "details-acquired" signal

void                user_function                      (GtkPrinter *printer,
                                                        gboolean    success,
                                                        gpointer    user_data)      : Run Last

Gets emitted in response to a request for detailed information about a printer from the print backend. The success parameter indicates if the information was actually obtained.

printer : | the GtkPrinter on which the signal is emitted
success : | TRUE if the details were successfully acquired
user_data : | user data set when the signal handler was connected.

Since 2.10


GtkPrintJob

GtkPrintJob — Represents a print job

Synopsis

#include <gtk/gtk.h>

                    GtkPrintJob;
void                (*GtkPrintJobCompleteFunc)          (GtkPrintJob *print_job,
                                                         gpointer user_data,
                                                         GError *error);
GtkPrintJob*        gtk_print_job_new                   (const gchar *title,
                                                         GtkPrinter *printer,
                                                         GtkPrintSettings *settings,
                                                         GtkPageSetup *page_setup);
GtkPrintSettings*   gtk_print_job_get_settings          (GtkPrintJob *job);
GtkPrinter*         gtk_print_job_get_printer           (GtkPrintJob *job);
const gchar*        gtk_print_job_get_title             (GtkPrintJob *job);
GtkPrintStatus      gtk_print_job_get_status            (GtkPrintJob *job);
gboolean            gtk_print_job_set_source_file       (GtkPrintJob *job,
                                                         const gchar *filename,
                                                         GError **error);
cairo_surface_t*    gtk_print_job_get_surface           (GtkPrintJob *job,
                                                         GError **error);
void                gtk_print_job_send                  (GtkPrintJob *job,
                                                         GtkPrintJobCompleteFunc callback,
                                                         gpointer user_data,
                                                         GDestroyNotify dnotify);
void                gtk_print_job_set_track_print_status
                                                        (GtkPrintJob *job,
                                                         gboolean track_status);
gboolean            gtk_print_job_get_track_print_status
                                                        (GtkPrintJob *job);

Object Hierarchy

  GObject
   +----GtkPrintJob

Properties

  "page-setup"               GtkPageSetup          : Read / Write / Construct Only
  "printer"                  GtkPrinter            : Read / Write / Construct Only
  "settings"                 GtkPrintSettings      : Read / Write / Construct Only
  "title"                    gchararray            : Read / Write / Construct Only
  "track-print-status"       gboolean              : Read / Write

Signals

  "status-changed"                                 : Run Last

Description

A GtkPrintJob object represents a job that is sent to a printer. You only need to deal directly with print jobs if you use the non-portable GtkPrintUnixDialog API.

Use gtk_print_job_get_surface() to obtain the cairo surface onto which the pages must be drawn. Use gtk_print_job_send() to send the finished job to the printer. If you don't use cairo GtkPrintJob also supports printing of manually generated postscript, via gtk_print_job_set_source_file().

Printing support was added in GTK+ 2.10.

Details

GtkPrintJob

typedef struct _GtkPrintJob GtkPrintJob;

The GtkPrintJob struct contains only private members and should not be directly accessed.

GtkPrintJobCompleteFunc ()

void                (*GtkPrintJobCompleteFunc)          (GtkPrintJob *print_job,
                                                         gpointer user_data,
                                                         GError *error);

The type of callback that is passed to gtk_print_job_send(). It is called when the print job has been completely sent.

print_job : | the GtkPrintJob
user_data : | user data that has been passed to gtk_print_job_send()
error : | a GError that contains error information if the sending of the print job failed, otherwise NULL

gtk_print_job_new ()

GtkPrintJob*        gtk_print_job_new                   (const gchar *title,
                                                         GtkPrinter *printer,
                                                         GtkPrintSettings *settings,
                                                         GtkPageSetup *page_setup);

Creates a new GtkPrintJob.

title : | the job title
printer : | a GtkPrinter
settings : | a GtkPrintSettings
page_setup : | a GtkPageSetup
Returns : | a new GtkPrintJob

Since 2.10

gtk_print_job_get_settings ()

GtkPrintSettings*   gtk_print_job_get_settings          (GtkPrintJob *job);

Gets the GtkPrintSettings of the print job.

job : | a GtkPrintJob
Returns : | the settings of job

Since 2.10

gtk_print_job_get_printer ()

GtkPrinter*         gtk_print_job_get_printer           (GtkPrintJob *job);

Gets the GtkPrinter of the print job.

job : | a GtkPrintJob
Returns : | the printer of job

Since 2.10

gtk_print_job_get_title ()

const gchar*        gtk_print_job_get_title             (GtkPrintJob *job);

Gets the job title.

job : | a GtkPrintJob
Returns : | the title of job

Since 2.10

gtk_print_job_get_status ()

GtkPrintStatus      gtk_print_job_get_status            (GtkPrintJob *job);

Gets the status of the print job.

job : | a GtkPrintJob
Returns : | the status of job

Since 2.10

gtk_print_job_set_source_file ()

gboolean            gtk_print_job_set_source_file       (GtkPrintJob *job,
                                                         const gchar *filename,
                                                         GError **error);

Make the GtkPrintJob send an existing document to the printing system. The file can be in any format understood by the platforms printing system (typically PostScript, but on many platforms PDF may work too). See gtk_printer_accepts_pdf() and gtk_printer_accepts_ps().

job : | a GtkPrintJob
filename : | the file to be printed
error : | return location for errors
Returns : | FALSE if an error occurred

Since 2.10

gtk_print_job_get_surface ()

cairo_surface_t*    gtk_print_job_get_surface           (GtkPrintJob *job,
                                                         GError **error);

Gets a cairo surface onto which the pages of the print job should be rendered.

job : | a GtkPrintJob
error : | return location for errors, or NULL
Returns : | the cairo surface of job

Since 2.10

gtk_print_job_send ()

void                gtk_print_job_send                  (GtkPrintJob *job,
                                                         GtkPrintJobCompleteFunc callback,
                                                         gpointer user_data,
                                                         GDestroyNotify dnotify);

Sends the print job off to the printer.

job : | a GtkPrintJob
callback : | function to call when the job completes or an error occurs
user_data : | user data that gets passed to callback
dnotify : | destroy notify for user_data

Since 2.10

gtk_print_job_set_track_print_status ()

void                gtk_print_job_set_track_print_status
                                                        (GtkPrintJob *job,
                                                         gboolean track_status);

If track_status is TRUE, the print job will try to continue report on the status of the print job in the printer queues and printer. This can allow your application to show things like "out of paper" issues, and when the print job actually reaches the printer.

This function is often implemented using some form of polling, so it should not be enabled unless needed.

job : | a GtkPrintJob
track_status : | TRUE to track status after printing

Since 2.10

gtk_print_job_get_track_print_status ()

gboolean            gtk_print_job_get_track_print_status
                                                        (GtkPrintJob *job);

Returns wheter jobs will be tracked after printing. For details, see gtk_print_job_set_track_print_status().

job : | a GtkPrintJob
Returns : | TRUE if print job status will be reported after printing

Since 2.10

Property Details

The "page-setup" property

  "page-setup"               GtkPageSetup          : Read / Write / Construct Only

Page Setup.

The "printer" property

  "printer"                  GtkPrinter            : Read / Write / Construct Only

Printer to print the job to.

The "settings" property

  "settings"                 GtkPrintSettings      : Read / Write / Construct Only

Printer settings.

The "title" property

  "title"                    gchararray            : Read / Write / Construct Only

Title of the print job.

Default value: NULL

The "track-print-status" property

  "track-print-status"       gboolean              : Read / Write

TRUE if the print job will continue to emit status-changed signals after the print data has been sent to the printer or print server.

Default value: FALSE

Signal Details

The "status-changed" signal

void                user_function                      (GtkPrintJob *job,
                                                        gpointer     user_data)      : Run Last

Gets emitted when the status of a job changes. The signal handler can use gtk_print_job_get_status() to obtain the new status.

job : | the GtkPrintJob object on which the signal was emitted
user_data : | user data set when the signal handler was connected.

Since 2.10


GtkPrintSettings

GtkPrintSettings — Stores print settings

Synopsis

#include <gtk/gtk.h>

                    GtkPrintSettings;
void                (*GtkPrintSettingsFunc)             (const gchar *key,
                                                         const gchar *value,
                                                         gpointer user_data);
GtkPrintSettings*   gtk_print_settings_new              (void);
GtkPrintSettings*   gtk_print_settings_copy             (GtkPrintSettings *other);
gboolean            gtk_print_settings_has_key          (GtkPrintSettings *settings,
                                                         const gchar *key);
const gchar*        gtk_print_settings_get              (GtkPrintSettings *settings,
                                                         const gchar *key);
void                gtk_print_settings_set              (GtkPrintSettings *settings,
                                                         const gchar *key,
                                                         const gchar *value);
void                gtk_print_settings_unset            (GtkPrintSettings *settings,
                                                         const gchar *key);
void                gtk_print_settings_foreach          (GtkPrintSettings *settings,
                                                         GtkPrintSettingsFunc func,
                                                         gpointer user_data);
gboolean            gtk_print_settings_get_bool         (GtkPrintSettings *settings,
                                                         const gchar *key);
void                gtk_print_settings_set_bool         (GtkPrintSettings *settings,
                                                         const gchar *key,
                                                         gboolean value);
gdouble             gtk_print_settings_get_double       (GtkPrintSettings *settings,
                                                         const gchar *key);
gdouble             gtk_print_settings_get_double_with_default
                                                        (GtkPrintSettings *settings,
                                                         const gchar *key,
                                                         gdouble def);
void                gtk_print_settings_set_double       (GtkPrintSettings *settings,
                                                         const gchar *key,
                                                         gdouble value);
gdouble             gtk_print_settings_get_length       (GtkPrintSettings *settings,
                                                         const gchar *key,
                                                         GtkUnit unit);
void                gtk_print_settings_set_length       (GtkPrintSettings *settings,
                                                         const gchar *key,
                                                         gdouble value,
                                                         GtkUnit unit);
gint                gtk_print_settings_get_int          (GtkPrintSettings *settings,
                                                         const gchar *key);
gint                gtk_print_settings_get_int_with_default
                                                        (GtkPrintSettings *settings,
                                                         const gchar *key,
                                                         gint def);
void                gtk_print_settings_set_int          (GtkPrintSettings *settings,
                                                         const gchar *key,
                                                         gint value);
#define             GTK_PRINT_SETTINGS_PRINTER
const gchar*        gtk_print_settings_get_printer      (GtkPrintSettings *settings);
void                gtk_print_settings_set_printer      (GtkPrintSettings *settings,
                                                         const gchar *printer);
enum                GtkPageOrientation;
#define             GTK_PRINT_SETTINGS_ORIENTATION
GtkPageOrientation  gtk_print_settings_get_orientation  (GtkPrintSettings *settings);
void                gtk_print_settings_set_orientation  (GtkPrintSettings *settings,
                                                         GtkPageOrientation orientation);
#define             GTK_PRINT_SETTINGS_PAPER_FORMAT
GtkPaperSize*       gtk_print_settings_get_paper_size   (GtkPrintSettings *settings);
void                gtk_print_settings_set_paper_size   (GtkPrintSettings *settings,
                                                         GtkPaperSize *paper_size);
#define             GTK_PRINT_SETTINGS_PAPER_WIDTH
gdouble             gtk_print_settings_get_paper_width  (GtkPrintSettings *settings,
                                                         GtkUnit unit);
void                gtk_print_settings_set_paper_width  (GtkPrintSettings *settings,
                                                         gdouble width,
                                                         GtkUnit unit);
#define             GTK_PRINT_SETTINGS_PAPER_HEIGHT
gdouble             gtk_print_settings_get_paper_height (GtkPrintSettings *settings,
                                                         GtkUnit unit);
void                gtk_print_settings_set_paper_height (GtkPrintSettings *settings,
                                                         gdouble height,
                                                         GtkUnit unit);
#define             GTK_PRINT_SETTINGS_USE_COLOR
gboolean            gtk_print_settings_get_use_color    (GtkPrintSettings *settings);
void                gtk_print_settings_set_use_color    (GtkPrintSettings *settings,
                                                         gboolean use_color);
#define             GTK_PRINT_SETTINGS_COLLATE
gboolean            gtk_print_settings_get_collate      (GtkPrintSettings *settings);
void                gtk_print_settings_set_collate      (GtkPrintSettings *settings,
                                                         gboolean collate);
#define             GTK_PRINT_SETTINGS_REVERSE
gboolean            gtk_print_settings_get_reverse      (GtkPrintSettings *settings);
void                gtk_print_settings_set_reverse      (GtkPrintSettings *settings,
                                                         gboolean reverse);
enum                GtkPrintDuplex;
#define             GTK_PRINT_SETTINGS_DUPLEX
GtkPrintDuplex      gtk_print_settings_get_duplex       (GtkPrintSettings *settings);
void                gtk_print_settings_set_duplex       (GtkPrintSettings *settings,
                                                         GtkPrintDuplex duplex);
enum                GtkPrintQuality;
#define             GTK_PRINT_SETTINGS_QUALITY
GtkPrintQuality     gtk_print_settings_get_quality      (GtkPrintSettings *settings);
void                gtk_print_settings_set_quality      (GtkPrintSettings *settings,
                                                         GtkPrintQuality quality);
#define             GTK_PRINT_SETTINGS_N_COPIES
gint                gtk_print_settings_get_n_copies     (GtkPrintSettings *settings);
void                gtk_print_settings_set_n_copies     (GtkPrintSettings *settings,
                                                         gint num_copies);
#define             GTK_PRINT_SETTINGS_NUMBER_UP
gint                gtk_print_settings_get_number_up    (GtkPrintSettings *settings);
void                gtk_print_settings_set_number_up    (GtkPrintSettings *settings,
                                                         gint number_up);
#define             GTK_PRINT_SETTINGS_RESOLUTION
gint                gtk_print_settings_get_resolution   (GtkPrintSettings *settings);
void                gtk_print_settings_set_resolution   (GtkPrintSettings *settings,
                                                         gint resolution);
#define             GTK_PRINT_SETTINGS_SCALE
gdouble             gtk_print_settings_get_scale        (GtkPrintSettings *settings);
void                gtk_print_settings_set_scale        (GtkPrintSettings *settings,
                                                         gdouble scale);
enum                GtkPrintPages;
#define             GTK_PRINT_SETTINGS_PRINT_PAGES
GtkPrintPages       gtk_print_settings_get_print_pages  (GtkPrintSettings *settings);
void                gtk_print_settings_set_print_pages  (GtkPrintSettings *settings,
                                                         GtkPrintPages pages);
                    GtkPageRange;
#define             GTK_PRINT_SETTINGS_PAGE_RANGES
GtkPageRange*       gtk_print_settings_get_page_ranges  (GtkPrintSettings *settings,
                                                         gint *num_ranges);
void                gtk_print_settings_set_page_ranges  (GtkPrintSettings *settings,
                                                         GtkPageRange *page_ranges,
                                                         gint num_ranges);
enum                GtkPageSet;
#define             GTK_PRINT_SETTINGS_PAGE_SET
GtkPageSet          gtk_print_settings_get_page_set     (GtkPrintSettings *settings);
void                gtk_print_settings_set_page_set     (GtkPrintSettings *settings,
                                                         GtkPageSet page_set);
#define             GTK_PRINT_SETTINGS_DEFAULT_SOURCE
const gchar*        gtk_print_settings_get_default_source
                                                        (GtkPrintSettings *settings);
void                gtk_print_settings_set_default_source
                                                        (GtkPrintSettings *settings,
                                                         const gchar *default_source);
#define             GTK_PRINT_SETTINGS_MEDIA_TYPE
const gchar*        gtk_print_settings_get_media_type   (GtkPrintSettings *settings);
void                gtk_print_settings_set_media_type   (GtkPrintSettings *settings,
                                                         const gchar *media_type);
#define             GTK_PRINT_SETTINGS_DITHER
const gchar*        gtk_print_settings_get_dither       (GtkPrintSettings *settings);
void                gtk_print_settings_set_dither       (GtkPrintSettings *settings,
                                                         const gchar *dither);
#define             GTK_PRINT_SETTINGS_FINISHINGS
const gchar*        gtk_print_settings_get_finishings   (GtkPrintSettings *settings);
void                gtk_print_settings_set_finishings   (GtkPrintSettings *settings,
                                                         const gchar *finishings);
#define             GTK_PRINT_SETTINGS_OUTPUT_BIN
const gchar*        gtk_print_settings_get_output_bin   (GtkPrintSettings *settings);
void                gtk_print_settings_set_output_bin   (GtkPrintSettings *settings,
                                                         const gchar *output_bin);
#define             GTK_PRINT_SETTINGS_OUTPUT_FILE_FORMAT
#define             GTK_PRINT_SETTINGS_OUTPUT_URI
#define             GTK_PRINT_SETTINGS_WIN32_DRIVER_EXTRA
#define             GTK_PRINT_SETTINGS_WIN32_DRIVER_VERSION

Object Hierarchy

  GObject
   +----GtkPrintSettings

Description

A GtkPrintSettings object represents the settings of a print dialog in a system-independent way. The main use for this object is that once you've printed you can get a settings object that represents the settings the user chose, and the next time you print you can pass that object in so that the user doesn't have to re-set all his settings.

Its also possible to enumerate the settings so that you can easily save the settings for the next time your app runs, or even store them in a document. The predefined keys try to use shared values as much as possible so that moving such a document between systems still works.

Printing support was added in GTK+ 2.10.

Details

GtkPrintSettings

typedef struct _GtkPrintSettings GtkPrintSettings;

GtkPrintSettingsFunc ()

void                (*GtkPrintSettingsFunc)             (const gchar *key,
                                                         const gchar *value,
                                                         gpointer user_data);

key :
value :
user_data :

gtk_print_settings_new ()

GtkPrintSettings*   gtk_print_settings_new              (void);

Creates a new GtkPrintSettings object.

Returns : a new GtkPrintSettings object

Since 2.10

gtk_print_settings_copy ()

GtkPrintSettings*   gtk_print_settings_copy             (GtkPrintSettings *other);

Copies a GtkPrintSettings object.

other : | a GtkPrintSettings
Returns : | a newly allocated copy of other

Since 2.10

gtk_print_settings_has_key ()

gboolean            gtk_print_settings_has_key          (GtkPrintSettings *settings,
                                                         const gchar *key);

Returns TRUE, if a value is associated with key.

settings : | a GtkPrintSettings
key : | a key
Returns : | TRUE, if key has a value

Since 2.10

gtk_print_settings_get ()

const gchar*        gtk_print_settings_get              (GtkPrintSettings *settings,
                                                         const gchar *key);

Looks up the string value associated with key.

settings : | a GtkPrintSettings
key : | a key
Returns : | the string value for key

Since 2.10

gtk_print_settings_set ()

void                gtk_print_settings_set              (GtkPrintSettings *settings,
                                                         const gchar *key,
                                                         const gchar *value);

Associates value with key.

settings : | a GtkPrintSettings
key : | a key
value : | a string value, or NULL

Since 2.10

gtk_print_settings_unset ()

void                gtk_print_settings_unset            (GtkPrintSettings *settings,
                                                         const gchar *key);

Removes any value associated with key. This has the same effect as setting the value to NULL.

settings : | a GtkPrintSettings
key : | a key

Since 2.10

gtk_print_settings_foreach ()

void                gtk_print_settings_foreach          (GtkPrintSettings *settings,
                                                         GtkPrintSettingsFunc func,
                                                         gpointer user_data);

Calls func for each key-value pair of settings.

settings : | a GtkPrintSettings
func : | the function to call
user_data : | user data for func

Since 2.10

gtk_print_settings_get_bool ()

gboolean            gtk_print_settings_get_bool         (GtkPrintSettings *settings,
                                                         const gchar *key);

Returns the boolean represented by the value that is associated with key.

The string "true" represents TRUE, any other string FALSE.

settings : | a GtkPrintSettings
key : | a key
Returns : | TRUE, if key maps to a true value.

Since 2.10

gtk_print_settings_set_bool ()

void                gtk_print_settings_set_bool         (GtkPrintSettings *settings,
                                                         const gchar *key,
                                                         gboolean value);

Sets key to a boolean value.

settings : | a GtkPrintSettings
key : | a key
value : | a boolean

Since 2.10

gtk_print_settings_get_double ()

gdouble             gtk_print_settings_get_double       (GtkPrintSettings *settings,
                                                         const gchar *key);

Returns the double value associated with key, or 0.

settings : | a GtkPrintSettings
key : | a key
Returns : | the double value of key

Since 2.10

gtk_print_settings_get_double_with_default ()

gdouble             gtk_print_settings_get_double_with_default
                                                        (GtkPrintSettings *settings,
                                                         const gchar *key,
                                                         gdouble def);

Returns the floating point number represented by the value that is associated with key, or default_val if the value does not represent a floating point number.

Floating point numbers are parsed with g_ascii_strtod().

settings : | a GtkPrintSettings
key : | a key
def : | the default value
Returns : | the floating point number associated with key

Since 2.10

gtk_print_settings_set_double ()

void                gtk_print_settings_set_double       (GtkPrintSettings *settings,
                                                         const gchar *key,
                                                         gdouble value);

Sets key to a double value.

settings : | a GtkPrintSettings
key : | a key
value : | a double value

Since 2.10

gtk_print_settings_get_length ()

gdouble             gtk_print_settings_get_length       (GtkPrintSettings *settings,
                                                         const gchar *key,
                                                         GtkUnit unit);

Returns the value associated with key, interpreted as a length. The returned value is converted to units.

settings : | a GtkPrintSettings
key : | a key
unit : | the unit of the return value
Returns : | the length value of key, converted to unit

Since 2.10

gtk_print_settings_set_length ()

void                gtk_print_settings_set_length       (GtkPrintSettings *settings,
                                                         const gchar *key,
                                                         gdouble value,
                                                         GtkUnit unit);

Associates a length in units of unit with key.

settings : | a GtkPrintSettings
key : | a key
value : | a length
unit : | the unit of length

Since 2.10

gtk_print_settings_get_int ()

gint                gtk_print_settings_get_int          (GtkPrintSettings *settings,
                                                         const gchar *key);

Returns the integer value of key, or 0.

settings : | a GtkPrintSettings
key : | a key
Returns : | the integer value of key

Since 2.10

gtk_print_settings_get_int_with_default ()

gint                gtk_print_settings_get_int_with_default
                                                        (GtkPrintSettings *settings,
                                                         const gchar *key,
                                                         gint def);

Returns the value of key, interpreted as an integer, or the default value.

settings : | a GtkPrintSettings
key : | a key
def : | the default value
Returns : | the integer value of key

Since 2.10

gtk_print_settings_set_int ()

void                gtk_print_settings_set_int          (GtkPrintSettings *settings,
                                                         const gchar *key,
                                                         gint value);

Sets key to an integer value.

settings : | a GtkPrintSettings
key : | a key
value : | an integer

Since 2.10

GTK_PRINT_SETTINGS_PRINTER

#define GTK_PRINT_SETTINGS_PRINTER        "printer"

gtk_print_settings_get_printer ()

const gchar*        gtk_print_settings_get_printer      (GtkPrintSettings *settings);

Convenience function to obtain the value of GTK_PRINT_SETTINGS_PRINTER.

settings : | a GtkPrintSettings
Returns : | the printer name

Since 2.10

gtk_print_settings_set_printer ()

void                gtk_print_settings_set_printer      (GtkPrintSettings *settings,
                                                         const gchar *printer);

Convenience function to set GTK_PRINT_SETTINGS_PRINTER to printer.

settings : | a GtkPrintSettings
printer : | the printer name

Since 2.10

enum GtkPageOrientation

typedef enum {
  GTK_PAGE_ORIENTATION_PORTRAIT,
  GTK_PAGE_ORIENTATION_LANDSCAPE,
  GTK_PAGE_ORIENTATION_REVERSE_PORTRAIT,
  GTK_PAGE_ORIENTATION_REVERSE_LANDSCAPE
} GtkPageOrientation;

GTK_PRINT_SETTINGS_ORIENTATION

#define GTK_PRINT_SETTINGS_ORIENTATION    "orientation"

gtk_print_settings_get_orientation ()

GtkPageOrientation  gtk_print_settings_get_orientation  (GtkPrintSettings *settings);

Get the value of GTK_PRINT_SETTINGS_ORIENTATION, converted to a GtkPageOrientation.

settings : | a GtkPrintSettings
Returns : | the orientation

Since 2.10

gtk_print_settings_set_orientation ()

void                gtk_print_settings_set_orientation  (GtkPrintSettings *settings,
                                                         GtkPageOrientation orientation);

Sets the value of GTK_PRINT_SETTINGS_ORIENTATION.

settings : | a GtkPrintSettings
orientation : | a page orientation

Since 2.10

GTK_PRINT_SETTINGS_PAPER_FORMAT

#define GTK_PRINT_SETTINGS_PAPER_FORMAT   "paper-format"

gtk_print_settings_get_paper_size ()

GtkPaperSize*       gtk_print_settings_get_paper_size   (GtkPrintSettings *settings);

Gets the value of GTK_PRINT_SETTINGS_PAPER_FORMAT, converted to a GtkPaperSize.

settings : | a GtkPrintSettings
Returns : | the paper size

Since 2.10

gtk_print_settings_set_paper_size ()

void                gtk_print_settings_set_paper_size   (GtkPrintSettings *settings,
                                                         GtkPaperSize *paper_size);

Sets the value of GTK_PRINT_SETTINGS_PAPER_FORMAT, GTK_PRINT_SETTINGS_PAPER_WIDTH and GTK_PRINT_SETTINGS_PAPER_HEIGHT.

settings : | a GtkPrintSettings
paper_size : | a paper size

Since 2.10

GTK_PRINT_SETTINGS_PAPER_WIDTH

#define GTK_PRINT_SETTINGS_PAPER_WIDTH    "paper-width"

gtk_print_settings_get_paper_width ()

gdouble             gtk_print_settings_get_paper_width  (GtkPrintSettings *settings,
                                                         GtkUnit unit);

Gets the value of GTK_PRINT_SETTINGS_PAPER_WIDTH, converted to unit.

settings : | a GtkPrintSettings
unit : | the unit for the return value
Returns : | the paper width, in units of unit

Since 2.10

gtk_print_settings_set_paper_width ()

void                gtk_print_settings_set_paper_width  (GtkPrintSettings *settings,
                                                         gdouble width,
                                                         GtkUnit unit);

Sets the value of GTK_PRINT_SETTINGS_PAPER_WIDTH.

settings : | a GtkPrintSettings
width : | the paper width
unit : | the units of width

Since 2.10

GTK_PRINT_SETTINGS_PAPER_HEIGHT

#define GTK_PRINT_SETTINGS_PAPER_HEIGHT   "paper-height"

gtk_print_settings_get_paper_height ()

gdouble             gtk_print_settings_get_paper_height (GtkPrintSettings *settings,
                                                         GtkUnit unit);

Gets the value of GTK_PRINT_SETTINGS_PAPER_HEIGHT, converted to unit.

settings : | a GtkPrintSettings
unit : | the unit for the return value
Returns : | the paper height, in units of unit

Since 2.10

gtk_print_settings_set_paper_height ()

void                gtk_print_settings_set_paper_height (GtkPrintSettings *settings,
                                                         gdouble height,
                                                         GtkUnit unit);

Sets the value of GTK_PRINT_SETTINGS_PAPER_HEIGHT.

settings : | a GtkPrintSettings
height : | the paper height
unit : | the units of height

Since 2.10

GTK_PRINT_SETTINGS_USE_COLOR

#define GTK_PRINT_SETTINGS_USE_COLOR      "use-color"

gtk_print_settings_get_use_color ()

gboolean            gtk_print_settings_get_use_color    (GtkPrintSettings *settings);

Gets the value of GTK_PRINT_SETTINGS_USE_COLOR.

settings : | a GtkPrintSettings
Returns : | whether to use color

Since 2.10

gtk_print_settings_set_use_color ()

void                gtk_print_settings_set_use_color    (GtkPrintSettings *settings,
                                                         gboolean use_color);

Sets the value of GTK_PRINT_SETTINGS_USE_COLOR.

settings : | a GtkPrintSettings
use_color : | whether to use color

Since 2.10

GTK_PRINT_SETTINGS_COLLATE

#define GTK_PRINT_SETTINGS_COLLATE        "collate"

gtk_print_settings_get_collate ()

gboolean            gtk_print_settings_get_collate      (GtkPrintSettings *settings);

Gets the value of GTK_PRINT_SETTINGS_COLLATE.

settings : | a GtkPrintSettings
Returns : | whether to collate the printed pages

Since 2.10

gtk_print_settings_set_collate ()

void                gtk_print_settings_set_collate      (GtkPrintSettings *settings,
                                                         gboolean collate);

Sets the value of GTK_PRINT_SETTINGS_COLLATE.

settings : | a GtkPrintSettings
collate : | whether to collate the output

Since 2.10

GTK_PRINT_SETTINGS_REVERSE

#define GTK_PRINT_SETTINGS_REVERSE        "reverse"

gtk_print_settings_get_reverse ()

gboolean            gtk_print_settings_get_reverse      (GtkPrintSettings *settings);

Gets the value of GTK_PRINT_SETTINGS_REVERSE.

settings : | a GtkPrintSettings
Returns : | whether to reverse the order of the printed pages

Since 2.10

gtk_print_settings_set_reverse ()

void                gtk_print_settings_set_reverse      (GtkPrintSettings *settings,
                                                         gboolean reverse);

Sets the value of GTK_PRINT_SETTINGS_REVERSE.

settings : | a GtkPrintSettings
reverse : | whether to reverse the output

Since 2.10

enum GtkPrintDuplex

typedef enum {
  GTK_PRINT_DUPLEX_SIMPLEX,
  GTK_PRINT_DUPLEX_HORIZONTAL,
  GTK_PRINT_DUPLEX_VERTICAL
} GtkPrintDuplex;

GTK_PRINT_SETTINGS_DUPLEX

#define GTK_PRINT_SETTINGS_DUPLEX         "duplex"

gtk_print_settings_get_duplex ()

GtkPrintDuplex      gtk_print_settings_get_duplex       (GtkPrintSettings *settings);

Gets the value of GTK_PRINT_SETTINGS_DUPLEX.

settings : | a GtkPrintSettings
Returns : | whether to print the output in duplex.

Since 2.10

gtk_print_settings_set_duplex ()

void                gtk_print_settings_set_duplex       (GtkPrintSettings *settings,
                                                         GtkPrintDuplex duplex);

Sets the value of GTK_PRINT_SETTINGS_DUPLEX.

settings : | a GtkPrintSettings
duplex : | a GtkPrintDuplex value

Since 2.10

enum GtkPrintQuality

typedef enum {
  GTK_PRINT_QUALITY_LOW,
  GTK_PRINT_QUALITY_NORMAL,
  GTK_PRINT_QUALITY_HIGH,
  GTK_PRINT_QUALITY_DRAFT
} GtkPrintQuality;

GTK_PRINT_SETTINGS_QUALITY

#define GTK_PRINT_SETTINGS_QUALITY        "quality"

gtk_print_settings_get_quality ()

GtkPrintQuality     gtk_print_settings_get_quality      (GtkPrintSettings *settings);

Gets the value of GTK_PRINT_SETTINGS_QUALITY.

settings : | a GtkPrintSettings
Returns : | the print quality

Since 2.10

gtk_print_settings_set_quality ()

void                gtk_print_settings_set_quality      (GtkPrintSettings *settings,
                                                         GtkPrintQuality quality);

Sets the value of GTK_PRINT_SETTINGS_QUALITY.

settings : | a GtkPrintSettings
quality : | a GtkPrintQuality value

Since 2.10

GTK_PRINT_SETTINGS_N_COPIES

#define GTK_PRINT_SETTINGS_N_COPIES       "n-copies"

gtk_print_settings_get_n_copies ()

gint                gtk_print_settings_get_n_copies     (GtkPrintSettings *settings);

Gets the value of GTK_PRINT_SETTINGS_N_COPIES.

settings : | a GtkPrintSettings
Returns : | the number of copies to print

Since 2.10

gtk_print_settings_set_n_copies ()

void                gtk_print_settings_set_n_copies     (GtkPrintSettings *settings,
                                                         gint num_copies);

Sets the value of GTK_PRINT_SETTINGS_N_COPIES.

settings : | a GtkPrintSettings
num_copies : | the number of copies

Since 2.10

GTK_PRINT_SETTINGS_NUMBER_UP

#define GTK_PRINT_SETTINGS_NUMBER_UP      "number-up"

gtk_print_settings_get_number_up ()

gint                gtk_print_settings_get_number_up    (GtkPrintSettings *settings);

Gets the value of GTK_PRINT_SETTINGS_NUMBER_UP.

settings : | a GtkPrintSettings
Returns : | the number of pages per sheet

Since 2.10

gtk_print_settings_set_number_up ()

void                gtk_print_settings_set_number_up    (GtkPrintSettings *settings,
                                                         gint number_up);

Sets the value of GTK_PRINT_SETTINGS_NUMBER_UP.

settings : | a GtkPrintSettings
number_up : | the number of pages per sheet

Since 2.10

GTK_PRINT_SETTINGS_RESOLUTION

#define GTK_PRINT_SETTINGS_RESOLUTION     "resolution"

gtk_print_settings_get_resolution ()

gint                gtk_print_settings_get_resolution   (GtkPrintSettings *settings);

Gets the value of GTK_PRINT_SETTINGS_RESOLUTION.

settings : | a GtkPrintSettings
Returns : | the resolution in dpi

Since 2.10

gtk_print_settings_set_resolution ()

void                gtk_print_settings_set_resolution   (GtkPrintSettings *settings,
                                                         gint resolution);

Sets the value of GTK_PRINT_SETTINGS_RESOLUTION.

settings : | a GtkPrintSettings
resolution : | the resolution in dpi

Since 2.10

GTK_PRINT_SETTINGS_SCALE

#define GTK_PRINT_SETTINGS_SCALE          "scale"

gtk_print_settings_get_scale ()

gdouble             gtk_print_settings_get_scale        (GtkPrintSettings *settings);

Gets the value of GTK_PRINT_SETTINGS_SCALE.

settings : | a GtkPrintSettings
Returns : | the scale in percent

Since 2.10

gtk_print_settings_set_scale ()

void                gtk_print_settings_set_scale        (GtkPrintSettings *settings,
                                                         gdouble scale);

Sets the value of GTK_PRINT_SETTINGS_SCALE.

settings : | a GtkPrintSettings
scale : | the scale in percent

Since 2.10

enum GtkPrintPages

typedef enum {
  GTK_PRINT_PAGES_ALL,
  GTK_PRINT_PAGES_CURRENT,
  GTK_PRINT_PAGES_RANGES
} GtkPrintPages;

GTK_PRINT_SETTINGS_PRINT_PAGES

#define GTK_PRINT_SETTINGS_PRINT_PAGES    "print-pages"

gtk_print_settings_get_print_pages ()

GtkPrintPages       gtk_print_settings_get_print_pages  (GtkPrintSettings *settings);

Gets the value of GTK_PRINT_SETTINGS_PRINT_PAGES.

settings : | a GtkPrintSettings
Returns : | which pages to print

Since 2.10

gtk_print_settings_set_print_pages ()

void                gtk_print_settings_set_print_pages  (GtkPrintSettings *settings,
                                                         GtkPrintPages pages);

Sets the value of GTK_PRINT_SETTINGS_PRINT_PAGES.

settings : | a GtkPrintSettings
pages : | a GtkPrintPages value

Since 2.10

GtkPageRange

typedef struct {
  gint start;
  gint end;
} GtkPageRange;

GTK_PRINT_SETTINGS_PAGE_RANGES

#define GTK_PRINT_SETTINGS_PAGE_RANGES    "page-ranges"

gtk_print_settings_get_page_ranges ()

GtkPageRange*       gtk_print_settings_get_page_ranges  (GtkPrintSettings *settings,
                                                         gint *num_ranges);

Gets the value of GTK_PRINT_SETTINGS_PAGE_RANGES.

settings : | a GtkPrintSettings
num_ranges : | return location for the length of the returned array
Returns : | an array of GtkPageRanges. Use g_free() to free the array when it is no longer needed.

Since 2.10

gtk_print_settings_set_page_ranges ()

void                gtk_print_settings_set_page_ranges  (GtkPrintSettings *settings,
                                                         GtkPageRange *page_ranges,
                                                         gint num_ranges);

Sets the value of GTK_PRINT_SETTINGS_PAGE_RANGES.

settings : | a GtkPrintSettings
page_ranges : | an array of GtkPageRanges
num_ranges : | the length of page_ranges

Since 2.10

enum GtkPageSet

typedef enum {
  GTK_PAGE_SET_ALL,
  GTK_PAGE_SET_EVEN,
  GTK_PAGE_SET_ODD
} GtkPageSet;

GTK_PRINT_SETTINGS_PAGE_SET

#define GTK_PRINT_SETTINGS_PAGE_SET       "page-set"

gtk_print_settings_get_page_set ()

GtkPageSet          gtk_print_settings_get_page_set     (GtkPrintSettings *settings);

Gets the value of GTK_PRINT_SETTINGS_PAGE_SET.

settings : | a GtkPrintSettings
Returns : | the set of pages to print

Since 2.10

gtk_print_settings_set_page_set ()

void                gtk_print_settings_set_page_set     (GtkPrintSettings *settings,
                                                         GtkPageSet page_set);

Sets the value of GTK_PRINT_SETTINGS_PAGE_SET.

settings : | a GtkPrintSettings
page_set : | a GtkPageSet value

Since 2.10

GTK_PRINT_SETTINGS_DEFAULT_SOURCE

#define GTK_PRINT_SETTINGS_DEFAULT_SOURCE "default-source"

gtk_print_settings_get_default_source ()

const gchar*        gtk_print_settings_get_default_source
                                                        (GtkPrintSettings *settings);

Gets the value of GTK_PRINT_SETTINGS_DEFAULT_SOURCE.

settings : | a GtkPrintSettings
Returns : | the default source

Since 2.10

gtk_print_settings_set_default_source ()

void                gtk_print_settings_set_default_source
                                                        (GtkPrintSettings *settings,
                                                         const gchar *default_source);

Sets the value of GTK_PRINT_SETTINGS_DEFAULT_SOURCE.

settings : | a GtkPrintSettings
default_source : | the default source

Since 2.10

GTK_PRINT_SETTINGS_MEDIA_TYPE

#define GTK_PRINT_SETTINGS_MEDIA_TYPE     "media-type"

gtk_print_settings_get_media_type ()

const gchar*        gtk_print_settings_get_media_type   (GtkPrintSettings *settings);

Gets the value of GTK_PRINT_SETTINGS_MEDIA_TYPE.

The set of media types is defined in PWG 5101.1-2002 PWG.

settings : | a GtkPrintSettings
Returns : | the media type

Since 2.10

gtk_print_settings_set_media_type ()

void                gtk_print_settings_set_media_type   (GtkPrintSettings *settings,
                                                         const gchar *media_type);

Sets the value of GTK_PRINT_SETTINGS_MEDIA_TYPE.

The set of media types is defined in PWG 5101.1-2002 PWG.

settings : | a GtkPrintSettings
media_type : | the media type

Since 2.10

GTK_PRINT_SETTINGS_DITHER

#define GTK_PRINT_SETTINGS_DITHER         "dither"

gtk_print_settings_get_dither ()

const gchar*        gtk_print_settings_get_dither       (GtkPrintSettings *settings);

Gets the value of GTK_PRINT_SETTINGS_DITHER.

settings : | a GtkPrintSettings
Returns : | the dithering that is used

Since 2.10

gtk_print_settings_set_dither ()

void                gtk_print_settings_set_dither       (GtkPrintSettings *settings,
                                                         const gchar *dither);

Sets the value of GTK_PRINT_SETTINGS_DITHER.

settings : | a GtkPrintSettings
dither : | the dithering that is used

Since 2.10

GTK_PRINT_SETTINGS_FINISHINGS

#define GTK_PRINT_SETTINGS_FINISHINGS     "finishings"

gtk_print_settings_get_finishings ()

const gchar*        gtk_print_settings_get_finishings   (GtkPrintSettings *settings);

Gets the value of GTK_PRINT_SETTINGS_FINISHINGS.

settings : | a GtkPrintSettings
Returns : | the finishings

Since 2.10

gtk_print_settings_set_finishings ()

void                gtk_print_settings_set_finishings   (GtkPrintSettings *settings,
                                                         const gchar *finishings);

Sets the value of GTK_PRINT_SETTINGS_FINISHINGS.

settings : | a GtkPrintSettings
finishings : | the finishings

Since 2.10

GTK_PRINT_SETTINGS_OUTPUT_BIN

#define GTK_PRINT_SETTINGS_OUTPUT_BIN     "output-bin"

gtk_print_settings_get_output_bin ()

const gchar*        gtk_print_settings_get_output_bin   (GtkPrintSettings *settings);

Gets the value of GTK_PRINT_SETTINGS_OUTPUT_BIN.

settings : | a GtkPrintSettings
Returns : | the output bin

Since 2.10

gtk_print_settings_set_output_bin ()

void                gtk_print_settings_set_output_bin   (GtkPrintSettings *settings,
                                                         const gchar *output_bin);

Sets the value of GTK_PRINT_SETTINGS_OUTPUT_BIN.

settings : | a GtkPrintSettings
output_bin : | the output bin

Since 2.10

GTK_PRINT_SETTINGS_OUTPUT_FILE_FORMAT

#define GTK_PRINT_SETTINGS_OUTPUT_FILE_FORMAT  "output-file-format"

The key used by the "Print to file" printer to store the format of the output. The supported values are "PS" and "PDF".

GTK_PRINT_SETTINGS_OUTPUT_URI

#define GTK_PRINT_SETTINGS_OUTPUT_URI          "output-uri"

The key used by the "Print to file" printer to store the URI to which the output should be written. GTK+ itself supports only "file://" URIs.

GTK_PRINT_SETTINGS_WIN32_DRIVER_EXTRA

#define GTK_PRINT_SETTINGS_WIN32_DRIVER_EXTRA   "win32-driver-extra"

GTK_PRINT_SETTINGS_WIN32_DRIVER_VERSION

#define GTK_PRINT_SETTINGS_WIN32_DRIVER_VERSION "win32-driver-version"


GtkPrintUnixDialog

GtkPrintUnixDialog — A print dialog

Synopsis

#include <gtk/gtkprintunixdialog.h>

                    GtkPrintUnixDialog;
GtkWidget*          gtk_print_unix_dialog_new           (const gchar *title,
                                                         GtkWindow *parent);
void                gtk_print_unix_dialog_set_page_setup
                                                        (GtkPrintUnixDialog *dialog,
                                                         GtkPageSetup *page_setup);
GtkPageSetup*       gtk_print_unix_dialog_get_page_setup
                                                        (GtkPrintUnixDialog *dialog);
void                gtk_print_unix_dialog_set_current_page
                                                        (GtkPrintUnixDialog *dialog,
                                                         gint current_page);
gint                gtk_print_unix_dialog_get_current_page
                                                        (GtkPrintUnixDialog *dialog);
void                gtk_print_unix_dialog_set_settings  (GtkPrintUnixDialog *dialog,
                                                         GtkPrintSettings *settings);
GtkPrintSettings*   gtk_print_unix_dialog_get_settings  (GtkPrintUnixDialog *dialog);
GtkPrinter*         gtk_print_unix_dialog_get_selected_printer
                                                        (GtkPrintUnixDialog *dialog);
void                gtk_print_unix_dialog_add_custom_tab
                                                        (GtkPrintUnixDialog *dialog,
                                                         GtkWidget *child,
                                                         GtkWidget *tab_label);
enum                GtkPrintCapabilities;
void                gtk_print_unix_dialog_set_manual_capabilities
                                                        (GtkPrintUnixDialog *dialog,
                                                         GtkPrintCapabilities capabilities);

Object Hierarchy

  GObject
   +----GInitiallyUnowned
         +----GtkObject
               +----GtkWidget
                     +----GtkContainer
                           +----GtkBin
                                 +----GtkWindow
                                       +----GtkDialog
                                             +----GtkPrintUnixDialog

Implemented Interfaces

GtkPrintUnixDialog implements AtkImplementorIface.

Properties

  "current-page"             gint                  : Read / Write
  "page-setup"               GtkPageSetup          : Read / Write
  "print-settings"           GtkPrintSettings      : Read / Write
  "selected-printer"         GtkPrinter            : Read

Description

GtkPrintUnixDialog implements a print dialog for platforms which don't provide a native print dialog, like Unix. It can be used very much like any other GTK+ dialog, at the cost of the portability offered by the high-level printing API

In order to print something with GtkPrintUnixDialog, you need to use gtk_print_unix_dialog_get_selected_printer() to obtain a GtkPrinter object and use it to construct a GtkPrintJob using gtk_print_job_new().

GtkPrintUnixDialog uses the following response values:

GTK_RESPONSE_OK | for the "Print" button
GTK_RESPONSE_APPLY | for the "Preview" button
GTK_RESPONSE_CANCEL | for the "Cancel" button

Printing support was added in GTK+ 2.10.

Details

GtkPrintUnixDialog

typedef struct _GtkPrintUnixDialog GtkPrintUnixDialog;

gtk_print_unix_dialog_new ()

GtkWidget*          gtk_print_unix_dialog_new           (const gchar *title,
                                                         GtkWindow *parent);

Creates a new GtkPrintUnixDialog.

title : | Title of the dialog, or NULL
parent : | Transient parent of the dialog, or NULL
Returns : | a new GtkPrintUnixDialog

Since 2.10

gtk_print_unix_dialog_set_page_setup ()

void                gtk_print_unix_dialog_set_page_setup
                                                        (GtkPrintUnixDialog *dialog,
                                                         GtkPageSetup *page_setup);

Sets the page setup of the GtkPrintUnixDialog.

dialog : | a GtkPrintUnixDialog
page_setup : | a GtkPageSetup

Since 2.10

gtk_print_unix_dialog_get_page_setup ()

GtkPageSetup*       gtk_print_unix_dialog_get_page_setup
                                                        (GtkPrintUnixDialog *dialog);

Gets the page setup that is used by the GtkPrintUnixDialog.

dialog : | a GtkPrintUnixDialog
Returns : | the page setup of dialog.

Since 2.10

gtk_print_unix_dialog_set_current_page ()

void                gtk_print_unix_dialog_set_current_page
                                                        (GtkPrintUnixDialog *dialog,
                                                         gint current_page);

Sets the current page number. If current_page is not -1, this enables the current page choice for the range of pages to print.

dialog : | a GtkPrintUnixDialog
current_page : | the current page number.

Since 2.10

gtk_print_unix_dialog_get_current_page ()

gint                gtk_print_unix_dialog_get_current_page
                                                        (GtkPrintUnixDialog *dialog);

Gets the current page of the GtkPrintDialog.

dialog : | a GtkPrintUnixDialog
Returns : | the current page of dialog

Since 2.10

gtk_print_unix_dialog_set_settings ()

void                gtk_print_unix_dialog_set_settings  (GtkPrintUnixDialog *dialog,
                                                         GtkPrintSettings *settings);

Sets the GtkPrintSettings for the GtkPrintUnixDialog. Typically, this is used to restore saved print settings from a previous print operation before the print dialog is shown.

dialog : | a GtkPrintUnixDialog
settings : | a GtkPrintSettings, or NULL

Since 2.10

gtk_print_unix_dialog_get_settings ()

GtkPrintSettings*   gtk_print_unix_dialog_get_settings  (GtkPrintUnixDialog *dialog);

Gets a new GtkPrintSettings object that represents the current values in the print dialog. Note that this creates a new object, and you need to unref it if don't want to keep it.

dialog : | a GtkPrintUnixDialog
Returns : | a new GtkPrintSettings object with the values from dialog

Since 2.10

gtk_print_unix_dialog_get_selected_printer ()

GtkPrinter*         gtk_print_unix_dialog_get_selected_printer
                                                        (GtkPrintUnixDialog *dialog);

Gets the currently selected printer.

dialog : | a GtkPrintUnixDialog
Returns : | the currently selected printer

Since 2.10

gtk_print_unix_dialog_add_custom_tab ()

void                gtk_print_unix_dialog_add_custom_tab
                                                        (GtkPrintUnixDialog *dialog,
                                                         GtkWidget *child,
                                                         GtkWidget *tab_label);

Adds a custom tab to the print dialog.

dialog : | a GtkPrintUnixDialog
child : | the widget to put in the custom tab
tab_label : | the widget to use as tab label

Since 2.10

enum GtkPrintCapabilities

typedef enum
{
  GTK_PRINT_CAPABILITY_PAGE_SET     = 1 << 0,
  GTK_PRINT_CAPABILITY_COPIES       = 1 << 1,
  GTK_PRINT_CAPABILITY_COLLATE      = 1 << 2,
  GTK_PRINT_CAPABILITY_REVERSE      = 1 << 3,
  GTK_PRINT_CAPABILITY_SCALE        = 1 << 4,
  GTK_PRINT_CAPABILITY_GENERATE_PDF = 1 << 5,
  GTK_PRINT_CAPABILITY_GENERATE_PS  = 1 << 6,
  GTK_PRINT_CAPABILITY_PREVIEW      = 1 << 7
} GtkPrintCapabilities;

An enum for specifying which features the print dialog should offer. I neither GTK_PRINT_CAPABILITY_GENERATE_PDF nor GTK_PRINT_CAPABILITY_GENERATE_PS is specified, GTK+ assumes that all formats are supported.

GTK_PRINT_CAPABILITY_PAGE_SET |
GTK_PRINT_CAPABILITY_COPIES |
GTK_PRINT_CAPABILITY_COLLATE |
GTK_PRINT_CAPABILITY_REVERSE |
GTK_PRINT_CAPABILITY_SCALE |
GTK_PRINT_CAPABILITY_GENERATE_PDF | The program will send the document to the printer in PDF format
GTK_PRINT_CAPABILITY_GENERATE_PS | The program will send the document to the printer in Postscript format
GTK_PRINT_CAPABILITY_PREVIEW |

gtk_print_unix_dialog_set_manual_capabilities ()

void                gtk_print_unix_dialog_set_manual_capabilities
                                                        (GtkPrintUnixDialog *dialog,
                                                         GtkPrintCapabilities capabilities);

This lets you specify the printing capabilities your application supports. For instance, if you can handle scaling the output then you pass GTK_PRINT_CAPABILITY_SCALE. If you don't pass that, then the dialog will only let you select the scale if the printing system automatically handles scaling.

dialog : | a GtkPrintUnixDialog
capabilities : | the printing capabilities of your application

Since 2.10

Property Details

The "current-page" property

  "current-page"             gint                  : Read / Write

The current page in the document.

Allowed values: >= -1

Default value: -1

The "page-setup" property

  "page-setup"               GtkPageSetup          : Read / Write

The GtkPageSetup to use.

The "print-settings" property

  "print-settings"           GtkPrintSettings      : Read / Write

The GtkPrintSettings used for initializing the dialog.

The "selected-printer" property

  "selected-printer"         GtkPrinter            : Read

The GtkPrinter which is selected.

See Also

GtkPageSetupUnixDialog, GtkPrinter, GtkPrintJob


GtkProgress

GtkProgress — Base class for GtkProgressBar

Synopsis

#include <gtk/gtk.h>

                    GtkProgress;
void                gtk_progress_set_show_text          (GtkProgress *progress,
                                                         gboolean show_text);
void                gtk_progress_set_text_alignment     (GtkProgress *progress,
                                                         gfloat x_align,
                                                         gfloat y_align);
void                gtk_progress_set_format_string      (GtkProgress *progress,
                                                         const gchar *format);
void                gtk_progress_set_adjustment         (GtkProgress *progress,
                                                         GtkAdjustment *adjustment);
void                gtk_progress_set_percentage         (GtkProgress *progress,
                                                         gdouble percentage);
void                gtk_progress_set_value              (GtkProgress *progress,
                                                         gdouble value);
gdouble             gtk_progress_get_value              (GtkProgress *progress);
void                gtk_progress_set_activity_mode      (GtkProgress *progress,
                                                         gboolean activity_mode);
gchar*              gtk_progress_get_current_text       (GtkProgress *progress);
gchar*              gtk_progress_get_text_from_value    (GtkProgress *progress,
                                                         gdouble value);
gdouble             gtk_progress_get_current_percentage (GtkProgress *progress);
gdouble             gtk_progress_get_percentage_from_value
                                                        (GtkProgress *progress,
                                                         gdouble value);
void                gtk_progress_configure              (GtkProgress *progress,
                                                         gdouble value,
                                                         gdouble hmin,
                                                         gdouble max);

Object Hierarchy

  GObject
   +----GInitiallyUnowned
         +----GtkObject
               +----GtkWidget
                     +----GtkProgress
                           +----GtkProgressBar

Implemented Interfaces

GtkProgress implements AtkImplementorIface.

Properties

  "activity-mode"            gboolean              : Read / Write
  "show-text"                gboolean              : Read / Write
  "text-xalign"              gfloat                : Read / Write
  "text-yalign"              gfloat                : Read / Write

Description

A GtkProgress is the abstract base class used to derive a GtkProgressBar which provides a visual representation of the progress of a long running operation.

Details

GtkProgress

typedef struct _GtkProgress GtkProgress;

The GtkProgress struct contains private data only. and should be accessed using the functions below.

gtk_progress_set_show_text ()

void                gtk_progress_set_show_text          (GtkProgress *progress,
                                                         gboolean show_text);

Warning

gtk_progress_set_show_text is deprecated and should not be used in newly-written code.

Controls whether progress text is shown.

progress : | a GtkProgress.
show_text : | a boolean indicating whether the progress text is shown.

gtk_progress_set_text_alignment ()

void                gtk_progress_set_text_alignment     (GtkProgress *progress,
                                                         gfloat x_align,
                                                         gfloat y_align);

Warning

gtk_progress_set_text_alignment is deprecated and should not be used in newly-written code.

Controls the alignment of the text within the progress bar area.

progress : | a GtkProgress.
x_align : | a number between 0.0 and 1.0 indicating the horizontal alignment of the progress text within the GtkProgress.
y_align : | a number between 0.0 and 1.0 indicating the vertical alignment of the progress text within the GtkProgress.

gtk_progress_set_format_string ()

void                gtk_progress_set_format_string      (GtkProgress *progress,
                                                         const gchar *format);

Warning

gtk_progress_set_format_string is deprecated and should not be used in newly-written code.

Sets a format string used to display text indicating the current progress. The string can contain the following substitution characters:

  • %v - the current progress value.

  • %l - the lower bound for the progress value.

  • %u - the upper bound for the progress value.

  • %p - the current progress percentage.

progress : | a GtkProgress.
format : | a string used to display progress text, or NULL to restore to the default format.

gtk_progress_set_adjustment ()

void                gtk_progress_set_adjustment         (GtkProgress *progress,
                                                         GtkAdjustment *adjustment);

Warning

gtk_progress_set_adjustment is deprecated and should not be used in newly-written code.

Associates a GtkAdjustment with the GtkProgress. A GtkAdjustment is used to represent the upper and lower bounds and the step interval of the underlying value for which progress is shown.

progress : | a GtkProgress.
adjustment : | the GtkAdjustment to be associated with the GtkProgress.

gtk_progress_set_percentage ()

void                gtk_progress_set_percentage         (GtkProgress *progress,
                                                         gdouble percentage);

Warning

gtk_progress_set_percentage is deprecated and should not be used in newly-written code.

Sets the current percentage completion for the GtkProgress.

progress : | a GtkProgress.
percentage : | the percentage complete which must be between 0.0 and 1.0.

gtk_progress_set_value ()

void                gtk_progress_set_value              (GtkProgress *progress,
                                                         gdouble value);

Warning

gtk_progress_set_value is deprecated and should not be used in newly-written code.

Sets the value within the GtkProgress to an absolute value. The value must be within the valid range of values for the underlying GtkAdjustment.

progress : | a GtkProgress.
value : | the value indicating the current completed amount.

gtk_progress_get_value ()

gdouble             gtk_progress_get_value              (GtkProgress *progress);

Warning

gtk_progress_get_value is deprecated and should not be used in newly-written code.

Returns the current progress complete value.

progress : | a GtkProgress.
Returns : | the current progress complete value.

gtk_progress_set_activity_mode ()

void                gtk_progress_set_activity_mode      (GtkProgress *progress,
                                                         gboolean activity_mode);

Warning

gtk_progress_set_activity_mode is deprecated and should not be used in newly-written code.

A GtkProgress can be in one of two different modes: percentage mode (the default) and activity mode. In activity mode, the progress is simply indicated as activity rather than as a percentage complete.

progress : | a GtkProgress.
activity_mode : | a boolean, TRUE for activity mode.

gtk_progress_get_current_text ()

gchar*              gtk_progress_get_current_text       (GtkProgress *progress);

Warning

gtk_progress_get_current_text is deprecated and should not be used in newly-written code.

Returns the current text associated with the GtkProgress. This text is the based on the underlying format string after any substitutions are made.

progress : | a GtkProgress.
Returns : | the text indicating the current progress.

gtk_progress_get_text_from_value ()

gchar*              gtk_progress_get_text_from_value    (GtkProgress *progress,
                                                         gdouble value);

Warning

gtk_progress_get_text_from_value is deprecated and should not be used in newly-written code.

Returns the text indicating the progress based on the supplied value. The current value for the GtkProgress remains unchanged.

progress : | a GtkProgress.
value : | an absolute progress value to use when formatting the progress text.
Returns : | a string indicating the progress.

gtk_progress_get_current_percentage ()

gdouble             gtk_progress_get_current_percentage (GtkProgress *progress);

Warning

gtk_progress_get_current_percentage is deprecated and should not be used in newly-written code.

Returns the current progress as a percentage.

progress : | a GtkProgress.
Returns : | a number between 0.0 and 1.0 indicating the percentage complete.

gtk_progress_get_percentage_from_value ()

gdouble             gtk_progress_get_percentage_from_value
                                                        (GtkProgress *progress,
                                                         gdouble value);

Warning

gtk_progress_get_percentage_from_value is deprecated and should not be used in newly-written code.

Returns the progress as a percentage calculated from the supplied absolute progress value.

progress : | a GtkProgress.
value : | an absolute progress value.
Returns : | a number between 0.0 and 1.0 indicating the percentage complete represented by value.

gtk_progress_configure ()

void                gtk_progress_configure              (GtkProgress *progress,
                                                         gdouble value,
                                                         gdouble hmin,
                                                         gdouble max);

Warning

gtk_progress_configure is deprecated and should not be used in newly-written code.

Allows the configuration of the minimum, maximum, and current values for the GtkProgress.

progress : | a GtkProgress.
value : | the current progress value.
hmin : |
max : | the maximum progress value.

Property Details

The "activity-mode" property

  "activity-mode"            gboolean              : Read / Write

If TRUE, the GtkProgress is in activity mode, meaning that it signals something is happening, but not how much of the activity is finished. This is used when you're doing something that you don't know how long it will take.

Default value: FALSE

The "show-text" property

  "show-text"                gboolean              : Read / Write

Whether the progress is shown as text.

Default value: FALSE

The "text-xalign" property

  "text-xalign"              gfloat                : Read / Write

A number between 0.0 and 1.0 specifying the horizontal alignment of the text in the progress widget.

Allowed values: [0,1]

Default value: 0.5

The "text-yalign" property

  "text-yalign"              gfloat                : Read / Write

A number between 0.0 and 1.0 specifying the vertical alignment of the text in the progress widget.

Allowed values: [0,1]

Default value: 0.5


GtkProgressBar

GtkProgressBar — A widget which indicates progress visually

Synopsis

#include <gtk/gtk.h>

                    GtkProgressBar;
GtkWidget*          gtk_progress_bar_new                (void);
void                gtk_progress_bar_pulse              (GtkProgressBar *pbar);
void                gtk_progress_bar_set_text           (GtkProgressBar *pbar,
                                                         const gchar *text);
void                gtk_progress_bar_set_fraction       (GtkProgressBar *pbar,
                                                         gdouble fraction);
void                gtk_progress_bar_set_pulse_step     (GtkProgressBar *pbar,
                                                         gdouble fraction);
void                gtk_progress_bar_set_orientation    (GtkProgressBar *pbar,
                                                         GtkProgressBarOrientation orientation);
void                gtk_progress_bar_set_ellipsize      (GtkProgressBar *pbar,
                                                         PangoEllipsizeMode mode);
enum                GtkProgressBarOrientation;
const gchar*        gtk_progress_bar_get_text           (GtkProgressBar *pbar);
gdouble             gtk_progress_bar_get_fraction       (GtkProgressBar *pbar);
gdouble             gtk_progress_bar_get_pulse_step     (GtkProgressBar *pbar);
GtkProgressBarOrientation gtk_progress_bar_get_orientation
                                                        (GtkProgressBar *pbar);
PangoEllipsizeMode  gtk_progress_bar_get_ellipsize      (GtkProgressBar *pbar);
GtkWidget*          gtk_progress_bar_new_with_adjustment
                                                        (GtkAdjustment *adjustment);
void                gtk_progress_bar_set_bar_style      (GtkProgressBar *pbar,
                                                         GtkProgressBarStyle style);
enum                GtkProgressBarStyle;
void                gtk_progress_bar_set_discrete_blocks
                                                        (GtkProgressBar *pbar,
                                                         guint blocks);
void                gtk_progress_bar_set_activity_step  (GtkProgressBar *pbar,
                                                         guint step);
void                gtk_progress_bar_set_activity_blocks
                                                        (GtkProgressBar *pbar,
                                                         guint blocks);
void                gtk_progress_bar_update             (GtkProgressBar *pbar,
                                                         gdouble percentage);

Object Hierarchy

  GObject
   +----GInitiallyUnowned
         +----GtkObject
               +----GtkWidget
                     +----GtkProgress
                           +----GtkProgressBar

Implemented Interfaces

GtkProgressBar implements AtkImplementorIface.

Properties

  "activity-blocks"          guint                 : Read / Write
  "activity-step"            guint                 : Read / Write
  "adjustment"               GtkAdjustment         : Read / Write
  "bar-style"                GtkProgressBarStyle   : Read / Write
  "discrete-blocks"          guint                 : Read / Write
  "ellipsize"                PangoEllipsizeMode    : Read / Write
  "fraction"                 gdouble               : Read / Write
  "orientation"              GtkProgressBarOrientation  : Read / Write
  "pulse-step"               gdouble               : Read / Write
  "text"                     gchararray            : Read / Write

Description

The GtkProgressBar is typically used to display the progress of a long running operation. It provides a visual clue that processing is underway. The GtkProgressBar can be used in two different modes: percentage mode and activity mode.

When an application can determine how much work needs to take place (e.g. read a fixed number of bytes from a file) and can monitor its progress, it can use the GtkProgressBar in percentage mode and the user sees a growing bar indicating the percentage of the work that has been completed. In this mode, the application is required to call gtk_progress_bar_set_fraction() periodically to update the progress bar.

When an application has no accurate way of knowing the amount of work to do, it can use the GtkProgressBar in activity mode, which shows activity by a block moving back and forth within the progress area. In this mode, the application is required to call gtk_progress_bar_pulse() perodically to update the progress bar.

There is quite a bit of flexibility provided to control the appearance of the GtkProgressBar. Functions are provided to control the orientation of the bar, optional text can be displayed along with the bar, and the step size used in activity mode can be set.

Note

The GtkProgressBar/GtkProgress API in GTK 1.2 was bloated, needlessly complex and hard to use properly. Therefore GtkProgress has been deprecated completely and the GtkProgressBar API has been reduced to the following 10 functions: gtk_progress_bar_new(), gtk_progress_bar_pulse(), gtk_progress_bar_set_text(), gtk_progress_bar_set_fraction(), gtk_progress_bar_set_pulse_step(), gtk_progress_bar_set_orientation(), gtk_progress_bar_get_text(), gtk_progress_bar_get_fraction(), gtk_progress_bar_get_pulse_step(), gtk_progress_bar_get_orientation(). These have been grouped at the beginning of this section, followed by a large chunk of deprecated 1.2 compatibility functions.

Details

GtkProgressBar

typedef struct _GtkProgressBar GtkProgressBar;

The GtkProgressBar struct contains private data only, and should be accessed using the functions below.

gtk_progress_bar_new ()

GtkWidget*          gtk_progress_bar_new                (void);

Creates a new GtkProgressBar.

Returns : a GtkProgressBar.

gtk_progress_bar_pulse ()

void                gtk_progress_bar_pulse              (GtkProgressBar *pbar);

Indicates that some progress is made, but you don't know how much. Causes the progress bar to enter "activity mode," where a block bounces back and forth. Each call to gtk_progress_bar_pulse() causes the block to move by a little bit (the amount of movement per pulse is determined by gtk_progress_bar_set_pulse_step()).

pbar : a GtkProgressBar

gtk_progress_bar_set_text ()

void                gtk_progress_bar_set_text           (GtkProgressBar *pbar,
                                                         const gchar *text);

Causes the given text to appear superimposed on the progress bar.

pbar : | a GtkProgressBar
text : | a UTF-8 string, or NULL

gtk_progress_bar_set_fraction ()

void                gtk_progress_bar_set_fraction       (GtkProgressBar *pbar,
                                                         gdouble fraction);

Causes the progress bar to "fill in" the given fraction of the bar. The fraction should be between 0.0 and 1.0, inclusive.

pbar : | a GtkProgressBar
fraction : | fraction of the task that's been completed

gtk_progress_bar_set_pulse_step ()

void                gtk_progress_bar_set_pulse_step     (GtkProgressBar *pbar,
                                                         gdouble fraction);

Sets the fraction of total progress bar length to move the bouncing block for each call to gtk_progress_bar_pulse().

pbar : | a GtkProgressBar
fraction : | fraction between 0.0 and 1.0

gtk_progress_bar_set_orientation ()

void                gtk_progress_bar_set_orientation    (GtkProgressBar *pbar,
                                                         GtkProgressBarOrientation orientation);

Causes the progress bar to switch to a different orientation (left-to-right, right-to-left, top-to-bottom, or bottom-to-top).

pbar : | a GtkProgressBar
orientation : | orientation of the progress bar

gtk_progress_bar_set_ellipsize ()

void                gtk_progress_bar_set_ellipsize      (GtkProgressBar *pbar,
                                                         PangoEllipsizeMode mode);

Sets the mode used to ellipsize (add an ellipsis: "...") the text if there is not enough space to render the entire string.

pbar : | a GtkProgressBar
mode : | a PangoEllipsizeMode

Since 2.6

enum GtkProgressBarOrientation

typedef enum
{
  GTK_PROGRESS_LEFT_TO_RIGHT,
  GTK_PROGRESS_RIGHT_TO_LEFT,
  GTK_PROGRESS_BOTTOM_TO_TOP,
  GTK_PROGRESS_TOP_TO_BOTTOM
} GtkProgressBarOrientation;

An enumeration representing possible orientations and growth directions for the visible progress bar.

GTK_PROGRESS_LEFT_TO_RIGHT | A horizontal progress bar growing from left to right.
GTK_PROGRESS_RIGHT_TO_LEFT | A horizontal progress bar growing from right to left.
GTK_PROGRESS_BOTTOM_TO_TOP | A vertical progress bar growing from bottom to top.
GTK_PROGRESS_TOP_TO_BOTTOM | A vertical progress bar growing from top to bottom.

gtk_progress_bar_get_text ()

const gchar*        gtk_progress_bar_get_text           (GtkProgressBar *pbar);

Retrieves the text displayed superimposed on the progress bar, if any, otherwise NULL. The return value is a reference to the text, not a copy of it, so will become invalid if you change the text in the progress bar.

pbar : | a GtkProgressBar
Returns : | text, or NULL; this string is owned by the widget and should not be modified or freed.

gtk_progress_bar_get_fraction ()

gdouble             gtk_progress_bar_get_fraction       (GtkProgressBar *pbar);

Returns the current fraction of the task that's been completed.

pbar : | a GtkProgressBar
Returns : | a fraction from 0.0 to 1.0

gtk_progress_bar_get_pulse_step ()

gdouble             gtk_progress_bar_get_pulse_step     (GtkProgressBar *pbar);

Retrieves the pulse step set with gtk_progress_bar_set_pulse_step()

pbar : | a GtkProgressBar
Returns : | a fraction from 0.0 to 1.0

gtk_progress_bar_get_orientation ()

GtkProgressBarOrientation gtk_progress_bar_get_orientation
                                                        (GtkProgressBar *pbar);

Retrieves the current progress bar orientation.

pbar : | a GtkProgressBar
Returns : | orientation of the progress bar

gtk_progress_bar_get_ellipsize ()

PangoEllipsizeMode  gtk_progress_bar_get_ellipsize      (GtkProgressBar *pbar);

Returns the ellipsizing position of the progressbar. See gtk_progress_bar_set_ellipsize().

pbar : | a GtkProgressBar
Returns : | PangoEllipsizeMode

Since 2.6

gtk_progress_bar_new_with_adjustment ()

GtkWidget*          gtk_progress_bar_new_with_adjustment
                                                        (GtkAdjustment *adjustment);

Warning

gtk_progress_bar_new_with_adjustment is deprecated and should not be used in newly-written code.

Creates a new GtkProgressBar with an associated GtkAdjustment.

adjustment : | a GtkAdjustment.
Returns : | a GtkProgressBar.

gtk_progress_bar_set_bar_style ()

void                gtk_progress_bar_set_bar_style      (GtkProgressBar *pbar,
                                                         GtkProgressBarStyle style);

Warning

gtk_progress_bar_set_bar_style is deprecated and should not be used in newly-written code.

Sets the style of the GtkProgressBar. The default style is GTK_PROGRESS_CONTINUOUS.

pbar : | a GtkProgressBar.
style : | a GtkProgressBarStyle value indicating the desired style.

enum GtkProgressBarStyle

typedef enum
{
  GTK_PROGRESS_CONTINUOUS,
  GTK_PROGRESS_DISCRETE
} GtkProgressBarStyle;

An enumeration representing the styles for drawing the progress bar.

GTK_PROGRESS_CONTINUOUS | The progress bar grows in a smooth, continuous manner.
GTK_PROGRESS_DISCRETE | The progress bar grows in discrete, visible blocks.

gtk_progress_bar_set_discrete_blocks ()

void                gtk_progress_bar_set_discrete_blocks
                                                        (GtkProgressBar *pbar,
                                                         guint blocks);

Warning

gtk_progress_bar_set_discrete_blocks is deprecated and should not be used in newly-written code.

Sets the number of blocks that the progress bar is divided into when the style is GTK_PROGRESS_DISCRETE.

pbar : | a GtkProgressBar.
blocks : | number of individual blocks making up the bar.

gtk_progress_bar_set_activity_step ()

void                gtk_progress_bar_set_activity_step  (GtkProgressBar *pbar,
                                                         guint step);

Warning

gtk_progress_bar_set_activity_step is deprecated and should not be used in newly-written code.

Sets the step value used when the progress bar is in activity mode. The step is the amount by which the progress is incremented each iteration.

pbar : | a GtkProgressBar.
step : | the amount which the progress is incremented in activity mode.

gtk_progress_bar_set_activity_blocks ()

void                gtk_progress_bar_set_activity_blocks
                                                        (GtkProgressBar *pbar,
                                                         guint blocks);

Warning

gtk_progress_bar_set_activity_blocks is deprecated and should not be used in newly-written code.

Sets the number of blocks used when the progress bar is in activity mode. Larger numbers make the visible block smaller.

pbar : | a GtkProgressBar.
blocks : | number of blocks which can fit within the progress bar area.

gtk_progress_bar_update ()

void                gtk_progress_bar_update             (GtkProgressBar *pbar,
                                                         gdouble percentage);

Warning

gtk_progress_bar_update is deprecated and should not be used in newly-written code.

This function is deprecated. Please use gtk_progress_set_value() or gtk_progress_set_percentage() instead.

pbar : | a GtkProgressBar.
percentage : | the new percent complete value.

Property Details

The "activity-blocks" property

  "activity-blocks"          guint                 : Read / Write

The number of blocks which can fit in the progress bar area in activity mode (Deprecated).

Allowed values: >= 2

Default value: 5

The "activity-step" property

  "activity-step"            guint                 : Read / Write

The increment used for each iteration in activity mode (Deprecated).

Default value: 3

The "adjustment" property

  "adjustment"               GtkAdjustment         : Read / Write

The GtkAdjustment connected to the progress bar (Deprecated).

The "bar-style" property

  "bar-style"                GtkProgressBarStyle   : Read / Write

Specifies the visual style of the bar in percentage mode (Deprecated).

Default value: GTK_PROGRESS_CONTINUOUS

The "discrete-blocks" property

  "discrete-blocks"          guint                 : Read / Write

The number of discrete blocks in a progress bar (when shown in the discrete style).

Allowed values: >= 2

Default value: 10

The "ellipsize" property

  "ellipsize"                PangoEllipsizeMode    : Read / Write

The preferred place to ellipsize the string, if the progressbar does not have enough room to display the entire string, specified as a PangoEllisizeMode.

Note that setting this property to a value other than PANGO_ELLIPSIZE_NONE has the side-effect that the progressbar requests only enough space to display the ellipsis "...". Another means to set a progressbar's width is gtk_widget_set_size_request().

Default value: PANGO_ELLIPSIZE_NONE

Since 2.6

The "fraction" property

  "fraction"                 gdouble               : Read / Write

The fraction of total work that has been completed.

Allowed values: [0,1]

Default value: 0

The "orientation" property

  "orientation"              GtkProgressBarOrientation  : Read / Write

Orientation and growth direction of the progress bar.

Default value: GTK_PROGRESS_LEFT_TO_RIGHT

The "pulse-step" property

  "pulse-step"               gdouble               : Read / Write

The fraction of total progress to move the bouncing block when pulsed.

Allowed values: [0,1]

Default value: 0.1

The "text" property

  "text"                     gchararray            : Read / Write

Text to be displayed in the progress bar.

Default value: "%P %%"


GtkRadioAction

GtkRadioAction — An action of which only one in a group can be active

Synopsis

#include <gtk/gtk.h>

                    GtkRadioAction;
GtkRadioAction*     gtk_radio_action_new                (const gchar *name,
                                                         const gchar *label,
                                                         const gchar *tooltip,
                                                         const gchar *stock_id,
                                                         gint value);
GSList*             gtk_radio_action_get_group          (GtkRadioAction *action);
void                gtk_radio_action_set_group          (GtkRadioAction *action,
                                                         GSList *group);
gint                gtk_radio_action_get_current_value  (GtkRadioAction *action);
void                gtk_radio_action_set_current_value  (GtkRadioAction *action,
                                                         gint current_value);

Object Hierarchy

  GObject
   +----GtkAction
         +----GtkToggleAction
               +----GtkRadioAction

Properties

  "current-value"            gint                  : Read / Write
  "group"                    GtkRadioAction        : Write
  "value"                    gint                  : Read / Write

Signals

  "changed"                                        : Run First / No Recursion

Description

A GtkRadioAction is similar to GtkRadioMenuItem. A number of radio actions can be linked together so that only one may be active at any one time.

Details

GtkRadioAction

typedef struct _GtkRadioAction GtkRadioAction;

The GtkRadioAction struct contains only private members and should not be accessed directly.

gtk_radio_action_new ()

GtkRadioAction*     gtk_radio_action_new                (const gchar *name,
                                                         const gchar *label,
                                                         const gchar *tooltip,
                                                         const gchar *stock_id,
                                                         gint value);

Creates a new GtkRadioAction object. To add the action to a GtkActionGroup and set the accelerator for the action, call gtk_action_group_add_action_with_accel().

name : | A unique name for the action
label : | The label displayed in menu items and on buttons
tooltip : | A tooltip for this action
stock_id : | The stock icon to display in widgets representing this action
value : | The value which gtk_radio_action_get_current_value() should return if this action is selected.
Returns : | a new GtkRadioAction

Since 2.4

gtk_radio_action_get_group ()

GSList*             gtk_radio_action_get_group          (GtkRadioAction *action);

Returns the list representing the radio group for this object. Note that the returned list is only valid until the next change to the group.

A common way to set up a group of radio group is the following:

  GSList *group = NULL;
  GtkRadioAction *action;

  while (/* more actions to add */)
    {
       action = gtk_radio_action_new (...);

       gtk_radio_action_set_group (action, group);
       group = gtk_radio_action_get_group (action);
    }

action : | the action object
Returns : | the list representing the radio group for this object

Since 2.4

gtk_radio_action_set_group ()

void                gtk_radio_action_set_group          (GtkRadioAction *action,
                                                         GSList *group);

Sets the radio group for the radio action object.

action : | the action object
group : | a list representing a radio group

Since 2.4

gtk_radio_action_get_current_value ()

gint                gtk_radio_action_get_current_value  (GtkRadioAction *action);

Obtains the value property of the currently active member of the group to which action belongs.

action : | a GtkRadioAction
Returns : | The value of the currently active group member

Since 2.4

gtk_radio_action_set_current_value ()

void                gtk_radio_action_set_current_value  (GtkRadioAction *action,
                                                         gint current_value);

Sets the currently active group member to the member with value property current_value.

action : | a GtkRadioAction
current_value : | the new value

Since 2.10

Property Details

The "current-value" property

  "current-value"            gint                  : Read / Write

The value property of the currently active member of the group to which this action belongs.

Default value: 0

Since 2.10

The "group" property

  "group"                    GtkRadioAction        : Write

Sets a new group for a radio action.

Since 2.4

The "value" property

  "value"                    gint                  : Read / Write

The value is an arbitrary integer which can be used as a convenient way to determine which action in the group is currently active in an ::activate or ::changed signal handler. See gtk_radio_action_get_current_value() and GtkRadioActionEntry for convenient ways to get and set this property.

Default value: 0

Since 2.4

Signal Details

The "changed" signal

void                user_function                      (GtkRadioAction *action,
                                                        GtkRadioAction *current,
                                                        gpointer        user_data)      : Run First / No Recursion

The ::changed signal is emitted on every member of a radio group when the active member is changed. The signal gets emitted after the ::activate signals for the previous and current active members.

action : | the action on which the signal is emitted
current : | the member of actions group which has just been activated
user_data : | user data set when the signal handler was connected.

Since 2.4


GtkRadioButton

GtkRadioButton — A choice from multiple check buttons

Synopsis

#include <gtk/gtk.h>

                    GtkRadioButton;
GtkWidget*          gtk_radio_button_new                (GSList *group);
GtkWidget*          gtk_radio_button_new_from_widget    (GtkRadioButton *group);
GtkWidget*          gtk_radio_button_new_with_label     (GSList *group,
                                                         const gchar *label);
GtkWidget*          gtk_radio_button_new_with_label_from_widget
                                                        (GtkRadioButton *group,
                                                         const gchar *label);
GtkWidget*          gtk_radio_button_new_with_mnemonic  (GSList *group,
                                                         const gchar *label);
GtkWidget*          gtk_radio_button_new_with_mnemonic_from_widget
                                                        (GtkRadioButton *group,
                                                         const gchar *label);
#define             gtk_radio_button_group
void                gtk_radio_button_set_group          (GtkRadioButton *radio_button,
                                                         GSList *group);
GSList*             gtk_radio_button_get_group          (GtkRadioButton *radio_button);

Object Hierarchy

  GObject
   +----GInitiallyUnowned
         +----GtkObject
               +----GtkWidget
                     +----GtkContainer
                           +----GtkBin
                                 +----GtkButton
                                       +----GtkToggleButton
                                             +----GtkCheckButton
                                                   +----GtkRadioButton

Implemented Interfaces

GtkRadioButton implements AtkImplementorIface.

Properties

  "group"                    GtkRadioButton        : Write

Signals

  "group-changed"                                  : Run First

Description

A single radio button performs the same basic function as a GtkCheckButton, as its position in the object hierarchy reflects. It is only when multiple radio buttons are grouped together that they become a different user interface component in their own right.

Every radio button is a member of some group of radio buttons. When one is selected, all other radio buttons in the same group are deselected. A GtkRadioButton is one way of giving the user a choice from many options.

Radio button widgets are created with gtk_radio_button_new(), passing NULL as the argument if this is the first radio button in a group. In subsequent calls, the group you wish to add this button to should be passed as an argument. Optionally, gtk_radio_button_new_with_label() can be used if you want a text label on the radio button.

Alternatively, when adding widgets to an existing group of radio buttons, use gtk_radio_button_new_from_widget() with a GtkRadioButton that already has a group assigned to it. The convenience function gtk_radio_button_new_with_label_from_widget() is also provided.

To retrieve the group a GtkRadioButton is assigned to, use gtk_radio_button_get_group().

To remove a GtkRadioButton from one group and make it part of a new one, use gtk_radio_button_set_group().

The group list does not need to be freed, as each GtkRadioButton will remove itself and its list item when it is destroyed.

Example 9. How to create a group of two radio buttons.

void create_radio_buttons (void) {

   GtkWidget *window, *radio1, *radio2, *box, *entry;
   window = gtk_window_new (GTK_WINDOW_TOPLEVEL);
   box = gtk_vbox_new (TRUE, 2);

   /* Create a radio button with a GtkEntry widget */
   radio1 = gtk_radio_button_new (NULL);
   entry = gtk_entry_new ();
   gtk_container_add (GTK_CONTAINER (radio1), entry);

   /* Create a radio button with a label */
   radio2 = gtk_radio_button_new_with_label_from_widget (GTK_RADIO_BUTTON (radio1),
                            "I'm the second radio button.");

   /* Pack them into a box, then show all the widgets */
   gtk_box_pack_start (GTK_BOX (box), radio1, TRUE, TRUE, 2);
   gtk_box_pack_start (GTK_BOX (box), radio2, TRUE, TRUE, 2);
   gtk_container_add (GTK_CONTAINER (window), box);
   gtk_widget_show_all (window);
   return;
}

When an unselected button in the group is clicked the clicked button receives the "toggled" signal, as does the previously selected button. Inside the "toggled" handler, gtk_toggle_button_get_active() can be used to determine if the button has been selected or deselected.

Details

GtkRadioButton

typedef struct _GtkRadioButton GtkRadioButton;

Contains only private data that should be read and manipulated using the functions below.

gtk_radio_button_new ()

GtkWidget*          gtk_radio_button_new                (GSList *group);

Creates a new GtkRadioButton. To be of any practical value, a widget should then be packed into the radio button.

group : | an existing radio button group, or NULL if you are creating a new group.
Returns : | a new radio button.

gtk_radio_button_new_from_widget ()

GtkWidget*          gtk_radio_button_new_from_widget    (GtkRadioButton *group);

Creates a new GtkRadioButton, adding it to the same group as group. As with gtk_radio_button_new(), a widget should be packed into the radio button.

group : | an existing GtkRadioButton.
Returns : | a new radio button.

gtk_radio_button_new_with_label ()

GtkWidget*          gtk_radio_button_new_with_label     (GSList *group,
                                                         const gchar *label);

Creates a new GtkRadioButton with a text label.

group : | an existing radio button group, or NULL if you are creating a new group.
label : | the text label to display next to the radio button.
Returns : | a new radio button.

gtk_radio_button_new_with_label_from_widget ()

GtkWidget*          gtk_radio_button_new_with_label_from_widget
                                                        (GtkRadioButton *group,
                                                         const gchar *label);

Creates a new GtkRadioButton with a text label, adding it to the same group as group.

group : | an existing GtkRadioButton.
label : | a text string to display next to the radio button.
Returns : | a new radio button.

gtk_radio_button_new_with_mnemonic ()

GtkWidget*          gtk_radio_button_new_with_mnemonic  (GSList *group,
                                                         const gchar *label);

Creates a new GtkRadioButton containing a label, adding it to the same group as group. The label will be created using gtk_label_new_with_mnemonic(), so underscores in label indicate the mnemonic for the button.

group : | the radio button group
label : | the text of the button, with an underscore in front of the mnemonic character
Returns : | a new GtkRadioButton

gtk_radio_button_new_with_mnemonic_from_widget ()

GtkWidget*          gtk_radio_button_new_with_mnemonic_from_widget
                                                        (GtkRadioButton *group,
                                                         const gchar *label);

Creates a new GtkRadioButton containing a label. The label will be created using gtk_label_new_with_mnemonic(), so underscores in label indicate the mnemonic for the button.

group : | widget to get radio group from
label : | the text of the button, with an underscore in front of the mnemonic character
Returns : | a new GtkRadioButton

gtk_radio_button_group

#define gtk_radio_button_group gtk_radio_button_get_group

Warning

gtk_radio_button_group is deprecated and should not be used in newly-written code.

Deprecated compatibility macro. Use gtk_radio_button_get_group() instead.

gtk_radio_button_set_group ()

void                gtk_radio_button_set_group          (GtkRadioButton *radio_button,
                                                         GSList *group);

Sets a GtkRadioButton's group. It should be noted that this does not change the layout of your interface in any way, so if you are changing the group, it is likely you will need to re-arrange the user interface to reflect these changes.

radio_button : | a GtkRadioButton.
group : | an existing radio button group, such as one returned from gtk_radio_button_get_group().

gtk_radio_button_get_group ()

GSList*             gtk_radio_button_get_group          (GtkRadioButton *radio_button);

Retrieves the group assigned to a radio button.

radio_button : | a GtkRadioButton.
Returns : | a linked list containing all the radio buttons in the same group as radio_button.

Property Details

The "group" property

  "group"                    GtkRadioButton        : Write

Sets a new group for a radio button.

Signal Details

The "group-changed" signal

void                user_function                      (GtkRadioButton *style,
                                                        gpointer        user_data)      : Run First

Emitted when the group of radio buttons that a radio button belongs to changes. This is emitted when a radio button switches from being alone to being part of a group of 2 or more buttons, or vice-versa, and when a buttton is moved from one group of 2 or more buttons to a different one, but not when the composition of the group that a button belongs to changes.

style : | the object which received the signal
user_data : | user data set when the signal handler was connected.

Since 2.4

See Also

GtkOptionMenu

Another way of offering the user a single choice from many.


GtkRadioMenuItem

GtkRadioMenuItem — A choice from multiple check menu items

Synopsis

#include <gtk/gtk.h>

                    GtkRadioMenuItem;
GtkWidget*          gtk_radio_menu_item_new             (GSList *group);
GtkWidget*          gtk_radio_menu_item_new_with_label  (GSList *group,
                                                         const gchar *label);
GtkWidget*          gtk_radio_menu_item_new_with_mnemonic
                                                        (GSList *group,
                                                         const gchar *label);
GtkWidget*          gtk_radio_menu_item_new_from_widget (GtkRadioMenuItem *group);
GtkWidget*          gtk_radio_menu_item_new_with_label_from_widget
                                                        (GtkRadioMenuItem *group,
                                                         const gchar *label);
GtkWidget*          gtk_radio_menu_item_new_with_mnemonic_from_widget
                                                        (GtkRadioMenuItem *group,
                                                         const gchar *label);
#define             gtk_radio_menu_item_group
void                gtk_radio_menu_item_set_group       (GtkRadioMenuItem *radio_menu_item,
                                                         GSList *group);
GSList*             gtk_radio_menu_item_get_group       (GtkRadioMenuItem *radio_menu_item);

Object Hierarchy

  GObject
   +----GInitiallyUnowned
         +----GtkObject
               +----GtkWidget
                     +----GtkContainer
                           +----GtkBin
                                 +----GtkItem
                                       +----GtkMenuItem
                                             +----GtkCheckMenuItem
                                                   +----GtkRadioMenuItem

Implemented Interfaces

GtkRadioMenuItem implements AtkImplementorIface.

Properties

  "group"                    GtkRadioMenuItem      : Write

Signals

  "group-changed"                                  : Run First

Description

A radio menu item is a check menu item that belongs to a group. At each instant exactly one of the radio menu items from a group is selected.

The group list does not need to be freed, as each GtkRadioMenuItem will remove itself and its list item when it is destroyed.

The correct way to create a group of radio menu items is approximatively this:

Example 21. How to create a group of radio menu items.

GSList *group = NULL;
GtkWidget *item;
gint i;

for (i = 0; i < 5; i++)
{
  item = gtk_radio_menu_item_new_with_label (group, "This is an example");
  group = gtk_radio_menu_item_get_group (GTK_RADIO_MENU_ITEM (item));
  if (i == 1)
    gtk_check_menu_item_set_active (GTK_CHECK_MENU_ITEM (item), TRUE);
}

Details

GtkRadioMenuItem

typedef struct _GtkRadioMenuItem GtkRadioMenuItem;

The structure contains only private data that must be accessed through the interface functions.

gtk_radio_menu_item_new ()

GtkWidget*          gtk_radio_menu_item_new             (GSList *group);

Creates a new GtkRadioMenuItem.

group : | the group to which the radio menu item is to be attached
Returns : | a new GtkRadioMenuItem

gtk_radio_menu_item_new_with_label ()

GtkWidget*          gtk_radio_menu_item_new_with_label  (GSList *group,
                                                         const gchar *label);

Creates a new GtkRadioMenuItem whose child is a simple GtkLabel.

group : | the group to which the radio menu item is to be attached
label : | the text for the label
Returns : | a new GtkRadioMenuItem

gtk_radio_menu_item_new_with_mnemonic ()

GtkWidget*          gtk_radio_menu_item_new_with_mnemonic
                                                        (GSList *group,
                                                         const gchar *label);

Creates a new GtkRadioMenuItem containing a label. The label will be created using gtk_label_new_with_mnemonic(), so underscores in label indicate the mnemonic for the menu item.

group : | group the radio menu item is inside
label : | the text of the button, with an underscore in front of the mnemonic character
Returns : | a new GtkRadioMenuItem

gtk_radio_menu_item_new_from_widget ()

GtkWidget*          gtk_radio_menu_item_new_from_widget (GtkRadioMenuItem *group);

Creates a new GtkRadioMenuItem adding it to the same group as group.

group : | An existing GtkRadioMenuItem
Returns : | The new GtkRadioMenuItem

Since 2.4

gtk_radio_menu_item_new_with_label_from_widget ()

GtkWidget*          gtk_radio_menu_item_new_with_label_from_widget
                                                        (GtkRadioMenuItem *group,
                                                         const gchar *label);

Creates a new GtkRadioMenuItem whose child is a simple GtkLabel. The new GtkRadioMenuItem is added to the same group as group.

group : | an existing GtkRadioMenuItem
label : | the text for the label
Returns : | The new GtkRadioMenuItem

Since 2.4

gtk_radio_menu_item_new_with_mnemonic_from_widget ()

GtkWidget*          gtk_radio_menu_item_new_with_mnemonic_from_widget
                                                        (GtkRadioMenuItem *group,
                                                         const gchar *label);

Creates a new GtkRadioMenuItem containing a label. The label will be created using gtk_label_new_with_mnemonic(), so underscores in label indicate the mnemonic for the menu item.

The new GtkRadioMenuItem is added to the same group as group.

group : | An existing GtkRadioMenuItem
label : | the text of the button, with an underscore in front of the mnemonic character
Returns : | The new GtkRadioMenuItem

Since 2.4

gtk_radio_menu_item_group

#define gtk_radio_menu_item_group gtk_radio_menu_item_get_group

Warning

gtk_radio_menu_item_group is deprecated and should not be used in newly-written code.

Deprecated compatibility macro. Use gtk_radio_menu_item_get_group() instead.

gtk_radio_menu_item_set_group ()

void                gtk_radio_menu_item_set_group       (GtkRadioMenuItem *radio_menu_item,
                                                         GSList *group);

Sets the group of a radio menu item, or changes it.

radio_menu_item : | a GtkRadioMenuItem.
group : | the new group.

gtk_radio_menu_item_get_group ()

GSList*             gtk_radio_menu_item_get_group       (GtkRadioMenuItem *radio_menu_item);

Returns the group to which the radio menu item belongs, as a GList of GtkRadioMenuItem. The list belongs to GTK+ and should not be freed.

radio_menu_item : | a GtkRadioMenuItem.
Returns : | the group of radio_menu_item.

Property Details

The "group" property

  "group"                    GtkRadioMenuItem      : Write

The radio menu item whose group this widget belongs to.

Since 2.8

Signal Details

The "group-changed" signal

void                user_function                      (GtkRadioMenuItem *radiomenuitem,
                                                        gpointer          user_data)          : Run First

radiomenuitem : | the object which received the signal.
user_data : | user data set when the signal handler was connected.

See Also

GtkMenuItem | because a radio menu item is a menu item.
GtkCheckMenuItem | to know how to handle the check.


GtkRadioToolButton

GtkRadioToolButton — A toolbar item that contains a radio button

Synopsis

#include <gtk/gtk.h>

                    GtkRadioToolButton;
GtkToolItem*        gtk_radio_tool_button_new           (GSList *group);
GtkToolItem*        gtk_radio_tool_button_new_from_stock
                                                        (GSList *group,
                                                         const gchar *stock_id);
GtkToolItem*        gtk_radio_tool_button_new_from_widget
                                                        (GtkRadioToolButton *group);
GtkToolItem*        gtk_radio_tool_button_new_with_stock_from_widget
                                                        (GtkRadioToolButton *group,
                                                         const gchar *stock_id);
GSList*             gtk_radio_tool_button_get_group     (GtkRadioToolButton *button);
void                gtk_radio_tool_button_set_group     (GtkRadioToolButton *button,
                                                         GSList *group);

Object Hierarchy

  GObject
   +----GInitiallyUnowned
         +----GtkObject
               +----GtkWidget
                     +----GtkContainer
                           +----GtkBin
                                 +----GtkToolItem
                                       +----GtkToolButton
                                             +----GtkToggleToolButton
                                                   +----GtkRadioToolButton

Implemented Interfaces

GtkRadioToolButton implements AtkImplementorIface.

Properties

  "group"                    GtkRadioToolButton    : Write

Description

A GtkRadioToolButton is a GtkToolItem that contains a radio button, that is, a button that is part of a group of toggle buttons where only one button can be active at a time.

Use gtk_radio_tool_button_new() to create a new GtkRadioToolButton. use gtk_radio_tool_button_new_from_widget() to create a new GtkRadioToolButton that is part of the same group as an existing GtkRadioToolButton. Use gtk_radio_tool_button_new_from_stock() or gtk_radio_tool_button_new_from_widget_with_stock() to create a new GtkRAdioToolButton containing a stock item.

Details

GtkRadioToolButton

typedef struct _GtkRadioToolButton GtkRadioToolButton;

The GtkRadioToolButton contains only private data and should only be accessed through the functions described below.

gtk_radio_tool_button_new ()

GtkToolItem*        gtk_radio_tool_button_new           (GSList *group);

Creates a new GtkRadioToolButton, adding it to group.

group : | An existing radio button group, or NULL if you are creating a new group
Returns : | The new GtkRadioToolButton

Since 2.4

gtk_radio_tool_button_new_from_stock ()

GtkToolItem*        gtk_radio_tool_button_new_from_stock
                                                        (GSList *group,
                                                         const gchar *stock_id);

Creates a new GtkRadioToolButton, adding it to group. The new GtkRadioToolButton will contain an icon and label from the stock item indicated by stock_id.

group : | an existing radio button group, or NULL if you are creating a new group
stock_id : | the name of a stock item
Returns : | The new GtkRadioToolItem

Since 2.4

gtk_radio_tool_button_new_from_widget ()

GtkToolItem*        gtk_radio_tool_button_new_from_widget
                                                        (GtkRadioToolButton *group);

Creates a new GtkRadioToolButton adding it to the same group as gruup

group : | An existing GtkRadioToolButton
Returns : | The new GtkRadioToolButton

Since 2.4

gtk_radio_tool_button_new_with_stock_from_widget ()

GtkToolItem*        gtk_radio_tool_button_new_with_stock_from_widget
                                                        (GtkRadioToolButton *group,
                                                         const gchar *stock_id);

Creates a new GtkRadioToolButton adding it to the same group as group. The new GtkRadioToolButton will contain an icon and label from the stock item indicated by stock_id.

group : | An existing GtkRadioToolButton.
stock_id : | the name of a stock item
Returns : | A new GtkRadioToolButton

Since 2.4

gtk_radio_tool_button_get_group ()

GSList*             gtk_radio_tool_button_get_group     (GtkRadioToolButton *button);

Returns the radio button group button belongs to.

button : | a GtkRadioToolButton
Returns : | The group button belongs to.

Since 2.4

gtk_radio_tool_button_set_group ()

void                gtk_radio_tool_button_set_group     (GtkRadioToolButton *button,
                                                         GSList *group);

Adds button to group, removing it from the group it belonged to before.

button : | a GtkRadioToolButton
group : | an existing radio button group

Since 2.4

Property Details

The "group" property

  "group"                    GtkRadioToolButton    : Write

Sets a new group for a radio tool button.

Since 2.4

See Also

GtkToolbar | The toolbar widget
GtkToolButton | An ancestor class of GtkRadioToolButton. The properties "label_widget", "label", "icon_widget", and "stock_id" on GtkToolButton determine the label and icon used on a GtkRadioToolButton.
GtkSeparatorToolItem | A subclass of GtkToolItem that separates groups of items on a toolbar. It is usually a good idea to put a separator before and after a group of GtkRadioToolButtons on a GtkToolbar.


GtkRange

GtkRange — Base class for widgets which visualize an adjustment

Synopsis

#include <gtk/gtk.h>

                    GtkRange;
GtkAdjustment*      gtk_range_get_adjustment            (GtkRange *range);
void                gtk_range_set_update_policy         (GtkRange *range,
                                                         GtkUpdateType policy);
void                gtk_range_set_adjustment            (GtkRange *range,
                                                         GtkAdjustment *adjustment);
gboolean            gtk_range_get_inverted              (GtkRange *range);
void                gtk_range_set_inverted              (GtkRange *range,
                                                         gboolean setting);
GtkUpdateType       gtk_range_get_update_policy         (GtkRange *range);
gdouble             gtk_range_get_value                 (GtkRange *range);
void                gtk_range_set_increments            (GtkRange *range,
                                                         gdouble step,
                                                         gdouble page);
void                gtk_range_set_range                 (GtkRange *range,
                                                         gdouble min,
                                                         gdouble max);
void                gtk_range_set_value                 (GtkRange *range,
                                                         gdouble value);
enum                GtkSensitivityType;
void                gtk_range_set_lower_stepper_sensitivity
                                                        (GtkRange *range,
                                                         GtkSensitivityType sensitivity);
GtkSensitivityType  gtk_range_get_lower_stepper_sensitivity
                                                        (GtkRange *range);
void                gtk_range_set_upper_stepper_sensitivity
                                                        (GtkRange *range,
                                                         GtkSensitivityType sensitivity);
GtkSensitivityType  gtk_range_get_upper_stepper_sensitivity
                                                        (GtkRange *range);

Object Hierarchy

  GObject
   +----GInitiallyUnowned
         +----GtkObject
               +----GtkWidget
                     +----GtkRange
                           +----GtkScale
                           +----GtkScrollbar

Implemented Interfaces

GtkRange implements AtkImplementorIface.

Properties

  "adjustment"               GtkAdjustment         : Read / Write / Construct
  "inverted"                 gboolean              : Read / Write
  "lower-stepper-sensitivity" GtkSensitivityType    : Read / Write
  "update-policy"            GtkUpdateType         : Read / Write
  "upper-stepper-sensitivity" GtkSensitivityType    : Read / Write

Style Properties

  "activate-slider"          gboolean              : Read
  "arrow-displacement-x"     gint                  : Read
  "arrow-displacement-y"     gint                  : Read
  "slider-width"             gint                  : Read
  "stepper-size"             gint                  : Read
  "stepper-spacing"          gint                  : Read
  "trough-border"            gint                  : Read
  "trough-side-details"      gboolean              : Read
  "trough-under-steppers"    gboolean              : Read

Signals

  "adjust-bounds"                                  : Run Last
  "change-value"                                   : Run Last
  "move-slider"                                    : Run Last / Action
  "value-changed"                                  : Run Last

Description

Details

GtkRange

typedef struct _GtkRange GtkRange;

gtk_range_get_adjustment ()

GtkAdjustment*      gtk_range_get_adjustment            (GtkRange *range);

Get the GtkAdjustment which is the "model" object for GtkRange. See gtk_range_set_adjustment() for details. The return value does not have a reference added, so should not be unreferenced.

range : | a GtkRange
Returns : | a GtkAdjustment

gtk_range_set_update_policy ()

void                gtk_range_set_update_policy         (GtkRange *range,
                                                         GtkUpdateType policy);

Sets the update policy for the range. GTK_UPDATE_CONTINUOUS means that anytime the range slider is moved, the range value will change and the value_changed signal will be emitted. GTK_UPDATE_DELAYED means that the value will be updated after a brief timeout where no slider motion occurs, so updates are spaced by a short time rather than continuous. GTK_UPDATE_DISCONTINUOUS means that the value will only be updated when the user releases the button and ends the slider drag operation.

range : | a GtkRange
policy : | update policy

gtk_range_set_adjustment ()

void                gtk_range_set_adjustment            (GtkRange *range,
                                                         GtkAdjustment *adjustment);

Sets the adjustment to be used as the "model" object for this range widget. The adjustment indicates the current range value, the minimum and maximum range values, the step/page increments used for keybindings and scrolling, and the page size. The page size is normally 0 for GtkScale and nonzero for GtkScrollbar, and indicates the size of the visible area of the widget being scrolled. The page size affects the size of the scrollbar slider.

range : | a GtkRange
adjustment : | a GtkAdjustment

gtk_range_get_inverted ()

gboolean            gtk_range_get_inverted              (GtkRange *range);

Gets the value set by gtk_range_set_inverted().

range : | a GtkRange
Returns : | TRUE if the range is inverted

gtk_range_set_inverted ()

void                gtk_range_set_inverted              (GtkRange *range,
                                                         gboolean setting);

Ranges normally move from lower to higher values as the slider moves from top to bottom or left to right. Inverted ranges have higher values at the top or on the right rather than on the bottom or left.

range : | a GtkRange
setting : | TRUE to invert the range

gtk_range_get_update_policy ()

GtkUpdateType       gtk_range_get_update_policy         (GtkRange *range);

Gets the update policy of range. See gtk_range_set_update_policy().

range : | a GtkRange
Returns : | the current update policy

gtk_range_get_value ()

gdouble             gtk_range_get_value                 (GtkRange *range);

Gets the current value of the range.

range : | a GtkRange
Returns : | current value of the range.

gtk_range_set_increments ()

void                gtk_range_set_increments            (GtkRange *range,
                                                         gdouble step,
                                                         gdouble page);

Sets the step and page sizes for the range. The step size is used when the user clicks the GtkScrollbar arrows or moves GtkScale via arrow keys. The page size is used for example when moving via Page Up or Page Down keys.

range : | a GtkRange
step : | step size
page : | page size

gtk_range_set_range ()

void                gtk_range_set_range                 (GtkRange *range,
                                                         gdouble min,
                                                         gdouble max);

Sets the allowable values in the GtkRange, and clamps the range value to be between min and max. (If the range has a non-zero page size, it is clamped between min and max - page-size.)

range : | a GtkRange
min : | minimum range value
max : | maximum range value

gtk_range_set_value ()

void                gtk_range_set_value                 (GtkRange *range,
                                                         gdouble value);

Sets the current value of the range; if the value is outside the minimum or maximum range values, it will be clamped to fit inside them. The range emits the "value_changed" signal if the value changes.

range : | a GtkRange
value : | new value of the range

enum GtkSensitivityType

typedef enum
{
  GTK_SENSITIVITY_AUTO,
  GTK_SENSITIVITY_ON,
  GTK_SENSITIVITY_OFF
} GtkSensitivityType;

Determines how GTK+ handles the sensitivity of stepper arrows at the end of range widgets.

GTK_SENSITIVITY_AUTO | The arrow is made insensitive if the thumb is at the end
GTK_SENSITIVITY_ON | The arrow is always sensitive
GTK_SENSITIVITY_OFF | The arrow is always insensitive

gtk_range_set_lower_stepper_sensitivity ()

void                gtk_range_set_lower_stepper_sensitivity
                                                        (GtkRange *range,
                                                         GtkSensitivityType sensitivity);

Sets the sensitivity policy for the stepper that points to the 'lower' end of the GtkRange's adjustment.

range : | a GtkRange
sensitivity : | the lower stepper's sensitivity policy.

Since 2.10

gtk_range_get_lower_stepper_sensitivity ()

GtkSensitivityType  gtk_range_get_lower_stepper_sensitivity
                                                        (GtkRange *range);

Gets the sensitivity policy for the stepper that points to the 'lower' end of the GtkRange's adjustment.

range : | a GtkRange
Returns : | The lower stepper's sensitivity policy.

Since 2.10

gtk_range_set_upper_stepper_sensitivity ()

void                gtk_range_set_upper_stepper_sensitivity
                                                        (GtkRange *range,
                                                         GtkSensitivityType sensitivity);

Sets the sensitivity policy for the stepper that points to the 'upper' end of the GtkRange's adjustment.

range : | a GtkRange
sensitivity : | the upper stepper's sensitivity policy.

Since 2.10

gtk_range_get_upper_stepper_sensitivity ()

GtkSensitivityType  gtk_range_get_upper_stepper_sensitivity
                                                        (GtkRange *range);

Gets the sensitivity policy for the stepper that points to the 'upper' end of the GtkRange's adjustment.

range : | a GtkRange
Returns : | The upper stepper's sensitivity policy.

Since 2.10

Property Details

The "adjustment" property

  "adjustment"               GtkAdjustment         : Read / Write / Construct

The GtkAdjustment that contains the current value of this range object.

The "inverted" property

  "inverted"                 gboolean              : Read / Write

Invert direction slider moves to increase range value.

Default value: FALSE

The "lower-stepper-sensitivity" property

  "lower-stepper-sensitivity" GtkSensitivityType    : Read / Write

The sensitivity policy for the stepper that points to the adjustment's lower side.

Default value: GTK_SENSITIVITY_AUTO

The "update-policy" property

  "update-policy"            GtkUpdateType         : Read / Write

How the range should be updated on the screen.

Default value: GTK_UPDATE_CONTINUOUS

The "upper-stepper-sensitivity" property

  "upper-stepper-sensitivity" GtkSensitivityType    : Read / Write

The sensitivity policy for the stepper that points to the adjustment's upper side.

Default value: GTK_SENSITIVITY_AUTO

Style Property Details

The "activate-slider" style property

  "activate-slider"          gboolean              : Read

With this option set to TRUE, sliders will be drawn ACTIVE and with shadow IN while they are dragged.

Default value: FALSE

The "arrow-displacement-x" style property

  "arrow-displacement-x"     gint                  : Read

How far in the x direction to move the arrow when the button is depressed.

Default value: 0

The "arrow-displacement-y" style property

  "arrow-displacement-y"     gint                  : Read

How far in the y direction to move the arrow when the button is depressed.

Default value: 0

The "slider-width" style property

  "slider-width"             gint                  : Read

Width of scrollbar or scale thumb.

Allowed values: >= 0

Default value: 14

The "stepper-size" style property

  "stepper-size"             gint                  : Read

Length of step buttons at ends.

Allowed values: >= 0

Default value: 14

The "stepper-spacing" style property

  "stepper-spacing"          gint                  : Read

The spacing between the stepper buttons and thumb. Note that setting this value to anything > 0 will automatically set the trough-under-steppers style property to TRUE as well. Also, stepper-spacing won't have any effect if there are no steppers.

Allowed values: >= 0

Default value: 0

The "trough-border" style property

  "trough-border"            gint                  : Read

Spacing between thumb/steppers and outer trough bevel.

Allowed values: >= 0

Default value: 1

The "trough-side-details" style property

  "trough-side-details"      gboolean              : Read

Default value: FALSE

Since 2.10

The "trough-under-steppers" style property

  "trough-under-steppers"    gboolean              : Read

Whether to draw the trough across the full length of the range or to exclude the steppers and their spacing. Note that setting the stepper-spacing style property to any value > 0 will automatically enable trough-under-steppers too.

Default value: TRUE

Since 2.10

Signal Details

The "adjust-bounds" signal

void                user_function                      (GtkRange *range,
                                                        gdouble   arg1,
                                                        gpointer  user_data)      : Run Last

range : | the object which received the signal.
arg1 : |
user_data : | user data set when the signal handler was connected.

The "change-value" signal

gboolean            user_function                      (GtkRange     *range,
                                                        GtkScrollType scroll,
                                                        gdouble       value,
                                                        gpointer      user_data)      : Run Last

The ::change-value signal is emitted when a scroll action is performed on a range. It allows an application to determine the type of scroll event that occurred and the resultant new value. The application can handle the event itself and return TRUE to prevent further processing. Or, by returning FALSE, it can pass the event to other handlers until the default GTK+ handler is reached.

The value parameter is unrounded. An application that overrides the ::change-value signal is responsible for clamping the value to the desired number of decimal digits; the default GTK+ handler clamps the value based on range->round_digits.

It is not possible to use delayed update policies in an overridden ::change-value handler.

range : | the range that received the signal.
scroll : | the type of scroll action that was performed.
value : | the new value resulting from the scroll action.
returns : | TRUE to prevent other handlers from being invoked for the signal. FALSE to propagate the signal further.
user_data : | user data set when the signal handler was connected.

Since 2.6

The "move-slider" signal

void                user_function                      (GtkRange     *range,
                                                        GtkScrollType arg1,
                                                        gpointer      user_data)      : Run Last / Action

Virtual function that moves the slider. Used for keybindings.

range : | the GtkRange
arg1 : |
user_data : | user data set when the signal handler was connected.

The "value-changed" signal

void                user_function                      (GtkRange *range,
                                                        gpointer  user_data)      : Run Last

Emitted when the range value changes.

range : | the GtkRange
user_data : | user data set when the signal handler was connected.


Advanced usage

The GtkRecentChooser widgets might display items sorted and filtered, either with already supplied or custom sorting and filtering functions. The biggest difference from the EggRecentView widgets in EggRecent is that the GtkRecentChooser widgets will use their own copy of the list and will apply the sorting and filtering functions only on the copy; this allows the creation of many viewers with a single controller, like using many GtkTreeView with a single GtkTreeModel instance.

Available sorting methods are:

        /* no sorting */
    gtk_recent_chooser_set_sort_type (GTK_RECENT_CHOOSER (chooser), GTK_RECENT_SORT_NONE);

        /* most recently used first */
    gtk_recent_chooser_set_sort_type (GTK_RECENT_CHOOSER (chooser), GTK_RECENT_SORT_MRU);

    /* most recently used last */
    gtk_recent_chooser_set_sort_type (GTK_RECENT_CHOOSER (chooser), GTK_RECENT_SORT_LRU);

You can create your own sorting function, and the use the GTK_RECENT_SORT_CUSTOM method:

    /* custom sorting function, based on the registration count
     * (most used first)
     */
    static void
    sort_by_usage_count (GtkRecentInfo *a,
                             GtkRecentInfo *b,
                             gpointer       data)
        {
      gint count_a, count_b;

      count_a = count_b = 0;

      if (gtk_recent_info_has_application (a, APP_NAME))
        gtk_recent_info_get_application_info (a, APP_NAME, NULL, &count_a, NULL);

      if (gtk_recent_info_has_application (b, APP_NAME))
        gtk_recent_info_get_application_info (b, APP_NAME, NULL, &count_b, NULL);

      return count_a < count_b;
    }

    ...

      /* set custom sorting and set the custom sorting function */
      gtk_recent_chooser_set_sort_type (GTK_RECENT_CHOOSER (chooser),
                                        GTK_RECENT_SORT_CUSTOM);
      gtk_recent_chooser_set_sort_func (GTK_RECENT_CHOOSER,
                                        sort_by_usage_count,
                          NULL, /* sort function data */
                        NULL  /* destroy notify for the data */);

Filtering is done using the GtkRecentFilter object, similar to the GtkFileFilter object used by the GtkFileChooser widgets. The GtkRecentFilter object has a set of pre-defined options based on the meta-data exposed by the GtkRecentInfo object. It also allows custom filtering function:

        GtkRecentFilter *filter;

    filter = gtk_recent_filter_new ();

    /* set the user visible name of the filter */
    gtk_recent_filter_set_name (filter, "Since Last Month");

    /* set the maximum age of a recently used document */
    gtk_recent_filter_set_age (filter, 31);

    /* the chooser takes the ownership of the object */
    gtk_recent_chooser_add_filter (GTK_RECENT_CHOOSER (chooser), filter);

    /* set the currently used filter */
    gtk_recent_chooser_set_filter (GTK_RECENT_CHOOSER (chooser), filter);

    filter = gtk_recent_filter_new ();
    gtk_recent_filter_set_name (filter, "Every text file");
    gtk_recent_filter_set_mime_type (filter, "text/plain");

    gtk_recent_chooser_add_filter (GTK_RECENT_CHOOSER (chooser), filter);

The GtkRecentChooserWidget and GtkRecentChooserDialog widgets allow multiple filters and the selection of an appropriate one; the GtkRecentChooserMenu widget allows just a single filter object.


Displaying the Recently Used Documents

Displaying the Recently Used Documents list is handled by any widget implementing the GtkRecentChooser interface. These widgets also handle the sorting and filtering of the list; they will create their own GtkRecentManager objects by default:

        GtkWidget *chooser;
    gint response;

    /* create a new dialog with the recently used documents list shown
     * using a GtkTreeView widget
     */
    chooser = gtk_recent_chooser_dialog_new ("Recent Documents",
                                             parent_window,
                         GTK_STOCK_CLOSE, GTK_RESPONSE_CANCEL,
                         GTK_STOCK_OPEN, GTK_RESPONSE_OK,
                         NULL);
        /* set the sorting order to "most recently used first" */
    gtk_recent_chooser_set_sort_type (GTK_RECENT_CHOOSER (chooser), GTK_RECENT_SORT_MRU);
    response = gtk_dialog_run (GTK_DIALOG (chooser));
    if (response == GTK_RESPONSE_OK)
      {
        GtkRecentInfo *info;

            info = gtk_recent_chooser_get_current_item (GTK_RECENT_CHOOSER (chooser));
        do_something_with_the_item (info);

        gtk_recent_info_unref (info);
      }

    gtk_widget_destroy (chooser);


GtkRecentChooser

GtkRecentChooser — Interface implemented by GtkRecentChooserWidget, GtkRecentChooserMenu and GtkRecentChooserDialog

Synopsis

#include <gtk/gtk.h>

                    GtkRecentChooser;
                    GtkRecentChooserIface;
#define             GTK_RECENT_CHOOSER_ERROR
enum                GtkRecentChooserError;
void                gtk_recent_chooser_set_show_private (GtkRecentChooser *chooser,
                                                         gboolean show_private);
gboolean            gtk_recent_chooser_get_show_private (GtkRecentChooser *chooser);
void                gtk_recent_chooser_set_show_not_found
                                                        (GtkRecentChooser *chooser,
                                                         gboolean show_not_found);
gboolean            gtk_recent_chooser_get_show_not_found
                                                        (GtkRecentChooser *chooser);
void                gtk_recent_chooser_set_show_icons   (GtkRecentChooser *chooser,
                                                         gboolean show_icons);
gboolean            gtk_recent_chooser_get_show_icons   (GtkRecentChooser *chooser);
void                gtk_recent_chooser_set_select_multiple
                                                        (GtkRecentChooser *chooser,
                                                         gboolean select_multiple);
gboolean            gtk_recent_chooser_get_select_multiple
                                                        (GtkRecentChooser *chooser);
void                gtk_recent_chooser_set_local_only   (GtkRecentChooser *chooser,
                                                         gboolean local_only);
gboolean            gtk_recent_chooser_get_local_only   (GtkRecentChooser *chooser);
void                gtk_recent_chooser_set_limit        (GtkRecentChooser *chooser,
                                                         gint limit);
gint                gtk_recent_chooser_get_limit        (GtkRecentChooser *chooser);
void                gtk_recent_chooser_set_show_tips    (GtkRecentChooser *chooser,
                                                         gboolean show_tips);
gboolean            gtk_recent_chooser_get_show_tips    (GtkRecentChooser *chooser);
void                gtk_recent_chooser_set_show_numbers (GtkRecentChooser *chooser,
                                                         gboolean show_numbers);
gboolean            gtk_recent_chooser_get_show_numbers (GtkRecentChooser *chooser);
enum                GtkRecentSortType;
void                gtk_recent_chooser_set_sort_type    (GtkRecentChooser *chooser,
                                                         GtkRecentSortType sort_type);
GtkRecentSortType   gtk_recent_chooser_get_sort_type    (GtkRecentChooser *chooser);
gint                (*GtkRecentSortFunc)                (GtkRecentInfo *a,
                                                         GtkRecentInfo *b,
                                                         gpointer user_data);
void                gtk_recent_chooser_set_sort_func    (GtkRecentChooser *chooser,
                                                         GtkRecentSortFunc sort_func,
                                                         gpointer sort_data,
                                                         GDestroyNotify data_destroy);
gboolean            gtk_recent_chooser_set_current_uri  (GtkRecentChooser *chooser,
                                                         const gchar *uri,
                                                         GError **error);
gchar*              gtk_recent_chooser_get_current_uri  (GtkRecentChooser *chooser);
GtkRecentInfo*      gtk_recent_chooser_get_current_item (GtkRecentChooser *chooser);
gboolean            gtk_recent_chooser_select_uri       (GtkRecentChooser *chooser,
                                                         const gchar *uri,
                                                         GError **error);
void                gtk_recent_chooser_unselect_uri     (GtkRecentChooser *chooser,
                                                         const gchar *uri);
void                gtk_recent_chooser_select_all       (GtkRecentChooser *chooser);
void                gtk_recent_chooser_unselect_all     (GtkRecentChooser *chooser);
GList*              gtk_recent_chooser_get_items        (GtkRecentChooser *chooser);
gchar**             gtk_recent_chooser_get_uris         (GtkRecentChooser *chooser,
                                                         gsize *length);
void                gtk_recent_chooser_add_filter       (GtkRecentChooser *chooser,
                                                         GtkRecentFilter *filter);
void                gtk_recent_chooser_remove_filter    (GtkRecentChooser *chooser,
                                                         GtkRecentFilter *filter);
GSList*             gtk_recent_chooser_list_filters     (GtkRecentChooser *chooser);
void                gtk_recent_chooser_set_filter       (GtkRecentChooser *chooser,
                                                         GtkRecentFilter *filter);
GtkRecentFilter*    gtk_recent_chooser_get_filter       (GtkRecentChooser *chooser);

Object Hierarchy

  GInterface
   +----GtkRecentChooser

Prerequisites

GtkRecentChooser requires GtkObject.

Known Implementations

GtkRecentChooser is implemented by GtkRecentChooserDialog, GtkRecentChooserWidget and GtkRecentChooserMenu.

Signals

  "item-activated"                                 : Run Last
  "selection-changed"                              : Run Last

Description

GtkRecentChooser is an interface that can be implemented by widgets displaying the list of recently used files. In GTK+, the main objects that implement this interface are GtkRecentChooserWidget, GtkRecentChooserDialog and GtkRecentChooserMenu.

Recently used files are supported since GTK+ 2.10.

Details

GtkRecentChooser

typedef struct _GtkRecentChooser GtkRecentChooser;

GtkRecentChooserIface

typedef struct {
  GTypeInterface base_iface;

  /*
   * Methods
   */
  gboolean          (* set_current_uri)    (GtkRecentChooser  *chooser,
                          const gchar       *uri,
                          GError           **error);
  gchar *           (* get_current_uri)    (GtkRecentChooser  *chooser);
  gboolean          (* select_uri)         (GtkRecentChooser  *chooser,
                          const gchar       *uri,
                          GError           **error);
  void              (* unselect_uri)       (GtkRecentChooser  *chooser,
                                            const gchar       *uri);
  void              (* select_all)         (GtkRecentChooser  *chooser);
  void              (* unselect_all)       (GtkRecentChooser  *chooser);
  GList *           (* get_items)          (GtkRecentChooser  *chooser);
  GtkRecentManager *(* get_recent_manager) (GtkRecentChooser  *chooser);
  void              (* add_filter)         (GtkRecentChooser  *chooser,
                          GtkRecentFilter   *filter);
  void              (* remove_filter)      (GtkRecentChooser  *chooser,
                          GtkRecentFilter   *filter);
  GSList *          (* list_filters)       (GtkRecentChooser  *chooser);
  void              (* set_sort_func)      (GtkRecentChooser  *chooser,
                          GtkRecentSortFunc  sort_func,
                          gpointer           data,
                          GDestroyNotify     destroy);

  /*
   * Signals
   */
  void		    (* item_activated)     (GtkRecentChooser  *chooser);
  void		    (* selection_changed)  (GtkRecentChooser  *chooser);
} GtkRecentChooserIface;

GTK_RECENT_CHOOSER_ERROR

#define GTK_RECENT_CHOOSER_ERROR	(gtk_recent_chooser_error_quark ())

Used to get the GError quark for GtkRecentChooser errors.

enum GtkRecentChooserError

typedef enum
{
  GTK_RECENT_CHOOSER_ERROR_NOT_FOUND,
  GTK_RECENT_CHOOSER_ERROR_INVALID_URI
} GtkRecentChooserError;

These identify the various errors that can occur while calling GtkRecentChooser functions.

GTK_RECENT_CHOOSER_ERROR_NOT_FOUND | Indicates that a file does not exist
GTK_RECENT_CHOOSER_ERROR_INVALID_URI | Indicates a malformed URI

gtk_recent_chooser_set_show_private ()

void                gtk_recent_chooser_set_show_private (GtkRecentChooser *chooser,
                                                         gboolean show_private);

Whether to show recently used resources marked registered as private.

chooser : | a GtkRecentChooser
show_private : | TRUE to show private items, FALSE otherwise

Since 2.10

gtk_recent_chooser_get_show_private ()

gboolean            gtk_recent_chooser_get_show_private (GtkRecentChooser *chooser);

Returns whether chooser should display recently used resources registered as private.

chooser : | a GtkRecentChooser
Returns : | TRUE if the recent chooser should show private items, FALSE otherwise.

Since 2.10

gtk_recent_chooser_set_show_not_found ()

void                gtk_recent_chooser_set_show_not_found
                                                        (GtkRecentChooser *chooser,
                                                         gboolean show_not_found);

Sets whether chooser should display the recently used resources that it didn't find. This only applies to local resources.

chooser : | a GtkRecentChooser
show_not_found : | whether to show the local items we didn't find

Since 2.10

gtk_recent_chooser_get_show_not_found ()

gboolean            gtk_recent_chooser_get_show_not_found
                                                        (GtkRecentChooser *chooser);

Retrieves whether chooser should show the recently used resources that were not found.

chooser : | a GtkRecentChooser
Returns : | TRUE if the resources not found should be displayed, and FALSE otheriwse.

Since 2.10

gtk_recent_chooser_set_show_icons ()

void                gtk_recent_chooser_set_show_icons   (GtkRecentChooser *chooser,
                                                         gboolean show_icons);

Sets whether chooser should show an icon near the resource when displaying it.

chooser : | a GtkRecentChooser
show_icons : | whether to show an icon near the resource

Since 2.10

gtk_recent_chooser_get_show_icons ()

gboolean            gtk_recent_chooser_get_show_icons   (GtkRecentChooser *chooser);

Retrieves whether chooser should show an icon near the resource.

chooser : | a GtkRecentChooser
Returns : | TRUE if the icons should be displayed, FALSE otherwise.

Since 2.10

gtk_recent_chooser_set_select_multiple ()

void                gtk_recent_chooser_set_select_multiple
                                                        (GtkRecentChooser *chooser,
                                                         gboolean select_multiple);

Sets whether chooser can select multiple items.

chooser : | a GtkRecentChooser
select_multiple : | TRUE if chooser can select more than one item

Since 2.10

gtk_recent_chooser_get_select_multiple ()

gboolean            gtk_recent_chooser_get_select_multiple
                                                        (GtkRecentChooser *chooser);

Gets whether chooser can select multiple items.

chooser : | a GtkRecentChooser
Returns : | TRUE if chooser can select more than one item.

Since 2.10

gtk_recent_chooser_set_local_only ()

void                gtk_recent_chooser_set_local_only   (GtkRecentChooser *chooser,
                                                         gboolean local_only);

Sets whether only local resources, that is resources using the file:// URI scheme, should be shown in the recently used resources selector. If local_only is TRUE (the default) then the shown resources are guaranteed to be accessible through the operating system native file system.

chooser : | a GtkRecentChooser
local_only : | TRUE if only local files can be shown

Since 2.10

gtk_recent_chooser_get_local_only ()

gboolean            gtk_recent_chooser_get_local_only   (GtkRecentChooser *chooser);

Gets whether only local resources should be shown in the recently used resources selector. See gtk_recent_chooser_set_local_only()

chooser : | a GtkRecentChooser
Returns : | TRUE if only local resources should be shown.

Since 2.10

gtk_recent_chooser_set_limit ()

void                gtk_recent_chooser_set_limit        (GtkRecentChooser *chooser,
                                                         gint limit);

Sets the number of items that should be returned by gtk_recent_chooser_get_items() and gtk_recent_chooser_get_uris().

chooser : | a GtkRecentChooser
limit : | a positive integer, or -1 for all items

Since 2.10

gtk_recent_chooser_get_limit ()

gint                gtk_recent_chooser_get_limit        (GtkRecentChooser *chooser);

Gets the number of items returned by gtk_recent_chooser_get_items() and gtk_recent_chooser_get_uris().

chooser : | a GtkRecentChooser
Returns : | A positive integer, or -1 meaning that all items are returned.

Since 2.10

gtk_recent_chooser_set_show_tips ()

void                gtk_recent_chooser_set_show_tips    (GtkRecentChooser *chooser,
                                                         gboolean show_tips);

Sets whether to show a tooltips on the widget.

chooser : | a GtkRecentChooser
show_tips : | TRUE if tooltips should be shown

Since 2.10

gtk_recent_chooser_get_show_tips ()

gboolean            gtk_recent_chooser_get_show_tips    (GtkRecentChooser *chooser);

Gets whether chooser should display tooltips.

chooser : | a GtkRecentChooser
Returns : | TRUE if the recent chooser should show tooltips, FALSE otherwise.

Since 2.10

gtk_recent_chooser_set_show_numbers ()

void                gtk_recent_chooser_set_show_numbers (GtkRecentChooser *chooser,
                                                         gboolean show_numbers);

Whether to show recently used resources prepended by a unique number.

Do not use this function: use gtk_recent_chooser_menu_set_show_numbers() instead.

chooser : | a GtkRecentChooser
show_numbers : | TRUE to show numbers, FALSE otherwise

Since 2.10

gtk_recent_chooser_get_show_numbers ()

gboolean            gtk_recent_chooser_get_show_numbers (GtkRecentChooser *chooser);

Returns whether chooser should display recently used resources prepended by a unique number.

Do not use this function: use gtk_recent_chooser_menu_get_show_numbers() instead.

chooser : | a GtkRecentChooser
Returns : | TRUE if the recent chooser should show display numbers, FALSE otherwise.

Since 2.10

enum GtkRecentSortType

typedef enum
{
  GTK_RECENT_SORT_NONE = 0,
  GTK_RECENT_SORT_MRU,
  GTK_RECENT_SORT_LRU,
  GTK_RECENT_SORT_CUSTOM
} GtkRecentSortType;

Used to specify the sorting method to be applyed to the recently used resource list.

GTK_RECENT_SORT_NONE | Do not sort the returned list of recently used resources.
GTK_RECENT_SORT_MRU | Sort the returned list with the most recently used items first.
GTK_RECENT_SORT_LRU | Sort the returned list with the least recently used items first.
GTK_RECENT_SORT_CUSTOM | Sort the returned list using a custom sorting function passed using gtk_recent_manager_set_sort_func().

gtk_recent_chooser_set_sort_type ()

void                gtk_recent_chooser_set_sort_type    (GtkRecentChooser *chooser,
                                                         GtkRecentSortType sort_type);

Changes the sorting order of the recently used resources list displayed by chooser.

chooser : | a GtkRecentChooser
sort_type : | sort order that the chooser should use

Since 2.10

gtk_recent_chooser_get_sort_type ()

GtkRecentSortType   gtk_recent_chooser_get_sort_type    (GtkRecentChooser *chooser);

Gets the value set by gtk_recent_chooser_set_sort_type().

chooser : | a GtkRecentChooser
Returns : | the sorting order of the chooser.

Since 2.10

GtkRecentSortFunc ()

gint                (*GtkRecentSortFunc)                (GtkRecentInfo *a,
                                                         GtkRecentInfo *b,
                                                         gpointer user_data);

a :
b :
user_data :
Returns :

gtk_recent_chooser_set_sort_func ()

void                gtk_recent_chooser_set_sort_func    (GtkRecentChooser *chooser,
                                                         GtkRecentSortFunc sort_func,
                                                         gpointer sort_data,
                                                         GDestroyNotify data_destroy);

Sets the comparison function used when sorting to be sort_func. If the chooser has the sort type set to GTK_RECENT_SORT_CUSTOM then the chooser will sort using this function.

To the comparison function will be passed two GtkRecentInfo structs and sort_data; sort_func should return a positive integer if the first item comes before the second, zero if the two items are equal and a negative integer if the first item comes after the second.

chooser : | a GtkRecentChooser
sort_func : | the comparison function
sort_data : | user data to pass to sort_func, or NULL
data_destroy : | destroy notifier for sort_data, or NULL

Since 2.10

gtk_recent_chooser_set_current_uri ()

gboolean            gtk_recent_chooser_set_current_uri  (GtkRecentChooser *chooser,
                                                         const gchar *uri,
                                                         GError **error);

Sets uri as the current URI for chooser.

chooser : | a GtkRecentChooser
uri : | a URI
error : | return location for a GError, or NULL
Returns : | TRUE if the URI was found.

Since 2.10

gtk_recent_chooser_get_current_uri ()

gchar*              gtk_recent_chooser_get_current_uri  (GtkRecentChooser *chooser);

Gets the URI currently selected by chooser.

chooser : | a GtkRecentChooser
Returns : | a newly allocated string holding a URI.

Since 2.10

gtk_recent_chooser_get_current_item ()

GtkRecentInfo*      gtk_recent_chooser_get_current_item (GtkRecentChooser *chooser);

Gets the GtkRecentInfo currently selected by chooser.

chooser : | a GtkRecentChooser
Returns : | a GtkRecentInfo. Use gtk_recent_info_unref() when when you have finished using it.

Since 2.10

gtk_recent_chooser_select_uri ()

gboolean            gtk_recent_chooser_select_uri       (GtkRecentChooser *chooser,
                                                         const gchar *uri,
                                                         GError **error);

Selects uri inside chooser.

chooser : | a GtkRecentChooser
uri : | a URI
error : | return location for a GError, or NULL
Returns : | TRUE if uri was found.

Since 2.10

gtk_recent_chooser_unselect_uri ()

void                gtk_recent_chooser_unselect_uri     (GtkRecentChooser *chooser,
                                                         const gchar *uri);

Unselects uri inside chooser.

chooser : | a GtkRecentChooser
uri : | a URI

Since 2.10

gtk_recent_chooser_select_all ()

void                gtk_recent_chooser_select_all       (GtkRecentChooser *chooser);

Selects all the items inside chooser, if the chooser supports multiple selection.

chooser : a GtkRecentChooser

Since 2.10

gtk_recent_chooser_unselect_all ()

void                gtk_recent_chooser_unselect_all     (GtkRecentChooser *chooser);

Unselects all the items inside chooser.

chooser : a GtkRecentChooser

Since 2.10

gtk_recent_chooser_get_items ()

GList*              gtk_recent_chooser_get_items        (GtkRecentChooser *chooser);

Gets the list of recently used resources in form of GtkRecentInfo objects.

The return value of this function is affected by the "sort-type" and "limit" properties of chooser.

chooser : | a GtkRecentChooser
Returns : | A newly allocated list of GtkRecentInfo objects. You should use gtk_recent_info_unref() on every item of the list, and then free the list itself using g_list_free().

Since 2.10

gtk_recent_chooser_get_uris ()

gchar**             gtk_recent_chooser_get_uris         (GtkRecentChooser *chooser,
                                                         gsize *length);

Gets the URI of the recently used resources.

The return value of this function is affected by the "sort-type" and "limit" properties of chooser.

Since the returned array is NULL terminated, length may be NULL.

chooser : | a GtkRecentChooser
length : | return location for a the length of the URI list, or NULL
Returns : | A newly allocated, NULL terminated array of strings. Use g_strfreev() to free it.

Since 2.10

gtk_recent_chooser_add_filter ()

void                gtk_recent_chooser_add_filter       (GtkRecentChooser *chooser,
                                                         GtkRecentFilter *filter);

Adds filter to the list of GtkRecentFilter objects held by chooser.

If no previous filter objects were defined, this function will call gtk_recent_chooser_set_filter().

chooser : | a GtkRecentChooser
filter : | a GtkRecentFilter

Since 2.10

gtk_recent_chooser_remove_filter ()

void                gtk_recent_chooser_remove_filter    (GtkRecentChooser *chooser,
                                                         GtkRecentFilter *filter);

Removes filter from the list of GtkRecentFilter objects held by chooser.

chooser : | a GtkRecentChooser
filter : | a GtkRecentFilter

Since 2.10

gtk_recent_chooser_list_filters ()

GSList*             gtk_recent_chooser_list_filters     (GtkRecentChooser *chooser);

Gets the GtkRecentFilter objects held by chooser.

chooser : | a GtkRecentChooser
Returns : | A singly linked list of GtkRecentFilter objects. You should just free the returned list using g_slist_free().

Since 2.10

gtk_recent_chooser_set_filter ()

void                gtk_recent_chooser_set_filter       (GtkRecentChooser *chooser,
                                                         GtkRecentFilter *filter);

Sets filter as the current GtkRecentFilter object used by chooser to affect the displayed recently used resources.

chooser : | a GtkRecentChooser
filter : | a GtkRecentFilter

Since 2.10

gtk_recent_chooser_get_filter ()

GtkRecentFilter*    gtk_recent_chooser_get_filter       (GtkRecentChooser *chooser);

Gets the GtkRecentFilter object currently used by chooser to affect the display of the recently used resources.

chooser : | a GtkRecentChooser
Returns : | a GtkRecentFilter object.

Since 2.10

Signal Details

The "item-activated" signal

void                user_function                      (GtkRecentChooser *chooser,
                                                        gpointer          user_data)      : Run Last

This signal is emitted when the user "activates" a recent item in the recent chooser. This can happen by double-clicking on an item in the recently used resources list, or by pressing Enter.

chooser : | the object which received the signal
user_data : | user data set when the signal handler was connected.

Since 2.10

The "selection-changed" signal

void                user_function                      (GtkRecentChooser *chooser,
                                                        gpointer          user_data)      : Run Last

This signal is emitted when there is a change in the set of selected recently used resources. This can happen when a user modifies the selection with the mouse or the keyboard, or when explicitely calling functions to change the selection.

chooser : | the object which received the signal
user_data : | user data set when the signal handler was connected.

Since 2.10

See Also

GtkRecentManager, GtkRecentChooserDialog, GtkRecentChooserWidget, GtkRecentChooserMenu


GtkRecentChooserDialog

GtkRecentChooserDialog — Displays recently used files in a dialog

Synopsis

#include <gtk/gtk.h>

                    GtkRecentChooserDialog;
GtkWidget*          gtk_recent_chooser_dialog_new       (const gchar *title,
                                                         GtkWindow *parent,
                                                         const gchar *first_button_text,
                                                         ...);
GtkWidget*          gtk_recent_chooser_dialog_new_for_manager
                                                        (const gchar *title,
                                                         GtkWindow *parent,
                                                         GtkRecentManager *manager,
                                                         const gchar *first_button_text,
                                                         ...);

Object Hierarchy

  GObject
   +----GInitiallyUnowned
         +----GtkObject
               +----GtkWidget
                     +----GtkContainer
                           +----GtkBin
                                 +----GtkWindow
                                       +----GtkDialog
                                             +----GtkRecentChooserDialog

Implemented Interfaces

GtkRecentChooserDialog implements AtkImplementorIface and GtkRecentChooser.

Description

GtkRecentChooserDialog is a dialog box suitable for displaying the recently used documents. This widgets works by putting a GtkRecentChooserWidget inside a GtkDialog. It exposes the GtkRecentChooserIface interface, so you can use all the GtkRecentChooser functions on the recent chooser dialog as well as those for GtkDialog.

Note that GtkRecentChooserDialog does not have any methods of its own. Instead, you should use the functions that work on a GtkRecentChooser.

Example 37. Typical usage

In the simplest of cases, you can use the following code to use a GtkRecentChooserDialog to select a recently used file:

GtkWidget *dialog;

dialog = gtk_recent_chooser_dialog_new ("Recent Documents",
                    parent_window,
                    GTK_STOCK_CANCEL, GTK_RESPONSE_CANCEL,
                    GTK_STOCK_OPEN, GTK_RESPONSE_ACCEPT,
                    NULL);

if (gtk_dialog_run (GTK_DIALOG (dialog)) == GTK_RESPONSE_ACCEPT)
  {
    GtkRecentInfo *info;

    info = gtk_recent_chooser_get_current_item (GTK_RECENT_CHOOSER (dialog));
    open_file (gtk_recent_info_get_uri (info));
    gtk_recent_info_unref (info);
  }

gtk_widget_destroy (dialog);

Recently used files are supported since GTK+ 2.10.

Details

GtkRecentChooserDialog

typedef struct _GtkRecentChooserDialog GtkRecentChooserDialog;

gtk_recent_chooser_dialog_new ()

GtkWidget*          gtk_recent_chooser_dialog_new       (const gchar *title,
                                                         GtkWindow *parent,
                                                         const gchar *first_button_text,
                                                         ...);

Creates a new GtkRecentChooserDialog. This function is analogous to gtk_dialog_new_with_buttons().

title : | Title of the dialog, or NULL
parent : | Transient parent of the dialog, or NULL,
first_button_text : | stock ID or text to go in the first button, or NULL
... : | response ID for the first button, then additional (button, id) pairs, ending with NULL
Returns : | a new GtkRecentChooserDialog

Since 2.10

gtk_recent_chooser_dialog_new_for_manager ()

GtkWidget*          gtk_recent_chooser_dialog_new_for_manager
                                                        (const gchar *title,
                                                         GtkWindow *parent,
                                                         GtkRecentManager *manager,
                                                         const gchar *first_button_text,
                                                         ...);

Creates a new GtkRecentChooserDialog with a specified recent manager.

This is useful if you have implemented your own recent manager, or if you have a customized instance of a GtkRecentManager object.

title : | Title of the dialog, or NULL
parent : | Transient parent of the dialog, or NULL,
manager : | a GtkRecentManager
first_button_text : | stock ID or text to go in the first button, or NULL
... : | response ID for the first button, then additional (button, id) pairs, ending with NULL
Returns : | a new GtkRecentChooserDialog

Since 2.10

See Also

GtkRecentChooser, GtkDialog


GtkRecentChooserMenu

GtkRecentChooserMenu — Displays recently used files in a menu

Synopsis

#include <gtk/gtk.h>

                    GtkRecentChooserMenu;
GtkWidget*          gtk_recent_chooser_menu_new         (void);
GtkWidget*          gtk_recent_chooser_menu_new_for_manager
                                                        (GtkRecentManager *manager);
gboolean            gtk_recent_chooser_menu_get_show_numbers
                                                        (GtkRecentChooserMenu *menu);
void                gtk_recent_chooser_menu_set_show_numbers
                                                        (GtkRecentChooserMenu *menu,
                                                         gboolean show_numbers);

Object Hierarchy

  GObject
   +----GInitiallyUnowned
         +----GtkObject
               +----GtkWidget
                     +----GtkContainer
                           +----GtkMenuShell
                                 +----GtkMenu
                                       +----GtkRecentChooserMenu

Implemented Interfaces

GtkRecentChooserMenu implements AtkImplementorIface and GtkRecentChooser.

Properties

  "show-numbers"             gboolean              : Read / Write

Description

GtkRecentChooserMenu is a widget suitable for displaying recently used files inside a menu. It can be used to set a sub-menu of a GtkMenuItem using gtk_menu_item_set_submenu(), or as the menu of a GtkMenuToolButton.

Note that GtkRecentChooserMenu does not have any methods of its own. Instead, you should use the functions that work on a GtkRecentChooser.

Note also that GtkRecentChooserMenu does not support multiple filters, as it has no way to let the user choose between them as the GtkRecentChooserWidget and GtkRecentChooserDialog widgets do. Thus using gtk_recent_chooser_add_filter() on a GtkRecentChooserMenu widget will yield the same effects as using gtk_recent_chooser_set_filter(), replacing any currently set filter with the supplied filter; gtk_recent_chooser_remove_filter() will remove any currently set GtkRecentFilter object and will unset the current filter; gtk_recent_chooser_list_filters() will return a list containing a single GtkRecentFilter object.

Recently used files are supported since GTK+ 2.10.

Details

GtkRecentChooserMenu

typedef struct _GtkRecentChooserMenu GtkRecentChooserMenu;

gtk_recent_chooser_menu_new ()

GtkWidget*          gtk_recent_chooser_menu_new         (void);

Creates a new GtkRecentChooserMenu widget.

This kind of widget shows the list of recently used resources as a menu, each item as a menu item. Each item inside the menu might have an icon, representing its MIME type, and a number, for mnemonic access.

This widget implements the GtkRecentChooser interface.

This widget creates its own GtkRecentManager object. See the gtk_recent_chooser_menu_new_for_manager() function to know how to create a GtkRecentChooserMenu widget bound to another GtkRecentManager object.

Returns : a new GtkRecentChooserMenu

Since 2.10

gtk_recent_chooser_menu_new_for_manager ()

GtkWidget*          gtk_recent_chooser_menu_new_for_manager
                                                        (GtkRecentManager *manager);

Creates a new GtkRecentChooserMenu widget using manager as the underlying recently used resources manager.

This is useful if you have implemented your own recent manager, or if you have a customized instance of a GtkRecentManager object or if you wish to share a common GtkRecentManager object among multiple GtkRecentChooser widgets.

manager : | a GtkRecentManager
Returns : | a new GtkRecentChooserMenu, bound to manager.

Since 2.10

gtk_recent_chooser_menu_get_show_numbers ()

gboolean            gtk_recent_chooser_menu_get_show_numbers
                                                        (GtkRecentChooserMenu *menu);

Returns the value set by gtk_recent_chooser_menu_set_show_numbers().

menu : | a GtkRecentChooserMenu
Returns : | TRUE if numbers should be shown.

Since 2.10

gtk_recent_chooser_menu_set_show_numbers ()

void                gtk_recent_chooser_menu_set_show_numbers
                                                        (GtkRecentChooserMenu *menu,
                                                         gboolean show_numbers);

Sets whether a number should be added to the items of menu. The numbers are shown to provide a unique character for a mnemonic to be used inside the menu item's label. Only the first the items get a number to avoid clashes.

menu : | a GtkRecentChooserMenu
show_numbers : | whether to show numbers

Since 2.10

Property Details

The "show-numbers" property

  "show-numbers"             gboolean              : Read / Write

Whether the first ten items in the menu should be prepended by a number acting as a unique mnemonic.

Default value: FALSE

Since 2.10

See Also

GtkRecentChooser


GtkRecentChooserWidget

GtkRecentChooserWidget — Displays recently used files

Synopsis

#include <gtk/gtk.h>

                    GtkRecentChooserWidget;
GtkWidget*          gtk_recent_chooser_widget_new       (void);
GtkWidget*          gtk_recent_chooser_widget_new_for_manager
                                                        (GtkRecentManager *manager);

Object Hierarchy

  GObject
   +----GInitiallyUnowned
         +----GtkObject
               +----GtkWidget
                     +----GtkContainer
                           +----GtkBox
                                 +----GtkVBox
                                       +----GtkRecentChooserWidget

Implemented Interfaces

GtkRecentChooserWidget implements AtkImplementorIface and GtkRecentChooser.

Description

GtkRecentChooserWidget is a widget suitable for selecting recently used files. It is the main building block of a GtkRecentChooserDialog. Most applications will only need to use the latter; you can use GtkRecentChooserWidget as part of a larger window if you have special needs.

Note that GtkRecentChooserWidget does not have any methods of its own. Instead, you should use the functions that work on a GtkRecentChooser.

Recently used files are supported since GTK+ 2.10.

Details

GtkRecentChooserWidget

typedef struct _GtkRecentChooserWidget GtkRecentChooserWidget;

gtk_recent_chooser_widget_new ()

GtkWidget*          gtk_recent_chooser_widget_new       (void);

Creates a new GtkRecentChooserWidget object. This is an embeddable widget used to access the recently used resources list.

Returns : a new GtkRecentChooserWidget

Since 2.10

gtk_recent_chooser_widget_new_for_manager ()

GtkWidget*          gtk_recent_chooser_widget_new_for_manager
                                                        (GtkRecentManager *manager);

Creates a new GtkRecentChooserWidget with a specified recent manager.

This is useful if you have implemented your own recent manager, or if you have a customized instance of a GtkRecentManager object.

manager : | a GtkRecentManager
Returns : | a new GtkRecentChooserWidget

Since 2.10

See Also

GtkRecentChooser, GtkRecentChooserDialog


GtkRecentFilter

GtkRecentFilter — A filter for selecting a subset of recently used files

Synopsis

#include <gtk/gtk.h>

                    GtkRecentFilter;
                    GtkRecentFilterInfo;
enum                GtkRecentFilterFlags;
gboolean            (*GtkRecentFilterFunc)              (const GtkRecentFilterInfo *filter_info,
                                                         gpointer user_data);
GtkRecentFilter*    gtk_recent_filter_new               (void);
const gchar*        gtk_recent_filter_get_name          (GtkRecentFilter *filter);
void                gtk_recent_filter_set_name          (GtkRecentFilter *filter,
                                                         const gchar *name);
void                gtk_recent_filter_add_mime_type     (GtkRecentFilter *filter,
                                                         const gchar *mime_type);
void                gtk_recent_filter_add_pattern       (GtkRecentFilter *filter,
                                                         const gchar *pattern);
void                gtk_recent_filter_add_pixbuf_formats
                                                        (GtkRecentFilter *filter);
void                gtk_recent_filter_add_application   (GtkRecentFilter *filter,
                                                         const gchar *application);
void                gtk_recent_filter_add_group         (GtkRecentFilter *filter,
                                                         const gchar *group);
void                gtk_recent_filter_add_age           (GtkRecentFilter *filter,
                                                         gint days);
void                gtk_recent_filter_add_custom        (GtkRecentFilter *filter,
                                                         GtkRecentFilterFlags needed,
                                                         GtkRecentFilterFunc func,
                                                         gpointer data,
                                                         GDestroyNotify data_destroy);
GtkRecentFilterFlags gtk_recent_filter_get_needed       (GtkRecentFilter *filter);
gboolean            gtk_recent_filter_filter            (GtkRecentFilter *filter,
                                                         const GtkRecentFilterInfo *filter_info);

Object Hierarchy

  GObject
   +----GInitiallyUnowned
         +----GtkObject
               +----GtkRecentFilter

Description

A GtkRecentFilter can be used to restrict the files being shown in a GtkRecentChooser. Files can be filtered based on their name (with gtk_recent_filter_add_pattern()), on their mime type (with gtk_file_filter_add_mime_type()), on the application that has registered them (with gtk_recent_filter_add_application()), or by a custom filter function (with gtk_recent_filter_add_custom()).

Filtering by mime type handles aliasing and subclassing of mime types; e.g. a filter for text/plain also matches a file with mime type application/rtf, since application/rtf is a subclass of text/plain. Note that GtkRecentFilter allows wildcards for the subtype of a mime type, so you can e.g. filter for image/*.

Normally, filters are used by adding them to a GtkRecentChooser, see gtk_recent_chooser_add_filter(), but it is also possible to manually use a filter on a file with gtk_recent_filter_filter().

Recently used files are supported since GTK+ 2.10.

Details

GtkRecentFilter

typedef struct _GtkRecentFilter GtkRecentFilter;

The GtkRecentFilter struct contains only private fields and should not be directly accessed.

GtkRecentFilterInfo

typedef struct {
  GtkRecentFilterFlags contains;

  const gchar *uri;
  const gchar *display_name;
  const gchar *mime_type;
  const gchar **applications;
  const gchar **groups;

  gint age;
} GtkRecentFilterInfo;

A GtkRecentFilterInfo struct is used to pass information about the tested file to gtk_recent_filter_filter().

GtkRecentFilterFlags contains; | Flags indicating which of the following fields need are filled
const gchar *uri; | the URI of the file being tested
const gchar *display_name; | the string that will be used to display the file in the recent chooser
const gchar *mime_type; | the mime type of the file
const gchar **applications; | the list of applications that have registered the file
const gchar **groups; | the groups to which the file belongs to
gint age; | the number of days elapsed since the file has been registered

enum GtkRecentFilterFlags

typedef enum {
  GTK_RECENT_FILTER_URI          = 1 << 0,
  GTK_RECENT_FILTER_DISPLAY_NAME = 1 << 1,
  GTK_RECENT_FILTER_MIME_TYPE    = 1 << 2,
  GTK_RECENT_FILTER_APPLICATION  = 1 << 3,
  GTK_RECENT_FILTER_GROUP        = 1 << 4,
  GTK_RECENT_FILTER_AGE          = 1 << 5
} GtkRecentFilterFlags;

These flags indicate what parts of a GtkRecentFilterInfo struct are filled or need to be filled.

GTK_RECENT_FILTER_URI | the URI of the file being tested
GTK_RECENT_FILTER_DISPLAY_NAME | the string that will be used to display the file in the recent chooser
GTK_RECENT_FILTER_MIME_TYPE | the mime type of the file
GTK_RECENT_FILTER_APPLICATION | the list of applications that have registered the file
GTK_RECENT_FILTER_GROUP | the groups to which the file belongs to
GTK_RECENT_FILTER_AGE | the number of days elapsed since the file has been registered

GtkRecentFilterFunc ()

gboolean            (*GtkRecentFilterFunc)              (const GtkRecentFilterInfo *filter_info,
                                                         gpointer user_data);

The type of function that is used with custom filters, see gtk_recent_filter_add_custom().

filter_info : | a GtkRecentFilterInfo that is filled according to the needed flags passed to gtk_recent_filter_add_custom()
user_data : | user data passed to gtk_recent_filter_add_custom()
Returns : | TRUE if the file should be displayed

gtk_recent_filter_new ()

GtkRecentFilter*    gtk_recent_filter_new               (void);

Creates a new GtkRecentFilter with no rules added to it. Such filter does not accept any recently used resources, so is not particularly useful until you add rules with gtk_recent_filter_add_pattern(), gtk_recent_filter_add_mime_type(), gtk_recent_filter_add_application(), gtk_recent_filter_add_age(). To create a filter that accepts any recently used resource, use:

GtkRecentFilter *filter = gtk_recent_filter_new ();
gtk_recent_filter_add_pattern (filter, "*");

Returns : a new GtkRecentFilter

Since 2.10

gtk_recent_filter_get_name ()

const gchar*        gtk_recent_filter_get_name          (GtkRecentFilter *filter);

Gets the human-readable name for the filter. See gtk_recent_filter_set_name().

filter : | a GtkRecentFilter
Returns : | the name of the filter, or NULL. The returned string is owned by the filter object and should not be freed.

Since 2.10

gtk_recent_filter_set_name ()

void                gtk_recent_filter_set_name          (GtkRecentFilter *filter,
                                                         const gchar *name);

Sets the human-readable name of the filter; this is the string that will be displayed in the recently used resources selector user interface if there is a selectable list of filters.

filter : | a GtkRecentFilter
name : | then human readable name of filter

Since 2.10

gtk_recent_filter_add_mime_type ()

void                gtk_recent_filter_add_mime_type     (GtkRecentFilter *filter,
                                                         const gchar *mime_type);

Adds a rule that allows resources based on their registered MIME type.

filter : | a GtkRecentFilter
mime_type : | a MIME type

Since 2.10

gtk_recent_filter_add_pattern ()

void                gtk_recent_filter_add_pattern       (GtkRecentFilter *filter,
                                                         const gchar *pattern);

Adds a rule that allows resources based on a pattern matching their display name.

filter : | a GtkRecentFilter
pattern : | a file pattern

Since 2.10

gtk_recent_filter_add_pixbuf_formats ()

void                gtk_recent_filter_add_pixbuf_formats
                                                        (GtkRecentFilter *filter);

Adds a rule allowing image files in the formats supported by GdkPixbuf.

filter : a GtkRecentFilter

Since 2.10

gtk_recent_filter_add_application ()

void                gtk_recent_filter_add_application   (GtkRecentFilter *filter,
                                                         const gchar *application);

Adds a rule that allows resources based on the name of the application that has registered them.

filter : | a GtkRecentFilter
application : | an application name

Since 2.10

gtk_recent_filter_add_group ()

void                gtk_recent_filter_add_group         (GtkRecentFilter *filter,
                                                         const gchar *group);

Adds a rule that allows resources based on the name of the group to which they belong

filter : | a GtkRecentFilter
group : | a group name

Since 2.10

gtk_recent_filter_add_age ()

void                gtk_recent_filter_add_age           (GtkRecentFilter *filter,
                                                         gint days);

Adds a rule that allows resources based on their age - that is, the number of days elapsed since they were last modified.

filter : | a GtkRecentFilter
days : | number of days

Since 2.10

gtk_recent_filter_add_custom ()

void                gtk_recent_filter_add_custom        (GtkRecentFilter *filter,
                                                         GtkRecentFilterFlags needed,
                                                         GtkRecentFilterFunc func,
                                                         gpointer data,
                                                         GDestroyNotify data_destroy);

Adds a rule to a filter that allows resources based on a custom callback function. The bitfield needed which is passed in provides information about what sorts of information that the filter function needs; this allows GTK+ to avoid retrieving expensive information when it isn't needed by the filter.

filter : | a GtkRecentFilter
needed : | bitfield of flags indicating the information that the custom filter function needs.
func : | callback function; if the function returns TRUE, then the file will be displayed.
data : | data to pass to func
data_destroy : | function to call to free data when it is no longer needed.

Since 2.10

gtk_recent_filter_get_needed ()

GtkRecentFilterFlags gtk_recent_filter_get_needed       (GtkRecentFilter *filter);

Gets the fields that need to be filled in for the structure passed to gtk_recent_filter_filter()

This function will not typically be used by applications; it is intended principally for use in the implementation of GtkRecentChooser.

filter : | a GtkRecentFilter
Returns : | bitfield of flags indicating needed fields when calling gtk_recent_filter_filter()

Since 2.10

gtk_recent_filter_filter ()

gboolean            gtk_recent_filter_filter            (GtkRecentFilter *filter,
                                                         const GtkRecentFilterInfo *filter_info);

Tests whether a file should be displayed according to filter. The GtkRecentFilterInfo structure filter_info should include the fields returned from gtk_recent_filter_get_needed().

This function will not typically be used by applications; it is intended principally for use in the implementation of GtkRecentChooser.

filter : | a GtkRecentFilter
filter_info : | a GtkRecentFilterInfo structure containing information about a recently used resource
Returns : | TRUE if the file should be displayed

Since 2.10

See Also

GtkRecentChooser


GtkRecentManager

GtkRecentManager — Managing Recently Used Files

Synopsis

#include <gtk/gtk.h>

                    GtkRecentManager;
                    GtkRecentInfo;
                    GtkRecentData;
#define             GTK_RECENT_MANAGER_ERROR
enum                GtkRecentManagerError;
GtkRecentManager*   gtk_recent_manager_new              (void);
GtkRecentManager*   gtk_recent_manager_get_default      (void);
GtkRecentManager*   gtk_recent_manager_get_for_screen   (GdkScreen *screen);
void                gtk_recent_manager_set_screen       (GtkRecentManager *manager,
                                                         GdkScreen *screen);
gboolean            gtk_recent_manager_add_item         (GtkRecentManager *manager,
                                                         const gchar *uri);
gboolean            gtk_recent_manager_add_full         (GtkRecentManager *manager,
                                                         const gchar *uri,
                                                         const GtkRecentData *recent_data);
gboolean            gtk_recent_manager_remove_item      (GtkRecentManager *manager,
                                                         const gchar *uri,
                                                         GError **error);
GtkRecentInfo*      gtk_recent_manager_lookup_item      (GtkRecentManager *manager,
                                                         const gchar *uri,
                                                         GError **error);
gboolean            gtk_recent_manager_has_item         (GtkRecentManager *manager,
                                                         const gchar *uri);
gboolean            gtk_recent_manager_move_item        (GtkRecentManager *manager,
                                                         const gchar *uri,
                                                         const gchar *new_uri,
                                                         GError **error);
gint                gtk_recent_manager_get_limit        (GtkRecentManager *manager);
void                gtk_recent_manager_set_limit        (GtkRecentManager *manager,
                                                         gint limit);
GList*              gtk_recent_manager_get_items        (GtkRecentManager *manager);
gint                gtk_recent_manager_purge_items      (GtkRecentManager *manager,
                                                         GError **error);

GtkRecentInfo*      gtk_recent_info_ref                 (GtkRecentInfo *info);
void                gtk_recent_info_unref               (GtkRecentInfo *info);
const gchar*        gtk_recent_info_get_uri             (GtkRecentInfo *info);
const gchar*        gtk_recent_info_get_display_name    (GtkRecentInfo *info);
const gchar*        gtk_recent_info_get_description     (GtkRecentInfo *info);
const gchar*        gtk_recent_info_get_mime_type       (GtkRecentInfo *info);
time_t              gtk_recent_info_get_added           (GtkRecentInfo *info);
time_t              gtk_recent_info_get_modified        (GtkRecentInfo *info);
time_t              gtk_recent_info_get_visited         (GtkRecentInfo *info);
gboolean            gtk_recent_info_get_private_hint    (GtkRecentInfo *info);
gboolean            gtk_recent_info_get_application_info
                                                        (GtkRecentInfo *info,
                                                         const gchar *app_name,
                                                         gchar **app_exec,
                                                         guint *count,
                                                         time_t *time_);
gchar**             gtk_recent_info_get_applications    (GtkRecentInfo *info,
                                                         gsize *length);
gchar*              gtk_recent_info_last_application    (GtkRecentInfo *info);
gchar**             gtk_recent_info_get_groups          (GtkRecentInfo *info,
                                                         gsize *length);
gboolean            gtk_recent_info_has_group           (GtkRecentInfo *info,
                                                         const gchar *group_name);
gboolean            gtk_recent_info_has_application     (GtkRecentInfo *info,
                                                         const gchar *app_name);
GdkPixbuf*          gtk_recent_info_get_icon            (GtkRecentInfo *info,
                                                         gint size);
gchar*              gtk_recent_info_get_short_name      (GtkRecentInfo *info);
gchar*              gtk_recent_info_get_uri_display     (GtkRecentInfo *info);
gint                gtk_recent_info_get_age             (GtkRecentInfo *info);
gboolean            gtk_recent_info_is_local            (GtkRecentInfo *info);
gboolean            gtk_recent_info_exists              (GtkRecentInfo *info);
gboolean            gtk_recent_info_match               (GtkRecentInfo *info_a,
                                                         GtkRecentInfo *info_b);

Object Hierarchy

  GObject
   +----GtkRecentManager

Properties

  "filename"                 gchararray            : Read / Write / Construct Only
  "limit"                    gint                  : Read / Write
  "size"                     gint                  : Read

Signals

  "changed"                                        : Run First

Description

GtkRecentManager provides a facility for adding, removing and looking up recently used files. Each recently used file is identified by its URI, and has meta-data associated to it, like the names and command lines of the applications that have registered it, the number of time each application has registered the same file, the mime type of the file and whether the file should be displayed only by the applications that have registered it.

The GtkRecentManager acts like a database of all the recently used files. You can create new GtkRecentManager objects, but it is more efficient to use the standard recent manager for the GdkScreen so that informations about the recently used files is shared with other people using them. In case the default screen is being used, adding a new recently used file is as simple as:

GtkRecentManager *manager;

manager = gtk_recent_manager_get_default ();
gtk_recent_manager_add_item (manager, file_uri);
While looking up a recently used file is as simple as:
GtkRecentManager *manager;
GtkRecentInfo *info;
GError *error = NULL;

manager = gtk_recent_manager_get_default ();
info = gtk_recent_manager_lookup_item (manager, file_uri, &error);
if (error)
  {
    g_warning ("Could not find the file: %s", error->message);
    g_error_free (error);
  }
else
  {
    /* Use the info object */
    gtk_recent_info_unref (info);
  }

Recently used files are supported since GTK+ 2.10.

Details

GtkRecentManager

typedef struct _GtkRecentManager GtkRecentManager;

Acts as a database of information about the list of recently used files. Normally, you retrieve the recent manager for a particular screen using gtk_recent_manager_get_for_screen() and it will contain information about current recent manager for that screen.

GtkRecentInfo

typedef struct _GtkRecentInfo GtkRecentInfo;

Contains informations found when looking up an entry of the recently used files list.

GtkRecentData

typedef struct {
  gchar *display_name;
  gchar *description;

  gchar *mime_type;

  gchar *app_name;
  gchar *app_exec;

  gchar **groups;

  gboolean is_private;
} GtkRecentData;

Meta-data to be passed to gtk_recent_manager_add_full() when registering a recently used resource.

Meta-data passed to gtk_recent_manager_add_full(). You should use GtkRecentData if you want to control the meta-data associated to an entry of the recently used files list when you are adding a new file to it.

gchar *display_name; | a UTF-8 encoded string, containing the name of the recently used resource to be displayed, or NULL;
gchar *description; | a UTF-8 encoded string, containing a short description of the resource, or NULL;
gchar *mime_type; | the MIME type of the resource;
gchar *app_name; | the name of the application that is registering this recently used resource;
gchar *app_exec; | command line used to launch this resource; may contain the "f" and "u" escape characters which will be expanded to the resource file path and URI respectively when the command line is retrieved;
gchar **groups; | a vector of strings containing groups names;
gboolean is_private; | whether this resource should be displayed only by the applications that have registered it or not.

GTK_RECENT_MANAGER_ERROR

#define GTK_RECENT_MANAGER_ERROR	(gtk_recent_manager_error_quark ())

The GQuark used for GtkRecentManagerError errors.

enum GtkRecentManagerError

typedef enum
{
  GTK_RECENT_MANAGER_ERROR_NOT_FOUND,
  GTK_RECENT_MANAGER_ERROR_INVALID_URI,
  GTK_RECENT_MANAGER_ERROR_INVALID_ENCODING,
  GTK_RECENT_MANAGER_ERROR_NOT_REGISTERED,
  GTK_RECENT_MANAGER_ERROR_READ,
  GTK_RECENT_MANAGER_ERROR_WRITE,
  GTK_RECENT_MANAGER_ERROR_UNKNOWN
} GtkRecentManagerError;

Error codes for GtkRecentManager operations

GTK_RECENT_MANAGER_ERROR_NOT_FOUND | the URI specified does not exists in the recently used resources list.
GTK_RECENT_MANAGER_ERROR_INVALID_URI | the URI specified is not valid.
GTK_RECENT_MANAGER_ERROR_INVALID_ENCODING | the supplied string is not UTF-8 encoded.
GTK_RECENT_MANAGER_ERROR_NOT_REGISTERED | no application has registered the specified item.
GTK_RECENT_MANAGER_ERROR_READ | failure while reading the recently used resources file.
GTK_RECENT_MANAGER_ERROR_WRITE | failure while writing the recently used resources file.
GTK_RECENT_MANAGER_ERROR_UNKNOWN | unspecified error.

gtk_recent_manager_new ()

GtkRecentManager*   gtk_recent_manager_new              (void);

Creates a new recent manager object. Recent manager objects are used to handle the list of recently used resources. A GtkRecentManager object monitors the recently used resources list, and emits the "changed" signal each time something inside the list changes.

GtkRecentManager objects are expensive: be sure to create them only when needed. You should use the gtk_recent_manager_new_for_screen() or the gtk_recent_manager_get_default() functions instead.

Returns : A newly created GtkRecentManager object.

Since 2.10

gtk_recent_manager_get_default ()

GtkRecentManager*   gtk_recent_manager_get_default      (void);

Gets the recent manager for the default screen. See gtk_recent_manager_get_for_screen().

Returns : A unique GtkRecentManager associated with the default screen. This recent manager is associated to the screen and can be used as long as the screen is open. Do no ref or unref it.

Since 2.10

gtk_recent_manager_get_for_screen ()

GtkRecentManager*   gtk_recent_manager_get_for_screen   (GdkScreen *screen);

Gets the recent manager object associated with screen; if this function has not previously been called for the given screen, a new recent manager object will be created and associated with the screen. Recent manager objects are fairly expensive to create, so using this function is usually a better choice than calling gtk_recent_manager_new() and setting the screen yourself; by using this function a single recent manager object will be shared between users.

screen : | a GdkScreen
Returns : | A unique GtkRecentManager associated with the given screen. This recent manager is associated to the with the screen and can be used as long as the screen is open. Do not ref or unref it.

Since 2.10

gtk_recent_manager_set_screen ()

void                gtk_recent_manager_set_screen       (GtkRecentManager *manager,
                                                         GdkScreen *screen);

Sets the screen for a recent manager; the screen is used to track the user's currently configured recently used documents storage.

manager : | a GtkRecentManager
screen : | a GdkScreen

Since 2.10

gtk_recent_manager_add_item ()

gboolean            gtk_recent_manager_add_item         (GtkRecentManager *manager,
                                                         const gchar *uri);

Adds a new resource, pointed by uri, into the recently used resources list.

This function automatically retrieving some of the needed metadata and setting other metadata to common default values; it then feeds the data to gtk_recent_manager_add_full().

See gtk_recent_manager_add_full() if you want to explicitely define the metadata for the resource pointed by uri.

manager : | a GtkRecentManager
uri : | a valid URI
Returns : | TRUE if the new item was successfully added to the recently used resources list

Since 2.10

gtk_recent_manager_add_full ()

gboolean            gtk_recent_manager_add_full         (GtkRecentManager *manager,
                                                         const gchar *uri,
                                                         const GtkRecentData *recent_data);

Adds a new resource, pointed by uri, into the recently used resources list, using the metadata specified inside the GtkRecentData structure passed in recent_data.

The passed URI will be used to identify this resource inside the list.

In order to register the new recently used resource, metadata about the resource must be passed as well as the URI; the metadata is stored in a GtkRecentData structure, which must contain the MIME type of the resource pointed by the URI; the name of the application that is registering the item, and a command line to be used when launching the item.

Optionally, a GtkRecentData structure might contain a UTF-8 string to be used when viewing the item instead of the last component of the URI; a short description of the item; whether the item should be considered private - that is, should be displayed only by the applications that have registered it.

manager : | a GtkRecentManager
uri : | a valid URI
recent_data : | metadata of the resource
Returns : | TRUE if the new item was successfully added to the recently used resources list, FALSE otherwise.

Since 2.10

gtk_recent_manager_remove_item ()

gboolean            gtk_recent_manager_remove_item      (GtkRecentManager *manager,
                                                         const gchar *uri,
                                                         GError **error);

Removes a resource pointed by uri from the recently used resources list handled by a recent manager.

manager : | a GtkRecentManager
uri : | the URI of the item you wish to remove
error : | return location for a GError, or NULL
Returns : | TRUE if the item pointed by uri has been successfully removed by the recently used resources list, and FALSE otherwise.

Since 2.10

gtk_recent_manager_lookup_item ()

GtkRecentInfo*      gtk_recent_manager_lookup_item      (GtkRecentManager *manager,
                                                         const gchar *uri,
                                                         GError **error);

Searches for a URI inside the recently used resources list, and returns a structure containing informations about the resource like its MIME type, or its display name.

manager : | a GtkRecentManager
uri : | a URI
error : | a return location for a GError, or NULL
Returns : | a GtkRecentInfo structure containing information about the resource pointed by uri, or NULL if the URI was not registered in the recently used resources list. Free with gtk_recent_info_unref().

Since 2.10

gtk_recent_manager_has_item ()

gboolean            gtk_recent_manager_has_item         (GtkRecentManager *manager,
                                                         const gchar *uri);

Checks whether there is a recently used resource registered with uri inside the recent manager.

manager : | a GtkRecentManager
uri : | a URI
Returns : | TRUE if the resource was found, FALSE otherwise.

Since 2.10

gtk_recent_manager_move_item ()

gboolean            gtk_recent_manager_move_item        (GtkRecentManager *manager,
                                                         const gchar *uri,
                                                         const gchar *new_uri,
                                                         GError **error);

Changes the location of a recently used resource from uri to new_uri.

Please note that this function will not affect the resource pointed by the URIs, but only the URI used in the recently used resources list.

manager : | a GtkRecentManager
uri : | the URI of a recently used resource
new_uri : | the new URI of the recently used resource, or NULL to remove the item pointed by uri in the list
error : | a return location for a GError, or NULL
Returns : | TRUE on success.

Since 2.10

gtk_recent_manager_get_limit ()

gint                gtk_recent_manager_get_limit        (GtkRecentManager *manager);

Gets the maximum number of items that the gtk_recent_manager_get_items() function should return.

manager : | a GtkRecentManager
Returns : | the number of items to return, or -1 for every item.

Since 2.10

gtk_recent_manager_set_limit ()

void                gtk_recent_manager_set_limit        (GtkRecentManager *manager,
                                                         gint limit);

Sets the maximum number of item that the gtk_recent_manager_get_items() function should return. If limit is set to -1, then return all the items.

manager : | a GtkRecentManager
limit : | the maximum number of items to return, or -1.

Since 2.10

gtk_recent_manager_get_items ()

GList*              gtk_recent_manager_get_items        (GtkRecentManager *manager);

Gets the list of recently used resources.

manager : | a GtkRecentManager
Returns : | a list of newly allocated GtkRecentInfo objects. Use gtk_recent_info_unref() on each item inside the list, and then free the list itself using g_list_free().

Since 2.10

gtk_recent_manager_purge_items ()

gint                gtk_recent_manager_purge_items      (GtkRecentManager *manager,
                                                         GError **error);

Purges every item from the recently used resources list.

manager : | a GtkRecentManager
error : | a return location for a GError, or NULL
Returns : | the number of items that have been removed from the recently used resources list.

Since 2.10

gtk_recent_info_ref ()

GtkRecentInfo*      gtk_recent_info_ref                 (GtkRecentInfo *info);

Increases the reference count of recent_info by one.

info : | a GtkRecentInfo
Returns : | the recent info object with its reference count increased by one.

Since 2.10

gtk_recent_info_unref ()

void                gtk_recent_info_unref               (GtkRecentInfo *info);

Decreases the reference count of info by one. If the reference count reaches zero, info is deallocated, and the memory freed.

info : a GtkRecentInfo

Since 2.10

gtk_recent_info_get_uri ()

const gchar*        gtk_recent_info_get_uri             (GtkRecentInfo *info);

Gets the URI of the resource.

info : | a GtkRecentInfo
Returns : | the URI of the resource. The returned string is owned by the recent manager, and should not be freed.

Since 2.10

gtk_recent_info_get_display_name ()

const gchar*        gtk_recent_info_get_display_name    (GtkRecentInfo *info);

Gets the name of the resource. If none has been defined, the basename of the resource is obtained.

info : | a GtkRecentInfo
Returns : | the display name of the resource. The returned string is owned by the recent manager, and should not be freed.

Since 2.10

gtk_recent_info_get_description ()

const gchar*        gtk_recent_info_get_description     (GtkRecentInfo *info);

Gets the (short) description of the resource.

info : | a GtkRecentInfo
Returns : | the description of the resource. The returned string is owned by the recent manager, and should not be freed.

Since 2.10

gtk_recent_info_get_mime_type ()

const gchar*        gtk_recent_info_get_mime_type       (GtkRecentInfo *info);

Gets the MIME type of the resource.

info : | a GtkRecentInfo
Returns : | the MIME type of the resource. The returned string is owned by the recent manager, and should not be freed.

Since 2.10

gtk_recent_info_get_added ()

time_t              gtk_recent_info_get_added           (GtkRecentInfo *info);

Gets the timestamp (seconds from system's Epoch) when the resource was added to the recently used resources list.

info : | a GtkRecentInfo
Returns : | the number of seconds elapsed from system's Epoch when the resource was added to the list, or -1 on failure.

Since 2.10

gtk_recent_info_get_modified ()

time_t              gtk_recent_info_get_modified        (GtkRecentInfo *info);

Gets the timestamp (seconds from system's Epoch) when the resource was last modified.

info : | a GtkRecentInfo
Returns : | the number of seconds elapsed from system's Epoch when the resource was last modified, or -1 on failure.

Since 2.10

gtk_recent_info_get_visited ()

time_t              gtk_recent_info_get_visited         (GtkRecentInfo *info);

Gets the timestamp (seconds from system's Epoch) when the resource was last visited.

info : | a GtkRecentInfo
Returns : | the number of seconds elapsed from system's Epoch when the resource was last visited, or -1 on failure.

Since 2.10

gtk_recent_info_get_private_hint ()

gboolean            gtk_recent_info_get_private_hint    (GtkRecentInfo *info);

Gets the value of the "private" flag. Resources in the recently used list that have this flag set to TRUE should only be displayed by the applications that have registered them.

info : | a GtkRecentInfo
Returns : | TRUE if the private flag was found, FALSE otherwise.

Since 2.10

gtk_recent_info_get_application_info ()

gboolean            gtk_recent_info_get_application_info
                                                        (GtkRecentInfo *info,
                                                         const gchar *app_name,
                                                         gchar **app_exec,
                                                         guint *count,
                                                         time_t *time_);

Gets the data regarding the application that has registered the resource pointed by info.

If the command line contains any escape characters defined inside the storage specification, they will be expanded.

info : | a GtkRecentInfo
app_name : | the name of the application that has registered this item
app_exec : | return location for the string containing the command line
count : | return location for the number of times this item was registered
time_ : | return location for the timestamp this item was last registered for this application
Returns : | TRUE if an application with app_name has registered this resource inside the recently used list, or FALSE otherwise. You should free the returned command line using g_free().

Since 2.10

gtk_recent_info_get_applications ()

gchar**             gtk_recent_info_get_applications    (GtkRecentInfo *info,
                                                         gsize *length);

Retrieves the list of applications that have registered this resource.

info : | a GtkRecentInfo
length : | return location for the length of the returned list, or NULL
Returns : | a newly allocated NULL-terminated array of strings. Use g_strfreev() to free it.

Since 2.10

gtk_recent_info_last_application ()

gchar*              gtk_recent_info_last_application    (GtkRecentInfo *info);

Gets the name of the last application that have registered the recently used resource represented by info.

info : | a GtkRecentInfo
Returns : | an application name. Use g_free() to free it.

Since 2.10

gtk_recent_info_get_groups ()

gchar**             gtk_recent_info_get_groups          (GtkRecentInfo *info,
                                                         gsize *length);

Returns all groups registered for the recently used item info. The array of returned group names will be NULL terminated, so length might optionally be NULL.

info : | a GtkRecentInfo
length : | return location for the number of groups returned, or NULL
Returns : | a newly allocated NULL terminated array of strings. Use g_strfreev() to free it.

Since 2.10

gtk_recent_info_has_group ()

gboolean            gtk_recent_info_has_group           (GtkRecentInfo *info,
                                                         const gchar *group_name);

Checks whether group_name appears inside the groups registered for the recently used item info.

info : | a GtkRecentInfo
group_name : | name of a group
Returns : | TRUE if the group was found.

Since 2.10

gtk_recent_info_has_application ()

gboolean            gtk_recent_info_has_application     (GtkRecentInfo *info,
                                                         const gchar *app_name);

Checks whether an application registered this resource using app_name.

info : | a GtkRecentInfo
app_name : | a string containing an application name
Returns : | TRUE if an application with name app_name was found, FALSE otherwise.

Since 2.10

gtk_recent_info_get_icon ()

GdkPixbuf*          gtk_recent_info_get_icon            (GtkRecentInfo *info,
                                                         gint size);

Retrieves the icon of size size associated to the resource MIME type.

info : | a GtkRecentInfo
size : | the size of the icon in pixels
Returns : | a GdkPixbuf containing the icon, or NULL.

Since 2.10

gtk_recent_info_get_short_name ()

gchar*              gtk_recent_info_get_short_name      (GtkRecentInfo *info);

Computes a valid UTF-8 string that can be used as the name of the item in a menu or list. For example, calling this function on an item that refers to "file:///foo/bar.txt" will yield "bar.txt".

info : | an GtkRecentInfo
Returns : | A newly-allocated string in UTF-8 encoding; free it with g_free().

Since 2.10

gtk_recent_info_get_uri_display ()

gchar*              gtk_recent_info_get_uri_display     (GtkRecentInfo *info);

Gets a displayable version of the resource's URI.

info : | a GtkRecentInfo
Returns : | a UTF-8 string containing the resource's URI or NULL

Since 2.10

gtk_recent_info_get_age ()

gint                gtk_recent_info_get_age             (GtkRecentInfo *info);

Gets the number of days elapsed since the last update of the resource pointed by info.

info : | a GtkRecentInfo
Returns : | a positive integer containing the number of days elapsed since the time this resource was last modified.

Since 2.10

gtk_recent_info_is_local ()

gboolean            gtk_recent_info_is_local            (GtkRecentInfo *info);

Checks whether the resource is local or not by looking at the scheme of its URI.

info : | a GtkRecentInfo
Returns : | TRUE if the resource is local.

Since 2.10

gtk_recent_info_exists ()

gboolean            gtk_recent_info_exists              (GtkRecentInfo *info);

Checks whether the resource pointed by info still exists. At the moment this check is done only on resources pointing to local files.

info : | a GtkRecentInfo
Returns : | TRUE if the resource exists

Since 2.10

gtk_recent_info_match ()

gboolean            gtk_recent_info_match               (GtkRecentInfo *info_a,
                                                         GtkRecentInfo *info_b);

Checks whether two GtkRecentInfo structures point to the same resource.

info_a : | a GtkRecentInfo
info_b : | a GtkRecentInfo
Returns : | TRUE if both GtkRecentInfo structures point to se same resource, FALSE otherwise.

Since 2.10

Property Details

The "filename" property

  "filename"                 gchararray            : Read / Write / Construct Only

The full path to the file to be used to store and read the recently used resources list

Default value: NULL

Since 2.10

The "limit" property

  "limit"                    gint                  : Read / Write

The maximum number of items to be returned by the gtk_recent_manager_get_items() function.

Allowed values: >= -1

Default value: -1

Since 2.10

The "size" property

  "size"                     gint                  : Read

The size of the recently used resources list.

Allowed values: >= -1

Default value: 0

Since 2.10

Signal Details

The "changed" signal

void                user_function                      (GtkRecentManager *recent_manager,
                                                        gpointer          user_data)           : Run First

Emitted when the current recently used resources manager changes its contents.

recent_manager : | the recent manager
user_data : | user data set when the signal handler was connected.

Since 2.10


GtkRuler

GtkRuler — Base class for horizontal or vertical rulers

Synopsis

#include <gtk/gtk.h>

                    GtkRuler;
                    GtkRulerMetric;
void                gtk_ruler_set_metric                (GtkRuler *ruler,
                                                         GtkMetricType metric);
void                gtk_ruler_set_range                 (GtkRuler *ruler,
                                                         gdouble lower,
                                                         gdouble upper,
                                                         gdouble position,
                                                         gdouble max_size);
GtkMetricType       gtk_ruler_get_metric                (GtkRuler *ruler);
void                gtk_ruler_get_range                 (GtkRuler *ruler,
                                                         gdouble *lower,
                                                         gdouble *upper,
                                                         gdouble *position,
                                                         gdouble *max_size);

Object Hierarchy

  GObject
   +----GInitiallyUnowned
         +----GtkObject
               +----GtkWidget
                     +----GtkRuler
                           +----GtkHRuler
                           +----GtkVRuler

Implemented Interfaces

GtkRuler implements AtkImplementorIface.

Properties

  "lower"                    gdouble               : Read / Write
  "max-size"                 gdouble               : Read / Write
  "metric"                   GtkMetricType         : Read / Write
  "position"                 gdouble               : Read / Write
  "upper"                    gdouble               : Read / Write

Description

Note

This widget is considered too specialized/little-used for GTK+, and will in the future be moved to some other package. If your application needs this widget, feel free to use it, as the widget does work and is useful in some applications; it's just not of general interest. However, we are not accepting new features for the widget, and it will eventually move out of the GTK+ distribution.

The GTKRuler widget is a base class for horizontal and vertical rulers. Rulers are used to show the mouse pointer's location in a window. The ruler can either be horizontal or vertical on the window. Within the ruler a small triangle indicates the location of the mouse relative to the horizontal or vertical ruler. See GtkHRuler to learn how to create a new horizontal ruler. See GtkVRuler to learn how to create a new vertical ruler.

Details

GtkRuler

typedef struct _GtkRuler GtkRuler;

All distances are in 1/72nd's of an inch. (According to Adobe thats a point, but points are really 1/72.27 in.)

GtkRulerMetric

typedef struct {
  gchar *metric_name;
  gchar *abbrev;
  /* This should be points_per_unit. This is the size of the unit
   * in 1/72nd's of an inch and has nothing to do with screen pixels */
  gdouble pixels_per_unit;
  gdouble ruler_scale[10];
  gint subdivide[5];        /* five possible modes of subdivision */
} GtkRulerMetric;

This should be points_per_unit. This is the size of the unit in 1/72nd's of an inch and has nothing to do with screen pixels.

gtk_ruler_set_metric ()

void                gtk_ruler_set_metric                (GtkRuler *ruler,
                                                         GtkMetricType metric);

This calls the GTKMetricType to set the ruler to units defined. Available units are GTK_PIXELS, GTK_INCHES, or GTK_CENTIMETERS. The default unit of measurement is GTK_PIXELS.

ruler : | the gtkruler
metric : | the unit of measurement

gtk_ruler_set_range ()

void                gtk_ruler_set_range                 (GtkRuler *ruler,
                                                         gdouble lower,
                                                         gdouble upper,
                                                         gdouble position,
                                                         gdouble max_size);

This sets the range of the ruler using gfloat lower, gfloat upper, gfloat position, and gfloat max_size.

ruler : | the gtkruler
lower : | the lower limit of the ruler
upper : | the upper limit of the ruler
position : | the mark on the ruler
max_size : | the maximum size of the ruler

gtk_ruler_get_metric ()

GtkMetricType       gtk_ruler_get_metric                (GtkRuler *ruler);

Gets the units used for a GtkRuler. See gtk_ruler_set_metric().

ruler : | a GtkRuler
Returns : | the units currently used for ruler

gtk_ruler_get_range ()

void                gtk_ruler_get_range                 (GtkRuler *ruler,
                                                         gdouble *lower,
                                                         gdouble *upper,
                                                         gdouble *position,
                                                         gdouble *max_size);

Retrieves values indicating the range and current position of a GtkRuler. See gtk_ruler_set_range().

ruler : | a GtkRuler
lower : | location to store lower limit of the ruler, or NULL
upper : | location to store upper limit of the ruler, or NULL
position : | location to store the current position of the mark on the ruler, or NULL
max_size : | location to store the maximum size of the ruler used when calculating the space to leave for the text, or NULL.

Property Details

The "lower" property

  "lower"                    gdouble               : Read / Write

Lower limit of ruler.

Default value: 0

The "max-size" property

  "max-size"                 gdouble               : Read / Write

Maximum size of the ruler.

Default value: 0

The "metric" property

  "metric"                   GtkMetricType         : Read / Write

The metric used for the ruler.

Default value: GTK_PIXELS

Since 2.8

The "position" property

  "position"                 gdouble               : Read / Write

Position of mark on the ruler.

Default value: 0

The "upper" property

  "upper"                    gdouble               : Read / Write

Upper limit of ruler.

Default value: 0

See Also

GtkHRuler, GtkVRuler


GtkScale

GtkScale — Base class for GtkHScale and GtkVScale

Synopsis

#include <gtk/gtk.h>

                    GtkScale;
void                gtk_scale_set_digits                (GtkScale *scale,
                                                         gint digits);
void                gtk_scale_set_draw_value            (GtkScale *scale,
                                                         gboolean draw_value);
void                gtk_scale_set_value_pos             (GtkScale *scale,
                                                         GtkPositionType pos);
gint                gtk_scale_get_digits                (GtkScale *scale);
gboolean            gtk_scale_get_draw_value            (GtkScale *scale);
GtkPositionType     gtk_scale_get_value_pos             (GtkScale *scale);
PangoLayout*        gtk_scale_get_layout                (GtkScale *scale);
void                gtk_scale_get_layout_offsets        (GtkScale *scale,
                                                         gint *x,
                                                         gint *y);

Object Hierarchy

  GObject
   +----GInitiallyUnowned
         +----GtkObject
               +----GtkWidget
                     +----GtkRange
                           +----GtkScale
                                 +----GtkHScale
                                 +----GtkVScale

Implemented Interfaces

GtkScale implements AtkImplementorIface.

Properties

  "digits"                   gint                  : Read / Write
  "draw-value"               gboolean              : Read / Write
  "value-pos"                GtkPositionType       : Read / Write

Style Properties

  "slider-length"            gint                  : Read
  "value-spacing"            gint                  : Read

Signals

  "format-value"                                   : Run Last

Description

A GtkScale is a slider control used to select a numeric value. To use it, you'll probably want to investigate the methods on its base class, GtkRange, in addition to the methods for GtkScale itself. To set the value of a scale, you would normally use gtk_range_set_value(). To detect changes to the value, you would normally use the "value_changed" signal.

The GtkScale widget is an abstract class, used only for deriving the subclasses GtkHScale and GtkVScale. To create a scale widget, call gtk_hscale_new_with_range() or gtk_vscale_new_with_range().

Details

GtkScale

typedef struct _GtkScale GtkScale;

The GtkScale struct contains the following fields. (These fields should be considered read-only. They should never be set by an application.)

guint draw_value; | non-zero if the scale's current value is displayed next to the slider.
guint value_pos; | the position in which the textual value is displayed, selected from GtkPositionType.

gtk_scale_set_digits ()

void                gtk_scale_set_digits                (GtkScale *scale,
                                                         gint digits);

Sets the number of decimal places that are displayed in the value. Also causes the value of the adjustment to be rounded off to this number of digits, so the retrieved value matches the value the user saw.

scale : | a GtkScale.
digits : | the number of decimal places to display, e.g. use 1 to display 1.0, 2 to display 1.00 etc.

gtk_scale_set_draw_value ()

void                gtk_scale_set_draw_value            (GtkScale *scale,
                                                         gboolean draw_value);

Specifies whether the current value is displayed as a string next to the slider.

scale : | a GtkScale.
draw_value : | a boolean.

gtk_scale_set_value_pos ()

void                gtk_scale_set_value_pos             (GtkScale *scale,
                                                         GtkPositionType pos);

Sets the position in which the current value is displayed.

scale : | a GtkScale.
pos : | the position in which the current value is displayed.

gtk_scale_get_digits ()

gint                gtk_scale_get_digits                (GtkScale *scale);

Gets the number of decimal places that are displayed in the value.

scale : | a GtkScale.
Returns : | the number of decimal places that are displayed.

gtk_scale_get_draw_value ()

gboolean            gtk_scale_get_draw_value            (GtkScale *scale);

Returns whether the current value is displayed as a string next to the slider.

scale : | a GtkScale.
Returns : | whether the current value is displayed as a string.

gtk_scale_get_value_pos ()

GtkPositionType     gtk_scale_get_value_pos             (GtkScale *scale);

Gets the position in which the current value is displayed.

scale : | a GtkScale.
Returns : | the position in which the current value is displayed.

gtk_scale_get_layout ()

PangoLayout*        gtk_scale_get_layout                (GtkScale *scale);

Gets the PangoLayout used to display the scale. The returned object is owned by the scale so does not need to be freed by the caller.

scale : | A GtkScale
Returns : | the PangoLayout for this scale, or NULL if the draw_value property is FALSE.

Since 2.4

gtk_scale_get_layout_offsets ()

void                gtk_scale_get_layout_offsets        (GtkScale *scale,
                                                         gint *x,
                                                         gint *y);

Obtains the coordinates where the scale will draw the PangoLayout representing the text in the scale. Remember when using the PangoLayout function you need to convert to and from pixels using PANGO_PIXELS() or PANGO_SCALE.

If the draw_value property is FALSE, the return values are undefined.

scale : | a GtkScale
x : | location to store X offset of layout, or NULL
y : | location to store Y offset of layout, or NULL

Since 2.4

Property Details

The "digits" property

  "digits"                   gint                  : Read / Write

The number of decimal places that are displayed in the value.

Allowed values: [-1,64]

Default value: 1

The "draw-value" property

  "draw-value"               gboolean              : Read / Write

Whether the current value is displayed as a string next to the slider.

Default value: TRUE

The "value-pos" property

  "value-pos"                GtkPositionType       : Read / Write

The position in which the current value is displayed.

Default value: GTK_POS_TOP

Style Property Details

The "slider-length" style property

  "slider-length"            gint                  : Read

Length of scale's slider.

Allowed values: >= 0

Default value: 31

The "value-spacing" style property

  "value-spacing"            gint                  : Read

Space between value text and the slider/trough area.

Allowed values: >= 0

Default value: 2

Signal Details

The "format-value" signal

gchar*              user_function                      (GtkScale *scale,
                                                        gdouble   arg1,
                                                        gpointer  user_data)      : Run Last

Signal which allows you to change how the scale value is displayed. Connect a signal handler which returns an allocated string representing value. That string will then be used to display the scale's value. Here's an example signal handler which displays a value 1.0 as with "-->1.0<--".

static gchar*
format_value_callback (GtkScale *scale,
                       gdouble   value)
{
  return g_strdup_printf ("-->%0.*g<--",
                          gtk_scale_get_digits (scale), value);
}

scale : | the object which received the signal.
arg1 : |
user_data : | user data set when the signal handler was connected.
Returns : | allocated string representing value


GtkScrollbar

GtkScrollbar — Base class for GtkHScrollbar and GtkVScrollbar

Synopsis

#include <gtk/gtk.h>

                    GtkScrollbar;

Object Hierarchy

  GObject
   +----GInitiallyUnowned
         +----GtkObject
               +----GtkWidget
                     +----GtkRange
                           +----GtkScrollbar
                                 +----GtkHScrollbar
                                 +----GtkVScrollbar

Implemented Interfaces

GtkScrollbar implements AtkImplementorIface.

Style Properties

  "fixed-slider-length"      gboolean              : Read
  "has-backward-stepper"     gboolean              : Read
  "has-forward-stepper"      gboolean              : Read
  "has-secondary-backward-stepper" gboolean              : Read
  "has-secondary-forward-stepper" gboolean              : Read
  "min-slider-length"        gint                  : Read

Description

The GtkScrollbar widget is an abstract base class for GtkHScrollbar and GtkVScrollbar. It is not very useful in itself.

The position of the thumb in a scrollbar is controlled by the scroll adjustments. See GtkAdjustment for the fields in an adjustment - for GtkScrollbar, the "value" field represents the position of the scrollbar, which must be between the "lower" field and "upper - page_size." The "page_size" field represents the size of the visible scrollable area. The "step_increment" and "page_increment" fields are used when the user asks to step down (using the small stepper arrows) or page down (using for example the PageDown key).

Details

GtkScrollbar

typedef struct _GtkScrollbar GtkScrollbar;

The GtkScrollbar struct does not contain any public data.

Style Property Details

The "fixed-slider-length" style property

  "fixed-slider-length"      gboolean              : Read

Don't change slider size, just lock it to the minimum length.

Default value: FALSE

The "has-backward-stepper" style property

  "has-backward-stepper"     gboolean              : Read

Display the standard backward arrow button.

Default value: TRUE

The "has-forward-stepper" style property

  "has-forward-stepper"      gboolean              : Read

Display the standard forward arrow button.

Default value: TRUE

The "has-secondary-backward-stepper" style property

  "has-secondary-backward-stepper" gboolean              : Read

Display a second backward arrow button on the opposite end of the scrollbar.

Default value: FALSE

The "has-secondary-forward-stepper" style property

  "has-secondary-forward-stepper" gboolean              : Read

Display a second forward arrow button on the opposite end of the scrollbar.

Default value: FALSE

The "min-slider-length" style property

  "min-slider-length"        gint                  : Read

Minimum length of scrollbar slider.

Allowed values: >= 0

Default value: 21

See Also

GtkHScrollbar | a horizontal scrollbar.
GtkVScrollbar | a vertical scrollbar.
GtkAdjustment | connects scrollbars to the widget being scrolled.
GtkScrolledWindow | convenient widget for setting up scrolling.


GtkScrolledWindow

GtkScrolledWindow — Adds scrollbars to its child widget

Synopsis

#include <gtk/gtk.h>

                    GtkScrolledWindow;
GtkWidget*          gtk_scrolled_window_new             (GtkAdjustment *hadjustment,
                                                         GtkAdjustment *vadjustment);
GtkAdjustment*      gtk_scrolled_window_get_hadjustment (GtkScrolledWindow *scrolled_window);
GtkAdjustment*      gtk_scrolled_window_get_vadjustment (GtkScrolledWindow *scrolled_window);
GtkWidget*          gtk_scrolled_window_get_hscrollbar  (GtkScrolledWindow *scrolled_window);
GtkWidget*          gtk_scrolled_window_get_vscrollbar  (GtkScrolledWindow *scrolled_window);
void                gtk_scrolled_window_set_policy      (GtkScrolledWindow *scrolled_window,
                                                         GtkPolicyType hscrollbar_policy,
                                                         GtkPolicyType vscrollbar_policy);
void                gtk_scrolled_window_add_with_viewport
                                                        (GtkScrolledWindow *scrolled_window,
                                                         GtkWidget *child);
void                gtk_scrolled_window_set_placement   (GtkScrolledWindow *scrolled_window,
                                                         GtkCornerType window_placement);
void                gtk_scrolled_window_unset_placement (GtkScrolledWindow *scrolled_window);
void                gtk_scrolled_window_set_shadow_type (GtkScrolledWindow *scrolled_window,
                                                         GtkShadowType type);
void                gtk_scrolled_window_set_hadjustment (GtkScrolledWindow *scrolled_window,
                                                         GtkAdjustment *hadjustment);
void                gtk_scrolled_window_set_vadjustment (GtkScrolledWindow *scrolled_window,
                                                         GtkAdjustment *vadjustment);
GtkCornerType       gtk_scrolled_window_get_placement   (GtkScrolledWindow *scrolled_window);
void                gtk_scrolled_window_get_policy      (GtkScrolledWindow *scrolled_window,
                                                         GtkPolicyType *hscrollbar_policy,
                                                         GtkPolicyType *vscrollbar_policy);
GtkShadowType       gtk_scrolled_window_get_shadow_type (GtkScrolledWindow *scrolled_window);

Object Hierarchy

  GObject
   +----GInitiallyUnowned
         +----GtkObject
               +----GtkWidget
                     +----GtkContainer
                           +----GtkBin
                                 +----GtkScrolledWindow

Implemented Interfaces

GtkScrolledWindow implements AtkImplementorIface.

Properties

  "hadjustment"              GtkAdjustment         : Read / Write / Construct
  "hscrollbar-policy"        GtkPolicyType         : Read / Write
  "shadow-type"              GtkShadowType         : Read / Write
  "vadjustment"              GtkAdjustment         : Read / Write / Construct
  "vscrollbar-policy"        GtkPolicyType         : Read / Write
  "window-placement"         GtkCornerType         : Read / Write
  "window-placement-set"     gboolean              : Read / Write

Style Properties

  "scrollbar-spacing"        gint                  : Read

Signals

  "move-focus-out"                                 : Run Last / Action
  "scroll-child"                                   : Run Last / Action

Description

GtkScrolledWindow is a GtkBin subclass: it's a container the accepts a single child widget. GtkScrolledWindow adds scrollbars to the child widget and optionally draws a beveled frame around the child widget.

The scrolled window can work in two ways. Some widgets have native scrolling support; these widgets have "slots" for GtkAdjustment objects. [5] Widgets with native scroll support include GtkTreeView, GtkTextView, and GtkLayout.

For widgets that lack native scrolling support, the GtkViewport widget acts as an adaptor class, implementing scrollability for child widgets that lack their own scrolling capabilities. Use GtkViewport to scroll child widgets such as GtkTable, GtkBox, and so on.

If a widget has native scrolling abilities, it can be added to the GtkScrolledWindow with gtk_container_add(). If a widget does not, you must first add the widget to a GtkViewport, then add the GtkViewport to the scrolled window. The convenience function gtk_scrolled_window_add_with_viewport() does exactly this, so you can ignore the presence of the viewport.

The position of the scrollbars is controlled by the scroll adjustments. See GtkAdjustment for the fields in an adjustment - for GtkScrollbar, used by GtkScrolledWindow, the "value" field represents the position of the scrollbar, which must be between the "lower" field and "upper - page_size." The "page_size" field represents the size of the visible scrollable area. The "step_increment" and "page_increment" fields are used when the user asks to step down (using the small stepper arrows) or page down (using for example the PageDown key).

If a GtkScrolledWindow doesn't behave quite as you would like, or doesn't have exactly the right layout, it's very possible to set up your own scrolling with GtkScrollbar and for example a GtkTable.

Details

GtkScrolledWindow

typedef struct {
  GtkWidget *hscrollbar;
  GtkWidget *vscrollbar;
} GtkScrolledWindow;

There are no public fields in the GtkScrolledWindow struct; it should only be accessed using the functions below.

gtk_scrolled_window_new ()

GtkWidget*          gtk_scrolled_window_new             (GtkAdjustment *hadjustment,
                                                         GtkAdjustment *vadjustment);

Creates a new scrolled window. The two arguments are the scrolled window's adjustments; these will be shared with the scrollbars and the child widget to keep the bars in sync with the child. Usually you want to pass NULL for the adjustments, which will cause the scrolled window to create them for you.

hadjustment : | Horizontal adjustment.
vadjustment : | Vertical adjustment.
Returns : | New scrolled window.

gtk_scrolled_window_get_hadjustment ()

GtkAdjustment*      gtk_scrolled_window_get_hadjustment (GtkScrolledWindow *scrolled_window);

Returns the horizontal scrollbar's adjustment, used to connect the horizontal scrollbar to the child widget's horizontal scroll functionality.

scrolled_window : | A GtkScrolledWindow.
Returns : | The horizontal GtkAdjustment.

gtk_scrolled_window_get_vadjustment ()

GtkAdjustment*      gtk_scrolled_window_get_vadjustment (GtkScrolledWindow *scrolled_window);

Returns the vertical scrollbar's adjustment, used to connect the vertical scrollbar to the child widget's vertical scroll functionality.

scrolled_window : | A GtkScrolledWindow.
Returns : | The vertical GtkAdjustment.

gtk_scrolled_window_get_hscrollbar ()

GtkWidget*          gtk_scrolled_window_get_hscrollbar  (GtkScrolledWindow *scrolled_window);

Returns the horizontal scrollbar of scrolled_window.

scrolled_window : | a GtkScrolledWindow
Returns : | the horizontal scrollbar of the scrolled window, or NULL if it does not have one.

Since 2.8

gtk_scrolled_window_get_vscrollbar ()

GtkWidget*          gtk_scrolled_window_get_vscrollbar  (GtkScrolledWindow *scrolled_window);

Returns the vertical scrollbar of scrolled_window.

scrolled_window : | a GtkScrolledWindow
Returns : | the vertical scrollbar of the scrolled window, or NULL if it does not have one.

Since 2.8

gtk_scrolled_window_set_policy ()

void                gtk_scrolled_window_set_policy      (GtkScrolledWindow *scrolled_window,
                                                         GtkPolicyType hscrollbar_policy,
                                                         GtkPolicyType vscrollbar_policy);

Sets the scrollbar policy for the horizontal and vertical scrollbars. The policy determines when the scrollbar should appear; it is a value from the GtkPolicyType enumeration. If GTK_POLICY_ALWAYS, the scrollbar is always present; if GTK_POLICY_NEVER, the scrollbar is never present; if GTK_POLICY_AUTOMATIC, the scrollbar is present only if needed (that is, if the slider part of the bar would be smaller than the trough - the display is larger than the page size).

scrolled_window : | A GtkScrolledWindow.
hscrollbar_policy : | Policy for horizontal bar.
vscrollbar_policy : | Policy for vertical bar.

gtk_scrolled_window_add_with_viewport ()

void                gtk_scrolled_window_add_with_viewport
                                                        (GtkScrolledWindow *scrolled_window,
                                                         GtkWidget *child);

Used to add children without native scrolling capabilities. This is simply a convenience function; it is equivalent to adding the unscrollable child to a viewport, then adding the viewport to the scrolled window. If a child has native scrolling, use gtk_container_add() instead of this function.

The viewport scrolls the child by moving its GdkWindow, and takes the size of the child to be the size of its toplevel GdkWindow. This will be very wrong for most widgets that support native scrolling; for example, if you add a widget such as GtkTreeView with a viewport, the whole widget will scroll, including the column headings. Thus, widgets with native scrolling support should not be used with the GtkViewport proxy.

A widget supports scrolling natively if the set_scroll_adjustments_signal field in GtkWidgetClass is non-zero, i.e. has been filled in with a valid signal identifier.

scrolled_window : | A GtkScrolledWindow.
child : | Widget you want to scroll.

gtk_scrolled_window_set_placement ()

void                gtk_scrolled_window_set_placement   (GtkScrolledWindow *scrolled_window,
                                                         GtkCornerType window_placement);

Sets the placement of the contents with respect to the scrollbars for the scrolled window.

See also gtk_scrolled_window_get_placement() and gtk_scrolled_window_unset_placement().

Determines the location of the child widget with respect to the scrollbars. The default is GTK_CORNER_TOP_LEFT, meaning the child is in the top left, with the scrollbars underneath and to the right. Other values in GtkCornerType are GTK_CORNER_TOP_RIGHT, GTK_CORNER_BOTTOM_LEFT, and GTK_CORNER_BOTTOM_RIGHT.

scrolled_window : | a GtkScrolledWindow
window_placement : | Position of the child window.

gtk_scrolled_window_unset_placement ()

void                gtk_scrolled_window_unset_placement (GtkScrolledWindow *scrolled_window);

Unsets the placement of the contents with respect to the scrollbars for the scrolled window. If no window placement is set for a scrolled window, it obeys the "gtk-scrolled-window-placement" XSETTING.

See also gtk_scrolled_window_set_placement() and gtk_scrolled_window_get_placement().

scrolled_window : a GtkScrolledWindow

Since 2.10

gtk_scrolled_window_set_shadow_type ()

void                gtk_scrolled_window_set_shadow_type (GtkScrolledWindow *scrolled_window,
                                                         GtkShadowType type);

Changes the type of shadow drawn around the contents of scrolled_window.

scrolled_window : | a GtkScrolledWindow
type : | kind of shadow to draw around scrolled window contents

gtk_scrolled_window_set_hadjustment ()

void                gtk_scrolled_window_set_hadjustment (GtkScrolledWindow *scrolled_window,
                                                         GtkAdjustment *hadjustment);

Sets the GtkAdjustment for the horizontal scrollbar.

scrolled_window : | A GtkScrolledWindow.
hadjustment : | Horizontal scroll adjustment.

gtk_scrolled_window_set_vadjustment ()

void                gtk_scrolled_window_set_vadjustment (GtkScrolledWindow *scrolled_window,
                                                         GtkAdjustment *vadjustment);

Sets the GtkAdjustment for the vertical scrollbar.

scrolled_window : | A GtkScrolledWindow.
vadjustment : | Vertical scroll adjustment.

gtk_scrolled_window_get_placement ()

GtkCornerType       gtk_scrolled_window_get_placement   (GtkScrolledWindow *scrolled_window);

Gets the placement of the contents with respect to the scrollbars for the scrolled window. See gtk_scrolled_window_set_placement().

scrolled_window : | a GtkScrolledWindow
Returns : | the current placement value. See also gtk_scrolled_window_set_placement() and gtk_scrolled_window_unset_placement().

gtk_scrolled_window_get_policy ()

void                gtk_scrolled_window_get_policy      (GtkScrolledWindow *scrolled_window,
                                                         GtkPolicyType *hscrollbar_policy,
                                                         GtkPolicyType *vscrollbar_policy);

Retrieves the current policy values for the horizontal and vertical scrollbars. See gtk_scrolled_window_set_policy().

scrolled_window : | a GtkScrolledWindow
hscrollbar_policy : | location to store the policy for the horizontal scrollbar, or NULL.
vscrollbar_policy : | location to store the policy for the horizontal scrollbar, or NULL.

gtk_scrolled_window_get_shadow_type ()

GtkShadowType       gtk_scrolled_window_get_shadow_type (GtkScrolledWindow *scrolled_window);

Gets the shadow type of the scrolled window. See gtk_scrolled_window_set_shadow_type().

scrolled_window : | a GtkScrolledWindow
Returns : | the current shadow type

Property Details

The "hadjustment" property

  "hadjustment"              GtkAdjustment         : Read / Write / Construct

The GtkAdjustment for the horizontal position.

The "hscrollbar-policy" property

  "hscrollbar-policy"        GtkPolicyType         : Read / Write

When the horizontal scrollbar is displayed.

Default value: GTK_POLICY_ALWAYS

The "shadow-type" property

  "shadow-type"              GtkShadowType         : Read / Write

Style of bevel around the contents.

Default value: GTK_SHADOW_NONE

The "vadjustment" property

  "vadjustment"              GtkAdjustment         : Read / Write / Construct

The GtkAdjustment for the vertical position.

The "vscrollbar-policy" property

  "vscrollbar-policy"        GtkPolicyType         : Read / Write

When the vertical scrollbar is displayed.

Default value: GTK_POLICY_ALWAYS

The "window-placement" property

  "window-placement"         GtkCornerType         : Read / Write

Where the contents are located with respect to the scrollbars. This property only takes effect if "window-placement-set" is TRUE.

Default value: GTK_CORNER_TOP_LEFT

The "window-placement-set" property

  "window-placement-set"     gboolean              : Read / Write

Whether "window-placement" should be used to determine the location of the contents with respect to the scrollbars. Otherwise, the "gtk-scrolled-window-placement" setting is used.

Default value: FALSE

Since 2.10

Style Property Details

The "scrollbar-spacing" style property

  "scrollbar-spacing"        gint                  : Read

Number of pixels between the scrollbars and the scrolled window.

Allowed values: >= 0

Default value: 3

Signal Details

The "move-focus-out" signal

void                user_function                      (GtkScrolledWindow *scrolledwindow,
                                                        GtkDirectionType   arg1,
                                                        gpointer           user_data)           : Run Last / Action

scrolledwindow : | the object which received the signal.
arg1 : |
user_data : | user data set when the signal handler was connected.

The "scroll-child" signal

gboolean            user_function                      (GtkScrolledWindow *scrolledwindow,
                                                        GtkScrollType      arg1,
                                                        gboolean           arg2,
                                                        gpointer           user_data)           : Run Last / Action

scrolledwindow : | the object which received the signal.
arg1 : |
arg2 : |
user_data : | user data set when the signal handler was connected.
Returns : |

See Also

GtkViewport, GtkAdjustment, GtkWidgetClass

[5] The scrolled window installs GtkAdjustment objects in the child window's slots using the set_scroll_adjustments_signal, found in GtkWidgetClass. (Conceptually, these widgets implement a "Scrollable" interface; because GTK+ 1.2 lacked interface support in the object system, this interface is hackily implemented as a signal in GtkWidgetClass. The GTK+ 2.0 object system would allow a clean implementation, but it wasn't worth breaking the API.)


GtkSeparator

GtkSeparator — Base class for GtkHSeparator and GtkVSeparator

Synopsis

#include <gtk/gtk.h>

                    GtkSeparator;

Object Hierarchy

  GObject
   +----GInitiallyUnowned
         +----GtkObject
               +----GtkWidget
                     +----GtkSeparator
                           +----GtkHSeparator
                           +----GtkVSeparator

Implemented Interfaces

GtkSeparator implements AtkImplementorIface.

Description

The GtkSeparator widget is an abstract class, used only for deriving the subclasses GtkHSeparator and GtkVSeparator.

Details

GtkSeparator

typedef struct _GtkSeparator GtkSeparator;

The GtkSeparator struct contains private data only.


GtkSeparatorMenuItem

GtkSeparatorMenuItem — A separator used in menus

Synopsis

#include <gtk/gtk.h>

                    GtkSeparatorMenuItem;
GtkWidget*          gtk_separator_menu_item_new         (void);

Object Hierarchy

  GObject
   +----GInitiallyUnowned
         +----GtkObject
               +----GtkWidget
                     +----GtkContainer
                           +----GtkBin
                                 +----GtkItem
                                       +----GtkMenuItem
                                             +----GtkSeparatorMenuItem

Implemented Interfaces

GtkSeparatorMenuItem implements AtkImplementorIface.

Description

The GtkSeparatorMenuItem is a separator used to group items within a menu. It displays a horizontal line with a shadow to make it appear sunken into the interface.

Details

GtkSeparatorMenuItem

typedef struct _GtkSeparatorMenuItem GtkSeparatorMenuItem;

The GtkSeparatorMenuItem struct contains private data only, and should be accessed using the functions below.

gtk_separator_menu_item_new ()

GtkWidget*          gtk_separator_menu_item_new         (void);

Creates a new GtkSeparatorMenuItem.

Returns : a new GtkSeparatorMenuItem.


GtkSeparatorToolItem

GtkSeparatorToolItem — A toolbar item that separates groups of other toolbar items

Synopsis

#include <gtk/gtk.h>

                    GtkSeparatorToolItem;
GtkToolItem*        gtk_separator_tool_item_new         (void);
void                gtk_separator_tool_item_set_draw    (GtkSeparatorToolItem *item,
                                                         gboolean draw);
gboolean            gtk_separator_tool_item_get_draw    (GtkSeparatorToolItem *item);

Object Hierarchy

  GObject
   +----GInitiallyUnowned
         +----GtkObject
               +----GtkWidget
                     +----GtkContainer
                           +----GtkBin
                                 +----GtkToolItem
                                       +----GtkSeparatorToolItem

Implemented Interfaces

GtkSeparatorToolItem implements AtkImplementorIface.

Properties

  "draw"                     gboolean              : Read / Write

Description

A GtkSeparatorItem is a GtkToolItem that separates groups of other GtkToolItems. Depending on the theme, a GtkSeparatorToolItem will often look like a vertical line on horizontally docked toolbars.

If the property "expand" is TRUE and the property "draw" is FALSE, a GtkSeparatorToolItem will act as a "spring" that forces other items to the ends of the toolbar.

Use gtk_separator_tool_item_new() to create a new GtkSeparatorToolItem.

Details

GtkSeparatorToolItem

typedef struct _GtkSeparatorToolItem GtkSeparatorToolItem;

The GtkSeparatorToolItem struct contains only private data and should only be accessed through the functions described below.

gtk_separator_tool_item_new ()

GtkToolItem*        gtk_separator_tool_item_new         (void);

Create a new GtkSeparatorToolItem

Returns : the new GtkSeparatorToolItem

Since 2.4

gtk_separator_tool_item_set_draw ()

void                gtk_separator_tool_item_set_draw    (GtkSeparatorToolItem *item,
                                                         gboolean draw);

When separator_tool_items is drawn as a vertical line, or just blank. Setting this FALSE along with gtk_tool_item_set_expand() is useful to create an item that forces following items to the end of the toolbar.

item : | a GtkSeparatorToolItem
draw : | whether separator_tool_item is drawn as a vertical line

Since 2.4

gtk_separator_tool_item_get_draw ()

gboolean            gtk_separator_tool_item_get_draw    (GtkSeparatorToolItem *item);

Returns whether separator_tool_item is drawn as a line, or just blank. See gtk_separator_tool_item_set_draw().

item : | a GtkSeparatorToolItem
Returns : | TRUE if separator_tool_item is drawn as a line, or just blank.

Since 2.4

Property Details

The "draw" property

  "draw"                     gboolean              : Read / Write

Whether the separator is drawn, or just blank.

Default value: TRUE

See Also

GtkToolbar | The toolbar widget
GtkRadioToolButton | A toolbar item containing a radio button


Settings

Settings — Sharing settings between applications

Synopsis

#include <gtk/gtk.h>

                    GtkSettings;
                    GtkSettingsValue;
GtkSettings*        gtk_settings_get_default            (void);
GtkSettings*        gtk_settings_get_for_screen         (GdkScreen *screen);
void                gtk_settings_install_property       (GParamSpec *pspec);
void                gtk_settings_install_property_parser
                                                        (GParamSpec *pspec,
                                                         GtkRcPropertyParser parser);
gboolean            gtk_rc_property_parse_color         (const GParamSpec *pspec,
                                                         const GString *gstring,
                                                         GValue *property_value);
gboolean            gtk_rc_property_parse_enum          (const GParamSpec *pspec,
                                                         const GString *gstring,
                                                         GValue *property_value);
gboolean            gtk_rc_property_parse_flags         (const GParamSpec *pspec,
                                                         const GString *gstring,
                                                         GValue *property_value);
gboolean            gtk_rc_property_parse_requisition   (const GParamSpec *pspec,
                                                         const GString *gstring,
                                                         GValue *property_value);
gboolean            gtk_rc_property_parse_border        (const GParamSpec *pspec,
                                                         const GString *gstring,
                                                         GValue *property_value);
void                gtk_settings_set_property_value     (GtkSettings *settings,
                                                         const gchar *name,
                                                         const GtkSettingsValue *svalue);
void                gtk_settings_set_string_property    (GtkSettings *settings,
                                                         const gchar *name,
                                                         const gchar *v_string,
                                                         const gchar *origin);
void                gtk_settings_set_long_property      (GtkSettings *settings,
                                                         const gchar *name,
                                                         glong v_long,
                                                         const gchar *origin);
void                gtk_settings_set_double_property    (GtkSettings *settings,
                                                         const gchar *name,
                                                         gdouble v_double,
                                                         const gchar *origin);

Object Hierarchy

  GObject
   +----GtkSettings

Properties

  "color-hash"               GHashTable            : Read
  "gtk-alternative-button-order" gboolean              : Read / Write
  "gtk-button-images"        gboolean              : Read / Write
  "gtk-can-change-accels"    gboolean              : Read / Write
  "gtk-color-palette"        gchararray            : Read / Write
  "gtk-color-scheme"         gchararray            : Read / Write
  "gtk-cursor-blink"         gboolean              : Read / Write
  "gtk-cursor-blink-time"    gint                  : Read / Write
  "gtk-cursor-theme-name"    gchararray            : Read / Write
  "gtk-cursor-theme-size"    gint                  : Read / Write
  "gtk-dnd-drag-threshold"   gint                  : Read / Write
  "gtk-double-click-distance" gint                  : Read / Write
  "gtk-double-click-time"    gint                  : Read / Write
  "gtk-enable-animations"    gboolean              : Read / Write
  "gtk-entry-password-hint-timeout" guint                 : Read / Write
  "gtk-entry-select-on-focus" gboolean              : Read / Write
  "gtk-fallback-icon-theme"  gchararray            : Read / Write
  "gtk-font-name"            gchararray            : Read / Write
  "gtk-icon-sizes"           gchararray            : Read / Write
  "gtk-icon-theme-name"      gchararray            : Read / Write
  "gtk-key-theme-name"       gchararray            : Read / Write
  "gtk-label-select-on-focus" gboolean              : Read / Write
  "gtk-menu-bar-accel"       gchararray            : Read / Write
  "gtk-menu-bar-popup-delay" gint                  : Read / Write
  "gtk-menu-images"          gboolean              : Read / Write
  "gtk-menu-popdown-delay"   gint                  : Read / Write
  "gtk-menu-popup-delay"     gint                  : Read / Write
  "gtk-modules"              gchararray            : Read / Write
  "gtk-scrolled-window-placement" GtkCornerType         : Read / Write
  "gtk-show-input-method-menu" gboolean              : Read / Write
  "gtk-show-unicode-menu"    gboolean              : Read / Write
  "gtk-split-cursor"         gboolean              : Read / Write
  "gtk-theme-name"           gchararray            : Read / Write
  "gtk-timeout-expand"       gint                  : Read / Write
  "gtk-timeout-initial"      gint                  : Read / Write
  "gtk-timeout-repeat"       gint                  : Read / Write
  "gtk-toolbar-icon-size"    GtkIconSize           : Read / Write
  "gtk-toolbar-style"        GtkToolbarStyle       : Read / Write
  "gtk-touchscreen-mode"     gboolean              : Read / Write
  "gtk-xft-antialias"        gint                  : Read / Write
  "gtk-xft-dpi"              gint                  : Read / Write
  "gtk-xft-hinting"          gint                  : Read / Write
  "gtk-xft-hintstyle"        gchararray            : Read / Write
  "gtk-xft-rgba"             gchararray            : Read / Write

Description

Details

GtkSettings

typedef struct _GtkSettings GtkSettings;

GtkSettingsValue

typedef struct {
  /* origin should be something like "filename:linenumber" for rc files,
   * or e.g. "XProperty" for other sources
   */
  gchar *origin;

  /* valid types are LONG, DOUBLE and STRING corresponding to the token parsed,
   * or a GSTRING holding an unparsed statement
   */
  GValue value;
} GtkSettingsValue;

gtk_settings_get_default ()

GtkSettings*        gtk_settings_get_default            (void);

Gets the GtkSettings object for the default GDK screen, creating it if necessary. See gtk_settings_get_for_screen().

Returns : a GtkSettings object. If there is no default screen, then returns NULL.

gtk_settings_get_for_screen ()

GtkSettings*        gtk_settings_get_for_screen         (GdkScreen *screen);

Gets the GtkSettings object for screen, creating it if necessary.

screen : | a GdkScreen.
Returns : | a GtkSettings object.

Since 2.2

gtk_settings_install_property ()

void                gtk_settings_install_property       (GParamSpec *pspec);

pspec :

gtk_settings_install_property_parser ()

void                gtk_settings_install_property_parser
                                                        (GParamSpec *pspec,
                                                         GtkRcPropertyParser parser);

pspec :
parser :

gtk_rc_property_parse_color ()

gboolean            gtk_rc_property_parse_color         (const GParamSpec *pspec,
                                                         const GString *gstring,
                                                         GValue *property_value);

A GtkRcPropertyParser for use with gtk_settings_install_property_parser() or gtk_widget_class_install_style_property_parser() which parses a color given either by its name or in the form { red, green, blue } where red, green and blue are integers between 0 and 65535 or floating-point numbers between 0 and 1.

pspec : | a GParamSpec
gstring : | the GString to be parsed
property_value : | a GValue which must hold GdkColor values.
Returns : | TRUE if gstring could be parsed and property_value has been set to the resulting GdkColor.

gtk_rc_property_parse_enum ()

gboolean            gtk_rc_property_parse_enum          (const GParamSpec *pspec,
                                                         const GString *gstring,
                                                         GValue *property_value);

A GtkRcPropertyParser for use with gtk_settings_install_property_parser() or gtk_widget_class_install_style_property_parser() which parses a single enumeration value.

The enumeration value can be specified by its name, its nickname or its numeric value. For consistency with flags parsing, the value may be surrounded by parentheses.

pspec : | a GParamSpec
gstring : | the GString to be parsed
property_value : | a GValue which must hold enum values.
Returns : | TRUE if gstring could be parsed and property_value has been set to the resulting GEnumValue.

gtk_rc_property_parse_flags ()

gboolean            gtk_rc_property_parse_flags         (const GParamSpec *pspec,
                                                         const GString *gstring,
                                                         GValue *property_value);

A GtkRcPropertyParser for use with gtk_settings_install_property_parser() or gtk_widget_class_install_style_property_parser() which parses flags.

Flags can be specified by their name, their nickname or numerically. Multiple flags can be specified in the form "( flag1 | flag2 | ... )".

pspec : | a GParamSpec
gstring : | the GString to be parsed
property_value : | a GValue which must hold flags values.
Returns : | TRUE if gstring could be parsed and property_value has been set to the resulting flags value.

gtk_rc_property_parse_requisition ()

gboolean            gtk_rc_property_parse_requisition   (const GParamSpec *pspec,
                                                         const GString *gstring,
                                                         GValue *property_value);

A GtkRcPropertyParser for use with gtk_settings_install_property_parser() or gtk_widget_class_install_style_property_parser() which parses a requisition in the form "{ width, height }" for integers width and height.

pspec : | a GParamSpec
gstring : | the GString to be parsed
property_value : | a GValue which must hold boxed values.
Returns : | TRUE if gstring could be parsed and property_value has been set to the resulting GtkRequisition.

gtk_rc_property_parse_border ()

gboolean            gtk_rc_property_parse_border        (const GParamSpec *pspec,
                                                         const GString *gstring,
                                                         GValue *property_value);

A GtkRcPropertyParser for use with gtk_settings_install_property_parser() or gtk_widget_class_install_style_property_parser() which parses borders in the form "{ left, right, top, bottom }" for integers left, right, top and bottom.

pspec : | a GParamSpec
gstring : | the GString to be parsed
property_value : | a GValue which must hold boxed values.
Returns : | TRUE if gstring could be parsed and property_value has been set to the resulting GtkBorder.

gtk_settings_set_property_value ()

void                gtk_settings_set_property_value     (GtkSettings *settings,
                                                         const gchar *name,
                                                         const GtkSettingsValue *svalue);

settings :
name :
svalue :

gtk_settings_set_string_property ()

void                gtk_settings_set_string_property    (GtkSettings *settings,
                                                         const gchar *name,
                                                         const gchar *v_string,
                                                         const gchar *origin);

settings :
name :
v_string :
origin :

gtk_settings_set_long_property ()

void                gtk_settings_set_long_property      (GtkSettings *settings,
                                                         const gchar *name,
                                                         glong v_long,
                                                         const gchar *origin);

settings :
name :
v_long :
origin :

gtk_settings_set_double_property ()

void                gtk_settings_set_double_property    (GtkSettings *settings,
                                                         const gchar *name,
                                                         gdouble v_double,
                                                         const gchar *origin);

settings :
name :
v_double :
origin :

Property Details

The "color-hash" property

  "color-hash"               GHashTable            : Read

Holds a hash table representation of the gtk-color-scheme setting, mapping color names to GdkColors.

Since 2.10

The "gtk-alternative-button-order" property

  "gtk-alternative-button-order" gboolean              : Read / Write

Whether buttons in dialogs should use the alternative button order.

Default value: FALSE

The "gtk-button-images" property

  "gtk-button-images"        gboolean              : Read / Write

Whether stock icons should be shown in buttons.

Default value: TRUE

The "gtk-can-change-accels" property

  "gtk-can-change-accels"    gboolean              : Read / Write

Whether menu accelerators can be changed by pressing a key over the menu item.

Default value: FALSE

The "gtk-color-palette" property

  "gtk-color-palette"        gchararray            : Read / Write

Palette to use in the color selector.

Default value: "black:white:gray50:red:purple:blue:light blue:green:yellow:orange:lavender:brown:goldenrod4:dodger blue:pink:light green:gray10:gray30:gray75:gray90"

The "gtk-color-scheme" property

  "gtk-color-scheme"         gchararray            : Read / Write

A palette of named colors for use in themes. The format of the string is

name1: color1
name2: color2
...

Color names must be acceptable as identifiers in the gtkrc syntax, and color specifications must be in the format accepted by gdk_color_parse().

Note that due to the way the color tables from different sources are merged, color specifications will be converted to hexadecimal form when getting this property.

Default value: ""

Since 2.10

The "gtk-cursor-blink" property

  "gtk-cursor-blink"         gboolean              : Read / Write

Whether the cursor should blink.

Default value: TRUE

The "gtk-cursor-blink-time" property

  "gtk-cursor-blink-time"    gint                  : Read / Write

Length of the cursor blink cycle, in milleseconds.

Allowed values: >= 100

Default value: 1200

The "gtk-cursor-theme-name" property

  "gtk-cursor-theme-name"    gchararray            : Read / Write

Name of the cursor theme to use, or NULL to use the default theme.

Default value: NULL

The "gtk-cursor-theme-size" property

  "gtk-cursor-theme-size"    gint                  : Read / Write

Size to use for cursors, or 0 to use the default size.

Allowed values: [0,128]

Default value: 0

The "gtk-dnd-drag-threshold" property

  "gtk-dnd-drag-threshold"   gint                  : Read / Write

Number of pixels the cursor can move before dragging.

Allowed values: >= 1

Default value: 8

The "gtk-double-click-distance" property

  "gtk-double-click-distance" gint                  : Read / Write

Maximum distance allowed between two clicks for them to be considered a double click (in pixels).

Allowed values: >= 0

Default value: 5

The "gtk-double-click-time" property

  "gtk-double-click-time"    gint                  : Read / Write

Maximum time allowed between two clicks for them to be considered a double click (in milliseconds).

Allowed values: >= 0

Default value: 250

The "gtk-enable-animations" property

  "gtk-enable-animations"    gboolean              : Read / Write

Whether to enable toolkit-wide animations.

Default value: TRUE

The "gtk-entry-password-hint-timeout" property

  "gtk-entry-password-hint-timeout" guint                 : Read / Write

How long to show the last inputted character in hidden entries. This value is in milliseconds. 0 disables showing the last char. 600 is a good value for enabling it.

Default value: 0

Since 2.10

The "gtk-entry-select-on-focus" property

  "gtk-entry-select-on-focus" gboolean              : Read / Write

Whether to select the contents of an entry when it is focused.

Default value: TRUE

The "gtk-fallback-icon-theme" property

  "gtk-fallback-icon-theme"  gchararray            : Read / Write

Name of a icon theme to fall back to.

Default value: NULL

The "gtk-font-name" property

  "gtk-font-name"            gchararray            : Read / Write

Name of default font to use.

Default value: "Sans 10"

The "gtk-icon-sizes" property

  "gtk-icon-sizes"           gchararray            : Read / Write

List of icon sizes (gtk-menu=16,16:gtk-button=20,20...

Default value: NULL

The "gtk-icon-theme-name" property

  "gtk-icon-theme-name"      gchararray            : Read / Write

Name of icon theme to use.

Default value: "hicolor"

The "gtk-key-theme-name" property

  "gtk-key-theme-name"       gchararray            : Read / Write

Name of key theme RC file to load.

Default value: NULL

The "gtk-label-select-on-focus" property

  "gtk-label-select-on-focus" gboolean              : Read / Write

Whether to select the contents of a selectable label when it is focused.

Default value: TRUE

The "gtk-menu-bar-accel" property

  "gtk-menu-bar-accel"       gchararray            : Read / Write

Keybinding to activate the menu bar.

Default value: "F10"

The "gtk-menu-bar-popup-delay" property

  "gtk-menu-bar-popup-delay" gint                  : Read / Write

Delay before the submenus of a menu bar appear.

Allowed values: >= 0

Default value: 0

The "gtk-menu-images" property

  "gtk-menu-images"          gboolean              : Read / Write

Whether images should be shown in menus.

Default value: TRUE

The "gtk-menu-popdown-delay" property

  "gtk-menu-popdown-delay"   gint                  : Read / Write

The time before hiding a submenu when the pointer is moving towards the submenu.

Allowed values: >= 0

Default value: 1000

The "gtk-menu-popup-delay" property

  "gtk-menu-popup-delay"     gint                  : Read / Write

Minimum time the pointer must stay over a menu item before the submenu appear.

Allowed values: >= 0

Default value: 225

The "gtk-modules" property

  "gtk-modules"              gchararray            : Read / Write

List of currently active GTK modules.

Default value: NULL

The "gtk-scrolled-window-placement" property

  "gtk-scrolled-window-placement" GtkCornerType         : Read / Write

Where the contents of scrolled windows are located with respect to the scrollbars, if not overridden by the scrolled window's own placement.

Default value: GTK_CORNER_TOP_LEFT

Since 2.10

The "gtk-show-input-method-menu" property

  "gtk-show-input-method-menu" gboolean              : Read / Write

Whether the context menus of entries and text views should offer to change the input method.

Default value: TRUE

The "gtk-show-unicode-menu" property

  "gtk-show-unicode-menu"    gboolean              : Read / Write

Whether the context menus of entries and text views should offer to insert control characters.

Default value: TRUE

The "gtk-split-cursor" property

  "gtk-split-cursor"         gboolean              : Read / Write

Whether two cursors should be displayed for mixed left-to-right and right-to-left text.

Default value: TRUE

The "gtk-theme-name" property

  "gtk-theme-name"           gchararray            : Read / Write

Name of theme RC file to load.

Default value: "Raleigh"

The "gtk-timeout-expand" property

  "gtk-timeout-expand"       gint                  : Read / Write

Expand value for timeouts, when a widget is expanding a new region.

Allowed values: >= 0

Default value: 500

The "gtk-timeout-initial" property

  "gtk-timeout-initial"      gint                  : Read / Write

Starting value for timeouts, when button is pressed.

Allowed values: >= 0

Default value: 200

The "gtk-timeout-repeat" property

  "gtk-timeout-repeat"       gint                  : Read / Write

Repeat value for timeouts, when button is pressed.

Allowed values: >= 0

Default value: 20

The "gtk-toolbar-icon-size" property

  "gtk-toolbar-icon-size"    GtkIconSize           : Read / Write

Size of icons in default toolbars.

Default value: GTK_ICON_SIZE_LARGE_TOOLBAR

The "gtk-toolbar-style" property

  "gtk-toolbar-style"        GtkToolbarStyle       : Read / Write

Whether default toolbars have text only, text and icons, icons only, etc.

Default value: GTK_TOOLBAR_BOTH

The "gtk-touchscreen-mode" property

  "gtk-touchscreen-mode"     gboolean              : Read / Write

When TRUE, there are no motion notify events delivered on this screen, and widgets can't use the pointer hovering them for any essential functionality.

Default value: FALSE

Since 2.10

The "gtk-xft-antialias" property

  "gtk-xft-antialias"        gint                  : Read / Write

Whether to antialias Xft fonts; 0=no, 1=yes, -1=default.

Allowed values: [-1,1]

Default value: -1

The "gtk-xft-dpi" property

  "gtk-xft-dpi"              gint                  : Read / Write

Resolution for Xft, in 1024 * dots/inch. -1 to use default value.

Allowed values: [-1,1048576]

Default value: -1

The "gtk-xft-hinting" property

  "gtk-xft-hinting"          gint                  : Read / Write

Whether to hint Xft fonts; 0=no, 1=yes, -1=default.

Allowed values: [-1,1]

Default value: -1

The "gtk-xft-hintstyle" property

  "gtk-xft-hintstyle"        gchararray            : Read / Write

What degree of hinting to use; hintnone, hintslight, hintmedium, or hintfull.

Default value: NULL

The "gtk-xft-rgba" property

  "gtk-xft-rgba"             gchararray            : Read / Write

Type of subpixel antialiasing; none, rgb, bgr, vrgb, vbgr.

Default value: NULL


GtkSizeGroup

GtkSizeGroup — Grouping widgets so they request the same size

Synopsis

#include <gtk/gtk.h>

                    GtkSizeGroup;
enum                GtkSizeGroupMode;
GtkSizeGroup*       gtk_size_group_new                  (GtkSizeGroupMode mode);
void                gtk_size_group_set_mode             (GtkSizeGroup *size_group,
                                                         GtkSizeGroupMode mode);
GtkSizeGroupMode    gtk_size_group_get_mode             (GtkSizeGroup *size_group);
void                gtk_size_group_set_ignore_hidden    (GtkSizeGroup *size_group,
                                                         gboolean ignore_hidden);
gboolean            gtk_size_group_get_ignore_hidden    (GtkSizeGroup *size_group);
void                gtk_size_group_add_widget           (GtkSizeGroup *size_group,
                                                         GtkWidget *widget);
void                gtk_size_group_remove_widget        (GtkSizeGroup *size_group,
                                                         GtkWidget *widget);
GSList*             gtk_size_group_get_widgets          (GtkSizeGroup *size_group);

Object Hierarchy

  GObject
   +----GtkSizeGroup

Properties

  "ignore-hidden"            gboolean              : Read / Write
  "mode"                     GtkSizeGroupMode      : Read / Write

Description

GtkSizeGroup provides a mechanism for grouping a number of widgets together so they all request the same amount of space. This is typically useful when you want a column of widgets to have the same size, but you can't use a GtkTable widget.

In detail, the size requested for each widget in a GtkSizeGroup is the maximum of the sizes that would have been requested for each widget in the size group if they were not in the size group. The mode of the size group (see gtk_size_group_set_mode()) determines whether this applies to the horizontal size, the vertical size, or both sizes.

Note that size groups only affect the amount of space requested, not the size that the widgets finally receive. If you want the widgets in a GtkSizeGroup to actually be the same size, you need to pack them in such a way that they get the size they request and not more. For example, if you are packing your widgets into a table, you would not include the GTK_FILL flag.

GtkSizeGroup objects are referenced by each widget in the size group, so once you have added all widgets to a GtkSizeGroup, you can drop the initial reference to the size group with g_object_unref(). If the widgets in the size group are subsequently destroyed, then they will be removed from the size group and drop their references on the size group; when all widgets have been removed, the size group will be freed.

Widgets can be part of multiple size groups; GTK+ will compute the horizontal size of a widget from the horizontal requisition of all widgets that can be reached from the widget by a chain of size groups of type GTK_SIZE_GROUP_HORIZONTAL or GTK_SIZE_GROUP_BOTH, and the vertical size from the vertical requisition of all widgets that can be reached from the widget by a chain of size groups of type GTK_SIZE_GROUP_VERTICAL or GTK_SIZE_GROUP_BOTH.

Details

GtkSizeGroup

typedef struct _GtkSizeGroup GtkSizeGroup;

enum GtkSizeGroupMode

typedef enum {
  GTK_SIZE_GROUP_NONE,
  GTK_SIZE_GROUP_HORIZONTAL,
  GTK_SIZE_GROUP_VERTICAL,
  GTK_SIZE_GROUP_BOTH
} GtkSizeGroupMode;

The mode of the size group determines the directions in which the size group affects the requested sizes of its component widgets.

GTK_SIZE_GROUP_NONE | group has no effect
GTK_SIZE_GROUP_HORIZONTAL | group affects horizontal requisition
GTK_SIZE_GROUP_VERTICAL | group affects vertical requisition
GTK_SIZE_GROUP_BOTH | group affects both horizontal and vertical requisition

gtk_size_group_new ()

GtkSizeGroup*       gtk_size_group_new                  (GtkSizeGroupMode mode);

Create a new GtkSizeGroup.

mode : | the mode for the new size group.
Returns : | a newly created GtkSizeGroup

gtk_size_group_set_mode ()

void                gtk_size_group_set_mode             (GtkSizeGroup *size_group,
                                                         GtkSizeGroupMode mode);

Sets the GtkSizeGroupMode of the size group. The mode of the size group determines whether the widgets in the size group should all have the same horizontal requisition (GTK_SIZE_GROUP_MODE_HORIZONTAL) all have the same vertical requisition (GTK_SIZE_GROUP_MODE_VERTICAL), or should all have the same requisition in both directions (GTK_SIZE_GROUP_MODE_BOTH).

size_group : | a GtkSizeGroup
mode : | the mode to set for the size group.

gtk_size_group_get_mode ()

GtkSizeGroupMode    gtk_size_group_get_mode             (GtkSizeGroup *size_group);

Gets the current mode of the size group. See gtk_size_group_set_mode().

size_group : | a GtkSizeGroup
Returns : | the current mode of the size group.

gtk_size_group_set_ignore_hidden ()

void                gtk_size_group_set_ignore_hidden    (GtkSizeGroup *size_group,
                                                         gboolean ignore_hidden);

Sets whether unmapped widgets should be ignored when calculating the size.

size_group : | a GtkSizeGroup
ignore_hidden : | whether unmapped widgets should be ignored when calculating the size

Since 2.8

gtk_size_group_get_ignore_hidden ()

gboolean            gtk_size_group_get_ignore_hidden    (GtkSizeGroup *size_group);

Returns if invisible widgets are ignored when calculating the size.

size_group : | a GtkSizeGroup
Returns : | TRUE if invisible widgets are ignored.

Since 2.8

gtk_size_group_add_widget ()

void                gtk_size_group_add_widget           (GtkSizeGroup *size_group,
                                                         GtkWidget *widget);

Adds a widget to a GtkSizeGroup. In the future, the requisition of the widget will be determined as the maximum of its requisition and the requisition of the other widgets in the size group. Whether this applies horizontally, vertically, or in both directions depends on the mode of the size group. See gtk_size_group_set_mode().

size_group : | a GtkSizeGroup
widget : | the GtkWidget to add

gtk_size_group_remove_widget ()

void                gtk_size_group_remove_widget        (GtkSizeGroup *size_group,
                                                         GtkWidget *widget);

Removes a widget from a GtkSizeGroup.

size_group : | a GtkSizeGrup
widget : | the GtkWidget to remove

gtk_size_group_get_widgets ()

GSList*             gtk_size_group_get_widgets          (GtkSizeGroup *size_group);

Returns the list of widgets associated with size_group.

size_group : | a GtkSizeGrup
Returns : | a GSList of widgets. The list is owned by GTK+ and should not be modified.

Since 2.10

Property Details

The "ignore-hidden" property

  "ignore-hidden"            gboolean              : Read / Write

If TRUE, unmapped widgets are ignored when determining the size of the group.

Default value: FALSE

Since 2.8

The "mode" property

  "mode"                     GtkSizeGroupMode      : Read / Write

The directions in which the size group affects the requested sizes of its component widgets.

Default value: GTK_SIZE_GROUP_HORIZONTAL


GtkSocket

GtkSocket — Container for widgets from other processes

Synopsis

#include <gtk/gtk.h>

                    GtkSocket;
GtkWidget*          gtk_socket_new                      (void);
void                gtk_socket_steal                    (GtkSocket *socket_,
                                                         GdkNativeWindow wid);
void                gtk_socket_add_id                   (GtkSocket *socket_,
                                                         GdkNativeWindow window_id);
GdkNativeWindow     gtk_socket_get_id                   (GtkSocket *socket_);

Object Hierarchy

  GObject
   +----GInitiallyUnowned
         +----GtkObject
               +----GtkWidget
                     +----GtkContainer
                           +----GtkSocket

Implemented Interfaces

GtkSocket implements AtkImplementorIface.

Signals

  "plug-added"                                     : Run Last
  "plug-removed"                                   : Run Last

Description

Together with GtkPlug, GtkSocket provides the ability to embed widgets from one process into another process in a fashion that is transparent to the user. One process creates a GtkSocket widget and, passes the that widget's window ID to the other process, which then creates a GtkPlug with that window ID. Any widgets contained in the GtkPlug then will appear inside the first applications window.

The socket's window ID is obtained by using gtk_socket_get_id(). Before using this function, the socket must have been realized, and for hence, have been added to its parent.

Example 36. Obtaining the window ID of a socket.

GtkWidget *socket = gtk_socket_new ();
gtk_widget_show (socket);
gtk_container_add (GTK_CONTAINER (parent), socket);

/* The following call is only necessary if one of
 * the ancestors of the socket is not yet visible.
 */
gtk_widget_realize (socket);
g_print ("The ID of the sockets window is %x\n",
         gtk_socket_get_id (socket));

Note that if you pass the window ID of the socket to another process that will create a plug in the socket, you must make sure that the socket widget is not destroyed until that plug is created. Violating this rule will cause unpredictable consequences, the most likely consequence being that the plug will appear as a separate toplevel window. You can check if the plug has been created by examining the plug_window field of the GtkSocket structure. If this field is non-NULL, then the plug has been successfully created inside of the socket.

When GTK+ is notified that the embedded window has been destroyed, then it will destroy the socket as well. You should always, therefore, be prepared for your sockets to be destroyed at any time when the main event loop is running.

The communication between a GtkSocket and a GtkPlug follows the XEmbed protocol. This protocol has also been implemented in other toolkits, e.g. Qt, allowing the same level of integration when embedding a Qt widget in GTK or vice versa.

A socket can also be used to swallow arbitrary pre-existing top-level windows using gtk_socket_steal(), though the integration when this is done will not be as close as between a GtkPlug and a GtkSocket.

Note

The GtkPlug and GtkSocket widgets are currently not available on all platforms supported by GTK+.

Details

GtkSocket

typedef struct _GtkSocket GtkSocket;

The GtkSocket structure contains the plug_window field. (This field should be considered read-only. It should never be set by an application.)

gtk_socket_new ()

GtkWidget*          gtk_socket_new                      (void);

Create a new empty GtkSocket.

Returns : the new GtkSocket.

gtk_socket_steal ()

void                gtk_socket_steal                    (GtkSocket *socket_,
                                                         GdkNativeWindow wid);

Warning

gtk_socket_steal is deprecated and should not be used in newly-written code.

Reparents a pre-existing toplevel window into a GtkSocket. This is meant to embed clients that do not know about embedding into a GtkSocket, however doing so is inherently unreliable, and using this function is not recommended.

The GtkSocket must have already be added into a toplevel window before you can make this call.

socket_ : | a GtkSocket
wid : | the window ID of an existing toplevel window.

gtk_socket_add_id ()

void                gtk_socket_add_id                   (GtkSocket *socket_,
                                                         GdkNativeWindow window_id);

Adds an XEMBED client, such as a GtkPlug, to the GtkSocket. The client may be in the same process or in a different process.

To embed a GtkPlug in a GtkSocket, you can either create the GtkPlug with gtk_plug_new (0), call gtk_plug_get_id() to get the window ID of the plug, and then pass that to the gtk_socket_add_id(), or you can call gtk_socket_get_id() to get the window ID for the socket, and call gtk_plug_new() passing in that ID.

The GtkSocket must have already be added into a toplevel window before you can make this call.

socket_ : | a GtkSocket
window_id : | the window ID of a client participating in the XEMBED protocol.

gtk_socket_get_id ()

GdkNativeWindow     gtk_socket_get_id                   (GtkSocket *socket_);

Gets the window ID of a GtkSocket widget, which can then be used to create a client embedded inside the socket, for instance with gtk_plug_new().

The GtkSocket must have already be added into a toplevel window before you can make this call.

socket_ : | a GtkSocket.
Returns : | the window ID for the socket

Signal Details

The "plug-added" signal

void                user_function                      (GtkSocket *socket,
                                                        gpointer   user_data)      : Run Last

This signal is emitted when a client is successfully added to the socket.

socket : | the object which received the signal.
user_data : | user data set when the signal handler was connected.

The "plug-removed" signal

gboolean            user_function                      (GtkSocket *socket,
                                                        gpointer   user_data)      : Run Last

This signal is emitted when a client is removed from the socket. The default action is to destroy the GtkSocket widget, so if you want to reuse it you must add a signal handler that returns TRUE.

socket : | the object which received the signal.
user_data : | user data set when the signal handler was connected.
Returns : |

See Also

GtkPlug | the widget that plugs into a GtkSocket.
XEmbed | the XEmbed Protocol Specification.


GtkSpinButton

GtkSpinButton — Retrieve an integer or floating-point number from the user

Synopsis

#include <gtk/gtk.h>

                    GtkSpinButton;
enum                GtkSpinButtonUpdatePolicy;
enum                GtkSpinType;
void                gtk_spin_button_configure           (GtkSpinButton *spin_button,
                                                         GtkAdjustment *adjustment,
                                                         gdouble climb_rate,
                                                         guint digits);
GtkWidget*          gtk_spin_button_new                 (GtkAdjustment *adjustment,
                                                         gdouble climb_rate,
                                                         guint digits);
GtkWidget*          gtk_spin_button_new_with_range      (gdouble min,
                                                         gdouble max,
                                                         gdouble step);
void                gtk_spin_button_set_adjustment      (GtkSpinButton *spin_button,
                                                         GtkAdjustment *adjustment);
GtkAdjustment*      gtk_spin_button_get_adjustment      (GtkSpinButton *spin_button);
void                gtk_spin_button_set_digits          (GtkSpinButton *spin_button,
                                                         guint digits);
void                gtk_spin_button_set_increments      (GtkSpinButton *spin_button,
                                                         gdouble step,
                                                         gdouble page);
void                gtk_spin_button_set_range           (GtkSpinButton *spin_button,
                                                         gdouble min,
                                                         gdouble max);
#define             gtk_spin_button_get_value_as_float
gint                gtk_spin_button_get_value_as_int    (GtkSpinButton *spin_button);
void                gtk_spin_button_set_value           (GtkSpinButton *spin_button,
                                                         gdouble value);
void                gtk_spin_button_set_update_policy   (GtkSpinButton *spin_button,
                                                         GtkSpinButtonUpdatePolicy policy);
void                gtk_spin_button_set_numeric         (GtkSpinButton *spin_button,
                                                         gboolean numeric);
void                gtk_spin_button_spin                (GtkSpinButton *spin_button,
                                                         GtkSpinType direction,
                                                         gdouble increment);
void                gtk_spin_button_set_wrap            (GtkSpinButton *spin_button,
                                                         gboolean wrap);
void                gtk_spin_button_set_snap_to_ticks   (GtkSpinButton *spin_button,
                                                         gboolean snap_to_ticks);
void                gtk_spin_button_update              (GtkSpinButton *spin_button);
guint               gtk_spin_button_get_digits          (GtkSpinButton *spin_button);
void                gtk_spin_button_get_increments      (GtkSpinButton *spin_button,
                                                         gdouble *step,
                                                         gdouble *page);
gboolean            gtk_spin_button_get_numeric         (GtkSpinButton *spin_button);
void                gtk_spin_button_get_range           (GtkSpinButton *spin_button,
                                                         gdouble *min,
                                                         gdouble *max);
gboolean            gtk_spin_button_get_snap_to_ticks   (GtkSpinButton *spin_button);
GtkSpinButtonUpdatePolicy gtk_spin_button_get_update_policy
                                                        (GtkSpinButton *spin_button);
gdouble             gtk_spin_button_get_value           (GtkSpinButton *spin_button);
gboolean            gtk_spin_button_get_wrap            (GtkSpinButton *spin_button);
#define             GTK_INPUT_ERROR

Object Hierarchy

  GObject
   +----GInitiallyUnowned
         +----GtkObject
               +----GtkWidget
                     +----GtkEntry
                           +----GtkSpinButton

Implemented Interfaces

GtkSpinButton implements AtkImplementorIface, GtkCellEditable and GtkEditable.

Properties

  "adjustment"               GtkAdjustment         : Read / Write
  "climb-rate"               gdouble               : Read / Write
  "digits"                   guint                 : Read / Write
  "numeric"                  gboolean              : Read / Write
  "snap-to-ticks"            gboolean              : Read / Write
  "update-policy"            GtkSpinButtonUpdatePolicy  : Read / Write
  "value"                    gdouble               : Read / Write
  "wrap"                     gboolean              : Read / Write

Style Properties

  "shadow-type"              GtkShadowType         : Read

Signals

  "change-value"                                   : Run Last / Action
  "input"                                          : Run Last
  "output"                                         : Run Last
  "value-changed"                                  : Run Last
  "wrapped"                                        : Run Last

Description

A GtkSpinButton is an ideal way to allow the user to set the value of some attribute. Rather than having to directly type a number into a GtkEntry, GtkSpinButton allows the user to click on one of two arrows to increment or decrement the displayed value. A value can still be typed in, with the bonus that it can be checked to ensure it is in a given range.

The main properties of a GtkSpinButton are through a GtkAdjustment. See the GtkAdjustment section for more details about an adjustment's properties.

Example 11. Using a GtkSpinButton to get an integer.

/* Provides a function to retrieve an integer value from a GtkSpinButton
 * and creates a spin button to model percentage values.
 */

gint grab_int_value (GtkSpinButton *a_spinner, gpointer user_data) {
   return gtk_spin_button_get_value_as_int (a_spinner);
}

void create_integer_spin_button (void) {

   GtkWidget *window, *spinner;
   GtkAdjustment *spinner_adj;

   spinner_adj = (GtkAdjustment *) gtk_adjustment_new (50.0, 0.0, 100.0, 1.0, 5.0, 5.0);

   window = gtk_window_new (GTK_WINDOW_TOPLEVEL);
   gtk_container_set_border_width (GTK_CONTAINER (window), 5);

   /* creates the spinner, with no decimal places */
   spinner = gtk_spin_button_new (spinner_adj, 1.0, 0);
   gtk_container_add (GTK_CONTAINER (window), spinner);

   gtk_widget_show_all (window);
   return;
}

Example 12. Using a GtkSpinButton to get a floating point value.

/* Provides a function to retrieve a floating point value from a
 * GtkSpinButton, and creates a high precision spin button.
 */

gfloat grab_int_value (GtkSpinButton *a_spinner, gpointer user_data) {
   return gtk_spin_button_get_value (a_spinner);
}

void create_floating_spin_button (void) {

   GtkWidget *window, *spinner;
   GtkAdjustment *spinner_adj;

   spinner_adj = (GtkAdjustment *) gtk_adjustment_new (2.500, 0.0, 5.0, 0.001, 0.1, 0.1);

   window = gtk_window_new (GTK_WINDOW_TOPLEVEL);
   gtk_container_set_border_width (GTK_CONTAINER (window), 5);

   /* creates the spinner, with three decimal places */
   spinner = gtk_spin_button_new (spinner_adj, 0.001, 3);
   gtk_container_add (GTK_CONTAINER (window), spinner);

   gtk_widget_show_all (window);
   return;
}

Details

GtkSpinButton

typedef struct _GtkSpinButton GtkSpinButton;

entry is the GtkEntry part of the GtkSpinButton widget, and can be used accordingly. All other fields contain private data and should only be modified using the functions below.

enum GtkSpinButtonUpdatePolicy

typedef enum
{
  GTK_UPDATE_ALWAYS,
  GTK_UPDATE_IF_VALID
} GtkSpinButtonUpdatePolicy;

GTK_UPDATE_ALWAYS | When refreshing your GtkSpinButton, the value is always displayed.
GTK_UPDATE_IF_VALID | When refreshing your GtkSpinButton, the value is only displayed if it is valid within the bounds of the spin button's GtkAdjustment.

enum GtkSpinType

typedef enum
{
  GTK_SPIN_STEP_FORWARD,
  GTK_SPIN_STEP_BACKWARD,
  GTK_SPIN_PAGE_FORWARD,
  GTK_SPIN_PAGE_BACKWARD,
  GTK_SPIN_HOME,
  GTK_SPIN_END,
  GTK_SPIN_USER_DEFINED
} GtkSpinType;

GTK_SPIN_STEP_FORWARD, GTK_SPIN_STEP_BACKWARD, GTK_SPIN_PAGE_FORWARD, GTK_SPIN_PAGE_BACKWARD | These values spin a GtkSpinButton by the relevant values of the spin button's GtkAdjustment.
GTK_SPIN_HOME, GTK_SPIN_END | These set the spin button's value to the minimum or maxmimum possible values, (set by its GtkAdjustment), respectively.
GTK_SPIN_USER_DEFINED | The programmer must specify the exact amount to spin the GtkSpinButton.

gtk_spin_button_configure ()

void                gtk_spin_button_configure           (GtkSpinButton *spin_button,
                                                         GtkAdjustment *adjustment,
                                                         gdouble climb_rate,
                                                         guint digits);

Changes the properties of an existing spin button. The adjustment, climb rate, and number of decimal places are all changed accordingly, after this function call.

spin_button : | a GtkSpinButton.
adjustment : | a GtkAdjustment.
climb_rate : | the new climb rate.
digits : | the number of decimal places to display in the spin button.

gtk_spin_button_new ()

GtkWidget*          gtk_spin_button_new                 (GtkAdjustment *adjustment,
                                                         gdouble climb_rate,
                                                         guint digits);

Creates a new GtkSpinButton.

adjustment : | the GtkAdjustment object that this spin button should use.
climb_rate : | specifies how much the spin button changes when an arrow is clicked on.
digits : | the number of decimal places to display.
Returns : | The new spin button as a GtkWidget.

gtk_spin_button_new_with_range ()

GtkWidget*          gtk_spin_button_new_with_range      (gdouble min,
                                                         gdouble max,
                                                         gdouble step);

This is a convenience constructor that allows creation of a numeric GtkSpinButton without manually creating an adjustment. The value is initially set to the minimum value and a page increment of 10 * step is the default. The precision of the spin button is equivalent to the precision of step.

Note that the way in which the precision is derived works best if step is a power of ten. If the resulting precision is not suitable for your needs, use gtk_spin_button_set_digits() to correct it.

min : | Minimum allowable value
max : | Maximum allowable value
step : | Increment added or subtracted by spinning the widget
Returns : | The new spin button as a GtkWidget.

gtk_spin_button_set_adjustment ()

void                gtk_spin_button_set_adjustment      (GtkSpinButton *spin_button,
                                                         GtkAdjustment *adjustment);

Replaces the GtkAdjustment associated with spin_button.

spin_button : | a GtkSpinButton
adjustment : | a GtkAdjustment to replace the existing adjustment

gtk_spin_button_get_adjustment ()

GtkAdjustment*      gtk_spin_button_get_adjustment      (GtkSpinButton *spin_button);

Get the adjustment associated with a GtkSpinButton

spin_button : | a GtkSpinButton
Returns : | the GtkAdjustment of spin_button

gtk_spin_button_set_digits ()

void                gtk_spin_button_set_digits          (GtkSpinButton *spin_button,
                                                         guint digits);

Set the precision to be displayed by spin_button. Up to 20 digit precision is allowed.

spin_button : | a GtkSpinButton
digits : | the number of digits after the decimal point to be displayed for the spin button's value

gtk_spin_button_set_increments ()

void                gtk_spin_button_set_increments      (GtkSpinButton *spin_button,
                                                         gdouble step,
                                                         gdouble page);

Sets the step and page increments for spin_button. This affects how quickly the value changes when the spin button's arrows are activated.

spin_button : | a GtkSpinButton
step : | increment applied for a button 1 press.
page : | increment applied for a button 2 press.

gtk_spin_button_set_range ()

void                gtk_spin_button_set_range           (GtkSpinButton *spin_button,
                                                         gdouble min,
                                                         gdouble max);

Sets the minimum and maximum allowable values for spin_button

spin_button : | a GtkSpinButton
min : | minimum allowable value
max : | maximum allowable value

gtk_spin_button_get_value_as_float

#define gtk_spin_button_get_value_as_float gtk_spin_button_get_value

Warning

gtk_spin_button_get_value_as_float is deprecated and should not be used in newly-written code.

Gets the value in the spin_button. This function is deprecated, use gtk_spin_button_get_value() instead.

Returns : the value of spin_button.

gtk_spin_button_get_value_as_int ()

gint                gtk_spin_button_get_value_as_int    (GtkSpinButton *spin_button);

Get the value spin_button represented as an integer.

spin_button : | a GtkSpinButton
Returns : | the value of spin_button

gtk_spin_button_set_value ()

void                gtk_spin_button_set_value           (GtkSpinButton *spin_button,
                                                         gdouble value);

Set the value of spin_button.

spin_button : | a GtkSpinButton
value : | the new value

gtk_spin_button_set_update_policy ()

void                gtk_spin_button_set_update_policy   (GtkSpinButton *spin_button,
                                                         GtkSpinButtonUpdatePolicy policy);

Sets the update behavior of a spin button. This determines whether the spin button is always updated or only when a valid value is set.

spin_button : | a GtkSpinButton
policy : | a GtkSpinButtonUpdatePolicy value

gtk_spin_button_set_numeric ()

void                gtk_spin_button_set_numeric         (GtkSpinButton *spin_button,
                                                         gboolean numeric);

Sets the flag that determines if non-numeric text can be typed into the spin button.

spin_button : | a GtkSpinButton
numeric : | flag indicating if only numeric entry is allowed.

gtk_spin_button_spin ()

void                gtk_spin_button_spin                (GtkSpinButton *spin_button,
                                                         GtkSpinType direction,
                                                         gdouble increment);

Increment or decrement a spin button's value in a specified direction by a specified amount.

spin_button : | a GtkSpinButton
direction : | a GtkSpinType indicating the direction to spin.
increment : | step increment to apply in the specified direction.

gtk_spin_button_set_wrap ()

void                gtk_spin_button_set_wrap            (GtkSpinButton *spin_button,
                                                         gboolean wrap);

Sets the flag that determines if a spin button value wraps around to the opposite limit when the upper or lower limit of the range is exceeded.

spin_button : | a GtkSpinButton
wrap : | a flag indicating if wrapping behavior is performed.

gtk_spin_button_set_snap_to_ticks ()

void                gtk_spin_button_set_snap_to_ticks   (GtkSpinButton *spin_button,
                                                         gboolean snap_to_ticks);

Sets the policy as to whether values are corrected to the nearest step increment when a spin button is activated after providing an invalid value.

spin_button : | a GtkSpinButton
snap_to_ticks : | a flag indicating if invalid values should be corrected.

gtk_spin_button_update ()

void                gtk_spin_button_update              (GtkSpinButton *spin_button);

Manually force an update of the spin button.

spin_button : a GtkSpinButton

gtk_spin_button_get_digits ()

guint               gtk_spin_button_get_digits          (GtkSpinButton *spin_button);

Fetches the precision of spin_button. See gtk_spin_button_set_digits().

spin_button : | a GtkSpinButton
Returns : | the current precision

gtk_spin_button_get_increments ()

void                gtk_spin_button_get_increments      (GtkSpinButton *spin_button,
                                                         gdouble *step,
                                                         gdouble *page);

Gets the current step and page the increments used by spin_button. See gtk_spin_button_set_increments().

spin_button : | a GtkSpinButton
step : | location to store step increment, or NULL
page : | location to store page increment, or NULL

gtk_spin_button_get_numeric ()

gboolean            gtk_spin_button_get_numeric         (GtkSpinButton *spin_button);

Returns whether non-numeric text can be typed into the spin button. See gtk_spin_button_set_numeric().

spin_button : | a GtkSpinButton
Returns : | TRUE if only numeric text can be entered

gtk_spin_button_get_range ()

void                gtk_spin_button_get_range           (GtkSpinButton *spin_button,
                                                         gdouble *min,
                                                         gdouble *max);

Gets the range allowed for spin_button. See gtk_spin_button_set_range().

spin_button : | a GtkSpinButton
min : | location to store minimum allowed value, or NULL
max : | location to store maximum allowed value, or NULL

gtk_spin_button_get_snap_to_ticks ()

gboolean            gtk_spin_button_get_snap_to_ticks   (GtkSpinButton *spin_button);

Returns whether the values are corrected to the nearest step. See gtk_spin_button_set_snap_to_ticks().

spin_button : | a GtkSpinButton
Returns : | TRUE if values are snapped to the nearest step.

gtk_spin_button_get_update_policy ()

GtkSpinButtonUpdatePolicy gtk_spin_button_get_update_policy
                                                        (GtkSpinButton *spin_button);

Gets the update behavior of a spin button. See gtk_spin_button_set_update_policy().

spin_button : | a GtkSpinButton
Returns : | the current update policy

gtk_spin_button_get_value ()

gdouble             gtk_spin_button_get_value           (GtkSpinButton *spin_button);

Get the value in the spin_button.

spin_button : | a GtkSpinButton
Returns : | the value of spin_button

gtk_spin_button_get_wrap ()

gboolean            gtk_spin_button_get_wrap            (GtkSpinButton *spin_button);

Returns whether the spin button's value wraps around to the opposite limit when the upper or lower limit of the range is exceeded. See gtk_spin_button_set_wrap().

spin_button : | a GtkSpinButton
Returns : | TRUE if the spin button wraps around

GTK_INPUT_ERROR

#define GTK_INPUT_ERROR -1

Property Details

The "adjustment" property

  "adjustment"               GtkAdjustment         : Read / Write

The adjustment that holds the value of the spinbutton.

The "climb-rate" property

  "climb-rate"               gdouble               : Read / Write

The acceleration rate when you hold down a button.

Allowed values: >= 0

Default value: 0

The "digits" property

  "digits"                   guint                 : Read / Write

The number of decimal places to display.

Allowed values: <= 20

Default value: 0

The "numeric" property

  "numeric"                  gboolean              : Read / Write

Whether non-numeric characters should be ignored.

Default value: FALSE

The "snap-to-ticks" property

  "snap-to-ticks"            gboolean              : Read / Write

Whether erroneous values are automatically changed to a spin button's nearest step increment.

Default value: FALSE

The "update-policy" property

  "update-policy"            GtkSpinButtonUpdatePolicy  : Read / Write

Whether the spin button should update always, or only when the value is legal.

Default value: GTK_UPDATE_ALWAYS

The "value" property

  "value"                    gdouble               : Read / Write

Reads the current value, or sets a new value.

Default value: 0

The "wrap" property

  "wrap"                     gboolean              : Read / Write

Whether a spin button should wrap upon reaching its limits.

Default value: FALSE

Style Property Details

The "shadow-type" style property

  "shadow-type"              GtkShadowType         : Read

the type of border that surrounds the arrows of a spin button.

Default value: GTK_SHADOW_IN

Signal Details

The "change-value" signal

void                user_function                      (GtkSpinButton *spinbutton,
                                                        GtkScrollType  arg1,
                                                        gpointer       user_data)       : Run Last / Action

spinbutton : | the object which received the signal.
arg1 : |
user_data : | user data set when the signal handler was connected.

The "input" signal

gint                user_function                      (GtkSpinButton *spinbutton,
                                                        gpointer       arg1,
                                                        gpointer       user_data)       : Run Last

spinbutton : | the object which received the signal.
arg1 : |
user_data : | user data set when the signal handler was connected.
Returns : |

The "output" signal

gboolean            user_function                      (GtkSpinButton *spinbutton,
                                                        gpointer       user_data)       : Run Last

spinbutton : | the object which received the signal.
user_data : | user data set when the signal handler was connected.
Returns : |

The "value-changed" signal

void                user_function                      (GtkSpinButton *spinbutton,
                                                        gpointer       user_data)       : Run Last

spinbutton : | the object which received the signal.
user_data : | user data set when the signal handler was connected.

The "wrapped" signal

void                user_function                      (GtkSpinButton *spinbutton,
                                                        gpointer       user_data)       : Run Last

The wrapped signal is emitted right after the spinbutton wraps from its maximum to minimum value or vice-versa.

spinbutton : | the object which received the signal
user_data : | user data set when the signal handler was connected.

Since 2.10

See Also

GtkEntry

retrieve text rather than numbers.


GtkStatusbar

GtkStatusbar — Report messages of minor importance to the user

Synopsis

#include <gtk/gtk.h>

                    GtkStatusbar;
GtkWidget*          gtk_statusbar_new                   (void);
guint               gtk_statusbar_get_context_id        (GtkStatusbar *statusbar,
                                                         const gchar *context_description);
guint               gtk_statusbar_push                  (GtkStatusbar *statusbar,
                                                         guint context_id,
                                                         const gchar *text);
void                gtk_statusbar_pop                   (GtkStatusbar *statusbar,
                                                         guint context_id);
void                gtk_statusbar_remove                (GtkStatusbar *statusbar,
                                                         guint context_id,
                                                         guint message_id);
void                gtk_statusbar_set_has_resize_grip   (GtkStatusbar *statusbar,
                                                         gboolean setting);
gboolean            gtk_statusbar_get_has_resize_grip   (GtkStatusbar *statusbar);

Object Hierarchy

  GObject
   +----GInitiallyUnowned
         +----GtkObject
               +----GtkWidget
                     +----GtkContainer
                           +----GtkBox
                                 +----GtkHBox
                                       +----GtkStatusbar

Implemented Interfaces

GtkStatusbar implements AtkImplementorIface.

Properties

  "has-resize-grip"          gboolean              : Read / Write

Style Properties

  "shadow-type"              GtkShadowType         : Read

Signals

  "text-popped"                                    : Run Last
  "text-pushed"                                    : Run Last

Description

A GtkStatusbar is usually placed along the bottom of an application's main GtkWindow. It may provide a regular commentary of the application's status (as is usually the case in a web browser, for example), or may be used to simply output a message when the status changes, (when an upload is complete in an FTP client, for example). It may also have a resize grip (a triangular area in the lower right corner) which can be clicked on to resize the window containing the statusbar.

Status bars in Gtk+ maintain a stack of messages. The message at the top of the each bar's stack is the one that will currently be displayed.

Any messages added to a statusbar's stack must specify a context_id that is used to uniquely identify the source of a message. This context_id can be generated by gtk_statusbar_get_context_id(), given a message and the statusbar that it will be added to. Note that messages are stored in a stack, and when choosing which message to display, the stack structure is adhered to, regardless of the context identifier of a message.

Status bars are created using gtk_statusbar_new().

Messages are added to the bar's stack with gtk_statusbar_push().

The message at the top of the stack can be removed using gtk_statusbar_pop(). A message can be removed from anywhere in the stack if its message_id was recorded at the time it was added. This is done using gtk_statusbar_remove().

Details

GtkStatusbar

typedef struct _GtkStatusbar GtkStatusbar;

Contains private data that should be modified with the functions described below.

gtk_statusbar_new ()

GtkWidget*          gtk_statusbar_new                   (void);

Creates a new GtkStatusbar ready for messages.

Returns : the new GtkStatusbar.

gtk_statusbar_get_context_id ()

guint               gtk_statusbar_get_context_id        (GtkStatusbar *statusbar,
                                                         const gchar *context_description);

Returns a new context identifier, given a description of the actual context.

statusbar : | a GtkStatusbar.
context_description : | textual description of what context the new message is being used in.
Returns : | an integer id.

gtk_statusbar_push ()

guint               gtk_statusbar_push                  (GtkStatusbar *statusbar,
                                                         guint context_id,
                                                         const gchar *text);

Pushes a new message onto a statusbar's stack.

statusbar : | a GtkStatusbar.
context_id : | the message's context id, as returned by gtk_statusbar_get_context_id().
text : | the message to add to the statusbar.
Returns : | the message's new message id for use with gtk_statusbar_remove().

gtk_statusbar_pop ()

void                gtk_statusbar_pop                   (GtkStatusbar *statusbar,
                                                         guint context_id);

Removes the message at the top of a GtkStatusBar's stack.

statusbar : | a GtkStatusBar.
context_id : | a context identifier.

gtk_statusbar_remove ()

void                gtk_statusbar_remove                (GtkStatusbar *statusbar,
                                                         guint context_id,
                                                         guint message_id);

Forces the removal of a message from a statusbar's stack. The exact context_id and message_id must be specified.

statusbar : | a GtkStatusBar.
context_id : | a context identifier.
message_id : | a message identifier, as returned by gtk_statusbar_push().

gtk_statusbar_set_has_resize_grip ()

void                gtk_statusbar_set_has_resize_grip   (GtkStatusbar *statusbar,
                                                         gboolean setting);

Sets whether the statusbar has a resize grip. TRUE by default.

statusbar : | a GtkStatusBar.
setting : | TRUE to have a resize grip.

gtk_statusbar_get_has_resize_grip ()

gboolean            gtk_statusbar_get_has_resize_grip   (GtkStatusbar *statusbar);

Returns whether the statusbar has a resize grip.

statusbar : | a GtkStatusBar.
Returns : | TRUE if the statusbar has a resize grip.

Property Details

The "has-resize-grip" property

  "has-resize-grip"          gboolean              : Read / Write

Whether the statusbar has a grip for resizing the toplevel window.

Default value: TRUE

Since 2.4

Style Property Details

The "shadow-type" style property

  "shadow-type"              GtkShadowType         : Read

Style of bevel around the statusbar text.

Default value: GTK_SHADOW_IN

Signal Details

The "text-popped" signal

void                user_function                      (GtkStatusbar *statusbar,
                                                        guint         context_id,
                                                        gchar        *text,
                                                        gpointer      user_data)       : Run Last

Is emitted whenever a new message is popped off a statusbar's stack.

statusbar : | the object which received the signal.
context_id : | the context id of the relevant message/statusbar.
text : | the message that was just popped.
user_data : | user data set when the signal handler was connected.

The "text-pushed" signal

void                user_function                      (GtkStatusbar *statusbar,
                                                        guint         context_id,
                                                        gchar        *text,
                                                        gpointer      user_data)       : Run Last

Is emitted whenever a new message gets pushed onto a statusbar's stack.

statusbar : | the object which received the signal.
context_id : | the context id of the relevant message/statusbar.
text : | the message that was pushed.
user_data : | user data set when the signal handler was connected.

See Also

GtkDialog

another way of reporting information to the user.


GtkStatusIcon

GtkStatusIcon — Display an icon in the system tray

Synopsis

#include <gtk/gtk.h>

                    GtkStatusIcon;
GtkStatusIcon*      gtk_status_icon_new                 (void);
GtkStatusIcon*      gtk_status_icon_new_from_pixbuf     (GdkPixbuf *pixbuf);
GtkStatusIcon*      gtk_status_icon_new_from_file       (const gchar *filename);
GtkStatusIcon*      gtk_status_icon_new_from_stock      (const gchar *stock_id);
GtkStatusIcon*      gtk_status_icon_new_from_icon_name  (const gchar *icon_name);
void                gtk_status_icon_set_from_pixbuf     (GtkStatusIcon *status_icon,
                                                         GdkPixbuf *pixbuf);
void                gtk_status_icon_set_from_file       (GtkStatusIcon *status_icon,
                                                         const gchar *filename);
void                gtk_status_icon_set_from_stock      (GtkStatusIcon *status_icon,
                                                         const gchar *stock_id);
void                gtk_status_icon_set_from_icon_name  (GtkStatusIcon *status_icon,
                                                         const gchar *icon_name);
GtkImageType        gtk_status_icon_get_storage_type    (GtkStatusIcon *status_icon);
GdkPixbuf*          gtk_status_icon_get_pixbuf          (GtkStatusIcon *status_icon);
const gchar*        gtk_status_icon_get_stock           (GtkStatusIcon *status_icon);
const gchar*        gtk_status_icon_get_icon_name       (GtkStatusIcon *status_icon);
gint                gtk_status_icon_get_size            (GtkStatusIcon *status_icon);
void                gtk_status_icon_set_tooltip         (GtkStatusIcon *status_icon,
                                                         const gchar *tooltip_text);
void                gtk_status_icon_set_visible         (GtkStatusIcon *status_icon,
                                                         gboolean visible);
gboolean            gtk_status_icon_get_visible         (GtkStatusIcon *status_icon);
void                gtk_status_icon_set_blinking        (GtkStatusIcon *status_icon,
                                                         gboolean blinking);
gboolean            gtk_status_icon_get_blinking        (GtkStatusIcon *status_icon);
gboolean            gtk_status_icon_is_embedded         (GtkStatusIcon *status_icon);
void                gtk_status_icon_position_menu       (GtkMenu *menu,
                                                         gint *x,
                                                         gint *y,
                                                         gboolean *push_in,
                                                         gpointer user_data);
gboolean            gtk_status_icon_get_geometry        (GtkStatusIcon *status_icon,
                                                         GdkScreen **screen,
                                                         GdkRectangle *area,
                                                         GtkOrientation *orientation);

Object Hierarchy

  GObject
   +----GtkStatusIcon

Properties

  "blinking"                 gboolean              : Read / Write
  "file"                     gchararray            : Write
  "icon-name"                gchararray            : Read / Write
  "pixbuf"                   GdkPixbuf             : Read / Write
  "size"                     gint                  : Read
  "stock"                    gchararray            : Read / Write
  "storage-type"             GtkImageType          : Read
  "visible"                  gboolean              : Read / Write

Signals

  "activate"                                       : Run First / Action
  "popup-menu"                                     : Run First / Action
  "size-changed"                                   : Run Last

Description

The "system tray" or notification area is normally used for transient icons that indicate some special state. For example, a system tray icon might appear to tell the user that they have new mail, or have an incoming instant message, or something along those lines. The basic idea is that creating an icon in the notification area is less annoying than popping up a dialog.

A GtkStatusIcon object can be used to display an icon in a "system tray". The icon can have a tooltip, and the user can interact with it by activating it or popping up a context menu. Critical information should not solely be displayed in a GtkStatusIcon, since it may not be visible (e.g. when the user doesn't have a notification area on his panel). This can be checked with gtk_status_icon_is_embedded().

On X11, the implementation follows the freedesktop.org "System Tray" specification. Implementations of the "tray" side of this specification can be found e.g. in the GNOME and KDE panel applications.

Note that a GtkStatusIcon is not a widget, but just a GObject. Making it a widget would be impractical, since the system tray on Win32 doesn't allow to embed arbitrary widgets.

Details

GtkStatusIcon

typedef struct _GtkStatusIcon GtkStatusIcon;

gtk_status_icon_new ()

GtkStatusIcon*      gtk_status_icon_new                 (void);

Creates an empty status icon object.

Returns : a new GtkStatusIcon

Since 2.10

gtk_status_icon_new_from_pixbuf ()

GtkStatusIcon*      gtk_status_icon_new_from_pixbuf     (GdkPixbuf *pixbuf);

Creates a status icon displaying pixbuf.

The image will be scaled down to fit in the available space in the notification area, if necessary.

pixbuf : | a GdkPixbuf
Returns : | a new GtkStatusIcon

Since 2.10

gtk_status_icon_new_from_file ()

GtkStatusIcon*      gtk_status_icon_new_from_file       (const gchar *filename);

Creates a status icon displaying the file filename.

The image will be scaled down to fit in the available space in the notification area, if necessary.

filename : | a filename
Returns : | a new GtkStatusIcon

Since 2.10

gtk_status_icon_new_from_stock ()

GtkStatusIcon*      gtk_status_icon_new_from_stock      (const gchar *stock_id);

Creates a status icon displaying a stock icon. Sample stock icon names are GTK_STOCK_OPEN, GTK_STOCK_QUIT. You can register your own stock icon names, see gtk_icon_factory_add_default() and gtk_icon_factory_add().

stock_id : | a stock icon id
Returns : | a new GtkStatusIcon

Since 2.10

gtk_status_icon_new_from_icon_name ()

GtkStatusIcon*      gtk_status_icon_new_from_icon_name  (const gchar *icon_name);

Creates a status icon displaying an icon from the current icon theme. If the current icon theme is changed, the icon will be updated appropriately.

icon_name : | an icon name
Returns : | a new GtkStatusIcon

Since 2.10

gtk_status_icon_set_from_pixbuf ()

void                gtk_status_icon_set_from_pixbuf     (GtkStatusIcon *status_icon,
                                                         GdkPixbuf *pixbuf);

Makes status_icon display pixbuf. See gtk_status_icon_new_from_pixbuf() for details.

status_icon : | a GtkStatusIcon
pixbuf : | a GdkPixbuf or NULL

Since 2.10

gtk_status_icon_set_from_file ()

void                gtk_status_icon_set_from_file       (GtkStatusIcon *status_icon,
                                                         const gchar *filename);

Makes status_icon display the file filename. See gtk_status_icon_new_from_file() for details.

status_icon : | a GtkStatusIcon
filename : | a filename

Since 2.10

gtk_status_icon_set_from_stock ()

void                gtk_status_icon_set_from_stock      (GtkStatusIcon *status_icon,
                                                         const gchar *stock_id);

Makes status_icon display the stock icon with the id stock_id. See gtk_status_icon_new_from_stock() for details.

status_icon : | a GtkStatusIcon
stock_id : | a stock icon id

Since 2.10

gtk_status_icon_set_from_icon_name ()

void                gtk_status_icon_set_from_icon_name  (GtkStatusIcon *status_icon,
                                                         const gchar *icon_name);

Makes status_icon display the icon named icon_name from the current icon theme. See gtk_status_icon_new_from_icon_name() for details.

status_icon : | a GtkStatusIcon
icon_name : | an icon name

Since 2.10

gtk_status_icon_get_storage_type ()

GtkImageType        gtk_status_icon_get_storage_type    (GtkStatusIcon *status_icon);

Gets the type of representation being used by the GtkStatusIcon to store image data. If the GtkStatusIcon has no image data, the return value will be GTK_IMAGE_EMPTY.

status_icon : | a GtkStatusIcon
Returns : | the image representation being used

Since 2.10

gtk_status_icon_get_pixbuf ()

GdkPixbuf*          gtk_status_icon_get_pixbuf          (GtkStatusIcon *status_icon);

Gets the GdkPixbuf being displayed by the GtkStatusIcon. The storage type of the status icon must be GTK_IMAGE_EMPTY or GTK_IMAGE_PIXBUF (see gtk_status_icon_get_storage_type()). The caller of this function does not own a reference to the returned pixbuf.

status_icon : | a GtkStatusIcon
Returns : | the displayed pixbuf, or NULL if the image is empty.

Since 2.10

gtk_status_icon_get_stock ()

const gchar*        gtk_status_icon_get_stock           (GtkStatusIcon *status_icon);

Gets the id of the stock icon being displayed by the GtkStatusIcon. The storage type of the status icon must be GTK_IMAGE_EMPTY or GTK_IMAGE_STOCK (see gtk_status_icon_get_storage_type()). The returned string is owned by the GtkStatusIcon and should not be freed or modified.

status_icon : | a GtkStatusIcon
Returns : | stock id of the displayed stock icon, or NULL if the image is empty.

Since 2.10

gtk_status_icon_get_icon_name ()

const gchar*        gtk_status_icon_get_icon_name       (GtkStatusIcon *status_icon);

Gets the name of the icon being displayed by the GtkStatusIcon. The storage type of the status icon must be GTK_IMAGE_EMPTY or GTK_IMAGE_ICON_NAME (see gtk_status_icon_get_storage_type()). The returned string is owned by the GtkStatusIcon and should not be freed or modified.

status_icon : | a GtkStatusIcon
Returns : | name of the displayed icon, or NULL if the image is empty.

Since 2.10

gtk_status_icon_get_size ()

gint                gtk_status_icon_get_size            (GtkStatusIcon *status_icon);

Gets the size in pixels that is available for the image. Stock icons and named icons adapt their size automatically if the size of the notification area changes. For other storage types, the size-changed signal can be used to react to size changes.

status_icon : | a GtkStatusIcon
Returns : | the size that is available for the image

Since 2.10

gtk_status_icon_set_tooltip ()

void                gtk_status_icon_set_tooltip         (GtkStatusIcon *status_icon,
                                                         const gchar *tooltip_text);

Sets the tooltip of the status icon.

status_icon : | a GtkStatusIcon
tooltip_text : | the tooltip text, or NULL

Since 2.10

gtk_status_icon_set_visible ()

void                gtk_status_icon_set_visible         (GtkStatusIcon *status_icon,
                                                         gboolean visible);

Shows or hides a status icon.

status_icon : | a GtkStatusIcon
visible : | TRUE to show the status icon, FALSE to hide it

Since 2.10

gtk_status_icon_get_visible ()

gboolean            gtk_status_icon_get_visible         (GtkStatusIcon *status_icon);

Returns whether the status icon is visible or not. Note that being visible does not guarantee that the user can actually see the icon, see also gtk_status_icon_is_embedded().

status_icon : | a GtkStatusIcon
Returns : | TRUE if the status icon is visible

Since 2.10

gtk_status_icon_set_blinking ()

void                gtk_status_icon_set_blinking        (GtkStatusIcon *status_icon,
                                                         gboolean blinking);

Makes the status icon start or stop blinking. Note that blinking user interface elements may be problematic for some users, and thus may be turned off, in which case this setting has no effect.

status_icon : | a GtkStatusIcon
blinking : | TRUE to turn blinking on, FALSE to turn it off

Since 2.10

gtk_status_icon_get_blinking ()

gboolean            gtk_status_icon_get_blinking        (GtkStatusIcon *status_icon);

Returns whether the icon is blinking, see gtk_status_icon_set_blinking().

status_icon : | a GtkStatusIcon
Returns : | TRUE if the icon is blinking

Since 2.10

gtk_status_icon_is_embedded ()

gboolean            gtk_status_icon_is_embedded         (GtkStatusIcon *status_icon);

Returns whether the status icon is embedded in a notification area.

status_icon : | a GtkStatusIcon
Returns : | TRUE if the status icon is embedded in a notification area.

Since 2.10

gtk_status_icon_position_menu ()

void                gtk_status_icon_position_menu       (GtkMenu *menu,
                                                         gint *x,
                                                         gint *y,
                                                         gboolean *push_in,
                                                         gpointer user_data);

Menu positioning function to use with gtk_menu_popup() to position menu aligned to the status icon user_data.

menu : | the GtkMenu
x : | return location for the x position
y : | return location for the y position
push_in : | return location for whether the menu should be pushed in to be completely inside the screen instead of just clamped to the size to the screen.
user_data : | the status icon to position the menu on

Since 2.10

gtk_status_icon_get_geometry ()

gboolean            gtk_status_icon_get_geometry        (GtkStatusIcon *status_icon,
                                                         GdkScreen **screen,
                                                         GdkRectangle *area,
                                                         GtkOrientation *orientation);

Obtains information about the location of the status icon on screen. This information can be used to e.g. position popups like notification bubbles.

See gtk_status_icon_position_menu() for a more convenient alternative for positioning menus.

Note that some platforms do not allow GTK+ to provide this information, and even on platforms that do allow it, the information is not reliable unless the status icon is embedded in a notification area, see gtk_status_icon_is_embedded().

status_icon : | a GtkStatusIcon
screen : | return location for the screen, or NULL if the information is not needed
area : | return location for the area occupied by the status icon, or NULL
orientation : | return location for the orientation of the panel in which the status icon is embedded, or NULL. A panel at the top or bottom of the screen is horizontal, a panel at the left or right is vertical.
Returns : | TRUE if the location information has been filled in

Since 2.10

Property Details

The "blinking" property

  "blinking"                 gboolean              : Read / Write

Whether or not the status icon is blinking.

Default value: FALSE

The "file" property

  "file"                     gchararray            : Write

Filename to load and display.

Default value: NULL

The "icon-name" property

  "icon-name"                gchararray            : Read / Write

The name of the icon from the icon theme.

Default value: NULL

The "pixbuf" property

  "pixbuf"                   GdkPixbuf             : Read / Write

A GdkPixbuf to display.

The "size" property

  "size"                     gint                  : Read

The size of the icon.

Allowed values: >= 0

Default value: 0

The "stock" property

  "stock"                    gchararray            : Read / Write

Stock ID for a stock image to display.

Default value: NULL

The "storage-type" property

  "storage-type"             GtkImageType          : Read

The representation being used for image data.

Default value: GTK_IMAGE_EMPTY

The "visible" property

  "visible"                  gboolean              : Read / Write

Whether or not the status icon is visible.

Default value: TRUE

Signal Details

The "activate" signal

void                user_function                      (GtkStatusIcon *status_icon,
                                                        gpointer       user_data)        : Run First / Action

Gets emitted when the user activates the status icon. If and how status icons can activated is platform-dependent.

status_icon : | the object which received the signal
user_data : | user data set when the signal handler was connected.

Since 2.10

The "popup-menu" signal

void                user_function                      (GtkStatusIcon *status_icon,
                                                        guint          button,
                                                        guint          activate_time,
                                                        gpointer       user_data)          : Run First / Action

Gets emitted when the user brings up the context menu of the status icon. Whether status icons can have context menus and how these are activated is platform-dependent.

The button and activate_timeout parameters should be passed as the last to arguments to gtk_menu_popup().

status_icon : | the object which received the signal
button : | the button that was pressed, or 0 if the signal is not emitted in response to a button press event
activate_time : | the timestamp of the event that triggered the signal emission
user_data : | user data set when the signal handler was connected.

Since 2.10

The "size-changed" signal

gboolean            user_function                      (GtkStatusIcon *status_icon,
                                                        gint           size,
                                                        gpointer       user_data)        : Run Last

Gets emitted when the size available for the image changes, e.g. because the notification area got resized.

status_icon : | the object which received the signal
size : | the new size
user_data : | user data set when the signal handler was connected.
Returns : | TRUE if the icon was updated for the new size. Otherwise, GTK+ will scale the icon as necessary.

Since 2.10


Styles

Styles — Functions for drawing widget parts

Synopsis

#include <gtk/gtk.h>

#define             GTK_STYLE_ATTACHED                  (style)
                    GtkStyle;
GtkStyle*           gtk_style_new                       (void);
GtkStyle*           gtk_style_copy                      (GtkStyle *style);
GtkStyle*           gtk_style_attach                    (GtkStyle *style,
                                                         GdkWindow *window);
void                gtk_style_detach                    (GtkStyle *style);
GtkStyle*           gtk_style_ref                       (GtkStyle *style);
void                gtk_style_unref                     (GtkStyle *style);
void                gtk_style_set_background            (GtkStyle *style,
                                                         GdkWindow *window,
                                                         GtkStateType state_type);
void                gtk_style_apply_default_background  (GtkStyle *style,
                                                         GdkWindow *window,
                                                         gboolean set_bg,
                                                         GtkStateType state_type,
                                                         GdkRectangle *area,
                                                         gint x,
                                                         gint y,
                                                         gint width,
                                                         gint height);
#define             gtk_style_apply_default_pixmap      (s,gw,st,a,x,y,w,h)
gboolean            gtk_style_lookup_color              (GtkStyle *style,
                                                         const gchar *color_name,
                                                         GdkColor *color);
GtkIconSet*         gtk_style_lookup_icon_set           (GtkStyle *style,
                                                         const gchar *stock_id);
GdkPixbuf*          gtk_style_render_icon               (GtkStyle *style,
                                                         const GtkIconSource *source,
                                                         GtkTextDirection direction,
                                                         GtkStateType state,
                                                         GtkIconSize size,
                                                         GtkWidget *widget,
                                                         const gchar *detail);
GdkFont*            gtk_style_get_font                  (GtkStyle *style);
void                gtk_style_set_font                  (GtkStyle *style,
                                                         GdkFont *font);
void                gtk_draw_hline                      (GtkStyle *style,
                                                         GdkWindow *window,
                                                         GtkStateType state_type,
                                                         gint x1,
                                                         gint x2,
                                                         gint y);
void                gtk_draw_vline                      (GtkStyle *style,
                                                         GdkWindow *window,
                                                         GtkStateType state_type,
                                                         gint y1_,
                                                         gint y2_,
                                                         gint x);
void                gtk_draw_shadow                     (GtkStyle *style,
                                                         GdkWindow *window,
                                                         GtkStateType state_type,
                                                         GtkShadowType shadow_type,
                                                         gint x,
                                                         gint y,
                                                         gint width,
                                                         gint height);
void                gtk_draw_polygon                    (GtkStyle *style,
                                                         GdkWindow *window,
                                                         GtkStateType state_type,
                                                         GtkShadowType shadow_type,
                                                         GdkPoint *points,
                                                         gint npoints,
                                                         gboolean fill);
void                gtk_draw_arrow                      (GtkStyle *style,
                                                         GdkWindow *window,
                                                         GtkStateType state_type,
                                                         GtkShadowType shadow_type,
                                                         GtkArrowType arrow_type,
                                                         gboolean fill,
                                                         gint x,
                                                         gint y,
                                                         gint width,
                                                         gint height);
void                gtk_draw_diamond                    (GtkStyle *style,
                                                         GdkWindow *window,
                                                         GtkStateType state_type,
                                                         GtkShadowType shadow_type,
                                                         gint x,
                                                         gint y,
                                                         gint width,
                                                         gint height);
void                gtk_draw_string                     (GtkStyle *style,
                                                         GdkWindow *window,
                                                         GtkStateType state_type,
                                                         gint x,
                                                         gint y,
                                                         const gchar *string);
void                gtk_draw_box                        (GtkStyle *style,
                                                         GdkWindow *window,
                                                         GtkStateType state_type,
                                                         GtkShadowType shadow_type,
                                                         gint x,
                                                         gint y,
                                                         gint width,
                                                         gint height);
void                gtk_draw_box_gap                    (GtkStyle *style,
                                                         GdkWindow *window,
                                                         GtkStateType state_type,
                                                         GtkShadowType shadow_type,
                                                         gint x,
                                                         gint y,
                                                         gint width,
                                                         gint height,
                                                         GtkPositionType gap_side,
                                                         gint gap_x,
                                                         gint gap_width);
void                gtk_draw_check                      (GtkStyle *style,
                                                         GdkWindow *window,
                                                         GtkStateType state_type,
                                                         GtkShadowType shadow_type,
                                                         gint x,
                                                         gint y,
                                                         gint width,
                                                         gint height);
void                gtk_draw_extension                  (GtkStyle *style,
                                                         GdkWindow *window,
                                                         GtkStateType state_type,
                                                         GtkShadowType shadow_type,
                                                         gint x,
                                                         gint y,
                                                         gint width,
                                                         gint height,
                                                         GtkPositionType gap_side);
void                gtk_draw_flat_box                   (GtkStyle *style,
                                                         GdkWindow *window,
                                                         GtkStateType state_type,
                                                         GtkShadowType shadow_type,
                                                         gint x,
                                                         gint y,
                                                         gint width,
                                                         gint height);
void                gtk_draw_focus                      (GtkStyle *style,
                                                         GdkWindow *window,
                                                         gint x,
                                                         gint y,
                                                         gint width,
                                                         gint height);
void                gtk_draw_handle                     (GtkStyle *style,
                                                         GdkWindow *window,
                                                         GtkStateType state_type,
                                                         GtkShadowType shadow_type,
                                                         gint x,
                                                         gint y,
                                                         gint width,
                                                         gint height,
                                                         GtkOrientation orientation);
void                gtk_draw_option                     (GtkStyle *style,
                                                         GdkWindow *window,
                                                         GtkStateType state_type,
                                                         GtkShadowType shadow_type,
                                                         gint x,
                                                         gint y,
                                                         gint width,
                                                         gint height);
void                gtk_draw_shadow_gap                 (GtkStyle *style,
                                                         GdkWindow *window,
                                                         GtkStateType state_type,
                                                         GtkShadowType shadow_type,
                                                         gint x,
                                                         gint y,
                                                         gint width,
                                                         gint height,
                                                         GtkPositionType gap_side,
                                                         gint gap_x,
                                                         gint gap_width);
void                gtk_draw_slider                     (GtkStyle *style,
                                                         GdkWindow *window,
                                                         GtkStateType state_type,
                                                         GtkShadowType shadow_type,
                                                         gint x,
                                                         gint y,
                                                         gint width,
                                                         gint height,
                                                         GtkOrientation orientation);
void                gtk_draw_tab                        (GtkStyle *style,
                                                         GdkWindow *window,
                                                         GtkStateType state_type,
                                                         GtkShadowType shadow_type,
                                                         gint x,
                                                         gint y,
                                                         gint width,
                                                         gint height);
void                gtk_draw_expander                   (GtkStyle *style,
                                                         GdkWindow *window,
                                                         GtkStateType state_type,
                                                         gint x,
                                                         gint y,
                                                         GtkExpanderStyle expander_style);
void                gtk_draw_layout                     (GtkStyle *style,
                                                         GdkWindow *window,
                                                         GtkStateType state_type,
                                                         gboolean use_text,
                                                         gint x,
                                                         gint y,
                                                         PangoLayout *layout);
void                gtk_draw_resize_grip                (GtkStyle *style,
                                                         GdkWindow *window,
                                                         GtkStateType state_type,
                                                         GdkWindowEdge edge,
                                                         gint x,
                                                         gint y,
                                                         gint width,
                                                         gint height);
void                gtk_paint_arrow                     (GtkStyle *style,
                                                         GdkWindow *window,
                                                         GtkStateType state_type,
                                                         GtkShadowType shadow_type,
                                                         GdkRectangle *area,
                                                         GtkWidget *widget,
                                                         const gchar *detail,
                                                         GtkArrowType arrow_type,
                                                         gboolean fill,
                                                         gint x,
                                                         gint y,
                                                         gint width,
                                                         gint height);
void                gtk_paint_box                       (GtkStyle *style,
                                                         GdkWindow *window,
                                                         GtkStateType state_type,
                                                         GtkShadowType shadow_type,
                                                         GdkRectangle *area,
                                                         GtkWidget *widget,
                                                         const gchar *detail,
                                                         gint x,
                                                         gint y,
                                                         gint width,
                                                         gint height);
void                gtk_paint_box_gap                   (GtkStyle *style,
                                                         GdkWindow *window,
                                                         GtkStateType state_type,
                                                         GtkShadowType shadow_type,
                                                         GdkRectangle *area,
                                                         GtkWidget *widget,
                                                         gchar *detail,
                                                         gint x,
                                                         gint y,
                                                         gint width,
                                                         gint height,
                                                         GtkPositionType gap_side,
                                                         gint gap_x,
                                                         gint gap_width);
void                gtk_paint_check                     (GtkStyle *style,
                                                         GdkWindow *window,
                                                         GtkStateType state_type,
                                                         GtkShadowType shadow_type,
                                                         GdkRectangle *area,
                                                         GtkWidget *widget,
                                                         const gchar *detail,
                                                         gint x,
                                                         gint y,
                                                         gint width,
                                                         gint height);
void                gtk_paint_diamond                   (GtkStyle *style,
                                                         GdkWindow *window,
                                                         GtkStateType state_type,
                                                         GtkShadowType shadow_type,
                                                         GdkRectangle *area,
                                                         GtkWidget *widget,
                                                         const gchar *detail,
                                                         gint x,
                                                         gint y,
                                                         gint width,
                                                         gint height);
void                gtk_paint_extension                 (GtkStyle *style,
                                                         GdkWindow *window,
                                                         GtkStateType state_type,
                                                         GtkShadowType shadow_type,
                                                         GdkRectangle *area,
                                                         GtkWidget *widget,
                                                         gchar *detail,
                                                         gint x,
                                                         gint y,
                                                         gint width,
                                                         gint height,
                                                         GtkPositionType gap_side);
void                gtk_paint_flat_box                  (GtkStyle *style,
                                                         GdkWindow *window,
                                                         GtkStateType state_type,
                                                         GtkShadowType shadow_type,
                                                         GdkRectangle *area,
                                                         GtkWidget *widget,
                                                         const gchar *detail,
                                                         gint x,
                                                         gint y,
                                                         gint width,
                                                         gint height);
void                gtk_paint_focus                     (GtkStyle *style,
                                                         GdkWindow *window,
                                                         GtkStateType state_type,
                                                         GdkRectangle *area,
                                                         GtkWidget *widget,
                                                         const gchar *detail,
                                                         gint x,
                                                         gint y,
                                                         gint width,
                                                         gint height);
void                gtk_paint_handle                    (GtkStyle *style,
                                                         GdkWindow *window,
                                                         GtkStateType state_type,
                                                         GtkShadowType shadow_type,
                                                         GdkRectangle *area,
                                                         GtkWidget *widget,
                                                         const gchar *detail,
                                                         gint x,
                                                         gint y,
                                                         gint width,
                                                         gint height,
                                                         GtkOrientation orientation);
void                gtk_paint_hline                     (GtkStyle *style,
                                                         GdkWindow *window,
                                                         GtkStateType state_type,
                                                         GdkRectangle *area,
                                                         GtkWidget *widget,
                                                         const gchar *detail,
                                                         gint x1,
                                                         gint x2,
                                                         gint y);
void                gtk_paint_option                    (GtkStyle *style,
                                                         GdkWindow *window,
                                                         GtkStateType state_type,
                                                         GtkShadowType shadow_type,
                                                         GdkRectangle *area,
                                                         GtkWidget *widget,
                                                         const gchar *detail,
                                                         gint x,
                                                         gint y,
                                                         gint width,
                                                         gint height);
void                gtk_paint_polygon                   (GtkStyle *style,
                                                         GdkWindow *window,
                                                         GtkStateType state_type,
                                                         GtkShadowType shadow_type,
                                                         GdkRectangle *area,
                                                         GtkWidget *widget,
                                                         const gchar *detail,
                                                         GdkPoint *points,
                                                         gint npoints,
                                                         gboolean fill);
void                gtk_paint_shadow                    (GtkStyle *style,
                                                         GdkWindow *window,
                                                         GtkStateType state_type,
                                                         GtkShadowType shadow_type,
                                                         GdkRectangle *area,
                                                         GtkWidget *widget,
                                                         const gchar *detail,
                                                         gint x,
                                                         gint y,
                                                         gint width,
                                                         gint height);
void                gtk_paint_shadow_gap                (GtkStyle *style,
                                                         GdkWindow *window,
                                                         GtkStateType state_type,
                                                         GtkShadowType shadow_type,
                                                         GdkRectangle *area,
                                                         GtkWidget *widget,
                                                         gchar *detail,
                                                         gint x,
                                                         gint y,
                                                         gint width,
                                                         gint height,
                                                         GtkPositionType gap_side,
                                                         gint gap_x,
                                                         gint gap_width);
void                gtk_paint_slider                    (GtkStyle *style,
                                                         GdkWindow *window,
                                                         GtkStateType state_type,
                                                         GtkShadowType shadow_type,
                                                         GdkRectangle *area,
                                                         GtkWidget *widget,
                                                         const gchar *detail,
                                                         gint x,
                                                         gint y,
                                                         gint width,
                                                         gint height,
                                                         GtkOrientation orientation);
void                gtk_paint_string                    (GtkStyle *style,
                                                         GdkWindow *window,
                                                         GtkStateType state_type,
                                                         GdkRectangle *area,
                                                         GtkWidget *widget,
                                                         const gchar *detail,
                                                         gint x,
                                                         gint y,
                                                         const gchar *string);
void                gtk_paint_tab                       (GtkStyle *style,
                                                         GdkWindow *window,
                                                         GtkStateType state_type,
                                                         GtkShadowType shadow_type,
                                                         GdkRectangle *area,
                                                         GtkWidget *widget,
                                                         const gchar *detail,
                                                         gint x,
                                                         gint y,
                                                         gint width,
                                                         gint height);
void                gtk_paint_vline                     (GtkStyle *style,
                                                         GdkWindow *window,
                                                         GtkStateType state_type,
                                                         GdkRectangle *area,
                                                         GtkWidget *widget,
                                                         const gchar *detail,
                                                         gint y1_,
                                                         gint y2_,
                                                         gint x);
void                gtk_paint_expander                  (GtkStyle *style,
                                                         GdkWindow *window,
                                                         GtkStateType state_type,
                                                         GdkRectangle *area,
                                                         GtkWidget *widget,
                                                         const gchar *detail,
                                                         gint x,
                                                         gint y,
                                                         GtkExpanderStyle expander_style);
void                gtk_paint_layout                    (GtkStyle *style,
                                                         GdkWindow *window,
                                                         GtkStateType state_type,
                                                         gboolean use_text,
                                                         GdkRectangle *area,
                                                         GtkWidget *widget,
                                                         const gchar *detail,
                                                         gint x,
                                                         gint y,
                                                         PangoLayout *layout);
void                gtk_paint_resize_grip               (GtkStyle *style,
                                                         GdkWindow *window,
                                                         GtkStateType state_type,
                                                         GdkRectangle *area,
                                                         GtkWidget *widget,
                                                         const gchar *detail,
                                                         GdkWindowEdge edge,
                                                         gint x,
                                                         gint y,
                                                         gint width,
                                                         gint height);
void                gtk_draw_insertion_cursor           (GtkWidget *widget,
                                                         GdkDrawable *drawable,
                                                         GdkRectangle *area,
                                                         GdkRectangle *location,
                                                         gboolean is_primary,
                                                         GtkTextDirection direction,
                                                         gboolean draw_arrow);

                    GtkBorder;
GtkBorder*          gtk_border_copy                     (const GtkBorder *border_);
void                gtk_border_free                     (GtkBorder *border_);

                    GtkRcProperty;
gboolean            (*GtkRcPropertyParser)              (const GParamSpec *pspec,
                                                         const GString *rc_string,
                                                         GValue *property_value);

Object Hierarchy

  GObject
   +----GtkStyle

Signals

  "realize"                                        : Run First
  "unrealize"                                      : Run First

Description

Details

GTK_STYLE_ATTACHED()

#define GTK_STYLE_ATTACHED(style)	(GTK_STYLE (style)->attach_count > 0)

Returns whether the style is attached to a window.

style : a GtkStyle.

GtkStyle

typedef struct {
  GdkColor fg[5];
  GdkColor bg[5];
  GdkColor light[5];
  GdkColor dark[5];
  GdkColor mid[5];
  GdkColor text[5];
  GdkColor base[5];
  GdkColor text_aa[5];		/* Halfway between text/base */

  GdkColor black;
  GdkColor white;
  PangoFontDescription *font_desc;

  gint xthickness;
  gint ythickness;

  GdkGC *fg_gc[5];
  GdkGC *bg_gc[5];
  GdkGC *light_gc[5];
  GdkGC *dark_gc[5];
  GdkGC *mid_gc[5];
  GdkGC *text_gc[5];
  GdkGC *base_gc[5];
  GdkGC *text_aa_gc[5];
  GdkGC *black_gc;
  GdkGC *white_gc;

  GdkPixmap *bg_pixmap[5];
} GtkStyle;

gtk_style_new ()

GtkStyle*           gtk_style_new                       (void);

Creates a new GtkStyle.

Returns : a new GtkStyle.

gtk_style_copy ()

GtkStyle*           gtk_style_copy                      (GtkStyle *style);

style :
Returns :

gtk_style_attach ()

GtkStyle*           gtk_style_attach                    (GtkStyle *style,
                                                         GdkWindow *window);

Attaches a style to a window; this process allocates the colors and creates the GC's for the style - it specializes it to a particular visual and colormap. The process may involve the creation of a new style if the style has already been attached to a window with a different style and colormap.

Since this function may return a new object, you have to use it in the following way: style = gtk_style_attach (style, window)

style : | a GtkStyle.
window : | a GdkWindow.
Returns : | Either style, or a newly-created GtkStyle. If the style is newly created, the style parameter will be dereferenced, and the new style will have a reference count belonging to the caller.

gtk_style_detach ()

void                gtk_style_detach                    (GtkStyle *style);

Detaches a style from a window. If the style is not attached to any windows anymore, it is unrealized. See gtk_style_attach().

style : a GtkStyle

gtk_style_ref ()

GtkStyle*           gtk_style_ref                       (GtkStyle *style);

Warning

gtk_style_ref is deprecated and should not be used in newly-written code.

Deprecated equivalent of g_object_ref().

style : | a GtkStyle.
Returns : | style.

gtk_style_unref ()

void                gtk_style_unref                     (GtkStyle *style);

Warning

gtk_style_unref is deprecated and should not be used in newly-written code.

Deprecated equivalent of g_object_unref().

style : a GtkStyle.

gtk_style_set_background ()

void                gtk_style_set_background            (GtkStyle *style,
                                                         GdkWindow *window,
                                                         GtkStateType state_type);

Sets the background of window to the background color or pixmap specified by style for the given state.

style : | a GtkStyle
window : | a GdkWindow
state_type : | a state

gtk_style_apply_default_background ()

void                gtk_style_apply_default_background  (GtkStyle *style,
                                                         GdkWindow *window,
                                                         gboolean set_bg,
                                                         GtkStateType state_type,
                                                         GdkRectangle *area,
                                                         gint x,
                                                         gint y,
                                                         gint width,
                                                         gint height);

style :
window :
set_bg :
state_type :
area :
x :
y :
width :
height :

gtk_style_apply_default_pixmap()

#define gtk_style_apply_default_pixmap(s,gw,st,a,x,y,w,h) gtk_style_apply_default_background (s,gw,1,st,a,x,y,w,h)

Warning

gtk_style_apply_default_pixmap is deprecated and should not be used in newly-written code.

Deprecated alias for gtk_style_apply_default_background().

s :
gw :
st :
a :
x :
y :
w :
h :

gtk_style_lookup_color ()

gboolean            gtk_style_lookup_color              (GtkStyle *style,
                                                         const gchar *color_name,
                                                         GdkColor *color);

Looks up color_name in the style's logical color mappings, filling in color and returning TRUE if found, otherwise returning FALSE. Do not cache the found mapping, because it depends on the GtkStyle and might change when a theme switch occurs.

style : | a GtkStyle
color_name : | the name of the logical color to look up
color : | the GdkColor to fill in
Returns : | TRUE if the mapping was found.

Since 2.10

gtk_style_lookup_icon_set ()

GtkIconSet*         gtk_style_lookup_icon_set           (GtkStyle *style,
                                                         const gchar *stock_id);

style :
stock_id :
Returns :

gtk_style_render_icon ()

GdkPixbuf*          gtk_style_render_icon               (GtkStyle *style,
                                                         const GtkIconSource *source,
                                                         GtkTextDirection direction,
                                                         GtkStateType state,
                                                         GtkIconSize size,
                                                         GtkWidget *widget,
                                                         const gchar *detail);

Renders the icon specified by source at the given size according to the given parameters and returns the result in a pixbuf.

style : | a GtkStyle
source : | the GtkIconSource specifying the icon to render
direction : | a text direction
state : | a state
size : | the size to render the icon at. A size of (GtkIconSize)-1 means render at the size of the source and don't scale.
widget : | the widget
detail : | a style detail
Returns : | a newly-created GdkPixbuf containing the rendered icon

gtk_style_get_font ()

GdkFont*            gtk_style_get_font                  (GtkStyle *style);

Warning

gtk_style_get_font is deprecated and should not be used in newly-written code.

Gets the GdkFont to use for the given style. This is meant only as a replacement for direct access to style->font and should not be used in new code. New code should use style->font_desc instead.

style : | a GtkStyle
Returns : | the GdkFont for the style. This font is owned by the style; if you want to keep around a copy, you must call gdk_font_ref().

gtk_style_set_font ()

void                gtk_style_set_font                  (GtkStyle *style,
                                                         GdkFont *font);

Warning

gtk_style_set_font is deprecated and should not be used in newly-written code.

Sets the GdkFont to use for a given style. This is meant only as a replacement for direct access to style->font and should not be used in new code. New code should use style->font_desc instead.

style : | a GtkStyle.
font : | a GdkFont, or NULL to use the GdkFont corresponding to style->font_desc.

gtk_draw_hline ()

void                gtk_draw_hline                      (GtkStyle *style,
                                                         GdkWindow *window,
                                                         GtkStateType state_type,
                                                         gint x1,
                                                         gint x2,
                                                         gint y);

Warning

gtk_draw_hline is deprecated and should not be used in newly-written code. Use gtk_paint_hline() instead.

Draws a horizontal line from (x1, y) to (x2, y) in window using the given style and state.

style : | a GtkStyle
window : | a GdkWindow
state_type : | a state
x1 : | the starting x coordinate
x2 : | the ending x coordinate
y : | the y coordinate

gtk_draw_vline ()

void                gtk_draw_vline                      (GtkStyle *style,
                                                         GdkWindow *window,
                                                         GtkStateType state_type,
                                                         gint y1_,
                                                         gint y2_,
                                                         gint x);

Warning

gtk_draw_vline is deprecated and should not be used in newly-written code. Use gtk_paint_vline() instead.

Draws a vertical line from (x, y1_) to (x, y2_) in window using the given style and state.

style : | a GtkStyle
window : | a GdkWindow
state_type : | a state
y1_ : | the starting y coordinate
y2_ : | the ending y coordinate
x : | the x coordinate

gtk_draw_shadow ()

void                gtk_draw_shadow                     (GtkStyle *style,
                                                         GdkWindow *window,
                                                         GtkStateType state_type,
                                                         GtkShadowType shadow_type,
                                                         gint x,
                                                         gint y,
                                                         gint width,
                                                         gint height);

Warning

gtk_draw_shadow is deprecated and should not be used in newly-written code. Use gtk_paint_shadow() instead.

Draws a shadow around the given rectangle in window using the given style and state and shadow type.

style : | a GtkStyle
window : | a GdkWindow
state_type : | a state
shadow_type : | type of shadow to draw
x : | x origin of the rectangle
y : | y origin of the rectangle
width : | width of the rectangle
height : | width of the rectangle

gtk_draw_polygon ()

void                gtk_draw_polygon                    (GtkStyle *style,
                                                         GdkWindow *window,
                                                         GtkStateType state_type,
                                                         GtkShadowType shadow_type,
                                                         GdkPoint *points,
                                                         gint npoints,
                                                         gboolean fill);

Warning

gtk_draw_polygon is deprecated and should not be used in newly-written code. Use gtk_paint_polygon() instead.

Draws a polygon on window with the given parameters.

style : | a GtkStyle
window : | a GdkWindow
state_type : | a state
shadow_type : | type of shadow to draw
points : | an array of GdkPoints
npoints : | length of points
fill : | TRUE if the polygon should be filled

gtk_draw_arrow ()

void                gtk_draw_arrow                      (GtkStyle *style,
                                                         GdkWindow *window,
                                                         GtkStateType state_type,
                                                         GtkShadowType shadow_type,
                                                         GtkArrowType arrow_type,
                                                         gboolean fill,
                                                         gint x,
                                                         gint y,
                                                         gint width,
                                                         gint height);

Warning

gtk_draw_arrow is deprecated and should not be used in newly-written code. Use gtk_paint_arrow() instead.

Draws an arrow in the given rectangle on window using the given parameters. arrow_type determines the direction of the arrow.

style : | a GtkStyle
window : | a GdkWindow
state_type : | a state
shadow_type : | the type of shadow to draw
arrow_type : | the type of arrow to draw
fill : | TRUE if the arrow tip should be filled
x : | x origin of the rectangle to draw the arrow in
y : | y origin of the rectangle to draw the arrow in
width : | width of the rectangle to draw the arrow in
height : | height of the rectangle to draw the arrow in

gtk_draw_diamond ()

void                gtk_draw_diamond                    (GtkStyle *style,
                                                         GdkWindow *window,
                                                         GtkStateType state_type,
                                                         GtkShadowType shadow_type,
                                                         gint x,
                                                         gint y,
                                                         gint width,
                                                         gint height);

Warning

gtk_draw_diamond is deprecated and should not be used in newly-written code. Use gtk_paint_diamond() instead.

Draws a diamond in the given rectangle on window using the given parameters.

style : | a GtkStyle
window : | a GdkWindow
state_type : | a state
shadow_type : | the type of shadow to draw
x : | x origin of the rectangle to draw the diamond in
y : | y origin of the rectangle to draw the diamond in
width : | width of the rectangle to draw the diamond in
height : | height of the rectangle to draw the diamond in

gtk_draw_string ()

void                gtk_draw_string                     (GtkStyle *style,
                                                         GdkWindow *window,
                                                         GtkStateType state_type,
                                                         gint x,
                                                         gint y,
                                                         const gchar *string);

Warning

gtk_draw_string is deprecated and should not be used in newly-written code. Use gtk_paint_layout() instead.

Draws a text string on window with the given parameters.

style : | a GtkStyle
window : | a GdkWindow
state_type : | a state
x : | x origin
y : | y origin
string : | the string to draw

gtk_draw_box ()

void                gtk_draw_box                        (GtkStyle *style,
                                                         GdkWindow *window,
                                                         GtkStateType state_type,
                                                         GtkShadowType shadow_type,
                                                         gint x,
                                                         gint y,
                                                         gint width,
                                                         gint height);

Warning

gtk_draw_box is deprecated and should not be used in newly-written code. Use gtk_paint_box() instead.

Draws a box on window with the given parameters.

style : | a GtkStyle
window : | a GdkWindow
state_type : | a state
shadow_type : | the type of shadow to draw
x : | x origin of the box
y : | y origin of the box
width : | the width of the box
height : | the height of the box

gtk_draw_box_gap ()

void                gtk_draw_box_gap                    (GtkStyle *style,
                                                         GdkWindow *window,
                                                         GtkStateType state_type,
                                                         GtkShadowType shadow_type,
                                                         gint x,
                                                         gint y,
                                                         gint width,
                                                         gint height,
                                                         GtkPositionType gap_side,
                                                         gint gap_x,
                                                         gint gap_width);

Warning

gtk_draw_box_gap is deprecated and should not be used in newly-written code. Use gtk_paint_box_gap() instead.

Draws a box in window using the given style and state and shadow type, leaving a gap in one side.

style : | a GtkStyle
window : | a GdkWindow
state_type : | a state
shadow_type : | type of shadow to draw
x : | x origin of the rectangle
y : | y origin of the rectangle
width : | width of the rectangle
height : | width of the rectangle
gap_side : | side in which to leave the gap
gap_x : | starting position of the gap
gap_width : | width of the gap

gtk_draw_check ()

void                gtk_draw_check                      (GtkStyle *style,
                                                         GdkWindow *window,
                                                         GtkStateType state_type,
                                                         GtkShadowType shadow_type,
                                                         gint x,
                                                         gint y,
                                                         gint width,
                                                         gint height);

Warning

gtk_draw_check is deprecated and should not be used in newly-written code. Use gtk_paint_check() instead.

Draws a check button indicator in the given rectangle on window with the given parameters.

style : | a GtkStyle
window : | a GdkWindow
state_type : | a state
shadow_type : | the type of shadow to draw
x : | x origin of the rectangle to draw the check in
y : | y origin of the rectangle to draw the check in
width : | the width of the rectangle to draw the check in
height : | the height of the rectangle to draw the check in

gtk_draw_extension ()

void                gtk_draw_extension                  (GtkStyle *style,
                                                         GdkWindow *window,
                                                         GtkStateType state_type,
                                                         GtkShadowType shadow_type,
                                                         gint x,
                                                         gint y,
                                                         gint width,
                                                         gint height,
                                                         GtkPositionType gap_side);

Warning

gtk_draw_extension is deprecated and should not be used in newly-written code. Use gtk_paint_extension() instead.

Draws an extension, i.e. a notebook tab.

style : | a GtkStyle
window : | a GdkWindow
state_type : | a state
shadow_type : | type of shadow to draw
x : | x origin of the extension
y : | y origin of the extension
width : | width of the extension
height : | width of the extension
gap_side : | the side on to which the extension is attached

gtk_draw_flat_box ()

void                gtk_draw_flat_box                   (GtkStyle *style,
                                                         GdkWindow *window,
                                                         GtkStateType state_type,
                                                         GtkShadowType shadow_type,
                                                         gint x,
                                                         gint y,
                                                         gint width,
                                                         gint height);

Warning

gtk_draw_flat_box is deprecated and should not be used in newly-written code. Use gtk_paint_flat_box() instead.

Draws a flat box on window with the given parameters.

style : | a GtkStyle
window : | a GdkWindow
state_type : | a state
shadow_type : | the type of shadow to draw
x : | x origin of the box
y : | y origin of the box
width : | the width of the box
height : | the height of the box

gtk_draw_focus ()

void                gtk_draw_focus                      (GtkStyle *style,
                                                         GdkWindow *window,
                                                         gint x,
                                                         gint y,
                                                         gint width,
                                                         gint height);

Warning

gtk_draw_focus is deprecated and should not be used in newly-written code. Use gtk_paint_focus() instead.

Draws a focus indicator around the given rectangle on window using the given style.

style : | a GtkStyle
window : | a GdkWindow
x : | the x origin of the rectangle around which to draw a focus indicator
y : | the y origin of the rectangle around which to draw a focus indicator
width : | the width of the rectangle around which to draw a focus indicator
height : | the height of the rectangle around which to draw a focus indicator

gtk_draw_handle ()

void                gtk_draw_handle                     (GtkStyle *style,
                                                         GdkWindow *window,
                                                         GtkStateType state_type,
                                                         GtkShadowType shadow_type,
                                                         gint x,
                                                         gint y,
                                                         gint width,
                                                         gint height,
                                                         GtkOrientation orientation);

Warning

gtk_draw_handle is deprecated and should not be used in newly-written code. Use gtk_paint_handle() instead.

Draws a handle as used in GtkHandleBox and GtkPaned.

style : | a GtkStyle
window : | a GdkWindow
state_type : | a state
shadow_type : | type of shadow to draw
x : | x origin of the handle
y : | y origin of the handle
width : | with of the handle
height : | height of the handle
orientation : | the orientation of the handle

gtk_draw_option ()

void                gtk_draw_option                     (GtkStyle *style,
                                                         GdkWindow *window,
                                                         GtkStateType state_type,
                                                         GtkShadowType shadow_type,
                                                         gint x,
                                                         gint y,
                                                         gint width,
                                                         gint height);

Warning

gtk_draw_option is deprecated and should not be used in newly-written code. Use gtk_paint_option() instead.

Draws a radio button indicator in the given rectangle on window with the given parameters.

style : | a GtkStyle
window : | a GdkWindow
state_type : | a state
shadow_type : | the type of shadow to draw
x : | x origin of the rectangle to draw the option in
y : | y origin of the rectangle to draw the option in
width : | the width of the rectangle to draw the option in
height : | the height of the rectangle to draw the option in

gtk_draw_shadow_gap ()

void                gtk_draw_shadow_gap                 (GtkStyle *style,
                                                         GdkWindow *window,
                                                         GtkStateType state_type,
                                                         GtkShadowType shadow_type,
                                                         gint x,
                                                         gint y,
                                                         gint width,
                                                         gint height,
                                                         GtkPositionType gap_side,
                                                         gint gap_x,
                                                         gint gap_width);

Warning

gtk_draw_shadow_gap is deprecated and should not be used in newly-written code. Use gtk_paint_shadow_gap() instead.

Draws a shadow around the given rectangle in window using the given style and state and shadow type, leaving a gap in one side.

style : | a GtkStyle
window : | a GdkWindow
state_type : | a state
shadow_type : | type of shadow to draw
x : | x origin of the rectangle
y : | y origin of the rectangle
width : | width of the rectangle
height : | width of the rectangle
gap_side : | side in which to leave the gap
gap_x : | starting position of the gap
gap_width : | width of the gap

gtk_draw_slider ()

void                gtk_draw_slider                     (GtkStyle *style,
                                                         GdkWindow *window,
                                                         GtkStateType state_type,
                                                         GtkShadowType shadow_type,
                                                         gint x,
                                                         gint y,
                                                         gint width,
                                                         gint height,
                                                         GtkOrientation orientation);

Warning

gtk_draw_slider is deprecated and should not be used in newly-written code.

style :
window :
state_type :
shadow_type :
x :
y :
width :
height :
orientation :

gtk_draw_tab ()

void                gtk_draw_tab                        (GtkStyle *style,
                                                         GdkWindow *window,
                                                         GtkStateType state_type,
                                                         GtkShadowType shadow_type,
                                                         gint x,
                                                         gint y,
                                                         gint width,
                                                         gint height);

Warning

gtk_draw_tab is deprecated and should not be used in newly-written code. Use gtk_paint_tab() instead.

Draws an option menu tab (i.e. the up and down pointing arrows) in the given rectangle on window using the given parameters.

style : | a GtkStyle
window : | a GdkWindow
state_type : | a state
shadow_type : | the type of shadow to draw
x : | x origin of the rectangle to draw the tab in
y : | y origin of the rectangle to draw the tab in
width : | the width of the rectangle to draw the tab in
height : | the height of the rectangle to draw the tab in

gtk_draw_expander ()

void                gtk_draw_expander                   (GtkStyle *style,
                                                         GdkWindow *window,
                                                         GtkStateType state_type,
                                                         gint x,
                                                         gint y,
                                                         GtkExpanderStyle expander_style);

Warning

gtk_draw_expander is deprecated and should not be used in newly-written code. Use gtk_paint_expander() instead.

Draws an expander as used in GtkTreeView.

style : | a GtkStyle
window : | a GdkWindow
state_type : | a state
x : | the x position to draw the expander at
y : | the y position to draw the expander at
expander_style : | the style to draw the expander in

gtk_draw_layout ()

void                gtk_draw_layout                     (GtkStyle *style,
                                                         GdkWindow *window,
                                                         GtkStateType state_type,
                                                         gboolean use_text,
                                                         gint x,
                                                         gint y,
                                                         PangoLayout *layout);

Warning

gtk_draw_layout is deprecated and should not be used in newly-written code.

style :
window :
state_type :
use_text :
x :
y :
layout :

gtk_draw_resize_grip ()

void                gtk_draw_resize_grip                (GtkStyle *style,
                                                         GdkWindow *window,
                                                         GtkStateType state_type,
                                                         GdkWindowEdge edge,
                                                         gint x,
                                                         gint y,
                                                         gint width,
                                                         gint height);

Warning

gtk_draw_resize_grip is deprecated and should not be used in newly-written code. Use gtk_paint_resize_grip() instead.

Draws a resize grip in the given rectangle on window using the given parameters.

style : | a GtkStyle
window : | a GdkWindow
state_type : | a state
edge : | the edge in which to draw the resize grip
x : | the x origin of the rectangle in which to draw the resize grip
y : | the y origin of the rectangle in which to draw the resize grip
width : | the width of the rectangle in which to draw the resize grip
height : | the height of the rectangle in which to draw the resize grip

gtk_paint_arrow ()

void                gtk_paint_arrow                     (GtkStyle *style,
                                                         GdkWindow *window,
                                                         GtkStateType state_type,
                                                         GtkShadowType shadow_type,
                                                         GdkRectangle *area,
                                                         GtkWidget *widget,
                                                         const gchar *detail,
                                                         GtkArrowType arrow_type,
                                                         gboolean fill,
                                                         gint x,
                                                         gint y,
                                                         gint width,
                                                         gint height);

Draws an arrow in the given rectangle on window using the given parameters. arrow_type determines the direction of the arrow.

style : | a GtkStyle
window : | a GdkWindow
state_type : | a state
shadow_type : | the type of shadow to draw
area : | clip rectangle, or NULL if the output should not be clipped
widget : | the widget (may be NULL)
detail : | a style detail (may be NULL)
arrow_type : | the type of arrow to draw
fill : | TRUE if the arrow tip should be filled
x : | x origin of the rectangle to draw the arrow in
y : | y origin of the rectangle to draw the arrow in
width : | width of the rectangle to draw the arrow in
height : | height of the rectangle to draw the arrow in

gtk_paint_box ()

void                gtk_paint_box                       (GtkStyle *style,
                                                         GdkWindow *window,
                                                         GtkStateType state_type,
                                                         GtkShadowType shadow_type,
                                                         GdkRectangle *area,
                                                         GtkWidget *widget,
                                                         const gchar *detail,
                                                         gint x,
                                                         gint y,
                                                         gint width,
                                                         gint height);

Draws a box on window with the given parameters.

style : | a GtkStyle
window : | a GdkWindow
state_type : | a state
shadow_type : | the type of shadow to draw
area : | clip rectangle, or NULL if the output should not be clipped
widget : | the widget (may be NULL)
detail : | a style detail (may be NULL)
x : | x origin of the box
y : | y origin of the box
width : | the width of the box
height : | the height of the box

gtk_paint_box_gap ()

void                gtk_paint_box_gap                   (GtkStyle *style,
                                                         GdkWindow *window,
                                                         GtkStateType state_type,
                                                         GtkShadowType shadow_type,
                                                         GdkRectangle *area,
                                                         GtkWidget *widget,
                                                         gchar *detail,
                                                         gint x,
                                                         gint y,
                                                         gint width,
                                                         gint height,
                                                         GtkPositionType gap_side,
                                                         gint gap_x,
                                                         gint gap_width);

Draws a box in window using the given style and state and shadow type, leaving a gap in one side.

style : | a GtkStyle
window : | a GdkWindow
state_type : | a state
shadow_type : | type of shadow to draw
area : | clip rectangle, or NULL if the output should not be clipped
widget : | the widget (may be NULL)
detail : | a style detail (may be NULL)
x : | x origin of the rectangle
y : | y origin of the rectangle
width : | width of the rectangle
height : | width of the rectangle
gap_side : | side in which to leave the gap
gap_x : | starting position of the gap
gap_width : | width of the gap

gtk_paint_check ()

void                gtk_paint_check                     (GtkStyle *style,
                                                         GdkWindow *window,
                                                         GtkStateType state_type,
                                                         GtkShadowType shadow_type,
                                                         GdkRectangle *area,
                                                         GtkWidget *widget,
                                                         const gchar *detail,
                                                         gint x,
                                                         gint y,
                                                         gint width,
                                                         gint height);

Draws a check button indicator in the given rectangle on window with the given parameters.

style : | a GtkStyle
window : | a GdkWindow
state_type : | a state
shadow_type : | the type of shadow to draw
area : | clip rectangle, or NULL if the output should not be clipped
widget : | the widget (may be NULL)
detail : | a style detail (may be NULL)
x : | x origin of the rectangle to draw the check in
y : | y origin of the rectangle to draw the check in
width : | the width of the rectangle to draw the check in
height : | the height of the rectangle to draw the check in

gtk_paint_diamond ()

void                gtk_paint_diamond                   (GtkStyle *style,
                                                         GdkWindow *window,
                                                         GtkStateType state_type,
                                                         GtkShadowType shadow_type,
                                                         GdkRectangle *area,
                                                         GtkWidget *widget,
                                                         const gchar *detail,
                                                         gint x,
                                                         gint y,
                                                         gint width,
                                                         gint height);

Draws a diamond in the given rectangle on window using the given parameters.

style : | a GtkStyle
window : | a GdkWindow
state_type : | a state
shadow_type : | the type of shadow to draw
area : | clip rectangle, or NULL if the output should not be clipped
widget : | the widget (may be NULL)
detail : | a style detail (may be NULL)
x : | x origin of the rectangle to draw the diamond in
y : | y origin of the rectangle to draw the diamond in
width : | width of the rectangle to draw the diamond in
height : | height of the rectangle to draw the diamond in

gtk_paint_extension ()

void                gtk_paint_extension                 (GtkStyle *style,
                                                         GdkWindow *window,
                                                         GtkStateType state_type,
                                                         GtkShadowType shadow_type,
                                                         GdkRectangle *area,
                                                         GtkWidget *widget,
                                                         gchar *detail,
                                                         gint x,
                                                         gint y,
                                                         gint width,
                                                         gint height,
                                                         GtkPositionType gap_side);

Draws an extension, i.e. a notebook tab.

style : | a GtkStyle
window : | a GdkWindow
state_type : | a state
shadow_type : | type of shadow to draw
area : | clip rectangle, or NULL if the output should not be clipped
widget : | the widget (may be NULL)
detail : | a style detail (may be NULL)
x : | x origin of the extension
y : | y origin of the extension
width : | width of the extension
height : | width of the extension
gap_side : | the side on to which the extension is attached

gtk_paint_flat_box ()

void                gtk_paint_flat_box                  (GtkStyle *style,
                                                         GdkWindow *window,
                                                         GtkStateType state_type,
                                                         GtkShadowType shadow_type,
                                                         GdkRectangle *area,
                                                         GtkWidget *widget,
                                                         const gchar *detail,
                                                         gint x,
                                                         gint y,
                                                         gint width,
                                                         gint height);

Draws a flat box on window with the given parameters.

style : | a GtkStyle
window : | a GdkWindow
state_type : | a state
shadow_type : | the type of shadow to draw
area : | clip rectangle, or NULL if the output should not be clipped
widget : | the widget (may be NULL)
detail : | a style detail (may be NULL)
x : | x origin of the box
y : | y origin of the box
width : | the width of the box
height : | the height of the box

gtk_paint_focus ()

void                gtk_paint_focus                     (GtkStyle *style,
                                                         GdkWindow *window,
                                                         GtkStateType state_type,
                                                         GdkRectangle *area,
                                                         GtkWidget *widget,
                                                         const gchar *detail,
                                                         gint x,
                                                         gint y,
                                                         gint width,
                                                         gint height);

Draws a focus indicator around the given rectangle on window using the given style.

style : | a GtkStyle
window : | a GdkWindow
state_type : | a state
area : | clip rectangle, or NULL if the output should not be clipped
widget : | the widget (may be NULL)
detail : | a style detail (may be NULL)
x : | the x origin of the rectangle around which to draw a focus indicator
y : | the y origin of the rectangle around which to draw a focus indicator
width : | the width of the rectangle around which to draw a focus indicator
height : | the height of the rectangle around which to draw a focus indicator

gtk_paint_handle ()

void                gtk_paint_handle                    (GtkStyle *style,
                                                         GdkWindow *window,
                                                         GtkStateType state_type,
                                                         GtkShadowType shadow_type,
                                                         GdkRectangle *area,
                                                         GtkWidget *widget,
                                                         const gchar *detail,
                                                         gint x,
                                                         gint y,
                                                         gint width,
                                                         gint height,
                                                         GtkOrientation orientation);

Draws a handle as used in GtkHandleBox and GtkPaned.

style : | a GtkStyle
window : | a GdkWindow
state_type : | a state
shadow_type : | type of shadow to draw
area : | clip rectangle, or NULL if the output should not be clipped
widget : | the widget (may be NULL)
detail : | a style detail (may be NULL)
x : | x origin of the handle
y : | y origin of the handle
width : | with of the handle
height : | height of the handle
orientation : | the orientation of the handle

gtk_paint_hline ()

void                gtk_paint_hline                     (GtkStyle *style,
                                                         GdkWindow *window,
                                                         GtkStateType state_type,
                                                         GdkRectangle *area,
                                                         GtkWidget *widget,
                                                         const gchar *detail,
                                                         gint x1,
                                                         gint x2,
                                                         gint y);

Draws a horizontal line from (x1, y) to (x2, y) in window using the given style and state.

style : | a GtkStyle
window : | a GdkWindow
state_type : | a state
area : | rectangle to which the output is clipped, or NULL if the output should not be clipped
widget : | the widget (may be NULL)
detail : | a style detail (may be NULL)
x1 : | the starting x coordinate
x2 : | the ending x coordinate
y : | the y coordinate

gtk_paint_option ()

void                gtk_paint_option                    (GtkStyle *style,
                                                         GdkWindow *window,
                                                         GtkStateType state_type,
                                                         GtkShadowType shadow_type,
                                                         GdkRectangle *area,
                                                         GtkWidget *widget,
                                                         const gchar *detail,
                                                         gint x,
                                                         gint y,
                                                         gint width,
                                                         gint height);

Draws a radio button indicator in the given rectangle on window with the given parameters.

style : | a GtkStyle
window : | a GdkWindow
state_type : | a state
shadow_type : | the type of shadow to draw
area : | clip rectangle, or NULL if the output should not be clipped
widget : | the widget (may be NULL)
detail : | a style detail (may be NULL)
x : | x origin of the rectangle to draw the option in
y : | y origin of the rectangle to draw the option in
width : | the width of the rectangle to draw the option in
height : | the height of the rectangle to draw the option in

gtk_paint_polygon ()

void                gtk_paint_polygon                   (GtkStyle *style,
                                                         GdkWindow *window,
                                                         GtkStateType state_type,
                                                         GtkShadowType shadow_type,
                                                         GdkRectangle *area,
                                                         GtkWidget *widget,
                                                         const gchar *detail,
                                                         GdkPoint *points,
                                                         gint npoints,
                                                         gboolean fill);

Draws a polygon on window with the given parameters.

style : | a GtkStyle
window : | a GdkWindow
state_type : | a state
shadow_type : | type of shadow to draw
area : | clip rectangle, or NULL if the output should not be clipped
widget : | the widget (may be NULL)
detail : | a style detail (may be NULL)
points : | an array of GdkPoints
npoints : | length of points
fill : | TRUE if the polygon should be filled

gtk_paint_shadow ()

void                gtk_paint_shadow                    (GtkStyle *style,
                                                         GdkWindow *window,
                                                         GtkStateType state_type,
                                                         GtkShadowType shadow_type,
                                                         GdkRectangle *area,
                                                         GtkWidget *widget,
                                                         const gchar *detail,
                                                         gint x,
                                                         gint y,
                                                         gint width,
                                                         gint height);

Draws a shadow around the given rectangle in window using the given style and state and shadow type.

style : | a GtkStyle
window : | a GdkWindow
state_type : | a state
shadow_type : | type of shadow to draw
area : | clip rectangle or NULL if the output should not be clipped
widget : | the widget (may be NULL)
detail : | a style detail (may be NULL)
x : | x origin of the rectangle
y : | y origin of the rectangle
width : | width of the rectangle
height : | width of the rectangle

gtk_paint_shadow_gap ()

void                gtk_paint_shadow_gap                (GtkStyle *style,
                                                         GdkWindow *window,
                                                         GtkStateType state_type,
                                                         GtkShadowType shadow_type,
                                                         GdkRectangle *area,
                                                         GtkWidget *widget,
                                                         gchar *detail,
                                                         gint x,
                                                         gint y,
                                                         gint width,
                                                         gint height,
                                                         GtkPositionType gap_side,
                                                         gint gap_x,
                                                         gint gap_width);

Draws a shadow around the given rectangle in window using the given style and state and shadow type, leaving a gap in one side.

style : | a GtkStyle
window : | a GdkWindow
state_type : | a state
shadow_type : | type of shadow to draw
area : | clip rectangle, or NULL if the output should not be clipped
widget : | the widget (may be NULL)
detail : | a style detail (may be NULL)
x : | x origin of the rectangle
y : | y origin of the rectangle
width : | width of the rectangle
height : | width of the rectangle
gap_side : | side in which to leave the gap
gap_x : | starting position of the gap
gap_width : | width of the gap

gtk_paint_slider ()

void                gtk_paint_slider                    (GtkStyle *style,
                                                         GdkWindow *window,
                                                         GtkStateType state_type,
                                                         GtkShadowType shadow_type,
                                                         GdkRectangle *area,
                                                         GtkWidget *widget,
                                                         const gchar *detail,
                                                         gint x,
                                                         gint y,
                                                         gint width,
                                                         gint height,
                                                         GtkOrientation orientation);

Draws a slider in the given rectangle on window using the given style and orientation.

style : | a GtkStyle
window : | a GdkWindow
state_type : | a state
shadow_type : | a shadow
area : | clip rectangle, or NULL if the output should not be clipped
widget : | the widget (may be NULL)
detail : | a style detail (may be NULL)
x : | the x origin of the rectangle in which to draw a slider
y : | the y origin of the rectangle in which to draw a slider
width : | the width of the rectangle in which to draw a slider
height : | the height of the rectangle in which to draw a slider
orientation : | the orientation to be used

gtk_paint_string ()

void                gtk_paint_string                    (GtkStyle *style,
                                                         GdkWindow *window,
                                                         GtkStateType state_type,
                                                         GdkRectangle *area,
                                                         GtkWidget *widget,
                                                         const gchar *detail,
                                                         gint x,
                                                         gint y,
                                                         const gchar *string);

Warning

gtk_paint_string is deprecated and should not be used in newly-written code. Use gtk_paint_layout() instead.

Draws a text string on window with the given parameters.

style : | a GtkStyle
window : | a GdkWindow
state_type : | a state
area : | clip rectangle, or NULL if the output should not be clipped
widget : | the widget (may be NULL)
detail : | a style detail (may be NULL)
x : | x origin
y : | y origin
string : | the string to draw

gtk_paint_tab ()

void                gtk_paint_tab                       (GtkStyle *style,
                                                         GdkWindow *window,
                                                         GtkStateType state_type,
                                                         GtkShadowType shadow_type,
                                                         GdkRectangle *area,
                                                         GtkWidget *widget,
                                                         const gchar *detail,
                                                         gint x,
                                                         gint y,
                                                         gint width,
                                                         gint height);

Draws an option menu tab (i.e. the up and down pointing arrows) in the given rectangle on window using the given parameters.

style : | a GtkStyle
window : | a GdkWindow
state_type : | a state
shadow_type : | the type of shadow to draw
area : | clip rectangle, or NULL if the output should not be clipped
widget : | the widget (may be NULL)
detail : | a style detail (may be NULL)
x : | x origin of the rectangle to draw the tab in
y : | y origin of the rectangle to draw the tab in
width : | the width of the rectangle to draw the tab in
height : | the height of the rectangle to draw the tab in

gtk_paint_vline ()

void                gtk_paint_vline                     (GtkStyle *style,
                                                         GdkWindow *window,
                                                         GtkStateType state_type,
                                                         GdkRectangle *area,
                                                         GtkWidget *widget,
                                                         const gchar *detail,
                                                         gint y1_,
                                                         gint y2_,
                                                         gint x);

Draws a vertical line from (x, y1_) to (x, y2_) in window using the given style and state.

style : | a GtkStyle
window : | a GdkWindow
state_type : | a state
area : | rectangle to which the output is clipped, or NULL if the output should not be clipped
widget : | the widget (may be NULL)
detail : | a style detail (may be NULL)
y1_ : | the starting y coordinate
y2_ : | the ending y coordinate
x : | the x coordinate

gtk_paint_expander ()

void                gtk_paint_expander                  (GtkStyle *style,
                                                         GdkWindow *window,
                                                         GtkStateType state_type,
                                                         GdkRectangle *area,
                                                         GtkWidget *widget,
                                                         const gchar *detail,
                                                         gint x,
                                                         gint y,
                                                         GtkExpanderStyle expander_style);

Draws an expander as used in GtkTreeView. x and y specify the center the expander. The size of the expander is determined by the "expander-size" style property of widget. (If widget is not specified or doesn't have an "expander-size" property, an unspecified default size will be used, since the caller doesn't have sufficient information to position the expander, this is likely not useful.) The expander is expander_size pixels tall in the collapsed position and expander_size pixels wide in the expanded position.

style : | a GtkStyle
window : | a GdkWindow
state_type : | a state
area : | clip rectangle, or NULL if the output should not be clipped
widget : | the widget (may be NULL)
detail : | a style detail (may be NULL)
x : | the x position to draw the expander at
y : | the y position to draw the expander at
expander_style : | the style to draw the expander in; determines whether the expander is collapsed, expanded, or in an intermediate state.

gtk_paint_layout ()

void                gtk_paint_layout                    (GtkStyle *style,
                                                         GdkWindow *window,
                                                         GtkStateType state_type,
                                                         gboolean use_text,
                                                         GdkRectangle *area,
                                                         GtkWidget *widget,
                                                         const gchar *detail,
                                                         gint x,
                                                         gint y,
                                                         PangoLayout *layout);

Draws a layout on window using the given parameters.

style : | a GtkStyle
window : | a GdkWindow
state_type : | a state
use_text : | whether to use the text or foreground graphics context of style
area : | clip rectangle, or NULL if the output should not be clipped
widget : | the widget (may be NULL)
detail : | a style detail (may be NULL)
x : | x origin
y : | y origin
layout : | the layout to draw

gtk_paint_resize_grip ()

void                gtk_paint_resize_grip               (GtkStyle *style,
                                                         GdkWindow *window,
                                                         GtkStateType state_type,
                                                         GdkRectangle *area,
                                                         GtkWidget *widget,
                                                         const gchar *detail,
                                                         GdkWindowEdge edge,
                                                         gint x,
                                                         gint y,
                                                         gint width,
                                                         gint height);

Draws a resize grip in the given rectangle on window using the given parameters.

style : | a GtkStyle
window : | a GdkWindow
state_type : | a state
area : | clip rectangle, or NULL if the output should not be clipped
widget : | the widget (may be NULL)
detail : | a style detail (may be NULL)
edge : | the edge in which to draw the resize grip
x : | the x origin of the rectangle in which to draw the resize grip
y : | the y origin of the rectangle in which to draw the resize grip
width : | the width of the rectangle in which to draw the resize grip
height : | the height of the rectangle in which to draw the resize grip

gtk_draw_insertion_cursor ()

void                gtk_draw_insertion_cursor           (GtkWidget *widget,
                                                         GdkDrawable *drawable,
                                                         GdkRectangle *area,
                                                         GdkRectangle *location,
                                                         gboolean is_primary,
                                                         GtkTextDirection direction,
                                                         gboolean draw_arrow);

Draws a text caret on drawable at location. This is not a style function but merely a convenience function for drawing the standard cursor shape.

widget : | a GtkWidget
drawable : | a GdkDrawable
area : | rectangle to which the output is clipped, or NULL if the output should not be clipped
location : | location where to draw the cursor (location->width is ignored)
is_primary : | if the cursor should be the primary cursor color.
direction : | whether the cursor is left-to-right or right-to-left. Should never be GTK_TEXT_DIR_NONE
draw_arrow : | TRUE to draw a directional arrow on the cursor. Should be FALSE unless the cursor is split.

Since 2.4

GtkBorder

typedef struct {
  gint left;
  gint right;
  gint top;
  gint bottom;
} GtkBorder;

gtk_border_copy ()

GtkBorder*          gtk_border_copy                     (const GtkBorder *border_);

Copies a GtkBorder structure.

border_ : | a GtkBorder.
Returns : | a copy of border_.

gtk_border_free ()

void                gtk_border_free                     (GtkBorder *border_);

Frees a GtkBorder structure.

border_ : a GtkBorder.

GtkRcProperty

typedef struct {
  /* quark-ified property identifier like "GtkScrollbar::spacing" */
  GQuark type_name;
  GQuark property_name;

  /* fields similar to GtkSettingsValue */
  gchar *origin;
  GValue value;
} GtkRcProperty;

GtkRcPropertyParser ()

gboolean            (*GtkRcPropertyParser)              (const GParamSpec *pspec,
                                                         const GString *rc_string,
                                                         GValue *property_value);

pspec :
rc_string :
property_value :
Returns :

Signal Details

The "realize" signal

void                user_function                      (GtkStyle *style,
                                                        gpointer  user_data)      : Run First

Emitted when the style has been initialized for a particular colormap and depth. Connecting to this signal is probably seldom useful since most of the time applications and widgets only deal with styles that have been already realized.

style : | the object which received the signal
user_data : | user data set when the signal handler was connected.

Since 2.4

The "unrealize" signal

void                user_function                      (GtkStyle *style,
                                                        gpointer  user_data)      : Run First

Emitted when the aspects of the style specific to a particular colormap and depth are being cleaned up. A connection to this signal can be useful if a widget wants to cache objects like a GdkGC as object data on GtkStyle. This signal provides a convenient place to free such cached objects.

style : | the object which received the signal
user_data : | user data set when the signal handler was connected.

Since 2.4


GtkTable

GtkTable — Pack widgets in regular patterns

Synopsis

#include <gtk/gtk.h>

                    GtkTable;
                    GtkTableChild;
                    GtkTableRowCol;
GtkWidget*          gtk_table_new                       (guint rows,
                                                         guint columns,
                                                         gboolean homogeneous);
void                gtk_table_resize                    (GtkTable *table,
                                                         guint rows,
                                                         guint columns);
void                gtk_table_attach                    (GtkTable *table,
                                                         GtkWidget *child,
                                                         guint left_attach,
                                                         guint right_attach,
                                                         guint top_attach,
                                                         guint bottom_attach,
                                                         GtkAttachOptions xoptions,
                                                         GtkAttachOptions yoptions,
                                                         guint xpadding,
                                                         guint ypadding);
void                gtk_table_attach_defaults           (GtkTable *table,
                                                         GtkWidget *widget,
                                                         guint left_attach,
                                                         guint right_attach,
                                                         guint top_attach,
                                                         guint bottom_attach);
void                gtk_table_set_row_spacing           (GtkTable *table,
                                                         guint row,
                                                         guint spacing);
void                gtk_table_set_col_spacing           (GtkTable *table,
                                                         guint column,
                                                         guint spacing);
void                gtk_table_set_row_spacings          (GtkTable *table,
                                                         guint spacing);
void                gtk_table_set_col_spacings          (GtkTable *table,
                                                         guint spacing);
void                gtk_table_set_homogeneous           (GtkTable *table,
                                                         gboolean homogeneous);
guint               gtk_table_get_default_row_spacing   (GtkTable *table);
gboolean            gtk_table_get_homogeneous           (GtkTable *table);
guint               gtk_table_get_row_spacing           (GtkTable *table,
                                                         guint row);
guint               gtk_table_get_col_spacing           (GtkTable *table,
                                                         guint column);
guint               gtk_table_get_default_col_spacing   (GtkTable *table);

Object Hierarchy

  GObject
   +----GInitiallyUnowned
         +----GtkObject
               +----GtkWidget
                     +----GtkContainer
                           +----GtkTable

Implemented Interfaces

GtkTable implements AtkImplementorIface.

Properties

  "column-spacing"           guint                 : Read / Write
  "homogeneous"              gboolean              : Read / Write
  "n-columns"                guint                 : Read / Write
  "n-rows"                   guint                 : Read / Write
  "row-spacing"              guint                 : Read / Write

Child Properties

  "bottom-attach"            guint                 : Read / Write
  "left-attach"              guint                 : Read / Write
  "right-attach"             guint                 : Read / Write
  "top-attach"               guint                 : Read / Write
  "x-options"                GtkAttachOptions      : Read / Write
  "x-padding"                guint                 : Read / Write
  "y-options"                GtkAttachOptions      : Read / Write
  "y-padding"                guint                 : Read / Write

Description

The GtkTable functions allow the programmer to arrange widgets in rows and columns, making it easy to align many widgets next to each other, horizontally and vertically.

Tables are created with a call to gtk_table_new(), the size of which can later be changed with gtk_table_resize().

Widgets can be added to a table using gtk_table_attach() or the more convenient (but slightly less flexible) gtk_table_attach_defaults().

To alter the space next to a specific row, use gtk_table_set_row_spacing(), and for a column, gtk_table_set_col_spacing().

The gaps between all rows or columns can be changed by calling gtk_table_set_row_spacings() or gtk_table_set_col_spacings() respectively.

gtk_table_set_homogeneous(), can be used to set whether all cells in the table will resize themselves to the size of the largest widget in the table.

Details

GtkTable

typedef struct _GtkTable GtkTable;

The GtkTable structure holds the data for the actual table itself. children is a GList of all the widgets the table contains. rows and columns are pointers to GtkTableRowCol structures, which contain the default spacing and expansion details for the GtkTable's rows and columns, respectively.

nrows and ncols are 16bit integers storing the number of rows and columns the table has.

GtkTableChild

typedef struct {
  GtkWidget *widget;
  guint16 left_attach;
  guint16 right_attach;
  guint16 top_attach;
  guint16 bottom_attach;
  guint16 xpadding;
  guint16 ypadding;
  guint xexpand : 1;
  guint yexpand : 1;
  guint xshrink : 1;
  guint yshrink : 1;
  guint xfill : 1;
  guint yfill : 1;
} GtkTableChild;

The widget field is a pointer to the widget that this GtkTableChild structure is keeping track of. The left_attach, right_attach, top_attach, and bottom_attach fields specify the row and column numbers which make up the invisible rectangle that the child widget is packed into.

xpadding and ypadding specify the space between this widget and the surrounding table cells.

GtkTableRowCol

typedef struct {
  guint16 requisition;
  guint16 allocation;
  guint16 spacing;
  guint need_expand : 1;
  guint need_shrink : 1;
  guint expand : 1;
  guint shrink : 1;
  guint empty : 1;
} GtkTableRowCol;

These fields should be considered read-only and not be modified directly.

gtk_table_new ()

GtkWidget*          gtk_table_new                       (guint rows,
                                                         guint columns,
                                                         gboolean homogeneous);

Used to create a new table widget. An initial size must be given by specifying how many rows and columns the table should have, although this can be changed later with gtk_table_resize(). rows and columns must both be in the range 0 .. 65535.

rows : | The number of rows the new table should have.
columns : | The number of columns the new table should have.
homogeneous : | If set to TRUE, all table cells are resized to the size of the cell containing the largest widget.
Returns : | A pointer to the the newly created table widget.

gtk_table_resize ()

void                gtk_table_resize                    (GtkTable *table,
                                                         guint rows,
                                                         guint columns);

If you need to change a table's size after it has been created, this function allows you to do so.

table : | The GtkTable you wish to change the size of.
rows : | The new number of rows.
columns : | The new number of columns.

gtk_table_attach ()

void                gtk_table_attach                    (GtkTable *table,
                                                         GtkWidget *child,
                                                         guint left_attach,
                                                         guint right_attach,
                                                         guint top_attach,
                                                         guint bottom_attach,
                                                         GtkAttachOptions xoptions,
                                                         GtkAttachOptions yoptions,
                                                         guint xpadding,
                                                         guint ypadding);

Adds a widget to a table. The number of 'cells' that a widget will occupy is specified by left_attach, right_attach, top_attach and bottom_attach. These each represent the leftmost, rightmost, uppermost and lowest column and row numbers of the table. (Columns and rows are indexed from zero).

table : | The GtkTable to add a new widget to.
child : | The widget to add.
left_attach : | the column number to attach the left side of a child widget to.
right_attach : | the column number to attach the right side of a child widget to.
top_attach : | the row number to attach the top of a child widget to.
bottom_attach : | the row number to attach the bottom of a child widget to.
xoptions : | Used to specify the properties of the child widget when the table is resized.
yoptions : | The same as xoptions, except this field determines behaviour of vertical resizing.
xpadding : | An integer value specifying the padding on the left and right of the widget being added to the table.
ypadding : | The amount of padding above and below the child widget.

gtk_table_attach_defaults ()

void                gtk_table_attach_defaults           (GtkTable *table,
                                                         GtkWidget *widget,
                                                         guint left_attach,
                                                         guint right_attach,
                                                         guint top_attach,
                                                         guint bottom_attach);

As there are many options associated with gtk_table_attach(), this convenience function provides the programmer with a means to add children to a table with identical padding and expansion options. The values used for the GtkAttachOptions are GTK_EXPAND | GTK_FILL, and the padding is set to 0.

table : | The table to add a new child widget to.
widget : | The child widget to add.
left_attach : | The column number to attach the left side of the child widget to.
right_attach : | The column number to attach the right side of the child widget to.
top_attach : | The row number to attach the top of the child widget to.
bottom_attach : | The row number to attach the bottom of the child widget to.

gtk_table_set_row_spacing ()

void                gtk_table_set_row_spacing           (GtkTable *table,
                                                         guint row,
                                                         guint spacing);

Changes the space between a given table row and the subsequent row.

table : | a GtkTable containing the row whose properties you wish to change.
row : | row number whose spacing will be changed.
spacing : | number of pixels that the spacing should take up.

gtk_table_set_col_spacing ()

void                gtk_table_set_col_spacing           (GtkTable *table,
                                                         guint column,
                                                         guint spacing);

Alters the amount of space between a given table column and the following column.

table : | a GtkTable.
column : | the column whose spacing should be changed.
spacing : | number of pixels that the spacing should take up.

gtk_table_set_row_spacings ()

void                gtk_table_set_row_spacings          (GtkTable *table,
                                                         guint spacing);

Sets the space between every row in table equal to spacing.

table : | a GtkTable.
spacing : | the number of pixels of space to place between every row in the table.

gtk_table_set_col_spacings ()

void                gtk_table_set_col_spacings          (GtkTable *table,
                                                         guint spacing);

Sets the space between every column in table equal to spacing.

table : | a GtkTable.
spacing : | the number of pixels of space to place between every column in the table.

gtk_table_set_homogeneous ()

void                gtk_table_set_homogeneous           (GtkTable *table,
                                                         gboolean homogeneous);

Changes the homogenous property of table cells, ie. whether all cells are an equal size or not.

table : | The GtkTable you wish to set the homogeneous properties of.
homogeneous : | Set to TRUE to ensure all table cells are the same size. Set to FALSE if this is not your desired behaviour.

gtk_table_get_default_row_spacing ()

guint               gtk_table_get_default_row_spacing   (GtkTable *table);

Gets the default row spacing for the table. This is the spacing that will be used for newly added rows. (See gtk_table_set_row_spacings())

table : | a GtkTable
Returns : | value: the default row spacing

gtk_table_get_homogeneous ()

gboolean            gtk_table_get_homogeneous           (GtkTable *table);

Returns whether the table cells are all constrained to the same width and height. (See gtk_table_set_homogenous())

table : | a GtkTable
Returns : | TRUE if the cells are all constrained to the same size

gtk_table_get_row_spacing ()

guint               gtk_table_get_row_spacing           (GtkTable *table,
                                                         guint row);

Gets the amount of space between row row, and row row + 1. See gtk_table_set_row_spacing().

table : | a GtkTable
row : | a row in the table, 0 indicates the first row
Returns : | the row spacing

gtk_table_get_col_spacing ()

guint               gtk_table_get_col_spacing           (GtkTable *table,
                                                         guint column);

Gets the amount of space between column col, and column col + 1. See gtk_table_set_col_spacing().

table : | a GtkTable
column : | a column in the table, 0 indicates the first column
Returns : | the column spacing

gtk_table_get_default_col_spacing ()

guint               gtk_table_get_default_col_spacing   (GtkTable *table);

Gets the default column spacing for the table. This is the spacing that will be used for newly added columns. (See gtk_table_set_col_spacings())

table : | a GtkTable
Returns : | value: the default column spacing

Property Details

The "column-spacing" property

  "column-spacing"           guint                 : Read / Write

The amount of space between two consecutive columns.

Default value: 0

The "homogeneous" property

  "homogeneous"              gboolean              : Read / Write

If TRUE, the table cells are all the same width/height.

Default value: FALSE

The "n-columns" property

  "n-columns"                guint                 : Read / Write

The number of columns in the table.

Default value: 0

The "n-rows" property

  "n-rows"                   guint                 : Read / Write

The number of rows in the table.

Default value: 0

The "row-spacing" property

  "row-spacing"              guint                 : Read / Write

The amount of space between two consecutive rows.

Default value: 0

Child Property Details

The "bottom-attach" child property

  "bottom-attach"            guint                 : Read / Write

The row number to attach the bottom of the child to.

Allowed values: [1,65535]

Default value: 1

The "left-attach" child property

  "left-attach"              guint                 : Read / Write

The column number to attach the left side of the child to.

Allowed values: <= 65535

Default value: 0

The "right-attach" child property

  "right-attach"             guint                 : Read / Write

The column number to attach the right side of a child widget to.

Allowed values: [1,65535]

Default value: 1

The "top-attach" child property

  "top-attach"               guint                 : Read / Write

The row number to attach the top of a child widget to.

Allowed values: <= 65535

Default value: 0

The "x-options" child property

  "x-options"                GtkAttachOptions      : Read / Write

Options specifying the horizontal behaviour of the child.

Default value: GTK_EXPAND|GTK_FILL

The "x-padding" child property

  "x-padding"                guint                 : Read / Write

Extra space to put between the child and its left and right neighbors, in pixels.

Allowed values: <= 65535

Default value: 0

The "y-options" child property

  "y-options"                GtkAttachOptions      : Read / Write

Options specifying the vertical behaviour of the child.

Default value: GTK_EXPAND|GTK_FILL

The "y-padding" child property

  "y-padding"                guint                 : Read / Write

Extra space to put between the child and its upper and lower neighbors, in pixels.

Allowed values: <= 65535

Default value: 0

See Also

GtkVBox | For packing widgets vertically only.
GtkHBox | For packing widgets horizontally only.


GtkTearoffMenuItem

GtkTearoffMenuItem — A menu item used to tear off and reattach its menu

Synopsis

#include <gtk/gtk.h>

                    GtkTearoffMenuItem;
GtkWidget*          gtk_tearoff_menu_item_new           (void);

Object Hierarchy

  GObject
   +----GInitiallyUnowned
         +----GtkObject
               +----GtkWidget
                     +----GtkContainer
                           +----GtkBin
                                 +----GtkItem
                                       +----GtkMenuItem
                                             +----GtkTearoffMenuItem

Implemented Interfaces

GtkTearoffMenuItem implements AtkImplementorIface.

Description

A GtkTearoffMenuItem is a special GtkMenuItem which is used to tear off and reattach its menu.

When its menu is shown normally, the GtkTearoffMenuItem is drawn as a dotted line indicating that the menu can be torn off. Activating it causes its menu to be torn off and displayed in its own window as a tearoff menu.

When its menu is shown as a tearoff menu, the GtkTearoffMenuItem is drawn as a dotted line which has a left pointing arrow graphic indicating that the tearoff menu can be reattached. Activating it will erase the tearoff menu window.

Details

GtkTearoffMenuItem

typedef struct _GtkTearoffMenuItem GtkTearoffMenuItem;

The GtkTearoffMenuItem struct contains private data only, and should be accessed using the functions below.

gtk_tearoff_menu_item_new ()

GtkWidget*          gtk_tearoff_menu_item_new           (void);

Creates a new GtkTearoffMenuItem.

Returns : a new GtkTearoffMenuItem.

See Also

GtkMenu

for further discussion of menus in GTK.


GtkText

GtkText — A text widget

Synopsis

#include <gtk/gtk.h>

                    GtkText;
                    GtkTextFont;
                    GtkPropertyMark;
GtkWidget*          gtk_text_new                        (GtkAdjustment *hadj,
                                                         GtkAdjustment *vadj);
void                gtk_text_set_editable               (GtkText *text,
                                                         gboolean editable);
void                gtk_text_set_word_wrap              (GtkText *text,
                                                         gboolean word_wrap);
void                gtk_text_set_line_wrap              (GtkText *text,
                                                         gboolean line_wrap);
void                gtk_text_set_adjustments            (GtkText *text,
                                                         GtkAdjustment *hadj,
                                                         GtkAdjustment *vadj);
void                gtk_text_set_point                  (GtkText *text,
                                                         guint index);
guint               gtk_text_get_point                  (GtkText *text);
guint               gtk_text_get_length                 (GtkText *text);
void                gtk_text_freeze                     (GtkText *text);
void                gtk_text_thaw                       (GtkText *text);
void                gtk_text_insert                     (GtkText *text,
                                                         GdkFont *font,
                                                         const GdkColor *fore,
                                                         const GdkColor *back,
                                                         const char *chars,
                                                         gint length);
gboolean            gtk_text_backward_delete            (GtkText *text,
                                                         guint nchars);
gboolean            gtk_text_forward_delete             (GtkText *text,
                                                         guint nchars);
#define             GTK_TEXT_INDEX                      (t, index)

Object Hierarchy

  GObject
   +----GInitiallyUnowned
         +----GtkObject
               +----GtkWidget
                     +----GtkOldEditable
                           +----GtkText

Implemented Interfaces

GtkText implements AtkImplementorIface and GtkEditable.

Properties

  "hadjustment"              GtkAdjustment         : Read / Write
  "line-wrap"                gboolean              : Read / Write
  "vadjustment"              GtkAdjustment         : Read / Write
  "word-wrap"                gboolean              : Read / Write

Signals

  "set-scroll-adjustments"                         : Run Last

Description

Warning

GtkText is deprecated and unsupported. It is known to be buggy. To use it, you must define the symbol GTK_ENABLE_BROKEN prior to including the GTK+ header files. Use GtkTextView instead.

A GtkText widget allows one to display any given text and manipulate it by deleting from one point to another, selecting a region, and various other functions as outlined below. It is inherited from GtkEditable.

Details

GtkText

typedef struct _GtkText GtkText;

Warning

GtkText is deprecated and should not be used in newly-written code.

Most of the GtkText struct members should not be accessed directly. Listed below are a few exceptions and how to use them.

GtkTextFont

typedef struct _GtkTextFont GtkTextFont;

Warning

GtkTextFont is deprecated and should not be used in newly-written code.

Internal GtkText data type.

GtkPropertyMark

typedef struct {
  /* Position in list. */
  GList* property;

  /* Offset into that property. */
  guint offset;

  /* Current index. */
  guint index;
} GtkPropertyMark;

Warning

GtkPropertyMark is deprecated and should not be used in newly-written code.

Internal GtkText data type. Should not be accessed directly.

gtk_text_new ()

GtkWidget*          gtk_text_new                        (GtkAdjustment *hadj,
                                                         GtkAdjustment *vadj);

Warning

gtk_text_new is deprecated and should not be used in newly-written code.

Creates a new GtkText widget, initialized with the given pointers to GtkAdjustments. These pointers can be used to track the viewing position of the GtkText widget. Passing NULL to either or both of them will make the GtkText create its own. You can set these later with the function gtk_text_set_adjustment().

hadj : | horizontal adjustment.
vadj : | vertical adjustment.
Returns : | the new GtkText widget.

gtk_text_set_editable ()

void                gtk_text_set_editable               (GtkText *text,
                                                         gboolean editable);

Warning

gtk_text_set_editable is deprecated and should not be used in newly-written code.

Sets whether the GtkText widget can be edited by the user or not. This still allows you the programmer to make changes with the various GtkText functions.

text : | the GtkText widget
editable : | TRUE makes it editable, FALSE makes it immutable by the user

gtk_text_set_word_wrap ()

void                gtk_text_set_word_wrap              (GtkText *text,
                                                         gboolean word_wrap);

Warning

gtk_text_set_word_wrap is deprecated and should not be used in newly-written code.

Sets whether the GtkText widget wraps words down to the next line if it can't be completed on the current line.

text : | the GtkText widget
word_wrap : | TRUE makes it word wrap, FALSE disables word wrapping

gtk_text_set_line_wrap ()

void                gtk_text_set_line_wrap              (GtkText *text,
                                                         gboolean line_wrap);

Warning

gtk_text_set_line_wrap is deprecated and should not be used in newly-written code.

Controls how GtkText handles long lines of continuous text. If line wrap is on, the line is broken when it reaches the extent of the GtkText widget viewing area and the rest is displayed on the next line. If it is not set, the line continues regardless size of current viewing area. Similar to word wrap but it disregards word boundaries.

text : | the GtkText widget
line_wrap : | TRUE turns line wrap on, FALSE turns it off

gtk_text_set_adjustments ()

void                gtk_text_set_adjustments            (GtkText *text,
                                                         GtkAdjustment *hadj,
                                                         GtkAdjustment *vadj);

Warning

gtk_text_set_adjustments is deprecated and should not be used in newly-written code.

Allows you to set GtkAdjustment pointers which in turn allows you to keep track of the viewing position of the GtkText widget.

text : | the GtkText widget
hadj : | the horizontal adjustment
vadj : | the vertical adjustment

gtk_text_set_point ()

void                gtk_text_set_point                  (GtkText *text,
                                                         guint index);

Warning

gtk_text_set_point is deprecated and should not be used in newly-written code.

Sets the cursor at the given point. In this case a point constitutes the number of characters from the extreme upper left corner of the GtkText widget.

text : | the GtkText widget
index : | the number of characters from the upper left corner

gtk_text_get_point ()

guint               gtk_text_get_point                  (GtkText *text);

Warning

gtk_text_get_point is deprecated and should not be used in newly-written code.

Gets the current position of the cursor as the number of characters from the upper left corner of the GtkText widget.

text : | the GtkText widget
Returns : | the number of characters from the upper left corner

gtk_text_get_length ()

guint               gtk_text_get_length                 (GtkText *text);

Warning

gtk_text_get_length is deprecated and should not be used in newly-written code.

Returns the length of the all the text contained within the GtkText widget; disregards current point position.

text : | the GtkText widget
Returns : | the length of the text

gtk_text_freeze ()

void                gtk_text_freeze                     (GtkText *text);

Warning

gtk_text_freeze is deprecated and should not be used in newly-written code.

Freezes the GtkText widget which disallows redrawing of the widget until it is thawed. This is useful if a large number of changes are going to made to the text within the widget, reducing the amount of flicker seen by the user.

text : the GtkText widget

gtk_text_thaw ()

void                gtk_text_thaw                       (GtkText *text);

Warning

gtk_text_thaw is deprecated and should not be used in newly-written code.

Allows the GtkText widget to be redrawn again by GTK.

text : the GtkText widget

gtk_text_insert ()

void                gtk_text_insert                     (GtkText *text,
                                                         GdkFont *font,
                                                         const GdkColor *fore,
                                                         const GdkColor *back,
                                                         const char *chars,
                                                         gint length);

Warning

gtk_text_insert is deprecated and should not be used in newly-written code.

Inserts given text into the GtkText widget with the given properties as outlined below.

text : | the GtkText widget
font : | the GdkFont to use
fore : | the foreground color to insert with
back : | the background color to insert with
chars : | the actual text to be inserted
length : | the length of the text to be inserted, passing -1 makes it insert all the text.

gtk_text_backward_delete ()

gboolean            gtk_text_backward_delete            (GtkText *text,
                                                         guint nchars);

Warning

gtk_text_backward_delete is deprecated and should not be used in newly-written code.

Deletes from the current point position backward the given number of characters.

text : | the GtkText widget
nchars : | the number of characters to delete
Returns : | TRUE if the operation was successful, otherwise returns FALSE

gtk_text_forward_delete ()

gboolean            gtk_text_forward_delete             (GtkText *text,
                                                         guint nchars);

Warning

gtk_text_forward_delete is deprecated and should not be used in newly-written code.

Deletes from the current point position forward the given number of characters.

text : | the GtkText widget
nchars : | the number of characters to delete
Returns : | TRUE if the operation was successful, otherwise returns FALSE

GTK_TEXT_INDEX()

#define             GTK_TEXT_INDEX(t, index)

Warning

GTK_TEXT_INDEX is deprecated and should not be used in newly-written code.

Returns the character at the given index within the GtkText widget.

t : | the GtkText widget
index : | the number of characters from the upper left corner

Property Details

The "hadjustment" property

  "hadjustment"              GtkAdjustment         : Read / Write

Used by the GtkText widget to keep track of the size of its horizontal text.

The "line-wrap" property

  "line-wrap"                gboolean              : Read / Write

Boolean value indicating whether line wrap is enabled or not.

Default value: TRUE

The "vadjustment" property

  "vadjustment"              GtkAdjustment         : Read / Write

Used by the GtkText widget to keep track of the size of its vertical text.

The "word-wrap" property

  "word-wrap"                gboolean              : Read / Write

Boolean value indicated whether word wrap is enabled or not.

Default value: FALSE

Signal Details

The "set-scroll-adjustments" signal

void                user_function                      (GtkText       *text,
                                                        GtkAdjustment *arg1,
                                                        GtkAdjustment *arg2,
                                                        gpointer       user_data)      : Run Last

text : | the object which received the signal.
arg1 : |
arg2 : |
user_data : | user data set when the signal handler was connected.


GtkTextBuffer

GtkTextBuffer — Stores attributed text for display in a GtkTextView

Synopsis

#include <gtk/gtk.h>

                    GtkTextBuffer;
GtkTextBuffer*      gtk_text_buffer_new                 (GtkTextTagTable *table);
gint                gtk_text_buffer_get_line_count      (GtkTextBuffer *buffer);
gint                gtk_text_buffer_get_char_count      (GtkTextBuffer *buffer);
GtkTextTagTable*    gtk_text_buffer_get_tag_table       (GtkTextBuffer *buffer);
void                gtk_text_buffer_insert              (GtkTextBuffer *buffer,
                                                         GtkTextIter *iter,
                                                         const gchar *text,
                                                         gint len);
void                gtk_text_buffer_insert_at_cursor    (GtkTextBuffer *buffer,
                                                         const gchar *text,
                                                         gint len);
gboolean            gtk_text_buffer_insert_interactive  (GtkTextBuffer *buffer,
                                                         GtkTextIter *iter,
                                                         const gchar *text,
                                                         gint len,
                                                         gboolean default_editable);
gboolean            gtk_text_buffer_insert_interactive_at_cursor
                                                        (GtkTextBuffer *buffer,
                                                         const gchar *text,
                                                         gint len,
                                                         gboolean default_editable);
void                gtk_text_buffer_insert_range        (GtkTextBuffer *buffer,
                                                         GtkTextIter *iter,
                                                         const GtkTextIter *start,
                                                         const GtkTextIter *end);
gboolean            gtk_text_buffer_insert_range_interactive
                                                        (GtkTextBuffer *buffer,
                                                         GtkTextIter *iter,
                                                         const GtkTextIter *start,
                                                         const GtkTextIter *end,
                                                         gboolean default_editable);
void                gtk_text_buffer_insert_with_tags    (GtkTextBuffer *buffer,
                                                         GtkTextIter *iter,
                                                         const gchar *text,
                                                         gint len,
                                                         GtkTextTag *first_tag,
                                                         ...);
void                gtk_text_buffer_insert_with_tags_by_name
                                                        (GtkTextBuffer *buffer,
                                                         GtkTextIter *iter,
                                                         const gchar *text,
                                                         gint len,
                                                         const gchar *first_tag_name,
                                                         ...);
void                gtk_text_buffer_delete              (GtkTextBuffer *buffer,
                                                         GtkTextIter *start,
                                                         GtkTextIter *end);
gboolean            gtk_text_buffer_delete_interactive  (GtkTextBuffer *buffer,
                                                         GtkTextIter *start_iter,
                                                         GtkTextIter *end_iter,
                                                         gboolean default_editable);
gboolean            gtk_text_buffer_backspace           (GtkTextBuffer *buffer,
                                                         GtkTextIter *iter,
                                                         gboolean interactive,
                                                         gboolean default_editable);
void                gtk_text_buffer_set_text            (GtkTextBuffer *buffer,
                                                         const gchar *text,
                                                         gint len);
gchar*              gtk_text_buffer_get_text            (GtkTextBuffer *buffer,
                                                         const GtkTextIter *start,
                                                         const GtkTextIter *end,
                                                         gboolean include_hidden_chars);
gchar*              gtk_text_buffer_get_slice           (GtkTextBuffer *buffer,
                                                         const GtkTextIter *start,
                                                         const GtkTextIter *end,
                                                         gboolean include_hidden_chars);
void                gtk_text_buffer_insert_pixbuf       (GtkTextBuffer *buffer,
                                                         GtkTextIter *iter,
                                                         GdkPixbuf *pixbuf);
void                gtk_text_buffer_insert_child_anchor (GtkTextBuffer *buffer,
                                                         GtkTextIter *iter,
                                                         GtkTextChildAnchor *anchor);
GtkTextChildAnchor* gtk_text_buffer_create_child_anchor (GtkTextBuffer *buffer,
                                                         GtkTextIter *iter);
GtkTextMark*        gtk_text_buffer_create_mark         (GtkTextBuffer *buffer,
                                                         const gchar *mark_name,
                                                         const GtkTextIter *where,
                                                         gboolean left_gravity);
void                gtk_text_buffer_move_mark           (GtkTextBuffer *buffer,
                                                         GtkTextMark *mark,
                                                         const GtkTextIter *where);
void                gtk_text_buffer_move_mark_by_name   (GtkTextBuffer *buffer,
                                                         const gchar *name,
                                                         const GtkTextIter *where);
void                gtk_text_buffer_delete_mark         (GtkTextBuffer *buffer,
                                                         GtkTextMark *mark);
void                gtk_text_buffer_delete_mark_by_name (GtkTextBuffer *buffer,
                                                         const gchar *name);
GtkTextMark*        gtk_text_buffer_get_mark            (GtkTextBuffer *buffer,
                                                         const gchar *name);
GtkTextMark*        gtk_text_buffer_get_insert          (GtkTextBuffer *buffer);
GtkTextMark*        gtk_text_buffer_get_selection_bound (GtkTextBuffer *buffer);
gboolean            gtk_text_buffer_get_has_selection   (GtkTextBuffer *buffer);
void                gtk_text_buffer_place_cursor        (GtkTextBuffer *buffer,
                                                         const GtkTextIter *where);
void                gtk_text_buffer_select_range        (GtkTextBuffer *buffer,
                                                         const GtkTextIter *ins,
                                                         const GtkTextIter *bound);
void                gtk_text_buffer_apply_tag           (GtkTextBuffer *buffer,
                                                         GtkTextTag *tag,
                                                         const GtkTextIter *start,
                                                         const GtkTextIter *end);
void                gtk_text_buffer_remove_tag          (GtkTextBuffer *buffer,
                                                         GtkTextTag *tag,
                                                         const GtkTextIter *start,
                                                         const GtkTextIter *end);
void                gtk_text_buffer_apply_tag_by_name   (GtkTextBuffer *buffer,
                                                         const gchar *name,
                                                         const GtkTextIter *start,
                                                         const GtkTextIter *end);
void                gtk_text_buffer_remove_tag_by_name  (GtkTextBuffer *buffer,
                                                         const gchar *name,
                                                         const GtkTextIter *start,
                                                         const GtkTextIter *end);
void                gtk_text_buffer_remove_all_tags     (GtkTextBuffer *buffer,
                                                         const GtkTextIter *start,
                                                         const GtkTextIter *end);
GtkTextTag*         gtk_text_buffer_create_tag          (GtkTextBuffer *buffer,
                                                         const gchar *tag_name,
                                                         const gchar *first_property_name,
                                                         ...);
void                gtk_text_buffer_get_iter_at_line_offset
                                                        (GtkTextBuffer *buffer,
                                                         GtkTextIter *iter,
                                                         gint line_number,
                                                         gint char_offset);
void                gtk_text_buffer_get_iter_at_offset  (GtkTextBuffer *buffer,
                                                         GtkTextIter *iter,
                                                         gint char_offset);
void                gtk_text_buffer_get_iter_at_line    (GtkTextBuffer *buffer,
                                                         GtkTextIter *iter,
                                                         gint line_number);
void                gtk_text_buffer_get_iter_at_line_index
                                                        (GtkTextBuffer *buffer,
                                                         GtkTextIter *iter,
                                                         gint line_number,
                                                         gint byte_index);
void                gtk_text_buffer_get_iter_at_mark    (GtkTextBuffer *buffer,
                                                         GtkTextIter *iter,
                                                         GtkTextMark *mark);
void                gtk_text_buffer_get_iter_at_child_anchor
                                                        (GtkTextBuffer *buffer,
                                                         GtkTextIter *iter,
                                                         GtkTextChildAnchor *anchor);
void                gtk_text_buffer_get_start_iter      (GtkTextBuffer *buffer,
                                                         GtkTextIter *iter);
void                gtk_text_buffer_get_end_iter        (GtkTextBuffer *buffer,
                                                         GtkTextIter *iter);
void                gtk_text_buffer_get_bounds          (GtkTextBuffer *buffer,
                                                         GtkTextIter *start,
                                                         GtkTextIter *end);
gboolean            gtk_text_buffer_get_modified        (GtkTextBuffer *buffer);
void                gtk_text_buffer_set_modified        (GtkTextBuffer *buffer,
                                                         gboolean setting);
gboolean            gtk_text_buffer_delete_selection    (GtkTextBuffer *buffer,
                                                         gboolean interactive,
                                                         gboolean default_editable);
void                gtk_text_buffer_paste_clipboard     (GtkTextBuffer *buffer,
                                                         GtkClipboard *clipboard,
                                                         GtkTextIter *override_location,
                                                         gboolean default_editable);
void                gtk_text_buffer_copy_clipboard      (GtkTextBuffer *buffer,
                                                         GtkClipboard *clipboard);
void                gtk_text_buffer_cut_clipboard       (GtkTextBuffer *buffer,
                                                         GtkClipboard *clipboard,
                                                         gboolean default_editable);
gboolean            gtk_text_buffer_get_selection_bounds
                                                        (GtkTextBuffer *buffer,
                                                         GtkTextIter *start,
                                                         GtkTextIter *end);
void                gtk_text_buffer_begin_user_action   (GtkTextBuffer *buffer);
void                gtk_text_buffer_end_user_action     (GtkTextBuffer *buffer);
void                gtk_text_buffer_add_selection_clipboard
                                                        (GtkTextBuffer *buffer,
                                                         GtkClipboard *clipboard);
void                gtk_text_buffer_remove_selection_clipboard
                                                        (GtkTextBuffer *buffer,
                                                         GtkClipboard *clipboard);

enum                GtkTextBufferTargetInfo;
gboolean            (*GtkTextBufferDeserializeFunc)     (GtkTextBuffer *register_buffer,
                                                         GtkTextBuffer *content_buffer,
                                                         GtkTextIter *iter,
                                                         const guint8 *data,
                                                         gsize length,
                                                         gboolean create_tags,
                                                         gpointer user_data,
                                                         GError **error);
gboolean            gtk_text_buffer_deserialize         (GtkTextBuffer *register_buffer,
                                                         GtkTextBuffer *content_buffer,
                                                         GdkAtom format,
                                                         GtkTextIter *iter,
                                                         const guint8 *data,
                                                         gsize length,
                                                         GError **error);
gboolean            gtk_text_buffer_deserialize_get_can_create_tags
                                                        (GtkTextBuffer *buffer,
                                                         GdkAtom format);
void                gtk_text_buffer_deserialize_set_can_create_tags
                                                        (GtkTextBuffer *buffer,
                                                         GdkAtom format,
                                                         gboolean can_create_tags);
GtkTargetList*      gtk_text_buffer_get_copy_target_list
                                                        (GtkTextBuffer *buffer);
GdkAtom*            gtk_text_buffer_get_deserialize_formats
                                                        (GtkTextBuffer *buffer,
                                                         gint *n_formats);
GtkTargetList*      gtk_text_buffer_get_paste_target_list
                                                        (GtkTextBuffer *buffer);
GdkAtom*            gtk_text_buffer_get_serialize_formats
                                                        (GtkTextBuffer *buffer,
                                                         gint *n_formats);
GdkAtom             gtk_text_buffer_register_deserialize_format
                                                        (GtkTextBuffer *buffer,
                                                         const gchar *mime_type,
                                                         GtkTextBufferDeserializeFunc function,
                                                         gpointer user_data,
                                                         GDestroyNotify user_data_destroy);
GdkAtom             gtk_text_buffer_register_deserialize_tagset
                                                        (GtkTextBuffer *buffer,
                                                         const gchar *tagset_name);
GdkAtom             gtk_text_buffer_register_serialize_format
                                                        (GtkTextBuffer *buffer,
                                                         const gchar *mime_type,
                                                         GtkTextBufferSerializeFunc function,
                                                         gpointer user_data,
                                                         GDestroyNotify user_data_destroy);
GdkAtom             gtk_text_buffer_register_serialize_tagset
                                                        (GtkTextBuffer *buffer,
                                                         const gchar *tagset_name);
guint8*             (*GtkTextBufferSerializeFunc)       (GtkTextBuffer *register_buffer,
                                                         GtkTextBuffer *content_buffer,
                                                         const GtkTextIter *start,
                                                         const GtkTextIter *end,
                                                         gsize *length,
                                                         gpointer user_data);
guint8*             gtk_text_buffer_serialize           (GtkTextBuffer *register_buffer,
                                                         GtkTextBuffer *content_buffer,
                                                         GdkAtom format,
                                                         const GtkTextIter *start,
                                                         const GtkTextIter *end,
                                                         gsize *length);
void                gtk_text_buffer_unregister_deserialize_format
                                                        (GtkTextBuffer *buffer,
                                                         GdkAtom format);
void                gtk_text_buffer_unregister_serialize_format
                                                        (GtkTextBuffer *buffer,
                                                         GdkAtom format);

Object Hierarchy

  GObject
   +----GtkTextBuffer

Properties

  "copy-target-list"         GtkTargetList         : Read
  "cursor-position"          gint                  : Read
  "has-selection"            gboolean              : Read
  "paste-target-list"        GtkTargetList         : Read
  "tag-table"                GtkTextTagTable       : Read / Write / Construct Only
  "text"                     gchararray            : Read / Write

Signals

  "apply-tag"                                      : Run Last
  "begin-user-action"                              : Run Last
  "changed"                                        : Run Last
  "delete-range"                                   : Run Last
  "end-user-action"                                : Run Last
  "insert-child-anchor"                            : Run Last
  "insert-pixbuf"                                  : Run Last
  "insert-text"                                    : Run Last
  "mark-deleted"                                   : Run Last
  "mark-set"                                       : Run Last
  "modified-changed"                               : Run Last
  "remove-tag"                                     : Run Last

Description

You may wish to begin by reading the text widget conceptual overview which gives an overview of all the objects and data types related to the text widget and how they work together.

Details

GtkTextBuffer

typedef struct _GtkTextBuffer GtkTextBuffer;

gtk_text_buffer_new ()

GtkTextBuffer*      gtk_text_buffer_new                 (GtkTextTagTable *table);

Creates a new text buffer.

table : | a tag table, or NULL to create a new one
Returns : | a new text buffer

gtk_text_buffer_get_line_count ()

gint                gtk_text_buffer_get_line_count      (GtkTextBuffer *buffer);

Obtains the number of lines in the buffer. This value is cached, so the function is very fast.

buffer : | a GtkTextBuffer
Returns : | number of lines in the buffer

gtk_text_buffer_get_char_count ()

gint                gtk_text_buffer_get_char_count      (GtkTextBuffer *buffer);

Gets the number of characters in the buffer; note that characters and bytes are not the same, you can't e.g. expect the contents of the buffer in string form to be this many bytes long. The character count is cached, so this function is very fast.

buffer : | a GtkTextBuffer
Returns : | number of characters in the buffer

gtk_text_buffer_get_tag_table ()

GtkTextTagTable*    gtk_text_buffer_get_tag_table       (GtkTextBuffer *buffer);

Get the GtkTextTagTable associated with this buffer.

buffer : | a GtkTextBuffer
Returns : | the buffer's tag table

gtk_text_buffer_insert ()

void                gtk_text_buffer_insert              (GtkTextBuffer *buffer,
                                                         GtkTextIter *iter,
                                                         const gchar *text,
                                                         gint len);

Inserts len bytes of text at position iter. If len is -1, text must be nul-terminated and will be inserted in its entirety. Emits the "insert_text" signal; insertion actually occurs in the default handler for the signal. iter is invalidated when insertion occurs (because the buffer contents change), but the default signal handler revalidates it to point to the end of the inserted text.

buffer : | a GtkTextBuffer
iter : | a position in the buffer
text : | UTF-8 format text to insert
len : | length of text in bytes, or -1

gtk_text_buffer_insert_at_cursor ()

void                gtk_text_buffer_insert_at_cursor    (GtkTextBuffer *buffer,
                                                         const gchar *text,
                                                         gint len);

Simply calls gtk_text_buffer_insert(), using the current cursor position as the insertion point.

buffer : | a GtkTextBuffer
text : | some text in UTF-8 format
len : | length of text, in bytes

gtk_text_buffer_insert_interactive ()

gboolean            gtk_text_buffer_insert_interactive  (GtkTextBuffer *buffer,
                                                         GtkTextIter *iter,
                                                         const gchar *text,
                                                         gint len,
                                                         gboolean default_editable);

Like gtk_text_buffer_insert(), but the insertion will not occur if iter is at a non-editable location in the buffer. Usually you want to prevent insertions at ineditable locations if the insertion results from a user action (is interactive).

default_editable indicates the editability of text that doesn't have a tag affecting editability applied to it. Typically the result of gtk_text_view_get_editable() is appropriate here.

buffer : | a GtkTextBuffer
iter : | a position in buffer
text : | some UTF-8 text
len : | length of text in bytes, or -1
default_editable : | default editability of buffer
Returns : | whether text was actually inserted

gtk_text_buffer_insert_interactive_at_cursor ()

gboolean            gtk_text_buffer_insert_interactive_at_cursor
                                                        (GtkTextBuffer *buffer,
                                                         const gchar *text,
                                                         gint len,
                                                         gboolean default_editable);

Calls gtk_text_buffer_insert_interactive() at the cursor position.

default_editable indicates the editability of text that doesn't have a tag affecting editability applied to it. Typically the result of gtk_text_view_get_editable() is appropriate here.

buffer : | a GtkTextBuffer
text : | text in UTF-8 format
len : | length of text in bytes, or -1
default_editable : | default editability of buffer
Returns : | whether text was actually inserted

gtk_text_buffer_insert_range ()

void                gtk_text_buffer_insert_range        (GtkTextBuffer *buffer,
                                                         GtkTextIter *iter,
                                                         const GtkTextIter *start,
                                                         const GtkTextIter *end);

Copies text, tags, and pixbufs between start and end (the order of start and end doesn't matter) and inserts the copy at iter. Used instead of simply getting/inserting text because it preserves images and tags. If start and end are in a different buffer from buffer, the two buffers must share the same tag table.

Implemented via emissions of the insert_text and apply_tag signals, so expect those.

buffer : | a GtkTextBuffer
iter : | a position in buffer
start : | a position in a GtkTextBuffer
end : | another position in the same buffer as start

gtk_text_buffer_insert_range_interactive ()

gboolean            gtk_text_buffer_insert_range_interactive
                                                        (GtkTextBuffer *buffer,
                                                         GtkTextIter *iter,
                                                         const GtkTextIter *start,
                                                         const GtkTextIter *end,
                                                         gboolean default_editable);

Same as gtk_text_buffer_insert_range(), but does nothing if the insertion point isn't editable. The default_editable parameter indicates whether the text is editable at iter if no tags enclosing iter affect editability. Typically the result of gtk_text_view_get_editable() is appropriate here.

buffer : | a GtkTextBuffer
iter : | a position in buffer
start : | a position in a GtkTextBuffer
end : | another position in the same buffer as start
default_editable : | default editability of the buffer
Returns : | whether an insertion was possible at iter

gtk_text_buffer_insert_with_tags ()

void                gtk_text_buffer_insert_with_tags    (GtkTextBuffer *buffer,
                                                         GtkTextIter *iter,
                                                         const gchar *text,
                                                         gint len,
                                                         GtkTextTag *first_tag,
                                                         ...);

Inserts text into buffer at iter, applying the list of tags to the newly-inserted text. The last tag specified must be NULL to terminate the list. Equivalent to calling gtk_text_buffer_insert(), then gtk_text_buffer_apply_tag() on the inserted text; gtk_text_buffer_insert_with_tags() is just a convenience function.

buffer : | a GtkTextBuffer
iter : | an iterator in buffer
text : | UTF-8 text
len : | length of text, or -1
first_tag : | first tag to apply to text
... : | NULL-terminated list of tags to apply

gtk_text_buffer_insert_with_tags_by_name ()

void                gtk_text_buffer_insert_with_tags_by_name
                                                        (GtkTextBuffer *buffer,
                                                         GtkTextIter *iter,
                                                         const gchar *text,
                                                         gint len,
                                                         const gchar *first_tag_name,
                                                         ...);

Same as gtk_text_buffer_insert_with_tags(), but allows you to pass in tag names instead of tag objects.

buffer : | a GtkTextBuffer
iter : | position in buffer
text : | UTF-8 text
len : | length of text, or -1
first_tag_name : | name of a tag to apply to text
... : | more tag names

gtk_text_buffer_delete ()

void                gtk_text_buffer_delete              (GtkTextBuffer *buffer,
                                                         GtkTextIter *start,
                                                         GtkTextIter *end);

Deletes text between start and end. The order of start and end is not actually relevant; gtk_text_buffer_delete() will reorder them. This function actually emits the "delete_range" signal, and the default handler of that signal deletes the text. Because the buffer is modified, all outstanding iterators become invalid after calling this function; however, the start and end will be re-initialized to point to the location where text was deleted.

buffer : | a GtkTextBuffer
start : | a position in buffer
end : | another position in buffer

gtk_text_buffer_delete_interactive ()

gboolean            gtk_text_buffer_delete_interactive  (GtkTextBuffer *buffer,
                                                         GtkTextIter *start_iter,
                                                         GtkTextIter *end_iter,
                                                         gboolean default_editable);

Deletes all editable text in the given range. Calls gtk_text_buffer_delete() for each editable sub-range of [start,end). start and end are revalidated to point to the location of the last deleted range, or left untouched if no text was deleted.

buffer : | a GtkTextBuffer
start_iter : | start of range to delete
end_iter : | end of range
default_editable : | whether the buffer is editable by default
Returns : | whether some text was actually deleted

gtk_text_buffer_backspace ()

gboolean            gtk_text_buffer_backspace           (GtkTextBuffer *buffer,
                                                         GtkTextIter *iter,
                                                         gboolean interactive,
                                                         gboolean default_editable);

Performs the appropriate action as if the user hit the delete key with the cursor at the position specified by iter. In the normal case a single character will be deleted, but when combining accents are involved, more than one character can be deleted, and when precomposed character and accent combinations are involved, less than one character will be deleted.

Because the buffer is modified, all outstanding iterators become invalid after calling this function; however, the iter will be re-initialized to point to the location where text was deleted.

buffer : | a GtkTextBuffer
iter : | a position in buffer
interactive : | whether the deletion is caused by user interaction
default_editable : | whether the buffer is editable by default
Returns : | TRUE if the buffer was modified

Since 2.6

gtk_text_buffer_set_text ()

void                gtk_text_buffer_set_text            (GtkTextBuffer *buffer,
                                                         const gchar *text,
                                                         gint len);

Deletes current contents of buffer, and inserts text instead. If len is -1, text must be nul-terminated. text must be valid UTF-8.

buffer : | a GtkTextBuffer
text : | UTF-8 text to insert
len : | length of text in bytes

gtk_text_buffer_get_text ()

gchar*              gtk_text_buffer_get_text            (GtkTextBuffer *buffer,
                                                         const GtkTextIter *start,
                                                         const GtkTextIter *end,
                                                         gboolean include_hidden_chars);

Returns the text in the range [start,end). Excludes undisplayed text (text marked with tags that set the invisibility attribute) if include_hidden_chars is FALSE. Does not include characters representing embedded images, so byte and character indexes into the returned string do not correspond to byte and character indexes into the buffer. Contrast with gtk_text_buffer_get_slice().

buffer : | a GtkTextBuffer
start : | start of a range
end : | end of a range
include_hidden_chars : | whether to include invisible text
Returns : | an allocated UTF-8 string

gtk_text_buffer_get_slice ()

gchar*              gtk_text_buffer_get_slice           (GtkTextBuffer *buffer,
                                                         const GtkTextIter *start,
                                                         const GtkTextIter *end,
                                                         gboolean include_hidden_chars);

Returns the text in the range [start,end). Excludes undisplayed text (text marked with tags that set the invisibility attribute) if include_hidden_chars is FALSE. The returned string includes a 0xFFFC character whenever the buffer contains embedded images, so byte and character indexes into the returned string do correspond to byte and character indexes into the buffer. Contrast with gtk_text_buffer_get_text(). Note that 0xFFFC can occur in normal text as well, so it is not a reliable indicator that a pixbuf or widget is in the buffer.

buffer : | a GtkTextBuffer
start : | start of a range
end : | end of a range
include_hidden_chars : | whether to include invisible text
Returns : | an allocated UTF-8 string

gtk_text_buffer_insert_pixbuf ()

void                gtk_text_buffer_insert_pixbuf       (GtkTextBuffer *buffer,
                                                         GtkTextIter *iter,
                                                         GdkPixbuf *pixbuf);

Inserts an image into the text buffer at iter. The image will be counted as one character in character counts, and when obtaining the buffer contents as a string, will be represented by the Unicode "object replacement character" 0xFFFC. Note that the "slice" variants for obtaining portions of the buffer as a string include this character for pixbufs, but the "text" variants do not. e.g. see gtk_text_buffer_get_slice() and gtk_text_buffer_get_text().

buffer : | a GtkTextBuffer
iter : | location to insert the pixbuf
pixbuf : | a GdkPixbuf

gtk_text_buffer_insert_child_anchor ()

void                gtk_text_buffer_insert_child_anchor (GtkTextBuffer *buffer,
                                                         GtkTextIter *iter,
                                                         GtkTextChildAnchor *anchor);

Inserts a child widget anchor into the text buffer at iter. The anchor will be counted as one character in character counts, and when obtaining the buffer contents as a string, will be represented by the Unicode "object replacement character" 0xFFFC. Note that the "slice" variants for obtaining portions of the buffer as a string include this character for child anchors, but the "text" variants do not. e.g. see gtk_text_buffer_get_slice() and gtk_text_buffer_get_text(). Consider gtk_text_buffer_create_child_anchor() as a more convenient alternative to this function. The buffer will add a reference to the anchor, so you can unref it after insertion.

buffer : | a GtkTextBuffer
iter : | location to insert the anchor
anchor : | a GtkTextChildAnchor

gtk_text_buffer_create_child_anchor ()

GtkTextChildAnchor* gtk_text_buffer_create_child_anchor (GtkTextBuffer *buffer,
                                                         GtkTextIter *iter);

This is a convenience function which simply creates a child anchor with gtk_text_child_anchor_new() and inserts it into the buffer with gtk_text_buffer_insert_child_anchor(). The new anchor is owned by the buffer; no reference count is returned to the caller of gtk_text_buffer_create_child_anchor().

buffer : | a GtkTextBuffer
iter : | location in the buffer
Returns : | the created child anchor

gtk_text_buffer_create_mark ()

GtkTextMark*        gtk_text_buffer_create_mark         (GtkTextBuffer *buffer,
                                                         const gchar *mark_name,
                                                         const GtkTextIter *where,
                                                         gboolean left_gravity);

Creates a mark at position where. If mark_name is NULL, the mark is anonymous; otherwise, the mark can be retrieved by name using gtk_text_buffer_get_mark(). If a mark has left gravity, and text is inserted at the mark's current location, the mark will be moved to the left of the newly-inserted text. If the mark has right gravity (left_gravity = FALSE), the mark will end up on the right of newly-inserted text. The standard left-to-right cursor is a mark with right gravity (when you type, the cursor stays on the right side of the text you're typing).

The caller of this function does not own a reference to the returned GtkTextMark, so you can ignore the return value if you like. Marks are owned by the buffer and go away when the buffer does.

Emits the "mark_set" signal as notification of the mark's initial placement.

buffer : | a GtkTextBuffer
mark_name : | name for mark, or NULL
where : | location to place mark
left_gravity : | whether the mark has left gravity
Returns : | the new GtkTextMark object

gtk_text_buffer_move_mark ()

void                gtk_text_buffer_move_mark           (GtkTextBuffer *buffer,
                                                         GtkTextMark *mark,
                                                         const GtkTextIter *where);

Moves mark to the new location where. Emits the "mark_set" signal as notification of the move.

buffer : | a GtkTextBuffer
mark : | a GtkTextMark
where : | new location for mark in buffer

gtk_text_buffer_move_mark_by_name ()

void                gtk_text_buffer_move_mark_by_name   (GtkTextBuffer *buffer,
                                                         const gchar *name,
                                                         const GtkTextIter *where);

Moves the mark named name (which must exist) to location where. See gtk_text_buffer_move_mark() for details.

buffer : | a GtkTextBuffer
name : | name of a mark
where : | new location for mark

gtk_text_buffer_delete_mark ()

void                gtk_text_buffer_delete_mark         (GtkTextBuffer *buffer,
                                                         GtkTextMark *mark);

Deletes mark, so that it's no longer located anywhere in the buffer. Removes the reference the buffer holds to the mark, so if you haven't called g_object_ref() on the mark, it will be freed. Even if the mark isn't freed, most operations on mark become invalid. There is no way to undelete a mark. gtk_text_mark_get_deleted() will return TRUE after this function has been called on a mark; gtk_text_mark_get_deleted() indicates that a mark no longer belongs to a buffer. The "mark_deleted" signal will be emitted as notification after the mark is deleted.

buffer : | a GtkTextBuffer
mark : | a GtkTextMark in buffer

gtk_text_buffer_delete_mark_by_name ()

void                gtk_text_buffer_delete_mark_by_name (GtkTextBuffer *buffer,
                                                         const gchar *name);

Deletes the mark named name; the mark must exist. See gtk_text_buffer_delete_mark() for details.

buffer : | a GtkTextBuffer
name : | name of a mark in buffer

gtk_text_buffer_get_mark ()

GtkTextMark*        gtk_text_buffer_get_mark            (GtkTextBuffer *buffer,
                                                         const gchar *name);

Returns the mark named name in buffer buffer, or NULL if no such mark exists in the buffer.

buffer : | a GtkTextBuffer
name : | a mark name
Returns : | a GtkTextMark, or NULL

gtk_text_buffer_get_insert ()

GtkTextMark*        gtk_text_buffer_get_insert          (GtkTextBuffer *buffer);

Returns the mark that represents the cursor (insertion point). Equivalent to calling gtk_text_buffer_get_mark() to get the mark named "insert", but very slightly more efficient, and involves less typing.

buffer : | a GtkTextBuffer
Returns : | insertion point mark

gtk_text_buffer_get_selection_bound ()

GtkTextMark*        gtk_text_buffer_get_selection_bound (GtkTextBuffer *buffer);

Returns the mark that represents the selection bound. Equivalent to calling gtk_text_buffer_get_mark() to get the mark named "selection_bound", but very slightly more efficient, and involves less typing.

The currently-selected text in buffer is the region between the "selection_bound" and "insert" marks. If "selection_bound" and "insert" are in the same place, then there is no current selection. gtk_text_buffer_get_selection_bounds() is another convenient function for handling the selection, if you just want to know whether there's a selection and what its bounds are.

buffer : | a GtkTextBuffer
Returns : | selection bound mark

gtk_text_buffer_get_has_selection ()

gboolean            gtk_text_buffer_get_has_selection   (GtkTextBuffer *buffer);

Indicates whether the buffer has some text currently selected.

buffer : | a GtkTextBuffer
Returns : | TRUE if the there is text selected

Since 2.10

gtk_text_buffer_place_cursor ()

void                gtk_text_buffer_place_cursor        (GtkTextBuffer *buffer,
                                                         const GtkTextIter *where);

This function moves the "insert" and "selection_bound" marks simultaneously. If you move them to the same place in two steps with gtk_text_buffer_move_mark(), you will temporarily select a region in between their old and new locations, which can be pretty inefficient since the temporarily-selected region will force stuff to be recalculated. This function moves them as a unit, which can be optimized.

buffer : | a GtkTextBuffer
where : | where to put the cursor

gtk_text_buffer_select_range ()

void                gtk_text_buffer_select_range        (GtkTextBuffer *buffer,
                                                         const GtkTextIter *ins,
                                                         const GtkTextIter *bound);

This function moves the "insert" and "selection_bound" marks simultaneously. If you move them in two steps with gtk_text_buffer_move_mark(), you will temporarily select a region in between their old and new locations, which can be pretty inefficient since the temporarily-selected region will force stuff to be recalculated. This function moves them as a unit, which can be optimized.

buffer : | a GtkTextBuffer
ins : | where to put the "insert" mark
bound : | where to put the "selection_bound" mark

Since 2.4

gtk_text_buffer_apply_tag ()

void                gtk_text_buffer_apply_tag           (GtkTextBuffer *buffer,
                                                         GtkTextTag *tag,
                                                         const GtkTextIter *start,
                                                         const GtkTextIter *end);

Emits the "apply_tag" signal on buffer. The default handler for the signal applies tag to the given range. start and end do not have to be in order.

buffer : | a GtkTextBuffer
tag : | a GtkTextTag
start : | one bound of range to be tagged
end : | other bound of range to be tagged

gtk_text_buffer_remove_tag ()

void                gtk_text_buffer_remove_tag          (GtkTextBuffer *buffer,
                                                         GtkTextTag *tag,
                                                         const GtkTextIter *start,
                                                         const GtkTextIter *end);

Emits the "remove_tag" signal. The default handler for the signal removes all occurrences of tag from the given range. start and end don't have to be in order.

buffer : | a GtkTextBuffer
tag : | a GtkTextTag
start : | one bound of range to be untagged
end : | other bound of range to be untagged

gtk_text_buffer_apply_tag_by_name ()

void                gtk_text_buffer_apply_tag_by_name   (GtkTextBuffer *buffer,
                                                         const gchar *name,
                                                         const GtkTextIter *start,
                                                         const GtkTextIter *end);

Calls gtk_text_tag_table_lookup() on the buffer's tag table to get a GtkTextTag, then calls gtk_text_buffer_apply_tag().

buffer : | a GtkTextBuffer
name : | name of a named GtkTextTag
start : | one bound of range to be tagged
end : | other bound of range to be tagged

gtk_text_buffer_remove_tag_by_name ()

void                gtk_text_buffer_remove_tag_by_name  (GtkTextBuffer *buffer,
                                                         const gchar *name,
                                                         const GtkTextIter *start,
                                                         const GtkTextIter *end);

Calls gtk_text_tag_table_lookup() on the buffer's tag table to get a GtkTextTag, then calls gtk_text_buffer_remove_tag().

buffer : | a GtkTextBuffer
name : | name of a GtkTextTag
start : | one bound of range to be untagged
end : | other bound of range to be untagged

gtk_text_buffer_remove_all_tags ()

void                gtk_text_buffer_remove_all_tags     (GtkTextBuffer *buffer,
                                                         const GtkTextIter *start,
                                                         const GtkTextIter *end);

Removes all tags in the range between start and end. Be careful with this function; it could remove tags added in code unrelated to the code you're currently writing. That is, using this function is probably a bad idea if you have two or more unrelated code sections that add tags.

buffer : | a GtkTextBuffer
start : | one bound of range to be untagged
end : | other bound of range to be untagged

gtk_text_buffer_create_tag ()

GtkTextTag*         gtk_text_buffer_create_tag          (GtkTextBuffer *buffer,
                                                         const gchar *tag_name,
                                                         const gchar *first_property_name,
                                                         ...);

Creates a tag and adds it to the tag table for buffer. Equivalent to calling gtk_text_tag_new() and then adding the tag to the buffer's tag table. The returned tag is owned by the buffer's tag table, so the ref count will be equal to one.

If tag_name is NULL, the tag is anonymous.

If tag_name is non-NULL, a tag called tag_name must not already exist in the tag table for this buffer.

The first_property_name argument and subsequent arguments are a list of properties to set on the tag, as with g_object_set().

buffer : | a GtkTextBuffer
tag_name : | name of the new tag, or NULL
first_property_name : | name of first property to set, or NULL
... : | NULL-terminated list of property names and values
Returns : | a new tag

gtk_text_buffer_get_iter_at_line_offset ()

void                gtk_text_buffer_get_iter_at_line_offset
                                                        (GtkTextBuffer *buffer,
                                                         GtkTextIter *iter,
                                                         gint line_number,
                                                         gint char_offset);

Obtains an iterator pointing to char_offset within the given line. The char_offset must exist, offsets off the end of the line are not allowed. Note characters, not bytes; UTF-8 may encode one character as multiple bytes.

buffer : | a GtkTextBuffer
iter : | iterator to initialize
line_number : | line number counting from 0
char_offset : | char offset from start of line

gtk_text_buffer_get_iter_at_offset ()

void                gtk_text_buffer_get_iter_at_offset  (GtkTextBuffer *buffer,
                                                         GtkTextIter *iter,
                                                         gint char_offset);

Initializes iter to a position char_offset chars from the start of the entire buffer. If char_offset is -1 or greater than the number of characters in the buffer, iter is initialized to the end iterator, the iterator one past the last valid character in the buffer.

buffer : | a GtkTextBuffer
iter : | iterator to initialize
char_offset : | char offset from start of buffer, counting from 0, or -1

gtk_text_buffer_get_iter_at_line ()

void                gtk_text_buffer_get_iter_at_line    (GtkTextBuffer *buffer,
                                                         GtkTextIter *iter,
                                                         gint line_number);

Initializes iter to the start of the given line.

buffer : | a GtkTextBuffer
iter : | iterator to initialize
line_number : | line number counting from 0

gtk_text_buffer_get_iter_at_line_index ()

void                gtk_text_buffer_get_iter_at_line_index
                                                        (GtkTextBuffer *buffer,
                                                         GtkTextIter *iter,
                                                         gint line_number,
                                                         gint byte_index);

Obtains an iterator pointing to byte_index within the given line. byte_index must be the start of a UTF-8 character, and must not be beyond the end of the line. Note bytes, not characters; UTF-8 may encode one character as multiple bytes.

buffer : | a GtkTextBuffer
iter : | iterator to initialize
line_number : | line number counting from 0
byte_index : | byte index from start of line

gtk_text_buffer_get_iter_at_mark ()

void                gtk_text_buffer_get_iter_at_mark    (GtkTextBuffer *buffer,
                                                         GtkTextIter *iter,
                                                         GtkTextMark *mark);

Initializes iter with the current position of mark.

buffer : | a GtkTextBuffer
iter : | iterator to initialize
mark : | a GtkTextMark in buffer

gtk_text_buffer_get_iter_at_child_anchor ()

void                gtk_text_buffer_get_iter_at_child_anchor
                                                        (GtkTextBuffer *buffer,
                                                         GtkTextIter *iter,
                                                         GtkTextChildAnchor *anchor);

Obtains the location of anchor within buffer.

buffer : | a GtkTextBuffer
iter : | an iterator to be initialized
anchor : | a child anchor that appears in buffer

gtk_text_buffer_get_start_iter ()

void                gtk_text_buffer_get_start_iter      (GtkTextBuffer *buffer,
                                                         GtkTextIter *iter);

Initialized iter with the first position in the text buffer. This is the same as using gtk_text_buffer_get_iter_at_offset() to get the iter at character offset 0.

buffer : | a GtkTextBuffer
iter : | iterator to initialize

gtk_text_buffer_get_end_iter ()

void                gtk_text_buffer_get_end_iter        (GtkTextBuffer *buffer,
                                                         GtkTextIter *iter);

Initializes iter with the "end iterator," one past the last valid character in the text buffer. If dereferenced with gtk_text_iter_get_char(), the end iterator has a character value of 0. The entire buffer lies in the range from the first position in the buffer (call gtk_text_buffer_get_start_iter() to get character position 0) to the end iterator.

buffer : | a GtkTextBuffer
iter : | iterator to initialize

gtk_text_buffer_get_bounds ()

void                gtk_text_buffer_get_bounds          (GtkTextBuffer *buffer,
                                                         GtkTextIter *start,
                                                         GtkTextIter *end);

Retrieves the first and last iterators in the buffer, i.e. the entire buffer lies within the range [start,end).

buffer : | a GtkTextBuffer
start : | iterator to initialize with first position in the buffer
end : | iterator to initialize with the end iterator

gtk_text_buffer_get_modified ()

gboolean            gtk_text_buffer_get_modified        (GtkTextBuffer *buffer);

Indicates whether the buffer has been modified since the last call to gtk_text_buffer_set_modified() set the modification flag to FALSE. Used for example to enable a "save" function in a text editor.

buffer : | a GtkTextBuffer
Returns : | TRUE if the buffer has been modified

gtk_text_buffer_set_modified ()

void                gtk_text_buffer_set_modified        (GtkTextBuffer *buffer,
                                                         gboolean setting);

Used to keep track of whether the buffer has been modified since the last time it was saved. Whenever the buffer is saved to disk, call gtk_text_buffer_set_modified (buffer, FALSE). When the buffer is modified, it will automatically toggled on the modified bit again. When the modified bit flips, the buffer emits a "modified_changed" signal.

buffer : | a GtkTextBuffer
setting : | modification flag setting

gtk_text_buffer_delete_selection ()

gboolean            gtk_text_buffer_delete_selection    (GtkTextBuffer *buffer,
                                                         gboolean interactive,
                                                         gboolean default_editable);

Deletes the range between the "insert" and "selection_bound" marks, that is, the currently-selected text. If interactive is TRUE, the editability of the selection will be considered (users can't delete uneditable text).

buffer : | a GtkTextBuffer
interactive : | whether the deletion is caused by user interaction
default_editable : | whether the buffer is editable by default
Returns : | whether there was a non-empty selection to delete

gtk_text_buffer_paste_clipboard ()

void                gtk_text_buffer_paste_clipboard     (GtkTextBuffer *buffer,
                                                         GtkClipboard *clipboard,
                                                         GtkTextIter *override_location,
                                                         gboolean default_editable);

Pastes the contents of a clipboard at the insertion point, or at override_location. (Note: pasting is asynchronous, that is, we'll ask for the paste data and return, and at some point later after the main loop runs, the paste data will be inserted.)

buffer : | a GtkTextBuffer
clipboard : | the GtkClipboard to paste from
override_location : | location to insert pasted text, or NULL for at the cursor
default_editable : | whether the buffer is editable by default

gtk_text_buffer_copy_clipboard ()

void                gtk_text_buffer_copy_clipboard      (GtkTextBuffer *buffer,
                                                         GtkClipboard *clipboard);

Copies the currently-selected text to a clipboard.

buffer : | a GtkTextBuffer
clipboard : | the GtkClipboard object to copy to.

gtk_text_buffer_cut_clipboard ()

void                gtk_text_buffer_cut_clipboard       (GtkTextBuffer *buffer,
                                                         GtkClipboard *clipboard,
                                                         gboolean default_editable);

Copies the currently-selected text to a clipboard, then deletes said text if it's editable.

buffer : | a GtkTextBuffer
clipboard : | the GtkClipboard object to cut to.
default_editable : | default editability of the buffer

gtk_text_buffer_get_selection_bounds ()

gboolean            gtk_text_buffer_get_selection_bounds
                                                        (GtkTextBuffer *buffer,
                                                         GtkTextIter *start,
                                                         GtkTextIter *end);

Returns TRUE if some text is selected; places the bounds of the selection in start and end (if the selection has length 0, then start and end are filled in with the same value). start and end will be in ascending order. If start and end are NULL, then they are not filled in, but the return value still indicates whether text is selected.

buffer : | a GtkTextBuffer a GtkTextBuffer
start : | iterator to initialize with selection start
end : | iterator to initialize with selection end
Returns : | whether the selection has nonzero length

gtk_text_buffer_begin_user_action ()

void                gtk_text_buffer_begin_user_action   (GtkTextBuffer *buffer);

Called to indicate that the buffer operations between here and a call to gtk_text_buffer_end_user_action() are part of a single user-visible operation. The operations between gtk_text_buffer_begin_user_action() and gtk_text_buffer_end_user_action() can then be grouped when creating an undo stack. GtkTextBuffer maintains a count of calls to gtk_text_buffer_begin_user_action() that have not been closed with a call to gtk_text_buffer_end_user_action(), and emits the "begin_user_action" and "end_user_action" signals only for the outermost pair of calls. This allows you to build user actions from other user actions.

The "interactive" buffer mutation functions, such as gtk_text_buffer_insert_interactive(), automatically call begin/end user action around the buffer operations they perform, so there's no need to add extra calls if you user action consists solely of a single call to one of those functions.

buffer : a GtkTextBuffer

gtk_text_buffer_end_user_action ()

void                gtk_text_buffer_end_user_action     (GtkTextBuffer *buffer);

Should be paired with a call to gtk_text_buffer_begin_user_action(). See that function for a full explanation.

buffer : a GtkTextBuffer

gtk_text_buffer_add_selection_clipboard ()

void                gtk_text_buffer_add_selection_clipboard
                                                        (GtkTextBuffer *buffer,
                                                         GtkClipboard *clipboard);

Adds clipboard to the list of clipboards in which the selection contents of buffer are available. In most cases, clipboard will be the GtkClipboard of type GDK_SELECTION_PRIMARY for a view of buffer.

buffer : | a GtkTextBuffer
clipboard : | a GtkClipboard

gtk_text_buffer_remove_selection_clipboard ()

void                gtk_text_buffer_remove_selection_clipboard
                                                        (GtkTextBuffer *buffer,
                                                         GtkClipboard *clipboard);

Removes a GtkClipboard added with gtk_text_buffer_add_selection_clipboard()

buffer : | a GtkTextBuffer
clipboard : | a GtkClipboard added to buffer by gtk_text_buffer_add_selection_clipboard().

enum GtkTextBufferTargetInfo

typedef enum
{
  GTK_TEXT_BUFFER_TARGET_INFO_BUFFER_CONTENTS = - 1,
  GTK_TEXT_BUFFER_TARGET_INFO_RICH_TEXT       = - 2,
  GTK_TEXT_BUFFER_TARGET_INFO_TEXT            = - 3
} GtkTextBufferTargetInfo;

GtkTextBufferDeserializeFunc ()

gboolean            (*GtkTextBufferDeserializeFunc)     (GtkTextBuffer *register_buffer,
                                                         GtkTextBuffer *content_buffer,
                                                         GtkTextIter *iter,
                                                         const guint8 *data,
                                                         gsize length,
                                                         gboolean create_tags,
                                                         gpointer user_data,
                                                         GError **error);

register_buffer :
content_buffer :
iter :
data :
length :
create_tags :
user_data :
error :
Returns :

gtk_text_buffer_deserialize ()

gboolean            gtk_text_buffer_deserialize         (GtkTextBuffer *register_buffer,
                                                         GtkTextBuffer *content_buffer,
                                                         GdkAtom format,
                                                         GtkTextIter *iter,
                                                         const guint8 *data,
                                                         gsize length,
                                                         GError **error);

This function deserializes rich text in format format and inserts it at iter.

formats to be used must be registered using gtk_text_buffer_register_deserialize_format() or gtk_text_buffer_register_deserialize_tagset() beforehand.

register_buffer : | the GtkTextBuffer format is registered with
content_buffer : | the GtkTextBuffer to deserialize into
format : | the rich text format to use for deserializing
iter : | insertion point for the deserialized text
data : | data to deserialize
length : | length of data
error : | return loaction for a GError
Returns : | TRUE on success, FALSE otherwise.

Since 2.10

gtk_text_buffer_deserialize_get_can_create_tags ()

gboolean            gtk_text_buffer_deserialize_get_can_create_tags
                                                        (GtkTextBuffer *buffer,
                                                         GdkAtom format);

This functions returns the value set with gtk_text_buffer_deserialize_set_can_create_tags()

buffer : | a GtkTextBuffer
format : | a GdkAtom representing a registered rich text format
Returns : | whether deserializing this format may create tags

Since 2.10

gtk_text_buffer_deserialize_set_can_create_tags ()

void                gtk_text_buffer_deserialize_set_can_create_tags
                                                        (GtkTextBuffer *buffer,
                                                         GdkAtom format,
                                                         gboolean can_create_tags);

Use this function to allow a rich text deserialization function to create new tags in the receiving buffer. Note that using this function is almost always a bad idea, because the rich text functions you register should know how to map the rich text format they handler to your text buffers set of tags.

The ability of creating new (arbitrary!) tags in the receiving buffer is meant for special rich text formats like the internal one that is registered using gtk_text_buffer_register_deserialize_tagset(), because that format is essentially a dump of the internal structure of the source buffer, including its tag names.

You should allow creation of tags only if you know what you are doing, e.g. if you defined a tagset name for your application suite's text buffers and you know that it's fine to receive new tags from these buffers, because you know that your application can handle the newly created tags.

buffer : | a GtkTextBuffer
format : | a GdkAtom representing a registered rich text format
can_create_tags : | whether deserializing this format may create tags

Since 2.10

gtk_text_buffer_get_copy_target_list ()

GtkTargetList*      gtk_text_buffer_get_copy_target_list
                                                        (GtkTextBuffer *buffer);

This function returns the list of targets this text buffer can provide for copying and as DND source. The targets in the list are added with info values from the GtkTextBufferTargetInfo enum, using gtk_target_list_add_rich_text_targets() and gtk_target_list_add_text_targets()

buffer : | a GtkTextBuffer
Returns : | the GtkTargetList

Since 2.10

gtk_text_buffer_get_deserialize_formats ()

GdkAtom*            gtk_text_buffer_get_deserialize_formats
                                                        (GtkTextBuffer *buffer,
                                                         gint *n_formats);

This function returns the rich text deserialize formats registered with buffer using gtk_text_buffer_register_deserialize_format() or gtk_text_buffer_register_deserialize_tagset()

buffer : | a GtkTextBuffer
n_formats : | return location for the number of formats
Returns : | an array of GdkAtoms representing the registered formats.

Since 2.10

gtk_text_buffer_get_paste_target_list ()

GtkTargetList*      gtk_text_buffer_get_paste_target_list
                                                        (GtkTextBuffer *buffer);

This function returns the list of targets this text buffer supports for pasting and as DND destination. The targets in the list are added with info values from the GtkTextBufferTargetInfo enum, using gtk_target_list_add_rich_text_targets() and gtk_target_list_add_text_targets()

buffer : | a GtkTextBuffer
Returns : | the GtkTargetList

Since 2.10

gtk_text_buffer_get_serialize_formats ()

GdkAtom*            gtk_text_buffer_get_serialize_formats
                                                        (GtkTextBuffer *buffer,
                                                         gint *n_formats);

This function returns the rich text serialize formats registered with buffer using gtk_text_buffer_register_serialize_format() or gtk_text_buffer_register_serialize_tagset()

buffer : | a GtkTextBuffer
n_formats : | return location for the number of formats
Returns : | an array of GdkAtoms representing the registered formats.

Since 2.10

gtk_text_buffer_register_deserialize_format ()

GdkAtom             gtk_text_buffer_register_deserialize_format
                                                        (GtkTextBuffer *buffer,
                                                         const gchar *mime_type,
                                                         GtkTextBufferDeserializeFunc function,
                                                         gpointer user_data,
                                                         GDestroyNotify user_data_destroy);

This function registers a rich text deserialization function along with its mime_type with the passed buffer.

buffer : | a GtkTextBuffer
mime_type : | the format's mime-type
function : | the deserialize function to register
user_data : | function's user_data
user_data_destroy : | a function to call when user_data is no longer needed
Returns : | the GdkAtom that corresponds to the newly registered format's mime-type.

Since 2.10

gtk_text_buffer_register_deserialize_tagset ()

GdkAtom             gtk_text_buffer_register_deserialize_tagset
                                                        (GtkTextBuffer *buffer,
                                                         const gchar *tagset_name);

This function registers GTK+'s internal rich text serialization format with the passed buffer. See gtk_text_buffer_register_serialize_tagset() for details.

buffer : | a GtkTextBuffer
tagset_name : | an optional tagset name, on NULL
Returns : | the GdkAtom that corresponds to the newly registered format's mime-type.

Since 2.10

gtk_text_buffer_register_serialize_format ()

GdkAtom             gtk_text_buffer_register_serialize_format
                                                        (GtkTextBuffer *buffer,
                                                         const gchar *mime_type,
                                                         GtkTextBufferSerializeFunc function,
                                                         gpointer user_data,
                                                         GDestroyNotify user_data_destroy);

This function registers a rich text serialization function along with its mime_type with the passed buffer.

buffer : | a GtkTextBuffer
mime_type : | the format's mime-type
function : | the serialize function to register
user_data : | function's user_data
user_data_destroy : | a function to call when user_data is no longer needed
Returns : | the GdkAtom that corresponds to the newly registered format's mime-type.

Since 2.10

gtk_text_buffer_register_serialize_tagset ()

GdkAtom             gtk_text_buffer_register_serialize_tagset
                                                        (GtkTextBuffer *buffer,
                                                         const gchar *tagset_name);

This function registers GTK+'s internal rich text serialization format with the passed buffer. The internal format does not comply to any standard rich text format and only works between GtkTextBuffer instances. It is capable of serializing all of a text buffer's tags and embedded pixbufs.

This function is just a wrapper around gtk_text_buffer_register_serialize_format(). The mime_type used for registering is "application/x-gtk-text-buffer-rich-text", or "application/x-gtk-text-buffer-rich-text;format=tagset_name" if a tagset_name was passed.

The tagset_name can be used to restrict the transfer of rich text to buffers with compatible sets of tags, in order to avoid unknown tags from being pasted. It is probably the common case to pass an identifier != NULL here, since the NULL tagset requires the receiving buffer to deal with with pasting of arbitrary tags.

buffer : | a GtkTextBuffer
tagset_name : | an optional tagset name, on NULL
Returns : | the GdkAtom that corresponds to the newly registered format's mime-type.

Since 2.10

GtkTextBufferSerializeFunc ()

guint8*             (*GtkTextBufferSerializeFunc)       (GtkTextBuffer *register_buffer,
                                                         GtkTextBuffer *content_buffer,
                                                         const GtkTextIter *start,
                                                         const GtkTextIter *end,
                                                         gsize *length,
                                                         gpointer user_data);

register_buffer :
content_buffer :
start :
end :
length :
user_data :
Returns :

gtk_text_buffer_serialize ()

guint8*             gtk_text_buffer_serialize           (GtkTextBuffer *register_buffer,
                                                         GtkTextBuffer *content_buffer,
                                                         GdkAtom format,
                                                         const GtkTextIter *start,
                                                         const GtkTextIter *end,
                                                         gsize *length);

This function serializes the portion of text between start and end in the rich text format represented by format.

formats to be used must be registered using gtk_text_buffer_register_serialize_format() or gtk_text_buffer_register_serialize_tagset() beforehand.

register_buffer : | the GtkTextBuffer format is registered with
content_buffer : | the GtkTextBuffer to serialize
format : | the rich text format to use for serializing
start : | start of block of text to serialize
end : | end of block of test to serialize
length : | return location for the length of the serialized data
Returns : | the serialized data, encoded as format

Since 2.10

gtk_text_buffer_unregister_deserialize_format ()

void                gtk_text_buffer_unregister_deserialize_format
                                                        (GtkTextBuffer *buffer,
                                                         GdkAtom format);

This function unregisters a rich text format that was previously registered using gtk_text_buffer_register_deserialize_format() or gtk_text_buffer_register_deserialize_tagset()

buffer : | a GtkTextBuffer
format : | a GdkAtom representing a registered rich text format.

Since 2.10

gtk_text_buffer_unregister_serialize_format ()

void                gtk_text_buffer_unregister_serialize_format
                                                        (GtkTextBuffer *buffer,
                                                         GdkAtom format);

This function unregisters a rich text format that was previously registered using gtk_text_buffer_register_serialize_format() or gtk_text_buffer_register_serialize_tagset()

buffer : | a GtkTextBuffer
format : | a GdkAtom representing a registered rich text format.

Since 2.10

Property Details

The "copy-target-list" property

  "copy-target-list"         GtkTargetList         : Read

The list of targets this buffer supports for clipboard copying and as DND source.

Since 2.10

The "cursor-position" property

  "cursor-position"          gint                  : Read

The position of the insert mark (as offset from the beginning of the buffer). It is useful for getting notified when the cursor moves.

Allowed values: >= 0

Default value: 0

Since 2.10

The "has-selection" property

  "has-selection"            gboolean              : Read

Whether the buffer has some text currently selected.

Default value: FALSE

Since 2.10

The "paste-target-list" property

  "paste-target-list"        GtkTargetList         : Read

The list of targets this buffer supports for clipboard pasting and as DND destination.

Since 2.10

The "tag-table" property

  "tag-table"                GtkTextTagTable       : Read / Write / Construct Only

Text Tag Table.

The "text" property

  "text"                     gchararray            : Read / Write

The text content of the buffer. Without child widgets and images, see gtk_text_buffer_get_text() for more information.

Default value: ""

Since 2.8

Signal Details

The "apply-tag" signal

void                user_function                      (GtkTextBuffer *textbuffer,
                                                        GtkTextTag    *tag,
                                                        GtkTextIter   *start,
                                                        GtkTextIter   *end,
                                                        gpointer       user_data)       : Run Last

The apply_tag signal is emitted to apply a tag to a range of text in a GtkTextBuffer. Applying actually occurs in the default handler.

Note that if your handler runs before the default handler it must not invalidate the start and end iters (or has to revalidate them).

See also:
gtk_text_buffer_apply_tag(),
gtk_text_buffer_insert_with_tags(),
gtk_text_buffer_insert_range().

textbuffer : | the object which received the signal
tag : | the applied tag
start : | the start of the range the tag is applied to
end : | the end of the range the tag is applied to
user_data : | user data set when the signal handler was connected.

The "begin-user-action" signal

void                user_function                      (GtkTextBuffer *textbuffer,
                                                        gpointer       user_data)       : Run Last

The begin_user_action signal is emitted at the beginning of a single user-visible operation on a GtkTextBuffer.

See also:
gtk_text_buffer_begin_user_action(),
gtk_text_buffer_insert_interactive(),
gtk_text_buffer_insert_range_interactive(),
gtk_text_buffer_delete_interactive(),
gtk_text_buffer_backspace(),
gtk_text_buffer_delete_selection().

textbuffer : | the object which received the signal
user_data : | user data set when the signal handler was connected.

The "changed" signal

void                user_function                      (GtkTextBuffer *textbuffer,
                                                        gpointer       user_data)       : Run Last

The changed signal is emitted when the content of a GtkTextBuffer has changed.

textbuffer : | the object which received the signal
user_data : | user data set when the signal handler was connected.

The "delete-range" signal

void                user_function                      (GtkTextBuffer *textbuffer,
                                                        GtkTextIter   *start,
                                                        GtkTextIter   *end,
                                                        gpointer       user_data)       : Run Last

The delete_range signal is emitted to delete a range from a GtkTextBuffer.

Note that if your handler runs before the default handler it must not invalidate the start and end iters (or has to revalidate them). The default signal handler revalidates the start and end iters to both point point to the location where text was deleted. Handlers which run after the default handler (see g_signal_connect_after()) do not have access to the deleted text.

See also: gtk_text_buffer_delete().

textbuffer : | the object which received the signal
start : | the start of the range to be deleted
end : | the end of the range to be deleted
user_data : | user data set when the signal handler was connected.

The "end-user-action" signal

void                user_function                      (GtkTextBuffer *textbuffer,
                                                        gpointer       user_data)       : Run Last

The end_user_action signal is emitted at the end of a single user-visible operation GtkTextBuffer.

See also:
gtk_text_buffer_end_user_action(),
gtk_text_buffer_insert_interactive(),
gtk_text_buffer_insert_range_interactive(),
gtk_text_buffer_delete_interactive(),
gtk_text_buffer_backspace(),
gtk_text_buffer_delete_selection(),
gtk_text_buffer_backspace().

textbuffer : | the object which received the signal
user_data : | user data set when the signal handler was connected.

The "insert-child-anchor" signal

void                user_function                      (GtkTextBuffer      *textbuffer,
                                                        GtkTextIter        *location,
                                                        GtkTextChildAnchor *anchor,
                                                        gpointer            user_data)       : Run Last

The insert_child_anchor signal is emitted to insert a GtkTextChildAnchor in a GtkTextBuffer. Insertion actually occurs in the default handler.

Note that if your handler runs before the default handler it must not invalidate the location iter (or has to revalidate it). The default signal handler revalidates it to be placed after the inserted anchor.

See also: gtk_text_buffer_insert_child_anchor().

textbuffer : | the object which received the signal
location : | position to insert anchor in textbuffer
anchor : | the GtkTextChildAnchor to be inserted
user_data : | user data set when the signal handler was connected.

The "insert-pixbuf" signal

void                user_function                      (GtkTextBuffer *textbuffer,
                                                        GtkTextIter   *location,
                                                        GdkPixbuf     *pixbuf,
                                                        gpointer       user_data)       : Run Last

The insert_pixbuf signal is emitted to insert a GdkPixbuf in a GtkTextBuffer. Insertion actually occurs in the default handler.

Note that if your handler runs before the default handler it must not invalidate the location iter (or has to revalidate it). The default signal handler revalidates it to be placed after the inserted pixbuf.

See also: gtk_text_buffer_insert_pixbuf().

textbuffer : | the object which received the signal
location : | position to insert pixbuf in textbuffer
pixbuf : | the GdkPixbuf to be inserted
user_data : | user data set when the signal handler was connected.

The "insert-text" signal

void                user_function                      (GtkTextBuffer *textbuffer,
                                                        GtkTextIter   *location,
                                                        gchar         *text,
                                                        gint           len,
                                                        gpointer       user_data)       : Run Last

The insert_text signal is emitted to insert text in a GtkTextBuffer. Insertion actually occurs in the default handler.

Note that if your handler runs before the default handler it must not invalidate the location iter (or has to revalidate it). The default signal handler revalidates it to point to the end of the inserted text.

See also: gtk_text_buffer_insert(), gtk_text_buffer_insert_range().

textbuffer : | the object which received the signal
location : | position to insert text in textbuffer
text : | the UTF-8 text to be inserted
len : | length of the inserted text in bytes
user_data : | user data set when the signal handler was connected.

The "mark-deleted" signal

void                user_function                      (GtkTextBuffer *textbuffer,
                                                        GtkTextMark   *mark,
                                                        gpointer       user_data)       : Run Last

The mark_deleted signal is emitted as notification after a GtkTextMark is deleted.

See also: gtk_text_buffer_delete_mark().

textbuffer : | the object which received the signal
mark : | The mark that was deleted
user_data : | user data set when the signal handler was connected.

The "mark-set" signal

void                user_function                      (GtkTextBuffer *textbuffer,
                                                        GtkTextIter   *location,
                                                        GtkTextMark   *mark,
                                                        gpointer       user_data)       : Run Last

The mark_set signal is emitted as notification after a GtkTextMark is set.

See also: gtk_text_buffer_create_mark(), gtk_text_buffer_move_mark().

textbuffer : | the object which received the signal
location : | The location of mark in textbuffer
mark : | The mark that is set
user_data : | user data set when the signal handler was connected.

The "modified-changed" signal

void                user_function                      (GtkTextBuffer *textbuffer,
                                                        gpointer       user_data)       : Run Last

The modified_changed signal is emitted when the modified bit of a GtkTextBuffer flips.

See also: gtk_text_buffer_set_modified().

textbuffer : | the object which received the signal
user_data : | user data set when the signal handler was connected.

The "remove-tag" signal

void                user_function                      (GtkTextBuffer *textbuffer,
                                                        GtkTextTag    *tag,
                                                        GtkTextIter   *start,
                                                        GtkTextIter   *end,
                                                        gpointer       user_data)       : Run Last

The remove_tag signal is emitted to remove all occurrences of tag from a range of text in a GtkTextBuffer. Removal actually occurs in the default handler.

Note that if your handler runs before the default handler it must not invalidate the start and end iters (or has to revalidate them).

See also: gtk_text_buffer_remove_tag().

textbuffer : | the object which received the signal
tag : | the tag to be removed
start : | the start of the range the tag is removed from
end : | the end of the range the tag is removed from
user_data : | user data set when the signal handler was connected.

See Also

GtkTextView, GtkTextIter, GtkTextMark


GtkTextMark

GtkTextMark — A position in the buffer preserved across buffer modifications

Synopsis

#include <gtk/gtk.h>

                    GtkTextMark;
void                gtk_text_mark_set_visible           (GtkTextMark *mark,
                                                         gboolean setting);
gboolean            gtk_text_mark_get_visible           (GtkTextMark *mark);
gboolean            gtk_text_mark_get_deleted           (GtkTextMark *mark);
const gchar*        gtk_text_mark_get_name              (GtkTextMark *mark);
GtkTextBuffer*      gtk_text_mark_get_buffer            (GtkTextMark *mark);
gboolean            gtk_text_mark_get_left_gravity      (GtkTextMark *mark);

Object Hierarchy

  GObject
   +----GtkTextMark

Description

You may wish to begin by reading the text widget conceptual overview which gives an overview of all the objects and data types related to the text widget and how they work together.

A GtkTextMark is like a bookmark in a text buffer; it preserves a position in the text. You can convert the mark to an iterator using gtk_text_buffer_get_iter_at_mark(). Unlike iterators, marks remain valid across buffer mutations, because their behavior is defined when text is inserted or deleted. When text containing a mark is deleted, the mark remains in the position originally occupied by the deleted text. When text is inserted at a mark, a mark with left gravity will be moved to the beginning of the newly-inserted text, and a mark with right gravity will be moved to the end. [3]

Marks are reference counted, but the reference count only controls the validity of the memory; marks can be deleted from the buffer at any time with gtk_text_buffer_delete_mark(). Once deleted from the buffer, a mark is essentially useless.

Marks optionally have names; these can be convenient to avoid passing the GtkTextMark object around.

Marks are typically created using the gtk_text_buffer_create_mark() function.

Details

GtkTextMark

typedef struct _GtkTextMark GtkTextMark;

gtk_text_mark_set_visible ()

void                gtk_text_mark_set_visible           (GtkTextMark *mark,
                                                         gboolean setting);

Sets the visibility of mark; the insertion point is normally visible, i.e. you can see it as a vertical bar. Also, the text widget uses a visible mark to indicate where a drop will occur when dragging-and-dropping text. Most other marks are not visible. Marks are not visible by default.

mark : | a GtkTextMark
setting : | visibility of mark

gtk_text_mark_get_visible ()

gboolean            gtk_text_mark_get_visible           (GtkTextMark *mark);

Returns TRUE if the mark is visible (i.e. a cursor is displayed for it)

mark : | a GtkTextMark
Returns : | TRUE if visible

gtk_text_mark_get_deleted ()

gboolean            gtk_text_mark_get_deleted           (GtkTextMark *mark);

Returns TRUE if the mark has been removed from its buffer with gtk_text_buffer_delete_mark(). Marks can't be used once deleted.

mark : | a GtkTextMark
Returns : | whether the mark is deleted

gtk_text_mark_get_name ()

const gchar*        gtk_text_mark_get_name              (GtkTextMark *mark);

Returns the mark name; returns NULL for anonymous marks.

mark : | a GtkTextMark
Returns : | mark name

gtk_text_mark_get_buffer ()

GtkTextBuffer*      gtk_text_mark_get_buffer            (GtkTextMark *mark);

Gets the buffer this mark is located inside, or NULL if the mark is deleted.

mark : | a GtkTextMark
Returns : | the mark's GtkTextBuffer

gtk_text_mark_get_left_gravity ()

gboolean            gtk_text_mark_get_left_gravity      (GtkTextMark *mark);

Determines whether the mark has left gravity.

mark : | a GtkTextMark
Returns : | TRUE if the mark has left gravity, FALSE otherwise

[3] "left" and "right" here refer to logical direction (left is the toward the start of the buffer); in some languages such as Hebrew the logically-leftmost text is not actually on the left when displayed.


GtkTextTag

GtkTextTag — A tag that can be applied to text in a GtkTextBuffer

Synopsis

#include <gtk/gtk.h>

                    GtkTextTag;
enum                GtkWrapMode;
                    GtkTextAttributes;
GtkTextTag*         gtk_text_tag_new                    (const gchar *name);
gint                gtk_text_tag_get_priority           (GtkTextTag *tag);
void                gtk_text_tag_set_priority           (GtkTextTag *tag,
                                                         gint priority);
gboolean            gtk_text_tag_event                  (GtkTextTag *tag,
                                                         GObject *event_object,
                                                         GdkEvent *event,
                                                         const GtkTextIter *iter);
                    GtkTextAppearance;
GtkTextAttributes*  gtk_text_attributes_new             (void);
GtkTextAttributes*  gtk_text_attributes_copy            (GtkTextAttributes *src);
void                gtk_text_attributes_copy_values     (GtkTextAttributes *src,
                                                         GtkTextAttributes *dest);
void                gtk_text_attributes_unref           (GtkTextAttributes *values);
GtkTextAttributes*  gtk_text_attributes_ref             (GtkTextAttributes *values);

Object Hierarchy

  GObject
   +----GtkTextTag

Properties

  "background"               gchararray            : Write
  "background-full-height"   gboolean              : Read / Write
  "background-full-height-set" gboolean              : Read / Write
  "background-gdk"           GdkColor              : Read / Write
  "background-set"           gboolean              : Read / Write
  "background-stipple"       GdkPixmap             : Read / Write
  "background-stipple-set"   gboolean              : Read / Write
  "direction"                GtkTextDirection      : Read / Write
  "editable"                 gboolean              : Read / Write
  "editable-set"             gboolean              : Read / Write
  "family"                   gchararray            : Read / Write
  "family-set"               gboolean              : Read / Write
  "font"                     gchararray            : Read / Write
  "font-desc"                PangoFontDescription  : Read / Write
  "foreground"               gchararray            : Write
  "foreground-gdk"           GdkColor              : Read / Write
  "foreground-set"           gboolean              : Read / Write
  "foreground-stipple"       GdkPixmap             : Read / Write
  "foreground-stipple-set"   gboolean              : Read / Write
  "indent"                   gint                  : Read / Write
  "indent-set"               gboolean              : Read / Write
  "invisible"                gboolean              : Read / Write
  "invisible-set"            gboolean              : Read / Write
  "justification"            GtkJustification      : Read / Write
  "justification-set"        gboolean              : Read / Write
  "language"                 gchararray            : Read / Write
  "language-set"             gboolean              : Read / Write
  "left-margin"              gint                  : Read / Write
  "left-margin-set"          gboolean              : Read / Write
  "name"                     gchararray            : Read / Write / Construct Only
  "paragraph-background"     gchararray            : Write
  "paragraph-background-gdk" GdkColor              : Read / Write
  "paragraph-background-set" gboolean              : Read / Write
  "pixels-above-lines"       gint                  : Read / Write
  "pixels-above-lines-set"   gboolean              : Read / Write
  "pixels-below-lines"       gint                  : Read / Write
  "pixels-below-lines-set"   gboolean              : Read / Write
  "pixels-inside-wrap"       gint                  : Read / Write
  "pixels-inside-wrap-set"   gboolean              : Read / Write
  "right-margin"             gint                  : Read / Write
  "right-margin-set"         gboolean              : Read / Write
  "rise"                     gint                  : Read / Write
  "rise-set"                 gboolean              : Read / Write
  "scale"                    gdouble               : Read / Write
  "scale-set"                gboolean              : Read / Write
  "size"                     gint                  : Read / Write
  "size-points"              gdouble               : Read / Write
  "size-set"                 gboolean              : Read / Write
  "stretch"                  PangoStretch          : Read / Write
  "stretch-set"              gboolean              : Read / Write
  "strikethrough"            gboolean              : Read / Write
  "strikethrough-set"        gboolean              : Read / Write
  "style"                    PangoStyle            : Read / Write
  "style-set"                gboolean              : Read / Write
  "tabs"                     PangoTabArray         : Read / Write
  "tabs-set"                 gboolean              : Read / Write
  "underline"                PangoUnderline        : Read / Write
  "underline-set"            gboolean              : Read / Write
  "variant"                  PangoVariant          : Read / Write
  "variant-set"              gboolean              : Read / Write
  "weight"                   gint                  : Read / Write
  "weight-set"               gboolean              : Read / Write
  "wrap-mode"                GtkWrapMode           : Read / Write
  "wrap-mode-set"            gboolean              : Read / Write

Signals

  "event"                                          : Run Last

Description

You may wish to begin by reading the text widget conceptual overview which gives an overview of all the objects and data types related to the text widget and how they work together.

Tags should be in the GtkTextTagTable for a given GtkTextBuffer before using them with that buffer.

gtk_text_buffer_create_tag() is the best way to create tags. See gtk-demo for numerous examples.

The "invisible" property was not implemented for GTK+ 2.0; it's planned to be implemented in future releases.

Details

GtkTextTag

typedef struct _GtkTextTag GtkTextTag;

enum GtkWrapMode

typedef enum
{
  GTK_WRAP_NONE,
  GTK_WRAP_CHAR,
  GTK_WRAP_WORD,
  GTK_WRAP_WORD_CHAR
} GtkWrapMode;

Describes a type of line wrapping.

GTK_WRAP_NONE | do not wrap lines; just make the text area wider
GTK_WRAP_CHAR | wrap text, breaking lines anywhere the cursor can appear (between characters, usually - if you want to be technical, between graphemes, see pango_get_log_attrs())
GTK_WRAP_WORD | wrap text, breaking lines in between words
GTK_WRAP_WORD_CHAR | wrap text, breaking lines in between words, or if that is not enough, also between graphemes.

GtkTextAttributes

typedef struct {
  GtkTextAppearance appearance;

  GtkJustification justification;
  GtkTextDirection direction;

  /* Individual chunks of this can be set/unset as a group */
  PangoFontDescription *font;

  gdouble font_scale;

  gint left_margin;

  gint indent;

  gint right_margin;

  gint pixels_above_lines;

  gint pixels_below_lines;

  gint pixels_inside_wrap;

  PangoTabArray *tabs;

  GtkWrapMode wrap_mode;        /* How to handle wrap-around for this tag.
                                 * Must be GTK_WRAPMODE_CHAR,
                                 * GTK_WRAPMODE_NONE, GTK_WRAPMODE_WORD
                                 */

  PangoLanguage *language;

  /* hide the text  */
  guint invisible : 1;

  /* Background is fit to full line height rather than
   * baseline +/- ascent/descent (font height)
   */
  guint bg_full_height : 1;

  /* can edit this text */
  guint editable : 1;

  /* colors are allocated etc. */
  guint realized : 1;
} GtkTextAttributes;

Using GtkTextAttributes directly should rarely be necessary. It's primarily useful with gtk_text_iter_get_attributes(). As with most GTK+ structs, the fields in this struct should only be read, never modified directly.

GtkTextAppearance appearance; | pointer to sub-struct containing certain attributes
GtkJustification justification; |
GtkTextDirection direction; |
PangoFontDescription *font; |
gdouble font_scale; |
gint left_margin; |
gint indent; |
gint right_margin; |
gint pixels_above_lines; |
gint pixels_below_lines; |
gint pixels_inside_wrap; |
PangoTabArray *tabs; |
GtkWrapMode wrap_mode; |
PangoLanguage *language; |
guint invisible : 1; |
guint bg_full_height : 1; |
guint editable : 1; |
guint realized : 1; |

gtk_text_tag_new ()

GtkTextTag*         gtk_text_tag_new                    (const gchar *name);

Creates a GtkTextTag. Configure the tag using object arguments, i.e. using g_object_set().

name : | tag name, or NULL
Returns : | a new GtkTextTag

gtk_text_tag_get_priority ()

gint                gtk_text_tag_get_priority           (GtkTextTag *tag);

Get the tag priority.

tag : | a GtkTextTag
Returns : | The tag's priority.

gtk_text_tag_set_priority ()

void                gtk_text_tag_set_priority           (GtkTextTag *tag,
                                                         gint priority);

Sets the priority of a GtkTextTag. Valid priorities are start at 0 and go to one less than gtk_text_tag_table_get_size(). Each tag in a table has a unique priority; setting the priority of one tag shifts the priorities of all the other tags in the table to maintain a unique priority for each tag. Higher priority tags "win" if two tags both set the same text attribute. When adding a tag to a tag table, it will be assigned the highest priority in the table by default; so normally the precedence of a set of tags is the order in which they were added to the table, or created with gtk_text_buffer_create_tag(), which adds the tag to the buffer's table automatically.

tag : | a GtkTextTag
priority : | the new priority

gtk_text_tag_event ()

gboolean            gtk_text_tag_event                  (GtkTextTag *tag,
                                                         GObject *event_object,
                                                         GdkEvent *event,
                                                         const GtkTextIter *iter);

Emits the "event" signal on the GtkTextTag.

tag : | a GtkTextTag
event_object : | object that received the event, such as a widget
event : | the event
iter : | location where the event was received
Returns : | result of signal emission (whether the event was handled)

GtkTextAppearance

typedef struct {
  GdkColor bg_color;
  GdkColor fg_color;
  GdkBitmap *bg_stipple;
  GdkBitmap *fg_stipple;

  /* super/subscript rise, can be negative */
  gint rise;

  guint underline : 4;          /* PangoUnderline */
  guint strikethrough : 1;

  /* Whether to use background-related values; this is irrelevant for
   * the values struct when in a tag, but is used for the composite
   * values struct; it's true if any of the tags being composited
   * had background stuff set.
   */
  guint draw_bg : 1;

  /* These are only used when we are actually laying out and rendering
   * a paragraph; not when a GtkTextAppearance is part of a
   * GtkTextAttributes.
   */
  guint inside_selection : 1;
  guint is_text : 1;
} GtkTextAppearance;

gtk_text_attributes_new ()

GtkTextAttributes*  gtk_text_attributes_new             (void);

Creates a GtkTextAttributes, which describes a set of properties on some text.

Returns : a new GtkTextAttributes

gtk_text_attributes_copy ()

GtkTextAttributes*  gtk_text_attributes_copy            (GtkTextAttributes *src);

Copies src and returns a new GtkTextAttributes.

src : | a GtkTextAttributes to be copied
Returns : | a copy of src

gtk_text_attributes_copy_values ()

void                gtk_text_attributes_copy_values     (GtkTextAttributes *src,
                                                         GtkTextAttributes *dest);

Copies the values from src to dest so that dest has the same values as src. Frees existing values in dest.

src : | a GtkTextAttributes
dest : | another GtkTextAttributes

gtk_text_attributes_unref ()

void                gtk_text_attributes_unref           (GtkTextAttributes *values);

Decrements the reference count on values, freeing the structure if the reference count reaches 0.

values : a GtkTextAttributes

gtk_text_attributes_ref ()

GtkTextAttributes*  gtk_text_attributes_ref             (GtkTextAttributes *values);

Increments the reference count on values.

values : | a GtkTextAttributes
Returns : | the GtkTextAttributes that were passed in

Property Details

The "background" property

  "background"               gchararray            : Write

Background color as a string.

Default value: NULL

The "background-full-height" property

  "background-full-height"   gboolean              : Read / Write

Whether the background color fills the entire line height or only the height of the tagged characters.

Default value: FALSE

The "background-full-height-set" property

  "background-full-height-set" gboolean              : Read / Write

Whether this tag affects background height.

Default value: FALSE

The "background-gdk" property

  "background-gdk"           GdkColor              : Read / Write

Background color as a (possibly unallocated) GdkColor.

The "background-set" property

  "background-set"           gboolean              : Read / Write

Whether this tag affects the background color.

Default value: FALSE

The "background-stipple" property

  "background-stipple"       GdkPixmap             : Read / Write

Bitmap to use as a mask when drawing the text background.

The "background-stipple-set" property

  "background-stipple-set"   gboolean              : Read / Write

Whether this tag affects the background stipple.

Default value: FALSE

The "direction" property

  "direction"                GtkTextDirection      : Read / Write

Text direction, e.g. right-to-left or left-to-right.

Default value: GTK_TEXT_DIR_NONE

The "editable" property

  "editable"                 gboolean              : Read / Write

Whether the text can be modified by the user.

Default value: TRUE

The "editable-set" property

  "editable-set"             gboolean              : Read / Write

Whether this tag affects text editability.

Default value: FALSE

The "family" property

  "family"                   gchararray            : Read / Write

Name of the font family, e.g. Sans, Helvetica, Times, Monospace.

Default value: NULL

The "family-set" property

  "family-set"               gboolean              : Read / Write

Whether this tag affects the font family.

Default value: FALSE

The "font" property

  "font"                     gchararray            : Read / Write

Font description as string, e.g. \"Sans Italic 12\".

Note that the initial value of this property depends on the internals of PangoFontDescription.

Default value: NULL

The "font-desc" property

  "font-desc"                PangoFontDescription  : Read / Write

Font description as a PangoFontDescription struct.

The "foreground" property

  "foreground"               gchararray            : Write

Foreground color as a string.

Default value: NULL

The "foreground-gdk" property

  "foreground-gdk"           GdkColor              : Read / Write

Foreground color as a (possibly unallocated) GdkColor.

The "foreground-set" property

  "foreground-set"           gboolean              : Read / Write

Whether this tag affects the foreground color.

Default value: FALSE

The "foreground-stipple" property

  "foreground-stipple"       GdkPixmap             : Read / Write

Bitmap to use as a mask when drawing the text foreground.

The "foreground-stipple-set" property

  "foreground-stipple-set"   gboolean              : Read / Write

Whether this tag affects the foreground stipple.

Default value: FALSE

The "indent" property

  "indent"                   gint                  : Read / Write

Amount to indent the paragraph, in pixels.

Default value: 0

The "indent-set" property

  "indent-set"               gboolean              : Read / Write

Whether this tag affects indentation.

Default value: FALSE

The "invisible" property

  "invisible"                gboolean              : Read / Write

Whether this text is hidden.

Note that there may still be problems with the support for invisible text, in particular when navigating programmatically inside a buffer containing invisible segments.

Default value: FALSE

Since 2.8

The "invisible-set" property

  "invisible-set"            gboolean              : Read / Write

Whether this tag affects text visibility.

Default value: FALSE

The "justification" property

  "justification"            GtkJustification      : Read / Write

Left, right, or center justification.

Default value: GTK_JUSTIFY_LEFT

The "justification-set" property

  "justification-set"        gboolean              : Read / Write

Whether this tag affects paragraph justification.

Default value: FALSE

The "language" property

  "language"                 gchararray            : Read / Write

The language this text is in, as an ISO code. Pango can use this as a hint when rendering the text. If not set, an appropriate default will be used.

Note that the initial value of this property depends on the current locale, see also gtk_get_default_language().

Default value: NULL

The "language-set" property

  "language-set"             gboolean              : Read / Write

Whether this tag affects the language the text is rendered as.

Default value: FALSE

The "left-margin" property

  "left-margin"              gint                  : Read / Write

Width of the left margin in pixels.

Allowed values: >= 0

Default value: 0

The "left-margin-set" property

  "left-margin-set"          gboolean              : Read / Write

Whether this tag affects the left margin.

Default value: FALSE

The "name" property

  "name"                     gchararray            : Read / Write / Construct Only

Name used to refer to the text tag. NULL for anonymous tags.

Default value: NULL

The "paragraph-background" property

  "paragraph-background"     gchararray            : Write

The paragraph background color as a string.

Default value: NULL

Since 2.8

The "paragraph-background-gdk" property

  "paragraph-background-gdk" GdkColor              : Read / Write

The paragraph background color as a as a (possibly unallocated) GdkColor.

Since 2.8

The "paragraph-background-set" property

  "paragraph-background-set" gboolean              : Read / Write

Whether this tag affects the paragraph background color.

Default value: FALSE

The "pixels-above-lines" property

  "pixels-above-lines"       gint                  : Read / Write

Pixels of blank space above paragraphs.

Allowed values: >= 0

Default value: 0

The "pixels-above-lines-set" property

  "pixels-above-lines-set"   gboolean              : Read / Write

Whether this tag affects the number of pixels above lines.

Default value: FALSE

The "pixels-below-lines" property

  "pixels-below-lines"       gint                  : Read / Write

Pixels of blank space below paragraphs.

Allowed values: >= 0

Default value: 0

The "pixels-below-lines-set" property

  "pixels-below-lines-set"   gboolean              : Read / Write

Whether this tag affects the number of pixels above lines.

Default value: FALSE

The "pixels-inside-wrap" property

  "pixels-inside-wrap"       gint                  : Read / Write

Pixels of blank space between wrapped lines in a paragraph.

Allowed values: >= 0

Default value: 0

The "pixels-inside-wrap-set" property

  "pixels-inside-wrap-set"   gboolean              : Read / Write

Whether this tag affects the number of pixels between wrapped lines.

Default value: FALSE

The "right-margin" property

  "right-margin"             gint                  : Read / Write

Width of the right margin in pixels.

Allowed values: >= 0

Default value: 0

The "right-margin-set" property

  "right-margin-set"         gboolean              : Read / Write

Whether this tag affects the right margin.

Default value: FALSE

The "rise" property

  "rise"                     gint                  : Read / Write

Offset of text above the baseline (below the baseline if rise is negative) in Pango units.

Default value: 0

The "rise-set" property

  "rise-set"                 gboolean              : Read / Write

Whether this tag affects the rise.

Default value: FALSE

The "scale" property

  "scale"                    gdouble               : Read / Write

Font size as a scale factor relative to the default font size. This properly adapts to theme changes etc. so is recommended. Pango predefines some scales such as PANGO_SCALE_X_LARGE.

Allowed values: >= 0

Default value: 1

The "scale-set" property

  "scale-set"                gboolean              : Read / Write

Whether this tag scales the font size by a factor.

Default value: FALSE

The "size" property

  "size"                     gint                  : Read / Write

Font size in Pango units.

Allowed values: >= 0

Default value: 0

The "size-points" property

  "size-points"              gdouble               : Read / Write

Font size in points.

Allowed values: >= 0

Default value: 0

The "size-set" property

  "size-set"                 gboolean              : Read / Write

Whether this tag affects the font size.

Default value: FALSE

The "stretch" property

  "stretch"                  PangoStretch          : Read / Write

Font stretch as a PangoStretch, e.g. PANGO_STRETCH_CONDENSED.

Default value: PANGO_STRETCH_NORMAL

The "stretch-set" property

  "stretch-set"              gboolean              : Read / Write

Whether this tag affects the font stretch.

Default value: FALSE

The "strikethrough" property

  "strikethrough"            gboolean              : Read / Write

Whether to strike through the text.

Default value: FALSE

The "strikethrough-set" property

  "strikethrough-set"        gboolean              : Read / Write

Whether this tag affects strikethrough.

Default value: FALSE

The "style" property

  "style"                    PangoStyle            : Read / Write

Font style as a PangoStyle, e.g. PANGO_STYLE_ITALIC.

Default value: PANGO_STYLE_NORMAL

The "style-set" property

  "style-set"                gboolean              : Read / Write

Whether this tag affects the font style.

Default value: FALSE

The "tabs" property

  "tabs"                     PangoTabArray         : Read / Write

Custom tabs for this text.

The "tabs-set" property

  "tabs-set"                 gboolean              : Read / Write

Whether this tag affects tabs.

Default value: FALSE

The "underline" property

  "underline"                PangoUnderline        : Read / Write

Style of underline for this text.

Default value: PANGO_UNDERLINE_NONE

The "underline-set" property

  "underline-set"            gboolean              : Read / Write

Whether this tag affects underlining.

Default value: FALSE

The "variant" property

  "variant"                  PangoVariant          : Read / Write

Font variant as a PangoVariant, e.g. PANGO_VARIANT_SMALL_CAPS.

Default value: PANGO_VARIANT_NORMAL

The "variant-set" property

  "variant-set"              gboolean              : Read / Write

Whether this tag affects the font variant.

Default value: FALSE

The "weight" property

  "weight"                   gint                  : Read / Write

Font weight as an integer, see predefined values in PangoWeight; for example, PANGO_WEIGHT_BOLD.

Allowed values: >= 0

Default value: 400

The "weight-set" property

  "weight-set"               gboolean              : Read / Write

Whether this tag affects the font weight.

Default value: FALSE

The "wrap-mode" property

  "wrap-mode"                GtkWrapMode           : Read / Write

Whether to wrap lines never, at word boundaries, or at character boundaries.

Default value: GTK_WRAP_NONE

The "wrap-mode-set" property

  "wrap-mode-set"            gboolean              : Read / Write

Whether this tag affects line wrap mode.

Default value: FALSE

Signal Details

The "event" signal

gboolean            user_function                      (GtkTextTag  *texttag,
                                                        GObject     *arg1,
                                                        GdkEvent    *event,
                                                        GtkTextIter *arg2,
                                                        gpointer     user_data)      : Run Last

texttag : | the object which received the signal.
arg1 : |
event : |
arg2 : |
user_data : | user data set when the signal handler was connected.
Returns : |


GtkTextTagTable

GtkTextTagTable — Collection of tags that can be used together

Synopsis

#include <gtk/gtk.h>

                    GtkTextTagTable;
void                (*GtkTextTagTableForeach)           (GtkTextTag *tag,
                                                         gpointer data);
GtkTextTagTable*    gtk_text_tag_table_new              (void);
void                gtk_text_tag_table_add              (GtkTextTagTable *table,
                                                         GtkTextTag *tag);
void                gtk_text_tag_table_remove           (GtkTextTagTable *table,
                                                         GtkTextTag *tag);
GtkTextTag*         gtk_text_tag_table_lookup           (GtkTextTagTable *table,
                                                         const gchar *name);
void                gtk_text_tag_table_foreach          (GtkTextTagTable *table,
                                                         GtkTextTagTableForeach func,
                                                         gpointer data);
gint                gtk_text_tag_table_get_size         (GtkTextTagTable *table);

Object Hierarchy

  GObject
   +----GtkTextTagTable

Signals

  "tag-added"                                      : Run Last
  "tag-changed"                                    : Run Last
  "tag-removed"                                    : Run Last

Description

You may wish to begin by reading the text widget conceptual overview which gives an overview of all the objects and data types related to the text widget and how they work together.

Details

GtkTextTagTable

typedef struct _GtkTextTagTable GtkTextTagTable;

GtkTextTagTableForeach ()

void                (*GtkTextTagTableForeach)           (GtkTextTag *tag,
                                                         gpointer data);

tag :
data :

gtk_text_tag_table_new ()

GtkTextTagTable*    gtk_text_tag_table_new              (void);

Creates a new GtkTextTagTable. The table contains no tags by default.

Returns : a new GtkTextTagTable

gtk_text_tag_table_add ()

void                gtk_text_tag_table_add              (GtkTextTagTable *table,
                                                         GtkTextTag *tag);

Add a tag to the table. The tag is assigned the highest priority in the table.

tag must not be in a tag table already, and may not have the same name as an already-added tag.

table : | a GtkTextTagTable
tag : | a GtkTextTag

gtk_text_tag_table_remove ()

void                gtk_text_tag_table_remove           (GtkTextTagTable *table,
                                                         GtkTextTag *tag);

Remove a tag from the table. This will remove the table's reference to the tag, so be careful - the tag will end up destroyed if you don't have a reference to it.

table : | a GtkTextTagTable
tag : | a GtkTextTag

gtk_text_tag_table_lookup ()

GtkTextTag*         gtk_text_tag_table_lookup           (GtkTextTagTable *table,
                                                         const gchar *name);

Look up a named tag.

table : | a GtkTextTagTable
name : | name of a tag
Returns : | The tag, or NULL if none by that name is in the table.

gtk_text_tag_table_foreach ()

void                gtk_text_tag_table_foreach          (GtkTextTagTable *table,
                                                         GtkTextTagTableForeach func,
                                                         gpointer data);

Calls func on each tag in table, with user data data. Note that the table may not be modified while iterating over it (you can't add/remove tags).

table : | a GtkTextTagTable
func : | a function to call on each tag
data : | user data

gtk_text_tag_table_get_size ()

gint                gtk_text_tag_table_get_size         (GtkTextTagTable *table);

Returns the size of the table (number of tags)

table : | a GtkTextTagTable
Returns : | number of tags in table

Signal Details

The "tag-added" signal

void                user_function                      (GtkTextTagTable *texttagtable,
                                                        GtkTextTag      *arg1,
                                                        gpointer         user_data)         : Run Last

texttagtable : | the object which received the signal.
arg1 : |
user_data : | user data set when the signal handler was connected.

The "tag-changed" signal

void                user_function                      (GtkTextTagTable *texttagtable,
                                                        GtkTextTag      *arg1,
                                                        gboolean         arg2,
                                                        gpointer         user_data)         : Run Last

texttagtable : | the object which received the signal.
arg1 : |
arg2 : |
user_data : | user data set when the signal handler was connected.

The "tag-removed" signal

void                user_function                      (GtkTextTagTable *texttagtable,
                                                        GtkTextTag      *arg1,
                                                        gpointer         user_data)         : Run Last

texttagtable : | the object which received the signal.
arg1 : |
user_data : | user data set when the signal handler was connected.


GtkTextView

GtkTextView — Widget that displays a GtkTextBuffer

Synopsis

#include <gtk/gtk.h>

                    GtkTextView;
enum                GtkTextWindowType;
GtkWidget*          gtk_text_view_new                   (void);
GtkWidget*          gtk_text_view_new_with_buffer       (GtkTextBuffer *buffer);
void                gtk_text_view_set_buffer            (GtkTextView *text_view,
                                                         GtkTextBuffer *buffer);
GtkTextBuffer*      gtk_text_view_get_buffer            (GtkTextView *text_view);
void                gtk_text_view_scroll_to_mark        (GtkTextView *text_view,
                                                         GtkTextMark *mark,
                                                         gdouble within_margin,
                                                         gboolean use_align,
                                                         gdouble xalign,
                                                         gdouble yalign);
gboolean            gtk_text_view_scroll_to_iter        (GtkTextView *text_view,
                                                         GtkTextIter *iter,
                                                         gdouble within_margin,
                                                         gboolean use_align,
                                                         gdouble xalign,
                                                         gdouble yalign);
void                gtk_text_view_scroll_mark_onscreen  (GtkTextView *text_view,
                                                         GtkTextMark *mark);
gboolean            gtk_text_view_move_mark_onscreen    (GtkTextView *text_view,
                                                         GtkTextMark *mark);
gboolean            gtk_text_view_place_cursor_onscreen (GtkTextView *text_view);
void                gtk_text_view_get_visible_rect      (GtkTextView *text_view,
                                                         GdkRectangle *visible_rect);
void                gtk_text_view_get_iter_location     (GtkTextView *text_view,
                                                         const GtkTextIter *iter,
                                                         GdkRectangle *location);
void                gtk_text_view_get_line_at_y         (GtkTextView *text_view,
                                                         GtkTextIter *target_iter,
                                                         gint y,
                                                         gint *line_top);
void                gtk_text_view_get_line_yrange       (GtkTextView *text_view,
                                                         const GtkTextIter *iter,
                                                         gint *y,
                                                         gint *height);
void                gtk_text_view_get_iter_at_location  (GtkTextView *text_view,
                                                         GtkTextIter *iter,
                                                         gint x,
                                                         gint y);
void                gtk_text_view_get_iter_at_position  (GtkTextView *text_view,
                                                         GtkTextIter *iter,
                                                         gint *trailing,
                                                         gint x,
                                                         gint y);
void                gtk_text_view_buffer_to_window_coords
                                                        (GtkTextView *text_view,
                                                         GtkTextWindowType win,
                                                         gint buffer_x,
                                                         gint buffer_y,
                                                         gint *window_x,
                                                         gint *window_y);
void                gtk_text_view_window_to_buffer_coords
                                                        (GtkTextView *text_view,
                                                         GtkTextWindowType win,
                                                         gint window_x,
                                                         gint window_y,
                                                         gint *buffer_x,
                                                         gint *buffer_y);
GdkWindow*          gtk_text_view_get_window            (GtkTextView *text_view,
                                                         GtkTextWindowType win);
GtkTextWindowType   gtk_text_view_get_window_type       (GtkTextView *text_view,
                                                         GdkWindow *window);
void                gtk_text_view_set_border_window_size
                                                        (GtkTextView *text_view,
                                                         GtkTextWindowType type,
                                                         gint size);
gint                gtk_text_view_get_border_window_size
                                                        (GtkTextView *text_view,
                                                         GtkTextWindowType type);
gboolean            gtk_text_view_forward_display_line  (GtkTextView *text_view,
                                                         GtkTextIter *iter);
gboolean            gtk_text_view_backward_display_line (GtkTextView *text_view,
                                                         GtkTextIter *iter);
gboolean            gtk_text_view_forward_display_line_end
                                                        (GtkTextView *text_view,
                                                         GtkTextIter *iter);
gboolean            gtk_text_view_backward_display_line_start
                                                        (GtkTextView *text_view,
                                                         GtkTextIter *iter);
gboolean            gtk_text_view_starts_display_line   (GtkTextView *text_view,
                                                         const GtkTextIter *iter);
gboolean            gtk_text_view_move_visually         (GtkTextView *text_view,
                                                         GtkTextIter *iter,
                                                         gint count);
void                gtk_text_view_add_child_at_anchor   (GtkTextView *text_view,
                                                         GtkWidget *child,
                                                         GtkTextChildAnchor *anchor);
                    GtkTextChildAnchor;
GtkTextChildAnchor* gtk_text_child_anchor_new           (void);
GList*              gtk_text_child_anchor_get_widgets   (GtkTextChildAnchor *anchor);
gboolean            gtk_text_child_anchor_get_deleted   (GtkTextChildAnchor *anchor);
void                gtk_text_view_add_child_in_window   (GtkTextView *text_view,
                                                         GtkWidget *child,
                                                         GtkTextWindowType which_window,
                                                         gint xpos,
                                                         gint ypos);
void                gtk_text_view_move_child            (GtkTextView *text_view,
                                                         GtkWidget *child,
                                                         gint xpos,
                                                         gint ypos);
void                gtk_text_view_set_wrap_mode         (GtkTextView *text_view,
                                                         GtkWrapMode wrap_mode);
GtkWrapMode         gtk_text_view_get_wrap_mode         (GtkTextView *text_view);
void                gtk_text_view_set_editable          (GtkTextView *text_view,
                                                         gboolean setting);
gboolean            gtk_text_view_get_editable          (GtkTextView *text_view);
void                gtk_text_view_set_cursor_visible    (GtkTextView *text_view,
                                                         gboolean setting);
gboolean            gtk_text_view_get_cursor_visible    (GtkTextView *text_view);
void                gtk_text_view_set_overwrite         (GtkTextView *text_view,
                                                         gboolean overwrite);
gboolean            gtk_text_view_get_overwrite         (GtkTextView *text_view);
void                gtk_text_view_set_pixels_above_lines
                                                        (GtkTextView *text_view,
                                                         gint pixels_above_lines);
gint                gtk_text_view_get_pixels_above_lines
                                                        (GtkTextView *text_view);
void                gtk_text_view_set_pixels_below_lines
                                                        (GtkTextView *text_view,
                                                         gint pixels_below_lines);
gint                gtk_text_view_get_pixels_below_lines
                                                        (GtkTextView *text_view);
void                gtk_text_view_set_pixels_inside_wrap
                                                        (GtkTextView *text_view,
                                                         gint pixels_inside_wrap);
gint                gtk_text_view_get_pixels_inside_wrap
                                                        (GtkTextView *text_view);
void                gtk_text_view_set_justification     (GtkTextView *text_view,
                                                         GtkJustification justification);
GtkJustification    gtk_text_view_get_justification     (GtkTextView *text_view);
void                gtk_text_view_set_left_margin       (GtkTextView *text_view,
                                                         gint left_margin);
gint                gtk_text_view_get_left_margin       (GtkTextView *text_view);
void                gtk_text_view_set_right_margin      (GtkTextView *text_view,
                                                         gint right_margin);
gint                gtk_text_view_get_right_margin      (GtkTextView *text_view);
void                gtk_text_view_set_indent            (GtkTextView *text_view,
                                                         gint indent);
gint                gtk_text_view_get_indent            (GtkTextView *text_view);
void                gtk_text_view_set_tabs              (GtkTextView *text_view,
                                                         PangoTabArray *tabs);
PangoTabArray*      gtk_text_view_get_tabs              (GtkTextView *text_view);
void                gtk_text_view_set_accepts_tab       (GtkTextView *text_view,
                                                         gboolean accepts_tab);
gboolean            gtk_text_view_get_accepts_tab       (GtkTextView *text_view);
GtkTextAttributes*  gtk_text_view_get_default_attributes
                                                        (GtkTextView *text_view);
#define             GTK_TEXT_VIEW_PRIORITY_VALIDATE

Object Hierarchy

  GObject
   +----GInitiallyUnowned
         +----GtkObject
               +----GtkWidget
                     +----GtkContainer
                           +----GtkTextView

  GObject
   +----GtkTextChildAnchor

Implemented Interfaces

GtkTextView implements AtkImplementorIface.

Properties

  "accepts-tab"              gboolean              : Read / Write
  "buffer"                   GtkTextBuffer         : Read / Write
  "cursor-visible"           gboolean              : Read / Write
  "editable"                 gboolean              : Read / Write
  "indent"                   gint                  : Read / Write
  "justification"            GtkJustification      : Read / Write
  "left-margin"              gint                  : Read / Write
  "overwrite"                gboolean              : Read / Write
  "pixels-above-lines"       gint                  : Read / Write
  "pixels-below-lines"       gint                  : Read / Write
  "pixels-inside-wrap"       gint                  : Read / Write
  "right-margin"             gint                  : Read / Write
  "tabs"                     PangoTabArray         : Read / Write
  "wrap-mode"                GtkWrapMode           : Read / Write

Style Properties

  "error-underline-color"    GdkColor              : Read

Signals

  "backspace"                                      : Run Last / Action
  "copy-clipboard"                                 : Run Last / Action
  "cut-clipboard"                                  : Run Last / Action
  "delete-from-cursor"                             : Run Last / Action
  "insert-at-cursor"                               : Run Last / Action
  "move-cursor"                                    : Run Last / Action
  "move-focus"                                     : Run Last / Action
  "move-viewport"                                  : Run Last / Action
  "page-horizontally"                              : Run Last / Action
  "paste-clipboard"                                : Run Last / Action
  "populate-popup"                                 : Run Last
  "select-all"                                     : Run Last / Action
  "set-anchor"                                     : Run Last / Action
  "set-scroll-adjustments"                         : Run Last / Action
  "toggle-overwrite"                               : Run Last / Action

Description

You may wish to begin by reading the text widget conceptual overview which gives an overview of all the objects and data types related to the text widget and how they work together.

Details

GtkTextView

typedef struct _GtkTextView GtkTextView;

enum GtkTextWindowType

typedef enum
{
  GTK_TEXT_WINDOW_PRIVATE,
  GTK_TEXT_WINDOW_WIDGET,
  GTK_TEXT_WINDOW_TEXT,
  GTK_TEXT_WINDOW_LEFT,
  GTK_TEXT_WINDOW_RIGHT,
  GTK_TEXT_WINDOW_TOP,
  GTK_TEXT_WINDOW_BOTTOM
} GtkTextWindowType;

gtk_text_view_new ()

GtkWidget*          gtk_text_view_new                   (void);

Creates a new GtkTextView. If you don't call gtk_text_view_set_buffer() before using the text view, an empty default buffer will be created for you. Get the buffer with gtk_text_view_get_buffer(). If you want to specify your own buffer, consider gtk_text_view_new_with_buffer().

Returns : a new GtkTextView

gtk_text_view_new_with_buffer ()

GtkWidget*          gtk_text_view_new_with_buffer       (GtkTextBuffer *buffer);

Creates a new GtkTextView widget displaying the buffer buffer. One buffer can be shared among many widgets. buffer may be NULL to create a default buffer, in which case this function is equivalent to gtk_text_view_new(). The text view adds its own reference count to the buffer; it does not take over an existing reference.

buffer : | a GtkTextBuffer
Returns : | a new GtkTextView.

gtk_text_view_set_buffer ()

void                gtk_text_view_set_buffer            (GtkTextView *text_view,
                                                         GtkTextBuffer *buffer);

Sets buffer as the buffer being displayed by text_view. The previous buffer displayed by the text view is unreferenced, and a reference is added to buffer. If you owned a reference to buffer before passing it to this function, you must remove that reference yourself; GtkTextView will not "adopt" it.

text_view : | a GtkTextView
buffer : | a GtkTextBuffer

gtk_text_view_get_buffer ()

GtkTextBuffer*      gtk_text_view_get_buffer            (GtkTextView *text_view);

Returns the GtkTextBuffer being displayed by this text view. The reference count on the buffer is not incremented; the caller of this function won't own a new reference.

text_view : | a GtkTextView
Returns : | a GtkTextBuffer

gtk_text_view_scroll_to_mark ()

void                gtk_text_view_scroll_to_mark        (GtkTextView *text_view,
                                                         GtkTextMark *mark,
                                                         gdouble within_margin,
                                                         gboolean use_align,
                                                         gdouble xalign,
                                                         gdouble yalign);

Scrolls text_view so that mark is on the screen in the position indicated by xalign and yalign. An alignment of 0.0 indicates left or top, 1.0 indicates right or bottom, 0.5 means center. If use_align is FALSE, the text scrolls the minimal distance to get the mark onscreen, possibly not scrolling at all. The effective screen for purposes of this function is reduced by a margin of size within_margin.

text_view : | a GtkTextView
mark : | a GtkTextMark
within_margin : | margin as a [0.0,0.5) fraction of screen size
use_align : | whether to use alignment arguments (if FALSE, just get the mark onscreen)
xalign : | horizontal alignment of mark within visible area.
yalign : | vertical alignment of mark within visible area

gtk_text_view_scroll_to_iter ()

gboolean            gtk_text_view_scroll_to_iter        (GtkTextView *text_view,
                                                         GtkTextIter *iter,
                                                         gdouble within_margin,
                                                         gboolean use_align,
                                                         gdouble xalign,
                                                         gdouble yalign);

Scrolls text_view so that iter is on the screen in the position indicated by xalign and yalign. An alignment of 0.0 indicates left or top, 1.0 indicates right or bottom, 0.5 means center. If use_align is FALSE, the text scrolls the minimal distance to get the mark onscreen, possibly not scrolling at all. The effective screen for purposes of this function is reduced by a margin of size within_margin. NOTE: This function uses the currently-computed height of the lines in the text buffer. Note that line heights are computed in an idle handler; so this function may not have the desired effect if it's called before the height computations. To avoid oddness, consider using gtk_text_view_scroll_to_mark() which saves a point to be scrolled to after line validation.

text_view : | a GtkTextView
iter : | a GtkTextIter
within_margin : | margin as a [0.0,0.5) fraction of screen size
use_align : | whether to use alignment arguments (if FALSE, just get the mark onscreen)
xalign : | horizontal alignment of mark within visible area.
yalign : | vertical alignment of mark within visible area
Returns : | TRUE if scrolling occurred

gtk_text_view_scroll_mark_onscreen ()

void                gtk_text_view_scroll_mark_onscreen  (GtkTextView *text_view,
                                                         GtkTextMark *mark);

Scrolls text_view the minimum distance such that mark is contained within the visible area of the widget.

text_view : | a GtkTextView
mark : | a mark in the buffer for text_view

gtk_text_view_move_mark_onscreen ()

gboolean            gtk_text_view_move_mark_onscreen    (GtkTextView *text_view,
                                                         GtkTextMark *mark);

Moves a mark within the buffer so that it's located within the currently-visible text area.

text_view : | a GtkTextView
mark : | a GtkTextMark
Returns : | TRUE if the mark moved (wasn't already onscreen)

gtk_text_view_place_cursor_onscreen ()

gboolean            gtk_text_view_place_cursor_onscreen (GtkTextView *text_view);

Moves the cursor to the currently visible region of the buffer, it it isn't there already.

text_view : | a GtkTextView
Returns : | TRUE if the cursor had to be moved.

gtk_text_view_get_visible_rect ()

void                gtk_text_view_get_visible_rect      (GtkTextView *text_view,
                                                         GdkRectangle *visible_rect);

Fills visible_rect with the currently-visible region of the buffer, in buffer coordinates. Convert to window coordinates with gtk_text_view_buffer_to_window_coords().

text_view : | a GtkTextView
visible_rect : | rectangle to fill

gtk_text_view_get_iter_location ()

void                gtk_text_view_get_iter_location     (GtkTextView *text_view,
                                                         const GtkTextIter *iter,
                                                         GdkRectangle *location);

Gets a rectangle which roughly contains the character at iter. The rectangle position is in buffer coordinates; use gtk_text_view_buffer_to_window_coords() to convert these coordinates to coordinates for one of the windows in the text view.

text_view : | a GtkTextView
iter : | a GtkTextIter
location : | bounds of the character at iter

gtk_text_view_get_line_at_y ()

void                gtk_text_view_get_line_at_y         (GtkTextView *text_view,
                                                         GtkTextIter *target_iter,
                                                         gint y,
                                                         gint *line_top);

Gets the GtkTextIter at the start of the line containing the coordinate y. y is in buffer coordinates, convert from window coordinates with gtk_text_view_window_to_buffer_coords(). If non-NULL, line_top will be filled with the coordinate of the top edge of the line.

text_view : | a GtkTextView
target_iter : | a GtkTextIter
y : | a y coordinate
line_top : | return location for top coordinate of the line

gtk_text_view_get_line_yrange ()

void                gtk_text_view_get_line_yrange       (GtkTextView *text_view,
                                                         const GtkTextIter *iter,
                                                         gint *y,
                                                         gint *height);

Gets the y coordinate of the top of the line containing iter, and the height of the line. The coordinate is a buffer coordinate; convert to window coordinates with gtk_text_view_buffer_to_window_coords().

text_view : | a GtkTextView
iter : | a GtkTextIter
y : | return location for a y coordinate
height : | return location for a height

gtk_text_view_get_iter_at_location ()

void                gtk_text_view_get_iter_at_location  (GtkTextView *text_view,
                                                         GtkTextIter *iter,
                                                         gint x,
                                                         gint y);

Retrieves the iterator at buffer coordinates x and y. Buffer coordinates are coordinates for the entire buffer, not just the currently-displayed portion. If you have coordinates from an event, you have to convert those to buffer coordinates with gtk_text_view_window_to_buffer_coords().

text_view : | a GtkTextView
iter : | a GtkTextIter
x : | x position, in buffer coordinates
y : | y position, in buffer coordinates

gtk_text_view_get_iter_at_position ()

void                gtk_text_view_get_iter_at_position  (GtkTextView *text_view,
                                                         GtkTextIter *iter,
                                                         gint *trailing,
                                                         gint x,
                                                         gint y);

Retrieves the iterator pointing to the character at buffer coordinates x and y. Buffer coordinates are coordinates for the entire buffer, not just the currently-displayed portion. If you have coordinates from an event, you have to convert those to buffer coordinates with gtk_text_view_window_to_buffer_coords().

Note that this is different from gtk_text_view_get_iter_at_location(), which returns cursor locations, i.e. positions between characters.

text_view : | a GtkTextView
iter : | a GtkTextIter
trailing : | location to store an integer indicating where in the grapheme the user clicked. It will either be zero, or the number of characters in the grapheme. 0 represents the trailing edge of the grapheme.
x : | x position, in buffer coordinates
y : | y position, in buffer coordinates

Since 2.6

gtk_text_view_buffer_to_window_coords ()

void                gtk_text_view_buffer_to_window_coords
                                                        (GtkTextView *text_view,
                                                         GtkTextWindowType win,
                                                         gint buffer_x,
                                                         gint buffer_y,
                                                         gint *window_x,
                                                         gint *window_y);

Converts coordinate (buffer_x, buffer_y) to coordinates for the window win, and stores the result in (window_x, window_y).

Note that you can't convert coordinates for a nonexisting window (see gtk_text_view_set_border_window_size()).

text_view : | a GtkTextView
win : | a GtkTextWindowType except GTK_TEXT_WINDOW_PRIVATE
buffer_x : | buffer x coordinate
buffer_y : | buffer y coordinate
window_x : | window x coordinate return location
window_y : | window y coordinate return location

gtk_text_view_window_to_buffer_coords ()

void                gtk_text_view_window_to_buffer_coords
                                                        (GtkTextView *text_view,
                                                         GtkTextWindowType win,
                                                         gint window_x,
                                                         gint window_y,
                                                         gint *buffer_x,
                                                         gint *buffer_y);

Converts coordinates on the window identified by win to buffer coordinates, storing the result in (buffer_x,buffer_y).

Note that you can't convert coordinates for a nonexisting window (see gtk_text_view_set_border_window_size()).

text_view : | a GtkTextView
win : | a GtkTextWindowType except GTK_TEXT_WINDOW_PRIVATE
window_x : | window x coordinate
window_y : | window y coordinate
buffer_x : | buffer x coordinate return location
buffer_y : | buffer y coordinate return location

gtk_text_view_get_window ()

GdkWindow*          gtk_text_view_get_window            (GtkTextView *text_view,
                                                         GtkTextWindowType win);

Retrieves the GdkWindow corresponding to an area of the text view; possible windows include the overall widget window, child windows on the left, right, top, bottom, and the window that displays the text buffer. Windows are NULL and nonexistent if their width or height is 0, and are nonexistent before the widget has been realized.

text_view : | a GtkTextView
win : | window to get
Returns : | a GdkWindow, or NULL

gtk_text_view_get_window_type ()

GtkTextWindowType   gtk_text_view_get_window_type       (GtkTextView *text_view,
                                                         GdkWindow *window);

Usually used to find out which window an event corresponds to. If you connect to an event signal on text_view, this function should be called on event->window to see which window it was.

text_view : | a GtkTextView
window : | a window type
Returns : | the window type.

gtk_text_view_set_border_window_size ()

void                gtk_text_view_set_border_window_size
                                                        (GtkTextView *text_view,
                                                         GtkTextWindowType type,
                                                         gint size);

Sets the width of GTK_TEXT_WINDOW_LEFT or GTK_TEXT_WINDOW_RIGHT, or the height of GTK_TEXT_WINDOW_TOP or GTK_TEXT_WINDOW_BOTTOM. Automatically destroys the corresponding window if the size is set to 0, and creates the window if the size is set to non-zero. This function can only be used for the "border windows," it doesn't work with GTK_TEXT_WINDOW_WIDGET, GTK_TEXT_WINDOW_TEXT, or GTK_TEXT_WINDOW_PRIVATE.

text_view : | a GtkTextView
type : | window to affect
size : | width or height of the window

gtk_text_view_get_border_window_size ()

gint                gtk_text_view_get_border_window_size
                                                        (GtkTextView *text_view,
                                                         GtkTextWindowType type);

Gets the width of the specified border window. See gtk_text_view_set_border_window_size().

text_view : | a GtkTextView
type : | window to return size from
Returns : | width of window

gtk_text_view_forward_display_line ()

gboolean            gtk_text_view_forward_display_line  (GtkTextView *text_view,
                                                         GtkTextIter *iter);

Moves the given iter forward by one display (wrapped) line. A display line is different from a paragraph. Paragraphs are separated by newlines or other paragraph separator characters. Display lines are created by line-wrapping a paragraph. If wrapping is turned off, display lines and paragraphs will be the same. Display lines are divided differently for each view, since they depend on the view's width; paragraphs are the same in all views, since they depend on the contents of the GtkTextBuffer.

text_view : | a GtkTextView
iter : | a GtkTextIter
Returns : | TRUE if iter was moved and is not on the end iterator

gtk_text_view_backward_display_line ()

gboolean            gtk_text_view_backward_display_line (GtkTextView *text_view,
                                                         GtkTextIter *iter);

Moves the given iter backward by one display (wrapped) line. A display line is different from a paragraph. Paragraphs are separated by newlines or other paragraph separator characters. Display lines are created by line-wrapping a paragraph. If wrapping is turned off, display lines and paragraphs will be the same. Display lines are divided differently for each view, since they depend on the view's width; paragraphs are the same in all views, since they depend on the contents of the GtkTextBuffer.

text_view : | a GtkTextView
iter : | a GtkTextIter
Returns : | TRUE if iter was moved and is not on the end iterator

gtk_text_view_forward_display_line_end ()

gboolean            gtk_text_view_forward_display_line_end
                                                        (GtkTextView *text_view,
                                                         GtkTextIter *iter);

Moves the given iter forward to the next display line end. A display line is different from a paragraph. Paragraphs are separated by newlines or other paragraph separator characters. Display lines are created by line-wrapping a paragraph. If wrapping is turned off, display lines and paragraphs will be the same. Display lines are divided differently for each view, since they depend on the view's width; paragraphs are the same in all views, since they depend on the contents of the GtkTextBuffer.

text_view : | a GtkTextView
iter : | a GtkTextIter
Returns : | TRUE if iter was moved and is not on the end iterator

gtk_text_view_backward_display_line_start ()

gboolean            gtk_text_view_backward_display_line_start
                                                        (GtkTextView *text_view,
                                                         GtkTextIter *iter);

Moves the given iter backward to the next display line start. A display line is different from a paragraph. Paragraphs are separated by newlines or other paragraph separator characters. Display lines are created by line-wrapping a paragraph. If wrapping is turned off, display lines and paragraphs will be the same. Display lines are divided differently for each view, since they depend on the view's width; paragraphs are the same in all views, since they depend on the contents of the GtkTextBuffer.

text_view : | a GtkTextView
iter : | a GtkTextIter
Returns : | TRUE if iter was moved and is not on the end iterator

gtk_text_view_starts_display_line ()

gboolean            gtk_text_view_starts_display_line   (GtkTextView *text_view,
                                                         const GtkTextIter *iter);

Determines whether iter is at the start of a display line. See gtk_text_view_forward_display_line() for an explanation of display lines vs. paragraphs.

text_view : | a GtkTextView
iter : | a GtkTextIter
Returns : | TRUE if iter begins a wrapped line

gtk_text_view_move_visually ()

gboolean            gtk_text_view_move_visually         (GtkTextView *text_view,
                                                         GtkTextIter *iter,
                                                         gint count);

Move the iterator a given number of characters visually, treating it as the strong cursor position. If count is positive, then the new strong cursor position will be count positions to the right of the old cursor position. If count is negative then the new strong cursor position will be count positions to the left of the old cursor position.

In the presence of bidirection text, the correspondence between logical and visual order will depend on the direction of the current run, and there may be jumps when the cursor is moved off of the end of a run.

text_view : | a GtkTextView
iter : | a GtkTextIter
count : | number of characters to move (negative moves left, positive moves right)
Returns : | TRUE if iter moved and is not on the end iterator

gtk_text_view_add_child_at_anchor ()

void                gtk_text_view_add_child_at_anchor   (GtkTextView *text_view,
                                                         GtkWidget *child,
                                                         GtkTextChildAnchor *anchor);

Adds a child widget in the text buffer, at the given anchor.

text_view : | a GtkTextView
child : | a GtkWidget
anchor : | a GtkTextChildAnchor in the GtkTextBuffer for text_view

GtkTextChildAnchor

typedef struct _GtkTextChildAnchor GtkTextChildAnchor;

A GtkTextChildAnchor is a spot in the buffer where child widgets can be "anchored" (inserted inline, as if they were characters). The anchor can have multiple widgets anchored, to allow for multiple views.

gtk_text_child_anchor_new ()

GtkTextChildAnchor* gtk_text_child_anchor_new           (void);

Creates a new GtkTextChildAnchor. Usually you would then insert it into a GtkTextBuffer with gtk_text_buffer_insert_child_anchor(). To perform the creation and insertion in one step, use the convenience function gtk_text_buffer_create_child_anchor().

Returns : a new GtkTextChildAnchor

gtk_text_child_anchor_get_widgets ()

GList*              gtk_text_child_anchor_get_widgets   (GtkTextChildAnchor *anchor);

Gets a list of all widgets anchored at this child anchor. The returned list should be freed with g_list_free().

anchor : | a GtkTextChildAnchor
Returns : | list of widgets anchored at anchor

gtk_text_child_anchor_get_deleted ()

gboolean            gtk_text_child_anchor_get_deleted   (GtkTextChildAnchor *anchor);

Determines whether a child anchor has been deleted from the buffer. Keep in mind that the child anchor will be unreferenced when removed from the buffer, so you need to hold your own reference (with g_object_ref()) if you plan to use this function — otherwise all deleted child anchors will also be finalized.

anchor : | a GtkTextChildAnchor
Returns : | TRUE if the child anchor has been deleted from its buffer

gtk_text_view_add_child_in_window ()

void                gtk_text_view_add_child_in_window   (GtkTextView *text_view,
                                                         GtkWidget *child,
                                                         GtkTextWindowType which_window,
                                                         gint xpos,
                                                         gint ypos);

Adds a child at fixed coordinates in one of the text widget's windows. The window must have nonzero size (see gtk_text_view_set_border_window_size()). Note that the child coordinates are given relative to the GdkWindow in question, and that these coordinates have no sane relationship to scrolling. When placing a child in GTK_TEXT_WINDOW_WIDGET, scrolling is irrelevant, the child floats above all scrollable areas. But when placing a child in one of the scrollable windows (border windows or text window), you'll need to compute the child's correct position in buffer coordinates any time scrolling occurs or buffer changes occur, and then call gtk_text_view_move_child() to update the child's position. Unfortunately there's no good way to detect that scrolling has occurred, using the current API; a possible hack would be to update all child positions when the scroll adjustments change or the text buffer changes. See bug 64518 on bugzilla.gnome.org for status of fixing this issue.

text_view : | a GtkTextView
child : | a GtkWidget
which_window : | which window the child should appear in
xpos : | X position of child in window coordinates
ypos : | Y position of child in window coordinates

gtk_text_view_move_child ()

void                gtk_text_view_move_child            (GtkTextView *text_view,
                                                         GtkWidget *child,
                                                         gint xpos,
                                                         gint ypos);

Updates the position of a child, as for gtk_text_view_add_child_in_window().

text_view : | a GtkTextView
child : | child widget already added to the text view
xpos : | new X position in window coordinates
ypos : | new Y position in window coordinates

gtk_text_view_set_wrap_mode ()

void                gtk_text_view_set_wrap_mode         (GtkTextView *text_view,
                                                         GtkWrapMode wrap_mode);

Sets the line wrapping for the view.

text_view : | a GtkTextView
wrap_mode : | a GtkWrapMode

gtk_text_view_get_wrap_mode ()

GtkWrapMode         gtk_text_view_get_wrap_mode         (GtkTextView *text_view);

Gets the line wrapping for the view.

text_view : | a GtkTextView
Returns : | the line wrap setting

gtk_text_view_set_editable ()

void                gtk_text_view_set_editable          (GtkTextView *text_view,
                                                         gboolean setting);

Sets the default editability of the GtkTextView. You can override this default setting with tags in the buffer, using the "editable" attribute of tags.

text_view : | a GtkTextView
setting : | whether it's editable

gtk_text_view_get_editable ()

gboolean            gtk_text_view_get_editable          (GtkTextView *text_view);

Returns the default editability of the GtkTextView. Tags in the buffer may override this setting for some ranges of text.

text_view : | a GtkTextView
Returns : | whether text is editable by default

gtk_text_view_set_cursor_visible ()

void                gtk_text_view_set_cursor_visible    (GtkTextView *text_view,
                                                         gboolean setting);

Toggles whether the insertion point is displayed. A buffer with no editable text probably shouldn't have a visible cursor, so you may want to turn the cursor off.

text_view : | a GtkTextView
setting : | whether to show the insertion cursor

gtk_text_view_get_cursor_visible ()

gboolean            gtk_text_view_get_cursor_visible    (GtkTextView *text_view);

Find out whether the cursor is being displayed.

text_view : | a GtkTextView
Returns : | whether the insertion mark is visible

gtk_text_view_set_overwrite ()

void                gtk_text_view_set_overwrite         (GtkTextView *text_view,
                                                         gboolean overwrite);

Changes the GtkTextView overwrite mode.

text_view : | a GtkTextView
overwrite : | TRUE to turn on overwrite mode, FALSE to turn it off

Since 2.4

gtk_text_view_get_overwrite ()

gboolean            gtk_text_view_get_overwrite         (GtkTextView *text_view);

Returns whether the GtkTextView is in overwrite mode or not.

text_view : | a GtkTextView
Returns : | whether text_view is in overwrite mode or not.

Since 2.4

gtk_text_view_set_pixels_above_lines ()

void                gtk_text_view_set_pixels_above_lines
                                                        (GtkTextView *text_view,
                                                         gint pixels_above_lines);

Sets the default number of blank pixels above paragraphs in text_view. Tags in the buffer for text_view may override the defaults.

text_view : | a GtkTextView
pixels_above_lines : | pixels above paragraphs

gtk_text_view_get_pixels_above_lines ()

gint                gtk_text_view_get_pixels_above_lines
                                                        (GtkTextView *text_view);

Gets the default number of pixels to put above paragraphs.

text_view : | a GtkTextView
Returns : | default number of pixels above paragraphs

gtk_text_view_set_pixels_below_lines ()

void                gtk_text_view_set_pixels_below_lines
                                                        (GtkTextView *text_view,
                                                         gint pixels_below_lines);

Sets the default number of pixels of blank space to put below paragraphs in text_view. May be overridden by tags applied to text_view's buffer.

text_view : | a GtkTextView
pixels_below_lines : | pixels below paragraphs

gtk_text_view_get_pixels_below_lines ()

gint                gtk_text_view_get_pixels_below_lines
                                                        (GtkTextView *text_view);

Gets the value set by gtk_text_view_set_pixels_below_lines().

text_view : | a GtkTextView
Returns : | default number of blank pixels below paragraphs

gtk_text_view_set_pixels_inside_wrap ()

void                gtk_text_view_set_pixels_inside_wrap
                                                        (GtkTextView *text_view,
                                                         gint pixels_inside_wrap);

Sets the default number of pixels of blank space to leave between display/wrapped lines within a paragraph. May be overridden by tags in text_view's buffer.

text_view : | a GtkTextView
pixels_inside_wrap : | default number of pixels between wrapped lines

gtk_text_view_get_pixels_inside_wrap ()

gint                gtk_text_view_get_pixels_inside_wrap
                                                        (GtkTextView *text_view);

Gets the value set by gtk_text_view_set_pixels_inside_wrap().

text_view : | a GtkTextView
Returns : | default number of pixels of blank space between wrapped lines

gtk_text_view_set_justification ()

void                gtk_text_view_set_justification     (GtkTextView *text_view,
                                                         GtkJustification justification);

Sets the default justification of text in text_view. Tags in the view's buffer may override the default.

text_view : | a GtkTextView
justification : | justification

gtk_text_view_get_justification ()

GtkJustification    gtk_text_view_get_justification     (GtkTextView *text_view);

Gets the default justification of paragraphs in text_view. Tags in the buffer may override the default.

text_view : | a GtkTextView
Returns : | default justification

gtk_text_view_set_left_margin ()

void                gtk_text_view_set_left_margin       (GtkTextView *text_view,
                                                         gint left_margin);

Sets the default left margin for text in text_view. Tags in the buffer may override the default.

text_view : | a GtkTextView
left_margin : | left margin in pixels

gtk_text_view_get_left_margin ()

gint                gtk_text_view_get_left_margin       (GtkTextView *text_view);

Gets the default left margin size of paragraphs in the text_view. Tags in the buffer may override the default.

text_view : | a GtkTextView
Returns : | left margin in pixels

gtk_text_view_set_right_margin ()

void                gtk_text_view_set_right_margin      (GtkTextView *text_view,
                                                         gint right_margin);

Sets the default right margin for text in the text view. Tags in the buffer may override the default.

text_view : | a GtkTextView
right_margin : | right margin in pixels

gtk_text_view_get_right_margin ()

gint                gtk_text_view_get_right_margin      (GtkTextView *text_view);

Gets the default right margin for text in text_view. Tags in the buffer may override the default.

text_view : | a GtkTextView
Returns : | right margin in pixels

gtk_text_view_set_indent ()

void                gtk_text_view_set_indent            (GtkTextView *text_view,
                                                         gint indent);

Sets the default indentation for paragraphs in text_view. Tags in the buffer may override the default.

text_view : | a GtkTextView
indent : | indentation in pixels

gtk_text_view_get_indent ()

gint                gtk_text_view_get_indent            (GtkTextView *text_view);

Gets the default indentation of paragraphs in text_view. Tags in the view's buffer may override the default. The indentation may be negative.

text_view : | a GtkTextView
Returns : | number of pixels of indentation

gtk_text_view_set_tabs ()

void                gtk_text_view_set_tabs              (GtkTextView *text_view,
                                                         PangoTabArray *tabs);

Sets the default tab stops for paragraphs in text_view. Tags in the buffer may override the default.

text_view : | a GtkTextView
tabs : | tabs as a PangoTabArray

gtk_text_view_get_tabs ()

PangoTabArray*      gtk_text_view_get_tabs              (GtkTextView *text_view);

Gets the default tabs for text_view. Tags in the buffer may override the defaults. The returned array will be NULL if "standard" (8-space) tabs are used. Free the return value with pango_tab_array_free().

text_view : | a GtkTextView
Returns : | copy of default tab array, or NULL if "standard" tabs are used; must be freed with pango_tab_array_free().

gtk_text_view_set_accepts_tab ()

void                gtk_text_view_set_accepts_tab       (GtkTextView *text_view,
                                                         gboolean accepts_tab);

Sets the behavior of the text widget when the Tab key is pressed. If accepts_tab is TRUE a tab character is inserted. If accepts_tab is FALSE the keyboard focus is moved to the next widget in the focus chain.

text_view : | A GtkTextView
accepts_tab : | TRUE if pressing the Tab key should insert a tab character, FALSE, if pressing the Tab key should move the keyboard focus.

Since 2.4

gtk_text_view_get_accepts_tab ()

gboolean            gtk_text_view_get_accepts_tab       (GtkTextView *text_view);

Returns whether pressing the Tab key inserts a tab characters. gtk_text_view_set_accepts_tab().

text_view : | A GtkTextView
Returns : | TRUE if pressing the Tab key inserts a tab character, FALSE if pressing the Tab key moves the keyboard focus.

Since 2.4

gtk_text_view_get_default_attributes ()

GtkTextAttributes*  gtk_text_view_get_default_attributes
                                                        (GtkTextView *text_view);

Obtains a copy of the default text attributes. These are the attributes used for text unless a tag overrides them. You'd typically pass the default attributes in to gtk_text_iter_get_attributes() in order to get the attributes in effect at a given text position.

The return value is a copy owned by the caller of this function, and should be freed.

text_view : | a GtkTextView
Returns : | a new GtkTextAttributes

GTK_TEXT_VIEW_PRIORITY_VALIDATE

#define GTK_TEXT_VIEW_PRIORITY_VALIDATE (GDK_PRIORITY_REDRAW + 5)

The priority at which the text view validates onscreen lines in an idle job in the background.

Property Details

The "accepts-tab" property

  "accepts-tab"              gboolean              : Read / Write

Whether Tab will result in a tab character being entered.

Default value: TRUE

The "buffer" property

  "buffer"                   GtkTextBuffer         : Read / Write

The buffer which is displayed.

The "cursor-visible" property

  "cursor-visible"           gboolean              : Read / Write

If the insertion cursor is shown.

Default value: TRUE

The "editable" property

  "editable"                 gboolean              : Read / Write

Whether the text can be modified by the user.

Default value: TRUE

The "indent" property

  "indent"                   gint                  : Read / Write

Amount to indent the paragraph, in pixels.

Allowed values: >= 0

Default value: 0

The "justification" property

  "justification"            GtkJustification      : Read / Write

Left, right, or center justification.

Default value: GTK_JUSTIFY_LEFT

The "left-margin" property

  "left-margin"              gint                  : Read / Write

Width of the left margin in pixels.

Allowed values: >= 0

Default value: 0

The "overwrite" property

  "overwrite"                gboolean              : Read / Write

Whether entered text overwrites existing contents.

Default value: FALSE

The "pixels-above-lines" property

  "pixels-above-lines"       gint                  : Read / Write

Pixels of blank space above paragraphs.

Allowed values: >= 0

Default value: 0

The "pixels-below-lines" property

  "pixels-below-lines"       gint                  : Read / Write

Pixels of blank space below paragraphs.

Allowed values: >= 0

Default value: 0

The "pixels-inside-wrap" property

  "pixels-inside-wrap"       gint                  : Read / Write

Pixels of blank space between wrapped lines in a paragraph.

Allowed values: >= 0

Default value: 0

The "right-margin" property

  "right-margin"             gint                  : Read / Write

Width of the right margin in pixels.

Allowed values: >= 0

Default value: 0

The "tabs" property

  "tabs"                     PangoTabArray         : Read / Write

Custom tabs for this text.

The "wrap-mode" property

  "wrap-mode"                GtkWrapMode           : Read / Write

Whether to wrap lines never, at word boundaries, or at character boundaries.

Default value: GTK_WRAP_NONE

Style Property Details

The "error-underline-color" style property

  "error-underline-color"    GdkColor              : Read

Color with which to draw error-indication underlines.

Signal Details

The "backspace" signal

void                user_function                      (GtkTextView *textview,
                                                        gpointer     user_data)      : Run Last / Action

textview : | the object which received the signal.
user_data : | user data set when the signal handler was connected.

The "copy-clipboard" signal

void                user_function                      (GtkTextView *textview,
                                                        gpointer     user_data)      : Run Last / Action

textview : | the object which received the signal.
user_data : | user data set when the signal handler was connected.

The "cut-clipboard" signal

void                user_function                      (GtkTextView *textview,
                                                        gpointer     user_data)      : Run Last / Action

textview : | the object which received the signal.
user_data : | user data set when the signal handler was connected.

The "delete-from-cursor" signal

void                user_function                      (GtkTextView  *textview,
                                                        GtkDeleteType arg1,
                                                        gint          arg2,
                                                        gpointer      user_data)      : Run Last / Action

textview : | the object which received the signal.
arg1 : |
arg2 : |
user_data : | user data set when the signal handler was connected.

The "insert-at-cursor" signal

void                user_function                      (GtkTextView *textview,
                                                        gchar       *arg1,
                                                        gpointer     user_data)      : Run Last / Action

textview : | the object which received the signal.
arg1 : |
user_data : | user data set when the signal handler was connected.

The "move-cursor" signal

void                user_function                      (GtkTextView    *widget,
                                                        GtkMovementStep step,
                                                        gint            count,
                                                        gboolean        extend_selection,
                                                        gpointer        user_data)             : Run Last / Action

The ::move-cursor signal is a keybinding signal which gets emitted when the user initiates a cursor movement.

Applications should not connect to it, but may emit it with g_signal_emit_by_name() if they need to control scrolling programmatically.

widget : | the object which received the signal
step : | the granularity of the move, as a GtkMovementStep
count : | the number of step units to move
extend_selection : | TRUE if the move should extend the selection
user_data : | user data set when the signal handler was connected.

The "move-focus" signal

void                user_function                      (GtkTextView     *textview,
                                                        GtkDirectionType arg1,
                                                        gpointer         user_data)      : Run Last / Action

textview : | the object which received the signal.
arg1 : |
user_data : | user data set when the signal handler was connected.

The "move-viewport" signal

void                user_function                      (GtkTextView  *textview,
                                                        GtkScrollStep arg1,
                                                        gint          arg2,
                                                        gpointer      user_data)      : Run Last / Action

textview : | the object which received the signal.
arg1 : |
arg2 : |
user_data : | user data set when the signal handler was connected.

The "page-horizontally" signal

void                user_function                      (GtkTextView *textview,
                                                        gint         arg1,
                                                        gboolean     arg2,
                                                        gpointer     user_data)      : Run Last / Action

textview : | the object which received the signal.
arg1 : |
arg2 : |
user_data : | user data set when the signal handler was connected.

The "paste-clipboard" signal

void                user_function                      (GtkTextView *textview,
                                                        gpointer     user_data)      : Run Last / Action

textview : | the object which received the signal.
user_data : | user data set when the signal handler was connected.

The "populate-popup" signal

void                user_function                      (GtkTextView *textview,
                                                        GtkMenu     *arg1,
                                                        gpointer     user_data)      : Run Last

textview : | the object which received the signal.
arg1 : |
user_data : | user data set when the signal handler was connected.

The "select-all" signal

void                user_function                      (GtkTextView *textview,
                                                        gboolean     arg1,
                                                        gpointer     user_data)      : Run Last / Action

textview : | the object which received the signal.
arg1 : |
user_data : | user data set when the signal handler was connected.

The "set-anchor" signal

void                user_function                      (GtkTextView *textview,
                                                        gpointer     user_data)      : Run Last / Action

textview : | the object which received the signal.
user_data : | user data set when the signal handler was connected.

The "set-scroll-adjustments" signal

void                user_function                      (GtkTextView   *textview,
                                                        GtkAdjustment *arg1,
                                                        GtkAdjustment *arg2,
                                                        gpointer       user_data)      : Run Last / Action

textview : | the object which received the signal.
arg1 : |
arg2 : |
user_data : | user data set when the signal handler was connected.

The "toggle-overwrite" signal

void                user_function                      (GtkTextView *textview,
                                                        gpointer     user_data)      : Run Last / Action

textview : | the object which received the signal.
user_data : | user data set when the signal handler was connected.

See Also

GtkTextBuffer, GtkTextIter


GtkTipsQuery

GtkTipsQuery — Displays help about widgets in the user interface

Synopsis

#include <gtk/gtk.h>

                    GtkTipsQuery;
GtkWidget*          gtk_tips_query_new                  (void);
void                gtk_tips_query_start_query          (GtkTipsQuery *tips_query);
void                gtk_tips_query_stop_query           (GtkTipsQuery *tips_query);
void                gtk_tips_query_set_caller           (GtkTipsQuery *tips_query,
                                                         GtkWidget *caller);
void                gtk_tips_query_set_labels           (GtkTipsQuery *tips_query,
                                                         const gchar *label_inactive,
                                                         const gchar *label_no_tip);

Object Hierarchy

  GObject
   +----GInitiallyUnowned
         +----GtkObject
               +----GtkWidget
                     +----GtkMisc
                           +----GtkLabel
                                 +----GtkTipsQuery

Implemented Interfaces

GtkTipsQuery implements AtkImplementorIface.

Properties

  "caller"                   GtkWidget             : Read / Write
  "emit-always"              gboolean              : Read / Write
  "label-inactive"           gchararray            : Read / Write
  "label-no-tip"             gchararray            : Read / Write

Signals

  "start-query"                                    : Run First
  "stop-query"                                     : Run First
  "widget-entered"                                 : Run Last
  "widget-selected"                                : Run Last

Description

The GtkTipsQuery widget is a subclass of GtkLabel which is used to display help about widgets in a user interface.

A query is started with a call to gtk_tips_query_start_query(), usually when some kind of 'Help' button is pressed. The GtkTipsQuery then grabs all events, stopping the user interface from functioning normally. Then as the user moves the mouse over the widgets, the GtkTipsQuery displays each widget's tooltip text.

By connecting to the "widget-entered" or "widget-selected" signals, it is possible to customize the GtkTipsQuery to perform other actions when widgets are entered or selected. For example, a help browser could be opened with documentation on the widget selected.

At some point a call to gtk_tips_query_stop_query() must be made in order to stop the query and return the interface to its normal state. The gtk_tips_query_set_caller() function can be used to specify a widget which the user can select to stop the query (often the same button used to start the query).

Details

GtkTipsQuery

typedef struct _GtkTipsQuery GtkTipsQuery;

Warning

GtkTipsQuery is deprecated and should not be used in newly-written code.

The GtkTipsQuery struct contains private data only, and should be accessed using the functions below.

gtk_tips_query_new ()

GtkWidget*          gtk_tips_query_new                  (void);

Warning

gtk_tips_query_new is deprecated and should not be used in newly-written code.

Creates a new GtkTipsQuery.

Returns : a new GtkTipsQuery.

gtk_tips_query_start_query ()

void                gtk_tips_query_start_query          (GtkTipsQuery *tips_query);

Warning

gtk_tips_query_start_query is deprecated and should not be used in newly-written code.

Starts a query. The GtkTipsQuery widget will take control of the mouse and as the mouse moves it will display the tooltip of the widget beneath the mouse.

tips_query : a GtkTipsQuery.

gtk_tips_query_stop_query ()

void                gtk_tips_query_stop_query           (GtkTipsQuery *tips_query);

Warning

gtk_tips_query_stop_query is deprecated and should not be used in newly-written code.

Stops a query.

tips_query : a GtkTipsQuery.

gtk_tips_query_set_caller ()

void                gtk_tips_query_set_caller           (GtkTipsQuery *tips_query,
                                                         GtkWidget *caller);

Warning

gtk_tips_query_set_caller is deprecated and should not be used in newly-written code.

Sets the widget which initiates the query, usually a button. If the caller is selected while the query is running, the query is automatically stopped.

tips_query : | a GtkTipsQuery.
caller : | the widget which initiates the query.

gtk_tips_query_set_labels ()

void                gtk_tips_query_set_labels           (GtkTipsQuery *tips_query,
                                                         const gchar *label_inactive,
                                                         const gchar *label_no_tip);

Warning

gtk_tips_query_set_labels is deprecated and should not be used in newly-written code.

Sets the text to display when the query is not in effect, and the text to display when the query is in effect but the widget beneath the pointer has no tooltip.

tips_query : | a GtkTipsQuery.
label_inactive : | the text to display when the query is not running.
label_no_tip : | the text to display when the query is running but the widget beneath the pointer has no tooltip.

Property Details

The "caller" property

  "caller"                   GtkWidget             : Read / Write

The widget that starts the tips query, usually a button. If it is selected while the query is in effect the query is automatically stopped.

The "emit-always" property

  "emit-always"              gboolean              : Read / Write

TRUE if the widget-entered and widget-selected signals are emitted even when the widget has no tooltip set.

Default value: FALSE

The "label-inactive" property

  "label-inactive"           gchararray            : Read / Write

The text to display in the GtkTipsQuery widget when the query is not in effect.

Default value: NULL

The "label-no-tip" property

  "label-no-tip"             gchararray            : Read / Write

The text to display in the GtkTipsQuery widget when the query is running and the widget that the pointer is over has no tooltip.

Default value: NULL

Signal Details

The "start-query" signal

void                user_function                      (GtkTipsQuery *tipsquery,
                                                        gpointer      user_data)      : Run First

Emitted when the query is started.

tipsquery : | the object which received the signal.
user_data : | user data set when the signal handler was connected.

The "stop-query" signal

void                user_function                      (GtkTipsQuery *tipsquery,
                                                        gpointer      user_data)      : Run First

Emitted when the query is stopped.

tipsquery : | the object which received the signal.
user_data : | user data set when the signal handler was connected.

The "widget-entered" signal

void                user_function                      (GtkTipsQuery *tipsquery,
                                                        GtkWidget    *widget,
                                                        gchar        *tip_text,
                                                        gchar        *tip_private,
                                                        gpointer      user_data)        : Run Last

Emitted when a widget is entered by the pointer while the query is in effect.

tipsquery : | the object which received the signal.
widget : | the widget that was entered by the pointer.
tip_text : | the widget's tooltip.
tip_private : | the widget's private tooltip (see gtk_tooltips_set_tip()).
user_data : | user data set when the signal handler was connected.

The "widget-selected" signal

gboolean            user_function                      (GtkTipsQuery   *tipsquery,
                                                        GtkWidget      *widget,
                                                        gchar          *tip_text,
                                                        gchar          *tip_private,
                                                        GdkEventButton *event,
                                                        gpointer        user_data)        : Run Last

Emitted when a widget is selected during a query.

tipsquery : | the object which received the signal.
widget : | the widget that was selected.
tip_text : | the widget's tooltip.
tip_private : | the widget's private tooltip (see gtk_tooltips_set_tip()).
event : | the button press or button release event.
user_data : | user data set when the signal handler was connected.
Returns : | TRUE if the query should be stopped.

See Also

GtkTooltips

the object which handles tooltips.


GtkToggleAction

GtkToggleAction — An action which can be toggled between two states

Synopsis

#include <gtk/gtk.h>

                    GtkToggleAction;
GtkToggleAction*    gtk_toggle_action_new               (const gchar *name,
                                                         const gchar *label,
                                                         const gchar *tooltip,
                                                         const gchar *stock_id);
void                gtk_toggle_action_toggled           (GtkToggleAction *action);
void                gtk_toggle_action_set_active        (GtkToggleAction *action,
                                                         gboolean is_active);
gboolean            gtk_toggle_action_get_active        (GtkToggleAction *action);
void                gtk_toggle_action_set_draw_as_radio (GtkToggleAction *action,
                                                         gboolean draw_as_radio);
gboolean            gtk_toggle_action_get_draw_as_radio (GtkToggleAction *action);

Object Hierarchy

  GObject
   +----GtkAction
         +----GtkToggleAction
               +----GtkRadioAction

Properties

  "active"                   gboolean              : Read / Write
  "draw-as-radio"            gboolean              : Read / Write

Signals

  "toggled"                                        : Run First

Description

A GtkToggleAction corresponds roughly to a GtkCheckMenuItem. It has an "active" state specifying whether the action has been checked or not.

Details

GtkToggleAction

typedef struct _GtkToggleAction GtkToggleAction;

The GtkToggleAction struct contains only private members and should not be accessed directly.

gtk_toggle_action_new ()

GtkToggleAction*    gtk_toggle_action_new               (const gchar *name,
                                                         const gchar *label,
                                                         const gchar *tooltip,
                                                         const gchar *stock_id);

Creates a new GtkToggleAction object. To add the action to a GtkActionGroup and set the accelerator for the action, call gtk_action_group_add_action_with_accel().

name : | A unique name for the action
label : | The label displayed in menu items and on buttons
tooltip : | A tooltip for the action
stock_id : | The stock icon to display in widgets representing the action
Returns : | a new GtkToggleAction

Since 2.4

gtk_toggle_action_toggled ()

void                gtk_toggle_action_toggled           (GtkToggleAction *action);

Emits the "toggled" signal on the toggle action.

action : the action object

Since 2.4

gtk_toggle_action_set_active ()

void                gtk_toggle_action_set_active        (GtkToggleAction *action,
                                                         gboolean is_active);

Sets the checked state on the toggle action.

action : | the action object
is_active : | whether the action should be checked or not

Since 2.4

gtk_toggle_action_get_active ()

gboolean            gtk_toggle_action_get_active        (GtkToggleAction *action);

Returns the checked state of the toggle action.

action : | the action object
Returns : | the checked state of the toggle action

Since 2.4

gtk_toggle_action_set_draw_as_radio ()

void                gtk_toggle_action_set_draw_as_radio (GtkToggleAction *action,
                                                         gboolean draw_as_radio);

Sets whether the action should have proxies like a radio action.

action : | the action object
draw_as_radio : | whether the action should have proxies like a radio action

Since 2.4

gtk_toggle_action_get_draw_as_radio ()

gboolean            gtk_toggle_action_get_draw_as_radio (GtkToggleAction *action);

Returns whether the action should have proxies like a radio action.

action : | the action object
Returns : | whether the action should have proxies like a radio action.

Since 2.4

Property Details

The "active" property

  "active"                   gboolean              : Read / Write

If the toggle action should be active in or not.

Default value: FALSE

Since 2.10

The "draw-as-radio" property

  "draw-as-radio"            gboolean              : Read / Write

Whether the proxies for this action look like radio action proxies.

Default value: FALSE

Signal Details

The "toggled" signal

void                user_function                      (GtkToggleAction *toggleaction,
                                                        gpointer         user_data)         : Run First

toggleaction : | the object which received the signal.
user_data : | user data set when the signal handler was connected.


GtkToggleButton

GtkToggleButton — Create buttons which retain their state

Synopsis

#include <gtk/gtk.h>

                    GtkToggleButton;
GtkWidget*          gtk_toggle_button_new               (void);
GtkWidget*          gtk_toggle_button_new_with_label    (const gchar *label);
GtkWidget*          gtk_toggle_button_new_with_mnemonic (const gchar *label);
void                gtk_toggle_button_set_mode          (GtkToggleButton *toggle_button,
                                                         gboolean draw_indicator);
gboolean            gtk_toggle_button_get_mode          (GtkToggleButton *toggle_button);
#define             gtk_toggle_button_set_state
void                gtk_toggle_button_toggled           (GtkToggleButton *toggle_button);
gboolean            gtk_toggle_button_get_active        (GtkToggleButton *toggle_button);
void                gtk_toggle_button_set_active        (GtkToggleButton *toggle_button,
                                                         gboolean is_active);
gboolean            gtk_toggle_button_get_inconsistent  (GtkToggleButton *toggle_button);
void                gtk_toggle_button_set_inconsistent  (GtkToggleButton *toggle_button,
                                                         gboolean setting);

Object Hierarchy

  GObject
   +----GInitiallyUnowned
         +----GtkObject
               +----GtkWidget
                     +----GtkContainer
                           +----GtkBin
                                 +----GtkButton
                                       +----GtkToggleButton
                                             +----GtkCheckButton

Implemented Interfaces

GtkToggleButton implements AtkImplementorIface.

Properties

  "active"                   gboolean              : Read / Write
  "draw-indicator"           gboolean              : Read / Write
  "inconsistent"             gboolean              : Read / Write

Signals

  "toggled"                                        : Run First

Description

A GtkToggleButton is a GtkButton which will remain 'pressed-in' when clicked. Clicking again will cause the toggle button to return to its normal state.

A toggle button is created by calling either gtk_toggle_button_new() or gtk_toggle_button_new_with_label(). If using the former, it is advisable to pack a widget, (such as a GtkLabel and/or a GtkPixmap), into the toggle button's container. (See GtkButton for more information).

The state of a GtkToggleButton can be set specifically using gtk_toggle_button_set_active(), and retrieved using gtk_toggle_button_get_active().

To simply switch the state of a toggle button, use gtk_toggle_button_toggled.

Example 10. Creating two GtkToggleButton widgets.

void make_toggles (void) {
   GtkWidget *dialog, *toggle1, *toggle2;

   dialog = gtk_dialog_new ();
   toggle1 = gtk_toggle_button_new_with_label ("Hi, i'm a toggle button.");

   /* Makes this toggle button invisible */
   gtk_toggle_button_set_mode (GTK_TOGGLE_BUTTON (toggle1), TRUE);

   g_signal_connect (toggle1, "toggled",
                     G_CALLBACK (output_state), NULL);
   gtk_box_pack_start (GTK_BOX (GTK_DIALOG (dialog)->action_area),
                       toggle1, FALSE, FALSE, 2);

   toggle2 = gtk_toggle_button_new_with_label ("Hi, i'm another toggle button.");
   gtk_toggle_button_set_mode (GTK_TOGGLE_BUTTON (toggle2), FALSE);
   g_signal_connect (toggle2, "toggled",
                     G_CALLBACK (output_state), NULL);
   gtk_box_pack_start (GTK_BOX (GTK_DIALOG (dialog)->action_area),
                       toggle2, FALSE, FALSE, 2);

   gtk_widget_show_all (dialog);
}

Details

GtkToggleButton

typedef struct _GtkToggleButton GtkToggleButton;

The GtkToggleButton struct contains private data only, and should be manipulated using the functions below.

gtk_toggle_button_new ()

GtkWidget*          gtk_toggle_button_new               (void);

Creates a new toggle button. A widget should be packed into the button, as in gtk_button_new().

Returns : a new toggle button.

gtk_toggle_button_new_with_label ()

GtkWidget*          gtk_toggle_button_new_with_label    (const gchar *label);

Creates a new toggle button with a text label.

label : | a string containing the message to be placed in the toggle button.
Returns : | a new toggle button.

gtk_toggle_button_new_with_mnemonic ()

GtkWidget*          gtk_toggle_button_new_with_mnemonic (const gchar *label);

Creates a new GtkToggleButton containing a label. The label will be created using gtk_label_new_with_mnemonic(), so underscores in label indicate the mnemonic for the button.

label : | the text of the button, with an underscore in front of the mnemonic character
Returns : | a new GtkToggleButton

gtk_toggle_button_set_mode ()

void                gtk_toggle_button_set_mode          (GtkToggleButton *toggle_button,
                                                         gboolean draw_indicator);

Sets whether the button is displayed as a separate indicator and label. You can call this function on a checkbutton or a radiobutton with draw_indicator = FALSE to make the button look like a normal button

This function only affects instances of classes like GtkCheckButton and GtkRadioButton that derive from GtkToggleButton, not instances of GtkToggleButton itself.

toggle_button : | a GtkToggleButton
draw_indicator : | if TRUE, draw the button as a separate indicator and label; if FALSE, draw the button like a normal button

gtk_toggle_button_get_mode ()

gboolean            gtk_toggle_button_get_mode          (GtkToggleButton *toggle_button);

Retrieves whether the button is displayed as a separate indicator and label. See gtk_toggle_button_set_mode().

toggle_button : | a GtkToggleButton
Returns : | TRUE if the togglebutton is drawn as a separate indicator and label.

gtk_toggle_button_set_state

#define	gtk_toggle_button_set_state		gtk_toggle_button_set_active

Warning

gtk_toggle_button_set_state is deprecated and should not be used in newly-written code.

This is a deprecated macro, and is only maintained for compatibility reasons.

gtk_toggle_button_toggled ()

void                gtk_toggle_button_toggled           (GtkToggleButton *toggle_button);

Emits the toggled signal on the GtkToggleButton. There is no good reason for an application ever to call this function.

toggle_button : a GtkToggleButton.

gtk_toggle_button_get_active ()

gboolean            gtk_toggle_button_get_active        (GtkToggleButton *toggle_button);

Queries a GtkToggleButton and returns its current state. Returns TRUE if the toggle button is pressed in and FALSE if it is raised.

toggle_button : | a GtkToggleButton.
Returns : | a gboolean value.

gtk_toggle_button_set_active ()

void                gtk_toggle_button_set_active        (GtkToggleButton *toggle_button,
                                                         gboolean is_active);

Sets the status of the toggle button. Set to TRUE if you want the GtkToggleButton to be 'pressed in', and FALSE to raise it. This action causes the toggled signal to be emitted.

toggle_button : | a GtkToggleButton.
is_active : | TRUE or FALSE.

gtk_toggle_button_get_inconsistent ()

gboolean            gtk_toggle_button_get_inconsistent  (GtkToggleButton *toggle_button);

Gets the value set by gtk_toggle_button_set_inconsistent().

toggle_button : | a GtkToggleButton
Returns : | TRUE if the button is displayed as inconsistent, FALSE otherwise

gtk_toggle_button_set_inconsistent ()

void                gtk_toggle_button_set_inconsistent  (GtkToggleButton *toggle_button,
                                                         gboolean setting);

If the user has selected a range of elements (such as some text or spreadsheet cells) that are affected by a toggle button, and the current values in that range are inconsistent, you may want to display the toggle in an "in between" state. This function turns on "in between" display. Normally you would turn off the inconsistent state again if the user toggles the toggle button. This has to be done manually, gtk_toggle_button_set_inconsistent() only affects visual appearance, it doesn't affect the semantics of the button.

toggle_button : | a GtkToggleButton
setting : | TRUE if state is inconsistent

Property Details

The "active" property

  "active"                   gboolean              : Read / Write

If the toggle button should be pressed in or not.

Default value: FALSE

The "draw-indicator" property

  "draw-indicator"           gboolean              : Read / Write

If the toggle part of the button is displayed.

Default value: FALSE

The "inconsistent" property

  "inconsistent"             gboolean              : Read / Write

If the toggle button is in an "in between" state.

Default value: FALSE

Signal Details

The "toggled" signal

void                user_function                      (GtkToggleButton *togglebutton,
                                                        gpointer         user_data)         : Run First

Should be connected if you wish to perform an action whenever the GtkToggleButton's state is changed.

togglebutton : | the object which received the signal.
user_data : | user data set when the signal handler was connected.

See Also

GtkButton | a more general button.
GtkCheckButton | another way of presenting a toggle option.
GtkCheckMenuItem | a GtkToggleButton as a menu item.


GtkToggleToolButton

GtkToggleToolButton — A GtkToolItem containing a toggle button

Synopsis

#include <gtk/gtk.h>

                    GtkToggleToolButton;
GtkToolItem*        gtk_toggle_tool_button_new          (void);
GtkToolItem*        gtk_toggle_tool_button_new_from_stock
                                                        (const gchar *stock_id);
void                gtk_toggle_tool_button_set_active   (GtkToggleToolButton *button,
                                                         gboolean is_active);
gboolean            gtk_toggle_tool_button_get_active   (GtkToggleToolButton *button);

Object Hierarchy

  GObject
   +----GInitiallyUnowned
         +----GtkObject
               +----GtkWidget
                     +----GtkContainer
                           +----GtkBin
                                 +----GtkToolItem
                                       +----GtkToolButton
                                             +----GtkToggleToolButton
                                                   +----GtkRadioToolButton

Implemented Interfaces

GtkToggleToolButton implements AtkImplementorIface.

Properties

  "active"                   gboolean              : Read / Write

Signals

  "toggled"                                        : Run First

Description

A GtkToggleToolButton is a GtkToolItem that contains a toggle button.

Use gtk_toggle_tool_button_new() to create a new GtkToggleToolButton. Use gtk_toggle_tool_button_new_from_stock() to create a new GtkToggleToolButton containing a stock item.

Details

GtkToggleToolButton

typedef struct _GtkToggleToolButton GtkToggleToolButton;

The GtkToggleToolButton struct contains only private data and should only be accessed through the functions described below.

gtk_toggle_tool_button_new ()

GtkToolItem*        gtk_toggle_tool_button_new          (void);

Returns a new GtkToggleToolButton

Returns : a newly created GtkToggleToolButton

Since 2.4

gtk_toggle_tool_button_new_from_stock ()

GtkToolItem*        gtk_toggle_tool_button_new_from_stock
                                                        (const gchar *stock_id);

Creates a new GtkToggleToolButton containing the image and text from a stock item. Some stock ids have preprocessor macros like GTK_STOCK_OK and GTK_STOCK_APPLY.

It is an error if stock_id is not a name of a stock item.

stock_id : | the name of the stock item
Returns : | A new GtkToggleToolButton

Since 2.4

gtk_toggle_tool_button_set_active ()

void                gtk_toggle_tool_button_set_active   (GtkToggleToolButton *button,
                                                         gboolean is_active);

Sets the status of the toggle tool button. Set to TRUE if you want the GtkToggleButton to be 'pressed in', and FALSE to raise it. This action causes the toggled signal to be emitted.

button : | a GtkToggleToolButton
is_active : | whether button should be active

Since 2.4

gtk_toggle_tool_button_get_active ()

gboolean            gtk_toggle_tool_button_get_active   (GtkToggleToolButton *button);

Queries a GtkToggleToolButton and returns its current state. Returns TRUE if the toggle button is pressed in and FALSE if it is raised.

button : | a GtkToggleToolButton
Returns : | TRUE if the toggle tool button is pressed in, FALSE if not

Since 2.4

Property Details

The "active" property

  "active"                   gboolean              : Read / Write

If the toggle tool button should be pressed in or not.

Default value: FALSE

Since 2.8

Signal Details

The "toggled" signal

void                user_function                      (GtkToggleToolButton *toggle_tool_button,
                                                        gpointer             user_data)               : Run First

Emitted whenever the toggle tool button changes state.

toggle_tool_button : | the object that emitted the signal
user_data : | user data set when the signal handler was connected.

See Also

GtkToolbar, GtkToolButton, GtkSeparatorToolItem

The toolbar widget

The parent class of GtkToggleToolButton. The properties "label_widget", "label", "icon_widget", and "stock_id" on GtkToolButton determine the label and icon used on GtkToggleToolButtons.

A subclass of GtkToolItem that separates groups of items on a toolbar.


GtkToolbar

GtkToolbar — Create bars of buttons and other widgets

Synopsis

#include <gtk/gtk.h>

                    GtkToolbar;
enum                GtkToolbarChildType;
enum                GtkToolbarSpaceStyle;
                    GtkToolbarChild;
GtkWidget*          gtk_toolbar_new                     (void);
void                gtk_toolbar_insert                  (GtkToolbar *toolbar,
                                                         GtkToolItem *item,
                                                         gint pos);
gint                gtk_toolbar_get_item_index          (GtkToolbar *toolbar,
                                                         GtkToolItem *item);
gint                gtk_toolbar_get_n_items             (GtkToolbar *toolbar);
GtkToolItem*        gtk_toolbar_get_nth_item            (GtkToolbar *toolbar,
                                                         gint n);
gint                gtk_toolbar_get_drop_index          (GtkToolbar *toolbar,
                                                         gint x,
                                                         gint y);
void                gtk_toolbar_set_drop_highlight_item (GtkToolbar *toolbar,
                                                         GtkToolItem *tool_item,
                                                         gint index_);
void                gtk_toolbar_set_show_arrow          (GtkToolbar *toolbar,
                                                         gboolean show_arrow);
void                gtk_toolbar_set_orientation         (GtkToolbar *toolbar,
                                                         GtkOrientation orientation);
void                gtk_toolbar_set_tooltips            (GtkToolbar *toolbar,
                                                         gboolean enable);
void                gtk_toolbar_unset_icon_size         (GtkToolbar *toolbar);
gboolean            gtk_toolbar_get_show_arrow          (GtkToolbar *toolbar);
GtkOrientation      gtk_toolbar_get_orientation         (GtkToolbar *toolbar);
GtkToolbarStyle     gtk_toolbar_get_style               (GtkToolbar *toolbar);
GtkIconSize         gtk_toolbar_get_icon_size           (GtkToolbar *toolbar);
gboolean            gtk_toolbar_get_tooltips            (GtkToolbar *toolbar);
GtkReliefStyle      gtk_toolbar_get_relief_style        (GtkToolbar *toolbar);
GtkWidget*          gtk_toolbar_append_item             (GtkToolbar *toolbar,
                                                         const char *text,
                                                         const char *tooltip_text,
                                                         const char *tooltip_private_text,
                                                         GtkWidget *icon,
                                                         GtkSignalFunc callback,
                                                         gpointer user_data);
GtkWidget*          gtk_toolbar_prepend_item            (GtkToolbar *toolbar,
                                                         const char *text,
                                                         const char *tooltip_text,
                                                         const char *tooltip_private_text,
                                                         GtkWidget *icon,
                                                         GtkSignalFunc callback,
                                                         gpointer user_data);
GtkWidget*          gtk_toolbar_insert_item             (GtkToolbar *toolbar,
                                                         const char *text,
                                                         const char *tooltip_text,
                                                         const char *tooltip_private_text,
                                                         GtkWidget *icon,
                                                         GtkSignalFunc callback,
                                                         gpointer user_data,
                                                         gint position);
void                gtk_toolbar_append_space            (GtkToolbar *toolbar);
void                gtk_toolbar_prepend_space           (GtkToolbar *toolbar);
void                gtk_toolbar_insert_space            (GtkToolbar *toolbar,
                                                         gint position);
GtkWidget*          gtk_toolbar_append_element          (GtkToolbar *toolbar,
                                                         GtkToolbarChildType type,
                                                         GtkWidget *widget,
                                                         const char *text,
                                                         const char *tooltip_text,
                                                         const char *tooltip_private_text,
                                                         GtkWidget *icon,
                                                         GtkSignalFunc callback,
                                                         gpointer user_data);
GtkWidget*          gtk_toolbar_prepend_element         (GtkToolbar *toolbar,
                                                         GtkToolbarChildType type,
                                                         GtkWidget *widget,
                                                         const char *text,
                                                         const char *tooltip_text,
                                                         const char *tooltip_private_text,
                                                         GtkWidget *icon,
                                                         GtkSignalFunc callback,
                                                         gpointer user_data);
GtkWidget*          gtk_toolbar_insert_element          (GtkToolbar *toolbar,
                                                         GtkToolbarChildType type,
                                                         GtkWidget *widget,
                                                         const char *text,
                                                         const char *tooltip_text,
                                                         const char *tooltip_private_text,
                                                         GtkWidget *icon,
                                                         GtkSignalFunc callback,
                                                         gpointer user_data,
                                                         gint position);
void                gtk_toolbar_append_widget           (GtkToolbar *toolbar,
                                                         GtkWidget *widget,
                                                         const char *tooltip_text,
                                                         const char *tooltip_private_text);
void                gtk_toolbar_prepend_widget          (GtkToolbar *toolbar,
                                                         GtkWidget *widget,
                                                         const char *tooltip_text,
                                                         const char *tooltip_private_text);
void                gtk_toolbar_insert_widget           (GtkToolbar *toolbar,
                                                         GtkWidget *widget,
                                                         const char *tooltip_text,
                                                         const char *tooltip_private_text,
                                                         gint position);
void                gtk_toolbar_set_style               (GtkToolbar *toolbar,
                                                         GtkToolbarStyle style);
GtkWidget*          gtk_toolbar_insert_stock            (GtkToolbar *toolbar,
                                                         const gchar *stock_id,
                                                         const char *tooltip_text,
                                                         const char *tooltip_private_text,
                                                         GtkSignalFunc callback,
                                                         gpointer user_data,
                                                         gint position);
void                gtk_toolbar_set_icon_size           (GtkToolbar *toolbar,
                                                         GtkIconSize icon_size);
void                gtk_toolbar_remove_space            (GtkToolbar *toolbar,
                                                         gint position);
void                gtk_toolbar_unset_style             (GtkToolbar *toolbar);

Object Hierarchy

  GObject
   +----GInitiallyUnowned
         +----GtkObject
               +----GtkWidget
                     +----GtkContainer
                           +----GtkToolbar

Implemented Interfaces

GtkToolbar implements AtkImplementorIface.

Properties

  "icon-size"                GtkIconSize           : Read / Write
  "icon-size-set"            gboolean              : Read / Write
  "orientation"              GtkOrientation        : Read / Write
  "show-arrow"               gboolean              : Read / Write
  "toolbar-style"            GtkToolbarStyle       : Read / Write
  "tooltips"                 gboolean              : Read / Write

Child Properties

  "expand"                   gboolean              : Read / Write
  "homogeneous"              gboolean              : Read / Write

Style Properties

  "button-relief"            GtkReliefStyle        : Read
  "internal-padding"         gint                  : Read
  "max-child-expand"         gint                  : Read
  "shadow-type"              GtkShadowType         : Read
  "space-size"               gint                  : Read
  "space-style"              GtkToolbarSpaceStyle  : Read

Signals

  "focus-home-or-end"                              : Run Last / Action
  "move-focus"                                     : Run Last / Action
  "orientation-changed"                            : Run First
  "popup-context-menu"                             : Run Last
  "style-changed"                                  : Run First

Description

A toolbar is created with a call to gtk_toolbar_new().

A toolbar can contain instances of a subclass of GtkToolItem. To add a GtkToolItem to the a toolbar, use gtk_toolbar_insert(). To remove an item from the toolbar use gtk_container_remove(). To add a button to the toolbar, add an instance of GtkToolButton.

Toolbar items can be visually grouped by adding instances of GtkSeparatorToolItem to the toolbar. If a GtkSeparatorToolItem has the "expand" property set to TRUE and the "draw" property set to FALSE the effect is to force all following items to the end of the toolbar.

Creating a context menu for the toolbar can be done by connecting to the GtkToolbar::popup-context-menu signal.

Details

GtkToolbar

typedef struct {
  gint             num_children;
  GList           *children;
  GtkOrientation   orientation;
  GtkToolbarStyle  style;
  GtkIconSize      icon_size;

  GtkTooltips     *tooltips;
} GtkToolbar;

The GtkToolbar struct only contains private data and should only be accessed through the function described below.

enum GtkToolbarChildType

typedef enum
{
  GTK_TOOLBAR_CHILD_SPACE,
  GTK_TOOLBAR_CHILD_BUTTON,
  GTK_TOOLBAR_CHILD_TOGGLEBUTTON,
  GTK_TOOLBAR_CHILD_RADIOBUTTON,
  GTK_TOOLBAR_CHILD_WIDGET
} GtkToolbarChildType;

Warning

GtkToolbarChildType is deprecated and should not be used in newly-written code.

GtkToolbarChildType is used to set the type of new elements that are added to a GtkToolbar.

GTK_TOOLBAR_CHILD_SPACE | a space in the style of the toolbar's GtkToolbarSpaceStyle.
GTK_TOOLBAR_CHILD_BUTTON | a GtkButton.
GTK_TOOLBAR_CHILD_TOGGLEBUTTON | a GtkToggleButton.
GTK_TOOLBAR_CHILD_RADIOBUTTON | a GtkRadioButton.
GTK_TOOLBAR_CHILD_WIDGET | a standard GtkWidget.

enum GtkToolbarSpaceStyle

typedef enum
{
  GTK_TOOLBAR_SPACE_EMPTY,
  GTK_TOOLBAR_SPACE_LINE
} GtkToolbarSpaceStyle;

GtkToolbarChild

typedef struct {
  GtkToolbarChildType type;
  GtkWidget *widget;
  GtkWidget *icon;
  GtkWidget *label;
} GtkToolbarChild;

Warning

GtkToolbarChild is deprecated and should not be used in newly-written code.

gtk_toolbar_new ()

GtkWidget*          gtk_toolbar_new                     (void);

Creates a new toolbar.

Returns : the newly-created toolbar.

gtk_toolbar_insert ()

void                gtk_toolbar_insert                  (GtkToolbar *toolbar,
                                                         GtkToolItem *item,
                                                         gint pos);

Insert a GtkToolItem into the toolbar at position pos. If pos is 0 the item is prepended to the start of the toolbar. If pos is negative, the item is appended to the end of the toolbar.

toolbar : | a GtkToolbar
item : | a GtkToolItem
pos : | the position of the new item

Since 2.4

gtk_toolbar_get_item_index ()

gint                gtk_toolbar_get_item_index          (GtkToolbar *toolbar,
                                                         GtkToolItem *item);

Returns the position of item on the toolbar, starting from 0. It is an error if item is not a child of the toolbar.

toolbar : | a GtkToolbar
item : | a GtkToolItem that is a child of toolbar
Returns : | the position of item on the toolbar.

Since 2.4

gtk_toolbar_get_n_items ()

gint                gtk_toolbar_get_n_items             (GtkToolbar *toolbar);

Returns the number of items on the toolbar.

toolbar : | a GtkToolbar
Returns : | the number of items on the toolbar

Since 2.4

gtk_toolbar_get_nth_item ()

GtkToolItem*        gtk_toolbar_get_nth_item            (GtkToolbar *toolbar,
                                                         gint n);

Returns the n'th item on toolbar, or NULL if the toolbar does not contain an n'th item.

toolbar : | a GtkToolbar
n : | A position on the toolbar
Returns : | The n'th GtkToolItem on toolbar, or NULL if there isn't an n'th item.

Since 2.4

gtk_toolbar_get_drop_index ()

gint                gtk_toolbar_get_drop_index          (GtkToolbar *toolbar,
                                                         gint x,
                                                         gint y);

Returns the position corresponding to the indicated point on toolbar. This is useful when dragging items to the toolbar: this function returns the position a new item should be inserted.

x and y are in toolbar coordinates.

toolbar : | a GtkToolbar
x : | x coordinate of a point on the toolbar
y : | y coordinate of a point on the toolbar
Returns : | The position corresponding to the point (x, y) on the toolbar.

Since 2.4

gtk_toolbar_set_drop_highlight_item ()

void                gtk_toolbar_set_drop_highlight_item (GtkToolbar *toolbar,
                                                         GtkToolItem *tool_item,
                                                         gint index_);

Highlights toolbar to give an idea of what it would look like if item was added to toolbar at the position indicated by index_. If item is NULL, highlighting is turned off. In that case index_ is ignored.

The tool_item passed to this function must not be part of any widget hierarchy. When an item is set as drop highlight item it can not added to any widget hierarchy or used as highlight item for another toolbar.

toolbar : | a GtkToolbar
tool_item : | a GtkToolItem, or NULL to turn of highlighting
index_ : | a position on toolbar

Since 2.4

gtk_toolbar_set_show_arrow ()

void                gtk_toolbar_set_show_arrow          (GtkToolbar *toolbar,
                                                         gboolean show_arrow);

Sets whether to show an overflow menu when toolbar doesn't have room for all items on it. If TRUE, items that there are not room are available through an overflow menu.

toolbar : | a GtkToolbar
show_arrow : | Whether to show an overflow menu

Since 2.4

gtk_toolbar_set_orientation ()

void                gtk_toolbar_set_orientation         (GtkToolbar *toolbar,
                                                         GtkOrientation orientation);

Sets whether a toolbar should appear horizontally or vertically.

toolbar : | a GtkToolbar.
orientation : | a new GtkOrientation.

gtk_toolbar_set_tooltips ()

void                gtk_toolbar_set_tooltips            (GtkToolbar *toolbar,
                                                         gboolean enable);

Sets if the tooltips of a toolbar should be active or not.

toolbar : | a GtkToolbar.
enable : | set to FALSE to disable the tooltips, or TRUE to enable them.

gtk_toolbar_unset_icon_size ()

void                gtk_toolbar_unset_icon_size         (GtkToolbar *toolbar);

Warning

gtk_toolbar_unset_icon_size is deprecated and should not be used in newly-written code.

Unsets toolbar icon size set with gtk_toolbar_set_icon_size(), so that user preferences will be used to determine the icon size.

toolbar : a GtkToolbar

gtk_toolbar_get_show_arrow ()

gboolean            gtk_toolbar_get_show_arrow          (GtkToolbar *toolbar);

Returns whether the toolbar has an overflow menu. See gtk_toolbar_set_show_arrow().

toolbar : | a GtkToolbar
Returns : | TRUE if the toolbar has an overflow menu.

Since 2.4

gtk_toolbar_get_orientation ()

GtkOrientation      gtk_toolbar_get_orientation         (GtkToolbar *toolbar);

Retrieves the current orientation of the toolbar. See gtk_toolbar_set_orientation().

toolbar : | a GtkToolbar
Returns : | the orientation

gtk_toolbar_get_style ()

GtkToolbarStyle     gtk_toolbar_get_style               (GtkToolbar *toolbar);

Retrieves whether the toolbar has text, icons, or both . See gtk_toolbar_set_style().

toolbar : | a GtkToolbar
Returns : | the current style of toolbar

gtk_toolbar_get_icon_size ()

GtkIconSize         gtk_toolbar_get_icon_size           (GtkToolbar *toolbar);

Retrieves the icon size for the toolbar. See gtk_toolbar_set_icon_size().

toolbar : | a GtkToolbar
Returns : | the current icon size for the icons on the toolbar.

gtk_toolbar_get_tooltips ()

gboolean            gtk_toolbar_get_tooltips            (GtkToolbar *toolbar);

Retrieves whether tooltips are enabled. See gtk_toolbar_set_tooltips().

toolbar : | a GtkToolbar
Returns : | TRUE if tooltips are enabled

gtk_toolbar_get_relief_style ()

GtkReliefStyle      gtk_toolbar_get_relief_style        (GtkToolbar *toolbar);

Returns the relief style of buttons on toolbar. See gtk_button_set_relief().

toolbar : | a GtkToolbar
Returns : | The relief style of buttons on toolbar.

Since 2.4

gtk_toolbar_append_item ()

GtkWidget*          gtk_toolbar_append_item             (GtkToolbar *toolbar,
                                                         const char *text,
                                                         const char *tooltip_text,
                                                         const char *tooltip_private_text,
                                                         GtkWidget *icon,
                                                         GtkSignalFunc callback,
                                                         gpointer user_data);

Warning

gtk_toolbar_append_item is deprecated and should not be used in newly-written code.

Inserts a new item into the toolbar. You must specify the position in the toolbar where it will be inserted.

callback must be a pointer to a function taking a GtkWidget and a gpointer as arguments. Use the GTK_SIGNAL_FUNC() to cast the function to GtkSignalFunc.

toolbar : | a GtkToolbar.
text : | give your toolbar button a label.
tooltip_text : | a string that appears when the user holds the mouse over this item.
tooltip_private_text : | use with GtkTipsQuery.
icon : | a GtkWidget that should be used as the button's icon.
callback : | the function to be executed when the button is pressed.
user_data : | a pointer to any data you wish to be passed to the callback.
Returns : | the new toolbar item as a GtkWidget.

gtk_toolbar_prepend_item ()

GtkWidget*          gtk_toolbar_prepend_item            (GtkToolbar *toolbar,
                                                         const char *text,
                                                         const char *tooltip_text,
                                                         const char *tooltip_private_text,
                                                         GtkWidget *icon,
                                                         GtkSignalFunc callback,
                                                         gpointer user_data);

Warning

gtk_toolbar_prepend_item is deprecated and should not be used in newly-written code.

Adds a new button to the beginning (top or left edges) of the given toolbar.

callback must be a pointer to a function taking a GtkWidget and a gpointer as arguments. Use the GTK_SIGNAL_FUNC() to cast the function to GtkSignalFunc.

toolbar : | a GtkToolbar.
text : | give your toolbar button a label.
tooltip_text : | a string that appears when the user holds the mouse over this item.
tooltip_private_text : | use with GtkTipsQuery.
icon : | a GtkWidget that should be used as the button's icon.
callback : | the function to be executed when the button is pressed.
user_data : | a pointer to any data you wish to be passed to the callback.
Returns : | the new toolbar item as a GtkWidget.

gtk_toolbar_insert_item ()

GtkWidget*          gtk_toolbar_insert_item             (GtkToolbar *toolbar,
                                                         const char *text,
                                                         const char *tooltip_text,
                                                         const char *tooltip_private_text,
                                                         GtkWidget *icon,
                                                         GtkSignalFunc callback,
                                                         gpointer user_data,
                                                         gint position);

Warning

gtk_toolbar_insert_item is deprecated and should not be used in newly-written code.

Inserts a new item into the toolbar. You must specify the position in the toolbar where it will be inserted.

callback must be a pointer to a function taking a GtkWidget and a gpointer as arguments. Use the GTK_SIGNAL_FUNC() to cast the function to GtkSignalFunc.

toolbar : | a GtkToolbar.
text : | give your toolbar button a label.
tooltip_text : | a string that appears when the user holds the mouse over this item.
tooltip_private_text : | use with GtkTipsQuery.
icon : | a GtkWidget that should be used as the button's icon.
callback : | the function to be executed when the button is pressed.
user_data : | a pointer to any data you wish to be passed to the callback.
position : | the number of widgets to insert this item after.
Returns : | the new toolbar item as a GtkWidget.

gtk_toolbar_append_space ()

void                gtk_toolbar_append_space            (GtkToolbar *toolbar);

Warning

gtk_toolbar_append_space is deprecated and should not be used in newly-written code.

Adds a new space to the end of the toolbar.

toolbar : a GtkToolbar.

gtk_toolbar_prepend_space ()

void                gtk_toolbar_prepend_space           (GtkToolbar *toolbar);

Warning

gtk_toolbar_prepend_space is deprecated and should not be used in newly-written code.

Adds a new space to the beginning of the toolbar.

toolbar : a GtkToolbar.

gtk_toolbar_insert_space ()

void                gtk_toolbar_insert_space            (GtkToolbar *toolbar,
                                                         gint position);

Warning

gtk_toolbar_insert_space is deprecated and should not be used in newly-written code.

Inserts a new space in the toolbar at the specified position.

toolbar : | a GtkToolbar
position : | the number of widgets after which a space should be inserted.

gtk_toolbar_append_element ()

GtkWidget*          gtk_toolbar_append_element          (GtkToolbar *toolbar,
                                                         GtkToolbarChildType type,
                                                         GtkWidget *widget,
                                                         const char *text,
                                                         const char *tooltip_text,
                                                         const char *tooltip_private_text,
                                                         GtkWidget *icon,
                                                         GtkSignalFunc callback,
                                                         gpointer user_data);

Warning

gtk_toolbar_append_element is deprecated and should not be used in newly-written code.

Adds a new element to the end of a toolbar.

If type == GTK_TOOLBAR_CHILD_WIDGET, widget is used as the new element. If type == GTK_TOOLBAR_CHILD_RADIOBUTTON, widget is used to determine the radio group for the new element. In all other cases, widget must be NULL.

callback must be a pointer to a function taking a GtkWidget and a gpointer as arguments. Use the GTK_SIGNAL_FUNC() to cast the function to GtkSignalFunc.

toolbar : | a GtkToolbar.
type : | a value of type GtkToolbarChildType that determines what widget will be.
widget : | a GtkWidget, or NULL.
text : | the element's label.
tooltip_text : | the element's tooltip.
tooltip_private_text : | used for context-sensitive help about this toolbar element.
icon : | a GtkWidget that provides pictorial representation of the element's function.
callback : | the function to be executed when the button is pressed.
user_data : | any data you wish to pass to the callback.
Returns : | the new toolbar element as a GtkWidget.

gtk_toolbar_prepend_element ()

GtkWidget*          gtk_toolbar_prepend_element         (GtkToolbar *toolbar,
                                                         GtkToolbarChildType type,
                                                         GtkWidget *widget,
                                                         const char *text,
                                                         const char *tooltip_text,
                                                         const char *tooltip_private_text,
                                                         GtkWidget *icon,
                                                         GtkSignalFunc callback,
                                                         gpointer user_data);

Warning

gtk_toolbar_prepend_element is deprecated and should not be used in newly-written code.

Adds a new element to the beginning of a toolbar.

If type == GTK_TOOLBAR_CHILD_WIDGET, widget is used as the new element. If type == GTK_TOOLBAR_CHILD_RADIOBUTTON, widget is used to determine the radio group for the new element. In all other cases, widget must be NULL.

callback must be a pointer to a function taking a GtkWidget and a gpointer as arguments. Use the GTK_SIGNAL_FUNC() to cast the function to GtkSignalFunc.

toolbar : | a GtkToolbar.
type : | a value of type GtkToolbarChildType that determines what widget will be.
widget : | a GtkWidget, or NULL
text : | the element's label.
tooltip_text : | the element's tooltip.
tooltip_private_text : | used for context-sensitive help about this toolbar element.
icon : | a GtkWidget that provides pictorial representation of the element's function.
callback : | the function to be executed when the button is pressed.
user_data : | any data you wish to pass to the callback.
Returns : | the new toolbar element as a GtkWidget.

gtk_toolbar_insert_element ()

GtkWidget*          gtk_toolbar_insert_element          (GtkToolbar *toolbar,
                                                         GtkToolbarChildType type,
                                                         GtkWidget *widget,
                                                         const char *text,
                                                         const char *tooltip_text,
                                                         const char *tooltip_private_text,
                                                         GtkWidget *icon,
                                                         GtkSignalFunc callback,
                                                         gpointer user_data,
                                                         gint position);

Warning

gtk_toolbar_insert_element is deprecated and should not be used in newly-written code.

Inserts a new element in the toolbar at the given position.

If type == GTK_TOOLBAR_CHILD_WIDGET, widget is used as the new element. If type == GTK_TOOLBAR_CHILD_RADIOBUTTON, widget is used to determine the radio group for the new element. In all other cases, widget must be NULL.

callback must be a pointer to a function taking a GtkWidget and a gpointer as arguments. Use the GTK_SIGNAL_FUNC() to cast the function to GtkSignalFunc.

toolbar : | a GtkToolbar.
type : | a value of type GtkToolbarChildType that determines what widget will be.
widget : | a GtkWidget, or NULL.
text : | the element's label.
tooltip_text : | the element's tooltip.
tooltip_private_text : | used for context-sensitive help about this toolbar element.
icon : | a GtkWidget that provides pictorial representation of the element's function.
callback : | the function to be executed when the button is pressed.
user_data : | any data you wish to pass to the callback.
position : | the number of widgets to insert this element after.
Returns : | the new toolbar element as a GtkWidget.

gtk_toolbar_append_widget ()

void                gtk_toolbar_append_widget           (GtkToolbar *toolbar,
                                                         GtkWidget *widget,
                                                         const char *tooltip_text,
                                                         const char *tooltip_private_text);

Warning

gtk_toolbar_append_widget is deprecated and should not be used in newly-written code.

Adds a widget to the end of the given toolbar.

toolbar : | a GtkToolbar.
widget : | a GtkWidget to add to the toolbar.
tooltip_text : | the element's tooltip.
tooltip_private_text : | used for context-sensitive help about this toolbar element.

gtk_toolbar_prepend_widget ()

void                gtk_toolbar_prepend_widget          (GtkToolbar *toolbar,
                                                         GtkWidget *widget,
                                                         const char *tooltip_text,
                                                         const char *tooltip_private_text);

Warning

gtk_toolbar_prepend_widget is deprecated and should not be used in newly-written code.

Adds a widget to the beginning of the given toolbar.

toolbar : | a GtkToolbar.
widget : | a GtkWidget to add to the toolbar.
tooltip_text : | the element's tooltip.
tooltip_private_text : | used for context-sensitive help about this toolbar element.

gtk_toolbar_insert_widget ()

void                gtk_toolbar_insert_widget           (GtkToolbar *toolbar,
                                                         GtkWidget *widget,
                                                         const char *tooltip_text,
                                                         const char *tooltip_private_text,
                                                         gint position);

Warning

gtk_toolbar_insert_widget is deprecated and should not be used in newly-written code.

Inserts a widget in the toolbar at the given position.

toolbar : | a GtkToolbar.
widget : | a GtkWidget to add to the toolbar.
tooltip_text : | the element's tooltip.
tooltip_private_text : | used for context-sensitive help about this toolbar element.
position : | the number of widgets to insert this widget after.

gtk_toolbar_set_style ()

void                gtk_toolbar_set_style               (GtkToolbar *toolbar,
                                                         GtkToolbarStyle style);

Alters the view of toolbar to display either icons only, text only, or both.

toolbar : | a GtkToolbar.
style : | the new style for toolbar.

gtk_toolbar_insert_stock ()

GtkWidget*          gtk_toolbar_insert_stock            (GtkToolbar *toolbar,
                                                         const gchar *stock_id,
                                                         const char *tooltip_text,
                                                         const char *tooltip_private_text,
                                                         GtkSignalFunc callback,
                                                         gpointer user_data,
                                                         gint position);

Warning

gtk_toolbar_insert_stock is deprecated and should not be used in newly-written code.

Inserts a stock item at the specified position of the toolbar. If stock_id is not a known stock item ID, it's inserted verbatim, except that underscores used to mark mnemonics are removed.

callback must be a pointer to a function taking a GtkWidget and a gpointer as arguments. Use the GTK_SIGNAL_FUNC() to cast the function to GtkSignalFunc.

toolbar : | A GtkToolbar
stock_id : | The id of the stock item you want to insert
tooltip_text : | The text in the tooltip of the toolbar button
tooltip_private_text : | The private text of the tooltip
callback : | The callback called when the toolbar button is clicked.
user_data : | user data passed to callback
position : | The position the button shall be inserted at. -1 means at the end.
Returns : | the inserted widget

gtk_toolbar_set_icon_size ()

void                gtk_toolbar_set_icon_size           (GtkToolbar *toolbar,
                                                         GtkIconSize icon_size);

Warning

gtk_toolbar_set_icon_size is deprecated and should not be used in newly-written code.

This function sets the size of stock icons in the toolbar. You can call it both before you add the icons and after they've been added. The size you set will override user preferences for the default icon size.

This should only be used for special-purpose toolbars, normal application toolbars should respect the user preferences for the size of icons.

toolbar : | A GtkToolbar
icon_size : | The GtkIconSize that stock icons in the toolbar shall have.

gtk_toolbar_remove_space ()

void                gtk_toolbar_remove_space            (GtkToolbar *toolbar,
                                                         gint position);

Warning

gtk_toolbar_remove_space is deprecated and should not be used in newly-written code.

Removes a space from the specified position.

toolbar : | a GtkToolbar.
position : | the index of the space to remove.

gtk_toolbar_unset_style ()

void                gtk_toolbar_unset_style             (GtkToolbar *toolbar);

Unsets a toolbar style set with gtk_toolbar_set_style(), so that user preferences will be used to determine the toolbar style.

toolbar : a GtkToolbar

Property Details

The "icon-size" property

  "icon-size"                GtkIconSize           : Read / Write

The size of the icons in a toolbar is normally determined by the toolbar-icon-size setting. When this property is set, it overrides the setting.

This should only be used for special-purpose toolbars, normal application toolbars should respect the user preferences for the size of icons.

Default value: GTK_ICON_SIZE_LARGE_TOOLBAR

Since 2.10

The "icon-size-set" property

  "icon-size-set"            gboolean              : Read / Write

Is TRUE if the icon-size property has been set.

Default value: FALSE

Since 2.10

The "orientation" property

  "orientation"              GtkOrientation        : Read / Write

The orientation of the toolbar.

Default value: GTK_ORIENTATION_HORIZONTAL

The "show-arrow" property

  "show-arrow"               gboolean              : Read / Write

If an arrow should be shown if the toolbar doesn't fit.

Default value: TRUE

The "toolbar-style" property

  "toolbar-style"            GtkToolbarStyle       : Read / Write

How to draw the toolbar.

Default value: GTK_TOOLBAR_ICONS

The "tooltips" property

  "tooltips"                 gboolean              : Read / Write

If the tooltips of the toolbar should be active or not.

Default value: TRUE

Since 2.8

Child Property Details

The "expand" child property

  "expand"                   gboolean              : Read / Write

Whether the item should receive extra space when the toolbar grows.

Default value: TRUE

The "homogeneous" child property

  "homogeneous"              gboolean              : Read / Write

Whether the item should be the same size as other homogeneous items.

Default value: TRUE

Style Property Details

The "button-relief" style property

  "button-relief"            GtkReliefStyle        : Read

Type of bevel around toolbar buttons.

Default value: GTK_RELIEF_NONE

The "internal-padding" style property

  "internal-padding"         gint                  : Read

Amount of border space between the toolbar shadow and the buttons.

Allowed values: >= 0

Default value: 0

The "max-child-expand" style property

  "max-child-expand"         gint                  : Read

Maximum amount of space an expandable item will be given.

Allowed values: >= 0

Default value: 2147483647

The "shadow-type" style property

  "shadow-type"              GtkShadowType         : Read

Style of bevel around the toolbar.

Default value: GTK_SHADOW_OUT

The "space-size" style property

  "space-size"               gint                  : Read

Size of spacers.

Allowed values: >= 0

Default value: 12

The "space-style" style property

  "space-style"              GtkToolbarSpaceStyle  : Read

Whether spacers are vertical lines or just blank.

Default value: GTK_TOOLBAR_SPACE_LINE

Signal Details

The "focus-home-or-end" signal

gboolean            user_function                      (GtkToolbar *toolbar,
                                                        gboolean    focus_home,
                                                        gpointer    user_data)       : Run Last / Action

A keybinding signal used internally by GTK+. This signal can't be used in application code

toolbar : | the GtkToolbar which emitted the signal
focus_home : | TRUE if the first item should be focused
user_data : | user data set when the signal handler was connected.
Returns : | TRUE if the signal was handled, FALSE if not

The "move-focus" signal

gboolean            user_function                      (GtkToolbar      *toolbar,
                                                        GtkDirectionType dir,
                                                        gpointer         user_data)      : Run Last / Action

A keybinding signal used internally by GTK+. This signal can't be used in application code.

toolbar : | the GtkToolbar which emitted the signal
dir : | a GtkDirection
user_data : | user data set when the signal handler was connected.
Returns : | TRUE if the signal was handled, FALSE if not

The "orientation-changed" signal

void                user_function                      (GtkToolbar    *toolbar,
                                                        GtkOrientation orientation,
                                                        gpointer       user_data)        : Run First

Emitted when the orientation of the toolbar changes.

toolbar : | the object which emitted the signal
orientation : | the new GtkOrientation of the toolbar
user_data : | user data set when the signal handler was connected.

The "popup-context-menu" signal

gboolean            user_function                      (GtkToolbar *toolbar,
                                                        gint        x,
                                                        gint        y,
                                                        gint        button,
                                                        gpointer    user_data)      : Run Last

Emitted when the user right-clicks the toolbar or uses the keybinding to display a popup menu.

Application developers should handle this signal if they want to display a context menu on the toolbar. The context-menu should appear at the coordinates given by x and y. The mouse button number is given by the button parameter. If the menu was popped up using the keybaord, button is -1.

toolbar : | the GtkToolbar which emitted the signal
x : | the x coordinate of the point where the menu should appear
y : | the y coordinate of the point where the menu should appear
button : | the mouse button the user pressed, or -1
user_data : | user data set when the signal handler was connected.
Returns : | return TRUE if the signal was handled, FALSE if not

The "style-changed" signal

void                user_function                      (GtkToolbar     *toolbar,
                                                        GtkToolbarStyle style,
                                                        gpointer        user_data)      : Run First

Emitted when the style of the toolbar changes.

toolbar : | The GtkToolbar which emitted the signal
style : | the new GtkToolbarStyle of the toolbar
user_data : | user data set when the signal handler was connected.

See Also

GtkToolItem

Base class of widgets that can be added to a toolbar.


GtkToolButton

GtkToolButton — A GtkToolItem subclass that displays buttons

Synopsis

#include <gtk/gtk.h>

                    GtkToolButton;
GtkToolItem*        gtk_tool_button_new                 (GtkWidget *icon_widget,
                                                         const gchar *label);
GtkToolItem*        gtk_tool_button_new_from_stock      (const gchar *stock_id);
void                gtk_tool_button_set_label           (GtkToolButton *button,
                                                         const gchar *label);
const gchar*        gtk_tool_button_get_label           (GtkToolButton *button);
void                gtk_tool_button_set_use_underline   (GtkToolButton *button,
                                                         gboolean use_underline);
gboolean            gtk_tool_button_get_use_underline   (GtkToolButton *button);
void                gtk_tool_button_set_stock_id        (GtkToolButton *button,
                                                         const gchar *stock_id);
const gchar*        gtk_tool_button_get_stock_id        (GtkToolButton *button);
void                gtk_tool_button_set_icon_name       (GtkToolButton *button,
                                                         const gchar *icon_name);
const gchar*        gtk_tool_button_get_icon_name       (GtkToolButton *button);
void                gtk_tool_button_set_icon_widget     (GtkToolButton *button,
                                                         GtkWidget *icon_widget);
GtkWidget*          gtk_tool_button_get_icon_widget     (GtkToolButton *button);
void                gtk_tool_button_set_label_widget    (GtkToolButton *button,
                                                         GtkWidget *label_widget);
GtkWidget*          gtk_tool_button_get_label_widget    (GtkToolButton *button);

Object Hierarchy

  GObject
   +----GInitiallyUnowned
         +----GtkObject
               +----GtkWidget
                     +----GtkContainer
                           +----GtkBin
                                 +----GtkToolItem
                                       +----GtkToolButton
                                             +----GtkMenuToolButton
                                             +----GtkToggleToolButton

Implemented Interfaces

GtkToolButton implements AtkImplementorIface.

Properties

  "icon-name"                gchararray            : Read / Write
  "icon-widget"              GtkWidget             : Read / Write
  "label"                    gchararray            : Read / Write
  "label-widget"             GtkWidget             : Read / Write
  "stock-id"                 gchararray            : Read / Write
  "use-underline"            gboolean              : Read / Write

Style Properties

  "icon-spacing"             gint                  : Read / Write

Signals

  "clicked"                                        : Run First / Action

Description

GtkToolButtons are GtkToolItems containing buttons.

Use gtk_tool_button_new() to create a new GtkToolButton. Use gtk_tool_button_new_with_stock() to create a GtkToolButton containing a stock item.

The label of a GtkToolButton is determined by the properties "label_widget", "label", and "stock_id". If "label_widget" is non-NULL, then that widget is used as the label. Otherwise, if "label" is non-NULL, that string is used as the label. Otherwise, if "stock_id" is non-NULL, the label is determined by the stock item. Otherwise, the button does not have a label.

The icon of a GtkToolButton is determined by the properties "icon_widget" and "stock_id". If "icon_widget" is non-NULL, then that widget is used as the icon. Otherwise, if "stock_id" is non-NULL, the icon is determined by the stock item. Otherwise, the button does not have a label.

Details

GtkToolButton

typedef struct _GtkToolButton GtkToolButton;

The GtkToolButton struct contains only private. It should only be accessed with the function described below.

gtk_tool_button_new ()

GtkToolItem*        gtk_tool_button_new                 (GtkWidget *icon_widget,
                                                         const gchar *label);

Creates a new GtkToolButton using icon_widget as icon and label as label.

icon_widget : | a widget that will be used as icon widget, or NULL
label : | a string that will be used as label, or NULL
Returns : | A new GtkToolButton

Since 2.4

gtk_tool_button_new_from_stock ()

GtkToolItem*        gtk_tool_button_new_from_stock      (const gchar *stock_id);

Creates a new GtkToolButton containing the image and text from a stock item. Some stock ids have preprocessor macros like GTK_STOCK_OK and GTK_STOCK_APPLY.

It is an error if stock_id is not a name of a stock item.

stock_id : | the name of the stock item
Returns : | A new GtkToolButton

Since 2.4

gtk_tool_button_set_label ()

void                gtk_tool_button_set_label           (GtkToolButton *button,
                                                         const gchar *label);

Sets label as the label used for the tool button. The "label" property only has an effect if not overridden by a non-NULL "label_widget" property. If both the "label_widget" and "label" properties are NULL, the label is determined by the "stock_id" property. If the "stock_id" property is also NULL, button will not have a label.

button : | a GtkToolButton
label : | a string that will be used as label, or NULL.

Since 2.4

gtk_tool_button_get_label ()

const gchar*        gtk_tool_button_get_label           (GtkToolButton *button);

Returns the label used by the tool button, or NULL if the tool button doesn't have a label. or uses a the label from a stock item. The returned string is owned by GTK+, and must not be modified or freed.

button : | a GtkToolButton
Returns : | The label, or NULL

Since 2.4

gtk_tool_button_set_use_underline ()

void                gtk_tool_button_set_use_underline   (GtkToolButton *button,
                                                         gboolean use_underline);

If set, an underline in the label property indicates that the next character should be used for the mnemonic accelerator key in the overflow menu. For example, if the label property is "_Open" and use_underline is TRUE, the label on the tool button will be "Open" and the item on the overflow menu will have an underlined 'O'.

Labels shown on tool buttons never have mnemonics on them; this property only affects the menu item on the overflow menu.

button : | a GtkToolButton
use_underline : | whether the button label has the form "_Open"

Since 2.4

gtk_tool_button_get_use_underline ()

gboolean            gtk_tool_button_get_use_underline   (GtkToolButton *button);

Returns whether underscores in the label property are used as mnemonics on menu items on the overflow menu. See gtk_tool_button_set_use_underline().

button : | a GtkToolButton
Returns : | TRUE if underscores in the label property are used as mnemonics on menu items on the overflow menu.

Since 2.4

gtk_tool_button_set_stock_id ()

void                gtk_tool_button_set_stock_id        (GtkToolButton *button,
                                                         const gchar *stock_id);

Sets the name of the stock item. See gtk_tool_button_new_from_stock(). The stock_id property only has an effect if not overridden by non-NULL "label" and "icon_widget" properties.

button : | a GtkToolButton
stock_id : | a name of a stock item, or NULL

Since 2.4

gtk_tool_button_get_stock_id ()

const gchar*        gtk_tool_button_get_stock_id        (GtkToolButton *button);

Returns the name of the stock item. See gtk_tool_button_set_stock_id(). The returned string is owned by GTK+ and must not be freed or modifed.

button : | a GtkToolButton
Returns : | the name of the stock item for button.

Since 2.4

gtk_tool_button_set_icon_name ()

void                gtk_tool_button_set_icon_name       (GtkToolButton *button,
                                                         const gchar *icon_name);

Sets the icon for the tool button from a named themed icon. See the docs for GtkIconTheme for more details. The "icon_name" property only has an effect if not overridden by non-NULL "label", "icon_widget" and "stock_id" properties.

button : | a GtkToolButton
icon_name : | the name of the themed icon

Since 2.8

gtk_tool_button_get_icon_name ()

const gchar*        gtk_tool_button_get_icon_name       (GtkToolButton *button);

Returns the name of the themed icon for the tool button, see gtk_tool_button_set_icon_name().

button : | a GtkToolButton
Returns : | the icon name or NULL if the tool button has no themed icon

Since 2.8

gtk_tool_button_set_icon_widget ()

void                gtk_tool_button_set_icon_widget     (GtkToolButton *button,
                                                         GtkWidget *icon_widget);

Sets icon as the widget used as icon on button. If icon_widget is NULL the icon is determined by the "stock_id" property. If the "stock_id" property is also NULL, button will not have an icon.

button : | a GtkToolButton
icon_widget : | the widget used as icon, or NULL

Since 2.4

gtk_tool_button_get_icon_widget ()

GtkWidget*          gtk_tool_button_get_icon_widget     (GtkToolButton *button);

Return the widget used as icon widget on button. See gtk_tool_button_set_icon_widget().

button : | a GtkToolButton
Returns : | The widget used as icon on button, or NULL.

Since 2.4

gtk_tool_button_set_label_widget ()

void                gtk_tool_button_set_label_widget    (GtkToolButton *button,
                                                         GtkWidget *label_widget);

Sets label_widget as the widget that will be used as the label for button. If label_widget is NULL the "label" property is used as label. If "label" is also NULL, the label in the stock item determined by the "stock_id" property is used as label. If "stock_id" is also NULL, button does not have a label.

button : | a GtkToolButton
label_widget : | the widget used as label, or NULL

Since 2.4

gtk_tool_button_get_label_widget ()

GtkWidget*          gtk_tool_button_get_label_widget    (GtkToolButton *button);

Returns the widget used as label on button. See gtk_tool_button_set_label_widget().

button : | a GtkToolButton
Returns : | The widget used as label on button, or NULL.

Since 2.4

Property Details

The "icon-name" property

  "icon-name"                gchararray            : Read / Write

The name of the themed icon displayed on the item. This property only has an effect if not overridden by "label", "icon_widget" or "stock_id" properties.

Default value: NULL

Since 2.8

The "icon-widget" property

  "icon-widget"              GtkWidget             : Read / Write

Icon widget to display in the item.

The "label" property

  "label"                    gchararray            : Read / Write

Text to show in the item.

Default value: NULL

The "label-widget" property

  "label-widget"             GtkWidget             : Read / Write

Widget to use as the item label.

The "stock-id" property

  "stock-id"                 gchararray            : Read / Write

The stock icon displayed on the item.

Default value: NULL

The "use-underline" property

  "use-underline"            gboolean              : Read / Write

If set, an underline in the label property indicates that the next character should be used for the mnemonic accelerator key in the overflow menu.

Default value: FALSE

Style Property Details

The "icon-spacing" style property

  "icon-spacing"             gint                  : Read / Write

Spacing in pixels between the icon and label.

Allowed values: >= 0

Default value: 0

Signal Details

The "clicked" signal

void                user_function                      (GtkToolButton *toolbutton,
                                                        gpointer       user_data)       : Run First / Action

This signal is emitted when the tool button is clicked with the mouse or activated with the keyboard.

toolbutton : | the object that emitted the signal
user_data : | user data set when the signal handler was connected.

See Also

GtkToolbar | The toolbar widget
GtkMenuToolButton | A subclass of GtkToolButton that displays on the toolbar a button with an additional dropdown menu
GtkToggleToolButton | A subclass of GtkToolButton that displays toggle buttons on the toolbar
GtkRadioToolButton | A subclass of GtkToolButton that displays radio buttons on the toolbar
GtkSeparatorToolItem | A subclass of GtkToolItem that separates groups of items on a toolbar


GtkToolItem

GtkToolItem — The base class of widgets that can be added to GtkToolbar

Synopsis

#include <gtk/gtk.h>

                    GtkToolItem;
GtkToolItem*        gtk_tool_item_new                   (void);
void                gtk_tool_item_set_homogeneous       (GtkToolItem *tool_item,
                                                         gboolean homogeneous);
gboolean            gtk_tool_item_get_homogeneous       (GtkToolItem *tool_item);
void                gtk_tool_item_set_expand            (GtkToolItem *tool_item,
                                                         gboolean expand);
gboolean            gtk_tool_item_get_expand            (GtkToolItem *tool_item);
void                gtk_tool_item_set_tooltip           (GtkToolItem *tool_item,
                                                         GtkTooltips *tooltips,
                                                         const gchar *tip_text,
                                                         const gchar *tip_private);
void                gtk_tool_item_set_use_drag_window   (GtkToolItem *toolitem,
                                                         gboolean use_drag_window);
gboolean            gtk_tool_item_get_use_drag_window   (GtkToolItem *toolitem);
void                gtk_tool_item_set_visible_horizontal
                                                        (GtkToolItem *toolitem,
                                                         gboolean visible_horizontal);
gboolean            gtk_tool_item_get_visible_horizontal
                                                        (GtkToolItem *toolitem);
void                gtk_tool_item_set_visible_vertical  (GtkToolItem *toolitem,
                                                         gboolean visible_vertical);
gboolean            gtk_tool_item_get_visible_vertical  (GtkToolItem *toolitem);
void                gtk_tool_item_set_is_important      (GtkToolItem *tool_item,
                                                         gboolean is_important);
gboolean            gtk_tool_item_get_is_important      (GtkToolItem *tool_item);
GtkIconSize         gtk_tool_item_get_icon_size         (GtkToolItem *tool_item);
GtkOrientation      gtk_tool_item_get_orientation       (GtkToolItem *tool_item);
GtkToolbarStyle     gtk_tool_item_get_toolbar_style     (GtkToolItem *tool_item);
GtkReliefStyle      gtk_tool_item_get_relief_style      (GtkToolItem *tool_item);
GtkWidget*          gtk_tool_item_retrieve_proxy_menu_item
                                                        (GtkToolItem *tool_item);
GtkWidget*          gtk_tool_item_get_proxy_menu_item   (GtkToolItem *tool_item,
                                                         const gchar *menu_item_id);
void                gtk_tool_item_set_proxy_menu_item   (GtkToolItem *tool_item,
                                                         const gchar *menu_item_id,
                                                         GtkWidget *menu_item);
void                gtk_tool_item_rebuild_menu          (GtkToolItem *tool_item);

Object Hierarchy

  GObject
   +----GInitiallyUnowned
         +----GtkObject
               +----GtkWidget
                     +----GtkContainer
                           +----GtkBin
                                 +----GtkToolItem
                                       +----GtkToolButton
                                       +----GtkSeparatorToolItem

Implemented Interfaces

GtkToolItem implements AtkImplementorIface.

Properties

  "is-important"             gboolean              : Read / Write
  "visible-horizontal"       gboolean              : Read / Write
  "visible-vertical"         gboolean              : Read / Write

Signals

  "create-menu-proxy"                              : Run Last
  "set-tooltip"                                    : Run Last
  "toolbar-reconfigured"                           : Run Last

Description

GtkToolItems are widgets that can appear on a toolbar. To create a toolbar item that contain something else than a button, use gtk_tool_item_new(). Use gtk_container_add() to add a child widget to the tool item.

For toolbar items that contain buttons, see the GtkToolButton, GtkToggleToolButton and GtkRadioToolButton classes.

See the GtkToolbar class for a description of the toolbar widget.

Details

GtkToolItem

typedef struct _GtkToolItem GtkToolItem;

The GtkToolItem struct contains only private data. It should only be accessed through the functions described below.

gtk_tool_item_new ()

GtkToolItem*        gtk_tool_item_new                   (void);

Creates a new GtkToolItem

Returns : the new GtkToolItem

Since 2.4

gtk_tool_item_set_homogeneous ()

void                gtk_tool_item_set_homogeneous       (GtkToolItem *tool_item,
                                                         gboolean homogeneous);

Sets whether tool_item is to be allocated the same size as other homogeneous items. The effect is that all homogeneous items will have the same width as the widest of the items.

tool_item : | a GtkToolItem:
homogeneous : | whether tool_item is the same size as other homogeneous items

Since 2.4

gtk_tool_item_get_homogeneous ()

gboolean            gtk_tool_item_get_homogeneous       (GtkToolItem *tool_item);

Returns whether tool_item is the same size as other homogeneous items. See gtk_tool_item_set_homogeneous().

tool_item : | a GtkToolItem:
Returns : | TRUE if the item is the same size as other homogeneous item.s

Since 2.4

gtk_tool_item_set_expand ()

void                gtk_tool_item_set_expand            (GtkToolItem *tool_item,
                                                         gboolean expand);

Sets whether tool_item is allocated extra space when there is more room on the toolbar then needed for the items. The effect is that the item gets bigger when the toolbar gets bigger and smaller when the toolbar gets smaller.

tool_item : | a GtkToolItem:
expand : | Whether tool_item is allocated extra space

Since 2.4

gtk_tool_item_get_expand ()

gboolean            gtk_tool_item_get_expand            (GtkToolItem *tool_item);

Returns whether tool_item is allocated extra space. See gtk_tool_item_set_expand().

tool_item : | a GtkToolItem:
Returns : | TRUE if tool_item is allocated extra space.

Since 2.4

gtk_tool_item_set_tooltip ()

void                gtk_tool_item_set_tooltip           (GtkToolItem *tool_item,
                                                         GtkTooltips *tooltips,
                                                         const gchar *tip_text,
                                                         const gchar *tip_private);

Sets the GtkTooltips object to be used for tool_item, the text to be displayed as tooltip on the item and the private text to be used. See gtk_tooltips_set_tip().

tool_item : | a GtkToolItem:
tooltips : | The GtkTooltips object to be used
tip_text : | text to be used as tooltip text for tool_item
tip_private : | text to be used as private tooltip text

Since 2.4

gtk_tool_item_set_use_drag_window ()

void                gtk_tool_item_set_use_drag_window   (GtkToolItem *toolitem,
                                                         gboolean use_drag_window);

Sets whether toolitem has a drag window. When TRUE the toolitem can be used as a drag source through gtk_drag_source_set(). When toolitem has a drag window it will intercept all events, even those that would otherwise be sent to a child of toolitem.

toolitem : | a GtkToolItem
use_drag_window : | Whether toolitem has a drag window.

Since 2.4

gtk_tool_item_get_use_drag_window ()

gboolean            gtk_tool_item_get_use_drag_window   (GtkToolItem *toolitem);

Returns whether toolitem has a drag window. See gtk_tool_item_set_use_drag_window().

toolitem : | a GtkToolItem
Returns : | TRUE if toolitem uses a drag window.

Since 2.4

gtk_tool_item_set_visible_horizontal ()

void                gtk_tool_item_set_visible_horizontal
                                                        (GtkToolItem *toolitem,
                                                         gboolean visible_horizontal);

Sets whether toolitem is visible when the toolbar is docked horizontally.

toolitem : | a GtkToolItem
visible_horizontal : | Whether toolitem is visible when in horizontal mode

Since 2.4

gtk_tool_item_get_visible_horizontal ()

gboolean            gtk_tool_item_get_visible_horizontal
                                                        (GtkToolItem *toolitem);

Returns whether the toolitem is visible on toolbars that are docked horizontally.

toolitem : | a GtkToolItem
Returns : | TRUE if toolitem is visible on toolbars that are docked horizontally.

Since 2.4

gtk_tool_item_set_visible_vertical ()

void                gtk_tool_item_set_visible_vertical  (GtkToolItem *toolitem,
                                                         gboolean visible_vertical);

Sets whether toolitem is visible when the toolbar is docked vertically. Some tool items, such as text entries, are too wide to be useful on a vertically docked toolbar. If visible_vertical is FALSE toolitem will not appear on toolbars that are docked vertically.

toolitem : | a GtkToolItem
visible_vertical : | whether toolitem is visible when the toolbar is in vertical mode

Since 2.4

gtk_tool_item_get_visible_vertical ()

gboolean            gtk_tool_item_get_visible_vertical  (GtkToolItem *toolitem);

Returns whether toolitem is visible when the toolbar is docked vertically. See gtk_tool_item_set_visible_vertical().

toolitem : | a GtkToolItem
Returns : | Whether toolitem is visible when the toolbar is docked vertically

Since 2.4

gtk_tool_item_set_is_important ()

void                gtk_tool_item_set_is_important      (GtkToolItem *tool_item,
                                                         gboolean is_important);

Sets whether tool_item should be considered important. The GtkToolButton class uses this property to determine whether to show or hide its label when the toolbar style is GTK_TOOLBAR_BOTH_HORIZ. The result is that only tool buttons with the "is_important" property set have labels, an effect known as "priority text"

tool_item : | a GtkToolItem
is_important : | whether the tool item should be considered important

Since 2.4

gtk_tool_item_get_is_important ()

gboolean            gtk_tool_item_get_is_important      (GtkToolItem *tool_item);

Returns whether tool_item is considered important. See gtk_tool_item_set_is_important()

tool_item : | a GtkToolItem
Returns : | TRUE if tool_item is considered important.

Since 2.4

gtk_tool_item_get_icon_size ()

GtkIconSize         gtk_tool_item_get_icon_size         (GtkToolItem *tool_item);

Returns the icon size used for tool_item. Custom subclasses of GtkToolItem should call this function to find out what size icons they should use.

tool_item : | a GtkToolItem:
Returns : | a GtkIconSize indicating the icon size used for tool_item

Since 2.4

gtk_tool_item_get_orientation ()

GtkOrientation      gtk_tool_item_get_orientation       (GtkToolItem *tool_item);

Returns the orientation used for tool_item. Custom subclasses of GtkToolItem should call this function to find out what size icons they should use.

tool_item : | a GtkToolItem:
Returns : | a GtkOrientation indicating the orientation used for tool_item

Since 2.4

gtk_tool_item_get_toolbar_style ()

GtkToolbarStyle     gtk_tool_item_get_toolbar_style     (GtkToolItem *tool_item);

Returns the toolbar style used for tool_item. Custom subclasses of GtkToolItem should call this function in the handler of the GtkToolItem::toolbar_reconfigured signal to find out in what style the toolbar is displayed and change themselves accordingly

Possibilities are:

  • GTK_TOOLBAR_BOTH, meaning the tool item should show both an icon and a label, stacked vertically
  • GTK_TOOLBAR_ICONS, meaning the toolbar shows only icons
  • GTK_TOOLBAR_TEXT, meaning the tool item should only show text
  • GTK_TOOLBAR_BOTH_HORIZ, meaning the tool item should show both an icon and a label, arranged horizontally (however, note the GtkToolButton::has_text_horizontally that makes tool buttons not show labels when the toolbar style is GTK_TOOLBAR_BOTH_HORIZ.

tool_item : | a GtkToolItem:
Returns : | A GtkToolbarStyle indicating the toolbar style used for tool_item.

Since 2.4

gtk_tool_item_get_relief_style ()

GtkReliefStyle      gtk_tool_item_get_relief_style      (GtkToolItem *tool_item);

Returns the relief style of tool_item. See gtk_button_set_relief_style(). Custom subclasses of GtkToolItem should call this function in the handler of the GtkToolItem::toolbar_reconfigured signal to find out the relief style of buttons.

tool_item : | a GtkToolItem:
Returns : | a GtkReliefStyle indicating the relief style used for tool_item.

Since 2.4

gtk_tool_item_retrieve_proxy_menu_item ()

GtkWidget*          gtk_tool_item_retrieve_proxy_menu_item
                                                        (GtkToolItem *tool_item);

Returns the GtkMenuItem that was last set by gtk_tool_item_set_proxy_menu_item(), ie. the GtkMenuItem that is going to appear in the overflow menu.

tool_item : | a GtkToolItem:
Returns : | The GtkMenuItem that is going to appear in the overflow menu for tool_item.

Since 2.4

gtk_tool_item_get_proxy_menu_item ()

GtkWidget*          gtk_tool_item_get_proxy_menu_item   (GtkToolItem *tool_item,
                                                         const gchar *menu_item_id);

If menu_item_id matches the string passed to gtk_tool_item_set_proxy_menu_item() return the corresponding GtkMenuItem.

Custom subclasses of GtkToolItem should use this function to update their menu item when the GtkToolItem changes. That the menu_item_ids must match ensures that a GtkToolItem will not inadvertently change a menu item that they did not create.

tool_item : | a GtkToolItem:
menu_item_id : | a string used to identify the menu item
Returns : | The GtkMenuItem passed to gtk_tool_item_set_proxy_menu_item(), if the menu_item_ids match.

Since 2.4

gtk_tool_item_set_proxy_menu_item ()

void                gtk_tool_item_set_proxy_menu_item   (GtkToolItem *tool_item,
                                                         const gchar *menu_item_id,
                                                         GtkWidget *menu_item);

Sets the GtkMenuItem used in the toolbar overflow menu. The menu_item_id is used to identify the caller of this function and should also be used with gtk_tool_item_get_proxy_menu_item().

tool_item : | a GtkToolItem:
menu_item_id : | a string used to identify menu_item
menu_item : | a GtkMenuItem to be used in the overflow menu

Since 2.4

gtk_tool_item_rebuild_menu ()

void                gtk_tool_item_rebuild_menu          (GtkToolItem *tool_item);

Calling this function signals to the toolbar that the overflow menu item for tool_item has changed. If the overflow menu is visible when this function it called, the menu will be rebuilt.

The function must be called when the tool item changes what it will do in response to the "create_menu_proxy" signal.

tool_item : a GtkToolItem

Since 2.6

Property Details

The "is-important" property

  "is-important"             gboolean              : Read / Write

Whether the toolbar item is considered important. When TRUE, toolbar buttons show text in GTK_TOOLBAR_BOTH_HORIZ mode.

Default value: FALSE

The "visible-horizontal" property

  "visible-horizontal"       gboolean              : Read / Write

Whether the toolbar item is visible when the toolbar is in a horizontal orientation.

Default value: TRUE

The "visible-vertical" property

  "visible-vertical"         gboolean              : Read / Write

Whether the toolbar item is visible when the toolbar is in a vertical orientation.

Default value: TRUE

Signal Details

The "create-menu-proxy" signal

gboolean            user_function                      (GtkToolItem *toolitem,
                                                        gpointer     user_data)      : Run Last

This signal is emitted when the toolbar needs information from tool_item about whether the item should appear in the toolbar overflow menu. In response the tool item should either

  • call gtk_tool_item_set_proxy_menu_item() with a NULL pointer and return TRUE to indicate that the item should not appear in the overflow menu
  • call gtk_tool_item_set_proxy_menu_item() with a new menu item and return TRUE, or
  • return FALSE to indicate that the signal was not handled by the item. This means that the item will not appear in the overflow menu unless a later handler installs a menu item.

The toolbar may cache the result of this signal. When the tool item changes how it will respond to this signal it must call gtk_tool_item_rebuild_menu() to invalidate the cache and ensure that the toolbar rebuilds its overflow menu.

toolitem : | the object the signal was emitted on
user_data : | user data set when the signal handler was connected.
Returns : | TRUE if the signal was handled, FALSE if not

The "set-tooltip" signal

gboolean            user_function                      (GtkToolItem *toolitem,
                                                        GtkTooltips *tooltips,
                                                        gchar       *tip_text,
                                                        gchar       *tip_private,
                                                        gpointer     user_data)        : Run Last

This signal is emitted when the toolitem's tooltip changes. Application developers can use gtk_tool_item_set_tooltip() to set the item's tooltip.

toolitem : | the object the signal was emitted on
tooltips : | the GtkTooltips
tip_text : | the tooltip text
tip_private : | the tooltip private text
user_data : | user data set when the signal handler was connected.
Returns : | TRUE if the signal was handled, FALSE if not

The "toolbar-reconfigured" signal

void                user_function                      (GtkToolItem *toolitem,
                                                        gpointer     user_data)      : Run Last

This signal is emitted when some property of the toolbar that the item is a child of changes. For custom subclasses of GtkToolItem, the default handler of this signal use the functions

  • gtk_toolbar_get_orientation()
  • gtk_toolbar_get_style()
  • gtk_toolbar_get_icon_size()
  • gtk_toolbar_get_relief_style()

to find out what the toolbar should look like and change themselves accordingly.

toolitem : | the object the signal was emitted on
user_data : | user data set when the signal handler was connected.

See Also

GtkToolbar

The toolbar widget

GtkToolButton

A subclass of GtkToolItem that displays buttons on the toolbar

GtkSeparatorToolItem

A subclass of GtkToolItem that separates groups of items on a toolbar


GtkTooltips

GtkTooltips — Add tips to your widgets

Synopsis

#include <gtk/gtk.h>

                    GtkTooltips;
                    GtkTooltipsData;
GtkTooltips*        gtk_tooltips_new                    (void);
void                gtk_tooltips_enable                 (GtkTooltips *tooltips);
void                gtk_tooltips_disable                (GtkTooltips *tooltips);
void                gtk_tooltips_set_delay              (GtkTooltips *tooltips,
                                                         guint delay);
void                gtk_tooltips_set_tip                (GtkTooltips *tooltips,
                                                         GtkWidget *widget,
                                                         const gchar *tip_text,
                                                         const gchar *tip_private);
GtkTooltipsData*    gtk_tooltips_data_get               (GtkWidget *widget);
void                gtk_tooltips_force_window           (GtkTooltips *tooltips);
gboolean            gtk_tooltips_get_info_from_tip_window
                                                        (GtkWindow *tip_window,
                                                         GtkTooltips **tooltips,
                                                         GtkWidget **current_widget);

Object Hierarchy

  GObject
   +----GInitiallyUnowned
         +----GtkObject
               +----GtkTooltips

Description

Tooltips are the messages that appear next to a widget when the mouse pointer is held over it for a short amount of time. They are especially helpful for adding more verbose descriptions of things such as buttons in a toolbar.

An individual tooltip belongs to a group of tooltips. A group is created with a call to gtk_tooltips_new(). Every tooltip in the group can then be turned off with a call to gtk_tooltips_disable() and enabled with gtk_tooltips_enable().

The length of time the user must keep the mouse over a widget before the tip is shown, can be altered with gtk_tooltips_set_delay(). This is set on a 'per group of tooltips' basis.

To assign a tip to a particular GtkWidget, gtk_tooltips_set_tip() is used.

Note

Tooltips can only be set on widgets which have their own X window and receive enter and leave events. To check if a widget has its own window use GTK_WIDGET_NO_WINDOW(). To add a tooltip to a widget that doesn't have its own window, place the widget inside a GtkEventBox and add a tooltip to that instead.

The default appearance of all tooltips in a program is determined by the current GTK+ theme that the user has selected.

Information about the tooltip (if any) associated with an arbitrary widget can be retrieved using gtk_tooltips_data_get().

Example 34. Adding tooltips to buttons.

   GtkWidget *load_button, *save_button, *hbox;
   GtkTooltips *button_bar_tips;

   button_bar_tips = gtk_tooltips_new ();

   /* Create the buttons and pack them into a GtkHBox */
   hbox = gtk_hbox_new (TRUE, 2);

   load_button = gtk_button_new_with_label ("Load a file");
   gtk_box_pack_start (GTK_BOX (hbox), load_button, TRUE, TRUE, 2);
   gtk_widget_show (load_button);

   save_button = gtk_button_new_with_label ("Save a file");
   gtk_box_pack_start (GTK_BOX (hbox), save_button, TRUE, TRUE, 2);
   gtk_widget_show (save_button);
   gtk_widget_show (hbox);

   /* Add the tips */
   gtk_tooltips_set_tip (GTK_TOOLTIPS (button_bar_tips), load_button,
                 "Load a new document into this window",
                 "Requests the filename of a document.
                  This will then be loaded into the current
                  window, replacing the contents of whatever
                  is already loaded.");
   gtk_tooltips_set_tip (GTK_TOOLTIPS (button_bar_tips), save_button,
                 "Saves the current document to a file",
                 "If you have saved the document previously,
                  then the new version will be saved over the
                  old one. Otherwise, you will be prompted for
                  a filename.");

Details

GtkTooltips

typedef struct _GtkTooltips GtkTooltips;

Holds information about a group of tooltips. Fields should be changed using the functions provided, rather than directly accessing the struct's members.

GtkTooltipsData

typedef struct {
  GtkTooltips *tooltips;
  GtkWidget *widget;
  gchar *tip_text;
  gchar *tip_private;
} GtkTooltipsData;

tooltips is the GtkTooltips group that this tooltip belongs to. widget is the GtkWidget that this tooltip data is associated with. tip_text is a string containing the tooltip message itself.

tip_private is a string that is not shown as the default tooltip. Instead, this message may be more informative and go towards forming a context-sensitive help system for your application. (FIXME: how to actually "switch on" private tips?)

gtk_tooltips_new ()

GtkTooltips*        gtk_tooltips_new                    (void);

Creates an empty group of tooltips. This function initialises a GtkTooltips structure. Without at least one such structure, you can not add tips to your application.

Returns : a new GtkTooltips group for you to use.

gtk_tooltips_enable ()

void                gtk_tooltips_enable                 (GtkTooltips *tooltips);

Allows the user to see your tooltips as they navigate your application.

tooltips : a GtkTooltips.

gtk_tooltips_disable ()

void                gtk_tooltips_disable                (GtkTooltips *tooltips);

Causes all tooltips in tooltips to become inactive. Any widgets that have tips associated with that group will no longer display their tips until they are enabled again with gtk_tooltips_enable().

tooltips : a GtkTooltips.

gtk_tooltips_set_delay ()

void                gtk_tooltips_set_delay              (GtkTooltips *tooltips,
                                                         guint delay);

Warning

gtk_tooltips_set_delay is deprecated and should not be used in newly-written code.

Sets the time between the user moving the mouse over a widget and the widget's tooltip appearing.

tooltips : | a GtkTooltips.
delay : | an integer value representing milliseconds.

gtk_tooltips_set_tip ()

void                gtk_tooltips_set_tip                (GtkTooltips *tooltips,
                                                         GtkWidget *widget,
                                                         const gchar *tip_text,
                                                         const gchar *tip_private);

Adds a tooltip containing the message tip_text to the specified GtkWidget.

tooltips : | a GtkTooltips.
widget : | the GtkWidget you wish to associate the tip with.
tip_text : | a string containing the tip itself.
tip_private : | a string of any further information that may be useful if the user gets stuck.

gtk_tooltips_data_get ()

GtkTooltipsData*    gtk_tooltips_data_get               (GtkWidget *widget);

Retrieves any GtkTooltipsData previously associated with the given widget.

widget : | a GtkWidget.
Returns : | a GtkTooltipsData struct, or NULL if the widget has no tooltip.

gtk_tooltips_force_window ()

void                gtk_tooltips_force_window           (GtkTooltips *tooltips);

Ensures that the window used for displaying the given tooltips is created.

Applications should never have to call this function, since GTK+ takes care of this.

tooltips : a GtkToolTips

gtk_tooltips_get_info_from_tip_window ()

gboolean            gtk_tooltips_get_info_from_tip_window
                                                        (GtkWindow *tip_window,
                                                         GtkTooltips **tooltips,
                                                         GtkWidget **current_widget);

Determines the tooltips and the widget they belong to from the window in which they are displayed.

This function is mostly intended for use by accessibility technologies; applications should have little use for it.

tip_window : | a GtkWindow
tooltips : | the return location for the tooltips which are displayed in tip_window, or NULL
current_widget : | the return location for the widget whose tooltips are displayed, or NULL
Returns : | TRUE if tip_window is displaying tooltips, otherwise FALSE.

Since 2.4

See Also

GtkToolbar | Create groups of widgets with their own tooltips.
GtkTipsQuery | Query tooltips to create context-sensitive help.


GtkTree

GtkTree — A tree widget

Synopsis

#include <gtk/gtk.h>

                    GtkTree;
#define             GTK_IS_ROOT_TREE                    (obj)
#define             GTK_TREE_ROOT_TREE                  (obj)
#define             GTK_TREE_SELECTION_OLD              (obj)
enum                GtkTreeViewMode;
GtkWidget*          gtk_tree_new                        (void);
void                gtk_tree_append                     (GtkTree *tree,
                                                         GtkWidget *tree_item);
void                gtk_tree_prepend                    (GtkTree *tree,
                                                         GtkWidget *tree_item);
void                gtk_tree_insert                     (GtkTree *tree,
                                                         GtkWidget *tree_item,
                                                         gint position);
void                gtk_tree_remove_items               (GtkTree *tree,
                                                         GList *items);
void                gtk_tree_clear_items                (GtkTree *tree,
                                                         gint start,
                                                         gint end);
void                gtk_tree_select_item                (GtkTree *tree,
                                                         gint item);
void                gtk_tree_unselect_item              (GtkTree *tree,
                                                         gint item);
void                gtk_tree_select_child               (GtkTree *tree,
                                                         GtkWidget *tree_item);
void                gtk_tree_unselect_child             (GtkTree *tree,
                                                         GtkWidget *tree_item);
gint                gtk_tree_child_position             (GtkTree *tree,
                                                         GtkWidget *child);
void                gtk_tree_set_selection_mode         (GtkTree *tree,
                                                         GtkSelectionMode mode);
void                gtk_tree_set_view_mode              (GtkTree *tree,
                                                         GtkTreeViewMode mode);
void                gtk_tree_set_view_lines             (GtkTree *tree,
                                                         gboolean flag);
void                gtk_tree_remove_item                (GtkTree *tree,
                                                         GtkWidget *child);

Object Hierarchy

  GObject
   +----GInitiallyUnowned
         +----GtkObject
               +----GtkWidget
                     +----GtkContainer
                           +----GtkTree

Implemented Interfaces

GtkTree implements AtkImplementorIface.

Signals

  "select-child"                                   : Run First
  "selection-changed"                              : Run First
  "unselect-child"                                 : Run First

Description

Warning

GtkTree is deprecated and unsupported. It is known to be buggy. To use it, you must define the symbol GTK_ENABLE_BROKEN prior to including the GTK+ header files. Use GtkTreeView instead.

The GtkTree widget is a container that shows users a list of items, in a tree format complete with branches and leafnodes. Branches can be expanded to show their child items, or collapsed to hide them.

Details

GtkTree

typedef struct _GtkTree GtkTree;

Warning

GtkTree is deprecated and should not be used in newly-written code.

struct _GtkTree
{
  GtkContainer container;
  GList *children;
  GtkTree* root_tree; /* owner of selection list */
  GtkWidget* tree_owner;
  GList *selection;
  guint level;
  guint indent_value;
  guint current_indent;
  guint selection_mode : 2;
  guint view_mode : 1;
  guint view_line : 1;
};

GTK_IS_ROOT_TREE()

#define GTK_IS_ROOT_TREE(obj)   ((GtkObject*) GTK_TREE(obj)->root_tree == (GtkObject*)obj)

Warning

GTK_IS_ROOT_TREE is deprecated and should not be used in newly-written code.

A macro that returns a boolean value which indicates if obj is a root tree or not.

obj : A pointer to the GtkTree. obj will accept any pointer, but if the pointer does not point to a GtkTree, the results are undefined.

GTK_TREE_ROOT_TREE()

#define GTK_TREE_ROOT_TREE(obj) (GTK_TREE(obj)->root_tree ? GTK_TREE(obj)->root_tree : GTK_TREE(obj))

Warning

GTK_TREE_ROOT_TREE is deprecated and should not be used in newly-written code.

A macro that returns the root tree of obj.

If obj is already a root tree, obj is cast to GtkTree and returned.

obj : A pointer to the GtkTree. obj will accept any pointer, but if the pointer does not point to a GtkTree, the results are undefined.

GTK_TREE_SELECTION_OLD()

#define GTK_TREE_SELECTION_OLD(obj) (GTK_TREE_ROOT_TREE(obj)->selection)

Warning

GTK_TREE_SELECTION_OLD is deprecated and should not be used in newly-written code.

obj :

enum GtkTreeViewMode

typedef enum
{
  GTK_TREE_VIEW_LINE,  /* default view mode */
  GTK_TREE_VIEW_ITEM
} GtkTreeViewMode;

Warning

GtkTreeViewMode is deprecated and should not be used in newly-written code.

gtk_tree_new ()

GtkWidget*          gtk_tree_new                        (void);

Warning

gtk_tree_new is deprecated and should not be used in newly-written code.

Creates a new GtkTree.

Returns : A pointer to the newly allocated widget.

gtk_tree_append ()

void                gtk_tree_append                     (GtkTree *tree,
                                                         GtkWidget *tree_item);

Warning

gtk_tree_append is deprecated and should not be used in newly-written code.

Adds the GtkTreeItem in tree_item to the end of the items in tree.

tree : | A pointer to a GtkTree.
tree_item : | A pointer to the GtkWidget that is to be appended to the tree.

gtk_tree_prepend ()

void                gtk_tree_prepend                    (GtkTree *tree,
                                                         GtkWidget *tree_item);

Warning

gtk_tree_prepend is deprecated and should not be used in newly-written code.

Adds the GtkTreeItem in tree_item to the start of the items in tree.

tree : | A pointer to a GtkTree.
tree_item : | A pointer to the GtkWidget that is to be prepended to the tree.

gtk_tree_insert ()

void                gtk_tree_insert                     (GtkTree *tree,
                                                         GtkWidget *tree_item,
                                                         gint position);

Warning

gtk_tree_insert is deprecated and should not be used in newly-written code.

Adds the GtkTreeItem in tree_item to the list of items in tree at the position indicated by position.

tree : | A pointer to a GtkTree.
tree_item : | A pointer to the GtkWidget that is to be added to the tree.
position : | A gint that indicates the position in the tree, that the tree_item is to be added at.

gtk_tree_remove_items ()

void                gtk_tree_remove_items               (GtkTree *tree,
                                                         GList *items);

Warning

gtk_tree_remove_items is deprecated and should not be used in newly-written code.

Removes a list of items from the GtkTree in tree.

If only one item is to be removed from the GtkTree, gtk_container_remove() can be used instead.

Removing an item from a GtkTree dereferences the item, and thus usually destroys the item and any subtrees it may contain. If the item is not to be destroyed, use g_object_ref() before removing it.

tree : | A pointer to a GtkTree.
items : | A pointer to a GList that contains the items to be removed.

gtk_tree_clear_items ()

void                gtk_tree_clear_items                (GtkTree *tree,
                                                         gint start,
                                                         gint end);

Warning

gtk_tree_clear_items is deprecated and should not be used in newly-written code.

Removes the items at positions between start and end from the GtkTree tree.

Removing an item from a GtkTree dereferences the item, and thus usually destroys the item and any subtrees it may contain. If the item is not to be destroyed, use g_object_ref() before removing it.

tree : | A pointer to a GtkTree.
start : | A gint.
end : | A gint.

gtk_tree_select_item ()

void                gtk_tree_select_item                (GtkTree *tree,
                                                         gint item);

Warning

gtk_tree_select_item is deprecated and should not be used in newly-written code.

Emits the select_item signal for the child at position item, and thus selects it (unless it is unselected in a signal handler).

tree : | A pointer to a GtkTree.
item : | A gint.

gtk_tree_unselect_item ()

void                gtk_tree_unselect_item              (GtkTree *tree,
                                                         gint item);

Warning

gtk_tree_unselect_item is deprecated and should not be used in newly-written code.

Emits the unselect_item for the child at position item, and thus unselects it.

tree : | A pointer to a GtkTree.
item : | A gint.

gtk_tree_select_child ()

void                gtk_tree_select_child               (GtkTree *tree,
                                                         GtkWidget *tree_item);

Warning

gtk_tree_select_child is deprecated and should not be used in newly-written code.

Emits the select_item signal for the child tree_item, and thus selects it (unless it is unselected in a signal handler).

tree : | A pointer to a GtkTree.
tree_item : | A pointer to the GtkWidget that is to be selected.

gtk_tree_unselect_child ()

void                gtk_tree_unselect_child             (GtkTree *tree,
                                                         GtkWidget *tree_item);

Warning

gtk_tree_unselect_child is deprecated and should not be used in newly-written code.

Emits the unselect_item signal for the child tree_item, and thus unselects it.

tree : | A pointer to a GtkTree.
tree_item : | A pointer to the GtkWidget that is to be selected.

gtk_tree_child_position ()

gint                gtk_tree_child_position             (GtkTree *tree,
                                                         GtkWidget *child);

Warning

gtk_tree_child_position is deprecated and should not be used in newly-written code.

Returns the position of child in the GtkTree tree.

If child is not a child of tree, then -1 is returned.

tree : | A pointer to a GtkTree.
child : | A pointer to a GtkWidget.
Returns : | A gint.

gtk_tree_set_selection_mode ()

void                gtk_tree_set_selection_mode         (GtkTree *tree,
                                                         GtkSelectionMode mode);

Warning

gtk_tree_set_selection_mode is deprecated and should not be used in newly-written code.

Sets the selection mode for the GtkTree tree.

mode can be one of

  • GTK_SELECTION_SINGLE for when only one item can be selected at a time.

  • GTK_SELECTION_BROWSE for when one item must be selected.

  • GTK_SELECTION_MULTIPLE for when many items can be selected at once.

  • GTK_SELECTION_EXTENDED Reserved for later use.

The selection mode is only defined for a root tree, as the root tree "owns" the selection.

The default mode is GTK_SELECTION_SINGLE.

tree : | A pointer to a GtkTree.
mode : | A GtkSelectionMode.

gtk_tree_set_view_mode ()

void                gtk_tree_set_view_mode              (GtkTree *tree,
                                                         GtkTreeViewMode mode);

Warning

gtk_tree_set_view_mode is deprecated and should not be used in newly-written code.

Sets the 'viewmode' for the GtkTree in tree. The 'viewmode' defines how the tree looks when an item is selected.

mode can be one of:

  • GTK_TREE_VIEW_LINE : When an item is selected the entire GtkTreeItem is highlighted.

  • GTK_TREE_VIEW_ITEM : When an item is selected only the selected item's child widget is highlighted.

The default mode is GTK_TREE_VIEW_LINE.

tree : | A pointer to a GtkTree.
mode : | A GtkTreeViewMode.

gtk_tree_set_view_lines ()

void                gtk_tree_set_view_lines             (GtkTree *tree,
                                                         gboolean flag);

Warning

gtk_tree_set_view_lines is deprecated and should not be used in newly-written code.

Sets whether or not the connecting lines between branches and children are drawn.

tree : | A pointer to a GtkTree.
flag : | A guint, indicating TRUE, or FALSE.

gtk_tree_remove_item ()

void                gtk_tree_remove_item                (GtkTree *tree,
                                                         GtkWidget *child);

Warning

gtk_tree_remove_item is deprecated and should not be used in newly-written code.

Removes the item child from the GtkTree tree.

tree : | A pointer to a GtkTree.
child : | A pointer to the GtkWidget that is to be removed from the tree.

Signal Details

The "select-child" signal

void                user_function                      (GtkTree   *tree,
                                                        GtkWidget *widget,
                                                        gpointer   user_data)      : Run First

This signal is emitted by tree whenever widget is about to be selected.

tree : | the object which received the signal.
widget : | The child that is about to be selected.
user_data : | user data set when the signal handler was connected.

The "selection-changed" signal

void                user_function                      (GtkTree *tree,
                                                        gpointer user_data)      : Run First

This signal is emitted by the root tree whenever the selection changes.

tree : | the object which received the signal.
user_data : | user data set when the signal handler was connected.

The "unselect-child" signal

void                user_function                      (GtkTree   *tree,
                                                        GtkWidget *widget,
                                                        gpointer   user_data)      : Run First

This signal is emitted by tree whenever widget is about to be unselected.

tree : | the object which received the signal.
widget : | The child that is about to be unselected.
user_data : | user data set when the signal handler was connected.

See Also

GtkTreeList for the items to put into a GtkTree.

GtkScrolledWindow for details on how to scroll around a GtkTree.


GtkTreeItem

GtkTreeItem — The widget used for items in a GtkTree

Synopsis

#include <gtk/gtk.h>

                    GtkTreeItem;
#define             GTK_TREE_ITEM_SUBTREE               (obj)
GtkWidget*          gtk_tree_item_new                   (void);
GtkWidget*          gtk_tree_item_new_with_label        (const gchar *label);
void                gtk_tree_item_set_subtree           (GtkTreeItem *tree_item,
                                                         GtkWidget *subtree);
void                gtk_tree_item_remove_subtree        (GtkTreeItem *tree_item);
void                gtk_tree_item_select                (GtkTreeItem *tree_item);
void                gtk_tree_item_deselect              (GtkTreeItem *tree_item);
void                gtk_tree_item_expand                (GtkTreeItem *tree_item);
void                gtk_tree_item_collapse              (GtkTreeItem *tree_item);

Object Hierarchy

  GObject
   +----GInitiallyUnowned
         +----GtkObject
               +----GtkWidget
                     +----GtkContainer
                           +----GtkBin
                                 +----GtkItem
                                       +----GtkTreeItem

Implemented Interfaces

GtkTreeItem implements AtkImplementorIface.

Signals

  "collapse"                                       : Run First
  "expand"                                         : Run First

Description

Warning

GtkTree is deprecated and unsupported. It is known to be buggy. To use it, you must define the symbol GTK_ENABLE_BROKEN prior to including the GTK+ header files. Use GtkTreeView instead.

Details

GtkTreeItem

typedef struct _GtkTreeItem GtkTreeItem;

Warning

GtkTreeItem is deprecated and should not be used in newly-written code.

GTK_TREE_ITEM_SUBTREE()

#define GTK_TREE_ITEM_SUBTREE(obj)      (GTK_TREE_ITEM(obj)->subtree)

Warning

GTK_TREE_ITEM_SUBTREE is deprecated and should not be used in newly-written code.

obj :

gtk_tree_item_new ()

GtkWidget*          gtk_tree_item_new                   (void);

Warning

gtk_tree_item_new is deprecated and should not be used in newly-written code.

Returns :

gtk_tree_item_new_with_label ()

GtkWidget*          gtk_tree_item_new_with_label        (const gchar *label);

Warning

gtk_tree_item_new_with_label is deprecated and should not be used in newly-written code.

label :
Returns :

gtk_tree_item_set_subtree ()

void                gtk_tree_item_set_subtree           (GtkTreeItem *tree_item,
                                                         GtkWidget *subtree);

Warning

gtk_tree_item_set_subtree is deprecated and should not be used in newly-written code.

tree_item :
subtree :

gtk_tree_item_remove_subtree ()

void                gtk_tree_item_remove_subtree        (GtkTreeItem *tree_item);

Warning

gtk_tree_item_remove_subtree is deprecated and should not be used in newly-written code.

tree_item :

gtk_tree_item_select ()

void                gtk_tree_item_select                (GtkTreeItem *tree_item);

Warning

gtk_tree_item_select is deprecated and should not be used in newly-written code.

tree_item :

gtk_tree_item_deselect ()

void                gtk_tree_item_deselect              (GtkTreeItem *tree_item);

Warning

gtk_tree_item_deselect is deprecated and should not be used in newly-written code.

tree_item :

gtk_tree_item_expand ()

void                gtk_tree_item_expand                (GtkTreeItem *tree_item);

Warning

gtk_tree_item_expand is deprecated and should not be used in newly-written code.

tree_item :

gtk_tree_item_collapse ()

void                gtk_tree_item_collapse              (GtkTreeItem *tree_item);

Warning

gtk_tree_item_collapse is deprecated and should not be used in newly-written code.

tree_item :

Signal Details

The "collapse" signal

void                user_function                      (GtkTreeItem *treeitem,
                                                        gpointer     user_data)      : Run First

treeitem : | the object which received the signal.
user_data : | user data set when the signal handler was connected.

The "expand" signal

void                user_function                      (GtkTreeItem *treeitem,
                                                        gpointer     user_data)      : Run First

treeitem : | the object which received the signal.
user_data : | user data set when the signal handler was connected.


GtkTreeModel

GtkTreeModel — The tree interface used by GtkTreeView

Synopsis

#include <gtk/gtk.h>

                    GtkTreeModel;
                    GtkTreeIter;
                    GtkTreePath;
                    GtkTreeRowReference;
                    GtkTreeModelIface;
gboolean            (*GtkTreeModelForeachFunc)          (GtkTreeModel *model,
                                                         GtkTreePath *path,
                                                         GtkTreeIter *iter,
                                                         gpointer data);
enum                GtkTreeModelFlags;
GtkTreePath*        gtk_tree_path_new                   (void);
GtkTreePath*        gtk_tree_path_new_from_string       (const gchar *path);
GtkTreePath*        gtk_tree_path_new_from_indices      (gint first_index,
                                                         ...);
gchar*              gtk_tree_path_to_string             (GtkTreePath *path);
GtkTreePath*        gtk_tree_path_new_first             (void);
#define             gtk_tree_path_new_root              ()
void                gtk_tree_path_append_index          (GtkTreePath *path,
                                                         gint index_);
void                gtk_tree_path_prepend_index         (GtkTreePath *path,
                                                         gint index_);
gint                gtk_tree_path_get_depth             (GtkTreePath *path);
gint*               gtk_tree_path_get_indices           (GtkTreePath *path);
void                gtk_tree_path_free                  (GtkTreePath *path);
GtkTreePath*        gtk_tree_path_copy                  (const GtkTreePath *path);
gint                gtk_tree_path_compare               (const GtkTreePath *a,
                                                         const GtkTreePath *b);
void                gtk_tree_path_next                  (GtkTreePath *path);
gboolean            gtk_tree_path_prev                  (GtkTreePath *path);
gboolean            gtk_tree_path_up                    (GtkTreePath *path);
void                gtk_tree_path_down                  (GtkTreePath *path);
gboolean            gtk_tree_path_is_ancestor           (GtkTreePath *path,
                                                         GtkTreePath *descendant);
gboolean            gtk_tree_path_is_descendant         (GtkTreePath *path,
                                                         GtkTreePath *ancestor);
GtkTreeRowReference* gtk_tree_row_reference_new         (GtkTreeModel *model,
                                                         GtkTreePath *path);
GtkTreeRowReference* gtk_tree_row_reference_new_proxy   (GObject *proxy,
                                                         GtkTreeModel *model,
                                                         GtkTreePath *path);
GtkTreeModel*       gtk_tree_row_reference_get_model    (GtkTreeRowReference *reference);
GtkTreePath*        gtk_tree_row_reference_get_path     (GtkTreeRowReference *reference);
gboolean            gtk_tree_row_reference_valid        (GtkTreeRowReference *reference);
void                gtk_tree_row_reference_free         (GtkTreeRowReference *reference);
GtkTreeRowReference* gtk_tree_row_reference_copy        (GtkTreeRowReference *reference);
void                gtk_tree_row_reference_inserted     (GObject *proxy,
                                                         GtkTreePath *path);
void                gtk_tree_row_reference_deleted      (GObject *proxy,
                                                         GtkTreePath *path);
void                gtk_tree_row_reference_reordered    (GObject *proxy,
                                                         GtkTreePath *path,
                                                         GtkTreeIter *iter,
                                                         gint *new_order);
GtkTreeIter*        gtk_tree_iter_copy                  (GtkTreeIter *iter);
void                gtk_tree_iter_free                  (GtkTreeIter *iter);
GtkTreeModelFlags   gtk_tree_model_get_flags            (GtkTreeModel *tree_model);
gint                gtk_tree_model_get_n_columns        (GtkTreeModel *tree_model);
GType               gtk_tree_model_get_column_type      (GtkTreeModel *tree_model,
                                                         gint index_);
gboolean            gtk_tree_model_get_iter             (GtkTreeModel *tree_model,
                                                         GtkTreeIter *iter,
                                                         GtkTreePath *path);
gboolean            gtk_tree_model_get_iter_from_string (GtkTreeModel *tree_model,
                                                         GtkTreeIter *iter,
                                                         const gchar *path_string);
gboolean            gtk_tree_model_get_iter_first       (GtkTreeModel *tree_model,
                                                         GtkTreeIter *iter);
#define             gtk_tree_model_get_iter_root        (tree_model, iter)
GtkTreePath*        gtk_tree_model_get_path             (GtkTreeModel *tree_model,
                                                         GtkTreeIter *iter);
void                gtk_tree_model_get_value            (GtkTreeModel *tree_model,
                                                         GtkTreeIter *iter,
                                                         gint column,
                                                         GValue *value);
gboolean            gtk_tree_model_iter_next            (GtkTreeModel *tree_model,
                                                         GtkTreeIter *iter);
gboolean            gtk_tree_model_iter_children        (GtkTreeModel *tree_model,
                                                         GtkTreeIter *iter,
                                                         GtkTreeIter *parent);
gboolean            gtk_tree_model_iter_has_child       (GtkTreeModel *tree_model,
                                                         GtkTreeIter *iter);
gint                gtk_tree_model_iter_n_children      (GtkTreeModel *tree_model,
                                                         GtkTreeIter *iter);
gboolean            gtk_tree_model_iter_nth_child       (GtkTreeModel *tree_model,
                                                         GtkTreeIter *iter,
                                                         GtkTreeIter *parent,
                                                         gint n);
gboolean            gtk_tree_model_iter_parent          (GtkTreeModel *tree_model,
                                                         GtkTreeIter *iter,
                                                         GtkTreeIter *child);
gchar*              gtk_tree_model_get_string_from_iter (GtkTreeModel *tree_model,
                                                         GtkTreeIter *iter);
void                gtk_tree_model_ref_node             (GtkTreeModel *tree_model,
                                                         GtkTreeIter *iter);
void                gtk_tree_model_unref_node           (GtkTreeModel *tree_model,
                                                         GtkTreeIter *iter);
void                gtk_tree_model_get                  (GtkTreeModel *tree_model,
                                                         GtkTreeIter *iter,
                                                         ...);
void                gtk_tree_model_get_valist           (GtkTreeModel *tree_model,
                                                         GtkTreeIter *iter,
                                                         va_list var_args);
void                gtk_tree_model_foreach              (GtkTreeModel *model,
                                                         GtkTreeModelForeachFunc func,
                                                         gpointer user_data);
void                gtk_tree_model_row_changed          (GtkTreeModel *tree_model,
                                                         GtkTreePath *path,
                                                         GtkTreeIter *iter);
void                gtk_tree_model_row_inserted         (GtkTreeModel *tree_model,
                                                         GtkTreePath *path,
                                                         GtkTreeIter *iter);
void                gtk_tree_model_row_has_child_toggled
                                                        (GtkTreeModel *tree_model,
                                                         GtkTreePath *path,
                                                         GtkTreeIter *iter);
void                gtk_tree_model_row_deleted          (GtkTreeModel *tree_model,
                                                         GtkTreePath *path);
void                gtk_tree_model_rows_reordered       (GtkTreeModel *tree_model,
                                                         GtkTreePath *path,
                                                         GtkTreeIter *iter,
                                                         gint *new_order);

Object Hierarchy

  GInterface
   +----GtkTreeModel

Prerequisites

GtkTreeModel requires GObject.

Known Derived Interfaces

GtkTreeModel is required by GtkTreeSortable.

Known Implementations

GtkTreeModel is implemented by GtkTreeModelSort, GtkTreeStore, GtkListStore and GtkTreeModelFilter.

Signals

  "row-changed"                                    : Run Last
  "row-deleted"                                    : Run First
  "row-has-child-toggled"                          : Run Last
  "row-inserted"                                   : Run First
  "rows-reordered"                                 : Run First

Description

The GtkTreeModel interface defines a generic tree interface for use by the GtkTreeView widget. It is an abstract interface, and is designed to be usable with any appropriate data structure. The programmer just has to implement this interface on their own data type for it to be viewable by a GtkTreeView widget.

The model is represented as a hierarchical tree of strongly-typed, columned data. In other words, the model can be seen as a tree where every node has different values depending on which column is being queried. The type of data found in a column is determined by using the GType system (ie. G_TYPE_INT, GTK_TYPE_BUTTON, G_TYPE_POINTER, etc.). The types are homogeneous per column across all nodes. It is important to note that this interface only provides a way of examining a model and observing changes. The implementation of each individual model decides how and if changes are made.

In order to make life simpler for programmers who do not need to write their own specialized model, two generic models are provided — the GtkTreeStore and the GtkListStore. To use these, the developer simply pushes data into these models as necessary. These models provide the data structure as well as all appropriate tree interfaces. As a result, implementing drag and drop, sorting, and storing data is trivial. For the vast majority of trees and lists, these two models are sufficient.

Models are accessed on a node/column level of granularity. One can query for the value of a model at a certain node and a certain column on that node. There are two structures used to reference a particular node in a model. They are the GtkTreePath and the GtkTreeIter [4] Most of the interface consists of operations on a GtkTreeIter.

A path is essentially a potential node. It is a location on a model that may or may not actually correspond to a node on a specific model. The GtkTreePath struct can be converted into either an array of unsigned integers or a string. The string form is a list of numbers separated by a colon. Each number refers to the offset at that level. Thus, the path “0” refers to the root node and the path “2:4” refers to the fifth child of the third node.

By contrast, a GtkTreeIter is a reference to a specific node on a specific model. It is a generic struct with an integer and three generic pointers. These are filled in by the model in a model-specific way. One can convert a path to an iterator by calling gtk_tree_model_get_iter(). These iterators are the primary way of accessing a model and are similar to the iterators used by GtkTextBuffer. They are generally statically allocated on the stack and only used for a short time. The model interface defines a set of operations using them for navigating the model.

It is expected that models fill in the iterator with private data. For example, the GtkListStore model, which is internally a simple linked list, stores a list node in one of the pointers. The GtkTreeModelSort stores an array and an offset in two of the pointers. Additionally, there is an integer field. This field is generally filled with a unique stamp per model. This stamp is for catching errors resulting from using invalid iterators with a model.

The lifecycle of an iterator can be a little confusing at first. Iterators are expected to always be valid for as long as the model is unchanged (and doesn't emit a signal). The model is considered to own all outstanding iterators and nothing needs to be done to free them from the user's point of view. Additionally, some models guarantee that an iterator is valid for as long as the node it refers to is valid (most notably the GtkTreeStore and GtkListStore). Although generally uninteresting, as one always has to allow for the case where iterators do not persist beyond a signal, some very important performance enhancements were made in the sort model. As a result, the GTK_TREE_MODEL_ITERS_PERSIST flag was added to indicate this behavior.

To help show some common operation of a model, some examples are provided. The first example shows three ways of getting the iter at the location “3:2:5”. While the first method shown is easier, the second is much more common, as you often get paths from callbacks.

Example 14. Acquiring a GtkTreeIter

/* Three ways of getting the iter pointing to the location
 */
{
  GtkTreePath *path;
  GtkTreeIter iter;
  GtkTreeIter parent_iter;

  /* get the iterator from a string */
  gtk_tree_model_get_iter_from_string (model, &iter, "3:2:5");

  /* get the iterator from a path */
  path = gtk_tree_path_new_from_string ("3:2:5");
  gtk_tree_model_get_iter (model, &iter, path);
  gtk_tree_path_free (path);

  /* walk the tree to find the iterator */
  gtk_tree_model_iter_nth_child (model, &iter, NULL, 3);
  parent_iter = iter;
  gtk_tree_model_iter_nth_child (model, &iter, &parent_iter, 2);
  parent_iter = iter;
  gtk_tree_model_iter_nth_child (model, &iter, &parent_iter, 5);
}

This second example shows a quick way of iterating through a list and getting a string and an integer from each row. The populate_model function used below is not shown, as it is specific to the GtkListStore. For information on how to write such a function, see the GtkListStore documentation.

Example 15. Reading data from a GtkTreeModel

enum
{
  STRING_COLUMN,
  INT_COLUMN,
  N_COLUMNS
};

{
  GtkTreeModel *list_store;
  GtkTreeIter iter;
  gboolean valid;
  gint row_count = 0;

  /* make a new list_store */
  list_store = gtk_list_store_new (N_COLUMNS, G_TYPE_STRING, G_TYPE_INT);

  /* Fill the list store with data */
  populate_model (list_store);

  /* Get the first iter in the list */
  valid = gtk_tree_model_get_iter_first (list_store, &iter);

  while (valid)
    {
      /* Walk through the list, reading each row */
      gchar *str_data;
      gint   int_data;

      /* Make sure you terminate calls to gtk_tree_model_get()
       * with a '-1' value
       */
      gtk_tree_model_get (list_store, &iter,
                          STRING_COLUMN, &str_data,
                          INT_COLUMN, &int_data,
                          -1);

      /* Do something with the data */
      g_print ("Row %d: (%s,%d)\n", row_count, str_data, int_data);
      g_free (str_data);

      row_count ++;
      valid = gtk_tree_model_iter_next (list_store, &iter);
    }
}

Details

GtkTreeModel

typedef struct _GtkTreeModel GtkTreeModel;

GtkTreeIter

typedef struct {
  gint stamp;
  gpointer user_data;
  gpointer user_data2;
  gpointer user_data3;
} GtkTreeIter;

The GtkTreeIter is the primary structure for accessing a structure. Models are expected to put a unique integer in the stamp member, and put model-specific data in the three user_data members.

gint stamp; | A unique stamp to catch invalid iterators
gpointer user_data; | Model specific data
gpointer user_data2; | Model specific data
gpointer user_data3; | Model specific data

GtkTreePath

typedef struct _GtkTreePath GtkTreePath;

GtkTreeRowReference

typedef struct _GtkTreeRowReference GtkTreeRowReference;

GtkTreeModelIface

typedef struct {
  GTypeInterface g_iface;

  /* Signals */
  void         (* row_changed)           (GtkTreeModel *tree_model,
                      GtkTreePath  *path,
                      GtkTreeIter  *iter);
  void         (* row_inserted)          (GtkTreeModel *tree_model,
                      GtkTreePath  *path,
                      GtkTreeIter  *iter);
  void         (* row_has_child_toggled) (GtkTreeModel *tree_model,
                      GtkTreePath  *path,
                      GtkTreeIter  *iter);
  void         (* row_deleted)           (GtkTreeModel *tree_model,
                      GtkTreePath  *path);
  void         (* rows_reordered)        (GtkTreeModel *tree_model,
                      GtkTreePath  *path,
                      GtkTreeIter  *iter,
                      gint         *new_order);

  /* Virtual Table */
  GtkTreeModelFlags (* get_flags)  (GtkTreeModel *tree_model);

  gint         (* get_n_columns)   (GtkTreeModel *tree_model);
  GType        (* get_column_type) (GtkTreeModel *tree_model,
                    gint          index_);
  gboolean     (* get_iter)        (GtkTreeModel *tree_model,
                    GtkTreeIter  *iter,
                    GtkTreePath  *path);
  GtkTreePath *(* get_path)        (GtkTreeModel *tree_model,
                    GtkTreeIter  *iter);
  void         (* get_value)       (GtkTreeModel *tree_model,
                    GtkTreeIter  *iter,
                    gint          column,
                    GValue       *value);
  gboolean     (* iter_next)       (GtkTreeModel *tree_model,
                    GtkTreeIter  *iter);
  gboolean     (* iter_children)   (GtkTreeModel *tree_model,
                    GtkTreeIter  *iter,
                    GtkTreeIter  *parent);
  gboolean     (* iter_has_child)  (GtkTreeModel *tree_model,
                    GtkTreeIter  *iter);
  gint         (* iter_n_children) (GtkTreeModel *tree_model,
                    GtkTreeIter  *iter);
  gboolean     (* iter_nth_child)  (GtkTreeModel *tree_model,
                    GtkTreeIter  *iter,
                    GtkTreeIter  *parent,
                    gint          n);
  gboolean     (* iter_parent)     (GtkTreeModel *tree_model,
                    GtkTreeIter  *iter,
                    GtkTreeIter  *child);
  void         (* ref_node)        (GtkTreeModel *tree_model,
                    GtkTreeIter  *iter);
  void         (* unref_node)      (GtkTreeModel *tree_model,
                    GtkTreeIter  *iter);
} GtkTreeModelIface;

GtkTreeModelForeachFunc ()

gboolean            (*GtkTreeModelForeachFunc)          (GtkTreeModel *model,
                                                         GtkTreePath *path,
                                                         GtkTreeIter *iter,
                                                         gpointer data);

model :
path :
iter :
data :
Returns :

enum GtkTreeModelFlags

typedef enum
{
  GTK_TREE_MODEL_ITERS_PERSIST = 1 << 0,
  GTK_TREE_MODEL_LIST_ONLY = 1 << 1
} GtkTreeModelFlags;

These flags indicate various properties of a GtkTreeModel. They are returned by gtk_tree_model_get_flags(), and must be static for the lifetime of the object. A more complete description of GTK_TREE_MODEL_ITERS_PERSIST can be found in the overview of this section.

GTK_TREE_MODEL_ITERS_PERSIST | Iterators survive all signals emitted by the tree.
GTK_TREE_MODEL_LIST_ONLY | The model is a list only, and never has children

gtk_tree_path_new ()

GtkTreePath*        gtk_tree_path_new                   (void);

Creates a new GtkTreePath. This structure refers to a row.

Returns : A newly created GtkTreePath.

gtk_tree_path_new_from_string ()

GtkTreePath*        gtk_tree_path_new_from_string       (const gchar *path);

Creates a new GtkTreePath initialized to path. path is expected to be a colon separated list of numbers. For example, the string "10:4:0" would create a path of depth 3 pointing to the 11th child of the root node, the 5th child of that 11th child, and the 1st child of that 5th child. If an invalid path string is passed in, NULL is returned.

path : | The string representation of a path.
Returns : | A newly-created GtkTreePath, or NULL

gtk_tree_path_new_from_indices ()

GtkTreePath*        gtk_tree_path_new_from_indices      (gint first_index,
                                                         ...);

Creates a new path with first_index and varargs as indices.

first_index : | first integer
... : | list of integers terminated by -1
Returns : | A newly created GtkTreePath.

Since 2.2

gtk_tree_path_to_string ()

gchar*              gtk_tree_path_to_string             (GtkTreePath *path);

Generates a string representation of the path. This string is a ':' separated list of numbers. For example, "4:10:0:3" would be an acceptable return value for this string.

path : | A GtkTreePath
Returns : | A newly-allocated string. Must be freed with g_free().

gtk_tree_path_new_first ()

GtkTreePath*        gtk_tree_path_new_first             (void);

Creates a new GtkTreePath. The string representation of this path is "0"

Returns : A new GtkTreePath.

gtk_tree_path_new_root()

#define gtk_tree_path_new_root() gtk_tree_path_new_first()

Warning

gtk_tree_path_new_root is deprecated and should not be used in newly-written code. Use gtk_tree_path_new_first() instead.

An alternate name for gtk_tree_path_new_first() provided for compatibility reasons.

Returns : A new GtkTreePath.

gtk_tree_path_append_index ()

void                gtk_tree_path_append_index          (GtkTreePath *path,
                                                         gint index_);

Appends a new index to a path. As a result, the depth of the path is increased.

path : | A GtkTreePath.
index_ : | The index.

gtk_tree_path_prepend_index ()

void                gtk_tree_path_prepend_index         (GtkTreePath *path,
                                                         gint index_);

Prepends a new index to a path. As a result, the depth of the path is increased.

path : | A GtkTreePath.
index_ : | The index.

gtk_tree_path_get_depth ()

gint                gtk_tree_path_get_depth             (GtkTreePath *path);

Returns the current depth of path.

path : | A GtkTreePath.
Returns : | The depth of path

gtk_tree_path_get_indices ()

gint*               gtk_tree_path_get_indices           (GtkTreePath *path);

Returns the current indices of path. This is an array of integers, each representing a node in a tree. This value should not be freed.

path : | A GtkTreePath.
Returns : | The current indices, or NULL.

gtk_tree_path_free ()

void                gtk_tree_path_free                  (GtkTreePath *path);

Frees path.

path : A GtkTreePath.

gtk_tree_path_copy ()

GtkTreePath*        gtk_tree_path_copy                  (const GtkTreePath *path);

Creates a new GtkTreePath as a copy of path.

path : | A GtkTreePath.
Returns : | A new GtkTreePath.

gtk_tree_path_compare ()

gint                gtk_tree_path_compare               (const GtkTreePath *a,
                                                         const GtkTreePath *b);

Compares two paths. If a appears before b in a tree, then -1 is returned. If b appears before a, then 1 is returned. If the two nodes are equal, then 0 is returned.

a : | A GtkTreePath.
b : | A GtkTreePath to compare with.
Returns : | The relative positions of a and b

gtk_tree_path_next ()

void                gtk_tree_path_next                  (GtkTreePath *path);

Moves the path to point to the next potential node at the current depth. You must use gtk_tree_model_get_iter() to discover whether a corresponding row actually exists.

path : A GtkTreePath.

gtk_tree_path_prev ()

gboolean            gtk_tree_path_prev                  (GtkTreePath *path);

Moves the path to point to the previous node at the current depth, if it exists.

path : | A GtkTreePath.
Returns : | TRUE if path has a previous node, and the move was made.

gtk_tree_path_up ()

gboolean            gtk_tree_path_up                    (GtkTreePath *path);

Moves the path to point to its parent node, if it has a parent.

path : | A GtkTreePath.
Returns : | TRUE if path has a parent, and the move was made.

gtk_tree_path_down ()

void                gtk_tree_path_down                  (GtkTreePath *path);

Moves path to point to the first child of the current path.

path : A GtkTreePath.

gtk_tree_path_is_ancestor ()

gboolean            gtk_tree_path_is_ancestor           (GtkTreePath *path,
                                                         GtkTreePath *descendant);

Returns TRUE if descendant is a descendant of path.

path : | a GtkTreePath
descendant : | another GtkTreePath
Returns : | TRUE if descendant is contained inside path

gtk_tree_path_is_descendant ()

gboolean            gtk_tree_path_is_descendant         (GtkTreePath *path,
                                                         GtkTreePath *ancestor);

Returns TRUE if path is a descendant of ancestor.

path : | a GtkTreePath
ancestor : | another GtkTreePath
Returns : | TRUE if ancestor contains path somewhere below it

gtk_tree_row_reference_new ()

GtkTreeRowReference* gtk_tree_row_reference_new         (GtkTreeModel *model,
                                                         GtkTreePath *path);

Creates a row reference based on path. This reference will keep pointing to the node pointed to by path, so long as it exists. It listens to all signals emitted by model, and updates its path appropriately. If path isn't a valid path in model, then NULL is returned.

model : | A GtkTreeModel
path : | A valid GtkTreePath to monitor
Returns : | A newly allocated GtkTreeRowReference, or NULL

gtk_tree_row_reference_new_proxy ()

GtkTreeRowReference* gtk_tree_row_reference_new_proxy   (GObject *proxy,
                                                         GtkTreeModel *model,
                                                         GtkTreePath *path);

You do not need to use this function. Creates a row reference based on path. This reference will keep pointing to the node pointed to by path, so long as it exists. If path isn't a valid path in model, then NULL is returned. However, unlike references created with gtk_tree_row_reference_new(), it does not listen to the model for changes. The creator of the row reference must do this explicitly using gtk_tree_row_reference_inserted(), gtk_tree_row_reference_deleted(), gtk_tree_row_reference_reordered().

These functions must be called exactly once per proxy when the corresponding signal on the model is emitted. This single call updates all row references for that proxy. Since built-in GTK+ objects like GtkTreeView already use this mechanism internally, using them as the proxy object will produce unpredictable results. Further more, passing the same object as model and proxy doesn't work for reasons of internal implementation.

This type of row reference is primarily meant by structures that need to carefully monitor exactly when a row reference updates itself, and is not generally needed by most applications.

proxy : | A proxy GObject
model : | A GtkTreeModel
path : | A valid GtkTreePath to monitor
Returns : | A newly allocated GtkTreeRowReference, or NULL

gtk_tree_row_reference_get_model ()

GtkTreeModel*       gtk_tree_row_reference_get_model    (GtkTreeRowReference *reference);

Returns the model that the row reference is monitoring.

reference : | A GtkTreeRowReference
Returns : | the model

Since 2.8

gtk_tree_row_reference_get_path ()

GtkTreePath*        gtk_tree_row_reference_get_path     (GtkTreeRowReference *reference);

Returns a path that the row reference currently points to, or NULL if the path pointed to is no longer valid.

reference : | A GtkTreeRowReference
Returns : | A current path, or NULL.

gtk_tree_row_reference_valid ()

gboolean            gtk_tree_row_reference_valid        (GtkTreeRowReference *reference);

Returns TRUE if the reference is non-NULL and refers to a current valid path.

reference : | A GtkTreeRowReference, or NULL
Returns : | TRUE if reference points to a valid path.

gtk_tree_row_reference_free ()

void                gtk_tree_row_reference_free         (GtkTreeRowReference *reference);

Free's reference. reference may be NULL.

reference : A GtkTreeRowReference, or NULL

gtk_tree_row_reference_copy ()

GtkTreeRowReference* gtk_tree_row_reference_copy        (GtkTreeRowReference *reference);

Copies a GtkTreeRowReference.

reference : | a GtkTreeRowReference
Returns : | a copy of reference.

Since 2.2

gtk_tree_row_reference_inserted ()

void                gtk_tree_row_reference_inserted     (GObject *proxy,
                                                         GtkTreePath *path);

Lets a set of row reference created by gtk_tree_row_reference_new_proxy() know that the model emitted the "row_inserted" signal.

proxy : | A GObject
path : | The row position that was inserted

gtk_tree_row_reference_deleted ()

void                gtk_tree_row_reference_deleted      (GObject *proxy,
                                                         GtkTreePath *path);

Lets a set of row reference created by gtk_tree_row_reference_new_proxy() know that the model emitted the "row_deleted" signal.

proxy : | A GObject
path : | The path position that was deleted

gtk_tree_row_reference_reordered ()

void                gtk_tree_row_reference_reordered    (GObject *proxy,
                                                         GtkTreePath *path,
                                                         GtkTreeIter *iter,
                                                         gint *new_order);

Lets a set of row reference created by gtk_tree_row_reference_new_proxy() know that the model emitted the "rows_reordered" signal.

proxy : | A GObject
path : | The parent path of the reordered signal
iter : | The iter pointing to the parent of the reordered
new_order : | The new order of rows

gtk_tree_iter_copy ()

GtkTreeIter*        gtk_tree_iter_copy                  (GtkTreeIter *iter);

Creates a dynamically allocated tree iterator as a copy of iter. This function is not intended for use in applications, because you can just copy the structs by value (GtkTreeIter new_iter = iter;). You must free this iter with gtk_tree_iter_free().

iter : | A GtkTreeIter.
Returns : | a newly-allocated copy of iter.

gtk_tree_iter_free ()

void                gtk_tree_iter_free                  (GtkTreeIter *iter);

Frees an iterator that has been allocated on the heap. This function is mainly used for language bindings.

iter : A dynamically allocated tree iterator.

gtk_tree_model_get_flags ()

GtkTreeModelFlags   gtk_tree_model_get_flags            (GtkTreeModel *tree_model);

Returns a set of flags supported by this interface. The flags are a bitwise combination of GtkTreeModelFlags. The flags supported should not change during the lifecycle of the tree_model.

tree_model : | A GtkTreeModel.
Returns : | The flags supported by this interface.

gtk_tree_model_get_n_columns ()

gint                gtk_tree_model_get_n_columns        (GtkTreeModel *tree_model);

Returns the number of columns supported by tree_model.

tree_model : | A GtkTreeModel.
Returns : | The number of columns.

gtk_tree_model_get_column_type ()

GType               gtk_tree_model_get_column_type      (GtkTreeModel *tree_model,
                                                         gint index_);

Returns the type of the column.

tree_model : | A GtkTreeModel.
index_ : | The column index.
Returns : | The type of the column.

gtk_tree_model_get_iter ()

gboolean            gtk_tree_model_get_iter             (GtkTreeModel *tree_model,
                                                         GtkTreeIter *iter,
                                                         GtkTreePath *path);

Sets iter to a valid iterator pointing to path.

tree_model : | A GtkTreeModel.
iter : | The uninitialized GtkTreeIter.
path : | The GtkTreePath.
Returns : | TRUE, if iter was set.

gtk_tree_model_get_iter_from_string ()

gboolean            gtk_tree_model_get_iter_from_string (GtkTreeModel *tree_model,
                                                         GtkTreeIter *iter,
                                                         const gchar *path_string);

Sets iter to a valid iterator pointing to path_string, if it exists. Otherwise, iter is left invalid and FALSE is returned.

tree_model : | A GtkTreeModel.
iter : | An uninitialized GtkTreeIter.
path_string : | A string representation of a GtkTreePath.
Returns : | TRUE, if iter was set.

gtk_tree_model_get_iter_first ()

gboolean            gtk_tree_model_get_iter_first       (GtkTreeModel *tree_model,
                                                         GtkTreeIter *iter);

Initializes iter with the first iterator in the tree (the one at the path "0") and returns TRUE. Returns FALSE if the tree is empty.

tree_model : | A GtkTreeModel.
iter : | The uninitialized GtkTreeIter.
Returns : | TRUE, if iter was set.

gtk_tree_model_get_iter_root()

#define gtk_tree_model_get_iter_root(tree_model, iter) gtk_tree_model_get_iter_first(tree_model, iter)

Warning

gtk_tree_model_get_iter_root is deprecated and should not be used in newly-written code.

A alternate name for gtk_tree_model_get_iter_first() provided for compatibility reasons; this macro will be deprecated in future versions of GTK+.

tree_model : | A GtkTreeModel.
iter : | uninitialized GtkTreeIter.
Returns : | TRUE, if iter was set.

gtk_tree_model_get_path ()

GtkTreePath*        gtk_tree_model_get_path             (GtkTreeModel *tree_model,
                                                         GtkTreeIter *iter);

Returns a newly-created GtkTreePath referenced by iter. This path should be freed with gtk_tree_path_free().

tree_model : | A GtkTreeModel.
iter : | The GtkTreeIter.
Returns : | a newly-created GtkTreePath.

gtk_tree_model_get_value ()

void                gtk_tree_model_get_value            (GtkTreeModel *tree_model,
                                                         GtkTreeIter *iter,
                                                         gint column,
                                                         GValue *value);

Sets initializes and sets value to that at column. When done with value, g_value_unset() needs to be called to free any allocated memory.

tree_model : | A GtkTreeModel.
iter : | The GtkTreeIter.
column : | The column to lookup the value at.
value : | An empty GValue to set.

gtk_tree_model_iter_next ()

gboolean            gtk_tree_model_iter_next            (GtkTreeModel *tree_model,
                                                         GtkTreeIter *iter);

Sets iter to point to the node following it at the current level. If there is no next iter, FALSE is returned and iter is set to be invalid.

tree_model : | A GtkTreeModel.
iter : | The GtkTreeIter.
Returns : | TRUE if iter has been changed to the next node.

gtk_tree_model_iter_children ()

gboolean            gtk_tree_model_iter_children        (GtkTreeModel *tree_model,
                                                         GtkTreeIter *iter,
                                                         GtkTreeIter *parent);

Sets iter to point to the first child of parent. If parent has no children, FALSE is returned and iter is set to be invalid. parent will remain a valid node after this function has been called.

If parent is NULL returns the first node, equivalent to gtk_tree_model_get_iter_first (tree_model, iter);

tree_model : | A GtkTreeModel.
iter : | The new GtkTreeIter to be set to the child.
parent : | The GtkTreeIter, or NULL
Returns : | TRUE, if child has been set to the first child.

gtk_tree_model_iter_has_child ()

gboolean            gtk_tree_model_iter_has_child       (GtkTreeModel *tree_model,
                                                         GtkTreeIter *iter);

Returns TRUE if iter has children, FALSE otherwise.

tree_model : | A GtkTreeModel.
iter : | The GtkTreeIter to test for children.
Returns : | TRUE if iter has children.

gtk_tree_model_iter_n_children ()

gint                gtk_tree_model_iter_n_children      (GtkTreeModel *tree_model,
                                                         GtkTreeIter *iter);

Returns the number of children that iter has. As a special case, if iter is NULL, then the number of toplevel nodes is returned.

tree_model : | A GtkTreeModel.
iter : | The GtkTreeIter, or NULL.
Returns : | The number of children of iter.

gtk_tree_model_iter_nth_child ()

gboolean            gtk_tree_model_iter_nth_child       (GtkTreeModel *tree_model,
                                                         GtkTreeIter *iter,
                                                         GtkTreeIter *parent,
                                                         gint n);

Sets iter to be the child of parent, using the given index. The first index is 0. If n is too big, or parent has no children, iter is set to an invalid iterator and FALSE is returned. parent will remain a valid node after this function has been called. As a special case, if parent is NULL, then the nth root node is set.

tree_model : | A GtkTreeModel.
iter : | The GtkTreeIter to set to the nth child.
parent : | The GtkTreeIter to get the child from, or NULL.
n : | Then index of the desired child.
Returns : | TRUE, if parent has an nth child.

gtk_tree_model_iter_parent ()

gboolean            gtk_tree_model_iter_parent          (GtkTreeModel *tree_model,
                                                         GtkTreeIter *iter,
                                                         GtkTreeIter *child);

Sets iter to be the parent of child. If child is at the toplevel, and doesn't have a parent, then iter is set to an invalid iterator and FALSE is returned. child will remain a valid node after this function has been called.

tree_model : | A GtkTreeModel
iter : | The new GtkTreeIter to set to the parent.
child : | The GtkTreeIter.
Returns : | TRUE, if iter is set to the parent of child.

gtk_tree_model_get_string_from_iter ()

gchar*              gtk_tree_model_get_string_from_iter (GtkTreeModel *tree_model,
                                                         GtkTreeIter *iter);

Generates a string representation of the iter. This string is a ':' separated list of numbers. For example, "4:10:0:3" would be an acceptable return value for this string.

tree_model : | A GtkTreeModel.
iter : | An GtkTreeIter.
Returns : | A newly-allocated string. Must be freed with g_free().

Since 2.2

gtk_tree_model_ref_node ()

void                gtk_tree_model_ref_node             (GtkTreeModel *tree_model,
                                                         GtkTreeIter *iter);

Lets the tree ref the node. This is an optional method for models to implement. To be more specific, models may ignore this call as it exists primarily for performance reasons.

This function is primarily meant as a way for views to let caching model know when nodes are being displayed (and hence, whether or not to cache that node.) For example, a file-system based model would not want to keep the entire file-hierarchy in memory, just the sections that are currently being displayed by every current view.

A model should be expected to be able to get an iter independent of its reffed state.

tree_model : | A GtkTreeModel.
iter : | The GtkTreeIter.

gtk_tree_model_unref_node ()

void                gtk_tree_model_unref_node           (GtkTreeModel *tree_model,
                                                         GtkTreeIter *iter);

Lets the tree unref the node. This is an optional method for models to implement. To be more specific, models may ignore this call as it exists primarily for performance reasons.

For more information on what this means, see gtk_tree_model_ref_node(). Please note that nodes that are deleted are not unreffed.

tree_model : | A GtkTreeModel.
iter : | The GtkTreeIter.

gtk_tree_model_get ()

void                gtk_tree_model_get                  (GtkTreeModel *tree_model,
                                                         GtkTreeIter *iter,
                                                         ...);

Gets the value of one or more cells in the row referenced by iter. The variable argument list should contain integer column numbers, each column number followed by a place to store the value being retrieved. The list is terminated by a -1. For example, to get a value from column 0 with type G_TYPE_STRING, you would write: gtk_tree_model_get (model, iter, 0, &place_string_here, -1), where place_string_here is a gchar* to be filled with the string. If appropriate, the returned values have to be freed or unreferenced.

tree_model : | a GtkTreeModel
iter : | a row in tree_model
... : | pairs of column number and value return locations, terminated by -1

gtk_tree_model_get_valist ()

void                gtk_tree_model_get_valist           (GtkTreeModel *tree_model,
                                                         GtkTreeIter *iter,
                                                         va_list var_args);

See gtk_tree_model_get(), this version takes a va_list for language bindings to use.

tree_model : | a GtkTreeModel
iter : | a row in tree_model
var_args : | va_list of column/return location pairs

gtk_tree_model_foreach ()

void                gtk_tree_model_foreach              (GtkTreeModel *model,
                                                         GtkTreeModelForeachFunc func,
                                                         gpointer user_data);

Calls func on each node in model in a depth-first fashion. If func returns TRUE, then the tree ceases to be walked, and gtk_tree_model_foreach() returns.

model : | A GtkTreeModel
func : | A function to be called on each row
user_data : | User data to passed to func.

gtk_tree_model_row_changed ()

void                gtk_tree_model_row_changed          (GtkTreeModel *tree_model,
                                                         GtkTreePath *path,
                                                         GtkTreeIter *iter);

Emits the "row_changed" signal on tree_model.

tree_model : | A GtkTreeModel
path : | A GtkTreePath pointing to the changed row
iter : | A valid GtkTreeIter pointing to the changed row

gtk_tree_model_row_inserted ()

void                gtk_tree_model_row_inserted         (GtkTreeModel *tree_model,
                                                         GtkTreePath *path,
                                                         GtkTreeIter *iter);

Emits the "row_inserted" signal on tree_model

tree_model : | A GtkTreeModel
path : | A GtkTreePath pointing to the inserted row
iter : | A valid GtkTreeIter pointing to the inserted row

gtk_tree_model_row_has_child_toggled ()

void                gtk_tree_model_row_has_child_toggled
                                                        (GtkTreeModel *tree_model,
                                                         GtkTreePath *path,
                                                         GtkTreeIter *iter);

Emits the "row_has_child_toggled" signal on tree_model. This should be called by models after the child state of a node changes.

tree_model : | A GtkTreeModel
path : | A GtkTreePath pointing to the changed row
iter : | A valid GtkTreeIter pointing to the changed row

gtk_tree_model_row_deleted ()

void                gtk_tree_model_row_deleted          (GtkTreeModel *tree_model,
                                                         GtkTreePath *path);

Emits the "row_deleted" signal on tree_model. This should be called by models after a row has been removed. The location pointed to by path should be the location that the row previously was at. It may not be a valid location anymore.

tree_model : | A GtkTreeModel
path : | A GtkTreePath pointing to the previous location of the deleted row.

gtk_tree_model_rows_reordered ()

void                gtk_tree_model_rows_reordered       (GtkTreeModel *tree_model,
                                                         GtkTreePath *path,
                                                         GtkTreeIter *iter,
                                                         gint *new_order);

Emits the "rows_reordered" signal on tree_model. This should be called by models when their rows have been reordered.

tree_model : | A GtkTreeModel
path : | A GtkTreePath pointing to the tree node whose children have been reordered
iter : | A valid GtkTreeIter pointing to the node whose children have been reordered, or NULL if the depth of path is 0.
new_order : | an array of integers mapping the current position of each child to its old position before the re-ordering, i.e. new_order[newpos] = oldpos.

Signal Details

The "row-changed" signal

void                user_function                      (GtkTreeModel *tree_model,
                                                        GtkTreePath  *path,
                                                        GtkTreeIter  *iter,
                                                        gpointer      user_data)       : Run Last

This signal is emitted when a row in the model has changed.

tree_model : | the GtkTreeModel on which the signal is emitted
path : | a GtkTreePath identifying the changed row
iter : | a valid GtkTreeIter pointing to the changed row
user_data : | user data set when the signal handler was connected.

The "row-deleted" signal

void                user_function                      (GtkTreeModel *tree_model,
                                                        GtkTreePath  *path,
                                                        gpointer      user_data)       : Run First

This signal is emitted when a row has been deleted.

Note that no iterator is passed to the signal handler, since the row is already deleted.

Implementations of GtkTreeModel must emit row-deleted before removing the node from its internal data structures. This is because models and views which access and monitor this model might have references on the node which need to be released in the row-deleted handler.

tree_model : | the GtkTreeModel on which the signal is emitted
path : | a GtkTreePath identifying the row
user_data : | user data set when the signal handler was connected.

The "row-has-child-toggled" signal

void                user_function                      (GtkTreeModel *tree_model,
                                                        GtkTreePath  *path,
                                                        GtkTreeIter  *iter,
                                                        gpointer      user_data)       : Run Last

This signal is emitted when a row has gotten the first child row or lost its last child row.

tree_model : | the GtkTreeModel on which the signal is emitted
path : | a GtkTreePath identifying the row
iter : | a valid GtkTreeIter pointing to the row
user_data : | user data set when the signal handler was connected.

The "row-inserted" signal

void                user_function                      (GtkTreeModel *tree_model,
                                                        GtkTreePath  *path,
                                                        GtkTreeIter  *iter,
                                                        gpointer      user_data)       : Run First

This signal is emitted when a new row has been inserted in the model.

Note that the row may still be empty at this point, since it is a common pattern to first insert an empty row, and then fill it with the desired values.

tree_model : | the GtkTreeModel on which the signal is emitted
path : | a GtkTreePath identifying the new row
iter : | a valid GtkTreeIter pointing to the new row
user_data : | user data set when the signal handler was connected.

The "rows-reordered" signal

void                user_function                      (GtkTreeModel *tree_model,
                                                        GtkTreePath  *path,
                                                        GtkTreeIter  *iter,
                                                        gpointer      arg3,
                                                        gpointer      user_data)       : Run First

This signal is emitted when the children of a node in the GtkTreeModel have been reordered.

Note that this signal is not emitted when rows are reordered by DND, since this is implemented by removing and then reinserting the row.

tree_model : | the GtkTreeModel on which the signal is emitted
path : | a GtkTreePath identifying the tree node whose children have been reordered
iter : | a valid GtkTreeIter pointing to the node whose
user_data : | user data set when the signal handler was connected.

See Also

GtkTreeView, GtkTreeStore, GtkListStore, GtkTreeDnd, GtkTreeSortable

[4] Here, iter is short for “iterator”


GtkTreeModelFilter

GtkTreeModelFilter — A GtkTreeModel which hides parts of an underlying tree model

Synopsis

#include <gtk/gtk.h>

                    GtkTreeModelFilter;
gboolean            (*GtkTreeModelFilterVisibleFunc)    (GtkTreeModel *model,
                                                         GtkTreeIter *iter,
                                                         gpointer data);
void                (*GtkTreeModelFilterModifyFunc)     (GtkTreeModel *model,
                                                         GtkTreeIter *iter,
                                                         GValue *value,
                                                         gint column,
                                                         gpointer data);
GtkTreeModel*       gtk_tree_model_filter_new           (GtkTreeModel *child_model,
                                                         GtkTreePath *root);
void                gtk_tree_model_filter_set_visible_func
                                                        (GtkTreeModelFilter *filter,
                                                         GtkTreeModelFilterVisibleFunc func,
                                                         gpointer data,
                                                         GtkDestroyNotify destroy);
void                gtk_tree_model_filter_set_modify_func
                                                        (GtkTreeModelFilter *filter,
                                                         gint n_columns,
                                                         GType *types,
                                                         GtkTreeModelFilterModifyFunc func,
                                                         gpointer data,
                                                         GtkDestroyNotify destroy);
void                gtk_tree_model_filter_set_visible_column
                                                        (GtkTreeModelFilter *filter,
                                                         gint column);
GtkTreeModel*       gtk_tree_model_filter_get_model     (GtkTreeModelFilter *filter);
gboolean            gtk_tree_model_filter_convert_child_iter_to_iter
                                                        (GtkTreeModelFilter *filter,
                                                         GtkTreeIter *filter_iter,
                                                         GtkTreeIter *child_iter);
void                gtk_tree_model_filter_convert_iter_to_child_iter
                                                        (GtkTreeModelFilter *filter,
                                                         GtkTreeIter *child_iter,
                                                         GtkTreeIter *filter_iter);
GtkTreePath*        gtk_tree_model_filter_convert_child_path_to_path
                                                        (GtkTreeModelFilter *filter,
                                                         GtkTreePath *child_path);
GtkTreePath*        gtk_tree_model_filter_convert_path_to_child_path
                                                        (GtkTreeModelFilter *filter,
                                                         GtkTreePath *filter_path);
void                gtk_tree_model_filter_refilter      (GtkTreeModelFilter *filter);
void                gtk_tree_model_filter_clear_cache   (GtkTreeModelFilter *filter);

Object Hierarchy

  GObject
   +----GtkTreeModelFilter

Implemented Interfaces

GtkTreeModelFilter implements GtkTreeModel and GtkTreeDragSource.

Properties

  "child-model"              GtkTreeModel          : Read / Write / Construct Only
  "virtual-root"             GtkTreePath           : Read / Write / Construct Only

Description

A GtkTreeModelFilter is a tree model which wraps another tree model, and can do the following things:

  • Filter specific rows, based on data from a "visible column", a column storing booleans indicating whether the row should be filtered or not, or based on the return value of a "visible function", which gets a model, iter and user_data and returns a boolean indicating whether the row should be filtered or not.

  • Modify the "appearance" of the model, using a modify function. This is extremely powerful and allows for just changing some values and also for creating a completely different model based on the given child model.

  • Set a different root node, also known as a "virtual root". You can pass in a GtkTreePath indicating the root node for the filter at construction time.

Details

GtkTreeModelFilter

typedef struct _GtkTreeModelFilter GtkTreeModelFilter;

The GtkTreeModelFilter struct contains only private fields.

GtkTreeModelFilterVisibleFunc ()

gboolean            (*GtkTreeModelFilterVisibleFunc)    (GtkTreeModel *model,
                                                         GtkTreeIter *iter,
                                                         gpointer data);

A function which decides whether the row indicated by iter is visible.

model : | the child model of the GtkTreeModelFilter
iter : | a GtkTreeIter pointing to the row in model whose visibility is determined
data : | user data given to gtk_tree_model_filter_set_visible_func()
Returns : | Whether the row indicated by iter is visible.

GtkTreeModelFilterModifyFunc ()

void                (*GtkTreeModelFilterModifyFunc)     (GtkTreeModel *model,
                                                         GtkTreeIter *iter,
                                                         GValue *value,
                                                         gint column,
                                                         gpointer data);

A function which calculates display values from raw values in the model. It must fill value with the display value for the column column in the row indicated by iter.

Since this function is called for each data access, it's not a particularly efficient operation.

model : | the GtkTreeModelFilter
iter : | a GtkTreeIter pointing to the row whose display values are determined
value : | A GValue which is already initialized for with the correct type for the column column.
column : | the column whose display value is determined
data : | user data given to gtk_tree_model_filter_set_modify_func()

gtk_tree_model_filter_new ()

GtkTreeModel*       gtk_tree_model_filter_new           (GtkTreeModel *child_model,
                                                         GtkTreePath *root);

Creates a new GtkTreeModel, with child_model as the child_model and root as the virtual root.

child_model : | A GtkTreeModel.
root : | A GtkTreePath or NULL.
Returns : | A new GtkTreeModel.

Since 2.4

gtk_tree_model_filter_set_visible_func ()

void                gtk_tree_model_filter_set_visible_func
                                                        (GtkTreeModelFilter *filter,
                                                         GtkTreeModelFilterVisibleFunc func,
                                                         gpointer data,
                                                         GtkDestroyNotify destroy);

Sets the visible function used when filtering the filter to be func. The function should return TRUE if the given row should be visible and FALSE otherwise.

If the condition calculated by the function changes over time (e.g. because it depends on some global parameters), you must call gtk_tree_model_filter_refilter() to keep the visibility information of the model uptodate.

filter : | A GtkTreeModelFilter.
func : | A GtkTreeModelFilterVisibleFunc, the visible function.
data : | User data to pass to the visible function, or NULL.
destroy : | Destroy notifier of data, or NULL.

Since 2.4

gtk_tree_model_filter_set_modify_func ()

void                gtk_tree_model_filter_set_modify_func
                                                        (GtkTreeModelFilter *filter,
                                                         gint n_columns,
                                                         GType *types,
                                                         GtkTreeModelFilterModifyFunc func,
                                                         gpointer data,
                                                         GtkDestroyNotify destroy);

With the n_columns and types parameters, you give an array of column types for this model (which will be exposed to the parent model/view). The func, data and destroy parameters are for specifying the modify function. The modify function will get called for each data access, the goal of the modify function is to return the data which should be displayed at the location specified using the parameters of the modify function.

filter : | A GtkTreeModelFilter.
n_columns : | The number of columns in the filter model.
types : | The GTypes of the columns.
func : | A GtkTreeModelFilterModifyFunc
data : | User data to pass to the modify function, or NULL.
destroy : | Destroy notifier of data, or NULL.

Since 2.4

gtk_tree_model_filter_set_visible_column ()

void                gtk_tree_model_filter_set_visible_column
                                                        (GtkTreeModelFilter *filter,
                                                         gint column);

Sets column of the child_model to be the column where filter should look for visibility information. columns should be a column of type G_TYPE_BOOLEAN, where TRUE means that a row is visible, and FALSE if not.

filter : | A GtkTreeModelFilter.
column : | A gint which is the column containing the visible information.

Since 2.4

gtk_tree_model_filter_get_model ()

GtkTreeModel*       gtk_tree_model_filter_get_model     (GtkTreeModelFilter *filter);

Returns a pointer to the child model of filter.

filter : | A GtkTreeModelFilter.
Returns : | A pointer to a GtkTreeModel.

Since 2.4

gtk_tree_model_filter_convert_child_iter_to_iter ()

gboolean            gtk_tree_model_filter_convert_child_iter_to_iter
                                                        (GtkTreeModelFilter *filter,
                                                         GtkTreeIter *filter_iter,
                                                         GtkTreeIter *child_iter);

Sets filter_iter to point to the row in filter that corresponds to the row pointed at by child_iter. If filter_iter was not set, FALSE is returned.

filter : | A GtkTreeModelFilter.
filter_iter : | An uninitialized GtkTreeIter.
child_iter : | A valid GtkTreeIter pointing to a row on the child model.
Returns : | TRUE, if filter_iter was set, i.e. if child_iter is a valid iterator pointing to a visible row in child model.

Since 2.4

gtk_tree_model_filter_convert_iter_to_child_iter ()

void                gtk_tree_model_filter_convert_iter_to_child_iter
                                                        (GtkTreeModelFilter *filter,
                                                         GtkTreeIter *child_iter,
                                                         GtkTreeIter *filter_iter);

Sets child_iter to point to the row pointed to by filter_iter.

filter : | A GtkTreeModelFilter.
child_iter : | An uninitialized GtkTreeIter.
filter_iter : | A valid GtkTreeIter pointing to a row on filter.

Since 2.4

gtk_tree_model_filter_convert_child_path_to_path ()

GtkTreePath*        gtk_tree_model_filter_convert_child_path_to_path
                                                        (GtkTreeModelFilter *filter,
                                                         GtkTreePath *child_path);

Converts child_path to a path relative to filter. That is, child_path points to a path in the child model. The rerturned path will point to the same row in the filtered model. If child_path isn't a valid path on the child model or points to a row which is not visible in filter, then NULL is returned.

filter : | A GtkTreeModelFilter.
child_path : | A GtkTreePath to convert.
Returns : | A newly allocated GtkTreePath, or NULL.

Since 2.4

gtk_tree_model_filter_convert_path_to_child_path ()

GtkTreePath*        gtk_tree_model_filter_convert_path_to_child_path
                                                        (GtkTreeModelFilter *filter,
                                                         GtkTreePath *filter_path);

Converts filter_path to a path on the child model of filter. That is, filter_path points to a location in filter. The returned path will point to the same location in the model not being filtered. If filter_path does not point to a location in the child model, NULL is returned.

filter : | A GtkTreeModelFilter.
filter_path : | A GtkTreePath to convert.
Returns : | A newly allocated GtkTreePath, or NULL.

Since 2.4

gtk_tree_model_filter_refilter ()

void                gtk_tree_model_filter_refilter      (GtkTreeModelFilter *filter);

Emits ::row_changed for each row in the child model, which causes the filter to re-evaluate whether a row is visible or not.

filter : A GtkTreeModelFilter.

Since 2.4

gtk_tree_model_filter_clear_cache ()

void                gtk_tree_model_filter_clear_cache   (GtkTreeModelFilter *filter);

This function should almost never be called. It clears the filter of any cached iterators that haven't been reffed with gtk_tree_model_ref_node(). This might be useful if the child model being filtered is static (and doesn't change often) and there has been a lot of unreffed access to nodes. As a side effect of this function, all unreffed iters will be invalid.

filter : A GtkTreeModelFilter.

Since 2.4

Property Details

The "child-model" property

  "child-model"              GtkTreeModel          : Read / Write / Construct Only

The model for the filtermodel to filter.

The "virtual-root" property

  "virtual-root"             GtkTreePath           : Read / Write / Construct Only

The virtual root (relative to the child model) for this filtermodel.

See Also

GtkTreeModelSort


GtkTreeModelSort

GtkTreeModelSort — A GtkTreeModel which makes an underlying tree model sortable

Synopsis

#include <gtk/gtk.h>

                    GtkTreeModelSort;
GtkTreeModel*       gtk_tree_model_sort_new_with_model  (GtkTreeModel *child_model);
GtkTreeModel*       gtk_tree_model_sort_get_model       (GtkTreeModelSort *tree_model);
GtkTreePath*        gtk_tree_model_sort_convert_child_path_to_path
                                                        (GtkTreeModelSort *tree_model_sort,
                                                         GtkTreePath *child_path);
void                gtk_tree_model_sort_convert_child_iter_to_iter
                                                        (GtkTreeModelSort *tree_model_sort,
                                                         GtkTreeIter *sort_iter,
                                                         GtkTreeIter *child_iter);
GtkTreePath*        gtk_tree_model_sort_convert_path_to_child_path
                                                        (GtkTreeModelSort *tree_model_sort,
                                                         GtkTreePath *sorted_path);
void                gtk_tree_model_sort_convert_iter_to_child_iter
                                                        (GtkTreeModelSort *tree_model_sort,
                                                         GtkTreeIter *child_iter,
                                                         GtkTreeIter *sorted_iter);
void                gtk_tree_model_sort_reset_default_sort_func
                                                        (GtkTreeModelSort *tree_model_sort);
void                gtk_tree_model_sort_clear_cache     (GtkTreeModelSort *tree_model_sort);
gboolean            gtk_tree_model_sort_iter_is_valid   (GtkTreeModelSort *tree_model_sort,
                                                         GtkTreeIter *iter);

Object Hierarchy

  GObject
   +----GtkTreeModelSort

Implemented Interfaces

GtkTreeModelSort implements GtkTreeModel, GtkTreeDragSource and GtkTreeSortable.

Properties

  "model"                    GtkTreeModel          : Read / Write / Construct Only

Description

The GtkTreeModelSort is a model which implements the GtkTreeSortable interface. It does not hold any data itself, but rather is created with a child model and proxies its data. It has identical column types to this child model, and the changes in the child are propagated. The primary purpose of this model is to provide a way to sort a different model without modifying it. Note that the sort function used by GtkTreeModelSort is not guaranteed to be stable.

The use of this is best demonstrated through an example. In the following sample code we create two GtkTreeView widgets each with a view of the same data. As the model is wrapped here by a GtkTreeModelSort, the two GtkTreeViews can each sort their view of the data without affecting the other. By contrast, if we simply put the same model in each widget, then sorting the first would sort the second.

Example 16. Using a GtkTreeModelSort

{
  GtkTreeView *tree_view1;
  GtkTreeView *tree_view2;
  GtkTreeModel *sort_model1;
  GtkTreeModel *sort_model2;
  GtkTreeModel *child_model;

  /* get the child model */
  child_model = get_my_model ();

  /* Create the first tree */
  sort_model1 = gtk_tree_model_sort_new_with_model (child_model);
  tree_view1 = gtk_tree_view_new_with_model (sort_model1);

  /* Create the second tree */
  sort_model2 = gtk_tree_model_sort_new_with_model (child_model);
  tree_view2 = gtk_tree_view_new_with_model (sort_model2);

  /* Now we can sort the two models independently */
  gtk_tree_sortable_set_sort_column_id (GTK_TREE_SORTABLE (sort_model1),
                                        COLUMN_1, GTK_SORT_ASCENDING);
  gtk_tree_sortable_set_sort_column_id (GTK_TREE_SORTABLE (sort_model2),
                                        COLUMN_1, GTK_SORT_DESCENDING);
}

To demonstrate how to access the underlying child model from the sort model, the next example will be a callback for the GtkTreeSelection "changed" signal. In this callback, we get a string from COLUMN_1 of the model. We then modify the string, find the same selected row on the child model, and change the row there.

Example 17. Accessing the child model of in a selection changed callback

void
selection_changed (GtkTreeSelection *selection, gpointer data)
{
  GtkTreeModel *sort_model = NULL;
  GtkTreeModel *child_model;
  GtkTreeIter sort_iter;
  GtkTreeIter child_iter;
  char *some_data = NULL;
  char *modified_data;

  /* Get the current selected row and the model. */
  if (! gtk_tree_selection_get_selected (selection,
                                         &sort_model,
                                         &sort_iter))
    return;

  /* Look up the current value on the selected row and get a new value
   * to change it to.
   */
  gtk_tree_model_get (GTK_TREE_MODEL (sort_model), &sort_iter,
                      COLUMN_1, &some_data,
                      -1);

  modified_data = change_the_data (some_data);
  g_free (some_data);

  /* Get an iterator on the child model, instead of the sort model. */
  gtk_tree_model_sort_convert_iter_to_child_iter (GTK_TREE_MODEL_SORT (sort_model),
                                                  &child_iter,
                                                  &sort_iter);

  /* Get the child model and change the value of the row.  In this
   * example, the child model is a GtkListStore.  It could be any other
   * type of model, though.
   */
  child_model = gtk_tree_model_sort_get_model (GTK_TREE_MODEL_SORT (sort_model));
  gtk_list_store_set (GTK_LIST_STORE (child_model), &child_iter,
                      COLUMN_1, &modified_data,
                      -1);
  g_free (modified_data);
}

Details

GtkTreeModelSort

typedef struct _GtkTreeModelSort GtkTreeModelSort;

This should not be accessed directly. Use the accessor functions below.

gtk_tree_model_sort_new_with_model ()

GtkTreeModel*       gtk_tree_model_sort_new_with_model  (GtkTreeModel *child_model);

Creates a new GtkTreeModel, with child_model as the child model.

child_model : | A GtkTreeModel
Returns : | A new GtkTreeModel.

gtk_tree_model_sort_get_model ()

GtkTreeModel*       gtk_tree_model_sort_get_model       (GtkTreeModelSort *tree_model);

Returns the model the GtkTreeModelSort is sorting.

tree_model : | a GtkTreeModelSort
Returns : | the "child model" being sorted

gtk_tree_model_sort_convert_child_path_to_path ()

GtkTreePath*        gtk_tree_model_sort_convert_child_path_to_path
                                                        (GtkTreeModelSort *tree_model_sort,
                                                         GtkTreePath *child_path);

Converts child_path to a path relative to tree_model_sort. That is, child_path points to a path in the child model. The returned path will point to the same row in the sorted model. If child_path isn't a valid path on the child model, then NULL is returned.

tree_model_sort : | A GtkTreeModelSort
child_path : | A GtkTreePath to convert
Returns : | A newly allocated GtkTreePath, or NULL

gtk_tree_model_sort_convert_child_iter_to_iter ()

void                gtk_tree_model_sort_convert_child_iter_to_iter
                                                        (GtkTreeModelSort *tree_model_sort,
                                                         GtkTreeIter *sort_iter,
                                                         GtkTreeIter *child_iter);

Sets sort_iter to point to the row in tree_model_sort that corresponds to the row pointed at by child_iter.

tree_model_sort : | A GtkTreeModelSort
sort_iter : | An uninitialized GtkTreeIter.
child_iter : | A valid GtkTreeIter pointing to a row on the child model

gtk_tree_model_sort_convert_path_to_child_path ()

GtkTreePath*        gtk_tree_model_sort_convert_path_to_child_path
                                                        (GtkTreeModelSort *tree_model_sort,
                                                         GtkTreePath *sorted_path);

Converts sorted_path to a path on the child model of tree_model_sort. That is, sorted_path points to a location in tree_model_sort. The returned path will point to the same location in the model not being sorted. If sorted_path does not point to a location in the child model, NULL is returned.

tree_model_sort : | A GtkTreeModelSort
sorted_path : | A GtkTreePath to convert
Returns : | A newly allocated GtkTreePath, or NULL

gtk_tree_model_sort_convert_iter_to_child_iter ()

void                gtk_tree_model_sort_convert_iter_to_child_iter
                                                        (GtkTreeModelSort *tree_model_sort,
                                                         GtkTreeIter *child_iter,
                                                         GtkTreeIter *sorted_iter);

Sets child_iter to point to the row pointed to by sorted_iter.

tree_model_sort : | A GtkTreeModelSort
child_iter : | An uninitialized GtkTreeIter
sorted_iter : | A valid GtkTreeIter pointing to a row on tree_model_sort.

gtk_tree_model_sort_reset_default_sort_func ()

void                gtk_tree_model_sort_reset_default_sort_func
                                                        (GtkTreeModelSort *tree_model_sort);

This resets the default sort function to be in the 'unsorted' state. That is, it is in the same order as the child model. It will re-sort the model to be in the same order as the child model only if the GtkTreeModelSort is in 'unsorted' state.

tree_model_sort : A GtkTreeModelSort

gtk_tree_model_sort_clear_cache ()

void                gtk_tree_model_sort_clear_cache     (GtkTreeModelSort *tree_model_sort);

This function should almost never be called. It clears the tree_model_sort of any cached iterators that haven't been reffed with gtk_tree_model_ref_node(). This might be useful if the child model being sorted is static (and doesn't change often) and there has been a lot of unreffed access to nodes. As a side effect of this function, all unreffed iters will be invalid.

tree_model_sort : A GtkTreeModelSort

gtk_tree_model_sort_iter_is_valid ()

gboolean            gtk_tree_model_sort_iter_is_valid   (GtkTreeModelSort *tree_model_sort,
                                                         GtkTreeIter *iter);

Warning

This function is slow. Only use it for debugging and/or testing purposes.

Checks if the given iter is a valid iter for this GtkTreeModelSort.

tree_model_sort : | A GtkTreeModelSort.
iter : | A GtkTreeIter.
Returns : | TRUE if the iter is valid, FALSE if the iter is invalid.

Since 2.2

Property Details

The "model" property

  "model"                    GtkTreeModel          : Read / Write / Construct Only

The model for the TreeModelSort to sort.

See Also

GtkTreeModel, GtkListStore, GtkTreeStore, GtkTreeSortable, GtkTreeModelFilter


GtkTreeSelection

GtkTreeSelection — The selection object for GtkTreeView

Synopsis

#include <gtk/gtk.h>

                    GtkTreeSelection;
gboolean            (*GtkTreeSelectionFunc)             (GtkTreeSelection *selection,
                                                         GtkTreeModel *model,
                                                         GtkTreePath *path,
                                                         gboolean path_currently_selected,
                                                         gpointer data);
void                (*GtkTreeSelectionForeachFunc)      (GtkTreeModel *model,
                                                         GtkTreePath *path,
                                                         GtkTreeIter *iter,
                                                         gpointer data);
void                gtk_tree_selection_set_mode         (GtkTreeSelection *selection,
                                                         GtkSelectionMode type);
GtkSelectionMode    gtk_tree_selection_get_mode         (GtkTreeSelection *selection);
void                gtk_tree_selection_set_select_function
                                                        (GtkTreeSelection *selection,
                                                         GtkTreeSelectionFunc func,
                                                         gpointer data,
                                                         GtkDestroyNotify destroy);
gpointer            gtk_tree_selection_get_user_data    (GtkTreeSelection *selection);
GtkTreeView*        gtk_tree_selection_get_tree_view    (GtkTreeSelection *selection);
gboolean            gtk_tree_selection_get_selected     (GtkTreeSelection *selection,
                                                         GtkTreeModel **model,
                                                         GtkTreeIter *iter);
void                gtk_tree_selection_selected_foreach (GtkTreeSelection *selection,
                                                         GtkTreeSelectionForeachFunc func,
                                                         gpointer data);
GList*              gtk_tree_selection_get_selected_rows
                                                        (GtkTreeSelection *selection,
                                                         GtkTreeModel **model);
gint                gtk_tree_selection_count_selected_rows
                                                        (GtkTreeSelection *selection);
void                gtk_tree_selection_select_path      (GtkTreeSelection *selection,
                                                         GtkTreePath *path);
void                gtk_tree_selection_unselect_path    (GtkTreeSelection *selection,
                                                         GtkTreePath *path);
gboolean            gtk_tree_selection_path_is_selected (GtkTreeSelection *selection,
                                                         GtkTreePath *path);
void                gtk_tree_selection_select_iter      (GtkTreeSelection *selection,
                                                         GtkTreeIter *iter);
void                gtk_tree_selection_unselect_iter    (GtkTreeSelection *selection,
                                                         GtkTreeIter *iter);
gboolean            gtk_tree_selection_iter_is_selected (GtkTreeSelection *selection,
                                                         GtkTreeIter *iter);
void                gtk_tree_selection_select_all       (GtkTreeSelection *selection);
void                gtk_tree_selection_unselect_all     (GtkTreeSelection *selection);
void                gtk_tree_selection_select_range     (GtkTreeSelection *selection,
                                                         GtkTreePath *start_path,
                                                         GtkTreePath *end_path);
void                gtk_tree_selection_unselect_range   (GtkTreeSelection *selection,
                                                         GtkTreePath *start_path,
                                                         GtkTreePath *end_path);

Object Hierarchy

  GObject
   +----GtkTreeSelection

Signals

  "changed"                                        : Run First

Description

The GtkTreeSelection object is a helper object to manage the selection for a GtkTreeView widget. The GtkTreeSelection object is automatically created when a new GtkTreeView widget is created, and cannot exist independentally of this widget. The primary reason the GtkTreeSelection objects exists is for cleanliness of code and API. That is, there is no conceptual reason all these functions could not be methods on the GtkTreeView widget instead of a separate function.

The GtkTreeSelection object is gotten from a GtkTreeView by calling gtk_tree_view_get_selection(). It can be manipulated to check the selection status of the tree, as well as select and deselect individual rows. Selection is done completely view side. As a result, multiple views of the same model can have completely different selections. Additionally, you cannot change the selection of a row on the model that is not currently displayed by the view without expanding its parents first.

One of the important things to remember when monitoring the selection of a view is that the "changed" signal is mostly a hint. That is, it may only emit one signal when a range of rows is selected. Additionally, it may on occasion emit a "changed" signal when nothing has happened (mostly as a result of programmers calling select_row on an already selected row).

Details

GtkTreeSelection

typedef struct _GtkTreeSelection GtkTreeSelection;

GtkTreeSelectionFunc ()

gboolean            (*GtkTreeSelectionFunc)             (GtkTreeSelection *selection,
                                                         GtkTreeModel *model,
                                                         GtkTreePath *path,
                                                         gboolean path_currently_selected,
                                                         gpointer data);

A function used by gtk_tree_selection_set_select_function() to filter whether or not a row may be selected. It is called whenever a row's state might change. A return value of TRUE indicates to selection that it is okay to change the selection.

selection : | A GtkTreeSelection
model : | A GtkTreeModel being viewed
path : | The GtkTreePath of the row in question
path_currently_selected : | TRUE, if the path is currently selected
data : | user data
Returns : | TRUE, if the selection state of the row can be toggled

GtkTreeSelectionForeachFunc ()

void                (*GtkTreeSelectionForeachFunc)      (GtkTreeModel *model,
                                                         GtkTreePath *path,
                                                         GtkTreeIter *iter,
                                                         gpointer data);

A function used by gtk_tree_selection_selected_foreach() to map all selected rows. It will be called on every selected row in the view.

model : | The GtkTreeModel being viewed
path : | The GtkTreePath of a selected row
iter : | A GtkTreeIter pointing to a selected row
data : | user data

gtk_tree_selection_set_mode ()

void                gtk_tree_selection_set_mode         (GtkTreeSelection *selection,
                                                         GtkSelectionMode type);

Sets the selection mode of the selection. If the previous type was GTK_SELECTION_MULTIPLE, then the anchor is kept selected, if it was previously selected.

selection : | A GtkTreeSelection.
type : | The selection mode

gtk_tree_selection_get_mode ()

GtkSelectionMode    gtk_tree_selection_get_mode         (GtkTreeSelection *selection);

Gets the selection mode for selection. See gtk_tree_selection_set_mode().

selection : | a GtkTreeSelection
Returns : | the current selection mode

gtk_tree_selection_set_select_function ()

void                gtk_tree_selection_set_select_function
                                                        (GtkTreeSelection *selection,
                                                         GtkTreeSelectionFunc func,
                                                         gpointer data,
                                                         GtkDestroyNotify destroy);

Sets the selection function. If set, this function is called before any node is selected or unselected, giving some control over which nodes are selected. The select function should return TRUE if the state of the node may be toggled, and FALSE if the state of the node should be left unchanged.

selection : | A GtkTreeSelection.
func : | The selection function.
data : | The selection function's data.
destroy : | The destroy function for user data. May be NULL.

gtk_tree_selection_get_user_data ()

gpointer            gtk_tree_selection_get_user_data    (GtkTreeSelection *selection);

Returns the user data for the selection function.

selection : | A GtkTreeSelection.
Returns : | The user data.

gtk_tree_selection_get_tree_view ()

GtkTreeView*        gtk_tree_selection_get_tree_view    (GtkTreeSelection *selection);

Returns the tree view associated with selection.

selection : | A GtkTreeSelection
Returns : | A GtkTreeView

gtk_tree_selection_get_selected ()

gboolean            gtk_tree_selection_get_selected     (GtkTreeSelection *selection,
                                                         GtkTreeModel **model,
                                                         GtkTreeIter *iter);

Sets iter to the currently selected node if selection is set to GTK_SELECTION_SINGLE or GTK_SELECTION_BROWSE. iter may be NULL if you just want to test if selection has any selected nodes. model is filled with the current model as a convenience. This function will not work if you use selection is GTK_SELECTION_MULTIPLE.

selection : | A GtkTreeSelection.
model : | A pointer to set to the GtkTreeModel, or NULL.
iter : | The GtkTreeIter, or NULL.
Returns : | TRUE, if there is a selected node.

gtk_tree_selection_selected_foreach ()

void                gtk_tree_selection_selected_foreach (GtkTreeSelection *selection,
                                                         GtkTreeSelectionForeachFunc func,
                                                         gpointer data);

Calls a function for each selected node. Note that you cannot modify the tree or selection from within this function. As a result, gtk_tree_selection_get_selected_rows() might be more useful.

selection : | A GtkTreeSelection.
func : | The function to call for each selected node.
data : | user data to pass to the function.

gtk_tree_selection_get_selected_rows ()

GList*              gtk_tree_selection_get_selected_rows
                                                        (GtkTreeSelection *selection,
                                                         GtkTreeModel **model);

Creates a list of path of all selected rows. Additionally, if you are planning on modifying the model after calling this function, you may want to convert the returned list into a list of GtkTreeRowReferences. To do this, you can use gtk_tree_row_reference_new().

To free the return value, use:

g_list_foreach (list, gtk_tree_path_free, NULL);
g_list_free (list);

selection : | A GtkTreeSelection.
model : | A pointer to set to the GtkTreeModel, or NULL.
Returns : | A GList containing a GtkTreePath for each selected row.

Since 2.2

gtk_tree_selection_count_selected_rows ()

gint                gtk_tree_selection_count_selected_rows
                                                        (GtkTreeSelection *selection);

Returns the number of rows that have been selected in tree.

selection : | A GtkTreeSelection.
Returns : | The number of rows selected.

Since 2.2

gtk_tree_selection_select_path ()

void                gtk_tree_selection_select_path      (GtkTreeSelection *selection,
                                                         GtkTreePath *path);

Select the row at path.

selection : | A GtkTreeSelection.
path : | The GtkTreePath to be selected.

gtk_tree_selection_unselect_path ()

void                gtk_tree_selection_unselect_path    (GtkTreeSelection *selection,
                                                         GtkTreePath *path);

Unselects the row at path.

selection : | A GtkTreeSelection.
path : | The GtkTreePath to be unselected.

gtk_tree_selection_path_is_selected ()

gboolean            gtk_tree_selection_path_is_selected (GtkTreeSelection *selection,
                                                         GtkTreePath *path);

Returns TRUE if the row pointed to by path is currently selected. If path does not point to a valid location, FALSE is returned

selection : | A GtkTreeSelection.
path : | A GtkTreePath to check selection on.
Returns : | TRUE if path is selected.

gtk_tree_selection_select_iter ()

void                gtk_tree_selection_select_iter      (GtkTreeSelection *selection,
                                                         GtkTreeIter *iter);

Selects the specified iterator.

selection : | A GtkTreeSelection.
iter : | The GtkTreeIter to be selected.

gtk_tree_selection_unselect_iter ()

void                gtk_tree_selection_unselect_iter    (GtkTreeSelection *selection,
                                                         GtkTreeIter *iter);

Unselects the specified iterator.

selection : | A GtkTreeSelection.
iter : | The GtkTreeIter to be unselected.

gtk_tree_selection_iter_is_selected ()

gboolean            gtk_tree_selection_iter_is_selected (GtkTreeSelection *selection,
                                                         GtkTreeIter *iter);

Returns TRUE if the row at iter is currently selected.

selection : | A GtkTreeSelection
iter : | A valid GtkTreeIter
Returns : | TRUE, if iter is selected

gtk_tree_selection_select_all ()

void                gtk_tree_selection_select_all       (GtkTreeSelection *selection);

Selects all the nodes. selection must be set to GTK_SELECTION_MULTIPLE mode.

selection : A GtkTreeSelection.

gtk_tree_selection_unselect_all ()

void                gtk_tree_selection_unselect_all     (GtkTreeSelection *selection);

Unselects all the nodes.

selection : A GtkTreeSelection.

gtk_tree_selection_select_range ()

void                gtk_tree_selection_select_range     (GtkTreeSelection *selection,
                                                         GtkTreePath *start_path,
                                                         GtkTreePath *end_path);

Selects a range of nodes, determined by start_path and end_path inclusive. selection must be set to GTK_SELECTION_MULTIPLE mode.

selection : | A GtkTreeSelection.
start_path : | The initial node of the range.
end_path : | The final node of the range.

gtk_tree_selection_unselect_range ()

void                gtk_tree_selection_unselect_range   (GtkTreeSelection *selection,
                                                         GtkTreePath *start_path,
                                                         GtkTreePath *end_path);

Unselects a range of nodes, determined by start_path and end_path inclusive.

selection : | A GtkTreeSelection.
start_path : | The initial node of the range.
end_path : | The initial node of the range.

Since 2.2

Signal Details

The "changed" signal

void                user_function                      (GtkTreeSelection *treeselection,
                                                        gpointer          user_data)          : Run First

Emitted whenever the selection has (possibly) changed. Please note that this signal is mostly a hint. It may only be emitted once when a range of rows are selected, and it may occasionally be emitted when nothing has happened.

treeselection : | the object which received the signal.
user_data : | user data set when the signal handler was connected.

See Also

GtkTreeView, GtkTreeViewColumn, GtkTreeDnd, GtkTreeMode, GtkTreeSortable, GtkTreeModelSort, GtkListStore, GtkTreeStore, GtkCellRenderer, GtkCellEditable, GtkCellRendererPixbuf, GtkCellRendererText, GtkCellRendererToggle


GtkTreeSortable

GtkTreeSortable — The interface for sortable models used by GtkTreeView

Synopsis

#include <gtk/gtk.h>

                    GtkTreeSortable;
                    GtkTreeSortableIface;
gint                (*GtkTreeIterCompareFunc)           (GtkTreeModel *model,
                                                         GtkTreeIter *a,
                                                         GtkTreeIter *b,
                                                         gpointer user_data);
void                gtk_tree_sortable_sort_column_changed
                                                        (GtkTreeSortable *sortable);
gboolean            gtk_tree_sortable_get_sort_column_id
                                                        (GtkTreeSortable *sortable,
                                                         gint *sort_column_id,
                                                         GtkSortType *order);
void                gtk_tree_sortable_set_sort_column_id
                                                        (GtkTreeSortable *sortable,
                                                         gint sort_column_id,
                                                         GtkSortType order);
void                gtk_tree_sortable_set_sort_func     (GtkTreeSortable *sortable,
                                                         gint sort_column_id,
                                                         GtkTreeIterCompareFunc sort_func,
                                                         gpointer user_data,
                                                         GtkDestroyNotify destroy);
void                gtk_tree_sortable_set_default_sort_func
                                                        (GtkTreeSortable *sortable,
                                                         GtkTreeIterCompareFunc sort_func,
                                                         gpointer user_data,
                                                         GtkDestroyNotify destroy);
gboolean            gtk_tree_sortable_has_default_sort_func
                                                        (GtkTreeSortable *sortable);

Object Hierarchy

  GInterface
   +----GtkTreeSortable

Prerequisites

GtkTreeSortable requires GtkTreeModel and GObject.

Known Implementations

GtkTreeSortable is implemented by GtkTreeModelSort, GtkTreeStore and GtkListStore.

Signals

  "sort-column-changed"                            : Run Last

Description

GtkTreeSortable is an interface to be implemented by tree models which support sorting. The GtkTreeView uses the methods provided by this interface to sort the model.

Details

GtkTreeSortable

typedef struct _GtkTreeSortable GtkTreeSortable;

GtkTreeSortableIface

typedef struct {
  GTypeInterface g_iface;

  /* signals */
  void     (* sort_column_changed)   (GtkTreeSortable        *sortable);

  /* virtual table */
  gboolean (* get_sort_column_id)    (GtkTreeSortable        *sortable,
                      gint                   *sort_column_id,
                      GtkSortType            *order);
  void     (* set_sort_column_id)    (GtkTreeSortable        *sortable,
                      gint                    sort_column_id,
                      GtkSortType             order);
  void     (* set_sort_func)         (GtkTreeSortable        *sortable,
                      gint                    sort_column_id,
                      GtkTreeIterCompareFunc  func,
                      gpointer                data,
                      GtkDestroyNotify        destroy);
  void     (* set_default_sort_func) (GtkTreeSortable        *sortable,
                      GtkTreeIterCompareFunc  func,
                      gpointer                data,
                      GtkDestroyNotify        destroy);
  gboolean (* has_default_sort_func) (GtkTreeSortable        *sortable);
} GtkTreeSortableIface;

GtkTreeIterCompareFunc ()

gint                (*GtkTreeIterCompareFunc)           (GtkTreeModel *model,
                                                         GtkTreeIter *a,
                                                         GtkTreeIter *b,
                                                         gpointer user_data);

A GtkTreeIterCompareFunc should return a negative integer, zero, or a positive integer if a sorts before b, a sorts with b, or a sorts after b respectively. If two iters compare as equal, their order in the sorted model is undefined. In order to ensure that the GtkTreeSortable behaves as expected, the GtkTreeIterCompareFunc must define a partial order on the model, i.e. it must be reflexive, antisymmetric and transitive.

For example, if model is a product catalogue, then a compare function for the "price" column could be one which returns price_of(a) - price_of(b).

model : | The GtkTreeModel the comparison is within
a : | A GtkTreeIter in model
b : | Another GtkTreeIter in model
user_data : | Data passed when the compare func is assigned e.g. by gtk_tree_sortable_set_sort_func()
Returns : |

gtk_tree_sortable_sort_column_changed ()

void                gtk_tree_sortable_sort_column_changed
                                                        (GtkTreeSortable *sortable);

Emits a GtkTreeSortable::sort_column_changed signal on

sortable : A GtkTreeSortable

gtk_tree_sortable_get_sort_column_id ()

gboolean            gtk_tree_sortable_get_sort_column_id
                                                        (GtkTreeSortable *sortable,
                                                         gint *sort_column_id,
                                                         GtkSortType *order);

Fills in sort_column_id and order with the current sort column and the order. It returns TRUE unless the sort_column_id is GTK_TREE_SORTABLE_DEFAULT_SORT_COLUMN_ID or GTK_TREE_SORTABLE_UNSORTED_SORT_COLUMN_ID.

sortable : | A GtkTreeSortable
sort_column_id : | The sort column id to be filled in
order : | The GtkSortType to be filled in
Returns : | TRUE if the sort column is not one of the special sort column ids.

gtk_tree_sortable_set_sort_column_id ()

void                gtk_tree_sortable_set_sort_column_id
                                                        (GtkTreeSortable *sortable,
                                                         gint sort_column_id,
                                                         GtkSortType order);

Sets the current sort column to be sort_column_id. The sortable will resort itself to reflect this change, after emitting a GtkTreeSortable::sort_column_changed signal. If sort_column_id is GTK_TREE_SORTABLE_DEFAULT_SORT_COLUMN_ID, then the default sort function will be used, if it is set.

sortable : | A GtkTreeSortable
sort_column_id : | the sort column id to set
order : | The sort order of the column

gtk_tree_sortable_set_sort_func ()

void                gtk_tree_sortable_set_sort_func     (GtkTreeSortable *sortable,
                                                         gint sort_column_id,
                                                         GtkTreeIterCompareFunc sort_func,
                                                         gpointer user_data,
                                                         GtkDestroyNotify destroy);

Sets the comparison function used when sorting to be sort_func. If the current sort column id of sortable is the same as sort_column_id, then the model will sort using this function.

sortable : | A GtkTreeSortable
sort_column_id : | the sort column id to set the function for
sort_func : | The comparison function
user_data : | User data to pass to sort_func, or NULL
destroy : | Destroy notifier of user_data, or NULL

gtk_tree_sortable_set_default_sort_func ()

void                gtk_tree_sortable_set_default_sort_func
                                                        (GtkTreeSortable *sortable,
                                                         GtkTreeIterCompareFunc sort_func,
                                                         gpointer user_data,
                                                         GtkDestroyNotify destroy);

Sets the default comparison function used when sorting to be sort_func. If the current sort column id of sortable is GTK_TREE_SORTABLE_DEFAULT_SORT_COLUMN_ID, then the model will sort using this function.

If sort_func is NULL, then there will be no default comparison function. This means that once the model has been sorted, it can't go back to the default state. In this case, when the current sort column id of sortable is GTK_TREE_SORTABLE_DEFAULT_SORT_COLUMN_ID, the model will be unsorted.

sortable : | A GtkTreeSortable
sort_func : | The comparison function
user_data : | User data to pass to sort_func, or NULL
destroy : | Destroy notifier of user_data, or NULL

gtk_tree_sortable_has_default_sort_func ()

gboolean            gtk_tree_sortable_has_default_sort_func
                                                        (GtkTreeSortable *sortable);

Returns TRUE if the model has a default sort function. This is used primarily by GtkTreeViewColumns in order to determine if a model can go back to the default state, or not.

sortable : | A GtkTreeSortable
Returns : | TRUE, if the model has a default sort function

Signal Details

The "sort-column-changed" signal

void                user_function                      (GtkTreeSortable *treesortable,
                                                        gpointer         user_data)         : Run Last

treesortable : | the object which received the signal.
user_data : | user data set when the signal handler was connected.

See Also

GtkTreeModel, GtkTreeView


GtkTreeStore

GtkTreeStore — A tree-like data structure that can be used with the GtkTreeView

Synopsis

#include <gtk/gtk.h>

                    GtkTreeStore;
GtkTreeStore*       gtk_tree_store_new                  (gint n_columns,
                                                         ...);
GtkTreeStore*       gtk_tree_store_newv                 (gint n_columns,
                                                         GType *types);
void                gtk_tree_store_set_column_types     (GtkTreeStore *tree_store,
                                                         gint n_columns,
                                                         GType *types);
void                gtk_tree_store_set_value            (GtkTreeStore *tree_store,
                                                         GtkTreeIter *iter,
                                                         gint column,
                                                         GValue *value);
void                gtk_tree_store_set                  (GtkTreeStore *tree_store,
                                                         GtkTreeIter *iter,
                                                         ...);
void                gtk_tree_store_set_valist           (GtkTreeStore *tree_store,
                                                         GtkTreeIter *iter,
                                                         va_list var_args);
gboolean            gtk_tree_store_remove               (GtkTreeStore *tree_store,
                                                         GtkTreeIter *iter);
void                gtk_tree_store_insert               (GtkTreeStore *tree_store,
                                                         GtkTreeIter *iter,
                                                         GtkTreeIter *parent,
                                                         gint position);
void                gtk_tree_store_insert_before        (GtkTreeStore *tree_store,
                                                         GtkTreeIter *iter,
                                                         GtkTreeIter *parent,
                                                         GtkTreeIter *sibling);
void                gtk_tree_store_insert_after         (GtkTreeStore *tree_store,
                                                         GtkTreeIter *iter,
                                                         GtkTreeIter *parent,
                                                         GtkTreeIter *sibling);
void                gtk_tree_store_insert_with_values   (GtkTreeStore *tree_store,
                                                         GtkTreeIter *iter,
                                                         GtkTreeIter *parent,
                                                         gint position,
                                                         ...);
void                gtk_tree_store_insert_with_valuesv  (GtkTreeStore *tree_store,
                                                         GtkTreeIter *iter,
                                                         GtkTreeIter *parent,
                                                         gint position,
                                                         gint *columns,
                                                         GValue *values,
                                                         gint n_values);
void                gtk_tree_store_prepend              (GtkTreeStore *tree_store,
                                                         GtkTreeIter *iter,
                                                         GtkTreeIter *parent);
void                gtk_tree_store_append               (GtkTreeStore *tree_store,
                                                         GtkTreeIter *iter,
                                                         GtkTreeIter *parent);
gboolean            gtk_tree_store_is_ancestor          (GtkTreeStore *tree_store,
                                                         GtkTreeIter *iter,
                                                         GtkTreeIter *descendant);
gint                gtk_tree_store_iter_depth           (GtkTreeStore *tree_store,
                                                         GtkTreeIter *iter);
void                gtk_tree_store_clear                (GtkTreeStore *tree_store);
gboolean            gtk_tree_store_iter_is_valid        (GtkTreeStore *tree_store,
                                                         GtkTreeIter *iter);
void                gtk_tree_store_reorder              (GtkTreeStore *tree_store,
                                                         GtkTreeIter *parent,
                                                         gint *new_order);
void                gtk_tree_store_swap                 (GtkTreeStore *tree_store,
                                                         GtkTreeIter *a,
                                                         GtkTreeIter *b);
void                gtk_tree_store_move_before          (GtkTreeStore *tree_store,
                                                         GtkTreeIter *iter,
                                                         GtkTreeIter *position);
void                gtk_tree_store_move_after           (GtkTreeStore *tree_store,
                                                         GtkTreeIter *iter,
                                                         GtkTreeIter *position);

Object Hierarchy

  GObject
   +----GtkTreeStore

Implemented Interfaces

GtkTreeStore implements GtkTreeModel, GtkTreeDragSource, GtkTreeDragDest and GtkTreeSortable.

Description

The GtkTreeStore object is a list model for use with a GtkTreeView widget. It implements the GtkTreeModel interface, and consequentialy, can use all of the methods available there. It also implements the GtkTreeSortable interface so it can be sorted by the view. Finally, it also implements the tree drag and drop interfaces.

Details

GtkTreeStore

typedef struct _GtkTreeStore GtkTreeStore;

gtk_tree_store_new ()

GtkTreeStore*       gtk_tree_store_new                  (gint n_columns,
                                                         ...);

Creates a new tree store as with n_columns columns each of the types passed in. Note that only types derived from standard GObject fundamental types are supported.

As an example, gtk_tree_store_new (3, G_TYPE_INT, G_TYPE_STRING, GDK_TYPE_PIXBUF); will create a new GtkTreeStore with three columns, of type int, string and GdkPixbuf respectively.

n_columns : | number of columns in the tree store
... : | all GType types for the columns, from first to last
Returns : | a new GtkTreeStore

gtk_tree_store_newv ()

GtkTreeStore*       gtk_tree_store_newv                 (gint n_columns,
                                                         GType *types);

Non vararg creation function. Used primarily by language bindings.

n_columns : | number of columns in the tree store
types : | an array of GType types for the columns, from first to last
Returns : | a new GtkTreeStore

gtk_tree_store_set_column_types ()

void                gtk_tree_store_set_column_types     (GtkTreeStore *tree_store,
                                                         gint n_columns,
                                                         GType *types);

This function is meant primarily for GObjects that inherit from GtkTreeStore, and should only be used when constructing a new GtkTreeStore. It will not function after a row has been added, or a method on the GtkTreeModel interface is called.

tree_store : | A GtkTreeStore
n_columns : | Number of columns for the tree store
types : | An array of GType types, one for each column

gtk_tree_store_set_value ()

void                gtk_tree_store_set_value            (GtkTreeStore *tree_store,
                                                         GtkTreeIter *iter,
                                                         gint column,
                                                         GValue *value);

Sets the data in the cell specified by iter and column. The type of value must be convertible to the type of the column.

tree_store : | a GtkTreeStore
iter : | A valid GtkTreeIter for the row being modified
column : | column number to modify
value : | new value for the cell

gtk_tree_store_set ()

void                gtk_tree_store_set                  (GtkTreeStore *tree_store,
                                                         GtkTreeIter *iter,
                                                         ...);

Sets the value of one or more cells in the row referenced by iter. The variable argument list should contain integer column numbers, each column number followed by the value to be set. The list is terminated by a -1. For example, to set column 0 with type G_TYPE_STRING to "Foo", you would write gtk_tree_store_set (store, iter, 0, "Foo", -1).

tree_store : | A GtkTreeStore
iter : | A valid GtkTreeIter for the row being modified
... : | pairs of column number and value, terminated with -1

gtk_tree_store_set_valist ()

void                gtk_tree_store_set_valist           (GtkTreeStore *tree_store,
                                                         GtkTreeIter *iter,
                                                         va_list var_args);

See gtk_tree_store_set(); this version takes a va_list for use by language bindings.

tree_store : | A GtkTreeStore
iter : | A valid GtkTreeIter for the row being modified
var_args : | va_list of column/value pairs

gtk_tree_store_remove ()

gboolean            gtk_tree_store_remove               (GtkTreeStore *tree_store,
                                                         GtkTreeIter *iter);

Removes iter from tree_store. After being removed, iter is set to the next valid row at that level, or invalidated if it previously pointed to the last one.

tree_store : | A GtkTreeStore
iter : | A valid GtkTreeIter
Returns : | TRUE if iter is still valid, FALSE if not.

gtk_tree_store_insert ()

void                gtk_tree_store_insert               (GtkTreeStore *tree_store,
                                                         GtkTreeIter *iter,
                                                         GtkTreeIter *parent,
                                                         gint position);

Creates a new row at position. If parent is non-NULL, then the row will be made a child of parent. Otherwise, the row will be created at the toplevel. If position is larger than the number of rows at that level, then the new row will be inserted to the end of the list. iter will be changed to point to this new row. The row will be empty after this function is called. To fill in values, you need to call gtk_tree_store_set() or gtk_tree_store_set_value().

tree_store : | A GtkTreeStore
iter : | An unset GtkTreeIter to set to the new row
parent : | A valid GtkTreeIter, or NULL
position : | position to insert the new row

gtk_tree_store_insert_before ()

void                gtk_tree_store_insert_before        (GtkTreeStore *tree_store,
                                                         GtkTreeIter *iter,
                                                         GtkTreeIter *parent,
                                                         GtkTreeIter *sibling);

Inserts a new row before sibling. If sibling is NULL, then the row will be appended to parent 's children. If parent and sibling are NULL, then the row will be appended to the toplevel. If both sibling and parent are set, then parent must be the parent of sibling. When sibling is set, parent is optional.

iter will be changed to point to this new row. The row will be empty after this function is called. To fill in values, you need to call gtk_tree_store_set() or gtk_tree_store_set_value().

tree_store : | A GtkTreeStore
iter : | An unset GtkTreeIter to set to the new row
parent : | A valid GtkTreeIter, or NULL
sibling : | A valid GtkTreeIter, or NULL

gtk_tree_store_insert_after ()

void                gtk_tree_store_insert_after         (GtkTreeStore *tree_store,
                                                         GtkTreeIter *iter,
                                                         GtkTreeIter *parent,
                                                         GtkTreeIter *sibling);

Inserts a new row after sibling. If sibling is NULL, then the row will be prepended to parent 's children. If parent and sibling are NULL, then the row will be prepended to the toplevel. If both sibling and parent are set, then parent must be the parent of sibling. When sibling is set, parent is optional.

iter will be changed to point to this new row. The row will be empty after this function is called. To fill in values, you need to call gtk_tree_store_set() or gtk_tree_store_set_value().

tree_store : | A GtkTreeStore
iter : | An unset GtkTreeIter to set to the new row
parent : | A valid GtkTreeIter, or NULL
sibling : | A valid GtkTreeIter, or NULL

gtk_tree_store_insert_with_values ()

void                gtk_tree_store_insert_with_values   (GtkTreeStore *tree_store,
                                                         GtkTreeIter *iter,
                                                         GtkTreeIter *parent,
                                                         gint position,
                                                         ...);

Creates a new row at position. iter will be changed to point to this new row. If position is larger than the number of rows on the list, then the new row will be appended to the list. The row will be filled with the values given to this function.

Calling gtk_tree_store_insert_with_values (tree_store, iter, position, ...) has the same effect as calling

gtk_tree_store_insert (tree_store, iter, position);
gtk_tree_store_set (tree_store, iter, ...);

with the different that the former will only emit a row_inserted signal, while the latter will emit row_inserted, row_changed and if the tree store is sorted, rows_reordered. Since emitting the rows_reordered signal repeatedly can affect the performance of the program, gtk_tree_store_insert_with_values() should generally be preferred when inserting rows in a sorted tree store.

tree_store : | A GtkTreeStore
iter : | An unset GtkTreeIter to set the new row, or NULL.
parent : | A valid GtkTreeIter, or NULL
position : | position to insert the new row
... : | pairs of column number and value, terminated with -1

Since 2.10

gtk_tree_store_insert_with_valuesv ()

void                gtk_tree_store_insert_with_valuesv  (GtkTreeStore *tree_store,
                                                         GtkTreeIter *iter,
                                                         GtkTreeIter *parent,
                                                         gint position,
                                                         gint *columns,
                                                         GValue *values,
                                                         gint n_values);

A variant of gtk_tree_store_insert_with_values() which takes the columns and values as two arrays, instead of varargs. This function is mainly intended for language bindings.

tree_store : | A GtkTreeStore
iter : | An unset GtkTreeIter to set the new row, or NULL.
parent : | A valid GtkTreeIter, or NULL
position : | position to insert the new row
columns : | an array of column numbers
values : | an array of GValues
n_values : | the length of the columns and values arrays

Since 2.10

gtk_tree_store_prepend ()

void                gtk_tree_store_prepend              (GtkTreeStore *tree_store,
                                                         GtkTreeIter *iter,
                                                         GtkTreeIter *parent);

Prepends a new row to tree_store. If parent is non-NULL, then it will prepend the new row before the first child of parent, otherwise it will prepend a row to the top level. iter will be changed to point to this new row. The row will be empty after this function is called. To fill in values, you need to call gtk_tree_store_set() or gtk_tree_store_set_value().

tree_store : | A GtkTreeStore
iter : | An unset GtkTreeIter to set to the prepended row
parent : | A valid GtkTreeIter, or NULL

gtk_tree_store_append ()

void                gtk_tree_store_append               (GtkTreeStore *tree_store,
                                                         GtkTreeIter *iter,
                                                         GtkTreeIter *parent);

Appends a new row to tree_store. If parent is non-NULL, then it will append the new row after the last child of parent, otherwise it will append a row to the top level. iter will be changed to point to this new row. The row will be empty after this function is called. To fill in values, you need to call gtk_tree_store_set() or gtk_tree_store_set_value().

tree_store : | A GtkTreeStore
iter : | An unset GtkTreeIter to set to the appended row
parent : | A valid GtkTreeIter, or NULL

gtk_tree_store_is_ancestor ()

gboolean            gtk_tree_store_is_ancestor          (GtkTreeStore *tree_store,
                                                         GtkTreeIter *iter,
                                                         GtkTreeIter *descendant);

Returns TRUE if iter is an ancestor of descendant. That is, iter is the parent (or grandparent or great-grandparent) of descendant.

tree_store : | A GtkTreeStore
iter : | A valid GtkTreeIter
descendant : | A valid GtkTreeIter
Returns : | TRUE, if iter is an ancestor of descendant

gtk_tree_store_iter_depth ()

gint                gtk_tree_store_iter_depth           (GtkTreeStore *tree_store,
                                                         GtkTreeIter *iter);

Returns the depth of iter. This will be 0 for anything on the root level, 1 for anything down a level, etc.

tree_store : | A GtkTreeStore
iter : | A valid GtkTreeIter
Returns : | The depth of iter

gtk_tree_store_clear ()

void                gtk_tree_store_clear                (GtkTreeStore *tree_store);

Removes all rows from tree_store

tree_store : a GtkTreeStore

gtk_tree_store_iter_is_valid ()

gboolean            gtk_tree_store_iter_is_valid        (GtkTreeStore *tree_store,
                                                         GtkTreeIter *iter);

WARNING: This function is slow. Only use it for debugging and/or testing purposes.

Checks if the given iter is a valid iter for this GtkTreeStore.

tree_store : | A GtkTreeStore.
iter : | A GtkTreeIter.
Returns : | TRUE if the iter is valid, FALSE if the iter is invalid.

Since 2.2

gtk_tree_store_reorder ()

void                gtk_tree_store_reorder              (GtkTreeStore *tree_store,
                                                         GtkTreeIter *parent,
                                                         gint *new_order);

Reorders the children of parent in tree_store to follow the order indicated by new_order. Note that this function only works with unsorted stores.

tree_store : | A GtkTreeStore.
parent : | A GtkTreeIter.
new_order : | an array of integers mapping the new position of each child to its old position before the re-ordering, i.e. new_order[newpos] = oldpos.

Since 2.2

gtk_tree_store_swap ()

void                gtk_tree_store_swap                 (GtkTreeStore *tree_store,
                                                         GtkTreeIter *a,
                                                         GtkTreeIter *b);

Swaps a and b in the same level of tree_store. Note that this function only works with unsorted stores.

tree_store : | A GtkTreeStore.
a : | A GtkTreeIter.
b : | Another GtkTreeIter.

Since 2.2

gtk_tree_store_move_before ()

void                gtk_tree_store_move_before          (GtkTreeStore *tree_store,
                                                         GtkTreeIter *iter,
                                                         GtkTreeIter *position);

Moves iter in tree_store to the position before position. iter and position should be in the same level. Note that this function only works with unsorted stores. If position is NULL, iter will be moved to the end of the level.

tree_store : | A GtkTreeStore.
iter : | A GtkTreeIter.
position : | A GtkTreeIter or NULL.

Since 2.2

gtk_tree_store_move_after ()

void                gtk_tree_store_move_after           (GtkTreeStore *tree_store,
                                                         GtkTreeIter *iter,
                                                         GtkTreeIter *position);

Moves iter in tree_store to the position after position. iter and position should be in the same level. Note that this function only works with unsorted stores. If position is NULL, iter will be moved to the start of the level.

tree_store : | A GtkTreeStore.
iter : | A GtkTreeIter.
position : | A GtkTreeIter.

Since 2.2

See Also

GtkTreeModel, GtkTreeStore


GtkTreeView

GtkTreeView — A widget for displaying both trees and lists

Synopsis

#include <gtk/gtk.h>

                    GtkTreeView;
enum                GtkTreeViewDropPosition;
                    GtkTreeViewPrivate;
gboolean            (*GtkTreeViewColumnDropFunc)        (GtkTreeView *tree_view,
                                                         GtkTreeViewColumn *column,
                                                         GtkTreeViewColumn *prev_column,
                                                         GtkTreeViewColumn *next_column,
                                                         gpointer data);
void                (*GtkTreeViewMappingFunc)           (GtkTreeView *tree_view,
                                                         GtkTreePath *path,
                                                         gpointer user_data);
gboolean            (*GtkTreeViewSearchEqualFunc)       (GtkTreeModel *model,
                                                         gint column,
                                                         const gchar *key,
                                                         GtkTreeIter *iter,
                                                         gpointer search_data);
GtkWidget*          gtk_tree_view_new                   (void);
GtkWidget*          gtk_tree_view_new_with_model        (GtkTreeModel *model);
GtkTreeModel*       gtk_tree_view_get_model             (GtkTreeView *tree_view);
void                gtk_tree_view_set_model             (GtkTreeView *tree_view,
                                                         GtkTreeModel *model);
GtkTreeSelection*   gtk_tree_view_get_selection         (GtkTreeView *tree_view);
GtkAdjustment*      gtk_tree_view_get_hadjustment       (GtkTreeView *tree_view);
void                gtk_tree_view_set_hadjustment       (GtkTreeView *tree_view,
                                                         GtkAdjustment *adjustment);
GtkAdjustment*      gtk_tree_view_get_vadjustment       (GtkTreeView *tree_view);
void                gtk_tree_view_set_vadjustment       (GtkTreeView *tree_view,
                                                         GtkAdjustment *adjustment);
gboolean            gtk_tree_view_get_headers_visible   (GtkTreeView *tree_view);
void                gtk_tree_view_set_headers_visible   (GtkTreeView *tree_view,
                                                         gboolean headers_visible);
void                gtk_tree_view_columns_autosize      (GtkTreeView *tree_view);
gboolean            gtk_tree_view_get_headers_clickable (GtkTreeView *tree_view);
void                gtk_tree_view_set_headers_clickable (GtkTreeView *tree_view,
                                                         gboolean setting);
void                gtk_tree_view_set_rules_hint        (GtkTreeView *tree_view,
                                                         gboolean setting);
gboolean            gtk_tree_view_get_rules_hint        (GtkTreeView *tree_view);
gint                gtk_tree_view_append_column         (GtkTreeView *tree_view,
                                                         GtkTreeViewColumn *column);
gint                gtk_tree_view_remove_column         (GtkTreeView *tree_view,
                                                         GtkTreeViewColumn *column);
gint                gtk_tree_view_insert_column         (GtkTreeView *tree_view,
                                                         GtkTreeViewColumn *column,
                                                         gint position);
gint                gtk_tree_view_insert_column_with_attributes
                                                        (GtkTreeView *tree_view,
                                                         gint position,
                                                         const gchar *title,
                                                         GtkCellRenderer *cell,
                                                         ...);
gint                gtk_tree_view_insert_column_with_data_func
                                                        (GtkTreeView *tree_view,
                                                         gint position,
                                                         const gchar *title,
                                                         GtkCellRenderer *cell,
                                                         GtkTreeCellDataFunc func,
                                                         gpointer data,
                                                         GDestroyNotify dnotify);
GtkTreeViewColumn*  gtk_tree_view_get_column            (GtkTreeView *tree_view,
                                                         gint n);
GList*              gtk_tree_view_get_columns           (GtkTreeView *tree_view);
void                gtk_tree_view_move_column_after     (GtkTreeView *tree_view,
                                                         GtkTreeViewColumn *column,
                                                         GtkTreeViewColumn *base_column);
void                gtk_tree_view_set_expander_column   (GtkTreeView *tree_view,
                                                         GtkTreeViewColumn *column);
GtkTreeViewColumn*  gtk_tree_view_get_expander_column   (GtkTreeView *tree_view);
void                gtk_tree_view_set_column_drag_function
                                                        (GtkTreeView *tree_view,
                                                         GtkTreeViewColumnDropFunc func,
                                                         gpointer user_data,
                                                         GtkDestroyNotify destroy);
void                gtk_tree_view_scroll_to_point       (GtkTreeView *tree_view,
                                                         gint tree_x,
                                                         gint tree_y);
void                gtk_tree_view_scroll_to_cell        (GtkTreeView *tree_view,
                                                         GtkTreePath *path,
                                                         GtkTreeViewColumn *column,
                                                         gboolean use_align,
                                                         gfloat row_align,
                                                         gfloat col_align);
void                gtk_tree_view_set_cursor            (GtkTreeView *tree_view,
                                                         GtkTreePath *path,
                                                         GtkTreeViewColumn *focus_column,
                                                         gboolean start_editing);
void                gtk_tree_view_set_cursor_on_cell    (GtkTreeView *tree_view,
                                                         GtkTreePath *path,
                                                         GtkTreeViewColumn *focus_column,
                                                         GtkCellRenderer *focus_cell,
                                                         gboolean start_editing);
void                gtk_tree_view_get_cursor            (GtkTreeView *tree_view,
                                                         GtkTreePath **path,
                                                         GtkTreeViewColumn **focus_column);
void                gtk_tree_view_row_activated         (GtkTreeView *tree_view,
                                                         GtkTreePath *path,
                                                         GtkTreeViewColumn *column);
void                gtk_tree_view_expand_all            (GtkTreeView *tree_view);
void                gtk_tree_view_collapse_all          (GtkTreeView *tree_view);
void                gtk_tree_view_expand_to_path        (GtkTreeView *tree_view,
                                                         GtkTreePath *path);
gboolean            gtk_tree_view_expand_row            (GtkTreeView *tree_view,
                                                         GtkTreePath *path,
                                                         gboolean open_all);
gboolean            gtk_tree_view_collapse_row          (GtkTreeView *tree_view,
                                                         GtkTreePath *path);
void                gtk_tree_view_map_expanded_rows     (GtkTreeView *tree_view,
                                                         GtkTreeViewMappingFunc func,
                                                         gpointer data);
gboolean            gtk_tree_view_row_expanded          (GtkTreeView *tree_view,
                                                         GtkTreePath *path);
void                gtk_tree_view_set_reorderable       (GtkTreeView *tree_view,
                                                         gboolean reorderable);
gboolean            gtk_tree_view_get_reorderable       (GtkTreeView *tree_view);
gboolean            gtk_tree_view_get_path_at_pos       (GtkTreeView *tree_view,
                                                         gint x,
                                                         gint y,
                                                         GtkTreePath **path,
                                                         GtkTreeViewColumn **column,
                                                         gint *cell_x,
                                                         gint *cell_y);
void                gtk_tree_view_get_cell_area         (GtkTreeView *tree_view,
                                                         GtkTreePath *path,
                                                         GtkTreeViewColumn *column,
                                                         GdkRectangle *rect);
void                gtk_tree_view_get_background_area   (GtkTreeView *tree_view,
                                                         GtkTreePath *path,
                                                         GtkTreeViewColumn *column,
                                                         GdkRectangle *rect);
void                gtk_tree_view_get_visible_rect      (GtkTreeView *tree_view,
                                                         GdkRectangle *visible_rect);
gboolean            gtk_tree_view_get_visible_range     (GtkTreeView *tree_view,
                                                         GtkTreePath **start_path,
                                                         GtkTreePath **end_path);
GdkWindow*          gtk_tree_view_get_bin_window        (GtkTreeView *tree_view);
void                gtk_tree_view_widget_to_tree_coords (GtkTreeView *tree_view,
                                                         gint wx,
                                                         gint wy,
                                                         gint *tx,
                                                         gint *ty);
void                gtk_tree_view_tree_to_widget_coords (GtkTreeView *tree_view,
                                                         gint tx,
                                                         gint ty,
                                                         gint *wx,
                                                         gint *wy);
void                gtk_tree_view_enable_model_drag_dest
                                                        (GtkTreeView *tree_view,
                                                         const GtkTargetEntry *targets,
                                                         gint n_targets,
                                                         GdkDragAction actions);
void                gtk_tree_view_enable_model_drag_source
                                                        (GtkTreeView *tree_view,
                                                         GdkModifierType start_button_mask,
                                                         const GtkTargetEntry *targets,
                                                         gint n_targets,
                                                         GdkDragAction actions);
void                gtk_tree_view_unset_rows_drag_source
                                                        (GtkTreeView *tree_view);
void                gtk_tree_view_unset_rows_drag_dest  (GtkTreeView *tree_view);
void                gtk_tree_view_set_drag_dest_row     (GtkTreeView *tree_view,
                                                         GtkTreePath *path,
                                                         GtkTreeViewDropPosition pos);
void                gtk_tree_view_get_drag_dest_row     (GtkTreeView *tree_view,
                                                         GtkTreePath **path,
                                                         GtkTreeViewDropPosition *pos);
gboolean            gtk_tree_view_get_dest_row_at_pos   (GtkTreeView *tree_view,
                                                         gint drag_x,
                                                         gint drag_y,
                                                         GtkTreePath **path,
                                                         GtkTreeViewDropPosition *pos);
GdkPixmap*          gtk_tree_view_create_row_drag_icon  (GtkTreeView *tree_view,
                                                         GtkTreePath *path);
void                gtk_tree_view_set_enable_search     (GtkTreeView *tree_view,
                                                         gboolean enable_search);
gboolean            gtk_tree_view_get_enable_search     (GtkTreeView *tree_view);
gint                gtk_tree_view_get_search_column     (GtkTreeView *tree_view);
void                gtk_tree_view_set_search_column     (GtkTreeView *tree_view,
                                                         gint column);
GtkTreeViewSearchEqualFunc gtk_tree_view_get_search_equal_func
                                                        (GtkTreeView *tree_view);
void                gtk_tree_view_set_search_equal_func (GtkTreeView *tree_view,
                                                         GtkTreeViewSearchEqualFunc search_equal_func,
                                                         gpointer search_user_data,
                                                         GtkDestroyNotify search_destroy);
GtkEntry*           gtk_tree_view_get_search_entry      (GtkTreeView *tree_view);
void                gtk_tree_view_set_search_entry      (GtkTreeView *tree_view,
                                                         GtkEntry *entry);
void                (*GtkTreeViewSearchPositionFunc)    (GtkTreeView *tree_view,
                                                         GtkWidget *search_dialog,
                                                         gpointer user_data);
GtkTreeViewSearchPositionFunc gtk_tree_view_get_search_position_func
                                                        (GtkTreeView *tree_view);
void                gtk_tree_view_set_search_position_func
                                                        (GtkTreeView *tree_view,
                                                         GtkTreeViewSearchPositionFunc func,
                                                         gpointer data,
                                                         GDestroyNotify destroy);
gboolean            gtk_tree_view_get_fixed_height_mode (GtkTreeView *tree_view);
void                gtk_tree_view_set_fixed_height_mode (GtkTreeView *tree_view,
                                                         gboolean enable);
gboolean            gtk_tree_view_get_hover_selection   (GtkTreeView *tree_view);
void                gtk_tree_view_set_hover_selection   (GtkTreeView *tree_view,
                                                         gboolean hover);
gboolean            gtk_tree_view_get_hover_expand      (GtkTreeView *tree_view);
void                gtk_tree_view_set_hover_expand      (GtkTreeView *tree_view,
                                                         gboolean expand);
void                (*GtkTreeDestroyCountFunc)          (GtkTreeView *tree_view,
                                                         GtkTreePath *path,
                                                         gint children,
                                                         gpointer user_data);
void                gtk_tree_view_set_destroy_count_func
                                                        (GtkTreeView *tree_view,
                                                         GtkTreeDestroyCountFunc func,
                                                         gpointer data,
                                                         GtkDestroyNotify destroy);
gboolean            (*GtkTreeViewRowSeparatorFunc)      (GtkTreeModel *model,
                                                         GtkTreeIter *iter,
                                                         gpointer data);
GtkTreeViewRowSeparatorFunc gtk_tree_view_get_row_separator_func
                                                        (GtkTreeView *tree_view);
void                gtk_tree_view_set_row_separator_func
                                                        (GtkTreeView *tree_view,
                                                         GtkTreeViewRowSeparatorFunc func,
                                                         gpointer data,
                                                         GtkDestroyNotify destroy);
gboolean            gtk_tree_view_get_rubber_banding    (GtkTreeView *tree_view);
void                gtk_tree_view_set_rubber_banding    (GtkTreeView *tree_view,
                                                         gboolean enable);
gboolean            gtk_tree_view_get_enable_tree_lines (GtkTreeView *tree_view);
void                gtk_tree_view_set_enable_tree_lines (GtkTreeView *tree_view,
                                                         gboolean enabled);
enum                GtkTreeViewGridLines;
GtkTreeViewGridLines gtk_tree_view_get_grid_lines       (GtkTreeView *tree_view);
void                gtk_tree_view_set_grid_lines        (GtkTreeView *tree_view,
                                                         GtkTreeViewGridLines grid_lines);

Object Hierarchy

  GObject
   +----GInitiallyUnowned
         +----GtkObject
               +----GtkWidget
                     +----GtkContainer
                           +----GtkTreeView

Implemented Interfaces

GtkTreeView implements AtkImplementorIface.

Properties

  "enable-grid-lines"        GtkTreeViewGridLines  : Read / Write
  "enable-search"            gboolean              : Read / Write
  "enable-tree-lines"        gboolean              : Read / Write
  "expander-column"          GtkTreeViewColumn     : Read / Write
  "fixed-height-mode"        gboolean              : Read / Write
  "hadjustment"              GtkAdjustment         : Read / Write
  "headers-clickable"        gboolean              : Read / Write
  "headers-visible"          gboolean              : Read / Write
  "hover-expand"             gboolean              : Read / Write
  "hover-selection"          gboolean              : Read / Write
  "level-indentation"        gint                  : Read / Write
  "model"                    GtkTreeModel          : Read / Write
  "reorderable"              gboolean              : Read / Write
  "rubber-banding"           gboolean              : Read / Write
  "rules-hint"               gboolean              : Read / Write
  "search-column"            gint                  : Read / Write
  "show-expanders"           gboolean              : Read / Write
  "vadjustment"              GtkAdjustment         : Read / Write

Style Properties

  "allow-rules"              gboolean              : Read
  "even-row-color"           GdkColor              : Read
  "expander-size"            gint                  : Read
  "grid-line-pattern"        gchararray            : Read
  "grid-line-width"          gint                  : Read
  "horizontal-separator"     gint                  : Read
  "indent-expanders"         gboolean              : Read
  "odd-row-color"            GdkColor              : Read
  "row-ending-details"       gboolean              : Read
  "tree-line-pattern"        gchararray            : Read
  "tree-line-width"          gint                  : Read
  "vertical-separator"       gint                  : Read

Signals

  "columns-changed"                                : Run Last
  "cursor-changed"                                 : Run Last
  "expand-collapse-cursor-row"                     : Run Last / Action
  "move-cursor"                                    : Run Last / Action
  "row-activated"                                  : Run Last / Action
  "row-collapsed"                                  : Run Last
  "row-expanded"                                   : Run Last
  "select-all"                                     : Run Last / Action
  "select-cursor-parent"                           : Run Last / Action
  "select-cursor-row"                              : Run Last / Action
  "set-scroll-adjustments"                         : Run Last / Action
  "start-interactive-search"                       : Run Last / Action
  "test-collapse-row"                              : Run Last
  "test-expand-row"                                : Run Last
  "toggle-cursor-row"                              : Run Last / Action
  "unselect-all"                                   : Run Last / Action

Description

Widget that displays any object that implements the GtkTreeModel interface.

Please refer to the tree widget conceptual overview for an overview of all the objects and data types related to the tree widget and how they work together.

Details

GtkTreeView

typedef struct _GtkTreeView GtkTreeView;

enum GtkTreeViewDropPosition

typedef enum
{
  /* drop before/after this row */
  GTK_TREE_VIEW_DROP_BEFORE,
  GTK_TREE_VIEW_DROP_AFTER,
  /* drop as a child of this row (with fallback to before or after
   * if into is not possible)
   */
  GTK_TREE_VIEW_DROP_INTO_OR_BEFORE,
  GTK_TREE_VIEW_DROP_INTO_OR_AFTER
} GtkTreeViewDropPosition;

An enum for determining where a dropped row goes.

GTK_TREE_VIEW_DROP_BEFORE | dropped row is inserted before
GTK_TREE_VIEW_DROP_AFTER | dropped row is inserted after
GTK_TREE_VIEW_DROP_INTO_OR_BEFORE | dropped row becomes a child or is inserted before
GTK_TREE_VIEW_DROP_INTO_OR_AFTER | dropped row becomes a child or is inserted after

GtkTreeViewPrivate

typedef struct _GtkTreeViewPrivate GtkTreeViewPrivate;

A private struct for internal use only. The definition of this structure is not publically available.

GtkTreeViewColumnDropFunc ()

gboolean            (*GtkTreeViewColumnDropFunc)        (GtkTreeView *tree_view,
                                                         GtkTreeViewColumn *column,
                                                         GtkTreeViewColumn *prev_column,
                                                         GtkTreeViewColumn *next_column,
                                                         gpointer data);

Function type for determining whether column can be dropped in a particular spot (as determined by prev_column and next_column). In left to right locales, prev_column is on the left of the potential drop spot, and next_column is on the right. In right to left mode, this is reversed. This function should return TRUE if the spot is a valid drop spot. Please note that returning TRUE does not actually indicate that the column drop was made, but is meant only to indicate a possible drop spot to the user.

tree_view : | A GtkTreeView
column : | The GtkTreeViewColumn being dragged
prev_column : | A GtkTreeViewColumn on one side of column
next_column : | A GtkTreeViewColumn on the other side of column
data : | user data
Returns : | TRUE, if column can be dropped in this spot

GtkTreeViewMappingFunc ()

void                (*GtkTreeViewMappingFunc)           (GtkTreeView *tree_view,
                                                         GtkTreePath *path,
                                                         gpointer user_data);

Function used for gtk_tree_view_map_expanded_rows.

tree_view : | A GtkTreeView
path : | The path that's expanded
user_data : | user data

GtkTreeViewSearchEqualFunc ()

gboolean            (*GtkTreeViewSearchEqualFunc)       (GtkTreeModel *model,
                                                         gint column,
                                                         const gchar *key,
                                                         GtkTreeIter *iter,
                                                         gpointer search_data);

A function used for checking whether a row in model matches a search key string entered by the user. Note the return value is reversed from what you would normally expect, though it has some similarity to strcmp() returning 0 for equal strings.

model : | the GtkTreeModel being searched
column : | the search column set by gtk_tree_view_set_search_column()
key : | the key string to compare with
iter : | a GtkTreeIter pointing the row of model that should be compared with key.
search_data : | user data from gtk_tree_view_set_search_equal_func()
Returns : | FALSE if the row matches, TRUE otherwise.

gtk_tree_view_new ()

GtkWidget*          gtk_tree_view_new                   (void);

Creates a new GtkTreeView widget.

Returns : A newly created GtkTreeView widget.

gtk_tree_view_new_with_model ()

GtkWidget*          gtk_tree_view_new_with_model        (GtkTreeModel *model);

Creates a new GtkTreeView widget with the model initialized to model.

model : | the model.
Returns : | A newly created GtkTreeView widget.

gtk_tree_view_get_model ()

GtkTreeModel*       gtk_tree_view_get_model             (GtkTreeView *tree_view);

Returns the model the GtkTreeView is based on. Returns NULL if the model is unset.

tree_view : | a GtkTreeView
Returns : | A GtkTreeModel, or NULL if none is currently being used.

gtk_tree_view_set_model ()

void                gtk_tree_view_set_model             (GtkTreeView *tree_view,
                                                         GtkTreeModel *model);

Sets the model for a GtkTreeView. If the tree_view already has a model set, it will remove it before setting the new model. If model is NULL, then it will unset the old model.

tree_view : | A GtkTreeNode.
model : | The model.

gtk_tree_view_get_selection ()

GtkTreeSelection*   gtk_tree_view_get_selection         (GtkTreeView *tree_view);

Gets the GtkTreeSelection associated with tree_view.

tree_view : | A GtkTreeView.
Returns : | A GtkTreeSelection object.

gtk_tree_view_get_hadjustment ()

GtkAdjustment*      gtk_tree_view_get_hadjustment       (GtkTreeView *tree_view);

Gets the GtkAdjustment currently being used for the horizontal aspect.

tree_view : | A GtkTreeView
Returns : | A GtkAdjustment object, or NULL if none is currently being used.

gtk_tree_view_set_hadjustment ()

void                gtk_tree_view_set_hadjustment       (GtkTreeView *tree_view,
                                                         GtkAdjustment *adjustment);

Sets the GtkAdjustment for the current horizontal aspect.

tree_view : | A GtkTreeView
adjustment : | The GtkAdjustment to set, or NULL

gtk_tree_view_get_vadjustment ()

GtkAdjustment*      gtk_tree_view_get_vadjustment       (GtkTreeView *tree_view);

Gets the GtkAdjustment currently being used for the vertical aspect.

tree_view : | A GtkTreeView
Returns : | A GtkAdjustment object, or NULL if none is currently being used.

gtk_tree_view_set_vadjustment ()

void                gtk_tree_view_set_vadjustment       (GtkTreeView *tree_view,
                                                         GtkAdjustment *adjustment);

Sets the GtkAdjustment for the current vertical aspect.

tree_view : | A GtkTreeView
adjustment : | The GtkAdjustment to set, or NULL

gtk_tree_view_get_headers_visible ()

gboolean            gtk_tree_view_get_headers_visible   (GtkTreeView *tree_view);

Returns TRUE if the headers on the tree_view are visible.

tree_view : | A GtkTreeView.
Returns : | Whether the headers are visible or not.

gtk_tree_view_set_headers_visible ()

void                gtk_tree_view_set_headers_visible   (GtkTreeView *tree_view,
                                                         gboolean headers_visible);

Sets the visibility state of the headers.

tree_view : | A GtkTreeView.
headers_visible : | TRUE if the headers are visible

gtk_tree_view_columns_autosize ()

void                gtk_tree_view_columns_autosize      (GtkTreeView *tree_view);

Resizes all columns to their optimal width. Only works after the treeview has been realized.

tree_view : A GtkTreeView.

gtk_tree_view_get_headers_clickable ()

gboolean            gtk_tree_view_get_headers_clickable (GtkTreeView *tree_view);

Returns whether all header columns are clickable.

tree_view : | A GtkTreeView.
Returns : | TRUE if all header columns are clickable, otherwise FALSE

Since 2.10

gtk_tree_view_set_headers_clickable ()

void                gtk_tree_view_set_headers_clickable (GtkTreeView *tree_view,
                                                         gboolean setting);

Allow the column title buttons to be clicked.

tree_view : | A GtkTreeView.
setting : | TRUE if the columns are clickable.

gtk_tree_view_set_rules_hint ()

void                gtk_tree_view_set_rules_hint        (GtkTreeView *tree_view,
                                                         gboolean setting);

This function tells GTK+ that the user interface for your application requires users to read across tree rows and associate cells with one another. By default, GTK+ will then render the tree with alternating row colors. Do not use it just because you prefer the appearance of the ruled tree; that's a question for the theme. Some themes will draw tree rows in alternating colors even when rules are turned off, and users who prefer that appearance all the time can choose those themes. You should call this function only as a semantic hint to the theme engine that your tree makes alternating colors useful from a functional standpoint (since it has lots of columns, generally).

tree_view : | a GtkTreeView
setting : | TRUE if the tree requires reading across rows

gtk_tree_view_get_rules_hint ()

gboolean            gtk_tree_view_get_rules_hint        (GtkTreeView *tree_view);

Gets the setting set by gtk_tree_view_set_rules_hint().

tree_view : | a GtkTreeView
Returns : | TRUE if rules are useful for the user of this tree

gtk_tree_view_append_column ()

gint                gtk_tree_view_append_column         (GtkTreeView *tree_view,
                                                         GtkTreeViewColumn *column);

Appends column to the list of columns. If tree_view has "fixed_height" mode enabled, then column must have its "sizing" property set to be GTK_TREE_VIEW_COLUMN_FIXED.

tree_view : | A GtkTreeView.
column : | The GtkTreeViewColumn to add.
Returns : | The number of columns in tree_view after appending.

gtk_tree_view_remove_column ()

gint                gtk_tree_view_remove_column         (GtkTreeView *tree_view,
                                                         GtkTreeViewColumn *column);

Removes column from tree_view.

tree_view : | A GtkTreeView.
column : | The GtkTreeViewColumn to remove.
Returns : | The number of columns in tree_view after removing.

gtk_tree_view_insert_column ()

gint                gtk_tree_view_insert_column         (GtkTreeView *tree_view,
                                                         GtkTreeViewColumn *column,
                                                         gint position);

This inserts the column into the tree_view at position. If position is -1, then the column is inserted at the end. If tree_view has "fixed_height" mode enabled, then column must have its "sizing" property set to be GTK_TREE_VIEW_COLUMN_FIXED.

tree_view : | A GtkTreeView.
column : | The GtkTreeViewColumn to be inserted.
position : | The position to insert column in.
Returns : | The number of columns in tree_view after insertion.

gtk_tree_view_insert_column_with_attributes ()

gint                gtk_tree_view_insert_column_with_attributes
                                                        (GtkTreeView *tree_view,
                                                         gint position,
                                                         const gchar *title,
                                                         GtkCellRenderer *cell,
                                                         ...);

Creates a new GtkTreeViewColumn and inserts it into the tree_view at position. If position is -1, then the newly created column is inserted at the end. The column is initialized with the attributes given. If tree_view has "fixed_height" mode enabled, then the new column will have its sizing property set to be GTK_TREE_VIEW_COLUMN_FIXED.

tree_view : | A GtkTreeView
position : | The position to insert the new column in.
title : | The title to set the header to.
cell : | The GtkCellRenderer.
... : | A NULL-terminated list of attributes.
Returns : | The number of columns in tree_view after insertion.

gtk_tree_view_insert_column_with_data_func ()

gint                gtk_tree_view_insert_column_with_data_func
                                                        (GtkTreeView *tree_view,
                                                         gint position,
                                                         const gchar *title,
                                                         GtkCellRenderer *cell,
                                                         GtkTreeCellDataFunc func,
                                                         gpointer data,
                                                         GDestroyNotify dnotify);

Convenience function that inserts a new column into the GtkTreeView with the given cell renderer and a GtkCellDataFunc to set cell renderer attributes (normally using data from the model). See also gtk_tree_view_column_set_cell_data_func(), gtk_tree_view_column_pack_start(). If tree_view has "fixed_height" mode enabled, then the new column will have its "sizing" property set to be GTK_TREE_VIEW_COLUMN_FIXED.

tree_view : | a GtkTreeView
position : | Position to insert, -1 for append
title : | column title
cell : | cell renderer for column
func : | function to set attributes of cell renderer
data : | data for func
dnotify : | destroy notifier for data
Returns : | number of columns in the tree view post-insert

gtk_tree_view_get_column ()

GtkTreeViewColumn*  gtk_tree_view_get_column            (GtkTreeView *tree_view,
                                                         gint n);

Gets the GtkTreeViewColumn at the given position in the tree_view.

tree_view : | A GtkTreeView.
n : | The position of the column, counting from 0.
Returns : | The GtkTreeViewColumn, or NULL if the position is outside the range of columns.

gtk_tree_view_get_columns ()

GList*              gtk_tree_view_get_columns           (GtkTreeView *tree_view);

Returns a GList of all the GtkTreeViewColumn s currently in tree_view. The returned list must be freed with g_list_free().

tree_view : | A GtkTreeView
Returns : | A list of GtkTreeViewColumn s

gtk_tree_view_move_column_after ()

void                gtk_tree_view_move_column_after     (GtkTreeView *tree_view,
                                                         GtkTreeViewColumn *column,
                                                         GtkTreeViewColumn *base_column);

Moves column to be after to base_column. If base_column is NULL, then column is placed in the first position.

tree_view : | A GtkTreeView
column : | The GtkTreeViewColumn to be moved.
base_column : | The GtkTreeViewColumn to be moved relative to, or NULL.

gtk_tree_view_set_expander_column ()

void                gtk_tree_view_set_expander_column   (GtkTreeView *tree_view,
                                                         GtkTreeViewColumn *column);

Sets the column to draw the expander arrow at. It must be in tree_view. If column is NULL, then the expander arrow is always at the first visible column.

If you do not want expander arrow to appear in your tree, set the expander column to a hidden column.

tree_view : | A GtkTreeView
column : | NULL, or the column to draw the expander arrow at.

gtk_tree_view_get_expander_column ()

GtkTreeViewColumn*  gtk_tree_view_get_expander_column   (GtkTreeView *tree_view);

Returns the column that is the current expander column. This column has the expander arrow drawn next to it.

tree_view : | A GtkTreeView
Returns : | The expander column.

gtk_tree_view_set_column_drag_function ()

void                gtk_tree_view_set_column_drag_function
                                                        (GtkTreeView *tree_view,
                                                         GtkTreeViewColumnDropFunc func,
                                                         gpointer user_data,
                                                         GtkDestroyNotify destroy);

Sets a user function for determining where a column may be dropped when dragged. This function is called on every column pair in turn at the beginning of a column drag to determine where a drop can take place. The arguments passed to func are: the tree_view, the GtkTreeViewColumn being dragged, the two GtkTreeViewColumn s determining the drop spot, and user_data. If either of the GtkTreeViewColumn arguments for the drop spot are NULL, then they indicate an edge. If func is set to be NULL, then tree_view reverts to the default behavior of allowing all columns to be dropped everywhere.

tree_view : | A GtkTreeView.
func : | A function to determine which columns are reorderable, or NULL.
user_data : | User data to be passed to func, or NULL
destroy : | Destroy notifier for user_data, or NULL

gtk_tree_view_scroll_to_point ()

void                gtk_tree_view_scroll_to_point       (GtkTreeView *tree_view,
                                                         gint tree_x,
                                                         gint tree_y);

Scrolls the tree view such that the top-left corner of the visible area is tree_x, tree_y, where tree_x and tree_y are specified in tree window coordinates. The tree_view must be realized before this function is called. If it isn't, you probably want to be using gtk_tree_view_scroll_to_cell().

If either tree_x or tree_y are -1, then that direction isn't scrolled.

tree_view : | a GtkTreeView
tree_x : | X coordinate of new top-left pixel of visible area, or -1
tree_y : | Y coordinate of new top-left pixel of visible area, or -1

gtk_tree_view_scroll_to_cell ()

void                gtk_tree_view_scroll_to_cell        (GtkTreeView *tree_view,
                                                         GtkTreePath *path,
                                                         GtkTreeViewColumn *column,
                                                         gboolean use_align,
                                                         gfloat row_align,
                                                         gfloat col_align);

Moves the alignments of tree_view to the position specified by column and path. If column is NULL, then no horizontal scrolling occurs. Likewise, if path is NULL no vertical scrolling occurs. At a minimum, one of column or path need to be non-NULL. row_align determines where the row is placed, and col_align determines where column is placed. Both are expected to be between 0.0 and 1.0. 0.0 means left/top alignment, 1.0 means right/bottom alignment, 0.5 means center.

If use_align is FALSE, then the alignment arguments are ignored, and the tree does the minimum amount of work to scroll the cell onto the screen. This means that the cell will be scrolled to the edge closest to its current position. If the cell is currently visible on the screen, nothing is done.

This function only works if the model is set, and path is a valid row on the model. If the model changes before the tree_view is realized, the centered path will be modified to reflect this change.

tree_view : | A GtkTreeView.
path : | The path of the row to move to, or NULL.
column : | The GtkTreeViewColumn to move horizontally to, or NULL.
use_align : | whether to use alignment arguments, or FALSE.
row_align : | The vertical alignment of the row specified by path.
col_align : | The horizontal alignment of the column specified by column.

gtk_tree_view_set_cursor ()

void                gtk_tree_view_set_cursor            (GtkTreeView *tree_view,
                                                         GtkTreePath *path,
                                                         GtkTreeViewColumn *focus_column,
                                                         gboolean start_editing);

Sets the current keyboard focus to be at path, and selects it. This is useful when you want to focus the user's attention on a particular row. If focus_column is not NULL, then focus is given to the column specified by it. Additionally, if focus_column is specified, and start_editing is TRUE, then editing should be started in the specified cell. This function is often followed by gtk_widget_grab_focus (tree_view) in order to give keyboard focus to the widget. Please note that editing can only happen when the widget is realized.

tree_view : | A GtkTreeView
path : | A GtkTreePath
focus_column : | A GtkTreeViewColumn, or NULL
start_editing : | TRUE if the specified cell should start being edited.

gtk_tree_view_set_cursor_on_cell ()

void                gtk_tree_view_set_cursor_on_cell    (GtkTreeView *tree_view,
                                                         GtkTreePath *path,
                                                         GtkTreeViewColumn *focus_column,
                                                         GtkCellRenderer *focus_cell,
                                                         gboolean start_editing);

Sets the current keyboard focus to be at path, and selects it. This is useful when you want to focus the user's attention on a particular row. If focus_column is not NULL, then focus is given to the column specified by it. If focus_column and focus_cell are not NULL, and focus_column contains 2 or more editable or activatable cells, then focus is given to the cell specified by focus_cell. Additionally, if focus_column is specified, and start_editing is TRUE, then editing should be started in the specified cell. This function is often followed by gtk_widget_grab_focus (tree_view) in order to give keyboard focus to the widget. Please note that editing can only happen when the widget is realized.

tree_view : | A GtkTreeView
path : | A GtkTreePath
focus_column : | A GtkTreeViewColumn, or NULL
focus_cell : | A GtkCellRenderer, or NULL
start_editing : | TRUE if the specified cell should start being edited.

Since 2.2

gtk_tree_view_get_cursor ()

void                gtk_tree_view_get_cursor            (GtkTreeView *tree_view,
                                                         GtkTreePath **path,
                                                         GtkTreeViewColumn **focus_column);

Fills in path and focus_column with the current path and focus column. If the cursor isn't currently set, then *path will be NULL. If no column currently has focus, then *focus_column will be NULL.

The returned GtkTreePath must be freed with gtk_tree_path_free() when you are done with it.

tree_view : | A GtkTreeView
path : | A pointer to be filled with the current cursor path, or NULL
focus_column : | A pointer to be filled with the current focus column, or NULL

gtk_tree_view_row_activated ()

void                gtk_tree_view_row_activated         (GtkTreeView *tree_view,
                                                         GtkTreePath *path,
                                                         GtkTreeViewColumn *column);

Activates the cell determined by path and column.

tree_view : | A GtkTreeView
path : | The GtkTreePath to be activated.
column : | The GtkTreeViewColumn to be activated.

gtk_tree_view_expand_all ()

void                gtk_tree_view_expand_all            (GtkTreeView *tree_view);

Recursively expands all nodes in the tree_view.

tree_view : A GtkTreeView.

gtk_tree_view_collapse_all ()

void                gtk_tree_view_collapse_all          (GtkTreeView *tree_view);

Recursively collapses all visible, expanded nodes in tree_view.

tree_view : A GtkTreeView.

gtk_tree_view_expand_to_path ()

void                gtk_tree_view_expand_to_path        (GtkTreeView *tree_view,
                                                         GtkTreePath *path);

Expands the row at path. This will also expand all parent rows of path as necessary.

tree_view : | A GtkTreeView.
path : | path to a row.

Since 2.2

gtk_tree_view_expand_row ()

gboolean            gtk_tree_view_expand_row            (GtkTreeView *tree_view,
                                                         GtkTreePath *path,
                                                         gboolean open_all);

Opens the row so its children are visible.

tree_view : | a GtkTreeView
path : | path to a row
open_all : | whether to recursively expand, or just expand immediate children
Returns : | TRUE if the row existed and had children

gtk_tree_view_collapse_row ()

gboolean            gtk_tree_view_collapse_row          (GtkTreeView *tree_view,
                                                         GtkTreePath *path);

Collapses a row (hides its child rows, if they exist).

tree_view : | a GtkTreeView
path : | path to a row in the tree_view
Returns : | TRUE if the row was collapsed.

gtk_tree_view_map_expanded_rows ()

void                gtk_tree_view_map_expanded_rows     (GtkTreeView *tree_view,
                                                         GtkTreeViewMappingFunc func,
                                                         gpointer data);

Calls func on all expanded rows.

tree_view : | A GtkTreeView
func : | A function to be called
data : | User data to be passed to the function.

gtk_tree_view_row_expanded ()

gboolean            gtk_tree_view_row_expanded          (GtkTreeView *tree_view,
                                                         GtkTreePath *path);

Returns TRUE if the node pointed to by path is expanded in tree_view.

tree_view : | A GtkTreeView.
path : | A GtkTreePath to test expansion state.
Returns : | TRUE if path is expanded.

gtk_tree_view_set_reorderable ()

void                gtk_tree_view_set_reorderable       (GtkTreeView *tree_view,
                                                         gboolean reorderable);

This function is a convenience function to allow you to reorder models that support the GtkDragSourceIface and the GtkDragDestIface. Both GtkTreeStore and GtkListStore support these. If reorderable is TRUE, then the user can reorder the model by dragging and dropping rows. The developer can listen to these changes by connecting to the model's row_inserted and row_deleted signals.

This function does not give you any degree of control over the order -- any reordering is allowed. If more control is needed, you should probably handle drag and drop manually.

tree_view : | A GtkTreeView.
reorderable : | TRUE, if the tree can be reordered.

gtk_tree_view_get_reorderable ()

gboolean            gtk_tree_view_get_reorderable       (GtkTreeView *tree_view);

Retrieves whether the user can reorder the tree via drag-and-drop. See gtk_tree_view_set_reorderable().

tree_view : | a GtkTreeView
Returns : | TRUE if the tree can be reordered.

gtk_tree_view_get_path_at_pos ()

gboolean            gtk_tree_view_get_path_at_pos       (GtkTreeView *tree_view,
                                                         gint x,
                                                         gint y,
                                                         GtkTreePath **path,
                                                         GtkTreeViewColumn **column,
                                                         gint *cell_x,
                                                         gint *cell_y);

Finds the path at the point (x, y), relative to widget coordinates. That is, x and y are relative to an events coordinates. x and y must come from an event on the tree_view only where event->window == gtk_tree_view_get_bin (). It is primarily for things like popup menus. If path is non-NULL, then it will be filled with the GtkTreePath at that point. This path should be freed with gtk_tree_path_free(). If column is non-NULL, then it will be filled with the column at that point. cell_x and cell_y return the coordinates relative to the cell background (i.e. the background_area passed to gtk_cell_renderer_render()). This function is only meaningful if tree_view is realized.

tree_view : | A GtkTreeView.
x : | The x position to be identified.
y : | The y position to be identified.
path : | A pointer to a GtkTreePath pointer to be filled in, or NULL
column : | A pointer to a GtkTreeViewColumn pointer to be filled in, or NULL
cell_x : | A pointer where the X coordinate relative to the cell can be placed, or NULL
cell_y : | A pointer where the Y coordinate relative to the cell can be placed, or NULL
Returns : | TRUE if a row exists at that coordinate.

gtk_tree_view_get_cell_area ()

void                gtk_tree_view_get_cell_area         (GtkTreeView *tree_view,
                                                         GtkTreePath *path,
                                                         GtkTreeViewColumn *column,
                                                         GdkRectangle *rect);

Fills the bounding rectangle in tree window coordinates for the cell at the row specified by path and the column specified by column. If path is NULL, or points to a path not currently displayed, the y and height fields of the rectangle will be filled with 0. If column is NULL, the x and width fields will be filled with 0. The sum of all cell rects does not cover the entire tree; there are extra pixels in between rows, for example. The returned rectangle is equivalent to the cell_area passed to gtk_cell_renderer_render(). This function is only valid if tree_view is realized.

tree_view : | a GtkTreeView
path : | a GtkTreePath for the row, or NULL to get only horizontal coordinates
column : | a GtkTreeViewColumn for the column, or NULL to get only vertical coordinates
rect : | rectangle to fill with cell rect

gtk_tree_view_get_background_area ()

void                gtk_tree_view_get_background_area   (GtkTreeView *tree_view,
                                                         GtkTreePath *path,
                                                         GtkTreeViewColumn *column,
                                                         GdkRectangle *rect);

Fills the bounding rectangle in tree window coordinates for the cell at the row specified by path and the column specified by column. If path is NULL, or points to a node not found in the tree, the y and height fields of the rectangle will be filled with 0. If column is NULL, the x and width fields will be filled with 0. The returned rectangle is equivalent to the background_area passed to gtk_cell_renderer_render(). These background areas tile to cover the entire tree window (except for the area used for header buttons). Contrast with the cell_area, returned by gtk_tree_view_get_cell_area(), which returns only the cell itself, excluding surrounding borders and the tree expander area.

tree_view : | a GtkTreeView
path : | a GtkTreePath for the row, or NULL to get only horizontal coordinates
column : | a GtkTreeViewColumn for the column, or NULL to get only vertical coordiantes
rect : | rectangle to fill with cell background rect

gtk_tree_view_get_visible_rect ()

void                gtk_tree_view_get_visible_rect      (GtkTreeView *tree_view,
                                                         GdkRectangle *visible_rect);

Fills visible_rect with the currently-visible region of the buffer, in tree coordinates. Convert to widget coordinates with gtk_tree_view_tree_to_widget_coords(). Tree coordinates start at 0,0 for row 0 of the tree, and cover the entire scrollable area of the tree.

tree_view : | a GtkTreeView
visible_rect : | rectangle to fill

gtk_tree_view_get_visible_range ()

gboolean            gtk_tree_view_get_visible_range     (GtkTreeView *tree_view,
                                                         GtkTreePath **start_path,
                                                         GtkTreePath **end_path);

Sets start_path and end_path to be the first and last visible path. Note that there may be invisible paths in between.

The paths should be freed with gtk_tree_path_free() after use.

tree_view : | A GtkTreeView
start_path : | Return location for start of region, or NULL.
end_path : | Return location for end of region, or NULL.
Returns : | TRUE, if valid paths were placed in start_path and end_path.

Since 2.8

gtk_tree_view_get_bin_window ()

GdkWindow*          gtk_tree_view_get_bin_window        (GtkTreeView *tree_view);

Returns the window that tree_view renders to. This is used primarily to compare to event->window to confirm that the event on tree_view is on the right window.

tree_view : | A GtkTreeView
Returns : | A GdkWindow, or NULL when tree_view hasn't been realized yet

gtk_tree_view_widget_to_tree_coords ()

void                gtk_tree_view_widget_to_tree_coords (GtkTreeView *tree_view,
                                                         gint wx,
                                                         gint wy,
                                                         gint *tx,
                                                         gint *ty);

Converts widget coordinates to coordinates for the tree window (the full scrollable area of the tree).

tree_view : | a GtkTreeView
wx : | widget X coordinate
wy : | widget Y coordinate
tx : | return location for tree X coordinate
ty : | return location for tree Y coordinate

gtk_tree_view_tree_to_widget_coords ()

void                gtk_tree_view_tree_to_widget_coords (GtkTreeView *tree_view,
                                                         gint tx,
                                                         gint ty,
                                                         gint *wx,
                                                         gint *wy);

Converts tree coordinates (coordinates in full scrollable area of the tree) to widget coordinates.

tree_view : | a GtkTreeView
tx : | tree X coordinate
ty : | tree Y coordinate
wx : | return location for widget X coordinate
wy : | return location for widget Y coordinate

gtk_tree_view_enable_model_drag_dest ()

void                gtk_tree_view_enable_model_drag_dest
                                                        (GtkTreeView *tree_view,
                                                         const GtkTargetEntry *targets,
                                                         gint n_targets,
                                                         GdkDragAction actions);

Turns tree_view into a drop destination for automatic DND.

tree_view : | a GtkTreeView
targets : | the table of targets that the drag will support
n_targets : | the number of items in targets
actions : | the bitmask of possible actions for a drag from this widget

gtk_tree_view_enable_model_drag_source ()

void                gtk_tree_view_enable_model_drag_source
                                                        (GtkTreeView *tree_view,
                                                         GdkModifierType start_button_mask,
                                                         const GtkTargetEntry *targets,
                                                         gint n_targets,
                                                         GdkDragAction actions);

Turns tree_view into a drag source for automatic DND.

tree_view : | a GtkTreeView
start_button_mask : | Mask of allowed buttons to start drag
targets : | the table of targets that the drag will support
n_targets : | the number of items in targets
actions : | the bitmask of possible actions for a drag from this widget

gtk_tree_view_unset_rows_drag_source ()

void                gtk_tree_view_unset_rows_drag_source
                                                        (GtkTreeView *tree_view);

Undoes the effect of gtk_tree_view_enable_model_drag_source().

tree_view : a GtkTreeView

gtk_tree_view_unset_rows_drag_dest ()

void                gtk_tree_view_unset_rows_drag_dest  (GtkTreeView *tree_view);

Undoes the effect of gtk_tree_view_enable_model_drag_dest().

tree_view : a GtkTreeView

gtk_tree_view_set_drag_dest_row ()

void                gtk_tree_view_set_drag_dest_row     (GtkTreeView *tree_view,
                                                         GtkTreePath *path,
                                                         GtkTreeViewDropPosition pos);

Sets the row that is highlighted for feedback.

tree_view : | a GtkTreeView
path : | The path of the row to highlight, or NULL.
pos : | Specifies whether to drop before, after or into the row

gtk_tree_view_get_drag_dest_row ()

void                gtk_tree_view_get_drag_dest_row     (GtkTreeView *tree_view,
                                                         GtkTreePath **path,
                                                         GtkTreeViewDropPosition *pos);

Gets information about the row that is highlighted for feedback.

tree_view : | a GtkTreeView
path : | Return location for the path of the highlighted row, or NULL.
pos : | Return location for the drop position, or NULL

gtk_tree_view_get_dest_row_at_pos ()

gboolean            gtk_tree_view_get_dest_row_at_pos   (GtkTreeView *tree_view,
                                                         gint drag_x,
                                                         gint drag_y,
                                                         GtkTreePath **path,
                                                         GtkTreeViewDropPosition *pos);

Determines the destination row for a given position.

tree_view : | a GtkTreeView
drag_x : | the position to determine the destination row for
drag_y : | the position to determine the destination row for
path : | Return location for the path of the highlighted row, or NULL.
pos : | Return location for the drop position, or NULL
Returns : | whether there is a row at the given position.

gtk_tree_view_create_row_drag_icon ()

GdkPixmap*          gtk_tree_view_create_row_drag_icon  (GtkTreeView *tree_view,
                                                         GtkTreePath *path);

Creates a GdkPixmap representation of the row at path. This image is used for a drag icon.

tree_view : | a GtkTreeView
path : | a GtkTreePath in tree_view
Returns : | a newly-allocated pixmap of the drag icon.

gtk_tree_view_set_enable_search ()

void                gtk_tree_view_set_enable_search     (GtkTreeView *tree_view,
                                                         gboolean enable_search);

If enable_search is set, then the user can type in text to search through the tree interactively (this is sometimes called "typeahead find").

Note that even if this is FALSE, the user can still initiate a search using the "start-interactive-search" key binding.

tree_view : | A GtkTreeView
enable_search : | TRUE, if the user can search interactively

gtk_tree_view_get_enable_search ()

gboolean            gtk_tree_view_get_enable_search     (GtkTreeView *tree_view);

Returns whether or not the tree allows to start interactive searching by typing in text.

tree_view : | A GtkTreeView
Returns : | whether or not to let the user search interactively

gtk_tree_view_get_search_column ()

gint                gtk_tree_view_get_search_column     (GtkTreeView *tree_view);

Gets the column searched on by the interactive search code.

tree_view : | A GtkTreeView
Returns : | the column the interactive search code searches in.

gtk_tree_view_set_search_column ()

void                gtk_tree_view_set_search_column     (GtkTreeView *tree_view,
                                                         gint column);

Sets column as the column where the interactive search code should search in.

If the sort column is set, users can use the "start-interactive-search" key binding to bring up search popup. The enable-search property controls whether simply typing text will also start an interactive search.

Note that column refers to a column of the model.

tree_view : | A GtkTreeView
column : | the column of the model to search in, or -1 to disable searching

gtk_tree_view_get_search_equal_func ()

GtkTreeViewSearchEqualFunc gtk_tree_view_get_search_equal_func
                                                        (GtkTreeView *tree_view);

Returns the compare function currently in use.

tree_view : | A GtkTreeView
Returns : | the currently used compare function for the search code.

gtk_tree_view_set_search_equal_func ()

void                gtk_tree_view_set_search_equal_func (GtkTreeView *tree_view,
                                                         GtkTreeViewSearchEqualFunc search_equal_func,
                                                         gpointer search_user_data,
                                                         GtkDestroyNotify search_destroy);

Sets the compare function for the interactive search capabilities; note that somewhat like strcmp() returning 0 for equality GtkTreeViewSearchEqualFunc returns FALSE on matches.

tree_view : | A GtkTreeView
search_equal_func : | the compare function to use during the search
search_user_data : | user data to pass to search_equal_func, or NULL
search_destroy : | Destroy notifier for search_user_data, or NULL

gtk_tree_view_get_search_entry ()

GtkEntry*           gtk_tree_view_get_search_entry      (GtkTreeView *tree_view);

Returns the GtkEntry which is currently in use as interactive search entry for tree_view. In case the built-in entry is being used, NULL will be returned.

tree_view : | A GtkTreeView
Returns : | the entry currently in use as search entry.

Since 2.10

gtk_tree_view_set_search_entry ()

void                gtk_tree_view_set_search_entry      (GtkTreeView *tree_view,
                                                         GtkEntry *entry);

Sets the entry which the interactive search code will use for this tree_view. This is useful when you want to provide a search entry in our interface at all time at a fixed position. Passing NULL for entry will make the interactive search code use the built-in popup entry again.

tree_view : | A GtkTreeView
entry : | the entry the interactive search code of tree_view should use or NULL

Since 2.10

GtkTreeViewSearchPositionFunc ()

void                (*GtkTreeViewSearchPositionFunc)    (GtkTreeView *tree_view,
                                                         GtkWidget *search_dialog,
                                                         gpointer user_data);

tree_view :
search_dialog :
user_data :

gtk_tree_view_get_search_position_func ()

GtkTreeViewSearchPositionFunc gtk_tree_view_get_search_position_func
                                                        (GtkTreeView *tree_view);

Returns the positioning function currently in use.

tree_view : | A GtkTreeView
Returns : | the currently used function for positioning the search dialog.

Since 2.10

gtk_tree_view_set_search_position_func ()

void                gtk_tree_view_set_search_position_func
                                                        (GtkTreeView *tree_view,
                                                         GtkTreeViewSearchPositionFunc func,
                                                         gpointer data,
                                                         GDestroyNotify destroy);

Sets the function to use when positioning the seach dialog.

tree_view : | A GtkTreeView
func : | the function to use to position the search dialog, or NULL to use the default search position function
data : | user data to pass to func, or NULL
destroy : | Destroy notifier for data, or NULL

Since 2.10

gtk_tree_view_get_fixed_height_mode ()

gboolean            gtk_tree_view_get_fixed_height_mode (GtkTreeView *tree_view);

Returns whether fixed height mode is turned on for tree_view.

tree_view : | a GtkTreeView
Returns : | TRUE if tree_view is in fixed height mode

Since 2.6

gtk_tree_view_set_fixed_height_mode ()

void                gtk_tree_view_set_fixed_height_mode (GtkTreeView *tree_view,
                                                         gboolean enable);

Enables or disables the fixed height mode of tree_view. Fixed height mode speeds up GtkTreeView by assuming that all rows have the same height. Only enable this option if all rows are the same height and all columns are of type GTK_TREE_VIEW_COLUMN_FIXED.

tree_view : | a GtkTreeView
enable : | TRUE to enable fixed height mode

Since 2.6

gtk_tree_view_get_hover_selection ()

gboolean            gtk_tree_view_get_hover_selection   (GtkTreeView *tree_view);

Returns whether hover selection mode is turned on for tree_view.

tree_view : | a GtkTreeView
Returns : | TRUE if tree_view is in hover selection mode

Since 2.6

gtk_tree_view_set_hover_selection ()

void                gtk_tree_view_set_hover_selection   (GtkTreeView *tree_view,
                                                         gboolean hover);

Enables of disables the hover selection mode of tree_view. Hover selection makes the selected row follow the pointer. Currently, this works only for the selection modes GTK_SELECTION_SINGLE and GTK_SELECTION_BROWSE.

tree_view : | a GtkTreeView
hover : | TRUE to enable hover selection mode

Since 2.6

gtk_tree_view_get_hover_expand ()

gboolean            gtk_tree_view_get_hover_expand      (GtkTreeView *tree_view);

Returns whether hover expansion mode is turned on for tree_view.

tree_view : | a GtkTreeView
Returns : | TRUE if tree_view is in hover expansion mode

Since 2.6

gtk_tree_view_set_hover_expand ()

void                gtk_tree_view_set_hover_expand      (GtkTreeView *tree_view,
                                                         gboolean expand);

Enables of disables the hover expansion mode of tree_view. Hover expansion makes rows expand or collaps if the pointer moves over them.

tree_view : | a GtkTreeView
expand : | TRUE to enable hover selection mode

Since 2.6

GtkTreeDestroyCountFunc ()

void                (*GtkTreeDestroyCountFunc)          (GtkTreeView *tree_view,
                                                         GtkTreePath *path,
                                                         gint children,
                                                         gpointer user_data);

tree_view :
path :
children :
user_data :

gtk_tree_view_set_destroy_count_func ()

void                gtk_tree_view_set_destroy_count_func
                                                        (GtkTreeView *tree_view,
                                                         GtkTreeDestroyCountFunc func,
                                                         gpointer data,
                                                         GtkDestroyNotify destroy);

This function should almost never be used. It is meant for private use by ATK for determining the number of visible children that are removed when the user collapses a row, or a row is deleted.

tree_view : | A GtkTreeView
func : | Function to be called when a view row is destroyed, or NULL
data : | User data to be passed to func, or NULL
destroy : | Destroy notifier for data, or NULL

GtkTreeViewRowSeparatorFunc ()

gboolean            (*GtkTreeViewRowSeparatorFunc)      (GtkTreeModel *model,
                                                         GtkTreeIter *iter,
                                                         gpointer data);

Function type for determining whether the row pointed to by iter should be rendered as a separator. A common way to implement this is to have a boolean column in the model, whose values the GtkTreeViewRowSeparatorFunc returns.

model : | the GtkTreeModel
iter : | a GtkTreeIter pointing at a row in model
data : | user data
Returns : | TRUE if the row is a separator

gtk_tree_view_get_row_separator_func ()

GtkTreeViewRowSeparatorFunc gtk_tree_view_get_row_separator_func
                                                        (GtkTreeView *tree_view);

Returns the current row separator function.

tree_view : | a GtkTreeView
Returns : | the current row separator function.

Since 2.6

gtk_tree_view_set_row_separator_func ()

void                gtk_tree_view_set_row_separator_func
                                                        (GtkTreeView *tree_view,
                                                         GtkTreeViewRowSeparatorFunc func,
                                                         gpointer data,
                                                         GtkDestroyNotify destroy);

Sets the row separator function, which is used to determine whether a row should be drawn as a separator. If the row separator function is NULL, no separators are drawn. This is the default value.

tree_view : | a GtkTreeView
func : | a GtkTreeViewRowSeparatorFunc
data : | user data to pass to func, or NULL
destroy : | destroy notifier for data, or NULL

Since 2.6

gtk_tree_view_get_rubber_banding ()

gboolean            gtk_tree_view_get_rubber_banding    (GtkTreeView *tree_view);

Returns whether rubber banding is turned on for tree_view. If the selection mode is GTK_SELECTION_MULTIPLE, rubber banding will allow the user to select multiple rows by dragging the mouse.

tree_view : | a GtkTreeView
Returns : | TRUE if rubber banding in tree_view is enabled.

Since 2.10

gtk_tree_view_set_rubber_banding ()

void                gtk_tree_view_set_rubber_banding    (GtkTreeView *tree_view,
                                                         gboolean enable);

Enables or disables rubber banding in tree_view. If the selection mode is GTK_SELECTION_MULTIPLE, rubber banding will allow the user to select multiple rows by dragging the mouse.

tree_view : | a GtkTreeView
enable : | TRUE to enable rubber banding

Since 2.10

gtk_tree_view_get_enable_tree_lines ()

gboolean            gtk_tree_view_get_enable_tree_lines (GtkTreeView *tree_view);

Returns whether or not tree lines are drawn in tree_view.

tree_view : | a GtkTreeView.
Returns : | TRUE if tree lines are drawn in tree_view, FALSE otherwise.

Since 2.10

gtk_tree_view_set_enable_tree_lines ()

void                gtk_tree_view_set_enable_tree_lines (GtkTreeView *tree_view,
                                                         gboolean enabled);

Sets whether to draw lines interconnecting the expanders in tree_view. This does not have any visible effects for lists.

tree_view : | a GtkTreeView
enabled : | TRUE to enable tree line drawing, FALSE otherwise.

Since 2.10

enum GtkTreeViewGridLines

typedef enum {
  GTK_TREE_VIEW_GRID_LINES_NONE,
  GTK_TREE_VIEW_GRID_LINES_HORIZONTAL,
  GTK_TREE_VIEW_GRID_LINES_VERTICAL,
  GTK_TREE_VIEW_GRID_LINES_BOTH
} GtkTreeViewGridLines;

gtk_tree_view_get_grid_lines ()

GtkTreeViewGridLines gtk_tree_view_get_grid_lines       (GtkTreeView *tree_view);

Returns which grid lines are enabled in tree_view.

tree_view : | a GtkTreeView
Returns : | a GtkTreeViewGridLines value indicating which grid lines are enabled.

Since 2.10

gtk_tree_view_set_grid_lines ()

void                gtk_tree_view_set_grid_lines        (GtkTreeView *tree_view,
                                                         GtkTreeViewGridLines grid_lines);

Sets which grid lines to draw in tree_view.

tree_view : | a GtkTreeView
grid_lines : | a GtkTreeViewGridLines value indicating which grid lines to enable.

Since 2.10

Property Details

The "enable-grid-lines" property

  "enable-grid-lines"        GtkTreeViewGridLines  : Read / Write

Whether grid lines should be drawn in the tree view.

Default value: GTK_TREE_VIEW_GRID_LINES_NONE

The "enable-search" property

  "enable-search"            gboolean              : Read / Write

View allows user to search through columns interactively.

Default value: TRUE

The "enable-tree-lines" property

  "enable-tree-lines"        gboolean              : Read / Write

Whether tree lines should be drawn in the tree view.

Default value: FALSE

The "expander-column" property

  "expander-column"          GtkTreeViewColumn     : Read / Write

Set the column for the expander column.

The "fixed-height-mode" property

  "fixed-height-mode"        gboolean              : Read / Write

Setting the ::fixed-height-mode property to TRUE speeds up GtkTreeView by assuming that all rows have the same height. Only enable this option if all rows are the same height. Please see gtk_tree_view_set_fixed_height_mode() for more information on this option.

Default value: FALSE

Since 2.4

The "hadjustment" property

  "hadjustment"              GtkAdjustment         : Read / Write

Horizontal Adjustment for the widget.

The "headers-clickable" property

  "headers-clickable"        gboolean              : Read / Write

Column headers respond to click events.

Default value: FALSE

The "headers-visible" property

  "headers-visible"          gboolean              : Read / Write

Show the column header buttons.

Default value: TRUE

The "hover-expand" property

  "hover-expand"             gboolean              : Read / Write

Enables of disables the hover expansion mode of tree_view. Hover expansion makes rows expand or collaps if the pointer moves over them.

This mode is primarily indended for treeviews in popups, e.g. in GtkComboBox or GtkEntryCompletion.

Default value: FALSE

Since 2.6

The "hover-selection" property

  "hover-selection"          gboolean              : Read / Write

Enables of disables the hover selection mode of tree_view. Hover selection makes the selected row follow the pointer. Currently, this works only for the selection modes GTK_SELECTION_SINGLE and GTK_SELECTION_BROWSE.

This mode is primarily indended for treeviews in popups, e.g. in GtkComboBox or GtkEntryCompletion.

Default value: FALSE

Since 2.6

The "level-indentation" property

  "level-indentation"        gint                  : Read / Write

Extra indentation for each level.

Allowed values: >= 0

Default value: 0

The "model" property

  "model"                    GtkTreeModel          : Read / Write

The model for the tree view.

The "reorderable" property

  "reorderable"              gboolean              : Read / Write

View is reorderable.

Default value: FALSE

The "rubber-banding" property

  "rubber-banding"           gboolean              : Read / Write

Whether to enable selection of multiple items by dragging the mouse pointer.

Default value: FALSE

The "rules-hint" property

  "rules-hint"               gboolean              : Read / Write

Set a hint to the theme engine to draw rows in alternating colors.

Default value: FALSE

The "search-column" property

  "search-column"            gint                  : Read / Write

Model column to search through when searching through code.

Allowed values: >= -1

Default value: -1

The "show-expanders" property

  "show-expanders"           gboolean              : Read / Write

View has expanders.

Default value: TRUE

The "vadjustment" property

  "vadjustment"              GtkAdjustment         : Read / Write

Vertical Adjustment for the widget.

Style Property Details

The "allow-rules" style property

  "allow-rules"              gboolean              : Read

Allow drawing of alternating color rows.

Default value: TRUE

The "even-row-color" style property

  "even-row-color"           GdkColor              : Read

Color to use for even rows.

The "expander-size" style property

  "expander-size"            gint                  : Read

Size of the expander arrow.

Allowed values: >= 0

Default value: 12

The "grid-line-pattern" style property

  "grid-line-pattern"        gchararray            : Read

Dash pattern used to draw the tree view grid lines.

Default value: "\001\001"

The "grid-line-width" style property

  "grid-line-width"          gint                  : Read

Width, in pixels, of the tree view grid lines.

Allowed values: >= 0

Default value: 1

The "horizontal-separator" style property

  "horizontal-separator"     gint                  : Read

Horizontal space between cells. Must be an even number.

Allowed values: >= 0

Default value: 2

The "indent-expanders" style property

  "indent-expanders"         gboolean              : Read

Make the expanders indented.

Default value: TRUE

The "odd-row-color" style property

  "odd-row-color"            GdkColor              : Read

Color to use for odd rows.

The "row-ending-details" style property

  "row-ending-details"       gboolean              : Read

Enable extended row background theming.

Default value: FALSE

The "tree-line-pattern" style property

  "tree-line-pattern"        gchararray            : Read

Dash pattern used to draw the tree view lines.

Default value: "\001\001"

The "tree-line-width" style property

  "tree-line-width"          gint                  : Read

Width, in pixels, of the tree view lines.

Allowed values: >= 0

Default value: 1

The "vertical-separator" style property

  "vertical-separator"       gint                  : Read

Vertical space between cells. Must be an even number.

Allowed values: >= 0

Default value: 2

Signal Details

The "columns-changed" signal

void                user_function                      (GtkTreeView *tree_view,
                                                        gpointer     user_data)      : Run Last

The number of columns of the treeview has changed.

tree_view : | the object on which the signal is emitted
user_data : | user data set when the signal handler was connected.

The "cursor-changed" signal

void                user_function                      (GtkTreeView *tree_view,
                                                        gpointer     user_data)      : Run Last

The position of the cursor (focused cell) has changed.

tree_view : | the object on which the signal is emitted
user_data : | user data set when the signal handler was connected.

The "expand-collapse-cursor-row" signal

gboolean            user_function                      (GtkTreeView *treeview,
                                                        gboolean     arg1,
                                                        gboolean     arg2,
                                                        gboolean     arg3,
                                                        gpointer     user_data)      : Run Last / Action

treeview : | the object which received the signal.
arg1 : |
arg2 : |
arg3 : |
user_data : | user data set when the signal handler was connected.
Returns : |

The "move-cursor" signal

gboolean            user_function                      (GtkTreeView    *treeview,
                                                        GtkMovementStep arg1,
                                                        gint            arg2,
                                                        gpointer        user_data)      : Run Last / Action

treeview : | the object which received the signal.
arg1 : |
arg2 : |
user_data : | user data set when the signal handler was connected.
Returns : |

The "row-activated" signal

void                user_function                      (GtkTreeView       *tree_view,
                                                        GtkTreePath       *path,
                                                        GtkTreeViewColumn *column,
                                                        gpointer           user_data)      : Run Last / Action

The "row-activated" signal is emitted when the method gtk_tree_view_row_activated() is called or the user double clicks a treeview row. It is also emitted when a non-editable row is selected and one of the keys: Space, Shift+Space, Return or Enter is pressed.

For selection handling refer to the tree widget conceptual overview as well as GtkTreeSelection.

tree_view : | the object on which the signal is emitted
path : | the GtkTreePath for the activated row
column : | the GtkTreeViewColumn in which the activation occurred
user_data : | user data set when the signal handler was connected.

The "row-collapsed" signal

void                user_function                      (GtkTreeView *tree_view,
                                                        GtkTreeIter *iter,
                                                        GtkTreePath *path,
                                                        gpointer     user_data)      : Run Last

The given row has been collapsed (child nodes are hidden).

tree_view : | the object on which the signal is emitted
iter : | the tree iter of the collapsed row
path : | a tree path that points to the row
user_data : | user data set when the signal handler was connected.

The "row-expanded" signal

void                user_function                      (GtkTreeView *tree_view,
                                                        GtkTreeIter *iter,
                                                        GtkTreePath *path,
                                                        gpointer     user_data)      : Run Last

The given row has been expanded (child nodes are shown).

tree_view : | the object on which the signal is emitted
iter : | the tree iter of the expanded row
path : | a tree path that points to the row
user_data : | user data set when the signal handler was connected.

The "select-all" signal

gboolean            user_function                      (GtkTreeView *treeview,
                                                        gpointer     user_data)      : Run Last / Action

treeview : | the object which received the signal.
user_data : | user data set when the signal handler was connected.
Returns : |

The "select-cursor-parent" signal

gboolean            user_function                      (GtkTreeView *treeview,
                                                        gpointer     user_data)      : Run Last / Action

treeview : | the object which received the signal.
user_data : | user data set when the signal handler was connected.
Returns : |

The "select-cursor-row" signal

gboolean            user_function                      (GtkTreeView *treeview,
                                                        gboolean     arg1,
                                                        gpointer     user_data)      : Run Last / Action

treeview : | the object which received the signal.
arg1 : |
user_data : | user data set when the signal handler was connected.
Returns : |

The "set-scroll-adjustments" signal

void                user_function                      (GtkTreeView   *treeview,
                                                        GtkAdjustment *arg1,
                                                        GtkAdjustment *arg2,
                                                        gpointer       user_data)      : Run Last / Action

treeview : | the object which received the signal.
arg1 : |
arg2 : |
user_data : | user data set when the signal handler was connected.

The "start-interactive-search" signal

gboolean            user_function                      (GtkTreeView *treeview,
                                                        gpointer     user_data)      : Run Last / Action

treeview : | the object which received the signal.
user_data : | user data set when the signal handler was connected.
Returns : |

The "test-collapse-row" signal

gboolean            user_function                      (GtkTreeView *tree_view,
                                                        GtkTreeIter *iter,
                                                        GtkTreePath *path,
                                                        gpointer     user_data)      : Run Last

The given row is about to be collapsed (hide its children nodes). Use this signal if you need to control the collapsibility of individual rows.

tree_view : | the object on which the signal is emitted
iter : | the tree iter of the row to collapse
path : | a tree path that points to the row
user_data : | user data set when the signal handler was connected.
Returns : | TRUE to allow expansion, FALSE to reject

The "test-expand-row" signal

gboolean            user_function                      (GtkTreeView *tree_view,
                                                        GtkTreeIter *iter,
                                                        GtkTreePath *path,
                                                        gpointer     user_data)      : Run Last

The given row is about to be expanded (show its children nodes). Use this signal if you need to control the expandability of individual rows.

tree_view : | the object on which the signal is emitted
iter : | the tree iter of the row to expand
path : | a tree path that points to the row
user_data : | user data set when the signal handler was connected.
Returns : | TRUE to allow expansion, FALSE to reject

The "toggle-cursor-row" signal

gboolean            user_function                      (GtkTreeView *treeview,
                                                        gpointer     user_data)      : Run Last / Action

treeview : | the object which received the signal.
user_data : | user data set when the signal handler was connected.
Returns : |

The "unselect-all" signal

gboolean            user_function                      (GtkTreeView *treeview,
                                                        gpointer     user_data)      : Run Last / Action

treeview : | the object which received the signal.
user_data : | user data set when the signal handler was connected.
Returns : |

See Also

GtkTreeViewColumn, GtkTreeSelection, GtkTreeDnd, GtkTreeMode, GtkTreeSortable, GtkTreeModelSort, GtkListStore, GtkTreeStore, GtkCellRenderer, GtkCellEditable, GtkCellRendererPixbuf, GtkCellRendererText, GtkCellRendererToggle


GtkTreeViewColumn

GtkTreeViewColumn — A visible column in a GtkTreeView widget

Synopsis

#include <gtk/gtk.h>

enum                GtkTreeViewColumnSizing;
void                (*GtkTreeCellDataFunc)              (GtkTreeViewColumn *tree_column,
                                                         GtkCellRenderer *cell,
                                                         GtkTreeModel *tree_model,
                                                         GtkTreeIter *iter,
                                                         gpointer data);
                    GtkTreeViewColumn;
GtkTreeViewColumn*  gtk_tree_view_column_new            (void);
GtkTreeViewColumn*  gtk_tree_view_column_new_with_attributes
                                                        (const gchar *title,
                                                         GtkCellRenderer *cell,
                                                         ...);
void                gtk_tree_view_column_pack_start     (GtkTreeViewColumn *tree_column,
                                                         GtkCellRenderer *cell,
                                                         gboolean expand);
void                gtk_tree_view_column_pack_end       (GtkTreeViewColumn *tree_column,
                                                         GtkCellRenderer *cell,
                                                         gboolean expand);
void                gtk_tree_view_column_clear          (GtkTreeViewColumn *tree_column);
GList*              gtk_tree_view_column_get_cell_renderers
                                                        (GtkTreeViewColumn *tree_column);
void                gtk_tree_view_column_add_attribute  (GtkTreeViewColumn *tree_column,
                                                         GtkCellRenderer *cell_renderer,
                                                         const gchar *attribute,
                                                         gint column);
void                gtk_tree_view_column_set_attributes (GtkTreeViewColumn *tree_column,
                                                         GtkCellRenderer *cell_renderer,
                                                         ...);
void                gtk_tree_view_column_set_cell_data_func
                                                        (GtkTreeViewColumn *tree_column,
                                                         GtkCellRenderer *cell_renderer,
                                                         GtkTreeCellDataFunc func,
                                                         gpointer func_data,
                                                         GtkDestroyNotify destroy);
void                gtk_tree_view_column_clear_attributes
                                                        (GtkTreeViewColumn *tree_column,
                                                         GtkCellRenderer *cell_renderer);
void                gtk_tree_view_column_set_spacing    (GtkTreeViewColumn *tree_column,
                                                         gint spacing);
gint                gtk_tree_view_column_get_spacing    (GtkTreeViewColumn *tree_column);
void                gtk_tree_view_column_set_visible    (GtkTreeViewColumn *tree_column,
                                                         gboolean visible);
gboolean            gtk_tree_view_column_get_visible    (GtkTreeViewColumn *tree_column);
void                gtk_tree_view_column_set_resizable  (GtkTreeViewColumn *tree_column,
                                                         gboolean resizable);
gboolean            gtk_tree_view_column_get_resizable  (GtkTreeViewColumn *tree_column);
void                gtk_tree_view_column_set_sizing     (GtkTreeViewColumn *tree_column,
                                                         GtkTreeViewColumnSizing type);
GtkTreeViewColumnSizing gtk_tree_view_column_get_sizing (GtkTreeViewColumn *tree_column);
gint                gtk_tree_view_column_get_width      (GtkTreeViewColumn *tree_column);
gint                gtk_tree_view_column_get_fixed_width
                                                        (GtkTreeViewColumn *tree_column);
void                gtk_tree_view_column_set_fixed_width
                                                        (GtkTreeViewColumn *tree_column,
                                                         gint fixed_width);
void                gtk_tree_view_column_set_min_width  (GtkTreeViewColumn *tree_column,
                                                         gint min_width);
gint                gtk_tree_view_column_get_min_width  (GtkTreeViewColumn *tree_column);
void                gtk_tree_view_column_set_max_width  (GtkTreeViewColumn *tree_column,
                                                         gint max_width);
gint                gtk_tree_view_column_get_max_width  (GtkTreeViewColumn *tree_column);
void                gtk_tree_view_column_clicked        (GtkTreeViewColumn *tree_column);
void                gtk_tree_view_column_set_title      (GtkTreeViewColumn *tree_column,
                                                         const gchar *title);
const gchar*        gtk_tree_view_column_get_title      (GtkTreeViewColumn *tree_column);
void                gtk_tree_view_column_set_expand     (GtkTreeViewColumn *tree_column,
                                                         gboolean expand);
gboolean            gtk_tree_view_column_get_expand     (GtkTreeViewColumn *tree_column);
void                gtk_tree_view_column_set_clickable  (GtkTreeViewColumn *tree_column,
                                                         gboolean clickable);
gboolean            gtk_tree_view_column_get_clickable  (GtkTreeViewColumn *tree_column);
void                gtk_tree_view_column_set_widget     (GtkTreeViewColumn *tree_column,
                                                         GtkWidget *widget);
GtkWidget*          gtk_tree_view_column_get_widget     (GtkTreeViewColumn *tree_column);
void                gtk_tree_view_column_set_alignment  (GtkTreeViewColumn *tree_column,
                                                         gfloat xalign);
gfloat              gtk_tree_view_column_get_alignment  (GtkTreeViewColumn *tree_column);
void                gtk_tree_view_column_set_reorderable
                                                        (GtkTreeViewColumn *tree_column,
                                                         gboolean reorderable);
gboolean            gtk_tree_view_column_get_reorderable
                                                        (GtkTreeViewColumn *tree_column);
void                gtk_tree_view_column_set_sort_column_id
                                                        (GtkTreeViewColumn *tree_column,
                                                         gint sort_column_id);
gint                gtk_tree_view_column_get_sort_column_id
                                                        (GtkTreeViewColumn *tree_column);
void                gtk_tree_view_column_set_sort_indicator
                                                        (GtkTreeViewColumn *tree_column,
                                                         gboolean setting);
gboolean            gtk_tree_view_column_get_sort_indicator
                                                        (GtkTreeViewColumn *tree_column);
void                gtk_tree_view_column_set_sort_order (GtkTreeViewColumn *tree_column,
                                                         GtkSortType order);
GtkSortType         gtk_tree_view_column_get_sort_order (GtkTreeViewColumn *tree_column);
void                gtk_tree_view_column_cell_set_cell_data
                                                        (GtkTreeViewColumn *tree_column,
                                                         GtkTreeModel *tree_model,
                                                         GtkTreeIter *iter,
                                                         gboolean is_expander,
                                                         gboolean is_expanded);
void                gtk_tree_view_column_cell_get_size  (GtkTreeViewColumn *tree_column,
                                                         GdkRectangle *cell_area,
                                                         gint *x_offset,
                                                         gint *y_offset,
                                                         gint *width,
                                                         gint *height);
gboolean            gtk_tree_view_column_cell_get_position
                                                        (GtkTreeViewColumn *tree_column,
                                                         GtkCellRenderer *cell_renderer,
                                                         gint *start_pos,
                                                         gint *width);
gboolean            gtk_tree_view_column_cell_is_visible
                                                        (GtkTreeViewColumn *tree_column);
void                gtk_tree_view_column_focus_cell     (GtkTreeViewColumn *tree_column,
                                                         GtkCellRenderer *cell);
void                gtk_tree_view_column_queue_resize   (GtkTreeViewColumn *tree_column);

Object Hierarchy

  GObject
   +----GInitiallyUnowned
         +----GtkObject
               +----GtkTreeViewColumn

Implemented Interfaces

GtkTreeViewColumn implements GtkCellLayout.

Properties

  "alignment"                gfloat                : Read / Write
  "clickable"                gboolean              : Read / Write
  "expand"                   gboolean              : Read / Write
  "fixed-width"              gint                  : Read / Write
  "max-width"                gint                  : Read / Write
  "min-width"                gint                  : Read / Write
  "reorderable"              gboolean              : Read / Write
  "resizable"                gboolean              : Read / Write
  "sizing"                   GtkTreeViewColumnSizing  : Read / Write
  "sort-indicator"           gboolean              : Read / Write
  "sort-order"               GtkSortType           : Read / Write
  "spacing"                  gint                  : Read / Write
  "title"                    gchararray            : Read / Write
  "visible"                  gboolean              : Read / Write
  "widget"                   GtkWidget             : Read / Write
  "width"                    gint                  : Read

Signals

  "clicked"                                        : Run Last

Description

The GtkTreeViewColumn object represents a visible column in a GtkTreeView widget. It allows to set properties of the column header, and functions as a holding pen for the cell renderers which determine how the data in the column is displayed.

Please refer to the tree widget conceptual overview for an overview of all the objects and data types related to the tree widget and how they work together.

Details

enum GtkTreeViewColumnSizing

typedef enum
{
  GTK_TREE_VIEW_COLUMN_GROW_ONLY,
  GTK_TREE_VIEW_COLUMN_AUTOSIZE,
  GTK_TREE_VIEW_COLUMN_FIXED
} GtkTreeViewColumnSizing;

The sizing method the column uses to determine its width. Please note that GTK_TREE_VIEW_COLUMN_AUTOSIZE are inefficient for large views, and can make columns appear choppy.

GTK_TREE_VIEW_COLUMN_GROW_ONLY | Columns only get bigger in reaction to changes in the model
GTK_TREE_VIEW_COLUMN_AUTOSIZE | Columns resize to be the optimal size everytime the model changes.
GTK_TREE_VIEW_COLUMN_FIXED | Columns are a fixed numbers of pixels wide.

GtkTreeCellDataFunc ()

void                (*GtkTreeCellDataFunc)              (GtkTreeViewColumn *tree_column,
                                                         GtkCellRenderer *cell,
                                                         GtkTreeModel *tree_model,
                                                         GtkTreeIter *iter,
                                                         gpointer data);

A function to set the properties of a cell instead of just using the straight mapping between the cell and the model. This is useful for customizing the cell renderer. For example, a function might get an integer from the tree_model, and render it to the "text" attribute of "cell" by converting it to its written equivilent. This is set by calling gtk_tree_view_column_set_cell_data_func()

tree_column : | A GtkTreeColumn
cell : | The GtkCellRenderer that is being rendered by tree_column
tree_model : | The GtkTreeModel being rendered
iter : | A GtkTreeIter of the current row rendered
data : | user data

GtkTreeViewColumn

typedef struct _GtkTreeViewColumn GtkTreeViewColumn;

gtk_tree_view_column_new ()

GtkTreeViewColumn*  gtk_tree_view_column_new            (void);

Creates a new GtkTreeViewColumn.

Returns : A newly created GtkTreeViewColumn.

gtk_tree_view_column_new_with_attributes ()

GtkTreeViewColumn*  gtk_tree_view_column_new_with_attributes
                                                        (const gchar *title,
                                                         GtkCellRenderer *cell,
                                                         ...);

Creates a new GtkTreeViewColumn with a number of default values.  This is
equivalent to calling gtk_tree_view_column_set_title(),
gtk_tree_view_column_pack_start(), and
gtk_tree_view_column_set_attributes() on the newly created GtkTreeViewColumn.

Here's a simple example:

 enum { TEXT_COLUMN, COLOR_COLUMN, N_COLUMNS };
 ...
 {
   GtkTreeViewColumn *column;
   GtkCellRenderer   *renderer = gtk_cell_renderer_text_new ();

   column = gtk_tree_view_column_new_with_attributes ("Title",
                                                      renderer,
                                                      "text", TEXT_COLUMN,
                                                      "foreground", COLOR_COLUMN,
                                                      NULL);
 }

title : | The title to set the header to.
cell : | The GtkCellRenderer.
... : | A NULL-terminated list of attributes.
Returns : | A newly created GtkTreeViewColumn.

gtk_tree_view_column_pack_start ()

void                gtk_tree_view_column_pack_start     (GtkTreeViewColumn *tree_column,
                                                         GtkCellRenderer *cell,
                                                         gboolean expand);

Packs the cell into the beginning of the column. If expand is FALSE, then the cell is allocated no more space than it needs. Any unused space is divided evenly between cells for which expand is TRUE.

tree_column : | A GtkTreeViewColumn.
cell : | The GtkCellRenderer.
expand : | TRUE if cell is to be given extra space allocated to tree_column.

gtk_tree_view_column_pack_end ()

void                gtk_tree_view_column_pack_end       (GtkTreeViewColumn *tree_column,
                                                         GtkCellRenderer *cell,
                                                         gboolean expand);

Adds the cell to end of the column. If expand is FALSE, then the cell is allocated no more space than it needs. Any unused space is divided evenly between cells for which expand is TRUE.

tree_column : | A GtkTreeViewColumn.
cell : | The GtkCellRenderer.
expand : | TRUE if cell is to be given extra space allocated to tree_column.

gtk_tree_view_column_clear ()

void                gtk_tree_view_column_clear          (GtkTreeViewColumn *tree_column);

Unsets all the mappings on all renderers on the tree_column.

tree_column : A GtkTreeViewColumn

gtk_tree_view_column_get_cell_renderers ()

GList*              gtk_tree_view_column_get_cell_renderers
                                                        (GtkTreeViewColumn *tree_column);

Returns a newly-allocated GList of all the cell renderers in the column, in no particular order. The list must be freed with g_list_free().

tree_column : | A GtkTreeViewColumn
Returns : | A list of GtkCellRenderers

gtk_tree_view_column_add_attribute ()

void                gtk_tree_view_column_add_attribute  (GtkTreeViewColumn *tree_column,
                                                         GtkCellRenderer *cell_renderer,
                                                         const gchar *attribute,
                                                         gint column);

Adds an attribute mapping to the list in tree_column. The column is the column of the model to get a value from, and the attribute is the parameter on cell_renderer to be set from the value. So for example if column 2 of the model contains strings, you could have the "text" attribute of a GtkCellRendererText get its values from column 2.

tree_column : | A GtkTreeViewColumn.
cell_renderer : | the GtkCellRenderer to set attributes on
attribute : | An attribute on the renderer
column : | The column position on the model to get the attribute from.

gtk_tree_view_column_set_attributes ()

void                gtk_tree_view_column_set_attributes (GtkTreeViewColumn *tree_column,
                                                         GtkCellRenderer *cell_renderer,
                                                         ...);

Sets the attributes in the list as the attributes of tree_column. The attributes should be in attribute/column order, as in gtk_tree_view_column_add_attribute(). All existing attributes are removed, and replaced with the new attributes.

tree_column : | A GtkTreeViewColumn.
cell_renderer : | the GtkCellRenderer we're setting the attributes of
... : | A NULL-terminated list of attributes.

gtk_tree_view_column_set_cell_data_func ()

void                gtk_tree_view_column_set_cell_data_func
                                                        (GtkTreeViewColumn *tree_column,
                                                         GtkCellRenderer *cell_renderer,
                                                         GtkTreeCellDataFunc func,
                                                         gpointer func_data,
                                                         GtkDestroyNotify destroy);

Sets the GtkTreeViewColumnFunc to use for the column. This function is used instead of the standard attributes mapping for setting the column value, and should set the value of tree_column's cell renderer as appropriate. func may be NULL to remove an older one.

tree_column : | A GtkTreeViewColumn
cell_renderer : | A GtkCellRenderer
func : | The GtkTreeViewColumnFunc to use.
func_data : | The user data for func.
destroy : | The destroy notification for func_data

gtk_tree_view_column_clear_attributes ()

void                gtk_tree_view_column_clear_attributes
                                                        (GtkTreeViewColumn *tree_column,
                                                         GtkCellRenderer *cell_renderer);

Clears all existing attributes previously set with gtk_tree_view_column_set_attributes().

tree_column : | a GtkTreeViewColumn
cell_renderer : | a GtkCellRenderer to clear the attribute mapping on.

gtk_tree_view_column_set_spacing ()

void                gtk_tree_view_column_set_spacing    (GtkTreeViewColumn *tree_column,
                                                         gint spacing);

Sets the spacing field of tree_column, which is the number of pixels to place between cell renderers packed into it.

tree_column : | A GtkTreeViewColumn.
spacing : | distance between cell renderers in pixels.

gtk_tree_view_column_get_spacing ()

gint                gtk_tree_view_column_get_spacing    (GtkTreeViewColumn *tree_column);

Returns the spacing of tree_column.

tree_column : | A GtkTreeViewColumn.
Returns : | the spacing of tree_column.

gtk_tree_view_column_set_visible ()

void                gtk_tree_view_column_set_visible    (GtkTreeViewColumn *tree_column,
                                                         gboolean visible);

Sets the visibility of tree_column.

tree_column : | A GtkTreeViewColumn.
visible : | TRUE if the tree_column is visible.

gtk_tree_view_column_get_visible ()

gboolean            gtk_tree_view_column_get_visible    (GtkTreeViewColumn *tree_column);

Returns TRUE if tree_column is visible.

tree_column : | A GtkTreeViewColumn.
Returns : | whether the column is visible or not. If it is visible, then the tree will show the column.

gtk_tree_view_column_set_resizable ()

void                gtk_tree_view_column_set_resizable  (GtkTreeViewColumn *tree_column,
                                                         gboolean resizable);

If resizable is TRUE, then the user can explicitly resize the column by grabbing the outer edge of the column button. If resizable is TRUE and sizing mode of the column is GTK_TREE_VIEW_COLUMN_AUTOSIZE, then the sizing mode is changed to GTK_TREE_VIEW_COLUMN_GROW_ONLY.

tree_column : | A GtkTreeViewColumn
resizable : | TRUE, if the column can be resized

gtk_tree_view_column_get_resizable ()

gboolean            gtk_tree_view_column_get_resizable  (GtkTreeViewColumn *tree_column);

Returns TRUE if the tree_column can be resized by the end user.

tree_column : | A GtkTreeViewColumn
Returns : | TRUE, if the tree_column can be resized.

gtk_tree_view_column_set_sizing ()

void                gtk_tree_view_column_set_sizing     (GtkTreeViewColumn *tree_column,
                                                         GtkTreeViewColumnSizing type);

Sets the growth behavior of tree_column to type.

tree_column : | A GtkTreeViewColumn.
type : | The GtkTreeViewColumnSizing.

gtk_tree_view_column_get_sizing ()

GtkTreeViewColumnSizing gtk_tree_view_column_get_sizing (GtkTreeViewColumn *tree_column);

Returns the current type of tree_column.

tree_column : | A GtkTreeViewColumn.
Returns : | The type of tree_column.

gtk_tree_view_column_get_width ()

gint                gtk_tree_view_column_get_width      (GtkTreeViewColumn *tree_column);

Returns the current size of tree_column in pixels.

tree_column : | A GtkTreeViewColumn.
Returns : | The current width of tree_column.

gtk_tree_view_column_get_fixed_width ()

gint                gtk_tree_view_column_get_fixed_width
                                                        (GtkTreeViewColumn *tree_column);

Gets the fixed width of the column. This value is only meaning may not be the actual width of the column on the screen, just what is requested.

tree_column : | a GtkTreeViewColumn
Returns : | the fixed width of the column

gtk_tree_view_column_set_fixed_width ()

void                gtk_tree_view_column_set_fixed_width
                                                        (GtkTreeViewColumn *tree_column,
                                                         gint fixed_width);

Sets the size of the column in pixels. This is meaningful only if the sizing type is GTK_TREE_VIEW_COLUMN_FIXED. The size of the column is clamped to the min/max width for the column. Please note that the min/max width of the column doesn't actually affect the "fixed_width" property of the widget, just the actual size when displayed.

tree_column : | A GtkTreeViewColumn.
fixed_width : | The size to set tree_column to. Must be greater than 0.

gtk_tree_view_column_set_min_width ()

void                gtk_tree_view_column_set_min_width  (GtkTreeViewColumn *tree_column,
                                                         gint min_width);

Sets the minimum width of the tree_column. If min_width is -1, then the minimum width is unset.

tree_column : | A GtkTreeViewColumn.
min_width : | The minimum width of the column in pixels, or -1.

gtk_tree_view_column_get_min_width ()

gint                gtk_tree_view_column_get_min_width  (GtkTreeViewColumn *tree_column);

Returns the minimum width in pixels of the tree_column, or -1 if no minimum width is set.

tree_column : | A GtkTreeViewColumn.
Returns : | The minimum width of the tree_column.

gtk_tree_view_column_set_max_width ()

void                gtk_tree_view_column_set_max_width  (GtkTreeViewColumn *tree_column,
                                                         gint max_width);

Sets the maximum width of the tree_column. If max_width is -1, then the maximum width is unset. Note, the column can actually be wider than max width if it's the last column in a view. In this case, the column expands to fill any extra space.

tree_column : | A GtkTreeViewColumn.
max_width : | The maximum width of the column in pixels, or -1.

gtk_tree_view_column_get_max_width ()

gint                gtk_tree_view_column_get_max_width  (GtkTreeViewColumn *tree_column);

Returns the maximum width in pixels of the tree_column, or -1 if no maximum width is set.

tree_column : | A GtkTreeViewColumn.
Returns : | The maximum width of the tree_column.

gtk_tree_view_column_clicked ()

void                gtk_tree_view_column_clicked        (GtkTreeViewColumn *tree_column);

Emits the "clicked" signal on the column. This function will only work if tree_column is clickable.

tree_column : a GtkTreeViewColumn

gtk_tree_view_column_set_title ()

void                gtk_tree_view_column_set_title      (GtkTreeViewColumn *tree_column,
                                                         const gchar *title);

Sets the title of the tree_column. If a custom widget has been set, then this value is ignored.

tree_column : | A GtkTreeViewColumn.
title : | The title of the tree_column.

gtk_tree_view_column_get_title ()

const gchar*        gtk_tree_view_column_get_title      (GtkTreeViewColumn *tree_column);

Returns the title of the widget.

tree_column : | A GtkTreeViewColumn.
Returns : | the title of the column. This string should not be modified or freed.

gtk_tree_view_column_set_expand ()

void                gtk_tree_view_column_set_expand     (GtkTreeViewColumn *tree_column,
                                                         gboolean expand);

Sets the column to take available extra space. This space is shared equally amongst all columns that have the expand set to TRUE. If no column has this option set, then the last column gets all extra space. By default, every column is created with this FALSE.

tree_column : | A GtkTreeViewColumn
expand : | TRUE if the column should take available extra space, FALSE if not

Since 2.4

gtk_tree_view_column_get_expand ()

gboolean            gtk_tree_view_column_get_expand     (GtkTreeViewColumn *tree_column);

Return TRUE if the column expands to take any available space.

tree_column : | a GtkTreeViewColumn
Returns : | TRUE, if the column expands

Since 2.4

gtk_tree_view_column_set_clickable ()

void                gtk_tree_view_column_set_clickable  (GtkTreeViewColumn *tree_column,
                                                         gboolean clickable);

Sets the header to be active if active is TRUE. When the header is active, then it can take keyboard focus, and can be clicked.

tree_column : | A GtkTreeViewColumn.
clickable : | TRUE if the header is active.

gtk_tree_view_column_get_clickable ()

gboolean            gtk_tree_view_column_get_clickable  (GtkTreeViewColumn *tree_column);

Returns TRUE if the user can click on the header for the column.

tree_column : | a GtkTreeViewColumn
Returns : | TRUE if user can click the column header.

gtk_tree_view_column_set_widget ()

void                gtk_tree_view_column_set_widget     (GtkTreeViewColumn *tree_column,
                                                         GtkWidget *widget);

Sets the widget in the header to be widget. If widget is NULL, then the header button is set with a GtkLabel set to the title of tree_column.

tree_column : | A GtkTreeViewColumn.
widget : | A child GtkWidget, or NULL.

gtk_tree_view_column_get_widget ()

GtkWidget*          gtk_tree_view_column_get_widget     (GtkTreeViewColumn *tree_column);

Returns the GtkWidget in the button on the column header. If a custom widget has not been set then NULL is returned.

tree_column : | A GtkTreeViewColumn.
Returns : | The GtkWidget in the column header, or NULL

gtk_tree_view_column_set_alignment ()

void                gtk_tree_view_column_set_alignment  (GtkTreeViewColumn *tree_column,
                                                         gfloat xalign);

Sets the alignment of the title or custom widget inside the column header. The alignment determines its location inside the button -- 0.0 for left, 0.5 for center, 1.0 for right.

tree_column : | A GtkTreeViewColumn.
xalign : | The alignment, which is between [0.0 and 1.0] inclusive.

gtk_tree_view_column_get_alignment ()

gfloat              gtk_tree_view_column_get_alignment  (GtkTreeViewColumn *tree_column);

Returns the current x alignment of tree_column. This value can range between 0.0 and 1.0.

tree_column : | A GtkTreeViewColumn.
Returns : | The current alignent of tree_column.

gtk_tree_view_column_set_reorderable ()

void                gtk_tree_view_column_set_reorderable
                                                        (GtkTreeViewColumn *tree_column,
                                                         gboolean reorderable);

If reorderable is TRUE, then the column can be reordered by the end user dragging the header.

tree_column : | A GtkTreeViewColumn
reorderable : | TRUE, if the column can be reordered.

gtk_tree_view_column_get_reorderable ()

gboolean            gtk_tree_view_column_get_reorderable
                                                        (GtkTreeViewColumn *tree_column);

Returns TRUE if the tree_column can be reordered by the user.

tree_column : | A GtkTreeViewColumn
Returns : | TRUE if the tree_column can be reordered by the user.

gtk_tree_view_column_set_sort_column_id ()

void                gtk_tree_view_column_set_sort_column_id
                                                        (GtkTreeViewColumn *tree_column,
                                                         gint sort_column_id);

Sets the logical sort_column_id that this column sorts on when this column is selected for sorting. Doing so makes the column header clickable.

tree_column : | a GtkTreeViewColumn
sort_column_id : | The sort_column_id of the model to sort on.

gtk_tree_view_column_get_sort_column_id ()

gint                gtk_tree_view_column_get_sort_column_id
                                                        (GtkTreeViewColumn *tree_column);

Gets the logical sort_column_id that the model sorts on when this column is selected for sorting. See gtk_tree_view_column_set_sort_column_id().

tree_column : | a GtkTreeViewColumn
Returns : | the current sort_column_id for this column, or -1 if this column can't be used for sorting.

gtk_tree_view_column_set_sort_indicator ()

void                gtk_tree_view_column_set_sort_indicator
                                                        (GtkTreeViewColumn *tree_column,
                                                         gboolean setting);

Call this function with a setting of TRUE to display an arrow in the header button indicating the column is sorted. Call gtk_tree_view_column_set_sort_order() to change the direction of the arrow.

tree_column : | a GtkTreeViewColumn
setting : | TRUE to display an indicator that the column is sorted

gtk_tree_view_column_get_sort_indicator ()

gboolean            gtk_tree_view_column_get_sort_indicator
                                                        (GtkTreeViewColumn *tree_column);

Gets the value set by gtk_tree_view_column_set_sort_indicator().

tree_column : | a GtkTreeViewColumn
Returns : | whether the sort indicator arrow is displayed

gtk_tree_view_column_set_sort_order ()

void                gtk_tree_view_column_set_sort_order (GtkTreeViewColumn *tree_column,
                                                         GtkSortType order);

Changes the appearance of the sort indicator.

This does not actually sort the model. Use gtk_tree_view_column_set_sort_column_id() if you want automatic sorting support. This function is primarily for custom sorting behavior, and should be used in conjunction with gtk_tree_sortable_set_sort_column() to do that. For custom models, the mechanism will vary.

The sort indicator changes direction to indicate normal sort or reverse sort. Note that you must have the sort indicator enabled to see anything when calling this function; see gtk_tree_view_column_set_sort_indicator().

tree_column : | a GtkTreeViewColumn
order : | sort order that the sort indicator should indicate

gtk_tree_view_column_get_sort_order ()

GtkSortType         gtk_tree_view_column_get_sort_order (GtkTreeViewColumn *tree_column);

Gets the value set by gtk_tree_view_column_set_sort_order().

tree_column : | a GtkTreeViewColumn
Returns : | the sort order the sort indicator is indicating

gtk_tree_view_column_cell_set_cell_data ()

void                gtk_tree_view_column_cell_set_cell_data
                                                        (GtkTreeViewColumn *tree_column,
                                                         GtkTreeModel *tree_model,
                                                         GtkTreeIter *iter,
                                                         gboolean is_expander,
                                                         gboolean is_expanded);

Sets the cell renderer based on the tree_model and iter. That is, for every attribute mapping in tree_column, it will get a value from the set column on the iter, and use that value to set the attribute on the cell renderer. This is used primarily by the GtkTreeView.

tree_column : | A GtkTreeViewColumn.
tree_model : | The GtkTreeModel to to get the cell renderers attributes from.
iter : | The GtkTreeIter to to get the cell renderer's attributes from.
is_expander : | TRUE, if the row has children
is_expanded : | TRUE, if the row has visible children

gtk_tree_view_column_cell_get_size ()

void                gtk_tree_view_column_cell_get_size  (GtkTreeViewColumn *tree_column,
                                                         GdkRectangle *cell_area,
                                                         gint *x_offset,
                                                         gint *y_offset,
                                                         gint *width,
                                                         gint *height);

Obtains the width and height needed to render the column. This is used primarily by the GtkTreeView.

tree_column : | A GtkTreeViewColumn.
cell_area : | The area a cell in the column will be allocated, or NULL
x_offset : | location to return x offset of a cell relative to cell_area, or NULL
y_offset : | location to return y offset of a cell relative to cell_area, or NULL
width : | location to return width needed to render a cell, or NULL
height : | location to return height needed to render a cell, or NULL

gtk_tree_view_column_cell_get_position ()

gboolean            gtk_tree_view_column_cell_get_position
                                                        (GtkTreeViewColumn *tree_column,
                                                         GtkCellRenderer *cell_renderer,
                                                         gint *start_pos,
                                                         gint *width);

Obtains the horizontal position and size of a cell in a column. If the cell is not found in the column, start_pos and width are not changed and FALSE is returned.

tree_column : | a GtkTreeViewColumn
cell_renderer : | a GtkCellRenderer
start_pos : | return location for the horizontal position of cell within tree_column, may be NULL
width : | return location for the width of cell, may be NULL
Returns : | TRUE if cell belongs to tree_column.

gtk_tree_view_column_cell_is_visible ()

gboolean            gtk_tree_view_column_cell_is_visible
                                                        (GtkTreeViewColumn *tree_column);

Returns TRUE if any of the cells packed into the tree_column are visible. For this to be meaningful, you must first initialize the cells with gtk_tree_view_column_cell_set_cell_data()

tree_column : | A GtkTreeViewColumn
Returns : | TRUE, if any of the cells packed into the tree_column are currently visible

gtk_tree_view_column_focus_cell ()

void                gtk_tree_view_column_focus_cell     (GtkTreeViewColumn *tree_column,
                                                         GtkCellRenderer *cell);

Sets the current keyboard focus to be at cell, if the column contains 2 or more editable and activatable cells.

tree_column : | A GtkTreeViewColumn
cell : | A GtkCellRenderer

Since 2.2

gtk_tree_view_column_queue_resize ()

void                gtk_tree_view_column_queue_resize   (GtkTreeViewColumn *tree_column);

Flags the column, and the cell renderers added to this column, to have their sizes renegotiated.

tree_column : A GtkTreeViewColumn

Since 2.8

Property Details

The "alignment" property

  "alignment"                gfloat                : Read / Write

X Alignment of the column header text or widget.

Allowed values: [0,1]

Default value: 0

The "clickable" property

  "clickable"                gboolean              : Read / Write

Whether the header can be clicked.

Default value: FALSE

The "expand" property

  "expand"                   gboolean              : Read / Write

Column gets share of extra width allocated to the widget.

Default value: FALSE

The "fixed-width" property

  "fixed-width"              gint                  : Read / Write

Current fixed width of the column.

Allowed values: >= 1

Default value: 1

The "max-width" property

  "max-width"                gint                  : Read / Write

Maximum allowed width of the column.

Allowed values: >= -1

Default value: -1

The "min-width" property

  "min-width"                gint                  : Read / Write

Minimum allowed width of the column.

Allowed values: >= -1

Default value: -1

The "reorderable" property

  "reorderable"              gboolean              : Read / Write

Whether the column can be reordered around the headers.

Default value: FALSE

The "resizable" property

  "resizable"                gboolean              : Read / Write

Column is user-resizable.

Default value: FALSE

The "sizing" property

  "sizing"                   GtkTreeViewColumnSizing  : Read / Write

Resize mode of the column.

Default value: GTK_TREE_VIEW_COLUMN_GROW_ONLY

The "sort-indicator" property

  "sort-indicator"           gboolean              : Read / Write

Whether to show a sort indicator.

Default value: FALSE

The "sort-order" property

  "sort-order"               GtkSortType           : Read / Write

Sort direction the sort indicator should indicate.

Default value: GTK_SORT_ASCENDING

The "spacing" property

  "spacing"                  gint                  : Read / Write

Space which is inserted between cells.

Allowed values: >= 0

Default value: 0

The "title" property

  "title"                    gchararray            : Read / Write

Title to appear in column header.

Default value: ""

The "visible" property

  "visible"                  gboolean              : Read / Write

Whether to display the column.

Default value: TRUE

The "widget" property

  "widget"                   GtkWidget             : Read / Write

Widget to put in column header button instead of column title.

The "width" property

  "width"                    gint                  : Read

Current width of the column.

Allowed values: >= 0

Default value: 0

Signal Details

The "clicked" signal

void                user_function                      (GtkTreeViewColumn *treeviewcolumn,
                                                        gpointer           user_data)           : Run Last

treeviewcolumn : | the object which received the signal.
user_data : | user data set when the signal handler was connected.

See Also

GtkTreeView, GtkTreeSelection, GtkTreeDnd, GtkTreeMode, GtkTreeSortable, GtkTreeModelSort, GtkListStore, GtkTreeStore, GtkCellRenderer, GtkCellEditable, GtkCellRendererPixbuf, GtkCellRendererText, GtkCellRendererToggle


GtkUIManager

GtkUIManager — Constructing menus and toolbars from an XML description

Synopsis

#include <gtk/gtk.h>

                    GtkUIManager;
GtkUIManager*       gtk_ui_manager_new                  (void);
void                gtk_ui_manager_set_add_tearoffs     (GtkUIManager *self,
                                                         gboolean add_tearoffs);
gboolean            gtk_ui_manager_get_add_tearoffs     (GtkUIManager *self);
void                gtk_ui_manager_insert_action_group  (GtkUIManager *self,
                                                         GtkActionGroup *action_group,
                                                         gint pos);
void                gtk_ui_manager_remove_action_group  (GtkUIManager *self,
                                                         GtkActionGroup *action_group);
GList*              gtk_ui_manager_get_action_groups    (GtkUIManager *self);
GtkAccelGroup*      gtk_ui_manager_get_accel_group      (GtkUIManager *self);
GtkWidget*          gtk_ui_manager_get_widget           (GtkUIManager *self,
                                                         const gchar *path);
GSList*             gtk_ui_manager_get_toplevels        (GtkUIManager *self,
                                                         GtkUIManagerItemType types);
GtkAction*          gtk_ui_manager_get_action           (GtkUIManager *self,
                                                         const gchar *path);
guint               gtk_ui_manager_add_ui_from_string   (GtkUIManager *self,
                                                         const gchar *buffer,
                                                         gssize length,
                                                         GError **error);
guint               gtk_ui_manager_add_ui_from_file     (GtkUIManager *self,
                                                         const gchar *filename,
                                                         GError **error);
guint               gtk_ui_manager_new_merge_id         (GtkUIManager *self);
enum                GtkUIManagerItemType;
void                gtk_ui_manager_add_ui               (GtkUIManager *self,
                                                         guint merge_id,
                                                         const gchar *path,
                                                         const gchar *name,
                                                         const gchar *action,
                                                         GtkUIManagerItemType type,
                                                         gboolean top);
void                gtk_ui_manager_remove_ui            (GtkUIManager *self,
                                                         guint merge_id);
gchar*              gtk_ui_manager_get_ui               (GtkUIManager *self);
void                gtk_ui_manager_ensure_update        (GtkUIManager *self);

Object Hierarchy

  GObject
   +----GtkUIManager

Properties

  "add-tearoffs"             gboolean              : Read / Write
  "ui"                       gchararray            : Read

Signals

  "actions-changed"                                : Run First / No Recursion
  "add-widget"                                     : Run First / No Recursion
  "connect-proxy"                                  : Run First / No Recursion
  "disconnect-proxy"                               : Run First / No Recursion
  "post-activate"                                  : Run First / No Recursion
  "pre-activate"                                   : Run First / No Recursion

Description

A GtkUIManager constructs a user interface (menus and toolbars) from one or more UI definitions, which reference actions from one or more action groups.

UI Definitions

The UI definitions are specified in an XML format which can be roughly described by the following DTD.

<!ELEMENT ui          (menubar|toolbar|popup|accelerator)* >
<!ELEMENT menubar     (menuitem|separator|placeholder|menu)* >
<!ELEMENT menu        (menuitem|separator|placeholder|menu)* >
<!ELEMENT popup       (menuitem|separator|placeholder|menu)* >
<!ELEMENT toolbar     (toolitem|separator|placeholder)* >
<!ELEMENT placeholder (menuitem|toolitem|separator|placeholder|menu)* >
<!ELEMENT menuitem     EMPTY >
<!ELEMENT toolitem     (menu?) >
<!ELEMENT separator    EMPTY >
<!ELEMENT accelerator  EMPTY >
<!ATTLIST menubar      name                  #IMPLIED
                       action                #IMPLIED >
<!ATTLIST toolbar      name                  #IMPLIED
                       action                #IMPLIED >
<!ATTLIST popup        name                  #IMPLIED
                       action                #IMPLIED >
<!ATTLIST placeholder  name                  #IMPLIED
                       action                #IMPLIED >
<!ATTLIST separator    name                  #IMPLIED
                       action                #IMPLIED
                       expand   (true|false) #IMPLIED >
<!ATTLIST menu         name                  #IMPLIED
                       action                #REQUIRED
                       position (top|bot)    #IMPLIED >
<!ATTLIST menuitem     name                  #IMPLIED
                       action                #REQUIRED
                       position (top|bot)    #IMPLIED >
<!ATTLIST toolitem     name                  #IMPLIED
                       action                #REQUIRED
                       position (top|bot)    #IMPLIED >
<!ATTLIST accelerator  name                  #IMPLIED
                       action                #REQUIRED >

There are some additional restrictions beyond those specified in the DTD, e.g. every toolitem must have a toolbar in its anchestry and every menuitem must have a menubar or popup in its anchestry. Since a GMarkup parser is used to parse the UI description, it must not only be valid XML, but valid GMarkup.

If a name is not specified, it defaults to the action. If an action is not specified either, the element name is used. The name and action attributes must not contain '/' characters after parsing (since that would mess up path lookup) and must be usable as XML attributes when enclosed in doublequotes, thus they must not '"' characters or references to the &quot; entity.

Example 22. A UI definition

<ui>
  <menubar>
    <menu name="FileMenu" action="FileMenuAction">
      <menuitem name="New" action="New2Action" />
      <placeholder name="FileMenuAdditions" />
    </menu>
    <menu name="JustifyMenu" action="JustifyMenuAction">
      <menuitem name="Left" action="justify-left"/>
      <menuitem name="Centre" action="justify-center"/>
      <menuitem name="Right" action="justify-right"/>
      <menuitem name="Fill" action="justify-fill"/>
    </menu>
  </menubar>
  <toolbar action="toolbar1">
    <placeholder name="JustifyToolItems">
      <separator/>
      <toolitem name="Left" action="justify-left"/>
      <toolitem name="Centre" action="justify-center"/>
      <toolitem name="Right" action="justify-right"/>
      <toolitem name="Fill" action="justify-fill"/>
      <separator/>
    </placeholder>
  </toolbar>
</ui>

The constructed widget hierarchy is very similar to the element tree of the XML, with the exception that placeholders are merged into their parents. The correspondence of XML elements to widgets should be almost obvious:

menubar | a GtkMenuBar
toolbar | a GtkToolbar
popup | a toplevel GtkMenu
menu | a GtkMenu attached to a menuitem
menuitem | a GtkMenuItem subclass, the exact type depends on the action
toolitem | a GtkToolItem subclass, the exact type depends on the action. Note that toolitem elements may contain a menu element, but only if their associated action specifies a GtkMenuToolButton as proxy.
separator | a GtkSeparatorMenuItem or GtkSeparatorToolItem
accelerator | a keyboard accelerator

The "position" attribute determines where a constructed widget is positioned wrt. to its siblings in the partially constructed tree. If it is "top", the widget is prepended, otherwise it is appended.

UI Merging

The most remarkable feature of GtkUIManager is that it can overlay a set of menuitems and toolitems over another one, and demerge them later.

Merging is done based on the names of the XML elements. Each element is identified by a path which consists of the names of its anchestors, separated by slashes. For example, the menuitem named "Left" in the example above has the path /ui/menubar/JustifyMenu/Left and the toolitem with the same name has path /ui/toolbar1/JustifyToolItems/Left.

Accelerators

Every action has an accelerator path. Accelerators are installed together with menuitem proxies, but they can also be explicitly added with <accelerator> elements in the UI definition. This makes it possible to have accelerators for actions even if they have no visible proxies.

Smart Separators

The separators created by GtkUIManager are "smart", i.e. they do not show up in the UI unless they end up between two visible menu or tool items. Separators which are located at the very beginning or end of the menu or toolbar containing them, or multiple separators next to each other, are hidden. This is a useful feature, since the merging of UI elements from multiple sources can make it hard or impossible to determine in advance whether a separator will end up in such an unfortunate position.

For separators in toolbars, you can set expand="true" to turn them from a small, visible separator to an expanding, invisible one. Toolitems following an expanding separator are effectively right-aligned.

Empty Menus

Submenus pose similar problems to separators inconnection with merging. It is impossible to know in advance whether they will end up empty after merging. GtkUIManager offers two ways to treat empty submenus:

  • make them disappear by hiding the menu item they're attached to

  • add an insensitive "Empty" item

The behaviour is chosen based on the "hide_if_empty" property of the action to which the submenu is associated.

Details

GtkUIManager

typedef struct _GtkUIManager GtkUIManager;

The GtkUIManager struct contains only private members and should not be accessed directly.

gtk_ui_manager_new ()

GtkUIManager*       gtk_ui_manager_new                  (void);

Creates a new ui manager object.

Returns : a new ui manager object.

Since 2.4

gtk_ui_manager_set_add_tearoffs ()

void                gtk_ui_manager_set_add_tearoffs     (GtkUIManager *self,
                                                         gboolean add_tearoffs);

Sets the "add_tearoffs" property, which controls whether menus generated by this GtkUIManager will have tearoff menu items.

Note that this only affects regular menus. Generated popup menus never have tearoff menu items.

self : | a GtkUIManager
add_tearoffs : | whether tearoff menu items are added

Since 2.4

gtk_ui_manager_get_add_tearoffs ()

gboolean            gtk_ui_manager_get_add_tearoffs     (GtkUIManager *self);

Returns whether menus generated by this GtkUIManager will have tearoff menu items.

self : | a GtkUIManager
Returns : | whether tearoff menu items are added

Since 2.4

gtk_ui_manager_insert_action_group ()

void                gtk_ui_manager_insert_action_group  (GtkUIManager *self,
                                                         GtkActionGroup *action_group,
                                                         gint pos);

Inserts an action group into the list of action groups associated with self. Actions in earlier groups hide actions with the same name in later groups.

self : | a GtkUIManager object
action_group : | the action group to be inserted
pos : | the position at which the group will be inserted.

Since 2.4

gtk_ui_manager_remove_action_group ()

void                gtk_ui_manager_remove_action_group  (GtkUIManager *self,
                                                         GtkActionGroup *action_group);

Removes an action group from the list of action groups associated with self.

self : | a GtkUIManager object
action_group : | the action group to be removed

Since 2.4

gtk_ui_manager_get_action_groups ()

GList*              gtk_ui_manager_get_action_groups    (GtkUIManager *self);

Returns the list of action groups associated with self.

self : | a GtkUIManager object
Returns : | a GList of action groups. The list is owned by GTK+ and should not be modified.

Since 2.4

gtk_ui_manager_get_accel_group ()

GtkAccelGroup*      gtk_ui_manager_get_accel_group      (GtkUIManager *self);

Returns the GtkAccelGroup associated with self.

self : | a GtkUIManager object
Returns : | the GtkAccelGroup.

Since 2.4

gtk_ui_manager_get_widget ()

GtkWidget*          gtk_ui_manager_get_widget           (GtkUIManager *self,
                                                         const gchar *path);

Looks up a widget by following a path. The path consists of the names specified in the XML description of the UI. separated by '/'. Elements which don't have a name or action attribute in the XML (e.g. <popup>) can be addressed by their XML element name (e.g. "popup"). The root element ("/ui") can be omitted in the path.

Note that the widget found by following a path that ends in a <menu> element is the menuitem to which the menu is attached, not the menu itself.

Also note that the widgets constructed by a ui manager are not tied to the lifecycle of the ui manager. If you add the widgets returned by this function to some container or explicitly ref them, they will survive the destruction of the ui manager.

self : | a GtkUIManager
path : | a path
Returns : | the widget found by following the path, or NULL if no widget was found.

Since 2.4

gtk_ui_manager_get_toplevels ()

GSList*             gtk_ui_manager_get_toplevels        (GtkUIManager *self,
                                                         GtkUIManagerItemType types);

Obtains a list of all toplevel widgets of the requested types.

self : | a GtkUIManager
types : | specifies the types of toplevel widgets to include. Allowed types are GTK_UI_MANAGER_MENUBAR, GTK_UI_MANAGER_TOOLBAR and GTK_UI_MANAGER_POPUP.
Returns : | a newly-allocated of all toplevel widgets of the requested types.

Since 2.4

gtk_ui_manager_get_action ()

GtkAction*          gtk_ui_manager_get_action           (GtkUIManager *self,
                                                         const gchar *path);

Looks up an action by following a path. See gtk_ui_manager_get_widget() for more information about paths.

self : | a GtkUIManager
path : | a path
Returns : | the action whose proxy widget is found by following the path, or NULL if no widget was found.

Since 2.4

gtk_ui_manager_add_ui_from_string ()

guint               gtk_ui_manager_add_ui_from_string   (GtkUIManager *self,
                                                         const gchar *buffer,
                                                         gssize length,
                                                         GError **error);

Parses a string containing a UI definition and merges it with the current contents of self. An enclosing <ui> element is added if it is missing.

self : | a GtkUIManager object
buffer : | the string to parse
length : | the length of buffer (may be -1 if buffer is nul-terminated)
error : | return location for an error
Returns : | The merge id for the merged UI. The merge id can be used to unmerge the UI with gtk_ui_manager_remove_ui(). If an error occurred, the return value is 0.

Since 2.4

gtk_ui_manager_add_ui_from_file ()

guint               gtk_ui_manager_add_ui_from_file     (GtkUIManager *self,
                                                         const gchar *filename,
                                                         GError **error);

Parses a file containing a UI definition and merges it with the current contents of self.

self : | a GtkUIManager object
filename : | the name of the file to parse
error : | return location for an error
Returns : | The merge id for the merged UI. The merge id can be used to unmerge the UI with gtk_ui_manager_remove_ui(). If an error occurred, the return value is 0.

Since 2.4

gtk_ui_manager_new_merge_id ()

guint               gtk_ui_manager_new_merge_id         (GtkUIManager *self);

Returns an unused merge id, suitable for use with gtk_ui_manager_add_ui().

self : | a GtkUIManager
Returns : | an unused merge id.

Since 2.4

enum GtkUIManagerItemType

typedef enum {
  GTK_UI_MANAGER_AUTO         = 0,
  GTK_UI_MANAGER_MENUBAR      = 1 << 0,
  GTK_UI_MANAGER_MENU         = 1 << 1,
  GTK_UI_MANAGER_TOOLBAR      = 1 << 2,
  GTK_UI_MANAGER_PLACEHOLDER  = 1 << 3,
  GTK_UI_MANAGER_POPUP        = 1 << 4,
  GTK_UI_MANAGER_MENUITEM     = 1 << 5,
  GTK_UI_MANAGER_TOOLITEM     = 1 << 6,
  GTK_UI_MANAGER_SEPARATOR    = 1 << 7,
  GTK_UI_MANAGER_ACCELERATOR  = 1 << 8
} GtkUIManagerItemType;

These enumeration values are used by gtk_ui_manager_add_ui() to determine what UI element to create.

GTK_UI_MANAGER_AUTO | Pick the type of the UI element according to context.
GTK_UI_MANAGER_MENUBAR | Create a menubar.
GTK_UI_MANAGER_MENU | Create a menu.
GTK_UI_MANAGER_TOOLBAR | Create a toolbar.
GTK_UI_MANAGER_PLACEHOLDER | Insert a placeholder.
GTK_UI_MANAGER_POPUP | Create a popup menu.
GTK_UI_MANAGER_MENUITEM | Create a menuitem.
GTK_UI_MANAGER_TOOLITEM | Create a toolitem.
GTK_UI_MANAGER_SEPARATOR | Create a separator.
GTK_UI_MANAGER_ACCELERATOR | Install an accelerator.

gtk_ui_manager_add_ui ()

void                gtk_ui_manager_add_ui               (GtkUIManager *self,
                                                         guint merge_id,
                                                         const gchar *path,
                                                         const gchar *name,
                                                         const gchar *action,
                                                         GtkUIManagerItemType type,
                                                         gboolean top);

Adds a UI element to the current contents of self.

If type is GTK_UI_MANAGER_AUTO, GTK+ inserts a menuitem, toolitem or separator if such an element can be inserted at the place determined by path. Otherwise type must indicate an element that can be inserted at the place determined by path.

If path points to a menuitem or toolitem, the new element will be inserted before or after this item, depending on top.

self : | a GtkUIManager
merge_id : | the merge id for the merged UI, see gtk_ui_manager_new_merge_id()
path : | a path
name : | the name for the added UI element
action : | the name of the action to be proxied, or NULL to add a separator
type : | the type of UI element to add.
top : | if TRUE, the UI element is added before its siblings, otherwise it is added after its siblings.

Since 2.4

gtk_ui_manager_remove_ui ()

void                gtk_ui_manager_remove_ui            (GtkUIManager *self,
                                                         guint merge_id);

Unmerges the part of selfs content identified by merge_id.

self : | a GtkUIManager object
merge_id : | a merge id as returned by gtk_ui_manager_add_ui_from_string()

Since 2.4

gtk_ui_manager_get_ui ()

gchar*              gtk_ui_manager_get_ui               (GtkUIManager *self);

Creates a UI definition of the merged UI.

self : | a GtkUIManager
Returns : | A newly allocated string containing an XML representation of the merged UI.

Since 2.4

gtk_ui_manager_ensure_update ()

void                gtk_ui_manager_ensure_update        (GtkUIManager *self);

Makes sure that all pending updates to the UI have been completed.

This may occasionally be necessary, since GtkUIManager updates the UI in an idle function. A typical example where this function is useful is to enforce that the menubar and toolbar have been added to the main window before showing it:

gtk_container_add (GTK_CONTAINER (window), vbox);
g_signal_connect (merge, "add_widget",
                  G_CALLBACK (add_widget), vbox);
gtk_ui_manager_add_ui_from_file (merge, "my-menus");
gtk_ui_manager_add_ui_from_file (merge, "my-toolbars");
gtk_ui_manager_ensure_update (merge);
gtk_widget_show (window);

self : a GtkUIManager

Since 2.4

Property Details

The "add-tearoffs" property

  "add-tearoffs"             gboolean              : Read / Write

The "add-tearoffs" property controls whether generated menus have tearoff menu items.

Note that this only affects regular menus. Generated popup menus never have tearoff menu items.

Default value: FALSE

Since 2.4

The "ui" property

  "ui"                       gchararray            : Read

An XML string describing the merged UI.

Default value: "<ui>\n</ui>\n"

Signal Details

The "actions-changed" signal

void                user_function                      (GtkUIManager *merge,
                                                        gpointer      user_data)      : Run First / No Recursion

The "actions-changed" signal is emitted whenever the set of actions changes.

merge : | a GtkUIManager
user_data : | user data set when the signal handler was connected.

Since 2.4

The "add-widget" signal

void                user_function                      (GtkUIManager *merge,
                                                        GtkWidget    *widget,
                                                        gpointer      user_data)      : Run First / No Recursion

The add_widget signal is emitted for each generated menubar and toolbar. It is not emitted for generated popup menus, which can be obtained by gtk_ui_manager_get_widget().

merge : | a GtkUIManager
widget : | the added widget
user_data : | user data set when the signal handler was connected.

Since 2.4

The "connect-proxy" signal

void                user_function                      (GtkUIManager *uimanager,
                                                        GtkAction    *action,
                                                        GtkWidget    *proxy,
                                                        gpointer      user_data)      : Run First / No Recursion

The connect_proxy signal is emitted after connecting a proxy to an action in the group.

This is intended for simple customizations for which a custom action class would be too clumsy, e.g. showing tooltips for menuitems in the statusbar.

uimanager : | the ui manager
action : | the action
proxy : | the proxy
user_data : | user data set when the signal handler was connected.

Since 2.4

The "disconnect-proxy" signal

void                user_function                      (GtkUIManager *uimanager,
                                                        GtkAction    *action,
                                                        GtkWidget    *proxy,
                                                        gpointer      user_data)      : Run First / No Recursion

The disconnect_proxy signal is emitted after disconnecting a proxy from an action in the group.

uimanager : | the ui manager
action : | the action
proxy : | the proxy
user_data : | user data set when the signal handler was connected.

Since 2.4

The "post-activate" signal

void                user_function                      (GtkUIManager *uimanager,
                                                        GtkAction    *action,
                                                        gpointer      user_data)      : Run First / No Recursion

The post_activate signal is emitted just after the action is activated.

This is intended for applications to get notification just after any action is activated.

uimanager : | the ui manager
action : | the action
user_data : | user data set when the signal handler was connected.

Since 2.4

The "pre-activate" signal

void                user_function                      (GtkUIManager *uimanager,
                                                        GtkAction    *action,
                                                        gpointer      user_data)      : Run First / No Recursion

The pre_activate signal is emitted just before the action is activated.

This is intended for applications to get notification just before any action is activated.

uimanager : | the ui manager
action : | the action
user_data : | user data set when the signal handler was connected.

Since 2.4


GtkVBox

GtkVBox — A vertical container box

Synopsis

#include <gtk/gtk.h>

                    GtkVBox;
GtkWidget*          gtk_vbox_new                        (gboolean homogeneous,
                                                         gint spacing);

Object Hierarchy

  GObject
   +----GInitiallyUnowned
         +----GtkObject
               +----GtkWidget
                     +----GtkContainer
                           +----GtkBox
                                 +----GtkVBox
                                       +----GtkColorSelection
                                       +----GtkFileChooserWidget
                                       +----GtkFontSelection
                                       +----GtkGammaCurve
                                       +----GtkRecentChooserWidget

Implemented Interfaces

GtkVBox implements AtkImplementorIface.

Description

GtkVBox is a container that organizes child widgets into a single column.

Use the GtkBox packing interface to determine the arrangement, spacing, height, and alignment of GtkVBox children.

All children are allocated the same width.

Details

GtkVBox

typedef struct _GtkVBox GtkVBox;

gtk_vbox_new ()

GtkWidget*          gtk_vbox_new                        (gboolean homogeneous,
                                                         gint spacing);

Creates a new GtkVBox.

homogeneous : | TRUE if all children are to be given equal space allotments.
spacing : | the number of pixels to place by default between children.
Returns : | a new GtkVBox.

See Also

GtkHBox

a sister class that organizes widgets into a row.


GtkVButtonBox

GtkVButtonBox — A container for arranging buttons vertically

Synopsis

#include <gtk/gtk.h>

                    GtkVButtonBox;
GtkWidget*          gtk_vbutton_box_new                 (void);
gint                gtk_vbutton_box_get_spacing_default (void);
void                gtk_vbutton_box_set_spacing_default (gint spacing);
GtkButtonBoxStyle   gtk_vbutton_box_get_layout_default  (void);
void                gtk_vbutton_box_set_layout_default  (GtkButtonBoxStyle layout);

Object Hierarchy

  GObject
   +----GInitiallyUnowned
         +----GtkObject
               +----GtkWidget
                     +----GtkContainer
                           +----GtkBox
                                 +----GtkButtonBox
                                       +----GtkVButtonBox

Implemented Interfaces

GtkVButtonBox implements AtkImplementorIface.

Description

A button box should be used to provide a consistent layout of buttons throughout your application. The layout/spacing can be altered by the programmer, or if desired, by the user to alter the 'feel' of a program to a small degree.

A GtkVButtonBox is created with gtk_vbutton_box_new(). Buttons are packed into a button box the same way widgets are added to any other container, using gtk_container_add(). You can also use gtk_box_pack_start() or gtk_box_pack_end(), but for button boxes both these functions work just like gtk_container_add(), ie., they pack the button in a way that depends on the current layout style and on whether the button has had gtk_button_box_set_child_secondary() called on it.

The spacing between buttons can be set with gtk_box_set_spacing(). The arrangement and layout of the buttons can be changed with gtk_button_box_set_layout().

Details

GtkVButtonBox

typedef struct _GtkVButtonBox GtkVButtonBox;

GtkVButtonBox does not contain any public fields.

gtk_vbutton_box_new ()

GtkWidget*          gtk_vbutton_box_new                 (void);

Creates a new vertical button box.

Returns : a new button box GtkWidget.

gtk_vbutton_box_get_spacing_default ()

gint                gtk_vbutton_box_get_spacing_default (void);

Warning

gtk_vbutton_box_get_spacing_default is deprecated and should not be used in newly-written code.

Retrieves the current default spacing for vertical button boxes. This is the number of pixels to be placed between the buttons when they are arranged.

Returns : the default number of pixels between buttons.

gtk_vbutton_box_set_spacing_default ()

void                gtk_vbutton_box_set_spacing_default (gint spacing);

Warning

gtk_vbutton_box_set_spacing_default is deprecated and should not be used in newly-written code.

Changes the default spacing that is placed between widgets in an vertical button box.

spacing : an integer value.

gtk_vbutton_box_get_layout_default ()

GtkButtonBoxStyle   gtk_vbutton_box_get_layout_default  (void);

Warning

gtk_vbutton_box_get_layout_default is deprecated and should not be used in newly-written code.

Retrieves the current layout used to arrange buttons in button box widgets.

Returns : the current GtkButtonBoxStyle.

gtk_vbutton_box_set_layout_default ()

void                gtk_vbutton_box_set_layout_default  (GtkButtonBoxStyle layout);

Warning

gtk_vbutton_box_set_layout_default is deprecated and should not be used in newly-written code.

Sets a new layout mode that will be used by all button boxes.

layout : a new GtkButtonBoxStyle.

See Also

GtkBox | Used to pack widgets into button boxes.
GtkButtonBox | Provides functions for controlling button boxes.
GtkHButtonBox | Pack buttons horizontally


GtkViewport

GtkViewport — An adapter which makes widgets scrollable

Synopsis

#include <gtk/gtk.h>

                    GtkViewport;
GtkWidget*          gtk_viewport_new                    (GtkAdjustment *hadjustment,
                                                         GtkAdjustment *vadjustment);
GtkAdjustment*      gtk_viewport_get_hadjustment        (GtkViewport *viewport);
GtkAdjustment*      gtk_viewport_get_vadjustment        (GtkViewport *viewport);
void                gtk_viewport_set_hadjustment        (GtkViewport *viewport,
                                                         GtkAdjustment *adjustment);
void                gtk_viewport_set_vadjustment        (GtkViewport *viewport,
                                                         GtkAdjustment *adjustment);
void                gtk_viewport_set_shadow_type        (GtkViewport *viewport,
                                                         GtkShadowType type);
GtkShadowType       gtk_viewport_get_shadow_type        (GtkViewport *viewport);

Object Hierarchy

  GObject
   +----GInitiallyUnowned
         +----GtkObject
               +----GtkWidget
                     +----GtkContainer
                           +----GtkBin
                                 +----GtkViewport

Implemented Interfaces

GtkViewport implements AtkImplementorIface.

Properties

  "hadjustment"              GtkAdjustment         : Read / Write / Construct
  "shadow-type"              GtkShadowType         : Read / Write
  "vadjustment"              GtkAdjustment         : Read / Write / Construct

Signals

  "set-scroll-adjustments"                         : Run Last / Action

Description

Details

GtkViewport

typedef struct _GtkViewport GtkViewport;

gtk_viewport_new ()

GtkWidget*          gtk_viewport_new                    (GtkAdjustment *hadjustment,
                                                         GtkAdjustment *vadjustment);

Creates a new GtkViewport with the given adjustments.

hadjustment : | horizontal adjustment.
vadjustment : | vertical adjustment.
Returns : | a new GtkViewport.

gtk_viewport_get_hadjustment ()

GtkAdjustment*      gtk_viewport_get_hadjustment        (GtkViewport *viewport);

Returns the horizontal adjustment of the viewport.

viewport : | a GtkViewport.
Returns : | the horizontal adjustment of viewport.

gtk_viewport_get_vadjustment ()

GtkAdjustment*      gtk_viewport_get_vadjustment        (GtkViewport *viewport);

Returns the vertical adjustment of the viewport.

viewport : | a GtkViewport.
Returns : | the vertical adjustment of viewport.

gtk_viewport_set_hadjustment ()

void                gtk_viewport_set_hadjustment        (GtkViewport *viewport,
                                                         GtkAdjustment *adjustment);

Sets the horizontal adjustment of the viewport.

viewport : | a GtkViewport.
adjustment : | a GtkAdjustment.

gtk_viewport_set_vadjustment ()

void                gtk_viewport_set_vadjustment        (GtkViewport *viewport,
                                                         GtkAdjustment *adjustment);

Sets the vertical adjustment of the viewport.

viewport : | a GtkViewport.
adjustment : | a GtkAdjustment.

gtk_viewport_set_shadow_type ()

void                gtk_viewport_set_shadow_type        (GtkViewport *viewport,
                                                         GtkShadowType type);

Sets the shadow type of the viewport.

viewport : | a GtkViewport.
type : | the new shadow type.

gtk_viewport_get_shadow_type ()

GtkShadowType       gtk_viewport_get_shadow_type        (GtkViewport *viewport);

Gets the shadow type of the GtkViewport. See gtk_viewport_set_shadow_type().

viewport : | a GtkViewport
Returns : | the shadow type

Property Details

The "hadjustment" property

  "hadjustment"              GtkAdjustment         : Read / Write / Construct

The GtkAdjustment that determines the values of the horizontal position for this viewport.

The "shadow-type" property

  "shadow-type"              GtkShadowType         : Read / Write

Determines how the shadowed box around the viewport is drawn.

Default value: GTK_SHADOW_IN

The "vadjustment" property

  "vadjustment"              GtkAdjustment         : Read / Write / Construct

The GtkAdjustment that determines the values of the vertical position for this viewport.

Signal Details

The "set-scroll-adjustments" signal

void                user_function                      (GtkViewport   *viewport,
                                                        GtkAdjustment *arg1,
                                                        GtkAdjustment *arg2,
                                                        gpointer       user_data)      : Run Last / Action

viewport : | the object which received the signal.
arg1 : |
arg2 : |
user_data : | user data set when the signal handler was connected.


GtkVPaned

GtkVPaned — A container with two panes arranged vertically

Synopsis

#include <gtk/gtk.h>

                    GtkVPaned;
GtkWidget*          gtk_vpaned_new                      (void);

Object Hierarchy

  GObject
   +----GInitiallyUnowned
         +----GtkObject
               +----GtkWidget
                     +----GtkContainer
                           +----GtkPaned
                                 +----GtkVPaned

Implemented Interfaces

GtkVPaned implements AtkImplementorIface.

Description

The VPaned widget is a container widget with two children arranged vertically. The division between the two panes is adjustable by the user by dragging a handle. See GtkPaned for details.

Details

GtkVPaned

typedef struct _GtkVPaned GtkVPaned;

gtk_vpaned_new ()

GtkWidget*          gtk_vpaned_new                      (void);

Create a new GtkVPaned

Returns : the new GtkVPaned


GtkVRuler

GtkVRuler — A vertical ruler.

Synopsis

#include <gtk/gtk.h>

                    GtkVRuler;
GtkWidget*          gtk_vruler_new                      (void);

Object Hierarchy

  GObject
   +----GInitiallyUnowned
         +----GtkObject
               +----GtkWidget
                     +----GtkRuler
                           +----GtkVRuler

Implemented Interfaces

GtkVRuler implements AtkImplementorIface.

Description

Note

This widget is considered too specialized/little-used for GTK+, and will in the future be moved to some other package. If your application needs this widget, feel free to use it, as the widget does work and is useful in some applications; it's just not of general interest. However, we are not accepting new features for the widget, and it will eventually move out of the GTK+ distribution.

The VRuler widget is a widget arranged vertically creating a ruler that is utilized around other widgets such as a text widget. The ruler is used to show the location of the mouse on the window and to show the size of the window in specified units. The available units of measurement are GTK_PIXELS, GTK_INCHES and GTK_CENTIMETERS. GTK_PIXELS is the default. rulers.

Details

GtkVRuler

typedef struct _GtkVRuler GtkVRuler;

The GtkVRuler struct contains private data and should be accessed using the functions below.

gtk_vruler_new ()

GtkWidget*          gtk_vruler_new                      (void);

Creates a new vertical ruler

Returns : a new GtkVRuler.


GtkVScale

GtkVScale — A vertical slider widget for selecting a value from a range

Synopsis

#include <gtk/gtk.h>

                    GtkVScale;
GtkWidget*          gtk_vscale_new                      (GtkAdjustment *adjustment);
GtkWidget*          gtk_vscale_new_with_range           (gdouble min,
                                                         gdouble max,
                                                         gdouble step);

Object Hierarchy

  GObject
   +----GInitiallyUnowned
         +----GtkObject
               +----GtkWidget
                     +----GtkRange
                           +----GtkScale
                                 +----GtkVScale

Implemented Interfaces

GtkVScale implements AtkImplementorIface.

Description

The GtkVScale widget is used to allow the user to select a value using a vertical slider. To create one, use gtk_hscale_new_with_range().

The position to show the current value, and the number of decimal places shown can be set using the parent GtkScale class's functions.

Details

GtkVScale

typedef struct _GtkVScale GtkVScale;

The GtkVScale struct contains private data only, and should be accessed using the functions below.

gtk_vscale_new ()

GtkWidget*          gtk_vscale_new                      (GtkAdjustment *adjustment);

Creates a new GtkVScale.

adjustment : | the GtkAdjustment which sets the range of the scale.
Returns : | a new GtkVScale.

gtk_vscale_new_with_range ()

GtkWidget*          gtk_vscale_new_with_range           (gdouble min,
                                                         gdouble max,
                                                         gdouble step);

Creates a new vertical scale widget that lets the user input a number between min and max (including min and max) with the increment step. step must be nonzero; it's the distance the slider moves when using the arrow keys to adjust the scale value.

Note that the way in which the precision is derived works best if step is a power of ten. If the resulting precision is not suitable for your needs, use gtk_scale_set_digits() to correct it.

min : | minimum value
max : | maximum value
step : | step increment (tick size) used with keyboard shortcuts
Returns : | a new GtkVScale


GtkVScrollbar

GtkVScrollbar — A vertical scrollbar

Synopsis

#include <gtk/gtk.h>

                    GtkVScrollbar;
GtkWidget*          gtk_vscrollbar_new                  (GtkAdjustment *adjustment);

Object Hierarchy

  GObject
   +----GInitiallyUnowned
         +----GtkObject
               +----GtkWidget
                     +----GtkRange
                           +----GtkScrollbar
                                 +----GtkVScrollbar

Implemented Interfaces

GtkVScrollbar implements AtkImplementorIface.

Description

The GtkVScrollbar widget is a widget arranged vertically creating a scrollbar. See GtkScrollbar for details on scrollbars. GtkAdjustment pointers may be added to handle the adjustment of the scrollbar or it may be left NULL in which case one will be created for you. See GtkAdjustment for details.

Details

GtkVScrollbar

typedef struct _GtkVScrollbar GtkVScrollbar;

The GtkVScrollbar struct contains private data and should be accessed using the functions below.

gtk_vscrollbar_new ()

GtkWidget*          gtk_vscrollbar_new                  (GtkAdjustment *adjustment);

Creates a new vertical scrollbar.

adjustment : | the GtkAdjustment to use, or NULL to create a new adjustment.
Returns : | the new GtkVScrollbar

See Also

GtkScrollbar, GtkScrolledWindow


GtkVSeparator

GtkVSeparator — A vertical separator

Synopsis

#include <gtk/gtk.h>

                    GtkVSeparator;
GtkWidget*          gtk_vseparator_new                  (void);

Object Hierarchy

  GObject
   +----GInitiallyUnowned
         +----GtkObject
               +----GtkWidget
                     +----GtkSeparator
                           +----GtkVSeparator

Implemented Interfaces

GtkVSeparator implements AtkImplementorIface.

Description

The GtkVSeparator widget is a vertical separator, used to group the widgets within a window. It displays a vertical line with a shadow to make it appear sunken into the interface.

Details

GtkVSeparator

typedef struct _GtkVSeparator GtkVSeparator;

The GtkVSeparator struct contains private data only, and should be accessed using the functions below.

gtk_vseparator_new ()

GtkWidget*          gtk_vseparator_new                  (void);

Creates a new GtkVSeparator.

Returns : a new GtkVSeparator.

See Also

GtkHSeparator

a horizontal separator.


GtkWidget

GtkWidget — Base class for all widgets

Synopsis

#include <gtk/gtk.h>

                    GtkWidget;
                    GtkWidgetClass;
enum                GtkWidgetFlags;
#define             GTK_WIDGET_TYPE                     (wid)
#define             GTK_WIDGET_STATE                    (wid)
#define             GTK_WIDGET_SAVED_STATE              (wid)
#define             GTK_WIDGET_FLAGS                    (wid)
#define             GTK_WIDGET_TOPLEVEL                 (wid)
#define             GTK_WIDGET_NO_WINDOW                (wid)
#define             GTK_WIDGET_REALIZED                 (wid)
#define             GTK_WIDGET_MAPPED                   (wid)
#define             GTK_WIDGET_VISIBLE                  (wid)
#define             GTK_WIDGET_DRAWABLE                 (wid)
#define             GTK_WIDGET_SENSITIVE                (wid)
#define             GTK_WIDGET_PARENT_SENSITIVE         (wid)
#define             GTK_WIDGET_IS_SENSITIVE             (wid)
#define             GTK_WIDGET_CAN_FOCUS                (wid)
#define             GTK_WIDGET_HAS_FOCUS                (wid)
#define             GTK_WIDGET_CAN_DEFAULT              (wid)
#define             GTK_WIDGET_RECEIVES_DEFAULT         (wid)
#define             GTK_WIDGET_HAS_DEFAULT              (wid)
#define             GTK_WIDGET_HAS_GRAB                 (wid)
#define             GTK_WIDGET_RC_STYLE                 (wid)
#define             GTK_WIDGET_COMPOSITE_CHILD          (wid)
#define             GTK_WIDGET_APP_PAINTABLE            (wid)
#define             GTK_WIDGET_DOUBLE_BUFFERED          (wid)
#define             GTK_WIDGET_SET_FLAGS                (wid,flag)
#define             GTK_WIDGET_UNSET_FLAGS              (wid,flag)
void                (*GtkCallback)                      (GtkWidget *widget,
                                                         gpointer data);
                    GtkRequisition;
struct              GtkAllocation;
                    GtkSelectionData;
                    GtkWidgetAuxInfo;
                    GtkWidgetShapeInfo;
enum                GtkWidgetHelpType;
GtkWidget*          gtk_widget_new                      (GType type,
                                                         const gchar *first_property_name,
                                                         ...);
GtkWidget*          gtk_widget_ref                      (GtkWidget *widget);
void                gtk_widget_unref                    (GtkWidget *widget);
void                gtk_widget_destroy                  (GtkWidget *widget);
void                gtk_widget_destroyed                (GtkWidget *widget,
                                                         GtkWidget **widget_pointer);
void                gtk_widget_set                      (GtkWidget *widget,
                                                         const gchar *first_property_name,
                                                         ...);
void                gtk_widget_unparent                 (GtkWidget *widget);
void                gtk_widget_show                     (GtkWidget *widget);
void                gtk_widget_show_now                 (GtkWidget *widget);
void                gtk_widget_hide                     (GtkWidget *widget);
void                gtk_widget_show_all                 (GtkWidget *widget);
void                gtk_widget_hide_all                 (GtkWidget *widget);
void                gtk_widget_map                      (GtkWidget *widget);
void                gtk_widget_unmap                    (GtkWidget *widget);
void                gtk_widget_realize                  (GtkWidget *widget);
void                gtk_widget_unrealize                (GtkWidget *widget);
void                gtk_widget_queue_draw               (GtkWidget *widget);
void                gtk_widget_queue_resize             (GtkWidget *widget);
void                gtk_widget_queue_resize_no_redraw   (GtkWidget *widget);
void                gtk_widget_draw                     (GtkWidget *widget,
                                                         GdkRectangle *area);
void                gtk_widget_size_request             (GtkWidget *widget,
                                                         GtkRequisition *requisition);
void                gtk_widget_get_child_requisition    (GtkWidget *widget,
                                                         GtkRequisition *requisition);
void                gtk_widget_size_allocate            (GtkWidget *widget,
                                                         GtkAllocation *allocation);
void                gtk_widget_add_accelerator          (GtkWidget *widget,
                                                         const gchar *accel_signal,
                                                         GtkAccelGroup *accel_group,
                                                         guint accel_key,
                                                         GdkModifierType accel_mods,
                                                         GtkAccelFlags accel_flags);
gboolean            gtk_widget_remove_accelerator       (GtkWidget *widget,
                                                         GtkAccelGroup *accel_group,
                                                         guint accel_key,
                                                         GdkModifierType accel_mods);
void                gtk_widget_set_accel_path           (GtkWidget *widget,
                                                         const gchar *accel_path,
                                                         GtkAccelGroup *accel_group);
GList*              gtk_widget_list_accel_closures      (GtkWidget *widget);
gboolean            gtk_widget_can_activate_accel       (GtkWidget *widget,
                                                         guint signal_id);
gboolean            gtk_widget_event                    (GtkWidget *widget,
                                                         GdkEvent *event);
gboolean            gtk_widget_activate                 (GtkWidget *widget);
void                gtk_widget_reparent                 (GtkWidget *widget,
                                                         GtkWidget *new_parent);
gboolean            gtk_widget_intersect                (GtkWidget *widget,
                                                         GdkRectangle *area,
                                                         GdkRectangle *intersection);
gboolean            gtk_widget_is_focus                 (GtkWidget *widget);
void                gtk_widget_grab_focus               (GtkWidget *widget);
void                gtk_widget_grab_default             (GtkWidget *widget);
void                gtk_widget_set_name                 (GtkWidget *widget,
                                                         const gchar *name);
const gchar*        gtk_widget_get_name                 (GtkWidget *widget);
void                gtk_widget_set_state                (GtkWidget *widget,
                                                         GtkStateType state);
void                gtk_widget_set_sensitive            (GtkWidget *widget,
                                                         gboolean sensitive);
void                gtk_widget_set_parent               (GtkWidget *widget,
                                                         GtkWidget *parent);
void                gtk_widget_set_parent_window        (GtkWidget *widget,
                                                         GdkWindow *parent_window);
GdkWindow*          gtk_widget_get_parent_window        (GtkWidget *widget);
void                gtk_widget_set_uposition            (GtkWidget *widget,
                                                         gint x,
                                                         gint y);
void                gtk_widget_set_usize                (GtkWidget *widget,
                                                         gint width,
                                                         gint height);
void                gtk_widget_set_events               (GtkWidget *widget,
                                                         gint events);
void                gtk_widget_add_events               (GtkWidget *widget,
                                                         gint events);
void                gtk_widget_set_extension_events     (GtkWidget *widget,
                                                         GdkExtensionMode mode);
GdkExtensionMode    gtk_widget_get_extension_events     (GtkWidget *widget);
GtkWidget*          gtk_widget_get_toplevel             (GtkWidget *widget);
GtkWidget*          gtk_widget_get_ancestor             (GtkWidget *widget,
                                                         GType widget_type);
GdkColormap*        gtk_widget_get_colormap             (GtkWidget *widget);
void                gtk_widget_set_colormap             (GtkWidget *widget,
                                                         GdkColormap *colormap);
GdkVisual*          gtk_widget_get_visual               (GtkWidget *widget);
gint                gtk_widget_get_events               (GtkWidget *widget);
void                gtk_widget_get_pointer              (GtkWidget *widget,
                                                         gint *x,
                                                         gint *y);
gboolean            gtk_widget_is_ancestor              (GtkWidget *widget,
                                                         GtkWidget *ancestor);
gboolean            gtk_widget_translate_coordinates    (GtkWidget *src_widget,
                                                         GtkWidget *dest_widget,
                                                         gint src_x,
                                                         gint src_y,
                                                         gint *dest_x,
                                                         gint *dest_y);
gboolean            gtk_widget_hide_on_delete           (GtkWidget *widget);
void                gtk_widget_set_style                (GtkWidget *widget,
                                                         GtkStyle *style);
#define             gtk_widget_set_rc_style             (widget)
void                gtk_widget_ensure_style             (GtkWidget *widget);
GtkStyle*           gtk_widget_get_style                (GtkWidget *widget);
#define             gtk_widget_restore_default_style    (widget)
void                gtk_widget_reset_rc_styles          (GtkWidget *widget);
void                gtk_widget_push_colormap            (GdkColormap *cmap);
void                gtk_widget_pop_colormap             (void);
void                gtk_widget_set_default_colormap     (GdkColormap *colormap);
GtkStyle*           gtk_widget_get_default_style        (void);
GdkColormap*        gtk_widget_get_default_colormap     (void);
GdkVisual*          gtk_widget_get_default_visual       (void);
void                gtk_widget_set_direction            (GtkWidget *widget,
                                                         GtkTextDirection dir);
enum                GtkTextDirection;
GtkTextDirection    gtk_widget_get_direction            (GtkWidget *widget);
void                gtk_widget_set_default_direction    (GtkTextDirection dir);
GtkTextDirection    gtk_widget_get_default_direction    (void);
void                gtk_widget_shape_combine_mask       (GtkWidget *widget,
                                                         GdkBitmap *shape_mask,
                                                         gint offset_x,
                                                         gint offset_y);
void                gtk_widget_input_shape_combine_mask (GtkWidget *widget,
                                                         GdkBitmap *shape_mask,
                                                         gint offset_x,
                                                         gint offset_y);
void                gtk_widget_path                     (GtkWidget *widget,
                                                         guint *path_length,
                                                         gchar **path,
                                                         gchar **path_reversed);
void                gtk_widget_class_path               (GtkWidget *widget,
                                                         guint *path_length,
                                                         gchar **path,
                                                         gchar **path_reversed);
gchar*              gtk_widget_get_composite_name       (GtkWidget *widget);
void                gtk_widget_modify_style             (GtkWidget *widget,
                                                         GtkRcStyle *style);
GtkRcStyle*         gtk_widget_get_modifier_style       (GtkWidget *widget);
void                gtk_widget_modify_fg                (GtkWidget *widget,
                                                         GtkStateType state,
                                                         const GdkColor *color);
void                gtk_widget_modify_bg                (GtkWidget *widget,
                                                         GtkStateType state,
                                                         const GdkColor *color);
void                gtk_widget_modify_text              (GtkWidget *widget,
                                                         GtkStateType state,
                                                         const GdkColor *color);
void                gtk_widget_modify_base              (GtkWidget *widget,
                                                         GtkStateType state,
                                                         const GdkColor *color);
void                gtk_widget_modify_font              (GtkWidget *widget,
                                                         PangoFontDescription *font_desc);
PangoContext*       gtk_widget_create_pango_context     (GtkWidget *widget);
PangoContext*       gtk_widget_get_pango_context        (GtkWidget *widget);
PangoLayout*        gtk_widget_create_pango_layout      (GtkWidget *widget,
                                                         const gchar *text);
GdkPixbuf*          gtk_widget_render_icon              (GtkWidget *widget,
                                                         const gchar *stock_id,
                                                         GtkIconSize size,
                                                         const gchar *detail);
void                gtk_widget_pop_composite_child      (void);
void                gtk_widget_push_composite_child     (void);
void                gtk_widget_queue_clear              (GtkWidget *widget);
void                gtk_widget_queue_clear_area         (GtkWidget *widget,
                                                         gint x,
                                                         gint y,
                                                         gint width,
                                                         gint height);
void                gtk_widget_queue_draw_area          (GtkWidget *widget,
                                                         gint x,
                                                         gint y,
                                                         gint width,
                                                         gint height);
void                gtk_widget_reset_shapes             (GtkWidget *widget);
void                gtk_widget_set_app_paintable        (GtkWidget *widget,
                                                         gboolean app_paintable);
void                gtk_widget_set_double_buffered      (GtkWidget *widget,
                                                         gboolean double_buffered);
void                gtk_widget_set_redraw_on_allocate   (GtkWidget *widget,
                                                         gboolean redraw_on_allocate);
void                gtk_widget_set_composite_name       (GtkWidget *widget,
                                                         const gchar *name);
gboolean            gtk_widget_set_scroll_adjustments   (GtkWidget *widget,
                                                         GtkAdjustment *hadjustment,
                                                         GtkAdjustment *vadjustment);
gboolean            gtk_widget_mnemonic_activate        (GtkWidget *widget,
                                                         gboolean group_cycling);
void                gtk_widget_class_install_style_property
                                                        (GtkWidgetClass *klass,
                                                         GParamSpec *pspec);
void                gtk_widget_class_install_style_property_parser
                                                        (GtkWidgetClass *klass,
                                                         GParamSpec *pspec,
                                                         GtkRcPropertyParser parser);
GParamSpec*         gtk_widget_class_find_style_property
                                                        (GtkWidgetClass *klass,
                                                         const gchar *property_name);
GParamSpec**        gtk_widget_class_list_style_properties
                                                        (GtkWidgetClass *klass,
                                                         guint *n_properties);
GdkRegion*          gtk_widget_region_intersect         (GtkWidget *widget,
                                                         GdkRegion *region);
gint                gtk_widget_send_expose              (GtkWidget *widget,
                                                         GdkEvent *event);
void                gtk_widget_style_get                (GtkWidget *widget,
                                                         const gchar *first_property_name,
                                                         ...);
void                gtk_widget_style_get_property       (GtkWidget *widget,
                                                         const gchar *property_name,
                                                         GValue *value);
void                gtk_widget_style_get_valist         (GtkWidget *widget,
                                                         const gchar *first_property_name,
                                                         va_list var_args);
AtkObject*          gtk_widget_get_accessible           (GtkWidget *widget);
gboolean            gtk_widget_child_focus              (GtkWidget *widget,
                                                         GtkDirectionType direction);
void                gtk_widget_child_notify             (GtkWidget *widget,
                                                         const gchar *child_property);
void                gtk_widget_freeze_child_notify      (GtkWidget *widget);
gboolean            gtk_widget_get_child_visible        (GtkWidget *widget);
GtkWidget*          gtk_widget_get_parent               (GtkWidget *widget);
GtkSettings*        gtk_widget_get_settings             (GtkWidget *widget);
GtkClipboard*       gtk_widget_get_clipboard            (GtkWidget *widget,
                                                         GdkAtom selection);
GdkDisplay*         gtk_widget_get_display              (GtkWidget *widget);
GdkWindow*          gtk_widget_get_root_window          (GtkWidget *widget);
GdkScreen*          gtk_widget_get_screen               (GtkWidget *widget);
gboolean            gtk_widget_has_screen               (GtkWidget *widget);
void                gtk_widget_get_size_request         (GtkWidget *widget,
                                                         gint *width,
                                                         gint *height);
#define             gtk_widget_pop_visual               ()
#define             gtk_widget_push_visual              (visual)
void                gtk_widget_set_child_visible        (GtkWidget *widget,
                                                         gboolean is_visible);
#define             gtk_widget_set_default_visual       (visual)
void                gtk_widget_set_size_request         (GtkWidget *widget,
                                                         gint width,
                                                         gint height);
#define             gtk_widget_set_visual               (widget,visual)
void                gtk_widget_thaw_child_notify        (GtkWidget *widget);
void                gtk_widget_set_no_show_all          (GtkWidget *widget,
                                                         gboolean no_show_all);
gboolean            gtk_widget_get_no_show_all          (GtkWidget *widget);
GList*              gtk_widget_list_mnemonic_labels     (GtkWidget *widget);
void                gtk_widget_add_mnemonic_label       (GtkWidget *widget,
                                                         GtkWidget *label);
void                gtk_widget_remove_mnemonic_label    (GtkWidget *widget,
                                                         GtkWidget *label);
GtkAction*          gtk_widget_get_action               (GtkWidget *widget);
gboolean            gtk_widget_is_composited            (GtkWidget *widget);

GtkRequisition*     gtk_requisition_copy                (const GtkRequisition *requisition);
void                gtk_requisition_free                (GtkRequisition *requisition);

Object Hierarchy

  GObject
   +----GInitiallyUnowned
         +----GtkObject
               +----GtkWidget
                     +----GtkContainer
                     +----GtkMisc
                     +----GtkCalendar
                     +----GtkCellView
                     +----GtkDrawingArea
                     +----GtkEntry
                     +----GtkRuler
                     +----GtkRange
                     +----GtkSeparator
                     +----GtkInvisible
                     +----GtkOldEditable
                     +----GtkPreview
                     +----GtkProgress

Known Derived Interfaces

GtkWidget is required by GtkFileChooser and GtkCellEditable.

Implemented Interfaces

GtkWidget implements AtkImplementorIface.

Properties

  "app-paintable"            gboolean              : Read / Write
  "can-default"              gboolean              : Read / Write
  "can-focus"                gboolean              : Read / Write
  "composite-child"          gboolean              : Read
  "events"                   GdkEventMask          : Read / Write
  "extension-events"         GdkExtensionMode      : Read / Write
  "has-default"              gboolean              : Read / Write
  "has-focus"                gboolean              : Read / Write
  "height-request"           gint                  : Read / Write
  "is-focus"                 gboolean              : Read / Write
  "name"                     gchararray            : Read / Write
  "no-show-all"              gboolean              : Read / Write
  "parent"                   GtkContainer          : Read / Write
  "receives-default"         gboolean              : Read / Write
  "sensitive"                gboolean              : Read / Write
  "style"                    GtkStyle              : Read / Write
  "visible"                  gboolean              : Read / Write
  "width-request"            gint                  : Read / Write

Style Properties

  "cursor-aspect-ratio"      gfloat                : Read
  "cursor-color"             GdkColor              : Read
  "draw-border"              GtkBorder             : Read
  "focus-line-pattern"       gchararray            : Read
  "focus-line-width"         gint                  : Read
  "focus-padding"            gint                  : Read
  "interior-focus"           gboolean              : Read
  "link-color"               GdkColor              : Read
  "scroll-arrow-hlength"     gint                  : Read
  "scroll-arrow-vlength"     gint                  : Read
  "secondary-cursor-color"   GdkColor              : Read
  "separator-height"         gint                  : Read
  "separator-width"          gint                  : Read
  "visited-link-color"       GdkColor              : Read
  "wide-separators"          gboolean              : Read

Signals

  "accel-closures-changed"
  "button-press-event"                             : Run Last
  "button-release-event"                           : Run Last
  "can-activate-accel"                             : Run Last
  "child-notify"                                   : Run First / No Recursion / Has Details / No Hooks
  "client-event"                                   : Run Last
  "composited-changed"                             : Run Last / Action
  "configure-event"                                : Run Last
  "delete-event"                                   : Run Last
  "destroy-event"                                  : Run Last
  "direction-changed"                              : Run First
  "drag-begin"                                     : Run Last
  "drag-data-delete"                               : Run Last
  "drag-data-get"                                  : Run Last
  "drag-data-received"                             : Run Last
  "drag-drop"                                      : Run Last
  "drag-end"                                       : Run Last
  "drag-leave"                                     : Run Last
  "drag-motion"                                    : Run Last
  "enter-notify-event"                             : Run Last
  "event"                                          : Run Last
  "event-after"
  "expose-event"                                   : Run Last
  "focus"                                          : Run Last
  "focus-in-event"                                 : Run Last
  "focus-out-event"                                : Run Last
  "grab-broken-event"                              : Run Last
  "grab-focus"                                     : Run Last / Action
  "grab-notify"                                    : Run First
  "hide"                                           : Run First
  "hierarchy-changed"                              : Run Last
  "key-press-event"                                : Run Last
  "key-release-event"                              : Run Last
  "leave-notify-event"                             : Run Last
  "map"                                            : Run First
  "map-event"                                      : Run Last
  "mnemonic-activate"                              : Run Last
  "motion-notify-event"                            : Run Last
  "no-expose-event"                                : Run Last
  "parent-set"                                     : Run First
  "popup-menu"                                     : Run Last / Action
  "property-notify-event"                          : Run Last
  "proximity-in-event"                             : Run Last
  "proximity-out-event"                            : Run Last
  "realize"                                        : Run First
  "screen-changed"                                 : Run Last
  "scroll-event"                                   : Run Last
  "selection-clear-event"                          : Run Last
  "selection-get"                                  : Run Last
  "selection-notify-event"                         : Run Last
  "selection-received"                             : Run Last
  "selection-request-event"                        : Run Last
  "show"                                           : Run First
  "show-help"                                      : Run Last / Action
  "size-allocate"                                  : Run First
  "size-request"                                   : Run First
  "state-changed"                                  : Run First
  "style-set"                                      : Run First
  "unmap"                                          : Run First
  "unmap-event"                                    : Run Last
  "unrealize"                                      : Run Last
  "visibility-notify-event"                        : Run Last
  "window-state-event"                             : Run Last

Description

GtkWidget introduces style properties - these are basically object properties that are stored not on the object, but in the style object associated to the widget. Style properties are set in resource files. This mechanism is used for configuring such things as the location of the scrollbar arrows through the theme, giving theme authors more control over the look of applications without the need to write a theme engine in C.

Use gtk_widget_class_install_style_property() to install style properties for
a widget class, gtk_widget_class_find_style_property() or
gtk_widget_class_list_style_properties() to get information about existing
style properties and gtk_widget_style_get_property(), gtk_widget_style_get() or
gtk_widget_style_get_valist() to obtain the value of a style property.

Details

GtkWidget

typedef struct {
  /* The style for the widget. The style contains the
   *  colors the widget should be drawn in for each state
   *  along with graphics contexts used to draw with and
   *  the font to use for text.
   */
  GtkStyle *style;

  /* The widget's desired size.
   */
  GtkRequisition requisition;

  /* The widget's allocated size.
   */
  GtkAllocation allocation;

  /* The widget's window or its parent window if it does
   *  not have a window. (Which will be indicated by the
   *  GTK_NO_WINDOW flag being set).
   */
  GdkWindow *window;

  /* The widget's parent.
   */
  GtkWidget *parent;
} GtkWidget;

GtkStyle *style; | The style for the widget. The style contains the colors the widget should be drawn in for each state along with graphics contexts used to draw with and the font to use for text.
GtkRequisition requisition; | The widget's desired size.
GtkAllocation allocation; | The widget's allocated size.
GdkWindow *window; | The widget's window or its parent window if it does not have a window. (Which will be indicated by the GTK_NO_WINDOW flag being set).
GtkWidget *parent; |

GtkWidgetClass

typedef struct {
  /* The object class structure needs to be the first
   *  element in the widget class structure in order for
   *  the class mechanism to work correctly. This allows a
   *  GtkWidgetClass pointer to be cast to a GtkObjectClass
   *  pointer.
   */
  GtkObjectClass parent_class;

  guint activate_signal;

  guint set_scroll_adjustments_signal;
} GtkWidgetClass;

activate_signal The signal to emit when a widget of this class is activated, gtk_widget_activate() handles the emission. Implementation of this signal is optional.

set_scroll_adjustment_signal This signal is emitted when a widget of this class is added to a scrolling aware parent, gtk_widget_set_scroll_adjustments() handles the emission. Implementation of this signal is optional.

enum GtkWidgetFlags

typedef enum
{
  GTK_TOPLEVEL         = 1 << 4,
  GTK_NO_WINDOW        = 1 << 5,
  GTK_REALIZED         = 1 << 6,
  GTK_MAPPED           = 1 << 7,
  GTK_VISIBLE          = 1 << 8,
  GTK_SENSITIVE        = 1 << 9,
  GTK_PARENT_SENSITIVE = 1 << 10,
  GTK_CAN_FOCUS        = 1 << 11,
  GTK_HAS_FOCUS        = 1 << 12,

  /* widget is allowed to receive the default via gtk_widget_grab_default
   * and will reserve space to draw the default if possible
   */
  GTK_CAN_DEFAULT      = 1 << 13,

  /* the widget currently is receiving the default action and should be drawn
   * appropriately if possible
   */
  GTK_HAS_DEFAULT      = 1 << 14,

  GTK_HAS_GRAB	       = 1 << 15,
  GTK_RC_STYLE	       = 1 << 16,
  GTK_COMPOSITE_CHILD  = 1 << 17,
  GTK_NO_REPARENT      = 1 << 18,
  GTK_APP_PAINTABLE    = 1 << 19,

  /* the widget when focused will receive the default action and have
   * HAS_DEFAULT set even if there is a different widget set as default
   */
  GTK_RECEIVES_DEFAULT = 1 << 20,

  GTK_DOUBLE_BUFFERED  = 1 << 21,
  GTK_NO_SHOW_ALL      = 1 << 22
} GtkWidgetFlags;

Tells about certain properties of the widget.

GTK_TOPLEVEL | widgets without a real parent, as there are GtkWindows and GtkMenus have this flag set throughout their lifetime. Toplevel widgets always contain their own GdkWindow.
GTK_NO_WINDOW | Indicative for a widget that does not provide its own GdkWindow. Visible action (e.g. drawing) is performed on the parent's GdkWindow.
GTK_REALIZED | Set by gtk_widget_realize(), unset by gtk_widget_unrealize(). A realized widget has an associated GdkWindow.
GTK_MAPPED | Set by gtk_widget_map(), unset by gtk_widget_unmap(). Only realized widgets can be mapped. It means that gdk_window_show() has been called on the widgets window(s).
GTK_VISIBLE | Set by gtk_widget_show(), unset by gtk_widget_hide(). Implies that a widget will be mapped as soon as its parent is mapped.
GTK_SENSITIVE | Set and unset by gtk_widget_set_sensitive(). The sensitivity of a widget determines whether it will receive certain events (e.g. button or key presses). One premise for the widget's sensitivity is to have this flag set.
GTK_PARENT_SENSITIVE | Set and unset by gtk_widget_set_sensitive() operations on the parents of the widget. This is the second premise for the widget's sensitivity. Once it has GTK_SENSITIVE and GTK_PARENT_SENSITIVE set, its state is effectively sensitive. This is expressed (and can be examined) by the GTK_WIDGET_IS_SENSITIVE macro.
GTK_CAN_FOCUS | Determines whether a widget is able to handle focus grabs.
GTK_HAS_FOCUS | Set by gtk_widget_grab_focus() for widgets that also have GTK_CAN_FOCUS set. The flag will be unset once another widget grabs the focus.
GTK_CAN_DEFAULT | The widget is allowed to receive the default action via gtk_widget_grab_default().
GTK_HAS_DEFAULT | The widget currently is receiving the default action.
GTK_HAS_GRAB | Set by gtk_grab_add(), unset by gtk_grab_remove(). It means that the widget is in the grab_widgets stack, and will be the preferred one for receiving events other than ones of cosmetic value.
GTK_RC_STYLE | Indicates that the widget's style has been looked up through the rc mechanism. It does not imply that the widget actually had a style defined through the rc mechanism.
GTK_COMPOSITE_CHILD | Indicates that the widget is a composite child of its parent; see gtk_widget_push_composite_child(), gtk_widget_pop_composite_child().
GTK_NO_REPARENT | Unused since before GTK+ 1.2, will be removed in a future version.
GTK_APP_PAINTABLE | Set and unset by gtk_widget_set_app_paintable(). Must be set on widgets whose window the application directly draws on, in order to keep GTK+ from overwriting the drawn stuff.
GTK_RECEIVES_DEFAULT | The widget when focused will receive the default action and have GTK_HAS_DEFAULT set even if there is a different widget set as default.
GTK_DOUBLE_BUFFERED | Set and unset by gtk_widget_set_double_buffered(). Indicates that exposes done on the widget should be double-buffered.
GTK_NO_SHOW_ALL |

GTK_WIDGET_TYPE()

#define GTK_WIDGET_TYPE(wid)		  (GTK_OBJECT_TYPE (wid))

Gets the type of a widget.

wid : a GtkWidget.

GTK_WIDGET_STATE()

#define GTK_WIDGET_STATE(wid)		  (GTK_WIDGET (wid)->state)

Returns the current state of the widget, as a GtkStateType.

wid : a GtkWidget.

GTK_WIDGET_SAVED_STATE()

#define GTK_WIDGET_SAVED_STATE(wid)	  (GTK_WIDGET (wid)->saved_state)

Returns the saved state of the widget, as a GtkStateType.

The saved state will be restored when a widget gets sensitive again, after it has been made insensitive with gtk_widget_set_state() or gtk_widget_set_sensitive().

wid : a GtkWidget.

GTK_WIDGET_FLAGS()

#define GTK_WIDGET_FLAGS(wid)		  (GTK_OBJECT_FLAGS (wid))

Returns the widget flags from wid.

wid : a GtkWidget.

GTK_WIDGET_TOPLEVEL()

#define GTK_WIDGET_TOPLEVEL(wid)	  ((GTK_WIDGET_FLAGS (wid) & GTK_TOPLEVEL) != 0)

Evaluates to TRUE if the widget is a toplevel widget.

wid : a GtkWidget.

GTK_WIDGET_NO_WINDOW()

#define GTK_WIDGET_NO_WINDOW(wid)	  ((GTK_WIDGET_FLAGS (wid) & GTK_NO_WINDOW) != 0)

Evaluates to TRUE if the widget doesn't have an own GdkWindow.

wid : a GtkWidget.

GTK_WIDGET_REALIZED()

#define GTK_WIDGET_REALIZED(wid)	  ((GTK_WIDGET_FLAGS (wid) & GTK_REALIZED) != 0)

Evaluates to TRUE if the widget is realized.

wid : a GtkWidget.

GTK_WIDGET_MAPPED()

#define GTK_WIDGET_MAPPED(wid)		  ((GTK_WIDGET_FLAGS (wid) & GTK_MAPPED) != 0)

Evaluates to TRUE if the widget is mapped.

wid : a GtkWidget.

GTK_WIDGET_VISIBLE()

#define GTK_WIDGET_VISIBLE(wid)		  ((GTK_WIDGET_FLAGS (wid) & GTK_VISIBLE) != 0)

Evaluates to TRUE if the widget is visible.

wid : a GtkWidget.

GTK_WIDGET_DRAWABLE()

#define GTK_WIDGET_DRAWABLE(wid)	  (GTK_WIDGET_VISIBLE (wid) && GTK_WIDGET_MAPPED (wid))

Evaluates to TRUE if the widget is mapped and visible.

wid : a GtkWidget.

GTK_WIDGET_SENSITIVE()

#define GTK_WIDGET_SENSITIVE(wid)	  ((GTK_WIDGET_FLAGS (wid) & GTK_SENSITIVE) != 0)

Evaluates to TRUE if the GTK_SENSITIVE flag has be set on the widget.

wid : a GtkWidget.

GTK_WIDGET_PARENT_SENSITIVE()

#define GTK_WIDGET_PARENT_SENSITIVE(wid)  ((GTK_WIDGET_FLAGS (wid) & GTK_PARENT_SENSITIVE) != 0)

Evaluates to TRUE if the GTK_PARENT_SENSITIVE flag has be set on the widget.

wid : a GtkWidget.

GTK_WIDGET_IS_SENSITIVE()

#define             GTK_WIDGET_IS_SENSITIVE(wid)

Evaluates to TRUE if the widget is effectively sensitive.

wid : a GtkWidget.

GTK_WIDGET_CAN_FOCUS()

#define GTK_WIDGET_CAN_FOCUS(wid)	  ((GTK_WIDGET_FLAGS (wid) & GTK_CAN_FOCUS) != 0)

Evaluates to TRUE if the widget is able to handle focus grabs.

wid : a GtkWidget.

GTK_WIDGET_HAS_FOCUS()

#define GTK_WIDGET_HAS_FOCUS(wid)	  ((GTK_WIDGET_FLAGS (wid) & GTK_HAS_FOCUS) != 0)

Evaluates to TRUE if the widget has grabbed the focus and no other widget has done so more recently.

wid : a GtkWidget.

GTK_WIDGET_CAN_DEFAULT()

#define GTK_WIDGET_CAN_DEFAULT(wid)	  ((GTK_WIDGET_FLAGS (wid) & GTK_CAN_DEFAULT) != 0)

Evaluates to TRUE if the widget is allowed to receive the default action via gtk_widget_grab_default().

wid : a GtkWidget.

GTK_WIDGET_RECEIVES_DEFAULT()

#define GTK_WIDGET_RECEIVES_DEFAULT(wid)  ((GTK_WIDGET_FLAGS (wid) & GTK_RECEIVES_DEFAULT) != 0)

Evaluates to TRUE if the widget when focused will receive the default action even if there is a different widget set as default.

wid : a GtkWidget.

GTK_WIDGET_HAS_DEFAULT()

#define GTK_WIDGET_HAS_DEFAULT(wid)	  ((GTK_WIDGET_FLAGS (wid) & GTK_HAS_DEFAULT) != 0)

Evaluates to TRUE if the widget currently is receiving the default action.

wid : a GtkWidget.

GTK_WIDGET_HAS_GRAB()

#define GTK_WIDGET_HAS_GRAB(wid)	  ((GTK_WIDGET_FLAGS (wid) & GTK_HAS_GRAB) != 0)

Evaluates to TRUE if the widget is in the grab_widgets stack, and will be the preferred one for receiving events other than ones of cosmetic value.

wid : a GtkWidget.

GTK_WIDGET_RC_STYLE()

#define GTK_WIDGET_RC_STYLE(wid)	  ((GTK_WIDGET_FLAGS (wid) & GTK_RC_STYLE) != 0)

Evaluates to TRUE if the widget's style has been looked up through the rc mechanism.

wid : a GtkWidget.

GTK_WIDGET_COMPOSITE_CHILD()

#define GTK_WIDGET_COMPOSITE_CHILD(wid)	  ((GTK_WIDGET_FLAGS (wid) & GTK_COMPOSITE_CHILD) != 0)

Evaluates to TRUE if the widget is a composite child of its parent.

wid : a GtkWidget.

GTK_WIDGET_APP_PAINTABLE()

#define GTK_WIDGET_APP_PAINTABLE(wid)	  ((GTK_WIDGET_FLAGS (wid) & GTK_APP_PAINTABLE) != 0)

Evaluates to TRUE if the GTK_APP_PAINTABLE flag has been set on the widget.

wid : a GtkWidget.

GTK_WIDGET_DOUBLE_BUFFERED()

#define GTK_WIDGET_DOUBLE_BUFFERED(wid)	  ((GTK_WIDGET_FLAGS (wid) & GTK_DOUBLE_BUFFERED) != 0)

Evaluates to TRUE if the GTK_DOUBLE_BUFFERED flag has been set on the widget.

wid : a GtkWidget.

GTK_WIDGET_SET_FLAGS()

#define GTK_WIDGET_SET_FLAGS(wid,flag)	  G_STMT_START{ (GTK_WIDGET_FLAGS (wid) |= (flag)); }G_STMT_END

Turns on certain widget flags.

wid : | a GtkWidget.
flag : | the flags to set.

GTK_WIDGET_UNSET_FLAGS()

#define GTK_WIDGET_UNSET_FLAGS(wid,flag)  G_STMT_START{ (GTK_WIDGET_FLAGS (wid) &= ~(flag)); }G_STMT_END

Turns off certain widget flags.

wid : | a GtkWidget.
flag : | the flags to unset.

GtkCallback ()

void                (*GtkCallback)                      (GtkWidget *widget,
                                                         gpointer data);

The type of the callback functions used for e.g. iterating over the children of a container, see gtk_container_foreach().

widget : | the widget to operate on
data : | user-supplied data

GtkRequisition

typedef struct {
  gint width;
  gint height;
} GtkRequisition;

A GtkRequisition represents the desired size of a widget. See the section called “Size Requisition” for more information.

gint width; | the widget's desired width
gint height; | the widget's desired height

struct GtkAllocation

struct GtkAllocation {
  gint x;
  gint y;
  gint width;
  gint height;
};

A GtkAllocation of a widget represents region which has been allocated to the widget by its parent. It is a subregion of its parents allocation. See the section called “Size Allocation” for more information.

gint x; | the X position of the widget's area relative to its parents allocation.
gint y; | the Y position of the widget's area relative to its parents allocation.
gint width; | the width of the widget's allocated area.
gint height; | the height of the widget's allocated area.

GtkSelectionData

typedef struct {
  GdkAtom	selection;
  GdkAtom	target;
  GdkAtom	type;
  gint		format;
  guchar       *data;
  gint		length;
  GdkDisplay   *display;
} GtkSelectionData;

GtkWidgetAuxInfo

typedef struct {
  gint x;
  gint y;
  gint width;
  gint height;
  guint x_set : 1;
  guint y_set : 1;
} GtkWidgetAuxInfo;

GtkWidgetShapeInfo

typedef struct {
  gint16     offset_x;
  gint16     offset_y;
  GdkBitmap *shape_mask;
} GtkWidgetShapeInfo;

enum GtkWidgetHelpType

typedef enum
{
  GTK_WIDGET_HELP_TOOLTIP,
  GTK_WIDGET_HELP_WHATS_THIS
} GtkWidgetHelpType;

gtk_widget_new ()

GtkWidget*          gtk_widget_new                      (GType type,
                                                         const gchar *first_property_name,
                                                         ...);

This is a convenience function for creating a widget and setting its properties in one go. For example you might write: gtk_widget_new (GTK_TYPE_LABEL, "label", "Hello World", "xalign", 0.0, NULL) to create a left-aligned label. Equivalent to g_object_new(), but returns a widget so you don't have to cast the object yourself.

type : | type ID of the widget to create
first_property_name : | name of first property to set
... : | value of first property, followed by more properties, NULL-terminated
Returns : | a new GtkWidget of type widget_type

gtk_widget_ref ()

GtkWidget*          gtk_widget_ref                      (GtkWidget *widget);

Adds a reference to a widget. This function is exactly the same as calling g_object_ref(), and exists mostly for historical reasons. It can still be convenient to avoid casting a widget to a GObject, it saves a small amount of typing.

widget : | a GtkWidget
Returns : | the widget that was referenced

gtk_widget_unref ()

void                gtk_widget_unref                    (GtkWidget *widget);

Inverse of gtk_widget_ref(). Equivalent to g_object_unref().

widget : a GtkWidget

gtk_widget_destroy ()

void                gtk_widget_destroy                  (GtkWidget *widget);

Destroys a widget. Equivalent to gtk_object_destroy(), except that you don't have to cast the widget to GtkObject. When a widget is destroyed, it will break any references it holds to other objects. If the widget is inside a container, the widget will be removed from the container. If the widget is a toplevel (derived from GtkWindow), it will be removed from the list of toplevels, and the reference GTK+ holds to it will be removed. Removing a widget from its container or the list of toplevels results in the widget being finalized, unless you've added additional references to the widget with g_object_ref().

In most cases, only toplevel widgets (windows) require explicit destruction, because when you destroy a toplevel its children will be destroyed as well.

widget : a GtkWidget

gtk_widget_destroyed ()

void                gtk_widget_destroyed                (GtkWidget *widget,
                                                         GtkWidget **widget_pointer);

This function sets *widget_pointer to NULL if widget_pointer != NULL. It's intended to be used as a callback connected to the "destroy" signal of a widget. You connect gtk_widget_destroyed() as a signal handler, and pass the address of your widget variable as user data. Then when the widget is destroyed, the variable will be set to NULL. Useful for example to avoid multiple copies of the same dialog.

widget : | a GtkWidget
widget_pointer : | address of a variable that contains widget

gtk_widget_set ()

void                gtk_widget_set                      (GtkWidget *widget,
                                                         const gchar *first_property_name,
                                                         ...);

Warning

gtk_widget_set is deprecated and should not be used in newly-written code.

Like g_object_set() - there's no reason to use this instead of g_object_set().

widget : | a GtkWidget
first_property_name : | name of first property to set
... : | value of first property, followed by more properties, NULL-terminated

gtk_widget_unparent ()

void                gtk_widget_unparent                 (GtkWidget *widget);

This function is only for use in widget implementations. Should be called by implementations of the remove method on GtkContainer, to dissociate a child from the container.

widget : a GtkWidget

gtk_widget_show ()

void                gtk_widget_show                     (GtkWidget *widget);

Flags a widget to be displayed. Any widget that isn't shown will not appear on the screen. If you want to show all the widgets in a container, it's easier to call gtk_widget_show_all() on the container, instead of individually showing the widgets.

Remember that you have to show the containers containing a widget, in addition to the widget itself, before it will appear onscreen.

When a toplevel container is shown, it is immediately realized and mapped; other shown widgets are realized and mapped when their toplevel container is realized and mapped.

widget : a GtkWidget

gtk_widget_show_now ()

void                gtk_widget_show_now                 (GtkWidget *widget);

Shows a widget. If the widget is an unmapped toplevel widget (i.e. a GtkWindow that has not yet been shown), enter the main loop and wait for the window to actually be mapped. Be careful; because the main loop is running, anything can happen during this function.

widget : a GtkWidget

gtk_widget_hide ()

void                gtk_widget_hide                     (GtkWidget *widget);

Reverses the effects of gtk_widget_show(), causing the widget to be hidden (invisible to the user).

widget : a GtkWidget

gtk_widget_show_all ()

void                gtk_widget_show_all                 (GtkWidget *widget);

Recursively shows a widget, and any child widgets (if the widget is a container).

widget : a GtkWidget

gtk_widget_hide_all ()

void                gtk_widget_hide_all                 (GtkWidget *widget);

Recursively hides a widget and any child widgets.

widget : a GtkWidget

gtk_widget_map ()

void                gtk_widget_map                      (GtkWidget *widget);

This function is only for use in widget implementations. Causes a widget to be mapped if it isn't already.

widget : a GtkWidget

gtk_widget_unmap ()

void                gtk_widget_unmap                    (GtkWidget *widget);

This function is only for use in widget implementations. Causes a widget to be unmapped if it's currently mapped.

widget : a GtkWidget

gtk_widget_realize ()

void                gtk_widget_realize                  (GtkWidget *widget);

Creates the GDK (windowing system) resources associated with a widget. For example, widget->window will be created when a widget is realized. Normally realization happens implicitly; if you show a widget and all its parent containers, then the widget will be realized and mapped automatically.

Realizing a widget requires all the widget's parent widgets to be realized; calling gtk_widget_realize() realizes the widget's parents in addition to widget itself. If a widget is not yet inside a toplevel window when you realize it, bad things will happen.

This function is primarily used in widget implementations, and isn't very useful otherwise. Many times when you think you might need it, a better approach is to connect to a signal that will be called after the widget is realized automatically, such as "expose_event". Or simply g_signal_connect_after() to the "realize" signal.

widget : a GtkWidget

gtk_widget_unrealize ()

void                gtk_widget_unrealize                (GtkWidget *widget);

This function is only useful in widget implementations. Causes a widget to be unrealized (frees all GDK resources associated with the widget, such as widget->window).

widget : a GtkWidget

gtk_widget_queue_draw ()

void                gtk_widget_queue_draw               (GtkWidget *widget);

Equivalent to calling gtk_widget_queue_draw_area() for the entire area of a widget.

widget : a GtkWidget

gtk_widget_queue_resize ()

void                gtk_widget_queue_resize             (GtkWidget *widget);

This function is only for use in widget implementations. Flags a widget to have its size renegotiated; should be called when a widget for some reason has a new size request. For example, when you change the text in a GtkLabel, GtkLabel queues a resize to ensure there's enough space for the new text.

widget : a GtkWidget

gtk_widget_queue_resize_no_redraw ()

void                gtk_widget_queue_resize_no_redraw   (GtkWidget *widget);

This function works like gtk_widget_queue_resize(), except that the widget is not invalidated.

widget : a GtkWidget

Since 2.4

gtk_widget_draw ()

void                gtk_widget_draw                     (GtkWidget *widget,
                                                         GdkRectangle *area);

Warning

gtk_widget_draw is deprecated and should not be used in newly-written code.

In GTK+ 1.2, this function would immediately render the region area of a widget, by invoking the virtual draw method of a widget. In GTK+ 2.0, the draw method is gone, and instead gtk_widget_draw() simply invalidates the specified region of the widget, then updates the invalid region of the widget immediately. Usually you don't want to update the region immediately for performance reasons, so in general gtk_widget_queue_draw_area() is a better choice if you want to draw a region of a widget.

widget : | a GtkWidget
area : | area to draw

gtk_widget_size_request ()

void                gtk_widget_size_request             (GtkWidget *widget,
                                                         GtkRequisition *requisition);

This function is typically used when implementing a GtkContainer subclass. Obtains the preferred size of a widget. The container uses this information to arrange its child widgets and decide what size allocations to give them with gtk_widget_size_allocate().

You can also call this function from an application, with some caveats. Most notably, getting a size request requires the widget to be associated with a screen, because font information may be needed. Multihead-aware applications should keep this in mind.

Also remember that the size request is not necessarily the size a widget will actually be allocated.

See also gtk_widget_get_child_requisition().

widget : | a GtkWidget
requisition : | a GtkRequisition to be filled in

gtk_widget_get_child_requisition ()

void                gtk_widget_get_child_requisition    (GtkWidget *widget,
                                                         GtkRequisition *requisition);

This function is only for use in widget implementations. Obtains widget->requisition, unless someone has forced a particular geometry on the widget (e.g. with gtk_widget_set_usize()), in which case it returns that geometry instead of the widget's requisition.

This function differs from gtk_widget_size_request() in that it retrieves the last size request value from widget->requisition, while gtk_widget_size_request() actually calls the "size_request" method on widget to compute the size request and fill in widget->requisition, and only then returns widget->requisition.

Because this function does not call the "size_request" method, it can only be used when you know that widget->requisition is up-to-date, that is, gtk_widget_size_request() has been called since the last time a resize was queued. In general, only container implementations have this information; applications should use gtk_widget_size_request().

widget : | a GtkWidget
requisition : | a GtkRequisition to be filled in

gtk_widget_size_allocate ()

void                gtk_widget_size_allocate            (GtkWidget *widget,
                                                         GtkAllocation *allocation);

This function is only used by GtkContainer subclasses, to assign a size and position to their child widgets.

widget : | a GtkWidget
allocation : | position and size to be allocated to widget

gtk_widget_add_accelerator ()

void                gtk_widget_add_accelerator          (GtkWidget *widget,
                                                         const gchar *accel_signal,
                                                         GtkAccelGroup *accel_group,
                                                         guint accel_key,
                                                         GdkModifierType accel_mods,
                                                         GtkAccelFlags accel_flags);

Installs an accelerator for this widget in accel_group that causes accel_signal to be emitted if the accelerator is activated. The accel_group needs to be added to the widget's toplevel via gtk_window_add_accel_group(), and the signal must be of type G_RUN_ACTION. Accelerators added through this function are not user changeable during runtime. If you want to support accelerators that can be changed by the user, use gtk_accel_map_add_entry() and gtk_widget_set_accel_path() or gtk_menu_item_set_accel_path() instead.

widget : | widget to install an accelerator on
accel_signal : | widget signal to emit on accelerator activation
accel_group : | accel group for this widget, added to its toplevel
accel_key : | GDK keyval of the accelerator
accel_mods : | modifier key combination of the accelerator
accel_flags : | flag accelerators, e.g. GTK_ACCEL_VISIBLE

gtk_widget_remove_accelerator ()

gboolean            gtk_widget_remove_accelerator       (GtkWidget *widget,
                                                         GtkAccelGroup *accel_group,
                                                         guint accel_key,
                                                         GdkModifierType accel_mods);

Removes an accelerator from widget, previously installed with gtk_widget_add_accelerator().

widget : | widget to install an accelerator on
accel_group : | accel group for this widget
accel_key : | GDK keyval of the accelerator
accel_mods : | modifier key combination of the accelerator
Returns : | whether an accelerator was installed and could be removed

gtk_widget_set_accel_path ()

void                gtk_widget_set_accel_path           (GtkWidget *widget,
                                                         const gchar *accel_path,
                                                         GtkAccelGroup *accel_group);

Given an accelerator group, accel_group, and an accelerator path, accel_path, sets up an accelerator in accel_group so whenever the key binding that is defined for accel_path is pressed, widget will be activated. This removes any accelerators (for any accelerator group) installed by previous calls to gtk_widget_set_accel_path(). Associating accelerators with paths allows them to be modified by the user and the modifications to be saved for future use. (See gtk_accel_map_save().)

This function is a low level function that would most likely be used by a menu creation system like GtkItemFactory. If you use GtkItemFactory, setting up accelerator paths will be done automatically.

Even when you you aren't using GtkItemFactory, if you only want to set up accelerators on menu items gtk_menu_item_set_accel_path() provides a somewhat more convenient interface.

widget : | a GtkWidget
accel_path : | path used to look up the accelerator
accel_group : | a GtkAccelGroup.

gtk_widget_list_accel_closures ()

GList*              gtk_widget_list_accel_closures      (GtkWidget *widget);

Lists the closures used by widget for accelerator group connections with gtk_accel_group_connect_by_path() or gtk_accel_group_connect(). The closures can be used to monitor accelerator changes on widget, by connecting to the ::accel_changed signal of the GtkAccelGroup of a closure which can be found out with gtk_accel_group_from_accel_closure().

widget : | widget to list accelerator closures for
Returns : | a newly allocated GList of closures

gtk_widget_can_activate_accel ()

gboolean            gtk_widget_can_activate_accel       (GtkWidget *widget,
                                                         guint signal_id);

Determines whether an accelerator that activates the signal identified by signal_id can currently be activated. This is done by emitting the GtkWidget::can-activate-accel signal on widget; if the signal isn't overridden by a handler or in a derived widget, then the default check is that the widget must be sensitive, and the widget and all its ancestors mapped.

widget : | a GtkWidget
signal_id : | the ID of a signal installed on widget
Returns : | TRUE if the accelerator can be activated.

Since 2.4

gtk_widget_event ()

gboolean            gtk_widget_event                    (GtkWidget *widget,
                                                         GdkEvent *event);

Rarely-used function. This function is used to emit the event signals on a widget (those signals should never be emitted without using this function to do so). If you want to synthesize an event though, don't use this function; instead, use gtk_main_do_event() so the event will behave as if it were in the event queue. Don't synthesize expose events; instead, use gdk_window_invalidate_rect() to invalidate a region of the window.

widget : | a GtkWidget
event : | a GdkEvent
Returns : | return from the event signal emission (TRUE if the event was handled)

gtk_widget_activate ()

gboolean            gtk_widget_activate                 (GtkWidget *widget);

For widgets that can be "activated" (buttons, menu items, etc.) this function activates them. Activation is what happens when you press Enter on a widget during key navigation. If widget isn't activatable, the function returns FALSE.

widget : | a GtkWidget that's activatable
Returns : | TRUE if the widget was activatable

gtk_widget_reparent ()

void                gtk_widget_reparent                 (GtkWidget *widget,
                                                         GtkWidget *new_parent);

Moves a widget from one GtkContainer to another, handling reference count issues to avoid destroying the widget.

widget : | a GtkWidget
new_parent : | a GtkContainer to move the widget into

gtk_widget_intersect ()

gboolean            gtk_widget_intersect                (GtkWidget *widget,
                                                         GdkRectangle *area,
                                                         GdkRectangle *intersection);

Computes the intersection of a widget's area and area, storing the intersection in intersection, and returns TRUE if there was an intersection. intersection may be NULL if you're only interested in whether there was an intersection.

widget : | a GtkWidget
area : | a rectangle
intersection : | rectangle to store intersection of widget and area
Returns : | TRUE if there was an intersection

gtk_widget_is_focus ()

gboolean            gtk_widget_is_focus                 (GtkWidget *widget);

Determines if the widget is the focus widget within its toplevel. (This does not mean that the HAS_FOCUS flag is necessarily set; HAS_FOCUS will only be set if the toplevel widget additionally has the global input focus.)

widget : | a GtkWidget
Returns : | TRUE if the widget is the focus widget.

gtk_widget_grab_focus ()

void                gtk_widget_grab_focus               (GtkWidget *widget);

Causes widget to have the keyboard focus for the GtkWindow it's inside. widget must be a focusable widget, such as a GtkEntry; something like GtkFrame won't work. (More precisely, it must have the GTK_CAN_FOCUS flag set.)

widget : a GtkWidget

gtk_widget_grab_default ()

void                gtk_widget_grab_default             (GtkWidget *widget);

Causes widget to become the default widget. widget must have the GTK_CAN_DEFAULT flag set; typically you have to set this flag yourself by calling GTK_WIDGET_SET_FLAGS (widget, GTK_CAN_DEFAULT). The default widget is activated when the user presses Enter in a window. Default widgets must be activatable, that is, gtk_widget_activate() should affect them.

widget : a GtkWidget

gtk_widget_set_name ()

void                gtk_widget_set_name                 (GtkWidget *widget,
                                                         const gchar *name);

Widgets can be named, which allows you to refer to them from a gtkrc file. You can apply a style to widgets with a particular name in the gtkrc file. See the documentation for gtkrc files (on the same page as the docs for GtkRcStyle).

Note that widget names are separated by periods in paths (see gtk_widget_path()), so names with embedded periods may cause confusion.

widget : | a GtkWidget
name : | name for the widget

gtk_widget_get_name ()

const gchar*        gtk_widget_get_name                 (GtkWidget *widget);

Retrieves the name of a widget. See gtk_widget_set_name() for the significance of widget names.

widget : | a GtkWidget
Returns : | name of the widget. This string is owned by GTK+ and should not be modified or freed

gtk_widget_set_state ()

void                gtk_widget_set_state                (GtkWidget *widget,
                                                         GtkStateType state);

This function is for use in widget implementations. Sets the state of a widget (insensitive, prelighted, etc.) Usually you should set the state using wrapper functions such as gtk_widget_set_sensitive().

widget : | a GtkWidget
state : | new state for widget

gtk_widget_set_sensitive ()

void                gtk_widget_set_sensitive            (GtkWidget *widget,
                                                         gboolean sensitive);

Sets the sensitivity of a widget. A widget is sensitive if the user can interact with it. Insensitive widgets are "grayed out" and the user can't interact with them. Insensitive widgets are known as "inactive", "disabled", or "ghosted" in some other toolkits.

widget : | a GtkWidget
sensitive : | TRUE to make the widget sensitive

gtk_widget_set_parent ()

void                gtk_widget_set_parent               (GtkWidget *widget,
                                                         GtkWidget *parent);

This function is useful only when implementing subclasses of GtkContainer. Sets the container as the parent of widget, and takes care of some details such as updating the state and style of the child to reflect its new location. The opposite function is gtk_widget_unparent().

widget : | a GtkWidget
parent : | parent container

gtk_widget_set_parent_window ()

void                gtk_widget_set_parent_window        (GtkWidget *widget,
                                                         GdkWindow *parent_window);

Sets a non default parent window for widget.

widget : | a GtkWidget.
parent_window : | the new parent window.

gtk_widget_get_parent_window ()

GdkWindow*          gtk_widget_get_parent_window        (GtkWidget *widget);

Gets widget's parent window.

widget : | a GtkWidget.
Returns : | the parent window of widget.

gtk_widget_set_uposition ()

void                gtk_widget_set_uposition            (GtkWidget *widget,
                                                         gint x,
                                                         gint y);

Warning

gtk_widget_set_uposition is deprecated and should not be used in newly-written code.

Sets the position of a widget. The funny "u" in the name comes from the "user position" hint specified by the X Window System, and exists for legacy reasons. This function doesn't work if a widget is inside a container; it's only really useful on GtkWindow.

Don't use this function to center dialogs over the main application window; most window managers will do the centering on your behalf if you call gtk_window_set_transient_for(), and it's really not possible to get the centering to work correctly in all cases from application code. But if you insist, use gtk_window_set_position() to set GTK_WIN_POS_CENTER_ON_PARENT, don't do the centering manually.

Note that although x and y can be individually unset, the position is not honoured unless both x and y are set.

widget : | a GtkWidget
x : | x position; -1 to unset x; -2 to leave x unchanged
y : | y position; -1 to unset y; -2 to leave y unchanged

gtk_widget_set_usize ()

void                gtk_widget_set_usize                (GtkWidget *widget,
                                                         gint width,
                                                         gint height);

Warning

gtk_widget_set_usize is deprecated and should not be used in newly-written code.

Sets the minimum size of a widget; that is, the widget's size request will be width by height. You can use this function to force a widget to be either larger or smaller than it is. The strange "usize" name dates from the early days of GTK+, and derives from X Window System terminology. In many cases, gtk_window_set_default_size() is a better choice for toplevel windows than this function; setting the default size will still allow users to shrink the window. Setting the usize will force them to leave the window at least as large as the usize. When dealing with window sizes, gtk_window_set_geometry_hints() can be a useful function as well.

Note the inherent danger of setting any fixed size - themes, translations into other languages, different fonts, and user action can all change the appropriate size for a given widget. So, it's basically impossible to hardcode a size that will always be correct.

Deprecated: Use gtk_widget_set_size_request() instead.

widget : | a GtkWidget
width : | minimum width, or -1 to unset
height : | minimum height, or -1 to unset

gtk_widget_set_events ()

void                gtk_widget_set_events               (GtkWidget *widget,
                                                         gint events);

Sets the event mask (see GdkEventMask) for a widget. The event mask determines which events a widget will receive. Keep in mind that different widgets have different default event masks, and by changing the event mask you may disrupt a widget's functionality, so be careful. This function must be called while a widget is unrealized. Consider gtk_widget_add_events() for widgets that are already realized, or if you want to preserve the existing event mask. This function can't be used with GTK_NO_WINDOW widgets; to get events on those widgets, place them inside a GtkEventBox and receive events on the event box.

widget : | a GtkWidget
events : | event mask

gtk_widget_add_events ()

void                gtk_widget_add_events               (GtkWidget *widget,
                                                         gint events);

Adds the events in the bitfield events to the event mask for widget. See gtk_widget_set_events() for details.

widget : | a GtkWidget
events : | an event mask, see GdkEventMask

gtk_widget_set_extension_events ()

void                gtk_widget_set_extension_events     (GtkWidget *widget,
                                                         GdkExtensionMode mode);

Sets the extension events mask to mode. See GdkExtensionMode and gdk_input_set_extension_events().

widget : | a GtkWidget
mode : | bitfield of extension events to receive

gtk_widget_get_extension_events ()

GdkExtensionMode    gtk_widget_get_extension_events     (GtkWidget *widget);

Retrieves the extension events the widget will receive; see gdk_input_set_extension_events().

widget : | a GtkWidget
Returns : | extension events for widget

gtk_widget_get_toplevel ()

GtkWidget*          gtk_widget_get_toplevel             (GtkWidget *widget);

This function returns the topmost widget in the container hierarchy widget is a part of. If widget has no parent widgets, it will be returned as the topmost widget. No reference will be added to the returned widget; it should not be unreferenced.

Note the difference in behavior vs. gtk_widget_get_ancestor(); gtk_widget_get_ancestor (widget, GTK_TYPE_WINDOW) would return NULL if widget wasn't inside a toplevel window, and if the window was inside a GtkWindow-derived widget which was in turn inside the toplevel GtkWindow. While the second case may seem unlikely, it actually happens when a GtkPlug is embedded inside a GtkSocket within the same application.

To reliably find the toplevel GtkWindow, use gtk_widget_get_toplevel() and check if the TOPLEVEL flags is set on the result.

 GtkWidget *toplevel = gtk_widget_get_toplevel (widget);
 if (GTK_WIDGET_TOPLEVEL (toplevel))
   {
     [ Perform action on toplevel. ]
   }

widget : | a GtkWidget
Returns : | the topmost ancestor of widget, or widget itself if there's no ancestor.

gtk_widget_get_ancestor ()

GtkWidget*          gtk_widget_get_ancestor             (GtkWidget *widget,
                                                         GType widget_type);

Gets the first ancestor of widget with type widget_type. For example, gtk_widget_get_ancestor (widget, GTK_TYPE_BOX) gets the first GtkBox that's an ancestor of widget. No reference will be added to the returned widget; it should not be unreferenced. See note about checking for a toplevel GtkWindow in the docs for gtk_widget_get_toplevel().

Note that unlike gtk_widget_is_ancestor(), gtk_widget_get_ancestor() considers widget to be an ancestor of itself.

widget : | a GtkWidget
widget_type : | ancestor type
Returns : | the ancestor widget, or NULL if not found

gtk_widget_get_colormap ()

GdkColormap*        gtk_widget_get_colormap             (GtkWidget *widget);

Gets the colormap that will be used to render widget. No reference will be added to the returned colormap; it should not be unreferenced.

widget : | a GtkWidget
Returns : | the colormap used by widget

gtk_widget_set_colormap ()

void                gtk_widget_set_colormap             (GtkWidget *widget,
                                                         GdkColormap *colormap);

Sets the colormap for the widget to the given value. Widget must not have been previously realized. This probably should only be used from an init() function (i.e. from the constructor for the widget).

widget : | a GtkWidget
colormap : | a colormap

gtk_widget_get_visual ()

GdkVisual*          gtk_widget_get_visual               (GtkWidget *widget);

Gets the visual that will be used to render widget.

widget : | a GtkWidget
Returns : | the visual for widget

gtk_widget_get_events ()

gint                gtk_widget_get_events               (GtkWidget *widget);

Returns the event mask for the widget (a bitfield containing flags from the GdkEventMask enumeration). These are the events that the widget will receive.

widget : | a GtkWidget
Returns : | event mask for widget

gtk_widget_get_pointer ()

void                gtk_widget_get_pointer              (GtkWidget *widget,
                                                         gint *x,
                                                         gint *y);

Obtains the location of the mouse pointer in widget coordinates. Widget coordinates are a bit odd; for historical reasons, they are defined as widget->window coordinates for widgets that are not GTK_NO_WINDOW widgets, and are relative to widget->allocation.x, widget->allocation.y for widgets that are GTK_NO_WINDOW widgets.

widget : | a GtkWidget
x : | return location for the X coordinate, or NULL
y : | return location for the Y coordinate, or NULL

gtk_widget_is_ancestor ()

gboolean            gtk_widget_is_ancestor              (GtkWidget *widget,
                                                         GtkWidget *ancestor);

Determines whether widget is somewhere inside ancestor, possibly with intermediate containers.

widget : | a GtkWidget
ancestor : | another GtkWidget
Returns : | TRUE if ancestor contains widget as a child, grandchild, great grandchild, etc.

gtk_widget_translate_coordinates ()

gboolean            gtk_widget_translate_coordinates    (GtkWidget *src_widget,
                                                         GtkWidget *dest_widget,
                                                         gint src_x,
                                                         gint src_y,
                                                         gint *dest_x,
                                                         gint *dest_y);

Translate coordinates relative to src_widget's allocation to coordinates relative to dest_widget's allocations. In order to perform this operation, both widgets must be realized, and must share a common toplevel.

src_widget : | a GtkWidget
dest_widget : | a GtkWidget
src_x : | X position relative to src_widget
src_y : | Y position relative to src_widget
dest_x : | location to store X position relative to dest_widget
dest_y : | location to store Y position relative to dest_widget
Returns : | FALSE if either widget was not realized, or there was no common ancestor. In this case, nothing is stored in *dest_x and *dest_y. Otherwise TRUE.

gtk_widget_hide_on_delete ()

gboolean            gtk_widget_hide_on_delete           (GtkWidget *widget);

Utility function; intended to be connected to the "delete_event" signal on a GtkWindow. The function calls gtk_widget_hide() on its argument, then returns TRUE. If connected to "delete_event", the result is that clicking the close button for a window (on the window frame, top right corner usually) will hide but not destroy the window. By default, GTK+ destroys windows when "delete_event" is received.

widget : | a GtkWidget
Returns : | TRUE

gtk_widget_set_style ()

void                gtk_widget_set_style                (GtkWidget *widget,
                                                         GtkStyle *style);

Sets the GtkStyle for a widget (widget->style). You probably don't want to use this function; it interacts badly with themes, because themes work by replacing the GtkStyle. Instead, use gtk_widget_modify_style().

widget : | a GtkWidget
style : | a GtkStyle, or NULL to remove the effect of a previous gtk_widget_set_style() and go back to the default style

gtk_widget_set_rc_style()

#define gtk_widget_set_rc_style(widget)          (gtk_widget_set_style (widget, NULL))

Warning

gtk_widget_set_rc_style is deprecated and should not be used in newly-written code.

Equivalent to gtk_widget_set_style (widget, NULL).

widget : a GtkWidget.

gtk_widget_ensure_style ()

void                gtk_widget_ensure_style             (GtkWidget *widget);

Ensures that widget has a style (widget->style). Not a very useful function; most of the time, if you want the style, the widget is realized, and realized widgets are guaranteed to have a style already.

widget : a GtkWidget

gtk_widget_get_style ()

GtkStyle*           gtk_widget_get_style                (GtkWidget *widget);

Simply an accessor function that returns widget->style.

widget : | a GtkWidget
Returns : | the widget's GtkStyle

gtk_widget_restore_default_style()

#define gtk_widget_restore_default_style(widget) (gtk_widget_set_style (widget, NULL))

Warning

gtk_widget_restore_default_style is deprecated and should not be used in newly-written code.

Equivalent to gtk_widget_set_style (widget, NULL).

widget : a GtkWidget.

gtk_widget_reset_rc_styles ()

void                gtk_widget_reset_rc_styles          (GtkWidget *widget);

Reset the styles of widget and all descendents, so when they are looked up again, they get the correct values for the currently loaded RC file settings.

This function is not useful for applications.

widget : a GtkWidget.

gtk_widget_push_colormap ()

void                gtk_widget_push_colormap            (GdkColormap *cmap);

Pushes cmap onto a global stack of colormaps; the topmost colormap on the stack will be used to create all widgets. Remove cmap with gtk_widget_pop_colormap(). There's little reason to use this function.

cmap : a GdkColormap

gtk_widget_pop_colormap ()

void                gtk_widget_pop_colormap             (void);

Removes a colormap pushed with gtk_widget_push_colormap().

gtk_widget_set_default_colormap ()

void                gtk_widget_set_default_colormap     (GdkColormap *colormap);

Sets the default colormap to use when creating widgets. gtk_widget_push_colormap() is a better function to use if you only want to affect a few widgets, rather than all widgets.

colormap : a GdkColormap

gtk_widget_get_default_style ()

GtkStyle*           gtk_widget_get_default_style        (void);

Returns the default style used by all widgets initially.

Returns : the default style. This GtkStyle object is owned by GTK+ and should not be modified or freed.

gtk_widget_get_default_colormap ()

GdkColormap*        gtk_widget_get_default_colormap     (void);

Obtains the default colormap used to create widgets.

Returns : default widget colormap

gtk_widget_get_default_visual ()

GdkVisual*          gtk_widget_get_default_visual       (void);

Obtains the visual of the default colormap. Not really useful; used to be useful before gdk_colormap_get_visual() existed.

Returns : visual of the default colormap

gtk_widget_set_direction ()

void                gtk_widget_set_direction            (GtkWidget *widget,
                                                         GtkTextDirection dir);

Sets the reading direction on a particular widget. This direction controls the primary direction for widgets containing text, and also the direction in which the children of a container are packed. The ability to set the direction is present in order so that correct localization into languages with right-to-left reading directions can be done. Generally, applications will let the default reading direction present, except for containers where the containers are arranged in an order that is explicitely visual rather than logical (such as buttons for text justification).

If the direction is set to GTK_TEXT_DIR_NONE, then the value set by gtk_widget_set_default_direction() will be used.

widget : | a GtkWidget
dir : | the new direction

enum GtkTextDirection

typedef enum
{
  GTK_TEXT_DIR_NONE,
  GTK_TEXT_DIR_LTR,
  GTK_TEXT_DIR_RTL
} GtkTextDirection;

gtk_widget_get_direction ()

GtkTextDirection    gtk_widget_get_direction            (GtkWidget *widget);

Gets the reading direction for a particular widget. See gtk_widget_set_direction().

widget : | a GtkWidget
Returns : | the reading direction for the widget.

gtk_widget_set_default_direction ()

void                gtk_widget_set_default_direction    (GtkTextDirection dir);

Sets the default reading direction for widgets where the direction has not been explicitly set by gtk_widget_set_direction().

dir : the new default direction. This cannot be GTK_TEXT_DIR_NONE.

gtk_widget_get_default_direction ()

GtkTextDirection    gtk_widget_get_default_direction    (void);

Obtains the current default reading direction. See gtk_widget_set_default_direction().

Returns : the current default direction.

gtk_widget_shape_combine_mask ()

void                gtk_widget_shape_combine_mask       (GtkWidget *widget,
                                                         GdkBitmap *shape_mask,
                                                         gint offset_x,
                                                         gint offset_y);

Sets a shape for this widget's GDK window. This allows for transparent windows etc., see gdk_window_shape_combine_mask() for more information.

widget : | a GtkWidget.
shape_mask : | shape to be added, or NULL to remove an existing shape.
offset_x : | X position of shape mask with respect to window.
offset_y : | Y position of shape mask with respect to window.

gtk_widget_input_shape_combine_mask ()

void                gtk_widget_input_shape_combine_mask (GtkWidget *widget,
                                                         GdkBitmap *shape_mask,
                                                         gint offset_x,
                                                         gint offset_y);

Sets an input shape for this widget's GDK window. This allows for windows which react to mouse click in a nonrectangular region, see gdk_window_input_shape_combine_mask() for more information.

widget : | a GtkWidget.
shape_mask : | shape to be added, or NULL to remove an existing shape.
offset_x : | X position of shape mask with respect to window.
offset_y : | Y position of shape mask with respect to window.

Since 2.10

gtk_widget_path ()

void                gtk_widget_path                     (GtkWidget *widget,
                                                         guint *path_length,
                                                         gchar **path,
                                                         gchar **path_reversed);

Obtains the full path to widget. The path is simply the name of a widget and all its parents in the container hierarchy, separated by periods. The name of a widget comes from gtk_widget_get_name(). Paths are used to apply styles to a widget in gtkrc configuration files. Widget names are the type of the widget by default (e.g. "GtkButton") or can be set to an application-specific value with gtk_widget_set_name(). By setting the name of a widget, you allow users or theme authors to apply styles to that specific widget in their gtkrc file. path_reversed_p fills in the path in reverse order, i.e. starting with widget's name instead of starting with the name of widget's outermost ancestor.

widget : | a GtkWidget
path_length : | location to store length of the path, or NULL
path : | location to store allocated path string, or NULL
path_reversed : | location to store allocated reverse path string, or NULL

gtk_widget_class_path ()

void                gtk_widget_class_path               (GtkWidget *widget,
                                                         guint *path_length,
                                                         gchar **path,
                                                         gchar **path_reversed);

Same as gtk_widget_path(), but always uses the name of a widget's type, never uses a custom name set with gtk_widget_set_name().

widget : | a GtkWidget
path_length : | location to store the length of the class path, or NULL
path : | location to store the class path as an allocated string, or NULL
path_reversed : | location to store the reverse class path as an allocated string, or NULL

gtk_widget_get_composite_name ()

gchar*              gtk_widget_get_composite_name       (GtkWidget *widget);

Obtains the composite name of a widget.

widget : | a GtkWidget.
Returns : | the composite name of widget, or NULL if widget is not a composite child. The string should not be freed when it is no longer needed.

gtk_widget_modify_style ()

void                gtk_widget_modify_style             (GtkWidget *widget,
                                                         GtkRcStyle *style);

Modifies style values on the widget. Modifications made using this technique take precedence over style values set via an RC file, however, they will be overriden if a style is explicitely set on the widget using gtk_widget_set_style(). The GtkRcStyle structure is designed so each field can either be set or unset, so it is possible, using this function, to modify some style values and leave the others unchanged.

Note that modifications made with this function are not cumulative with previous calls to gtk_widget_modify_style() or with such functions as gtk_widget_modify_fg(). If you wish to retain previous values, you must first call gtk_widget_get_modifier_style(), make your modifications to the returned style, then call gtk_widget_modify_style() with that style. On the other hand, if you first call gtk_widget_modify_style(), subsequent calls to such functions gtk_widget_modify_fg() will have a cumulative effect with the initial modifications.

widget : | a GtkWidget
style : | the GtkRcStyle holding the style modifications

gtk_widget_get_modifier_style ()

GtkRcStyle*         gtk_widget_get_modifier_style       (GtkWidget *widget);

Returns the current modifier style for the widget. (As set by gtk_widget_modify_style().) If no style has previously set, a new GtkRcStyle will be created with all values unset, and set as the modifier style for the widget. If you make changes to this rc style, you must call gtk_widget_modify_style(), passing in the returned rc style, to make sure that your changes take effect.

Caution: passing the style back to gtk_widget_modify_style() will normally end up destroying it, because gtk_widget_modify_style() copies the passed-in style and sets the copy as the new modifier style, thus dropping any reference to the old modifier style. Add a reference to the modifier style if you want to keep it alive.

widget : | a GtkWidget
Returns : | the modifier style for the widget. This rc style is owned by the widget. If you want to keep a pointer to value this around, you must add a refcount using g_object_ref().

gtk_widget_modify_fg ()

void                gtk_widget_modify_fg                (GtkWidget *widget,
                                                         GtkStateType state,
                                                         const GdkColor *color);

Sets the foreground color for a widget in a particular state. All other style values are left untouched. See also gtk_widget_modify_style().

widget : | a GtkWidget.
state : | the state for which to set the foreground color.
color : | the color to assign (does not need to be allocated), or NULL to undo the effect of previous calls to of gtk_widget_modify_fg().

gtk_widget_modify_bg ()

void                gtk_widget_modify_bg                (GtkWidget *widget,
                                                         GtkStateType state,
                                                         const GdkColor *color);

Sets the background color for a widget in a particular state. All other style values are left untouched. See also gtk_widget_modify_style().

Note that "no window" widgets (which have the GTK_NO_WINDOW flag set) draw on their parent container's window and thus may not draw any background themselves. This is the case for e.g. GtkLabel. To modify the background of such widgets, you have to set the background color on their parent; if you want to set the background of a rectangular area around a label, try placing the label in a GtkEventBox widget and setting the background color on that.

widget : | a GtkWidget.
state : | the state for which to set the background color.
color : | the color to assign (does not need to be allocated), or NULL to undo the effect of previous calls to of gtk_widget_modify_bg().

gtk_widget_modify_text ()

void                gtk_widget_modify_text              (GtkWidget *widget,
                                                         GtkStateType state,
                                                         const GdkColor *color);

Sets the text color for a widget in a particular state. All other style values are left untouched. The text color is the foreground color used along with the base color (see gtk_widget_modify_base()) for widgets such as GtkEntry and GtkTextView. See also gtk_widget_modify_style().

widget : | a GtkWidget.
state : | the state for which to set the text color.
color : | the color to assign (does not need to be allocated), or NULL to undo the effect of previous calls to of gtk_widget_modify_text().

gtk_widget_modify_base ()

void                gtk_widget_modify_base              (GtkWidget *widget,
                                                         GtkStateType state,
                                                         const GdkColor *color);

Sets the base color for a widget in a particular state. All other style values are left untouched. The base color is the background color used along with the text color (see gtk_widget_modify_text()) for widgets such as GtkEntry and GtkTextView. See also gtk_widget_modify_style().

Note that "no window" widgets (which have the GTK_NO_WINDOW flag set) draw on their parent container's window and thus may not draw any background themselves. This is the case for e.g. GtkLabel. To modify the background of such widgets, you have to set the base color on their parent; if you want to set the background of a rectangular area around a label, try placing the label in a GtkEventBox widget and setting the base color on that.

widget : | a GtkWidget.
state : | the state for which to set the base color.
color : | the color to assign (does not need to be allocated), or NULL to undo the effect of previous calls to of gtk_widget_modify_base().

gtk_widget_modify_font ()

void                gtk_widget_modify_font              (GtkWidget *widget,
                                                         PangoFontDescription *font_desc);

Sets the font to use for a widget. All other style values are left untouched. See also gtk_widget_modify_style().

widget : | a GtkWidget
font_desc : | the font description to use, or NULL to undo the effect of previous calls to gtk_widget_modify_font().

gtk_widget_create_pango_context ()

PangoContext*       gtk_widget_create_pango_context     (GtkWidget *widget);

Creates a new PangoContext with the appropriate font map, font description, and base direction for drawing text for this widget. See also gtk_widget_get_pango_context().

widget : | a GtkWidget
Returns : | the new PangoContext

gtk_widget_get_pango_context ()

PangoContext*       gtk_widget_get_pango_context        (GtkWidget *widget);

Gets a PangoContext with the appropriate font map, font description, and base direction for this widget. Unlike the context returned by gtk_widget_create_pango_context(), this context is owned by the widget (it can be used until the screen for the widget changes or the widget is removed from its toplevel), and will be updated to match any changes to the widget's attributes.

If you create and keep a PangoLayout using this context, you must deal with changes to the context by calling pango_layout_context_changed() on the layout in response to the ::style-set and ::direction-changed signals for the widget.

widget : | a GtkWidget
Returns : | the PangoContext for the widget.

gtk_widget_create_pango_layout ()

PangoLayout*        gtk_widget_create_pango_layout      (GtkWidget *widget,
                                                         const gchar *text);

Creates a new PangoLayout with the appropriate font map, font description, and base direction for drawing text for this widget.

If you keep a PangoLayout created in this way around, in order to notify the layout of changes to the base direction or font of this widget, you must call pango_layout_context_changed() in response to the ::style-set and ::direction-changed signals for the widget.

widget : | a GtkWidget
text : | text to set on the layout (can be NULL)
Returns : | the new PangoLayout

gtk_widget_render_icon ()

GdkPixbuf*          gtk_widget_render_icon              (GtkWidget *widget,
                                                         const gchar *stock_id,
                                                         GtkIconSize size,
                                                         const gchar *detail);

A convenience function that uses the theme engine and RC file settings for widget to look up stock_id and render it to a pixbuf. stock_id should be a stock icon ID such as GTK_STOCK_OPEN or GTK_STOCK_OK. size should be a size such as GTK_ICON_SIZE_MENU. detail should be a string that identifies the widget or code doing the rendering, so that theme engines can special-case rendering for that widget or code.

The pixels in the returned GdkPixbuf are shared with the rest of the application and should not be modified. The pixbuf should be freed after use with g_object_unref().

widget : | a GtkWidget
stock_id : | a stock ID
size : | a stock size. A size of (GtkIconSize)-1 means render at the size of the source and don't scale (if there are multiple source sizes, GTK+ picks one of the available sizes).
detail : | render detail to pass to theme engine
Returns : | a new pixbuf, or NULL if the stock ID wasn't known

gtk_widget_pop_composite_child ()

void                gtk_widget_pop_composite_child      (void);

Cancels the effect of a previous call to gtk_widget_push_composite_child().

gtk_widget_push_composite_child ()

void                gtk_widget_push_composite_child     (void);

Makes all newly-created widgets as composite children until the corresponding gtk_widget_pop_composite_child() call.

A composite child is a child that's an implementation detail of the container it's inside and should not be visible to people using the container. Composite children aren't treated differently by GTK (but see gtk_container_foreach() vs. gtk_container_forall()), but e.g. GUI builders might want to treat them in a different way.

Here is a simple example:

  gtk_widget_push_composite_child ();
  scrolled_window->hscrollbar = gtk_hscrollbar_new (hadjustment);
  gtk_widget_set_composite_name (scrolled_window->hscrollbar, "hscrollbar");
  gtk_widget_pop_composite_child ();
  gtk_widget_set_parent (scrolled_window->hscrollbar,
                         GTK_WIDGET (scrolled_window));
  g_object_ref (scrolled_window->hscrollbar);

gtk_widget_queue_clear ()

void                gtk_widget_queue_clear              (GtkWidget *widget);

Warning

gtk_widget_queue_clear is deprecated and should not be used in newly-written code.

This function does the same as gtk_widget_queue_draw().

Deprecated: Use gtk_widget_queue_draw() instead.

widget : a GtkWidget

gtk_widget_queue_clear_area ()

void                gtk_widget_queue_clear_area         (GtkWidget *widget,
                                                         gint x,
                                                         gint y,
                                                         gint width,
                                                         gint height);

Warning

gtk_widget_queue_clear_area is deprecated and should not be used in newly-written code.

This function is no longer different from gtk_widget_queue_draw_area(), though it once was. Now it just calls gtk_widget_queue_draw_area(). Originally gtk_widget_queue_clear_area() would force a redraw of the background for GTK_NO_WINDOW widgets, and gtk_widget_queue_draw_area() would not. Now both functions ensure the background will be redrawn.

Deprecated: Use gtk_widget_queue_draw_area() instead.

widget : | a GtkWidget
x : | x coordinate of upper-left corner of rectangle to redraw
y : | y coordinate of upper-left corner of rectangle to redraw
width : | width of region to draw
height : | height of region to draw

gtk_widget_queue_draw_area ()

void                gtk_widget_queue_draw_area          (GtkWidget *widget,
                                                         gint x,
                                                         gint y,
                                                         gint width,
                                                         gint height);

Invalidates the rectangular area of widget defined by x, y, width and height by calling gdk_window_invalidate_rect() on the widget's window and all its child windows. Once the main loop becomes idle (after the current batch of events has been processed, roughly), the window will receive expose events for the union of all regions that have been invalidated.

Normally you would only use this function in widget implementations. You might also use it, or gdk_window_invalidate_rect() directly, to schedule a redraw of a GtkDrawingArea or some portion thereof.

Frequently you can just call gdk_window_invalidate_rect() or gdk_window_invalidate_region() instead of this function. Those functions will invalidate only a single window, instead of the widget and all its children.

The advantage of adding to the invalidated region compared to simply drawing immediately is efficiency; using an invalid region ensures that you only have to redraw one time.

widget : | a GtkWidget
x : | x coordinate of upper-left corner of rectangle to redraw
y : | y coordinate of upper-left corner of rectangle to redraw
width : | width of region to draw
height : | height of region to draw

gtk_widget_reset_shapes ()

void                gtk_widget_reset_shapes             (GtkWidget *widget);

Recursively resets the shape on this widget and its descendants.

widget : a GtkWidget.

gtk_widget_set_app_paintable ()

void                gtk_widget_set_app_paintable        (GtkWidget *widget,
                                                         gboolean app_paintable);

Sets whether the application intends to draw on the widget in an ::expose-event handler.

This is a hint to the widget and does not affect the behavior of the GTK+ core; many widgets ignore this flag entirely. For widgets that do pay attention to the flag, such as GtkEventBox and GtkWindow, the effect is to suppress default themed drawing of the widget's background. (Children of the widget will still be drawn.) The application is then entirely responsible for drawing the widget background.

Note that the background is still drawn when the widget is mapped. If this is not suitable (e.g. because you want to make a transparent window using an RGBA visual), you can work around this by doing:

 gtk_widget_realize (window);
 gdk_window_set_back_pixmap (window->window, NULL, FALSE);
 gtk_widget_show (window);

widget : | a GtkWidget
app_paintable : | TRUE if the application will paint on the widget

gtk_widget_set_double_buffered ()

void                gtk_widget_set_double_buffered      (GtkWidget *widget,
                                                         gboolean double_buffered);

Widgets are double buffered by default; you can use this function to turn off the buffering. "Double buffered" simply means that gdk_window_begin_paint_region() and gdk_window_end_paint() are called automatically around expose events sent to the widget. gdk_window_begin_paint() diverts all drawing to a widget's window to an offscreen buffer, and gdk_window_end_paint() draws the buffer to the screen. The result is that users see the window update in one smooth step, and don't see individual graphics primitives being rendered.

In very simple terms, double buffered widgets don't flicker, so you would only use this function to turn off double buffering if you had special needs and really knew what you were doing.

Note: if you turn off double-buffering, you have to handle expose events, since even the clearing to the background color or pixmap will not happen automatically (as it is done in gdk_window_begin_paint()).

widget : | a GtkWidget
double_buffered : | TRUE to double-buffer a widget

gtk_widget_set_redraw_on_allocate ()

void                gtk_widget_set_redraw_on_allocate   (GtkWidget *widget,
                                                         gboolean redraw_on_allocate);

Sets whether the entire widget is queued for drawing when its size allocation changes. By default, this setting is TRUE and the entire widget is redrawn on every size change. If your widget leaves the upper left unchanged when made bigger, turning this setting on will improve performance.

Note that for NO_WINDOW widgets setting this flag to FALSE turns off all allocation on resizing: the widget will not even redraw if its position changes; this is to allow containers that don't draw anything to avoid excess invalidations. If you set this flag on a NO_WINDOW widget that does draw on widget->window, you are responsible for invalidating both the old and new allocation of the widget when the widget is moved and responsible for invalidating regions newly when the widget increases size.

widget : | a GtkWidget
redraw_on_allocate : | if TRUE, the entire widget will be redrawn when it is allocated to a new size. Otherwise, only the new portion of the widget will be redrawn.

gtk_widget_set_composite_name ()

void                gtk_widget_set_composite_name       (GtkWidget *widget,
                                                         const gchar *name);

Sets a widgets composite name. The widget must be a composite child of its parent; see gtk_widget_push_composite_child().

widget : | a GtkWidget.
name : | the name to set.

gtk_widget_set_scroll_adjustments ()

gboolean            gtk_widget_set_scroll_adjustments   (GtkWidget *widget,
                                                         GtkAdjustment *hadjustment,
                                                         GtkAdjustment *vadjustment);

For widgets that support scrolling, sets the scroll adjustments and returns TRUE. For widgets that don't support scrolling, does nothing and returns FALSE. Widgets that don't support scrolling can be scrolled by placing them in a GtkViewport, which does support scrolling.

widget : | a GtkWidget
hadjustment : | an adjustment for horizontal scrolling, or NULL
vadjustment : | an adjustment for vertical scrolling, or NULL
Returns : | TRUE if the widget supports scrolling

gtk_widget_mnemonic_activate ()

gboolean            gtk_widget_mnemonic_activate        (GtkWidget *widget,
                                                         gboolean group_cycling);

widget :
group_cycling :
Returns :

gtk_widget_class_install_style_property ()

void                gtk_widget_class_install_style_property
                                                        (GtkWidgetClass *klass,
                                                         GParamSpec *pspec);

Installs a style property on a widget class. The parser for the style property is determined by the value type of pspec.

klass : | a GtkWidgetClass
pspec : | the GParamSpec for the property

gtk_widget_class_install_style_property_parser ()

void                gtk_widget_class_install_style_property_parser
                                                        (GtkWidgetClass *klass,
                                                         GParamSpec *pspec,
                                                         GtkRcPropertyParser parser);

Installs a style property on a widget class.

klass : | a GtkWidgetClass
pspec : | the GParamSpec for the style property
parser : | the parser for the style property

gtk_widget_class_find_style_property ()

GParamSpec*         gtk_widget_class_find_style_property
                                                        (GtkWidgetClass *klass,
                                                         const gchar *property_name);

Finds a style property of a widget class by name.

klass : | a GtkWidgetClass
property_name : | the name of the style property to find
Returns : | the GParamSpec of the style property or NULL if class has no style property with that name.

Since 2.2

gtk_widget_class_list_style_properties ()

GParamSpec**        gtk_widget_class_list_style_properties
                                                        (GtkWidgetClass *klass,
                                                         guint *n_properties);

Returns all style properties of a widget class.

klass : | a GtkWidgetClass
n_properties : | location to return the number of style properties found
Returns : | an newly allocated array of GParamSpec*. The array must be freed with g_free().

Since 2.2

gtk_widget_region_intersect ()

GdkRegion*          gtk_widget_region_intersect         (GtkWidget *widget,
                                                         GdkRegion *region);

Computes the intersection of a widget's area and region, returning the intersection. The result may be empty, use gdk_region_empty() to check.

widget : | a GtkWidget
region : | a GdkRegion, in the same coordinate system as widget->allocation. That is, relative to widget->window for NO_WINDOW widgets; relative to the parent window of widget->window for widgets with their own window.
Returns : | A newly allocated region holding the intersection of widget and region. The coordinates of the return value are relative to widget->window for NO_WINDOW widgets, and relative to the parent window of widget->window for widgets with their own window.

gtk_widget_send_expose ()

gint                gtk_widget_send_expose              (GtkWidget *widget,
                                                         GdkEvent *event);

Very rarely-used function. This function is used to emit an expose event signals on a widget. This function is not normally used directly. The only time it is used is when propagating an expose event to a child NO_WINDOW widget, and that is normally done using gtk_container_propagate_expose().

If you want to force an area of a window to be redrawn, use gdk_window_invalidate_rect() or gdk_window_invalidate_region(). To cause the redraw to be done immediately, follow that call with a call to gdk_window_process_updates().

widget : | a GtkWidget
event : | a expose GdkEvent
Returns : | return from the event signal emission (TRUE if the event was handled)

gtk_widget_style_get ()

void                gtk_widget_style_get                (GtkWidget *widget,
                                                         const gchar *first_property_name,
                                                         ...);

Gets the values of a multiple style properties of widget.

widget : | a GtkWidget
first_property_name : | the name of the first property to get
... : | pairs of property names and locations to return the property values, starting with the location for first_property_name, terminated by NULL.

gtk_widget_style_get_property ()

void                gtk_widget_style_get_property       (GtkWidget *widget,
                                                         const gchar *property_name,
                                                         GValue *value);

Gets the value of a style property of widget.

widget : | a GtkWidget
property_name : | the name of a style property
value : | location to return the property value

gtk_widget_style_get_valist ()

void                gtk_widget_style_get_valist         (GtkWidget *widget,
                                                         const gchar *first_property_name,
                                                         va_list var_args);

Non-vararg variant of gtk_widget_style_get(). Used primarily by language bindings.

widget : | a GtkWidget
first_property_name : | the name of the first property to get
var_args : | a va_list of pairs of property names and locations to return the property values, starting with the location for first_property_name.

gtk_widget_get_accessible ()

AtkObject*          gtk_widget_get_accessible           (GtkWidget *widget);

Returns the accessible object that describes the widget to an assistive technology.

If no accessibility library is loaded (i.e. no ATK implementation library is loaded via GTK_MODULES or via another application library, such as libgnome), then this AtkObject instance may be a no-op. Likewise, if no class-specific AtkObject implementation is available for the widget instance in question, it will inherit an AtkObject implementation from the first ancestor class for which such an implementation is defined.

The documentation of the ATK library contains more information about accessible objects and their uses.

widget : | a GtkWidget
Returns : | the AtkObject associated with widget

gtk_widget_child_focus ()

gboolean            gtk_widget_child_focus              (GtkWidget *widget,
                                                         GtkDirectionType direction);

This function is used by custom widget implementations; if you're writing an app, you'd use gtk_widget_grab_focus() to move the focus to a particular widget, and gtk_container_set_focus_chain() to change the focus tab order. So you may want to investigate those functions instead.

gtk_widget_child_focus() is called by containers as the user moves around the window using keyboard shortcuts. direction indicates what kind of motion is taking place (up, down, left, right, tab forward, tab backward). gtk_widget_child_focus() invokes the "focus" signal on GtkWidget; widgets override the default handler for this signal in order to implement appropriate focus behavior.

The "focus" default handler for a widget should return TRUE if moving in direction left the focus on a focusable location inside that widget, and FALSE if moving in direction moved the focus outside the widget. If returning TRUE, widgets normally call gtk_widget_grab_focus() to place the focus accordingly; if returning FALSE, they don't modify the current focus location.

This function replaces gtk_container_focus() from GTK+ 1.2. It was necessary to check that the child was visible, sensitive, and focusable before calling gtk_container_focus(). gtk_widget_child_focus() returns FALSE if the widget is not currently in a focusable state, so there's no need for those checks.

widget : | a GtkWidget
direction : | direction of focus movement
Returns : | TRUE if focus ended up inside widget

gtk_widget_child_notify ()

void                gtk_widget_child_notify             (GtkWidget *widget,
                                                         const gchar *child_property);

Emits a "child-notify" signal for the child property child_property on widget.

This is the analogue of g_object_notify() for child properties.

widget : | a GtkWidget
child_property : | the name of a child property installed on the class of widget's parent.

gtk_widget_freeze_child_notify ()

void                gtk_widget_freeze_child_notify      (GtkWidget *widget);

Stops emission of "child-notify" signals on widget. The signals are queued until gtk_widget_thaw_child_notify() is called on widget.

This is the analogue of g_object_freeze_notify() for child properties.

widget : a GtkWidget

gtk_widget_get_child_visible ()

gboolean            gtk_widget_get_child_visible        (GtkWidget *widget);

Gets the value set with gtk_widget_set_child_visible(). If you feel a need to use this function, your code probably needs reorganization.

This function is only useful for container implementations and never should be called by an application.

widget : | a GtkWidget
Returns : | TRUE if the widget is mapped with the parent.

gtk_widget_get_parent ()

GtkWidget*          gtk_widget_get_parent               (GtkWidget *widget);

Returns the parent container of widget.

widget : | a GtkWidget
Returns : | the parent container of widget, or NULL

gtk_widget_get_settings ()

GtkSettings*        gtk_widget_get_settings             (GtkWidget *widget);

Gets the settings object holding the settings (global property settings, RC file information, etc) used for this widget.

Note that this function can only be called when the GtkWidget is attached to a toplevel, since the settings object is specific to a particular GdkScreen.

widget : | a GtkWidget
Returns : | the relevant GtkSettings object

gtk_widget_get_clipboard ()

GtkClipboard*       gtk_widget_get_clipboard            (GtkWidget *widget,
                                                         GdkAtom selection);

Returns the clipboard object for the given selection to be used with widget. widget must have a GdkDisplay associated with it, so must be attached to a toplevel window.

widget : | a GtkWidget
selection : | a GdkAtom which identifies the clipboard to use. GDK_SELECTION_CLIPBOARD gives the default clipboard. Another common value is GDK_SELECTION_PRIMARY, which gives the primary X selection.
Returns : | the appropriate clipboard object. If no clipboard already exists, a new one will be created. Once a clipboard object has been created, it is persistent for all time.

Since 2.2

gtk_widget_get_display ()

GdkDisplay*         gtk_widget_get_display              (GtkWidget *widget);

Get the GdkDisplay for the toplevel window associated with this widget. This function can only be called after the widget has been added to a widget hierarchy with a GtkWindow at the top.

In general, you should only create display specific resources when a widget has been realized, and you should free those resources when the widget is unrealized.

widget : | a GtkWidget
Returns : | the GdkDisplay for the toplevel for this widget.

Since 2.2

gtk_widget_get_root_window ()

GdkWindow*          gtk_widget_get_root_window          (GtkWidget *widget);

Get the root window where this widget is located. This function can only be called after the widget has been added to a widget heirarchy with GtkWindow at the top.

The root window is useful for such purposes as creating a popup GdkWindow associated with the window. In general, you should only create display specific resources when a widget has been realized, and you should free those resources when the widget is unrealized.

widget : | a GtkWidget
Returns : | the GdkWindow root window for the toplevel for this widget.

Since 2.2

gtk_widget_get_screen ()

GdkScreen*          gtk_widget_get_screen               (GtkWidget *widget);

Get the GdkScreen from the toplevel window associated with this widget. This function can only be called after the widget has been added to a widget hierarchy with a GtkWindow at the top.

In general, you should only create screen specific resources when a widget has been realized, and you should free those resources when the widget is unrealized.

widget : | a GtkWidget
Returns : | the GdkScreen for the toplevel for this widget.

Since 2.2

gtk_widget_has_screen ()

gboolean            gtk_widget_has_screen               (GtkWidget *widget);

Checks whether there is a GdkScreen is associated with this widget. All toplevel widgets have an associated screen, and all widgets added into a heirarchy with a toplevel window at the top.

widget : | a GtkWidget
Returns : | TRUE if there is a GdkScreen associcated with the widget.

Since 2.2

gtk_widget_get_size_request ()

void                gtk_widget_get_size_request         (GtkWidget *widget,
                                                         gint *width,
                                                         gint *height);

Gets the size request that was explicitly set for the widget using gtk_widget_set_size_request(). A value of -1 stored in width or height indicates that that dimension has not been set explicitly and the natural requisition of the widget will be used intead. See gtk_widget_set_size_request(). To get the size a widget will actually use, call gtk_widget_size_request() instead of this function.

widget : | a GtkWidget
width : | return location for width, or NULL
height : | return location for height, or NULL

gtk_widget_pop_visual()

#define gtk_widget_pop_visual()               ((void) 0)

Warning

gtk_widget_pop_visual is deprecated and should not be used in newly-written code.

This function is deprecated; it does nothing.

gtk_widget_push_visual()

#define gtk_widget_push_visual(visual)        ((void) 0)

Warning

gtk_widget_push_visual is deprecated and should not be used in newly-written code.

This function is deprecated; it does nothing.

visual :

gtk_widget_set_child_visible ()

void                gtk_widget_set_child_visible        (GtkWidget *widget,
                                                         gboolean is_visible);

Sets whether widget should be mapped along with its when its parent is mapped and widget has been shown with gtk_widget_show().

The child visibility can be set for widget before it is added to a container with gtk_widget_set_parent(), to avoid mapping children unnecessary before immediately unmapping them. However it will be reset to its default state of TRUE when the widget is removed from a container.

Note that changing the child visibility of a widget does not queue a resize on the widget. Most of the time, the size of a widget is computed from all visible children, whether or not they are mapped. If this is not the case, the container can queue a resize itself.

This function is only useful for container implementations and never should be called by an application.

widget : | a GtkWidget
is_visible : | if TRUE, widget should be mapped along with its parent.

gtk_widget_set_default_visual()

#define gtk_widget_set_default_visual(visual) ((void) 0)

Warning

gtk_widget_set_default_visual is deprecated and should not be used in newly-written code.

This function is deprecated; it does nothing.

visual :

gtk_widget_set_size_request ()

void                gtk_widget_set_size_request         (GtkWidget *widget,
                                                         gint width,
                                                         gint height);

Sets the minimum size of a widget; that is, the widget's size request will be width by height. You can use this function to force a widget to be either larger or smaller than it normally would be.

In most cases, gtk_window_set_default_size() is a better choice for toplevel windows than this function; setting the default size will still allow users to shrink the window. Setting the size request will force them to leave the window at least as large as the size request. When dealing with window sizes, gtk_window_set_geometry_hints() can be a useful function as well.

Note the inherent danger of setting any fixed size - themes, translations into other languages, different fonts, and user action can all change the appropriate size for a given widget. So, it's basically impossible to hardcode a size that will always be correct.

The size request of a widget is the smallest size a widget can accept while still functioning well and drawing itself correctly. However in some strange cases a widget may be allocated less than its requested size, and in many cases a widget may be allocated more space than it requested.

If the size request in a given direction is -1 (unset), then the "natural" size request of the widget will be used instead.

Widgets can't actually be allocated a size less than 1 by 1, but you can pass 0,0 to this function to mean "as small as possible."

widget : | a GtkWidget
width : | width widget should request, or -1 to unset
height : | height widget should request, or -1 to unset

gtk_widget_set_visual()

#define gtk_widget_set_visual(widget,visual)  ((void) 0)

Warning

gtk_widget_set_visual is deprecated and should not be used in newly-written code.

This function is deprecated; it does nothing.

widget :
visual :

gtk_widget_thaw_child_notify ()

void                gtk_widget_thaw_child_notify        (GtkWidget *widget);

Reverts the effect of a previous call to gtk_widget_freeze_child_notify(). This causes all queued "child-notify" signals on widget to be emitted.

widget : a GtkWidget

gtk_widget_set_no_show_all ()

void                gtk_widget_set_no_show_all          (GtkWidget *widget,
                                                         gboolean no_show_all);

Sets the "no_show_all" property, which determines whether calls to gtk_widget_show_all() and gtk_widget_hide_all() will affect this widget.

This is mostly for use in constructing widget hierarchies with externally controlled visibility, see GtkUIManager.

widget : | a GtkWidget
no_show_all : | the new value for the "no_show_all" property

Since 2.4

gtk_widget_get_no_show_all ()

gboolean            gtk_widget_get_no_show_all          (GtkWidget *widget);

Returns the current value of the "no_show_all" property, which determines whether calls to gtk_widget_show_all() and gtk_widget_hide_all() will affect this widget.

widget : | a GtkWidget
Returns : | the current value of the "no_show_all" property.

Since 2.4

gtk_widget_list_mnemonic_labels ()

GList*              gtk_widget_list_mnemonic_labels     (GtkWidget *widget);

Returns a newly allocated list of the widgets, normally labels, for which this widget is a the target of a mnemonic (see for example, gtk_label_set_mnemonic_widget()).

The widgets in the list are not individually referenced. If you want to iterate through the list and perform actions involving callbacks that might destroy the widgets, you must call g_list_foreach (result, (GFunc)g_object_ref, NULL) first, and then unref all the widgets afterwards.

widget : | a GtkWidget
Returns : | the list of mnemonic labels; free this list with g_list_free() when you are done with it.

Since 2.4

gtk_widget_add_mnemonic_label ()

void                gtk_widget_add_mnemonic_label       (GtkWidget *widget,
                                                         GtkWidget *label);

Adds a widget to the list of mnemonic labels for this widget. (See gtk_widget_list_mnemonic_labels()). Note the list of mnemonic labels for the widget is cleared when the widget is destroyed, so the caller must make sure to update its internal state at this point as well, by using a connection to the ::destroy signal or a weak notifier.

widget : | a GtkWidget
label : | a GtkWidget that acts as a mnemonic label for widget.

Since 2.4

gtk_widget_remove_mnemonic_label ()

void                gtk_widget_remove_mnemonic_label    (GtkWidget *widget,
                                                         GtkWidget *label);

Removes a widget from the list of mnemonic labels for this widget. (See gtk_widget_list_mnemonic_labels()). The widget must have previously been added to the list with gtk_widget_add_mnemonic_label().

widget : | a GtkWidget
label : | a GtkWidget that was previously set as a mnemnic label for widget with gtk_widget_add_mnemonic_label().

Since 2.4

gtk_widget_get_action ()

GtkAction*          gtk_widget_get_action               (GtkWidget *widget);

Returns the GtkAction that widget is a proxy for. See also gtk_action_get_proxies().

widget : | a GtkWidget
Returns : | the action that a widget is a proxy for, or NULL, if it is not attached to an action.

Since 2.10

gtk_widget_is_composited ()

gboolean            gtk_widget_is_composited            (GtkWidget *widget);

Whether widget can rely on having its alpha channel drawn correctly. On X11 this function returns whether a compositing manager is running for widget's screen

widget : | a GtkWidget
Returns : | TRUE if the widget can rely on its alpha channel being drawn correctly.

Since 2.10

gtk_requisition_copy ()

GtkRequisition*     gtk_requisition_copy                (const GtkRequisition *requisition);

Copies a GtkRequisition.

requisition : | a GtkRequisition.
Returns : | a copy of requisition.

gtk_requisition_free ()

void                gtk_requisition_free                (GtkRequisition *requisition);

Frees a GtkRequisition.

requisition : a GtkRequisition.

Property Details

The "app-paintable" property

  "app-paintable"            gboolean              : Read / Write

Whether the application will paint directly on the widget.

Default value: FALSE

The "can-default" property

  "can-default"              gboolean              : Read / Write

Whether the widget can be the default widget.

Default value: FALSE

The "can-focus" property

  "can-focus"                gboolean              : Read / Write

Whether the widget can accept the input focus.

Default value: FALSE

The "composite-child" property

  "composite-child"          gboolean              : Read

Whether the widget is part of a composite widget.

Default value: FALSE

The "events" property

  "events"                   GdkEventMask          : Read / Write

The event mask that decides what kind of GdkEvents this widget gets.

Default value: GDK_STRUCTURE_MASK

The "extension-events" property

  "extension-events"         GdkExtensionMode      : Read / Write

The mask that decides what kind of extension events this widget gets.

Default value: GDK_EXTENSION_EVENTS_NONE

The "has-default" property

  "has-default"              gboolean              : Read / Write

Whether the widget is the default widget.

Default value: FALSE

The "has-focus" property

  "has-focus"                gboolean              : Read / Write

Whether the widget has the input focus.

Default value: FALSE

The "height-request" property

  "height-request"           gint                  : Read / Write

Override for height request of the widget, or -1 if natural request should be used.

Allowed values: >= -1

Default value: -1

The "is-focus" property

  "is-focus"                 gboolean              : Read / Write

Whether the widget is the focus widget within the toplevel.

Default value: FALSE

The "name" property

  "name"                     gchararray            : Read / Write

The name of the widget.

Default value: NULL

The "no-show-all" property

  "no-show-all"              gboolean              : Read / Write

Whether gtk_widget_show_all() should not affect this widget.

Default value: FALSE

The "parent" property

  "parent"                   GtkContainer          : Read / Write

The parent widget of this widget. Must be a Container widget.

The "receives-default" property

  "receives-default"         gboolean              : Read / Write

If TRUE, the widget will receive the default action when it is focused.

Default value: FALSE

The "sensitive" property

  "sensitive"                gboolean              : Read / Write

Whether the widget responds to input.

Default value: TRUE

The "style" property

  "style"                    GtkStyle              : Read / Write

The style of the widget, which contains information about how it will look (colors etc).

The "visible" property

  "visible"                  gboolean              : Read / Write

Whether the widget is visible.

Default value: FALSE

The "width-request" property

  "width-request"            gint                  : Read / Write

Override for width request of the widget, or -1 if natural request should be used.

Allowed values: >= -1

Default value: -1

Style Property Details

The "cursor-aspect-ratio" style property

  "cursor-aspect-ratio"      gfloat                : Read

Aspect ratio with which to draw insertion cursor.

Allowed values: [0,1]

Default value: 0.04

The "cursor-color" style property

  "cursor-color"             GdkColor              : Read

Color with which to draw insertion cursor.

The "draw-border" style property

  "draw-border"              GtkBorder             : Read

The "draw-border" property defines the size of areas outside the widget's allocation to draw.

Since 2.8

The "focus-line-pattern" style property

  "focus-line-pattern"       gchararray            : Read

Dash pattern used to draw the focus indicator.

Default value: "\001\001"

The "focus-line-width" style property

  "focus-line-width"         gint                  : Read

Width, in pixels, of the focus indicator line.

Allowed values: >= 0

Default value: 1

The "focus-padding" style property

  "focus-padding"            gint                  : Read

Width, in pixels, between focus indicator and the widget 'box'.

Allowed values: >= 0

Default value: 1

The "interior-focus" style property

  "interior-focus"           gboolean              : Read

Whether to draw the focus indicator inside widgets.

Default value: TRUE

The "link-color" style property

  "link-color"               GdkColor              : Read

The "link-color" property defines the color of unvisited links.

Since 2.10

The "scroll-arrow-hlength" style property

  "scroll-arrow-hlength"     gint                  : Read

The "scroll-arrow-hlength" property defines the length of horizontal scroll arrows.

Allowed values: >= 1

Default value: 16

Since 2.10

The "scroll-arrow-vlength" style property

  "scroll-arrow-vlength"     gint                  : Read

The "scroll-arrow-vlength" property defines the length of vertical scroll arrows.

Allowed values: >= 1

Default value: 16

Since 2.10

The "secondary-cursor-color" style property

  "secondary-cursor-color"   GdkColor              : Read

Color with which to draw the secondary insertion cursor when editing mixed right-to-left and left-to-right text.

The "separator-height" style property

  "separator-height"         gint                  : Read

The "separator-height" property defines the height of separators. This property only takes effect if "wide-separators" is TRUE.

Allowed values: >= 0

Default value: 0

Since 2.10

The "separator-width" style property

  "separator-width"          gint                  : Read

The "separator-width" property defines the width of separators. This property only takes effect if "wide-separators" is TRUE.

Allowed values: >= 0

Default value: 0

Since 2.10

The "visited-link-color" style property

  "visited-link-color"       GdkColor              : Read

The "visited-link-color" property defines the color of visited links.

Since 2.10

The "wide-separators" style property

  "wide-separators"          gboolean              : Read

The "wide-separators" property defines whether separators have configurable width and should be drawn using a box instead of a line.

Default value: FALSE

Since 2.10

Signal Details

The "accel-closures-changed" signal

void                user_function                      (GtkWidget *widget,
                                                        gpointer   user_data)

widget : | the object which received the signal.
user_data : | user data set when the signal handler was connected.

The "button-press-event" signal

gboolean            user_function                      (GtkWidget      *widget,
                                                        GdkEventButton *event,
                                                        gpointer        user_data)      : Run Last

widget : | the object which received the signal.
event : |
user_data : | user data set when the signal handler was connected.
Returns : | TRUE to stop other handlers from being invoked for the event. FALSE to propagate the event further.

The "button-release-event" signal

gboolean            user_function                      (GtkWidget      *widget,
                                                        GdkEventButton *event,
                                                        gpointer        user_data)      : Run Last

widget : | the object which received the signal.
event : |
user_data : | user data set when the signal handler was connected.
Returns : | TRUE to stop other handlers from being invoked for the event. FALSE to propagate the event further.

The "can-activate-accel" signal

gboolean            user_function                      (GtkWidget *widget,
                                                        guint      signal_id,
                                                        gpointer   user_data)      : Run Last

Determines whether an accelerator that activates the signal identified by signal_id can currently be activated. This signal is present to allow applications and derived widgets to override the default GtkWidget handling for determining whether an accelerator can be activated.

widget : | the object which received the signal
signal_id : | the ID of a signal installed on widget
returns : | TRUE if the signal can be activated.
user_data : | user data set when the signal handler was connected.

The "child-notify" signal

void                user_function                      (GtkWidget  *widget,
                                                        GParamSpec *pspec,
                                                        gpointer    user_data)      : Run First / No Recursion / Has Details / No Hooks

The ::child-notify signal is emitted for each child property that has changed on an object. The signal's detail holds the property name.

widget : | the object which received the signal.
pspec : | the GParamSpec of the changed child property.
user_data : | user data set when the signal handler was connected.

The "client-event" signal

gboolean            user_function                      (GtkWidget      *widget,
                                                        GdkEventClient *event,
                                                        gpointer        user_data)      : Run Last

widget : | the object which received the signal.
event : |
user_data : | user data set when the signal handler was connected.
Returns : | TRUE to stop other handlers from being invoked for the event. FALSE to propagate the event further.

The "composited-changed" signal

void                user_function                      (GtkWidget *widget,
                                                        gpointer   user_data)      : Run Last / Action

widget : | the object which received the signal.
user_data : | user data set when the signal handler was connected.

The "configure-event" signal

gboolean            user_function                      (GtkWidget         *widget,
                                                        GdkEventConfigure *event,
                                                        gpointer           user_data)      : Run Last

widget : | the object which received the signal.
event : |
user_data : | user data set when the signal handler was connected.
Returns : | TRUE to stop other handlers from being invoked for the event. FALSE to propagate the event further.

The "delete-event" signal

gboolean            user_function                      (GtkWidget *widget,
                                                        GdkEvent  *event,
                                                        gpointer   user_data)      : Run Last

The ::delete-event signal is emitted if a user requests that a toplevel window is closed. The default handler for this signal destroys the window. Connecting gtk_widget_hide_on_delete() to this signal will cause the window to be hidden instead, so that it can later be shown again without reconstructing it.

widget : | the object which received the signal.
event : | the event which triggered this signal
user_data : | user data set when the signal handler was connected.
Returns : | TRUE to stop other handlers from being invoked for the event. FALSE to propagate the event further.

The "destroy-event" signal

gboolean            user_function                      (GtkWidget *widget,
                                                        GdkEvent  *event,
                                                        gpointer   user_data)      : Run Last

The ::destroy-event signal is emitted when a GdkWindow is destroyed. You rarely get this signal, because most widgets disconnect themselves from their window before they destroy it, so no widget owns the window at destroy time.

widget : | the object which received the signal.
event : | the event which triggered this signal
user_data : | user data set when the signal handler was connected.
Returns : | TRUE to stop other handlers from being invoked for the event. FALSE to propagate the event further.

The "direction-changed" signal

void                user_function                      (GtkWidget       *widget,
                                                        GtkTextDirection arg1,
                                                        gpointer         user_data)      : Run First

widget : | the object which received the signal.
arg1 : |
user_data : | user data set when the signal handler was connected.

The "drag-begin" signal

void                user_function                      (GtkWidget      *widget,
                                                        GdkDragContext *drag_context,
                                                        gpointer        user_data)         : Run Last

The ::drag-begin signal is emitted on the drag source when a drag is started. A typical reason to connect to this signal is to set up a custom drag icon with gtk_drag_source_set_icon().

widget : | the object which received the signal.
drag_context : | the drag context
user_data : | user data set when the signal handler was connected.

The "drag-data-delete" signal

void                user_function                      (GtkWidget      *widget,
                                                        GdkDragContext *drag_context,
                                                        gpointer        user_data)         : Run Last

The ::drag-data-delete signal is emitted on the drag source when a drag with the action GDK_ACTION_MOVE is successfully completed. The signal handler is responsible for deleting the data that has been dropped. What "delete" means, depends on the context of the drag operation.

widget : | the object which received the signal.
drag_context : | the drag context
user_data : | user data set when the signal handler was connected.

The "drag-data-get" signal

void                user_function                      (GtkWidget        *widget,
                                                        GdkDragContext   *drag_context,
                                                        GtkSelectionData *data,
                                                        guint             info,
                                                        guint             time,
                                                        gpointer          user_data)         : Run Last

The ::drag-data-get signal is emitted on the drag source when the drop site requests the data which is dragged. It is the responsibility of the signal handler to fill data with the data in the format which is indicated by info. See gtk_selection_data_set() and gtk_selection_data_set_text().

widget : | the object which received the signal.
drag_context : | the drag context
data : | the GtkSelectionData to be filled with the dragged data
info : | the info that has been registered with the target in the GtkTargetList.
time : | the timestamp at which the data was requested
user_data : | user data set when the signal handler was connected.

The "drag-data-received" signal

void                user_function                      (GtkWidget        *widget,
                                                        GdkDragContext   *drag_context,
                                                        gint              x,
                                                        gint              y,
                                                        GtkSelectionData *data,
                                                        guint             info,
                                                        guint             time,
                                                        gpointer          user_data)         : Run Last

The ::drag-data-received signal is emitted on the drop site when the dragged data has been received. If the data was received in order to determine whether the drop will be accepted, the handler is expected to call gdk_drag_status() and not finish the drag. If the data was received in response to a ::drag-drop signal (and this is the last target to be received), the handler for this signal is expected to process the received data and then call gtk_drag_finish(), setting the success parameter depending on whether the data was processed successfully.

The handler may inspect and modify drag_context->action before calling gtk_drag_finish(), e.g. to implement GDK_ACTION_ASK as shown in the following example:

void
drag_data_received (GtkWidget          *widget,
                    GdkDragContext     *drag_context,
                    gint                x,
                    gint                y,
                    GtkSelectionData   *data,
                    guint               info,
                    guint               time)
{
  if ((data->length >= 0) && (data->format == 8))
    {
      if (drag_context->action == GDK_ACTION_ASK)
        {
          GtkWidget *dialog;
          gint response;

          dialog = gtk_message_dialog_new (NULL,
                                           GTK_DIALOG_MODAL |
                                           GTK_DIALOG_DESTROY_WITH_PARENT,
                                           GTK_MESSAGE_INFO,
                                           GTK_BUTTONS_YES_NO,
                                           "Move the data ?\n");
          response = gtk_dialog_run (GTK_DIALOG (dialog));
          gtk_widget_destroy (dialog);

          if (response == GTK_RESPONSE_YES)
            drag_context->action = GDK_ACTION_MOVE;
          else
            drag_context->action = GDK_ACTION_COPY;
         }

      gtk_drag_finish (drag_context, TRUE, FALSE, time);
      return;
    }

   gtk_drag_finish (drag_context, FALSE, FALSE, time);
 }

widget : | the object which received the signal.
drag_context : | the drag context
x : | where the drop happened
y : | where the drop happened
data : | the received data
info : | the info that has been registered with the target in the GtkTargetList.
time : | the timestamp at which the data was received
user_data : | user data set when the signal handler was connected.

The "drag-drop" signal

gboolean            user_function                      (GtkWidget      *widget,
                                                        GdkDragContext *drag_context,
                                                        gint            x,
                                                        gint            y,
                                                        guint           time,
                                                        gpointer        user_data)         : Run Last

The ::drag-drop signal is emitted on the drop site when the user drops the data onto the widget. The signal handler must determine whether the cursor position is in a drop zone or not. If it is not in a drop zone, it returns FALSE and no further processing is necessary. Otherwise, the handler returns TRUE. In this case, the handler must ensure that gtk_drag_finish() is called to let the source know that the drop is done. The call to gtk_drag_finish() can be done either directly or in a ::drag-data-received handler which gets triggered by calling gtk_drop_get_data() to receive the data for one or more of the supported targets.

widget : | the object which received the signal.
drag_context : | the drag context
x : | the x coordinate of the current cursor position
y : | the y coordinate of the current cursor position
time : | the timestamp of the motion event
returns : | whether the cursor position is in a drop zone
user_data : | user data set when the signal handler was connected.

The "drag-end" signal

void                user_function                      (GtkWidget      *widget,
                                                        GdkDragContext *drag_context,
                                                        gpointer        user_data)         : Run Last

The ::drag-end signal is emitted on the drag source when a drag is finished. A typical reason to connect to this signal is to undo things done in ::drag-begin.

widget : | the object which received the signal.
drag_context : | the drag context
user_data : | user data set when the signal handler was connected.

The "drag-leave" signal

void                user_function                      (GtkWidget      *widget,
                                                        GdkDragContext *drag_context,
                                                        guint           time,
                                                        gpointer        user_data)         : Run Last

The ::drag-leave signal is emitted on the drop site when the cursor leaves the widget. A typical reason to connect to this signal is to undo things done in ::drag-motion, e.g. undo highlighting with gtk_drag_unhighlight()

widget : | the object which received the signal.
drag_context : | the drag context
time : | the timestamp of the motion event
user_data : | user data set when the signal handler was connected.

The "drag-motion" signal

gboolean            user_function                      (GtkWidget      *widget,
                                                        GdkDragContext *drag_context,
                                                        gint            x,
                                                        gint            y,
                                                        guint           time,
                                                        gpointer        user_data)         : Run Last

The ::drag-motion signal is emitted on the drop site when the user moves the cursor over the widget during a drag. The signal handler must determine whether the cursor position is in a drop zone or not. If it is not in a drop zone, it returns FALSE and no further processing is necessary. Otherwise, the handler returns TRUE. In this case, the handler is responsible for providing the necessary information for displaying feedback to the user, by calling gdk_drag_status(). If the decision whether the drop will be accepted or rejected can't be made based solely on the cursor position and the type of the data, the handler may inspect the dragged data by calling gtk_drag_get_data() and defer the gdk_drag_status() call to the ::drag-data-received handler.

Note that there is no ::drag-enter signal. The drag receiver has to keep track of whether he has received any ::drag-motion signals since the last ::drag-leave and if not, treat the ::drag-motion signal as an "enter" signal. Upon an "enter", the handler will typically highlight the drop site with gtk_drag_highlight().

static void
drag_motion (GtkWidget *widget,
            GdkDragContext *context,
             gint x,
             gint y,
             guint time)
{
  GdkAtom target;

  PrivateData *private_data = GET_PRIVATE_DATA (widget);

  if (!private_data->drag_highlight)
   {
     private_data->drag_highlight = 1;
     gtk_drag_highlight (widget);
   }

  target = gtk_drag_dest_find_target (widget, context, NULL);
  if (target == GDK_NONE)
    gdk_drag_status (context, 0, time);
  else
   {
     private_data->pending_status = context->suggested_action;
     gtk_drag_get_data (widget, context, target, time);
   }

  return TRUE;
}

static void
drag_data_received (GtkWidget        *widget,
                    GdkDragContext   *context,
                    gint              x,
                    gint              y,
                    GtkSelectionData *selection_data,
                    guint             info,
                    guint             time)
{
  PrivateData *private_data = GET_PRIVATE_DATA (widget);

  if (private_data->suggested_action)
   {
     private_data->suggested_action = 0;

    /* We are getting this data due to a request in drag_motion,
     * rather than due to a request in drag_drop, so we are just
     * supposed to call gdk_drag_status(), not actually paste in
     * the data.
     */
     str = gtk_selection_data_get_text (selection_data);
     if (!data_is_acceptable (str))
       gdk_drag_status (context, 0, time);
     else
       gdk_drag_status (context, private_data->suggested_action, time);
   }
  else
   {
     /* accept the drop */
   }
}

widget : | the object which received the signal.
drag_context : | the drag context
x : | the x coordinate of the current cursor position
y : | the y coordinate of the current cursor position
time : | the timestamp of the motion event
returns : | whether the cursor position is in a drop zone
user_data : | user data set when the signal handler was connected.

The "enter-notify-event" signal

gboolean            user_function                      (GtkWidget        *widget,
                                                        GdkEventCrossing *event,
                                                        gpointer          user_data)      : Run Last

widget : | the object which received the signal.
event : |
user_data : | user data set when the signal handler was connected.
Returns : | TRUE to stop other handlers from being invoked for the event. FALSE to propagate the event further.

The "event" signal

gboolean            user_function                      (GtkWidget *widget,
                                                        GdkEvent  *event,
                                                        gpointer   user_data)      : Run Last

widget : | the object which received the signal.
event : |
user_data : | user data set when the signal handler was connected.
Returns : | TRUE to stop other handlers from being invoked for the event. FALSE to propagate the event further.

The "event-after" signal

void                user_function                      (GtkWidget *widget,
                                                        GdkEvent  *event,
                                                        gpointer   user_data)

widget : | the object which received the signal.
event : |
user_data : | user data set when the signal handler was connected.

The "expose-event" signal

gboolean            user_function                      (GtkWidget      *widget,
                                                        GdkEventExpose *event,
                                                        gpointer        user_data)      : Run Last

widget : | the object which received the signal.
event : |
user_data : | user data set when the signal handler was connected.
Returns : | TRUE to stop other handlers from being invoked for the event. FALSE to propagate the event further.

The "focus" signal

gboolean            user_function                      (GtkWidget       *widget,
                                                        GtkDirectionType arg1,
                                                        gpointer         user_data)      : Run Last

widget : | the object which received the signal.
arg1 : |
user_data : | user data set when the signal handler was connected.
Returns : | TRUE to stop other handlers from being invoked for the event. FALSE to propagate the event further.

The "focus-in-event" signal

gboolean            user_function                      (GtkWidget     *widget,
                                                        GdkEventFocus *event,
                                                        gpointer       user_data)      : Run Last

widget : | the object which received the signal.
event : |
user_data : | user data set when the signal handler was connected.
Returns : | TRUE to stop other handlers from being invoked for the event. FALSE to propagate the event further.

The "focus-out-event" signal

gboolean            user_function                      (GtkWidget     *widget,
                                                        GdkEventFocus *event,
                                                        gpointer       user_data)      : Run Last

widget : | the object which received the signal.
event : |
user_data : | user data set when the signal handler was connected.
Returns : | TRUE to stop other handlers from being invoked for the event. FALSE to propagate the event further.

The "grab-broken-event" signal

gboolean            user_function                      (GtkWidget *widget,
                                                        GdkEvent  *event,
                                                        gpointer   user_data)      : Run Last

Emitted when a pointer or keyboard grab on a window belonging to widget gets broken.

On X11, this happens when the grab window becomes unviewable (i.e. it or one of its ancestors is unmapped), or if the same application grabs the pointer or keyboard again.

widget : | the object which received the signal
event : | the GdkEventGrabBroken event
user_data : | user data set when the signal handler was connected.
Returns : | TRUE to stop other handlers from being invoked for the event. FALSE to propagate the event further.

Since 2.8

The "grab-focus" signal

void                user_function                      (GtkWidget *widget,
                                                        gpointer   user_data)      : Run Last / Action

widget : | the object which received the signal.
user_data : | user data set when the signal handler was connected.

The "grab-notify" signal

void                user_function                      (GtkWidget *widget,
                                                        gboolean   was_grabbed,
                                                        gpointer   user_data)        : Run First

The ::grab-notify signal is emitted when a widget becomes shadowed by a GTK+ grab (not a pointer or keyboard grab) on another widget, or when it becomes unshadowed due to a grab being removed.

A widget is shadowed by a gtk_grab_add() when the topmost grab widget in the grab stack of its window group is not its ancestor.

widget : | the object which received the signal
was_grabbed : | FALSE if the widget becomes shadowed, TRUE if it becomes unshadowed
user_data : | user data set when the signal handler was connected.

The "hide" signal

void                user_function                      (GtkWidget *widget,
                                                        gpointer   user_data)      : Run First

widget : | the object which received the signal.
user_data : | user data set when the signal handler was connected.

The "hierarchy-changed" signal

void                user_function                      (GtkWidget *widget,
                                                        GtkWidget *widget2,
                                                        gpointer   user_data)      : Run Last

Emitted when there is a chance in the hierarchy to which a widget belong. More precisely, a widget is anchored when its toplevel ancestor is a GtkWindow. This signal is emitted when a widget changes from un-anchored to anchored or vice-versa.

widget : | the object which received the signal.
widget2 : |
user_data : | user data set when the signal handler was connected.

The "key-press-event" signal

gboolean            user_function                      (GtkWidget   *widget,
                                                        GdkEventKey *event,
                                                        gpointer     user_data)      : Run Last

widget : | the object which received the signal.
event : |
user_data : | user data set when the signal handler was connected.
Returns : | TRUE to stop other handlers from being invoked for the event. FALSE to propagate the event further.

The "key-release-event" signal

gboolean            user_function                      (GtkWidget   *widget,
                                                        GdkEventKey *event,
                                                        gpointer     user_data)      : Run Last

widget : | the object which received the signal.
event : |
user_data : | user data set when the signal handler was connected.
Returns : | TRUE to stop other handlers from being invoked for the event. FALSE to propagate the event further.

The "leave-notify-event" signal

gboolean            user_function                      (GtkWidget        *widget,
                                                        GdkEventCrossing *event,
                                                        gpointer          user_data)      : Run Last

widget : | the object which received the signal.
event : |
user_data : | user data set when the signal handler was connected.
Returns : | TRUE to stop other handlers from being invoked for the event. FALSE to propagate the event further.

The "map" signal

void                user_function                      (GtkWidget *widget,
                                                        gpointer   user_data)      : Run First

widget : | the object which received the signal.
user_data : | user data set when the signal handler was connected.

The "map-event" signal

gboolean            user_function                      (GtkWidget *widget,
                                                        GdkEvent  *event,
                                                        gpointer   user_data)      : Run Last

widget : | the object which received the signal.
event : |
user_data : | user data set when the signal handler was connected.
Returns : | TRUE to stop other handlers from being invoked for the event. FALSE to propagate the event further.

The "mnemonic-activate" signal

gboolean            user_function                      (GtkWidget *widget,
                                                        gboolean   arg1,
                                                        gpointer   user_data)      : Run Last

widget : | the object which received the signal.
arg1 : |
user_data : | user data set when the signal handler was connected.
Returns : |

The "motion-notify-event" signal

gboolean            user_function                      (GtkWidget      *widget,
                                                        GdkEventMotion *event,
                                                        gpointer        user_data)      : Run Last

widget : | the object which received the signal.
event : |
user_data : | user data set when the signal handler was connected.
Returns : | TRUE to stop other handlers from being invoked for the event. FALSE to propagate the event further.

The "no-expose-event" signal

gboolean            user_function                      (GtkWidget        *widget,
                                                        GdkEventNoExpose *event,
                                                        gpointer          user_data)      : Run Last

widget : | the object which received the signal.
event : |
user_data : | user data set when the signal handler was connected.
Returns : | TRUE to stop other handlers from being invoked for the event. FALSE to propagate the event further.

The "parent-set" signal

void                user_function                      (GtkWidget *widget,
                                                        GtkObject *old_parent,
                                                        gpointer   user_data)       : Run First

The parent-set signal is emitted when a new parent has been set on a widget.

widget : | the object on which the signal is emitted
old_parent : | the previous parent, or NULL if the widget just got its initial parent.
user_data : | user data set when the signal handler was connected.

The "popup-menu" signal

gboolean            user_function                      (GtkWidget *widget,
                                                        gpointer   user_data)      : Run Last / Action

This signal gets emitted whenever a widget should pop up a context-sensitive menu. This usually happens through the standard key binding mechanism; by pressing a certain key while a widget is focused, the user can cause the widget to pop up a menu. For example, the GtkEntry widget creates a menu with clipboard commands. See the section called “Implement GtkWidget::popup_menu” for an example of how to use this signal.

widget : | the object which received the signal
returns : | TRUE if a menu was activated
user_data : | user data set when the signal handler was connected.

The "property-notify-event" signal

gboolean            user_function                      (GtkWidget        *widget,
                                                        GdkEventProperty *event,
                                                        gpointer          user_data)      : Run Last

widget : | the object which received the signal.
event : |
user_data : | user data set when the signal handler was connected.
Returns : | TRUE to stop other handlers from being invoked for the event. FALSE to propagate the event further.

The "proximity-in-event" signal

gboolean            user_function                      (GtkWidget         *widget,
                                                        GdkEventProximity *event,
                                                        gpointer           user_data)      : Run Last

widget : | the object which received the signal.
event : |
user_data : | user data set when the signal handler was connected.
Returns : | TRUE to stop other handlers from being invoked for the event. FALSE to propagate the event further.

The "proximity-out-event" signal

gboolean            user_function                      (GtkWidget         *widget,
                                                        GdkEventProximity *event,
                                                        gpointer           user_data)      : Run Last

widget : | the object which received the signal.
event : |
user_data : | user data set when the signal handler was connected.
Returns : | TRUE to stop other handlers from being invoked for the event. FALSE to propagate the event further.

The "realize" signal

void                user_function                      (GtkWidget *widget,
                                                        gpointer   user_data)      : Run First

widget : | the object which received the signal.
user_data : | user data set when the signal handler was connected.

The "screen-changed" signal

void                user_function                      (GtkWidget *widget,
                                                        GdkScreen *arg1,
                                                        gpointer   user_data)      : Run Last

widget : | the object which received the signal.
arg1 : |
user_data : | user data set when the signal handler was connected.

The "scroll-event" signal

gboolean            user_function                      (GtkWidget      *widget,
                                                        GdkEventScroll *event,
                                                        gpointer        user_data)      : Run Last

widget : | the object which received the signal.
event : |
user_data : | user data set when the signal handler was connected.
Returns : | TRUE to stop other handlers from being invoked for the event. FALSE to propagate the event further.

The "selection-clear-event" signal

gboolean            user_function                      (GtkWidget         *widget,
                                                        GdkEventSelection *event,
                                                        gpointer           user_data)      : Run Last

widget : | the object which received the signal.
event : |
user_data : | user data set when the signal handler was connected.
Returns : | TRUE to stop other handlers from being invoked for the event. FALSE to propagate the event further.

The "selection-get" signal

void                user_function                      (GtkWidget        *widget,
                                                        GtkSelectionData *data,
                                                        guint             info,
                                                        guint             time,
                                                        gpointer          user_data)      : Run Last

widget : | the object which received the signal.
data : |
info : |
time : |
user_data : | user data set when the signal handler was connected.

The "selection-notify-event" signal

gboolean            user_function                      (GtkWidget         *widget,
                                                        GdkEventSelection *event,
                                                        gpointer           user_data)      : Run Last

widget : | the object which received the signal.
event : |
user_data : | user data set when the signal handler was connected.
Returns : | TRUE to stop other handlers from being invoked for the event. FALSE to propagate the event further.

The "selection-received" signal

void                user_function                      (GtkWidget        *widget,
                                                        GtkSelectionData *data,
                                                        guint             time,
                                                        gpointer          user_data)      : Run Last

widget : | the object which received the signal.
data : |
time : |
user_data : | user data set when the signal handler was connected.

The "selection-request-event" signal

gboolean            user_function                      (GtkWidget         *widget,
                                                        GdkEventSelection *event,
                                                        gpointer           user_data)      : Run Last

widget : | the object which received the signal.
event : |
user_data : | user data set when the signal handler was connected.
Returns : | TRUE to stop other handlers from being invoked for the event. FALSE to propagate the event further.

The "show" signal

void                user_function                      (GtkWidget *widget,
                                                        gpointer   user_data)      : Run First

widget : | the object which received the signal.
user_data : | user data set when the signal handler was connected.

The "show-help" signal

gboolean            user_function                      (GtkWidget        *widget,
                                                        GtkWidgetHelpType arg1,
                                                        gpointer          user_data)      : Run Last / Action

widget : | the object which received the signal.
arg1 : |
user_data : | user data set when the signal handler was connected.
Returns : |

The "size-allocate" signal

void                user_function                      (GtkWidget     *widget,
                                                        GtkAllocation *allocation,
                                                        gpointer       user_data)       : Run First

widget : | the object which received the signal.
allocation : |
user_data : | user data set when the signal handler was connected.

The "size-request" signal

void                user_function                      (GtkWidget      *widget,
                                                        GtkRequisition *requisition,
                                                        gpointer        user_data)        : Run First

widget : | the object which received the signal.
requisition : |
user_data : | user data set when the signal handler was connected.

The "state-changed" signal

void                user_function                      (GtkWidget   *widget,
                                                        GtkStateType state,
                                                        gpointer     user_data)      : Run First

widget : | the object which received the signal.
state : |
user_data : | user data set when the signal handler was connected.

The "style-set" signal

void                user_function                      (GtkWidget *widget,
                                                        GtkStyle  *previous_style,
                                                        gpointer   user_data)           : Run First

The style-set signal is emitted when a new style has been set on a widget. Note that style-modifying functions like gtk_widget_modify_base() also cause this signal to be emitted.

widget : | the object on which the signal is emitted
previous_style : | the previous style, or NULL if the widget just got its initial style
user_data : | user data set when the signal handler was connected.

The "unmap" signal

void                user_function                      (GtkWidget *widget,
                                                        gpointer   user_data)      : Run First

widget : | the object which received the signal.
user_data : | user data set when the signal handler was connected.

The "unmap-event" signal

gboolean            user_function                      (GtkWidget *widget,
                                                        GdkEvent  *event,
                                                        gpointer   user_data)      : Run Last

widget : | the object which received the signal.
event : |
user_data : | user data set when the signal handler was connected.
Returns : | TRUE to stop other handlers from being invoked for the event. FALSE to propagate the event further.

The "unrealize" signal

void                user_function                      (GtkWidget *widget,
                                                        gpointer   user_data)      : Run Last

widget : | the object which received the signal.
user_data : | user data set when the signal handler was connected.

The "visibility-notify-event" signal

gboolean            user_function                      (GtkWidget          *widget,
                                                        GdkEventVisibility *event,
                                                        gpointer            user_data)      : Run Last

widget : | the object which received the signal.
event : |
user_data : | user data set when the signal handler was connected.
Returns : | TRUE to stop other handlers from being invoked for the event. FALSE to propagate the event further.

The "window-state-event" signal

gboolean            user_function                      (GtkWidget           *widget,
                                                        GdkEventWindowState *event,
                                                        gpointer             user_data)      : Run Last

widget : | the object which received the signal.
event : |
user_data : | user data set when the signal handler was connected.
Returns : | TRUE to stop other handlers from being invoked for the event. FALSE to propagate the event further.


GtkWindow

GtkWindow — Toplevel which can contain other widgets

Synopsis

#include <gtk/gtk.h>

                    GtkWindow;
GtkWidget*          gtk_window_new                      (GtkWindowType type);
void                gtk_window_set_title                (GtkWindow *window,
                                                         const gchar *title);
void                gtk_window_set_wmclass              (GtkWindow *window,
                                                         const gchar *wmclass_name,
                                                         const gchar *wmclass_class);
void                gtk_window_set_policy               (GtkWindow *window,
                                                         gint allow_shrink,
                                                         gint allow_grow,
                                                         gint auto_shrink);
void                gtk_window_set_resizable            (GtkWindow *window,
                                                         gboolean resizable);
gboolean            gtk_window_get_resizable            (GtkWindow *window);
void                gtk_window_add_accel_group          (GtkWindow *window,
                                                         GtkAccelGroup *accel_group);
void                gtk_window_remove_accel_group       (GtkWindow *window,
                                                         GtkAccelGroup *accel_group);
#define             gtk_window_position
gboolean            gtk_window_activate_focus           (GtkWindow *window);
gboolean            gtk_window_activate_default         (GtkWindow *window);
void                gtk_window_set_modal                (GtkWindow *window,
                                                         gboolean modal);
void                gtk_window_set_default_size         (GtkWindow *window,
                                                         gint width,
                                                         gint height);
void                gtk_window_set_geometry_hints       (GtkWindow *window,
                                                         GtkWidget *geometry_widget,
                                                         GdkGeometry *geometry,
                                                         GdkWindowHints geom_mask);
void                gtk_window_set_gravity              (GtkWindow *window,
                                                         GdkGravity gravity);
GdkGravity          gtk_window_get_gravity              (GtkWindow *window);
void                gtk_window_set_position             (GtkWindow *window,
                                                         GtkWindowPosition position);
void                gtk_window_set_transient_for        (GtkWindow *window,
                                                         GtkWindow *parent);
void                gtk_window_set_destroy_with_parent  (GtkWindow *window,
                                                         gboolean setting);
void                gtk_window_set_screen               (GtkWindow *window,
                                                         GdkScreen *screen);
GdkScreen*          gtk_window_get_screen               (GtkWindow *window);
gboolean            gtk_window_is_active                (GtkWindow *window);
gboolean            gtk_window_has_toplevel_focus       (GtkWindow *window);
GList*              gtk_window_list_toplevels           (void);
void                gtk_window_add_mnemonic             (GtkWindow *window,
                                                         guint keyval,
                                                         GtkWidget *target);
void                gtk_window_remove_mnemonic          (GtkWindow *window,
                                                         guint keyval,
                                                         GtkWidget *target);
gboolean            gtk_window_mnemonic_activate        (GtkWindow *window,
                                                         guint keyval,
                                                         GdkModifierType modifier);
gboolean            gtk_window_activate_key             (GtkWindow *window,
                                                         GdkEventKey *event);
gboolean            gtk_window_propagate_key_event      (GtkWindow *window,
                                                         GdkEventKey *event);
GtkWidget*          gtk_window_get_focus                (GtkWindow *window);
void                gtk_window_set_focus                (GtkWindow *window,
                                                         GtkWidget *focus);
void                gtk_window_set_default              (GtkWindow *window,
                                                         GtkWidget *default_widget);
void                gtk_window_present                  (GtkWindow *window);
void                gtk_window_present_with_time        (GtkWindow *window,
                                                         guint32 timestamp);
void                gtk_window_iconify                  (GtkWindow *window);
void                gtk_window_deiconify                (GtkWindow *window);
void                gtk_window_stick                    (GtkWindow *window);
void                gtk_window_unstick                  (GtkWindow *window);
void                gtk_window_maximize                 (GtkWindow *window);
void                gtk_window_unmaximize               (GtkWindow *window);
void                gtk_window_fullscreen               (GtkWindow *window);
void                gtk_window_unfullscreen             (GtkWindow *window);
void                gtk_window_set_keep_above           (GtkWindow *window,
                                                         gboolean setting);
void                gtk_window_set_keep_below           (GtkWindow *window,
                                                         gboolean setting);
void                gtk_window_begin_resize_drag        (GtkWindow *window,
                                                         GdkWindowEdge edge,
                                                         gint button,
                                                         gint root_x,
                                                         gint root_y,
                                                         guint32 timestamp);
void                gtk_window_begin_move_drag          (GtkWindow *window,
                                                         gint button,
                                                         gint root_x,
                                                         gint root_y,
                                                         guint32 timestamp);
void                gtk_window_set_decorated            (GtkWindow *window,
                                                         gboolean setting);
void                gtk_window_set_deletable            (GtkWindow *window,
                                                         gboolean setting);
void                gtk_window_set_frame_dimensions     (GtkWindow *window,
                                                         gint left,
                                                         gint top,
                                                         gint right,
                                                         gint bottom);
void                gtk_window_set_has_frame            (GtkWindow *window,
                                                         gboolean setting);
void                gtk_window_set_mnemonic_modifier    (GtkWindow *window,
                                                         GdkModifierType modifier);
void                gtk_window_set_role                 (GtkWindow *window,
                                                         const gchar *role);
void                gtk_window_set_type_hint            (GtkWindow *window,
                                                         GdkWindowTypeHint hint);
void                gtk_window_set_skip_taskbar_hint    (GtkWindow *window,
                                                         gboolean setting);
void                gtk_window_set_skip_pager_hint      (GtkWindow *window,
                                                         gboolean setting);
void                gtk_window_set_urgency_hint         (GtkWindow *window,
                                                         gboolean setting);
void                gtk_window_set_accept_focus         (GtkWindow *window,
                                                         gboolean setting);
void                gtk_window_set_focus_on_map         (GtkWindow *window,
                                                         gboolean setting);
gboolean            gtk_window_get_decorated            (GtkWindow *window);
gboolean            gtk_window_get_deletable            (GtkWindow *window);
GList*              gtk_window_get_default_icon_list    (void);
void                gtk_window_get_default_size         (GtkWindow *window,
                                                         gint *width,
                                                         gint *height);
gboolean            gtk_window_get_destroy_with_parent  (GtkWindow *window);
void                gtk_window_get_frame_dimensions     (GtkWindow *window,
                                                         gint *left,
                                                         gint *top,
                                                         gint *right,
                                                         gint *bottom);
gboolean            gtk_window_get_has_frame            (GtkWindow *window);
GdkPixbuf*          gtk_window_get_icon                 (GtkWindow *window);
GList*              gtk_window_get_icon_list            (GtkWindow *window);
gchar*              gtk_window_get_icon_name            (GtkWindow *window);
GdkModifierType     gtk_window_get_mnemonic_modifier    (GtkWindow *window);
gboolean            gtk_window_get_modal                (GtkWindow *window);
void                gtk_window_get_position             (GtkWindow *window,
                                                         gint *root_x,
                                                         gint *root_y);
const gchar*        gtk_window_get_role                 (GtkWindow *window);
void                gtk_window_get_size                 (GtkWindow *window,
                                                         gint *width,
                                                         gint *height);
const gchar*        gtk_window_get_title                (GtkWindow *window);
GtkWindow*          gtk_window_get_transient_for        (GtkWindow *window);
GdkWindowTypeHint   gtk_window_get_type_hint            (GtkWindow *window);
gboolean            gtk_window_get_skip_taskbar_hint    (GtkWindow *window);
gboolean            gtk_window_get_skip_pager_hint      (GtkWindow *window);
gboolean            gtk_window_get_urgency_hint         (GtkWindow *window);
gboolean            gtk_window_get_accept_focus         (GtkWindow *window);
gboolean            gtk_window_get_focus_on_map         (GtkWindow *window);
GtkWindowGroup*     gtk_window_get_group                (GtkWindow *window);
void                gtk_window_move                     (GtkWindow *window,
                                                         gint x,
                                                         gint y);
gboolean            gtk_window_parse_geometry           (GtkWindow *window,
                                                         const gchar *geometry);
void                gtk_window_reshow_with_initial_size (GtkWindow *window);
void                gtk_window_resize                   (GtkWindow *window,
                                                         gint width,
                                                         gint height);
void                gtk_window_set_default_icon_list    (GList *list);
void                gtk_window_set_default_icon         (GdkPixbuf *icon);
gboolean            gtk_window_set_default_icon_from_file
                                                        (const gchar *filename,
                                                         GError **err);
void                gtk_window_set_default_icon_name    (const gchar *name);
void                gtk_window_set_icon                 (GtkWindow *window,
                                                         GdkPixbuf *icon);
void                gtk_window_set_icon_list            (GtkWindow *window,
                                                         GList *list);
gboolean            gtk_window_set_icon_from_file       (GtkWindow *window,
                                                         const gchar *filename,
                                                         GError **err);
void                gtk_window_set_icon_name            (GtkWindow *window,
                                                         const gchar *name);
void                gtk_window_set_auto_startup_notification
                                                        (gboolean setting);

void                gtk_decorated_window_init           (GtkWindow *window);
void                gtk_decorated_window_calculate_frame_size
                                                        (GtkWindow *window);
void                gtk_decorated_window_set_title      (GtkWindow *window,
                                                         const gchar *title);
void                gtk_decorated_window_move_resize_window
                                                        (GtkWindow *window,
                                                         gint x,
                                                         gint y,
                                                         gint width,
                                                         gint height);

Object Hierarchy

  GObject
   +----GInitiallyUnowned
         +----GtkObject
               +----GtkWidget
                     +----GtkContainer
                           +----GtkBin
                                 +----GtkWindow
                                       +----GtkDialog
                                       +----GtkAssistant
                                       +----GtkPlug

Implemented Interfaces

GtkWindow implements AtkImplementorIface.

Properties

  "accept-focus"             gboolean              : Read / Write
  "allow-grow"               gboolean              : Read / Write
  "allow-shrink"             gboolean              : Read / Write
  "decorated"                gboolean              : Read / Write
  "default-height"           gint                  : Read / Write
  "default-width"            gint                  : Read / Write
  "deletable"                gboolean              : Read / Write
  "destroy-with-parent"      gboolean              : Read / Write
  "focus-on-map"             gboolean              : Read / Write
  "gravity"                  GdkGravity            : Read / Write
  "has-toplevel-focus"       gboolean              : Read
  "icon"                     GdkPixbuf             : Read / Write
  "icon-name"                gchararray            : Read / Write
  "is-active"                gboolean              : Read
  "modal"                    gboolean              : Read / Write
  "resizable"                gboolean              : Read / Write
  "role"                     gchararray            : Read / Write
  "screen"                   GdkScreen             : Read / Write
  "skip-pager-hint"          gboolean              : Read / Write
  "skip-taskbar-hint"        gboolean              : Read / Write
  "title"                    gchararray            : Read / Write
  "transient-for"            GtkWindow             : Read / Write / Construct
  "type"                     GtkWindowType         : Read / Write / Construct Only
  "type-hint"                GdkWindowTypeHint     : Read / Write
  "urgency-hint"             gboolean              : Read / Write
  "window-position"          GtkWindowPosition     : Read / Write

Signals

  "activate-default"                               : Run Last / Action
  "activate-focus"                                 : Run Last / Action
  "frame-event"                                    : Run Last
  "keys-changed"                                   : Run First
  "move-focus"                                     : Run Last / Action
  "set-focus"                                      : Run Last

Description

Details

GtkWindow

typedef struct _GtkWindow GtkWindow;

gtk_window_new ()

GtkWidget*          gtk_window_new                      (GtkWindowType type);

Creates a new GtkWindow, which is a toplevel window that can contain other widgets. Nearly always, the type of the window should be GTK_WINDOW_TOPLEVEL. If you're implementing something like a popup menu from scratch (which is a bad idea, just use GtkMenu), you might use GTK_WINDOW_POPUP. GTK_WINDOW_POPUP is not for dialogs, though in some other toolkits dialogs are called "popups". In GTK+, GTK_WINDOW_POPUP means a pop-up menu or pop-up tooltip. On X11, popup windows are not controlled by the window manager.

If you simply want an undecorated window (no window borders), use gtk_window_set_decorated(), don't use GTK_WINDOW_POPUP.

type : | type of window
Returns : | a new GtkWindow.

gtk_window_set_title ()

void                gtk_window_set_title                (GtkWindow *window,
                                                         const gchar *title);

Sets the title of the GtkWindow. The title of a window will be displayed in its title bar; on the X Window System, the title bar is rendered by the window manager, so exactly how the title appears to users may vary according to a user's exact configuration. The title should help a user distinguish this window from other windows they may have open. A good title might include the application name and current document filename, for example.

window : | a GtkWindow
title : | title of the window

gtk_window_set_wmclass ()

void                gtk_window_set_wmclass              (GtkWindow *window,
                                                         const gchar *wmclass_name,
                                                         const gchar *wmclass_class);

Don't use this function. It sets the X Window System "class" and "name" hints for a window. According to the ICCCM, you should always set these to the same value for all windows in an application, and GTK+ sets them to that value by default, so calling this function is sort of pointless. However, you may want to call gtk_window_set_role() on each window in your application, for the benefit of the session manager. Setting the role allows the window manager to restore window positions when loading a saved session.

window : | a GtkWindow
wmclass_name : | window name hint
wmclass_class : | window class hint

gtk_window_set_policy ()

void                gtk_window_set_policy               (GtkWindow *window,
                                                         gint allow_shrink,
                                                         gint allow_grow,
                                                         gint auto_shrink);

Warning

gtk_window_set_policy is deprecated and should not be used in newly-written code. Use gtk_window_set_resizable() instead.

Changes how a toplevel window deals with its size request and user resize attempts. There are really only two reasonable ways to call this function:

  1. gtk_window_set_policy (GTK_WINDOW (window), FALSE, TRUE, FALSE) means that the window is user-resizable.

  2. gtk_window_set_policy (GTK_WINDOW (window), FALSE, FALSE, TRUE) means that the window's size is program-controlled, and should simply match the current size request of the window's children.

The first policy is the default, that is, by default windows are designed to be resized by users.

The basic ugly truth of this function is that it should be simply: void gtk_window_set_resizable (GtkWindow* window, gboolean setting); ...which is why GTK+ 2.0 introduces gtk_window_set_resizable(), which you should use instead of gtk_window_set_policy().

If set to TRUE, the allow_grow parameter allows the user to expand the window beyond the size request of its child widgets. If allow_grow is TRUE, be sure to check that your child widgets work properly as the window is resized.

A toplevel window will always change size to ensure its child widgets receive their requested size. This means that if you add child widgets, the toplevel window will expand to contain them. However, normally the toplevel will not shrink to fit the size request of its children if it's too large; the auto_shrink parameter causes the window to shrink when child widgets have too much space. auto_shrink is normally used with the second of the two window policies mentioned above. That is, set auto_shrink to TRUE if you want the window to have a fixed, always-optimal size determined by your program.

Note that auto_shrink doesn't do anything if allow_shrink and allow_grow are both set to FALSE.

Neither of the two suggested window policies set the allow_shrink parameter to TRUE. If allow_shrink is TRUE, the user can shrink the window so that its children do not receive their full size request; this is basically a bad thing, because most widgets will look wrong if this happens. Furthermore GTK+ has a tendency to re-expand the window if size is recalculated for any reason. The upshot is that allow_shrink should always be set to FALSE.

Sometimes when you think you want to use allow_shrink, the real problem is that some specific child widget is requesting too much space, so the user can't shrink the window sufficiently. Perhaps you are calling gtk_widget_set_size_request() on a child widget, and forcing its size request to be too large. Instead of setting the child's usize, consider using gtk_window_set_default_size() so that the child gets a larger allocation than it requests.

window : | the window
allow_shrink : | whether the user can shrink the window below its size request
allow_grow : | whether the user can grow the window larger than its size request
auto_shrink : | whether the window automatically snaps back to its size request if it's larger

gtk_window_set_resizable ()

void                gtk_window_set_resizable            (GtkWindow *window,
                                                         gboolean resizable);

Sets whether the user can resize a window. Windows are user resizable by default.

window : | a GtkWindow
resizable : | TRUE if the user can resize this window

gtk_window_get_resizable ()

gboolean            gtk_window_get_resizable            (GtkWindow *window);

Gets the value set by gtk_window_set_resizable().

window : | a GtkWindow
Returns : | TRUE if the user can resize the window

gtk_window_add_accel_group ()

void                gtk_window_add_accel_group          (GtkWindow *window,
                                                         GtkAccelGroup *accel_group);

Associate accel_group with window, such that calling gtk_accel_groups_activate() on window will activate accelerators in accel_group.

window : | window to attach accelerator group to
accel_group : | a GtkAccelGroup

gtk_window_remove_accel_group ()

void                gtk_window_remove_accel_group       (GtkWindow *window,
                                                         GtkAccelGroup *accel_group);

Reverses the effects of gtk_window_add_accel_group().

window : | a GtkWindow
accel_group : | a GtkAccelGroup

gtk_window_position

#define	gtk_window_position			gtk_window_set_position

Warning

gtk_window_position is deprecated and should not be used in newly-written code.

Deprecated alias for gtk_window_set_position().

gtk_window_activate_focus ()

gboolean            gtk_window_activate_focus           (GtkWindow *window);

Activates the current focused widget within the window.

window : | a GtkWindow
Returns : | TRUE if a widget got activated.

gtk_window_activate_default ()

gboolean            gtk_window_activate_default         (GtkWindow *window);

Activates the default widget for the window, unless the current focused widget has been configured to receive the default action (see GTK_RECEIVES_DEFAULT in GtkWidgetFlags), in which case the focused widget is activated.

window : | a GtkWindow
Returns : | TRUE if a widget got activated.

gtk_window_set_modal ()

void                gtk_window_set_modal                (GtkWindow *window,
                                                         gboolean modal);

Sets a window modal or non-modal. Modal windows prevent interaction with other windows in the same application. To keep modal dialogs on top of main application windows, use gtk_window_set_transient_for() to make the dialog transient for the parent; most window managers will then disallow lowering the dialog below the parent.

window : | a GtkWindow
modal : | whether the window is modal

gtk_window_set_default_size ()

void                gtk_window_set_default_size         (GtkWindow *window,
                                                         gint width,
                                                         gint height);

Sets the default size of a window. If the window's "natural" size (its size request) is larger than the default, the default will be ignored. More generally, if the default size does not obey the geometry hints for the window (gtk_window_set_geometry_hints() can be used to set these explicitly), the default size will be clamped to the nearest permitted size.

Unlike gtk_widget_set_size_request(), which sets a size request for a widget and thus would keep users from shrinking the window, this function only sets the initial size, just as if the user had resized the window themselves. Users can still shrink the window again as they normally would. Setting a default size of -1 means to use the "natural" default size (the size request of the window).

For more control over a window's initial size and how resizing works, investigate gtk_window_set_geometry_hints().

For some uses, gtk_window_resize() is a more appropriate function. gtk_window_resize() changes the current size of the window, rather than the size to be used on initial display. gtk_window_resize() always affects the window itself, not the geometry widget.

The default size of a window only affects the first time a window is shown; if a window is hidden and re-shown, it will remember the size it had prior to hiding, rather than using the default size.

Windows can't actually be 0x0 in size, they must be at least 1x1, but passing 0 for width and height is OK, resulting in a 1x1 default size.

window : | a GtkWindow
width : | width in pixels, or -1 to unset the default width
height : | height in pixels, or -1 to unset the default height

gtk_window_set_geometry_hints ()

void                gtk_window_set_geometry_hints       (GtkWindow *window,
                                                         GtkWidget *geometry_widget,
                                                         GdkGeometry *geometry,
                                                         GdkWindowHints geom_mask);

This function sets up hints about how a window can be resized by the user. You can set a minimum and maximum size; allowed resize increments (e.g. for xterm, you can only resize by the size of a character); aspect ratios; and more. See the GdkGeometry struct.

window : | a GtkWindow
geometry_widget : | widget the geometry hints will be applied to
geometry : | struct containing geometry information
geom_mask : | mask indicating which struct fields should be paid attention to

gtk_window_set_gravity ()

void                gtk_window_set_gravity              (GtkWindow *window,
                                                         GdkGravity gravity);

Window gravity defines the meaning of coordinates passed to gtk_window_move(). See gtk_window_move() and GdkGravity for more details.

The default window gravity is GDK_GRAVITY_NORTH_WEST which will typically "do what you mean."

window : | a GtkWindow
gravity : | window gravity

gtk_window_get_gravity ()

GdkGravity          gtk_window_get_gravity              (GtkWindow *window);

Gets the value set by gtk_window_set_gravity().

window : | a GtkWindow
Returns : | window gravity

gtk_window_set_position ()

void                gtk_window_set_position             (GtkWindow *window,
                                                         GtkWindowPosition position);

Sets a position constraint for this window. If the old or new constraint is GTK_WIN_POS_CENTER_ALWAYS, this will also cause the window to be repositioned to satisfy the new constraint.

window : | a GtkWindow.
position : | a position constraint.

gtk_window_set_transient_for ()

void                gtk_window_set_transient_for        (GtkWindow *window,
                                                         GtkWindow *parent);

Dialog windows should be set transient for the main application window they were spawned from. This allows window managers to e.g. keep the dialog on top of the main window, or center the dialog over the main window. gtk_dialog_new_with_buttons() and other convenience functions in GTK+ will sometimes call gtk_window_set_transient_for() on your behalf.

On Windows, this function will and put the child window on top of the parent, much as the window manager would have done on X.

window : | a GtkWindow
parent : | parent window

gtk_window_set_destroy_with_parent ()

void                gtk_window_set_destroy_with_parent  (GtkWindow *window,
                                                         gboolean setting);

If setting is TRUE, then destroying the transient parent of window will also destroy window itself. This is useful for dialogs that shouldn't persist beyond the lifetime of the main window they're associated with, for example.

window : | a GtkWindow
setting : | whether to destroy window with its transient parent

gtk_window_set_screen ()

void                gtk_window_set_screen               (GtkWindow *window,
                                                         GdkScreen *screen);

Sets the GdkScreen where the window is displayed; if the window is already mapped, it will be unmapped, and then remapped on the new screen.

window : | a GtkWindow.
screen : | a GdkScreen.

Since 2.2

gtk_window_get_screen ()

GdkScreen*          gtk_window_get_screen               (GtkWindow *window);

Returns the GdkScreen associated with window.

window : | a GtkWindow.
Returns : | a GdkScreen.

Since 2.2

gtk_window_is_active ()

gboolean            gtk_window_is_active                (GtkWindow *window);

Returns whether the window is part of the current active toplevel. (That is, the toplevel window receiving keystrokes.) The return value is TRUE if the window is active toplevel itself, but also if it is, say, a GtkPlug embedded in the active toplevel. You might use this function if you wanted to draw a widget differently in an active window from a widget in an inactive window. See gtk_window_has_toplevel_focus()

window : | a GtkWindow
Returns : | TRUE if the window part of the current active window.

Since 2.4

gtk_window_has_toplevel_focus ()

gboolean            gtk_window_has_toplevel_focus       (GtkWindow *window);

Returns whether the input focus is within this GtkWindow. For real toplevel windows, this is identical to gtk_window_is_active(), but for embedded windows, like GtkPlug, the results will differ.

window : | a GtkWindow
Returns : | TRUE if the input focus is within this GtkWindow

Since 2.4

gtk_window_list_toplevels ()

GList*              gtk_window_list_toplevels           (void);

Returns a list of all existing toplevel windows. The widgets in the list are not individually referenced. If you want to iterate through the list and perform actions involving callbacks that might destroy the widgets, you must call g_list_foreach (result, (GFunc)g_object_ref, NULL) first, and then unref all the widgets afterwards.

Returns : list of toplevel widgets

gtk_window_add_mnemonic ()

void                gtk_window_add_mnemonic             (GtkWindow *window,
                                                         guint keyval,
                                                         GtkWidget *target);

Adds a mnemonic to this window.

window : | a GtkWindow
keyval : | the mnemonic
target : | the widget that gets activated by the mnemonic

gtk_window_remove_mnemonic ()

void                gtk_window_remove_mnemonic          (GtkWindow *window,
                                                         guint keyval,
                                                         GtkWidget *target);

Removes a mnemonic from this window.

window : | a GtkWindow
keyval : | the mnemonic
target : | the widget that gets activated by the mnemonic

gtk_window_mnemonic_activate ()

gboolean            gtk_window_mnemonic_activate        (GtkWindow *window,
                                                         guint keyval,
                                                         GdkModifierType modifier);

Activates the targets associated with the mnemonic.

window : | a GtkWindow
keyval : | the mnemonic
modifier : | the modifiers
Returns : | TRUE if the activation is done.

gtk_window_activate_key ()

gboolean            gtk_window_activate_key             (GtkWindow *window,
                                                         GdkEventKey *event);

Activates mnemonics and accelerators for this GtkWindow. This is normally called by the default ::key_press_event handler for toplevel windows, however in some cases it may be useful to call this directly when overriding the standard key handling for a toplevel window.

window : | a GtkWindow
event : | a GdkEventKey
Returns : | TRUE if a mnemonic or accelerator was found and activated.

gtk_window_propagate_key_event ()

gboolean            gtk_window_propagate_key_event      (GtkWindow *window,
                                                         GdkEventKey *event);

Propagate a key press or release event to the focus widget and up the focus container chain until a widget handles event. This is normally called by the default ::key_press_event and ::key_release_event handlers for toplevel windows, however in some cases it may be useful to call this directly when overriding the standard key handling for a toplevel window.

window : | a GtkWindow
event : | a GdkEventKey
Returns : | TRUE if a widget in the focus chain handled the event.

gtk_window_get_focus ()

GtkWidget*          gtk_window_get_focus                (GtkWindow *window);

Retrieves the current focused widget within the window. Note that this is the widget that would have the focus if the toplevel window focused; if the toplevel window is not focused then GTK_WIDGET_HAS_FOCUS (widget) will not be TRUE for the widget.

window : | a GtkWindow
Returns : | the currently focused widget, or NULL if there is none.

gtk_window_set_focus ()

void                gtk_window_set_focus                (GtkWindow *window,
                                                         GtkWidget *focus);

If focus is not the current focus widget, and is focusable, sets it as the focus widget for the window. If focus is NULL, unsets the focus widget for this window. To set the focus to a particular widget in the toplevel, it is usually more convenient to use gtk_widget_grab_focus() instead of this function.

window : | a GtkWindow
focus : | widget to be the new focus widget, or NULL to unset any focus widget for the toplevel window.

gtk_window_set_default ()

void                gtk_window_set_default              (GtkWindow *window,
                                                         GtkWidget *default_widget);

The default widget is the widget that's activated when the user presses Enter in a dialog (for example). This function sets or unsets the default widget for a GtkWindow about. When setting (rather than unsetting) the default widget it's generally easier to call gtk_widget_grab_focus() on the widget. Before making a widget the default widget, you must set the GTK_CAN_DEFAULT flag on the widget you'd like to make the default using GTK_WIDGET_SET_FLAGS().

window : | a GtkWindow
default_widget : | widget to be the default, or NULL to unset the default widget for the toplevel.

gtk_window_present ()

void                gtk_window_present                  (GtkWindow *window);

Presents a window to the user. This may mean raising the window in the stacking order, deiconifying it, moving it to the current desktop, and/or giving it the keyboard focus, possibly dependent on the user's platform, window manager, and preferences.

If window is hidden, this function calls gtk_widget_show() as well.

This function should be used when the user tries to open a window that's already open. Say for example the preferences dialog is currently open, and the user chooses Preferences from the menu a second time; use gtk_window_present() to move the already-open dialog where the user can see it.

If you are calling this function in response to a user interaction, it is preferable to use gtk_window_present_with_time().

window : a GtkWindow

gtk_window_present_with_time ()

void                gtk_window_present_with_time        (GtkWindow *window,
                                                         guint32 timestamp);

Presents a window to the user in response to a user interaction. If you need to present a window without a timestamp, use gtk_window_present(). See gtk_window_present() for details.

window : | a GtkWindow
timestamp : | the timestamp of the user interaction (typically a button or key press event) which triggered this call

Since 2.8

gtk_window_iconify ()

void                gtk_window_iconify                  (GtkWindow *window);

Asks to iconify (i.e. minimize) the specified window. Note that you shouldn't assume the window is definitely iconified afterward, because other entities (e.g. the user or window manager) could deiconify it again, or there may not be a window manager in which case iconification isn't possible, etc. But normally the window will end up iconified. Just don't write code that crashes if not.

It's permitted to call this function before showing a window, in which case the window will be iconified before it ever appears onscreen.

You can track iconification via the "window_state_event" signal on GtkWidget.

window : a GtkWindow

gtk_window_deiconify ()

void                gtk_window_deiconify                (GtkWindow *window);

Asks to deiconify (i.e. unminimize) the specified window. Note that you shouldn't assume the window is definitely deiconified afterward, because other entities (e.g. the user or window manager) could iconify it again before your code which assumes deiconification gets to run.

You can track iconification via the "window_state_event" signal on GtkWidget.

window : a GtkWindow

gtk_window_stick ()

void                gtk_window_stick                    (GtkWindow *window);

Asks to stick window, which means that it will appear on all user desktops. Note that you shouldn't assume the window is definitely stuck afterward, because other entities (e.g. the user or window manager) could unstick it again, and some window managers do not support sticking windows. But normally the window will end up stuck. Just don't write code that crashes if not.

It's permitted to call this function before showing a window.

You can track stickiness via the "window_state_event" signal on GtkWidget.

window : a GtkWindow

gtk_window_unstick ()

void                gtk_window_unstick                  (GtkWindow *window);

Asks to unstick window, which means that it will appear on only one of the user's desktops. Note that you shouldn't assume the window is definitely unstuck afterward, because other entities (e.g. the user or window manager) could stick it again. But normally the window will end up stuck. Just don't write code that crashes if not.

You can track stickiness via the "window_state_event" signal on GtkWidget.

window : a GtkWindow

gtk_window_maximize ()

void                gtk_window_maximize                 (GtkWindow *window);

Asks to maximize window, so that it becomes full-screen. Note that you shouldn't assume the window is definitely maximized afterward, because other entities (e.g. the user or window manager) could unmaximize it again, and not all window managers support maximization. But normally the window will end up maximized. Just don't write code that crashes if not.

It's permitted to call this function before showing a window, in which case the window will be maximized when it appears onscreen initially.

You can track maximization via the "window_state_event" signal on GtkWidget.

window : a GtkWindow

gtk_window_unmaximize ()

void                gtk_window_unmaximize               (GtkWindow *window);

Asks to unmaximize window. Note that you shouldn't assume the window is definitely unmaximized afterward, because other entities (e.g. the user or window manager) could maximize it again, and not all window managers honor requests to unmaximize. But normally the window will end up unmaximized. Just don't write code that crashes if not.

You can track maximization via the "window_state_event" signal on GtkWidget.

window : a GtkWindow

gtk_window_fullscreen ()

void                gtk_window_fullscreen               (GtkWindow *window);

Asks to place window in the fullscreen state. Note that you shouldn't assume the window is definitely full screen afterward, because other entities (e.g. the user or window manager) could unfullscreen it again, and not all window managers honor requests to fullscreen windows. But normally the window will end up fullscreen. Just don't write code that crashes if not.

You can track the fullscreen state via the "window_state_event" signal on GtkWidget.

window : a GtkWindow

Since 2.2

gtk_window_unfullscreen ()

void                gtk_window_unfullscreen             (GtkWindow *window);

Asks to toggle off the fullscreen state for window. Note that you shouldn't assume the window is definitely not full screen afterward, because other entities (e.g. the user or window manager) could fullscreen it again, and not all window managers honor requests to unfullscreen windows. But normally the window will end up restored to its normal state. Just don't write code that crashes if not.

You can track the fullscreen state via the "window_state_event" signal on GtkWidget.

window : a GtkWindow

Since 2.2

gtk_window_set_keep_above ()

void                gtk_window_set_keep_above           (GtkWindow *window,
                                                         gboolean setting);

Asks to keep window above, so that it stays on top. Note that you shouldn't assume the window is definitely above afterward, because other entities (e.g. the user or window manager) could not keep it above, and not all window managers support keeping windows above. But normally the window will end kept above. Just don't write code that crashes if not.

It's permitted to call this function before showing a window, in which case the window will be kept above when it appears onscreen initially.

You can track the above state via the "window_state_event" signal on GtkWidget.

Note that, according to the Extended Window Manager Hints specification, the above state is mainly meant for user preferences and should not be used by applications e.g. for drawing attention to their dialogs.

window : | a GtkWindow
setting : | whether to keep window above other windows

Since 2.4

gtk_window_set_keep_below ()

void                gtk_window_set_keep_below           (GtkWindow *window,
                                                         gboolean setting);

Asks to keep window below, so that it stays in bottom. Note that you shouldn't assume the window is definitely below afterward, because other entities (e.g. the user or window manager) could not keep it below, and not all window managers support putting windows below. But normally the window will be kept below. Just don't write code that crashes if not.

It's permitted to call this function before showing a window, in which case the window will be kept below when it appears onscreen initially.

You can track the below state via the "window_state_event" signal on GtkWidget.

Note that, according to the Extended Window Manager Hints specification, the above state is mainly meant for user preferences and should not be used by applications e.g. for drawing attention to their dialogs.

window : | a GtkWindow
setting : | whether to keep window below other windows

Since 2.4

gtk_window_begin_resize_drag ()

void                gtk_window_begin_resize_drag        (GtkWindow *window,
                                                         GdkWindowEdge edge,
                                                         gint button,
                                                         gint root_x,
                                                         gint root_y,
                                                         guint32 timestamp);

Starts resizing a window. This function is used if an application has window resizing controls. When GDK can support it, the resize will be done using the standard mechanism for the window manager or windowing system. Otherwise, GDK will try to emulate window resizing, potentially not all that well, depending on the windowing system.

window : | a GtkWindow
edge : | position of the resize control
button : | mouse button that initiated the drag
root_x : | X position where the user clicked to initiate the drag, in root window coordinates
root_y : | Y position where the user clicked to initiate the drag
timestamp : | timestamp from the click event that initiated the drag

gtk_window_begin_move_drag ()

void                gtk_window_begin_move_drag          (GtkWindow *window,
                                                         gint button,
                                                         gint root_x,
                                                         gint root_y,
                                                         guint32 timestamp);

Starts moving a window. This function is used if an application has window movement grips. When GDK can support it, the window movement will be done using the standard mechanism for the window manager or windowing system. Otherwise, GDK will try to emulate window movement, potentially not all that well, depending on the windowing system.

window : | a GtkWindow
button : | mouse button that initiated the drag
root_x : | X position where the user clicked to initiate the drag, in root window coordinates
root_y : | Y position where the user clicked to initiate the drag
timestamp : | timestamp from the click event that initiated the drag

gtk_window_set_decorated ()

void                gtk_window_set_decorated            (GtkWindow *window,
                                                         gboolean setting);

By default, windows are decorated with a title bar, resize controls, etc. Some window managers allow GTK+ to disable these decorations, creating a borderless window. If you set the decorated property to FALSE using this function, GTK+ will do its best to convince the window manager not to decorate the window. Depending on the system, this function may not have any effect when called on a window that is already visible, so you should call it before calling gtk_window_show().

On Windows, this function always works, since there's no window manager policy involved.

window : | a GtkWindow
setting : | TRUE to decorate the window

gtk_window_set_deletable ()

void                gtk_window_set_deletable            (GtkWindow *window,
                                                         gboolean setting);

By default, windows have a close button in the window frame. Some window managers allow GTK+ to disable this button. If you set the deletable property to FALSE using this function, GTK+ will do its best to convince the window manager not to show a close button. Depending on the system, this function may not have any effect when called on a window that is already visible, so you should call it before calling gtk_window_show().

On Windows, this function always works, since there's no window manager policy involved.

window : | a GtkWindow
setting : | TRUE to decorate the window as deletable

Since 2.10

gtk_window_set_frame_dimensions ()

void                gtk_window_set_frame_dimensions     (GtkWindow *window,
                                                         gint left,
                                                         gint top,
                                                         gint right,
                                                         gint bottom);

(Note: this is a special-purpose function intended for the framebuffer port; see gtk_window_set_has_frame(). It will have no effect on the window border drawn by the window manager, which is the normal case when using the X Window system.)

For windows with frames (see gtk_window_set_has_frame()) this function can be used to change the size of the frame border.

window : | a GtkWindow that has a frame
left : | The width of the left border
top : | The height of the top border
right : | The width of the right border
bottom : | The height of the bottom border

gtk_window_set_has_frame ()

void                gtk_window_set_has_frame            (GtkWindow *window,
                                                         gboolean setting);

(Note: this is a special-purpose function for the framebuffer port, that causes GTK+ to draw its own window border. For most applications, you want gtk_window_set_decorated() instead, which tells the window manager whether to draw the window border.)

If this function is called on a window with setting of TRUE, before it is realized or showed, it will have a "frame" window around window->window, accessible in window->frame. Using the signal frame_event you can receive all events targeted at the frame.

This function is used by the linux-fb port to implement managed windows, but it could conceivably be used by X-programs that want to do their own window decorations.

window : | a GtkWindow
setting : | a boolean

gtk_window_set_mnemonic_modifier ()

void                gtk_window_set_mnemonic_modifier    (GtkWindow *window,
                                                         GdkModifierType modifier);

Sets the mnemonic modifier for this window.

window : | a GtkWindow
modifier : | the modifier mask used to activate mnemonics on this window.

gtk_window_set_role ()

void                gtk_window_set_role                 (GtkWindow *window,
                                                         const gchar *role);

This function is only useful on X11, not with other GTK+ targets.

In combination with the window title, the window role allows a window manager to identify "the same" window when an application is restarted. So for example you might set the "toolbox" role on your app's toolbox window, so that when the user restarts their session, the window manager can put the toolbox back in the same place.

If a window already has a unique title, you don't need to set the role, since the WM can use the title to identify the window when restoring the session.

window : | a GtkWindow
role : | unique identifier for the window to be used when restoring a session

gtk_window_set_type_hint ()

void                gtk_window_set_type_hint            (GtkWindow *window,
                                                         GdkWindowTypeHint hint);

By setting the type hint for the window, you allow the window manager to decorate and handle the window in a way which is suitable to the function of the window in your application.

This function should be called before the window becomes visible.

gtk_dialog_new_with_buttons() and other convenience functions in GTK+ will sometimes call gtk_window_set_type_hint() on your behalf.

window : | a GtkWindow
hint : | the window type

gtk_window_set_skip_taskbar_hint ()

void                gtk_window_set_skip_taskbar_hint    (GtkWindow *window,
                                                         gboolean setting);

Windows may set a hint asking the desktop environment not to display the window in the task bar. This function sets this hint.

window : | a GtkWindow
setting : | TRUE to keep this window from appearing in the task bar

Since 2.2

gtk_window_set_skip_pager_hint ()

void                gtk_window_set_skip_pager_hint      (GtkWindow *window,
                                                         gboolean setting);

Windows may set a hint asking the desktop environment not to display the window in the pager. This function sets this hint. (A "pager" is any desktop navigation tool such as a workspace switcher that displays a thumbnail representation of the windows on the screen.)

window : | a GtkWindow
setting : | TRUE to keep this window from appearing in the pager

Since 2.2

gtk_window_set_urgency_hint ()

void                gtk_window_set_urgency_hint         (GtkWindow *window,
                                                         gboolean setting);

Windows may set a hint asking the desktop environment to draw the users attention to the window. This function sets this hint.

window : | a GtkWindow
setting : | TRUE to mark this window as urgent

Since 2.8

gtk_window_set_accept_focus ()

void                gtk_window_set_accept_focus         (GtkWindow *window,
                                                         gboolean setting);

Windows may set a hint asking the desktop environment not to receive the input focus. This function sets this hint.

window : | a GtkWindow
setting : | TRUE to let this window receive input focus

Since 2.4

gtk_window_set_focus_on_map ()

void                gtk_window_set_focus_on_map         (GtkWindow *window,
                                                         gboolean setting);

Windows may set a hint asking the desktop environment not to receive the input focus when the window is mapped. This function sets this hint.

window : | a GtkWindow
setting : | TRUE to let this window receive input focus on map

Since 2.6

gtk_window_get_decorated ()

gboolean            gtk_window_get_decorated            (GtkWindow *window);

Returns whether the window has been set to have decorations such as a title bar via gtk_window_set_decorated().

window : | a GtkWindow
Returns : | TRUE if the window has been set to have decorations

gtk_window_get_deletable ()

gboolean            gtk_window_get_deletable            (GtkWindow *window);

Returns whether the window has been set to have a close button via gtk_window_set_deletable().

window : | a GtkWindow
Returns : | TRUE if the window has been set to have a close button

Since 2.10

gtk_window_get_default_icon_list ()

GList*              gtk_window_get_default_icon_list    (void);

Gets the value set by gtk_window_set_default_icon_list(). The list is a copy and should be freed with g_list_free(), but the pixbufs in the list have not had their reference count incremented.

Returns : copy of default icon list

gtk_window_get_default_size ()

void                gtk_window_get_default_size         (GtkWindow *window,
                                                         gint *width,
                                                         gint *height);

Gets the default size of the window. A value of -1 for the width or height indicates that a default size has not been explicitly set for that dimension, so the "natural" size of the window will be used.

window : | a GtkWindow
width : | location to store the default width, or NULL
height : | location to store the default height, or NULL

gtk_window_get_destroy_with_parent ()

gboolean            gtk_window_get_destroy_with_parent  (GtkWindow *window);

Returns whether the window will be destroyed with its transient parent. See gtk_window_set_destroy_with_parent().

window : | a GtkWindow
Returns : | TRUE if the window will be destroyed with its transient parent.

gtk_window_get_frame_dimensions ()

void                gtk_window_get_frame_dimensions     (GtkWindow *window,
                                                         gint *left,
                                                         gint *top,
                                                         gint *right,
                                                         gint *bottom);

(Note: this is a special-purpose function intended for the framebuffer port; see gtk_window_set_has_frame(). It will not return the size of the window border drawn by the window manager, which is the normal case when using a windowing system. See gdk_window_get_frame_extents() to get the standard window border extents.)

Retrieves the dimensions of the frame window for this toplevel. See gtk_window_set_has_frame(), gtk_window_set_frame_dimensions().

window : | a GtkWindow
left : | location to store the width of the frame at the left, or NULL
top : | location to store the height of the frame at the top, or NULL
right : | location to store the width of the frame at the returns, or NULL
bottom : | location to store the height of the frame at the bottom, or NULL

gtk_window_get_has_frame ()

gboolean            gtk_window_get_has_frame            (GtkWindow *window);

Accessor for whether the window has a frame window exterior to window->window. Gets the value set by gtk_window_set_has_frame().

window : | a GtkWindow
Returns : | TRUE if a frame has been added to the window via gtk_window_set_has_frame().

gtk_window_get_icon ()

GdkPixbuf*          gtk_window_get_icon                 (GtkWindow *window);

Gets the value set by gtk_window_set_icon() (or if you've called gtk_window_set_icon_list(), gets the first icon in the icon list).

window : | a GtkWindow
Returns : | icon for window

gtk_window_get_icon_list ()

GList*              gtk_window_get_icon_list            (GtkWindow *window);

Retrieves the list of icons set by gtk_window_set_icon_list(). The list is copied, but the reference count on each member won't be incremented.

window : | a GtkWindow
Returns : | copy of window's icon list

gtk_window_get_icon_name ()

gchar*              gtk_window_get_icon_name            (GtkWindow *window);

Returns the name of the themed icon for the window, see gtk_window_set_icon_name().

window : | a GtkWindow
Returns : | the icon name or NULL if the window has no themed icon

Since 2.6

gtk_window_get_mnemonic_modifier ()

GdkModifierType     gtk_window_get_mnemonic_modifier    (GtkWindow *window);

Returns the mnemonic modifier for this window. See gtk_window_set_mnemonic_modifier().

window : | a GtkWindow
Returns : | the modifier mask used to activate mnemonics on this window.

gtk_window_get_modal ()

gboolean            gtk_window_get_modal                (GtkWindow *window);

Returns whether the window is modal. See gtk_window_set_modal().

window : | a GtkWindow
Returns : | TRUE if the window is set to be modal and establishes a grab when shown

gtk_window_get_position ()

void                gtk_window_get_position             (GtkWindow *window,
                                                         gint *root_x,
                                                         gint *root_y);

This function returns the position you need to pass to gtk_window_move() to keep window in its current position. This means that the meaning of the returned value varies with window gravity. See gtk_window_move() for more details.

If you haven't changed the window gravity, its gravity will be GDK_GRAVITY_NORTH_WEST. This means that gtk_window_get_position() gets the position of the top-left corner of the window manager frame for the window. gtk_window_move() sets the position of this same top-left corner.

gtk_window_get_position() is not 100% reliable because the X Window System does not specify a way to obtain the geometry of the decorations placed on a window by the window manager. Thus GTK+ is using a "best guess" that works with most window managers.

Moreover, nearly all window managers are historically broken with respect to their handling of window gravity. So moving a window to its current position as returned by gtk_window_get_position() tends to result in moving the window slightly. Window managers are slowly getting better over time.

If a window has gravity GDK_GRAVITY_STATIC the window manager frame is not relevant, and thus gtk_window_get_position() will always produce accurate results. However you can't use static gravity to do things like place a window in a corner of the screen, because static gravity ignores the window manager decorations.

If you are saving and restoring your application's window positions, you should know that it's impossible for applications to do this without getting it somewhat wrong because applications do not have sufficient knowledge of window manager state. The Correct Mechanism is to support the session management protocol (see the "GnomeClient" object in the GNOME libraries for example) and allow the window manager to save your window sizes and positions.

window : | a GtkWindow
root_x : | return location for X coordinate of gravity-determined reference p\oint
root_y : | return location for Y coordinate of gravity-determined reference p\oint

gtk_window_get_role ()

const gchar*        gtk_window_get_role                 (GtkWindow *window);

Returns the role of the window. See gtk_window_set_role() for further explanation.

window : | a GtkWindow
Returns : | the role of the window if set, or NULL. The returned is owned by the widget and must not be modified or freed.

gtk_window_get_size ()

void                gtk_window_get_size                 (GtkWindow *window,
                                                         gint *width,
                                                         gint *height);

Obtains the current size of window. If window is not onscreen, it returns the size GTK+ will suggest to the window manager for the initial window size (but this is not reliably the same as the size the window manager will actually select). The size obtained by gtk_window_get_size() is the last size received in a GdkEventConfigure, that is, GTK+ uses its locally-stored size, rather than querying the X server for the size. As a result, if you call gtk_window_resize() then immediately call gtk_window_get_size(), the size won't have taken effect yet. After the window manager processes the resize request, GTK+ receives notification that the size has changed via a configure event, and the size of the window gets updated.

Note 1: Nearly any use of this function creates a race condition, because the size of the window may change between the time that you get the size and the time that you perform some action assuming that size is the current size. To avoid race conditions, connect to "configure_event" on the window and adjust your size-dependent state to match the size delivered in the GdkEventConfigure.

Note 2: The returned size does not include the size of the window manager decorations (aka the window frame or border). Those are not drawn by GTK+ and GTK+ has no reliable method of determining their size.

Note 3: If you are getting a window size in order to position the window onscreen, there may be a better way. The preferred way is to simply set the window's semantic type with gtk_window_set_type_hint(), which allows the window manager to e.g. center dialogs. Also, if you set the transient parent of dialogs with gtk_window_set_transient_for() window managers will often center the dialog over its parent window. It's much preferred to let the window manager handle these things rather than doing it yourself, because all apps will behave consistently and according to user prefs if the window manager handles it. Also, the window manager can take the size of the window decorations/border into account, while your application cannot.

In any case, if you insist on application-specified window positioning, there's still a better way than doing it yourself - gtk_window_set_position() will frequently handle the details for you.

window : | a GtkWindow
width : | return location for width, or NULL
height : | return location for height, or NULL

gtk_window_get_title ()

const gchar*        gtk_window_get_title                (GtkWindow *window);

Retrieves the title of the window. See gtk_window_set_title().

window : | a GtkWindow
Returns : | the title of the window, or NULL if none has been set explicitely. The returned string is owned by the widget and must not be modified or freed.

gtk_window_get_transient_for ()

GtkWindow*          gtk_window_get_transient_for        (GtkWindow *window);

Fetches the transient parent for this window. See gtk_window_set_transient_for().

window : | a GtkWindow
Returns : | the transient parent for this window, or NULL if no transient parent has been set.

gtk_window_get_type_hint ()

GdkWindowTypeHint   gtk_window_get_type_hint            (GtkWindow *window);

Gets the type hint for this window. See gtk_window_set_type_hint().

window : | a GtkWindow
Returns : | the type hint for window.

gtk_window_get_skip_taskbar_hint ()

gboolean            gtk_window_get_skip_taskbar_hint    (GtkWindow *window);

Gets the value set by gtk_window_set_skip_taskbar_hint()

window : | a GtkWindow
Returns : | TRUE if window shouldn't be in taskbar

Since 2.2

gtk_window_get_skip_pager_hint ()

gboolean            gtk_window_get_skip_pager_hint      (GtkWindow *window);

Gets the value set by gtk_window_set_skip_pager_hint().

window : | a GtkWindow
Returns : | TRUE if window shouldn't be in pager

Since 2.2

gtk_window_get_urgency_hint ()

gboolean            gtk_window_get_urgency_hint         (GtkWindow *window);

Gets the value set by gtk_window_set_urgency_hint()

window : | a GtkWindow
Returns : | TRUE if window is urgent

Since 2.8

gtk_window_get_accept_focus ()

gboolean            gtk_window_get_accept_focus         (GtkWindow *window);

Gets the value set by gtk_window_set_accept_focus().

window : | a GtkWindow
Returns : | TRUE if window should receive the input focus

Since 2.4

gtk_window_get_focus_on_map ()

gboolean            gtk_window_get_focus_on_map         (GtkWindow *window);

Gets the value set by gtk_window_set_focus_on_map().

window : | a GtkWindow
Returns : | TRUE if window should receive the input focus when mapped.

Since 2.6

gtk_window_get_group ()

GtkWindowGroup*     gtk_window_get_group                (GtkWindow *window);

Returns the group for window or the default group, if window is NULL or if window does not have an explicit window group.

window : | a GtkWindow, or NULL
Returns : | the GtkWindowGroup for a window or the default group

Since 2.10

gtk_window_move ()

void                gtk_window_move                     (GtkWindow *window,
                                                         gint x,
                                                         gint y);

Asks the window manager to move window to the given position. Window managers are free to ignore this; most window managers ignore requests for initial window positions (instead using a user-defined placement algorithm) and honor requests after the window has already been shown.

Note: the position is the position of the gravity-determined reference point for the window. The gravity determines two things: first, the location of the reference point in root window coordinates; and second, which point on the window is positioned at the reference point.

By default the gravity is GDK_GRAVITY_NORTH_WEST, so the reference point is simply the x, y supplied to gtk_window_move(). The top-left corner of the window decorations (aka window frame or border) will be placed at x, y. Therefore, to position a window at the top left of the screen, you want to use the default gravity (which is GDK_GRAVITY_NORTH_WEST) and move the window to 0,0.

To position a window at the bottom right corner of the screen, you would set GDK_GRAVITY_SOUTH_EAST, which means that the reference point is at x + the window width and y + the window height, and the bottom-right corner of the window border will be placed at that reference point. So, to place a window in the bottom right corner you would first set gravity to south east, then write: gtk_window_move (window, gdk_screen_width() - window_width, gdk_screen_height() - window_height) (note that this example does not take multi-head scenarios into account).

The Extended Window Manager Hints specification at http://www.freedesktop.org/Standards/wm-spec has a nice table of gravities in the "implementation notes" section.

The gtk_window_get_position() documentation may also be relevant.

window : | a GtkWindow
x : | X coordinate to move window to
y : | Y coordinate to move window to

gtk_window_parse_geometry ()

gboolean            gtk_window_parse_geometry           (GtkWindow *window,
                                                         const gchar *geometry);

Parses a standard X Window System geometry string - see the manual page for X (type 'man X') for details on this. gtk_window_parse_geometry() does work on all GTK+ ports including Win32 but is primarily intended for an X environment.

If either a size or a position can be extracted from the geometry string, gtk_window_parse_geometry() returns TRUE and calls gtk_window_set_default_size() and/or gtk_window_move() to resize/move the window.

If gtk_window_parse_geometry() returns TRUE, it will also set the GDK_HINT_USER_POS and/or GDK_HINT_USER_SIZE hints indicating to the window manager that the size/position of the window was user-specified. This causes most window managers to honor the geometry.

Note that for gtk_window_parse_geometry() to work as expected, it has to be called when the window has its "final" size, i.e. after calling gtk_widget_show_all() on the contents and gtk_window_set_geometry_hints() on the window.

#include <gtk/gtk.h>

static void
fill_with_content (GtkWidget *vbox)
{
  /* fill with content... */
}

int
main (int argc, char *argv[])
{
  GtkWidget *window, *vbox;
  GdkGeometry size_hints = {
    100, 50, 0, 0, 100, 50, 10, 10, 0.0, 0.0, GDK_GRAVITY_NORTH_WEST
  };

  gtk_init (&argc, &argv);

  window = gtk_window_new (GTK_WINDOW_TOPLEVEL);
  vbox = gtk_vbox_new (FALSE, 0);

  gtk_container_add (GTK_CONTAINER (window), vbox);
  fill_with_content (vbox);
  gtk_widget_show_all (vbox);

  gtk_window_set_geometry_hints (GTK_WINDOW (window),
                      window,
                    &size_hints,
                    GDK_HINT_MIN_SIZE |
                    GDK_HINT_BASE_SIZE |
                    GDK_HINT_RESIZE_INC);

  if (argc > 1)
    {
      if (!gtk_window_parse_geometry (GTK_WINDOW (window), argv[1]))
        fprintf (stderr, "Failed to parse '%s'\n", argv[1]);
    }

  gtk_widget_show_all (window);
  gtk_main ();

  return 0;
}

window : | a GtkWindow
geometry : | geometry string
Returns : | TRUE if string was parsed successfully

gtk_window_reshow_with_initial_size ()

void                gtk_window_reshow_with_initial_size (GtkWindow *window);

Hides window, then reshows it, resetting the default size and position of the window. Used by GUI builders only.

window : a GtkWindow

gtk_window_resize ()

void                gtk_window_resize                   (GtkWindow *window,
                                                         gint width,
                                                         gint height);

Resizes the window as if the user had done so, obeying geometry constraints. The default geometry constraint is that windows may not be smaller than their size request; to override this constraint, call gtk_widget_set_size_request() to set the window's request to a smaller value.

If gtk_window_resize() is called before showing a window for the first time, it overrides any default size set with gtk_window_set_default_size().

Windows may not be resized smaller than 1 by 1 pixels.

window : | a GtkWindow
width : | width in pixels to resize the window to
height : | height in pixels to resize the window to

gtk_window_set_default_icon_list ()

void                gtk_window_set_default_icon_list    (GList *list);

Sets an icon list to be used as fallback for windows that haven't had gtk_window_set_icon_list() called on them to set up a window-specific icon list. This function allows you to set up the icon for all windows in your app at once.

See gtk_window_set_icon_list() for more details.

list : a list of GdkPixbuf

gtk_window_set_default_icon ()

void                gtk_window_set_default_icon         (GdkPixbuf *icon);

Sets an icon to be used as fallback for windows that haven't had gtk_window_set_icon() called on them from a pixbuf.

icon : the icon

Since 2.4

gtk_window_set_default_icon_from_file ()

gboolean            gtk_window_set_default_icon_from_file
                                                        (const gchar *filename,
                                                         GError **err);

Sets an icon to be used as fallback for windows that haven't had gtk_window_set_icon_list() called on them from a file on disk. Warns on failure if err is NULL.

filename : | location of icon file
err : | location to store error, or NULL.
Returns : | TRUE if setting the icon succeeded.

Since 2.2

gtk_window_set_default_icon_name ()

void                gtk_window_set_default_icon_name    (const gchar *name);

Sets an icon to be used as fallback for windows that haven't had gtk_window_set_icon_list() called on them from a named themed icon, see gtk_window_set_icon_name().

name : the name of the themed icon

Since 2.6

gtk_window_set_icon ()

void                gtk_window_set_icon                 (GtkWindow *window,
                                                         GdkPixbuf *icon);

Sets up the icon representing a GtkWindow. This icon is used when the window is minimized (also known as iconified). Some window managers or desktop environments may also place it in the window frame, or display it in other contexts.

The icon should be provided in whatever size it was naturally drawn; that is, don't scale the image before passing it to GTK+. Scaling is postponed until the last minute, when the desired final size is known, to allow best quality.

If you have your icon hand-drawn in multiple sizes, use gtk_window_set_icon_list(). Then the best size will be used.

This function is equivalent to calling gtk_window_set_icon_list() with a 1-element list.

See also gtk_window_set_default_icon_list() to set the icon for all windows in your application in one go.

window : | a GtkWindow
icon : | icon image, or NULL

gtk_window_set_icon_list ()

void                gtk_window_set_icon_list            (GtkWindow *window,
                                                         GList *list);

Sets up the icon representing a GtkWindow. The icon is used when the window is minimized (also known as iconified). Some window managers or desktop environments may also place it in the window frame, or display it in other contexts.

gtk_window_set_icon_list() allows you to pass in the same icon in several hand-drawn sizes. The list should contain the natural sizes your icon is available in; that is, don't scale the image before passing it to GTK+. Scaling is postponed until the last minute, when the desired final size is known, to allow best quality.

By passing several sizes, you may improve the final image quality of the icon, by reducing or eliminating automatic image scaling.

Recommended sizes to provide: 16x16, 32x32, 48x48 at minimum, and larger images (64x64, 128x128) if you have them.

See also gtk_window_set_default_icon_list() to set the icon for all windows in your application in one go.

Note that transient windows (those who have been set transient for another window using gtk_window_set_transient_for()) will inherit their icon from their transient parent. So there's no need to explicitly set the icon on transient windows.

window : | a GtkWindow
list : | list of GdkPixbuf

gtk_window_set_icon_from_file ()

gboolean            gtk_window_set_icon_from_file       (GtkWindow *window,
                                                         const gchar *filename,
                                                         GError **err);

Sets the icon for window. Warns on failure if err is NULL.

This function is equivalent to calling gtk_window_set_icon() with a pixbuf created by loading the image from filename.

window : | a GtkWindow
filename : | location of icon file
err : | location to store error, or NULL.
Returns : | TRUE if setting the icon succeeded.

Since 2.2

gtk_window_set_icon_name ()

void                gtk_window_set_icon_name            (GtkWindow *window,
                                                         const gchar *name);

Sets the icon for the window from a named themed icon. See the docs for GtkIconTheme for more details.

Note that this has nothing to do with the WM_ICON_NAME property which is mentioned in the ICCCM.

window : | a GtkWindow
name : | the name of the themed icon

Since 2.6

gtk_window_set_auto_startup_notification ()

void                gtk_window_set_auto_startup_notification
                                                        (gboolean setting);

By default, after showing the first GtkWindow, GTK+ calls gdk_notify_startup_complete(). Call this function to disable the automatic startup notification. You might do this if your first window is a splash screen, and you want to delay notification until after your real main window has been shown, for example.

In that example, you would disable startup notification temporarily, show your splash screen, then re-enable it so that showing the main window would automatically result in notification.

setting : TRUE to automatically do startup notification

Since 2.2

gtk_decorated_window_init ()

void                gtk_decorated_window_init           (GtkWindow *window);

window :

gtk_decorated_window_calculate_frame_size ()

void                gtk_decorated_window_calculate_frame_size
                                                        (GtkWindow *window);

window :

gtk_decorated_window_set_title ()

void                gtk_decorated_window_set_title      (GtkWindow *window,
                                                         const gchar *title);

window :
title :

gtk_decorated_window_move_resize_window ()

void                gtk_decorated_window_move_resize_window
                                                        (GtkWindow *window,
                                                         gint x,
                                                         gint y,
                                                         gint width,
                                                         gint height);

window :
x :
y :
width :
height :

Property Details

The "accept-focus" property

  "accept-focus"             gboolean              : Read / Write

TRUE if the window should receive the input focus.

Default value: TRUE

The "allow-grow" property

  "allow-grow"               gboolean              : Read / Write

If TRUE, users can expand the window beyond its minimum size.

Default value: TRUE

The "allow-shrink" property

  "allow-shrink"             gboolean              : Read / Write

If TRUE, the window has no mimimum size. Setting this to TRUE is 99% of the time a bad idea.

Default value: FALSE

The "decorated" property

  "decorated"                gboolean              : Read / Write

Whether the window should be decorated by the window manager.

Default value: TRUE

Since 2.4

The "default-height" property

  "default-height"           gint                  : Read / Write

The default height of the window, used when initially showing the window.

Allowed values: >= -1

Default value: -1

The "default-width" property

  "default-width"            gint                  : Read / Write

The default width of the window, used when initially showing the window.

Allowed values: >= -1

Default value: -1

The "deletable" property

  "deletable"                gboolean              : Read / Write

Whether the window frame should have a close button.

Default value: TRUE

Since 2.10

The "destroy-with-parent" property

  "destroy-with-parent"      gboolean              : Read / Write

If this window should be destroyed when the parent is destroyed.

Default value: FALSE

The "focus-on-map" property

  "focus-on-map"             gboolean              : Read / Write

TRUE if the window should receive the input focus when mapped.

Default value: TRUE

The "gravity" property

  "gravity"                  GdkGravity            : Read / Write

The window gravity of the window. See gtk_window_move() and GdkGravity for more details about window gravity.

Default value: GDK_GRAVITY_NORTH_WEST

Since 2.4

The "has-toplevel-focus" property

  "has-toplevel-focus"       gboolean              : Read

Whether the input focus is within this GtkWindow.

Default value: FALSE

The "icon" property

  "icon"                     GdkPixbuf             : Read / Write

Icon for this window.

The "icon-name" property

  "icon-name"                gchararray            : Read / Write

The :icon-name property specifies the name of the themed icon to use as the window icon. See GtkIconTheme for more details.

Default value: NULL

Since 2.6

The "is-active" property

  "is-active"                gboolean              : Read

Whether the toplevel is the current active window.

Default value: FALSE

The "modal" property

  "modal"                    gboolean              : Read / Write

If TRUE, the window is modal (other windows are not usable while this one is up).

Default value: FALSE

The "resizable" property

  "resizable"                gboolean              : Read / Write

If TRUE, users can resize the window.

Default value: TRUE

The "role" property

  "role"                     gchararray            : Read / Write

Unique identifier for the window to be used when restoring a session.

Default value: NULL

The "screen" property

  "screen"                   GdkScreen             : Read / Write

The screen where this window will be displayed.

The "skip-pager-hint" property

  "skip-pager-hint"          gboolean              : Read / Write

TRUE if the window should not be in the pager.

Default value: FALSE

The "skip-taskbar-hint" property

  "skip-taskbar-hint"        gboolean              : Read / Write

TRUE if the window should not be in the task bar.

Default value: FALSE

The "title" property

  "title"                    gchararray            : Read / Write

The title of the window.

Default value: NULL

The "transient-for" property

  "transient-for"            GtkWindow             : Read / Write / Construct

The transient parent of the window. See gtk_window_set_transient_for() for more details about transient windows.

Since 2.10

The "type" property

  "type"                     GtkWindowType         : Read / Write / Construct Only

The type of the window.

Default value: GTK_WINDOW_TOPLEVEL

The "type-hint" property

  "type-hint"                GdkWindowTypeHint     : Read / Write

Hint to help the desktop environment understand what kind of window this is and how to treat it.

Default value: GDK_WINDOW_TYPE_HINT_NORMAL

The "urgency-hint" property

  "urgency-hint"             gboolean              : Read / Write

TRUE if the window should be brought to the user's attention.

Default value: FALSE

The "window-position" property

  "window-position"          GtkWindowPosition     : Read / Write

The initial position of the window.

Default value: GTK_WIN_POS_NONE

Signal Details

The "activate-default" signal

void                user_function                      (GtkWindow *window,
                                                        gpointer   user_data)      : Run Last / Action

window : | the object which received the signal.
user_data : | user data set when the signal handler was connected.

The "activate-focus" signal

void                user_function                      (GtkWindow *window,
                                                        gpointer   user_data)      : Run Last / Action

window : | the object which received the signal.
user_data : | user data set when the signal handler was connected.

The "frame-event" signal

gboolean            user_function                      (GtkWindow *window,
                                                        GdkEvent  *event,
                                                        gpointer   user_data)      : Run Last

window : | the object which received the signal.
event : |
user_data : | user data set when the signal handler was connected.
Returns : |

The "keys-changed" signal

void                user_function                      (GtkWindow *window,
                                                        gpointer   user_data)      : Run First

window : | the object which received the signal.
user_data : | user data set when the signal handler was connected.

The "move-focus" signal

void                user_function                      (GtkWindow       *window,
                                                        GtkDirectionType arg1,
                                                        gpointer         user_data)      : Run Last / Action

window : | the object which received the signal.
arg1 : |
user_data : | user data set when the signal handler was connected.

The "set-focus" signal

void                user_function                      (GtkWindow *window,
                                                        GtkWidget *widget,
                                                        gpointer   user_data)      : Run Last

window : | the object which received the signal.
widget : |
user_data : | user data set when the signal handler was connected.


GtkWindowGroup

GtkWindowGroup — Limit the effect of grabs

Synopsis

#include <gtk/gtk.h>

                    GtkWindowGroup;
GtkWindowGroup*     gtk_window_group_new                (void);
void                gtk_window_group_add_window         (GtkWindowGroup *window_group,
                                                         GtkWindow *window);
void                gtk_window_group_remove_window      (GtkWindowGroup *window_group,
                                                         GtkWindow *window);

Object Hierarchy

  GObject
   +----GtkWindowGroup

Description

Details

GtkWindowGroup

typedef struct _GtkWindowGroup GtkWindowGroup;

gtk_window_group_new ()

GtkWindowGroup*     gtk_window_group_new                (void);

Creates a new GtkWindowGroup object. Grabs added with gtk_grab_add() only affect windows within the same GtkWindowGroup.

Returns : a new GtkWindowGroup.

gtk_window_group_add_window ()

void                gtk_window_group_add_window         (GtkWindowGroup *window_group,
                                                         GtkWindow *window);

Adds a window to a GtkWindowGroup.

window_group : | a GtkWindowGroup
window : | the GtkWindow to add

gtk_window_group_remove_window ()

void                gtk_window_group_remove_window      (GtkWindowGroup *window_group,
                                                         GtkWindow *window);

Removes a window from a GtkWindowGroup.

window_group : | a GtkWindowGroup
window : | the GtkWindow to remove


Index

G

GtkAboutDialog, GtkAboutDialog
GtkAboutDialog:artists, The "artists" property
GtkAboutDialog:authors, The "authors" property
GtkAboutDialog:comments, The "comments" property
GtkAboutDialog:copyright, The "copyright" property
GtkAboutDialog:documenters, The "documenters" property
GtkAboutDialog:license, The "license" property
GtkAboutDialog:logo, The "logo" property
GtkAboutDialog:logo-icon-name, The "logo-icon-name" property
GtkAboutDialog:name, The "name" property
GtkAboutDialog:translator-credits, The "translator-credits" property
GtkAboutDialog:version, The "version" property
GtkAboutDialog:website, The "website" property
GtkAboutDialog:website-label, The "website-label" property
GtkAboutDialog:wrap-license, The "wrap-license" property
GtkAboutDialogActivateLinkFunc, GtkAboutDialogActivateLinkFunc ()
GtkAccelFlags, enum GtkAccelFlags
GtkAccelGroup, GtkAccelGroup
GtkAccelGroup::accel-activate, The "accel-activate" signal
GtkAccelGroup::accel-changed, The "accel-changed" signal
GtkAccelGroupActivate, GtkAccelGroupActivate ()
GtkAccelGroupFindFunc, GtkAccelGroupFindFunc ()
GtkAccelKey, GtkAccelKey
GtkAccelLabel, GtkAccelLabel
GtkAccelLabel:accel-closure, The "accel-closure" property
GtkAccelLabel:accel-widget, The "accel-widget" property
GtkAccelMap, GtkAccelMap
GtkAccelMap::changed, The "changed" signal
GtkAccelMapForeach, GtkAccelMapForeach ()
GtkAccessible, GtkAccessible
GtkAction, GtkAction
GtkAction::activate, The "activate" signal
GtkAction:action-group, The "action-group" property
GtkAction:hide-if-empty, The "hide-if-empty" property
GtkAction:icon-name, The "icon-name" property
GtkAction:is-important, The "is-important" property
GtkAction:label, The "label" property
GtkAction:name, The "name" property
GtkAction:sensitive, The "sensitive" property
GtkAction:short-label, The "short-label" property
GtkAction:stock-id, The "stock-id" property
GtkAction:tooltip, The "tooltip" property
GtkAction:visible, The "visible" property
GtkAction:visible-horizontal, The "visible-horizontal" property
GtkAction:visible-overflown, The "visible-overflown" property
GtkAction:visible-vertical, The "visible-vertical" property
GtkActionEntry, GtkActionEntry
GtkActionGroup, GtkActionGroup
GtkActionGroup::connect-proxy, The "connect-proxy" signal
GtkActionGroup::disconnect-proxy, The "disconnect-proxy" signal
GtkActionGroup::post-activate, The "post-activate" signal
GtkActionGroup::pre-activate, The "pre-activate" signal
GtkActionGroup:name, The "name" property
GtkActionGroup:sensitive, The "sensitive" property
GtkActionGroup:visible, The "visible" property
GtkAdjustment, GtkAdjustment
GtkAdjustment::changed, The "changed" signal
GtkAdjustment::value-changed, The "value-changed" signal
GtkAdjustment:lower, The "lower" property
GtkAdjustment:page-increment, The "page-increment" property
GtkAdjustment:page-size, The "page-size" property
GtkAdjustment:step-increment, The "step-increment" property
GtkAdjustment:upper, The "upper" property
GtkAdjustment:value, The "value" property
GtkAlignment, GtkAlignment
GtkAlignment:bottom-padding, The "bottom-padding" property
GtkAlignment:left-padding, The "left-padding" property
GtkAlignment:right-padding, The "right-padding" property
GtkAlignment:top-padding, The "top-padding" property
GtkAlignment:xalign, The "xalign" property
GtkAlignment:xscale, The "xscale" property
GtkAlignment:yalign, The "yalign" property
GtkAlignment:yscale, The "yscale" property
GtkAllocation, struct GtkAllocation
GtkAnchorType, enum GtkAnchorType
GtkArg, GtkArg
GtkArgFlags, enum GtkArgFlags
GtkArrow, GtkArrow
GtkArrow:arrow-type, The "arrow-type" property
GtkArrow:shadow-type, The "shadow-type" property
GtkArrowType, enum GtkArrowType
GtkAspectFrame, GtkAspectFrame
GtkAspectFrame:obey-child, The "obey-child" property
GtkAspectFrame:ratio, The "ratio" property
GtkAspectFrame:xalign, The "xalign" property
GtkAspectFrame:yalign, The "yalign" property
GtkAssistant, GtkAssistant
GtkAssistant::apply, The "apply" signal
GtkAssistant::cancel, The "cancel" signal
GtkAssistant::close, The "close" signal
GtkAssistant::prepare, The "prepare" signal
GtkAssistant:complete, The "complete" child property
GtkAssistant:content-padding, The "content-padding" style property
GtkAssistant:header-image, The "header-image" child property
GtkAssistant:header-padding, The "header-padding" style property
GtkAssistant:page-type, The "page-type" child property
GtkAssistant:sidebar-image, The "sidebar-image" child property
GtkAssistant:title, The "title" child property
GtkAssistantPageFunc, GtkAssistantPageFunc ()
GtkAssistantPageType, enum GtkAssistantPageType
GtkAttachOptions, enum GtkAttachOptions
GtkBin, GtkBin
GtkBindingArg, GtkBindingArg
GtkBindingEntry, GtkBindingEntry
GtkBindingSet, GtkBindingSet
GtkBindingSignal, GtkBindingSignal
GtkBorder, GtkBorder
GtkBox, GtkBox
GtkBox:expand, The "expand" child property
GtkBox:fill, The "fill" child property
GtkBox:homogeneous, The "homogeneous" property
GtkBox:pack-type, The "pack-type" child property
GtkBox:padding, The "padding" child property
GtkBox:position, The "position" child property
GtkBox:spacing, The "spacing" property
GtkBoxChild, GtkBoxChild
GtkButton, GtkButton
GtkButton::activate, The "activate" signal
GtkButton::clicked, The "clicked" signal
GtkButton::enter, The "enter" signal
GtkButton::leave, The "leave" signal
GtkButton::pressed, The "pressed" signal
GtkButton::released, The "released" signal
GtkButton:child-displacement-x, The "child-displacement-x" style property
GtkButton:child-displacement-y, The "child-displacement-y" style property
GtkButton:default-border, The "default-border" style property
GtkButton:default-outside-border, The "default-outside-border" style property
GtkButton:displace-focus, The "displace-focus" style property
GtkButton:focus-on-click, The "focus-on-click" property
GtkButton:image, The "image" property
GtkButton:image-position, The "image-position" property
GtkButton:image-spacing, The "image-spacing" style property
GtkButton:inner-border, The "inner-border" style property
GtkButton:label, The "label" property
GtkButton:relief, The "relief" property
GtkButton:use-stock, The "use-stock" property
GtkButton:use-underline, The "use-underline" property
GtkButton:xalign, The "xalign" property
GtkButton:yalign, The "yalign" property
GtkButtonAction, enum GtkButtonAction
GtkButtonBox, GtkButtonBox
GtkButtonBox:child-internal-pad-x, The "child-internal-pad-x" style property
GtkButtonBox:child-internal-pad-y, The "child-internal-pad-y" style property
GtkButtonBox:child-min-height, The "child-min-height" style property
GtkButtonBox:child-min-width, The "child-min-width" style property
GtkButtonBox:layout-style, The "layout-style" property
GtkButtonBox:secondary, The "secondary" child property
GtkButtonBoxStyle, enum GtkButtonBoxStyle
GtkButtonsType, enum GtkButtonsType
GtkCalendar, GtkCalendar
GtkCalendar::day-selected, The "day-selected" signal
GtkCalendar::day-selected-double-click, The "day-selected-double-click" signal
GtkCalendar::month-changed, The "month-changed" signal
GtkCalendar::next-month, The "next-month" signal
GtkCalendar::next-year, The "next-year" signal
GtkCalendar::prev-month, The "prev-month" signal
GtkCalendar::prev-year, The "prev-year" signal
GtkCalendar:day, The "day" property
GtkCalendar:month, The "month" property
GtkCalendar:no-month-change, The "no-month-change" property
GtkCalendar:show-day-names, The "show-day-names" property
GtkCalendar:show-heading, The "show-heading" property
GtkCalendar:show-week-numbers, The "show-week-numbers" property
GtkCalendar:year, The "year" property
GtkCalendarDisplayOptions, enum GtkCalendarDisplayOptions
GtkCallback, GtkCallback ()
GtkCallbackMarshal, GtkCallbackMarshal ()
GtkCell, GtkCell
GtkCellEditable, GtkCellEditable
GtkCellEditable::editing-done, The "editing-done" signal
GtkCellEditable::remove-widget, The "remove-widget" signal
GtkCellEditableIface, GtkCellEditableIface
GtkCellLayout, GtkCellLayout
GtkCellLayoutDataFunc, GtkCellLayoutDataFunc ()
GtkCellLayoutIface, GtkCellLayoutIface
GtkCellPixmap, GtkCellPixmap
GtkCellPixText, GtkCellPixText
GtkCellRenderer, GtkCellRenderer
GtkCellRenderer::editing-canceled, The "editing-canceled" signal
GtkCellRenderer::editing-started, The "editing-started" signal
GtkCellRenderer:cell-background, The "cell-background" property
GtkCellRenderer:cell-background-gdk, The "cell-background-gdk" property
GtkCellRenderer:cell-background-set, The "cell-background-set" property
GtkCellRenderer:height, The "height" property
GtkCellRenderer:is-expanded, The "is-expanded" property
GtkCellRenderer:is-expander, The "is-expander" property
GtkCellRenderer:mode, The "mode" property
GtkCellRenderer:sensitive, The "sensitive" property
GtkCellRenderer:visible, The "visible" property
GtkCellRenderer:width, The "width" property
GtkCellRenderer:xalign, The "xalign" property
GtkCellRenderer:xpad, The "xpad" property
GtkCellRenderer:yalign, The "yalign" property
GtkCellRenderer:ypad, The "ypad" property
GtkCellRendererAccel, GtkCellRendererAccel
GtkCellRendererAccel::accel-cleared, The "accel-cleared" signal
GtkCellRendererAccel::accel-edited, The "accel-edited" signal
GtkCellRendererAccel:accel-key, The "accel-key" property
GtkCellRendererAccel:accel-mode, The "accel-mode" property
GtkCellRendererAccel:accel-mods, The "accel-mods" property
GtkCellRendererAccel:keycode, The "keycode" property
GtkCellRendererAccelMode, enum GtkCellRendererAccelMode
GtkCellRendererCombo, GtkCellRendererCombo
GtkCellRendererCombo:has-entry, The "has-entry" property
GtkCellRendererCombo:model, The "model" property
GtkCellRendererCombo:text-column, The "text-column" property
GtkCellRendererMode, enum GtkCellRendererMode
GtkCellRendererPixbuf, GtkCellRendererPixbuf
GtkCellRendererPixbuf:follow-state, The "follow-state" property
GtkCellRendererPixbuf:icon-name, The "icon-name" property
GtkCellRendererPixbuf:pixbuf, The "pixbuf" property
GtkCellRendererPixbuf:pixbuf-expander-closed, The "pixbuf-expander-closed" property
GtkCellRendererPixbuf:pixbuf-expander-open, The "pixbuf-expander-open" property
GtkCellRendererPixbuf:stock-detail, The "stock-detail" property
GtkCellRendererPixbuf:stock-id, The "stock-id" property
GtkCellRendererPixbuf:stock-size, The "stock-size" property
GtkCellRendererProgress, GtkCellRendererProgress
GtkCellRendererProgress:text, The "text" property
GtkCellRendererProgress:value, The "value" property
GtkCellRendererSpin, GtkCellRendererSpin
GtkCellRendererSpin:adjustment, The "adjustment" property
GtkCellRendererSpin:climb-rate, The "climb-rate" property
GtkCellRendererSpin:digits, The "digits" property
GtkCellRendererState, enum GtkCellRendererState
GtkCellRendererText, GtkCellRendererText
GtkCellRendererText::edited, The "edited" signal
GtkCellRendererText:alignment, The "alignment" property
GtkCellRendererText:attributes, The "attributes" property
GtkCellRendererText:background, The "background" property
GtkCellRendererText:background-gdk, The "background-gdk" property
GtkCellRendererText:background-set, The "background-set" property
GtkCellRendererText:editable, The "editable" property
GtkCellRendererText:editable-set, The "editable-set" property
GtkCellRendererText:ellipsize, The "ellipsize" property
GtkCellRendererText:ellipsize-set, The "ellipsize-set" property
GtkCellRendererText:family, The "family" property
GtkCellRendererText:family-set, The "family-set" property
GtkCellRendererText:font, The "font" property
GtkCellRendererText:font-desc, The "font-desc" property
GtkCellRendererText:foreground, The "foreground" property
GtkCellRendererText:foreground-gdk, The "foreground-gdk" property
GtkCellRendererText:foreground-set, The "foreground-set" property
GtkCellRendererText:language, The "language" property
GtkCellRendererText:language-set, The "language-set" property
GtkCellRendererText:markup, The "markup" property
GtkCellRendererText:rise, The "rise" property
GtkCellRendererText:rise-set, The "rise-set" property
GtkCellRendererText:scale, The "scale" property
GtkCellRendererText:scale-set, The "scale-set" property
GtkCellRendererText:single-paragraph-mode, The "single-paragraph-mode" property
GtkCellRendererText:size, The "size" property
GtkCellRendererText:size-points, The "size-points" property
GtkCellRendererText:size-set, The "size-set" property
GtkCellRendererText:stretch, The "stretch" property
GtkCellRendererText:stretch-set, The "stretch-set" property
GtkCellRendererText:strikethrough, The "strikethrough" property
GtkCellRendererText:strikethrough-set, The "strikethrough-set" property
GtkCellRendererText:style, The "style" property
GtkCellRendererText:style-set, The "style-set" property
GtkCellRendererText:text, The "text" property
GtkCellRendererText:underline, The "underline" property
GtkCellRendererText:underline-set, The "underline-set" property
GtkCellRendererText:variant, The "variant" property
GtkCellRendererText:variant-set, The "variant-set" property
GtkCellRendererText:weight, The "weight" property
GtkCellRendererText:weight-set, The "weight-set" property
GtkCellRendererText:width-chars, The "width-chars" property
GtkCellRendererText:wrap-mode, The "wrap-mode" property
GtkCellRendererText:wrap-width, The "wrap-width" property
GtkCellRendererToggle, GtkCellRendererToggle
GtkCellRendererToggle::toggled, The "toggled" signal
GtkCellRendererToggle:activatable, The "activatable" property
GtkCellRendererToggle:active, The "active" property
GtkCellRendererToggle:inconsistent, The "inconsistent" property
GtkCellRendererToggle:indicator-size, The "indicator-size" property
GtkCellRendererToggle:radio, The "radio" property
GtkCellText, GtkCellText
GtkCellType, enum GtkCellType
GtkCellView, GtkCellView
GtkCellView:background, The "background" property
GtkCellView:background-gdk, The "background-gdk" property
GtkCellView:background-set, The "background-set" property
GtkCellView:model, The "model" property
GtkCellWidget, GtkCellWidget
GtkCheckButton, GtkCheckButton
GtkCheckButton:indicator-size, The "indicator-size" style property
GtkCheckButton:indicator-spacing, The "indicator-spacing" style property
GtkCheckMenuItem, GtkCheckMenuItem
GtkCheckMenuItem::toggled, The "toggled" signal
GtkCheckMenuItem:active, The "active" property
GtkCheckMenuItem:draw-as-radio, The "draw-as-radio" property
GtkCheckMenuItem:inconsistent, The "inconsistent" property
GtkCheckMenuItem:indicator-size, The "indicator-size" style property
GtkClassInitFunc, GtkClassInitFunc
GtkClipboard, GtkClipboard
GtkClipboard::owner-change, The "owner-change" signal
GtkClipboardClearFunc, GtkClipboardClearFunc ()
GtkClipboardGetFunc, GtkClipboardGetFunc ()
GtkClipboardImageReceivedFunc, GtkClipboardImageReceivedFunc ()
GtkClipboardReceivedFunc, GtkClipboardReceivedFunc ()
GtkClipboardRichTextReceivedFunc, GtkClipboardRichTextReceivedFunc ()
GtkClipboardTargetsReceivedFunc, GtkClipboardTargetsReceivedFunc ()
GtkClipboardTextReceivedFunc, GtkClipboardTextReceivedFunc ()
GtkCList, GtkCList
GtkCList::abort-column-resize, The "abort-column-resize" signal
GtkCList::click-column, The "click-column" signal
GtkCList::end-selection, The "end-selection" signal
GtkCList::extend-selection, The "extend-selection" signal
GtkCList::resize-column, The "resize-column" signal
GtkCList::row-move, The "row-move" signal
GtkCList::scroll-horizontal, The "scroll-horizontal" signal
GtkCList::scroll-vertical, The "scroll-vertical" signal
GtkCList::select-all, The "select-all" signal
GtkCList::select-row, The "select-row" signal
GtkCList::set-scroll-adjustments, The "set-scroll-adjustments" signal
GtkCList::start-selection, The "start-selection" signal
GtkCList::toggle-add-mode, The "toggle-add-mode" signal
GtkCList::toggle-focus-row, The "toggle-focus-row" signal
GtkCList::undo-selection, The "undo-selection" signal
GtkCList::unselect-all, The "unselect-all" signal
GtkCList::unselect-row, The "unselect-row" signal
GtkCList:n-columns, The "n-columns" property
GtkCList:reorderable, The "reorderable" property
GtkCList:row-height, The "row-height" property
GtkCList:selection-mode, The "selection-mode" property
GtkCList:shadow-type, The "shadow-type" property
GtkCList:sort-type, The "sort-type" property
GtkCList:titles-active, The "titles-active" property
GtkCList:use-drag-icons, The "use-drag-icons" property
GtkCListCellInfo, GtkCListCellInfo
GtkCListColumn, GtkCListColumn
GtkCListCompareFunc, GtkCListCompareFunc ()
GtkCListDestInfo, GtkCListDestInfo
GtkCListDragPos, enum GtkCListDragPos
GtkCListRow, GtkCListRow
GtkColorButton, GtkColorButton
GtkColorButton::color-set, The "color-set" signal
GtkColorButton:alpha, The "alpha" property
GtkColorButton:color, The "color" property
GtkColorButton:title, The "title" property
GtkColorButton:use-alpha, The "use-alpha" property
GtkColorSelection, GtkColorSelection
GtkColorSelection::color-changed, The "color-changed" signal
GtkColorSelection:current-alpha, The "current-alpha" property
GtkColorSelection:current-color, The "current-color" property
GtkColorSelection:has-opacity-control, The "has-opacity-control" property
GtkColorSelection:has-palette, The "has-palette" property
GtkColorSelectionChangePaletteFunc, GtkColorSelectionChangePaletteFunc ()
GtkColorSelectionChangePaletteWithScreenFunc, GtkColorSelectionChangePaletteWithScreenFunc ()
GtkColorSelectionDialog, GtkColorSelectionDialog
GtkCombo, GtkCombo
GtkCombo:allow-empty, The "allow-empty" property
GtkCombo:case-sensitive, The "case-sensitive" property
GtkCombo:enable-arrow-keys, The "enable-arrow-keys" property
GtkCombo:enable-arrows-always, The "enable-arrows-always" property
GtkCombo:value-in-list, The "value-in-list" property
GtkComboBox, GtkComboBox
GtkComboBox::changed, The "changed" signal
GtkComboBox:active, The "active" property
GtkComboBox:add-tearoffs, The "add-tearoffs" property
GtkComboBox:appears-as-list, The "appears-as-list" style property
GtkComboBox:column-span-column, The "column-span-column" property
GtkComboBox:focus-on-click, The "focus-on-click" property
GtkComboBox:has-frame, The "has-frame" property
GtkComboBox:model, The "model" property
GtkComboBox:popup-shown, The "popup-shown" property
GtkComboBox:row-span-column, The "row-span-column" property
GtkComboBox:tearoff-title, The "tearoff-title" property
GtkComboBox:wrap-width, The "wrap-width" property
GtkComboBoxEntry, GtkComboBoxEntry
GtkComboBoxEntry:text-column, The "text-column" property
GtkContainer, GtkContainer
GtkContainer::add, The "add" signal
GtkContainer::check-resize, The "check-resize" signal
GtkContainer::remove, The "remove" signal
GtkContainer::set-focus-child, The "set-focus-child" signal
GtkContainer:border-width, The "border-width" property
GtkContainer:child, The "child" property
GtkContainer:resize-mode, The "resize-mode" property
GtkCornerType, enum GtkCornerType
GtkCTree, GtkCTree
GtkCTree::change-focus-row-expansion, The "change-focus-row-expansion" signal
GtkCTree::tree-collapse, The "tree-collapse" signal
GtkCTree::tree-expand, The "tree-expand" signal
GtkCTree::tree-move, The "tree-move" signal
GtkCTree::tree-select-row, The "tree-select-row" signal
GtkCTree::tree-unselect-row, The "tree-unselect-row" signal
GtkCTree:expander-style, The "expander-style" property
GtkCTree:indent, The "indent" property
GtkCTree:line-style, The "line-style" property
GtkCTree:n-columns, The "n-columns" property
GtkCTree:show-stub, The "show-stub" property
GtkCTree:spacing, The "spacing" property
GtkCTree:tree-column, The "tree-column" property
GtkCTreeCompareDragFunc, GtkCTreeCompareDragFunc ()
GtkCTreeExpanderStyle, enum GtkCTreeExpanderStyle
GtkCTreeExpansionType, enum GtkCTreeExpansionType
GtkCTreeFunc, GtkCTreeFunc ()
GtkCTreeGNodeFunc, GtkCTreeGNodeFunc ()
GtkCTreeLineStyle, enum GtkCTreeLineStyle
GtkCTreeNode, GtkCTreeNode
GtkCTreePos, enum GtkCTreePos
GtkCTreeRow, GtkCTreeRow
GtkCurve, GtkCurve
GtkCurve::curve-type-changed, The "curve-type-changed" signal
GtkCurve:curve-type, The "curve-type" property
GtkCurve:max-x, The "max-x" property
GtkCurve:max-y, The "max-y" property
GtkCurve:min-x, The "min-x" property
GtkCurve:min-y, The "min-y" property
GtkCurveType, enum GtkCurveType
GtkDeleteType, enum GtkDeleteType
GtkDestDefaults, enum GtkDestDefaults
GtkDestroyNotify, GtkDestroyNotify ()
GtkDialog, GtkDialog
GtkDialog::close, The "close" signal
GtkDialog::response, The "response" signal
GtkDialog:action-area-border, The "action-area-border" style property
GtkDialog:button-spacing, The "button-spacing" style property
GtkDialog:content-area-border, The "content-area-border" style property
GtkDialog:has-separator, The "has-separator" property
GtkDialogFlags, enum GtkDialogFlags
GtkDirectionType, enum GtkDirectionType
GtkDitherInfo, union GtkDitherInfo
GtkDrawingArea, GtkDrawingArea
GtkEditable, GtkEditable
GtkEditable::changed, The "changed" signal
GtkEditable::delete-text, The "delete-text" signal
GtkEditable::insert-text, The "insert-text" signal
GtkEntry, GtkEntry
GtkEntry::activate, The "activate" signal
GtkEntry::backspace, The "backspace" signal
GtkEntry::copy-clipboard, The "copy-clipboard" signal
GtkEntry::cut-clipboard, The "cut-clipboard" signal
GtkEntry::delete-from-cursor, The "delete-from-cursor" signal
GtkEntry::insert-at-cursor, The "insert-at-cursor" signal
GtkEntry::move-cursor, The "move-cursor" signal
GtkEntry::paste-clipboard, The "paste-clipboard" signal
GtkEntry::populate-popup, The "populate-popup" signal
GtkEntry::toggle-overwrite, The "toggle-overwrite" signal
GtkEntry:activates-default, The "activates-default" property
GtkEntry:cursor-position, The "cursor-position" property
GtkEntry:editable, The "editable" property
GtkEntry:has-frame, The "has-frame" property
GtkEntry:inner-border, The "inner-border" property, The "inner-border" style property
GtkEntry:invisible-char, The "invisible-char" property
GtkEntry:max-length, The "max-length" property
GtkEntry:scroll-offset, The "scroll-offset" property
GtkEntry:selection-bound, The "selection-bound" property
GtkEntry:text, The "text" property
GtkEntry:truncate-multiline, The "truncate-multiline" property
GtkEntry:visibility, The "visibility" property
GtkEntry:width-chars, The "width-chars" property
GtkEntry:xalign, The "xalign" property
GtkEntryCompletion, GtkEntryCompletion
GtkEntryCompletion::action-activated, The "action-activated" signal
GtkEntryCompletion::insert-prefix, The "insert-prefix" signal
GtkEntryCompletion::match-selected, The "match-selected" signal
GtkEntryCompletion:inline-completion, The "inline-completion" property
GtkEntryCompletion:minimum-key-length, The "minimum-key-length" property
GtkEntryCompletion:model, The "model" property
GtkEntryCompletion:popup-completion, The "popup-completion" property
GtkEntryCompletion:popup-set-width, The "popup-set-width" property
GtkEntryCompletion:popup-single-match, The "popup-single-match" property
GtkEntryCompletion:text-column, The "text-column" property
GtkEntryCompletionMatchFunc, GtkEntryCompletionMatchFunc ()
GtkEnumValue, GtkEnumValue
GtkEventBox, GtkEventBox
GtkEventBox:above-child, The "above-child" property
GtkEventBox:visible-window, The "visible-window" property
GtkExpander, GtkExpander
GtkExpander::activate, The "activate" signal
GtkExpander:expanded, The "expanded" property
GtkExpander:expander-size, The "expander-size" style property
GtkExpander:expander-spacing, The "expander-spacing" style property
GtkExpander:label, The "label" property
GtkExpander:label-widget, The "label-widget" property
GtkExpander:spacing, The "spacing" property
GtkExpander:use-markup, The "use-markup" property
GtkExpander:use-underline, The "use-underline" property
GtkExpanderStyle, enum GtkExpanderStyle
GtkFileChooser, GtkFileChooser
GtkFileChooser::confirm-overwrite, The "confirm-overwrite" signal
GtkFileChooser::current-folder-changed, The "current-folder-changed" signal
GtkFileChooser::file-activated, The "file-activated" signal
GtkFileChooser::selection-changed, The "selection-changed" signal
GtkFileChooser::update-preview, The "update-preview" signal
GtkFileChooserAction, enum GtkFileChooserAction
GtkFileChooserButton, GtkFileChooserButton
GtkFileChooserButton:dialog, The "dialog" property
GtkFileChooserButton:focus-on-click, The "focus-on-click" property
GtkFileChooserButton:title, The "title" property
GtkFileChooserButton:width-chars, The "width-chars" property
GtkFileChooserConfirmation, enum GtkFileChooserConfirmation
GtkFileChooserDialog, GtkFileChooserDialog
GtkFileChooserError, enum GtkFileChooserError
GtkFileChooserWidget, GtkFileChooserWidget
GtkFileFilter, GtkFileFilter
GtkFileFilterFlags, enum GtkFileFilterFlags
GtkFileFilterFunc, GtkFileFilterFunc ()
GtkFileFilterInfo, GtkFileFilterInfo
GtkFileSelection, GtkFileSelection
GtkFileSelection:filename, The "filename" property
GtkFileSelection:select-multiple, The "select-multiple" property
GtkFileSelection:show-fileops, The "show-fileops" property
GtkFixed, GtkFixed
GtkFixed:x, The "x" child property
GtkFixed:y, The "y" child property
GtkFixedChild, GtkFixedChild
GtkFlagValue, GtkFlagValue
GtkFontButton, GtkFontButton
GtkFontButton::font-set, The "font-set" signal
GtkFontButton:font-name, The "font-name" property
GtkFontButton:show-size, The "show-size" property
GtkFontButton:show-style, The "show-style" property
GtkFontButton:title, The "title" property
GtkFontButton:use-font, The "use-font" property
GtkFontButton:use-size, The "use-size" property
GtkFontSelection, GtkFontSelection
GtkFontSelection:font, The "font" property
GtkFontSelection:font-name, The "font-name" property
GtkFontSelection:preview-text, The "preview-text" property
GtkFontSelectionDialog, GtkFontSelectionDialog
GtkFrame, GtkFrame
GtkFrame:label, The "label" property
GtkFrame:label-widget, The "label-widget" property
GtkFrame:label-xalign, The "label-xalign" property
GtkFrame:label-yalign, The "label-yalign" property
GtkFrame:shadow, The "shadow" property
GtkFrame:shadow-type, The "shadow-type" property
GtkFunction, GtkFunction ()
GtkFundamentalType, GtkFundamentalType
GtkGammaCurve, GtkGammaCurve
GtkHandleBox, GtkHandleBox
GtkHandleBox::child-attached, The "child-attached" signal
GtkHandleBox::child-detached, The "child-detached" signal
GtkHandleBox:handle-position, The "handle-position" property
GtkHandleBox:shadow, The "shadow" property
GtkHandleBox:shadow-type, The "shadow-type" property
GtkHandleBox:snap-edge, The "snap-edge" property
GtkHandleBox:snap-edge-set, The "snap-edge-set" property
GtkHBox, GtkHBox
GtkHButtonBox, GtkHButtonBox
GtkHPaned, GtkHPaned
GtkHRuler, GtkHRuler
GtkHScale, GtkHScale
GtkHScrollbar, GtkHScrollbar
GtkHSeparator, GtkHSeparator
GtkIconFactory, GtkIconFactory
GtkIconInfo, GtkIconInfo
GtkIconLookupFlags, enum GtkIconLookupFlags
GtkIconSet, GtkIconSet
GtkIconSize, enum GtkIconSize
GtkIconSource, GtkIconSource
GtkIconTheme, GtkIconTheme
GtkIconTheme::changed, The "changed" signal
GtkIconThemeError, enum GtkIconThemeError
GtkIconView, GtkIconView
GtkIconView::activate-cursor-item, The "activate-cursor-item" signal
GtkIconView::item-activated, The "item-activated" signal
GtkIconView::move-cursor, The "move-cursor" signal
GtkIconView::select-all, The "select-all" signal
GtkIconView::select-cursor-item, The "select-cursor-item" signal
GtkIconView::selection-changed, The "selection-changed" signal
GtkIconView::set-scroll-adjustments, The "set-scroll-adjustments" signal
GtkIconView::toggle-cursor-item, The "toggle-cursor-item" signal
GtkIconView::unselect-all, The "unselect-all" signal
GtkIconView:column-spacing, The "column-spacing" property
GtkIconView:columns, The "columns" property
GtkIconView:item-width, The "item-width" property
GtkIconView:margin, The "margin" property
GtkIconView:markup-column, The "markup-column" property
GtkIconView:model, The "model" property
GtkIconView:orientation, The "orientation" property
GtkIconView:pixbuf-column, The "pixbuf-column" property
GtkIconView:reorderable, The "reorderable" property
GtkIconView:row-spacing, The "row-spacing" property
GtkIconView:selection-box-alpha, The "selection-box-alpha" style property
GtkIconView:selection-box-color, The "selection-box-color" style property
GtkIconView:selection-mode, The "selection-mode" property
GtkIconView:spacing, The "spacing" property
GtkIconView:text-column, The "text-column" property
GtkIconViewDropPosition, enum GtkIconViewDropPosition
GtkIconViewForeachFunc, GtkIconViewForeachFunc ()
GtkImage, GtkImage
GtkImage:file, The "file" property
GtkImage:icon-name, The "icon-name" property
GtkImage:icon-set, The "icon-set" property
GtkImage:icon-size, The "icon-size" property
GtkImage:image, The "image" property
GtkImage:mask, The "mask" property
GtkImage:pixbuf, The "pixbuf" property
GtkImage:pixbuf-animation, The "pixbuf-animation" property
GtkImage:pixel-size, The "pixel-size" property
GtkImage:pixmap, The "pixmap" property
GtkImage:stock, The "stock" property
GtkImage:storage-type, The "storage-type" property
GtkImageMenuItem, GtkImageMenuItem
GtkImageMenuItem:image, The "image" property
GtkImageType, enum GtkImageType
GtkIMContext, GtkIMContext
GtkIMContext::commit, The "commit" signal
GtkIMContext::delete-surrounding, The "delete-surrounding" signal
GtkIMContext::preedit-changed, The "preedit-changed" signal
GtkIMContext::preedit-end, The "preedit-end" signal
GtkIMContext::preedit-start, The "preedit-start" signal
GtkIMContext::retrieve-surrounding, The "retrieve-surrounding" signal
GtkIMContextSimple, GtkIMContextSimple
GtkIMMulticontext, GtkIMMulticontext
GtkIMPreeditStyle, enum GtkIMPreeditStyle
GtkIMStatusStyle, enum GtkIMStatusStyle
GtkInputDialog, GtkInputDialog
GtkInputDialog::disable-device, The "disable-device" signal
GtkInputDialog::enable-device, The "enable-device" signal
GtkInvisible, GtkInvisible
GtkInvisible:screen, The "screen" property
GtkItem, GtkItem
GtkItem::deselect, The "deselect" signal
GtkItem::select, The "select" signal
GtkItem::toggle, The "toggle" signal
GtkItemFactory, GtkItemFactory
GtkItemFactoryCallback, GtkItemFactoryCallback ()
GtkItemFactoryCallback1, GtkItemFactoryCallback1 ()
GtkItemFactoryCallback2, GtkItemFactoryCallback2 ()
GtkItemFactoryEntry, GtkItemFactoryEntry
GtkItemFactoryItem, GtkItemFactoryItem
GtkJustification, enum GtkJustification
GtkKeySnoopFunc, GtkKeySnoopFunc ()
GtkLabel, GtkLabel
GtkLabel::copy-clipboard, The "copy-clipboard" signal
GtkLabel::move-cursor, The "move-cursor" signal
GtkLabel::populate-popup, The "populate-popup" signal
GtkLabel:angle, The "angle" property
GtkLabel:attributes, The "attributes" property
GtkLabel:cursor-position, The "cursor-position" property
GtkLabel:ellipsize, The "ellipsize" property
GtkLabel:justify, The "justify" property
GtkLabel:label, The "label" property
GtkLabel:max-width-chars, The "max-width-chars" property
GtkLabel:mnemonic-keyval, The "mnemonic-keyval" property
GtkLabel:mnemonic-widget, The "mnemonic-widget" property
GtkLabel:pattern, The "pattern" property
GtkLabel:selectable, The "selectable" property
GtkLabel:selection-bound, The "selection-bound" property
GtkLabel:single-line-mode, The "single-line-mode" property
GtkLabel:use-markup, The "use-markup" property
GtkLabel:use-underline, The "use-underline" property
GtkLabel:width-chars, The "width-chars" property
GtkLabel:wrap, The "wrap" property
GtkLabel:wrap-mode, The "wrap-mode" property
GtkLayout, GtkLayout
GtkLayout::set-scroll-adjustments, The "set-scroll-adjustments" signal
GtkLayout:hadjustment, The "hadjustment" property
GtkLayout:height, The "height" property
GtkLayout:vadjustment, The "vadjustment" property
GtkLayout:width, The "width" property
GtkLayout:x, The "x" child property
GtkLayout:y, The "y" child property
GtkLinkButton, GtkLinkButton
GtkLinkButton:uri, The "uri" property
GtkLinkButtonUriFunc, GtkLinkButtonUriFunc ()
GtkList, GtkList
GtkList::select-child, The "select-child" signal
GtkList::selection-changed, The "selection-changed" signal
GtkList::unselect-child, The "unselect-child" signal
GtkList:selection-mode, The "selection-mode" property
GtkListItem, GtkListItem
GtkListItem::end-selection, The "end-selection" signal
GtkListItem::extend-selection, The "extend-selection" signal
GtkListItem::scroll-horizontal, The "scroll-horizontal" signal
GtkListItem::scroll-vertical, The "scroll-vertical" signal
GtkListItem::select-all, The "select-all" signal
GtkListItem::start-selection, The "start-selection" signal
GtkListItem::toggle-add-mode, The "toggle-add-mode" signal
GtkListItem::toggle-focus-row, The "toggle-focus-row" signal
GtkListItem::undo-selection, The "undo-selection" signal
GtkListItem::unselect-all, The "unselect-all" signal
GtkListStore, GtkListStore
GtkMatchType, enum GtkMatchType
GtkMenu, GtkMenu
GtkMenu::move-scroll, The "move-scroll" signal
GtkMenu:bottom-attach, The "bottom-attach" child property
GtkMenu:double-arrows, The "double-arrows" style property
GtkMenu:horizontal-offset, The "horizontal-offset" style property
GtkMenu:horizontal-padding, The "horizontal-padding" style property
GtkMenu:left-attach, The "left-attach" child property
GtkMenu:right-attach, The "right-attach" child property
GtkMenu:tearoff-state, The "tearoff-state" property
GtkMenu:tearoff-title, The "tearoff-title" property
GtkMenu:top-attach, The "top-attach" child property
GtkMenu:vertical-offset, The "vertical-offset" style property
GtkMenu:vertical-padding, The "vertical-padding" style property
GtkMenuBar, GtkMenuBar
GtkMenuBar:child-pack-direction, The "child-pack-direction" property
GtkMenuBar:internal-padding, The "internal-padding" style property
GtkMenuBar:pack-direction, The "pack-direction" property
GtkMenuBar:shadow-type, The "shadow-type" style property
GtkMenuDetachFunc, GtkMenuDetachFunc ()
GtkMenuDirectionType, enum GtkMenuDirectionType
GtkMenuItem, GtkMenuItem
GtkMenuItem::activate, The "activate" signal
GtkMenuItem::activate-item, The "activate-item" signal
GtkMenuItem::toggle-size-allocate, The "toggle-size-allocate" signal
GtkMenuItem::toggle-size-request, The "toggle-size-request" signal
GtkMenuItem:arrow-spacing, The "arrow-spacing" style property
GtkMenuItem:horizontal-padding, The "horizontal-padding" style property
GtkMenuItem:selected-shadow-type, The "selected-shadow-type" style property
GtkMenuItem:toggle-spacing, The "toggle-spacing" style property
GtkMenuPositionFunc, GtkMenuPositionFunc ()
GtkMenuShell, GtkMenuShell
GtkMenuShell::activate-current, The "activate-current" signal
GtkMenuShell::cancel, The "cancel" signal
GtkMenuShell::cycle-focus, The "cycle-focus" signal
GtkMenuShell::deactivate, The "deactivate" signal
GtkMenuShell::move-current, The "move-current" signal
GtkMenuShell::selection-done, The "selection-done" signal
GtkMenuShell:take-focus, The "take-focus" property
GtkMenuToolButton, GtkMenuToolButton
GtkMenuToolButton::show-menu, The "show-menu" signal
GtkMenuToolButton:menu, The "menu" property
GtkMessageDialog, GtkMessageDialog
GtkMessageDialog:buttons, The "buttons" property
GtkMessageDialog:image, The "image" property
GtkMessageDialog:message-border, The "message-border" style property
GtkMessageDialog:message-type, The "message-type" property
GtkMessageDialog:secondary-text, The "secondary-text" property
GtkMessageDialog:secondary-use-markup, The "secondary-use-markup" property
GtkMessageDialog:text, The "text" property
GtkMessageDialog:use-markup, The "use-markup" property
GtkMessageDialog:use-separator, The "use-separator" style property
GtkMessageType, enum GtkMessageType
GtkMetricType, enum GtkMetricType
GtkMisc, GtkMisc
GtkMisc:xalign, The "xalign" property
GtkMisc:xpad, The "xpad" property
GtkMisc:yalign, The "yalign" property
GtkMisc:ypad, The "ypad" property
GtkModuleDisplayInitFunc, GtkModuleDisplayInitFunc ()
GtkModuleInitFunc, GtkModuleInitFunc ()
GtkMovementStep, enum GtkMovementStep
GtkNotebook, GtkNotebook
GtkNotebook::change-current-page, The "change-current-page" signal
GtkNotebook::focus-tab, The "focus-tab" signal
GtkNotebook::move-focus-out, The "move-focus-out" signal
GtkNotebook::page-added, The "page-added" signal
GtkNotebook::page-removed, The "page-removed" signal
GtkNotebook::page-reordered, The "page-reordered" signal
GtkNotebook::reorder-tab, The "reorder-tab" signal
GtkNotebook::select-page, The "select-page" signal
GtkNotebook::switch-page, The "switch-page" signal
GtkNotebook:arrow-spacing, The "arrow-spacing" style property
GtkNotebook:detachable, The "detachable" child property
GtkNotebook:enable-popup, The "enable-popup" property
GtkNotebook:group-id, The "group-id" property
GtkNotebook:has-backward-stepper, The "has-backward-stepper" style property
GtkNotebook:has-forward-stepper, The "has-forward-stepper" style property
GtkNotebook:has-secondary-backward-stepper, The "has-secondary-backward-stepper" style property
GtkNotebook:has-secondary-forward-stepper, The "has-secondary-forward-stepper" style property
GtkNotebook:homogeneous, The "homogeneous" property
GtkNotebook:menu-label, The "menu-label" child property
GtkNotebook:page, The "page" property
GtkNotebook:position, The "position" child property
GtkNotebook:reorderable, The "reorderable" child property
GtkNotebook:scrollable, The "scrollable" property
GtkNotebook:show-border, The "show-border" property
GtkNotebook:show-tabs, The "show-tabs" property
GtkNotebook:tab-border, The "tab-border" property
GtkNotebook:tab-curvature, The "tab-curvature" style property
GtkNotebook:tab-expand, The "tab-expand" child property
GtkNotebook:tab-fill, The "tab-fill" child property
GtkNotebook:tab-hborder, The "tab-hborder" property
GtkNotebook:tab-label, The "tab-label" child property
GtkNotebook:tab-overlap, The "tab-overlap" style property
GtkNotebook:tab-pack, The "tab-pack" child property
GtkNotebook:tab-pos, The "tab-pos" property
GtkNotebook:tab-vborder, The "tab-vborder" property
GtkNotebookPage, GtkNotebookPage
GtkNotebookWindowCreationFunc, GtkNotebookWindowCreationFunc ()
GtkObject, GtkObject
GtkObject::destroy, The "destroy" signal
GtkObject:user-data, The "user-data" property
GtkObjectFlags, enum GtkObjectFlags
GtkObjectInitFunc, GtkObjectInitFunc
GtkOldEditable, GtkOldEditable
GtkOldEditable::activate, The "activate" signal
GtkOldEditable::copy-clipboard, The "copy-clipboard" signal
GtkOldEditable::cut-clipboard, The "cut-clipboard" signal
GtkOldEditable::kill-char, The "kill-char" signal
GtkOldEditable::kill-line, The "kill-line" signal
GtkOldEditable::kill-word, The "kill-word" signal
GtkOldEditable::move-cursor, The "move-cursor" signal
GtkOldEditable::move-page, The "move-page" signal
GtkOldEditable::move-to-column, The "move-to-column" signal
GtkOldEditable::move-to-row, The "move-to-row" signal
GtkOldEditable::move-word, The "move-word" signal
GtkOldEditable::paste-clipboard, The "paste-clipboard" signal
GtkOldEditable::set-editable, The "set-editable" signal
GtkOldEditable:editable, The "editable" property
GtkOldEditable:text-position, The "text-position" property
GtkOptionMenu, GtkOptionMenu
GtkOptionMenu::changed, The "changed" signal
GtkOptionMenu:indicator-size, The "indicator-size" style property
GtkOptionMenu:indicator-spacing, The "indicator-spacing" style property
GtkOptionMenu:menu, The "menu" property
GtkOrientation, enum GtkOrientation
GtkPackDirection, enum GtkPackDirection
GtkPackType, enum GtkPackType
GtkPageOrientation, enum GtkPageOrientation
GtkPageRange, GtkPageRange
GtkPageSet, enum GtkPageSet
GtkPageSetup, GtkPageSetup
GtkPageSetupDoneFunc, GtkPageSetupDoneFunc ()
GtkPageSetupUnixDialog, GtkPageSetupUnixDialog
GtkPaned, GtkPaned
GtkPaned::accept-position, The "accept-position" signal
GtkPaned::cancel-position, The "cancel-position" signal
GtkPaned::cycle-child-focus, The "cycle-child-focus" signal
GtkPaned::cycle-handle-focus, The "cycle-handle-focus" signal
GtkPaned::move-handle, The "move-handle" signal
GtkPaned::toggle-handle-focus, The "toggle-handle-focus" signal
GtkPaned:handle-size, The "handle-size" style property
GtkPaned:max-position, The "max-position" property
GtkPaned:min-position, The "min-position" property
GtkPaned:position, The "position" property
GtkPaned:position-set, The "position-set" property
GtkPaned:resize, The "resize" child property
GtkPaned:shrink, The "shrink" child property
GtkPaperSize, GtkPaperSize
GtkPathPriorityType, enum GtkPathPriorityType
GtkPathType, enum GtkPathType
GtkPixmap, GtkPixmap
GtkPlug, GtkPlug
GtkPlug::embedded, The "embedded" signal
GtkPolicyType, enum GtkPolicyType
GtkPositionType, enum GtkPositionType
GtkPreview, GtkPreview
GtkPreview:expand, The "expand" property
GtkPreviewInfo, GtkPreviewInfo
GtkPreviewType, enum GtkPreviewType
GtkPrintBackend, GtkPrintBackend
GtkPrintCapabilities, enum GtkPrintCapabilities
GtkPrintContext, GtkPrintContext
GtkPrintDuplex, enum GtkPrintDuplex
GtkPrinter, GtkPrinter
GtkPrinter::details-acquired, The "details-acquired" signal
GtkPrinter:accepts-pdf, The "accepts-pdf" property
GtkPrinter:accepts-ps, The "accepts-ps" property
GtkPrinter:backend, The "backend" property
GtkPrinter:icon-name, The "icon-name" property
GtkPrinter:is-virtual, The "is-virtual" property
GtkPrinter:job-count, The "job-count" property
GtkPrinter:location, The "location" property
GtkPrinter:name, The "name" property
GtkPrinter:state-message, The "state-message" property
GtkPrinterFunc, GtkPrinterFunc ()
GtkPrintError, enum GtkPrintError
GtkPrintFunc, GtkPrintFunc ()
GtkPrintJob, GtkPrintJob
GtkPrintJob::status-changed, The "status-changed" signal
GtkPrintJob:page-setup, The "page-setup" property
GtkPrintJob:printer, The "printer" property
GtkPrintJob:settings, The "settings" property
GtkPrintJob:title, The "title" property
GtkPrintJob:track-print-status, The "track-print-status" property
GtkPrintJobCompleteFunc, GtkPrintJobCompleteFunc ()
GtkPrintOperation, GtkPrintOperation
GtkPrintOperation::begin-print, The "begin-print" signal
GtkPrintOperation::create-custom-widget, The "create-custom-widget" signal
GtkPrintOperation::custom-widget-apply, The "custom-widget-apply" signal
GtkPrintOperation::done, The "done" signal
GtkPrintOperation::draw-page, The "draw-page" signal
GtkPrintOperation::end-print, The "end-print" signal
GtkPrintOperation::paginate, The "paginate" signal
GtkPrintOperation::preview, The "preview" signal
GtkPrintOperation::request-page-setup, The "request-page-setup" signal
GtkPrintOperation::status-changed, The "status-changed" signal
GtkPrintOperation:allow-async, The "allow-async" property
GtkPrintOperation:current-page, The "current-page" property
GtkPrintOperation:custom-tab-label, The "custom-tab-label" property
GtkPrintOperation:default-page-setup, The "default-page-setup" property
GtkPrintOperation:export-filename, The "export-filename" property
GtkPrintOperation:job-name, The "job-name" property
GtkPrintOperation:n-pages, The "n-pages" property
GtkPrintOperation:print-settings, The "print-settings" property
GtkPrintOperation:show-progress, The "show-progress" property
GtkPrintOperation:status, The "status" property
GtkPrintOperation:status-string, The "status-string" property
GtkPrintOperation:track-print-status, The "track-print-status" property
GtkPrintOperation:unit, The "unit" property
GtkPrintOperation:use-full-page, The "use-full-page" property
GtkPrintOperationAction, enum GtkPrintOperationAction
GtkPrintOperationPreview, GtkPrintOperationPreview
GtkPrintOperationResult, enum GtkPrintOperationResult
GtkPrintPages, enum GtkPrintPages
GtkPrintQuality, enum GtkPrintQuality
GtkPrintSettings, GtkPrintSettings
GtkPrintSettingsFunc, GtkPrintSettingsFunc ()
GtkPrintStatus, enum GtkPrintStatus
GtkPrintUnixDialog, GtkPrintUnixDialog
GtkPrintUnixDialog:current-page, The "current-page" property
GtkPrintUnixDialog:page-setup, The "page-setup" property
GtkPrintUnixDialog:print-settings, The "print-settings" property
GtkPrintUnixDialog:selected-printer, The "selected-printer" property
GtkProgress, GtkProgress
GtkProgress:activity-mode, The "activity-mode" property
GtkProgress:show-text, The "show-text" property
GtkProgress:text-xalign, The "text-xalign" property
GtkProgress:text-yalign, The "text-yalign" property
GtkProgressBar, GtkProgressBar
GtkProgressBar:activity-blocks, The "activity-blocks" property
GtkProgressBar:activity-step, The "activity-step" property
GtkProgressBar:adjustment, The "adjustment" property
GtkProgressBar:bar-style, The "bar-style" property
GtkProgressBar:discrete-blocks, The "discrete-blocks" property
GtkProgressBar:ellipsize, The "ellipsize" property
GtkProgressBar:fraction, The "fraction" property
GtkProgressBar:orientation, The "orientation" property
GtkProgressBar:pulse-step, The "pulse-step" property
GtkProgressBar:text, The "text" property
GtkProgressBarOrientation, enum GtkProgressBarOrientation
GtkProgressBarStyle, enum GtkProgressBarStyle
GtkPropertyMark, GtkPropertyMark
GtkRadioAction, GtkRadioAction
GtkRadioAction::changed, The "changed" signal
GtkRadioAction:current-value, The "current-value" property
GtkRadioAction:group, The "group" property
GtkRadioAction:value, The "value" property
GtkRadioActionEntry, GtkRadioActionEntry
GtkRadioButton, GtkRadioButton
GtkRadioButton::group-changed, The "group-changed" signal
GtkRadioButton:group, The "group" property
GtkRadioMenuItem, GtkRadioMenuItem
GtkRadioMenuItem::group-changed, The "group-changed" signal
GtkRadioMenuItem:group, The "group" property
GtkRadioToolButton, GtkRadioToolButton
GtkRadioToolButton:group, The "group" property
GtkRange, GtkRange
GtkRange::adjust-bounds, The "adjust-bounds" signal
GtkRange::change-value, The "change-value" signal
GtkRange::move-slider, The "move-slider" signal
GtkRange::value-changed, The "value-changed" signal
GtkRange:activate-slider, The "activate-slider" style property
GtkRange:adjustment, The "adjustment" property
GtkRange:arrow-displacement-x, The "arrow-displacement-x" style property
GtkRange:arrow-displacement-y, The "arrow-displacement-y" style property
GtkRange:inverted, The "inverted" property
GtkRange:lower-stepper-sensitivity, The "lower-stepper-sensitivity" property
GtkRange:slider-width, The "slider-width" style property
GtkRange:stepper-size, The "stepper-size" style property
GtkRange:stepper-spacing, The "stepper-spacing" style property
GtkRange:trough-border, The "trough-border" style property
GtkRange:trough-side-details, The "trough-side-details" style property
GtkRange:trough-under-steppers, The "trough-under-steppers" style property
GtkRange:update-policy, The "update-policy" property
GtkRange:upper-stepper-sensitivity, The "upper-stepper-sensitivity" property
GtkRcFlags, enum GtkRcFlags
GtkRcProperty, GtkRcProperty
GtkRcPropertyParser, GtkRcPropertyParser ()
GtkRcStyle, GtkRcStyle
GtkRcTokenType, enum GtkRcTokenType
GtkRecentChooser, GtkRecentChooser
GtkRecentChooser::item-activated, The "item-activated" signal
GtkRecentChooser::selection-changed, The "selection-changed" signal
GtkRecentChooserDialog, GtkRecentChooserDialog
GtkRecentChooserError, enum GtkRecentChooserError
GtkRecentChooserIface, GtkRecentChooserIface
GtkRecentChooserMenu, GtkRecentChooserMenu
GtkRecentChooserMenu:show-numbers, The "show-numbers" property
GtkRecentChooserWidget, GtkRecentChooserWidget
GtkRecentData, GtkRecentData
GtkRecentFilter, GtkRecentFilter
GtkRecentFilterFlags, enum GtkRecentFilterFlags
GtkRecentFilterFunc, GtkRecentFilterFunc ()
GtkRecentFilterInfo, GtkRecentFilterInfo
GtkRecentInfo, GtkRecentInfo
GtkRecentManager, GtkRecentManager
GtkRecentManager::changed, The "changed" signal
GtkRecentManager:filename, The "filename" property
GtkRecentManager:limit, The "limit" property
GtkRecentManager:size, The "size" property
GtkRecentManagerError, enum GtkRecentManagerError
GtkRecentSortFunc, GtkRecentSortFunc ()
GtkRecentSortType, enum GtkRecentSortType
GtkReliefStyle, enum GtkReliefStyle
GtkRequisition, GtkRequisition
GtkResizeMode, enum GtkResizeMode
GtkResponseType, enum GtkResponseType
GtkRuler, GtkRuler
GtkRuler:lower, The "lower" property
GtkRuler:max-size, The "max-size" property
GtkRuler:metric, The "metric" property
GtkRuler:position, The "position" property
GtkRuler:upper, The "upper" property
GtkRulerMetric, GtkRulerMetric
GtkScale, GtkScale
GtkScale::format-value, The "format-value" signal
GtkScale:digits, The "digits" property
GtkScale:draw-value, The "draw-value" property
GtkScale:slider-length, The "slider-length" style property
GtkScale:value-pos, The "value-pos" property
GtkScale:value-spacing, The "value-spacing" style property
GtkScrollbar, GtkScrollbar
GtkScrollbar:fixed-slider-length, The "fixed-slider-length" style property
GtkScrollbar:has-backward-stepper, The "has-backward-stepper" style property
GtkScrollbar:has-forward-stepper, The "has-forward-stepper" style property
GtkScrollbar:has-secondary-backward-stepper, The "has-secondary-backward-stepper" style property
GtkScrollbar:has-secondary-forward-stepper, The "has-secondary-forward-stepper" style property
GtkScrollbar:min-slider-length, The "min-slider-length" style property
GtkScrolledWindow, GtkScrolledWindow
GtkScrolledWindow::move-focus-out, The "move-focus-out" signal
GtkScrolledWindow::scroll-child, The "scroll-child" signal
GtkScrolledWindow:hadjustment, The "hadjustment" property
GtkScrolledWindow:hscrollbar-policy, The "hscrollbar-policy" property
GtkScrolledWindow:scrollbar-spacing, The "scrollbar-spacing" style property
GtkScrolledWindow:shadow-type, The "shadow-type" property
GtkScrolledWindow:vadjustment, The "vadjustment" property
GtkScrolledWindow:vscrollbar-policy, The "vscrollbar-policy" property
GtkScrolledWindow:window-placement, The "window-placement" property
GtkScrolledWindow:window-placement-set, The "window-placement-set" property
GtkScrollStep, enum GtkScrollStep
GtkScrollType, enum GtkScrollType
GtkSelectionData, GtkSelectionData
GtkSelectionMode, enum GtkSelectionMode
GtkSensitivityType, enum GtkSensitivityType
GtkSeparator, GtkSeparator
GtkSeparatorMenuItem, GtkSeparatorMenuItem
GtkSeparatorToolItem, GtkSeparatorToolItem
GtkSeparatorToolItem:draw, The "draw" property
GtkSettings, GtkSettings
GtkSettings:color-hash, The "color-hash" property
GtkSettings:gtk-alternative-button-order, The "gtk-alternative-button-order" property
GtkSettings:gtk-button-images, The "gtk-button-images" property
GtkSettings:gtk-can-change-accels, The "gtk-can-change-accels" property
GtkSettings:gtk-color-palette, The "gtk-color-palette" property
GtkSettings:gtk-color-scheme, The "gtk-color-scheme" property
GtkSettings:gtk-cursor-blink, The "gtk-cursor-blink" property
GtkSettings:gtk-cursor-blink-time, The "gtk-cursor-blink-time" property
GtkSettings:gtk-cursor-theme-name, The "gtk-cursor-theme-name" property
GtkSettings:gtk-cursor-theme-size, The "gtk-cursor-theme-size" property
GtkSettings:gtk-dnd-drag-threshold, The "gtk-dnd-drag-threshold" property
GtkSettings:gtk-double-click-distance, The "gtk-double-click-distance" property
GtkSettings:gtk-double-click-time, The "gtk-double-click-time" property
GtkSettings:gtk-enable-animations, The "gtk-enable-animations" property
GtkSettings:gtk-entry-password-hint-timeout, The "gtk-entry-password-hint-timeout" property
GtkSettings:gtk-entry-select-on-focus, The "gtk-entry-select-on-focus" property
GtkSettings:gtk-fallback-icon-theme, The "gtk-fallback-icon-theme" property
GtkSettings:gtk-font-name, The "gtk-font-name" property
GtkSettings:gtk-icon-sizes, The "gtk-icon-sizes" property
GtkSettings:gtk-icon-theme-name, The "gtk-icon-theme-name" property
GtkSettings:gtk-key-theme-name, The "gtk-key-theme-name" property
GtkSettings:gtk-label-select-on-focus, The "gtk-label-select-on-focus" property
GtkSettings:gtk-menu-bar-accel, The "gtk-menu-bar-accel" property
GtkSettings:gtk-menu-bar-popup-delay, The "gtk-menu-bar-popup-delay" property
GtkSettings:gtk-menu-images, The "gtk-menu-images" property
GtkSettings:gtk-menu-popdown-delay, The "gtk-menu-popdown-delay" property
GtkSettings:gtk-menu-popup-delay, The "gtk-menu-popup-delay" property
GtkSettings:gtk-modules, The "gtk-modules" property
GtkSettings:gtk-scrolled-window-placement, The "gtk-scrolled-window-placement" property
GtkSettings:gtk-show-input-method-menu, The "gtk-show-input-method-menu" property
GtkSettings:gtk-show-unicode-menu, The "gtk-show-unicode-menu" property
GtkSettings:gtk-split-cursor, The "gtk-split-cursor" property
GtkSettings:gtk-theme-name, The "gtk-theme-name" property
GtkSettings:gtk-timeout-expand, The "gtk-timeout-expand" property
GtkSettings:gtk-timeout-initial, The "gtk-timeout-initial" property
GtkSettings:gtk-timeout-repeat, The "gtk-timeout-repeat" property
GtkSettings:gtk-toolbar-icon-size, The "gtk-toolbar-icon-size" property
GtkSettings:gtk-toolbar-style, The "gtk-toolbar-style" property
GtkSettings:gtk-touchscreen-mode, The "gtk-touchscreen-mode" property
GtkSettings:gtk-xft-antialias, The "gtk-xft-antialias" property
GtkSettings:gtk-xft-dpi, The "gtk-xft-dpi" property
GtkSettings:gtk-xft-hinting, The "gtk-xft-hinting" property
GtkSettings:gtk-xft-hintstyle, The "gtk-xft-hintstyle" property
GtkSettings:gtk-xft-rgba, The "gtk-xft-rgba" property
GtkSettingsValue, GtkSettingsValue
GtkShadowType, enum GtkShadowType
GtkSideType, enum GtkSideType
GtkSignalFunc, GtkSignalFunc ()
GtkSignalMarshaller, GtkSignalMarshaller
GtkSignalRunType, enum GtkSignalRunType
GtkSizeGroup, GtkSizeGroup
GtkSizeGroup:ignore-hidden, The "ignore-hidden" property
GtkSizeGroup:mode, The "mode" property
GtkSizeGroupMode, enum GtkSizeGroupMode
GtkSocket, GtkSocket
GtkSocket::plug-added, The "plug-added" signal
GtkSocket::plug-removed, The "plug-removed" signal
GtkSortType, enum GtkSortType
GtkSpinButton, GtkSpinButton
GtkSpinButton::change-value, The "change-value" signal
GtkSpinButton::input, The "input" signal
GtkSpinButton::output, The "output" signal
GtkSpinButton::value-changed, The "value-changed" signal
GtkSpinButton::wrapped, The "wrapped" signal
GtkSpinButton:adjustment, The "adjustment" property
GtkSpinButton:climb-rate, The "climb-rate" property
GtkSpinButton:digits, The "digits" property
GtkSpinButton:numeric, The "numeric" property
GtkSpinButton:shadow-type, The "shadow-type" style property
GtkSpinButton:snap-to-ticks, The "snap-to-ticks" property
GtkSpinButton:update-policy, The "update-policy" property
GtkSpinButton:value, The "value" property
GtkSpinButton:wrap, The "wrap" property
GtkSpinButtonUpdatePolicy, enum GtkSpinButtonUpdatePolicy
GtkSpinType, enum GtkSpinType
GtkStateType, enum GtkStateType
GtkStatusbar, GtkStatusbar
GtkStatusbar::text-popped, The "text-popped" signal
GtkStatusbar::text-pushed, The "text-pushed" signal
GtkStatusbar:has-resize-grip, The "has-resize-grip" property
GtkStatusbar:shadow-type, The "shadow-type" style property
GtkStatusIcon, GtkStatusIcon
GtkStatusIcon::activate, The "activate" signal
GtkStatusIcon::popup-menu, The "popup-menu" signal
GtkStatusIcon::size-changed, The "size-changed" signal
GtkStatusIcon:blinking, The "blinking" property
GtkStatusIcon:file, The "file" property
GtkStatusIcon:icon-name, The "icon-name" property
GtkStatusIcon:pixbuf, The "pixbuf" property
GtkStatusIcon:size, The "size" property
GtkStatusIcon:stock, The "stock" property
GtkStatusIcon:storage-type, The "storage-type" property
GtkStatusIcon:visible, The "visible" property
GtkStockItem, GtkStockItem
GtkStyle, GtkStyle
GtkStyle::realize, The "realize" signal
GtkStyle::unrealize, The "unrealize" signal
GtkSubmenuDirection, enum GtkSubmenuDirection
GtkSubmenuPlacement, enum GtkSubmenuPlacement
GtkTable, GtkTable
GtkTable:bottom-attach, The "bottom-attach" child property
GtkTable:column-spacing, The "column-spacing" property
GtkTable:homogeneous, The "homogeneous" property
GtkTable:left-attach, The "left-attach" child property
GtkTable:n-columns, The "n-columns" property
GtkTable:n-rows, The "n-rows" property
GtkTable:right-attach, The "right-attach" child property
GtkTable:row-spacing, The "row-spacing" property
GtkTable:top-attach, The "top-attach" child property
GtkTable:x-options, The "x-options" child property
GtkTable:x-padding, The "x-padding" child property
GtkTable:y-options, The "y-options" child property
GtkTable:y-padding, The "y-padding" child property
GtkTableChild, GtkTableChild
GtkTableRowCol, GtkTableRowCol
GtkTargetEntry, GtkTargetEntry
GtkTargetFlags, enum GtkTargetFlags
GtkTargetList, GtkTargetList
GtkTargetPair, GtkTargetPair
GtkTearoffMenuItem, GtkTearoffMenuItem
GtkText, GtkText
GtkText::set-scroll-adjustments, The "set-scroll-adjustments" signal
GtkText:hadjustment, The "hadjustment" property
GtkText:line-wrap, The "line-wrap" property
GtkText:vadjustment, The "vadjustment" property
GtkText:word-wrap, The "word-wrap" property
GtkTextAppearance, GtkTextAppearance
GtkTextAttributes, GtkTextAttributes
GtkTextBuffer, GtkTextBuffer
GtkTextBuffer::apply-tag, The "apply-tag" signal
GtkTextBuffer::begin-user-action, The "begin-user-action" signal
GtkTextBuffer::changed, The "changed" signal
GtkTextBuffer::delete-range, The "delete-range" signal
GtkTextBuffer::end-user-action, The "end-user-action" signal
GtkTextBuffer::insert-child-anchor, The "insert-child-anchor" signal
GtkTextBuffer::insert-pixbuf, The "insert-pixbuf" signal
GtkTextBuffer::insert-text, The "insert-text" signal
GtkTextBuffer::mark-deleted, The "mark-deleted" signal
GtkTextBuffer::mark-set, The "mark-set" signal
GtkTextBuffer::modified-changed, The "modified-changed" signal
GtkTextBuffer::remove-tag, The "remove-tag" signal
GtkTextBuffer:copy-target-list, The "copy-target-list" property
GtkTextBuffer:cursor-position, The "cursor-position" property
GtkTextBuffer:has-selection, The "has-selection" property
GtkTextBuffer:paste-target-list, The "paste-target-list" property
GtkTextBuffer:tag-table, The "tag-table" property
GtkTextBuffer:text, The "text" property
GtkTextBufferDeserializeFunc, GtkTextBufferDeserializeFunc ()
GtkTextBufferSerializeFunc, GtkTextBufferSerializeFunc ()
GtkTextBufferTargetInfo, enum GtkTextBufferTargetInfo
GtkTextCharPredicate, GtkTextCharPredicate ()
GtkTextChildAnchor, GtkTextChildAnchor
GtkTextDirection, enum GtkTextDirection
GtkTextFont, GtkTextFont
GtkTextFunction, GtkTextFunction ()
GtkTextIter, GtkTextIter
GtkTextMark, GtkTextMark
GtkTextSearchFlags, enum GtkTextSearchFlags
GtkTextTag, GtkTextTag
GtkTextTag::event, The "event" signal
GtkTextTag:background, The "background" property
GtkTextTag:background-full-height, The "background-full-height" property
GtkTextTag:background-full-height-set, The "background-full-height-set" property
GtkTextTag:background-gdk, The "background-gdk" property
GtkTextTag:background-set, The "background-set" property
GtkTextTag:background-stipple, The "background-stipple" property
GtkTextTag:background-stipple-set, The "background-stipple-set" property
GtkTextTag:direction, The "direction" property
GtkTextTag:editable, The "editable" property
GtkTextTag:editable-set, The "editable-set" property
GtkTextTag:family, The "family" property
GtkTextTag:family-set, The "family-set" property
GtkTextTag:font, The "font" property
GtkTextTag:font-desc, The "font-desc" property
GtkTextTag:foreground, The "foreground" property
GtkTextTag:foreground-gdk, The "foreground-gdk" property
GtkTextTag:foreground-set, The "foreground-set" property
GtkTextTag:foreground-stipple, The "foreground-stipple" property
GtkTextTag:foreground-stipple-set, The "foreground-stipple-set" property
GtkTextTag:indent, The "indent" property
GtkTextTag:indent-set, The "indent-set" property
GtkTextTag:invisible, The "invisible" property
GtkTextTag:invisible-set, The "invisible-set" property
GtkTextTag:justification, The "justification" property
GtkTextTag:justification-set, The "justification-set" property
GtkTextTag:language, The "language" property
GtkTextTag:language-set, The "language-set" property
GtkTextTag:left-margin, The "left-margin" property
GtkTextTag:left-margin-set, The "left-margin-set" property
GtkTextTag:name, The "name" property
GtkTextTag:paragraph-background, The "paragraph-background" property
GtkTextTag:paragraph-background-gdk, The "paragraph-background-gdk" property
GtkTextTag:paragraph-background-set, The "paragraph-background-set" property
GtkTextTag:pixels-above-lines, The "pixels-above-lines" property
GtkTextTag:pixels-above-lines-set, The "pixels-above-lines-set" property
GtkTextTag:pixels-below-lines, The "pixels-below-lines" property
GtkTextTag:pixels-below-lines-set, The "pixels-below-lines-set" property
GtkTextTag:pixels-inside-wrap, The "pixels-inside-wrap" property
GtkTextTag:pixels-inside-wrap-set, The "pixels-inside-wrap-set" property
GtkTextTag:right-margin, The "right-margin" property
GtkTextTag:right-margin-set, The "right-margin-set" property
GtkTextTag:rise, The "rise" property
GtkTextTag:rise-set, The "rise-set" property
GtkTextTag:scale, The "scale" property
GtkTextTag:scale-set, The "scale-set" property
GtkTextTag:size, The "size" property
GtkTextTag:size-points, The "size-points" property
GtkTextTag:size-set, The "size-set" property
GtkTextTag:stretch, The "stretch" property
GtkTextTag:stretch-set, The "stretch-set" property
GtkTextTag:strikethrough, The "strikethrough" property
GtkTextTag:strikethrough-set, The "strikethrough-set" property
GtkTextTag:style, The "style" property
GtkTextTag:style-set, The "style-set" property
GtkTextTag:tabs, The "tabs" property
GtkTextTag:tabs-set, The "tabs-set" property
GtkTextTag:underline, The "underline" property
GtkTextTag:underline-set, The "underline-set" property
GtkTextTag:variant, The "variant" property
GtkTextTag:variant-set, The "variant-set" property
GtkTextTag:weight, The "weight" property
GtkTextTag:weight-set, The "weight-set" property
GtkTextTag:wrap-mode, The "wrap-mode" property
GtkTextTag:wrap-mode-set, The "wrap-mode-set" property
GtkTextTagTable, GtkTextTagTable
GtkTextTagTable::tag-added, The "tag-added" signal
GtkTextTagTable::tag-changed, The "tag-changed" signal
GtkTextTagTable::tag-removed, The "tag-removed" signal
GtkTextTagTableForeach, GtkTextTagTableForeach ()
GtkTextView, GtkTextView
GtkTextView::backspace, The "backspace" signal
GtkTextView::copy-clipboard, The "copy-clipboard" signal
GtkTextView::cut-clipboard, The "cut-clipboard" signal
GtkTextView::delete-from-cursor, The "delete-from-cursor" signal
GtkTextView::insert-at-cursor, The "insert-at-cursor" signal
GtkTextView::move-cursor, The "move-cursor" signal
GtkTextView::move-focus, The "move-focus" signal
GtkTextView::move-viewport, The "move-viewport" signal
GtkTextView::page-horizontally, The "page-horizontally" signal
GtkTextView::paste-clipboard, The "paste-clipboard" signal
GtkTextView::populate-popup, The "populate-popup" signal
GtkTextView::select-all, The "select-all" signal
GtkTextView::set-anchor, The "set-anchor" signal
GtkTextView::set-scroll-adjustments, The "set-scroll-adjustments" signal
GtkTextView::toggle-overwrite, The "toggle-overwrite" signal
GtkTextView:accepts-tab, The "accepts-tab" property
GtkTextView:buffer, The "buffer" property
GtkTextView:cursor-visible, The "cursor-visible" property
GtkTextView:editable, The "editable" property
GtkTextView:error-underline-color, The "error-underline-color" style property
GtkTextView:indent, The "indent" property
GtkTextView:justification, The "justification" property
GtkTextView:left-margin, The "left-margin" property
GtkTextView:overwrite, The "overwrite" property
GtkTextView:pixels-above-lines, The "pixels-above-lines" property
GtkTextView:pixels-below-lines, The "pixels-below-lines" property
GtkTextView:pixels-inside-wrap, The "pixels-inside-wrap" property
GtkTextView:right-margin, The "right-margin" property
GtkTextView:tabs, The "tabs" property
GtkTextView:wrap-mode, The "wrap-mode" property
GtkTextWindowType, enum GtkTextWindowType
GtkTipsQuery, GtkTipsQuery
GtkTipsQuery::start-query, The "start-query" signal
GtkTipsQuery::stop-query, The "stop-query" signal
GtkTipsQuery::widget-entered, The "widget-entered" signal
GtkTipsQuery::widget-selected, The "widget-selected" signal
GtkTipsQuery:caller, The "caller" property
GtkTipsQuery:emit-always, The "emit-always" property
GtkTipsQuery:label-inactive, The "label-inactive" property
GtkTipsQuery:label-no-tip, The "label-no-tip" property
GtkToggleAction, GtkToggleAction
GtkToggleAction::toggled, The "toggled" signal
GtkToggleAction:active, The "active" property
GtkToggleAction:draw-as-radio, The "draw-as-radio" property
GtkToggleActionEntry, GtkToggleActionEntry
GtkToggleButton, GtkToggleButton
GtkToggleButton::toggled, The "toggled" signal
GtkToggleButton:active, The "active" property
GtkToggleButton:draw-indicator, The "draw-indicator" property
GtkToggleButton:inconsistent, The "inconsistent" property
GtkToggleToolButton, GtkToggleToolButton
GtkToggleToolButton::toggled, The "toggled" signal
GtkToggleToolButton:active, The "active" property
GtkToolbar, GtkToolbar
GtkToolbar::focus-home-or-end, The "focus-home-or-end" signal
GtkToolbar::move-focus, The "move-focus" signal
GtkToolbar::orientation-changed, The "orientation-changed" signal
GtkToolbar::popup-context-menu, The "popup-context-menu" signal
GtkToolbar::style-changed, The "style-changed" signal
GtkToolbar:button-relief, The "button-relief" style property
GtkToolbar:expand, The "expand" child property
GtkToolbar:homogeneous, The "homogeneous" child property
GtkToolbar:icon-size, The "icon-size" property
GtkToolbar:icon-size-set, The "icon-size-set" property
GtkToolbar:internal-padding, The "internal-padding" style property
GtkToolbar:max-child-expand, The "max-child-expand" style property
GtkToolbar:orientation, The "orientation" property
GtkToolbar:shadow-type, The "shadow-type" style property
GtkToolbar:show-arrow, The "show-arrow" property
GtkToolbar:space-size, The "space-size" style property
GtkToolbar:space-style, The "space-style" style property
GtkToolbar:toolbar-style, The "toolbar-style" property
GtkToolbar:tooltips, The "tooltips" property
GtkToolbarChild, GtkToolbarChild
GtkToolbarChildType, enum GtkToolbarChildType
GtkToolbarSpaceStyle, enum GtkToolbarSpaceStyle
GtkToolbarStyle, enum GtkToolbarStyle
GtkToolButton, GtkToolButton
GtkToolButton::clicked, The "clicked" signal
GtkToolButton:icon-name, The "icon-name" property
GtkToolButton:icon-spacing, The "icon-spacing" style property
GtkToolButton:icon-widget, The "icon-widget" property
GtkToolButton:label, The "label" property
GtkToolButton:label-widget, The "label-widget" property
GtkToolButton:stock-id, The "stock-id" property
GtkToolButton:use-underline, The "use-underline" property
GtkToolItem, GtkToolItem
GtkToolItem::create-menu-proxy, The "create-menu-proxy" signal
GtkToolItem::set-tooltip, The "set-tooltip" signal
GtkToolItem::toolbar-reconfigured, The "toolbar-reconfigured" signal
GtkToolItem:is-important, The "is-important" property
GtkToolItem:visible-horizontal, The "visible-horizontal" property
GtkToolItem:visible-vertical, The "visible-vertical" property
GtkTooltips, GtkTooltips
GtkTooltipsData, GtkTooltipsData
GtkTranslateFunc, GtkTranslateFunc ()
GtkTree, GtkTree
GtkTree::select-child, The "select-child" signal
GtkTree::selection-changed, The "selection-changed" signal
GtkTree::unselect-child, The "unselect-child" signal
GtkTreeCellDataFunc, GtkTreeCellDataFunc ()
GtkTreeDestroyCountFunc, GtkTreeDestroyCountFunc ()
GtkTreeDragDest, GtkTreeDragDest
GtkTreeDragDestIface, GtkTreeDragDestIface
GtkTreeDragSource, GtkTreeDragSource
GtkTreeDragSourceIface, GtkTreeDragSourceIface
GtkTreeItem, GtkTreeItem
GtkTreeItem::collapse, The "collapse" signal
GtkTreeItem::expand, The "expand" signal
GtkTreeIter, GtkTreeIter
GtkTreeIterCompareFunc, GtkTreeIterCompareFunc ()
GtkTreeModel, GtkTreeModel
GtkTreeModel::row-changed, The "row-changed" signal
GtkTreeModel::row-deleted, The "row-deleted" signal
GtkTreeModel::row-has-child-toggled, The "row-has-child-toggled" signal
GtkTreeModel::row-inserted, The "row-inserted" signal
GtkTreeModel::rows-reordered, The "rows-reordered" signal
GtkTreeModelFilter, GtkTreeModelFilter
GtkTreeModelFilter:child-model, The "child-model" property
GtkTreeModelFilter:virtual-root, The "virtual-root" property
GtkTreeModelFilterModifyFunc, GtkTreeModelFilterModifyFunc ()
GtkTreeModelFilterVisibleFunc, GtkTreeModelFilterVisibleFunc ()
GtkTreeModelFlags, enum GtkTreeModelFlags
GtkTreeModelForeachFunc, GtkTreeModelForeachFunc ()
GtkTreeModelIface, GtkTreeModelIface
GtkTreeModelSort, GtkTreeModelSort
GtkTreeModelSort:model, The "model" property
GtkTreePath, GtkTreePath
GtkTreeRowReference, GtkTreeRowReference
GtkTreeSelection, GtkTreeSelection
GtkTreeSelection::changed, The "changed" signal
GtkTreeSelectionForeachFunc, GtkTreeSelectionForeachFunc ()
GtkTreeSelectionFunc, GtkTreeSelectionFunc ()
GtkTreeSortable, GtkTreeSortable
GtkTreeSortable::sort-column-changed, The "sort-column-changed" signal
GtkTreeSortableIface, GtkTreeSortableIface
GtkTreeStore, GtkTreeStore
GtkTreeView, GtkTreeView
GtkTreeView::columns-changed, The "columns-changed" signal
GtkTreeView::cursor-changed, The "cursor-changed" signal
GtkTreeView::expand-collapse-cursor-row, The "expand-collapse-cursor-row" signal
GtkTreeView::move-cursor, The "move-cursor" signal
GtkTreeView::row-activated, The "row-activated" signal
GtkTreeView::row-collapsed, The "row-collapsed" signal
GtkTreeView::row-expanded, The "row-expanded" signal
GtkTreeView::select-all, The "select-all" signal
GtkTreeView::select-cursor-parent, The "select-cursor-parent" signal
GtkTreeView::select-cursor-row, The "select-cursor-row" signal
GtkTreeView::set-scroll-adjustments, The "set-scroll-adjustments" signal
GtkTreeView::start-interactive-search, The "start-interactive-search" signal
GtkTreeView::test-collapse-row, The "test-collapse-row" signal
GtkTreeView::test-expand-row, The "test-expand-row" signal
GtkTreeView::toggle-cursor-row, The "toggle-cursor-row" signal
GtkTreeView::unselect-all, The "unselect-all" signal
GtkTreeView:allow-rules, The "allow-rules" style property
GtkTreeView:enable-grid-lines, The "enable-grid-lines" property
GtkTreeView:enable-search, The "enable-search" property
GtkTreeView:enable-tree-lines, The "enable-tree-lines" property
GtkTreeView:even-row-color, The "even-row-color" style property
GtkTreeView:expander-column, The "expander-column" property
GtkTreeView:expander-size, The "expander-size" style property
GtkTreeView:fixed-height-mode, The "fixed-height-mode" property
GtkTreeView:grid-line-pattern, The "grid-line-pattern" style property
GtkTreeView:grid-line-width, The "grid-line-width" style property
GtkTreeView:hadjustment, The "hadjustment" property
GtkTreeView:headers-clickable, The "headers-clickable" property
GtkTreeView:headers-visible, The "headers-visible" property
GtkTreeView:horizontal-separator, The "horizontal-separator" style property
GtkTreeView:hover-expand, The "hover-expand" property
GtkTreeView:hover-selection, The "hover-selection" property
GtkTreeView:indent-expanders, The "indent-expanders" style property
GtkTreeView:level-indentation, The "level-indentation" property
GtkTreeView:model, The "model" property
GtkTreeView:odd-row-color, The "odd-row-color" style property
GtkTreeView:reorderable, The "reorderable" property
GtkTreeView:row-ending-details, The "row-ending-details" style property
GtkTreeView:rubber-banding, The "rubber-banding" property
GtkTreeView:rules-hint, The "rules-hint" property
GtkTreeView:search-column, The "search-column" property
GtkTreeView:show-expanders, The "show-expanders" property
GtkTreeView:tree-line-pattern, The "tree-line-pattern" style property
GtkTreeView:tree-line-width, The "tree-line-width" style property
GtkTreeView:vadjustment, The "vadjustment" property
GtkTreeView:vertical-separator, The "vertical-separator" style property
GtkTreeViewColumn, GtkTreeViewColumn
GtkTreeViewColumn::clicked, The "clicked" signal
GtkTreeViewColumn:alignment, The "alignment" property
GtkTreeViewColumn:clickable, The "clickable" property
GtkTreeViewColumn:expand, The "expand" property
GtkTreeViewColumn:fixed-width, The "fixed-width" property
GtkTreeViewColumn:max-width, The "max-width" property
GtkTreeViewColumn:min-width, The "min-width" property
GtkTreeViewColumn:reorderable, The "reorderable" property
GtkTreeViewColumn:resizable, The "resizable" property
GtkTreeViewColumn:sizing, The "sizing" property
GtkTreeViewColumn:sort-indicator, The "sort-indicator" property
GtkTreeViewColumn:sort-order, The "sort-order" property
GtkTreeViewColumn:spacing, The "spacing" property
GtkTreeViewColumn:title, The "title" property
GtkTreeViewColumn:visible, The "visible" property
GtkTreeViewColumn:widget, The "widget" property
GtkTreeViewColumn:width, The "width" property
GtkTreeViewColumnDropFunc, GtkTreeViewColumnDropFunc ()
GtkTreeViewColumnSizing, enum GtkTreeViewColumnSizing
GtkTreeViewDropPosition, enum GtkTreeViewDropPosition
GtkTreeViewGridLines, enum GtkTreeViewGridLines
GtkTreeViewMappingFunc, GtkTreeViewMappingFunc ()
GtkTreeViewMode, enum GtkTreeViewMode
GtkTreeViewPrivate, GtkTreeViewPrivate
GtkTreeViewRowSeparatorFunc, GtkTreeViewRowSeparatorFunc ()
GtkTreeViewSearchEqualFunc, GtkTreeViewSearchEqualFunc ()
GtkTreeViewSearchPositionFunc, GtkTreeViewSearchPositionFunc ()
GtkType, GtkType
GtkTypeClass, GtkTypeClass
GtkTypeInfo, GtkTypeInfo
GtkTypeObject, GtkTypeObject
GtkUIManager, GtkUIManager
GtkUIManager::actions-changed, The "actions-changed" signal
GtkUIManager::add-widget, The "add-widget" signal
GtkUIManager::connect-proxy, The "connect-proxy" signal
GtkUIManager::disconnect-proxy, The "disconnect-proxy" signal
GtkUIManager::post-activate, The "post-activate" signal
GtkUIManager::pre-activate, The "pre-activate" signal
GtkUIManager:add-tearoffs, The "add-tearoffs" property
GtkUIManager:ui, The "ui" property
GtkUIManagerItemType, enum GtkUIManagerItemType
GtkUnit, enum GtkUnit
GtkUpdateType, enum GtkUpdateType
GtkVBox, GtkVBox
GtkVButtonBox, GtkVButtonBox
GtkViewport, GtkViewport
GtkViewport::set-scroll-adjustments, The "set-scroll-adjustments" signal
GtkViewport:hadjustment, The "hadjustment" property
GtkViewport:shadow-type, The "shadow-type" property
GtkViewport:vadjustment, The "vadjustment" property
GtkVisibility, enum GtkVisibility
GtkVPaned, GtkVPaned
GtkVRuler, GtkVRuler
GtkVScale, GtkVScale
GtkVScrollbar, GtkVScrollbar
GtkVSeparator, GtkVSeparator
GtkWidget, GtkWidget
GtkWidget::accel-closures-changed, The "accel-closures-changed" signal
GtkWidget::button-press-event, The "button-press-event" signal
GtkWidget::button-release-event, The "button-release-event" signal
GtkWidget::can-activate-accel, The "can-activate-accel" signal
GtkWidget::child-notify, The "child-notify" signal
GtkWidget::client-event, The "client-event" signal
GtkWidget::composited-changed, The "composited-changed" signal
GtkWidget::configure-event, The "configure-event" signal
GtkWidget::delete-event, The "delete-event" signal
GtkWidget::destroy-event, The "destroy-event" signal
GtkWidget::direction-changed, The "direction-changed" signal
GtkWidget::drag-begin, The "drag-begin" signal
GtkWidget::drag-data-delete, The "drag-data-delete" signal
GtkWidget::drag-data-get, The "drag-data-get" signal
GtkWidget::drag-data-received, The "drag-data-received" signal
GtkWidget::drag-drop, The "drag-drop" signal
GtkWidget::drag-end, The "drag-end" signal
GtkWidget::drag-leave, The "drag-leave" signal
GtkWidget::drag-motion, The "drag-motion" signal
GtkWidget::enter-notify-event, The "enter-notify-event" signal
GtkWidget::event, The "event" signal
GtkWidget::event-after, The "event-after" signal
GtkWidget::expose-event, The "expose-event" signal
GtkWidget::focus, The "focus" signal
GtkWidget::focus-in-event, The "focus-in-event" signal
GtkWidget::focus-out-event, The "focus-out-event" signal
GtkWidget::grab-broken-event, The "grab-broken-event" signal
GtkWidget::grab-focus, The "grab-focus" signal
GtkWidget::grab-notify, The "grab-notify" signal
GtkWidget::hide, The "hide" signal
GtkWidget::hierarchy-changed, The "hierarchy-changed" signal
GtkWidget::key-press-event, The "key-press-event" signal
GtkWidget::key-release-event, The "key-release-event" signal
GtkWidget::leave-notify-event, The "leave-notify-event" signal
GtkWidget::map, The "map" signal
GtkWidget::map-event, The "map-event" signal
GtkWidget::mnemonic-activate, The "mnemonic-activate" signal
GtkWidget::motion-notify-event, The "motion-notify-event" signal
GtkWidget::no-expose-event, The "no-expose-event" signal
GtkWidget::parent-set, The "parent-set" signal
GtkWidget::popup-menu, The "popup-menu" signal
GtkWidget::property-notify-event, The "property-notify-event" signal
GtkWidget::proximity-in-event, The "proximity-in-event" signal
GtkWidget::proximity-out-event, The "proximity-out-event" signal
GtkWidget::realize, The "realize" signal
GtkWidget::screen-changed, The "screen-changed" signal
GtkWidget::scroll-event, The "scroll-event" signal
GtkWidget::selection-clear-event, The "selection-clear-event" signal
GtkWidget::selection-get, The "selection-get" signal
GtkWidget::selection-notify-event, The "selection-notify-event" signal
GtkWidget::selection-received, The "selection-received" signal
GtkWidget::selection-request-event, The "selection-request-event" signal
GtkWidget::show, The "show" signal
GtkWidget::show-help, The "show-help" signal
GtkWidget::size-allocate, The "size-allocate" signal
GtkWidget::size-request, The "size-request" signal
GtkWidget::state-changed, The "state-changed" signal
GtkWidget::style-set, The "style-set" signal
GtkWidget::unmap, The "unmap" signal
GtkWidget::unmap-event, The "unmap-event" signal
GtkWidget::unrealize, The "unrealize" signal
GtkWidget::visibility-notify-event, The "visibility-notify-event" signal
GtkWidget::window-state-event, The "window-state-event" signal
GtkWidget:app-paintable, The "app-paintable" property
GtkWidget:can-default, The "can-default" property
GtkWidget:can-focus, The "can-focus" property
GtkWidget:composite-child, The "composite-child" property
GtkWidget:cursor-aspect-ratio, The "cursor-aspect-ratio" style property
GtkWidget:cursor-color, The "cursor-color" style property
GtkWidget:draw-border, The "draw-border" style property
GtkWidget:events, The "events" property
GtkWidget:extension-events, The "extension-events" property
GtkWidget:focus-line-pattern, The "focus-line-pattern" style property
GtkWidget:focus-line-width, The "focus-line-width" style property
GtkWidget:focus-padding, The "focus-padding" style property
GtkWidget:has-default, The "has-default" property
GtkWidget:has-focus, The "has-focus" property
GtkWidget:height-request, The "height-request" property
GtkWidget:interior-focus, The "interior-focus" style property
GtkWidget:is-focus, The "is-focus" property
GtkWidget:link-color, The "link-color" style property
GtkWidget:name, The "name" property
GtkWidget:no-show-all, The "no-show-all" property
GtkWidget:parent, The "parent" property
GtkWidget:receives-default, The "receives-default" property
GtkWidget:scroll-arrow-hlength, The "scroll-arrow-hlength" style property
GtkWidget:scroll-arrow-vlength, The "scroll-arrow-vlength" style property
GtkWidget:secondary-cursor-color, The "secondary-cursor-color" style property
GtkWidget:sensitive, The "sensitive" property
GtkWidget:separator-height, The "separator-height" style property
GtkWidget:separator-width, The "separator-width" style property
GtkWidget:style, The "style" property
GtkWidget:visible, The "visible" property
GtkWidget:visited-link-color, The "visited-link-color" style property
GtkWidget:wide-separators, The "wide-separators" style property
GtkWidget:width-request, The "width-request" property
GtkWidgetAuxInfo, GtkWidgetAuxInfo
GtkWidgetClass, GtkWidgetClass
GtkWidgetFlags, enum GtkWidgetFlags
GtkWidgetHelpType, enum GtkWidgetHelpType
GtkWidgetShapeInfo, GtkWidgetShapeInfo
GtkWindow, GtkWindow
GtkWindow::activate-default, The "activate-default" signal
GtkWindow::activate-focus, The "activate-focus" signal
GtkWindow::frame-event, The "frame-event" signal
GtkWindow::keys-changed, The "keys-changed" signal
GtkWindow::move-focus, The "move-focus" signal
GtkWindow::set-focus, The "set-focus" signal
GtkWindow:accept-focus, The "accept-focus" property
GtkWindow:allow-grow, The "allow-grow" property
GtkWindow:allow-shrink, The "allow-shrink" property
GtkWindow:decorated, The "decorated" property
GtkWindow:default-height, The "default-height" property
GtkWindow:default-width, The "default-width" property
GtkWindow:deletable, The "deletable" property
GtkWindow:destroy-with-parent, The "destroy-with-parent" property
GtkWindow:focus-on-map, The "focus-on-map" property
GtkWindow:gravity, The "gravity" property
GtkWindow:has-toplevel-focus, The "has-toplevel-focus" property
GtkWindow:icon, The "icon" property
GtkWindow:icon-name, The "icon-name" property
GtkWindow:is-active, The "is-active" property
GtkWindow:modal, The "modal" property
GtkWindow:resizable, The "resizable" property
GtkWindow:role, The "role" property
GtkWindow:screen, The "screen" property
GtkWindow:skip-pager-hint, The "skip-pager-hint" property
GtkWindow:skip-taskbar-hint, The "skip-taskbar-hint" property
GtkWindow:title, The "title" property
GtkWindow:transient-for, The "transient-for" property
GtkWindow:type, The "type" property
GtkWindow:type-hint, The "type-hint" property
GtkWindow:urgency-hint, The "urgency-hint" property
GtkWindow:window-position, The "window-position" property
GtkWindowGroup, GtkWindowGroup
GtkWindowPosition, enum GtkWindowPosition
GtkWindowType, enum GtkWindowType
GtkWrapMode, enum GtkWrapMode
gtk_about_dialog_get_artists, gtk_about_dialog_get_artists ()
gtk_about_dialog_get_authors, gtk_about_dialog_get_authors ()
gtk_about_dialog_get_comments, gtk_about_dialog_get_comments ()
gtk_about_dialog_get_copyright, gtk_about_dialog_get_copyright ()
gtk_about_dialog_get_documenters, gtk_about_dialog_get_documenters ()
gtk_about_dialog_get_license, gtk_about_dialog_get_license ()
gtk_about_dialog_get_logo, gtk_about_dialog_get_logo ()
gtk_about_dialog_get_logo_icon_name, gtk_about_dialog_get_logo_icon_name ()
gtk_about_dialog_get_name, gtk_about_dialog_get_name ()
gtk_about_dialog_get_translator_credits, gtk_about_dialog_get_translator_credits ()
gtk_about_dialog_get_version, gtk_about_dialog_get_version ()
gtk_about_dialog_get_website, gtk_about_dialog_get_website ()
gtk_about_dialog_get_website_label, gtk_about_dialog_get_website_label ()
gtk_about_dialog_get_wrap_license, gtk_about_dialog_get_wrap_license ()
gtk_about_dialog_new, gtk_about_dialog_new ()
gtk_about_dialog_set_artists, gtk_about_dialog_set_artists ()
gtk_about_dialog_set_authors, gtk_about_dialog_set_authors ()
gtk_about_dialog_set_comments, gtk_about_dialog_set_comments ()
gtk_about_dialog_set_copyright, gtk_about_dialog_set_copyright ()
gtk_about_dialog_set_documenters, gtk_about_dialog_set_documenters ()
gtk_about_dialog_set_email_hook, gtk_about_dialog_set_email_hook ()
gtk_about_dialog_set_license, gtk_about_dialog_set_license ()
gtk_about_dialog_set_logo, gtk_about_dialog_set_logo ()
gtk_about_dialog_set_logo_icon_name, gtk_about_dialog_set_logo_icon_name ()
gtk_about_dialog_set_name, gtk_about_dialog_set_name ()
gtk_about_dialog_set_translator_credits, gtk_about_dialog_set_translator_credits ()
gtk_about_dialog_set_url_hook, gtk_about_dialog_set_url_hook ()
gtk_about_dialog_set_version, gtk_about_dialog_set_version ()
gtk_about_dialog_set_website, gtk_about_dialog_set_website ()
gtk_about_dialog_set_website_label, gtk_about_dialog_set_website_label ()
gtk_about_dialog_set_wrap_license, gtk_about_dialog_set_wrap_license ()
gtk_accelerator_get_default_mod_mask, gtk_accelerator_get_default_mod_mask ()
gtk_accelerator_get_label, gtk_accelerator_get_label ()
gtk_accelerator_name, gtk_accelerator_name ()
gtk_accelerator_parse, gtk_accelerator_parse ()
gtk_accelerator_set_default_mod_mask, gtk_accelerator_set_default_mod_mask ()
gtk_accelerator_valid, gtk_accelerator_valid ()
gtk_accel_groups_activate, gtk_accel_groups_activate ()
gtk_accel_groups_from_object, gtk_accel_groups_from_object ()
gtk_accel_group_activate, gtk_accel_group_activate ()
gtk_accel_group_connect, gtk_accel_group_connect ()
gtk_accel_group_connect_by_path, gtk_accel_group_connect_by_path ()
gtk_accel_group_disconnect, gtk_accel_group_disconnect ()
gtk_accel_group_disconnect_key, gtk_accel_group_disconnect_key ()
gtk_accel_group_find, gtk_accel_group_find ()
gtk_accel_group_from_accel_closure, gtk_accel_group_from_accel_closure ()
gtk_accel_group_lock, gtk_accel_group_lock ()
gtk_accel_group_new, gtk_accel_group_new ()
gtk_accel_group_query, gtk_accel_group_query ()
gtk_accel_group_ref, gtk_accel_group_ref
gtk_accel_group_unlock, gtk_accel_group_unlock ()
gtk_accel_group_unref, gtk_accel_group_unref
gtk_accel_label_get_accel_widget, gtk_accel_label_get_accel_widget ()
gtk_accel_label_get_accel_width, gtk_accel_label_get_accel_width ()
gtk_accel_label_new, gtk_accel_label_new ()
gtk_accel_label_refetch, gtk_accel_label_refetch ()
gtk_accel_label_set_accel_closure, gtk_accel_label_set_accel_closure ()
gtk_accel_label_set_accel_widget, gtk_accel_label_set_accel_widget ()
gtk_accel_map_add_entry, gtk_accel_map_add_entry ()
gtk_accel_map_add_filter, gtk_accel_map_add_filter ()
gtk_accel_map_change_entry, gtk_accel_map_change_entry ()
gtk_accel_map_foreach, gtk_accel_map_foreach ()
gtk_accel_map_foreach_unfiltered, gtk_accel_map_foreach_unfiltered ()
gtk_accel_map_get, gtk_accel_map_get ()
gtk_accel_map_load, gtk_accel_map_load ()
gtk_accel_map_load_fd, gtk_accel_map_load_fd ()
gtk_accel_map_load_scanner, gtk_accel_map_load_scanner ()
gtk_accel_map_lock_path, gtk_accel_map_lock_path ()
gtk_accel_map_lookup_entry, gtk_accel_map_lookup_entry ()
gtk_accel_map_save, gtk_accel_map_save ()
gtk_accel_map_save_fd, gtk_accel_map_save_fd ()
gtk_accel_map_unlock_path, gtk_accel_map_unlock_path ()
gtk_accessible_connect_widget_destroyed, gtk_accessible_connect_widget_destroyed ()
gtk_action_activate, gtk_action_activate ()
gtk_action_block_activate_from, gtk_action_block_activate_from ()
gtk_action_connect_accelerator, gtk_action_connect_accelerator ()
gtk_action_connect_proxy, gtk_action_connect_proxy ()
gtk_action_create_icon, gtk_action_create_icon ()
gtk_action_create_menu_item, gtk_action_create_menu_item ()
gtk_action_create_tool_item, gtk_action_create_tool_item ()
gtk_action_disconnect_accelerator, gtk_action_disconnect_accelerator ()
gtk_action_disconnect_proxy, gtk_action_disconnect_proxy ()
gtk_action_get_accel_closure, gtk_action_get_accel_closure ()
gtk_action_get_accel_path, gtk_action_get_accel_path ()
gtk_action_get_name, gtk_action_get_name ()
gtk_action_get_proxies, gtk_action_get_proxies ()
gtk_action_get_sensitive, gtk_action_get_sensitive ()
gtk_action_get_visible, gtk_action_get_visible ()
gtk_action_group_add_action, gtk_action_group_add_action ()
gtk_action_group_add_actions, gtk_action_group_add_actions ()
gtk_action_group_add_actions_full, gtk_action_group_add_actions_full ()
gtk_action_group_add_action_with_accel, gtk_action_group_add_action_with_accel ()
gtk_action_group_add_radio_actions, gtk_action_group_add_radio_actions ()
gtk_action_group_add_radio_actions_full, gtk_action_group_add_radio_actions_full ()
gtk_action_group_add_toggle_actions, gtk_action_group_add_toggle_actions ()
gtk_action_group_add_toggle_actions_full, gtk_action_group_add_toggle_actions_full ()
gtk_action_group_get_action, gtk_action_group_get_action ()
gtk_action_group_get_name, gtk_action_group_get_name ()
gtk_action_group_get_sensitive, gtk_action_group_get_sensitive ()
gtk_action_group_get_visible, gtk_action_group_get_visible ()
gtk_action_group_list_actions, gtk_action_group_list_actions ()
gtk_action_group_new, gtk_action_group_new ()
gtk_action_group_remove_action, gtk_action_group_remove_action ()
gtk_action_group_set_sensitive, gtk_action_group_set_sensitive ()
gtk_action_group_set_translate_func, gtk_action_group_set_translate_func ()
gtk_action_group_set_translation_domain, gtk_action_group_set_translation_domain ()
gtk_action_group_set_visible, gtk_action_group_set_visible ()
gtk_action_group_translate_string, gtk_action_group_translate_string ()
gtk_action_is_sensitive, gtk_action_is_sensitive ()
gtk_action_is_visible, gtk_action_is_visible ()
gtk_action_new, gtk_action_new ()
gtk_action_set_accel_group, gtk_action_set_accel_group ()
gtk_action_set_accel_path, gtk_action_set_accel_path ()
gtk_action_set_sensitive, gtk_action_set_sensitive ()
gtk_action_set_visible, gtk_action_set_visible ()
gtk_action_unblock_activate_from, gtk_action_unblock_activate_from ()
gtk_adjustment_changed, gtk_adjustment_changed ()
gtk_adjustment_clamp_page, gtk_adjustment_clamp_page ()
gtk_adjustment_get_value, gtk_adjustment_get_value ()
gtk_adjustment_new, gtk_adjustment_new ()
gtk_adjustment_set_value, gtk_adjustment_set_value ()
gtk_adjustment_value_changed, gtk_adjustment_value_changed ()
gtk_alignment_get_padding, gtk_alignment_get_padding ()
gtk_alignment_new, gtk_alignment_new ()
gtk_alignment_set, gtk_alignment_set ()
gtk_alignment_set_padding, gtk_alignment_set_padding ()
gtk_alternative_dialog_button_order, gtk_alternative_dialog_button_order ()
gtk_arrow_new, gtk_arrow_new ()
gtk_arrow_set, gtk_arrow_set ()
gtk_aspect_frame_new, gtk_aspect_frame_new ()
gtk_aspect_frame_set, gtk_aspect_frame_set ()
gtk_assistant_add_action_widget, gtk_assistant_add_action_widget ()
gtk_assistant_append_page, gtk_assistant_append_page ()
gtk_assistant_get_current_page, gtk_assistant_get_current_page ()
gtk_assistant_get_nth_page, gtk_assistant_get_nth_page ()
gtk_assistant_get_n_pages, gtk_assistant_get_n_pages ()
gtk_assistant_get_page_complete, gtk_assistant_get_page_complete ()
gtk_assistant_get_page_header_image, gtk_assistant_get_page_header_image ()
gtk_assistant_get_page_side_image, gtk_assistant_get_page_side_image ()
gtk_assistant_get_page_title, gtk_assistant_get_page_title ()
gtk_assistant_get_page_type, gtk_assistant_get_page_type ()
gtk_assistant_insert_page, gtk_assistant_insert_page ()
gtk_assistant_new, gtk_assistant_new ()
gtk_assistant_prepend_page, gtk_assistant_prepend_page ()
gtk_assistant_remove_action_widget, gtk_assistant_remove_action_widget ()
gtk_assistant_set_current_page, gtk_assistant_set_current_page ()
gtk_assistant_set_forward_page_func, gtk_assistant_set_forward_page_func ()
gtk_assistant_set_page_complete, gtk_assistant_set_page_complete ()
gtk_assistant_set_page_header_image, gtk_assistant_set_page_header_image ()
gtk_assistant_set_page_side_image, gtk_assistant_set_page_side_image ()
gtk_assistant_set_page_title, gtk_assistant_set_page_title ()
gtk_assistant_set_page_type, gtk_assistant_set_page_type ()
gtk_assistant_update_buttons_state, gtk_assistant_update_buttons_state ()
gtk_binary_age, gtk_binary_age
GTK_BINARY_AGE, GTK_BINARY_AGE
gtk_bindings_activate, gtk_bindings_activate ()
gtk_bindings_activate_event, gtk_bindings_activate_event ()
gtk_binding_entry_add, gtk_binding_entry_add
gtk_binding_entry_add_signal, gtk_binding_entry_add_signal ()
gtk_binding_entry_add_signall, gtk_binding_entry_add_signall ()
gtk_binding_entry_clear, gtk_binding_entry_clear ()
gtk_binding_entry_remove, gtk_binding_entry_remove ()
gtk_binding_parse_binding, gtk_binding_parse_binding ()
gtk_binding_set_activate, gtk_binding_set_activate ()
gtk_binding_set_add_path, gtk_binding_set_add_path ()
gtk_binding_set_by_class, gtk_binding_set_by_class ()
gtk_binding_set_find, gtk_binding_set_find ()
gtk_binding_set_new, gtk_binding_set_new ()
gtk_bin_get_child, gtk_bin_get_child ()
gtk_border_copy, gtk_border_copy ()
gtk_border_free, gtk_border_free ()
gtk_box_get_homogeneous, gtk_box_get_homogeneous ()
gtk_box_get_spacing, gtk_box_get_spacing ()
gtk_box_pack_end, gtk_box_pack_end ()
gtk_box_pack_end_defaults, gtk_box_pack_end_defaults ()
gtk_box_pack_start, gtk_box_pack_start ()
gtk_box_pack_start_defaults, gtk_box_pack_start_defaults ()
gtk_box_query_child_packing, gtk_box_query_child_packing ()
gtk_box_reorder_child, gtk_box_reorder_child ()
gtk_box_set_child_packing, gtk_box_set_child_packing ()
gtk_box_set_homogeneous, gtk_box_set_homogeneous ()
gtk_box_set_spacing, gtk_box_set_spacing ()
GTK_BUTTONBOX_DEFAULT, GTK_BUTTONBOX_DEFAULT
gtk_button_box_get_child_ipadding, gtk_button_box_get_child_ipadding ()
gtk_button_box_get_child_secondary, gtk_button_box_get_child_secondary ()
gtk_button_box_get_child_size, gtk_button_box_get_child_size ()
gtk_button_box_get_layout, gtk_button_box_get_layout ()
gtk_button_box_get_spacing, gtk_button_box_get_spacing()
gtk_button_box_set_child_ipadding, gtk_button_box_set_child_ipadding ()
gtk_button_box_set_child_secondary, gtk_button_box_set_child_secondary ()
gtk_button_box_set_child_size, gtk_button_box_set_child_size ()
gtk_button_box_set_layout, gtk_button_box_set_layout ()
gtk_button_box_set_spacing, gtk_button_box_set_spacing()
gtk_button_clicked, gtk_button_clicked ()
gtk_button_enter, gtk_button_enter ()
gtk_button_get_alignment, gtk_button_get_alignment ()
gtk_button_get_focus_on_click, gtk_button_get_focus_on_click ()
gtk_button_get_image, gtk_button_get_image ()
gtk_button_get_image_position, gtk_button_get_image_position ()
gtk_button_get_label, gtk_button_get_label ()
gtk_button_get_relief, gtk_button_get_relief ()
gtk_button_get_use_stock, gtk_button_get_use_stock ()
gtk_button_get_use_underline, gtk_button_get_use_underline ()
gtk_button_leave, gtk_button_leave ()
gtk_button_new, gtk_button_new ()
gtk_button_new_from_stock, gtk_button_new_from_stock ()
gtk_button_new_with_label, gtk_button_new_with_label ()
gtk_button_new_with_mnemonic, gtk_button_new_with_mnemonic ()
gtk_button_pressed, gtk_button_pressed ()
gtk_button_released, gtk_button_released ()
gtk_button_set_alignment, gtk_button_set_alignment ()
gtk_button_set_focus_on_click, gtk_button_set_focus_on_click ()
gtk_button_set_image, gtk_button_set_image ()
gtk_button_set_image_position, gtk_button_set_image_position ()
gtk_button_set_label, gtk_button_set_label ()
gtk_button_set_relief, gtk_button_set_relief ()
gtk_button_set_use_stock, gtk_button_set_use_stock ()
gtk_button_set_use_underline, gtk_button_set_use_underline ()
gtk_calendar_clear_marks, gtk_calendar_clear_marks ()
gtk_calendar_display_options, gtk_calendar_display_options ()
gtk_calendar_freeze, gtk_calendar_freeze ()
gtk_calendar_get_date, gtk_calendar_get_date ()
gtk_calendar_get_display_options, gtk_calendar_get_display_options ()
gtk_calendar_mark_day, gtk_calendar_mark_day ()
gtk_calendar_new, gtk_calendar_new ()
gtk_calendar_select_day, gtk_calendar_select_day ()
gtk_calendar_select_month, gtk_calendar_select_month ()
gtk_calendar_set_display_options, gtk_calendar_set_display_options ()
gtk_calendar_thaw, gtk_calendar_thaw ()
gtk_calendar_unmark_day, gtk_calendar_unmark_day ()
gtk_cell_editable_editing_done, gtk_cell_editable_editing_done ()
gtk_cell_editable_remove_widget, gtk_cell_editable_remove_widget ()
gtk_cell_editable_start_editing, gtk_cell_editable_start_editing ()
gtk_cell_layout_add_attribute, gtk_cell_layout_add_attribute ()
gtk_cell_layout_clear, gtk_cell_layout_clear ()
gtk_cell_layout_clear_attributes, gtk_cell_layout_clear_attributes ()
gtk_cell_layout_pack_end, gtk_cell_layout_pack_end ()
gtk_cell_layout_pack_start, gtk_cell_layout_pack_start ()
gtk_cell_layout_reorder, gtk_cell_layout_reorder ()
gtk_cell_layout_set_attributes, gtk_cell_layout_set_attributes ()
gtk_cell_layout_set_cell_data_func, gtk_cell_layout_set_cell_data_func ()
GTK_CELL_PIXMAP, GTK_CELL_PIXMAP()
GTK_CELL_PIXTEXT, GTK_CELL_PIXTEXT()
gtk_cell_renderer_accel_new, gtk_cell_renderer_accel_new ()
gtk_cell_renderer_activate, gtk_cell_renderer_activate ()
gtk_cell_renderer_combo_new, gtk_cell_renderer_combo_new ()
gtk_cell_renderer_editing_canceled, gtk_cell_renderer_editing_canceled ()
gtk_cell_renderer_get_fixed_size, gtk_cell_renderer_get_fixed_size ()
gtk_cell_renderer_get_size, gtk_cell_renderer_get_size ()
gtk_cell_renderer_pixbuf_new, gtk_cell_renderer_pixbuf_new ()
gtk_cell_renderer_progress_new, gtk_cell_renderer_progress_new ()
gtk_cell_renderer_render, gtk_cell_renderer_render ()
gtk_cell_renderer_set_fixed_size, gtk_cell_renderer_set_fixed_size ()
gtk_cell_renderer_spin_new, gtk_cell_renderer_spin_new ()
gtk_cell_renderer_start_editing, gtk_cell_renderer_start_editing ()
gtk_cell_renderer_stop_editing, gtk_cell_renderer_stop_editing ()
gtk_cell_renderer_text_new, gtk_cell_renderer_text_new ()
gtk_cell_renderer_text_set_fixed_height_from_font, gtk_cell_renderer_text_set_fixed_height_from_font ()
gtk_cell_renderer_toggle_get_active, gtk_cell_renderer_toggle_get_active ()
gtk_cell_renderer_toggle_get_radio, gtk_cell_renderer_toggle_get_radio ()
gtk_cell_renderer_toggle_new, gtk_cell_renderer_toggle_new ()
gtk_cell_renderer_toggle_set_active, gtk_cell_renderer_toggle_set_active ()
gtk_cell_renderer_toggle_set_radio, gtk_cell_renderer_toggle_set_radio ()
GTK_CELL_TEXT, GTK_CELL_TEXT()
gtk_cell_view_get_cell_renderers, gtk_cell_view_get_cell_renderers ()
gtk_cell_view_get_displayed_row, gtk_cell_view_get_displayed_row ()
gtk_cell_view_get_size_of_row, gtk_cell_view_get_size_of_row ()
gtk_cell_view_new, gtk_cell_view_new ()
gtk_cell_view_new_with_markup, gtk_cell_view_new_with_markup ()
gtk_cell_view_new_with_pixbuf, gtk_cell_view_new_with_pixbuf ()
gtk_cell_view_new_with_text, gtk_cell_view_new_with_text ()
gtk_cell_view_set_background_color, gtk_cell_view_set_background_color ()
gtk_cell_view_set_displayed_row, gtk_cell_view_set_displayed_row ()
gtk_cell_view_set_model, gtk_cell_view_set_model ()
GTK_CELL_WIDGET, GTK_CELL_WIDGET()
gtk_check_button_new, gtk_check_button_new ()
gtk_check_button_new_with_label, gtk_check_button_new_with_label ()
gtk_check_button_new_with_mnemonic, gtk_check_button_new_with_mnemonic ()
GTK_CHECK_CAST, GTK_CHECK_CAST
GTK_CHECK_CLASS_CAST, GTK_CHECK_CLASS_CAST
GTK_CHECK_CLASS_TYPE, GTK_CHECK_CLASS_TYPE
GTK_CHECK_GET_CLASS, GTK_CHECK_GET_CLASS
gtk_check_menu_item_get_active, gtk_check_menu_item_get_active ()
gtk_check_menu_item_get_draw_as_radio, gtk_check_menu_item_get_draw_as_radio ()
gtk_check_menu_item_get_inconsistent, gtk_check_menu_item_get_inconsistent ()
gtk_check_menu_item_new, gtk_check_menu_item_new ()
gtk_check_menu_item_new_with_label, gtk_check_menu_item_new_with_label ()
gtk_check_menu_item_new_with_mnemonic, gtk_check_menu_item_new_with_mnemonic ()
gtk_check_menu_item_set_active, gtk_check_menu_item_set_active ()
gtk_check_menu_item_set_draw_as_radio, gtk_check_menu_item_set_draw_as_radio ()
gtk_check_menu_item_set_inconsistent, gtk_check_menu_item_set_inconsistent ()
gtk_check_menu_item_set_show_toggle, gtk_check_menu_item_set_show_toggle ()
gtk_check_menu_item_set_state, gtk_check_menu_item_set_state
gtk_check_menu_item_toggled, gtk_check_menu_item_toggled ()
GTK_CHECK_TYPE, GTK_CHECK_TYPE
gtk_check_version, gtk_check_version ()
GTK_CHECK_VERSION, GTK_CHECK_VERSION()
GTK_CLASS_NAME, GTK_CLASS_NAME()
GTK_CLASS_TYPE, GTK_CLASS_TYPE()
gtk_clipboard_clear, gtk_clipboard_clear ()
gtk_clipboard_get, gtk_clipboard_get ()
gtk_clipboard_get_display, gtk_clipboard_get_display ()
gtk_clipboard_get_for_display, gtk_clipboard_get_for_display ()
gtk_clipboard_get_owner, gtk_clipboard_get_owner ()
gtk_clipboard_request_contents, gtk_clipboard_request_contents ()
gtk_clipboard_request_image, gtk_clipboard_request_image ()
gtk_clipboard_request_rich_text, gtk_clipboard_request_rich_text ()
gtk_clipboard_request_targets, gtk_clipboard_request_targets ()
gtk_clipboard_request_text, gtk_clipboard_request_text ()
gtk_clipboard_set_can_store, gtk_clipboard_set_can_store ()
gtk_clipboard_set_image, gtk_clipboard_set_image ()
gtk_clipboard_set_text, gtk_clipboard_set_text ()
gtk_clipboard_set_with_data, gtk_clipboard_set_with_data ()
gtk_clipboard_set_with_owner, gtk_clipboard_set_with_owner ()
gtk_clipboard_store, gtk_clipboard_store ()
gtk_clipboard_wait_for_contents, gtk_clipboard_wait_for_contents ()
gtk_clipboard_wait_for_image, gtk_clipboard_wait_for_image ()
gtk_clipboard_wait_for_rich_text, gtk_clipboard_wait_for_rich_text ()
gtk_clipboard_wait_for_targets, gtk_clipboard_wait_for_targets ()
gtk_clipboard_wait_for_text, gtk_clipboard_wait_for_text ()
gtk_clipboard_wait_is_image_available, gtk_clipboard_wait_is_image_available ()
gtk_clipboard_wait_is_rich_text_available, gtk_clipboard_wait_is_rich_text_available ()
gtk_clipboard_wait_is_target_available, gtk_clipboard_wait_is_target_available ()
gtk_clipboard_wait_is_text_available, gtk_clipboard_wait_is_text_available ()
GTK_CLIST_ADD_MODE, GTK_CLIST_ADD_MODE()
gtk_clist_append, gtk_clist_append ()
GTK_CLIST_AUTO_RESIZE_BLOCKED, GTK_CLIST_AUTO_RESIZE_BLOCKED()
GTK_CLIST_AUTO_SORT, GTK_CLIST_AUTO_SORT()
gtk_clist_clear, gtk_clist_clear ()
gtk_clist_columns_autosize, gtk_clist_columns_autosize ()
gtk_clist_column_titles_active, gtk_clist_column_titles_active ()
gtk_clist_column_titles_hide, gtk_clist_column_titles_hide ()
gtk_clist_column_titles_passive, gtk_clist_column_titles_passive ()
gtk_clist_column_titles_show, gtk_clist_column_titles_show ()
gtk_clist_column_title_active, gtk_clist_column_title_active ()
gtk_clist_column_title_passive, gtk_clist_column_title_passive ()
GTK_CLIST_DRAW_DRAG_LINE, GTK_CLIST_DRAW_DRAG_LINE()
GTK_CLIST_DRAW_DRAG_RECT, GTK_CLIST_DRAW_DRAG_RECT()
gtk_clist_find_row_from_data, gtk_clist_find_row_from_data ()
GTK_CLIST_FLAGS, GTK_CLIST_FLAGS()
gtk_clist_freeze, gtk_clist_freeze ()
gtk_clist_get_cell_style, gtk_clist_get_cell_style ()
gtk_clist_get_cell_type, gtk_clist_get_cell_type ()
gtk_clist_get_column_title, gtk_clist_get_column_title ()
gtk_clist_get_column_widget, gtk_clist_get_column_widget ()
gtk_clist_get_hadjustment, gtk_clist_get_hadjustment ()
gtk_clist_get_pixmap, gtk_clist_get_pixmap ()
gtk_clist_get_pixtext, gtk_clist_get_pixtext ()
gtk_clist_get_row_data, gtk_clist_get_row_data ()
gtk_clist_get_row_style, gtk_clist_get_row_style ()
gtk_clist_get_selectable, gtk_clist_get_selectable ()
gtk_clist_get_selection_info, gtk_clist_get_selection_info ()
gtk_clist_get_text, gtk_clist_get_text ()
gtk_clist_get_vadjustment, gtk_clist_get_vadjustment ()
gtk_clist_insert, gtk_clist_insert ()
GTK_CLIST_IN_DRAG, GTK_CLIST_IN_DRAG()
gtk_clist_moveto, gtk_clist_moveto ()
gtk_clist_new, gtk_clist_new ()
gtk_clist_new_with_titles, gtk_clist_new_with_titles ()
gtk_clist_optimal_column_width, gtk_clist_optimal_column_width ()
gtk_clist_prepend, gtk_clist_prepend ()
gtk_clist_remove, gtk_clist_remove ()
GTK_CLIST_REORDERABLE, GTK_CLIST_REORDERABLE()
GTK_CLIST_ROW, GTK_CLIST_ROW()
GTK_CLIST_ROW_HEIGHT_SET, GTK_CLIST_ROW_HEIGHT_SET()
gtk_clist_row_is_visible, gtk_clist_row_is_visible ()
gtk_clist_row_move, gtk_clist_row_move ()
gtk_clist_select_all, gtk_clist_select_all ()
gtk_clist_select_row, gtk_clist_select_row ()
gtk_clist_set_auto_sort, gtk_clist_set_auto_sort ()
gtk_clist_set_background, gtk_clist_set_background ()
gtk_clist_set_button_actions, gtk_clist_set_button_actions ()
gtk_clist_set_cell_style, gtk_clist_set_cell_style ()
gtk_clist_set_column_auto_resize, gtk_clist_set_column_auto_resize ()
gtk_clist_set_column_justification, gtk_clist_set_column_justification ()
gtk_clist_set_column_max_width, gtk_clist_set_column_max_width ()
gtk_clist_set_column_min_width, gtk_clist_set_column_min_width ()
gtk_clist_set_column_resizeable, gtk_clist_set_column_resizeable ()
gtk_clist_set_column_title, gtk_clist_set_column_title ()
gtk_clist_set_column_visibility, gtk_clist_set_column_visibility ()
gtk_clist_set_column_widget, gtk_clist_set_column_widget ()
gtk_clist_set_column_width, gtk_clist_set_column_width ()
gtk_clist_set_compare_func, gtk_clist_set_compare_func ()
GTK_CLIST_SET_FLAG, GTK_CLIST_SET_FLAG()
gtk_clist_set_foreground, gtk_clist_set_foreground ()
gtk_clist_set_hadjustment, gtk_clist_set_hadjustment ()
gtk_clist_set_pixmap, gtk_clist_set_pixmap ()
gtk_clist_set_pixtext, gtk_clist_set_pixtext ()
gtk_clist_set_reorderable, gtk_clist_set_reorderable ()
gtk_clist_set_row_data, gtk_clist_set_row_data ()
gtk_clist_set_row_data_full, gtk_clist_set_row_data_full ()
gtk_clist_set_row_height, gtk_clist_set_row_height ()
gtk_clist_set_row_style, gtk_clist_set_row_style ()
gtk_clist_set_selectable, gtk_clist_set_selectable ()
gtk_clist_set_selection_mode, gtk_clist_set_selection_mode ()
gtk_clist_set_shadow_type, gtk_clist_set_shadow_type ()
gtk_clist_set_shift, gtk_clist_set_shift ()
gtk_clist_set_sort_column, gtk_clist_set_sort_column ()
gtk_clist_set_sort_type, gtk_clist_set_sort_type ()
gtk_clist_set_text, gtk_clist_set_text ()
gtk_clist_set_use_drag_icons, gtk_clist_set_use_drag_icons ()
gtk_clist_set_vadjustment, gtk_clist_set_vadjustment ()
GTK_CLIST_SHOW_TITLES, GTK_CLIST_SHOW_TITLES()
gtk_clist_sort, gtk_clist_sort ()
gtk_clist_swap_rows, gtk_clist_swap_rows ()
gtk_clist_thaw, gtk_clist_thaw ()
gtk_clist_undo_selection, gtk_clist_undo_selection ()
gtk_clist_unselect_all, gtk_clist_unselect_all ()
gtk_clist_unselect_row, gtk_clist_unselect_row ()
GTK_CLIST_UNSET_FLAG, GTK_CLIST_UNSET_FLAG()
GTK_CLIST_USE_DRAG_ICONS, GTK_CLIST_USE_DRAG_ICONS()
gtk_color_button_get_alpha, gtk_color_button_get_alpha ()
gtk_color_button_get_color, gtk_color_button_get_color ()
gtk_color_button_get_title, gtk_color_button_get_title ()
gtk_color_button_get_use_alpha, gtk_color_button_get_use_alpha ()
gtk_color_button_new, gtk_color_button_new ()
gtk_color_button_new_with_color, gtk_color_button_new_with_color ()
gtk_color_button_set_alpha, gtk_color_button_set_alpha ()
gtk_color_button_set_color, gtk_color_button_set_color ()
gtk_color_button_set_title, gtk_color_button_set_title ()
gtk_color_button_set_use_alpha, gtk_color_button_set_use_alpha ()
gtk_color_selection_dialog_new, gtk_color_selection_dialog_new ()
gtk_color_selection_get_color, gtk_color_selection_get_color ()
gtk_color_selection_get_current_alpha, gtk_color_selection_get_current_alpha ()
gtk_color_selection_get_current_color, gtk_color_selection_get_current_color ()
gtk_color_selection_get_has_opacity_control, gtk_color_selection_get_has_opacity_control ()
gtk_color_selection_get_has_palette, gtk_color_selection_get_has_palette ()
gtk_color_selection_get_previous_alpha, gtk_color_selection_get_previous_alpha ()
gtk_color_selection_get_previous_color, gtk_color_selection_get_previous_color ()
gtk_color_selection_is_adjusting, gtk_color_selection_is_adjusting ()
gtk_color_selection_new, gtk_color_selection_new ()
gtk_color_selection_palette_from_string, gtk_color_selection_palette_from_string ()
gtk_color_selection_palette_to_string, gtk_color_selection_palette_to_string ()
gtk_color_selection_set_change_palette_hook, gtk_color_selection_set_change_palette_hook ()
gtk_color_selection_set_change_palette_with_screen_hook, gtk_color_selection_set_change_palette_with_screen_hook ()
gtk_color_selection_set_color, gtk_color_selection_set_color ()
gtk_color_selection_set_current_alpha, gtk_color_selection_set_current_alpha ()
gtk_color_selection_set_current_color, gtk_color_selection_set_current_color ()
gtk_color_selection_set_has_opacity_control, gtk_color_selection_set_has_opacity_control ()
gtk_color_selection_set_has_palette, gtk_color_selection_set_has_palette ()
gtk_color_selection_set_previous_alpha, gtk_color_selection_set_previous_alpha ()
gtk_color_selection_set_previous_color, gtk_color_selection_set_previous_color ()
gtk_color_selection_set_update_policy, gtk_color_selection_set_update_policy ()
gtk_combo_box_append_text, gtk_combo_box_append_text ()
gtk_combo_box_entry_get_text_column, gtk_combo_box_entry_get_text_column ()
gtk_combo_box_entry_new, gtk_combo_box_entry_new ()
gtk_combo_box_entry_new_text, gtk_combo_box_entry_new_text ()
gtk_combo_box_entry_new_with_model, gtk_combo_box_entry_new_with_model ()
gtk_combo_box_entry_set_text_column, gtk_combo_box_entry_set_text_column ()
gtk_combo_box_get_active, gtk_combo_box_get_active ()
gtk_combo_box_get_active_iter, gtk_combo_box_get_active_iter ()
gtk_combo_box_get_active_text, gtk_combo_box_get_active_text ()
gtk_combo_box_get_add_tearoffs, gtk_combo_box_get_add_tearoffs ()
gtk_combo_box_get_column_span_column, gtk_combo_box_get_column_span_column ()
gtk_combo_box_get_focus_on_click, gtk_combo_box_get_focus_on_click ()
gtk_combo_box_get_model, gtk_combo_box_get_model ()
gtk_combo_box_get_popup_accessible, gtk_combo_box_get_popup_accessible ()
gtk_combo_box_get_row_separator_func, gtk_combo_box_get_row_separator_func ()
gtk_combo_box_get_row_span_column, gtk_combo_box_get_row_span_column ()
gtk_combo_box_get_title, gtk_combo_box_get_title ()
gtk_combo_box_get_wrap_width, gtk_combo_box_get_wrap_width ()
gtk_combo_box_insert_text, gtk_combo_box_insert_text ()
gtk_combo_box_new, gtk_combo_box_new ()
gtk_combo_box_new_text, gtk_combo_box_new_text ()
gtk_combo_box_new_with_model, gtk_combo_box_new_with_model ()
gtk_combo_box_popdown, gtk_combo_box_popdown ()
gtk_combo_box_popup, gtk_combo_box_popup ()
gtk_combo_box_prepend_text, gtk_combo_box_prepend_text ()
gtk_combo_box_remove_text, gtk_combo_box_remove_text ()
gtk_combo_box_set_active, gtk_combo_box_set_active ()
gtk_combo_box_set_active_iter, gtk_combo_box_set_active_iter ()
gtk_combo_box_set_add_tearoffs, gtk_combo_box_set_add_tearoffs ()
gtk_combo_box_set_column_span_column, gtk_combo_box_set_column_span_column ()
gtk_combo_box_set_focus_on_click, gtk_combo_box_set_focus_on_click ()
gtk_combo_box_set_model, gtk_combo_box_set_model ()
gtk_combo_box_set_row_separator_func, gtk_combo_box_set_row_separator_func ()
gtk_combo_box_set_row_span_column, gtk_combo_box_set_row_span_column ()
gtk_combo_box_set_title, gtk_combo_box_set_title ()
gtk_combo_box_set_wrap_width, gtk_combo_box_set_wrap_width ()
gtk_combo_disable_activate, gtk_combo_disable_activate ()
gtk_combo_new, gtk_combo_new ()
gtk_combo_set_case_sensitive, gtk_combo_set_case_sensitive ()
gtk_combo_set_item_string, gtk_combo_set_item_string ()
gtk_combo_set_popdown_strings, gtk_combo_set_popdown_strings ()
gtk_combo_set_use_arrows, gtk_combo_set_use_arrows ()
gtk_combo_set_use_arrows_always, gtk_combo_set_use_arrows_always ()
gtk_combo_set_value_in_list, gtk_combo_set_value_in_list ()
gtk_container_add, gtk_container_add ()
gtk_container_add_with_properties, gtk_container_add_with_properties ()
gtk_container_border_width, gtk_container_border_width
gtk_container_check_resize, gtk_container_check_resize ()
gtk_container_children, gtk_container_children
gtk_container_child_get, gtk_container_child_get ()
gtk_container_child_get_property, gtk_container_child_get_property ()
gtk_container_child_get_valist, gtk_container_child_get_valist ()
gtk_container_child_set, gtk_container_child_set ()
gtk_container_child_set_property, gtk_container_child_set_property ()
gtk_container_child_set_valist, gtk_container_child_set_valist ()
gtk_container_child_type, gtk_container_child_type ()
gtk_container_class_find_child_property, gtk_container_class_find_child_property ()
gtk_container_class_install_child_property, gtk_container_class_install_child_property ()
gtk_container_class_list_child_properties, gtk_container_class_list_child_properties ()
gtk_container_forall, gtk_container_forall ()
gtk_container_foreach, gtk_container_foreach ()
gtk_container_foreach_full, gtk_container_foreach_full ()
gtk_container_get_border_width, gtk_container_get_border_width ()
gtk_container_get_children, gtk_container_get_children ()
gtk_container_get_focus_chain, gtk_container_get_focus_chain ()
gtk_container_get_focus_hadjustment, gtk_container_get_focus_hadjustment ()
gtk_container_get_focus_vadjustment, gtk_container_get_focus_vadjustment ()
gtk_container_get_resize_mode, gtk_container_get_resize_mode ()
gtk_container_propagate_expose, gtk_container_propagate_expose ()
gtk_container_remove, gtk_container_remove ()
gtk_container_resize_children, gtk_container_resize_children ()
gtk_container_set_border_width, gtk_container_set_border_width ()
gtk_container_set_focus_chain, gtk_container_set_focus_chain ()
gtk_container_set_focus_child, gtk_container_set_focus_child ()
gtk_container_set_focus_hadjustment, gtk_container_set_focus_hadjustment ()
gtk_container_set_focus_vadjustment, gtk_container_set_focus_vadjustment ()
gtk_container_set_reallocate_redraws, gtk_container_set_reallocate_redraws ()
gtk_container_set_resize_mode, gtk_container_set_resize_mode ()
gtk_container_unset_focus_chain, gtk_container_unset_focus_chain ()
GTK_CONTAINER_WARN_INVALID_CHILD_PROPERTY_ID, GTK_CONTAINER_WARN_INVALID_CHILD_PROPERTY_ID()
gtk_ctree_collapse, gtk_ctree_collapse ()
gtk_ctree_collapse_recursive, gtk_ctree_collapse_recursive ()
gtk_ctree_collapse_to_depth, gtk_ctree_collapse_to_depth ()
gtk_ctree_expand, gtk_ctree_expand ()
gtk_ctree_expand_recursive, gtk_ctree_expand_recursive ()
gtk_ctree_expand_to_depth, gtk_ctree_expand_to_depth ()
gtk_ctree_export_to_gnode, gtk_ctree_export_to_gnode ()
gtk_ctree_find, gtk_ctree_find ()
gtk_ctree_find_all_by_row_data, gtk_ctree_find_all_by_row_data ()
gtk_ctree_find_all_by_row_data_custom, gtk_ctree_find_all_by_row_data_custom ()
gtk_ctree_find_by_row_data, gtk_ctree_find_by_row_data ()
gtk_ctree_find_by_row_data_custom, gtk_ctree_find_by_row_data_custom ()
gtk_ctree_find_node_ptr, gtk_ctree_find_node_ptr ()
GTK_CTREE_FUNC, GTK_CTREE_FUNC()
gtk_ctree_get_node_info, gtk_ctree_get_node_info ()
gtk_ctree_insert_gnode, gtk_ctree_insert_gnode ()
gtk_ctree_insert_node, gtk_ctree_insert_node ()
gtk_ctree_is_ancestor, gtk_ctree_is_ancestor ()
gtk_ctree_is_hot_spot, gtk_ctree_is_hot_spot ()
gtk_ctree_is_viewable, gtk_ctree_is_viewable ()
gtk_ctree_last, gtk_ctree_last ()
gtk_ctree_move, gtk_ctree_move ()
gtk_ctree_new, gtk_ctree_new ()
gtk_ctree_new_with_titles, gtk_ctree_new_with_titles ()
GTK_CTREE_NODE, GTK_CTREE_NODE()
gtk_ctree_node_get_cell_style, gtk_ctree_node_get_cell_style ()
gtk_ctree_node_get_cell_type, gtk_ctree_node_get_cell_type ()
gtk_ctree_node_get_pixmap, gtk_ctree_node_get_pixmap ()
gtk_ctree_node_get_pixtext, gtk_ctree_node_get_pixtext ()
gtk_ctree_node_get_row_data, gtk_ctree_node_get_row_data ()
gtk_ctree_node_get_row_style, gtk_ctree_node_get_row_style ()
gtk_ctree_node_get_selectable, gtk_ctree_node_get_selectable ()
gtk_ctree_node_get_text, gtk_ctree_node_get_text ()
gtk_ctree_node_is_visible, gtk_ctree_node_is_visible ()
gtk_ctree_node_moveto, gtk_ctree_node_moveto ()
GTK_CTREE_NODE_NEXT, GTK_CTREE_NODE_NEXT()
gtk_ctree_node_nth, gtk_ctree_node_nth ()
GTK_CTREE_NODE_PREV, GTK_CTREE_NODE_PREV()
gtk_ctree_node_set_background, gtk_ctree_node_set_background ()
gtk_ctree_node_set_cell_style, gtk_ctree_node_set_cell_style ()
gtk_ctree_node_set_foreground, gtk_ctree_node_set_foreground ()
gtk_ctree_node_set_pixmap, gtk_ctree_node_set_pixmap ()
gtk_ctree_node_set_pixtext, gtk_ctree_node_set_pixtext ()
gtk_ctree_node_set_row_data, gtk_ctree_node_set_row_data ()
gtk_ctree_node_set_row_data_full, gtk_ctree_node_set_row_data_full ()
gtk_ctree_node_set_row_style, gtk_ctree_node_set_row_style ()
gtk_ctree_node_set_selectable, gtk_ctree_node_set_selectable ()
gtk_ctree_node_set_shift, gtk_ctree_node_set_shift ()
gtk_ctree_node_set_text, gtk_ctree_node_set_text ()
gtk_ctree_post_recursive, gtk_ctree_post_recursive ()
gtk_ctree_post_recursive_to_depth, gtk_ctree_post_recursive_to_depth ()
gtk_ctree_pre_recursive, gtk_ctree_pre_recursive ()
gtk_ctree_pre_recursive_to_depth, gtk_ctree_pre_recursive_to_depth ()
gtk_ctree_real_select_recursive, gtk_ctree_real_select_recursive ()
gtk_ctree_remove_node, gtk_ctree_remove_node ()
GTK_CTREE_ROW, GTK_CTREE_ROW()
gtk_ctree_select, gtk_ctree_select ()
gtk_ctree_select_recursive, gtk_ctree_select_recursive ()
gtk_ctree_set_drag_compare_func, gtk_ctree_set_drag_compare_func ()
gtk_ctree_set_expander_style, gtk_ctree_set_expander_style ()
gtk_ctree_set_indent, gtk_ctree_set_indent ()
gtk_ctree_set_line_style, gtk_ctree_set_line_style ()
gtk_ctree_set_node_info, gtk_ctree_set_node_info ()
gtk_ctree_set_reorderable, gtk_ctree_set_reorderable()
gtk_ctree_set_show_stub, gtk_ctree_set_show_stub ()
gtk_ctree_set_spacing, gtk_ctree_set_spacing ()
gtk_ctree_sort_node, gtk_ctree_sort_node ()
gtk_ctree_sort_recursive, gtk_ctree_sort_recursive ()
gtk_ctree_toggle_expansion, gtk_ctree_toggle_expansion ()
gtk_ctree_toggle_expansion_recursive, gtk_ctree_toggle_expansion_recursive ()
gtk_ctree_unselect, gtk_ctree_unselect ()
gtk_ctree_unselect_recursive, gtk_ctree_unselect_recursive ()
gtk_curve_get_vector, gtk_curve_get_vector ()
gtk_curve_new, gtk_curve_new ()
gtk_curve_reset, gtk_curve_reset ()
gtk_curve_set_curve_type, gtk_curve_set_curve_type ()
gtk_curve_set_gamma, gtk_curve_set_gamma ()
gtk_curve_set_range, gtk_curve_set_range ()
gtk_curve_set_vector, gtk_curve_set_vector ()
gtk_decorated_window_calculate_frame_size, gtk_decorated_window_calculate_frame_size ()
gtk_decorated_window_init, gtk_decorated_window_init ()
gtk_decorated_window_move_resize_window, gtk_decorated_window_move_resize_window ()
gtk_decorated_window_set_title, gtk_decorated_window_set_title ()
gtk_dialog_add_action_widget, gtk_dialog_add_action_widget ()
gtk_dialog_add_button, gtk_dialog_add_button ()
gtk_dialog_add_buttons, gtk_dialog_add_buttons ()
gtk_dialog_get_has_separator, gtk_dialog_get_has_separator ()
gtk_dialog_get_response_for_widget, gtk_dialog_get_response_for_widget ()
gtk_dialog_new, gtk_dialog_new ()
gtk_dialog_new_with_buttons, gtk_dialog_new_with_buttons ()
gtk_dialog_response, gtk_dialog_response ()
gtk_dialog_run, gtk_dialog_run ()
gtk_dialog_set_alternative_button_order, gtk_dialog_set_alternative_button_order ()
gtk_dialog_set_alternative_button_order_from_array, gtk_dialog_set_alternative_button_order_from_array ()
gtk_dialog_set_default_response, gtk_dialog_set_default_response ()
gtk_dialog_set_has_separator, gtk_dialog_set_has_separator ()
gtk_dialog_set_response_sensitive, gtk_dialog_set_response_sensitive ()
gtk_disable_setlocale, gtk_disable_setlocale ()
gtk_drag_begin, gtk_drag_begin ()
gtk_drag_check_threshold, gtk_drag_check_threshold ()
gtk_drag_dest_add_image_targets, gtk_drag_dest_add_image_targets ()
gtk_drag_dest_add_text_targets, gtk_drag_dest_add_text_targets ()
gtk_drag_dest_add_uri_targets, gtk_drag_dest_add_uri_targets ()
gtk_drag_dest_find_target, gtk_drag_dest_find_target ()
gtk_drag_dest_get_target_list, gtk_drag_dest_get_target_list ()
gtk_drag_dest_get_track_motion, gtk_drag_dest_get_track_motion ()
gtk_drag_dest_set, gtk_drag_dest_set ()
gtk_drag_dest_set_proxy, gtk_drag_dest_set_proxy ()
gtk_drag_dest_set_target_list, gtk_drag_dest_set_target_list ()
gtk_drag_dest_set_track_motion, gtk_drag_dest_set_track_motion ()
gtk_drag_dest_unset, gtk_drag_dest_unset ()
gtk_drag_finish, gtk_drag_finish ()
gtk_drag_get_data, gtk_drag_get_data ()
gtk_drag_get_source_widget, gtk_drag_get_source_widget ()
gtk_drag_highlight, gtk_drag_highlight ()
gtk_drag_set_default_icon, gtk_drag_set_default_icon ()
gtk_drag_set_icon_default, gtk_drag_set_icon_default ()
gtk_drag_set_icon_name, gtk_drag_set_icon_name ()
gtk_drag_set_icon_pixbuf, gtk_drag_set_icon_pixbuf ()
gtk_drag_set_icon_pixmap, gtk_drag_set_icon_pixmap ()
gtk_drag_set_icon_stock, gtk_drag_set_icon_stock ()
gtk_drag_set_icon_widget, gtk_drag_set_icon_widget ()
gtk_drag_source_add_image_targets, gtk_drag_source_add_image_targets ()
gtk_drag_source_add_text_targets, gtk_drag_source_add_text_targets ()
gtk_drag_source_add_uri_targets, gtk_drag_source_add_uri_targets ()
gtk_drag_source_get_target_list, gtk_drag_source_get_target_list ()
gtk_drag_source_set, gtk_drag_source_set ()
gtk_drag_source_set_icon, gtk_drag_source_set_icon ()
gtk_drag_source_set_icon_name, gtk_drag_source_set_icon_name ()
gtk_drag_source_set_icon_pixbuf, gtk_drag_source_set_icon_pixbuf ()
gtk_drag_source_set_icon_stock, gtk_drag_source_set_icon_stock ()
gtk_drag_source_set_target_list, gtk_drag_source_set_target_list ()
gtk_drag_source_unset, gtk_drag_source_unset ()
gtk_drag_unhighlight, gtk_drag_unhighlight ()
gtk_drawing_area_new, gtk_drawing_area_new ()
gtk_drawing_area_size, gtk_drawing_area_size ()
gtk_draw_arrow, gtk_draw_arrow ()
gtk_draw_box, gtk_draw_box ()
gtk_draw_box_gap, gtk_draw_box_gap ()
gtk_draw_check, gtk_draw_check ()
gtk_draw_diamond, gtk_draw_diamond ()
gtk_draw_expander, gtk_draw_expander ()
gtk_draw_extension, gtk_draw_extension ()
gtk_draw_flat_box, gtk_draw_flat_box ()
gtk_draw_focus, gtk_draw_focus ()
gtk_draw_handle, gtk_draw_handle ()
gtk_draw_hline, gtk_draw_hline ()
gtk_draw_insertion_cursor, gtk_draw_insertion_cursor ()
gtk_draw_layout, gtk_draw_layout ()
gtk_draw_option, gtk_draw_option ()
gtk_draw_polygon, gtk_draw_polygon ()
gtk_draw_resize_grip, gtk_draw_resize_grip ()
gtk_draw_shadow, gtk_draw_shadow ()
gtk_draw_shadow_gap, gtk_draw_shadow_gap ()
gtk_draw_slider, gtk_draw_slider ()
gtk_draw_string, gtk_draw_string ()
gtk_draw_tab, gtk_draw_tab ()
gtk_draw_vline, gtk_draw_vline ()
gtk_editable_copy_clipboard, gtk_editable_copy_clipboard ()
gtk_editable_cut_clipboard, gtk_editable_cut_clipboard ()
gtk_editable_delete_selection, gtk_editable_delete_selection ()
gtk_editable_delete_text, gtk_editable_delete_text ()
gtk_editable_get_chars, gtk_editable_get_chars ()
gtk_editable_get_editable, gtk_editable_get_editable ()
gtk_editable_get_position, gtk_editable_get_position ()
gtk_editable_get_selection_bounds, gtk_editable_get_selection_bounds ()
gtk_editable_insert_text, gtk_editable_insert_text ()
gtk_editable_paste_clipboard, gtk_editable_paste_clipboard ()
gtk_editable_select_region, gtk_editable_select_region ()
gtk_editable_set_editable, gtk_editable_set_editable ()
gtk_editable_set_position, gtk_editable_set_position ()
gtk_entry_append_text, gtk_entry_append_text ()
gtk_entry_completion_complete, gtk_entry_completion_complete ()
gtk_entry_completion_delete_action, gtk_entry_completion_delete_action ()
gtk_entry_completion_get_entry, gtk_entry_completion_get_entry ()
gtk_entry_completion_get_inline_completion, gtk_entry_completion_get_inline_completion ()
gtk_entry_completion_get_minimum_key_length, gtk_entry_completion_get_minimum_key_length ()
gtk_entry_completion_get_model, gtk_entry_completion_get_model ()
gtk_entry_completion_get_popup_completion, gtk_entry_completion_get_popup_completion ()
gtk_entry_completion_get_popup_set_width, gtk_entry_completion_get_popup_set_width ()
gtk_entry_completion_get_popup_single_match, gtk_entry_completion_get_popup_single_match ()
gtk_entry_completion_get_text_column, gtk_entry_completion_get_text_column ()
gtk_entry_completion_insert_action_markup, gtk_entry_completion_insert_action_markup ()
gtk_entry_completion_insert_action_text, gtk_entry_completion_insert_action_text ()
gtk_entry_completion_insert_prefix, gtk_entry_completion_insert_prefix ()
gtk_entry_completion_new, gtk_entry_completion_new ()
gtk_entry_completion_set_inline_completion, gtk_entry_completion_set_inline_completion ()
gtk_entry_completion_set_match_func, gtk_entry_completion_set_match_func ()
gtk_entry_completion_set_minimum_key_length, gtk_entry_completion_set_minimum_key_length ()
gtk_entry_completion_set_model, gtk_entry_completion_set_model ()
gtk_entry_completion_set_popup_completion, gtk_entry_completion_set_popup_completion ()
gtk_entry_completion_set_popup_set_width, gtk_entry_completion_set_popup_set_width ()
gtk_entry_completion_set_popup_single_match, gtk_entry_completion_set_popup_single_match ()
gtk_entry_completion_set_text_column, gtk_entry_completion_set_text_column ()
gtk_entry_get_activates_default, gtk_entry_get_activates_default ()
gtk_entry_get_alignment, gtk_entry_get_alignment ()
gtk_entry_get_completion, gtk_entry_get_completion ()
gtk_entry_get_has_frame, gtk_entry_get_has_frame ()
gtk_entry_get_inner_border, gtk_entry_get_inner_border ()
gtk_entry_get_invisible_char, gtk_entry_get_invisible_char ()
gtk_entry_get_layout, gtk_entry_get_layout ()
gtk_entry_get_layout_offsets, gtk_entry_get_layout_offsets ()
gtk_entry_get_max_length, gtk_entry_get_max_length ()
gtk_entry_get_text, gtk_entry_get_text ()
gtk_entry_get_visibility, gtk_entry_get_visibility ()
gtk_entry_get_width_chars, gtk_entry_get_width_chars ()
gtk_entry_layout_index_to_text_index, gtk_entry_layout_index_to_text_index ()
gtk_entry_new, gtk_entry_new ()
gtk_entry_new_with_max_length, gtk_entry_new_with_max_length ()
gtk_entry_prepend_text, gtk_entry_prepend_text ()
gtk_entry_select_region, gtk_entry_select_region ()
gtk_entry_set_activates_default, gtk_entry_set_activates_default ()
gtk_entry_set_alignment, gtk_entry_set_alignment ()
gtk_entry_set_completion, gtk_entry_set_completion ()
gtk_entry_set_editable, gtk_entry_set_editable ()
gtk_entry_set_has_frame, gtk_entry_set_has_frame ()
gtk_entry_set_inner_border, gtk_entry_set_inner_border ()
gtk_entry_set_invisible_char, gtk_entry_set_invisible_char ()
gtk_entry_set_max_length, gtk_entry_set_max_length ()
gtk_entry_set_position, gtk_entry_set_position ()
gtk_entry_set_text, gtk_entry_set_text ()
gtk_entry_set_visibility, gtk_entry_set_visibility ()
gtk_entry_set_width_chars, gtk_entry_set_width_chars ()
gtk_entry_text_index_to_layout_index, gtk_entry_text_index_to_layout_index ()
gtk_enumerate_printers, gtk_enumerate_printers ()
gtk_events_pending, gtk_events_pending ()
gtk_event_box_get_above_child, gtk_event_box_get_above_child ()
gtk_event_box_get_visible_window, gtk_event_box_get_visible_window ()
gtk_event_box_new, gtk_event_box_new ()
gtk_event_box_set_above_child, gtk_event_box_set_above_child ()
gtk_event_box_set_visible_window, gtk_event_box_set_visible_window ()
gtk_exit, gtk_exit ()
gtk_expander_get_expanded, gtk_expander_get_expanded ()
gtk_expander_get_label, gtk_expander_get_label ()
gtk_expander_get_label_widget, gtk_expander_get_label_widget ()
gtk_expander_get_spacing, gtk_expander_get_spacing ()
gtk_expander_get_use_markup, gtk_expander_get_use_markup ()
gtk_expander_get_use_underline, gtk_expander_get_use_underline ()
gtk_expander_new, gtk_expander_new ()
gtk_expander_new_with_mnemonic, gtk_expander_new_with_mnemonic ()
gtk_expander_set_expanded, gtk_expander_set_expanded ()
gtk_expander_set_label, gtk_expander_set_label ()
gtk_expander_set_label_widget, gtk_expander_set_label_widget ()
gtk_expander_set_spacing, gtk_expander_set_spacing ()
gtk_expander_set_use_markup, gtk_expander_set_use_markup ()
gtk_expander_set_use_underline, gtk_expander_set_use_underline ()
gtk_false, gtk_false ()
gtk_file_chooser_add_filter, gtk_file_chooser_add_filter ()
gtk_file_chooser_add_shortcut_folder, gtk_file_chooser_add_shortcut_folder ()
gtk_file_chooser_add_shortcut_folder_uri, gtk_file_chooser_add_shortcut_folder_uri ()
gtk_file_chooser_button_get_focus_on_click, gtk_file_chooser_button_get_focus_on_click ()
gtk_file_chooser_button_get_title, gtk_file_chooser_button_get_title ()
gtk_file_chooser_button_get_width_chars, gtk_file_chooser_button_get_width_chars ()
gtk_file_chooser_button_new, gtk_file_chooser_button_new ()
gtk_file_chooser_button_new_with_backend, gtk_file_chooser_button_new_with_backend ()
gtk_file_chooser_button_new_with_dialog, gtk_file_chooser_button_new_with_dialog ()
gtk_file_chooser_button_set_focus_on_click, gtk_file_chooser_button_set_focus_on_click ()
gtk_file_chooser_button_set_title, gtk_file_chooser_button_set_title ()
gtk_file_chooser_button_set_width_chars, gtk_file_chooser_button_set_width_chars ()
gtk_file_chooser_dialog_new, gtk_file_chooser_dialog_new ()
gtk_file_chooser_dialog_new_with_backend, gtk_file_chooser_dialog_new_with_backend ()
GTK_FILE_CHOOSER_ERROR, GTK_FILE_CHOOSER_ERROR
gtk_file_chooser_get_action, gtk_file_chooser_get_action ()
gtk_file_chooser_get_current_folder, gtk_file_chooser_get_current_folder ()
gtk_file_chooser_get_current_folder_uri, gtk_file_chooser_get_current_folder_uri ()
gtk_file_chooser_get_do_overwrite_confirmation, gtk_file_chooser_get_do_overwrite_confirmation ()
gtk_file_chooser_get_extra_widget, gtk_file_chooser_get_extra_widget ()
gtk_file_chooser_get_filename, gtk_file_chooser_get_filename ()
gtk_file_chooser_get_filenames, gtk_file_chooser_get_filenames ()
gtk_file_chooser_get_filter, gtk_file_chooser_get_filter ()
gtk_file_chooser_get_local_only, gtk_file_chooser_get_local_only ()
gtk_file_chooser_get_preview_filename, gtk_file_chooser_get_preview_filename ()
gtk_file_chooser_get_preview_uri, gtk_file_chooser_get_preview_uri ()
gtk_file_chooser_get_preview_widget, gtk_file_chooser_get_preview_widget ()
gtk_file_chooser_get_preview_widget_active, gtk_file_chooser_get_preview_widget_active ()
gtk_file_chooser_get_select_multiple, gtk_file_chooser_get_select_multiple ()
gtk_file_chooser_get_show_hidden, gtk_file_chooser_get_show_hidden ()
gtk_file_chooser_get_uri, gtk_file_chooser_get_uri ()
gtk_file_chooser_get_uris, gtk_file_chooser_get_uris ()
gtk_file_chooser_get_use_preview_label, gtk_file_chooser_get_use_preview_label ()
gtk_file_chooser_list_filters, gtk_file_chooser_list_filters ()
gtk_file_chooser_list_shortcut_folders, gtk_file_chooser_list_shortcut_folders ()
gtk_file_chooser_list_shortcut_folder_uris, gtk_file_chooser_list_shortcut_folder_uris ()
gtk_file_chooser_remove_filter, gtk_file_chooser_remove_filter ()
gtk_file_chooser_remove_shortcut_folder, gtk_file_chooser_remove_shortcut_folder ()
gtk_file_chooser_remove_shortcut_folder_uri, gtk_file_chooser_remove_shortcut_folder_uri ()
gtk_file_chooser_select_all, gtk_file_chooser_select_all ()
gtk_file_chooser_select_filename, gtk_file_chooser_select_filename ()
gtk_file_chooser_select_uri, gtk_file_chooser_select_uri ()
gtk_file_chooser_set_action, gtk_file_chooser_set_action ()
gtk_file_chooser_set_current_folder, gtk_file_chooser_set_current_folder ()
gtk_file_chooser_set_current_folder_uri, gtk_file_chooser_set_current_folder_uri ()
gtk_file_chooser_set_current_name, gtk_file_chooser_set_current_name ()
gtk_file_chooser_set_do_overwrite_confirmation, gtk_file_chooser_set_do_overwrite_confirmation ()
gtk_file_chooser_set_extra_widget, gtk_file_chooser_set_extra_widget ()
gtk_file_chooser_set_filename, gtk_file_chooser_set_filename ()
gtk_file_chooser_set_filter, gtk_file_chooser_set_filter ()
gtk_file_chooser_set_local_only, gtk_file_chooser_set_local_only ()
gtk_file_chooser_set_preview_widget, gtk_file_chooser_set_preview_widget ()
gtk_file_chooser_set_preview_widget_active, gtk_file_chooser_set_preview_widget_active ()
gtk_file_chooser_set_select_multiple, gtk_file_chooser_set_select_multiple ()
gtk_file_chooser_set_show_hidden, gtk_file_chooser_set_show_hidden ()
gtk_file_chooser_set_uri, gtk_file_chooser_set_uri ()
gtk_file_chooser_set_use_preview_label, gtk_file_chooser_set_use_preview_label ()
gtk_file_chooser_unselect_all, gtk_file_chooser_unselect_all ()
gtk_file_chooser_unselect_filename, gtk_file_chooser_unselect_filename ()
gtk_file_chooser_unselect_uri, gtk_file_chooser_unselect_uri ()
gtk_file_chooser_widget_new, gtk_file_chooser_widget_new ()
gtk_file_chooser_widget_new_with_backend, gtk_file_chooser_widget_new_with_backend ()
gtk_file_filter_add_custom, gtk_file_filter_add_custom ()
gtk_file_filter_add_mime_type, gtk_file_filter_add_mime_type ()
gtk_file_filter_add_pattern, gtk_file_filter_add_pattern ()
gtk_file_filter_add_pixbuf_formats, gtk_file_filter_add_pixbuf_formats ()
gtk_file_filter_filter, gtk_file_filter_filter ()
gtk_file_filter_get_name, gtk_file_filter_get_name ()
gtk_file_filter_get_needed, gtk_file_filter_get_needed ()
gtk_file_filter_new, gtk_file_filter_new ()
gtk_file_filter_set_name, gtk_file_filter_set_name ()
gtk_file_selection_complete, gtk_file_selection_complete ()
gtk_file_selection_get_filename, gtk_file_selection_get_filename ()
gtk_file_selection_get_selections, gtk_file_selection_get_selections ()
gtk_file_selection_get_select_multiple, gtk_file_selection_get_select_multiple ()
gtk_file_selection_hide_fileop_buttons, gtk_file_selection_hide_fileop_buttons ()
gtk_file_selection_new, gtk_file_selection_new ()
gtk_file_selection_set_filename, gtk_file_selection_set_filename ()
gtk_file_selection_set_select_multiple, gtk_file_selection_set_select_multiple ()
gtk_file_selection_show_fileop_buttons, gtk_file_selection_show_fileop_buttons ()
gtk_fixed_get_has_window, gtk_fixed_get_has_window ()
gtk_fixed_move, gtk_fixed_move ()
gtk_fixed_new, gtk_fixed_new ()
gtk_fixed_put, gtk_fixed_put ()
gtk_fixed_set_has_window, gtk_fixed_set_has_window ()
gtk_font_button_get_font_name, gtk_font_button_get_font_name ()
gtk_font_button_get_show_size, gtk_font_button_get_show_size ()
gtk_font_button_get_show_style, gtk_font_button_get_show_style ()
gtk_font_button_get_title, gtk_font_button_get_title ()
gtk_font_button_get_use_font, gtk_font_button_get_use_font ()
gtk_font_button_get_use_size, gtk_font_button_get_use_size ()
gtk_font_button_new, gtk_font_button_new ()
gtk_font_button_new_with_font, gtk_font_button_new_with_font ()
gtk_font_button_set_font_name, gtk_font_button_set_font_name ()
gtk_font_button_set_show_size, gtk_font_button_set_show_size ()
gtk_font_button_set_show_style, gtk_font_button_set_show_style ()
gtk_font_button_set_title, gtk_font_button_set_title ()
gtk_font_button_set_use_font, gtk_font_button_set_use_font ()
gtk_font_button_set_use_size, gtk_font_button_set_use_size ()
gtk_font_selection_dialog_get_font, gtk_font_selection_dialog_get_font ()
gtk_font_selection_dialog_get_font_name, gtk_font_selection_dialog_get_font_name ()
gtk_font_selection_dialog_get_preview_text, gtk_font_selection_dialog_get_preview_text ()
gtk_font_selection_dialog_new, gtk_font_selection_dialog_new ()
gtk_font_selection_dialog_set_font_name, gtk_font_selection_dialog_set_font_name ()
gtk_font_selection_dialog_set_preview_text, gtk_font_selection_dialog_set_preview_text ()
gtk_font_selection_get_font, gtk_font_selection_get_font ()
gtk_font_selection_get_font_name, gtk_font_selection_get_font_name ()
gtk_font_selection_get_preview_text, gtk_font_selection_get_preview_text ()
gtk_font_selection_new, gtk_font_selection_new ()
gtk_font_selection_set_font_name, gtk_font_selection_set_font_name ()
gtk_font_selection_set_preview_text, gtk_font_selection_set_preview_text ()
gtk_frame_get_label, gtk_frame_get_label ()
gtk_frame_get_label_align, gtk_frame_get_label_align ()
gtk_frame_get_label_widget, gtk_frame_get_label_widget ()
gtk_frame_get_shadow_type, gtk_frame_get_shadow_type ()
gtk_frame_new, gtk_frame_new ()
gtk_frame_set_label, gtk_frame_set_label ()
gtk_frame_set_label_align, gtk_frame_set_label_align ()
gtk_frame_set_label_widget, gtk_frame_set_label_widget ()
gtk_frame_set_shadow_type, gtk_frame_set_shadow_type ()
GTK_FUNDAMENTAL_TYPE, GTK_FUNDAMENTAL_TYPE
gtk_gamma_curve_new, gtk_gamma_curve_new ()
gtk_gc_get, gtk_gc_get ()
gtk_gc_release, gtk_gc_release ()
gtk_get_current_event, gtk_get_current_event ()
gtk_get_current_event_state, gtk_get_current_event_state ()
gtk_get_current_event_time, gtk_get_current_event_time ()
gtk_get_default_language, gtk_get_default_language ()
gtk_get_event_widget, gtk_get_event_widget ()
gtk_get_option_group, gtk_get_option_group ()
gtk_grab_add, gtk_grab_add ()
gtk_grab_get_current, gtk_grab_get_current ()
gtk_grab_remove, gtk_grab_remove ()
gtk_handle_box_get_handle_position, gtk_handle_box_get_handle_position ()
gtk_handle_box_get_shadow_type, gtk_handle_box_get_shadow_type ()
gtk_handle_box_get_snap_edge, gtk_handle_box_get_snap_edge ()
gtk_handle_box_new, gtk_handle_box_new ()
gtk_handle_box_set_handle_position, gtk_handle_box_set_handle_position ()
gtk_handle_box_set_shadow_type, gtk_handle_box_set_shadow_type ()
gtk_handle_box_set_snap_edge, gtk_handle_box_set_snap_edge ()
gtk_hbox_new, gtk_hbox_new ()
gtk_hbutton_box_get_layout_default, gtk_hbutton_box_get_layout_default ()
gtk_hbutton_box_get_spacing_default, gtk_hbutton_box_get_spacing_default ()
gtk_hbutton_box_new, gtk_hbutton_box_new ()
gtk_hbutton_box_set_layout_default, gtk_hbutton_box_set_layout_default ()
gtk_hbutton_box_set_spacing_default, gtk_hbutton_box_set_spacing_default ()
gtk_hpaned_new, gtk_hpaned_new ()
gtk_hruler_new, gtk_hruler_new ()
gtk_hscale_new, gtk_hscale_new ()
gtk_hscale_new_with_range, gtk_hscale_new_with_range ()
gtk_hscrollbar_new, gtk_hscrollbar_new ()
gtk_hseparator_new, gtk_hseparator_new ()
gtk_icon_factory_add, gtk_icon_factory_add ()
gtk_icon_factory_add_default, gtk_icon_factory_add_default ()
gtk_icon_factory_lookup, gtk_icon_factory_lookup ()
gtk_icon_factory_lookup_default, gtk_icon_factory_lookup_default ()
gtk_icon_factory_new, gtk_icon_factory_new ()
gtk_icon_factory_remove_default, gtk_icon_factory_remove_default ()
gtk_icon_info_copy, gtk_icon_info_copy ()
gtk_icon_info_free, gtk_icon_info_free ()
gtk_icon_info_get_attach_points, gtk_icon_info_get_attach_points ()
gtk_icon_info_get_base_size, gtk_icon_info_get_base_size ()
gtk_icon_info_get_builtin_pixbuf, gtk_icon_info_get_builtin_pixbuf ()
gtk_icon_info_get_display_name, gtk_icon_info_get_display_name ()
gtk_icon_info_get_embedded_rect, gtk_icon_info_get_embedded_rect ()
gtk_icon_info_get_filename, gtk_icon_info_get_filename ()
gtk_icon_info_load_icon, gtk_icon_info_load_icon ()
gtk_icon_info_set_raw_coordinates, gtk_icon_info_set_raw_coordinates ()
gtk_icon_set_add_source, gtk_icon_set_add_source ()
gtk_icon_set_copy, gtk_icon_set_copy ()
gtk_icon_set_get_sizes, gtk_icon_set_get_sizes ()
gtk_icon_set_new, gtk_icon_set_new ()
gtk_icon_set_new_from_pixbuf, gtk_icon_set_new_from_pixbuf ()
gtk_icon_set_ref, gtk_icon_set_ref ()
gtk_icon_set_render_icon, gtk_icon_set_render_icon ()
gtk_icon_set_unref, gtk_icon_set_unref ()
gtk_icon_size_from_name, gtk_icon_size_from_name ()
gtk_icon_size_get_name, gtk_icon_size_get_name ()
gtk_icon_size_lookup, gtk_icon_size_lookup ()
gtk_icon_size_lookup_for_settings, gtk_icon_size_lookup_for_settings ()
gtk_icon_size_register, gtk_icon_size_register ()
gtk_icon_size_register_alias, gtk_icon_size_register_alias ()
gtk_icon_source_copy, gtk_icon_source_copy ()
gtk_icon_source_free, gtk_icon_source_free ()
gtk_icon_source_get_direction, gtk_icon_source_get_direction ()
gtk_icon_source_get_direction_wildcarded, gtk_icon_source_get_direction_wildcarded ()
gtk_icon_source_get_filename, gtk_icon_source_get_filename ()
gtk_icon_source_get_icon_name, gtk_icon_source_get_icon_name ()
gtk_icon_source_get_pixbuf, gtk_icon_source_get_pixbuf ()
gtk_icon_source_get_size, gtk_icon_source_get_size ()
gtk_icon_source_get_size_wildcarded, gtk_icon_source_get_size_wildcarded ()
gtk_icon_source_get_state, gtk_icon_source_get_state ()
gtk_icon_source_get_state_wildcarded, gtk_icon_source_get_state_wildcarded ()
gtk_icon_source_new, gtk_icon_source_new ()
gtk_icon_source_set_direction, gtk_icon_source_set_direction ()
gtk_icon_source_set_direction_wildcarded, gtk_icon_source_set_direction_wildcarded ()
gtk_icon_source_set_filename, gtk_icon_source_set_filename ()
gtk_icon_source_set_icon_name, gtk_icon_source_set_icon_name ()
gtk_icon_source_set_pixbuf, gtk_icon_source_set_pixbuf ()
gtk_icon_source_set_size, gtk_icon_source_set_size ()
gtk_icon_source_set_size_wildcarded, gtk_icon_source_set_size_wildcarded ()
gtk_icon_source_set_state, gtk_icon_source_set_state ()
gtk_icon_source_set_state_wildcarded, gtk_icon_source_set_state_wildcarded ()
gtk_icon_theme_add_builtin_icon, gtk_icon_theme_add_builtin_icon ()
gtk_icon_theme_append_search_path, gtk_icon_theme_append_search_path ()
GTK_ICON_THEME_ERROR, GTK_ICON_THEME_ERROR
gtk_icon_theme_get_default, gtk_icon_theme_get_default ()
gtk_icon_theme_get_example_icon_name, gtk_icon_theme_get_example_icon_name ()
gtk_icon_theme_get_for_screen, gtk_icon_theme_get_for_screen ()
gtk_icon_theme_get_icon_sizes, gtk_icon_theme_get_icon_sizes ()
gtk_icon_theme_get_search_path, gtk_icon_theme_get_search_path ()
gtk_icon_theme_has_icon, gtk_icon_theme_has_icon ()
gtk_icon_theme_list_icons, gtk_icon_theme_list_icons ()
gtk_icon_theme_load_icon, gtk_icon_theme_load_icon ()
gtk_icon_theme_lookup_icon, gtk_icon_theme_lookup_icon ()
gtk_icon_theme_new, gtk_icon_theme_new ()
gtk_icon_theme_prepend_search_path, gtk_icon_theme_prepend_search_path ()
gtk_icon_theme_rescan_if_needed, gtk_icon_theme_rescan_if_needed ()
gtk_icon_theme_set_custom_theme, gtk_icon_theme_set_custom_theme ()
gtk_icon_theme_set_screen, gtk_icon_theme_set_screen ()
gtk_icon_theme_set_search_path, gtk_icon_theme_set_search_path ()
gtk_icon_view_create_drag_icon, gtk_icon_view_create_drag_icon ()
gtk_icon_view_enable_model_drag_dest, gtk_icon_view_enable_model_drag_dest ()
gtk_icon_view_enable_model_drag_source, gtk_icon_view_enable_model_drag_source ()
gtk_icon_view_get_columns, gtk_icon_view_get_columns ()
gtk_icon_view_get_column_spacing, gtk_icon_view_get_column_spacing ()
gtk_icon_view_get_cursor, gtk_icon_view_get_cursor ()
gtk_icon_view_get_dest_item_at_pos, gtk_icon_view_get_dest_item_at_pos ()
gtk_icon_view_get_drag_dest_item, gtk_icon_view_get_drag_dest_item ()
gtk_icon_view_get_item_at_pos, gtk_icon_view_get_item_at_pos ()
gtk_icon_view_get_item_width, gtk_icon_view_get_item_width ()
gtk_icon_view_get_margin, gtk_icon_view_get_margin ()
gtk_icon_view_get_markup_column, gtk_icon_view_get_markup_column ()
gtk_icon_view_get_model, gtk_icon_view_get_model ()
gtk_icon_view_get_orientation, gtk_icon_view_get_orientation ()
gtk_icon_view_get_path_at_pos, gtk_icon_view_get_path_at_pos ()
gtk_icon_view_get_pixbuf_column, gtk_icon_view_get_pixbuf_column ()
gtk_icon_view_get_reorderable, gtk_icon_view_get_reorderable ()
gtk_icon_view_get_row_spacing, gtk_icon_view_get_row_spacing ()
gtk_icon_view_get_selected_items, gtk_icon_view_get_selected_items ()
gtk_icon_view_get_selection_mode, gtk_icon_view_get_selection_mode ()
gtk_icon_view_get_spacing, gtk_icon_view_get_spacing ()
gtk_icon_view_get_text_column, gtk_icon_view_get_text_column ()
gtk_icon_view_get_visible_range, gtk_icon_view_get_visible_range ()
gtk_icon_view_item_activated, gtk_icon_view_item_activated ()
gtk_icon_view_new, gtk_icon_view_new ()
gtk_icon_view_new_with_model, gtk_icon_view_new_with_model ()
gtk_icon_view_path_is_selected, gtk_icon_view_path_is_selected ()
gtk_icon_view_scroll_to_path, gtk_icon_view_scroll_to_path ()
gtk_icon_view_selected_foreach, gtk_icon_view_selected_foreach ()
gtk_icon_view_select_all, gtk_icon_view_select_all ()
gtk_icon_view_select_path, gtk_icon_view_select_path ()
gtk_icon_view_set_columns, gtk_icon_view_set_columns ()
gtk_icon_view_set_column_spacing, gtk_icon_view_set_column_spacing ()
gtk_icon_view_set_cursor, gtk_icon_view_set_cursor ()
gtk_icon_view_set_drag_dest_item, gtk_icon_view_set_drag_dest_item ()
gtk_icon_view_set_item_width, gtk_icon_view_set_item_width ()
gtk_icon_view_set_margin, gtk_icon_view_set_margin ()
gtk_icon_view_set_markup_column, gtk_icon_view_set_markup_column ()
gtk_icon_view_set_model, gtk_icon_view_set_model ()
gtk_icon_view_set_orientation, gtk_icon_view_set_orientation ()
gtk_icon_view_set_pixbuf_column, gtk_icon_view_set_pixbuf_column ()
gtk_icon_view_set_reorderable, gtk_icon_view_set_reorderable ()
gtk_icon_view_set_row_spacing, gtk_icon_view_set_row_spacing ()
gtk_icon_view_set_selection_mode, gtk_icon_view_set_selection_mode ()
gtk_icon_view_set_spacing, gtk_icon_view_set_spacing ()
gtk_icon_view_set_text_column, gtk_icon_view_set_text_column ()
gtk_icon_view_unselect_all, gtk_icon_view_unselect_all ()
gtk_icon_view_unselect_path, gtk_icon_view_unselect_path ()
gtk_icon_view_unset_model_drag_dest, gtk_icon_view_unset_model_drag_dest ()
gtk_icon_view_unset_model_drag_source, gtk_icon_view_unset_model_drag_source ()
gtk_idle_add, gtk_idle_add ()
gtk_idle_add_full, gtk_idle_add_full ()
gtk_idle_add_priority, gtk_idle_add_priority ()
gtk_idle_remove, gtk_idle_remove ()
gtk_idle_remove_by_data, gtk_idle_remove_by_data ()
gtk_image_clear, gtk_image_clear ()
gtk_image_get, gtk_image_get ()
gtk_image_get_animation, gtk_image_get_animation ()
gtk_image_get_icon_name, gtk_image_get_icon_name ()
gtk_image_get_icon_set, gtk_image_get_icon_set ()
gtk_image_get_image, gtk_image_get_image ()
gtk_image_get_pixbuf, gtk_image_get_pixbuf ()
gtk_image_get_pixel_size, gtk_image_get_pixel_size ()
gtk_image_get_pixmap, gtk_image_get_pixmap ()
gtk_image_get_stock, gtk_image_get_stock ()
gtk_image_get_storage_type, gtk_image_get_storage_type ()
gtk_image_menu_item_get_image, gtk_image_menu_item_get_image ()
gtk_image_menu_item_new, gtk_image_menu_item_new ()
gtk_image_menu_item_new_from_stock, gtk_image_menu_item_new_from_stock ()
gtk_image_menu_item_new_with_label, gtk_image_menu_item_new_with_label ()
gtk_image_menu_item_new_with_mnemonic, gtk_image_menu_item_new_with_mnemonic ()
gtk_image_menu_item_set_image, gtk_image_menu_item_set_image ()
gtk_image_new, gtk_image_new ()
gtk_image_new_from_animation, gtk_image_new_from_animation ()
gtk_image_new_from_file, gtk_image_new_from_file ()
gtk_image_new_from_icon_name, gtk_image_new_from_icon_name ()
gtk_image_new_from_icon_set, gtk_image_new_from_icon_set ()
gtk_image_new_from_image, gtk_image_new_from_image ()
gtk_image_new_from_pixbuf, gtk_image_new_from_pixbuf ()
gtk_image_new_from_pixmap, gtk_image_new_from_pixmap ()
gtk_image_new_from_stock, gtk_image_new_from_stock ()
gtk_image_set, gtk_image_set ()
gtk_image_set_from_animation, gtk_image_set_from_animation ()
gtk_image_set_from_file, gtk_image_set_from_file ()
gtk_image_set_from_icon_name, gtk_image_set_from_icon_name ()
gtk_image_set_from_icon_set, gtk_image_set_from_icon_set ()
gtk_image_set_from_image, gtk_image_set_from_image ()
gtk_image_set_from_pixbuf, gtk_image_set_from_pixbuf ()
gtk_image_set_from_pixmap, gtk_image_set_from_pixmap ()
gtk_image_set_from_stock, gtk_image_set_from_stock ()
gtk_image_set_pixel_size, gtk_image_set_pixel_size ()
gtk_im_context_delete_surrounding, gtk_im_context_delete_surrounding ()
gtk_im_context_filter_keypress, gtk_im_context_filter_keypress ()
gtk_im_context_focus_in, gtk_im_context_focus_in ()
gtk_im_context_focus_out, gtk_im_context_focus_out ()
gtk_im_context_get_preedit_string, gtk_im_context_get_preedit_string ()
gtk_im_context_get_surrounding, gtk_im_context_get_surrounding ()
gtk_im_context_reset, gtk_im_context_reset ()
gtk_im_context_set_client_window, gtk_im_context_set_client_window ()
gtk_im_context_set_cursor_location, gtk_im_context_set_cursor_location ()
gtk_im_context_set_surrounding, gtk_im_context_set_surrounding ()
gtk_im_context_set_use_preedit, gtk_im_context_set_use_preedit ()
gtk_im_context_simple_add_table, gtk_im_context_simple_add_table ()
gtk_im_context_simple_new, gtk_im_context_simple_new ()
gtk_im_multicontext_append_menuitems, gtk_im_multicontext_append_menuitems ()
gtk_im_multicontext_new, gtk_im_multicontext_new ()
gtk_init, gtk_init ()
gtk_init_add, gtk_init_add ()
gtk_init_check, gtk_init_check ()
gtk_init_with_args, gtk_init_with_args ()
gtk_input_add_full, gtk_input_add_full ()
gtk_input_dialog_new, gtk_input_dialog_new ()
GTK_INPUT_ERROR, GTK_INPUT_ERROR
gtk_input_remove, gtk_input_remove ()
gtk_interface_age, gtk_interface_age
GTK_INTERFACE_AGE, GTK_INTERFACE_AGE
gtk_invisible_get_screen, gtk_invisible_get_screen ()
gtk_invisible_new, gtk_invisible_new ()
gtk_invisible_new_for_screen, gtk_invisible_new_for_screen ()
gtk_invisible_set_screen, gtk_invisible_set_screen ()
GTK_IS_RESIZE_CONTAINER, GTK_IS_RESIZE_CONTAINER()
GTK_IS_ROOT_TREE, GTK_IS_ROOT_TREE()
gtk_item_deselect, gtk_item_deselect ()
gtk_item_factories_path_delete, gtk_item_factories_path_delete ()
gtk_item_factory_add_foreign, gtk_item_factory_add_foreign ()
gtk_item_factory_construct, gtk_item_factory_construct ()
gtk_item_factory_create_item, gtk_item_factory_create_item ()
gtk_item_factory_create_items, gtk_item_factory_create_items ()
gtk_item_factory_create_items_ac, gtk_item_factory_create_items_ac ()
gtk_item_factory_create_menu_entries, gtk_item_factory_create_menu_entries ()
gtk_item_factory_delete_entries, gtk_item_factory_delete_entries ()
gtk_item_factory_delete_entry, gtk_item_factory_delete_entry ()
gtk_item_factory_delete_item, gtk_item_factory_delete_item ()
gtk_item_factory_from_path, gtk_item_factory_from_path ()
gtk_item_factory_from_widget, gtk_item_factory_from_widget ()
gtk_item_factory_get_item, gtk_item_factory_get_item ()
gtk_item_factory_get_item_by_action, gtk_item_factory_get_item_by_action ()
gtk_item_factory_get_widget, gtk_item_factory_get_widget ()
gtk_item_factory_get_widget_by_action, gtk_item_factory_get_widget_by_action ()
gtk_item_factory_new, gtk_item_factory_new ()
gtk_item_factory_path_from_widget, gtk_item_factory_path_from_widget ()
gtk_item_factory_popup, gtk_item_factory_popup ()
gtk_item_factory_popup_data, gtk_item_factory_popup_data ()
gtk_item_factory_popup_data_from_widget, gtk_item_factory_popup_data_from_widget ()
gtk_item_factory_popup_with_data, gtk_item_factory_popup_with_data ()
gtk_item_factory_set_translate_func, gtk_item_factory_set_translate_func ()
gtk_item_select, gtk_item_select ()
gtk_item_toggle, gtk_item_toggle ()
gtk_key_snooper_install, gtk_key_snooper_install ()
gtk_key_snooper_remove, gtk_key_snooper_remove ()
gtk_label_get, gtk_label_get ()
gtk_label_get_angle, gtk_label_get_angle ()
gtk_label_get_attributes, gtk_label_get_attributes ()
gtk_label_get_ellipsize, gtk_label_get_ellipsize ()
gtk_label_get_justify, gtk_label_get_justify ()
gtk_label_get_label, gtk_label_get_label ()
gtk_label_get_layout, gtk_label_get_layout ()
gtk_label_get_layout_offsets, gtk_label_get_layout_offsets ()
gtk_label_get_line_wrap, gtk_label_get_line_wrap ()
gtk_label_get_line_wrap_mode, gtk_label_get_line_wrap_mode ()
gtk_label_get_max_width_chars, gtk_label_get_max_width_chars ()
gtk_label_get_mnemonic_keyval, gtk_label_get_mnemonic_keyval ()
gtk_label_get_mnemonic_widget, gtk_label_get_mnemonic_widget ()
gtk_label_get_selectable, gtk_label_get_selectable ()
gtk_label_get_selection_bounds, gtk_label_get_selection_bounds ()
gtk_label_get_single_line_mode, gtk_label_get_single_line_mode ()
gtk_label_get_text, gtk_label_get_text ()
gtk_label_get_use_markup, gtk_label_get_use_markup ()
gtk_label_get_use_underline, gtk_label_get_use_underline ()
gtk_label_get_width_chars, gtk_label_get_width_chars ()
gtk_label_new, gtk_label_new ()
gtk_label_new_with_mnemonic, gtk_label_new_with_mnemonic ()
gtk_label_parse_uline, gtk_label_parse_uline ()
gtk_label_select_region, gtk_label_select_region ()
gtk_label_set, gtk_label_set
gtk_label_set_angle, gtk_label_set_angle ()
gtk_label_set_attributes, gtk_label_set_attributes ()
gtk_label_set_ellipsize, gtk_label_set_ellipsize ()
gtk_label_set_justify, gtk_label_set_justify ()
gtk_label_set_label, gtk_label_set_label ()
gtk_label_set_line_wrap, gtk_label_set_line_wrap ()
gtk_label_set_line_wrap_mode, gtk_label_set_line_wrap_mode ()
gtk_label_set_markup, gtk_label_set_markup ()
gtk_label_set_markup_with_mnemonic, gtk_label_set_markup_with_mnemonic ()
gtk_label_set_max_width_chars, gtk_label_set_max_width_chars ()
gtk_label_set_mnemonic_widget, gtk_label_set_mnemonic_widget ()
gtk_label_set_pattern, gtk_label_set_pattern ()
gtk_label_set_selectable, gtk_label_set_selectable ()
gtk_label_set_single_line_mode, gtk_label_set_single_line_mode ()
gtk_label_set_text, gtk_label_set_text ()
gtk_label_set_text_with_mnemonic, gtk_label_set_text_with_mnemonic ()
gtk_label_set_use_markup, gtk_label_set_use_markup ()
gtk_label_set_use_underline, gtk_label_set_use_underline ()
gtk_label_set_width_chars, gtk_label_set_width_chars ()
gtk_layout_freeze, gtk_layout_freeze ()
gtk_layout_get_hadjustment, gtk_layout_get_hadjustment ()
gtk_layout_get_size, gtk_layout_get_size ()
gtk_layout_get_vadjustment, gtk_layout_get_vadjustment ()
gtk_layout_move, gtk_layout_move ()
gtk_layout_new, gtk_layout_new ()
gtk_layout_put, gtk_layout_put ()
gtk_layout_set_hadjustment, gtk_layout_set_hadjustment ()
gtk_layout_set_size, gtk_layout_set_size ()
gtk_layout_set_vadjustment, gtk_layout_set_vadjustment ()
gtk_layout_thaw, gtk_layout_thaw ()
gtk_link_button_get_uri, gtk_link_button_get_uri ()
gtk_link_button_new, gtk_link_button_new ()
gtk_link_button_new_with_label, gtk_link_button_new_with_label ()
gtk_link_button_set_uri, gtk_link_button_set_uri ()
gtk_link_button_set_uri_hook, gtk_link_button_set_uri_hook ()
gtk_list_append_items, gtk_list_append_items ()
gtk_list_child_position, gtk_list_child_position ()
gtk_list_clear_items, gtk_list_clear_items ()
gtk_list_end_drag_selection, gtk_list_end_drag_selection ()
gtk_list_end_selection, gtk_list_end_selection ()
gtk_list_extend_selection, gtk_list_extend_selection ()
gtk_list_insert_items, gtk_list_insert_items ()
gtk_list_item_deselect, gtk_list_item_deselect ()
gtk_list_item_new, gtk_list_item_new ()
gtk_list_item_new_with_label, gtk_list_item_new_with_label ()
gtk_list_item_select, gtk_list_item_select ()
gtk_list_new, gtk_list_new ()
gtk_list_prepend_items, gtk_list_prepend_items ()
gtk_list_remove_items, gtk_list_remove_items ()
gtk_list_remove_items_no_unref, gtk_list_remove_items_no_unref ()
gtk_list_scroll_horizontal, gtk_list_scroll_horizontal ()
gtk_list_scroll_vertical, gtk_list_scroll_vertical ()
gtk_list_select_all, gtk_list_select_all ()
gtk_list_select_child, gtk_list_select_child ()
gtk_list_select_item, gtk_list_select_item ()
gtk_list_set_selection_mode, gtk_list_set_selection_mode ()
gtk_list_start_selection, gtk_list_start_selection ()
gtk_list_store_append, gtk_list_store_append ()
gtk_list_store_clear, gtk_list_store_clear ()
gtk_list_store_insert, gtk_list_store_insert ()
gtk_list_store_insert_after, gtk_list_store_insert_after ()
gtk_list_store_insert_before, gtk_list_store_insert_before ()
gtk_list_store_insert_with_values, gtk_list_store_insert_with_values ()
gtk_list_store_insert_with_valuesv, gtk_list_store_insert_with_valuesv ()
gtk_list_store_iter_is_valid, gtk_list_store_iter_is_valid ()
gtk_list_store_move_after, gtk_list_store_move_after ()
gtk_list_store_move_before, gtk_list_store_move_before ()
gtk_list_store_new, gtk_list_store_new ()
gtk_list_store_newv, gtk_list_store_newv ()
gtk_list_store_prepend, gtk_list_store_prepend ()
gtk_list_store_remove, gtk_list_store_remove ()
gtk_list_store_reorder, gtk_list_store_reorder ()
gtk_list_store_set, gtk_list_store_set ()
gtk_list_store_set_column_types, gtk_list_store_set_column_types ()
gtk_list_store_set_valist, gtk_list_store_set_valist ()
gtk_list_store_set_value, gtk_list_store_set_value ()
gtk_list_store_swap, gtk_list_store_swap ()
gtk_list_toggle_add_mode, gtk_list_toggle_add_mode ()
gtk_list_toggle_focus_row, gtk_list_toggle_focus_row ()
gtk_list_toggle_row, gtk_list_toggle_row ()
gtk_list_undo_selection, gtk_list_undo_selection ()
gtk_list_unselect_all, gtk_list_unselect_all ()
gtk_list_unselect_child, gtk_list_unselect_child ()
gtk_list_unselect_item, gtk_list_unselect_item ()
gtk_main, gtk_main ()
gtk_main_do_event, gtk_main_do_event ()
gtk_main_iteration, gtk_main_iteration ()
gtk_main_iteration_do, gtk_main_iteration_do ()
gtk_main_level, gtk_main_level ()
gtk_main_quit, gtk_main_quit ()
gtk_major_version, gtk_major_version
GTK_MAJOR_VERSION, GTK_MAJOR_VERSION
GTK_MAX_COMPOSE_LEN, GTK_MAX_COMPOSE_LEN
gtk_menu_append, gtk_menu_append()
gtk_menu_attach, gtk_menu_attach ()
gtk_menu_attach_to_widget, gtk_menu_attach_to_widget ()
gtk_menu_bar_append, gtk_menu_bar_append()
gtk_menu_bar_get_child_pack_direction, gtk_menu_bar_get_child_pack_direction ()
gtk_menu_bar_get_pack_direction, gtk_menu_bar_get_pack_direction ()
gtk_menu_bar_insert, gtk_menu_bar_insert()
gtk_menu_bar_new, gtk_menu_bar_new ()
gtk_menu_bar_prepend, gtk_menu_bar_prepend()
gtk_menu_bar_set_child_pack_direction, gtk_menu_bar_set_child_pack_direction ()
gtk_menu_bar_set_pack_direction, gtk_menu_bar_set_pack_direction ()
gtk_menu_detach, gtk_menu_detach ()
gtk_menu_get_accel_group, gtk_menu_get_accel_group ()
gtk_menu_get_active, gtk_menu_get_active ()
gtk_menu_get_attach_widget, gtk_menu_get_attach_widget ()
gtk_menu_get_for_attach_widget, gtk_menu_get_for_attach_widget ()
gtk_menu_get_tearoff_state, gtk_menu_get_tearoff_state ()
gtk_menu_get_title, gtk_menu_get_title ()
gtk_menu_insert, gtk_menu_insert()
gtk_menu_item_activate, gtk_menu_item_activate ()
gtk_menu_item_deselect, gtk_menu_item_deselect ()
gtk_menu_item_get_right_justified, gtk_menu_item_get_right_justified ()
gtk_menu_item_get_submenu, gtk_menu_item_get_submenu ()
gtk_menu_item_new, gtk_menu_item_new ()
gtk_menu_item_new_with_label, gtk_menu_item_new_with_label ()
gtk_menu_item_new_with_mnemonic, gtk_menu_item_new_with_mnemonic ()
gtk_menu_item_remove_submenu, gtk_menu_item_remove_submenu ()
gtk_menu_item_right_justify, gtk_menu_item_right_justify()
gtk_menu_item_select, gtk_menu_item_select ()
gtk_menu_item_set_accel_path, gtk_menu_item_set_accel_path ()
gtk_menu_item_set_right_justified, gtk_menu_item_set_right_justified ()
gtk_menu_item_set_submenu, gtk_menu_item_set_submenu ()
gtk_menu_item_toggle_size_allocate, gtk_menu_item_toggle_size_allocate ()
gtk_menu_item_toggle_size_request, gtk_menu_item_toggle_size_request ()
gtk_menu_new, gtk_menu_new ()
gtk_menu_popdown, gtk_menu_popdown ()
gtk_menu_popup, gtk_menu_popup ()
gtk_menu_prepend, gtk_menu_prepend()
gtk_menu_reorder_child, gtk_menu_reorder_child ()
gtk_menu_reposition, gtk_menu_reposition ()
gtk_menu_set_accel_group, gtk_menu_set_accel_group ()
gtk_menu_set_accel_path, gtk_menu_set_accel_path ()
gtk_menu_set_active, gtk_menu_set_active ()
gtk_menu_set_monitor, gtk_menu_set_monitor ()
gtk_menu_set_screen, gtk_menu_set_screen ()
gtk_menu_set_tearoff_state, gtk_menu_set_tearoff_state ()
gtk_menu_set_title, gtk_menu_set_title ()
gtk_menu_shell_activate_item, gtk_menu_shell_activate_item ()
gtk_menu_shell_append, gtk_menu_shell_append ()
gtk_menu_shell_cancel, gtk_menu_shell_cancel ()
gtk_menu_shell_deactivate, gtk_menu_shell_deactivate ()
gtk_menu_shell_deselect, gtk_menu_shell_deselect ()
gtk_menu_shell_get_take_focus, gtk_menu_shell_get_take_focus ()
gtk_menu_shell_insert, gtk_menu_shell_insert ()
gtk_menu_shell_prepend, gtk_menu_shell_prepend ()
gtk_menu_shell_select_first, gtk_menu_shell_select_first ()
gtk_menu_shell_select_item, gtk_menu_shell_select_item ()
gtk_menu_shell_set_take_focus, gtk_menu_shell_set_take_focus ()
gtk_menu_tool_button_get_menu, gtk_menu_tool_button_get_menu ()
gtk_menu_tool_button_new, gtk_menu_tool_button_new ()
gtk_menu_tool_button_new_from_stock, gtk_menu_tool_button_new_from_stock ()
gtk_menu_tool_button_set_arrow_tooltip, gtk_menu_tool_button_set_arrow_tooltip ()
gtk_menu_tool_button_set_menu, gtk_menu_tool_button_set_menu ()
gtk_message_dialog_format_secondary_markup, gtk_message_dialog_format_secondary_markup ()
gtk_message_dialog_format_secondary_text, gtk_message_dialog_format_secondary_text ()
gtk_message_dialog_new, gtk_message_dialog_new ()
gtk_message_dialog_new_with_markup, gtk_message_dialog_new_with_markup ()
gtk_message_dialog_set_image, gtk_message_dialog_set_image ()
gtk_message_dialog_set_markup, gtk_message_dialog_set_markup ()
gtk_micro_version, gtk_micro_version
GTK_MICRO_VERSION, GTK_MICRO_VERSION
gtk_minor_version, gtk_minor_version
GTK_MINOR_VERSION, GTK_MINOR_VERSION
gtk_misc_get_alignment, gtk_misc_get_alignment ()
gtk_misc_get_padding, gtk_misc_get_padding ()
gtk_misc_set_alignment, gtk_misc_set_alignment ()
gtk_misc_set_padding, gtk_misc_set_padding ()
gtk_notebook_append_page, gtk_notebook_append_page ()
gtk_notebook_append_page_menu, gtk_notebook_append_page_menu ()
gtk_notebook_current_page, gtk_notebook_current_page
gtk_notebook_get_current_page, gtk_notebook_get_current_page ()
gtk_notebook_get_group_id, gtk_notebook_get_group_id ()
gtk_notebook_get_menu_label, gtk_notebook_get_menu_label ()
gtk_notebook_get_menu_label_text, gtk_notebook_get_menu_label_text ()
gtk_notebook_get_nth_page, gtk_notebook_get_nth_page ()
gtk_notebook_get_n_pages, gtk_notebook_get_n_pages ()
gtk_notebook_get_scrollable, gtk_notebook_get_scrollable ()
gtk_notebook_get_show_border, gtk_notebook_get_show_border ()
gtk_notebook_get_show_tabs, gtk_notebook_get_show_tabs ()
gtk_notebook_get_tab_detachable, gtk_notebook_get_tab_detachable ()
gtk_notebook_get_tab_label, gtk_notebook_get_tab_label ()
gtk_notebook_get_tab_label_text, gtk_notebook_get_tab_label_text ()
gtk_notebook_get_tab_pos, gtk_notebook_get_tab_pos ()
gtk_notebook_get_tab_reorderable, gtk_notebook_get_tab_reorderable ()
gtk_notebook_insert_page, gtk_notebook_insert_page ()
gtk_notebook_insert_page_menu, gtk_notebook_insert_page_menu ()
gtk_notebook_new, gtk_notebook_new ()
gtk_notebook_next_page, gtk_notebook_next_page ()
gtk_notebook_page_num, gtk_notebook_page_num ()
gtk_notebook_popup_disable, gtk_notebook_popup_disable ()
gtk_notebook_popup_enable, gtk_notebook_popup_enable ()
gtk_notebook_prepend_page, gtk_notebook_prepend_page ()
gtk_notebook_prepend_page_menu, gtk_notebook_prepend_page_menu ()
gtk_notebook_prev_page, gtk_notebook_prev_page ()
gtk_notebook_query_tab_label_packing, gtk_notebook_query_tab_label_packing ()
gtk_notebook_remove_page, gtk_notebook_remove_page ()
gtk_notebook_reorder_child, gtk_notebook_reorder_child ()
gtk_notebook_set_current_page, gtk_notebook_set_current_page ()
gtk_notebook_set_group_id, gtk_notebook_set_group_id ()
gtk_notebook_set_homogeneous_tabs, gtk_notebook_set_homogeneous_tabs ()
gtk_notebook_set_menu_label, gtk_notebook_set_menu_label ()
gtk_notebook_set_menu_label_text, gtk_notebook_set_menu_label_text ()
gtk_notebook_set_page, gtk_notebook_set_page
gtk_notebook_set_scrollable, gtk_notebook_set_scrollable ()
gtk_notebook_set_show_border, gtk_notebook_set_show_border ()
gtk_notebook_set_show_tabs, gtk_notebook_set_show_tabs ()
gtk_notebook_set_tab_border, gtk_notebook_set_tab_border ()
gtk_notebook_set_tab_detachable, gtk_notebook_set_tab_detachable ()
gtk_notebook_set_tab_hborder, gtk_notebook_set_tab_hborder ()
gtk_notebook_set_tab_label, gtk_notebook_set_tab_label ()
gtk_notebook_set_tab_label_packing, gtk_notebook_set_tab_label_packing ()
gtk_notebook_set_tab_label_text, gtk_notebook_set_tab_label_text ()
gtk_notebook_set_tab_pos, gtk_notebook_set_tab_pos ()
gtk_notebook_set_tab_reorderable, gtk_notebook_set_tab_reorderable ()
gtk_notebook_set_tab_vborder, gtk_notebook_set_tab_vborder ()
gtk_notebook_set_window_creation_hook, gtk_notebook_set_window_creation_hook ()
gtk_object_add_arg_type, gtk_object_add_arg_type ()
gtk_object_data_force_id, gtk_object_data_force_id
gtk_object_data_try_key, gtk_object_data_try_key
gtk_object_destroy, gtk_object_destroy ()
GTK_OBJECT_FLAGS, GTK_OBJECT_FLAGS()
GTK_OBJECT_FLOATING, GTK_OBJECT_FLOATING()
gtk_object_get, gtk_object_get ()
gtk_object_get_data, gtk_object_get_data ()
gtk_object_get_data_by_id, gtk_object_get_data_by_id ()
gtk_object_get_user_data, gtk_object_get_user_data ()
gtk_object_new, gtk_object_new ()
gtk_object_ref, gtk_object_ref ()
gtk_object_remove_data, gtk_object_remove_data ()
gtk_object_remove_data_by_id, gtk_object_remove_data_by_id ()
gtk_object_remove_no_notify, gtk_object_remove_no_notify ()
gtk_object_remove_no_notify_by_id, gtk_object_remove_no_notify_by_id ()
gtk_object_set, gtk_object_set ()
gtk_object_set_data, gtk_object_set_data ()
gtk_object_set_data_by_id, gtk_object_set_data_by_id ()
gtk_object_set_data_by_id_full, gtk_object_set_data_by_id_full ()
gtk_object_set_data_full, gtk_object_set_data_full ()
gtk_object_set_user_data, gtk_object_set_user_data ()
gtk_object_sink, gtk_object_sink ()
GTK_OBJECT_TYPE, GTK_OBJECT_TYPE()
GTK_OBJECT_TYPE_NAME, GTK_OBJECT_TYPE_NAME()
gtk_object_unref, gtk_object_unref ()
gtk_object_weakref, gtk_object_weakref ()
gtk_object_weakunref, gtk_object_weakunref ()
gtk_old_editable_changed, gtk_old_editable_changed ()
gtk_old_editable_claim_selection, gtk_old_editable_claim_selection ()
gtk_option_menu_get_history, gtk_option_menu_get_history ()
gtk_option_menu_get_menu, gtk_option_menu_get_menu ()
gtk_option_menu_new, gtk_option_menu_new ()
gtk_option_menu_remove_menu, gtk_option_menu_remove_menu ()
gtk_option_menu_set_history, gtk_option_menu_set_history ()
gtk_option_menu_set_menu, gtk_option_menu_set_menu ()
gtk_page_setup_copy, gtk_page_setup_copy ()
gtk_page_setup_get_bottom_margin, gtk_page_setup_get_bottom_margin ()
gtk_page_setup_get_left_margin, gtk_page_setup_get_left_margin ()
gtk_page_setup_get_orientation, gtk_page_setup_get_orientation ()
gtk_page_setup_get_page_height, gtk_page_setup_get_page_height ()
gtk_page_setup_get_page_width, gtk_page_setup_get_page_width ()
gtk_page_setup_get_paper_height, gtk_page_setup_get_paper_height ()
gtk_page_setup_get_paper_size, gtk_page_setup_get_paper_size ()
gtk_page_setup_get_paper_width, gtk_page_setup_get_paper_width ()
gtk_page_setup_get_right_margin, gtk_page_setup_get_right_margin ()
gtk_page_setup_get_top_margin, gtk_page_setup_get_top_margin ()
gtk_page_setup_new, gtk_page_setup_new ()
gtk_page_setup_set_bottom_margin, gtk_page_setup_set_bottom_margin ()
gtk_page_setup_set_left_margin, gtk_page_setup_set_left_margin ()
gtk_page_setup_set_orientation, gtk_page_setup_set_orientation ()
gtk_page_setup_set_paper_size, gtk_page_setup_set_paper_size ()
gtk_page_setup_set_paper_size_and_default_margins, gtk_page_setup_set_paper_size_and_default_margins ()
gtk_page_setup_set_right_margin, gtk_page_setup_set_right_margin ()
gtk_page_setup_set_top_margin, gtk_page_setup_set_top_margin ()
gtk_page_setup_unix_dialog_get_page_setup, gtk_page_setup_unix_dialog_get_page_setup ()
gtk_page_setup_unix_dialog_get_print_settings, gtk_page_setup_unix_dialog_get_print_settings ()
gtk_page_setup_unix_dialog_new, gtk_page_setup_unix_dialog_new ()
gtk_page_setup_unix_dialog_set_page_setup, gtk_page_setup_unix_dialog_set_page_setup ()
gtk_page_setup_unix_dialog_set_print_settings, gtk_page_setup_unix_dialog_set_print_settings ()
gtk_paint_arrow, gtk_paint_arrow ()
gtk_paint_box, gtk_paint_box ()
gtk_paint_box_gap, gtk_paint_box_gap ()
gtk_paint_check, gtk_paint_check ()
gtk_paint_diamond, gtk_paint_diamond ()
gtk_paint_expander, gtk_paint_expander ()
gtk_paint_extension, gtk_paint_extension ()
gtk_paint_flat_box, gtk_paint_flat_box ()
gtk_paint_focus, gtk_paint_focus ()
gtk_paint_handle, gtk_paint_handle ()
gtk_paint_hline, gtk_paint_hline ()
gtk_paint_layout, gtk_paint_layout ()
gtk_paint_option, gtk_paint_option ()
gtk_paint_polygon, gtk_paint_polygon ()
gtk_paint_resize_grip, gtk_paint_resize_grip ()
gtk_paint_shadow, gtk_paint_shadow ()
gtk_paint_shadow_gap, gtk_paint_shadow_gap ()
gtk_paint_slider, gtk_paint_slider ()
gtk_paint_string, gtk_paint_string ()
gtk_paint_tab, gtk_paint_tab ()
gtk_paint_vline, gtk_paint_vline ()
gtk_paned_add1, gtk_paned_add1 ()
gtk_paned_add2, gtk_paned_add2 ()
gtk_paned_get_child1, gtk_paned_get_child1 ()
gtk_paned_get_child2, gtk_paned_get_child2 ()
gtk_paned_get_position, gtk_paned_get_position ()
gtk_paned_gutter_size, gtk_paned_gutter_size()
gtk_paned_pack1, gtk_paned_pack1 ()
gtk_paned_pack2, gtk_paned_pack2 ()
gtk_paned_set_gutter_size, gtk_paned_set_gutter_size()
gtk_paned_set_position, gtk_paned_set_position ()
GTK_PAPER_NAME_A3, GTK_PAPER_NAME_A3
GTK_PAPER_NAME_A4, GTK_PAPER_NAME_A4
GTK_PAPER_NAME_A5, GTK_PAPER_NAME_A5
GTK_PAPER_NAME_B5, GTK_PAPER_NAME_B5
GTK_PAPER_NAME_EXECUTIVE, GTK_PAPER_NAME_EXECUTIVE
GTK_PAPER_NAME_LEGAL, GTK_PAPER_NAME_LEGAL
GTK_PAPER_NAME_LETTER, GTK_PAPER_NAME_LETTER
gtk_paper_size_copy, gtk_paper_size_copy ()
gtk_paper_size_free, gtk_paper_size_free ()
gtk_paper_size_get_default, gtk_paper_size_get_default ()
gtk_paper_size_get_default_bottom_margin, gtk_paper_size_get_default_bottom_margin ()
gtk_paper_size_get_default_left_margin, gtk_paper_size_get_default_left_margin ()
gtk_paper_size_get_default_right_margin, gtk_paper_size_get_default_right_margin ()
gtk_paper_size_get_default_top_margin, gtk_paper_size_get_default_top_margin ()
gtk_paper_size_get_display_name, gtk_paper_size_get_display_name ()
gtk_paper_size_get_height, gtk_paper_size_get_height ()
gtk_paper_size_get_name, gtk_paper_size_get_name ()
gtk_paper_size_get_ppd_name, gtk_paper_size_get_ppd_name ()
gtk_paper_size_get_width, gtk_paper_size_get_width ()
gtk_paper_size_is_custom, gtk_paper_size_is_custom ()
gtk_paper_size_is_equal, gtk_paper_size_is_equal ()
gtk_paper_size_new, gtk_paper_size_new ()
gtk_paper_size_new_custom, gtk_paper_size_new_custom ()
gtk_paper_size_new_from_ppd, gtk_paper_size_new_from_ppd ()
gtk_paper_size_set_size, gtk_paper_size_set_size ()
gtk_parse_args, gtk_parse_args ()
gtk_pixmap_get, gtk_pixmap_get ()
gtk_pixmap_new, gtk_pixmap_new ()
gtk_pixmap_set, gtk_pixmap_set ()
gtk_pixmap_set_build_insensitive, gtk_pixmap_set_build_insensitive ()
gtk_plug_construct, gtk_plug_construct ()
gtk_plug_construct_for_display, gtk_plug_construct_for_display ()
gtk_plug_get_id, gtk_plug_get_id ()
gtk_plug_new, gtk_plug_new ()
gtk_plug_new_for_display, gtk_plug_new_for_display ()
gtk_preview_draw_row, gtk_preview_draw_row ()
gtk_preview_get_cmap, gtk_preview_get_cmap ()
gtk_preview_get_info, gtk_preview_get_info ()
gtk_preview_get_visual, gtk_preview_get_visual ()
gtk_preview_new, gtk_preview_new ()
gtk_preview_put, gtk_preview_put ()
gtk_preview_reset, gtk_preview_reset ()
gtk_preview_set_color_cube, gtk_preview_set_color_cube ()
gtk_preview_set_dither, gtk_preview_set_dither ()
gtk_preview_set_expand, gtk_preview_set_expand ()
gtk_preview_set_gamma, gtk_preview_set_gamma ()
gtk_preview_set_install_cmap, gtk_preview_set_install_cmap ()
gtk_preview_set_reserved, gtk_preview_set_reserved ()
gtk_preview_size, gtk_preview_size ()
gtk_preview_uninit, gtk_preview_uninit ()
gtk_printer_accepts_pdf, gtk_printer_accepts_pdf ()
gtk_printer_accepts_ps, gtk_printer_accepts_ps ()
gtk_printer_compare, gtk_printer_compare ()
gtk_printer_get_backend, gtk_printer_get_backend ()
gtk_printer_get_description, gtk_printer_get_description ()
gtk_printer_get_icon_name, gtk_printer_get_icon_name ()
gtk_printer_get_job_count, gtk_printer_get_job_count ()
gtk_printer_get_location, gtk_printer_get_location ()
gtk_printer_get_name, gtk_printer_get_name ()
gtk_printer_get_state_message, gtk_printer_get_state_message ()
gtk_printer_is_active, gtk_printer_is_active ()
gtk_printer_is_default, gtk_printer_is_default ()
gtk_printer_is_virtual, gtk_printer_is_virtual ()
gtk_printer_new, gtk_printer_new ()
gtk_print_context_create_pango_context, gtk_print_context_create_pango_context ()
gtk_print_context_create_pango_layout, gtk_print_context_create_pango_layout ()
gtk_print_context_get_cairo_context, gtk_print_context_get_cairo_context ()
gtk_print_context_get_dpi_x, gtk_print_context_get_dpi_x ()
gtk_print_context_get_dpi_y, gtk_print_context_get_dpi_y ()
gtk_print_context_get_height, gtk_print_context_get_height ()
gtk_print_context_get_page_setup, gtk_print_context_get_page_setup ()
gtk_print_context_get_pango_fontmap, gtk_print_context_get_pango_fontmap ()
gtk_print_context_get_width, gtk_print_context_get_width ()
gtk_print_context_set_cairo_context, gtk_print_context_set_cairo_context ()
GTK_PRINT_ERROR, GTK_PRINT_ERROR
gtk_print_job_get_printer, gtk_print_job_get_printer ()
gtk_print_job_get_settings, gtk_print_job_get_settings ()
gtk_print_job_get_status, gtk_print_job_get_status ()
gtk_print_job_get_surface, gtk_print_job_get_surface ()
gtk_print_job_get_title, gtk_print_job_get_title ()
gtk_print_job_get_track_print_status, gtk_print_job_get_track_print_status ()
gtk_print_job_new, gtk_print_job_new ()
gtk_print_job_send, gtk_print_job_send ()
gtk_print_job_set_source_file, gtk_print_job_set_source_file ()
gtk_print_job_set_track_print_status, gtk_print_job_set_track_print_status ()
gtk_print_operation_cancel, gtk_print_operation_cancel ()
gtk_print_operation_get_default_page_setup, gtk_print_operation_get_default_page_setup ()
gtk_print_operation_get_error, gtk_print_operation_get_error (), gtk_print_operation_get_error ()
gtk_print_operation_get_print_settings, gtk_print_operation_get_print_settings ()
gtk_print_operation_get_status, gtk_print_operation_get_status ()
gtk_print_operation_get_status_string, gtk_print_operation_get_status_string ()
gtk_print_operation_is_finished, gtk_print_operation_is_finished ()
gtk_print_operation_new, gtk_print_operation_new ()
gtk_print_operation_preview_end_preview, gtk_print_operation_preview_end_preview ()
gtk_print_operation_preview_is_selected, gtk_print_operation_preview_is_selected ()
gtk_print_operation_preview_render_page, gtk_print_operation_preview_render_page ()
gtk_print_operation_run, gtk_print_operation_run ()
gtk_print_operation_set_allow_async, gtk_print_operation_set_allow_async ()
gtk_print_operation_set_current_page, gtk_print_operation_set_current_page ()
gtk_print_operation_set_custom_tab_label, gtk_print_operation_set_custom_tab_label ()
gtk_print_operation_set_default_page_setup, gtk_print_operation_set_default_page_setup ()
gtk_print_operation_set_export_filename, gtk_print_operation_set_export_filename ()
gtk_print_operation_set_job_name, gtk_print_operation_set_job_name ()
gtk_print_operation_set_n_pages, gtk_print_operation_set_n_pages ()
gtk_print_operation_set_print_settings, gtk_print_operation_set_print_settings ()
gtk_print_operation_set_show_progress, gtk_print_operation_set_show_progress ()
gtk_print_operation_set_track_print_status, gtk_print_operation_set_track_print_status ()
gtk_print_operation_set_unit, gtk_print_operation_set_unit ()
gtk_print_operation_set_use_full_page, gtk_print_operation_set_use_full_page ()
gtk_print_run_page_setup_dialog, gtk_print_run_page_setup_dialog ()
gtk_print_run_page_setup_dialog_async, gtk_print_run_page_setup_dialog_async ()
GTK_PRINT_SETTINGS_COLLATE, GTK_PRINT_SETTINGS_COLLATE
gtk_print_settings_copy, gtk_print_settings_copy ()
GTK_PRINT_SETTINGS_DEFAULT_SOURCE, GTK_PRINT_SETTINGS_DEFAULT_SOURCE
GTK_PRINT_SETTINGS_DITHER, GTK_PRINT_SETTINGS_DITHER
GTK_PRINT_SETTINGS_DUPLEX, GTK_PRINT_SETTINGS_DUPLEX
GTK_PRINT_SETTINGS_FINISHINGS, GTK_PRINT_SETTINGS_FINISHINGS
gtk_print_settings_foreach, gtk_print_settings_foreach ()
gtk_print_settings_get, gtk_print_settings_get ()
gtk_print_settings_get_bool, gtk_print_settings_get_bool ()
gtk_print_settings_get_collate, gtk_print_settings_get_collate ()
gtk_print_settings_get_default_source, gtk_print_settings_get_default_source ()
gtk_print_settings_get_dither, gtk_print_settings_get_dither ()
gtk_print_settings_get_double, gtk_print_settings_get_double ()
gtk_print_settings_get_double_with_default, gtk_print_settings_get_double_with_default ()
gtk_print_settings_get_duplex, gtk_print_settings_get_duplex ()
gtk_print_settings_get_finishings, gtk_print_settings_get_finishings ()
gtk_print_settings_get_int, gtk_print_settings_get_int ()
gtk_print_settings_get_int_with_default, gtk_print_settings_get_int_with_default ()
gtk_print_settings_get_length, gtk_print_settings_get_length ()
gtk_print_settings_get_media_type, gtk_print_settings_get_media_type ()
gtk_print_settings_get_number_up, gtk_print_settings_get_number_up ()
gtk_print_settings_get_n_copies, gtk_print_settings_get_n_copies ()
gtk_print_settings_get_orientation, gtk_print_settings_get_orientation ()
gtk_print_settings_get_output_bin, gtk_print_settings_get_output_bin ()
gtk_print_settings_get_page_ranges, gtk_print_settings_get_page_ranges ()
gtk_print_settings_get_page_set, gtk_print_settings_get_page_set ()
gtk_print_settings_get_paper_height, gtk_print_settings_get_paper_height ()
gtk_print_settings_get_paper_size, gtk_print_settings_get_paper_size ()
gtk_print_settings_get_paper_width, gtk_print_settings_get_paper_width ()
gtk_print_settings_get_printer, gtk_print_settings_get_printer ()
gtk_print_settings_get_print_pages, gtk_print_settings_get_print_pages ()
gtk_print_settings_get_quality, gtk_print_settings_get_quality ()
gtk_print_settings_get_resolution, gtk_print_settings_get_resolution ()
gtk_print_settings_get_reverse, gtk_print_settings_get_reverse ()
gtk_print_settings_get_scale, gtk_print_settings_get_scale ()
gtk_print_settings_get_use_color, gtk_print_settings_get_use_color ()
gtk_print_settings_has_key, gtk_print_settings_has_key ()
GTK_PRINT_SETTINGS_MEDIA_TYPE, GTK_PRINT_SETTINGS_MEDIA_TYPE
gtk_print_settings_new, gtk_print_settings_new ()
GTK_PRINT_SETTINGS_NUMBER_UP, GTK_PRINT_SETTINGS_NUMBER_UP
GTK_PRINT_SETTINGS_N_COPIES, GTK_PRINT_SETTINGS_N_COPIES
GTK_PRINT_SETTINGS_ORIENTATION, GTK_PRINT_SETTINGS_ORIENTATION
GTK_PRINT_SETTINGS_OUTPUT_BIN, GTK_PRINT_SETTINGS_OUTPUT_BIN
GTK_PRINT_SETTINGS_OUTPUT_FILE_FORMAT, GTK_PRINT_SETTINGS_OUTPUT_FILE_FORMAT
GTK_PRINT_SETTINGS_OUTPUT_URI, GTK_PRINT_SETTINGS_OUTPUT_URI
GTK_PRINT_SETTINGS_PAGE_RANGES, GTK_PRINT_SETTINGS_PAGE_RANGES
GTK_PRINT_SETTINGS_PAGE_SET, GTK_PRINT_SETTINGS_PAGE_SET
GTK_PRINT_SETTINGS_PAPER_FORMAT, GTK_PRINT_SETTINGS_PAPER_FORMAT
GTK_PRINT_SETTINGS_PAPER_HEIGHT, GTK_PRINT_SETTINGS_PAPER_HEIGHT
GTK_PRINT_SETTINGS_PAPER_WIDTH, GTK_PRINT_SETTINGS_PAPER_WIDTH
GTK_PRINT_SETTINGS_PRINTER, GTK_PRINT_SETTINGS_PRINTER
GTK_PRINT_SETTINGS_PRINT_PAGES, GTK_PRINT_SETTINGS_PRINT_PAGES
GTK_PRINT_SETTINGS_QUALITY, GTK_PRINT_SETTINGS_QUALITY
GTK_PRINT_SETTINGS_RESOLUTION, GTK_PRINT_SETTINGS_RESOLUTION
GTK_PRINT_SETTINGS_REVERSE, GTK_PRINT_SETTINGS_REVERSE
GTK_PRINT_SETTINGS_SCALE, GTK_PRINT_SETTINGS_SCALE
gtk_print_settings_set, gtk_print_settings_set ()
gtk_print_settings_set_bool, gtk_print_settings_set_bool ()
gtk_print_settings_set_collate, gtk_print_settings_set_collate ()
gtk_print_settings_set_default_source, gtk_print_settings_set_default_source ()
gtk_print_settings_set_dither, gtk_print_settings_set_dither ()
gtk_print_settings_set_double, gtk_print_settings_set_double ()
gtk_print_settings_set_duplex, gtk_print_settings_set_duplex ()
gtk_print_settings_set_finishings, gtk_print_settings_set_finishings ()
gtk_print_settings_set_int, gtk_print_settings_set_int ()
gtk_print_settings_set_length, gtk_print_settings_set_length ()
gtk_print_settings_set_media_type, gtk_print_settings_set_media_type ()
gtk_print_settings_set_number_up, gtk_print_settings_set_number_up ()
gtk_print_settings_set_n_copies, gtk_print_settings_set_n_copies ()
gtk_print_settings_set_orientation, gtk_print_settings_set_orientation ()
gtk_print_settings_set_output_bin, gtk_print_settings_set_output_bin ()
gtk_print_settings_set_page_ranges, gtk_print_settings_set_page_ranges ()
gtk_print_settings_set_page_set, gtk_print_settings_set_page_set ()
gtk_print_settings_set_paper_height, gtk_print_settings_set_paper_height ()
gtk_print_settings_set_paper_size, gtk_print_settings_set_paper_size ()
gtk_print_settings_set_paper_width, gtk_print_settings_set_paper_width ()
gtk_print_settings_set_printer, gtk_print_settings_set_printer ()
gtk_print_settings_set_print_pages, gtk_print_settings_set_print_pages ()
gtk_print_settings_set_quality, gtk_print_settings_set_quality ()
gtk_print_settings_set_resolution, gtk_print_settings_set_resolution ()
gtk_print_settings_set_reverse, gtk_print_settings_set_reverse ()
gtk_print_settings_set_scale, gtk_print_settings_set_scale ()
gtk_print_settings_set_use_color, gtk_print_settings_set_use_color ()
gtk_print_settings_unset, gtk_print_settings_unset ()
GTK_PRINT_SETTINGS_USE_COLOR, GTK_PRINT_SETTINGS_USE_COLOR
GTK_PRINT_SETTINGS_WIN32_DRIVER_EXTRA, GTK_PRINT_SETTINGS_WIN32_DRIVER_EXTRA
GTK_PRINT_SETTINGS_WIN32_DRIVER_VERSION, GTK_PRINT_SETTINGS_WIN32_DRIVER_VERSION
gtk_print_unix_dialog_add_custom_tab, gtk_print_unix_dialog_add_custom_tab ()
gtk_print_unix_dialog_get_current_page, gtk_print_unix_dialog_get_current_page ()
gtk_print_unix_dialog_get_page_setup, gtk_print_unix_dialog_get_page_setup ()
gtk_print_unix_dialog_get_selected_printer, gtk_print_unix_dialog_get_selected_printer ()
gtk_print_unix_dialog_get_settings, gtk_print_unix_dialog_get_settings ()
gtk_print_unix_dialog_new, gtk_print_unix_dialog_new ()
gtk_print_unix_dialog_set_current_page, gtk_print_unix_dialog_set_current_page ()
gtk_print_unix_dialog_set_manual_capabilities, gtk_print_unix_dialog_set_manual_capabilities ()
gtk_print_unix_dialog_set_page_setup, gtk_print_unix_dialog_set_page_setup ()
gtk_print_unix_dialog_set_settings, gtk_print_unix_dialog_set_settings ()
GTK_PRIORITY_DEFAULT, GTK_PRIORITY_DEFAULT
GTK_PRIORITY_HIGH, GTK_PRIORITY_HIGH
GTK_PRIORITY_INTERNAL, GTK_PRIORITY_INTERNAL
GTK_PRIORITY_LOW, GTK_PRIORITY_LOW
GTK_PRIORITY_REDRAW, GTK_PRIORITY_REDRAW
GTK_PRIORITY_RESIZE, GTK_PRIORITY_RESIZE
gtk_progress_bar_get_ellipsize, gtk_progress_bar_get_ellipsize ()
gtk_progress_bar_get_fraction, gtk_progress_bar_get_fraction ()
gtk_progress_bar_get_orientation, gtk_progress_bar_get_orientation ()
gtk_progress_bar_get_pulse_step, gtk_progress_bar_get_pulse_step ()
gtk_progress_bar_get_text, gtk_progress_bar_get_text ()
gtk_progress_bar_new, gtk_progress_bar_new ()
gtk_progress_bar_new_with_adjustment, gtk_progress_bar_new_with_adjustment ()
gtk_progress_bar_pulse, gtk_progress_bar_pulse ()
gtk_progress_bar_set_activity_blocks, gtk_progress_bar_set_activity_blocks ()
gtk_progress_bar_set_activity_step, gtk_progress_bar_set_activity_step ()
gtk_progress_bar_set_bar_style, gtk_progress_bar_set_bar_style ()
gtk_progress_bar_set_discrete_blocks, gtk_progress_bar_set_discrete_blocks ()
gtk_progress_bar_set_ellipsize, gtk_progress_bar_set_ellipsize ()
gtk_progress_bar_set_fraction, gtk_progress_bar_set_fraction ()
gtk_progress_bar_set_orientation, gtk_progress_bar_set_orientation ()
gtk_progress_bar_set_pulse_step, gtk_progress_bar_set_pulse_step ()
gtk_progress_bar_set_text, gtk_progress_bar_set_text ()
gtk_progress_bar_update, gtk_progress_bar_update ()
gtk_progress_configure, gtk_progress_configure ()
gtk_progress_get_current_percentage, gtk_progress_get_current_percentage ()
gtk_progress_get_current_text, gtk_progress_get_current_text ()
gtk_progress_get_percentage_from_value, gtk_progress_get_percentage_from_value ()
gtk_progress_get_text_from_value, gtk_progress_get_text_from_value ()
gtk_progress_get_value, gtk_progress_get_value ()
gtk_progress_set_activity_mode, gtk_progress_set_activity_mode ()
gtk_progress_set_adjustment, gtk_progress_set_adjustment ()
gtk_progress_set_format_string, gtk_progress_set_format_string ()
gtk_progress_set_percentage, gtk_progress_set_percentage ()
gtk_progress_set_show_text, gtk_progress_set_show_text ()
gtk_progress_set_text_alignment, gtk_progress_set_text_alignment ()
gtk_progress_set_value, gtk_progress_set_value ()
gtk_propagate_event, gtk_propagate_event ()
gtk_quit_add, gtk_quit_add ()
gtk_quit_add_destroy, gtk_quit_add_destroy ()
gtk_quit_add_full, gtk_quit_add_full ()
gtk_quit_remove, gtk_quit_remove ()
gtk_quit_remove_by_data, gtk_quit_remove_by_data ()
gtk_radio_action_get_current_value, gtk_radio_action_get_current_value ()
gtk_radio_action_get_group, gtk_radio_action_get_group ()
gtk_radio_action_new, gtk_radio_action_new ()
gtk_radio_action_set_current_value, gtk_radio_action_set_current_value ()
gtk_radio_action_set_group, gtk_radio_action_set_group ()
gtk_radio_button_get_group, gtk_radio_button_get_group ()
gtk_radio_button_group, gtk_radio_button_group
gtk_radio_button_new, gtk_radio_button_new ()
gtk_radio_button_new_from_widget, gtk_radio_button_new_from_widget ()
gtk_radio_button_new_with_label, gtk_radio_button_new_with_label ()
gtk_radio_button_new_with_label_from_widget, gtk_radio_button_new_with_label_from_widget ()
gtk_radio_button_new_with_mnemonic, gtk_radio_button_new_with_mnemonic ()
gtk_radio_button_new_with_mnemonic_from_widget, gtk_radio_button_new_with_mnemonic_from_widget ()
gtk_radio_button_set_group, gtk_radio_button_set_group ()
gtk_radio_menu_item_get_group, gtk_radio_menu_item_get_group ()
gtk_radio_menu_item_group, gtk_radio_menu_item_group
gtk_radio_menu_item_new, gtk_radio_menu_item_new ()
gtk_radio_menu_item_new_from_widget, gtk_radio_menu_item_new_from_widget ()
gtk_radio_menu_item_new_with_label, gtk_radio_menu_item_new_with_label ()
gtk_radio_menu_item_new_with_label_from_widget, gtk_radio_menu_item_new_with_label_from_widget ()
gtk_radio_menu_item_new_with_mnemonic, gtk_radio_menu_item_new_with_mnemonic ()
gtk_radio_menu_item_new_with_mnemonic_from_widget, gtk_radio_menu_item_new_with_mnemonic_from_widget ()
gtk_radio_menu_item_set_group, gtk_radio_menu_item_set_group ()
gtk_radio_tool_button_get_group, gtk_radio_tool_button_get_group ()
gtk_radio_tool_button_new, gtk_radio_tool_button_new ()
gtk_radio_tool_button_new_from_stock, gtk_radio_tool_button_new_from_stock ()
gtk_radio_tool_button_new_from_widget, gtk_radio_tool_button_new_from_widget ()
gtk_radio_tool_button_new_with_stock_from_widget, gtk_radio_tool_button_new_with_stock_from_widget ()
gtk_radio_tool_button_set_group, gtk_radio_tool_button_set_group ()
gtk_range_get_adjustment, gtk_range_get_adjustment ()
gtk_range_get_inverted, gtk_range_get_inverted ()
gtk_range_get_lower_stepper_sensitivity, gtk_range_get_lower_stepper_sensitivity ()
gtk_range_get_update_policy, gtk_range_get_update_policy ()
gtk_range_get_upper_stepper_sensitivity, gtk_range_get_upper_stepper_sensitivity ()
gtk_range_get_value, gtk_range_get_value ()
gtk_range_set_adjustment, gtk_range_set_adjustment ()
gtk_range_set_increments, gtk_range_set_increments ()
gtk_range_set_inverted, gtk_range_set_inverted ()
gtk_range_set_lower_stepper_sensitivity, gtk_range_set_lower_stepper_sensitivity ()
gtk_range_set_range, gtk_range_set_range ()
gtk_range_set_update_policy, gtk_range_set_update_policy ()
gtk_range_set_upper_stepper_sensitivity, gtk_range_set_upper_stepper_sensitivity ()
gtk_range_set_value, gtk_range_set_value ()
gtk_rc_add_class_style, gtk_rc_add_class_style ()
gtk_rc_add_default_file, gtk_rc_add_default_file ()
gtk_rc_add_widget_class_style, gtk_rc_add_widget_class_style ()
gtk_rc_add_widget_name_style, gtk_rc_add_widget_name_style ()
gtk_rc_find_module_in_path, gtk_rc_find_module_in_path ()
gtk_rc_find_pixmap_in_path, gtk_rc_find_pixmap_in_path ()
gtk_rc_get_default_files, gtk_rc_get_default_files ()
gtk_rc_get_im_module_file, gtk_rc_get_im_module_file ()
gtk_rc_get_im_module_path, gtk_rc_get_im_module_path ()
gtk_rc_get_module_dir, gtk_rc_get_module_dir ()
gtk_rc_get_style, gtk_rc_get_style ()
gtk_rc_get_style_by_paths, gtk_rc_get_style_by_paths ()
gtk_rc_get_theme_dir, gtk_rc_get_theme_dir ()
gtk_rc_parse, gtk_rc_parse ()
gtk_rc_parse_color, gtk_rc_parse_color ()
gtk_rc_parse_priority, gtk_rc_parse_priority ()
gtk_rc_parse_state, gtk_rc_parse_state ()
gtk_rc_parse_string, gtk_rc_parse_string ()
gtk_rc_property_parse_border, gtk_rc_property_parse_border ()
gtk_rc_property_parse_color, gtk_rc_property_parse_color ()
gtk_rc_property_parse_enum, gtk_rc_property_parse_enum ()
gtk_rc_property_parse_flags, gtk_rc_property_parse_flags ()
gtk_rc_property_parse_requisition, gtk_rc_property_parse_requisition ()
gtk_rc_reparse_all, gtk_rc_reparse_all ()
gtk_rc_reparse_all_for_settings, gtk_rc_reparse_all_for_settings ()
gtk_rc_reset_styles, gtk_rc_reset_styles ()
gtk_rc_scanner_new, gtk_rc_scanner_new ()
gtk_rc_set_default_files, gtk_rc_set_default_files ()
gtk_rc_style_copy, gtk_rc_style_copy ()
gtk_rc_style_new, gtk_rc_style_new ()
gtk_rc_style_ref, gtk_rc_style_ref ()
gtk_rc_style_unref, gtk_rc_style_unref ()
gtk_recent_chooser_add_filter, gtk_recent_chooser_add_filter ()
gtk_recent_chooser_dialog_new, gtk_recent_chooser_dialog_new ()
gtk_recent_chooser_dialog_new_for_manager, gtk_recent_chooser_dialog_new_for_manager ()
GTK_RECENT_CHOOSER_ERROR, GTK_RECENT_CHOOSER_ERROR
gtk_recent_chooser_get_current_item, gtk_recent_chooser_get_current_item ()
gtk_recent_chooser_get_current_uri, gtk_recent_chooser_get_current_uri ()
gtk_recent_chooser_get_filter, gtk_recent_chooser_get_filter ()
gtk_recent_chooser_get_items, gtk_recent_chooser_get_items ()
gtk_recent_chooser_get_limit, gtk_recent_chooser_get_limit ()
gtk_recent_chooser_get_local_only, gtk_recent_chooser_get_local_only ()
gtk_recent_chooser_get_select_multiple, gtk_recent_chooser_get_select_multiple ()
gtk_recent_chooser_get_show_icons, gtk_recent_chooser_get_show_icons ()
gtk_recent_chooser_get_show_not_found, gtk_recent_chooser_get_show_not_found ()
gtk_recent_chooser_get_show_numbers, gtk_recent_chooser_get_show_numbers ()
gtk_recent_chooser_get_show_private, gtk_recent_chooser_get_show_private ()
gtk_recent_chooser_get_show_tips, gtk_recent_chooser_get_show_tips ()
gtk_recent_chooser_get_sort_type, gtk_recent_chooser_get_sort_type ()
gtk_recent_chooser_get_uris, gtk_recent_chooser_get_uris ()
gtk_recent_chooser_list_filters, gtk_recent_chooser_list_filters ()
gtk_recent_chooser_menu_get_show_numbers, gtk_recent_chooser_menu_get_show_numbers ()
gtk_recent_chooser_menu_new, gtk_recent_chooser_menu_new ()
gtk_recent_chooser_menu_new_for_manager, gtk_recent_chooser_menu_new_for_manager ()
gtk_recent_chooser_menu_set_show_numbers, gtk_recent_chooser_menu_set_show_numbers ()
gtk_recent_chooser_remove_filter, gtk_recent_chooser_remove_filter ()
gtk_recent_chooser_select_all, gtk_recent_chooser_select_all ()
gtk_recent_chooser_select_uri, gtk_recent_chooser_select_uri ()
gtk_recent_chooser_set_current_uri, gtk_recent_chooser_set_current_uri ()
gtk_recent_chooser_set_filter, gtk_recent_chooser_set_filter ()
gtk_recent_chooser_set_limit, gtk_recent_chooser_set_limit ()
gtk_recent_chooser_set_local_only, gtk_recent_chooser_set_local_only ()
gtk_recent_chooser_set_select_multiple, gtk_recent_chooser_set_select_multiple ()
gtk_recent_chooser_set_show_icons, gtk_recent_chooser_set_show_icons ()
gtk_recent_chooser_set_show_not_found, gtk_recent_chooser_set_show_not_found ()
gtk_recent_chooser_set_show_numbers, gtk_recent_chooser_set_show_numbers ()
gtk_recent_chooser_set_show_private, gtk_recent_chooser_set_show_private ()
gtk_recent_chooser_set_show_tips, gtk_recent_chooser_set_show_tips ()
gtk_recent_chooser_set_sort_func, gtk_recent_chooser_set_sort_func ()
gtk_recent_chooser_set_sort_type, gtk_recent_chooser_set_sort_type ()
gtk_recent_chooser_unselect_all, gtk_recent_chooser_unselect_all ()
gtk_recent_chooser_unselect_uri, gtk_recent_chooser_unselect_uri ()
gtk_recent_chooser_widget_new, gtk_recent_chooser_widget_new ()
gtk_recent_chooser_widget_new_for_manager, gtk_recent_chooser_widget_new_for_manager ()
gtk_recent_filter_add_age, gtk_recent_filter_add_age ()
gtk_recent_filter_add_application, gtk_recent_filter_add_application ()
gtk_recent_filter_add_custom, gtk_recent_filter_add_custom ()
gtk_recent_filter_add_group, gtk_recent_filter_add_group ()
gtk_recent_filter_add_mime_type, gtk_recent_filter_add_mime_type ()
gtk_recent_filter_add_pattern, gtk_recent_filter_add_pattern ()
gtk_recent_filter_add_pixbuf_formats, gtk_recent_filter_add_pixbuf_formats ()
gtk_recent_filter_filter, gtk_recent_filter_filter ()
gtk_recent_filter_get_name, gtk_recent_filter_get_name ()
gtk_recent_filter_get_needed, gtk_recent_filter_get_needed ()
gtk_recent_filter_new, gtk_recent_filter_new ()
gtk_recent_filter_set_name, gtk_recent_filter_set_name ()
gtk_recent_info_exists, gtk_recent_info_exists ()
gtk_recent_info_get_added, gtk_recent_info_get_added ()
gtk_recent_info_get_age, gtk_recent_info_get_age ()
gtk_recent_info_get_applications, gtk_recent_info_get_applications ()
gtk_recent_info_get_application_info, gtk_recent_info_get_application_info ()
gtk_recent_info_get_description, gtk_recent_info_get_description ()
gtk_recent_info_get_display_name, gtk_recent_info_get_display_name ()
gtk_recent_info_get_groups, gtk_recent_info_get_groups ()
gtk_recent_info_get_icon, gtk_recent_info_get_icon ()
gtk_recent_info_get_mime_type, gtk_recent_info_get_mime_type ()
gtk_recent_info_get_modified, gtk_recent_info_get_modified ()
gtk_recent_info_get_private_hint, gtk_recent_info_get_private_hint ()
gtk_recent_info_get_short_name, gtk_recent_info_get_short_name ()
gtk_recent_info_get_uri, gtk_recent_info_get_uri ()
gtk_recent_info_get_uri_display, gtk_recent_info_get_uri_display ()
gtk_recent_info_get_visited, gtk_recent_info_get_visited ()
gtk_recent_info_has_application, gtk_recent_info_has_application ()
gtk_recent_info_has_group, gtk_recent_info_has_group ()
gtk_recent_info_is_local, gtk_recent_info_is_local ()
gtk_recent_info_last_application, gtk_recent_info_last_application ()
gtk_recent_info_match, gtk_recent_info_match ()
gtk_recent_info_ref, gtk_recent_info_ref ()
gtk_recent_info_unref, gtk_recent_info_unref ()
gtk_recent_manager_add_full, gtk_recent_manager_add_full ()
gtk_recent_manager_add_item, gtk_recent_manager_add_item ()
GTK_RECENT_MANAGER_ERROR, GTK_RECENT_MANAGER_ERROR
gtk_recent_manager_get_default, gtk_recent_manager_get_default ()
gtk_recent_manager_get_for_screen, gtk_recent_manager_get_for_screen ()
gtk_recent_manager_get_items, gtk_recent_manager_get_items ()
gtk_recent_manager_get_limit, gtk_recent_manager_get_limit ()
gtk_recent_manager_has_item, gtk_recent_manager_has_item ()
gtk_recent_manager_lookup_item, gtk_recent_manager_lookup_item ()
gtk_recent_manager_move_item, gtk_recent_manager_move_item ()
gtk_recent_manager_new, gtk_recent_manager_new ()
gtk_recent_manager_purge_items, gtk_recent_manager_purge_items ()
gtk_recent_manager_remove_item, gtk_recent_manager_remove_item ()
gtk_recent_manager_set_limit, gtk_recent_manager_set_limit ()
gtk_recent_manager_set_screen, gtk_recent_manager_set_screen ()
gtk_requisition_copy, gtk_requisition_copy ()
gtk_requisition_free, gtk_requisition_free ()
GTK_RETLOC_BOOL, GTK_RETLOC_BOOL()
GTK_RETLOC_BOXED, GTK_RETLOC_BOXED()
GTK_RETLOC_CHAR, GTK_RETLOC_CHAR()
GTK_RETLOC_DOUBLE, GTK_RETLOC_DOUBLE()
GTK_RETLOC_ENUM, GTK_RETLOC_ENUM()
GTK_RETLOC_FLAGS, GTK_RETLOC_FLAGS()
GTK_RETLOC_FLOAT, GTK_RETLOC_FLOAT()
GTK_RETLOC_INT, GTK_RETLOC_INT()
GTK_RETLOC_LONG, GTK_RETLOC_LONG()
GTK_RETLOC_OBJECT, GTK_RETLOC_OBJECT()
GTK_RETLOC_POINTER, GTK_RETLOC_POINTER()
GTK_RETLOC_STRING, GTK_RETLOC_STRING()
GTK_RETLOC_UCHAR, GTK_RETLOC_UCHAR()
GTK_RETLOC_UINT, GTK_RETLOC_UINT()
GTK_RETLOC_ULONG, GTK_RETLOC_ULONG()
gtk_ruler_get_metric, gtk_ruler_get_metric ()
gtk_ruler_get_range, gtk_ruler_get_range ()
gtk_ruler_set_metric, gtk_ruler_set_metric ()
gtk_ruler_set_range, gtk_ruler_set_range ()
gtk_scale_get_digits, gtk_scale_get_digits ()
gtk_scale_get_draw_value, gtk_scale_get_draw_value ()
gtk_scale_get_layout, gtk_scale_get_layout ()
gtk_scale_get_layout_offsets, gtk_scale_get_layout_offsets ()
gtk_scale_get_value_pos, gtk_scale_get_value_pos ()
gtk_scale_set_digits, gtk_scale_set_digits ()
gtk_scale_set_draw_value, gtk_scale_set_draw_value ()
gtk_scale_set_value_pos, gtk_scale_set_value_pos ()
gtk_scrolled_window_add_with_viewport, gtk_scrolled_window_add_with_viewport ()
gtk_scrolled_window_get_hadjustment, gtk_scrolled_window_get_hadjustment ()
gtk_scrolled_window_get_hscrollbar, gtk_scrolled_window_get_hscrollbar ()
gtk_scrolled_window_get_placement, gtk_scrolled_window_get_placement ()
gtk_scrolled_window_get_policy, gtk_scrolled_window_get_policy ()
gtk_scrolled_window_get_shadow_type, gtk_scrolled_window_get_shadow_type ()
gtk_scrolled_window_get_vadjustment, gtk_scrolled_window_get_vadjustment ()
gtk_scrolled_window_get_vscrollbar, gtk_scrolled_window_get_vscrollbar ()
gtk_scrolled_window_new, gtk_scrolled_window_new ()
gtk_scrolled_window_set_hadjustment, gtk_scrolled_window_set_hadjustment ()
gtk_scrolled_window_set_placement, gtk_scrolled_window_set_placement ()
gtk_scrolled_window_set_policy, gtk_scrolled_window_set_policy ()
gtk_scrolled_window_set_shadow_type, gtk_scrolled_window_set_shadow_type ()
gtk_scrolled_window_set_vadjustment, gtk_scrolled_window_set_vadjustment ()
gtk_scrolled_window_unset_placement, gtk_scrolled_window_unset_placement ()
gtk_selection_add_target, gtk_selection_add_target ()
gtk_selection_add_targets, gtk_selection_add_targets ()
gtk_selection_clear, gtk_selection_clear ()
gtk_selection_clear_targets, gtk_selection_clear_targets ()
gtk_selection_convert, gtk_selection_convert ()
gtk_selection_data_copy, gtk_selection_data_copy ()
gtk_selection_data_free, gtk_selection_data_free ()
gtk_selection_data_get_pixbuf, gtk_selection_data_get_pixbuf ()
gtk_selection_data_get_targets, gtk_selection_data_get_targets ()
gtk_selection_data_get_text, gtk_selection_data_get_text ()
gtk_selection_data_get_uris, gtk_selection_data_get_uris ()
gtk_selection_data_set, gtk_selection_data_set ()
gtk_selection_data_set_pixbuf, gtk_selection_data_set_pixbuf ()
gtk_selection_data_set_text, gtk_selection_data_set_text ()
gtk_selection_data_set_uris, gtk_selection_data_set_uris ()
gtk_selection_data_targets_include_image, gtk_selection_data_targets_include_image ()
gtk_selection_data_targets_include_rich_text, gtk_selection_data_targets_include_rich_text ()
gtk_selection_data_targets_include_text, gtk_selection_data_targets_include_text ()
gtk_selection_data_targets_include_uri, gtk_selection_data_targets_include_uri ()
gtk_selection_owner_set, gtk_selection_owner_set ()
gtk_selection_owner_set_for_display, gtk_selection_owner_set_for_display ()
gtk_selection_remove_all, gtk_selection_remove_all ()
gtk_separator_menu_item_new, gtk_separator_menu_item_new ()
gtk_separator_tool_item_get_draw, gtk_separator_tool_item_get_draw ()
gtk_separator_tool_item_new, gtk_separator_tool_item_new ()
gtk_separator_tool_item_set_draw, gtk_separator_tool_item_set_draw ()
gtk_settings_get_default, gtk_settings_get_default ()
gtk_settings_get_for_screen, gtk_settings_get_for_screen ()
gtk_settings_install_property, gtk_settings_install_property ()
gtk_settings_install_property_parser, gtk_settings_install_property_parser ()
gtk_settings_set_double_property, gtk_settings_set_double_property ()
gtk_settings_set_long_property, gtk_settings_set_long_property ()
gtk_settings_set_property_value, gtk_settings_set_property_value ()
gtk_settings_set_string_property, gtk_settings_set_string_property ()
gtk_set_locale, gtk_set_locale ()
gtk_show_about_dialog, gtk_show_about_dialog ()
gtk_signal_connect, gtk_signal_connect()
gtk_signal_connect_after, gtk_signal_connect_after()
gtk_signal_connect_full, gtk_signal_connect_full ()
gtk_signal_connect_object, gtk_signal_connect_object()
gtk_signal_connect_object_after, gtk_signal_connect_object_after()
gtk_signal_connect_object_while_alive, gtk_signal_connect_object_while_alive ()
gtk_signal_connect_while_alive, gtk_signal_connect_while_alive ()
gtk_signal_default_marshaller, gtk_signal_default_marshaller
gtk_signal_disconnect, gtk_signal_disconnect()
gtk_signal_disconnect_by_data, gtk_signal_disconnect_by_data()
gtk_signal_disconnect_by_func, gtk_signal_disconnect_by_func()
gtk_signal_emit, gtk_signal_emit ()
gtk_signal_emitv, gtk_signal_emitv ()
gtk_signal_emitv_by_name, gtk_signal_emitv_by_name ()
gtk_signal_emit_by_name, gtk_signal_emit_by_name ()
gtk_signal_emit_stop, gtk_signal_emit_stop()
gtk_signal_emit_stop_by_name, gtk_signal_emit_stop_by_name ()
GTK_SIGNAL_FUNC, GTK_SIGNAL_FUNC()
gtk_signal_handler_block, gtk_signal_handler_block()
gtk_signal_handler_block_by_data, gtk_signal_handler_block_by_data()
gtk_signal_handler_block_by_func, gtk_signal_handler_block_by_func()
gtk_signal_handler_pending, gtk_signal_handler_pending()
gtk_signal_handler_pending_by_func, gtk_signal_handler_pending_by_func()
gtk_signal_handler_unblock, gtk_signal_handler_unblock()
gtk_signal_handler_unblock_by_data, gtk_signal_handler_unblock_by_data()
gtk_signal_handler_unblock_by_func, gtk_signal_handler_unblock_by_func()
gtk_signal_lookup, gtk_signal_lookup()
gtk_signal_name, gtk_signal_name()
gtk_signal_new, gtk_signal_new ()
gtk_signal_newv, gtk_signal_newv ()
GTK_SIGNAL_OFFSET, GTK_SIGNAL_OFFSET
gtk_size_group_add_widget, gtk_size_group_add_widget ()
gtk_size_group_get_ignore_hidden, gtk_size_group_get_ignore_hidden ()
gtk_size_group_get_mode, gtk_size_group_get_mode ()
gtk_size_group_get_widgets, gtk_size_group_get_widgets ()
gtk_size_group_new, gtk_size_group_new ()
gtk_size_group_remove_widget, gtk_size_group_remove_widget ()
gtk_size_group_set_ignore_hidden, gtk_size_group_set_ignore_hidden ()
gtk_size_group_set_mode, gtk_size_group_set_mode ()
gtk_socket_add_id, gtk_socket_add_id ()
gtk_socket_get_id, gtk_socket_get_id ()
gtk_socket_new, gtk_socket_new ()
gtk_socket_steal, gtk_socket_steal ()
gtk_spin_button_configure, gtk_spin_button_configure ()
gtk_spin_button_get_adjustment, gtk_spin_button_get_adjustment ()
gtk_spin_button_get_digits, gtk_spin_button_get_digits ()
gtk_spin_button_get_increments, gtk_spin_button_get_increments ()
gtk_spin_button_get_numeric, gtk_spin_button_get_numeric ()
gtk_spin_button_get_range, gtk_spin_button_get_range ()
gtk_spin_button_get_snap_to_ticks, gtk_spin_button_get_snap_to_ticks ()
gtk_spin_button_get_update_policy, gtk_spin_button_get_update_policy ()
gtk_spin_button_get_value, gtk_spin_button_get_value ()
gtk_spin_button_get_value_as_float, gtk_spin_button_get_value_as_float
gtk_spin_button_get_value_as_int, gtk_spin_button_get_value_as_int ()
gtk_spin_button_get_wrap, gtk_spin_button_get_wrap ()
gtk_spin_button_new, gtk_spin_button_new ()
gtk_spin_button_new_with_range, gtk_spin_button_new_with_range ()
gtk_spin_button_set_adjustment, gtk_spin_button_set_adjustment ()
gtk_spin_button_set_digits, gtk_spin_button_set_digits ()
gtk_spin_button_set_increments, gtk_spin_button_set_increments ()
gtk_spin_button_set_numeric, gtk_spin_button_set_numeric ()
gtk_spin_button_set_range, gtk_spin_button_set_range ()
gtk_spin_button_set_snap_to_ticks, gtk_spin_button_set_snap_to_ticks ()
gtk_spin_button_set_update_policy, gtk_spin_button_set_update_policy ()
gtk_spin_button_set_value, gtk_spin_button_set_value ()
gtk_spin_button_set_wrap, gtk_spin_button_set_wrap ()
gtk_spin_button_spin, gtk_spin_button_spin ()
gtk_spin_button_update, gtk_spin_button_update ()
gtk_statusbar_get_context_id, gtk_statusbar_get_context_id ()
gtk_statusbar_get_has_resize_grip, gtk_statusbar_get_has_resize_grip ()
gtk_statusbar_new, gtk_statusbar_new ()
gtk_statusbar_pop, gtk_statusbar_pop ()
gtk_statusbar_push, gtk_statusbar_push ()
gtk_statusbar_remove, gtk_statusbar_remove ()
gtk_statusbar_set_has_resize_grip, gtk_statusbar_set_has_resize_grip ()
gtk_status_icon_get_blinking, gtk_status_icon_get_blinking ()
gtk_status_icon_get_geometry, gtk_status_icon_get_geometry ()
gtk_status_icon_get_icon_name, gtk_status_icon_get_icon_name ()
gtk_status_icon_get_pixbuf, gtk_status_icon_get_pixbuf ()
gtk_status_icon_get_size, gtk_status_icon_get_size ()
gtk_status_icon_get_stock, gtk_status_icon_get_stock ()
gtk_status_icon_get_storage_type, gtk_status_icon_get_storage_type ()
gtk_status_icon_get_visible, gtk_status_icon_get_visible ()
gtk_status_icon_is_embedded, gtk_status_icon_is_embedded ()
gtk_status_icon_new, gtk_status_icon_new ()
gtk_status_icon_new_from_file, gtk_status_icon_new_from_file ()
gtk_status_icon_new_from_icon_name, gtk_status_icon_new_from_icon_name ()
gtk_status_icon_new_from_pixbuf, gtk_status_icon_new_from_pixbuf ()
gtk_status_icon_new_from_stock, gtk_status_icon_new_from_stock ()
gtk_status_icon_position_menu, gtk_status_icon_position_menu ()
gtk_status_icon_set_blinking, gtk_status_icon_set_blinking ()
gtk_status_icon_set_from_file, gtk_status_icon_set_from_file ()
gtk_status_icon_set_from_icon_name, gtk_status_icon_set_from_icon_name ()
gtk_status_icon_set_from_pixbuf, gtk_status_icon_set_from_pixbuf ()
gtk_status_icon_set_from_stock, gtk_status_icon_set_from_stock ()
gtk_status_icon_set_tooltip, gtk_status_icon_set_tooltip ()
gtk_status_icon_set_visible, gtk_status_icon_set_visible ()
GTK_STOCK_ABOUT, GTK_STOCK_ABOUT
gtk_stock_add, gtk_stock_add ()
GTK_STOCK_ADD, GTK_STOCK_ADD
gtk_stock_add_static, gtk_stock_add_static ()
GTK_STOCK_APPLY, GTK_STOCK_APPLY
GTK_STOCK_BOLD, GTK_STOCK_BOLD
GTK_STOCK_CANCEL, GTK_STOCK_CANCEL
GTK_STOCK_CDROM, GTK_STOCK_CDROM
GTK_STOCK_CLEAR, GTK_STOCK_CLEAR
GTK_STOCK_CLOSE, GTK_STOCK_CLOSE
GTK_STOCK_COLOR_PICKER, GTK_STOCK_COLOR_PICKER
GTK_STOCK_CONNECT, GTK_STOCK_CONNECT
GTK_STOCK_CONVERT, GTK_STOCK_CONVERT
GTK_STOCK_COPY, GTK_STOCK_COPY
GTK_STOCK_CUT, GTK_STOCK_CUT
GTK_STOCK_DELETE, GTK_STOCK_DELETE
GTK_STOCK_DIALOG_AUTHENTICATION, GTK_STOCK_DIALOG_AUTHENTICATION
GTK_STOCK_DIALOG_ERROR, GTK_STOCK_DIALOG_ERROR
GTK_STOCK_DIALOG_INFO, GTK_STOCK_DIALOG_INFO
GTK_STOCK_DIALOG_QUESTION, GTK_STOCK_DIALOG_QUESTION
GTK_STOCK_DIALOG_WARNING, GTK_STOCK_DIALOG_WARNING
GTK_STOCK_DIRECTORY, GTK_STOCK_DIRECTORY
GTK_STOCK_DISCONNECT, GTK_STOCK_DISCONNECT
GTK_STOCK_DND, GTK_STOCK_DND
GTK_STOCK_DND_MULTIPLE, GTK_STOCK_DND_MULTIPLE
GTK_STOCK_EDIT, GTK_STOCK_EDIT
GTK_STOCK_EXECUTE, GTK_STOCK_EXECUTE
GTK_STOCK_FILE, GTK_STOCK_FILE
GTK_STOCK_FIND, GTK_STOCK_FIND
GTK_STOCK_FIND_AND_REPLACE, GTK_STOCK_FIND_AND_REPLACE
GTK_STOCK_FLOPPY, GTK_STOCK_FLOPPY
GTK_STOCK_FULLSCREEN, GTK_STOCK_FULLSCREEN
GTK_STOCK_GOTO_BOTTOM, GTK_STOCK_GOTO_BOTTOM
GTK_STOCK_GOTO_FIRST, GTK_STOCK_GOTO_FIRST
GTK_STOCK_GOTO_LAST, GTK_STOCK_GOTO_LAST
GTK_STOCK_GOTO_TOP, GTK_STOCK_GOTO_TOP
GTK_STOCK_GO_BACK, GTK_STOCK_GO_BACK
GTK_STOCK_GO_DOWN, GTK_STOCK_GO_DOWN
GTK_STOCK_GO_FORWARD, GTK_STOCK_GO_FORWARD
GTK_STOCK_GO_UP, GTK_STOCK_GO_UP
GTK_STOCK_HARDDISK, GTK_STOCK_HARDDISK
GTK_STOCK_HELP, GTK_STOCK_HELP
GTK_STOCK_HOME, GTK_STOCK_HOME
GTK_STOCK_INDENT, GTK_STOCK_INDENT
GTK_STOCK_INDEX, GTK_STOCK_INDEX
GTK_STOCK_INFO, GTK_STOCK_INFO
GTK_STOCK_ITALIC, GTK_STOCK_ITALIC
gtk_stock_item_copy, gtk_stock_item_copy ()
gtk_stock_item_free, gtk_stock_item_free ()
GTK_STOCK_JUMP_TO, GTK_STOCK_JUMP_TO
GTK_STOCK_JUSTIFY_CENTER, GTK_STOCK_JUSTIFY_CENTER
GTK_STOCK_JUSTIFY_FILL, GTK_STOCK_JUSTIFY_FILL
GTK_STOCK_JUSTIFY_LEFT, GTK_STOCK_JUSTIFY_LEFT
GTK_STOCK_JUSTIFY_RIGHT, GTK_STOCK_JUSTIFY_RIGHT
GTK_STOCK_LEAVE_FULLSCREEN, GTK_STOCK_LEAVE_FULLSCREEN
gtk_stock_list_ids, gtk_stock_list_ids ()
gtk_stock_lookup, gtk_stock_lookup ()
GTK_STOCK_MEDIA_FORWARD, GTK_STOCK_MEDIA_FORWARD
GTK_STOCK_MEDIA_NEXT, GTK_STOCK_MEDIA_NEXT
GTK_STOCK_MEDIA_PAUSE, GTK_STOCK_MEDIA_PAUSE
GTK_STOCK_MEDIA_PLAY, GTK_STOCK_MEDIA_PLAY
GTK_STOCK_MEDIA_PREVIOUS, GTK_STOCK_MEDIA_PREVIOUS
GTK_STOCK_MEDIA_RECORD, GTK_STOCK_MEDIA_RECORD
GTK_STOCK_MEDIA_REWIND, GTK_STOCK_MEDIA_REWIND
GTK_STOCK_MEDIA_STOP, GTK_STOCK_MEDIA_STOP
GTK_STOCK_MISSING_IMAGE, GTK_STOCK_MISSING_IMAGE
GTK_STOCK_NETWORK, GTK_STOCK_NETWORK
GTK_STOCK_NEW, GTK_STOCK_NEW
GTK_STOCK_NO, GTK_STOCK_NO
GTK_STOCK_OK, GTK_STOCK_OK
GTK_STOCK_OPEN, GTK_STOCK_OPEN
GTK_STOCK_ORIENTATION_LANDSCAPE, GTK_STOCK_ORIENTATION_LANDSCAPE
GTK_STOCK_ORIENTATION_PORTRAIT, GTK_STOCK_ORIENTATION_PORTRAIT
GTK_STOCK_ORIENTATION_REVERSE_LANDSCAPE, GTK_STOCK_ORIENTATION_REVERSE_LANDSCAPE
GTK_STOCK_ORIENTATION_REVERSE_PORTRAIT, GTK_STOCK_ORIENTATION_REVERSE_PORTRAIT
GTK_STOCK_PASTE, GTK_STOCK_PASTE
GTK_STOCK_PREFERENCES, GTK_STOCK_PREFERENCES
GTK_STOCK_PRINT, GTK_STOCK_PRINT
GTK_STOCK_PRINT_PREVIEW, GTK_STOCK_PRINT_PREVIEW
GTK_STOCK_PROPERTIES, GTK_STOCK_PROPERTIES
GTK_STOCK_QUIT, GTK_STOCK_QUIT
GTK_STOCK_REDO, GTK_STOCK_REDO
GTK_STOCK_REFRESH, GTK_STOCK_REFRESH
GTK_STOCK_REMOVE, GTK_STOCK_REMOVE
GTK_STOCK_REVERT_TO_SAVED, GTK_STOCK_REVERT_TO_SAVED
GTK_STOCK_SAVE, GTK_STOCK_SAVE
GTK_STOCK_SAVE_AS, GTK_STOCK_SAVE_AS
GTK_STOCK_SELECT_ALL, GTK_STOCK_SELECT_ALL
GTK_STOCK_SELECT_COLOR, GTK_STOCK_SELECT_COLOR
GTK_STOCK_SELECT_FONT, GTK_STOCK_SELECT_FONT
gtk_stock_set_translate_func, gtk_stock_set_translate_func ()
GTK_STOCK_SORT_ASCENDING, GTK_STOCK_SORT_ASCENDING
GTK_STOCK_SORT_DESCENDING, GTK_STOCK_SORT_DESCENDING
GTK_STOCK_SPELL_CHECK, GTK_STOCK_SPELL_CHECK
GTK_STOCK_STOP, GTK_STOCK_STOP
GTK_STOCK_STRIKETHROUGH, GTK_STOCK_STRIKETHROUGH
GTK_STOCK_UNDELETE, GTK_STOCK_UNDELETE
GTK_STOCK_UNDERLINE, GTK_STOCK_UNDERLINE
GTK_STOCK_UNDO, GTK_STOCK_UNDO
GTK_STOCK_UNINDENT, GTK_STOCK_UNINDENT
GTK_STOCK_YES, GTK_STOCK_YES
GTK_STOCK_ZOOM_100, GTK_STOCK_ZOOM_100
GTK_STOCK_ZOOM_FIT, GTK_STOCK_ZOOM_FIT
GTK_STOCK_ZOOM_IN, GTK_STOCK_ZOOM_IN
GTK_STOCK_ZOOM_OUT, GTK_STOCK_ZOOM_OUT
GTK_STRUCT_OFFSET, GTK_STRUCT_OFFSET
gtk_style_apply_default_background, gtk_style_apply_default_background ()
gtk_style_apply_default_pixmap, gtk_style_apply_default_pixmap()
gtk_style_attach, gtk_style_attach ()
GTK_STYLE_ATTACHED, GTK_STYLE_ATTACHED()
gtk_style_copy, gtk_style_copy ()
gtk_style_detach, gtk_style_detach ()
gtk_style_get_font, gtk_style_get_font ()
gtk_style_lookup_color, gtk_style_lookup_color ()
gtk_style_lookup_icon_set, gtk_style_lookup_icon_set ()
gtk_style_new, gtk_style_new ()
gtk_style_ref, gtk_style_ref ()
gtk_style_render_icon, gtk_style_render_icon ()
gtk_style_set_background, gtk_style_set_background ()
gtk_style_set_font, gtk_style_set_font ()
gtk_style_unref, gtk_style_unref ()
gtk_table_attach, gtk_table_attach ()
gtk_table_attach_defaults, gtk_table_attach_defaults ()
gtk_table_get_col_spacing, gtk_table_get_col_spacing ()
gtk_table_get_default_col_spacing, gtk_table_get_default_col_spacing ()
gtk_table_get_default_row_spacing, gtk_table_get_default_row_spacing ()
gtk_table_get_homogeneous, gtk_table_get_homogeneous ()
gtk_table_get_row_spacing, gtk_table_get_row_spacing ()
gtk_table_new, gtk_table_new ()
gtk_table_resize, gtk_table_resize ()
gtk_table_set_col_spacing, gtk_table_set_col_spacing ()
gtk_table_set_col_spacings, gtk_table_set_col_spacings ()
gtk_table_set_homogeneous, gtk_table_set_homogeneous ()
gtk_table_set_row_spacing, gtk_table_set_row_spacing ()
gtk_table_set_row_spacings, gtk_table_set_row_spacings ()
gtk_targets_include_image, gtk_targets_include_image ()
gtk_targets_include_rich_text, gtk_targets_include_rich_text ()
gtk_targets_include_text, gtk_targets_include_text ()
gtk_targets_include_uri, gtk_targets_include_uri ()
gtk_target_list_add, gtk_target_list_add ()
gtk_target_list_add_image_targets, gtk_target_list_add_image_targets ()
gtk_target_list_add_rich_text_targets, gtk_target_list_add_rich_text_targets ()
gtk_target_list_add_table, gtk_target_list_add_table ()
gtk_target_list_add_text_targets, gtk_target_list_add_text_targets ()
gtk_target_list_add_uri_targets, gtk_target_list_add_uri_targets ()
gtk_target_list_find, gtk_target_list_find ()
gtk_target_list_new, gtk_target_list_new ()
gtk_target_list_ref, gtk_target_list_ref ()
gtk_target_list_remove, gtk_target_list_remove ()
gtk_target_list_unref, gtk_target_list_unref ()
gtk_target_table_free, gtk_target_table_free ()
gtk_target_table_new_from_list, gtk_target_table_new_from_list ()
gtk_tearoff_menu_item_new, gtk_tearoff_menu_item_new ()
gtk_text_attributes_copy, gtk_text_attributes_copy ()
gtk_text_attributes_copy_values, gtk_text_attributes_copy_values ()
gtk_text_attributes_new, gtk_text_attributes_new ()
gtk_text_attributes_ref, gtk_text_attributes_ref ()
gtk_text_attributes_unref, gtk_text_attributes_unref ()
gtk_text_backward_delete, gtk_text_backward_delete ()
gtk_text_buffer_add_selection_clipboard, gtk_text_buffer_add_selection_clipboard ()
gtk_text_buffer_apply_tag, gtk_text_buffer_apply_tag ()
gtk_text_buffer_apply_tag_by_name, gtk_text_buffer_apply_tag_by_name ()
gtk_text_buffer_backspace, gtk_text_buffer_backspace ()
gtk_text_buffer_begin_user_action, gtk_text_buffer_begin_user_action ()
gtk_text_buffer_copy_clipboard, gtk_text_buffer_copy_clipboard ()
gtk_text_buffer_create_child_anchor, gtk_text_buffer_create_child_anchor ()
gtk_text_buffer_create_mark, gtk_text_buffer_create_mark ()
gtk_text_buffer_create_tag, gtk_text_buffer_create_tag ()
gtk_text_buffer_cut_clipboard, gtk_text_buffer_cut_clipboard ()
gtk_text_buffer_delete, gtk_text_buffer_delete ()
gtk_text_buffer_delete_interactive, gtk_text_buffer_delete_interactive ()
gtk_text_buffer_delete_mark, gtk_text_buffer_delete_mark ()
gtk_text_buffer_delete_mark_by_name, gtk_text_buffer_delete_mark_by_name ()
gtk_text_buffer_delete_selection, gtk_text_buffer_delete_selection ()
gtk_text_buffer_deserialize, gtk_text_buffer_deserialize ()
gtk_text_buffer_deserialize_get_can_create_tags, gtk_text_buffer_deserialize_get_can_create_tags ()
gtk_text_buffer_deserialize_set_can_create_tags, gtk_text_buffer_deserialize_set_can_create_tags ()
gtk_text_buffer_end_user_action, gtk_text_buffer_end_user_action ()
gtk_text_buffer_get_bounds, gtk_text_buffer_get_bounds ()
gtk_text_buffer_get_char_count, gtk_text_buffer_get_char_count ()
gtk_text_buffer_get_copy_target_list, gtk_text_buffer_get_copy_target_list ()
gtk_text_buffer_get_deserialize_formats, gtk_text_buffer_get_deserialize_formats ()
gtk_text_buffer_get_end_iter, gtk_text_buffer_get_end_iter ()
gtk_text_buffer_get_has_selection, gtk_text_buffer_get_has_selection ()
gtk_text_buffer_get_insert, gtk_text_buffer_get_insert ()
gtk_text_buffer_get_iter_at_child_anchor, gtk_text_buffer_get_iter_at_child_anchor ()
gtk_text_buffer_get_iter_at_line, gtk_text_buffer_get_iter_at_line ()
gtk_text_buffer_get_iter_at_line_index, gtk_text_buffer_get_iter_at_line_index ()
gtk_text_buffer_get_iter_at_line_offset, gtk_text_buffer_get_iter_at_line_offset ()
gtk_text_buffer_get_iter_at_mark, gtk_text_buffer_get_iter_at_mark ()
gtk_text_buffer_get_iter_at_offset, gtk_text_buffer_get_iter_at_offset ()
gtk_text_buffer_get_line_count, gtk_text_buffer_get_line_count ()
gtk_text_buffer_get_mark, gtk_text_buffer_get_mark ()
gtk_text_buffer_get_modified, gtk_text_buffer_get_modified ()
gtk_text_buffer_get_paste_target_list, gtk_text_buffer_get_paste_target_list ()
gtk_text_buffer_get_selection_bound, gtk_text_buffer_get_selection_bound ()
gtk_text_buffer_get_selection_bounds, gtk_text_buffer_get_selection_bounds ()
gtk_text_buffer_get_serialize_formats, gtk_text_buffer_get_serialize_formats ()
gtk_text_buffer_get_slice, gtk_text_buffer_get_slice ()
gtk_text_buffer_get_start_iter, gtk_text_buffer_get_start_iter ()
gtk_text_buffer_get_tag_table, gtk_text_buffer_get_tag_table ()
gtk_text_buffer_get_text, gtk_text_buffer_get_text ()
gtk_text_buffer_insert, gtk_text_buffer_insert ()
gtk_text_buffer_insert_at_cursor, gtk_text_buffer_insert_at_cursor ()
gtk_text_buffer_insert_child_anchor, gtk_text_buffer_insert_child_anchor ()
gtk_text_buffer_insert_interactive, gtk_text_buffer_insert_interactive ()
gtk_text_buffer_insert_interactive_at_cursor, gtk_text_buffer_insert_interactive_at_cursor ()
gtk_text_buffer_insert_pixbuf, gtk_text_buffer_insert_pixbuf ()
gtk_text_buffer_insert_range, gtk_text_buffer_insert_range ()
gtk_text_buffer_insert_range_interactive, gtk_text_buffer_insert_range_interactive ()
gtk_text_buffer_insert_with_tags, gtk_text_buffer_insert_with_tags ()
gtk_text_buffer_insert_with_tags_by_name, gtk_text_buffer_insert_with_tags_by_name ()
gtk_text_buffer_move_mark, gtk_text_buffer_move_mark ()
gtk_text_buffer_move_mark_by_name, gtk_text_buffer_move_mark_by_name ()
gtk_text_buffer_new, gtk_text_buffer_new ()
gtk_text_buffer_paste_clipboard, gtk_text_buffer_paste_clipboard ()
gtk_text_buffer_place_cursor, gtk_text_buffer_place_cursor ()
gtk_text_buffer_register_deserialize_format, gtk_text_buffer_register_deserialize_format ()
gtk_text_buffer_register_deserialize_tagset, gtk_text_buffer_register_deserialize_tagset ()
gtk_text_buffer_register_serialize_format, gtk_text_buffer_register_serialize_format ()
gtk_text_buffer_register_serialize_tagset, gtk_text_buffer_register_serialize_tagset ()
gtk_text_buffer_remove_all_tags, gtk_text_buffer_remove_all_tags ()
gtk_text_buffer_remove_selection_clipboard, gtk_text_buffer_remove_selection_clipboard ()
gtk_text_buffer_remove_tag, gtk_text_buffer_remove_tag ()
gtk_text_buffer_remove_tag_by_name, gtk_text_buffer_remove_tag_by_name ()
gtk_text_buffer_select_range, gtk_text_buffer_select_range ()
gtk_text_buffer_serialize, gtk_text_buffer_serialize ()
gtk_text_buffer_set_modified, gtk_text_buffer_set_modified ()
gtk_text_buffer_set_text, gtk_text_buffer_set_text ()
gtk_text_buffer_unregister_deserialize_format, gtk_text_buffer_unregister_deserialize_format ()
gtk_text_buffer_unregister_serialize_format, gtk_text_buffer_unregister_serialize_format ()
gtk_text_child_anchor_get_deleted, gtk_text_child_anchor_get_deleted ()
gtk_text_child_anchor_get_widgets, gtk_text_child_anchor_get_widgets ()
gtk_text_child_anchor_new, gtk_text_child_anchor_new ()
gtk_text_forward_delete, gtk_text_forward_delete ()
gtk_text_freeze, gtk_text_freeze ()
gtk_text_get_length, gtk_text_get_length ()
gtk_text_get_point, gtk_text_get_point ()
GTK_TEXT_INDEX, GTK_TEXT_INDEX()
gtk_text_insert, gtk_text_insert ()
gtk_text_iter_backward_char, gtk_text_iter_backward_char ()
gtk_text_iter_backward_chars, gtk_text_iter_backward_chars ()
gtk_text_iter_backward_cursor_position, gtk_text_iter_backward_cursor_position ()
gtk_text_iter_backward_cursor_positions, gtk_text_iter_backward_cursor_positions ()
gtk_text_iter_backward_find_char, gtk_text_iter_backward_find_char ()
gtk_text_iter_backward_line, gtk_text_iter_backward_line ()
gtk_text_iter_backward_lines, gtk_text_iter_backward_lines ()
gtk_text_iter_backward_search, gtk_text_iter_backward_search ()
gtk_text_iter_backward_sentence_start, gtk_text_iter_backward_sentence_start ()
gtk_text_iter_backward_sentence_starts, gtk_text_iter_backward_sentence_starts ()
gtk_text_iter_backward_to_tag_toggle, gtk_text_iter_backward_to_tag_toggle ()
gtk_text_iter_backward_visible_cursor_position, gtk_text_iter_backward_visible_cursor_position ()
gtk_text_iter_backward_visible_cursor_positions, gtk_text_iter_backward_visible_cursor_positions ()
gtk_text_iter_backward_visible_line, gtk_text_iter_backward_visible_line ()
gtk_text_iter_backward_visible_lines, gtk_text_iter_backward_visible_lines ()
gtk_text_iter_backward_visible_word_start, gtk_text_iter_backward_visible_word_start ()
gtk_text_iter_backward_visible_word_starts, gtk_text_iter_backward_visible_word_starts ()
gtk_text_iter_backward_word_start, gtk_text_iter_backward_word_start ()
gtk_text_iter_backward_word_starts, gtk_text_iter_backward_word_starts ()
gtk_text_iter_begins_tag, gtk_text_iter_begins_tag ()
gtk_text_iter_can_insert, gtk_text_iter_can_insert ()
gtk_text_iter_compare, gtk_text_iter_compare ()
gtk_text_iter_copy, gtk_text_iter_copy ()
gtk_text_iter_editable, gtk_text_iter_editable ()
gtk_text_iter_ends_line, gtk_text_iter_ends_line ()
gtk_text_iter_ends_sentence, gtk_text_iter_ends_sentence ()
gtk_text_iter_ends_tag, gtk_text_iter_ends_tag ()
gtk_text_iter_ends_word, gtk_text_iter_ends_word ()
gtk_text_iter_equal, gtk_text_iter_equal ()
gtk_text_iter_forward_char, gtk_text_iter_forward_char ()
gtk_text_iter_forward_chars, gtk_text_iter_forward_chars ()
gtk_text_iter_forward_cursor_position, gtk_text_iter_forward_cursor_position ()
gtk_text_iter_forward_cursor_positions, gtk_text_iter_forward_cursor_positions ()
gtk_text_iter_forward_find_char, gtk_text_iter_forward_find_char ()
gtk_text_iter_forward_line, gtk_text_iter_forward_line ()
gtk_text_iter_forward_lines, gtk_text_iter_forward_lines ()
gtk_text_iter_forward_search, gtk_text_iter_forward_search ()
gtk_text_iter_forward_sentence_end, gtk_text_iter_forward_sentence_end ()
gtk_text_iter_forward_sentence_ends, gtk_text_iter_forward_sentence_ends ()
gtk_text_iter_forward_to_end, gtk_text_iter_forward_to_end ()
gtk_text_iter_forward_to_line_end, gtk_text_iter_forward_to_line_end ()
gtk_text_iter_forward_to_tag_toggle, gtk_text_iter_forward_to_tag_toggle ()
gtk_text_iter_forward_visible_cursor_position, gtk_text_iter_forward_visible_cursor_position ()
gtk_text_iter_forward_visible_cursor_positions, gtk_text_iter_forward_visible_cursor_positions ()
gtk_text_iter_forward_visible_line, gtk_text_iter_forward_visible_line ()
gtk_text_iter_forward_visible_lines, gtk_text_iter_forward_visible_lines ()
gtk_text_iter_forward_visible_word_end, gtk_text_iter_forward_visible_word_end ()
gtk_text_iter_forward_visible_word_ends, gtk_text_iter_forward_visible_word_ends ()
gtk_text_iter_forward_word_end, gtk_text_iter_forward_word_end ()
gtk_text_iter_forward_word_ends, gtk_text_iter_forward_word_ends ()
gtk_text_iter_free, gtk_text_iter_free ()
gtk_text_iter_get_attributes, gtk_text_iter_get_attributes ()
gtk_text_iter_get_buffer, gtk_text_iter_get_buffer ()
gtk_text_iter_get_bytes_in_line, gtk_text_iter_get_bytes_in_line ()
gtk_text_iter_get_char, gtk_text_iter_get_char ()
gtk_text_iter_get_chars_in_line, gtk_text_iter_get_chars_in_line ()
gtk_text_iter_get_child_anchor, gtk_text_iter_get_child_anchor ()
gtk_text_iter_get_language, gtk_text_iter_get_language ()
gtk_text_iter_get_line, gtk_text_iter_get_line ()
gtk_text_iter_get_line_index, gtk_text_iter_get_line_index ()
gtk_text_iter_get_line_offset, gtk_text_iter_get_line_offset ()
gtk_text_iter_get_marks, gtk_text_iter_get_marks ()
gtk_text_iter_get_offset, gtk_text_iter_get_offset ()
gtk_text_iter_get_pixbuf, gtk_text_iter_get_pixbuf ()
gtk_text_iter_get_slice, gtk_text_iter_get_slice ()
gtk_text_iter_get_tags, gtk_text_iter_get_tags ()
gtk_text_iter_get_text, gtk_text_iter_get_text ()
gtk_text_iter_get_toggled_tags, gtk_text_iter_get_toggled_tags ()
gtk_text_iter_get_visible_line_index, gtk_text_iter_get_visible_line_index ()
gtk_text_iter_get_visible_line_offset, gtk_text_iter_get_visible_line_offset ()
gtk_text_iter_get_visible_slice, gtk_text_iter_get_visible_slice ()
gtk_text_iter_get_visible_text, gtk_text_iter_get_visible_text ()
gtk_text_iter_has_tag, gtk_text_iter_has_tag ()
gtk_text_iter_inside_sentence, gtk_text_iter_inside_sentence ()
gtk_text_iter_inside_word, gtk_text_iter_inside_word ()
gtk_text_iter_in_range, gtk_text_iter_in_range ()
gtk_text_iter_is_cursor_position, gtk_text_iter_is_cursor_position ()
gtk_text_iter_is_end, gtk_text_iter_is_end ()
gtk_text_iter_is_start, gtk_text_iter_is_start ()
gtk_text_iter_order, gtk_text_iter_order ()
gtk_text_iter_set_line, gtk_text_iter_set_line ()
gtk_text_iter_set_line_index, gtk_text_iter_set_line_index ()
gtk_text_iter_set_line_offset, gtk_text_iter_set_line_offset ()
gtk_text_iter_set_offset, gtk_text_iter_set_offset ()
gtk_text_iter_set_visible_line_index, gtk_text_iter_set_visible_line_index ()
gtk_text_iter_set_visible_line_offset, gtk_text_iter_set_visible_line_offset ()
gtk_text_iter_starts_line, gtk_text_iter_starts_line ()
gtk_text_iter_starts_sentence, gtk_text_iter_starts_sentence ()
gtk_text_iter_starts_word, gtk_text_iter_starts_word ()
gtk_text_iter_toggles_tag, gtk_text_iter_toggles_tag ()
gtk_text_mark_get_buffer, gtk_text_mark_get_buffer ()
gtk_text_mark_get_deleted, gtk_text_mark_get_deleted ()
gtk_text_mark_get_left_gravity, gtk_text_mark_get_left_gravity ()
gtk_text_mark_get_name, gtk_text_mark_get_name ()
gtk_text_mark_get_visible, gtk_text_mark_get_visible ()
gtk_text_mark_set_visible, gtk_text_mark_set_visible ()
gtk_text_new, gtk_text_new ()
gtk_text_set_adjustments, gtk_text_set_adjustments ()
gtk_text_set_editable, gtk_text_set_editable ()
gtk_text_set_line_wrap, gtk_text_set_line_wrap ()
gtk_text_set_point, gtk_text_set_point ()
gtk_text_set_word_wrap, gtk_text_set_word_wrap ()
gtk_text_tag_event, gtk_text_tag_event ()
gtk_text_tag_get_priority, gtk_text_tag_get_priority ()
gtk_text_tag_new, gtk_text_tag_new ()
gtk_text_tag_set_priority, gtk_text_tag_set_priority ()
gtk_text_tag_table_add, gtk_text_tag_table_add ()
gtk_text_tag_table_foreach, gtk_text_tag_table_foreach ()
gtk_text_tag_table_get_size, gtk_text_tag_table_get_size ()
gtk_text_tag_table_lookup, gtk_text_tag_table_lookup ()
gtk_text_tag_table_new, gtk_text_tag_table_new ()
gtk_text_tag_table_remove, gtk_text_tag_table_remove ()
gtk_text_thaw, gtk_text_thaw ()
gtk_text_view_add_child_at_anchor, gtk_text_view_add_child_at_anchor ()
gtk_text_view_add_child_in_window, gtk_text_view_add_child_in_window ()
gtk_text_view_backward_display_line, gtk_text_view_backward_display_line ()
gtk_text_view_backward_display_line_start, gtk_text_view_backward_display_line_start ()
gtk_text_view_buffer_to_window_coords, gtk_text_view_buffer_to_window_coords ()
gtk_text_view_forward_display_line, gtk_text_view_forward_display_line ()
gtk_text_view_forward_display_line_end, gtk_text_view_forward_display_line_end ()
gtk_text_view_get_accepts_tab, gtk_text_view_get_accepts_tab ()
gtk_text_view_get_border_window_size, gtk_text_view_get_border_window_size ()
gtk_text_view_get_buffer, gtk_text_view_get_buffer ()
gtk_text_view_get_cursor_visible, gtk_text_view_get_cursor_visible ()
gtk_text_view_get_default_attributes, gtk_text_view_get_default_attributes ()
gtk_text_view_get_editable, gtk_text_view_get_editable ()
gtk_text_view_get_indent, gtk_text_view_get_indent ()
gtk_text_view_get_iter_at_location, gtk_text_view_get_iter_at_location ()
gtk_text_view_get_iter_at_position, gtk_text_view_get_iter_at_position ()
gtk_text_view_get_iter_location, gtk_text_view_get_iter_location ()
gtk_text_view_get_justification, gtk_text_view_get_justification ()
gtk_text_view_get_left_margin, gtk_text_view_get_left_margin ()
gtk_text_view_get_line_at_y, gtk_text_view_get_line_at_y ()
gtk_text_view_get_line_yrange, gtk_text_view_get_line_yrange ()
gtk_text_view_get_overwrite, gtk_text_view_get_overwrite ()
gtk_text_view_get_pixels_above_lines, gtk_text_view_get_pixels_above_lines ()
gtk_text_view_get_pixels_below_lines, gtk_text_view_get_pixels_below_lines ()
gtk_text_view_get_pixels_inside_wrap, gtk_text_view_get_pixels_inside_wrap ()
gtk_text_view_get_right_margin, gtk_text_view_get_right_margin ()
gtk_text_view_get_tabs, gtk_text_view_get_tabs ()
gtk_text_view_get_visible_rect, gtk_text_view_get_visible_rect ()
gtk_text_view_get_window, gtk_text_view_get_window ()
gtk_text_view_get_window_type, gtk_text_view_get_window_type ()
gtk_text_view_get_wrap_mode, gtk_text_view_get_wrap_mode ()
gtk_text_view_move_child, gtk_text_view_move_child ()
gtk_text_view_move_mark_onscreen, gtk_text_view_move_mark_onscreen ()
gtk_text_view_move_visually, gtk_text_view_move_visually ()
gtk_text_view_new, gtk_text_view_new ()
gtk_text_view_new_with_buffer, gtk_text_view_new_with_buffer ()
gtk_text_view_place_cursor_onscreen, gtk_text_view_place_cursor_onscreen ()
GTK_TEXT_VIEW_PRIORITY_VALIDATE, GTK_TEXT_VIEW_PRIORITY_VALIDATE
gtk_text_view_scroll_mark_onscreen, gtk_text_view_scroll_mark_onscreen ()
gtk_text_view_scroll_to_iter, gtk_text_view_scroll_to_iter ()
gtk_text_view_scroll_to_mark, gtk_text_view_scroll_to_mark ()
gtk_text_view_set_accepts_tab, gtk_text_view_set_accepts_tab ()
gtk_text_view_set_border_window_size, gtk_text_view_set_border_window_size ()
gtk_text_view_set_buffer, gtk_text_view_set_buffer ()
gtk_text_view_set_cursor_visible, gtk_text_view_set_cursor_visible ()
gtk_text_view_set_editable, gtk_text_view_set_editable ()
gtk_text_view_set_indent, gtk_text_view_set_indent ()
gtk_text_view_set_justification, gtk_text_view_set_justification ()
gtk_text_view_set_left_margin, gtk_text_view_set_left_margin ()
gtk_text_view_set_overwrite, gtk_text_view_set_overwrite ()
gtk_text_view_set_pixels_above_lines, gtk_text_view_set_pixels_above_lines ()
gtk_text_view_set_pixels_below_lines, gtk_text_view_set_pixels_below_lines ()
gtk_text_view_set_pixels_inside_wrap, gtk_text_view_set_pixels_inside_wrap ()
gtk_text_view_set_right_margin, gtk_text_view_set_right_margin ()
gtk_text_view_set_tabs, gtk_text_view_set_tabs ()
gtk_text_view_set_wrap_mode, gtk_text_view_set_wrap_mode ()
gtk_text_view_starts_display_line, gtk_text_view_starts_display_line ()
gtk_text_view_window_to_buffer_coords, gtk_text_view_window_to_buffer_coords ()
gtk_timeout_add, gtk_timeout_add ()
gtk_timeout_add_full, gtk_timeout_add_full ()
gtk_timeout_remove, gtk_timeout_remove ()
gtk_tips_query_new, gtk_tips_query_new ()
gtk_tips_query_set_caller, gtk_tips_query_set_caller ()
gtk_tips_query_set_labels, gtk_tips_query_set_labels ()
gtk_tips_query_start_query, gtk_tips_query_start_query ()
gtk_tips_query_stop_query, gtk_tips_query_stop_query ()
gtk_toggle_action_get_active, gtk_toggle_action_get_active ()
gtk_toggle_action_get_draw_as_radio, gtk_toggle_action_get_draw_as_radio ()
gtk_toggle_action_new, gtk_toggle_action_new ()
gtk_toggle_action_set_active, gtk_toggle_action_set_active ()
gtk_toggle_action_set_draw_as_radio, gtk_toggle_action_set_draw_as_radio ()
gtk_toggle_action_toggled, gtk_toggle_action_toggled ()
gtk_toggle_button_get_active, gtk_toggle_button_get_active ()
gtk_toggle_button_get_inconsistent, gtk_toggle_button_get_inconsistent ()
gtk_toggle_button_get_mode, gtk_toggle_button_get_mode ()
gtk_toggle_button_new, gtk_toggle_button_new ()
gtk_toggle_button_new_with_label, gtk_toggle_button_new_with_label ()
gtk_toggle_button_new_with_mnemonic, gtk_toggle_button_new_with_mnemonic ()
gtk_toggle_button_set_active, gtk_toggle_button_set_active ()
gtk_toggle_button_set_inconsistent, gtk_toggle_button_set_inconsistent ()
gtk_toggle_button_set_mode, gtk_toggle_button_set_mode ()
gtk_toggle_button_set_state, gtk_toggle_button_set_state
gtk_toggle_button_toggled, gtk_toggle_button_toggled ()
gtk_toggle_tool_button_get_active, gtk_toggle_tool_button_get_active ()
gtk_toggle_tool_button_new, gtk_toggle_tool_button_new ()
gtk_toggle_tool_button_new_from_stock, gtk_toggle_tool_button_new_from_stock ()
gtk_toggle_tool_button_set_active, gtk_toggle_tool_button_set_active ()
gtk_toolbar_append_element, gtk_toolbar_append_element ()
gtk_toolbar_append_item, gtk_toolbar_append_item ()
gtk_toolbar_append_space, gtk_toolbar_append_space ()
gtk_toolbar_append_widget, gtk_toolbar_append_widget ()
gtk_toolbar_get_drop_index, gtk_toolbar_get_drop_index ()
gtk_toolbar_get_icon_size, gtk_toolbar_get_icon_size ()
gtk_toolbar_get_item_index, gtk_toolbar_get_item_index ()
gtk_toolbar_get_nth_item, gtk_toolbar_get_nth_item ()
gtk_toolbar_get_n_items, gtk_toolbar_get_n_items ()
gtk_toolbar_get_orientation, gtk_toolbar_get_orientation ()
gtk_toolbar_get_relief_style, gtk_toolbar_get_relief_style ()
gtk_toolbar_get_show_arrow, gtk_toolbar_get_show_arrow ()
gtk_toolbar_get_style, gtk_toolbar_get_style ()
gtk_toolbar_get_tooltips, gtk_toolbar_get_tooltips ()
gtk_toolbar_insert, gtk_toolbar_insert ()
gtk_toolbar_insert_element, gtk_toolbar_insert_element ()
gtk_toolbar_insert_item, gtk_toolbar_insert_item ()
gtk_toolbar_insert_space, gtk_toolbar_insert_space ()
gtk_toolbar_insert_stock, gtk_toolbar_insert_stock ()
gtk_toolbar_insert_widget, gtk_toolbar_insert_widget ()
gtk_toolbar_new, gtk_toolbar_new ()
gtk_toolbar_prepend_element, gtk_toolbar_prepend_element ()
gtk_toolbar_prepend_item, gtk_toolbar_prepend_item ()
gtk_toolbar_prepend_space, gtk_toolbar_prepend_space ()
gtk_toolbar_prepend_widget, gtk_toolbar_prepend_widget ()
gtk_toolbar_remove_space, gtk_toolbar_remove_space ()
gtk_toolbar_set_drop_highlight_item, gtk_toolbar_set_drop_highlight_item ()
gtk_toolbar_set_icon_size, gtk_toolbar_set_icon_size ()
gtk_toolbar_set_orientation, gtk_toolbar_set_orientation ()
gtk_toolbar_set_show_arrow, gtk_toolbar_set_show_arrow ()
gtk_toolbar_set_style, gtk_toolbar_set_style ()
gtk_toolbar_set_tooltips, gtk_toolbar_set_tooltips ()
gtk_toolbar_unset_icon_size, gtk_toolbar_unset_icon_size ()
gtk_toolbar_unset_style, gtk_toolbar_unset_style ()
gtk_tooltips_data_get, gtk_tooltips_data_get ()
gtk_tooltips_disable, gtk_tooltips_disable ()
gtk_tooltips_enable, gtk_tooltips_enable ()
gtk_tooltips_force_window, gtk_tooltips_force_window ()
gtk_tooltips_get_info_from_tip_window, gtk_tooltips_get_info_from_tip_window ()
gtk_tooltips_new, gtk_tooltips_new ()
gtk_tooltips_set_delay, gtk_tooltips_set_delay ()
gtk_tooltips_set_tip, gtk_tooltips_set_tip ()
gtk_tool_button_get_icon_name, gtk_tool_button_get_icon_name ()
gtk_tool_button_get_icon_widget, gtk_tool_button_get_icon_widget ()
gtk_tool_button_get_label, gtk_tool_button_get_label ()
gtk_tool_button_get_label_widget, gtk_tool_button_get_label_widget ()
gtk_tool_button_get_stock_id, gtk_tool_button_get_stock_id ()
gtk_tool_button_get_use_underline, gtk_tool_button_get_use_underline ()
gtk_tool_button_new, gtk_tool_button_new ()
gtk_tool_button_new_from_stock, gtk_tool_button_new_from_stock ()
gtk_tool_button_set_icon_name, gtk_tool_button_set_icon_name ()
gtk_tool_button_set_icon_widget, gtk_tool_button_set_icon_widget ()
gtk_tool_button_set_label, gtk_tool_button_set_label ()
gtk_tool_button_set_label_widget, gtk_tool_button_set_label_widget ()
gtk_tool_button_set_stock_id, gtk_tool_button_set_stock_id ()
gtk_tool_button_set_use_underline, gtk_tool_button_set_use_underline ()
gtk_tool_item_get_expand, gtk_tool_item_get_expand ()
gtk_tool_item_get_homogeneous, gtk_tool_item_get_homogeneous ()
gtk_tool_item_get_icon_size, gtk_tool_item_get_icon_size ()
gtk_tool_item_get_is_important, gtk_tool_item_get_is_important ()
gtk_tool_item_get_orientation, gtk_tool_item_get_orientation ()
gtk_tool_item_get_proxy_menu_item, gtk_tool_item_get_proxy_menu_item ()
gtk_tool_item_get_relief_style, gtk_tool_item_get_relief_style ()
gtk_tool_item_get_toolbar_style, gtk_tool_item_get_toolbar_style ()
gtk_tool_item_get_use_drag_window, gtk_tool_item_get_use_drag_window ()
gtk_tool_item_get_visible_horizontal, gtk_tool_item_get_visible_horizontal ()
gtk_tool_item_get_visible_vertical, gtk_tool_item_get_visible_vertical ()
gtk_tool_item_new, gtk_tool_item_new ()
gtk_tool_item_rebuild_menu, gtk_tool_item_rebuild_menu ()
gtk_tool_item_retrieve_proxy_menu_item, gtk_tool_item_retrieve_proxy_menu_item ()
gtk_tool_item_set_expand, gtk_tool_item_set_expand ()
gtk_tool_item_set_homogeneous, gtk_tool_item_set_homogeneous ()
gtk_tool_item_set_is_important, gtk_tool_item_set_is_important ()
gtk_tool_item_set_proxy_menu_item, gtk_tool_item_set_proxy_menu_item ()
gtk_tool_item_set_tooltip, gtk_tool_item_set_tooltip ()
gtk_tool_item_set_use_drag_window, gtk_tool_item_set_use_drag_window ()
gtk_tool_item_set_visible_horizontal, gtk_tool_item_set_visible_horizontal ()
gtk_tool_item_set_visible_vertical, gtk_tool_item_set_visible_vertical ()
gtk_tree_append, gtk_tree_append ()
gtk_tree_child_position, gtk_tree_child_position ()
gtk_tree_clear_items, gtk_tree_clear_items ()
gtk_tree_drag_dest_drag_data_received, gtk_tree_drag_dest_drag_data_received ()
gtk_tree_drag_dest_row_drop_possible, gtk_tree_drag_dest_row_drop_possible ()
gtk_tree_drag_source_drag_data_delete, gtk_tree_drag_source_drag_data_delete ()
gtk_tree_drag_source_drag_data_get, gtk_tree_drag_source_drag_data_get ()
gtk_tree_drag_source_row_draggable, gtk_tree_drag_source_row_draggable ()
gtk_tree_get_row_drag_data, gtk_tree_get_row_drag_data ()
gtk_tree_insert, gtk_tree_insert ()
gtk_tree_item_collapse, gtk_tree_item_collapse ()
gtk_tree_item_deselect, gtk_tree_item_deselect ()
gtk_tree_item_expand, gtk_tree_item_expand ()
gtk_tree_item_new, gtk_tree_item_new ()
gtk_tree_item_new_with_label, gtk_tree_item_new_with_label ()
gtk_tree_item_remove_subtree, gtk_tree_item_remove_subtree ()
gtk_tree_item_select, gtk_tree_item_select ()
gtk_tree_item_set_subtree, gtk_tree_item_set_subtree ()
GTK_TREE_ITEM_SUBTREE, GTK_TREE_ITEM_SUBTREE()
gtk_tree_iter_copy, gtk_tree_iter_copy ()
gtk_tree_iter_free, gtk_tree_iter_free ()
gtk_tree_model_filter_clear_cache, gtk_tree_model_filter_clear_cache ()
gtk_tree_model_filter_convert_child_iter_to_iter, gtk_tree_model_filter_convert_child_iter_to_iter ()
gtk_tree_model_filter_convert_child_path_to_path, gtk_tree_model_filter_convert_child_path_to_path ()
gtk_tree_model_filter_convert_iter_to_child_iter, gtk_tree_model_filter_convert_iter_to_child_iter ()
gtk_tree_model_filter_convert_path_to_child_path, gtk_tree_model_filter_convert_path_to_child_path ()
gtk_tree_model_filter_get_model, gtk_tree_model_filter_get_model ()
gtk_tree_model_filter_new, gtk_tree_model_filter_new ()
gtk_tree_model_filter_refilter, gtk_tree_model_filter_refilter ()
gtk_tree_model_filter_set_modify_func, gtk_tree_model_filter_set_modify_func ()
gtk_tree_model_filter_set_visible_column, gtk_tree_model_filter_set_visible_column ()
gtk_tree_model_filter_set_visible_func, gtk_tree_model_filter_set_visible_func ()
gtk_tree_model_foreach, gtk_tree_model_foreach ()
gtk_tree_model_get, gtk_tree_model_get ()
gtk_tree_model_get_column_type, gtk_tree_model_get_column_type ()
gtk_tree_model_get_flags, gtk_tree_model_get_flags ()
gtk_tree_model_get_iter, gtk_tree_model_get_iter ()
gtk_tree_model_get_iter_first, gtk_tree_model_get_iter_first ()
gtk_tree_model_get_iter_from_string, gtk_tree_model_get_iter_from_string ()
gtk_tree_model_get_iter_root, gtk_tree_model_get_iter_root()
gtk_tree_model_get_n_columns, gtk_tree_model_get_n_columns ()
gtk_tree_model_get_path, gtk_tree_model_get_path ()
gtk_tree_model_get_string_from_iter, gtk_tree_model_get_string_from_iter ()
gtk_tree_model_get_valist, gtk_tree_model_get_valist ()
gtk_tree_model_get_value, gtk_tree_model_get_value ()
gtk_tree_model_iter_children, gtk_tree_model_iter_children ()
gtk_tree_model_iter_has_child, gtk_tree_model_iter_has_child ()
gtk_tree_model_iter_next, gtk_tree_model_iter_next ()
gtk_tree_model_iter_nth_child, gtk_tree_model_iter_nth_child ()
gtk_tree_model_iter_n_children, gtk_tree_model_iter_n_children ()
gtk_tree_model_iter_parent, gtk_tree_model_iter_parent ()
gtk_tree_model_ref_node, gtk_tree_model_ref_node ()
gtk_tree_model_rows_reordered, gtk_tree_model_rows_reordered ()
gtk_tree_model_row_changed, gtk_tree_model_row_changed ()
gtk_tree_model_row_deleted, gtk_tree_model_row_deleted ()
gtk_tree_model_row_has_child_toggled, gtk_tree_model_row_has_child_toggled ()
gtk_tree_model_row_inserted, gtk_tree_model_row_inserted ()
gtk_tree_model_sort_clear_cache, gtk_tree_model_sort_clear_cache ()
gtk_tree_model_sort_convert_child_iter_to_iter, gtk_tree_model_sort_convert_child_iter_to_iter ()
gtk_tree_model_sort_convert_child_path_to_path, gtk_tree_model_sort_convert_child_path_to_path ()
gtk_tree_model_sort_convert_iter_to_child_iter, gtk_tree_model_sort_convert_iter_to_child_iter ()
gtk_tree_model_sort_convert_path_to_child_path, gtk_tree_model_sort_convert_path_to_child_path ()
gtk_tree_model_sort_get_model, gtk_tree_model_sort_get_model ()
gtk_tree_model_sort_iter_is_valid, gtk_tree_model_sort_iter_is_valid ()
gtk_tree_model_sort_new_with_model, gtk_tree_model_sort_new_with_model ()
gtk_tree_model_sort_reset_default_sort_func, gtk_tree_model_sort_reset_default_sort_func ()
gtk_tree_model_unref_node, gtk_tree_model_unref_node ()
gtk_tree_new, gtk_tree_new ()
gtk_tree_path_append_index, gtk_tree_path_append_index ()
gtk_tree_path_compare, gtk_tree_path_compare ()
gtk_tree_path_copy, gtk_tree_path_copy ()
gtk_tree_path_down, gtk_tree_path_down ()
gtk_tree_path_free, gtk_tree_path_free ()
gtk_tree_path_get_depth, gtk_tree_path_get_depth ()
gtk_tree_path_get_indices, gtk_tree_path_get_indices ()
gtk_tree_path_is_ancestor, gtk_tree_path_is_ancestor ()
gtk_tree_path_is_descendant, gtk_tree_path_is_descendant ()
gtk_tree_path_new, gtk_tree_path_new ()
gtk_tree_path_new_first, gtk_tree_path_new_first ()
gtk_tree_path_new_from_indices, gtk_tree_path_new_from_indices ()
gtk_tree_path_new_from_string, gtk_tree_path_new_from_string ()
gtk_tree_path_new_root, gtk_tree_path_new_root()
gtk_tree_path_next, gtk_tree_path_next ()
gtk_tree_path_prepend_index, gtk_tree_path_prepend_index ()
gtk_tree_path_prev, gtk_tree_path_prev ()
gtk_tree_path_to_string, gtk_tree_path_to_string ()
gtk_tree_path_up, gtk_tree_path_up ()
gtk_tree_prepend, gtk_tree_prepend ()
gtk_tree_remove_item, gtk_tree_remove_item ()
gtk_tree_remove_items, gtk_tree_remove_items ()
GTK_TREE_ROOT_TREE, GTK_TREE_ROOT_TREE()
gtk_tree_row_reference_copy, gtk_tree_row_reference_copy ()
gtk_tree_row_reference_deleted, gtk_tree_row_reference_deleted ()
gtk_tree_row_reference_free, gtk_tree_row_reference_free ()
gtk_tree_row_reference_get_model, gtk_tree_row_reference_get_model ()
gtk_tree_row_reference_get_path, gtk_tree_row_reference_get_path ()
gtk_tree_row_reference_inserted, gtk_tree_row_reference_inserted ()
gtk_tree_row_reference_new, gtk_tree_row_reference_new ()
gtk_tree_row_reference_new_proxy, gtk_tree_row_reference_new_proxy ()
gtk_tree_row_reference_reordered, gtk_tree_row_reference_reordered ()
gtk_tree_row_reference_valid, gtk_tree_row_reference_valid ()
gtk_tree_selection_count_selected_rows, gtk_tree_selection_count_selected_rows ()
gtk_tree_selection_get_mode, gtk_tree_selection_get_mode ()
gtk_tree_selection_get_selected, gtk_tree_selection_get_selected ()
gtk_tree_selection_get_selected_rows, gtk_tree_selection_get_selected_rows ()
gtk_tree_selection_get_tree_view, gtk_tree_selection_get_tree_view ()
gtk_tree_selection_get_user_data, gtk_tree_selection_get_user_data ()
gtk_tree_selection_iter_is_selected, gtk_tree_selection_iter_is_selected ()
GTK_TREE_SELECTION_OLD, GTK_TREE_SELECTION_OLD()
gtk_tree_selection_path_is_selected, gtk_tree_selection_path_is_selected ()
gtk_tree_selection_selected_foreach, gtk_tree_selection_selected_foreach ()
gtk_tree_selection_select_all, gtk_tree_selection_select_all ()
gtk_tree_selection_select_iter, gtk_tree_selection_select_iter ()
gtk_tree_selection_select_path, gtk_tree_selection_select_path ()
gtk_tree_selection_select_range, gtk_tree_selection_select_range ()
gtk_tree_selection_set_mode, gtk_tree_selection_set_mode ()
gtk_tree_selection_set_select_function, gtk_tree_selection_set_select_function ()
gtk_tree_selection_unselect_all, gtk_tree_selection_unselect_all ()
gtk_tree_selection_unselect_iter, gtk_tree_selection_unselect_iter ()
gtk_tree_selection_unselect_path, gtk_tree_selection_unselect_path ()
gtk_tree_selection_unselect_range, gtk_tree_selection_unselect_range ()
gtk_tree_select_child, gtk_tree_select_child ()
gtk_tree_select_item, gtk_tree_select_item ()
gtk_tree_set_row_drag_data, gtk_tree_set_row_drag_data ()
gtk_tree_set_selection_mode, gtk_tree_set_selection_mode ()
gtk_tree_set_view_lines, gtk_tree_set_view_lines ()
gtk_tree_set_view_mode, gtk_tree_set_view_mode ()
gtk_tree_sortable_get_sort_column_id, gtk_tree_sortable_get_sort_column_id ()
gtk_tree_sortable_has_default_sort_func, gtk_tree_sortable_has_default_sort_func ()
gtk_tree_sortable_set_default_sort_func, gtk_tree_sortable_set_default_sort_func ()
gtk_tree_sortable_set_sort_column_id, gtk_tree_sortable_set_sort_column_id ()
gtk_tree_sortable_set_sort_func, gtk_tree_sortable_set_sort_func ()
gtk_tree_sortable_sort_column_changed, gtk_tree_sortable_sort_column_changed ()
gtk_tree_store_append, gtk_tree_store_append ()
gtk_tree_store_clear, gtk_tree_store_clear ()
gtk_tree_store_insert, gtk_tree_store_insert ()
gtk_tree_store_insert_after, gtk_tree_store_insert_after ()
gtk_tree_store_insert_before, gtk_tree_store_insert_before ()
gtk_tree_store_insert_with_values, gtk_tree_store_insert_with_values ()
gtk_tree_store_insert_with_valuesv, gtk_tree_store_insert_with_valuesv ()
gtk_tree_store_is_ancestor, gtk_tree_store_is_ancestor ()
gtk_tree_store_iter_depth, gtk_tree_store_iter_depth ()
gtk_tree_store_iter_is_valid, gtk_tree_store_iter_is_valid ()
gtk_tree_store_move_after, gtk_tree_store_move_after ()
gtk_tree_store_move_before, gtk_tree_store_move_before ()
gtk_tree_store_new, gtk_tree_store_new ()
gtk_tree_store_newv, gtk_tree_store_newv ()
gtk_tree_store_prepend, gtk_tree_store_prepend ()
gtk_tree_store_remove, gtk_tree_store_remove ()
gtk_tree_store_reorder, gtk_tree_store_reorder ()
gtk_tree_store_set, gtk_tree_store_set ()
gtk_tree_store_set_column_types, gtk_tree_store_set_column_types ()
gtk_tree_store_set_valist, gtk_tree_store_set_valist ()
gtk_tree_store_set_value, gtk_tree_store_set_value ()
gtk_tree_store_swap, gtk_tree_store_swap ()
gtk_tree_unselect_child, gtk_tree_unselect_child ()
gtk_tree_unselect_item, gtk_tree_unselect_item ()
gtk_tree_view_append_column, gtk_tree_view_append_column ()
gtk_tree_view_collapse_all, gtk_tree_view_collapse_all ()
gtk_tree_view_collapse_row, gtk_tree_view_collapse_row ()
gtk_tree_view_columns_autosize, gtk_tree_view_columns_autosize ()
gtk_tree_view_column_add_attribute, gtk_tree_view_column_add_attribute ()
gtk_tree_view_column_cell_get_position, gtk_tree_view_column_cell_get_position ()
gtk_tree_view_column_cell_get_size, gtk_tree_view_column_cell_get_size ()
gtk_tree_view_column_cell_is_visible, gtk_tree_view_column_cell_is_visible ()
gtk_tree_view_column_cell_set_cell_data, gtk_tree_view_column_cell_set_cell_data ()
gtk_tree_view_column_clear, gtk_tree_view_column_clear ()
gtk_tree_view_column_clear_attributes, gtk_tree_view_column_clear_attributes ()
gtk_tree_view_column_clicked, gtk_tree_view_column_clicked ()
gtk_tree_view_column_focus_cell, gtk_tree_view_column_focus_cell ()
gtk_tree_view_column_get_alignment, gtk_tree_view_column_get_alignment ()
gtk_tree_view_column_get_cell_renderers, gtk_tree_view_column_get_cell_renderers ()
gtk_tree_view_column_get_clickable, gtk_tree_view_column_get_clickable ()
gtk_tree_view_column_get_expand, gtk_tree_view_column_get_expand ()
gtk_tree_view_column_get_fixed_width, gtk_tree_view_column_get_fixed_width ()
gtk_tree_view_column_get_max_width, gtk_tree_view_column_get_max_width ()
gtk_tree_view_column_get_min_width, gtk_tree_view_column_get_min_width ()
gtk_tree_view_column_get_reorderable, gtk_tree_view_column_get_reorderable ()
gtk_tree_view_column_get_resizable, gtk_tree_view_column_get_resizable ()
gtk_tree_view_column_get_sizing, gtk_tree_view_column_get_sizing ()
gtk_tree_view_column_get_sort_column_id, gtk_tree_view_column_get_sort_column_id ()
gtk_tree_view_column_get_sort_indicator, gtk_tree_view_column_get_sort_indicator ()
gtk_tree_view_column_get_sort_order, gtk_tree_view_column_get_sort_order ()
gtk_tree_view_column_get_spacing, gtk_tree_view_column_get_spacing ()
gtk_tree_view_column_get_title, gtk_tree_view_column_get_title ()
gtk_tree_view_column_get_visible, gtk_tree_view_column_get_visible ()
gtk_tree_view_column_get_widget, gtk_tree_view_column_get_widget ()
gtk_tree_view_column_get_width, gtk_tree_view_column_get_width ()
gtk_tree_view_column_new, gtk_tree_view_column_new ()
gtk_tree_view_column_new_with_attributes, gtk_tree_view_column_new_with_attributes ()
gtk_tree_view_column_pack_end, gtk_tree_view_column_pack_end ()
gtk_tree_view_column_pack_start, gtk_tree_view_column_pack_start ()
gtk_tree_view_column_queue_resize, gtk_tree_view_column_queue_resize ()
gtk_tree_view_column_set_alignment, gtk_tree_view_column_set_alignment ()
gtk_tree_view_column_set_attributes, gtk_tree_view_column_set_attributes ()
gtk_tree_view_column_set_cell_data_func, gtk_tree_view_column_set_cell_data_func ()
gtk_tree_view_column_set_clickable, gtk_tree_view_column_set_clickable ()
gtk_tree_view_column_set_expand, gtk_tree_view_column_set_expand ()
gtk_tree_view_column_set_fixed_width, gtk_tree_view_column_set_fixed_width ()
gtk_tree_view_column_set_max_width, gtk_tree_view_column_set_max_width ()
gtk_tree_view_column_set_min_width, gtk_tree_view_column_set_min_width ()
gtk_tree_view_column_set_reorderable, gtk_tree_view_column_set_reorderable ()
gtk_tree_view_column_set_resizable, gtk_tree_view_column_set_resizable ()
gtk_tree_view_column_set_sizing, gtk_tree_view_column_set_sizing ()
gtk_tree_view_column_set_sort_column_id, gtk_tree_view_column_set_sort_column_id ()
gtk_tree_view_column_set_sort_indicator, gtk_tree_view_column_set_sort_indicator ()
gtk_tree_view_column_set_sort_order, gtk_tree_view_column_set_sort_order ()
gtk_tree_view_column_set_spacing, gtk_tree_view_column_set_spacing ()
gtk_tree_view_column_set_title, gtk_tree_view_column_set_title ()
gtk_tree_view_column_set_visible, gtk_tree_view_column_set_visible ()
gtk_tree_view_column_set_widget, gtk_tree_view_column_set_widget ()
gtk_tree_view_create_row_drag_icon, gtk_tree_view_create_row_drag_icon ()
gtk_tree_view_enable_model_drag_dest, gtk_tree_view_enable_model_drag_dest ()
gtk_tree_view_enable_model_drag_source, gtk_tree_view_enable_model_drag_source ()
gtk_tree_view_expand_all, gtk_tree_view_expand_all ()
gtk_tree_view_expand_row, gtk_tree_view_expand_row ()
gtk_tree_view_expand_to_path, gtk_tree_view_expand_to_path ()
gtk_tree_view_get_background_area, gtk_tree_view_get_background_area ()
gtk_tree_view_get_bin_window, gtk_tree_view_get_bin_window ()
gtk_tree_view_get_cell_area, gtk_tree_view_get_cell_area ()
gtk_tree_view_get_column, gtk_tree_view_get_column ()
gtk_tree_view_get_columns, gtk_tree_view_get_columns ()
gtk_tree_view_get_cursor, gtk_tree_view_get_cursor ()
gtk_tree_view_get_dest_row_at_pos, gtk_tree_view_get_dest_row_at_pos ()
gtk_tree_view_get_drag_dest_row, gtk_tree_view_get_drag_dest_row ()
gtk_tree_view_get_enable_search, gtk_tree_view_get_enable_search ()
gtk_tree_view_get_enable_tree_lines, gtk_tree_view_get_enable_tree_lines ()
gtk_tree_view_get_expander_column, gtk_tree_view_get_expander_column ()
gtk_tree_view_get_fixed_height_mode, gtk_tree_view_get_fixed_height_mode ()
gtk_tree_view_get_grid_lines, gtk_tree_view_get_grid_lines ()
gtk_tree_view_get_hadjustment, gtk_tree_view_get_hadjustment ()
gtk_tree_view_get_headers_clickable, gtk_tree_view_get_headers_clickable ()
gtk_tree_view_get_headers_visible, gtk_tree_view_get_headers_visible ()
gtk_tree_view_get_hover_expand, gtk_tree_view_get_hover_expand ()
gtk_tree_view_get_hover_selection, gtk_tree_view_get_hover_selection ()
gtk_tree_view_get_model, gtk_tree_view_get_model ()
gtk_tree_view_get_path_at_pos, gtk_tree_view_get_path_at_pos ()
gtk_tree_view_get_reorderable, gtk_tree_view_get_reorderable ()
gtk_tree_view_get_row_separator_func, gtk_tree_view_get_row_separator_func ()
gtk_tree_view_get_rubber_banding, gtk_tree_view_get_rubber_banding ()
gtk_tree_view_get_rules_hint, gtk_tree_view_get_rules_hint ()
gtk_tree_view_get_search_column, gtk_tree_view_get_search_column ()
gtk_tree_view_get_search_entry, gtk_tree_view_get_search_entry ()
gtk_tree_view_get_search_equal_func, gtk_tree_view_get_search_equal_func ()
gtk_tree_view_get_search_position_func, gtk_tree_view_get_search_position_func ()
gtk_tree_view_get_selection, gtk_tree_view_get_selection ()
gtk_tree_view_get_vadjustment, gtk_tree_view_get_vadjustment ()
gtk_tree_view_get_visible_range, gtk_tree_view_get_visible_range ()
gtk_tree_view_get_visible_rect, gtk_tree_view_get_visible_rect ()
gtk_tree_view_insert_column, gtk_tree_view_insert_column ()
gtk_tree_view_insert_column_with_attributes, gtk_tree_view_insert_column_with_attributes ()
gtk_tree_view_insert_column_with_data_func, gtk_tree_view_insert_column_with_data_func ()
gtk_tree_view_map_expanded_rows, gtk_tree_view_map_expanded_rows ()
gtk_tree_view_move_column_after, gtk_tree_view_move_column_after ()
gtk_tree_view_new, gtk_tree_view_new ()
gtk_tree_view_new_with_model, gtk_tree_view_new_with_model ()
gtk_tree_view_remove_column, gtk_tree_view_remove_column ()
gtk_tree_view_row_activated, gtk_tree_view_row_activated ()
gtk_tree_view_row_expanded, gtk_tree_view_row_expanded ()
gtk_tree_view_scroll_to_cell, gtk_tree_view_scroll_to_cell ()
gtk_tree_view_scroll_to_point, gtk_tree_view_scroll_to_point ()
gtk_tree_view_set_column_drag_function, gtk_tree_view_set_column_drag_function ()
gtk_tree_view_set_cursor, gtk_tree_view_set_cursor ()
gtk_tree_view_set_cursor_on_cell, gtk_tree_view_set_cursor_on_cell ()
gtk_tree_view_set_destroy_count_func, gtk_tree_view_set_destroy_count_func ()
gtk_tree_view_set_drag_dest_row, gtk_tree_view_set_drag_dest_row ()
gtk_tree_view_set_enable_search, gtk_tree_view_set_enable_search ()
gtk_tree_view_set_enable_tree_lines, gtk_tree_view_set_enable_tree_lines ()
gtk_tree_view_set_expander_column, gtk_tree_view_set_expander_column ()
gtk_tree_view_set_fixed_height_mode, gtk_tree_view_set_fixed_height_mode ()
gtk_tree_view_set_grid_lines, gtk_tree_view_set_grid_lines ()
gtk_tree_view_set_hadjustment, gtk_tree_view_set_hadjustment ()
gtk_tree_view_set_headers_clickable, gtk_tree_view_set_headers_clickable ()
gtk_tree_view_set_headers_visible, gtk_tree_view_set_headers_visible ()
gtk_tree_view_set_hover_expand, gtk_tree_view_set_hover_expand ()
gtk_tree_view_set_hover_selection, gtk_tree_view_set_hover_selection ()
gtk_tree_view_set_model, gtk_tree_view_set_model ()
gtk_tree_view_set_reorderable, gtk_tree_view_set_reorderable ()
gtk_tree_view_set_row_separator_func, gtk_tree_view_set_row_separator_func ()
gtk_tree_view_set_rubber_banding, gtk_tree_view_set_rubber_banding ()
gtk_tree_view_set_rules_hint, gtk_tree_view_set_rules_hint ()
gtk_tree_view_set_search_column, gtk_tree_view_set_search_column ()
gtk_tree_view_set_search_entry, gtk_tree_view_set_search_entry ()
gtk_tree_view_set_search_equal_func, gtk_tree_view_set_search_equal_func ()
gtk_tree_view_set_search_position_func, gtk_tree_view_set_search_position_func ()
gtk_tree_view_set_vadjustment, gtk_tree_view_set_vadjustment ()
gtk_tree_view_tree_to_widget_coords, gtk_tree_view_tree_to_widget_coords ()
gtk_tree_view_unset_rows_drag_dest, gtk_tree_view_unset_rows_drag_dest ()
gtk_tree_view_unset_rows_drag_source, gtk_tree_view_unset_rows_drag_source ()
gtk_tree_view_widget_to_tree_coords, gtk_tree_view_widget_to_tree_coords ()
gtk_true, gtk_true ()
gtk_type_class, gtk_type_class ()
GTK_TYPE_CTREE_NODE, GTK_TYPE_CTREE_NODE
gtk_type_enum_find_value, gtk_type_enum_find_value ()
gtk_type_enum_get_values, gtk_type_enum_get_values ()
gtk_type_flags_find_value, gtk_type_flags_find_value ()
gtk_type_flags_get_values, gtk_type_flags_get_values ()
gtk_type_from_name, gtk_type_from_name()
GTK_TYPE_FUNDAMENTAL_LAST, GTK_TYPE_FUNDAMENTAL_LAST
GTK_TYPE_FUNDAMENTAL_MAX, GTK_TYPE_FUNDAMENTAL_MAX
gtk_type_init, gtk_type_init ()
gtk_type_is_a, gtk_type_is_a()
GTK_TYPE_IS_OBJECT, GTK_TYPE_IS_OBJECT()
gtk_type_name, gtk_type_name()
gtk_type_new, gtk_type_new ()
gtk_type_parent, gtk_type_parent()
gtk_type_unique, gtk_type_unique ()
gtk_ui_manager_add_ui, gtk_ui_manager_add_ui ()
gtk_ui_manager_add_ui_from_file, gtk_ui_manager_add_ui_from_file ()
gtk_ui_manager_add_ui_from_string, gtk_ui_manager_add_ui_from_string ()
gtk_ui_manager_ensure_update, gtk_ui_manager_ensure_update ()
gtk_ui_manager_get_accel_group, gtk_ui_manager_get_accel_group ()
gtk_ui_manager_get_action, gtk_ui_manager_get_action ()
gtk_ui_manager_get_action_groups, gtk_ui_manager_get_action_groups ()
gtk_ui_manager_get_add_tearoffs, gtk_ui_manager_get_add_tearoffs ()
gtk_ui_manager_get_toplevels, gtk_ui_manager_get_toplevels ()
gtk_ui_manager_get_ui, gtk_ui_manager_get_ui ()
gtk_ui_manager_get_widget, gtk_ui_manager_get_widget ()
gtk_ui_manager_insert_action_group, gtk_ui_manager_insert_action_group ()
gtk_ui_manager_new, gtk_ui_manager_new ()
gtk_ui_manager_new_merge_id, gtk_ui_manager_new_merge_id ()
gtk_ui_manager_remove_action_group, gtk_ui_manager_remove_action_group ()
gtk_ui_manager_remove_ui, gtk_ui_manager_remove_ui ()
gtk_ui_manager_set_add_tearoffs, gtk_ui_manager_set_add_tearoffs ()
GTK_VALUE_BOOL, GTK_VALUE_BOOL()
GTK_VALUE_BOXED, GTK_VALUE_BOXED()
GTK_VALUE_CHAR, GTK_VALUE_CHAR()
GTK_VALUE_DOUBLE, GTK_VALUE_DOUBLE()
GTK_VALUE_ENUM, GTK_VALUE_ENUM()
GTK_VALUE_FLAGS, GTK_VALUE_FLAGS()
GTK_VALUE_FLOAT, GTK_VALUE_FLOAT()
GTK_VALUE_INT, GTK_VALUE_INT()
GTK_VALUE_LONG, GTK_VALUE_LONG()
GTK_VALUE_OBJECT, GTK_VALUE_OBJECT()
GTK_VALUE_POINTER, GTK_VALUE_POINTER()
GTK_VALUE_SIGNAL, GTK_VALUE_SIGNAL()
GTK_VALUE_STRING, GTK_VALUE_STRING()
GTK_VALUE_UCHAR, GTK_VALUE_UCHAR()
GTK_VALUE_UINT, GTK_VALUE_UINT()
GTK_VALUE_ULONG, GTK_VALUE_ULONG()
gtk_vbox_new, gtk_vbox_new ()
gtk_vbutton_box_get_layout_default, gtk_vbutton_box_get_layout_default ()
gtk_vbutton_box_get_spacing_default, gtk_vbutton_box_get_spacing_default ()
gtk_vbutton_box_new, gtk_vbutton_box_new ()
gtk_vbutton_box_set_layout_default, gtk_vbutton_box_set_layout_default ()
gtk_vbutton_box_set_spacing_default, gtk_vbutton_box_set_spacing_default ()
gtk_viewport_get_hadjustment, gtk_viewport_get_hadjustment ()
gtk_viewport_get_shadow_type, gtk_viewport_get_shadow_type ()
gtk_viewport_get_vadjustment, gtk_viewport_get_vadjustment ()
gtk_viewport_new, gtk_viewport_new ()
gtk_viewport_set_hadjustment, gtk_viewport_set_hadjustment ()
gtk_viewport_set_shadow_type, gtk_viewport_set_shadow_type ()
gtk_viewport_set_vadjustment, gtk_viewport_set_vadjustment ()
gtk_vpaned_new, gtk_vpaned_new ()
gtk_vruler_new, gtk_vruler_new ()
gtk_vscale_new, gtk_vscale_new ()
gtk_vscale_new_with_range, gtk_vscale_new_with_range ()
gtk_vscrollbar_new, gtk_vscrollbar_new ()
gtk_vseparator_new, gtk_vseparator_new ()
gtk_widget_activate, gtk_widget_activate ()
gtk_widget_add_accelerator, gtk_widget_add_accelerator ()
gtk_widget_add_events, gtk_widget_add_events ()
gtk_widget_add_mnemonic_label, gtk_widget_add_mnemonic_label ()
GTK_WIDGET_APP_PAINTABLE, GTK_WIDGET_APP_PAINTABLE()
gtk_widget_can_activate_accel, gtk_widget_can_activate_accel ()
GTK_WIDGET_CAN_DEFAULT, GTK_WIDGET_CAN_DEFAULT()
GTK_WIDGET_CAN_FOCUS, GTK_WIDGET_CAN_FOCUS()
gtk_widget_child_focus, gtk_widget_child_focus ()
gtk_widget_child_notify, gtk_widget_child_notify ()
gtk_widget_class_find_style_property, gtk_widget_class_find_style_property ()
gtk_widget_class_install_style_property, gtk_widget_class_install_style_property ()
gtk_widget_class_install_style_property_parser, gtk_widget_class_install_style_property_parser ()
gtk_widget_class_list_style_properties, gtk_widget_class_list_style_properties ()
gtk_widget_class_path, gtk_widget_class_path ()
GTK_WIDGET_COMPOSITE_CHILD, GTK_WIDGET_COMPOSITE_CHILD()
gtk_widget_create_pango_context, gtk_widget_create_pango_context ()
gtk_widget_create_pango_layout, gtk_widget_create_pango_layout ()
gtk_widget_destroy, gtk_widget_destroy ()
gtk_widget_destroyed, gtk_widget_destroyed ()
GTK_WIDGET_DOUBLE_BUFFERED, GTK_WIDGET_DOUBLE_BUFFERED()
gtk_widget_draw, gtk_widget_draw ()
GTK_WIDGET_DRAWABLE, GTK_WIDGET_DRAWABLE()
gtk_widget_ensure_style, gtk_widget_ensure_style ()
gtk_widget_event, gtk_widget_event ()
GTK_WIDGET_FLAGS, GTK_WIDGET_FLAGS()
gtk_widget_freeze_child_notify, gtk_widget_freeze_child_notify ()
gtk_widget_get_accessible, gtk_widget_get_accessible ()
gtk_widget_get_action, gtk_widget_get_action ()
gtk_widget_get_ancestor, gtk_widget_get_ancestor ()
gtk_widget_get_child_requisition, gtk_widget_get_child_requisition ()
gtk_widget_get_child_visible, gtk_widget_get_child_visible ()
gtk_widget_get_clipboard, gtk_widget_get_clipboard ()
gtk_widget_get_colormap, gtk_widget_get_colormap ()
gtk_widget_get_composite_name, gtk_widget_get_composite_name ()
gtk_widget_get_default_colormap, gtk_widget_get_default_colormap ()
gtk_widget_get_default_direction, gtk_widget_get_default_direction ()
gtk_widget_get_default_style, gtk_widget_get_default_style ()
gtk_widget_get_default_visual, gtk_widget_get_default_visual ()
gtk_widget_get_direction, gtk_widget_get_direction ()
gtk_widget_get_display, gtk_widget_get_display ()
gtk_widget_get_events, gtk_widget_get_events ()
gtk_widget_get_extension_events, gtk_widget_get_extension_events ()
gtk_widget_get_modifier_style, gtk_widget_get_modifier_style ()
gtk_widget_get_name, gtk_widget_get_name ()
gtk_widget_get_no_show_all, gtk_widget_get_no_show_all ()
gtk_widget_get_pango_context, gtk_widget_get_pango_context ()
gtk_widget_get_parent, gtk_widget_get_parent ()
gtk_widget_get_parent_window, gtk_widget_get_parent_window ()
gtk_widget_get_pointer, gtk_widget_get_pointer ()
gtk_widget_get_root_window, gtk_widget_get_root_window ()
gtk_widget_get_screen, gtk_widget_get_screen ()
gtk_widget_get_settings, gtk_widget_get_settings ()
gtk_widget_get_size_request, gtk_widget_get_size_request ()
gtk_widget_get_style, gtk_widget_get_style ()
gtk_widget_get_toplevel, gtk_widget_get_toplevel ()
gtk_widget_get_visual, gtk_widget_get_visual ()
gtk_widget_grab_default, gtk_widget_grab_default ()
gtk_widget_grab_focus, gtk_widget_grab_focus ()
GTK_WIDGET_HAS_DEFAULT, GTK_WIDGET_HAS_DEFAULT()
GTK_WIDGET_HAS_FOCUS, GTK_WIDGET_HAS_FOCUS()
GTK_WIDGET_HAS_GRAB, GTK_WIDGET_HAS_GRAB()
gtk_widget_has_screen, gtk_widget_has_screen ()
gtk_widget_hide, gtk_widget_hide ()
gtk_widget_hide_all, gtk_widget_hide_all ()
gtk_widget_hide_on_delete, gtk_widget_hide_on_delete ()
gtk_widget_input_shape_combine_mask, gtk_widget_input_shape_combine_mask ()
gtk_widget_intersect, gtk_widget_intersect ()
gtk_widget_is_ancestor, gtk_widget_is_ancestor ()
gtk_widget_is_composited, gtk_widget_is_composited ()
gtk_widget_is_focus, gtk_widget_is_focus ()
GTK_WIDGET_IS_SENSITIVE, GTK_WIDGET_IS_SENSITIVE()
gtk_widget_list_accel_closures, gtk_widget_list_accel_closures ()
gtk_widget_list_mnemonic_labels, gtk_widget_list_mnemonic_labels ()
gtk_widget_map, gtk_widget_map ()
GTK_WIDGET_MAPPED, GTK_WIDGET_MAPPED()
gtk_widget_mnemonic_activate, gtk_widget_mnemonic_activate ()
gtk_widget_modify_base, gtk_widget_modify_base ()
gtk_widget_modify_bg, gtk_widget_modify_bg ()
gtk_widget_modify_fg, gtk_widget_modify_fg ()
gtk_widget_modify_font, gtk_widget_modify_font ()
gtk_widget_modify_style, gtk_widget_modify_style ()
gtk_widget_modify_text, gtk_widget_modify_text ()
gtk_widget_new, gtk_widget_new ()
GTK_WIDGET_NO_WINDOW, GTK_WIDGET_NO_WINDOW()
GTK_WIDGET_PARENT_SENSITIVE, GTK_WIDGET_PARENT_SENSITIVE()
gtk_widget_path, gtk_widget_path ()
gtk_widget_pop_colormap, gtk_widget_pop_colormap ()
gtk_widget_pop_composite_child, gtk_widget_pop_composite_child ()
gtk_widget_pop_visual, gtk_widget_pop_visual()
gtk_widget_push_colormap, gtk_widget_push_colormap ()
gtk_widget_push_composite_child, gtk_widget_push_composite_child ()
gtk_widget_push_visual, gtk_widget_push_visual()
gtk_widget_queue_clear, gtk_widget_queue_clear ()
gtk_widget_queue_clear_area, gtk_widget_queue_clear_area ()
gtk_widget_queue_draw, gtk_widget_queue_draw ()
gtk_widget_queue_draw_area, gtk_widget_queue_draw_area ()
gtk_widget_queue_resize, gtk_widget_queue_resize ()
gtk_widget_queue_resize_no_redraw, gtk_widget_queue_resize_no_redraw ()
GTK_WIDGET_RC_STYLE, GTK_WIDGET_RC_STYLE()
gtk_widget_realize, gtk_widget_realize ()
GTK_WIDGET_REALIZED, GTK_WIDGET_REALIZED()
GTK_WIDGET_RECEIVES_DEFAULT, GTK_WIDGET_RECEIVES_DEFAULT()
gtk_widget_ref, gtk_widget_ref ()
gtk_widget_region_intersect, gtk_widget_region_intersect ()
gtk_widget_remove_accelerator, gtk_widget_remove_accelerator ()
gtk_widget_remove_mnemonic_label, gtk_widget_remove_mnemonic_label ()
gtk_widget_render_icon, gtk_widget_render_icon ()
gtk_widget_reparent, gtk_widget_reparent ()
gtk_widget_reset_rc_styles, gtk_widget_reset_rc_styles ()
gtk_widget_reset_shapes, gtk_widget_reset_shapes ()
gtk_widget_restore_default_style, gtk_widget_restore_default_style()
GTK_WIDGET_SAVED_STATE, GTK_WIDGET_SAVED_STATE()
gtk_widget_send_expose, gtk_widget_send_expose ()
GTK_WIDGET_SENSITIVE, GTK_WIDGET_SENSITIVE()
gtk_widget_set, gtk_widget_set ()
gtk_widget_set_accel_path, gtk_widget_set_accel_path ()
gtk_widget_set_app_paintable, gtk_widget_set_app_paintable ()
gtk_widget_set_child_visible, gtk_widget_set_child_visible ()
gtk_widget_set_colormap, gtk_widget_set_colormap ()
gtk_widget_set_composite_name, gtk_widget_set_composite_name ()
gtk_widget_set_default_colormap, gtk_widget_set_default_colormap ()
gtk_widget_set_default_direction, gtk_widget_set_default_direction ()
gtk_widget_set_default_visual, gtk_widget_set_default_visual()
gtk_widget_set_direction, gtk_widget_set_direction ()
gtk_widget_set_double_buffered, gtk_widget_set_double_buffered ()
gtk_widget_set_events, gtk_widget_set_events ()
gtk_widget_set_extension_events, gtk_widget_set_extension_events ()
GTK_WIDGET_SET_FLAGS, GTK_WIDGET_SET_FLAGS()
gtk_widget_set_name, gtk_widget_set_name ()
gtk_widget_set_no_show_all, gtk_widget_set_no_show_all ()
gtk_widget_set_parent, gtk_widget_set_parent ()
gtk_widget_set_parent_window, gtk_widget_set_parent_window ()
gtk_widget_set_rc_style, gtk_widget_set_rc_style()
gtk_widget_set_redraw_on_allocate, gtk_widget_set_redraw_on_allocate ()
gtk_widget_set_scroll_adjustments, gtk_widget_set_scroll_adjustments ()
gtk_widget_set_sensitive, gtk_widget_set_sensitive ()
gtk_widget_set_size_request, gtk_widget_set_size_request ()
gtk_widget_set_state, gtk_widget_set_state ()
gtk_widget_set_style, gtk_widget_set_style ()
gtk_widget_set_uposition, gtk_widget_set_uposition ()
gtk_widget_set_usize, gtk_widget_set_usize ()
gtk_widget_set_visual, gtk_widget_set_visual()
gtk_widget_shape_combine_mask, gtk_widget_shape_combine_mask ()
gtk_widget_show, gtk_widget_show ()
gtk_widget_show_all, gtk_widget_show_all ()
gtk_widget_show_now, gtk_widget_show_now ()
gtk_widget_size_allocate, gtk_widget_size_allocate ()
gtk_widget_size_request, gtk_widget_size_request ()
GTK_WIDGET_STATE, GTK_WIDGET_STATE()
gtk_widget_style_get, gtk_widget_style_get ()
gtk_widget_style_get_property, gtk_widget_style_get_property ()
gtk_widget_style_get_valist, gtk_widget_style_get_valist ()
gtk_widget_thaw_child_notify, gtk_widget_thaw_child_notify ()
GTK_WIDGET_TOPLEVEL, GTK_WIDGET_TOPLEVEL()
gtk_widget_translate_coordinates, gtk_widget_translate_coordinates ()
GTK_WIDGET_TYPE, GTK_WIDGET_TYPE()
gtk_widget_unmap, gtk_widget_unmap ()
gtk_widget_unparent, gtk_widget_unparent ()
gtk_widget_unrealize, gtk_widget_unrealize ()
gtk_widget_unref, gtk_widget_unref ()
GTK_WIDGET_UNSET_FLAGS, GTK_WIDGET_UNSET_FLAGS()
GTK_WIDGET_VISIBLE, GTK_WIDGET_VISIBLE()
gtk_window_activate_default, gtk_window_activate_default ()
gtk_window_activate_focus, gtk_window_activate_focus ()
gtk_window_activate_key, gtk_window_activate_key ()
gtk_window_add_accel_group, gtk_window_add_accel_group ()
gtk_window_add_mnemonic, gtk_window_add_mnemonic ()
gtk_window_begin_move_drag, gtk_window_begin_move_drag ()
gtk_window_begin_resize_drag, gtk_window_begin_resize_drag ()
gtk_window_deiconify, gtk_window_deiconify ()
gtk_window_fullscreen, gtk_window_fullscreen ()
gtk_window_get_accept_focus, gtk_window_get_accept_focus ()
gtk_window_get_decorated, gtk_window_get_decorated ()
gtk_window_get_default_icon_list, gtk_window_get_default_icon_list ()
gtk_window_get_default_size, gtk_window_get_default_size ()
gtk_window_get_deletable, gtk_window_get_deletable ()
gtk_window_get_destroy_with_parent, gtk_window_get_destroy_with_parent ()
gtk_window_get_focus, gtk_window_get_focus ()
gtk_window_get_focus_on_map, gtk_window_get_focus_on_map ()
gtk_window_get_frame_dimensions, gtk_window_get_frame_dimensions ()
gtk_window_get_gravity, gtk_window_get_gravity ()
gtk_window_get_group, gtk_window_get_group ()
gtk_window_get_has_frame, gtk_window_get_has_frame ()
gtk_window_get_icon, gtk_window_get_icon ()
gtk_window_get_icon_list, gtk_window_get_icon_list ()
gtk_window_get_icon_name, gtk_window_get_icon_name ()
gtk_window_get_mnemonic_modifier, gtk_window_get_mnemonic_modifier ()
gtk_window_get_modal, gtk_window_get_modal ()
gtk_window_get_position, gtk_window_get_position ()
gtk_window_get_resizable, gtk_window_get_resizable ()
gtk_window_get_role, gtk_window_get_role ()
gtk_window_get_screen, gtk_window_get_screen ()
gtk_window_get_size, gtk_window_get_size ()
gtk_window_get_skip_pager_hint, gtk_window_get_skip_pager_hint ()
gtk_window_get_skip_taskbar_hint, gtk_window_get_skip_taskbar_hint ()
gtk_window_get_title, gtk_window_get_title ()
gtk_window_get_transient_for, gtk_window_get_transient_for ()
gtk_window_get_type_hint, gtk_window_get_type_hint ()
gtk_window_get_urgency_hint, gtk_window_get_urgency_hint ()
gtk_window_group_add_window, gtk_window_group_add_window ()
gtk_window_group_new, gtk_window_group_new ()
gtk_window_group_remove_window, gtk_window_group_remove_window ()
gtk_window_has_toplevel_focus, gtk_window_has_toplevel_focus ()
gtk_window_iconify, gtk_window_iconify ()
gtk_window_is_active, gtk_window_is_active ()
gtk_window_list_toplevels, gtk_window_list_toplevels ()
gtk_window_maximize, gtk_window_maximize ()
gtk_window_mnemonic_activate, gtk_window_mnemonic_activate ()
gtk_window_move, gtk_window_move ()
gtk_window_new, gtk_window_new ()
gtk_window_parse_geometry, gtk_window_parse_geometry ()
gtk_window_position, gtk_window_position
gtk_window_present, gtk_window_present ()
gtk_window_present_with_time, gtk_window_present_with_time ()
gtk_window_propagate_key_event, gtk_window_propagate_key_event ()
gtk_window_remove_accel_group, gtk_window_remove_accel_group ()
gtk_window_remove_mnemonic, gtk_window_remove_mnemonic ()
gtk_window_reshow_with_initial_size, gtk_window_reshow_with_initial_size ()
gtk_window_resize, gtk_window_resize ()
gtk_window_set_accept_focus, gtk_window_set_accept_focus ()
gtk_window_set_auto_startup_notification, gtk_window_set_auto_startup_notification ()
gtk_window_set_decorated, gtk_window_set_decorated ()
gtk_window_set_default, gtk_window_set_default ()
gtk_window_set_default_icon, gtk_window_set_default_icon ()
gtk_window_set_default_icon_from_file, gtk_window_set_default_icon_from_file ()
gtk_window_set_default_icon_list, gtk_window_set_default_icon_list ()
gtk_window_set_default_icon_name, gtk_window_set_default_icon_name ()
gtk_window_set_default_size, gtk_window_set_default_size ()
gtk_window_set_deletable, gtk_window_set_deletable ()
gtk_window_set_destroy_with_parent, gtk_window_set_destroy_with_parent ()
gtk_window_set_focus, gtk_window_set_focus ()
gtk_window_set_focus_on_map, gtk_window_set_focus_on_map ()
gtk_window_set_frame_dimensions, gtk_window_set_frame_dimensions ()
gtk_window_set_geometry_hints, gtk_window_set_geometry_hints ()
gtk_window_set_gravity, gtk_window_set_gravity ()
gtk_window_set_has_frame, gtk_window_set_has_frame ()
gtk_window_set_icon, gtk_window_set_icon ()
gtk_window_set_icon_from_file, gtk_window_set_icon_from_file ()
gtk_window_set_icon_list, gtk_window_set_icon_list ()
gtk_window_set_icon_name, gtk_window_set_icon_name ()
gtk_window_set_keep_above, gtk_window_set_keep_above ()
gtk_window_set_keep_below, gtk_window_set_keep_below ()
gtk_window_set_mnemonic_modifier, gtk_window_set_mnemonic_modifier ()
gtk_window_set_modal, gtk_window_set_modal ()
gtk_window_set_policy, gtk_window_set_policy ()
gtk_window_set_position, gtk_window_set_position ()
gtk_window_set_resizable, gtk_window_set_resizable ()
gtk_window_set_role, gtk_window_set_role ()
gtk_window_set_screen, gtk_window_set_screen ()
gtk_window_set_skip_pager_hint, gtk_window_set_skip_pager_hint ()
gtk_window_set_skip_taskbar_hint, gtk_window_set_skip_taskbar_hint ()
gtk_window_set_title, gtk_window_set_title ()
gtk_window_set_transient_for, gtk_window_set_transient_for ()
gtk_window_set_type_hint, gtk_window_set_type_hint ()
gtk_window_set_urgency_hint, gtk_window_set_urgency_hint ()
gtk_window_set_wmclass, gtk_window_set_wmclass ()
gtk_window_stick, gtk_window_stick ()
gtk_window_unfullscreen, gtk_window_unfullscreen ()
gtk_window_unmaximize, gtk_window_unmaximize ()
gtk_window_unstick, gtk_window_unstick ()


Index of deprecated symbols

G

GtkArg, GtkArg
GtkArgFlags, enum GtkArgFlags
GtkButtonAction, enum GtkButtonAction
GtkCell, GtkCell
GtkCellPixmap, GtkCellPixmap
GtkCellPixText, GtkCellPixText
GtkCellText, GtkCellText
GtkCellType, enum GtkCellType
GtkCellWidget, GtkCellWidget
GtkClassInitFunc, GtkClassInitFunc
GtkCList, GtkCList
GtkCListCellInfo, GtkCListCellInfo
GtkCListColumn, GtkCListColumn
GtkCListCompareFunc, GtkCListCompareFunc ()
GtkCListDestInfo, GtkCListDestInfo
GtkCListDragPos, enum GtkCListDragPos
GtkCListRow, GtkCListRow
GtkCombo, GtkCombo
GtkCTree, GtkCTree
GtkCTreeCompareDragFunc, GtkCTreeCompareDragFunc ()
GtkCTreeExpanderStyle, enum GtkCTreeExpanderStyle
GtkCTreeExpansionType, enum GtkCTreeExpansionType
GtkCTreeFunc, GtkCTreeFunc ()
GtkCTreeGNodeFunc, GtkCTreeGNodeFunc ()
GtkCTreeLineStyle, enum GtkCTreeLineStyle
GtkCTreeNode, GtkCTreeNode
GtkCTreePos, enum GtkCTreePos
GtkCTreeRow, GtkCTreeRow
GtkDitherInfo, union GtkDitherInfo
GtkEnumValue, GtkEnumValue
GtkFlagValue, GtkFlagValue
GtkFundamentalType, GtkFundamentalType
GtkItemFactory, GtkItemFactory
GtkItemFactoryCallback, GtkItemFactoryCallback ()
GtkItemFactoryCallback1, GtkItemFactoryCallback1 ()
GtkItemFactoryCallback2, GtkItemFactoryCallback2 ()
GtkItemFactoryEntry, GtkItemFactoryEntry
GtkItemFactoryItem, GtkItemFactoryItem
GtkList, GtkList
GtkListItem, GtkListItem
GtkMatchType, enum GtkMatchType
GtkObjectInitFunc, GtkObjectInitFunc
GtkOldEditable, GtkOldEditable
GtkOptionMenu, GtkOptionMenu
GtkPixmap, GtkPixmap
GtkPreview, GtkPreview
GtkPreviewInfo, GtkPreviewInfo
GtkPreviewType, enum GtkPreviewType
GtkPrintFunc, GtkPrintFunc ()
GtkPropertyMark, GtkPropertyMark
GtkSideType, enum GtkSideType
GtkSignalMarshaller, GtkSignalMarshaller
GtkSignalRunType, enum GtkSignalRunType
GtkSubmenuDirection, enum GtkSubmenuDirection
GtkSubmenuPlacement, enum GtkSubmenuPlacement
GtkText, GtkText
GtkTextFont, GtkTextFont
GtkTextFunction, GtkTextFunction ()
GtkTipsQuery, GtkTipsQuery
GtkToolbarChild, GtkToolbarChild
GtkToolbarChildType, enum GtkToolbarChildType
GtkTree, GtkTree
GtkTreeItem, GtkTreeItem
GtkTreeViewMode, enum GtkTreeViewMode
GtkTypeClass, GtkTypeClass
GtkTypeInfo, GtkTypeInfo
GtkTypeObject, GtkTypeObject
gtk_accel_group_ref, gtk_accel_group_ref
gtk_accel_group_unref, gtk_accel_group_unref
gtk_button_box_get_child_ipadding, gtk_button_box_get_child_ipadding ()
gtk_button_box_get_child_size, gtk_button_box_get_child_size ()
gtk_button_box_get_spacing, gtk_button_box_get_spacing()
gtk_button_box_set_child_ipadding, gtk_button_box_set_child_ipadding ()
gtk_button_box_set_child_size, gtk_button_box_set_child_size ()
gtk_button_box_set_spacing, gtk_button_box_set_spacing()
gtk_calendar_display_options, gtk_calendar_display_options ()
gtk_calendar_freeze, gtk_calendar_freeze ()
gtk_calendar_thaw, gtk_calendar_thaw ()
GTK_CELL_PIXMAP, GTK_CELL_PIXMAP()
GTK_CELL_PIXTEXT, GTK_CELL_PIXTEXT()
gtk_cell_renderer_editing_canceled, gtk_cell_renderer_editing_canceled ()
GTK_CELL_TEXT, GTK_CELL_TEXT()
GTK_CELL_WIDGET, GTK_CELL_WIDGET()
gtk_check_menu_item_set_show_toggle, gtk_check_menu_item_set_show_toggle ()
gtk_check_menu_item_set_state, gtk_check_menu_item_set_state
GTK_CLASS_NAME, GTK_CLASS_NAME()
GTK_CLASS_TYPE, GTK_CLASS_TYPE()
GTK_CLIST_ADD_MODE, GTK_CLIST_ADD_MODE()
gtk_clist_append, gtk_clist_append ()
GTK_CLIST_AUTO_RESIZE_BLOCKED, GTK_CLIST_AUTO_RESIZE_BLOCKED()
GTK_CLIST_AUTO_SORT, GTK_CLIST_AUTO_SORT()
gtk_clist_clear, gtk_clist_clear ()
gtk_clist_columns_autosize, gtk_clist_columns_autosize ()
gtk_clist_column_titles_active, gtk_clist_column_titles_active ()
gtk_clist_column_titles_hide, gtk_clist_column_titles_hide ()
gtk_clist_column_titles_passive, gtk_clist_column_titles_passive ()
gtk_clist_column_titles_show, gtk_clist_column_titles_show ()
gtk_clist_column_title_active, gtk_clist_column_title_active ()
gtk_clist_column_title_passive, gtk_clist_column_title_passive ()
GTK_CLIST_DRAW_DRAG_LINE, GTK_CLIST_DRAW_DRAG_LINE()
GTK_CLIST_DRAW_DRAG_RECT, GTK_CLIST_DRAW_DRAG_RECT()
gtk_clist_find_row_from_data, gtk_clist_find_row_from_data ()
GTK_CLIST_FLAGS, GTK_CLIST_FLAGS()
gtk_clist_freeze, gtk_clist_freeze ()
gtk_clist_get_cell_style, gtk_clist_get_cell_style ()
gtk_clist_get_cell_type, gtk_clist_get_cell_type ()
gtk_clist_get_column_title, gtk_clist_get_column_title ()
gtk_clist_get_column_widget, gtk_clist_get_column_widget ()
gtk_clist_get_hadjustment, gtk_clist_get_hadjustment ()
gtk_clist_get_pixmap, gtk_clist_get_pixmap ()
gtk_clist_get_pixtext, gtk_clist_get_pixtext ()
gtk_clist_get_row_data, gtk_clist_get_row_data ()
gtk_clist_get_row_style, gtk_clist_get_row_style ()
gtk_clist_get_selectable, gtk_clist_get_selectable ()
gtk_clist_get_selection_info, gtk_clist_get_selection_info ()
gtk_clist_get_text, gtk_clist_get_text ()
gtk_clist_get_vadjustment, gtk_clist_get_vadjustment ()
gtk_clist_insert, gtk_clist_insert ()
GTK_CLIST_IN_DRAG, GTK_CLIST_IN_DRAG()
gtk_clist_moveto, gtk_clist_moveto ()
gtk_clist_new, gtk_clist_new ()
gtk_clist_new_with_titles, gtk_clist_new_with_titles ()
gtk_clist_optimal_column_width, gtk_clist_optimal_column_width ()
gtk_clist_prepend, gtk_clist_prepend ()
gtk_clist_remove, gtk_clist_remove ()
GTK_CLIST_REORDERABLE, GTK_CLIST_REORDERABLE()
GTK_CLIST_ROW, GTK_CLIST_ROW()
GTK_CLIST_ROW_HEIGHT_SET, GTK_CLIST_ROW_HEIGHT_SET()
gtk_clist_row_is_visible, gtk_clist_row_is_visible ()
gtk_clist_row_move, gtk_clist_row_move ()
gtk_clist_select_all, gtk_clist_select_all ()
gtk_clist_select_row, gtk_clist_select_row ()
gtk_clist_set_auto_sort, gtk_clist_set_auto_sort ()
gtk_clist_set_background, gtk_clist_set_background ()
gtk_clist_set_button_actions, gtk_clist_set_button_actions ()
gtk_clist_set_cell_style, gtk_clist_set_cell_style ()
gtk_clist_set_column_auto_resize, gtk_clist_set_column_auto_resize ()
gtk_clist_set_column_justification, gtk_clist_set_column_justification ()
gtk_clist_set_column_max_width, gtk_clist_set_column_max_width ()
gtk_clist_set_column_min_width, gtk_clist_set_column_min_width ()
gtk_clist_set_column_resizeable, gtk_clist_set_column_resizeable ()
gtk_clist_set_column_title, gtk_clist_set_column_title ()
gtk_clist_set_column_visibility, gtk_clist_set_column_visibility ()
gtk_clist_set_column_widget, gtk_clist_set_column_widget ()
gtk_clist_set_column_width, gtk_clist_set_column_width ()
gtk_clist_set_compare_func, gtk_clist_set_compare_func ()
GTK_CLIST_SET_FLAG, GTK_CLIST_SET_FLAG()
gtk_clist_set_foreground, gtk_clist_set_foreground ()
gtk_clist_set_hadjustment, gtk_clist_set_hadjustment ()
gtk_clist_set_pixmap, gtk_clist_set_pixmap ()
gtk_clist_set_pixtext, gtk_clist_set_pixtext ()
gtk_clist_set_reorderable, gtk_clist_set_reorderable ()
gtk_clist_set_row_data, gtk_clist_set_row_data ()
gtk_clist_set_row_data_full, gtk_clist_set_row_data_full ()
gtk_clist_set_row_height, gtk_clist_set_row_height ()
gtk_clist_set_row_style, gtk_clist_set_row_style ()
gtk_clist_set_selectable, gtk_clist_set_selectable ()
gtk_clist_set_selection_mode, gtk_clist_set_selection_mode ()
gtk_clist_set_shadow_type, gtk_clist_set_shadow_type ()
gtk_clist_set_shift, gtk_clist_set_shift ()
gtk_clist_set_sort_column, gtk_clist_set_sort_column ()
gtk_clist_set_sort_type, gtk_clist_set_sort_type ()
gtk_clist_set_text, gtk_clist_set_text ()
gtk_clist_set_use_drag_icons, gtk_clist_set_use_drag_icons ()
gtk_clist_set_vadjustment, gtk_clist_set_vadjustment ()
GTK_CLIST_SHOW_TITLES, GTK_CLIST_SHOW_TITLES()
gtk_clist_sort, gtk_clist_sort ()
gtk_clist_swap_rows, gtk_clist_swap_rows ()
gtk_clist_thaw, gtk_clist_thaw ()
gtk_clist_undo_selection, gtk_clist_undo_selection ()
gtk_clist_unselect_all, gtk_clist_unselect_all ()
gtk_clist_unselect_row, gtk_clist_unselect_row ()
GTK_CLIST_UNSET_FLAG, GTK_CLIST_UNSET_FLAG()
GTK_CLIST_USE_DRAG_ICONS, GTK_CLIST_USE_DRAG_ICONS()
gtk_color_selection_get_color, gtk_color_selection_get_color ()
gtk_color_selection_set_change_palette_hook, gtk_color_selection_set_change_palette_hook ()
gtk_color_selection_set_color, gtk_color_selection_set_color ()
gtk_color_selection_set_update_policy, gtk_color_selection_set_update_policy ()
gtk_combo_disable_activate, gtk_combo_disable_activate ()
gtk_combo_new, gtk_combo_new ()
gtk_combo_set_case_sensitive, gtk_combo_set_case_sensitive ()
gtk_combo_set_item_string, gtk_combo_set_item_string ()
gtk_combo_set_popdown_strings, gtk_combo_set_popdown_strings ()
gtk_combo_set_use_arrows, gtk_combo_set_use_arrows ()
gtk_combo_set_use_arrows_always, gtk_combo_set_use_arrows_always ()
gtk_combo_set_value_in_list, gtk_combo_set_value_in_list ()
gtk_container_border_width, gtk_container_border_width
gtk_container_children, gtk_container_children
gtk_container_foreach_full, gtk_container_foreach_full ()
gtk_ctree_collapse, gtk_ctree_collapse ()
gtk_ctree_collapse_recursive, gtk_ctree_collapse_recursive ()
gtk_ctree_collapse_to_depth, gtk_ctree_collapse_to_depth ()
gtk_ctree_expand, gtk_ctree_expand ()
gtk_ctree_expand_recursive, gtk_ctree_expand_recursive ()
gtk_ctree_expand_to_depth, gtk_ctree_expand_to_depth ()
gtk_ctree_export_to_gnode, gtk_ctree_export_to_gnode ()
gtk_ctree_find, gtk_ctree_find ()
gtk_ctree_find_all_by_row_data, gtk_ctree_find_all_by_row_data ()
gtk_ctree_find_all_by_row_data_custom, gtk_ctree_find_all_by_row_data_custom ()
gtk_ctree_find_by_row_data, gtk_ctree_find_by_row_data ()
gtk_ctree_find_by_row_data_custom, gtk_ctree_find_by_row_data_custom ()
gtk_ctree_find_node_ptr, gtk_ctree_find_node_ptr ()
GTK_CTREE_FUNC, GTK_CTREE_FUNC()
gtk_ctree_get_node_info, gtk_ctree_get_node_info ()
gtk_ctree_insert_gnode, gtk_ctree_insert_gnode ()
gtk_ctree_insert_node, gtk_ctree_insert_node ()
gtk_ctree_is_ancestor, gtk_ctree_is_ancestor ()
gtk_ctree_is_hot_spot, gtk_ctree_is_hot_spot ()
gtk_ctree_is_viewable, gtk_ctree_is_viewable ()
gtk_ctree_last, gtk_ctree_last ()
gtk_ctree_move, gtk_ctree_move ()
gtk_ctree_new, gtk_ctree_new ()
gtk_ctree_new_with_titles, gtk_ctree_new_with_titles ()
GTK_CTREE_NODE, GTK_CTREE_NODE()
gtk_ctree_node_get_cell_style, gtk_ctree_node_get_cell_style ()
gtk_ctree_node_get_cell_type, gtk_ctree_node_get_cell_type ()
gtk_ctree_node_get_pixmap, gtk_ctree_node_get_pixmap ()
gtk_ctree_node_get_pixtext, gtk_ctree_node_get_pixtext ()
gtk_ctree_node_get_row_data, gtk_ctree_node_get_row_data ()
gtk_ctree_node_get_row_style, gtk_ctree_node_get_row_style ()
gtk_ctree_node_get_selectable, gtk_ctree_node_get_selectable ()
gtk_ctree_node_get_text, gtk_ctree_node_get_text ()
gtk_ctree_node_is_visible, gtk_ctree_node_is_visible ()
gtk_ctree_node_moveto, gtk_ctree_node_moveto ()
GTK_CTREE_NODE_NEXT, GTK_CTREE_NODE_NEXT()
gtk_ctree_node_nth, gtk_ctree_node_nth ()
GTK_CTREE_NODE_PREV, GTK_CTREE_NODE_PREV()
gtk_ctree_node_set_background, gtk_ctree_node_set_background ()
gtk_ctree_node_set_cell_style, gtk_ctree_node_set_cell_style ()
gtk_ctree_node_set_foreground, gtk_ctree_node_set_foreground ()
gtk_ctree_node_set_pixmap, gtk_ctree_node_set_pixmap ()
gtk_ctree_node_set_pixtext, gtk_ctree_node_set_pixtext ()
gtk_ctree_node_set_row_data, gtk_ctree_node_set_row_data ()
gtk_ctree_node_set_row_data_full, gtk_ctree_node_set_row_data_full ()
gtk_ctree_node_set_row_style, gtk_ctree_node_set_row_style ()
gtk_ctree_node_set_selectable, gtk_ctree_node_set_selectable ()
gtk_ctree_node_set_shift, gtk_ctree_node_set_shift ()
gtk_ctree_node_set_text, gtk_ctree_node_set_text ()
gtk_ctree_post_recursive, gtk_ctree_post_recursive ()
gtk_ctree_post_recursive_to_depth, gtk_ctree_post_recursive_to_depth ()
gtk_ctree_pre_recursive, gtk_ctree_pre_recursive ()
gtk_ctree_pre_recursive_to_depth, gtk_ctree_pre_recursive_to_depth ()
gtk_ctree_real_select_recursive, gtk_ctree_real_select_recursive ()
gtk_ctree_remove_node, gtk_ctree_remove_node ()
GTK_CTREE_ROW, GTK_CTREE_ROW()
gtk_ctree_select, gtk_ctree_select ()
gtk_ctree_select_recursive, gtk_ctree_select_recursive ()
gtk_ctree_set_drag_compare_func, gtk_ctree_set_drag_compare_func ()
gtk_ctree_set_expander_style, gtk_ctree_set_expander_style ()
gtk_ctree_set_indent, gtk_ctree_set_indent ()
gtk_ctree_set_line_style, gtk_ctree_set_line_style ()
gtk_ctree_set_node_info, gtk_ctree_set_node_info ()
gtk_ctree_set_reorderable, gtk_ctree_set_reorderable()
gtk_ctree_set_show_stub, gtk_ctree_set_show_stub ()
gtk_ctree_set_spacing, gtk_ctree_set_spacing ()
gtk_ctree_sort_node, gtk_ctree_sort_node ()
gtk_ctree_sort_recursive, gtk_ctree_sort_recursive ()
gtk_ctree_toggle_expansion, gtk_ctree_toggle_expansion ()
gtk_ctree_toggle_expansion_recursive, gtk_ctree_toggle_expansion_recursive ()
gtk_ctree_unselect, gtk_ctree_unselect ()
gtk_ctree_unselect_recursive, gtk_ctree_unselect_recursive ()
gtk_drag_set_default_icon, gtk_drag_set_default_icon ()
gtk_drawing_area_size, gtk_drawing_area_size ()
gtk_draw_arrow, gtk_draw_arrow ()
gtk_draw_box, gtk_draw_box ()
gtk_draw_box_gap, gtk_draw_box_gap ()
gtk_draw_check, gtk_draw_check ()
gtk_draw_diamond, gtk_draw_diamond ()
gtk_draw_expander, gtk_draw_expander ()
gtk_draw_extension, gtk_draw_extension ()
gtk_draw_flat_box, gtk_draw_flat_box ()
gtk_draw_focus, gtk_draw_focus ()
gtk_draw_handle, gtk_draw_handle ()
gtk_draw_hline, gtk_draw_hline ()
gtk_draw_layout, gtk_draw_layout ()
gtk_draw_option, gtk_draw_option ()
gtk_draw_polygon, gtk_draw_polygon ()
gtk_draw_resize_grip, gtk_draw_resize_grip ()
gtk_draw_shadow, gtk_draw_shadow ()
gtk_draw_shadow_gap, gtk_draw_shadow_gap ()
gtk_draw_slider, gtk_draw_slider ()
gtk_draw_string, gtk_draw_string ()
gtk_draw_tab, gtk_draw_tab ()
gtk_draw_vline, gtk_draw_vline ()
gtk_entry_append_text, gtk_entry_append_text ()
gtk_entry_new_with_max_length, gtk_entry_new_with_max_length ()
gtk_entry_prepend_text, gtk_entry_prepend_text ()
gtk_entry_select_region, gtk_entry_select_region ()
gtk_entry_set_editable, gtk_entry_set_editable ()
gtk_entry_set_position, gtk_entry_set_position ()
gtk_exit, gtk_exit ()
gtk_font_selection_dialog_get_font, gtk_font_selection_dialog_get_font ()
gtk_font_selection_get_font, gtk_font_selection_get_font ()
GTK_FUNDAMENTAL_TYPE, GTK_FUNDAMENTAL_TYPE
gtk_hbutton_box_get_layout_default, gtk_hbutton_box_get_layout_default ()
gtk_hbutton_box_get_spacing_default, gtk_hbutton_box_get_spacing_default ()
gtk_hbutton_box_set_layout_default, gtk_hbutton_box_set_layout_default ()
gtk_hbutton_box_set_spacing_default, gtk_hbutton_box_set_spacing_default ()
gtk_idle_add, gtk_idle_add ()
gtk_idle_add_full, gtk_idle_add_full ()
gtk_idle_add_priority, gtk_idle_add_priority ()
gtk_idle_remove, gtk_idle_remove ()
gtk_idle_remove_by_data, gtk_idle_remove_by_data ()
gtk_image_get, gtk_image_get ()
gtk_image_set, gtk_image_set ()
gtk_input_add_full, gtk_input_add_full ()
gtk_input_remove, gtk_input_remove ()
GTK_IS_ROOT_TREE, GTK_IS_ROOT_TREE()
gtk_item_factories_path_delete, gtk_item_factories_path_delete ()
gtk_item_factory_add_foreign, gtk_item_factory_add_foreign ()
gtk_item_factory_construct, gtk_item_factory_construct ()
gtk_item_factory_create_item, gtk_item_factory_create_item ()
gtk_item_factory_create_items, gtk_item_factory_create_items ()
gtk_item_factory_create_items_ac, gtk_item_factory_create_items_ac ()
gtk_item_factory_create_menu_entries, gtk_item_factory_create_menu_entries ()
gtk_item_factory_delete_entries, gtk_item_factory_delete_entries ()
gtk_item_factory_delete_entry, gtk_item_factory_delete_entry ()
gtk_item_factory_delete_item, gtk_item_factory_delete_item ()
gtk_item_factory_from_path, gtk_item_factory_from_path ()
gtk_item_factory_from_widget, gtk_item_factory_from_widget ()
gtk_item_factory_get_item, gtk_item_factory_get_item ()
gtk_item_factory_get_item_by_action, gtk_item_factory_get_item_by_action ()
gtk_item_factory_get_widget, gtk_item_factory_get_widget ()
gtk_item_factory_get_widget_by_action, gtk_item_factory_get_widget_by_action ()
gtk_item_factory_new, gtk_item_factory_new ()
gtk_item_factory_path_from_widget, gtk_item_factory_path_from_widget ()
gtk_item_factory_popup, gtk_item_factory_popup ()
gtk_item_factory_popup_data, gtk_item_factory_popup_data ()
gtk_item_factory_popup_data_from_widget, gtk_item_factory_popup_data_from_widget ()
gtk_item_factory_popup_with_data, gtk_item_factory_popup_with_data ()
gtk_item_factory_set_translate_func, gtk_item_factory_set_translate_func ()
gtk_label_get, gtk_label_get ()
gtk_label_parse_uline, gtk_label_parse_uline ()
gtk_label_set, gtk_label_set
gtk_layout_freeze, gtk_layout_freeze ()
gtk_layout_thaw, gtk_layout_thaw ()
gtk_list_append_items, gtk_list_append_items ()
gtk_list_child_position, gtk_list_child_position ()
gtk_list_clear_items, gtk_list_clear_items ()
gtk_list_end_drag_selection, gtk_list_end_drag_selection ()
gtk_list_end_selection, gtk_list_end_selection ()
gtk_list_extend_selection, gtk_list_extend_selection ()
gtk_list_insert_items, gtk_list_insert_items ()
gtk_list_item_deselect, gtk_list_item_deselect ()
gtk_list_item_new, gtk_list_item_new ()
gtk_list_item_new_with_label, gtk_list_item_new_with_label ()
gtk_list_item_select, gtk_list_item_select ()
gtk_list_new, gtk_list_new ()
gtk_list_prepend_items, gtk_list_prepend_items ()
gtk_list_remove_items, gtk_list_remove_items ()
gtk_list_remove_items_no_unref, gtk_list_remove_items_no_unref ()
gtk_list_scroll_horizontal, gtk_list_scroll_horizontal ()
gtk_list_scroll_vertical, gtk_list_scroll_vertical ()
gtk_list_select_all, gtk_list_select_all ()
gtk_list_select_child, gtk_list_select_child ()
gtk_list_select_item, gtk_list_select_item ()
gtk_list_set_selection_mode, gtk_list_set_selection_mode ()
gtk_list_start_selection, gtk_list_start_selection ()
gtk_list_toggle_add_mode, gtk_list_toggle_add_mode ()
gtk_list_toggle_focus_row, gtk_list_toggle_focus_row ()
gtk_list_toggle_row, gtk_list_toggle_row ()
gtk_list_undo_selection, gtk_list_undo_selection ()
gtk_list_unselect_all, gtk_list_unselect_all ()
gtk_list_unselect_child, gtk_list_unselect_child ()
gtk_list_unselect_item, gtk_list_unselect_item ()
gtk_menu_append, gtk_menu_append()
gtk_menu_bar_append, gtk_menu_bar_append()
gtk_menu_bar_insert, gtk_menu_bar_insert()
gtk_menu_bar_prepend, gtk_menu_bar_prepend()
gtk_menu_insert, gtk_menu_insert()
gtk_menu_item_right_justify, gtk_menu_item_right_justify()
gtk_menu_prepend, gtk_menu_prepend()
gtk_notebook_current_page, gtk_notebook_current_page
gtk_notebook_set_homogeneous_tabs, gtk_notebook_set_homogeneous_tabs ()
gtk_notebook_set_page, gtk_notebook_set_page
gtk_notebook_set_tab_border, gtk_notebook_set_tab_border ()
gtk_notebook_set_tab_hborder, gtk_notebook_set_tab_hborder ()
gtk_notebook_set_tab_vborder, gtk_notebook_set_tab_vborder ()
gtk_object_add_arg_type, gtk_object_add_arg_type ()
gtk_object_data_force_id, gtk_object_data_force_id
gtk_object_data_try_key, gtk_object_data_try_key
GTK_OBJECT_FLOATING, GTK_OBJECT_FLOATING()
gtk_object_get, gtk_object_get ()
gtk_object_get_data, gtk_object_get_data ()
gtk_object_get_data_by_id, gtk_object_get_data_by_id ()
gtk_object_get_user_data, gtk_object_get_user_data ()
gtk_object_new, gtk_object_new ()
gtk_object_ref, gtk_object_ref ()
gtk_object_remove_data, gtk_object_remove_data ()
gtk_object_remove_data_by_id, gtk_object_remove_data_by_id ()
gtk_object_remove_no_notify, gtk_object_remove_no_notify ()
gtk_object_remove_no_notify_by_id, gtk_object_remove_no_notify_by_id ()
gtk_object_set, gtk_object_set ()
gtk_object_set_data, gtk_object_set_data ()
gtk_object_set_data_by_id, gtk_object_set_data_by_id ()
gtk_object_set_data_by_id_full, gtk_object_set_data_by_id_full ()
gtk_object_set_data_full, gtk_object_set_data_full ()
gtk_object_set_user_data, gtk_object_set_user_data ()
gtk_object_sink, gtk_object_sink ()
gtk_object_unref, gtk_object_unref ()
gtk_object_weakref, gtk_object_weakref ()
gtk_object_weakunref, gtk_object_weakunref ()
gtk_old_editable_changed, gtk_old_editable_changed ()
gtk_old_editable_claim_selection, gtk_old_editable_claim_selection ()
gtk_option_menu_get_history, gtk_option_menu_get_history ()
gtk_option_menu_get_menu, gtk_option_menu_get_menu ()
gtk_option_menu_new, gtk_option_menu_new ()
gtk_option_menu_remove_menu, gtk_option_menu_remove_menu ()
gtk_option_menu_set_history, gtk_option_menu_set_history ()
gtk_option_menu_set_menu, gtk_option_menu_set_menu ()
gtk_paint_string, gtk_paint_string ()
gtk_paned_gutter_size, gtk_paned_gutter_size()
gtk_paned_set_gutter_size, gtk_paned_set_gutter_size()
gtk_pixmap_get, gtk_pixmap_get ()
gtk_pixmap_new, gtk_pixmap_new ()
gtk_pixmap_set, gtk_pixmap_set ()
gtk_pixmap_set_build_insensitive, gtk_pixmap_set_build_insensitive ()
gtk_preview_draw_row, gtk_preview_draw_row ()
gtk_preview_get_cmap, gtk_preview_get_cmap ()
gtk_preview_get_info, gtk_preview_get_info ()
gtk_preview_get_visual, gtk_preview_get_visual ()
gtk_preview_new, gtk_preview_new ()
gtk_preview_put, gtk_preview_put ()
gtk_preview_reset, gtk_preview_reset ()
gtk_preview_set_color_cube, gtk_preview_set_color_cube ()
gtk_preview_set_dither, gtk_preview_set_dither ()
gtk_preview_set_expand, gtk_preview_set_expand ()
gtk_preview_set_gamma, gtk_preview_set_gamma ()
gtk_preview_set_install_cmap, gtk_preview_set_install_cmap ()
gtk_preview_set_reserved, gtk_preview_set_reserved ()
gtk_preview_size, gtk_preview_size ()
gtk_preview_uninit, gtk_preview_uninit ()
GTK_PRIORITY_DEFAULT, GTK_PRIORITY_DEFAULT
GTK_PRIORITY_HIGH, GTK_PRIORITY_HIGH
GTK_PRIORITY_INTERNAL, GTK_PRIORITY_INTERNAL
GTK_PRIORITY_LOW, GTK_PRIORITY_LOW
GTK_PRIORITY_REDRAW, GTK_PRIORITY_REDRAW
gtk_progress_bar_new_with_adjustment, gtk_progress_bar_new_with_adjustment ()
gtk_progress_bar_set_activity_blocks, gtk_progress_bar_set_activity_blocks ()
gtk_progress_bar_set_activity_step, gtk_progress_bar_set_activity_step ()
gtk_progress_bar_set_bar_style, gtk_progress_bar_set_bar_style ()
gtk_progress_bar_set_discrete_blocks, gtk_progress_bar_set_discrete_blocks ()
gtk_progress_bar_update, gtk_progress_bar_update ()
gtk_progress_configure, gtk_progress_configure ()
gtk_progress_get_current_percentage, gtk_progress_get_current_percentage ()
gtk_progress_get_current_text, gtk_progress_get_current_text ()
gtk_progress_get_percentage_from_value, gtk_progress_get_percentage_from_value ()
gtk_progress_get_text_from_value, gtk_progress_get_text_from_value ()
gtk_progress_get_value, gtk_progress_get_value ()
gtk_progress_set_activity_mode, gtk_progress_set_activity_mode ()
gtk_progress_set_adjustment, gtk_progress_set_adjustment ()
gtk_progress_set_format_string, gtk_progress_set_format_string ()
gtk_progress_set_percentage, gtk_progress_set_percentage ()
gtk_progress_set_show_text, gtk_progress_set_show_text ()
gtk_progress_set_text_alignment, gtk_progress_set_text_alignment ()
gtk_progress_set_value, gtk_progress_set_value ()
gtk_radio_button_group, gtk_radio_button_group
gtk_radio_menu_item_group, gtk_radio_menu_item_group
gtk_rc_add_class_style, gtk_rc_add_class_style ()
gtk_rc_add_widget_class_style, gtk_rc_add_widget_class_style ()
gtk_rc_add_widget_name_style, gtk_rc_add_widget_name_style ()
GTK_RETLOC_BOOL, GTK_RETLOC_BOOL()
GTK_RETLOC_BOXED, GTK_RETLOC_BOXED()
GTK_RETLOC_CHAR, GTK_RETLOC_CHAR()
GTK_RETLOC_DOUBLE, GTK_RETLOC_DOUBLE()
GTK_RETLOC_ENUM, GTK_RETLOC_ENUM()
GTK_RETLOC_FLAGS, GTK_RETLOC_FLAGS()
GTK_RETLOC_FLOAT, GTK_RETLOC_FLOAT()
GTK_RETLOC_INT, GTK_RETLOC_INT()
GTK_RETLOC_LONG, GTK_RETLOC_LONG()
GTK_RETLOC_OBJECT, GTK_RETLOC_OBJECT()
GTK_RETLOC_POINTER, GTK_RETLOC_POINTER()
GTK_RETLOC_STRING, GTK_RETLOC_STRING()
GTK_RETLOC_UCHAR, GTK_RETLOC_UCHAR()
GTK_RETLOC_UINT, GTK_RETLOC_UINT()
GTK_RETLOC_ULONG, GTK_RETLOC_ULONG()
gtk_selection_clear, gtk_selection_clear ()
gtk_signal_connect, gtk_signal_connect()
gtk_signal_connect_after, gtk_signal_connect_after()
gtk_signal_connect_full, gtk_signal_connect_full ()
gtk_signal_connect_object, gtk_signal_connect_object()
gtk_signal_connect_object_after, gtk_signal_connect_object_after()
gtk_signal_connect_object_while_alive, gtk_signal_connect_object_while_alive ()
gtk_signal_connect_while_alive, gtk_signal_connect_while_alive ()
gtk_signal_default_marshaller, gtk_signal_default_marshaller
gtk_signal_disconnect, gtk_signal_disconnect()
gtk_signal_disconnect_by_data, gtk_signal_disconnect_by_data()
gtk_signal_disconnect_by_func, gtk_signal_disconnect_by_func()
gtk_signal_emit, gtk_signal_emit ()
gtk_signal_emitv, gtk_signal_emitv ()
gtk_signal_emitv_by_name, gtk_signal_emitv_by_name ()
gtk_signal_emit_by_name, gtk_signal_emit_by_name ()
gtk_signal_emit_stop, gtk_signal_emit_stop()
gtk_signal_emit_stop_by_name, gtk_signal_emit_stop_by_name ()
gtk_signal_handler_block, gtk_signal_handler_block()
gtk_signal_handler_block_by_data, gtk_signal_handler_block_by_data()
gtk_signal_handler_block_by_func, gtk_signal_handler_block_by_func()
gtk_signal_handler_pending, gtk_signal_handler_pending()
gtk_signal_handler_pending_by_func, gtk_signal_handler_pending_by_func()
gtk_signal_handler_unblock, gtk_signal_handler_unblock()
gtk_signal_handler_unblock_by_data, gtk_signal_handler_unblock_by_data()
gtk_signal_handler_unblock_by_func, gtk_signal_handler_unblock_by_func()
gtk_signal_lookup, gtk_signal_lookup()
gtk_signal_name, gtk_signal_name()
gtk_signal_new, gtk_signal_new ()
gtk_signal_newv, gtk_signal_newv ()
GTK_SIGNAL_OFFSET, GTK_SIGNAL_OFFSET
gtk_socket_steal, gtk_socket_steal ()
gtk_spin_button_get_value_as_float, gtk_spin_button_get_value_as_float
GTK_STRUCT_OFFSET, GTK_STRUCT_OFFSET
gtk_style_apply_default_pixmap, gtk_style_apply_default_pixmap()
gtk_style_get_font, gtk_style_get_font ()
gtk_style_ref, gtk_style_ref ()
gtk_style_set_font, gtk_style_set_font ()
gtk_style_unref, gtk_style_unref ()
gtk_text_backward_delete, gtk_text_backward_delete ()
gtk_text_forward_delete, gtk_text_forward_delete ()
gtk_text_freeze, gtk_text_freeze ()
gtk_text_get_length, gtk_text_get_length ()
gtk_text_get_point, gtk_text_get_point ()
GTK_TEXT_INDEX, GTK_TEXT_INDEX()
gtk_text_insert, gtk_text_insert ()
gtk_text_new, gtk_text_new ()
gtk_text_set_adjustments, gtk_text_set_adjustments ()
gtk_text_set_editable, gtk_text_set_editable ()
gtk_text_set_line_wrap, gtk_text_set_line_wrap ()
gtk_text_set_point, gtk_text_set_point ()
gtk_text_set_word_wrap, gtk_text_set_word_wrap ()
gtk_text_thaw, gtk_text_thaw ()
gtk_timeout_add, gtk_timeout_add ()
gtk_timeout_add_full, gtk_timeout_add_full ()
gtk_timeout_remove, gtk_timeout_remove ()
gtk_tips_query_new, gtk_tips_query_new ()
gtk_tips_query_set_caller, gtk_tips_query_set_caller ()
gtk_tips_query_set_labels, gtk_tips_query_set_labels ()
gtk_tips_query_start_query, gtk_tips_query_start_query ()
gtk_tips_query_stop_query, gtk_tips_query_stop_query ()
gtk_toggle_button_set_state, gtk_toggle_button_set_state
gtk_toolbar_append_element, gtk_toolbar_append_element ()
gtk_toolbar_append_item, gtk_toolbar_append_item ()
gtk_toolbar_append_space, gtk_toolbar_append_space ()
gtk_toolbar_append_widget, gtk_toolbar_append_widget ()
gtk_toolbar_insert_element, gtk_toolbar_insert_element ()
gtk_toolbar_insert_item, gtk_toolbar_insert_item ()
gtk_toolbar_insert_space, gtk_toolbar_insert_space ()
gtk_toolbar_insert_stock, gtk_toolbar_insert_stock ()
gtk_toolbar_insert_widget, gtk_toolbar_insert_widget ()
gtk_toolbar_prepend_element, gtk_toolbar_prepend_element ()
gtk_toolbar_prepend_item, gtk_toolbar_prepend_item ()
gtk_toolbar_prepend_space, gtk_toolbar_prepend_space ()
gtk_toolbar_prepend_widget, gtk_toolbar_prepend_widget ()
gtk_toolbar_remove_space, gtk_toolbar_remove_space ()
gtk_toolbar_set_icon_size, gtk_toolbar_set_icon_size ()
gtk_toolbar_unset_icon_size, gtk_toolbar_unset_icon_size ()
gtk_tooltips_set_delay, gtk_tooltips_set_delay ()
gtk_tree_append, gtk_tree_append ()
gtk_tree_child_position, gtk_tree_child_position ()
gtk_tree_clear_items, gtk_tree_clear_items ()
gtk_tree_insert, gtk_tree_insert ()
gtk_tree_item_collapse, gtk_tree_item_collapse ()
gtk_tree_item_deselect, gtk_tree_item_deselect ()
gtk_tree_item_expand, gtk_tree_item_expand ()
gtk_tree_item_new, gtk_tree_item_new ()
gtk_tree_item_new_with_label, gtk_tree_item_new_with_label ()
gtk_tree_item_remove_subtree, gtk_tree_item_remove_subtree ()
gtk_tree_item_select, gtk_tree_item_select ()
gtk_tree_item_set_subtree, gtk_tree_item_set_subtree ()
GTK_TREE_ITEM_SUBTREE, GTK_TREE_ITEM_SUBTREE()
gtk_tree_model_get_iter_root, gtk_tree_model_get_iter_root()
gtk_tree_new, gtk_tree_new ()
gtk_tree_path_new_root, gtk_tree_path_new_root()
gtk_tree_prepend, gtk_tree_prepend ()
gtk_tree_remove_item, gtk_tree_remove_item ()
gtk_tree_remove_items, gtk_tree_remove_items ()
GTK_TREE_ROOT_TREE, GTK_TREE_ROOT_TREE()
GTK_TREE_SELECTION_OLD, GTK_TREE_SELECTION_OLD()
gtk_tree_select_child, gtk_tree_select_child ()
gtk_tree_select_item, gtk_tree_select_item ()
gtk_tree_set_selection_mode, gtk_tree_set_selection_mode ()
gtk_tree_set_view_lines, gtk_tree_set_view_lines ()
gtk_tree_set_view_mode, gtk_tree_set_view_mode ()
gtk_tree_unselect_child, gtk_tree_unselect_child ()
gtk_tree_unselect_item, gtk_tree_unselect_item ()
GTK_TYPE_CTREE_NODE, GTK_TYPE_CTREE_NODE
gtk_type_enum_find_value, gtk_type_enum_find_value ()
gtk_type_enum_get_values, gtk_type_enum_get_values ()
gtk_type_flags_find_value, gtk_type_flags_find_value ()
gtk_type_flags_get_values, gtk_type_flags_get_values ()
gtk_type_from_name, gtk_type_from_name()
GTK_TYPE_FUNDAMENTAL_LAST, GTK_TYPE_FUNDAMENTAL_LAST
GTK_TYPE_FUNDAMENTAL_MAX, GTK_TYPE_FUNDAMENTAL_MAX
gtk_type_init, gtk_type_init ()
gtk_type_is_a, gtk_type_is_a()
GTK_TYPE_IS_OBJECT, GTK_TYPE_IS_OBJECT()
gtk_type_name, gtk_type_name()
gtk_type_new, gtk_type_new ()
gtk_type_parent, gtk_type_parent()
gtk_type_unique, gtk_type_unique ()
GTK_VALUE_BOOL, GTK_VALUE_BOOL()
GTK_VALUE_BOXED, GTK_VALUE_BOXED()
GTK_VALUE_CHAR, GTK_VALUE_CHAR()
GTK_VALUE_DOUBLE, GTK_VALUE_DOUBLE()
GTK_VALUE_ENUM, GTK_VALUE_ENUM()
GTK_VALUE_FLAGS, GTK_VALUE_FLAGS()
GTK_VALUE_FLOAT, GTK_VALUE_FLOAT()
GTK_VALUE_INT, GTK_VALUE_INT()
GTK_VALUE_LONG, GTK_VALUE_LONG()
GTK_VALUE_OBJECT, GTK_VALUE_OBJECT()
GTK_VALUE_POINTER, GTK_VALUE_POINTER()
GTK_VALUE_SIGNAL, GTK_VALUE_SIGNAL()
GTK_VALUE_STRING, GTK_VALUE_STRING()
GTK_VALUE_UCHAR, GTK_VALUE_UCHAR()
GTK_VALUE_UINT, GTK_VALUE_UINT()
GTK_VALUE_ULONG, GTK_VALUE_ULONG()
gtk_vbutton_box_get_layout_default, gtk_vbutton_box_get_layout_default ()
gtk_vbutton_box_get_spacing_default, gtk_vbutton_box_get_spacing_default ()
gtk_vbutton_box_set_layout_default, gtk_vbutton_box_set_layout_default ()
gtk_vbutton_box_set_spacing_default, gtk_vbutton_box_set_spacing_default ()
gtk_widget_draw, gtk_widget_draw ()
gtk_widget_pop_visual, gtk_widget_pop_visual()
gtk_widget_push_visual, gtk_widget_push_visual()
gtk_widget_queue_clear, gtk_widget_queue_clear ()
gtk_widget_queue_clear_area, gtk_widget_queue_clear_area ()
gtk_widget_restore_default_style, gtk_widget_restore_default_style()
gtk_widget_set, gtk_widget_set ()
gtk_widget_set_default_visual, gtk_widget_set_default_visual()
gtk_widget_set_rc_style, gtk_widget_set_rc_style()
gtk_widget_set_uposition, gtk_widget_set_uposition ()
gtk_widget_set_usize, gtk_widget_set_usize ()
gtk_widget_set_visual, gtk_widget_set_visual()
gtk_window_position, gtk_window_position
gtk_window_set_policy, gtk_window_set_policy ()


Index of new symbols in 2.2

G

GtkAccelGroupFindFunc, GtkAccelGroupFindFunc ()
GtkColorSelectionChangePaletteWithScreenFunc, GtkColorSelectionChangePaletteWithScreenFunc ()
GtkModuleDisplayInitFunc, GtkModuleDisplayInitFunc ()
gtk_clipboard_get_display, gtk_clipboard_get_display ()
gtk_clipboard_get_for_display, gtk_clipboard_get_for_display ()
gtk_color_selection_set_change_palette_with_screen_hook, gtk_color_selection_set_change_palette_with_screen_hook ()
gtk_icon_size_lookup_for_settings, gtk_icon_size_lookup_for_settings ()
gtk_invisible_get_screen, gtk_invisible_get_screen ()
gtk_invisible_new_for_screen, gtk_invisible_new_for_screen ()
gtk_invisible_set_screen, gtk_invisible_set_screen ()
gtk_list_store_iter_is_valid, gtk_list_store_iter_is_valid ()
gtk_list_store_move_after, gtk_list_store_move_after ()
gtk_list_store_move_before, gtk_list_store_move_before ()
gtk_list_store_reorder, gtk_list_store_reorder ()
gtk_list_store_swap, gtk_list_store_swap ()
gtk_menu_set_screen, gtk_menu_set_screen ()
gtk_menu_shell_select_first, gtk_menu_shell_select_first ()
gtk_notebook_get_n_pages, gtk_notebook_get_n_pages ()
gtk_plug_construct_for_display, gtk_plug_construct_for_display ()
gtk_plug_new_for_display, gtk_plug_new_for_display ()
gtk_selection_clear, gtk_selection_clear ()
gtk_selection_owner_set_for_display, gtk_selection_owner_set_for_display ()
gtk_settings_get_for_screen, gtk_settings_get_for_screen ()
GTK_STOCK_COLOR_PICKER, GTK_STOCK_COLOR_PICKER
gtk_tree_model_get_string_from_iter, gtk_tree_model_get_string_from_iter ()
gtk_tree_model_sort_iter_is_valid, gtk_tree_model_sort_iter_is_valid ()
gtk_tree_path_new_from_indices, gtk_tree_path_new_from_indices ()
gtk_tree_row_reference_copy, gtk_tree_row_reference_copy ()
gtk_tree_selection_count_selected_rows, gtk_tree_selection_count_selected_rows ()
gtk_tree_selection_get_selected_rows, gtk_tree_selection_get_selected_rows ()
gtk_tree_selection_unselect_range, gtk_tree_selection_unselect_range ()
gtk_tree_store_iter_is_valid, gtk_tree_store_iter_is_valid ()
gtk_tree_store_move_after, gtk_tree_store_move_after ()
gtk_tree_store_move_before, gtk_tree_store_move_before ()
gtk_tree_store_reorder, gtk_tree_store_reorder ()
gtk_tree_store_swap, gtk_tree_store_swap ()
gtk_tree_view_column_focus_cell, gtk_tree_view_column_focus_cell ()
gtk_tree_view_expand_to_path, gtk_tree_view_expand_to_path ()
gtk_tree_view_set_cursor_on_cell, gtk_tree_view_set_cursor_on_cell ()
gtk_widget_class_find_style_property, gtk_widget_class_find_style_property ()
gtk_widget_class_list_style_properties, gtk_widget_class_list_style_properties ()
gtk_widget_get_clipboard, gtk_widget_get_clipboard ()
gtk_widget_get_display, gtk_widget_get_display ()
gtk_widget_get_root_window, gtk_widget_get_root_window ()
gtk_widget_get_screen, gtk_widget_get_screen ()
gtk_widget_has_screen, gtk_widget_has_screen ()
gtk_window_fullscreen, gtk_window_fullscreen ()
gtk_window_get_screen, gtk_window_get_screen ()
gtk_window_get_skip_pager_hint, gtk_window_get_skip_pager_hint ()
gtk_window_get_skip_taskbar_hint, gtk_window_get_skip_taskbar_hint ()
gtk_window_set_auto_startup_notification, gtk_window_set_auto_startup_notification ()
gtk_window_set_default_icon_from_file, gtk_window_set_default_icon_from_file ()
gtk_window_set_icon_from_file, gtk_window_set_icon_from_file ()
gtk_window_set_screen, gtk_window_set_screen ()
gtk_window_set_skip_pager_hint, gtk_window_set_skip_pager_hint ()
gtk_window_set_skip_taskbar_hint, gtk_window_set_skip_taskbar_hint ()
gtk_window_unfullscreen, gtk_window_unfullscreen ()


Index of new symbols in 2.4

G

GtkAccelMap::changed, The "changed" signal
GtkAction::activate, The "activate" signal
GtkActionGroup::connect-proxy, The "connect-proxy" signal
GtkActionGroup::disconnect-proxy, The "disconnect-proxy" signal
GtkActionGroup::post-activate, The "post-activate" signal
GtkActionGroup::pre-activate, The "pre-activate" signal
GtkAdjustment:lower, The "lower" property
GtkAdjustment:page-increment, The "page-increment" property
GtkAdjustment:page-size, The "page-size" property
GtkAdjustment:step-increment, The "step-increment" property
GtkAdjustment:upper, The "upper" property
GtkAdjustment:value, The "value" property
GtkAlignment:bottom-padding, The "bottom-padding" property
GtkAlignment:left-padding, The "left-padding" property
GtkAlignment:right-padding, The "right-padding" property
GtkAlignment:top-padding, The "top-padding" property
GtkButton:xalign, The "xalign" property
GtkButton:yalign, The "yalign" property
GtkCalendar:no-month-change, The "no-month-change" property
GtkCalendar:show-day-names, The "show-day-names" property
GtkCalendar:show-heading, The "show-heading" property
GtkCalendar:show-week-numbers, The "show-week-numbers" property
GtkCellRenderer::editing-canceled, The "editing-canceled" signal
GtkClipboardTargetsReceivedFunc, GtkClipboardTargetsReceivedFunc ()
GtkColorButton::color-set, The "color-set" signal
GtkColorButton:alpha, The "alpha" property
GtkColorButton:color, The "color" property
GtkColorButton:title, The "title" property
GtkColorButton:use-alpha, The "use-alpha" property
GtkComboBox::changed, The "changed" signal
GtkComboBox:active, The "active" property
GtkComboBox:column-span-column, The "column-span-column" property
GtkComboBox:model, The "model" property
GtkComboBox:row-span-column, The "row-span-column" property
GtkComboBox:wrap-width, The "wrap-width" property
GtkEntry:xalign, The "xalign" property
GtkEntryCompletion::action-activated, The "action-activated" signal
GtkEntryCompletion::match-selected, The "match-selected" signal
GtkFontButton::font-set, The "font-set" signal
GtkFontButton:font-name, The "font-name" property
GtkFontButton:show-size, The "show-size" property
GtkFontButton:show-style, The "show-style" property
GtkFontButton:title, The "title" property
GtkFontButton:use-font, The "use-font" property
GtkFontButton:use-size, The "use-size" property
GtkMessageDialog:use-separator, The "use-separator" style property
GtkNotebook:has-backward-stepper, The "has-backward-stepper" style property
GtkNotebook:has-forward-stepper, The "has-forward-stepper" style property
GtkNotebook:has-secondary-backward-stepper, The "has-secondary-backward-stepper" style property
GtkNotebook:has-secondary-forward-stepper, The "has-secondary-forward-stepper" style property
GtkPaned:max-position, The "max-position" property
GtkPaned:min-position, The "min-position" property
GtkPaned:resize, The "resize" child property
GtkPaned:shrink, The "shrink" child property
GtkRadioAction::changed, The "changed" signal
GtkRadioAction:group, The "group" property
GtkRadioAction:value, The "value" property
GtkRadioButton::group-changed, The "group-changed" signal
GtkRadioToolButton:group, The "group" property
GtkStatusbar:has-resize-grip, The "has-resize-grip" property
GtkStyle::realize, The "realize" signal
GtkStyle::unrealize, The "unrealize" signal
GtkTreeView:fixed-height-mode, The "fixed-height-mode" property
GtkUIManager::actions-changed, The "actions-changed" signal
GtkUIManager::add-widget, The "add-widget" signal
GtkUIManager::connect-proxy, The "connect-proxy" signal
GtkUIManager::disconnect-proxy, The "disconnect-proxy" signal
GtkUIManager::post-activate, The "post-activate" signal
GtkUIManager::pre-activate, The "pre-activate" signal
GtkUIManager:add-tearoffs, The "add-tearoffs" property
GtkWindow:decorated, The "decorated" property
GtkWindow:gravity, The "gravity" property
gtk_accel_map_get, gtk_accel_map_get ()
gtk_accel_map_lock_path, gtk_accel_map_lock_path ()
gtk_accel_map_unlock_path, gtk_accel_map_unlock_path ()
gtk_action_activate, gtk_action_activate ()
gtk_action_block_activate_from, gtk_action_block_activate_from ()
gtk_action_connect_accelerator, gtk_action_connect_accelerator ()
gtk_action_connect_proxy, gtk_action_connect_proxy ()
gtk_action_create_icon, gtk_action_create_icon ()
gtk_action_create_menu_item, gtk_action_create_menu_item ()
gtk_action_create_tool_item, gtk_action_create_tool_item ()
gtk_action_disconnect_accelerator, gtk_action_disconnect_accelerator ()
gtk_action_disconnect_proxy, gtk_action_disconnect_proxy ()
gtk_action_get_name, gtk_action_get_name ()
gtk_action_get_proxies, gtk_action_get_proxies ()
gtk_action_get_sensitive, gtk_action_get_sensitive ()
gtk_action_get_visible, gtk_action_get_visible ()
gtk_action_group_add_action, gtk_action_group_add_action ()
gtk_action_group_add_actions, gtk_action_group_add_actions ()
gtk_action_group_add_actions_full, gtk_action_group_add_actions_full ()
gtk_action_group_add_action_with_accel, gtk_action_group_add_action_with_accel ()
gtk_action_group_add_radio_actions, gtk_action_group_add_radio_actions ()
gtk_action_group_add_radio_actions_full, gtk_action_group_add_radio_actions_full ()
gtk_action_group_add_toggle_actions, gtk_action_group_add_toggle_actions ()
gtk_action_group_add_toggle_actions_full, gtk_action_group_add_toggle_actions_full ()
gtk_action_group_get_action, gtk_action_group_get_action ()
gtk_action_group_get_name, gtk_action_group_get_name ()
gtk_action_group_get_sensitive, gtk_action_group_get_sensitive ()
gtk_action_group_get_visible, gtk_action_group_get_visible ()
gtk_action_group_list_actions, gtk_action_group_list_actions ()
gtk_action_group_new, gtk_action_group_new ()
gtk_action_group_remove_action, gtk_action_group_remove_action ()
gtk_action_group_set_sensitive, gtk_action_group_set_sensitive ()
gtk_action_group_set_translate_func, gtk_action_group_set_translate_func ()
gtk_action_group_set_translation_domain, gtk_action_group_set_translation_domain ()
gtk_action_group_set_visible, gtk_action_group_set_visible ()
gtk_action_is_sensitive, gtk_action_is_sensitive ()
gtk_action_is_visible, gtk_action_is_visible ()
gtk_action_new, gtk_action_new ()
gtk_action_set_accel_group, gtk_action_set_accel_group ()
gtk_action_set_accel_path, gtk_action_set_accel_path ()
gtk_action_unblock_activate_from, gtk_action_unblock_activate_from ()
gtk_alignment_get_padding, gtk_alignment_get_padding ()
gtk_alignment_set_padding, gtk_alignment_set_padding ()
gtk_button_box_get_child_secondary, gtk_button_box_get_child_secondary ()
gtk_button_get_alignment, gtk_button_get_alignment ()
gtk_button_get_focus_on_click, gtk_button_get_focus_on_click ()
gtk_button_set_alignment, gtk_button_set_alignment ()
gtk_button_set_focus_on_click, gtk_button_set_focus_on_click ()
gtk_calendar_get_display_options, gtk_calendar_get_display_options ()
gtk_calendar_set_display_options, gtk_calendar_set_display_options ()
gtk_cell_layout_add_attribute, gtk_cell_layout_add_attribute ()
gtk_cell_layout_clear, gtk_cell_layout_clear ()
gtk_cell_layout_clear_attributes, gtk_cell_layout_clear_attributes ()
gtk_cell_layout_pack_end, gtk_cell_layout_pack_end ()
gtk_cell_layout_pack_start, gtk_cell_layout_pack_start ()
gtk_cell_layout_reorder, gtk_cell_layout_reorder ()
gtk_cell_layout_set_attributes, gtk_cell_layout_set_attributes ()
gtk_cell_layout_set_cell_data_func, gtk_cell_layout_set_cell_data_func ()
gtk_cell_renderer_editing_canceled, gtk_cell_renderer_editing_canceled ()
gtk_check_menu_item_get_draw_as_radio, gtk_check_menu_item_get_draw_as_radio ()
gtk_check_menu_item_set_draw_as_radio, gtk_check_menu_item_set_draw_as_radio ()
gtk_clipboard_request_targets, gtk_clipboard_request_targets ()
gtk_clipboard_wait_for_targets, gtk_clipboard_wait_for_targets ()
gtk_color_button_get_alpha, gtk_color_button_get_alpha ()
gtk_color_button_get_color, gtk_color_button_get_color ()
gtk_color_button_get_title, gtk_color_button_get_title ()
gtk_color_button_get_use_alpha, gtk_color_button_get_use_alpha ()
gtk_color_button_new, gtk_color_button_new ()
gtk_color_button_new_with_color, gtk_color_button_new_with_color ()
gtk_color_button_set_alpha, gtk_color_button_set_alpha ()
gtk_color_button_set_color, gtk_color_button_set_color ()
gtk_color_button_set_title, gtk_color_button_set_title ()
gtk_color_button_set_use_alpha, gtk_color_button_set_use_alpha ()
gtk_combo_box_append_text, gtk_combo_box_append_text ()
gtk_combo_box_entry_get_text_column, gtk_combo_box_entry_get_text_column ()
gtk_combo_box_entry_new, gtk_combo_box_entry_new ()
gtk_combo_box_entry_new_text, gtk_combo_box_entry_new_text ()
gtk_combo_box_entry_new_with_model, gtk_combo_box_entry_new_with_model ()
gtk_combo_box_entry_set_text_column, gtk_combo_box_entry_set_text_column ()
gtk_combo_box_get_active, gtk_combo_box_get_active ()
gtk_combo_box_get_active_iter, gtk_combo_box_get_active_iter ()
gtk_combo_box_get_model, gtk_combo_box_get_model ()
gtk_combo_box_insert_text, gtk_combo_box_insert_text ()
gtk_combo_box_new, gtk_combo_box_new ()
gtk_combo_box_new_text, gtk_combo_box_new_text ()
gtk_combo_box_new_with_model, gtk_combo_box_new_with_model ()
gtk_combo_box_popdown, gtk_combo_box_popdown ()
gtk_combo_box_popup, gtk_combo_box_popup ()
gtk_combo_box_prepend_text, gtk_combo_box_prepend_text ()
gtk_combo_box_remove_text, gtk_combo_box_remove_text ()
gtk_combo_box_set_active, gtk_combo_box_set_active ()
gtk_combo_box_set_active_iter, gtk_combo_box_set_active_iter ()
gtk_combo_box_set_column_span_column, gtk_combo_box_set_column_span_column ()
gtk_combo_box_set_model, gtk_combo_box_set_model ()
gtk_combo_box_set_row_span_column, gtk_combo_box_set_row_span_column ()
gtk_combo_box_set_wrap_width, gtk_combo_box_set_wrap_width ()
gtk_drag_source_get_target_list, gtk_drag_source_get_target_list ()
gtk_drag_source_set_target_list, gtk_drag_source_set_target_list ()
gtk_draw_insertion_cursor, gtk_draw_insertion_cursor ()
gtk_entry_completion_complete, gtk_entry_completion_complete ()
gtk_entry_completion_delete_action, gtk_entry_completion_delete_action ()
gtk_entry_completion_get_entry, gtk_entry_completion_get_entry ()
gtk_entry_completion_get_minimum_key_length, gtk_entry_completion_get_minimum_key_length ()
gtk_entry_completion_get_model, gtk_entry_completion_get_model ()
gtk_entry_completion_insert_action_markup, gtk_entry_completion_insert_action_markup ()
gtk_entry_completion_insert_action_text, gtk_entry_completion_insert_action_text ()
gtk_entry_completion_new, gtk_entry_completion_new ()
gtk_entry_completion_set_match_func, gtk_entry_completion_set_match_func ()
gtk_entry_completion_set_minimum_key_length, gtk_entry_completion_set_minimum_key_length ()
gtk_entry_completion_set_model, gtk_entry_completion_set_model ()
gtk_entry_completion_set_text_column, gtk_entry_completion_set_text_column ()
gtk_entry_get_alignment, gtk_entry_get_alignment ()
gtk_entry_get_completion, gtk_entry_get_completion ()
gtk_entry_set_alignment, gtk_entry_set_alignment ()
gtk_entry_set_completion, gtk_entry_set_completion ()
gtk_event_box_get_above_child, gtk_event_box_get_above_child ()
gtk_event_box_get_visible_window, gtk_event_box_get_visible_window ()
gtk_event_box_set_above_child, gtk_event_box_set_above_child ()
gtk_event_box_set_visible_window, gtk_event_box_set_visible_window ()
gtk_expander_get_expanded, gtk_expander_get_expanded ()
gtk_expander_get_label, gtk_expander_get_label ()
gtk_expander_get_label_widget, gtk_expander_get_label_widget ()
gtk_expander_get_spacing, gtk_expander_get_spacing ()
gtk_expander_get_use_markup, gtk_expander_get_use_markup ()
gtk_expander_get_use_underline, gtk_expander_get_use_underline ()
gtk_expander_new, gtk_expander_new ()
gtk_expander_new_with_mnemonic, gtk_expander_new_with_mnemonic ()
gtk_expander_set_expanded, gtk_expander_set_expanded ()
gtk_expander_set_label, gtk_expander_set_label ()
gtk_expander_set_label_widget, gtk_expander_set_label_widget ()
gtk_expander_set_spacing, gtk_expander_set_spacing ()
gtk_expander_set_use_markup, gtk_expander_set_use_markup ()
gtk_expander_set_use_underline, gtk_expander_set_use_underline ()
gtk_file_chooser_add_filter, gtk_file_chooser_add_filter ()
gtk_file_chooser_add_shortcut_folder, gtk_file_chooser_add_shortcut_folder ()
gtk_file_chooser_add_shortcut_folder_uri, gtk_file_chooser_add_shortcut_folder_uri ()
gtk_file_chooser_dialog_new, gtk_file_chooser_dialog_new ()
gtk_file_chooser_dialog_new_with_backend, gtk_file_chooser_dialog_new_with_backend ()
gtk_file_chooser_get_action, gtk_file_chooser_get_action ()
gtk_file_chooser_get_current_folder, gtk_file_chooser_get_current_folder ()
gtk_file_chooser_get_current_folder_uri, gtk_file_chooser_get_current_folder_uri ()
gtk_file_chooser_get_extra_widget, gtk_file_chooser_get_extra_widget ()
gtk_file_chooser_get_filename, gtk_file_chooser_get_filename ()
gtk_file_chooser_get_filenames, gtk_file_chooser_get_filenames ()
gtk_file_chooser_get_filter, gtk_file_chooser_get_filter ()
gtk_file_chooser_get_local_only, gtk_file_chooser_get_local_only ()
gtk_file_chooser_get_preview_filename, gtk_file_chooser_get_preview_filename ()
gtk_file_chooser_get_preview_uri, gtk_file_chooser_get_preview_uri ()
gtk_file_chooser_get_preview_widget, gtk_file_chooser_get_preview_widget ()
gtk_file_chooser_get_preview_widget_active, gtk_file_chooser_get_preview_widget_active ()
gtk_file_chooser_get_select_multiple, gtk_file_chooser_get_select_multiple ()
gtk_file_chooser_get_uri, gtk_file_chooser_get_uri ()
gtk_file_chooser_get_uris, gtk_file_chooser_get_uris ()
gtk_file_chooser_list_filters, gtk_file_chooser_list_filters ()
gtk_file_chooser_list_shortcut_folders, gtk_file_chooser_list_shortcut_folders ()
gtk_file_chooser_list_shortcut_folder_uris, gtk_file_chooser_list_shortcut_folder_uris ()
gtk_file_chooser_remove_filter, gtk_file_chooser_remove_filter ()
gtk_file_chooser_remove_shortcut_folder, gtk_file_chooser_remove_shortcut_folder ()
gtk_file_chooser_remove_shortcut_folder_uri, gtk_file_chooser_remove_shortcut_folder_uri ()
gtk_file_chooser_select_all, gtk_file_chooser_select_all ()
gtk_file_chooser_select_filename, gtk_file_chooser_select_filename ()
gtk_file_chooser_select_uri, gtk_file_chooser_select_uri ()
gtk_file_chooser_set_action, gtk_file_chooser_set_action ()
gtk_file_chooser_set_current_folder, gtk_file_chooser_set_current_folder ()
gtk_file_chooser_set_current_folder_uri, gtk_file_chooser_set_current_folder_uri ()
gtk_file_chooser_set_current_name, gtk_file_chooser_set_current_name ()
gtk_file_chooser_set_extra_widget, gtk_file_chooser_set_extra_widget ()
gtk_file_chooser_set_filename, gtk_file_chooser_set_filename ()
gtk_file_chooser_set_filter, gtk_file_chooser_set_filter ()
gtk_file_chooser_set_local_only, gtk_file_chooser_set_local_only ()
gtk_file_chooser_set_preview_widget, gtk_file_chooser_set_preview_widget ()
gtk_file_chooser_set_preview_widget_active, gtk_file_chooser_set_preview_widget_active ()
gtk_file_chooser_set_select_multiple, gtk_file_chooser_set_select_multiple ()
gtk_file_chooser_set_uri, gtk_file_chooser_set_uri ()
gtk_file_chooser_set_use_preview_label, gtk_file_chooser_set_use_preview_label ()
gtk_file_chooser_unselect_all, gtk_file_chooser_unselect_all ()
gtk_file_chooser_unselect_filename, gtk_file_chooser_unselect_filename ()
gtk_file_chooser_unselect_uri, gtk_file_chooser_unselect_uri ()
gtk_file_chooser_widget_new, gtk_file_chooser_widget_new ()
gtk_file_chooser_widget_new_with_backend, gtk_file_chooser_widget_new_with_backend ()
gtk_file_filter_add_custom, gtk_file_filter_add_custom ()
gtk_file_filter_add_mime_type, gtk_file_filter_add_mime_type ()
gtk_file_filter_add_pattern, gtk_file_filter_add_pattern ()
gtk_file_filter_filter, gtk_file_filter_filter ()
gtk_file_filter_get_name, gtk_file_filter_get_name ()
gtk_file_filter_get_needed, gtk_file_filter_get_needed ()
gtk_file_filter_new, gtk_file_filter_new ()
gtk_file_filter_set_name, gtk_file_filter_set_name ()
gtk_font_button_get_font_name, gtk_font_button_get_font_name ()
gtk_font_button_get_show_size, gtk_font_button_get_show_size ()
gtk_font_button_get_show_style, gtk_font_button_get_show_style ()
gtk_font_button_get_title, gtk_font_button_get_title ()
gtk_font_button_get_use_font, gtk_font_button_get_use_font ()
gtk_font_button_get_use_size, gtk_font_button_get_use_size ()
gtk_font_button_new, gtk_font_button_new ()
gtk_font_button_new_with_font, gtk_font_button_new_with_font ()
gtk_font_button_set_font_name, gtk_font_button_set_font_name ()
gtk_font_button_set_show_size, gtk_font_button_set_show_size ()
gtk_font_button_set_show_style, gtk_font_button_set_show_style ()
gtk_font_button_set_title, gtk_font_button_set_title ()
gtk_font_button_set_use_font, gtk_font_button_set_use_font ()
gtk_font_button_set_use_size, gtk_font_button_set_use_size ()
gtk_icon_info_copy, gtk_icon_info_copy ()
gtk_icon_info_free, gtk_icon_info_free ()
gtk_icon_info_get_attach_points, gtk_icon_info_get_attach_points ()
gtk_icon_info_get_base_size, gtk_icon_info_get_base_size ()
gtk_icon_info_get_builtin_pixbuf, gtk_icon_info_get_builtin_pixbuf ()
gtk_icon_info_get_display_name, gtk_icon_info_get_display_name ()
gtk_icon_info_get_embedded_rect, gtk_icon_info_get_embedded_rect ()
gtk_icon_info_get_filename, gtk_icon_info_get_filename ()
gtk_icon_info_load_icon, gtk_icon_info_load_icon ()
gtk_icon_info_set_raw_coordinates, gtk_icon_info_set_raw_coordinates ()
gtk_icon_theme_add_builtin_icon, gtk_icon_theme_add_builtin_icon ()
gtk_icon_theme_append_search_path, gtk_icon_theme_append_search_path ()
gtk_icon_theme_get_default, gtk_icon_theme_get_default ()
gtk_icon_theme_get_example_icon_name, gtk_icon_theme_get_example_icon_name ()
gtk_icon_theme_get_for_screen, gtk_icon_theme_get_for_screen ()
gtk_icon_theme_get_search_path, gtk_icon_theme_get_search_path ()
gtk_icon_theme_has_icon, gtk_icon_theme_has_icon ()
gtk_icon_theme_list_icons, gtk_icon_theme_list_icons ()
gtk_icon_theme_load_icon, gtk_icon_theme_load_icon ()
gtk_icon_theme_lookup_icon, gtk_icon_theme_lookup_icon ()
gtk_icon_theme_new, gtk_icon_theme_new ()
gtk_icon_theme_prepend_search_path, gtk_icon_theme_prepend_search_path ()
gtk_icon_theme_rescan_if_needed, gtk_icon_theme_rescan_if_needed ()
gtk_icon_theme_set_custom_theme, gtk_icon_theme_set_custom_theme ()
gtk_icon_theme_set_screen, gtk_icon_theme_set_screen ()
gtk_icon_theme_set_search_path, gtk_icon_theme_set_search_path ()
gtk_menu_attach, gtk_menu_attach ()
gtk_menu_set_monitor, gtk_menu_set_monitor ()
gtk_menu_shell_cancel, gtk_menu_shell_cancel ()
gtk_message_dialog_new_with_markup, gtk_message_dialog_new_with_markup ()
gtk_message_dialog_set_markup, gtk_message_dialog_set_markup ()
gtk_paned_get_child1, gtk_paned_get_child1 ()
gtk_paned_get_child2, gtk_paned_get_child2 ()
gtk_radio_action_get_current_value, gtk_radio_action_get_current_value ()
gtk_radio_action_get_group, gtk_radio_action_get_group ()
gtk_radio_action_new, gtk_radio_action_new ()
gtk_radio_action_set_group, gtk_radio_action_set_group ()
gtk_radio_menu_item_new_from_widget, gtk_radio_menu_item_new_from_widget ()
gtk_radio_menu_item_new_with_label_from_widget, gtk_radio_menu_item_new_with_label_from_widget ()
gtk_radio_menu_item_new_with_mnemonic_from_widget, gtk_radio_menu_item_new_with_mnemonic_from_widget ()
gtk_radio_tool_button_get_group, gtk_radio_tool_button_get_group ()
gtk_radio_tool_button_new, gtk_radio_tool_button_new ()
gtk_radio_tool_button_new_from_stock, gtk_radio_tool_button_new_from_stock ()
gtk_radio_tool_button_new_from_widget, gtk_radio_tool_button_new_from_widget ()
gtk_radio_tool_button_new_with_stock_from_widget, gtk_radio_tool_button_new_with_stock_from_widget ()
gtk_radio_tool_button_set_group, gtk_radio_tool_button_set_group ()
gtk_rc_reset_styles, gtk_rc_reset_styles ()
gtk_scale_get_layout, gtk_scale_get_layout ()
gtk_scale_get_layout_offsets, gtk_scale_get_layout_offsets ()
gtk_separator_tool_item_get_draw, gtk_separator_tool_item_get_draw ()
gtk_separator_tool_item_new, gtk_separator_tool_item_new ()
gtk_separator_tool_item_set_draw, gtk_separator_tool_item_set_draw ()
GTK_STOCK_DIALOG_AUTHENTICATION, GTK_STOCK_DIALOG_AUTHENTICATION
GTK_STOCK_HARDDISK, GTK_STOCK_HARDDISK
GTK_STOCK_INDENT, GTK_STOCK_INDENT
GTK_STOCK_NETWORK, GTK_STOCK_NETWORK
GTK_STOCK_UNINDENT, GTK_STOCK_UNINDENT
gtk_text_buffer_select_range, gtk_text_buffer_select_range ()
gtk_text_iter_backward_visible_cursor_position, gtk_text_iter_backward_visible_cursor_position ()
gtk_text_iter_backward_visible_cursor_positions, gtk_text_iter_backward_visible_cursor_positions ()
gtk_text_iter_backward_visible_word_start, gtk_text_iter_backward_visible_word_start ()
gtk_text_iter_backward_visible_word_starts, gtk_text_iter_backward_visible_word_starts ()
gtk_text_iter_forward_visible_cursor_position, gtk_text_iter_forward_visible_cursor_position ()
gtk_text_iter_forward_visible_cursor_positions, gtk_text_iter_forward_visible_cursor_positions ()
gtk_text_iter_forward_visible_word_end, gtk_text_iter_forward_visible_word_end ()
gtk_text_iter_forward_visible_word_ends, gtk_text_iter_forward_visible_word_ends ()
gtk_text_view_get_accepts_tab, gtk_text_view_get_accepts_tab ()
gtk_text_view_get_overwrite, gtk_text_view_get_overwrite ()
gtk_text_view_set_accepts_tab, gtk_text_view_set_accepts_tab ()
gtk_text_view_set_overwrite, gtk_text_view_set_overwrite ()
gtk_toggle_action_get_active, gtk_toggle_action_get_active ()
gtk_toggle_action_get_draw_as_radio, gtk_toggle_action_get_draw_as_radio ()
gtk_toggle_action_new, gtk_toggle_action_new ()
gtk_toggle_action_set_active, gtk_toggle_action_set_active ()
gtk_toggle_action_set_draw_as_radio, gtk_toggle_action_set_draw_as_radio ()
gtk_toggle_action_toggled, gtk_toggle_action_toggled ()
gtk_toggle_tool_button_get_active, gtk_toggle_tool_button_get_active ()
gtk_toggle_tool_button_new, gtk_toggle_tool_button_new ()
gtk_toggle_tool_button_new_from_stock, gtk_toggle_tool_button_new_from_stock ()
gtk_toggle_tool_button_set_active, gtk_toggle_tool_button_set_active ()
gtk_toolbar_get_drop_index, gtk_toolbar_get_drop_index ()
gtk_toolbar_get_item_index, gtk_toolbar_get_item_index ()
gtk_toolbar_get_nth_item, gtk_toolbar_get_nth_item ()
gtk_toolbar_get_n_items, gtk_toolbar_get_n_items ()
gtk_toolbar_get_relief_style, gtk_toolbar_get_relief_style ()
gtk_toolbar_get_show_arrow, gtk_toolbar_get_show_arrow ()
gtk_toolbar_insert, gtk_toolbar_insert ()
gtk_toolbar_set_drop_highlight_item, gtk_toolbar_set_drop_highlight_item ()
gtk_toolbar_set_show_arrow, gtk_toolbar_set_show_arrow ()
gtk_tooltips_get_info_from_tip_window, gtk_tooltips_get_info_from_tip_window ()
gtk_tool_button_get_icon_widget, gtk_tool_button_get_icon_widget ()
gtk_tool_button_get_label, gtk_tool_button_get_label ()
gtk_tool_button_get_label_widget, gtk_tool_button_get_label_widget ()
gtk_tool_button_get_stock_id, gtk_tool_button_get_stock_id ()
gtk_tool_button_get_use_underline, gtk_tool_button_get_use_underline ()
gtk_tool_button_new, gtk_tool_button_new ()
gtk_tool_button_new_from_stock, gtk_tool_button_new_from_stock ()
gtk_tool_button_set_icon_widget, gtk_tool_button_set_icon_widget ()
gtk_tool_button_set_label, gtk_tool_button_set_label ()
gtk_tool_button_set_label_widget, gtk_tool_button_set_label_widget ()
gtk_tool_button_set_stock_id, gtk_tool_button_set_stock_id ()
gtk_tool_button_set_use_underline, gtk_tool_button_set_use_underline ()
gtk_tool_item_get_expand, gtk_tool_item_get_expand ()
gtk_tool_item_get_homogeneous, gtk_tool_item_get_homogeneous ()
gtk_tool_item_get_icon_size, gtk_tool_item_get_icon_size ()
gtk_tool_item_get_is_important, gtk_tool_item_get_is_important ()
gtk_tool_item_get_orientation, gtk_tool_item_get_orientation ()
gtk_tool_item_get_proxy_menu_item, gtk_tool_item_get_proxy_menu_item ()
gtk_tool_item_get_relief_style, gtk_tool_item_get_relief_style ()
gtk_tool_item_get_toolbar_style, gtk_tool_item_get_toolbar_style ()
gtk_tool_item_get_use_drag_window, gtk_tool_item_get_use_drag_window ()
gtk_tool_item_get_visible_horizontal, gtk_tool_item_get_visible_horizontal ()
gtk_tool_item_get_visible_vertical, gtk_tool_item_get_visible_vertical ()
gtk_tool_item_new, gtk_tool_item_new ()
gtk_tool_item_retrieve_proxy_menu_item, gtk_tool_item_retrieve_proxy_menu_item ()
gtk_tool_item_set_expand, gtk_tool_item_set_expand ()
gtk_tool_item_set_homogeneous, gtk_tool_item_set_homogeneous ()
gtk_tool_item_set_is_important, gtk_tool_item_set_is_important ()
gtk_tool_item_set_proxy_menu_item, gtk_tool_item_set_proxy_menu_item ()
gtk_tool_item_set_tooltip, gtk_tool_item_set_tooltip ()
gtk_tool_item_set_use_drag_window, gtk_tool_item_set_use_drag_window ()
gtk_tool_item_set_visible_horizontal, gtk_tool_item_set_visible_horizontal ()
gtk_tool_item_set_visible_vertical, gtk_tool_item_set_visible_vertical ()
gtk_tree_model_filter_clear_cache, gtk_tree_model_filter_clear_cache ()
gtk_tree_model_filter_convert_child_iter_to_iter, gtk_tree_model_filter_convert_child_iter_to_iter ()
gtk_tree_model_filter_convert_child_path_to_path, gtk_tree_model_filter_convert_child_path_to_path ()
gtk_tree_model_filter_convert_iter_to_child_iter, gtk_tree_model_filter_convert_iter_to_child_iter ()
gtk_tree_model_filter_convert_path_to_child_path, gtk_tree_model_filter_convert_path_to_child_path ()
gtk_tree_model_filter_get_model, gtk_tree_model_filter_get_model ()
gtk_tree_model_filter_new, gtk_tree_model_filter_new ()
gtk_tree_model_filter_refilter, gtk_tree_model_filter_refilter ()
gtk_tree_model_filter_set_modify_func, gtk_tree_model_filter_set_modify_func ()
gtk_tree_model_filter_set_visible_column, gtk_tree_model_filter_set_visible_column ()
gtk_tree_model_filter_set_visible_func, gtk_tree_model_filter_set_visible_func ()
gtk_tree_view_column_get_expand, gtk_tree_view_column_get_expand ()
gtk_tree_view_column_set_expand, gtk_tree_view_column_set_expand ()
gtk_ui_manager_add_ui, gtk_ui_manager_add_ui ()
gtk_ui_manager_add_ui_from_file, gtk_ui_manager_add_ui_from_file ()
gtk_ui_manager_add_ui_from_string, gtk_ui_manager_add_ui_from_string ()
gtk_ui_manager_ensure_update, gtk_ui_manager_ensure_update ()
gtk_ui_manager_get_accel_group, gtk_ui_manager_get_accel_group ()
gtk_ui_manager_get_action, gtk_ui_manager_get_action ()
gtk_ui_manager_get_action_groups, gtk_ui_manager_get_action_groups ()
gtk_ui_manager_get_add_tearoffs, gtk_ui_manager_get_add_tearoffs ()
gtk_ui_manager_get_toplevels, gtk_ui_manager_get_toplevels ()
gtk_ui_manager_get_ui, gtk_ui_manager_get_ui ()
gtk_ui_manager_get_widget, gtk_ui_manager_get_widget ()
gtk_ui_manager_insert_action_group, gtk_ui_manager_insert_action_group ()
gtk_ui_manager_new, gtk_ui_manager_new ()
gtk_ui_manager_new_merge_id, gtk_ui_manager_new_merge_id ()
gtk_ui_manager_remove_action_group, gtk_ui_manager_remove_action_group ()
gtk_ui_manager_remove_ui, gtk_ui_manager_remove_ui ()
gtk_ui_manager_set_add_tearoffs, gtk_ui_manager_set_add_tearoffs ()
gtk_widget_add_mnemonic_label, gtk_widget_add_mnemonic_label ()
gtk_widget_can_activate_accel, gtk_widget_can_activate_accel ()
gtk_widget_get_no_show_all, gtk_widget_get_no_show_all ()
gtk_widget_list_mnemonic_labels, gtk_widget_list_mnemonic_labels ()
gtk_widget_queue_resize_no_redraw, gtk_widget_queue_resize_no_redraw ()
gtk_widget_remove_mnemonic_label, gtk_widget_remove_mnemonic_label ()
gtk_widget_set_no_show_all, gtk_widget_set_no_show_all ()
gtk_window_get_accept_focus, gtk_window_get_accept_focus ()
gtk_window_has_toplevel_focus, gtk_window_has_toplevel_focus ()
gtk_window_is_active, gtk_window_is_active ()
gtk_window_set_accept_focus, gtk_window_set_accept_focus ()
gtk_window_set_default_icon, gtk_window_set_default_icon ()
gtk_window_set_keep_above, gtk_window_set_keep_above ()
gtk_window_set_keep_below, gtk_window_set_keep_below ()


Index of new symbols in 2.6

G

GtkAboutDialog:artists, The "artists" property
GtkAboutDialog:authors, The "authors" property
GtkAboutDialog:comments, The "comments" property
GtkAboutDialog:copyright, The "copyright" property
GtkAboutDialog:documenters, The "documenters" property
GtkAboutDialog:license, The "license" property
GtkAboutDialog:logo, The "logo" property
GtkAboutDialog:logo-icon-name, The "logo-icon-name" property
GtkAboutDialog:name, The "name" property
GtkAboutDialog:translator-credits, The "translator-credits" property
GtkAboutDialog:version, The "version" property
GtkAboutDialog:website, The "website" property
GtkAboutDialog:website-label, The "website-label" property
GtkAction:visible-overflown, The "visible-overflown" property
GtkButton:displace-focus, The "displace-focus" style property
GtkCellRenderer::editing-started, The "editing-started" signal
GtkCellRendererCombo:has-entry, The "has-entry" property
GtkCellRendererCombo:model, The "model" property
GtkCellRendererCombo:text-column, The "text-column" property
GtkCellRendererProgress:text, The "text" property
GtkCellRendererProgress:value, The "value" property
GtkCellRendererText:ellipsize, The "ellipsize" property
GtkCellRendererText:width-chars, The "width-chars" property
GtkClipboardImageReceivedFunc, GtkClipboardImageReceivedFunc ()
GtkComboBox:add-tearoffs, The "add-tearoffs" property
GtkComboBox:has-frame, The "has-frame" property
GtkEntryCompletion::insert-prefix, The "insert-prefix" signal
GtkEntryCompletion:inline-completion, The "inline-completion" property
GtkEntryCompletion:popup-completion, The "popup-completion" property
GtkEntryCompletion:text-column, The "text-column" property
GtkFileChooserButton:dialog, The "dialog" property
GtkFileChooserButton:title, The "title" property
GtkFileChooserButton:width-chars, The "width-chars" property
GtkIconView:column-spacing, The "column-spacing" property
GtkIconView:columns, The "columns" property
GtkIconView:item-width, The "item-width" property
GtkIconView:margin, The "margin" property
GtkIconView:markup-column, The "markup-column" property
GtkIconView:orientation, The "orientation" property
GtkIconView:pixbuf-column, The "pixbuf-column" property
GtkIconView:row-spacing, The "row-spacing" property
GtkIconView:selection-mode, The "selection-mode" property
GtkIconView:spacing, The "spacing" property
GtkIconView:text-column, The "text-column" property
GtkImage:icon-name, The "icon-name" property
GtkImage:pixel-size, The "pixel-size" property
GtkLabel:angle, The "angle" property
GtkLabel:ellipsize, The "ellipsize" property
GtkLabel:max-width-chars, The "max-width-chars" property
GtkLabel:single-line-mode, The "single-line-mode" property
GtkLabel:width-chars, The "width-chars" property
GtkMenu:tearoff-state, The "tearoff-state" property
GtkProgressBar:ellipsize, The "ellipsize" property
GtkRange::change-value, The "change-value" signal
GtkTreeView:hover-expand, The "hover-expand" property
GtkTreeView:hover-selection, The "hover-selection" property
GtkWindow:icon-name, The "icon-name" property
gtk_about_dialog_get_artists, gtk_about_dialog_get_artists ()
gtk_about_dialog_get_authors, gtk_about_dialog_get_authors ()
gtk_about_dialog_get_comments, gtk_about_dialog_get_comments ()
gtk_about_dialog_get_copyright, gtk_about_dialog_get_copyright ()
gtk_about_dialog_get_documenters, gtk_about_dialog_get_documenters ()
gtk_about_dialog_get_license, gtk_about_dialog_get_license ()
gtk_about_dialog_get_logo, gtk_about_dialog_get_logo ()
gtk_about_dialog_get_logo_icon_name, gtk_about_dialog_get_logo_icon_name ()
gtk_about_dialog_get_name, gtk_about_dialog_get_name ()
gtk_about_dialog_get_translator_credits, gtk_about_dialog_get_translator_credits ()
gtk_about_dialog_get_version, gtk_about_dialog_get_version ()
gtk_about_dialog_get_website, gtk_about_dialog_get_website ()
gtk_about_dialog_get_website_label, gtk_about_dialog_get_website_label ()
gtk_about_dialog_new, gtk_about_dialog_new ()
gtk_about_dialog_set_artists, gtk_about_dialog_set_artists ()
gtk_about_dialog_set_authors, gtk_about_dialog_set_authors ()
gtk_about_dialog_set_comments, gtk_about_dialog_set_comments ()
gtk_about_dialog_set_copyright, gtk_about_dialog_set_copyright ()
gtk_about_dialog_set_documenters, gtk_about_dialog_set_documenters ()
gtk_about_dialog_set_email_hook, gtk_about_dialog_set_email_hook ()
gtk_about_dialog_set_license, gtk_about_dialog_set_license ()
gtk_about_dialog_set_logo, gtk_about_dialog_set_logo ()
gtk_about_dialog_set_logo_icon_name, gtk_about_dialog_set_logo_icon_name ()
gtk_about_dialog_set_name, gtk_about_dialog_set_name ()
gtk_about_dialog_set_translator_credits, gtk_about_dialog_set_translator_credits ()
gtk_about_dialog_set_url_hook, gtk_about_dialog_set_url_hook ()
gtk_about_dialog_set_version, gtk_about_dialog_set_version ()
gtk_about_dialog_set_website, gtk_about_dialog_set_website ()
gtk_about_dialog_set_website_label, gtk_about_dialog_set_website_label ()
gtk_accelerator_get_label, gtk_accelerator_get_label ()
gtk_action_get_accel_path, gtk_action_get_accel_path ()
gtk_action_group_translate_string, gtk_action_group_translate_string ()
gtk_action_set_sensitive, gtk_action_set_sensitive ()
gtk_action_set_visible, gtk_action_set_visible ()
gtk_alternative_dialog_button_order, gtk_alternative_dialog_button_order ()
gtk_button_get_image, gtk_button_get_image ()
gtk_button_set_image, gtk_button_set_image ()
gtk_cell_renderer_combo_new, gtk_cell_renderer_combo_new ()
gtk_cell_renderer_progress_new, gtk_cell_renderer_progress_new ()
gtk_cell_renderer_stop_editing, gtk_cell_renderer_stop_editing ()
gtk_cell_view_get_cell_renderers, gtk_cell_view_get_cell_renderers ()
gtk_cell_view_get_displayed_row, gtk_cell_view_get_displayed_row ()
gtk_cell_view_get_size_of_row, gtk_cell_view_get_size_of_row ()
gtk_cell_view_new, gtk_cell_view_new ()
gtk_cell_view_new_with_markup, gtk_cell_view_new_with_markup ()
gtk_cell_view_new_with_pixbuf, gtk_cell_view_new_with_pixbuf ()
gtk_cell_view_new_with_text, gtk_cell_view_new_with_text ()
gtk_cell_view_set_background_color, gtk_cell_view_set_background_color ()
gtk_cell_view_set_displayed_row, gtk_cell_view_set_displayed_row ()
gtk_cell_view_set_model, gtk_cell_view_set_model ()
gtk_clipboard_request_image, gtk_clipboard_request_image ()
gtk_clipboard_set_can_store, gtk_clipboard_set_can_store ()
gtk_clipboard_set_image, gtk_clipboard_set_image ()
gtk_clipboard_store, gtk_clipboard_store ()
gtk_clipboard_wait_for_image, gtk_clipboard_wait_for_image ()
gtk_clipboard_wait_is_image_available, gtk_clipboard_wait_is_image_available ()
gtk_clipboard_wait_is_target_available, gtk_clipboard_wait_is_target_available ()
gtk_combo_box_get_active_text, gtk_combo_box_get_active_text ()
gtk_combo_box_get_column_span_column, gtk_combo_box_get_column_span_column ()
gtk_combo_box_get_focus_on_click, gtk_combo_box_get_focus_on_click ()
gtk_combo_box_get_popup_accessible, gtk_combo_box_get_popup_accessible ()
gtk_combo_box_get_row_separator_func, gtk_combo_box_get_row_separator_func ()
gtk_combo_box_get_row_span_column, gtk_combo_box_get_row_span_column ()
gtk_combo_box_get_wrap_width, gtk_combo_box_get_wrap_width ()
gtk_combo_box_set_add_tearoffs, gtk_combo_box_set_add_tearoffs ()
gtk_combo_box_set_focus_on_click, gtk_combo_box_set_focus_on_click ()
gtk_combo_box_set_row_separator_func, gtk_combo_box_set_row_separator_func ()
gtk_dialog_set_alternative_button_order, gtk_dialog_set_alternative_button_order ()
gtk_dialog_set_alternative_button_order_from_array, gtk_dialog_set_alternative_button_order_from_array ()
gtk_drag_dest_add_image_targets, gtk_drag_dest_add_image_targets ()
gtk_drag_dest_add_text_targets, gtk_drag_dest_add_text_targets ()
gtk_drag_dest_add_uri_targets, gtk_drag_dest_add_uri_targets ()
gtk_drag_source_add_image_targets, gtk_drag_source_add_image_targets ()
gtk_drag_source_add_text_targets, gtk_drag_source_add_text_targets ()
gtk_drag_source_add_uri_targets, gtk_drag_source_add_uri_targets ()
gtk_entry_completion_get_inline_completion, gtk_entry_completion_get_inline_completion ()
gtk_entry_completion_get_popup_completion, gtk_entry_completion_get_popup_completion ()
gtk_entry_completion_get_text_column, gtk_entry_completion_get_text_column ()
gtk_entry_completion_insert_prefix, gtk_entry_completion_insert_prefix ()
gtk_entry_completion_set_inline_completion, gtk_entry_completion_set_inline_completion ()
gtk_entry_completion_set_popup_completion, gtk_entry_completion_set_popup_completion ()
gtk_file_chooser_button_get_title, gtk_file_chooser_button_get_title ()
gtk_file_chooser_button_get_width_chars, gtk_file_chooser_button_get_width_chars ()
gtk_file_chooser_button_new, gtk_file_chooser_button_new ()
gtk_file_chooser_button_new_with_backend, gtk_file_chooser_button_new_with_backend ()
gtk_file_chooser_button_new_with_dialog, gtk_file_chooser_button_new_with_dialog ()
gtk_file_chooser_button_set_title, gtk_file_chooser_button_set_title ()
gtk_file_chooser_button_set_width_chars, gtk_file_chooser_button_set_width_chars ()
gtk_file_chooser_get_show_hidden, gtk_file_chooser_get_show_hidden ()
gtk_file_chooser_set_show_hidden, gtk_file_chooser_set_show_hidden ()
gtk_file_filter_add_pixbuf_formats, gtk_file_filter_add_pixbuf_formats ()
gtk_get_option_group, gtk_get_option_group ()
gtk_icon_theme_get_icon_sizes, gtk_icon_theme_get_icon_sizes ()
gtk_icon_view_get_columns, gtk_icon_view_get_columns ()
gtk_icon_view_get_column_spacing, gtk_icon_view_get_column_spacing ()
gtk_icon_view_get_item_width, gtk_icon_view_get_item_width ()
gtk_icon_view_get_margin, gtk_icon_view_get_margin ()
gtk_icon_view_get_markup_column, gtk_icon_view_get_markup_column ()
gtk_icon_view_get_model, gtk_icon_view_get_model ()
gtk_icon_view_get_orientation, gtk_icon_view_get_orientation ()
gtk_icon_view_get_path_at_pos, gtk_icon_view_get_path_at_pos ()
gtk_icon_view_get_pixbuf_column, gtk_icon_view_get_pixbuf_column ()
gtk_icon_view_get_row_spacing, gtk_icon_view_get_row_spacing ()
gtk_icon_view_get_selected_items, gtk_icon_view_get_selected_items ()
gtk_icon_view_get_selection_mode, gtk_icon_view_get_selection_mode ()
gtk_icon_view_get_spacing, gtk_icon_view_get_spacing ()
gtk_icon_view_get_text_column, gtk_icon_view_get_text_column ()
gtk_icon_view_item_activated, gtk_icon_view_item_activated ()
gtk_icon_view_new, gtk_icon_view_new ()
gtk_icon_view_new_with_model, gtk_icon_view_new_with_model ()
gtk_icon_view_path_is_selected, gtk_icon_view_path_is_selected ()
gtk_icon_view_selected_foreach, gtk_icon_view_selected_foreach ()
gtk_icon_view_select_all, gtk_icon_view_select_all ()
gtk_icon_view_select_path, gtk_icon_view_select_path ()
gtk_icon_view_set_columns, gtk_icon_view_set_columns ()
gtk_icon_view_set_column_spacing, gtk_icon_view_set_column_spacing ()
gtk_icon_view_set_item_width, gtk_icon_view_set_item_width ()
gtk_icon_view_set_margin, gtk_icon_view_set_margin ()
gtk_icon_view_set_markup_column, gtk_icon_view_set_markup_column ()
gtk_icon_view_set_model, gtk_icon_view_set_model ()
gtk_icon_view_set_orientation, gtk_icon_view_set_orientation ()
gtk_icon_view_set_pixbuf_column, gtk_icon_view_set_pixbuf_column ()
gtk_icon_view_set_row_spacing, gtk_icon_view_set_row_spacing ()
gtk_icon_view_set_selection_mode, gtk_icon_view_set_selection_mode ()
gtk_icon_view_set_spacing, gtk_icon_view_set_spacing ()
gtk_icon_view_set_text_column, gtk_icon_view_set_text_column ()
gtk_icon_view_unselect_all, gtk_icon_view_unselect_all ()
gtk_icon_view_unselect_path, gtk_icon_view_unselect_path ()
gtk_image_get_icon_name, gtk_image_get_icon_name ()
gtk_image_get_pixel_size, gtk_image_get_pixel_size ()
gtk_image_new_from_icon_name, gtk_image_new_from_icon_name ()
gtk_image_set_from_icon_name, gtk_image_set_from_icon_name ()
gtk_image_set_pixel_size, gtk_image_set_pixel_size ()
gtk_init_with_args, gtk_init_with_args ()
gtk_label_get_angle, gtk_label_get_angle ()
gtk_label_get_ellipsize, gtk_label_get_ellipsize ()
gtk_label_get_max_width_chars, gtk_label_get_max_width_chars ()
gtk_label_get_single_line_mode, gtk_label_get_single_line_mode ()
gtk_label_get_width_chars, gtk_label_get_width_chars ()
gtk_label_set_angle, gtk_label_set_angle ()
gtk_label_set_ellipsize, gtk_label_set_ellipsize ()
gtk_label_set_max_width_chars, gtk_label_set_max_width_chars ()
gtk_label_set_single_line_mode, gtk_label_set_single_line_mode ()
gtk_label_set_width_chars, gtk_label_set_width_chars ()
gtk_list_store_insert_with_values, gtk_list_store_insert_with_values ()
gtk_list_store_insert_with_valuesv, gtk_list_store_insert_with_valuesv ()
gtk_menu_get_for_attach_widget, gtk_menu_get_for_attach_widget ()
gtk_menu_tool_button_get_menu, gtk_menu_tool_button_get_menu ()
gtk_menu_tool_button_new, gtk_menu_tool_button_new ()
gtk_menu_tool_button_new_from_stock, gtk_menu_tool_button_new_from_stock ()
gtk_menu_tool_button_set_arrow_tooltip, gtk_menu_tool_button_set_arrow_tooltip ()
gtk_menu_tool_button_set_menu, gtk_menu_tool_button_set_menu ()
gtk_message_dialog_format_secondary_markup, gtk_message_dialog_format_secondary_markup ()
gtk_message_dialog_format_secondary_text, gtk_message_dialog_format_secondary_text ()
gtk_progress_bar_get_ellipsize, gtk_progress_bar_get_ellipsize ()
gtk_progress_bar_set_ellipsize, gtk_progress_bar_set_ellipsize ()
gtk_selection_data_get_pixbuf, gtk_selection_data_get_pixbuf ()
gtk_selection_data_get_uris, gtk_selection_data_get_uris ()
gtk_selection_data_set_pixbuf, gtk_selection_data_set_pixbuf ()
gtk_selection_data_set_uris, gtk_selection_data_set_uris ()
gtk_selection_data_targets_include_image, gtk_selection_data_targets_include_image ()
gtk_show_about_dialog, gtk_show_about_dialog ()
GTK_STOCK_ABOUT, GTK_STOCK_ABOUT
GTK_STOCK_CONNECT, GTK_STOCK_CONNECT
GTK_STOCK_DIRECTORY, GTK_STOCK_DIRECTORY
GTK_STOCK_DISCONNECT, GTK_STOCK_DISCONNECT
GTK_STOCK_EDIT, GTK_STOCK_EDIT
GTK_STOCK_FILE, GTK_STOCK_FILE
GTK_STOCK_MEDIA_FORWARD, GTK_STOCK_MEDIA_FORWARD
GTK_STOCK_MEDIA_NEXT, GTK_STOCK_MEDIA_NEXT
GTK_STOCK_MEDIA_PAUSE, GTK_STOCK_MEDIA_PAUSE
GTK_STOCK_MEDIA_PLAY, GTK_STOCK_MEDIA_PLAY
GTK_STOCK_MEDIA_PREVIOUS, GTK_STOCK_MEDIA_PREVIOUS
GTK_STOCK_MEDIA_RECORD, GTK_STOCK_MEDIA_RECORD
GTK_STOCK_MEDIA_REWIND, GTK_STOCK_MEDIA_REWIND
GTK_STOCK_MEDIA_STOP, GTK_STOCK_MEDIA_STOP
gtk_target_list_add_image_targets, gtk_target_list_add_image_targets ()
gtk_target_list_add_text_targets, gtk_target_list_add_text_targets ()
gtk_target_list_add_uri_targets, gtk_target_list_add_uri_targets ()
gtk_text_buffer_backspace, gtk_text_buffer_backspace ()
gtk_text_view_get_iter_at_position, gtk_text_view_get_iter_at_position ()
gtk_tool_item_rebuild_menu, gtk_tool_item_rebuild_menu ()
gtk_tree_view_get_fixed_height_mode, gtk_tree_view_get_fixed_height_mode ()
gtk_tree_view_get_hover_expand, gtk_tree_view_get_hover_expand ()
gtk_tree_view_get_hover_selection, gtk_tree_view_get_hover_selection ()
gtk_tree_view_get_row_separator_func, gtk_tree_view_get_row_separator_func ()
gtk_tree_view_set_fixed_height_mode, gtk_tree_view_set_fixed_height_mode ()
gtk_tree_view_set_hover_expand, gtk_tree_view_set_hover_expand ()
gtk_tree_view_set_hover_selection, gtk_tree_view_set_hover_selection ()
gtk_tree_view_set_row_separator_func, gtk_tree_view_set_row_separator_func ()
gtk_window_get_focus_on_map, gtk_window_get_focus_on_map ()
gtk_window_get_icon_name, gtk_window_get_icon_name ()
gtk_window_set_default_icon_name, gtk_window_set_default_icon_name ()
gtk_window_set_focus_on_map, gtk_window_set_focus_on_map ()
gtk_window_set_icon_name, gtk_window_set_icon_name ()


Index of new symbols in 2.8

G

GtkAboutDialog:wrap-license, The "wrap-license" property
GtkCellRendererPixbuf:follow-state, The "follow-state" property
GtkCellRendererPixbuf:icon-name, The "icon-name" property
GtkCellRendererText:wrap-mode, The "wrap-mode" property
GtkCellRendererText:wrap-width, The "wrap-width" property
GtkEntryCompletion:popup-set-width, The "popup-set-width" property
GtkEntryCompletion:popup-single-match, The "popup-single-match" property
GtkIconView:reorderable, The "reorderable" property
GtkMenuBar:child-pack-direction, The "child-pack-direction" property
GtkMenuBar:pack-direction, The "pack-direction" property
GtkMenuShell:take-focus, The "take-focus" property
GtkRadioMenuItem:group, The "group" property
GtkRuler:metric, The "metric" property
GtkSizeGroup:ignore-hidden, The "ignore-hidden" property
GtkTextBuffer:text, The "text" property
GtkTextTag:invisible, The "invisible" property
GtkTextTag:paragraph-background, The "paragraph-background" property
GtkTextTag:paragraph-background-gdk, The "paragraph-background-gdk" property
GtkToggleToolButton:active, The "active" property
GtkToolbar:tooltips, The "tooltips" property
GtkToolButton:icon-name, The "icon-name" property
GtkWidget::grab-broken-event, The "grab-broken-event" signal
GtkWidget:draw-border, The "draw-border" style property
gtk_about_dialog_get_wrap_license, gtk_about_dialog_get_wrap_license ()
gtk_about_dialog_set_wrap_license, gtk_about_dialog_set_wrap_license ()
gtk_action_get_accel_closure, gtk_action_get_accel_closure ()
gtk_dialog_get_response_for_widget, gtk_dialog_get_response_for_widget ()
gtk_drag_set_icon_name, gtk_drag_set_icon_name ()
gtk_drag_source_set_icon_name, gtk_drag_source_set_icon_name ()
gtk_entry_completion_get_popup_set_width, gtk_entry_completion_get_popup_set_width ()
gtk_entry_completion_get_popup_single_match, gtk_entry_completion_get_popup_single_match ()
gtk_entry_completion_set_popup_set_width, gtk_entry_completion_set_popup_set_width ()
gtk_entry_completion_set_popup_single_match, gtk_entry_completion_set_popup_single_match ()
gtk_file_chooser_get_do_overwrite_confirmation, gtk_file_chooser_get_do_overwrite_confirmation ()
gtk_file_chooser_set_do_overwrite_confirmation, gtk_file_chooser_set_do_overwrite_confirmation ()
gtk_icon_view_create_drag_icon, gtk_icon_view_create_drag_icon ()
gtk_icon_view_enable_model_drag_dest, gtk_icon_view_enable_model_drag_dest ()
gtk_icon_view_enable_model_drag_source, gtk_icon_view_enable_model_drag_source ()
gtk_icon_view_get_cursor, gtk_icon_view_get_cursor ()
gtk_icon_view_get_dest_item_at_pos, gtk_icon_view_get_dest_item_at_pos ()
gtk_icon_view_get_drag_dest_item, gtk_icon_view_get_drag_dest_item ()
gtk_icon_view_get_item_at_pos, gtk_icon_view_get_item_at_pos ()
gtk_icon_view_get_reorderable, gtk_icon_view_get_reorderable ()
gtk_icon_view_get_visible_range, gtk_icon_view_get_visible_range ()
gtk_icon_view_scroll_to_path, gtk_icon_view_scroll_to_path ()
gtk_icon_view_set_cursor, gtk_icon_view_set_cursor ()
gtk_icon_view_set_drag_dest_item, gtk_icon_view_set_drag_dest_item ()
gtk_icon_view_set_reorderable, gtk_icon_view_set_reorderable ()
gtk_icon_view_unset_model_drag_dest, gtk_icon_view_unset_model_drag_dest ()
gtk_icon_view_unset_model_drag_source, gtk_icon_view_unset_model_drag_source ()
gtk_image_clear, gtk_image_clear ()
gtk_menu_bar_get_child_pack_direction, gtk_menu_bar_get_child_pack_direction ()
gtk_menu_bar_get_pack_direction, gtk_menu_bar_get_pack_direction ()
gtk_menu_bar_set_child_pack_direction, gtk_menu_bar_set_child_pack_direction ()
gtk_menu_bar_set_pack_direction, gtk_menu_bar_set_pack_direction ()
gtk_menu_shell_get_take_focus, gtk_menu_shell_get_take_focus ()
gtk_menu_shell_set_take_focus, gtk_menu_shell_set_take_focus ()
gtk_scrolled_window_get_hscrollbar, gtk_scrolled_window_get_hscrollbar ()
gtk_scrolled_window_get_vscrollbar, gtk_scrolled_window_get_vscrollbar ()
gtk_size_group_get_ignore_hidden, gtk_size_group_get_ignore_hidden ()
gtk_size_group_set_ignore_hidden, gtk_size_group_set_ignore_hidden ()
GTK_STOCK_FULLSCREEN, GTK_STOCK_FULLSCREEN
GTK_STOCK_INFO, GTK_STOCK_INFO
GTK_STOCK_LEAVE_FULLSCREEN, GTK_STOCK_LEAVE_FULLSCREEN
gtk_stock_set_translate_func, gtk_stock_set_translate_func ()
gtk_text_iter_backward_visible_line, gtk_text_iter_backward_visible_line ()
gtk_text_iter_backward_visible_lines, gtk_text_iter_backward_visible_lines ()
gtk_text_iter_forward_visible_line, gtk_text_iter_forward_visible_line ()
gtk_text_iter_forward_visible_lines, gtk_text_iter_forward_visible_lines ()
gtk_tool_button_get_icon_name, gtk_tool_button_get_icon_name ()
gtk_tool_button_set_icon_name, gtk_tool_button_set_icon_name ()
gtk_tree_row_reference_get_model, gtk_tree_row_reference_get_model ()
gtk_tree_view_column_queue_resize, gtk_tree_view_column_queue_resize ()
gtk_tree_view_get_visible_range, gtk_tree_view_get_visible_range ()
gtk_window_get_urgency_hint, gtk_window_get_urgency_hint ()
gtk_window_present_with_time, gtk_window_present_with_time ()
gtk_window_set_urgency_hint, gtk_window_set_urgency_hint ()


Index of new symbols in 2.10

G

GtkAction:icon-name, The "icon-name" property
GtkAssistant::apply, The "apply" signal
GtkAssistant::cancel, The "cancel" signal
GtkAssistant::close, The "close" signal
GtkAssistant::prepare, The "prepare" signal
GtkAssistant:complete, The "complete" child property
GtkAssistant:header-image, The "header-image" child property
GtkAssistant:page-type, The "page-type" child property
GtkAssistant:title, The "title" child property
GtkButton:image-position, The "image-position" property
GtkButton:inner-border, The "inner-border" style property
GtkCellRendererAccel::accel-cleared, The "accel-cleared" signal
GtkCellRendererAccel::accel-edited, The "accel-edited" signal
GtkCellRendererAccel:accel-key, The "accel-key" property
GtkCellRendererAccel:accel-mode, The "accel-mode" property
GtkCellRendererAccel:accel-mods, The "accel-mods" property
GtkCellRendererAccel:keycode, The "keycode" property
GtkCellRendererSpin:adjustment, The "adjustment" property
GtkCellRendererSpin:climb-rate, The "climb-rate" property
GtkCellRendererSpin:digits, The "digits" property
GtkCellRendererText:alignment, The "alignment" property
GtkComboBox:popup-shown, The "popup-shown" property
GtkComboBox:tearoff-title, The "tearoff-title" property
GtkEntry:inner-border, The "inner-border" property, The "inner-border" style property
GtkEntry:truncate-multiline, The "truncate-multiline" property
GtkFileChooserButton:focus-on-click, The "focus-on-click" property
GtkLabel:wrap-mode, The "wrap-mode" property
GtkLinkButton:uri, The "uri" property
GtkMessageDialog:image, The "image" property
GtkMessageDialog:secondary-text, The "secondary-text" property
GtkMessageDialog:secondary-use-markup, The "secondary-use-markup" property
GtkMessageDialog:text, The "text" property
GtkMessageDialog:use-markup, The "use-markup" property
GtkNotebook::page-added, The "page-added" signal
GtkNotebook::page-removed, The "page-removed" signal
GtkNotebook::page-reordered, The "page-reordered" signal
GtkNotebook:arrow-spacing, The "arrow-spacing" style property
GtkNotebook:tab-curvature, The "tab-curvature" style property
GtkNotebook:tab-overlap, The "tab-overlap" style property
GtkPrinter::details-acquired, The "details-acquired" signal
GtkPrintJob::status-changed, The "status-changed" signal
GtkPrintOperation::begin-print, The "begin-print" signal
GtkPrintOperation::create-custom-widget, The "create-custom-widget" signal
GtkPrintOperation::custom-widget-apply, The "custom-widget-apply" signal
GtkPrintOperation::done, The "done" signal
GtkPrintOperation::draw-page, The "draw-page" signal
GtkPrintOperation::end-print, The "end-print" signal
GtkPrintOperation::paginate, The "paginate" signal
GtkPrintOperation::preview, The "preview" signal
GtkPrintOperation::request-page-setup, The "request-page-setup" signal
GtkPrintOperation::status-changed, The "status-changed" signal
GtkPrintOperation:allow-async, The "allow-async" property
GtkPrintOperation:current-page, The "current-page" property
GtkPrintOperation:custom-tab-label, The "custom-tab-label" property
GtkPrintOperation:default-page-setup, The "default-page-setup" property
GtkPrintOperation:export-filename, The "export-filename" property
GtkPrintOperation:job-name, The "job-name" property
GtkPrintOperation:n-pages, The "n-pages" property
GtkPrintOperation:print-settings, The "print-settings" property
GtkPrintOperation:show-progress, The "show-progress" property
GtkPrintOperation:status, The "status" property
GtkPrintOperation:status-string, The "status-string" property
GtkPrintOperation:track-print-status, The "track-print-status" property
GtkPrintOperation:unit, The "unit" property
GtkPrintOperation:use-full-page, The "use-full-page" property
GtkRadioAction:current-value, The "current-value" property
GtkRange:trough-side-details, The "trough-side-details" style property
GtkRange:trough-under-steppers, The "trough-under-steppers" style property
GtkRecentChooser::item-activated, The "item-activated" signal
GtkRecentChooser::selection-changed, The "selection-changed" signal
GtkRecentChooserMenu:show-numbers, The "show-numbers" property
GtkRecentManager::changed, The "changed" signal
GtkRecentManager:filename, The "filename" property
GtkRecentManager:limit, The "limit" property
GtkRecentManager:size, The "size" property
GtkScrolledWindow:window-placement-set, The "window-placement-set" property
GtkSettings:color-hash, The "color-hash" property
GtkSettings:gtk-color-scheme, The "gtk-color-scheme" property
GtkSettings:gtk-entry-password-hint-timeout, The "gtk-entry-password-hint-timeout" property
GtkSettings:gtk-scrolled-window-placement, The "gtk-scrolled-window-placement" property
GtkSettings:gtk-touchscreen-mode, The "gtk-touchscreen-mode" property
GtkSpinButton::wrapped, The "wrapped" signal
GtkStatusIcon::activate, The "activate" signal
GtkStatusIcon::popup-menu, The "popup-menu" signal
GtkStatusIcon::size-changed, The "size-changed" signal
GtkTextBuffer:copy-target-list, The "copy-target-list" property
GtkTextBuffer:cursor-position, The "cursor-position" property
GtkTextBuffer:has-selection, The "has-selection" property
GtkTextBuffer:paste-target-list, The "paste-target-list" property
GtkToggleAction:active, The "active" property
GtkToolbar:icon-size, The "icon-size" property
GtkToolbar:icon-size-set, The "icon-size-set" property
GtkWidget:link-color, The "link-color" style property
GtkWidget:scroll-arrow-hlength, The "scroll-arrow-hlength" style property
GtkWidget:scroll-arrow-vlength, The "scroll-arrow-vlength" style property
GtkWidget:separator-height, The "separator-height" style property
GtkWidget:separator-width, The "separator-width" style property
GtkWidget:visited-link-color, The "visited-link-color" style property
GtkWidget:wide-separators, The "wide-separators" style property
GtkWindow:deletable, The "deletable" property
GtkWindow:transient-for, The "transient-for" property
gtk_assistant_add_action_widget, gtk_assistant_add_action_widget ()
gtk_assistant_append_page, gtk_assistant_append_page ()
gtk_assistant_get_current_page, gtk_assistant_get_current_page ()
gtk_assistant_get_nth_page, gtk_assistant_get_nth_page ()
gtk_assistant_get_n_pages, gtk_assistant_get_n_pages ()
gtk_assistant_get_page_complete, gtk_assistant_get_page_complete ()
gtk_assistant_get_page_header_image, gtk_assistant_get_page_header_image ()
gtk_assistant_get_page_side_image, gtk_assistant_get_page_side_image ()
gtk_assistant_get_page_title, gtk_assistant_get_page_title ()
gtk_assistant_get_page_type, gtk_assistant_get_page_type ()
gtk_assistant_insert_page, gtk_assistant_insert_page ()
gtk_assistant_new, gtk_assistant_new ()
gtk_assistant_prepend_page, gtk_assistant_prepend_page ()
gtk_assistant_remove_action_widget, gtk_assistant_remove_action_widget ()
gtk_assistant_set_current_page, gtk_assistant_set_current_page ()
gtk_assistant_set_forward_page_func, gtk_assistant_set_forward_page_func ()
gtk_assistant_set_page_complete, gtk_assistant_set_page_complete ()
gtk_assistant_set_page_header_image, gtk_assistant_set_page_header_image ()
gtk_assistant_set_page_side_image, gtk_assistant_set_page_side_image ()
gtk_assistant_set_page_title, gtk_assistant_set_page_title ()
gtk_assistant_set_page_type, gtk_assistant_set_page_type ()
gtk_assistant_update_buttons_state, gtk_assistant_update_buttons_state ()
gtk_button_get_image_position, gtk_button_get_image_position ()
gtk_button_set_image_position, gtk_button_set_image_position ()
gtk_cell_renderer_accel_new, gtk_cell_renderer_accel_new ()
gtk_cell_renderer_spin_new, gtk_cell_renderer_spin_new ()
gtk_clipboard_request_rich_text, gtk_clipboard_request_rich_text ()
gtk_clipboard_wait_for_rich_text, gtk_clipboard_wait_for_rich_text ()
gtk_clipboard_wait_is_rich_text_available, gtk_clipboard_wait_is_rich_text_available ()
gtk_combo_box_get_title, gtk_combo_box_get_title ()
gtk_combo_box_set_title, gtk_combo_box_set_title ()
gtk_drag_dest_get_track_motion, gtk_drag_dest_get_track_motion ()
gtk_drag_dest_set_track_motion, gtk_drag_dest_set_track_motion ()
gtk_entry_get_inner_border, gtk_entry_get_inner_border ()
gtk_entry_set_inner_border, gtk_entry_set_inner_border ()
gtk_enumerate_printers, gtk_enumerate_printers ()
gtk_file_chooser_button_get_focus_on_click, gtk_file_chooser_button_get_focus_on_click ()
gtk_file_chooser_button_set_focus_on_click, gtk_file_chooser_button_set_focus_on_click ()
gtk_label_get_line_wrap_mode, gtk_label_get_line_wrap_mode ()
gtk_label_set_line_wrap_mode, gtk_label_set_line_wrap_mode ()
gtk_link_button_get_uri, gtk_link_button_get_uri ()
gtk_link_button_new, gtk_link_button_new ()
gtk_link_button_new_with_label, gtk_link_button_new_with_label ()
gtk_link_button_set_uri, gtk_link_button_set_uri ()
gtk_link_button_set_uri_hook, gtk_link_button_set_uri_hook ()
gtk_message_dialog_set_image, gtk_message_dialog_set_image ()
gtk_notebook_get_group_id, gtk_notebook_get_group_id ()
gtk_notebook_get_tab_detachable, gtk_notebook_get_tab_detachable ()
gtk_notebook_get_tab_reorderable, gtk_notebook_get_tab_reorderable ()
gtk_notebook_set_group_id, gtk_notebook_set_group_id ()
gtk_notebook_set_tab_detachable, gtk_notebook_set_tab_detachable ()
gtk_notebook_set_tab_reorderable, gtk_notebook_set_tab_reorderable ()
gtk_notebook_set_window_creation_hook, gtk_notebook_set_window_creation_hook ()
gtk_page_setup_copy, gtk_page_setup_copy ()
gtk_page_setup_get_bottom_margin, gtk_page_setup_get_bottom_margin ()
gtk_page_setup_get_left_margin, gtk_page_setup_get_left_margin ()
gtk_page_setup_get_orientation, gtk_page_setup_get_orientation ()
gtk_page_setup_get_page_height, gtk_page_setup_get_page_height ()
gtk_page_setup_get_page_width, gtk_page_setup_get_page_width ()
gtk_page_setup_get_paper_height, gtk_page_setup_get_paper_height ()
gtk_page_setup_get_paper_size, gtk_page_setup_get_paper_size ()
gtk_page_setup_get_paper_width, gtk_page_setup_get_paper_width ()
gtk_page_setup_get_right_margin, gtk_page_setup_get_right_margin ()
gtk_page_setup_get_top_margin, gtk_page_setup_get_top_margin ()
gtk_page_setup_new, gtk_page_setup_new ()
gtk_page_setup_set_bottom_margin, gtk_page_setup_set_bottom_margin ()
gtk_page_setup_set_left_margin, gtk_page_setup_set_left_margin ()
gtk_page_setup_set_orientation, gtk_page_setup_set_orientation ()
gtk_page_setup_set_paper_size, gtk_page_setup_set_paper_size ()
gtk_page_setup_set_paper_size_and_default_margins, gtk_page_setup_set_paper_size_and_default_margins ()
gtk_page_setup_set_right_margin, gtk_page_setup_set_right_margin ()
gtk_page_setup_set_top_margin, gtk_page_setup_set_top_margin ()
gtk_page_setup_unix_dialog_get_page_setup, gtk_page_setup_unix_dialog_get_page_setup ()
gtk_page_setup_unix_dialog_get_print_settings, gtk_page_setup_unix_dialog_get_print_settings ()
gtk_page_setup_unix_dialog_new, gtk_page_setup_unix_dialog_new ()
gtk_page_setup_unix_dialog_set_page_setup, gtk_page_setup_unix_dialog_set_page_setup ()
gtk_page_setup_unix_dialog_set_print_settings, gtk_page_setup_unix_dialog_set_print_settings ()
gtk_paper_size_copy, gtk_paper_size_copy ()
gtk_paper_size_free, gtk_paper_size_free ()
gtk_paper_size_get_default, gtk_paper_size_get_default ()
gtk_paper_size_get_default_bottom_margin, gtk_paper_size_get_default_bottom_margin ()
gtk_paper_size_get_default_left_margin, gtk_paper_size_get_default_left_margin ()
gtk_paper_size_get_default_right_margin, gtk_paper_size_get_default_right_margin ()
gtk_paper_size_get_default_top_margin, gtk_paper_size_get_default_top_margin ()
gtk_paper_size_get_display_name, gtk_paper_size_get_display_name ()
gtk_paper_size_get_height, gtk_paper_size_get_height ()
gtk_paper_size_get_name, gtk_paper_size_get_name ()
gtk_paper_size_get_ppd_name, gtk_paper_size_get_ppd_name ()
gtk_paper_size_get_width, gtk_paper_size_get_width ()
gtk_paper_size_is_equal, gtk_paper_size_is_equal ()
gtk_paper_size_new, gtk_paper_size_new ()
gtk_paper_size_new_custom, gtk_paper_size_new_custom ()
gtk_paper_size_new_from_ppd, gtk_paper_size_new_from_ppd ()
gtk_paper_size_set_size, gtk_paper_size_set_size ()
gtk_printer_accepts_pdf, gtk_printer_accepts_pdf ()
gtk_printer_accepts_ps, gtk_printer_accepts_ps ()
gtk_printer_compare, gtk_printer_compare ()
gtk_printer_get_backend, gtk_printer_get_backend ()
gtk_printer_get_description, gtk_printer_get_description ()
gtk_printer_get_icon_name, gtk_printer_get_icon_name ()
gtk_printer_get_job_count, gtk_printer_get_job_count ()
gtk_printer_get_location, gtk_printer_get_location ()
gtk_printer_get_name, gtk_printer_get_name ()
gtk_printer_get_state_message, gtk_printer_get_state_message ()
gtk_printer_is_active, gtk_printer_is_active ()
gtk_printer_is_default, gtk_printer_is_default ()
gtk_printer_is_virtual, gtk_printer_is_virtual ()
gtk_printer_new, gtk_printer_new ()
gtk_print_context_create_pango_context, gtk_print_context_create_pango_context ()
gtk_print_context_create_pango_layout, gtk_print_context_create_pango_layout ()
gtk_print_context_get_cairo_context, gtk_print_context_get_cairo_context ()
gtk_print_context_get_dpi_x, gtk_print_context_get_dpi_x ()
gtk_print_context_get_dpi_y, gtk_print_context_get_dpi_y ()
gtk_print_context_get_height, gtk_print_context_get_height ()
gtk_print_context_get_page_setup, gtk_print_context_get_page_setup ()
gtk_print_context_get_pango_fontmap, gtk_print_context_get_pango_fontmap ()
gtk_print_context_get_width, gtk_print_context_get_width ()
gtk_print_context_set_cairo_context, gtk_print_context_set_cairo_context ()
gtk_print_job_get_printer, gtk_print_job_get_printer ()
gtk_print_job_get_settings, gtk_print_job_get_settings ()
gtk_print_job_get_status, gtk_print_job_get_status ()
gtk_print_job_get_surface, gtk_print_job_get_surface ()
gtk_print_job_get_title, gtk_print_job_get_title ()
gtk_print_job_get_track_print_status, gtk_print_job_get_track_print_status ()
gtk_print_job_new, gtk_print_job_new ()
gtk_print_job_send, gtk_print_job_send ()
gtk_print_job_set_source_file, gtk_print_job_set_source_file ()
gtk_print_job_set_track_print_status, gtk_print_job_set_track_print_status ()
gtk_print_operation_cancel, gtk_print_operation_cancel ()
gtk_print_operation_get_default_page_setup, gtk_print_operation_get_default_page_setup ()
gtk_print_operation_get_error, gtk_print_operation_get_error (), gtk_print_operation_get_error ()
gtk_print_operation_get_print_settings, gtk_print_operation_get_print_settings ()
gtk_print_operation_get_status, gtk_print_operation_get_status ()
gtk_print_operation_get_status_string, gtk_print_operation_get_status_string ()
gtk_print_operation_is_finished, gtk_print_operation_is_finished ()
gtk_print_operation_new, gtk_print_operation_new ()
gtk_print_operation_preview_end_preview, gtk_print_operation_preview_end_preview ()
gtk_print_operation_preview_is_selected, gtk_print_operation_preview_is_selected ()
gtk_print_operation_preview_render_page, gtk_print_operation_preview_render_page ()
gtk_print_operation_run, gtk_print_operation_run ()
gtk_print_operation_set_allow_async, gtk_print_operation_set_allow_async ()
gtk_print_operation_set_current_page, gtk_print_operation_set_current_page ()
gtk_print_operation_set_custom_tab_label, gtk_print_operation_set_custom_tab_label ()
gtk_print_operation_set_default_page_setup, gtk_print_operation_set_default_page_setup ()
gtk_print_operation_set_export_filename, gtk_print_operation_set_export_filename ()
gtk_print_operation_set_job_name, gtk_print_operation_set_job_name ()
gtk_print_operation_set_n_pages, gtk_print_operation_set_n_pages ()
gtk_print_operation_set_print_settings, gtk_print_operation_set_print_settings ()
gtk_print_operation_set_show_progress, gtk_print_operation_set_show_progress ()
gtk_print_operation_set_track_print_status, gtk_print_operation_set_track_print_status ()
gtk_print_operation_set_unit, gtk_print_operation_set_unit ()
gtk_print_operation_set_use_full_page, gtk_print_operation_set_use_full_page ()
gtk_print_run_page_setup_dialog, gtk_print_run_page_setup_dialog ()
gtk_print_run_page_setup_dialog_async, gtk_print_run_page_setup_dialog_async ()
gtk_print_settings_copy, gtk_print_settings_copy ()
gtk_print_settings_foreach, gtk_print_settings_foreach ()
gtk_print_settings_get, gtk_print_settings_get ()
gtk_print_settings_get_bool, gtk_print_settings_get_bool ()
gtk_print_settings_get_collate, gtk_print_settings_get_collate ()
gtk_print_settings_get_default_source, gtk_print_settings_get_default_source ()
gtk_print_settings_get_dither, gtk_print_settings_get_dither ()
gtk_print_settings_get_double, gtk_print_settings_get_double ()
gtk_print_settings_get_double_with_default, gtk_print_settings_get_double_with_default ()
gtk_print_settings_get_duplex, gtk_print_settings_get_duplex ()
gtk_print_settings_get_finishings, gtk_print_settings_get_finishings ()
gtk_print_settings_get_int, gtk_print_settings_get_int ()
gtk_print_settings_get_int_with_default, gtk_print_settings_get_int_with_default ()
gtk_print_settings_get_length, gtk_print_settings_get_length ()
gtk_print_settings_get_media_type, gtk_print_settings_get_media_type ()
gtk_print_settings_get_number_up, gtk_print_settings_get_number_up ()
gtk_print_settings_get_n_copies, gtk_print_settings_get_n_copies ()
gtk_print_settings_get_orientation, gtk_print_settings_get_orientation ()
gtk_print_settings_get_output_bin, gtk_print_settings_get_output_bin ()
gtk_print_settings_get_page_ranges, gtk_print_settings_get_page_ranges ()
gtk_print_settings_get_page_set, gtk_print_settings_get_page_set ()
gtk_print_settings_get_paper_height, gtk_print_settings_get_paper_height ()
gtk_print_settings_get_paper_size, gtk_print_settings_get_paper_size ()
gtk_print_settings_get_paper_width, gtk_print_settings_get_paper_width ()
gtk_print_settings_get_printer, gtk_print_settings_get_printer ()
gtk_print_settings_get_print_pages, gtk_print_settings_get_print_pages ()
gtk_print_settings_get_quality, gtk_print_settings_get_quality ()
gtk_print_settings_get_resolution, gtk_print_settings_get_resolution ()
gtk_print_settings_get_reverse, gtk_print_settings_get_reverse ()
gtk_print_settings_get_scale, gtk_print_settings_get_scale ()
gtk_print_settings_get_use_color, gtk_print_settings_get_use_color ()
gtk_print_settings_has_key, gtk_print_settings_has_key ()
gtk_print_settings_new, gtk_print_settings_new ()
gtk_print_settings_set, gtk_print_settings_set ()
gtk_print_settings_set_bool, gtk_print_settings_set_bool ()
gtk_print_settings_set_collate, gtk_print_settings_set_collate ()
gtk_print_settings_set_default_source, gtk_print_settings_set_default_source ()
gtk_print_settings_set_dither, gtk_print_settings_set_dither ()
gtk_print_settings_set_double, gtk_print_settings_set_double ()
gtk_print_settings_set_duplex, gtk_print_settings_set_duplex ()
gtk_print_settings_set_finishings, gtk_print_settings_set_finishings ()
gtk_print_settings_set_int, gtk_print_settings_set_int ()
gtk_print_settings_set_length, gtk_print_settings_set_length ()
gtk_print_settings_set_media_type, gtk_print_settings_set_media_type ()
gtk_print_settings_set_number_up, gtk_print_settings_set_number_up ()
gtk_print_settings_set_n_copies, gtk_print_settings_set_n_copies ()
gtk_print_settings_set_orientation, gtk_print_settings_set_orientation ()
gtk_print_settings_set_output_bin, gtk_print_settings_set_output_bin ()
gtk_print_settings_set_page_ranges, gtk_print_settings_set_page_ranges ()
gtk_print_settings_set_page_set, gtk_print_settings_set_page_set ()
gtk_print_settings_set_paper_height, gtk_print_settings_set_paper_height ()
gtk_print_settings_set_paper_size, gtk_print_settings_set_paper_size ()
gtk_print_settings_set_paper_width, gtk_print_settings_set_paper_width ()
gtk_print_settings_set_printer, gtk_print_settings_set_printer ()
gtk_print_settings_set_print_pages, gtk_print_settings_set_print_pages ()
gtk_print_settings_set_quality, gtk_print_settings_set_quality ()
gtk_print_settings_set_resolution, gtk_print_settings_set_resolution ()
gtk_print_settings_set_reverse, gtk_print_settings_set_reverse ()
gtk_print_settings_set_scale, gtk_print_settings_set_scale ()
gtk_print_settings_set_use_color, gtk_print_settings_set_use_color ()
gtk_print_settings_unset, gtk_print_settings_unset ()
gtk_print_unix_dialog_add_custom_tab, gtk_print_unix_dialog_add_custom_tab ()
gtk_print_unix_dialog_get_current_page, gtk_print_unix_dialog_get_current_page ()
gtk_print_unix_dialog_get_page_setup, gtk_print_unix_dialog_get_page_setup ()
gtk_print_unix_dialog_get_selected_printer, gtk_print_unix_dialog_get_selected_printer ()
gtk_print_unix_dialog_get_settings, gtk_print_unix_dialog_get_settings ()
gtk_print_unix_dialog_new, gtk_print_unix_dialog_new ()
gtk_print_unix_dialog_set_current_page, gtk_print_unix_dialog_set_current_page ()
gtk_print_unix_dialog_set_manual_capabilities, gtk_print_unix_dialog_set_manual_capabilities ()
gtk_print_unix_dialog_set_page_setup, gtk_print_unix_dialog_set_page_setup ()
gtk_print_unix_dialog_set_settings, gtk_print_unix_dialog_set_settings ()
gtk_radio_action_set_current_value, gtk_radio_action_set_current_value ()
gtk_range_get_lower_stepper_sensitivity, gtk_range_get_lower_stepper_sensitivity ()
gtk_range_get_upper_stepper_sensitivity, gtk_range_get_upper_stepper_sensitivity ()
gtk_range_set_lower_stepper_sensitivity, gtk_range_set_lower_stepper_sensitivity ()
gtk_range_set_upper_stepper_sensitivity, gtk_range_set_upper_stepper_sensitivity ()
gtk_recent_chooser_add_filter, gtk_recent_chooser_add_filter ()
gtk_recent_chooser_dialog_new, gtk_recent_chooser_dialog_new ()
gtk_recent_chooser_dialog_new_for_manager, gtk_recent_chooser_dialog_new_for_manager ()
gtk_recent_chooser_get_current_item, gtk_recent_chooser_get_current_item ()
gtk_recent_chooser_get_current_uri, gtk_recent_chooser_get_current_uri ()
gtk_recent_chooser_get_filter, gtk_recent_chooser_get_filter ()
gtk_recent_chooser_get_items, gtk_recent_chooser_get_items ()
gtk_recent_chooser_get_limit, gtk_recent_chooser_get_limit ()
gtk_recent_chooser_get_local_only, gtk_recent_chooser_get_local_only ()
gtk_recent_chooser_get_select_multiple, gtk_recent_chooser_get_select_multiple ()
gtk_recent_chooser_get_show_icons, gtk_recent_chooser_get_show_icons ()
gtk_recent_chooser_get_show_not_found, gtk_recent_chooser_get_show_not_found ()
gtk_recent_chooser_get_show_numbers, gtk_recent_chooser_get_show_numbers ()
gtk_recent_chooser_get_show_private, gtk_recent_chooser_get_show_private ()
gtk_recent_chooser_get_show_tips, gtk_recent_chooser_get_show_tips ()
gtk_recent_chooser_get_sort_type, gtk_recent_chooser_get_sort_type ()
gtk_recent_chooser_get_uris, gtk_recent_chooser_get_uris ()
gtk_recent_chooser_list_filters, gtk_recent_chooser_list_filters ()
gtk_recent_chooser_menu_get_show_numbers, gtk_recent_chooser_menu_get_show_numbers ()
gtk_recent_chooser_menu_new, gtk_recent_chooser_menu_new ()
gtk_recent_chooser_menu_new_for_manager, gtk_recent_chooser_menu_new_for_manager ()
gtk_recent_chooser_menu_set_show_numbers, gtk_recent_chooser_menu_set_show_numbers ()
gtk_recent_chooser_remove_filter, gtk_recent_chooser_remove_filter ()
gtk_recent_chooser_select_all, gtk_recent_chooser_select_all ()
gtk_recent_chooser_select_uri, gtk_recent_chooser_select_uri ()
gtk_recent_chooser_set_current_uri, gtk_recent_chooser_set_current_uri ()
gtk_recent_chooser_set_filter, gtk_recent_chooser_set_filter ()
gtk_recent_chooser_set_limit, gtk_recent_chooser_set_limit ()
gtk_recent_chooser_set_local_only, gtk_recent_chooser_set_local_only ()
gtk_recent_chooser_set_select_multiple, gtk_recent_chooser_set_select_multiple ()
gtk_recent_chooser_set_show_icons, gtk_recent_chooser_set_show_icons ()
gtk_recent_chooser_set_show_not_found, gtk_recent_chooser_set_show_not_found ()
gtk_recent_chooser_set_show_numbers, gtk_recent_chooser_set_show_numbers ()
gtk_recent_chooser_set_show_private, gtk_recent_chooser_set_show_private ()
gtk_recent_chooser_set_show_tips, gtk_recent_chooser_set_show_tips ()
gtk_recent_chooser_set_sort_func, gtk_recent_chooser_set_sort_func ()
gtk_recent_chooser_set_sort_type, gtk_recent_chooser_set_sort_type ()
gtk_recent_chooser_unselect_all, gtk_recent_chooser_unselect_all ()
gtk_recent_chooser_unselect_uri, gtk_recent_chooser_unselect_uri ()
gtk_recent_chooser_widget_new, gtk_recent_chooser_widget_new ()
gtk_recent_chooser_widget_new_for_manager, gtk_recent_chooser_widget_new_for_manager ()
gtk_recent_filter_add_age, gtk_recent_filter_add_age ()
gtk_recent_filter_add_application, gtk_recent_filter_add_application ()
gtk_recent_filter_add_custom, gtk_recent_filter_add_custom ()
gtk_recent_filter_add_group, gtk_recent_filter_add_group ()
gtk_recent_filter_add_mime_type, gtk_recent_filter_add_mime_type ()
gtk_recent_filter_add_pattern, gtk_recent_filter_add_pattern ()
gtk_recent_filter_add_pixbuf_formats, gtk_recent_filter_add_pixbuf_formats ()
gtk_recent_filter_filter, gtk_recent_filter_filter ()
gtk_recent_filter_get_name, gtk_recent_filter_get_name ()
gtk_recent_filter_get_needed, gtk_recent_filter_get_needed ()
gtk_recent_filter_new, gtk_recent_filter_new ()
gtk_recent_filter_set_name, gtk_recent_filter_set_name ()
gtk_recent_info_exists, gtk_recent_info_exists ()
gtk_recent_info_get_added, gtk_recent_info_get_added ()
gtk_recent_info_get_age, gtk_recent_info_get_age ()
gtk_recent_info_get_applications, gtk_recent_info_get_applications ()
gtk_recent_info_get_application_info, gtk_recent_info_get_application_info ()
gtk_recent_info_get_description, gtk_recent_info_get_description ()
gtk_recent_info_get_display_name, gtk_recent_info_get_display_name ()
gtk_recent_info_get_groups, gtk_recent_info_get_groups ()
gtk_recent_info_get_icon, gtk_recent_info_get_icon ()
gtk_recent_info_get_mime_type, gtk_recent_info_get_mime_type ()
gtk_recent_info_get_modified, gtk_recent_info_get_modified ()
gtk_recent_info_get_private_hint, gtk_recent_info_get_private_hint ()
gtk_recent_info_get_short_name, gtk_recent_info_get_short_name ()
gtk_recent_info_get_uri, gtk_recent_info_get_uri ()
gtk_recent_info_get_uri_display, gtk_recent_info_get_uri_display ()
gtk_recent_info_get_visited, gtk_recent_info_get_visited ()
gtk_recent_info_has_application, gtk_recent_info_has_application ()
gtk_recent_info_has_group, gtk_recent_info_has_group ()
gtk_recent_info_is_local, gtk_recent_info_is_local ()
gtk_recent_info_last_application, gtk_recent_info_last_application ()
gtk_recent_info_match, gtk_recent_info_match ()
gtk_recent_info_ref, gtk_recent_info_ref ()
gtk_recent_info_unref, gtk_recent_info_unref ()
gtk_recent_manager_add_full, gtk_recent_manager_add_full ()
gtk_recent_manager_add_item, gtk_recent_manager_add_item ()
gtk_recent_manager_get_default, gtk_recent_manager_get_default ()
gtk_recent_manager_get_for_screen, gtk_recent_manager_get_for_screen ()
gtk_recent_manager_get_items, gtk_recent_manager_get_items ()
gtk_recent_manager_get_limit, gtk_recent_manager_get_limit ()
gtk_recent_manager_has_item, gtk_recent_manager_has_item ()
gtk_recent_manager_lookup_item, gtk_recent_manager_lookup_item ()
gtk_recent_manager_move_item, gtk_recent_manager_move_item ()
gtk_recent_manager_new, gtk_recent_manager_new ()
gtk_recent_manager_purge_items, gtk_recent_manager_purge_items ()
gtk_recent_manager_remove_item, gtk_recent_manager_remove_item ()
gtk_recent_manager_set_limit, gtk_recent_manager_set_limit ()
gtk_recent_manager_set_screen, gtk_recent_manager_set_screen ()
gtk_scrolled_window_unset_placement, gtk_scrolled_window_unset_placement ()
gtk_selection_data_targets_include_rich_text, gtk_selection_data_targets_include_rich_text ()
gtk_selection_data_targets_include_uri, gtk_selection_data_targets_include_uri ()
gtk_size_group_get_widgets, gtk_size_group_get_widgets ()
gtk_status_icon_get_blinking, gtk_status_icon_get_blinking ()
gtk_status_icon_get_geometry, gtk_status_icon_get_geometry ()
gtk_status_icon_get_icon_name, gtk_status_icon_get_icon_name ()
gtk_status_icon_get_pixbuf, gtk_status_icon_get_pixbuf ()
gtk_status_icon_get_size, gtk_status_icon_get_size ()
gtk_status_icon_get_stock, gtk_status_icon_get_stock ()
gtk_status_icon_get_storage_type, gtk_status_icon_get_storage_type ()
gtk_status_icon_get_visible, gtk_status_icon_get_visible ()
gtk_status_icon_is_embedded, gtk_status_icon_is_embedded ()
gtk_status_icon_new, gtk_status_icon_new ()
gtk_status_icon_new_from_file, gtk_status_icon_new_from_file ()
gtk_status_icon_new_from_icon_name, gtk_status_icon_new_from_icon_name ()
gtk_status_icon_new_from_pixbuf, gtk_status_icon_new_from_pixbuf ()
gtk_status_icon_new_from_stock, gtk_status_icon_new_from_stock ()
gtk_status_icon_position_menu, gtk_status_icon_position_menu ()
gtk_status_icon_set_blinking, gtk_status_icon_set_blinking ()
gtk_status_icon_set_from_file, gtk_status_icon_set_from_file ()
gtk_status_icon_set_from_icon_name, gtk_status_icon_set_from_icon_name ()
gtk_status_icon_set_from_pixbuf, gtk_status_icon_set_from_pixbuf ()
gtk_status_icon_set_from_stock, gtk_status_icon_set_from_stock ()
gtk_status_icon_set_tooltip, gtk_status_icon_set_tooltip ()
gtk_status_icon_set_visible, gtk_status_icon_set_visible ()
GTK_STOCK_ORIENTATION_LANDSCAPE, GTK_STOCK_ORIENTATION_LANDSCAPE
GTK_STOCK_ORIENTATION_PORTRAIT, GTK_STOCK_ORIENTATION_PORTRAIT
GTK_STOCK_ORIENTATION_REVERSE_LANDSCAPE, GTK_STOCK_ORIENTATION_REVERSE_LANDSCAPE
GTK_STOCK_ORIENTATION_REVERSE_PORTRAIT, GTK_STOCK_ORIENTATION_REVERSE_PORTRAIT
GTK_STOCK_SELECT_ALL, GTK_STOCK_SELECT_ALL
gtk_style_lookup_color, gtk_style_lookup_color ()
gtk_targets_include_image, gtk_targets_include_image ()
gtk_targets_include_rich_text, gtk_targets_include_rich_text ()
gtk_targets_include_text, gtk_targets_include_text ()
gtk_targets_include_uri, gtk_targets_include_uri ()
gtk_target_list_add_rich_text_targets, gtk_target_list_add_rich_text_targets ()
gtk_target_table_free, gtk_target_table_free ()
gtk_target_table_new_from_list, gtk_target_table_new_from_list ()
gtk_text_buffer_deserialize, gtk_text_buffer_deserialize ()
gtk_text_buffer_deserialize_get_can_create_tags, gtk_text_buffer_deserialize_get_can_create_tags ()
gtk_text_buffer_deserialize_set_can_create_tags, gtk_text_buffer_deserialize_set_can_create_tags ()
gtk_text_buffer_get_copy_target_list, gtk_text_buffer_get_copy_target_list ()
gtk_text_buffer_get_deserialize_formats, gtk_text_buffer_get_deserialize_formats ()
gtk_text_buffer_get_has_selection, gtk_text_buffer_get_has_selection ()
gtk_text_buffer_get_paste_target_list, gtk_text_buffer_get_paste_target_list ()
gtk_text_buffer_get_serialize_formats, gtk_text_buffer_get_serialize_formats ()
gtk_text_buffer_register_deserialize_format, gtk_text_buffer_register_deserialize_format ()
gtk_text_buffer_register_deserialize_tagset, gtk_text_buffer_register_deserialize_tagset ()
gtk_text_buffer_register_serialize_format, gtk_text_buffer_register_serialize_format ()
gtk_text_buffer_register_serialize_tagset, gtk_text_buffer_register_serialize_tagset ()
gtk_text_buffer_serialize, gtk_text_buffer_serialize ()
gtk_text_buffer_unregister_deserialize_format, gtk_text_buffer_unregister_deserialize_format ()
gtk_text_buffer_unregister_serialize_format, gtk_text_buffer_unregister_serialize_format ()
gtk_tree_store_insert_with_values, gtk_tree_store_insert_with_values ()
gtk_tree_store_insert_with_valuesv, gtk_tree_store_insert_with_valuesv ()
gtk_tree_view_get_enable_tree_lines, gtk_tree_view_get_enable_tree_lines ()
gtk_tree_view_get_grid_lines, gtk_tree_view_get_grid_lines ()
gtk_tree_view_get_headers_clickable, gtk_tree_view_get_headers_clickable ()
gtk_tree_view_get_rubber_banding, gtk_tree_view_get_rubber_banding ()
gtk_tree_view_get_search_entry, gtk_tree_view_get_search_entry ()
gtk_tree_view_get_search_position_func, gtk_tree_view_get_search_position_func ()
gtk_tree_view_set_enable_tree_lines, gtk_tree_view_set_enable_tree_lines ()
gtk_tree_view_set_grid_lines, gtk_tree_view_set_grid_lines ()
gtk_tree_view_set_rubber_banding, gtk_tree_view_set_rubber_banding ()
gtk_tree_view_set_search_entry, gtk_tree_view_set_search_entry ()
gtk_tree_view_set_search_position_func, gtk_tree_view_set_search_position_func ()
gtk_widget_get_action, gtk_widget_get_action ()
gtk_widget_input_shape_combine_mask, gtk_widget_input_shape_combine_mask ()
gtk_widget_is_composited, gtk_widget_is_composited ()
gtk_window_get_deletable, gtk_window_get_deletable ()
gtk_window_get_group, gtk_window_get_group ()
gtk_window_set_deletable, gtk_window_set_deletable ()


Layout Containers

GtkAlignment — A widget which controls the alignment and size of its child
GtkAspectFrame — A frame that constrains its child to a particular aspect ratio
GtkHBox — A horizontal container box
GtkVBox — A vertical container box
GtkHButtonBox — A container for arranging buttons horizontally
GtkVButtonBox — A container for arranging buttons vertically
GtkFixed — A container which allows you to position widgets at fixed coordinates
GtkHPaned — A container with two panes arranged horizontally
GtkVPaned — A container with two panes arranged vertically
GtkLayout — Infinite scrollable area containing child widgets and/or custom drawing
GtkNotebook — A tabbed notebook container
GtkTable — Pack widgets in regular patterns
GtkExpander — A container which can hide its child


Menus, Combo Box, Toolbar

GtkComboBox — A widget used to choose from a list of items
GtkComboBoxEntry — A text entry field with a dropdown list
GtkMenu — A menu widget
GtkMenuBar — A subclass widget for GtkMenuShell which holds GtkMenuItem widgets
GtkMenuItem — The widget used for item in menus
GtkMenuShell — A base class for menu objects
GtkImageMenuItem — A menu item with an icon
GtkRadioMenuItem — A choice from multiple check menu items
GtkCheckMenuItem — A menu item with a check box
GtkSeparatorMenuItem — A separator used in menus
GtkTearoffMenuItem — A menu item used to tear off and reattach its menu
GtkToolbar — Create bars of buttons and other widgets
GtkToolItem — The base class of widgets that can be added to GtkToolbar
GtkSeparatorToolItem — A toolbar item that separates groups of other toolbar items
GtkToolButton — A GtkToolItem subclass that displays buttons
GtkMenuToolButton — A GtkToolItem containing a button with an additional dropdown menu
GtkToggleToolButton — A GtkToolItem containing a toggle button
GtkRadioToolButton — A toolbar item that contains a radio button


Part IV. Migrating from Previous Versions of GTK+

This part describes what you need to change in programs use older versions of GTK+ so that they can use the new features. It also mentions how to convert applications using widgets found in the libgnomeui library to use their counterparts in GTK+.


Migrating from GnomeUIInfo

Prior to GTK+ 2.4, some applications used the GnomeUIInfo mechanism from <libgnomeui/gnome-app-helper.h> to define their menus and toolbars. With it, a program decleres an array of GnomeUIInfo structures, which contain information for menu or toolbar items such as their label, icon, and accelerator key. Then, one calls gnome_app_fill_menu() or gnome_app_fill_toolbar(), or one of the related functions, to create the appropriate widgets based on these structures.

A downside of this API is that the same structures are used to pass back pointers to the widgets that got created. This means that the structures cannot simply be kept around if the program requires multiple instances of the user interface (e.g. several windows); each new invocation of gnome_app_fill_menu() would overwrite the widget fields of the structures.

Another disadvantage is that there is no automatic way to synchronize the state of related controls. If there are toolbar toogle buttons for "Bold", "Italic", "Underline", and also corresponding menu items under "Format/Bold", etc., one has to synchronize their toggled states by hand whenever the user selects any one of them.

Finally, there is no way to do menu and toolbar merging for applications that require embedded components.

To convert an application that uses GnomeUIInfo into the new GtkAction mechanism, you need to do several things:

  1. Separate your existing GnomeUIInfo entries into normal actions, toggle actions, and radio actions, and then create a separate array of GtkActionEntry structures for each group. This will allow you to create the necessary GtkActionGroup objects. Note that this does not describe the actual "shape" that your menus and toolbars will have; it simply defines the set of commands that will appear in them.

  2. Create an XML description of your menus and toolbars for use with GtkUIManager. This defines the actual shape of the menus and toolbars.

  3. Port the code that uses gnome-app and gnome-app-helper to GtkAction and GtkUIManager.

  4. If your GnomeUIInfo entries use GNOME_APP_PIXMAP_DATA or GNOME_APP_PIXMAP_FILENAME for pixmaps, you have to create a GtkIconFactory, add it to the list of default factories, then create a GtkIconSet for each of your own icons. Add the sets to the factory, and use the id in the GtkActionEntry like a regular GTK+ stock id.

Example 40. GnomeUIInfo Example

The following code shows a declaration of a simple menu bar to be used with gnome_app_fill_menu() or similar. The menu hierarchy looks like this:

  • File

    Open
    —
    Exit

  • View

    Zoom In
    Zoom Out
    —
    [ ] Full Screen
    —
    ( ) High Quality
    ( ) Normal Quality
    ( ) Low Quality
static GnomeUIInfo file_menu_items[] = {
  { GNOME_APP_UI_ITEM, "_Open", "Open a file",
    open_callback, NULL, NULL, GNOME_APP_PIXMAP_STOCK, GTK_STOCK_OPEN,
    'o', GDK_CONTROL_MASK, NULL },
  { GNOME_APP_UI_SEPARATOR },
  { GNOME_APP_UI_ITEM, "E_xit", "Exit the program",
    exit_callback, NULL, NULL, GNOME_APP_PIXMAP_STOCK, GTK_STOCK_QUIT,
    'q', GDK_CONTROL_MASK, NULL},
  { GNOME_APP_UI_ENDOFINFO }
};

static GnomeUIInfo view_radio_items[] = {
  { GNOME_APP_UI_ITEM, "_High Quality", "Display images in high quality, slow mode",
    high_quality_callback, NULL, NULL, GNOME_APP_PIXMAP_FILENAME, "high-quality.png",
    0, 0, NULL },
  { GNOME_APP_UI_ITEM, "_Normal Quality", "Display images in normal quality",
    normal_quality_callback, NULL, NULL, GNOME_APP_PIXMAP_FILENAME, "normal-quality.png",
    0, 0, NULL },
  { GNOME_APP_UI_ITEM, "_Low Quality", "Display images in low quality, fast mode",
    low_quality_callback, NULL, NULL, GNOME_APP_PIXMAP_FILENAME, "low-quality.png",
    0, 0, NULL },
  { GNOME_APP_UI_ENDOFINFO }
};

static GnomeUIInfo view_menu_items[] = {
  { GNOME_APP_UI_ITEM, "Zoom _In", "Zoom into the image",
    zoom_in_callback, NULL, NULL, GNOME_APP_PIXMAP_STOCK, GTK_STOCK_ZOOM_IN,
    GDK_PLUS, 0, NULL },
  { GNOME_APP_UI_ITEM, "Zoom _Out", "Zoom away from the image",
    zoom_out_callback, NULL, NULL, GNOME_APP_PIXMAP_STOCK, GTK_STOCK_ZOOM_OUT,
    GDK_MINUS, 0, NULL },
  { GNOME_APP_UI_SEPARATOR },
  { GNOME_APP_UI_TOGGLEITEM, "_Full Screen", "Switch between full screen and windowed mode",
    full_screen_callback, NULL, NULL, GNOME_APP_PIXMAP_NONE, NULL,
    GDK_F11, 0, NULL },
  { GNOME_APP_UI_SEPARATOR },
  { GNOME_APP_UI_RADIOITEMS, NULL, NULL, view_radio_items },
  { GNOME_APP_UI_ENDOFINFO }
};

static GnomeUIInfo menubar[] = {
  { GNOME_APP_UI_SUBTREE, "_File", NULL, file_menu_items },
  { GNOME_APP_UI_SUBTREE, "_View", NULL, view_menu_items },
  { GNOME_APP_UI_ENDOFINFO }
}

Example 41. GtkActionEntry Structures

The following code is the set of actions that are present in the previous example. Note that the toggle and radio entries are separate from normal actions. Also, note that GtkActionEntry structures take key names in the format of gdk_accelerator_parse() rather than key values plus modifiers; you will have to convert these values by hand. For example, GDK_F11 with no modifiers is equivalent to a key name of "F11". Likewise, "o" with GDK_CONTROL_MASK is equivalent to "<ontrol>O".

/* Normal items */
static const GtkActionEntry entries[] = {
  { "FileMenu", NULL, "_File" },
  { "ViewMenu", NULL, "_View" },
  { "Open", GTK_STOCK_OPEN, "_Open", "<control>O", "Open a file", open_action_callback },
  { "Exit", GTK_STOCK_QUIT, "E_xit", "<control>Q", "Exit the program", exit_action_callback },
  { "ZoomIn", GTK_STOCK_ZOOM_IN, "Zoom _In", "plus", "Zoom into the image", zoom_in_action_callback },
  { "ZoomOut", GTK_STOCK_ZOOM_OUT, "Zoom _Out", "minus", "Zoom away from the image", zoom_out_action_callback },
};

/* Toggle items */
static const GtkToggleActionEntry toggle_entries[] = {
  { "FullScreen", NULL, "_Full Screen", "F11", "Switch between full screen and windowed mode", full_screen_action_callback, FALSE }
};

/* Radio items */
static const GtkRadioActionEntry radio_entries[] = {
  { "HighQuality", "my-stock-high-quality", "_High Quality", NULL, "Display images in high quality, slow mode", 0 },
  { "NormalQuality", "my-stock-normal-quality", "_Normal Quality", NULL, "Display images in normal quality", 1 },
  { "LowQuality", "my-stock-low-quality", "_Low Quality", NULL, "Display images in low quality, fast mode", 2 }
};

Example 42. XML Description

After extracting the actions, you will need to create an XML description of the actual layout of your menus and toolbars for use with GtkUIManager. The following code shows a simple menu bar that corresponds to the previous example. Note that the File and View menus have their names specified in the action entries, not in the XML itself. This is because the XML description only contains identifiers for the items in the GUI, rather than human-readable names.

static const char *ui_description =
"<ui>"
"  <menubar name='MainMenu'>"
"    <menu action='FileMenu'>"
"      <menuitem action='Open'/>"
"      <menuitem action='Exit'/>"
"    </menu>"
"    <menu action='ViewMenu'>"
"      <menuitem action='ZoomIn'/>"
"      <menuitem action='ZoomOut'/>"
"      <separator/>"
"      <menuitem action='FullScreen'/>"
"      <separator/>"
"      <menuitem action='HighQuality'/>"
"      <menuitem action='NormalQuality'/>"
"      <menuitem action='LowQuality'/>"
"    </menu>"
"  </menubar>"
"</ui>";

Example 43. Creating the Menu Bar

In this last example, we will create a GtkActionGroup based on the action entries we created above. We will then create a GtkUIManager with the XML description of the menu layout. We will also extract the accelerator group and the widgets from the GtkUIManager put them into a window.

GtkWidget *window;
GtkWidget *vbox;
GtkWidget *menubar;
GtkActionGroup *action_group;
GtkUIManager *ui_manager;
GtkAccelGroup *accel_group;
GError *error;

register_my_stock_icons ();

window = gtk_window_new (GTK_WINDOW_TOPLEVEL);

vbox = gtk_vbox_new (FALSE, 0);
gtk_container_add (GTK_CONTAINER (window), vbox);

action_group = gtk_action_group_new ("MenuActions");
gtk_action_group_add_actions (action_group, entries, G_N_ELEMENTS (entries), window);
gtk_action_group_add_toggle_actions (action_group, toggle_entries, G_N_ELEMENTS (toggle_entries), window);
gtk_action_group_add_radio_actions (action_group, radio_entries, G_N_ELEMENTS (radio_entries), 0, radio_action_callback, window);

ui_manager = gtk_ui_manager_new ();
gtk_ui_manager_insert_action_group (ui_manager, action_group, 0);

accel_group = gtk_ui_manager_get_accel_group (ui_manager);
gtk_window_add_accel_group (GTK_WINDOW (window), accel_group);

error = NULL;
if (!gtk_ui_manager_add_ui_from_string (ui_manager, ui_description, -1, &error))
  {
    g_message ("building menus failed: %s", error->message);
    g_error_free (error);
    exit (EXIT_FAILURE);
  }

menubar = gtk_ui_manager_get_widget (ui_manager, "/MainMenu");
gtk_box_pack_start (GTK_BOX (vbox), menubar, FALSE, FALSE, 0);

gtk_widget_show_all (window);

Example 44. Registering the icons

Here we show how the register_my_stock_icons() function used in the previous example could look like.

static struct {
  gchar *filename;
  gchar *stock_id;
} stock_icons[] = {
  { "high-quality.png", "my-stock-high-quality" },
  { "normal-quality.png", "my-stock-normal-quality" },
  { "low-quality.png", "my-stock-low-quality" },
};

static gint n_stock_icons = G_N_ELEMENTS (stock_icons);

static void
register_my_stock_icons (void)
{
   GtkIconFactory *icon_factory;
   GtkIconSet *icon_set;
   GtkIconSource *icon_source;
   gint i;

   icon_factory = gtk_icon_factory_new ();

   for (i = 0; i < n_stock_icons; i++)
    {
      icon_set = gtk_icon_set_new ();
      icon_source = gtk_icon_source_new ();
      gtk_icon_source_set_filename (icon_source, stock_icons[i].filename);
      gtk_icon_set_add_source (icon_set, icon_source);
      gtk_icon_source_free (icon_source);
      gtk_icon_factory_add (icon_factory, stock_icons[i].stock_id, icon_set);
      gtk_icon_set_unref (icon_set);
    }

   gtk_icon_factory_add_default (icon_factory);

   g_object_unref (icon_factory);
}


Migrating from GtkCombo to GtkComboBoxEntry

Here is an example of a simple, but typical use of a GtkCombo:

GtkWidget *combo;
GList *items = NULL;

items = g_list_append (items, "First Item");
items = g_list_append (items, "Second Item");
items = g_list_append (items, "Third Item");

combo = gtk_combo_new ();
gtk_combo_set_popdown_strings (GTK_COMBO (combo), items);

In order to react to the user's selection, connect to the "changed" signal on the combo and use gtk_entry_get_text (GTK_ENTRY (combo->entry)) to retrieve the selected text.

And here is how it would be done using GtkComboBoxEntry:

combo_box = gtk_combo_box_entry_new_text ();

gtk_combo_box_append_text (GTK_COMBO_BOX (combo_box), "First Item");
gtk_combo_box_append_text (GTK_COMBO_BOX (combo_box), "Second Item");
gtk_combo_box_append_text (GTK_COMBO_BOX (combo_box), "Third Item");

In order to react to the user's selection, connect to the "changed" signal on the combo and use gtk_entry_get_text (GTK_ENTRY (GTK_BIN (combo_box)->child)) to retrieve the selected text.


Miscellaneous

GtkAdjustment — A GtkObject representing an adjustable bounded value
GtkArrow — Displays an arrow
GtkCalendar — Displays a calendar and allows the user to select a date
GtkDrawingArea — A widget for custom user interface elements
GtkEventBox — A widget used to catch events for widgets which do not have their own window
GtkHandleBox — a widget for detachable window portions
GtkIMContextSimple — An input method context supporting table-based input methods
GtkIMMulticontext — An input method context supporting multiple, loadable input methods
GtkSizeGroup — Grouping widgets so they request the same size
GtkTooltips — Add tips to your widgets
GtkViewport — An adapter which makes widgets scrollable
GtkAccessible — Accessibility support for widgets


New features

The new widgets have more to offer than a mere combination of the features of GtkOptionMenu and GtkCombo. Notable new features include:

Grid mode | Sometimes it is preferable to display the available options not in a linear list, but in a grid. A typical example would be a "color combo" where the individual items are small square color swatches. The new widgets support gridded display with the functions gtk_combo_box_set_wrap_width(), gtk_combo_box_set_row_span_column() and gtk_combo_box_set_column_span_column().
Display of icons | An often-heard complaint about GtkOptionMenu is that the icons which appear in the image menu items in its menu are not displayed in the button showing the selected item. This limitation has been removed in GtkComboBox; the selected item appears in the same way as the options in the popup.
Full tree model power | Since the new widgets are built around the same models that are used for GtkTreeView, all of the powerful machinery of tree models and cell renderers can be used.


Numeric/Text Data Entry

GtkEntry — A single line text entry field
GtkEntryCompletion — Completion functionality for GtkEntry
GtkHScale — A horizontal slider widget for selecting a value from a range
GtkVScale — A vertical slider widget for selecting a value from a range
GtkSpinButton — Retrieve an integer or floating-point number from the user
GtkEditable — Interface for text-editing widgets


Ornaments

GtkFrame — A bin with a decorative frame and optional label
GtkHSeparator — A horizontal separator
GtkVSeparator — A vertical separator


Cross-process Embedding

GtkPlug — Toplevel for embedding into other processes
GtkSocket — Container for widgets from other processes


Printing

GtkPrintOperation — High-level Printing API
GtkPrintContext — Encapsulates context for drawing pages
GtkPrintSettings — Stores print settings
GtkPageSetup — Stores page setup information
GtkPaperSize — Support for named paper sizes
GtkPrinter — Represents a printer
GtkPrintJob — Represents a print job
GtkPrintUnixDialog — A print dialog
GtkPageSetupUnixDialog — A page setup dialog


Prev Home GTK+ Reference Manual Next

Part V. GTK+ Tools


Recently Used Documents

GtkRecentManager — Managing Recently Used Files
GtkRecentChooser — Interface implemented by GtkRecentChooserWidget, GtkRecentChooserMenu and GtkRecentChooserDialog
GtkRecentChooserDialog — Displays recently used files in a dialog
GtkRecentChooserMenu — Displays recently used files in a menu
GtkRecentChooserWidget — Displays recently used files
GtkRecentFilter — A filter for selecting a subset of recently used files


Scrolling

GtkHScrollbar — A horizontal scrollbar
GtkVScrollbar — A vertical scrollbar
GtkScrolledWindow — Adds scrollbars to its child widget


Selectors (File/Font/Color/Input Devices)

GtkColorButton — A button to launch a color selection dialog
GtkColorSelection — A widget used to select a color
GtkColorSelectionDialog — A standard dialog box for selecting a color
GtkFileSelection — Prompt the user for a file or directory name
GtkFileChooser — File chooser interface used by GtkFileChooserWidget and GtkFileChooserDialog
GtkFileChooserButton — A button to launch a file selection dialog
GtkFileChooserDialog — A file chooser dialog, suitable for "File/Open" or "File/Save" commands
GtkFileChooserWidget — File chooser widget that can be embedded in other widgets
GtkFileFilter — A filter for selecting a file subset
GtkFontButton — A button to launch a font selection dialog
GtkFontSelection — A widget for selecting fonts
GtkFontSelectionDialog — A dialog box for selecting fonts
GtkInputDialog — Configure devices for the XInput extension


Setting the page flow

Here is the area where GtkAssistant and GnomeDruid differ the most. While GnomeDruid used the "next" and "back" signals from the GnomeDruidPage, GtkAssistant uses the following techniques:

  • gtk_assistant_set_forward_page_func(): Allows to define a GtkAssistantPageFunc to let the assistant know which will be the following page given the current page.

  • gtk_assistant_set_page_complete(): Lets the assistant know whether the specified page is complete or not, updating buttons state accordingly.

  • gtk_assistant_set_page_type(): Lets the assistant know the page role and update the buttons state accordingly. Pages can have the following roles:

    Intro
    Content
    Progress
    Confirmation
    Summary

A sample GtkAssistantPageFunc could look like this:

static gint
forward_page_function (gint     current_page,
                       gpointer data)
{
  switch (current_page)
    {
    case 0:
      return 1;
    case 1:
      if (check_page1_data ())
       return 2;
     else
       return 3;
    case 2:
      return 3;
    default:
      return -1;
    }
}


Special-purpose features

GtkCurve — Allows direct editing of a curve
GtkGammaCurve — a subclass of GtkCurve for editing gamma curves.
GtkRuler — Base class for horizontal or vertical rulers
GtkHRuler — A horizontal ruler.
GtkVRuler — A vertical ruler.


Text Widget Overview

Text Widget Overview — Overview of GtkTextBuffer, GtkTextView, and friends

Conceptual Overview

GTK+ has an extremely powerful framework for multiline text editing. The primary objects involved in the process are GtkTextBuffer, which represents the text being edited, and GtkTextView, a widget which can display a GtkTextBuffer. Each buffer can be displayed by any number of views.

One of the important things to remember about text in GTK+ is that it's in the UTF-8 encoding. This means that one character can be encoded as multiple bytes. Character counts are usually referred to as offsets, while byte counts are called indexes. If you confuse these two, things will work fine with ASCII, but as soon as your buffer contains multibyte characters, bad things will happen.

Text in a buffer can be marked with tags. A tag is an attribute that can be applied to some range of text. For example, a tag might be called "bold" and make the text inside the tag bold. However, the tag concept is more general than that; tags don't have to affect appearance. They can instead affect the behavior of mouse and key presses, "lock" a range of text so the user can't edit it, or countless other things. A tag is represented by a GtkTextTag object. One GtkTextTag can be applied to any number of text ranges in any number of buffers.

Each tag is stored in a GtkTextTagTable. A tag table defines a set of tags that can be used together. Each buffer has one tag table associated with it; only tags from that tag table can be used with the buffer. A single tag table can be shared between multiple buffers, however.

Tags can have names, which is convenient sometimes (for example, you can name your tag that makes things bold "bold"), but they can also be anonymous (which is convenient if you're creating tags on-the-fly).

Most text manipulation is accomplished with iterators, represented by a GtkTextIter. An iterator represents a position between two characters in the text buffer. GtkTextIter is a struct designed to be allocated on the stack; it's guaranteed to be copiable by value and never contain any heap-allocated data. Iterators are not valid indefinitely; whenever the buffer is modified in a way that affects the number of characters in the buffer, all outstanding iterators become invalid. (Note that deleting 5 characters and then reinserting 5 still invalidates iterators, though you end up with the same number of characters you pass through a state with a different number).

Because of this, iterators can't be used to preserve positions across buffer modifications. To preserve a position, the GtkTextMark object is ideal. You can think of a mark as an invisible cursor or insertion point; it floats in the buffer, saving a position. If the text surrounding the mark is deleted, the mark remains in the position the text once occupied; if text is inserted at the mark, the mark ends up either to the left or to the right of the new text, depending on its gravity. The standard text cursor in left-to-right languages is a mark with right gravity, because it stays to the right of inserted text.

Like tags, marks can be either named or anonymous. There are two marks built-in to GtkTextBuffer; these are named "insert" and "selection_bound" and refer to the insertion point and the boundary of the selection which is not the insertion point, respectively. If no text is selected, these two marks will be in the same position. You can manipulate what is selected and where the cursor appears by moving these marks around. [2]

Text buffers always contain at least one line, but may be empty (that is, buffers can contain zero characters). The last line in the text buffer never ends in a line separator (such as newline); the other lines in the buffer always end in a line separator. Line separators count as characters when computing character counts and character offsets. Note that some Unicode line separators are represented with multiple bytes in UTF-8, and the two-character sequence "\r\n" is also considered a line separator.

Simple Example

The simplest usage of GtkTextView might look like this:

  GtkWidget *view;
  GtkTextBuffer *buffer;

  view = gtk_text_view_new ();

  buffer = gtk_text_view_get_buffer (GTK_TEXT_VIEW (view));

  gtk_text_buffer_set_text (buffer, "Hello, this is some text", -1);

  /* Now you might put the view in a container and display it on the
   * screen; when the user edits the text, signals on the buffer
   * will be emitted, such as "changed", "insert_text", and so on.
   */

In many cases it's also convenient to first create the buffer with gtk_text_buffer_new(), then create a widget for that buffer with gtk_text_view_new_with_buffer(). Or you can change the buffer the widget displays after the widget is created with gtk_text_view_set_buffer().

Example of Changing Text Attributes

There are two ways to affect text attributes in GtkTextView. You can change the default attributes for a given GtkTextView, and you can apply tags that change the attributes for a region of text. For text features that come from the theme — such as font and foreground color — use standard GtkWidget functions such as gtk_widget_modify_font() or gtk_widget_modify_text(). For other attributes there are dedicated methods on GtkTextView such as gtk_text_view_set_tabs().

  GtkWidget *view;
  GtkTextBuffer *buffer;
  GtkTextIter start, end;
  PangoFontDescription *font_desc;
  GdkColor color;
  GtkTextTag *tag;

  view = gtk_text_view_new ();

  buffer = gtk_text_view_get_buffer (GTK_TEXT_VIEW (view));

  gtk_text_buffer_set_text (buffer, "Hello, this is some text", -1);

  /* Change default font throughout the widget */
  font_desc = pango_font_description_from_string ("Serif 15");
  gtk_widget_modify_font (view, font_desc);
  pango_font_description_free (font_desc);

  /* Change default color throughout the widget */
  gdk_color_parse ("green", &color);
  gtk_widget_modify_text (view, GTK_STATE_NORMAL, &color);

  /* Change left margin throughout the widget */
  gtk_text_view_set_left_margin (GTK_TEXT_VIEW (view), 30);

  /* Use a tag to change the color for just one part of the widget */
  tag = gtk_text_buffer_create_tag (buffer, "blue_foreground",
                           "foreground", "blue", NULL);
  gtk_text_buffer_get_iter_at_offset (buffer, &start, 7);
  gtk_text_buffer_get_iter_at_offset (buffer, &end, 12);
  gtk_text_buffer_apply_tag (buffer, tag, &start, &end);

The gtk-demo application that comes with GTK+ contains more example code for GtkTextView.

[2] If you want to place the cursor in response to a user action, be sure to use gtk_text_buffer_place_cursor(), which moves both at once without causing a temporary selection (moving one then the other temporarily selects the range in between the old and new positions).


Multiline Text Editor

Text Widget Overview — Overview of GtkTextBuffer, GtkTextView, and friends
GtkTextIter — Text buffer iterator
GtkTextMark — A position in the buffer preserved across buffer modifications
GtkTextBuffer — Stores attributed text for display in a GtkTextView
GtkTextTag — A tag that can be applied to text in a GtkTextBuffer
GtkTextTagTable — Collection of tags that can be used together
GtkTextView — Widget that displays a GtkTextBuffer


Tree and List Widget Overview

Tree and List Widget Overview — Overview of GtkTreeModel, GtkTreeView, and other associated widgets

Overview

To create a tree or list in GTK+, use the GtkTreeModel interface in conjunction with the GtkTreeView widget. This widget is designed around a Model/View/Controller design and consists of four major parts:

The tree view widget (GtkTreeView)
The view column (GtkTreeViewColumn)
The cell renderers (GtkCellRenderer etc.)
The model interface (GtkTreeModel)

The View is composed of the first three objects, while the last is the Model. One of the prime benefits of the MVC design is that multiple views can be created of a single model. For example, a model mapping the file system could be created for a file manager. Many views could be created to display various parts of the file system, but only one copy need be kept in memory.

The purpose of the cell renderers is to provide extensibility to the widget and to allow multiple ways of rendering the same type of data. For example, consider how to render a boolean variable. Should it render it as a string of "True" or "False", "On" or "Off", or should it be rendered as a checkbox?

Creating a model

GTK+ provides two simple models that can be used: the GtkListStore and the GtkTreeStore. GtkListStore is used to model list widgets, while the GtkTreeStore models trees. It is possible to develop a new type of model, but the existing models should be satisfactory for all but the most specialized of situations. Creating the model is quite simple:

GtkListStore *store = gtk_list_store_new (2, G_TYPE_STRING, G_TYPE_BOOLEAN);

This creates a list store with two columns: a string column and a boolean column. Typically the 2 is never passed directly like that; usually an enum is created wherein the different columns are enumerated, followed by a token that represents the total number of columns. The next example will illustrate this, only using a tree store instead of a list store. Creating a tree store operates almost exactly the same.

enum
{
   TITLE_COLUMN,
   AUTHOR_COLUMN,
   CHECKED_COLUMN,
   N_COLUMNS
};

GtkTreeStore *store = gtk_tree_store_new (N_COLUMNS,       /* Total number of columns */
                                          G_TYPE_STRING,   /* Book title              */
                                          G_TYPE_STRING,   /* Author                  */
                                          G_TYPE_BOOLEAN); /* Is checked out?         */

Adding data to the model is done using gtk_tree_store_set() or gtk_list_store_set(), depending upon which sort of model was created. To do this, a GtkTreeIter must be acquired. The iterator points to the location where data will be added.

Once an iterator has been acquired, gtk_tree_store_set() is used to apply data to the part of the model that the iterator points to. Consider the following example:

GtkTreeIter   iter;

gtk_tree_store_append (store, &iter, NULL);  /* Acquire an iterator */

gtk_tree_store_set (store, &iter,
                    TITLE_COLUMN, "The Principle of Reason",
                    AUTHOR_COLUMN, "Martin Heidegger",
                    CHECKED_COLUMN, FALSE,
                    -1);

Notice that the last argument is -1. This is always done because this is a variable-argument function and it needs to know when to stop processing arguments. It can be used to set the data in any or all columns in a given row.

The third argument to gtk_tree_store_append() is the parent iterator. It is used to add a row to a GtkTreeStore as a child of an existing row. This means that the new row will only be visible when its parent is visible and in its expanded state. Consider the following example:

GtkTreeIter iter1;  /* Parent iter */
GtkTreeIter iter2;  /* Child iter  */

gtk_tree_store_append (store, &iter1, NULL);  /* Acquire a top-level iterator */
gtk_tree_store_set (store, &iter1,
                    TITLE_COLUMN, "The Art of Computer Programming",
                    AUTHOR_COLUMN, "Donald E. Knuth",
                    CHECKED_COLUMN, FALSE,
                    -1);

gtk_tree_store_append (store, &iter2, &iter1);  /* Acquire a child iterator */
gtk_tree_store_set (store, &iter2,
                    TITLE_COLUMN, "Volume 1: Fundamental Algorithms",
                    -1);

gtk_tree_store_append (store, &iter2, &iter1);
gtk_tree_store_set (store, &iter2,
                    TITLE_COLUMN, "Volume 2: Seminumerical Algorithms",
                    -1);

gtk_tree_store_append (store, &iter2, &iter1);
gtk_tree_store_set (store, &iter2,
                    TITLE_COLUMN, "Volume 3: Sorting and Searching",
                    -1);

Creating the view component

While there are several different models to choose from, there is only one view widget to deal with. It works with either the list or the tree store. Setting up a GtkTreeView is not a difficult matter. It needs a GtkTreeModel to know where to retrieve its data from.

GtkWidget *tree;

tree = gtk_tree_view_new_with_model (GTK_TREE_MODEL (store));

Columns and cell renderers

Once the GtkTreeView widget has a model, it will need to know how to display the model. It does this with columns and cell renderers.

Cell renderers are used to draw the data in the tree model in a way. There are a number of cell renderers that come with GTK+ 2.x, including the GtkCellRendererText, GtkCellRendererPixbuf and the GtkCellRendererToggle. It is relatively easy to write a custom renderer.

A GtkTreeViewColumn is the object that GtkTreeView uses to organize the vertical columns in the tree view. It needs to know the name of the column to label for the user, what type of cell renderer to use, and which piece of data to retrieve from the model for a given row.

GtkCellRenderer *renderer;
GtkTreeViewColumn *column;

renderer = gtk_cell_renderer_text_new ();
column = gtk_tree_view_column_new_with_attributes ("Author",
                                                   renderer,
                                                   "text", AUTHOR_COLUMN,
                                                   NULL);
gtk_tree_view_append_column (GTK_TREE_VIEW (tree), column);

At this point, all the steps in creating a displayable tree have been covered. The model is created, data is stored in it, a tree view is created and columns are added to it.

Selection handling

Most applications will need to not only deal with displaying data, but also receiving input events from users. To do this, simply get a reference to a selection object and connect to the "changed" signal.

/* Prototype for selection handler callback */
static void tree_selection_changed_cb (GtkTreeSelection *selection, gpointer data);

/* Setup the selection handler */
GtkTreeSelection *select;

select = gtk_tree_view_get_selection (GTK_TREE_VIEW (tree));
gtk_tree_selection_set_mode (select, GTK_SELECTION_SINGLE);
g_signal_connect (G_OBJECT (select), "changed",
                  G_CALLBACK (tree_selection_changed_cb),
                  NULL);

Then to retrieve data for the row selected:

static void
tree_selection_changed_cb (GtkTreeSelection *selection, gpointer data)
{
        GtkTreeIter iter;
        GtkTreeModel *model;
        gchar *author;

        if (gtk_tree_selection_get_selected (selection, &model, &iter))
        {
                gtk_tree_model_get (model, &iter, AUTHOR_COLUMN, &author, -1);

                g_print ("You selected a book by %s\n", author);

                g_free (author);
        }
}

Simple Example

Here is a simple example of using a GtkTreeView widget in context of the other widgets. It simply creates a simple model and view, and puts them together. Note that the model is never populated with data — that is left as an exercise for the reader. More information can be found on this in the GtkTreeModel section.

enum
{
   TITLE_COLUMN,
   AUTHOR_COLUMN,
   CHECKED_COLUMN,
   N_COLUMNS
};

void
setup_tree (void)
{
   GtkTreeStore *store;
   GtkWidget *tree;
   GtkTreeViewColumn *column;
   GtkCellRenderer *renderer;

   /* Create a model.  We are using the store model for now, though we
    * could use any other GtkTreeModel */
   store = gtk_tree_store_new (N_COLUMNS,
                               G_TYPE_STRING,
                               G_TYPE_STRING,
                               G_TYPE_BOOLEAN);

   /* custom function to fill the model with data */
   populate_tree_model (store);

   /* Create a view */
   tree = gtk_tree_view_new_with_model (GTK_TREE_MODEL (store));

   /* The view now holds a reference.  We can get rid of our own
    * reference */
   g_object_unref (G_OBJECT (store));

   /* Create a cell render and arbitrarily make it red for demonstration
    * purposes */
   renderer = gtk_cell_renderer_text_new ();
   g_object_set (G_OBJECT (renderer),
                 "foreground", "red",
                 NULL);

   /* Create a column, associating the "text" attribute of the
    * cell_renderer to the first column of the model */
   column = gtk_tree_view_column_new_with_attributes ("Author", renderer,
                                                      "text", AUTHOR_COLUMN,
                                                      NULL);

   /* Add the column to the view. */
   gtk_tree_view_append_column (GTK_TREE_VIEW (tree), column);

   /* Second column.. title of the book. */
   renderer = gtk_cell_renderer_text_new ();
   column = gtk_tree_view_column_new_with_attributes ("Title",
                                                      renderer,
                                                      "text", TITLE_COLUMN,
                                                      NULL);
   gtk_tree_view_append_column (GTK_TREE_VIEW (tree), column);

   /* Last column.. whether a book is checked out. */
   renderer = gtk_cell_renderer_toggle_new ();
   column = gtk_tree_view_column_new_with_attributes ("Checked out",
                                                      renderer,
                                                      "active", CHECKED_COLUMN,
                                                      NULL);
   gtk_tree_view_append_column (GTK_TREE_VIEW (tree), column);

   /* Now we can manipulate the view just like any other GTK widget */
   ...
}


Tree, List and Icon Grid Widgets

Tree and List Widget Overview — Overview of GtkTreeModel, GtkTreeView, and other associated widgets
GtkTreeModel — The tree interface used by GtkTreeView
GtkTreeSelection — The selection object for GtkTreeView
GtkTreeViewColumn — A visible column in a GtkTreeView widget
GtkTreeView — A widget for displaying both trees and lists
GtkTreeView drag-and-drop — Interfaces for drag-and-drop support in GtkTreeView
GtkCellView — A widget displaying a single row of a GtkTreeModel
GtkIconView — A widget which displays a list of icons in a grid
GtkTreeSortable — The interface for sortable models used by GtkTreeView
GtkTreeModelSort — A GtkTreeModel which makes an underlying tree model sortable
GtkTreeModelFilter — A GtkTreeModel which hides parts of an underlying tree model
GtkCellLayout — An interface for packing cells
GtkCellRenderer — An object for rendering a single cell on a GdkDrawable
GtkCellEditable — Interface for widgets which can are used for editing cells
GtkCellRendererAccel — Renders a keyboard accelerator in a cell
GtkCellRendererCombo — Renders a combobox in a cell
GtkCellRendererPixbuf — Renders a pixbuf in a cell
GtkCellRendererProgress — Renders numbers as progress bars
GtkCellRendererSpin — Renders a spin button in a cell
GtkCellRendererText — Renders text in a cell
GtkCellRendererToggle — Renders a toggle button in a cell
GtkListStore — A list-like data structure that can be used with the GtkTreeView
GtkTreeStore — A tree-like data structure that can be used with the GtkTreeView


User Interface Manager Object

GtkUIManager is an object that can construct menu and toolbar widgets from an XML description. These widgets are in turn associated to corresponding actions and action groups.

GtkUIManager supports merging of menus and toolbars for applications that have multiple components, each with separate sets of commands. For example, a word processor that can embed images may want to have toolbar buttons for Bold and Italic when the cursor is on a text block, but Crop and Brightness/Contrast buttons when the cursor is on an image. These actions, which change depending on the state of the application, can be merged and de-merged from a GtkUIManager as appropriate.


Windows

GtkDialog — Create popup windows
GtkInvisible — A widget which is not displayed
GtkMessageDialog — A convenient message window
GtkWindow — Toplevel which can contain other widgets
GtkWindowGroup — Limit the effect of grabs
GtkAboutDialog — Display information about an application
GtkAssistant — A widget used to guide users through multi-step operations


Part II. GdkGLExt API Reference

Prev Home GtkGLExt Reference Manual Next

GdkGLExt API Reference

Table of Contents

Initialization - Library initialization functions
Query - Functions to query OpenGL support information
Frame Buffer Configuration - OpenGL frame buffer configuration object
Rendering Context - OpenGL rendering context object
Rendering Surface - OpenGL rendering surface interface
OpenGL Pixmap - OpenGL pixmap which is maintained off-screen
OpenGL Window - OpenGL window which is located on-screen
Font Rendering - Functions for font rendering in OpenGL
Geometric Object Rendering - Functions for generating easily recognizable 3D geometric objects
Tokens - OpenGL-related tokens
X Window System Interaction - Internal X-related functions
Version Information - Variables and macros to check the GdkGLExt version


Part III. GtkGLExt API Reference

Prev Home GtkGLExt Reference Manual Next

GtkGLExt API Reference

Table of Contents

Initialization - Library initialization functions
OpenGL-Capable Widget - OpenGL extension to GtkWidget API
Version Information - Variables and macros to check the GtkGLExt version


Compiling the GtkGLExt libraries

Compiling the GtkGLExt Libraries — How to compile GtkGLExt

Building GtkGLExt on UNIX-like systems

This chapter covers building and installing GtkGLExt on UNIX and UNIX-like systems such as Linux. Compiling GtkGLExt on Microsoft Windows is different in detail and somewhat more difficult to get going since the necessary tools aren't included with the operating system.

On UNIX-like systems GtkGLExt uses the standard GNU build system, using autoconf for package configuration and resolving portability issues, automake for building makefiles that comply with the GNU Coding Standards, and libtool for building shared libraries on multiple platforms.

If you are building GtkGLExt from the distributed source packages, then won't need these tools installed; the necessary pieces of the tools are already included in the source packages. But it's useful to know a bit about how packages that use these tools work. A source package is distributed as tar.gz or tar.bz2 file which you unpack into a directory full of the source files as follows:

      tar zxvf gtkglext-x.y.z.tar.gz

      tar jxvf gtkglext-x.y.z.tar.bz2

In the toplevel of the directory that is created, there will be a shell script called configure which you then run to take the template makefiles called Makefile.in in the package and create makefiles customized for your operating system. The configure script can be passed various command line arguments to determine how the package is built and installed. The most commonly useful argument is the --prefix argument which determines where the package is installed. To install a package in /opt/gtk you would run configure as:

      ./configure --prefix=/opt/gtk

A full list of options can be found by running configure with the --help argument. In general, the defaults are right and should be trusted. After you've run configure, you then run the make command to build the package and install it.

      make
      make install

If you don't have permission to write to the directory you are installing in, you may have to change to root temporarily before running make install. Also, if you are installing in a system directory, on some systems (such as Linux), you will need to run ldconfig after make install so that the newly installed libraries will be found.

If you want to compile example programs shipped with the source package, run the following command.

      make examples

Several environment variables are useful to pass to set before running configure. CPPFLAGS contains options to pass to the C compiler, and is used to tell the compiler where to look for include files. The LDFLAGS variable is used in a similar fashion for the linker. Finally the PKG_CONFIG_PATH environment variable contains a search path that pkg-config (see below) uses when looking for for file describing how to compile programs using different libraries. If you were installing GTK+ and it's dependencies into /opt/gtk, you might want to set these variables as:

      CPPFLAGS="-I/opt/gtk/include"
      LDFLAGS="-L/opt/gtk/lib"
      PKG_CONFIG_PATH="/opt/gtk/lib/pkgconfig"
      export CPPFLAGS LDFLAGS PKG_CONFIG_PATH

You may also need to set the LD_LIBRARY_PATH environment variable so the systems dynamic linker can find the newly installed libraries, and the PATH environment program so that utility binaries installed by the various libraries will be found.

      LD_LIBRARY_PATH="/opt/gtk/lib"
      PATH="/opt/gtk/bin:$PATH"
      export LD_LIBRARY_PATH PATH

Dependencies

Before you can compile the GtkGLExt library, you need to have various other tools and libraries installed on your system. The two tools needed during the build process (as differentiated from the tools used in when creating GTK+ mentioned above such as autoconf) are pkg-config and GNU make.

  • pkg-config is a tool for tracking the compilation flags needed for libraries that is used by the GTK+ libraries. (For each library, a small .pc text file is installed in a standard location that contains the compilation flags needed for that library along with version number information.)

  • The GtkGLExt makefiles will mostly work with different versions of make, however, there tends to be a few incompatibilities, so we recommend installing GNU make if you don't already have it on your system and using it. (It may be called gmake rather than make.)

  • GTK+ -- The GIMP Toolkit -- version 2.0 or above.

  • OpenGL or Mesa.

Extra Configuration Options

In addition to the normal options, the configure script for the GtkGLExt supports the following additional arguments.

configure [[--with-gl-prefix=DIR]] [[--with-gl-includedir=DIR]] [[--with-gl-libdir=DIR]] [[--enable-debug=[no|minimum|yes]]] [[--disable-gtk-doc] | [--enable-gtk-doc]] [[--with-html-dir=PATH]] [[--with-gdktarget=[x11|win32]]]

--with-gl-prefix=DIR. Directory where OpenGL (Mesa) is installed. The default is 'auto'.

--with-gl-includedir=DIR. Directory where OpenGL (Mesa) header files are installed. The default is 'auto'.

--with-gl-libdir=DIR. Directory where OpenGL (Mesa) libraries are installed. The default is 'auto'.

--enable-debug. Turns on various amounts of debugging support. Setting this to 'no' disables g_assert(), g_return_if_fail(), g_return_val_if_fail() and all cast checks between different object types. Setting it to 'minimum' disables only cast checks. Setting it to 'yes' enables runtime debugging. The default is 'minimum'. Note that 'no' is fast, but dangerous as it tends to destabilize even mostly bug-free software by changing the effect of many bugs from simple warnings into fatal crashes. Thus --enable-debug=no should not be used for stable releases of GtkGLExt.

--disable-gtk-doc and --enable-gtk-doc. The gtk-doc package is used to generate the reference documentation included with GtkGLExt. By default support for gtk-doc is disabled because it requires various extra dependencies to be installed. If you have gtk-doc installed and are modifying GtkGLExt, you may want to enable gtk-doc support by passing in --enable-gtk-doc. If not enabled, pre-generated HTML files distributed with GtkGLExt will be installed.

--with-html-dir. Path to installed the reference documentation. The default is ${datadir}/gtk-doc/html.

--with-gdktarget. Toggles between the supported backends for GdkGLExt. The default is x11, unless the platform is Windows, in which case the default is win32.


Frame Buffer Configuration

Frame Buffer Configuration — OpenGL frame buffer configuration object

Synopsis

#include <gdk/gdkgl.h>

enum        GdkGLConfigMode;
struct      GdkGLConfig;
GdkGLConfig* gdk_gl_config_new              (const int *attrib_list);
GdkGLConfig* gdk_gl_config_new_for_screen   (GdkScreen *screen,
                                             const int *attrib_list);
GdkGLConfig* gdk_gl_config_new_by_mode      (GdkGLConfigMode mode);
GdkGLConfig* gdk_gl_config_new_by_mode_for_screen
                                            (GdkScreen *screen,
                                             GdkGLConfigMode mode);
GdkScreen*  gdk_gl_config_get_screen        (GdkGLConfig *glconfig);
gboolean    gdk_gl_config_get_attrib        (GdkGLConfig *glconfig,
                                             int attribute,
                                             int *value);
GdkColormap* gdk_gl_config_get_colormap     (GdkGLConfig *glconfig);
GdkVisual*  gdk_gl_config_get_visual        (GdkGLConfig *glconfig);
gint        gdk_gl_config_get_depth         (GdkGLConfig *glconfig);
gint        gdk_gl_config_get_layer_plane   (GdkGLConfig *glconfig);
gint        gdk_gl_config_get_n_aux_buffers (GdkGLConfig *glconfig);
gint        gdk_gl_config_get_n_sample_buffers
                                            (GdkGLConfig *glconfig);
gboolean    gdk_gl_config_is_rgba           (GdkGLConfig *glconfig);
gboolean    gdk_gl_config_is_double_buffered
                                            (GdkGLConfig *glconfig);
gboolean    gdk_gl_config_is_stereo         (GdkGLConfig *glconfig);
gboolean    gdk_gl_config_has_alpha         (GdkGLConfig *glconfig);
gboolean    gdk_gl_config_has_depth_buffer  (GdkGLConfig *glconfig);
gboolean    gdk_gl_config_has_stencil_buffer
                                            (GdkGLConfig *glconfig);
gboolean    gdk_gl_config_has_accum_buffer  (GdkGLConfig *glconfig);

Object Hierarchy

  GObject
   +----GdkGLConfig

Description

Details

enum GdkGLConfigMode

typedef enum
{
  GDK_GL_MODE_RGB         = 0,
  GDK_GL_MODE_RGBA        = 0,       /* same as RGB */
  GDK_GL_MODE_INDEX       = 1 << 0,
  GDK_GL_MODE_SINGLE      = 0,
  GDK_GL_MODE_DOUBLE      = 1 << 1,
  GDK_GL_MODE_STEREO      = 1 << 2,
  GDK_GL_MODE_ALPHA       = 1 << 3,
  GDK_GL_MODE_DEPTH       = 1 << 4,
  GDK_GL_MODE_STENCIL     = 1 << 5,
  GDK_GL_MODE_ACCUM       = 1 << 6,
  GDK_GL_MODE_MULTISAMPLE = 1 << 7   /* not supported yet */
} GdkGLConfigMode;

struct GdkGLConfig

struct GdkGLConfig;

gdk_gl_config_new ()

GdkGLConfig* gdk_gl_config_new              (const int *attrib_list);

Returns an OpenGL frame buffer configuration that match the specified attributes.

attrib_list is a int array that contains the attribute/value pairs. Available attributes are: GDK_GL_USE_GL, GDK_GL_BUFFER_SIZE, GDK_GL_LEVEL, GDK_GL_RGBA, GDK_GL_DOUBLEBUFFER, GDK_GL_STEREO, GDK_GL_AUX_BUFFERS, GDK_GL_RED_SIZE, GDK_GL_GREEN_SIZE, GDK_GL_BLUE_SIZE, GDK_GL_ALPHA_SIZE, GDK_GL_DEPTH_SIZE, GDK_GL_STENCIL_SIZE, GDK_GL_ACCUM_RED_SIZE, GDK_GL_ACCUM_GREEN_SIZE, GDK_GL_ACCUM_BLUE_SIZE, GDK_GL_ACCUM_ALPHA_SIZE.

attrib_list : | a list of attribute/value pairs. The last attribute must be GDK_GL_ATTRIB_LIST_NONE.
Returns : | the new GdkGLConfig.

gdk_gl_config_new_for_screen ()

GdkGLConfig* gdk_gl_config_new_for_screen   (GdkScreen *screen,
                                             const int *attrib_list);

Returns an OpenGL frame buffer configuration that match the specified attributes.

screen : | target screen.
attrib_list : | a list of attribute/value pairs. The last attribute must be GDK_GL_ATTRIB_LIST_NONE.
Returns : | the new GdkGLConfig.

gdk_gl_config_new_by_mode ()

GdkGLConfig* gdk_gl_config_new_by_mode      (GdkGLConfigMode mode);

Returns an OpenGL frame buffer configuration that match the specified display mode.

mode : | display mode bit mask.
Returns : | the new GdkGLConfig.

gdk_gl_config_new_by_mode_for_screen ()

GdkGLConfig* gdk_gl_config_new_by_mode_for_screen
                                            (GdkScreen *screen,
                                             GdkGLConfigMode mode);

Returns an OpenGL frame buffer configuration that match the specified display mode.

screen : | target screen.
mode : | display mode bit mask.
Returns : | the new GdkGLConfig.

gdk_gl_config_get_screen ()

GdkScreen*  gdk_gl_config_get_screen        (GdkGLConfig *glconfig);

Gets GdkScreen.

glconfig : | a GdkGLConfig.
Returns : | the GdkScreen.

gdk_gl_config_get_attrib ()

gboolean    gdk_gl_config_get_attrib        (GdkGLConfig *glconfig,
                                             int attribute,
                                             int *value);

Gets information about a OpenGL frame buffer configuration.

glconfig : | a GdkGLConfig.
attribute : | the attribute to be returned.
value : | returns the requested value.
Returns : | TRUE if it succeeded, FALSE otherwise.

gdk_gl_config_get_colormap ()

GdkColormap* gdk_gl_config_get_colormap     (GdkGLConfig *glconfig);

Gets the GdkColormap that is appropriate for the OpenGL frame buffer configuration.

glconfig : | a GdkGLConfig.
Returns : | the appropriate GdkColormap.

gdk_gl_config_get_visual ()

GdkVisual*  gdk_gl_config_get_visual        (GdkGLConfig *glconfig);

Gets the GdkVisual that is appropriate for the OpenGL frame buffer configuration.

glconfig : | a GdkGLConfig.
Returns : | the appropriate GdkVisual.

gdk_gl_config_get_depth ()

gint        gdk_gl_config_get_depth         (GdkGLConfig *glconfig);

Gets the color depth of the OpenGL-capable visual.

glconfig : | a GdkGLConfig.
Returns : | number of bits per pixel

gdk_gl_config_get_layer_plane ()

gint        gdk_gl_config_get_layer_plane   (GdkGLConfig *glconfig);

Gets the layer plane (level) of the frame buffer. Zero is the default frame buffer. Positive layer planes correspond to frame buffers that overlay the default buffer, and negative layer planes correspond to frame buffers that underlie the default frame buffer.

glconfig : | a GdkGLConfig.
Returns : | layer plane.

gdk_gl_config_get_n_aux_buffers ()

gint        gdk_gl_config_get_n_aux_buffers (GdkGLConfig *glconfig);

Gets the number of auxiliary color buffers.

glconfig : | a GdkGLConfig.
Returns : | number of auxiliary color buffers.

gdk_gl_config_get_n_sample_buffers ()

gint        gdk_gl_config_get_n_sample_buffers
                                            (GdkGLConfig *glconfig);

Gets the number of multisample buffers.

glconfig : | a GdkGLConfig.
Returns : | number of multisample buffers.

gdk_gl_config_is_rgba ()

gboolean    gdk_gl_config_is_rgba           (GdkGLConfig *glconfig);

Returns whether the configured frame buffer is RGBA mode.

glconfig : | a GdkGLConfig.
Returns : | TRUE if the configured frame buffer is RGBA mode, FALSE otherwise.

gdk_gl_config_is_double_buffered ()

gboolean    gdk_gl_config_is_double_buffered
                                            (GdkGLConfig *glconfig);

Returns whether the configuration supports the double-buffered visual.

glconfig : | a GdkGLConfig.
Returns : | TRUE if the double-buffered visual is supported, FALSE otherwise.

gdk_gl_config_is_stereo ()

gboolean    gdk_gl_config_is_stereo         (GdkGLConfig *glconfig);

Returns whether the configuration supports the stereo visual.

glconfig : | a GdkGLConfig.
Returns : | TRUE if the stereo visual is supported, FALSE otherwise.

gdk_gl_config_has_alpha ()

gboolean    gdk_gl_config_has_alpha         (GdkGLConfig *glconfig);

Returns whether the configured color buffer has alpha bits.

glconfig : | a GdkGLConfig.
Returns : | TRUE if the color buffer has alpha bits, FALSE otherwise.

gdk_gl_config_has_depth_buffer ()

gboolean    gdk_gl_config_has_depth_buffer  (GdkGLConfig *glconfig);

Returns whether the configured frame buffer has depth buffer.

glconfig : | a GdkGLConfig.
Returns : | TRUE if the frame buffer has depth buffer, FALSE otherwise.

gdk_gl_config_has_stencil_buffer ()

gboolean    gdk_gl_config_has_stencil_buffer
                                            (GdkGLConfig *glconfig);

Returns whether the configured frame buffer has stencil buffer.

glconfig : | a GdkGLConfig.
Returns : | TRUE if the frame buffer has stencil buffer, FALSE otherwise.

gdk_gl_config_has_accum_buffer ()

gboolean    gdk_gl_config_has_accum_buffer  (GdkGLConfig *glconfig);

Returns whether the configured frame buffer has accumulation buffer.

glconfig : | a GdkGLConfig.
Returns : | TRUE if the frame buffer has accumulation buffer, FALSE otherwise.


Rendering Context

Rendering Context — OpenGL rendering context object

Synopsis

#include <gdk/gdkgl.h>

struct      GdkGLContext;
GdkGLContext* gdk_gl_context_new            (GdkGLDrawable *gldrawable,
                                             GdkGLContext *share_list,
                                             gboolean direct,
                                             int render_type);
void        gdk_gl_context_destroy          (GdkGLContext *glcontext);
gboolean    gdk_gl_context_copy             (GdkGLContext *glcontext,
                                             GdkGLContext *src,
                                             unsigned long  mask);
GdkGLDrawable* gdk_gl_context_get_gl_drawable
                                            (GdkGLContext *glcontext);
GdkGLConfig* gdk_gl_context_get_gl_config   (GdkGLContext *glcontext);
GdkGLContext* gdk_gl_context_get_share_list (GdkGLContext *glcontext);
gboolean    gdk_gl_context_is_direct        (GdkGLContext *glcontext);
int         gdk_gl_context_get_render_type  (GdkGLContext *glcontext);
GdkGLContext* gdk_gl_context_get_current    (void);

Object Hierarchy

  GObject
   +----GdkGLContext

Description

Details

struct GdkGLContext

struct GdkGLContext;

gdk_gl_context_new ()

GdkGLContext* gdk_gl_context_new            (GdkGLDrawable *gldrawable,
                                             GdkGLContext *share_list,
                                             gboolean direct,
                                             int render_type);

Creates a new OpenGL rendering context.

gldrawable : | a GdkGLDrawable.
share_list : | the GdkGLContext with which to share display lists and texture objects. NULL indicates that no sharing is to take place.
direct : | whether rendering is to be done with a direct connection to the graphics system.
render_type : | GDK_GL_RGBA_TYPE or GDK_GL_COLOR_INDEX_TYPE (currently not used).
Returns : | the new GdkGLContext.

gdk_gl_context_destroy ()

void        gdk_gl_context_destroy          (GdkGLContext *glcontext);

Destroys the OpenGL resources associated with glcontext and decrements glcontext's reference count.

glcontext : a GdkGLContext.

gdk_gl_context_copy ()

gboolean    gdk_gl_context_copy             (GdkGLContext *glcontext,
                                             GdkGLContext *src,
                                             unsigned long  mask);

Copy state from src rendering context to glcontext.

mask contains the bitwise-OR of the same symbolic names that are passed to the glPushAttrib() function. You can use GL_ALL_ATTRIB_BITS to copy all the rendering state information.

glcontext : | a GdkGLContext.
src : | the source context.
Param3 : |
Returns : | FALSE if it fails, TRUE otherwise.

gdk_gl_context_get_gl_drawable ()

GdkGLDrawable* gdk_gl_context_get_gl_drawable
                                            (GdkGLContext *glcontext);

Gets GdkGLDrawable to which the glcontext is bound.

glcontext : | a GdkGLContext.
Returns : | the GdkGLDrawable or NULL if no GdkGLDrawable is bound.

gdk_gl_context_get_gl_config ()

GdkGLConfig* gdk_gl_context_get_gl_config   (GdkGLContext *glcontext);

Gets GdkGLConfig with which the glcontext is configured.

glcontext : | a GdkGLContext.
Returns : | the GdkGLConfig.

gdk_gl_context_get_share_list ()

GdkGLContext* gdk_gl_context_get_share_list (GdkGLContext *glcontext);

Gets GdkGLContext with which the glcontext shares the display lists and texture objects.

glcontext : | a GdkGLContext.
Returns : | the GdkGLContext.

gdk_gl_context_is_direct ()

gboolean    gdk_gl_context_is_direct        (GdkGLContext *glcontext);

Returns whether the glcontext is a direct rendering context.

glcontext : | a GdkGLContext.
Returns : | TRUE if the glcontext is a direct rendering contest.

gdk_gl_context_get_render_type ()

int         gdk_gl_context_get_render_type  (GdkGLContext *glcontext);

Gets render_type of the glcontext.

glcontext : | a GdkGLContext.
Returns : | GDK_GL_RGBA_TYPE or GDK_GL_COLOR_INDEX_TYPE.

gdk_gl_context_get_current ()

GdkGLContext* gdk_gl_context_get_current    (void);

Returns the current GdkGLContext.

Returns : the current GdkGLContext or NULL if there is no current context.


Rendering Surface

Rendering Surface — OpenGL rendering surface interface

Synopsis

#include <gdk/gdkgl.h>

struct      GdkGLDrawable;
gboolean    gdk_gl_drawable_make_current    (GdkGLDrawable *gldrawable,
                                             GdkGLContext *glcontext);
gboolean    gdk_gl_drawable_is_double_buffered
                                            (GdkGLDrawable *gldrawable);
void        gdk_gl_drawable_swap_buffers    (GdkGLDrawable *gldrawable);
void        gdk_gl_drawable_wait_gl         (GdkGLDrawable *gldrawable);
void        gdk_gl_drawable_wait_gdk        (GdkGLDrawable *gldrawable);
gboolean    gdk_gl_drawable_gl_begin        (GdkGLDrawable *gldrawable,
                                             GdkGLContext *glcontext);
void        gdk_gl_drawable_gl_end          (GdkGLDrawable *gldrawable);
GdkGLConfig* gdk_gl_drawable_get_gl_config  (GdkGLDrawable *gldrawable);
void        gdk_gl_drawable_get_size        (GdkGLDrawable *gldrawable,
                                             gint *width,
                                             gint *height);
GdkGLDrawable* gdk_gl_drawable_get_current  (void);

Object Hierarchy

  GInterface
   +----GdkGLDrawable

Description

Details

struct GdkGLDrawable

struct GdkGLDrawable;

gdk_gl_drawable_make_current ()

gboolean    gdk_gl_drawable_make_current    (GdkGLDrawable *gldrawable,
                                             GdkGLContext *glcontext);

Attach an OpenGL rendering context to a gldrawable.

gldrawable : | a GdkGLDrawable.
glcontext : | a GdkGLContext.
Returns : | TRUE if it is successful, FALSE otherwise.

gdk_gl_drawable_is_double_buffered ()

gboolean    gdk_gl_drawable_is_double_buffered
                                            (GdkGLDrawable *gldrawable);

Returns whether the gldrawable supports the double-buffered visual.

gldrawable : | a GdkGLDrawable.
Returns : | TRUE if the double-buffered visual is supported, FALSE otherwise.

gdk_gl_drawable_swap_buffers ()

void        gdk_gl_drawable_swap_buffers    (GdkGLDrawable *gldrawable);

Exchange front and back buffers.

gldrawable : a GdkGLDrawable.

gdk_gl_drawable_wait_gl ()

void        gdk_gl_drawable_wait_gl         (GdkGLDrawable *gldrawable);

Complete OpenGL execution prior to subsequent GDK drawing calls.

gldrawable : a GdkGLDrawable.

gdk_gl_drawable_wait_gdk ()

void        gdk_gl_drawable_wait_gdk        (GdkGLDrawable *gldrawable);

Complete GDK drawing execution prior to subsequent OpenGL calls.

gldrawable : a GdkGLDrawable.

gdk_gl_drawable_gl_begin ()

gboolean    gdk_gl_drawable_gl_begin        (GdkGLDrawable *gldrawable,
                                             GdkGLContext *glcontext);

Delimits the begining of the OpenGL execution.

gldrawable : | a GdkGLDrawable.
glcontext : | a GdkGLContext.
Returns : | TRUE if it is successful, FALSE otherwise.

gdk_gl_drawable_gl_end ()

void        gdk_gl_drawable_gl_end          (GdkGLDrawable *gldrawable);

Delimits the end of the OpenGL execution.

gldrawable : a GdkGLDrawable.

gdk_gl_drawable_get_gl_config ()

GdkGLConfig* gdk_gl_drawable_get_gl_config  (GdkGLDrawable *gldrawable);

Gets GdkGLConfig with which the gldrawable is configured.

gldrawable : | a GdkGLDrawable.
Returns : | the GdkGLConfig.

gdk_gl_drawable_get_size ()

void        gdk_gl_drawable_get_size        (GdkGLDrawable *gldrawable,
                                             gint *width,
                                             gint *height);

Fills *width and *height with the size of GL drawable. width or height can be NULL if you only want the other one.

gldrawable : | a GdkGLDrawable.
width : | location to store drawable's width, or NULL.
height : | location to store drawable's height, or NULL.

gdk_gl_drawable_get_current ()

GdkGLDrawable* gdk_gl_drawable_get_current  (void);

Returns the current GdkGLDrawable.

Returns : the current GdkGLDrawable or NULL if there is no current drawable.


Font Rendering

Font Rendering — Functions for font rendering in OpenGL

Synopsis

#include <gdk/gdkgl.h>

PangoFont*  gdk_gl_font_use_pango_font      (const PangoFontDescription *font_desc,
                                             int first,
                                             int count,
                                             int list_base);
PangoFont*  gdk_gl_font_use_pango_font_for_display
                                            (GdkDisplay *display,
                                             const PangoFontDescription *font_desc,
                                             int first,
                                             int count,
                                             int list_base);

Description

Details

gdk_gl_font_use_pango_font ()

PangoFont*  gdk_gl_font_use_pango_font      (const PangoFontDescription *font_desc,
                                             int first,
                                             int count,
                                             int list_base);

Creates bitmap display lists from a PangoFont.

font_desc : | a PangoFontDescription describing the font to use.
first : | the index of the first glyph to be taken.
count : | the number of glyphs to be taken.
list_base : | the index of the first display list to be generated.
Returns : | the PangoFont used, or NULL if no font matched.

gdk_gl_font_use_pango_font_for_display ()

PangoFont*  gdk_gl_font_use_pango_font_for_display
                                            (GdkDisplay *display,
                                             const PangoFontDescription *font_desc,
                                             int first,
                                             int count,
                                             int list_base);

Creates bitmap display lists from a PangoFont.

display : | a GdkDisplay.
font_desc : | a PangoFontDescription describing the font to use.
first : | the index of the first glyph to be taken.
count : | the number of glyphs to be taken.
list_base : | the index of the first display list to be generated.
Returns : | the PangoFont used, or NULL if no font matched.


Initialization

Initialization — Library initialization functions

Synopsis

#include <gdk/gdkgl.h>

void        gdk_gl_init                     (int *argc,
                                             char ***argv);
gboolean    gdk_gl_init_check               (int *argc,
                                             char ***argv);
gboolean    gdk_gl_parse_args               (int *argc,
                                             char ***argv);

Description

Details

gdk_gl_init ()

void        gdk_gl_init                     (int *argc,
                                             char ***argv);

Call this function before using any other GdkGLExt functions in your applications. It will initialize everything needed to operate the library and parses some standard command line options. argc and argv are adjusted accordingly so your own code will never see those standard arguments.

Note

This function will terminate your program if it was unable to initialize the library for some reason. If you want your program to fall back to a textual interface you want to call gdk_gl_init_check() instead.

argc : | Address of the argc parameter of your main() function. Changed if any arguments were handled.
argv : | Address of the argv parameter of main(). Any parameters understood by gdk_gl_init() are stripped before return.

gdk_gl_init_check ()

gboolean    gdk_gl_init_check               (int *argc,
                                             char ***argv);

This function does the same work as gdk_gl_init() with only a single change: It does not terminate the program if the library can't be initialized. Instead it returns FALSE on failure.

This way the application can fall back to some other means of communication with the user - for example a curses or command line interface.

argc : | Address of the argc parameter of your main() function. Changed if any arguments were handled.
argv : | Address of the argv parameter of main(). Any parameters understood by gdk_gl_init() are stripped before return.
Returns : | TRUE if the GUI has been successfully initialized, FALSE otherwise.

gdk_gl_parse_args ()

gboolean    gdk_gl_parse_args               (int *argc,
                                             char ***argv);

Parses command line arguments, and initializes global attributes of GdkGLExt.

Any arguments used by GdkGLExt are removed from the array and argc and argv are updated accordingly.

You shouldn't call this function explicitely if you are using gdk_gl_init(), or gdk_gl_init_check().

argc : | the number of command line arguments.
argv : | the array of command line arguments.
Returns : | TRUE if initialization succeeded, otherwise FALSE.


OpenGL Pixmap

OpenGL Pixmap — OpenGL pixmap which is maintained off-screen

Synopsis

#include <gdk/gdkgl.h>

struct      GdkGLPixmap;
GdkGLPixmap* gdk_gl_pixmap_new              (GdkGLConfig *glconfig,
                                             GdkPixmap *pixmap,
                                             const int *attrib_list);
void        gdk_gl_pixmap_destroy           (GdkGLPixmap *glpixmap);
GdkPixmap*  gdk_gl_pixmap_get_pixmap        (GdkGLPixmap *glpixmap);
GdkGLPixmap* gdk_pixmap_set_gl_capability   (GdkPixmap *pixmap,
                                             GdkGLConfig *glconfig,
                                             const int *attrib_list);
void        gdk_pixmap_unset_gl_capability  (GdkPixmap *pixmap);
gboolean    gdk_pixmap_is_gl_capable        (GdkPixmap *pixmap);
GdkGLPixmap* gdk_pixmap_get_gl_pixmap       (GdkPixmap *pixmap);
#define     gdk_pixmap_get_gl_drawable      (pixmap)

Object Hierarchy

  GObject
   +----GdkDrawable
         +----GdkGLPixmap

Description

Details

struct GdkGLPixmap

struct GdkGLPixmap;

gdk_gl_pixmap_new ()

GdkGLPixmap* gdk_gl_pixmap_new              (GdkGLConfig *glconfig,
                                             GdkPixmap *pixmap,
                                             const int *attrib_list);

Creates an off-screen rendering area. attrib_list is currently unused. This must be set to NULL or empty (first attribute of None). See GLX 1.3 spec.

glconfig : | a GdkGLConfig.
pixmap : | the GdkPixmap to be used as the rendering area.
attrib_list : | this must be set to NULL or empty (first attribute of None).
Returns : | the new GdkGLPixmap.

gdk_gl_pixmap_destroy ()

void        gdk_gl_pixmap_destroy           (GdkGLPixmap *glpixmap);

Destroys the OpenGL resources associated with glpixmap and decrements glpixmap's reference count.

glpixmap : a GdkGLPixmap.

gdk_gl_pixmap_get_pixmap ()

GdkPixmap*  gdk_gl_pixmap_get_pixmap        (GdkGLPixmap *glpixmap);

Returns the GdkPixmap associated with glpixmap.

Notice that GdkGLPixmap is not GdkPixmap, but another GdkDrawable which have an associated GdkPixmap.

glpixmap : | a GdkGLPixmap.
Returns : | the GdkPixmap associated with glpixmap.

gdk_pixmap_set_gl_capability ()

GdkGLPixmap* gdk_pixmap_set_gl_capability   (GdkPixmap *pixmap,
                                             GdkGLConfig *glconfig,
                                             const int *attrib_list);

Set the OpenGL-capability to the pixmap. This function creates a new GdkGLPixmap held by the pixmap. attrib_list is currently unused. This must be set to NULL or empty (first attribute of None).

pixmap : | the GdkPixmap to be used as the rendering area.
glconfig : | a GdkGLConfig.
attrib_list : | this must be set to NULL or empty (first attribute of None).
Returns : | the GdkGLPixmap used by the pixmap if it is successful, NULL otherwise.

gdk_pixmap_unset_gl_capability ()

void        gdk_pixmap_unset_gl_capability  (GdkPixmap *pixmap);

Unset the OpenGL-capability of the pixmap. This function destroys the GdkGLPixmap held by the pixmap.

pixmap : a GdkPixmap.

gdk_pixmap_is_gl_capable ()

gboolean    gdk_pixmap_is_gl_capable        (GdkPixmap *pixmap);

Returns whether the pixmap is OpenGL-capable.

pixmap : | a GdkPixmap.
Returns : | TRUE if the pixmap is OpenGL-capable, FALSE otherwise.

gdk_pixmap_get_gl_pixmap ()

GdkGLPixmap* gdk_pixmap_get_gl_pixmap       (GdkPixmap *pixmap);

Returns the GdkGLPixmap held by the pixmap.

pixmap : | a GdkPixmap.
Returns : | the GdkGLPixmap.

gdk_pixmap_get_gl_drawable()

#define     gdk_pixmap_get_gl_drawable(pixmap)

Returns the GdkGLDrawable held by the pixmap. In fact, this is macro that casts the result of gdk_pixmap_get_gl_pixmap to GdkGLDrawable.

pixmap : | a GdkGLPixmap.
Returns : | the GdkGLDrawable.


Query

Query — Functions to query OpenGL support information

Synopsis

#include <gdk/gdkgl.h>

void        (*GdkGLProc)                    (void);
gboolean    gdk_gl_query_extension          (void);
gboolean    gdk_gl_query_extension_for_display
                                            (GdkDisplay *display);
gboolean    gdk_gl_query_version            (int *major,
                                             int *minor);
gboolean    gdk_gl_query_version_for_display
                                            (GdkDisplay *display,
                                             int *major,
                                             int *minor);
gboolean    gdk_gl_query_gl_extension       (const char *extension);
GdkGLProc   gdk_gl_get_proc_address         (const char *proc_name);

Description

Details

GdkGLProc ()

void        (*GdkGLProc)                    (void);

gdk_gl_query_extension ()

gboolean    gdk_gl_query_extension          (void);

Indicates whether the window system supports the OpenGL extension (GLX, WGL, etc.).

Returns : TRUE if OpenGL is supported, FALSE otherwise.

gdk_gl_query_extension_for_display ()

gboolean    gdk_gl_query_extension_for_display
                                            (GdkDisplay *display);

Indicates whether the window system supports the OpenGL extension (GLX, WGL, etc.).

display : | the GdkDisplay where the query is sent to.
Returns : | TRUE if OpenGL is supported, FALSE otherwise.

gdk_gl_query_version ()

gboolean    gdk_gl_query_version            (int *major,
                                             int *minor);

Returns the version numbers of the OpenGL extension to the window system.

In the X Window System, it returns the GLX version.

In the Microsoft Windows, it returns the Windows version.

major : | returns the major version number of the OpenGL extension.
minor : | returns the minor version number of the OpenGL extension.
Returns : | FALSE if it fails, TRUE otherwise.

gdk_gl_query_version_for_display ()

gboolean    gdk_gl_query_version_for_display
                                            (GdkDisplay *display,
                                             int *major,
                                             int *minor);

Returns the version numbers of the OpenGL extension to the window system.

In the X Window System, it returns the GLX version.

In the Microsoft Windows, it returns the Windows version.

display : | the GdkDisplay where the query is sent to.
major : | returns the major version number of the OpenGL extension.
minor : | returns the minor version number of the OpenGL extension.
Returns : | FALSE if it fails, TRUE otherwise.

gdk_gl_query_gl_extension ()

gboolean    gdk_gl_query_gl_extension       (const char *extension);

Determines whether a given OpenGL extension is supported.

There must be a valid current rendering context to call gdk_gl_query_gl_extension().

gdk_gl_query_gl_extension() returns information about OpenGL extensions only. This means that window system dependent extensions (for example, GLX extensions) are not reported by gdk_gl_query_gl_extension().

extension : | name of OpenGL extension.
Returns : | TRUE if the OpenGL extension is supported, FALSE if not supported.

gdk_gl_get_proc_address ()

GdkGLProc   gdk_gl_get_proc_address         (const char *proc_name);

Returns the address of the OpenGL, GLU, or GLX function.

proc_name : | function name.
Returns : | the address of the function named by proc_name.


Geometric Object Rendering

Geometric Object Rendering — Functions for generating easily recognizable 3D geometric objects

Synopsis

#include <gdk/gdkgl.h>

void        gdk_gl_draw_cube                (gboolean solid,
                                             double size);
void        gdk_gl_draw_sphere              (gboolean solid,
                                             double radius,
                                             int slices,
                                             int stacks);
void        gdk_gl_draw_cone                (gboolean solid,
                                             double base,
                                             double height,
                                             int slices,
                                             int stacks);
void        gdk_gl_draw_torus               (gboolean solid,
                                             double inner_radius,
                                             double outer_radius,
                                             int nsides,
                                             int rings);
void        gdk_gl_draw_tetrahedron         (gboolean solid);
void        gdk_gl_draw_octahedron          (gboolean solid);
void        gdk_gl_draw_dodecahedron        (gboolean solid);
void        gdk_gl_draw_icosahedron         (gboolean solid);
void        gdk_gl_draw_teapot              (gboolean solid,
                                             double scale);

Description

Details

gdk_gl_draw_cube ()

void        gdk_gl_draw_cube                (gboolean solid,
                                             double size);

Renders a cube. The cube is centered at the modeling coordinates origin with sides of length size.

solid : | TRUE if the cube should be solid.
size : | length of cube sides.

gdk_gl_draw_sphere ()

void        gdk_gl_draw_sphere              (gboolean solid,
                                             double radius,
                                             int slices,
                                             int stacks);

Renders a sphere centered at the modeling coordinates origin of the specified radius. The sphere is subdivided around the Z axis into slices and along the Z axis into stacks.

solid : | TRUE if the sphere should be solid.
radius : | the radius of the sphere.
slices : | the number of subdivisions around the Z axis (similar to lines of longitude).
stacks : | the number of subdivisions along the Z axis (similar to lines of latitude).

gdk_gl_draw_cone ()

void        gdk_gl_draw_cone                (gboolean solid,
                                             double base,
                                             double height,
                                             int slices,
                                             int stacks);

Renders a cone oriented along the Z axis. The base of the cone is placed at Z = 0, and the top at Z = height. The cone is subdivided around the Z axis into slices, and along the Z axis into stacks.

solid : | TRUE if the cone should be solid.
base : | the radius of the base of the cone.
height : | the height of the cone.
slices : | the number of subdivisions around the Z axis.
stacks : | the number of subdivisions along the Z axis.

gdk_gl_draw_torus ()

void        gdk_gl_draw_torus               (gboolean solid,
                                             double inner_radius,
                                             double outer_radius,
                                             int nsides,
                                             int rings);

Renders a torus (doughnut) centered at the modeling coordinates origin whose axis is aligned with the Z axis.

solid : | TRUE if the torus should be solid.
inner_radius : | inner radius of the torus.
outer_radius : | outer radius of the torus.
nsides : | number of sides for each radial section.
rings : | number of radial divisions for the torus.

gdk_gl_draw_tetrahedron ()

void        gdk_gl_draw_tetrahedron         (gboolean solid);

Renders a tetrahedron centered at the modeling coordinates origin with a radius of the square root of 3.

solid : TRUE if the tetrahedron should be solid.

gdk_gl_draw_octahedron ()

void        gdk_gl_draw_octahedron          (gboolean solid);

Renders a octahedron centered at the modeling coordinates origin with a radius of 1.0.

solid : TRUE if the octahedron should be solid.

gdk_gl_draw_dodecahedron ()

void        gdk_gl_draw_dodecahedron        (gboolean solid);

Renders a dodecahedron centered at the modeling coordinates origin with a radius of the square root of 3.

solid : TRUE if the dodecahedron should be solid.

gdk_gl_draw_icosahedron ()

void        gdk_gl_draw_icosahedron         (gboolean solid);

Renders a icosahedron. The icosahedron is centered at the modeling coordinates origin and has a radius of 1.0.

solid : TRUE if the icosahedron should be solid.

gdk_gl_draw_teapot ()

void        gdk_gl_draw_teapot              (gboolean solid,
                                             double scale);

Renders a teapot. Both surface normals and texture coordinates for the teapot are generated. The teapot is generated with OpenGL evaluators.

solid : | TRUE if the teapot should be solid.
scale : | relative size of the teapot.


Tokens

Tokens — OpenGL-related tokens

Synopsis

#include <gdk/gdkgl.h>

#define     GDK_GL_SUCCESS
#define     GDK_GL_ATTRIB_LIST_NONE
enum        GdkGLConfigAttrib;
#define     GDK_GL_DONT_CARE
#define     GDK_GL_NONE
enum        GdkGLConfigCaveat;
enum        GdkGLVisualType;
enum        GdkGLTransparentType;
enum        GdkGLDrawableTypeMask;
enum        GdkGLRenderTypeMask;
enum        GdkGLBufferMask;
enum        GdkGLConfigError;
enum        GdkGLRenderType;
enum        GdkGLDrawableAttrib;
enum        GdkGLPbufferAttrib;
enum        GdkGLEventMask;
enum        GdkGLEventType;
enum        GdkGLDrawableType;

Description

Details

GDK_GL_SUCCESS

#define GDK_GL_SUCCESS          0  /* same as 'Success' of X11 */

GDK_GL_ATTRIB_LIST_NONE

#define GDK_GL_ATTRIB_LIST_NONE 0  /* same as 'None' of X11 */

enum GdkGLConfigAttrib

typedef enum
{
  GDK_GL_USE_GL                     = 1,  /* support GLX rendering */
  GDK_GL_BUFFER_SIZE                = 2,  /* depth of the color buffer */
  GDK_GL_LEVEL                      = 3,  /* level in plane stacking */
  GDK_GL_RGBA                       = 4,  /* true if RGBA mode */
  GDK_GL_DOUBLEBUFFER               = 5,  /* double buffering supported */
  GDK_GL_STEREO                     = 6,  /* stereo buffering supported */
  GDK_GL_AUX_BUFFERS                = 7,  /* number of aux buffers */
  GDK_GL_RED_SIZE                   = 8,  /* number of red component bits */
  GDK_GL_GREEN_SIZE                 = 9,  /* number of green component bits */
  GDK_GL_BLUE_SIZE                  = 10, /* number of blue component bits */
  GDK_GL_ALPHA_SIZE                 = 11, /* number of alpha component bits */
  GDK_GL_DEPTH_SIZE                 = 12, /* number of depth bits */
  GDK_GL_STENCIL_SIZE               = 13, /* number of stencil bits */
  GDK_GL_ACCUM_RED_SIZE             = 14, /* number of red accum bits */
  GDK_GL_ACCUM_GREEN_SIZE           = 15, /* number of green accum bits */
  GDK_GL_ACCUM_BLUE_SIZE            = 16, /* number of blue accum bits */
  GDK_GL_ACCUM_ALPHA_SIZE           = 17, /* number of alpha accum bits */

  /*
   * FBConfig-specific attributes.
   * [ GLX 1.3 and later ]
   */
  GDK_GL_CONFIG_CAVEAT              = 0x20,
  GDK_GL_X_VISUAL_TYPE              = 0x22,
  GDK_GL_TRANSPARENT_TYPE           = 0x23,
  GDK_GL_TRANSPARENT_INDEX_VALUE    = 0x24,
  GDK_GL_TRANSPARENT_RED_VALUE      = 0x25,
  GDK_GL_TRANSPARENT_GREEN_VALUE    = 0x26,
  GDK_GL_TRANSPARENT_BLUE_VALUE     = 0x27,
  GDK_GL_TRANSPARENT_ALPHA_VALUE    = 0x28,
  GDK_GL_DRAWABLE_TYPE              = 0x8010,
  GDK_GL_RENDER_TYPE                = 0x8011,
  GDK_GL_X_RENDERABLE               = 0x8012,
  GDK_GL_FBCONFIG_ID                = 0x8013,
  GDK_GL_MAX_PBUFFER_WIDTH          = 0x8016,
  GDK_GL_MAX_PBUFFER_HEIGHT         = 0x8017,
  GDK_GL_MAX_PBUFFER_PIXELS         = 0x8018,
  GDK_GL_VISUAL_ID                  = 0x800B,
  GDK_GL_SCREEN                     = 0x800C,

  /*
   * Multisampling configuration attributes.
   * [ GLX 1.4 and later ]
   */
  GDK_GL_SAMPLE_BUFFERS             = 100000,
  GDK_GL_SAMPLES                    = 100001

} GdkGLConfigAttrib;

GDK_GL_DONT_CARE

#define GDK_GL_DONT_CARE              0xFFFFFFFF

GDK_GL_NONE

#define GDK_GL_NONE                   0x8000

enum GdkGLConfigCaveat

typedef enum
{
  GDK_GL_CONFIG_CAVEAT_DONT_CARE    = 0xFFFFFFFF, /* GDK_GL_DONT_CARE */
  GDK_GL_CONFIG_CAVEAT_NONE         = 0x8000,     /* GDK_GL_NONE */
  GDK_GL_SLOW_CONFIG                = 0x8001,
  GDK_GL_NON_CONFORMANT_CONFIG      = 0x800D
} GdkGLConfigCaveat;

enum GdkGLVisualType

typedef enum
{
  GDK_GL_VISUAL_TYPE_DONT_CARE      = 0xFFFFFFFF, /* GDK_GL_DONT_CARE */
  GDK_GL_TRUE_COLOR                 = 0x8002,
  GDK_GL_DIRECT_COLOR               = 0x8003,
  GDK_GL_PSEUDO_COLOR               = 0x8004,
  GDK_GL_STATIC_COLOR               = 0x8005,
  GDK_GL_GRAY_SCALE                 = 0x8006,
  GDK_GL_STATIC_GRAY                = 0x8007
} GdkGLVisualType;

enum GdkGLTransparentType

typedef enum
{
  GDK_GL_TRANSPARENT_NONE           = 0x8000, /* GDK_GL_NONE */
  GDK_GL_TRANSPARENT_RGB            = 0x8008,
  GDK_GL_TRANSPARENT_INDEX          = 0x8009
} GdkGLTransparentType;

enum GdkGLDrawableTypeMask

typedef enum
{
  GDK_GL_WINDOW_BIT                 = 1 << 0, /* 0x00000001 */
  GDK_GL_PIXMAP_BIT                 = 1 << 1, /* 0x00000002 */
  GDK_GL_PBUFFER_BIT                = 1 << 2  /* 0x00000004 */
} GdkGLDrawableTypeMask;

enum GdkGLRenderTypeMask

typedef enum
{
  GDK_GL_RGBA_BIT                   = 1 << 0, /* 0x00000001 */
  GDK_GL_COLOR_INDEX_BIT            = 1 << 1  /* 0x00000002 */
} GdkGLRenderTypeMask;

enum GdkGLBufferMask

typedef enum
{
  GDK_GL_FRONT_LEFT_BUFFER_BIT      = 1 << 0, /* 0x00000001 */
  GDK_GL_FRONT_RIGHT_BUFFER_BIT     = 1 << 1, /* 0x00000002 */
  GDK_GL_BACK_LEFT_BUFFER_BIT       = 1 << 2, /* 0x00000004 */
  GDK_GL_BACK_RIGHT_BUFFER_BIT      = 1 << 3, /* 0x00000008 */
  GDK_GL_AUX_BUFFERS_BIT            = 1 << 4, /* 0x00000010 */
  GDK_GL_DEPTH_BUFFER_BIT           = 1 << 5, /* 0x00000020 */
  GDK_GL_STENCIL_BUFFER_BIT         = 1 << 6, /* 0x00000040 */
  GDK_GL_ACCUM_BUFFER_BIT           = 1 << 7  /* 0x00000080 */
} GdkGLBufferMask;

enum GdkGLConfigError

typedef enum
{
  GDK_GL_BAD_SCREEN                 = 1, /* screen # is bad */
  GDK_GL_BAD_ATTRIBUTE              = 2, /* attribute to get is bad */
  GDK_GL_NO_EXTENSION               = 3, /* no glx extension on server */
  GDK_GL_BAD_VISUAL                 = 4, /* visual # not known by GLX */
  GDK_GL_BAD_CONTEXT                = 5, /* returned only by import_context EXT? */
  GDK_GL_BAD_VALUE                  = 6, /* returned only by glXSwapIntervalSGI? */
  GDK_GL_BAD_ENUM                   = 7  /* unused? */
} GdkGLConfigError;

enum GdkGLRenderType

typedef enum
{
  GDK_GL_RGBA_TYPE                  = 0x8014,
  GDK_GL_COLOR_INDEX_TYPE           = 0x8015
} GdkGLRenderType;

enum GdkGLDrawableAttrib

typedef enum
{
  GDK_GL_PRESERVED_CONTENTS         = 0x801B,
  GDK_GL_LARGEST_PBUFFER            = 0x801C,
  GDK_GL_WIDTH                      = 0x801D,
  GDK_GL_HEIGHT                     = 0x801E,
  GDK_GL_EVENT_MASK                 = 0x801F
} GdkGLDrawableAttrib;

enum GdkGLPbufferAttrib

typedef enum
{
  GDK_GL_PBUFFER_PRESERVED_CONTENTS = 0x801B, /* GDK_GL_PRESERVED_CONTENTS */
  GDK_GL_PBUFFER_LARGEST_PBUFFER    = 0x801C, /* GDK_GL_LARGEST_PBUFFER */
  GDK_GL_PBUFFER_HEIGHT             = 0x8040,
  GDK_GL_PBUFFER_WIDTH              = 0x8041
} GdkGLPbufferAttrib;

enum GdkGLEventMask

typedef enum
{
  GDK_GL_PBUFFER_CLOBBER_MASK       = 1 << 27  /* 0x08000000 */
} GdkGLEventMask;

enum GdkGLEventType

typedef enum
{
  GDK_GL_DAMAGED                    = 0x8020,
  GDK_GL_SAVED                      = 0x8021
} GdkGLEventType;

enum GdkGLDrawableType

typedef enum
{
  GDK_GL_WINDOW                     = 0x8022,
  GDK_GL_PBUFFER                    = 0x8023
} GdkGLDrawableType;


Version Information

Version Information — Variables and macros to check the GdkGLExt version

Synopsis

#include <gdk/gdkgl.h>

#define     GDKGLEXT_MAJOR_VERSION
#define     GDKGLEXT_MINOR_VERSION
#define     GDKGLEXT_MICRO_VERSION
#define     GDKGLEXT_INTERFACE_AGE
#define     GDKGLEXT_BINARY_AGE
#define     GDKGLEXT_CHECK_VERSION          (major, minor, micro)
extern      const guint gdkglext_major_version;
extern      const guint gdkglext_minor_version;
extern      const guint gdkglext_micro_version;
extern      const guint gdkglext_interface_age;
extern      const guint gdkglext_binary_age;

Description

Details

GDKGLEXT_MAJOR_VERSION

#define GDKGLEXT_MAJOR_VERSION (1)

GDKGLEXT_MINOR_VERSION

#define GDKGLEXT_MINOR_VERSION (0)

GDKGLEXT_MICRO_VERSION

#define GDKGLEXT_MICRO_VERSION (5)

GDKGLEXT_INTERFACE_AGE

#define GDKGLEXT_INTERFACE_AGE (3)

GDKGLEXT_BINARY_AGE

#define GDKGLEXT_BINARY_AGE    (5)

GDKGLEXT_CHECK_VERSION()

#define     GDKGLEXT_CHECK_VERSION(major, minor, micro)

major :
minor :
micro :

gdkglext_major_version

extern const guint gdkglext_major_version;

gdkglext_minor_version

extern const guint gdkglext_minor_version;

gdkglext_micro_version

extern const guint gdkglext_micro_version;

gdkglext_interface_age

extern const guint gdkglext_interface_age;

gdkglext_binary_age

extern const guint gdkglext_binary_age;


OpenGL Window

OpenGL Window — OpenGL window which is located on-screen

Synopsis

#include <gdk/gdkgl.h>

struct      GdkGLWindow;
GdkGLWindow* gdk_gl_window_new              (GdkGLConfig *glconfig,
                                             GdkWindow *window,
                                             const int *attrib_list);
void        gdk_gl_window_destroy           (GdkGLWindow *glwindow);
GdkWindow*  gdk_gl_window_get_window        (GdkGLWindow *glwindow);
GdkGLWindow* gdk_window_set_gl_capability   (GdkWindow *window,
                                             GdkGLConfig *glconfig,
                                             const int *attrib_list);
void        gdk_window_unset_gl_capability  (GdkWindow *window);
gboolean    gdk_window_is_gl_capable        (GdkWindow *window);
GdkGLWindow* gdk_window_get_gl_window       (GdkWindow *window);
#define     gdk_window_get_gl_drawable      (window)

Object Hierarchy

  GObject
   +----GdkDrawable
         +----GdkGLWindow

Description

Details

struct GdkGLWindow

struct GdkGLWindow;

gdk_gl_window_new ()

GdkGLWindow* gdk_gl_window_new              (GdkGLConfig *glconfig,
                                             GdkWindow *window,
                                             const int *attrib_list);

Creates an on-screen rendering area. attrib_list is currently unused. This must be set to NULL or empty (first attribute of None). See GLX 1.3 spec.

glconfig : | a GdkGLConfig.
window : | the GdkWindow to be used as the rendering area.
attrib_list : | this must be set to NULL or empty (first attribute of None).
Returns : | the new GdkGLWindow.

gdk_gl_window_destroy ()

void        gdk_gl_window_destroy           (GdkGLWindow *glwindow);

Destroys the OpenGL resources associated with glwindow and decrements glwindow's reference count.

glwindow : a GdkGLWindow.

gdk_gl_window_get_window ()

GdkWindow*  gdk_gl_window_get_window        (GdkGLWindow *glwindow);

Returns the GdkWindow associated with glwindow.

Notice that GdkGLWindow is not GdkWindow, but another GdkDrawable which have an associated GdkWindow.

glwindow : | a GdkGLWindow.
Returns : | the GdkWindow associated with glwindow.

gdk_window_set_gl_capability ()

GdkGLWindow* gdk_window_set_gl_capability   (GdkWindow *window,
                                             GdkGLConfig *glconfig,
                                             const int *attrib_list);

Set the OpenGL-capability to the window. This function creates a new GdkGLWindow held by the window. attrib_list is currently unused. This must be set to NULL or empty (first attribute of None).

window : | the GdkWindow to be used as the rendering area.
glconfig : | a GdkGLConfig.
attrib_list : | this must be set to NULL or empty (first attribute of None).
Returns : | the GdkGLWindow used by the window if it is successful, NULL otherwise.

gdk_window_unset_gl_capability ()

void        gdk_window_unset_gl_capability  (GdkWindow *window);

Unset the OpenGL-capability of the window. This function destroys the GdkGLWindow held by the window.

window : a GdkWindow.

gdk_window_is_gl_capable ()

gboolean    gdk_window_is_gl_capable        (GdkWindow *window);

Returns whether the window is OpenGL-capable.

window : | a GdkWindow.
Returns : | TRUE if the window is OpenGL-capable, FALSE otherwise.

gdk_window_get_gl_window ()

GdkGLWindow* gdk_window_get_gl_window       (GdkWindow *window);

Returns the GdkGLWindow held by the window.

window : | a GdkWindow.
Returns : | the GdkGLWindow.

gdk_window_get_gl_drawable()

#define     gdk_window_get_gl_drawable(window)

Returns the GdkGLDrawable held by the window. In fact, this is macro that casts the result of gdk_window_get_gl_window to GdkGLDrawable.

window : | a GdkGLWindow.
Returns : | the GdkGLDrawable.


X Window System Interaction

X Window System Interaction — Internal X-related functions

Synopsis

#include <gdk/x11/gdkglx.h>

gboolean    gdk_x11_gl_query_glx_extension  (GdkGLConfig *glconfig,
                                             const char *extension);
GdkGLConfig* gdk_x11_gl_config_new_from_visualid
                                            (VisualID xvisualid);
GdkGLConfig* gdk_x11_gl_config_new_from_visualid_for_screen
                                            (GdkScreen *screen,
                                             VisualID xvisualid);
Display*    gdk_x11_gl_config_get_xdisplay  (GdkGLConfig *glconfig);
int         gdk_x11_gl_config_get_screen_number
                                            (GdkGLConfig *glconfig);
XVisualInfo* gdk_x11_gl_config_get_xvinfo   (GdkGLConfig *glconfig);
gboolean    gdk_x11_gl_config_is_mesa_glx   (GdkGLConfig *glconfig);
GdkGLContext* gdk_x11_gl_context_foreign_new
                                            (GdkGLConfig *glconfig,
                                             GdkGLContext *share_list,
                                             GLXContext glxcontext);
GLXContext  gdk_x11_gl_context_get_glxcontext
                                            (GdkGLContext *glcontext);
GLXPixmap   gdk_x11_gl_pixmap_get_glxpixmap (GdkGLPixmap *glpixmap);
Window      gdk_x11_gl_window_get_glxwindow (GdkGLWindow *glwindow);
#define     GDK_GL_CONFIG_XDISPLAY          (glconfig)
#define     GDK_GL_CONFIG_SCREEN_XNUMBER    (glconfig)
#define     GDK_GL_CONFIG_XVINFO            (glconfig)
#define     GDK_GL_CONFIG_XCOLORMAP         (glconfig)
#define     GDK_GL_CONTEXT_GLXCONTEXT       (glcontext)
#define     GDK_GL_PIXMAP_GLXPIXMAP         (glpixmap)
#define     GDK_GL_WINDOW_GLXWINDOW         (glwindow)

Description

Details

gdk_x11_gl_query_glx_extension ()

gboolean    gdk_x11_gl_query_glx_extension  (GdkGLConfig *glconfig,
                                             const char *extension);

Determines whether a given GLX extension is supported.

glconfig : | a GdkGLConfig.
extension : | name of GLX extension.
Returns : | TRUE if the GLX extension is supported, FALSE if not supported.

gdk_x11_gl_config_new_from_visualid ()

GdkGLConfig* gdk_x11_gl_config_new_from_visualid
                                            (VisualID xvisualid);

Creates GdkGLConfig from given visual ID that specifies the OpenGL-capable visual.

xvisualid : | visual ID.
Returns : | the new GdkGLConfig.

gdk_x11_gl_config_new_from_visualid_for_screen ()

GdkGLConfig* gdk_x11_gl_config_new_from_visualid_for_screen
                                            (GdkScreen *screen,
                                             VisualID xvisualid);

Creates GdkGLConfig from given visual ID that specifies the OpenGL-capable visual.

screen : | target screen.
xvisualid : | visual ID.
Returns : | the new GdkGLConfig.

gdk_x11_gl_config_get_xdisplay ()

Display*    gdk_x11_gl_config_get_xdisplay  (GdkGLConfig *glconfig);

Gets X Display.

glconfig : | a GdkGLConfig.
Returns : | pointer to the Display.

gdk_x11_gl_config_get_screen_number ()

int         gdk_x11_gl_config_get_screen_number
                                            (GdkGLConfig *glconfig);

Gets X screen number.

glconfig : | a GdkGLConfig.
Returns : | the screen number.

gdk_x11_gl_config_get_xvinfo ()

XVisualInfo* gdk_x11_gl_config_get_xvinfo   (GdkGLConfig *glconfig);

Gets XVisualInfo data.

glconfig : | a GdkGLConfig.
Returns : | pointer to the XVisualInfo data.

gdk_x11_gl_config_is_mesa_glx ()

gboolean    gdk_x11_gl_config_is_mesa_glx   (GdkGLConfig *glconfig);

Returns whether the server's GLX entension is Mesa.

glconfig : | a GdkGLConfig.
Returns : | TRUE if Mesa GLX, FALSE otherwise.

gdk_x11_gl_context_foreign_new ()

GdkGLContext* gdk_x11_gl_context_foreign_new
                                            (GdkGLConfig *glconfig,
                                             GdkGLContext *share_list,
                                             GLXContext glxcontext);

Creates GdkGLContext from existing GLXContext.

glconfig : | GdkGLConfig that represents the visual the GLXContext uses.
share_list : | the GdkGLContext which shares display lists with the GLXContext, or NULL.
glxcontext : | exsisting GLXContext.
Returns : | the newly-created GdkGLContext wrapper.

gdk_x11_gl_context_get_glxcontext ()

GLXContext  gdk_x11_gl_context_get_glxcontext
                                            (GdkGLContext *glcontext);

Gets GLXContext.

glcontext : | a GdkGLContext.
Returns : | the GLXContext.

gdk_x11_gl_pixmap_get_glxpixmap ()

GLXPixmap   gdk_x11_gl_pixmap_get_glxpixmap (GdkGLPixmap *glpixmap);

Gets GLXPixmap.

glpixmap : | a GdkGLPixmap.
Returns : | the GLXPixmap.

gdk_x11_gl_window_get_glxwindow ()

Window      gdk_x11_gl_window_get_glxwindow (GdkGLWindow *glwindow);

Gets X Window.

glwindow : | a GdkGLWindow.
Returns : | the Window.

GDK_GL_CONFIG_XDISPLAY()

#define     GDK_GL_CONFIG_XDISPLAY(glconfig)

Gets X Display.

glconfig : | a GdkGLConfig.
Returns : | pointer to the Display.

GDK_GL_CONFIG_SCREEN_XNUMBER()

#define     GDK_GL_CONFIG_SCREEN_XNUMBER(glconfig)

Gets X screen number.

glconfig : | a GdkGLConfig.
Returns : | the screen number.

GDK_GL_CONFIG_XVINFO()

#define     GDK_GL_CONFIG_XVINFO(glconfig)

Gets XVisualInfo data.

glconfig : | a GdkGLConfig.
Returns : | pointer to the XVisualInfo data.

GDK_GL_CONFIG_XCOLORMAP()

#define     GDK_GL_CONFIG_XCOLORMAP(glconfig)

Gets X Colormap.

glconfig : | a GdkGLConfig.
Returns : | the Colormap.

GDK_GL_CONTEXT_GLXCONTEXT()

#define     GDK_GL_CONTEXT_GLXCONTEXT(glcontext)

Gets GLXContext.

glcontext : | a GdkGLContext.
Returns : | the GLXContext.

GDK_GL_PIXMAP_GLXPIXMAP()

#define     GDK_GL_PIXMAP_GLXPIXMAP(glpixmap)

Gets GLXPixmap.

glpixmap : | a GdkGLPixmap.
Returns : | the GLXPixmap.

GDK_GL_WINDOW_GLXWINDOW()

#define     GDK_GL_WINDOW_GLXWINDOW(glwindow)

Gets X Window.

glwindow : | a GdkGLWindow.
Returns : | the Window.


Initialization

Initialization — Library initialization functions

Synopsis

#include <gtk/gtkgl.h>

void        gtk_gl_init                     (int *argc,
                                             char ***argv);
gboolean    gtk_gl_init_check               (int *argc,
                                             char ***argv);
gboolean    gtk_gl_parse_args               (int *argc,
                                             char ***argv);

Description

Details

gtk_gl_init ()

void        gtk_gl_init                     (int *argc,
                                             char ***argv);

Call this function before using any other GtkGLExt functions in your applications. It will initialize everything needed to operate the library and parses some standard command line options. argc and argv are adjusted accordingly so your own code will never see those standard arguments.

Note

This function will terminate your program if it was unable to initialize the library for some reason. If you want your program to fall back to a textual interface you want to call gtk_gl_init_check() instead.

argc : | Address of the argc parameter of your main() function. Changed if any arguments were handled.
argv : | Address of the argv parameter of main(). Any parameters understood by gtk_gl_init() are stripped before return.

gtk_gl_init_check ()

gboolean    gtk_gl_init_check               (int *argc,
                                             char ***argv);

This function does the same work as gtk_gl_init() with only a single change: It does not terminate the program if the library can't be initialized. Instead it returns FALSE on failure.

This way the application can fall back to some other means of communication with the user - for example a curses or command line interface.

argc : | Address of the argc parameter of your main() function. Changed if any arguments were handled.
argv : | Address of the argv parameter of main(). Any parameters understood by gtk_gl_init() are stripped before return.
Returns : | TRUE if the GUI has been successfully initialized, FALSE otherwise.

gtk_gl_parse_args ()

gboolean    gtk_gl_parse_args               (int *argc,
                                             char ***argv);

Parses command line arguments, and initializes global attributes of GtkGLExt.

Any arguments used by GtkGLExt are removed from the array and argc and argv are updated accordingly.

You shouldn't call this function explicitely if you are using gtk_gl_init(), or gtk_gl_init_check().

argc : | the number of command line arguments.
argv : | the array of command line arguments.
Returns : | TRUE if initialization succeeded, otherwise FALSE.


Version Information

Version Information — Variables and macros to check the GtkGLExt version

Synopsis

#include <gtk/gtkgl.h>

#define     GTKGLEXT_MAJOR_VERSION
#define     GTKGLEXT_MINOR_VERSION
#define     GTKGLEXT_MICRO_VERSION
#define     GTKGLEXT_INTERFACE_AGE
#define     GTKGLEXT_BINARY_AGE
#define     GTKGLEXT_CHECK_VERSION          (major, minor, micro)
extern      const guint gtkglext_major_version;
extern      const guint gtkglext_minor_version;
extern      const guint gtkglext_micro_version;
extern      const guint gtkglext_interface_age;
extern      const guint gtkglext_binary_age;

Description

Details

GTKGLEXT_MAJOR_VERSION

#define GTKGLEXT_MAJOR_VERSION (1)

GTKGLEXT_MINOR_VERSION

#define GTKGLEXT_MINOR_VERSION (0)

GTKGLEXT_MICRO_VERSION

#define GTKGLEXT_MICRO_VERSION (5)

GTKGLEXT_INTERFACE_AGE

#define GTKGLEXT_INTERFACE_AGE (3)

GTKGLEXT_BINARY_AGE

#define GTKGLEXT_BINARY_AGE    (5)

GTKGLEXT_CHECK_VERSION()

#define     GTKGLEXT_CHECK_VERSION(major, minor, micro)

major :
minor :
micro :

gtkglext_major_version

extern const guint gtkglext_major_version;

gtkglext_minor_version

extern const guint gtkglext_minor_version;

gtkglext_micro_version

extern const guint gtkglext_micro_version;

gtkglext_interface_age

extern const guint gtkglext_interface_age;

gtkglext_binary_age

extern const guint gtkglext_binary_age;

<< OpenGL-Capable Widget


OpenGL-Capable Widget

OpenGL-Capable Widget — OpenGL extension to GtkWidget API

Synopsis

#include <gtk/gtkgl.h>

gboolean    gtk_widget_set_gl_capability    (GtkWidget *widget,
                                             GdkGLConfig *glconfig,
                                             GdkGLContext *share_list,
                                             gboolean direct,
                                             int render_type);
gboolean    gtk_widget_is_gl_capable        (GtkWidget *widget);
GdkGLConfig* gtk_widget_get_gl_config       (GtkWidget *widget);
GdkGLContext* gtk_widget_create_gl_context  (GtkWidget *widget,
                                             GdkGLContext *share_list,
                                             gboolean direct,
                                             int render_type);
GdkGLContext* gtk_widget_get_gl_context     (GtkWidget *widget);
GdkGLWindow* gtk_widget_get_gl_window       (GtkWidget *widget);
#define     gtk_widget_get_gl_drawable      (widget)

Description

GtkGLExt is an extension to GTK which adds OpenGL capabilities to GtkWidget. Its use is quite simple: use gtk_widget_set_gl_capability to add OpenGL support to a widget, it will create a OpenGL drawable (GdkGLDrawable) for the widget, which can be obtained via gtk_widget_get_gl_drawable. OpenGL rendering context (GdkGLContext) can also be obtained via gtk_widget_get_gl_context. With GdkGLDrawable and GdkGLContext, gdk_gl_drawable_gl_begin and gdk_gl_drawable_gl_end can be called, and OpenGL function calls can be made between those two functions.

Details

gtk_widget_set_gl_capability ()

gboolean    gtk_widget_set_gl_capability    (GtkWidget *widget,
                                             GdkGLConfig *glconfig,
                                             GdkGLContext *share_list,
                                             gboolean direct,
                                             int render_type);

Set the OpenGL-capability to the widget. This function prepares the widget for its use with OpenGL.

widget : | the GtkWidget to be used as the rendering area.
glconfig : | a GdkGLConfig.
share_list : | the GdkGLContext with which to share display lists and texture objects. NULL indicates that no sharing is to take place.
direct : | whether rendering is to be done with a direct connection to the graphics system.
render_type : | GDK_GL_RGBA_TYPE or GDK_GL_COLOR_INDEX_TYPE (currently not used).
Returns : | TRUE if it is successful, FALSE otherwise.

gtk_widget_is_gl_capable ()

gboolean    gtk_widget_is_gl_capable        (GtkWidget *widget);

Returns whether the widget is OpenGL-capable.

widget : | a GtkWidget.
Returns : | TRUE if the widget is OpenGL-capable, FALSE otherwise.

gtk_widget_get_gl_config ()

GdkGLConfig* gtk_widget_get_gl_config       (GtkWidget *widget);

Returns the GdkGLConfig referred by the widget.

widget : | a GtkWidget.
Returns : | the GdkGLConfig.

gtk_widget_create_gl_context ()

GdkGLContext* gtk_widget_create_gl_context  (GtkWidget *widget,
                                             GdkGLContext *share_list,
                                             gboolean direct,
                                             int render_type);

Creates a new GdkGLContext with the appropriate GdkGLDrawable for this widget. The GL context must be freed when you're finished with it. See also gtk_widget_get_gl_context().

widget : | a GtkWidget.
share_list : | the GdkGLContext with which to share display lists and texture objects. NULL indicates that no sharing is to take place.
direct : | whether rendering is to be done with a direct connection to the graphics system.
render_type : | GDK_GL_RGBA_TYPE or GDK_GL_COLOR_INDEX_TYPE (currently not used).
Returns : | the new GdkGLContext.

gtk_widget_get_gl_context ()

GdkGLContext* gtk_widget_get_gl_context     (GtkWidget *widget);

Returns the GdkGLContext with the appropriate GdkGLDrawable for this widget. Unlike the GL context returned by gtk_widget_create_gl_context(), this context is owned by the widget.

GdkGLContext is needed for the function gdk_gl_drawable_begin, or for sharing display lists (see gtk_widget_set_gl_capability()).

widget : | a GtkWidget.
Returns : | the GdkGLContext.

gtk_widget_get_gl_window ()

GdkGLWindow* gtk_widget_get_gl_window       (GtkWidget *widget);

Returns the GdkGLWindow owned by the widget.

widget : | a GtkWidget.
Returns : | the GdkGLWindow.

gtk_widget_get_gl_drawable()

#define     gtk_widget_get_gl_drawable(widget)

Returns the GdkGLDrawable owned by the widget. In fact, this is macro that casts the result of gtk_widget_get_gl_window to GdkGLDrawable.

widget : | a GtkWidget.
Returns : | the GdkGLDrawable.


Running GtkGLExt Applications

Running GtkGLExt Applications — How to run and debug your GtkGLExt application

Running and debugging GtkGLExt Applications

Common command line options

All GtkGLExt applications support the following command line options. These are removed from argv by gtk_gl_init().

--gtk-gl-install-colormap. Install OpenGL window's colormap to the top-level window. If window manager doesn't watch the WM_COLORMAP_WINDOWS property on the top-level window, we have to set OpenGL window's colormap to the top-level window, especially in color index mode (color index mode uses own private colormap).

--gtk-gl-debug options. A list of debug options to turn on in addition to those specified in the GTK_GL_DEBUG environment variable. This option is only available if GtkGLExt has been configured with --enable-debug=yes.

--gtk-gl-no-debug options. A list of debug options to turn off. This option is only available if GtkGLExt has been configured with --enable-debug=yes.

The following options are really used by GdkGLExt library.

--gdk-gl-no-standard-colormap. This option disables GdkGLExt library to find a standard RGB colormap using XmuLookupStandardColormap(). If your application gets a BadColor X Window System error, try this option. On Solaris 2.4 and 2.5, they have a bug in XmuLookupStandardColormap() implementation. If your application gets a BadMatch X Window System error from XCreateWindow(), pass this option to avoid using broken XmuLookupStandardColormap(). Sun fixed this bug in Solaris 2.6.

--gdk-gl-force-indirect. Users can force GdkGLExt library to use indirect rendering context. If your application has a problem with hardware acceleration, try this option.

--gdk-gl-debug options. A list of debug options to turn on in addition to those specified in the GDK_GL_DEBUG environment variable. This option is only available if GtkGLExt has been configured with --enable-debug=yes.

--gdk-gl-no-debug options. A list of debug options to turn off. This option is only available if GtkGLExt has been configured with --enable-debug=yes.

Environment variables

GtkGLExt inspects the following environment variables.

GTK_GL_INSTALL_COLORMAP. If this variable is set to 1, GtkGLExt will try to install colormap to the top-level window. If window manager doesn't watch the WM_COLORMAP_WINDOWS property on the top-level window, we have to set OpenGL window's colormap to the top-level window.

GTK_GL_DEBUG. If GtkGLExt has been configured with --enable-debug=yes, this variable can be set to a list of debug options, which cause GtkGLExt library to print out different types of debugging information.

misc | Miscellaneous information
func | Show function call information

The special value all can be used to turn on all debug options.

GDK_GL_NO_STANDARD_COLORMAP. If this variable is set to 1, GdkGLExt library doesn't try to find a standard RGB colormap using XmuLookupStandardColormap(). If your application gets a BadColor X Window System error, try to set this environment variable. On Solaris 2.4 and 2.5, they have a bug in XmuLookupStandardColormap() implementation. If your application gets a BadMatch X Window System error from XCreateWindow(), set this environment variable to avoid using broken XmuLookupStandardColormap(). Sun fixed this bug in Solaris 2.6.

GDK_GL_FORCE_INDIRECT. If this variable is set to 1, GdkGLExt library uses indirect rendering context. If your application has a problem with hardware acceleration, try to set this environment variable.

GDK_GL_DEBUG. If GtkGLExt has been configured with --enable-debug=yes, this variable can be set to a list of debug options, which cause GdkGLExt library to print out different types of debugging information.

misc | Miscellaneous information
func | Show function call information
impl | Show window system specific (GLX, WGL) function call information

The special value all can be used to turn on all debug options.


Part I. GtkGLExt Overview

Prev Home GtkGLExt Reference Manual Next

GtkGLExt Overview

Table of Contents

Compiling the GtkGLExt libraries - How to compile GtkGLExt
Running GtkGLExt Applications - How to run and debug your GtkGLExt application


GladeXML

GladeXML — Allows dynamic loading of user interfaces from XML descriptions.

Synopsis

#include <glade/glade-xml.h>

            GladeXML;
            GladeXMLClass;
GladeXML*   glade_xml_new                   (const char *fname,
                                             const char *root,
                                             const char *domain);
GladeXML*   glade_xml_new_from_buffer       (const char *buffer,
                                             int size,
                                             const char *root,
                                             const char *domain);
gboolean    glade_xml_construct             (GladeXML *self,
                                             const char *fname,
                                             const char *root,
                                             const char *domain);

void        glade_xml_signal_connect        (GladeXML *self,
                                             const char *handlername,
                                             GCallback func);
void        glade_xml_signal_connect_data   (GladeXML *self,
                                             const char *handlername,
                                             GCallback func,
                                             gpointer user_data);
void        glade_xml_signal_autoconnect    (GladeXML *self);

GtkWidget*  glade_xml_get_widget            (GladeXML *self,
                                             const char *name);
GList*      glade_xml_get_widget_prefix     (GladeXML *self,
                                             const char *name);
const char* glade_get_widget_name           (GtkWidget *widget);
GladeXML*   glade_get_widget_tree           (GtkWidget *widget);

void        (*GladeXMLConnectFunc)          (const gchar *handler_name,
                                             GObject *object,
                                             const gchar *signal_name,
                                             const gchar *signal_data,
                                             GObject *connect_object,
                                             gboolean after,
                                             gpointer user_data);
void        glade_xml_signal_connect_full   (GladeXML *self,
                                             const gchar *handler_name,
                                             GladeXMLConnectFunc func,
                                             gpointer user_data);
void        glade_xml_signal_autoconnect_full
                                            (GladeXML *self,
                                             GladeXMLConnectFunc func,
                                             gpointer user_data);
GtkWidget*  (*GladeXMLCustomWidgetHandler)  (GladeXML *xml,
                                             gchar *func_name,
                                             gchar *name,
                                             gchar *string1,
                                             gchar *string2,
                                             gint int1,
                                             gint int2,
                                             gpointer user_data);
void        glade_set_custom_handler        (GladeXMLCustomWidgetHandler handler,
                                             gpointer user_data);

Object Hierarchy

  GObject
   +----GladeXML

Description

This object represents an `instantiation' of an XML interface description. When one of these objects is created, the XML file is read, and the interface is created. The GladeXML object then provides an interface for accessing the widgets in the interface by the names assigned to them inside the XML description.

The GladeXML object can also be used to connect handlers to the named signals in the description. Libglade also provides an interface by which it can look up the signal handler names in the program's symbol table and automatically connect as many handlers up as it can that way.

Details

GladeXML

typedef struct {
    GObject parent;

    char *filename;
} GladeXML;

GladeXMLClass

typedef struct {
    GObjectClass parent_class;

    /* Virtual function: gets the appropriate gtype for the typename.*/
    GType (* lookup_type) (GladeXML*self, const char *gtypename);
} GladeXMLClass;

glade_xml_new ()

GladeXML*   glade_xml_new                   (const char *fname,
                                             const char *root,
                                             const char *domain);

Creates a new GladeXML object (and the corresponding widgets) from the XML file fname. Optionally it will only build the interface from the widget node root (if it is not NULL). This feature is useful if you only want to build say a toolbar or menu from the XML file, but not the window it is embedded in. Note also that the XML parse tree is cached to speed up creating another GladeXML object for the same file

fname : | the XML file name.
root : | the widget node in fname to start building from (or NULL)
domain : | the translation domain for the XML file (or NULL for default)
Returns : | the newly created GladeXML object, or NULL on failure.

glade_xml_new_from_buffer ()

GladeXML*   glade_xml_new_from_buffer       (const char *buffer,
                                             int size,
                                             const char *root,
                                             const char *domain);

Creates a new GladeXML object (and the corresponding widgets) from the buffer buffer. Optionally it will only build the interface from the widget node root (if it is not NULL). This feature is useful if you only want to build say a toolbar or menu from the XML document, but not the window it is embedded in.

buffer : | the memory buffer containing the XML document.
size : | the size of the buffer.
root : | the widget node in buffer to start building from (or NULL)
domain : | the translation domain to use for this interface (or NULL)
Returns : | the newly created GladeXML object, or NULL on failure.

glade_xml_construct ()

gboolean    glade_xml_construct             (GladeXML *self,
                                             const char *fname,
                                             const char *root,
                                             const char *domain);

This routine can be used by bindings (such as gtk--) to help construct a GladeXML object, if it is needed.

self : | the GladeXML object
fname : | the XML filename
root : | the root widget node (or NULL for none)
domain : | the translation domain (or NULL for the default)
Returns : | TRUE if the construction succeeded.

glade_xml_signal_connect ()

void        glade_xml_signal_connect        (GladeXML *self,
                                             const char *handlername,
                                             GCallback func);

In the glade interface descriptions, signal handlers are specified for widgets by name. This function allows you to connect a C function to all signals in the GladeXML file with the given signal handler name.

self : | the GladeXML object
handlername : | the signal handler name
func : | the signal handler function

glade_xml_signal_connect_data ()

void        glade_xml_signal_connect_data   (GladeXML *self,
                                             const char *handlername,
                                             GCallback func,
                                             gpointer user_data);

In the glade interface descriptions, signal handlers are specified for widgets by name. This function allows you to connect a C function to all signals in the GladeXML file with the given signal handler name.

It differs from glade_xml_signal_connect since it allows you to specify the data parameter for the signal handler. It is also a small demonstration of how to use glade_xml_signal_connect_full.

self : | the GladeXML object
handlername : | the signal handler name
func : | the signal handler function
user_data : | the signal handler data

glade_xml_signal_autoconnect ()

void        glade_xml_signal_autoconnect    (GladeXML *self);

This function is a variation of glade_xml_signal_connect. It uses gmodule's introspective features (by openning the module NULL) to look at the application's symbol table. From here it tries to match the signal handler names given in the interface description with symbols in the application and connects the signals.

Note that this function will not work correctly if gmodule is not supported on the platform.

self : the GladeXML object.

glade_xml_get_widget ()

GtkWidget*  glade_xml_get_widget            (GladeXML *self,
                                             const char *name);

This function is used to get a pointer to the GtkWidget corresponding to name in the interface description. You would use this if you have to do anything to the widget after loading.

self : | the GladeXML object.
name : | the name of the widget.
Returns : | the widget matching name, or NULL if none exists.

glade_xml_get_widget_prefix ()

GList*      glade_xml_get_widget_prefix     (GladeXML *self,
                                             const char *name);

This function is used to get a list of pointers to the GtkWidget(s) with names that start with the string name in the interface description. You would use this if you have to do something to all of these widgets after loading.

self : | the GladeXML object.
name : | the name of the widget.
Returns : | A list of the widget that match name as the start of their name, or NULL if none exists.

glade_get_widget_name ()

const char* glade_get_widget_name           (GtkWidget *widget);

Used to get the name of a widget that was generated by a GladeXML object.

widget : | the widget
Returns : | the name of the widget.

glade_get_widget_tree ()

GladeXML*   glade_get_widget_tree           (GtkWidget *widget);

This function is used to get the GladeXML object that built this widget.

widget : | the widget
Returns : | the GladeXML object that built this widget.

GladeXMLConnectFunc ()

void        (*GladeXMLConnectFunc)          (const gchar *handler_name,
                                             GObject *object,
                                             const gchar *signal_name,
                                             const gchar *signal_data,
                                             GObject *connect_object,
                                             gboolean after,
                                             gpointer user_data);

This is the signature of a function used to connect signals. It is used by the glade_xml_signal_connect_full and glade_xml_signal_autoconnect_full functions. It is mainly intented for interpreted language bindings, but could be useful where the programmer wants more control over the signal connection process.

handler_name : | the name of the handler function to connect.
object : | the object to connect the signal to.
signal_name : | the name of the signal.
signal_data : | the string value of the signal data given in the XML file.
connect_object : | non NULL if g_signal_connect_object should be used.
after : | TRUE if the connection should be made with g_signal_connect_after.
user_data : | the user data argument.

glade_xml_signal_connect_full ()

void        glade_xml_signal_connect_full   (GladeXML *self,
                                             const gchar *handler_name,
                                             GladeXMLConnectFunc func,
                                             gpointer user_data);

This function is similar to glade_xml_signal_connect, except that it allows you to give an arbitrary function that will be used for actually connecting the signals. This is mainly useful for writers of interpreted language bindings, or applications where you need more control over the signal connection process.

self : | the GladeXML object.
handler_name : | the name of the signal handler that we want to connect.
func : | the function to use to connect the signals.
user_data : | arbitrary data to pass to the connect function.

glade_xml_signal_autoconnect_full ()

void        glade_xml_signal_autoconnect_full
                                            (GladeXML *self,
                                             GladeXMLConnectFunc func,
                                             gpointer user_data);

This function is similar to glade_xml_signal_connect_full, except that it will try to connect all signals in the interface, not just a single named handler. It can be thought of the interpeted language binding version of glade_xml_signal_autoconnect, except that it does not require gmodule to function correctly.

self : | the GladeXML object.
func : | the function used to connect the signals.
user_data : | arbitrary data that will be passed to the connection function.

GladeXMLCustomWidgetHandler ()

GtkWidget*  (*GladeXMLCustomWidgetHandler)  (GladeXML *xml,
                                             gchar *func_name,
                                             gchar *name,
                                             gchar *string1,
                                             gchar *string2,
                                             gint int1,
                                             gint int2,
                                             gpointer user_data);

This prototype is for a function that creates custom widgets.

xml : | the GladeXML object.
func_name : | the function name.
name : | the name of the widget to be created.
string1 : | the string1 property.
string2 : | the string2 property.
int1 : | the int1 property.
int2 : | the int2 property.
user_data : | the data passed to glade_set_custom_handler()
Returns : | the GtkWidget.

glade_set_custom_handler ()

void        glade_set_custom_handler        (GladeXMLCustomWidgetHandler handler,
                                             gpointer user_data);

Calling this function allows you to override the default behaviour when a Custom widget is found in an interface. This could be used by a language binding to call some other function, or to limit what functions can be called to create custom widgets.

handler : | the custom widget handler
user_data : | user data passed to the custom handler


Glade 2.0 File Format

Property Representations
Exceptions

Libglade 2.0 introduces a new file format for storing the user interface. Unlike the previous format, this one does not introduce a new element for each new property. This was done so that the format could be described with a fairly small DTD:

<!-- proposed DTD for new glade format -->

<!ELEMENT glade-interface (requires*, widget*) >
<!ATTLIST glade-interface
  xmlns CDATA #FIXED 'http://glade.gnome.org/glade-2.0.dtd' >

<!ELEMENT requires EMPTY >
<!ATTLIST requires
  lib CDATA #REQUIRED >

<!ELEMENT widget (property*, accessibility?, signal*, accelerator*, child*) >
<!ATTLIST widget
  class CDATA #REQUIRED
  id ID #REQUIRED >

<!ELEMENT property (#PCDATA) >
<!-- type is an optional tag, and should be the string name of the
     GType for the property -->
<!-- translatable specifies whether the property should be translated
     before use. -->
<!-- context indicates that the value has a |-separated
     context which must be stripped before use, look up g_strip_context()
     in the GLib API documentation for details.-->
<!ATTLIST property
  name CDATA #REQUIRED
  type CDATA #IMPLIED
  translatable (yes|no) 'no'
  context (yes|no) 'no'
  comments CDATA #IMPLIED
  agent CDATA #IMPLIED >

<!ELEMENT atkproperty (#PCDATA | accessibility)* >
<!ATTLIST atkproperty
  name CDATA #REQUIRED
  type CDATA #IMPLIED
  translatable (yes|no) 'no'
  context (yes|no) 'no'
  comments CDATA #IMPLIED >

<!ELEMENT atkrelation EMPTY >
<!ATTLIST atkrelation
  target CDATA #REQUIRED
  type CDATA #REQUIRED >

<!-- description is assumed to be a translatable string -->
<!ELEMENT atkaction EMPTY >
<!ATTLIST atkaction
  action_name CDATA #REQUIRED
  description CDATA #IMPLIED >

<!ELEMENT accessibility (atkrelation | atkaction | atkproperty)* >

<!ELEMENT signal (property*) >
<!ATTLIST signal
  name CDATA #REQUIRED
  handler CDATA #REQUIRED
  after (yes|no) 'no'
  object IDREF #IMPLIED
  last_modification_time CDATA #IMPLIED >

<!ELEMENT accelerator EMPTY >
<!ATTLIST accelerator
  key CDATA #REQUIRED
  modifiers CDATA #REQUIRED
  signal CDATA #REQUIRED >

<!ELEMENT child ((widget|placeholder), packing?) >
<!-- internal children should not have any properties set on them.
     (Internal children are things like the scrollbars in a
     GtkScrolledWindow, or the vbox in a GtkDialog). -->
<!ATTLIST child
  internal-child CDATA #IMPLIED >

<!ELEMENT packing (property+) >

<!ELEMENT placeholder EMPTY >

The <widget> elements contain <property> elements which define widget properties. In general these map to GObject properties.

The <signal> and <accelerator> elements are used to define signals and accelerators on the widget.

The <widget> element may also contain an <accessibility> element, which contains accessibility related properties. These set various ATK options (such as ATK properties, relations and actions).

For each child of the widget, there is an <child> element. The internal-child attribute is used to mark "internal children of the parent. These children are widgets that are created when the parent is constructed, such as the GtkVBox and GtkHButtonBox in a GtkDialog.

The <child> element contains either a <widget> element representing the child widget, or a <placeholder> element, which is ignored when building the interface. It may also contain a <packing> element, which contains <property> elements defining packing properties. These map to GtkContainer child packing properties.

Property Representations

Properties are represented as straight content data in the glade file. All programs working with glade files must represent the various types in the same way.


Exceptions

As some widgets do not implement properties for all required properties. This section documents some of the exceptions built into libglade's logic.

The following properties have custom handlers in libglade. Most of these will probably become real properties in GTK+ 2.2.

  • GtkWidget::visible is handled specially so that it gets applied after children have been added. This works around some sizing bugs in certain widgets (and is the same behaviour libglade-0.x had).

  • GtkWidget::tooltip implements tooltips for the widget. The property value is the tooltip to set on the widget.

  • GtkOptionMenu::history sets which menu item index in the list should be selected initially with gtk_option_menu_set_history().

  • GtkTextView::text offers an easy way to set the contents of a text view's buffer.

  • GtkCallendar::display_options sets display options of a calendar with gtk_calendar_display_options().

  • GtkRadioMenuItem::group sets the group for the radio item. The property value is the name of another widget in the group. This property won't handle forward references like the GtkRadioButton::group property.

  • GtkToolbar::tooltips sets whether the toolbar shows tooltips with gtk_toolbar_set_tooltips().

  • GtkStatusbar::has_resize_grip sets whether the status bar has a resize grip in the bottom corner with gtk_statusbar_set_has_resize_grip().

  • GtkRuler::metric sets the bounds and metric type for the ruler with gtk_ruler_set_metric().

  • GtkMenuItem::label, GtkMenuItem::use_underline and GtkMenuItem::use_stock are used to create a label inside a menu item, and set whether it has a mnemonic (underlined letter), and whether it should be a stock item (standardised, translated label and an icon, if it is a GtkImageMenuItem). These properties act similarly to the identically named GtkButton properties.

There are custom handlers for a number of deprecated widgets, and deprecated settings for some widgets. These most likely won't be converted to real properties in the future. These include:

GtkPixmap::build_insensitive
GtkPixmap::filename
GtkProgress::format
GtkCalendar::display_options
GtkCList::column_widths
GtkCList::selection_mode
GtkCList::shadow_type
GtkCList::show_titles
GtkTree::selection_mode
GtkTree::view_mode
GtkTree::view_line
GtkList::selection_mode
GtkCheckMenuItem::always_show_toggle
GtkText::text

XXXX - To be done


Embedding Libglade Interfaces

Sometimes you will only want to use libglade for a small part of your program. If it is just for some dialogs, this is easy -- you just generate the dialogs from the interface files when needed (note that libglade caches the XML parse tree between calls to glade_xml_new, so you will not suffer the performance hit of parsing a particular XML file more than once).

On the other hand, you may want to use libglade to generate just part of the UI, such as the menubar or a notebook or something. Libglade allows you to build only part of the interface if you want to. The second argument to glade_xml_new specifies the name of the base widget to build the interface from. This way we can limit the widgets that are constructed by libglade.

For the menubar example, we would create a dummy window in Glade, and insert a menubar widget into the window. We would then name the menubar in glade ("menubar" would be a good choice for the widget name ), and customise it as much as we want. Now in the program, we can use the following code:

GladeXML *xml;
GtkWidget *menubar;

xml = glade_xml_new("some-interface-file", "menubar", NULL);

glade_xml_signal_autoconnect(xml);

menubar = glade_xml_get_widget(xml, "menubar");
/* do whatever we want to with the menubar */

From here, we can do what ever we want with the menubar widget. The dummy window we created in Glade is never created, so does not affect the program. You can also use similar code to only build a single dialog from a glade file that contains many dialogs.

One thing to note -- if you don't want a widget to be displayed as soon as it is constructed with glade_xml_new, you should set the visible property on that widget to "no" in Glade. This is the correct solution to the problem (putting a hack into libglade so that it never shows the toplevel windows is not The Right Thing).


Extending Libglade

In some cases, libglade may not provide support for the widgets you want to use, or you may want to insert a bit of hand coded interface into the larger libglade generated interface. Libglade provides support for doing this.

If you are only need a few custom widgets (eg. a word processor may have a custom widget for the document editing area), the simplest choice is probably Glade's custom widget. It allows you to specify a custom function that will be used to create the widget. The signature of the function is as follows:

GtkWidget *custom_func(gchar *widget_name, gchar *string1, gchar *string2,
                       gint int1, gint int2);

When calling this function, widget_name is the name of the widget given in the XML file, and string1, string2, int1 and int2 are arbitrary constants whose values also come from the XML file. Libglade supports the custom widget using gmodule. For most cases, this is sufficient.

If you wish to get libglade to recognise a new widget type directly, your best option is to ensure that it implements properties for all settings required to construct the widget, and packing properties if the widget happens to be a container. If the widget satisifies this requirement, libglade will support the widget with no extra code (provided the widget's get_type() function has been called to register it with GLib).

If a widget has more complex requirements, a libglade module must be written (or if the library containing the widget already depends on libglade, it may build the module in). In the module, a widget construction routine and a build children routine must be registered. If the widget can be manipulated via properties for construction or adding children, glade_standard_build_widget or glade_standard_build_children can be used here.

If the widget mostly supports properties, custom handlers for particular properties can be registered with glade_register_custom_prop.

If the widget implements no properties (and you have no way to convince the author to do so), you will most likely need to implement custom handlers for construction and adding children.

For a more extensive example of registering new widget types and build functions, see glade/glade-gtk.c in the libglade package. For more information on the exact API's used to register new widget types with libglade, see the Libglade Build section of this manual.


Internationalisation with Libglade

Glade files mark properties for translation with the translatable property of the <property> element:

<widget class="GtkLabel" id="label1">
  <property name="label" translatable="yes">Foo</property>
  ...
</widget>

Libglade will translate marked properties using the translation domain specified in the glade_xml_new() (or the default domain if NULL).

Libglade also supports disambiguating properties by prefixing them with a |-separated context string, e.g. "Menu/Printer|Open" vs. "Menu/File|Open". You must tell Libglade that the property has a prefix by setting the context attribute of the <property> element to "yes". To learn more about this technique, read the chapter "How to use gettext in GUI programs" in the gettext manual, and see the GLib API documentation for g_strip_context().

To add the strings found in a glade file to your translation catalog template through the use of intltool. (XXXX - does this actually work yet?).


Part I. Libglade Library Reference

Prev Home Libglade Reference Manual Next

Libglade Library Reference

This section contains the API reference for libglade. All the public interfaces are documented here.


Libglade Build

Libglade Build — Routines used by widget building routines

Synopsis

#include <glade/glade.h>
#include <glade/glade-build.h>

GtkWidget*  (*GladeNewFunc)                 (GladeXML *xml,
                                             GType widget_type,
                                             GladeWidgetInfo *info);
void        (*GladeBuildChildrenFunc)       (GladeXML *xml,
                                             GtkWidget *parent,
                                             GladeWidgetInfo *info);
GtkWidget*  (*GladeFindInternalChildFunc)   (GladeXML *xml,
                                             GtkWidget *parent,
                                             const gchar *childname);
GtkWidget*  glade_xml_build_widget          (GladeXML *self,
                                             GladeWidgetInfo *info);
void        glade_xml_handle_internal_child (GladeXML *self,
                                             GtkWidget *parent,
                                             GladeChildInfo *child_info);
void        glade_xml_set_common_params     (GladeXML *self,
                                             GtkWidget *widget,
                                             GladeWidgetInfo *info);
void        glade_register_widget           (GType type,
                                             GladeNewFunc new_func,
                                             GladeBuildChildrenFunc build_children,
                                             GladeFindInternalChildFunc find_internal_child);

GtkWidget*  glade_standard_build_widget     (GladeXML *xml,
                                             GType widget_type,
                                             GladeWidgetInfo *info);
void        glade_xml_handle_widget_prop    (GladeXML *self,
                                             GtkWidget *widget,
                                             const gchar *prop_name,
                                             const gchar *value_name);
void        glade_standard_build_children   (GladeXML *self,
                                             GtkWidget *parent,
                                             GladeWidgetInfo *info);
void        glade_xml_set_packing_property  (GladeXML *self,
                                             GtkWidget *parent,
                                             GtkWidget *child,
                                             const char *name,
                                             const char *value);
void        (*GladeApplyCustomPropFunc)     (GladeXML *xml,
                                             GtkWidget *widget,
                                             const gchar *propname,
                                             const gchar *value);
void        glade_register_custom_prop      (GType type,
                                             const gchar *prop_name,
                                             GladeApplyCustomPropFunc apply_prop);

gchar*      glade_xml_relative_file         (GladeXML *self,
                                             const gchar *filename);
gint        glade_enum_from_string          (GType type,
                                             const char *string);
guint       glade_flags_from_string         (GType type,
                                             const char *string);
gboolean    glade_xml_set_value_from_string (GladeXML *xml,
                                             GParamSpec *pspec,
                                             const gchar *string,
                                             GValue *value);

void        glade_xml_set_toplevel          (GladeXML *xml,
                                             GtkWindow *window);
GtkAccelGroup* glade_xml_ensure_accel       (GladeXML *xml);

#define     GLADE_MODULE_CHECK_INIT

Description

These functions are used by the routines that are responsible for building the actual widgets from the XML node data structures.

Details

GladeNewFunc ()

GtkWidget*  (*GladeNewFunc)                 (GladeXML *xml,
                                             GType widget_type,
                                             GladeWidgetInfo *info);

This function signature should be used by functions that build particular widget types. The function should create the new widget and set any non standard widget parameters (ie. don't set visibility, size, etc), as this is handled by glade_xml_build_widget, which calls these functions.

xml : | The GladeXML object.
widget_type : | the GType code of the widget.
info : | the GladeWidgetInfo structure for this widget.
Returns : | the new widget.

GladeBuildChildrenFunc ()

void        (*GladeBuildChildrenFunc)       (GladeXML *xml,
                                             GtkWidget *parent,
                                             GladeWidgetInfo *info);

This function signature should be used by functions that are responsible for adding children to a container widget. To create each child widget, glade_xml_build_widget should be called.

xml : | the GladeXML object.
parent : | the parent.
info : | the GladeWidgetInfo structure for the parent.

GladeFindInternalChildFunc ()

GtkWidget*  (*GladeFindInternalChildFunc)   (GladeXML *xml,
                                             GtkWidget *parent,
                                             const gchar *childname);

When some composite widgets are created, a number of children are added at the same time (for example, the vbox in a GtkDialog). These widgets are identified in the XML interface file by the internal-child attribute on their &lt;child&gt; element.

When libglade encounters an internal child, rather than creating a new widget instance, libglade walks up the tree until it finds the first non internal-child parent. It then calls the find_internal_child callback for that parent's class.

That callback should return the internal child corresponding to the name passed in as the third argument.

xml : | the GladeXML object.
parent : | the parent widget.
childname : | the name of the internal child
Returns : | the named internal child.

glade_xml_build_widget ()

GtkWidget*  glade_xml_build_widget          (GladeXML *self,
                                             GladeWidgetInfo *info);

This function is not intended for people who just use libglade. Instead it is for people extending it (it is designed to be called in the child build routine defined for the parent widget). It first checks the type of the widget from the class tag, then calls the corresponding widget creation routine. This routine sets up all the settings specific to that type of widget. Then general widget settings are performed on the widget. Then it sets up accelerators for the widget, and extracts any signal information for the widget. Then it checks to see if there are any child widget nodes for this widget, and if so calls the widget's build routine, which will create the children with this function and add them to the widget in the appropriate way. Finally it returns the widget.

self : | the GladeXML object.
info : | the GladeWidgetInfo structure for the widget.
Returns : | the newly created widget.

glade_xml_handle_internal_child ()

void        glade_xml_handle_internal_child (GladeXML *self,
                                             GtkWidget *parent,
                                             GladeChildInfo *child_info);

This function is intended to be called by the build_children callback for container widgets. If the build_children callback encounters a child with the internal-child attribute set, then it should call this function to handle it and then continue on to the next child.

self : | the GladeXML object.
parent : | the parent widget.
child_info : | the GladeChildInfo structure for the child.

glade_xml_set_common_params ()

void        glade_xml_set_common_params     (GladeXML *self,
                                             GtkWidget *widget,
                                             GladeWidgetInfo *info);

This function sets the common parameters on a widget, and is responsible for inserting it into the GladeXML object's internal structures. It will also add the children to this widget. Usually this function is only called by glade_xml_build_widget, but is exposed for difficult cases, such as setting up toolbar buttons and the like.

self : | the GladeXML widget.
widget : | the widget to set parameters on.
info : | the GladeWidgetInfo structure for the widget.

glade_register_widget ()

void        glade_register_widget           (GType type,
                                             GladeNewFunc new_func,
                                             GladeBuildChildrenFunc build_children,
                                             GladeFindInternalChildFunc find_internal_child);

This function is used to register new construction functions for a widget type. The child building routine would call glade_xml_build_widget() on each child node to create the child before packing it.

This function is mainly useful for addon widget modules for libglade (it would get called from the glade_init_module() function).

type : | the GType of the widget.
new_func : | the function used to construct instances of the widget.
build_children : | function used to construct children (or NULL).
find_internal_child : | function to find internal children (or NULL).

glade_standard_build_widget ()

GtkWidget*  glade_standard_build_widget     (GladeXML *xml,
                                             GType widget_type,
                                             GladeWidgetInfo *info);

This is the standard widget building function. It processes all the widget properties using the standard object properties interfaces. This function will be sufficient for most widget types, thus reducing the ammount of work needed to wrap a library.

xml : | the GladeXML object.
widget_type : | the GType of the widget.
info : | the GladeWidgetInfo structure.
Returns : | the constructed widget.

glade_xml_handle_widget_prop ()

void        glade_xml_handle_widget_prop    (GladeXML *self,
                                             GtkWidget *widget,
                                             const gchar *prop_name,
                                             const gchar *value_name);

Some widgets have properties of type GtkWidget. These are represented as the widget name in the glade file. When constructing the interface, the widget specified as the value for a property may not exist yet.

Rather than setting the property directly, this function should be used. It will perform the name to GtkWidget conversion, and if the widget is yet to be constructed, defer setting the property until the widget is constructed.

self : | the GladeXML object
widget : | the property the widget to set the property on.
prop_name : | the name of the property.
value_name : | the name of the widget used as the value for the property.

glade_standard_build_children ()

void        glade_standard_build_children   (GladeXML *self,
                                             GtkWidget *parent,
                                             GladeWidgetInfo *info);

This is the standard child building function. It simply calls gtk_container_add on each child to add them to the parent, and process any packing properties using the generic container packing properties interfaces.

This function will be sufficient for most container widgets provided that they implement the GtkContainer child packing properties interfaces.

self : | the GladeXML object.
parent : | the container widget.
info : | the GladeWidgetInfo structure.

glade_xml_set_packing_property ()

void        glade_xml_set_packing_property  (GladeXML *self,
                                             GtkWidget *parent,
                                             GtkWidget *child,
                                             const char *name,
                                             const char *value);

This sets the packing property on container parent of widget child with name to value

self : | the GladeXML object.
parent : | the container widget.
child : | the contained child
name : | the name of the property
value : | it's stringified value

GladeApplyCustomPropFunc ()

void        (*GladeApplyCustomPropFunc)     (GladeXML *xml,
                                             GtkWidget *widget,
                                             const gchar *propname,
                                             const gchar *value);

This prototype is used for custom property handlers registered with glade_register_custom_prop().

xml : | the GladeXML object.
widget : | the widget to apply the property to.
propname : | the name of the property.
value : | the value of the property.

glade_register_custom_prop ()

void        glade_register_custom_prop      (GType type,
                                             const gchar *prop_name,
                                             GladeApplyCustomPropFunc apply_prop);

Some properties are not (yet) handled through the GObject property code, so can not be handled by the generic code. This function provides a way to register handlers for these properties. Such handlers will apply for the GType type and all its descendants.

type : | the GType of the widget.
prop_name : | the name for the custom widget.
apply_prop : | the function to be called when the custom property is found.

glade_xml_relative_file ()

gchar*      glade_xml_relative_file         (GladeXML *self,
                                             const gchar *filename);

This function resolves a relative pathname, using the directory of the XML file as a base. If the pathname is absolute, then the original filename is returned.

self : | the GladeXML object.
filename : | the filename.
Returns : | the filename. The result must be g_free'd.

glade_enum_from_string ()

gint        glade_enum_from_string          (GType type,
                                             const char *string);

This helper routine is designed to be used by widget build routines to convert the string representations of enumeration values found in the XML descriptions to the integer values that can be used to configure the widget.

type : | the GType for this enum type.
string : | the string representation of the enum value.
Returns : | the integer value for this enumeration, or 0 if it couldn't be found.

glade_flags_from_string ()

guint       glade_flags_from_string         (GType type,
                                             const char *string);

This helper routine is designed to be used by widget build routines to convert the string representations of flags values found in the XML descriptions to the integer values that can be used to configure the widget. The string is composed of string names or nicknames for various flags separated by '|'.

type : | the GType for this flags type.
string : | the string representation of the flags value.
Returns : | the integer value for this flags string

glade_xml_set_value_from_string ()

gboolean    glade_xml_set_value_from_string (GladeXML *xml,
                                             GParamSpec *pspec,
                                             const gchar *string,
                                             GValue *value);

This function demarshals a value from a string. This function calls g_value_init() on the value argument, so it need not be initialised beforehand.

This function can handle char, uchar, boolean, int, uint, long, ulong, enum, flags, float, double, string, GdkColor and GtkAdjustment type values. Support for GtkWidget type values is still to come.

xml : | the GladeXML object.
pspec : | the GParamSpec for the property
string : | the string representation of the value.
value : | the GValue to store the result in.
Returns : | TRUE on success.

glade_xml_set_toplevel ()

void        glade_xml_set_toplevel          (GladeXML *xml,
                                             GtkWindow *window);

This is used while the tree is being built to set the toplevel window that is currently being built. It is mainly used to enable GtkAccelGroup's to be bound to the correct window, but could have other uses.

xml : | the GladeXML object.
window : | the toplevel.

glade_xml_ensure_accel ()

GtkAccelGroup* glade_xml_ensure_accel       (GladeXML *xml);

This function is used to get the current GtkAccelGroup. If there isn't one, a new one is created and bound to the current toplevel window (if a toplevel has been set).

xml : | the GladeXML object.
Returns : | the current GtkAccelGroup.

GLADE_MODULE_CHECK_INIT

#define     GLADE_MODULE_CHECK_INIT

This macro will insert a suitable version check function into a libglade loadable module.

<< Libglade SAX Parser


Libglade Initialisation

Libglade Initialisation — Routines used to initialise libglade.

Synopsis

#include <glade/glade-init.h>

void        glade_init                      (void);
void        glade_require                   (const gchar *library);
void        glade_provide                   (const gchar *library);

Description

These routines are used to initialise libglade, and to load addon modules that recognise extra widget sets. The glade_init routine must be called before any libglade routines are used, and the glade_load_module routine would be used to load extra modules.

Details

glade_init ()

void        glade_init                      (void);

It used to be necessary to call glade_init() before creating GladeXML objects. This is now no longer the case, as libglade will be initialised on demand now. Calling glade_init() manually will not cause any problems though.

glade_require ()

void        glade_require                   (const gchar *library);

Ensure that a required library is available. If it is not already available, libglade will attempt to dynamically load a module that contains the handlers for that library.

library : the required library

glade_provide ()

void        glade_provide                   (const gchar *library);

This function should be called by a module to assert that it provides wrappers for a particular library. This should be called by the register_widgets() function of a libglade module so that it isn't loaded twice, for instance.

library : the provided library


Libglade SAX Parser

Libglade SAX Parser — Declarations and routines for accessing the SAX based parser.

Synopsis

#include <glade/glade-parser.h>

            GladeInterface;
            GladeWidgetInfo;
            GladeChildInfo;
            GladeProperty;
            GladeSignalInfo;
            GladeAccelInfo;
            GladeAtkActionInfo;
            GladeAtkRelationInfo;

GladeInterface* glade_parser_parse_file     (const gchar *file,
                                             const gchar *domain);
GladeInterface* glade_parser_parse_buffer   (const gchar *buffer,
                                             gint len,
                                             const gchar *domain);
void        glade_interface_destroy         (GladeInterface *interface);
void        glade_interface_dump            (GladeInterface *interface,
                                             const gchar *filename);

Description

The structures described here are the output of libglade's XML parser. These structures are really only useful for people who are extending libglade to handle other widget sets, but it could also be useful for other applications that need to read glade XML files.

If you only wish to use libglade, you don't need to worry about these functions and structures.

Details

GladeInterface

typedef struct {
    gchar **requires;
    guint n_requires;

    GladeWidgetInfo **toplevels;
    guint n_toplevels;

    GHashTable *names;

    GHashTable *strings;
} GladeInterface;

GladeWidgetInfo

typedef struct {
    GladeWidgetInfo *parent;

    gchar *classname;
    gchar *name;

    GladeProperty *properties;
    guint n_properties;

    GladeProperty *atk_props;
    guint n_atk_props;

    GladeSignalInfo *signals;
    guint n_signals;

    GladeAtkActionInfo *atk_actions;
    guint n_atk_actions;

    GladeAtkRelationInfo *relations;
    guint n_relations;

    GladeAccelInfo *accels;
    guint n_accels;

    GladeChildInfo *children;
    guint n_children;
} GladeWidgetInfo;

GladeChildInfo

typedef struct {
    GladeProperty *properties;
    guint n_properties;

    GladeWidgetInfo *child;
    gchar *internal_child;
} GladeChildInfo;

GladeProperty

typedef struct {
    gchar *name;
    gchar *value;
} GladeProperty;

GladeSignalInfo

typedef struct {
    gchar *name;
    gchar *handler;
    gchar *object; /* NULL if this isn't a connect_object signal */
    guint after : 1;
} GladeSignalInfo;

GladeAccelInfo

typedef struct {
    guint key;
    GdkModifierType modifiers;
    gchar *signal;
} GladeAccelInfo;

GladeAtkActionInfo

typedef struct {
    gchar *action_name;
    gchar *description;
} GladeAtkActionInfo;

GladeAtkRelationInfo

typedef struct {
    gchar *target;
    gchar *type;
} GladeAtkRelationInfo;

glade_parser_parse_file ()

GladeInterface* glade_parser_parse_file     (const gchar *file,
                                             const gchar *domain);

This function parses a Glade XML interface file to a GladeInterface object (which is libglade's internal representation of the interface data).

Generally, user code won't need to call this function. Instead, it should go through the GladeXML interfaces.

file : | the filename of the glade XML file.
domain : | the translation domain for the XML file.
Returns : | the GladeInterface structure for the XML file.

glade_parser_parse_buffer ()

GladeInterface* glade_parser_parse_buffer   (const gchar *buffer,
                                             gint len,
                                             const gchar *domain);

This function is similar to glade_parser_parse_file, except that it parses XML data from a buffer in memory. This could be used to embed an interface into the executable, for instance.

Generally, user code won't need to call this function. Instead, it should go through the GladeXML interfaces.

buffer : | a buffer in memory containing XML data.
len : | the length of buffer.
domain : | the translation domain for the XML file.
Returns : | the GladeInterface structure for the XML buffer.

glade_interface_destroy ()

void        glade_interface_destroy         (GladeInterface *interface);

Frees a GladeInterface structure.

interface : the GladeInterface structure.

glade_interface_dump ()

void        glade_interface_dump            (GladeInterface *interface,
                                             const gchar *filename);

This function dumps the contents of a GladeInterface into a file as XML. It is intended mainly as a debugging tool.

interface : | the GladeInterface
filename : | the filename to write the interface data to.


Libglade Modules

Libglade can be extended to support widget libraries built on top of GTK+. These modules are loaded dynamically at runtime. These modules are loaded when <requires> elements are found in the glade file.

Currently there are libglade module support for libbonoboui libgnomecanvas and libgnomeui. Note that libglade can also handle widgets that implement the properties interfaces with no extra code.

While no additional libglade initialisation is required to use a module, however, the underlying library might need initialisation. For instance, to use libgnomeui widgets from libglade, you must call gnome_program_init beforehand.


Libglade Programming Notes

Libglade Programming Basics
Libglade Modules
Internationalisation with Libglade
Extending Libglade
Embedding Libglade Interfaces

Libglade is an alternative to using Glade's code generation. Instead of generating code from the XML interface description, libglade loads and parses the description at runtime. It also provides functions that can be used to connect signal handlers to parts of the interface.

In this way, it allows you to separate your program code from the interface code. In fact, if you use the glade_xml_signal_autoconnect() function, the GUI code could be as simple as the test-libglade.c example that comes with libglade. Of course, you would also add your own signal handlers to the code. Note that the signals are connected the same way as if you had hand coded the interface. There is no extra overhead to user interfaces constructed by libglade (after the initial generating of course, and this is not much of an overhead) when compared to a hand crafted interface.

Libglade Programming Basics

Your basic libglade program will look something like this:

#include <gtk/gtk.h>
#include <glade/glade.h>

void some_signal_handler_func(GtkWidget *widget, gpointer user_data) {
  /* do something useful here */
}

int main(int argc, char *argv[]) {
    GladeXML *xml;

    gtk_init(&argc, &argv);

    /* load the interface */
    xml = glade_xml_new("filename.glade", NULL, NULL);

    /* connect the signals in the interface */
    glade_xml_signal_autoconnect(xml);

    /* start the event loop */
    gtk_main();

    return 0;
}

This will create the interface from the file filename.glade, then connect all the signals in the interface. The automatic signal connection is done by looking up function names in the global symbol table using gmodule. This means that the interface file can use standard GTK functions such as gtk_widget_show, or gtk_main_quit, or others in the interface and not have to write any code to connect the signals.

The some_signal_handler_func function is not referenced anywhere in the program explicitely, but if any signals are defined in the interface description that use "some_signal_handler_func" as the handler name, then this function will automatically be connected. Note that the function can not be static, since we require it to apear in the symbol table. Here is an example of the XML that would cause some_signal_handler_func to be connected:

<widget class="GtkWindow" id="MainWindow">
  <property name="visible">yes</property>
  <signal name="destroy" handler="some_signal_handler_func" />
  ...
</widget>

Note

If you wish to autoconnect handlers defined in the main executable (not a shared library), you will need to pass a linker flag to export the executable's symbols for dynamic linking. This flag is platform specific, but libtool can take care of this for you. Just add -export-dynamic argument to your link flags, and libtool will convert it to the correct format.

Many people did not see this problem on GNU/Linux with GTK+ 1.2, because the gtk-config script adds the correct flag on that platform. Such programs would sometimes break when run on alternative platforms.

To compile the program, we would use the following:

cc -o testprogram testprogram.c `pkg-config --cflags --libs libglade-2.0`

The pkg-config program is used to deduce the compiler and link flags necessary to compile various modules. If you are using automake or autoconf, you probably want to use the PKG_CHECK_MODULES macro. This can be used to check for the presence of a collection of a number of packages, and set some shell variables:

PKG_CHECK_MODULES(MYPROG, libglade-2.0 libgnomeui-2.0 >= 1.110.0)
AC_SUBST(MYPROG_CFLAGS)
AC_SUBST(MYPROG_LIBS)


Index

P

PangoAlignment, enum PangoAlignment
PangoAnalysis, PangoAnalysis
PangoAttrClass, PangoAttrClass
PangoAttrColor, PangoAttrColor
PangoAttrDataCopyFunc, PangoAttrDataCopyFunc ()
PangoAttrFilterFunc, PangoAttrFilterFunc ()
PangoAttrFloat, PangoAttrFloat
PangoAttrFontDesc, PangoAttrFontDesc
PangoAttribute, PangoAttribute
PangoAttrInt, PangoAttrInt
PangoAttrIterator, PangoAttrIterator
PangoAttrLanguage, PangoAttrLanguage
PangoAttrList, PangoAttrList
PangoAttrShape, PangoAttrShape
PangoAttrSize, PangoAttrSize
PangoAttrString, PangoAttrString
PangoAttrType, enum PangoAttrType
PangoCairoATSUIFont, PangoCairoATSUIFont
PangoCairoFontMap, PangoCairoFontMap
PangoColor, PangoColor
PangoContext, PangoContext
PangoCoverage, PangoCoverage
PangoCoverageLevel, enum PangoCoverageLevel
PangoDirection, enum PangoDirection
PangoEllipsizeMode, enum PangoEllipsizeMode
PangoEngine, PangoEngine
PangoEngineClass, PangoEngineClass
PangoEngineInfo, PangoEngineInfo
PangoEngineLang, PangoEngineLang
PangoEngineLangClass, PangoEngineLangClass
PangoEngineScriptInfo, PangoEngineScriptInfo
PangoEngineShape, PangoEngineShape
PangoEngineShapeClass, PangoEngineShapeClass
PangoFcDecoder, PangoFcDecoder
PangoFcDecoderClass, PangoFcDecoderClass
PangoFcDecoderFindFunc, PangoFcDecoderFindFunc ()
PangoFcFont, PangoFcFont
PangoFcFont:pattern, The "pattern" property
PangoFcFontClass, PangoFcFontClass
PangoFcFontMap, PangoFcFontMap
PangoFcFontMapClass, PangoFcFontMapClass
PangoFont, PangoFont
PangoFontDescription, PangoFontDescription
PangoFontFace, PangoFontFace
PangoFontFamily, PangoFontFamily
PangoFontMap, PangoFontMap
PangoFontMapClass, PangoFontMapClass
PangoFontMask, enum PangoFontMask
PangoFontMetrics, PangoFontMetrics
PangoFontset, PangoFontset
PangoFontsetClass, PangoFontsetClass
PangoFontsetForeachFunc, PangoFontsetForeachFunc ()
PangoFontsetSimple, PangoFontsetSimple
PangoFreeGCFunc, PangoFreeGCFunc ()
PangoFT2FontMap, PangoFT2FontMap
PangoFT2SubstituteFunc, PangoFT2SubstituteFunc ()
PangoGetGCFunc, PangoGetGCFunc ()
PangoGlyph, PangoGlyph
PangoGlyphGeometry, PangoGlyphGeometry
PangoGlyphInfo, PangoGlyphInfo
PangoGlyphItem, PangoGlyphItem
PangoGlyphString, PangoGlyphString
PangoGlyphUnit, PangoGlyphUnit
PangoGlyphVisAttr, PangoGlyphVisAttr
PangoGravity, enum PangoGravity
PangoGravityHint, enum PangoGravityHint
PangoIncludedModule, PangoIncludedModule
PangoItem, PangoItem
PangoLanguage, PangoLanguage
PangoLayout, PangoLayout
PangoLayoutIter, PangoLayoutIter
PangoLayoutLine, PangoLayoutLine
PangoLayoutRun, PangoLayoutRun
PangoLogAttr, PangoLogAttr
PangoMap, PangoMap
PangoMapEntry, PangoMapEntry
PangoMatrix, PangoMatrix
PangoOTBuffer, PangoOTBuffer
PangoOTGlyph, PangoOTGlyph
PangoOTInfo, PangoOTInfo
PangoOTRuleset, PangoOTRuleset
PangoOTTableType, enum PangoOTTableType
PangoOTTag, PangoOTTag
PangoRectangle, PangoRectangle
PangoRenderer, PangoRenderer
PangoRendererClass, PangoRendererClass
PangoRenderPart, enum PangoRenderPart
PangoScript, enum PangoScript
PangoScriptIter, PangoScriptIter
PangoStretch, enum PangoStretch
PangoStyle, enum PangoStyle
PangoTabAlign, enum PangoTabAlign
PangoTabArray, PangoTabArray
PangoUnderline, enum PangoUnderline
PangoVariant, enum PangoVariant
PangoWeight, enum PangoWeight
PangoWin32FontCache, PangoWin32FontCache
PangoWrapMode, enum PangoWrapMode
PangoXFontCache, PangoXFontCache
PangoXftFont, PangoXftFont
PangoXftFontMap, PangoXftFontMap
PangoXftRenderer, PangoXftRenderer
PangoXftRendererClass, PangoXftRendererClass
PangoXftSubstituteFunc, PangoXftSubstituteFunc ()
PangoXSubfont, PangoXSubfont
PANGO_ANALYSIS_FLAG_CENTERED_BASELINE, PANGO_ANALYSIS_FLAG_CENTERED_BASELINE
PANGO_ASCENT, PANGO_ASCENT()
pango_attribute_copy, pango_attribute_copy ()
pango_attribute_destroy, pango_attribute_destroy ()
pango_attribute_equal, pango_attribute_equal ()
pango_attr_background_new, pango_attr_background_new ()
pango_attr_fallback_new, pango_attr_fallback_new ()
pango_attr_family_new, pango_attr_family_new ()
pango_attr_font_desc_new, pango_attr_font_desc_new ()
pango_attr_foreground_new, pango_attr_foreground_new ()
pango_attr_gravity_hint_new, pango_attr_gravity_hint_new ()
pango_attr_gravity_new, pango_attr_gravity_new ()
pango_attr_iterator_copy, pango_attr_iterator_copy ()
pango_attr_iterator_destroy, pango_attr_iterator_destroy ()
pango_attr_iterator_get, pango_attr_iterator_get ()
pango_attr_iterator_get_attrs, pango_attr_iterator_get_attrs ()
pango_attr_iterator_get_font, pango_attr_iterator_get_font ()
pango_attr_iterator_next, pango_attr_iterator_next ()
pango_attr_iterator_range, pango_attr_iterator_range ()
pango_attr_language_new, pango_attr_language_new ()
pango_attr_letter_spacing_new, pango_attr_letter_spacing_new ()
pango_attr_list_change, pango_attr_list_change ()
pango_attr_list_copy, pango_attr_list_copy ()
pango_attr_list_filter, pango_attr_list_filter ()
pango_attr_list_get_iterator, pango_attr_list_get_iterator ()
pango_attr_list_insert, pango_attr_list_insert ()
pango_attr_list_insert_before, pango_attr_list_insert_before ()
pango_attr_list_new, pango_attr_list_new ()
pango_attr_list_ref, pango_attr_list_ref ()
pango_attr_list_splice, pango_attr_list_splice ()
pango_attr_list_unref, pango_attr_list_unref ()
pango_attr_rise_new, pango_attr_rise_new ()
pango_attr_scale_new, pango_attr_scale_new ()
pango_attr_shape_new, pango_attr_shape_new ()
pango_attr_shape_new_with_data, pango_attr_shape_new_with_data ()
pango_attr_size_new, pango_attr_size_new ()
pango_attr_size_new_absolute, pango_attr_size_new_absolute ()
pango_attr_stretch_new, pango_attr_stretch_new ()
pango_attr_strikethrough_color_new, pango_attr_strikethrough_color_new ()
pango_attr_strikethrough_new, pango_attr_strikethrough_new ()
pango_attr_style_new, pango_attr_style_new ()
pango_attr_type_register, pango_attr_type_register ()
pango_attr_underline_color_new, pango_attr_underline_color_new ()
pango_attr_underline_new, pango_attr_underline_new ()
pango_attr_variant_new, pango_attr_variant_new ()
pango_attr_weight_new, pango_attr_weight_new ()
pango_break, pango_break ()
pango_cairo_atsui_font_get_atsu_font_id, pango_cairo_atsui_font_get_atsu_font_id ()
pango_cairo_context_get_font_options, pango_cairo_context_get_font_options ()
pango_cairo_context_get_resolution, pango_cairo_context_get_resolution ()
pango_cairo_context_set_font_options, pango_cairo_context_set_font_options ()
pango_cairo_context_set_resolution, pango_cairo_context_set_resolution ()
pango_cairo_create_layout, pango_cairo_create_layout ()
pango_cairo_error_underline_path, pango_cairo_error_underline_path ()
pango_cairo_font_map_create_context, pango_cairo_font_map_create_context ()
pango_cairo_font_map_get_default, pango_cairo_font_map_get_default ()
pango_cairo_font_map_get_resolution, pango_cairo_font_map_get_resolution ()
pango_cairo_font_map_new, pango_cairo_font_map_new ()
pango_cairo_font_map_set_resolution, pango_cairo_font_map_set_resolution ()
pango_cairo_glyph_string_path, pango_cairo_glyph_string_path ()
pango_cairo_layout_line_path, pango_cairo_layout_line_path ()
pango_cairo_layout_path, pango_cairo_layout_path ()
pango_cairo_show_error_underline, pango_cairo_show_error_underline ()
pango_cairo_show_glyph_string, pango_cairo_show_glyph_string ()
pango_cairo_show_layout, pango_cairo_show_layout ()
pango_cairo_show_layout_line, pango_cairo_show_layout_line ()
pango_cairo_update_context, pango_cairo_update_context ()
pango_cairo_update_layout, pango_cairo_update_layout ()
pango_color_copy, pango_color_copy ()
pango_color_free, pango_color_free ()
pango_color_parse, pango_color_parse ()
pango_color_to_string, pango_color_to_string ()
pango_config_key_get, pango_config_key_get ()
pango_context_get_base_dir, pango_context_get_base_dir ()
pango_context_get_base_gravity, pango_context_get_base_gravity ()
pango_context_get_font_description, pango_context_get_font_description ()
pango_context_get_font_map, pango_context_get_font_map ()
pango_context_get_gravity, pango_context_get_gravity ()
pango_context_get_gravity_hint, pango_context_get_gravity_hint ()
pango_context_get_language, pango_context_get_language ()
pango_context_get_matrix, pango_context_get_matrix ()
pango_context_get_metrics, pango_context_get_metrics ()
pango_context_list_families, pango_context_list_families ()
pango_context_load_font, pango_context_load_font ()
pango_context_load_fontset, pango_context_load_fontset ()
pango_context_new, pango_context_new ()
pango_context_set_base_dir, pango_context_set_base_dir ()
pango_context_set_base_gravity, pango_context_set_base_gravity ()
pango_context_set_font_description, pango_context_set_font_description ()
pango_context_set_font_map, pango_context_set_font_map ()
pango_context_set_gravity_hint, pango_context_set_gravity_hint ()
pango_context_set_language, pango_context_set_language ()
pango_context_set_matrix, pango_context_set_matrix ()
pango_coverage_copy, pango_coverage_copy ()
pango_coverage_from_bytes, pango_coverage_from_bytes ()
pango_coverage_get, pango_coverage_get ()
pango_coverage_max, pango_coverage_max ()
pango_coverage_new, pango_coverage_new ()
pango_coverage_ref, pango_coverage_ref ()
pango_coverage_set, pango_coverage_set ()
pango_coverage_to_bytes, pango_coverage_to_bytes ()
pango_coverage_unref, pango_coverage_unref ()
pango_default_break, pango_default_break ()
PANGO_DESCENT, PANGO_DESCENT()
PANGO_ENGINE_LANG_DEFINE_TYPE, PANGO_ENGINE_LANG_DEFINE_TYPE()
PANGO_ENGINE_SHAPE_DEFINE_TYPE, PANGO_ENGINE_SHAPE_DEFINE_TYPE()
PANGO_ENGINE_TYPE_LANG, PANGO_ENGINE_TYPE_LANG
PANGO_ENGINE_TYPE_SHAPE, PANGO_ENGINE_TYPE_SHAPE
pango_extents_to_pixels, pango_extents_to_pixels ()
pango_fc_decoder_get_charset, pango_fc_decoder_get_charset ()
pango_fc_decoder_get_glyph, pango_fc_decoder_get_glyph ()
pango_fc_font_description_from_pattern, pango_fc_font_description_from_pattern ()
pango_fc_font_get_glyph, pango_fc_font_get_glyph ()
pango_fc_font_get_unknown_glyph, pango_fc_font_get_unknown_glyph ()
pango_fc_font_has_char, pango_fc_font_has_char ()
pango_fc_font_kern_glyphs, pango_fc_font_kern_glyphs ()
pango_fc_font_lock_face, pango_fc_font_lock_face ()
pango_fc_font_map_add_decoder_find_func, pango_fc_font_map_add_decoder_find_func ()
pango_fc_font_map_cache_clear, pango_fc_font_map_cache_clear ()
pango_fc_font_map_create_context, pango_fc_font_map_create_context ()
pango_fc_font_map_shutdown, pango_fc_font_map_shutdown ()
pango_fc_font_unlock_face, pango_fc_font_unlock_face ()
pango_find_base_dir, pango_find_base_dir ()
pango_find_map, pango_find_map ()
pango_find_paragraph_boundary, pango_find_paragraph_boundary ()
PANGO_FONT, PANGO_FONT()
pango_fontset_foreach, pango_fontset_foreach ()
pango_fontset_get_font, pango_fontset_get_font ()
pango_fontset_get_metrics, pango_fontset_get_metrics ()
pango_fontset_simple_append, pango_fontset_simple_append ()
pango_fontset_simple_new, pango_fontset_simple_new ()
pango_fontset_simple_size, pango_fontset_simple_size ()
pango_font_describe, pango_font_describe ()
pango_font_describe_with_absolute_size, pango_font_describe_with_absolute_size ()
pango_font_descriptions_free, pango_font_descriptions_free ()
pango_font_description_better_match, pango_font_description_better_match ()
pango_font_description_copy, pango_font_description_copy ()
pango_font_description_copy_static, pango_font_description_copy_static ()
pango_font_description_equal, pango_font_description_equal ()
pango_font_description_free, pango_font_description_free ()
pango_font_description_from_string, pango_font_description_from_string ()
pango_font_description_get_family, pango_font_description_get_family ()
pango_font_description_get_gravity, pango_font_description_get_gravity ()
pango_font_description_get_set_fields, pango_font_description_get_set_fields ()
pango_font_description_get_size, pango_font_description_get_size ()
pango_font_description_get_size_is_absolute, pango_font_description_get_size_is_absolute ()
pango_font_description_get_stretch, pango_font_description_get_stretch ()
pango_font_description_get_style, pango_font_description_get_style ()
pango_font_description_get_variant, pango_font_description_get_variant ()
pango_font_description_get_weight, pango_font_description_get_weight ()
pango_font_description_hash, pango_font_description_hash ()
pango_font_description_merge, pango_font_description_merge ()
pango_font_description_merge_static, pango_font_description_merge_static ()
pango_font_description_new, pango_font_description_new ()
pango_font_description_set_absolute_size, pango_font_description_set_absolute_size ()
pango_font_description_set_family, pango_font_description_set_family ()
pango_font_description_set_family_static, pango_font_description_set_family_static ()
pango_font_description_set_gravity, pango_font_description_set_gravity ()
pango_font_description_set_size, pango_font_description_set_size ()
pango_font_description_set_stretch, pango_font_description_set_stretch ()
pango_font_description_set_style, pango_font_description_set_style ()
pango_font_description_set_variant, pango_font_description_set_variant ()
pango_font_description_set_weight, pango_font_description_set_weight ()
pango_font_description_to_filename, pango_font_description_to_filename ()
pango_font_description_to_string, pango_font_description_to_string ()
pango_font_description_unset_fields, pango_font_description_unset_fields ()
PANGO_FONT_FACE, PANGO_FONT_FACE()
pango_font_face_describe, pango_font_face_describe ()
pango_font_face_get_face_name, pango_font_face_get_face_name ()
pango_font_face_list_sizes, pango_font_face_list_sizes ()
PANGO_FONT_FAMILY, PANGO_FONT_FAMILY()
pango_font_family_get_name, pango_font_family_get_name ()
pango_font_family_is_monospace, pango_font_family_is_monospace ()
pango_font_family_list_faces, pango_font_family_list_faces ()
pango_font_find_shaper, pango_font_find_shaper ()
pango_font_get_coverage, pango_font_get_coverage ()
pango_font_get_font_map, pango_font_get_font_map ()
pango_font_get_glyph_extents, pango_font_get_glyph_extents ()
pango_font_get_metrics, pango_font_get_metrics ()
PANGO_FONT_MAP, PANGO_FONT_MAP()
PANGO_FONT_MAP_CLASS, PANGO_FONT_MAP_CLASS()
PANGO_FONT_MAP_GET_CLASS, PANGO_FONT_MAP_GET_CLASS()
pango_font_map_get_shape_engine_type, pango_font_map_get_shape_engine_type ()
pango_font_map_list_families, pango_font_map_list_families ()
pango_font_map_load_font, pango_font_map_load_font ()
pango_font_map_load_fontset, pango_font_map_load_fontset ()
pango_font_metrics_get_approximate_char_width, pango_font_metrics_get_approximate_char_width ()
pango_font_metrics_get_approximate_digit_width, pango_font_metrics_get_approximate_digit_width ()
pango_font_metrics_get_ascent, pango_font_metrics_get_ascent ()
pango_font_metrics_get_descent, pango_font_metrics_get_descent ()
pango_font_metrics_get_strikethrough_position, pango_font_metrics_get_strikethrough_position ()
pango_font_metrics_get_strikethrough_thickness, pango_font_metrics_get_strikethrough_thickness ()
pango_font_metrics_get_underline_position, pango_font_metrics_get_underline_position ()
pango_font_metrics_get_underline_thickness, pango_font_metrics_get_underline_thickness ()
pango_font_metrics_ref, pango_font_metrics_ref ()
pango_font_metrics_unref, pango_font_metrics_unref ()
pango_ft2_font_get_coverage, pango_ft2_font_get_coverage ()
pango_ft2_font_get_face, pango_ft2_font_get_face ()
pango_ft2_font_get_kerning, pango_ft2_font_get_kerning ()
pango_ft2_font_map_create_context, pango_ft2_font_map_create_context ()
pango_ft2_font_map_for_display, pango_ft2_font_map_for_display ()
pango_ft2_font_map_new, pango_ft2_font_map_new ()
pango_ft2_font_map_set_default_substitute, pango_ft2_font_map_set_default_substitute ()
pango_ft2_font_map_set_resolution, pango_ft2_font_map_set_resolution ()
pango_ft2_font_map_substitute_changed, pango_ft2_font_map_substitute_changed ()
pango_ft2_get_context, pango_ft2_get_context ()
pango_ft2_get_unknown_glyph, pango_ft2_get_unknown_glyph ()
pango_ft2_render, pango_ft2_render ()
pango_ft2_render_layout, pango_ft2_render_layout ()
pango_ft2_render_layout_line, pango_ft2_render_layout_line ()
pango_ft2_render_layout_line_subpixel, pango_ft2_render_layout_line_subpixel ()
pango_ft2_render_layout_subpixel, pango_ft2_render_layout_subpixel ()
pango_ft2_render_transformed, pango_ft2_render_transformed ()
pango_ft2_shutdown_display, pango_ft2_shutdown_display ()
pango_get_lib_subdirectory, pango_get_lib_subdirectory ()
pango_get_log_attrs, pango_get_log_attrs ()
pango_get_mirror_char, pango_get_mirror_char ()
pango_get_sysconf_subdirectory, pango_get_sysconf_subdirectory ()
PANGO_GET_UNKNOWN_GLYPH, PANGO_GET_UNKNOWN_GLYPH()
PANGO_GLYPH_EMPTY, PANGO_GLYPH_EMPTY
pango_glyph_item_apply_attrs, pango_glyph_item_apply_attrs ()
pango_glyph_item_free, pango_glyph_item_free ()
pango_glyph_item_letter_space, pango_glyph_item_letter_space ()
pango_glyph_item_split, pango_glyph_item_split ()
pango_glyph_string_copy, pango_glyph_string_copy ()
pango_glyph_string_extents, pango_glyph_string_extents ()
pango_glyph_string_extents_range, pango_glyph_string_extents_range ()
pango_glyph_string_free, pango_glyph_string_free ()
pango_glyph_string_get_logical_widths, pango_glyph_string_get_logical_widths ()
pango_glyph_string_get_width, pango_glyph_string_get_width ()
pango_glyph_string_index_to_x, pango_glyph_string_index_to_x ()
pango_glyph_string_new, pango_glyph_string_new ()
pango_glyph_string_set_size, pango_glyph_string_set_size ()
pango_glyph_string_x_to_index, pango_glyph_string_x_to_index ()
PANGO_GLYPH_UNKNOWN_FLAG, PANGO_GLYPH_UNKNOWN_FLAG
pango_gravity_get_for_matrix, pango_gravity_get_for_matrix ()
pango_gravity_get_for_script, pango_gravity_get_for_script ()
PANGO_GRAVITY_IS_VERTICAL, PANGO_GRAVITY_IS_VERTICAL()
pango_gravity_to_rotation, pango_gravity_to_rotation ()
PANGO_IS_FONT, PANGO_IS_FONT()
PANGO_IS_FONT_FACE, PANGO_IS_FONT_FACE()
PANGO_IS_FONT_FAMILY, PANGO_IS_FONT_FAMILY()
PANGO_IS_FONT_MAP, PANGO_IS_FONT_MAP()
PANGO_IS_FONT_MAP_CLASS, PANGO_IS_FONT_MAP_CLASS()
pango_is_zero_width, pango_is_zero_width ()
pango_itemize, pango_itemize ()
pango_itemize_with_base_dir, pango_itemize_with_base_dir ()
pango_item_copy, pango_item_copy ()
pango_item_free, pango_item_free ()
pango_item_new, pango_item_new ()
pango_item_split, pango_item_split ()
pango_language_from_string, pango_language_from_string ()
pango_language_get_default, pango_language_get_default ()
pango_language_get_sample_string, pango_language_get_sample_string ()
pango_language_includes_script, pango_language_includes_script ()
pango_language_matches, pango_language_matches ()
pango_language_to_string, pango_language_to_string()
pango_layout_context_changed, pango_layout_context_changed ()
pango_layout_copy, pango_layout_copy ()
pango_layout_get_alignment, pango_layout_get_alignment ()
pango_layout_get_attributes, pango_layout_get_attributes ()
pango_layout_get_auto_dir, pango_layout_get_auto_dir ()
pango_layout_get_context, pango_layout_get_context ()
pango_layout_get_cursor_pos, pango_layout_get_cursor_pos ()
pango_layout_get_ellipsize, pango_layout_get_ellipsize ()
pango_layout_get_extents, pango_layout_get_extents ()
pango_layout_get_font_description, pango_layout_get_font_description ()
pango_layout_get_indent, pango_layout_get_indent ()
pango_layout_get_iter, pango_layout_get_iter ()
pango_layout_get_justify, pango_layout_get_justify ()
pango_layout_get_line, pango_layout_get_line ()
pango_layout_get_lines, pango_layout_get_lines ()
pango_layout_get_lines_readonly, pango_layout_get_lines_readonly ()
pango_layout_get_line_count, pango_layout_get_line_count ()
pango_layout_get_line_readonly, pango_layout_get_line_readonly ()
pango_layout_get_log_attrs, pango_layout_get_log_attrs ()
pango_layout_get_pixel_extents, pango_layout_get_pixel_extents ()
pango_layout_get_pixel_size, pango_layout_get_pixel_size ()
pango_layout_get_single_paragraph_mode, pango_layout_get_single_paragraph_mode ()
pango_layout_get_size, pango_layout_get_size ()
pango_layout_get_spacing, pango_layout_get_spacing ()
pango_layout_get_tabs, pango_layout_get_tabs ()
pango_layout_get_text, pango_layout_get_text ()
pango_layout_get_unknown_glyphs_count, pango_layout_get_unknown_glyphs_count ()
pango_layout_get_width, pango_layout_get_width ()
pango_layout_get_wrap, pango_layout_get_wrap ()
pango_layout_index_to_line_x, pango_layout_index_to_line_x ()
pango_layout_index_to_pos, pango_layout_index_to_pos ()
pango_layout_is_ellipsized, pango_layout_is_ellipsized ()
pango_layout_is_wrapped, pango_layout_is_wrapped ()
pango_layout_iter_at_last_line, pango_layout_iter_at_last_line ()
pango_layout_iter_free, pango_layout_iter_free ()
pango_layout_iter_get_baseline, pango_layout_iter_get_baseline ()
pango_layout_iter_get_char_extents, pango_layout_iter_get_char_extents ()
pango_layout_iter_get_cluster_extents, pango_layout_iter_get_cluster_extents ()
pango_layout_iter_get_index, pango_layout_iter_get_index ()
pango_layout_iter_get_layout_extents, pango_layout_iter_get_layout_extents ()
pango_layout_iter_get_line, pango_layout_iter_get_line ()
pango_layout_iter_get_line_extents, pango_layout_iter_get_line_extents ()
pango_layout_iter_get_line_readonly, pango_layout_iter_get_line_readonly ()
pango_layout_iter_get_line_yrange, pango_layout_iter_get_line_yrange ()
pango_layout_iter_get_run, pango_layout_iter_get_run ()
pango_layout_iter_get_run_extents, pango_layout_iter_get_run_extents ()
pango_layout_iter_get_run_readonly, pango_layout_iter_get_run_readonly ()
pango_layout_iter_next_char, pango_layout_iter_next_char ()
pango_layout_iter_next_cluster, pango_layout_iter_next_cluster ()
pango_layout_iter_next_line, pango_layout_iter_next_line ()
pango_layout_iter_next_run, pango_layout_iter_next_run ()
pango_layout_line_get_extents, pango_layout_line_get_extents ()
pango_layout_line_get_pixel_extents, pango_layout_line_get_pixel_extents ()
pango_layout_line_get_x_ranges, pango_layout_line_get_x_ranges ()
pango_layout_line_index_to_x, pango_layout_line_index_to_x ()
pango_layout_line_ref, pango_layout_line_ref ()
pango_layout_line_unref, pango_layout_line_unref ()
pango_layout_line_x_to_index, pango_layout_line_x_to_index ()
pango_layout_move_cursor_visually, pango_layout_move_cursor_visually ()
pango_layout_new, pango_layout_new ()
pango_layout_set_alignment, pango_layout_set_alignment ()
pango_layout_set_attributes, pango_layout_set_attributes ()
pango_layout_set_auto_dir, pango_layout_set_auto_dir ()
pango_layout_set_ellipsize, pango_layout_set_ellipsize ()
pango_layout_set_font_description, pango_layout_set_font_description ()
pango_layout_set_indent, pango_layout_set_indent ()
pango_layout_set_justify, pango_layout_set_justify ()
pango_layout_set_markup, pango_layout_set_markup ()
pango_layout_set_markup_with_accel, pango_layout_set_markup_with_accel ()
pango_layout_set_single_paragraph_mode, pango_layout_set_single_paragraph_mode ()
pango_layout_set_spacing, pango_layout_set_spacing ()
pango_layout_set_tabs, pango_layout_set_tabs ()
pango_layout_set_text, pango_layout_set_text ()
pango_layout_set_width, pango_layout_set_width ()
pango_layout_set_wrap, pango_layout_set_wrap ()
pango_layout_xy_to_index, pango_layout_xy_to_index ()
PANGO_LBEARING, PANGO_LBEARING()
pango_log2vis_get_embedding_levels, pango_log2vis_get_embedding_levels ()
pango_lookup_aliases, pango_lookup_aliases ()
pango_map_get_engine, pango_map_get_engine ()
pango_map_get_engines, pango_map_get_engines ()
pango_matrix_concat, pango_matrix_concat ()
pango_matrix_copy, pango_matrix_copy ()
pango_matrix_free, pango_matrix_free ()
pango_matrix_get_font_scale_factor, pango_matrix_get_font_scale_factor ()
PANGO_MATRIX_INIT, PANGO_MATRIX_INIT
pango_matrix_rotate, pango_matrix_rotate ()
pango_matrix_scale, pango_matrix_scale ()
pango_matrix_transform_distance, pango_matrix_transform_distance ()
pango_matrix_transform_pixel_rectangle, pango_matrix_transform_pixel_rectangle ()
pango_matrix_transform_point, pango_matrix_transform_point ()
pango_matrix_transform_rectangle, pango_matrix_transform_rectangle ()
pango_matrix_translate, pango_matrix_translate ()
pango_module_register, pango_module_register ()
PANGO_OT_ALL_GLYPHS, PANGO_OT_ALL_GLYPHS
pango_ot_buffer_add_glyph, pango_ot_buffer_add_glyph ()
pango_ot_buffer_clear, pango_ot_buffer_clear ()
pango_ot_buffer_destroy, pango_ot_buffer_destroy ()
pango_ot_buffer_get_glyphs, pango_ot_buffer_get_glyphs ()
pango_ot_buffer_new, pango_ot_buffer_new ()
pango_ot_buffer_output, pango_ot_buffer_output ()
pango_ot_buffer_set_rtl, pango_ot_buffer_set_rtl ()
pango_ot_buffer_set_zero_width_marks, pango_ot_buffer_set_zero_width_marks ()
PANGO_OT_DEFAULT_LANGUAGE, PANGO_OT_DEFAULT_LANGUAGE
pango_ot_info_find_feature, pango_ot_info_find_feature ()
pango_ot_info_find_language, pango_ot_info_find_language ()
pango_ot_info_find_script, pango_ot_info_find_script ()
pango_ot_info_get, pango_ot_info_get ()
pango_ot_info_list_features, pango_ot_info_list_features ()
pango_ot_info_list_languages, pango_ot_info_list_languages ()
pango_ot_info_list_scripts, pango_ot_info_list_scripts ()
pango_ot_ruleset_add_feature, pango_ot_ruleset_add_feature ()
pango_ot_ruleset_new, pango_ot_ruleset_new ()
pango_ot_ruleset_position, pango_ot_ruleset_position ()
pango_ot_ruleset_substitute, pango_ot_ruleset_substitute ()
pango_parse_enum, pango_parse_enum ()
pango_parse_markup, pango_parse_markup ()
pango_parse_stretch, pango_parse_stretch ()
pango_parse_style, pango_parse_style ()
pango_parse_variant, pango_parse_variant ()
pango_parse_weight, pango_parse_weight ()
PANGO_PIXELS, PANGO_PIXELS()
PANGO_PIXELS_CEIL, PANGO_PIXELS_CEIL()
PANGO_PIXELS_FLOOR, PANGO_PIXELS_FLOOR()
pango_quantize_line_geometry, pango_quantize_line_geometry ()
PANGO_RBEARING, PANGO_RBEARING()
pango_read_line, pango_read_line ()
pango_renderer_activate, pango_renderer_activate ()
pango_renderer_deactivate, pango_renderer_deactivate ()
pango_renderer_draw_error_underline, pango_renderer_draw_error_underline ()
pango_renderer_draw_glyph, pango_renderer_draw_glyph ()
pango_renderer_draw_glyphs, pango_renderer_draw_glyphs ()
pango_renderer_draw_layout, pango_renderer_draw_layout ()
pango_renderer_draw_layout_line, pango_renderer_draw_layout_line ()
pango_renderer_draw_rectangle, pango_renderer_draw_rectangle ()
pango_renderer_draw_trapezoid, pango_renderer_draw_trapezoid ()
pango_renderer_get_color, pango_renderer_get_color ()
pango_renderer_get_matrix, pango_renderer_get_matrix ()
pango_renderer_part_changed, pango_renderer_part_changed ()
pango_renderer_set_color, pango_renderer_set_color ()
pango_renderer_set_matrix, pango_renderer_set_matrix ()
PANGO_RENDER_TYPE_FC, PANGO_RENDER_TYPE_FC
PANGO_RENDER_TYPE_FT2, PANGO_RENDER_TYPE_FT2
PANGO_RENDER_TYPE_NONE, PANGO_RENDER_TYPE_NONE
PANGO_RENDER_TYPE_WIN32, PANGO_RENDER_TYPE_WIN32
PANGO_RENDER_TYPE_X, PANGO_RENDER_TYPE_X
PANGO_RENDER_TYPE_XFT, PANGO_RENDER_TYPE_XFT
pango_reorder_items, pango_reorder_items ()
PANGO_SCALE, PANGO_SCALE
PANGO_SCALE_LARGE, PANGO_SCALE_LARGE
PANGO_SCALE_MEDIUM, PANGO_SCALE_MEDIUM
PANGO_SCALE_SMALL, PANGO_SCALE_SMALL
PANGO_SCALE_XX_LARGE, PANGO_SCALE_XX_LARGE
PANGO_SCALE_XX_SMALL, PANGO_SCALE_XX_SMALL
PANGO_SCALE_X_LARGE, PANGO_SCALE_X_LARGE
PANGO_SCALE_X_SMALL, PANGO_SCALE_X_SMALL
pango_scan_int, pango_scan_int ()
pango_scan_string, pango_scan_string ()
pango_scan_word, pango_scan_word ()
pango_script_for_unichar, pango_script_for_unichar ()
pango_script_get_sample_language, pango_script_get_sample_language ()
pango_script_iter_free, pango_script_iter_free ()
pango_script_iter_get_range, pango_script_iter_get_range ()
pango_script_iter_new, pango_script_iter_new ()
pango_script_iter_next, pango_script_iter_next ()
pango_shape, pango_shape ()
pango_skip_space, pango_skip_space ()
pango_split_file_list, pango_split_file_list ()
pango_tab_array_copy, pango_tab_array_copy ()
pango_tab_array_free, pango_tab_array_free ()
pango_tab_array_get_positions_in_pixels, pango_tab_array_get_positions_in_pixels ()
pango_tab_array_get_size, pango_tab_array_get_size ()
pango_tab_array_get_tab, pango_tab_array_get_tab ()
pango_tab_array_get_tabs, pango_tab_array_get_tabs ()
pango_tab_array_new, pango_tab_array_new ()
pango_tab_array_new_with_positions, pango_tab_array_new_with_positions ()
pango_tab_array_resize, pango_tab_array_resize ()
pango_tab_array_set_tab, pango_tab_array_set_tab ()
pango_trim_string, pango_trim_string ()
PANGO_TYPE_ALIGNMENT, PANGO_TYPE_ALIGNMENT
PANGO_TYPE_ATTR_LIST, PANGO_TYPE_ATTR_LIST
PANGO_TYPE_ATTR_TYPE, PANGO_TYPE_ATTR_TYPE
PANGO_TYPE_COLOR, PANGO_TYPE_COLOR
PANGO_TYPE_COVERAGE_LEVEL, PANGO_TYPE_COVERAGE_LEVEL
PANGO_TYPE_DIRECTION, PANGO_TYPE_DIRECTION
PANGO_TYPE_ELLIPSIZE_MODE, PANGO_TYPE_ELLIPSIZE_MODE
PANGO_TYPE_FONT, PANGO_TYPE_FONT
PANGO_TYPE_FONTSET, PANGO_TYPE_FONTSET
PANGO_TYPE_FONTSET_SIMPLE, PANGO_TYPE_FONTSET_SIMPLE
PANGO_TYPE_FONT_DESCRIPTION, PANGO_TYPE_FONT_DESCRIPTION
PANGO_TYPE_FONT_FACE, PANGO_TYPE_FONT_FACE
PANGO_TYPE_FONT_FAMILY, PANGO_TYPE_FONT_FAMILY
PANGO_TYPE_FONT_MAP, PANGO_TYPE_FONT_MAP
PANGO_TYPE_FONT_MASK, PANGO_TYPE_FONT_MASK
PANGO_TYPE_FONT_METRICS, PANGO_TYPE_FONT_METRICS
PANGO_TYPE_GLYPH_STRING, PANGO_TYPE_GLYPH_STRING
PANGO_TYPE_GRAVITY, PANGO_TYPE_GRAVITY
PANGO_TYPE_GRAVITY_HINT, PANGO_TYPE_GRAVITY_HINT
PANGO_TYPE_LANGUAGE, PANGO_TYPE_LANGUAGE
PANGO_TYPE_MATRIX, PANGO_TYPE_MATRIX
PANGO_TYPE_RENDER_PART, PANGO_TYPE_RENDER_PART
PANGO_TYPE_SCRIPT, PANGO_TYPE_SCRIPT
PANGO_TYPE_STRETCH, PANGO_TYPE_STRETCH
PANGO_TYPE_STYLE, PANGO_TYPE_STYLE
PANGO_TYPE_TAB_ALIGN, PANGO_TYPE_TAB_ALIGN
PANGO_TYPE_TAB_ARRAY, PANGO_TYPE_TAB_ARRAY
PANGO_TYPE_UNDERLINE, PANGO_TYPE_UNDERLINE
PANGO_TYPE_VARIANT, PANGO_TYPE_VARIANT
PANGO_TYPE_WEIGHT, PANGO_TYPE_WEIGHT
PANGO_TYPE_WRAP_MODE, PANGO_TYPE_WRAP_MODE
pango_unichar_direction, pango_unichar_direction ()
pango_units_from_double, pango_units_from_double ()
pango_units_to_double, pango_units_to_double ()
PANGO_VERSION, PANGO_VERSION
pango_version, pango_version ()
PANGO_VERSION_CHECK, PANGO_VERSION_CHECK()
pango_version_check, pango_version_check ()
PANGO_VERSION_ENCODE, PANGO_VERSION_ENCODE()
PANGO_VERSION_MAJOR, PANGO_VERSION_MAJOR
PANGO_VERSION_MICRO, PANGO_VERSION_MICRO
PANGO_VERSION_MINOR, PANGO_VERSION_MINOR
PANGO_VERSION_STRING, PANGO_VERSION_STRING
pango_version_string, pango_version_string ()
pango_win32_font_cache_free, pango_win32_font_cache_free ()
pango_win32_font_cache_load, pango_win32_font_cache_load ()
pango_win32_font_cache_new, pango_win32_font_cache_new ()
pango_win32_font_cache_unload, pango_win32_font_cache_unload ()
pango_win32_font_description_from_logfont, pango_win32_font_description_from_logfont ()
pango_win32_font_done_font, pango_win32_font_done_font ()
pango_win32_font_get_glyph_index, pango_win32_font_get_glyph_index ()
pango_win32_font_get_metrics_factor, pango_win32_font_get_metrics_factor ()
pango_win32_font_logfont, pango_win32_font_logfont ()
pango_win32_font_map_for_display, pango_win32_font_map_for_display ()
pango_win32_font_map_get_font_cache, pango_win32_font_map_get_font_cache ()
pango_win32_font_select_font, pango_win32_font_select_font ()
pango_win32_get_context, pango_win32_get_context ()
pango_win32_get_dc, pango_win32_get_dc ()
pango_win32_get_debug_flag, pango_win32_get_debug_flag ()
pango_win32_get_unknown_glyph, pango_win32_get_unknown_glyph ()
pango_win32_render, pango_win32_render ()
pango_win32_render_layout, pango_win32_render_layout ()
pango_win32_render_layout_line, pango_win32_render_layout_line ()
pango_win32_render_transformed, pango_win32_render_transformed ()
pango_win32_shutdown_display, pango_win32_shutdown_display ()
pango_xft_font_get_display, pango_xft_font_get_display ()
pango_xft_font_get_font, pango_xft_font_get_font ()
pango_xft_font_get_glyph, pango_xft_font_get_glyph ()
pango_xft_font_get_unknown_glyph, pango_xft_font_get_unknown_glyph ()
pango_xft_font_has_char, pango_xft_font_has_char ()
pango_xft_font_lock_face, pango_xft_font_lock_face ()
pango_xft_font_unlock_face, pango_xft_font_unlock_face ()
pango_xft_get_context, pango_xft_get_context ()
pango_xft_get_font_map, pango_xft_get_font_map ()
pango_xft_picture_render, pango_xft_picture_render ()
pango_xft_render, pango_xft_render ()
pango_xft_renderer_new, pango_xft_renderer_new ()
pango_xft_renderer_set_default_color, pango_xft_renderer_set_default_color ()
pango_xft_renderer_set_draw, pango_xft_renderer_set_draw ()
pango_xft_render_layout, pango_xft_render_layout ()
pango_xft_render_layout_line, pango_xft_render_layout_line ()
pango_xft_render_transformed, pango_xft_render_transformed ()
pango_xft_set_default_substitute, pango_xft_set_default_substitute ()
pango_xft_shutdown_display, pango_xft_shutdown_display ()
pango_xft_substitute_changed, pango_xft_substitute_changed ()
pango_x_apply_ligatures, pango_x_apply_ligatures ()
pango_x_context_set_funcs, pango_x_context_set_funcs ()
pango_x_fallback_shape, pango_x_fallback_shape ()
pango_x_find_first_subfont, pango_x_find_first_subfont ()
pango_x_font_cache_free, pango_x_font_cache_free ()
pango_x_font_cache_load, pango_x_font_cache_load ()
pango_x_font_cache_new, pango_x_font_cache_new ()
pango_x_font_cache_unload, pango_x_font_cache_unload ()
pango_x_font_get_unknown_glyph, pango_x_font_get_unknown_glyph ()
pango_x_font_map_for_display, pango_x_font_map_for_display ()
pango_x_font_map_get_font_cache, pango_x_font_map_get_font_cache ()
pango_x_font_subfont_xlfd, pango_x_font_subfont_xlfd ()
pango_x_get_context, pango_x_get_context ()
pango_x_get_unknown_glyph, pango_x_get_unknown_glyph ()
PANGO_X_GLYPH_INDEX, PANGO_X_GLYPH_INDEX()
PANGO_X_GLYPH_SUBFONT, PANGO_X_GLYPH_SUBFONT()
pango_x_has_glyph, pango_x_has_glyph ()
pango_x_list_subfonts, pango_x_list_subfonts ()
pango_x_load_font, pango_x_load_font ()
PANGO_X_MAKE_GLYPH, PANGO_X_MAKE_GLYPH()
pango_x_render, pango_x_render ()
pango_x_render_layout, pango_x_render_layout ()
pango_x_render_layout_line, pango_x_render_layout_line ()
pango_x_shutdown_display, pango_x_shutdown_display ()

S

script_engine_create, script_engine_create ()
script_engine_exit, script_engine_exit ()
script_engine_init, script_engine_init ()
script_engine_list, script_engine_list ()


Index of deprecated symbols

P

PangoFreeGCFunc, PangoFreeGCFunc ()
PangoGetGCFunc, PangoGetGCFunc ()
PangoXFontCache, PangoXFontCache
PangoXSubfont, PangoXSubfont
pango_fc_font_get_unknown_glyph, pango_fc_font_get_unknown_glyph ()
pango_ft2_font_get_coverage, pango_ft2_font_get_coverage ()
pango_ft2_font_get_face, pango_ft2_font_get_face ()
pango_ft2_font_get_kerning, pango_ft2_font_get_kerning ()
pango_ft2_font_map_for_display, pango_ft2_font_map_for_display ()
pango_ft2_get_context, pango_ft2_get_context ()
pango_ft2_get_unknown_glyph, pango_ft2_get_unknown_glyph ()
pango_ft2_shutdown_display, pango_ft2_shutdown_display ()
pango_get_mirror_char, pango_get_mirror_char ()
PANGO_RENDER_TYPE_FT2, PANGO_RENDER_TYPE_FT2
PANGO_RENDER_TYPE_X, PANGO_RENDER_TYPE_X
PANGO_RENDER_TYPE_XFT, PANGO_RENDER_TYPE_XFT
pango_win32_get_unknown_glyph, pango_win32_get_unknown_glyph ()
pango_xft_font_get_glyph, pango_xft_font_get_glyph ()
pango_xft_font_get_unknown_glyph, pango_xft_font_get_unknown_glyph ()
pango_xft_font_has_char, pango_xft_font_has_char ()
pango_xft_font_lock_face, pango_xft_font_lock_face ()
pango_xft_font_unlock_face, pango_xft_font_unlock_face ()
pango_x_apply_ligatures, pango_x_apply_ligatures ()
pango_x_context_set_funcs, pango_x_context_set_funcs ()
pango_x_fallback_shape, pango_x_fallback_shape ()
pango_x_find_first_subfont, pango_x_find_first_subfont ()
pango_x_font_cache_free, pango_x_font_cache_free ()
pango_x_font_cache_load, pango_x_font_cache_load ()
pango_x_font_cache_new, pango_x_font_cache_new ()
pango_x_font_cache_unload, pango_x_font_cache_unload ()
pango_x_font_get_unknown_glyph, pango_x_font_get_unknown_glyph ()
pango_x_font_map_for_display, pango_x_font_map_for_display ()
pango_x_font_map_get_font_cache, pango_x_font_map_get_font_cache ()
pango_x_font_subfont_xlfd, pango_x_font_subfont_xlfd ()
pango_x_get_context, pango_x_get_context ()
pango_x_get_unknown_glyph, pango_x_get_unknown_glyph ()
PANGO_X_GLYPH_INDEX, PANGO_X_GLYPH_INDEX()
PANGO_X_GLYPH_SUBFONT, PANGO_X_GLYPH_SUBFONT()
pango_x_has_glyph, pango_x_has_glyph ()
pango_x_list_subfonts, pango_x_list_subfonts ()
pango_x_load_font, pango_x_load_font ()
PANGO_X_MAKE_GLYPH, PANGO_X_MAKE_GLYPH()
pango_x_render, pango_x_render ()
pango_x_render_layout, pango_x_render_layout ()
pango_x_render_layout_line, pango_x_render_layout_line ()
pango_x_shutdown_display, pango_x_shutdown_display ()


Index of new symbols in 1.2

P

pango_attr_iterator_get_attrs, pango_attr_iterator_get_attrs ()
pango_attr_list_filter, pango_attr_list_filter ()
pango_ft2_font_map_create_context, pango_ft2_font_map_create_context ()
pango_ft2_font_map_new, pango_ft2_font_map_new ()
pango_ft2_font_map_set_default_substitute, pango_ft2_font_map_set_default_substitute ()
pango_ft2_font_map_set_resolution, pango_ft2_font_map_set_resolution ()
pango_ft2_font_map_substitute_changed, pango_ft2_font_map_substitute_changed ()
pango_glyph_item_apply_attrs, pango_glyph_item_apply_attrs ()
pango_glyph_item_split, pango_glyph_item_split ()
pango_ot_info_get, pango_ot_info_get ()
pango_win32_get_debug_flag, pango_win32_get_debug_flag ()
pango_xft_font_get_glyph, pango_xft_font_get_glyph ()
pango_xft_font_has_char, pango_xft_font_has_char ()
pango_xft_font_lock_face, pango_xft_font_lock_face ()
pango_xft_font_unlock_face, pango_xft_font_unlock_face ()
pango_xft_get_font_map, pango_xft_get_font_map ()
pango_xft_set_default_substitute, pango_xft_set_default_substitute ()
pango_xft_shutdown_display, pango_xft_shutdown_display ()
pango_xft_substitute_changed, pango_xft_substitute_changed ()


Index of new symbols in 1.4

P

PangoFontsetForeachFunc, PangoFontsetForeachFunc ()
pango_attr_fallback_new, pango_attr_fallback_new ()
pango_fc_font_description_from_pattern, pango_fc_font_description_from_pattern ()
pango_fc_font_get_glyph, pango_fc_font_get_glyph ()
pango_fc_font_get_unknown_glyph, pango_fc_font_get_unknown_glyph ()
pango_fc_font_has_char, pango_fc_font_has_char ()
pango_fc_font_kern_glyphs, pango_fc_font_kern_glyphs ()
pango_fc_font_lock_face, pango_fc_font_lock_face ()
pango_fc_font_map_cache_clear, pango_fc_font_map_cache_clear ()
pango_fc_font_map_create_context, pango_fc_font_map_create_context ()
pango_fc_font_map_shutdown, pango_fc_font_map_shutdown ()
pango_fc_font_unlock_face, pango_fc_font_unlock_face ()
pango_find_base_dir, pango_find_base_dir ()
pango_fontset_foreach, pango_fontset_foreach ()
pango_font_face_list_sizes, pango_font_face_list_sizes ()
pango_font_family_is_monospace, pango_font_family_is_monospace ()
pango_font_map_get_shape_engine_type, pango_font_map_get_shape_engine_type ()
pango_itemize_with_base_dir, pango_itemize_with_base_dir ()
pango_language_includes_script, pango_language_includes_script ()
pango_layout_get_auto_dir, pango_layout_get_auto_dir ()
pango_layout_set_auto_dir, pango_layout_set_auto_dir ()
pango_log2vis_get_embedding_levels, pango_log2vis_get_embedding_levels ()
pango_map_get_engines, pango_map_get_engines ()
pango_ot_buffer_add_glyph, pango_ot_buffer_add_glyph ()
pango_ot_buffer_clear, pango_ot_buffer_clear ()
pango_ot_buffer_destroy, pango_ot_buffer_destroy ()
pango_ot_buffer_get_glyphs, pango_ot_buffer_get_glyphs ()
pango_ot_buffer_new, pango_ot_buffer_new ()
pango_ot_buffer_output, pango_ot_buffer_output ()
pango_ot_buffer_set_rtl, pango_ot_buffer_set_rtl ()
pango_ot_ruleset_position, pango_ot_ruleset_position ()
pango_ot_ruleset_substitute, pango_ot_ruleset_substitute ()
pango_script_for_unichar, pango_script_for_unichar ()
pango_script_get_sample_language, pango_script_get_sample_language ()
pango_script_iter_free, pango_script_iter_free ()
pango_script_iter_get_range, pango_script_iter_get_range ()
pango_script_iter_new, pango_script_iter_new ()
pango_script_iter_next, pango_script_iter_next ()


Index of new symbols in 1.6

P

PangoFcDecoder, PangoFcDecoder
PangoFcDecoderClass, PangoFcDecoderClass
PangoMatrix, PangoMatrix
pango_attr_letter_spacing_new, pango_attr_letter_spacing_new ()
pango_context_get_font_map, pango_context_get_font_map ()
pango_context_get_matrix, pango_context_get_matrix ()
pango_context_set_matrix, pango_context_set_matrix ()
pango_fc_decoder_get_charset, pango_fc_decoder_get_charset ()
pango_fc_decoder_get_glyph, pango_fc_decoder_get_glyph ()
pango_font_metrics_get_strikethrough_position, pango_font_metrics_get_strikethrough_position ()
pango_font_metrics_get_strikethrough_thickness, pango_font_metrics_get_strikethrough_thickness ()
pango_font_metrics_get_underline_position, pango_font_metrics_get_underline_position ()
pango_font_metrics_get_underline_thickness, pango_font_metrics_get_underline_thickness ()
pango_ft2_render_layout_line_subpixel, pango_ft2_render_layout_line_subpixel ()
pango_ft2_render_layout_subpixel, pango_ft2_render_layout_subpixel ()
pango_ft2_render_transformed, pango_ft2_render_transformed ()
pango_glyph_item_free, pango_glyph_item_free ()
pango_glyph_item_letter_space, pango_glyph_item_letter_space ()
pango_layout_get_ellipsize, pango_layout_get_ellipsize ()
pango_layout_set_ellipsize, pango_layout_set_ellipsize ()
pango_matrix_concat, pango_matrix_concat ()
pango_matrix_copy, pango_matrix_copy ()
pango_matrix_free, pango_matrix_free ()
PANGO_MATRIX_INIT, PANGO_MATRIX_INIT
pango_matrix_rotate, pango_matrix_rotate ()
pango_matrix_scale, pango_matrix_scale ()
pango_matrix_translate, pango_matrix_translate ()
pango_ot_buffer_set_zero_width_marks, pango_ot_buffer_set_zero_width_marks ()


Index of new symbols in 1.8

P

PangoRenderer, PangoRenderer
PangoRendererClass, PangoRendererClass
PangoRenderPart, enum PangoRenderPart
PangoXftRenderer, PangoXftRenderer
PangoXftRendererClass, PangoXftRendererClass
pango_attr_shape_new_with_data, pango_attr_shape_new_with_data ()
pango_attr_size_new_absolute, pango_attr_size_new_absolute ()
pango_attr_strikethrough_color_new, pango_attr_strikethrough_color_new ()
pango_attr_underline_color_new, pango_attr_underline_color_new ()
pango_font_description_get_size_is_absolute, pango_font_description_get_size_is_absolute ()
pango_font_description_set_absolute_size, pango_font_description_set_absolute_size ()
pango_layout_get_font_description, pango_layout_get_font_description ()
pango_renderer_activate, pango_renderer_activate ()
pango_renderer_deactivate, pango_renderer_deactivate ()
pango_renderer_draw_error_underline, pango_renderer_draw_error_underline ()
pango_renderer_draw_glyph, pango_renderer_draw_glyph ()
pango_renderer_draw_glyphs, pango_renderer_draw_glyphs ()
pango_renderer_draw_layout, pango_renderer_draw_layout ()
pango_renderer_draw_layout_line, pango_renderer_draw_layout_line ()
pango_renderer_draw_rectangle, pango_renderer_draw_rectangle ()
pango_renderer_draw_trapezoid, pango_renderer_draw_trapezoid ()
pango_renderer_get_color, pango_renderer_get_color ()
pango_renderer_get_matrix, pango_renderer_get_matrix ()
pango_renderer_part_changed, pango_renderer_part_changed ()
pango_renderer_set_color, pango_renderer_set_color ()
pango_renderer_set_matrix, pango_renderer_set_matrix ()
pango_xft_renderer_new, pango_xft_renderer_new ()
pango_xft_renderer_set_default_color, pango_xft_renderer_set_default_color ()
pango_xft_renderer_set_draw, pango_xft_renderer_set_draw ()
pango_xft_render_layout, pango_xft_render_layout ()
pango_xft_render_layout_line, pango_xft_render_layout_line ()
pango_xft_render_transformed, pango_xft_render_transformed ()


Index of new symbols in 1.10

P

PangoCairoFontMap, PangoCairoFontMap
pango_attr_list_ref, pango_attr_list_ref ()
pango_cairo_context_get_resolution, pango_cairo_context_get_resolution ()
pango_cairo_context_set_resolution, pango_cairo_context_set_resolution ()
pango_cairo_create_layout, pango_cairo_create_layout ()
pango_cairo_font_map_create_context, pango_cairo_font_map_create_context ()
pango_cairo_font_map_get_default, pango_cairo_font_map_get_default ()
pango_cairo_font_map_get_resolution, pango_cairo_font_map_get_resolution ()
pango_cairo_font_map_new, pango_cairo_font_map_new ()
pango_cairo_font_map_set_resolution, pango_cairo_font_map_set_resolution ()
pango_cairo_glyph_string_path, pango_cairo_glyph_string_path ()
pango_cairo_layout_line_path, pango_cairo_layout_line_path ()
pango_cairo_layout_path, pango_cairo_layout_path ()
pango_cairo_show_glyph_string, pango_cairo_show_glyph_string ()
pango_cairo_show_layout, pango_cairo_show_layout ()
pango_cairo_show_layout_line, pango_cairo_show_layout_line ()
pango_cairo_update_context, pango_cairo_update_context ()
pango_cairo_update_layout, pango_cairo_update_layout ()
pango_font_get_font_map, pango_font_get_font_map ()
pango_is_zero_width, pango_is_zero_width ()
pango_layout_line_ref, pango_layout_line_ref ()


Index of new symbols in 1.12

P

pango_cairo_atsui_font_get_atsu_font_id, pango_cairo_atsui_font_get_atsu_font_id ()
pango_matrix_get_font_scale_factor, pango_matrix_get_font_scale_factor ()
pango_quantize_line_geometry, pango_quantize_line_geometry ()
pango_win32_font_description_from_logfont, pango_win32_font_description_from_logfont ()


Index of new symbols in 1.14

P

pango_cairo_error_underline_path, pango_cairo_error_underline_path ()
pango_cairo_show_error_underline, pango_cairo_show_error_underline ()
pango_font_describe_with_absolute_size, pango_font_describe_with_absolute_size ()
pango_glyph_string_get_width, pango_glyph_string_get_width ()


Index of new symbols in 1.16

P

PangoGravity, enum PangoGravity
PangoGravityHint, enum PangoGravityHint
pango_attr_gravity_hint_new, pango_attr_gravity_hint_new ()
pango_attr_gravity_new, pango_attr_gravity_new ()
pango_color_to_string, pango_color_to_string ()
pango_context_get_base_gravity, pango_context_get_base_gravity ()
pango_context_get_gravity, pango_context_get_gravity ()
pango_context_get_gravity_hint, pango_context_get_gravity_hint ()
pango_context_set_base_gravity, pango_context_set_base_gravity ()
pango_context_set_gravity_hint, pango_context_set_gravity_hint ()
pango_extents_to_pixels, pango_extents_to_pixels ()
pango_font_description_get_gravity, pango_font_description_get_gravity ()
pango_font_description_set_gravity, pango_font_description_set_gravity ()
pango_gravity_get_for_matrix, pango_gravity_get_for_matrix ()
pango_gravity_get_for_script, pango_gravity_get_for_script ()
PANGO_GRAVITY_IS_VERTICAL, PANGO_GRAVITY_IS_VERTICAL()
pango_gravity_to_rotation, pango_gravity_to_rotation ()
pango_language_get_default, pango_language_get_default ()
pango_layout_get_lines_readonly, pango_layout_get_lines_readonly ()
pango_layout_get_line_readonly, pango_layout_get_line_readonly ()
pango_layout_get_unknown_glyphs_count, pango_layout_get_unknown_glyphs_count ()
pango_layout_is_ellipsized, pango_layout_is_ellipsized ()
pango_layout_is_wrapped, pango_layout_is_wrapped ()
pango_layout_iter_get_line_readonly, pango_layout_iter_get_line_readonly ()
pango_layout_iter_get_run_readonly, pango_layout_iter_get_run_readonly ()
pango_matrix_transform_distance, pango_matrix_transform_distance ()
pango_matrix_transform_pixel_rectangle, pango_matrix_transform_pixel_rectangle ()
pango_matrix_transform_point, pango_matrix_transform_point ()
pango_matrix_transform_rectangle, pango_matrix_transform_rectangle ()
pango_parse_enum, pango_parse_enum ()
pango_units_from_double, pango_units_from_double ()
pango_units_to_double, pango_units_to_double ()
pango_version, pango_version ()
pango_version_check, pango_version_check ()
pango_version_string, pango_version_string ()


Low Level Functionality

PangoRenderer - Rendering driver base class
PangoFcFontMap - Base fontmap class for Fontconfig-based backends
PangoFcFont - Base font class for Fontconfig-based backends
PangoFcDecoder - Custom font encoding handling
OpenType Font Handling - Obtaining information from OpenType tables
Coverage Maps - Unicode character range coverage storage
Engines - Language-specific and rendering-system-specific processing
PangoEngineLang - Rendering-system independent script engines
PangoEngineShape - Rendering-system dependent script engines
Modules - Support for loadable modules
Miscellaneous Utilities - Various convenience and utility functions
Version Checking - Tools for checking Pango version at compile- and run-time.


Basic Pango Interfaces

Rendering - Functions to run the rendering pipeline
Glyph Storage - Structures for storing information about glyphs
Fonts - Structures representing abstract fonts
Text Attributes - Font and other attributes for annotating text
Tab Stops - Structures for storing tab stops
Text Attribute Markup - Simple markup language to encode text with attributes
Layout Objects - High-level layout driver objects
Scripts - Identifying writing systems
Vertical Text - Laying text out in vertical directions


ATSUI Fonts

ATSUI Fonts — Font handling and rendering with ATSUI fonts

Synopsis

            PangoCairoATSUIFont;
ATSUFontID  pango_cairo_atsui_font_get_atsu_font_id
                                            (PangoCairoATSUIFont *cafont);

Description

The macros and functions in this section are used to access fonts natively on MacOS systems using the ATSUI text rendering subsystem.

Details

PangoCairoATSUIFont

typedef struct _PangoCairoATSUIFont PangoCairoATSUIFont;

The PangoCairoATSUIFont is PangoFont used to represent an ATSUI font used with the cairo backend.

pango_cairo_atsui_font_get_atsu_font_id ()

ATSUFontID  pango_cairo_atsui_font_get_atsu_font_id
                                            (PangoCairoATSUIFont *cafont);

Returns the ATSUFontID of a font.

cafont : | A PangoCairoATSUIFont
Returns : | the ATSUFontID associated to cafont.

Since 1.12


Cairo Rendering

Cairo Rendering — Rendering with the Cairo backend

Synopsis

            PangoCairoFontMap;
PangoFontMap* pango_cairo_font_map_new      (void);
PangoFontMap* pango_cairo_font_map_get_default
                                            (void);
void        pango_cairo_font_map_set_resolution
                                            (PangoCairoFontMap *fontmap,
                                             double dpi);
double      pango_cairo_font_map_get_resolution
                                            (PangoCairoFontMap *fontmap);
PangoContext* pango_cairo_font_map_create_context
                                            (PangoCairoFontMap *fontmap);
void        pango_cairo_context_set_resolution
                                            (PangoContext *context,
                                             double dpi);
double      pango_cairo_context_get_resolution
                                            (PangoContext *context);
void        pango_cairo_context_set_font_options
                                            (PangoContext *context,
                                             const cairo_font_options_t *options);
const cairo_font_options_t* pango_cairo_context_get_font_options
                                            (PangoContext *context);
void        pango_cairo_update_context      (cairo_t *cr,
                                             PangoContext *context);
PangoLayout* pango_cairo_create_layout      (cairo_t *cr);
void        pango_cairo_update_layout       (cairo_t *cr,
                                             PangoLayout *layout);
void        pango_cairo_show_glyph_string   (cairo_t *cr,
                                             PangoFont *font,
                                             PangoGlyphString *glyphs);
void        pango_cairo_show_layout_line    (cairo_t *cr,
                                             PangoLayoutLine *line);
void        pango_cairo_show_layout         (cairo_t *cr,
                                             PangoLayout *layout);
void        pango_cairo_show_error_underline
                                            (cairo_t *cr,
                                             double x,
                                             double y,
                                             double width,
                                             double height);
void        pango_cairo_glyph_string_path   (cairo_t *cr,
                                             PangoFont *font,
                                             PangoGlyphString *glyphs);
void        pango_cairo_layout_line_path    (cairo_t *cr,
                                             PangoLayoutLine *line);
void        pango_cairo_layout_path         (cairo_t *cr,
                                             PangoLayout *layout);
void        pango_cairo_error_underline_path
                                            (cairo_t *cr,
                                             double x,
                                             double y,
                                             double width,
                                             double height);

Object Hierarchy

  GInterface
   +----PangoCairoFontMap

Prerequisites

PangoCairoFontMap requires PangoFontMap.

Description

The Cairo library is a vector graphics library with a powerful rendering model. It has such features as anti-aliased primitives, alpha-compositing, and gradients. Multiple backends for Cairo are available, to allow rendering to images, to PDF files, and to the screen on X and on other windowing systems. The functions in this section allow using Pango to render to Cairo surfaces.

Using Pango with Cairo is straightforward. A PangoContext created with pango_cairo_font_map_create_context() can be used on any Cairo context (cairo_t), but needs to be updated to match the current transformation matrix and target surface of the Cairo context using pango_cairo_update_context(). The convenience functions pango_cairo_create_layout() and pango_cairo_update_layout() handle the common case where the program doesn't need to manipulate the properties of the PangoContext.

When you get the metrics of a layout or of a piece of a layout using functions such as pango_layout_get_extents(), the reported metrics are in user-space coordinates. If a piece of text is 10 units long, and you call cairo_scale (cr, 2.0), it still is more-or-less 10 units long. However, the results will be affected by hinting (that is, the process of adjusting the text to look good on the pixel grid), so you shouldn't assume they are completely independent of the current transformation matrix. Note that the basic metrics functions in Pango report results in integer Pango units. To get to the floating point units used in Cairo divide by PANGO_SCALE.

Example 1. Using Pango with Cairo

#include <math.h>
#include <pango/pangocairo.h>

static void
draw_text (cairo_t *cr)
{
#define RADIUS 150
#define N_WORDS 10
#define FONT "Sans Bold 27"

  PangoLayout *layout;
  PangoFontDescription *desc;
  int i;

  /* Center coordinates on the middle of the region we are drawing
   */
  cairo_translate (cr, RADIUS, RADIUS);

  /* Create a PangoLayout, set the font and text */
  layout = pango_cairo_create_layout (cr);

  pango_layout_set_text (layout, "Text", -1);
  desc = pango_font_description_from_string (FONT);
  pango_layout_set_font_description (layout, desc);
  pango_font_description_free (desc);

  /* Draw the layout N_WORDS times in a circle */
  for (i = 0; i < N_WORDS; i++)
    {
      int width, height;
      double angle = (360. * i) / N_WORDS;
      double red;

      cairo_save (cr);

      /* Gradient from red at angle == 60 to blue at angle == 240 */
      red   = (1 + cos ((angle - 60) * G_PI / 180.)) / 2;
      cairo_set_source_rgb (cr, red, 0, 1.0 - red);

      cairo_rotate (cr, angle * G_PI / 180.);

      /* Inform Pango to re-layout the text with the new transformation */
      pango_cairo_update_layout (cr, layout);

      pango_layout_get_size (layout, &width, &height);
      cairo_move_to (cr, - ((double)width / PANGO_SCALE) / 2, - RADIUS);
      pango_cairo_show_layout (cr, layout);

      cairo_restore (cr);
    }

  /* free the layout object */
  g_object_unref (layout);
}

int main (int argc, char **argv)
{
  cairo_t *cr;
  char *filename;
  cairo_status_t status;
  cairo_surface_t *surface;

  if (argc != 2)
    {
      g_printerr ("Usage: cairosimple OUTPUT_FILENAME\n");
      return 1;
    }

  filename = argv[1];

  surface = cairo_image_surface_create (CAIRO_FORMAT_ARGB32,
                    2 * RADIUS, 2 * RADIUS);
  cr = cairo_create (surface);

  cairo_set_source_rgb (cr, 1.0, 1.0, 1.0);
  cairo_paint (cr);
  draw_text (cr);
  cairo_destroy (cr);

  status = cairo_surface_write_to_png (surface, filename);
  cairo_surface_destroy (surface);

  if (status != CAIRO_STATUS_SUCCESS)
    {
      g_printerr ("Could not save png to 's'\n", filename);
      return 1;
    }

  return 0;
}

Figure 1. Output of Example 1, “Using Pango with Cairo”

Details

PangoCairoFontMap

typedef struct _PangoCairoFontMap PangoCairoFontMap;

PangoCairoFontMap is an interface exported by font maps for use with Cairo. The actual type of the font map will depend on the particular font technology Cairo was compiled to use.

Since 1.10

pango_cairo_font_map_new ()

PangoFontMap* pango_cairo_font_map_new      (void);

Creates a new PangoCairoFontMap object; a fontmap is used to cache information about available fonts, and holds certain global parameters such as the resolution. In most cases, you can use pango_cairo_font_map_get_default() instead.

Note that the type of the returned object will depend on the particular font backend Cairo was compiled to use; You generally should only use the PangoFontMap and PangoCairoFontMap interfaces on the returned object.

Returns : the newly allocated PangoFontMap, which should be freed with g_object_unref().

Since 1.10

pango_cairo_font_map_get_default ()

PangoFontMap* pango_cairo_font_map_get_default
                                            (void);

Gets a default font map to use with Cairo.

Returns : the default Cairo fontmap for Pango. This object is owned by Pango and must not be freed.

Since 1.10

pango_cairo_font_map_set_resolution ()

void        pango_cairo_font_map_set_resolution
                                            (PangoCairoFontMap *fontmap,
                                             double dpi);

Sets the resolution for the fontmap. This is a scale factor between points specified in a PangoFontDescription and Cairo units. The default value is 96, meaning that a 10 point font will be 13 units high. (10 * 96. / 72. = 13.3).

fontmap : | a PangoCairoFontMap
dpi : | the resolution in "dots per inch". (Physical inches aren't actually involved; the terminology is conventional.)

Since 1.10

pango_cairo_font_map_get_resolution ()

double      pango_cairo_font_map_get_resolution
                                            (PangoCairoFontMap *fontmap);

Gets the resolution for the fontmap. See pango_cairo_font_map_set_resolution()

fontmap : | a PangoCairoFontMap
Returns : | the resolution in "dots per inch"

Since 1.10

pango_cairo_font_map_create_context ()

PangoContext* pango_cairo_font_map_create_context
                                            (PangoCairoFontMap *fontmap);

Create a PangoContext for the given fontmap.

fontmap : | a PangoCairoFontMap
Returns : | the newly created context; free with g_object_unref().

Since 1.10

pango_cairo_context_set_resolution ()

void        pango_cairo_context_set_resolution
                                            (PangoContext *context,
                                             double dpi);

Sets the resolution for the context. This is a scale factor between points specified in a PangoFontDescription and Cairo units. The default value is 96, meaning that a 10 point font will be 13 units high. (10 * 96. / 72. = 13.3).

context : | a PangoContext, from pango_cairo_font_map_create_context()
dpi : | the resolution in "dots per inch". (Physical inches aren't actually involved; the terminology is conventional.) A 0 or negative value means to use the resolution from the font map.

Since 1.10

pango_cairo_context_get_resolution ()

double      pango_cairo_context_get_resolution
                                            (PangoContext *context);

Gets the resolution for the context. See pango_cairo_context_set_resolution()

context : | a PangoContext, from pango_cairo_font_map_create_context()
Returns : | the resolution in "dots per inch". A negative value will be returned if no resolution has previously been set.

Since 1.10

pango_cairo_context_set_font_options ()

void        pango_cairo_context_set_font_options
                                            (PangoContext *context,
                                             const cairo_font_options_t *options);

Sets the font options used when rendering text with this context. These options override any options that pango_cairo_update_context() derives from the target surface.

context : | a PangoContext, from pango_cairo_font_map_create_context()
options : | a cairo_font_options_t, or NULL to unset any previously set options. A copy is made.

pango_cairo_context_get_font_options ()

const cairo_font_options_t* pango_cairo_context_get_font_options
                                            (PangoContext *context);

Retrieves any font rendering options previously set with pango_cairo_font_map_set_font_options(). This functions not report options that are derived from the target surface by pango_cairo_update_context()

context : | a PangoContext, from pango_cairo_font_map_create_context()
Returns : | the font options previously set on the context, or NULL if no options have been set. This value is owned by the context and must not be modified or freed.

pango_cairo_update_context ()

void        pango_cairo_update_context      (cairo_t *cr,
                                             PangoContext *context);

Updates a PangoContext previously created for use with Cairo to match the current transformation and target surface of a Cairo context. If any layouts have been created for the context, it's necessary to call pango_layout_context_changed() on those layouts.

cr : | a Cairo context
context : | a PangoContext, from pango_cairo_font_map_create_context()

Since 1.10

pango_cairo_create_layout ()

PangoLayout* pango_cairo_create_layout      (cairo_t *cr);

Creates a layout object set up to match the current transformation and target surface of the Cairo context. This layout can then be used for text measurement with functions like pango_layout_get_size() or drawing with functions like pango_cairo_show_layout(). If you change the transformation or target surface for cr, you need to call pango_cairo_update_layout()

This function is the most convenient way to use Cairo with Pango, however it is slightly inefficient since it creates a separate PangoContext object for each layout. This might matter in an application that was laying out large amounts of text.

cr : | a Cairo context
Returns : | the newly created PangoLayout. Free with g_object_unref().

Since 1.10

pango_cairo_update_layout ()

void        pango_cairo_update_layout       (cairo_t *cr,
                                             PangoLayout *layout);

Updates the private PangoContext of a PangoLayout created with pango_cairo_create_layout() to match the current transformation and target surface of a Cairo context.

cr : | a Cairo context
layout : | a PangoLayout, from pango_cairo_create_layout()

Since 1.10

pango_cairo_show_glyph_string ()

void        pango_cairo_show_glyph_string   (cairo_t *cr,
                                             PangoFont *font,
                                             PangoGlyphString *glyphs);

Draws the glyphs in glyphs in the specified cairo context. The origin of the glyphs (the left edge of the baseline) will be drawn at the current point of the cairo context.

cr : | a Cairo context
font : | a PangoFont
glyphs : | a PangoGlyphString

Since 1.10

pango_cairo_show_layout_line ()

void        pango_cairo_show_layout_line    (cairo_t *cr,
                                             PangoLayoutLine *line);

Draws a PangoLayoutLine in the specified cairo context. The origin of the glyphs (the left edge of the line) will be drawn at the current point of the cairo context.

cr : | a Cairo context
line : | a PangoLayoutLine

Since 1.10

pango_cairo_show_layout ()

void        pango_cairo_show_layout         (cairo_t *cr,
                                             PangoLayout *layout);

Draws a PangoLayoutLine in the specified cairo context. The top-left corner of the PangoLayout will be drawn at the current point of the cairo context.

cr : | a Cairo context
layout : | a Pango layout

Since 1.10

pango_cairo_show_error_underline ()

void        pango_cairo_show_error_underline
                                            (cairo_t *cr,
                                             double x,
                                             double y,
                                             double width,
                                             double height);

Draw a squiggly line in the specified cairo context that approximately covers the given rectangle in the style of an underline used to indicate a spelling error. (The width of the underline is rounded to an integer number of up/down segments and the resulting rectangle is centered in the original rectangle)

cr : | a Cairo context
x : | The X coordinate of one corner of the rectangle
y : | The Y coordinate of one corner of the rectangle
width : | Non-negative width of the rectangle
height : | Non-negative height of the rectangle

Since 1.14

pango_cairo_glyph_string_path ()

void        pango_cairo_glyph_string_path   (cairo_t *cr,
                                             PangoFont *font,
                                             PangoGlyphString *glyphs);

Adds the glyphs in glyphs to the current path in the specified cairo context. The origin of the glyphs (the left edge of the baseline) will be at the current point of the cairo context.

cr : | a Cairo context
font : | a PangoFont
glyphs : | a PangoGlyphString

Since 1.10

pango_cairo_layout_line_path ()

void        pango_cairo_layout_line_path    (cairo_t *cr,
                                             PangoLayoutLine *line);

Adds the text in PangoLayoutLine to the current path in the specified cairo context. The origin of the glyphs (the left edge of the line) will be at the current point of the cairo context.

cr : | a Cairo context
line : | a PangoLayoutLine

Since 1.10

pango_cairo_layout_path ()

void        pango_cairo_layout_path         (cairo_t *cr,
                                             PangoLayout *layout);

Adds the text in a PangoLayout to the current path in the specified cairo context. The top-left corner of the PangoLayout will be at the current point of the cairo context.

cr : | a Cairo context
layout : | a Pango layout

Since 1.10

pango_cairo_error_underline_path ()

void        pango_cairo_error_underline_path
                                            (cairo_t *cr,
                                             double x,
                                             double y,
                                             double width,
                                             double height);

Add a squiggly line to the current path in the specified cairo context that approximately covers the given rectangle in the style of an underline used to indicate a spelling error. (The width of the underline is rounded to an integer number of up/down segments and the resulting rectangle is centered in the original rectangle)

cr : | a Cairo context
x : | The X coordinate of one corner of the rectangle
y : | The Y coordinate of one corner of the rectangle
width : | Non-negative width of the rectangle
height : | Non-negative height of the rectangle

Since 1.14


Coverage Maps

Coverage Maps — Unicode character range coverage storage

Synopsis

enum        PangoCoverageLevel;
#define     PANGO_TYPE_COVERAGE_LEVEL
            PangoCoverage;

PangoCoverage* pango_coverage_new           (void);
PangoCoverage* pango_coverage_ref           (PangoCoverage *coverage);
void        pango_coverage_unref            (PangoCoverage *coverage);
PangoCoverage* pango_coverage_copy          (PangoCoverage *coverage);
PangoCoverageLevel pango_coverage_get       (PangoCoverage *coverage,
                                             int index_);
void        pango_coverage_max              (PangoCoverage *coverage,
                                             PangoCoverage *other);
void        pango_coverage_set              (PangoCoverage *coverage,
                                             int index_,
                                             PangoCoverageLevel level);
void        pango_coverage_to_bytes         (PangoCoverage *coverage,
                                             guchar **bytes,
                                             int *n_bytes);
PangoCoverage* pango_coverage_from_bytes    (guchar *bytes,
                                             int n_bytes);

Description

It is often necessary in Pango to determine if a particular font can represent a particular character, and also how well it can represent that character. The PangoCoverage is a data structure that is used to represent that information.

Details

enum PangoCoverageLevel

typedef enum {
  PANGO_COVERAGE_NONE,
  PANGO_COVERAGE_FALLBACK,
  PANGO_COVERAGE_APPROXIMATE,
  PANGO_COVERAGE_EXACT
} PangoCoverageLevel;

Used to indicate how well a font can represent a particular Unicode character point for a particular script.

PANGO_COVERAGE_NONE | The character is not representable with the font.
PANGO_COVERAGE_FALLBACK | The character is represented in a way that may be comprehensible but is not the correct graphical form. For instance, a Hangul character represented as a a sequence of Jamos, or a Latin transliteration of a Cyrillic word.
PANGO_COVERAGE_APPROXIMATE | The character is represented as basically the correct graphical form, but with a stylistic variant inappropriate for the current script.
PANGO_COVERAGE_EXACT | The character is represented as the correct graphical form.

PANGO_TYPE_COVERAGE_LEVEL

#define PANGO_TYPE_COVERAGE_LEVEL (pango_coverage_level_get_type())

The GObject type for PangoCoverageLevel.

PangoCoverage

typedef struct _PangoCoverage PangoCoverage;

The PangoCoverage structure represents a map from Unicode characters to PangoCoverageLevel. It is an opaque structure with no public fields.

pango_coverage_new ()

PangoCoverage* pango_coverage_new           (void);

Create a new PangoCoverage

Returns : the newly allocated PangoCoverage, initialized to PANGO_COVERAGE_NONE with a reference count of one, which should be freed with pango_coverage_unref().

pango_coverage_ref ()

PangoCoverage* pango_coverage_ref           (PangoCoverage *coverage);

Increase the reference count on the PangoCoverage by one

coverage : | a PangoCoverage
Returns : | coverage

pango_coverage_unref ()

void        pango_coverage_unref            (PangoCoverage *coverage);

Increase the reference count on the PangoCoverage by one. if the result is zero, free the coverage and all associated memory.

coverage : a PangoCoverage

pango_coverage_copy ()

PangoCoverage* pango_coverage_copy          (PangoCoverage *coverage);

Copy an existing PangoCoverage. (This function may now be unnecessary since we refcount the structure. File a bug if you use it.)

coverage : | a PangoCoverage
Returns : | the newly allocated PangoCoverage, with a reference count of one, which should be freed with pango_coverage_unref().

pango_coverage_get ()

PangoCoverageLevel pango_coverage_get       (PangoCoverage *coverage,
                                             int index_);

Determine whether a particular index is covered by coverage

coverage : | a PangoCoverage
index_ : | the index to check
Returns : | the coverage level of coverage for character index_.

pango_coverage_max ()

void        pango_coverage_max              (PangoCoverage *coverage,
                                             PangoCoverage *other);

Set the coverage for each index in coverage to be the max (better) value of the current coverage for the index and the coverage for the corresponding index in other.

coverage : | a PangoCoverage
other : | another PangoCoverage

pango_coverage_set ()

void        pango_coverage_set              (PangoCoverage *coverage,
                                             int index_,
                                             PangoCoverageLevel level);

Modify a particular index within coverage

coverage : | a PangoCoverage
index_ : | the index to modify
level : | the new level for index_

pango_coverage_to_bytes ()

void        pango_coverage_to_bytes         (PangoCoverage *coverage,
                                             guchar **bytes,
                                             int *n_bytes);

Convert a PangoCoverage structure into a flat binary format

coverage : | a PangoCoverage
bytes : | location to store result (must be freed with g_free())
n_bytes : | location to store size of result

pango_coverage_from_bytes ()

PangoCoverage* pango_coverage_from_bytes    (guchar *bytes,
                                             int n_bytes);

Convert data generated from pango_converage_to_bytes() back to a PangoCoverage

bytes : | binary data representing a PangoCoverage
n_bytes : | the size of bytes in bytes
Returns : | a newly allocated PangoCoverage, or NULL if the data was invalid.


Engines

Engines — Language-specific and rendering-system-specific processing

Synopsis

            PangoEngineInfo;
            PangoEngineScriptInfo;
            PangoEngine;
            PangoEngineClass;
#define     PANGO_RENDER_TYPE_NONE
void        script_engine_list              (PangoEngineInfo **engines,
                                             int *n_engines);
void        script_engine_init              (GTypeModule *module);
void        script_engine_exit              (void);
PangoEngine* script_engine_create           (const char *id);

Object Hierarchy

  GObject
   +----PangoEngine
         +----PangoEngineLang
         +----PangoEngineShape

Description

Pango utilizes a module architecture in which the language-specific and render-system-specific components are provided by loadable modules. Each loadable module supplies one or more engines. Each engine has an associated engine type and render type. These two types are represented by strings.

Each dynamically-loaded module exports several functions which provide the public API. These functions are script_engine_list(), script_engine_init() and script_engine_exit, and script_engine_create(). The latter three functions are used when creating engines from the module at run time, while the first function is used when building a catalog of all available modules.

Details

PangoEngineInfo

typedef struct {
  const gchar *id;
  const gchar *engine_type;
  const gchar *render_type;
  PangoEngineScriptInfo *scripts;
  gint n_scripts;
} PangoEngineInfo;

The PangoEngineInfo structure contains information about a particular engine. It contains the following fields:

const gchar *id; | a unique string ID for the engine.
const gchar *engine_type; | a string identifying the engine type.
const gchar *render_type; | a string identifying the render type.
PangoEngineScriptInfo *scripts; | array of scripts this engine supports.
gint n_scripts; | number of items in scripts.

PangoEngineScriptInfo

typedef struct {
  PangoScript script;
  const gchar *langs;
} PangoEngineScriptInfo;

The PangoEngineScriptInfo structure contains information about how the shaper covers a particular script.

PangoScript script; | a PangoScript. The value PANGO_SCRIPT_COMMON has the special meaning here of "all scripts"
const gchar *langs; | a semicolon separated list of languages that this engine handles for this script. This may be empty, in which case the engine is saying that it is a fallback choice for all languages for this range, but should not be used if another engine indicates that it is specific for the language for a given code point. An entry in this list of "*" indicates that this engine is specific to all languages for this range.

PangoEngine

typedef struct _PangoEngine PangoEngine;

PangoEngine is the base class for all types of language and script specific engines. It has no functionality by itself.

PangoEngineClass

typedef struct {
} PangoEngineClass;

Class structure for PangoEngine

PANGO_RENDER_TYPE_NONE

#define PANGO_RENDER_TYPE_NONE "PangoRenderNone"

A string constant defining the render type for engines that are not rendering-system specific.

script_engine_list ()

void        script_engine_list              (PangoEngineInfo **engines,
                                             int *n_engines);

Function to be provided by a module to list the engines that the module supplies. The function stores a pointer to an array of PangoEngineInfo structures and the length of that array in the given location.

Note that script_engine_init() will not be called before this function.

engines : | location to store a pointer to an array of engines.
n_engines : | location to store the number of elements in engines.

script_engine_init ()

void        script_engine_init              (GTypeModule *module);

Function to be provided by a module to register any GObject types in the module.

module : a GTypeModule structure used to associate any GObject types created in this module with the module.

script_engine_exit ()

void        script_engine_exit              (void);

Function to be provided by the module that is called when the module is unloading. Frequently does nothing.

script_engine_create ()

PangoEngine* script_engine_create           (const char *id);

Function to be provided by the module to create an instance of one of the engines implemented by the module.

id : | the ID of an engine as reported by script_engine_list.
Returns : | a newly created PangoEngine of the specified type, or NULL if an error occurred. (In normal operation, a module should not return NULL. A NULL return is only acceptable in the case where system misconfiguration or bugs in the driver routine are encountered.)


Fonts

Fonts — Structures representing abstract fonts

Synopsis

            PangoFontDescription;
#define     PANGO_TYPE_FONT_DESCRIPTION
enum        PangoStyle;
#define     PANGO_TYPE_STYLE
enum        PangoWeight;
#define     PANGO_TYPE_WEIGHT
enum        PangoVariant;
#define     PANGO_TYPE_VARIANT
enum        PangoStretch;
#define     PANGO_TYPE_STRETCH
enum        PangoFontMask;
#define     PANGO_TYPE_FONT_MASK
PangoFontDescription* pango_font_description_new
                                            (void);
PangoFontDescription* pango_font_description_copy
                                            (const PangoFontDescription *desc);
PangoFontDescription* pango_font_description_copy_static
                                            (const PangoFontDescription *desc);
guint       pango_font_description_hash     (const PangoFontDescription *desc);
gboolean    pango_font_description_equal    (const PangoFontDescription *desc1,
                                             const PangoFontDescription *desc2);
void        pango_font_description_free     (PangoFontDescription *desc);
void        pango_font_descriptions_free    (PangoFontDescription **descs,
                                             int n_descs);
void        pango_font_description_set_family
                                            (PangoFontDescription *desc,
                                             const char *family);
void        pango_font_description_set_family_static
                                            (PangoFontDescription *desc,
                                             const char *family);
const char* pango_font_description_get_family
                                            (const PangoFontDescription *desc);
void        pango_font_description_set_style
                                            (PangoFontDescription *desc,
                                             PangoStyle style);
PangoStyle  pango_font_description_get_style
                                            (const PangoFontDescription *desc);
void        pango_font_description_set_variant
                                            (PangoFontDescription *desc,
                                             PangoVariant variant);
PangoVariant pango_font_description_get_variant
                                            (const PangoFontDescription *desc);
void        pango_font_description_set_weight
                                            (PangoFontDescription *desc,
                                             PangoWeight weight);
PangoWeight pango_font_description_get_weight
                                            (const PangoFontDescription *desc);
void        pango_font_description_set_stretch
                                            (PangoFontDescription *desc,
                                             PangoStretch stretch);
PangoStretch pango_font_description_get_stretch
                                            (const PangoFontDescription *desc);
void        pango_font_description_set_size (PangoFontDescription *desc,
                                             gint size);
gint        pango_font_description_get_size (const PangoFontDescription *desc);
void        pango_font_description_set_absolute_size
                                            (PangoFontDescription *desc,
                                             double size);
gboolean    pango_font_description_get_size_is_absolute
                                            (const PangoFontDescription *desc);
void        pango_font_description_set_gravity
                                            (PangoFontDescription *desc,
                                             PangoGravity gravity);
PangoGravity pango_font_description_get_gravity
                                            (const PangoFontDescription *desc);
PangoFontMask pango_font_description_get_set_fields
                                            (const PangoFontDescription *desc);
void        pango_font_description_unset_fields
                                            (PangoFontDescription *desc,
                                             PangoFontMask to_unset);
void        pango_font_description_merge    (PangoFontDescription *desc,
                                             const PangoFontDescription *desc_to_merge,
                                             gboolean replace_existing);
void        pango_font_description_merge_static
                                            (PangoFontDescription *desc,
                                             const PangoFontDescription *desc_to_merge,
                                             gboolean replace_existing);
gboolean    pango_font_description_better_match
                                            (const PangoFontDescription *desc,
                                             const PangoFontDescription *old_match,
                                             const PangoFontDescription *new_match);
PangoFontDescription* pango_font_description_from_string
                                            (const char *str);
char*       pango_font_description_to_string
                                            (const PangoFontDescription *desc);
char*       pango_font_description_to_filename
                                            (const PangoFontDescription *desc);

            PangoFontMetrics;
#define     PANGO_TYPE_FONT_METRICS
PangoFontMetrics* pango_font_metrics_ref    (PangoFontMetrics *metrics);
void        pango_font_metrics_unref        (PangoFontMetrics *metrics);
int         pango_font_metrics_get_ascent   (PangoFontMetrics *metrics);
int         pango_font_metrics_get_descent  (PangoFontMetrics *metrics);
int         pango_font_metrics_get_approximate_char_width
                                            (PangoFontMetrics *metrics);
int         pango_font_metrics_get_approximate_digit_width
                                            (PangoFontMetrics *metrics);
int         pango_font_metrics_get_underline_thickness
                                            (PangoFontMetrics *metrics);
int         pango_font_metrics_get_underline_position
                                            (PangoFontMetrics *metrics);
int         pango_font_metrics_get_strikethrough_thickness
                                            (PangoFontMetrics *metrics);
int         pango_font_metrics_get_strikethrough_position
                                            (PangoFontMetrics *metrics);

            PangoFont;
#define     PANGO_TYPE_FONT
#define     PANGO_FONT                      (object)
#define     PANGO_IS_FONT                   (object)
PangoEngineShape* pango_font_find_shaper    (PangoFont *font,
                                             PangoLanguage *language,
                                             guint32 ch);
PangoFontDescription* pango_font_describe   (PangoFont *font);
PangoFontDescription* pango_font_describe_with_absolute_size
                                            (PangoFont *font);
PangoCoverage* pango_font_get_coverage      (PangoFont *font,
                                             PangoLanguage *language);
void        pango_font_get_glyph_extents    (PangoFont *font,
                                             PangoGlyph glyph,
                                             PangoRectangle *ink_rect,
                                             PangoRectangle *logical_rect);
PangoFontMetrics* pango_font_get_metrics    (PangoFont *font,
                                             PangoLanguage *language);
PangoFontMap* pango_font_get_font_map       (PangoFont *font);

            PangoFontFamily;
#define     PANGO_TYPE_FONT_FAMILY
#define     PANGO_FONT_FAMILY               (object)
#define     PANGO_IS_FONT_FAMILY            (object)
const char* pango_font_family_get_name      (PangoFontFamily *family);
gboolean    pango_font_family_is_monospace  (PangoFontFamily *family);
void        pango_font_family_list_faces    (PangoFontFamily *family,
                                             PangoFontFace ***faces,
                                             int *n_faces);

            PangoFontFace;
#define     PANGO_TYPE_FONT_FACE
#define     PANGO_FONT_FACE                 (object)
#define     PANGO_IS_FONT_FACE              (object)
const char* pango_font_face_get_face_name   (PangoFontFace *face);
void        pango_font_face_list_sizes      (PangoFontFace *face,
                                             int **sizes,
                                             int *n_sizes);
PangoFontDescription* pango_font_face_describe
                                            (PangoFontFace *face);

            PangoFontMap;
#define     PANGO_TYPE_FONT_MAP
#define     PANGO_FONT_MAP                  (object)
#define     PANGO_IS_FONT_MAP               (object)
            PangoFontMapClass;
#define     PANGO_FONT_MAP_CLASS            (klass)
#define     PANGO_IS_FONT_MAP_CLASS         (klass)
#define     PANGO_FONT_MAP_GET_CLASS        (obj)
PangoFont*  pango_font_map_load_font        (PangoFontMap *fontmap,
                                             PangoContext *context,
                                             const PangoFontDescription *desc);
PangoFontset* pango_font_map_load_fontset   (PangoFontMap *fontmap,
                                             PangoContext *context,
                                             const PangoFontDescription *desc,
                                             PangoLanguage *language);
void        pango_font_map_list_families    (PangoFontMap *fontmap,
                                             PangoFontFamily ***families,
                                             int *n_families);
const char* pango_font_map_get_shape_engine_type
                                            (PangoFontMap *fontmap);

            PangoFontset;
#define     PANGO_TYPE_FONTSET
            PangoFontsetClass;
PangoFont*  pango_fontset_get_font          (PangoFontset *fontset,
                                             guint wc);
PangoFontMetrics* pango_fontset_get_metrics (PangoFontset *fontset);
gboolean    (*PangoFontsetForeachFunc)      (PangoFontset *fontset,
                                             PangoFont *font,
                                             gpointer data);
void        pango_fontset_foreach           (PangoFontset *fontset,
                                             PangoFontsetForeachFunc func,
                                             gpointer data);
            PangoFontsetSimple;
#define     PANGO_TYPE_FONTSET_SIMPLE
PangoFontsetSimple* pango_fontset_simple_new
                                            (PangoLanguage *language);
void        pango_fontset_simple_append     (PangoFontsetSimple *fontset,
                                             PangoFont *font);
int         pango_fontset_simple_size       (PangoFontsetSimple *fontset);

Object Hierarchy

  GObject
   +----PangoFont
         +----PangoFcFont

  GObject
   +----PangoFontFamily

  GObject
   +----PangoFontFace

  GObject
   +----PangoFontMap
         +----PangoFcFontMap

  GObject
   +----PangoFontset
         +----PangoFontsetSimple

  GObject
   +----PangoFontset
         +----PangoFontsetSimple

Known Derived Interfaces

PangoFontMap is required by PangoCairoFontMap.

Description

Pango supports a flexible architecture where a particular rendering architecture can supply an implementation of fonts. The PangoFont structure represents an abstract rendering-system-independent font. Pango provides routines to list available fonts, and to load a font of a given description.

Details

PangoFontDescription

typedef struct _PangoFontDescription PangoFontDescription;

The PangoFontDescription structure represents the description of an ideal font. These structures are used both to list what fonts are available on the system and also for specifying the characteristics of a font to load.

PANGO_TYPE_FONT_DESCRIPTION

#define PANGO_TYPE_FONT_DESCRIPTION (pango_font_description_get_type ())

The GObject type for PangoFontDescription.

enum PangoStyle

typedef enum {
  PANGO_STYLE_NORMAL,
  PANGO_STYLE_OBLIQUE,
  PANGO_STYLE_ITALIC
} PangoStyle;

An enumeration specifying the various slant styles possible for a font.

PANGO_STYLE_NORMAL | the font is upright.
PANGO_STYLE_OBLIQUE | the font is slanted, but in a roman style.
PANGO_STYLE_ITALIC | the font is slanted in an italic style.

PANGO_TYPE_STYLE

#define PANGO_TYPE_STYLE (pango_style_get_type())

The GObject type for PangoStyle.

enum PangoWeight

typedef enum {
  PANGO_WEIGHT_ULTRALIGHT = 200,
  PANGO_WEIGHT_LIGHT = 300,
  PANGO_WEIGHT_NORMAL = 400,
  PANGO_WEIGHT_SEMIBOLD = 600,
  PANGO_WEIGHT_BOLD = 700,
  PANGO_WEIGHT_ULTRABOLD = 800,
  PANGO_WEIGHT_HEAVY = 900
} PangoWeight;

An enumeration specifying the weight (boldness) of a font. This is a numerical value ranging from 100 to 900, but there are some predefined values:

PANGO_WEIGHT_ULTRALIGHT | the ultralight weight (= 200)
PANGO_WEIGHT_LIGHT | the light weight (=300)
PANGO_WEIGHT_NORMAL | the default weight (= 400)
PANGO_WEIGHT_SEMIBOLD | a weight intermediate between normal and bold (=600)
PANGO_WEIGHT_BOLD | the bold weight (= 700)
PANGO_WEIGHT_ULTRABOLD | the ultrabold weight (= 800)
PANGO_WEIGHT_HEAVY | the heavy weight (= 900)

PANGO_TYPE_WEIGHT

#define PANGO_TYPE_WEIGHT (pango_weight_get_type())

The GObject type for PangoWeight.

enum PangoVariant

typedef enum {
  PANGO_VARIANT_NORMAL,
  PANGO_VARIANT_SMALL_CAPS
} PangoVariant;

An enumeration specifying capitalization variant of the font.

PANGO_VARIANT_NORMAL | A normal font.
PANGO_VARIANT_SMALL_CAPS | A font with the lower case characters replaced by smaller variants of the capital characters.

PANGO_TYPE_VARIANT

#define PANGO_TYPE_VARIANT (pango_variant_get_type())

The GObject type for PangoVariant.

enum PangoStretch

typedef enum {
  PANGO_STRETCH_ULTRA_CONDENSED,
  PANGO_STRETCH_EXTRA_CONDENSED,
  PANGO_STRETCH_CONDENSED,
  PANGO_STRETCH_SEMI_CONDENSED,
  PANGO_STRETCH_NORMAL,
  PANGO_STRETCH_SEMI_EXPANDED,
  PANGO_STRETCH_EXPANDED,
  PANGO_STRETCH_EXTRA_EXPANDED,
  PANGO_STRETCH_ULTRA_EXPANDED
} PangoStretch;

An enumeration specifying the width of the font relative to other designs within a family.

PANGO_STRETCH_ULTRA_CONDENSED | ultra condensed width
PANGO_STRETCH_EXTRA_CONDENSED | extra condensed width
PANGO_STRETCH_CONDENSED | condensed width
PANGO_STRETCH_SEMI_CONDENSED | semi condensed width
PANGO_STRETCH_NORMAL | the normal width
PANGO_STRETCH_SEMI_EXPANDED | semi expanded width
PANGO_STRETCH_EXPANDED | expanded width
PANGO_STRETCH_EXTRA_EXPANDED | extra expanded width
PANGO_STRETCH_ULTRA_EXPANDED | ultra expanded width

PANGO_TYPE_STRETCH

#define PANGO_TYPE_STRETCH (pango_stretch_get_type())

The GObject type for PangoStretch.

enum PangoFontMask

typedef enum {
  PANGO_FONT_MASK_FAMILY  = 1 << 0,
  PANGO_FONT_MASK_STYLE   = 1 << 1,
  PANGO_FONT_MASK_VARIANT = 1 << 2,
  PANGO_FONT_MASK_WEIGHT  = 1 << 3,
  PANGO_FONT_MASK_STRETCH = 1 << 4,
  PANGO_FONT_MASK_SIZE    = 1 << 5,
  PANGO_FONT_MASK_GRAVITY = 1 << 6
} PangoFontMask;

The bits in a PangoFontMask correspond to fields in a PangoFontDescription that have been set.

PANGO_FONT_MASK_FAMILY | the font family is specified.
PANGO_FONT_MASK_STYLE | the font style is specified.
PANGO_FONT_MASK_VARIANT | the font variant is specified.
PANGO_FONT_MASK_WEIGHT | the font weight is specified.
PANGO_FONT_MASK_STRETCH | the font stretch is specified.
PANGO_FONT_MASK_SIZE | the font size is specified.
PANGO_FONT_MASK_GRAVITY | the font gravity is specified (Since: 1.16.)

PANGO_TYPE_FONT_MASK

#define PANGO_TYPE_FONT_MASK (pango_font_mask_get_type())

The GObject type for PangoFontMask.

pango_font_description_new ()

PangoFontDescription* pango_font_description_new
                                            (void);

Creates a new font description structure with all fields unset.

Returns : the newly allocated PangoFontDescription, which should be freed using pango_font_description_free().

pango_font_description_copy ()

PangoFontDescription* pango_font_description_copy
                                            (const PangoFontDescription *desc);

Make a copy of a PangoFontDescription.

desc : | a PangoFontDescription
Returns : | the newly allocated PangoFontDescription, which should be freed with pango_font_description_free().

pango_font_description_copy_static ()

PangoFontDescription* pango_font_description_copy_static
                                            (const PangoFontDescription *desc);

Like pango_font_description_copy(), but only a shallow copy is made of the family name and other allocated fields. The result can only be used until desc is modified or freed. This is meant to be used when the copy is only needed temporarily.

desc : | a PangoFontDescription
Returns : | the newly allocated PangoFontDescription, which should be freed with pango_font_description_free().

pango_font_description_hash ()

guint       pango_font_description_hash     (const PangoFontDescription *desc);

Computes a hash of a PangoFontDescription structure suitable to be used, for example, as an argument to g_hash_table_new(). The hash value is independent of desc->mask.

desc : | a PangoFontDescription
Returns : | the hash value.

pango_font_description_equal ()

gboolean    pango_font_description_equal    (const PangoFontDescription *desc1,
                                             const PangoFontDescription *desc2);

Compares two font descriptions for equality. Two font descriptions are considered equal if the fonts they describe are provably identical. This means that their masks do not have to match, as long as other fields are all the same. (Two font descriptions may result in identical fonts being loaded, but still compare FALSE.)

desc1 : | a PangoFontDescription
desc2 : | another PangoFontDescription
Returns : | TRUE if the two font descriptions are identical, FALSE otherwise.

pango_font_description_free ()

void        pango_font_description_free     (PangoFontDescription *desc);

Frees a font description.

desc : a PangoFontDescription

pango_font_descriptions_free ()

void        pango_font_descriptions_free    (PangoFontDescription **descs,
                                             int n_descs);

Frees a list of font descriptions from pango_font_map_list_fonts()

descs : | a pointer to an array of PangoFontDescription
n_descs : | number of font descriptions in descs

pango_font_description_set_family ()

void        pango_font_description_set_family
                                            (PangoFontDescription *desc,
                                             const char *family);

Sets the family name field of a font description. The family name represents a family of related font styles, and will resolve to a particular PangoFontFamily. In some uses of PangoFontDescription, it is also possible to use a comma separated list of family names for this field.

desc : | a PangoFontDescription.
family : | a string representing the family name.

pango_font_description_set_family_static ()

void        pango_font_description_set_family_static
                                            (PangoFontDescription *desc,
                                             const char *family);

Like pango_font_description_set_family(), except that no copy of family is made. The caller must make sure that the string passed in stays around until desc has been freed or the name is set again. This function can be used if family is a static string such as a C string literal, or if desc is only needed temporarily.

desc : | a PangoFontDescription
family : | a string representing the family name.

pango_font_description_get_family ()

const char* pango_font_description_get_family
                                            (const PangoFontDescription *desc);

Gets the family name field of a font description. See pango_font_description_set_family().

desc : | a PangoFontDescription.
Returns : | the family name field for the font description, or NULL if not previously set. This has the same life-time as the font description itself and should not be freed.

pango_font_description_set_style ()

void        pango_font_description_set_style
                                            (PangoFontDescription *desc,
                                             PangoStyle style);

Sets the style field of a PangoFontDescription. The PangoStyle enumeration describes whether the font is slanted and the manner in which it is slanted; it can be either PANGO_STYLE_NORMAL, PANGO_STYLE_ITALIC, or PANGO_STYLE_OBLIQUE. Most fonts will either have a italic style or an oblique style, but not both, and font matching in Pango will match italic specifications with oblique fonts and vice-versa if an exact match is not found.

desc : | a PangoFontDescription
style : | the style for the font description

pango_font_description_get_style ()

PangoStyle  pango_font_description_get_style
                                            (const PangoFontDescription *desc);

Gets the style field of a PangoFontDescription. See pango_font_description_set_style().

desc : | a PangoFontDescription
Returns : | the style field for the font description. Use pango_font_description_get_set_fields() to find out if the field was explicitly set or not.

pango_font_description_set_variant ()

void        pango_font_description_set_variant
                                            (PangoFontDescription *desc,
                                             PangoVariant variant);

Sets the variant field of a font description. The PangoVariant can either be PANGO_VARIANT_NORMAL or PANGO_VARIANT_SMALL_CAPS.

desc : | a PangoFontDescription
variant : | the variant type for the font description.

pango_font_description_get_variant ()

PangoVariant pango_font_description_get_variant
                                            (const PangoFontDescription *desc);

Gets the variant field of a PangoFontDescription. See pango_font_description_set_variant().

desc : | a PangoFontDescription.
Returns : | the variant field for the font description. Use pango_font_description_get_set_fields() to find out if the field was explicitly set or not.

pango_font_description_set_weight ()

void        pango_font_description_set_weight
                                            (PangoFontDescription *desc,
                                             PangoWeight weight);

Sets the weight field of a font description. The weight field specifies how bold or light the font should be. In addition to the values of the PangoWeight enumeration, other intermediate numeric values are possible.

desc : | a PangoFontDescription
weight : | the weight for the font description.

pango_font_description_get_weight ()

PangoWeight pango_font_description_get_weight
                                            (const PangoFontDescription *desc);

Gets the weight field of a font description. See pango_font_description_set_weight().

desc : | a PangoFontDescription
Returns : | the weight field for the font description. Use pango_font_description_get_set_fields() to find out if the field was explicitly set or not.

pango_font_description_set_stretch ()

void        pango_font_description_set_stretch
                                            (PangoFontDescription *desc,
                                             PangoStretch stretch);

Sets the stretch field of a font description. The stretch field specifies how narrow or wide the font should be.

desc : | a PangoFontDescription
stretch : | the stretch for the font description

pango_font_description_get_stretch ()

PangoStretch pango_font_description_get_stretch
                                            (const PangoFontDescription *desc);

Gets the stretch field of a font description. See pango_font_description_set_stretch().

desc : | a PangoFontDescription.
Returns : | the stretch field for the font description. Use pango_font_description_get_set_fields() to find out if the field was explicitly set or not.

pango_font_description_set_size ()

void        pango_font_description_set_size (PangoFontDescription *desc,
                                             gint size);

Sets the size field of a font description in fractional points. This is mutually exclusive with pango_font_description_set_absolute_size().

desc : | a PangoFontDescription
size : | the size of the font in points, scaled by PANGO_SCALE. (That is, a size value of 10 * PANGO_SCALE is a 10 point font. The conversion factor between points and device units depends on system configuration and the output device. For screen display, a logical DPI of 96 is common, in which case a 10 point font corresponds to a 10 * (96 / 72) = 13.3 pixel font. Use pango_font_description_set_absolute_size() if you need a particular size in device units.

pango_font_description_get_size ()

gint        pango_font_description_get_size (const PangoFontDescription *desc);

Gets the size field of a font description. See pango_font_description_set_size().

desc : | a PangoFontDescription
Returns : | the size field for the font description in points or device units. You must call pango_font_description_get_size_is_absolute() to find out which is the case. Returns 0 if the size field has not previously been set or it has been set to 0 explicitly. Use pango_font_description_get_set_fields() to find out if the field was explicitly set or not.

pango_font_description_set_absolute_size ()

void        pango_font_description_set_absolute_size
                                            (PangoFontDescription *desc,
                                             double size);

Sets the size field of a font description, in device units. This is mutually exclusive with pango_font_description_set_size().

desc : | a PangoFontDescription
size : | the new size, in Pango units. There are PANGO_SCALE Pango units in one device unit. For an output backend where a device unit is a pixel, a size value of 10 * PANGO_SCALE gives a 10 pixel font.

Since 1.8

pango_font_description_get_size_is_absolute ()

gboolean    pango_font_description_get_size_is_absolute
                                            (const PangoFontDescription *desc);

Determines whether the size of the font is in points or device units. See pango_font_description_set_size() and pango_font_description_set_absolute_size().

desc : | a PangoFontDescription
Returns : | whether the size for the font description is in points or device units. Use pango_font_description_get_set_fields() to find out if the size field of the font description was explicitly set or not.

Since 1.8

pango_font_description_set_gravity ()

void        pango_font_description_set_gravity
                                            (PangoFontDescription *desc,
                                             PangoGravity gravity);

Sets the gravity field of a font description. The gravity field specifies how the glyphs should be rotated. If gravity is PANGO_GRAVITY_AUTO, this actually unsets the gravity mask on the font description.

This function is seldom useful to the user. Gravity should normally be set on a PangoContext.

desc : | a PangoFontDescription
gravity : | the gravity for the font description.

Since 1.16

pango_font_description_get_gravity ()

PangoGravity pango_font_description_get_gravity
                                            (const PangoFontDescription *desc);

Gets the gravity field of a font description. See pango_font_description_set_gravity().

desc : | a PangoFontDescription
Returns : | the gravity field for the font description. Use pango_font_description_get_set_fields() to find out if the field was explicitly set or not.

Since 1.16

pango_font_description_get_set_fields ()

PangoFontMask pango_font_description_get_set_fields
                                            (const PangoFontDescription *desc);

Determines which fields in a font description have been set.

desc : | a PangoFontDescription
Returns : | a bitmask with bits set corresponding to the fields in desc that have been set.

pango_font_description_unset_fields ()

void        pango_font_description_unset_fields
                                            (PangoFontDescription *desc,
                                             PangoFontMask to_unset);

Unsets some of the fields in a PangoFontDescription. The unset fields will get back to their default values.

desc : | a PangoFontDescription
to_unset : | bitmask of fields in the desc to unset.

pango_font_description_merge ()

void        pango_font_description_merge    (PangoFontDescription *desc,
                                             const PangoFontDescription *desc_to_merge,
                                             gboolean replace_existing);

Merges the fields that are set in desc_to_merge into the fields in desc. If replace_existing is FALSE, only fields in desc that are not already set are affected. If TRUE, then fields that are already set will be replaced as well.

desc : | a PangoFontDescription
desc_to_merge : | the PangoFontDescription to merge from
replace_existing : | if TRUE, replace fields in desc with the corresponding values from desc_to_merge, even if they are already exist.

pango_font_description_merge_static ()

void        pango_font_description_merge_static
                                            (PangoFontDescription *desc,
                                             const PangoFontDescription *desc_to_merge,
                                             gboolean replace_existing);

Like pango_font_description_merge(), but only a shallow copy is made of the family name and other allocated fields. desc can only be used until desc_to_merge is modified or freed. This is meant to be used when the merged font description is only needed temporarily.

desc : | a PangoFontDescription
desc_to_merge : | the PangoFontDescription to merge from
replace_existing : | if TRUE, replace fields in desc with the corresponding values from desc_to_merge, even if they are already exist.

pango_font_description_better_match ()

gboolean    pango_font_description_better_match
                                            (const PangoFontDescription *desc,
                                             const PangoFontDescription *old_match,
                                             const PangoFontDescription *new_match);

Determines if the style attributes of new_match are a closer match for desc than old_match, or if old_match is NULL, determines if new_match is a match at all. Approximate matching is done for weight and style; other attributes must match exactly.

desc : | a PangoFontDescription
old_match : | a PangoFontDescription, or NULL
new_match : | a PangoFontDescription
Returns : | TRUE if new_match is a better match

pango_font_description_from_string ()

PangoFontDescription* pango_font_description_from_string
                                            (const char *str);

Creates a new font description from a string representation in the form "[FAMILY-LIST] [STYLE-OPTIONS] [SIZE]", where FAMILY-LIST is a comma separated list of families optionally terminated by a comma, STYLE_OPTIONS is a whitespace separated list of words where each WORD describes one of style, variant, weight, stretch, or gravity, and SIZE is a decimal number (size in points) or optionally followed by the unit modifier "px" for absolute size. Any one of the options may be absent. If FAMILY-LIST is absent, then the family_name field of the resulting font description will be initialized to NULL. If STYLE-OPTIONS is missing, then all style options will be set to the default values. If SIZE is missing, the size in the resulting font description will be set to 0.

str : | string representation of a font description.
Returns : | a new PangoFontDescription.

pango_font_description_to_string ()

char*       pango_font_description_to_string
                                            (const PangoFontDescription *desc);

Creates a string representation of a font description. See pango_font_description_from_string() for a description of the format of the string representation. The family list in the string description will only have a terminating comma if the last word of the list is a valid style option.

desc : | a PangoFontDescription
Returns : | a new string that must be freed with g_free().

pango_font_description_to_filename ()

char*       pango_font_description_to_filename
                                            (const PangoFontDescription *desc);

Creates a filename representation of a font description. The filename is identical to the result from calling pango_font_description_to_string(), but with underscores instead of characters that are untypical in filenames, and in lower case only.

desc : | a PangoFontDescription
Returns : | a new string that must be freed with g_free().

PangoFontMetrics

typedef struct {
  guint ref_count;

  int ascent;
  int descent;
  int approximate_char_width;
  int approximate_digit_width;
  int underline_position;
  int underline_thickness;
  int strikethrough_position;
  int strikethrough_thickness;
} PangoFontMetrics;

A PangoFontMetrics structure holds the overall metric information for a font (possibly restricted to a script). The fields of this structure are private to implementations of a font backend. See the documentation of the corresponding getters for documentation of their meaning.

guint ref_count; | reference count. Used internally. See pango_font_metrics_ref() and pango_font_metrics_unref().
int ascent; | the distance from the baseline to the highest point of the glyphs of the font. This is positive in practically all fonts.
int descent; | the distance from the baseline to the lowest point of the glyphs of the font. This is positive in practically all fonts.
int approximate_char_width; | approximate average width of the regular glyphs of the font.
int approximate_digit_width; | approximate average width of the glyphs for digits of the font.
int underline_position; | position of the underline. This is normally negative.
int underline_thickness; | thickness of the underline.
int strikethrough_position; | position of the strikethrough line. This is normally positive.
int strikethrough_thickness; | thickness of the strikethrough line.

PANGO_TYPE_FONT_METRICS

#define PANGO_TYPE_FONT_METRICS  (pango_font_metrics_get_type ())

The GObject type for PangoFontMetrics.

pango_font_metrics_ref ()

PangoFontMetrics* pango_font_metrics_ref    (PangoFontMetrics *metrics);

Increase the reference count of a font metrics structure by one.

metrics : | a PangoFontMetrics structure
Returns : | metrics

pango_font_metrics_unref ()

void        pango_font_metrics_unref        (PangoFontMetrics *metrics);

Decrease the reference count of a font metrics structure by one. If the result is zero, frees the structure and any associated memory.

metrics : a PangoFontMetrics structure

pango_font_metrics_get_ascent ()

int         pango_font_metrics_get_ascent   (PangoFontMetrics *metrics);

Gets the ascent from a font metrics structure. The ascent is the distance from the baseline to the logical top of a line of text. (The logical top may be above or below the top of the actual drawn ink. It is necessary to lay out the text to figure where the ink will be.)

metrics : | a PangoFontMetrics structure
Returns : | the ascent, in Pango units. (1 point == PANGO_SCALE Pango units.)

pango_font_metrics_get_descent ()

int         pango_font_metrics_get_descent  (PangoFontMetrics *metrics);

Gets the descent from a font metrics structure. The descent is the distance from the baseline to the logical bottom of a line of text. (The logical bottom may be above or below the bottom of the actual drawn ink. It is necessary to lay out the text to figure where the ink will be.)

metrics : | a PangoFontMetrics structure
Returns : | the descent, in Pango units. (1 point == PANGO_SCALE Pango units.)

pango_font_metrics_get_approximate_char_width ()

int         pango_font_metrics_get_approximate_char_width
                                            (PangoFontMetrics *metrics);

Gets the approximate character width for a font metrics structure. This is merely a representative value useful, for example, for determining the initial size for a window. Actual characters in text will be wider and narrower than this.

metrics : | a PangoFontMetrics structure
Returns : | the character width, in Pango units. (1 point == PANGO_SCALE Pango units.)

pango_font_metrics_get_approximate_digit_width ()

int         pango_font_metrics_get_approximate_digit_width
                                            (PangoFontMetrics *metrics);

Gets the approximate digit width for a font metrics structure. This is merely a representative value useful, for example, for determining the initial size for a window. Actual digits in text can be wider or narrower than this, though this value is generally somewhat more accurate than the result of pango_font_metrics_get_approximate_char_width() for digits.

metrics : | a PangoFontMetrics structure
Returns : | the digit width, in Pango units. (1 point == PANGO_SCALE Pango units.)

pango_font_metrics_get_underline_thickness ()

int         pango_font_metrics_get_underline_thickness
                                            (PangoFontMetrics *metrics);

Gets the suggested thickness to draw for the underline.

metrics : | a PangoFontMetrics structure
Returns : | the suggested underline thickness, in Pango units.

Since 1.6

pango_font_metrics_get_underline_position ()

int         pango_font_metrics_get_underline_position
                                            (PangoFontMetrics *metrics);

Gets the suggested position to draw the underline. The value returned is the distance above the baseline of the top of the underline. Since most fonts have underline positions beneath the baseline, this value is typically negative.

metrics : | a PangoFontMetrics structure
Returns : | the suggested underline position, in Pango units.

Since 1.6

pango_font_metrics_get_strikethrough_thickness ()

int         pango_font_metrics_get_strikethrough_thickness
                                            (PangoFontMetrics *metrics);

Gets the suggested thickness to draw for the strikethrough.

metrics : | a PangoFontMetrics structure
Returns : | the suggested strikethrough thickness, in Pango units.

Since 1.6

pango_font_metrics_get_strikethrough_position ()

int         pango_font_metrics_get_strikethrough_position
                                            (PangoFontMetrics *metrics);

Gets the suggested position to draw the strikethrough. The value returned is the distance above the baseline of the top of the strikethrough.

metrics : | a PangoFontMetrics structure
Returns : | the suggested strikethrough position, in Pango units.

Since 1.6

PangoFont

typedef struct _PangoFont PangoFont;

The PangoFont structure is used to represent a font in a rendering-system-independent matter. To create an implementation of a PangoFont, the rendering-system specific code should allocate a larger structure that contains a nested PangoFont, fill in the klass member of the nested PangoFont with a pointer to a appropriate PangoFontClass, then call pango_font_init() on the structure.

The PangoFont structure contains one member which the implementation fills in.

PANGO_TYPE_FONT

#define PANGO_TYPE_FONT              (pango_font_get_type ())

The GObject type for PangoFont.

PANGO_FONT()

#define PANGO_FONT(object)           (G_TYPE_CHECK_INSTANCE_CAST ((object), PANGO_TYPE_FONT, PangoFont))

Casts a GObject to a PangoFont.

object : a GObject.

PANGO_IS_FONT()

#define PANGO_IS_FONT(object)        (G_TYPE_CHECK_INSTANCE_TYPE ((object), PANGO_TYPE_FONT))

Returns TRUE if object is a PangoFont.

object : a GObject.

pango_font_find_shaper ()

PangoEngineShape* pango_font_find_shaper    (PangoFont *font,
                                             PangoLanguage *language,
                                             guint32 ch);

Finds the best matching shaper for a font for a particular language tag and character point.

font : | a PangoFont
language : | the language tag
ch : | a Unicode character.
Returns : | the best matching shaper.

pango_font_describe ()

PangoFontDescription* pango_font_describe   (PangoFont *font);

Returns a description of the font, with font size set in points. Use pango_font_describe_with_absolute_size() if you want the font size in device units.

font : | a PangoFont
Returns : | a newly-allocated PangoFontDescription object.

pango_font_describe_with_absolute_size ()

PangoFontDescription* pango_font_describe_with_absolute_size
                                            (PangoFont *font);

Returns a description of the font, with absolute font size set (in device units). Use pango_font_describe() if you want the font size in points.

font : | a PangoFont
Returns : | a newly-allocated PangoFontDescription object.

Since 1.14

pango_font_get_coverage ()

PangoCoverage* pango_font_get_coverage      (PangoFont *font,
                                             PangoLanguage *language);

Computes the coverage map for a given font and language tag.

font : | a PangoFont
language : | the language tag
Returns : | a newly-allocated PangoCoverage object.

pango_font_get_glyph_extents ()

void        pango_font_get_glyph_extents    (PangoFont *font,
                                             PangoGlyph glyph,
                                             PangoRectangle *ink_rect,
                                             PangoRectangle *logical_rect);

Gets the logical and ink extents of a glyph within a font. The coordinate system for each rectangle has its origin at the base line and horizontal origin of the character with increasing coordinates extending to the right and down. The macros PANGO_ASCENT(), PANGO_DESCENT(), PANGO_LBEARING(), and PANGO_RBEARING() can be used to convert from the extents rectangle to more traditional font metrics. The units of the rectangles are in 1/PANGO_SCALE of a device unit.

font : | a PangoFont
glyph : | the glyph index
ink_rect : | rectangle used to store the extents of the glyph as drawn or NULL to indicate that the result is not needed.
logical_rect : | rectangle used to store the logical extents of the glyph or NULL to indicate that the result is not needed.

pango_font_get_metrics ()

PangoFontMetrics* pango_font_get_metrics    (PangoFont *font,
                                             PangoLanguage *language);

Gets overall metric information for a font. Since the metrics may be substantially different for different scripts, a language tag can be provided to indicate that the metrics should be retrieved that correspond to the script(s) used by that language.

font : | a PangoFont
language : | language tag used to determine which script to get the metrics for, or NULL to indicate to get the metrics for the entire font.
Returns : | a PangoFontMetrics object. The caller must call pango_font_metrics_unref() when finished using the object.

pango_font_get_font_map ()

PangoFontMap* pango_font_get_font_map       (PangoFont *font);

Gets the font map for which the font was created.

font : | a PangoFont
Returns : | the PangoFontMap for the font

Since 1.10

PangoFontFamily

typedef struct _PangoFontFamily PangoFontFamily;

The PangoFontFamily structure is used to represent a family of related font faces. The faces in a family share a common design, but differ in slant, weight, width and other aspects.

PANGO_TYPE_FONT_FAMILY

#define PANGO_TYPE_FONT_FAMILY              (pango_font_family_get_type ())

The GObject type for PangoFontFamily.

PANGO_FONT_FAMILY()

#define PANGO_FONT_FAMILY(object)           (G_TYPE_CHECK_INSTANCE_CAST ((object), PANGO_TYPE_FONT_FAMILY, PangoFontFamily))

Casts a GObject to a PangoFontFamily.

object : a GObject.

PANGO_IS_FONT_FAMILY()

#define PANGO_IS_FONT_FAMILY(object)        (G_TYPE_CHECK_INSTANCE_TYPE ((object), PANGO_TYPE_FONT_FAMILY))

Returns TRUE if object is a PangoFontFamily.

object : a GObject.

pango_font_family_get_name ()

const char* pango_font_family_get_name      (PangoFontFamily *family);

Gets the name of the family. The name is unique among all fonts for the font backend and can be used in a PangoFontDescription to specify that a face from this family is desired.

family : | a PangoFontFamily
Returns : | the name of the family. This string is owned by the family object and must not be modified or freed.

pango_font_family_is_monospace ()

gboolean    pango_font_family_is_monospace  (PangoFontFamily *family);

A monospace font is a font designed for text display where the the characters form a regular grid. For Western languages this would mean that the advance width of all characters are the same, but this categorization also includes Asian fonts which include double-width characters: characters that occupy two grid cells. g_unichar_iswide() returns a result that indicates whether a character is typically double-width in a monospace font.

The best way to find out the grid-cell size is to call pango_font_metrics_get_approximate_digit_width(), since the results of pango_font_metrics_get_approximate_char_width() may be affected by double-width characters.

family : | a PangoFontFamily
Returns : | TRUE if the family is monospace.

Since 1.4

pango_font_family_list_faces ()

void        pango_font_family_list_faces    (PangoFontFamily *family,
                                             PangoFontFace ***faces,
                                             int *n_faces);

Lists the different font faces that make up family. The faces in a family share a common design, but differ in slant, weight, width and other aspects.

family : | a PangoFontFamily
faces : | location to store an array of pointers to PangoFontFace objects, or NULL. This array should be freed with g_free() when it is no longer needed.
n_faces : | location to store number of elements in faces.

PangoFontFace

typedef struct _PangoFontFace PangoFontFace;

The PangoFontFace structure is used to represent a group of fonts with the same family, slant, weight, width, but varying sizes.

PANGO_TYPE_FONT_FACE

#define PANGO_TYPE_FONT_FACE              (pango_font_face_get_type ())

The GObject type for PangoFontFace.

PANGO_FONT_FACE()

#define PANGO_FONT_FACE(object)           (G_TYPE_CHECK_INSTANCE_CAST ((object), PANGO_TYPE_FONT_FACE, PangoFontFace))

Casts a GObject to a PangoFontFace.

object : a GObject.

PANGO_IS_FONT_FACE()

#define PANGO_IS_FONT_FACE(object)        (G_TYPE_CHECK_INSTANCE_TYPE ((object), PANGO_TYPE_FONT_FACE))

Returns TRUE if object is a PangoFontFace.

object : a GObject.

pango_font_face_get_face_name ()

const char* pango_font_face_get_face_name   (PangoFontFace *face);

Gets a name representing the style of this face among the different faces in the PangoFontFamily for the face. This name is unique among all faces in the family and is suitable for displaying to users.

face : | a PangoFontFace.
Returns : | the face name for the face. This string is owned by the face object and must not be modified or freed.

pango_font_face_list_sizes ()

void        pango_font_face_list_sizes      (PangoFontFace *face,
                                             int **sizes,
                                             int *n_sizes);

List the available sizes for a font. This is only applicable to bitmap fonts. For scalable fonts, stores NULL at the location pointed to by sizes and 0 at the location pointed to by n_sizes. The sizes returned are in Pango units and are sorted in ascending order.

face : | a PangoFontFace.
sizes : | location to store a pointer to an array of int. This array should be freed with g_free().
n_sizes : | location to store the number of elements in sizes

Since 1.4

pango_font_face_describe ()

PangoFontDescription* pango_font_face_describe
                                            (PangoFontFace *face);

Returns the family, style, variant, weight and stretch of a PangoFontFace. The size field of the resulting font description will be unset.

face : | a PangoFontFace
Returns : | a newly-created PangoFontDescription structure holding the description of the face. Use pango_font_description_free() to free the result.

PangoFontMap

typedef struct _PangoFontMap PangoFontMap;

The PangoFontMap represents the set of fonts available for a particular rendering system. This is a virtual object with implementations being specific to particular rendering systems. To create an implementation of a PangoFontMap, the rendering-system specific code should allocate a larger structure that contains a nested PangoFontMap, fill in the klass member of the nested PangoFontMap with a pointer to a appropriate PangoFontMapClass, then call pango_font_map_init() on the structure.

The PangoFontMap structure contains one member which the implementation fills in.

PANGO_TYPE_FONT_MAP

#define PANGO_TYPE_FONT_MAP              (pango_font_map_get_type ())

The GObject type for PangoFontMap.

PANGO_FONT_MAP()

#define PANGO_FONT_MAP(object)           (G_TYPE_CHECK_INSTANCE_CAST ((object), PANGO_TYPE_FONT_MAP, PangoFontMap))

Casts a GObject to a PangoFontMap.

object : a GObject.

PANGO_IS_FONT_MAP()

#define PANGO_IS_FONT_MAP(object)        (G_TYPE_CHECK_INSTANCE_TYPE ((object), PANGO_TYPE_FONT_MAP))

Returns TRUE if object is a PangoFontMap.

object : a GObject.

PangoFontMapClass

typedef struct {
  GObjectClass parent_class;

  PangoFont *   (*load_font)     (PangoFontMap               *fontmap,
                  PangoContext               *context,
                  const PangoFontDescription *desc);
  void          (*list_families) (PangoFontMap               *fontmap,
                  PangoFontFamily          ***families,
                  int                        *n_families);
  PangoFontset *(*load_fontset)  (PangoFontMap               *fontmap,
                  PangoContext               *context,
                  const PangoFontDescription *desc,
                  PangoLanguage              *language);

  const char *shape_engine_type;
} PangoFontMapClass;

The PangoFontMapClass structure holds the virtual functions for a particular PangoFontMap implementation.

GObjectClass parent_class; | parent GObjectClass.
load_font () | a function to load a font with a given description. See pango_font_map_load_font().
list_families () | A function to list available font families. See pango_font_map_list_families().
load_fontset () | a function to load a fontset with a given given description suitable for a particular language. See pango_font_map_load_fontset().
const char *shape_engine_type; | the type of rendering-system-dependent engines that can handle fonts of this fonts loaded with this fontmap.

PANGO_FONT_MAP_CLASS()

#define PANGO_FONT_MAP_CLASS(klass)      (G_TYPE_CHECK_CLASS_CAST ((klass), PANGO_TYPE_FONT_MAP, PangoFontMapClass))

Casts a GObject to a PangoFontMapClass.

klass : a GObject.

PANGO_IS_FONT_MAP_CLASS()

#define PANGO_IS_FONT_MAP_CLASS(klass)   (G_TYPE_CHECK_CLASS_TYPE ((klass), PANGO_TYPE_FONT_MAP))

Returns TRUE if klass is a subtype of PangoFontMapClass.

klass : a GObject.

PANGO_FONT_MAP_GET_CLASS()

#define PANGO_FONT_MAP_GET_CLASS(obj)    (G_TYPE_INSTANCE_GET_CLASS ((obj), PANGO_TYPE_FONT_MAP, PangoFontMapClass))

Returns the type of a PangoFontMap.

obj : a PangoFontMap.

pango_font_map_load_font ()

PangoFont*  pango_font_map_load_font        (PangoFontMap *fontmap,
                                             PangoContext *context,
                                             const PangoFontDescription *desc);

Load the font in the fontmap that is the closest match for desc.

fontmap : | a PangoFontMap
context : | the PangoContext the font will be used with
desc : | a PangoFontDescription describing the font to load
Returns : | the font loaded, or NULL if no font matched.

pango_font_map_load_fontset ()

PangoFontset* pango_font_map_load_fontset   (PangoFontMap *fontmap,
                                             PangoContext *context,
                                             const PangoFontDescription *desc,
                                             PangoLanguage *language);

Load a set of fonts in the fontmap that can be used to render a font matching desc.

fontmap : | a PangoFontMap
context : | the PangoContext the font will be used with
desc : | a PangoFontDescription describing the font to load
language : | a PangoLanguage the fonts will be used for
Returns : | the fontset, or NULL if no font matched.

pango_font_map_list_families ()

void        pango_font_map_list_families    (PangoFontMap *fontmap,
                                             PangoFontFamily ***families,
                                             int *n_families);

List all families for a fontmap.

fontmap : | a PangoFontMap
families : | location to store a pointer to an array of PangoFontFamily *. This array should be freed with g_free().
n_families : | location to store the number of elements in families

pango_font_map_get_shape_engine_type ()

const char* pango_font_map_get_shape_engine_type
                                            (PangoFontMap *fontmap);

Returns the render ID for shape engines for this fontmap. See the render_type field of PangoEngineInfo.

fontmap : | a PangoFontMap
Returns : | the ID string for shape engines for this fontmap. Owned by Pango, should not be modified or freed.

Since 1.4

PangoFontset

typedef struct _PangoFontset PangoFontset;

A PangoFontset represents a set of PangoFont to use when rendering text. It is the result of resolving a PangoFontDescription against a particular PangoContext. It has operations for finding the component font for a particular Unicode character, and for finding a composite set of metrics for the entire fontset.

PANGO_TYPE_FONTSET

#define PANGO_TYPE_FONTSET              (pango_fontset_get_type ())

The GObject type for PangoFontset.

PangoFontsetClass

typedef struct {
  GObjectClass parent_class;

  PangoFont *       (*get_font)     (PangoFontset     *fontset,
                     guint             wc);

  PangoFontMetrics *(*get_metrics)  (PangoFontset     *fontset);
  PangoLanguage *   (*get_language) (PangoFontset     *fontset);
  void              (*foreach)      (PangoFontset           *fontset,
                     PangoFontsetForeachFunc func,
                     gpointer                data);
} PangoFontsetClass;

The PangoFontsetClass structure holds the virtual functions for a particular PangoFontset implementation.

GObjectClass parent_class; | parent GObjectClass.
get_font () | a function to get the font in the fontset that contains the best glyph for the given Unicode character; see pango_fontset_get_font().
get_metrics () | a function to get overall metric information for the fonts in the fontset; see pango_fontset_get_metrics().
get_language () | a function to get the language of the fontset.
foreach () | a function to loop over the fonts in the fontset. See pango_fontset_foreach().

pango_fontset_get_font ()

PangoFont*  pango_fontset_get_font          (PangoFontset *fontset,
                                             guint wc);

Returns the font in the fontset that contains the best glyph for the Unicode character wc.

fontset : | a PangoFontset
wc : | a Unicode character
Returns : | a PangoFont. The caller must call g_object_unref when finished with the font.

pango_fontset_get_metrics ()

PangoFontMetrics* pango_fontset_get_metrics (PangoFontset *fontset);

Get overall metric information for the fonts in the fontset.

fontset : | a PangoFontset
Returns : | a PangoFontMetrics object. The caller must call pango_font_metrics_unref() when finished using the object.

PangoFontsetForeachFunc ()

gboolean    (*PangoFontsetForeachFunc)      (PangoFontset *fontset,
                                             PangoFont *font,
                                             gpointer data);

A callback function used by pango_fontset_foreach() when enumerating the fonts in a fontset.

fontset : | a PangoFontset
font : | a font from fontset
data : | callback data
Returns : | if TRUE, stop iteration and return immediately.

Since 1.4

pango_fontset_foreach ()

void        pango_fontset_foreach           (PangoFontset *fontset,
                                             PangoFontsetForeachFunc func,
                                             gpointer data);

Iterates through all the fonts in a fontset, calling func for each one. If func returns TRUE, that stops the iteration.

fontset : | a PangoFontset
func : | Callback function
data : | data to pass to the callback function

Since 1.4

PangoFontsetSimple

typedef struct _PangoFontsetSimple PangoFontsetSimple;

PangoFontsetSimple is a implementation of the abstract PangoFontset base class in terms of an array of fonts, which the creator provides when constructing the PangoFontsetSimple.

PANGO_TYPE_FONTSET_SIMPLE

#define PANGO_TYPE_FONTSET_SIMPLE       (pango_fontset_simple_get_type ())

The GObject type for PangoFontsetSimple.

pango_fontset_simple_new ()

PangoFontsetSimple* pango_fontset_simple_new
                                            (PangoLanguage *language);

Creates a new PangoFontsetSimple for the given language.

language : | a PangoLanguage tag
Returns : | the newly allocated PangoFontsetSimple, which should be freed with g_object_unref().

pango_fontset_simple_append ()

void        pango_fontset_simple_append     (PangoFontsetSimple *fontset,
                                             PangoFont *font);

Adds a font to the fontset.

fontset : | a PangoFontsetSimple.
font : | a PangoFont.

pango_fontset_simple_size ()

int         pango_fontset_simple_size       (PangoFontsetSimple *fontset);

Returns the number of fonts in the fontset.

fontset : | a PangoFontsetSimple.
Returns : | the size of fontset.


FreeType Fonts and Rendering

FreeType Fonts and Rendering — Functions for shape engines to manipulate FreeType fonts

Synopsis

            PangoFT2FontMap;
#define     PANGO_RENDER_TYPE_FT2
PangoFontMap* pango_ft2_font_map_new        (void);
void        pango_ft2_font_map_set_resolution
                                            (PangoFT2FontMap *fontmap,
                                             double dpi_x,
                                             double dpi_y);
PangoContext* pango_ft2_font_map_create_context
                                            (PangoFT2FontMap *fontmap);
void        (*PangoFT2SubstituteFunc)       (FcPattern *pattern,
                                             gpointer data);
void        pango_ft2_font_map_set_default_substitute
                                            (PangoFT2FontMap *fontmap,
                                             PangoFT2SubstituteFunc func,
                                             gpointer data,
                                             GDestroyNotify notify);
void        pango_ft2_font_map_substitute_changed
                                            (PangoFT2FontMap *fontmap);
PangoContext* pango_ft2_get_context         (double dpi_x,
                                             double dpi_y);
void        pango_ft2_render                (FT_Bitmap *bitmap,
                                             PangoFont *font,
                                             PangoGlyphString *glyphs,
                                             gint x,
                                             gint y);
void        pango_ft2_render_transformed    (FT_Bitmap *bitmap,
                                             const PangoMatrix *matrix,
                                             PangoFont *font,
                                             PangoGlyphString *glyphs,
                                             int x,
                                             int y);
void        pango_ft2_render_layout_line    (FT_Bitmap *bitmap,
                                             PangoLayoutLine *line,
                                             int x,
                                             int y);
void        pango_ft2_render_layout_line_subpixel
                                            (FT_Bitmap *bitmap,
                                             PangoLayoutLine *line,
                                             int x,
                                             int y);
void        pango_ft2_render_layout         (FT_Bitmap *bitmap,
                                             PangoLayout *layout,
                                             int x,
                                             int y);
void        pango_ft2_render_layout_subpixel
                                            (FT_Bitmap *bitmap,
                                             PangoLayout *layout,
                                             int x,
                                             int y);
PangoGlyph  pango_ft2_get_unknown_glyph     (PangoFont *font);
int         pango_ft2_font_get_kerning      (PangoFont *font,
                                             PangoGlyph left,
                                             PangoGlyph right);
FT_Face     pango_ft2_font_get_face         (PangoFont *font);
PangoCoverage* pango_ft2_font_get_coverage  (PangoFont *font,
                                             PangoLanguage *language);
PangoFontMap* pango_ft2_font_map_for_display
                                            (void);
void        pango_ft2_shutdown_display      (void);

Object Hierarchy

  GObject
   +----PangoFontMap
         +----PangoFcFontMap
               +----PangoFT2FontMap

Description

The macros and functions in this section are used to access fonts and render text to bitmaps using the FreeType 2 library.

Details

PangoFT2FontMap

typedef struct _PangoFT2FontMap PangoFT2FontMap;

The PangoFT2FontMap is the PangoFontMap implementation for FreeType fonts.

PANGO_RENDER_TYPE_FT2

#define PANGO_RENDER_TYPE_FT2 "PangoRenderFT2"

Warning

PANGO_RENDER_TYPE_FT2 is deprecated and should not be used in newly-written code.

A string constant that was used to identify shape engines that work with the FreeType backend. See PANGO_RENDER_TYPE_FC for the replacement.

pango_ft2_font_map_new ()

PangoFontMap* pango_ft2_font_map_new        (void);

Create a new PangoFT2FontMap object; a fontmap is used to cache information about available fonts, and holds certain global parameters such as the resolution and the default substitute function (see pango_ft2_font_map_set_default_substitute()).

Returns : the newly created fontmap object. Unref with g_object_unref() when you are finished with it.

Since 1.2

pango_ft2_font_map_set_resolution ()

void        pango_ft2_font_map_set_resolution
                                            (PangoFT2FontMap *fontmap,
                                             double dpi_x,
                                             double dpi_y);

Sets the horizontal and vertical resolutions for the fontmap.

fontmap : | a PangoFT2Fontmap
dpi_x : | dots per inch in the X direction
dpi_y : | dots per inch in the Y direction

Since 1.2

pango_ft2_font_map_create_context ()

PangoContext* pango_ft2_font_map_create_context
                                            (PangoFT2FontMap *fontmap);

Create a PangoContext for the given fontmap.

fontmap : | a PangoFT2Fontmap
Returns : | the newly created context; free with g_object_unref().

Since 1.2

PangoFT2SubstituteFunc ()

void        (*PangoFT2SubstituteFunc)       (FcPattern *pattern,
                                             gpointer data);

Function type for doing final config tweaking on prepared FcPatterns.

pattern : | the FcPattern to tweak.
data : | user data.

pango_ft2_font_map_set_default_substitute ()

void        pango_ft2_font_map_set_default_substitute
                                            (PangoFT2FontMap *fontmap,
                                             PangoFT2SubstituteFunc func,
                                             gpointer data,
                                             GDestroyNotify notify);

Sets a function that will be called to do final configuration substitution on a FcPattern before it is used to load the font. This function can be used to do things like set hinting and antialiasing options.

fontmap : | a PangoFT2FontMap
func : | function to call to to do final config tweaking on FcPattern objects.
data : | data to pass to func
notify : | function to call when data is no longer used.

Since 1.2

pango_ft2_font_map_substitute_changed ()

void        pango_ft2_font_map_substitute_changed
                                            (PangoFT2FontMap *fontmap);

Call this function any time the results of the default substitution function set with pango_ft2_font_map_set_default_substitute() change. That is, if your substitution function will return different results for the same input pattern, you must call this function.

fontmap : a PangoFT2Fontmap

Since 1.2

pango_ft2_get_context ()

PangoContext* pango_ft2_get_context         (double dpi_x,
                                             double dpi_y);

Warning

pango_ft2_get_context is deprecated and should not be used in newly-written code.

Retrieves a PangoContext for the default PangoFT2 fontmap (see pango_ft2_fontmap_get_for_display()) and sets the resolution for the default fontmap to dpi_x by dpi_y.

Use of this function is deprecated; see pango_ft2_fontmap_create_context() instead.

dpi_x : | the horizontal DPI of the target device
dpi_y : | the vertical DPI of the target device
Returns : | the new PangoContext

pango_ft2_render ()

void        pango_ft2_render                (FT_Bitmap *bitmap,
                                             PangoFont *font,
                                             PangoGlyphString *glyphs,
                                             gint x,
                                             gint y);

Renders a PangoGlyphString onto a FreeType2 bitmap.

bitmap : | the FreeType2 bitmap onto which to draw the string
font : | the font in which to draw the string
glyphs : | the glyph string to draw
x : | the x position of the start of the string (in pixels)
y : | the y position of the baseline (in pixels)

pango_ft2_render_transformed ()

void        pango_ft2_render_transformed    (FT_Bitmap *bitmap,
                                             const PangoMatrix *matrix,
                                             PangoFont *font,
                                             PangoGlyphString *glyphs,
                                             int x,
                                             int y);

Renders a PangoGlyphString onto a FreeType2 bitmap, possibly transforming the layed-out coordinates through a transformation matrix. Note that the transformation matrix for font is not changed, so to produce correct rendering results, the font must have been loaded using a PangoContext with an identical transformation matrix to that passed in to this function.

bitmap : | the FreeType2 bitmap onto which to draw the string
matrix : | a PangoMatrix, or NULL to use an identity transformation
font : | the font in which to draw the string
glyphs : | the glyph string to draw
x : | the x position of the start of the string (in Pango units in user space coordinates)
y : | the y position of the baseline (in Pango units in user space coordinates)

Since 1.6

pango_ft2_render_layout_line ()

void        pango_ft2_render_layout_line    (FT_Bitmap *bitmap,
                                             PangoLayoutLine *line,
                                             int x,
                                             int y);

Render a PangoLayoutLine onto a FreeType2 bitmap

bitmap : | a FT_Bitmap to render the line onto
line : | a PangoLayoutLine
x : | the x position of start of string (in pixels)
y : | the y position of baseline (in pixels)

pango_ft2_render_layout_line_subpixel ()

void        pango_ft2_render_layout_line_subpixel
                                            (FT_Bitmap *bitmap,
                                             PangoLayoutLine *line,
                                             int x,
                                             int y);

Render a PangoLayoutLine onto a FreeType2 bitmap, with he location specified in fixed-point Pango units rather than pixels. (Using this will avoid extra inaccuracies from rounding to integer pixels multiple times, even if the final glyph positions are integers.)

bitmap : | a FT_Bitmap to render the line onto
line : | a PangoLayoutLine
x : | the x position of start of string (in Pango units)
y : | the y position of baseline (in Pango units)

Since 1.6

pango_ft2_render_layout ()

void        pango_ft2_render_layout         (FT_Bitmap *bitmap,
                                             PangoLayout *layout,
                                             int x,
                                             int y);

Render a PangoLayout onto a FreeType2 bitmap

bitmap : | a FT_Bitmap to render the layout onto
layout : | a PangoLayout
x : | the X position of the left of the layout (in pixels)
y : | the Y position of the top of the layout (in pixels)

pango_ft2_render_layout_subpixel ()

void        pango_ft2_render_layout_subpixel
                                            (FT_Bitmap *bitmap,
                                             PangoLayout *layout,
                                             int x,
                                             int y);

Render a PangoLayout onto a FreeType2 bitmap, with he location specified in fixed-point Pango units rather than pixels. (Using this will avoid extra inaccuracies from rounding to integer pixels multiple times, even if the final glyph positions are integers.)

bitmap : | a FT_Bitmap to render the layout onto
layout : | a PangoLayout
x : | the X position of the left of the layout (in Pango units)
y : | the Y position of the top of the layout (in Pango units)

Since 1.6

pango_ft2_get_unknown_glyph ()

PangoGlyph  pango_ft2_get_unknown_glyph     (PangoFont *font);

Warning

pango_ft2_get_unknown_glyph is deprecated and should not be used in newly-written code.

Return the index of a glyph suitable for drawing unknown characters with font, or PANGO_GLYPH_EMPTY if no suitable glyph found.

If you want to draw an unknown-box for a character that is not covered by the font, use PANGO_GET_UNKNOWN_GLYPH() instead.

font : | a PangoFont
Returns : | a glyph index into font, or PANGO_GLYPH_EMPTY

pango_ft2_font_get_kerning ()

int         pango_ft2_font_get_kerning      (PangoFont *font,
                                             PangoGlyph left,
                                             PangoGlyph right);

Warning

pango_ft2_font_get_kerning is deprecated and should not be used in newly-written code.

Retrieves kerning information for a combination of two glyphs.

Use pango_fc_font_kern_glyphs() instead.

font : | a PangoFont
left : | the left PangoGlyph
right : | the right PangoGlyph
Returns : | The amount of kerning (in Pango units) to apply for the given combination of glyphs.

pango_ft2_font_get_face ()

FT_Face     pango_ft2_font_get_face         (PangoFont *font);

Warning

pango_ft2_font_get_face is deprecated and should not be used in newly-written code.

Returns the native FreeType2 FT_Face structure used for this PangoFont. This may be useful if you want to use FreeType2 functions directly.

Use pango_fc_font_lock_face() instead; when you are done with a face from pango_fc_font_lock_face() you must call pango_fc_font_unlock_face().

font : | a PangoFont
Returns : | a pointer to a FT_Face structure, with the size set correctly

pango_ft2_font_get_coverage ()

PangoCoverage* pango_ft2_font_get_coverage  (PangoFont *font,
                                             PangoLanguage *language);

Warning

pango_ft2_font_get_coverage is deprecated and should not be used in newly-written code.

Gets the PangoCoverage for a PangoFT2Font. Use pango_font_get_coverage() instead.

font : | a PangoFT2Font.
language : | a language tag.
Returns : | a PangoCoverage.

pango_ft2_font_map_for_display ()

PangoFontMap* pango_ft2_font_map_for_display
                                            (void);

Warning

pango_ft2_font_map_for_display is deprecated and should not be used in newly-written code.

Returns a PangoFT2FontMap. This font map is cached and should not be freed. If the font map is no longer needed, it can be released with pango_ft2_shutdown_display(). Use of the global PangoFT2 fontmap is deprecated; use pango_ft2_font_map_new() instead.

Returns : a PangoFT2FontMap.

pango_ft2_shutdown_display ()

void        pango_ft2_shutdown_display      (void);

Warning

pango_ft2_shutdown_display is deprecated and should not be used in newly-written code.

Free the global fontmap. (See pango_ft2_font_map_for_display()) Use of the global PangoFT2 fontmap is deprecated.


Glyph Storage

Glyph Storage — Structures for storing information about glyphs

Synopsis

#define     PANGO_SCALE
#define     PANGO_PIXELS                    (d)
#define     PANGO_PIXELS_FLOOR              (d)
#define     PANGO_PIXELS_CEIL               (d)
double      pango_units_to_double           (int i);
int         pango_units_from_double         (double d);
            PangoRectangle;
#define     PANGO_ASCENT                    (rect)
#define     PANGO_DESCENT                   (rect)
#define     PANGO_LBEARING                  (rect)
#define     PANGO_RBEARING                  (rect)
void        pango_extents_to_pixels         (PangoRectangle *ink_rect,
                                             PangoRectangle *logical_rect);
            PangoMatrix;
#define     PANGO_TYPE_MATRIX
#define     PANGO_MATRIX_INIT
PangoMatrix* pango_matrix_copy              (const PangoMatrix *matrix);
void        pango_matrix_free               (PangoMatrix *matrix);
void        pango_matrix_translate          (PangoMatrix *matrix,
                                             double tx,
                                             double ty);
void        pango_matrix_scale              (PangoMatrix *matrix,
                                             double scale_x,
                                             double scale_y);
void        pango_matrix_rotate             (PangoMatrix *matrix,
                                             double degrees);
void        pango_matrix_concat             (PangoMatrix *matrix,
                                             const PangoMatrix *new_matrix);
void        pango_matrix_transform_point    (const PangoMatrix *matrix,
                                             double *x,
                                             double *y);
void        pango_matrix_transform_distance (const PangoMatrix *matrix,
                                             double *dx,
                                             double *dy);
void        pango_matrix_transform_rectangle
                                            (const PangoMatrix *matrix,
                                             PangoRectangle *rect);
void        pango_matrix_transform_pixel_rectangle
                                            (const PangoMatrix *matrix,
                                             PangoRectangle *rect);
double      pango_matrix_get_font_scale_factor
                                            (const PangoMatrix *matrix);
typedef     PangoGlyph;
#define     PANGO_GLYPH_EMPTY
#define     PANGO_GLYPH_UNKNOWN_FLAG
#define     PANGO_GET_UNKNOWN_GLYPH         (wc)
            PangoGlyphInfo;
            PangoGlyphGeometry;
typedef     PangoGlyphUnit;
            PangoGlyphVisAttr;
            PangoGlyphString;
            PangoGlyphItem;
#define     PANGO_TYPE_GLYPH_STRING
PangoGlyphString* pango_glyph_string_new    (void);
PangoGlyphString* pango_glyph_string_copy   (PangoGlyphString *string);
void        pango_glyph_string_set_size     (PangoGlyphString *string,
                                             gint new_len);
void        pango_glyph_string_free         (PangoGlyphString *string);
void        pango_glyph_string_extents      (PangoGlyphString *glyphs,
                                             PangoFont *font,
                                             PangoRectangle *ink_rect,
                                             PangoRectangle *logical_rect);
void        pango_glyph_string_extents_range
                                            (PangoGlyphString *glyphs,
                                             int start,
                                             int end,
                                             PangoFont *font,
                                             PangoRectangle *ink_rect,
                                             PangoRectangle *logical_rect);
int         pango_glyph_string_get_width    (PangoGlyphString *glyphs);
void        pango_glyph_string_index_to_x   (PangoGlyphString *glyphs,
                                             char *text,
                                             int length,
                                             PangoAnalysis *analysis,
                                             int index_,
                                             gboolean trailing,
                                             int *x_pos);
void        pango_glyph_string_x_to_index   (PangoGlyphString *glyphs,
                                             char *text,
                                             int length,
                                             PangoAnalysis *analysis,
                                             int x_pos,
                                             int *index_,
                                             int *trailing);
void        pango_glyph_string_get_logical_widths
                                            (PangoGlyphString *glyphs,
                                             const char *text,
                                             int length,
                                             int embedding_level,
                                             int *logical_widths);
PangoGlyphItem* pango_glyph_item_split      (PangoGlyphItem *orig,
                                             const char *text,
                                             int split_index);
GSList*     pango_glyph_item_apply_attrs    (PangoGlyphItem *glyph_item,
                                             const char *text,
                                             PangoAttrList *list);
void        pango_glyph_item_letter_space   (PangoGlyphItem *glyph_item,
                                             const char *text,
                                             PangoLogAttr *log_attrs,
                                             int letter_spacing);
void        pango_glyph_item_free           (PangoGlyphItem *glyph_item);

Description

pango_shape() produces a string of glyphs which can be measured or drawn to the screen. The following structures are used to store information about glyphs.

Details

PANGO_SCALE

#define PANGO_SCALE 1024

The PANGO_SCALE macro represents the scale between dimensions used for Pango distances and device units. (The definition of device units is dependent on the output device; it will typically be pixels for a screen, and points for a printer.) PANGO_SCALE is currently 1024, but this may be changed in the future.

When setting font sizes, device units are always considered to be points (as in "12 point font"), rather than pixels.

PANGO_PIXELS()

#define PANGO_PIXELS(d) (((int)(d) + 512) >> 10)

Converts a dimension to device units by rounding.

d : a dimension in Pango units.

PANGO_PIXELS_FLOOR()

#define PANGO_PIXELS_FLOOR(d) (((int)(d)) >> 10)

Converts a dimension to device units by flooring.

d : a dimension in Pango units.

PANGO_PIXELS_CEIL()

#define PANGO_PIXELS_CEIL(d) (((int)(d) + 1023) >> 10)

Converts a dimension to device units by ceiling.

d : a dimension in Pango units.

pango_units_to_double ()

double      pango_units_to_double           (int i);

Converts a number in Pango units to floating-point: divides it by PANGO_SCALE.

i : | value in Pango units
Returns : | the double value.

Since 1.16

pango_units_from_double ()

int         pango_units_from_double         (double d);

Converts a floating-point number to Pango units: multiplies it by PANGO_SCALE and rounds to nearest integer.

d : | double floating-point value
Returns : | the value in Pango units.

Since 1.16

PangoRectangle

typedef struct {
  int x;
  int y;
  int width;
  int height;
} PangoRectangle;

The PangoRectangle structure represents a rectangle. It is frequently used to represent the logical or ink extents of a single glyph or section of text. (See, for instance, pango_font_get_glyph_extents())

int x; | X coordinate of the left side of the rectangle.
int y; | Y coordinate of the the top side of the rectangle.
int width; | width of the rectangle.
int height; | height of the rectangle.

PANGO_ASCENT()

#define PANGO_ASCENT(rect) (-(rect).y)

Extracts the ascent from a PangoRectangle representing glyph extents. The ascent is the distance from the baseline to the highest point of the character. This is positive if the glyph ascends above the baseline.

rect : a PangoRectangle

PANGO_DESCENT()

#define PANGO_DESCENT(rect) ((rect).y + (rect).height)

Extracts the descent from a PangoRectangle representing glyph extents. The descent is the distance from the baseline to the lowest point of the character. This is positive if the glyph descends below the baseline.

rect : a PangoRectangle

PANGO_LBEARING()

#define PANGO_LBEARING(rect) ((rect).x)

Extracts the left bearing from a PangoRectangle representing glyph extents. The left bearing is the distance from the horizontal origin to the farthest left point of the character. This is positive for characters drawn completely to the right of the glyph origin.

rect : a PangoRectangle

PANGO_RBEARING()

#define PANGO_RBEARING(rect) ((rect).x + (rect).width)

Extracts the right bearing from a PangoRectangle representing glyph extents. The right bearing is the distance from the horizontal origin to the farthest right point of the character. This is positive except for characters drawn completely to the left of the horizontal origin.

rect : a PangoRectangle

pango_extents_to_pixels ()

void        pango_extents_to_pixels         (PangoRectangle *ink_rect,
                                             PangoRectangle *logical_rect);

Converts extents from Pango units to device units, dividing by the PANGO_SCALE factor and performing rounding.

The ink rectangle is converted by flooring the x/y coordinates and extending width/height, such that the final rectangle completely includes the original rectangle.

The logical rectangle is converted by rounding the coordinates of the rectangle to the nearest device unit.

Note that in certain situations you may want pass a logical extents rectangle to this function as ink_rect. The rule is: if you want the resulting device-space rectangle to completely contain the original rectangle, pass it in as ink_rect.

ink_rect : | ink rectangle to convert, or NULL.
logical_rect : | logical rectangle to convert, or NULL.

Since 1.16

PangoMatrix

typedef struct {
  double xx;
  double xy;
  double yx;
  double yy;
  double x0;
  double y0;
} PangoMatrix;

A structure specifying a transformation between user-space coordinates and device coordinates. The transformation is given by

x_device = x_user * matrix->xx + y_user * matrix->xy + matrix->x0;
y_device = x_user * matrix->yx + y_user * matrix->yy + matrix->y0;

double xx; | 1st component of the transformation matrix
double xy; | 2nd component of the transformation matrix
double yx; | 3rd component of the transformation matrix
double yy; | 4th component of the transformation matrix
double x0; | x translation
double y0; | y translation

Since 1.6

PANGO_TYPE_MATRIX

#define PANGO_TYPE_MATRIX (pango_matrix_get_type ())

The GObject type for PangoMatrix

PANGO_MATRIX_INIT

#define PANGO_MATRIX_INIT { 1., 0., 0., 1., 0., 0. }

Constant that can be used to initialize a PangoMatrix to the identity transform.

PangoMatrix matrix = PANGO_MATRIX_INIT;
pango_matrix_rotate (&matrix, 45.);

Since 1.6

pango_matrix_copy ()

PangoMatrix* pango_matrix_copy              (const PangoMatrix *matrix);

Copies a PangoMatrix.

matrix : | a PangoMatrix, can be NULL
Returns : | the newly allocated PangoMatrix, which should be freed with pango_matrix_free(), or NULL if matrix was NULL.

Since 1.6

pango_matrix_free ()

void        pango_matrix_free               (PangoMatrix *matrix);

Free a PangoMatrix created with pango_matrix_copy(). Does nothing if matrix is NULL.

matrix : a PangoMatrix, or NULL

Since 1.6

pango_matrix_translate ()

void        pango_matrix_translate          (PangoMatrix *matrix,
                                             double tx,
                                             double ty);

Changes the transformation represented by matrix to be the transformation given by first translating by (tx, ty) then applying the original transformation.

matrix : | a PangoMatrix
tx : | amount to translate in the X direction
ty : | amount to translate in the Y direction

Since 1.6

pango_matrix_scale ()

void        pango_matrix_scale              (PangoMatrix *matrix,
                                             double scale_x,
                                             double scale_y);

Changes the transformation represented by matrix to be the transformation given by first scaling by sx in the X direction and sy in the Y direction then applying the original transformation.

matrix : | a PangoMatrix
scale_x : | amount to scale by in X direction
scale_y : | amount to scale by in Y direction

Since 1.6

pango_matrix_rotate ()

void        pango_matrix_rotate             (PangoMatrix *matrix,
                                             double degrees);

Changes the transformation represented by matrix to be the transformation given by first rotating by degrees degrees counter-clockwise then applying the original transformation.

matrix : | a PangoMatrix
degrees : | degrees to rotate counter-clockwise

Since 1.6

pango_matrix_concat ()

void        pango_matrix_concat             (PangoMatrix *matrix,
                                             const PangoMatrix *new_matrix);

Changes the transformation represented by matrix to be the transformation given by first applying transformation given by new_matrix then applying the original transformation.

matrix : | a PangoMatrix
new_matrix : | a PangoMatrix

Since 1.6

pango_matrix_transform_point ()

void        pango_matrix_transform_point    (const PangoMatrix *matrix,
                                             double *x,
                                             double *y);

Transforms the point (x, y) by matrix.

matrix : | a PangoMatrix, or NULL
x : | in/out X position
y : | in/out Y position

Since 1.16

pango_matrix_transform_distance ()

void        pango_matrix_transform_distance (const PangoMatrix *matrix,
                                             double *dx,
                                             double *dy);

Transforms the distance vector (dx,dy) by matrix. This is similar to pango_matrix_transform_point() except that the translation components of the transformation are ignored. The calculation of the returned vector is as follows:

dx2 = dx1 * xx + dy1 * xy;
dy2 = dx1 * yx + dy1 * yy;

Affine transformations are position invariant, so the same vector always transforms to the same vector. If (x1,y1) transforms to (x2,y2) then (x1+dx1,y1+dy1) will transform to (x1+dx2,y1+dy2) for all values of x1 and x2.

matrix : | a PangoMatrix, or NULL
dx : | in/out X component of a distance vector
dy : | yn/out Y component of a distance vector

Since 1.16

pango_matrix_transform_rectangle ()

void        pango_matrix_transform_rectangle
                                            (const PangoMatrix *matrix,
                                             PangoRectangle *rect);

First transforms rect using matrix, then calculates the bounding box of the transformed rectangle. The rectangle should be in Pango units.

This function is useful for example when you want to draw a rotated PangoLayout to an image buffer, and want to know how large the image should be and how much you should shift the layout when rendering.

If you have a rectangle in device units (pixels), use pango_matrix_transform_pixel_rectangle().

If you have the rectangle in Pango units and want to convert to transformed pixel bounding box, it is more accurate to transform it first (using this function) and pass the result to pango_extents_to_pixels(), as ink_rect. However, there is a reason that you may want to convert to pixels first and then transform, and that is when the transformed coordinates may overflow in Pango units (large matrix translation for example).

matrix : | a PangoMatrix, or NULL
rect : | in/out bounding box in Pango units, or NULL

Since 1.16

pango_matrix_transform_pixel_rectangle ()

void        pango_matrix_transform_pixel_rectangle
                                            (const PangoMatrix *matrix,
                                             PangoRectangle *rect);

First transforms the rect using matrix, then calculates the bounding box of the transformed rectangle. The rectangle should be in device units (pixels).

This function is useful for example when you want to draw a rotated PangoLayout to an image buffer, and want to know how large the image should be and how much you should shift the layout when rendering.

For better accuracy, you should use pango_matrix_transform_rectangle() on original rectangle in Pango units and convert to pixels afterward using pango_extents_to_pixels() as ink_rect.

matrix : | a PangoMatrix, or NULL
rect : | in/out bounding box in device units, or NULL

Since 1.16

pango_matrix_get_font_scale_factor ()

double      pango_matrix_get_font_scale_factor
                                            (const PangoMatrix *matrix);

Returns the scale factor of a matrix on the height of the font. That is, the scale factor in the direction perpendicular to the vector that the X coordinate is mapped to.

matrix : | a PangoMatrix, may be NULL
Returns : | the scale factor of matrix on the height of the font, or 1.0 if matrix is NULL.

Since 1.12

PangoGlyph

typedef guint32 PangoGlyph;

A PangoGlyph represents a single glyph in the output form of a string.

PANGO_GLYPH_EMPTY

#define PANGO_GLYPH_EMPTY           ((PangoGlyph)0x0FFFFFFF)

The PANGO_GLYPH_EMPTY macro represents a PangoGlyph value that has a special meaning, which is a zero-width empty glyph. This is useful for example in shaper modules, to use as the glyph for various zero-width Unicode characters (those passing pango_is_zero_width()).

PANGO_GLYPH_UNKNOWN_FLAG

#define PANGO_GLYPH_UNKNOWN_FLAG    ((PangoGlyph)0x10000000)

The PANGO_GLYPH_UNKNOWN_FLAG macro is a flag value that can be added to a gunichar value of a valid Unicode character, to produce a PangoGlyph value, representing an unknown-character glyph for the respective gunichar.

PANGO_GET_UNKNOWN_GLYPH()

#define PANGO_GET_UNKNOWN_GLYPH(wc) ((PangoGlyph)(wc)|PANGO_GLYPH_UNKNOWN_FLAG)

Returns a PangoGlyph value that means no glyph was found for wc. The way this unknown glyphs are rendered is backend specific. For example, a box with the hexadecimal Unicode code-point of the character written in it is what is done in the most common backends.

wc : a Unicode character

PangoGlyphInfo

typedef struct {
  PangoGlyph    glyph;
  PangoGlyphGeometry geometry;
  PangoGlyphVisAttr  attr;
} PangoGlyphInfo;

The PangoGlyphInfo structure represents a single glyph together with positioning information and visual attributes. It contains the following fields.

PangoGlyph glyph; | the glyph itself.
PangoGlyphGeometry geometry; | the positional information about the glyph.
PangoGlyphVisAttr attr; | the visual attributes of the glyph.

PangoGlyphGeometry

typedef struct {
  PangoGlyphUnit width;
  PangoGlyphUnit x_offset;
  PangoGlyphUnit y_offset;
} PangoGlyphGeometry;

The PangoGlyphGeometry structure contains width and positioning information for a single glyph.

PangoGlyphUnit width; | the logical width to use for the the character.
PangoGlyphUnit x_offset; | horizontal offset from nominal character position.
PangoGlyphUnit y_offset; | vertical offset from nominal character position.

PangoGlyphUnit

typedef gint32 PangoGlyphUnit;

The PangoGlyphUnit type is used to store dimensions within Pango. Dimensions are stored in 1/PANGO_SCALE of a device unit. (A device unit might be a pixel for screen display, or a point on a printer.) PANGO_SCALE is currently 1024, and may change in the future (unlikely though), but you should not depend on its exact value. The PANGO_PIXELS() macro can be used to convert from glyph units into device units with correct rounding.

PangoGlyphVisAttr

typedef struct {
  guint is_cluster_start : 1;
} PangoGlyphVisAttr;

The PangoGlyphVisAttr is used to communicate information between the shaping phase and the rendering phase. More attributes may be added in the future.

guint is_cluster_start : 1; set for the first logical glyph in each cluster. (Clusters are stored in visual order, within the cluster, glyphs are always ordered in logical order, since visual order is meaningless; that is, in Arabic text, accent glyphs follow the glyphs for the base character.)

PangoGlyphString

typedef struct {
  gint num_glyphs;

  PangoGlyphInfo *glyphs;

  /* This is a memory inefficient way of representing the information
   * here - each value gives the byte index within the text
   * corresponding to the glyph string of the start of the cluster to
   * which the glyph belongs.
   */
  gint *log_clusters;
} PangoGlyphString;

The PangoGlyphString structure is used to store strings of glyphs with geometry and visual attribute information. The storage for the glyph information is owned by the structure which simplifies memory management.

gint num_glyphs; | the number of glyphs in the string.
PangoGlyphInfo *glyphs; | an array of PangoGlyphInfo structures of length num_glyphs.
gint *log_clusters; | for each glyph, byte index of the starting character for the cluster. The indices are relative to the start of the text corresponding to the PangoGlyphString.

PangoGlyphItem

typedef struct {
  PangoItem        *item;
  PangoGlyphString *glyphs;
} PangoGlyphItem;

A PangoGlyphItem is a pair of a PangoItem and the glyphs resulting from shaping the text corresponding to an item. As an example of the usage of PangoGlyphItem, the results of shaping text with PangoLayout is a list of PangoLayoutLine, each of which contains a list of PangoGlyphItem.

PangoItem *item; | a PangoItem structure that provides information about a segment of text.
PangoGlyphString *glyphs; | the glyphs obtained by shaping the text corresponding to item.

PANGO_TYPE_GLYPH_STRING

#define PANGO_TYPE_GLYPH_STRING (pango_glyph_string_get_type ())

The GObject type for PangoGlyphString.

pango_glyph_string_new ()

PangoGlyphString* pango_glyph_string_new    (void);

Create a new PangoGlyphString.

Returns : the newly allocated PangoGlyphString, which should be freed with pango_glyph_string_free().

pango_glyph_string_copy ()

PangoGlyphString* pango_glyph_string_copy   (PangoGlyphString *string);

Copy a glyph string and associated storage.

string : | a PangoGlyphString.
Returns : | the newly allocated PangoGlyphString, which should be freed with pango_glyph_string_free().

pango_glyph_string_set_size ()

void        pango_glyph_string_set_size     (PangoGlyphString *string,
                                             gint new_len);

Resize a glyph string to the given length.

string : | a PangoGlyphString.
new_len : | the new length of the string.

pango_glyph_string_free ()

void        pango_glyph_string_free         (PangoGlyphString *string);

Free a glyph string and associated storage.

string : a PangoGlyphString.

pango_glyph_string_extents ()

void        pango_glyph_string_extents      (PangoGlyphString *glyphs,
                                             PangoFont *font,
                                             PangoRectangle *ink_rect,
                                             PangoRectangle *logical_rect);

Compute the logical and ink extents of a glyph string. See the documentation for pango_font_get_glyph_extents() for details about the interpretation of the rectangles.

glyphs : | a PangoGlyphString
font : | a PangoFont
ink_rect : | rectangle used to store the extents of the glyph string as drawn or NULL to indicate that the result is not needed.
logical_rect : | rectangle used to store the logical extents of the glyph string or NULL to indicate that the result is not needed.

pango_glyph_string_extents_range ()

void        pango_glyph_string_extents_range
                                            (PangoGlyphString *glyphs,
                                             int start,
                                             int end,
                                             PangoFont *font,
                                             PangoRectangle *ink_rect,
                                             PangoRectangle *logical_rect);

Computes the extents of a sub-portion of a glyph string. The extents are relative to the start of the glyph string range (the origin of their coordinate system is at the start of the range, not at the start of the entire glyph string).

glyphs : | a PangoGlyphString
start : | start index
end : | end index (the range is the set of bytes with indices such that start <= index < end)
font : | a PangoFont
ink_rect : | rectangle used to store the extents of the glyph string range as drawn or NULL to indicate that the result is not needed.
logical_rect : | rectangle used to store the logical extents of the glyph string range or NULL to indicate that the result is not needed.

pango_glyph_string_get_width ()

int         pango_glyph_string_get_width    (PangoGlyphString *glyphs);

Computes the logical width of the glyph string as can also be computed using pango_glyph_string_extents(). However, since this only computes the width, it's much faster. This is in fact only a convenience function that computes the sum of geometry.width for each glyph in the glyphs.

glyphs : | a PangoGlyphString
Returns : | the logical width of the glyph string.

Since 1.14

pango_glyph_string_index_to_x ()

void        pango_glyph_string_index_to_x   (PangoGlyphString *glyphs,
                                             char *text,
                                             int length,
                                             PangoAnalysis *analysis,
                                             int index_,
                                             gboolean trailing,
                                             int *x_pos);

Converts from character position to x position. (X position is measured from the left edge of the run). Character positions are computed by dividing up each cluster into equal portions.

glyphs : | the glyphs return from pango_shape()
text : | the text for the run
length : | the number of bytes (not characters) in text.
analysis : | the analysis information return from pango_itemize()
index_ : | the byte index within text
trailing : | whether we should compute the result for the beginning or end of the character.
x_pos : | location to store result

pango_glyph_string_x_to_index ()

void        pango_glyph_string_x_to_index   (PangoGlyphString *glyphs,
                                             char *text,
                                             int length,
                                             PangoAnalysis *analysis,
                                             int x_pos,
                                             int *index_,
                                             int *trailing);

Convert from x offset to character position. Character positions are computed by dividing up each cluster into equal portions. In scripts where positioning within a cluster is not allowed (such as Thai), the returned value may not be a valid cursor position; the caller must combine the result with the logical attributes for the text to compute the valid cursor position.

glyphs : | the glyphs return from pango_shape()
text : | the text for the run
length : | the number of bytes (not characters) in text.
analysis : | the analysis information return from pango_itemize()
x_pos : | the x offset (in PangoGlyphUnit)
index_ : | location to store calculated byte index within text
trailing : | location to store a integer indicating where whether the user clicked on the leading or trailing edge of the character.

pango_glyph_string_get_logical_widths ()

void        pango_glyph_string_get_logical_widths
                                            (PangoGlyphString *glyphs,
                                             const char *text,
                                             int length,
                                             int embedding_level,
                                             int *logical_widths);

Given a PangoGlyphString resulting from pango_shape() and the corresponding text, determine the screen width corresponding to each character. When multiple characters compose a single cluster, the width of the entire cluster is divided equally among the characters.

glyphs : | a PangoGlyphString
text : | the text corresponding to the glyphs
length : | the length of text, in bytes
embedding_level : | the embedding level of the string
logical_widths : | an array whose length is g_utf8_strlen (text, length) to be filled in with the resulting character widths.

pango_glyph_item_split ()

PangoGlyphItem* pango_glyph_item_split      (PangoGlyphItem *orig,
                                             const char *text,
                                             int split_index);

Modifies orig to cover only the text after split_index, and returns a new item that covers the text before split_index that used to be in orig. You can think of split_index as the length of the returned item. split_index may not be 0, and it may not be greater than or equal to the length of orig (that is, there must be at least one byte assigned to each item, you can't create a zero-length item).

This function is similar in function to pango_item_split() (and uses it internally.)

orig : | a PangoItem
text : | text to which positions in orig apply
split_index : | byte index of position to split item, relative to the start of the item
Returns : | the newly allocated item representing text before split_index, which should be freed with pango_glyph_item_free().

Since 1.2

pango_glyph_item_apply_attrs ()

GSList*     pango_glyph_item_apply_attrs    (PangoGlyphItem *glyph_item,
                                             const char *text,
                                             PangoAttrList *list);

Splits a shaped item (PangoGlyphItem) into multiple items based on an attribute list. The idea is that if you have attributes that don't affect shaping, such as color or underline, to avoid affecting shaping, you filter them out (pango_attr_list_filter()), apply the shaping process and then reapply them to the result using this function.

All attributes that start or end inside a cluster are applied to that cluster; for instance, if half of a cluster is underlined and the other-half strikethrough, then the cluster will end up with both underline and strikethrough attributes. In these cases, it may happen that item->extra_attrs for some of the result items can have multiple attributes of the same type.

This function takes ownership of glyph_item; it will be reused as one of the elements in the list.

glyph_item : | a shaped item
text : | text that list applies to
list : | a PangoAttrList
Returns : | a list of glyph items resulting from splitting glyph_item. Free the elements using pango_glyph_item_free(), the list using g_slist_free().

Since 1.2

pango_glyph_item_letter_space ()

void        pango_glyph_item_letter_space   (PangoGlyphItem *glyph_item,
                                             const char *text,
                                             PangoLogAttr *log_attrs,
                                             int letter_spacing);

Adds spacing between the graphemes of glyph_item to give the effect of typographic letter spacing.

glyph_item : | a PangoGlyphItem
text : | text that glyph_item corresponds to (glyph_item->item->offset is an offset from the start of text)
log_attrs : | logical attributes for the item (the first logical attribute refers to the position before the first character in the item)
letter_spacing : | amount of letter spacing to add in Pango units. May be negative, though too large negative values will give ugly results.

Since 1.6

pango_glyph_item_free ()

void        pango_glyph_item_free           (PangoGlyphItem *glyph_item);

Frees a PangoGlyphItem and memory to which it points.

glyph_item : a PangoGlyphItem

Since 1.6


Object Hierarchy

    GObject
        PangoEngine
            PangoEngineLang
            PangoEngineShape
        PangoFont
            PangoFcFont
                PangoXftFont
        PangoFontFamily
        PangoFontFace
        PangoContext
        PangoFontMap
            PangoFcFontMap
                PangoFT2FontMap
        PangoFontset
            PangoFontsetSimple
        PangoFcDecoder
    GInterface
        PangoCairoFontMap


Layout Objects

Layout Objects — High-level layout driver objects

Synopsis

            PangoLayout;
            PangoLayoutIter;
PangoLayout* pango_layout_new               (PangoContext *context);
PangoLayout* pango_layout_copy              (PangoLayout *src);
PangoContext* pango_layout_get_context      (PangoLayout *layout);
void        pango_layout_context_changed    (PangoLayout *layout);
void        pango_layout_set_text           (PangoLayout *layout,
                                             const char *text,
                                             int length);
const char* pango_layout_get_text           (PangoLayout *layout);
void        pango_layout_set_markup         (PangoLayout *layout,
                                             const char *markup,
                                             int length);
void        pango_layout_set_markup_with_accel
                                            (PangoLayout *layout,
                                             const char *markup,
                                             int length,
                                             gunichar accel_marker,
                                             gunichar *accel_char);
void        pango_layout_set_attributes     (PangoLayout *layout,
                                             PangoAttrList *attrs);
PangoAttrList* pango_layout_get_attributes  (PangoLayout *layout);
void        pango_layout_set_font_description
                                            (PangoLayout *layout,
                                             const PangoFontDescription *desc);
const PangoFontDescription* pango_layout_get_font_description
                                            (PangoLayout *layout);
void        pango_layout_set_width          (PangoLayout *layout,
                                             int width);
int         pango_layout_get_width          (PangoLayout *layout);
void        pango_layout_set_wrap           (PangoLayout *layout,
                                             PangoWrapMode wrap);
PangoWrapMode pango_layout_get_wrap         (PangoLayout *layout);
gboolean    pango_layout_is_wrapped         (PangoLayout *layout);
enum        PangoWrapMode;
#define     PANGO_TYPE_WRAP_MODE
void        pango_layout_set_ellipsize      (PangoLayout *layout,
                                             PangoEllipsizeMode ellipsize);
PangoEllipsizeMode pango_layout_get_ellipsize
                                            (PangoLayout *layout);
gboolean    pango_layout_is_ellipsized      (PangoLayout *layout);
enum        PangoEllipsizeMode;
#define     PANGO_TYPE_ELLIPSIZE_MODE
void        pango_layout_set_indent         (PangoLayout *layout,
                                             int indent);
int         pango_layout_get_indent         (PangoLayout *layout);
int         pango_layout_get_spacing        (PangoLayout *layout);
void        pango_layout_set_spacing        (PangoLayout *layout,
                                             int spacing);
void        pango_layout_set_justify        (PangoLayout *layout,
                                             gboolean justify);
gboolean    pango_layout_get_justify        (PangoLayout *layout);
void        pango_layout_set_auto_dir       (PangoLayout *layout,
                                             gboolean auto_dir);
gboolean    pango_layout_get_auto_dir       (PangoLayout *layout);
void        pango_layout_set_alignment      (PangoLayout *layout,
                                             PangoAlignment alignment);
PangoAlignment pango_layout_get_alignment   (PangoLayout *layout);
void        pango_layout_set_tabs           (PangoLayout *layout,
                                             PangoTabArray *tabs);
PangoTabArray* pango_layout_get_tabs        (PangoLayout *layout);
void        pango_layout_set_single_paragraph_mode
                                            (PangoLayout *layout,
                                             gboolean setting);
gboolean    pango_layout_get_single_paragraph_mode
                                            (PangoLayout *layout);
enum        PangoAlignment;
#define     PANGO_TYPE_ALIGNMENT
int         pango_layout_get_unknown_glyphs_count
                                            (PangoLayout *layout);
void        pango_layout_get_log_attrs      (PangoLayout *layout,
                                             PangoLogAttr **attrs,
                                             gint *n_attrs);
void        pango_layout_index_to_pos       (PangoLayout *layout,
                                             int index_,
                                             PangoRectangle *pos);
void        pango_layout_index_to_line_x    (PangoLayout *layout,
                                             int index_,
                                             gboolean trailing,
                                             int *line,
                                             int *x_pos);
gboolean    pango_layout_xy_to_index        (PangoLayout *layout,
                                             int x,
                                             int y,
                                             int *index_,
                                             int *trailing);
void        pango_layout_get_cursor_pos     (PangoLayout *layout,
                                             int index_,
                                             PangoRectangle *strong_pos,
                                             PangoRectangle *weak_pos);
void        pango_layout_move_cursor_visually
                                            (PangoLayout *layout,
                                             gboolean strong,
                                             int old_index,
                                             int old_trailing,
                                             int direction,
                                             int *new_index,
                                             int *new_trailing);
void        pango_layout_get_extents        (PangoLayout *layout,
                                             PangoRectangle *ink_rect,
                                             PangoRectangle *logical_rect);
void        pango_layout_get_pixel_extents  (PangoLayout *layout,
                                             PangoRectangle *ink_rect,
                                             PangoRectangle *logical_rect);
void        pango_layout_get_size           (PangoLayout *layout,
                                             int *width,
                                             int *height);
void        pango_layout_get_pixel_size     (PangoLayout *layout,
                                             int *width,
                                             int *height);
int         pango_layout_get_line_count     (PangoLayout *layout);
PangoLayoutLine* pango_layout_get_line      (PangoLayout *layout,
                                             int line);
PangoLayoutLine* pango_layout_get_line_readonly
                                            (PangoLayout *layout,
                                             int line);
GSList*     pango_layout_get_lines          (PangoLayout *layout);
GSList*     pango_layout_get_lines_readonly (PangoLayout *layout);
PangoLayoutIter* pango_layout_get_iter      (PangoLayout *layout);
void        pango_layout_iter_free          (PangoLayoutIter *iter);
gboolean    pango_layout_iter_next_run      (PangoLayoutIter *iter);
gboolean    pango_layout_iter_next_char     (PangoLayoutIter *iter);
gboolean    pango_layout_iter_next_cluster  (PangoLayoutIter *iter);
gboolean    pango_layout_iter_next_line     (PangoLayoutIter *iter);
gboolean    pango_layout_iter_at_last_line  (PangoLayoutIter *iter);
int         pango_layout_iter_get_index     (PangoLayoutIter *iter);
int         pango_layout_iter_get_baseline  (PangoLayoutIter *iter);
PangoLayoutRun* pango_layout_iter_get_run   (PangoLayoutIter *iter);
PangoLayoutRun* pango_layout_iter_get_run_readonly
                                            (PangoLayoutIter *iter);
PangoLayoutLine* pango_layout_iter_get_line (PangoLayoutIter *iter);
PangoLayoutLine* pango_layout_iter_get_line_readonly
                                            (PangoLayoutIter *iter);
void        pango_layout_iter_get_char_extents
                                            (PangoLayoutIter *iter,
                                             PangoRectangle *logical_rect);
void        pango_layout_iter_get_cluster_extents
                                            (PangoLayoutIter *iter,
                                             PangoRectangle *ink_rect,
                                             PangoRectangle *logical_rect);
void        pango_layout_iter_get_run_extents
                                            (PangoLayoutIter *iter,
                                             PangoRectangle *ink_rect,
                                             PangoRectangle *logical_rect);
void        pango_layout_iter_get_line_yrange
                                            (PangoLayoutIter *iter,
                                             int *y0_,
                                             int *y1_);
void        pango_layout_iter_get_line_extents
                                            (PangoLayoutIter *iter,
                                             PangoRectangle *ink_rect,
                                             PangoRectangle *logical_rect);
void        pango_layout_iter_get_layout_extents
                                            (PangoLayoutIter *iter,
                                             PangoRectangle *ink_rect,
                                             PangoRectangle *logical_rect);

            PangoLayoutLine;
typedef     PangoLayoutRun;
PangoLayoutLine* pango_layout_line_ref      (PangoLayoutLine *line);
void        pango_layout_line_unref         (PangoLayoutLine *line);
void        pango_layout_line_get_extents   (PangoLayoutLine *line,
                                             PangoRectangle *ink_rect,
                                             PangoRectangle *logical_rect);
void        pango_layout_line_get_pixel_extents
                                            (PangoLayoutLine *layout_line,
                                             PangoRectangle *ink_rect,
                                             PangoRectangle *logical_rect);
void        pango_layout_line_index_to_x    (PangoLayoutLine *line,
                                             int index_,
                                             gboolean trailing,
                                             int *x_pos);
gboolean    pango_layout_line_x_to_index    (PangoLayoutLine *line,
                                             int x_pos,
                                             int *index_,
                                             int *trailing);
void        pango_layout_line_get_x_ranges  (PangoLayoutLine *line,
                                             int start_index,
                                             int end_index,
                                             int **ranges,
                                             int *n_ranges);

Description

While complete access to the layout capabilities of Pango is provided using the detailed interfaces for itemization and shaping, using that functionality directly involves writing a fairly large amount of code. The objects and functions in this section provide a high-level driver for formatting entire paragraphs of text at once.

Details

PangoLayout

typedef struct _PangoLayout PangoLayout;

The PangoLayout structure represents and entire paragraph of text. It is initialized with a PangoContext, UTF-8 string and set of attributes for that string. Once that is done, the set of formatted lines can be extracted from the object, the layout can be rendered, and conversion between logical character positions within the layout's text, and the physical position of the resulting glyphs can be made.

There are also a number of parameters to adjust the formatting of a PangoLayout, which are illustrated in Figure 1, “Adjustable parameters for a PangoLayout”. It is possible, as well, to ignore the 2-D setup, and simply treat the results of a PangoLayout as a list of lines.

Figure 1. Adjustable parameters for a PangoLayout

Adjustable parameters for a PangoLayout

The PangoLayout structure is opaque, and has no user-visible fields.

PangoLayoutIter

typedef struct _PangoLayoutIter PangoLayoutIter;

A PangoLayoutIter structure can be used to iterate over the visual extents of a PangoLayout.

The PangoLayoutIter structure is opaque, and has no user-visible fields.

pango_layout_new ()

PangoLayout* pango_layout_new               (PangoContext *context);

Create a new PangoLayout object with attributes initialized to default values for a particular PangoContext.

context : | a PangoContext
Returns : | the newly allocated PangoLayout, with a reference count of one, which should be freed with g_object_unref().

pango_layout_copy ()

PangoLayout* pango_layout_copy              (PangoLayout *src);

Does a deep copy-by-value of the src layout. The attribute list, tab array, and text from the original layout are all copied by value.

src : | a PangoLayout
Returns : | the newly allocated PangoLayout, with a reference count of one, which should be freed with g_object_unref().

pango_layout_get_context ()

PangoContext* pango_layout_get_context      (PangoLayout *layout);

Retrieves the PangoContext used for this layout.

layout : | a PangoLayout
Returns : | the PangoContext for the layout. This does not have an additional refcount added, so if you want to keep a copy of this around, you must reference it yourself.

pango_layout_context_changed ()

void        pango_layout_context_changed    (PangoLayout *layout);

Forces recomputation of any state in the PangoLayout that might depend on the layout's context. This function should be called if you make changes to the context subsequent to creating the layout.

layout : a PangoLayout

pango_layout_set_text ()

void        pango_layout_set_text           (PangoLayout *layout,
                                             const char *text,
                                             int length);

Sets the text of the layout.

layout : | a PangoLayout
text : | a valid UTF-8 string
length : | maximum length of text, in bytes. -1 indicates that the string is nul-terminated and the length should be calculated. The text will also be truncated on encountering a nul-termination even when length is positive.

pango_layout_get_text ()

const char* pango_layout_get_text           (PangoLayout *layout);

Gets the text in the layout. The returned text should not be freed or modified.

layout : | a PangoLayout
Returns : | the text in the layout.

pango_layout_set_markup ()

void        pango_layout_set_markup         (PangoLayout *layout,
                                             const char *markup,
                                             int length);

Same as pango_layout_set_markup_with_accel(), but the markup text isn't scanned for accelerators.

layout : | a PangoLayout
markup : | marked-up text
length : | length of marked-up text in bytes, or -1 if markup is nul-terminated

pango_layout_set_markup_with_accel ()

void        pango_layout_set_markup_with_accel
                                            (PangoLayout *layout,
                                             const char *markup,
                                             int length,
                                             gunichar accel_marker,
                                             gunichar *accel_char);

Sets the layout text and attribute list from marked-up text (see markup format). Replaces the current text and attribute list.

If accel_marker is nonzero, the given character will mark the character following it as an accelerator. For example, accel_marker might be an ampersand or underscore. All characters marked as an accelerator will receive a PANGO_UNDERLINE_LOW attribute, and the first character so marked will be returned in accel_char. Two accel_marker characters following each other produce a single literal accel_marker character.

layout : | a PangoLayout
markup : | marked-up text (see markup format)
length : | length of marked-up text in bytes, or -1 if markup is nul-terminated
accel_marker : | marker for accelerators in the text
accel_char : | return location for first located accelerator, or NULL

pango_layout_set_attributes ()

void        pango_layout_set_attributes     (PangoLayout *layout,
                                             PangoAttrList *attrs);

Sets the text attributes for a layout object.

layout : | a PangoLayout
attrs : | a PangoAttrList

pango_layout_get_attributes ()

PangoAttrList* pango_layout_get_attributes  (PangoLayout *layout);

Gets the attribute list for the layout, if any.

layout : | a PangoLayout
Returns : | a PangoAttrList.

pango_layout_set_font_description ()

void        pango_layout_set_font_description
                                            (PangoLayout *layout,
                                             const PangoFontDescription *desc);

Sets the default font description for the layout. If no font description is set on the layout, the font description from the layout's context is used.

layout : | a PangoLayout
desc : | the new PangoFontDescription, or NULL to unset the current font description

pango_layout_get_font_description ()

const PangoFontDescription* pango_layout_get_font_description
                                            (PangoLayout *layout);

Gets the font description for the layout, if any.

layout : | a PangoLayout
Returns : | a pointer to the layout's font description, or NULL if the font description from the layout's context is inherited. This value is owned by the layout and must not be modified or freed.

Since 1.8

pango_layout_set_width ()

void        pango_layout_set_width          (PangoLayout *layout,
                                             int width);

Sets the width to which the lines of the PangoLayout should wrap.

layout : | a PangoLayout.
width : | the desired width in Pango units, or -1 to indicate that no wrapping should be performed.

pango_layout_get_width ()

int         pango_layout_get_width          (PangoLayout *layout);

Gets the width to which the lines of the PangoLayout should wrap.

layout : | a PangoLayout
Returns : | the width, or -1 if no width set.

pango_layout_set_wrap ()

void        pango_layout_set_wrap           (PangoLayout *layout,
                                             PangoWrapMode wrap);

Sets the wrap mode; the wrap mode only has effect if a width is set on the layout with pango_layout_set_width(). To turn off wrapping, set the width to -1.

layout : | a PangoLayout
wrap : | the wrap mode

pango_layout_get_wrap ()

PangoWrapMode pango_layout_get_wrap         (PangoLayout *layout);

Gets the wrap mode for the layout.

Use pango_layout_is_wrapped() to query whether any paragraphs were actually wrapped.

layout : | a PangoLayout
Returns : | active wrap mode.

pango_layout_is_wrapped ()

gboolean    pango_layout_is_wrapped         (PangoLayout *layout);

Queries whether the layout had to wrap any paragraphs.

This returns TRUE if a positive width is set on layout, ellipsization mode of layout is set to PANGO_ELLIPSIZE_NONE, and there are paragraphs exceeding the layout width that have to be wrapped.

layout : | a PangoLayout
Returns : | TRUE if any paragraphs had to be wrapped, FALSE otherwise.

Since 1.16

enum PangoWrapMode

typedef enum {
  PANGO_WRAP_WORD,
  PANGO_WRAP_CHAR,
  PANGO_WRAP_WORD_CHAR
} PangoWrapMode;

A PangoWrapMode describes how to wrap the lines of a PangoLayout to the desired width.

PANGO_WRAP_WORD | wrap lines at word boundaries.
PANGO_WRAP_CHAR | wrap lines at character boundaries.
PANGO_WRAP_WORD_CHAR | wrap lines at word boundaries, but fall back to character boundaries if there is not enough space for a full word.

PANGO_TYPE_WRAP_MODE

#define PANGO_TYPE_WRAP_MODE (pango_wrap_mode_get_type())

The GObject type for PangoWrapMode.

pango_layout_set_ellipsize ()

void        pango_layout_set_ellipsize      (PangoLayout *layout,
                                             PangoEllipsizeMode ellipsize);

Sets the type of ellipsization being performed for layout. Depending on the ellipsization mode ellipsize text is removed from the start, middle, or end of lines so they fit within the width of layout set with pango_layout_set_width().

If the layout contains characters such as newlines that force it to be layed out in multiple lines, then each line is ellipsized separately.

layout : | a PangoLayout
ellipsize : | the new ellipsization mode for layout

Since 1.6

pango_layout_get_ellipsize ()

PangoEllipsizeMode pango_layout_get_ellipsize
                                            (PangoLayout *layout);

Gets the type of ellipsization being performed for layout. See pango_layout_set_ellipsize()

layout : | a PangoLayout
Returns : | the current ellipsization mode for layout. Use pango_layout_is_ellipsized() to query whether any paragraphs were actually ellipsized.

Since 1.6

pango_layout_is_ellipsized ()

gboolean    pango_layout_is_ellipsized      (PangoLayout *layout);

Queries whether the layout had to ellipsize any paragraphs.

This returns TRUE if the ellipsization mode for layout is not PANGO_ELLIPSIZE_NONE, a positive width is set on layout, and there are paragraphs exceeding that width that have to be ellipsized.

layout : | a PangoLayout
Returns : | TRUE if any paragraphs had to be ellipsized, FALSE otherwise.

Since 1.16

enum PangoEllipsizeMode

typedef enum {
  PANGO_ELLIPSIZE_NONE,
  PANGO_ELLIPSIZE_START,
  PANGO_ELLIPSIZE_MIDDLE,
  PANGO_ELLIPSIZE_END
} PangoEllipsizeMode;

The PangoEllipsizeMode type describes what sort of (if any) ellipsization should be applied to a line of text. In the ellipsization process characters are removed from the text in order to make it fit to a given width and replaced with an ellipsis.

PANGO_ELLIPSIZE_NONE | No ellipsization
PANGO_ELLIPSIZE_START | Omit characters at the start of the text
PANGO_ELLIPSIZE_MIDDLE | Omit characters in the middle of the text
PANGO_ELLIPSIZE_END | Omit characters at the end of the text

PANGO_TYPE_ELLIPSIZE_MODE

#define PANGO_TYPE_ELLIPSIZE_MODE (pango_ellipsize_mode_get_type())

The GObject type for PangoEllipsizeMode.

pango_layout_set_indent ()

void        pango_layout_set_indent         (PangoLayout *layout,
                                             int indent);

Sets the width in Pango units to indent each paragraph. A negative value of indent will produce a hanging indentation. That is, the first line will have the full width, and subsequent lines will be indented by the absolute value of indent.

layout : | a PangoLayout.
indent : | the amount by which to indent.

pango_layout_get_indent ()

int         pango_layout_get_indent         (PangoLayout *layout);

Gets the paragraph indent width in Pango units. A negative value indicates a hanging indentation.

layout : | a PangoLayout
Returns : | the indent.

pango_layout_get_spacing ()

int         pango_layout_get_spacing        (PangoLayout *layout);

Gets the amount of spacing in PangoGlyphUnit between the lines of the layout.

layout : | a PangoLayout
Returns : | the spacing.

pango_layout_set_spacing ()

void        pango_layout_set_spacing        (PangoLayout *layout,
                                             int spacing);

Sets the amount of spacing in PangoGlyphUnit between the lines of the layout.

layout : | a PangoLayout.
spacing : | the amount of spacing

pango_layout_set_justify ()

void        pango_layout_set_justify        (PangoLayout *layout,
                                             gboolean justify);

Sets whether each complete line should be stretched to fill the entire width of the layout. This stretching is typically done by adding whitespace, but for some scripts (such as Arabic), the justification may be done in more complex ways, like extending the characters.

Note that as of Pango-1.16, this functionality is not yet implemented.

layout : | a PangoLayout
justify : | whether the lines in the layout should be justified.

pango_layout_get_justify ()

gboolean    pango_layout_get_justify        (PangoLayout *layout);

Gets whether each complete line should be stretched to fill the entire width of the layout.

layout : | a PangoLayout
Returns : | the justify.

pango_layout_set_auto_dir ()

void        pango_layout_set_auto_dir       (PangoLayout *layout,
                                             gboolean auto_dir);

Sets whether to calculate the bidirectional base direction for the layout according to the contents of the layout; when this flag is on (the default), then paragraphs in layout that begin with strong right-to-left characters (Arabic and Hebrew principally), will have right-to-left layout, paragraphs with letters from other scripts will have left-to-right layout. Paragraphs with only neutral characters get their direction from the surrounding paragraphs.

When FALSE, the choice between left-to-right and right-to-left layout is done according to the base direction of the layout's PangoContext. (See pango_context_set_base_dir()).

When the auto-computed direction of a paragraph differs from the base direction of the context, the interpretation of PANGO_ALIGN_LEFT and PANGO_ALIGN_RIGHT are swapped.

layout : | a PangoLayout
auto_dir : | if TRUE, compute the bidirectional base direction from the layout's contents.

Since 1.4

pango_layout_get_auto_dir ()

gboolean    pango_layout_get_auto_dir       (PangoLayout *layout);

Gets whether to calculate the bidirectional base direction for the layout according to the contents of the layout. See pango_layout_set_auto_dir().

layout : | a PangoLayout
Returns : | TRUE if the bidirectional base direction is computed from the layout's contents, FALSE otherwise.

Since 1.4

pango_layout_set_alignment ()

void        pango_layout_set_alignment      (PangoLayout *layout,
                                             PangoAlignment alignment);

Sets the alignment for the layout: how partial lines are positioned within the horizontal space available.

layout : | a PangoLayout
alignment : | the alignment

pango_layout_get_alignment ()

PangoAlignment pango_layout_get_alignment   (PangoLayout *layout);

Gets the alignment for the layout: how partial lines are positioned within the horizontal space available.

layout : | a PangoLayout
Returns : | the alignment.

pango_layout_set_tabs ()

void        pango_layout_set_tabs           (PangoLayout *layout,
                                             PangoTabArray *tabs);

Sets the tabs to use for layout, overriding the default tabs (by default, tabs are every 8 spaces). If tabs is NULL, the default tabs are reinstated. tabs is copied into the layout; you must free your copy of tabs yourself.

layout : | a PangoLayout
tabs : | a PangoTabArray

pango_layout_get_tabs ()

PangoTabArray* pango_layout_get_tabs        (PangoLayout *layout);

Gets the current PangoTabArray used by this layout. If no PangoTabArray has been set, then the default tabs are in use and NULL is returned. Default tabs are every 8 spaces. The return value should be freed with pango_tab_array_free().

layout : | a PangoLayout
Returns : | a copy of the tabs for this layout, or NULL.

pango_layout_set_single_paragraph_mode ()

void        pango_layout_set_single_paragraph_mode
                                            (PangoLayout *layout,
                                             gboolean setting);

If setting is TRUE, do not treat newlines and similar characters as paragraph separators; instead, keep all text in a single paragraph, and display a glyph for paragraph separator characters. Used when you want to allow editing of newlines on a single text line.

layout : | a PangoLayout
setting : | new setting

pango_layout_get_single_paragraph_mode ()

gboolean    pango_layout_get_single_paragraph_mode
                                            (PangoLayout *layout);

Obtains the value set by pango_layout_set_single_paragraph_mode().

layout : | a PangoLayout
Returns : | TRUE if the layout does not break paragraphs at paragraph separator characters, FALSE otherwise.

enum PangoAlignment

typedef enum {
  PANGO_ALIGN_LEFT,
  PANGO_ALIGN_CENTER,
  PANGO_ALIGN_RIGHT
} PangoAlignment;

A PangoAlignment describes how to align the lines of a PangoLayout within the available space. If the PangoLayout is set to justify using pango_layout_set_justify(), this only has effect for partial lines.

PANGO_ALIGN_LEFT | Put all available space on the right
PANGO_ALIGN_CENTER | Center the line within the available space
PANGO_ALIGN_RIGHT | Put all available space on the left

PANGO_TYPE_ALIGNMENT

#define PANGO_TYPE_ALIGNMENT (pango_alignment_get_type())

The GObject type for PangoAlignment.

pango_layout_get_unknown_glyphs_count ()

int         pango_layout_get_unknown_glyphs_count
                                            (PangoLayout *layout);

Counts the number unknown glyphs in layout. That is, zero if glyphs for all characters in the layout text were found, or more than zero otherwise.

layout : | a PangoLayout
Returns : | The number of unknown glyphs in layout.

Since 1.16

pango_layout_get_log_attrs ()

void        pango_layout_get_log_attrs      (PangoLayout *layout,
                                             PangoLogAttr **attrs,
                                             gint *n_attrs);

Retrieves an array of logical attributes for each character in the layout.

layout : | a PangoLayout
attrs : | location to store a pointer to an array of logical attributes This value must be freed with g_free().
n_attrs : | location to store the number of the attributes in the array. (The stored value will be one more than the total number of characters in the layout, since there need to be attributes corresponding to both the position before the first character and the position after the last character.)

pango_layout_index_to_pos ()

void        pango_layout_index_to_pos       (PangoLayout *layout,
                                             int index_,
                                             PangoRectangle *pos);

Converts from an index within a PangoLayout to the onscreen position corresponding to the grapheme at that index, which is represented as rectangle. Note that pos->x is always the leading edge of the grapheme and pos->x + pos->width the trailing edge of the grapheme. If the directionality of the grapheme is right-to-left, then pos->width will be negative.

layout : | a PangoLayout
index_ : | byte index within layout
pos : | rectangle in which to store the position of the grapheme

pango_layout_index_to_line_x ()

void        pango_layout_index_to_line_x    (PangoLayout *layout,
                                             int index_,
                                             gboolean trailing,
                                             int *line,
                                             int *x_pos);

Converts from byte index_ within the layout to line and X position. (X position is measured from the left edge of the line)

layout : | a PangoLayout
index_ : | the byte index of a grapheme within the layout.
trailing : | an integer indicating the edge of the grapheme to retrieve the position of. If 0, the trailing edge of the grapheme, if > 0, the leading of the grapheme.
line : | location to store resulting line index. (which will between 0 and pango_layout_get_line_count(layout) - 1)
x_pos : | location to store resulting position within line (PANGO_SCALE units per device unit)

pango_layout_xy_to_index ()

gboolean    pango_layout_xy_to_index        (PangoLayout *layout,
                                             int x,
                                             int y,
                                             int *index_,
                                             int *trailing);

Converts from X and Y position within a layout to the byte index to the character at that logical position. If the Y position is not inside the layout, the closest position is chosen (the position will be clamped inside the layout). If the X position is not within the layout, then the start or the end of the line is chosen as described for pango_layout_x_to_index(). If either the X or Y positions were not inside the layout, then the function returns FALSE; on an exact hit, it returns TRUE.

layout : | a PangoLayout
x : | the X offset (in PangoGlyphUnit) from the left edge of the layout.
y : | the Y offset (in PangoGlyphUnit) from the top edge of the layout
index_ : | location to store calculated byte index
trailing : | location to store a integer indicating where in the grapheme the user clicked. It will either be zero, or the number of characters in the grapheme. 0 represents the trailing edge of the grapheme.
Returns : | TRUE if the coordinates were inside text, FALSE otherwise.

pango_layout_get_cursor_pos ()

void        pango_layout_get_cursor_pos     (PangoLayout *layout,
                                             int index_,
                                             PangoRectangle *strong_pos,
                                             PangoRectangle *weak_pos);

Given an index within a layout, determines the positions that of the strong and weak cursors if the insertion point is at that index. The position of each cursor is stored as a zero-width rectangle. The strong cursor location is the location where characters of the directionality equal to the base direction of the layout are inserted. The weak cursor location is the location where characters of the directionality opposite to the base direction of the layout are inserted.

layout : | a PangoLayout
index_ : | the byte index of the cursor
strong_pos : | location to store the strong cursor position (may be NULL)
weak_pos : | location to store the weak cursor position (may be NULL)

pango_layout_move_cursor_visually ()

void        pango_layout_move_cursor_visually
                                            (PangoLayout *layout,
                                             gboolean strong,
                                             int old_index,
                                             int old_trailing,
                                             int direction,
                                             int *new_index,
                                             int *new_trailing);

Computes a new cursor position from an old position and a count of positions to move visually. If direction is positive, then the new strong cursor position will be one position to the right of the old cursor position. If direction is negative, then the new strong cursor position will be one position to the left of the old cursor position.

In the presence of bidirectional text, the correspondence between logical and visual order will depend on the direction of the current run, and there may be jumps when the cursor is moved off of the end of a run.

Motion here is in cursor positions, not in characters, so a single call to pango_layout_move_cursor_visually() may move the cursor over multiple characters when multiple characters combine to form a single grapheme.

layout : | a PangoLayout.
strong : | whether the moving cursor is the strong cursor or the weak cursor. The strong cursor is the cursor corresponding to text insertion in the base direction for the layout.
old_index : | the byte index of the grapheme for the old index
old_trailing : | if 0, the cursor was at the trailing edge of the grapheme indicated by old_index, if > 0, the cursor was at the leading edge.
direction : | direction to move cursor. A negative value indicates motion to the left.
new_index : | location to store the new cursor byte index. A value of -1 indicates that the cursor has been moved off the beginning of the layout. A value of G_MAXINT indicates that the cursor has been moved off the end of the layout.
new_trailing : | number of characters to move forward from the location returned for new_index to get the position where the cursor should be displayed. This allows distinguishing the position at the beginning of one line from the position at the end of the preceding line. new_index is always on the line where the cursor should be displayed.

pango_layout_get_extents ()

void        pango_layout_get_extents        (PangoLayout *layout,
                                             PangoRectangle *ink_rect,
                                             PangoRectangle *logical_rect);

Computes the logical and ink extents of layout. Logical extents are usually what you want for positioning things. Note that both extents may have non-zero x and y. You may want to use those to offset where you render the layout. Not doing that is a very typical bug that shows up as right-to-left layouts not being correctly positioned in a layout with a set width.

The extents are given in layout coordinates and in Pango units; layout coordinates begin at the top left corner of the layout.

layout : | a PangoLayout
ink_rect : | rectangle used to store the extents of the layout as drawn or NULL to indicate that the result is not needed.
logical_rect : | rectangle used to store the logical extents of the layout or NULL to indicate that the result is not needed.

pango_layout_get_pixel_extents ()

void        pango_layout_get_pixel_extents  (PangoLayout *layout,
                                             PangoRectangle *ink_rect,
                                             PangoRectangle *logical_rect);

Computes the logical and ink extents of layout in device units. This function just calls pango_layout_get_extents() followed by pango_extents_to_pixels().

layout : | a PangoLayout
ink_rect : | rectangle used to store the extents of the layout as drawn or NULL to indicate that the result is not needed.
logical_rect : | rectangle used to store the logical extents of the layout or NULL to indicate that the result is not needed.

pango_layout_get_size ()

void        pango_layout_get_size           (PangoLayout *layout,
                                             int *width,
                                             int *height);

Determines the logical width and height of a PangoLayout in Pango units (device units scaled by PANGO_SCALE). This is simply a convenience function around pango_layout_get_extents().

layout : | a PangoLayout
width : | location to store the logical width, or NULL
height : | location to store the logical height, or NULL

pango_layout_get_pixel_size ()

void        pango_layout_get_pixel_size     (PangoLayout *layout,
                                             int *width,
                                             int *height);

Determines the logical width and height of a PangoLayout in device units. (pango_layout_get_size() returns the width and height scaled by PANGO_SCALE.) This is simply a convenience function around pango_layout_get_pixel_extents().

layout : | a PangoLayout
width : | location to store the logical width, or NULL
height : | location to store the logical height, or NULL

pango_layout_get_line_count ()

int         pango_layout_get_line_count     (PangoLayout *layout);

Retrieves the count of lines for the layout.

layout : | PangoLayout
Returns : | the line count.

pango_layout_get_line ()

PangoLayoutLine* pango_layout_get_line      (PangoLayout *layout,
                                             int line);

Retrieves a particular line from a PangoLayout.

Use the faster pango_layout_get_line_readonly() if you do not plan to modify the contents of the line (glyphs, glyph widths, etc.).

layout : | a PangoLayout
line : | the index of a line, which must be between 0 and pango_layout_get_line_count(layout) - 1, inclusive.
Returns : | the requested PangoLayoutLine, or NULL if the index is out of range. This layout line can be ref'ed and retained, but will become invalid if changes are made to the PangoLayout.

pango_layout_get_line_readonly ()

PangoLayoutLine* pango_layout_get_line_readonly
                                            (PangoLayout *layout,
                                             int line);

Retrieves a particular line from a PangoLayout.

This is a faster alternative to pango_layout_get_line(), but the user is not expected to modify the contents of the line (glyphs, glyph widths, etc.).

layout : | a PangoLayout
line : | the index of a line, which must be between 0 and pango_layout_get_line_count(layout) - 1, inclusive.
Returns : | the requested PangoLayoutLine, or NULL if the index is out of range. This layout line can be ref'ed and retained, but will become invalid if changes are made to the PangoLayout. No changes should be made to the line.

Since 1.16

pango_layout_get_lines ()

GSList*     pango_layout_get_lines          (PangoLayout *layout);

Returns the lines of the layout as a list.

Use the faster pango_layout_get_lines_readonly() if you do not plan to modify the contents of the lines (glyphs, glyph widths, etc.).

layout : | a PangoLayout
Returns : | a GSList containing the lines in the layout. This points to internal data of the PangoLayout and must be used with care. It will become invalid on any change to the layout's text or properties.

pango_layout_get_lines_readonly ()

GSList*     pango_layout_get_lines_readonly (PangoLayout *layout);

Returns the lines of the layout as a list.

This is a faster alternative to pango_layout_get_lines(), but the user is not expected to modify the contents of the lines (glyphs, glyph widths, etc.).

layout : | a PangoLayout
Returns : | a GSList containing the lines in the layout. This points to internal data of the PangoLayout and must be used with care. It will become invalid on any change to the layout's text or properties. No changes should be made to the lines.

Since 1.16

pango_layout_get_iter ()

PangoLayoutIter* pango_layout_get_iter      (PangoLayout *layout);

Returns an iterator to iterate over the visual extents of the layout.

layout : | a PangoLayout
Returns : | the new PangoLayoutIter that should be freed using pango_layout_iter_free().

pango_layout_iter_free ()

void        pango_layout_iter_free          (PangoLayoutIter *iter);

Frees an iterator that's no longer in use.

iter : a PangoLayoutIter

pango_layout_iter_next_run ()

gboolean    pango_layout_iter_next_run      (PangoLayoutIter *iter);

Moves iter forward to the next run in visual order. If iter was already at the end of the layout, returns FALSE.

iter : | a PangoLayoutIter
Returns : | whether motion was possible.

pango_layout_iter_next_char ()

gboolean    pango_layout_iter_next_char     (PangoLayoutIter *iter);

Moves iter forward to the next character in visual order. If iter was already at the end of the layout, returns FALSE.

iter : | a PangoLayoutIter
Returns : | whether motion was possible.

pango_layout_iter_next_cluster ()

gboolean    pango_layout_iter_next_cluster  (PangoLayoutIter *iter);

Moves iter forward to the next cluster in visual order. If iter was already at the end of the layout, returns FALSE.

iter : | a PangoLayoutIter
Returns : | whether motion was possible.

pango_layout_iter_next_line ()

gboolean    pango_layout_iter_next_line     (PangoLayoutIter *iter);

Moves iter forward to the start of the next line. If iter is already on the last line, returns FALSE.

iter : | a PangoLayoutIter
Returns : | whether motion was possible.

pango_layout_iter_at_last_line ()

gboolean    pango_layout_iter_at_last_line  (PangoLayoutIter *iter);

Determines whether iter is on the last line of the layout.

iter : | a PangoLayoutIter
Returns : | TRUE if iter is on the last line.

pango_layout_iter_get_index ()

int         pango_layout_iter_get_index     (PangoLayoutIter *iter);

Gets the current byte index. Note that iterating forward by char moves in visual order, not logical order, so indexes may not be sequential. Also, the index may be equal to the length of the text in the layout, if on the NULL run (see pango_layout_iter_get_run()).

iter : | a PangoLayoutIter
Returns : | current byte index.

pango_layout_iter_get_baseline ()

int         pango_layout_iter_get_baseline  (PangoLayoutIter *iter);

Gets the Y position of the current line's baseline, in layout coordinates (origin at top left of the entire layout).

iter : | a PangoLayoutIter
Returns : | baseline of current line.

pango_layout_iter_get_run ()

PangoLayoutRun* pango_layout_iter_get_run   (PangoLayoutIter *iter);

Gets the current run. When iterating by run, at the end of each line, there's a position with a NULL run, so this function can return NULL. The NULL run at the end of each line ensures that all lines have at least one run, even lines consisting of only a newline.

Use the faster pango_layout_iter_get_run_readonly() if you do not plan to modify the contents of the run (glyphs, glyph widths, etc.).

iter : | a PangoLayoutIter
Returns : | the current run.

pango_layout_iter_get_run_readonly ()

PangoLayoutRun* pango_layout_iter_get_run_readonly
                                            (PangoLayoutIter *iter);

Gets the current run. When iterating by run, at the end of each line, there's a position with a NULL run, so this function can return NULL. The NULL run at the end of each line ensures that all lines have at least one run, even lines consisting of only a newline.

This is a faster alternative to pango_layout_iter_get_run(), but the user is not expected to modify the contents of the run (glyphs, glyph widths, etc.).

iter : | a PangoLayoutIter
Returns : | the current run, that should not be modified.

Since 1.16

pango_layout_iter_get_line ()

PangoLayoutLine* pango_layout_iter_get_line (PangoLayoutIter *iter);

Gets the current line.

Use the faster pango_layout_iter_get_line_readonly() if you do not plan to modify the contents of the line (glyphs, glyph widths, etc.).

iter : | a PangoLayoutIter
Returns : | the current line.

pango_layout_iter_get_line_readonly ()

PangoLayoutLine* pango_layout_iter_get_line_readonly
                                            (PangoLayoutIter *iter);

Gets the current line for read-only access.

This is a faster alternative to pango_layout_iter_get_line(), but the user is not expected to modify the contents of the line (glyphs, glyph widths, etc.).

iter : | a PangoLayoutIter
Returns : | the current line, that should not be modified.

Since 1.16

pango_layout_iter_get_char_extents ()

void        pango_layout_iter_get_char_extents
                                            (PangoLayoutIter *iter,
                                             PangoRectangle *logical_rect);

Gets the extents of the current character, in layout coordinates (origin is the top left of the entire layout). Only logical extents can sensibly be obtained for characters; ink extents make sense only down to the level of clusters.

iter : | a PangoLayoutIter
logical_rect : | rectangle to fill with logical extents

pango_layout_iter_get_cluster_extents ()

void        pango_layout_iter_get_cluster_extents
                                            (PangoLayoutIter *iter,
                                             PangoRectangle *ink_rect,
                                             PangoRectangle *logical_rect);

Gets the extents of the current cluster, in layout coordinates (origin is the top left of the entire layout).

iter : | a PangoLayoutIter
ink_rect : | rectangle to fill with ink extents, or NULL
logical_rect : | rectangle to fill with logical extents, or NULL

pango_layout_iter_get_run_extents ()

void        pango_layout_iter_get_run_extents
                                            (PangoLayoutIter *iter,
                                             PangoRectangle *ink_rect,
                                             PangoRectangle *logical_rect);

Gets the extents of the current run in layout coordinates (origin is the top left of the entire layout).

iter : | a PangoLayoutIter
ink_rect : | rectangle to fill with ink extents, or NULL
logical_rect : | rectangle to fill with logical extents, or NULL

pango_layout_iter_get_line_yrange ()

void        pango_layout_iter_get_line_yrange
                                            (PangoLayoutIter *iter,
                                             int *y0_,
                                             int *y1_);

Divides the vertical space in the PangoLayout being iterated over between the lines in the layout, and returns the space belonging to the current line. A line's range includes the line's logical extents, plus half of the spacing above and below the line, if pango_layout_set_spacing() has been called to set layout spacing. The Y positions are in layout coordinates (origin at top left of the entire layout).

iter : | a PangoLayoutIter
y0_ : | start of line
y1_ : | end of line

pango_layout_iter_get_line_extents ()

void        pango_layout_iter_get_line_extents
                                            (PangoLayoutIter *iter,
                                             PangoRectangle *ink_rect,
                                             PangoRectangle *logical_rect);

Obtains the extents of the current line. ink_rect or logical_rect can be NULL if you aren't interested in them. Extents are in layout coordinates (origin is the top-left corner of the entire PangoLayout). Thus the extents returned by this function will be the same width/height but not at the same x/y as the extents returned from pango_layout_line_get_extents().

iter : | a PangoLayoutIter
ink_rect : | rectangle to fill with ink extents, or NULL
logical_rect : | rectangle to fill with logical extents, or NULL

pango_layout_iter_get_layout_extents ()

void        pango_layout_iter_get_layout_extents
                                            (PangoLayoutIter *iter,
                                             PangoRectangle *ink_rect,
                                             PangoRectangle *logical_rect);

Obtains the extents of the PangoLayout being iterated over. ink_rect or logical_rect can be NULL if you aren't interested in them.

iter : | a PangoLayoutIter
ink_rect : | rectangle to fill with ink extents, or NULL
logical_rect : | rectangle to fill with logical extents, or NULL

PangoLayoutLine

typedef struct {
  PangoLayout *layout;
  gint         start_index;     /* start of line as byte index into layout->text */
  gint         length;		/* length of line in bytes */
  GSList      *runs;
  guint        is_paragraph_start : 1;  /* TRUE if this is the first line of the paragraph */
  guint        resolved_dir : 3;  /* Resolved PangoDirection of line */
} PangoLayoutLine;

The PangoLayoutLine structure represents one of the lines resulting from laying out a paragraph via PangoLayout. PangoLayoutLine structures are obtained by calling pango_layout_get_line() and are only valid until the text, attributes, or settings of the parent PangoLayout are modified.

Routines for rendering PangoLayout objects are provided in code specific to each rendering system.

PangoLayout *layout; | the parent layout for this line
gint start_index; | the start of the line as byte index into layout->text
gint length; | the length of the line in bytes
GSList *runs; | a list containing the runs of the line in visual order
guint is_paragraph_start : 1; | TRUE if this is the first line of the paragraph
guint resolved_dir : 3; | the resolved PangoDirection of the line

PangoLayoutRun

typedef PangoGlyphItem PangoLayoutRun;

The PangoLayoutRun structure represents a single run within a PangoLayoutLine; it is simply an alternate name for PangoGlyphItem, present for backwards compatibility. See the PangoGlyphItem docs for details on the fields.

pango_layout_line_ref ()

PangoLayoutLine* pango_layout_line_ref      (PangoLayoutLine *line);

Increase the reference count of a PangoLayoutLine by one.

line : | a PangoLayoutLine
Returns : | the line passed in.

Since 1.10

pango_layout_line_unref ()

void        pango_layout_line_unref         (PangoLayoutLine *line);

Decrease the reference count of a PangoLayoutLine by one. If the result is zero, the line and all associated memory will be freed.

line : a PangoLayoutLine

pango_layout_line_get_extents ()

void        pango_layout_line_get_extents   (PangoLayoutLine *line,
                                             PangoRectangle *ink_rect,
                                             PangoRectangle *logical_rect);

Computes the logical and ink extents of a layout line. See pango_font_get_glyph_extents() for details about the interpretation of the rectangles.

line : | a PangoLayoutLine
ink_rect : | rectangle used to store the extents of the glyph string as drawn, or NULL
logical_rect : | rectangle used to store the logical extents of the glyph string, or NULL

pango_layout_line_get_pixel_extents ()

void        pango_layout_line_get_pixel_extents
                                            (PangoLayoutLine *layout_line,
                                             PangoRectangle *ink_rect,
                                             PangoRectangle *logical_rect);

Computes the logical and ink extents of layout_line in device units. This function just calls pango_layout_line_get_extents() followed by pango_extents_to_pixels().

layout_line : | a PangoLayoutLine
ink_rect : | rectangle used to store the extents of the glyph string as drawn, or NULL
logical_rect : | rectangle used to store the logical extents of the glyph string, or NULL

pango_layout_line_index_to_x ()

void        pango_layout_line_index_to_x    (PangoLayoutLine *line,
                                             int index_,
                                             gboolean trailing,
                                             int *x_pos);

Converts an index within a line to a X position.

line : | a PangoLayoutLine
index_ : | byte offset of a grapheme within the layout
trailing : | an integer indicating the edge of the grapheme to retrieve the position of. If 0, the trailing edge of the grapheme, if > 0, the leading of the grapheme.
x_pos : | location to store the x_offset (in PangoGlyphUnit)

pango_layout_line_x_to_index ()

gboolean    pango_layout_line_x_to_index    (PangoLayoutLine *line,
                                             int x_pos,
                                             int *index_,
                                             int *trailing);

Converts from x offset to the byte index of the corresponding character within the text of the layout. If x_pos is outside the line, index_ and trailing will point to the very first or very last position in the line. This determination is based on the resolved direction of the paragraph; for example, if the resolved direction is right-to-left, then an X position to the right of the line (after it) results in 0 being stored in index_ and trailing. An X position to the left of the line results in index_ pointing to the (logical) last grapheme in the line and trailing being set to the number of characters in that grapheme. The reverse is true for a left-to-right line.

line : | a PangoLayoutLine
x_pos : | the X offset (in PangoGlyphUnit) from the left edge of the line.
index_ : | location to store calculated byte index for the grapheme in which the user clicked.
trailing : | location to store a integer indicating where in the grapheme the user clicked. It will either be zero, or the number of characters in the grapheme. 0 represents the trailing edge of the grapheme.
Returns : | FALSE if x_pos was outside the line, TRUE if inside

pango_layout_line_get_x_ranges ()

void        pango_layout_line_get_x_ranges  (PangoLayoutLine *line,
                                             int start_index,
                                             int end_index,
                                             int **ranges,
                                             int *n_ranges);

Gets a list of visual ranges corresponding to a given logical range. This list is not necessarily minimal - there may be consecutive ranges which are adjacent. The ranges will be sorted from left to right. The ranges are with respect to the left edge of the entire layout, not with respect to the line.

line : | a PangoLayoutLine
start_index : | Start byte index of the logical range. If this value is less than the start index for the line, then the first range will extend all the way to the leading edge of the layout. Otherwise it will start at the leading edge of the first character.
end_index : | Ending byte index of the logical range. If this value is greater than the end index for the line, then the last range will extend all the way to the trailing edge of the layout. Otherwise, it will end at the trailing edge of the last character.
ranges : | location to store a pointer to an array of ranges. The array will be of length 2*n_ranges, with each range starting at (*ranges)[2*n] and of width (*ranges)[2*n + 1] - (*ranges)[2*n]. This array must be freed with g_free(). The coordinates are relative to the layout and are in PangoGlyphUnit.
n_ranges : | The number of ranges stored in ranges.


Miscellaneous Utilities

Miscellaneous Utilities — Various convenience and utility functions

Synopsis

char**      pango_split_file_list           (const char *str);
char*       pango_trim_string               (const char *str);
gint        pango_read_line                 (FILE *stream,
                                             GString *str);
gboolean    pango_skip_space                (const char **pos);
gboolean    pango_scan_word                 (const char **pos,
                                             GString *out);
gboolean    pango_scan_string               (const char **pos,
                                             GString *out);
gboolean    pango_scan_int                  (const char **pos,
                                             int *out);
char*       pango_config_key_get            (const char *key);
void        pango_lookup_aliases            (const char *fontname,
                                             char ***families,
                                             int *n_families);
gboolean    pango_parse_enum                (GType type,
                                             const char *str,
                                             int *value,
                                             gboolean warn,
                                             char **possible_values);
gboolean    pango_parse_style               (const char *str,
                                             PangoStyle *style,
                                             gboolean warn);
gboolean    pango_parse_variant             (const char *str,
                                             PangoVariant *variant,
                                             gboolean warn);
gboolean    pango_parse_weight              (const char *str,
                                             PangoWeight *weight,
                                             gboolean warn);
gboolean    pango_parse_stretch             (const char *str,
                                             PangoStretch *stretch,
                                             gboolean warn);
const char* pango_get_sysconf_subdirectory  (void);
const char* pango_get_lib_subdirectory      (void);
guint8*     pango_log2vis_get_embedding_levels
                                            (const gchar *text,
                                             int length,
                                             PangoDirection *pbase_dir);
PangoLanguage* pango_language_get_default   (void);
const char* pango_language_get_sample_string
                                            (PangoLanguage *language);
gboolean    pango_is_zero_width             (gunichar ch);
void        pango_quantize_line_geometry    (int *thickness,
                                             int *position);

Description

The functions and utilities in this section are mostly used from Pango backends and modules, but may be useful for other purposes too.

Details

pango_split_file_list ()

char**      pango_split_file_list           (const char *str);

Splits a G_SEARCHPATH_SEPARATOR-separated list of files, stripping white space and substituting ~/ with $HOME/.

str : | a G_SEARCHPATH_SEPARATOR separated list of filenames
Returns : | a list of strings to be freed with g_strfreev()

pango_trim_string ()

char*       pango_trim_string               (const char *str);

Trims leading and trailing whitespace from a string.

str : | a string
Returns : | A newly-allocated string that must be freed with g_free()

pango_read_line ()

gint        pango_read_line                 (FILE *stream,
                                             GString *str);

Reads an entire line from a file into a buffer. Lines may be delimited with '\n', '\r', '\n\r', or '\r\n'. The delimiter is not written into the buffer. Text after a '#' character is treated as a comment and skipped. '\' can be used to escape a # character. '\' proceeding a line delimiter combines adjacent lines. A '\' proceeding any other character is ignored and written into the output buffer unmodified.

stream : | a stdio stream
str : | GString buffer into which to write the result
Returns : | 0 if the stream was already at an EOF character, otherwise the number of lines read (this is useful for maintaining a line number counter which doesn't combine lines with '\')

pango_skip_space ()

gboolean    pango_skip_space                (const char **pos);

Skips 0 or more characters of white space.

pos : | in/out string position
Returns : | FALSE if skipping the white space leaves the position at a '\0' character.

pango_scan_word ()

gboolean    pango_scan_word                 (const char **pos,
                                             GString *out);

Scans a word into a GString buffer. A word consists of [A-Za-z_] followed by zero or more [A-Za-z_0-9] Leading white space is skipped.

pos : | in/out string position
out : | a GString into which to write the result
Returns : | FALSE if a parse error occurred.

pango_scan_string ()

gboolean    pango_scan_string               (const char **pos,
                                             GString *out);

Scans a string into a GString buffer. The string may either be a sequence of non-white-space characters, or a quoted string with '"'. Instead a quoted string, '\"' represents a literal quote. Leading white space outside of quotes is skipped.

pos : | in/out string position
out : | a GString into which to write the result
Returns : | FALSE if a parse error occurred.

pango_scan_int ()

gboolean    pango_scan_int                  (const char **pos,
                                             int *out);

Scans an integer. Leading white space is skipped.

pos : | in/out string position
out : | an int into which to write the result
Returns : | FALSE if a parse error occurred.

pango_config_key_get ()

char*       pango_config_key_get            (const char *key);

Looks up a key in the Pango config database (pseudo-win.ini style, read from $sysconfdir/pango/pangorc, ~/.pangorc, and getenv (PANGO_RC_FILE).)

key : | Key to look up, in the form "SECTION/KEY".
Returns : | the value, if found, otherwise NULL. The value is a newly-allocated string and must be freed with g_free().

pango_lookup_aliases ()

void        pango_lookup_aliases            (const char *fontname,
                                             char ***families,
                                             int *n_families);

Look up all user defined aliases for the alias fontname. The resulting font family names will be stored in families, and the number of families in n_families.

fontname : | an ascii string
families : | will be set to an array of font family names. this array is owned by pango and should not be freed.
n_families : | will be set to the length of the families array.

pango_parse_enum ()

gboolean    pango_parse_enum                (GType type,
                                             const char *str,
                                             int *value,
                                             gboolean warn,
                                             char **possible_values);

Parses an enum type and stored the result in value.

If str does not match the nick name of any of the possible values for the enum, FALSE is returned, a warning is issued if warn is TRUE, and a string representing the list of possible values is stored in possible_values. The list is slash-separated, eg. "none/start/middle/end". If failed and possible_values is not NULL, returned string should be freed using g_free().

type : | enum type to parse, eg. PANGO_TYPE_ELLIPSIZE_MODE.
str : | string to parse. May be NULL.
value : | integer to store the result in, or NULL.
warn : | if TRUE, issue a g_warning() on bad input.
possible_values : | place to store list of possible values on failure, or NULL.
Returns : | TRUE if str was successfully parsed.

Since 1.16

pango_parse_style ()

gboolean    pango_parse_style               (const char *str,
                                             PangoStyle *style,
                                             gboolean warn);

Parses a font style. The allowed values are "normal", "italic" and "oblique", case variations being ignored.

str : | a string to parse.
style : | a PangoStyle to store the result in.
warn : | if TRUE, issue a g_warning() on bad input.
Returns : | TRUE if str was successfully parsed.

pango_parse_variant ()

gboolean    pango_parse_variant             (const char *str,
                                             PangoVariant *variant,
                                             gboolean warn);

Parses a font variant. The allowed values are "normal" and "smallcaps" or "small_caps", case variations being ignored.

str : | a string to parse.
variant : | a PangoVariant to store the result in.
warn : | if TRUE, issue a g_warning() on bad input.
Returns : | TRUE if str was successfully parsed.

pango_parse_weight ()

gboolean    pango_parse_weight              (const char *str,
                                             PangoWeight *weight,
                                             gboolean warn);

Parses a font weight. The allowed values are "heavy", "ultrabold", "bold", "normal", "light", "ultraleight" and integers. Case variations are ignored.

str : | a string to parse.
weight : | a PangoWeight to store the result in.
warn : | if TRUE, issue a g_warning() on bad input.
Returns : | TRUE if str was successfully parsed.

pango_parse_stretch ()

gboolean    pango_parse_stretch             (const char *str,
                                             PangoStretch *stretch,
                                             gboolean warn);

Parses a font stretch. The allowed values are "ultra_condensed", "extra_condensed", "condensed", "semi_condensed", "normal", "semi_expanded", "expanded", "extra_expanded" and "ultra_expanded". Case variations are ignored and the '_' characters may be omitted.

str : | a string to parse.
stretch : | a PangoStretch to store the result in.
warn : | if TRUE, issue a g_warning() on bad input.
Returns : | TRUE if str was successfully parsed.

pango_get_sysconf_subdirectory ()

const char* pango_get_sysconf_subdirectory  (void);

On Unix, returns the name of the "pango" subdirectory of SYSCONFDIR (which is set at compile time). On Win32, returns a subdirectory of the Pango installation directory (which is deduced at run time from the DLL's location, or stored in the Registry).

Returns : the Pango sysconf directory. The returned string should not be freed.

pango_get_lib_subdirectory ()

const char* pango_get_lib_subdirectory      (void);

On Unix, returns the name of the "pango" subdirectory of LIBDIR (which is set at compile time). On Win32, returns the Pango installation directory (which is deduced at run time from the DLL's location, or stored in the Registry). The returned string should not be freed.

Returns : the Pango lib directory. The returned string should not be freed.

pango_log2vis_get_embedding_levels ()

guint8*     pango_log2vis_get_embedding_levels
                                            (const gchar *text,
                                             int length,
                                             PangoDirection *pbase_dir);

This will return the bidirectional embedding levels of the input paragraph as defined by the Unicode Bidirectional Algorithm available at:

http://www.unicode.org/reports/tr9/

If the input base direction is a weak direction, the direction of the characters in the text will determine the final resolved direction.

text : | the text to itemize.
length : | the number of bytes (not characters) to process, or -1 if text is nul-terminated and the length should be calculated.
pbase_dir : | input base direction, and output resolved direction.
Returns : | a newly allocated array of embedding levels, one item per character (not byte), that should be freed using g_free.

Since 1.4

pango_language_get_default ()

PangoLanguage* pango_language_get_default   (void);

Returns the PangoLanguage for the current locale of the process. Note that this can change over the life of an application.

On Unix systems, this is the return value is derived from setlocale(LC_CTYPE, NULL), and the user can affect this through the environment variables LC_ALL, LC_CTYPE or LANG (checked in that order). The locale string typically is in the form lang_COUNTRY, where lang is an ISO-639 language code, and COUNTRY is an ISO-3166 country code. For instance, sv_FI for Swedish as written in Finland or pt_BR for Portuguese as written in Brazil.

On Windows, the C library does not use any such environment variables, and setting them won't affect the behavior of functions like ctime(). The user sets the locale through the Regional Options in the Control Panel. The C library (in the setlocale() function) does not use country and language codes, but country and language names spelled out in English. However, this function does check the above environment variables, and does return a Unix-style locale string based on either said environment variables or the thread's current locale.

Your application should call setlocale(LC_ALL, ""); for the user settings to take effect. Gtk+ does this in its initialization functions automatically (by calling gtk_set_locale()). See man setlocale for more details.

Returns : the default language as a PangoLanguage, must not be freed.

Since 1.16

pango_language_get_sample_string ()

const char* pango_language_get_sample_string
                                            (PangoLanguage *language);

Get a string that is representative of the characters needed to render a particular language. This function is a bad hack for internal use by renderers and Pango.

language : | a PangoLanguage
Returns : | the sample string. This value is owned by Pango and must not be freed.

pango_is_zero_width ()

gboolean    pango_is_zero_width             (gunichar ch);

Checks ch to see if it is a character that should not be normally rendered on the screen. This includes all Unicode characters with "ZERO WIDTH" in their name, as well as bidi formatting characters, and a few other ones. This is totally different from g_unichar_iszerowidth() and is at best misnamed.

ch : | a Unicode character
Returns : | TRUE if ch is a zero-width character, FALSE otherwise

Since 1.10

pango_quantize_line_geometry ()

void        pango_quantize_line_geometry    (int *thickness,
                                             int *position);

Quantizes the thickness and position of a line, typically an underline or strikethrough, to whole device pixels, that is integer multiples of PANGO_SCALE. The purpose of this function is to avoid such lines looking blurry.

thickness : | pointer to the thickness of a line, in Pango scaled units
position : | corresponding position

Since 1.12


Modules

Modules — Support for loadable modules

Synopsis

            PangoIncludedModule;
            PangoMap;
            PangoMapEntry;
PangoMap*   pango_find_map                  (PangoLanguage *language,
                                             guint engine_type_id,
                                             guint render_type_id);
PangoEngine* pango_map_get_engine           (PangoMap *map,
                                             PangoScript script);
void        pango_map_get_engines           (PangoMap *map,
                                             PangoScript script,
                                             GSList **exact_engines,
                                             GSList **fallback_engines);
void        pango_module_register           (PangoIncludedModule *module);

Description

Functions and macros in this section are used to support loading dynamic modules that add engines to Pango at run time.

Details

PangoIncludedModule

typedef struct {
  void (*list) (PangoEngineInfo **engines,
        int              *n_engines);
  void (*init) (GTypeModule      *module);
  void (*exit) (void);
  PangoEngine *(*create) (const char       *id);
} PangoIncludedModule;

The PangoIncludedModule structure for a statically linked module contains the functions that would otherwise be loaded from a dynamically loaded module.

list () | a function that lists the engines defined in this module.
init () | a function to initialize the module.
exit () | a function to finalize the module.
create () | a function to create an engine, given the engine name.

PangoMap

typedef struct _PangoMap PangoMap;

A PangoMap structure can be used to determine the engine to use for each character.

PangoMapEntry

typedef struct _PangoMapEntry PangoMapEntry;

A PangoMapEntry contains information about the engine that should be used for the codepoint to which this entry belongs and also whether the engine matches the language tag for this entry's map exactly or just approximately.

pango_find_map ()

PangoMap*   pango_find_map                  (PangoLanguage *language,
                                             guint engine_type_id,
                                             guint render_type_id);

Locate a PangoMap for a particular engine type and render type. The resulting map can be used to determine the engine for each character.

language : | the language tag for which to find the map
engine_type_id : | the engine type for the map to find
render_type_id : | the render type for the map to find
Returns : | the suitable PangoMap.

pango_map_get_engine ()

PangoEngine* pango_map_get_engine           (PangoMap *map,
                                             PangoScript script);

Returns the best engine listed in the map for a given script

map : | a PangoMap
script : | a PangoScript
Returns : | the best engine, if one is listed for the script, or NULL. The lookup may cause the engine to be loaded; once an engine is loaded, it won't be unloaded. If multiple engines are exact for the script, the choice of which is returned is arbitrary.

pango_map_get_engines ()

void        pango_map_get_engines           (PangoMap *map,
                                             PangoScript script,
                                             GSList **exact_engines,
                                             GSList **fallback_engines);

Finds engines in the map that handle the given script. The returned lists should be freed with g_slist_free, but the engines in the lists are owned by GLib and will be kept around permanently, so they should not be unref'ed.

map : | a PangoMap
script : | a PangoScript
exact_engines : | location to store list of engines that exactly handle this script.
fallback_engines : | location to store list of engines that approximately handle this script.

Since 1.4

pango_module_register ()

void        pango_module_register           (PangoIncludedModule *module);

Registers a statically linked module with Pango. The PangoIncludedModule structure that is passed in contains the functions that would otherwise be loaded from a dynamically loaded module.

module : a PangoIncludedModule


OpenType Font Handling

OpenType Font Handling — Obtaining information from OpenType tables

Synopsis

typedef     PangoOTTag;
            PangoOTInfo;
            PangoOTBuffer;
            PangoOTGlyph;
            PangoOTRuleset;
enum        PangoOTTableType;
#define     PANGO_OT_ALL_GLYPHS
#define     PANGO_OT_DEFAULT_LANGUAGE
PangoOTInfo* pango_ot_info_get              (FT_Face face);
gboolean    pango_ot_info_find_script       (PangoOTInfo *info,
                                             PangoOTTableType table_type,
                                             PangoOTTag script_tag,
                                             guint *script_index);
gboolean    pango_ot_info_find_language     (PangoOTInfo *info,
                                             PangoOTTableType table_type,
                                             guint script_index,
                                             PangoOTTag language_tag,
                                             guint *language_index,
                                             guint *required_feature_index);
gboolean    pango_ot_info_find_feature      (PangoOTInfo *info,
                                             PangoOTTableType table_type,
                                             PangoOTTag feature_tag,
                                             guint script_index,
                                             guint language_index,
                                             guint *feature_index);
PangoOTTag* pango_ot_info_list_scripts      (PangoOTInfo *info,
                                             PangoOTTableType table_type);
PangoOTTag* pango_ot_info_list_languages    (PangoOTInfo *info,
                                             PangoOTTableType table_type,
                                             guint script_index,
                                             PangoOTTag language_tag);
PangoOTTag* pango_ot_info_list_features     (PangoOTInfo *info,
                                             PangoOTTableType table_type,
                                             PangoOTTag tag,
                                             guint script_index,
                                             guint language_index);
PangoOTBuffer* pango_ot_buffer_new          (PangoFcFont *font);
void        pango_ot_buffer_destroy         (PangoOTBuffer *buffer);
void        pango_ot_buffer_clear           (PangoOTBuffer *buffer);
void        pango_ot_buffer_add_glyph       (PangoOTBuffer *buffer,
                                             guint glyph,
                                             guint properties,
                                             guint cluster);
void        pango_ot_buffer_set_rtl         (PangoOTBuffer *buffer,
                                             gboolean rtl);
void        pango_ot_buffer_set_zero_width_marks
                                            (PangoOTBuffer *buffer,
                                             gboolean zero_width_marks);
void        pango_ot_buffer_get_glyphs      (PangoOTBuffer *buffer,
                                             PangoOTGlyph **glyphs,
                                             int *n_glyphs);
void        pango_ot_buffer_output          (PangoOTBuffer *buffer,
                                             PangoGlyphString *glyphs);
PangoOTRuleset* pango_ot_ruleset_new        (PangoOTInfo *info);
void        pango_ot_ruleset_add_feature    (PangoOTRuleset *ruleset,
                                             PangoOTTableType table_type,
                                             guint feature_index,
                                             gulong property_bit);
void        pango_ot_ruleset_substitute     (PangoOTRuleset *ruleset,
                                             PangoOTBuffer *buffer);
void        pango_ot_ruleset_position       (PangoOTRuleset *ruleset,
                                             PangoOTBuffer *buffer);

Description

Functions and macros in this section are used to implement the OpenType Layout features and algorithms. These are mostly useful when writing Fontconfig-based shaping engines

Details

PangoOTTag

typedef guint32  PangoOTTag;

The PangoOTTag typedef is used to represent TrueType and OpenType four letter tags inside Pango. Use the FT_MAKE_TAG() macro defined in the FreeType2 header freetype/freetype.h to create PangoOTTags manually.

PangoOTInfo

typedef struct _PangoOTInfo PangoOTInfo;

The PangoOTInfo struct contains the various tables associated with an OpenType font. It contains only private fields and should only be accessed via the pango_ot_info_* functions which are documented below. To obtain a PangoOTInfo, use pango_ot_info_new().

PangoOTBuffer

typedef struct _PangoOTBuffer PangoOTBuffer;

The PangoOTBuffer structure is used to store strings of glyphs associated with a PangoFcFont, suitable for OpenType layout processing. It contains only private fields and should only be accessed via the pango_ot_buffer_* functions which are documented below. To obtain a PangoOTBuffer, use pango_ot_buffer_new().

PangoOTGlyph

typedef struct {
  guint    glyph;
  guint    properties;
  guint    cluster;
  gushort  component;
  gushort  ligID;
  gushort  property_cache;    /* Internal */
} PangoOTGlyph;

The PangoOTGlyph structure represents a single glyph together with information used for OpenType layout processing of the glyph. It contains the following fields.

guint glyph; | the glyph itself.
guint properties; | the properties value, identifying which features should be applied on this glyph. See pango_ruleset_add_feature().
guint cluster; | the cluster that this glyph belongs to.
gushort component; | a component value, set by the OpenType layout engine.
gushort ligID; | a ligature index value, set by the OpenType layout engine.
gushort property_cache; | for internal use.

PangoOTRuleset

typedef struct _PangoOTRuleset PangoOTRuleset;

The PangoOTRuleSet structure holds a set of features selected from the tables in an OpenType font. (A feature is an operation such as adjusting glyph positioning that should be applied to a text feature such as a certain type of accent.) A PangoOTRuleSet is created with pango_ot_ruleset_new(), features are added to it with pango_ot_ruleset_add_feature(), then it is applied to a PangoGlyphString with pango_ot_ruleset_shape().

enum PangoOTTableType

typedef enum
{
  PANGO_OT_TABLE_GSUB,
  PANGO_OT_TABLE_GPOS
} PangoOTTableType;

The PangoOTTableType enumeration values are used to identify the various OpenType tables in the pango_ot_info_* functions.

PANGO_OT_TABLE_GSUB | The GSUB table.
PANGO_OT_TABLE_GPOS | The GPOS table.

PANGO_OT_ALL_GLYPHS

#define PANGO_OT_ALL_GLYPHS		((guint)0xFFFF)

This is used as the property bit in pango_ot_ruleset_add_feature() when a feature should be applied to all glyphs.

PANGO_OT_DEFAULT_LANGUAGE

#define PANGO_OT_DEFAULT_LANGUAGE	((guint)0xFFFF)

This is used as the language index in pango_ot_info_find_feature() when a the default language system of the script is desired.

pango_ot_info_get ()

PangoOTInfo* pango_ot_info_get              (FT_Face face);

Returns the PangoOTInfo structure for the given FreeType font.

face : | a FT_Face.
Returns : | the PangoOTInfo for face. This object will have the same lifetime as face.

Since 1.2

pango_ot_info_find_script ()

gboolean    pango_ot_info_find_script       (PangoOTInfo *info,
                                             PangoOTTableType table_type,
                                             PangoOTTag script_tag,
                                             guint *script_index);

Finds the index of a script.

info : | a PangoOTInfo.
table_type : | the table type to obtain information about.
script_tag : | the tag of the script to find.
script_index : | location to store the index of the script, or NULL.
Returns : | TRUE if the script was found.

pango_ot_info_find_language ()

gboolean    pango_ot_info_find_language     (PangoOTInfo *info,
                                             PangoOTTableType table_type,
                                             guint script_index,
                                             PangoOTTag language_tag,
                                             guint *language_index,
                                             guint *required_feature_index);

Finds the index of a language and its required feature index.

info : | a PangoOTInfo.
table_type : | the table type to obtain information about.
script_index : | the index of the script whose languages are searched.
language_tag : | the tag of the language to find.
language_index : | location to store the index of the language, or NULL.
required_feature_index : | location to store the required feature index of the language, or NULL.
Returns : | TRUE if the language was found.

pango_ot_info_find_feature ()

gboolean    pango_ot_info_find_feature      (PangoOTInfo *info,
                                             PangoOTTableType table_type,
                                             PangoOTTag feature_tag,
                                             guint script_index,
                                             guint language_index,
                                             guint *feature_index);

Finds the index of a feature.

info : | a PangoOTInfo.
table_type : | the table type to obtain information about.
feature_tag : | the tag of the feature to find.
script_index : | the index of the script.
language_index : | the index of the language whose features are searched, or PANGO_OT_DEFAULT_LANGUAGE to use the default language of the script.
feature_index : | location to store the index of the feature, or NULL.
Returns : | TRUE if the feature was found.

pango_ot_info_list_scripts ()

PangoOTTag* pango_ot_info_list_scripts      (PangoOTInfo *info,
                                             PangoOTTableType table_type);

Obtains the list of available scripts.

info : | a PangoOTInfo.
table_type : | the table type to obtain information about.
Returns : | a newly-allocated array containing the tags of the available scripts.

pango_ot_info_list_languages ()

PangoOTTag* pango_ot_info_list_languages    (PangoOTInfo *info,
                                             PangoOTTableType table_type,
                                             guint script_index,
                                             PangoOTTag language_tag);

Obtains the list of available languages for a given script.

info : | a PangoOTInfo.
table_type : | the table type to obtain information about.
script_index : | the index of the script to list languages for.
language_tag : | unused parameter.
Returns : | a newly-allocated array containing the tags of the available languages.

pango_ot_info_list_features ()

PangoOTTag* pango_ot_info_list_features     (PangoOTInfo *info,
                                             PangoOTTableType table_type,
                                             PangoOTTag tag,
                                             guint script_index,
                                             guint language_index);

Obtains the list of features for the given language of the given script.

info : | a PangoOTInfo.
table_type : | the table type to obtain information about.
tag : | unused parameter.
script_index : | the index of the script to obtain information about.
language_index : | the index of the language to list features for, or PANGO_OT_DEFAULT_LANGUAGE, to list features for the default language of the script.
Returns : | a newly-allocated array containing the tags of the available features.

pango_ot_buffer_new ()

PangoOTBuffer* pango_ot_buffer_new          (PangoFcFont *font);

Creates a new PangoOTBuffer for the given OpenType font.

font : | a PangoFcFont
Returns : | the newly allocated PangoOTBuffer, which should be freed with pango_ot_buffer_destroy().

Since 1.4

pango_ot_buffer_destroy ()

void        pango_ot_buffer_destroy         (PangoOTBuffer *buffer);

Destroys a PangoOTBuffer and free all associated memory.

buffer : a PangoOTBuffer

Since 1.4

pango_ot_buffer_clear ()

void        pango_ot_buffer_clear           (PangoOTBuffer *buffer);

Empties a PangoOTBuffer, make it ready to add glyphs to.

buffer : a PangoOTBuffer

Since 1.4

pango_ot_buffer_add_glyph ()

void        pango_ot_buffer_add_glyph       (PangoOTBuffer *buffer,
                                             guint glyph,
                                             guint properties,
                                             guint cluster);

Appends a glyph to a PangoOTBuffer, with properties identifying which features should be applied on this glyph. See pango_ruleset_add_feature().

buffer : | a PangoOTBuffer
glyph : | the glyph index to add, like a PangoGlyph
properties : | the glyph properties
cluster : | the cluster that this glyph belongs to

Since 1.4

pango_ot_buffer_set_rtl ()

void        pango_ot_buffer_set_rtl         (PangoOTBuffer *buffer,
                                             gboolean rtl);

Sets whether glyphs will be rendered right-to-left. This setting is needed for proper horizontal positioning of right-to-left scripts.

buffer : | a PangoOTBuffer
rtl : | TRUE for right-to-left text

Since 1.4

pango_ot_buffer_set_zero_width_marks ()

void        pango_ot_buffer_set_zero_width_marks
                                            (PangoOTBuffer *buffer,
                                             gboolean zero_width_marks);

Sets whether characters with a mark class should be forced to zero width. This setting is needed for proper positioning of Arabic accents, but will produce incorrect results with standard OpenType Indic fonts.

buffer : | a PangoOTBuffer
zero_width_marks : | TRUE if characters with a mark class should be forced to zero width.

Since 1.6

pango_ot_buffer_get_glyphs ()

void        pango_ot_buffer_get_glyphs      (PangoOTBuffer *buffer,
                                             PangoOTGlyph **glyphs,
                                             int *n_glyphs);

Gets the glyph array contained in a PangoOTBuffer. The glyphs are owned by the buffer and should not be freed, and are only valid as long as buffer is not modified.

buffer : | a PangoOTBuffer
glyphs : | location to store the array of glyphs, or NULL
n_glyphs : | location to store the number of glyphs, or NULL

Since 1.4

pango_ot_buffer_output ()

void        pango_ot_buffer_output          (PangoOTBuffer *buffer,
                                             PangoGlyphString *glyphs);

Exports the glyphs in a PangoOTBuffer into a PangoGlyphString. This is typically used after the OpenType layout processing is over, to convert the resulting glyphs into a generic Pango glyph string.

buffer : | a PangoOTBuffer
glyphs : | a PangoGlyphString

Since 1.4

pango_ot_ruleset_new ()

PangoOTRuleset* pango_ot_ruleset_new        (PangoOTInfo *info);

Creates a new PangoOTRuleset for the given OpenType info.

info : | a PangoOTInfo.
Returns : | the newly allocated PangoOTRuleset, which should be freed with g_object_unref().

pango_ot_ruleset_add_feature ()

void        pango_ot_ruleset_add_feature    (PangoOTRuleset *ruleset,
                                             PangoOTTableType table_type,
                                             guint feature_index,
                                             gulong property_bit);

Adds a feature to the ruleset.

ruleset : | a PangoOTRuleset.
table_type : | the table type to add a feature to.
feature_index : | the index of the feature to add.
property_bit : | the property bit to use for this feature. Used to identify the glyphs that this feature should be applied to, or PANGO_OT_ALL_GLYPHS if it should be applied to all glyphs.

pango_ot_ruleset_substitute ()

void        pango_ot_ruleset_substitute     (PangoOTRuleset *ruleset,
                                             PangoOTBuffer *buffer);

Performs the OpenType GSUB substitution on buffer using the features in ruleset

ruleset : | a PangoOTRuleset.
buffer : | a PangoOTBuffer.

Since 1.4

pango_ot_ruleset_position ()

void        pango_ot_ruleset_position       (PangoOTRuleset *ruleset,
                                             PangoOTBuffer *buffer);

Performs the OpenType GPOS positioning on buffer using the features in ruleset

ruleset : | a PangoOTRuleset.
buffer : | a PangoOTBuffer.

Since 1.4


PangoRenderer

PangoRenderer — Rendering driver base class

Synopsis

            PangoRenderer;
enum        PangoRenderPart;
#define     PANGO_TYPE_RENDER_PART
            PangoRendererClass;
void        pango_renderer_draw_layout      (PangoRenderer *renderer,
                                             PangoLayout *layout,
                                             int x,
                                             int y);
void        pango_renderer_draw_layout_line (PangoRenderer *renderer,
                                             PangoLayoutLine *line,
                                             int x,
                                             int y);
void        pango_renderer_draw_glyphs      (PangoRenderer *renderer,
                                             PangoFont *font,
                                             PangoGlyphString *glyphs,
                                             int x,
                                             int y);
void        pango_renderer_draw_rectangle   (PangoRenderer *renderer,
                                             PangoRenderPart part,
                                             int x,
                                             int y,
                                             int width,
                                             int height);
void        pango_renderer_draw_error_underline
                                            (PangoRenderer *renderer,
                                             int x,
                                             int y,
                                             int width,
                                             int height);
void        pango_renderer_draw_trapezoid   (PangoRenderer *renderer,
                                             PangoRenderPart part,
                                             double y1_,
                                             double x11,
                                             double x21,
                                             double y2,
                                             double x12,
                                             double x22);
void        pango_renderer_draw_glyph       (PangoRenderer *renderer,
                                             PangoFont *font,
                                             PangoGlyph glyph,
                                             double x,
                                             double y);
void        pango_renderer_activate         (PangoRenderer *renderer);
void        pango_renderer_deactivate       (PangoRenderer *renderer);
void        pango_renderer_part_changed     (PangoRenderer *renderer,
                                             PangoRenderPart part);
void        pango_renderer_set_color        (PangoRenderer *renderer,
                                             PangoRenderPart part,
                                             const PangoColor *color);
PangoColor* pango_renderer_get_color        (PangoRenderer *renderer,
                                             PangoRenderPart part);
void        pango_renderer_set_matrix       (PangoRenderer *renderer,
                                             const PangoMatrix *matrix);
const PangoMatrix* pango_renderer_get_matrix
                                            (PangoRenderer *renderer);

Description

PangoRenderer is a base class that contains the necessary logic for rendering a PangoLayout or PangoLayoutLine. By subclassing PangoRenderer and overriding operations such as draw_glyphs and draw_rectangle, renderers for particular font backends and destinations can be created.

Details

PangoRenderer

typedef struct {
  PangoMatrix *matrix;		/* May be NULL */
} PangoRenderer;

PangoRenderer is a base class for objects that are used to render Pango objects such as PangoGlyphString and PangoLayout.

PangoMatrix *matrix; the current transformation matrix for the Renderer; may be NULL, which should be treated the same as the identity matrix.

Since 1.8

enum PangoRenderPart

typedef enum
{
  PANGO_RENDER_PART_FOREGROUND,
  PANGO_RENDER_PART_BACKGROUND,
  PANGO_RENDER_PART_UNDERLINE,
  PANGO_RENDER_PART_STRIKETHROUGH
} PangoRenderPart;

PangoRenderPart defines different items to render for such purposes as setting colors.

PANGO_RENDER_PART_FOREGROUND | the text itself
PANGO_RENDER_PART_BACKGROUND | the area behind the text
PANGO_RENDER_PART_UNDERLINE | underlines
PANGO_RENDER_PART_STRIKETHROUGH | strikethrough lines

Since 1.8

PANGO_TYPE_RENDER_PART

#define PANGO_TYPE_RENDER_PART (pango_render_part_get_type())

The GObject type for PangoRenderPart.

PangoRendererClass

typedef struct {
  /* All of the following have default implementations
   * and take as coordinates user coordinates in Pango units
   */
  void (*draw_glyphs) (PangoRenderer     *renderer,
               PangoFont         *font,
               PangoGlyphString  *glyphs,
               int                x,
               int                y);
  void (*draw_rectangle) (PangoRenderer     *renderer,
              PangoRenderPart    part,
              int                x,
              int                y,
              int                width,
              int                height);
  void (*draw_error_underline) (PangoRenderer     *renderer,
                int                x,
                int                y,
                int                width,
                int                height);

  /* Nothing is drawn for shaped glyphs unless this is implemented */
  void (*draw_shape) (PangoRenderer  *renderer,
              PangoAttrShape *attr,
              int             x,
              int             y);

  /* These two must be implemented and take coordinates in
   * device space as doubles.
   */
  void (*draw_trapezoid) (PangoRenderer  *renderer,
              PangoRenderPart part,
              double          y1_,
              double          x11,
              double          x21,
              double          y2,
              double          x12,
              double          x22);
  void (*draw_glyph) (PangoRenderer *renderer,
              PangoFont     *font,
              PangoGlyph     glyph,
              double         x,
              double         y);

  /* Notification of change in rendering attributes
   */
  void (*part_changed) (PangoRenderer   *renderer,
            PangoRenderPart  part);

  /* Paired around drawing operations
   */
  void (*begin) (PangoRenderer *renderer);
  void (*end)   (PangoRenderer *renderer);

  /* Hooks into the details of layout rendering
   */
  void (*prepare_run) (PangoRenderer  *renderer,
               PangoLayoutRun *run);
} PangoRendererClass;

Class structure for PangoRenderer.

draw_glyphs () | draws a PangoGlyphString
draw_rectangle () | draws a rectangle
draw_error_underline () | draws a squiggly line that approximately covers the given rectangle in the style of an underline used to indicate a spelling error.
draw_shape () | draw content for a glyph shaped with PangoAttrShape. x, y are the coordinates of the left edge of the baseline, in user coordinates.
draw_trapezoid () | draws a trapezoidal filled area
draw_glyph () | draws a single glyph
part_changed () | do renderer specific processing when rendering attributes change
begin () | Do renderer-specific initialization before drawing
end () | Do renderer-specific cleanup after drawing
prepare_run () | updates the renderer for a new run

Since 1.8

pango_renderer_draw_layout ()

void        pango_renderer_draw_layout      (PangoRenderer *renderer,
                                             PangoLayout *layout,
                                             int x,
                                             int y);

Draws layout with the specified PangoRenderer.

renderer : | a PangoRenderer
layout : | a PangoLayout
x : | X position of left edge of baseline, in user space coordinates in Pango units.
y : | Y position of left edge of baseline, in user space coordinates in Pango units.

Since 1.8

pango_renderer_draw_layout_line ()

void        pango_renderer_draw_layout_line (PangoRenderer *renderer,
                                             PangoLayoutLine *line,
                                             int x,
                                             int y);

Draws line with the specified PangoRenderer.

renderer : | a PangoRenderer
line : | a PangoLayoutLine
x : | X position of left edge of baseline, in user space coordinates in Pango units.
y : | Y position of left edge of baseline, in user space coordinates in Pango units.

Since 1.8

pango_renderer_draw_glyphs ()

void        pango_renderer_draw_glyphs      (PangoRenderer *renderer,
                                             PangoFont *font,
                                             PangoGlyphString *glyphs,
                                             int x,
                                             int y);

Draws the glyphs in glyphs with the specified PangoRenderer.

renderer : | a PangoRenderer
font : | a PangoFont
glyphs : | a PangoGlyphString
x : | X position of left edge of baseline, in user space coordinates in Pango units.
y : | Y position of left edge of baseline, in user space coordinates in Pango units.

Since 1.8

pango_renderer_draw_rectangle ()

void        pango_renderer_draw_rectangle   (PangoRenderer *renderer,
                                             PangoRenderPart part,
                                             int x,
                                             int y,
                                             int width,
                                             int height);

Draws an axis-aligned rectangle in user space coordinates with the specified PangoRenderer.

This should be called while renderer is already active. Use pango_renderer_activate() to activate a renderer.

renderer : | a PangoRenderer
part : | type of object this rectangle is part of
x : | X position at which to draw rectangle, in user space coordinates in Pango units
y : | Y position at which to draw rectangle, in user space coordinates in Pango units
width : | width of rectangle in Pango units in user space coordinates
height : | height of rectangle in Pango units in user space coordinates

Since 1.8

pango_renderer_draw_error_underline ()

void        pango_renderer_draw_error_underline
                                            (PangoRenderer *renderer,
                                             int x,
                                             int y,
                                             int width,
                                             int height);

Draw a squiggly line that approximately covers the given rectangle in the style of an underline used to indicate a spelling error. (The width of the underline is rounded to an integer number of up/down segments and the resulting rectangle is centered in the original rectangle)

This should be called while renderer is already active. Use pango_renderer_activate() to activate a renderer.

renderer : | a PangoRenderer
x : | X coordinate of underline, in Pango units in user coordinate system
y : | Y coordinate of underline, in Pango units in user coordinate system
width : | width of underline, in Pango units in user coordinate system
height : | height of underline, in Pango units in user coordinate system

Since 1.8

pango_renderer_draw_trapezoid ()

void        pango_renderer_draw_trapezoid   (PangoRenderer *renderer,
                                             PangoRenderPart part,
                                             double y1_,
                                             double x11,
                                             double x21,
                                             double y2,
                                             double x12,
                                             double x22);

Draws a trapezoid with the parallel sides aligned with the X axis using the given PangoRenderer; coordinates are in device space.

renderer : | a PangoRenderer
part : | type of object this trapezoid is part of
y1_ : | Y coordinate of top of trapezoid
x11 : | X coordinate of left end of top of trapezoid
x21 : | X coordinate of right end of top of trapezoid
y2 : | Y coordinate of bottom of trapezoid
x12 : | X coordinate of left end of bottom of trapezoid
x22 : | X coordinate of right end of bottom of trapezoid

Since 1.8

pango_renderer_draw_glyph ()

void        pango_renderer_draw_glyph       (PangoRenderer *renderer,
                                             PangoFont *font,
                                             PangoGlyph glyph,
                                             double x,
                                             double y);

Draws a single glyph with coordinates in device space.

renderer : | a PangoRenderer
font : | a PangoFont
glyph : | the glyph index of a single glyph
x : | X coordinate of left edge of baseline of glyph
y : | Y coordinate of left edge of baseline of glyph

Since 1.8

pango_renderer_activate ()

void        pango_renderer_activate         (PangoRenderer *renderer);

Does initial setup before rendering operations on renderer. pango_renderer_deactivate() should be called when done drawing. Calls such as pango_renderer_draw_layout() automatically activate the layout before drawing on it. Calls to pango_renderer_activate() and pango_renderer_deactivate() can be nested and the renderer will only be initialized and deinitialized once.

renderer : a PangoRenderer

Since 1.8

pango_renderer_deactivate ()

void        pango_renderer_deactivate       (PangoRenderer *renderer);

Cleans up after rendering operations on renderer. See docs for pango_renderer_activate().

renderer : a PangoRenderer

Since 1.8

pango_renderer_part_changed ()

void        pango_renderer_part_changed     (PangoRenderer *renderer,
                                             PangoRenderPart part);

Informs Pango that the way that the rendering is done for part has changed in a way that would prevent multiple pieces being joined together into one drawing call. For instance, if a subclass of PangoRenderer was to add a stipple option for drawing underlines, it needs to call

pango_renderer_part_changed (render, PANGO_RENDER_PART_UNDERLINE);

When the stipple changes or underlines with different stipples might be joined together. Pango automatically calls this for changes to colors. (See pango_renderer_set_color())

renderer : | a PangoRenderer
part : | the part for which rendering has changed.

Since 1.8

pango_renderer_set_color ()

void        pango_renderer_set_color        (PangoRenderer *renderer,
                                             PangoRenderPart part,
                                             const PangoColor *color);

Sets the color for part of the rendering.

renderer : | a PangoRenderer
part : | the part to change the color of
color : | the new color or NULL to unset the current color

Since 1.8

pango_renderer_get_color ()

PangoColor* pango_renderer_get_color        (PangoRenderer *renderer,
                                             PangoRenderPart part);

Gets the current rendering color for the specified part.

renderer : | a PangoRenderer
part : | the part to get the color for
Returns : | the color for the specified part, or NULL if it hasn't been set and should be inherited from the environment.

Since 1.8

pango_renderer_set_matrix ()

void        pango_renderer_set_matrix       (PangoRenderer *renderer,
                                             const PangoMatrix *matrix);

Sets the transformation matrix that will be applied when rendering.

renderer : | a PangoRenderer
matrix : | a PangoMatrix, or NULL to unset any existing matrix. (No matrix set is the same as setting the identity matrix.)

Since 1.8

pango_renderer_get_matrix ()

const PangoMatrix* pango_renderer_get_matrix
                                            (PangoRenderer *renderer);

Gets the transformation matrix that will be applied when rendering. See pango_renderer_set_matrix().

renderer : | a PangoRenderer
Returns : | the matrix, or NULL if no matrix has been set (which is the same as the identity matrix). The returned matrix is owned by Pango and must not be modified or freed.

Since 1.8


pango-querymodules

pango-querymodules — Module registration utility

Synopsis

pango-querymodules [module...]

Description

pango-querymodules collects information about loadable modules for Pango and writes it to stdout.

If called without arguments, it looks for modules in the Pango module path.

If called with arguments, it looks for the specified modules. The arguments may be absolute or relative paths.

Environment

The Pango module path is specified by the key Pango/ModulesPath in the Pango config database, which is read from sysconfdir/pango/pangorc, ~/.pangorc and the file specified in the environment variable PANGO_RC_FILE.

Bugs

None known yet.


Scripts

Scripts — Identifying writing systems

Synopsis

            PangoScriptIter;
enum        PangoScript;
#define     PANGO_TYPE_SCRIPT
PangoScript pango_script_for_unichar        (gunichar ch);
PangoLanguage* pango_script_get_sample_language
                                            (PangoScript script);
gboolean    pango_language_includes_script  (PangoLanguage *language,
                                             PangoScript script);
PangoScriptIter* pango_script_iter_new      (const char *text,
                                             int length);
void        pango_script_iter_get_range     (PangoScriptIter *iter,
                                             G_CONST_RETURN char **start,
                                             G_CONST_RETURN char **end,
                                             PangoScript *script);
gboolean    pango_script_iter_next          (PangoScriptIter *iter);
void        pango_script_iter_free          (PangoScriptIter *iter);

Description

The functions in this section are used to identify the writing system, or script of individual characters and of ranges within a larger text string.

Details

PangoScriptIter

typedef struct _PangoScriptIter PangoScriptIter;

A PangoScriptIter is used to iterate through a string and identify ranges in different scripts.

enum PangoScript

typedef enum {                         /* ISO 15924 code */
      PANGO_SCRIPT_INVALID_CODE = -1,
      PANGO_SCRIPT_COMMON       = 0,   /* Zyyy */
      PANGO_SCRIPT_INHERITED,          /* Qaai */
      PANGO_SCRIPT_ARABIC,             /* Arab */
      PANGO_SCRIPT_ARMENIAN,           /* Armn */
      PANGO_SCRIPT_BENGALI,            /* Beng */
      PANGO_SCRIPT_BOPOMOFO,           /* Bopo */
      PANGO_SCRIPT_CHEROKEE,           /* Cher */
      PANGO_SCRIPT_COPTIC,             /* Qaac */
      PANGO_SCRIPT_CYRILLIC,           /* Cyrl (Cyrs) */
      PANGO_SCRIPT_DESERET,            /* Dsrt */
      PANGO_SCRIPT_DEVANAGARI,         /* Deva */
      PANGO_SCRIPT_ETHIOPIC,           /* Ethi */
      PANGO_SCRIPT_GEORGIAN,           /* Geor (Geon, Geoa) */
      PANGO_SCRIPT_GOTHIC,             /* Goth */
      PANGO_SCRIPT_GREEK,              /* Grek */
      PANGO_SCRIPT_GUJARATI,           /* Gujr */
      PANGO_SCRIPT_GURMUKHI,           /* Guru */
      PANGO_SCRIPT_HAN,                /* Hani */
      PANGO_SCRIPT_HANGUL,             /* Hang */
      PANGO_SCRIPT_HEBREW,             /* Hebr */
      PANGO_SCRIPT_HIRAGANA,           /* Hira */
      PANGO_SCRIPT_KANNADA,            /* Knda */
      PANGO_SCRIPT_KATAKANA,           /* Kana */
      PANGO_SCRIPT_KHMER,              /* Khmr */
      PANGO_SCRIPT_LAO,                /* Laoo */
      PANGO_SCRIPT_LATIN,              /* Latn (Latf, Latg) */
      PANGO_SCRIPT_MALAYALAM,          /* Mlym */
      PANGO_SCRIPT_MONGOLIAN,          /* Mong */
      PANGO_SCRIPT_MYANMAR,            /* Mymr */
      PANGO_SCRIPT_OGHAM,              /* Ogam */
      PANGO_SCRIPT_OLD_ITALIC,         /* Ital */
      PANGO_SCRIPT_ORIYA,              /* Orya */
      PANGO_SCRIPT_RUNIC,              /* Runr */
      PANGO_SCRIPT_SINHALA,            /* Sinh */
      PANGO_SCRIPT_SYRIAC,             /* Syrc (Syrj, Syrn, Syre) */
      PANGO_SCRIPT_TAMIL,              /* Taml */
      PANGO_SCRIPT_TELUGU,             /* Telu */
      PANGO_SCRIPT_THAANA,             /* Thaa */
      PANGO_SCRIPT_THAI,               /* Thai */
      PANGO_SCRIPT_TIBETAN,            /* Tibt */
      PANGO_SCRIPT_CANADIAN_ABORIGINAL, /* Cans */
      PANGO_SCRIPT_YI,                 /* Yiii */
      PANGO_SCRIPT_TAGALOG,            /* Tglg */
      PANGO_SCRIPT_HANUNOO,            /* Hano */
      PANGO_SCRIPT_BUHID,              /* Buhd */
      PANGO_SCRIPT_TAGBANWA,           /* Tagb */

      /* Unicode-4.0 additions */
      PANGO_SCRIPT_BRAILLE,            /* Brai */
      PANGO_SCRIPT_CYPRIOT,            /* Cprt */
      PANGO_SCRIPT_LIMBU,              /* Limb */
      PANGO_SCRIPT_OSMANYA,            /* Osma */
      PANGO_SCRIPT_SHAVIAN,            /* Shaw */
      PANGO_SCRIPT_LINEAR_B,           /* Linb */
      PANGO_SCRIPT_TAI_LE,             /* Tale */
      PANGO_SCRIPT_UGARITIC,           /* Ugar */

      /* Unicode-4.1 additions */
      PANGO_SCRIPT_NEW_TAI_LUE,        /* Talu */
      PANGO_SCRIPT_BUGINESE,           /* Bugi */
      PANGO_SCRIPT_GLAGOLITIC,         /* Glag */
      PANGO_SCRIPT_TIFINAGH,           /* Tfng */
      PANGO_SCRIPT_SYLOTI_NAGRI,       /* Sylo */
      PANGO_SCRIPT_OLD_PERSIAN,        /* Xpeo */
      PANGO_SCRIPT_KHAROSHTHI,         /* Khar */

      /* Unicode-5.0 additions */
      PANGO_SCRIPT_UNKNOWN,            /* Zzzz */
      PANGO_SCRIPT_BALINESE,           /* Bali */
      PANGO_SCRIPT_CUNEIFORM,          /* Xsux */
      PANGO_SCRIPT_PHOENICIAN,         /* Phnx */
      PANGO_SCRIPT_PHAGS_PA,           /* Phag */
      PANGO_SCRIPT_NKO                 /* Nkoo */
} PangoScript;

The PangoScript enumeration identifies different writing systems. The values correspond to the names as defined in the Unicode standard. Note that new types may be added in the future. Applications should be ready to handle unknown values. See Unicode Standard Annex 24: Script names.

PANGO_SCRIPT_INVALID_CODE | a value never returned from pango_script_for_unichar()
PANGO_SCRIPT_COMMON | a character used by multiple different scripts
PANGO_SCRIPT_INHERITED | a mark glyph that takes its script from the base glyph to which it is attached
PANGO_SCRIPT_ARABIC | Arabic
PANGO_SCRIPT_ARMENIAN | Armenian
PANGO_SCRIPT_BENGALI | Bengali
PANGO_SCRIPT_BOPOMOFO | Bopomofo
PANGO_SCRIPT_CHEROKEE | Cherokee
PANGO_SCRIPT_COPTIC | Coptic
PANGO_SCRIPT_CYRILLIC | Cyrillic
PANGO_SCRIPT_DESERET | Deseret
PANGO_SCRIPT_DEVANAGARI | Devanagari
PANGO_SCRIPT_ETHIOPIC | Ethiopic
PANGO_SCRIPT_GEORGIAN | Georgian
PANGO_SCRIPT_GOTHIC | Gothic
PANGO_SCRIPT_GREEK | Greek
PANGO_SCRIPT_GUJARATI | Gujarati
PANGO_SCRIPT_GURMUKHI | Gurmukhi
PANGO_SCRIPT_HAN | Han
PANGO_SCRIPT_HANGUL | Hangul
PANGO_SCRIPT_HEBREW | Hebrew
PANGO_SCRIPT_HIRAGANA | Hiragana
PANGO_SCRIPT_KANNADA | Kannada
PANGO_SCRIPT_KATAKANA | Katakana
PANGO_SCRIPT_KHMER | Khmer
PANGO_SCRIPT_LAO | Lao
PANGO_SCRIPT_LATIN | Latin
PANGO_SCRIPT_MALAYALAM | Malayalam
PANGO_SCRIPT_MONGOLIAN | Mongolian
PANGO_SCRIPT_MYANMAR | Myanmar
PANGO_SCRIPT_OGHAM | Ogham
PANGO_SCRIPT_OLD_ITALIC | Old Italic
PANGO_SCRIPT_ORIYA | Oriya
PANGO_SCRIPT_RUNIC | Runic
PANGO_SCRIPT_SINHALA | Sinhala
PANGO_SCRIPT_SYRIAC | Syriac
PANGO_SCRIPT_TAMIL | Tamil
PANGO_SCRIPT_TELUGU | Telugu
PANGO_SCRIPT_THAANA | Thaana
PANGO_SCRIPT_THAI | Thai
PANGO_SCRIPT_TIBETAN | Tibetan
PANGO_SCRIPT_CANADIAN_ABORIGINAL | Canadian Aboriginal
PANGO_SCRIPT_YI | Yi
PANGO_SCRIPT_TAGALOG | Tagalog
PANGO_SCRIPT_HANUNOO | Hanunoo
PANGO_SCRIPT_BUHID | Buhid
PANGO_SCRIPT_TAGBANWA | Tagbanwa
PANGO_SCRIPT_BRAILLE | Braille
PANGO_SCRIPT_CYPRIOT | Cypriot
PANGO_SCRIPT_LIMBU | Limbu
PANGO_SCRIPT_OSMANYA | Osmanya
PANGO_SCRIPT_SHAVIAN | Shavian
PANGO_SCRIPT_LINEAR_B | Linear B
PANGO_SCRIPT_TAI_LE | Tai Le
PANGO_SCRIPT_UGARITIC | Ugaritic
PANGO_SCRIPT_NEW_TAI_LUE | New Tai Lue
PANGO_SCRIPT_BUGINESE | Buginese
PANGO_SCRIPT_GLAGOLITIC | Glagolitic
PANGO_SCRIPT_TIFINAGH | Tifinagh
PANGO_SCRIPT_SYLOTI_NAGRI | Syloti Nagri
PANGO_SCRIPT_OLD_PERSIAN | Old Persian
PANGO_SCRIPT_KHAROSHTHI | Kharoshthi
PANGO_SCRIPT_UNKNOWN | an unassigned code point
PANGO_SCRIPT_BALINESE | Balinese
PANGO_SCRIPT_CUNEIFORM | Cuneiform
PANGO_SCRIPT_PHOENICIAN | Phoenician
PANGO_SCRIPT_PHAGS_PA | Phags-pa
PANGO_SCRIPT_NKO | N'Ko

PANGO_TYPE_SCRIPT

#define PANGO_TYPE_SCRIPT (pango_script_get_type())

The GObject type for PangoScript

pango_script_for_unichar ()

PangoScript pango_script_for_unichar        (gunichar ch);

Looks up the PangoScript for a particular character (as defined by Unicode Standard Annex 24). No check is made for ch being a valid Unicode character; if you pass in invalid character, the result is undefined.

ch : | a Unicode character
Returns : | the PangoScript for the character.

Since 1.4

pango_script_get_sample_language ()

PangoLanguage* pango_script_get_sample_language
                                            (PangoScript script);

Given a script, finds a language tag that is reasonably representative of that script. This will usually be the most widely spoken or used language written in that script: for instance, the sample language for PANGO_SCRIPT_CYRILLIC is ru (Russian), the sample language for PANGO_SCRIPT_ARABIC is ar.

For some scripts, no sample language will be returned because there is no language that is sufficiently representative. The best example of this is PANGO_SCRIPT_HAN, where various different variants of written Chinese, Japanese, and Korean all use significantly different sets of Han characters and forms of shared characters. No sample language can be provided for many historical scripts as well.

script : | a PangoScript
Returns : | a PangoLanguage that is representative of the script, or NULL if no such language exists.

Since 1.4

pango_language_includes_script ()

gboolean    pango_language_includes_script  (PangoLanguage *language,
                                             PangoScript script);

Determines if script is one of the scripts used to write language. The returned value is conservative; if nothing is known about the language tag language, TRUE will be returned, since, as far as Pango knows, script might be used to write language.

This routine is used in Pango's itemization process when determining if a supplied language tag is relevant to a particular section of text. It probably is not useful for applications in most circumstances.

language : | a PangoLanguage
script : | a PangoScript
Returns : | TRUE if script is one of the scripts used to write language, or if nothing is known about language.

Since 1.4

pango_script_iter_new ()

PangoScriptIter* pango_script_iter_new      (const char *text,
                                             int length);

Create a new PangoScriptIter, used to break a string of Unicode into runs by text. No copy is made of text, so the caller needs to make sure it remains valid until the iterator is freed with pango_script_iter_free().x

text : | a UTF-8 string
length : | length of text, or -1 if text is nul-terminated.
Returns : | the new script iterator, initialized to point at the first range in the text, which should be freed with pango_script_iter_free(). If the string is empty, it will point at an empty range.

Since 1.4

pango_script_iter_get_range ()

void        pango_script_iter_get_range     (PangoScriptIter *iter,
                                             G_CONST_RETURN char **start,
                                             G_CONST_RETURN char **end,
                                             PangoScript *script);

Gets information about the range to which iter currently points. The range is the set of locations p where *start <= p < *end. (That is, it doesn't include the character stored at *end)

iter : | a PangoScriptIter
start : | location to store start position of the range, or NULL
end : | location to store end position of the range, or NULL
script : | location to store script for range, or NULL

Since 1.4

pango_script_iter_next ()

gboolean    pango_script_iter_next          (PangoScriptIter *iter);

Advances a PangoScriptIter to the next range. If iter is already at the end, it is left unchanged and FALSE is returned.

iter : | a PangoScriptIter
Returns : | TRUE if iter was successfully advanced.

Since 1.4

pango_script_iter_free ()

void        pango_script_iter_free          (PangoScriptIter *iter);

Frees a PangoScriptIter created with pango_script_iter_new().

iter : a PangoScriptIter

Since 1.4


Tab Stops

Tab Stops — Structures for storing tab stops

Synopsis

            PangoTabArray;
#define     PANGO_TYPE_TAB_ARRAY
enum        PangoTabAlign;
#define     PANGO_TYPE_TAB_ALIGN
PangoTabArray* pango_tab_array_new          (gint initial_size,
                                             gboolean positions_in_pixels);
PangoTabArray* pango_tab_array_new_with_positions
                                            (gint size,
                                             gboolean positions_in_pixels,
                                             PangoTabAlign first_alignment,
                                             gint first_position,
                                             ...);
PangoTabArray* pango_tab_array_copy         (PangoTabArray *src);
void        pango_tab_array_free            (PangoTabArray *tab_array);
gint        pango_tab_array_get_size        (PangoTabArray *tab_array);
void        pango_tab_array_resize          (PangoTabArray *tab_array,
                                             gint new_size);
void        pango_tab_array_set_tab         (PangoTabArray *tab_array,
                                             gint tab_index,
                                             PangoTabAlign alignment,
                                             gint location);
void        pango_tab_array_get_tab         (PangoTabArray *tab_array,
                                             gint tab_index,
                                             PangoTabAlign *alignment,
                                             gint *location);
void        pango_tab_array_get_tabs        (PangoTabArray *tab_array,
                                             PangoTabAlign **alignments,
                                             gint **locations);
gboolean    pango_tab_array_get_positions_in_pixels
                                            (PangoTabArray *tab_array);

Description

Functions in this section are used to deal with PangoTabArray objects that can be used to set tab stop positions in a PangoLayout.

Details

PangoTabArray

typedef struct _PangoTabArray PangoTabArray;

A PangoTabArray struct contains an array of tab stops. Each tab stop has an alignment and a position.

PANGO_TYPE_TAB_ARRAY

#define PANGO_TYPE_TAB_ARRAY (pango_tab_array_get_type ())

The GObject type for PangoTabArray.

enum PangoTabAlign

typedef enum
{
  PANGO_TAB_LEFT

  /* These are not supported now, but may be in the
   * future.
   *
   *  PANGO_TAB_RIGHT,
   *  PANGO_TAB_CENTER,
   *  PANGO_TAB_NUMERIC
   */
} PangoTabAlign;

A PangoTabAlign specifies where a tab stop appears relative to the text.

PANGO_TAB_LEFT the tab stop appears to the left of the text.

PANGO_TYPE_TAB_ALIGN

#define PANGO_TYPE_TAB_ALIGN (pango_tab_align_get_type())

The GObject type for PangoTabAlign.

pango_tab_array_new ()

PangoTabArray* pango_tab_array_new          (gint initial_size,
                                             gboolean positions_in_pixels);

Creates an array of initial_size tab stops. Tab stops are specified in pixel units if positions_in_pixels is TRUE, otherwise in Pango units. All stops are initially at position 0.

initial_size : | Initial number of tab stops to allocate, can be 0
positions_in_pixels : | whether positions are in pixel units
Returns : | the newly allocated PangoTabArray, which should be freed with pango_tab_array_free().

pango_tab_array_new_with_positions ()

PangoTabArray* pango_tab_array_new_with_positions
                                            (gint size,
                                             gboolean positions_in_pixels,
                                             PangoTabAlign first_alignment,
                                             gint first_position,
                                             ...);

This is a convenience function that creates a PangoTabArray and allows you to specify the alignment and position of each tab stop. You must provide an alignment and position for size tab stops.

size : | number of tab stops in the array
positions_in_pixels : | whether positions are in pixel units
first_alignment : | alignment of first tab stop
first_position : | position of first tab stop
... : | additional alignment/position pairs
Returns : | the newly allocated PangoTabArray, which should be freed with pango_tab_array_free().

pango_tab_array_copy ()

PangoTabArray* pango_tab_array_copy         (PangoTabArray *src);

Copies a PangoTabArray

src : | PangoTabArray to copy
Returns : | the newly allocated PangoTabArray, which should be freed with pango_tab_array_free().

pango_tab_array_free ()

void        pango_tab_array_free            (PangoTabArray *tab_array);

Frees a tab array and associated resources.

tab_array : a PangoTabArray

pango_tab_array_get_size ()

gint        pango_tab_array_get_size        (PangoTabArray *tab_array);

Gets the number of tab stops in tab_array.

tab_array : | a PangoTabArray
Returns : | the number of tab stops in the array.

pango_tab_array_resize ()

void        pango_tab_array_resize          (PangoTabArray *tab_array,
                                             gint new_size);

Resizes a tab array. You must subsequently initialize any tabs that were added as a result of growing the array.

tab_array : | a PangoTabArray
new_size : | new size of the array

pango_tab_array_set_tab ()

void        pango_tab_array_set_tab         (PangoTabArray *tab_array,
                                             gint tab_index,
                                             PangoTabAlign alignment,
                                             gint location);

Sets the alignment and location of a tab stop. alignment must always be PANGO_TAB_LEFT in the current implementation.

tab_array : | a PangoTabArray
tab_index : | the index of a tab stop
alignment : | tab alignment
location : | tab location in Pango units

pango_tab_array_get_tab ()

void        pango_tab_array_get_tab         (PangoTabArray *tab_array,
                                             gint tab_index,
                                             PangoTabAlign *alignment,
                                             gint *location);

Gets the alignment and position of a tab stop.

tab_array : | a PangoTabArray
tab_index : | tab stop index
alignment : | location to store alignment, or NULL
location : | location to store tab position, or NULL

pango_tab_array_get_tabs ()

void        pango_tab_array_get_tabs        (PangoTabArray *tab_array,
                                             PangoTabAlign **alignments,
                                             gint **locations);

If non-NULL, alignments and locations are filled with allocated arrays of length pango_tab_array_get_size(). You must free the returned array.

tab_array : | a PangoTabArray
alignments : | location to store an array of tab stop alignments, or NULL
locations : | location to store an array of tab positions, or NULL

pango_tab_array_get_positions_in_pixels ()

gboolean    pango_tab_array_get_positions_in_pixels
                                            (PangoTabArray *tab_array);

Returns TRUE if the tab positions are in pixels, FALSE if they are in Pango units.

tab_array : | a PangoTabArray
Returns : | whether positions are in pixels.


Text Attributes

Text Attributes — Font and other attributes for annotating text

Synopsis

enum        PangoAttrType;
#define     PANGO_TYPE_ATTR_TYPE
            PangoAttrClass;
            PangoAttribute;
            PangoAttrString;
            PangoAttrLanguage;
            PangoAttrColor;
            PangoAttrInt;
            PangoAttrFloat;
            PangoAttrFontDesc;
            PangoAttrShape;
            PangoAttrSize;
gboolean    pango_parse_markup              (const char *markup_text,
                                             int length,
                                             gunichar accel_marker,
                                             PangoAttrList **attr_list,
                                             char **text,
                                             gunichar *accel_char,
                                             GError **error);
PangoAttrType pango_attr_type_register      (const gchar *name);
PangoAttribute* pango_attribute_copy        (const PangoAttribute *attr);
gboolean    pango_attribute_equal           (const PangoAttribute *attr1,
                                             const PangoAttribute *attr2);
void        pango_attribute_destroy         (PangoAttribute *attr);

PangoAttribute* pango_attr_language_new     (PangoLanguage *language);
PangoAttribute* pango_attr_family_new       (const char *family);
PangoAttribute* pango_attr_style_new        (PangoStyle style);
PangoAttribute* pango_attr_variant_new      (PangoVariant variant);
PangoAttribute* pango_attr_stretch_new      (PangoStretch stretch);
PangoAttribute* pango_attr_weight_new       (PangoWeight weight);
PangoAttribute* pango_attr_size_new         (int size);
PangoAttribute* pango_attr_size_new_absolute
                                            (int size);
PangoAttribute* pango_attr_font_desc_new    (const PangoFontDescription *desc);
PangoAttribute* pango_attr_foreground_new   (guint16 red,
                                             guint16 green,
                                             guint16 blue);
PangoAttribute* pango_attr_background_new   (guint16 red,
                                             guint16 green,
                                             guint16 blue);
PangoAttribute* pango_attr_strikethrough_new
                                            (gboolean strikethrough);
PangoAttribute* pango_attr_strikethrough_color_new
                                            (guint16 red,
                                             guint16 green,
                                             guint16 blue);
PangoAttribute* pango_attr_underline_new    (PangoUnderline underline);
PangoAttribute* pango_attr_underline_color_new
                                            (guint16 red,
                                             guint16 green,
                                             guint16 blue);
enum        PangoUnderline;
#define     PANGO_TYPE_UNDERLINE
PangoAttribute* pango_attr_shape_new        (const PangoRectangle *ink_rect,
                                             const PangoRectangle *logical_rect);
PangoAttribute* pango_attr_shape_new_with_data
                                            (const PangoRectangle *ink_rect,
                                             const PangoRectangle *logical_rect,
                                             gpointer data,
                                             PangoAttrDataCopyFunc copy_func,
                                             GDestroyNotify destroy_func);
gpointer    (*PangoAttrDataCopyFunc)        (gconstpointer data);
PangoAttribute* pango_attr_scale_new        (double scale_factor);
#define     PANGO_SCALE_XX_SMALL
#define     PANGO_SCALE_X_SMALL
#define     PANGO_SCALE_SMALL
#define     PANGO_SCALE_MEDIUM
#define     PANGO_SCALE_LARGE
#define     PANGO_SCALE_X_LARGE
#define     PANGO_SCALE_XX_LARGE
PangoAttribute* pango_attr_rise_new         (int rise);
PangoAttribute* pango_attr_letter_spacing_new
                                            (int letter_spacing);
PangoAttribute* pango_attr_fallback_new     (gboolean enable_fallback);
PangoAttribute* pango_attr_gravity_new      (PangoGravity gravity);
PangoAttribute* pango_attr_gravity_hint_new (PangoGravityHint hint);
            PangoColor;
#define     PANGO_TYPE_COLOR
gboolean    pango_color_parse               (PangoColor *color,
                                             const char *spec);
PangoColor* pango_color_copy                (const PangoColor *src);
void        pango_color_free                (PangoColor *color);
gchar*      pango_color_to_string           (const PangoColor *color);
            PangoLanguage;
#define     PANGO_TYPE_LANGUAGE
PangoLanguage* pango_language_from_string   (const char *language);
#define     pango_language_to_string        (language)
gboolean    pango_language_matches          (PangoLanguage *language,
                                             const char *range_list);

            PangoAttrList;
#define     PANGO_TYPE_ATTR_LIST
PangoAttrList* pango_attr_list_new          (void);
PangoAttrList* pango_attr_list_ref          (PangoAttrList *list);
void        pango_attr_list_unref           (PangoAttrList *list);
PangoAttrList* pango_attr_list_copy         (PangoAttrList *list);
void        pango_attr_list_insert          (PangoAttrList *list,
                                             PangoAttribute *attr);
void        pango_attr_list_insert_before   (PangoAttrList *list,
                                             PangoAttribute *attr);
void        pango_attr_list_change          (PangoAttrList *list,
                                             PangoAttribute *attr);
void        pango_attr_list_splice          (PangoAttrList *list,
                                             PangoAttrList *other,
                                             gint pos,
                                             gint len);
PangoAttrList* pango_attr_list_filter       (PangoAttrList *list,
                                             PangoAttrFilterFunc func,
                                             gpointer data);
gboolean    (*PangoAttrFilterFunc)          (PangoAttribute *attribute,
                                             gpointer data);
PangoAttrIterator* pango_attr_list_get_iterator
                                            (PangoAttrList *list);
            PangoAttrIterator;
PangoAttrIterator* pango_attr_iterator_copy (PangoAttrIterator *iterator);
gboolean    pango_attr_iterator_next        (PangoAttrIterator *iterator);
void        pango_attr_iterator_range       (PangoAttrIterator *iterator,
                                             gint *start,
                                             gint *end);
PangoAttribute* pango_attr_iterator_get     (PangoAttrIterator *iterator,
                                             PangoAttrType type);
void        pango_attr_iterator_get_font    (PangoAttrIterator *iterator,
                                             PangoFontDescription *desc,
                                             PangoLanguage **language,
                                             GSList **extra_attrs);
GSList*     pango_attr_iterator_get_attrs   (PangoAttrIterator *iterator);
void        pango_attr_iterator_destroy     (PangoAttrIterator *iterator);

Description

Attributed text is used in a number of places in Pango. It is used as the input to the itemization process and also when creating a PangoLayout. The data types and functions in this section are used to represent and manipulate sets of attributes applied to a portion of text.

Details

enum PangoAttrType

typedef enum
{
  PANGO_ATTR_INVALID,           /* 0 is an invalid attribute type */
  PANGO_ATTR_LANGUAGE,		/* PangoAttrLanguage */
  PANGO_ATTR_FAMILY,		/* PangoAttrString */
  PANGO_ATTR_STYLE,		/* PangoAttrInt */
  PANGO_ATTR_WEIGHT,		/* PangoAttrInt */
  PANGO_ATTR_VARIANT,		/* PangoAttrInt */
  PANGO_ATTR_STRETCH,		/* PangoAttrInt */
  PANGO_ATTR_SIZE,		/* PangoAttrSize */
  PANGO_ATTR_FONT_DESC,		/* PangoAttrFontDesc */
  PANGO_ATTR_FOREGROUND,	/* PangoAttrColor */
  PANGO_ATTR_BACKGROUND,	/* PangoAttrColor */
  PANGO_ATTR_UNDERLINE,		/* PangoAttrInt */
  PANGO_ATTR_STRIKETHROUGH,	/* PangoAttrInt */
  PANGO_ATTR_RISE,		/* PangoAttrInt */
  PANGO_ATTR_SHAPE,		/* PangoAttrShape */
  PANGO_ATTR_SCALE,             /* PangoAttrFloat */
  PANGO_ATTR_FALLBACK,          /* PangoAttrInt */
  PANGO_ATTR_LETTER_SPACING,    /* PangoAttrInt */
  PANGO_ATTR_UNDERLINE_COLOR,	/* PangoAttrColor */
  PANGO_ATTR_STRIKETHROUGH_COLOR,/* PangoAttrColor */
  PANGO_ATTR_ABSOLUTE_SIZE,	/* PangoAttrSize */
  PANGO_ATTR_GRAVITY,		/* PangoAttrInt */
  PANGO_ATTR_GRAVITY_HINT	/* PangoAttrInt */
} PangoAttrType;

The PangoAttrType distinguishes between different types of attributes. Along with the predefined values, it is possible to allocate additional values for custom attributes using pango_attr_type_register(). The predefined values are given below. The type of structure used to store the attribute is listed in parentheses after the description.

PANGO_ATTR_INVALID | does not happen
PANGO_ATTR_LANGUAGE | language (PangoAttrLanguage)
PANGO_ATTR_FAMILY | font family name list (PangoAttrString)
PANGO_ATTR_STYLE | font slant style (PangoAttrInt)
PANGO_ATTR_WEIGHT | font weight (PangoAttrInt)
PANGO_ATTR_VARIANT | font variant (normal or small caps) (PangoAttrInt)
PANGO_ATTR_STRETCH | font stretch (PangoAttrInt)
PANGO_ATTR_SIZE | font size in points scaled by PANGO_SCALE (PangoAttrInt)
PANGO_ATTR_FONT_DESC | font description (PangoAttrFontDesc)
PANGO_ATTR_FOREGROUND | foreground color (PangoAttrColor)
PANGO_ATTR_BACKGROUND | background color (PangoAttrColor)
PANGO_ATTR_UNDERLINE | whether the text has an underline (PangoAttrInt)
PANGO_ATTR_STRIKETHROUGH | whether the text is struck-through (PangoAttrInt)
PANGO_ATTR_RISE | baseline displacement (PangoAttrInt)
PANGO_ATTR_SHAPE | shape (PangoAttrShape)
PANGO_ATTR_SCALE | font size scale factor (PangoAttrFloat)
PANGO_ATTR_FALLBACK | whether fallback is enabled (PangoAttrInt)
PANGO_ATTR_LETTER_SPACING | letter spacing (PangoAttrInt)
PANGO_ATTR_UNDERLINE_COLOR | underline color (PangoAttrColor)
PANGO_ATTR_STRIKETHROUGH_COLOR | strikethrough color (PangoAttrColor)
PANGO_ATTR_ABSOLUTE_SIZE | font size in pixels scaled by PANGO_SCALE (PangoAttrInt)
PANGO_ATTR_GRAVITY | base text gravity (PangoAttrInt)
PANGO_ATTR_GRAVITY_HINT | gravity hint (PangoAttrInt)

PANGO_TYPE_ATTR_TYPE

#define PANGO_TYPE_ATTR_TYPE (pango_attr_type_get_type())

The GObject type for PangoAttrType.

PangoAttrClass

typedef struct {
  PangoAttrType type;
  PangoAttribute * (*copy) (const PangoAttribute *attr);
  void             (*destroy) (PangoAttribute *attr);
  gboolean         (*equal) (const PangoAttribute *attr1, const PangoAttribute *attr2);
} PangoAttrClass;

The PangoAttrClass structure stores the type and operations for a particular type of attribute. The functions in this structure should not be called directly. Instead, one should use the wrapper functions provided for PangoAttribute.

PangoAttrType type; | the type ID for this attribute
copy () | function to duplicate an attribute of this type (see pango_attribute_copy())
destroy () | function to free an attribute of this type (see pango_attribute_destroy())
equal () | function to check two attributes of this type for equality (see pango_attribute_equal())

PangoAttribute

typedef struct {
  const PangoAttrClass *klass;
  guint start_index;	/* in bytes */
  guint end_index;	/* in bytes. The character at this index is not included */
} PangoAttribute;

The PangoAttribute structure represents the common portions of all attributes. Particular types of attributes include this structure as their initial portion. The common portion of the attribute holds the range to which the value in the type-specific part of the attribute applies.

const PangoAttrClass *klass; | the class structure holding information about the type of the attribute
guint start_index; | the start index of the range (in bytes).
guint end_index; | end index of the range (in bytes). The character at this index is not included in the range.

PangoAttrString

typedef struct {
  PangoAttribute attr;
  char *value;
} PangoAttrString;

The PangoAttrString structure is used to represent attributes with a string value.

PangoAttribute attr; | the common portion of the attribute
char *value; | the string which is the value of the attribute

PangoAttrLanguage

typedef struct {
  PangoAttribute attr;
  PangoLanguage *value;
} PangoAttrLanguage;

The PangoAttrLanguage structure is used to represent attributes that are languages.

PangoAttribute attr; | the common portion of the attribute
PangoLanguage *value; | the PangoLanguage which is the value of the attribute

PangoAttrColor

typedef struct {
  PangoAttribute attr;
  PangoColor color;
} PangoAttrColor;

The PangoAttrColor structure is used to represent attributes that are colors.

PangoAttribute attr; | the common portion of the attribute
PangoColor color; | the PangoColor which is the value of the attribute

PangoAttrInt

typedef struct {
  PangoAttribute attr;
  int value;
} PangoAttrInt;

The PangoAttrInt structure is used to represent attributes with an integer or enumeration value.

PangoAttribute attr; | the common portion of the attribute
int value; | the value of the attribute

PangoAttrFloat

typedef struct {
  PangoAttribute attr;
  double value;
} PangoAttrFloat;

The PangoAttrFloat structure is used to represent attributes with a float or double value.

PangoAttribute attr; | the common portion of the attribute
double value; | the value of the attribute

PangoAttrFontDesc

typedef struct {
  PangoAttribute attr;
  PangoFontDescription *desc;
} PangoAttrFontDesc;

The PangoAttrFontDesc structure is used to store an attribute that sets all aspects of the font description at once.

PangoAttribute attr; | the common portion of the attribute
PangoFontDescription *desc; | the font description which is the value of this attribute

PangoAttrShape

typedef struct {
  PangoAttribute attr;
  PangoRectangle ink_rect;
  PangoRectangle logical_rect;

  gpointer              data;
  PangoAttrDataCopyFunc copy_func;
  GDestroyNotify        destroy_func;
} PangoAttrShape;

The PangoAttrShape structure is used to represent attributes which impose shape restrictions.

PangoAttribute attr; | the common portion of the attribute
PangoRectangle ink_rect; | the ink rectangle to restrict to
PangoRectangle logical_rect; | the logical rectangle to restrict to
gpointer data; | user data set (see pango_attr_shape_new_with_data())
PangoAttrDataCopyFunc copy_func; | copy function for the user data
GDestroyNotify destroy_func; | destroy function for the user data

PangoAttrSize

typedef struct {
  PangoAttribute attr;
  int size;
  guint absolute : 1;
} PangoAttrSize;

The PangoAttrShape structure is used to represent attributes which set font size.

PangoAttribute attr; | the common portion of the attribute
int size; | size of font, in units of 1/PANGO_SCALE of a point (for PANGO_ATTR_SIZE) or of a device uni (for PANGO_ATTR_ABSOLUTE_SIZE)
guint absolute : 1; | whether the font size is in device units or points. This field is only present for compatibility with Pango-1.8.0 (PANGO_ATTR_ABSOLUTE_SIZE was added in 1.8.1); and always will be FALSE for PANGO_ATTR_SIZE and TRUE for PANGO_ATTR_ABSOLUTE_SIZE.

pango_parse_markup ()

gboolean    pango_parse_markup              (const char *markup_text,
                                             int length,
                                             gunichar accel_marker,
                                             PangoAttrList **attr_list,
                                             char **text,
                                             gunichar *accel_char,
                                             GError **error);

Parses marked-up text (see markup format) to create a plain-text string and an attribute list.

If accel_marker is nonzero, the given character will mark the character following it as an accelerator. For example, accel_marker might be an ampersand or underscore. All characters marked as an accelerator will receive a PANGO_UNDERLINE_LOW attribute, and the first character so marked will be returned in accel_char. Two accel_marker characters following each other produce a single literal accel_marker character.

markup_text : | markup to parse (see markup format)
length : | length of markup_text, or -1 if nul-terminated
accel_marker : | character that precedes an accelerator, or 0 for none
attr_list : | address of return location for a PangoAttrList, or NULL
text : | address of return location for text with tags stripped, or NULL
accel_char : | address of return location for accelerator char, or NULL
error : | address of return location for errors, or NULL
Returns : | FALSE if error is set, otherwise TRUE

pango_attr_type_register ()

PangoAttrType pango_attr_type_register      (const gchar *name);

Allocate a new attribute type ID.

name : | an identifier for the type (currently unused.)
Returns : | the new type ID.

pango_attribute_copy ()

PangoAttribute* pango_attribute_copy        (const PangoAttribute *attr);

Make a copy of an attribute.

attr : | a PangoAttribute
Returns : | the newly allocated PangoAttribute, which should be freed with pango_attribute_destroy().

pango_attribute_equal ()

gboolean    pango_attribute_equal           (const PangoAttribute *attr1,
                                             const PangoAttribute *attr2);

Compare two attributes for equality. This compares only the actual value of the two attributes and not the ranges that the attributes apply to.

attr1 : | a PangoAttribute
attr2 : | another PangoAttribute
Returns : | TRUE if the two attributes have the same value.

pango_attribute_destroy ()

void        pango_attribute_destroy         (PangoAttribute *attr);

Destroy a PangoAttribute and free all associated memory.

attr : a PangoAttribute.

pango_attr_language_new ()

PangoAttribute* pango_attr_language_new     (PangoLanguage *language);

Create a new language tag attribute.

language : | language tag
Returns : | the newly allocated PangoAttribute, which should be freed with pango_attribute_destroy().

pango_attr_family_new ()

PangoAttribute* pango_attr_family_new       (const char *family);

Create a new font family attribute.

family : | the family or comma separated list of families
Returns : | the newly allocated PangoAttribute, which should be freed with pango_attribute_destroy().

pango_attr_style_new ()

PangoAttribute* pango_attr_style_new        (PangoStyle style);

Create a new font slant style attribute.

style : | the slant style
Returns : | the newly allocated PangoAttribute, which should be freed with pango_attribute_destroy().

pango_attr_variant_new ()

PangoAttribute* pango_attr_variant_new      (PangoVariant variant);

Create a new font variant attribute (normal or small caps)

variant : | the variant
Returns : | the newly allocated PangoAttribute, which should be freed with pango_attribute_destroy().

pango_attr_stretch_new ()

PangoAttribute* pango_attr_stretch_new      (PangoStretch stretch);

Create a new font stretch attribute

stretch : | the stretch
Returns : | the newly allocated PangoAttribute, which should be freed with pango_attribute_destroy().

pango_attr_weight_new ()

PangoAttribute* pango_attr_weight_new       (PangoWeight weight);

Create a new font weight attribute.

weight : | the weight
Returns : | the newly allocated PangoAttribute, which should be freed with pango_attribute_destroy().

pango_attr_size_new ()

PangoAttribute* pango_attr_size_new         (int size);

Create a new font-size attribute in fractional points.

size : | the font size, in PANGO_SCALEths of a point.
Returns : | the newly allocated PangoAttribute, which should be freed with pango_attribute_destroy().

pango_attr_size_new_absolute ()

PangoAttribute* pango_attr_size_new_absolute
                                            (int size);

Create a new font-size attribute in device units.

size : | the font size, in PANGO_SCALEths of a device unit.
Returns : | the newly allocated PangoAttribute, which should be freed with pango_attribute_destroy().

Since 1.8

pango_attr_font_desc_new ()

PangoAttribute* pango_attr_font_desc_new    (const PangoFontDescription *desc);

Create a new font description attribute. This attribute allows setting family, style, weight, variant, stretch, and size simultaneously.

desc : | the font description
Returns : | the newly allocated PangoAttribute, which should be freed with pango_attribute_destroy().

pango_attr_foreground_new ()

PangoAttribute* pango_attr_foreground_new   (guint16 red,
                                             guint16 green,
                                             guint16 blue);

Create a new foreground color attribute.

red : | the red value (ranging from 0 to 65535)
green : | the green value
blue : | the blue value
Returns : | the newly allocated PangoAttribute, which should be freed with pango_attribute_destroy().

pango_attr_background_new ()

PangoAttribute* pango_attr_background_new   (guint16 red,
                                             guint16 green,
                                             guint16 blue);

Create a new background color attribute.

red : | the red value (ranging from 0 to 65535)
green : | the green value
blue : | the blue value
Returns : | the newly allocated PangoAttribute, which should be freed with pango_attribute_destroy().

pango_attr_strikethrough_new ()

PangoAttribute* pango_attr_strikethrough_new
                                            (gboolean strikethrough);

Create a new strike-through attribute.

strikethrough : | TRUE if the text should be struck-through.
Returns : | the newly allocated PangoAttribute, which should be freed with pango_attribute_destroy().

pango_attr_strikethrough_color_new ()

PangoAttribute* pango_attr_strikethrough_color_new
                                            (guint16 red,
                                             guint16 green,
                                             guint16 blue);

Create a new strikethrough color attribute. This attribute modifies the color of strikethrough lines. If not set, strikethrough lines will use the foreground color.

red : | the red value (ranging from 0 to 65535)
green : | the green value
blue : | the blue value
Returns : | the newly allocated PangoAttribute, which should be freed with pango_attribute_destroy().

Since 1.8

pango_attr_underline_new ()

PangoAttribute* pango_attr_underline_new    (PangoUnderline underline);

Create a new underline-style attribute.

underline : | the underline style.
Returns : | the newly allocated PangoAttribute, which should be freed with pango_attribute_destroy().

pango_attr_underline_color_new ()

PangoAttribute* pango_attr_underline_color_new
                                            (guint16 red,
                                             guint16 green,
                                             guint16 blue);

Create a new underline color attribute. This attribute modifies the color of underlines. If not set, underlines will use the foreground color.

red : | the red value (ranging from 0 to 65535)
green : | the green value
blue : | the blue value
Returns : | the newly allocated PangoAttribute, which should be freed with pango_attribute_destroy().

Since 1.8

enum PangoUnderline

typedef enum {
  PANGO_UNDERLINE_NONE,
  PANGO_UNDERLINE_SINGLE,
  PANGO_UNDERLINE_DOUBLE,
  PANGO_UNDERLINE_LOW,
  PANGO_UNDERLINE_ERROR
} PangoUnderline;

the PangoUnderline enumeration is used to specify whether text should be underlined, and if so, the type of underlining.

PANGO_UNDERLINE_NONE | no underline should be drawn
PANGO_UNDERLINE_SINGLE | a single underline should be drawn
PANGO_UNDERLINE_DOUBLE | a double underline should be drawn
PANGO_UNDERLINE_LOW | a single underline should be drawn at a position beneath the ink extents of the text being underlined. This should be used only for underlining single characters, such as for keyboard accelerators. PANGO_UNDERLINE_SINGLE should be used for extended portions of text.
PANGO_UNDERLINE_ERROR | a wavy underline should be drawn below. This underline is typically used to indicate an error such as a possilble mispelling; in some cases a contrasting color may automatically be used. This type of underlining is available since Pango 1.4.

PANGO_TYPE_UNDERLINE

#define PANGO_TYPE_UNDERLINE (pango_underline_get_type())

The GObject type for PangoUnderline.

pango_attr_shape_new ()

PangoAttribute* pango_attr_shape_new        (const PangoRectangle *ink_rect,
                                             const PangoRectangle *logical_rect);

Create a new shape attribute. A shape is used to impose a particular ink and logical rectangle on the result of shaping a particular glyph. This might be used, for instance, for embedding a picture or a widget inside a PangoLayout.

ink_rect : | ink rectangle to assign to each character
logical_rect : | logical rectangle to assign to each character
Returns : | the newly allocated PangoAttribute, which should be freed with pango_attribute_destroy().

pango_attr_shape_new_with_data ()

PangoAttribute* pango_attr_shape_new_with_data
                                            (const PangoRectangle *ink_rect,
                                             const PangoRectangle *logical_rect,
                                             gpointer data,
                                             PangoAttrDataCopyFunc copy_func,
                                             GDestroyNotify destroy_func);

Like pango_attr_shape_new(), but a user data pointer is also provided; this pointer can be accessed when later rendering the glyph.

ink_rect : | ink rectangle to assign to each character
logical_rect : | logical rectangle to assign to each character
data : | user data pointer
copy_func : | function to copy data when the attribute is copied. If NULL, data is simply copied as a pointer.
destroy_func : | function to free data when the attribute is freed, or NULL
Returns : | the newly allocated PangoAttribute, which should be freed with pango_attribute_destroy().

Since 1.8

PangoAttrDataCopyFunc ()

gpointer    (*PangoAttrDataCopyFunc)        (gconstpointer data);

A copy function passed to attribute new functions that take user data.

data : | the user data
Returns : | a new copy of data.

pango_attr_scale_new ()

PangoAttribute* pango_attr_scale_new        (double scale_factor);

Create a new font size scale attribute. The base font for the affected text will have its size multiplied by scale_factor.

scale_factor : | factor to scale the font
Returns : | the newly allocated PangoAttribute, which should be freed with pango_attribute_destroy().

PANGO_SCALE_XX_SMALL

#define PANGO_SCALE_XX_SMALL ((double)0.5787037037037)

The scale factor for three shrinking steps (1 / (1.2 * 1.2 * 1.2)).

PANGO_SCALE_X_SMALL

#define PANGO_SCALE_X_SMALL  ((double)0.6444444444444)

The scale factor for two shrinking steps (1 / (1.2 * 1.2)).

PANGO_SCALE_SMALL

#define PANGO_SCALE_SMALL    ((double)0.8333333333333)

The scale factor for one shrinking step (1 / 1.2).

PANGO_SCALE_MEDIUM

#define PANGO_SCALE_MEDIUM   ((double)1.0)

The scale factor for normal size (1.0).

PANGO_SCALE_LARGE

#define PANGO_SCALE_LARGE    ((double)1.2)

The scale factor for one magnification step (1.2).

PANGO_SCALE_X_LARGE

#define PANGO_SCALE_X_LARGE  ((double)1.4399999999999)

The scale factor for two magnification steps (1.2 * 1.2).

PANGO_SCALE_XX_LARGE

#define PANGO_SCALE_XX_LARGE ((double)1.728)

The scale factor for three magnification steps (1.2 * 1.2 * 1.2).

pango_attr_rise_new ()

PangoAttribute* pango_attr_rise_new         (int rise);

Create a new baseline displacement attribute.

rise : | the amount that the text should be displaced vertically, in Pango units. Positive values displace the text upwards.
Returns : | the newly allocated PangoAttribute, which should be freed with pango_attribute_destroy().

pango_attr_letter_spacing_new ()

PangoAttribute* pango_attr_letter_spacing_new
                                            (int letter_spacing);

Create a new letter-spacing attribute.

letter_spacing : | amount of extra space to add between graphemes of the text, in Pango units.
Returns : | the newly allocated PangoAttribute, which should be freed with pango_attribute_destroy().

Since 1.6

pango_attr_fallback_new ()

PangoAttribute* pango_attr_fallback_new     (gboolean enable_fallback);

Create a new font fallback attribute.

If fallback is disabled, characters will only be used from the closest matching font on the system. No fallback will be done to other fonts on the system that might contain the characters in the text.

enable_fallback : | TRUE if we should fall back on other fonts for characters the active font is missing.
Returns : | the newly allocated PangoAttribute, which should be freed with pango_attribute_destroy().

Since 1.4

pango_attr_gravity_new ()

PangoAttribute* pango_attr_gravity_new      (PangoGravity gravity);

Create a new gravity attribute.

gravity : | the gravity value; should not be PANGO_GRAVITY_AUTO.
Returns : | the newly allocated PangoAttribute, which should be freed with pango_attribute_destroy().

Since 1.16

pango_attr_gravity_hint_new ()

PangoAttribute* pango_attr_gravity_hint_new (PangoGravityHint hint);

Create a new gravity hint attribute.

hint : | the gravity hint value.
Returns : | the newly allocated PangoAttribute, which should be freed with pango_attribute_destroy().

Since 1.16

PangoColor

typedef struct {
  guint16 red;
  guint16 green;
  guint16 blue;
} PangoColor;

The PangoColor structure is used to represent a color in an uncalibrated RGB color-space.

guint16 red; | The red component of the color. This is a value between 0 and 65535, with 65535 indicating full intensity.
guint16 green; | The green component of the color. This is a value between 0 and 65535, with 65535 indicating full intensity.
guint16 blue; | The blue component of the color. This is a value between 0 and 65535, with 65535 indicating full intensity.

PANGO_TYPE_COLOR

#define PANGO_TYPE_COLOR pango_color_get_type ()

The GObject type for PangoColor.

pango_color_parse ()

gboolean    pango_color_parse               (PangoColor *color,
                                             const char *spec);

Fill in the fields of a color from a string specification. The string can either one of a large set of standard names. (Taken from the X11 rgb.txt file), or it can be a hex value in the form '#rgb' '#rrggbb' '#rrrgggbbb' or '#rrrrggggbbbb' where 'r', 'g' and 'b' are hex digits of the red, green, and blue components of the color, respectively. (White in the four forms is '#fff' '#ffffff' '#fffffffff' and '#ffffffffffff')

color : | a PangoColor structure in which to store the result
spec : | a string specifying the new color
Returns : | TRUE if parsing of the specifier succeeded, otherwise false.

pango_color_copy ()

PangoColor* pango_color_copy                (const PangoColor *src);

Creates a copy of src, which should be freed with pango_color_free(). Primarily used by language bindings, not that useful otherwise (since colors can just be copied by assignment in C).

src : | color to copy
Returns : | the newly allocated PangoColor, which should be freed with pango_color_free().

pango_color_free ()

void        pango_color_free                (PangoColor *color);

Frees a color allocated by pango_color_copy().

color : an allocated PangoColor

pango_color_to_string ()

gchar*      pango_color_to_string           (const PangoColor *color);

Returns a textual specification of color in the hexadecimal form #rrrrggggbbbb, where r, g and b are hex digits representing the red, green, and blue components respectively.

color : | a PangoColor
Returns : | a newly-allocated text string that must be freed with g_free().

Since 1.16

PangoLanguage

typedef struct _PangoLanguage PangoLanguage;

The PangoLanguage structure is used to represent a language.

PangoLanguage pointers can be efficiently copied and compared with each other.

PANGO_TYPE_LANGUAGE

#define PANGO_TYPE_LANGUAGE (pango_language_get_type ())

The GObject type for PangoLanguage.

pango_language_from_string ()

PangoLanguage* pango_language_from_string   (const char *language);

Take a RFC-3066 format language tag as a string and convert it to a PangoLanguage pointer that can be efficiently copied (copy the pointer) and compared with other language tags (compare the pointer.)

This function first canonicalizes the string by converting it to lowercase, mapping '_' to '-', and stripping all characters other than letters and '-'.

Use pango_language_get_default() if you want to get the PangoLanguage for the current locale of the process.

language : | a string representing a language tag
Returns : | an opaque pointer to a PangoLanguage structure. this will be valid forever after.

pango_language_to_string()

#define pango_language_to_string(language) ((const char *)language)

Returns a RFC-3066 format string representing the given language tag.

language : | a language tag.
Returns : | a string representing the language tag.

pango_language_matches ()

gboolean    pango_language_matches          (PangoLanguage *language,
                                             const char *range_list);

Checks if a language tag matches one of the elements in a list of language ranges. A language tag is considered to match a range in the list if the range is '*', the range is exactly the tag, or the range is a prefix of the tag, and the character after it in the tag is '-'.

language : | a language tag (see pango_language_from_string()), NULL is allowed and matches nothing but '*'
range_list : | a list of language ranges, separated by ';', ':', ',', or space characters. Each element must either be '*', or a RFC 3066 language range canonicalized as by pango_language_from_string()
Returns : | TRUE if a match was found.

PangoAttrList

typedef struct _PangoAttrList PangoAttrList;

The PangoAttrList structure represents a list of attributes that apply to a section of text. The attributes are, in general, allowed to overlap in an arbitrary fashion, however, if the attributes are manipulated only through pango_attr_list_change(), the overlap between properties will meet stricter criteria.

Since the PangoAttrList structure is stored as a linear list, it is not suitable for storing attributes for large amounts of text. In general, you should not use a single PangoAttrList for more than one paragraph of text.

PANGO_TYPE_ATTR_LIST

#define PANGO_TYPE_ATTR_LIST pango_attr_list_get_type ()

The GObject type for PangoAttrList.

pango_attr_list_new ()

PangoAttrList* pango_attr_list_new          (void);

Create a new empty attribute list with a reference count of one.

Returns : the newly allocated PangoAttrList, which should be freed with pango_attr_list_unref().

pango_attr_list_ref ()

PangoAttrList* pango_attr_list_ref          (PangoAttrList *list);

Increase the reference count of the given attribute list by one.

list : | a PangoAttrList
Returns : | The attribute list passed in

Since 1.10

pango_attr_list_unref ()

void        pango_attr_list_unref           (PangoAttrList *list);

Decrease the reference count of the given attribute list by one. If the result is zero, free the attribute list and the attributes it contains.

list : a PangoAttrList

pango_attr_list_copy ()

PangoAttrList* pango_attr_list_copy         (PangoAttrList *list);

Copy list and return an identical new list.

list : | a PangoAttrList
Returns : | the newly allocated PangoAttrList, with a reference count of one, which should be freed with pango_attr_list_unref().

pango_attr_list_insert ()

void        pango_attr_list_insert          (PangoAttrList *list,
                                             PangoAttribute *attr);

Insert the given attribute into the PangoAttrList. It will be inserted after all other attributes with a matching start_index.

list : | a PangoAttrList
attr : | the attribute to insert. Ownership of this value is assumed by the list.

pango_attr_list_insert_before ()

void        pango_attr_list_insert_before   (PangoAttrList *list,
                                             PangoAttribute *attr);

Insert the given attribute into the PangoAttrList. It will be inserted before all other attributes with a matching start_index.

list : | a PangoAttrList
attr : | the attribute to insert. Ownership of this value is assumed by the list.

pango_attr_list_change ()

void        pango_attr_list_change          (PangoAttrList *list,
                                             PangoAttribute *attr);

Insert the given attribute into the PangoAttrList. It will replace any attributes of the same type on that segment and be merged with any adjoining attributes that are identical.

This function is slower than pango_attr_list_insert() for creating a attribute list in order (potentially much slower for large lists). However, pango_attr_list_insert() is not suitable for continually changing a set of attributes since it never removes or combines existing attributes.

list : | a PangoAttrList
attr : | the attribute to insert. Ownership of this value is assumed by the list.

pango_attr_list_splice ()

void        pango_attr_list_splice          (PangoAttrList *list,
                                             PangoAttrList *other,
                                             gint pos,
                                             gint len);

This function opens up a hole in list, fills it in with attributes from the left, and then merges other on top of the hole.

This operation is equivalent to stretching every attribute that applies at position pos in list by an amount len, and then calling pango_attr_list_change() with a copy of each attribute in other in sequence (offset in position by pos).

This operation proves useful for, for instance, inserting a pre-edit string in the middle of an edit buffer.

list : | a PangoAttrList
other : | another PangoAttrList
pos : | the position in list at which to insert other
len : | the length of the spliced segment. (Note that this must be specified since the attributes in other may only be present at some subsection of this range)

pango_attr_list_filter ()

PangoAttrList* pango_attr_list_filter       (PangoAttrList *list,
                                             PangoAttrFilterFunc func,
                                             gpointer data);

Given a PangoAttrList and callback function, removes any elements of list for which func returns TRUE and inserts them into a new list.

list : | a PangoAttrList
func : | callback function; returns TRUE if an attribute should be filtered out.
data : | Data to be passed to func
Returns : | the new PangoAttrList or NULL if no attributes of the given types were found.

Since 1.2

PangoAttrFilterFunc ()

gboolean    (*PangoAttrFilterFunc)          (PangoAttribute *attribute,
                                             gpointer data);

A predicate function used by pango_attr_list_filter() to filter out a subset of attributes for a list.

attribute : | a PangoAttribute
data : | callback data passed to pango_attr_list_filter()
Returns : | TRUE if the attribute should be filtered out

pango_attr_list_get_iterator ()

PangoAttrIterator* pango_attr_list_get_iterator
                                            (PangoAttrList *list);

Create a iterator initialized to the beginning of the list. list must not be modified until this iterator is freed.

list : | a PangoAttrList
Returns : | the newly allocated PangoAttrIterator, which should be freed with pango_attr_iterator_destroy().

PangoAttrIterator

typedef struct _PangoAttrIterator PangoAttrIterator;

The PangoAttrIterator structure is used to represent an iterator through a PangoAttrList. A new iterator is created with pango_attr_list_get_iterator(). Once the iterator is created, it can be advanced through the style changes in the text using pango_attr_iterator_next(). At each style change, the range of the current style segment and the attributes currently in effect can be queried.

pango_attr_iterator_copy ()

PangoAttrIterator* pango_attr_iterator_copy (PangoAttrIterator *iterator);

Copy a PangoAttrIterator

iterator : | a PangoAttrIterator.
Returns : | the newly allocated PangoAttrIterator, which should be freed with pango_attr_iterator_destroy().

pango_attr_iterator_next ()

gboolean    pango_attr_iterator_next        (PangoAttrIterator *iterator);

Advance the iterator until the next change of style.

iterator : | a PangoAttrIterator
Returns : | FALSE if the iterator is at the end of the list, otherwise TRUE

pango_attr_iterator_range ()

void        pango_attr_iterator_range       (PangoAttrIterator *iterator,
                                             gint *start,
                                             gint *end);

Get the range of the current segment. Note that the stored return values are signed, not unsigned like the values in PangoAttribute. To deal with this API oversight, stored return values that wouldn't fit into a signed integer are clamped to G_MAXINT.

iterator : | a PangoAttrIterator
start : | location to store the start of the range
end : | location to store the end of the range

pango_attr_iterator_get ()

PangoAttribute* pango_attr_iterator_get     (PangoAttrIterator *iterator,
                                             PangoAttrType type);

Find the current attribute of a particular type at the iterator location. When multiple attributes of the same type overlap, the attribute whose range starts closest to the current location is used.

iterator : | a PangoAttrIterator
type : | the type of attribute to find.
Returns : | the current attribute of the given type, or NULL if no attribute of that type applies to the current location.

pango_attr_iterator_get_font ()

void        pango_attr_iterator_get_font    (PangoAttrIterator *iterator,
                                             PangoFontDescription *desc,
                                             PangoLanguage **language,
                                             GSList **extra_attrs);

Get the font and other attributes at the current iterator position.

iterator : | a PangoAttrIterator
desc : | a PangoFontDescription to fill in with the current values. The family name in this structure will be set using pango_font_description_set_family_static() using values from an attribute in the PangoAttrList associated with the iterator, so if you plan to keep it around, you must call: pango_font_description_set_family (desc, pango_font_description_get_family (desc)).
language : | if non-NULL, location to store language tag for item, or NULL if none is found.
extra_attrs : | if non-NULL, location in which to store a list of non-font attributes at the the current position; only the highest priority value of each attribute will be added to this list. In order to free this value, you must call pango_attribute_destroy() on each member.

pango_attr_iterator_get_attrs ()

GSList*     pango_attr_iterator_get_attrs   (PangoAttrIterator *iterator);

Gets a list of all attributes at the current position of the iterator.

iterator : | a PangoAttrIterator
Returns : | a list of all attributes for the current range. To free this value, call pango_attribute_destroy() on each value and g_slist_free() on the list.

Since 1.2

pango_attr_iterator_destroy ()

void        pango_attr_iterator_destroy     (PangoAttrIterator *iterator);

Destroy a PangoAttrIterator and free all associated memory.

iterator : a PangoAttrIterator.


Rendering

Rendering — Functions to run the rendering pipeline

Synopsis

            PangoContext;
            PangoItem;
            PangoAnalysis;
#define     PANGO_ANALYSIS_FLAG_CENTERED_BASELINE
enum        PangoDirection;
#define     PANGO_TYPE_DIRECTION

GList*      pango_itemize                   (PangoContext *context,
                                             const char *text,
                                             int start_index,
                                             int length,
                                             PangoAttrList *attrs,
                                             PangoAttrIterator *cached_iter);
GList*      pango_itemize_with_base_dir     (PangoContext *context,
                                             PangoDirection base_dir,
                                             const char *text,
                                             int start_index,
                                             int length,
                                             PangoAttrList *attrs,
                                             PangoAttrIterator *cached_iter);
void        pango_item_free                 (PangoItem *item);
PangoItem*  pango_item_copy                 (PangoItem *item);
PangoItem*  pango_item_new                  (void);
PangoItem*  pango_item_split                (PangoItem *orig,
                                             int split_index,
                                             int split_offset);
GList*      pango_reorder_items             (GList *logical_items);

PangoContext* pango_context_new             (void);
void        pango_context_set_font_map      (PangoContext *context,
                                             PangoFontMap *font_map);
PangoFontMap* pango_context_get_font_map    (PangoContext *context);
PangoFontDescription* pango_context_get_font_description
                                            (PangoContext *context);
void        pango_context_set_font_description
                                            (PangoContext *context,
                                             const PangoFontDescription *desc);
PangoLanguage* pango_context_get_language   (PangoContext *context);
void        pango_context_set_language      (PangoContext *context,
                                             PangoLanguage *language);
PangoDirection pango_context_get_base_dir   (PangoContext *context);
void        pango_context_set_base_dir      (PangoContext *context,
                                             PangoDirection direction);
PangoGravity pango_context_get_base_gravity (PangoContext *context);
void        pango_context_set_base_gravity  (PangoContext *context,
                                             PangoGravity gravity);
PangoGravity pango_context_get_gravity      (PangoContext *context);
PangoGravityHint pango_context_get_gravity_hint
                                            (PangoContext *context);
void        pango_context_set_gravity_hint  (PangoContext *context,
                                             PangoGravityHint hint);
const PangoMatrix* pango_context_get_matrix (PangoContext *context);
void        pango_context_set_matrix        (PangoContext *context,
                                             const PangoMatrix *matrix);
PangoFont*  pango_context_load_font         (PangoContext *context,
                                             const PangoFontDescription *desc);
PangoFontset* pango_context_load_fontset    (PangoContext *context,
                                             const PangoFontDescription *desc,
                                             PangoLanguage *language);
PangoFontMetrics* pango_context_get_metrics (PangoContext *context,
                                             const PangoFontDescription *desc,
                                             PangoLanguage *language);
void        pango_context_list_families     (PangoContext *context,
                                             PangoFontFamily ***families,
                                             int *n_families);

gboolean    pango_get_mirror_char           (gunichar ch,
                                             gunichar *mirrored_ch);
PangoDirection pango_unichar_direction      (gunichar ch);
PangoDirection pango_find_base_dir          (const gchar *text,
                                             gint length);
double      pango_gravity_to_rotation       (PangoGravity gravity);

void        pango_break                     (const gchar *text,
                                             int length,
                                             PangoAnalysis *analysis,
                                             PangoLogAttr *attrs,
                                             int attrs_len);
void        pango_get_log_attrs             (const char *text,
                                             int length,
                                             int level,
                                             PangoLanguage *language,
                                             PangoLogAttr *log_attrs,
                                             int attrs_len);
void        pango_find_paragraph_boundary   (const gchar *text,
                                             gint length,
                                             gint *paragraph_delimiter_index,
                                             gint *next_paragraph_start);
void        pango_default_break             (const gchar *text,
                                             int length,
                                             PangoAnalysis *analysis,
                                             PangoLogAttr *attrs,
                                             int attrs_len);
            PangoLogAttr;

void        pango_shape                     (const gchar *text,
                                             gint length,
                                             const PangoAnalysis *analysis,
                                             PangoGlyphString *glyphs);

Object Hierarchy

  GObject
   +----PangoContext

Description

The Pango rendering pipeline takes a string of Unicode characters and converts it into glyphs. The functions described in this section accomplish various steps of this process.

Details

PangoContext

typedef struct _PangoContext PangoContext;

The PangoContext structure stores global information used to control the itemization process.

PangoItem

typedef struct {
  gint offset;
  gint length;
  gint num_chars;
  PangoAnalysis analysis;
} PangoItem;

The PangoItem structure stores information about a segment of text. It contains the following fields:

gint offset; | the offset of the segment from the beginning of the string in bytes.
gint length; | the length of the segment in bytes.
gint num_chars; | the length of the segment in characters.
PangoAnalysis analysis; | the properties of the segment.

PangoAnalysis

typedef struct {
  PangoEngineShape *shape_engine;
  PangoEngineLang  *lang_engine;
  PangoFont *font;

  guint8 level;
  guint8 gravity; /* PangoGravity */
  guint8 flags;

  PangoLanguage *language;
  GSList *extra_attrs;
} PangoAnalysis;

The PangoAnalysis structure stores information about the properties of a segment of text. It has the following fields:

PangoEngineShape *shape_engine; | the engine for doing rendering-system-dependent processing.
PangoEngineLang *lang_engine; | the engine for doing rendering-system-independent processing.
PangoFont *font; | the font for this segment.
guint8 level; | the bidirectional level for this segment.
guint8 gravity; | the glyph orientation for this segment.
guint8 flags; | boolean flags for this segment (currently only one) (Since: 1.16).
PangoLanguage *language; | the detected language for this segment.
GSList *extra_attrs; | extra attributes for this segment.

PANGO_ANALYSIS_FLAG_CENTERED_BASELINE

#define PANGO_ANALYSIS_FLAG_CENTERED_BASELINE (1 << 0)

Whether the segment should be shifted to center around the baseline. Used in vertical writing directions mostly. Since: 1.16

enum PangoDirection

typedef enum {
  PANGO_DIRECTION_LTR,
  PANGO_DIRECTION_RTL,
  PANGO_DIRECTION_TTB_LTR,
  PANGO_DIRECTION_TTB_RTL,
  PANGO_DIRECTION_WEAK_LTR,
  PANGO_DIRECTION_WEAK_RTL,
  PANGO_DIRECTION_NEUTRAL
} PangoDirection;

The PangoDirection type represents a direction in the Unicode bidirectional algorithm; not every value in this enumeration makes sense for every usage of PangoDirection; for example, the return value of pango_unichar_direction() and pango_find_base_dir() cannot be PANGO_DIRECTION_WEAK_LTR or PANGO_DIRECTION_WEAK_RTL, since every character is either neutral or has a strong direction; on the other hand PANGO_DIRECTION_NEUTRAL doesn't make sense to pass to pango_itemize_with_base_dir().

The PANGO_DIRECTION_TTB_LTR, PANGO_DIRECTION_TTB_RTL values come from an earlier interpretation of this enumeration as the writing direction of a block of text and are no longer used; See PangoGravity for how vertical text is handled in Pango.

PANGO_DIRECTION_LTR | A strong left-to-right direction
PANGO_DIRECTION_RTL | A strong right-to-left direction
PANGO_DIRECTION_TTB_LTR | Deprecated value; treated the same as PANGO_DIRECTION_RTL.
PANGO_DIRECTION_TTB_RTL | Deprecated value; treated the same as PANGO_DIRECTION_LTR
PANGO_DIRECTION_WEAK_LTR | A weak left-to-right direction
PANGO_DIRECTION_WEAK_RTL | A weak right-to-left direction
PANGO_DIRECTION_NEUTRAL | No direction specified

PANGO_TYPE_DIRECTION

#define PANGO_TYPE_DIRECTION (pango_direction_get_type())

The GObject type for PangoDirection.

pango_itemize ()

GList*      pango_itemize                   (PangoContext *context,
                                             const char *text,
                                             int start_index,
                                             int length,
                                             PangoAttrList *attrs,
                                             PangoAttrIterator *cached_iter);

Breaks a piece of text into segments with consistent directional level and shaping engine. Each byte of text will be contained in exactly one of the items in the returned list; the generated list of items will be in logical order (the start offsets of the items are ascending).

cached_iter should be an iterator over attrs currently positioned at a range before or containing start_index; cached_iter will be advanced to the range covering the position just after start_index + length. (i.e. if itemizing in a loop, just keep passing in the same cached_iter).

context : | a structure holding information that affects the itemization process.
text : | the text to itemize.
start_index : | first byte in text to process
length : | the number of bytes (not characters) to process after start_index. This must be >= 0.
attrs : | the set of attributes that apply to text.
cached_iter : | Cached attribute iterator, or NULL
Returns : | a GList of PangoItem structures.

pango_itemize_with_base_dir ()

GList*      pango_itemize_with_base_dir     (PangoContext *context,
                                             PangoDirection base_dir,
                                             const char *text,
                                             int start_index,
                                             int length,
                                             PangoAttrList *attrs,
                                             PangoAttrIterator *cached_iter);

Like pango_itemize(), but the base direction to use when computing bidirectional levels (see pango_context_set_base_dir()), is specified explicitly rather than gotten from the PangoContext.

context : | a structure holding information that affects the itemization process.
base_dir : | base direction to use for bidirectional processing
text : | the text to itemize.
start_index : | first byte in text to process
length : | the number of bytes (not characters) to process after start_index. This must be >= 0.
attrs : | the set of attributes that apply to text.
cached_iter : | Cached attribute iterator, or NULL
Returns : | a GList of PangoItem structures.

Since 1.4

pango_item_free ()

void        pango_item_free                 (PangoItem *item);

Free a PangoItem and all associated memory.

item : a PangoItem

pango_item_copy ()

PangoItem*  pango_item_copy                 (PangoItem *item);

Copy an existing PangoItem structure.

item : | a PangoItem
Returns : | the newly allocated PangoItem, which should be freed with pango_item_free().

pango_item_new ()

PangoItem*  pango_item_new                  (void);

Creates a new PangoItem structure initialized to default values.

Returns : the newly allocated PangoItem, which should be freed with pango_item_free().

pango_item_split ()

PangoItem*  pango_item_split                (PangoItem *orig,
                                             int split_index,
                                             int split_offset);

Modifies orig to cover only the text after split_index, and returns a new item that covers the text before split_index that used to be in orig. You can think of split_index as the length of the returned item. split_index may not be 0, and it may not be greater than or equal to the length of orig (that is, there must be at least one byte assigned to each item, you can't create a zero-length item). split_offset is the length of the first item in chars, and must be provided because the text used to generate the item isn't available, so pango_item_split() can't count the char length of the split items itself.

orig : | a PangoItem
split_index : | byte index of position to split item, relative to the start of the item
split_offset : | number of chars between start of orig and split_index
Returns : | new item representing text before split_index, which should be freed with pango_item_free().

pango_reorder_items ()

GList*      pango_reorder_items             (GList *logical_items);

From a list of items in logical order and the associated directional levels, produce a list in visual order. The original list is unmodified.

logical_items : | a GList of PangoItem in logical order.
Returns : | a GList of PangoItem structures in visual order. (Please open a bug if you use this function. It is not a particularly convenient interface, and the code is duplicated elsewhere in Pango for that reason.)

pango_context_new ()

PangoContext* pango_context_new             (void);

Creates a new PangoContext initialized to default value.

This function is only useful when implementing a new backend for Pango, something applications won't do. You should use the context creation function for the backend you are using, for example, pango_cairo_font_map_create_context(), pango_xft_get_context(), pango_win32_get_context() or, pango_ft2_font_map_create_context().

If you are using Pango as part of a higher-level system, that system may have it's own ways of create a PangoContext. For instance, the GTK+ toolkit has, among others, gdk_pango_context_get_for_screen(), and gtk_widget_get_pango_context().

Returns : the newly allocated PangoContext, which should be freed with g_object_unref().

pango_context_set_font_map ()

void        pango_context_set_font_map      (PangoContext *context,
                                             PangoFontMap *font_map);

Sets the font map to be searched when fonts are looked-up in this context. This is only for internal use by Pango backends, a PangoContext obtained via one of the recommended methods should already have a suitable font map.

context : | a PangoContext
font_map : | the PangoFontMap to set.

pango_context_get_font_map ()

PangoFontMap* pango_context_get_font_map    (PangoContext *context);

Gets the PangoFontmap used to look up fonts for this context.

context : | a PangoContext
Returns : | the font map for the PangoContext. This value is owned by Pango and should not be unreferenced.

Since 1.6

pango_context_get_font_description ()

PangoFontDescription* pango_context_get_font_description
                                            (PangoContext *context);

Retrieve the default font description for the context.

context : | a PangoContext
Returns : | a pointer to the context's default font description. This value must not be modified or freed.

pango_context_set_font_description ()

void        pango_context_set_font_description
                                            (PangoContext *context,
                                             const PangoFontDescription *desc);

Set the default font description for the context

context : | a PangoContext
desc : | the new pango font description

pango_context_get_language ()

PangoLanguage* pango_context_get_language   (PangoContext *context);

Retrieves the global language tag for the context.

context : | a PangoContext
Returns : | the global language tag.

pango_context_set_language ()

void        pango_context_set_language      (PangoContext *context,
                                             PangoLanguage *language);

Sets the global language tag for the context. The default language for the locale of the running process can be found using pango_language_get_default().

context : | a PangoContext
language : | the new language tag.

pango_context_get_base_dir ()

PangoDirection pango_context_get_base_dir   (PangoContext *context);

Retrieves the base direction for the context. See pango_context_set_base_dir().

context : | a PangoContext
Returns : | the base direction for the context.

pango_context_set_base_dir ()

void        pango_context_set_base_dir      (PangoContext *context,
                                             PangoDirection direction);

Sets the base direction for the context.

The base direction is used in applying the Unicode bidirectional algorithm; if the direction is PANGO_DIRECTION_LTR or PANGO_DIRECTION_RTL, then the value will be used as the paragraph direction in the Unicode bidirectional algorithm. A value of PANGO_DIRECTION_WEAK_LTR or PANGO_DIRECTION_WEAK_RTL is used only for paragraphs that do not contain any strong characters themselves.

context : | a PangoContext
direction : | the new base direction

pango_context_get_base_gravity ()

PangoGravity pango_context_get_base_gravity (PangoContext *context);

Retrieves the base gravity for the context. See pango_context_set_base_gravity().

context : | a PangoContext
Returns : | the base gravity for the context.

Since 1.16

pango_context_set_base_gravity ()

void        pango_context_set_base_gravity  (PangoContext *context,
                                             PangoGravity gravity);

Sets the base gravity for the context.

The base gravity is used in laying vertical text out.

context : | a PangoContext
gravity : | the new base gravity

Since 1.16

pango_context_get_gravity ()

PangoGravity pango_context_get_gravity      (PangoContext *context);

Retrieves the gravity for the context. This is similar to pango_context_get_base_gravity(), except for when the base gravity is PANGO_GRAVITY_AUTO for which pango_gravity_get_for_matrix() is used to return the gravity from the current context matrix.

context : | a PangoContext
Returns : | the resolved gravity for the context.

Since 1.16

pango_context_get_gravity_hint ()

PangoGravityHint pango_context_get_gravity_hint
                                            (PangoContext *context);

Retrieves the gravity hint for the context. See pango_context_set_gravity_hint() for details.

context : | a PangoContext
Returns : | the gravity hint for the context.

Since 1.16

pango_context_set_gravity_hint ()

void        pango_context_set_gravity_hint  (PangoContext *context,
                                             PangoGravityHint hint);

Sets the gravity hint for the context.

The gravity hint is used in laying vertical text out, and is only relevant if gravity of the context as returned by pango_context_get_gravity() is set PANGO_GRAVITY_EAST or PANGO_GRAVITY_WEST.

context : | a PangoContext
hint : | the new gravity hint

Since 1.16

pango_context_get_matrix ()

const PangoMatrix* pango_context_get_matrix (PangoContext *context);

Gets the transformation matrix that will be applied when rendering with this context. See pango_context_set_matrix().

context : | a PangoContext
Returns : | the matrix, or NULL if no matrix has been set (which is the same as the identity matrix). The returned matrix is owned by Pango and must not be modified or freed.

Since 1.6

pango_context_set_matrix ()

void        pango_context_set_matrix        (PangoContext *context,
                                             const PangoMatrix *matrix);

Sets the transformation matrix that will be applied when rendering with this context. Note that reported metrics are in the user space coordinates before the application of the matrix, not device-space coordinates after the application of the matrix. So, they don't scale with the matrix, though they may change slightly for different matrices, depending on how the text is fit to the pixel grid.

context : | a PangoContext
matrix : | a PangoMatrix, or NULL to unset any existing matrix. (No matrix set is the same as setting the identity matrix.)

Since 1.6

pango_context_load_font ()

PangoFont*  pango_context_load_font         (PangoContext *context,
                                             const PangoFontDescription *desc);

Loads the font in one of the fontmaps in the context that is the closest match for desc.

context : | a PangoContext
desc : | a PangoFontDescription describing the font to load
Returns : | the font loaded, or NULL if no font matched.

pango_context_load_fontset ()

PangoFontset* pango_context_load_fontset    (PangoContext *context,
                                             const PangoFontDescription *desc,
                                             PangoLanguage *language);

Load a set of fonts in the context that can be used to render a font matching desc.

context : | a PangoContext
desc : | a PangoFontDescription describing the fonts to load
language : | a PangoLanguage the fonts will be used for
Returns : | the fontset, or NULL if no font matched.

pango_context_get_metrics ()

PangoFontMetrics* pango_context_get_metrics (PangoContext *context,
                                             const PangoFontDescription *desc,
                                             PangoLanguage *language);

Get overall metric information for a particular font description. Since the metrics may be substantially different for different scripts, a language tag can be provided to indicate that the metrics should be retrieved that correspond to the script(s) used by that language.

The PangoFontDescription is interpreted in the same way as by pango_itemize(), and the family name may be a comma separated list of figures. If characters from multiple of these families would be used to render the string, then the returned fonts would be a composite of the metrics for the fonts loaded for the individual families.

context : | a PangoContext
desc : | a PangoFontDescription structure
language : | language tag used to determine which script to get the metrics for. NULL means that the language tag from the context will be used. If no language tag is set on the context, metrics large enough to cover a range of languages will be returned. The process of determining such metrics is slow, so it is best to always make sure some real language tag will be used.
Returns : | a PangoFontMetrics object. The caller must call pango_font_metrics_unref() when finished using the object.

pango_context_list_families ()

void        pango_context_list_families     (PangoContext *context,
                                             PangoFontFamily ***families,
                                             int *n_families);

List all families for a context.

context : | a PangoContext
families : | location to store a pointer to an array of PangoFontFamily *. This array should be freed with g_free().
n_families : | location to store the number of elements in descs

pango_get_mirror_char ()

gboolean    pango_get_mirror_char           (gunichar ch,
                                             gunichar *mirrored_ch);

Warning

pango_get_mirror_char is deprecated and should not be used in newly-written code.

If ch has the Unicode mirrored property and there is another Unicode character that typically has a glyph that is the mirror image of ch's glyph, puts that character in the address pointed to by mirrored_ch.

Use g_unichar_get_mirror_char() instead; the docs for that function provide full details.

ch : | a Unicode character
mirrored_ch : | location to store the mirrored character
Returns : | TRUE if ch has a mirrored character and mirrored_ch is filled in, FALSE otherwise

pango_unichar_direction ()

PangoDirection pango_unichar_direction      (gunichar ch);

Determines the direction of a character; either PANGO_DIRECTION_LTR, PANGO_DIRECTION_RTL, or PANGO_DIRECTION_NEUTRAL.

ch : | a Unicode character
Returns : | the direction of the character, as used in the Unicode bidirectional algorithm.

pango_find_base_dir ()

PangoDirection pango_find_base_dir          (const gchar *text,
                                             gint length);

Searches a string the first character that has a strong direction, according to the Unicode bidirectional algorithm.

text : | the text to process
length : | length of text in bytes (may be -1 if text is nul-terminated)
Returns : | The direction corresponding to the first strong character. If no such character is found, then PANGO_DIRECTION_NEUTRAL is returned.

Since 1.4

pango_gravity_to_rotation ()

double      pango_gravity_to_rotation       (PangoGravity gravity);

Converts a PangoGravity value to its rotation value. gravity should not be PANGO_GRAVITY_AUTO.

gravity : | gravity to query
Returns : | the rotation value corresponding to gravity.

Since 1.16

pango_break ()

void        pango_break                     (const gchar *text,
                                             int length,
                                             PangoAnalysis *analysis,
                                             PangoLogAttr *attrs,
                                             int attrs_len);

Determines possible line, word, and character breaks for a string of Unicode text with a single analysis. For most purposes you may want to use pango_get_log_attrs().

text : | the text to process
length : | length of text in bytes (may be -1 if text is nul-terminated)
analysis : | PangoAnalysis structure from pango_itemize()
attrs : | an array to store character information in
attrs_len : | size of the array passed as attrs

pango_get_log_attrs ()

void        pango_get_log_attrs             (const char *text,
                                             int length,
                                             int level,
                                             PangoLanguage *language,
                                             PangoLogAttr *log_attrs,
                                             int attrs_len);

Computes a PangoLogAttr for each character in text. The log_attrs array must have one PangoLogAttr for each position in text; if text contains N characters, it has N+1 positions, including the last position at the end of the text. text should be an entire paragraph; logical attributes can't be computed without context (for example you need to see spaces on either side of a word to know the word is a word).

text : | text to process
length : | length in bytes of text
level : | embedding level, or -1 if unknown
language : | language tag
log_attrs : | array with one PangoLogAttr per character in text, plus one extra, to be filled in
attrs_len : | length of log_attrs array

pango_find_paragraph_boundary ()

void        pango_find_paragraph_boundary   (const gchar *text,
                                             gint length,
                                             gint *paragraph_delimiter_index,
                                             gint *next_paragraph_start);

Locates a paragraph boundary in text. A boundary is caused by delimiter characters, such as a newline, carriage return, carriage return-newline pair, or Unicode paragraph separator character. The index of the run of delimiters is returned in paragraph_delimiter_index. The index of the start of the paragraph (index after all delimiters) is stored in next_paragraph_start.

If no delimiters are found, both paragraph_delimiter_index and next_paragraph_start are filled with the length of text (an index one off the end).

text : | UTF-8 text
length : | length of text in bytes, or -1 if nul-terminated
paragraph_delimiter_index : | return location for index of delimiter
next_paragraph_start : | return location for start of next paragraph

pango_default_break ()

void        pango_default_break             (const gchar *text,
                                             int length,
                                             PangoAnalysis *analysis,
                                             PangoLogAttr *attrs,
                                             int attrs_len);

This is the default break algorithm, used if no language engine overrides it. Normally you should use pango_break() instead. Unlike pango_break(), analysis can be NULL, but only do that if you know what you're doing. If you need an analysis to pass to pango_break(), you need to pango_itemize(). In most cases however you should simply use pango_get_log_attrs().

text : | text to break
length : | length of text in bytes (may be -1 if text is nul-terminated)
analysis : | a PangoAnalysis for the text
attrs : | logical attributes to fill in
attrs_len : | size of the array passed as attrs

PangoLogAttr

typedef struct {
  guint is_line_break : 1;      /* Can break line in front of character */

  guint is_mandatory_break : 1; /* Must break line in front of character */

  guint is_char_break : 1;      /* Can break here when doing char wrap */

  guint is_white : 1;           /* Whitespace character */

  /* cursor can appear in front of character (i.e. this is a grapheme
   * boundary, or the first character in the text)
   */
  guint is_cursor_position : 1;

  /* Note that in degenerate cases, you could have both start/end set on
   * some text, most likely for sentences (e.g. no space after a period, so
   * the next sentence starts right away)
   */

  guint is_word_start : 1;      /* first character in a word */
  guint is_word_end   : 1;      /* is first non-word char after a word */

  /* There are two ways to divide sentences. The first assigns all
   * intersentence whitespace/control/format chars to some sentence,
   * so all chars are in some sentence; is_sentence_boundary denotes
   * the boundaries there. The second way doesn't assign
   * between-sentence spaces, etc. to any sentence, so
   * is_sentence_start/is_sentence_end mark the boundaries of those
   * sentences.
   */
  guint is_sentence_boundary : 1;
  guint is_sentence_start : 1;  /* first character in a sentence */
  guint is_sentence_end : 1;    /* first non-sentence char after a sentence */

  /* if set, backspace deletes one character rather than
   * the entire grapheme cluster
   */
  guint backspace_deletes_character : 1;
} PangoLogAttr;

The PangoLogAttr structure stores information about the attributes of a single character.

guint is_line_break : 1; | if set, can break line in front of character
guint is_mandatory_break : 1; | if set, must break line in front of character
guint is_char_break : 1; | if set, can break here when doing character wrapping
guint is_white : 1; | is whitespace character
guint is_cursor_position : 1; | if set, cursor can appear in front of character. i.e. this is a grapheme boundary, or the first character in the text.
guint is_word_start : 1; | is first character in a word
guint is_word_end : 1; | is first non-word char after a word Note that in degenerate cases, you could have both is_word_start and is_word_end set for some character.
guint is_sentence_boundary : 1; | is a sentence boundary. There are two ways to divide sentences. The first assigns all inter-sentence whitespace/control/format chars to some sentence, so all chars are in some sentence; is_sentence_boundary denotes the boundaries there. The second way doesn't assign between-sentence spaces, etc. to any sentence, so is_sentence_start/is_sentence_end mark the boundaries of those sentences.
guint is_sentence_start : 1; | is first character in a sentence
guint is_sentence_end : 1; | is first char after a sentence. Note that in degenerate cases, you could have both is_sentence_start and is_sentence_end set for some character. (e.g. no space after a period, so the next sentence starts right away)
guint backspace_deletes_character : 1; | if set, backspace deletes one character rather than the entire grapheme cluster. This field is only meaningful on grapheme boundaries (where is_cursor_position is set). In some languages, the full grapheme (e.g. letter + diacritics) is considered a unit, while in others, each decomposed character in the grapheme is a unit. In the default implementation of pango_break(), this bit is set on all grapheme boundaries except those following Latin, Cyrillic or Greek base characters.

pango_shape ()

void        pango_shape                     (const gchar *text,
                                             gint length,
                                             const PangoAnalysis *analysis,
                                             PangoGlyphString *glyphs);

Given a segment of text and the corresponding PangoAnalysis structure returned from pango_itemize(), convert the characters into glyphs. You may also pass in only a substring of the item from pango_itemize().

text : | the text to process
length : | the length (in bytes) of text
analysis : | PangoAnalysis structure from pango_itemize()
glyphs : | glyph string in which to store results


Version Checking

Version Checking — Tools for checking Pango version at compile- and run-time.

Synopsis

#define     PANGO_VERSION_ENCODE            (major, minor, micro)
#define     PANGO_VERSION
#define     PANGO_VERSION_MAJOR
#define     PANGO_VERSION_MINOR
#define     PANGO_VERSION_MICRO
#define     PANGO_VERSION_STRING
#define     PANGO_VERSION_CHECK             (major,minor,micro)
int         pango_version                   (void);
const char* pango_version_string            (void);
const char* pango_version_check             (int required_major,
                                             int required_minor,
                                             int required_micro);

Description

The capital-letter macros defined here can be used to check the version of Pango at compile-time, and to encode Pango versions into integers. The functions can be used to check the version of the linked Pango library at run-time.

Details

PANGO_VERSION_ENCODE()

#define     PANGO_VERSION_ENCODE(major, minor, micro)

This macro encodes the given Pango version into an integer. The numbers returned by PANGO_VERSION and pango_version() are encoded using this macro. Two encoded version numbers can be compared as integers.

major : | the major component of the version number
minor : | the minor component of the version number
micro : | the micro component of the version number

PANGO_VERSION

#define     PANGO_VERSION

The version of Pango available at compile-time, encoded using PANGO_VERSION_ENCODE().

PANGO_VERSION_MAJOR

#define PANGO_VERSION_MAJOR 1

The major component of the version of Pango available at compile-time.

PANGO_VERSION_MINOR

#define PANGO_VERSION_MINOR 16

The minor component of the version of Pango available at compile-time.

PANGO_VERSION_MICRO

#define PANGO_VERSION_MICRO 0

The micro component of the version of Pango available at compile-time.

PANGO_VERSION_STRING

#define PANGO_VERSION_STRING "1.16.0"

A string literal containing the version of Pango available at compile-time.

PANGO_VERSION_CHECK()

#define     PANGO_VERSION_CHECK(major,minor,micro)

Checks that the version of Pango available at compile-time is not older than the provided version number.

major : | the major component of the version number
minor : | the minor component of the version number
micro : | the micro component of the version number

pango_version ()

int         pango_version                   (void);

This is similar to the macro PANGO_VERSION except that it returns the encoded version of Pango available at run-time, as opposed to the version available at compile-time.

A version number can be encoded into an integer using PANGO_VERSION_ENCODE().

Returns : value: The encoded version of Pango library available at run time.

Since 1.16

pango_version_string ()

const char* pango_version_string            (void);

This is similar to the macro PANGO_VERSION_STRING except that it returns the version of Pango available at run-time, as opposed to the version available at compile-time.

Returns : value: A string containing the version of Pango library available at run time. The returned string is owned by Pango and should not be modified or freed.

Since 1.16

pango_version_check ()

const char* pango_version_check             (int required_major,
                                             int required_minor,
                                             int required_micro);

Checks that the Pango library in use is compatible with the given version. Generally you would pass in the constants PANGO_VERSION_MAJOR, PANGO_VERSION_MINOR, PANGO_VERSION_MICRO as the three arguments to this function; that produces a check that the library in use at run-time is compatible with the version of Pango the application or module was compiled against.

Compatibility is defined by two things: first the version of the running library is newer than the version required_major.required_minor.required_micro. Second the running library must be binary compatible with the version required_major.required_minor.required_micro (same major version.)

For compile-time version checking use PANGO_VERSION_CHECK().

required_major : | the required major version.
required_minor : | the required minor version.
required_micro : | the required major version.
Returns : | NULL if the Pango library is compatible with the given version, or a string describing the version mismatch. The returned string is owned by Pango and should not be modified or freed.

Since 1.16


Vertical Text

Vertical Text — Laying text out in vertical directions

Synopsis

enum        PangoGravity;
#define     PANGO_TYPE_GRAVITY
enum        PangoGravityHint;
#define     PANGO_TYPE_GRAVITY_HINT
#define     PANGO_GRAVITY_IS_VERTICAL       (gravity)
PangoGravity pango_gravity_get_for_matrix   (const PangoMatrix *matrix);
PangoGravity pango_gravity_get_for_script   (PangoScript script,
                                             PangoGravity base_gravity,
                                             PangoGravityHint hint);

Description

Since 1.16, Pango is able to correctly lay vertical text out. In fact, it can set layouts of mixed vertical and non-vertical text. This section describes the types used for setting vertical text parameters.

Details

enum PangoGravity

typedef enum {
  PANGO_GRAVITY_SOUTH,
  PANGO_GRAVITY_EAST,
  PANGO_GRAVITY_NORTH,
  PANGO_GRAVITY_WEST,
  PANGO_GRAVITY_AUTO
} PangoGravity;

The PangoGravity type represents the orientation of glyphs in a segment of text. This is useful when rendering vertical text layouts. In those situations, the layout is rotated using a non-identity PangoMatrix, and then glyph orientation is controlled using PangoGravity. Not every value in this enumeration makes sense for every usage of PangoGravity; for example, PANGO_GRAVITY_AUTO only can be passed to pango_context_set_base_gravity() and can only be returned by pango_context_get_base_gravity().

See also: PangoGravityHint

PANGO_GRAVITY_SOUTH | Glyphs stand upright (default)
PANGO_GRAVITY_EAST | Glyphs are rotated 90 degrees clockwise
PANGO_GRAVITY_NORTH | Glyphs are upside-down
PANGO_GRAVITY_WEST | Glyphs are rotated 90 degrees counter-clockwise
PANGO_GRAVITY_AUTO | Gravity is resolved from the context matrix

Since 1.16

PANGO_TYPE_GRAVITY

#define PANGO_TYPE_GRAVITY (pango_gravity_get_type())

The GObject type for PangoGravity.

enum PangoGravityHint

typedef enum {
  PANGO_GRAVITY_HINT_NATURAL,
  PANGO_GRAVITY_HINT_STRONG,
  PANGO_GRAVITY_HINT_LINE
} PangoGravityHint;

The PangoGravityHint defines how horizontal scripts should behave in a vertical context. That is, English excerpt in a vertical paragraph for example.

See PangoGravity.

PANGO_GRAVITY_HINT_NATURAL | scripts will take their natural gravity based on the base gravity and the script. This is the default.
PANGO_GRAVITY_HINT_STRONG | always use the base gravity set, regardless of the script.
PANGO_GRAVITY_HINT_LINE | for scripts not in their natural direction (eg. Latin in East gravity), choose per-script gravity such that every script respects the line progression. This means, Latin and Arabic will take opposite gravities and both flow top-to-bottom for example.

Since 1.16

PANGO_TYPE_GRAVITY_HINT

#define PANGO_TYPE_GRAVITY_HINT (pango_gravity_hint_get_type())

The GObject type for PangoGravity.

PANGO_GRAVITY_IS_VERTICAL()

#define     PANGO_GRAVITY_IS_VERTICAL(gravity)

Whether a PangoGravity represents vertical writing directions.

gravity : the PangoGravity to check

Since 1.16

pango_gravity_get_for_matrix ()

PangoGravity pango_gravity_get_for_matrix   (const PangoMatrix *matrix);

Finds the gravity that best matches the rotation component in a PangoMatrix.

matrix : | a PangoMatrix
Returns : | the gravity of matrix, which will never be PANGO_GRAVITY_AUTO, or PANGO_GRAVITY_SOUTH if matrix is NULL

Since 1.16

pango_gravity_get_for_script ()

PangoGravity pango_gravity_get_for_script   (PangoScript script,
                                             PangoGravity base_gravity,
                                             PangoGravityHint hint);

Based on the script, base gravity, and hint, returns actual gravity to use in laying out a single PangoItem.

If base_gravity is PANGO_GRAVITY_AUTO, it is first replaced with the preferred gravity of script. To get the preferred gravity of a script, pass PANGO_GRAVITY_AUTO and PANGO_GRAVITY_HINT_STRONG in.

script : | PangoScript to query
base_gravity : | base gravity of the paragraph
hint : | orientation hint
Returns : | resolved gravity suitable to use for a run of text

Since 1.16


Win32 Fonts and Rendering

Win32 Fonts and Rendering — Functions for shape engines to manipulate Win32 fonts

Synopsis

#define     PANGO_RENDER_TYPE_WIN32
PangoContext* pango_win32_get_context       (void);
void        pango_win32_render              (HDC hdc,
                                             PangoFont *font,
                                             PangoGlyphString *glyphs,
                                             gint x,
                                             gint y);
void        pango_win32_render_transformed  (HDC hdc,
                                             const PangoMatrix *matrix,
                                             PangoFont *font,
                                             PangoGlyphString *glyphs,
                                             int x,
                                             int y);
void        pango_win32_render_layout_line  (HDC hdc,
                                             PangoLayoutLine *line,
                                             int x,
                                             int y);
void        pango_win32_render_layout       (HDC hdc,
                                             PangoLayout *layout,
                                             int x,
                                             int y);
PangoGlyph  pango_win32_get_unknown_glyph   (PangoFont *font,
                                             gunichar wc);
gint        pango_win32_font_get_glyph_index
                                            (PangoFont *font,
                                             gunichar wc);
gboolean    pango_win32_font_select_font    (PangoFont *font,
                                             HDC hdc);
void        pango_win32_font_done_font      (PangoFont *font);
double      pango_win32_font_get_metrics_factor
                                            (PangoFont *font);
gboolean    pango_win32_get_debug_flag      (void);
HDC         pango_win32_get_dc              (void);
            PangoWin32FontCache;
PangoWin32FontCache* pango_win32_font_cache_new
                                            (void);
void        pango_win32_font_cache_free     (PangoWin32FontCache *cache);
HFONT       pango_win32_font_cache_load     (PangoWin32FontCache *cache,
                                             const LOGFONT *logfont);
void        pango_win32_font_cache_unload   (PangoWin32FontCache *cache,
                                             HFONT hfont);
PangoFontMap* pango_win32_font_map_for_display
                                            (void);
void        pango_win32_shutdown_display    (void);
PangoWin32FontCache* pango_win32_font_map_get_font_cache
                                            (PangoFontMap *font_map);
LOGFONT*    pango_win32_font_logfont        (PangoFont *font);
PangoFontDescription* pango_win32_font_description_from_logfont
                                            (const LOGFONT *lfp);

Description

The macros and functions in this section are used to access fonts natively on Win32 systems and to render text in conjunction with Win32 APIs.

Details

PANGO_RENDER_TYPE_WIN32

#define PANGO_RENDER_TYPE_WIN32 "PangoRenderWin32"

A string constant identifying the Win32 renderer. The associated quark (see g_quark_from_string()) is used to identify the renderer in pango_find_map().

pango_win32_get_context ()

PangoContext* pango_win32_get_context       (void);

Retrieves a PangoContext appropriate for rendering with Windows fonts.

Returns : the new PangoContext

pango_win32_render ()

void        pango_win32_render              (HDC hdc,
                                             PangoFont *font,
                                             PangoGlyphString *glyphs,
                                             gint x,
                                             gint y);

Render a PangoGlyphString onto a Windows DC

hdc : | the device context
font : | the font in which to draw the string
glyphs : | the glyph string to draw
x : | the x position of start of string (in pixels)
y : | the y position of baseline (in pixels)

pango_win32_render_transformed ()

void        pango_win32_render_transformed  (HDC hdc,
                                             const PangoMatrix *matrix,
                                             PangoFont *font,
                                             PangoGlyphString *glyphs,
                                             int x,
                                             int y);

Renders a PangoGlyphString onto a windows DC, possibly transforming the layed-out coordinates through a transformation matrix. Note that the transformation matrix for font is not changed, so to produce correct rendering results, the font must have been loaded using a PangoContext with an identical transformation matrix to that passed in to this function.

hdc : | a windows device context
matrix : | a PangoMatrix, or NULL to use an identity transformation
font : | the font in which to draw the string
glyphs : | the glyph string to draw
x : | the x position of the start of the string (in Pango units in user space coordinates)
y : | the y position of the baseline (in Pango units in user space coordinates)

pango_win32_render_layout_line ()

void        pango_win32_render_layout_line  (HDC hdc,
                                             PangoLayoutLine *line,
                                             int x,
                                             int y);

Render a PangoLayoutLine onto a device context. For underlining to work property the text alignment of the DC should have TA_BASELINE and TA_LEFT.

hdc : | DC to use for uncolored drawing
line : | a PangoLayoutLine
x : | the x position of start of string (in pixels)
y : | the y position of baseline (in pixels)

pango_win32_render_layout ()

void        pango_win32_render_layout       (HDC hdc,
                                             PangoLayout *layout,
                                             int x,
                                             int y);

Render a PangoLayoutLine onto an X drawable

hdc : | HDC to use for uncolored drawing
layout : | a PangoLayout
x : | the X position of the left of the layout (in pixels)
y : | the Y position of the top of the layout (in pixels)

pango_win32_get_unknown_glyph ()

PangoGlyph  pango_win32_get_unknown_glyph   (PangoFont *font,
                                             gunichar wc);

Warning

pango_win32_get_unknown_glyph is deprecated and should not be used in newly-written code.

Returns the index of a glyph suitable for drawing wc as an unknown character.

Use PANGO_GET_UNKNOWN_GLYPH() instead.

font : | a PangoFont
wc : | the Unicode character for which a glyph is needed.
Returns : | a glyph index into font

pango_win32_font_get_glyph_index ()

gint        pango_win32_font_get_glyph_index
                                            (PangoFont *font,
                                             gunichar wc);

Obtains the index of the glyph for wc in font, or 0, if not covered.

font : | a PangoFont.
wc : | a Unicode character.
Returns : | the glyph index for wc.

pango_win32_font_select_font ()

gboolean    pango_win32_font_select_font    (PangoFont *font,
                                             HDC hdc);

Selects the font into the specified DC and changes the mapping mode and world transformation of the DC appropriately for the font. You may want to surround the use of this function with calls to SaveDC() and RestoreDC(). Call pango_win32_font_done_font() when you are done using the DC to release allocated resources.

See pango_win32_font_get_metrics_factor() for information about converting from the coordinate space used by this function into Pango units.

font : | a PangoFont from the Win32 backend
hdc : | a windows device context
Returns : | TRUE if the operation succeeded.

pango_win32_font_done_font ()

void        pango_win32_font_done_font      (PangoFont *font);

Releases any resources allocated by pango_win32_font_done_font()

font : a PangoFont from the win32 backend

pango_win32_font_get_metrics_factor ()

double      pango_win32_font_get_metrics_factor
                                            (PangoFont *font);

Returns the scale factor from logical units in the coordinate space used by pango_win32_font_select_font() to Pango units in user space.

font : | a PangoFont from the win32 backend
Returns : | factor to multiply logical units by to get Pango units.

pango_win32_get_debug_flag ()

gboolean    pango_win32_get_debug_flag      (void);

Returns whether debugging is turned on.

Returns : TRUE if debugging is turned on.

Since 1.2

pango_win32_get_dc ()

HDC         pango_win32_get_dc              (void);

Obtains a handle to the Windows device context that is used by Pango.

Returns : A handle to the Windows device context that is used by Pango.

PangoWin32FontCache

typedef struct _PangoWin32FontCache PangoWin32FontCache;

A PangoWin32FontCache caches HFONTs by their LOGFONT descriptions.

pango_win32_font_cache_new ()

PangoWin32FontCache* pango_win32_font_cache_new
                                            (void);

Creates a font cache.

Returns : The new font cache. This must be freed with pango_win32_font_cache_free().

pango_win32_font_cache_free ()

void        pango_win32_font_cache_free     (PangoWin32FontCache *cache);

Frees a PangoWin32FontCache and all associated memory. All fonts loaded through this font cache will be freed along with the cache.

cache : a PangoWin32FontCache

pango_win32_font_cache_load ()

HFONT       pango_win32_font_cache_load     (PangoWin32FontCache *cache,
                                             const LOGFONT *logfont);

Creates a HFONT from a LOGFONT. The result may be newly loaded, or it may have been previously stored

cache : | a PangoWin32FontCache
logfont : | a pointer to a LOGFONT structure describing the font to load.
Returns : | The font structure, or NULL if the font could not be loaded. In order to free this structure, you must call pango_win32_font_cache_unload().

pango_win32_font_cache_unload ()

void        pango_win32_font_cache_unload   (PangoWin32FontCache *cache,
                                             HFONT hfont);

Frees a font structure previously loaded with pango_win32_font_cache_load().

cache : | a PangoWin32FontCache
hfont : | the HFONT to unload

pango_win32_font_map_for_display ()

PangoFontMap* pango_win32_font_map_for_display
                                            (void);

Returns a PangoWin32FontMap. Font maps are cached and should not be freed. If the font map is no longer needed, it can be released with pango_win32_shutdown_display().

Returns : a PangoFontMap.

pango_win32_shutdown_display ()

void        pango_win32_shutdown_display    (void);

Free cached resources.

pango_win32_font_map_get_font_cache ()

PangoWin32FontCache* pango_win32_font_map_get_font_cache
                                            (PangoFontMap *font_map);

Obtains the font cache associated with the given font map.

font_map : | a PangoWin32FontMap.
Returns : | the PangoWin32FontCache of font_map.

pango_win32_font_logfont ()

LOGFONT*    pango_win32_font_logfont        (PangoFont *font);

Determine the LOGFONT struct for the specified font.

font : | a PangoFont which must be from the Win32 backend
Returns : | A newly allocated LOGFONT struct. It must be freed with g_free().

pango_win32_font_description_from_logfont ()

PangoFontDescription* pango_win32_font_description_from_logfont
                                            (const LOGFONT *lfp);

Creates a PangoFontDescription that matches the specified LOGFONT.

The face name, italicness and weight fields in the LOGFONT are used to set up the resulting PangoFontDescription. If the face name in the LOGFONT contains non-ASCII characters the font is temporarily loaded (using CreateFontIndirect()) and an ASCII (usually English) name for it is looked up from the font name tables in the font data. If that doesn't work, the face name is converted from the system codepage to UTF-8 and that is used.

lfp : | a LOGFONT
Returns : | the newly allocated PangoFontDescription, which should be freed using pango_font_description_free()

Since 1.12


Deprecated X font backend

Deprecated X font backend — Font handling and rendering with the deprecated X font backend

Synopsis

#define     PANGO_RENDER_TYPE_X
PangoContext* pango_x_get_context           (Display *display);
void        pango_x_context_set_funcs       (PangoContext *context,
                                             PangoGetGCFunc get_gc_func,
                                             PangoFreeGCFunc free_gc_func);
GC          (*PangoGetGCFunc)               (PangoContext *context,
                                             PangoColor *color,
                                             GC base_gc);
void        (*PangoFreeGCFunc)              (PangoContext *context,
                                             GC gc);
void        pango_x_render                  (Display *display,
                                             Drawable d,
                                             GC gc,
                                             PangoFont *font,
                                             PangoGlyphString *glyphs,
                                             gint x,
                                             gint y);
void        pango_x_render_layout_line      (Display *display,
                                             Drawable drawable,
                                             GC gc,
                                             PangoLayoutLine *line,
                                             int x,
                                             int y);
void        pango_x_render_layout           (Display *display,
                                             Drawable drawable,
                                             GC gc,
                                             PangoLayout *layout,
                                             int x,
                                             int y);
typedef     PangoXSubfont;
#define     PANGO_X_MAKE_GLYPH              (subfont,index_)
#define     PANGO_X_GLYPH_SUBFONT           (glyph)
#define     PANGO_X_GLYPH_INDEX             (glyph)
PangoFont*  pango_x_load_font               (Display *display,
                                             const gchar *spec);
PangoGlyph  pango_x_get_unknown_glyph       (PangoFont *font);
gboolean    pango_x_has_glyph               (PangoFont *font,
                                             PangoGlyph glyph);
int         pango_x_list_subfonts           (PangoFont *font,
                                             char **charsets,
                                             int n_charsets,
                                             PangoXSubfont **subfont_ids,
                                             int **subfont_charsets);
PangoFontMap* pango_x_font_map_for_display  (Display *display);
void        pango_x_shutdown_display        (Display *display);
PangoXFontCache* pango_x_font_map_get_font_cache
                                            (PangoFontMap *font_map);
char*       pango_x_font_subfont_xlfd       (PangoFont *font,
                                             PangoXSubfont subfont_id);
gboolean    pango_x_find_first_subfont      (PangoFont *font,
                                             char **charsets,
                                             int n_charsets,
                                             PangoXSubfont *rfont);
PangoGlyph  pango_x_font_get_unknown_glyph  (PangoFont *font,
                                             gunichar wc);
gboolean    pango_x_apply_ligatures         (PangoFont *font,
                                             PangoXSubfont subfont,
                                             gunichar **glyphs,
                                             int *n_glyphs,
                                             int **clusters);
void        pango_x_fallback_shape          (PangoFont *font,
                                             PangoGlyphString *glyphs,
                                             const char *text,
                                             int n_chars);
            PangoXFontCache;
PangoXFontCache* pango_x_font_cache_new     (Display *display);
void        pango_x_font_cache_free         (PangoXFontCache *cache);
XFontStruct* pango_x_font_cache_load        (PangoXFontCache *cache,
                                             const char *xlfd);
void        pango_x_font_cache_unload       (PangoXFontCache *cache,
                                             XFontStruct *fs);

Description

The functions and macros in this section are for use with the old X font backend which used server-side bitmap fonts. This font backend is no longer supported, and attempts to use it will produce unpredictable results. Use the Xft or Cairo backend instead.

Details

PANGO_RENDER_TYPE_X

#define PANGO_RENDER_TYPE_X "PangoRenderX"

Warning

PANGO_RENDER_TYPE_X is deprecated and should not be used in newly-written code.

A string constant identifying the X renderer. The associated quark (see g_quark_from_string()) is used to identify the renderer in pango_find_map().

pango_x_get_context ()

PangoContext* pango_x_get_context           (Display *display);

Warning

pango_x_get_context is deprecated and should not be used in newly-written code.

Retrieves a PangoContext appropriate for rendering with X fonts on the given display.

display : | an X display (As returned by XOpenDisplay().)
Returns : | the new PangoContext.

pango_x_context_set_funcs ()

void        pango_x_context_set_funcs       (PangoContext *context,
                                             PangoGetGCFunc get_gc_func,
                                             PangoFreeGCFunc free_gc_func);

Warning

pango_x_context_set_funcs is deprecated and should not be used in newly-written code.

Sets the functions that will be used to get GC's in various colors when rendering layouts with this context.

context : | a PangoContext.
get_gc_func : | function called to create a new GC for a given color.
free_gc_func : | function called to free a GC created with get_gc_func.

PangoGetGCFunc ()

GC          (*PangoGetGCFunc)               (PangoContext *context,
                                             PangoColor *color,
                                             GC base_gc);

Warning

PangoGetGCFunc is deprecated and should not be used in newly-written code.

Specifies the type of the function used to create a new GC for a given color.

context : | a PangoContext.
color : | the color to create a new GC for.
base_gc : | the GC to base the new GC on.
Returns : | the new GC.

PangoFreeGCFunc ()

void        (*PangoFreeGCFunc)              (PangoContext *context,
                                             GC gc);

Warning

PangoFreeGCFunc is deprecated and should not be used in newly-written code.

Specifies the type of the function used to free a GC created with the corresponding PangoGetGCFunc function.

context : | a PangoContext.
gc : | the GC to free.

pango_x_render ()

void        pango_x_render                  (Display *display,
                                             Drawable d,
                                             GC gc,
                                             PangoFont *font,
                                             PangoGlyphString *glyphs,
                                             gint x,
                                             gint y);

Warning

pango_x_render is deprecated and should not be used in newly-written code.

Renders a PangoGlyphString onto an X drawable.

display : | the X display.
d : | the drawable on which to draw string.
gc : | the graphics context.
font : | the font in which to draw the string.
glyphs : | the glyph string to draw.
x : | the x position of start of string (in pixels).
y : | the y position of baseline (in pixels).

pango_x_render_layout_line ()

void        pango_x_render_layout_line      (Display *display,
                                             Drawable drawable,
                                             GC gc,
                                             PangoLayoutLine *line,
                                             int x,
                                             int y);

Warning

pango_x_render_layout_line is deprecated and should not be used in newly-written code.

Renders a PangoLayoutLine onto an X drawable.

display : | the X display.
drawable : | the drawable on which to draw.
gc : | GC to use for uncolored drawing.
line : | a PangoLayoutLine.
x : | the x position of start of string (in pixels).
y : | the y position of baseline (in pixels).

pango_x_render_layout ()

void        pango_x_render_layout           (Display *display,
                                             Drawable drawable,
                                             GC gc,
                                             PangoLayout *layout,
                                             int x,
                                             int y);

Warning

pango_x_render_layout is deprecated and should not be used in newly-written code.

Renders a PangoLayout onto an X drawable.

display : | the X display.
drawable : | the drawable on which to draw.
gc : | GC to use for uncolored drawing.
layout : | a PangoLayout.
x : | the x position of the left of the layout (in pixels).
y : | the y position of the top of the layout (in pixels).

PangoXSubfont

typedef guint16 PangoXSubfont;

Warning

PangoXSubfont is deprecated and should not be used in newly-written code.

The PangoXSubFont type is an integer ID that identifies one particular X font within the fonts referenced in a PangoFont.

PANGO_X_MAKE_GLYPH()

#define PANGO_X_MAKE_GLYPH(subfont,index_) ((subfont)<<16 | (index_))

Warning

PANGO_X_MAKE_GLYPH is deprecated and should not be used in newly-written code.

Make a glyph index from a PangoXSubFont index and a index of a character with the corresponding X font.

subfont : | a PangoXSubfont index
index_ : | the index of a character within an X font.

PANGO_X_GLYPH_SUBFONT()

#define PANGO_X_GLYPH_SUBFONT(glyph) ((glyph)>>16)

Warning

PANGO_X_GLYPH_SUBFONT is deprecated and should not be used in newly-written code.

Extract the subfont index from a glyph index.

glyph : a PangoGlyphIndex

PANGO_X_GLYPH_INDEX()

#define PANGO_X_GLYPH_INDEX(glyph) ((glyph) & 0xffff)

Warning

PANGO_X_GLYPH_INDEX is deprecated and should not be used in newly-written code.

Extract the character index within the X font from a glyph index.

glyph : a PangoGlyphIndex

pango_x_load_font ()

PangoFont*  pango_x_load_font               (Display *display,
                                             const gchar *spec);

Warning

pango_x_load_font is deprecated and should not be used in newly-written code.

Loads up a logical font based on a "fontset" style text specification. This is not remotely useful (Pango API's generally work in terms of PangoFontDescription) and the result may not work correctly in all circumstances. Use of this function should be avoided.

display : | the X display.
spec : | a comma-separated list of XLFD's.
Returns : | a new PangoFont.

pango_x_get_unknown_glyph ()

PangoGlyph  pango_x_get_unknown_glyph       (PangoFont *font);

Warning

pango_x_get_unknown_glyph is deprecated and should not be used in newly-written code.

Returns the index of a glyph suitable for drawing unknown characters; you should generally use PANGO_GET_UNKNOWN_GLYPH() instead, since that may return a glyph that provides a better representation of a particular char. (E.g., by showing hex digits, or a glyph representative of a certain Unicode range.)

font : | a PangoFont.
Returns : | a glyph index into font.

pango_x_has_glyph ()

gboolean    pango_x_has_glyph               (PangoFont *font,
                                             PangoGlyph glyph);

Warning

pango_x_has_glyph is deprecated and should not be used in newly-written code.

Checks if the given glyph is present in a X font.

font : | a PangoFont which must be from the X backend.
glyph : | the index of a glyph in the font. (Formed using the PANGO_X_MAKE_GLYPH macro)
Returns : | TRUE if the glyph is present.

pango_x_list_subfonts ()

int         pango_x_list_subfonts           (PangoFont *font,
                                             char **charsets,
                                             int n_charsets,
                                             PangoXSubfont **subfont_ids,
                                             int **subfont_charsets);

Warning

pango_x_list_subfonts is deprecated and should not be used in newly-written code.

Lists the subfonts of a given font. The result is ordered first by charset, and then within each charset, by the order of fonts in the font specification.

font : | a PangoFont.
charsets : | the charsets to list subfonts for.
n_charsets : | the number of charsets in charsets.
subfont_ids : | location to store a pointer to an array of subfont IDs for each found subfont; the result must be freed using g_free().
subfont_charsets : | location to store a pointer to an array of subfont IDs for each found subfont; the result must be freed using g_free().
Returns : | length of the arrays stored in subfont_ids and subfont_charsets.

pango_x_font_map_for_display ()

PangoFontMap* pango_x_font_map_for_display  (Display *display);

Warning

pango_x_font_map_for_display is deprecated and should not be used in newly-written code.

Returns a PangoXFontMap for display. Font maps are cached and should not be freed. If the font map for a display is no longer needed, it can be released with pango_x_shutdown_display().

display : | an X Display.
Returns : | a PangoXFontMap for display.

pango_x_shutdown_display ()

void        pango_x_shutdown_display        (Display *display);

Warning

pango_x_shutdown_display is deprecated and should not be used in newly-written code.

Free cached resources for the given X display structure.

display : an X Display

pango_x_font_map_get_font_cache ()

PangoXFontCache* pango_x_font_map_get_font_cache
                                            (PangoFontMap *font_map);

Warning

pango_x_font_map_get_font_cache is deprecated and should not be used in newly-written code.

Obtains the font cache associated with the given font map.

font_map : | a PangoXFontMap.
Returns : | the PangoXFontCache of font_map.

pango_x_font_subfont_xlfd ()

char*       pango_x_font_subfont_xlfd       (PangoFont *font,
                                             PangoXSubfont subfont_id);

Warning

pango_x_font_subfont_xlfd is deprecated and should not be used in newly-written code.

Determines the X Logical Font Description for the specified subfont.

font : | a PangoFont which must be from the X backend.
subfont_id : | the id of a subfont within the font.
Returns : | A newly-allocated string containing the XLFD for the subfont. This string must be freed with g_free().

pango_x_find_first_subfont ()

gboolean    pango_x_find_first_subfont      (PangoFont *font,
                                             char **charsets,
                                             int n_charsets,
                                             PangoXSubfont *rfont);

Warning

pango_x_find_first_subfont is deprecated and should not be used in newly-written code.

Looks for subfonts with the charset charset, in font, and puts the first one in *rfont.

font : | A PangoFont.
charsets : | An array of charsets.
n_charsets : | The number of charsets in charsets.
rfont : | A pointer to a PangoXSubfont.
Returns : | TRUE if *rfont now contains a font.

pango_x_font_get_unknown_glyph ()

PangoGlyph  pango_x_font_get_unknown_glyph  (PangoFont *font,
                                             gunichar wc);

Warning

pango_x_font_get_unknown_glyph is deprecated and should not be used in newly-written code.

Returns the index of a glyph suitable for drawing wc as an unknown character.

Use PANGO_GET_UNKNOWN_GLYPH() instead.

font : | a PangoFont.
wc : | the Unicode character for which a glyph is needed.
Returns : | a glyph index into font.

pango_x_apply_ligatures ()

gboolean    pango_x_apply_ligatures         (PangoFont *font,
                                             PangoXSubfont subfont,
                                             gunichar **glyphs,
                                             int *n_glyphs,
                                             int **clusters);

Warning

pango_x_apply_ligatures is deprecated and should not be used in newly-written code.

Previously did subfont-specific ligation. Now a no-op.

font : | unused
subfont : | unused
glyphs : | unused
n_glyphs : | unused
clusters : | unused
Returns : | FALSE, always.

pango_x_fallback_shape ()

void        pango_x_fallback_shape          (PangoFont *font,
                                             PangoGlyphString *glyphs,
                                             const char *text,
                                             int n_chars);

Warning

pango_x_fallback_shape is deprecated and should not be used in newly-written code.

This is a simple fallback shaper, that can be used if no subfont that supports a given script is found. For every character in text, it puts the unknown glyph.

font : | A PangoFont.
glyphs : | A pointer to a PangoGlyphString.
text : | UTF-8 string.
n_chars : | Number of UTF-8 seqs in text.

PangoXFontCache

typedef struct _PangoXFontCache PangoXFontCache;

Warning

PangoXFontCache is deprecated and should not be used in newly-written code.

A PangoXFontCache caches XFontStructs for a single display by their XLFD name.

pango_x_font_cache_new ()

PangoXFontCache* pango_x_font_cache_new     (Display *display);

Warning

pango_x_font_cache_new is deprecated and should not be used in newly-written code.

Creates a font cache for the specified display.

display : | an X display.
Returns : | The newly allocated PangoXFontCache, which should be freed with pango_x_font_cache_free().

pango_x_font_cache_free ()

void        pango_x_font_cache_free         (PangoXFontCache *cache);

Warning

pango_x_font_cache_free is deprecated and should not be used in newly-written code.

Frees a PangoXFontCache and all associated memory. All fonts loaded through this font cache will be freed along with the cache.

cache : a PangoXFontCache

pango_x_font_cache_load ()

XFontStruct* pango_x_font_cache_load        (PangoXFontCache *cache,
                                             const char *xlfd);

Warning

pango_x_font_cache_load is deprecated and should not be used in newly-written code.

Loads a XFontStruct from a X Logical Font Description. The result may be newly loaded, or it may have been previously stored.

cache : | a PangoXFontCache
xlfd : | the X Logical Font Description to load.
Returns : | The font structure, or NULL if the font could not be loaded. In order to free this structure, you must call pango_x_font_cache_unload().

pango_x_font_cache_unload ()

void        pango_x_font_cache_unload       (PangoXFontCache *cache,
                                             XFontStruct *fs);

Warning

pango_x_font_cache_unload is deprecated and should not be used in newly-written code.

Frees a font structure previously loaded with pango_x_font_cache_load().

cache : | a PangoXFontCache
fs : | the font structure to unload


Xft Fonts and Rendering

Xft Fonts and Rendering — Font handling and rendering with the Xft backend

Synopsis

            PangoXftFont;
            PangoXftFontMap;
#define     PANGO_RENDER_TYPE_XFT
PangoContext* pango_xft_get_context         (Display *display,
                                             int screen);
PangoFontMap* pango_xft_get_font_map        (Display *display,
                                             int screen);
void        pango_xft_set_default_substitute
                                            (Display *display,
                                             int screen,
                                             PangoXftSubstituteFunc func,
                                             gpointer data,
                                             GDestroyNotify notify);
void        (*PangoXftSubstituteFunc)       (FcPattern *pattern,
                                             gpointer data);
void        pango_xft_substitute_changed    (Display *display,
                                             int screen);
void        pango_xft_shutdown_display      (Display *display,
                                             int screen);
XftFont*    pango_xft_font_get_font         (PangoFont *font);
Display*    pango_xft_font_get_display      (PangoFont *font);
gboolean    pango_xft_font_has_char         (PangoFont *font,
                                             gunichar wc);
FT_Face     pango_xft_font_lock_face        (PangoFont *font);
void        pango_xft_font_unlock_face      (PangoFont *font);
guint       pango_xft_font_get_glyph        (PangoFont *font,
                                             gunichar wc);
PangoGlyph  pango_xft_font_get_unknown_glyph
                                            (PangoFont *font,
                                             gunichar wc);
            PangoXftRenderer;
            PangoXftRendererClass;
PangoRenderer* pango_xft_renderer_new       (Display *display,
                                             int screen);
void        pango_xft_renderer_set_draw     (PangoXftRenderer *xftrenderer,
                                             XftDraw *draw);
void        pango_xft_renderer_set_default_color
                                            (PangoXftRenderer *xftrenderer,
                                             PangoColor *default_color);
void        pango_xft_render                (XftDraw *draw,
                                             XftColor *color,
                                             PangoFont *font,
                                             PangoGlyphString *glyphs,
                                             gint x,
                                             gint y);
void        pango_xft_picture_render        (Display *display,
                                             Picture src_picture,
                                             Picture dest_picture,
                                             PangoFont *font,
                                             PangoGlyphString *glyphs,
                                             gint x,
                                             gint y);
void        pango_xft_render_transformed    (XftDraw *draw,
                                             XftColor *color,
                                             PangoMatrix *matrix,
                                             PangoFont *font,
                                             PangoGlyphString *glyphs,
                                             int x,
                                             int y);
void        pango_xft_render_layout_line    (XftDraw *draw,
                                             XftColor *color,
                                             PangoLayoutLine *line,
                                             int x,
                                             int y);
void        pango_xft_render_layout         (XftDraw *draw,
                                             XftColor *color,
                                             PangoLayout *layout,
                                             int x,
                                             int y);

Object Hierarchy

  GObject
   +----PangoFont
         +----PangoFcFont
               +----PangoXftFont

Description

The Xft library is a library for displaying fonts on the X window system; internally it uses the fontconfig library to locate font files, and the FreeType library to load and render fonts. The Xft backend is the recommended Pango font backend for screen display with X. (The Cairo back end is another possibility.)

Using the Xft backend is generally straightforward; pango_xft_get_context() creates a context for a specified display and screen. You can then create a PangoLayout with that context and render it with pango_xft_render_layout(). At a more advanced level, the low-level fontconfig options used for rendering fonts can be affected using pango_xft_set_default_substitute(), and pango_xft_substitute_changed().

A range of functions for drawing pieces of a layout, such as individual layout lines and glyphs strings are provided. You can also directly create a PangoXftRenderer. Finally, in some advanced cases, it is useful to derive from PangoXftRenderer. Deriving from PangoXftRenderer is useful for two reasons. One reason is be to support custom attributes by overriding PangoRendererClass virtual functions like 'prepare_run' or 'draw_shape'. The reason is to customize exactly how the final bits are drawn to the destination by overriding the PangoXftRendererClass virtual functions 'composite_glyphs' and 'composite_trapezoids'.

Details

PangoXftFont

typedef struct _PangoXftFont PangoXftFont;

PangoXftFont is an implementation of PangoFcFont using the Xft library for rendering. It is used in conjunction with PangoXftFontMap.

PangoXftFontMap

typedef struct _PangoXftFontMap PangoXftFontMap;

PangoXftFontMap is an implementation of PangoFcFontMap suitable for the Xft library as the renderer. It is used in to create fonts of type PangoXftFont.

PANGO_RENDER_TYPE_XFT

#define PANGO_RENDER_TYPE_XFT "PangoRenderXft"

Warning

PANGO_RENDER_TYPE_XFT is deprecated and should not be used in newly-written code.

A string constant that was used to identify shape engines that work with the Xft backend. See PANGO_RENDER_TYPE_FC for the replacement.

pango_xft_get_context ()

PangoContext* pango_xft_get_context         (Display *display,
                                             int screen);

Retrieves a PangoContext appropriate for rendering with Xft fonts on the given screen of the given display.

display : | an X display.
screen : | an X screen.
Returns : | the new PangoContext.

pango_xft_get_font_map ()

PangoFontMap* pango_xft_get_font_map        (Display *display,
                                             int screen);

Returns the PangoXftFontmap for the given display and screen. The fontmap is owned by Pango and will be valid until the display is closed.

display : | an X display
screen : | the screen number of a screen within display
Returns : | a PangoFontMap object, owned by Pango.

Since 1.2

pango_xft_set_default_substitute ()

void        pango_xft_set_default_substitute
                                            (Display *display,
                                             int screen,
                                             PangoXftSubstituteFunc func,
                                             gpointer data,
                                             GDestroyNotify notify);

Sets a function that will be called to do final configuration substitution on a FcPattern before it is used to load the font. This function can be used to do things like set hinting and antialiasing options.

display : | an X Display
screen : | the screen number of a screen within display
func : | function to call to to do final config tweaking on FcPattern objects.
data : | data to pass to func
notify : | function to call when data is no longer used.

Since 1.2

PangoXftSubstituteFunc ()

void        (*PangoXftSubstituteFunc)       (FcPattern *pattern,
                                             gpointer data);

Function type for doing final config tweaking on prepared FcPatterns.

pattern : | the FcPattern to tweak.
data : | user data.

pango_xft_substitute_changed ()

void        pango_xft_substitute_changed    (Display *display,
                                             int screen);

Call this function any time the results of the default substitution function set with pango_xft_set_default_substitute() change. That is, if your substitution function will return different results for the same input pattern, you must call this function.

display : | an X Display
screen : | the screen number of a screen within display

Since 1.2

pango_xft_shutdown_display ()

void        pango_xft_shutdown_display      (Display *display,
                                             int screen);

Release any resources that have been cached for the combination of display and screen. Note that when the X display is closed, resources are released automatically, without needing to call this function.

display : | an X display
screen : | the screen number of a screen within display

Since 1.2

pango_xft_font_get_font ()

XftFont*    pango_xft_font_get_font         (PangoFont *font);

Returns the XftFont of a font.

font : | a PangoFont.
Returns : | the XftFont associated to font.

pango_xft_font_get_display ()

Display*    pango_xft_font_get_display      (PangoFont *font);

Returns the X display of the XftFont of a font.

font : | a PangoFont.
Returns : | the X display of the XftFont associated to font.

pango_xft_font_has_char ()

gboolean    pango_xft_font_has_char         (PangoFont *font,
                                             gunichar wc);

Warning

pango_xft_font_has_char is deprecated and should not be used in newly-written code.

Determines whether font has a glyph for the codepoint wc.

Use pango_fc_font_has_char() instead.

font : | a PangoFont for the Xft backend
wc : | Unicode codepoint to look up
Returns : | TRUE if font has the requested codepoint.

Since 1.2

pango_xft_font_lock_face ()

FT_Face     pango_xft_font_lock_face        (PangoFont *font);

Warning

pango_xft_font_lock_face is deprecated and should not be used in newly-written code.

Gets the FreeType FT_Face associated with a font, This face will be kept around until you call pango_xft_font_unlock_face().

Use pango_fc_font_lock_face() instead.

font : | a PangoFont.
Returns : | the FreeType FT_Face associated with font.

Since 1.2

pango_xft_font_unlock_face ()

void        pango_xft_font_unlock_face      (PangoFont *font);

Warning

pango_xft_font_unlock_face is deprecated and should not be used in newly-written code.

Releases a font previously obtained with pango_xft_font_lock_face().

Use pango_fc_font_unlock_face() instead.

font : a PangoFont.

Since 1.2

pango_xft_font_get_glyph ()

guint       pango_xft_font_get_glyph        (PangoFont *font,
                                             gunichar wc);

Warning

pango_xft_font_get_glyph is deprecated and should not be used in newly-written code.

Gets the glyph index for a given Unicode character for font. If you only want to determine whether the font has the glyph, use pango_xft_font_has_char().

Use pango_fc_font_get_glyph() instead.

font : | a PangoFont for the Xft backend
wc : | Unicode codepoint to look up
Returns : | the glyph index, or 0, if the Unicode character does not exist in the font.

Since 1.2

pango_xft_font_get_unknown_glyph ()

PangoGlyph  pango_xft_font_get_unknown_glyph
                                            (PangoFont *font,
                                             gunichar wc);

Warning

pango_xft_font_get_unknown_glyph is deprecated and should not be used in newly-written code.

Returns the index of a glyph suitable for drawing wc as an unknown character.

Use PANGO_GET_UNKNOWN_GLYPH() instead.

font : | a PangoFont.
wc : | the Unicode character for which a glyph is needed.
Returns : | a glyph index into font.

PangoXftRenderer

typedef struct {
} PangoXftRenderer;

PangoXftRenderer is a subclass of PangoRenderer used for rendering with Pango's Xft backend. It can be used directly, or it can be further subclassed to modify exactly how drawing of individual elements occurs.

Since 1.8

PangoXftRendererClass

typedef struct {
  void (*composite_trapezoids) (PangoXftRenderer *xftrenderer,
                PangoRenderPart   part,
                XTrapezoid       *trapezoids,
                int               n_trapezoids);
  void (*composite_glyphs)     (PangoXftRenderer *xftrenderer,
                XftFont          *xft_font,
                XftGlyphSpec     *glyphs,
                int               n_glyphs);
} PangoXftRendererClass;

The class structure for PangoXftRenderer

composite_trapezoids () | draw the specified trapezoids using the current color and other attributes for part
composite_glyphs () | draw the specified glyphs using the current foreground color and other foreground attributes

Since 1.8

pango_xft_renderer_new ()

PangoRenderer* pango_xft_renderer_new       (Display *display,
                                             int screen);

Create a new PangoXftRenderer to allow rendering Pango objects with the Xft library. You must call pango_xft_renderer_set_draw() before using the renderer.

display : | an X display
screen : | the index of the screen for display to which rendering will be done
Returns : | the newly created PangoXftRenderer, which should be freed with g_object_unref().

Since 1.8

pango_xft_renderer_set_draw ()

void        pango_xft_renderer_set_draw     (PangoXftRenderer *xftrenderer,
                                             XftDraw *draw);

Sets the XftDraw object that the renderer is drawing to. The renderer must not be currently active.

xftrenderer : | a PangoXftRenderer
draw : | a XftDraw

Since 1.8

pango_xft_renderer_set_default_color ()

void        pango_xft_renderer_set_default_color
                                            (PangoXftRenderer *xftrenderer,
                                             PangoColor *default_color);

Sets the default foreground color for a XftRenderer.

xftrenderer : | a XftRenderer
default_color : | the default foreground color

Since 1.8

pango_xft_render ()

void        pango_xft_render                (XftDraw *draw,
                                             XftColor *color,
                                             PangoFont *font,
                                             PangoGlyphString *glyphs,
                                             gint x,
                                             gint y);

Renders a PangoGlyphString onto an XftDraw object wrapping an X drawable.

draw : | the XftDraw object.
color : | the color in which to draw the string
font : | the font in which to draw the string
glyphs : | the glyph string to draw
x : | the x position of start of string (in pixels)
y : | the y position of baseline (in pixels)

pango_xft_picture_render ()

void        pango_xft_picture_render        (Display *display,
                                             Picture src_picture,
                                             Picture dest_picture,
                                             PangoFont *font,
                                             PangoGlyphString *glyphs,
                                             gint x,
                                             gint y);

Renders a PangoGlyphString onto an Xrender Picture object.

display : | an X display
src_picture : | the source picture to draw the string with
dest_picture : | the destination picture to draw the string onto
font : | the font in which to draw the string
glyphs : | the glyph string to draw
x : | the x position of start of string (in pixels)
y : | the y position of baseline (in pixels)

pango_xft_render_transformed ()

void        pango_xft_render_transformed    (XftDraw *draw,
                                             XftColor *color,
                                             PangoMatrix *matrix,
                                             PangoFont *font,
                                             PangoGlyphString *glyphs,
                                             int x,
                                             int y);

Renders a PangoGlyphString onto a XftDraw, possibly transforming the layed-out coordinates through a transformation matrix. Note that the transformation matrix for font is not changed, so to produce correct rendering results, the font must have been loaded using a PangoContext with an identical transformation matrix to that passed in to this function.

draw : | an XftDraw
color : | the color in which to draw the glyphs
matrix : | a PangoMatrix, or NULL to use an identity transformation
font : | the font in which to draw the string
glyphs : | the glyph string to draw
x : | the x position of the start of the string (in Pango units in user space coordinates)
y : | the y position of the baseline (in Pango units in user space coordinates)

Since 1.8

pango_xft_render_layout_line ()

void        pango_xft_render_layout_line    (XftDraw *draw,
                                             XftColor *color,
                                             PangoLayoutLine *line,
                                             int x,
                                             int y);

Render a PangoLayoutLine onto a XftDraw

draw : | an XftDraw
color : | the foreground color in which to draw the layout line (may be overridden by color attributes)
line : | a PangoLayoutLine
x : | the x position of start of string (in Pango units)
y : | the y position of baseline (in Pango units)

Since 1.8

pango_xft_render_layout ()

void        pango_xft_render_layout         (XftDraw *draw,
                                             XftColor *color,
                                             PangoLayout *layout,
                                             int x,
                                             int y);

Render a PangoLayout onto a XftDraw

draw : | an XftDraw
color : | the foreground color in which to draw the layout (may be overridden by color attributes)
layout : | a PangoLayout
x : | the X position of the left of the layout (in Pango units)
y : | the Y position of the top of the layout (in Pango units)

Since 1.8


PangoEngineLang

PangoEngineLang — Rendering-system independent script engines

Synopsis

            PangoEngineLang;
            PangoEngineLangClass;
#define     PANGO_ENGINE_TYPE_LANG
#define     PANGO_ENGINE_LANG_DEFINE_TYPE   (name, prefix, class_init, instance_init)

Object Hierarchy

  GObject
   +----PangoEngine
         +----PangoEngineLang

Description

The language engines are rendering-system independent engines that determine line, word, and character breaks for character strings. These engines are used in pango_break().

Details

PangoEngineLang

typedef struct _PangoEngineLang PangoEngineLang;

The PangoEngineLang class is implemented by engines that customize the rendering-system independent part of the Pango pipeline for a particular script or language. For instance, a custom PangoEngineLang could be provided for Thai to implement the dictionary-based word boundary lookups needed for that language.

PangoEngineLangClass

typedef struct {
  void (*script_break) (PangoEngineLang *engine,
            const char    *text,
            int            len,
            PangoAnalysis *analysis,
            PangoLogAttr  *attrs,
            int            attrs_len);
} PangoEngineLangClass;

Class structure for PangoEngineLang

script_break () Provides a custom implementation of pango_break(). If NULL, pango_default_break() is used instead. If not NULL, for Pango versions before 1.16 (module interface version before 1.6.0), this was called instead of pango_default_break(), but in newer versions, pango_default_break() is always called and this is called after that to allow tailoring the breaking results.

PANGO_ENGINE_TYPE_LANG

#define PANGO_ENGINE_TYPE_LANG "PangoEngineLang"

A string constant defining the engine type for language engines. These engines derive from PangoEngineLang.

PANGO_ENGINE_LANG_DEFINE_TYPE()

#define     PANGO_ENGINE_LANG_DEFINE_TYPE(name, prefix, class_init, instance_init)

Outputs the necessary code for GObject type registration for a PangoEngineLang class defined in a module. Two static symbols are defined.

 static GType prefix_type;
 static void prefix_register_type (GTypeModule module);

The prefix, _register_type() function should be called in your script_engine_init() function for each type that your module implements, and then your script_engine_create() function can create instances of the object as follows:

 PangoEngine *engine = g_object_new (prefix_type, NULL);

name : | Name of the the type to register (for example:, ArabicEngineFc
prefix : | Prefix for symbols that will be defined (for example:, arabic_engine_fc
class_init : | Class initialization function for the new type, or NULL
instance_init : | Instance initialization function for the new type, or NULL


PangoEngineShape

PangoEngineShape — Rendering-system dependent script engines

Synopsis

            PangoEngineShape;
            PangoEngineShapeClass;
#define     PANGO_ENGINE_TYPE_SHAPE
#define     PANGO_ENGINE_SHAPE_DEFINE_TYPE  (name, prefix, class_init, instance_init)

Object Hierarchy

  GObject
   +----PangoEngine
         +----PangoEngineShape

Description

The shape engines are rendering-system dependent engines that convert character strings into glyph strings. These engines are used in pango_shape().

Details

PangoEngineShape

typedef struct _PangoEngineShape PangoEngineShape;

The PangoEngineShape class is implemented by engines that customize the rendering-system dependent part of the Pango pipeline for a particular script or language. A PangoEngineShape implementation is then specific to both a particular rendering system or group of rendering systems and to a particular script. For instance, there is one PangoEngineShape implementation to handle shaping Arabic for Fontconfig-based backends.

PangoEngineShapeClass

typedef struct {
  void (*script_shape) (PangoEngineShape *engine,
            PangoFont        *font,
            const char       *text,
            int               length,
            const PangoAnalysis *analysis,
            PangoGlyphString *glyphs);
  PangoCoverageLevel (*covers)   (PangoEngineShape *engine,
                  PangoFont        *font,
                  PangoLanguage    *language,
                  gunichar          wc);
} PangoEngineShapeClass;

Class structure for PangoEngineShape

script_shape () | Given a font, a piece of text, and a PangoAnalysis structure, converts characters to glyphs and positions the resulting glyphs. The results are stored in the PangoGlyphString that is passed in. (The implementation should resize it appropriately using pango_glyph_string_set_size()). All fields of the log_clusters and glyphs array must be filled in, with the exception that Pango will automatically generate glyphs->glyphs[i].attr.is_cluster_start using the log_clusters array. Each input character must occur in one of the output logical clusters; if no rendering is desired for a character, this may involve inserting glyphs with the PangoGlyph ID PANGO_GLYPH_EMPTY, which is guaranteed never to render. If the shaping fails for any reason, the shaper should return with an empty (zero-size) glyph string. If the shaper has not set the size on the glyph string yet, simply returning signals the failure too.
covers () | Returns the characters that this engine can cover with a given font for a given language. If not overridden, the default implementation simply returns the coverage information for the font itself unmodified.

PANGO_ENGINE_TYPE_SHAPE

#define PANGO_ENGINE_TYPE_SHAPE "PangoEngineShape"

A string constant defining the engine type for shaping engines. These engines derive from PangoEngineShape.

PANGO_ENGINE_SHAPE_DEFINE_TYPE()

#define     PANGO_ENGINE_SHAPE_DEFINE_TYPE(name, prefix, class_init, instance_init)

Outputs the necessary code for GObject type registration for a PangoEngineShape class defined in a module. Two static symbols are defined.

 static GType prefix_type;
 static void prefix_register_type (GTypeModule module);

The prefix, _register_type() function should be called in your script_engine_init() function for each type that your module implements, and then your script_engine_create() function can create instances of the object as follows:

 PangoEngine *engine = g_object_new (prefix_type, NULL);

name : | Name of the the type to register (for example:, ArabicEngineFc
prefix : | Prefix for symbols that will be defined (for example:, arabic_engine_fc
class_init : | Class initialization function for the new type, or NULL
instance_init : | Instance initialization function for the new type, or NULL


PangoFcDecoder

PangoFcDecoder — Custom font encoding handling

Synopsis

            PangoFcDecoder;
            PangoFcDecoderClass;
FcCharSet*  pango_fc_decoder_get_charset    (PangoFcDecoder *decoder,
                                             PangoFcFont *fcfont);
PangoGlyph  pango_fc_decoder_get_glyph      (PangoFcDecoder *decoder,
                                             PangoFcFont *fcfont,
                                             guint32 wc);

Object Hierarchy

  GObject
   +----PangoFcDecoder

Description

PangoFcDecoder represents a decoder that an application provides for handling a font that is encoded in a custom way.

Details

PangoFcDecoder

typedef struct _PangoFcDecoder PangoFcDecoder;

PangoFcDecoder is a virtual base class that implementations will inherit from. It's the interface that is used to define a custom encoding for a font. These objects are created in your code from a function callback that was originally registered with pango_fc_font_map_add_decoder_find_func(). Pango requires information about the supported charset for a font as well as the individual character to glyph conversions. Pango gets that information via the get_charset and get_glyph callbacks into your object implementation.

Since 1.6

PangoFcDecoderClass

typedef struct {
  FcCharSet  *(*get_charset) (PangoFcDecoder *decoder,
                  PangoFcFont    *fcfont);
  PangoGlyph  (*get_glyph)   (PangoFcDecoder *decoder,
                  PangoFcFont    *fcfont,
                  guint32         wc);
} PangoFcDecoderClass;

Class structure for PangoFcDecoder.

get_charset () | This returns an FcCharset given a PangoFcFont that includes a list of supported characters in the font. The FcCharSet that is returned should be an internal reference to your code. Pango will not free this structure. It is important that you make this callback fast because this callback is called separately for each character to determine Unicode coverage.
get_glyph () | This returns a single PangoGlyph for a given Unicode code point.

Since 1.6

pango_fc_decoder_get_charset ()

FcCharSet*  pango_fc_decoder_get_charset    (PangoFcDecoder *decoder,
                                             PangoFcFont *fcfont);

Generates an FcCharSet of supported characters for the fcfont given. The returned FcCharSet will be a reference to an internal value stored by the PangoFcDecoder and must not be modified or freed.

decoder : | a PangoFcDecoder
fcfont : | the PangoFcFont to query.
Returns : | the FcCharset for fcfont; must not be modified or freed.

Since 1.6

pango_fc_decoder_get_glyph ()

PangoGlyph  pango_fc_decoder_get_glyph      (PangoFcDecoder *decoder,
                                             PangoFcFont *fcfont,
                                             guint32 wc);

Generates a PangoGlyph for the given Unicode point using the custom decoder. For complex scripts where there can be multiple glyphs for a single character, the decoder will return whatever glyph is most convenient for it. (Usually whatever glyph is directly in the fonts character map table.)

decoder : | a PangoFcDecoder
fcfont : | a PangoFcFont to query.
wc : | the Unicode code point to convert to a single PangoGlyph.
Returns : | the glyph index, or 0 if the glyph isn't covered by the font.

Since 1.6


PangoFcFont

PangoFcFont — Base font class for Fontconfig-based backends

Synopsis

            PangoFcFont;
            PangoFcFontClass;
#define     PANGO_RENDER_TYPE_FC
FT_Face     pango_fc_font_lock_face         (PangoFcFont *font);
void        pango_fc_font_unlock_face       (PangoFcFont *font);
gboolean    pango_fc_font_has_char          (PangoFcFont *font,
                                             gunichar wc);
guint       pango_fc_font_get_glyph         (PangoFcFont *font,
                                             gunichar wc);
PangoGlyph  pango_fc_font_get_unknown_glyph (PangoFcFont *font,
                                             gunichar wc);
void        pango_fc_font_kern_glyphs       (PangoFcFont *font,
                                             PangoGlyphString *glyphs);

Object Hierarchy

  GObject
   +----PangoFont
         +----PangoFcFont
               +----PangoXftFont

Properties

  "pattern"              gpointer              : Write / Construct Only

Description

PangoFcFont is a base class for font implementation using the Fontconfig and FreeType libraries. It is used in the Xft and FreeType backends shipped with Pango, but can also be used when creating new backends. Any backend deriving from this base class will take advantage of the wide range of shapers implemented using FreeType that come with Pango.

Details

PangoFcFont

typedef struct _PangoFcFont PangoFcFont;

PangoFcFont is a base class for font implementations using the Fontconfig and FreeType libraries and is used in conjunction with PangoFcFontMap. When deriving from this class, you need to implement all of its virtual functions other than shutdown() along with the get_glyph_extents() virtual function from PangoFont.

PangoFcFontClass

typedef struct {
  FT_Face    (*lock_face)         (PangoFcFont      *font);
  void       (*unlock_face)       (PangoFcFont      *font);
  gboolean   (*has_char)          (PangoFcFont      *font,
                   gunichar          wc);
  guint      (*get_glyph)         (PangoFcFont      *font,
                   gunichar          wc);
  PangoGlyph (*get_unknown_glyph) (PangoFcFont      *font,
                   gunichar          wc);
  void       (*shutdown)          (PangoFcFont      *font);
} PangoFcFontClass;

Class structure for PangoFcFont.

lock_face () | Returns the FT_Face of the font and increases the reference count for the face by one.
unlock_face () | Decreases the reference count for the FT_Face of the font by one. When the count is zero, the PangoFcFont subclass is allowed to free the FT_Face.
has_char () | Return TRUE if the the font contains a glyph corresponding to the specified character.
get_glyph () | Gets the glyph that corresponds to the given Unicode character.
get_unknown_glyph () | Gets the glyph that should be used to display an unknown-glyph indication for the specified Unicode character. May be NULL.
shutdown () | Performs any font-specific shutdown code that needs to be done when pango_fc_font_map_shutdown is called. May be NULL.

PANGO_RENDER_TYPE_FC

#define PANGO_RENDER_TYPE_FC "PangoRenderFc"

A string constant used to identify shape engines that work with the fontconfig based backends. See the engine_type field of PangoEngineInfo.

pango_fc_font_lock_face ()

FT_Face     pango_fc_font_lock_face         (PangoFcFont *font);

Gets the FreeType FT_Face associated with a font, This face will be kept around until you call pango_fc_font_unlock_face().

font : | a PangoFcFont.
Returns : | the FreeType FT_Face associated with font.

Since 1.4

pango_fc_font_unlock_face ()

void        pango_fc_font_unlock_face       (PangoFcFont *font);

Releases a font previously obtained with pango_fc_font_lock_face().

font : a PangoFcFont.

Since 1.4

pango_fc_font_has_char ()

gboolean    pango_fc_font_has_char          (PangoFcFont *font,
                                             gunichar wc);

Determines whether font has a glyph for the codepoint wc.

font : | a PangoFcFont
wc : | Unicode codepoint to look up
Returns : | TRUE if font has the requested codepoint.

Since 1.4

pango_fc_font_get_glyph ()

guint       pango_fc_font_get_glyph         (PangoFcFont *font,
                                             gunichar wc);

Gets the glyph index for a given Unicode character for font. If you only want to determine whether the font has the glyph, use pango_fc_font_has_char().

font : | a PangoFcFont
wc : | Unicode character to look up
Returns : | the glyph index, or 0, if the Unicode character doesn't exist in the font.

Since 1.4

pango_fc_font_get_unknown_glyph ()

PangoGlyph  pango_fc_font_get_unknown_glyph (PangoFcFont *font,
                                             gunichar wc);

Warning

pango_fc_font_get_unknown_glyph is deprecated and should not be used in newly-written code.

Returns the index of a glyph suitable for drawing wc as an unknown character.

Use PANGO_GET_UNKNOWN_GLYPH() instead.

font : | a PangoFcFont
wc : | the Unicode character for which a glyph is needed.
Returns : | a glyph index into font.

Since 1.4

pango_fc_font_kern_glyphs ()

void        pango_fc_font_kern_glyphs       (PangoFcFont *font,
                                             PangoGlyphString *glyphs);

Adjust each adjacent pair of glyphs in glyphs according to kerning information in font.

font : | a PangoFcFont
glyphs : | a PangoGlyphString

Since 1.4

Property Details

The "pattern" property

  "pattern"              gpointer              : Write / Construct Only

The fontconfig pattern for this font.

See Also

PangoFcFontMap

The base class for font maps; creating a new Fontconfig-based backend involves deriving from both PangoFcFontMap and PangoFcFont. .


PangoFcFontMap

PangoFcFontMap — Base fontmap class for Fontconfig-based backends

Synopsis

            PangoFcFontMap;
            PangoFcFontMapClass;
PangoFontDescription* pango_fc_font_description_from_pattern
                                            (FcPattern *pattern,
                                             gboolean include_size);
void        pango_fc_font_map_cache_clear   (PangoFcFontMap *fcfontmap);
PangoContext* pango_fc_font_map_create_context
                                            (PangoFcFontMap *fcfontmap);
void        pango_fc_font_map_shutdown      (PangoFcFontMap *fcfontmap);
void        pango_fc_font_map_add_decoder_find_func
                                            (PangoFcFontMap *fcfontmap,
                                             PangoFcDecoderFindFunc findfunc,
                                             gpointer user_data,
                                             GDestroyNotify dnotify);
PangoFcDecoder* (*PangoFcDecoderFindFunc)   (FcPattern *pattern,
                                             gpointer user_data);

Object Hierarchy

  GObject
   +----PangoFontMap
         +----PangoFcFontMap
               +----PangoFT2FontMap

Description

PangoFcFontMap is a base class for font map implementations using the Fontconfig and FreeType libraries. It is used in the Xft and FreeType backends shipped with Pango, but can also be used when creating new backends. Any backend deriving from this base class will take advantage of the wide range of shapers implemented using FreeType that come with Pango.

Details

PangoFcFontMap

typedef struct _PangoFcFontMap PangoFcFontMap;

PangoFcFontMap is a base class for font map implementations using the Fontconfig and FreeType libraries. To create a new backend using Fontconfig and FreeType, you derive from this class and implement a new_font() virtual function that creates an instance deriving from PangoFcFont.

PangoFcFontMapClass

typedef struct {
  /* Deprecated in favor of context_substitute */
  void         (*default_substitute) (PangoFcFontMap   *fontmap,
                      FcPattern        *pattern);
  /* Deprecated in favor of create_font */
  PangoFcFont  *(*new_font)          (PangoFcFontMap  *fontmap,
                      FcPattern       *pattern);

  double       (*get_resolution)     (PangoFcFontMap             *fcfontmap,
                      PangoContext               *context);

  gconstpointer (*context_key_get)   (PangoFcFontMap             *fcfontmap,
                      PangoContext               *context);
  gpointer     (*context_key_copy)   (PangoFcFontMap             *fcfontmap,
                      gconstpointer               key);
  void         (*context_key_free)   (PangoFcFontMap             *fcfontmap,
                      gpointer                    key);
  guint32      (*context_key_hash)   (PangoFcFontMap             *fcfontmap,
                      gconstpointer               key);
  gboolean     (*context_key_equal)  (PangoFcFontMap             *fcfontmap,
                      gconstpointer               key_a,
                      gconstpointer               key_b);

  void         (*context_substitute) (PangoFcFontMap             *fontmap,
                      PangoContext               *context,
                      FcPattern                  *pattern);
  PangoFcFont  *(*create_font)       (PangoFcFontMap             *fontmap,
                      PangoContext               *context,
                      const PangoFontDescription *desc,
                      FcPattern                  *pattern);
} PangoFcFontMapClass;

Class structure for PangoFcFontMap.

default_substitute () | Substitutes in default values for unspecified fields in a FcPattern. This will be called prior to creating a font for the pattern. May be NULL. Deprecated in favor of @context_substitute().
new_font () | Creates a new PangoFcFont for the specified pattern of the appropriate type for this font map. The pattern argument must be passed to the "pattern" property of PangoFcFont when you call g_object_new(). Deprecated in favor of @create_font().
get_resolution () | Gets the resolution (the scale factor between logical and absolute font sizes) that the backend will use for a particular fontmap and context. context may be null.
context_key_get () | Gets an opaque key holding backend specific options for the context that will affect fonts created by create_font(). The result must point to persistent storage owned by the fontmap. This key is used to index hash tables used to look up fontsets and fonts.
context_key_copy () | Copies a context key. Pango uses this to make a persistent copy of the value returned from context_key_get.
context_key_free () | Frees a context key copied with context_key_copy.
context_key_hash () | Gets a hash value for a context key
context_key_equal () | Compares two context keys for equality.
context_substitute () | Substitutes in default values for unspecified fields in a FcPattern. This will be called prior to creating a font for the pattern. May be NULL.
create_font () | Creates a new PangoFcFont for the specified pattern of the appropriate type for this font map using information from the context that is passed in. The pattern argument must be passed to the "pattern" property of PangoFcFont when you call g_object_new(). Deprecated in favor of @create_font(). If NULL, new_font() is used.

pango_fc_font_description_from_pattern ()

PangoFontDescription* pango_fc_font_description_from_pattern
                                            (FcPattern *pattern,
                                             gboolean include_size);

Creates a PangoFontDescription that matches the specified Fontconfig pattern as closely as possible. Many possible Fontconfig pattern values, such as FC_RASTERIZER or FC_DPI, don't make sense in the context of PangoFontDescription, so will be ignored.

pattern : | a FcPattern
include_size : | if TRUE, the pattern will include the size from the pattern; otherwise the resulting pattern will be unsized. (only FC_SIZE is examined, not FC_PIXEL_SIZE)
Returns : | a new PangoFontDescription. Free with pango_font_description_free().

Since 1.4

pango_fc_font_map_cache_clear ()

void        pango_fc_font_map_cache_clear   (PangoFcFontMap *fcfontmap);

Clear all cached information and fontsets for this font map; this should be called whenever there is a change in the output of the default_substitute() virtual function.

This function is intended to be used only by backend implementations deriving from PangoFcFontmap.

fcfontmap : a PangoFcFontmap

Since 1.4

pango_fc_font_map_create_context ()

PangoContext* pango_fc_font_map_create_context
                                            (PangoFcFontMap *fcfontmap);

Creates a new context for this fontmap. This function is intended only for backend implementations deriving from PangoFcFontmap; it is possible that a backend will store additional information needed for correct operation on the PangoContext after calling this function.

fcfontmap : | a PangoFcFontMap
Returns : | a new PangoContext

Since 1.4

pango_fc_font_map_shutdown ()

void        pango_fc_font_map_shutdown      (PangoFcFontMap *fcfontmap);

Clears all cached information for the fontmap and marks all fonts open for the fontmap as dead. (See the shutdown() virtual function of PangoFcFont.) This function might be used by a backend when the underlying windowing system for the font map exits. This function is only intended to be called from only for backend implementations deriving from PangoFcFontmap.

fcfontmap : a PangoFcFontmap

Since 1.4

pango_fc_font_map_add_decoder_find_func ()

void        pango_fc_font_map_add_decoder_find_func
                                            (PangoFcFontMap *fcfontmap,
                                             PangoFcDecoderFindFunc findfunc,
                                             gpointer user_data,
                                             GDestroyNotify dnotify);

This function saves a callback method in the PangoFcFontMap that will be called whenever new fonts are created. If the function returns a PangoFcDecoder, that decoder will be used to determine both coverage via a FcCharSet and a one-to-one mapping of characters to glyphs. This will allow applications to have application-specific encodings for various fonts.

fcfontmap : | The PangoFcFontMap to add this method to.
findfunc : | The PangoFcDecoderFindFunc callback function
user_data : | User data.
dnotify : | A GDestroyNotify callback that will be called when the fontmap is finalized and the decoder is released.

Since 1.6.

PangoFcDecoderFindFunc ()

PangoFcDecoder* (*PangoFcDecoderFindFunc)   (FcPattern *pattern,
                                             gpointer user_data);

Callback function passed to pango_fc_font_map_add_decoder_find_func().

pattern : | a fully resolved FcPattern specifying the font on the system
user_data : | user data passed to pango_fc_font_map_add_decoder_find_func()
Returns : | a new reference to a custom decoder for this pattern, or NULL if the default decoder handling should be used.

See Also

PangoFcFont

The base class for fonts; creating a new Fontconfig-based backend involves deriving from both PangoFcFontMap and PangoFcFont.


Text Attribute Markup

Text Attribute Markup — Simple markup language to encode text with attributes

Pango Text Attribute Markup Language

Frequently, you want to display some text to the user with attributes applied to part of the text (for example, you might want bold or italicized words). With the base Pango interfaces, you could create a PangoAttrList and apply it to the text; the problem is that you'd need to apply attributes to some numeric range of characters, for example "characters 12-17." This is broken from an internationalization standpoint; once the text is translated, the word you wanted to italicize could be in a different position.

The solution is to include the text attributes in the string to be translated. Pango provides this feature with a small markup language. You can parse a marked-up string into the string text plus a PangoAttrList using the function pango_parse_markup().

A simple example of a marked-up string might be: "<span foreground="blue" size="x-large">Blue text</span> is <i>cool</i>!"

The root tag of a marked-up document is <markup>, but pango_parse_markup() allows you to omit this tag, so you will most likely never need to use it. The most general markup tag is <span>, then there are some convenience tags. <span> has the following attributes:

<span> attributes

font_desc | A font description string, such as "Sans Italic 12"; note that any other span attributes will override this description. So if you have "Sans Italic" and also a style="normal" attribute, you will get Sans normal, not italic.
font_family | A font family name
face | Synonym for font_family
size | Font size in 1024ths of a point, or one of the absolute sizes 'xx-small', 'x-small', 'small', 'medium', 'large', 'x-large', 'xx-large', or one of the relative sizes 'smaller' or 'larger'. If you want to specify a absolute size, it's usually easier to take advantage of the ability to specify a partial font description using 'font_desc'; you can use font_desc='12.5' rather than size='12800'.
style | One of 'normal', 'oblique', 'italic'
weight | One of 'ultralight', 'light', 'normal', 'bold', 'ultrabold', 'heavy', or a numeric weight
variant | 'normal' or 'smallcaps'
stretch | One of 'ultracondensed', 'extracondensed', 'condensed', 'semicondensed', 'normal', 'semiexpanded', 'expanded', 'extraexpanded', 'ultraexpanded'
foreground | An RGB color specification such as '#00FF00' or a color name such as 'red'
background | An RGB color specification such as '#00FF00' or a color name such as 'red'
underline | One of 'single', 'double', 'low', 'none'
underline_color | The color of underlines; an RGB color specification such as '#00FF00' or a color name such as 'red'
rise | Vertical displacement, in 10000ths of an em. Can be negative for subscript, positive for superscript.
strikethrough | 'true' or 'false' whether to strike through the text
strikethrough_color | The color of strikethrough lines; an RGB color specification such as '#00FF00' or a color name such as 'red'
fallback | 'true' or 'false' whether to enable fallback. If disabled, then characters will only be used from the closest matching font on the system. No fallback will be done to other fonts on the system that might contain the characters in the text. Fallback is enabled by default. Most applications should not disable fallback.
lang | A language code, indicating the text language

The following convenience tags are provided:

Convenience tags

b | Bold
big | Makes font relatively larger, equivalent to <span size="larger">
i | Italic
s | Strikethrough
sub | Subscript
sup | Superscript
small | Makes font relatively smaller, equivalent to <span size="smaller">
tt | Monospace font
u | Underline


Rendering with Pango

Win32 Fonts and Rendering - Functions for shape engines to manipulate Win32 fonts
FreeType Fonts and Rendering - Functions for shape engines to manipulate FreeType fonts
Xft Fonts and Rendering - Font handling and rendering with the Xft backend
Cairo Rendering - Rendering with the Cairo backend
ATSUI Fonts - Font handling and rendering with ATSUI fonts
Deprecated X font backend - Font handling and rendering with the deprecated X font backend


Pango Tools

pango-querymodules - Module registration utility


Index

R

RsvgDimensionData, RsvgDimensionData

RsvgError, enum RsvgError

RsvgSizeFunc, RsvgSizeFunc ()

RSVG_ERROR, RSVG_ERROR

rsvg_error_quark, rsvg_error_quark ()

rsvg_handle_close, rsvg_handle_close ()

rsvg_handle_free, rsvg_handle_free ()

rsvg_handle_get_base_uri, rsvg_handle_get_base_uri ()

rsvg_handle_get_desc, rsvg_handle_get_desc ()

rsvg_handle_get_dimensions, rsvg_handle_get_dimensions ()

rsvg_handle_get_pixbuf, rsvg_handle_get_pixbuf ()

rsvg_handle_get_pixbuf_sub, rsvg_handle_get_pixbuf_sub ()

rsvg_handle_get_title, rsvg_handle_get_title ()

rsvg_handle_new, rsvg_handle_new ()

rsvg_handle_new_from_data, rsvg_handle_new_from_data ()

rsvg_handle_new_from_file, rsvg_handle_new_from_file ()

rsvg_handle_render_cairo, rsvg_handle_render_cairo ()

rsvg_handle_render_cairo_sub, rsvg_handle_render_cairo_sub ()

rsvg_handle_set_base_uri, rsvg_handle_set_base_uri ()

rsvg_handle_set_dpi, rsvg_handle_set_dpi ()

rsvg_handle_set_dpi_x_y, rsvg_handle_set_dpi_x_y ()

rsvg_handle_set_size_callback, rsvg_handle_set_size_callback ()

rsvg_handle_write, rsvg_handle_write ()

rsvg_init, rsvg_init ()

rsvg_pixbuf_from_file, rsvg_pixbuf_from_file ()

rsvg_pixbuf_from_file_at_max_size, rsvg_pixbuf_from_file_at_max_size ()

rsvg_pixbuf_from_file_at_size, rsvg_pixbuf_from_file_at_size ()

rsvg_pixbuf_from_file_at_zoom, rsvg_pixbuf_from_file_at_zoom ()

rsvg_pixbuf_from_file_at_zoom_with_max, rsvg_pixbuf_from_file_at_zoom_with_max ()

rsvg_set_default_dpi, rsvg_set_default_dpi ()

rsvg_set_default_dpi_x_y, rsvg_set_default_dpi_x_y ()

rsvg_term, rsvg_term ()


Prev Home RSVG Reference Manual Next

Part II. Using RSVG


Prev Home RSVG Reference Manual Next

Part III. Using RSVG with Cairo


Prev Home RSVG Reference Manual Next

Part IV. Using RSVG with GdkPixbuf


Part I. RSVG Overview

The GNOME SVG Library (RSVG) is library for rendering SVG and SVGZ files. RSVG is released under the GNU General Public License (GNU GPL), which allows for flexible licensing of client applications.

RSVG depends on the following libraries:

GLib | A general-purpose utility library, not specific to graphical user interfaces. GLib provides many useful data types, macros, type conversions, string utilities, file utilities, a main loop abstraction, and so on.
Pango | A general-purpose text library. http://www.pango.org/
GdkPixbuf | A general-purpose image library.
Cairo | Cairo is a 2D graphics library with support for multiple output devices. Cairo is designed to produce consistent output on all output media while taking advantage of display hardware acceleration when available. http://www.cairographics.org/


Cairo

Cairo

Synopsis

void        rsvg_handle_render_cairo        (RsvgHandle *handle,
                                             cairo_t *cr);
void        rsvg_handle_render_cairo_sub    (RsvgHandle *handle,
                                             cairo_t *cr,
                                             const char *id);

Description

Details

rsvg_handle_render_cairo ()

void        rsvg_handle_render_cairo        (RsvgHandle *handle,
                                             cairo_t *cr);

Draws a SVG to a Cairo surface

handle : | A RsvgHandle
cr : | A Cairo renderer

Since 2.14

rsvg_handle_render_cairo_sub ()

void        rsvg_handle_render_cairo_sub    (RsvgHandle *handle,
                                             cairo_t *cr,
                                             const char *id);

Draws a subset of a SVG to a Cairo surface

handle : | A RsvgHandle
cr : | A Cairo renderer
id : | An element's id within the SVG, or NULL to render the whole SVG

Since 2.14


Core API

Core API —

Create and manipulate SVG objects

Synopsis

enum        RsvgError;
#define     RSVG_ERROR
GQuark      rsvg_error_quark                (void);
void        rsvg_init                       (void);
void        rsvg_term                       (void);
void        rsvg_set_default_dpi            (double dpi);
void        rsvg_set_default_dpi_x_y        (double dpi_x,
                                             double dpi_y);
RsvgHandle* rsvg_handle_new                 (void);
void        rsvg_handle_free                (RsvgHandle *handle);
void        rsvg_handle_set_dpi             (RsvgHandle *handle,
                                             double dpi);
void        rsvg_handle_set_dpi_x_y         (RsvgHandle *handle,
                                             double dpi_x,
                                             double dpi_y);
gboolean    rsvg_handle_write               (RsvgHandle *handle,
                                             const guchar *buf,
                                             gsize count,
                                             GError **error);
gboolean    rsvg_handle_close               (RsvgHandle *handle,
                                             GError **error);
RsvgHandle* rsvg_handle_new_from_data       (const guint8 *data,
                                             gsize data_len,
                                             GError **error);
RsvgHandle* rsvg_handle_new_from_file       (const gchar *file_name,
                                             GError **error);
            RsvgDimensionData;
void        (*RsvgSizeFunc)                 (gint *width,
                                             gint *height,
                                             gpointer user_data);
void        rsvg_handle_set_size_callback   (RsvgHandle *handle,
                                             RsvgSizeFunc size_func,
                                             gpointer user_data,
                                             GDestroyNotify user_data_destroy);
const char* rsvg_handle_get_base_uri        (RsvgHandle *handle);
void        rsvg_handle_set_base_uri        (RsvgHandle *handle,
                                             const char *base_uri);
const char* rsvg_handle_get_title           (RsvgHandle *handle);
const char* rsvg_handle_get_desc            (RsvgHandle *handle);
void        rsvg_handle_get_dimensions      (RsvgHandle *handle,
                                             RsvgDimensionData *dimension_data);

Description

librsvg is a component used within software applications to enable support for SVG-format scalable graphics. In contrast to raster formats, scalable vector graphics provide users and artists a way to create, view, and provide imagery that is not limited to the pixel or dot density that an output device is capable of.

Many software developers use the librsvg library to render SVG graphics. It is lightweight and portable.

Details

enum RsvgError

typedef enum {
    RSVG_ERROR_FAILED
} RsvgError;

RSVG_ERROR

#define RSVG_ERROR (rsvg_error_quark ())

rsvg_error_quark ()

GQuark      rsvg_error_quark                (void);

The error domain for RSVG

Returns : The error domain

rsvg_init ()

void        rsvg_init                       (void);

Initializes librsvg

Since 2.9

rsvg_term ()

void        rsvg_term                       (void);

De-initializes librsvg

Since 2.9

rsvg_set_default_dpi ()

void        rsvg_set_default_dpi            (double dpi);

Sets the DPI for the all future outgoing pixbufs. Common values are 75, 90, and 300 DPI. Passing a number <= 0 to dpi will reset the DPI to whatever the default value happens to be.

dpi : Dots Per Inch (aka Pixels Per Inch)

Since 2.8

rsvg_set_default_dpi_x_y ()

void        rsvg_set_default_dpi_x_y        (double dpi_x,
                                             double dpi_y);

Sets the DPI for the all future outgoing pixbufs. Common values are 75, 90, and 300 DPI. Passing a number <= 0 to dpi will reset the DPI to whatever the default value happens to be.

dpi_x : | Dots Per Inch (aka Pixels Per Inch)
dpi_y : | Dots Per Inch (aka Pixels Per Inch)

Since 2.8

rsvg_handle_new ()

RsvgHandle* rsvg_handle_new                 (void);

Returns a new rsvg handle. Must be freed with g_object_unref. This handle can be used for dynamically loading an image. You need to feed it data using rsvg_handle_write, then call rsvg_handle_close when done. Afterwords, you can render it using Cairo or get a GdkPixbuf from it. When finished, free with g_object_unref(). No more than one image can be loaded with one handle.

Returns : A new RsvgHandle

rsvg_handle_free ()

void        rsvg_handle_free                (RsvgHandle *handle);

Warning

rsvg_handle_free is deprecated and should not be used in newly-written code. Use g_object_unref() instead.

Frees handle.

handle : An RsvgHandle

rsvg_handle_set_dpi ()

void        rsvg_handle_set_dpi             (RsvgHandle *handle,
                                             double dpi);

Sets the DPI for the outgoing pixbuf. Common values are 75, 90, and 300 DPI. Passing a number <= 0 to dpi will reset the DPI to whatever the default value happens to be.

handle : | An RsvgHandle
dpi : | Dots Per Inch (aka Pixels Per Inch)

Since 2.8

rsvg_handle_set_dpi_x_y ()

void        rsvg_handle_set_dpi_x_y         (RsvgHandle *handle,
                                             double dpi_x,
                                             double dpi_y);

Sets the DPI for the outgoing pixbuf. Common values are 75, 90, and 300 DPI. Passing a number <= 0 to dpi_x or dpi_y will reset the DPI to whatever the default value happens to be.

handle : | An RsvgHandle
dpi_x : | Dots Per Inch (aka Pixels Per Inch)
dpi_y : | Dots Per Inch (aka Pixels Per Inch)

Since 2.8

rsvg_handle_write ()

gboolean    rsvg_handle_write               (RsvgHandle *handle,
                                             const guchar *buf,
                                             gsize count,
                                             GError **error);

Loads the next count bytes of the image. This will return TRUE if the data was loaded successful, and FALSE if an error occurred. In the latter case, the loader will be closed, and will not accept further writes. If FALSE is returned, error will be set to an error from the RSVG_ERROR domain.

handle : | An RsvgHandle
buf : | Pointer to svg data
count : | length of the buf buffer in bytes
error : | return location for errors
Returns : | TRUE if the write was successful, or FALSE if there was an error.

rsvg_handle_close ()

gboolean    rsvg_handle_close               (RsvgHandle *handle,
                                             GError **error);

Closes handle, to indicate that loading the image is complete. This will return TRUE if the loader closed successfully. Note that handle isn't freed until g_object_unref is called.

handle : | A RsvgHandle
error : | A GError
Returns : | TRUE if the loader closed successfully, or FALSE if there was an error.

rsvg_handle_new_from_data ()

RsvgHandle* rsvg_handle_new_from_data       (const guint8 *data,
                                             gsize data_len,
                                             GError **error);

Loads the SVG specified by data.

data : | The SVG data
data_len : | The length of data, in bytes
error : | return location for errors
Returns : | A RsvgHandle or NULL if an error occurs.

Since 2.14

rsvg_handle_new_from_file ()

RsvgHandle* rsvg_handle_new_from_file       (const gchar *file_name,
                                             GError **error);

Loads the SVG specified by file_name.

file_name : | The file name to load. If built with gnome-vfs, can be a URI.
error : | return location for errors
Returns : | A RsvgHandle or NULL if an error occurs.

Since 2.14

RsvgDimensionData

typedef struct {
    /**
     * SVG's width, in pixels
     */
    int width;

    /**
     * SVG's height, in pixels
     */
    int height;

    /**
     * em
     */
    gdouble em;

    /**
     * ex
     */
    gdouble ex;
} RsvgDimensionData;

RsvgSizeFunc ()

void        (*RsvgSizeFunc)                 (gint *width,
                                             gint *height,
                                             gpointer user_data);

Warning

RsvgSizeFunc is deprecated and should not be used in newly-written code. Set up a cairo matrix and use rsvg_handle_render_cairo() instead.

Function to let a user of the library specify the SVG's dimensions width: the ouput width the SVG should be height: the output height the SVG should be user_data: user data

width : | Pointer to where to set/store the width
height : | Pointer to where to set/store the height
user_data : | User data pointer

rsvg_handle_set_size_callback ()

void        rsvg_handle_set_size_callback   (RsvgHandle *handle,
                                             RsvgSizeFunc size_func,
                                             gpointer user_data,
                                             GDestroyNotify user_data_destroy);

Warning

rsvg_handle_set_size_callback is deprecated and should not be used in newly-written code. Set up a cairo matrix and use rsvg_handle_render_cairo() instead.

Sets the sizing function for the handle. This function is called right after the size of the image has been loaded. The size of the image is passed in to the function, which may then modify these values to set the real size of the generated pixbuf. If the image has no associated size, then the size arguments are set to -1.

handle : | An RsvgHandle
size_func : | A sizing function, or NULL
user_data : | User data to pass to size_func, or NULL
user_data_destroy : | Destroy function for user_data, or NULL

rsvg_handle_get_base_uri ()

const char* rsvg_handle_get_base_uri        (RsvgHandle *handle);

Gets the base uri for this RsvgHandle.

handle : | A RsvgHandle
Returns : | the base uri, possibly null

Since 2.9 (really present in 2.8 as well)

rsvg_handle_set_base_uri ()

void        rsvg_handle_set_base_uri        (RsvgHandle *handle,
                                             const char *base_uri);

Set the base URI for this SVG. This can only be called before rsvg_handle_write() has been called.

handle : | A RsvgHandle
base_uri : | The base uri

Since 2.9

rsvg_handle_get_title ()

const char* rsvg_handle_get_title           (RsvgHandle *handle);

Returns the SVG's title in UTF-8 or NULL. You must make a copy of this title if you wish to use it after handle has been freed.

handle : | An RsvgHandle
Returns : | The SVG's title

Since 2.4

rsvg_handle_get_desc ()

const char* rsvg_handle_get_desc            (RsvgHandle *handle);

Returns the SVG's description in UTF-8 or NULL. You must make a copy of this description if you wish to use it after handle has been freed.

handle : | An RsvgHandle
Returns : | The SVG's description

Since 2.4

rsvg_handle_get_dimensions ()

void        rsvg_handle_get_dimensions      (RsvgHandle *handle,
                                             RsvgDimensionData *dimension_data);

Get the SVG's size. Do not call from within the size_func callback, because an infinite loop will occur.

handle : | A RsvgHandle
dimension_data : | A place to store the SVG's size

Since 2.14


Rendering SVGs with GdkPixbuf

Rendering SVGs with GdkPixbuf —

How to render SVGs into GdkPixbufs, for easy use in GTK+ applications

Synopsis

GdkPixbuf*  rsvg_handle_get_pixbuf          (RsvgHandle *handle);
GdkPixbuf*  rsvg_handle_get_pixbuf_sub      (RsvgHandle *handle,
                                             const char *id);
GdkPixbuf*  rsvg_pixbuf_from_file           (const gchar *file_name,
                                             GError **error);
GdkPixbuf*  rsvg_pixbuf_from_file_at_zoom   (const gchar *file_name,
                                             double x_zoom,
                                             double y_zoom,
                                             GError **error);
GdkPixbuf*  rsvg_pixbuf_from_file_at_size   (const gchar *file_name,
                                             gint width,
                                             gint height,
                                             GError **error);
GdkPixbuf*  rsvg_pixbuf_from_file_at_max_size
                                            (const gchar *file_name,
                                             gint max_width,
                                             gint max_height,
                                             GError **error);
GdkPixbuf*  rsvg_pixbuf_from_file_at_zoom_with_max
                                            (const gchar *file_name,
                                             double x_zoom,
                                             double y_zoom,
                                             gint max_width,
                                             gint max_height,
                                             GError **error);

Description

GdkPixbuf is a library for image loading and manipulation. It is part of the cross-platform GTK+ widget toolkit.

Details

rsvg_handle_get_pixbuf ()

GdkPixbuf*  rsvg_handle_get_pixbuf          (RsvgHandle *handle);

Returns the pixbuf loaded by handle. The pixbuf returned will be reffed, so the caller of this function must assume that ref. If insufficient data has been read to create the pixbuf, or an error occurred in loading, then NULL will be returned. Note that the pixbuf may not be complete until rsvg_handle_close has been called.

handle : | An RsvgHandle
Returns : | the pixbuf loaded by handle, or NULL.

rsvg_handle_get_pixbuf_sub ()

GdkPixbuf*  rsvg_handle_get_pixbuf_sub      (RsvgHandle *handle,
                                             const char *id);

Returns the pixbuf loaded by handle. The pixbuf returned will be reffed, so the caller of this function must assume that ref. If insufficient data has been read to create the pixbuf, or an error occurred in loading, then NULL will be returned. Note that the pixbuf may not be complete until rsvg_handle_close has been called.

handle : | An RsvgHandle
id : | The id of an element inside the SVG, or NULL to render the whole SVG
Returns : | the pixbuf loaded by handle, or NULL.

Since 2.14

rsvg_pixbuf_from_file ()

GdkPixbuf*  rsvg_pixbuf_from_file           (const gchar *file_name,
                                             GError **error);

Warning

rsvg_pixbuf_from_file is deprecated and should not be used in newly-written code. Set up a cairo matrix and use rsvg_handle_new_from_file() + rsvg_handle_render_cairo() instead.

Loads a new GdkPixbuf from file_name and returns it. The caller must assume the reference to the reurned pixbuf. If an error occurred, error is set and NULL is returned.

file_name : | A file name
error : | return location for errors
Returns : | A newly allocated GdkPixbuf, or NULL

rsvg_pixbuf_from_file_at_zoom ()

GdkPixbuf*  rsvg_pixbuf_from_file_at_zoom   (const gchar *file_name,
                                             double x_zoom,
                                             double y_zoom,
                                             GError **error);

Warning

rsvg_pixbuf_from_file_at_zoom is deprecated and should not be used in newly-written code. Set up a cairo matrix and use rsvg_handle_new_from_file() + rsvg_handle_render_cairo() instead.

Loads a new GdkPixbuf from file_name and returns it. This pixbuf is scaled from the size indicated by the file by a factor of x_zoom and y_zoom. The caller must assume the reference to the returned pixbuf. If an error occurred, error is set and NULL is returned.

file_name : | A file name
x_zoom : | The horizontal zoom factor
y_zoom : | The vertical zoom factor
error : | return location for errors
Returns : | A newly allocated GdkPixbuf, or NULL

rsvg_pixbuf_from_file_at_size ()

GdkPixbuf*  rsvg_pixbuf_from_file_at_size   (const gchar *file_name,
                                             gint width,
                                             gint height,
                                             GError **error);

Warning

rsvg_pixbuf_from_file_at_size is deprecated and should not be used in newly-written code. Set up a cairo matrix and use rsvg_handle_new_from_file() + rsvg_handle_render_cairo() instead.

Loads a new GdkPixbuf from file_name and returns it. This pixbuf is scaled from the size indicated to the new size indicated by width and height. If either of these are -1, then the default size of the image being loaded is used. The caller must assume the reference to the returned pixbuf. If an error occurred, error is set and NULL is returned.

file_name : | A file name
width : | The new width, or -1
height : | The new height, or -1
error : | return location for errors
Returns : | A newly allocated GdkPixbuf, or NULL

rsvg_pixbuf_from_file_at_max_size ()

GdkPixbuf*  rsvg_pixbuf_from_file_at_max_size
                                            (const gchar *file_name,
                                             gint max_width,
                                             gint max_height,
                                             GError **error);

Warning

rsvg_pixbuf_from_file_at_max_size is deprecated and should not be used in newly-written code. Set up a cairo matrix and use rsvg_handle_new_from_file() + rsvg_handle_render_cairo() instead.

Loads a new GdkPixbuf from file_name and returns it. This pixbuf is uniformly scaled so that the it fits into a rectangle of size max_width * max_height. The caller must assume the reference to the returned pixbuf. If an error occurred, error is set and NULL is returned.

file_name : | A file name
max_width : | The requested max width
max_height : | The requested max heigh
error : | return location for errors
Returns : | A newly allocated GdkPixbuf, or NULL

rsvg_pixbuf_from_file_at_zoom_with_max ()

GdkPixbuf*  rsvg_pixbuf_from_file_at_zoom_with_max
                                            (const gchar *file_name,
                                             double x_zoom,
                                             double y_zoom,
                                             gint max_width,
                                             gint max_height,
                                             GError **error);

Warning

rsvg_pixbuf_from_file_at_zoom_with_max is deprecated and should not be used in newly-written code. Set up a cairo matrix and use rsvg_handle_new_from_file() + rsvg_handle_render_cairo() instead.

Loads a new GdkPixbuf from file_name and returns it. This pixbuf is scaled from the size indicated by the file by a factor of x_zoom and y_zoom. If the resulting pixbuf would be larger than max_width/max_heigh it is uniformly scaled down to fit in that rectangle. The caller must assume the reference to the returned pixbuf. If an error occurred, error is set and NULL is returned.

file_name : | A file name
x_zoom : | The horizontal zoom factor
y_zoom : | The vertical zoom factor
max_width : | The requested max width
max_height : | The requested max heigh
error : | return location for errors
Returns : | A newly allocated GdkPixbuf, or NULL


＜ABS Example Program＞

Program abs_example
  Real :: a(5) = [ 0.0, -0.0, 1.5, -2.5, 3.5 ]
  Integer :: b(2) = [ 1,-1 ]
  Complex, Dimension(3) :: c = [ (3e-30,4e-30),(3,4),(3e30,4e30) ]
  Print 1, Abs(a)
1 Format(1X,'Real: ',5F8.5)
  Print 2, Abs(b)
2 Format(1X,'Integer:',2(1X,I0))
  Print 3, Abs(c)
3 Format(1X,'Complex (Real result):',3(1X,ES12.5))
End Program

■ Execution Results

 Real:  0.00000 0.00000 1.50000 2.50000 3.50000
 Integer: 1 1
 Complex (Real result):  5.00000E-30  5.00000E+00  5.00000E+30


＜ACHAR Example Program＞

Program achar_example
  !
  ! Display the ASCII printing characters (excluding space).
  !
  Implicit None
  Integer i,j
  Do i=33,126,8
    Print 1,i,(Achar(j),j=i,Min(i+7,126))
1   Format(1X,I3,': ',99(A,:,' '))
  End Do
End Program

■ Execution Results

  33: ! " # $ % & ' (
  41: ) * + , - . / 0
  49: 1 2 3 4 5 6 7 8
  57: 9 : ; < = > ? @
  65: A B C D E F G H
  73: I J K L M N O P
  81: Q R S T U V W X
  89: Y Z [ \ ] ^ _ `
  97: a b c d e f g h
 105: i j k l m n o p
 113: q r s t u v w x
 121: y z { | } ~


＜ACOS Example Program＞

Program acos_example
  Real, Dimension(2,3) :: a
  Complex, Dimension(3) :: c
  a = Reshape( [ 0.0,0.1,0.3,0.4,0.5,1.0 ], [ 2,3 ])
  c = [ (.2,.3),(.5,-.1),(.4,-.3) ]
  Print 1, Acos(a)
1 Format(6(2X,F0.5))
  Print 2, Acos(c)
2 Format(3(2X,'(',F0.5,',',F0.5,')'))
End Program

■ Execution Results

  1.57080  1.47063  1.26610  1.15928  1.04720  .00000
  (1.37834,-.30107)  (1.05099,.11497)  (1.18048,.31896)


＜ACOSH Example Program＞

Program acosh_example
  Real, Dimension(2,3) :: a
  Complex, Dimension(3) :: c
  a = Reshape( [ 1.0,1.25,2.5,5.8,15.,27.5 ], [ 2,3 ])
  c = [ (.2,.3),(.5,-.1),(.4,-.3) ]
  Print 1, Acosh(a)
1 Format(6(2X,F0.5))
  Print 2, Acosh(c)
2 Format(3(2X,'(',F0.5,',',F0.5,')'))
End Program

■ Execution Results

  .00000  .69315  1.56680  2.44349  3.40008  4.00700
  (.30107,1.37834)  (-.11497,1.05099)  (-.31896,1.18048)


＜ADJUSTL Example Program＞

Program adjustl_example
  Character(7) :: a(9) = [ 'a      ', &
                           'ab     ', &
                           'abc    ', &
                           ' bcd   ', &
                           '  cde  ', &
                           '   def ', &
                           '    efg', &
                           '     fg', &
                           '      g' ]
  Print 1, Adjustl(a)
1 Format(A10)
End Program

■ Execution Results

   a
   ab
   abc
   bcd
   cde
   def
   efg
   fg
   g


＜ADJUSTR Example Program＞

Program adjustr_example
  Character(7) :: a(9) = [ 'a      ', &
                           'ab     ', &
                           'abc    ', &
                           ' bcd   ', &
                           '  cde  ', &
                           '   def ', &
                           '    efg', &
                           '     fg', &
                           '      g' ]
  Print 1, Adjustr(a)
1 Format(A10)
End Program

■ Execution Results

         a
        ab
       abc
       bcd
       cde
       def
       efg
        fg
         g


＜ADVANCE= Example Program＞

Program advance_specifier_example
    Character ch
    Character(80) :: name(10) = ''
    Integer pos

    Print *,'Please enter a list of names separated by commas.'

    Do i=1,10
        pos = 1
        Do
            Read (*,'(a)',Advance='No',Eor=10) ch
            If (ch==',') Exit
            name(i)(pos:pos) = ch
            pos = pos + 1
        End do
    End do
    Print *,'Only the first 10 names are accepted'
    i = 10
10  Continue
    Print 20,i
20  Format(/,1X,'You have entered ',I0,' names.')
    Do j=1,i
        Print 30,j,Trim(name(j))
30      Format(1X,I0,1X,A)
    End do
End program

＜Example Input＞

Fred Nurke,X the Unknown,Penelope Pettigrew

■ Execution Results

 You have entered 3 names.
 1 Fred Nurke
 2 X the Unknown
 3 Penelope Pettigrew


＜AIMAG Example Program＞

Program aimag_example
  Complex :: c(3) = [ (1,2),(3,4),(5,6) ]
  Print 1, Aimag(c)
1 Format(3(2X,F0.5))
End Program

■ Execution Results

  2.00000  4.00000  6.00000


＜AINT Example Program＞

Program aint_example
  Call test( [ 10.49,10.50,10.51 ] )
Contains
  Subroutine test(a)
    Real,Intent(In) :: a(:)
    Print 1,a,Aint(a)
 1  Format(3F8.2,/,3F8.2)
    Print 1,-a,Aint(-a)
  End Subroutine
End Program

■ Execution Results

   10.49   10.50   10.51
   10.00   10.00   10.00
  -10.49  -10.50  -10.51
  -10.00  -10.00  -10.00


＜ALL Example Program＞

Program all_example
  Real, Dimension(2,3) :: a, b
  a = Reshape( (/2.,3.,5.,-1.,4.,-3./), (/2,3/))
  b = Reshape( (/2.,3.,5.,-1.,0.,-3./), (/2,3/))
  Print *, All(a==b)
  Print *, All(a==b,1)
  Print *, All(Mask=a.Eq.b,Dim=2)
End Program

■ Execution Results

 F
 T T F
 F T


＜ALLOCATABLE Example Program＞

Program allocatable_example
  Real, Allocatable :: a(:,:)
  Read *, n
  Allocate(a(2,n))
  Do i = 1, 2
    Do j = 1, n
      a(i,j) = i*100 + j
    End Do
  End Do
  Print *, a(2,n)
End Program

＜Example input 1＞

4

■ Execution Results

 2.0400000E+02

＜Example input 2＞

11

■ Execution Results

 2.1100000E+02

＜ALLOCATABLE Example Program 2＞

Program allocatable_example_2
  Character(:),Allocatable :: name
  Allocate(name,Source='Fred Nurke')
  Print *,Len(name),name
  Deallocate(name)
  Allocate(name,Source='')
  Print *,Len(name),name
  name = 'Akira'
  Print *,Len(name),name
  name(:) = '123456789'
  Print *,Len(name),name
End Program

■ Execution Results

 10 Fred Nurke
 0
 5 Akira
 5 12345


＜ALLOCATE Example Program＞

Program allocate_example
  Real, Allocatable :: a(:,:)
  Read *, n
  Allocate(a(2,n))
  Do i = 1, 2
    Do j = 1, n
      a(i,j) = i*100 + j
    End Do
  End Do
  Print *, a(2,n)
End Program

＜Example input 1＞

4

■ Execution Results

 2.0400000E+02

＜Example input 2＞

11

■ Execution Results

 2.1100000E+02


＜ALLOCATED Example Program＞

Program allocated_example
  Real, Allocatable :: x(:,:)
  Print 1, Allocated(x)
  Allocate(x(3,4))
  Print 1, Allocated(x)
1 Format (1X, 'X is now allocated: ', L1)
End Program

■ Execution Results

 X is now allocated: F
 X is now allocated: T


＜.AND. Example Program＞

Program and_example
  Logical :: op1val(4) = (/ .true.,.true.,.false.,.false. /)
  Logical :: op2val(4) = (/ .true.,.false.,.true.,.false. /)
  Print 1,'Logical Operator Truth Table','.AND.'
1 Format (1x,A,/,/,1X,'Op1',T8,'Op2',T14,A)
  Do i=1,4
    Print 2,op1val(i),op2val(i),op1val(i).And.op2val(i)
2   Format(T4,L1,T9,L1,T15,L1)
  End Do
End Program

■ Execution Results

 Logical Operator Truth Table

 Op1   Op2   .AND.
   T    T     T
   T    F     F
   F    T     F
   F    F     F


＜ANINT Example Program＞

Program anint_example
  Call test( [ 10.49,10.50,10.51 ] )
Contains
  Subroutine test(a)
    Real,Intent(In) :: a(:)
    Print 1,a,Anint(a)
 1  Format(3F8.2,/,3F8.2)
    Print 1,-a,Anint(-a)
  End Subroutine
End Program

■ Execution Results

   10.49   10.50   10.51
   10.00   11.00   11.00
  -10.49  -10.50  -10.51
  -10.00  -11.00  -11.00


＜ANY Example Program＞

Program any_example
  Real, Dimension(2,3) :: a, b
  a = Reshape( (/2.,3.,5.,-1.,4.,-3./), (/2,3/))
  b = Reshape( (/9.,9.,5.,-1.,0.,-3./), (/2,3/))
  Print *, Any(a==b)
  Print *, Any(a==b,1)
  Print *, Any(Mask=a.Eq.b,Dim=2)
End Program

■ Execution Results

 T
 F T T
 T T


＜ASIN Example Program＞

Program asin_example
  Real, Dimension(2,3) :: a
  Complex, Dimension(3) :: c
  a = Reshape( [ 0.0,-0.2,0.3,-0.4,0.5,1.0 ], [ 2,3 ])
  c = [ (.2,.3),(.5,-.1),(.4,-.3) ]
  Print 1, Asin(a)
1 Format(6(2X,F0.5))
  Print 2, Asin(c)
2 Format(3(2X,'(',F0.5,',',F0.5,')'))
End Program

■ Execution Results

  .00000  -.20136  .30469  -.41152  .52360  1.57080
  (.19245,.30107)  (.51981,-.11497)  (.39032,-.31896)


＜ASINH Example Program＞

Program asinh_example
  Real, Dimension(2,3) :: a
  Complex, Dimension(3) :: c
  a = Reshape( [ 1.0,-1.25,2.5,5.8,-15.,27.5 ], [ 2,3 ])
  c = [ (.2,.3),(.5,-.1),(4.,-3.5) ]
  Print 1, Asinh(a)
1 Format(6(2X,F0.5))
  Print 2, Asinh(c)
2 Format(3(2X,'(',F0.5,',',F0.5,')'))
End Program

■ Execution Results

  .88137  -1.04759  1.64723  2.45836  -3.40231  4.00766
  (.20773,.29803)  (.48301,-.08949)  (2.36498,-.71009)


＜ASSIGN Example Program＞

Program assign_example
  Integer format,branch
  Assign 1 To format
  Print format
  Assign 2 To branch
  Go To branch
  Stop 'Impossible'
1 Format(1X,'This is an example of ASSIGN format.')
2 Print *,'Arrived at ASSIGNed branch'
End Program

■ Execution Results

 This is an example of ASSIGN format.
 Arrived at ASSIGNed branch


＜ASSOCIATE Example Program＞

Module associate_example_module
  Type item_type
    Character(:),Allocatable :: name
    Real cost
    Integer number
  End Type
  Type(item_type),Allocatable :: stock(:)
Contains
  Subroutine create_base_stock
    stock = [ item_type('Something cheap', 1.5, 100), &
              item_type('Something expensive', 2500.17, 10), &
              item_type('Something else', 12.50, 2) ]
  End Subroutine
End Module
Program associate_example
  Use associate_example_module
  Call create_base_stock
  Do i=1,Size(stock)
    Associate(item=>stock(i), number_to_buy=>3)
      If (item%number>=number_to_buy) Then
        item%number = item%number - number_to_buy
        Print 1,number_to_buy,item%name,item%cost
1       Format(1X,'Bought ',I0,' "',A,'" at $',F0.2)
      Else
        Print 2,number_to_buy,item%name
2       Format(1X,'Could not buy ',I0,' of "',A,'"')
      End If
    End Associate
  End Do
End Program

■ Execution Results

 Bought 3 "Something cheap" at $1.50
 Bought 3 "Something expensive" at $2500.17
 Could not buy 3 of "Something else"


＜ASSOCIATED Example Program＞

Program associated_example
  Integer, Pointer :: i(:,:)
  Integer, Target :: j(2,2), k(2,3)
  j = 1
  k = 3
  i => j
  Print *, Associated(i), i
  Nullify (i)
  Print *, Associated(i)
  i => k
  Print *, Associated(i,j), Associated(i,k), i
End

■ Execution Results

 T 1 1 1 1
 F
 F T 3 3 3 3 3 3


＜ASYNCHRONOUS Example Program＞

Program asynchronous_attribute_example
  Real,Asynchronous :: a(100,2)
  Logical finished
  Open (17,File='Results',Form='Unformatted',Asynchronous='Yes')
  Do
    Call produce_results(a(:,1),finished)
    Call write_results(a(:,1))
    If (finished) Exit
    Call produce_results(a(:,2),finished)
    Call write_results(a(:,2))
    If (finished) Exit
  End Do
Contains
  Subroutine produce_results(vector,finished)
    Real,Intent(Out) :: vector(:)
    Logical,Intent(Out) :: finished
    Call Random_Number(vector)
    finished = vector(1)<0.1
  End Subroutine
  Subroutine write_results(vector)
    Real,Asynchronous,Intent(In) :: vector(:)
    Wait (17)
    Write (17,Asynchronous='Yes') vector
  End Subroutine
End Program

＜Comments＞

The use of the ASYNCHRONOUS attribute allows the overlap of the writing of one set of results while computing the next. The WAIT statement in WRITE_RESULTS waits for the previous output to unit 17 to finish, thus ensuring that the previous VECTOR can be re-used for computation.

The ASYNCHRONOUS attribute is needed to tell the compiler that A is subject to asynchronous input/output; this information prevents unsafe optimisations.


＜ASYNCHRONOUS= Example Program＞

Program asynchronous_specifier_example
  Real,Asynchronous :: a(100,2)
  Logical finished
  Open (17,File='Results',Form='Unformatted',Asynchronous='Yes')
  Do
    Call produce_results(a(:,1),finished)
    Call write_results(a(:,1))
    If (finished) Exit
    Call produce_results(a(:,2),finished)
    Call write_results(a(:,2))
    If (finished) Exit
  End Do
Contains
  Subroutine produce_results(vector,finished)
    Real,Intent(Out) :: vector(:)
    Logical,Intent(Out) :: finished
    Call Random_Number(vector)
    finished = vector(1)<0.1
  End Subroutine
  Subroutine write_results(vector)
    Real,Asynchronous,Intent(In) :: vector(:)
    Wait (17)
    Write (17,Asynchronous='Yes') vector
  End Subroutine
End Program

＜Comments＞

The use of the ASYNCHRONOUS= specifier allows the overlap of the writing of one set of results while computing the next. The WAIT statement in WRITE_RESULTS waits for the previous output to unit 17 to finish, thus ensuring that the previous VECTOR can be re-used for computation.

The ASYNCHRONOUS attribute is needed to tell the compiler that A is subject to asynchronous input/output; this information prevents unsafe optimisations.


＜ATAN Example Program＞

Program atan_example
  Real, Dimension(2,3) :: a
  Complex, Dimension(3) :: c
  a = Reshape( [ 0.0,-0.2,0.5,-1.4,2.5,100. ], [ 2,3 ])
  c = [ (.2,.3),(5.5,-.1),(4.4,-1.3) ]
  Print 1, Atan(a)
1 Format(6(2X,F0.5))
  Print 2, Atan(c)
2 Format(3(2X,'(',F0.5,',',F0.5,')'))
End Program

■ Execution Results

  .00000  -.19740  .46365  -.95055  1.19029  1.56080
  (.21547,.29575)  (1.39100,-.00320)  (1.36400,-.05923)


＜ATAN2 Example Program＞

Program atan2_example
  Real, Dimension(2,3) :: a, b, c
  a = Reshape( [ 0.0,0.5,-0.8,1.6,-2.8,2.8 ], [ 2,3 ])
  Print 1, a
  b = Sin(a)
  Print 1, b
  c = Cos(a)
  Print 1, c
  Print 1, Atan2(b,c)
1 Format(6(2X,F8.5))
End Program

■ Execution Results

   0.00000   0.50000  -0.80000   1.60000  -2.80000   2.80000
   0.00000   0.47943  -0.71736   0.99957  -0.33499   0.33499
   1.00000   0.87758   0.69671  -0.02920  -0.94222  -0.94222
   0.00000   0.50000  -0.80000   1.60000  -2.80000   2.80000


＜ATANH Example Program＞

Program atanh_example
  Real, Dimension(2,3) :: a
  Complex, Dimension(3) :: c
  a = Reshape( [ 0.0,-0.2,0.3,-0.4,0.5,0.99 ], [ 2,3 ])
  c = [ (.2,.3),(.5,-.1),(.4,-.3) ]
  Print 1, Atanh(a)
1 Format(6(2X,F0.5))
  Print 2, Atanh(c)
2 Format(3(2X,'(',F0.5,',',F0.5,')'))
End Program

■ Execution Results

  .00000  -.20273  .30952  -.42365  .54931  2.64665
  (.18499,.30187)  (.54061,-.13198)  (.37909,-.33737)


＜ATOMIC_ADD Example Program＞

Module stopping
  Use iso_fortran_env
  Integer(atomic_int_kind),Private :: nfinished[*] = 0
Contains
  Subroutine i_am_finished
    CALL atomic_add(nfinished[1],1)
  End Subroutine
  Logical Function all_finished()
    Integer(atomic_int_kind) res
    Call atomic_ref(res,nfinished[1])
    all_finished = res==Num_Images()
  End Function
End Module
Program atomic_add_example
  Use stopping
  Logical :: finished = .False.
  ! All images will execute until finished.
  ! There is no synchronisation between images.
  Do
    Call do_some_work(finished)
    If (finished) Then
      Call i_am_finished
      Exit
    End If
  End Do
  If (This_Image()==1) Then
    Do While (.Not.all_finished())
      Sync Memory
    End Do
    ! In principle we could do something with the results,
    ! but this is just a simple example.
    Print *,'All finished'
  End If
Contains
  Subroutine do_some_work(done)
    Logical,Intent(Out) :: done
    Real x
    ! Because this is an example, we don't actually do any work.
    ! We just randomly (1%) set the done flag.
    Call random_number(x)
    done = x>0.99
  End Subroutine
End Program

■ Execution Results

 All finished


＜ATOMIC_AND Example Program＞

Module stopping
  Use iso_fortran_env
  Integer,Parameter :: ntasks = 25
  ! This only works for ntasks up to Bit_Size(0_atomic_int_kind)-1.
  Integer(atomic_int_kind) :: imask[*] = 2**ntasks - 1
Contains
  Subroutine task_finished(tasknum)
    Integer,Intent(In) :: tasknum
    CALL atomic_and(imask[1],Ibclr(Not(0),tasknum-1))
  End Subroutine
  Logical Function all_finished()
    Integer(atomic_int_kind) res
    Call atomic_ref(res,imask[1])
    all_finished = res==0
  End Function
End Module
Program atomic_and_example
  Use stopping
  Logical :: finished = .False.
  Integer mytask
  ! All images will execute until finished.
  mytask = This_Image()
  Do While (mytask<=ntasks)
    Call do_task(mytask,finished)
    If (finished) Then
      Call task_finished(mytask)
      mytask = mytask + Num_Images()
    End If
  End Do
  If (This_Image()==1) Then
    Do While (.Not.all_finished())
      Sync Memory
    End Do
    ! In principle we could do something with the results,
    ! but this is just a simple example.
    Print *,'All finished'
  End If
Contains
  Subroutine do_task(tasknum,done)
    Integer,Intent(In) :: tasknum
    Logical,Intent(Out) :: done
    Real x(tasknum)
    ! Because this is an example, we don't actually do any work.
    ! We just randomly (1% per element, i.e. approx tasknum%) set the done flag.
    Call random_number(x)
    done = Any(x>0.99)
  End Subroutine
End Program

■ Execution Results

 All finished


＜ATOMIC_CAS Example Program＞

Module value_module
  Use iso_fortran_env
  Integer(atomic_int_kind) :: value[*] = 1
End Module
Program atomic_cas_example
  Use value_module
  ! Images compete by calculating the a possible next value for VALUE.
  ! Whichever image wins the compare-and-swap replaces the value and prints it.
  Integer(atomic_int_kind) newvalue,oldvalue,valuewas
  Logical me
  oldvalue = 1
  Do
    newvalue = calculate_new_value(oldvalue)
    Call atomic_cas(Atom=value[1],New=newvalue,Old=valuewas,Compare=oldvalue)
    me = oldvalue==valuewas
    If (me) Then
      oldvalue = newvalue
      Print 1,This_Image(),newvalue
1     Format(1X,'Image ',I0,' calculated the new value to be ',I0)
    Else
      oldvalue = valuewas
    End If
    If (oldvalue>2**24) Exit
  End Do
  If (me) Then
    Print *,'End of sequence'
  End If
Contains
  Integer(atomic_int_kind) Function calculate_new_value(old)
    Integer(atomic_int_kind),Intent(In) :: old
    calculate_new_value = old**2 - old + 3
  End Function
End Program

■ Execution Results

 Image 2 calculated the new value to be 3
 Image 2 calculated the new value to be 5553
 Image 3 calculated the new value to be 75
 Image 4 calculated the new value to be 30830259
 End of sequence
 Image 1 calculated the new value to be 9

(This is with four images. The mixing of output records from the different images is indeterminate.)


＜ATOMIC_DEFINE Example Program＞

Module stopping
  Use iso_fortran_env
  Logical(atomic_logical_kind),Private :: stop_flag[*] = .False.
Contains
  Subroutine make_it_stop
    CALL atomic_define(stop_flag[1],.TRUE._atomic_logical_kind)
  End Subroutine
  Logical(atomic_logical_kind) Function please_stop()
    Call atomic_ref(please_stop,stop_flag[1])
  End Function
End Module
Program atomic_define_example
  Use stopping
  Logical :: finished = .False.
  ! All images will execute until one decides we are finished.
  ! There is no synchronisation between images.
  Do
    Call do_some_work(finished)
    If (finished) Call make_it_stop
    ! All images will (eventually) exit if anyone calls "make_it_stop".
    If (please_stop()) Exit
  End Do
  Print *,'Stopped'
Contains
  Subroutine do_some_work(done)
    Logical,Intent(Out) :: done
    Real x
    ! Because this is an example, we don't actually do any work.
    ! We just randomly (1%) set the done flag.
    Call random_number(x)
    done = x>0.99
  End Subroutine
End Program

■ Execution Results

 Stopped


＜ATOMIC_FETCH_ADD Example Program＞

Program atomic_fetch_add_example
  Use iso_fortran_env
  Implicit None
  Integer(atomic_int_kind) :: nexttask[*] = 1, task
  Integer i
  Integer :: task_done_by(1000)[*] = 0
  Do
    Call atomic_fetch_add(nexttask[1],1,task)
    If (task>1000) Exit
    Call do_task(task)
  End Do
  Sync All
  If (This_Image()==1) Then
    Do i=1,Num_Images()
      Print *,Count(task_done_by==i),'tasks done by image',i
    End Do
  End If
Contains
  Subroutine do_task(num)
    Integer(atomic_int_kind),Intent(In) :: num
    ! This is where we would do the work, if this were not an example.
    task_done_by(num)[1] = This_Image()
  End Subroutine
End Program

■ Execution Results

(Possible results with four images.)
 707 tasks done by image 1
 124 tasks done by image 2
 142 tasks done by image 3
  27 tasks done by image 4


＜ATOMIC_FETCH_AND Example Program＞

Program atomic_fetch_and_example
  Use iso_fortran_env
  Implicit None
  Integer,Parameter :: ntasks = 12345
  Integer,Parameter :: tasks_per_word = Bit_Size(0_atomic_int_kind)
  Integer,Parameter :: nwords = (ntasks+tasks_per_word-1)/tasks_per_word
  Integer(atomic_int_kind) taskmask(nwords)[*],oldmask,taskbit,taskcount[*]
  Integer i,j
  If (This_Image()==1) Then
    taskmask(:nwords-1) = Not(0_atomic_int_kind)
    taskmask(nwords) = Maskr(ntasks-(nwords-1)*tasks_per_word,atomic_int_kind)
    taskcount = 0
  End If
  Sync All
  Do i=1,nwords
    Do j=1,tasks_per_word
      taskbit = Shiftl(1_atomic_int_kind,j-1)
      Call atomic_fetch_and(taskmask(i)[1],Not(taskbit),oldmask)
      If (Iand(taskbit,oldmask)==taskbit) Then
        ! Do task (i,j).
        ! Since this is an example, we just add one to the task count.
        Call atomic_add(taskcount[1],1)
      End If
    End Do
  End Do
  Sync All
  If (This_Image()==1) Then
    Print *,taskcount,'tasks completed.'
  End If
End Program

■ Execution Results

 12345 tasks completed.


＜ATOMIC_FETCH_OR Example Program＞

Program atomic_fetch_or_example
  Use iso_fortran_env
  Implicit None
  Integer(atomic_int_kind) :: bits(100)[*] = 0, bit, oldbits
  Integer i,j
  ! Demonstrate setting individual bits in a bitmask without interference between images.
  ! The FETCH form is used to check that the bit was not already set.
  Do i=1,Size(bits)
    Do j=This_Image(),Bit_Size(bits),Num_Images()
      bit = Shiftl(1_atomic_int_kind,j-1)
      Call atomic_fetch_or(bits(i)[1],bit,oldbits)
      If (Iand(oldbits,bit)/=0) Error Stop 'Bit already set'
    End Do
  End Do
  Sync All
  If (This_Image()==1) Then
    Do i=1,Size(bits)
      If (bits(i)/=Not(0)) Error Stop 'Bit not set'
    End Do
    Print *,'Bits set as expected.'
  End If
End Program

■ Execution Results

 Bits set as expected.


＜ATOMIC_FETCH_XOR Example Program＞

Program atomic_fetch_xor_example
  Use iso_fortran_env
  Implicit None
  Integer(atomic_int_kind) :: result[*] = 0
  ! Exclusive-or all the integers from 1 to 1000,000,000,
  ! sharing the work across all images.
  Integer(atomic_int_kind),Parameter :: target = 1000000000
  Integer(atomic_int_kind) :: i,from,to,n,was,tmp
  n = target / Num_Images()
  from = (This_Image()-1)*n + 1
  If (This_Image()==Num_Images()) Then
    to = target
  Else
    to = This_Image()*n
  End If
  tmp = from
  Do i=from+1,to
    tmp =Ieor(tmp,i)
  End Do
  Call atomic_fetch_xor(result[1],tmp,was)
  Print 1,This_Image(),tmp,was,Ieor(was,tmp)
1 Format(1X,'Image ',I0,' x-or ',Z0,' changing ',Z0,' to ',Z0)
  Sync All
  If (This_Image()==1) Print 2,result
2 Format(1X,'Final result was ',Z0)
End Program

■ Execution Results

(Possible results with four images.)
 Image 3 x-or 31797280 changing 0 to 31797280
 Image 4 x-or 172EDD80 changing 31797280 to 2657AF00
 Image 2 x-or 132BD780 changing 2657AF00 to 357C7880
 Image 1 x-or EE6B280 changing 357C7880 to 3B9ACA00
 Final result was 3B9ACA00


＜ATOMIC_OR Example Program＞

Module stopping
  Use iso_fortran_env
  Integer,Parameter :: ntasks = 25
  ! This only works for ntasks up to Bit_Size(0_atomic_int_kind)-1.
  Integer(atomic_int_kind) :: imask[*] = 0
Contains
  Subroutine task_finished(tasknum)
    Integer,Intent(In) :: tasknum
    CALL atomic_or(imask[1],2**(tasknum-1))
  End Subroutine
  Logical Function all_finished()
    Integer(atomic_int_kind) res
    Call atomic_ref(res,imask[1])
    all_finished = res==2**ntasks - 1
  End Function
End Module
Program atomic_or_example
  Use stopping
  Logical :: finished = .False.
  Integer mytask
  ! All images will execute until finished.
  mytask = This_Image()
  Do While (mytask<=ntasks)
    Call do_task(mytask,finished)
    If (finished) Then
      Call task_finished(mytask)
      mytask = mytask + Num_Images()
    End If
  End Do
  If (This_Image()==1) Then
    Do While (.Not.all_finished())
      Sync Memory
    End Do
    ! In principle we could do something with the results,
    ! but this is just a simple example.
    Print *,'All finished'
  End If
Contains
  Subroutine do_task(tasknum,done)
    Integer,Intent(In) :: tasknum
    Logical,Intent(Out) :: done
    Real x(tasknum)
    ! Because this is an example, we don't actually do any work.
    ! We just randomly (1% per element, i.e. approx tasknum%) set the done flag.
    Call random_number(x)
    done = Any(x>0.99)
  End Subroutine
End Program

■ Execution Results

 All finished


＜ATOMIC_REF Example Program＞

Module stopping
  Use iso_fortran_env
  Logical(atomic_logical_kind),Private :: stop_flag[*] = .False.
Contains
  Subroutine make_it_stop
    CALL atomic_define(stop_flag[1],.TRUE._atomic_logical_kind)
  End Subroutine
  Logical(atomic_logical_kind) Function please_stop()
    Call atomic_ref(please_stop,stop_flag[1])
  End Function
End Module
Program atomic_ref_example
  Use stopping
  Logical :: finished = .False.
  ! All images will execute until one decides we are finished.
  ! There is no synchronisation between images.
  Do
    Call do_some_work(finished)
    If (finished) Call make_it_stop
    ! All images will (eventually) exit if anyone calls "make_it_stop".
    If (please_stop()) Exit
  End Do
  Print *,'Stopped'
Contains
  Subroutine do_some_work(done)
    Logical,Intent(Out) :: done
    Real x
    ! Because this is an example, we don't actually do any work.
    ! We just randomly (1%) set the done flag.
    Call random_number(x)
    done = x>0.99
  End Subroutine
End Program

■ Execution Results

 Stopped


＜ATOMIC_XOR Example Program＞

Module taskmanager
  Use iso_fortran_env
  Integer(atomic_int_kind) :: ntasks[*] = 2
  Integer,Parameter :: maxtasks = 30
  ! This only works for ntasks up to Bit_Size(0_atomic_int_kind)-1.
  Integer(atomic_int_kind) :: imask[*] = 0
Contains
  Subroutine task_finished(tasknum)
    Integer,Intent(In) :: tasknum
    CALL atomic_xor(imask[1],2**(tasknum-1))
  End Subroutine
  Logical Function task_available(tasknum)
    Integer,Intent(In) :: tasknum
    Integer check,n
    Call atomic_ref(n,ntasks[1])
    If (tasknum>n) Then
      task_available = .False.
    Else
      Call atomic_ref(check,imask[1])
      task_available = .Not.Btest(check,tasknum-1)
    End If
  End Function
  Subroutine newtask
    Integer m
    Call atomic_ref(m,ntasks[1])
    If (m<maxtasks) Call atomic_define(ntasks[1],m+1)
  End Subroutine
  Logical Function all_finished()
    Integer(atomic_int_kind) res,n
    Call atomic_ref(res,imask[1])
    Call atomic_ref(n,ntasks[1])
    all_finished = res==Maskr(n)
  End Function
End Module
Program atomic_xor_example
  Use taskmanager
  Logical :: finished
  Integer mytask
  ! All images will execute until all are finished.
  mytask = This_Image()
  Do
    If (task_available(mytask)) Then
      Call do_task(mytask,finished)
      If (finished) Then
        Call task_finished(mytask)
        mytask = mytask + Num_Images()
      End If
    Else
      If (all_finished()) Exit
      Sync Memory ! Not needed, just to take some time.
    End If
  End Do
  If (This_Image()==1) Then
    ! In principle we could do something with the results,
    ! but this is just a simple example.
    Call atomic_ref(mytask,ntasks)
    Print *,mytask,'tasks finished'
  End If
Contains
  Subroutine do_task(tasknum,done)
    Integer,Intent(In) :: tasknum
    Logical,Intent(Out) :: done
    Real x(tasknum)
    ! Because this is an example, we don't actually do any work.
    ! We just randomly (1% per element, i.e. approx tasknum%) set the done flag.
    ! 10% of the time we also spawn a new task (up to the maximum).
    Call random_number(x)
    If (Any(x>0.9)) Call newtask
    done = Any(x>0.99)
  End Subroutine
End Program

■ Execution Results

 30 tasks finished


＜BACKSPACE Example Program＞

Program backspace_example
  Character(80) :: line
  Open (17,File='INPUT.DAT',Status='OLD',Position='REWIND')
  Do
    Read (17,'(A)',End=1) line
  End Do
1 Continue
  Backspace 17
  Write (17,'(A)') '999'
  Rewind 17
  Do
    Read (17,'(A)',End=2) line
    Print *,Trim(line)
  End Do
2 Close (17)
End Program

＜File: INPUT.DAT＞

1
2
5

■ Execution Results

 1
 2
 5
 999


＜BESSEL_J0 Example Program＞

Program bessel_j0_example
  Implicit None
  Integer i
  Real :: x(8) = [ (i*0.5,i=1,8) ]
  Print 1, x
  Print 1, Bessel_J0(x)
1 Format(999F9.3)
End Program

■ Execution Results

    0.500    1.000    1.500    2.000    2.500    3.000    3.500    4.000
    0.938    0.765    0.512    0.224   -0.048   -0.260   -0.380   -0.397


＜BESSEL_J1 Example Program＞

Program bessel_j1_example
  Implicit None
  Integer i
  Real :: x(8) = [ (i*0.5,i=1,8) ]
  Print 1, x
  Print 1, Bessel_J1(x)
1 Format(999F9.3)
End Program

■ Execution Results

    0.500    1.000    1.500    2.000    2.500    3.000    3.500    4.000
    0.242    0.440    0.558    0.577    0.497    0.339    0.137   -0.066


BESSEL_JN example program

＜BESSEL_JN Example Program 1＞

Program bessel_jn_example_1
  Implicit None
  Integer i
  Real :: x(8) = [ (i*0.5,i=1,8) ]
  Print 1, x
  ! Elemental over X.
  Print 1, Bessel_JN(3,x)
1 Format(999F9.3)
End Program

■ Execution Results

    0.500    1.000    1.500    2.000    2.500    3.000    3.500    4.000
    0.003    0.020    0.061    0.129    0.217    0.309    0.387    0.430

＜BESSEL_JN Example Program 2＞

Program bessel_jn_example_2
  Implicit None
  Integer i
  Real :: x = 2.5
  Integer :: n(8) = [ 1,3,5,7,11,13,17,19 ]
  Print 1, (n(i),x,i=1,8)
1 Format(999(1X,'J',I2.2,'(',F3.1,')',:))
  ! Elemental over N.
  Print 2, Bessel_JN(n,x)
2 Format(999F9.5)
End Program

■ Execution Results

 J01(2.5) J03(2.5) J05(2.5) J07(2.5) J11(2.5) J13(2.5) J17(2.5) J19(2.5)
  0.49709  0.21660  0.01950  0.00078  0.00000  0.00000  0.00000  0.00000

＜BESSEL_JN Example Program 3＞

Program bessel_jn_example_3
  Implicit None
  Integer i
  Real :: x = 2.5
  Print 1, (i,x,i=1,7)
1 Format(999(2X,'J',I1,'(',F3.1,')',:))
  ! Transformational.
  Print 2, Bessel_JN(1,7,x)
2 Format(999F9.5)
End Program

■ Execution Results

  J1(2.5)  J2(2.5)  J3(2.5)  J4(2.5)  J5(2.5)  J6(2.5)  J7(2.5)
  0.49709  0.44606  0.21660  0.07378  0.01950  0.00422  0.00077


＜BESSEL_Y0 Example Program＞

Program bessel_y0_example
  Implicit None
  Integer i
  Real :: x(8) = [ (i*0.5,i=1,8) ]
  Print 1, x
  Print 1, Bessel_Y0(x)
1 Format(999F9.3)
End Program

■ Execution Results

    0.500    1.000    1.500    2.000    2.500    3.000    3.500    4.000
   -0.445    0.088    0.382    0.510    0.498    0.377    0.189   -0.017


＜BESSEL_Y1 Example Program＞

Program bessel_y1_example
  Implicit None
  Integer i
  Real :: x(8) = [ (i*0.5,i=1,8) ]
  Print 1, x
  Print 1, Bessel_Y1(x)
1 Format(999F9.3)
End Program

■ Execution Results

    0.500    1.000    1.500    2.000    2.500    3.000    3.500    4.000
   -1.471   -0.781   -0.412   -0.107    0.146    0.325    0.410    0.398


BESSEL_YN Example Program

＜BESSEL_YN Example Program 1＞

Program bessel_yn_example_1
  Implicit None
  Integer i
  Real :: x(8) = [ (i*0.5,i=1,8) ]
  Print 1, x
  ! Elemental over X.
  Print 1, Bessel_YN(3,x)
1 Format(999F9.3)
End Program

■ Execution Results

    0.500    1.000    1.500    2.000    2.500    3.000    3.500    4.000
  -42.059   -5.822   -2.074   -1.128   -0.756   -0.539   -0.358   -0.182

＜BESSEL_YN Example Program 2＞

Program bessel_yn_example_2
  Implicit None
  Integer i
  Real :: x = 9.5
  Integer :: n(7) = [ 1,3,5,7,11,13,17 ]
  Print 1, (n(i),x,i=1,Size(n))
1 Format(999(2X,'J',I2.2,'(',F3.1,')',:))
  ! Elemental over N.
  Print 2, Bessel_YN(n,x)
2 Format(999F10.5)
End Program

■ Execution Results

  J01(9.5)  J03(9.5)  J05(9.5)  J07(9.5)  J11(9.5)  J13(9.5)  J17(9.5)
   0.20318  -0.25726   0.22859   0.11835  -0.64735  -2.01846 -92.43208

＜BESSEL_YN Example Program 3＞

Program bessel_yn_example_3
  Implicit None
  Integer i
  Real :: x = 2.5
  Print 1, (i,x,i=1,7)
1 Format(999(3X,'J',I1,'(',F3.1,')',:))
  ! Transformational.
  Print 2, Bessel_YN(1,7,x)
2 Format(999F10.5)
End Program

■ Execution Results

   J1(2.5)   J2(2.5)   J3(2.5)   J4(2.5)   J5(2.5)   J6(2.5)   J7(2.5)
   0.14592  -0.38134  -0.75606  -1.43320  -3.83018 -13.88751 -62.82986


＜BGE Example Program＞

Program bge_example
  Integer,Parameter :: i8 = Selected_Int_Kind(2)
  Integer(i8) :: a(3) = [ Int(z'ff',i8),Int(z'7f',i8),Int(z'0f',i8) ]
  Print *,Bge(127,a)
End Program

■ Execution Results

  F T T


＜BGT Example Program＞

Program bgt_example
  Integer,Parameter :: i8 = Selected_Int_Kind(2)
  Integer(i8) :: a(3) = [ Int(z'ff',i8),Int(z'7f',i8),Int(z'0f',i8) ]
  Print *,Bgt(127,a)
End Program

■ Execution Results

  F F T


BIND Example Programs

＜BIND Example Program 1＞

!
! Demonstrates declaring and invoking a C procedure from Fortran.
!
Program bind_example_1
  Use Iso_C_Binding,Only:C_double
  Interface
    !
    ! This is for hypot from "libm".
    !
    Function hypotenuse(x,y) Bind(C,Name='hypot')
      Use Iso_C_Binding
      Real(C_double),Value :: x,y
      Real(C_double) :: hypotenuse
    End Function
  End Interface
  Print 1,0.3d0,0.4d0,hypotenuse(0.3_C_double,0.4_C_double)
1 Format(1X,'Hypotenuse for ',F0.2,',',F0.2,' is ',F0.2)
End

■ Execution Results

 Hypotenuse for .30,.40 is .50

＜BIND Example Program 2＞

! "ex2_fprog.f90"
! Demonstrates defining a procedure to be invoked from C.
!
! Fortran part.
!
Subroutine real_cshift_for_c(a,n,shift) Bind(C,Name='cshiftf')
  Use Iso_C_Binding
  Intrinsic Cshift
  Integer(C_int),Value :: n,shift
  Real(C_float),Intent(InOut) :: a(n)
  a = cshift(a,shift)
End Subroutine

/* "ex2_cprog.c"
 *
 * C part.
 */
#include <stdio.h>
extern void cshiftf(float *a,int n,int shift);

main()
{
  int i;
  float x[5] = { 1,2,3,4,5 };
  cshiftf(x,5,2);
  for (i=0; i<5; i++) printf(" %5.2f",x[i]);
  putc('\n',stdout);
  return 0;
}

■ Execution Results

 3.00  4.00  5.00  1.00  2.00

＜BIND Example Program 3＞

! "ex3_fprog.f90"
! Demonstrates BIND attribute on a variable.
! Also uses BIND attribute on procedures.
!
! Fortran part.
!
Module c_global_variables
  Use Iso_C_Binding
  Integer(C_long),Bind(C,Name='var1') :: x = 37_C_long
  Integer(C_short),Bind(C) :: y,z
  Interface
    Subroutine c_routine() Bind(C)
    End Subroutine
  End Interface
End Module
Program bind_example_3
  Use c_global_variables
  Call c_routine
  Print *,x,y,z
End Program

/* "ex3_cprog.c"
 *
 * C part.
 */
extern long var1;
short y = 10, z = 0;

void c_routine(void)
{
  z = var1 + 1;
}

■ Execution Results

 37 10 38

＜BIND Example Program 3＞

! "ex4_fprog.f90"
! Demonstrates BIND attribute on a derived type,
! Also uses BIND attribute on procedures.
!
! Fortran part.
!
Module c_struct_defn
  Use Iso_C_Binding
  Type,Bind(C) :: mystruct
    Real(C_float) :: x,y
    Integer(C_int) :: flags(100,200)
    Type(C_ptr) :: name  ! This is actually a char *.
    Type(C_ptr) :: z     ! This is actually a float *.
    Type(C_funptr) :: callback
  End Type
  Interface
    Subroutine init_mystruct(newvar) Bind(C)
      Import mystruct
      Type(mystruct),Intent(Out) :: newvar
    End Subroutine
    Subroutine process_mystruct(var) Bind(C)
      Import mystruct
      Type(mystruct),Value :: var
    End Subroutine
  End Interface
End Module
Program bind_example_4
  Use c_struct_defn
  Type(mystruct) x
  Call init_mystruct(x)
  x%x = 100
  x%y = 140
  Call process_mystruct(x)
End Program

/* "ex4_cprog.c"
 *
 * C part.
 */
#include <stdio.h>

struct mystruct {
  float x,y;
  int flags[200][100];
  char *name;
  float *z;
  void (*callback)(struct mystruct *);
};

void print_my_name(struct mystruct *object)
{
  fputs(object->name,stdout);
}

void init_mystruct(struct mystruct *newvar)
{
  int i,j;
  newvar->x = 0;
  newvar->y = 0;
  for (i=0; i<200; i++) for (j=0; j<100; j++) newvar->flags[i][j] = 0;
  newvar->name = "No name yet";
  newvar->z = (float *)0;
  newvar->callback = &print_my_name;
}

void process_mystruct(struct mystruct var)
{
  int i,j;
  printf("mystruct processing: %f, %f\n",var.x,var.y);
  for (i=0; i<200; i++) for (j=0; j<100; j++) if (var.flags[i][j])
    printf("  flags[%d][%d]==0x%x\n",i,j,var.flags[i][j]);
  if (var.callback) var.callback(&var);
}

■ Execution Results

 mystruct processing: 100.000000, 140.000000
 No name yet


＜BIT_SIZE Example Program＞

Program bit_size_example
  Integer,Parameter :: i8 = Selected_Int_Kind(2)
  Integer(i8),Pointer :: p
  Print *,Bit_Size(p)
End Program

■ Execution Results

 8


＜BLE Example Program＞

Program ble_example
  Integer,Parameter :: i8 = Selected_Int_Kind(2)
  Integer(i8) :: a(3) = [ Int(z'ff',i8),Int(z'7f',i8),Int(z'0f',i8) ]
  Print *,Ble(127,a)
End Program

■ Execution Results

  T T F


＜BLOCK Example Program＞

Program demonstrate_block
  Implicit None
  Integer i,tmp
  Real :: a(10) = [ (i,i=1,10) ]
  Real :: b(10) = 100
  tmp = 42
  Do i=1, Size(a)
    Block
      Real tmp
      tmp = a(i)**3
      If (tmp>b(i)) b(i) = tmp
    End Block
  End Do
  ! The outer "tmp" is unaffected by the inner one.
  Print 1, tmp, b
1 Format(1X,I0,10F7.1)
End Program

■ Execution Results

 42  100.0  100.0  100.0  100.0  125.0  216.0  343.0  512.0  729.0 1000.0


＜BLOCK DATA Example Program＞

Program blockdata_example
  Common /abc/ a(3)
  Call suba
  Print '(3F7.2)', a
End Program
Subroutine suba
  Common /abc/ a(3)
  a = a*10.5
End Program
Block Data xyz
  Common /abc/ a(3)
  Data a/1., 2., 3./
End Block Data

■ Execution Results

  10.50  21.00  31.50


＜BLT Example Program＞

Program blt_example
  Integer,Parameter :: i8 = Selected_Int_Kind(2)
  Integer(i8) :: a(3) = [ Int(z'ff',i8),Int(z'7f',i8),Int(z'0f',i8) ]
  Print *,Blt(127,a)
End Program

■ Execution Results

  T F F


＜BTEST Example Program＞

Program btest_example
  Integer :: k = Ibset(5, 10)
  Do i=0, Bit_Size(k)-1
    If (Btest(k, i)) Then
      Print 1, i
1     Format(1X, 'Bit ', I0, ' is set')
    End If
  End Do
End Program

■ Execution Results

 Bit 0 is set
 Bit 2 is set
 Bit 10 is set


＜Array Section Example Program＞

Program array_section_example
  Real a(5)
  a(5:1:-1) = (/ 3.,4.,5.,6.,7. /)
  Print *, a(2:3)
End Program

■ Execution Results

  6.0000000   5.0000000


＜CALL Example Program＞

Program call_example
  Call shiki(1.0,3.0,2.0,x1,x2)
  Print *,x1,x2
End Program
Subroutine shiki(a,b,c,x1,x2)
  Intent(In) :: a,b,c
  Intent(Out) :: x1,x2
  d = b**2 - 4.0*a*c
  If (d > 0.) Then
    x1 = (-b+Sqrt(d))/(2.0*a)
    x2 = (-b-Sqrt(d))/(2.0*a)
  End If
End Subroutine shiki

■ Execution Results

  -1.0000000  -2.0000000


＜CASE Example Program＞

Program case_example
  Integer :: i
  Read *, i
  Select Case (i)
  Case (1)
    Print *, 'one'
  Case (2)
    Print *, 'two'
  End Select
End Program

＜Example input 1＞

1

■ Execution Results

 one

＜Example input 2＞

2

■ Execution Results

 two


＜CASE DEFAULT Example Program＞

Program case_default_example
  Integer :: i
  Read *, i
  Select Case (i)
  Case (1:)
    Print *, 'I>0'
  Case (:-1)
    Print *, 'I<0'
  Case Default
    Print *, 'I=0'
  End Select
End Program

＜Example input 1＞

1

■ Execution Results

 I>0

＜Example input 2＞

-2

■ Execution Results

 I<0

＜Example input 3＞

0

■ Execution Results

 I=0


＜SELECT CASE Example Program＞

Program case_construct_example
  Integer :: i
  Read *, i
  Select Case (i)
  Case (1)
    Print *, 'one'
  Case (2)
    Print *, 'two'
  End Select
End Program

＜Example input 1＞

1

■ Execution Results

 one

＜Example input 2＞

2

■ Execution Results

 two


＜CEILING Example Program＞

Program ceiling_example
  Call test( [ 10.49,10.50,10.51 ] )
Contains
  Subroutine test(a)
    Real,Intent(In) :: a(:)
    Print 1,a,Ceiling(a)
 1  Format(3F8.2,/,3I8)
    Print 1,-a,Ceiling(-a)
  End Subroutine
End Program

■ Execution Results

   10.49   10.50   10.51
      11      11      11
  -10.49  -10.50  -10.51
     -10     -10     -10


＜CHANGE TEAM Example Program＞

Program change_team_example
  Use Iso_Fortran_Env
  Implicit None
  Integer :: myteamid,i
  Type(team_type) team
  Integer :: temp[*],answer[*] = 0
  If (Num_Images()<4) Error Stop 'Not enough images (need 4)'
  myteamid = (This_Image()+1)/2
  Form Team(myteamid,team)
  Change Team(team)
    If (myteamid==1) Then
      ! Do what team 1 is supposed to do.
      temp = This_Image()**2
      Sync All ! Just syncs team one.
      If (This_Image()==1) answer = temp + temp[2]
    Else If (myteamid==2) Then
      ! Do what team 2 is supposed to do.
      temp = This_Image()**3
      Sync All ! Just syncs team two.
      If (This_Image()==1) answer = temp + temp[2]
    Else
      answer = 0
    End If
  End Team
  If (This_Image()==1) Then
    Do i=2,Num_Images()
      answer = answer + answer[i]
    End Do
    Print *,answer
  End If
End Program

■ Execution Results

 14


CHAR Example Program

＜Example Program＞

Program char_example
  Integer,Parameter :: iso10646 = Selected_Char_Kind('ISO_10646')
  Character(*,iso10646),Parameter :: hello_string = iso10646_'Hello Char'
  Call show([ (Ichar(hello_string(i:i)),i=1,Len(hello_string)) ])
Contains
  Subroutine show(array)
    Integer,Intent(In) :: array(:)
    Print *,(Char(array(i),iso10646),i=1,Size(array))
  End Subroutine
End Program

■ Execution Results

 Hello Char


＜Concatenation Example Program＞

Program concat_example
  Character(20),Parameter :: left(2) = (/ 'First     ','The Second' /)
  Character(20),Parameter :: right(2) = ' Example'
  Do i=1,2
    Print 1,Trim(left(i))//Trim(right(i))
1   Format(1X,'"',A,'"')
  End Do
End Program

■ Execution Results

  "First Example"
  "The Second Example"


＜CHARACTER Example Program＞

Program character_example
  Character(3) :: a
  a = 'ABC'
  Print *, a
End Program

■ Execution Results

 ABC


CLASS Example Programs

＜CLASS Example Program 1＞

Module point_module
  Type point
    Real x,y
  End Type
Contains
  Real Function distance(p)
    Class(point),Intent(In) :: p
    distance = sqrt(p%x**2 + p%y**2)
  End Function
End Module
Program class_specifier_example
  Use point_module
  Type,Extends(point) :: named_point
    Character(80) name
  End Type
  Type(point) :: a = point(3.0,4.0)
  Type(named_point) :: b = named_point(1.0,1.0,'corner')
  Print *,distance(a)
  Print *,distance(b)
End Program

■ Execution Results

   5.0000000
   1.4142135

＜CLASS Example Program 2＞

Module class_star_module
  Type point
    Real x,y
  End Type
Contains
  Subroutine print_value(x)
    Class(*) x
    Select Type (x)
    Type Is (Integer)
      Print *,x
    Type Is (Real)
      Print *,x
    Class Is (point)
      Print *,x%x,x%y
    Class Default
      Print *,'Unknown Type'
    End Select
  End Subroutine
End Module
Program class_star_example
  Use class_star_module
  Call print_value(17)
  Call print_value(1.5)
  Call print_value(point(1,2))
  Call print_value(.true.)
End Program

■ Execution Results

 17
   1.5000000
   1.0000000   2.0000000
 Unknown Type


＜CLOSE Example Program＞

Program close_example
  Character(80) :: line
  Open (1, File='TEMP', Status='OLD', Position='REWIND')
  n_lines = 0
  Do
    Read (1, '(A)', End=100) line
    n_lines = n_lines + 1
  End Do
100 Continue
  Print *, n_lines
  Close (1)
End Program

＜File: TEMP＞

1
2
5

■ Execution Results

 3


CMPLX Example Program

＜Example Program＞

Program cmplx_example
  Real :: a(3) = [ 0.0625,1.5,200.0 ]
  Print 1, Cmplx(a,1)
1 Format(3(2X,'(',F0.5,',',F0.5,')'))
End Program

Results

  (.06250,1.00000)  (1.50000,1.00000)  (200.00000,1.00000)


＜CODIMENSION Example Program＞

Program codimension_example
  Implicit None
  Real, Codimension [*] :: a
  Integer i
  a = This_Image()**2
  Sync All
  If (This_Image()==Num_Images()) Then
    Do i=1, Num_Images()
      Print '(1X,I0,": ",F0.1)',i,a[i]
    End Do
  End If
End Program

■ Execution Results

With the number of images equal to one:
 1: 1.0
With the number of images equal to eight:
 1: 1.0
 2: 4.0
 3: 9.0
 4: 16.0
 5: 25.0
 6: 36.0
 7: 49.0
 8: 64.0


COMMAND_ARGUMENT_COUNT Example Program

＜Example Program＞

Program command_argument_count_example
  Integer i, n
  Character(80) arg
  n = Command_Argument_Count()
  If (n==0) Print *, 'No argument found'
  Do i=1, n
    Call Get_Command_Argument(i,arg)
    Print *, 'Argument',i,'is "',Trim(arg),'"'
  End Do
End Program

■ Execution Results

If invoked with no argument, the results are:

 No argument found

If the program is called “a” and is invoked as “a simple example” the results are:

 Argument 1 is "simple"
 Argument 2 is "example"


＜COMPILER_OPTIONS Example Program＞

Module compiler_info_module
  Use Iso_Fortran_Env, Only:Compiler_Options, Compiler_Version
  Character(Len(Compiler_Version())) :: version = Compiler_Version()
  Character(Len(Compiler_Options())) :: options = Compiler_Options()
End Module
Program compiler_options_example
  Use compiler_info_module
  Print *, 'This was compiled by: ', version
  Print *, 'The compiler options used were: ', options
End Program

＜Results (when compiled with build 6106 of the NAG Fortran Compiler, with the -C=array option.)＞

 This was compiled by: NAG Fortran Compiler Release 6.1(Tozai) Build 6106
 The compiler options used were: -C=array


＜COMPILER_VERSION Example Program＞

Module compiler_info_module
  Use Iso_Fortran_Env, Only:Compiler_Options, Compiler_Version
  Character(Len(Compiler_Version())) :: version = Compiler_Version()
  Character(Len(Compiler_Options())) :: options = Compiler_Options()
End Module
Program compiler_version_example
  Use compiler_info_module
  Print *, 'This was compiled by: ', version
  Print *, 'The compiler options used were: ', options
End Program

＜Results (when compiled with build 6106 of the NAG Fortran Compiler, with the -C=array option.)＞

 This was compiled by: NAG Fortran Compiler Release 6.1(Tozai) Build 6106
 The compiler options used were: -C=array


＜COMPLEX Example Program＞

Program complex_example
  Complex :: a
  a = (1, 2)
  Print *,a
End Program

■ Execution Results

 (1.0000000,2.0000000)


＜CONJG Example Program＞

Program conjg_example
  Complex :: c(3) = [ (1,2),(3,4),(5,6) ]
  Print 1, Conjg(c)
1 Format(3(2X,'(',F0.5,',',F0.5,')'))
End Program

■ Execution Results

  (1.00000,-2.00000)  (3.00000,-4.00000)  (5.00000,-6.00000)


＜CONTAINS Example Program＞

Module example_module
  Real :: a = 10.
Contains
  Subroutine sub1
    a = a + 10
  End Subroutine
End Module
Program contains_example
  Use example_module
  Real :: b=10., c=10.
  Call sub1()
  Call sub2()
  Call sub3(c)
  Print *, a,b,c
Contains
  Subroutine sub2()
    Real b
    b = 175.
  End Subroutine sub2
  Subroutine sub3(c)
    Real c
    c = c + 10.
  End Subroutine sub3
End Program contains_example

■ Execution Results

  20.000000  10.0000000  20.0000000


＜CONTIGUOUS Example Program＞

Program contiguous_example
  Integer :: k(10)
  k = 0
  Print *, 'Old k', k
  Print *, 'Actual is contiguous?', Is_Contiguous(k(::2))
  Call sub(k(::2))
  Print *, 'New k', k
Contains
  Subroutine sub(x)
    Integer, Contiguous :: x(:)
    Print *, 'Dummy is contiguous?', Is_Contiguous(x)
    x = 42
  End Subroutine
End Program

■ Execution Results

 Old k 0 0 0 0 0 0 0 0 0 0
 Actual is contiguous? F
 Dummy is contiguous? T
 New k 42 0 42 0 42 0 42 0 42 0


＜CONTINUE Example Program＞

Program continue_example
    Integer :: i,x
    x = 0
    Do 100 i = 1, 6, 2
        x = x + i
100 Continue
    Print *, x
End Program

■ Execution Results

 9


＜CONVERT= Example Program＞

Program convert_example
  Double Precision :: x(100), y(100)
  ! File "f1.dat" is in big-endian format.
  Open (10,File='f1.dat',Convert='Big_Endian',Form='Unformatted',Status='Old')
  ! File "f2.dat" is in little-endian format.
  Open (11,File='f2.dat',Convert='Little_Endian',Form='Unformatted',Status='Old')
  ! We will write the results in big-endian format.
  Open (12,File='fnew.dat',Convert='Big_Endian',Form='Unformatted',Status='Replace')
  Read (10) x
  Read (11) y
  Write (12) x + y
  ! Files close automatically at the end of the program.
End Program


＜COS Example Program＞

Program cos_example
  Real, Dimension(2,3) :: a
  Complex, Dimension(3) :: c
  a = Reshape( [ 0.0,0.2,-0.4,0.6,-0.8,1.57 ], [ 2,3 ])
  c = [ (.2,.3),(.5,-.1),(.4,-.3) ]
  Print 1, Cos(a)
1 Format(6(2X,F0.5))
  Print 2, Cos(c)
2 Format(3(2X,'(',F0.5,',',F0.5,')'))
End Program

■ Execution Results

  1.00000  .98007  .92106  .82534  .69671  .00080
  (1.02450,-.06050)  (.88197,.04802)  (.96282,.11859)


＜COSH Example Program＞

Program cosh_example
  Real, Dimension(2,3) :: a
  Complex, Dimension(3) :: c
  a = Reshape( [ 0.0,0.2,-0.4,0.6,-1.2,5.7 ], [ 2,3 ])
  c = [ (0.2,0.0),(0.5,-1.5707963),(5.7,1.5707963) ]
  Print 1, Cosh(a)
1 Format(6(2X,F0.5))
  Print 2, Cosh(c)
2 Format(3(2X,'(',F0.5,',',F0.5,')'))
End Program

■ Execution Results

  1.00000  1.02007  1.08107  1.18547  1.81066  149.43535
  (1.02007,.00000)  (.00001,-.52110)  (.00001,149.43199)


COUNT intrinsic function

＜Example Program＞

Program count_example
  Integer, Dimension(2,3) :: a,b
  a = Reshape( (/2,3,5,-1,4,-3/), (/2,3/))
  b = Reshape( (/2,3,5,-1,0,-3/), (/2,3/))
  Print *, Count(a==b)
  Print *, Count(a==b,1)
  Print *, Count(Mask=A==B,Dim=2)
End Program

■ Execution Results

 5
 2 2 1
 2 3


＜CPU_TIME Example Program＞

Program cpu_time_example
  Real x,y
  Integer i
  Call Cpu_Time(x)
  If (x<0) Stop 'No CPU time available'
  Do i=1, Huge(i)
    Call cpu_time(y)
    If (y/=x) Then
      If (y-x>0.01) Then
        Print 1, y-x, 'seconds'
      Else If (y-x>1e-5) Then
        Print 1, 1000*(y-x), 'milliseconds'
      Else
        Print 1, 1e6*(y-x), 'microseconds'
      End If
1     Format(1X,'CPU_TIME clock resolution appears to be ',F0.3,1X,A)
      Stop
    End If
  End Do
  Print *, 'Could not determine the resolution of the CPU_TIME clock'
End Program

■ Execution Results

 CPU_TIME clock resolution appears to be .016 seconds


＜CRITICAL Example Program＞

Module module
  Logical :: finished = .False.
  Integer :: count[*] = 0
Contains
  Subroutine do_some_work
    ! Just increment the count on image one, safely.
    Critical
      ! We only read or write the value of count[1] inside this
      ! Critical block, so only one image at a time.
      If (count[1]==100) Then
        finished = .True.
      Else
        count[1] = count[1] + 1
      End If
    End Critical
  End Subroutine
End Module
Program critical_example
  Use module
  ! All images will do this.
  Do While (.Not.finished)
    Call do_some_work
  End Do
  If (This_Image()==1) Then
    Print 1,count
1   Format(1X,'Finished ',I0,' units of work')
  End If
End Program

■ Execution Results

 Finished 100 units of work


＜CSHIFT Example Program＞

Program cshift_example
  Real, Dimension(2,3) :: a, b, c
  a = Reshape( (/1.,2.,3.,4.,5.,6./), (/2,3/))
  b = Cshift(a,1)
  c = Cshift(a,Shift=1,Dim=2)
  Print *, b( 1,: )
  Print *, b( 2,: )
  Print *
  Print *, c( 1,: )
  Print *, c( 2,: )
End Program

■ Execution Results

  2.0000000   4.0000000   6.0000000
  1.0000000   3.0000000   5.0000000
  3.0000000   5.0000000   1.0000000
  4.0000000   6.0000000   2.0000000


＜CYCLE Example Program＞

Program cycle_example
  Integer :: i
  Do i = 1, 5
    If (Mod(i,2)==0) Cycle
    Print *, i
  End Do
End

■ Execution Results

 1
 3
 5


＜DATA Example Program＞

Program data_example
  Real x
  Integer m(2)
  Data x,m/4.125,123,456/
  Print 1,x,m
1 Format(F10.5,2I5)
End Program

■ Execution Results

   4.12500  123  456


＜DATE_AND_TIME Example Program＞

Program date_and_time_example
  Character date*8, time*10, zone*5
  Integer values(8)
  Call date_and_time(date, time, zone, values)
  Print *, date(:4), '/', date(5:6), '/', date(7:), ' ', &
           time(:2), ':', time(3:4), ':', time(5:), ' ', zone
  Print *, values
End Program

■ Execution Results

 2014/08/09 16:34:26.753 +0900
 2014 8 9 540 16 34 26 753


＜DBLE Example Program＞

Program dble_example
  Complex :: c(3) = [ (1,2),(3,4),(5,6) ]
  Print 1, Dble(13), Dble(c)
1 Format(4(2X,F0.5))
End Program

■ Execution Results

  13.00000  1.00000  3.00000  5.00000


＜DEALLOCATE Example Program＞

Program deallocate_example
  Real, Allocatable :: a(:)
  Read *, n
  Allocate(a(n))
  a(n) = n
  Print *, a(n)
  Deallocate(a)
  Allocate(a(n+3))
  a(n+3) = n + 3
  Print *, a(n+3)
End Program

＜Example input 1＞

4

■ Execution Results

  4.0000000
  7.0000000

＜Example input 2＞

11

■ Execution Results

  11.0000000
  14.0000000


＜DECIMAL= Example Program＞

Program decimal_example
  Write (*,1,Decimal='Point') 1.5,2.5,3.5
1 Format(1X,F5.1,DP,F5.1,DC,F5.1)
  Write (*,1,Decimal='Comma') 1.5,2.5,3.5
End Program

■ Execution Results

   1.5   2.5   3,5
   1,5   2.5   3,5


＜DIGITS Example Program＞

Program digits_example
  Integer,Pointer :: p
  Real,Allocatable :: q
  Double Precision :: d
  Print *,'Default Integer has', Digits(p), 'digits'
  Print *,'Default Real has', Digits(q), 'digits'
  Print *,'Double Precision Real has', Digits(d), 'digits'
End Program

■ Execution Results

 Default Integer has 31 digits
 Default Real has 24 digits
 Double Precision Real has 53 digits


＜DIM Example Program＞

Program dim_example
  Real :: a(2,3) = Reshape( [ 1,2,3,4,5,6 ], [ 2,3 ] )
  Real :: b(2,3) = Reshape( [ 6,5,4,3,2,1 ], [ 2,3 ] )
  Print 1, a - b
  Print 1, Dim(a,b)
  Print *
  Print 1, b - a
  Print 1, Dim(b,a)
1 Format(6(2X,F8.5))
End Program

■ Execution Results

  -5.00000  -3.00000  -1.00000   1.00000   3.00000   5.00000
   0.00000   0.00000   0.00000   1.00000   3.00000   5.00000

   5.00000   3.00000   1.00000  -1.00000  -3.00000  -5.00000
   5.00000   3.00000   1.00000   0.00000   0.00000   0.00000


DIMENSION Example Programs

＜DIMENSION Example Program 1＞

Program dimension_example_1
  Real, Dimension (2,3) :: a
  Do i = 1, 2
    Do j = 1, 3
      a(i,j) = 100*i + j
    End Do
  End Do
  Print *, a(1,3)
End Program

■ Execution Results

   1.0300000E+02

＜DIMENSION Example Program 2＞

Program dimension_example_2
  Real :: a(0:1,0:2)
  Do i = 0, 1
    Do j = 0, 2
      a(i,j) = 100*i + j
    End Do
  End Do
  Print *, a(0,2)
 End Program

■ Execution Results

   2.0000000


DO Example Programs

＜Example Program 1＞

Program do_example_1
  Do i = 1, 5, 2
    Print *, i
  End Do
End Program

■ Execution Results

 1
 3
 5

＜Example Program 2＞

Program do_example_2
  loop: Do i = 5, 1, -2
    Print *, I
  End Do loop
End Program

■ Execution Results

 5
 3
 1

＜Example Program 3＞

Program do_example_3
  i = 2
  Do
    Print *, i
    If (i>100) Exit
    i = i**2
  End Do
End Program

■ Execution Results

 2
 4
 16
 256


＜DO CONCURRENT Example Program＞

Program concurrent_example
  Logical :: m(20)
  m = .True.
  Call test( m, [ 2,3,5,7,11,13,17,19 ] )
Contains
  Subroutine test(pattern,list)
    Logical,Intent(InOut) :: pattern(:)
    Integer,Intent(In) :: list(:)
    ! "list" has no repeated elements, so we can do this safely.
    Do Concurrent (i=1:Size(list))
      pattern(list(i)) = .False.
    End Do
    Print *,pattern
  End Subroutine
End Program

■ Execution Results

 T F F T F T F T T T F T F T T T F T F T


＜DO WHILE Example Program＞

Program do_while_example
  Integer :: x
  x = 0
  Do While (x < 3)
    x = x + 1
    Print *, x
  End Do
End Program

■ Execution Results

 1
 2
 3


＜DOT_PRODUCT Example Program＞

Program dot_product_example
  Real :: a(3), b(3), dot
  a = (/1.,2.,3./)
  b = (/4.,5.,6./)
  dot = Dot_product(a,b)
  Print *,dot
End Program

■ Execution Results

  32.0000000


＜DOUBLE PRECISION Example Program＞

Program double_precision_example
  Double Precision :: a
  a = 1.23456789d0
  Print *,a
End Program

■ Execution Results

   1.2345678899999999


＜DPROD Example Program＞

Program dprod_example
  Real :: a(3) = [ 1.5e-30, 1.5, 1.5e+30 ]
  Real :: b(3) = [ 2.5e-30, 2.5, 2.5e+30 ]
  Print 1, Dprod(a, b)
1 Format(3(2X,ES12.5))
End Program

■ Execution Results

   3.75000E-60   3.75000E+00   3.75000E+60


＜DSHIFTL Example Program＞

Program dshiftl_example
  Integer,Parameter :: i8 = Selected_Int_Kind(2)
  Integer(i8) :: a = Int(z'f0',i8), b = Int(z'70',i8)
  Print 1, 'I', a
1 Format(1X, A, ' = ', B8.8)
  Do i=0,8
    Print 2,i,Dshiftl(a,b,i)
2   Format(I3,2X,B8.8)
  End Do
  Print 1, 'J', b
End Program

■ Execution Results

 I = 11110000
  0  11110000
  1  11100000
  2  11000001
  3  10000011
  4  00000111
  5  00001110
  6  00011100
  7  00111000
  8  01110000
 J = 01110000


＜DSHIFTR Example Program＞

Program dshiftr_example
  Integer,Parameter :: i8 = Selected_Int_Kind(2)
  Integer(i8) :: a = Int(z'2a',i8), b = Int(z'3e',i8)
  Print 1, 'J', b
1 Format(1X, A, ' = ', B8.8)
  Do i=0,8
    Print 2,i,Dshiftr(a,b,i)
2   Format(I3,2X,B8.8)
  End Do
  Print 1, 'I', a
End Program

■ Execution Results

 J = 00111110
  0  00111110
  1  00011111
  2  10001111
  3  01000111
  4  10100011
  5  01010001
  6  10101000
  7  01010100
  8  00101010
 I = 00101010


＜ELEMENTAL Example Program＞

Program elemental_example
  Integer :: a(7) = [ 1, 0, 0, 2, 3, 0, 4 ]
  Where (a>0) a = f(a)
  Print *, a
Contains
  Elemental Integer Function f(i)
    Integer, Intent(In) :: i
    f = 2*i**2 - i**3 + i
  End Function
End Program

■ Execution Results

 2 0 0 2 -6 0 -28


＜ELSE Example Program＞

Program else_example
  Integer :: i
  Read *, i
  If (Mod(i,2)==0) Then
    Print *, 'even'
  Else
    Print *, 'odd'
  End If
End Program

＜Example input 1＞

3

■ Execution Results

 odd

＜Example input 2＞

4

■ Execution Results

 even


＜ELSE IF Example Program＞

Program elseif_example
  Integer :: x
  Read *, x
  If (x>2) Then
    Print *, 'big plus'
  Else If (x<-2) Then
    Print *, 'big minus'
  End If
End Program

＜Example input 1＞

3

■ Execution Results

 big plus

＜Example input 2＞

-4

■ Execution Results

 big minus


＜ELSEWHERE Example Program＞

Program elsewhere_example
  Real a(2,2)
  a = Reshape( (/-1.,2.,3.,4./), (/2,2/) )
  Where (a<0.)
    a = 0.0
  ElseWhere (a>3.)
    a = 1.0
  Elsewhere
    a = 10*a
  End Where
  Print 1, a(1,1),a(1,2)
  Print 1, a(2,1),a(2,2)
1 Format(2F10.4)
End Program

■ Execution Results

    0.0000   30.0000
   20.0000    1.0000


END Example Programs

＜END Example Program 1＞

Program end_example_1
  Real, Dimension(3) :: a, b
  a = (/1.,2.,3./)
  b = 2*a
  Print *, b
End Program end_example_1

■ Execution Results

  2.0000000   4.0000000   6.0000000

＜END Example Program 2＞

  Real :: a=1., b=3., c=2.
  Call shiki(a,b,c,x1,x2)
  Print *, x1,x2
End Program
Subroutine shiki(a,b,c,x1,x2)
  Intent(In) :: a,b,c
  Intent(Out) :: x1,x2
  tmp = Sqrt(b**2 - 4*a*c)
  x1 = (-b+tmp)/(2*a)
  x2 = (-b-tmp)/(2*a)
End Subroutine shiki

■ Execution Results

  -1.0000000  -2.0000000


＜END ASSOCIATE Example Program＞

Module associate_example_module
  Type item_type
    Character(:),Allocatable :: name
    Real cost
    Integer number
  End Type
  Type(item_type),Allocatable :: stock(:)
Contains
  Subroutine create_base_stock
    stock = [ item_type('Something cheap', 1.5, 100), &
              item_type('Something expensive', 2500.17, 10), &
              item_type('Something else', 12.50, 2) ]
  End Subroutine
End Module
Program associate_example
  Use associate_example_module
  Call create_base_stock
  Do i=1,Size(stock)
buy: Associate(item=>stock(i), number_to_buy=>3)
      If (item%number>=number_to_buy) Then
        item%number = item%number - number_to_buy
        Print 1,number_to_buy,item%name,item%cost
1       Format(1X,'Bought ',I0,' "',A,'" at $',F0.2)
      Else
        Print 2,number_to_buy,item%name
2       Format(1X,'Could not buy ',I0,' of "',A,'"')
      End If
    End Associate buy
  End Do
End Program

■ Execution Results

 Bought 3 "Something cheap" at $1.50
 Bought 3 "Something expensive" at $2500.17
 Could not buy 3 of "Something else"


＜END BLOCK Example Program＞

Program end_block_example
  Implicit None
  Integer i,tmp
  Real :: a(10) = [ (i,i=1,10) ]
  Real :: b(10) = 100
  tmp = 42
  Do i=1, Size(a)
exb: Block
      Real tmp
      tmp = a(i)**3
      If (tmp>b(i)) b(i) = tmp
    End Block exb
  End Do
  ! The outer "tmp" is unaffected by the inner one.
  Print 1, tmp, b
1 Format(1X,I0,10F7.1)
End Program

■ Execution Results

 42  100.0  100.0  100.0  100.0  125.0  216.0  343.0  512.0  729.0 1000.0


＜END CRITICAL Example Program＞

Module module
  Logical :: finished = .False.
  Integer :: count[*] = 0
Contains
  Subroutine do_some_work
    ! Just increment the count on image one, safely.
    Critical
      ! We only read or write the value of count[1] inside this
      ! Critical block, so only one image at a time.
      If (count[1]==100) Then
        finished = .True.
      Else
        count[1] = count[1] + 1
      End If
    End Critical
  End Subroutine
End Module
Program end_critical_example
  Use module
  ! All images will do this.
  Do While (.Not.finished)
    Call do_some_work
  End Do
  If (This_Image()==1) Then
    Print 1,count
1   Format(1X,'Finished ',I0,' units of work')
  End If
End Program

■ Execution Results

 Finished 100 units of work


＜END DO Example Program＞

Program end_do_example
  Integer :: i,x
  x = 0
  Do i = 1, 6, 2
    x = x + i
  End Do
  Print *, x
End Program

■ Execution Results

 9


＜END ENUM Example Program＞

Module enum_module
  Enum,Bind(C)
    Enumerator cx_default
    Enumerator :: cx_open=4, cx_reopen, cx_close
  End Enum
Contains
  Subroutine cx_show(status)
    Integer(Kind(cx_default)),Intent(In) :: status
    If (status==cx_default) Then
      Print *,'Default'
    Else
      Print *,'cx value',status
    End If
  End Subroutine
End Module
Program end_enum_example
  Use enum_module
  Call cx_show(cx_default)
  Call cx_show(cx_reopen)
End Program

■ Execution Results

 Default
 cx value 5


＜END FUNCTION Example Program＞

Program end_function_example
  Real :: a=2, b=3, c=4
  Print *,shiki1(2.,a,b,c)
  Print *,shiki2(2.,a,b,c)
  Print *,shiki3(2.,a,b,c)
End Program
Real Function shiki1(x,a,b,c)
  shiki1 = a*x**2 + b*x + c
End Function shiki1
Function shiki2(x,a,b,c) Result (shiki)
  shiki = a*x**2 + b*x + c
End Function
Function shiki3(x,a,b,c)
  shiki3 = a*x**2 + b*x + c
End

■ Execution Results

  18.0000000
  18.0000000
  18.0000000


＜END IF Example Program＞

Program end_if_example
  Integer :: x
  Read *, x
  If (Mod(x,2)==0) Then
    Print *, 'even',x
  End If
End Program

＜Example Input＞

4

■ Execution Results

 even 4


＜END INTERFACE Example Program＞

Program end_interface_example
  Interface
    Real Function mag(a)
      Real, Intent(In) :: a(:)
    End Function
  End Interface
  Real :: a(3)
  a = (/ 1.,2.,3. /)
  Print *, mag(a)
End Program
Real Function mag(a)
  Real, Intent(In) :: a(:)
  mag = Sqrt(Sum(a**2))
End Function mag

■ Execution Results

  3.7416575


＜END MODULE Example Program＞

Module set
  Integer :: node
  Real :: coord = 10.
End Module
Program end_module_example
  Use set
  Call sub1()
  Print *, node,coord
  Call sub2()
  Print *,node,coord
End Program
Subroutine Sub1()
  Use set
  node = 5
  coord = 20.
End Subroutine
Subroutine sub2()
  node = 7
  coord = 30.
End Subroutine

■ Execution Results

 5  20.0000000
 5  20.0000000


＜END PROGRAM Example Program＞

Program end_program_example
  Real, Dimension(3) :: a, b
  a = (/1.,2.,3./)
  b = 2.*a
  Print *, b
End Program end_program_example

■ Execution Results

  2.0000000   4.0000000   6.0000000


＜END SELECT Example Program＞

Program end_select_example
  Integer :: x
  Read *, x
  Select Case (x)
  Case (1)
    Print *, 'one'
  Case (2)
    Print *, 'two'
  End Select
End Program

＜Example input 1＞

1

■ Execution Results

 one

＜Example input 2＞

2

■ Execution Results

 two


＜END SUBMODULE Example Program＞

Module mymod
  Interface
    Module Integer Function next_number() Result(res)
    End Function
    Module Subroutine reset()
    End Subroutine
  End Interface
End Module
Submodule (mymod) variables
  Integer :: next = 1
End
Submodule (mymod:variables) functions
Contains
  Module Procedure next_number
    res = next
    next = next + 1
  End Procedure
End Submodule
Submodule (mymod:variables) subroutines
Contains
  Module Subroutine reset()
    Print *,'Resetting'
    next = 1
  End Subroutine
End Submodule subroutines
Program demo
  Use mymod
  Print *,'Hello',next_number()
  Print *,'Hello again',next_number()
  Call reset
  Print *,'Hello last',next_number()
End Program

■ Execution Results

 Hello 1
 Hello again 2
 Resetting
 Hello last 1


＜END SUBROUTINE Example Program＞

Program end_subroutine_example
  Real :: a=1., b=3., c=2.
  Call shiki(a,b,c,x1,x2)
  Print *, x1,x2
End Program
Subroutine shiki(a,b,c,x1,x2)
    Real, Intent(In) :: a, b, c
    Real, Intent(Out) :: x1, x2
    d = b**2 - 4.0*a*c
    If (d>0.) Then
        x1 = (-b+Sqrt(d))/(2.0*a)
        x2 = (-b-Sqrt(d))/(2.0*a)
    End If
End Subroutine shiki

■ Execution Results

  -1.0000000  -2.0000000


＜END TEAM Example Program＞

Program end_team_example
  Use Iso_Fortran_Env
  Implicit None
  Integer :: myteamid,i
  Type(team_type) team
  Integer :: temp[*],answer[*] = 0
  If (Num_Images()<4) Error Stop 'Not enough images (need 4)'
  myteamid = (This_Image()+1)/2
  Form Team(myteamid,team)
  Change Team(team)
    If (myteamid==1) Then
      ! Do what team 1 is supposed to do.
      temp = This_Image()**2
      Sync All ! Just syncs team one.
      If (This_Image()==1) answer = temp + temp[2]
    Else If (myteamid==2) Then
      ! Do what team 2 is supposed to do.
      temp = This_Image()**3
      Sync All ! Just syncs team two.
      If (This_Image()==1) answer = temp + temp[2]
    Else
      answer = 0
    End If
  End Team
  If (This_Image()==1) Then
    Do i=2,Num_Images()
      answer = answer + answer[i]
    End Do
    Print *,answer
  End If
End Program

■ Execution Results

 14


＜END TYPE Example Program＞

Program end_type_example
  Type material
    Character (5) :: name
    Real :: young
    Real :: poisson
  End Type material
  Type (material) steel,concrete
  steel%name = 'A36'
  steel%young = 200.
  steel%poisson = 0.3
  concrete = material( 'A36',200.,0.3 )
  Print *, steel
  Print *, concrete
End Program

■ Execution Results

 A36     2.0000000E+02   0.3000000
 A36     2.0000000E+02   0.3000000


＜END WHERE Example Program＞

Program end_where_example
  Real :: a(2,2)
  a = Reshape( (/-1.,2.,3.,4./), (/2,2/) )
  Where (a<0.)
    a = 0.0
  ElseWhere (a>3.)
    a = 1.0
  Elsewhere
    a = 10*a
  End Where
  Print *, a(1,:)
  Print *, a(2,:)
End Program

■ Execution Results

   0.0000000  30.0000000
  20.0000000   1.0000000


＜ENDFILE Example Program＞

Program endfile_example
  Implicit None
  Character(80) :: line
  Integer :: unit, line_number
  Open (Newunit=unit,File='LIST.DAT',Status='OLD',Position='REWIND')
  line_number = 0
  Do
    Read (unit,'(A)',End=1) line
    line_number = line_number + 1
    If (Index(line,'end')>0) Exit
  End Do
  Endfile unit
  Print *,'LIST.DAT truncated after line',line_number
  Go To 2
1 Continue
  Print *,'Did not find "end" in LIST.DAT'
2 Continue
  Close (unit)
End Program

＜File: LIST.DAT before execution＞

Drink
and
be
merry
my
friends
for
tomorrow
we
die.

■ Execution Results

 LIST.DAT truncated after line 6

＜File: LIST.DAT after execution＞

Drink
and
be
merry
my
friends


ENUM example program

＜Example Program＞

Module enum_module
  Enum,Bind(C)
    Enumerator cx_default
    Enumerator :: cx_open=4, cx_reopen, cx_close
  End Enum
Contains
  Subroutine cx_show(status)
    Integer(Kind(cx_default)),Intent(In) :: status
    If (status==cx_default) Then
      Print *,'Default'
    Else
      Print *,'cx value',status
    End If
  End Subroutine
End Module
Program enum_example
  Use enum_module
  Call cx_show(cx_default)
  Call cx_show(cx_reopen)
End Program

■ Execution Results

 Default
 cx value 5


＜ENUMERATOR Example Program＞

Module enum_module
  Enum,Bind(C)
    Enumerator cx_default
    Enumerator :: cx_open=4, cx_reopen, cx_close}
  End Enum
Contains
  Subroutine cx_show(status)
    Integer(Kind(cx_default)),Intent(In) :: status
    If (status==cx_default) Then
      Print *,'Default'
    Else
      Print *,'cx value',status
    End If
  End Subroutine
End Module
Program enumerator_example
  Use enum_module
  Call cx_show(cx_default)
  Call cx_show(cx_reopen)
End Program

■ Execution Results

 Default
 cx value 5


＜EOR= Example Program＞

Program eor_specifier_example
  Character ch
  Character(80) :: name(10) = ''
  Integer pos
  Print *,'Please enter a list of names separated by commas.'
  Do i=1,10
    pos = 1
    Do
      Read (*,'(a)',Advance='No',Eor=1) ch
      If (ch==',') Exit
      name(i)(pos:pos) = ch
      pos = pos + 1
    End do
  End do
  Print *,'Only the first 10 names are accepted'
  i = 10
1 Continue
  Print 2,i
2 Format(/,1X,'You have entered ',I0,' names.')
  Do j=1,i
    Print *,j,Trim(name(j))
  End do
End Program

＜Example input＞

Fred Nurke,X the Unknown,Penelope Pettigrew

■ Execution Results

 You have entered 3 names.
 1 Fred Nurke
 2 X the Unknown
 3 Penelope Pettigrew


＜EOSHIFT Example Program＞

Program eoshift_example
  Real, Dimension(2,3) :: a,b,c
  a = Reshape( (/1.,2.,3.,4.,5.,6./), (/2,3/))
  b = Eoshift(a,Shift=1,Dim=2)
  c = Eoshift(a,Shift=-1,Boundary=(/10.,20./),Dim=2)
  Print *, b(1,:)
  Print *, b(2,:)
  Print *, c(1,:)
  Print *, c(2,:)
End Program

■ Execution Results

   3.0000000   5.0000000   0.0000000
   4.0000000   6.0000000   0.0000000
  10.0000000   1.0000000   3.0000000
  20.0000000   2.0000000   4.0000000


＜EPSILON Example Program＞

Program epsilon_example
  Integer, Parameter :: r6 = Selected_Real_Kind(6)
  Real(r6), Pointer :: p
  Print *, Epsilon(p)
End Program

■ Execution Results

 1.1920929E-07


＜.EQ. (==) Example Program＞

Program eq_example
  Do i=1,10
    If (i**2+28==i*11) Then
      Print *,'True at',i
    End If
  End Do
End Program

■ Execution Results

 True at 4
 True at 7


＜.EQV. Example Program＞

Program eqv_example
  Logical :: op1val(4) = (/ .true.,.true.,.false.,.false. /)
  Logical :: op2val(4) = (/ .true.,.false.,.true.,.false. /)
  Print 1,'Logical Operator Truth Table','.EQV.'
1 Format (1x,A,/,/,1X,'Op1',T8,'Op2',T14,A)
  Do i=1,4
    Print 2,op1val(i),op2val(i),op1val(i).Eqv.op2val(i)
2   Format(T4,L1,T9,L1,T15,L1)
  End Do
End Program

■ Execution Results

 Logical Operator Truth Table

 Op1   Op2   .EQV.
   T    T     T
   T    F     F
   F    T     F
   F    F     T


ERF Example Program

＜Example Program＞

Program erf_example
  Real :: x(6) = [ 0.5,1.0,2.0,3.0,4.0,5.0 ]
  Print 1, x
  Print 1, Erf(x)
1 Format(999F9.6)
End Program

■ Execution Results

 0.500000 1.000000 2.000000 3.000000 4.000000 5.000000
 0.520500 0.842701 0.995322 0.999978 1.000000 1.000000


＜ERFC Example Program＞

Program erfc_example
  Real :: x(6) = [ 0.5,1.0,2.0,3.0,4.0,5.0 ]
  Print 1, x
  Print 2, Erfc(x)
1 Format(999F12.6)
2 Format(999ES12.5)
End Program

■ Execution Results

    0.500000    1.000000    2.000000    3.000000    4.000000    5.000000
 4.79500E-01 1.57299E-01 4.67774E-03 2.20905E-05 1.54173E-08 1.53746E-12


＜ERFC_SCALED Example Program＞

Program erfc_scaled_example
  Real :: x(6) = [ 0.5,1.0,2.0,33.0,444.0,5555.0 ]
  Print 1, x
  Print 2, Erfc_scaled(x)
1 Format(999F12.6)
2 Format(999ES12.5)
End Program

■ Execution Results

    0.500000    1.000000    2.000000   33.000000  444.000000 5555.000000
 6.15690E-01 4.27584E-01 2.55396E-01 1.70888E-02 1.27069E-03 1.01564E-04


＜ERR= Example Program＞

Program err_specifier_example
  Character(80) :: errortext
  Character(8) :: text(2) = (/ '3.5','bad' /)
  Do i=1,Size(text)
      Read (text(i),*,Err=10,Iomsg=errortext) x
      Print *,'Read value',x
  End do
  Stop
10 Continue
  Print *,'Bad value read: ',Trim(errortext)
End Program

■ Execution Results

 Read value   3.5000000
 Bad value read: Invalid input for real editing


＜ERRMSG= Example Program＞

Program errmsg_example
  Real,Allocatable :: a(:)
  Call newmem(100)
  Print 1,Size(a)
1 Format(1X,'Got memory: ',I0,' elements')
  Call newmem(1000)
  Print 1,Size(a)
  Print *,'Finished'
Contains
  Subroutine newmem(n)
    Integer,Intent(In) :: n
    Integer stat
    Character(100) error
    Deallocate(a,Stat=stat,Errmsg=error)
    If (stat/=0) Then
      Print *,'Deallocation error: ',Trim(error),'; continuing'
    End If
    If (Allocated(a)) Stop 'Cannot continue - still allocated'
    Allocate(a(n),Stat=stat,Errmsg=error)
    If (stat/=0) Then
      Print *,Trim(error)
      Stop 'Cannot continue - allocation failed'
    End If
  End Subroutine
End Program

■ Execution Results

 Deallocation error: Allocatable variable is not allocated; continuing
 Got memory: 100 elements
 Got memory: 1000 elements
 Finished


＜ERROR STOP Example Program＞

Program error_stop_example
  Call test(13)
  Call test(-27)
Contains
  Subroutine test(n)
    Integer,Intent(In) :: n
    If (n<=0) Error Stop 'n must be positive'
    Print *,'ok',n
  End Subroutine
End Program

■ Execution Results

 ok 13
ERROR STOP: n must be positive


＜EVENT POST Example Program＞

Program event_post_example
  Use iso_fortran_env
  Type(event_type) ev[*]
  If (num_images()<2) Error Stop 'Not enough images'
  If (this_image()==1) Then
    ! Post an event to every other image.
    Do i=2,num_images()
      ! (A real program would store some data for the other image first.)
      Event Post (ev[i])
    End Do
    ! Wait for them to post back.
    Event Wait (ev,Until_Count=num_images()-1)
    Print *,'All events processed.'
  Else
    ! Wait for the event (from image one).
    Event Wait (ev)
    ! (A real program would process the data from image one first.)
    ! Send image one an event to say we have finished.
    Event Post (ev[1])
  End If
End Program

■ Execution Results

 All events processed.


＜EVENT WAIT Example Program＞

Program event_post_example
  Use iso_fortran_env
  Type(event_type) ev[*]
  If (num_images()<2) Error Stop 'Not enough images'
  If (this_image()==1) Then
    ! Post an event to every other image.
    Do i=2,num_images()
      ! (A real program would store some data for the other image first.)
      Event Post (ev[i])
    End Do
    ! Wait for them to post back.
    Event Wait (ev,Until_Count=num_images()-1)
    Print *,'All events processed.'
  Else
    ! Wait for the event (from image one).
    Event Wait (ev)
    ! (A real program would process the data from image one first.)
    ! Send image one an event to say we have finished.
    Event Post (ev[1])
  End If
End Program

■ Execution Results

 All events processed.


＜EXECUTE_COMMAND_LINE Example Program＞

Program execute_command_line_example
  Call execute_command_line('echo Hello world')
End Program

■ Execution Results

Hello world


＜EXIT Example Program＞

Program exit_example
  Integer :: i,irem
  Do i = 5, 10
    irem = Mod(i,4)
    If (irem==0) Exit
    Print *, irem
  End Do
  Print *, i
End Program

■ Execution Results

 1
 2
 3
 8


＜EXP Example Program＞

Program exp_example
  Real :: a(3) = [ 0.0, Log(10.0), Log(100.0) ]
  Real,Parameter :: pi = 3.141592653589793238462643383279502884197
  Complex :: c(3) = [ Cmplx(0.0,pi/2), Cmplx(0.0,pi), Cmplx(Log(5.0*Sqrt(2.0)),pi/4) ]
  Print 1, Exp(a)
1 Format(3(2X,F0.5))
  Print 2, Exp(c)
2 Format(3(2X,'(',F0.5,',',F0.5,')'))
End Program

■ Execution Results

  1.00000  10.00000  100.00001
  (-.00000,1.00000)  (-1.00000,-.00001)  (5.00000,5.00000)


＜EXPONENT Example Program＞

Program exponent_example
  Real :: x(3) = [ 1.5*2.0**(-100), 1.5, 1.5*2.0**100 ]
  Integer i
  Do i=1, Size(x)
    Print *, x(i), '=', Fraction(x(i)), '*', Radix(x), '**', Exponent(x(i))
  End Do
End Program

■ Execution Results

   1.1832914E-30 =   0.7500000 * 2 ** -99
   1.5000000 =   0.7500000 * 2 ** 1
   1.9014759E+30 =   0.7500000 * 2 ** 101


＜EXTENDS Example Program＞

Module point_module
  Type point
    Real x,y
  Contains
    Procedure :: identify => identify_point
    Procedure distance
  End Type
  Private identify_point,distance
Contains
  Real Function distance(p)
    Class(point),Intent(In) :: p
    distance = sqrt(p%x**2 + p%y**2)
  End Function
  Subroutine identify_point(this)
    Class(point),Intent(In) :: this
    Write (*,'(1X,A,1X,2G10.2)',Advance='NO') &
        "The point at",this%x,this%y
  End Subroutine
End Module
Module more_points
  Use point_module
  Type,Extends(point) :: named_point
    ! Inherit Real x,y
    Character(80) name ! Extra component
  Contains
    ! Override identify with our own procedure.
    Procedure :: identify => identify_named_point
    ! Inherit distance as is.
  End Type
Contains
  Subroutine identify_named_point(this)
    Class(named_point),Intent(In) :: this
    Write (*,'(1X,A,1X,2G10.2)',Advance='NO') &
        'The point "'//Trim(this%name)//'" at',this%x,this%y
  End Subroutine
End Module
Program extends_example
  Use more_points
  Type(point) :: a = point(3.0,4.0)
  Type(named_point) :: b = named_point(1.0,1.0,'corner')
  Call show_info(a)
  Call show_info(b)
Contains
  Subroutine show_info(x)
    Class(point),Intent(In) :: x
    Call x%identify
    Print '(" has distance ",G10.2)',x%distance()
  End Subroutine
End Program

■ Execution Results

 The point at    3.0       4.0     has distance    5.0
 The point "corner" at    1.0       1.0     has distance    1.4


＜EXTENDS_TYPE_OF Example Program＞

Module types
  Type t1
    Real a
  End Type
  Type, Extends(t1) :: et1
    Real b
  End Type
  Type t2
    Logical a
  End Type
End Module
Program example
  Use types
  Class(*),Pointer :: a, b, c
  Allocate(t1::a)
  Allocate(t2::b)
  Allocate(et1::c)
  Print *,'a vs. b:', Extends_Type_Of(a, b), Extends_Type_Of(b, a)
  Print *,'a vs. c:', Extends_Type_Of(a, c), Extends_Type_Of(c, a)
End Program

■ Execution Results

 a vs. b: F F
 a vs. c: F T


＜FAILED_IMAGES Example Program＞

Program failed_images_example
  Use Iso_Fortran_Env
  Implicit None
  Integer istat
  If (Num_Images()<3) Error Stop 'Not enough images'
  If (This_Image()==3) Fail Image
  Sync All(Stat=istat)
  If (istat==Stat_Failed_Image) Then
    If (This_Image()==1) Print *,'Failed images:',Failed_Images()
  End If
End Program

■ Execution Results

 Failed images: 3
Warning: 1 image(s) failed


＜FINAL Example Program＞

Module final_module
  Type t
    Logical :: valid = .False.
    Integer :: code = 0
  Contains
    Final :: zap
  End Type
Contains
  Subroutine zap(x)
    Type(t) :: x
    If (x%valid) Then
      Print *, '[Code',x%code,'zapped.]'
    Else
      Print *, '[Invalid code zapped.]'
    End If
    x%valid = .False.
  End Subroutine
End Module
!
Program show
  Use final_module
  Type(t) :: x = t(.True., 13)
  ! The next line will finalise X (code 13) on the call.
  Call set(x,42)
  ! Nothing is finalised on program termination.
Contains
  Subroutine set(a, code)
    Type(t), Intent(Out) :: a
    Integer, Intent(In) :: code
    Type(t) :: y
    ! The next line will finalise (invalid code) Y.
    y = t(.True., code)
    Print *, 'Setting', code
    ! The next line will finalise (invalid code) A.
    a = y
    ! Returning will finalise Y (code 42).
    Return
  End Subroutine
End Program

■ Execution Results

 [Code 13 zapped.]
 [Invalid code zapped.]
 Setting 42
 [Invalid code zapped.]
 [Code 42 zapped.]


＜FINDLOC Example Program＞

Program findloc_example
  Real :: a(2,3)
  Logical :: m(2,3)
  a = Reshape( [ 2.,3.,5.,-1.,4.,3. ], [ 2,3 ])
  m = Reshape( [ .True.,.True.,.True.,.True.,.False.,.False. ], [ 2,3 ])
  Print *, Findloc(a,3.0)
  Print *, Findloc(a,3.0,Back=.True.)
  Print *, Findloc(a,3.0,Back=.True.,Mask=m)
  Print *, Findloc(a,3.0,Dim=1)
  Print *, Findloc(a,3.0,Dim=2)
End

■ Execution Results

 2 1
 2 3
 2 1
 2 0 2
 0 1


＜FLOOR Example Program＞

Program floor_example
  Call test( [ 10.49,10.50,10.51 ] )
Contains
  Subroutine test(a)
    Real,Intent(In) :: a(:)
    Print 1,a,Floor(a)
 1  Format(3F8.2,/,3I8)
    Print 1,-a,Floor(-a)
  End Subroutine
End Program

■ Execution Results

   10.49   10.50   10.51
      10      10      10
  -10.49  -10.50  -10.51
     -11     -11     -11


＜FORALL Example Program＞

Program forall_statement_example
  Real a(2,3)
  Forall (i=1:2,j=1:3) a(i,j) = i*10 + j
  Print *,a(1,:)
  Print *,a(2,:)
End Program

■ Execution Results

  11.0000000  12.0000000  13.0000000
  21.0000000  22.0000000  23.0000000


＜FORALL Example Program＞

Program forall_construct_example
  Real a(2,3)
  Forall (i=1:2,j=1:3)
    a(i,j) = i*10 + j
  End Forall}
  Print *,a(1,:)
  Print *,a(2,:)
End Program

■ Execution Results

  11.0000000  12.0000000  13.0000000
  21.0000000  22.0000000  23.0000000


＜FORM TEAM Example Program＞

Program form_team_example
  Use Iso_Fortran_Env
  Implicit None
  Integer :: myteamid,i
  Type(team_type) team
  Integer :: temp[*],answer[*] = 0
  If (Num_Images()<4) Error Stop 'Not enough images (need 4)'
  myteamid = (This_Image()+1)/2
  Form Team(myteamid,team)
  Change Team(team)
    If (myteamid==1) Then
      ! Do what team 1 is supposed to do.
      temp = This_Image()**2
      Sync All ! Just syncs team one.
      If (This_Image()==1) answer = temp + temp[2]
    Else If (myteamid==2) Then
      ! Do what team 2 is supposed to do.
      temp = This_Image()**3
      Sync All ! Just syncs team two.
      If (This_Image()==1) answer = temp + temp[2]
    Else
      answer = 0
    End If
  End Team
  If (This_Image()==1) Then
    Do i=2,Num_Images()
      answer = answer + answer[i]
    End Do
    Print *,answer
  End If
End Program

■ Execution Results

 14


＜FUNCTION Example Program＞

Program function_example
  Real :: a=2, b=3, c=4
  Real, External :: shiki1,shiki2,shiki3
  Print *, shiki1(2.,a,b,c)
  Print *, shiki2(2.,a,b,c)
  Print *, shiki3(2.,a,b,c)
End Program
Real Function shiki1(x,a,b,c)
  Real, Intent(In) :: x,a,b,c
  shiki1 = a*x**2 + b*x + c
End Function shiki1
Function shiki2(x,a,b,c) Result( y )
  Real y,x,a,b,c
  Intent(In) x,a,b,c
  y = a*x**2 + b*x + c
End Function
Function shiki3(x,a,b,c)
  Real shiki3
  Real,Intent(In) :: x,a,b,c
  shiki3 = a*x**2 + b*x + c
End

■ Execution Results

  18.0000000
  18.0000000
  18.0000000


GAMMA example program

＜Example Program＞

Program gamma_example
  Real :: x(8) = [ 2.0, 4.0, 6.0, 8.0, 10.0, 12.0, 14.0, 16.0 ]
  Print 1, x
  Print 2, Gamma(x)
1 Format(999F9.2)
2 Format(999ES9.2)
End Program

■ Execution Results

     2.00     4.00     6.00     8.00    10.00    12.00    14.00    16.00
 1.00E+00 6.00E+00 1.20E+02 5.04E+03 3.63E+05 3.99E+07 6.23E+09 1.31E+12


.GE. (>=) Example Program

＜.GE. (&gt;=) Example Program＞

Program ge_example
  Integer x
  Do x=1,10
    If (x**2+28>=x*11) Then
      Print *,'True at',x
    End If
  End Do
End Program

■ Execution Results

 True at 1
 True at 2
 True at 3
 True at 4
 True at 7
 True at 8
 True at 9
 True at 10


＜GET_COMMAND Example Program＞

Program get_command_example
  Integer n
  Character(:), Allocatable :: cmd
  Call Get_Command(Length=n)
  If (n==0) Then
    Print *, 'No command found'
  Else
    Allocate(Character(n) :: cmd)
    Call Get_Command(cmd)
    Print *, 'Command line is "', cmd, '"'
  End If
End Program

■ Execution Results

If the program is called “C:\Example\a.exe” and is invoked as “a simple example” the results are likely to be either:

 Command line is "a simple example"
or
 Command line is "C:\Example\a.exe simple example"
(This will depend on the particular command shell in use.)


＜GET_COMMAND_ARGUMENT Example Program＞

Program get_command_argument_example
  Integer i, n
  Character(80) arg
  n = Command_Argument_Count()
  If (n==0) Print *, 'No argument found'
  Do i=1, n
    Call Get_Command_Argument(i,arg)
    Print *, 'Argument',i,'is "',Trim(arg),'"'
  End Do
End Program

■ Execution Results

If invoked with no argument, the results are:

 No argument found

If the program is called “a” and is invoked as “a simple example” the results are:

 Argument 1 is "simple"
 Argument 2 is "example"


＜GET_ENVIRONMENT_VARIABLE Example Program＞

Program get_environment_variable_example
  Integer n
  Character(:), Allocatable :: logname
  Call Get_Environment_Variable(Name='LOGNAME',Length=n)
  If (n==0) Then
    Print *, 'Environment variable LOGNAME not found'
  Else
    Allocate(Character(n) :: logname)
    Call Get_Environment_Variable(Name='LOGNAME',Value=logname)
    Print *, 'Login name is "', logname, '"'
  End If
End Program

■ Execution Results

If the user is logged in as “Local User”, the result is likely to be:

 Login name is "Local User"


＜GET_TEAM Example Program＞

Program get_team_example
  Use Iso_Fortran_Env,Only:team_type,initial_team
  Implicit None
  Integer myteamid
  Type(team_type) myteam
  If (Num_Images()<2) Error Stop 'Not enough images'
  myteamid = Mod(This_Image(),2) + 1
  Form Team (myteamid,myteam)
  Change Team (myteam)
    If (myteamid==1 .And. This_Image()==1) Print *,'Hello from team one'
    ! Synchronise the initial team,
    ! so that team two will wait for team one to get here.
    Sync Team (Get_Team(initial_team))
    If (myteamid==2 .And. This_Image()==1) Print *,'Hello from team two'
  End Team
End Program

■ Execution Results

With two or more images, the result will be:

 Hello from team one
 Hello from team two


＜GO TO Example Program＞

Program goto_example
    Integer :: x,y
    x = 0
10  Continue
    x = x + 1
    y = x**2
    Print *, x,y
    If (y<8) Goto 10
    Print *, 'Finished'
End

■ Execution Results

 1 1
 2 4
 3 9
 Finished


.GT. (>) Example Program

＜.GT. (&gt;) Example Program＞

Program gt_example
  Do i=1,10
    If (i**2+28>i*11) Then
      Print *,'True at',i
    End If
  End Do
End Program

■ Execution Results

 True at 1
 True at 2
 True at 3
 True at 8
 True at 9
 True at 10


＜Array Constructor Example Program＞

Program array_constructor_example
  Real :: a(3) = (/ 1.,2.,3. /)
  Real b(3)
  b = (/ 4.,5.,6. /)
  Print *, a
  Print *, b
End Program

■ Execution Results

  1.0000000   2.0000000   3.0000000
  4.0000000   5.0000000   6.0000000


＜Array Assignment Example Program＞

Program array_assignment_example
  Real :: a(5) = (/ 1.,2.,3.,4.,5. /)
  Real b(3),c(5),d(5)
  b = a(2:4)
  c(2:4) = b
  d(1:3) = a(3:5)}
  Print *, b
  Print *, c(2:4)
  Print *, d(:3)
End Program

■ Execution Results

  2.0000000   3.0000000   4.0000000
  2.0000000   3.0000000   4.0000000
  3.0000000   4.0000000   5.0000000


＜HUGE Example Program＞

Program huge_example
  Integer,Parameter :: i8 = Selected_Int_Kind(2)
  Integer(i8),Pointer :: p
  Print *,Huge(p)
End Program

■ Execution Results

 127


＜HYPOT Example Program＞

Program hypot_example
  Real :: a(3) = [ 3.0e-30, 3.0, 3.0e+30 ]
  Real :: b(3) = [ 4.0e-30, 4.0, 4.0e+30 ]
  Print 1, Hypot(a,b)
1 Format(3(2X,ES12.6))
End Program

■ Execution Results

  5.000000E-30  5.000000E+00  5.000000E+30


＜IALL Example Program＞

Program iall_example
  Integer :: a(2,3)
  a = Reshape( [ 12.,13.,5.,-1.,4.,-3. ], [ 2,3 ])
  Print *, Iall(a)
  Print *, Iall(a,1)
  Print *, Iall(Array=a,Dim=2)
  Print *, Iall(a, Mask=a)
End Program

■ Execution Results

 4
 12 5 4
 4 13
 -3


＜IAND Example Program＞

Program iand_example
    Integer :: a(3), b(3)
    a = [ 12,65549,263 ]
    b = [ -1,1158,-3 ]
    Print 1, a
1  Format(3(1X,Z8))
    Print 1, b
    Print 1, Iand(a,b)
End Program

■ Execution Results

        C    1000D      107
 FFFFFFFF      486 FFFFFFFD
        C        4      105


＜IANY Example Program＞

Program iany_example
  Integer :: a(2,3)
  a = Reshape( [ 12.,13.,5.,-12.,2.,-3. ], [ 2,3 ])
  Print *, Iany(a)
  Print *, Iany(a,1)
  Print *, Iany(Array=a,Dim=2)
  Print *, Iany(a, Mask=a>0)
End Program

■ Execution Results

 -1
 13 -11 -1
 15 -3
 15


＜IBCLR Example Program＞

Program ibclr_example
  Use Iso_Fortran_Env, Only:int8
  Integer :: i
  Do i=0, Bit_Size(1_int8)-1
    Print 1, Ibclr(Not(0_int8), i)
1   Format(1X, B8.8)
  End Do
End Program

■ Execution Results

 11111110
 11111101
 11111011
 11110111
 11101111
 11011111
 10111111
 01111111


＜IBITS Example Program＞

Program ibits_example
  Use Iso_Fortran_Env, Only:int8
  Integer(int8), Parameter :: x = Int(B'11100101', int8)
  Integer :: i
  Do i=0, Bit_Size(1_int8)-2
    Print 1, i, i+1, x, Ibits(x, i, 2)
1   Format(1X, 'Bits ', I0, '-', I0, ' of ', B8.8, ' = ', B2.2)
  End Do
End Program

■ Execution Results

 Bits 0-1 of 11100101 = 01
 Bits 1-2 of 11100101 = 10
 Bits 2-3 of 11100101 = 01
 Bits 3-4 of 11100101 = 00
 Bits 4-5 of 11100101 = 10
 Bits 5-6 of 11100101 = 11
 Bits 6-7 of 11100101 = 11


＜IBSET Example Program＞

Program ibset_example
  Use Iso_Fortran_Env, Only:int8
  Integer :: i
  Do i=0, Bit_Size(1_int8)-1
    Print 1, Ibset(0_int8, i)
1   Format(1X, B8.8)
  End Do
End Program

■ Execution Results

 00000001
 00000010
 00000100
 00001000
 00010000
 00100000
 01000000
 10000000


＜IEOR Example Program＞

Program ieor_example
  Integer :: a(3), b(3)
  a = [ 12,65549,263 ]
  b = [ -1,1158,-3 ]
  Print 1, a
1 Format(3(1X,Z8))
  Print 1, b
  Print 1, Ieor(a,b)
End Program

■ Execution Results

        C    1000D      107
 FFFFFFFF      486 FFFFFFFD
 FFFFFFF3    1048B FFFFFEFA


＜Image-selector Example Program＞

Program image_selector_example
  Implicit None
  Real,Allocatable :: a(:,:)[:]
  Integer i,image,iset,j,m[*],m_per_image,n[*]
  If (This_Image()==1) Then
    !
    ! Read the problem size.
    !
    Read *,n,m
    !
    ! M vectors of length N.
    !
  End If
  !
  ! All images allocate the coarray that will hold the data.
  ! Get N from image 1 before allocation.
  ! If there are more data sets than images, the data sets
  ! are spread as evenly as possible: M_PER_IMAGE is the maximum
  ! number of data sets on any image.
  !
  Sync All
  If (This_Image()>1) Then
    n = n[1]
    m = m[1]
  End If
  m_per_image = (m-1)/Num_Images() + 1
  Allocate(a(n,m_per_image)[*])
  If (This_Image()==1) Then
    !
    ! Image 1 continues to read the data for all images.
    !
    image = 1
    iset = 1
    Do i=1,m
      Read *,a(:,iset)[image]
      If (image==Num_Images()) Then
        ! Filled up this slot on each image, reset to 1.
        image = 1
        iset = iset + 1
      Else
        image = image + 1
      End If
    End Do
  End If
  Sync All
  !
  ! All images process all of their data locally.
  ! Use ISET to keep track of the data set number, so that
  ! we don't try to process data sets beyond M.
  !
  iset = This_Image()
  Do i=1,m_per_image
    If (iset>m) Exit ! Nothing more to do on this image.
    ! We have the data: calculate the magnitude sum suffix.
    a(1,i) = Abs(a(1,i))
    Do j=2,n
      a(j,i) = a(j-1,i) + Abs(a(j,i))
    End Do
    iset = iset + Num_Images()
  End Do
  !
  ! Wait for everyone to finish.
  !
  Sync All
  If (This_Image()==1) Then
    !
    ! Image one will now report the results.
    !
    image = 1
    iset = 1
    Do i=1,m
      Print 1,i,(a(j,iset)[image],j=1,n)
1     Format(1X,'Data set ',I0,' magsumsuffix =',999F7.2)
      If (image==Num_Images()) Then
        ! Processed this slot on each image, reset to 1.
        image = 1
        iset = iset + 1
      Else
        image = image + 1
      End If
    End Do
  End If
End Program

＜Example Input＞

5 10
 -3.00 4.19 4.80 4.17 3.72
 2.80 -.31 2.09 -4.29 -4.29
 .59 4.07 3.68 -1.90 .53
 -1.29 2.47 -.61 2.06 .25
 -4.03 -1.37 -4.89 -2.53 3.22
 -3.46 -.16 -3.37 -2.10 -.03
 -2.93 3.49 4.03 2.14 -2.24
 4.98 1.15 3.56 1.50 .35
 -.58 1.54 -.42 -4.02 4.04
 -.36 4.51 4.17 .21 1.98

■ Execution Results

 Data set 1 magsumsuffix =   3.00   7.19  11.99  16.16  19.88
 Data set 2 magsumsuffix =   2.80   3.11   5.20   9.49  13.78
 Data set 3 magsumsuffix =   0.59   4.66   8.34  10.24  10.77
 Data set 4 magsumsuffix =   1.29   3.76   4.37   6.43   6.68
 Data set 5 magsumsuffix =   4.03   5.40  10.29  12.82  16.04
 Data set 6 magsumsuffix =   3.46   3.62   6.99   9.09   9.12
 Data set 7 magsumsuffix =   2.93   6.42  10.45  12.59  14.83
 Data set 8 magsumsuffix =   4.98   6.13   9.69  11.19  11.54
 Data set 9 magsumsuffix =   0.58   2.12   2.54   6.56  10.60
 Data set 10 magsumsuffix =   0.36   4.87   9.04   9.25  11.23


＜IMAGE_STATUS Example Program＞

Program image_status_example
  Use Iso_Fortran_Env
  Implicit None
  Integer i,istat
  If (Num_Images()<4) Error Stop 'Not enough images'
  If (This_Image()==3) Fail Image
  Sync All(Stat=istat)
  If (istat/=Stat_Failed_Image) Error Stop 'Expected failed image stat'
  If (This_Image()==2) Stop
  Sync All(Stat=istat)
  If (istat/=Stat_Stopped_Image) Error Stop 'Expected stopped image stat'
  If (This_Image()==1) Then
    Do i=1,4
      Select Case (Image_Status(i))
      Case (0)
        Print *,'Image',i,'is active'
      Case (Stat_Failed_Image)
        Print *,'Image',i,'has failed'
      Case (Stat_Stopped_Image)
        Print *,'Image',i,'has stopped'
      End Select
    End Do
  End If
  If (This_Image()<5) Sync Images([1,4])
End Program

■ Execution Results

 Image 1 is active
 Image 2 has stopped
 Image 3 has failed
 Image 4 is active
Warning: 1 image(s) failed


INT Example Program

<Example Program>

Program int_example
  Call test( [ 10.49,10.50,10.51 ] )
Contains
  Subroutine test(a)
    Real,Intent(In) :: a(:)
    Print 1,a,Int(a)
 1  Format(3F8.2,/,3I8)
    Print 1,-a,Int(-a)
  End Subroutine
End Program

Execution Results

   10.49   10.50   10.51
      10      10      10
  -10.49  -10.50  -10.51
     -10     -10     -10


＜INTEGER Example Program＞

Program integer_example
  Integer :: a
  a = 5
  Print *,a
End Program

■ Execution Results

 5


INTERFACE Example Program

＜INTERFACE Example Program 1＞

Program specific_interface_example
  Interface
    Real Function mag( a )
      Real, Intent(In) :: a(:)
    End Function
  End Interface
  Real, Allocatable :: a(:)
  Allocate( A(3) )
  a = [ 1.,2.,3. ]
  Print *, mag(a)
End Program
Real Function mag( a )
  Real, Intent(In) :: a(:)
  mag = Sqrt( Sum( a**2 ) )
End Function mag

■ Execution Results

  3.7416575

＜INTERFACE Example Program 2＞

Module generic_interface_example
  Interface display
    Module Procedure display_integer, display_real
  End Interface
  Private display_integer, display_real
Contains
  Subroutine display_integer(a)
    Integer, Intent(In) :: a
    Print *, 'Integer',a
  End Subroutine
  Subroutine display_real(a)
    Real, Intent(In) :: a
    Print *, 'Real',a
  End Subroutine
End Module
Program example_program_2
  Use generic_interface_example
  Call display(42)
  Call display(4.25)
End Program

■ Execution Results

 Integer 42
 Real   4.2500000


＜IOSTAT= Example Program＞

Program iostat_example
  Character c
  Integer ios, nchars, nlines, nvowels
  nchars = 0
  nlines = 0
  nvowels = 0
  Do
    Read (*,'(A)',Advance='No',Iostat=ios) c
    If (Is_Iostat_End(ios)) Exit
    If (ios==0) Then
      nchars = nchars + 1
      If (Verify(c,'aeiouAEIOU')&gt;0) nvowels = nvowels + 1
    Else If (Is_Iostat_Eor(ios) Then
      nlines = nlines + 1
    Else
      Print *, 'Unexpected i/o error', ios
      Stop
    End If
  End Do
  Print *, 'The input contained', nchars, 'characters in', nlines, 'lines.'
  Print *, nvowels, 'of the characters were vowels.'
End Program

■ Execution Results

When run with the input:

Now is the time∞
for all good men∞
to come to the aid∞
of the party.∞
where ∞ indicates the end of each record, the output is
 The input contained 62 characters in 4 lines.
 42 of the characters were vowels.


＜LBOUND Example Program＞

Program lbound_example
  Real a(0:2,4)
  Print 1, Lbound(a,Dim=1)
  Print 1, Lbound(a,Dim=2)
  Print 1, Lbound(a)
1 Format(99(1X,I0,:,','))
End

■ Execution Results

 0
 1
 0, 1


＜LCOBOUND Example Program＞

Program lcobound_example
  Real a[0:2,*]
  If (This_Image()==1) Then
    Print 1, Lcobound(a,Dim=1)
    Print 1, Lcobound(a,Dim=2)
    Print 1, Lcobound(a)
1   Format(99(1X,I0,:,','))
  End If
End

■ Execution Results

 0
 1
 0, 1


＜LOCK Example Program＞

Program lock_example
  Use Iso_Fortran_Env
  Type(lock_type) :: worklock[*]
  Type work_type
    Integer value
    Logical avail,done
  End Type
  Type(work_type) :: work(10)[*] = work_type(0,.True.,.False.)
  !
  ! Only the WORK variable on image 1 is used, to keep track.
  ! Similarly, only the WORKLOCK variable on image 1 is used.
  !
  Integer i
  Do
    Lock(worklock[1])
    Do i=1,Size(work)
      If (work(i)[1]%avail) Then
        ! Unset avail while we still hold the lock.
        work(i)[1]%avail = .False.
        Exit
      End If
    End Do
    Unlock(worklock[1])
    If (i>Size(work)) Exit ! No work available.
    !
    ! A real program would do some real work here.
    ! This example will just assign I to the value on image 1.
    !
    work(i)[1]%value = i
    work(i)[1]%done = .True.
  End Do
  ! Wait for all images to finish the work.
  Sync All
  ! Image 1 will check the results.
  If (This_Image()==1) Then
    Do i=1,Size(work)
      If (.Not.work(i)%done) Error Stop 'Work was not done'
    End Do
    Print *,'Work complete'
  End If
End Program

■ Execution Results

 Work complete


＜LOGICAL Example Program＞

Program logical_example
  Logical :: a
  a = .False.
  Print *,a
End Program

■ Execution Results

 F


＜MAXLOC Example Program＞

Program maxloc_example
  Real :: a(2,3)
  a = Reshape( (/2.,3.,5.,-1.,4.,-3./), (/2,3/))
  Print *, Maxloc(a)
  Print *, Maxloc(a,Dim=1)
  Print *, Maxloc(a,Dim=2)
  Print *, Maxloc(a,Mask=a<5)
End

■ Execution Results

 1 2
 2 1 1
 2 1
 1 3


＜MINLOC Example Program＞

Program minloc_example
  Real :: a(2,3)
  a = Reshape( (/2.,3.,5.,-1.,4.,-3./), (/2,3/))
  Print *, Minloc(a)
  Print *, Minloc(a,Dim=1)
  Print *, Minloc(a,Dim=2)
  Print *, Minloc(a,Mask=a<5)
End

■ Execution Results

 2 3
 1 2 2
 1 3
 1 1


＜MOD Example Program＞

Program mod_example
  Integer :: a(10) = [ (i-5,i=1,10) ]
  Print 1, a
  Print 1, a / 3
  Print 1, Mod(a,3)
1 Format(10I6)
End Program

■ Execution Results

    -4    -3    -2    -1     0     1     2     3     4     5
    -1    -1     0     0     0     0     0     1     1     1
    -1     0    -2    -1     0     1     2     0     1     2


＜MODULE Example Program＞

Module set
  Integer :: node = 0
  Real :: coord = 10.
End Module
Program module_example
  Use set
  Print *, node,coord
  Call sub()
  Print *, node,coord
End Program
Subroutine sub()
  Use set
  node = 5
  coord = 20.
End Subroutine

■ Execution Results

 0  10.0000000
 5  20.0000000


＜MODULE PROCEDURE Example Program＞

Module data_swap
  Interface swap
    Procedure int_swap, real_swap
  End Interface
Contains
  Subroutine int_swap(a,b)
    Integer,Intent(InOut) :: a,b
    Integer :: tmp
    tmp = a
    a = b
    b = tmp
  End Subroutine
  Subroutine real_swap(a,b)
    Real,Intent(InOut) :: a,b
    Real :: tmp
    tmp = a
    a = b
    b = tmp
  End Subroutine
End Module
Program module_procedure_example
  Use data_swap
  Integer :: i,j
  Real :: x,y
  i = 10 ; j = 20
  x = 3. ; y = 4.
  Call swap(i,j)
  Call swap(x,y)
  Print *, i,j
  Print *, x,y
End Program

■ Execution Results

 20 10
  4.0000000   3.0000000


＜MODULO Example Program＞

Program mod_example
  Integer :: a(10) = [ (i-5,i=1,10) ]
  Print 1, a
  Print 1, a / 3
  Print 1, Modulo(a,3)
1 Format(10I6)
End Program

■ Execution Results

    -4    -3    -2    -1     0     1     2     3     4     5
    -1    -1     0     0     0     0     0     1     1     1
     2     0     1     2     0     1     2     0     1     2


＜MOLD= Example Program＞

Module mold_types
  Type t1
    Integer :: a = 3
  End Type
  Type,Extends(t1) :: t2
    Integer :: b = 4
  End Type
End Module
Program mold_example
  Use mold_types
  Class(t1),Allocatable :: x
  Type(t2) :: y = t2(123,456)
  Allocate(x,Mold=y)
  Print 1,'Y',y
1 Format(1X,'Value of ',A,' is',99(1X,I0,:,','))
  Select Type (x)
  Type Is (t2)
    Print 1,'X',x
  Class Default
    Stop 'Impossible'
  End Select
End Program

■ Execution Results

 Value of Y is 123, 456
 Value of X is 3, 4


＜MOVE_ALLOC Example Program＞

Program move_alloc_example
  Character(:),Allocatable :: a(:), tmp(:)
  a = [ 'Hello','World' ]
  Print *, 'A has shape', Shape(a), 'length', Len(a), 'and value ', a
  Allocate(Character(6)::tmp(4))
  tmp(1) = 'First:'
  tmp(2:3) = a
  tmp(4) = ':Last!'
  Call Move_Alloc(tmp, a)
  Print *, 'A now has shape', Shape(a), 'length', Len(a), 'and value ', a
End Program

■ Execution Results

 A has shape 2 length 5 and value HelloWorld
 A now has shape 4 length 6 and value First:Hello World :Last!


NINT Example Program

<Example Program>

Program nint_example
  Call test( [ 10.49,10.50,10.51 ] )
Contains
  Subroutine test(a)
    Real,Intent(In) :: a(:)
    Print 1,a,Nint(a)
 1  Format(3F8.2,/,3I8)
    Print 1,-a,Nint(-a)
  End Subroutine
End Program

Execution Results

   10.49   10.50   10.51
      10      11      11
  -10.49  -10.50  -10.51
     -10     -11     -11


＜NON_RECURSIVE Example Program＞

Program non_recursive_example
  Print *, ifactorial(5)
End Program
Non_Recursive Integer Function ifactorial( i ) Result( res )
  Integer j
  res = 1
  Do j=2,i
    res = res*j
  End Do
End Function

■ Execution Results

 120


＜NUM_IMAGES Example Program＞

Program num_images_example
  If (Num_Images()==1) Then
    Print *,'Single image execution'
  Else If (This_Image()==Num_Images()) Then
    Print *,'Hello from image',Num_Images()
  End If
End Program

■ Execution Results

 Single image execution


Pointer Assignment Example Program

＜Pointer Assignment Example Program 1＞

Program pointer_asgn_example_1
  Integer,Pointer :: p,q(:)
  Integer,Target :: x(10) = (/ (i,i=1,10) /)
  p => x(1)
  Print *,p
  p => x(7)
  Print *,p
  q => x(2:10:3)
  q = q + p
  Print *,q
End Program

■ Execution Results

 1
 7
 9 12 15

＜Pointer Assignment Example Program 2＞

Program pointer_asgn_example_2 ! Lower-bounds setting.
  Integer,Pointer :: p(:,:)
  Integer,Target :: y(-10:10,1000:2000)
  p => y
  Print 1,Lbound(p),Ubound(p)
1 Format(1X,'Lower bounds are ',I0,1X,I0,', and the upper bounds are ',I0,1X,I0)
  p(1:,0:) => y
  Print 1,Lbound(p),Ubound(p)
End Program

■ Execution Results

 Lower bounds are -10 1000, and the upper bounds are 10 2000
 Lower bounds are 1 0, and the upper bounds are 21 1000

＜Pointer Assignment Example Program 3＞

Program pointer_asgn_example_3 ! Rank remapping.
  Integer,Pointer :: diagonal(:),matrix(:,:),storage(:)
  Integer i,j
  Allocate(storage(9))
  matrix(1:3,1:3) => storage
  diagonal => storage(1::4)
  matrix = 0
  diagonal = 1
  Print 1,((matrix(i,j),j=1,3),i=1,3)
1 Format(1X,3I5)
End Program

■ Execution Results

     1    0    0
     0    1    0
     0    0    1


＜PURE Example Program＞

Program pure_example
  Real, Dimension(2,3) :: a
  Forall (i=1:2,j=1:3) a(i,j) = f(i,j)
  Print 1, a
1 Format(6(2X,F0.5))
Contains
  Pure Real Function f(i,j)
    Integer, Intent(In) :: i, j
    f = i + j*0.1
  End Function
End Program

■ Execution Results

  1.10000  2.10000  1.20000  2.20000  1.30000  2.30000


＜RANK DEFAULT Example Program＞

Program select_rank_example
  Real d(1,5,1)
  Call example(d,Size(d))
Contains
  Subroutine example(x,n)
    Real x(*)
    Integer n
    Real a,b(2),c(2,2),d(2,2,2)
    Call set(x,n)
    Print 1,x(:n)
    Call set(a,n)
    Print 1,a
    Call set(b,n)
    Print 1,b
    Call set(c,n)
    Print 1,c
    Call set(d,n)
    Print 1,d
1   Format(*(F7.2))
  End Subroutine
  Subroutine set(y,n)
    Real y(..)
    Integer,Intent(In) :: n
    Select Rank (y)
    Rank (0)
      y = 1
    Rank (1)
      y = n
    Rank (2)
      y = n**2
    Rank (*)
      y(1:n) = -n
    Rank Default
      Stop 'Rank of argument out of range'
    End Select
  End Subroutine
End Program

■ Execution Results

  -5.00  -5.00  -5.00  -5.00  -5.00
   1.00
   5.00   5.00
  25.00  25.00  25.00  25.00
STOP: Rank of argument out of range


＜RANK statement Example Program＞

Program select_rank_example
  Real d(1,5,1)
  Call example(d,Size(d))
Contains
  Subroutine example(x,n)
    Real x(*)
    Integer n
    Real a,b(2),c(2,2),d(2,2,2)
    Call set(x,n)
    Print 1,x(:n)
    Call set(a,n)
    Print 1,a
    Call set(b,n)
    Print 1,b
    Call set(c,n)
    Print 1,c
    Call set(d,n)
    Print 1,d
1   Format(*(F7.2))
  End Subroutine
  Subroutine set(y,n)
    Real y(..)
    Integer,Intent(In) :: n
    Select Rank (y)
    Rank (0)
      y = 1
    Rank (1)
      y = n
    Rank (2)
      y = n**2
    Rank (*)
      y(1:n) = -n
    Rank Default
      Stop 'Rank of argument out of range'
    End Select
  End Subroutine
End Program

■ Execution Results

  -5.00  -5.00  -5.00  -5.00  -5.00
   1.00
   5.00   5.00
  25.00  25.00  25.00  25.00
STOP: Rank of argument out of range


＜REAL Example Program＞

Program real_example
  Real :: a
  a = 5.35678/1000
  Print *,a
End Program

■ Execution Results

   5.3567803E-03


＜RECURSIVE Example Program＞

Program recursive_example
  Print *, ifactorial(5)
End Program
Recursive Integer Function ifactorial( i ) Result( res )
  If (i<2) Then
    res = 1
  Else
    res = i*ifactorial( i-1 )
  End If
End Function

■ Execution Results

 120


＜REDUCE Example Program＞

Module triplet_m
  Type triplet
    Integer i,j,k
  End Type
Contains
  Pure Type(triplet) Function tadd(a,b)
    Type(triplet),Intent(In) :: a,b
    tadd%i = a%i + b%i
    tadd%j = a%j + b%j
    tadd%k = a%k + b%k
  End Function
End Module
Program reduce_example
  Use triplet_m
  Type(triplet) a(2,3)
  a = Reshape( [ triplet(1,2,3),triplet(1,2,4), &
                 triplet(2,2,5),triplet(2,2,6), &
                 triplet(3,2,7),triplet(3,2,8) ], [ 2,3 ] )
  Print 1, Reduce(a,tadd)
  Print 1, Reduce(a,tadd,1)
  Print 1, Reduce(a,tadd,a%i/=2)
  Print 1, Reduce(Array=a,Dim=2,Operation=tadd)
  Print 1, Reduce(a, Mask=a%i/=2, Dim=1, Operation=tadd, Identity=triplet(0,0,0))
1 Format(1x,6('triplet(',I0,',',I0,',',I0,')',:,'; '))
End Program

■ Execution Results

 triplet(12,12,33)
 triplet(2,4,7); triplet(4,4,11); triplet(6,4,15)
 triplet(8,8,22)
 triplet(6,6,15); triplet(6,6,18)
 triplet(2,4,7); triplet(0,0,0); triplet(6,4,15)


＜ROUND= Example Program＞

Program round_example
  Call test( [ 1.25, 1.75, -1.25, -1.75 ] )
Contains
  Subroutine test(a)
    Real,Intent(In) :: a(:)
    Write (*,1,Round='Compatible') 'Compatible', a
1   Format(1X,'ROUND="',A,'"',T25,4F6.1)
    Write (*,1,Round='Down') 'Down', a
    Write (*,1,Round='Nearest') 'Nearest', a
    Write (*,1,Round='Up') 'Up', a
    Write (*,1,Round='Zero') 'Zero', a
  End Subroutine
End Program

■ Execution Results

 ROUND="Compatible"        1.3   1.8  -1.3  -1.8
 ROUND="Down"              1.2   1.7  -1.3  -1.8
 ROUND="Nearest"           1.2   1.8  -1.2  -1.8
 ROUND="Up"                1.3   1.8  -1.2  -1.7
 ROUND="Zero"              1.2   1.7  -1.2  -1.7


＜Component Example Program＞

Program component_defn_example
   Type material
      Real young, poisson
   End Type material
   Type member
      Type(material) steel, concrete
   End Type member
   Type (member) kouzou
   kouzou%steel%young = 200.
   kouzou%concrete%young = 20.
   kouzou%steel%poisson = 0.3
   kouzou%concrete%poisson = 0.16
   Print 1, kouzou%steel
   Print 1, kouzou%concrete
1  Format(1X,2G15.6)
End

■ Execution Results

     200.000       0.300000
     20.0000       0.160000


＜SELECT CASE Example Program＞

Program select_case_example_1
  Integer x
  Read *, x
  Select Case (x)
  Case (1)
    Print *, 'one'
  Case (2)
    Print *, 'two'
  End Select
End Program

＜Example input 1＞

1

■ Execution Results

 one

＜Example input 2＞

2

■ Execution Results

 two


＜SELECT RANK Example Program＞

Program select_rank_example
  Real d(1,5,1)
  Call example(d,Size(d))
Contains
  Subroutine example(x,n)
    Real x(*)
    Integer n
    Real a,b(2),c(2,2),d(2,2,2)
    Call set(x,n)
    Print 1,x(:n)
    Call set(a,n)
    Print 1,a
    Call set(b,n)
    Print 1,b
    Call set(c,n)
    Print 1,c
    Call set(d,n)
    Print 1,d
1   Format(*(F7.2))
  End Subroutine
  Subroutine set(y,n)
    Real y(..)
    Integer,Intent(In) :: n
    Select Rank (y)
    Rank (0)
      y = 1
    Rank (1)
      y = n
    Rank (2)
      y = n**2
    Rank (*)
      y(1:n) = -n
    Rank Default
      Stop 'Rank of argument out of range'
    End Select
  End Subroutine
End Program

■ Execution Results

  -5.00  -5.00  -5.00  -5.00  -5.00
   1.00
   5.00   5.00
  25.00  25.00  25.00  25.00
STOP: Rank of argument out of range


＜SELECT TYPE Example Program＞

Module type_module
  Type value_type
    Character(Len=8) name
  End Type
  Type, Extends(value_type) :: real_value
    Real x
  End Type
  Type, Extends(value_type) :: integer_value
    Integer v
  End Type
Contains
  Subroutine print(value)
    Class(value_type), Intent(In) :: value
    Write (*,'(A)',Advance='No') '"'//Trim(value%name)//'" is '
    Select Type (value)
    Class Is (real_value)
      Print *, 'Real',value%x
    Class Is (integer_value)
      Print *, 'Int',value%v
    Class Default
      Print *, 'Unrecognised'
    End Select
  End Subroutine
End Module
Program select_type_example
  Use type_module
  Type(real_value) :: x = real_value('one',17.5)
  Type(integer_value) :: y = integer_value('two',42)
  Type, Extends(value_type) :: logical_value
    Logical x
  End Type
  Type(logical_value) :: z = logical_value('three',.false.)
  Call print(x)
  Call print(y)
  Call print(z)
End Program

■ Execution Results

  "one" is Real  17.5000000
  "two" is Int 42
  "three" is Unrecognised


Separate Module Procedures Example Programs

＜Separate Module Procedures Example Program 1＞

Module separate_mp_example_mod
  Integer,Parameter :: wp = Selected_Real_Kind(10)
  Interface
    Module Real(wp) Function myfun(x)
      Real(wp),Intent(In) :: x
    End Function
  End Interface
Contains
  Real(wp) Module Function myfun(x)
    Real(wp),Intent(In) :: x
    myfun = (x+1)*(x-1)*(x+4)
  End Function
End Module
Program test
  Use separate_mp_example_mod
  Print 1,myfun(-0.5_wp),myfun(0.5_wp),myfun(1.5_wp)
1 Format(3F10.4)
End Program

■ Execution Results

   -2.6250   -3.3750    6.8750

＜Separate Module Procedures Example Program 2＞

Module separate_mp_example_mod2
  Interface
    Module Recursive Real Function f(x,y) Result(res)
      Real,Intent(In) :: x,y
    End Function
  End Interface
Contains
  Module Procedure f
    If (y>x) Then
      res = f(x,-Abs(y))
    Else
      res = x**2 - y**3
    End If
  End Procedure
End Module
Program test
  Use separate_mp_example_mod2
  Print 1,f(1.5,2.5),f(2.5,1.5),f(1.5,1.5)
1 Format(3F10.4)
End Program

■ Execution Results

   17.8750    2.8750   -1.1250


＜SIGN Example Program＞

Program sign_example
  Real :: a(4) = [ -1.0, -0.0, +0.0, +1.0 ]
  Print 1, 'A', a
  Print 1, 'SIGN(A,-1)', Sign(a, -1.0)
  Print 1, 'SIGN(A,-0)', Sign(a, -0.0)
  Print 1, 'SIGN(A,+0)', Sign(a, +0.0)
  Print 1, 'SIGN(A,+1)', Sign(a, +1.0)
1 Format(1X,A10,' = ',SP,4F8.3)
End Program

■ Execution Results

          A =   -1.000  -0.000  +0.000  +1.000
 SIGN(A,-1) =   -1.000  -0.000  -0.000  -1.000
 SIGN(A,-0) =   -1.000  -0.000  -0.000  -1.000
 SIGN(A,+0) =   +1.000  +0.000  +0.000  +1.000
 SIGN(A,+1) =   +1.000  +0.000  +0.000  +1.000


＜SOURCE= Example Program＞

Program source_example
  Integer,Allocatable :: a(:)
  Class(*),Allocatable :: x
  Allocate(a,Source=[11,22,33])
  Print 1,Size(a),a
1 Format(1X,I0,':',999(1X,I0,:))
  Allocate(x,Source='Hello source')
  Select Type (x)
  Type Is (Character(*))
    Print *,x
  Class Default
    Stop 'Impossible'
  End Select
End Program

■ Execution Results

 3: 11 22 33
 Hello source


＜STAT= Example Program＞

Program stat_example
  Real,Allocatable :: a(:)
  Call newmem(100)
  Print 1,Size(a)
1 Format(1X,'Got memory: ',I0,' elements')
  Call newmem(1000)
  Print 1,Size(a)
  Print *,'Finished'
Contains
  Subroutine newmem(n)
    Integer,Intent(In) :: n
    Integer stat
    Character(100) error
    Deallocate(a,Stat=stat,Errmsg=error)
    If (stat/=0) Then
      Print *,'Deallocation error: ',Trim(error),'; continuing'
    End If
    If (Allocated(a)) Stop 'Cannot continue - still allocated'
    Allocate(a(n),Stat=stat,Errmsg=error)
    If (stat/=0) Then
      Print *,Trim(error)
      Stop 'Cannot continue - allocation failed'
    End If
  End Subroutine
End Program

■ Execution Results

 Deallocation error: Allocatable variable is not allocated; continuing
 Got memory: 100 elements
 Got memory: 1000 elements
 Finished


STOP Example Program

＜STOP Example Program 1＞

Program stop_example_1
  Print *, 'ABC'
  Call sub
  Print *, 'XYZ'
End Program
Subroutine sub
  Stop
End Subroutine

■ Execution Results

 ABC

＜STOP Example Program 2＞

Program stop_example_2
  Print *, 'Hello'
  Stop 'Goodbye'
End Program

■ Execution Results

 Hello
STOP: Goodbye

＜STOP Example Program 3＞

Program stop_example_3
  Print *,'Program started'
  Call stopme('quietly',.True.)
Contains
  Subroutine stopme(why,quiet)
    Character(*),Intent(In) :: why
    Logical,Intent(In) :: quiet
    Stop 'Program stopped '//why, Quiet=quiet
  End Subroutine
End Program

■ Execution Results

 Program started


＜STOPPED_IMAGES Example Program＞

Program stopped_images_example
  Use Iso_Fortran_Env
  Implicit None
  Integer i,istat
  If (Num_Images()<3) Error Stop 'Not enough images'
  If (This_Image()==3) Stop
  Sync All(Stat=istat)
  If (istat==Stat_Stopped_Image) Then
    If (This_Image()==1) Print *,'Stopped images:',Stopped_Images()
    Sync Images( [ 1,2,(i,i=4,Num_Images()) ] )
  End If
End Program

■ Execution Results

 Stopped images: 3


＜SUBMODULE Example Program＞

Module mymod
  Interface
    Module Integer Function next_number() Result(res)
    End Function
    Module Subroutine reset()
    End Subroutine
  End Interface
End Module
Submodule (mymod) variables
  Integer :: next = 1
End Submodule
Submodule (mymod:variables) functions
Contains
  Module Procedure next_number
    res = next
    next = next + 1
  End Procedure
End Submodule
Submodule (mymod:variables) subroutines
Contains
  Module Subroutine reset()
    Print *,'Resetting'
    next = 1
  End Subroutine
End Submodule
Program demo
  Use mymod
  Print *,'Hello',next_number()
  Print *,'Hello again',next_number()
  Call reset
  Print *,'Hello last',next_number()
End Program

■ Execution Results

 Hello 1
 Hello again 2
 Resetting
 Hello last 1


＜SUBROUTINE Example Program＞

Program subroutine_example
  Real x1,x2
  Call shiki(1.0,3.0,2.0,x1,x2)
  Print *, x1,x2
End
Subroutine shiki(a,b,c,x1,x2)
  Real, Intent(In) :: a,b,c
  Real, Intent(Out) :: x1,x2
  tmp = b**2 - 4.0*a*c
  x1 = (-b+Sqrt(tmp))/(2.0*a)
  x2 = (-b-Sqrt(tmp))/(2.0*a)
End Subroutine shiki

■ Execution Results

  -1.0000000  -2.0000000


＜SYNC ALL Example Program＞

Program sync_all_example
  Implicit None
  Real :: a[*]
  Integer i
  ! The first image will set the value of the coarray A on every image.
  If (This_Image()==1) Then
    Do i = 1, Num_Images()
      a[i] = i**2
    End Do
  End If
  ! Wait for image one to finish.
  Sync All
  ! Check the results.
  If (a/=This_Image()**2) Error Stop 'FAILed'
  ! Wait for everyone to finishing checking.
  Sync All
  ! The last image will report success.
  If (This_Image()==Num_Images()) Print *,'ok'
End Program

■ Execution Results

 ok


SYNC ALL Example Program

＜SYNC IMAGES Example Program＞

Program sync_images_example
  Implicit None
  Real :: a[*]
  Integer i
  ! The first image will set the value of the coarray A on every image.
  If (This_Image()==1) Then
    Do i = 1, Num_Images()
      a[i] = i**2
    End Do
    ! Tell the other images (if any) the data is ready.
    Sync Images (*)
  Else
    ! Wait for image one to prepare the data.
    Sync Images (1)
  End If
  ! Each image checks its own results.
  If (a/=This_Image()**2) Error Stop 'FAILed'
  ! Wait for everyone to finishing checking.
  Sync All
  ! The last image will report success.
  If (This_Image()==Num_Images()) Print *,'ok'
End Program

■ Execution Results

 ok


＜SYNC MEMORY Example Program＞

Program sync_memory_example
  Integer :: value[*]
  If (This_Image()==1) Then
    value = 123
    ! Segment break before the synchronisation.
    Sync Memory
    ! Use the filesystem to synchronise.
    Open(13,File='u2.tmp',Status='New')
    Close(13)
  End If
  If (This_Image()==Num_Images()) Then
    ! Wait for the first image to create the file.
    Do
      Open(17,File='u2.tmp',Status='Old',Err=100)
      Exit
100   Continue
    End Do
    ! Segment break after the synchronisation.
    Sync Memory
    If (value[1]==123) Then
      Print *,'ok'
    Else
      Print *,'FAIL',value[1]
    End If
    Close(17,Status='Delete')
  End If
End Program

■ Execution Results

  ok


＜SYNC TEAM Example Program＞

Program sync_team_example
  Use iso_fortran_env
  Implicit None
  Integer :: a[*],b[*]
  Integer i,me,myteamid
  Integer,Parameter :: redteam = 1, greenteam = 2, blackteam = 3
  Type(team_type) redgreenblack,initialteam
  If (Num_Images()<4) Error Stop 'Need at least four images'
  me = This_Image()
  myteamid = Merge(redteam,Merge(greenteam,blackteam,me<5),me<3)
  initialteam = Get_Team()
  Form Team(myteamid,redgreenblack)
  Change Team(redgreenblack)
    If (myteamid==redteam) Then
      a = me*100
    Else If (myteamid==greenteam) Then
      a = me**3
    Else ! blackteam
      a = 0
    End If
    ! Need to sync the initial team, as we will reference their values.
    Sync Team (initialteam)
    b = 0
    Do i=1,4
      b = b + a[i,Team=initialteam]
    End Do
  End Team
  Sync All
  If (This_Image()==1) Then
    Do i = 2, Num_Images()
      If (b[i]/=b) Error Stop 'FAIL value check'
    End Do
    Print *,'Value confirmed as',b
  End If
End Program

■ Execution Results

 Value confirmed as 391


＜THIS_IMAGE Example Program＞

Program this_image_example
  Real x[3,4:5,-6:*]
  If (This_Image()==1) Then
    Print 1,'On image 1'
1   Format(1X,A,99(:,1X,I0))
    Print 1,'My cosubscripts for X are:',This_Image(x)
    Print 1,'My cosubscript for codimension 2 of X are:',This_Image(x,2)
  End If
End Program

■ Execution Results

 On image 1
 My cosubscripts for X are: 1 4 -6
 My cosubscript for codimension 2 of X is: 4


＜Type-bound procedure Example Program＞

Module simple_callback
  Type callback_object
    Character(6) :: id = ''
    Logical :: stop = .False.
  Contains
    Procedure :: action => basic_callback_proc
  End Type
Contains
  Subroutine basic_callback_proc(me)
    Class(callback_object) me
    If (me%stop) Then
      If (me%id/='') Then
        Print *,'Goodbye from ',Trim(me%id)
      Else
        Print *,'Goodbye from no-one.'
      End If
    Else If (me%id/='') Then
      Print *,'Hello from ',Trim(me%id)
    End If
    If (me%stop) Stop
  End Subroutine
  Subroutine process(cba)
    Class(callback_object) cba(:)
    Do i=1,Size(cba)
      Call cba(i)%action
    End Do
  End Subroutine
End Module

Program example
  Use simple_callback
  Type(callback_object) x(5)
  x(1) = callback_object('X1',.False.)
  x(3)%id = 'Noone'
  x(5)%id = 'End!'
  x(5)%stop = .True.
  Call process(x)
End Program

■ Execution Results

 Hello from X1
 Hello from Noone
 Goodbye from End!


＜UBOUND Example Program＞

Program ubound_example
  Real a(0:2,4)
  Print 1, Ubound(a,Dim=1)
  Print 1, Ubound(a,Dim=2)
  Print 1, Ubound(a)
1 Format(99(1X,I0,:,','))
End

■ Execution Results

 2
 4
 2, 4


＜UCOBOUND Example Program＞

Program ucobound_example
  Real a[0:2,*]
  If (This_Image()==1) Then
    Print 1, Ucobound(a,Dim=1)
    Print 1, Ucobound(a,Dim=2)
    Print 1, Ucobound(a)
1   Format(99(1X,I0,:,','))
  End If
End

■ Execution Results

With the number of images equal to one:
 2
 1
 2, 1
With the number of images equal to eight:
 2
 3
 2, 3


＜UNLOCK Example Program＞

Program unlock_example
  Use Iso_Fortran_Env
  Type(lock_type) :: worklock[*]
  Type work_type
    Integer value
    Logical avail,done
  End Type
  Type(work_type) :: work(10)[*] = work_type(0,.True.,.False.)
  !
  ! Only the WORK variable on image 1 is used, to keep track.
  ! Similarly, only the WORKLOCK variable on image 1 is used.
  !
  Integer i
  Do
    Lock(worklock[1])
    Do i=1,Size(work)
      If (work(i)[1]%avail) Then
        ! Unset avail while we still hold the lock.
        work(i)[1]%avail = .False.
        Exit
      End If
    End Do
    Unlock(worklock[1])
    If (i>Size(work)) Exit ! No work available.
    !
    ! A real program would do some real work here.
    ! This example will just assign I to the value on image 1.
    !
    work(i)[1]%value = i
    work(i)[1]%done = .True.
  End Do
  ! Wait for all images to finish the work.
  Sync All
  ! Image 1 will check the results.
  If (This_Image()==1) Then
    Do i=1,Size(work)
      If (.Not.work(i)%done) Error Stop 'Work was not done'
    End Do
    Print *,'Work complete'
  End If
End Program

■ Execution Results

 Work complete


＜VALUE Example Program＞

Program value_example
  Integer :: ivar,jvar
  ivar = 17
  jvar = 42
  !
  Call inner(ivar,jvar)
  !
  ! The variable IVAR will still be equal to 17,
  ! but JVAR will have been changed by INNER.
  !
  Print *,ivar,jvar
  !
Contains
  Subroutine inner(a,b)
    Integer,Value :: a
    Integer,Intent(InOut) :: b
    Print *,a,b
    a = a**2  ! Only changes the local copy.
    b = b**2  ! Changes the actual argument.
    Print *,a,b
  End Subroutine
End Program

■ Execution Results

 17 42
 289 1764
 17 1764


＜WAIT Example Program＞

Program wait_example
  Real,Asynchronous :: a(100,2)
  Logical finished
  Open (17,File='Results',Form='Unformatted',Asynchronous='Yes')
  Do
    Call produce_results(a(:,1),finished)
    Call write_results(a(:,1))
    If (finished) Exit
    Call produce_results(a(:,2),finished)
    Call write_results(a(:,2))
    If (finished) Exit
  End Do
Contains
  Subroutine produce_results(vector,finished)
    Real,Intent(Out) :: vector(:)
    Logical,Intent(Out) :: finished
    Call Random_Number(vector)
    finished = vector(1)
  End Subroutine
  Subroutine write_results(vector)
    Real,Asynchronous,Intent(In) :: vector(:)
    Wait (17)
    Write (17,Asynchronous='Yes') vector
  End Subroutine
End Program

＜Comments＞

The use of the ASYNCHRONOUS attribute allows the overlap of the writing of one set of results while computing the next. The WAIT statement in WRITE_RESULTS waits for the previous output to unit 17 to finish, thus ensuring that the previous VECTOR can be re-used for computation.

The ASYNCHRONOUS attribute is needed to tell the compiler that A is subject to asynchronous input/output; this information prevents unsafe optimisations.


＜WHERE Example Program＞

Program where_statement_example
  Real a(2,2)
  a = Reshape( (/-1.,2.,3.,4./), (/2,2/))
  Where (a<0.) a = 0.0
  Print *, a(1,:)
  Print *, a(2,:)
End Program

■ Execution Results

  0.0000000   3.0000000
  2.0000000   4.0000000


＜WHERE Example Program＞

Program where_construct_example
  Real a(2,2)
  a = Reshape( (/-1.,2.,3.,4./), (/2,2/))
  Where (a<0.)
    a = 0.0
  Elsewhere (a>3.)
    a = 1.0
  Elsewhere
    a = 10*a
  End Where
  Print *, a(1,:)
  Print *, a(2,:)
End Program

■ Execution Results

   0.0000000  30.0000000
  20.0000000   1.0000000


＜WRITE Example Program＞

Program write_example
  Write (*,*) (i,i=1,3)
  Write (*,*) (5,j=1,3)}
End Program

■ Execution Results

  1  2  3
  5  5  5


END SUBMODULE statement

Standard: F77 F90 F95 F2003 F2008 F2018 Example program

＜Syntax＞

END [ SUBMODULE [ submodule-name ] ]

The blank between END and SUBMODULE is optional.

＜Semantics＞

The END SUBMODULE statement marks the end of a submodule program unit.

＜Related＞

END statement, MODULE statement, SUBMODULE statement


LOG example program

<Example Program>

Program log_example
  Real :: a(3) = [ 1,10,100 ]
  Complex :: c(3) = [ (0,1), (-1,0), (5,5) ]
  Print 1, Log(a)
1 Format(3(2X,F0.5))
  Print 2, Log(c)
2 Format(3(2X,'(',F0.5,',',F0.5,')'))
End Program

Execution Results

  .00000  2.30259  4.60517
  (.00000,1.57080)  (.00000,3.14159)  (1.95601,.78540)


<Example Program>

Program merge_example
Real :: a(3) = (/ 1.,-2.,3. /)
Real :: b(3) = (/ 4.,5.,6. /)
Real :: c(3)
c = Merge(a,b,Mask=a>0)
Print *, c
End
Execution Results

1.0000000 5.0000000 3.0000000


NEWUNIT= example program

<Example Program>

Program newunit_example
Integer :: unit
Open (Newunit=unit,File='DAT',Status='old',Position='Rewind')
n_lines = 0
Do
Read (unit,'( )',End=10)
n_lines = n_lines + 1
End Do
10 Continue
Print *,'There are',n_lines,'lines in the file.'
Close(unit)
End Program
Contents of file: DAT

This is line 1
This is line 2
This is line 3; it is longer than the other lines

Execution Results

There are 3 lines in the file.


<Example Program>

Program pointer_example
Integer, Pointer :: i(:,:)
Integer, Target :: j(2,2)
j = 1
i => j
Print *, i
Print *, j
End
Execution Results

1 1 1 1
1 1 1 1


RANK DEFAULT statement

Standard: F77 F90 F95 F2003 F2008 F2018 Example program

＜Syntax＞

RANK DEFAULT [ construct-name ]

The construct-name shall appear if and only if the SELECT RANK statement is named.

＜Semantics＞

If the rank (and assumed-size-ness) of the variable-name in the SELECT RANK statement does not match any other RANK statement in the construct, the block of statements following the RANK DEFAULT statement is executed. Within that block, variable-name remains assumed-rank, the same as outside the construct.

There must be no more than one RANK DEFAULT statement in a SELECT RANK construct.

＜Related＞

RANK statement, END SELECT statement, SELECT RANK construct


RANK statement

Standard: F77 F90 F95 F2003 F2008 F2018 Example program

＜Syntax＞

RANK ( expression | * ) [ construct-name ]

The expression must be a scalar Integer constant expression with a non-negative value. The construct-name shall appear if and only if the SELECT RANK statement is named.

＜Semantics＞

If the RANK statement is “RANK (*)”, and the variable-name in the SELECT RANK statement is argument associated with an assumed-size array, the block of statements following that RANK statement is executed. Within that block, variable-name is treated as if it were declared as “(1:*)”; that is, it is a rank one assumed-size array with lower bound equal to one.

If the RANK statement is “RANK (expression)”, and the variable-name in the SELECT RANK statement is not associated with an assumed-size array, and the rank of the variable-name is equal to the expression, the block of statements following that RANK statement is executed. Within that block,

  • if expression is equal to zero, variable-name is scalar;
  • otherwise, if variable-name is allocatable or a pointer, it is treated as an allocatable array or array pointer with deferred shape (and that rank);
  • otherwise, variable-name is treated as if it were an assumed-shape array, with the shape of its associated argument, and lower bounds equal to LOWER(variable-name).

Note that the RANK conditions must be distinct, i.e. not a duplicate of another RANK statement in the same construct.

＜Related＞

RANK DEFAULT statement, END SELECT statement, SELECT RANK construct


REDUCE intrinsic function

Standard: F77 F90 F95 F2003 F2008 F2018 Example program

＜Syntax＞

REDUCE ( ARRAY, OPERATION [ , MASK, IDENTITY, ORDERED ] ) or
REDUCE ( ARRAY, OPERATION DIM, [ , MASK, IDENTITY, ORDERED ] )

ARRAY : array of any type;
OPERATION : pure function with two arguments, each argument being scalar, non-allocatable, non-pointer,
non-polymorphic non-optional variables with the same declared type and type parameters as ARRAY;
if one argument has the ASYNCHRONOUS, TARGET or VALUE attribute, the other must also
have that attribute;
the result must be a non-polymorphic scalar variable with the same type and type parameters as ARRAY;
DIM : scalar Integer in the range 1 to N, where N is the rank of ARRAY;
MASK : type Logical, and either scalar or an array with the same shape as ARRAY;
IDENTITY : scalar with the same declared type and type parameters as ARRAY;
ORDERED : scalar of type Logical;

Result : Same type and type parameters as ARRAY.

＜Semantics＞

The result is ARRAY reduced by the user-supplied OPERATION. If DIM is absent, the result is scalar. If DIM is present, the result has rank N-1 and the shape of ARRAY with dimension DIM removed; each element of the result is the reduction of the masked elements in that dimension.

If exactly one element contributes to a result value, that value is equal to the element; that is, OPERATION is only invoked when more that one element appears.

If no elements contribute to a result value, the IDENTITY argument must be present, and that value is equal to IDENTITY.

＜Related＞

ALL intrinsic function, ANY intrinsic function, COUNT intrinsic function, IALL intrinsic function, IAND intrinsic function, IANY intrinsic function, IPARITY intrinsic function, MAXLOC intrinsic function, MAXVAL intrinsic function, MINLOC intrinsic function, MINVAL intrinsic function, PARITY intrinsic function, PRODUCT intrinsic function, Reduction intrinsic functions, SUM intrinsic function


SCALE intrinsic function
Standard: F77 F90 F95 F2003 F2008 Example Program
<Syntax>

SCALE ( X, I )

X : Real with any kind;
I : Integer with any kind;

Result : same type and kind as X.

<Semantics>

The result is the value X*RADIX(X)**I without computing RADIX(X)**I directly; that is, even if I is less than MINEXPONENT(X) or greater than MAXEXPONENT(X), so that RADIX(X)**I would be out of range (underflow or overflow), as long as X*RADIX(X)**I is not out of range there is no underflow or overflow.

Like many intrinsic functions, this is elemental; the result has the same shape as X, with the operation being applied elementwise.

<Related>
MAXEXPONENT intrinsic function, MINEXPONENT intrinsic function, RADIX intrinsic function, REAL type, SET_EXPONENT intrinsic function.


SCALE example program

<Example Program>

Program scale_example
  Implicit None
  Real :: x = Real(Radix(0.0))**(MinExponent(0.0)+1)
  Integer i
  Do i = 0, 3
    Print *,Scale(x,i)
  End Do
  Print *,Scale(x,MaxExponent(0.0)+2)
End Program

Execution Results

   4.7019774E-38
   9.4039548E-38
   1.8807910E-37
   3.7615819E-37
  64.0000000


SELECT RANK construct

Standard: F77 F90 F95 F2003 F2008 F2018 Example program

＜Syntax＞

The syntax of the SELECT RANK construct is as follows.

select-rank-stmt
[ rank-stmt | rank-default-stmt
block ]...
end-select-stmt

The syntax of the SELECT RANK statement is:

select-rank-stmt ::= [ construct-name : ] SELECT RANK ( variable-name )

The variable-name must be the name of an assumed-rank dummy argument.

＜Semantics＞

The SELECT RANK construct begins with a SELECT RANK statement and ends with an END SELECT statement. When the SELECT RANK statement is executed, the rank and status of the variable is examined; if this satisfies one of the RANK conditions, the corresponding block is executed, otherwise control is transferred to the END SELECT statement.

Note that the RANK conditions must be distinct, i.e. not a duplicate of another RANK statement in the same construct.

＜Related＞

RANK statement, RANK DEFAULT statement, END SELECT statement


Separate module procedures

Standard: F77 F90 F95 F2003 F2008 F2018 Example program

＜Syntax＞

A “separate module procedure” is a procedure whose interface is declared in the specification part of a module, but whose definition may provided either in the module itself, or in a submodule of that module. The interface of a separate module procedure is declared by using the MODULE keyword in the prefix of the FUNCTION or SUBROUTINE statement.

A separate module procedure may be defined by a module subprogram that also uses the MODULE keyword in its FUNCTION or SUBROUTINE statement. This definition must have exactly the same characteristics, the same names for the dummy arguments, the same name for the result variable (if a function), and if it uses BIND(C), the same binding-name. Also, it must be RECURSIVE if and only if the interface is declared so. (The compiler will check that all these are correct.) In Fortran 2018, procedures are RECURSIVE by default, and so this requirement becomes that it must be NON_RECURSIVE if and only if the interface is so declared.

Alternatively, a separate module procedure may be defined by a separate module subprogram, which has the syntax:
mp-subprogram-stmt
specification-part
execution-part
internal-subprogram-part
end-mp-subprogram-stmt
where
mp-subprogram-stmt ::= MODULE PROCEDURE procedure-name
and
end-mp-subprogram-stmt ::= END PROCEDURE [ procedure-name ]

The separate module subprogram syntax automatically provides the characteristics, dummy argument names, etc..

Note that although the mp-subprogram-stmt has similar syntax to the MODULE PROCEDURE statement, it appears in a different place and has different semantics.

＜Semantics＞

Separate module procedures are called “separate” because they allow the separation of the interface (declared in the module specification part) and the definition. If submodules are being used, the definition need not be in the same file as the interface declaration.

An important aspect of the interface for a separate module procedure is that, unlike any other interface body, it accesses the module by host association without the need for an IMPORT statement. This makes it easier to use derived types and named constants defined by the module.

＜Related＞

FUNCTION statement, INTERFACE statement, INTERFACE ASSIGNMENT statement, INTERFACE OPERATOR statement, MODULE statement, SUBMODULE statement, SUBROUTINE statement


SET_EXPONENT example program

<Example Program>

Program set_exponent_example
  Implicit None
  Real :: x(3) = [ 1.375*2.0**(-100), 1.375, 1.375*2.0**100 ]
  Print 1, 'x', x
1 Format(1X,A20,1X,3ES12.4)
  Print 1, 'scale formula(0)', Scale(x,0-Exponent(x))
  Print 1, 'fraction form(0)', Fraction(x)
  Print 1, 'set exponent (0)',Set_Exponent(x,0)
  Print 1, 'set exponent (1)',Set_Exponent(x,1)
End Program

Execution Results

                    x   1.0847E-30  1.3750E+00  1.7430E+30
     scale formula(0)   6.8750E-01  6.8750E-01  6.8750E-01
     fraction form(0)   6.8750E-01  6.8750E-01  6.8750E-01
     set exponent (0)   6.8750E-01  6.8750E-01  6.8750E-01
     set exponent (1)   1.3750E+00  1.3750E+00  1.3750E+00


<Example Program>

Program type_example
Type material
Character(Len=5) :: name
Real :: young,poisson
End Type material
Type (material) steel,concrete
steel%name = 'A36'
steel%young = 200.
steel%poisson = 0.3
concrete = material( 'A36',200.,0.3 )
Print *, steel
Print *, concrete
End
Execution Results

A36 2.0000000E+02 0.3000000
A36 2.0000000E+02 0.3000000


a00aafe.r

 A00AAF Example Program Results

 *** Start of NAG Library implementation details ***

 Implementation title: ?OS?, ?x?-bit, ?Fortran compiler? (?y?-bit integers)
            Precision: Fortran double precision
         Product Code: ?FL?
                 Mark: ?z? (self-contained)

 *** End of NAG Library implementation details ***


a00acfe.r

 A00ACF Example Program Results

 A valid licence key is available


a00adfe.r

 A00ADF Example Program Results

*** Start of NAG Library implementation details ***

Implementation title: ?OS?, ?x?-bit, ?Fortran compiler? (?y?-bit integers)
           Precision: Fortran double precision
        Product Code: ?FL?
                Mark: ?z?
      Vendor Library: ?vendlib?
Applicable to:
            hardware: ?hardware?
    operating system: ?OS long?
    Fortran compiler: ?Fortran compiler long?
and compatible systems.
       Licence query: Successful

*** End of NAG Library implementation details ***

 This program was run on the following date:
   YYYYMMDD-HH:MM:SS:MSS
 *** ----------------------------------------- ***


a02aafe.r

 A02AAF Example Program Results

    XR    XI      YR       YI
   -1.7   2.6   0.8386   1.5502


a02abfe.r

 A02ABF Example Program Results

    XR    XI       Y
   -1.7   2.6   3.1064


a02acfe.r

 A02ACF Example Program Results

    XR    XI    YR    YI      ZR       ZI
   -1.7   2.6  -3.1  -0.9   0.2812  -0.9203


c02affe.r

 C02AFF Example Program Results

 Example 1

 Degree of polynomial =    5

 Computed roots of polynomial

 z =  -2.4328E+01 -4.8555E+00*i
 z =   5.2487E+00 +2.2736E+01*i
 z =   1.4653E+01 -1.6569E+01*i
 z =  -6.9264E-03 -7.4434E-03*i
 z =   6.5264E-03 +7.4232E-03*i

 Example 2

 Degree of polynomial =    5

 Computed roots of polynomial     Error estimates
                                (machine-dependent)

 z =  -2.4328E+01 -4.8555E+00*i       1.1E-16
 z =   5.2487E+00 +2.2736E+01*i       3.0E-16
 z =   1.4653E+01 -1.6569E+01*i       3.2E-16
 z =  -6.9264E-03 -7.4434E-03*i       1.7E-16
 z =   6.5264E-03 +7.4232E-03*i       1.1E-16


c02agfe.r

 C02AGF Example Program Results

 Example 1

 Degree of polynomial =    5

 Computed roots of polynomial

 z =  -1.4918E+00
 z =   5.5169E-01 +/-   1.2533E+00*i
 z =  -8.0579E-01 +/-   1.2229E+00*i

 Example 2

 Degree of polynomial =    5

 Computed roots of polynomial     Error estimates
                                (machine-dependent)

 z =  -1.4918E+00 +0.0000E+00*i       1.0E-15
 z =   5.5169E-01 +1.2533E+00*i       1.1E-16
 z =   5.5169E-01 -1.2533E+00*i       1.1E-16
 z =  -8.0579E-01 +1.2229E+00*i       1.5E-16
 z =  -8.0579E-01 -1.2229E+00*i       1.5E-16


c02ahfe.r

 C02AHF Example Program Results

 Roots of quadratic equation

 z =   1.0000E+00   +2.0000E+00*i
 z =   2.0000E+00   -3.0000E+00*i


c02ajfe.r

 C02AJF Example Program Results

 Roots of quadratic equation

 z =   2.0000E+00
 z =  -5.0000E+00


c02akfe.r

 C02AKF Example Program Results

  Roots of cubic equation             Error estimates
                                    (machine-dependent)

  z =   1.0000E+00 +0.0000E+00*i          1.0E-15
  z =  -2.0000E+00 +3.0000E+00*i          1.0E-15
  z =  -2.0000E+00 -3.0000E+00*i          1.0E-15


c02alfe.r

 C02ALF Example Program Results

  Roots of quartic equation           Error estimates
                                    (machine-dependent)

  z =   2.0000E+00 +0.0000E+00*i          8.9E-16
  z =  -2.0000E+00 +0.0000E+00*i          1.1E-15
  z =  -1.0000E+00 +3.0000E+00*i          1.0E-15
  z =  -1.0000E+00 -3.0000E+00*i          1.0E-15


c02amfe.r

 C02AMF Example Program Results

  Roots of cubic equation             Error estimates
                                    (machine-dependent)

  z =  -2.0000E+00 +3.0000E+00*i          1.7E-15
  z =   1.0000E+00 -2.0000E+00*i          3.6E-15
  z =   3.0000E+00 -4.0000E+00*i          3.7E-15


c02anfe.r

 C02ANF Example Program Results

  Roots of quartic equation           Error estimates
                                    (machine-dependent)

  z =   3.0000E+00 -2.0000E+00*i          3.0E-15
  z =   1.0000E+00 -2.0000E+00*i          2.9E-15
  z =  -2.0000E+00 +1.0000E+00*i          2.9E-15
  z =  -2.0000E+00 +3.0000E+00*i          3.0E-15


c05aufe.r

 C05AUF Example Program Results

 Root is       0.56714
 Interval searched is [ 0.50000, 0.90000]


c05avfe.r

 C05AVF Example Program Results

 Interval containing root is [X,Y], where
 X =      1.7000   Y =      2.5000
 Values of f at X and Y are
 f(X) =     -0.2100   f(Y) =      0.7500


c05awfe.r

 C05AWF Example Program Results

 With EPS =   0.10E-02   root =        0.56715
 With EPS =   0.10E-03   root =        0.56715


c05axfe.r

 C05AXF Example Program Results

 TOL = 0.1000E-02

 Root is        0.56715

 TOL = 0.1000E-03

 Root is        0.56715


c05ayfe.r

 C05AYF Example Program Results

 Zero at X =     0.56714


c05azfe.r

 C05AZF Example Program Results

  Iterations

  X = 0.00000   FX =  0.1000E+01   IND = 2
  X = 1.00000   FX = -0.6321E+00   IND = 3
  X = 0.61270   FX = -0.7081E-01   IND = 4
  X = 0.56707   FX =  0.1154E-03   IND = 4
  X = 0.56714   FX = -0.9448E-06   IND = 4
  X = 0.56713   FX =  0.1473E-04   IND = 4
  X = 0.56714   FX = -0.9448E-06   IND = 4

  Solution

  X = 0.56714   Y = 0.56713


c05bafe.r

 C05BAF Example Program Results

 BRANCH =   0
 OFFSET = .FALSE.

         X           W(X)     IFAIL

    5.00000E-01   3.51734E-01     0
    1.00000E+00   5.67143E-01     0
    4.50000E+00   1.26724E+00     0
    6.00000E+00   1.43240E+00     0
    7.00000E+07   1.53339E+01     0


c05bbfe.r

 C05BBF Example Program Results

 BRANCH =   0
 OFFSET = .FALSE.

               Z                            W(Z)                  RESID    IFAIL

 (  5.00000E-01, -1.00000E+00) (  5.16511E-01, -4.22053E-01)   5.55112E-17     0
 (  1.00000E+00,  2.30000E+00) (  8.73606E-01,  5.76978E-01)   1.11022E-16     0
 (  4.50000E+00, -1.00000E-01) (  1.26735E+00, -1.24194E-02)   0.00000E+00     0
 (  6.00000E+00,  6.00000E+00) (  1.61492E+00,  4.90515E-01)   1.25607E-15     0


c05qbfe.r

 C05QBF Example Program Results

 Final 2-norm of the residuals =  0.1193E-07

 Final approximate solution

      -0.5707     -0.6816     -0.7017
      -0.7042     -0.7014     -0.6919
      -0.6658     -0.5960     -0.4164


c05qcfe.r

 C05QCF Example Program Results

 Final 2-norm of the residuals =  0.1193E-07

 Number of function evaluations =        14

 Final approximate solution

      -0.5707     -0.6816     -0.7017
      -0.7042     -0.7014     -0.6919
      -0.6658     -0.5960     -0.4164


c05qdfe.r

 C05QDF Example Program Results

 Final 2-norm of the residuals after  11 iterations is   0.1193E-07

 Final approximate solution

          -0.5707     -0.6816     -0.7017
          -0.7042     -0.7014     -0.6919
          -0.6658     -0.5960     -0.4164


c05qsfe.r

 C05QSF Example Program Results

 Final 2-norm of the residuals =  0.1759E-08

 Final approximate solution

      -0.5707     -0.6816     -0.7017
      -0.7042     -0.7014     -0.6919
      -0.6658     -0.5960     -0.4164

 Final 2-norm of the residuals =  0.2633E-12

 Final approximate solution

      -0.5697     -0.6804     -0.7004
      -0.7029     -0.7000     -0.6906
      -0.6646     -0.5951     -0.4159


c05rbfe.r

 C05RBF Example Program Results

 Final 2-norm of the residuals =  0.1193E-07

 Final approximate solution

      -0.5707     -0.6816     -0.7017
      -0.7042     -0.7014     -0.6919
      -0.6658     -0.5960     -0.4164


c05rcfe.r

 C05RCF Example Program Results

 Final 2-norm of the residuals =  0.1193E-07

 Final approximate solution

      -0.5707     -0.6816     -0.7017
      -0.7042     -0.7014     -0.6919
      -0.6658     -0.5960     -0.4164


c05rdfe.r

 C05RDF Example Program Results

 Final 2-norm of the residuals after  11 iterations is   0.1193E-07

 Final approximate solution

          -0.5707     -0.6816     -0.7017
          -0.7042     -0.7014     -0.6919
          -0.6658     -0.5960     -0.4164


c05zdfe.r

 C05ZDF Example Program Results

 At point       0.9200      0.1300      0.5400,
 gradients appear correct


c06bafe.r

 C06BAF Example Program Results

                                    Estimated       Actual
   I       SEQN       RESULT        abs error        error

    1      1.0000      1.0000             -         0.18E+00
    2      0.7500      0.7500             -        -0.72E-01
    3      0.8611      0.8269             -         0.45E-02
    4      0.7986      0.8211         0.26E+00     -0.14E-02
    5      0.8386      0.8226         0.78E-01      0.12E-03
    6      0.8108      0.8224         0.60E-02     -0.33E-04
    7      0.8312      0.8225         0.15E-02      0.35E-05
    8      0.8156      0.8225         0.16E-03     -0.85E-06
    9      0.8280      0.8225         0.37E-04      0.10E-06
   10      0.8180      0.8225         0.45E-05     -0.23E-07


c06dcfe.r

 C06DCF Example Program Results

     x       sum of series

   0.5000      0.5000
   1.0000      2.2500
  -0.2000     -0.0180


c06fafe.r

 C06FAF Example Program Results

 Components of discrete Fourier transform

           Real      Imag

     0   2.48361   0.00000
     1  -0.26599   0.53090
     2  -0.25768   0.20298
     3  -0.25636   0.05806
     4  -0.25636  -0.05806
     5  -0.25768  -0.20298
     6  -0.26599  -0.53090

 Original sequence as restored by inverse transform

         Original  Restored

     0   0.34907   0.34907
     1   0.54890   0.54890
     2   0.74776   0.74776
     3   0.94459   0.94459
     4   1.13850   1.13850
     5   1.32850   1.32850
     6   1.51370   1.51370


c06fbfe.r

 C06FBF Example Program Results

 Original sequence and corresponding complex sequence

          Data           Real      Imag

     0   0.34907        0.34907   0.00000
     1   0.54890        0.54890   1.51370
     2   0.74776        0.74776   1.32850
     3   0.94459        0.94459   1.13850
     4   1.13850        0.94459  -1.13850
     5   1.32850        0.74776  -1.32850
     6   1.51370        0.54890  -1.51370

 Components of discrete Fourier transform

     0   1.82616
     1   1.86862
     2  -0.01750
     3   0.50200
     4  -0.59873
     5  -0.03144
     6  -2.62557

 Original sequence as restored by inverse transform

         Original  Restored

     0   0.34907   0.34907
     1   0.54890   0.54890
     2   0.74776   0.74776
     3   0.94459   0.94459
     4   1.13850   1.13850
     5   1.32850   1.32850
     6   1.51370   1.51370


c06fcfe.r

 C06FCF Example Program Results

 Components of discrete Fourier transform

           Real      Imag

     0   2.48361  -0.47100
     1  -0.55180   0.49684
     2  -0.36711   0.09756
     3  -0.28767  -0.05865
     4  -0.22506  -0.17477
     5  -0.14825  -0.30840
     6   0.01983  -0.56496

 Original sequence as restored by inverse transform

              Original                 Restored
           Real      Imag           Real      Imag

     0   0.34907  -0.37168        0.34907  -0.37168
     1   0.54890  -0.35669        0.54890  -0.35669
     2   0.74776  -0.31175        0.74776  -0.31175
     3   0.94459  -0.23702        0.94459  -0.23702
     4   1.13850  -0.13274        1.13850  -0.13274
     5   1.32850   0.00074        1.32850   0.00074
     6   1.51370   0.16298        1.51370   0.16298


c06fffe.r

 C06FFF Example Program Results

 Original data

 Real      1.000     0.999     0.987     0.936     0.802
 Imag      0.000    -0.040    -0.159    -0.352    -0.597

 Real      0.994     0.989     0.963     0.891     0.731
 Imag     -0.111    -0.151    -0.268    -0.454    -0.682

 Real      0.903     0.885     0.823     0.694     0.467
 Imag     -0.430    -0.466    -0.568    -0.720    -0.884

 Discrete Fourier transform of variable 2

 Real      2.113     0.288     0.126    -0.003    -0.287
 Imag     -0.513    -0.000     0.130     0.190     0.194

 Real      2.043     0.286     0.139     0.018    -0.263
 Imag     -0.745    -0.032     0.115     0.189     0.225

 Real      1.687     0.260     0.170     0.079    -0.176
 Imag     -1.372    -0.125     0.063     0.173     0.299

 Original sequence as restored by inverse transform

 Real      1.000     0.999     0.987     0.936     0.802
 Imag     -0.000    -0.040    -0.159    -0.352    -0.597

 Real      0.994     0.989     0.963     0.891     0.731
 Imag     -0.111    -0.151    -0.268    -0.454    -0.682

 Real      0.903     0.885     0.823     0.694     0.467
 Imag     -0.430    -0.466    -0.568    -0.720    -0.884


c06fjfe.r

 C06FJF Example Program Results

 Original data values

 Real      1.000     0.999     0.987     0.936     0.802
 Imag      0.000    -0.040    -0.159    -0.352    -0.597

 Real      0.994     0.989     0.963     0.891     0.731
 Imag     -0.111    -0.151    -0.268    -0.454    -0.682

 Real      0.903     0.885     0.823     0.694     0.467
 Imag     -0.430    -0.466    -0.568    -0.720    -0.884

 Components of discrete Fourier transform

 Real      3.373     0.481     0.251     0.054    -0.419
 Imag     -1.519    -0.091     0.178     0.319     0.415

 Real      0.457     0.055     0.009    -0.022    -0.076
 Imag      0.137     0.032     0.039     0.036     0.004

 Real     -0.170    -0.037    -0.042    -0.038    -0.002
 Imag      0.493     0.058     0.008    -0.025    -0.083

 Original sequence as restored by inverse transform

 Real      1.000     0.999     0.987     0.936     0.802
 Imag     -0.000    -0.040    -0.159    -0.352    -0.597

 Real      0.994     0.989     0.963     0.891     0.731
 Imag     -0.111    -0.151    -0.268    -0.454    -0.682

 Real      0.903     0.885     0.823     0.694     0.467
 Imag     -0.430    -0.466    -0.568    -0.720    -0.884


c06fkfe.r

 C06FKF Example Program Results

         Convolution  Correlation

     0      0.50000      2.00000
     1      1.00000      1.50000
     2      1.50000      1.00000
     3      2.00000      0.50000
     4      2.00000      0.00000
     5      1.50000      0.50000
     6      1.00000      1.00000
     7      0.50000      1.50000
     8      0.00000      2.00000


c06fxfe.r

 C06FXF Example Program Results

 Original data values

 z(i,j,k) for i =     1

 Real      1.000     0.999     0.987     0.936
 Imag      0.000    -0.040    -0.159    -0.352

 Real      0.994     0.989     0.963     0.891
 Imag     -0.111    -0.151    -0.268    -0.454

 Real      0.903     0.885     0.823     0.694
 Imag     -0.430    -0.466    -0.568    -0.720

 z(i,j,k) for i =     2

 Real      0.500     0.499     0.487     0.436
 Imag      0.500     0.040     0.159     0.352

 Real      0.494     0.489     0.463     0.391
 Imag      0.111     0.151     0.268     0.454

 Real      0.403     0.385     0.323     0.194
 Imag      0.430     0.466     0.568     0.720

 Components of discrete Fourier transform

 z(i,j,k) for i =     1

 Real      3.292     0.051     0.113     0.051
 Imag      0.102    -0.042     0.102     0.246

 Real      0.143     0.016    -0.024    -0.050
 Imag     -0.086     0.153     0.127     0.086

 Real      0.143    -0.050    -0.024     0.016
 Imag      0.290     0.118     0.077     0.051

 z(i,j,k) for i =     2

 Real      1.225     0.355    -0.000    -0.355
 Imag     -1.620     0.083     0.162     0.083

 Real      0.424     0.020     0.013    -0.007
 Imag      0.320    -0.115    -0.091    -0.080

 Real     -0.424     0.007    -0.013    -0.020
 Imag      0.320    -0.080    -0.091    -0.115

 Original sequence as restored by inverse transform

 z(i,j,k) for i =     1

 Real      1.000     0.999     0.987     0.936
 Imag      0.000    -0.040    -0.159    -0.352

 Real      0.994     0.989     0.963     0.891
 Imag     -0.111    -0.151    -0.268    -0.454

 Real      0.903     0.885     0.823     0.694
 Imag     -0.430    -0.466    -0.568    -0.720

 z(i,j,k) for i =     2

 Real      0.500     0.499     0.487     0.436
 Imag      0.500     0.040     0.159     0.352

 Real      0.494     0.489     0.463     0.391
 Imag      0.111     0.151     0.268     0.454

 Real      0.403     0.385     0.323     0.194
 Imag      0.430     0.466     0.568     0.720


c06lafe.r

 C06LAF Example Program Results

 (results may be machine-dependent)

 Test with T(1) = 1.0

   MXTERM = 200  TFAC =  7.50  ALPHAB = -0.50  RELERR = 1.0E-02

    T        Result        exp(-T/2)   Relative error  Error estimate
  1.0        0.607          0.607         0.1E-02         0.4E-02

 Test with T(1) = 1.0

   MXTERM = 200  TFAC =  0.80  ALPHAB = -0.50  RELERR = 1.0E-03

    T        Result        exp(-T/2)   Relative error  Error estimate
  1.0        0.607          0.607         0.2E-04         0.8E-04

 Compute inverse

   MXTERM = 200  TFAC =  0.80  ALPHAB = -0.50  RELERR = 1.0E-03

    T        Result        exp(-T/2)   Relative error  Error estimate
  1.0        0.607          0.607         0.5E-04         0.3E-03
  2.0        0.368          0.368         0.7E-05         0.9E-04
  3.0        0.223          0.223         0.2E-04         0.8E-04
  4.0        0.135          0.135         0.1E-04         0.8E-04
  5.0        0.082          0.082         0.2E-04         0.8E-04

  NTERMS =  23  NFEVAL =  43  ALOW =   0.65  AHIGH =   0.90  IFAIL = 0


c06lbfe.r

 C06LBF Example Program Results

 No. of coefficients returned by C06LBF =    64

                  Computed          Exact      Pseudo
          T           f(T)           f(T)       error

   0.00E+00     1.5129E-09     0.0000E+00     1.5E-09
   1.00E+00     1.0018E+01     1.0018E+01     1.7E-09
   2.00E+00     2.0171E+02     2.0171E+02     1.2E-10
   3.00E+00     4.0515E+03     4.0515E+03     9.8E-10
   4.00E+00     8.1377E+04     8.1377E+04     3.0E-10
   5.00E+00     1.6345E+06     1.6345E+06     1.7E-09


c06pafe.r

 C06PAF Example Program Results

 Components of discrete Fourier transform

           Real      Imag

     0   2.48361   0.00000
     1  -0.26599   0.53090
     2  -0.25768   0.20298
     3  -0.25636   0.05806
     4  -0.25636  -0.05806
     5  -0.25768  -0.20298
     6  -0.26599  -0.53090

 Original sequence as restored by inverse transform

         Original  Restored

     0   0.34907   0.34907
     1   0.54890   0.54890
     2   0.74776   0.74776
     3   0.94459   0.94459
     4   1.13850   1.13850
     5   1.32850   1.32850
     6   1.51370   1.51370


c06pcfe.r

 C06PCF Example Program Results

 Components of discrete Fourier transform

               Real      Imag

     0     ( 2.48361,-0.47100)
     1     (-0.55180, 0.49684)
     2     (-0.36711, 0.09756)
     3     (-0.28767,-0.05865)
     4     (-0.22506,-0.17477)
     5     (-0.14825,-0.30840)
     6     ( 0.01983,-0.56496)

 Original sequence as restored by inverse transform

                  Original                 Restored
               Real      Imag           Real      Imag

     0     ( 0.34907,-0.37168)     ( 0.34907,-0.37168)
     1     ( 0.54890,-0.35669)     ( 0.54890,-0.35669)
     2     ( 0.74776,-0.31175)     ( 0.74776,-0.31175)
     3     ( 0.94459,-0.23702)     ( 0.94459,-0.23702)
     4     ( 1.13850,-0.13274)     ( 1.13850,-0.13274)
     5     ( 1.32850, 0.00074)     ( 1.32850, 0.00074)
     6     ( 1.51370, 0.16298)     ( 1.51370, 0.16298)


c06ppfe.r

 C06PPF Example Program Results

 Original data values

           0.3854     0.6772     0.1138     0.6751     0.6362     0.1424
           0.5417     0.2983     0.1181     0.7255     0.8638     0.8723
           0.9172     0.0644     0.6037     0.6430     0.0428     0.4815

 Discrete Fourier transforms in complex Hermitian format

 Real      1.0737    -0.1041     0.1126    -0.1467
 Imag      0.0000    -0.0044    -0.3738     0.0000

 Real      1.3961    -0.0365     0.0780    -0.1521
 Imag      0.0000     0.4666    -0.0607     0.0000

 Real      1.1237     0.0914     0.3936     0.1530
 Imag      0.0000    -0.0508     0.3458     0.0000

 Fourier transforms in full complex form

 Real      1.0737    -0.1041     0.1126    -0.1467     0.1126    -0.1041
 Imag      0.0000    -0.0044    -0.3738     0.0000     0.3738     0.0044

 Real      1.3961    -0.0365     0.0780    -0.1521     0.0780    -0.0365
 Imag      0.0000     0.4666    -0.0607     0.0000     0.0607    -0.4666

 Real      1.1237     0.0914     0.3936     0.1530     0.3936     0.0914
 Imag      0.0000    -0.0508     0.3458     0.0000    -0.3458     0.0508

 Original data as restored by inverse transform

           0.3854     0.6772     0.1138     0.6751     0.6362     0.1424
           0.5417     0.2983     0.1181     0.7255     0.8638     0.8723
           0.9172     0.0644     0.6037     0.6430     0.0428     0.4815


c06pqfe.r

 C06PQF Example Program Results

 Original data values

           0.3854     0.6772     0.1138     0.6751     0.6362     0.1424
           0.5417     0.2983     0.1181     0.7255     0.8638     0.8723
           0.9172     0.0644     0.6037     0.6430     0.0428     0.4815

 Discrete Fourier transforms in complex Hermitian format

 Real      1.0737    -0.1041     0.1126    -0.1467
 Imag      0.0000    -0.0044    -0.3738     0.0000

 Real      1.3961    -0.0365     0.0780    -0.1521
 Imag      0.0000     0.4666    -0.0607     0.0000

 Real      1.1237     0.0914     0.3936     0.1530
 Imag      0.0000    -0.0508     0.3458     0.0000

 Fourier transforms in full complex form

 Real      1.0737    -0.1041     0.1126    -0.1467     0.1126    -0.1041
 Imag      0.0000    -0.0044    -0.3738     0.0000     0.3738     0.0044

 Real      1.3961    -0.0365     0.0780    -0.1521     0.0780    -0.0365
 Imag      0.0000     0.4666    -0.0607     0.0000     0.0607    -0.4666

 Real      1.1237     0.0914     0.3936     0.1530     0.3936     0.0914
 Imag      0.0000    -0.0508     0.3458     0.0000    -0.3458     0.0508

 Original data as restored by inverse transform

           0.3854     0.6772     0.1138     0.6751     0.6362     0.1424
           0.5417     0.2983     0.1181     0.7255     0.8638     0.8723
           0.9172     0.0644     0.6037     0.6430     0.0428     0.4815


c06pufe.r

 C06PUF Example Program Results

 Original data values

 Real      1.000     0.999     0.987     0.936     0.802
 Imag      0.000    -0.040    -0.159    -0.352    -0.597

 Real      0.994     0.989     0.963     0.891     0.731
 Imag     -0.111    -0.151    -0.268    -0.454    -0.682

 Real      0.903     0.885     0.823     0.694     0.467
 Imag     -0.430    -0.466    -0.568    -0.720    -0.884

 Components of discrete Fourier transform

 Real      3.373     0.481     0.251     0.054    -0.419
 Imag     -1.519    -0.091     0.178     0.319     0.415

 Real      0.457     0.055     0.009    -0.022    -0.076
 Imag      0.137     0.032     0.039     0.036     0.004

 Real     -0.170    -0.037    -0.042    -0.038    -0.002
 Imag      0.493     0.058     0.008    -0.025    -0.083

 Original sequence as restored by inverse transform

 Real      1.000     0.999     0.987     0.936     0.802
 Imag      0.000    -0.040    -0.159    -0.352    -0.597

 Real      0.994     0.989     0.963     0.891     0.731
 Imag     -0.111    -0.151    -0.268    -0.454    -0.682

 Real      0.903     0.885     0.823     0.694     0.467
 Imag     -0.430    -0.466    -0.568    -0.720    -0.884


c06pvfe.r

 C06PVF Example Program Results

 Original data values

 Real      0.010     0.346

 Real      1.284     1.960

 Real      1.754     0.855

 Real      0.089     0.161

 Real      1.004     1.844

 Components of discrete Fourier transform

 Real      2.943    -0.324
 Imag      0.000     0.000

 Real     -0.024    -0.466
 Imag     -0.558    -0.230

 Real     -1.167     0.362
 Imag      0.636     0.262

 Original sequence as restored by inverse transform

 Real      0.010     0.346

 Real      1.284     1.960

 Real      1.754     0.855

 Real      0.089     0.161

 Real      1.004     1.844


c06pxfe.r

 C06PXF Example Program Results

 Original data values

 z(i,j,k) for i =     1

 Real      1.000     0.999     0.987     0.936
 Imag      0.000    -0.040    -0.159    -0.352

 Real      0.994     0.989     0.963     0.891
 Imag     -0.111    -0.151    -0.268    -0.454

 Real      0.903     0.885     0.823     0.694
 Imag     -0.430    -0.466    -0.568    -0.720

 z(i,j,k) for i =     2

 Real      0.500     0.499     0.487     0.436
 Imag      0.500     0.040     0.159     0.352

 Real      0.494     0.489     0.463     0.391
 Imag      0.111     0.151     0.268     0.454

 Real      0.403     0.385     0.323     0.194
 Imag      0.430     0.466     0.568     0.720

 Components of discrete Fourier transform

 z(i,j,k) for i =     1

 Real      3.292     0.051     0.113     0.051
 Imag      0.102    -0.042     0.102     0.246

 Real      0.143     0.016    -0.024    -0.050
 Imag     -0.086     0.153     0.127     0.086

 Real      0.143    -0.050    -0.024     0.016
 Imag      0.290     0.118     0.077     0.051

 z(i,j,k) for i =     2

 Real      1.225     0.355     0.000    -0.355
 Imag     -1.620     0.083     0.162     0.083

 Real      0.424     0.020     0.013    -0.007
 Imag      0.320    -0.115    -0.091    -0.080

 Real     -0.424     0.007    -0.013    -0.020
 Imag      0.320    -0.080    -0.091    -0.115

 Original sequence as restored by inverse transform

 z(i,j,k) for i =     1

 Real      1.000     0.999     0.987     0.936
 Imag     -0.000    -0.040    -0.159    -0.352

 Real      0.994     0.989     0.963     0.891
 Imag     -0.111    -0.151    -0.268    -0.454

 Real      0.903     0.885     0.823     0.694
 Imag     -0.430    -0.466    -0.568    -0.720

 z(i,j,k) for i =     2

 Real      0.500     0.499     0.487     0.436
 Imag      0.500     0.040     0.159     0.352

 Real      0.494     0.489     0.463     0.391
 Imag      0.111     0.151     0.268     0.454

 Real      0.403     0.385     0.323     0.194
 Imag      0.430     0.466     0.568     0.720


c06pyfe.r

 C06PYF Example Program Results

 Original data values

 x(i,j,k) for i =     1

 Real      1.541     0.161     1.989     0.037

 Real      0.346     1.907     0.001     1.915

 Real      1.754     0.042     1.991     0.151

 x(i,j,k) for i =     2

 Real      0.584     1.004     1.408     0.252

 Real      1.284     1.137     0.467     1.834

 Real      0.855     0.725     1.647     0.096

 x(i,j,k) for i =     3

 Real      0.010     1.844     0.452     1.154

 Real      1.960     0.240     1.424     0.987

 Real      0.089     1.660     0.708     0.872

 Components of discrete Fourier transform

 y(i,j,k) for i =     1

 Real      5.755    -0.277     0.415    -0.277
 Imag      0.000    -0.237     0.000     0.237

 Real     -0.268     0.109     0.175    -0.688
 Imag     -0.420    -0.756     0.871    -0.210

 Real     -0.268    -0.688     0.175     0.109
 Imag      0.420     0.210    -0.871     0.756

 y(i,j,k) for i =     2

 Real      0.081     0.060     0.645     0.047
 Imag      0.015     0.156    -0.478    -0.077

 Real      0.038    -0.275     1.585     0.201
 Imag      0.198     0.295     0.616     0.061

 Real      0.067     0.280    -0.113    -0.128
 Imag     -0.122     0.012    -1.555    -0.117

 Original sequence as restored by inverse transform

 x(i,j,k) for i =     1

 Real      1.541     0.161     1.989     0.037

 Real      0.346     1.907     0.001     1.915

 Real      1.754     0.042     1.991     0.151

 x(i,j,k) for i =     2

 Real      0.584     1.004     1.408     0.252

 Real      1.284     1.137     0.467     1.834

 Real      0.855     0.725     1.647     0.096

 x(i,j,k) for i =     3

 Real      0.010     1.844     0.452     1.154

 Real      1.960     0.240     1.424     0.987

 Real      0.089     1.660     0.708     0.872


c06rafe.r

 C06RAF Example Program Results

 Original data values

          0.6772    0.1138    0.6751    0.6362    0.1424
          0.2983    0.1182    0.7255    0.8638    0.8723
          0.0644    0.6037    0.6430    0.0428    0.4815

 Discrete Fourier sine transforms

          1.0014    0.0062    0.0834    0.5286    0.2514
          1.2478   -0.6598    0.2570    0.0858    0.2658
          0.8521    0.0719   -0.0561   -0.4890    0.2056

 Original data as restored by inverse transform

          0.6772    0.1138    0.6751    0.6362    0.1424
          0.2983    0.1182    0.7255    0.8638    0.8723
          0.0644    0.6037    0.6430    0.0428    0.4815


c06rcfe.r

 C06RCF Example Program Results

 Original data values

          0.3854    0.6772    0.1138    0.6751    0.6362    0.1424
          0.5417    0.2983    0.1181    0.7255    0.8638    0.8723
          0.9172    0.0644    0.6037    0.6430    0.0428    0.4815

 Discrete quarter-wave Fourier sine transforms

          0.7304    0.2078    0.1150    0.2577   -0.2869   -0.0815
          0.9274   -0.1152    0.2532    0.2883   -0.0026   -0.0635
          0.6268    0.3547    0.0760    0.3078    0.4987   -0.0507

 Original data as restored by inverse transform

          0.3854    0.6772    0.1138    0.6751    0.6362    0.1424
          0.5417    0.2983    0.1181    0.7255    0.8638    0.8723
          0.9172    0.0644    0.6037    0.6430    0.0428    0.4815


c06rdfe.r

 C06RDF Example Program Results

 Original data values

          0.3854    0.6772    0.1138    0.6751    0.6362    0.1424
          0.5417    0.2983    0.1181    0.7255    0.8638    0.8723
          0.9172    0.0644    0.6037    0.6430    0.0428    0.4815

 Discrete quarter-wave Fourier cosine transforms

          0.7257   -0.2216    0.1011    0.2355   -0.1406   -0.2282
          0.7479   -0.6172    0.4112    0.0791    0.1331   -0.0906
          0.6713   -0.1363   -0.0064   -0.0285    0.4758    0.1475

 Original data as restored by inverse transform

          0.3854    0.6772    0.1138    0.6751    0.6362    0.1424
          0.5417    0.2983    0.1181    0.7255    0.8638    0.8723
          0.9172    0.0644    0.6037    0.6430    0.0428    0.4815


c06refe.r

 C06REF Example Program Results

 Original data values

     0.6772    0.1138    0.6751    0.6362    0.1424
     0.2983    0.1182    0.7255    0.8638    0.8723
     0.0644    0.6037    0.6430    0.0428    0.4815

 Discrete Fourier sine transforms

     1.0014    0.0062    0.0834    0.5286    0.2514
     1.2478   -0.6598    0.2570    0.0858    0.2658
     0.8521    0.0719   -0.0561   -0.4890    0.2056

 Original data as restored by inverse transform

     0.6772    0.1138    0.6751    0.6362    0.1424
     0.2983    0.1182    0.7255    0.8638    0.8723
     0.0644    0.6037    0.6430    0.0428    0.4815


c06rgfe.r

 C06RGF Example Program Results

 Original data values

     0.3854    0.6772    0.1138    0.6751    0.6362    0.1424
     0.5417    0.2983    0.1181    0.7255    0.8638    0.8723
     0.9172    0.0644    0.6037    0.6430    0.0428    0.4815

 Discrete quarter-wave Fourier sine transforms

     0.7304    0.2078    0.1150    0.2577   -0.2869   -0.0815
     0.9274   -0.1152    0.2532    0.2883   -0.0026   -0.0635
     0.6268    0.3547    0.0760    0.3078    0.4987   -0.0507

 Original data as restored by inverse transform

     0.3854    0.6772    0.1138    0.6751    0.6362    0.1424
     0.5417    0.2983    0.1181    0.7255    0.8638    0.8723
     0.9172    0.0644    0.6037    0.6430    0.0428    0.4815


c06rhfe.r

 C06RHF Example Program Results

 Original data values

     0.3854    0.6772    0.1138    0.6751    0.6362    0.1424
     0.5417    0.2983    0.1181    0.7255    0.8638    0.8723
     0.9172    0.0644    0.6037    0.6430    0.0428    0.4815

 Discrete quarter-wave Fourier cosine transforms

     0.7257   -0.2216    0.1011    0.2355   -0.1406   -0.2282
     0.7479   -0.6172    0.4112    0.0791    0.1331   -0.0906
     0.6713   -0.1363   -0.0064   -0.0285    0.4758    0.1475

 Original data as restored by inverse transform

     0.3854    0.6772    0.1138    0.6751    0.6362    0.1424
     0.5417    0.2983    0.1181    0.7255    0.8638    0.8723
     0.9172    0.0644    0.6037    0.6430    0.0428    0.4815


c09aafe.r

 C09AAF Example Program Results

  Parameters read from file ::
     Wavelet : Haar       End mode : Zero       N =          8
  Input Data           X :
   2.000    5.000    8.000    9.000    7.000    4.000   -1.000    1.000

  Length of wavelet filter :                      2
  Number of Levels :                              3
  Number of coefficients in each level :
                       1        1        2        4
  Total number of wavelet coefficients :          8

  Wavelet coefficients C :
  12.374    4.596   -5.000    5.500   -2.121   -0.707    2.121   -1.414

  Reconstruction       Y :
   2.000    5.000    8.000    9.000    7.000    4.000   -1.000    1.000


c09bafe.r

 C09BAF Example Program Results

  Parameters read from file ::
    Wavelet : MORLET,  wparam :      5
          n :     10,   nscal :      4

  Input Data ::
     Scales :       1        2        3        4
          x :   0.000    0.000    0.000    0.000    1.000
                0.000    0.000    0.000    0.000    0.000

  Number of Scales :               4
  Wavelet coefficients C ::
    Scale :      1            2            3            4
          -1.7651E-05   1.5012E-04   5.2331E-02   1.4454E-01
          -1.3643E-03  -5.8141E-02   1.7057E-01  -8.4364E-02
           4.6511E-03   1.8442E-01  -1.4891E-01  -2.8870E-01
           8.9294E-02  -2.6380E-01  -2.6822E-01  -9.4993E-02
          -9.2563E-02   1.3289E-01   2.5680E-01   2.8293E-01
          -9.2563E-02   1.3289E-01   2.5680E-01   2.8293E-01
           8.9294E-02  -2.6380E-01  -2.6822E-01  -9.4993E-02
           4.6511E-03   1.8442E-01  -1.4891E-01  -2.8870E-01
          -1.3643E-03  -5.8141E-02   1.7057E-01  -8.4364E-02
          -1.7651E-05   1.5012E-04   5.2331E-02   1.4454E-01


c09cafe.r

 C09CAF Example Program Results
 DWT :: Wavelet: DB4         , End mode: Zero
 Input Data      X :
   1.0000   3.0000   5.0000   7.0000   6.0000   4.0000   5.0000   2.0000
 Approximation coefficients CA :
   0.0011  -0.0043  -0.0174   4.4778   8.9557   7.3401   2.5816
 Detail coefficients        CD :
   0.0237   0.0410  -0.5966   1.7763  -0.7517   0.3332  -0.1188
 Reconstruction              Y :
   1.0000   3.0000   5.0000   7.0000   6.0000   4.0000   5.0000   2.0000


c09dafe.r

 C09DAF Example Program Results
 MODWT :: Wavelet: DB4           , End mode: Periodic
 Input Data      X :
   1.0000   3.0000   5.0000   7.0000   6.0000   4.0000   5.0000   2.0000
 Approximation coefficients CA :
   2.7781   1.5146   2.2505   4.8788   6.6845   6.3423   4.7869   3.7644
 Detail coefficients        CD :
  -0.6187   0.6272   0.1883  -1.1966   1.2618   0.3354  -0.3314  -0.2660
 Reconstruction              Y :
   1.0000   3.0000   5.0000   7.0000   6.0000   4.0000   5.0000   2.0000


d01ahfe.r

 D01AHF Example Program Results

 Integral =  3.14159

 Estimated relative error =   0.58E-08

 Number of function evaluations =    15


d01ajfe.r

 D01AJF Example Program Results

 A      -       lower limit of integration =     0.0000
 B      -       upper limit of integration =     6.2832
 EPSABS -      absolute accuracy requested =  0.00E+00
 EPSREL -      relative accuracy requested =  0.10E-03

 RESULT -    approximation to the integral =  -2.54326
 ABSERR -   estimate of the absolute error =  0.13E-04
 IW(1)  -      number of subintervals used =   19


d01akfe.r

 D01AKF Example Program Results

 A      -       lower limit of integration =     0.0000
 B      -       upper limit of integration =     6.2832
 EPSABS -      absolute accuracy requested =  0.00E+00
 EPSREL -      relative accuracy requested =  0.10E-02

 RESULT -    approximation to the integral =  -0.20967
 ABSERR -   estimate of the absolute error =  0.45E-13
 IW(1)  -      number of subintervals used =    4


d01alfe.r

 D01ALF Example Program Results

 A         -       lower limit of integration =     0.0000
 B         -       upper limit of integration =     1.0000
 EPSABS    -      absolute accuracy requested =  0.00E+00
 EPSREL    -      relative accuracy requested =  0.10E-02
 POINTS(1) -                given break-point =     0.1429

 RESULT    -    approximation to the integral =   2.60757
 ABSERR    -   estimate of the absolute error =  0.62E-13
 IW(1)     -      number of subintervals used =   12


d01amfe.r

 D01AMF Example Program Results

 A      -       lower limit of integration =     0.0000
 B      -       upper limit of integration = infinity
 EPSABS -      absolute accuracy requested =  0.00E+00
 EPSREL -      relative accuracy requested =  0.10E-03

 RESULT -    approximation to the integral =   3.14159
 ABSERR -   estimate of the absolute error =  0.27E-04
 IW(1)  -      number of subintervals used =   10


d01anfe.r

 D01ANF Example Program Results

 A      -       lower limit of integration =     0.0000
 B      -       upper limit of integration =     1.0000
 EPSABS -      absolute accuracy requested =  0.00E+00
 EPSREL -      relative accuracy requested =  0.10E-03

 RESULT -    approximation to the integral =  -0.12814
 ABSERR -   estimate of the absolute error =  0.36E-05
 IW(1)  -      number of subintervals used =    8


d01apfe.r

 D01APF Example Program Results

 A      -       lower limit of integration =     0.0000
 B      -       upper limit of integration =     1.0000
 EPSABS -      absolute accuracy requested =  0.00E+00
 EPSREL -      relative accuracy requested =  0.10E-03

 ALPHA  - parameter in the weight function =  0.00E+00
 BETA   - parameter in the weight function =  0.00E+00
 KEY    -    which weight function is used =    2

 RESULT -    approximation to the integral =  -0.04899
 ABSERR -   estimate of the absolute error =  0.11E-06
  IW(1) -     number of subintervals used  =    4

 A      -       lower limit of integration =     0.0000
 B      -       upper limit of integration =     1.0000
 EPSABS -      absolute accuracy requested =  0.00E+00
 EPSREL -      relative accuracy requested =  0.10E-03

 ALPHA  - parameter in the weight function = -0.50E+00
 BETA   - parameter in the weight function = -0.50E+00
 KEY    -    which weight function is used =    1

 RESULT -    approximation to the integral =   0.53502
 ABSERR -   estimate of the absolute error =  0.19E-11
  IW(1) -     number of subintervals used  =    2


d01aqfe.r

 D01AQF Example Program Results

 A      -       lower limit of integration =    -1.0000
 B      -       upper limit of integration =     1.0000
 EPSABS -      absolute accuracy requested =  0.00E+00
 EPSREL -      relative accuracy requested =  0.10E-03
 C      -        weight function parameter =  0.50E+00

 RESULT -    approximation to the integral =   -628.46
 ABSERR -   estimate of the absolute error =  0.13E-01
 IW(1)  -      number of subintervals used =    8


d01arfe.r

 D01ARF Example Program Results

 Definite integral of 4/(1+x*x) over (0,1)
 Estimated value of the integral =  3.14159
 Estimated absolute error =  0.18E-07
 Number of points used =  15

 Definite integral of x**(1/8) over (1,2)
 Estimated value of the integral =  1.04979
 Estimated absolute error =  0.59E-06
 Number of points used =   7

 Indefinite integral of x**(1/8) over (1.2,1.8)
 Estimated value of the integral =  0.63073


d01asfe.r

 D01ASF Example Program Results

 A      - lower limit of integration =     0.0000
 B      - upper limit of integration =  infinity
 EPSABS - absolute accuracy requested =  0.10E-02

 RESULT - approximation to the integral =   1.00000
 ABSERR - estimate of the absolute error =  0.59E-03
 LST    - number of intervals used =    6
 IW(1)  - max. no. of subintervals used in any one interval =    8


d01atfe.r

 D01ATF Example Program Results

 A      -     lower limit of integration =     0.0000
 B      -     upper limit of integration =     6.2832
 EPSABS -    absolute accuracy requested =  0.00E+00
 EPSREL -    relative accuracy requested =  0.10E-03

 RESULT -  approximation to the integral =  -2.54326
 ABSERR - estimate of the absolute error =  0.13E-04
 IW(1)  -    number of subintervals used =   19


d01aufe.r

 D01AUF Example Program Results

 A      -     lower limit of integration =     0.0000
 B      -     upper limit of integration =     6.2832
 EPSABS -    absolute accuracy requested =  0.00E+00
 EPSREL -    relative accuracy requested =  0.10E-02

 RESULT -  approximation to the integral =  -0.20967
 ABSERR - estimate of the absolute error =  0.45E-13
 IW(1)  -    number of subintervals used =    4


d01bcfe.r

 D01BCF Example Program Results

 Laguerre formula,  7 points

       Abscissae             Weights

     0.19304E+00         0.49648E+00
     0.10267E+01         0.11776E+01
     0.25679E+01         0.19182E+01
     0.49004E+01         0.27718E+01
     0.81822E+01         0.38412E+01
     0.12734E+02         0.53807E+01
     0.19396E+02         0.84054E+01


d01bdfe.r

 D01BDF Example Program Results

 A      - lower limit of integration =     0.0000
 B      - upper limit of integration =     1.0000
 EPSABS - absolute accuracy requested =  0.00E+00
 EPSREL - relative accuracy requested =  0.10E-03

 RESULT - approximation to the integral =  -0.03183
 ABSERR - estimate to the absolute error =  0.13E-10


d01dafe.r

 D01DAF Example Program Results

 First formulation
 Integral =   0.6667
 Number of function evaluations =  189

 Second formulation
 Integral =   0.6667
 Number of function evaluations =   89


d01eafe.r

 D01EAF Example Program Results
 ** MAXCLS too small to obtain required accuracy.
 ** MAXCLS =                   57.
 ** ABNORMAL EXIT from NAG Library routine D01EAF: IFAIL =     1
 ** NAG soft failure - control returned

 Results so far (     57 FUNSUB calls in last call of D01EAF)

    I       Integral   Estimated error
    1        0.0422        0.0086
    2        0.3998        0.0038
    3        0.3898        0.0127
    4        0.0214        0.0099
    5       -0.3666        0.0020
    6       -0.4176        0.0120
    7       -0.0846        0.0110
    8        0.3261        0.0001
    9        0.4371        0.0112
   10        0.1461        0.0119

 ** MAXCLS too small to obtain required accuracy.
 ** MAXCLS =                  912.
 ** ABNORMAL EXIT from NAG Library routine D01EAF: IFAIL =     1
 ** NAG soft failure - control returned

 Results so far (    798 FUNSUB calls in last call of D01EAF)

    I       Integral   Estimated error
    1        0.0384        0.0006
    2        0.4012        0.0006
    3        0.3952        0.0006
    4        0.0258        0.0006
    5       -0.3673        0.0006
    6       -0.4227        0.0006
    7       -0.0895        0.0006
    8        0.3260        0.0006
    9        0.4417        0.0006
   10        0.1514        0.0006

 Final Results (    912 FUNSUB calls in last call of D01EAF)

    I       Integral   Estimated error
    1        0.0384        0.0004
    2        0.4012        0.0003
    3        0.3952        0.0003
    4        0.0258        0.0003
    5       -0.3672        0.0003
    6       -0.4227        0.0003
    7       -0.0895        0.0003
    8        0.3260        0.0003
    9        0.4417        0.0003
   10        0.1514        0.0003


d01esfe.r

 D01ESF Example Program Results

 Integral # | Estimated value | Error estimate | Final state of integral
           1|      3.83522E-02|     2.39770E-05|       0
           2|      4.01177E-01|     1.69503E-05|       0
           3|      3.95161E-01|     5.66045E-06|       0
           4|      2.58363E-02|     2.30670E-05|       0
           5|     -3.67242E-01|     1.92659E-05|       0
           6|     -4.22680E-01|     2.24822E-06|       0
           7|     -8.95077E-02|     2.16953E-05|       0
           8|      3.25958E-01|     2.11959E-05|       0
           9|      4.41739E-01|     1.20901E-06|       0
          10|      1.51388E-01|     1.98894E-05|       0


d01fbfe.r

 D01FBF Example Program Results

 Answer =    0.25065


d01fcfe.r

 D01FCF Example Program Results

 Requested accuracy =     0.10E-03
 Estimated value    =       0.5754
 Estimated accuracy =     0.99E-04


d01fdfe.r

 D01FDF Example Program Results

 Sphere-to-sphere transformation

 Estimated value of the integral =    22.168
 Number of integrand evaluations =  8026

 Product region transformation

 Estimated value of the integral =    22.137
 Number of integrand evaluations =  8026


d01gafe.r

 D01GAF Example Program Results

 Integral =  3.1414     Estimated error = -0.0001


d01gbfe.r

 D01GBF Example Program Results

 Requested accuracy    =      0.10E-01
 Estimated value       =       0.57572
 Estimated accuracy    =      0.92E-02
 Number of evaluations =  1728


d01gcfe.r

 D01GCF Example Program Results

 Result =      0.43999  Standard error =  0.19E-05


d01gdfe.r

 D01GDF Example Program Results

 Result =       0.43999, standard error =   0.19E-05


d01gyfe.r

 D01GYF Example Program Results

 NDIM =  4 NPTS =   631

 Coefficients =    1.  198.   82.  461.


d01gzfe.r

 D01GZF Example Program Results

 NDIM =  4 NP1 =    89 NP2 =    11

 Coefficients =    1.  102.  614.  951.


d01jafe.r

 D01JAF Example Program Results

 Dimension of the sphere       =    2
 Requested relative tolerance  = 0.50E-04
 Approximation to the integral =  6.28319
 No. of function evaluations   =  193
 Estimated relative error      = 0.31E-04

 Dimension of the sphere       =    4
 Requested relative tolerance  = 0.50E-04
 Approximation to the integral = 13.16004
 No. of function evaluations   = 2873
 Estimated relative error      = 0.40E-04


d01pafe.r

 D01PAF Example Program Results

 MAXORD   Estimated      Estimated         Integrand
            value         accuracy        evaluations
    1      0.25816       0.258E+00              1
    2      0.25011       0.806E-02              5
    3      0.25000       0.107E-03             15
    4      0.25000       0.410E-06             35
    5      0.25000       0.173E-08             70


d01rafe.r

 D01RAF Example Program Results

                  Quadrature rule :             GK41
             Maximum Subdivisions :               50
                    Extrapolation :             ON
          Extrapolation safeguard :       1.0000E-12

 Integral |  NEEDI  |   DINEST   |   ERREST
         1         0  -2.8431E-02   1.1234E-14
         2         0   7.9083E-03   2.6600E-09

 Information on integration:
 NI =   2, nseg =   7, nsdiv =   3.
 Integral  1 total approximations:   2.
 Integral  2 total approximations:   4.

 Information on subdivision and evaluations over segments.

 Segment   1.
 Sid =   1, Parent =   0, Level =   1.
 Children = (  2,  3).
 Bounds ( 0.0000E+00, 3.1416E+00).
 Integral  1 approximation : -2.8431E-02.
 Integral  1 error estimate:  8.0372E-04.
 Integral  1 evaluation has been superseded by descendants.
 Integral  2 approximation : -3.6050E-01.
 Integral  2 error estimate:  4.2596E+00.
 Integral  2 evaluation has been superseded by descendants.

 Segment   2.
 Sid =   2, Parent =   1, Level =   2.
 Children = (  6,  7).
 Bounds ( 0.0000E+00, 1.5708E+00).
 Integral  1 approximation : -1.2285E-03.
 Integral  1 error estimate:  2.8161E-15.
 Integral  2 approximation :  1.9771E-03.
 Integral  2 error estimate:  4.0437E-01.
 Integral  2 evaluation has been superseded by descendants.

 Segment   3.
 Sid =   2, Parent =   1, Level =   2.
 Children = (  4,  5).
 Bounds ( 1.5708E+00, 3.1416E+00).
 Integral  1 approximation : -2.7202E-02.
 Integral  1 error estimate:  8.4182E-15.
 Integral  2 approximation :  5.9313E-03.
 Integral  2 error estimate:  3.0259E+00.
 Integral  2 evaluation has been superseded by descendants.

 Segment   4.
 Sid =   3, Parent =   3, Level =   3.
 Bounds ( 1.5708E+00, 2.3562E+00).
 Integral  2 approximation :  1.0922E-01.
 Integral  2 error estimate:  7.9151E-10.

 Segment   5.
 Sid =   3, Parent =   3, Level =   3.
 Bounds ( 2.3562E+00, 3.1416E+00).
 Integral  2 approximation : -1.0329E-01.
 Integral  2 error estimate:  1.6413E-09.

 Segment   6.
 Sid =   4, Parent =   2, Level =   3.
 Bounds ( 0.0000E+00, 7.8540E-01).
 Integral  2 approximation :  1.2343E-02.
 Integral  2 error estimate:  5.2456E-11.

 Segment   7.
 Sid =   4, Parent =   2, Level =   3.
 Bounds ( 7.8540E-01, 1.5708E+00).
 Integral  2 approximation : -1.0365E-02.
 Integral  2 error estimate:  1.7467E-10.


d01rgfe.r

 D01RGF Example Program Results

 A      -     lower limit of integration =    -1.0000
 B      -     upper limit of integration =     1.0000
 EPSABS -    absolute accuracy requested =   0.00E+00
 EPSREL -    relative accuracy requested =   0.10E-03

 DINEST -  approximation to the integral =    3.81155
 ERREST - estimate of the absolute error =   0.34E-03
 NEVALS - number of function evaluations =        593


d01tbfe.r

 D01TBF Example Program Results

 Laguerre formula,  6 points

     Abscissae        Weights

    0.222847E+00   0.573536E+00
    0.118893E+01   0.136925E+01
    0.299274E+01   0.226068E+01
    0.577514E+01   0.335052E+01
    0.983747E+01   0.488683E+01
    0.159829E+02   0.784902E+01


d01tefe.r

 D01TEF Example Program Results

       a         b         c
   -1.73205   0.00000   1.73205
   -1.93649   0.00000   1.11803
   -1.97203   0.00000   1.01835
   -1.00000   0.00000   0.50709

    weights       abscissae
    0.34785       -0.86114
    0.65215       -0.33998
    0.65215        0.33998
    0.34785        0.86114


d01uafe.r

 D01UAF Example Program Results

 Gauss-Legendre example
     2 Points     Answer =    3.14754
     4 Points     Answer =    3.14161
     8 Points     Answer =    3.14159
    16 Points     Answer =    3.14159
    32 Points     Answer =    3.14159
    64 Points     Answer =    3.14159

 Rational Gauss example
     2 Points     Answer =    0.37989
     4 Points     Answer =    0.37910
     8 Points     Answer =    0.37876
    16 Points     Answer =    0.37869
    32 Points     Answer =    0.37867
    64 Points     Answer =    0.37867

 Gauss-Laguerre example (adjusted weights)
     2 Points     Answer =    0.04833
     4 Points     Answer =    0.04887
     8 Points     Answer =    0.04890
    16 Points     Answer =    0.04890
    32 Points     Answer =    0.04890
    64 Points     Answer =    0.04890

 Gauss-Laguerre example (normal weights)
     2 Points     Answer =    0.04833
     4 Points     Answer =    0.04887
     8 Points     Answer =    0.04890
    16 Points     Answer =    0.04890
    32 Points     Answer =    0.04890
    64 Points     Answer =    0.04890

 Gauss-Hermite example (adjusted weights)
     2 Points     Answer =    1.38381
     4 Points     Answer =    1.42803
     8 Points     Answer =    1.42817
    16 Points     Answer =    1.42817
    32 Points     Answer =    1.42817
    64 Points     Answer =    1.42817

 Gauss-Hermite example (normal weights)
     2 Points     Answer =    1.38381
     4 Points     Answer =    1.42803
     8 Points     Answer =    1.42817
    16 Points     Answer =    1.42817
    32 Points     Answer =    1.42817
    64 Points     Answer =    1.42817


d01ubfe.r

 D01UBF Example Program Results

 Approximation to the integral =   0.50000


d02agfe.r

 D02AGF Example Program Results

 Case 1

 Final parameters
     0.464269E-01    0.349429E-02

 Final solution
 X-value     Components of solution
    0.10   0.1025E+00   0.1734E-01
    3.28   0.1217E+00   0.4180E-02
    6.46   0.1338E+00   0.3576E-02
    9.64   0.1449E+00   0.3418E-02
   12.82   0.1557E+00   0.3414E-02
   16.00   0.1667E+00   0.3494E-02

 Case 2

 Final parameters
     0.323729E+02    0.596317E+04   -0.535231E+00

 Final solution
 X-value     Components of solution
      0.   0.0000E+00   0.5000E+03   0.5000E+00
   1193.   0.5298E+03   0.4516E+03   0.3281E+00
   2385.   0.8076E+03   0.4203E+03   0.1231E+00
   3578.   0.8208E+03   0.4094E+03  -0.1032E+00
   4771.   0.5563E+03   0.4200E+03  -0.3296E+00
   5963.   0.0000E+00   0.4500E+03  -0.5352E+00


d02bgfe.r

 D02BGF Example Program Results

 Calculation with TOL = 0.1E-03
  Y(M) changes sign at X =  7.2884

 Calculation with TOL = 0.1E-04
  Y(M) changes sign at X =  7.2883


d02bhfe.r

 D02BHF Example Program Results

 Calculation with TOL = 0.1E-03
  Root of Y(1) at 7.2884
  Solution is      0.00000      0.47485     -0.76010

 Calculation with TOL = 0.1E-04
  Root of Y(1) at 7.2883
  Solution is     -0.00000      0.47486     -0.76011


d02bjfe.r

 D02BJF Example Program Results

 Case 1: intermediate output, root-finding

  Calculation with TOL = 0.1E-03
      X         Y(1)         Y(2)         Y(3)
     0.00       0.5000       0.5000       0.6283
     2.00       1.5493       0.4055       0.3066
     4.00       1.7423       0.3743      -0.1289
     6.00       1.0055       0.4173      -0.5507
   Root of Y(1) = 0.0 at  7.288
   Solution is      -0.0000       0.4749      -0.7601

  Calculation with TOL = 0.1E-04
      X         Y(1)         Y(2)         Y(3)
     0.00       0.5000       0.5000       0.6283
     2.00       1.5493       0.4055       0.3066
     4.00       1.7423       0.3743      -0.1289
     6.00       1.0055       0.4173      -0.5507
   Root of Y(1) = 0.0 at  7.288
   Solution is       0.0000       0.4749      -0.7601

 Case 2: no intermediate output, root-finding

  Calculation with TOL = 0.1E-03
   Root of Y(1) = 0.0 at  7.288
   Solution is      -0.0000       0.4749      -0.7601

  Calculation with TOL = 0.1E-04
   Root of Y(1) = 0.0 at  7.288
   Solution is       0.0000       0.4749      -0.7601

 Case 3: intermediate output, no root-finding

  Calculation with TOL = 0.1E-03
      X         Y(1)         Y(2)         Y(3)
     0.00       0.5000       0.5000       0.6283
     2.00       1.5493       0.4055       0.3066
     4.00       1.7423       0.3743      -0.1289
     6.00       1.0055       0.4173      -0.5507
     8.00      -0.7460       0.5130      -0.8537
    10.00      -3.6283       0.6333      -1.0515

  Calculation with TOL = 0.1E-04
      X         Y(1)         Y(2)         Y(3)
     0.00       0.5000       0.5000       0.6283
     2.00       1.5493       0.4055       0.3066
     4.00       1.7423       0.3743      -0.1289
     6.00       1.0055       0.4173      -0.5507
     8.00      -0.7459       0.5130      -0.8537
    10.00      -3.6282       0.6333      -1.0515

 Case 4: no intermediate output, no root-finding ( integrate to XEND)

  Calculation with TOL = 0.1E-03
      X         Y(1)         Y(2)         Y(3)
     0.00       0.5000       0.5000       0.6283
    10.00      -3.6283       0.6333      -1.0515

  Calculation with TOL = 0.1E-04
      X         Y(1)         Y(2)         Y(3)
     0.00       0.5000       0.5000       0.6283
    10.00      -3.6282       0.6333      -1.0515


d02cjfe.r

 D02CJF Example Program Results

 Case 1: intermediate output, root-finding

  Calculation with TOL = 0.1E-03
      X         Y(1)         Y(2)         Y(3)
     0.00      0.50000      0.50000      0.62832
     2.00      1.54931      0.40548      0.30662
     4.00      1.74229      0.37433     -0.12890
     6.00      1.00554      0.41731     -0.55068
   Root of Y(1) = 0.0 at  7.288
   Solution is     -0.00000      0.47486     -0.76011

  Calculation with TOL = 0.1E-04
      X         Y(1)         Y(2)         Y(3)
     0.00      0.50000      0.50000      0.62832
     2.00      1.54933      0.40548      0.30662
     4.00      1.74232      0.37433     -0.12891
     6.00      1.00552      0.41731     -0.55069
   Root of Y(1) = 0.0 at  7.288
   Solution is     -0.00000      0.47486     -0.76010

 Case 2: no intermediate output, root-finding

  Calculation with TOL = 0.1E-03
   Root of Y(1) = 0.0 at  7.288
   Solution is     -0.00000      0.47486     -0.76011

  Calculation with TOL = 0.1E-04
   Root of Y(1) = 0.0 at  7.288
   Solution is     -0.00000      0.47486     -0.76010

 Case 3: intermediate output, no root-finding

  Calculation with TOL = 0.1E-03
      X         Y(1)         Y(2)         Y(3)
     0.00      0.50000      0.50000      0.62832
     2.00      1.54931      0.40548      0.30662
     4.00      1.74229      0.37433     -0.12890
     6.00      1.00554      0.41731     -0.55068
     8.00     -0.74589      0.51299     -0.85371
    10.00     -3.62813      0.63325     -1.05152

  Calculation with TOL = 0.1E-04
      X         Y(1)         Y(2)         Y(3)
     0.00      0.50000      0.50000      0.62832
     2.00      1.54933      0.40548      0.30662
     4.00      1.74232      0.37433     -0.12891
     6.00      1.00552      0.41731     -0.55069
     8.00     -0.74601      0.51299     -0.85372
    10.00     -3.62829      0.63326     -1.05153

 Case 4: no intermediate output, no root-finding ( integrate to XEND)

  Calculation with TOL = 0.1E-03
      X         Y(1)         Y(2)         Y(3)
     0.00      0.50000      0.50000      0.62832
    10.00     -3.62813      0.63325     -1.05152

  Calculation with TOL = 0.1E-04
      X         Y(1)         Y(2)         Y(3)
     0.00      0.50000      0.50000      0.62832
    10.00     -3.62829      0.63326     -1.05153


d02ejfe.r

 D02EJF Example Program Results

 Case 1: calculating Jacobian internally,
        intermediate output, root-finding

  Calculation with TOL = 0.1E-02
      X         Y(1)         Y(2)         Y(3)
     0.00      1.00000      0.00000      0.00000
     2.00      0.94163      0.00003      0.05834
     4.00      0.90551      0.00002      0.09447
   Root of Y(1)-0.9 at  4.377
   Solution is      0.90000      0.00002      0.09998

  Calculation with TOL = 0.1E-03
      X         Y(1)         Y(2)         Y(3)
     0.00      1.00000      0.00000      0.00000
     2.00      0.94161      0.00003      0.05837
     4.00      0.90551      0.00002      0.09446
   Root of Y(1)-0.9 at  4.377
   Solution is      0.90000      0.00002      0.09998

 Case 2: calculating Jacobian by PEDERV,
        intermediate output, root-finding

  Calculation with TOL = 0.1E-02
      X         Y(1)         Y(2)         Y(3)
     0.00      1.00000      0.00000      0.00000
     2.00      0.94163      0.00003      0.05834
     4.00      0.90551      0.00002      0.09447
   Root of Y(1)-0.9 at  4.377
   Solution is      0.90000      0.00002      0.09998

  Calculation with TOL = 0.1E-03
      X         Y(1)         Y(2)         Y(3)
     0.00      1.00000      0.00000      0.00000
     2.00      0.94161      0.00003      0.05837
     4.00      0.90551      0.00002      0.09446
   Root of Y(1)-0.9 at  4.377
   Solution is      0.90000      0.00002      0.09998

 Case 3: calculating Jacobian internally,
        no intermediate output, root-finding

  Calculation with TOL = 0.1E-02
   Root of Y(1)-0.9 at  4.377
   Solution is      0.90000      0.00002      0.09998

  Calculation with TOL = 0.1E-03
   Root of Y(1)-0.9 at  4.377
   Solution is      0.90000      0.00002      0.09998

 Case 4: calculating Jacobian internally,
        intermediate output, no root-finding

  Calculation with TOL = 0.1E-02
      X         Y(1)         Y(2)         Y(3)
     0.00      1.00000      0.00000      0.00000
     2.00      0.94163      0.00003      0.05834
     4.00      0.90551      0.00002      0.09447
     6.00      0.87930      0.00002      0.12068
     8.00      0.85858      0.00002      0.14140
    10.00      0.84136      0.00002      0.15862

  Calculation with TOL = 0.1E-03
      X         Y(1)         Y(2)         Y(3)
     0.00      1.00000      0.00000      0.00000
     2.00      0.94161      0.00003      0.05837
     4.00      0.90551      0.00002      0.09446
     6.00      0.87926      0.00002      0.12072
     8.00      0.85854      0.00002      0.14145
    10.00      0.84136      0.00002      0.15863

 Case 5: calculating Jacobian internally,
        no intermediate output, no root-finding (integrate to XEND)

  Calculation with TOL = 0.1E-02
      X         Y(1)         Y(2)         Y(3)
     0.00      1.00000      0.00000      0.00000
    10.00      0.84136      0.00002      0.15862

  Calculation with TOL = 0.1E-03
      X         Y(1)         Y(2)         Y(3)
     0.00      1.00000      0.00000      0.00000
    10.00      0.84136      0.00002      0.15863


d02hafe.r

 D02HAF Example Program Results

 Results with TOL =  0.500E-03

  X-value and final solution
  0.0     0.000     0.500     1.168
  1.0     1.918     0.334     0.975
  2.0     2.928     0.207     0.493
  3.0     2.977     0.196    -0.419
  4.0     2.021     0.310    -0.975
  5.0    -0.000     0.460    -1.201

 Results with TOL =  0.500E-04

  X-value and final solution
  0.0     0.0000    0.5000    1.1681
  1.0     1.9176    0.3343    0.9749
  2.0     2.9281    0.2070    0.4929
  3.0     2.9771    0.1955   -0.4195
  4.0     2.0210    0.3095   -0.9752
  5.0    -0.0000    0.4597   -1.2014


d02hbfe.r

 D02HBF Example Program Results

 Case 1

 Final parameters
       4.629E-02      3.494E-03

 Final solution
 X-value     Components of solution
    0.10       0.1025       0.0173
    3.28       0.1217       0.0042
    6.46       0.1338       0.0036
    9.64       0.1449       0.0034
   12.82       0.1557       0.0034
   16.00       0.1667       0.0035

 Case 2

 Final parameters
       3.239E+01      5.962E+03     -5.353E-01

 Final solution
 X-value     Components of solution
      0.          0.0        500.0        0.500
   1192.        529.6        451.6        0.328
   2385.        807.2        420.3        0.123
   3577.        820.4        409.4       -0.103
   4769.        556.1        420.0       -0.330
   5962.         -0.0        450.0       -0.535


d02lafe.r

 D02LAF Example Program Results

 Calculation with TOL =   1.0E-04

   T      Y(1)       Y(2)
   0.0    0.50000    0.00000
   2.0   -1.20573    0.61357
   4.0   -1.33476   -0.47685
   6.0    0.35748   -0.44558
   8.0   -1.03762    0.73022
  10.0   -1.42617   -0.32658
  12.0    0.05515   -0.72032
  14.0   -0.82880    0.81788
  16.0   -1.48103   -0.16788
  18.0   -0.26719   -0.84223
  20.0   -0.57803    0.86339

  Number of successful steps =   108
  Number of   failed   steps =    16

 Calculation with TOL =   1.0E-05

   T      Y(1)       Y(2)
   0.0    0.50000    0.00000
   2.0   -1.20573    0.61357
   4.0   -1.33476   -0.47685
   6.0    0.35748   -0.44558
   8.0   -1.03762    0.73022
  10.0   -1.42617   -0.32658
  12.0    0.05516   -0.72031
  14.0   -0.82880    0.81787
  16.0   -1.48103   -0.16789
  18.0   -0.26718   -0.84223
  20.0   -0.57804    0.86338

  Number of successful steps =   169
  Number of   failed   steps =    15


d02mvfe.r

 D02MVF Example Program Results

 Pendulum problem with relative tolerance = 1.0E-03
                   and absolute tolerance = 1.0E-06

   t          y1      y2      y3      y4      y5      y6
  0.0000    1.0000  0.0000  0.0000  0.0000  0.0000  0.0000
  3.1416   -0.9856 -0.1694 -0.0986  0.5736  0.5080  0.0000


d02mwfe.r

 D02MWF Example Program Results

   t           y(1)       y(2)       y(3)       y(4)       y(5)
  0.0000     1.000000   0.000000   0.000000   1.000000   1.000000
  1.0000     0.867349   0.497701  -0.033748   0.058813  -0.493103

 D02NEF returned with ITASK =    3

 The position-level constraint G1 =  -0.8580E-08
 The velocity-level constraint G2 =  -0.3005E-07


d02mzfe.r

 D02MZF Example Program Results

     X          Y(1)           Y(2)           Y(3)
    0.000      1.00000        0.00000        0.00000
    0.020      0.99920        0.00004        0.00076
    0.040      0.99841        0.00004        0.00155
    0.060      0.99763        0.00004        0.00234
    0.080      0.99685        0.00004        0.00311
    0.100      0.99608        0.00004        0.00389


d02nbfe.r

 D02NBF Example Program Results

   Numerical Jacobian

     X          Y(1)           Y(2)           Y(3)
    0.000      1.00000        0.00000        0.00000
   10.000      0.84136        0.00002        0.15863

  HUSED =  0.51867E+00  HNEXT =  0.51867E+00  TCUR =  0.10000E+02
  NST =     55    NRE =    132    NJE =     17
  NQU =      3    NQ  =      3  NITER =     79
  Max Err Comp =    3

   Analytic Jacobian

     X          Y(1)           Y(2)           Y(3)
    0.000      1.00000        0.00000        0.00000
   10.000      0.84136        0.00002        0.15863

  HUSED =  0.51867E+00  HNEXT =  0.51867E+00  TCUR =  0.10000E+02
  NST =     55    NRE =     81    NJE =     17
  NQU =      3    NQ  =      3  NITER =     79
  Max Err Comp =    3


d02ncfe.r

 D02NCF Example Program Results

     X          Y(1)           Y(2)           Y(3)
    0.000      1.00000        0.00000        0.00000
    5.000      0.89152        0.00002        0.10846
   10.000      0.84137        0.00002        0.15861

  HUSED =  0.11280E+01  HNEXT =  0.11280E+01  TCUR =  0.10034E+02
  NST =     63    NRE =    274    NJE =     14
  NQU =      4    NQ  =      4  NITER =    272
  Max Err Comp =    3


d02ndfe.r

 D02NDF Example Program Results

   Numerical Jacobian, structure not supplied

     X          Y(1)           Y(2)           Y(3)
    0.000      1.00000        0.00000        0.00000
    2.000      0.94161        0.00003        0.05836
    4.000      0.90552        0.00002        0.09446
    6.000      0.87927        0.00002        0.12072
    8.000      0.85855        0.00002        0.14144
   10.000      0.84137        0.00002        0.15863

  HUSED =  0.90236E+00  HNEXT =  0.90236E+00  TCUR =  0.10769E+02
  NST =     55    NRE =    136    NJE =     16
  NQU =      4    NQ  =      4  NITER =     78
  Max err comp =    3

  NJCPVT (required  100  used      160)
  NWKJAC (required   29  used       78)
  No. of LU-decomps   16  No. of nonzeros        7
  No. of FCN calls to form Jacobian    3  Try ISPLIT   73
  Growth est     1108  No. of blocks on diagonal    1

   Numerical Jacobian, structure supplied

     X          Y(1)           Y(2)           Y(3)
    0.000      1.00000        0.00000        0.00000
    2.000      0.94161        0.00003        0.05836
    4.000      0.90551        0.00002        0.09446
    6.000      0.87926        0.00002        0.12072
    8.000      0.85854        0.00002        0.14144
   10.000      0.84135        0.00002        0.15863

  HUSED =  0.90178E+00  HNEXT =  0.90178E+00  TCUR =  0.10766E+02
  NST =     55    NRE =    129    NJE =     16
  NQU =      4    NQ  =      4  NITER =     78
  Max err comp =    3

  NJCPVT (required  106  used      160)
  NWKJAC (required   31  used       77)
  No. of LU-decomps   16  No. of nonzeros        8
  No. of FCN calls to form Jacobian    3  Try ISPLIT   73
  Growth est   277504  No. of blocks on diagonal    1


d02nefe.r

 D02NEF Example Program Results

 D02NEF Example 1

     t            Y(1)        Y(2)        Y(3)
   0.0000       1.000000    0.000000    0.000000
   0.0200       0.999204    0.000036    0.000760
   0.0400       0.998415    0.000036    0.001549
   0.0600       0.997631    0.000036    0.002333
   0.0800       0.996852    0.000036    0.003112
   0.1000       0.996080    0.000036    0.003884

 The integrator completed task, ITASK =    3

 D02NEF Example 2

     t            y(1)
   0.0000       2.000000
   0.2000       2.038016
   0.4000       2.078379
   0.6000       2.121462
   0.8000       2.167736
   1.0000       2.217821

 The integrator completed task, ITASK =    3


d02ngfe.r

 D02NGF Example Program Results

     X          Y(1)           Y(2)           Y(3)
    0.000      1.00000        0.00000        0.00000
    0.020      0.99920        0.00004        0.00076
    0.040      0.99841        0.00004        0.00155
    0.060      0.99763        0.00004        0.00234
    0.080      0.99685        0.00004        0.00311
    0.100      0.99608        0.00004        0.00389

  HUSED =  0.26516E-03  HNEXT =  0.53032E-03  TCUR =  0.10016E+00
  NST =    244    NRE =    809    NJE =      0
  NQU =      1    NQ  =      1  NITER =      0
  Max err comp =    2


d02nhfe.r

 D02NHF Example Program Results
 Warning: Equation(=i1) and possibly other equations are
 implicit and in calculating the initial values the
 equations will be treated as implicit.
 In above message i1 =         1

  Initial    Y :      1.0000       0.0000       0.0000
  Initial YDOT :     -0.0400       0.0400       0.0000
 Warning: Equation(=i1) and possibly other equations are
 implicit and in calculating the initial values the
 equations will be treated as implicit.
 In above message i1 =         1

     X          Y(1)           Y(2)           Y(3)
   10.000      0.84135        0.00002        0.15863

  HUSED =  0.91752E+00  HNEXT =  0.91752E+00  TCUR =  0.10885E+02
  NST =     51    NRE =    118    NJE =     14
  NQU =      4    NQ  =      4  NITER =     68
  Max err comp =    3


d02njfe.r

 D02NJF Example Program Results

   Analytic Jacobian, structure not supplied

     X          Y(1)           Y(2)           Y(3)
    0.000      1.00000        0.00000        0.00000
    4.957      0.89208        0.00002        0.10790

  HUSED =  0.59971E+00  HNEXT =  0.59971E+00  TCUR =  0.49566E+01
  NST =     52    NRE =    132    NJE =     12
  NQU =      4    NQ  =      4  NITER =    117
  Max err comp =    3

  NJCPVT (required  105  used      156)
  NWKJAC (required   34  used       79)
  No. of LU-decomps   12  No. of nonzeros        9
  No. of FCN calls to form Jacobian    0  Try ISPLIT   73
  Growth est     1034  No. of blocks on diagonal    1

   Analytic Jacobian, structure supplied

     X          Y(1)           Y(2)           Y(3)
    0.000      1.00000        0.00000        0.00000
    4.957      0.89208        0.00002        0.10790

  HUSED =  0.59971E+00  HNEXT =  0.59971E+00  TCUR =  0.49566E+01
  NST =     52    NRE =    131    NJE =     12
  NQU =      4    NQ  =      4  NITER =    117
  Max err comp =    3

  NJCPVT (required   99  used      156)
  NWKJAC (required   31  used       79)
  No. of LU-decomps   12  No. of nonzeros        8
  No. of FCN calls to form Jacobian    0  Try ISPLIT   72
  Growth est     1034  No. of blocks on diagonal    1


d02nmfe.r

 D02NMF Example Program Results

     X          Y(1)           Y(2)           Y(3)
    0.000      1.00000        0.00000        0.00000
    2.000      0.94161        0.00003        0.05836
    4.000      0.90551        0.00002        0.09446
    6.000      0.87926        0.00002        0.12072
    8.000      0.85854        0.00002        0.14144
   10.000      0.84135        0.00002        0.15863

  HUSED =  0.90178E+00  HNEXT =  0.90178E+00  TCUR =  0.10766E+02
  NST =     55    NRE =    128    NJE =     16
  NQU =      4    NQ  =      4  NITER =     78
  Max err comp =    3


d02nnfe.r

 D02NNF Example Program Results

     X          Y(1)           Y(2)           Y(3)
    0.000      1.00000        0.00000        0.00000
 Warning: Equation(=i1) and possibly other equations are
 implicit and in calculating the initial values the
 equations will be treated as implicit.
 In above message i1 =         1
   10.000      0.84136        0.00002        0.15863

  HUSED =  0.81503E+00  HNEXT =  0.12467E+01  TCUR =  0.10409E+02
  NST =     51    NRE =    130    NJE =     14
  NQU =      4    NQ  =      4  NITER =    121
  Max err comp =    3   No. of failed steps =    0

  NJCPVT (required  105  used      156)
  NWKJAC (required   34  used       79)
  No. of LU-decomps   14  No. of nonzeros        9
  No. of FCN calls to form Jacobian    0  Try ISPLIT   73
  Growth est     1386  No. of blocks on diagonal    1


d02pefe.r

 D02PEF Example Program Results

 Calculation with TOL =  1.0E-03

    t         y1        y2

  0.000     0.000     1.000
  0.785     0.707     0.707
  1.571     0.999    -0.000
  2.356     0.706    -0.706
  3.142    -0.000    -0.999
  3.927    -0.706    -0.706
  4.712    -0.998     0.000
  5.498    -0.705     0.706
  6.283     0.001     0.997

 Cost of the integration in evaluations of F is   430

 Calculation with TOL =  1.0E-04

    t         y1        y2

  0.000     0.000     1.000
  0.785     0.707     0.707
  1.571     1.000    -0.000
  2.356     0.707    -0.707
  3.142    -0.000    -1.000
  3.927    -0.707    -0.707
  4.712    -1.000     0.000
  5.498    -0.707     0.707
  6.283     0.000     1.000

 Cost of the integration in evaluations of F is   892


d02pufe.r

 D02PUF Example Program Results

 Calculation with TOL =  0.1E-05

    t         y1         y2         y3         y4

  0.000     0.3000     0.0000     0.0000     2.3805
  9.425    -1.7000     0.0000    -0.0000    -0.4201

 Componentwise error assessment
            0.38E-05   0.71E-05   0.69E-05   0.21E-05

 Worst global error observed was  0.34E-04 - it occurred at T =  6.302

 Cost of the integration in evaluations of F is  1361


d02qffe.r

 D02QFF Example Program Results

 Root at   0.00000E+00
 for event equation  2 with type  1 and residual   0.00000E+00
  Y(1) =   0.00000E+00   Y'(1) =   1.00000E+00

 Root at   1.57076E+00
 for event equation  1 with type  1 and residual  -5.20417E-17
  Y(1) =   1.00003E+00   Y'(1) =  -5.20417E-17

 Root at   3.14151E+00
 for event equation  2 with type  1 and residual  -1.27676E-15
  Y(1) =  -1.27676E-15   Y'(1) =  -1.00012E+00

 Root at   4.71228E+00
 for event equation  1 with type  1 and residual   1.67921E-15
  Y(1) =  -1.00010E+00   Y'(1) =   1.67921E-15

 Root at   6.28306E+00
 for event equation  2 with type  1 and residual   2.65066E-15
  Y(1) =   2.65066E-15   Y'(1) =   9.99979E-01

 Root at   7.85379E+00
 for event equation  1 with type  4 and residual  -7.63278E-17
  Y(1) =   9.99970E-01   Y'(1) =  -7.63278E-17

 Root at   9.42469E+00
 for event equation  2 with type  4 and residual  -6.86950E-16
  Y(1) =  -6.86950E-16   Y'(1) =  -9.99854E-01


d02qgfe.r

 D02QGF Example Program Results

   T         Y(1)     Y(2)     Y(3)
  0.0000   0.5000   0.5000   0.6283
  2.0000   1.5493   0.4055   0.3066
  4.0000   1.7423   0.3743  -0.1289
  6.0000   1.0055   0.4173  -0.5507
  7.2883  -0.0000   0.4749  -0.7601


d02tyfe.r

 D02TYF Example Program Results

 Tolerance =  0.1E-04 A =     1.00

 Used a mesh of   11 points
 Maximum error =   0.31E-05  in interval    1 for component    1

 Mesh points:
   1(1) 0.0000E+00   2(3) 0.1000E+00   3(2) 0.2000E+00   4(3) 0.3000E+00
   5(2) 0.4000E+00   6(3) 0.5000E+00   7(2) 0.6000E+00   8(3) 0.7000E+00
   9(2) 0.8000E+00  10(3) 0.9000E+00  11(1) 0.1000E+01

 Computed solution
       x     solution   derivative
     0.00    1.00000   -1.84496
     0.10    0.84944   -1.32330
     0.20    0.72721   -1.13911
     0.30    0.61927   -1.02776
     0.40    0.52040   -0.95468
     0.50    0.42754   -0.90583
     0.60    0.33867   -0.87372
     0.70    0.25239   -0.85369
     0.80    0.16764   -0.84248
     0.90    0.08368   -0.83756
     1.00    0.00000   -0.83655


d02uyfe.r

  D02UYF Example Program Results

 Integral of f(x) from   -1.0 to   3.00 =      28.00000.


d02uzfe.r

  D02UZF Example Program Results

     x_even     x_map      Sum
    -1.0000   -0.7540    1.3715
    -0.7500   -0.4634    1.1261
    -0.5000   -0.1728    1.0158
    -0.2500    0.1178    1.0067
     0.0000    0.4084    1.0731
     0.2500    0.6990    1.1961
     0.5000    0.9896    1.3613
     0.7500    1.2802    1.5582
     1.0000    1.5708    1.7787


d03eafe.r

 D03EAF Example Program Results

 Interior Neumann problem

 Total integral =          16.00

 Nodes
            X              Y              PHI            PHID
            1.50           2.00           1.00           0.00
           -1.50           2.00           1.00           0.00
            0.00           0.00           1.00           0.00
            0.00           1.00           1.00           0.00
           -1.00           2.00           1.00           0.00
            1.00           2.00           1.00           0.00

 Selected points
            X              Y              PHI
            2.00           1.00           1.00
            2.50           0.50           1.00
            3.00           0.00           1.00


d03fafe.r

 D03FAF Example Program Results

 Maximum component of discretization error = 5.176553E-04


d03pcae.r

 D03PCA Example Program Results

 Accuracy requirement  =  0.10000E-02
 Parameter ALPHA =          0.100E+01

   T  /  X     0.0000  0.4000  0.6000  0.8000  0.9000  1.0000

  0.0001 U(1)  0.0000  0.8008  1.1988  1.5990  1.7958  1.8485
         U(2)  0.9997  0.9995  0.9994  0.9988  0.9663 -0.0000

  0.0010 U(1)  0.0000  0.7982  1.1940  1.5841  1.7179  1.6734
         U(2)  0.9969  0.9952  0.9937  0.9484  0.6385 -0.0000

  0.0100 U(1)  0.0000  0.7676  1.1239  1.3547  1.3635  1.2830
         U(2)  0.9627  0.9495  0.8754  0.5537  0.2908 -0.0000

  0.1000 U(1)  0.0000  0.3908  0.5007  0.5297  0.5120  0.4744
         U(2)  0.5468  0.4299  0.2995  0.1479  0.0724 -0.0000

  1.0000 U(1)  0.0000  0.0007  0.0008  0.0008  0.0008  0.0007
         U(2)  0.0010  0.0007  0.0005  0.0002  0.0001 -0.0000

 Number of integration steps in time                     78
 Number of residual evaluations of resulting ODE system 378
 Number of Jacobian evaluations                          25
 Number of iterations of nonlinear solver               190


d03pcfe.r

 D03PCF Example Program Results

 Accuracy requirement  =  0.10000E-02
 Parameter ALPHA =          0.100E+01

   T  /  X     0.0000  0.4000  0.6000  0.8000  0.9000  1.0000

  0.0001 U(1)  0.0000  0.8008  1.1988  1.5990  1.7958  1.8485
         U(2)  0.9997  0.9995  0.9994  0.9988  0.9663 -0.0000

  0.0010 U(1)  0.0000  0.7982  1.1940  1.5841  1.7179  1.6734
         U(2)  0.9969  0.9952  0.9937  0.9484  0.6385 -0.0000

  0.0100 U(1)  0.0000  0.7676  1.1239  1.3547  1.3635  1.2830
         U(2)  0.9627  0.9495  0.8754  0.5537  0.2908 -0.0000

  0.1000 U(1)  0.0000  0.3908  0.5007  0.5297  0.5120  0.4744
         U(2)  0.5468  0.4299  0.2995  0.1479  0.0724 -0.0000

  1.0000 U(1)  0.0000  0.0007  0.0008  0.0008  0.0008  0.0007
         U(2)  0.0010  0.0007  0.0005  0.0002  0.0001 -0.0000

 Number of integration steps in time                    78
 Number of residual evaluations of resulting ODE system 378
 Number of Jacobian evaluations                          25
 Number of iterations of nonlinear solver               190


d03pdae.r

 D03PDA Example Program Results
 Polynomial degree =   3   No. of elements =    9
 Accuracy requirement = 0.100E-03  Number of points =    28

  T /   X     -1.0000 -0.6000 -0.2000  0.2000  0.6000  1.0000

  0.0001 U(1)  1.0000  0.8090  0.3090 -0.3090 -0.8090 -1.0000
         U(2) -2.4850 -1.9957 -0.7623  0.7623  1.9957  2.4850

  0.0010 U(1)  1.0000  0.8085  0.3088 -0.3088 -0.8085 -1.0000
         U(2) -2.5583 -1.9913 -0.7606  0.7606  1.9913  2.5583

  0.0100 U(1)  1.0000  0.8051  0.3068 -0.3068 -0.8051 -1.0000
         U(2) -2.6962 -1.9481 -0.7439  0.7439  1.9481  2.6962

  0.1000 U(1)  1.0000  0.7951  0.2985 -0.2985 -0.7951 -1.0000
         U(2) -2.9022 -1.8339 -0.6338  0.6338  1.8339  2.9022

  1.0000 U(1)  1.0000  0.7939  0.2972 -0.2972 -0.7939 -1.0000
         U(2) -2.9233 -1.8247 -0.6120  0.6120  1.8247  2.9233

 Number of integration steps in time                     50
 Number of residual evaluations of resulting ODE system 407
 Number of Jacobian evaluations                          18
 Number of iterations of nonlinear solver               122


d03pdfe.r

 D03PDF Example Program Results
 Polynomial degree =   3   No. of elements =    9
 Accuracy requirement = 0.100E-03  Number of points =    28

  T /   X     -1.0000 -0.6000 -0.2000  0.2000  0.6000  1.0000

  0.0001 U(1)  1.0000  0.8090  0.3090 -0.3090 -0.8090 -1.0000
         U(2) -2.4850 -1.9957 -0.7623  0.7623  1.9957  2.4850

  0.0010 U(1)  1.0000  0.8085  0.3088 -0.3088 -0.8085 -1.0000
         U(2) -2.5583 -1.9913 -0.7606  0.7606  1.9913  2.5583

  0.0100 U(1)  1.0000  0.8051  0.3068 -0.3068 -0.8051 -1.0000
         U(2) -2.6962 -1.9481 -0.7439  0.7439  1.9481  2.6962

  0.1000 U(1)  1.0000  0.7951  0.2985 -0.2985 -0.7951 -1.0000
         U(2) -2.9022 -1.8339 -0.6338  0.6338  1.8339  2.9022

  1.0000 U(1)  1.0000  0.7939  0.2972 -0.2972 -0.7939 -1.0000
         U(2) -2.9233 -1.8247 -0.6120  0.6120  1.8247  2.9233

 Number of integration steps in time                     50
 Number of residual evaluations of resulting ODE system 407
 Number of Jacobian evaluations                          18
 Number of iterations of nonlinear solver               122


d03pefe.r

 D03PEF Example Program Results

  Accuracy requirement = 0.100E-05 Number of points =  41

 X            0.1000    0.3000    0.5000    0.7000    0.9000

 T =  0.20
 Approx U1    0.7845    1.0010    1.2733    1.6115    2.0281
 Exact  U1    0.7845    1.0010    1.2733    1.6115    2.0281
 Approx U2   -0.8352   -0.8159   -0.8367   -0.9128   -1.0609
 Exact  U2   -0.8353   -0.8160   -0.8367   -0.9129   -1.0609

 T =  0.40
 Approx U1    0.6481    0.8533    1.1212    1.4627    1.8903
 Exact  U1    0.6481    0.8533    1.1212    1.4627    1.8903
 Approx U2   -1.5216   -1.6767   -1.8934   -2.1917   -2.5944
 Exact  U2   -1.5217   -1.6767   -1.8935   -2.1917   -2.5945

 T =  0.60
 Approx U1    0.6892    0.8961    1.1747    1.5374    1.9989
 Exact  U1    0.6892    0.8962    1.1747    1.5374    1.9989
 Approx U2   -2.0047   -2.3434   -2.7677   -3.3002   -3.9680
 Exact  U2   -2.0048   -2.3436   -2.7678   -3.3003   -3.9680

 T =  0.80
 Approx U1    0.8977    1.1247    1.4320    1.8349    2.3514
 Exact  U1    0.8977    1.1247    1.4320    1.8349    2.3512
 Approx U2   -2.3403   -2.8675   -3.5110   -4.2960   -5.2536
 Exact  U2   -2.3405   -2.8677   -3.5111   -4.2961   -5.2537

 T =  1.00
 Approx U1    1.2470    1.5206    1.8828    2.3528    2.9519
 Exact  U1    1.2470    1.5205    1.8829    2.3528    2.9518
 Approx U2   -2.6229   -3.3338   -4.1998   -5.2505   -6.5218
 Exact  U2   -2.6232   -3.3340   -4.2001   -5.2507   -6.5219

 Number of integration steps in time =    149
 Number of function evaluations =    399
 Number of Jacobian evaluations =    13
 Number of iterations =    323


d03pffe.r

 D03PFF Example Program Results

 Example 1

 Number of mesh points used =  101
 Relative tolerance used    =  0.100E-03
 Absolute tolerance used    =  0.100E-04

     t         x        Approx u    Exact u     Approx v    Exact v

  0.100      0.0000      1.0615      1.0613     -0.0155     -0.0150
             0.2000      0.9892      0.9891     -0.0953     -0.0957
             0.4000      1.0826      1.0826      0.1180      0.1178
             0.6000      1.7001      1.7001     -0.0751     -0.0746
             0.8000      2.3959      2.3966     -0.2453     -0.2458
             1.0000      2.1029      2.1025      0.3760      0.3753

  0.200      0.0000      1.0957      1.0956      0.0368      0.0370
             0.2000      1.0808      1.0811      0.1826      0.1828
             0.4000      1.1102      1.1100     -0.2935     -0.2938
             0.6000      1.6461      1.6454     -1.2921     -1.2908
             0.8000      1.7913      1.7920     -0.8510     -0.8525
             1.0000      2.2050      2.2050     -0.4222     -0.4221

 Number of time steps           (nearest 5)  =     55
 Number of function evaluations (nearest 50) =    250
 Number of Jacobian evaluations (nearest 10) =     10
 Number of iterations           (nearest 50) =    150

 Example 2

 Number of mesh points used =  151
 Relative tolerance used    =  0.100E-04
 Absolute tolerance used    =  0.100E-04

 x            -1.0000  -0.9600  -0.5200   0.0000   0.4800   0.9600   1.0000
 u(t= 1.000)   3.0000   3.6221   3.8087   4.0000   4.1766   4.3779   5.0000
 u(t=10.000)   3.0000   3.9592   4.0000   4.0000   4.0000   4.0408   5.0000

 Number of time steps           (nearest 5)  =    505
 Number of function evaluations (nearest 50) =   1200
 Number of Jacobian evaluations (nearest 10) =     30
 Number of iterations           (nearest 50) =   1050


d03phae.r

 D03PHA Example Program Results

 Simple coupled PDE using BDF
 Local Accuracy        =    1.000E-05
 Number of mesh points =  101

   time        solution at x=0
    0.2                0.22
    0.4                0.49
    0.8                1.23
    1.6                3.95
    3.2               23.53


d03phfe.r

 D03PHF Example Program Results

 Simple coupled PDE using BDF
 Local Accuracy        =    1.000E-05
 Number of mesh points =  101

   time        solution at x=0
    0.2                0.22
    0.4                0.49
    0.8                1.23
    1.6                3.95
    3.2               23.53


d03pjae.r

 D03PJA Example Program Results

 Simple coupled PDE using BDF
 Local Accuracy        =    1.000E-05
 Degree of Polynomial  =    3
 Number of elements    =   29
 Number of mesh points =   88

   time        solution at x=0
    0.2                0.22
    0.4                0.49
    0.8                1.23
    1.6                3.95
    3.2               23.53


d03pjfe.r

 D03PJF Example Program Results

 Simple coupled PDE using BDF
 Accuracy requirement  =    1.000E-05
 Degree of Polynomial  =    3
 Number of elements    =   29
 Number of mesh points =   88

   time        solution at x=0
    0.2                0.22
    0.4                0.49
    0.8                1.23
    1.6                3.95
    3.2               23.53


d03pkfe.r

 D03PKF Example Program Results

  Accuracy requirement = 0.100E-03 Number of points =  21

  X            0.000    0.200    0.400    0.600    1.000

 T =  0.200
 App.  sol.    0.222    0.174    0.128    0.084    0.000  ODE sol. =   0.200
 Exact sol.    0.221    0.174    0.127    0.083    0.000  ODE sol. =   0.200

 T =  0.400
 App.  sol.    0.492    0.377    0.271    0.174    0.000  ODE sol. =   0.400
 Exact sol.    0.492    0.377    0.271    0.174    0.000  ODE sol. =   0.400

 T =  0.800
 App.  sol.    1.226    0.896    0.616    0.377   -0.000  ODE sol. =   0.800
 Exact sol.    1.226    0.896    0.616    0.377    0.000  ODE sol. =   0.800

 T =  1.600
 App.  sol.    3.952    2.595    1.610    0.895   -0.001  ODE sol. =   1.600
 Exact sol.    3.953    2.597    1.612    0.896    0.000  ODE sol. =   1.600

 T =  3.200
 App.  sol.   23.522   11.918    5.807    2.588   -0.004  ODE sol. =   3.197
 Exact sol.   23.533   11.936    5.821    2.597    0.000  ODE sol. =   3.200

 Number of integration steps in time =    642
 Number of function evaluations =   3022
 Number of Jacobian evaluations =    39
 Number of iterations =   1328


d03plfe.r

 D03PLF Example Program Results

 Example 1

 Method Parameters:
  Number of mesh points used =  201
  Relative tolerance used    =  0.250E-03
  Absolute tolerance used    =  0.100E-04

 Integration Results:
  Global error is less than 100 times the local error tolerance.

 Integration Statistics:
  Number of time steps           (nearest  50) =    150
  Number of function evaluations (nearest 100) =   1400
  Number of Jacobian evaluations (nearest  20) =     20
  Number of iterations           (nearest 100) =    400

 Example 2

 Problem Parameter and initial conditions:
  gamma          = 1.400
      e(x<0.5,0) = 2.500    e(x>0.5,0) = 0.250
    rho(x>0.5,0) = 1.000  rho(x>0.5,0) = 0.125

 Method Parameters:
  Number of mesh points used =  141
  Relative tolerance used    =  0.500E-03
  Absolute tolerance used    =  0.500E-02

 Solution
    t      x     density velocity pressure
  0.100  0.0000   1.0000   0.0000   1.0000
          0.100   1.0000  -0.0000   1.0000
          0.200   1.0000  -0.0000   1.0000
          0.300   1.0000  -0.0000   1.0000
          0.400   0.8668   0.1665   0.8188
          0.500   0.4299   0.9182   0.3071
          0.600   0.2969   0.9274   0.3028
          0.700   0.1250   0.0000   0.1000
          0.800   0.1250  -0.0000   0.1000
          0.900   0.1250  -0.0000   0.1000
          1.000   0.1250   0.0000   0.1000

  0.200  0.0000   1.0000   0.0000   1.0000
          0.100   1.0000  -0.0000   1.0000
          0.200   1.0000  -0.0000   1.0000
          0.300   0.8718   0.1601   0.8253
          0.400   0.6113   0.5543   0.5022
          0.500   0.4245   0.9314   0.3014
          0.600   0.4259   0.9277   0.3030
          0.700   0.2772   0.9272   0.3031
          0.800   0.2657   0.9276   0.3032
          0.900   0.1250  -0.0000   0.1000
          1.000   0.1250   0.0000   0.1000

 Number of time steps           (nearest 50) =    150
 Number of function evaluations (nearest 50) =    400
 Number of Jacobian evaluations (nearest  1) =      1
 Number of iterations           (nearest  1) =      2


d03ppae.r

 D03PPA Example Program Results

  Accuracy requirement = 0.500E-04 Number of points =  61

  Remeshing every  3 time steps

  E =   0.005

 T =  0.200
 X              0.3000   0.4000   0.5000   0.6000   0.7000
 Approx sol.    0.9968   0.7448   0.4700   0.1667   0.1018
 Exact  sol.    0.9967   0.7495   0.4700   0.1672   0.1015

 T =  0.400
 X              0.4000   0.5000   0.6000   0.7000   0.8000
 Approx sol.    1.0003   0.9601   0.4088   0.1154   0.1005
 Exact  sol.    0.9997   0.9615   0.4094   0.1157   0.1003

 T =  0.600
 X              0.6000   0.6500   0.7000   0.7500   0.8000
 Approx sol.    0.9966   0.9390   0.3978   0.1264   0.1037
 Exact  sol.    0.9964   0.9428   0.4077   0.1270   0.1033

 T =  0.800
 X              0.7000   0.7500   0.8000   0.8500   0.9000
 Approx sol.    1.0003   0.9872   0.5450   0.1151   0.1010
 Exact  sol.    0.9996   0.9878   0.5695   0.1156   0.1008

 T =  1.000
 X              0.8000   0.8500   0.9000   0.9500   1.0000
 Approx sol.    1.0001   0.9961   0.7324   0.1245   0.1004
 Exact  sol.    0.9999   0.9961   0.7567   0.1273   0.1004

 Number of integration steps in time =    205
 Number of function evaluations =   4872
 Number of Jacobian evaluations =    71
 Number of iterations =    518


d03ppfe.r

 D03PPF Example Program Results

  Accuracy requirement = 0.500E-04 Number of points =  61

  Remeshing every  3 time steps

  E =   0.005

 T =  0.200
 X              0.3000   0.4000   0.5000   0.6000   0.7000
 Approx sol.    0.9968   0.7448   0.4700   0.1667   0.1018
 Exact  sol.    0.9967   0.7495   0.4700   0.1672   0.1015

 T =  0.400
 X              0.4000   0.5000   0.6000   0.7000   0.8000
 Approx sol.    1.0003   0.9601   0.4088   0.1154   0.1005
 Exact  sol.    0.9997   0.9615   0.4094   0.1157   0.1003

 T =  0.600
 X              0.6000   0.6500   0.7000   0.7500   0.8000
 Approx sol.    0.9966   0.9390   0.3978   0.1264   0.1037
 Exact  sol.    0.9964   0.9428   0.4077   0.1270   0.1033

 T =  0.800
 X              0.7000   0.7500   0.8000   0.8500   0.9000
 Approx sol.    1.0003   0.9872   0.5450   0.1151   0.1010
 Exact  sol.    0.9996   0.9878   0.5695   0.1156   0.1008

 T =  1.000
 X              0.8000   0.8500   0.9000   0.9500   1.0000
 Approx sol.    1.0001   0.9961   0.7324   0.1245   0.1004
 Exact  sol.    0.9999   0.9961   0.7567   0.1273   0.1004

 Number of integration steps in time =    205
 Number of function evaluations =   4872
 Number of Jacobian evaluations =    71
 Number of iterations =    518


d03prfe.r

 D03PRF Example Program Results

  Accuracy requirement = 0.500E-04 Number of points =  61

 Remeshing every   3 time steps

 X            0.0000    0.2500    0.5000    0.7500    1.0000

 T =  0.050
 Approx U1    0.9923    1.0894    1.4686    2.3388    2.1071
 Exact  U1    0.9923    1.0893    1.4686    2.3391    2.1073
 Approx U2   -0.0997    0.1057    0.7180    0.0967    0.2021
 Exact  U2   -0.0998    0.1046    0.7193    0.0966    0.2022

 T =  0.100
 Approx U1    1.0613    0.9856    1.3120    2.3084    2.1039
 Exact  U1    1.0613    0.9851    1.3113    2.3092    2.1025
 Approx U2   -0.0150   -0.0481    0.1075   -0.3240    0.3753
 Exact  U2   -0.0150   -0.0495    0.1089   -0.3235    0.3753

 T =  0.150
 Approx U1    1.1485    0.9763    1.2658    2.0906    2.2027
 Exact  U1    1.1485    0.9764    1.2654    2.0911    2.2027
 Approx U2    0.1370   -0.0250   -0.4107   -0.8577    0.3096
 Exact  U2    0.1366   -0.0266   -0.4100   -0.8567    0.3096

 T =  0.200
 Approx U1    1.0956    1.0529    1.3407    1.8322    2.2035
 Exact  U1    1.0956    1.0515    1.3393    1.8327    2.2050
 Approx U2    0.0381    0.1282   -0.7979   -1.1776   -0.4221
 Exact  U2    0.0370    0.1247   -0.7961   -1.1784   -0.4221

 T =  0.250
 Approx U1    0.8119    1.1288    1.5163    1.6076    2.2027
 Exact  U1    0.8119    1.1276    1.5142    1.6091    2.2035
 Approx U2   -0.4968    0.2123   -1.0259   -1.2149   -1.3938
 Exact  U2   -0.4992    0.2078   -1.0257   -1.2183   -1.3938

 Number of integration steps in time =     50
 Number of function evaluations =   2579
 Number of Jacobian evaluations =    20
 Number of iterations =    126


d03psfe.r

 D03PSF Example Program Results

 Example 1

  NPTS =   61 ATOL =  0.100E-03 RTOL =  0.100E-03

 T =  0.100
 X           0.2000   0.3000   0.4000   0.5000   0.6000   0.7000   0.8000
 Approx U    0.0000   0.1198   0.9461   0.1182   0.0000   0.0000   0.0000

 T =  0.200
 X           0.2000   0.3000   0.4000   0.5000   0.6000   0.7000   0.8000
 Approx U    0.0000   0.0007   0.1631   0.9015   0.1629   0.0001   0.0000

 T =  0.300
 X           0.2000   0.3000   0.4000   0.5000   0.6000   0.7000   0.8000
 Approx U    0.0000   0.0000   0.0025   0.1924   0.8596   0.1946   0.0002

 Number of integration steps in time =     92
 Number of function evaluations =    443
 Number of Jacobian evaluations =    39
 Number of iterations =    231

 Example 2

 NPTS =   61 ATOL =  0.500E-03 RTOL =  0.500E-01

 T =  0.200
        X        Approx U    Exact U

      0.0000      1.0000      1.0000
      0.3000      0.9536      1.0000
      0.4000      0.0000      0.0000
      0.5000      0.0000      0.0000
      0.6000      0.0000      0.0000
      0.7000     -0.0000      0.0000
      1.0000      0.0000      0.0000
 T =  0.400
        X        Approx U    Exact U

      0.0000      1.0000      1.0000
      0.3000      1.0000      1.0000
      0.4000      1.0000      1.0000
      0.5000      0.9750      1.0000
      0.6000     -0.0000      0.0000
      0.7000      0.0000      0.0000
      1.0000      0.0000      0.0000

 Number of integration steps in time =    672
 Number of function evaluations =   1515
 Number of Jacobian evaluations =     1
 Number of iterations =      2


d03pwfe.r

 D03PWF Example Program Results

 T =  0.035

    X       APPROX D   EXACT D    APPROX V   EXACT V    APPROX P   EXACT P
  0.10E+00 0.5999E+01 0.5999E+01 0.1960E+02 0.1960E+02 0.4609E+03 0.4609E+03
  0.20E+00 0.5999E+01 0.5999E+01 0.1960E+02 0.1960E+02 0.4609E+03 0.4609E+03
  0.30E+00 0.5999E+01 0.5999E+01 0.1960E+02 0.1960E+02 0.4609E+03 0.4609E+03
  0.40E+00 0.5999E+01 0.5999E+01 0.1960E+02 0.1960E+02 0.4609E+03 0.4609E+03
  0.50E+00 0.5999E+01 0.5999E+01 0.1960E+02 0.1960E+02 0.4609E+03 0.4609E+03
  0.60E+00 0.1422E+02 0.1428E+02 0.8658E+01 0.8690E+01 0.1687E+04 0.1692E+04
  0.70E+00 0.1426E+02 0.1428E+02 0.8670E+01 0.8690E+01 0.1688E+04 0.1692E+04
  0.80E+00 0.1944E+02 0.1428E+02 0.8678E+01 0.8690E+01 0.1691E+04 0.1692E+04
  0.90E+00 0.3100E+02 0.3104E+02 0.8676E+01 0.8690E+01 0.1687E+04 0.1692E+04

 Number of integration steps in time =    699
 Number of function evaluations =   1714
 Number of Jacobian evaluations =     1
 Number of iterations =      2


d03pxfe.r

 D03PXF Example Program Results

 T =  0.035

    X       APPROX D   EXACT D    APPROX V   EXACT V    APPROX P   EXACT P
  0.10E+00 0.5999E+01 0.5999E+01 0.1960E+02 0.1960E+02 0.4609E+03 0.4609E+03
  0.20E+00 0.5999E+01 0.5999E+01 0.1960E+02 0.1960E+02 0.4609E+03 0.4609E+03
  0.30E+00 0.5999E+01 0.5999E+01 0.1960E+02 0.1960E+02 0.4609E+03 0.4609E+03
  0.40E+00 0.5999E+01 0.5999E+01 0.1960E+02 0.1960E+02 0.4609E+03 0.4609E+03
  0.50E+00 0.5999E+01 0.5999E+01 0.1960E+02 0.1960E+02 0.4609E+03 0.4609E+03
  0.60E+00 0.1423E+02 0.1428E+02 0.8660E+01 0.8690E+01 0.1688E+04 0.1692E+04
  0.70E+00 0.1425E+02 0.1428E+02 0.8672E+01 0.8690E+01 0.1688E+04 0.1692E+04
  0.80E+00 0.1921E+02 0.1428E+02 0.8674E+01 0.8690E+01 0.1689E+04 0.1692E+04
  0.90E+00 0.3100E+02 0.3104E+02 0.8675E+01 0.8690E+01 0.1687E+04 0.1692E+04

 Number of integration steps in time =    697
 Number of function evaluations =   1708
 Number of Jacobian evaluations =     1
 Number of iterations =      2


d04aafe.r

 D04AAF Example Program Results

 Four separate runs to calculate the first four odd order derivatives of
    FUN(X) = 0.5*exp(2.0*X-1.0) at X = 0.5.
 The exact results are 1, 4, 16 and 64

 Input parameters common to all four runs
   XVAL =  0.5    NDER = -7    IFAIL = 0

 with step length   0.5000  the results are
 Order        Derivative       Questionable?
  1           0.1392E+04             Yes
  3          -0.3139E+04             Yes
  5           0.8762E+04             Yes
  7          -0.2475E+05             Yes

 with step length   0.0500  the results are
 Order        Derivative       Questionable?
  1           0.1000E+01             No
  3           0.4000E+01             No
  5           0.1600E+02             No
  7           0.6400E+02             No

 with step length   0.0050  the results are
 Order        Derivative       Questionable?
  1           0.1000E+01             No
  3           0.4000E+01             No
  5           0.1600E+02             No
  7           0.6404E+02             No

 with step length   0.0005  the results are
 Order        Derivative       Questionable?
  1           0.1000E+01             No
  3           0.4000E+01             No
  5           0.1599E+02             No
  7           0.3825E+05             Yes


d04bafe.r

 D04BAF Example Program Results

  Find the derivatives of the polygamma (psi) function
  using function values generated by S14AEF.

  Demonstrate the effect of successively reducing HBASE.

  Derivative (1) calculated using S14AEF :  4.0153E+02
  Derivative and error estimates for derivative (1)
          hbase       DER(1)     EREST(1)
     2.5000E-03   4.0204E+02   1.3940E+02
     2.5000E-04   4.0153E+02   4.9170E-11
     2.5000E-05   4.0153E+02   2.1799E-10
     2.5000E-06   4.0153E+02   1.1826E-09

  Derivative (2) calculated using S14AEF : -1.6002E+04
  Derivative and error estimates for derivative (2)
          hbase       DER(2)     EREST(2)
     2.5000E-03  -1.6022E+04   5.5760E+03
     2.5000E-04  -1.6002E+04   1.2831E-07
     2.5000E-05  -1.6002E+04   6.0543E-06
     2.5000E-06  -1.6002E+04   9.5762E-04

  Derivative (3) calculated using S14AEF :  9.6001E+05
  Derivative and error estimates for derivative (3)
          hbase       DER(3)     EREST(3)
     2.5000E-03   9.1465E+05  -7.3750E+06
     2.5000E-04   9.6001E+05   2.3718E-04
     2.5000E-05   9.6001E+05   4.2253E-02
     2.5000E-06   9.6001E+05   5.9679E+01


d05aafe.r

 D05AAF Example Program Results

 Kernel is centro-symmetric and G is even so the solution is even

 Chebyshev coefficients

     0.9440E+00   -0.4994E+00    0.2799E-01   -0.5967E-03    0.6658E-05

 X= 0.10    ANS=    0.3090


d05abfe.r

 D05ABF Example Program Results

 Solution is even

 Results for N =  5

 Solution on first  5 Chebyshev points and Chebyshev coefficients
   I           X             F(I)         C(I)
   1        0.93969        0.75572    0.14152E+01
   2        0.76604        0.74534    0.49384E-01
   3        0.50000        0.71729   -0.10476E-02
   4        0.17365        0.68319   -0.23282E-03
   5       -0.17365        0.66051    0.20890E-04

 Solution on evenly spaced grid
      X           F(X)
   0.0000        0.65742
   0.2500        0.66383
   0.5000        0.68319
   0.7500        0.71489
   1.0000        0.75572

 Results for N = 10

 Solution on first 10 Chebyshev points and Chebyshev coefficients
   I           X             F(I)         C(I)
   1        0.98636        0.75572    0.14152E+01
   2        0.94582        0.75336    0.49384E-01
   3        0.87947        0.74639   -0.10475E-02
   4        0.78914        0.73525   -0.23275E-03
   5        0.67728        0.72081    0.19986E-04
   6        0.54695        0.70452    0.98675E-06
   7        0.40170        0.68825   -0.23796E-06
   8        0.24549        0.67404    0.18581E-08
   9        0.08258        0.66361    0.24483E-08
  10       -0.08258        0.65812   -0.16527E-09

 Solution on evenly spaced grid
      X           F(X)
   0.0000        0.65742
   0.2500        0.66384
   0.5000        0.68319
   0.7500        0.71489
   1.0000        0.75572


d05bafe.r

 D05BAF Example Program Results

 Size of workspace =         486
 Tolerance         =  0.1000E-02

    T        Approx. Sol.  True Sol.    Est. Error    Actual Error
   3.33       1.80037       1.80033    0.80378E-04    0.23847E-04
   6.67       2.23916       2.23911    0.17774E-03    0.23477E-04
  10.00       2.54310       2.54304    0.24595E-03    0.22456E-04
  13.33       2.77587       2.77581    0.30574E-03    0.21743E-04
  16.67       2.96456       2.96450    0.36170E-03    0.21382E-04
  20.00       3.12324       3.12317    0.41713E-03    0.21310E-04


d05bdfe.r

 D05BDF Example Program Results

 Example 1

 The stepsize h =   0.1000

      T        Approximate
                 Solution

   0.0000         0.0000
   0.5000         0.7071
   1.0000         1.0000
   1.5000         1.2247
   2.0000         1.4142
   2.5000         1.5811
   3.0000         1.7321
   3.5000         1.8708
   4.0000         2.0000
   4.5000         2.1213
   5.0000         2.2361
   5.5000         2.3452
   6.0000         2.4495
   6.5000         2.5495
   7.0000         2.6458

 Example 2

 The stepsize h =   0.0714

      T        Approximate
                 Solution

   0.0000         0.0000
   0.5000         0.3536
   1.0000         0.0000
   1.5000        -0.6124
   2.0000        -1.4142
   2.5000        -2.3717
   3.0000        -3.4641
   3.5000        -4.6771
   4.0000        -6.0000
   4.5000        -7.4246
   5.0000        -8.9443


d05befe.r

 D05BEF Example Program Results

 Example 1

 The stepsize h =   0.1000

      T        Approximate
                 Solution

   0.5000         0.1191
   1.0000         0.0528
   1.5000         0.0265
   2.0000         0.0146
   2.5000         0.0086
   3.0000         0.0052
   3.5000         0.0033
   4.0000         0.0022
   4.5000         0.0014
   5.0000         0.0010
   5.5000         0.0007
   6.0000         0.0004
   6.5000         0.0003
   7.0000         0.0002

 The maximum absolute error,   0.29E-02, occurred at T =  0.1000
 with solution   0.0326

 Example 2

 The stepsize h =   0.0714

      T        Approximate
                 Solution

   0.5000         0.6667
   1.0000         0.5000
   1.5000         0.4000
   2.0000         0.3333
   2.5000         0.2857
   3.0000         0.2500
   3.5000         0.2222
   4.0000         0.2000
   4.5000         0.1818
   5.0000         0.1667

 The maximum absolute error,   0.32E-05, occurred at T =  0.0714
 with solution   0.9333


d06aafe.r

 D06AAF Example Program Results

 NV   =   250
 NELT =   402


d06abfe.r

 D06ABF Example Program Results

 Mesh characteristics with NPROPA =    -5
  NV   =       2250 to the nearest 250
  NELT =       4250 to the nearest 250
 Mesh characteristics with NPROPA =    -1
  NV   =       4500 to the nearest 250
  NELT =       8500 to the nearest 250
 Mesh characteristics with NPROPA =     1
  NV   =       5250 to the nearest 250
  NELT =      10000 to the nearest 250
 Mesh characteristics with NPROPA =     5
  NV   =       2000 to the nearest 250
  NELT =       3750 to the nearest 250


d06acfe.r

 D06ACF Example Program Results

 Boundary mesh characteristics
 NVB   =   120
 NEDGE =   120
 Complete mesh characteristics
 NV (rounded to nearest 10)   =  1890
 NELT (rounded to nearest 10) =  3660


d06bafe.r

 D06BAF Example Program Results

 Analysis of the boundary created:
 The boundary mesh contains    332 vertices and    332 edges
 There are      4 components comprising the boundary:
 The  1-st component contains      4 lines in anticlockwise orientation
 The  2-nd component contains     10 lines in     clockwise orientation
 The  3-rd component contains     12 lines in anticlockwise orientation
 The  4-th component contains     19 lines in     clockwise orientation
 Boundary mesh characteristics
 NVB   =   332
 NEDGE =   332
 Complete mesh (via the 2D Delaunay-Voronoi
 mesh generator) characteristics
 NV (rounded to nearest 10)   =   900
 NELT (rounded to nearest 10) =  1480
 Complete mesh (via the 2D Advancing front mesh
 generator) characteristics
 NV (rounded to nearest 10)   =   920
 NELT (rounded to nearest 10) =  1520


d06cafe.r

 D06CAF Example Program Results

 The complete distorted mesh characteristics
 Number of vertices =   400
 Number of elements =   722
 BEFORE SMOOTHING
 Minimum smoothness measure:       1.0060557
 Maximum smoothness measure:      45.7310387
 Distribution interval            Number of elements
      1.0060557 -       5.4785540       715
      5.4785540 -       9.9510523         4
      9.9510523 -      14.4235506         1
     14.4235506 -      18.8960489         0
     18.8960489 -      23.3685472         0
     23.3685472 -      27.8410455         0
     27.8410455 -      32.3135438         0
     32.3135438 -      36.7860421         0
     36.7860421 -      41.2585404         0
     41.2585404 -      45.7310387         1

 AFTER SMOOTHING
 Minimum smoothness measure:       1.3377832
 Maximum smoothness measure:       1.4445226
 Distribution interval            Number of elements
      1.3377832 -       1.3484572         0
      1.3484572 -       1.3591311        13
      1.3591311 -       1.3698050        42
      1.3698050 -       1.3804790       104
      1.3804790 -       1.3911529       162
      1.3911529 -       1.4018268       159
      1.4018268 -       1.4125008       122
      1.4125008 -       1.4231747        74
      1.4231747 -       1.4338486        31
      1.4338486 -       1.4445226        14

 The complete smoothed mesh characteristics
 Number of vertices =   400
 Number of elements =   722


d06ccfe.r

 D06CCF Example Program Results

 Matrix Sparsity characteristics before renumbering
 nv   =   260
 nnz  =  1626
 nelt =   422

 Initial half-bandwidth:   251    Initial profile: 19911
   Final half-bandwidth:    27      Final profile:  4012

 Matrix Sparsity characteristics after renumbering
 nv   =   260
 nnz  =  1626
 nelt =   422


d06dbfe.r

 D06DBF Example Program Results

 Example 1

 The restitched mesh characteristics in the overlapping case
 nv    =   785
 nelt  =  1428
 nedge =   152
 The restitched mesh characteristics in the partition case
 nv    =   780
 nelt  =  1444
 nedge =   133

 Example 2

 The restitched mesh characteristics
 nv    =   643
 nelt  =  1133
 nedge =   171


e01aafe.r

 E01AAF Example Program Results

 Interpolated values
     -1.35680    -1.28000    -0.39253     1.28000     5.67808
     -1.23699    -0.60467     0.01434     1.38680
     -0.88289    -0.88662    -0.74722
     -0.88125    -0.91274

 Interpolation point =      0.28000

 Function value at interpolation point =     -0.83591


e01abfe.r

 E01ABF Example Program Results

 Central differences order 0 of Y0 =    -1.00000
                                Y1 =    -0.46000
 Central differences order 1 of Y0 =     1.01000
                                Y1 =     1.92000
 Central differences order 2 of Y0 =    -0.04000
                                Y1 =     3.80000

 Function value at interpolation point =    -0.83591


e01aefe.r

 E01AEF Example Program Results

 Total number of interpolating conditions =   7

 Interpolating polynomial

    i                a_i
    0              9.1250
    1             -4.5781
    2              0.4609
    3              2.8516
    4             -2.8125
    5              2.2266
    6             -0.7109

   i   x_i    order(k)   y^(k)    Residual
   1   2.0      0        1.0         -
   2   4.0      0        2.0         -
                1       -1.0         -
   3   5.0      0        1.0         -
   4   6.0      0        2.0         -
                1        4.0         -
                2       -2.0         -


e01befe.r

 E01BEF Example Program Results

                 Interpolated
      Abscissa          Value
        7.9900         0.0000
        9.1910         0.4640
       10.3920         0.9645
       11.5930         0.9965
       12.7940         0.9992
       13.9950         0.9998
       15.1960         0.9999
       16.3970         1.0000
       17.5980         1.0000
       18.7990         1.0000
       20.0000         1.0000


e01bffe.r

 E01BFF Example Program Results

                   Interpolated
        Abscissa          Value
          7.9900         0.0000
          9.1910         0.4640
         10.3920         0.9645
         11.5930         0.9965
         12.7940         0.9992
         13.9950         0.9998
         15.1960         0.9999
         16.3970         1.0000
         17.5980         1.0000
         18.7990         1.0000
         20.0000         1.0000


e01bgfe.r

 E01BGF Example Program Results

                   Interpolated   Interpolated
        Abscissa          Value     Derivative
          7.9900         0.0000      0.000E+00
          9.1910         0.4640      6.060E-01
         10.3920         0.9645      4.569E-02
         11.5930         0.9965      9.917E-03
         12.7940         0.9992      6.249E-04
         13.9950         0.9998      2.708E-04
         15.1960         0.9999      2.809E-05
         16.3970         1.0000      2.034E-05
         17.5980         1.0000      1.308E-05
         18.7990         1.0000      6.297E-06
         20.0000         1.0000     -3.388E-21


e01bhfe.r

 E01BHF Example Program Results

                                Integral
           A            B     over (A,B)
        7.9900      20.0000      10.7648
       10.0000      12.0000       1.9622
       12.0000      10.0000      -1.9622
       15.0000      15.0000       0.0000


e01eafe.r

 E01EAF Example Program Results

    px      py     Interpolated Value
  2.0500  1.7750        48.2100
  3.7500  3.2500        41.4195
  5.0000  5.0000        36.1613
  8.5400  2.0500        28.2458
  9.1400  4.4500        24.4543


e01rafe.r

 E01RAF Example Program Results

 The values of U(J) are
   0.0000E+00  3.0000E+00  1.0000E+00

 The Thiele coefficients A(J) are
   4.0000E+00  1.0000E+00  7.5000E-01 -1.0000E+00


e01rbfe.r

 E01RBF Example Program Results

 X =  6.0000E+00

 The value of R(X) is   1.7714E+01


e01sgfe.r

 E01SGF Example Program Results

      I      U(I)      V(I)      Q(I)
      1     20.00      3.14     15.95
      2      6.41     15.44     38.71
      3      7.54     10.69     19.31
      4      9.91     18.27     16.39
      5     12.30      9.22     14.66


e01tgfe.r

 E01TGF Example Program Results

      I     U(I)      V(I)      W(I)      Q(I)
      1    0.1000    0.1000    0.1000    0.2663
      2    0.2000    0.2000    0.2000    0.1040
      3    0.3000    0.3000    0.3000    0.0695
      4    0.4000    0.4000    0.4000    0.1539
      5    0.5000    0.5000    0.5000    0.3010
      6    0.6000    0.6000    0.6000    0.5695


e01zmfe.r

 E01ZMF Example Program Results

 Interpolated Evaluation Points (columns)
          1       2       3       4       5       6
 1   0.1000  0.2000  0.3000  0.4000  0.5000  0.6000
 2   0.1000  0.2000  0.3000  0.4000  0.5000  0.6000
 3   0.1000  0.2000  0.3000  0.4000  0.5000  0.6000
 4   0.1000  0.2000  0.3000  0.4000  0.5000  0.6000
 5   0.1000  0.2000  0.3000  0.4000  0.5000  0.6000
 6   0.1000  0.2000  0.3000  0.4000  0.5000  0.6000

 Interpolated values
             1          2          3          4          5          6
 1     -7.2059    -3.9343    -0.9674     1.6680     3.9251     5.9318


e02acfe.r

 E02ACF Example Program Results

    Polynomial coefficients
        0.1000E+01
        0.1000E+01
        0.4991E+00
        0.1704E+00
        0.3478E-01
        0.1391E-01

    Reference deviation =   0.11E-05

   X     exp(X)    Fit     Residual
  0.00   1.0000   1.0000  -0.11E-05
  0.10   1.1052   1.1052   0.97E-06
  0.20   1.2214   1.2214  -0.74E-06
  0.30   1.3499   1.3499  -0.92E-06
  0.40   1.4918   1.4918   0.30E-06
  0.50   1.6487   1.6487   0.11E-05
  0.60   1.8221   1.8221   0.46E-06
  0.70   2.0138   2.0138  -0.82E-06
  0.80   2.2255   2.2255  -0.84E-06
  0.90   2.4596   2.4596   0.88E-06
  1.00   2.7183   2.7183  -0.11E-05


e02adfe.r

 E02ADF Example Program Results

 Degree   0   R.M.S. residual =    0.41E+01

   J  Chebyshev coeff A(J)
   1        12.1740

 Degree   1   R.M.S. residual =    0.43E+01

   J  Chebyshev coeff A(J)
   1        12.2954
   2         0.2740

 Degree   2   R.M.S. residual =    0.17E+01

   J  Chebyshev coeff A(J)
   1        20.7345
   2         6.2016
   3         8.1876

 Degree   3   R.M.S. residual =    0.68E-01

   J  Chebyshev coeff A(J)
   1        24.1429
   2         9.4065
   3        10.8400
   4         3.0589

 Polynomial approximation and residuals for degree   3

   R   Abscissa     Weight   Ordinate  Polynomial  Residual
   1     1.0000     1.0000    10.4000    10.4461   0.46E-01
         1.5500                           9.3106
   2     2.1000     1.0000     7.9000     7.7977  -0.10E+00
         2.6000                           6.2555
   3     3.1000     1.0000     4.7000     4.7025   0.25E-02
         3.5000                           3.5488
   4     3.9000     1.0000     2.5000     2.5533   0.53E-01
         4.4000                           1.6435
   5     4.9000     1.0000     1.2000     1.2390   0.39E-01
         5.3500                           1.4257
   6     5.8000     0.8000     2.2000     2.2425   0.42E-01
         6.1500                           3.3803
   7     6.5000     0.8000     5.1000     5.0116  -0.88E-01
         6.8000                           6.8400
   8     7.1000     0.7000     9.2000     9.0982  -0.10E+00
         7.4500                          12.3171
   9     7.8000     0.5000    16.1000    16.2123   0.11E+00
         8.1000                          20.1266
  10     8.4000     0.3000    24.5000    24.6048   0.10E+00
         8.7000                          29.6779
  11     9.0000     0.2000    35.3000    35.3769   0.77E-01


e02aefe.r

 E02AEF Example Program Results

   R       Argument       Value of polynomial
   1       -1.0000            0.6875
   2       -0.8000            0.6613
   3       -0.6000            0.6943
   4       -0.4000            0.7433
   5       -0.2000            0.7843
   6        0.0000            0.8125
   7        0.2000            0.8423
   8        0.4000            0.9073
   9        0.6000            1.0603
  10        0.8000            1.3733
  11        1.0000            1.9375


e02agfe.r

 E02AGF Example Program Results

 Degree  RMS residual
    3       2.55E-03
    4       2.94E-03

 Details of the fit of degree  4

   Index   Coefficient
      0     3.9980
      1     3.4995
      2     3.0010
      3     0.5005
      4    -0.0000

      I      X(I)       Y(I)       Fit     Residual
      1     0.5000     0.0300     0.0310   0.10E-02
      2     1.0000    -0.7500    -0.7508  -0.78E-03
      3     2.0000    -1.0000    -1.0020  -0.20E-02
      4     2.5000    -0.1000    -0.0961   0.39E-02
      5     3.0000     1.7500     1.7478  -0.22E-02


e02ahfe.r

 E02AHF Example Program Results

    I  Argument    1st deriv    2nd deriv
    1  -0.5000       0.2453       0.1637
    2   0.5000       0.4777       0.3185
    3   1.5000       0.9304       0.6203
    4   2.5000       1.8119       1.2056


e02ajfe.r

 E02AJF Example Program Results

 Value of definite integral is     2.1515


e02akfe.r

 E02AKF Example Program Results

    I   Argument  Value of polynomial
    1   -0.5000       0.3679
    2    0.5000       0.7165
    3    1.5000       1.3956
    4    2.5000       2.7183


e02alfe.r

 E02ALF Example Program Results

    Polynomial coefficients
        0.1000E+01
        0.1000E+01
        0.4991E+00
        0.1704E+00
        0.3478E-01
        0.1391E-01

    Reference deviation =   0.11E-05

   x     Fit      exp(x)   Residual
  0.00   1.0000   1.0000  -0.11E-05
  0.10   1.1052   1.1052   0.97E-06
  0.20   1.2214   1.2214  -0.74E-06
  0.30   1.3499   1.3499  -0.92E-06
  0.40   1.4918   1.4918   0.30E-06
  0.50   1.6487   1.6487   0.11E-05
  0.60   1.8221   1.8221   0.46E-06
  0.70   2.0138   2.0138  -0.82E-06
  0.80   2.2255   2.2255  -0.84E-06
  0.90   2.4596   2.4596   0.88E-06
  1.00   2.7183   2.7183  -0.11E-05


e02bbfe.r

 E02BBF Example Program Results

   J       LAMDA(J)    B-spline coefficient (J-2)

   1        1.0000
   2        1.0000
   3        1.0000               1.0000
   4        1.0000               2.0000
   5        3.0000               4.0000
   6        6.0000               7.0000
   7        8.0000               6.0000
   8        9.0000               4.0000
   9        9.0000               3.0000
  10        9.0000
  11        9.0000

   R       Argument      Value of cubic spline

   1        1.0000               1.0000
   2        2.0000               2.3779
   3        3.0000               3.6229
   4        4.0000               4.8327
   5        5.0000               5.8273
   6        6.0000               6.3571
   7        7.0000               6.1905
   8        8.0000               5.1667
   9        9.0000               3.0000


e02bdfe.r

 E02BDF Example Program Results

 Definite integral =   0.100E+03


e02befe.r

 E02BEF Example Program Results

 Calling with smoothing factor S =   1.000E+00

                                            B-Spline
              J       Knot LAMDA(J+2)   Coefficient C(J)
              1                             -1.3201
              2            0.0000            1.3542
              3            4.0000            5.5510
              4            8.0000            4.7031
              5                              8.2277

 Weighted sum of squared residuals FP =   1.000E+00

 Calling with smoothing factor S =   5.000E-01

                                            B-Spline
              J       Knot LAMDA(J+2)   Coefficient C(J)
              1                             -1.1072
              2            0.0000           -0.6571
              3            1.0000            0.4350
              4            2.0000            2.8061
              5            4.0000            4.6824
              6            5.0000            4.6416
              7            6.0000            5.1976
              8            8.0000            6.9008
              9                              7.9979

 Weighted sum of squared residuals FP =   5.001E-01

 Calling with smoothing factor S =   1.000E-01

                                            B-Spline
              J       Knot LAMDA(J+2)   Coefficient C(J)
              1                             -1.0901
              2            0.0000           -0.6401
              3            1.0000            0.0334
              4            1.5000            1.6390
              5            2.0000            2.1243
              6            3.0000            4.5591
              7            4.0000            4.2174
              8            4.5000            4.9105
              9            5.0000            4.5475
             10            5.5000            4.6960
             11            6.0000            5.7370
             12            8.0000            6.8179
             13                              7.9953

 Weighted sum of squared residuals FP =   9.999E-02


e02defe.r

 E02DEF Example Program Results

       I       X(I)       Y(I)      FF(I)
       1      1.000      0.000      1.000
       2      1.100      0.100      1.310
       3      1.500      0.700      2.950
       4      1.600      0.400      2.960
       5      1.900      0.300      3.910
       6      1.900      0.800      4.410
       7      2.000      1.000      5.000


e02dhfe.r

 E02DHF Example Program Results

 Spline fit used smoothing factor S =   1.0000E-01.
 Number of knots in each direction  =   10,   13.

 Sum of squared residuals           =   1.0004E-01.

 Derivative of spline has order nux, nuy =    1,    0.

 Spline evaluated on X-Y grid (X across, Y down):
          0.00    1.00    2.00    3.00    4.00    5.00
 0.00    0.992   2.043   3.029   4.014   5.021   5.997
 1.00    0.541   1.088   1.607   2.142   2.705   3.239
 2.00   -0.417  -0.829  -1.241  -1.665  -2.083  -2.485
 3.00   -0.978  -1.975  -2.914  -3.913  -4.965  -5.924
 4.00   -0.648  -1.363  -1.991  -2.606  -3.251  -3.933

 Spline derivative evaluated on X-Y grid:
          0.00    1.00    2.00    3.00    4.00    5.00
 0.00    1.093   1.013   0.970   1.004   1.001   0.939
 1.00    0.565   0.531   0.515   0.558   0.559   0.499
 2.00   -0.429  -0.404  -0.421  -0.423  -0.412  -0.389
 3.00   -1.060  -0.951  -0.949  -1.048  -1.031  -0.861
 4.00   -0.779  -0.661  -0.608  -0.628  -0.663  -0.701


e02gafe.r

 E02GAF Example Program Results

 Resid =   0.28E-02  Rank =     3  Iterations =     5  IFAIL =    0

 Solution
     1.0014    2.0035    1.4960


e02gbfe.r

 E02GBF Example Program Results

 Results at iteration     8
 X-values
          0.0000         0.6943        -2.1482         2.1339
 Norm of residuals = 0.95714E-02


e02gcfe.r

 E02GCF Example Program Results

 RESMAX =   0.10E-02  Rank =     3  Iterations =     4  IFAIL =    0

 Solution
     1.0049    2.0149    1.4822


e02jdfe.r

 E02JDF Example Program Results

 Computing the coefficients of a C^1 spline approximation to Franke's function
 Using a  6 by  6 grid
 Using an averaged local approximation

 Values of computed spline at (x_i,y_i):

          x_i         y_i  f(x_i,y_i)
         0.00        0.00        0.76

 Outputting of the function values on the mesh is disabled


e02rafe.r

 E02RAF Example Program Results

 The given series coefficients are
    0.1000E+01   0.1000E+01   0.5000E+00   0.1667E+00   0.4167E-01
    0.8333E-02   0.1389E-02   0.1984E-03   0.2480E-04

 Numerator coefficients
    0.1000E+01   0.5000E+00   0.1071E+00   0.1190E-01   0.5952E-03

 Denominator coefficients
    0.1000E+01  -0.5000E+00   0.1071E+00  -0.1190E-01   0.5952E-03

 Zeros of approximant are at

     Real part    Imag part
   -0.5792E+01   0.1734E+01
   -0.5792E+01  -0.1734E+01
   -0.4208E+01   0.5315E+01
   -0.4208E+01  -0.5315E+01

 Poles of approximant are at

     Real part    Imag part
    0.5792E+01   0.1734E+01
    0.5792E+01  -0.1734E+01
    0.4208E+01   0.5315E+01
    0.4208E+01  -0.5315E+01


e02zafe.r

 E02ZAF Example Program Results

 Panel   1
    0.00   0.77
    0.21   0.44
    0.54   0.04

 Panel   2
    0.70   1.06

 Panel   3
    0.71   1.95

 Panel   4
    1.44   0.33
    1.01   0.50
    1.84   0.02
    1.53   0.18

 Panel   5

 Panel   6
    1.00   1.20


e04abae.r

 E04ABA Example Program Results

 The minimum lies in the interval 4.49340940 to 4.49340951
 Its estimated position is 4.49340945,
 where the function value is -0.2172
 10 function evaluations were required


e04abfe.r

 E04ABF Example Program Results

 The minimum lies in the interval 4.49340940 to 4.49340951
 Its estimated position is 4.49340945,
 where the function value is -0.2172
 10 function evaluations were required


e04bbae.r

 E04BBA Example Program Results

 The minimum lies in the interval 4.49340946 to 4.49340952
 Its estimated position is 4.49340946,
 where the function value is -0.2172
 and the gradient is -3.8E-16 (machine dependent)
  6 calls of FUNCT were required


e04bbfe.r

 E04BBF Example Program Results

 The minimum lies in the interval 4.49340946 to 4.49340952
 Its estimated position is 4.49340946,
 where the function value is -0.2172
 and the gradient is -3.8E-16 (machine dependent)
  6 calls of FUNCT were required


e04cbfe.r

 E04CBF Example Program Results

 The final function value is      0.0000
 at the point      0.5000     -0.9999


e04dgae.r

 E04DGA Example Program Results

 Variable          Value        Gradient value

 Varbl   1      0.5000000          9.1E-07
 Varbl   2     -0.9999999          8.3E-07

 Final objective value =   0.5308300E-13


e04dgfe.r

 E04DGF Example Program Results

 *** E04DGF

 Parameters
 ----------

 Variables..............         2

 Maximum step length....  1.00E+20       EPS (machine precision)  1.11E-16
 Optimality tolerance...  3.26E-12       Linesearch tolerance...  9.00E-01

 Est. opt. function val.      None       Function precision.....  4.37E-15
 Verify level...........         0

 Iteration limit........        50       Print level............        10

 Verification of the objective gradients.
 ----------------------------------------

 The objective gradients seem to be ok.

 Directional derivative of the objective   -1.47151776E-01
 Difference approximation                  -1.47151796E-01

  Itn      Step  Nfun      Objective    Norm G    Norm X   Norm (X(k-1)-X(k))
    0               1   1.839397E+00   8.2E-01   1.4E+00
    1   3.7E-01     3   1.724275E+00   2.8E-01   1.3E+00         3.0E-01
    2   1.6E+01     8   6.083488E-02   9.2E-01   9.3E-01         2.2E+00
    3   1.6E-03    14   5.367978E-02   1.0E+00   9.6E-01         3.7E-02
    4   4.8E-01    16   1.783392E-04   5.8E-02   1.1E+00         1.6E-01
    5   1.0E+00    17   1.671122E-05   2.0E-02   1.1E+00         6.7E-03
    6   1.0E+00    18   1.101991E-07   1.7E-03   1.1E+00         2.4E-03
    7   1.0E+00    19   2.332133E-09   1.8E-04   1.1E+00         1.5E-04
    8   1.0E+00    20   9.130924E-11   3.3E-05   1.1E+00         3.0E-05
    9   1.0E+00    21   1.085455E-12   4.7E-06   1.1E+00         7.0E-06
   10   1.0E+00    22   5.308300E-14   1.2E-06   1.1E+00         6.4E-07

 Exit from E04DGF after    10 iterations.

 Variable          Value      Gradient value
 Varbl    1     0.500000          9.1E-07
 Varbl    2     -1.00000          8.3E-07

 Exit E04DGF - Optimal solution found.

 Final objective value =   0.5308300E-13


e04djae.r

 E04DJA Example Program Results

 Variable          Value        Gradient value

 Varbl   1      0.5000000          9.1E-07
 Varbl   2     -0.9999999          8.3E-07

 Final objective value =   0.5235082E-13


e04djfe.r

 E04DJF Example Program Results

 Calls to E04DKF
 ---------------

       Verify Level = -1
       Maximum Step Length = 100.0

 OPTIONS file
 ------------

      Begin   Example options file for  E04DJF
      Iteration Limit  =  25                  *  (Default =  50)
      Print Level      =   1                  *  (Default =  10)
      End

 *** E04DGF

 Parameters
 ----------

 Variables..............         2

 Maximum step length....  1.00E+02       EPS (machine precision)  1.11E-16
 Optimality tolerance...  3.26E-12       Linesearch tolerance...  9.00E-01

 Est. opt. function val.      None       Function precision.....  4.37E-15
 Verify level...........        -1

 Iteration limit........        25       Print level............         1

 Exit from E04DGF after    10 iterations.

 Variable          Value      Gradient value
 Varbl    1     0.500000          9.1E-07
 Varbl    2     -1.00000          8.3E-07

 Exit E04DGF - Optimal solution found.

 Final objective value =   0.5235082E-13


e04fcfe.r

 E04FCF Example Program Results

 On exit, the sum of squares is      0.0082
 at the point      0.0824      1.1330      2.3437
 The estimated gradient is  -1.607E-09  -7.436E-11   6.130E-10
                            (machine dependent)
 and the residuals are
  -5.9E-03
  -2.7E-04
   2.7E-04
   6.5E-03
  -8.2E-04
  -1.3E-03
  -4.5E-03
  -2.0E-02
   8.2E-02
  -1.8E-02
  -1.5E-02
  -1.5E-02
  -1.1E-02
  -4.2E-03
   6.8E-03


e04fyfe.r

 E04FYF Example Program Results

 On exit, the sum of squares is      0.0082
 at the point      0.0824      1.1330      2.3437


e04gbfe.r

 E04GBF Example Program Results

 On exit, the sum of squares is      0.0082
 at the point      0.0824      1.1330      2.3437
 The corresponding gradient is   1.199E-09  -1.865E-11   1.807E-11
                            (machine dependent)
 and the residuals are
  -5.9E-03
  -2.7E-04
   2.7E-04
   6.5E-03
  -8.2E-04
  -1.3E-03
  -4.5E-03
  -2.0E-02
   8.2E-02
  -1.8E-02
  -1.5E-02
  -1.5E-02
  -1.1E-02
  -4.2E-03
   6.8E-03


e04gdfe.r

 E04GDF Example Program Results

 On exit, the sum of squares is      0.0082
 at the point      0.0824      1.1330      2.3437
 The corresponding gradient is  -6.061E-12   9.031E-11   9.385E-11
                            (machine dependent)
 and the residuals are
  -5.9E-03
  -2.7E-04
   2.7E-04
   6.5E-03
  -8.2E-04
  -1.3E-03
  -4.5E-03
  -2.0E-02
   8.2E-02
  -1.8E-02
  -1.5E-02
  -1.5E-02
  -1.1E-02
  -4.2E-03
   6.8E-03


e04gyfe.r

 E04GYF Example Program Results

 On exit, the sum of squares is      0.0082
 at the point      0.0824      1.1330      2.3437


e04gzfe.r

 E04GZF Example Program Results

 On exit, the sum of squares is      0.0082
 at the point      0.0824      1.1330      2.3437


e04hcfe.r

 E04HCF Example Program Results

 The test point is
     1.4600   -0.8200    0.5700    1.2100

 1st derivatives are consistent with function values

 At the test point, FUNCT gives the function value  6.2273E+01
 and the 1st derivatives
   -1.285E+01  -1.649E+02   5.384E+01   5.775E+00


e04hdfe.r

 E04HDF Example Program Results

 The test point is
    1.4600  -0.8200   0.5700   1.2100

 2nd derivatives are consistent with 1st derivatives

 At the test point, FUNCT gives the function value  6.2273E+01
 and the 1st derivatives
   -1.285E+01  -1.649E+02   5.384E+01   5.775E+00

 H gives the lower triangle of the Hessian matrix
    9.500E+00
    2.000E+01   2.461E+02
    0.000E+00  -9.220E+01   1.944E+02
   -7.500E+00   0.000E+00  -1.000E+01   1.750E+01


e04hefe.r

 E04HEF Example Program Results

 On exit, the sum of squares is      0.0082
 at the point      0.0824      1.1330      2.3437
 The corresponding gradient is  -6.060E-12   9.030E-11   9.385E-11
                            (machine dependent)
 and the residuals are
  -5.9E-03
  -2.7E-04
   2.7E-04
   6.5E-03
  -8.2E-04
  -1.3E-03
  -4.5E-03
  -2.0E-02
   8.2E-02
  -1.8E-02
  -1.5E-02
  -1.5E-02
  -1.1E-02
  -4.2E-03
   6.8E-03


e04hyfe.r

 E04HYF Example Program Results

 On exit, the sum of squares is      0.0082
 at the point      0.0824      1.1330      2.3437


e04jcfe.r

 E04JCF Example Program Results

    Monitoring: new trust region radius =  1.000E-02

    Monitoring: new trust region radius =  1.000E-03

    Monitoring: new trust region radius =  1.000E-04

    Monitoring: new trust region radius =  1.000E-05

    Monitoring: new trust region radius =  1.000E-06

 Successful exit from E04JCF.
 Function value at lowest point found =    2.434E+00
 The corresponding X is:
      0.100E+01   -0.852E-01    0.409E+00    0.100E+01


e04jyfe.r

 E04JYF Example Program Results
 ** It is probable that a local minimum has been found,
 ** but it cannot be guaranteed.
 ** ABNORMAL EXIT from NAG Library routine E04JYF: IFAIL =     5
 ** NAG soft failure - control returned

 Function value on exit is   2.4338
 at the point   1.0000  -0.0852   0.4093   1.0000


e04kdfe.r

 E04KDF Example Program Results
 ** The conditions for a minimum have not all been satisfied,
 ** but a lower point could not be found.
 ** ABNORMAL EXIT from NAG Library routine E04KDF: IFAIL =     3
 ** NAG soft failure - control returned

 Function value on exit is       2.4338
 at the point      1.0000     -0.0852      0.4093      1.0000
 The corresponding (machine dependent) gradient is
                           2.953E-01  -5.870E-10   1.176E-09   5.907E+00
 ISTATE contains   -2    1    2   -2
 and HESD contains  0.2098E+03  0.4738E+02  0.4552E+02  0.0000E+00


e04kyfe.r

 E04KYF Example Program Results

 Function value on exit is    2.4338
 at the point   1.0000  -0.0852   0.4093   1.0000
 The corresponding (machine dependent) gradient is
               0.2953E+00  0.3022E-08 -0.1236E-07  0.5907E+01


e04kzfe.r

 E04KZF Example Program Results
 ** It is probable that a local minimum has been found,
 ** but it cannot be guaranteed.
 ** ABNORMAL EXIT from NAG Library routine E04KZF: IFAIL =     5
 ** NAG soft failure - control returned

 Function value on exit is       2.4338
 at the point      1.0000     -0.0852      0.4093      1.0000
 the corresponding (machine dependent) gradient is
               0.2953E+00 -0.5870E-09  0.1176E-08  0.5907E+01


e04lbfe.r

 E04LBF Example Program Results
 ** The conditions for a minimum have not all been satisfied,
 ** but a lower point could not be found.
 ** ABNORMAL EXIT from NAG Library routine E04LBF: IFAIL =     3
 ** NAG soft failure - control returned

 Function value on exit is    2.4338
 at the point   1.0000  -0.0852   0.4093   1.0000
 The corresponding (machine dependent) gradient is
                          2.953E-01  -5.867E-10   1.173E-09   5.907E+00
 ISTATE contains   -2    1    2   -2
 and HESD contains  0.2098E+03  0.4738E+02


e04lyfe.r

 E04LYF Example Program Results
 ** It is probable that a local minimum has been found,
 ** but it cannot be guaranteed.
 ** ABNORMAL EXIT from NAG Library routine E04LYF: IFAIL =     5
 ** NAG soft failure - control returned

 Function value on exit is    2.4338
 at the point   1.0000  -0.0852   0.4093   1.0000
 The corresponding (machine dependent) gradient is
               0.2953E+00 -0.5867E-09  0.1173E-08  0.5907E+01


e04mfae.r

 E04MFA Example Program Results

 Varbl   Istate    Value         Lagr Mult

 V   1   1        -1.000E-02     3.301E-01
 V   2   1        -1.000E-01     1.438E-02
 V   3   2         3.000E-02    -9.100E-02
 V   4   2         2.000E-02    -7.661E-02
 V   5   0        -6.749E-02     0.000E+00
 V   6   0        -2.280E-03     0.000E+00
 V   7   0        -2.345E-04     0.000E+00

 L Con   Istate    Value         Lagr Mult

 L   1   3        -1.300E-01    -1.431E+00
 L   2   0        -5.480E-03     0.000E+00
 L   3   0        -6.572E-03     0.000E+00
 L   4   0        -4.850E-03     0.000E+00
 L   5   0        -3.875E-03     0.000E+00
 L   6   1        -9.920E-02     1.501E+00
 L   7   1        -3.000E-03     1.517E+00

 Final objective value =       2.360E-02


e04mffe.r

 E04MFF Example Program Results

 Varbl   Istate    Value         Lagr Mult
 V   1   1        -1.000E-02     3.301E-01
 V   2   1        -1.000E-01     1.438E-02
 V   3   2         3.000E-02    -9.100E-02
 V   4   2         2.000E-02    -7.661E-02
 V   5   0        -6.749E-02     0.000E+00
 V   6   0        -2.280E-03     0.000E+00
 V   7   0        -2.345E-04     0.000E+00

 L Con   Istate    Value         Lagr Mult
 L   1   3        -1.300E-01    -1.431E+00
 L   2   0        -5.480E-03     0.000E+00
 L   3   0        -6.572E-03     0.000E+00
 L   4   0        -4.850E-03     0.000E+00
 L   5   0        -3.875E-03     0.000E+00
 L   6   1        -9.920E-02     1.501E+00
 L   7   1        -3.000E-03     1.517E+00

 Final objective value =       2.360E-02


e04mgae.r

 E04MGA Example Program Results

 Varbl   Istate    Value         Lagr Mult

 V   1   1        -1.000E-02     3.301E-01
 V   2   1        -1.000E-01     1.438E-02
 V   3   2         3.000E-02    -9.100E-02
 V   4   2         2.000E-02    -7.661E-02
 V   5   0        -6.749E-02     0.000E+00
 V   6   0        -2.280E-03     0.000E+00
 V   7   0        -2.345E-04     0.000E+00

 L Con   Istate    Value         Lagr Mult

 L   1   3        -1.300E-01    -1.431E+00
 L   2   0        -5.480E-03     0.000E+00
 L   3   0        -6.572E-03     0.000E+00
 L   4   0        -4.850E-03     0.000E+00
 L   5   0        -3.875E-03     0.000E+00
 L   6   1        -9.920E-02     1.501E+00
 L   7   1        -3.000E-03     1.517E+00

 Final objective value =       2.360E-02


e04mgfe.r

 E04MGF Example Program Results

 Calls to E04MHF
 ---------------

      Print Level = 0
       Check Frequency = 10
       Infinite Bound Size = 1.0D+25

 OPTIONS file
 ------------

      Begin   Example options file for  E04MGF
         Crash Tolerance  =  0.05    *  (Default = 0.01)
         Iteration Limit  =  25      *  (Default = 70)
      End

 Varbl   Istate    Value         Lagr Mult
 V   1   1        -1.000E-02     3.301E-01
 V   2   1        -1.000E-01     1.438E-02
 V   3   2         3.000E-02    -9.100E-02
 V   4   2         2.000E-02    -7.661E-02
 V   5   0        -6.749E-02     0.000E+00
 V   6   0        -2.280E-03     0.000E+00
 V   7   0        -2.345E-04     0.000E+00

 L Con   Istate    Value         Lagr Mult
 L   1   3        -1.300E-01    -1.431E+00
 L   2   0        -5.480E-03     0.000E+00
 L   3   0        -6.572E-03     0.000E+00
 L   4   0        -4.850E-03     0.000E+00
 L   5   0        -3.875E-03     0.000E+00
 L   6   1        -9.920E-02     1.501E+00
 L   7   1        -3.000E-03     1.517E+00

 Final objective value =       2.360E-02


e04mwfe.r

E04MWF Example Program Results

QP problem contains   7 variables and   8 linear constraints

Final objective value =  -1.848E+06
Optimal X =      0.00   349.40   648.85   172.85   407.52   271.36   150.02

MPS file was written: e04mwfe.mps


e04mxfe.r

 E04MXF Example Program Results

 MPSX INPUT LISTING
 ------------------
 Searching for indicator line
 Line          1: Found NAME indicator line
                  Query mode - Ignoring NAME data.
 Line          2: Found ROWS indicator line
                  Query mode - Counting ROWS data.
 Line          7: Found COLUMNS indicator line
                  Query mode - Counting COLUMNS data.
 Line         26: Found RHS indicator line
                  Query mode - Ignoring RHS data.
 Line         31: Found RANGES indicator line
                  Query mode - Ignoring RANGES data.
 Line         35: Found BOUNDS indicator line
                  Query mode - Counting BOUNDS data.
 Line         54: Found QUADOBJ indicator line
                  Query mode - Counting QUADOBJ data.
                  Query mode - End of QUADOBJ data. Exit

 MPSX INPUT LISTING
 ------------------
 Searching for indicator line
 Line          1: Found NAME indicator line
 Line          2: Found ROWS indicator line
 Line          7: Found COLUMNS indicator line
 Line         26: Found RHS indicator line
 Line         31: Found RANGES indicator line
 Line         35: Found BOUNDS indicator line
 Line         54: Found QUADOBJ indicator line
 Line         64: Found ENDATA indicator line

 Parameters
 ==========

 Files
 -----
 Solution file..........         0       Old basis file ........         0       (Print file)...........         6
 Insert file............         0       New basis file ........         0       (Summary file).........         0
 Punch file.............         0       Backup basis file......         0
 Load file..............         0       Dump file..............         0

 Frequencies
 -----------
 Print frequency........       100       Check frequency........        60       Save new basis map.....       100
 Summary frequency......       100       Factorization frequency        50       Expand frequency.......     10000

 LP/QP Parameters
 ----------------
 Minimize...............                 QPsolver Cholesky......                 Cold start.............
 Scale tolerance........     0.900       Feasibility tolerance..  1.00E-06       Iteration limit........     10000
 Scale option...........         2       Optimality tolerance...  1.00E-06       Print level............         1
 Crash tolerance........     0.100       Pivot tolerance........  2.04E-11       Partial price..........         1
 Crash option...........         3       Elastic weight.........  1.00E+00       Prtl price section ( A)         9
 Elastic mode...........         1       Elastic objective......         1       Prtl price section (-I)         4

 QP objective
 ------------
 Objective variables....         5       Hessian columns........         5       Superbasics limit......         6
 Nonlin Objective vars..         5       Unbounded step size....  1.00E+20
 Linear Objective vars..         0

 Miscellaneous
 -------------
 LU factor tolerance....      3.99       LU singularity tol.....  2.04E-11       Timing level...........         0
 LU update tolerance....      3.99       LU swap tolerance......  1.03E-04       Debug level............         0
 LU partial  pivoting...                 eps (machine precision)  1.11E-16       System information.....        No

 Matrix statistics
 -----------------
               Total      Normal        Free       Fixed     Bounded
 Rows              4           0           1           0           3
 Columns           9           0           0           0           9

 No. of matrix elements                   36     Density     100.000
 Biggest                          4.0000E+00  (excluding fixed columns,
 Smallest                         1.0000E+00   free rows, and RHS)

 No. of objective coefficients             9
 Biggest                          4.0000E+00  (excluding fixed columns)
 Smallest                         1.0000E-01

 Nonlinear constraints       0     Linear constraints       4
 Nonlinear variables         5     Linear variables         4
 Jacobian  variables         0     Objective variables      5
 Total constraints           4     Total variables          9

 Itn      0: Feasible linear constraints

 E04NQT EXIT   0 -- finished successfully
 E04NQT INFO   1 -- optimality conditions satisfied

 Problem name                 E04MX.EX
 No. of iterations                  11   Objective value     -8.0677777778E+00
 No. of Hessian products            25   Objective row       -1.0785555556E+01
                                         Quadratic objective  2.7177777778E+00
 No. of superbasics                  4   No. of basic nonlinears             2
 No. of degenerate steps             2   Percentage                      18.18
 Max x       (scaled)        1 1.3E+00   Max pi      (scaled)        4 1.0E+00
 Max x                       1 2.0E+00   Max pi                      4 1.0E+00
 Max Prim inf(scaled)        0 0.0E+00   Max Dual inf(scaled)        0 0.0E+00
 Max Primal infeas           0 0.0E+00   Max Dual infeas             0 0.0E+00

 Name           E04MX.EX                 Objective Value     -8.0677777778E+00

 Status         Optimal Soln             Iteration     11    Superbasics     4

 Section 1 - Rows

  Number  ...Row.. State  ...Activity...  Slack Activity  ..Lower Limit.  ..Upper Limit.  .Dual Activity    ..i

      10  ..ROW1..    UL         1.50000          .             -2.00000         1.50000        -0.06667      1
      11  ..ROW2..    UL         1.50000          .             -2.00000         1.50000        -0.03333      2
      12  ..ROW3..   SBS         3.93333        -0.06667        -2.00000         4.00000          .           3
      13  ..COST..    BS       -10.78556       -10.78556           None            None         -1.0          4

 Section 2 - Columns

  Number  .Column. State  ...Activity...  .Obj Gradient.  ..Lower Limit.  ..Upper Limit.  Reduced Gradnt    m+j

       1  ...X1...    UL         2.00000        -0.90000        -2.00000         2.00000        -0.80000      5
       2  ...X2...   SBS        -0.23333        -0.13333        -2.00000         2.00000          .           6
       3  ...X3...    BS        -0.26667        -0.16667        -2.00000         2.00000          .           7
       4  ...X4...    BS        -0.30000        -0.20000        -2.00000         2.00000          .           8
       5  ...X5...   SBS        -0.10000          .             -2.00000         2.00000          .           9
       6  ...X6...    UL         2.00000        -1.0            -2.00000         2.00000        -0.90000     10
       7  ...X7...    UL         2.00000        -1.0            -2.00000         2.00000        -0.90000     11
       8  ...X8...   SBS        -1.77778        -0.10000        -2.00000         2.00000          .          12
       9  ...X9...    BS        -0.45556        -0.30000        -2.00000         2.00000          .          13


e04mzfe.r

 E04MZF Example Program Results

 Reading MPSX file:
 MPSX file contains   9 variables and   4 linear constraints

 Solving QP problem:
 Optimal objective value:  -8.068E+00
 Optimal X:
   X( 1) =    2.0000
   X( 2) =   -0.2333
   X( 3) =   -0.2667
   X( 4) =   -0.3000
   X( 5) =   -0.1000
   X( 6) =    2.0000
   X( 7) =    2.0000
   X( 8) =   -1.7778
   X( 9) =   -0.4556


e04ncae.r

 E04NCA Example Program Results

 Varbl   Istate    Value         Lagr Mult
 V   1   1         0.000E+00     1.572E-01
 V   2   0         4.153E-02     0.000E+00
 V   3   0         5.872E-01     0.000E+00
 V   4   1         0.000E+00     8.782E-01
 V   5   0         9.964E-02     0.000E+00
 V   6   1         0.000E+00     1.473E-01
 V   7   0         4.906E-02     0.000E+00
 V   8   1         0.000E+00     8.603E-01
 V   9   0         3.056E-01     0.000E+00

 L Con   Istate    Value         Lagr Mult
 L   1   1         2.000E+00     3.777E-01
 L   2   2         2.000E+00    -5.791E-02
 L   3   1         1.000E+00     1.075E-01

 Final objective value =       8.134E-02


e04ncfe.r

 E04NCF Example Program Results

 Varbl   Istate    Value         Lagr Mult
 V   1   1         0.000E+00     1.572E-01
 V   2   0         4.153E-02     0.000E+00
 V   3   0         5.872E-01     0.000E+00
 V   4   1         0.000E+00     8.782E-01
 V   5   0         9.964E-02     0.000E+00
 V   6   1         0.000E+00     1.473E-01
 V   7   0         4.906E-02     0.000E+00
 V   8   1         0.000E+00     8.603E-01
 V   9   0         3.056E-01     0.000E+00

 L Con   Istate    Value         Lagr Mult
 L   1   1         2.000E+00     3.777E-01
 L   2   2         2.000E+00    -5.791E-02
 L   3   1         1.000E+00     1.075E-01

 Final objective value =       8.134E-02


e04ndae.r

 E04NDA Example Program Results

 Varbl  Istate   Value         Lagr Mult

 V   1   2       2.00000       -0.8000
 V   2   0     -0.233333         0.000
 V   3   0     -0.266667         0.000
 V   4   0     -0.300000         0.000
 V   5   0     -0.100000         0.000
 V   6   2       2.00000       -0.9000
 V   7   2       2.00000       -0.9000
 V   8   0      -1.77778         0.000
 V   9   0     -0.455556         0.000

 L Con  Istate   Value         Lagr Mult

 L   1   2       1.50000       -6.6667E-02
 L   2   2       1.50000       -3.3333E-02
 L   3   0       3.93333         0.000

 Final objective value =   -8.067778


e04ndfe.r

 E04NDF Example Program Results

 Calls to E04NEF
 ---------------

       Problem Type = QP2

 OPTIONS file
 ------------

      Begin   Example options file for  E04NDF
         Iteration Limit   =  30      *  (Default =  90)
      End

 *** E04NCF

 Parameters
 ----------

 Problem type...........       QP2       Hessian................        NO

 Linear constraints.....         3       Feasibility tolerance..  1.05E-08
 Variables..............         9       Crash tolerance........  1.00E-02
 Objective matrix rows..         9       Rank tolerance.........  1.05E-07

 Infinite bound size....  1.00E+20       COLD start.............
 Infinite step size.....  1.00E+20       EPS (machine precision)  1.11E-16

 Print level............        10       Feasibility phase itns.        60
 Monitoring file........        -1       Optimality  phase itns.        30

 Workspace provided is     IWORK(       9),  WORK(     270).
 To solve problem we need  IWORK(       9),  WORK(     270).

 Rank of the objective function data matrix =     5

 Itn     Step Ninf Sinf/Objective  Norm Gz
   0  0.0E+00    0   0.000000E+00  4.5E+00
   1  7.5E-01    0  -4.375000E+00  5.0E-01
   2  1.0E+00    0  -4.400000E+00  2.8E-17
   3  3.0E-01    0  -4.700000E+00  8.9E-01
   4  1.0E+00    0  -5.100000E+00  2.4E-17
   5  5.4E-01    0  -6.055714E+00  1.7E+00
   6  1.1E-02    0  -6.113326E+00  1.6E+00
   7  1.1E-01    0  -6.215049E+00  1.2E+00
   8  1.0E+00    0  -6.538008E+00  1.8E-17
   9  6.5E-01    0  -7.428704E+00  7.2E-02
  10  1.0E+00    0  -7.429717E+00  1.8E-17
  11  1.0E+00    0  -8.067718E+00  1.8E-17
  12  1.0E+00    0  -8.067778E+00  1.8E-17

 Exit from QP problem after    12 iterations.

 Varbl State     Value       Lower Bound   Upper Bound    Lagr Mult   Slack

 V   1    UL    2.00000      -2.00000       2.00000     -0.8000         .
 V   2    FR  -0.233333      -2.00000       2.00000           .       1.767
 V   3    FR  -0.266667      -2.00000       2.00000           .       1.733
 V   4    FR  -0.300000      -2.00000       2.00000           .       1.700
 V   5    FR  -0.100000      -2.00000       2.00000           .       1.900
 V   6    UL    2.00000      -2.00000       2.00000     -0.9000         .
 V   7    UL    2.00000      -2.00000       2.00000     -0.9000         .
 V   8    FR   -1.77778      -2.00000       2.00000           .      0.2222
 V   9    FR  -0.455556      -2.00000       2.00000           .       1.544

 L Con State     Value       Lower Bound   Upper Bound    Lagr Mult   Slack

 L   1    UL    1.50000      -2.00000       1.50000     -6.6667E-02  1.1102E-15
 L   2    UL    1.50000      -2.00000       1.50000     -3.3333E-02 -4.4409E-16
 L   3    FR    3.93333      -2.00000       4.00000           .      6.6667E-02

 Exit E04NCF - Optimal QP solution.

 Final QP objective value =   -8.067778


e04nfae.r

 E04NFA Example Program Results

 Varbl  Istate   Value         Lagr Mult

 V   1   1     -1.000000E-02    0.4700
 V   2   0     -6.986465E-02     0.000
 V   3   0      1.825915E-02     0.000
 V   4   0     -2.426081E-02     0.000
 V   5   0     -6.200564E-02     0.000
 V   6   0      1.380544E-02     0.000
 V   7   0      4.066496E-03     0.000

 L Con  Istate   Value         Lagr Mult

 L   1   3     -0.130000        -1.908
 L   2   0     -5.879898E-03     0.000
 L   3   2     -6.400000E-03   -0.3144
 L   4   0     -4.537323E-03     0.000
 L   5   0     -2.915996E-03     0.000
 L   6   1     -9.920000E-02     1.955
 L   7   1     -3.000000E-03     1.972

 Final objective value =   0.3703165E-01

 Exit from problem after      7 iterations.


e04nffe.r

 E04NFF Example Program Results

 *** E04NFF

 Parameters
 ----------

 Problem type...........       QP2

 Linear constraints.....         7       Feasibility tolerance..  1.05E-08
 Variables..............         7       Optimality tolerance...  1.05E-08
 Hessian rows...........         7       Rank tolerance.........  1.11E-14

 Infinite bound size....  1.00E+20       COLD start.............
 Infinite step size.....  1.00E+20       EPS (machine precision)  1.11E-16

 Check frequency........        50       Expand frequency.......         5
 Minimum sum of infeas..        NO       Crash tolerance........  1.00E-02

 Max degrees of freedom.         7       Print level............        10
 Feasibility phase itns.        70       Monitoring file........        -1
 Optimality  phase itns.        70

 Workspace provided is     IWORK(      17),  WORK(     189).
 To solve problem we need  IWORK(      17),  WORK(     189).

  Itn     Step Ninf Sinf/Objective  Norm Gz
    0  0.0E+00    3   1.038000E-01  0.0E+00
    1  4.1E-02    1   3.000000E-02  0.0E+00
    2  4.2E-02    0   0.000000E+00  0.0E+00
 Itn     2 -- Feasible point found.
    2  0.0E+00    0   4.580000E-02  0.0E+00
    3  1.3E-01    0   4.161596E-02  0.0E+00
    4  1.0E+00    0   3.936227E-02  4.2E-17
    5  4.1E-01    0   3.758935E-02  1.2E-02
    6  1.0E+00    0   3.755377E-02  2.4E-17
    7  1.0E+00    0   3.703165E-02  4.2E-17

 Varbl State     Value       Lower Bound   Upper Bound    Lagr Mult   Slack

 V   1    LL  -1.000000E-02 -1.000000E-02  1.000000E-02  0.4700         .
 V   2    FR  -6.986465E-02 -0.100000      0.150000           .      3.0135E-02
 V   3    FR   1.825915E-02 -1.000000E-02  3.000000E-02       .      1.1741E-02
 V   4    FR  -2.426081E-02 -4.000000E-02  2.000000E-02       .      1.5739E-02
 V   5    FR  -6.200564E-02 -0.100000      5.000000E-02       .      3.7994E-02
 V   6    FR   1.380544E-02 -1.000000E-02      None           .      2.3805E-02
 V   7    FR   4.066496E-03 -1.000000E-02      None           .      1.4066E-02

 L Con State     Value       Lower Bound   Upper Bound    Lagr Mult   Slack

 L   1    EQ  -0.130000     -0.130000     -0.130000      -1.908         .
 L   2    FR  -5.879898E-03      None     -4.900000E-03       .      9.7990E-04
 L   3    UL  -6.400000E-03      None     -6.400000E-03 -0.3144      8.6736E-19
 L   4    FR  -4.537323E-03      None     -3.700000E-03       .      8.3732E-04
 L   5    FR  -2.915996E-03      None     -1.200000E-03       .      1.7160E-03
 L   6    LL  -9.920000E-02 -9.920000E-02      None       1.955      1.3878E-17
 L   7    LL  -3.000000E-03 -3.000000E-03  2.000000E-03   1.972      8.6736E-19

 Exit E04NFF - Optimal QP solution.

 Final QP objective value =   0.3703165E-01

 Exit from QP problem after     7 iterations.


e04ngae.r

 E04NGA Example Program Results

 Varbl  Istate   Value         Lagr Mult

 V   1   1     -1.000000E-02    0.4700
 V   2   0     -6.986465E-02     0.000
 V   3   0      1.825915E-02     0.000
 V   4   0     -2.426081E-02     0.000
 V   5   0     -6.200564E-02     0.000
 V   6   0      1.380544E-02     0.000
 V   7   0      4.066496E-03     0.000

 L Con  Istate   Value         Lagr Mult

 L   1   3     -0.130000        -1.908
 L   2   0     -5.879898E-03     0.000
 L   3   2     -6.400000E-03   -0.3144
 L   4   0     -4.537323E-03     0.000
 L   5   0     -2.915996E-03     0.000
 L   6   1     -9.920000E-02     1.955
 L   7   1     -3.000000E-03     1.972

 Final objective value =   0.3703165E-01

 Exit from problem after      8 iterations.


e04ngfe.r

 E04NGF Example Program Results

 Calls to E04NHF
 ---------------

       Print Level = 1
       Check Frequency = 10
       Crash Tolerance = 0.05
       Infinite Bound Size = 1.0D+25

 OPTIONS file
 ------------

      Begin   Example options file for  E04NGF
         Feasibility Phase Iteration Limit  =   5    *  (Default = 70)
         Optimality  Phase Iteration Limit  =  10    *  (Default = 70)
      End

 *** E04NFF

 Parameters
 ----------

 Problem type...........       QP2

 Linear constraints.....         7       Feasibility tolerance..  1.05E-08
 Variables..............         7       Optimality tolerance...  1.05E-08
 Hessian rows...........         7       Rank tolerance.........  1.11E-14

 Infinite bound size....  1.00E+25       COLD start.............
 Infinite step size.....  1.00E+25       EPS (machine precision)  1.11E-16

 Check frequency........        10       Expand frequency.......         5
 Minimum sum of infeas..        NO       Crash tolerance........  5.00E-02

 Max degrees of freedom.         7       Print level............         1
 Feasibility phase itns.         5       Monitoring file........        -1
 Optimality  phase itns.        10

 Workspace provided is     IWORK(      17),  WORK(     189).
 To solve problem we need  IWORK(      17),  WORK(     189).

 Varbl State     Value       Lower Bound   Upper Bound    Lagr Mult   Slack

 V   1    LL  -1.000000E-02 -1.000000E-02  1.000000E-02  0.4700         .
 V   2    FR  -6.986465E-02 -0.100000      0.150000           .      3.0135E-02
 V   3    FR   1.825915E-02 -1.000000E-02  3.000000E-02       .      1.1741E-02
 V   4    FR  -2.426081E-02 -4.000000E-02  2.000000E-02       .      1.5739E-02
 V   5    FR  -6.200564E-02 -0.100000      5.000000E-02       .      3.7994E-02
 V   6    FR   1.380544E-02 -1.000000E-02      None           .      2.3805E-02
 V   7    FR   4.066496E-03 -1.000000E-02      None           .      1.4066E-02

 L Con State     Value       Lower Bound   Upper Bound    Lagr Mult   Slack

 L   1    EQ  -0.130000     -0.130000     -0.130000      -1.908         .
 L   2    FR  -5.879898E-03      None     -4.900000E-03       .      9.7990E-04
 L   3    UL  -6.400000E-03      None     -6.400000E-03 -0.3144     -2.6021E-18
 L   4    FR  -4.537323E-03      None     -3.700000E-03       .      8.3732E-04
 L   5    FR  -2.915996E-03      None     -1.200000E-03       .      1.7160E-03
 L   6    LL  -9.920000E-02 -9.920000E-02      None       1.955      4.1633E-17
 L   7    LL  -3.000000E-03 -3.000000E-03  2.000000E-03   1.972      1.7347E-18

 Exit E04NFF - Optimal QP solution.

 Final QP objective value =   0.3703165E-01

 Exit from QP problem after     8 iterations.


e04nkae.r

 E04NKA Example Program Results

 Variable  Istate     Value         Lagr Mult

  ...X1...   0       0.00000         2361.
  ...X2...   3       349.399       -3.6566E-12
  ...X3...   2       648.853       -5.9240E-12
  ...X4...   2       172.847        1.9491E-12
  ...X5...   3       407.521         0.000
  ...X6...   3       271.356       -3.2802E-12
  ...X7...   3       150.023       -1.4130E-12

 Constrnt  Istate     Value         Lagr Mult

  ..ROW1..   0       2000.00       -1.2901E+04
  ..ROW2..   3       49.2316         0.000
  ..ROW3..   1       100.000        -2325.
  ..ROW4..   3       32.0719         0.000
  ..ROW5..   3       14.5572         0.000
  ..ROW6..   0       1500.00        1.4455E+04
  ..ROW7..   0       250.000        1.4581E+04
  ..COST..   3     -2.988690E+06    -1.000

 Final objective value =   -1847785.


e04nkfe.r

 E04NKF Example Program Results

 Workspace provided is                 IZ(       1),  Z(       1).
 To start solving the problem we need  IZ(     428),  Z(     358).

 Exit E04NKF - Not enough integer workspace to start solving the problem.

 *** E04NKF

 Parameters
 ----------

 Frequencies.
 Check frequency.........        60       Expand frequency........     10000
 Factorization frequency.       100

 LP Parameters.
 Scale tolerance.........  9.00E-01       Feasibility tolerance...  1.00E-06
 Iteration limit.........        75       Scale option............         2
 Optimality tolerance....  1.00E-06       Partial price...........        10
 Crash tolerance.........  1.00E-01       Pivot tolerance.........  2.04E-11
 Crash option............         2

 QP objective.
 Objective variables.....         7       Hessian columns.........         7
 Superbasics limit.......         7

 Miscellaneous.
 Variables...............         7       Linear constraints......         8
 LU factor tolerance.....  1.00E+02       LU update tolerance.....  1.00E+01
 LU singularity tolerance  2.04E-11       Monitoring file.........        -1
 EPS (machine precision).  1.11E-16       Print level.............        10
 Infinite bound size.....  1.00E+20       Infinite step size......  1.00E+20
 COLD start..............                 MINIMIZE................

 Workspace provided is                 IZ(     428),  Z(     358).
 To start solving the problem we need  IZ(     428),  Z(     358).

   Itn     Step  Ninf  Sinf/Objective  Norm rg
 Itn      0 -- Infeasible.
     0  0.0E+00     1    1.152891E+03  0.0E+00
     1  4.3E+02     0    0.000000E+00  0.0E+00
 Itn      1 -- Feasible point found (for      1 equality constraints).
     1  0.0E+00     0    0.000000E+00  0.0E+00
     1  0.0E+00     0    1.460000E+06  0.0E+00
 Itn      1 -- Feasible QP solution.
     2  8.7E-02     0    9.409959E+05  0.0E+00
     3  5.3E-01     0   -1.056552E+06  0.0E+00
     4  1.0E+00     0   -1.462190E+06  0.0E+00
     5  1.0E+00     0   -1.698092E+06  1.8E-12
     6  4.6E-02     0   -1.764906E+06  7.0E+02
     7  1.0E+00     0   -1.811946E+06  1.4E-12
     8  1.7E-02     0   -1.847325E+06  1.7E+02
     9  1.0E+00     0   -1.847785E+06  9.1E-13

 Variable State     Value       Lower Bound  Upper Bound   Lagr Mult  Residual

 ...X1...    LL    0.00000           .        200.00       2361.         .
 ...X2...    BS    349.399           .        2500.0     -1.2975E-12   349.4
 ...X3...   SBS    648.853       400.00       800.00     -5.7329E-13   151.1
 ...X4...   SBS    172.847       100.00       700.00      6.4970E-13   72.85
 ...X5...    BS    407.521           .        1500.0      9.1881E-13   407.5
 ...X6...    BS    271.356           .           None    -1.1928E-12   271.4
 ...X7...    BS    150.023           .           None    -1.4130E-12   150.0

 Constrnt State     Value       Lower Bound  Upper Bound   Lagr Mult  Residual

 ..ROW1..    EQ    2000.00       2000.0       2000.0     -1.2901E+04     .
 ..ROW2..    BS    49.2316          None      60.000           .      -10.77
 ..ROW3..    UL    100.000          None      100.00      -2325.         .
 ..ROW4..    BS    32.0719          None      40.000           .      -7.928
 ..ROW5..    BS    14.5572          None      30.000           .      -15.44
 ..ROW6..    LL    1500.00       1500.0          None     1.4455E+04     .
 ..ROW7..    LL    250.000       250.00       300.00      1.4581E+04     .
 ..COST..    BS  -2.988690E+06      None         None     -1.000     -2.9887E+06

 Exit E04NKF - Optimal QP solution found.

 Final QP objective value =    -1847785.

 Exit from QP problem after       9 iterations.


e04nlae.r

 E04NLA Example Program Results

 This is the E04NLA example.   NCOLH =   7.

 Finished the E04NLA example.

 Variable  Istate     Value         Lagr Mult

  ...X1...   0       0.00000         2361.
  ...X2...   3       349.399       -3.6566E-12
  ...X3...   2       648.853       -5.9240E-12
  ...X4...   2       172.847        1.9491E-12
  ...X5...   3       407.521         0.000
  ...X6...   3       271.356       -3.2802E-12
  ...X7...   3       150.023       -1.4130E-12

 Constrnt  Istate     Value         Lagr Mult

  ..ROW1..   0       2000.00       -1.2901E+04
  ..ROW2..   3       49.2316         0.000
  ..ROW3..   1       100.000        -2325.
  ..ROW4..   3       32.0719         0.000
  ..ROW5..   3       14.5572         0.000
  ..ROW6..   0       1500.00        1.4455E+04
  ..ROW7..   0       250.000        1.4581E+04
  ..COST..   3     -2.988690E+06    -1.000

 Final objective value =   -1847785.


e04nlfe.r

 E04NLF Example Program Results

 Calls to E04NMF
 ---------------

       Check Frequency = 10
       Crash Tolerance = 0.05
       Infinite Bound Size = 1.0E+25

 OPTIONS file
 ------------

      Begin * Example options file for E04NLF
         Iteration Limit = 25  * (Default = 75)
             Print Level =  1  * (Default = 10)
      End

 Workspace provided is                 IZ(       1),  Z(       1).
 To start solving the problem we need  IZ(     428),  Z(     358).

 Exit E04NKF - Not enough integer workspace to start solving the problem.

 *** E04NKF

 Parameters
 ----------

 Frequencies.
 Check frequency.........        10       Expand frequency........     10000
 Factorization frequency.       100

 LP Parameters.
 Scale tolerance.........  9.00E-01       Feasibility tolerance...  1.00E-06
 Iteration limit.........        25       Scale option............         2
 Optimality tolerance....  1.00E-06       Partial price...........        10
 Crash tolerance.........  5.00E-02       Pivot tolerance.........  2.04E-11
 Crash option............         2

 QP objective.
 Objective variables.....         7       Hessian columns.........         7
 Superbasics limit.......         7

 Miscellaneous.
 Variables...............         7       Linear constraints......         8
 LU factor tolerance.....  1.00E+02       LU update tolerance.....  1.00E+01
 LU singularity tolerance  2.04E-11       Monitoring file.........        -1
 EPS (machine precision).  1.11E-16       Print level.............         1
 Infinite bound size.....  1.00E+25       Infinite step size......  1.00E+25
 COLD start..............                 MINIMIZE................

 Workspace provided is                 IZ(     428),  Z(     358).
 To start solving the problem we need  IZ(     428),  Z(     358).

 This is the E04NLF example.   NCOLH =   7.

 Variable State     Value       Lower Bound  Upper Bound   Lagr Mult  Residual

 ...X1...    LL    0.00000           .        200.00       2361.         .
 ...X2...    BS    349.399           .        2500.0     -1.2975E-12   349.4
 ...X3...   SBS    648.853       400.00       800.00     -5.7329E-13   151.1
 ...X4...   SBS    172.847       100.00       700.00      6.4970E-13   72.85
 ...X5...    BS    407.521           .        1500.0      9.1881E-13   407.5
 ...X6...    BS    271.356           .           None    -1.1928E-12   271.4
 ...X7...    BS    150.023           .           None    -1.4130E-12   150.0

 Constrnt State     Value       Lower Bound  Upper Bound   Lagr Mult  Residual

 ..ROW1..    EQ    2000.00       2000.0       2000.0     -1.2901E+04     .
 ..ROW2..    BS    49.2316          None      60.000           .      -10.77
 ..ROW3..    UL    100.000          None      100.00      -2325.         .
 ..ROW4..    BS    32.0719          None      40.000           .      -7.928
 ..ROW5..    BS    14.5572          None      30.000           .      -15.44
 ..ROW6..    LL    1500.00       1500.0          None     1.4455E+04     .
 ..ROW7..    LL    250.000       250.00       300.00      1.4581E+04     .
 ..COST..    BS  -2.988690E+06      None         None     -1.000     -2.9887E+06

 Finished the E04NLF example.

 Exit E04NKF - Optimal QP solution found.

 Final QP objective value =    -1847785.

 Exit from QP problem after      10 iterations.


e04nqfe.r

 E04NQF Example Program Results

 QP problem contains   7 variables and   8 linear constraints

 Final objective value =  -1.848E+06
 Optimal X =      0.00   349.40   648.85   172.85   407.52   271.36   150.02


e04nrfe.r

 E04NRF Example Program Results

 QP problem contains   7 variables and   8 linear constraints

 Option 'Elastic mode' has the value   1.
 Option 'Feasibility tolerance' has the value   1.000E-04.

 Final objective value =  -1.848E+06
 Optimal X =      0.00   349.40   648.85   172.85   407.52   271.36   150.02


e04pcfe.r

 E04PCF Example Program Results

 Solution vector
    1.8133   1.0000   5.0000   4.3467

 Dual Solution
    0.0000  -2.7200   2.7200   0.0000

 Residual    3.4246


e04rdfe.r

 E04RDF Example Program Results

 Reading SDPA file: e04rdfe.opt
 ** At least one of MAXNVAR, MAXNBLK or MAXNNZ is too small.
 ** MAXNVAR should be at least                    2, was                    0.
 ** MAXNBLK should be at least                    3, was                    0.
 ** MAXNNZ should be at least                   10, was                    0.
 ** ABNORMAL EXIT from NAG Library routine E04RDF: IFAIL =     1
 ** NAG soft failure - control returned
 Allocating space for the problem.
      NVAR =       2
      NBLK =       3
      NNZ  =      10
 Linear SDP problem was read, start formulating the problem
 The problem formulation in a handle is completed.

 Overview
   Status:                  Problem and option settings are editable.
   No of variables:         2
   Objective function:      linear
   Simple bounds:           not defined yet
   Linear constraints:      not defined yet
   Nonlinear constraints:   not defined yet
   Matrix constraints:      3
 E04SV, NLP-SDP Solver (Pennon)
 ------------------------------
 Number of variables             2                 [eliminated            0]
                            simple  linear  nonlin
 (Standard) inequalities         0       2       0
 (Standard) equalities                   0       0
 Matrix inequalities                     1       0 [dense    1, sparse    0]
                                                   [max dimension         2]

 Begin of Options
     Outer Iteration Limit         =                 100     * d
     Inner Iteration Limit         =                 100     * d
     Infinite Bound Size           =         1.00000E+20     * d
     Initial X                     =           Automatic     * U
     Initial U                     =           Automatic     * d
     Initial P                     =           Automatic     * d
     Hessian Density               =               Dense     * S
     Init Value P                  =         1.00000E+00     * d
     Init Value Pmat               =         1.00000E+00     * d
     Presolve Block Detect         =                 Yes     * d
     Print File                    =                   6     * d
     Print Level                   =                   2     * d
     Print Options                 =                 Yes     * d
     Monitoring File               =                  -1     * d
     Monitoring Level              =                   4     * d
     Monitor Frequency             =                   0     * d
     Stats Time                    =                  No     * d
     P Min                         =         1.05367E-08     * d
     Pmat Min                      =         1.05367E-08     * d
     U Update Restriction          =         5.00000E-01     * d
     Umat Update Restriction       =         3.00000E-01     * d
     Preference                    =               Speed     * d
     Transform Constraints         =                  No     * S
     Dimacs Measures               =               Check     * U
     Stop Criteria                 =                Soft     * d
     Stop Tolerance 1              =         1.00000E-06     * d
     Stop Tolerance 2              =         1.00000E-07     * d
     Stop Tolerance Feasibility    =         1.00000E-07     * d
     Linesearch Mode               =            Fullstep     * S
     Inner Stop Tolerance          =         1.00000E-02     * d
     Inner Stop Criteria           =           Heuristic     * d
     Task                          =            Minimize     * d
     P Update Speed                =                  12     * d
 End of Options
 --------------------------------------------------------------
  it|  objective |  optim  |   feas  |  compl  | pen min |inner
 --------------------------------------------------------------
   0  0.00000E+00  4.06E+01  4.00E+00  3.16E+01  1.00E+00   0
   1  4.02661E+01  1.07E-01  2.78E-01  1.52E+01  1.00E+00   5
   2  2.90783E+01  6.52E-02  9.77E-02  2.78E+00  4.65E-01   5
   3  2.84228E+01  1.67E-01  2.39E-01  7.76E-01  2.16E-01   2
   4  2.97263E+01  3.98E-02  4.39E-02  2.05E-01  1.01E-01   3
   5  2.99618E+01  5.01E-02  6.40E-03  3.32E-02  4.68E-02   2
   6  2.99934E+01  1.45E-01  1.25E-03  6.23E-03  2.18E-02   1
   7  2.99999E+01  3.31E-02  1.28E-05  4.16E-04  1.01E-02   1
   8  3.00001E+01  9.97E-05  3.01E-07  9.67E-05  4.71E-03   1
   9  3.00000E+01  1.37E-04  3.25E-08  2.25E-05  2.19E-03   1
  10  3.00000E+01  1.16E-05  3.52E-09  5.23E-06  1.02E-03   1
  11  3.00000E+01  1.13E-06  3.81E-10  1.22E-06  4.74E-04   1
 --------------------------------------------------------------
 Status: converged, an optimal solution found
 --------------------------------------------------------------
 Final objective value                3.000000E+01
 Relative precision                   3.941484E-08
 Optimality                           1.133096E-06
 Feasibility                          3.806810E-10
 Complementarity                      1.216064E-06
 DIMACS error 1                       5.395697E-08
 DIMACS error 2                       0.000000E+00
 DIMACS error 3                       0.000000E+00
 DIMACS error 4                       7.613621E-11
 DIMACS error 5                       4.324629E-09
 DIMACS error 6                       2.296238E-08
 Iteration counts
   Outer iterations                             11
   Inner iterations                             23
   Linesearch steps                             50
 Evaluation counts
   Augm. Lagr. values                           35
   Augm. Lagr. gradient                         35
   Augm. Lagr. hessian                          23
 --------------------------------------------------------------

 Optimal solution:
 X =      1.00     1.00
 Lagrangian multiplier for A_1
             1
 1     10.0000
 Lagrangian multiplier for A_2
               1
 1    2.4321E-06
 Lagrangian multiplier for A_3
             1          2
 1      2.8571
 2     -2.8571     2.8571


e04rffe.r

 E04RFF Example Program Results

 E04SV, NLP-SDP Solver (Pennon)
 ------------------------------
 Number of variables             3                 [eliminated            0]
                            simple  linear  nonlin
 (Standard) inequalities         0       0       0
 (Standard) equalities                   0       0
 Matrix inequalities                     1       0 [dense    1, sparse    0]
                                                   [max dimension         4]

 --------------------------------------------------------------
  it|  objective |  optim  |   feas  |  compl  | pen min |inner
 --------------------------------------------------------------
   0  0.00000E+00  0.00E+00  6.19E-01  6.63E+00  1.00E+00   0
   1  4.12017E-01  6.38E-04  0.00E+00  1.44E+00  1.00E+00   5
   2  3.29642E-01  7.76E-04  0.00E+00  4.96E-01  4.65E-01   2
   3  2.65315E-01  1.02E-04  0.00E+00  1.55E-01  2.16E-01   3
   4  2.33229E-01  1.03E-03  0.00E+00  4.71E-02  1.01E-01   3
   5  2.19082E-01  2.22E-03  0.00E+00  1.46E-02  4.68E-02   3
   6  2.13121E-01  2.12E-03  0.00E+00  4.72E-03  2.18E-02   3
   7  2.10698E-01  1.26E-03  0.00E+00  1.56E-03  1.01E-02   3
   8  2.09756E-01  4.90E-04  0.00E+00  4.85E-04  4.71E-03   3
   9  2.09413E-01  1.13E-04  0.00E+00  1.21E-04  2.19E-03   3
  10  2.09310E-01  1.95E-03  0.00E+00  1.63E-05  1.02E-03   2
  11  2.09297E-01  1.25E-05  0.00E+00  2.77E-06  4.74E-04   2
  12  2.09294E-01  2.68E-07  0.00E+00  3.89E-07  2.21E-04   2
  13  2.09294E-01  2.25E-09  0.00E+00  5.43E-08  1.03E-04   2
 --------------------------------------------------------------
 Status: converged, an optimal solution found
 --------------------------------------------------------------
 Final objective value                2.092940E-01
 Relative precision                   2.759238E-07
 Optimality                           2.249294E-09
 Feasibility                          0.000000E+00
 Complementarity                      5.426796E-08
 Iteration counts
   Outer iterations                             13
   Inner iterations                             36
   Linesearch steps                             36
 Evaluation counts
   Augm. Lagr. values                           50
   Augm. Lagr. gradient                         50
   Augm. Lagr. hessian                          36
 --------------------------------------------------------------
 Nearest Correlation Matrix
          1       2       3       4
 1   1.0000 -0.6823  0.0000  0.0000
 2           1.0000 -0.5344  0.0000
 3                   1.0000 -0.6823
 4                           1.0000


e04rhfe.r

 E04RHF Example Program Results

 Monitor at iteration   0: objective    0.00, avg.error  3.14E+01
 Monitor at iteration   1: objective  154.74, avg.error  4.98E+01
 Monitor at iteration   2: objective   71.71, avg.error  2.15E+01
 Monitor at iteration   3: objective   36.88, avg.error  9.13E+00
 Monitor at iteration   4: objective   22.50, avg.error  3.84E+00
 Monitor at iteration   5: objective   16.47, avg.error  1.61E+00
 Monitor at iteration   6: objective   13.88, avg.error  6.87E-01
 Monitor at iteration   7: objective   12.76, avg.error  2.97E-01
 Monitor at iteration   8: objective   12.27, avg.error  1.29E-01
 Monitor at iteration   9: objective   12.06, avg.error  5.63E-02
 Monitor at iteration  10: objective   11.97, avg.error  2.50E-02
 Monitor at iteration  11: objective   11.93, avg.error  1.17E-02
 Monitor at iteration  12: objective   11.91, avg.error  5.77E-03
 Monitor at iteration  13: objective   11.91, avg.error  3.33E-03
 Monitor at iteration  14: objective   11.90, avg.error  9.11E-04
 Monitor at iteration  15: objective   11.90, avg.error  3.77E-04
 Monitor at iteration  16: objective   11.90, avg.error  1.64E-04
 Monitor at iteration  17: objective   11.90, avg.error  7.07E-05
 Monitor at iteration  18: objective   11.90, avg.error  3.05E-05
 Monitor at iteration  19: objective   11.90, avg.error  1.31E-05
 Monitor at iteration  20: objective   11.90, avg.error  5.60E-06
 Monitor at iteration  21: objective   11.90, avg.error  2.38E-06
 Monitor at iteration  22: objective   11.90, avg.error  1.01E-06
 Finished at iteration 23: objective   11.90, avg.error  4.31E-07
 Completed Matrix
          1      2      3      4      5      6
  1     0.5    0.3    0.2    0.2    0.4    0.4
  2     0.6    0.4    0.8    0.2    0.3    0.4
  3     0.4    0.3    0.8    0.0    0.2    0.2
  4     0.8    0.2    0.3    0.4    0.3    0.4
  5     0.0    0.4    0.2    0.0    0.2    0.2
  6     0.4    0.1    0.2    0.2    0.1    0.2
  7     0.6    0.8    0.2    0.6    0.2    0.4
  8     0.1    0.1    0.2    0.0    0.0    0.1
  9     0.6    0.4    0.1    0.6    0.0    0.3
 10     0.2    0.1    0.4    0.0    0.1    0.1
 11     0.5    0.3    0.2    0.2    0.4    0.4
 12     0.7    0.4    0.3    0.0    1.0    0.8
 13     1.0    0.3    0.2    0.5    0.5    0.6
 14     0.2    0.1    0.1    0.1    0.2    0.2
 15     0.6    0.3    0.2    0.4    0.2    0.3
 Rank is                   4


e04rjfe.r

 E04RJF Example Program Results

 Reading MPS file:  e04rjfe.opt

 MPSX INPUT LISTING
 ------------------
 Searching for indicator line
 Line          1: Found NAME indicator line
                  Query mode - Ignoring NAME data.
 Line          2: Found ROWS indicator line
                  Query mode - Counting ROWS data.
 Line          7: Found COLUMNS indicator line
                  Query mode - Counting COLUMNS data.
 Line         26: Found RHS indicator line
                  Query mode - Ignoring RHS data.
 Line         31: Found RANGES indicator line
                  Query mode - Ignoring RANGES data.
 Line         35: Found BOUNDS indicator line
                  Query mode - Ignoring BOUNDS data.
 Line         54: Found QUADOBJ indicator line
                  Query mode - Counting QUADOBJ data.
                  Query mode - End of QUADOBJ data. Exit

 MPSX INPUT LISTING
 ------------------
 Searching for indicator line
 Line          1: Found NAME indicator line
 Line          2: Found ROWS indicator line
 Line          7: Found COLUMNS indicator line
 Line         26: Found RHS indicator line
 Line         31: Found RANGES indicator line
 Line         35: Found BOUNDS indicator line
 Line         54: Found QUADOBJ indicator line
 Line         64: Found ENDATA indicator line
 MPS/QPS file read
 The problem was set-up
 E04SV, NLP-SDP Solver (Pennon)
 ------------------------------
 Number of variables             9                 [eliminated            0]
                            simple  linear  nonlin
 (Standard) inequalities        18       6       0
 (Standard) equalities                   0       0
 Matrix inequalities                     0       0 [dense    0, sparse    0]
                                                   [max dimension         0]

 --------------------------------------------------------------
  it|  objective |  optim  |   feas  |  compl  | pen min |inner
 --------------------------------------------------------------
   0  0.00000E+00  4.70E+00  0.00E+00  1.00E+01  1.00E+00   0
   1 -6.76762E+00  9.46E-04  0.00E+00  6.25E-01  1.00E+00   4
   2 -7.82467E+00  1.79E-03  3.69E-02  1.45E-01  4.65E-01   4
   3 -8.02059E+00  7.27E-03  2.27E-02  3.38E-02  2.16E-01   4
   4 -8.06187E+00  3.18E-03  5.75E-03  7.86E-03  1.01E-01   4
   5 -8.06653E+00  1.30E-03  1.13E-03  1.83E-03  4.68E-02   5
   6 -8.06739E+00  6.98E-03  1.42E-04  4.25E-04  2.18E-02   3
   7 -8.06775E+00  2.16E-04  2.80E-05  9.89E-05  1.01E-02   2
   8 -8.06778E+00  4.44E-05  6.94E-05  2.30E-05  4.71E-03   1
   9 -8.06778E+00  1.88E-06  1.15E-05  5.35E-06  2.19E-03   1
  10 -8.06778E+00  4.38E-08  1.52E-06  1.24E-06  1.02E-03   1
  11 -8.06778E+00  6.52E-10  1.74E-07  2.90E-07  4.74E-04   1
  12 -8.06778E+00  8.12E-12  1.90E-08  6.73E-08  2.21E-04   1
 --------------------------------------------------------------
 Status: converged, an optimal solution found
 --------------------------------------------------------------
 Final objective value               -8.067778E+00
 Relative precision                   1.518278E-09
 Optimality                           8.116995E-12
 Feasibility                          1.900689E-08
 Complementarity                      6.734260E-08
 Iteration counts
   Outer iterations                             12
   Inner iterations                             31
   Linesearch steps                             43
 Evaluation counts
   Augm. Lagr. values                           56
   Augm. Lagr. gradient                         44
   Augm. Lagr. hessian                          31
 --------------------------------------------------------------

 Optimal solution:
 X =      2.00    -0.23    -0.27
 X =     -0.30    -0.10     2.00
 X =      2.00    -1.78    -0.46


e04rnfe.r

 E04RNF Example Program Results

 E04SV, NLP-SDP Solver (Pennon)
 ------------------------------
 Number of variables            42                 [eliminated            0]
                            simple  linear  nonlin
 (Standard) inequalities        41       2       0
 (Standard) equalities                   0       0
 Matrix inequalities                     1       0 [dense    1, sparse    0]
                                                   [max dimension         5]

 Begin of Options
     Outer Iteration Limit         =                 100     * d
     Inner Iteration Limit         =                 100     * d
     Infinite Bound Size           =         1.00000E+20     * d
     Initial X                     =           Automatic     * U
     Initial U                     =           Automatic     * d
     Initial P                     =           Automatic     * d
     Hessian Density               =               Dense     * S
     Init Value P                  =         1.00000E+00     * d
     Init Value Pmat               =         1.00000E+00     * d
     Presolve Block Detect         =                 Yes     * d
     Print File                    =                   6     * d
     Print Level                   =                   2     * d
     Print Options                 =                 Yes     * d
     Monitoring File               =                  -1     * d
     Monitoring Level              =                   4     * d
     Monitor Frequency             =                   0     * d
     Stats Time                    =                  No     * d
     P Min                         =         1.05367E-08     * d
     Pmat Min                      =         1.05367E-08     * d
     U Update Restriction          =         5.00000E-01     * d
     Umat Update Restriction       =         3.00000E-01     * d
     Preference                    =               Speed     * d
     Transform Constraints         =          Equalities     * S
     Dimacs Measures               =               Check     * d
     Stop Criteria                 =                Soft     * d
     Stop Tolerance 1              =         1.00000E-06     * d
     Stop Tolerance 2              =         1.00000E-07     * d
     Stop Tolerance Feasibility    =         1.00000E-07     * d
     Linesearch Mode               =            Fullstep     * S
     Inner Stop Tolerance          =         1.00000E-02     * d
     Inner Stop Criteria           =           Heuristic     * d
     Task                          =            Maximize     * U
     P Update Speed                =                  12     * d
 End of Options
 --------------------------------------------------------------
  it|  objective |  optim  |   feas  |  compl  | pen min |inner
 --------------------------------------------------------------
   0  0.00000E+00  4.80E+01  5.90E-01  2.37E+00  1.00E+00   0
   1 -2.25709E+00  2.53E-03  7.15E-01  2.76E+00  1.00E+00   6
   2 -9.90666E-01  1.29E-03  1.38E-02  1.25E+00  4.65E-01   5
   3 -3.96590E-01  1.52E-03  2.07E-02  5.42E-01  2.16E-01   5
   4 -1.52400E-01  6.63E-04  1.42E-02  2.26E-01  1.01E-01   5
   5 -5.45545E-02  5.47E-03  9.33E-03  8.91E-02  4.68E-02   5
   6 -1.62316E-02  1.05E-02  3.18E-03  3.33E-02  2.18E-02   5
   7 -2.39571E-03  6.74E-03  3.90E-04  1.22E-02  1.01E-02   5
   8  3.39831E-03  5.41E-04  4.33E-05  4.43E-03  4.71E-03   6
   9  6.27924E-03  2.25E-03  3.47E-06  1.64E-03  2.19E-03   5
  10  7.23641E-03  4.07E-03  4.79E-07  5.77E-04  1.02E-03   4
  11  7.56230E-03  5.26E-04  1.76E-05  2.08E-04  4.74E-04   4
  12  7.67523E-03  1.18E-02  2.18E-06  7.69E-05  2.21E-04   3
  13  7.71758E-03  4.26E-03  2.51E-07  2.94E-05  1.03E-04   3
  14  7.73491E-03  4.34E-06  2.95E-08  1.11E-05  4.77E-05   4
 --------------------------------------------------------------
  it|  objective |  optim  |   feas  |  compl  | pen min |inner
 --------------------------------------------------------------
  15  7.74186E-03  8.50E-07  2.29E-09  3.96E-06  2.22E-05   4
  16  7.74450E-03  7.25E-08  1.58E-10  1.29E-06  1.03E-05   4
  17  7.74545E-03  2.51E-09  8.39E-12  3.32E-07  4.81E-06   4
  18  7.74574E-03  5.19E-10  3.49E-13  4.73E-08  2.24E-06   4
 --------------------------------------------------------------
 Status: converged, an optimal solution found
 --------------------------------------------------------------
 Final objective value                7.745738E-03
 Relative precision                   2.815426E-07
 Optimality                           5.188682E-10
 Feasibility                          3.486927E-13
 Complementarity                      4.732416E-08
 DIMACS error 1                       2.594341E-10
 DIMACS error 2                       0.000000E+00
 DIMACS error 3                       0.000000E+00
 DIMACS error 4                       1.743464E-13
 DIMACS error 5                       4.676597E-08
 DIMACS error 6                       4.662494E-08
 Iteration counts
   Outer iterations                             18
   Inner iterations                             81
   Linesearch steps                            186
 Evaluation counts
   Augm. Lagr. values                          100
   Augm. Lagr. gradient                        100
   Augm. Lagr. hessian                          81
 --------------------------------------------------------------

   Weight        Row of design matrix
 -----------------------------------------------------
    0.09         1.00   -1.00    1.00   -1.00    1.00
    0.25         1.00   -0.70    0.49   -0.34    0.24
    0.32         1.00    0.00    0.00    0.00    0.00
    0.25         1.00    0.70    0.49    0.34    0.24
    0.09         1.00    1.00    1.00    1.00    1.00
 only those rows with a weight >  0.1E-04 are shown


e04rpfe.r

 E04RPF Example Program Results

 SDP problem was read, passing it to the solver.

 Overview
   Status:                  Problem and option settings are editable.
   No of variables:         5
   Objective function:      linear
   Simple bounds:           not defined yet
   Linear constraints:      not defined yet
   Nonlinear constraints:   not defined yet
   Matrix constraints:      2
 Matrix constraints
   IDblk =     1, size =      2 x     2, polynomial of order 2
   IDblk =     2, size =      2 x     2, linear
 E04SV, NLP-SDP Solver (Pennon)
 ------------------------------
 Number of variables             5                 [eliminated            0]
                            simple  linear  nonlin
 (Standard) inequalities         0       0       0
 (Standard) equalities                   0       0
 Matrix inequalities                     1       1 [dense    2, sparse    0]
                                                   [max dimension         2]

 Begin of Options
     Outer Iteration Limit         =                 100     * d
     Inner Iteration Limit         =                 100     * d
     Infinite Bound Size           =         1.00000E+20     * d
     Initial X                     =                User     * d
     Initial U                     =           Automatic     * d
     Initial P                     =           Automatic     * d
     Hessian Density               =               Dense     * S
     Init Value P                  =         1.00000E+00     * d
     Init Value Pmat               =         1.00000E+00     * d
     Presolve Block Detect         =                 Yes     * d
     Print File                    =                   6     * d
     Print Level                   =                   2     * d
     Print Options                 =                 Yes     * d
     Monitoring File               =                  -1     * d
     Monitoring Level              =                   4     * d
     Monitor Frequency             =                   0     * d
     Stats Time                    =                  No     * d
     P Min                         =         1.05367E-08     * d
     Pmat Min                      =         1.05367E-08     * d
     U Update Restriction          =         5.00000E-01     * d
     Umat Update Restriction       =         3.00000E-01     * d
     Preference                    =               Speed     * d
     Transform Constraints         =                  No     * S
     Dimacs Measures               =                  No     * S
     Stop Criteria                 =                Soft     * d
     Stop Tolerance 1              =         1.00000E-06     * d
     Stop Tolerance 2              =         1.00000E-07     * d
     Stop Tolerance Feasibility    =         1.00000E-07     * d
     Linesearch Mode               =           Goldstein     * S
     Inner Stop Tolerance          =         1.00000E-02     * d
     Inner Stop Criteria           =           Heuristic     * d
     Task                          =            Minimize     * d
     P Update Speed                =                  12     * d
 End of Options
 --------------------------------------------------------------
  it|  objective |  optim  |   feas  |  compl  | pen min |inner
 --------------------------------------------------------------
   0  0.00000E+00  1.82E+01  1.00E+00  4.00E+00  2.00E+00   0
   1  4.11823E+00  3.85E-03  0.00E+00  1.73E+00  2.00E+00   6
   2  2.58252E+00  5.36E-03  0.00E+00  4.93E-01  9.04E-01   4
   3  2.06132E+00  1.02E-03  0.00E+00  7.70E-02  4.08E-01   4
   4  2.00050E+00  3.00E-03  8.91E-03  1.78E-02  1.85E-01   3
   5  1.99929E+00  1.55E-03  3.16E-03  3.65E-03  8.34E-02   2
   6  1.99985E+00  1.03E-04  3.16E-04  7.19E-04  3.77E-02   4
   7  1.99997E+00  7.04E-04  5.76E-05  1.41E-04  1.70E-02   1
   8  2.00000E+00  1.32E-04  6.52E-06  2.76E-05  7.70E-03   1
   9  2.00000E+00  8.49E-06  7.86E-07  5.37E-06  3.48E-03   1
  10  2.00000E+00  5.88E-07  1.06E-07  1.04E-06  1.57E-03   1
  11  2.00000E+00  5.55E-08  4.87E-08  2.02E-07  7.11E-04   1
  12  2.00000E+00  5.34E-09  5.37E-09  3.93E-08  3.21E-04   1
  13  2.00000E+00  5.03E-10  5.45E-09  7.62E-09  1.45E-04   1
  14  2.00000E+00  4.45E-11  5.55E-09  1.48E-09  6.56E-05   1
 --------------------------------------------------------------
  it|  objective |  optim  |   feas  |  compl  | pen min |inner
 --------------------------------------------------------------
  15  2.00000E+00  4.36E-12  5.67E-09  2.87E-10  2.96E-05   1
  16  2.00000E+00  1.61E-11  5.82E-09  5.57E-11  1.34E-05   1
  17  2.00000E+00  3.13E-11  6.00E-09  1.08E-11  6.06E-06   1
  18  2.00000E+00  8.65E-11  6.22E-09  2.10E-12  2.74E-06   1
  19  2.00000E+00  1.31E-10  6.48E-09  4.07E-13  1.24E-06   1
 --------------------------------------------------------------
 Status: converged, an optimal solution found
 --------------------------------------------------------------
 Final objective value                2.000000E+00
 Relative precision                   8.141636E-16
 Optimality                           1.310533E-10
 Feasibility                          6.484489E-09
 Complementarity                      4.066867E-13
 Iteration counts
   Outer iterations                             19
   Inner iterations                             36
   Linesearch steps                             56
 Evaluation counts
   Augm. Lagr. values                           76
   Augm. Lagr. gradient                         56
   Augm. Lagr. hessian                          36
 --------------------------------------------------------------


e04ryfe.r

 E04RYF Example Program Results

 Freshly created handle
 Overview
   Status:                  Problem and option settings are editable.
   No of variables:         2
   Objective function:      not defined yet
   Simple bounds:           not defined yet
   Linear constraints:      not defined yet
   Nonlinear constraints:   not defined yet
   Matrix constraints:      not defined yet

 Handle after definition of simple bounds and the objective
 Overview
   Status:                  Problem and option settings are editable.
   No of variables:         2
   Objective function:      linear
   Simple bounds:           defined
   Linear constraints:      not defined yet
   Nonlinear constraints:   not defined yet
   Matrix constraints:      not defined yet
 Objective function
   linear part
   c(      2) =  1.00E+00,
 Simple bounds
    0.000E+00 <= X_      1
   -3.000E+00 <= X_      2 <=  3.000E+00

 Handle after definition of the 1st matrix constraint
 Overview
   Status:                  Problem and option settings are editable.
   No of variables:         2
   Objective function:      linear
   Simple bounds:           defined
   Linear constraints:      not defined yet
   Nonlinear constraints:   not defined yet
   Matrix constraints:      1
 Matrix constraints
   IDblk =     1, size =      3 x     3, linear

 Handle after partial definition of the 2nd matrix constraint
 Matrix constraints
   IDblk =     1, size =      3 x     3, linear
   IDblk =     2, size =      2 x     2, linear

 Handle with the complete problem formulation
 Overview
   Status:                  Problem and option settings are editable.
   No of variables:         2
   Objective function:      linear
   Simple bounds:           defined
   Linear constraints:      not defined yet
   Nonlinear constraints:   not defined yet
   Matrix constraints:      2
 Matrix constraints
   IDblk =     1, size =      3 x     3, linear
   IDblk =     2, size =      2 x     2, polynomial of order 2
 Lagrangian multipliers sizes
   (Standard) multipliers U: 4 + 0 + 0
   Matrix multipliers UA:    9
 Matrix constraints (detailed)
   Matrix inequality IDBLK =     1, dimension     3
     multiindex k =     0
       A_k(     1,     1) = -1.000E+00
       A_k(     2,     1) =  1.000E+00
       A_k(     2,     2) = -7.500E-01
       A_k(     3,     3) = -1.600E+01

     multiindex k =     1
       A_k(     2,     1) =  1.000E+00

     multiindex k =     2
       A_k(     3,     1) =  1.000E+00

   Matrix inequality IDBLK =     2, dimension     2
     multiindex k =     0
       A_k(     2,     2) = -1.000E+00

     multiindex k =     1
       A_k(     1,     1) =  1.000E+00

     multiindex k =     1,     2
       Q_k(     2,     1) = -1.000E+00

 Option settings
 Begin of Options
     Outer Iteration Limit         =                 100     * d
     Inner Iteration Limit         =                 100     * d
     Infinite Bound Size           =         1.00000E+20     * d
     Initial X                     =           Automatic     * U
     Initial U                     =           Automatic     * d
     Initial P                     =           Automatic     * d
     Hessian Density               =                Auto     * d
     Init Value P                  =         1.00000E+00     * d
     Init Value Pmat               =         1.00000E+00     * d
     Presolve Block Detect         =                 Yes     * d
     Print File                    =                   6     * d
     Print Level                   =                   2     * d
     Print Options                 =                  No     * U
     Monitoring File               =                  -1     * d
     Monitoring Level              =                   4     * d
     Monitor Frequency             =                   0     * d
     Stats Time                    =                  No     * d
     P Min                         =         1.05367E-08     * d
     Pmat Min                      =         1.05367E-08     * d
     U Update Restriction          =         5.00000E-01     * d
     Umat Update Restriction       =         3.00000E-01     * d
     Preference                    =               Speed     * d
     Transform Constraints         =                Auto     * d
     Dimacs Measures               =               Check     * d
     Stop Criteria                 =                Soft     * d
     Stop Tolerance 1              =         1.00000E-06     * d
     Stop Tolerance 2              =         1.00000E-07     * d
     Stop Tolerance Feasibility    =         1.00000E-07     * d
     Linesearch Mode               =                Auto     * d
     Inner Stop Tolerance          =         1.00000E-02     * d
     Inner Stop Criteria           =           Heuristic     * d
     Task                          =            Minimize     * d
     P Update Speed                =                  12     * d
     Hessian Mode                  =                Auto     * d
     Verify Derivatives            =                Auto     * d
     Time Limit                    =         1.00000E+06     * d
 End of Options
 E04SV, NLP-SDP Solver (Pennon)
 ------------------------------
 Number of variables             2                 [eliminated            0]
                            simple  linear  nonlin
 (Standard) inequalities         3       0       0
 (Standard) equalities                   0       0
 Matrix inequalities                     1       1 [dense    2, sparse    0]
                                                   [max dimension         3]

 --------------------------------------------------------------
  it|  objective |  optim  |   feas  |  compl  | pen min |inner
 --------------------------------------------------------------
   0  0.00000E+00  4.56E+00  1.23E-01  4.41E+01  1.00E+00   0
   1 -3.01854E-01  1.21E-03  0.00E+00  1.89E+00  1.00E+00   7
   2 -6.21230E-01  2.58E-03  0.00E+00  6.72E-01  4.65E-01   2
   3 -2.11706E+00  4.31E-03  3.39E-02  6.07E-02  2.16E-01   5
   4 -2.01852E+00  5.71E-03  6.05E-03  8.55E-03  1.01E-01   3
   5 -2.00164E+00  3.36E-03  6.26E-04  1.02E-03  4.68E-02   2
   6 -2.00022E+00  4.45E-03  8.37E-05  1.82E-04  2.18E-02   1
   7 -2.00001E+00  4.73E-04  4.01E-06  3.96E-05  1.01E-02   1
   8 -2.00000E+00  4.77E-06  2.25E-07  9.20E-06  4.71E-03   1
   9 -2.00000E+00  4.52E-08  3.61E-08  2.14E-06  2.19E-03   1
  10 -2.00000E+00  6.63E-09  3.19E-08  4.98E-07  1.02E-03   1
  11 -2.00000E+00  8.80E-10  5.34E-09  1.16E-07  4.74E-04   1
  12 -2.00000E+00  1.02E-10  5.41E-09  2.69E-08  2.21E-04   1
 --------------------------------------------------------------
 Status: converged, an optimal solution found
 --------------------------------------------------------------
 Final objective value               -2.000000E+00
 Relative precision                   9.839057E-10
 Optimality                           1.019125E-10
 Feasibility                          5.406175E-09
 Complementarity                      2.693704E-08
 Iteration counts
   Outer iterations                             12
   Inner iterations                             26
   Linesearch steps                             37
 Evaluation counts
   Augm. Lagr. values                           50
   Augm. Lagr. gradient                         39
   Augm. Lagr. hessian                          26
 --------------------------------------------------------------

 Problem solved
 Overview
   Status:                  Solver finished, only options can be changed.
   No of variables:         2
   Objective function:      linear
   Simple bounds:           defined
   Linear constraints:      not defined
   Nonlinear constraints:   not defined
   Matrix constraints:      2

 Final objective value =     -2.00
 Final X =      0.25    -2.00


e04stfe.r

 E04STF Example Program Results

 Overview
   Status:                  Problem and option settings are editable.
   No of variables:         4
   Objective function:      nonlinear
   Simple bounds:           defined
   Linear constraints:      2
   Nonlinear constraints:   1
   Matrix constraints:      not defined yet
 Option settings
 Begin of Options
     Outer Iteration Limit         =                  26     * U
     Infinite Bound Size           =         1.00000E+40     * U
     Print File                    =                  66     * U
     Print Level                   =                   2     * U
     Monitoring File               =                  67     * U
     Monitoring Level              =                   5     * U
     Stats Time                    =                  No     * d
     Stop Tolerance 1              =         2.50000E-08     * U
     Hessian Mode                  =               Exact     * S
     Verify Derivatives            =                 Yes     * S
     Time Limit                    =         6.00000E+01     * U
 End of Options

Variables
     x(         1)                 =        6.355216E-01
     x(         2)                 =        2.066279E-10
     x(         3)                 =        3.127019E-01
     x(         4)                 =        5.177655E-02
Variable bound Lagrange multipliers
     zL(         1)                =        3.916168E-09
     zU(         1)                =        0.000000E+00
     zL(         2)                =        2.433326E-01
     zU(         2)                =        0.000000E+00
     zL(         3)                =        7.974843E-09
     zU(         3)                =        0.000000E+00
     zL(         4)                =        4.944607E-08
     zU(         4)                =        0.000000E+00
Linear constraints Lagrange multipliers
     l+(         1)                =        0.000000E+00
     l-(         1)                =        4.105411E-01
     l+(         2)                =        0.000000E+00
     l-(         2)                =        5.803551E-01
Nonlinear constraints Lagrange multipliers
     l+(         1)                =        0.000000E+00
     l-(         1)                =        1.837124E+01
At solution, Objective minimum     =       2.9894378E+01
             Constraint violation  =            1.11E-16
             Dual infeasibility    =            6.71E-12
             Complementarity       =            2.56E-09
             KKT error             =            2.56E-09
Solved in allotted time limit
    after iterations                        :          8
    after objective evaluations             :          9
    after objective gradient evaluations    :          9
    after constraint evaluations            :          9
    after constraint gradient evaluations   :          9
    after hessian evaluations               :          8
 Overview
   Status:                  Solver finished, only options can be changed.
   No of variables:         4
   Objective function:      nonlinear
   Simple bounds:           defined
   Linear constraints:      2
   Nonlinear constraints:   1
   Matrix constraints:      not defined
 ---------------------------------------------
 Overview
   Status:                  Problem and option settings are editable.
   No of variables:         4
   Objective function:      linear
   Simple bounds:           defined
   Linear constraints:      2
   Nonlinear constraints:   1
   Matrix constraints:      not defined yet
 Option settings
 Begin of Options
     Outer Iteration Limit         =                  26     * U
     Infinite Bound Size           =         1.00000E+40     * U
     Print File                    =                  66     * U
     Print Level                   =                   2     * U
     Monitoring File               =                  67     * U
     Monitoring Level              =                   5     * U
     Stats Time                    =                  No     * d
     Stop Tolerance 1              =         2.50000E-08     * U
     Hessian Mode                  =               Exact     * S
     Verify Derivatives            =                 Yes     * S
     Time Limit                    =         6.00000E+01     * U
 End of Options

Variables
     x(         1)                 =        6.355216E-01
     x(         2)                 =        2.066279E-10
     x(         3)                 =        3.127019E-01
     x(         4)                 =        5.177655E-02
Variable bound Lagrange multipliers
     zL(         1)                =        3.916168E-09
     zU(         1)                =        0.000000E+00
     zL(         2)                =        2.433326E-01
     zU(         2)                =        0.000000E+00
     zL(         3)                =        7.974843E-09
     zU(         3)                =        0.000000E+00
     zL(         4)                =        4.944607E-08
     zU(         4)                =        0.000000E+00
Linear constraints Lagrange multipliers
     l+(         1)                =        0.000000E+00
     l-(         1)                =        4.105411E-01
     l+(         2)                =        0.000000E+00
     l-(         2)                =        5.803551E-01
Nonlinear constraints Lagrange multipliers
     l+(         1)                =        0.000000E+00
     l-(         1)                =        1.837124E+01
At solution, Objective minimum     =       2.9894378E+01
             Constraint violation  =            1.11E-16
             Dual infeasibility    =            6.71E-12
             Complementarity       =            2.56E-09
             KKT error             =            2.56E-09
Solved in allotted time limit
    after iterations                        :          8
    after objective evaluations             :          9
    after objective gradient evaluations    :          9
    after constraint evaluations            :          9
    after constraint gradient evaluations   :          9
    after hessian evaluations               :          8
 Overview
   Status:                  Solver finished, only options can be changed.
   No of variables:         4
   Objective function:      linear
   Simple bounds:           defined
   Linear constraints:      2
   Nonlinear constraints:   1
   Matrix constraints:      not defined
 ---------------------------------------------


e04svfe.r

 E04SVF Example Program Results

 E04SV, NLP-SDP Solver (Pennon)
 ------------------------------
 Number of variables            16                 [eliminated            0]
                            simple  linear  nonlin
 (Standard) inequalities         0       0       0
 (Standard) equalities                   0       0
 Matrix inequalities                     1       0 [dense    1, sparse    0]
                                                   [max dimension        10]

 Begin of Options
     Outer Iteration Limit         =                 100     * d
     Inner Iteration Limit         =                 100     * d
     Infinite Bound Size           =         1.00000E+20     * d
     Initial X                     =           Automatic     * U
     Initial U                     =           Automatic     * d
     Initial P                     =           Automatic     * d
     Hessian Density               =               Dense     * S
     Init Value P                  =         1.00000E+00     * d
     Init Value Pmat               =         1.00000E+00     * d
     Presolve Block Detect         =                 Yes     * d
     Print File                    =                   6     * d
     Print Level                   =                   2     * d
     Print Options                 =                 Yes     * d
     Monitoring File               =                  -1     * d
     Monitoring Level              =                   4     * d
     Monitor Frequency             =                   0     * d
     Stats Time                    =                  No     * d
     P Min                         =         1.05367E-08     * d
     Pmat Min                      =         1.05367E-08     * d
     U Update Restriction          =         5.00000E-01     * d
     Umat Update Restriction       =         3.00000E-01     * d
     Preference                    =               Speed     * d
     Transform Constraints         =                  No     * S
     Dimacs Measures               =               Check     * d
     Stop Criteria                 =                Soft     * d
     Stop Tolerance 1              =         1.00000E-06     * d
     Stop Tolerance 2              =         1.00000E-07     * d
     Stop Tolerance Feasibility    =         1.00000E-07     * d
     Linesearch Mode               =            Fullstep     * S
     Inner Stop Tolerance          =         1.00000E-02     * d
     Inner Stop Criteria           =           Heuristic     * d
     Task                          =            Minimize     * d
     P Update Speed                =                  12     * d
 End of Options
 --------------------------------------------------------------
  it|  objective |  optim  |   feas  |  compl  | pen min |inner
 --------------------------------------------------------------
   0  0.00000E+00  4.71E+01  1.00E+01  4.81E+01  1.60E+01   0
   1  9.55399E+01  9.29E-03  0.00E+00  9.52E+01  1.60E+01   8
   2  3.93849E+01  1.16E-03  0.00E+00  3.81E+01  6.63E+00   5
   3  1.68392E+01  1.19E-02  0.00E+00  1.52E+01  2.75E+00   3
   4  8.50544E+00  7.32E-04  0.00E+00  5.78E+00  1.14E+00   4
   5  5.62254E+00  1.56E-02  0.00E+00  2.07E+00  4.72E-01   3
   6  4.63348E+00  7.66E-03  0.00E+00  7.33E-01  1.96E-01   4
   7  4.25322E+00  2.99E-03  0.00E+00  2.72E-01  8.11E-02   4
   8  4.10154E+00  2.41E-03  0.00E+00  1.05E-01  3.36E-02   4
   9  4.04076E+00  1.87E-03  0.00E+00  4.14E-02  1.39E-02   4
  10  4.01631E+00  6.25E-03  0.00E+00  1.65E-02  5.77E-03   5
  11  4.00656E+00  3.23E-03  0.00E+00  6.59E-03  2.39E-03   5
  12  4.00263E+00  2.89E-03  0.00E+00  2.64E-03  9.91E-04   5
  13  4.00106E+00  2.08E-03  0.00E+00  1.06E-03  4.11E-04   5
  14  4.00042E+00  1.53E-03  0.00E+00  4.25E-04  1.70E-04   5
 --------------------------------------------------------------
  it|  objective |  optim  |   feas  |  compl  | pen min |inner
 --------------------------------------------------------------
  15  4.00017E+00  1.30E-06  0.00E+00  1.70E-04  7.05E-05   6
  16  4.00007E+00  7.48E-07  0.00E+00  6.82E-05  2.92E-05   6
  17  4.00003E+00  3.20E-07  0.00E+00  2.73E-05  1.21E-05   6
  18  4.00001E+00  1.31E-07  0.00E+00  1.10E-05  5.02E-06   6
  19  4.00000E+00  5.15E-08  0.00E+00  4.39E-06  2.08E-06   6
  20  4.00000E+00  1.92E-08  0.00E+00  1.76E-06  8.62E-07   6
  21  4.00000E+00  7.06E-09  0.00E+00  7.05E-07  3.57E-07   6
  22  4.00000E+00  1.98E-09  0.00E+00  2.82E-07  1.48E-07   6
 --------------------------------------------------------------
 Status: converged, an optimal solution found
 --------------------------------------------------------------
 Final objective value                4.000000E+00
 Relative precision                   8.450361E-08
 Optimality                           1.983580E-09
 Feasibility                          0.000000E+00
 Complementarity                      2.822749E-07
 DIMACS error 1                       9.917898E-10
 DIMACS error 2                       0.000000E+00
 DIMACS error 3                       0.000000E+00
 DIMACS error 4                       0.000000E+00
 DIMACS error 5                       3.202984E-08
 DIMACS error 6                       3.136387E-08
 Iteration counts
   Outer iterations                             22
   Inner iterations                            112
   Linesearch steps                            308
 Evaluation counts
   Augm. Lagr. values                          135
   Augm. Lagr. gradient                        135
   Augm. Lagr. hessian                         112
 --------------------------------------------------------------
 The solver chose to use DENSE hessian
 and FULLSTEP as linesearch.
 Lovasz theta number of the given graph is    4.00


e04ucae.r

 E04UCA Example Program Results

 Varbl  Istate   Value         Lagr Mult

 V   1   1       1.00000         1.088
 V   2   0       4.74300         0.000
 V   3   0       3.82115         0.000
 V   4   0       1.37941         0.000

 L Con  Istate   Value         Lagr Mult

 L   1   0       10.9436         0.000

 N Con  Istate   Value         Lagr Mult

 N   1   2       40.0000       -0.1615
 N   2   1       25.0000        0.5523

 Final objective value =    17.01402


e04ucfe.r

 E04UCF Example Program Results

 *** E04UCF

 Parameters
 ----------

 Linear constraints.....         1       Variables..............         4
 Nonlinear constraints..         2

 Infinite bound size....  1.00E+20       COLD start.............
 Infinite step size.....  1.00E+20       EPS (machine precision)  1.11E-16
 Step limit.............  2.00E+00       Hessian................        NO

 Linear feasibility.....  1.05E-08       Crash tolerance........  1.00E-02
 Nonlinear feasibility..  1.05E-08       Optimality tolerance...  3.26E-12
 Line search tolerance..  9.00E-01       Function precision.....  4.37E-15

 Derivative level.......         3       Monitoring file........        -1
 Verify level...........         0

 Major iterations limit.        50       Major print level......        10
 Minor iterations limit.        50       Minor print level......         0

 Start point
    1.000000E+00   5.000000E+00   5.000000E+00   1.000000E+00

 Workspace provided is     IWORK(      17),  WORK(     185).
 To solve problem we need  IWORK(      17),  WORK(     185).

 Verification of the constraint gradients.
 -----------------------------------------

 The constraint Jacobian seems to be ok.

 The largest relative error was    2.29E-07  in constraint    2

 Verification of the objective gradients.
 ----------------------------------------

 The objective gradients seem to be ok.

 Directional derivative of the objective    8.15250000E-01
 Difference approximation                   8.15249734E-01

  Maj  Mnr    Step Merit Function Norm Gz  Violtn Cond Hz
    0    4 0.0E+00   1.738281E+01 7.1E-01 1.2E+01 1.0E+00
    1    1 1.0E+00   1.703169E+01 4.6E-02 1.9E+00 1.0E+00
    2    1 1.0E+00   1.701442E+01 2.1E-02 8.8E-02 1.0E+00
    3    1 1.0E+00   1.701402E+01 3.1E-04 5.4E-04 1.0E+00
    4    1 1.0E+00   1.701402E+01 7.0E-06 9.9E-08 1.0E+00
    5    1 1.0E+00   1.701402E+01 1.1E-08 4.6E-11 1.0E+00

 Exit from NP problem after     5 major iterations,
                                9 minor iterations.

 Varbl State     Value       Lower Bound   Upper Bound    Lagr Mult   Slack

 V   1    LL    1.00000       1.00000       5.00000       1.088         .
 V   2    FR    4.74300       1.00000       5.00000           .      0.2570
 V   3    FR    3.82115       1.00000       5.00000           .       1.179
 V   4    FR    1.37941       1.00000       5.00000           .      0.3794

 L Con State     Value       Lower Bound   Upper Bound    Lagr Mult   Slack

 L   1    FR    10.9436          None       20.0000           .       9.056

 N Con State     Value       Lower Bound   Upper Bound    Lagr Mult   Slack

 N   1    UL    40.0000          None       40.0000     -0.1615     -3.5264E-11
 N   2    LL    25.0000       25.0000          None      0.5523     -2.8791E-11

 Exit E04UCF - Optimal solution found.

 Final objective value =    17.01402


e04udae.r

 E04UDA Example Program Results

 Varbl  Istate   Value         Lagr Mult

 V   1   1       1.00000         1.088
 V   2   0       4.74300         0.000
 V   3   0       3.82115         0.000
 V   4   0       1.37941         0.000

 L Con  Istate   Value         Lagr Mult

 L   1   0       10.9436         0.000

 N Con  Istate   Value         Lagr Mult

 N   1   2       40.0000       -0.1615
 N   2   1       25.0000        0.5523

 Final objective value =    17.01402


e04udfe.r

 E04UDF Example Program Results

 Calls to E04UEF
 ---------------

       Infinite Bound Size = 1.0D+25
       Print Level = 1
       Verify Level = -1

 OPTIONS file
 ------------

      Begin   Example options file for  E04UDF
         Major Iteration Limit   =  15      *  (Default =  50)
         Minor Iteration Limit   =  10      *  (Default =  50)
      End

 *** E04UCF

 Parameters
 ----------

 Linear constraints.....         1       Variables..............         4
 Nonlinear constraints..         2

 Infinite bound size....  1.00E+25       COLD start.............
 Infinite step size.....  1.00E+25       EPS (machine precision)  1.11E-16
 Step limit.............  2.00E+00       Hessian................        NO

 Linear feasibility.....  1.05E-08       Crash tolerance........  1.00E-02
 Nonlinear feasibility..  1.05E-08       Optimality tolerance...  3.26E-12
 Line search tolerance..  9.00E-01       Function precision.....  4.37E-15

 Derivative level.......         3       Monitoring file........        -1
 Verify level...........        -1

 Major iterations limit.        15       Major print level......         1
 Minor iterations limit.        10       Minor print level......         0

 Start point
    1.000000E+00   5.000000E+00   5.000000E+00   1.000000E+00

 Workspace provided is     IWORK(      17),  WORK(     185).
 To solve problem we need  IWORK(      17),  WORK(     185).

 Exit from NP problem after     5 major iterations,
                                9 minor iterations.

 Varbl State     Value       Lower Bound   Upper Bound    Lagr Mult   Slack

 V   1    LL    1.00000       1.00000       5.00000       1.088         .
 V   2    FR    4.74300       1.00000       5.00000           .      0.2570
 V   3    FR    3.82115       1.00000       5.00000           .       1.179
 V   4    FR    1.37941       1.00000       5.00000           .      0.3794

 L Con State     Value       Lower Bound   Upper Bound    Lagr Mult   Slack

 L   1    FR    10.9436          None       20.0000           .       9.056

 N Con State     Value       Lower Bound   Upper Bound    Lagr Mult   Slack

 N   1    UL    40.0000          None       40.0000     -0.1615     -3.5264E-11
 N   2    LL    25.0000       25.0000          None      0.5523     -2.8791E-11

 Exit E04UCF - Optimal solution found.

 Final objective value =    17.01402


e04ufae.r

 E04UFA Example Program Results

 Varbl  Istate   Value         Lagr Mult

 V   1   1       1.00000         1.088
 V   2   0       4.74300         0.000
 V   3   0       3.82115         0.000
 V   4   0       1.37941         0.000

 L Con  Istate   Value         Lagr Mult

 L   1   0       10.9436         0.000

 N Con  Istate   Value         Lagr Mult

 N   1   2       40.0000       -0.1615
 N   2   1       25.0000        0.5523

 Final objective value =    17.01402


e04uffe.r

 E04UFF Example Program Results

 *** E04UFF

 Parameters
 ----------

 Linear constraints.....         1       Variables..............         4
 Nonlinear constraints..         2

 Infinite bound size....  1.00E+20       COLD start.............
 Infinite step size.....  1.00E+20       EPS (machine precision)  1.11E-16
 Step limit.............  2.00E+00       Hessian................        NO

 Linear feasibility.....  1.05E-08       Crash tolerance........  1.00E-02
 Nonlinear feasibility..  1.05E-08       Optimality tolerance...  3.26E-12
 Line search tolerance..  9.00E-01       Function precision.....  4.37E-15

 Derivative level.......         3       Monitoring file........        -1
 Verify level...........         0

 Major iterations limit.        50       Major print level......        10
 Minor iterations limit.        50       Minor print level......         0

 Workspace provided is     IWORK(      17),  WORK(     192).
 To solve problem we need  IWORK(      17),  WORK(     192).

 Verification of the constraint gradients.
 -----------------------------------------

 The constraint Jacobian seems to be ok.

 The largest relative error was    2.29E-07  in constraint    2

 Verification of the objective gradients.
 ----------------------------------------

 The objective gradients seem to be ok.

 Directional derivative of the objective    8.15250000E-01
 Difference approximation                   8.15249734E-01

  Maj  Mnr    Step Merit Function Norm Gz  Violtn Cond Hz
    0    4 0.0E+00   1.738281E+01 7.1E-01 1.2E+01 1.0E+00
    1    1 1.0E+00   1.703169E+01 4.6E-02 1.9E+00 1.0E+00
    2    1 1.0E+00   1.701442E+01 2.1E-02 8.8E-02 1.0E+00
    3    1 1.0E+00   1.701402E+01 3.1E-04 5.4E-04 1.0E+00
    4    1 1.0E+00   1.701402E+01 7.0E-06 9.9E-08 1.0E+00
    5    1 1.0E+00   1.701402E+01 1.1E-08 4.6E-11 1.0E+00

 Exit from NP problem after     5 major iterations,
                                9 minor iterations.

 Varbl State     Value       Lower Bound   Upper Bound    Lagr Mult   Slack

 V   1    LL    1.00000       1.00000       5.00000       1.088         .
 V   2    FR    4.74300       1.00000       5.00000           .      0.2570
 V   3    FR    3.82115       1.00000       5.00000           .       1.179
 V   4    FR    1.37941       1.00000       5.00000           .      0.3794

 L Con State     Value       Lower Bound   Upper Bound    Lagr Mult   Slack

 L   1    FR    10.9436          None       20.0000           .       9.056

 N Con State     Value       Lower Bound   Upper Bound    Lagr Mult   Slack

 N   1    UL    40.0000          None       40.0000     -0.1615     -3.5264E-11
 N   2    LL    25.0000       25.0000          None      0.5523     -2.8791E-11

 Exit E04UFF - Optimal solution found.

 Final objective value =    17.01402


e04ugae.r

 E04UGA Example Program Results

 Variable  Istate     Value         Lagr Mult

 Varble  1   3      0.118876       -1.2529E-07
 Varble  2   3     -0.396234        1.9245E-08
 Varble  3   3       679.945        1.7001E-10
 Varble  4   2       1026.07       -2.1918E-10

 Constrnt  Istate     Value         Lagr Mult

 NlnCon  1   0      -894.800        -4.387
 NlnCon  2   0      -894.800        -4.106
 NlnCon  3   0      -1294.80        -5.463
 LinCon  1   3     -0.515110         0.000
 LinCon  2   3      0.515110         0.000
 Free Row    3       4091.97        -1.000

 Final objective value =    5126.498


e04ugfe.r

 E04UGF Example Program Results

 Workspace provided is                   IZ(     500),  Z(     500).
 To start solving the problem we need    IZ(     628),  Z(     758).

 Exit E04UGF - Not enough integer workspace to start solving the problem.

 *** E04UGF

 Parameters
 ----------

 Frequencies.
 Check frequency.........        60       Expand frequency.......     10000
 Factorization frequency.        50

 QP subproblems.
 Scale tolerance.........  9.00E-01       Minor feasibility tol..  1.05E-08
 Scale option............         1       Minor optimality tol...  1.05E-08
 Partial price...........         1       Crash tolerance........  1.00E-01
 Pivot tolerance.........  2.04E-11       Minor print level......         0
 Crash option............         0       Elastic weight.........  1.00E+02

 The SQP method.
 Minimize................
 Nonlinear objective vars         4       Major optimality tol...  1.05E-08
 Function precision......  1.72E-13       Unbounded step size....  1.00E+20
 Superbasics limit.......         4       Forward difference int.  4.15E-07
 Unbounded objective.....  1.00E+15       Central difference int.  5.56E-05
 Major step limit........  2.00E+00       Derivative linesearch..
 Derivative level........         3       Major iteration limit..      1000
 Linesearch tolerance....  9.00E-01       Verify level...........         0
 Minor iteration limit...       500       Major print level......        10
 Infinite bound size.....  1.00E+20       Iteration limit........     10000

 Hessian approximation.
 Hessian full memory.....                 Hessian updates........  99999999
 Hessian frequency.......  99999999

 Nonlinear constraints.
 Nonlinear constraints...         3       Major feasibility tol..  1.05E-08
 Nonlinear Jacobian vars.         2       Violation limit........  1.00E+01

 Miscellaneous.
 Variables...............         4       Linear constraints.....         3
 Nonlinear variables.....         4       Linear variables.......         0
 LU factor tolerance.....  5.00E+00       LU singularity tol.....  2.04E-11
 LU update tolerance.....  5.00E+00       LU density tolerance...  6.00E-01
 eps (machine precision).  1.11E-16       Monitoring file........        -1
 COLD start..............                 Infeasible exit........

 Workspace provided is                 IZ(    1256),  Z(    1516).
 To start solving the problem we need  IZ(     628),  Z(     758).

 Itn      0 -- Scale option reduced from                1 to                0.

 Itn      0 -- Feasible linear rows.

 Itn      0 -- Norm(x-x0) minimized. Sum of infeasibilities = 0.00E+00.

 confun  sets       6   out of       6   constraint gradients.
 objfun  sets       4   out of       4   objective  gradients.

 Cheap test on confun...

 The Jacobian seems to be OK.

 The largest discrepancy was    4.41E-08  in constraint     2.

 Cheap test on objfun...

 The objective gradients seem to be OK.
 Gradient projected in two directions   0.00000000000E+00   0.00000000000E+00
 Difference approximations              1.74111992322E-19   4.48742248252E-21

 Itn      0 -- All-slack basis B = I selected.

 Itn      7 -- Large multipliers.
               Elastic mode started with weight =  2.0E+02.

  Maj  Mnr    Step Merit Function Feasibl Optimal Cond Hz PD
    0   12 0.0E+00   3.199952E+05 1.7E+00 8.0E-01 2.1E+06 FF  R   i
    1    2 1.0E+00   2.463016E+05 1.2E+00 3.2E+03 4.5E+00 FF s
    2    1 1.0E+00   1.001802E+04 3.3E-02 9.2E+01 4.5E+00 FF
    3    1 1.0E+00   5.253418E+03 6.6E-04 2.5E+01 4.8E+00 FF
    4    1 1.0E+00   5.239444E+03 2.0E-06 2.8E+01 1.0E+02 FF
    5    1 1.0E+00   5.126208E+03 6.0E-04 5.9E-01 1.1E+02 FF
    6    1 1.0E+00   5.126498E+03 4.7E-07 2.9E-02 1.0E+02 FF
    7    1 1.0E+00   5.126498E+03 5.9E-10 1.5E-03 1.1E+02 TF
    8    1 1.0E+00   5.126498E+03 1.2E-12 7.6E-09 1.1E+02 TT

 Exit from NP problem after     8 major iterations,
                               21 minor iterations.

 Variable State     Value       Lower Bound  Upper Bound   Lagr Mult  Residual

 Varble 1    BS   0.118876     -0.55000      0.55000     -1.2529E-07  0.4311
 Varble 2    BS  -0.396234     -0.55000      0.55000      1.9245E-08  0.1538
 Varble 3    BS    679.945           .        1200.0      1.7001E-10   520.1
 Varble 4   SBS    1026.07           .        1200.0     -2.1918E-10   173.9

 Constrnt State     Value       Lower Bound  Upper Bound   Lagr Mult  Residual

 NlnCon 1    EQ   -894.800      -894.80      -894.80      -4.387      3.3644E-09
 NlnCon 2    EQ   -894.800      -894.80      -894.80      -4.106      6.0049E-10
 NlnCon 3    EQ   -1294.80      -1294.8      -1294.8      -5.463      3.3551E-09
 LinCon 1    BS  -0.515110     -0.55000          None          .      3.4890E-02
 LinCon 2    BS   0.515110     -0.55000          None          .       1.065
 Free Row    BS    4091.97          None         None     -1.000       4092.

 Exit E04UGF - Optimal solution found.

 Final objective value =     5126.498


e04uhae.r

 E04UHA Example Program Results

 Variable  Istate     Value         Lagr Mult

 Varble  1   1       1.00000        -1.000
 Varble  2   1       2.00000       -0.5000
 Varble  3   1       3.00000       -0.3333
 Varble  4   1       4.00000       -0.2500
 Varble  5   1       5.00000       -0.2000

 Constrnt  Istate     Value         Lagr Mult

 DummyRow    3       0.00000        -1.000

 Final objective value =    1.000000


e04uhfe.r

 E04UHF Example Program Results

 Calls to E04UJF
 ---------------

       Verify Level = -1
       Major Iteration Limit = 25
       Infinite Bound Size = 1.0D+25

 OPTIONS file
 ------------

      Begin * Example options file for E04UHF
         Check Frequency = 25   * (Default = 60 )
         Crash Tolerance = 0.05 * (Default = 0.1)
      End

 Workspace provided is                   IZ(     500),  Z(     500).
 To start solving the problem we need    IZ(     566),  Z(     670).

 Exit E04UGF - Not enough integer workspace to start solving the problem.

 *** E04UGF

 Parameters
 ----------

 Frequencies.
 Check frequency.........        25       Expand frequency.......     10000
 Factorization frequency.       100

 QP subproblems.
 Scale tolerance.........  9.00E-01       Minor feasibility tol..  1.05E-08
 Scale option............         2       Minor optimality tol...  1.05E-08
 Partial price...........        10       Crash tolerance........  5.00E-02
 Pivot tolerance.........  2.04E-11       Minor print level......         0
 Crash option............         3       Elastic weight.........  1.00E+00

 The SQP method.
 Minimize................
 Nonlinear objective vars         5       Major optimality tol...  1.05E-08
 Function precision......  1.72E-13       Unbounded step size....  1.00E+20
 Superbasics limit.......         5       Forward difference int.  4.15E-07
 Unbounded objective.....  1.00E+15       Central difference int.  5.56E-05
 Major step limit........  2.00E+00       Derivative linesearch..
 Derivative level........         3       Major iteration limit..        25
 Linesearch tolerance....  9.00E-01       Verify level...........        -1
 Minor iteration limit...       500       Major print level......        10
 Infinite bound size.....  1.00E+25       Iteration limit........     10000

 Hessian approximation.
 Hessian full memory.....                 Hessian updates........  99999999
 Hessian frequency.......  99999999

 Nonlinear constraints.
 Nonlinear constraints...         0       Nonlinear Jacobian vars         0

 Miscellaneous.
 Variables...............         5       Linear constraints.....         1
 Nonlinear variables.....         5       Linear variables.......         0
 LU factor tolerance.....  1.00E+02       LU singularity tol.....  2.04E-11
 LU update tolerance.....  1.00E+01       LU density tolerance...  6.00E-01
 eps (machine precision).  1.11E-16       Monitoring file........        -1
 COLD start..............                 Infeasible exit........

 Workspace provided is                 IZ(    1132),  Z(    1340).
 To start solving the problem we need  IZ(     566),  Z(     670).

 Itn      0 -- Partial price reduced from               10 to                1.

 Itn      0 -- Feasible linear rows.

 Itn      0 -- Norm(x-x0) minimized. Sum of infeasibilities = 0.00E+00.

 objfun  sets       5   out of       5   objective  gradients.

  Maj  Mnr    Step      Objective Optimal Cond Hz PD
    0    3 0.0E+00   1.866667E+00 3.3E-02 1.0E+00 TF  R
    1    2 1.5E+01   1.550000E+00 7.5E-02 1.0E+00 TF n
    2    2 6.7E+00   1.200000E+00 1.0E-01 1.0E+00 TF n
    3    1 5.0E+00   1.000000E+00 0.0E+00 1.0E+00 TT n

 Exit from NP problem after     3 major iterations,
                                8 minor iterations.

 Variable State     Value       Lower Bound  Upper Bound   Lagr Mult  Residual

 Varble 1    UL    1.00000           .        1.0000      -1.000         .
 Varble 2    UL    2.00000           .        2.0000     -0.5000         .
 Varble 3    UL    3.00000           .        3.0000     -0.3333         .
 Varble 4    UL    4.00000           .        4.0000     -0.2500         .
 Varble 5    UL    5.00000           .        5.0000     -0.2000         .

 Constrnt State     Value       Lower Bound  Upper Bound   Lagr Mult  Residual

 DummyRow    BS    0.00000          None         None     -1.000         .

 Exit E04UGF - Optimal solution found.

 Final objective value =     1.000000


e04uqae.r

 E04UQA Example Program Results

 Varbl  Istate   Value         Lagr Mult

 V   1   0      0.419953         0.000
 V   2   0       1.28485         0.000

 L Con  Istate   Value         Lagr Mult

 L   1   0       1.70480         0.000

 N Con  Istate   Value         Lagr Mult

 N   1   1     -9.767742E-13    3.3358E-02

 Final objective value =   0.1422983E-01


e04uqfe.r

 E04UQF Example Program Results

 Calls to E04URF
 ---------------

       Infinite Bound Size = 1.0D+25
       Print Level = 1
       Verify Level = -1

 OPTIONS file
 ------------

      Begin   Example options file for  E04UQF
         Major Iteration Limit   =  15      *  (Default =  50)
         Minor Iteration Limit   =  10      *  (Default =  50)
      End

 *** E04USF

 Parameters
 ----------

 Linear constraints.....         1       Variables..............         2
 Nonlinear constraints..         1       Subfunctions...........        44

 Infinite bound size....  1.00E+25       COLD start.............
 Infinite step size.....  1.00E+25       EPS (machine precision)  1.11E-16
 Step limit.............  2.00E+00       Hessian................        NO

 Linear feasibility.....  1.05E-08       Crash tolerance........  1.00E-02
 Nonlinear feasibility..  1.05E-08       Optimality tolerance...  3.26E-12
 Line search tolerance..  9.00E-01       Function precision.....  4.37E-15

 Derivative level.......         3       Monitoring file........        -1
 Verify level...........        -1

 Major iterations limit.        15       Major print level......         1
 Minor iterations limit.        10       Minor print level......         0

 J'J initial Hessian....                 Reset frequency........         2

 Workspace provided is     IWORK(       9),  WORK(     306).
 To solve problem we need  IWORK(       9),  WORK(     306).

 Exit from NP problem after     6 major iterations,
                                8 minor iterations.

 Varbl State     Value       Lower Bound   Upper Bound    Lagr Mult   Slack

 V   1    FR   0.419953      0.400000          None           .      1.9953E-02
 V   2    FR    1.28485      -4.00000          None           .       5.285

 L Con State     Value       Lower Bound   Upper Bound    Lagr Mult   Slack

 L   1    FR    1.70480       1.00000          None           .      0.7048

 N Con State     Value       Lower Bound   Upper Bound    Lagr Mult   Slack

 N   1    LL  -9.767742E-13       .            None      3.3358E-02 -9.7677E-13

 Exit E04USF - Optimal solution found.

 Final objective value =   0.1422983E-01


e04usae.r

 E04USA Example Program Results

 Varbl  Istate   Value         Lagr Mult

 V   1   0      0.419953         0.000
 V   2   0       1.28485         0.000

 L Con  Istate   Value         Lagr Mult

 L   1   0       1.70480         0.000

 N Con  Istate   Value         Lagr Mult

 N   1   1     -9.767742E-13    3.3358E-02

 Final objective value =   0.1422983E-01


e04usfe.r

 E04USF Example Program Results

 *** E04USF

 Parameters
 ----------

 Linear constraints.....         1       Variables..............         2
 Nonlinear constraints..         1       Subfunctions...........        44

 Infinite bound size....  1.00E+20       COLD start.............
 Infinite step size.....  1.00E+20       EPS (machine precision)  1.11E-16
 Step limit.............  2.00E+00       Hessian................        NO

 Linear feasibility.....  1.05E-08       Crash tolerance........  1.00E-02
 Nonlinear feasibility..  1.05E-08       Optimality tolerance...  3.26E-12
 Line search tolerance..  9.00E-01       Function precision.....  4.37E-15

 Derivative level.......         3       Monitoring file........        -1
 Verify level...........         0

 Major iterations limit.        50       Major print level......        10
 Minor iterations limit.        50       Minor print level......         0

 J'J initial Hessian....                 Reset frequency........         2

 Workspace provided is     IWORK(       9),  WORK(     306).
 To solve problem we need  IWORK(       9),  WORK(     306).

 Verification of the constraint gradients.
 -----------------------------------------

 The constraint Jacobian seems to be ok.

 The largest relative error was    1.89E-08  in constraint    1

 Verification of the objective gradients.
 ----------------------------------------

 The objective Jacobian seems to be ok.

 The largest relative error was    1.04E-08  in subfunction    3

  Maj  Mnr    Step Merit Function Norm Gz  Violtn Cond Hz
    0    2 0.0E+00   2.224070E-02 8.5E-02 3.6E-02 1.0E+00
    1    1 1.0E+00   1.455402E-02 1.5E-03 9.8E-03 1.0E+00
    2    1 1.0E+00   1.436491E-02 4.9E-03 7.2E-04 1.0E+00
    3    1 1.0E+00   1.427013E-02 2.9E-03 9.2E-06 1.0E+00
    4    1 1.0E+00   1.422989E-02 1.6E-04 3.6E-05 1.0E+00
    5    1 1.0E+00   1.422983E-02 5.4E-07 6.4E-08 1.0E+00
    6    1 1.0E+00   1.422983E-02 3.4E-09 9.8E-13 1.0E+00

 Exit from NP problem after     6 major iterations,
                                8 minor iterations.

 Varbl State     Value       Lower Bound   Upper Bound    Lagr Mult   Slack

 V   1    FR   0.419953      0.400000          None           .      1.9953E-02
 V   2    FR    1.28485      -4.00000          None           .       5.285

 L Con State     Value       Lower Bound   Upper Bound    Lagr Mult   Slack

 L   1    FR    1.70480       1.00000          None           .      0.7048

 N Con State     Value       Lower Bound   Upper Bound    Lagr Mult   Slack

 N   1    LL  -9.767742E-13       .            None      3.3358E-02 -9.7677E-13

 Exit E04USF - Optimal solution found.

 Final objective value =   0.1422983E-01


e04vhfe.r

 E04VHF Example Program Results

 NLP problem contains   4 variables

 Final objective value =      5126.5
 Optimal X =      0.119    -0.396   679.945  1026.067


e04vjfe.r

 E04VJF Example Program Results

 NLP problem contains   4 variables

 NEA (the number of nonzero entries in A) =   4
   I     IAFUN(I)   JAVAR(I)          A(I)
 ----    --------   --------   -----------
   1         4         1       -1.0000E+00
   2         5         1        1.0000E+00
   3         4         2        1.0000E+00
   4         5         2       -1.0000E+00

 NEG (the number of nonzero entries in G) =  10
   I     IGFUN(I)   JGVAR(I)
 ----    --------   --------
   1         1         1
   2         2         1
   3         3         1
   4         1         2
   5         2         2
   6         3         2
   7         6         3
   8         6         4
   9         1         3
  10         2         4

 Final objective value =      5126.5
 Optimal X =    1.189E-01  -3.962E-01   6.799E+02   1.026E+03


e04vkfe.r

 E04VKF Example Program Results

 NLP problem contains   4 variables

 Option 'Elastic mode' has the value   1.
 Option 'Feasibility tolerance' has the value   1.000E-04.

 Final objective value =      5126.5
 Optimal X =    1.189E-01  -3.962E-01   6.799E+02   1.026E+03


e04wdfe.r

 E04WDF Example Program Results

 Parameters
 ==========

 Files
 -----
 Solution file..........         0       Old basis file ........         0       (Print file)...........         6
 Insert file............         0       New basis file ........         0       (Summary file).........         0
 Punch file.............         0       Backup basis file......         0
 Load file..............         0       Dump file..............         0

 Frequencies
 -----------
 Print frequency........       100       Check frequency........        60       Save new basis map.....       100
 Summary frequency......       100       Factorization frequency        50       Expand frequency.......     10000

 QP subproblems
 --------------
 QPsolver Cholesky......
 Scale tolerance........     0.900       Minor feasibility tol..  1.00E-06       Iteration limit........     10000
 Scale option...........         0       Minor optimality  tol..  1.00E-06       Minor print level......         1
 Crash tolerance........     0.100       Pivot tolerance........  2.04E-11       Partial price..........         1
 Crash option...........         3       Elastic weight.........  1.00E+04       Prtl price section ( A)         4
                                         New superbasics........        99       Prtl price section (-I)         3

 The SQP Method
 --------------
 Minimize...............                 Cold start.............                 Proximal Point method..         1
 Nonlinear objectiv vars         4       Major optimality tol...  2.00E-06       Function precision.....  1.72E-13
 Unbounded step size....  1.00E+20       Superbasics limit......         4       Difference interval....  4.15E-07
 Unbounded objective....  1.00E+15       Reduced Hessian dim....         4       Central difference int.  5.57E-05
 Major step limit.......  2.00E+00       Derivative linesearch..                 Derivative level.......         3
 Major iterations limit.      1000       Linesearch tolerance...   0.90000       Verify level...........         0
 Minor iterations limit.       500       Penalty parameter......  0.00E+00       Major Print Level......         1

 Hessian Approximation
 ---------------------
 Full-Memory Hessian....                 Hessian updates........  99999999       Hessian frequency......  99999999
                                                                                Hessian flush..........  99999999

 Nonlinear constraints
 ---------------------
 Nonlinear constraints..         2       Major feasibility tol..  1.00E-06       Violation limit........  1.00E+06
 Nonlinear Jacobian vars         4

 Miscellaneous
 -------------
 LU factor tolerance....      1.10       LU singularity tol.....  2.04E-11       Timing level...........         0
 LU update tolerance....      1.10       LU swap tolerance......  1.03E-04       Debug level............         0
 LU partial  pivoting...                 eps (machine precision)  1.11E-16       System information.....        No

 Matrix statistics
 -----------------
               Total      Normal        Free       Fixed     Bounded
 Rows              3           3           0           0           0
 Columns           4           0           0           0           4

 No. of matrix elements                   12     Density     100.000
 Biggest                          1.0000E+00  (excluding fixed columns,
 Smallest                         0.0000E+00   free rows, and RHS)

 No. of objective coefficients             0

 Nonlinear constraints       2     Linear constraints       1
 Nonlinear variables         4     Linear variables         0
 Jacobian  variables         4     Objective variables      4
 Total constraints           3     Total variables          4

 The user has defined       8   out of       8   constraint gradients.
 The user has defined       4   out of       4   objective  gradients.

 Cheap test of user-supplied problem derivatives...

 The constraint gradients seem to be OK.

 -->  The largest discrepancy was    1.84E-07  in constraint     6

 The objective  gradients seem to be OK.

 Gradient projected in one direction   4.99993000077E+00
 Difference approximation              4.99993303560E+00

   Itns Major Minors    Step   nCon  Feasible   Optimal  MeritFunction     L+U BSwap     nS  condHz Penalty
      2     0      2              1   1.7E+00   2.8E+00  1.6000000E+01       7            2 1.0E+00         _  r
      4     1      2 1.0E+00      2   1.3E-01   3.2E-01  1.7726188E+01       8            1 6.2E+00 8.3E-02 _n r
      5     2      1 1.0E+00      3   3.7E-02   1.7E-01  1.7099571E+01       7            1 2.0E+00 8.3E-02 _s
      6     3      1 1.0E+00      4   2.2E-02   1.1E-02  1.7014005E+01       7            1 1.8E+00 8.3E-02 _
      7     4      1 1.0E+00      5   1.5E-04   6.0E-04  1.7014018E+01       7            1 1.8E+00 9.2E-02 _
      8     5      1 1.0E+00      6 ( 3.3E-07)  2.3E-05  1.7014017E+01       7            1 1.9E+00 3.6E-01 _
      9     6      1 1.0E+00      7 ( 4.2E-10)( 2.4E-08) 1.7014017E+01       7            1 1.9E+00 3.6E-01 _

 E04WDM EXIT   0 -- finished successfully
 E04WDM INFO   1 -- optimality conditions satisfied

 Problem name                      NLP
 No. of iterations                   9   Objective value      1.7014017287E+01
 No. of major iterations             6   Linear objective     0.0000000000E+00
 Penalty parameter           3.599E-01   Nonlinear objective  1.7014017287E+01
 No. of calls to funobj              8   No. of calls to funcon              8
 No. of superbasics                  1   No. of basic nonlinears             2
 No. of degenerate steps             0   Percentage                       0.00
 Max x                       2 4.7E+00   Max pi                      2 5.5E-01
 Max Primal infeas           0 0.0E+00   Max Dual infeas             3 4.8E-08
 Nonlinear constraint violn    2.7E-09

 Variable         State      Value       Lower bound     Upper bound   Lagr multiplier       Slack

 variable     1     LL    1.000000        1.000000        5.000000        1.087871            .
 variable     2     FR    4.743000        1.000000        5.000000            .             0.2570
 variable     3     FR    3.821150        1.000000        5.000000            .              1.179
 variable     4     FR    1.379408        1.000000        5.000000            .             0.3794

 Linear constrnt  State      Value       Lower bound     Upper bound   Lagr multiplier       Slack

 lincon       1     FR    10.94356          None          20.00000            .              9.056

 Nonlin constrnt  State      Value       Lower bound     Upper bound   Lagr multiplier       Slack

 nlncon       1     UL    40.00000          None          40.00000      -0.1614686         -0.2700E-08
 nlncon       2     LL    25.00000        25.00000          None         0.5522937         -0.2215E-08

 Final objective value =      17.014
 Optimal X =      1.00     4.74     3.82     1.38


e04wefe.r

 E04WEF Example Program Results

 OPTIONS file
 ------------

      Begin example options file
      * Comment lines like this begin with an asterisk.
      * Switch off output of timing information:
      Timing level 0
      * Allow elastic variables:
      Elastic mode 1
      * Set the feasibility tolerance:
      Feasibility tolerance 1.0D-4
      End

 E04WEZ EXIT 100 -- finished successfully
 E04WEZ INFO 101 -- OPTIONS file read

 Option 'Elastic mode' has the value   1.
 Option 'Feasibility tolerance' has the value   1.00000E-04.

 Parameters
 ==========

 Files
 -----
 Solution file..........         0       Old basis file ........         0       (Print file)...........         6
 Insert file............         0       New basis file ........         0       (Summary file).........         0
 Punch file.............         0       Backup basis file......         0
 Load file..............         0       Dump file..............         0

 Frequencies
 -----------
 Print frequency........       100       Check frequency........        60       Save new basis map.....       100
 Summary frequency......       100       Factorization frequency        50       Expand frequency.......     10000

 QP subproblems
 --------------
 QPsolver Cholesky......
 Scale tolerance........     0.900       Minor feasibility tol..  1.00E-04       Iteration limit........     10000
 Scale option...........         0       Minor optimality  tol..  1.00E-06       Minor print level......         1
 Crash tolerance........     0.100       Pivot tolerance........  2.04E-11       Partial price..........         1
 Crash option...........         3       Elastic weight.........  1.00E+04       Prtl price section ( A)         4
                                         New superbasics........        99       Prtl price section (-I)         3

 The SQP Method
 --------------
 Minimize...............                 Cold start.............                 Proximal Point method..         1
 Nonlinear objectiv vars         4       Major optimality tol...  2.00E-06       Function precision.....  1.72E-13
 Unbounded step size....  1.00E+10       Superbasics limit......         4       Difference interval....  4.15E-07
 Unbounded objective....  1.00E+15       Reduced Hessian dim....         4       Central difference int.  5.57E-05
 Major step limit.......  2.00E+00       Derivative linesearch..                 Derivative level.......         3
 Major iterations limit.        50       Linesearch tolerance...   0.90000       Verify level...........         0
 Minor iterations limit.       500       Penalty parameter......  0.00E+00       Major Print Level......         1

 Hessian Approximation
 ---------------------
 Full-Memory Hessian....                 Hessian updates........  99999999       Hessian frequency......  99999999
                                                                                Hessian flush..........  99999999

 Nonlinear constraints
 ---------------------
 Nonlinear constraints..         2       Major feasibility tol..  1.00E-06       Violation limit........  1.00E+06
 Nonlinear Jacobian vars         4

 Miscellaneous
 -------------
 LU factor tolerance....      1.10       LU singularity tol.....  2.04E-11       Timing level...........         0
 LU update tolerance....      1.10       LU swap tolerance......  1.03E-04       Debug level............         0
 LU partial  pivoting...                 eps (machine precision)  1.11E-16       System information.....        No

 Matrix statistics
 -----------------
               Total      Normal        Free       Fixed     Bounded
 Rows              3           3           0           0           0
 Columns           4           0           0           0           4

 No. of matrix elements                   12     Density     100.000
 Biggest                          1.0000E+00  (excluding fixed columns,
 Smallest                         0.0000E+00   free rows, and RHS)

 No. of objective coefficients             0

 Nonlinear constraints       2     Linear constraints       1
 Nonlinear variables         4     Linear variables         0
 Jacobian  variables         4     Objective variables      4
 Total constraints           3     Total variables          4

 The user has defined       8   out of       8   constraint gradients.
 The user has defined       4   out of       4   objective  gradients.

 Cheap test of user-supplied problem derivatives...

 The constraint gradients seem to be OK.

 -->  The largest discrepancy was    1.84E-07  in constraint     6

 The objective  gradients seem to be OK.

 Gradient projected in one direction   4.99993000077E+00
 Difference approximation              4.99993303560E+00

   Itns Major Minors    Step   nCon  Feasible   Optimal  MeritFunction     L+U BSwap     nS  condHz Penalty
      2     0      2              1   1.7E+00   2.8E+00  1.6000000E+01       7            2 1.0E+00         _  r
      4     1      2 1.0E+00      2   1.3E-01   3.2E-01  1.7726188E+01       8            1 6.2E+00 8.3E-02 _n r
      5     2      1 1.0E+00      3   3.7E-02   1.7E-01  1.7099571E+01       7            1 2.0E+00 8.3E-02 _s
      6     3      1 1.0E+00      4   2.2E-02   1.1E-02  1.7014005E+01       7            1 1.8E+00 8.3E-02 _
      7     4      1 1.0E+00      5   1.5E-04   6.0E-04  1.7014018E+01       7            1 1.8E+00 9.2E-02 _
      8     5      1 1.0E+00      6 ( 3.3E-07)  2.3E-05  1.7014017E+01       7            1 1.9E+00 3.6E-01 _
      9     6      1 1.0E+00      7 ( 4.2E-10)( 2.4E-08) 1.7014017E+01       7            1 1.9E+00 3.6E-01 _

 E04WDM EXIT   0 -- finished successfully
 E04WDM INFO   1 -- optimality conditions satisfied

 Problem name                      NLP
 No. of iterations                   9   Objective value      1.7014017287E+01
 No. of major iterations             6   Linear objective     0.0000000000E+00
 Penalty parameter           3.599E-01   Nonlinear objective  1.7014017287E+01
 No. of calls to funobj              8   No. of calls to funcon              8
 No. of superbasics                  1   No. of basic nonlinears             2
 No. of degenerate steps             0   Percentage                       0.00
 Max x                       2 4.7E+00   Max pi                      2 5.5E-01
 Max Primal infeas           0 0.0E+00   Max Dual infeas             3 4.8E-08
 Nonlinear constraint violn    2.7E-09

 Variable         State      Value       Lower bound     Upper bound   Lagr multiplier       Slack

 variable     1     LL    1.000000        1.000000        5.000000        1.087871            .
 variable     2     FR    4.743000        1.000000        5.000000            .             0.2570
 variable     3     FR    3.821150        1.000000        5.000000            .              1.179
 variable     4     FR    1.379408        1.000000        5.000000            .             0.3794

 Linear constrnt  State      Value       Lower bound     Upper bound   Lagr multiplier       Slack

 lincon       1     FR    10.94356          None          20.00000            .              9.056

 Nonlin constrnt  State      Value       Lower bound     Upper bound   Lagr multiplier       Slack

 nlncon       1     UL    40.00000          None          40.00000      -0.1614686         -0.2700E-08
 nlncon       2     LL    25.00000        25.00000          None         0.5522937         -0.2215E-08

 Final objective value =      17.014
 Optimal X =      1.00     4.74     3.82     1.38


e04xaae.r

 E04XAA Example Program Results

 Find gradients and Hessian diagonals given function only
 ( i.e. MODE = 0 ).
 Function value is    1.550E+02
 Estimated gradient vector is
    2.400E+01   -2.680E+02    2.160E+02   -4.000E+01
 Estimated Hessian matrix diagonal is
    1.220E+02    3.080E+02    4.420E+02    1.300E+02

 Find Hessian matrix given function and gradients
 ( i.e. MODE = 1 ).
 Function value is    1.550E+02
 Gradient vector is
    2.400E+01   -2.680E+02    2.160E+02   -4.000E+01
 Estimated Hessian matrix (machine dependent) is
    1.220E+02    2.000E+01    0.000E+00   -1.200E+02
    2.000E+01    3.080E+02   -2.160E+02    0.000E+00
    0.000E+00   -2.160E+02    4.420E+02   -1.000E+01
   -1.200E+02    0.000E+00   -1.000E+01    1.300E+02

 Find gradients and Hessian matrix given function only
 ( i.e. MODE = 2 ).
 Function value is    1.550E+02
 Estimated gradient vector is
    2.400E+01   -2.680E+02    2.160E+02   -4.000E+01
 Estimated Hessian matrix (machine dependent) is
    1.220E+02    2.000E+01   -4.404E-03   -1.200E+02
    2.000E+01    3.080E+02   -2.160E+02    6.605E-03
   -4.404E-03   -2.160E+02    4.420E+02   -1.000E+01
   -1.200E+02    6.605E-03   -1.000E+01    1.300E+02


e04xafe.r

 E04XAF Example Program Results

 Find gradients and Hessian diagonals given function only
 ( i.e. MODE = 0 ).
 Function value is    1.550E+02
 Estimated gradient vector is
    2.400E+01   -2.680E+02    2.160E+02   -4.000E+01
 Estimated Hessian matrix diagonal is
    1.220E+02    3.080E+02    4.420E+02    1.300E+02

 Find Hessian matrix given function and gradients
 ( i.e. MODE = 1 ).
 Function value is    1.550E+02
 Gradient vector is
    2.400E+01   -2.680E+02    2.160E+02   -4.000E+01
 Estimated Hessian matrix (machine dependent) is
    1.220E+02    2.000E+01    0.000E+00   -1.200E+02
    2.000E+01    3.080E+02   -2.160E+02    0.000E+00
    0.000E+00   -2.160E+02    4.420E+02   -1.000E+01
   -1.200E+02    0.000E+00   -1.000E+01    1.300E+02

 Find gradients and Hessian matrix given function only
 ( i.e. MODE = 2 ).
 Function value is    1.550E+02
 Estimated gradient vector is
    2.400E+01   -2.680E+02    2.160E+02   -4.000E+01
 Estimated Hessian matrix (machine dependent) is
    1.220E+02    2.000E+01   -4.404E-03   -1.200E+02
    2.000E+01    3.080E+02   -2.160E+02    6.605E-03
   -4.404E-03   -2.160E+02    4.420E+02   -1.000E+01
   -1.200E+02    6.605E-03   -1.000E+01    1.300E+02


e04ybfe.r

 E04YBF Example Program Results

 The test point is
    0.19000  -1.34000   0.88000

 The matrix B is consistent with 1st derivatives

 At the test point, LSQFUN gives

       Residuals                   1st derivatives
      -2.029E-03      1.000E+00     -4.061E-02     -2.707E-03
      -1.076E-01      1.000E+00     -9.689E-02     -1.384E-02
      -2.330E-01      1.000E+00     -1.785E-01     -4.120E-02
      -3.785E-01      1.000E+00     -3.043E-01     -1.014E-01
      -5.836E-01      1.000E+00     -5.144E-01     -2.338E-01
      -8.689E-01      1.000E+00     -9.100E-01     -5.460E-01
      -1.346E+00      1.000E+00     -1.810E+00     -1.408E+00
      -2.374E+00      1.000E+00     -4.726E+00     -4.726E+00
      -2.975E+00      1.000E+00     -6.076E+00     -6.076E+00
      -4.013E+00      1.000E+00     -7.876E+00     -7.876E+00
      -5.323E+00      1.000E+00     -1.040E+01     -1.040E+01
      -7.292E+00      1.000E+00     -1.418E+01     -1.418E+01
      -1.057E+01      1.000E+00     -2.048E+01     -2.048E+01
      -1.713E+01      1.000E+00     -3.308E+01     -3.308E+01
      -3.681E+01      1.000E+00     -7.089E+01     -7.089E+01

 and LSQHES gives the lower triangle of the matrix B

       0.000E+00
       0.000E+00      1.571E+04
       0.000E+00      1.571E+04      1.571E+04


e04ycfe.r

 E04YCF Example Program Results

 On exit, the sum of squares is      0.0082
 at the point
       0.0824      1.1330      2.3437

 and estimates of the variances of the sample
 regression coefficients are
       0.0002      0.0948      0.0878


e05jbfe.r

 E05JBF Example Program Results

 (OBJFUN was just called for the first time)

 *** Begin monitoring information ***

 Values controlling initial splitting of a box:
 **
 In dimension     1
 Extent of initialization list in this dimension =    3
 Initialization points in this dimension:
 LIST(I,1:NUMPTS(I)) = -3.00000  0.00000  3.00000
 Initial point in this dimension: LIST(I,    2)
 **
 In dimension     2
 Extent of initialization list in this dimension =    3
 Initialization points in this dimension:
 LIST(I,1:NUMPTS(I)) = -3.00000  0.00000  3.00000
 Initial point in this dimension: LIST(I,    2)
 Total sub-boxes =  228
 Total function evaluations (rounded to nearest 10) =  200
 Total function evaluations used in local search (rounded
   to nearest 10) =   90
 Total points used in local search =   13
 Total sweeps through levels =   12
 Total splits by init. list =    5
 Lowest level with nonsplit boxes =    7
 Number of candidate minima in the "shopping basket" =    2
 Shopping basket:
 XBASKT(  1,:) = -1.34740  0.22828
 XBASKT(  2,:) =  0.20452 -1.62553
 Best point:
 XBEST =  0.22828 -1.62553

 *** End monitoring information ***

 Final objective value =   -6.55113
 Global optimum X =  0.22828 -1.62553


e05jcfe.r

 E05JCF Example Program Results

 Option "Local Searches Limit" has the value     40.
 Option "Infinite Bound Size" holds its default value.
 Option "Local Searches Tolerance" has the value   0.14901E-07.
 Option "Local Searches" has the value "ON".

 (OBJFUN was just called for the first time)

 *** Begin monitoring information ***

 Values controlling initial splitting of a box:
 **
 In dimension     1
 Extent of initialization list in this dimension =    3
 Initialization points in this dimension:
 LIST(I,1:NUMPTS(I)) = -3.00000 -1.00000  3.00000
 Initial point in this dimension: LIST(I,    2)
 **
 In dimension     2
 Extent of initialization list in this dimension =    3
 Initialization points in this dimension:
 LIST(I,1:NUMPTS(I)) = -3.00000  0.00000  3.00000
 Initial point in this dimension: LIST(I,    2)
 Total sub-boxes =  180
 Total function evaluations (rounded to nearest 10) =  190
 Total function evaluations used in local search (rounded
   to nearest 10) =  100
 Total points used in local search =    9
 Total sweeps through levels =    9
 Total splits by init. list =    5
 Lowest level with nonsplit boxes =    6
 Number of candidate minima in the "shopping basket" =    2
 Shopping basket:
 XBASKT(  1,:) =  0.22828 -1.34740
 XBASKT(  2,:) = -1.62553  0.20452
 Best point:
 XBEST =  0.22828 -1.62553

 *** End monitoring information ***

 Final objective value =   -6.55113
 Global optimum X =  0.22828 -1.62553


e05safe.r

 E05SAF Example Program Results

 Minimization of the Schwefel function.

   Default Option Queries:

   Boundary                             :                 FLOATING
   Maximum Iterations Completed         :          1000   DEFAULT
   Distance Tolerance                   :        0.0001

 1. Solution without using coupled local minimizer.

  Algorithm Statistics
  --------------------
  Total complete iterations             :           395
  Complete iterations since improvement :           152
  Total particles converged to xb       :             2
  Total improvements to global optimum  :            59
  Total function evaluations            :          2773
  Total particles re-initialized        :             2

  Solution Status :          Maximum static iterations attained

  Known objective optimum               :    -837.96577
  Achieved objective value              :    -837.96567

  Comparison between known and achieved optima.
        x_target          xb
  1      -420.97     -420.95
  2      -420.97     -420.94

 2. Solution using coupled local minimizer E04CBF

  Algorithm Statistics
  --------------------
  Total complete iterations             :            51
  Complete iterations since improvement :             1
  Total particles converged to xb       :             0
  Total improvements to global optimum  :            12
  Total function evaluations            :           537
  Total particles re-initialized        :             0

  Solution Status :                       Target value achieved

  Known objective optimum               :    -837.96577
  Achieved objective value              :    -837.96577

  Comparison between known and achieved optima.
        x_target          xb
  1      -420.97     -420.97
  2      -420.97     -420.97

 3. Solution using coupled local minimizer E04DGF

  Algorithm Statistics
  --------------------
  Total complete iterations             :           123
  Complete iterations since improvement :             1
  Total particles converged to xb       :             0
  Total improvements to global optimum  :            10
  Total function evaluations            :           898
  Total particles re-initialized        :             0

  Solution Status :                       Target value achieved

  Known objective optimum               :    -837.96577
  Achieved objective value              :    -837.96568

  Comparison between known and achieved optima.
        x_target          xb
  1      -420.97     -420.95
  2      -420.97     -420.95


e05safe_smp.r

 E05SAF Example Program Results

 Minimization of the Schwefel function.

 * Solution without using coupled local minimizer *
  Total complete iterations             :             2245
  Complete iterations since improvement :                1
  Total particles converged to xb       :                0
  Total improvements to global optimum  :             1573
  Total function evaluations            :          9882001
  Total particles re-initialized        :                0

                        Target value achieved

  Known objective optimum  :       0.00000
  Achieved objective value :       0.86400
  Comparison between known and achieved optima.
     x_target       xb
  1   -420.97  -420.54
  2   -420.97  -421.09
  3   -420.97  -420.70
  4   -420.97  -420.94
  5   -420.97  -421.14
  6   -420.97  -420.93
  7   -420.97  -420.59
  8   -420.97  -421.20
  9   -420.97  -421.04
 10   -420.97  -422.64
 11   -420.97  -420.43
 12   -420.97  -421.07
 13   -420.97  -421.31
 14   -420.97  -421.50
 15   -420.97  -422.12
 16   -420.97  -420.96
 17   -420.97  -421.22
 18   -420.97  -421.05
 19   -420.97  -421.92
 20   -420.97  -421.70
**--------------------**--------------------**

 * Solution using coupled local minimizer E04JYF *
  Total complete iterations             :             1075
  Complete iterations since improvement :                1
  Total particles converged to xb       :                0
  Total improvements to global optimum  :               50
  Total function evaluations            :          4742115
  Total particles re-initialized        :                0

                        Target value achieved

  Known objective optimum  :       0.00000
  Achieved objective value :      -0.00000
  Comparison between known and achieved optima.
     x_target       xb
  1   -420.97  -420.97
  2   -420.97  -420.97
  3   -420.97  -420.97
  4   -420.97  -420.97
  5   -420.97  -420.97
  6   -420.97  -420.97
  7   -420.97  -420.97
  8   -420.97  -420.97
  9   -420.97  -420.97
 10   -420.97  -420.97
 11   -420.97  -420.97
 12   -420.97  -420.97
 13   -420.97  -420.97
 14   -420.97  -420.97
 15   -420.97  -420.97
 16   -420.97  -420.97
 17   -420.97  -420.97
 18   -420.97  -420.97
 19   -420.97  -420.97
 20   -420.97  -420.97
**--------------------**--------------------**

 * Solution using coupled local minimizer E04UCF *
  Total complete iterations             :             1387
  Complete iterations since improvement :                1
  Total particles converged to xb       :                0
  Total improvements to global optimum  :               64
  Total function evaluations            :          6107056
  Total particles re-initialized        :                0

                        Target value achieved

  Known objective optimum  :       0.00000
  Achieved objective value :       0.00000
  Comparison between known and achieved optima.
     x_target       xb
  1   -420.97  -420.97
  2   -420.97  -420.97
  3   -420.97  -420.97
  4   -420.97  -420.97
  5   -420.97  -420.97
  6   -420.97  -420.97
  7   -420.97  -420.97
  8   -420.97  -420.97
  9   -420.97  -420.97
 10   -420.97  -420.97
 11   -420.97  -420.97
 12   -420.97  -420.97
 13   -420.97  -420.97
 14   -420.97  -420.97
 15   -420.97  -420.97
 16   -420.97  -420.97
 17   -420.97  -420.97
 18   -420.97  -420.97
 19   -420.97  -420.97
 20   -420.97  -420.97
**--------------------**--------------------**


e05sbfe.r

 E05SBF Example Program Results

 Minimization of the Schwefel function.
 Subject to one linear and two nonlinear constraints.

   Default Option Queries:

   Constraint Norm                         :                 L1
   Maximum Iterations Completed            :          1000   DEFAULT
   Distance Tolerance                      :        0.0001

 1. Solution without using coupled local minimizer

  Algorithm Statistics
  --------------------
  Total complete iterations                :          277
  Complete iterations since improvement    :            1
  Total particles converged to xb          :            0
  Total improvements to global optimum     :          117
  Total function evaluations               :         4222
  Total particles re-initialized           :            0
  Total constraints violated               :            0

  Solution Status :                  Target value achieved

  Known unconstrained objective minimum    :      -837.966
  Best Known constrained objective minimum :      -731.707
  Achieved objective value                 :      -731.708

  Comparison between known and achieved optima.
      x_target_u  x_target_c          xb
  1      -420.97     -394.15     -394.17
  2      -420.97     -433.48     -433.53

  Comparison between scaled constraint violations.
      c_target_u  c_target_c          cb
  1      0.00000     0.00000     0.00000
  2      0.04219     0.00000     0.00000
  3      0.75749     0.00000     0.00002

 2. Solution using coupled local minimizer E04UCF

  Algorithm Statistics
  --------------------
  Total complete iterations                :            4
  Complete iterations since improvement    :            1
  Total particles converged to xb          :            0
  Total improvements to global optimum     :            7
  Total function evaluations               :          155
  Total particles re-initialized           :            0
  Total constraints violated               :            0

  Solution Status :                  Target value achieved

  Known unconstrained objective minimum    :      -837.966
  Best Known constrained objective minimum :      -731.707
  Achieved objective value                 :      -731.706

  Comparison between known and achieved optima.
      x_target_u  x_target_c          xb
  1      -420.97     -394.15     -394.15
  2      -420.97     -433.48     -433.49

  Comparison between scaled constraint violations.
      c_target_u  c_target_c          cb
  1      0.00000     0.00000     0.00000
  2      0.04219     0.00000     0.00000
  3      0.75749     0.00000     0.00000


e05ucfe.r

 E05UCF Example Program Results

 Solution number               1

 Local minimization exited with code    0

 Varbl  Istate   Value         Lagr Mult

 V   1   0       -394.1514        0.0000
 V   2   0       -433.4910        0.0000

 L Con  Istate   Value         Lagr Mult

 L   1   0       -315.4722        0.0000

 N Con  Istate   Value         Lagr Mult

 N   1   0     480024.1075        0.0000
 N   2   2          0.9000     -718.9448

 Final objective value =     -731.7064

 QP multipliers
       0.0000
       0.0000
       0.0000
       0.0000
    -718.9448

  ------------------------------------------------------

 Solution number               2

 Local minimization exited with code    0

 Varbl  Istate   Value         Lagr Mult

 V   1   0       -394.1504        0.0000
 V   2   0       -433.4891        0.0000

 L Con  Istate   Value         Lagr Mult

 L   1   0       -315.4731        0.0000

 N Con  Istate   Value         Lagr Mult

 N   1   0     480021.5064        0.0000
 N   2   2          0.9000     -718.9558

 Final objective value =     -731.7064

 QP multipliers
       0.0000
       0.0000
       0.0000
       0.0000
    -718.9558

  ------------------------------------------------------


e05usfe.r

 E05USF Example Program Results

 Solution number               1

 Local minimization exited with code    0

 Varbl  Istate   Value         Lagr Mult

 V   1   0          0.4200        0.0000
 V   2   0          1.2848        0.0000

 L Con  Istate   Value         Lagr Mult

 L   1   0          1.7048        0.0000

 N Con  Istate   Value         Lagr Mult

 N   1   1         -0.0000        0.0334

 Final objective value =        0.0142

 QP multipliers
       0.0000
       0.0000
       0.0000
       0.0334


f01abfe.r

 F01ABF Example Program Results

 Lower triangle of inverse
             1          2          3          4
 1     68.0000
 2    -41.0000    25.0000
 3    -17.0000    10.0000     5.0000
 4     10.0000    -6.0000    -3.0000     2.0000


f01adfe.r

 F01ADF Example Program Results

 Lower triangle of inverse
             1          2          3          4
 1
 2     68.0000
 3    -41.0000    25.0000
 4    -17.0000    10.0000     5.0000
 5     10.0000    -6.0000    -3.0000     2.0000


f01blfe.r

 F01BLF Example Program Results

 Maximum element in A(K) for I.GE.K and J.GE.K

    K    Modulus
    1    9.0000E+00
    2    9.3101E+00
    3    8.7461E+00
    4    5.6832E+00
    5    2.8449E-16

 Rank =     4

 T =  2.9948E-15  (machine dependent)

 Transpose of pseudo-inverse
    1.7807E-02 -2.1565E-02  5.2029E-02  2.3686E-02  7.1957E-03
   -1.1826E-02  4.3417E-02 -8.1265E-02  3.5717E-02 -1.3957E-03
    4.7157E-02  2.9446E-02  1.3926E-02 -1.3808E-02  7.6720E-03
   -5.6636E-02  2.9132E-02  4.7442E-02  3.0478E-02  5.0415E-03
   -3.6741E-03 -1.3781E-02  1.6647E-02  3.5665E-02  3.4857E-03
    3.8408E-02  3.4256E-02  5.7594E-02 -5.7134E-02  7.3123E-03


f01brfe.r

 F01BRF Example Program Results

 Number of nonzeros in decomposition         =   16
 Minimum size of array IRN                    =   15
 Minimum size of arrays A and ICN             =   19
 Number of compresses on IRN (IDISP(3))       =    0
 Number of compresses on A and ICN (IDISP(4)) =    0

 Value of W(1) = 18.0000

 Structural rank                =    6
 Number of diagonal blocks      =    3
 Size of largest diagonal block =    4


f01bsfe.r

 F01BSF Example Program Results

 On exit from F01BRF
 Value of W(1)  = 18.0000

 On exit from F01BSF
 Value of W(1)  = 51.0000

 Value of RPMIN =  0.1000


f01bufe.r

 F01BUF Example Program Results

 Computed upper triangular matrix

    3.0000
   -3.0000   4.0000
    2.0000   4.0000   2.0000
   -1.0000   5.0000   3.0000
    3.0000  -4.0000   5.0000
    2.0000  -1.0000   2.0000
   -3.0000   4.0000   6.0000


f01bvfe.r

 F01BVF Example Program Results

 Selected eigenvalues
   -0.2643  -0.1530  -0.0418


f01ckfe.r

 F01CKF Example Program Results

 Matrix A
      5.0    8.0
      8.0   14.0


f01crfe.r

 F01CRF Example Program Results

     1.0    4.0    7.0   10.0   13.0   16.0   19.0
     2.0    5.0    8.0   11.0   14.0   17.0   20.0
     3.0    6.0    9.0   12.0   15.0   18.0   21.0


f01ctfe.r

 F01CTF Example Program Results

 TRANSA = 'N', TRANSB = 'N', ALPHA =   1.000E+00, BETA =   1.000E+00
 Matrix C:
             1          2          3
 1      3.0000     0.0000     1.0000
 2     -1.0000     3.0000    -0.5000
 3      2.0000     4.5000    -5.0000
 4      3.5000    -4.0000     2.0000

 TRANSA = 'N', TRANSB = 'T', ALPHA =   1.000E+00, BETA =  -1.000E+00
 Matrix C:
             1          2          3          4          5
 1     -1.0000     1.5000     4.5000    -0.5000     1.5000
 2      0.5000     1.0000    -4.0000     0.0000    -2.0000
 3      5.5000     1.0000     0.0000    -2.5000     0.0000


f01ecfe.r

 F01ECF Example Program Results

 Exp(A)
             1          2          3          4
 1    740.7038   610.8500   542.2743   549.1753
 2    731.2510   603.5524   535.0884   542.2743
 3    823.7630   679.4257   603.5524   610.8500
 4    998.4355   823.7630   731.2510   740.7038


f01edfe.r

 F01EDF Example Program Results

 Symmetric Exp(A)
             1          2          3          4
 1   2675.3899  2193.0210  2193.2062  2675.2803
 2              1798.3297  1797.8497  2193.2062
 3                         1798.3297  2193.0210
 4                                    2675.3899


f01effe.r

 F01EFF Example Program Results

 Symmetric f(A)
          1       2       3       4
 1  -0.5420 -0.6612 -0.0261  0.1580
 2           0.2306 -0.3396 -0.0261
 3                   0.2306 -0.6612
 4                          -0.5420


f01ejfe.r

 F01EJF Example Program Results

 log(A)
             1          2          3          4
 1      1.1957    -1.2076    -0.5802     1.0872
 2      0.8464     1.0133    -0.5985    -0.1641
 3      0.4389     0.6701     1.8449    -1.2111
 4      1.2792     0.6177     2.1448    -1.9743


f01ekfe.r

 F01EKF Example Program Results

 F(A) = COS (A)
             1          2          3          4
 1     -0.2998     1.5003    -0.7849     0.4677
 2     -0.2385    -3.2657     0.5812    -1.1460
 3      0.4677     0.3008    -4.0853    -0.2200
 4     -0.2107    -2.8199    -1.2964    -0.8325

 Imnorm =  0.00


f01elfe.r

 F01ELF Example Program Results

 F(A) = COS(2A)
             1          2          3          4
 1     -0.1704    -1.1597    -0.1878    -0.7307
 2     -0.3950    -0.4410     0.7606     0.0655
 3     -0.0950    -0.0717     0.0619    -0.4351
 4     -0.1034     0.6424    -1.3964     0.1042

 Imnorm =  0.00


f01emfe.r

 F01EMF Example Program Results

 F(A) = EXP(2A)
             1          2          3          4
 1    -12.1880     0.0000    -3.4747     8.3697
 2    -13.7274    54.5982   -23.9801    82.8593
 3     -9.7900     0.0000   -25.4527    26.5294
 4    -18.1597     0.0000   -34.8991    49.2404

 Imnorm =  0.00


f01enfe.r

 F01ENF Example Program Results

 sqrt(A)
               1            2            3            4
 1    1.5000E+01   1.4000E+01   8.0000E+00  -6.0000E+00
 2    6.0000E+00   1.4000E+01   3.0000E+00   9.6589E-15
 3    2.1000E+01   2.4000E+01   1.2000E+01  -8.0000E+00
 4   -5.0000E+00  -4.0000E+00  -7.0000E+00   8.0000E+00


f01epfe.r

 F01EPF Example Program Results

 sqrt(A)
               1            2            3            4
 1    2.0000E+00   1.0000E+00  -2.0000E+00   3.0000E+00
 2    2.0000E+00   2.0000E+00   3.1721E-16   1.0000E+00
 3    0.0000E+00   0.0000E+00   2.0000E+00  -1.0000E+00
 4    0.0000E+00   0.0000E+00   1.0000E+00   2.0000E+00


f01eqfe.r

 F01EQF Example Program Results

 A^p
             1          2          3          4
 1      1.2446     0.2375     0.2172    -0.1359
 2      0.0925     1.1239    -0.1453     0.3731
 3     -0.0769     0.1972     1.3131     0.1837
 4      0.3985    -0.2902     0.1085     1.1560


f01fdfe.r

 F01FDF Example Program Results

 Hermitian Exp(A)
               1            2            3            4
 1    1.1457E+04   8.7983E+03   7.8120E+03   8.3103E+03
      0.0000E+00   2.0776E+03   4.5500E+03   7.8871E+03

 2                 7.1339E+03   6.8242E+03   7.8120E+03
                   0.0000E+00   2.0776E+03   4.5500E+03

 3                              7.1339E+03   8.7983E+03
                                0.0000E+00   2.0776E+03

 4                                           1.1457E+04
                                             0.0000E+00


f01fffe.r

 F01FFF Example Program Results

 Hermitian f(A)
          1       2       3       4
 1   0.0904 -0.3377 -0.1009 -0.1092
     0.0000 -0.0273 -0.0594 -0.1586

 2           0.4265 -0.3139 -0.1009
             0.0000 -0.0273 -0.0594

 3                   0.4265 -0.3377
                     0.0000 -0.0273

 4                           0.0904
                             0.0000


f01gafe.r

 F01GAF Example Program Results

 exp(tA)B
             1          2
 1      0.2138     7.6756
 2      4.9980    11.6051
 3      0.8307     7.5468
 4      1.2406     9.7261


f01gbfe.r

 F01GBF Example Program Results

 exp(tA)B
             1          2
 1      0.1933     0.7812
 2      1.4423    -0.4055
 3     -1.0756     0.6686
 4      0.0276     0.4900


f01hafe.r

 F01HAF Example Program Results

 exp(tA)B
             1          2
 1      0.4251    -0.0220
       -0.1061     0.3289

 2      0.7229    -1.7931
       -0.5940     1.4952

 3     -0.1394     1.4781
       -0.1151    -0.4514

 4      0.1054    -1.0059
       -0.0786    -0.7079


f01hbfe.r

 F01HBF Example Program Results

 exp(tA)B
             1          2
 1    -15.3125    -4.5605
        5.9123    -2.4288

 2     12.3396     9.2005
      -50.6993   -10.3632

 3    -65.4353   -17.6075
       34.3271    -1.0019

 4     45.6506    11.3339
      -28.3253     0.1127


f01jafe.r

 F01JAF Example Program Results

 A
             1          2          3          4
 1      2.0000     1.0000     3.0000     1.0000
 2      3.0000    -1.0000     0.0000     2.0000
 3      1.0000     0.0000     3.0000     1.0000
 4      1.0000     2.0000     0.0000     3.0000

 F(A) = SINH(A)
 Estimated absolute condition number is:  204.45
 Estimated relative condition number is:    7.90


f01jbfe.r

 F01JBF Example Program Results

 A
             1          2          3          4
 1     -1.0000    -1.0000    -2.0000     1.0000
 2      0.0000     1.0000    -1.0000     0.0000
 3     -1.0000    -2.0000     1.0000    -1.0000
 4      0.0000    -1.0000     0.0000    -1.0000

 F(A) = cos(2A)
 Estimated absolute condition number is:   4.10
 Estimated relative condition number is:  14.48


f01jcfe.r

 F01JCF Example Program Results

 A
             1          2          3          4
 1      0.0000    -1.0000    -1.0000     1.0000
 2     -2.0000     0.0000     1.0000    -1.0000
 3      2.0000    -1.0000     2.0000    -2.0000
 4     -1.0000    -2.0000     0.0000    -1.0000

 F(A) = exp(2A)
 Estimated absolute condition number is:  183.90
 Estimated relative condition number is:   13.90


f01jdfe.r

 F01JDF Example Program Results

 sqrt(A)
             1          2          3          4
 1      1.0000     2.0000    -1.0000    -1.0000
 2     -3.0000     1.0000     2.0000     4.0000
 3     -2.0000     3.0000     1.0000     2.0000
 4      2.0000    -1.0000     3.0000     4.0000

 Estimated relative condition number is:  77.10
 Condition number for the relative residual is:   1.70


f01jefe.r

 F01JEF Example Program Results

 A^p
             1          2          3          4
 1      1.2368     0.1977     0.1749    -0.0314
 2     -0.0543     1.1643    -0.0947     0.3145
 3      0.0537     0.3514     1.3254     0.0214
 4      0.3339    -0.2125     0.1880     1.0581

 Estimated condition number is:   2.75


f01jgfe.r

 F01JGF Example Program Results

 Exp(A)
             1          2          3          4
 1    404.4441   412.6036   496.7221   398.3043
 2    474.4388   482.8457   579.1310   460.6474
 3    466.9764   477.2769   574.3994   458.3804
 4    407.7005   420.8935   510.1939   410.4808

 Estimated condition number is:   9.40


f01jjfe.r

 F01JJF Example Program Results

 log(A)
             1          2          3          4
 1      1.4081    -0.2051    -0.1071     0.1904
 2      0.4396     1.7096    -0.5147     0.2226
 3      0.2560     0.2613     1.2485    -0.2413
 4      0.3030    -0.0107     0.3834     2.0891

 Estimated condition number is:   5.50


f01kafe.r

 F01KAF Example Program Results

 A
             1          2          3          4
 1      0.0000    -1.0000     1.0000     2.0000
        1.0000     0.0000     0.0000     0.0000

 2      2.0000     0.0000     0.0000     1.0000
        1.0000    -1.0000     0.0000     0.0000

 3      0.0000     0.0000     1.0000     0.0000
        1.0000     0.0000     1.0000     2.0000

 4      1.0000     2.0000    -2.0000     0.0000
        0.0000     0.0000     3.0000     1.0000

 F(A) = SINH(A)
 Estimated absolute condition number is:   7.33
 Estimated relative condition number is:   4.94


f01kbfe.r

 F01KBF Example Program Results

 A
             1          2          3          4
 1      2.0000     0.0000     1.0000     0.0000
        0.0000     1.0000     1.0000     3.0000

 2      1.0000     0.0000     2.0000     0.0000
        1.0000     2.0000     2.0000     0.0000

 3      0.0000     2.0000     1.0000     1.0000
        0.0000     0.0000     2.0000     0.0000

 4      1.0000     3.0000     0.0000     1.0000
        1.0000     0.0000     0.0000     2.0000

 F(A) = sin(2A)
 Estimated absolute condition number is: 2016.99
 Estimated relative condition number is:   12.86


f01kcfe.r

 F01KCF Example Program Results

 A
             1          2          3          4
 1      1.0000     0.0000     1.0000     2.0000
        1.0000     1.0000     0.0000     0.0000

 2      0.0000     2.0000     0.0000     1.0000
        0.0000     0.0000     2.0000     0.0000

 3      0.0000     0.0000     0.0000     2.0000
        1.0000     1.0000     0.0000     0.0000

 4      1.0000     0.0000     1.0000     0.0000
        0.0000     1.0000     0.0000     1.0000

 F(A) = exp(3A)
 Estimated absolute condition number is: 9474.43
 Estimated relative condition number is:   13.74


f01kdfe.r

 F01KDF Example Program Results

 sqrt(A)
               1            2            3            4
 1    2.0000E+00   1.0000E+00  -2.0000E+00  -2.0000E+00
      3.0000E+00   8.0000E+00  -7.5495E-15   1.0000E+00

 2    5.0000E+00   7.0000E+00   7.0000E+00   3.9968E-15
     -4.0000E+00  -6.0000E+00   6.0000E+00   3.5527E-15

 3    1.0000E+00   2.0000E+00   4.0000E+00  -2.0000E+00
     -2.0000E+00   1.0000E+00   1.0000E+00   2.0000E+00

 4   -3.0000E+00  -2.0000E+00  -7.0000E+00   6.0000E+00
      7.0000E+00   2.0000E+00  -1.0000E+00   2.0000E+00

 Estimated relative condition number is:  21.17
 Condition number for the relative residual is:   1.86


f01kefe.r

 F01KEF Example Program Results

 A^p
             1          2          3          4
 1      0.9742     0.8977     0.6389     0.0975
        0.5211    -0.1170    -0.3900     0.6205

 2      0.1586     1.0176     0.0623     0.6431
        0.2763    -0.0250    -0.3471     0.2560

 3      0.2589     0.5633     1.1470    -0.3771
       -0.5817     0.3969     0.4042     0.3113

 4      0.8713    -0.5734     0.2816     1.3568
       -0.0270     0.0868     0.3739    -0.2709

 Estimated condition number is:   6.86


f01kjfe.r

 F01KJF Example Program Results

 log(A)
             1          2          3          4
 1      1.4498     0.3665     0.1358     0.4890
        0.5154     0.6955    -0.1097     0.1622

 2     -0.9351     1.2908     0.1010     0.3128
        0.2859    -2.8365    -0.0672     0.2538

 3     -0.1399    -0.3208     1.2738     0.2658
       -0.1083    -0.8912     0.5775     0.3127

 4      0.3049    -0.4858     0.1797     1.1843
       -0.0019     0.3215    -0.1922     0.9427

 Estimated condition number is:   2.25


f01lefe.r

 F01LEF Example Program Results

 Details of factorization

  Main diagonal of U
    3.0000   3.6000   7.0000  -6.0000   1.1508

  First superdiagonal of U
    2.1000  -5.0000  -0.9000   7.1000

  Second superdiagonal of U
    0.0000   1.9000   8.0000

  Multipliers
    1.1333  -0.0222  -0.1587   0.0168

  Vector of interchanges
         0        1        1        1

  Solution vector
   -4.0000   7.0000   3.0000  -4.0000  -3.0000


f01lhfe.r

 F01LHF Example Program Results

 Component Solution
              1
  1      1.0000
  2      1.0000
  3      1.0000
  4      1.0000
  5      1.0000
  6      1.0000
  7      1.0000
  8      1.0000
  9      1.0000
 10      1.0000
 11      1.0000
 12      1.0000
 13      1.0000
 14      1.0000
 15      1.0000
 16      1.0000
 17      1.0000
 18      1.0000


f01mcfe.r

 F01MCF Example Program Results

   I    D(I)   Row I of unit lower triangle

   1   1.000   1.000
   2   1.000   2.000   1.000
   3   4.000   3.000   1.000
   4  16.000   1.000
   5   1.000   5.000   4.000   1.500   0.500   1.000
   6  16.000   1.500   5.000   1.000


f01qgfe.r

 F01QGF Example Program Results

 RQ factorization of A

 Vector ZETA
   1.2649   1.3416   1.1547

 Matrix A after factorization (R is in left-hand upper triangle)
   -4.0000 -1.0000 -1.0000  0.6325 -0.0000
    0.0000 -2.0000  0.0000  0.0000 -0.4472
    0.0000  0.0000 -3.0000  0.5774  0.5774


f01qjfe.r

 F01QJF Example Program Results

 RQ factorization of A

 Vector ZETA
   1.0092   1.2981   1.2329

 Matrix A after factorization (R is in left-hand upper triangle)
   -3.1446 -1.0705 -2.2283  0.6333  0.7619
    0.5277 -2.8345 -2.2283 -0.1662  0.0945
    0.3766  0.3766 -5.3852  0.0753 -0.4368


f01qkfe.r

 F01QKF Example Program Results

 Matrix  P
  -0.1310  -0.5170  -0.4642  -0.5054  -0.4946
  -0.1310  -0.5170  -0.4642   0.5054   0.4946
  -0.3276   0.5499  -0.5199  -0.3957   0.4043
  -0.6551   0.2494  -0.0928   0.4946  -0.5054
  -0.6551  -0.3175   0.5385  -0.2967   0.3032


f01rgfe.r

 F01RGF Example Program Results

 RQ factorization of A

 Vector THETA
  ( 1.2924, -0.0000) ( 1.3861, -0.0000) ( 1.1867, -0.0000)

 Matrix A after factorization (R is in left-hand upper triangle)
   (-3.5808, 0.0000) ( 0.2533,-0.9059) (-2.2862,-0.6532) ( 0.5120, 0.2601)
   ( 0.0000, 0.0000) (-1.7369, 0.0000) (-0.4491,-0.6940) (-0.2544,-0.1187)
   ( 0.0000, 0.0000) ( 0.0000, 0.0000) (-2.4495, 0.0000) ( 0.6880, 0.3440)


f01rjfe.r

 F01RJF Example Program Results

 RQ factorization of A

 Vector THETA
 ( 1.039,-0.101) ( 1.181, 0.381) ( 1.224,-0.000)

 Matrix A after factorization (R is in left-hand upper triangle)
   ( 0.788, 0.000) (-0.255,-0.401) (-0.277,-0.277) (-0.285, 0.559) ( 0.115, 0.703)
   ( 0.040, 0.522) (-2.112, 0.000) (-1.109,-0.555) ( 0.128, 0.232) ( 0.079,-0.036)
   (-0.227, 0.227) ( 0.045, 0.317) (-3.606, 0.000) ( 0.000,-0.000) ( 0.000, 0.544)


f01vafe.r

 F01VAF Example Program Results

 Unpacked Matrix A:
       1    2    3    4
 1  1.10 1.20 1.30 1.40
 2       2.20 2.30 2.40
 3            3.30 3.40
 4                 4.40

 Packed Matrix AP:
  1  1.10
  2  1.20
  3  2.20
  4  1.30
  5  2.30
  6  3.30
  7  1.40
  8  2.40
  9  3.40
 10  4.40


f01vcfe.r

 F01VCF Example Program Results

 Packed Matrix AP:
  1  1.10
  2  1.20
  3  2.20
  4  1.30
  5  2.30
  6  3.30
  7  1.40
  8  2.40
  9  3.40
 10  4.40

 Unpacked Matrix A:
       1    2    3    4
 1  1.10 1.20 1.30 1.40
 2       2.20 2.30 2.40
 3            3.30 3.40
 4                 4.40


f01vefe.r

 F01VEF Example Program Results

 Unpacked Matrix A:
       1    2    3    4
 1  1.10 1.20 1.30 1.40
 2       2.20 2.30 2.40
 3            3.30 3.40
 4                 4.40

 RFP Packed Array AR:
  1  1.30
  2  2.30
  3  3.30
  4  1.10
  5  1.20
  6  1.40
  7  2.40
  8  3.40
  9  4.40
 10  2.20

 RFP Packed Array AR (graphical representation):
       1    2
 1  1.30 1.40
 2  2.30 2.40
 3  3.30 3.40
 4  1.10 4.40
 5  1.20 2.20


f01vgfe.r

 F01VGF Example Program Results

 RFP Packed Array AR:
  1  1.30
  2  2.30
  3  3.30
  4  1.10
  5  1.20
  6  1.40
  7  2.40
  8  3.40
  9  4.40
 10  2.20

 Unpacked Matrix A:
       1    2    3    4
 1  1.10 1.20 1.30 1.40
 2       2.20 2.30 2.40
 3            3.30 3.40
 4                 4.40


f01vjfe.r

 F01VJF Example Program Results

 Packed Array AP:
  1  1.10
  2  1.20
  3  2.20
  4  1.30
  5  2.30
  6  3.30
  7  1.40
  8  2.40
  9  3.40
 10  4.40

 RFP Packed Array AR:
  1  1.30
  2  2.30
  3  3.30
  4  1.10
  5  1.20
  6  1.40
  7  2.40
  8  3.40
  9  4.40
 10  2.20

 RFP Packed Array AR (graphical representation):
       1    2
 1  1.30 1.40
 2  2.30 2.40
 3  3.30 3.40
 4  1.10 4.40
 5  1.20 2.20


f01vlfe.r

 F01VLF Example Program Results

 RFP Packed Array AR:
  1  1.30
  2  2.30
  3  3.30
  4  1.10
  5  1.20
  6  1.40
  7  2.40
  8  3.40
  9  4.40
 10  2.20

 Packed Array AP:
  1  1.10
  2  1.20
  3  2.20
  4  1.30
  5  2.30
  6  3.30
  7  1.40
  8  2.40
  9  3.40
 10  4.40


f01zafe.r

 F01ZAF Example Program Results

 Unpacked Matrix A:
       1    2    3    4
 1  1.10 1.20 1.30 1.40
 2       2.20 2.30 2.40
 3            3.30 3.40
 4                 4.40

 Packed Vector B:
  1  1.10
  2  1.20
  3  2.20
  4  1.30
  5  2.30
  6  3.30
  7  1.40
  8  2.40
  9  3.40
 10  4.40


f02ecfe.r

 F02ECF Example Program Results

 Eigenvalues
    (-0.0994, 0.4008) (-0.0994,-0.4008)

 Eigenvectors
                    1                 2
 1  (-0.1933, 0.2546) (-0.1933,-0.2546)
 2  ( 0.2519,-0.5224) ( 0.2519, 0.5224)
 3  ( 0.0972,-0.3084) ( 0.0972, 0.3084)
 4  ( 0.6760, 0.0000) ( 0.6760,-0.0000)


f02ekfe.r

 F02EKF Example Program Results

  Arnoldi basis vectors used:  20
  The following Ritz values (mu) are related to the
  true eigenvalues (lambda) by lambda = sigma + 1/mu

  Iteration number    1
  Ritz values converged so far (   2) and their Ritz estimates:
     1 (  0.56992E+00,  0.88081E+00)   0.13008E-19
     2 (  0.56992E+00, -0.88081E+00)   0.13008E-19
  Next (unconverged) Ritz value:
     3 (  0.60777E+00,  0.00000E+00)

 The    5 Ritz values of closest to   0.55000E+01 are:

        1     (   0.60178E+01 ,  -0.80028E+00 )
        2     (   0.60178E+01 ,   0.80028E+00 )
        3     (   0.43431E+01 ,  -0.19456E+01 )
        4     (   0.43431E+01 ,   0.19456E+01 )
        5     (   0.71453E+01 ,   0.00000E+00 )


f02fkfe.r

 F02FKF Example Program Results

  Ritz values and residuals
               1            2
 1    1.9702E+01   5.6583E-13
 2    4.9036E+01   7.2456E-13
 3    4.9036E+01   7.0022E-13
 4    7.8370E+01   8.8089E-13
 5    9.7197E+01   8.7693E-13
 6    9.7197E+01   8.7672E-13
 7    1.2653E+02   6.8423E-13
 8    1.2653E+02   9.8310E-13


f02gcfe.r

 F02GCF Example Program Results

 Eigenvalues
    (-5.0000, 2.0060) ( 3.0023,-3.9998)

 Eigenvectors
                    1                 2
 1  (-0.3865, 0.1732) (-0.0356,-0.1782)
 2  (-0.3539, 0.4529) ( 0.1264, 0.2666)
 3  ( 0.6124, 0.0000) ( 0.0129,-0.2966)
 4  (-0.0859,-0.3284) ( 0.8898, 0.0000)


f02jcfe.r

 F02JCF Example Program Results

 Eigenvalue(  1) = (-3.8513E+00,  0.0000E+00)
 Eigenvalue(  2) = (-5.9217E-01,  8.0280E-01)
 Eigenvalue(  3) = (-5.9217E-01, -8.0280E-01)
 Eigenvalue(  4) = ( 5.2326E-01,  6.2251E-01)
 Eigenvalue(  5) = ( 5.2326E-01, -6.2251E-01)
 Eigenvalue(  6) = ( 7.8909E-01,  0.0000E+00)

 Right eigenvectors (matrix VR)
          1       2       3       4       5       6
 1  -0.2108  0.3751 -0.1877 -0.6593  0.0424 -0.3478
 2   0.7695  0.5020 -0.2433  0.0302  0.0197  0.8277
 3  -0.6028  0.7162  0.0000  0.7498  0.0000 -0.4405

 Left eigenvectors (matrix VL)
          1       2       3       4       5       6
 1   0.1052  0.7816  0.0000  0.8079  0.0000  0.0358
 2   0.7381  0.5075 -0.1352 -0.1124 -0.0314  0.7072
 3  -0.6664  0.3202 -0.1038 -0.5704  0.0913 -0.7061

 Eigenvalue Condition numbers
  2.3092E+00
  7.0275E-01
  7.0275E-01
  2.7013E+00
  2.7013E+00
  2.0144E+00

 Backward errors for eigenvalues and right eigenvectors
  1.1321E-16
  5.1930E-16
  5.1930E-16
  2.4397E-16
  2.4397E-16
  1.3853E-16

 Backward errors for eigenvalues and left eigenvectors
  9.5738E-17
  5.2313E-16
  5.2313E-16
  1.8837E-16
  1.8837E-16
  3.7483E-16


f02sdfe.r

 F02SDF Example Program Results

 Corrected eigenvalue = -12.3394

 Eigenvector is
   -0.0572   0.3951  -0.8427   1.0000  -0.6540


f02wgfe.r

 F02WGF Example Program Results

   Singular Value    Residual
    0.00830          0.27E-18
    0.01223          0.59E-17
    0.02381          0.12E-16
    0.11274          0.78E-16


f02wufe.r

 F02WUF Example Program Results

 Singular value decomposition of A

 Singular values
    6.5616   3.0000   2.4384

 Left-hand singular vectors, by column
   -0.7699  0.5883 -0.2471
   -0.4324 -0.1961  0.8801
   -0.4694 -0.7845 -0.4054

 Right-hand singular vectors, by column
    0.4694  -0.7845   0.4054
    0.4324  -0.1961  -0.8801
    0.7699   0.5883   0.2471

 Vector Q'*B
    1.6716   0.3922  -0.2276


f02xufe.r

 F02XUF Example Program Results

 Singular value decomposition of A

 Singular values
    3.9263   2.0000   0.7641

 Left-hand singular vectors, by column
   (-0.5005,-0.0000) (-0.4529, 0.0000) ( 0.7378, 0.0000)
   ( 0.5152,-0.1514) ( 0.1132,-0.5661) ( 0.4190,-0.4502)
   ( 0.4041,-0.5457) ( 0.0000, 0.6794) ( 0.2741, 0.0468)

 Right-hand singular vectors, by column
   (-0.1275, -0.0000) (-0.2265, -0.0000) ( 0.9656, -0.0000)
   (-0.3899,  0.2046) (-0.3397,  0.7926) (-0.1311,  0.2129)
   (-0.5289,  0.7142) (-0.0000, -0.4529) (-0.0698, -0.0119)

 Vector conjg( Q' )*B
   (-1.9656, -0.7935) ( 0.1132, -0.3397) ( 0.0915,  0.6086)


f03bafe.r

 F03BAF Example Program Results

 Array A after factorization
             1          2          3
 1     33.0000    16.0000    72.0000
 2     -0.7273     1.6364    -4.6364
 3     -0.2424    -0.0741     0.1111

 Pivots
              1             2             3

 D =       0.37500 ID =            4

 Value of determinant =   0.60000E+01


f03bffe.r

 F03BFF Example Program Results

 Array A after factorization
             1          2          3          4
 1      2.4495
 2      2.8577     1.6833
 3      2.4495     0.5941     2.1557
 4      2.0412     0.6931     1.6645     1.8927

 D =       0.06909 ID =           12

 Value of determinant =   0.28300E+03


f03bhfe.r

 F03BHF Example Program Results

 Array AB after factorization
             1          2          3          4          5          6          7
 1      2.2361
 2     -1.7889     1.6733
 3      0.4472    -1.9124     1.4639
 4                 0.5976    -1.9518     1.3540
 5                            0.6831    -1.9695     1.2863
 6                                       0.7385    -1.9789     1.2403
 7                                                  0.7774    -1.9846     0.6761

 D =       0.25000 ID = 8

 Value of determinant =   0.64000E+02


f03bnfe.r

 F03BNF Example Program Results

 Array A after factorization
             1          2          3
 1      1.0000     0.0000    -5.0000
        1.0000     3.0000    14.0000

 2      1.0000     0.0000    -3.0000
        0.0000     2.0000     6.0000

 3      0.5000     0.2500    -0.2500
       -0.5000     0.2500    -0.2500

 Pivots
              2             3             3

 D = (      0.06250,      0.00000), ID = (4, 0)

 Value of determinant = (  0.10000E+01,  0.00000E+00)


f04abfe.r

 F04ABF Example Program Results

  Solution
    1.0000
    1.0000
    1.0000
    1.0000


f04aefe.r

 F04AEF Example Program Results

  Solution
    1.0000
   -2.0000
   -5.0000


f04amfe.r

 F04AMF Example Program Results

  Solution
    1.3010
    0.7935


f04asfe.r

 F04ASF Example Program Results

  Solution
    1.0000
    1.0000
    1.0000
    1.0000


f04atfe.r

 F04ATF Example Program Results

  Solution
    1.0000
   -2.0000
   -5.0000


f04axfe.r

 F04AXF Example Program Results

 On exit from F01BRF
 Value of W(1) =   18.0000

 On exit from F04AXF
  Solution
    3.0000
    3.0000
    6.0000
    6.0000
    3.0000
    1.0000


f04bafe.r

 F04BAF Example Program Results

 Solution
             1          2
 1      1.0000     3.0000
 2     -1.0000     2.0000
 3      3.0000     4.0000
 4     -5.0000     1.0000

 Estimate of condition number
        1.5E+02

 Estimate of error bound for computed solutions
        1.7E-14


f04bbfe.r

 F04BBF Example Program Results

 Solution
             1          2
 1     -2.0000     1.0000
 2      3.0000    -4.0000
 3      1.0000     7.0000
 4     -4.0000    -2.0000

 Estimate of condition number
        5.6E+01

 Estimate of error bound for computed solutions
        6.3E-15


f04bcfe.r

 F04BCF Example Program Results

 Solution
             1          2
 1     -4.0000     5.0000
 2      7.0000    -4.0000
 3      3.0000    -3.0000
 4     -4.0000    -2.0000
 5     -3.0000     1.0000

 Estimate of condition number
        9.3E+01

 Estimate of error bound for computed solutions
        1.0E-14


f04bdfe.r

 F04BDF Example Program Results

 Solution
             1          2
 1      1.0000     4.0000
 2     -1.0000     3.0000
 3      2.0000     2.0000
 4     -3.0000     1.0000

 Estimate of condition number
        9.7E+01

 Estimate of error bound for computed solutions
        1.1E-14


f04befe.r

 F04BEF Example Program Results

 Solution
             1          2
 1      1.0000     4.0000
 2     -1.0000     3.0000
 3      2.0000     2.0000
 4     -3.0000     1.0000

 Estimate of condition number
        9.7E+01

 Estimate of error bound for computed solutions
        1.1E-14


f04bffe.r

 F04BFF Example Program Results

 Solution
             1          2
 1      5.0000    -2.0000
 2     -2.0000     6.0000
 3     -3.0000    -1.0000
 4      1.0000     4.0000

 Estimate of condition number
        7.4E+01

 Estimate of error bound for computed solutions
        8.2E-15


f04bgfe.r

 F04BGF Example Program Results

 Solution
             1          2
 1      2.5000     2.0000
 2      2.0000    -1.0000
 3      1.0000    -3.0000
 4     -1.0000     6.0000
 5      3.0000    -5.0000

 Estimate of condition number
        1.1E+02

 Estimate of error bound for computed solutions
        1.2E-14


f04bhfe.r

 F04BHF Example Program Results

 Solution
             1          2
 1     -5.0000     2.0000
 2     -2.0000     3.0000
 3      1.0000     4.0000
 4      4.0000     1.0000

 Estimate of condition number
        7.6E+01

 Estimate of error bound for computed solutions
        8.4E-15


f04bjfe.r

 F04BJF Example Program Results

 Solution
             1          2
 1     -5.0000     2.0000
 2     -2.0000     3.0000
 3      1.0000     4.0000
 4      4.0000     1.0000

 Estimate of condition number
        7.6E+01

 Estimate of error bound for computed solutions
        8.4E-15


f04cafe.r

 F04CAF Example Program Results

 Solution
                            1                         2
 1  (     1.0000,     1.0000) (    -1.0000,    -2.0000)
 2  (     2.0000,    -3.0000) (     5.0000,     1.0000)
 3  (    -4.0000,    -5.0000) (    -3.0000,     4.0000)
 4  (     0.0000,     6.0000) (     2.0000,    -3.0000)

 Estimate of condition number
          1.5E+02

 Estimate of error bound for computed solutions
          1.7E-14


f04cbfe.r

 F04CBF Example Program Results

 Solution
                    1                 2
 1  (-3.0000, 2.0000) ( 1.0000, 6.0000)
 2  ( 1.0000,-7.0000) (-7.0000,-4.0000)
 3  (-5.0000, 4.0000) ( 3.0000, 5.0000)
 4  ( 6.0000,-8.0000) (-8.0000, 2.0000)

 Estimate of condition number
      1.0E+02

 Estimate of error bound for computed solutions
      1.2E-14


f04ccfe.r

 F04CCF Example Program Results

 Solution
                            1                         2
 1  (     1.0000,     1.0000) (     2.0000,    -1.0000)
 2  (     3.0000,    -1.0000) (     1.0000,     2.0000)
 3  (     4.0000,     5.0000) (    -1.0000,     1.0000)
 4  (    -1.0000,    -2.0000) (     2.0000,     1.0000)
 5  (     1.0000,    -1.0000) (     2.0000,    -2.0000)

 Estimate of condition number
          1.8E+02

 Estimate of error bound for computed solutions
          2.0E-14


f04cdfe.r

 F04CDF Example Program Results

 Solution
                            1                         2
 1  (     1.0000,    -1.0000) (    -1.0000,     2.0000)
 2  (    -0.0000,     3.0000) (     3.0000,    -4.0000)
 3  (    -4.0000,    -5.0000) (    -2.0000,     3.0000)
 4  (     2.0000,     1.0000) (     4.0000,    -5.0000)

 Estimate of condition number
          1.5E+02

 Estimate of error bound for computed solutions
          1.7E-14


f04cefe.r

 F04CEF Example Program Results

 Solution
                    1                 2
 1  ( 1.0000,-1.0000) (-1.0000, 2.0000)
 2  (-0.0000, 3.0000) ( 3.0000,-4.0000)
 3  (-4.0000,-5.0000) (-2.0000, 3.0000)
 4  ( 2.0000, 1.0000) ( 4.0000,-5.0000)

 Estimate of condition number
      1.5E+02

 Estimate of error bound for computed solutions
      1.7E-14


f04cffe.r

 F04CFF Example Program Results

 Solution
                    1                 2
 1  (-1.0000, 8.0000) ( 5.0000,-6.0000)
 2  ( 2.0000,-3.0000) ( 2.0000, 3.0000)
 3  (-4.0000,-5.0000) (-8.0000, 4.0000)
 4  ( 7.0000, 6.0000) (-1.0000,-7.0000)

 Estimate of condition number
      1.3E+02

 Estimate of error bound for computed solutions
      1.5E-14


f04cgfe.r

 F04CGF Example Program Results

 Solution
                            1                         2
 1  (     2.0000,     1.0000) (    -3.0000,    -2.0000)
 2  (     1.0000,     1.0000) (     1.0000,     1.0000)
 3  (     1.0000,    -2.0000) (     1.0000,    -2.0000)
 4  (     1.0000,    -1.0000) (     2.0000,     1.0000)

 Estimate of condition number
          9.2E+03

 Estimate of error bound for computed solutions
          1.0E-12


f04chfe.r

 F04CHF Example Program Results

 Solution
                            1                         2
 1  (     2.0000,     1.0000) (    -8.0000,     6.0000)
 2  (     3.0000,    -2.0000) (     7.0000,    -2.0000)
 3  (    -1.0000,     2.0000) (    -1.0000,     5.0000)
 4  (     1.0000,    -1.0000) (     3.0000,    -4.0000)

 Estimate of condition number
          6.7E+00

 Estimate of error bound for computed solutions
          7.4E-16


f04cjfe.r

 F04CJF Example Program Results

 Solution
                            1                         2
 1  (     2.0000,     1.0000) (    -8.0000,     6.0000)
 2  (     3.0000,    -2.0000) (     7.0000,    -2.0000)
 3  (    -1.0000,     2.0000) (    -1.0000,     5.0000)
 4  (     1.0000,    -1.0000) (     3.0000,    -4.0000)

 Estimate of condition number
          6.7E+00

 Estimate of error bound for computed solutions
          7.4E-16


f04dhfe.r

 F04DHF Example Program Results

 Solution
                            1                         2
 1  (    -4.0000,     3.0000) (    -1.0000,     1.0000)
 2  (     3.0000,    -2.0000) (     3.0000,     2.0000)
 3  (    -2.0000,     5.0000) (     1.0000,    -3.0000)
 4  (     1.0000,    -1.0000) (    -2.0000,    -1.0000)

 Estimate of condition number
          2.1E+01

 Estimate of error bound for computed solutions
          2.3E-15


f04djfe.r

 F04DJF Example Program Results

 Solution
                            1                         2
 1  (    -4.0000,     3.0000) (    -1.0000,     1.0000)
 2  (     3.0000,    -2.0000) (     3.0000,     2.0000)
 3  (    -2.0000,     5.0000) (     1.0000,    -3.0000)
 4  (     1.0000,    -1.0000) (    -2.0000,    -1.0000)

 Estimate of condition number
          2.1E+01

 Estimate of error bound for computed solutions
          2.3E-15


f04fefe.r

 F04FEF Example Program Results

 Solution vector
   -0.8000   0.0000  -0.0000   0.2000

 Reflection coefficients
   -0.7500   0.1429   0.1667   0.2000

 Mean square prediction errors
    0.4375   0.4286   0.4167   0.4000


f04fffe.r

 F04FFF Example Program Results

 Solution vector
    0.2000   0.0000  -0.0000   0.2000

 Reflection coefficients
   -0.7500   0.1429   0.1667


f04jgfe.r

 F04JGF Example Program Results

 Solution vector
     4.967   -2.833    4.567    3.233

 Standard error =  0.909    Rank =  3

 SVD =  T


f04lefe.r

 F04LEF Example Program Results

 Solution vector for T*X = Y
    -4.000    7.000    3.000   -4.000   -3.000

 Solution vector for transpose(T)*X = Y
    -4.630    4.880   -0.555    0.672   -0.377


f04lhfe.r

 F04LHF Example Program Results

 Component Solution
     1       1.0000
     2       1.0000
     3       1.0000
     4       1.0000
     5       1.0000
     6       1.0000
     7       1.0000
     8       1.0000
     9       1.0000
    10       1.0000
    11       1.0000
    12       1.0000
    13       1.0000
    14       1.0000
    15       1.0000
    16       1.0000
    17       1.0000
    18       1.0000


f04mcfe.r

 F04MCF Example Program Results

  Solution
    -3.000    4.000
     2.000   -2.000
    -1.000    3.000
    -2.000    1.000
     1.000   -2.000
     1.000    1.000


f04mefe.r

 F04MEF Example Program Results

 Solution for system of order    1
   -0.7500
 Mean square prediction error
    0.4375

 Solution for system of order    2
   -0.8571   0.1429
 Mean square prediction error
    0.4286

 Solution for system of order    3
   -0.8333   0.0000   0.1667
 Mean square prediction error
    0.4167

 Solution for system of order    4
   -0.8000   0.0000  -0.0000   0.2000
 Mean square prediction error
    0.4000


f04mffe.r

 F04MFF Example Program Results

 Solution for system of order    1
    0.2500

 Solution for system of order    2
    0.1429   0.1429
 Reflection coefficient
   -0.7500

 Solution for system of order    3
    0.1667   0.0000   0.1667
 Reflection coefficient
    0.1429

 Solution for system of order    4
    0.2000   0.0000  -0.0000   0.2000
 Reflection coefficient
    0.1667


f04qafe.r

 F04QAF Example Program Results

 Output from sparse linear least squares solver.

 Least squares solution of  A*x = b

 The matrix A has     13 rows and     12 cols
 The damping parameter is  damp =      0.00E+00

 atol =     1.00E-05     conlim =      1.00E+05
 btol =     1.00E-04     itnlim =    100

 No. of iterations  =      2
 stopping condition =      2
 ( The least squares solution is good enough, given atol )

 Actual        norm(rbar), norm(x)            1.15E-02    4.33E+00
    Norm(transpose(Abar)*rbar)                9.16E-15
 Estimates of  norm(Abar), cond(Abar)         4.12E+00    2.45E+00

 Solution returned by F04QAF
     1.250    1.250    1.250    1.247    1.247
     1.250    1.250    1.247    1.247    1.250
     1.250    1.250

 Norm of the residual =     1.15E-02


f04yafe.r

 F04YAF Example Program Results

 SIGMA =   0.4123  Rank =  3  SVD =  F

 Solution vector
    0.9533  -0.8433   0.9067

 Estimated variances of regression coefficients
    0.0106   0.0093   0.0045


f04ydfe.r

 F04YDF Example Program Results
 Example 1

 The norm of A is:  18.20
 The estimated norm of inverse(A) is:   2.97

 Estimated condition number of A:  54.14

 Example 2

 The norm of A is:   6.00
 The estimated norm of inverse(A) is:   3.37

 Estimated condition number of A:  20.20


f04zdfe.r

 F04ZDF Example Program Results

 The norm of A is:  16.11
 The estimated norm of inverse(A) is:  24.02

 Estimated condition number of A: 387.08


f05aafe.r

 F05AAF Example Program Results

 N1 =  2  N2 =  4

 CC =  0.5822 ICOL =  4

 Final vectors
   -0.6325   0.3310  -0.5404
    0.3162  -0.2483   0.2119
   -0.6325  -0.0000   0.7735
    0.3162   0.9104   0.2543


f06wafe.r

 F06WAF Example Program Results

 Norms of symmetric matrix stored in RFP format in ar:

 One norm           =   36.0000
 Infinity norm      =   36.0000
 Frobenius norm     =   28.1247
 Maximum norm       =    6.0000


f06wbfe.r

 F06WBF Example Program Results

 The Solution
             1          2          3          4
 1     13.5562     5.7677     9.7251     1.2209
 2    -10.1040    -1.9787    -8.9252    -4.4205
 3     -0.8280     0.2386     2.0348     2.0769
 4      2.8488    -7.1745    -3.7925    -2.9505
 5     -3.9321     0.8652    -1.4082     3.1217
 6     -2.3127     1.8398     2.0152     1.5198


f06wcfe.r

 F06WCF Example Program Results

 The Solution
             1          2          3          4          5          6
 1     74.3339
 2     35.9614    38.3792
 3     61.9998    46.3791    72.2571
 4     44.8769    40.1617    13.6156   220.8276
 5    -18.4440    -2.9162   -37.3241   101.0169    85.3835
 6    -18.2242   -13.5482   -19.1635   -21.4356     9.1315    16.5209


f06wnfe.r

 F06WNF Example Program Results

 Norms of Hermitian matrix stored in RFP format in ar:

 One norm           =   50.9719
 Infinity norm      =   50.9719
 Frobenius norm     =   40.3801
 Maximum norm       =    9.1439


f06wpfe.r

 F06WPF Example Program Results

 The Solution
             1          2          3
 1     -2.0339     8.6009     3.8676
        2.6429     4.3188     2.2452

 2      4.3280     1.0930     3.3517
       -4.3756    -8.8840    -0.0650

 3      2.5393    -0.9711    -2.0155
       -0.1237     2.5460    -1.5364

 4     -0.3229     0.1410     0.7955
        1.0621     1.2554    -0.8975


f06wqfe.r

 F06WQF Example Program Results

 The Solution
             1          2          3          4
 1     55.1885
        0.0000

 2     17.5536    40.2153
       -9.2637     0.0000

 3     22.7883    14.2818   156.4204
      -59.3437    11.3638    -0.0000

 4    -19.8678    11.4084     7.0222    62.2194
        3.9432     9.7064   -44.0297    -0.0000


f07aafe.r

 F07AAF Example Program Results

 Solution
        1.0000    -1.0000     3.0000    -5.0000

 Details of factorization
             1          2          3          4
 1      5.2500    -2.9500    -0.9500    -3.8000
 2      0.3429     3.8914     2.3757     0.4129
 3      0.3010    -0.4631    -1.5139     0.2948
 4     -0.2114    -0.3299     0.0047     0.1314

 Pivot indices
             2          2          3          4


f07abfe.r

 F07ABF Example Program Results

 Solution(s)
             1          2
 1      1.0000     3.0000
 2     -1.0000     2.0000
 3      3.0000     4.0000
 4     -5.0000     1.0000

 Backward errors (machine-dependent)
       6.8E-17    9.1E-17

 Estimated forward error bounds (machine-dependent)
       2.4E-14    3.6E-14

 A has been row scaled as diag(R)*A

 Reciprocal condition number estimate of scaled matrix
       1.8E-02

 Estimate of reciprocal pivot growth factor
       7.4E-01


f07acfe.r

 F07ACF Example Program Results

 Solution
        1.0000    -1.0000     3.0000    -5.0000

 Pivot indices
             2          2          3          4


f07adfe.r

 F07ADF Example Program Results

 Details of factorization
             1          2          3          4
 1      5.2500    -2.9500    -0.9500    -3.8000
 2      0.3429     3.8914     2.3757     0.4129
 3      0.3010    -0.4631    -1.5139     0.2948
 4     -0.2114    -0.3299     0.0047     0.1314

 IPIV
             2          2          3          4


f07aefe.r

 F07AEF Example Program Results

 Solution(s)
             1          2
 1      1.0000     3.0000
 2     -1.0000     2.0000
 3      3.0000     4.0000
 4     -5.0000     1.0000


f07affe.r

 F07AFF Example Program Results

 Matrix A
               1            2            3            4
 1    1.8000E+10   2.8800E+10   2.0500E+00  -8.9000E+09
 2    5.2500E+00  -2.9500E+00  -9.5000E-09  -3.8000E+00
 3    1.5800E+00  -2.6900E+00  -2.9000E-10  -1.0400E+00
 4   -1.1100E+00  -6.6000E-01  -5.9000E-11   8.0000E-01

 ROWCND = 3.9E-11, COLCND = 1.8E-09, AMAX = 2.9E+10

 Row scale factors
    3.47E-11   1.90E-01   3.72E-01   9.01E-01

 Column scale factors
    1.00E+00   1.00E+00   5.53E+08   1.38E+00

 Scaled matrix
             1          2          3          4
 1      0.6250     1.0000     0.0393    -0.4269
 2      1.0000    -0.5619    -1.0000    -1.0000
 3      0.5874    -1.0000    -0.0596    -0.5341
 4     -1.0000    -0.5946    -0.0294     0.9957


f07agfe.r

 F07AGF Example Program Results

 Estimate of condition number =  1.52E+02


f07ahfe.r

 F07AHF Example Program Results

 Solution(s)
             1          2
 1      1.0000     3.0000
 2     -1.0000     2.0000
 3      3.0000     4.0000
 4     -5.0000     1.0000

 Backward errors (machine-dependent)
       9.4E-17    3.7E-17
 Estimated forward error bounds (machine-dependent)
       2.4E-14    3.3E-14


f07ajfe.r

 F07AJF Example Program Results

 Inverse
             1          2          3          4
 1      1.7720     0.5757     0.0843     4.8155
 2     -0.1175    -0.4456     0.4114    -1.7126
 3      0.1799     0.4527    -0.6676     1.4824
 4      2.4944     0.7650    -0.0360     7.6119


f07apfe.r

 F07APF Example Program Results

 Solution(s)
                    1                 2
 1  ( 1.0000, 1.0000) (-1.0000,-2.0000)
 2  ( 2.0000,-3.0000) ( 5.0000, 1.0000)
 3  (-4.0000,-5.0000) (-3.0000, 4.0000)
 4  ( 0.0000, 6.0000) ( 2.0000,-3.0000)

 Backward errors (machine-dependent)
       5.3E-17    4.8E-17

 Estimated forward error bounds (machine-dependent)
       5.8E-14    7.4E-14

 A has been row scaled as diag(R)*A

 Reciprocal condition number estimate of scaled matrix
       1.0E-02

 Estimate of reciprocal pivot growth factor
       8.3E-01


f07aqfe.r

 F07AQF Example Program Results

 Solution
    ( 1.0000, 1.0000) ( 2.0000,-3.0000) (-4.0000,-5.0000) ( 0.0000, 6.0000)

 Pivot indices
           3          2          3          4


f07asfe.r

 F07ASF Example Program Results

 Solution(s)
                    1                 2
 1  ( 1.0000, 1.0000) (-1.0000,-2.0000)
 2  ( 2.0000,-3.0000) ( 5.0000, 1.0000)
 3  (-4.0000,-5.0000) (-3.0000, 4.0000)
 4  ( 0.0000, 6.0000) ( 2.0000,-3.0000)


f07aufe.r

 F07AUF Example Program Results

 Estimate of condition number =  1.50E+02


f07avfe.r

 F07AVF Example Program Results

 Solution(s)
                    1                 2
 1  ( 1.0000, 1.0000) (-1.0000,-2.0000)
 2  ( 2.0000,-3.0000) ( 5.0000, 1.0000)
 3  (-4.0000,-5.0000) (-3.0000, 4.0000)
 4  ( 0.0000, 6.0000) ( 2.0000,-3.0000)

 Backward errors (machine-dependent)
         4.1E-17           8.7E-17
 Estimated forward error bounds (machine-dependent)
         5.8E-14           7.8E-14


f07bafe.r

 F07BAF Example Program Results

 Solution
       -2.0000     3.0000     1.0000    -4.0000

 Details of factorization
             1          2          3          4
 1     -6.9800     2.4600    -2.7300    -2.1300
 2      0.0330     2.5600     2.4600     4.0700
 3                 0.9605    -5.9329    -3.8391
 4                            0.8057    -0.7269

 Pivot indices
             2          3          3          4


f07bbfe.r

 F07BBF Example Program Results

 Solution(s)
             1          2
 1     -2.0000     1.0000
 2      3.0000    -4.0000
 3      1.0000     7.0000
 4     -4.0000    -2.0000

 Backward errors (machine-dependent)
       1.1E-16    9.9E-17

 Estimated forward error bounds (machine-dependent)
       1.6E-14    1.9E-14

 Estimate of reciprocal condition number
       1.8E-02

 A has not been equilibrated

 Estimate of reciprocal pivot growth factor
       1.0E+00


f07bdfe.r

 F07BDF Example Program Results

 Details of factorization
             1          2          3          4
 1     -6.9800     2.4600    -2.7300    -2.1300
 2      0.0330     2.5600     2.4600     4.0700
 3                 0.9605    -5.9329    -3.8391
 4                            0.8057    -0.7269

 IPIV
             2          3          3          4


f07befe.r

 F07BEF Example Program Results

 Solution(s)
             1          2
 1     -2.0000     1.0000
 2      3.0000    -4.0000
 3      1.0000     7.0000
 4     -4.0000    -2.0000


f07bffe.r

 F07BFF Example Program Results

 Matrix A
               1            2            3            4
 1   -2.3000E-01   2.5400E+00  -3.6600E-10
 2   -6.9800E+10   2.4600E+10  -2.7300E+00  -2.1300E+10
 3                 2.5600E+00   2.4600E-10   4.0700E+00
 4                             -4.7800E-10  -3.8200E+00

 ROWCND = 3.6E-11, COLCND = 1.4E-10, AMAX = 7.0E+10

 Row scale factors
    3.94E-01   1.43E-11   2.46E-01   2.62E-01

 Column scale factors
    1.00E+00   1.00E+00   6.94E+09   1.00E+00

 Scaled matrix
          1       2       3       4
 1  -0.0906  1.0000 -1.0000
 2  -1.0000  0.3524 -0.2714 -0.3052
 3           0.6290  0.4195  1.0000
 4                  -0.8684 -1.0000


f07bgfe.r

 F07BGF Example Program Results

 Estimate of condition number =  5.64E+01


f07bhfe.r

 F07BHF Example Program Results

 Solution(s)
             1          2
 1     -2.0000     1.0000
 2      3.0000    -4.0000
 3      1.0000     7.0000
 4     -4.0000    -2.0000

 Backward errors (machine-dependent)
       1.1E-16    9.9E-17
 Estimated forward error bounds (machine-dependent)
       1.6E-14    1.9E-14


f07bpfe.r

 F07BPF Example Program Results

 Solution(s)
                    1                 2
 1  (-3.0000, 2.0000) ( 1.0000, 6.0000)
 2  ( 1.0000,-7.0000) (-7.0000,-4.0000)
 3  (-5.0000, 4.0000) ( 3.0000, 5.0000)
 4  ( 6.0000,-8.0000) (-8.0000, 2.0000)

 Backward errors (machine-dependent)
       1.8E-17    6.7E-17

 Estimated forward error bounds (machine-dependent)
       3.5E-14    4.3E-14

 Estimate of reciprocal condition number
       9.6E-03

 A has not been equilibrated

 Estimate of reciprocal pivot growth factor
       1.0E+00


f07brfe.r

 F07BRF Example Program Results

 Details of factorization
                    1                 2                 3                 4
 1  ( 0.0000, 6.3000) (-1.4800,-1.7500) (-3.9900, 4.0100) ( 0.5900,-0.4800)
 2  ( 0.3587, 0.2619) (-0.7700, 2.8300) (-1.0600, 1.9400) ( 3.3300,-1.0400)
 3                    ( 0.2314, 0.6358) ( 4.9303,-3.0086) (-1.7692,-1.8587)
 4                                      ( 0.7604, 0.2429) ( 0.4338, 0.1233)

 IPIV
            2                 3                 3                 4


f07bsfe.r

 F07BSF Example Program Results

 Solution(s)
                    1                 2
 1  (-3.0000, 2.0000) ( 1.0000, 6.0000)
 2  ( 1.0000,-7.0000) (-7.0000,-4.0000)
 3  (-5.0000, 4.0000) ( 3.0000, 5.0000)
 4  ( 6.0000,-8.0000) (-8.0000, 2.0000)


f07bufe.r

 F07BUF Example Program Results

 Estimate of condition number =  1.04E+02


f07bvfe.r

 F07BVF Example Program Results

 Solution(s)
                    1                 2
 1  (-3.0000, 2.0000) ( 1.0000, 6.0000)
 2  ( 1.0000,-7.0000) (-7.0000,-4.0000)
 3  (-5.0000, 4.0000) ( 3.0000, 5.0000)
 4  ( 6.0000,-8.0000) (-8.0000, 2.0000)

 Backward errors (machine-dependent)
         1.8E-17           6.7E-17
 Estimated forward error bounds (machine-dependent)
         3.5E-14           4.3E-14


f07cafe.r

 F07CAF Example Program Results

 Solution
     -4.0000     7.0000     3.0000    -4.0000    -3.0000


f07cbfe.r

 F07CBF Example Program Results

 Solution(s)
             1          2
 1     -4.0000     5.0000
 2      7.0000    -4.0000
 3      3.0000    -3.0000
 4     -4.0000    -2.0000
 5     -3.0000     1.0000

 Backward errors (machine-dependent)
       7.2E-17    5.9E-17

 Estimated forward error bounds (machine-dependent)
       9.4E-15    1.4E-14

 Estimate of reciprocal condition number
       1.1E-02


f07cdfe.r

 F07CDF Example Program Results

 Details of factorization

  Second superdiagonal of U
   -1.0000   1.9000   8.0000

  First superdiagonal of U
    2.3000  -5.0000  -0.9000   7.1000

  Main diagonal of U
    3.4000   3.6000   7.0000  -6.0000  -1.0154

  Multipliers
    0.8824   0.0196   0.1401  -0.0148

  Vector of interchanges
         2        3        4        5        5


f07cefe.r

 F07CEF Example Program Results

 Solution(s)
             1          2
 1     -4.0000     5.0000
 2      7.0000    -4.0000
 3      3.0000    -3.0000
 4     -4.0000    -2.0000
 5     -3.0000     1.0000


f07cgfe.r

 F07CGF Example Program Results

 Estimate of condition number =   9.27E+01


f07chfe.r

 F07CHF Example Program Results

 Solution(s)
             1          2
 1     -4.0000     5.0000
 2      7.0000    -4.0000
 3      3.0000    -3.0000
 4     -4.0000    -2.0000
 5     -3.0000     1.0000

 Backward errors (machine-dependent)
       7.2E-17    5.9E-17

 Estimated forward error bounds (machine-dependent)
       9.4E-15    1.4E-14


f07cnfe.r

 F07CNF Example Program Results

 Solution
 (  1.0000,  1.0000) (  3.0000, -1.0000) (  4.0000,  5.0000) ( -1.0000, -2.0000)
 (  1.0000, -1.0000)


f07cpfe.r

 F07CPF Example Program Results

 Solution(s)
                    1                 2
 1  ( 1.0000, 1.0000) ( 2.0000,-1.0000)
 2  ( 3.0000,-1.0000) ( 1.0000, 2.0000)
 3  ( 4.0000, 5.0000) (-1.0000, 1.0000)
 4  (-1.0000,-2.0000) ( 2.0000, 1.0000)
 5  ( 1.0000,-1.0000) ( 2.0000,-2.0000)

 Backward errors (machine-dependent)
       3.7E-17    6.7E-17

 Estimated forward error bounds (machine-dependent)
       5.4E-14    7.3E-14

 Estimate of reciprocal condition number
       5.4E-03


f07crfe.r

 F07CRF Example Program Results

 Details of factorization

  Second superdiagonal of U
 (  2.0000,  1.0000) ( -1.0000,  1.0000) (  1.0000, -1.0000)

  First superdiagonal of U
 ( -1.3000,  1.3000) ( -1.3000,  3.3000) ( -0.3000,  4.3000) ( -3.3000,  1.3000)

  Main diagonal of U
 (  1.0000, -2.0000) (  1.0000,  1.0000) (  2.0000, -3.0000) (  1.0000,  1.0000)
 ( -1.3399,  0.2875)

  Multipliers
 ( -0.7800, -0.2600) (  0.1620, -0.4860) ( -0.0452, -0.0010) ( -0.3979, -0.0562)

  Vector of interchanges
       2      3      4      5      5


f07csfe.r

 F07CSF Example Program Results

 Solution(s)
                    1                 2
 1  ( 1.0000, 1.0000) ( 2.0000,-1.0000)
 2  ( 3.0000,-1.0000) ( 1.0000, 2.0000)
 3  ( 4.0000, 5.0000) (-1.0000, 1.0000)
 4  (-1.0000,-2.0000) ( 2.0000, 1.0000)
 5  ( 1.0000,-1.0000) ( 2.0000,-2.0000)


f07cufe.r

 F07CUF Example Program Results

 Estimate of condition number =   1.84E+02


f07cvfe.r

 F07CVF Example Program Results

 Solution(s)
                    1                 2
 1  ( 1.0000, 1.0000) ( 2.0000,-1.0000)
 2  ( 3.0000,-1.0000) ( 1.0000, 2.0000)
 3  ( 4.0000, 5.0000) (-1.0000, 1.0000)
 4  (-1.0000,-2.0000) ( 2.0000, 1.0000)
 5  ( 1.0000,-1.0000) ( 2.0000,-2.0000)

 Backward errors (machine-dependent)
       3.7E-17    6.7E-17

 Estimated forward error bounds (machine-dependent)
       5.4E-14    7.3E-14


f07fafe.r

 F07FAF Example Program Results

 Solution
        1.0000    -1.0000     2.0000    -3.0000

 Cholesky factor U
             1          2          3          4
 1      2.0396    -1.5297     0.2746    -0.0490
 2                 1.6401    -0.2500     0.6737
 3                            0.7887     0.6617
 4                                       0.5347


f07fbfe.r

 F07FBF Example Program Results

 Solution(s)
             1          2
 1      1.0000     4.0000
 2     -1.0000     3.0000
 3      2.0000     2.0000
 4     -3.0000     1.0000

 Backward errors (machine-dependent)
       6.7E-17    7.9E-17

 Estimated forward error bounds (machine-dependent)
       2.3E-14    2.3E-14

 Estimate of reciprocal condition number
       1.0E-02

 A has not been equilibrated


f07fcfe.r

 F07FCF Example Program Results

 Solution
        1.0000    -1.0000     2.0000    -3.0000


f07fdfe.r

 F07FDF Example Program Results

 Factor
             1          2          3          4
 1      2.0396
 2     -1.5297     1.6401
 3      0.2746    -0.2500     0.7887
 4     -0.0490     0.6737     0.6617     0.5347


f07fefe.r

 F07FEF Example Program Results

 Solution(s)
             1          2
 1      1.0000     4.0000
 2     -1.0000     3.0000
 3      2.0000     2.0000
 4     -3.0000     1.0000


f07fffe.r

 F07FFF Example Program Results

 Matrix A
               1            2            3            4
 1    4.1600E+00  -3.1200E+05   5.6000E-01  -1.0000E-01
 2                 5.0300E+10  -8.3000E+04   1.1800E+05
 3                              7.6000E-01   3.4000E-01
 4                                           1.1800E+00

 SCOND = 3.9E-06, AMAX = 5.0E+10

 Diagonal scaling factors
     4.9E-01    4.5E-06    1.1E+00    9.2E-01

 Scaled matrix
             1          2          3          4
 1      1.0000    -0.6821     0.3149    -0.0451
 2                 1.0000    -0.4245     0.4843
 3                            1.0000     0.3590
 4                                       1.0000


f07fgfe.r

 F07FGF Example Program Results

 Estimate of condition number =  9.73E+01


f07fhfe.r

 F07FHF Example Program Results

 Solution(s)
             1          2
 1      1.0000     4.0000
 2     -1.0000     3.0000
 3      2.0000     2.0000
 4     -3.0000     1.0000

 Backward errors (machine-dependent)
       7.6E-17    5.0E-17
 Estimated forward error bounds (machine-dependent)
       2.4E-14    2.3E-14


f07fjfe.r

 F07FJF Example Program Results

 Inverse
             1          2          3          4
 1      0.6995
 2      0.7769     1.4239
 3      0.7508     1.8255     4.0688
 4     -0.9340    -1.8841    -2.9342     3.4978


f07fpfe.r

 F07FPF Example Program Results

 Solution(s)
                    1                 2
 1  ( 1.0000,-1.0000) (-1.0000, 2.0000)
 2  (-0.0000, 3.0000) ( 3.0000,-4.0000)
 3  (-4.0000,-5.0000) (-2.0000, 3.0000)
 4  ( 2.0000, 1.0000) ( 4.0000,-5.0000)

 Backward errors (machine-dependent)
       5.9E-17    4.8E-17

 Estimated forward error bounds (machine-dependent)
       6.0E-14    7.2E-14

 Estimate of reciprocal condition number
       6.6E-03

 A has not been equilibrated


f07fqfe.r

 F07FQF Example Program Results

 Solution
    ( 1.0000,-1.0000) (-0.0000, 3.0000) (-4.0000,-5.0000) ( 2.0000, 1.0000)


f07frfe.r

 F07FRF Example Program Results

 Factor
                    1                 2                 3                 4
 1  ( 1.7972, 0.0000)
 2  ( 0.8402, 1.0683) ( 1.3164, 0.0000)
 3  ( 1.0572,-0.4674) (-0.4702, 0.3131) ( 1.5604, 0.0000)
 4  ( 0.2337,-1.3910) ( 0.0834, 0.0368) ( 0.9360, 0.9900) ( 0.6603, 0.0000)


f07fsfe.r

 F07FSF Example Program Results

 Solution(s)
                    1                 2
 1  ( 1.0000,-1.0000) (-1.0000, 2.0000)
 2  (-0.0000, 3.0000) ( 3.0000,-4.0000)
 3  (-4.0000,-5.0000) (-2.0000, 3.0000)
 4  ( 2.0000, 1.0000) ( 4.0000,-5.0000)


f07fufe.r

 F07FUF Example Program Results

 Estimate of condition number =  1.51E+02


f07fvfe.r

 F07FVF Example Program Results

 Solution(s)
                    1                 2
 1  ( 1.0000,-1.0000) (-1.0000, 2.0000)
 2  (-0.0000, 3.0000) ( 3.0000,-4.0000)
 3  (-4.0000,-5.0000) (-2.0000, 3.0000)
 4  ( 2.0000, 1.0000) ( 4.0000,-5.0000)

 Backward errors (machine-dependent)
         9.2E-17           8.4E-17
 Estimated forward error bounds (machine-dependent)
         6.0E-14           7.1E-14


f07fwfe.r

 F07FWF Example Program Results

 Inverse
                    1                 2                 3                 4
 1  ( 5.4691, 0.0000)
 2  (-1.2624,-1.5491) ( 1.1024, 0.0000)
 3  (-2.9746,-0.9616) ( 0.8989,-0.5672) ( 2.1589, 0.0000)
 4  ( 1.1962, 2.9772) (-0.9826,-0.2566) (-1.3756,-1.4550) ( 2.2934,-0.0000)


f07gafe.r

 F07GAF Example Program Results

 Solution
        1.0000    -1.0000     2.0000    -3.0000

 Cholesky factor
             1          2          3          4
 1      2.0396    -1.5297     0.2746    -0.0490
 2                 1.6401    -0.2500     0.6737
 3                            0.7887     0.6617
 4                                       0.5347


f07gbfe.r

 F07GBF Example Program Results

 Solution(s)
             1          2
 1      1.0000     4.0000
 2     -1.0000     3.0000
 3      2.0000     2.0000
 4     -3.0000     1.0000

 Backward errors (machine-dependent)
       6.7E-17    7.9E-17

 Estimated forward error bounds (machine-dependent)
       2.3E-14    2.3E-14

 Estimate of reciprocal condition number
       1.0E-02

 A has not been equilibrated


f07gdfe.r

 F07GDF Example Program Results

 Factor
             1          2          3          4
 1      2.0396
 2     -1.5297     1.6401
 3      0.2746    -0.2500     0.7887
 4     -0.0490     0.6737     0.6617     0.5347


f07gefe.r

 F07GEF Example Program Results

 Solution(s)
             1          2
 1      1.0000     4.0000
 2     -1.0000     3.0000
 3      2.0000     2.0000
 4     -3.0000     1.0000


f07gffe.r

 F07GFF Example Program Results

 Matrix A
               1            2            3            4
 1    4.1600E+00  -3.1200E+05   5.6000E-01  -1.0000E-01
 2                 5.0300E+10  -8.3000E+04   1.1800E+05
 3                              7.6000E-01   3.4000E-01
 4                                           1.1800E+00

 SCOND = 3.9E-06, AMAX = 5.0E+10

 Diagonal scaling factors
     4.9E-01    4.5E-06    1.1E+00    9.2E-01

 Scaled matrix
             1          2          3          4
 1      1.0000    -0.6821     0.3149    -0.0451
 2                 1.0000    -0.4245     0.4843
 3                            1.0000     0.3590
 4                                       1.0000


f07ggfe.r

 F07GGF Example Program Results

 Estimate of condition number =  9.73E+01


f07ghfe.r

 F07GHF Example Program Results

 Solution(s)
             1          2
 1      1.0000     4.0000
 2     -1.0000     3.0000
 3      2.0000     2.0000
 4     -3.0000     1.0000

 Backward errors (machine-dependent)
       5.1E-17    6.1E-17
 Estimated forward error bounds (machine-dependent)
       2.3E-14    2.3E-14


f07gjfe.r

 F07GJF Example Program Results

 Inverse
             1          2          3          4
 1      0.6995
 2      0.7769     1.4239
 3      0.7508     1.8255     4.0688
 4     -0.9340    -1.8841    -2.9342     3.4978


f07gpfe.r

 F07GPF Example Program Results

 Solution(s)
                    1                 2
 1  ( 1.0000,-1.0000) (-1.0000, 2.0000)
 2  (-0.0000, 3.0000) ( 3.0000,-4.0000)
 3  (-4.0000,-5.0000) (-2.0000, 3.0000)
 4  ( 2.0000, 1.0000) ( 4.0000,-5.0000)

 Backward errors (machine-dependent)
       1.1E-16    7.9E-17

 Estimated forward error bounds (machine-dependent)
       6.1E-14    7.4E-14

 Estimate of reciprocal condition number
       6.6E-03

 A has not been equilibrated


f07grfe.r

 F07GRF Example Program Results

 Factor
                    1                 2                 3                 4
 1  ( 1.7972, 0.0000)
 2  ( 0.8402, 1.0683) ( 1.3164, 0.0000)
 3  ( 1.0572,-0.4674) (-0.4702, 0.3131) ( 1.5604, 0.0000)
 4  ( 0.2337,-1.3910) ( 0.0834, 0.0368) ( 0.9360, 0.9900) ( 0.6603, 0.0000)


f07gsfe.r

 F07GSF Example Program Results

 Solution(s)
                    1                 2
 1  ( 1.0000,-1.0000) (-1.0000, 2.0000)
 2  (-0.0000, 3.0000) ( 3.0000,-4.0000)
 3  (-4.0000,-5.0000) (-2.0000, 3.0000)
 4  ( 2.0000, 1.0000) ( 4.0000,-5.0000)


f07gufe.r

 F07GUF Example Program Results

 Estimate of condition number =  1.51E+02


f07gvfe.r

 F07GVF Example Program Results

 Solution(s)
                    1                 2
 1  ( 1.0000,-1.0000) (-1.0000, 2.0000)
 2  (-0.0000, 3.0000) ( 3.0000,-4.0000)
 3  (-4.0000,-5.0000) (-2.0000, 3.0000)
 4  ( 2.0000, 1.0000) ( 4.0000,-5.0000)

 Backward errors (machine-dependent)
         5.5E-17           7.9E-17
 Estimated forward error bounds (machine-dependent)
         6.0E-14           7.2E-14


f07gwfe.r

 F07GWF Example Program Results

 Inverse
                    1                 2                 3                 4
 1  ( 5.4691, 0.0000)
 2  (-1.2624,-1.5491) ( 1.1024, 0.0000)
 3  (-2.9746,-0.9616) ( 0.8989,-0.5672) ( 2.1589, 0.0000)
 4  ( 1.1962, 2.9772) (-0.9826,-0.2566) (-1.3756,-1.4550) ( 2.2934, 0.0000)


f07hafe.r

 F07HAF Example Program Results

 Solution
        5.0000    -2.0000    -3.0000     1.0000

 Cholesky factor U
             1          2          3          4
 1      2.3431     1.1438
 2                 2.0789    -1.1497
 3                            1.1306    -1.9635
 4                                       1.1465


f07hbfe.r

 F07HBF Example Program Results

 Solution(s)
             1          2
 1      5.0000    -2.0000
 2     -2.0000     6.0000
 3     -3.0000    -1.0000
 4      1.0000     4.0000

 Backward errors (machine-dependent)
       1.1E-16    1.1E-16

 Estimated forward error bounds (machine-dependent)
       2.1E-14    3.0E-14

 Estimate of reciprocal condition number
       1.3E-02

 A has not been equilibrated


f07hdfe.r

 F07HDF Example Program Results

 Factor
             1          2          3          4
 1      2.3431
 2      1.1438     2.0789
 3                -1.1497     1.1306
 4                           -1.9635     1.1465


f07hefe.r

 F07HEF Example Program Results

 Solution(s)
             1          2
 1      5.0000    -2.0000
 2     -2.0000     6.0000
 3     -3.0000    -1.0000
 4      1.0000     4.0000


f07hffe.r

 F07HFF Example Program Results

 Matrix A
               1            2            3            4
 1    5.4900E+00   2.6800E+10
 2                 5.6300E+20  -2.3900E+10
 3                              2.6000E+00  -2.2200E+00
 4                                           5.1700E+00

 SCOND = 6.8E-11, AMAX = 5.6E+20

 Diagonal scaling factors
     4.3E-01    4.2E-11    6.2E-01    4.4E-01

 Scaled matrix
             1          2          3          4
 1      1.0000     0.4821
 2                 1.0000    -0.6247
 3                            1.0000    -0.6055
 4                                       1.0000


f07hgfe.r

 F07HGF Example Program Results

 Estimate of condition number =  7.42E+01


f07hhfe.r

 F07HHF Example Program Results

 Solution(s)
             1          2
 1      5.0000    -2.0000
 2     -2.0000     6.0000
 3     -3.0000    -1.0000
 4      1.0000     4.0000

 Backward errors (machine-dependent)
       4.4E-17    9.2E-17
 Estimated forward error bounds (machine-dependent)
       2.0E-14    2.9E-14


f07hnfe.r

 F07HNF Example Program Results

 Solution
    (-1.0000, 8.0000) ( 2.0000,-3.0000) (-4.0000,-5.0000) ( 7.0000, 6.0000)

 Cholesky factor U
                    1                 2                 3                 4
 1  ( 3.0643, 0.0000) ( 0.3524,-0.5646)
 2                    ( 1.1167, 0.0000) (-0.0358, 0.2597)
 3                                      ( 1.6066, 0.0000) (-0.2054, 1.3942)
 4                                                        ( 0.4289, 0.0000)


f07hpfe.r

 F07HPF Example Program Results

 Solution(s)
                    1                 2
 1  (-1.0000, 8.0000) ( 5.0000,-6.0000)
 2  ( 2.0000,-3.0000) ( 2.0000, 3.0000)
 3  (-4.0000,-5.0000) (-8.0000, 4.0000)
 4  ( 7.0000, 6.0000) (-1.0000,-7.0000)

 Backward errors (machine-dependent)
       8.2E-17    5.4E-17

 Estimated forward error bounds (machine-dependent)
       3.6E-14    3.0E-14

 Estimate of reciprocal condition number
       7.6E-03

 A has not been equilibrated


f07hrfe.r

 F07HRF Example Program Results

 Factor
                    1                 2                 3                 4
 1  ( 3.0643, 0.0000)
 2  ( 0.3524, 0.5646) ( 1.1167, 0.0000)
 3                    (-0.0358,-0.2597) ( 1.6066, 0.0000)
 4                                      (-0.2054,-1.3942) ( 0.4289, 0.0000)


f07hsfe.r

 F07HSF Example Program Results

 Solution(s)
                    1                 2
 1  (-1.0000, 8.0000) ( 5.0000,-6.0000)
 2  ( 2.0000,-3.0000) ( 2.0000, 3.0000)
 3  (-4.0000,-5.0000) (-8.0000, 4.0000)
 4  ( 7.0000, 6.0000) (-1.0000,-7.0000)


f07htfe.r

 F07HTF Example Program Results

 Matrix A
                          1                       2                       3
 1  (  9.39E+00,  0.00E+00) (  1.08E+00, -1.73E+00)
 2                          (  1.69E+00,  0.00E+00) ( -4.00E+08,  2.90E+09)
 3                                                  (  2.64E+20,  0.00E+00)
 4

                          4
 1
 2
 3  ( -3.30E+09,  2.24E+10)
 4  (  2.17E+00,  0.00E+00)

 SCOND = 8.0E-11, AMAX = 2.6E+20

 Diagonal scaling factors
     3.3E-01    7.7E-01    6.2E-11    6.8E-01

 Scaled matrix
                    1                 2                 3                 4
 1  ( 1.0000, 0.0000) ( 0.2711,-0.4343)
 2                    ( 1.0000, 0.0000) (-0.0189, 0.1373)
 3                                      ( 1.0000, 0.0000) (-0.1379, 0.9359)
 4                                                        ( 1.0000, 0.0000)


f07hufe.r

 F07HUF Example Program Results

 Estimate of condition number =  1.32E+02


f07hvfe.r

 F07HVF Example Program Results

 Solution(s)
                    1                 2
 1  (-1.0000, 8.0000) ( 5.0000,-6.0000)
 2  ( 2.0000,-3.0000) ( 2.0000, 3.0000)
 3  (-4.0000,-5.0000) (-8.0000, 4.0000)
 4  ( 7.0000, 6.0000) (-1.0000,-7.0000)

 Backward errors (machine-dependent)
         8.2E-17           8.3E-17
 Estimated forward error bounds (machine-dependent)
         3.5E-14           3.2E-14


f07jafe.r

 F07JAF Example Program Results

 Solution
      2.5000     2.0000     1.0000    -1.0000     3.0000

 Diagonal elements of the diagonal matrix D
      4.0000     9.0000    25.0000    16.0000     1.0000

 Subdiagonal elements of the Cholesky factor L
     -0.5000    -0.6667     0.6000     0.5000


f07jbfe.r

 F07JBF Example Program Results

 Solution(s)
             1          2
 1      2.5000     2.0000
 2      2.0000    -1.0000
 3      1.0000    -3.0000
 4     -1.0000     6.0000
 5      3.0000    -5.0000

 Backward errors (machine-dependent)
     0.0E+00    7.4E-17

 Estimated forward error bounds (machine-dependent)
     2.4E-14    4.7E-14

 Estimate of reciprocal condition number
     9.5E-03


f07jdfe.r

 F07JDF Example Program Results

 Details of factorization

  The diagonal elements of D
    4.0000   9.0000  25.0000  16.0000   1.0000

  Subdiagonal elements of the Cholesky factor L
   -0.5000  -0.6667   0.6000   0.5000


f07jefe.r

 F07JEF Example Program Results

 Solution(s)
             1          2
 1      2.5000     2.0000
 2      2.0000    -1.0000
 3      1.0000    -3.0000
 4     -1.0000     6.0000
 5      3.0000    -5.0000


f07jgfe.r

 F07JGF Example Program Results

 Estimate of condition number =   1.05E+02


f07jhfe.r

 F07JHF Example Program Results

 Solution(s)
             1          2
 1      2.5000     2.0000
 2      2.0000    -1.0000
 3      1.0000    -3.0000
 4     -1.0000     6.0000
 5      3.0000    -5.0000

 Backward errors (machine-dependent)
       0.0E+00    7.4E-17

 Estimated forward error bounds (machine-dependent)
       2.4E-14    4.7E-14


f07jnfe.r

 F07JNF Example Program Results

 Solution
 (  2.0000,  1.0000) (  1.0000,  1.0000) (  1.0000, -2.0000) (  1.0000, -1.0000)

 Diagonal elements of the diagonal matrix D
  16.0000            9.0000            1.0000            4.0000

 Subdiagonal elements of the Cholesky factor L
 (  1.0000,  1.0000) (  2.0000, -1.0000) (  1.0000, -4.0000)


f07jpfe.r

 F07JPF Example Program Results

 Solution(s)
                    1                 2
 1  ( 2.0000, 1.0000) (-3.0000,-2.0000)
 2  ( 1.0000, 1.0000) ( 1.0000, 1.0000)
 3  ( 1.0000,-2.0000) ( 1.0000,-2.0000)
 4  ( 1.0000,-1.0000) ( 2.0000, 1.0000)

 Backward errors (machine-dependent)
     0.0E+00    0.0E+00

 Estimated forward error bounds (machine-dependent)
     9.0E-12    6.1E-12

 Estimate of reciprocal condition number
     1.1E-04


f07jrfe.r

 F07JRF Example Program Results

 Details of factorization

  The diagonal elements of D
   16.0000   9.0000   1.0000   4.0000

  Subdiagonal elements of the Cholesky factor L
    1.0000   1.0000   2.0000  -1.0000   1.0000  -4.0000


f07jsfe.r

 F07JSF Example Program Results

 Solution(s)
                            1                         2
 1  (     2.0000,     1.0000) (    -3.0000,    -2.0000)
 2  (     1.0000,     1.0000) (     1.0000,     1.0000)
 3  (     1.0000,    -2.0000) (     1.0000,    -2.0000)
 4  (     1.0000,    -1.0000) (     2.0000,     1.0000)


f07jufe.r

 F07JUF Example Program Results

 Estimate of condition number =   9.21E+03


f07jvfe.r

 F07JVF Example Program Results

 Solution(s)
                    1                 2
 1  ( 2.0000, 1.0000) (-3.0000,-2.0000)
 2  ( 1.0000, 1.0000) ( 1.0000, 1.0000)
 3  ( 1.0000,-2.0000) ( 1.0000,-2.0000)
 4  ( 1.0000,-1.0000) ( 2.0000, 1.0000)

 Backward errors (machine-dependent)
       0.0E+00    0.0E+00

 Estimated forward error bounds (machine-dependent)
       9.0E-12    6.1E-12


f07kdfe.r

 F07KDF Example Program Results

 Computed rank:   3

 Factor
             1          2          3          4          5
 1      2.8671
 2      1.4091     0.7242
 3      2.5741    -0.3965     0.5262
 4      0.9348     0.0315    -0.2920     0.0000
 5      0.8510     0.1254    -0.0018     0.0000     0.0000

 PIV
             2          1          3          4          5


f07krfe.r

 F07KRF Example Program Results

 Computed rank:   3

 Factor
                1             2             3             4             5
 1  ( 3.52, 0.00)
 2  ( 0.68, 0.00) ( 1.08, 0.00)
 3  ( 1.27, 0.00) ( 0.26, 0.00) ( 0.18, 0.00)
 4  ( 1.56, 0.01) (-0.02, 0.08) ( 0.01,-0.05) ( 0.00, 0.00)
 5  ( 3.38, 0.00) (-0.45, 0.00) (-0.17, 0.00) ( 0.00, 0.00) ( 0.00, 0.00)

 PIV
                1             2             4             3             5


f07mafe.r

 F07MAF Example Program Results

 Solution
       -5.0000    -2.0000     1.0000     4.0000

 Details of the factorization
             1          2          3          4
 1      0.4074     0.3031    -0.5960     0.6537
 2                -2.5907     0.8115     0.2230
 3                            1.1500     4.2000
 4                                       2.0700

 Pivot indices
           1          2         -2         -2


f07mbfe.r

 F07MBF Example Program Results

 Solution(s)
             1          2
 1     -5.0000     2.0000
 2     -2.0000     3.0000
 3      1.0000     4.0000
 4      4.0000     1.0000

 Backward errors (machine-dependent)
       1.4E-16    1.0E-16

 Estimated forward error bounds (machine-dependent)
       2.5E-14    3.2E-14

 Estimate of reciprocal condition number
       1.3E-02


f07mdfe.r

 F07MDF Example Program Results

 Details of factorization
             1          2          3          4
 1      2.0700
 2      4.2000     1.1500
 3      0.2230     0.8115    -2.5907
 4      0.6537    -0.5960     0.3031     0.4074

 IPIV
            -3         -3          3          4


f07mefe.r

 F07MEF Example Program Results

 Solution(s)
             1          2
 1     -4.0000     1.0000
 2     -1.0000     4.0000
 3      2.0000     3.0000
 4      5.0000     2.0000


f07mgfe.r

 F07MGF Example Program Results

 Estimate of condition number =  7.57E+01


f07mhfe.r

 F07MHF Example Program Results

 Solution(s)
             1          2
 1     -4.0000     1.0000
 2     -1.0000     4.0000
 3      2.0000     3.0000
 4      5.0000     2.0000

 Backward errors (machine-dependent)
       9.9E-17    8.3E-17
 Estimated forward error bounds (machine-dependent)
       2.4E-14    3.2E-14


f07mjfe.r

 F07MJF Example Program Results

 Inverse
             1          2          3          4
 1      0.7485
 2      0.5221    -0.1605
 3     -1.0058    -0.3131     1.3501
 4     -1.4386    -0.7440     2.0667     2.4547


f07mnfe.r

 F07MNF Example Program Results

 Solution
    ( 2.0000, 1.0000) ( 3.0000,-2.0000) (-1.0000, 2.0000) ( 1.0000,-1.0000)

 Details of the factorization
                    1                 2                 3                 4
 1  (-7.1028, 0.0000) ( 0.2997, 0.1578) ( 0.3397, 0.0303) (-0.1518, 0.3743)
 2                    (-5.4176, 0.0000) ( 0.5637, 0.2850) ( 0.3100, 0.0433)
 3                                      (-1.8400, 0.0000) ( 3.9100,-1.5000)
 4                                                        (-1.3600, 0.0000)

 Pivot indices
           1          2         -1         -1


f07mpfe.r

 F07MPF Example Program Results

 Solution(s)
                    1                 2
 1  ( 2.0000, 1.0000) (-8.0000, 6.0000)
 2  ( 3.0000,-2.0000) ( 7.0000,-2.0000)
 3  (-1.0000, 2.0000) (-1.0000, 5.0000)
 4  ( 1.0000,-1.0000) ( 3.0000,-4.0000)

 Backward errors (machine-dependent)
       5.1E-17    5.9E-17

 Estimated forward error bounds (machine-dependent)
       2.5E-15    3.0E-15

 Estimate of reciprocal condition number
       1.5E-01


f07mrfe.r

 F07MRF Example Program Results

 Details of factorization
                    1                 2                 3                 4
 1  (-1.3600, 0.0000)
 2  ( 3.9100,-1.5000) (-1.8400, 0.0000)
 3  ( 0.3100, 0.0433) ( 0.5637, 0.2850) (-5.4176, 0.0000)
 4  (-0.1518, 0.3743) ( 0.3397, 0.0303) ( 0.2997, 0.1578) (-7.1028, 0.0000)

 IPIV
           -4                -4                 3                 4


f07msfe.r

 F07MSF Example Program Results

 Solution(s)
                    1                 2
 1  ( 1.0000,-1.0000) ( 3.0000,-4.0000)
 2  (-1.0000, 2.0000) (-1.0000, 5.0000)
 3  ( 3.0000,-2.0000) ( 7.0000,-2.0000)
 4  ( 2.0000, 1.0000) (-8.0000, 6.0000)


f07mufe.r

 F07MUF Example Program Results

 Estimate of condition number =  6.68E+00


f07mvfe.r

 F07MVF Example Program Results

 Solution(s)
                    1                 2
 1  ( 1.0000,-1.0000) ( 3.0000,-4.0000)
 2  (-1.0000, 2.0000) (-1.0000, 5.0000)
 3  ( 3.0000,-2.0000) ( 7.0000,-2.0000)
 4  ( 2.0000, 1.0000) (-8.0000, 6.0000)

 Backward errors (machine-dependent)
         5.1E-17           3.5E-17
 Estimated forward error bounds (machine-dependent)
         2.5E-15           3.0E-15


f07mwfe.r

 F07MWF Example Program Results

 Inverse
                    1                 2                 3                 4
 1  ( 0.0826, 0.0000)
 2  (-0.0335, 0.0440) (-0.1408, 0.0000)
 3  ( 0.0603,-0.0105) ( 0.0422,-0.0222) (-0.2007, 0.0000)
 4  ( 0.2391,-0.0926) ( 0.0304, 0.0203) ( 0.0982,-0.0635) ( 0.0073,-0.0000)


f07nnfe.r

 F07NNF Example Program Results

 Solution
    (-4.0000, 3.0000) ( 3.0000,-2.0000) (-2.0000, 5.0000) ( 1.0000,-1.0000)

 Details of the factorization
                    1                 2                 3                 4
 1  (-2.0954,-2.2011) (-0.1071,-0.3157) (-0.4823, 0.0150) ( 0.4426, 0.1936)
 2                    ( 4.4079, 5.3991) (-0.6078, 0.2811) ( 0.5279,-0.3715)
 3                                      (-2.8300,-0.0300) (-7.8600,-2.9600)
 4                                                        (-0.3900,-0.7100)

 Pivot indices
           1          2         -2         -2


f07npfe.r

 F07NPF Example Program Results

 Solution(s)
                    1                 2
 1  (-4.0000, 3.0000) (-1.0000, 1.0000)
 2  ( 3.0000,-2.0000) ( 3.0000, 2.0000)
 3  (-2.0000, 5.0000) ( 1.0000,-3.0000)
 4  ( 1.0000,-1.0000) (-2.0000,-1.0000)

 Backward errors (machine-dependent)
       8.1E-17    3.0E-17

 Estimated forward error bounds (machine-dependent)
       1.2E-14    1.2E-14

 Estimate of reciprocal condition number
       4.9E-02


f07nrfe.r

 F07NRF Example Program Results

 Details of factorization
                    1                 2                 3                 4
 1  (-0.3900,-0.7100)
 2  (-7.8600,-2.9600) (-2.8300,-0.0300)
 3  ( 0.5279,-0.3715) (-0.6078, 0.2811) ( 4.4079, 5.3991)
 4  ( 0.4426, 0.1936) (-0.4823, 0.0150) (-0.1071,-0.3157) (-2.0954,-2.2011)

 IPIV
           -3                -3                 3                 4


f07nsfe.r

 F07NSF Example Program Results

 Solution(s)
                    1                 2
 1  ( 1.0000,-1.0000) (-2.0000,-1.0000)
 2  (-2.0000, 5.0000) ( 1.0000,-3.0000)
 3  ( 3.0000,-2.0000) ( 3.0000, 2.0000)
 4  (-4.0000, 3.0000) (-1.0000, 1.0000)


f07nufe.r

 F07NUF Example Program Results

 Estimate of condition number =  2.06E+01


f07nvfe.r

 F07NVF Example Program Results

 Solution(s)
                    1                 2
 1  ( 1.0000,-1.0000) (-2.0000,-1.0000)
 2  (-2.0000, 5.0000) ( 1.0000,-3.0000)
 3  ( 3.0000,-2.0000) ( 3.0000, 2.0000)
 4  (-4.0000, 3.0000) (-1.0000, 1.0000)

 Backward errors (machine-dependent)
         8.9E-17           7.3E-17
 Estimated forward error bounds (machine-dependent)
         1.2E-14           1.2E-14


f07nwfe.r

 F07NWF Example Program Results

 Inverse
                    1                 2                 3                 4
 1  (-0.1562,-0.1014)
 2  ( 0.0400, 0.1527) ( 0.0946,-0.1475)
 3  ( 0.0550, 0.0845) (-0.0326,-0.1370) (-0.1320,-0.0102)
 4  ( 0.2162,-0.0742) (-0.0995,-0.0461) (-0.1793, 0.1183) (-0.2269, 0.2383)


f07pafe.r

 F07PAF Example Program Results

 Solution
       -5.0000    -2.0000     1.0000     4.0000

 Details of the factorization
             1          2          3          4
 1      0.4074     0.3031    -0.5960     0.6537
 2                -2.5907     0.8115     0.2230
 3                            1.1500     4.2000
 4                                       2.0700

 Pivot indices
           1          2         -2         -2


f07pbfe.r

 F07PBF Example Program Results

 Solution(s)
             1          2
 1     -5.0000     2.0000
 2     -2.0000     3.0000
 3      1.0000     4.0000
 4      4.0000     1.0000

 Backward errors (machine-dependent)
       1.4E-16    1.0E-16

 Estimated forward error bounds (machine-dependent)
       2.5E-14    3.2E-14

 Estimate of reciprocal condition number
       1.3E-02


f07pdfe.r

 F07PDF Example Program Results

 Details of factorization
             1          2          3          4
 1      2.0700
 2      4.2000     1.1500
 3      0.2230     0.8115    -2.5907
 4      0.6537    -0.5960     0.3031     0.4074

 IPIV
            -3         -3          3          4


f07pefe.r

 F07PEF Example Program Results

 Solution(s)
             1          2
 1     -4.0000     1.0000
 2     -1.0000     4.0000
 3      2.0000     3.0000
 4      5.0000     2.0000


f07pgfe.r

 F07PGF Example Program Results

 Estimate of condition number =  7.57E+01


f07phfe.r

 F07PHF Example Program Results

 Solution(s)
             1          2
 1     -4.0000     1.0000
 2     -1.0000     4.0000
 3      2.0000     3.0000
 4      5.0000     2.0000

 Backward errors (machine-dependent)
       9.9E-17    8.3E-17
 Estimated forward error bounds (machine-dependent)
       2.4E-14    3.2E-14


f07pjfe.r

 F07PJF Example Program Results

 Inverse
             1          2          3          4
 1      0.7485
 2      0.5221    -0.1605
 3     -1.0058    -0.3131     1.3501
 4     -1.4386    -0.7440     2.0667     2.4547


f07pnfe.r

 F07PNF Example Program Results

 Solution
    ( 2.0000, 1.0000) ( 3.0000,-2.0000) (-1.0000, 2.0000) ( 1.0000,-1.0000)

 Details of factorization
                    1                 2                 3                 4
 1  (-7.1028, 0.0000) ( 0.2997, 0.1578) ( 0.3397, 0.0303) (-0.1518, 0.3743)
 2                    (-5.4176, 0.0000) ( 0.5637, 0.2850) ( 0.3100, 0.0433)
 3                                      (-1.8400, 0.0000) ( 3.9100,-1.5000)
 4                                                        (-1.3600, 0.0000)

 Pivot indices
           1          2         -1         -1


f07ppfe.r

 F07PPF Example Program Results

 Solution(s)
                    1                 2
 1  ( 2.0000, 1.0000) (-8.0000, 6.0000)
 2  ( 3.0000,-2.0000) ( 7.0000,-2.0000)
 3  (-1.0000, 2.0000) (-1.0000, 5.0000)
 4  ( 1.0000,-1.0000) ( 3.0000,-4.0000)

 Backward errors (machine-dependent)
       5.1E-17    5.9E-17

 Estimated forward error bounds (machine-dependent)
       2.5E-15    3.0E-15

 Estimate of reciprocal condition number
       1.5E-01


f07prfe.r

 F07PRF Example Program Results

 Details of factorization
                    1                 2                 3                 4
 1  (-1.3600, 0.0000)
 2  ( 3.9100,-1.5000) (-1.8400, 0.0000)
 3  ( 0.3100, 0.0433) ( 0.5637, 0.2850) (-5.4176, 0.0000)
 4  (-0.1518, 0.3743) ( 0.3397, 0.0303) ( 0.2997, 0.1578) (-7.1028, 0.0000)

 IPIV
           -4                -4                 3                 4


f07psfe.r

 F07PSF Example Program Results

 Solution(s)
                    1                 2
 1  ( 1.0000,-1.0000) ( 3.0000,-4.0000)
 2  (-1.0000, 2.0000) (-1.0000, 5.0000)
 3  ( 3.0000,-2.0000) ( 7.0000,-2.0000)
 4  ( 2.0000, 1.0000) (-8.0000, 6.0000)


f07pufe.r

 F07PUF Example Program Results

 Estimate of condition number =  6.68E+00


f07pvfe.r

 F07PVF Example Program Results

 Solution(s)
                    1                 2
 1  ( 1.0000,-1.0000) ( 3.0000,-4.0000)
 2  (-1.0000, 2.0000) (-1.0000, 5.0000)
 3  ( 3.0000,-2.0000) ( 7.0000,-2.0000)
 4  ( 2.0000, 1.0000) (-8.0000, 6.0000)

 Backward errors (machine-dependent)
         5.1E-17           3.5E-17
 Estimated forward error bounds (machine-dependent)
         2.5E-15           3.0E-15


f07pwfe.r

 F07PWF Example Program Results

 Inverse
                    1                 2                 3                 4
 1  ( 0.0826, 0.0000)
 2  (-0.0335, 0.0440) (-0.1408, 0.0000)
 3  ( 0.0603,-0.0105) ( 0.0422,-0.0222) (-0.2007, 0.0000)
 4  ( 0.2391,-0.0926) ( 0.0304, 0.0203) ( 0.0982,-0.0635) ( 0.0073,-0.0000)


f07qnfe.r

 F07QNF Example Program Results

 Solution
    (-4.0000, 3.0000) ( 3.0000,-2.0000) (-2.0000, 5.0000) ( 1.0000,-1.0000)

 Details of factorization
                    1                 2                 3                 4
 1  (-2.0954,-2.2011) (-0.1071,-0.3157) (-0.4823, 0.0150) ( 0.4426, 0.1936)
 2                    ( 4.4079, 5.3991) (-0.6078, 0.2811) ( 0.5279,-0.3715)
 3                                      (-2.8300,-0.0300) (-7.8600,-2.9600)
 4                                                        (-0.3900,-0.7100)

 Pivot indices
           1          2         -2         -2


f07qpfe.r

 F07QPF Example Program Results

 Solution(s)
                    1                 2
 1  (-4.0000, 3.0000) (-1.0000, 1.0000)
 2  ( 3.0000,-2.0000) ( 3.0000, 2.0000)
 3  (-2.0000, 5.0000) ( 1.0000,-3.0000)
 4  ( 1.0000,-1.0000) (-2.0000,-1.0000)

 Backward errors (machine-dependent)
       8.1E-17    3.0E-17

 Estimated forward error bounds (machine-dependent)
       1.2E-14    1.2E-14

 Estimate of reciprocal condition number
       4.9E-02


f07qrfe.r

 F07QRF Example Program Results

 Details of factorization
                    1                 2                 3                 4
 1  (-0.3900,-0.7100)
 2  (-7.8600,-2.9600) (-2.8300,-0.0300)
 3  ( 0.5279,-0.3715) (-0.6078, 0.2811) ( 4.4079, 5.3991)
 4  ( 0.4426, 0.1936) (-0.4823, 0.0150) (-0.1071,-0.3157) (-2.0954,-2.2011)

 IPIV
           -3                -3                 3                 4


f07qsfe.r

 F07QSF Example Program Results

 Solution(s)
                    1                 2
 1  ( 1.0000,-1.0000) (-2.0000,-1.0000)
 2  (-2.0000, 5.0000) ( 1.0000,-3.0000)
 3  ( 3.0000,-2.0000) ( 3.0000, 2.0000)
 4  (-4.0000, 3.0000) (-1.0000, 1.0000)


f07qufe.r

 F07QUF Example Program Results

 Estimate of condition number =  2.06E+01


f07qvfe.r

 F07QVF Example Program Results

 Solution(s)
                    1                 2
 1  ( 1.0000,-1.0000) (-2.0000,-1.0000)
 2  (-2.0000, 5.0000) ( 1.0000,-3.0000)
 3  ( 3.0000,-2.0000) ( 3.0000, 2.0000)
 4  (-4.0000, 3.0000) (-1.0000, 1.0000)

 Backward errors (machine-dependent)
         8.9E-17           7.3E-17
 Estimated forward error bounds (machine-dependent)
         1.2E-14           1.2E-14


f07qwfe.r

 F07QWF Example Program Results

 Inverse
                    1                 2                 3                 4
 1  (-0.1562,-0.1014)
 2  ( 0.0400, 0.1527) ( 0.0946,-0.1475)
 3  ( 0.0550, 0.0845) (-0.0326,-0.1370) (-0.1320,-0.0102)
 4  ( 0.2162,-0.0742) (-0.0995,-0.0461) (-0.1793, 0.1183) (-0.2269, 0.2383)


f07tefe.r

 F07TEF Example Program Results

 Solution(s)
             1          2
 1     -3.0000    -5.0000
 2     -1.0000     1.0000
 3      2.0000    -1.0000
 4      1.0000     6.0000


f07tgfe.r

 F07TGF Example Program Results

 Estimate of condition number =  1.16E+02


f07thfe.r

 F07THF Example Program Results

 Solution(s)
             1          2
 1     -3.0000    -5.0000
 2     -1.0000     1.0000
 3      2.0000    -1.0000
 4      1.0000     6.0000

 Backward errors (machine-dependent)
       6.9E-17    0.0E+00
 Estimated forward error bounds (machine-dependent)
       8.3E-14    2.6E-14


f07tjfe.r

 F07TJF Example Program Results

 Inverse
             1          2          3          4
 1      0.2326
 2     -0.1891    -0.2053
 3      0.0043    -0.0079    -0.1247
 4      0.8463    -0.2738    -6.1825     8.3333


f07tsfe.r

 F07TSF Example Program Results

 Solution(s)
                    1                 2
 1  (-5.0000,-2.0000) ( 1.0000, 5.0000)
 2  (-3.0000,-1.0000) (-2.0000,-2.0000)
 3  ( 2.0000, 1.0000) ( 3.0000, 4.0000)
 4  ( 4.0000, 3.0000) ( 4.0000,-3.0000)


f07tufe.r

 F07TUF Example Program Results

 Estimate of condition number =  3.74E+01


f07tvfe.r

 F07TVF Example Program Results

 Solution(s)
                    1                 2
 1  (-5.0000,-2.0000) ( 1.0000, 5.0000)
 2  (-3.0000,-1.0000) (-2.0000,-2.0000)
 3  ( 2.0000, 1.0000) ( 3.0000, 4.0000)
 4  ( 4.0000, 3.0000) ( 4.0000,-3.0000)

 Backward errors (machine-dependent)
         6.2E-17           2.7E-17
 Estimated forward error bounds (machine-dependent)
         2.9E-14           3.2E-14


f07twfe.r

 F07TWF Example Program Results

 Inverse
                    1                 2                 3                 4
 1  ( 0.1095,-0.1045)
 2  ( 0.0582,-0.0411) (-0.2227,-0.0677)
 3  ( 0.0032, 0.1905) ( 0.1538,-0.2192) ( 0.2323,-0.0448)
 4  ( 0.7602, 0.2814) ( 1.6184,-1.4346) ( 0.1289,-0.2250) ( 1.8697, 1.4731)


f07uefe.r

 F07UEF Example Program Results

 Solution(s)
             1          2
 1     -3.0000    -5.0000
 2     -1.0000     1.0000
 3      2.0000    -1.0000
 4      1.0000     6.0000


f07ugfe.r

 F07UGF Example Program Results

 Estimate of condition number =  1.16E+02


f07uhfe.r

 F07UHF Example Program Results

 Solution(s)
             1          2
 1     -3.0000    -5.0000
 2     -1.0000     1.0000
 3      2.0000    -1.0000
 4      1.0000     6.0000

 Backward errors (machine-dependent)
       6.9E-17    0.0E+00
 Estimated forward error bounds (machine-dependent)
       8.3E-14    2.6E-14


f07ujfe.r

 F07UJF Example Program Results

 Inverse
             1          2          3          4
 1      0.2326
 2     -0.1891    -0.2053
 3      0.0043    -0.0079    -0.1247
 4      0.8463    -0.2738    -6.1825     8.3333


f07usfe.r

 F07USF Example Program Results

 Solution(s)
                    1                 2
 1  (-5.0000,-2.0000) ( 1.0000, 5.0000)
 2  (-3.0000,-1.0000) (-2.0000,-2.0000)
 3  ( 2.0000, 1.0000) ( 3.0000, 4.0000)
 4  ( 4.0000, 3.0000) ( 4.0000,-3.0000)


f07uufe.r

 F07UUF Example Program Results

 Estimate of condition number =  3.74E+01


f07uvfe.r

 F07UVF Example Program Results

 Solution(s)
                    1                 2
 1  (-5.0000,-2.0000) ( 1.0000, 5.0000)
 2  (-3.0000,-1.0000) (-2.0000,-2.0000)
 3  ( 2.0000, 1.0000) ( 3.0000, 4.0000)
 4  ( 4.0000, 3.0000) ( 4.0000,-3.0000)

 Backward errors (machine-dependent)
         6.2E-17           2.7E-17
 Estimated forward error bounds (machine-dependent)
         2.9E-14           3.2E-14


f07uwfe.r

 F07UWF Example Program Results

 Inverse
                    1                 2                 3                 4
 1  ( 0.1095,-0.1045)
 2  ( 0.0582,-0.0411) (-0.2227,-0.0677)
 3  ( 0.0032, 0.1905) ( 0.1538,-0.2192) ( 0.2323,-0.0448)
 4  ( 0.7602, 0.2814) ( 1.6184,-1.4346) ( 0.1289,-0.2250) ( 1.8697, 1.4731)


f07vefe.r

 F07VEF Example Program Results

 Solution(s)
             1          2
 1      4.0000     1.0000
 2     -1.0000    -3.0000
 3      3.0000     2.0000
 4      2.0000    -2.0000


f07vgfe.r

 F07VGF Example Program Results

 Estimate of condition number =  6.96E+01


f07vhfe.r

 F07VHF Example Program Results

 Solution(s)
             1          2
 1      4.0000     1.0000
 2     -1.0000    -3.0000
 3      3.0000     2.0000
 4      2.0000    -2.0000

 Backward errors (machine-dependent)
       4.7E-17    2.5E-17
 Estimated forward error bounds (machine-dependent)
       5.4E-14    5.8E-14


f07vsfe.r

 F07VSF Example Program Results

 Solution(s)
                    1                 2
 1  ( 0.0000, 2.0000) ( 1.0000, 5.0000)
 2  ( 1.0000,-3.0000) (-7.0000,-2.0000)
 3  (-4.0000,-5.0000) ( 3.0000, 4.0000)
 4  ( 2.0000,-1.0000) (-6.0000,-9.0000)


f07vufe.r

 F07VUF Example Program Results

 Estimate of condition number =  3.35E+01


f07vvfe.r

 F07VVF Example Program Results

 Solution(s)
                    1                 2
 1  ( 0.0000, 2.0000) ( 1.0000, 5.0000)
 2  ( 1.0000,-3.0000) (-7.0000,-2.0000)
 3  (-4.0000,-5.0000) ( 3.0000, 4.0000)
 4  ( 2.0000,-1.0000) (-6.0000,-9.0000)

 Backward errors (machine-dependent)
         4.1E-17           4.2E-17
 Estimated forward error bounds (machine-dependent)
         1.8E-14           2.2E-14


f07wdfe.r

 F07WDF Example Program Results

 Factor
             1          2          3          4
 1      2.0396
 2     -1.5297     1.6401
 3      0.2746    -0.2500     0.7887
 4     -0.0490     0.6737     0.6617     0.5347


f07wefe.r

 F07WEF Example Program Results

 Solution(s)
             1          2
 1      1.0000     4.0000
 2     -1.0000     3.0000
 3      2.0000     2.0000
 4     -3.0000     1.0000


f07wjfe.r

 F07WJF Example Program Results

 Inverse
             1          2          3          4
 1      0.6995
 2      0.7769     1.4239
 3      0.7508     1.8255     4.0688
 4     -0.9340    -1.8841    -2.9342     3.4978


f07wkfe.r

 F07WKF Example Program Results

 Inverse
             1          2          3          4
 1      0.2326
 2     -0.1891    -0.2053
 3      0.0043    -0.0079    -0.1247
 4      0.8463    -0.2738    -6.1825     8.3333


f07wrfe.r

 F07WRF Example Program Results

 Factor
                    1                 2                 3                 4
 1  ( 1.7972, 0.0000)
 2  ( 0.8402, 1.0683) ( 1.3164, 0.0000)
 3  ( 1.0572,-0.4674) (-0.4702, 0.3131) ( 1.5604,-0.0000)
 4  ( 0.2337,-1.3910) ( 0.0834, 0.0368) ( 0.9360, 0.8105) ( 0.8713,-0.0000)


f07wsfe.r

 F07WSF Example Program Results

 Solution(s)
                    1                 2
 1  ( 1.0000,-1.0000) (-1.0000, 2.0000)
 2  (-0.0000, 3.0000) ( 3.0000,-4.0000)
 3  (-4.0000,-5.0000) (-2.0000, 3.0000)
 4  ( 2.0000, 1.0000) ( 4.0000,-5.0000)


f07wwfe.r

 F07WWF Example Program Results

 Inverse
                    1                 2                 3                 4
 1  ( 5.4691, 0.0000)
 2  (-1.2624,-1.5491) ( 1.1024, 0.0000)
 3  (-2.9746,-0.9616) ( 0.8989,-0.5672) ( 2.1589,-0.0000)
 4  ( 1.1962, 2.9772) (-0.9826,-0.2566) (-1.3756,-1.4550) ( 2.2934, 0.0000)


f07wxfe.r

 F07WXF Example Program Results

 Inverse
                    1                 2                 3                 4
 1  ( 0.1095,-0.1045)
 2  ( 0.0582,-0.0411) (-0.2227,-0.0677)
 3  ( 0.0032, 0.1905) ( 0.1538,-0.2192) ( 0.2323,-0.0448)
 4  ( 0.7602, 0.2814) ( 1.6184,-1.4346) ( 0.1289,-0.2250) ( 1.8697, 1.4731)


f08aafe.r

 F08AAF Example Program Results

 Least squares solution
      1.5339     1.8707    -1.5241     0.0392

 Square root of the residual sum of squares
      2.22E-02


f08abfe.r

 F08ABF Example Program Results

 Least squares solution(s)
             1          2
 1      1.5339    -1.5753
 2      1.8707     0.5559
 3     -1.5241     1.3119
 4      0.0392     2.9585

 Square root(s) of the residual sum(s) of squares
        2.22E-02   1.38E-02


f08aefe.r

 F08AEF Example Program Results

 Least squares solution(s)
             1          2
 1      1.5339    -1.5753
 2      1.8707     0.5559
 3     -1.5241     1.3119
 4      0.0392     2.9585

 Square root(s) of the residual sum(s) of squares
        2.22E-02   1.38E-02


f08affe.r

 F08AFF Example Program Results

 The leading  4 columns of Q
          1       2       3       4
 1  -0.1576  0.6744 -0.4571  0.4489
 2  -0.5335 -0.3861  0.2583  0.3898
 3   0.6358 -0.2928  0.0165  0.1930
 4  -0.5335 -0.1692 -0.0834 -0.2350
 5   0.0415 -0.1593  0.1475  0.7436
 6  -0.0055 -0.5064 -0.8339  0.0335


f08ahfe.r

 F08AHF Example Program Results

 Minimum-norm solution(s)
             1          2
 1      0.2371     0.7383
 2     -0.4575     0.0158
 3     -0.0085    -0.0161
 4     -0.5192     1.0768
 5      0.0239    -0.6436
 6     -0.0543    -0.6613


f08ajfe.r

 F08AJF Example Program Results

 The leading  4 rows of Q
          1       2       3       4       5       6
 1  -0.7104  0.4299 -0.4824  0.0354  0.2700  0.0603
 2  -0.2412 -0.5323 -0.4845 -0.1595 -0.6311 -0.0027
 3   0.1287 -0.2619 -0.2108 -0.7447  0.5227 -0.2063
 4  -0.3403 -0.0921  0.4546 -0.3869 -0.0465  0.7191


f08anfe.r

 F08ANF Example Program Results

 Least squares solution
 (-0.5044,-1.2179) (-2.4281, 2.8574) ( 1.4872,-2.1955) ( 0.4537, 2.6904)

 Square root of the residual sum of squares
   6.88E-02


f08apfe.r

 F08APF Example Program Results

 Least squares solution(s)
                    1                 2
 1  (-0.5044,-1.2179) ( 0.7629, 1.4529)
 2  (-2.4281, 2.8574) ( 5.1570,-3.6089)
 3  ( 1.4872,-2.1955) (-2.6518, 2.1203)
 4  ( 0.4537, 2.6904) (-2.7606, 0.3318)

 Square root(s) of the residual sum(s) of squares
      6.88E-02   1.87E-01


f08asfe.r

 F08ASF Example Program Results

 Least squares solution(s)
                    1                 2
 1  (-0.5044,-1.2179) ( 0.7629, 1.4529)
 2  (-2.4281, 2.8574) ( 5.1570,-3.6089)
 3  ( 1.4872,-2.1955) (-2.6518, 2.1203)
 4  ( 0.4537, 2.6904) (-2.7606, 0.3318)

 Square root(s) of the residual sum(s) of squares
      6.88E-02   1.87E-01


f08avfe.r

 F08AVF Example Program Results

 Minimum-norm solution(s)
                    1                 2
 1  (-2.8501, 6.4683) (-1.1682,-1.8886)
 2  ( 1.6264,-0.7799) ( 2.8377, 0.7654)
 3  ( 6.9290, 4.6481) (-1.7610,-0.7041)
 4  ( 1.4048, 3.2400) ( 1.0518,-1.6365)


f08bafe.r

 F08BAF Example Program Results

 Least squares solution
      0.6344     0.9699    -1.4402     3.3678     3.3992

 Tolerance used to estimate the rank of A
      1.00E-02
 Estimated rank of A
      4


f08bbfe.r

 F08BBF Example Program Results

 solution(s) for n rows
             1          2
 1      1.5179    -1.5850
 2      1.8629     0.5531
 3     -1.4608     1.3485
 4      0.0398     2.9619

 Least squares solution(s) for all rows
             1          2
 1      1.5339    -1.5753
 2      1.8707     0.5559
 3     -1.5241     1.3119
 4      0.0392     2.9585

 Square root(s) of the residual sum(s) of squares
        2.22E-02   1.38E-02


f08befe.r

 F08BEF Example Program Results

 Least squares solution
          1       2
 1  -0.0370 -0.0044
 2   0.0647 -0.0335
 3   0.0000  0.0000
 4  -0.0515  0.0018
 5   0.0066  0.0102


f08bffe.r

 F08BFF Example Program Results

 Tolerance used to estimate the rank of A
        1.00E-02
 Estimated rank of A
        4

 Least squares solution(s)
             1          2
 1      0.9767     4.0159
 2      1.9861     2.9867
 3      0.0000     0.0000
 4      2.9927     2.0032
 5      4.0272     0.9976

 Square root(s) of the residual sum(s) of squares
        2.54E-02   3.65E-02


f08bhfe.r

 F08BHF Example Program Results

 Tolerance used to estimate the rank of A
        1.00E-02
 Estimated rank of A
        4

 Least squares solution(s)
             1          2
 1      0.6344     3.6258
 2      0.9699     1.8284
 3     -1.4402    -1.6416
 4      3.3678     2.4307
 5      3.3992     0.2818

 Square root(s) of the residual sum(s) of squares
        2.54E-02   3.65E-02


f08bnfe.r

 F08BNF Example Program Results

 Least squares solution
 ( 1.1669,-3.3224) ( 1.3486, 5.5027) ( 4.1764, 2.3435) ( 0.6467, 0.0107)

 Tolerance used to estimate the rank of A
   1.00E-02
 Estimated rank of A
      3


f08bpfe.r

 F08BPF Example Program Results

 solution(s) for n rows
                    1                 2
 1  (-0.5091,-1.2428) ( 0.7569, 1.4384)
 2  (-2.3789, 2.8651) ( 5.1727,-3.6193)
 3  ( 1.4634,-2.2064) (-2.6613, 2.1339)
 4  ( 0.4701, 2.6964) (-2.6933, 0.2724)

 Least squares solution(s) for all rows
                    1                 2
 1  (-0.5044,-1.2179) ( 0.7629, 1.4529)
 2  (-2.4281, 2.8574) ( 5.1570,-3.6089)
 3  ( 1.4872,-2.1955) (-2.6518, 2.1203)
 4  ( 0.4537, 2.6904) (-2.7606, 0.3318)

 Square root(s) of the residual sum(s) of squares
        6.88E-02   1.87E-01


f08bsfe.r

 F08BSF Example Program Results

 Least squares solution
                    1                 2
 1  ( 0.0000, 0.0000) ( 0.0000, 0.0000)
 2  ( 2.6925, 8.0446) (-2.0563,-2.9759)
 3  ( 2.7602, 2.5455) ( 1.0588, 1.4635)
 4  ( 2.7383, 0.5123) (-1.4150, 0.2982)


f08btfe.r

 F08BTF Example Program Results

 Tolerance used to estimate the rank of A
      1.00E-02
 Estimated rank of A
        3

 Least squares solution(s)
                    1                 2
 1  ( 0.0000, 0.0000) ( 0.0000, 0.0000)
 2  ( 2.7020, 8.0911) (-2.2682,-2.9884)
 3  ( 2.8888, 2.5012) ( 0.9779, 1.3565)
 4  ( 2.7100, 0.4791) (-1.3734, 0.2212)

 Square root(s) of the residual sum(s) of squares
      2.51E-01   8.10E-02


f08bvfe.r

 F08BVF Example Program Results

 Tolerance used to estimate the rank of A
      1.00E-02
 Estimated rank of A
      3

 Least squares solution(s)
                    1                 2
 1  ( 1.1669,-3.3224) (-0.5023, 1.8323)
 2  ( 1.3486, 5.5027) (-1.4418,-1.6465)
 3  ( 4.1764, 2.3435) ( 0.2908, 1.4900)
 4  ( 0.6467, 0.0107) (-0.2453, 0.3951)

 Square root(s) of the residual sum(s) of squares
      2.51E-01   8.10E-02


f08cefe.r

 F08CEF Example Program Results

 Least squares solution(s)
             1          2
 1      1.5339    -1.5753
 2      1.8707     0.5559
 3     -1.5241     1.3119
 4      0.0392     2.9585

 Square root(s) of the residual sum(s) of squares
        2.22E-02   1.38E-02


f08cffe.r

 F08CFF Example Program Results

 The leading    4 columns of Q
          1       2       3       4
 1  -0.0833  0.9100 -0.2202 -0.0809
 2   0.2972 -0.1080 -0.2706  0.6922
 3  -0.6404 -0.2351  0.2220  0.1132
 4   0.4461 -0.1620 -0.3866 -0.0259
 5  -0.2938  0.2022  0.0015  0.6890
 6  -0.4575 -0.1946 -0.8243 -0.1617


f08chfe.r

 F08CHF Example Program Results

 Minimum-norm solution
    0.2371  -0.4575  -0.0085  -0.5192   0.0239  -0.0543


f08cjfe.r

 F08CJF Example Program Results

 The leading    4 rows of Q
          1       2       3       4       5       6
 1  -0.0833  0.2972 -0.6404  0.4461 -0.2938 -0.4575
 2   0.9100 -0.1080 -0.2351 -0.1620  0.2022 -0.1946
 3  -0.2202 -0.2706  0.2220 -0.3866  0.0015 -0.8243
 4  -0.0809  0.6922  0.1132 -0.0259  0.6890 -0.1617


f08csfe.r

 F08CSF Example Program Results

 Least squares solution(s)
                    1                 2
 1  (-0.5044,-1.2179) ( 0.7629, 1.4529)
 2  (-2.4281, 2.8574) ( 5.1570,-3.6089)
 3  ( 1.4872,-2.1955) (-2.6518, 2.1203)
 4  ( 0.4537, 2.6904) (-2.7606, 0.3318)

 Square root(s) of the residual sum(s) of squares
      6.88E-02   1.87E-01


f08cvfe.r

 F08CVF Example Program Results

 Minimum-norm solution
 ( -2.8501,  6.4683) (  1.6264, -0.7799) (  6.9290,  4.6481) (  1.4048,  3.2400)


f08fafe.r

 F08FAF Example Program Results

 Eigenvalues
    -2.0531 -0.5146 -0.2943 12.8621
 Eigenvectors
          1       2       3       4
 1   0.7003 -0.5144 -0.2767  0.4103
 2   0.3592  0.4851  0.6634  0.4422
 3  -0.1569  0.5420 -0.6504  0.5085
 4  -0.5965 -0.4543  0.2457  0.6144

 Error estimate for the eigenvalues
        1.4E-15

 Error estimates for the eigenvectors
        9.3E-16    6.5E-15    6.5E-15    1.1E-16


f08fbfe.r

 F08FBF Example Program Results

 Number of eigenvalues found =    2

 Eigenvalues
    -0.5146 -0.2943
 Selected eigenvectors
          1       2
 1  -0.5144  0.2767
 2   0.4851 -0.6634
 3   0.5420  0.6504
 4  -0.4543 -0.2457


f08fcfe.r

 F08FCF Example Program Results

 Eigenvalues
    -2.0531 -0.5146 -0.2943 12.8621

 Eigenvectors
          1       2       3       4
 1   0.7003 -0.5144 -0.2767  0.4103
 2   0.3592  0.4851  0.6634  0.4422
 3  -0.1569  0.5420 -0.6504  0.5085
 4  -0.5965 -0.4543  0.2457  0.6144


f08fdfe.r

 F08FDF Example Program Results

 Selected eigenvalues
    -0.5146 -0.2943
 Selected eigenvectors
          1       2
 1  -0.5144  0.2767
 2   0.4851 -0.6634
 3   0.5420  0.6504
 4  -0.4543 -0.2457


f08fefe.r

 F08FEF Example Program Results

 Diagonal and off-diagonal elements of tridiagonal form

     i         D            E
     1      2.07000      5.82575
     2      1.47409      2.62405
     3     -0.64916      0.91627
     4     -1.69493


f08fffe.r

 F08FFF Example Program Results

 Eigenvalues
    -5.0034 -1.9987  0.2013  8.0008

 Eigenvectors
          1       2       3       4
 1   0.5658 -0.2328 -0.3965  0.6845
 2  -0.3478  0.7994 -0.1780  0.4564
 3  -0.4740 -0.4087  0.5381  0.5645
 4   0.5781  0.3737  0.7221  0.0676


f08fgfe.r

 F08FGF Example Program Results

 Eigenvalues
    -5.0034 -1.9987

 Eigenvectors
          1       2
 1   0.5658 -0.2328
 2  -0.3478  0.7994
 3  -0.4740 -0.4087
 4   0.5781  0.3737


f08fnfe.r

 F08FNF Example Program Results

 Eigenvalues
    -4.2443 -0.6886  1.1412 13.7916

 Eigenvectors
          1       2       3       4
 1  -0.3839  0.6470  0.0179  0.3309
    -0.2941  0.0000 -0.4453 -0.1986

 2  -0.4512 -0.4984  0.5706  0.3728
     0.1102 -0.1130 -0.0000 -0.2419

 3   0.0263  0.2949 -0.1530  0.4870
     0.4857  0.3165  0.5273 -0.1938

 4   0.5602 -0.2241 -0.2118  0.6155
     0.0000 -0.2878 -0.3598  0.0000

 Error estimate for the eigenvalues
        1.5E-15

 Error estimates for the eigenvectors
        4.3E-16    8.4E-16    8.4E-16    1.2E-16


f08fpfe.r

 F08FPF Example Program Results

 Number of eigenvalues found =    2

 Eigenvalues
    -0.6886  1.1412
 Selected eigenvectors
          1       2
 1   0.6470  0.0179
     0.0000 -0.4453

 2  -0.4984  0.5706
    -0.1130  0.0000

 3   0.2949 -0.1530
     0.3165  0.5273

 4  -0.2241 -0.2118
    -0.2878 -0.3598


f08frfe.r

 F08FRF Example Program Results

 Selected eigenvalues
    -0.6886  1.1412
 Selected eigenvectors
          1       2
 1   0.6470  0.0179
     0.0000 -0.4453

 2  -0.4984  0.5706
    -0.1130  0.0000

 3   0.2949 -0.1530
     0.3165  0.5273

 4  -0.2241 -0.2118
    -0.2878 -0.3598


f08fsfe.r

 F08FSF Example Program Results

 Diagonal and off-diagonal elements of tridiagonal form

     i         D            E
     1     -2.28000      4.33846
     2     -0.12846      2.02259
     3     -0.16659      1.80232
     4     -1.92495


f08fufe.r

 F08FUF Example Program Results

 Eigenvalues
        -6.0002           -3.0030

 Eigenvectors
                    1                 2
 1  ( 0.7299, 0.0000) (-0.2120, 0.1497)
 2  (-0.1663,-0.2061) ( 0.7307, 0.0000)
 3  (-0.4165,-0.1417) (-0.3291, 0.0479)
 4  ( 0.1743, 0.4162) ( 0.5200, 0.1329)


f08gafe.r

 F08GAF Example Program Results

 Eigenvalues
    -2.0531 -0.5146 -0.2943 12.8621

 Error estimate for the eigenvalues
        1.4E-15


f08gbfe.r

 F08GBF Example Program Results

 Number of eigenvalues found =    2

 Eigenvalues
    -0.5146 -0.2943
 Selected eigenvectors
          1       2
 1  -0.5144 -0.2767
 2   0.4851  0.6634
 3   0.5420 -0.6504
 4  -0.4543  0.2457


f08gcfe.r

 F08GCF Example Program Results

 Eigenvalues
    -2.0531 -0.5146 -0.2943 12.8621

 Eigenvectors
          1       2       3       4
 1   0.7003 -0.5144 -0.2767  0.4103
 2   0.3592  0.4851  0.6634  0.4422
 3  -0.1569  0.5420 -0.6504  0.5085
 4  -0.5965 -0.4543  0.2457  0.6144


f08gefe.r

 F08GEF Example Program Results

 Diagonal and off-diagonal elements of tridiagonal form

     i         D            E
     1      2.07000      5.82575
     2      1.47409      2.62405
     3     -0.64916      0.91627
     4     -1.69493


f08gffe.r

 F08GFF Example Program Results

 Eigenvalues
    -5.0034 -1.9987  0.2013  8.0008

 Eigenvectors
          1       2       3       4
 1   0.5658 -0.2328 -0.3965  0.6845
 2  -0.3478  0.7994 -0.1780  0.4564
 3  -0.4740 -0.4087  0.5381  0.5645
 4   0.5781  0.3737  0.7221  0.0676


f08ggfe.r

 F08GGF Example Program Results

 Eigenvalues
    -5.0034 -1.9987

 Eigenvectors
          1       2
 1   0.5658 -0.2328
 2  -0.3478  0.7994
 3  -0.4740 -0.4087
 4   0.5781  0.3737


f08gnfe.r

 F08GNF Example Program Results

 Eigenvalues
    -4.2443 -0.6886  1.1412 13.7916

 Error estimate for the eigenvalues
        1.5E-15


f08gpfe.r

 F08GPF Example Program Results

 Number of eigenvalues found =    2

 Eigenvalues
    -0.6886  1.1412
 Selected eigenvectors
          1       2
 1   0.6470  0.0179
     0.0000 -0.4453

 2  -0.4984  0.5706
    -0.1130 -0.0000

 3   0.2949 -0.1530
     0.3165  0.5273

 4  -0.2241 -0.2118
    -0.2878 -0.3598


f08gsfe.r

 F08GSF Example Program Results

 Diagonal and off-diagonal elements of tridiagonal form

     i         D            E
     1     -2.28000      4.33846
     2     -0.12846      2.02259
     3     -0.16659      1.80232
     4     -1.92495


f08gufe.r

 F08GUF Example Program Results

 Eigenvalues
        -6.0002           -3.0030

 Eigenvectors
                    1                 2
 1  ( 0.7299, 0.0000) (-0.2120, 0.1497)
 2  (-0.1663,-0.2061) ( 0.7307,-0.0000)
 3  (-0.4165,-0.1417) (-0.3291, 0.0479)
 4  ( 0.1743, 0.4162) ( 0.5200, 0.1329)


f08hafe.r

 F08HAF Example Program Results

 Eigenvalues
    -3.2474 -2.6633  1.7511  4.1599 14.9997
 Eigenvectors
          1       2       3       4       5
 1   0.0394  0.6238  0.5635  0.5165  0.1582
 2   0.5721 -0.2575 -0.3896  0.5955  0.3161
 3  -0.4372 -0.5900  0.4008  0.1470  0.5277
 4  -0.4424  0.4308 -0.5581 -0.0470  0.5523
 5   0.5332  0.1039  0.2421 -0.5956  0.5400

 Error estimate for the eigenvalues
        1.7E-15

 Error estimates for the eigenvectors
        2.9E-15    2.9E-15    6.9E-16    6.9E-16    1.5E-16


f08hbfe.r

 F08HBF Example Program Results

 Number of eigenvalues found =    2

 Eigenvalues
    -2.6633  1.7511
 Selected eigenvectors
          1       2
 1  -0.6238 -0.5635
 2   0.2575  0.3896
 3   0.5900 -0.4008
 4  -0.4308  0.5581
 5  -0.1039 -0.2421


f08hcfe.r

 F08HCF Example Program Results

 Eigenvalues
    -3.2474 -2.6633  1.7511  4.1599 14.9997

 Eigenvectors
          1       2       3       4       5
 1   0.0394  0.6238  0.5635  0.5165  0.1582
 2   0.5721 -0.2575 -0.3896  0.5955  0.3161
 3  -0.4372 -0.5900  0.4008  0.1470  0.5277
 4  -0.4424  0.4308 -0.5581 -0.0470  0.5523
 5   0.5332  0.1039  0.2421 -0.5956  0.5400


f08hefe.r

 F08HEF Example Program Results

 Eigenvalues
    -2.9943 -0.7000  1.9974  4.9969

 Eigenvectors
          1       2       3       4
 1   0.0251  0.0162  0.0113  0.9995
 2  -0.0656 -0.5859  0.8077  0.0020
 3  -0.9002 -0.3135 -0.3006  0.0311
 4  -0.4298  0.7471  0.5070 -0.0071


f08hpfe.r

 F08HPF Example Program Results

 Number of eigenvalues found =    2

 Eigenvalues
    -1.4094  1.4421
 Selected eigenvectors
          1       2
 1   0.6367  0.4516
     0.0000  0.0000

 2  -0.2578 -0.3029
     0.2413 -0.4402

 3  -0.3039  0.3160
    -0.3481  0.2978

 4   0.3450 -0.4088
    -0.0832 -0.3213

 5  -0.2469  0.0204
     0.2634  0.2262


f08jafe.r

 F08JAF Example Program Results

 Eigenvalues
     0.6476  3.5470  8.6578 17.1477
 Eigenvectors
          1       2       3       4
 1   0.9396  0.3388  0.0494  0.0034
 2  -0.3311  0.8628  0.3781  0.0545
 3   0.0853 -0.3648  0.8558  0.3568
 4  -0.0167  0.0879 -0.3497  0.9326

 Error estimate for the eigenvalues
        1.9E-15

 Error estimates for the eigenvectors
        6.6E-16    6.6E-16    3.7E-16    2.2E-16


f08jbfe.r

 F08JBF Example Program Results

 Number of eigenvalues found =    2

 Eigenvalues
     0.6476  3.5470
 Selected eigenvectors
          1       2
 1   0.9396  0.3388
 2  -0.3311  0.8628
 3   0.0853 -0.3648
 4  -0.0167  0.0879


f08jcfe.r

 F08JCF Example Program Results

 Eigenvalues
     0.6476  3.5470  8.6578 17.1477

 Eigenvectors
          1       2       3       4
 1   0.9396  0.3388  0.0494  0.0034
 2  -0.3311  0.8628  0.3781  0.0545
 3   0.0853 -0.3648  0.8558  0.3568
 4  -0.0167  0.0879 -0.3497  0.9326


f08jdfe.r

 F08JDF Example Program Results

 Selected eigenvalues
     3.5470  8.6578
 Selected eigenvectors
          1       2
 1   0.3388  0.0494
 2   0.8628  0.3781
 3  -0.3648  0.8558
 4   0.0879 -0.3497


f08jefe.r

 F08JEF Example Program Results

 Eigenvalues
    -7.0037 -0.4059  2.0028  8.9968

 Eigenvectors
          1       2       3       4
 1   0.9995  0.0109  0.0167  0.0255
 2   0.0310 -0.1627 -0.3408 -0.9254
 3   0.0089 -0.5170 -0.7696  0.3746
 4   0.0014 -0.8403  0.5397 -0.0509


f08jffe.r

 F08JFF Example Program Results

 Eigenvalues
    -7.0037 -0.4059  2.0028  8.9968


f08jgfe.r

 F08JGF Example Program Results

 Eigenvalues
     8.0023  1.9926  1.0014  0.1237

 Eigenvectors
          1       2       3       4
 1   0.6326  0.6245 -0.4191  0.1847
 2   0.7668 -0.4270  0.4176 -0.2352
 3  -0.1082  0.6071  0.4594 -0.6393
 4  -0.0081  0.2432  0.6625  0.7084


f08jhfe.r

 F08JHF Example Program Results

 Eigenvalues
    -2.9943 -0.7000  1.9974  4.9969

 Eigenvectors
          1       2       3       4
 1   0.0251  0.0162  0.0113  0.9995
 2  -0.0656 -0.5859  0.8077  0.0020
 3  -0.9002 -0.3135 -0.3006  0.0311
 4  -0.4298  0.7471  0.5070 -0.0071


f08jlfe.r

 F08JLF Example Program Results

 Eigenvalues
     0.6476  3.5470  8.6578 17.1477

 Eigenvectors
          1       2       3       4
 1   0.9396  0.3388  0.0494  0.0034
 2  -0.3311  0.8628  0.3781  0.0545
 3   0.0853 -0.3648  0.8558  0.3568
 4  -0.0167  0.0879 -0.3497  0.9326


f08kafe.r

 F08KAF Example Program Results

 Least squares solution
      0.6344     0.9699    -1.4403     3.3678     3.3992

 Tolerance used to estimate the rank of A
      1.00E-02
 Estimated rank of A
      4

 Singular values of A
      3.9997     2.9962     2.0001     0.9988     0.0025


f08kbfe.r

 F08KBF Example Program Results

 Singular values of A:
         9.9966        3.6831        1.3569        0.5000

 Least squares solution:
        -0.0563       -0.1700        0.8202        0.5545

 Norm of Residual:
         1.7472


f08kcfe.r

 F08KCF Example Program Results

 Least squares solution
      1.5938    -0.1180    -3.1501     0.1554     2.5529    -1.6730

 Tolerance used to estimate the rank of A
      1.00E-02
 Estimated rank of A
      4

 Singular values of A
      3.9997     2.9962     2.0001     0.9988     0.0025


f08kdfe.r

 F08KDF Example Program Results

 Singular values
     9.9966  3.6831  1.3569  0.5000
 Left singular vectors
          1       2       3       4
 1   0.1921  0.8030  0.0041  0.5642
 2  -0.8794  0.3926 -0.0752 -0.2587
 3   0.2140  0.2980  0.7827 -0.5027
 4  -0.3795 -0.3351  0.6178  0.6017

 Right singular vectors by row (first m rows of V**T)
          1       2       3       4       5       6
 1   0.2774  0.2020  0.2918 -0.0938 -0.4213  0.7816
 2   0.6003  0.0301 -0.3348  0.3699 -0.5266 -0.3353
 3  -0.1277  0.2805  0.6453  0.6781  0.0413 -0.1645
 4  -0.1323 -0.7034 -0.1906  0.5399  0.0575  0.3957

 Error estimate for the singular values
        1.1E-15

 Error estimates for the left singular vectors
        1.8E-16    4.8E-16    1.3E-15    1.3E-15

 Error estimates for the right singular vectors
        1.8E-16    4.8E-16    1.3E-15    2.2E-15


f08kefe.r

 F08KEF Example Program Results

 Diagonal
    3.6177   2.4161  -1.9213  -1.4265
 Superdiagonal
    1.2587   1.5262  -1.1895


f08kgfe.r

 F08KGF Example Program Results

 Example 1: bidiagonal matrix B
 Diagonal
     3.6177 -2.4161  1.9213 -1.4265
 Superdiagonal
     1.2587 -1.5262  1.1895

 Example 1: matrix Q
          1       2       3       4
 1  -0.1576 -0.2690  0.2612  0.8513
 2  -0.5335  0.5311 -0.2922  0.0184
 3   0.6358  0.3495 -0.0250 -0.0210
 4  -0.5335  0.0035  0.1537 -0.2592
 5   0.0415  0.5572 -0.2917  0.4523
 6  -0.0055  0.4614  0.8585 -0.0532

 Example 2: bidiagonal matrix B
 Diagonal
    -7.7724  6.1573 -6.0576  5.7933
 Superdiagonal
     1.1926  0.5734 -1.9143

 Example 2: matrix P**T
          1       2       3       4       5       6
 1  -0.7104  0.4299 -0.4824  0.0354  0.2700  0.0603
 2   0.3583  0.1382 -0.4110  0.4044  0.0951 -0.7148
 3  -0.0507  0.4244  0.3795  0.7402 -0.2773  0.2203
 4   0.2442  0.4016  0.4158 -0.1354  0.7666 -0.0137


f08khfe.r

 F08KHF Example Program Results

 Singular values
     9.9966  3.6831  1.3569  0.5000

 Left singular vectors
          1       2       3       4
 1   0.2774 -0.6003 -0.1277  0.1323
 2   0.2020 -0.0301  0.2805  0.7034
 3   0.2918  0.3348  0.6453  0.1906
 4  -0.0938 -0.3699  0.6781 -0.5399
 5  -0.4213  0.5266  0.0413 -0.0575
 6   0.7816  0.3353 -0.1645 -0.3957

 Right singular vectors
          1       2       3       4
 1   0.1921 -0.8030  0.0041 -0.5642
 2  -0.8794 -0.3926 -0.0752  0.2587
 3   0.2140 -0.2980  0.7827  0.5027
 4  -0.3795  0.3351  0.6178 -0.6017

 Estimate of the condition number of column equilibrated A
        9.0E+00

 Error estimate for the singular values
        1.1E-15

 Error estimates for left singular vectors
        1.8E-16    4.8E-16    1.3E-15    2.2E-15

 Error estimates for right singular vectors
        1.8E-16    4.8E-16    1.3E-15    1.3E-15


f08kjfe.r

 F08KJF Example Program Results

 Singular values
     9.9966  3.6831  1.3569  0.5000
 Left singular vectors
          1       2       3       4
 1  -0.2774  0.6003 -0.1277  0.1323
 2  -0.2020  0.0301  0.2805  0.7034
 3  -0.2918 -0.3348  0.6453  0.1906
 4   0.0938  0.3699  0.6781 -0.5399
 5   0.4213 -0.5266  0.0413 -0.0575
 6  -0.7816 -0.3353 -0.1645 -0.3957

 Right singular vectors
          1       2       3       4
 1  -0.1921  0.8030  0.0041 -0.5642
 2   0.8794  0.3926 -0.0752  0.2587
 3  -0.2140  0.2980  0.7827  0.5027
 4   0.3795 -0.3351  0.6178 -0.6017

 Error estimate for the singular values
        1.1E-15

 Error estimates for left singular vectors
        1.8E-16    4.8E-16    1.3E-15    2.2E-15

 Error estimates for right singular vectors
        1.8E-16    4.8E-16    1.3E-15    1.3E-15


f08kmfe.r

 F08KMF Example Program Results

 Singular values of A:
         3.6831        1.3569

 Estimates given as multiples of machine precision
 Error estimate for the singular values
              4

 Error estimates for the left singular vectors
              2          3

 Error estimates for the right singular vectors
              2          2


f08knfe.r

 F08KNF Example Program Results

 Least squares solution
 ( 1.1673,-3.3222) ( 1.3480, 5.5028) ( 4.1762, 2.3434) ( 0.6465, 0.0105)

 Tolerance used to estimate the rank of A
      1.00E-02
 Estimated rank of A
      3

 Singular values of A
      2.9979     1.9983     1.0044     0.0064


f08kpfe.r

 F08KPF Example Program Results

 Singular values of A:
         3.9994        3.0003        1.9944        0.9995

 Least squares solution:
    ( -0.0719, -0.2761)
    (  0.6796,  0.4326)
    ( -0.3832, -0.5447)
    (  0.0096, -0.3489)

 Norm of Residual:
         1.5266


f08kqfe.r

 F08KQF Example Program Results

 Least squares solution
 ( 3.9747,-1.8377) (-0.9186, 0.8253) (-0.3105, 0.1477) ( 1.0050, 0.8626)
 (-0.2256,-1.9425)

 Tolerance used to estimate the rank of A
      1.00E-02
 Estimated rank of A
      3

 Singular values of A
      2.9979     1.9983     1.0044     0.0064


f08krfe.r

 F08KRF Example Program Results

 Singular values of A:
         3.9994        3.0003        1.9944        0.9995

 Minimum norm solution:
    ( -0.4024,  0.3777)
    ( -0.2272,  0.3626)
    (  0.1704, -0.1532)
    (  0.2125,  0.0781)
    (  0.2041,  0.2236)
    (  0.2766, -0.1517)

 Norm of Solution:
         0.8846

 Norm of Residual:
         0.0000


f08ksfe.r

 F08KSF Example Program Results

 Diagonal
   -3.0870   2.0660   1.8731   2.0022
 Superdiagonal
    2.1126   1.2628  -1.6126


f08kvfe.r

 F08KVF Example Program Results

 Singular values
     3.9994  3.0003  1.9944  0.9995

 Left singular vectors
          1       2       3       4
 1   0.5634 -0.1804  0.0757  0.0127
    -0.0021  0.3395 -0.5208  0.4822

 2  -0.1200  0.1917 -0.4535  0.0220
     0.6109  0.2443 -0.1124 -0.0420

 3   0.0815  0.4205  0.6021  0.1237
    -0.1614  0.0403 -0.0346 -0.2071

 4  -0.1440 -0.2257  0.0942  0.5805
     0.1534 -0.1364 -0.1237 -0.1439

 5   0.2488  0.1251 -0.2252  0.0533
     0.0924 -0.6961 -0.1398  0.0860

 6   0.3758 -0.0684  0.0004  0.0448
    -0.0796  0.0540 -0.2158 -0.5805

 Right singular vectors
          1       2       3       4
 1   0.6971 -0.0729  0.4144 -0.2817
    -0.0006 -0.2289  0.3013 -0.3384

 2   0.0864  0.2006  0.3471  0.8276
    -0.3549 -0.1400  0.0379 -0.0000

 3  -0.0564  0.5794 -0.3585 -0.2202
    -0.5399  0.0755  0.3776 -0.2106

 4   0.1876 -0.4206 -0.5845  0.1264
    -0.2254 -0.6035  0.0527  0.1116

 Estimate of the condition number of column equilibrated A
       2.61E+00

 Error estimates (as multiples of machine precision):

   for the singular values
       4

   for left singular vectors
       4   4   4   4

   for right singular vectors
       4   4   4   4


f08kzfe.r

 F08KZF Example Program Results

 Singular values of A:
         3.9994        3.0003        1.9944

 Error estimates (as multiples of machine precision):
   for the singular values
              4

   for the left singular vectors
              4          4          4

   for the right singular vectors
              4          4          4


f08lefe.r

 F08LEF Example Program Results

 Diagonal D:
         3.0561        1.5259        0.9690        1.5685

 Off-diagonal E:
         0.6206        1.2353        1.1240


f08lsfe.r

 F08LSF Example Program Results

 Diagonal
    2.6560   1.7501   2.0607   0.8658
 Superdiagonal
    1.7033   1.2800   0.1467


f08mbfe.r

 F08MBF Example Program Results

  3 singular values of B in the range [  0.000,  4.000]:
         3.0006        1.9960        0.9998


f08mdfe.r

 F08MDF Example Program Results

 Singular values of B:
         4.0001        3.0006        1.9960        0.9998


f08mefe.r

 F08MEF Example Program Results

 Singular values
     4.0001  3.0006  1.9960  0.9998

 Right singular vectors, by row
          1       2       3       4
 1   0.8261  0.5246  0.2024  0.0369
 2   0.4512 -0.4056 -0.7350 -0.3030
 3   0.2823 -0.5644  0.1731  0.7561
 4   0.1852 -0.4916  0.6236 -0.5789

 Left singular vectors, by column
          1       2       3       4
 1   0.9129  0.3740  0.1556  0.0512
 2  -0.3935  0.7005  0.5489  0.2307
 3   0.1081 -0.5904  0.6173  0.5086
 4  -0.0132  0.1444 -0.5417  0.8280


f08nafe.r

 F08NAF Example Program Results

 Eigenvalue( 1) =  7.9948E-01

 Eigenvector( 1)
 -6.5509E-01
 -5.2363E-01
  5.3622E-01
 -9.5607E-02

 Eigenvalue( 2) = (-9.9412E-02, 4.0079E-01)

 Eigenvector( 2)
 (-1.9330E-01, 2.5463E-01)
 ( 2.5186E-01,-5.2240E-01)
 ( 9.7182E-02,-3.0838E-01)
 ( 6.7595E-01, 0.0000E+00)

 Eigenvalue( 3) = (-9.9412E-02,-4.0079E-01)

 Eigenvector( 3)
 (-1.9330E-01,-2.5463E-01)
 ( 2.5186E-01, 5.2240E-01)
 ( 9.7182E-02, 3.0838E-01)
 ( 6.7595E-01,-0.0000E+00)

 Eigenvalue( 4) = -1.0066E-01

 Eigenvector( 4)
  1.2533E-01
  3.3202E-01
  5.9384E-01
  7.2209E-01


f08nbfe.r

 F08NBF Example Program Results

 Eigenvalues

          Eigenvalue           rcond    error
  1   7.9948E-01               0.9936    -
  2 (-9.9412E-02, 4.0079E-01)  0.7027    -
  3 (-9.9412E-02,-4.0079E-01)  0.7027    -
  4  -1.0066E-01               0.5710    -

 Eigenvectors

          Eigenvector          rcond    error

  1   6.5509E-01               0.6252    -
      5.2363E-01
     -5.3622E-01
      9.5607E-02

  2 (-1.9330E-01, 2.5463E-01)  0.3996    -
    ( 2.5186E-01,-5.2240E-01)
    ( 9.7182E-02,-3.0838E-01)
    ( 6.7595E-01, 0.0000E+00)

  3 (-1.9330E-01,-2.5463E-01)  0.3996    -
    ( 2.5186E-01, 5.2240E-01)
    ( 9.7182E-02, 3.0838E-01)
    ( 6.7595E-01,-0.0000E+00)

  4   1.2533E-01               0.3125    -
      3.3202E-01
      5.9384E-01
      7.2209E-01

 Errors below 10*machine precision are not displayed


f08nefe.r

 F08NEF Example Program Results

 Upper Hessenberg form
          1       2       3       4
 1   0.3500 -0.1160 -0.3886 -0.2942
 2  -0.5140  0.1225  0.1004  0.1126
 3   0.0000  0.6443 -0.1357 -0.0977
 4   0.0000  0.0000  0.4262  0.1632


f08nffe.r

 F08NFF Example Program Results

 Matrix A
          1       2       3       4
 1   0.3500  0.4500 -0.1400 -0.1700
 2   0.0900  0.0700 -0.5400  0.3500
 3  -0.4400 -0.3300 -0.0300  0.1700
 4   0.2500 -0.3200 -0.1300  0.1100

 Eigenvalues
  (  0.7995,  0.0000)
  ( -0.0994,  0.4008)
  ( -0.0994, -0.4008)
  ( -0.1007,  0.0000)


f08ngfe.r

 F08NGF Example Program Results

 Eigenvalues
  (  0.7995,  0.0000)
  ( -0.0994,  0.4008)
  ( -0.0994, -0.4008)
  ( -0.1007,  0.0000)

 Contents of array C
          1       2       3
 1  -0.1933  0.2546  0.1493
 2   0.2519 -0.5224  0.3956
 3   0.0972 -0.3084  0.7075
 4   0.6760  0.0000  0.8603


f08nhfe.r

 F08NHF Example Program Results

 Eigenvalues
  ( -0.4000,  0.0000)
  ( -4.0208,  0.0000)
  (  3.0136,  0.0000)
  (  7.0072,  0.0000)

 Contents of array VR
          1       2       3       4
 1   0.0000 -0.4381  0.4654  0.9513
 2   0.0000  0.8923  0.7888 -0.1714
 3   1.0000 -0.0481  0.3981  0.2494
 4   0.0000 -0.0976  0.0521 -0.0589


f08nufe.r

 F08NUF Example Program Results

 Eigenvalues
    (-6.0004,-6.9998) (-5.0000, 2.0060) ( 7.9982,-0.9964) ( 3.0023,-3.9998)

 Contents of array C
                    1                 2
 1  ( 0.8457, 0.0000) (-0.3865, 0.1732)
 2  (-0.0177, 0.3036) (-0.3539, 0.4529)
 3  ( 0.0875, 0.3115) ( 0.6124, 0.0000)
 4  (-0.0561,-0.2906) (-0.0859,-0.3284)


f08pafe.r

 F08PAF Example Program Results

 Matrix A
          1       2       3       4
 1   0.3500  0.4500 -0.1400 -0.1700
 2   0.0900  0.0700 -0.5400  0.3500
 3  -0.4400 -0.3300 -0.0300  0.1700
 4   0.2500 -0.3200 -0.1300  0.1100

 Number of eigenvalues for which SELECT is true =    1
 (dimension of invariant subspace)

 Selected eigenvalues
  (  0.7995,  0.0000)


f08pbfe.r

 F08PBF Example Program Results

 Matrix A
          1       2       3       4
 1   0.3500  0.4500 -0.1400 -0.1700
 2   0.0900  0.0700 -0.5400  0.3500
 3  -0.4400 -0.3300 -0.0300  0.1700
 4   0.2500 -0.3200 -0.1300  0.1100

 Number of eigenvalues for which SELECT is true =    1
 (dimension of invariant subspace)

 Selected eigenvalues
  (  0.7995,  0.0000)


f08pefe.r

 F08PEF Example Program Results
 Matrix H
          1       2       3       4
 1   0.3500 -0.1160 -0.3886 -0.2942
 2  -0.5140  0.1225  0.1004  0.1126
 3   0.0000  0.6443 -0.1357 -0.0977
 4   0.0000  0.0000  0.4262  0.1632

 Eigenvalues
  (  0.7995,  0.0000)
  ( -0.0994,  0.4008)
  ( -0.0994, -0.4008)
  ( -0.1007,  0.0000)


f08ppfe.r

 F08PPF Example Program Results

 Matrix A
                    1                 2                 3                 4
 1  (-3.9700,-5.0400) (-4.1100, 3.7000) (-0.3400, 1.0100) ( 1.2900,-0.8600)
 2  ( 0.3400,-1.5000) ( 1.5200,-0.4300) ( 1.8800,-5.3800) ( 3.3600, 0.6500)
 3  ( 3.3100,-3.8500) ( 2.5000, 3.4500) ( 0.8800,-1.0800) ( 0.6400,-1.4800)
 4  (-1.1000, 0.8200) ( 1.8100,-1.5900) ( 3.2500, 1.3300) ( 1.5700,-3.4400)

 Number of eigenvalues for which SELECT is true =    2
 (dimension of invariant subspace)

 Selected eigenvalues
    1   ( 7.9982,-0.9964)
    2   ( 3.0023,-3.9998)


f08qffe.r

 F08QFF Example Program Results

 Reordered Schur form
          1       2       3       4
 1  -0.1000 -0.6463  0.0874  0.2010
 2   0.2514 -0.1000  0.0927  0.3505
 3   0.0000  0.0000  0.8000 -0.0117
 4   0.0000  0.0000  0.0000 -0.1000


f08qgfe.r

 F08QGF Example Program Results

 Matrix A computed from Q*T*Q^T
          1       2       3       4
 1   0.3500  0.4500 -0.1400 -0.1700
 2   0.0900  0.0700 -0.5399  0.3500
 3  -0.4400 -0.3300 -0.0300  0.1700
 4   0.2500 -0.3200 -0.1300  0.1100

 Condition number estimate of the selected cluster of eigenvalues =   1.75E+00

 Condition number estimate of the specified invariant subspace    =   3.22E+00


f08qhfe.r

 F08QHF Example Program Results

 Solution Matrix
          1       2       3       4
 1  -0.4209  0.1764  0.2438 -0.9577
 2   0.5600 -0.8337 -0.7221  0.5386
 3  -0.1246 -0.3392  0.6221  0.8691
 4  -0.2865  0.4113  0.5535  0.3174


f08qlfe.r

 F08QLF Example Program Results

 S
       9.9E-01    7.0E-01    7.0E-01    5.7E-01

 SEP
       6.3E-01    3.7E-01    3.7E-01    3.1E-01

 Approximate error estimates for eigenvalues of T (machine-dependent)
       9.6E-17    1.4E-16    1.4E-16    1.7E-16

 Approximate error estimates for right eigenvectors of T (machine-dependent)
       1.5E-16    2.6E-16    2.6E-16    3.1E-16


f08qufe.r

 F08QUF Example Program Results

 Matrix A created from Q*T*Q^T
                    1                 2                 3                 4
 1  (-3.9702,-5.0406) (-4.1108, 3.7002) (-0.3403, 1.0098) ( 1.2899,-0.8590)
 2  ( 0.3397,-1.5006) ( 1.5201,-0.4301) ( 1.8797,-5.3804) ( 3.3606, 0.6498)
 3  ( 3.3101,-3.8506) ( 2.4996, 3.4504) ( 0.8802,-1.0802) ( 0.6401,-1.4800)
 4  (-1.0999, 0.8199) ( 1.8103,-1.5905) ( 3.2502, 1.3297) ( 1.5701,-3.4397)

 Condition number estimate of the selected cluster of eigenvalues =   1.02E+00

 Condition number estimate of the specified invariant subspace    =   1.82E-01


f08qyfe.r

 F08QYF Example Program Results

 S
       9.9E-01    1.0E+00    9.8E-01    9.8E-01

 SEP
       8.4E+00    8.0E+00    5.8E+00    5.8E+00

 Approximate error estimates for eigenvalues of T (machine-dependent)
       1.0E-15    1.0E-15    1.1E-15    1.1E-15

 Approximate error estimates for right eigenvectors of T (machine-dependent)
       1.2E-16    1.3E-16    1.8E-16    1.8E-16


f08safe.r

 F08SAF Example Program Results

 Eigenvalues
       -2.2254    -0.4548     0.1001     1.1270

 Eigenvectors
             1          2          3          4
 1      0.0690    -0.3080    -0.4469     0.5528
 2      0.5740    -0.5329    -0.0371     0.6766
 3      1.5428     0.3496     0.0505     0.9276
 4     -1.4004     0.6211     0.4743    -0.2510

 Estimate of reciprocal condition number for B
        5.8E-03

 Error estimates for the eigenvalues
        4.7E-14    1.2E-14    5.6E-15    2.5E-14

 Error estimates for the eigenvectors
        5.2E-14    1.0E-13    9.2E-14    6.9E-14


f08sbfe.r

 F08SBF Example Program Results

 Number of eigenvalues found =    2

 Eigenvalues
    -0.4548  0.1001
 Selected eigenvectors
          1       2
 1  -0.3080 -0.4469
 2  -0.5329 -0.0371
 3   0.3496  0.0505
 4   0.6211  0.4743


f08scfe.r

 F08SCF Example Program Results

 Eigenvalues
       -3.5411    -0.3347     0.2983     2.2544
 Eigenvectors
             1          2          3          4
 1     -0.0356    -0.1039    -0.7459     0.1909
 2      0.3809     0.4322    -0.7845     0.3540
 3     -0.2943     1.5644    -0.7144     0.5665
 4     -0.3186    -1.0647     1.1184     0.3859

 Estimate of reciprocal condition number for B
        5.8E-03

 Error estimates for the eigenvalues
        7.0E-14    8.6E-15    7.9E-15    4.6E-14

 Error estimates for the eigenvectors
        2.8E-14    6.4E-14    6.4E-14    3.4E-14


f08sefe.r

 F08SEF Example Program Results

 Eigenvalues
    -2.2254 -0.4548  0.1001  1.1270


f08snfe.r

 F08SNF Example Program Results

 Eigenvalues
       -5.9990    -2.9936     0.5047     3.9990
 Eigenvectors
             1          2          3          4
 1      1.7405    -0.6626     0.2835     1.2378
        0.0000     0.2258    -0.5806     0.0000

 2     -0.4136    -0.1164    -0.3769    -0.5608
       -0.4689    -0.0178    -0.3194    -0.3729

 3     -0.8404     0.9098    -0.3338    -0.6643
       -0.2483    -0.0000    -0.0134    -0.1021

 4      0.3021    -0.6120     0.6663     0.1589
        0.6103    -0.5348     0.0000     0.8366

 Estimate of reciprocal condition number for B
        2.5E-03

 Error estimates for the eigenvalues
        3.4E-13    2.0E-13    9.6E-14    2.5E-13

 Error estimates for the eigenvectors
        5.8E-13    5.3E-13    4.3E-13    4.7E-13


f08spfe.r

 F08SPF Example Program Results

 Number of eigenvalues found =    2

 Eigenvalues
    -2.9936  0.5047
 Selected eigenvectors
          1       2
 1  -0.6626  0.2835
     0.2258 -0.5806

 2  -0.1164 -0.3769
    -0.0178 -0.3194

 3   0.9098 -0.3338
     0.0000 -0.0134

 4  -0.6120  0.6663
    -0.5348  0.0000


f08sqfe.r

 F08SQF Example Program Results

 Eigenvalues
      -61.7321    -6.6195     0.0725    43.1883
 Eigenvectors
             1          2          3          4
 1      0.3903    -0.1560     2.2909    -0.1943
        0.0000    -0.0404     0.0000    -0.0690

 2     -0.1814    -0.1552    -0.5042     0.3884
        0.0114    -0.3651    -0.7120     0.0000

 3      0.0438     0.5364    -1.2701     0.0657
        0.0338     0.0000    -0.4547    -0.2095

 4     -0.2221    -0.1298     0.5706     0.2924
       -0.2272    -0.1880     1.3132    -0.0675

 Estimate of reciprocal condition number for B
        2.5E-03

 Error estimates (relative to machine precision)
 for the eigenvalues:
        2.4E+04    2.8E+03    2.3E+02    1.7E+04

 for the eigenvectors:
        4.7E+02    1.0E+03    1.0E+03    4.9E+02


f08ssfe.r

 F08SSF Example Program Results

 Eigenvalues
    -5.9990 -2.9936  0.5047  3.9990


f08tafe.r

 F08TAF Example Program Results

 Eigenvalues
       -2.2254    -0.4548     0.1001     1.1270

 Estimate of reciprocal condition number for B
        5.8E-03

 Error estimates for the eigenvalues
        4.7E-14    1.2E-14    5.6E-15    2.5E-14


f08tbfe.r

 F08TBF Example Program Results

 Number of eigenvalues found =    2

 Eigenvalues
    -0.4548  0.1001
 Selected eigenvectors
          1       2
 1  -0.3080 -0.4469
 2  -0.5329 -0.0371
 3   0.3496  0.0505
 4   0.6211  0.4743


f08tcfe.r

 F08TCF Example Program Results

 Eigenvalues
       -3.5411    -0.3347     0.2983     2.2544

 Estimate of reciprocal condition number for B
        5.8E-03

 Error estimates for the eigenvalues
        7.0E-14    8.6E-15    7.9E-15    4.6E-14


f08tefe.r

 F08TEF Example Program Results

 Eigenvalues
    -2.2254 -0.4548  0.1001  1.1270


f08tnfe.r

 F08TNF Example Program Results

 Eigenvalues
       -5.9990    -2.9936     0.5047     3.9990

 Estimate of reciprocal condition number for B
        2.5E-03

 Error estimates for the eigenvalues
        3.4E-13    2.0E-13    9.6E-14    2.5E-13


f08tpfe.r

 F08TPF Example Program Results

 Number of eigenvalues found =    2

 Eigenvalues
    -2.9936  0.5047
 Selected eigenvectors
          1       2
 1  -0.6626  0.2835
     0.2258 -0.5806

 2  -0.1164 -0.3769
    -0.0178 -0.3194

 3   0.9098 -0.3338
    -0.0000 -0.0134

 4  -0.6120  0.6663
    -0.5348  0.0000


f08tqfe.r

 F08TQF Example Program Results

 Eigenvalues
      -61.7321    -6.6195     0.0725    43.1883

 Estimate of reciprocal condition number for B
        2.5E-03

 Error estimates (relative to machine precision)
 for the eigenvalues:
        2.4E+04    2.8E+03    2.3E+02    1.7E+04


f08tsfe.r

 F08TSF Example Program Results

 Eigenvalues
    -5.9990 -2.9936  0.5047  3.9990


f08uafe.r

 F08UAF Example Program Results

 Eigenvalues
       -0.8305    -0.6401     0.0992     1.8525


f08ubfe.r

 F08UBF Example Program Results

 Number of eigenvalues found =    1

 Eigenvalues
     0.0992
 Selected eigenvectors
          1
 1   0.6729
 2  -0.1009
 3   0.0155
 4  -0.3806


f08ucfe.r

 F08UCF Example Program Results

 Eigenvalues
       -0.8305    -0.6401     0.0992     1.8525


f08uefe.r

 F08UEF Example Program Results

 Eigenvalues
    -0.8305 -0.6401  0.0992  1.8525


f08unfe.r

 F08UNF Example Program Results

 Eigenvalues
       -6.6089    -2.0416     0.1603     1.7712


f08upfe.r

 F08UPF Example Program Results

 Number of eigenvalues found =    2

 Eigenvalues
     0.1603  1.7712
 Selected eigenvectors
             1          2
 1      0.1908     0.0494
        0.0137    -0.0045

 2      0.1413     0.2505
        0.1012     0.4427

 3     -0.0437    -0.9705
       -0.0905     0.0679

 4     -0.2135     0.0606
        0.2880    -1.3227


f08uqfe.r

 F08UQF Example Program Results

 Eigenvalues
       -6.6089    -2.0416     0.1603     1.7712


f08usfe.r

 F08USF Example Program Results

 Eigenvalues
    -6.6089 -2.0416  0.1603  1.7712


f08vafe.r

 F08VAF Example Program Results

 Number of infinite generalized singular values (K)
     1
 Number of finite generalized singular values (L)
     2
 Numerical rank of (A**T B**T)**T (K+L)
     3

 Finite generalized singular values
     1.3151E+00  8.0185E-02

 Orthogonal matrix U
              1           2           3           4
 1  -1.3484E-01  5.2524E-01 -2.0924E-01  8.1373E-01
 2   6.7420E-01 -5.2213E-01 -3.8886E-01  3.4874E-01
 3   2.6968E-01  5.2757E-01 -6.5782E-01 -4.6499E-01
 4   6.7420E-01  4.1615E-01  6.1014E-01  1.5127E-15

 Orthogonal matrix V
              1           2
 1   3.5539E-01 -9.3472E-01
 2   9.3472E-01  3.5539E-01

 Orthogonal matrix Q
              1           2           3
 1  -8.3205E-01 -9.4633E-02 -5.4657E-01
 2   5.5470E-01 -1.4195E-01 -8.1985E-01
 3   0.0000E+00 -9.8534E-01  1.7060E-01

 Nonsingular upper triangular matrix R
              1           2           3
 1  -2.0569E+00 -9.0121E+00 -9.3705E+00
 2              -1.0882E+01 -7.2688E+00
 3                          -6.0405E+00

 Estimate of reciprocal condition number for R
     4.2E-02

 Error estimate for the generalized singular values
     2.6E-15


f08vcfe.r

 F08VCF Example Program Results

 Number of infinite generalized singular values (K)
     1
 Number of finite generalized singular values (L)
     2
 Numerical rank of (A**T B**T)**T (K+L)
     3

 Finite generalized singular values
     1.3151E+00  8.0185E-02

 Orthogonal matrix U
              1           2           3           4
 1  -1.3484E-01  5.2524E-01 -2.0924E-01  8.1373E-01
 2   6.7420E-01 -5.2213E-01 -3.8886E-01  3.4874E-01
 3   2.6968E-01  5.2757E-01 -6.5782E-01 -4.6499E-01
 4   6.7420E-01  4.1615E-01  6.1014E-01  1.5127E-15

 Orthogonal matrix V
              1           2
 1   3.5539E-01 -9.3472E-01
 2   9.3472E-01  3.5539E-01

 Orthogonal matrix Q
              1           2           3
 1  -8.3205E-01 -9.4633E-02 -5.4657E-01
 2   5.5470E-01 -1.4195E-01 -8.1985E-01
 3   0.0000E+00 -9.8534E-01  1.7060E-01

 Nonsingular upper triangular matrix R
              1           2           3
 1  -2.0569E+00 -9.0121E+00 -9.3705E+00
 2              -1.0882E+01 -7.2688E+00
 3                          -6.0405E+00

 Estimate of reciprocal condition number for R
     4.2E-02

 Error estimate for the generalized singular values
     2.6E-15


f08vefe.r

 F08VEF Example Program Results

 Numerical rank of (A**T B**T)**T (K+L)
     3

 Upper triangular matrix S
              1           2           3
 1  -2.0569E+00  1.0771E+01 -7.2814E+00
 2               7.1947E+00 -7.5262E+00
 3                           5.8129E-01

 Upper triangular matrix T
              1           2
 1   8.0623E+00 -3.1305E+00
 2              -4.9193E+00

 Orthogonal matrix U
              1           2           3           4
 1  -1.3484E-01  5.1025E-01 -2.4351E-01  8.1373E-01
 2   6.7420E-01 -5.4670E-01 -3.5349E-01  3.4874E-01
 3   2.6968E-01  4.8292E-01 -6.9127E-01 -4.6499E-01
 4   6.7420E-01  4.5558E-01  5.8129E-01  1.5127E-15

 Orthogonal matrix V
              1           2
 1  -4.4721E-01  8.9443E-01
 2   8.9443E-01  4.4721E-01

 Orthogonal matrix Q
              1           2           3
 1  -8.3205E-01  5.5470E-01  0.0000E+00
 2   5.5470E-01  8.3205E-01  0.0000E+00
 3   0.0000E+00  0.0000E+00 -1.0000E+00


f08vgfe.r

 F08VGF Example Program Results

 Number of infinite generalized singular values (k)
     1
 Number of finite generalized singular values (l)
     2
 Effective Numerical rank of (A; B) (k+l)
     3

 Finite generalized singular values
     1.3151E+00  8.0185E-02

 Orthogonal matrix U
              1           2           3           4
 1  -1.3484E-01  5.2524E-01 -2.0924E-01  8.1373E-01
 2   6.7420E-01 -5.2213E-01 -3.8886E-01  3.4874E-01
 3   2.6968E-01  5.2757E-01 -6.5782E-01 -4.6499E-01
 4   6.7420E-01  4.1615E-01  6.1014E-01  1.5127E-15

 Orthogonal matrix V
              1           2
 1   3.5539E-01 -9.3472E-01
 2   9.3472E-01  3.5539E-01

 Orthogonal matrix Q
              1           2           3
 1  -8.3205E-01 -9.4633E-02 -5.4657E-01
 2   5.5470E-01 -1.4195E-01 -8.1985E-01
 3   0.0000E+00 -9.8534E-01  1.7060E-01

 Nonsingular upper triangular matrix R
              1           2           3
 1  -2.0569E+00 -9.0121E+00 -9.3705E+00
 2              -1.0882E+01 -7.2688E+00
 3                          -6.0405E+00

 Number of cycles of the Kogbetliantz method
     2


f08wafe.r

 F08WAF Example Program Results

 Eigenvalue( 1) =      20.000

 Eigenvector( 1)
    10.00000
     0.05714
     0.62857
     0.62857

 Eigenvalue( 2) = (     30.000,    -40.000)

 Eigenvector( 2)
 (    7.12215,    0.00000)
 (    1.42443,   -0.00000)
 (    0.85466,    1.13954)
 (    0.85466,    1.13954)

 Eigenvalue( 3) = (     30.000,     40.000)

 Eigenvector( 3)
 (    7.12215,    0.00000)
 (    1.42443,    0.00000)
 (    0.85466,   -1.13954)
 (    0.85466,   -1.13954)

 Eigenvalue( 4) =      40.000

 Eigenvector( 4)
    10.00000
     0.11111
    -0.33333
     1.55556


f08wbfe.r

 F08WBF Example Program Results

 Eigenvalue( 1) =     2.00000

   Reciprocal condition number =  9.5E-02

 Eigenvector( 1)
     0.99606
     0.00569
     0.06261
     0.06261

   Reciprocal condition number =  1.3E-01

 Eigenvalue( 2) = (    3.00000,   -4.00000)

   Reciprocal condition number =  1.7E-01

 Eigenvector( 2)
 (    0.94491,   -0.00000)
 (    0.18898,    0.00000)
 (    0.11339,    0.15119)
 (    0.11339,    0.15119)

   Reciprocal condition number =  3.8E-02

 Eigenvalue( 3) = (    3.00000,    4.00000)

   Reciprocal condition number =  1.7E-01

 Eigenvector( 3)
 (    0.94491,    0.00000)
 (    0.18898,   -0.00000)
 (    0.11339,   -0.15119)
 (    0.11339,   -0.15119)

   Reciprocal condition number =  3.8E-02

 Eigenvalue( 4) =     4.00000

   Reciprocal condition number =  5.1E-01

 Eigenvector( 4)
     0.98752
     0.01097
    -0.03292
     0.15361

   Reciprocal condition number =  7.1E-02


f08xafe.r

 F08XAF Example Program Results

 Matrix A
             1          2          3          4
 1      3.9000    12.5000   -34.5000    -0.5000
 2      4.3000    21.5000   -47.5000     7.5000
 3      4.3000    21.5000   -43.5000     3.5000
 4      4.4000    26.0000   -46.0000     6.0000

 Matrix B
             1          2          3          4
 1      1.0000     2.0000    -3.0000     1.0000
 2      1.0000     3.0000    -5.0000     4.0000
 3      1.0000     3.0000    -4.0000     3.0000
 4      1.0000     3.0000    -4.0000     4.0000

 Number of eigenvalues for which SELCTG is true =    2
 (dimension of deflating subspaces)

 Selected generalized eigenvalues
    1     (  2.000,  0.000)
    2     (  4.000,  0.000)


f08xbfe.r

 F08XBF Example Program Results

 Matrix A
             1          2          3          4
 1      3.9000    12.5000   -34.5000    -0.5000
 2      4.3000    21.5000   -47.5000     7.5000
 3      4.3000    21.5000   -43.5000     3.5000
 4      4.4000    26.0000   -46.0000     6.0000

 Matrix B
             1          2          3          4
 1      1.0000     2.0000    -3.0000     1.0000
 2      1.0000     3.0000    -5.0000     4.0000
 3      1.0000     3.0000    -4.0000     3.0000
 4      1.0000     3.0000    -4.0000     4.0000

 Number of eigenvalues for which SELCTG is true =    2
 (dimension of deflating subspaces)

 Selected generalized eigenvalues
    1     (  2.000,  0.000)
    2     (  4.000,  0.000)

 Reciprocals of left and right projection norms onto
 the deflating subspaces for the selected eigenvalues
 RCONDE(1) =  1.9E-01, RCONDE(2) =  1.8E-02

 Reciprocal condition numbers for the left and right
 deflating subspaces
 RCONDV(1) =  5.4E-02, RCONDV(2) =  9.0E-02

 Approximate asymptotic error bound for selected eigenvalues    =  5.7E-14
 Approximate asymptotic error bound for the deflating subspaces =  1.2E-13


f08xcfe.r

 F08XCF Example Program Results

 Matrix A
             1          2          3          4
 1      3.9000    12.5000   -34.5000    -0.5000
 2      4.3000    21.5000   -47.5000     7.5000
 3      4.3000    21.5000   -43.5000     3.5000
 4      4.4000    26.0000   -46.0000     6.0000

 Matrix B
             1          2          3          4
 1      1.0000     2.0000    -3.0000     1.0000
 2      1.0000     3.0000    -5.0000     4.0000
 3      1.0000     3.0000    -4.0000     3.0000
 4      1.0000     3.0000    -4.0000     4.0000

 Number of eigenvalues for which SELCTG is true =    2
 (dimension of deflating subspaces)

 Selected generalized eigenvalues
    1     (  2.000,  0.000)
    2     (  4.000,  0.000)


f08xnfe.r

 F08XNF Example Program Results

 Generalized Eigenvalues
  1   (  3.00, -9.00)
  2   (  4.00, -5.00)
  3   (  2.00, -5.00)
  4   (  3.00, -1.00)


f08xpfe.r

 F08XPF Example Program Results

 Number of eigenvalues for which SELCTG is true =    2
 (dimension of deflating subspaces)

 Selected generalized eigenvalues
  1 (  2.00, -5.00)
  2 (  3.00, -1.00)


f08yefe.r

 F08YEF Example Program Results

 Number of infinite generalized singular values (K)
     1
 Number of finite generalized singular values (L)
     2
  Effective Numerical rank of (A**T B**T)**T (K+L)
     3

 Finite generalized singular values
     1.3151E+00  8.0185E-02

 Orthogonal matrix U
              1           2           3           4
 1  -1.3484E-01  5.2524E-01 -2.0924E-01  8.1373E-01
 2   6.7420E-01 -5.2213E-01 -3.8886E-01  3.4874E-01
 3   2.6968E-01  5.2757E-01 -6.5782E-01 -4.6499E-01
 4   6.7420E-01  4.1615E-01  6.1014E-01  1.5127E-15

 Orthogonal matrix V
              1           2
 1   3.5539E-01 -9.3472E-01
 2   9.3472E-01  3.5539E-01

 Orthogonal matrix Q
              1           2           3
 1  -8.3205E-01 -9.4633E-02 -5.4657E-01
 2   5.5470E-01 -1.4195E-01 -8.1985E-01
 3   0.0000E+00 -9.8534E-01  1.7060E-01

 Nonsingular upper triangular matrix R
              1           2           3
 1  -2.0569E+00 -9.0121E+00 -9.3705E+00
 2              -1.0882E+01 -7.2688E+00
 3                          -6.0405E+00

 Number of cycles of the Kogbetliantz method
     2


f08yffe.r

 F08YFF Example Program Results

 Reordered Schur matrix A
             1          2          3          4
 1      4.1926     1.2591     2.5578     0.4520
 2     -0.8712     0.8627     2.7912     1.1383
 3      0.0000     0.0000     4.2426     2.1213
 4      0.0000     0.0000     0.0000     6.0000

 Reordered Schur matrix B
             1          2          3          4
 1      1.7439     0.0000     0.7533     0.0661
 2      0.0000     0.5406     1.8972     1.7308
 3      0.0000     0.0000     2.1213     2.8284
 4      0.0000     0.0000     0.0000     2.0000


f08ygfe.r

 F08YGF Example Program Results

 Number of selected eigenvalues  =    2

 Selected Generalized Eigenvalues

  1 ( 2.0000E+00, 0.0000E+00)
  2 ( 3.0000E+00, 0.0000E+00)

 Norm estimate of projection onto left  eigenspace for selected cluster
   2.69E+00

 Norm estimate of projection onto right eigenspace for selected cluster
   1.50E+00

 F-norm based upper bound on Difu
   2.52E-01

 F-norm based upper bound on Difl
   2.45E-01


f08yhfe.r

 F08YHF Example Program Results

 Solution matrix R
             1          2          3          4
 1      1.0000     1.0000     1.0000     1.0000
 2     -1.0000     2.0000    -1.0000    -1.0000
 3     -1.0000     1.0000     3.0000     1.0000
 4     -1.0000     1.0000    -1.0000     4.0000

 Solution matrix L
             1          2          3          4
 1      4.0000    -1.0000     1.0000    -1.0000
 2      1.0000     3.0000    -1.0000     1.0000
 3     -1.0000     1.0000     2.0000    -1.0000
 4      1.0000    -1.0000     1.0000     1.0000

 SCALE =   1.00E+00


f08ylfe.r

 F08YLF Example Program Results

 S
       1.6E+00    1.7E+00    1.7E+00    1.4E+00

 DIF
       5.4E-01    1.5E-01    1.5E-01    1.2E-01

 Approximate error estimates for eigenvalues of (A,B)
       8.7E-16    7.8E-16    7.8E-16    9.9E-16

 Approximate error estimates for right eigenvectors of (A,B)
       2.5E-15    9.0E-15    9.0E-15    1.1E-14


f08yufe.r

 F08YUF Example Program Results

 Reordered Schur matrix A
                    1                 2                 3                 4
 1  ( 4.6904, 2.3452) (-2.1563, 0.1192) ( 1.9599,-0.5174) ( 1.8091,-1.2060)
 2  ( 0.0000, 0.0000) ( 2.0084,-1.0042) ( 0.9161,-0.2762) ( 1.8574,-0.5326)
 3  ( 0.0000, 0.0000) ( 0.0000, 0.0000) ( 1.6985, 1.6985) ( 0.1270, 0.7231)
 4  ( 0.0000, 0.0000) ( 0.0000, 0.0000) ( 0.0000, 0.0000) ( 6.0000,-2.0000)

 Reordered Schur matrix B
                    1                 2                 3                 4
 1  ( 2.3452, 0.0000) (-0.6181, 1.8237) ( 0.9290, 0.5409) ( 2.7136,-1.5076)
 2  ( 0.0000, 0.0000) ( 1.0042, 0.0000) ( 1.2251,-1.1857) ( 1.8541,-0.2929)
 3  ( 0.0000, 0.0000) ( 0.0000, 0.0000) ( 0.8492, 0.0000) ( 0.1435, 0.9053)
 4  ( 0.0000, 0.0000) ( 0.0000, 0.0000) ( 0.0000, 0.0000) ( 2.0000, 0.0000)

 Basis of left deflating invariant subspace
                    1                 2
 1  ( 0.9045, 0.3015) (-0.0033,-0.2397)
 2  ( 0.3015, 0.0000) ( 0.2497, 0.7157)
 3  ( 0.0000, 0.0000) ( 0.0549, 0.6042)
 4  ( 0.0000, 0.0000) ( 0.0000, 0.0000)

 Basis of right deflating invariant subspace
                    1                 2
 1  ( 0.7071, 0.0000) (-0.5607, 0.0000)
 2  ( 0.7071, 0.0000) ( 0.5607, 0.0000)
 3  ( 0.0000, 0.0000) ( 0.0552, 0.6067)
 4  ( 0.0000, 0.0000) ( 0.0000, 0.0000)

 Norm estimate of projection onto left  eigenspace for selected cluster
   8.90E+00

 Norm estimate of projection onto right eigenspace for selected cluster
   7.02E+00

 F-norm based upper bound on Difu
   2.18E-01

 F-norm based upper bound on Difl
   2.62E-01


f08yyfe.r

 F08YYF Example Program Results

 S
       1.0E+00    8.2E-01    7.2E-01    8.2E-01

 DIF
       3.2E-01    3.6E-01    5.5E-01    2.8E-01

 Approximate error estimates for eigenvalues of (A,B)
       1.5E-15    1.9E-15    2.1E-15    1.9E-15

 Approximate error estimates for right eigenvectors of (A,B)
       4.8E-15    4.3E-15    2.8E-15    5.5E-15


f08zafe.r

 F08ZAF Example Program Results

 Constrained least squares solution
      0.4890     0.9975     0.4890     0.9975

 Square root of the residual sum of squares
      2.51E-02


f08zbfe.r

 F08ZBF Example Program Results

 Weighted least squares solution
      1.9889    -1.0058    -2.9911

 Residual vector
     -6.37E-04  -2.45E-03  -4.72E-03   7.70E-03

 Square root of the residual sum of squares
      9.38E-03


f08zefe.r

 F08ZEF Example Program Results

 Generalized least squares solution
      1.9889    -1.0058    -2.9911

 Residual vector
     -6.37E-04  -2.45E-03  -4.72E-03   7.70E-03

 Square root of the residual sum of squares
      9.38E-03


f08zffe.r

 F08ZFF Example Program Results

 Constrained least squares solution
      0.4890     0.9975     0.4890     0.9975

 Square root of the residual sum of squares
      2.51E-02


f08znfe.r

 F08ZNF Example Program Results

 Constrained least squares solution
 ( 1.0874,-1.9621) (-0.7409, 3.7297) ( 1.0874,-1.9621) (-0.7409, 3.7297)

 Square root of the residual sum of squares
   1.59E-01


f08zpfe.r

 F08ZPF Example Program Results

 Weighted least squares solution
 (  -0.9846,   1.9950) (   3.9929,  -4.9748) (  -3.0026,   0.9994)

 Residual vector
 ( 1.26E-04,-4.66E-04) ( 1.11E-03,-8.61E-04) ( 3.84E-03,-1.82E-03)
 ( 2.03E-03, 3.02E-03)

 Square root of the residual sum of squares
   5.79E-03


f08zsfe.r

 F08ZSF Example Program Results

 Generalized least squares solution
 (  -0.9846,   1.9950) (   3.9929,  -4.9748) (  -3.0026,   0.9994)

 Residual vector
 ( 1.26E-04,-4.66E-04) ( 1.11E-03,-8.61E-04) ( 3.84E-03,-1.82E-03)
 ( 2.03E-03, 3.02E-03)

 Square root of the residual sum of squares
   5.79E-03


f08ztfe.r

 F08ZTF Example Program Results

 Constrained least squares solution
 ( 1.0874,-1.9621) (-0.7409, 3.7297) ( 1.0874,-1.9621) (-0.7409, 3.7297)

 Square root of the residual sum of squares
   1.59E-01


f11bdfe.r

 F11BDF Example Program Results

 Monitoring at iteration no.   1
 residual norm:     1.4059E+02

    Solution vector   Residual vector
      -4.5858E+00       1.5256E+01
       1.0154E+00       2.6624E+01
      -2.2234E+00      -8.7498E+00
       6.0097E+00       1.8602E+01
       1.3827E+00       8.2821E+00
      -7.9070E+00       2.0416E+01
       4.4270E-01       9.6094E+00
       5.9248E+00       3.3055E+01

 Monitoring at iteration no.   2
 residual norm:     3.2742E+01

    Solution vector   Residual vector
       4.1642E+00      -2.9585E+00
       4.9370E+00      -5.5523E+00
       4.8101E+00       8.2070E-01
       5.4324E+00      -1.6828E+01
       5.8531E+00       5.5975E-01
       1.1925E+01      -1.9150E+00
       8.4826E+00       1.0081E+00
       6.0625E+00      -3.1004E+00

 Final Results
 Number of iterations for convergence:       3
 Residual norm:                               1.0373E-08
 Right-hand side of termination criterion:    5.5900E-06
 1-norm of matrix A:                          1.1000E+01

    Solution vector   Residual vector
       1.0000E+00      -1.3554E-09
       2.0000E+00      -2.6109E-09
       3.0000E+00       2.2471E-10
       4.0000E+00      -3.2203E-09
       5.0000E+00       6.3045E-10
       6.0000E+00      -5.2431E-10
       7.0000E+00       9.5771E-10
       8.0000E+00      -8.4890E-10


f11brfe.r

 F11BRF Example Program Results

 Monitoring at iteration no.   2
 residual norm:     8.2345E+01

    Solution vector
 (      6.9055E-01,      1.4236E+00)
 (      7.3931E-02,     -1.1880E+00)
 (      1.4778E+00,      4.7846E-01)
 (      5.6572E+00,     -3.0786E+00)
 (      1.4243E+00,     -1.1246E+00)
 (      1.0374E-01,      1.9740E+00)
 (      4.4985E-01,     -1.2715E+00)
 (      2.5704E+00,      1.7578E+00)

    Residual vector
 (      1.7772E+00,      4.6797E+00)
 (      1.0774E+00,      6.4600E+00)
 (     -3.2812E+00,     -1.1314E+01)
 (     -3.8698E+00,     -1.6438E+00)
 (      8.9912E+00,      1.1100E+01)
 (      9.7428E+00,     -4.6218E-01)
 (      3.1668E+00,      2.8721E+00)
 (     -1.0323E+01,      1.5837E+00)

 Final Results
 Number of iterations for convergence:       4
 Residual norm:                               7.9221E-12
 Right-hand side of termination criterion:    8.9100E-06
 1-norm of matrix A:                          2.7000E+01

    Solution vector
 (      1.0000E+00,      1.0000E+00)
 (      2.0000E+00,     -1.0000E+00)
 (      3.0000E+00,      1.0000E+00)
 (      4.0000E+00,     -1.0000E+00)
 (      3.0000E+00,     -1.0000E+00)
 (      2.0000E+00,      1.0000E+00)
 (      1.0000E+00,     -1.0000E+00)
 (      5.4088E-13,      3.0000E+00)

    Residual vector
 (      6.2172E-14,      5.1514E-13)
 (     -4.8139E-13,      7.9581E-13)
 (     -2.6645E-13,     -8.4910E-13)
 (     -4.6896E-13,     -6.0396E-14)
 (      7.1410E-13,      8.2068E-13)
 (      7.3541E-13,     -5.4179E-14)
 (      2.9843E-13,     -8.2645E-13)
 (     -8.7752E-13,      9.5923E-14)


f11dafe.r

 F11DAF Example Program Results

  Original Matrix
 N     =   4
 NNZ   =  11
       1      0.1000E+01       1       2
       2      0.1000E+01       1       3
       3     -0.1000E+01       2       1
       4      0.2000E+01       2       3
       5      0.2000E+01       2       4
       6      0.3000E+01       3       1
       7     -0.2000E+01       3       4
       8      0.1000E+01       4       1
       9     -0.2000E+01       4       2
      10      0.1000E+01       4       3
      11      0.1000E+01       4       4

  Factorization
 N     =   4
 NNZ   =  11
 NPIVM =   0
      12      0.1000E+01       1       1
      13      0.1000E+01       1       3
      14      0.3333E+00       2       2
      15     -0.6667E+00       2       4
      16     -0.3333E+00       3       2
      17      0.5000E+00       3       3
      18      0.6667E+00       3       4
      19     -0.2000E+01       4       1
      20      0.3333E+00       4       2
      21      0.1500E+01       4       3
      22     -0.3000E+01       4       4

         I       IPIVP(I)  IPIVQ(I)
         1         1         2
         2         3         1
         3         2         3
         4         4         4


f11dbfe.r

 F11DBF Example Program Results

  Solution of linear system
      0.1000E+01
      0.2000E+01
      0.3000E+01
      0.4000E+01


f11dcfe.r

 F11DCF Example Program Results

  Converged in   4 iterations
  Final residual norm < tolerance ( 1.000E-12)

        Solution
        1.000E+00
        2.000E+00
        3.000E+00
        4.000E+00
        5.000E+00
        6.000E+00
        7.000E+00
        8.000E+00


f11ddfe.r

 F11DDF Example Program Results

 Converged in        12 iterations
 Matrix norm =       1.200E+01
 Final residual norm =       3.841E-09

            X
       1.0000E+00
       2.0000E+00
       3.0000E+00
       4.0000E+00
       5.0000E+00


f11defe.r

 F11DEF Example Program Results

 Converged in        13 iterations
 Final residual norm =       5.087E-09

            X
       1.0000E+00
       2.0000E+00
       3.0000E+00
       4.0000E+00
       5.0000E+00


f11dgfe.r

 F11DGF Example Program Results

 Converged in         4 iterations
 Final residual norm =       1.106D-05

  Solution vector  X
  ------------------
  5.2603
  5.9165
  4.1131
  5.9165
  6.6636
  4.6119
  4.1131
  4.6119
  3.2919


f11dkfe.r

 F11DKF Example Program Results

 Final Results
 Number of iterations for convergence:       2
 Residual norm:                               1.1177E-04
 Right-hand side of termination criterion:    5.4082E-04
 1-norm of matrix A:                          1.5000E+01

    Solution vector   Residual vector
       1.7035E+00       3.2377E-07
       1.0805E+00      -1.7625E-05
       1.8305E+00       2.7964E-05
       6.0251E+00      -2.5914E-05
       3.2942E+00       7.8156E-06
       1.9068E+00       9.2064E-06
       4.1365E+00      -3.0848E-06
       5.2111E+00       1.9834E-05


f11dpfe.r

 F11DPF Example Program Results

 Solution of linear system
 (      0.1000E+01,      0.4000E+01)
 (      0.2000E+01,      0.3000E+01)
 (      0.3000E+01,     -0.2000E+01)
 (      0.4000E+01,     -0.1000E+01)


f11dqfe.r

 F11DQF Example Program Results

 Converged in         4 iterations
 Final residual norm =       2.857E-11

                    X
 (      1.0000E+00,      1.0000E+00)
 (      2.0000E+00,     -1.0000E+00)
 (      3.0000E+00,      1.0000E+00)
 (      4.0000E+00,     -1.0000E+00)
 (      3.0000E+00,     -1.0000E+00)
 (      2.0000E+00,      1.0000E+00)
 (      1.0000E+00,     -1.0000E+00)
 (      3.0103E-12,      3.0000E+00)


f11drfe.r

 F11DRF Example Program Results

 Converged in         5 iterations
 Matrix norm =       1.500E+01
 Final residual norm =       1.776E-14

                    X
 (      1.0000E+00,      2.0000E+00)
 (      2.0000E+00,      3.0000E+00)
 (      3.0000E+00,      4.0000E+00)
 (      4.0000E+00,      5.0000E+00)
 (      5.0000E+00,      6.0000E+00)


f11dsfe.r

 F11DSF Example Program Results

 Converged in         5 iterations
 Final residual norm =       1.020E-10

                    X
 (      1.0000E+00,      2.0000E+00)
 (      2.0000E+00,      3.0000E+00)
 (      3.0000E+00,      4.0000E+00)
 (      4.0000E+00,      5.0000E+00)
 (      5.0000E+00,      6.0000E+00)


f11dufe.r

 F11DUF Example Program Results

  Converged in         8 iterations
  Final residual norm =       6.492D-04

 Solution vector   X
 -------------------
 (  2.2040,  1.6972)
 (  2.3511,  1.9275)
 (  1.5931,  1.4368)
 (  2.8641,  1.9762)
 (  3.0687,  2.2645)
 (  2.0467,  1.6948)
 (  2.2065,  1.3244)
 (  2.3724,  1.5170)
 (  1.6254,  1.1783)


f11dxfe.r

 F11DXF Example Program Results

 Monitoring at iteration number   1
   order of residual norm:   2

 Monitoring at iteration number   2
   order of residual norm:   2

 Monitoring at iteration number   3
   order of residual norm:   2

 Final Results

    Solution vector
 (   1.000,   1.000)
 (   2.000,  -1.000)
 (   3.000,   1.000)
 (   4.000,  -1.000)
 (   3.000,  -1.000)
 (   2.000,   1.000)
 (   1.000,  -1.000)
 (  -0.000,   3.000)


f11gdfe.r

 F11GDF Example Program Results

 Solve a system of linear equations using the conjugate gradient method

 Monitoring at iteration no.   2
 residual norm:     1.9938E+00
  Solution vector  Residual vector
       9.6320E-01      -2.2960E-01
       1.9934E+00       2.2254E-01
       3.0583E+00       9.5827E-02
       4.1453E+00      -2.5155E-01
       4.8289E+00      -1.7160E-01
       5.6630E+00       6.7533E-01
       7.1062E+00      -3.4737E-01

 Monitoring at iteration no.   4
 residual norm:     6.6574E-03
  Solution vector  Residual vector
       9.9940E-01      -1.0551E-03
       2.0011E+00      -2.4675E-03
       3.0008E+00      -1.7116E-05
       3.9996E+00       4.4929E-05
       4.9991E+00       2.1359E-03
       5.9993E+00      -8.7482E-04
       7.0007E+00       6.2045E-05

 Final Results
 Number of iterations for convergence:       5
 Residual norm:                               2.0428E-14
 Right-hand side of termination criterion:    3.9200E-04
 1-norm of matrix A:                          1.0000E+01
 Largest singular value of A_bar:             1.3596E+00
  Solution vector  Residual vector
       1.0000E+00       0.0000E+00
       2.0000E+00       0.0000E+00
       3.0000E+00      -2.6645E-15
       4.0000E+00      -3.5527E-15
       5.0000E+00      -5.3291E-15
       6.0000E+00       1.7764E-15
       7.0000E+00       7.1054E-15


f11jbfe.r

 F11JBF Example Program Results
  Solution of linear system
       0.7000E+00
       0.1600E+00
       0.5200E+00
       0.7700E+00
       0.2800E+00
       0.2100E+00
       0.9300E+00
       0.2000E+00
       0.9000E+00
  Solution of linear system with Reverse Cuthill-McKee
       0.7000E+00
       0.1600E+00
       0.5200E+00
       0.7700E+00
       0.2800E+00
       0.2100E+00
       0.9300E+00
       0.2000E+00
       0.9000E+00


f11jcfe.r

 F11JCF Example Program Results
 Converged in         1 iterations
 Final residual norm =       7.105E-15
       1.0000E+00
       2.0000E+00
       3.0000E+00
       4.0000E+00
       5.0000E+00
       6.0000E+00
       7.0000E+00


f11jdfe.r

 F11JDF Example Program Results
 Converged in         6 iterations
 Final residual norm =       7.105E-15
       1.0000E+00
       2.0000E+00
       3.0000E+00
       4.0000E+00
       5.0000E+00
       6.0000E+00
       7.0000E+00


f11jefe.r

 F11JEF Example Program Results
 Converged in         6 iterations
 Final residual norm =       5.026E-06
       1.0000E+00
       2.0000E+00
       3.0000E+00
       4.0000E+00
       5.0000E+00
       6.0000E+00
       7.0000E+00


f11jpfe.r

 F11JPF Example Program Results
 Solution of linear system
 (      0.1000E+01,      0.9000E+01)
 (      0.2000E+01,     -0.8000E+01)
 (      0.3000E+01,      0.7000E+01)
 (      0.4000E+01,     -0.6000E+01)
 (      0.5000E+01,      0.5000E+01)
 (      0.6000E+01,     -0.4000E+01)
 (      0.7000E+01,      0.3000E+01)
 (      0.8000E+01,     -0.2000E+01)
 (      0.9000E+01,      0.1000E+01)


f11jqfe.r

 F11JQF Example Program Results
 Converged in         5 iterations
 Final residual norm =       3.197E-14
 (      0.1000E+01,      0.9000E+01)
 (      0.2000E+01,     -0.8000E+01)
 (      0.3000E+01,      0.7000E+01)
 (      0.4000E+01,     -0.6000E+01)
 (      0.5000E+01,      0.5000E+01)
 (      0.6000E+01,     -0.4000E+01)
 (      0.7000E+01,      0.3000E+01)
 (      0.8000E+01,     -0.2000E+01)
 (      0.9000E+01,      0.1000E+01)


f11jrfe.r

 F11JRF Example Program Results
 (      0.1098E+01,      0.5914E+01)
 (      0.2230E+00,     -0.1408E+02)
 (      0.2232E+01,      0.7087E+01)
 (      0.4816E+01,     -0.6181E+01)
 (      0.6763E+01,      0.1569E+01)
 (      0.3353E+01,     -0.4785E+01)
 (      0.6699E+00,     -0.1465E+01)
 (      0.8832E+01,     -0.3633E+01)
 (      0.4768E+01,      0.1213E+00)


f11jsfe.r

 F11JSF Example Program Results
 Converged in         7 iterations
 Final residual norm =       1.477E-05
 (      0.1000E+01,      0.9000E+01)
 (      0.2000E+01,     -0.8000E+01)
 (      0.3000E+01,      0.7000E+01)
 (      0.4000E+01,     -0.6000E+01)
 (      0.5000E+01,      0.5000E+01)
 (      0.6000E+01,     -0.4000E+01)
 (      0.7000E+01,      0.3000E+01)
 (      0.8000E+01,     -0.2000E+01)
 (      0.9000E+01,      0.1000E+01)


f11mdfe.r

 F11MDF Example Program Results

 COLAMD Permutation
     1     0     4     3     2

 User Permutation
     4     3     2     1     0

 Natural Permutation
     0     1     2     3     4


f11mefe.r

 F11MEF Example Program Results

 Number of nonzeros in factors (excluding unit diagonal)
       14
 Factor elements in LVAL
    -2.00  -0.50   4.00   0.50   2.00   0.50  -1.00   0.50   1.00  -1.00
 Factor elements in UVAL
     1.00   3.00   1.00   1.00


f11mffe.r

 F11MFF Example Program Results

 Solutions
             1          2
 1      0.7000     1.4000
 2      0.1600     0.3200
 3      0.5200     1.0400
 4      0.7700     1.5400
 5      0.2800     0.5600


f11mgfe.r

 F11MGF Example Program Results

 Norm  ,Condition number
  6.000, 20.250


f11mhfe.r

 F11MHF Example Program Results

 Solutions
             1          2
 1      0.7000     1.4000
 2      0.1600     0.3200
 3      0.5200     1.0400
 4      0.7700     1.5400
 5      0.2800     0.5600
 Estimated Forward Error
   5.0E-15
   5.0E-15
 Backward Error
   3.6E-17
   3.6E-17


f11mkfe.r

 F11MKF Example Program Results

 Matrix-matrix product
             1          2
 1      1.5600     3.1200
 2     -0.2500    -0.5000
 3      3.6000     7.2000
 4      1.3300     2.6600
 5      0.5200     1.0400

 Transposed matrix-matrix product
             1          2
 1      3.4800     6.9600
 2      0.1400     0.2800
 3      0.6800     1.3600
 4      0.6100     1.2200
 5      2.9000     5.8000


f11mlfe.r

 F11MLF Example Program Results

 One-norm
  6.000

 Max
  4.000

 Infinity-norm
  6.000


f11mmfe.r

 F11MMF Example Program Results

 Reciprocal pivot growth
  1.000


f11xafe.r

 F11XAF Example Program Results

  Matrix-vector product
      0.1560E+01
     -0.2500E+00
      0.3600E+01
      0.1330E+01
      0.5200E+00

  Transposed matrix-vector product
      0.3480E+01
      0.1400E+00
      0.6800E+00
      0.6100E+00
      0.2900E+01


f11xefe.r

 F11XEF Example Program Results
  Matrix-vector product
       0.4100E+01
      -0.2940E+01
       0.1410E+01
       0.2530E+01
       0.4350E+01
       0.1290E+01
       0.5010E+01
       0.5200E+00
       0.4570E+01


f11xnfe.r

 F11XNF Example Program Results

  Matrix-vector product
 (     -0.7900E+00,      0.1450E+01)
 (     -0.2500E+00,     -0.5700E+00)
 (      0.3820E+01,      0.2260E+01)
 (     -0.3280E+01,     -0.3730E+01)
 (      0.1160E+01,     -0.7800E+00)

  Conjugate transposed matrix-vector product
 (      0.5080E+01,      0.1680E+01)
 (     -0.7000E+00,      0.4290E+01)
 (      0.1130E+01,     -0.9500E+00)
 (      0.7000E+00,      0.1520E+01)
 (      0.5170E+01,      0.1830E+01)


f11xsfe.r

 F11XSF Example Program Results
  Matrix-vector product
 (      0.8000E+01,      0.5400E+02)
 (     -0.1000E+02,     -0.9200E+02)
 (      0.2500E+02,      0.2700E+02)
 (      0.2600E+02,     -0.2800E+02)
 (      0.5400E+02,      0.1200E+02)
 (      0.2600E+02,     -0.2200E+02)
 (      0.4700E+02,      0.6500E+02)
 (      0.7100E+02,     -0.5700E+02)
 (      0.6000E+02,      0.7000E+02)


f11yefe.r

 F11YEF Example Program Results
Permutation (perm):
      1      5      2      6      4      3
     26      7     30     11     12     10
     21     16     27     25      8     29
     17     15     13      9     22     20
     28     24     42     43     18     14
     37     38     23     19     47     48
     41     44     32     33     36     39
     52     53     46     49     45     31
     34     40     51     54     50     58
     35     57     55     59     56     60

Statistics:
  Before:  Bandwidth =     34
  Before:  Profile   =    490
  After :  Bandwidth =     10
  After :  Profile   =    458


f11zafe.r

 F11ZAF Example Program Results

 Original elements
 NNZ =   15
                        A    IROW    ICOL
        1      4.0000E+00       3       1
        2     -2.0000E+00       5       2
        3      1.0000E+00       4       4
        4     -2.0000E+00       4       2
        5     -3.0000E+00       5       5
        6      1.0000E+00       1       2
        7      0.0000E+00       1       5
        8      1.0000E+00       3       5
        9     -1.0000E+00       2       4
       10      6.0000E+00       5       5
       11      2.0000E+00       1       1
       12      2.0000E+00       4       2
       13      1.0000E+00       2       3
       14      1.0000E+00       3       3
       15      2.0000E+00       4       5
 Reordered elements, along rows first
 NNZ =   11
        1      2.0000E+00       1       1
        2      1.0000E+00       1       2
        3      1.0000E+00       2       3
        4     -1.0000E+00       2       4
        5      4.0000E+00       3       1
        6      1.0000E+00       3       3
        7      1.0000E+00       3       5
        8      1.0000E+00       4       4
        9      2.0000E+00       4       5
       10     -2.0000E+00       5       2
       11      3.0000E+00       5       5
 Reordered elements, along columns first
 NNZ =   11
        1      2.0000E+00       1       1
        2      4.0000E+00       3       1
        3      1.0000E+00       1       2
        4     -2.0000E+00       5       2
        5      1.0000E+00       2       3
        6      1.0000E+00       3       3
        7     -1.0000E+00       2       4
        8      1.0000E+00       4       4
        9      1.0000E+00       3       5
       10      2.0000E+00       4       5
       11      3.0000E+00       5       5
             ISTR
        1       1
        2       3
        3       5
        4       7
        5       9
        6      12
 One norm       6.0000E+00


f11zbfe.r

 F11ZBF Example Program Results
 Original elements
 NNZ =                9
        1      0.1000E+01       3       2
        2      0.0000E+00       2       1
        3      0.1000E+01       3       2
        4      0.3000E+01       4       4
        5      0.4000E+01       1       1
        6      0.6000E+01       2       2
        7      0.2000E+01       3       3
        8      0.1000E+01       3       2
        9      0.1000E+01       3       2
 Reordered elements
 NNZ =    5
        1      0.4000E+01       1       1
        2      0.6000E+01       2       2
        3      0.4000E+01       3       2
        4      0.2000E+01       3       3
        5      0.3000E+01       4       4


f12aafe.r

 F12AAF Example Program Results

 The   10 Ritz values of smallest magnitude are:

        1     (     251.8027 ,     152.7109 )
        2     (     251.8027 ,    -152.7109 )
        3     (     280.4166 ,     152.7109 )
        4     (     280.4166 ,    -152.7109 )
        5     (     325.5237 ,     152.7109 )
        6     (     325.5237 ,    -152.7109 )
        7     (     383.4696 ,     152.7109 )
        8     (     383.4696 ,    -152.7109 )
        9     (     449.5598 ,     152.7109 )
       10     (     449.5598 ,    -152.7109 )


f12abfe.r

 F12ABF Example Program Results

 The    4 Ritz values of closest to unity are:

        1     (       1.0192 ,       0.0000 )
        2     (       0.9656 ,       0.0000 )
        3     (       1.0738 ,       0.0000 )
        4     (       0.9129 ,       0.0000 )


f12acfe.r

 F12ACF Example Program Results

 The    4 generalized Ritz values of largest magnitude are:

        1     (   20383.0384 ,       0.0000 )
        2     (   20338.7563 ,       0.0000 )
        3     (   20265.2844 ,       0.0000 )
        4     (   20163.1142 ,       0.0000 )


f12adfe.r

 F12ADF Example Program Results

 The    4 generalized Ritz values closest to unity are:

        1     (      34.8634 ,       0.0000 )
        2     (      64.4479 ,       0.0000 )
        3     (     113.7872 ,       0.0000 )
        4     (     182.9293 ,       0.0000 )


f12aefe.r

 F12AEF Example Program Results

 Iteration   1, No. converged =   0, norm of estimates =  0.1052E+00
 Iteration   2, No. converged =   0, norm of estimates =  0.1188E-02
 Iteration   3, No. converged =   0, norm of estimates =  0.1389E-05
 Iteration   4, No. converged =   0, norm of estimates =  0.3939E-08
 Iteration   5, No. converged =   0, norm of estimates =  0.1158E-10
 Iteration   6, No. converged =   0, norm of estimates =  0.5222E-13

 The    4 generalized Ritz values closest to (  0.4000,   0.6000) are:

        1     ( 0.5000,-0.5958)
        2     ( 0.5000, 0.5958)
        3     ( 0.5000,-0.6331)
        4     ( 0.5000, 0.6331)


f12agfe.r

 F12AGF Example Program Results

  Ritz values closest to sigma
          1       2
 1   0.3610  0.7223
 2   0.3610 -0.7223
 3   0.4598 -0.7199
 4   0.4598  0.7199


f12anfe.r

 F12ANF Example Program Results

 The    4 Ritz values of largest magnitude are:

        1     (     716.1973 ,   -1029.5838 )
        2     (     716.1973 ,    1029.5838 )
        3     (     687.5834 ,   -1029.5838 )
        4     (     687.5834 ,    1029.5838 )


f12apfe.r

 F12APF Example Program Results

 The    4 Ritz values of smallest magnitude are:

        1     (      34.8720 ,       0.0000 )
        2     (      64.4326 ,      -0.0000 )
        3     (     113.6685 ,       0.0000 )
        4     (     182.5320 ,       0.0000 )


f12aqfe.r

 F12AQF Example Program Results

 The    4 Ritz values of largest magnitude are:

        1     (   20383.0384 ,       0.0000 )
        2     (   20338.7563 ,      -0.0000 )
        3     (   20265.2844 ,       0.0000 )
        4     (   20163.1142 ,      -0.0000 )


f12arfe.r

 F12ARF Example Program Results

 The    4 generalized Ritz values closest to (500.000,  0.000) are:

        1     (   509.9390 ,     0.0000 )
        2     (   380.9092 ,     0.0000 )
        3     (   659.1558 ,     0.0000 )
        4     (   271.9412 ,    -0.0000 )


f12asfe.r

 F12ASF Example Program Results

 Iteration   1, No. converged =   0, norm of estimates =  0.5947E-06
 Iteration   2, No. converged =   1, norm of estimates =  0.1478E-08
 Iteration   3, No. converged =   2, norm of estimates =  0.3293E-10
 Iteration   4, No. converged =   2, norm of estimates =  0.5941E-13
 Iteration   5, No. converged =   2, norm of estimates =  0.8408E-15
 Iteration   6, No. converged =   3, norm of estimates =  0.8134E-17

 The    4 generalized Ritz values closest to (5000.000,   0.000) are:

        1     (  4829.8497 ,     0.0000 )
        2     (  5279.5223 ,    -0.0000 )
        3     (  4400.6310 ,     0.0000 )
        4     (  5749.7160 ,    -0.0000 )


f12aufe.r

 F12AUF Example Program Results

  Ritz values closest to sigma
          1       2
 1   0.3610  0.7223
 2   0.4598  0.7199
 3   0.2868  0.7241
 4   0.2410  0.7257


f12fafe.r

 F12FAF Example Program Results

 The    4 Ritz values of smallest magnitude are:

        1          19.6054
        2          48.2193
        3          48.2193
        4          76.8333


f12fbfe.r

 F12FBF Example Program Results

 F12FBF Example 1

 The    4 Ritz values of closest to   0.0000 are:

        1           9.8688
        2          39.4657
        3          88.7620
        4         157.7101

 F12FBF Example 2

  Singular values and direct residuals
               1            2
 1    4.1012E-02   1.1877E-17
 2    6.0488E-02   2.6231E-17
 3    1.1784E-01   1.6455E-17
 4    5.5723E-01   3.2163E-16


f12fcfe.r

 F12FCF Example Program Results

 The    4 generalized Ritz values of largest magnitude are:

        1      121003.5
        2      121616.6
        3      122057.5
        4      122323.2


f12fdfe.r

 F12FDF Example Program Results

 The    4 Ritz values of closest to   0.0000 are:

        1           9.8704
        2          39.4912
        3          88.8909
        4         158.1175


f12fefe.r

 F12FEF Example Program Results

 Iteration   1, No. converged =   0, norm of estimates =  0.20534331E-05
 Iteration   2, No. converged =   2, norm of estimates =  0.60759940E-10
 Iteration   3, No. converged =   3, norm of estimates =  0.52652580E-14

 The    4 generalized Ritz values closest to   1.0000 are:

        1           9.8704
        2          39.4912
        3          88.8909
        4         158.1175


f12fgfe.r

 F12FGF Example Program Results

  Ritz values and residuals
               1            2
 1    8.9117E+02   1.7472E-15
 2    9.1978E+02   7.7418E-16
 3    9.1978E+02   5.7476E-16
 4    9.4839E+02   1.0840E-15


f16dlfe.r

 F16DLF Example Program Results

 Sum of elements of x is   29


f16dnfe.r

 F16DNF Example Program Results

 Index of largest component of x is  3
 Largest component of x is          11


f16dpfe.r

 F16DPF Example Program Results

 Index of smallest component of x is  4
 Smallest component of x is          -2


f16dqfe.r

 F16DQF Example Program Results

 Index of absolutely largest component of x is  3
 Absolutely largest component of x is          11


f16drfe.r

 F16DRF Example Program Results

 Index of absolutely smallest component of x is  1
 Absolutely smallest component of x is           1


f16eafe.r

 F16EAF Example Program Results

 Accumulated dot product, r =    0.6000


f16ecfe.r

 F16ECF Example Program Results

 Result of scaled vector addition is
 y = -12.9000  18.5000   4.7000   8.7000  -9.0000


f16ehfe.r

 F16EHF Example Program Results

 Result of scaled vector addition is
 w = -12.9000  18.5000   4.7000   8.7000  -9.0000


f16elfe.r

 F16ELF Example Program Results

 Sum of elements of x is 29.30000


f16gcfe.r

 F16GCF Example Program Results

 Result of scaled vector addition is
 y = ( ( -20.4000,  -3.3000), (  -2.9000,  14.5000), ( -18.6000,   1.3000) )


f16ghfe.r

 F16GHF Example Program Results

 Result of scaled vector addition is
 w = ( ( -20.4000,  -3.3000), (  -2.9000,  14.5000), ( -18.6000,   1.3000) )


f16glfe.r

 F16GLF Example Program Results

 Sum of elements of x is ( 21.80000,  7.50000)


f16jnfe.r

 F16JNF Example Program Results

 Index of largest component of x is  3
 Largest component of x is    11.00000


f16jpfe.r

 F16JPF Example Program Results

 Index of smallest component of x is  4
 Smallest component of x is    -2.00000


f16jqfe.r

 F16JQF Example Program Results

 Index of absolutely largest component of x is  3
 Absolutely largest component of x is    11.00000


f16jrfe.r

 F16JRF Example Program Results

 Index of absolutely smallest component of x is  1
 Absolutely smallest component of x is     1.00000


f16jsfe.r

 F16JSF Example Program Results

 Index of absolutely largest component of x is  2
 Absolutely largest component of x is     8.20000


f16jtfe.r

 F16JTF Example Program Results

 Index of absolutely smallest component of x is  1
 Absolutely smallest component of x is     6.10000


f16rbfe.r

 F16RBF Example Program Results

 Norms of banded matrix AB:

 One norm           =   18.0000
 Infinity norm      =   12.0000
 Frobenius norm     =   13.5647
 Maximum norm       =    6.0000


f16ubfe.r

 F16UBF Example Program Results

 Norms of banded matrix AB:

 One norm           =   24.2711
 Infinity norm      =   16.0105
 Frobenius norm     =   17.4069
 Maximum norm       =    7.2111


g01abfe.r

 G01ABF Example Program Results

 Number of cases   29
 Data as input -
          Var  1     Var  2     Var  1     Var  2     Var  1     Var  2
           350.0       47.0      550.0       95.0      380.0      211.0
           510.0      122.0     1270.0      530.0      300.0       38.0
          2630.0      278.0      810.0      309.0      140.0       75.0
           450.0       43.0     2280.0      407.0      250.0      142.0
           540.0       89.0      720.0      159.0       90.0       35.0
           480.0      103.0      180.0       78.0     3160.0      969.0
           220.0      120.0      860.0      333.0      300.0       73.0
          1460.0      147.0      400.0       30.0      620.0      100.0
           120.0       55.0      780.0      145.0      230.0      101.0
          1070.0      468.0      160.0       86.0

 No. of valid cases   29
             Variable 1                    Variable 2
 Mean              734.8                         185.8
 Corr SSP    0.16396E+08    0.34830E+07    0.11319E+07
 Minimum            90.0                          30.0
 Maximum          3160.0                         969.0
 Sum of weights                    29.0
 Std devn          765.2                         201.1
 Correln                         0.8085


g01adfe.r

 G01ADF Example Program Results

 Number of classes   14

           Class          Frequency

       9.30     12.00           3
      12.00     14.00          19
      14.00     16.00          52
      16.00     18.00          96
      18.00     20.00         121
      20.00     22.00         115
      22.00     24.00          86
      24.00     26.00          70
      26.00     28.00          49
      28.00     30.00          31
      30.00     32.00          16
      32.00     34.00           6
      34.00     36.00           8
      36.00     39.70           7

  Mean          21.4932
  Std devn       4.9325
  Skewness       0.7072
  Kurtosis       0.5738
  Number of cases     679


g01aefe.r

 G01AEF Example Program Results

 Number of cases  70
 Number of classes   7
 Routine-supplied class boundaries

 *** Frequency  distribution ***

        Class            Frequency

    Up to       20.70          0
    20.70 to    21.28          6
    21.28 to    21.86         16
    21.86 to    22.44         21
    22.44 to    23.02         14
    23.02 to    23.60         13
    23.60    and over          0

 Total frequency =     70
 Minimum =     20.70
 Maximum =     23.60


g01affe.r

 G01AFF Example Program Results

 Data as input -
 Number of rows  2
 Number of columns  3
 NUM =  0 (NUM = 1 means table reduced in size if necessary)

 Table of observed and expected frequencies

               Column
            1     2     3
 Row
  1        86    51    13
           74.   57.   19.
                                                 Row total =     150
  2       130   115    41
          142.  109.   35.
                                                 Row total =     286

 Column
 totals   216   166    54
                                                 Grand total =     436

 Chi-squared =      6.352   D.F. =   2


g01ajfe.r

 G01AJF Example Program Results

           FREQUENCY
              20  .          .   20
              18  .          .   18
              16  .          .   16
              14  .          .   14
              12  .    *     .   12
              10  .    **    .   10
               8  .   ***    .    8
               6  .   ***    .    6
               4  .* *****   .    4
               2  .******* * .    2
                  ------------
                 -4.44    18.09

 CUM. FREQ.
    30  .          .   30
    27  .          .   27
    24  .          .   24
    21  .         *.   21
    18  .         *.   18
    15  .        **.   15
    12  .        **.   12
     9  .       ***.    9
     6  .      ****.    6
     3  .    ******.    3
        ------------
      -10.00     5.00


g01alfe.r

 G01ALF Example Program Results

 Maximum                            12.0000
 Upper Hinge (75% quantile)          9.5000
 Median      (50% quantile)          6.5000
 Lower Hinge (25% quantile)          2.5000
 Minimum                             1.0000


g01amfe.r

 G01AMF Example Program Results

 Data Values:
    4.90   7.00   3.90   9.50   1.30   3.10   9.70   0.30   8.50   0.60   6.20

 Quantile     Result

    0.25       2.20
    0.50       4.90
    1.00       9.70


g01anfe.r

 G01ANF Example Program Results

 Input data:
 60 observations
 eps =  0.20

 Quantile     Result
    0.25      22.49
    0.50      36.86
    1.00      59.95


g01apfe.r

 G01APF Example Program Results

 Input data:
 60 observations
 eps =  0.20

 Quantile     Result
    0.25      22.49
    0.50      39.54
    1.00      59.95


g01arfe.r

 G01ARF Example Program Results

 Stem-and-leaf display
 Leaf digit unit = 1.0
 1  2  represents  12.

       LO  -9

   3    0  11
   6    0  222
  10    0  3333
  15    0  44444
  15    0  55555
  10    0  6666
   6    0  777
   3    0  88

       HI  31

 Stem-and-leaf display
 Leaf digit unit = 1.0
 1  2  represents  12.

   1    -0. 9
   1    -0*
  15    +0* 11222333344444
  15    +0. 55555666677788
   1     1*
   1     1.
   1     2*
   1     2.
   1     3* 1


g01atfe.r

 G01ATF Example Program Results

 Data supplied in 3 blocks
 100 valid observations
 Mean                   0.51
 Std devn               4.24
 Skewness               0.18
 Kurtosis              -0.59
 Minimum               -8.86
 Maximum               10.25


g01aufe.r

 G01AUF Example Program Results

 Summary for block 1
 21 valid observations
   Mean                    0.73
   Std devn                4.40
   Skewness               -0.05
   Kurtosis               -1.00
   Minimum                -8.74
   Maximum                 7.65

 Summary for block 2
 51 valid observations
   Mean                    0.28
   Std devn                3.96
   Skewness                0.46
   Kurtosis               -0.16
   Minimum                -6.25
   Maximum                10.12

 Summary for block 3
 28 valid observations
   Mean                    0.48
   Std devn                4.65
   Skewness                0.19
   Kurtosis               -0.58
   Minimum                -8.86
   Maximum                10.25

 Summary for the combined data
 100 valid observations
   Mean                    0.51
   Std devn                4.24
   Skewness                0.18
   Kurtosis               -0.59
   Minimum                -8.86
   Maximum                10.25


g01bjfe.r

 G01BJF Example Program Results

    N     P      K     PLEK      PGTK      PEQK

    4   0.500    2   0.68750   0.31250   0.37500
   19   0.440   13   0.99138   0.00862   0.01939
  100   0.750   67   0.04460   0.95540   0.01700
 2000   0.330  700   0.97251   0.02749   0.00312


g01bkfe.r

 G01BKF Example Program Results

     RLAMDA     K     PLEK      PGTK      PEQK

      0.750     3   0.99271   0.00729   0.03321
      9.200    12   0.86074   0.13926   0.07755
     34.000    25   0.06736   0.93264   0.02140
    175.000   175   0.52009   0.47991   0.03014


g01blfe.r

 G01BLF Example Program Results

    N   L   M   K     PLEK      PGTK      PEQK

   10   2   5   1   0.77778   0.22222   0.55556
   40  10   3   2   0.98785   0.01215   0.13664
  155  35 122  22   0.01101   0.98899   0.00779
 1000 444 500 220   0.42429   0.57571   0.04913


g01dafe.r

 G01DAF Example Program Results

 Set size = 15
 Error tolerance (input) =     0.100E-02
 Error estimate (output) =     0.222E-07
 Normal scores
              -1.736    -1.248    -0.948    -0.715    -0.516
              -0.335    -0.165     0.000     0.165     0.335
               0.516     0.715     0.948     1.248     1.736


g01dbfe.r

 G01DBF Example Program Results

 Sample size = 10
 Normal scores
               -1.5388     -1.0014     -0.6561     -0.3757     -0.1227
                0.1227      0.3757      0.6561      1.0014      1.5388


g01dcfe.r

 G01DCF Example Program Results

 Sample size =  6
 Variance-covariance matrix
   0.4159
   0.2085  0.2796
   0.1394  0.1889  0.2462
   0.1025  0.1397  0.1834  0.2462
   0.0774  0.1060  0.1397  0.1889  0.2796
   0.0563  0.0774  0.1025  0.1394  0.2085  0.4159


g01ddfe.r

 G01DDF Example Program Results

 For sample number 1, value of W statistic =  0.9005
                      Significance level is   0.0421

 For sample number 2, value of W statistic =  0.9590
                      Significance level is   0.5246


g01dhfe.r

 G01DHF Example Program Results

 Scores: Savage
 Ties  : Average

     1.4500
     0.3250
     1.4500
     1.4500
     0.3250


g01eafe.r

 G01EAF Example Program Results

  TAIL    X      Probability

   L     1.96       0.9750
   U     1.96       0.0250
   C     1.96       0.9500
   S     1.96       0.0500


g01ebfe.r

 G01EBF Example Program Results

  TAIL     T       DF      Probability

   L     0.850    20.0        0.7973
   S     0.850    20.0        0.4054
   C     0.850    20.0        0.5946
   U     0.850    20.0        0.2027


g01ecfe.r

 G01ECF Example Program Results

  TAIL     X       DF      Probability

   L     8.260    20.0        0.0100
   L     6.200     7.5        0.4279
   L    55.760    45.0        0.8694


g01edfe.r

 G01EDF Example Program Results

  TAIL      F      DF1     DF2     Probability

   L     5.500    1.50   25.50        0.9837
   L    39.900    1.00    1.00        0.9000
   L     2.500   20.25    1.00        0.5342


g01eefe.r

 G01EEF Example Program Results

     X        A        B        P        Q       PDF

  0.2500   1.0000   2.0000   0.4375   0.5625   1.5000
  0.7500   1.5000   1.5000   0.8045   0.1955   1.1027
  0.5000   2.0000   1.0000   0.2500   0.7500   1.0000


g01effe.r

 G01EFF Example Program Results

  TAIL        G            A        B      Probability

   L        15.50         4.00     2.00        0.9499
   L         0.50         4.00     1.00        0.0018
   L        10.00         1.00     2.00        0.9933
   L         5.00         2.00     2.00        0.7127


g01emfe.r

 G01EMF Example Program Results

   Q       V    IR    Prob

  4.6543  10.0   5     0.9500
  2.8099  60.0  12     0.3000
  4.2636   5.0   4     0.9000


g01epfe.r

 G01EPF Example Program Results

  Durbin-Watson statistic     0.9238

  Probability for the lower bound =     0.0610
  Probability for the upper bound =     0.0060


g01erfe.r

 G01ERF Example Program Results

       T          VK     Probability

    7.0000      0.0000      0.6141
    2.8000      2.4000      0.9983
    1.0000      1.0000      0.7944
   -1.4000      1.3000      0.1016


g01etfe.r

 G01ETF Example Program Results

   X          Y

  0.5     3.7328E-01


g01eufe.r

 G01EUF Example Program Results

  X     RKAPPA    BETA2        Y        IFAIL

  0.1      2.5      0.7     9.9982E-01     0


g01eyfe.r

 G01EYF Example Program Results

     D       N    One-sided probability

  0.3230    10           0.0994
  0.3690    10           0.0497
  0.4090    10           0.0251
  0.4570    10           0.0099
  0.4890    10           0.0050
  0.0535   400           0.1001
  0.0610   400           0.0502
  0.0680   400           0.0243
  0.0760   400           0.0096
  0.0815   400           0.0048


g01ezfe.r

 G01EZF Example Program Results

     D      N1    N2    Two-sided probability

  0.5000     5    10           0.3506
  0.5000    10    10           0.1678
  0.5000    20    10           0.0623
  0.4833    20    15           0.0261
  0.1412   400   200           0.0083
  0.2861   200    20           0.0789
  0.2113  1000    20           0.2941
  0.1796   200    50           0.1392
  0.1800    15   200           0.6926
  0.1800   100   100           0.0782


g01fafe.r

 G01FAF Example Program Results

  Tail    Probability     Deviate

   L         0.975         1.9600
   U         0.025         1.9600
   C         0.950         1.9600
   S         0.050         1.9600


g01fbfe.r

 G01FBF Example Program Results

      P      DF    TAIL      X

    0.010  20.000   S      2.845
    0.010   7.500   L     -2.943
    0.990  45.000   C      2.690


g01fcfe.r

 G01FCF Example Program Results

      P       DF      X

    0.010  20.000   8.260
    0.428   7.500   6.200
    0.869  45.000  55.759


g01fdfe.r

 G01FDF Example Program Results

      P      DF1     DF2      F

    0.984  10.000  25.500   2.837
    0.900   1.000   1.000  39.863
    0.534  20.250   1.000   2.500


g01fefe.r

 G01FEF Example Program Results

  Probability     A         B     Deviate

    0.5000     1.000     2.000    0.2929
    0.9900     1.500     1.500    0.9672
    0.2500    20.000    10.000    0.6105


g01fffe.r

 G01FFF Example Program Results

    P       A       B           X

    0.010   1.000  20.000     0.201
    0.428   7.500   0.100     0.670
    0.869  45.000  10.000   525.979


g01fmfe.r

 G01FMF Example Program Results

   P     V    IR    Quantile

  0.95  10.0   5     4.6543
  0.30  60.0  12     2.8099
  0.90   5.0   4     4.2636


g01ftfe.r

 G01FTF Example Program Results

   X          Y        IFAIL

  0.5     1.3558E+00     0


g01gbfe.r

 G01GBF Example Program Results

      T       DF    DELTA    PROB

   -1.528  20.000   2.000  0.0003
   -0.188   7.500   1.000  0.1189
    1.138  45.000   0.000  0.8694


g01gcfe.r

 G01GCF Example Program Results

      X       DF   RLAMDA   PROB

    8.260  20.000   3.500  0.0032
    6.200   7.500   2.000  0.2699
   55.760  45.000   1.000  0.8443


g01gdfe.r

 G01GDF Example Program Results

      F      DF1     DF2   RLAMDA   PROB

    5.500   1.500  25.500   3.000  0.8214
   39.900   1.000   1.000   2.000  0.8160
    2.500  20.250   1.000   0.000  0.5342


g01gefe.r

 G01GEF Example Program Results

      X       A       B    RLAMDA   PROB

    0.250   1.000   2.000   1.000  0.3168
    0.750   1.500   1.500   0.500  0.7705
    0.500   2.000   1.000   0.000  0.2500


g01hafe.r

 G01HAF Example Program Results

      X       Y      RHO    PROB

    1.700  23.100   0.000  0.9554
    0.000   0.000   0.100  0.2659
    3.300  11.100   0.540  0.9995
    9.100   9.100   0.170  1.0000


g01hbfe.r

 G01HBF Example Program Results

 Multivariate Normal probability = 0.9142


g01hcfe.r

 G01HCF Example Program Results

  A(1)         B(1)       A(2)        B(2)        DF  RHO     TAIL P

 -Inf         0.4000E+01 -Inf         0.8000E+00   8  0.6000  L    0.7764
 -0.4000E+02  0.2000E+01  0.0000E+00  0.4000E+01  12 -0.2000  C    0.4876
 -0.2000E+01  Inf         0.8000E+01  Inf          2  0.3000  U    0.0059


g01hdfe.r

 G01HDF Example Program Results

           Probability:             0.30164222E+00
           Error estimate:                0.11E-04

           Probability:             0.86224881E-04
           Error estimate:                0.73E-07


g01jcfe.r

 G01JCF Example Program Results

         A     MULT  RLAMDA

       6.00     1     0.00
       3.00     1     0.00
       1.00     1     0.00
 C =  20.00    PROB = 0.8760
       7.00     1     6.00
       3.00     1     2.00
 C =  10.00    PROB = 0.0451


g01jdfe.r

 G01JDF Example Program Results

  Values of lambda  -9.00 -7.00 -5.00 -3.00 -1.00  2.00  4.00  6.00  8.00 10.00
  Value of D         1.00
  value of C         0.00

  Probability =     0.5749


g01kafe.r

 G01KAF Example Program Results

    X             MEAN          STANDARD      RESULT
                                DEVIATION

    1.00000E+00   0.00000E+00   1.00000E+00   2.41971E-01
    4.00000E+00   2.00000E+00   1.00000E+00   5.39910E-02
    1.00000E-01   0.00000E+00   1.00000E-02   7.69460E-21
    1.00000E+00   0.00000E+00   1.00000E+01   3.96953E-02


g01kffe.r

 G01KFF Example Program Results

       X            A            B          RESULT

    1.0000E-01   3.0000E+00   2.0000E+00   5.9452E-04
    3.0000E+00   1.0000E+01   1.1000E+01   1.5921E-12
    6.0000E+00   5.0000E+00   1.0000E+00   1.3385E-01
    4.0000E+00   1.0000E+01   1.0000E-01   3.0690E-08
    9.0000E+00   9.0000E+00   5.0000E-01   8.3251E-03
    1.6000E+01   3.5000E+00   2.5000E+00   2.0723E-02


g01kkfe.r

 G01KKF Example Program Results

     X         A         B         PDF      IVALID
 --------------------------------------------------
   0.10      3.00      2.00     0.595E-03      0
   3.00     10.00     11.00     0.159E-11      0
   6.00      5.00      1.00     0.134E+00      0
   4.00     10.00      0.10     0.307E-07      0
   9.00      9.00      0.50     0.833E-02      0


g01kqfe.r

 G01KQF Example Program Results

     X        XMU      XSTD        PDF      IVALID
 --------------------------------------------------
   1.00      0.00      1.00     0.242E+00      0
   4.00      2.00      1.00     0.540E-01      0
   0.10      0.00      0.01     0.769E-20      0
   1.00      0.00     10.00     0.397E-01      0


g01lbfe.r

 G01LBF Example Program Results

 Vector of Means:
   0.1000   0.2000   0.3000   0.4000

 Covariance Matrix:
             1          2          3          4
 1      4.1600
 2     -3.1200     5.0300
 3      0.5600    -0.8300     0.7600
 4     -0.1000     1.1800     0.3400     1.1800

 Rank of the covariance matrix:  4

        PDF                     X
   ------------------------------------------------
    3.0307E-03   1.0000   1.0000   1.0000   1.0000
    4.5232E-06   1.0000   2.0000   3.0000   4.0000


g01mbfe.r

 G01MBF Example Program Results

  Mean     Sigma    X        Reciprocal
                             Mills Ratio

  0.0000   1.0000   0.0000   0.7979
  1.0000   2.5000  -2.0000   0.0878
  9.0000   1.6000  10.3000   0.8607


g01mtfe.r

 G01MTF Example Program Results

   X          Y

  0.5     1.6523E-01


g01mufe.r

 G01MUF Example Program Results

   X     RKAPPA    BETA2        Y        IFAIL

  2.5      0.4      0.1     8.3675E-02     0


g01nafe.r

 G01NAF Example Program Results

 N =  10 BETA =  0.800 CON =  1.000

     Cumulants       Moments

  1  0.1752E+02      0.1752E+02
  2  0.3501E+03      0.6569E+03
  3  0.1609E+05      0.3986E+05
  4  0.1170E+07      0.3404E+07


g01nbfe.r

 G01NBF Example Program Results

 N =  10 BETA =  0.800 Y0 =  1.000

       Moments

  1   0.682E+00
  2   0.536E+00
  3   0.443E+00


g01ptfe.r

 G01PTF Example Program Results

   X          Y

  0.5    -6.2932E-01


g01qtfe.r

 G01QTF Example Program Results

   X          Y

  0.5     9.0868E-01


g01rtfe.r

 G01RTF Example Program Results

   X          Y

  0.5    -3.6034E-02


g01safe.r

 G01SAF Example Program Results

    TAIL      X        XMU      XSTD       P     IVALID
 --------------------------------------------------------
     L      1.96      0.00      1.00     0.975      0
     U      1.96      0.00      1.00     0.025      0
     C      1.96      0.00      1.00     0.950      0
     S      1.96      0.00      1.00     0.050      0


g01sbfe.r

 G01SBF Example Program Results

    TAIL      T        DF        P      IVALID
 -----------------------------------------------
     L      0.85     20.00     0.797      0
     S      0.85     20.00     0.405      0
     C      0.85     20.00     0.595      0
     U      0.85     20.00     0.203      0


g01scfe.r

 G01SCF Example Program Results

    TAIL     X        DF        P      IVALID
 ---------------------------------------------
     L      8.26     20.00     0.010      0
     L      6.20      7.50     0.428      0
     L     55.76     45.00     0.869      0


g01sdfe.r

 G01SDF Example Program Results

    TAIL      F        DF1       DF2       P      IVALID
 --------------------------------------------------------
     L      5.50      1.50     25.50     0.984      0
     L     39.90      1.00      1.00     0.900      0
     L      2.50     20.25      1.00     0.534      0


g01sefe.r

 G01SEF Example Program Results

   TAIL    BETA        A         B        P      IVALID
 --------------------------------------------------------
     L      0.26      1.00      2.00     0.452      0
     L      0.75      1.50      1.50     0.804      0
     L      0.50      2.00      1.00     0.250      0


g01sffe.r

 G01SFF Example Program Results

   TAIL      G         A         B         P     IVALID
 ---------------------------------------------------------
     L     15.50      4.00      2.00     0.950      0
     L      0.50      4.00      1.00     0.002      0
     L     10.00      1.00      2.00     0.993      0
     L      5.00      2.00      2.00     0.713      0


g01sjfe.r

 G01SJF Example Program Results

     N         P         K       PLEK      PGTK      PEQK    IVALID
 --------------------------------------------------------------------
      4      0.50         2     0.688     0.312     0.375      0
     19      0.44        13     0.991     0.009     0.019      0
    100      0.75        67     0.045     0.955     0.017      0
   2000      0.33       700     0.973     0.027     0.003      0


g01skfe.r

 G01SKF Example Program Results

     L         K       PLEK      PGTK      PEQK    IVALID
 ----------------------------------------------------------
   0.75         3     0.993     0.007     0.033      0
   9.20        12     0.861     0.139     0.078      0
  34.00        25     0.067     0.933     0.021      0
 175.00       175     0.520     0.480     0.030      0


g01slfe.r

 G01SLF Example Program Results

     N         L         M         K       PLEK      PGTK      PEQK    IVALID
 ------------------------------------------------------------------------------
     10         2         5         1     0.778     0.222     0.556      0
     40        10         3         2     0.988     0.012     0.137      0
    155        35       122        22     0.011     0.989     0.008      0
   1000       444       500       220     0.424     0.576     0.049      0


g01tafe.r

 G01TAF Example Program Results

    TAIL      P        XMU      XSTD       X     IVALID
 --------------------------------------------------------
     L     0.975     0.000     1.000     1.960      0
     U     0.025     0.000     1.000     1.960      0
     C     0.950     0.000     1.000     1.960      0
     S     0.050     0.000     1.000     1.960      0


g01tbfe.r

 G01TBF Example Program Results

    TAIL      P        DF        T      IVALID
 -----------------------------------------------
     S     0.010     20.00     2.845      0
     L     0.010      7.50    -2.943      0
     C     0.990     45.00     2.690      0


g01tcfe.r

 G01TCF Example Program Results

    TAIL      P        DF        X      IVALID
 ------------------------------------------------
     L     0.010     20.00     8.260      0
     L     0.428      7.50     6.201      0
     L     0.869     45.00    55.738      0


g01tdfe.r

 G01TDF Example Program Results

    TAIL      P        DF1       DF2       F      IVALID
 ---------------------------------------------------------
     L     0.984     10.00     25.50     2.847      0
     L     0.900      1.00      1.00    39.863      0
     L     0.534     20.25      1.00     2.498      0


g01tefe.r

 G01TEF Example Program Results

    TAIL      P        A         B        BETA   IVALID
 -------------------------------------------------------
     L     0.500      1.00      2.00     0.293      0
     L     0.990      1.50      1.50     0.967      0
     L     0.250     20.00     10.00     0.611      0


g01tffe.r

 G01TFF Example Program Results

    TAIL    P         A         B         G     IVALID
 -------------------------------------------------------
     L     0.010      1.00     20.00     0.201      0
     L     0.428      7.50      0.10     0.670      0
     L     0.869     45.00     10.00   525.839      0


g01wafe.r

 G01WAF Example Program Results

  Interval         Mean
 ------------------------
 [  1, 15]        -427.6
 [  2, 16]        -332.5
 [  3, 17]        -337.1
 [  4, 18]        -438.2
 [  5, 19]        -604.4
 [  6, 20]        -789.4
 [  7, 21]        -935.4
 [  8, 22]        -990.6
 [  9, 23]        -927.1
 [ 10, 24]        -752.1
 [ 11, 25]        -501.3
 [ 12, 26]        -227.2
 [ 13, 27]          23.2
 [ 14, 28]         236.2
 [ 15, 29]         422.4
 [ 16, 30]         604.2

 Total number of observations :    30
 Length of window             :    15


g02aafe.r

 G02AAF Example Program Results

 Nearest Correlation Matrix
          1       2       3       4
 1   1.0000 -0.8084  0.1916  0.1068
 2  -0.8084  1.0000 -0.6562  0.1916
 3   0.1916 -0.6562  1.0000 -0.8084
 4   0.1068  0.1916 -0.8084  1.0000

  Number of Newton steps taken:          3
  Number of function evaluations:        4


g02abfe.r

 G02ABF Example Program Results

 Nearest Correlation Matrix X
          1       2       3       4
 1   1.0000 -0.9187  0.0257  0.0086
 2  -0.9187  1.0000 -0.3008  0.2270
 3   0.0257 -0.3008  1.0000 -0.8859
 4   0.0086  0.2270 -0.8859  1.0000

 Number of Newton steps taken:          5
 Number of function evaluations:        6

 ALPHA:                                 0.020

 Eigenvalues of X
             1          2          3          4
 1      0.0392     0.1183     1.6515     2.1910


g02aefe.r

 G02AEF Example Program Results

 Factor Loading Matrix X
          1       2
 1   0.7665 -0.6271
 2  -0.4250  0.9052
 3  -0.4250 -0.9052
 4   0.7665  0.6271

 Number of steps taken:          5
 Number of function evaluations:        6

 Nearest Correlation Matrix
          1       2       3       4
 1   1.0000 -0.8935  0.2419  0.1943
 2  -0.8935  1.0000 -0.6388  0.2419
 3   0.2419 -0.6388  1.0000 -0.8935
 4   0.1943  0.2419 -0.8935  1.0000


g02ajfe.r

 G02AJF Example Program Results

 Returned H Matrix
          1       2       3       4
 1   0.0000  1.0000  0.0000  0.0000
 2   1.0000  0.0000  0.1500  0.1500
 3   0.0000  0.1500  0.0000  0.0000
 4   0.0000  0.1500  0.0000  0.0000

 Nearest Correlation Matrix X
               1            2            3            4
 1    1.0000E+00  -9.2285E-01   7.7335E-01   2.5854E-03
 2   -9.2285E-01   1.0000E+00  -7.8433E-01  -8.4891E-07
 3    7.7335E-01  -7.8433E-01   1.0000E+00  -6.1477E-02
 4    2.5854E-03  -8.4891E-07  -6.1477E-02   1.0000E+00

 Number of iterations:         66

 Norm value:                    0.1183

 ALPHA:                         0.0400

 Eigenvalues of X
             1          2          3          4
 1      0.0769     0.2637     1.0031     2.6563


g02anfe.r

 G02ANF Example Program Results

 Symmetrised Input Matrix G
          1       2       3       4       5
 1   1.0000 -0.0991  0.5665 -0.5653 -0.3441
 2  -0.0991  1.0000 -0.4273  0.8474  0.4975
 3   0.5665 -0.4273  1.0000 -0.1837 -0.0585
 4  -0.5653  0.8474 -0.1837  1.0000 -0.2713
 5  -0.3441  0.4975 -0.0585 -0.2713  1.0000

 Nearest Perturbed Correlation Matrix X
          1       2       3       4       5
 1   1.0000 -0.0991  0.5665 -0.3826 -0.2329
 2  -0.0991  1.0000 -0.4273  0.5735  0.3367
 3   0.5665 -0.4273  1.0000 -0.1243 -0.0396
 4  -0.3826  0.5735 -0.1243  1.0000 -0.1836
 5  -0.2329  0.3367 -0.0396 -0.1836  1.0000

 K:                                 3

 Number of iterations taken:       27

 ALPHA:                             0.3232

 Norm value:                        0.5624

 Smallest eigenvalue of A:          0.3359


g02apfe.r

 G02APF Example Program Results

 Symmetrised Input Matrix G
          1       2       3       4       5
 1   1.0000 -0.0991  0.5665 -0.5653 -0.3441
 2  -0.0991  1.0000 -0.4273  0.8474  0.4975
 3   0.5665 -0.4273  1.0000 -0.1837 -0.0585
 4  -0.5653  0.8474 -0.1837  1.0000 -0.2713
 5  -0.3441  0.4975 -0.0585 -0.2713  1.0000

 Nearest Correlation Matrix X
          1       2       3       4       5
 1   1.0000 -0.0991  0.3799 -0.3791 -0.2308
 2  -0.0991  1.0000 -0.2865  0.5683  0.3336
 3   0.3799 -0.2865  1.0000 -0.1232 -0.0392
 4  -0.3791  0.5683 -0.1232  1.0000 -0.2266
 5  -0.2308  0.3336 -0.0392 -0.2266  1.0000

 Number of iterations taken:       27

 ALPHA:                             0.3294

 Norm value:                        0.6526

 THETA:                             0.1000

 Smallest eigenvalue of target:     0.8643

 Eigenvalues of X
             1          2          3          4          5
 1      0.0864     0.7431     1.0044     1.2018     1.9642


g02bafe.r

 G02BAF Example Program Results

 Number of variables (columns) = 3
 Number of cases     (rows)    = 5

 Data matrix is:-

            1           2           3
   1      2.0000      3.0000      3.0000
   2      4.0000      6.0000      4.0000
   3      9.0000      9.0000      0.0000
   4      0.0000     12.0000      2.0000
   5     12.0000     -1.0000      5.0000

 Variable   Mean    St. dev.
     1     5.4000     4.9800
     2     5.8000     5.0695
     3     2.8000     1.9235

 Sums of squares and cross-products of deviations
            1           2           3
   1     99.2000    -57.6000      6.4000
   2    -57.6000    102.8000    -29.2000
   3      6.4000    -29.2000     14.8000

 Correlation coefficients
            1           2           3
   1      1.0000     -0.5704      0.1670
   2     -0.5704      1.0000     -0.7486
   3      0.1670     -0.7486      1.0000


g02bbfe.r

 G02BBF Example Program Results

 Number of variables (columns) =    3
 Number of cases     (rows)    =    5

 Data matrix is:-

            1           2           3
   1      2.0000      3.0000      3.0000
   2      4.0000      6.0000      4.0000
   3      9.0000      9.0000      0.0000
   4      0.0000     12.0000      2.0000
   5     12.0000     -1.0000      5.0000

 Variable   Mean    St. dev.
     1     6.0000     5.2915
     2     2.6667     3.5119
     3     4.0000     1.0000

 Sums of squares and cross-products of deviations
            1           2           3
   1     56.0000    -30.0000     10.0000
   2    -30.0000     24.6667     -4.0000
   3     10.0000     -4.0000      2.0000

 Correlation coefficients
            1           2           3
   1      1.0000     -0.8072      0.9449
   2     -0.8072      1.0000     -0.5695
   3      0.9449     -0.5695      1.0000

 Number of cases actually used:     3


g02bcfe.r

 G02BCF Example Program Results

 Number of variables (columns) = 3
 Number of cases     (rows)    = 5

 Data matrix is:-

            1           2           3
   1      2.0000      3.0000      3.0000
   2      4.0000      6.0000      4.0000
   3      9.0000      9.0000      0.0000
   4      0.0000     12.0000      2.0000
   5     12.0000     -1.0000      5.0000

 Variable   Mean    St. dev.
     1     6.7500     4.5735
     2     7.5000     3.8730
     3     3.5000     1.2910

 Sums of squares and cross-products of deviations
            1           2           3
   1     62.7500     21.0000     10.0000
   2     21.0000     45.0000     -6.0000
   3     10.0000     -6.0000      5.0000

 Correlation coefficients
            1           2           3
   1      1.0000      0.9707      0.9449
   2      0.9707      1.0000     -0.6547
   3      0.9449     -0.6547      1.0000

 Minimum number of cases used for any pair of variables:  3

 Numbers used for each pair are:
            1           2           3
   1      4.0000      3.0000      3.0000
   2      3.0000      4.0000      3.0000
   3      3.0000      3.0000      4.0000


g02bdfe.r

 G02BDF Example Program Results

 Number of variables (columns) =    3
 Number of cases     (rows)    =    5

 Data matrix is:-

            1           2           3
   1      2.0000      3.0000      3.0000
   2      4.0000      6.0000      4.0000
   3      9.0000      9.0000      0.0000
   4      0.0000     12.0000      2.0000
   5     12.0000     -1.0000      5.0000

 Variable   Mean    St. dev.
     1     5.4000     4.9800
     2     5.8000     5.0695
     3     2.8000     1.9235

 Sums of squares and cross-products about zero
            1           2           3
   1    245.0000     99.0000     82.0000
   2     99.0000    271.0000     52.0000
   3     82.0000     52.0000     54.0000

 Correlation-like coefficients
            1           2           3
   1      1.0000      0.3842      0.7129
   2      0.3842      1.0000      0.4299
   3      0.7129      0.4299      1.0000


g02befe.r

 G02BEF Example Program Results

 Number of variables (columns) =    3
 Number of cases     (rows)    =    5

 Data matrix is:-

            1           2           3
   1      2.0000      3.0000      3.0000
   2      4.0000      6.0000      4.0000
   3      9.0000      9.0000      0.0000
   4      0.0000     12.0000      2.0000
   5     12.0000     -1.0000      5.0000

 Variable   Mean    St. dev.
     1     6.0000     5.2915
     2     2.6667     3.5119
     3     4.0000     1.0000

 Sums of squares and cross-products about zero
            1           2           3
   1    164.0000     18.0000     82.0000
   2     18.0000     46.0000     28.0000
   3     82.0000     28.0000     50.0000

 Correlation-like coefficients
            1           2           3
   1      1.0000      0.2072      0.9055
   2      0.2072      1.0000      0.5838
   3      0.9055      0.5838      1.0000

 Number of cases actually used:     3


g02bffe.r

 G02BFF Example Program Results

 Number of variables (columns) =    3
 Number of cases     (rows)    =    5

 Data matrix is:-

            1           2           3
   1      2.0000      3.0000      3.0000
   2      4.0000      6.0000      4.0000
   3      9.0000      9.0000      0.0000
   4      0.0000     12.0000      2.0000
   5     12.0000     -1.0000      5.0000

 Variable   Mean    St. dev.
     1     6.7500     4.5735
     2     7.5000     3.8730
     3     3.5000     1.2910

 Sums of squares and cross-products about zero
            1           2           3
   1    245.0000    111.0000     82.0000
   2    111.0000    270.0000     57.0000
   3     82.0000     57.0000     54.0000

 Correlation-like coefficients
            1           2           3
   1      1.0000      0.9840      0.9055
   2      0.9840      1.0000      0.7699
   3      0.9055      0.7699      1.0000

 Minimum number of cases used for any pair of variables:     3

 Numbers used for each pair are:
            1           2           3
   1      4.0000      3.0000      3.0000
   2      3.0000      4.0000      3.0000
   3      3.0000      3.0000      4.0000


g02bgfe.r

 G02BGF Example Program Results

 Number of variables (columns) =    4
 Number of cases     (rows)    =    5

 Data matrix is:-

            1           2           3           4
   1      3.0000      3.0000      1.0000      2.0000
   2      6.0000      4.0000     -1.0000      4.0000
   3      9.0000      0.0000      5.0000      9.0000
   4     12.0000      2.0000      0.0000      0.0000
   5     -1.0000      5.0000      4.0000     12.0000

 Variable   Mean    St. dev.
     4     5.4000     4.9800
     1     5.8000     5.0695
     2     2.8000     1.9235

 Sums of squares and cross-products of deviations
            4           1           2
   4     99.2000    -57.6000      6.4000
   1    -57.6000    102.8000    -29.2000
   2      6.4000    -29.2000     14.8000

 Correlation coefficients
            4           1           2
   4      1.0000     -0.5704      0.1670
   1     -0.5704      1.0000     -0.7486
   2      0.1670     -0.7486      1.0000


g02bhfe.r

 G02BHF Example Program Results

 Number of variables (columns) =    4
 Number of cases     (rows)    =    5

 Data matrix is:-
            1           2           3           4
   1      3.0000      3.0000      1.0000      2.0000
   2      6.0000      4.0000     -1.0000      4.0000
   3      9.0000      0.0000      5.0000      9.0000
   4     12.0000      2.0000      0.0000      0.0000
   5     -1.0000      5.0000      4.0000     12.0000

 Variable   Mean    St. dev.
     4     6.0000     5.2915
     1     2.6667     3.5119
     2     4.0000     1.0000

 Sums of squares and cross-products of deviations
            4           1           2
   4     56.0000    -30.0000     10.0000
   1    -30.0000     24.6667     -4.0000
   2     10.0000     -4.0000      2.0000

 Correlation coefficients
            4           1           2
   4      1.0000     -0.8072      0.9449
   1     -0.8072      1.0000     -0.5695
   2      0.9449     -0.5695      1.0000

 Number of cases actually used:    3


g02bjfe.r

 G02BJF Example Program Results

 Number of variables (columns) =    4
 Number of cases     (rows)    =    5

 Data matrix is:-
            1           2           3           4
   1      3.0000      3.0000      1.0000      2.0000
   2      6.0000      4.0000     -1.0000      4.0000
   3      9.0000      0.0000      5.0000      9.0000
   4     12.0000      2.0000      0.0000      0.0000
   5     -1.0000      5.0000      4.0000     12.0000

 Variable   Mean    St. dev.
     4     6.7500     4.5735
     1     7.5000     3.8730
     2     3.5000     1.2910

 Sums of squares and cross-products of deviations
            4           1           2
   4     62.7500     21.0000     10.0000
   1     21.0000     45.0000     -6.0000
   2     10.0000     -6.0000      5.0000

 Correlation coefficients
            4           1           2
   4      1.0000      0.9707      0.9449
   1      0.9707      1.0000     -0.6547
   2      0.9449     -0.6547      1.0000

 Minimum number of cases used for any pair of variables:    3

 Numbers used for each pair are:
            4           1           2
   4      4.0000      3.0000      3.0000
   1      3.0000      4.0000      3.0000
   2      3.0000      3.0000      4.0000


g02bkfe.r

 G02BKF Example Program Results

 Number of variables (columns) =    4
 Number of cases     (rows)    =    5

 Data matrix is:-

            1           2           3           4
   1      3.0000      3.0000      1.0000      2.0000
   2      6.0000      4.0000     -1.0000      4.0000
   3      9.0000      0.0000      5.0000      9.0000
   4     12.0000      2.0000      0.0000      0.0000
   5     -1.0000      5.0000      4.0000     12.0000

 Variable   Mean    St. dev.
     4     5.4000     4.9800
     1     5.8000     5.0695
     2     2.8000     1.9235

 Sums of squares and cross-products about zero
            4           1           2
   4    245.0000     99.0000     82.0000
   1     99.0000    271.0000     52.0000
   2     82.0000     52.0000     54.0000

 Correlation-like coefficients
            4           1           2
   4      1.0000      0.3842      0.7129
   1      0.3842      1.0000      0.4299
   2      0.7129      0.4299      1.0000


g02blfe.r

 G02BLF Example Program Results

 Number of variables (columns) =    4
 Number of cases     (rows)    =    5

 Data matrix is:-

            1           2           3           4
   1      3.0000      3.0000      1.0000      2.0000
   2      6.0000      4.0000     -1.0000      4.0000
   3      9.0000      0.0000      5.0000      9.0000
   4     12.0000      2.0000      0.0000      0.0000
   5     -1.0000      5.0000      4.0000     12.0000

 Variable   Mean    St. dev.
     4     6.0000     5.2915
     1     2.6667     3.5119
     2     4.0000     1.0000

 Sums of squares and cross-products about zero
            4           1           2
   4    164.0000     18.0000     82.0000
   1     18.0000     46.0000     28.0000
   2     82.0000     28.0000     50.0000

 Correlation-like coefficients
            4           1           2
   4      1.0000      0.2072      0.9055
   1      0.2072      1.0000      0.5838
   2      0.9055      0.5838      1.0000

 Number of cases actually used:    3


g02bmfe.r

 G02BMF Example Program Results

 Number of variables (columns) =    4
 Number of cases     (rows)    =    5

 Data matrix is:-

            1           2           3           4
   1      3.0000      3.0000      1.0000      2.0000
   2      6.0000      4.0000     -1.0000      4.0000
   3      9.0000      0.0000      5.0000      9.0000
   4     12.0000      2.0000      0.0000      0.0000
   5     -1.0000      5.0000      4.0000     12.0000

 Variable   Mean    St. dev.
     4     6.7500     4.5735
     1     7.5000     3.8730
     2     3.5000     1.2910

 Sums of squares and cross-products about zero
            4           1           2
   4    245.0000    111.0000     82.0000
   1    111.0000    270.0000     57.0000
   2     82.0000     57.0000     54.0000

 Correlation-like coefficients
            4           1           2
   4      1.0000      0.9840      0.9055
   1      0.9840      1.0000      0.7699
   2      0.9055      0.7699      1.0000

 Minimum number of cases used for any pair of variables:    3

 Numbers used for each pair are:
            4           1           2
   4      4.0000      3.0000      3.0000
   1      3.0000      4.0000      3.0000
   2      3.0000      3.0000      4.0000


g02bnfe.r

 G02BNF Example Program Results

 Number of variables (columns) =    3
 Number of cases     (rows)    =    9

 Data matrix is:-

            1           2           3
   1      1.7000      1.0000      0.5000
   2      2.8000      4.0000      3.0000
   3      0.6000      6.0000      2.5000
   4      1.8000      9.0000      6.0000
   5      0.9900      4.0000      2.5000
   6      1.4000      2.0000      5.5000
   7      1.8000      9.0000      7.5000
   8      2.5000      7.0000      0.0000
   9      0.9900      5.0000      3.0000

 Matrix of ranks:-
            1           2           3
   1      5.0000      1.0000      2.0000
   2      9.0000      3.5000      5.5000
   3      1.0000      6.0000      3.5000
   4      6.5000      8.5000      8.0000
   5      2.5000      3.5000      3.5000
   6      4.0000      2.0000      7.0000
   7      6.5000      8.5000      9.0000
   8      8.0000      7.0000      1.0000
   9      2.5000      5.0000      5.5000

 Matrix of rank correlation coefficients:
 Upper triangle -- Spearman's
 Lower triangle -- Kendall's tau

            1           2           3
   1      1.0000      0.2246      0.1186
   2      0.0294      1.0000      0.3814
   3      0.1176      0.2353      1.0000


g02bpfe.r

 G02BPF Example Program Results

 Number of variables (columns) =    3
 Number of cases     (rows)    =    9

 Data matrix is:-

            1           2           3
   1      1.7000      1.0000      0.5000
   2      2.8000      4.0000      3.0000
   3      0.6000      6.0000      2.5000
   4      1.8000      9.0000      6.0000
   5      0.9900      4.0000      2.5000
   6      1.4000      2.0000      5.5000
   7      1.8000      9.0000      7.5000
   8      2.5000      7.0000      0.0000
   9      0.9900      5.0000      3.0000

 Matrix of ranks:-

 (1 in the column headed In/Out indicates the case was included,
  0 in the column headed In/Out indicates the case was omitted.)

 Case   In/Out     1           2           3
   1      1      3.0000      1.0000      1.0000
   2      1      6.0000      3.0000      3.0000
   3      1      1.0000      4.0000      2.0000
   4      1      4.5000      5.5000      5.0000
   5      0      0.0000      0.0000      0.0000
   6      1      2.0000      2.0000      4.0000
   7      1      4.5000      5.5000      6.0000
   8      0      0.0000      0.0000      0.0000
   9      0      0.0000      0.0000      0.0000

 Matrix of rank correlation coefficients:
 Upper triangle -- Spearman's
 Lower triangle -- Kendall's tau

            1           2           3
   1      1.0000      0.2941      0.4058
   2      0.1429      1.0000      0.7537
   3      0.2760      0.5521      1.0000

 Number of cases actually used:    6


g02bqfe.r

 G02BQF Example Program Results

 Number of variables (columns) =    3
 Number of cases     (rows)    =    9

 Data matrix is:-

            1           2           3
   1      1.7000      1.0000      0.5000
   2      2.8000      4.0000      3.0000
   3      0.6000      6.0000      2.5000
   4      1.8000      9.0000      6.0000
   5      0.9900      4.0000      2.5000
   6      1.4000      2.0000      5.5000
   7      1.8000      9.0000      7.5000
   8      2.5000      7.0000      0.0000
   9      0.9900      5.0000      3.0000

 Matrix of rank correlation coefficients:
 Upper triangle -- Spearman's
 Lower triangle -- Kendall's tau

            1           2           3
   1      1.0000      0.2246      0.1186
   2      0.0294      1.0000      0.3814
   3      0.1176      0.2353      1.0000


g02brfe.r

 G02BRF Example Program Results

 Number of variables (columns) =    3
 Number of cases     (rows)    =    9

 Data matrix is:-

            1           2           3
   1      1.7000      1.0000      0.5000
   2      2.8000      4.0000      3.0000
   3      0.6000      6.0000      2.5000
   4      1.8000      9.0000      6.0000
   5      0.9900      4.0000      2.5000
   6      1.4000      2.0000      5.5000
   7      1.8000      9.0000      7.5000
   8      2.5000      7.0000      0.0000
   9      0.9900      5.0000      3.0000

 Matrix of rank correlation coefficients:
 Upper triangle -- Spearman's
 Lower triangle -- Kendall's tau

            1           2           3
   1      1.0000      0.2941      0.4058
   2      0.1429      1.0000      0.7537
   3      0.2760      0.5521      1.0000

 Number of cases actually used:    6


g02bsfe.r

 G02BSF Example Program Results

 Number of variables (columns) =    3
 Number of cases     (rows)    =    9

 Data matrix is:-

            1           2           3
   1      1.7000      1.0000      0.5000
   2      2.8000      4.0000      3.0000
   3      0.6000      6.0000      2.5000
   4      1.8000      9.0000      6.0000
   5      0.9900      4.0000      2.5000
   6      1.4000      2.0000      5.5000
   7      1.8000      9.0000      7.5000
   8      2.5000      7.0000      0.0000
   9      0.9900      5.0000      3.0000

 Matrix of rank correlation coefficients:
 Upper triangle -- Spearman's
 Lower triangle -- Kendall's tau

            1           2           3
   1      1.0000      0.1000      0.4058
   2      0.0000      1.0000      0.0896
   3      0.2760      0.0000      1.0000

 Minimum number of cases used for any pair of variables:    5

 Numbers used for each pair are:
            1           2           3
   1      7.0000      5.0000      6.0000
   2      5.0000      7.0000      6.0000
   3      6.0000      6.0000      8.0000


g02btfe.r

 G02BTF Example Program Results

 ---------------------------------------------
 Observation:    3      Weight =        0.3700
 ---------------------------------------------

 Means
         1.3299        0.3334        0.9874

 Sums of squares and cross-products
             1          2          3
 1      8.7569     3.6978     4.0707
 2                 1.5905     1.6861
 3                            1.9297

 Variance matrix
             1          2          3
 1     10.8512     4.5822     5.0443
 2                 1.9709     2.0893
 3                            2.3912


g02bufe.r

 G02BUF Example Program Results

 Means
         1.3299        0.3334        0.9874

 Weights
         0.1300        1.3070        0.3700

 Sums of squares and cross-products
             1          2          3
 1      8.7569     3.6978     4.0707
 2                 1.5905     1.6861
 3                            1.9297

 Variance matrix
             1          2          3
 1     10.8512     4.5822     5.0443
 2                 1.9709     2.0893
 3                            2.3912


g02bwfe.r

 G02BWF Example Program Results

 Correlation matrix
          1       2       3
 1   1.0000  0.9908  0.9903
 2           1.0000  0.9624
 3                   1.0000


g02bxfe.r

 G02BXF Example Program Results

      Means

       11.0810      48.7900       7.2545       2.0038      14.6190

      Standard deviations

        0.2132       0.9002       0.2349       0.0902       1.0249

      Correlation matrix
          1       2       3       4       5
 1   1.0000  0.4416 -0.5427  0.0696  0.3912
 2           1.0000 -0.5058 -0.0678  0.7057
 3                   1.0000  0.2768 -0.4352
 4                           1.0000 -0.1494
 5                                   1.0000


g02byfe.r

 G02BYF Example Program Results

 Correlation matrix
          1       2       3
 1   1.0000  0.7560  0.8309
 2           1.0000  0.9876
 3                   1.0000

 Partial Correlation matrix
          1       2
 1   1.0000 -0.7381
 2           1.0000


g02bzfe.r

 G02BZF Example Program Results

 Means
         0.4369        0.4929       -1.3387       -0.5684        0.0987

 Sums of squares and cross-products
             1          2          3          4          5
 1    304.5052  -123.7700   -27.1830   -60.7092    83.4830
 2               298.9148   -17.3196    -2.1710     5.2072
 3                          332.1639    -3.9445   -96.9299
 4                                     264.7684    79.6211
 5                                                225.5948

 Covariance matrix
             1          2          3          4          5
 1     17.1746    -6.9808    -1.5332    -3.4241     4.7086
 2                16.8593    -0.9769    -0.1224     0.2937
 3                           18.7346    -0.2225    -5.4670
 4                                      14.9334     4.4908
 5                                                 12.7239


g02cafe.r

 G02CAF Example Program Results

  Case     Independent     Dependent
 number     variable       variable

    1         1.0000        20.0000
    2         0.0000        15.5000
    3         4.0000        28.3000
    4         7.5000        45.0000
    5         2.5000        24.5000
    6         0.0000        10.0000
    7        10.0000        99.0000
    8         5.0000        31.2000

 Mean of independent variable               =   3.7500
 Mean of   dependent variable               =  34.1875
 Standard deviation of independent variable =   3.6253
 Standard deviation of   dependent variable =  28.2604
 Correlation coefficient                    =   0.9096

 Regression coefficient                     =   7.0905
 Standard error of coefficient              =   1.3224
 t-value for coefficient                    =   5.3620

 Regression constant                        =   7.5982
 Standard error of constant                 =   6.6858
 t-value for constant                       =   1.1365

 Analysis of regression table :-

       Source        Sum of squares  D.F.    Mean square     F-value

 Due to regression      4625.303      1.      4625.303        28.751
 About  regression       965.245      6.       160.874
 Total                  5590.549      7.


g02cbfe.r

 G02CBF Example Program Results

  Case     Independent     Dependent
 number     variable       variable

    1         1.0000        20.0000
    2         0.0000        15.5000
    3         4.0000        28.3000
    4         7.5000        45.0000
    5         2.5000        24.5000
    6         0.0000        10.0000
    7        10.0000        99.0000
    8         5.0000        31.2000

 Mean of independent variable               =   3.7500
 Mean of   dependent variable               =  34.1875
 Standard deviation of independent variable =   3.6253
 Standard deviation of   dependent variable =  28.2604
 Correlation coefficient                    =   0.9096

 Regression coefficient                     =   8.2051
 Standard error of coefficient              =   0.9052
 t-value for coefficient                    =   9.0642

 Analysis of regression table :-

       Source        Sum of squares  D.F.    Mean square     F-value

 Due to regression    13767.8054      1.    13767.8054       82.1591
 About  regression     1173.0246      7.      167.5749
 Total                14940.8300      8.


g02ccfe.r

 G02CCF Example Program Results

  Case     Independent     Dependent
 number     variable       variable

    1         1.0000        20.0000
    2         0.0000        15.5000
    3         4.0000        28.3000
    4         7.5000        45.0000
    5         2.5000        24.5000
    6         0.0000        10.0000
    7        10.0000        99.0000
    8         5.0000        31.2000

 Mean of independent variable               =   4.0000
 Mean of   dependent variable               =  29.8000
 Standard deviation of independent variable =   2.4749
 Standard deviation of   dependent variable =   9.4787
 Correlation coefficient                    =   0.9799

 Regression coefficient                     =   3.7531
 Standard error of coefficient              =   0.4409
 t-value for coefficient                    =   8.5128

 Regression constant                        =  14.7878
 Standard error of constant                 =   2.0155
 t-value for constant                       =   7.3370

 Analysis of regression table :-

       Source        Sum of squares  D.F.    Mean square     F-value

 Due to regression      345.0940      1.      345.0940       72.4682
 About  regression       14.2860      3.        4.7620
 Total                  359.3800      4.

 Number of cases used =  5.


g02cdfe.r

 G02CDF Example Program Results

  Case     Independent     Dependent
 number     variable       variable

    1         1.0000        20.0000
    2         0.0000        15.5000
    3         4.0000        28.3000
    4         7.5000        45.0000
    5         2.5000        24.5000
    6         0.0000        10.0000
    7        10.0000        99.0000
    8         5.0000        31.2000

 Mean of independent variable               =   4.0000
 Mean of   dependent variable               =  29.8000
 Standard deviation of independent variable =   2.4749
 Standard deviation of   dependent variable =   9.4787
 Correlation coefficient                    =   0.9799

 Regression coefficient                     =   6.5833
 Standard error of coefficient              =   0.8046
 t-value for coefficient                    =   8.1816

 Analysis of regression table :-

       Source        Sum of squares  D.F.    Mean square     F-value

 Due to regression     4528.9493      1.     4528.9493       66.9392
 About  regression      270.6307      4.       67.6577
 Total                 4799.5800      5.

 Number of cases used =  5.


g02cffe.r

 G02CFF Example Program Results

 Original vector XBAR :        5.4000     5.8000     2.8000

 Original vector STD  :        4.9800     5.0695     1.9240

 Original matrix SSP  :
             1          2          3
 1     99.2000   -57.6000     6.4000
 2    -57.6000   102.8000   -29.2000
 3      6.4000   -29.2000    14.8000

 Original matrix R    :
          1       2       3
 1   1.0000 -0.5704  0.1670
 2  -0.5704  1.0000 -0.7486
 3   0.1670 -0.7486  1.0000

 New vector XBAR :        5.4000     2.8000     5.8000

 New vector STD  :        4.9800     1.9240     5.0695

 New matrix SSP  :
             1          2          3
 1     99.2000     6.4000   -57.6000
 2      6.4000    14.8000   -29.2000
 3    -57.6000   -29.2000   102.8000

 New matrix R    :
          1       2       3
 1   1.0000  0.1670 -0.5704
 2   0.1670  1.0000 -0.7486
 3  -0.5704 -0.7486  1.0000


g02cgfe.r

 G02CGF Example Program Results

 Means:
    1    5.4000
    2    5.8000
    3    2.8000

 Sums of squares and cross-products about means:
          1         2         3
    1   99.2000  -57.6000    6.4000
    2  -57.6000  102.8000  -29.2000
    3    6.4000  -29.2000   14.8000

 Correlation coefficients:
          1         2         3
    1    1.0000   -0.5704    0.1670
    2   -0.5704    1.0000   -0.7486
    3    0.1670   -0.7486    1.0000

 Vble     Coef       Std err      t-value
   1     -0.1488      0.1937     -0.7683
   2     -0.3674      0.1903     -1.9309

 Const     5.7350       2.0327       2.8213

 Analysis of regression table :-

       Source        Sum of squares  D.F.    Mean square     F-value

 Due to regression        9.7769      2.        4.8884        1.9464
 About  regression        5.0231      2.        2.5116
 Total                   14.8000      4.

 Standard error of estimate =  1.5848
 Multiple correlation (R)   =  0.8128
 Determination (R squared)  =  0.6606
 Corrected R squared        =  0.3212

 Inverse of correlation matrix of independent variables:
          1         2
    1    1.4823    0.8455
    2    0.8455    1.4823

 Modified inverse matrix:
          1         2
    1    0.0149    0.0084
    2    0.0084    0.0144


g02chfe.r

 G02CHF Example Program Results

 Sums of squares and cross-products about zero:
          1         2         3
    1  245.0000   99.0000   82.0000
    2   99.0000  271.0000   52.0000
    3   82.0000   52.0000   54.0000

 Correlation-like coefficients:
          1         2         3
    1    1.0000    0.3842    0.7129
    2    0.3842    1.0000    0.4299
    3    0.7129    0.4299    1.0000

 Vble     Coef       Std err      t-value
   1      0.3017      0.1998      1.5098
   2      0.0817      0.1900      0.4299

 Analysis of regression table :-

       Source        Sum of squares  D.F.    Mean square     F-value

 Due to regression       28.9857      2.       14.4929        1.7382
 About  regression       25.0143      3.        8.3381
 Total                   54.0000      5.

 Standard error of estimate =  2.8876
 Multiple correlation (R)   =  0.7326
 Determination (R squared)  =  0.5368
 Corrected R squared        =  0.2280

 Inverse of correlation matrix of independent variables:
          1         2
    1    1.1732   -0.4507
    2   -0.4507    1.1732

 Modified inverse matrix:
          1         2
    1    0.0048   -0.0017
    2   -0.0017    0.0043


g02dafe.r

 G02DAF Example Program Results

 Model not of full rank, rank =    4

 Residual sum of squares =   0.2223E+02
 Degrees of freedom      =    8
 R-squared               =   0.7004E+00
 Adjusted R-squared      =   0.5881E+00
 AIC                     =   0.1540E+02

 Variable   Parameter estimate   Standard error

      1          0.3056E+02          0.3849E+00
      2          0.5447E+01          0.8390E+00
      3          0.6743E+01          0.8390E+00
      4          0.1105E+02          0.8390E+00
      5          0.7320E+01          0.8390E+00

    Obs          Residuals              H

      1         -0.2373E+01          0.3333E+00
      2          0.1743E+01          0.3333E+00
      3          0.8800E+00          0.3333E+00
      4         -0.1433E+00          0.3333E+00
      5          0.1433E+00          0.3333E+00
      6         -0.1470E+01          0.3333E+00
      7         -0.1887E+01          0.3333E+00
      8          0.5767E+00          0.3333E+00
      9          0.1317E+01          0.3333E+00
     10          0.1797E+01          0.3333E+00
     11         -0.1173E+01          0.3333E+00
     12          0.5900E+00          0.3333E+00


g02dcfe.r

 G02DCF Example Program Results

 Results from initial model fit using G02DAF
 Residual sum of squares =   0.5275E+04
 Degrees of freedom =    8

 Variable   Parameter estimate   Standard error

      1          0.2072E+02          0.1380E+02
      2          0.1409E+02          0.1624E+02
      3          0.2632E+02          0.1380E+02
      4          0.2260E+02          0.1380E+02

 Results from dropping an observation using G02DCF
 Residual sum of squares =   0.2170E+02
 Degrees of freedom =    7

 Variable   Parameter estimate   Standard error

      1          0.3600E+02          0.1017E+01
      2          0.3701E+02          0.1245E+01
      3          0.4160E+02          0.1017E+01
      4          0.3788E+02          0.1017E+01

 Results from adding an observation using G02DCF
 Residual sum of squares =   0.2223E+02
 Degrees of freedom =    8

 Variable   Parameter estimate   Standard error

      1          0.3600E+02          0.9623E+00
      2          0.3730E+02          0.9623E+00
      3          0.4160E+02          0.9623E+00
      4          0.3788E+02          0.9623E+00


g02ddfe.r

 G02DDF Example Program Results

 Residual sum of squares =   0.2223E+02
 Degrees of freedom =    8

 Variable   Parameter estimate   Standard error

      1          0.3600E+02          0.9623E+00
      2          0.3730E+02          0.9623E+00
      3          0.4160E+02          0.9623E+00
      4          0.3788E+02          0.9623E+00


g02defe.r

 G02DEF Example Program Results

 Variable 1 added
 Residual sum of squares =    0.3627E+02
 Degrees of freedom = 11

 Variable   Parameter estimate   Standard error

      1          0.7972E+01          0.5242E+00

 Variable 2 added
 Residual sum of squares =    0.4016E+01
 Degrees of freedom = 10

 Variable   Parameter estimate   Standard error

      1          0.4410E+01          0.4376E+00
      2          0.9498E+00          0.1060E+00

 Variable 3 added
 Residual sum of squares =    0.3887E+01
 Degrees of freedom = 9

 Variable   Parameter estimate   Standard error

      1          0.4224E+01          0.5673E+00
      2          0.1055E+01          0.2222E+00
      3         -0.4196E+00          0.7670E+00

 Variable 4 added
 Residual sum of squares =    0.1870E+00
 Degrees of freedom = 8

 Variable   Parameter estimate   Standard error

      1          0.2760E+01          0.1759E+00
      2          0.1706E+01          0.7310E-01
      3          0.4458E+01          0.4268E+00
      4         -0.1301E+01          0.1034E+00

 Variable 5 added
 Residual sum of squares =    0.8407E-01
 Degrees of freedom = 7

 Variable   Parameter estimate   Standard error

      1          0.3144E+01          0.1818E+00
      2          0.9075E+00          0.2776E+00
      3          0.2079E+01          0.8680E+00
      4         -0.6159E+00          0.2453E+00
      5          0.2922E+00          0.9981E-01


g02dffe.r

 G02DFF Example Program Results

 Results from full model
 Residual sum of squares =    0.8407E-01
 Degrees of freedom =    7

 Variable   2 dropped
 Residual sum of squares =    0.2124E+00
 Degrees of freedom =    8

 Parameter estimate   Standard error

      0.3637E+01          0.1508E+00
      0.6126E+00          0.2801E-01
     -0.6015E+00          0.4234E+00
      0.1671E+00          0.7866E-01
 Variable   4 dropped
 Residual sum of squares =    0.3322E+00
 Degrees of freedom =    9

 Parameter estimate   Standard error

      0.3597E+01          0.1765E+00
      0.6209E+00          0.3271E-01
      0.2425E+00          0.1724E+00


g02dgfe.r

 G02DGF Example Program Results

 Results for original y-variable using G02DAF

 Model not of full rank

 Residual sum of squares =   0.2223E+02
 Degrees of freedom =    8

 Variable   Parameter estimate   Standard error

      1          0.3056E+02          0.3849E+00
      2          0.5447E+01          0.8390E+00
      3          0.6743E+01          0.8390E+00
      4          0.1105E+02          0.8390E+00
      5          0.7320E+01          0.8390E+00

 Results for second y-variable using G02DGF

 Residual sum of squares =   0.2400E+02
 Degrees of freedom =    8

 Variable   Parameter estimate   Standard error

      1          0.5407E+02          0.4000E+00
      2          0.1127E+02          0.8718E+00
      3          0.1260E+02          0.8718E+00
      4          0.1693E+02          0.8718E+00
      5          0.1327E+02          0.8718E+00


g02dkfe.r

 G02DKF Example Program Results

 Estimates from G02DAF

 Residual sum of squares =     0.222E+02
 Degrees of freedom =    8

 Variable    Parameter estimate   Standard error

      1           0.306E+02           0.385E+00
      2           0.545E+01           0.839E+00
      3           0.674E+01           0.839E+00
      4           0.110E+02           0.839E+00
      5           0.732E+01           0.839E+00

 Estimates from G02DKF using constraints

 Variable    Parameter estimate   Standard error

      1           0.382E+02           0.481E+00
      2          -0.219E+01           0.833E+00
      3          -0.896E+00           0.833E+00
      4           0.341E+01           0.833E+00
      5          -0.319E+00           0.833E+00


g02dnfe.r

 G02DNF Example Program Results

 Estimates from G02DAF

 Residual sum of squares =   0.2223E+02
 Degrees of freedom =    8

 Variable   Parameter estimate   Standard error

      1          0.3056E+02          0.3849E+00
      2          0.5447E+01          0.8390E+00
      3          0.6743E+01          0.8390E+00
      4          0.1105E+02          0.8390E+00
      5          0.7320E+01          0.8390E+00

 Function    1

     1.00    1.00    0.00    0.00    0.00

 STAT =    36.0033 SE =     0.9623 T =    37.4119

 Function    2

     0.00    1.00   -1.00    0.00    0.00

 STAT =    -1.2967 SE =     1.3610 T =    -0.9528

 Function    3

     0.00    1.00    0.00    0.00    0.00

 Function not estimable


g02eafe.r

 G02EAF Example Program Results

 Number of     RSS    RANK  MODL
 parameters
        0     5.0634  32
        1     5.0219  31    TKN
        1     2.5044  30    TVS
        1     2.0338  28    BOD
        1     1.5563  25    COD
        1     1.5370  24    TS
        2     2.4381  29    TKN TVS
        2     1.7462  27    BOD TVS
        2     1.5921  26    BOD TKN
        2     1.4963  23    BOD COD
        2     1.4707  22    TKN TS
        2     1.4590  21    TS  TVS
        2     1.4397  20    BOD TS
        2     1.4388  19    TKN COD
        2     1.3287  15    TVS COD
        2     1.0850   8    TS  COD
        3     1.4257  18    BOD TKN TVS
        3     1.3900  17    TKN TS  TVS
        3     1.3894  16    BOD TS  TVS
        3     1.3204  14    BOD TVS COD
        3     1.2764  13    BOD TKN COD
        3     1.2582  12    BOD TKN TS
        3     1.2179  10    TKN TVS COD
        3     1.0644   7    BOD TS  COD
        3     1.0634   6    TS  TVS COD
        3     0.9871   4    TKN TS  COD
        4     1.2199  11    BOD TKN TS  TVS
        4     1.1565   9    BOD TKN TVS COD
        4     1.0388   5    BOD TS  TVS COD
        4     0.9871   3    BOD TKN TS  COD
        4     0.9653   2    TKN TS  TVS COD
        5     0.9652   1    BOD TKN TS  TVS COD


g02ecfe.r

 G02ECF Example Program Results

 Number of     CP      RSQ         MODEL
 parameters

       0      55.45  0.0000
       1      56.84  0.0082  TKN
       1      20.33  0.5054  TVS
       1      13.50  0.5983  BOD
       1       6.57  0.6926  COD
       1       6.29  0.6965  TS
       2      21.36  0.5185  TKN TVS
       2      11.33  0.6551  BOD TVS
       2       9.09  0.6856  BOD TKN
       2       7.70  0.7045  BOD COD
       2       7.33  0.7095  TKN TS
       2       7.16  0.7119  TS  TVS
       2       6.88  0.7157  BOD TS
       2       6.87  0.7158  TKN COD
       2       5.27  0.7376  TVS COD
       2       1.74  0.7857  TS  COD
       3       8.68  0.7184  BOD TKN TVS
       3       8.16  0.7255  TKN TS  TVS
       3       8.15  0.7256  BOD TS  TVS
       3       7.15  0.7392  BOD TVS COD
       3       6.51  0.7479  BOD TKN COD
       3       6.25  0.7515  BOD TKN TS
       3       5.67  0.7595  TKN TVS COD
       3       3.44  0.7898  BOD TS  COD
       3       3.42  0.7900  TS  TVS COD
       3       2.32  0.8050  TKN TS  COD
       4       7.70  0.7591  BOD TKN TS  TVS
       4       6.78  0.7716  BOD TKN TVS COD
       4       5.07  0.7948  BOD TS  TVS COD
       4       4.32  0.8050  BOD TKN TS  COD
       4       4.00  0.8094  TKN TS  TVS COD
       5       6.00  0.8094  BOD TKN TS  TVS COD


g02eefe.r

 G02EEF Example Program Results

 Step  1
 Added variable is TS
 Change in residual sum of squares =   0.4713E+00
 F Statistic =    7.38

 Variables in model: COD TS

 Residual sum of squares =    0.1085E+01
 Degrees of freedom = 17

 Free variables:        TKN      BOD      TVS
 Change in residual sums of squares for free variables:
                     0.1175   0.0600   0.2276

 Step  2
 No further variables added maximum F =   1.59
 Free variables:        TKN      BOD      TVS
 Change in residual sums of squares for free variables:
                     0.0979   0.0207   0.0217


g02effe.r

 G02EFF Example Program Results

 Starting Stepwise Selection

 Forward Selection
 Variable    1 Variance ratio =    1.260E+01
 Variable    2 Variance ratio =    2.196E+01
 Variable    3 Variance ratio =    4.403E+00
 Variable    4 Variance ratio =    2.280E+01

 Adding variable    4 to model

 Backward Selection
 Variable    4 Variance ratio =    2.280E+01

 Keeping all current variables

 Forward Selection
 Variable    1 Variance ratio =    1.082E+02
 Variable    2 Variance ratio =    1.725E-01
 Variable    3 Variance ratio =    4.029E+01

 Adding variable    1 to model

 Backward Selection
 Variable    1 Variance ratio =    1.082E+02
 Variable    4 Variance ratio =    1.593E+02

 Keeping all current variables

 Forward Selection
 Variable    2 Variance ratio =    5.026E+00
 Variable    3 Variance ratio =    4.236E+00

 Adding variable    2 to model

 Backward Selection
 Variable    1 Variance ratio =    1.540E+02
 Variable    2 Variance ratio =    5.026E+00
 Variable    4 Variance ratio =    1.863E+00

 Dropping variable    4 from model

 Forward Selection
 Variable    3 Variance ratio =    1.832E+00
 Variable    4 Variance ratio =    1.863E+00

 Finished Stepwise Selection

 Fitted Model Summary
 Term              Estimate   Standard Error
 Intercept:       5.258E+01        2.294E+00
 Variable:   1    1.468E+00        1.213E-01
 Variable:   2    6.623E-01        4.585E-02

 RMS:    5.790E+00


g02fafe.r

 G02FAF Example Program Results

         Internally    Internally
 Obs.   standardized  standardized   Cook's D   Atkinson's T
          residuals     residuals

  1        0.522        0.507        0.030        0.611
  2       -1.143       -1.158        4.557       -7.797
  3       -0.638       -0.622        0.062       -0.875
  4        0.940        0.935        0.037        0.689
  5       -0.686       -0.672        0.030       -0.610
  6        0.300        0.289        0.014        0.408
  7       -2.573       -3.529        0.729       -4.223
  8        1.683        1.828        0.078        1.094
  9        0.055        0.053        0.000        0.048
 10       -1.165       -1.183        0.069       -0.960


g02fcfe.r

 G02FCF Example Program Results

  Durbin-Watson statistic     0.9238

  Lower and upper bound     0.0610    0.0060


g02gafe.r

 G02GAF Example Program Results

 Residual sum of squares     =   0.3872E+00
  Residual degrees of freedom =  3

       Estimate    Standard error

        -0.0239        0.0028
         0.0638        0.0026

      Y        FV     Residual       H

    25.0     25.04     -0.0387     0.995
    10.0      9.64      0.3613     0.458
     6.0      5.97      0.0320     0.268
     4.0      4.32     -0.3221     0.167
     3.0      3.39     -0.3878     0.112


g02gbfe.r

 G02GBF Example Program Results

 Deviance =   0.7354E-01
 Degrees of freedom = 1

        Estimate     Standard error

        -2.8682        0.1217
        -0.4264        0.1598

        N          Y        FV      Residual      H

      516.0      19.0     18.45      0.1296     0.769
      560.0      29.0     30.10     -0.2070     0.422
      293.0      24.0     23.45      0.1178     0.809


g02gdfe.r

 G02GDF Example Program Results

 Deviance =   0.3503E+02
 Degrees of freedom = 8

      Estimate     Standard error

         1.4408        0.6678
        -1.2865        0.6717

      Y        FV     Residual        H

     1.0      6.48     -1.3909     0.200
     0.3      6.48     -1.9228     0.200
    10.5      6.48      0.5236     0.200
     9.7      6.48      0.4318     0.200
    10.9      6.48      0.5678     0.200
     0.6      0.69     -0.1107     0.200
     0.1      0.69     -1.3287     0.200
     0.1      0.69     -1.4815     0.200
     0.5      0.69     -0.3106     0.200
     2.1      0.69      1.3665     0.200


g02gkfe.r

 G02GKF Example Program Results

 Deviance =   0.9038E+01
 Degrees of freedom =  8

       Estimate     Standard error

         3.9831        0.0396
         0.3961        0.0458
         0.4118        0.0457
        -0.8079        0.0622
         0.5112        0.0562
        -0.2285        0.0727
         0.4680        0.0569
        -0.0316        0.0675
        -0.7191        0.0887


g02gnfe.r

 G02GNF Example Program Results

 Deviance =   0.9038E+01
 Degrees of freedom =  8

       Estimate     Standard error

         2.5977        0.0258
         1.2619        0.0438
         1.2777        0.0436
         0.0580        0.0668
         1.0307        0.0551
         0.2910        0.0732
         0.9876        0.0559
         0.4880        0.0675
        -0.1996        0.0904

 Function    1
     1.00    1.00    0.00    0.00    1.00
     0.00    0.00    0.00    0.00

 STAT =     4.8903 SE =     0.0674 Z =    72.5934

 Function    2
     0.00    1.00   -1.00    0.00    0.00
     0.00    0.00    0.00    0.00

 STAT =    -0.0158 SE =     0.0672 Z =    -0.2350

 Function    3
     0.00    1.00    0.00    0.00    0.00
     0.00    0.00    0.00    0.00

 Function not estimable


g02gpfe.r

 G02GPF Example Program Results

 Residual sum of squares =   0.3872E+00
 Degrees of freedom      = 3

       Estimate     Standard error

        -0.0239        0.0028
         0.0638        0.0026

   I      ETA         SE(ETA)      Predicted   SE(Predicted)

   1)   2.01807       0.08168       0.49552       0.35981
   2)   1.12472       0.04476       0.88911       0.36098


g02hafe.r

 G02HAF Example Program Results

 Sigma =     0.2026

        THETA      Standard
                    errors
       4.0423       0.0384
       1.3083       0.0272
       0.7519       0.0311

      Weights     Residuals
       0.5783       0.1179
       0.5783       0.1141
       0.5783      -0.0987
       0.5783      -0.0026
       0.4603      -0.1256
       0.4603      -0.6385
       0.4603       0.0410
       0.4603      -0.0462


g02hbfe.r

 G02HBF Example Program Results

 G02HBF required 16 iterations to converge

 Matrix A
               1            2            3
 1    1.3208E+00
 2    1.7023E-17  -5.7532E-01
 3    1.4518E+00   2.7351E-17   9.3403E-01

 Vector Z
    2.4760
    1.9953
    2.4760
    1.9953
    2.5890

 Vector of Krasker-Welsch weights
    0.4039
    0.5012
    0.4039
    0.5012
    0.3862


g02hdfe.r

 G02HDF Example Program Results

 G02HDF required 5 iterations to converge
                    K = 3
                Sigma =    2.7783
     THETA
   12.2321
    1.0500
    1.2464

   Weights  Residuals
    0.4039   0.5643
    0.5012  -1.1286
    0.4039   0.5643
    0.5012  -1.1286
    0.3862   1.1286


g02hffe.r

 G02HFF Example Program Results

 Covariance matrix
          1       2       3
 1   0.2070  0.0000 -0.0478
 2   0.0000  0.2229  0.0000
 3  -0.0478  0.0000  0.0796


g02hkfe.r

 G02HKF Example Program Results

 G02HKF required 23 iterations to converge

 Covariance matrix
             1          2          3
 1      3.4611    -3.6806     4.6818
 2                 5.3477    -6.6445
 3                           14.4389

 THETA
      5.818
      3.681
     15.037


g02hlfe.r

 G02HLF Example Program Results

 G02HLF required 25 iterations to converge

 Robust covariance matrix
             1          2          3
 1      3.2778    -3.6918     4.7391
 2                 5.2841    -6.4086
 3                           11.8371

 Robust estimates of THETA
      5.700
      3.864
     14.704


g02hmfe.r

 G02HMF Example Program Results

 G02HMF required 34 iterations to converge

 Robust covariance matrix
             1          2          3
 1      3.2779    -3.6918     4.7391
 2                 5.2841    -6.4087
 3                           11.8373

 Robust estimates of THETA
      5.700
      3.864
     14.704


g02jafe.r

 G02JAF Example Program Results

 Fixed effects (Estimate and Standard Deviation)

 Intercept                37.0000    4.6674
 Variable   1 Level   2    1.0000    3.5173
 Variable   1 Level   3  -11.0000    3.5173
 Variable   2 Level   2   -8.2500    2.1635
 Variable   3 Level   2    0.5000    3.0596
 Variable   3 Level   3    7.7500    3.0596

 Random Effects (Estimate and Standard Deviation)

 Intercept for Subject Level   1            10.7631    4.4865
 Subject Level   1 Variable   1 Level   1    3.7276    3.0331
 Subject Level   1 Variable   1 Level   2   -1.4476    3.0331
 Subject Level   1 Variable   1 Level   3    0.3733    3.0331
 Intercept for Subject Level   2            -0.5269    4.4865
 Subject Level   2 Variable   1 Level   1   -3.7171    3.0331
 Subject Level   2 Variable   1 Level   2   -1.2253    3.0331
 Subject Level   2 Variable   1 Level   3    4.8125    3.0331
 Intercept for Subject Level   3            -5.6450    4.4865
 Subject Level   3 Variable   1 Level   1    0.5903    3.0331
 Subject Level   3 Variable   1 Level   2    0.3987    3.0331
 Subject Level   3 Variable   1 Level   3   -2.3806    3.0331
 Intercept for Subject Level   4            -4.5912    4.4865
 Subject Level   4 Variable   1 Level   1   -0.6009    3.0331
 Subject Level   4 Variable   1 Level   2    2.2742    3.0331
 Subject Level   4 Variable   1 Level   3   -2.8052    3.0331

  Variance Components
    1   62.3958
    2   15.3819

 SIGMA^2     =     9.3611
 -2LOG LIKE  =   119.7618
 DF          =               16


g02jbfe.r

 G02JBF Example Program Results

 Fixed effects (Estimate and Standard Deviation)

 Intercept                37.0000    4.0421
 Variable   1 Level   2    1.0000    3.0461
 Variable   1 Level   3  -11.0000    3.0461
 Variable   2 Level   2   -8.2500    1.8736
 Variable   3 Level   2    0.5000    2.6497
 Variable   3 Level   3    7.7500    2.6497

 Random Effects (Estimate and Standard Deviation)

 Intercept for Subject Level   1            10.7631    3.8855
 Subject Level   1 Variable   1 Level   1    3.7276    2.6268
 Subject Level   1 Variable   1 Level   2   -1.4476    2.6268
 Subject Level   1 Variable   1 Level   3    0.3733    2.6268
 Intercept for Subject Level   2            -0.5269    3.8855
 Subject Level   2 Variable   1 Level   1   -3.7171    2.6268
 Subject Level   2 Variable   1 Level   2   -1.2253    2.6268
 Subject Level   2 Variable   1 Level   3    4.8125    2.6268
 Intercept for Subject Level   3            -5.6450    3.8855
 Subject Level   3 Variable   1 Level   1    0.5903    2.6268
 Subject Level   3 Variable   1 Level   2    0.3987    2.6268
 Subject Level   3 Variable   1 Level   3   -2.3806    2.6268
 Intercept for Subject Level   4            -4.5912    3.8855
 Subject Level   4 Variable   1 Level   1   -0.6009    2.6268
 Subject Level   4 Variable   1 Level   2    2.2742    2.6268
 Subject Level   4 Variable   1 Level   3   -2.8052    2.6268

  Variance Components
    1   46.7969
    2   11.5365

 SIGMA^2     =     7.0208
 -2LOG LIKE  =   141.6877
 DF          =               16


g02jdfe.r

 G02JDF Example Program Results

 Number of observations (N)                    =  90
 Number of random factors (NRF)                =  55
 Number of fixed factors (NFF)                 =  4
 Number of subject levels (NLSV)               =  3
 Rank of X (RNKX)                              =  4
 Effective N (EFFN)                            =  90
 Number of nonzero variance components (NCOV) =  7
 Parameter Estimates

 Random Effects
  Subject: Variable 10 (Level  1) Variable 11 (Level  1) Variable 12 (Level  1)
     Variable  3 (Level  1)         2.1561     3.7946
     Variable  3 (Level  2)         1.8951     3.9284
     Variable  4 (Level  1)         0.6496     3.1617

  Subject: Variable 10 (Level  1) Variable 11 (Level  1) Variable 12 (Level  1)
     Variable  4 (Level  3)         0.7390     3.1424

  Subject: Variable 10 (Level  2) Variable 11 (Level  1) Variable 12 (Level  1)
     Variable  3 (Level  1)         1.4216     3.3773
     Variable  3 (Level  2)        -2.8921     3.3953
     Variable  4 (Level  1)         3.6789     2.3162
     Variable  4 (Level  2)        -1.9742     2.3887
     Variable  4 (Level  3)        -2.2088     2.0697

  Subject: Variable 10 (Level  1) Variable 11 (Level  2) Variable 12 (Level  1)
     Variable  3 (Level  1)        -2.9659     3.9127
     Variable  3 (Level  2)         2.7951     4.7183
     Variable  4 (Level  1)        -4.7330     2.3094
     Variable  4 (Level  2)         5.5161     2.2330
     Variable  4 (Level  3)        -0.8417     2.3826

  Subject: Variable 10 (Level  2) Variable 11 (Level  2) Variable 12 (Level  1)
     Variable  3 (Level  1)         4.2202     3.6675
     Variable  3 (Level  2)        -4.3883     3.4424
     Variable  4 (Level  1)        -1.1391     3.2187
     Variable  4 (Level  2)         1.0814     3.0654

  Subject: Variable 10 (Level  1) Variable 11 (Level  3) Variable 12 (Level  1)
     Variable  3 (Level  1)         0.3391     4.0647
     Variable  3 (Level  2)         0.1502     3.4787
     Variable  4 (Level  1)        -1.0026     2.4363

  Subject: Variable 10 (Level  1) Variable 11 (Level  3) Variable 12 (Level  1)
     Variable  4 (Level  3)         1.1703     2.6365

  Subject: Variable 10 (Level  2) Variable 11 (Level  3) Variable 12 (Level  1)
     Variable  3 (Level  1)         1.2658     3.4819
     Variable  3 (Level  2)        -1.5356     3.9097

  Subject: Variable 10 (Level  2) Variable 11 (Level  3) Variable 12 (Level  1)
     Variable  4 (Level  2)         0.7992     2.7902
     Variable  4 (Level  3)        -0.8916     2.8763

  Subject: Variable 11 (Level  1) Variable 12 (Level  1)
     Variable  5 (Level  1)        -0.4885     2.8206
     Variable  5 (Level  2)         1.8829     2.7530
     Variable  6 (Level  1)         0.9249     3.7747
     Variable  6 (Level  2)        -2.3568     3.1624
     Variable  6 (Level  3)         4.3117     3.1474

  Subject: Variable 11 (Level  2) Variable 12 (Level  1)
     Variable  5 (Level  1)         1.3898     2.9362
     Variable  5 (Level  2)        -1.5729     2.8909
     Variable  6 (Level  1)         0.2111     3.9967
     Variable  6 (Level  2)        -3.7083     4.2866
     Variable  6 (Level  3)         3.1190     4.7983

  Subject: Variable 11 (Level  3) Variable 12 (Level  1)
     Variable  5 (Level  1)         1.7352     3.1370
     Variable  5 (Level  2)        -1.6165     3.1713
     Variable  6 (Level  1)        -1.1102     3.9374
     Variable  6 (Level  2)         4.4877     3.6980
     Variable  6 (Level  3)        -3.1325     3.1966

  Subject: Variable 12 (Level  1)
     Variable  7                    0.6827     0.5060
     Variable  8 (Level  1)         1.5964     1.3206
     Variable  8 (Level  2)        -0.7533     1.5663
     Variable  8 (Level  3)         0.4035     1.6840
     Variable  8 (Level  4)        -0.8523     1.7518
     Variable  9 (Level  1)         0.5699     1.6236
     Variable  9 (Level  2)         0.0012     1.9111
     Variable  9 (Level  3)        -0.2850     1.9245
     Variable  9 (Level  4)         0.4468     2.0329
     Variable  9 (Level  5)         0.0030     2.1390

  Subject: Variable 10 (Level  1) Variable 11 (Level  1) Variable 12 (Level  2)
     Variable  3 (Level  1)         6.2551     3.3595
     Variable  3 (Level  2)         5.6085     3.4127

  Subject: Variable 10 (Level  1) Variable 11 (Level  1) Variable 12 (Level  2)
     Variable  4 (Level  2)         2.6922     2.7542
     Variable  4 (Level  3)         1.3742     2.8068

  Subject: Variable 10 (Level  2) Variable 11 (Level  1) Variable 12 (Level  2)
     Variable  3 (Level  1)         1.5647     3.8353
     Variable  3 (Level  2)        -2.7565     3.9041
     Variable  4 (Level  1)        -0.8621     2.8257

  Subject: Variable 10 (Level  2) Variable 11 (Level  1) Variable 12 (Level  2)
     Variable  4 (Level  3)         0.4536     2.8070

  Subject: Variable 10 (Level  1) Variable 11 (Level  2) Variable 12 (Level  2)
     Variable  3 (Level  1)       -10.1544     3.3433
     Variable  3 (Level  2)         3.2446     4.1221
     Variable  4 (Level  1)        -2.9419     2.3508
     Variable  4 (Level  2)         0.2510     3.0675
     Variable  4 (Level  3)         0.3224     2.9710

  Subject: Variable 10 (Level  2) Variable 11 (Level  2) Variable 12 (Level  2)
     Variable  3 (Level  1)        -1.3577     3.1925
     Variable  3 (Level  2)         8.1277     3.9975
     Variable  4 (Level  1)        -0.4290     2.4578
     Variable  4 (Level  2)         2.7495     2.5821

  Subject: Variable 10 (Level  1) Variable 11 (Level  3) Variable 12 (Level  2)
     Variable  3 (Level  1)         4.8432     4.0069
     Variable  3 (Level  2)         0.0370     3.6006
     Variable  4 (Level  1)         3.0713     2.2706
     Variable  4 (Level  2)        -1.8899     2.4756
     Variable  4 (Level  3)         0.4914     2.2914

  Subject: Variable 10 (Level  2) Variable 11 (Level  3) Variable 12 (Level  2)
     Variable  3 (Level  1)        -4.4766     3.3355
     Variable  3 (Level  2)        -3.7936     4.0759
     Variable  4 (Level  1)        -0.5459     2.7097
     Variable  4 (Level  2)        -1.5619     2.7412
     Variable  4 (Level  3)        -0.7269     2.9735

  Subject: Variable 11 (Level  1) Variable 12 (Level  2)
     Variable  5 (Level  1)         4.8653     3.0706
     Variable  5 (Level  2)         0.9011     3.0696
     Variable  6 (Level  1)         6.9277     3.8411
     Variable  6 (Level  2)        -1.3108     3.1667
     Variable  6 (Level  3)         6.2916     3.5327

  Subject: Variable 11 (Level  2) Variable 12 (Level  2)
     Variable  5 (Level  1)        -0.4047     3.0956
     Variable  5 (Level  2)         0.3291     3.0784
     Variable  6 (Level  1)         6.9096     3.3073
     Variable  6 (Level  2)        -1.0680     3.6213
     Variable  6 (Level  3)        -5.9977     3.7299

  Subject: Variable 11 (Level  3) Variable 12 (Level  2)
     Variable  5 (Level  1)        -1.0925     3.0994
     Variable  5 (Level  2)        -0.7392     2.9900
     Variable  6 (Level  1)         2.7758     3.8748
     Variable  6 (Level  2)        -6.3526     3.3014
     Variable  6 (Level  3)        -0.2060     3.6481

  Subject: Variable 12 (Level  2)
     Variable  7                    0.1711     0.5785
     Variable  8 (Level  1)         1.7186     1.9143
     Variable  8 (Level  2)        -0.6768     1.7352
     Variable  8 (Level  3)        -0.0439     1.6395
     Variable  8 (Level  4)         0.1463     1.5358
     Variable  9 (Level  1)         0.9761     2.3930
     Variable  9 (Level  2)         6.5436     1.8193
     Variable  9 (Level  3)        -1.5504     1.8527
     Variable  9 (Level  4)         0.1047     2.0244
     Variable  9 (Level  5)        -3.9386     1.7937

  Subject: Variable 10 (Level  1) Variable 11 (Level  1) Variable 12 (Level  3)
     Variable  3 (Level  1)        10.6802     3.2596
     Variable  3 (Level  2)        -1.0290     3.7842
     Variable  4 (Level  1)        -2.8612     2.2917
     Variable  4 (Level  2)         3.9265     2.8934
     Variable  4 (Level  3)         2.2427     2.3737

  Subject: Variable 10 (Level  2) Variable 11 (Level  1) Variable 12 (Level  3)
     Variable  3 (Level  1)        -6.2076     3.3642
     Variable  3 (Level  2)        -8.7670     3.8463
     Variable  4 (Level  1)        -2.9251     2.4657

  Subject: Variable 10 (Level  2) Variable 11 (Level  1) Variable 12 (Level  3)
     Variable  4 (Level  3)        -2.2077     2.3743

  Subject: Variable 10 (Level  1) Variable 11 (Level  2) Variable 12 (Level  3)
     Variable  3 (Level  1)        -3.3334     3.4665
     Variable  3 (Level  2)        -0.3111     3.2650
     Variable  4 (Level  1)         1.5131     2.4890
     Variable  4 (Level  2)        -3.0345     3.0562
     Variable  4 (Level  3)         0.2722     2.8300

  Subject: Variable 10 (Level  2) Variable 11 (Level  2) Variable 12 (Level  3)
     Variable  3 (Level  1)         6.5905     4.0386
     Variable  3 (Level  2)        -5.3168     3.4549
     Variable  4 (Level  1)        -3.5280     2.9663
     Variable  4 (Level  2)         1.7056     2.9293
     Variable  4 (Level  3)         2.2590     3.1780

  Subject: Variable 10 (Level  1) Variable 11 (Level  3) Variable 12 (Level  3)
     Variable  3 (Level  1)         8.1889     4.1429
     Variable  3 (Level  2)        -1.5388     3.3333
     Variable  4 (Level  1)         3.4338     2.6376

  Subject: Variable 10 (Level  1) Variable 11 (Level  3) Variable 12 (Level  3)
     Variable  4 (Level  3)        -1.1544     2.9885

  Subject: Variable 10 (Level  2) Variable 11 (Level  3) Variable 12 (Level  3)
     Variable  3 (Level  1)        -4.4243     4.0049
     Variable  3 (Level  2)        -4.1349     3.1248
     Variable  4 (Level  1)         1.0460     2.6550
     Variable  4 (Level  2)        -4.4844     2.2843
     Variable  4 (Level  3)         0.5046     2.6926

  Subject: Variable 11 (Level  1) Variable 12 (Level  3)
     Variable  5 (Level  1)         5.3030     3.0278
     Variable  5 (Level  2)        -8.1794     3.1335
     Variable  6 (Level  1)        -0.8188     3.7810
     Variable  6 (Level  2)        -2.5078     3.1514
     Variable  6 (Level  3)        -2.6138     3.4600

  Subject: Variable 11 (Level  2) Variable 12 (Level  3)
     Variable  5 (Level  1)         4.3331     3.1489
     Variable  5 (Level  2)        -5.6142     3.1649
     Variable  6 (Level  1)        -5.8804     3.1770
     Variable  6 (Level  2)         5.4265     3.3006
     Variable  6 (Level  3)        -2.1917     3.2156

  Subject: Variable 11 (Level  3) Variable 12 (Level  3)
     Variable  5 (Level  1)         0.4305     2.9144
     Variable  5 (Level  2)        -1.4620     3.0119
     Variable  6 (Level  1)        14.3595     3.9254
     Variable  6 (Level  2)        -5.2399     3.3099
     Variable  6 (Level  3)       -11.2498     3.2212

  Subject: Variable 12 (Level  3)
     Variable  7                   -0.3839     0.6755
     Variable  8 (Level  1)         2.7549     1.6017
     Variable  8 (Level  2)         0.4377     1.8826
     Variable  8 (Level  3)        -0.2261     1.9909
     Variable  8 (Level  4)        -4.5051     1.5398
     Variable  9 (Level  1)        -4.7091     2.1458
     Variable  9 (Level  2)         3.7940     1.9872
     Variable  9 (Level  3)        -1.7994     1.8614
     Variable  9 (Level  4)         0.4480     1.9016
     Variable  9 (Level  5)        -0.6047     2.4729

 Fixed Effects
   Intercept                        1.6433     2.4596
   Variable  1 (Level  2)          -1.6224     0.8549
   Variable  2 (Level  2)          -2.4817     1.1414
   Variable  2 (Level  3)           0.4624     1.2133

 Variance Components
  Estimate      Parameter        Subject
   36.32491      Variable  3     Variables 10 11 12
   12.45090      Variable  4     Variables 10 11 12
   19.62767      Variable  5     Variables 11 12
   40.53480      Variable  6     Variables 11 12
    0.56320      Variable  7     Variables 12
    5.81968      Variable  8     Variables 12
   10.86069      Variable  9     Variables 12

 SIGMA**2         =         0.00239
 -2LOG LIKELIHOOD =       608.19449


g02jefe.r

 G02JEF Example Program Results

 Number of observations (N)                    =  90
 Number of random factors (NRF)                =  55
 Number of fixed factors (NFF)                 =  4
 Number of subject levels (NLSV)               =  3
 Rank of X (RNKX)                              =  4
 Effective N (EFFN)                            =  90
 Number of nonzero variance components (NCOV) =  7
 Parameter Estimates

 Random Effects
  Subject: Variable 10 (Level  1) Variable 11 (Level  1) Variable 12 (Level  1)
     Variable  3 (Level  1)         2.1566     3.7320
     Variable  3 (Level  2)         1.7769     3.8543
     Variable  4 (Level  1)         0.5583     3.0508

  Subject: Variable 10 (Level  1) Variable 11 (Level  1) Variable 12 (Level  1)
     Variable  4 (Level  3)         0.6776     3.0358

  Subject: Variable 10 (Level  2) Variable 11 (Level  1) Variable 12 (Level  1)
     Variable  3 (Level  1)         1.4448     3.3293
     Variable  3 (Level  2)        -2.8634     3.3533
     Variable  4 (Level  1)         3.6811     2.2253
     Variable  4 (Level  2)        -1.9988     2.2929
     Variable  4 (Level  3)        -2.1281     1.9896

  Subject: Variable 10 (Level  1) Variable 11 (Level  2) Variable 12 (Level  1)
     Variable  3 (Level  1)        -3.1562     3.8624
     Variable  3 (Level  2)         2.8856     4.6985
     Variable  4 (Level  1)        -4.6811     2.2236
     Variable  4 (Level  2)         5.5794     2.1390
     Variable  4 (Level  3)        -0.9832     2.2841

  Subject: Variable 10 (Level  2) Variable 11 (Level  2) Variable 12 (Level  1)
     Variable  3 (Level  1)         4.3449     3.6258
     Variable  3 (Level  2)        -4.4285     3.4096
     Variable  4 (Level  1)        -1.0798     3.1008
     Variable  4 (Level  2)         1.0536     2.9612

  Subject: Variable 10 (Level  1) Variable 11 (Level  3) Variable 12 (Level  1)
     Variable  3 (Level  1)         0.4216     4.0146
     Variable  3 (Level  2)         0.2268     3.4265
     Variable  4 (Level  1)        -1.0626     2.3505

  Subject: Variable 10 (Level  1) Variable 11 (Level  3) Variable 12 (Level  1)
     Variable  4 (Level  3)         1.2664     2.5276

  Subject: Variable 10 (Level  2) Variable 11 (Level  3) Variable 12 (Level  1)
     Variable  3 (Level  1)         1.2785     3.4331
     Variable  3 (Level  2)        -1.6652     3.8605

  Subject: Variable 10 (Level  2) Variable 11 (Level  3) Variable 12 (Level  1)
     Variable  4 (Level  2)         0.7332     2.6958
     Variable  4 (Level  3)        -0.8547     2.7819

  Subject: Variable 11 (Level  1) Variable 12 (Level  1)
     Variable  5 (Level  1)        -0.5540     2.8120
     Variable  5 (Level  2)         1.9179     2.7500
     Variable  6 (Level  1)         0.6925     3.6813
     Variable  6 (Level  2)        -2.2632     3.1202
     Variable  6 (Level  3)         4.3216     3.1131

  Subject: Variable 11 (Level  2) Variable 12 (Level  1)
     Variable  5 (Level  1)         1.5151     2.9154
     Variable  5 (Level  2)        -1.7072     2.8715
     Variable  6 (Level  1)         0.2154     3.9398
     Variable  6 (Level  2)        -3.7591     4.2153
     Variable  6 (Level  3)         3.1563     4.7621

  Subject: Variable 11 (Level  3) Variable 12 (Level  1)
     Variable  5 (Level  1)         1.7892     3.1214
     Variable  5 (Level  2)        -1.6473     3.1579
     Variable  6 (Level  1)        -1.2268     3.8853
     Variable  6 (Level  2)         4.6247     3.6412
     Variable  6 (Level  3)        -3.1117     3.1648

  Subject: Variable 12 (Level  1)
     Variable  7                    0.6016     0.4634
     Variable  8 (Level  1)         1.5887     1.2518
     Variable  8 (Level  2)        -0.7951     1.4856
     Variable  8 (Level  3)         0.3798     1.6037
     Variable  8 (Level  4)        -0.8295     1.6629
     Variable  9 (Level  1)         0.5197     1.5510
     Variable  9 (Level  2)         0.0156     1.8248
     Variable  9 (Level  3)        -0.1723     1.8271
     Variable  9 (Level  4)         0.4305     1.9494
     Variable  9 (Level  5)        -0.1412     2.0379

  Subject: Variable 10 (Level  1) Variable 11 (Level  1) Variable 12 (Level  2)
     Variable  3 (Level  1)         6.3424     3.3173
     Variable  3 (Level  2)         5.7538     3.3626

  Subject: Variable 10 (Level  1) Variable 11 (Level  1) Variable 12 (Level  2)
     Variable  4 (Level  2)         2.5053     2.6520
     Variable  4 (Level  3)         1.2953     2.6978

  Subject: Variable 10 (Level  2) Variable 11 (Level  1) Variable 12 (Level  2)
     Variable  3 (Level  1)         1.6342     3.7874
     Variable  3 (Level  2)        -2.8693     3.8549
     Variable  4 (Level  1)        -0.9274     2.7266

  Subject: Variable 10 (Level  2) Variable 11 (Level  1) Variable 12 (Level  2)
     Variable  4 (Level  3)         0.5394     2.7100

  Subject: Variable 10 (Level  1) Variable 11 (Level  2) Variable 12 (Level  2)
     Variable  3 (Level  1)       -10.2379     3.2977
     Variable  3 (Level  2)         3.2457     4.0593
     Variable  4 (Level  1)        -2.8362     2.2599
     Variable  4 (Level  2)         0.2805     2.9513
     Variable  4 (Level  3)         0.3587     2.8663

  Subject: Variable 10 (Level  2) Variable 11 (Level  2) Variable 12 (Level  2)
     Variable  3 (Level  1)        -1.3161     3.1545
     Variable  3 (Level  2)         8.2719     3.9322
     Variable  4 (Level  1)        -0.4813     2.3705
     Variable  4 (Level  2)         2.6668     2.4832

  Subject: Variable 10 (Level  1) Variable 11 (Level  3) Variable 12 (Level  2)
     Variable  3 (Level  1)         4.9485     3.9465
     Variable  3 (Level  2)         0.0987     3.5531
     Variable  4 (Level  1)         3.0791     2.1790
     Variable  4 (Level  2)        -1.9469     2.3796
     Variable  4 (Level  3)         0.4536     2.1984

  Subject: Variable 10 (Level  2) Variable 11 (Level  3) Variable 12 (Level  2)
     Variable  3 (Level  1)        -4.5419     3.2940
     Variable  3 (Level  2)        -3.9095     4.0163
     Variable  4 (Level  1)        -0.4456     2.6194
     Variable  4 (Level  2)        -1.5462     2.6514
     Variable  4 (Level  3)        -0.6636     2.8738

  Subject: Variable 11 (Level  1) Variable 12 (Level  2)
     Variable  5 (Level  1)         4.9921     3.0570
     Variable  5 (Level  2)         0.8986     3.0576
     Variable  6 (Level  1)         7.0091     3.7851
     Variable  6 (Level  2)        -1.3173     3.1348
     Variable  6 (Level  3)         6.1881     3.4928

  Subject: Variable 11 (Level  2) Variable 12 (Level  2)
     Variable  5 (Level  1)        -0.3947     3.0751
     Variable  5 (Level  2)         0.3750     3.0579
     Variable  6 (Level  1)         6.9902     3.2654
     Variable  6 (Level  2)        -1.0683     3.5699
     Variable  6 (Level  3)        -5.9617     3.6688

  Subject: Variable 11 (Level  3) Variable 12 (Level  2)
     Variable  5 (Level  1)        -1.0471     3.0732
     Variable  5 (Level  2)        -0.7991     2.9597
     Variable  6 (Level  1)         2.7549     3.8142
     Variable  6 (Level  2)        -6.3441     3.2624
     Variable  6 (Level  3)        -0.1341     3.5956

  Subject: Variable 12 (Level  2)
     Variable  7                    0.1533     0.5196
     Variable  8 (Level  1)         1.6630     1.8224
     Variable  8 (Level  2)        -0.6835     1.6502
     Variable  8 (Level  3)        -0.0959     1.5604
     Variable  8 (Level  4)         0.1696     1.4537
     Variable  9 (Level  1)         1.0203     2.2901
     Variable  9 (Level  2)         6.4354     1.7420
     Variable  9 (Level  3)        -1.5942     1.7761
     Variable  9 (Level  4)         0.0955     1.9436
     Variable  9 (Level  5)        -3.9588     1.7124

  Subject: Variable 10 (Level  1) Variable 11 (Level  1) Variable 12 (Level  3)
     Variable  3 (Level  1)        10.9751     3.2085
     Variable  3 (Level  2)        -1.0674     3.7219
     Variable  4 (Level  1)        -2.8350     2.2037
     Variable  4 (Level  2)         3.7075     2.7912
     Variable  4 (Level  3)         2.2405     2.2796

  Subject: Variable 10 (Level  2) Variable 11 (Level  1) Variable 12 (Level  3)
     Variable  3 (Level  1)        -6.2719     3.3190
     Variable  3 (Level  2)        -9.2923     3.7884
     Variable  4 (Level  1)        -2.8586     2.3728

  Subject: Variable 10 (Level  2) Variable 11 (Level  1) Variable 12 (Level  3)
     Variable  4 (Level  3)        -2.0316     2.2895

  Subject: Variable 10 (Level  1) Variable 11 (Level  2) Variable 12 (Level  3)
     Variable  3 (Level  1)        -3.3222     3.4246
     Variable  3 (Level  2)        -0.3111     3.2221
     Variable  4 (Level  1)         1.6131     2.3970
     Variable  4 (Level  2)        -3.0099     2.9300
     Variable  4 (Level  3)         0.2552     2.7229

  Subject: Variable 10 (Level  2) Variable 11 (Level  2) Variable 12 (Level  3)
     Variable  3 (Level  1)         6.6372     3.9751
     Variable  3 (Level  2)        -5.4249     3.4039
     Variable  4 (Level  1)        -3.2357     2.8565
     Variable  4 (Level  2)         1.5313     2.8232
     Variable  4 (Level  3)         2.0854     3.0661

  Subject: Variable 10 (Level  1) Variable 11 (Level  3) Variable 12 (Level  3)
     Variable  3 (Level  1)         8.5902     4.0894
     Variable  3 (Level  2)        -1.6058     3.2906
     Variable  4 (Level  1)         3.2575     2.5450

  Subject: Variable 10 (Level  1) Variable 11 (Level  3) Variable 12 (Level  3)
     Variable  4 (Level  3)        -1.0630     2.8692

  Subject: Variable 10 (Level  2) Variable 11 (Level  3) Variable 12 (Level  3)
     Variable  3 (Level  1)        -4.5747     3.9475
     Variable  3 (Level  2)        -4.1752     3.0911
     Variable  4 (Level  1)         1.0578     2.5496
     Variable  4 (Level  2)        -4.4284     2.2029
     Variable  4 (Level  3)         0.6214     2.5884

  Subject: Variable 11 (Level  1) Variable 12 (Level  3)
     Variable  5 (Level  1)         5.4387     3.0091
     Variable  5 (Level  2)        -8.5065     3.1099
     Variable  6 (Level  1)        -0.9179     3.7257
     Variable  6 (Level  2)        -2.4920     3.1176
     Variable  6 (Level  3)        -2.7772     3.4083

  Subject: Variable 11 (Level  2) Variable 12 (Level  3)
     Variable  5 (Level  1)         4.4193     3.1282
     Variable  5 (Level  2)        -5.7324     3.1435
     Variable  6 (Level  1)        -5.9992     3.1431
     Variable  6 (Level  2)         5.5657     3.2599
     Variable  6 (Level  3)        -2.2147     3.1758

  Subject: Variable 11 (Level  3) Variable 12 (Level  3)
     Variable  5 (Level  1)         0.3594     2.9017
     Variable  5 (Level  2)        -1.3169     3.0004
     Variable  6 (Level  1)        14.5815     3.8519
     Variable  6 (Level  2)        -5.2262     3.2578
     Variable  6 (Level  3)       -11.2864     3.1821

  Subject: Variable 12 (Level  3)
     Variable  7                   -0.2970     0.5930
     Variable  8 (Level  1)         2.6255     1.5201
     Variable  8 (Level  2)         0.5048     1.7865
     Variable  8 (Level  3)        -0.1518     1.8905
     Variable  8 (Level  4)        -4.3754     1.4651
     Variable  9 (Level  1)        -4.4219     2.0532
     Variable  9 (Level  2)         3.7058     1.9085
     Variable  9 (Level  3)        -1.7524     1.7894
     Variable  9 (Level  4)         0.4339     1.8210
     Variable  9 (Level  5)        -0.6161     2.3700

 Fixed Effects
   Intercept                        1.5913     2.4106
   Variable  1 (Level  2)          -1.5994     0.8183
   Variable  2 (Level  2)          -2.3793     1.0996
   Variable  2 (Level  3)           0.5328     1.1677

 Variance Components
  Estimate      Parameter        Subject
   36.38867      Variable  3     Variables 10 11 12
   11.43322      Variable  4     Variables 10 11 12
   19.73586      Variable  5     Variables 11 12
   39.80174      Variable  6     Variables 11 12
    0.41583      Variable  7     Variables 12
    5.16442      Variable  8     Variables 12
    9.79904      Variable  9     Variables 12

 SIGMA**2         =         0.00042
 -2LOG LIKELIHOOD =       617.11969


g02kafe.r

 G02KAF Example Program Results

 Value of ridge parameter:     0.0712

 Sum of squares of residuals: 0.1092E+03
 Degrees of freedom:     16
 Number of effective parameters:     2.9059

 Parameter estimates
    1     20.1950
    2      9.7934
    3      9.9576
    4     -2.0125

 Number of iterations:               6

 Ridge parameter minimises GCV

 Estimated prediction errors:
 GCV    =     7.4718
 UEV    =     6.3862
 FPE    =     7.3141
 BIC    =     8.2380
 LOO CV =     7.5495

 Residuals
    1     -1.9894
    2      3.5469
    3     -3.0392
    4     -3.0309
    5     -0.1899
    6     -0.3146
    7      0.9775
    8      4.0157
    9      2.5332
   10     -2.3560
   11      0.5446
   12      2.3989
   13     -4.0876
   14      3.2778
   15      0.2894
   16      0.7330
   17     -0.7116
   18     -0.6092
   19     -2.9995
   20      1.0110

 Variance inflation factors
    1      0.2928
    2      0.4162
    3      0.8089


g02ldfe.r

 G02LDF Example Program Results

 YHAT
              1
  1      0.2132
  2      0.5152
  3      0.1437
  4      0.4459
  5      0.1716
  6      2.4809
  7      0.0964
  8      1.4475
  9     -0.1546
 10     -0.5492
 11      0.5393
 12      0.2686
 13     -1.1332
 14      1.7975
 15      0.4973


g02qffe.r

 G02QFF Example Program Results

 Quantile:  0.100

         Lower   Parameter   Upper
         Limit   Estimate    Limit
   1    74.946   110.142   145.337
   2     0.370     0.402     0.433

 Quantile:  0.250

         Lower   Parameter   Upper
         Limit   Estimate    Limit
   1    64.232    95.483   126.735
   2     0.446     0.474     0.502

 Quantile:  0.500

         Lower   Parameter   Upper
         Limit   Estimate    Limit
   1    55.399    81.482   107.566
   2     0.537     0.560     0.584

 Quantile:  0.750

         Lower   Parameter   Upper
         Limit   Estimate    Limit
   1    41.372    62.396    83.421
   2     0.625     0.644     0.663

 Quantile:  0.900

         Lower   Parameter   Upper
         Limit   Estimate    Limit
   1    26.829    67.351   107.873
   2     0.650     0.686     0.723


g02qgfe.r

 G02QGF Example Program Results

 Quantile:  0.100

         Lower   Parameter   Upper
         Limit   Estimate    Limit
   1    74.946   110.142   145.337
   2     0.370     0.402     0.433

 Covariance matrix
  0.319E+03
 -0.254E+00    0.259E-03

 Quantile:  0.250

         Lower   Parameter   Upper
         Limit   Estimate    Limit
   1    64.232    95.483   126.735
   2     0.446     0.474     0.502

 Covariance matrix
  0.252E+03
 -0.200E+00    0.204E-03

 Quantile:  0.500

         Lower   Parameter   Upper
         Limit   Estimate    Limit
   1    55.399    81.482   107.566
   2     0.537     0.560     0.584

 Covariance matrix
  0.175E+03
 -0.140E+00    0.142E-03

 Quantile:  0.750

         Lower   Parameter   Upper
         Limit   Estimate    Limit
   1    41.372    62.396    83.421
   2     0.625     0.644     0.663

 Covariance matrix
  0.114E+03
 -0.907E-01    0.923E-04

 Quantile:  0.900

         Lower   Parameter   Upper
         Limit   Estimate    Limit
   1    26.829    67.351   107.873
   2     0.650     0.686     0.723

 Covariance matrix
  0.423E+03
 -0.337E+00    0.343E-03

 First 10 Residuals
                               Quantile
 Obs.    0.100      0.250      0.500      0.750      0.900
    1  -23.10718  -38.84219  -61.00711  -77.14462  -99.86551
    2  140.20549   96.93582   42.00636   -6.04177  -44.85812
    3   91.19725   59.31654   17.93924  -16.90993  -49.06884
    4  -16.70358  -41.20981  -73.81193 -100.11463 -127.96277
    5  296.77717  221.32470  128.09970   42.75414  -14.87476
    6 -271.39185 -441.31464 -646.95350 -841.78309 -954.63488
    7   13.48419  -37.04518 -100.61322 -157.07478 -200.13481
    8  218.91527  146.69601   57.31834  -24.28017  -80.01908
    9    0.00000 -115.21109 -255.74639 -387.16920 -468.03911
   10   36.09526    4.52393  -36.48522  -70.97584 -102.95390


g03aafe.r

 G03AAF Example Program Results

 Eigenvalues  Percentage  Cumulative     Chisq      DF     Sig
               variation   variation

      8.2739      0.6515      0.6515    8.6127     5.0  0.1255
      3.6761      0.2895      0.9410    4.1183     2.0  0.1276
      0.7499      0.0590      1.0000    0.0000     0.0  0.0000


g03acfe.r

 G03ACF Example Program Results

 Rank of X = 3

 Canonical    Eigenvalues Percentage     CHISQ      DF     SIG
 Correlations              Variation
       0.8826      3.5238     0.9795    7.9032     6.0  0.2453
       0.2623      0.0739     0.0205    0.3564     2.0  0.8368

 Canonical Coefficients for X
             1          2
 1     -1.7070     0.7277
 2     -1.3481     0.3138
 3      0.9327     1.2199

 Canonical variate means
             1          2
 1      0.9841     0.2797
 2      1.1805    -0.2632
 3     -2.1646    -0.0164


g03adfe.r

 G03ADF Example Program Results

 Rank of X = 2 Rank of Y = 2

 Canonical    Eigenvalues Percentage     Chisq      DF     Sig
 correlations              variation
       0.9570      0.9159     0.8746   14.3914     4.0  0.0061
       0.3624      0.1313     0.1254    0.7744     1.0  0.3789

 Canonical Coefficients for X
             1          2
 1     -0.4261     1.0337
 2     -0.3444    -1.1136

 Canonical Coefficients for Y
          1       2
 1  -0.1415  0.1504
 2  -0.2384 -0.3424


g03bcfe.r

 G03BCF Example Program Results

 Rotation Matrix
          1       2
 1   0.9673  0.2536
 2  -0.2536  0.9673

  Scale factor =      1.556

 Target Matrix
             1          2
 1      0.0000     0.0000
 2      1.0000     0.0000
 3      0.0000     2.0000

 Fitted Matrix
             1          2
 1     -0.0934     0.0239
 2      1.0805     0.0259
 3      0.0130     1.9502

 RSS =      0.019


g03bdfe.r

 G03BDF Example Program Results

 Factor pattern
             1          2
 1      0.9556    -0.0979
 2      0.9184    -0.0935
 3      0.7605     0.3393
 4     -0.0791     1.0019
 5      0.0480     0.9751

 ProMax rotation
          1       2
 1   0.7380  0.5420
 2  -0.7055  0.8653

 Inter-factor correlations
          1       2
 1   1.0000  0.2019
 2   0.2019  1.0000

 Factor structure
          1       2
 1   0.9358  0.0950
 2   0.8995  0.0919
 3   0.8290  0.4928
 4   0.1232  0.9860
 5   0.2448  0.9848


g03ccfe.r

 G03CCF Example Program Results

  Loadings, Communalities and PSI

    0.553   -0.429    0.490    0.510
    0.568   -0.288    0.406    0.594
    0.392   -0.450    0.356    0.644
    0.740    0.273    0.623    0.377
    0.724    0.211    0.569    0.431
    0.595    0.132    0.372    0.628

 Factor score coefficients
          1       2
 1   0.1932 -0.3920
 2   0.1703 -0.2265
 3   0.1085 -0.3262
 4   0.3495  0.3374
 5   0.2989  0.2286
 6   0.1688  0.0978


g03dafe.r

 G03DAF Example Program Results

 Group means
             1          2
 1      1.0433    -0.6034
 2      2.0073    -0.2060
 3      2.7097     1.5998

  LOG of determinants

    -0.8273   -3.0460   -2.2877

  STAT = 19.2410
    DF =  6.0000
   SIG =  0.0038


g03dbfe.r

 G03DBF Example Program Results

 Distances
             1          2          3
 1      3.3393     0.7521    50.9283
 2     20.7771     5.6559     0.0597
 3     21.3631     4.8411    19.4978
 4      0.7184     6.2803   124.7323
 5     55.0003    88.8604    71.7852
 6     36.1703    15.7849    15.7489


g03dcfe.r

 G03DCF Example Program Results

    Obs       Posterior        Allocated     Atypicality
              probabilities    to group      index

     1      0.094 0.905 0.002     2      0.596 0.254 0.975
     2      0.005 0.168 0.827     3      0.952 0.836 0.018
     3      0.019 0.920 0.062     2      0.954 0.797 0.912
     4      0.697 0.303 0.000     1      0.207 0.860 0.993
     5      0.317 0.013 0.670     3      0.991 1.000 0.984
     6      0.032 0.366 0.601     3      0.981 0.978 0.887


g03eafe.r

 G03EAF Example Program Results

  Distance Matrix

          1       2       3       4

  2      1.00
  3     29.00   26.00
  4     50.00   49.00    5.00
  5     50.00   53.00   13.00    4.00


g03ecfe.r

 G03ECF Example Program Results

   Distance   Clusters Joined

     1.000     B  D
     2.000     A  C
     6.500     A  E
    14.125     A  B


g03effe.r

 G03EFF Example Program Results

  The cluster each point belongs to
      1     1     3     2     3     1     1     2     2     3
      3     3     3     3     3     3     3     1     1     3

  The number of points in each cluster
      6     3    11

  The within-cluster sum of weights of each cluster
      6.00     3.00    11.00

  The within-cluster sum of squares of each cluster
       46.5717      20.3800     468.8964

 The final cluster centres
             1          2          3          4          5
 1     81.1833    11.6667     7.1500     2.0500     6.6000
 2     47.8667    35.8000    16.3333     2.4000     6.7333
 3     64.0455    25.2091    10.7455     2.8364     6.6545


g03ehfe.r

 G03EHF Example Program Results

 Dendrogram, Orientation East

         ...............................(
        (                         .......
        (                        (    ...
        (........................(...(...

 Dendrogram, Orientation South

    ----------
    I        I
    I        I
    I        I
    I        I
    I        I
    I        I
    I        I
    I        I
    I        I
    I        I
    I        I
    I        I
    I        I
    I        I
    I        I
    I        I
    I        I
    I        I
    I        I
    I        I
    I        I
    I        I
    I        I
    I        I
    I        I
    I        I
    I        I
    I  ------*
    I  I     I
    I  I     I
    I  I     I
    I  I  ---*
    I  I  I  I
    I  I  I  I
 ---*  I  I  I
 I  I  I  I  I


g03ejfe.r

 G03EJF Example Program Results

   Distance   Clusters Joined

      1.000     B  D
      2.000     A  C
      6.500     A  E
     14.125     A  B

  Allocation to 2 clusters
  Clusters found at distance 6.500

  Object  Cluster

      A        1
      B        2
      C        1
      D        2
      E        1


g03fafe.r

 G03FAF Example Program Results

  Scaled Eigenvalues

    0.7871    0.2808

 Co-ordinates
           1       2
  1   0.2408  0.2337
  2   0.1137  0.1168
  3   0.2394  0.0760
  4   0.2129  0.0605
  5   0.2495 -0.0693
  6   0.1487 -0.0778
  7  -0.0514 -0.1623
  8   0.0115 -0.3446
  9  -0.0039  0.0059
 10   0.0386 -0.0089
 11  -0.0421 -0.0566
 12  -0.5158  0.0291
 13  -0.3180  0.1501
 14  -0.3238  0.0475


g03zafe.r

 G03ZAF Example Program Results

 Standardized Values
             1          2
 1      0.1000     1.0707
 2     -1.1000    -0.1190
 3      1.3000     0.3569
 4     -0.3000    -1.3086


g04agfe.r

 G04AGF Example Program Results

 Data values

  Group  Subgroup  Observations
     1        1     2.1 2.4 2.0 2.0 2.0
     1        2     2.4 2.1 2.2
     1        3     2.4 2.2 2.6
     1        4     2.4 2.4 2.5
     1        5     1.9 1.7
     2        1     2.1 1.5 2.0
     2        2     1.9 1.7 1.9 1.9 1.9
     2        3     2.0 2.1 2.3

 Subgroup means

    Group  Subgroup  Mean
      1       1      2.10
      1       2      2.23
      1       3      2.40
      1       4      2.43
      1       5      1.80
      2       1      1.87
      2       2      1.86
      2       3      2.13

     Group 1 mean = 2.21   (16 observations)
     Group 2 mean = 1.94   (11 observations)
     Grand mean   = 2.10   (27 observations)

 Analysis of variance table

    Source                SS    DF  F ratio  Sig

 Between groups         0.475    1  16.15   0.001
 Bet sbgps within gps   0.816    6   4.63   0.005
 Residual               0.559   19

 Total                  1.850   26


g04bbfe.r

 G04BBF Example Program Results

  ANOVA table

   Source        df         SS          MS          F        Prob

 Blocks          9.       60.00        6.67        4.79     0.0039
 Treatments      5.      101.78       20.36       14.62     0.0000
 Residual       15.       20.89        1.39
 Total          29.      182.67

  Efficiency Factors

      0.00      0.80      0.80      0.80      0.80      0.80

  Grand Mean      5.33

  Treatment Means

      2.50      7.25      8.08      5.92      2.92      5.33

 Standard errors of differences between means
          1       2       3       4       5       6
 1
 2   0.8344
 3   0.8344  0.8344
 4   0.8344  0.8344  0.8344
 5   0.8344  0.8344  0.8344  0.8344
 6   0.8344  0.8344  0.8344  0.8344  0.8344


g04bcfe.r

 G04BCF Example Program Results

  ANOVA TABLE

 Rows         4.     29.4231      7.3558      9.0266    0.0013
 Columns      4.     22.9950      5.7487      7.0545    0.0037
 Treatments   4.      0.5423      0.1356      0.1664    0.9514
 Residual    12.      9.7788      0.8149
 Total       24.     62.7392

  Treatment means

    7.3180    7.2440    7.2060    6.9000    7.2600

 S.E. of difference (orthogonal design) =     0.5709


g04cafe.r

 G04CAF Example Program Results

  ANOVA table

   Source      df         SS          MS          F        Prob

 Blocks        2.      30119.      15059.       7.685     0.0018
 Effect   1    5.      73008.      14602.       7.451     0.0001
 Effect   2    2.      21596.      10798.       5.510     0.0085
 Effect   3   10.      31192.       3119.       1.592     0.1513
 Residual     34.      66628.       1960.
 Total        53.     222543.

  Treatment Means and Standard Errors

 Effect     1

    254.78    339.00    333.33    367.78    330.78    360.67

 SE of difference in means  =      20.87

 Effect     2

    334.28    353.78    305.11

 SE of difference in means  =      14.76

 Effect     3

    235.33    332.67    196.33    342.67    341.67    332.67    309.33    370.33
    320.33    395.00    370.33    338.00    373.33    326.67    292.33    350.00
    381.00    351.00

 SE of difference in means  =      36.14


g04dafe.r

 G04DAF Example Program Results

  ANOVA table

   Source        df         SS          MS          F        Prob

 Treatments    6.       972.3       162.1       3.608     0.0103
 Residual     25.      1122.9        44.9
 Total        31.      2095.2

  Orthogonal Contrasts

 Cntl v S      1.       518.0       518.0      11.533     0.0023
 Spring v A    1.       228.2       228.2       5.080     0.0332


g04dbfe.r

 G04DBF Example Program Results

  ANOVA table

   Source        df         SS          MS          F        Prob

 Treatments    3.       239.9        80.0      24.029     0.0000
 Residual     22.        73.2         3.3
 Total        25.       313.1

  Treatment means

   3.000   7.000   2.250   9.429

  Simultaneous Confidence Intervals

   2 1        0.933        7.067   *
   3 1       -3.486        1.986
   3 2       -7.638       -1.862   *
   4 1        3.610        9.247   *
   4 2       -0.538        5.395
   4 3        4.557        9.800   *


g04eafe.r

 G04EAF Example Program Results

 Model not of full rank, rank =    4

 Residual sum of squares =   0.2223E+02
 Degrees of freedom =    8

 Variable   Parameter estimate   Standard error

      1          0.3056E+02          0.3849E+00
      2          0.5447E+01          0.8390E+00
      3          0.6743E+01          0.8390E+00
      4          0.1105E+02          0.8390E+00
      5          0.7320E+01          0.8390E+00


g05kffe.r

 G05KFF Example Program Results

     0.6364
     0.1065
     0.7460
     0.7983
     0.1046


g05kgfe.r

 G05KGF Example Program Results

 The two samples differ, as expected


g05khfe.r

 G05KHF Example Program Results

 Stream                1
     0.7460
     0.4925
     0.4982
     0.2580
     0.5938

 Stream                2
     0.7983
     0.3843
     0.6717
     0.6238
     0.2785

 Stream                3
     0.1046
     0.7871
     0.0505
     0.0535
     0.2375


g05kjfe.r

 G05KJF Example Program Results

     0.2071
     0.8413
     0.8817
     0.5494
     0.5248


g05kkfe.r

 G05KKF Example Program Results

     0.7357
     0.3521
     0.4188
     0.0046
     0.0365


g05ncfe.r

 G05NCF Example Program Results

 10 Permutations of first 8 integers

   6  2  4  8  1  3  5  7
   8  6  4  2  7  3  1  5
   4  2  8  7  5  6  3  1
   1  6  4  5  2  3  7  8
   1  7  3  8  4  2  5  6
   6  3  4  7  1  2  8  5
   6  4  1  8  2  5  3  7
   3  2  1  7  5  8  6  4
   4  2  1  5  3  6  8  7
   1  5  6  4  2  7  8  3


g05ndfe.r

 G05NDF Example Program Results

  Samples from the first 8 integers

  Sample size     Values
      1            2
      2            3   6
      3            1   5   7
      4            2   6   7   8
      5            1   2   3   4   8
      6            1   3   4   5   6   7
      7            1   3   4   5   6   7   8
      8            1   2   3   4   5   6   7   8


g05nefe.r

 G05NEF Example Program Results

  125   41  185   40   37  196   22   25   76  172


g05phfe.r

 G05PHF Example Program Results

      -1.7103
      -0.4042
      -0.1845
      -1.5004
      -1.1946
      -1.8184
      -1.0895
       1.6408
       1.3555
       1.1908


g05pmfe.r

 G05PMF Example Program Results

 Initial values used:
     168.018
       3.800

Mean Deviation     =   0.2547E+02
Absolute Deviation =   0.2123E+02

          Observed      1-Step
  Period   Values      Forecast      Residual

   1      180.000      171.818        8.182
   2      135.000      175.782      -40.782
   3      213.000      178.848       34.152
   4      181.000      183.005       -2.005
   5      148.000      186.780      -38.780
   6      204.000      189.800       14.200
   7      228.000      193.492       34.508
   8      225.000      197.732       27.268
   9      198.000      202.172       -4.172
  10      200.000      206.256       -6.256
  11      187.000      210.256      -23.256

                                            Simulated CI         Simulated CI
 Obs.  Forecast      Estimated CI        (Gaussian Errors)    (Bootstrap Errors)
 12    213.854    163.928    263.781    161.431    258.001    173.073    248.363
 13    217.685    167.748    267.622    172.660    262.100    177.311    252.638
 14    221.516    171.556    271.475    169.259    263.107    179.344    256.921
 15    225.346    175.347    275.345    180.721    272.776    183.672    260.804
 16    229.177    179.115    279.238    184.790    263.591    186.398    264.173
  95.0% CIs were produced


g05pvfe.r

 G05PVF Example Program Results

                       Observed
             --------------------------
 Predicted | Negative  Positive   Total
 --------------------------------------
 Negative  |    18         8        26
 Positive  |     4        10        14
 Total     |    22        18        40

 True Positive Rate (Sensitivity): 0.56
 True Negative Rate (Specificity): 0.82


g05pwfe.r

 G05PWF Example Program Results

                       Observed
             --------------------------
 Predicted | Negative  Positive   Total
 --------------------------------------
 Negative  |    38        20        58
 Positive  |     8        14        22
 Total     |    46        34        80

 True Positive Rate (Sensitivity): 0.41
 True Negative Rate (Specificity): 0.83


g05pxfe.r

 G05PXF Example Program Results

 Random Matrix
          1       2       3       4
 1   0.1756  0.7401 -0.3067 -0.5722
 2   0.6593 -0.5781 -0.2191 -0.4279
 3   0.6680  0.3172  0.6077  0.2895
 4  -0.2971 -0.1323  0.6990 -0.6369


g05pyfe.r

 G05PYF Example Program Results

 Correlation Matrix
          1       2       3
 1   1.0000 -0.2549 -0.1004
 2  -0.2549  1.0000  0.2343
 3  -0.1004  0.2343  1.0000


g05pzfe.r

 G05PZF Example Program Results

 Random Table
    1 2 3
 1  2 4 3
 2  6 1 4
 3  2 4 1
 4  6 8 9

 Supplied row totals:
           9        11         7        23
 Supplied column totals:
          16        17        17


g05refe.r

 G05REF Example Program Results

 Uniform variates with copula joint distribution
           1       2
  1   0.6400  0.2223
  2   0.1154  0.8101
  3   0.7486  0.1439
  4   0.8003  0.1062
  5   0.1135  0.9946
  6   0.4975  0.7655
  7   0.3904  0.4925
  8   0.7892  0.1196
  9   0.5032  0.4116
 10   0.6750  0.2093
 11   0.0600  0.9055
 12   0.2655  0.7085
 13   0.6276  0.2370


g05rffe.r

 G05RFF Example Program Results

 Uniform variates with copula joint distribution
           1       2
  1   0.6364  0.1411
  2   0.1065  0.8967
  3   0.7460  0.1843
  4   0.7983  0.1254
  5   0.1046  0.9982
  6   0.4925  0.6901
  7   0.3843  0.6250
  8   0.7871  0.1654
  9   0.4982  0.5298
 10   0.6717  0.2902
 11   0.0505  0.9554
 12   0.2580  0.8190
 13   0.6238  0.3014


g05rgfe.r

 G05RGF Example Program Results

 Uniform variates with copula joint distribution
           1       2
  1   0.6364  0.0695
  2   0.1065  0.4586
  3   0.7460  0.3586
  4   0.7983  0.3267
  5   0.1046  0.9888
  6   0.4925  0.8920
  7   0.3843  0.4903
  8   0.7871  0.4248
  9   0.4982  0.5783
 10   0.6717  0.4419
 11   0.0505  0.5802
 12   0.2580  0.6629
 13   0.6238  0.3291


g05safe.r

 G05SAF Example Program Results

     0.6364
     0.1065
     0.7460
     0.7983
     0.1046


g05sbfe.r

 G05SBF Example Program Results

     0.5977
     0.6818
     0.1797
     0.4174
     0.4987


g05scfe.r

 G05SCF Example Program Results

     6.1229
     2.2328
    -2.2118
     0.4118
     0.9892


g05sdfe.r

 G05SDF Example Program Results

     4.4731
     5.9371
     1.7636
     2.9812
     4.3280


g05sefe.r

 G05SEF Example Program Results

          1       2       3       4
 1   0.3600  0.3138  0.0837  0.2426
 2   0.2874  0.5121  0.1497  0.0509
 3   0.2286  0.2190  0.3959  0.1566
 4   0.1744  0.3961  0.2764  0.1530
 5   0.1522  0.2845  0.2074  0.3559


g05sffe.r

 G05SFF Example Program Results

     0.4520
     2.2398
     0.2930
     0.2253
     2.2577


g05sgfe.r

 G05SGF Example Program Results

     0.4520
     2.2398
     1.4649
     0.2253
    11.2884


g05shfe.r

 G05SHF Example Program Results

     1.4401
     1.8083
     0.3638
     0.5464
     4.0895


g05sjfe.r

 G05SJF Example Program Results

     5.0702
     6.1337
     3.1018
     3.9863
     4.9648


g05skfe.r

 G05SKF Example Program Results

     1.4272
    -0.5254
     1.8109
     2.0232
    -0.5380


g05slfe.r

 G05SLF Example Program Results

     2.1193
    -3.2544
     3.1552
     3.7510
    -3.2944


g05smfe.r

 G05SMF Example Program Results

     4.4515
     0.4670
     6.9331
     8.8597
     0.4603


g05snfe.r

 G05SNF Example Program Results

     0.3849
    -0.9461
    -2.2814
     0.1127
     0.5272


g05spfe.r

 G05SPF Example Program Results

     0.3817
    -0.4348
     0.4960
     0.5509
    -0.4398


g05sqfe.r

 G05SQF Example Program Results

     0.2727
    -0.7870
     0.4921
     0.5965
    -0.7908


g05srfe.r

 G05SRF Example Program Results

     1.2947
    -1.9542
    -0.6464
    -1.4172
     1.2536


g05ssfe.r

 G05SSF Example Program Results

     0.9039
     4.4796
     0.5860
     0.4506
     4.5154


g05tafe.r

 G05TAF Example Program Results

         4811
         4761
         4821
         4826
         4761
         4800
         4791
         4825
         4800
         4814
         4749
         4780
         4810
         4750
         4807
         4782
         4778
         4877
         4840
         4802


g05tbfe.r

 G05TBF Example Program Results

 F
 T
 F
 F
 T
 T
 T
 F
 T
 F
 T
 T
 F
 T
 F
 T
 T
 F
 F
 F


g05tcfe.r

 G05TCF Example Program Results

          451
         2238
          292
          225
         2256
          708
          955
          239
          696
          397


g05tdfe.r

 G05TDF Example Program Results

            0
           -2
            1
            1
           -2
            0
            0
            1
            0
            1
           -3
           -1
            0
           -3
            0
           -1
           -1
            5
            2
            0


g05tefe.r

 G05TEF Example Program Results

          452
          444
          453
          454
          444
          450
          449
          454
          450
          452
          442
          447
          451
          442
          451
          447
          447
          462
          456
          450


g05tffe.r

 G05TFF Example Program Results

            6
           23
         2765
           30
            3
            1
          299
          968
          166
            4


g05thfe.r

 G05THF Example Program Results

        62339
        50505
        64863
        66289
        50434
        59461
        57365
        65965
        59572
        63104
        47833
        54735
        62075
        48018
        61458
        55190
        54263
        80995
        70129
        60200


g05tjfe.r

 G05TJF Example Program Results

           21
           15
           23
           24
           14
           20
           19
           23
           20
           22


g05tkfe.r

 G05TKF Example Program Results

             1            1            6           12          507         1003
             2            0            9           11          520         1028
             3            1            3            7          483         1041
             4            0            3           11          513         1012
             5            1            5            9          496          940
             6            0            6           17          548          990
             7            1            9            8          512         1035
             8            0            4           10          458         1029
             9            1            6           13          523          971
            10            0            9           16          519          999


g05tlfe.r

 G05TLF Example Program Results

            2
           -4
            3
            3
           -4


g05yjfe.r

 G05YJF Example Program Results

     1.5820    2.2448    0.9154    3.0722
     2.8768    1.6057    3.7341    5.4521
     0.9240    3.0223    2.3828    3.8154
     0.6004    1.9290    1.9355    3.4806
     2.0141    3.9061    3.3680    4.8479


g05ykfe.r

 G05YKF Example Program Results

     4.8648    9.4382    2.4979   21.5895
    17.7572    4.9813   41.8501  233.2386
     2.5195   20.5384   10.8353   45.3933
     1.8229    6.8823    6.9276   32.4808
     7.4938   49.7034   29.0198  127.4745


g05zmfe.r

 G05ZMF Example Program Results

 Size of embedding matrix =      16

 Approximation not required

 Square roots of eigenvalues of embedding matrix:

    0.74207   0.73932   0.73150   0.71991
    0.70639   0.69304   0.68184   0.67442
    0.67182   0.67442   0.68184   0.69304
    0.70639   0.71991   0.73150   0.73932


g05znfe.r

 G05ZNF Example Program Results

 Size of embedding matrix =      16

 Approximation not required

 Square roots of eigenvalues of embedding matrix:

    0.74207   0.73932   0.73150   0.71991
    0.70639   0.69304   0.68184   0.67442
    0.67182   0.67442   0.68184   0.69304
    0.70639   0.71991   0.73150   0.73932


g07aafe.r

 G07AAF Example Program Results

  Probability    Confidence Interval

     0.1097      ( 0.0915 , 0.1300 )
     0.1343      ( 0.1025 , 0.1716 )


g07abfe.r

 G07ABF Example Program Results

 The point estimate of the Poisson parameter = 3.0204

 95 percent Confidence Interval for the estimate
      ( 2.6861 , 3.3848 )

 99 percent Confidence Interval for the estimate
      ( 2.5874 , 3.5027 )


g07bbfe.r

 G07BBF Example Program Results

  Mean =   4.4924
  Standard deviation =   1.0196
  Standard error of mean =   0.2606
  Standard error of sigma =   0.1940
  Correlation coefficient =   0.0160
  Number of right censored observations =  3
  Number of left censored observations =  2
  Number of interval censored observations =  1
  Number of exactly specified observations = 12
  Number of iterations =  5
  Log-likelihood = -22.2817


g07befe.r

 G07BEF Example Program Results

  BETA  =    -2.1073 Standard error =     0.4627
  GAMMA =     2.7870 Standard error =     0.4273


g07bffe.r

 G07BFF Example Program Results

 Parameter estimates
 xi               0.540439E+00
 beta             0.104055E+01

 Observed distribution
 Var(xi)            0.799320E-01
 Var(beta)          0.119872E+00
 Covar(xi,beta)    -0.455092E-01
 Final log-likelihood:  -0.363443E+02


g07cafe.r

 G07CAF Example Program Results

 Sample X
   Sample size        =     4
   Mean               = 0.2500E+02
   Standard deviation = 0.8185E+00

 Sample Y
   Sample size        =     8
   Mean               = 0.2100E+02
   Standard deviation = 0.4208E+01

 Assuming population variances are equal.

 t test statistic         =      1.8403
 Degrees of freedom       =     10.0
 Significance level       =      0.0955

 Difference in means
   Value                  =     4.0000
   Lower confidence limit =    -0.8429
   Upper confidence limit =     8.8429
   Confidence level       =     0.9500

 No assumptions about population variances.

 t test statistic         =      2.5922
 Degrees of freedom       =      8.0
 Significance level       =      0.0320

 Difference in means
   Value                  =     4.0000
   Lower confidence limit =     0.4410
   Upper confidence limit =     7.5590
   Confidence level       =     0.9500


g07dafe.r

 G07DAF Example Program Results

 Original Data
  13.000 11.000 16.000  5.000  3.000 18.000  9.000  8.000  6.000 27.000  7.000

 Sorted Data
   3.000  5.000  6.000  7.000  8.000  9.000 11.000 13.000 16.000 18.000 27.000

 Median                             =  9.000
 Median absolute deviation          =  4.000
 Robust estimate standard deviation =  5.930


g07dbfe.r

 G07DBF Example Program Results

           Input parameters     Output parameters
 ISIGMA   SIGMA   THETA   TOL    SIGMA  THETA
   1    -1.0000  0.0000 0.0001   6.3247 10.5487
   1     7.0000  2.0000 0.0001   6.3249 10.5487
   0    -1.0000  0.0000 0.0001   5.9304 10.4896
   0     7.0000  2.0000 0.0001   7.0000 10.6500


g07dcfe.r

 G07DCF Example Program Results

           Input parameters     Output parameters
 ISIGMA   SIGMA   THETA   TOL    SIGMA  THETA
   1    -1.0000  0.0000 0.0001   6.3247 10.5487
   1     7.0000  2.0000 0.0001   6.3249 10.5487
   0    -1.0000  0.0000 0.0001   5.9304 10.4896
   0     7.0000  2.0000 0.0001   7.0000 10.6500


g07ddfe.r

 G07DDF Example Program Results

 Statistics from middle  75.00% of data

                Trimmed-mean =      8.8333
    Variance of Trimmed-mean =      1.5434

             Winsorized-mean =      9.1250
 Variance of Winsorized-mean =      1.5381


g07eafe.r

 G07EAF Example Program Results

  Location estimator     Confidence Interval

      -0.1300            (-0.3300 , 0.0350 )

  Corresponding Wilcoxon statistics

 Lower :   556.00
 Upper :   264.00


g07ebfe.r

 G07EBF Example Program Results

  Location estimator     Confidence Interval

       0.9505            ( 0.5650 , 1.3050 )

  Corresponding Mann-Whitney U statistics

 Lower :  2007.00
 Upper :  2993.00


g07gafe.r

 G07GAF Example Program Results

 Number of potential outliers: 2
   No.  Index    Value       Diff    ln(lambda^2)
    1    13      -1.40       0.31      -0.30
    2    11       1.01


g07gbfe.r

 G07GBF Example Program Results

 Sample size                              :         15
 Largest absolute residual (E)            :     -1.400
 Variance for whole sample                :      0.303
 Variance excluding E                     :      0.161
 Estimate for cutoff (X)                  :      0.000
 Lower limit for cutoff (LX)              :      0.000
 Upper limit for cutoff (UX)              :      0.000
 E is a potential outlier

 Sample size                              :         14
 Largest absolute residual (E)            :      1.010
 Variance for whole sample                :      0.161
 Variance excluding E                     :      0.103
 Estimate for cutoff (X)                  :      0.105
 Lower limit for cutoff (LX)              :      0.100
 Upper limit for cutoff (UX)              :      0.110
 E is a potential outlier

 Sample size                              :         13
 Largest absolute residual (E)            :      0.630
 Variance for whole sample                :      0.103
 Variance excluding E                     :      0.080
 Estimate for cutoff (X)                  :      1.059
 Lower limit for cutoff (LX)              :      1.011
 Upper limit for cutoff (UX)              :      1.155
 E does not appear to be an outlier


g08aafe.r

 G08AAF Example Program Results

 Sign test

 Data values

     4. 4. 5. 5. 3. 2. 5. 3. 1. 5. 5. 5. 4. 5. 5. 5. 5.
     2. 3. 3. 3. 3. 3. 3. 3. 2. 3. 2. 2. 5. 2. 5. 3. 1.

 Test statistic       3
 Observations        14
 Lower tail prob. 0.029


g08acfe.r

 G08ACF Example Program Results

 Median test

 Data values

     Group 1   13.  6. 12.  7. 12.  7. 10.  7.
               10.  7. 10.  7. 10.  8.  9.  8.

     Group 2   17.  6. 16.  8. 15.  8. 15. 10.
               15. 10. 14. 10. 14. 11. 14. 11.
               13. 12. 13. 12. 13. 12. 12.

     13 scores below median in group 1
      6 scores below median in group 2

      Significance   0.00088


g08affe.r

 G08AFF Example Program Results

 Kruskal-Wallis test

 Data values

   Group    Observations
     1      23. 27. 26. 19. 30.
     2      29. 25. 33. 36. 32. 28. 30. 31.
     3      38. 31. 28. 35. 33. 36.
     4      30. 27. 28. 22. 33. 34. 34. 32.
     5      31. 33. 31. 28. 30. 24. 29. 30.

 Test statistic          10.537
 Degrees of freedom           4
 Significance             0.032


g08agfe.r

 G08AGF Example Program Results

 Wilcoxon one sample signed ranks test

 Data values
     82.0 69.0 73.0 43.0 58.0 56.0 76.0 65.0
     63.0 42.0 74.0 37.0 51.0 43.0 80.0 62.0

 Test statistic            =  32.0000
 Normalized test statistic =   1.8904
 Degrees of freedom        =        8
 Two tail probability      =   0.0547


g08ahfe.r

 G08AHF Example Program Results

 Mann-Whitney U test

 Sample size of group 1 =    16
 Sample size of group 2 =    23

 Data values

     Group 1   13.0  6.0 12.0  7.0 12.0  7.0 10.0  7.0
               10.0  7.0 16.0  7.0 10.0  8.0  9.0  8.0

     Group 2   17.0  6.0 10.0  8.0 15.0  8.0 15.0 10.0
               15.0 10.0 14.0 10.0 14.0 11.0 14.0 11.0
               13.0 12.0 13.0 12.0 13.0 12.0 12.0

 Test statistic           =    86.0000
 Normal Statistic         =    -2.8039
 Approx. tail probability =     0.0025

 There are ties in the pooled sample

 Exact tail probability   =     0.0020


g08ajfe.r

 G08AJF Example Program Results

 Mann-Whitney U test

 Sample size of group 1 =    16
 Sample size of group 2 =    23

 Data values

     Group 1   13.0  5.8 11.7  6.5 12.3  6.7  9.2  6.9
               10.0  7.3 16.0  7.0 10.5  8.5  9.0  7.5

     Group 2   17.0  6.2 10.1  8.0 15.3  8.2 15.0  9.6
               14.9 10.4 14.2  9.8 13.8 11.0 14.0 11.1
               12.9 11.6 12.8 12.0 13.1 12.4 11.9

 Test statistic     =    86.0000
 Normal statistic   =    -2.7838
 Tail probability   =     0.0027

 Exact tail probability =     0.0022


g08akfe.r

 G08AKF Example Program Results

 Mann-Whitney U test

 Sample size of group 1 =    16
 Sample size of group 2 =    23

 Data values

     Group 1   13.0  6.0 12.0  7.0 12.0  7.0 10.0  7.0
               10.0  7.0 16.0  7.0 10.0  8.0  9.0  8.0

     Group 2   17.0  6.0 10.0  8.0 15.0  8.0 15.0 10.0
               15.0 10.0 14.0 10.0 14.0 11.0 14.0 11.0
               13.0 12.0 13.0 12.0 13.0 12.0 12.0

 Test statistic     =    86.0000
 Normal statistic   =    -2.8039
 Tail probability   =     0.0025

 Ranks

     Group 1   29.5  1.5 24.5  5.0 24.5  5.0 16.0  5.0
               16.0  5.0 38.0  5.0 16.0  9.5 12.0  9.5

     Group 2   39.0  1.5 16.0  9.5 36.0  9.5 36.0 16.0
               36.0 16.0 33.0 16.0 33.0 20.5 33.0 20.5
               29.5 24.5 29.5 24.5 29.5 24.5 24.5

 Exact tail probability =     0.0020


g08alfe.r

 G08ALF Example Program Results

 Cochrans Q test

 Data matrix
           1       2       3
  1   1.0000  1.0000  1.0000
  2   1.0000  1.0000  1.0000
  3   0.0000  1.0000  0.0000
  4   1.0000  1.0000  0.0000
  5   0.0000  0.0000  0.0000
  6   1.0000  1.0000  1.0000
  7   1.0000  1.0000  1.0000
  8   1.0000  1.0000  0.0000
  9   0.0000  0.0000  1.0000
 10   0.0000  1.0000  0.0000
 11   1.0000  1.0000  1.0000
 12   1.0000  1.0000  1.0000

 Cochrans Q test statistic =       2.8000
 Degrees of freedom =    2.0
 Upper-tail probability =       0.2466


g08bafe.r

 G08BAF Example Program Results

 Mood's test and David's test

 Data values

 Group 1
   6.  9. 12.  4. 10. 11.

 Group 2
   8.  1.  3.  7.  2.  5.

     Mood's measure  =   75.500   Significance =   0.5830
     David's measure =    9.467   Significance =   0.1986


g08cbfe.r

 G08CBF Example Program Results

 K-S Test
 Distribution: N
 Parameters  :   0.6967  0.2564

 Test statistic D =   0.1108
 Z statistic      =   0.6068
 Tail probability =   0.8925


g08ccfe.r

 G08CCF Example Program Results

 Test against normal distribution with mean = 0.75
 and standard deviation = 0.5.

 Test statistic D =   0.1439
 Z statistic      =   0.7882
 Tail probability =   0.5262


g08cdfe.r

 G08CDF Example Program Results

 Test statistic D =   0.1800
 Z statistic      =   0.0312
 Tail probability =   0.2222


g08cgfe.r

 G08CGF Example Program Results

 Chi-squared test statistic   =    14.2000
 Degrees of freedom.          =     4
 Significance level           =     0.0067

 The contributions to the test statistic are :-
     3.2000
     6.0500
     0.4500
     4.0500
     0.4500


g08chfe.r

 G08CHF Example Program Results

 H0: data from exponential distribution with mean 0.1524E+01
 Test statistic, A-squared:    0.1616
 Upper tail probability:       0.9798


g08cjfe.r

 G08CJF Example Program Results

 H0: data from exponential distribution with mean 0.1650E+01
 Test statistic, A-squared:    0.1830
 Upper tail probability:       0.9945


g08ckfe.r

 G08CKF Example Program Results

 H0: data from Normal distribution with mean 0.5639E+00 and variance 0.1139E+01
 Test statistic, A-squared:    0.1660
 Adjusted A-squared:           0.1713
 Upper tail probability:       0.9312


g08clfe.r

 G08CLF Example Program Results

 H0: data from exponential distribution with mean 0.1524E+01
 Test statistic, A-squared:    0.1616
 Adjusted A-squared:           0.1654
 Upper tail probability:       0.9831


g08dafe.r

 G08DAF Example Program Results

 Kendall's coefficient of concordance

 Data values

 Comparison 1 scores    1.0  4.5  2.0  4.5  3.0  7.5  6.0  9.0  7.5 10.0
 Comparison 2 scores    2.5  1.0  2.5  4.5  4.5  8.0  9.0  6.5 10.0  6.5
 Comparison 3 scores    2.0  1.0  4.5  4.5  4.5  4.5  8.0  8.0  8.0 10.0

 Kendall's coefficient =   0.828
           Significance =   0.008


g08ebfe.r

 G08EBF Example Program Results

 Count matrix
     1  2  3  4  5
 1   7 10  5 16  8
 2   9 10  7  6  8
 3  13 15 10 10 12
 4  10 21  7  5 13
 5  13  5 10 12  8

 Expected value =    10.00
 CHISQ          =    34.8000
 DF             =    24.00
 Probability    =     0.0714


g08ecfe.r

 G08ECF Example Program Results

 Count matrix

  I =  1
     1  2
 1  22 25
 2  18 17

  I =  2
     1  2
 1  23 24
 2  24 13

 Expected value =    20.75
 CHISQ          =     6.1446
 DF             =     7.00
 Prob           =     0.5230


g08edfe.r

 G08EDF Example Program Results

 Total number of gaps found =         99

 Count
       0      1      2      3      4      5      6      7      8     >9
      22     11     10     13      6     12      4      6      2     13

 Expect
       0      1      2      3      4      5      6      7      8     >9
    19.8   15.8   12.7   10.1    8.1    6.5    5.2    4.2    3.3   13.3

 Chisq =     9.9540
 DF    =     9.0
 Prob  =     0.3542


g08rafe.r

 G08RAF Example Program Results

 Number of samples = 1
 Number of parameters fitted = 2
 Distribution = 2
 Tolerance for ties = 0.00001

 Score statistic
    -1.048   64.333

 Covariance matrix of score statistic
     0.673
    -4.159  533.670

 Parameter estimates
    -0.852    0.114

 Covariance matrix of parameter estimates
     1.560
     0.012    0.002

 Chi-squared statistic =    8.221 with 2 d.f.

 Standard errors of estimates and
 approximate z-statistics
     1.249        -0.682
     0.044         2.567


g08rbfe.r

 G08RBF Example Program Results

 Number of samples = 1
 Number of parameters fitted = 1
 Distribution power parameter =   0.00001
 Tolerance for ties =   0.00001

 Score statistic
     4.584

 Covariance matrix of score statistic
     7.653

 Parameter estimates
     0.599

 Covariance matrix of parameter estimates
     0.131

 Chi-squared statistic =    2.746 with 1 d.f.

 Standard errors of estimates and
 approximate z-statistics
     0.361         1.657


g10zafe.r

 G10ZAF Example Program Results

 Number of distinct observations =      6
 Residual sum of squares         =       7.00000

              X                 Y                 WT
           1.00000           4.00000           1.00000
           3.00000           4.50000           2.00000
           4.00000           3.00000           1.00000
           5.00000           1.50000           2.00000
           6.00000           9.00000           1.00000
           9.00000           5.00000           3.00000


g11aafe.r

  G11AAF Example Program Results

 Probability = 0.0975
 Pearson Chi-square statistic =    7.844
 Likelihood ratio test statistic =    8.096
 Degrees of freedom =   4.


g11bafe.r

 G11BAF Example Program Results

  TABLE

   235.33( 3)  342.67( 3)  309.33( 3)  395.00( 3)  373.33( 3)  350.00( 3)
   332.67( 3)  341.67( 3)  370.33( 3)  370.33( 3)  326.67( 3)  381.00( 3)
   196.33( 3)  332.67( 3)  320.33( 3)  338.00( 3)  292.33( 3)  351.00( 3)


g11bbfe.r

 G11BBF Example Program Results

 TABLE for  50.th percentile

   226.00( 3)  320.25( 3)  299.50( 3)  385.75( 3)  348.00( 3)  334.75( 3)
   329.25( 3)  343.25( 3)  365.25( 3)  370.50( 3)  327.25( 3)  378.00( 3)
   185.50( 3)  328.75( 3)  319.50( 3)  339.25( 3)  286.25( 3)  350.25( 3)


g11bcfe.r

 G11BCF Example Program Results

  Marginal Table

  235.33  332.67  196.33
  342.67  341.67  332.67
  309.33  370.33  320.33
  395.00  370.33  338.00
  373.33  326.67  292.33
  350.00  381.00  351.00


g11cafe.r

 G11CAF Example Program Results

 Deviance =    0.5475E+01

  Strata     No. Cases   No. Controls

     1           2           2
     2           1           2

  Parameter      Estimate       Standard Error

     1           -0.5223            1.3901
     2           -0.2674            0.8473


g11safe.r

 G11SAF Example Program Results

 LOG LIKELIHOOD KERNEL ON EXIT =   -0.24039E+04

 MAXIMUM LIKELIHOOD ESTIMATES OF ITEM PARAMETERS ARE AS FOLLOWS
 --------------------------------------------------------------

 ITEM J     ALPHA(J)         S.E.       ALPHA(J,0)         PI(J)          S.E.
 ------     --------         ----       ----------         -----          ----

    1        1.045          0.148         -1.276           0.218         0.017

    2        1.409          0.179          0.424           0.604         0.022

    3        2.659          0.525          1.615           0.834         0.036

    4        1.122          0.140         -0.062           0.485         0.020

 EXPECTED (AND OBSERVED) PERCENTAGE OF CASES PRODUCING
 POSITIVE RESPONSES FOR INDIVIDUAL AND PAIRS OF ITEMS
 -----------------------------------------------------

                                         ITEM
                                         ----

 ITEM      1     2     3     4
 ----      -     -     -     -
   1     25.9
        (25.9)
   2     19.1  57.7
        (19.1)(57.7)
   3     22.5  48.0  69.4
        (22.6)(48.1)(69.5)
   4     16.4  33.9  40.6  48.8
        (16.3)(33.9)(40.7)(48.8)

 OBSERVED   EXPECTED   THETA   COMPONENT   RAW    SCORE
 FREQUENCY  FREQUENCY  SCORE   SCORE       SCORE  PATTERN
 ---------  ---------  -----   ---------   -----  -------

    154      147.061  -1.273     0.000       0    FFFF
     11       13.444  -0.873     1.045       1    TFFF
     42       42.420  -0.846     1.122       1    FFFT
     49       54.818  -0.747     1.409       1    FTFF
      2        5.886  -0.494     2.167       2    TFFT
     10        8.410  -0.399     2.455       2    TTFF
     27       27.511  -0.374     2.531       2    FTFT
     84       92.062  -0.332     2.659       1    FFTF
     10        6.237  -0.019     3.577       3    TTFT
     25       21.847   0.027     3.705       2    TFTF
     75       73.835   0.055     3.781       2    FFTT
    129      123.766   0.162     4.069       2    FTTF
     30       26.899   0.466     4.826       3    TFTT
     50       50.881   0.591     5.114       3    TTTF
    181      179.564   0.626     5.190       3    FTTT
    121      125.360   1.144     6.236       4    TTTT
 ---------  ---------
   1000     1000.000

 LIKELIHOOD RATIO GOODNESS OF FIT STATISTIC =      9.027
                         SIGNIFICANCE LEVEL =      0.251
 (BASED ON   7 DEGREES OF FREEDOM)

 Value of IFAIL parameter on exit from G11SAF =     0


g11sbfe.r

 G11SBF Example Program Results

 Frequency     Score pattern

     4             F F F
     1             F T F
     1             T T T
     2             F F T
     1             T T F
     1             F T T


g12aafe.r

 G12AAF Example Program Results

   Time   Survival    Standard
         probability  deviation

    6.0     0.857       0.076
    7.0     0.807       0.087
   10.0     0.753       0.096
   13.0     0.690       0.107
   16.0     0.627       0.114
   22.0     0.538       0.128
   23.0     0.448       0.135


g12abfe.r

 G12ABF Example Program Results

           Observed  Expected
 Group 1    14.00     22.48
 Group 2    28.00     19.52

 No. Unique Failure Times =   36

 Test Statistic           =    7.4966
 Degrees of Freedom       =    1
 p-value                  =    0.0062


g12bafe.r

 G12BAF Example Program Results

  Parameter      Estimate       Standard Error

     1           -1.5091            0.4096

 Deviance =    0.1728E+03

     Time     Survivor Function

        1.       0.9640
        2.       0.9264
        3.       0.9065
        4.       0.8661
        5.       0.8235
        6.       0.7566
        7.       0.7343
        8.       0.6506
       10.       0.6241
       11.       0.5724
       12.       0.5135
       13.       0.4784
       15.       0.4447
       16.       0.4078
       17.       0.3727
       22.       0.2859
       23.       0.1908


g12zafe.r

 G12ZAF Example Program Results

  Parameter      Estimate       Standard Error

     1            1.6282            0.4331


g13aafe.r

 G13AAF Example Program Results

 Non-seasonal differencing of order 2 and seasonal differencing
 of order 1 with seasonality 4 are applied

 The output array holds 20 values, of which the first 14 are differenced values

     -11.0    -10.0     -8.0      4.0     12.0
      -2.0     18.0      9.0     -4.0     -6.0
      -5.0     -2.0    -12.0      5.0      2.0
     -10.0    -13.0     17.0      6.0    105.0


g13abfe.r

 G13ABF Example Program Results

 The first 10 coefficients are required
 The input array has sample mean      37.4180
 The input array has sample variance    1002.0301
 The sample autocorrelation coefficients are

    Lag    Coeff      Lag    Coeff
      1    0.8004       2    0.4355
      3    0.0328       4   -0.2835
      5   -0.4505       6   -0.4242
      7   -0.2419       8    0.0550
      9    0.3783      10    0.5857

 The value of STAT is      92.1231


g13acfe.r

 G13ACF Example Program Results

 Lag  Partial    Predictor error  Autoregressive
      autocorrn  variance ratio   parameter

  1    0.800           0.359         1.108
  2   -0.571           0.242        -0.290
  3   -0.239           0.228        -0.193
  4   -0.049           0.228        -0.014
  5   -0.032           0.228        -0.032


g13adfe.r

 G13ADF Example Program Results

 Parameter estimation success/failure indicator   0   1   0   1

 ARIMA model parameter values    0.37390   0.51237

 Residual variance   0.00148


g13aefe.r

 G13AEF Example Program Results

 Convergence was achieved after 16 cycles

 Final values of the PAR parameters and the constant are as follows
    -0.0547   -0.5568   -0.6636    9.9807

 Residual sum of squares is  9397.924  with  25 degrees of freedom

 The final values of ZSP were
      0.1000E-14     0.1000E+02     0.1000E+04     0.1000E-03

 The number of parameters estimated was    6
 ( backward forecasts, PAR and C, in that order )

 The corresponding G array holds
   -0.1512  -0.2343  -6.4097  13.5617 -72.6232  -0.1642

 The corresponding SD array holds
   14.8379  15.1887   0.3507   0.2709   0.1695   7.3893

 Corresponding H matrix
               1            2            3            4            5
 1    1.9416E+00  -6.1794E-01   2.4409E-01   1.7942E+00  -8.3579E-01
 2    3.4176E-01   1.9446E+00  -1.6544E-01  -2.5084E-01   1.7952E+00
 3   -1.0544E-02   5.5643E-03   9.0416E+03  -9.6825E+03   5.4626E+02
 4   -1.2113E-02   5.6011E-03   8.1322E-01   1.7031E+04  -5.6761E+03
 5   -2.3216E-03  -1.1495E-03   3.6741E-01   4.7942E-01   1.7028E+04
 6   -1.4580E-01  -2.6004E-01  -4.0877E-02  -4.8389E-02  -3.7442E-02

               6
 1    2.4106E-01
 2    8.5926E-01
 3    8.1847E-01
 4    6.9417E+00
 5    6.3308E+00
 6    7.4339E+00
 Holds second derivatives in the upper half (including the main diagonal)
 and correlation coefficients in the lower triangle

 EX, EXR, and AL each hold   32 values made up of    2 back forecast(s),
    29 differenced values, and
     1 element(s) of reconstituted information

   EX
     19.5250     5.8753    40.0000    11.0000    30.0000
     26.0000    15.0000    31.0000    27.0000    23.0000
    -11.0000   -26.0000   -11.0000   -11.0000   -15.0000
    -25.0000    -7.0000    37.0000    50.0000    14.0000
     40.0000    -4.0000    27.0000     0.0000    34.0000
     10.0000    34.0000     4.0000   -12.0000   -29.0000
    -21.0000    64.0000

   EXR
     19.5250    -3.9279    19.5711    -5.6291    10.2221
     15.1582    -9.3276    16.4285    15.2115    -5.4211
    -27.3444   -18.3061     5.3890   -12.9812   -22.4767
    -15.2183     4.4944    33.6867    19.7586   -27.1470
     32.2426   -12.2765     1.6941    -1.8465    23.3772
    -10.4576    14.3302    -5.7061   -28.6401   -20.4502
     -2.7215     0.0000

   AL
     19.5250     5.8753    30.0193     1.0193    20.0193
     16.0193     5.0193    21.0193    17.0193    13.0193
    -20.9807   -35.9807   -20.9807   -20.9807   -24.9807
    -34.9807   -16.9807    27.0193    40.0193     4.0193
     30.0193   -13.9807    17.0193    -9.9807    24.0193
      0.0193    24.0193    -5.9807   -21.9807   -38.9807
    -30.9807     0.0000

 The state set consists of  4 values
     64.0000   -30.9807   -20.4502    -2.7215


g13affe.r

 G13AFF Example Program Results

 Convergence was achieved after  25 cycles

 Final values of the PAR parameters and the constant are as follows
    -0.0543   -0.5548   -0.6734    9.9848

 Residual sum of squares is  9397.220  with  25 degrees of freedom

 The corresponding SD array holds
    0.3457   0.2636   0.1665   7.4170

 The correlation matrix is as follows
          1       2       3       4
 1   1.0000  0.8072  0.3548 -0.0404
 2   0.8072  1.0000  0.4681 -0.0491
 3   0.3548  0.4681  1.0000 -0.0376
 4  -0.0404 -0.0491 -0.0376  1.0000

 The residuals consist of  29 values
    19.6275   -5.3093    9.7983   15.2412   -9.1693
    16.1107   15.3929   -5.4500  -27.6205  -18.1306
     5.7202  -13.0881  -22.7151  -14.9256    4.6930
    33.5406   19.7138  -27.3360   32.1231  -11.7681
     1.1524   -1.7756   23.6821  -10.6238   13.9619
    -5.2727  -28.7868  -20.6573   -2.2555

 The state set consists of  4 values
      64.000    -30.985    -20.657     -2.256


g13agfe.r

 G13AGF Example Program Results

 The updated state set array now holds the values
   0.0660 -0.0513  0.1716 -0.0250  0.0589  0.1167  0.1493  0.0198
  -0.1884 -0.1289 -0.1172  0.1123  6.0039  0.0444 -0.0070  0.0253
   0.0019  0.0354 -0.0460  0.0374  0.0151 -0.0237  0.0032  0.0188
   0.0067  0.0126

 The residuals corresponding to the 12
 values used to update the system are
   0.0309  0.0031  0.0263  0.0105  0.0388 -0.0333  0.0265  0.0238
  -0.0159 -0.0020  0.0182  0.0126


g13ahfe.r

 G13AHF Example Program Results

 The required 12 forecast values are as follows
   6.0381  5.9912  6.1469  6.1207  6.1574  6.3029  6.4288  6.4392
   6.2657  6.1348  6.0059  6.1139

 The standard deviations corresponding to the forecasts are
   0.0374  0.0451  0.0517  0.0575  0.0627  0.0676  0.0721  0.0764
   0.0805  0.0843  0.0880  0.0915


g13ajfe.r

 G13AJF Example Program Results

 The residual mean square is    375.91

 The state set consists of 4 values
     64.0000   -30.9807   -20.4495    -2.7212

 The  5 forecast values and standard errors are -
               60.59     19.39
               69.50     34.99
               79.54     54.25
               89.51     67.87
               99.50     79.20


g13amfe.r

 G13AMF Example Program Results

 Initial values used:
   1      168.018
   2        3.800

Mean Deviation     =   0.2547E+02
Absolute Deviation =   0.2123E+02

          Observed      1-Step
  Period   Values      Forecast      Residual

   1      180.000      171.818        8.182
   2      135.000      175.782      -40.782
   3      213.000      178.848       34.152
   4      181.000      183.005       -2.005
   5      148.000      186.780      -38.780
   6      204.000      189.800       14.200
   7      228.000      193.492       34.508
   8      225.000      197.732       27.268
   9      198.000      202.172       -4.172
  10      200.000      206.256       -6.256
  11      187.000      210.256      -23.256

          Forecast     Standard
  Period   Values       Errors

  12      213.854       25.473
  13      217.685       25.478
  14      221.516       25.490
  15      225.346       25.510
  16      229.177       25.542


g13asfe.r

 G13ASF Example Program Results

 RESIDUAL AUTOCORRELATION FUNCTION
 ---------------------------------

 LAG  K      1      2      3      4      5      6      7
 R(K)      0.020 -0.040 -0.019  0.068 -0.143 -0.046 -0.205
 ST.ERROR  0.007  0.125  0.128  0.150  0.168  0.168  0.178
 ---------------------------------------------------------
 LAG  K      8      9     10
 R(K)     -0.108 -0.001 -0.058
 ST.ERROR  0.179  0.181  0.183
 ---------------------------------------------------------

 BOX - LJUNG PORTMANTEAU STATISTIC =      3.465
                SIGNIFICANCE LEVEL =      0.839
 (BASED ON   7 DEGREES OF FREEDOM)

 VALUE OF IFAIL PARAMETER ON EXIT FROM G13ASF =   0


g13aufe.r

 G13AUF Example Program Results

      Mean      Range
    -------------------
     72.375    148.000
     70.000    123.000
     43.500     84.000
     29.750     45.000
      7.625     28.000
     26.750     40.000
     30.250     65.000
     61.000    131.000
     47.625     92.000
     75.250     85.000
     46.875     92.000
     39.250     67.000


g13awfe.r

 G13AWF Example Program Results

Dickey-Fuller test statistic     = -2.540
associated p-value               =  0.013


g13bcfe.r

 G13BCF Example Program Results

                            Between        Between
                            X and Y        Y and X

 Standard deviation ratio    2.0053         0.4987

 Cross correlation at lag
                        0    0.0568         0.0568
                        1    0.0438        -0.0151
                        2   -0.3762         0.3955
                        3   -0.4864         0.3417
                        4   -0.6294         0.5486
                        5   -0.3871         0.2291
                        6   -0.1690         0.3190
                        7   -0.0678         0.1980
                        8    0.0962         0.0438
                        9    0.0788        -0.1428
                       10    0.2910        -0.1376
                       11    0.0950        -0.0387
                       12    0.0547        -0.0380
                       13    0.1855        -0.1551
                       14    0.0243        -0.1536
                       15    0.0034        -0.0696

 Test statistic             22.1269        17.2917


g13bdfe.r

 G13BDF Example Program Results

 Success/failure indicator   1   1

 Transfer function model B, Q, P =   3   2   1

 Parameter initial estimates
    -0.5575    0.3166    0.4626    0.6169


g13bgfe.r

 G13BGF Example Program Results

 The updated state set
     6.7160  158.3155  -80.3412  -74.9035  -80.7814  -70.3155
     0.8416   -2.0333   -5.8201   10.2810

 The residuals (after differencing)
    1    1.4586
    2   -2.4674
    3   -4.7714
    4   13.2830

 The values of z(t) and n(t)
             1          2
 1    176.3412   -80.3412
 2    169.9035   -74.9035
 3    160.7814   -80.7814
 4    158.3155   -70.3155
 The first 1 columns hold the z(t) and the last column the n(t)


g13bhfe.r

 G13BHF Example Program Results

 The forecast values and their standard errors

    I     FVA       FSD

    1   88.2723    4.7881
    2   99.9425    6.4690
    3  100.6499    7.3175
    4   95.0958    7.5534

 The values of z(t) and n(t)
             1          2
 1    164.4620   -76.1897
 2    170.3924   -70.4499
 3    174.5193   -73.8694
 4    175.2747   -80.1789
 The first 1 columns hold the z(t) and the last column the n(t)


g13cbfe.r

 G13CBF Example Program Results

 Frequency width of smoothing window = 1/30
 Degrees of freedom = 7.0      Bandwidth = 0.1767

 95 percent confidence limits -   Lower = -0.8275  Upper =  1.4213

       Spectrum       Spectrum       Spectrum       Spectrum
       estimate       estimate       estimate       estimate
    1   -0.1776    2   -0.4561    3   -0.1784    4    1.9042
    5    2.1094    6    1.7061    7   -0.7659    8   -1.4734
    9   -1.5939   10   -2.1157   11   -2.9151   12   -2.7055
   13   -2.8200   14   -3.4077   15   -3.8813   16   -3.6607
   17   -4.0601   18   -4.4756   19   -4.2700   20   -4.3092
   21   -4.5711   22   -4.8111   23   -4.5658   24   -4.7285
   25   -5.4386   26   -5.5081   27   -5.2325   28   -5.0262
   29   -4.4539   30   -4.4764   31   -4.9152   32   -5.8492
   33   -5.5872   34   -4.9804   35   -4.8904   36   -5.2666
   37   -5.7643   38   -5.8620   39   -5.5011   40   -5.7129
   41   -6.3894   42   -6.4027   43   -6.1352   44   -6.5766
   45   -7.3676   46   -7.1405   47   -6.1674   48   -5.8600
   49   -6.1036   50   -6.2673   51   -6.4321


g13cefe.r

 G13CEF Example Program Results

       Cross amplitude spectrum

                     Lower     Upper
           Value     bound     bound
     0    6.5499    3.9277   10.9228
     1    1.2382    0.7364    2.0820
     2    0.1299    0.0755    0.2236
     3    0.0099    0.0049    0.0197
     4    0.0005    0.0001    0.0017
     5    0.0004    0.0001    0.0015
     6    0.0003    0.0001    0.0010
     7    0.0002    0.0001    0.0007
     8    0.0001    0.0000    0.0018

 Squared coherency test statistic =      0.1926

          Squared coherency

                     Lower     Upper
           Value     bound     bound
     0    0.9593    0.9185    0.9799
     1    0.9018    0.8093    0.9507
     2    0.7679    0.5811    0.8790
     3    0.3674    0.1102    0.6177
     4    0.0797    0.0000    0.3253
     5    0.0750    0.0000    0.3182
     6    0.1053    0.0000    0.3610
     7    0.0952    0.0000    0.3475
     8    0.0122    0.0000    0.1912


g13cgfe.r

 G13CGF Example Program Results

            Noise spectrum
     0          0.8941
     1          0.3238
     2          0.0668
     3          0.0157
     4          0.0026
     5          0.0019
     6          0.0011
     7          0.0010
     8          0.0019

 Noise spectrum bounds multiplying factors
 Lower =    0.6298     Upper =    1.8291

 Impulse response function

     0         -0.0547
     1          0.0586
     2         -0.0322
     3         -0.6956
     4         -0.7181
     5         -0.8019
     6         -0.4303
     7         -0.2392
     8         -0.0766
     9          0.0657
    10         -0.1652
    11         -0.0439
    12         -0.0494
    13         -0.0384
    14          0.0838
    15         -0.0814

 Impulse response function standard error =    0.0863


g13djfe.r

 G13DJF Example Program Results

  FORECAST SUMMARY TABLE
  ----------------------

  Forecast origin is set at t =   48

 Lead Time                      1         2         3         4         5

 Series  1 : Forecast          7.82      7.28      6.77      6.33      5.95
           : Standard Error    1.72      2.23      2.51      2.68      2.79
 Series  2 : Forecast         10.31      9.25      8.65      8.30      8.10
           : Standard Error    2.32      2.68      2.78      2.82      2.83


g13dkfe.r

 G13DKF Example Program Results

  FORECAST SUMMARY TABLE
  ----------------------

  Forecast origin is set at t =   48

 Lead Time                      1         2         3         4         5

 Series  1 : Forecast          7.82      7.28      6.77      6.33      5.95
           : Standard Error    1.72      2.23      2.51      2.68      2.79
 Series  2 : Forecast         10.31      9.25      8.65      8.30      8.10
           : Standard Error    2.32      2.68      2.78      2.82      2.83

  FORECAST SUMMARY TABLE
  ----------------------

  Forecast origin is set at t =   49

 Lead Time                      1         2         3         4         5

 Series  1 : Forecast          8.10      7.49      6.94      6.46      6.06
           : Standard Error    0.00      1.72      2.23      2.51      2.68
 Series  2 : Forecast         10.20      9.19      8.61      8.28      8.08
           : Standard Error    0.00      2.32      2.68      2.78      2.82

  FORECAST SUMMARY TABLE
  ----------------------

  Forecast origin is set at t =   50

 Lead Time                      1         2         3         4         5

 Series  1 : Forecast          8.10      8.50      7.80      7.18      6.65
           : Standard Error    0.00      0.00      1.72      2.23      2.51
 Series  2 : Forecast         10.20     10.00      9.08      8.54      8.24
           : Standard Error    0.00      0.00      2.32      2.68      2.78


g13dmfe.r

 G13DMF Example Program Results

  THE MEANS
  ---------

       4.370      7.868

  CROSS-CORRELATION MATRICES
  --------------------------

  Lag =  0
           2.818    0.249
           0.249    2.815

  Lag =  1
           0.736    0.174
           0.211    0.555

  Lag =  2
           0.456    0.076
           0.069    0.260

  Lag =  3
           0.379    0.014
           0.026   -0.038

  Lag =  4
           0.322    0.110
           0.093   -0.236

  Lag =  5
           0.341    0.269
           0.087   -0.250

  Lag =  6
           0.363    0.344
           0.132   -0.227

  Lag =  7
           0.280    0.425
           0.207   -0.128

  Lag =  8
           0.248    0.522
           0.197   -0.085

  Lag =  9
           0.240    0.266
           0.254    0.075

  Lag = 10
           0.162   -0.020
           0.267    0.005

  Standard error = 1 / SQRT(N) = 0.144

  TABLES OF INDICATOR SYMBOLS
  ---------------------------

  For Lags 1 to 10

  Auto-correlation function for series  1

                0.005  : *
          +     0.01   : * * *
                0.05   : * * * * * *
     Sig. Level        : - - - - - - - - - -  Lags
                0.05   :
          -     0.01   :
                0.005  :

  Cross-correlation function for series  1 and series 2

                0.005  :               *
          +     0.01   :             * *
                0.05   :           * * *
     Sig. Level        : - - - - - - - - - -  Lags
                0.05   :
          -     0.01   :
                0.005  :

  Cross-correlation function for series  2 and series 1

                0.005  :
          +     0.01   :
                0.05   :
     Sig. Level        : - - - - - - - - - -  Lags
                0.05   :
          -     0.01   :
                0.005  :

  Auto-correlation function for series  2

                0.005  : *
          +     0.01   : *
                0.05   : *
     Sig. Level        : - - - - - - - - - -  Lags
                0.05   :
          -     0.01   :
                0.005  :


g13dnfe.r

 G13DNF Example Program Results

  PARTIAL LAG CORRELATION MATRICES
  --------------------------------

  Lag =  1
           0.736    0.174
           0.211    0.555

  Lag =  2
          -0.187   -0.083
          -0.180   -0.072

  Lag =  3
           0.278   -0.007
           0.084   -0.213

  Lag =  4
          -0.084    0.227
           0.128   -0.176

  Lag =  5
           0.236    0.238
          -0.047   -0.046

  Lag =  6
          -0.016    0.087
           0.100   -0.081

  Lag =  7
          -0.036    0.261
           0.126    0.012

  Lag =  8
           0.077    0.381
           0.027   -0.149

  Lag =  9
          -0.065   -0.387
           0.189    0.057

  Lag = 10
          -0.026   -0.286
           0.028   -0.173

  Standard error = 1 / SQRT(N) = 0.144

  TABLES OF INDICATOR SYMBOLS
  ---------------------------

  For Lags 1 to 10

  Auto-correlation function for series  1

                0.005  : *
          +     0.01   : *
                0.05   : *
     Sig. Level        : - - - - - - - - - -  Lags
                0.05   :
          -     0.01   :
                0.005  :

  Cross-correlation function for series  1 and series 2

                0.005  :
          +     0.01   :               *
                0.05   :               *
     Sig. Level        : - - - - - - - - - -  Lags
                0.05   :                 * *
          -     0.01   :                 *
                0.005  :

  Cross-correlation function for series  2 and series 1

                0.005  :
          +     0.01   :
                0.05   :
     Sig. Level        : - - - - - - - - - -  Lags
                0.05   :
          -     0.01   :
                0.005  :

  Auto-correlation function for series  2

                0.005  : *
          +     0.01   : *
                0.05   : *
     Sig. Level        : - - - - - - - - - -  Lags
                0.05   :
          -     0.01   :
                0.005  :

  Lag     Chi-square statistic     P-value
  ---     --------------------     -------

    1            44.362             0.0000
    2             3.824             0.4304
    3             6.219             0.1834
    4             5.094             0.2778
    5             5.609             0.2303
    6             1.170             0.8830
    7             4.098             0.3929
    8             8.371             0.0789
    9             9.244             0.0553
   10             5.435             0.2455


g13dxfe.r

 G13DXF Example Program Results

         Eigenvalues       Moduli
         -----------       ------
      0.802  +  0.000 i     0.802
      0.575  +  0.000 i     0.575


g13ejfe.r

 G13EJF Example Program Results

  Time           Estimate of State
 ----------------------------------------
   1          0.664     -0.092      0.104
   2          1.598      0.081      0.314
   3          2.128      0.213      0.378
   4          3.134      0.674      0.660
   5          3.809      1.181      0.906
   6          4.730      2.000      1.298
   7          4.429      2.474      1.762
   8          4.357      3.246      2.162
   9          3.907      3.852      2.246
  10          3.360      4.398      2.504
  11          2.552      4.741      2.750
  12          2.191      5.193      3.281
  13          1.309      5.018      3.610
  14          1.071      4.894      4.031
  15          0.618      4.322      4.124

 Estimate of Cholesky Factorization of the State
 Covariance Matrix at the Last Time Point
  0.192E+00
 -0.382E+00  0.222E-01
  0.158E-05  0.223E-06  0.995E-02


g13ekfe.r

 G13EKF Example Program Results

  Time           Estimate of State
 ----------------------------------------
   1          0.664     -0.092      0.104
   2          1.598      0.081      0.314
   3          2.128      0.213      0.378
   4          3.134      0.674      0.660
   5          3.809      1.181      0.906
   6          4.730      2.000      1.298
   7          4.429      2.474      1.762
   8          4.357      3.246      2.162
   9          3.907      3.852      2.246
  10          3.360      4.398      2.504
  11          2.552      4.741      2.750
  12          2.191      5.193      3.281
  13          1.309      5.018      3.610
  14          1.071      4.894      4.031
  15          0.618      4.322      4.124

 Estimate of Cholesky Factorization of the State
 Covariance Matrix at the Last Time Point
  0.192E+00
 -0.382E+00  0.222E-01
  0.158E-05  0.223E-06  0.995E-02


g13fafe.r

 G13FAF Example Program Results

                Parameter        Standard
                estimates         errors
 Alpha0             0.00            0.06
 Alpha1             0.11            0.13

  Beta1             0.66            0.23

  Gamma            -0.62            0.62

     DF             6.25            4.70

     B0             3.85           24.11
     B1             1.48            1.82
     B2             2.15           10.16

 Volatility forecast =         0.09


g13fcfe.r

 G13FCF Example Program Results

                Parameter        Standard
                estimates         errors
 Alpha0             6.82            1.68
 Alpha1             0.00            1.00

  Beta1             0.00            3.17

  Gamma            -0.36            1.01

     DF             2.10            0.33

     B0           -25.14            4.80
     B1            -0.95            0.90
     B2            14.41            2.08

 Volatility forecast =         6.82


g13fefe.r

 G13FEF Example Program Results

                Parameter        Standard
                estimates         errors
 Alpha0             0.08            0.12
 Alpha1             0.00            0.85

  Beta1             0.67            0.19

  Gamma             0.35            0.63

     DF             5.03            5.13

     B0            50.22            3.33
     B1           -18.48            1.43
     B2             6.45            0.54

 Volatility forecast =         0.61


g13fgfe.r

 G13FGF Example Program Results

                Parameter        Standard
                estimates         errors
 Alpha0             0.20            0.16
 Alpha1            -0.65            0.28
 Alpha2            -0.40            0.21
   Psi1            -0.18            0.34
   Psi2             0.54            0.31

  Beta1             0.43            0.19

     DF             4.31            1.02

     B0            29.63            0.98
     B1            -9.91            0.43
     B2             5.57            0.83

 Volatility forecast =         1.44


g13nafe.r

 G13NAF Example Program Results

  -- Change Points --         --- Distribution ---
  Number     Position              Parameters
 ==================================================
    1           12            0.34            1.00
    2           32            2.57            1.00
    3           49            1.45            1.00
    4           52           -0.48            1.00
    5           70            1.20            1.00
    6          100           -0.23            1.00


g13nbfe.r

 G13NBF Example Program Results

  -- Change Points --
  Number     Position
 =====================
    1            5
    2           12
    3           32
    4           70
    5           73
    6          100


g13ndfe.r

 G13NDF Example Program Results

  -- Change Points --         --- Distribution ---
  Number     Position              Parameters
 ==================================================
    1           12            0.34            1.00
    2           32            2.57            1.00
    3           70            1.18            1.00
    4          100           -0.23            1.00


g13nefe.r

 G13NEF Example Program Results

  -- Change Points --
  Number     Position
 =====================
    1            5
    2           12
    3           32
    4           70
    5           73
    6          100


h02bbfe.r

 H02BBF Example Program Results

 *** IP solver

 Parameters
 ----------

 Linear constraints......         3        First integer solution..       OFF
 Variables...............         2        Max depth of the tree...         4

 Feasibility tolerance...  1.05E-08        Print level.............        10
 Infinite bound size.....  1.00E+20        EPS (machine precision).  1.11E-16

 Integer feasibility tol.  1.00E-05        Iteration limit.........        50
 Max number of nodes.....      NONE

 ** Workspace provided with MAXDPT =     4: LRWORK =    84  LIWORK =   137
 ** Workspace required with MAXDPT =     4: LRWORK =    84  LIWORK =   137

   *** Optimum LP solution ***   -17.50000

 Varbl State     Value     Lower Bound   Upper Bound    Lagr Mult   Residual

 V  1    FR    3.92857       0.00000         None        0.000       3.929
 V  2    FR    1.42857       0.00000         None        0.000       1.429

 L Con State     Value     Lower Bound   Upper Bound    Lagr Mult   Residual

 L  1    UL    15.0000         None        15.0000      -1.000       0.000
 L  2    UL    5.00000         None        5.00000     -0.5000     -8.8818E-16
 L  3    FR    14.6429       5.00000         None        0.000       9.643

   *** Start of tree search ***

  Node  Parent   Obj       Varbl  Value      Lower      Upper      Value   Depth
   No    Node   Value      Chosen Before     Bound      Bound      After
    2     1   No Feas Soln    1    3.93       4.00       None       4.00       1
    3     1    -16.2          1    3.93       0.00       3.00       3.00       1
    4     3    -15.5          2    1.80       2.00       None       2.00       2
    5     3    -13.0          2    1.80       0.00       1.00       1.00       2
      *** Integer solution ***

  Node  Parent   Obj       Varbl  Value      Lower      Upper      Value   Depth
   No    Node   Value      Chosen Before     Bound      Bound      After
    6     4   No Feas Soln    1    2.50       3.00       3.00       3.00       3
    7     4    -14.8          1    2.50       0.00       2.00       2.00       3
    8     7    -12.0     CO   2    2.20       3.00       None       3.00       4
    9     7    -14.0          2    2.20       2.00       2.00       2.00       4
      *** Integer solution ***

     *** End of tree search ***

 Total of     9 nodes investigated.

 Exit IP solver - Optimum IP solution found.

 Final IP objective value =   -14.00000

 Varbl State     Value     Lower Bound   Upper Bound    Lagr Mult   Residual

 V  1    UL    2.00000       0.00000       2.00000      -3.000       0.000
 V  2    EQ    2.00000       2.00000       2.00000      -4.000       0.000

 L Con State     Value     Lower Bound   Upper Bound    Lagr Mult   Residual

 L  1    FR    14.0000         None        15.0000       0.000       1.000
 L  2    FR    0.00000         None        5.00000       0.000       5.000
 L  3    FR    10.0000       5.00000         None        0.000       5.000


h02bffe.r

 H02BFF Example Program Results

 *** IP solver

 Parameters
 ----------

 Linear constraints......         3        First integer solution..       OFF
 Variables...............         6        Max depth of the tree...        75

 Feasibility tolerance...  1.05E-08        Print level.............         1
 Infinite bound size.....  1.00E+20        EPS (machine precision).  1.11E-16

 Integer feasibility tol.  1.00E-05        Iteration limit.........        50
 Max number of nodes.....      NONE

 ** Workspace provided with MAXDPT =    75: LRWORK = 10075  LIWORK =  9679
 ** Workspace required with MAXDPT =    75: LRWORK =   677  LIWORK =  2587

 Varbl   State     Value     Lower Bound   Upper Bound    Lagr Mult   Residual

 OATMEAL  EQ    4.00000       4.00000       4.00000       3.000       0.000
 CHICKEN  LL    0.00000       0.00000       3.00000       24.00       0.000
 EGGS     LL    0.00000       0.00000       2.00000       13.00       0.000
 MILK     LL    5.00000       5.00000       8.00000       9.000       0.000
 PIE      EQ    2.00000       2.00000       2.00000       20.00       0.000
 BACON    LL    0.00000       0.00000       2.00000       19.00       0.000

 L Con   State     Value     Lower Bound   Upper Bound    Lagr Mult   Residual

 ENERGY   FR    2080.00       2000.00         None        0.000       80.00
 PROTEIN  FR    64.0000       55.0000         None        0.000       9.000
 CALCIUM  FR    1477.00       800.000         None        0.000       677.0


h02bufe.r

 H02BUF Example Program Results

 Calls to E04MHF
 ---------------

      Print Level = 5

 *** E04MFF

 Parameters
 ----------

 Problem type...........        LP

 Linear constraints.....         3       Feasibility tolerance..  1.05E-08
 Variables..............         6       Optimality tolerance...  1.05E-08

 Infinite bound size....  1.00E+20       COLD start.............
 Infinite step size.....  1.00E+20       EPS (machine precision)  1.11E-16

 Check frequency........        50       Expand frequency.......         5
 Minimum sum of infeas..        NO       Crash tolerance........  1.00E-02

 Print level............         5       Iteration limit........        50
 Monitoring file........        -1

 Workspace provided is     IWORK(     103),  WORK(    5802).
 To solve problem we need  IWORK(      15),  WORK(      89).

  Itn     Step Ninf Sinf/Objective  Norm Gz
    0  0.0E+00    3   1.799000E+03  0.0E+00
    1  1.5E-02    1   2.550000E+02  0.0E+00
    2  1.4E-03    0   1.271429E+02  0.0E+00
    3  8.7E-02    0   1.129048E+02  0.0E+00
    4  2.1E-01    0   1.062857E+02  0.0E+00
    5  1.9E+00    0   9.733333E+01  0.0E+00
    6  2.9E+00    0   9.250000E+01  0.0E+00

 Exit E04MFF - Optimal LP solution.

 Final LP objective value =    92.50000

 Exit from LP problem after     6 iterations.

 Varbl   State     Value     Lower Bound   Upper Bound    Lagr Mult   Residual

 OATMEAL  UL    4.00000       0.00000       4.00000      -3.187       0.000
 CHICKEN  LL    0.00000       0.00000       3.00000       12.47       0.000
 EGGS     LL    0.00000       0.00000       2.00000       4.000       0.000
 MILK     FR    4.50000       0.00000       8.00000       0.000       3.500
 PIE      UL    2.00000       0.00000       2.00000      -3.625       0.000
 BACON    LL    0.00000       0.00000       2.00000       4.375       0.000

 L Con   State     Value     Lower Bound   Upper Bound    Lagr Mult   Residual

 ENERGY   LL    2000.00       2000.00         None       5.6250E-02   0.000
 PROTEIN  FR    60.0000       55.0000         None        0.000       5.000
 CALCIUM  FR    1334.50       800.000         None        0.000       534.5


h02bzfe.r

 H02BZF Example Program Results

 IP objective value =        97.00

 Varbl   State     Value     Lower Bound   Upper Bound    Lagr Mult   Residual

 Oatmeal   EQ      4.000         4.000         4.000       3.000       0.000
 Chicken   LL      0.000         0.000         3.000       24.00       0.000
 Eggs      LL      0.000         0.000         2.000       13.00       0.000
 Milk      LL      5.000         5.000         8.000       9.000       0.000
 Pie       EQ      2.000         2.000         2.000       20.00       0.000
 Bacon     LL      0.000         0.000         2.000       19.00       0.000

 L Con   State     Value     Lower Bound   Upper Bound    Lagr Mult   Residual

 Energy    FR      2080.         2000.        None         0.000       80.00
 Protein   FR      64.00         55.00        None         0.000       9.000
 Calcium   FR      1477.         800.0        None         0.000       677.0

 Increase the energy requirements from   2000.      to   2200.

 IP objective value =        106.0

 Varbl   State     Value     Lower Bound   Upper Bound    Lagr Mult   Residual

 Oatmeal   EQ      4.000         4.000         4.000       3.000       0.000
 Chicken   LL      0.000         0.000         3.000       24.00       0.000
 Eggs      LL      0.000         0.000         2.000       13.00       0.000
 Milk      LL      6.000         6.000         8.000       9.000       0.000
 Pie       EQ      2.000         2.000         2.000       20.00       0.000
 Bacon     LL      0.000         0.000         2.000       19.00       0.000

 L Con   State     Value     Lower Bound   Upper Bound    Lagr Mult   Residual

 Energy    FR      2240.         2200.        None         0.000       40.00
 Protein   FR      72.00         55.00        None         0.000       17.00
 Calcium   FR      1762.         800.0        None         0.000       962.0


h02cbfe.r

 H02CBF Example Program Results
 Optimal Integer Value is =       0.37469662E-01
 Components are
 X(  1) =     -0.01000000
 X(  2) =     -0.07332830
 X(  3) =     -0.00025809
 X(  4) =      0.00000000
 X(  5) =     -0.06335433
 X(  6) =      0.01410944
 X(  7) =      0.00283128


h02ccfe.r

 H02CCF Example Program Results

 Calls to H02CDF
 ---------------

       Print Level = 1
       Check Frequency = 10
       Crash Tolerance = 0.05
       Infinite Bound Size = 1.0D+25

 OPTIONS file
 ------------

      Begin   Example options file for H02CCF
         Feasibility Phase Iteration Limit = 5  *  (Default = 70)
         Optimality Phase Iteration Limit = 10  *  (Default = 70)
      End

 Optimal Integer Value is =       0.37469662E-01
 Components are
 X(  1) =     -0.01000000
 X(  2) =     -0.07332830
 X(  3) =     -0.00025809
 X(  4) =      0.00000000
 X(  5) =     -0.06335433
 X(  6) =      0.01410944
 X(  7) =      0.00283128


h02cefe.r

 H02CEF Example Program Results
 New integer solution found
   Nodes solved so far:                  272
   Reached depth:                   18
   Solution value at current node:  -0.18475E+07
   Solution vector at current node:
     0.00000E+00
     0.35500E+03
     0.64500E+03
     0.16400E+03
     0.41000E+03
     0.27500E+03
     0.15100E+03
   Current best function value:  -0.18475E+07
   Current best solution:
     0.00000E+00
     0.35500E+03
     0.64500E+03
     0.16400E+03
     0.41000E+03
     0.27500E+03
     0.15100E+03
   Current lower bounds:
     0.00000E+00
     0.35500E+03
     0.40000E+03
     0.16400E+03
     0.00000E+00
     0.00000E+00
     0.00000E+00
   Current upper bounds:
     0.20000E+03
     0.35500E+03
     0.64500E+03
     0.16400E+03
     0.15000E+04
     0.10000E+26
     0.10000E+26
 Optimal Integer Value is =      -0.18475180E+07
 Components are
 X(  1) =       0.00
 X(  2) =     355.00
 X(  3) =     645.00
 X(  4) =     164.00
 X(  5) =     410.00
 X(  6) =     275.00
 X(  7) =     151.00


h02cffe.r

 H02CFF Example Program Results

 Calls to H02CGF
 ---------------

       Check Frequency = 10
       Feasibility Tolerance = 0.00001
       Infinite Bound Size = 1.0D+25

 OPTIONS file
 ------------

      Begin
        Iteration Limit = 125 * (Default = 75)
        Print Level = 1      * (Default = 10)
      End
 Optimal Integer Value is =      -0.18475180E+07
 Components are
 X(  1) =       0.00
 X(  2) =     355.00
 X(  3) =     645.00
 X(  4) =     164.00
 X(  5) =     410.00
 X(  6) =     275.00
 X(  7) =     151.00


h02dafe.r

 H02DAF Example Program Results

 Final estimate:
          1
 1   0.3750
 2   0.0000
 3   0.5250
 4   0.1000
 5   1.0000
 6   0.0000
 7   1.0000
 8   1.0000

 Requested accuracy of QP subproblems   0.1000E-09
 Optimised value:    2.925


h03abfe.r

 H03ABF Example Program Results

 Total cost =  77.0

 Goods from  to

   4     3    2
   2     3    3
   1     2    3
   1     1    3
   4     2    1


h03adfe.r

 H03ADF Example Program Results

 Shortest path =  1  to  4  to  6  to  8  to  9  to 11

 Length of shortest path =      15.0000


h03bbfe.r

 H03BBF Example Program Results

 Initial search end cost:   432459.00
 Search best cost       :   237068.00
 Initial temperature    :   598481.00
 Lower bound            :   106350.00
 Termination mode       :           3

 Final cost             :   131580.00

 Final Path:
 Oxford --> Cambridge
        --> Birmingham
        --> Glasgow
        --> Stirling
        --> Edinburgh
        --> Perth
        --> Dundee
        --> Aberdeen
        --> Inverness
        --> Holyhead
        --> Dublin
        --> Bangor
        --> St.Asaph
        --> Aberystwyth
        --> St.Davids
        --> Swansea
        --> Cardiff
        --> Newport
        --> Exeter
        --> Plymouth
        --> Oxford


h05aafe.r

 H05AAF Example Program Results

     Score        Feature Subset
     -----        --------------
  0.10475E+04     4     7     8    10    14
  0.10599E+04     4     5     7     8    14
  0.10702E+04     4     5     7    10    14

 45 subsets evaluated in total


h05abfe.r

 H05ABF Example Program Results

     Score        Feature Subset
     -----        --------------
  0.10475E+04     4     7     8    10    14
  0.10599E+04     4     5     7     8    14
  0.10702E+04     4     5     7    10    14

 45 subsets evaluated in total


m01cafe.r

 M01CAF Example Program Results

 Sorted numbers

     0.5    0.5    1.1    1.2    1.3    1.3    2.1    2.3    2.3    4.1
     5.8    5.9    6.5    6.5    8.6    9.9


m01cbfe.r

 M01CBF Example Program Results

 Sorted numbers

     999    112     99     96     90     78     78     69     69     67
      45     45     45     24     23      1


m01ccfe.r

 M01CCF Example Program Results

 Records sorted on columns  7  to 12

 C05AZF  2181
 C05AUF  1351
 C02AEF   599
 A02ACF   531
 A02ABF   523
 A02AAF   289
 C05AVF   240
 C05AXF   211
 C05AYF   183
 C02ADF   169
 C05AWF   136


m01dafe.r

 M01DAF Example Program Results

    Data   Ranks

     5.3      7
     4.6      6
     7.8     10
     1.7      2
     5.3      8
     9.9     12
     3.2      3
     4.3      4
     7.8     11
     4.5      5
     1.2      1
     7.6      9


m01dbfe.r

 M01DBF Example Program Results

    Data   Ranks

      34      9
      44      8
      89      2
      64      7
      69      4
      69      5
      23     10
       1     12
     999      1
      65      6
      22     11
      76      3


m01dcfe.r

 M01DCF Example Program Results

 Records ranked on columns  7  to 12

 Data            Ranks

 A02AAF   289      6
 A02ABF   523      5
 A02ACF   531      4
 C02ADF   169     10
 C02AEF   599      3
 C05AUF  1351      2
 C05AVF   240      7
 C05AWF   136     11
 C05AXF   211      8
 C05AYF   183      9
 C05AZF  2181      1


m01defe.r

 M01DEF Example Program Results

 Data                        Ranks

     6.0    5.0    4.0         11
     5.0    2.0    1.0          9
     2.0    4.0    9.0          3
     4.0    9.0    6.0          7
     4.0    9.0    5.0          6
     4.0    1.0    2.0          5
     3.0    4.0    1.0          4
     2.0    4.0    6.0          2
     1.0    6.0    4.0          1
     9.0    3.0    2.0         12
     6.0    2.0    5.0         10
     4.0    9.0    6.0          8


m01dffe.r

 M01DFF Example Program Results

 Data                        Ranks

       6      5      4          2
       5      2      1          4
       2      4      9         10
       4      9      6          5
       4      9      5          7
       4      1      2          8
       3      4      1          9
       2      4      6         11
       1      6      4         12
       9      3      2          1
       6      2      5          3
       4      9      6          6


m01djfe.r

 M01DJF Example Program Results

 Data

    5.0   4.0   3.0   2.0   2.0   1.0   9.0   4.0   4.0   2.0   2.0   1.0
    3.0   8.0   2.0   5.0   5.0   6.0   9.0   8.0   9.0   5.0   4.0   1.0
    9.0   1.0   6.0   1.0   2.0   4.0   8.0   1.0   2.0   2.0   6.0   2.0

 Ranks

     11     8     7     4     5     2    12     9    10     6     3     1


m01dkfe.r

 M01DKF Example Program Results

 Data

      5     4     3     2     2     1     9     4     4     2     2     1
      3     8     2     5     5     6     9     8     9     5     4     1
      9     1     6     1     2     4     8     1     2     2     6     2

 Ranks

      2     4     6     9     7    11     1     5     3     8    10    12


m01dzfe.r

 M01DZF Example Program Results

    Data in sorted order

      -2    7.0
      -1    6.0
      -1    2.0
       0    4.0
       0    5.0
       1    0.0
       1    3.0
       1    4.0
       1    5.0
       2    1.0
       2    2.0
       2    3.0


m01eafe.r

 M01EAF Example Program Results

 Matrix sorted on column  1

     1.0    6.0    4.0
     2.0    4.0    9.0
     2.0    4.0    6.0
     3.0    4.0    1.0
     4.0    9.0    6.0
     4.0    9.0    5.0
     4.0    1.0    2.0
     4.0    9.0    6.0
     5.0    2.0    1.0
     6.0    5.0    4.0
     6.0    2.0    5.0
     9.0    3.0    2.0


m01ebfe.r

 M01EBF Example Program Results

 Matrix sorted on column  1

       1      6      4
       2      4      9
       2      4      6
       3      4      1
       4      9      6
       4      9      5
       4      1      2
       4      9      6
       5      2      1
       6      5      4
       6      2      5
       9      3      2


m01ecfe.r

 M01ECF Example Program Results

 Names in order of frequency

 C05AZF
 C05AUF
 C02AEF
 A02ACF
 A02ABF
 A02AAF
 C05AVF
 C05AXF
 C05AYF
 C02ADF
 C05AWF


m01nafe.r

 M01NAF Example Program Results

 Reference Vector is:
     0.5    0.6    1.1    1.2    1.3    1.3    2.1    2.3
     2.3    4.1    5.8    5.9    6.5    6.5    8.6    9.9

 Search for item     2.1 returned index:    7

 Search for item     0.4 returned index:    0

 Search for item     7.1 returned index:   14

 Search for item    10.0 returned index:   16


m01nbfe.r

 M01NBF Example Program Results

 Reference Vector is:
     5    6   11   12   13   13   21   23
    23   41   58   59   65   65   86   99

 Search for item    21 returned index:    7

 Search for item     4 returned index:    0

 Search for item    71 returned index:   14

 Search for item   100 returned index:   16


m01ncfe.r

 M01NCF Example Program Results

 Reference Vector is:
 A02AAF A02ABF A02ACF C02ADF C02AEF C05AUF C05AVF C05AWF C05AXF C05AYF

 Search for item C02ADF returned index:    4

 Search for item A01AAF returned index:    0

 Search for item C04AYF returned index:    5

 Search for item D01NBF returned index:   10


m01zafe.r

 M01ZAF Example Program Results

 Matrix sorted by rows

     1.0    6.0    4.0
     2.0    4.0    6.0
     2.0    4.0    9.0
     3.0    4.0    1.0
     4.0    1.0    2.0
     4.0    9.0    5.0
     4.0    9.0    6.0
     4.0    9.0    6.0
     5.0    2.0    1.0
     6.0    2.0    5.0
     6.0    5.0    4.0
     9.0    3.0    2.0


m01zbfe.r

 M01ZBF Example Program Results

 Numbers in rank order

     1.2    1.7    3.2    4.3    4.5    4.6    5.3    5.3    7.6    7.8
     7.8    9.9


m01zcfe.r

 M01ZCF Example Program Results

 Matrix sorted on row  3

    4.0   2.0   4.0   2.0   4.0   2.0   1.0   1.0   3.0   2.0   9.0   5.0
    8.0   5.0   8.0   5.0   9.0   5.0   1.0   6.0   2.0   4.0   9.0   3.0
    1.0   1.0   1.0   2.0   2.0   2.0   2.0   4.0   6.0   6.0   8.0   9.0


s01bafe.r

 S01BAF Example Program Results

        X           Y
   2.5000E+00  1.2528E+00
   1.2500E-01  1.1778E-01
  -9.0600E-01 -2.3645E+00
   1.2900E-03  1.2892E-03
  -7.8300E-06 -7.8300E-06
   1.0000E-09  1.0000E-09


s01eafe.r

 S01EAF Example Program Results

               Z                              exp(Z)
 (      1.0000,      0.0000)      (      2.7183,      0.0000)
 (     -0.5000,      2.0000)      (     -0.2524,      0.5515)
 (      0.0000,     -2.0000)      (     -0.4161,     -0.9093)
 (     -2.5000,     -1.5000)      (      0.0058,     -0.0819)


s07aafe.r

 S07AAF Example Program Results

      X           Y

   -2.000E+00   2.185E+00
   -5.000E-01  -5.463E-01
    1.000E+00   1.557E+00
    3.000E+00  -1.425E-01
    1.571E+00  -2.722E+05


s09aafe.r

 S09AAF Example Program Results

      X           Y

   -5.000E-01  -5.236E-01
    1.000E-01   1.002E-01
    9.000E-01   1.120E+00


s09abfe.r

 S09ABF Example Program Results

      X           Y

   -5.000E-01   2.094E+00
    1.000E-01   1.471E+00
    9.000E-01   4.510E-01


s10aafe.r

 S10AAF Example Program Results

      X           Y

   -2.000E+01  -1.000E+00
   -5.000E+00  -9.999E-01
    5.000E-01   4.621E-01
    5.000E+00   9.999E-01


s10abfe.r

 S10ABF Example Program Results

      X           Y

   -1.000E+01  -1.101E+04
   -5.000E-01  -5.211E-01
    0.000E+00   0.000E+00
    5.000E-01   5.211E-01
    2.500E+01   3.600E+10


s10acfe.r

 S10ACF Example Program Results

      X           Y

   -1.000E+01   1.101E+04
   -5.000E-01   1.128E+00
    0.000E+00   1.000E+00
    5.000E-01   1.128E+00
    2.500E+01   3.600E+10


s11aafe.r

 S11AAF Example Program Results

      X           Y

   -5.000E-01  -5.493E-01
    0.000E+00   0.000E+00
    5.000E-01   5.493E-01
   -9.999E-01  -4.952E+00


s11abfe.r

 S11ABF Example Program Results

      X           Y

   -2.000E+00  -1.444E+00
   -5.000E-01  -4.812E-01
    1.000E+00   8.814E-01
    6.000E+00   2.492E+00


s11acfe.r

 S11ACF Example Program Results

      X            Y

    1.000E+00   0.000E+00
    2.000E+00   1.317E+00
    5.000E+00   2.292E+00
    1.000E+01   2.993E+00


s13aafe.r

 S13AAF Example Program Results

      X           Y

    2.000E+00   4.890E-02
   -1.000E+00  -1.895E+00


s13acfe.r

 S13ACF Example Program Results

      X           Y

    2.000E-01  -1.042E+00
    4.000E-01  -3.788E-01
    6.000E-01  -2.227E-02
    8.000E-01   1.983E-01
    1.000E+00   3.374E-01


s13adfe.r

 S13ADF Example Program Results

      X           Y

    0.000E+00   0.000E+00
    2.000E-01   1.996E-01
    4.000E-01   3.965E-01
    6.000E-01   5.881E-01
    8.000E-01   7.721E-01
    1.000E+00   9.461E-01


s14aafe.r

 S14AAF Example Program Results

      X           Y

    1.000E+00   1.000E+00
    1.250E+00   9.064E-01
    1.500E+00   8.862E-01
    1.750E+00   9.191E-01
    2.000E+00   1.000E+00
    5.000E+00   2.400E+01
    1.000E+01   3.629E+05
   -1.500E+00   2.363E+00


s14abfe.r

 S14ABF Example Program Results

      X           Y

    1.000E+00   0.000E+00
    1.250E+00  -9.827E-02
    1.500E+00  -1.208E-01
    1.750E+00  -8.440E-02
    2.000E+00   0.000E+00
    5.000E+00   3.178E+00
    1.000E+01   1.280E+01
    2.000E+01   3.934E+01
    1.000E+03   5.905E+03


s14acfe.r

 S14ACF Example Program Results

        X        psi(X)-log(X)

       0.1000        -8.1212
       0.5000        -1.2704
       3.6000        -0.1453
       8.0000        -0.0638


s14adfe.r

 S14ADF Example Program Results

       X           ANS(1)        ANS(2)        ANS(3)        ANS(4)

   1.0000E-01    1.0424E+01    1.0143E+02    1.0009E+03    1.0001E+04
   5.0000E-01    1.9635E+00    4.9348E+00    8.4144E+00    1.6235E+01
   3.6000E+00   -1.1357E+00    3.1988E-01    5.0750E-02    1.0653E-02
   8.0000E+00   -2.0156E+00    1.3314E-01    8.8498E-03    7.8321E-04


s14aefe.r

 S14AEF Example Program Results

    X     K    (d^K/dx^K)psi(X)

   2.5    2      -2.3620E-01


s14affe.r

 S14AFF Example Program Results

        Z           K         (d^K/dz^K)psi(Z)

 ( -1.5,  2.5 )     1   ( -1.9737E-01, -2.4271E-01 )


s14agfe.r

 S14AGF Example Program Results

        Z                 ln(Gamma(Z))

 ( -1.5,  2.5 )   ( -5.0140E+00, -4.0718E+00 )


s14ahfe.r

 S14AHF Example Program Results

      X           Y

    1.000E+00   1.000E+00
    1.250E+00   1.096E+00
    1.500E+00   1.176E+00
    1.750E+00   1.246E+00
    2.000E+00   1.307E+00
    5.000E+00   1.740E+00
    1.000E+01   2.079E+00
    2.000E+01   2.421E+00
    1.000E+03   4.373E+00


s14bafe.r

 S14BAF Example Program Results

          A           X           P           Q
       2.0000      3.0000      0.8009      0.1991
       7.0000      1.0000      0.0001      0.9999
       0.5000     99.0000      1.0000      0.0000
      20.0000     21.0000      0.6157      0.3843
      21.0000     20.0000      0.4409      0.5591


s15abfe.r

 S15ABF Example Program Results

      X           Y

   -2.000E+01   2.754E-89
   -1.000E+00   1.587E-01
    0.000E+00   5.000E-01
    1.000E+00   8.413E-01
    2.000E+00   9.772E-01
    2.000E+01   1.000E+00


s15acfe.r

 S15ACF Example Program Results

      X           Y

   -2.000E+01   1.000E+00
   -1.000E+00   8.413E-01
    0.000E+00   5.000E-01
    1.000E+00   1.587E-01
    2.000E+00   2.275E-02
    2.000E+01   2.754E-89


s15adfe.r

 S15ADF Example Program Results

      X           Y

   -1.000E+01   2.000E+00
   -1.000E+00   1.843E+00
    0.000E+00   1.000E+00
    1.000E+00   1.573E-01
    1.000E+01   2.088E-45


s15aefe.r

 S15AEF Example Program Results

      X           Y

   -6.000E+00  -1.000E+00
   -4.500E+00  -1.000E+00
   -1.000E+00  -8.427E-01
    1.000E+00   8.427E-01
    4.500E+00   1.000E+00
    6.000E+00   1.000E+00


s15affe.r

 S15AFF Example Program Results

      X           Y

   -2.000E+00  -3.013E-01
   -5.000E-01  -4.244E-01
    1.000E+00   5.381E-01
    1.500E+00   4.282E-01
    2.000E+00   3.013E-01
    5.000E+00   1.021E-01
    1.000E+01   5.025E-02


s15agfe.r

 S15AGF Example Program Results

        X          erfcx(X)

   -6.00000E+00   8.62246E+15
   -4.50000E+00   1.24593E+09
   -1.00000E+00   5.00898E+00
    1.00000E+00   4.27584E-01
    4.50000E+00   1.22485E-01
    6.00000E+00   9.27766E-02


s15ddfe.r

 S15DDF Example Program Results

               Z                                W
 (      1.0000,      0.0000)      (      0.3679,      0.6072)
 (     -3.0100,      0.7500)      (      0.0522,     -0.1838)
 (      2.7500,     -1.5200)      (     -0.1015,      0.1654)
 (     -1.3300,     -0.5400)      (     -0.1839,     -0.7891)


s17acfe.r

 S17ACF Example Program Results

      X           Y

    5.000E-01  -4.445E-01
    1.000E+00   8.826E-02
    3.000E+00   3.769E-01
    6.000E+00  -2.882E-01
    8.000E+00   2.235E-01
    1.000E+01   5.567E-02
    1.000E+03   4.716E-03


s17adfe.r

 S17ADF Example Program Results

      X           Y

    5.000E-01  -1.471E+00
    1.000E+00  -7.812E-01
    3.000E+00   3.247E-01
    6.000E+00  -1.750E-01
    8.000E+00  -1.581E-01
    1.000E+01   2.490E-01
    1.000E+03  -2.478E-02


s17aefe.r

 S17AEF Example Program Results

      X           Y

    0.000E+00   1.000E+00
    5.000E-01   9.385E-01
    1.000E+00   7.652E-01
    3.000E+00  -2.601E-01
    6.000E+00   1.506E-01
    8.000E+00   1.717E-01
    1.000E+01  -2.459E-01
   -1.000E+00   7.652E-01
    1.000E+03   2.479E-02


s17affe.r

 S17AFF Example Program Results

      X           Y

    0.000E+00   0.000E+00
    5.000E-01   2.423E-01
    1.000E+00   4.401E-01
    3.000E+00   3.391E-01
    6.000E+00  -2.767E-01
    8.000E+00   2.346E-01
    1.000E+01   4.347E-02
   -1.000E+00  -4.401E-01
    1.000E+03   4.728E-03


s17agfe.r

 S17AGF Example Program Results

      X           Y

   -1.000E+01   4.024E-02
   -1.000E+00   5.356E-01
    0.000E+00   3.550E-01
    1.000E+00   1.353E-01
    5.000E+00   1.083E-04
    1.000E+01   1.105E-10
    2.000E+01   1.692E-27


s17ahfe.r

 S17AHF Example Program Results

      X           Y

   -1.000E+01  -3.147E-01
   -1.000E+00   1.040E-01
    0.000E+00   6.149E-01
    1.000E+00   1.207E+00
    5.000E+00   6.578E+02
    1.000E+01   4.556E+08
    2.000E+01   2.104E+25


s17ajfe.r

 S17AJF Example Program Results

      X           Y

   -1.000E+01   9.963E-01
   -1.000E+00  -1.016E-02
    0.000E+00  -2.588E-01
    1.000E+00  -1.591E-01
    5.000E+00  -2.474E-04
    1.000E+01  -3.521E-10
    2.000E+01  -7.586E-27


s17akfe.r

 S17AKF Example Program Results

      X           Y

   -1.000E+01   1.194E-01
   -1.000E+00   5.924E-01
    0.000E+00   4.483E-01
    1.000E+00   9.324E-01
    5.000E+00   1.436E+03
    1.000E+01   1.429E+09
    2.000E+01   9.382E+25


s17alfe.r

 S17ALF Example Program Results

    A   N   MODE        REL
                  (machine-dependent)

  0.0   5      1      1.1E-08

 Leading N positive zeros of J

 X =
  2.4048E+00
  5.5201E+00
  8.6537E+00
  1.1792E+01
  1.4931E+01


s17aqfe.r

 S17AQF Example Program Results

      X           F          IVALID

    5.000E-01  -4.445E-01    0
    1.000E+00   8.826E-02    0
    3.000E+00   3.769E-01    0
    6.000E+00  -2.882E-01    0
    8.000E+00   2.235E-01    0
    1.000E+01   5.567E-02    0
    1.000E+03   4.716E-03    0


s17arfe.r

 S17ARF Example Program Results

      X           F          IVALID

    5.000E-01  -1.471E+00    0
    1.000E+00  -7.812E-01    0
    3.000E+00   3.247E-01    0
    6.000E+00  -1.750E-01    0
    8.000E+00  -1.581E-01    0
    1.000E+01   2.490E-01    0
    1.000E+03  -2.478E-02    0


s17asfe.r

 S17ASF Example Program Results

      X           F          IVALID

    0.000E+00   1.000E+00    0
    5.000E-01   9.385E-01    0
    1.000E+00   7.652E-01    0
    3.000E+00  -2.601E-01    0
    6.000E+00   1.506E-01    0
    8.000E+00   1.717E-01    0
    1.000E+01  -2.459E-01    0
   -1.000E+00   7.652E-01    0
    1.000E+03   2.479E-02    0


s17atfe.r

 S17ATF Example Program Results

      X           F          IVALID

    0.000E+00   0.000E+00    0
    5.000E-01   2.423E-01    0
    1.000E+00   4.401E-01    0
    3.000E+00   3.391E-01    0
    6.000E+00  -2.767E-01    0
    8.000E+00   2.346E-01    0
    1.000E+01   4.347E-02    0
   -1.000E+00  -4.401E-01    0
    1.000E+03   4.728E-03    0


s17aufe.r

 S17AUF Example Program Results

      X           F          IVALID

   -1.000E+01   4.024E-02    0
   -1.000E+00   5.356E-01    0
    0.000E+00   3.550E-01    0
    1.000E+00   1.353E-01    0
    5.000E+00   1.083E-04    0
    1.000E+01   1.105E-10    0
    2.000E+01   1.692E-27    0


s17avfe.r

 S17AVF Example Program Results

      X           F          IVALID

   -1.000E+01  -3.147E-01    0
   -1.000E+00   1.040E-01    0
    0.000E+00   6.149E-01    0
    1.000E+00   1.207E+00    0
    5.000E+00   6.578E+02    0
    1.000E+01   4.556E+08    0
    2.000E+01   2.104E+25    0


s17awfe.r

 S17AWF Example Program Results

      X           F          IVALID

   -1.000E+01   9.963E-01    0
   -1.000E+00  -1.016E-02    0
    0.000E+00  -2.588E-01    0
    1.000E+00  -1.591E-01    0
    5.000E+00  -2.474E-04    0
    1.000E+01  -3.521E-10    0
    2.000E+01  -7.586E-27    0


s17axfe.r

 S17AXF Example Program Results

      X           F          IVALID

   -1.000E+01   1.194E-01    0
   -1.000E+00   5.924E-01    0
    0.000E+00   4.483E-01    0
    1.000E+00   9.324E-01    0
    5.000E+00   1.436E+03    0
    1.000E+01   1.429E+09    0
    2.000E+01   9.382E+25    0


s17dgfe.r

 S17DGF Example Program Results

 DERIV           Z         SCAL           AI          NZ

   F   (  0.3000,  0.4000)   U   (  0.2716, -0.1002)   0
   F   (  0.2000,  0.0000)   U   (  0.3037,  0.0000)   0
   F   (  1.1000, -6.6000)   U   (-43.6632,-47.9030)   0
   F   (  1.1000, -6.6000)   S   (  0.1655,  0.0597)   0
   D   ( -1.0000,  0.0000)   U   ( -0.0102,  0.0000)   0


s17dhfe.r

 S17DHF Example Program Results

 DERIV           Z         SCAL           BI

   F   (  0.3000,  0.4000)   U   (  0.7355,  0.1825)
   F   (  0.2000,  0.0000)   U   (  0.7055,  0.0000)
   F   (  1.1000, -6.6000)   U   (-47.9039, 43.6634)
   F   (  1.1000, -6.6000)   S   ( -0.1300,  0.1185)
   D   ( -1.0000,  0.0000)   U   (  0.5924,  0.0000)


s18acfe.r

 S18ACF Example Program Results

      X           Y

    4.000E-01   1.115E+00
    6.000E-01   7.775E-01
    1.400E+00   2.437E-01
    1.600E+00   1.880E-01
    2.500E+00   6.235E-02
    3.500E+00   1.960E-02
    6.000E+00   1.244E-03
    8.000E+00   1.465E-04
    1.000E+01   1.778E-05
    1.000E+03   0.000E+00


s18adfe.r

 S18ADF Example Program Results

      X           Y

    4.000E-01   2.184E+00
    6.000E-01   1.303E+00
    1.400E+00   3.208E-01
    1.600E+00   2.406E-01
    2.500E+00   7.389E-02
    3.500E+00   2.224E-02
    6.000E+00   1.344E-03
    8.000E+00   1.554E-04
    1.000E+01   1.865E-05
    1.000E+03   0.000E+00


s18aefe.r

 S18AEF Example Program Results

      X           Y

    0.000E+00   1.000E+00
    5.000E-01   1.063E+00
    1.000E+00   1.266E+00
    3.000E+00   4.881E+00
    6.000E+00   6.723E+01
    8.000E+00   4.276E+02
    1.000E+01   2.816E+03
    1.500E+01   3.396E+05
    2.000E+01   4.356E+07
   -1.000E+00   1.266E+00


s18affe.r

 S18AFF Example Program Results

      X           Y

    0.000E+00   0.000E+00
    5.000E-01   2.579E-01
    1.000E+00   5.652E-01
    3.000E+00   3.953E+00
    6.000E+00   6.134E+01
    8.000E+00   3.999E+02
    1.000E+01   2.671E+03
    1.500E+01   3.281E+05
    2.000E+01   4.245E+07
   -1.000E+00  -5.652E-01


s18aqfe.r

 S18AQF Example Program Results

      X           F          IVALID

    4.000E-01   1.115E+00    0
    6.000E-01   7.775E-01    0
    1.400E+00   2.437E-01    0
    1.600E+00   1.880E-01    0
    2.500E+00   6.235E-02    0
    3.500E+00   1.960E-02    0
    6.000E+00   1.244E-03    0
    8.000E+00   1.465E-04    0
    1.000E+01   1.778E-05    0
    1.000E+03   0.000E+00    0


s18arfe.r

 S18ARF Example Program Results

      X           F          IVALID

    4.000E-01   2.184E+00    0
    6.000E-01   1.303E+00    0
    1.400E+00   3.208E-01    0
    1.600E+00   2.406E-01    0
    2.500E+00   7.389E-02    0
    3.500E+00   2.224E-02    0
    6.000E+00   1.344E-03    0
    8.000E+00   1.554E-04    0
    1.000E+01   1.865E-05    0
    1.000E+03   0.000E+00    0


s18asfe.r

 S18ASF Example Program Results

      X           F          IVALID

    0.000E+00   1.000E+00    0
    5.000E-01   1.063E+00    0
    1.000E+00   1.266E+00    0
    3.000E+00   4.881E+00    0
    6.000E+00   6.723E+01    0
    8.000E+00   4.276E+02    0
    1.000E+01   2.816E+03    0
    1.500E+01   3.396E+05    0
    2.000E+01   4.356E+07    0
   -1.000E+00   1.266E+00    0


s18atfe.r

 S18ATF Example Program Results

      X           F          IVALID

    0.000E+00   0.000E+00    0
    5.000E-01   2.579E-01    0
    1.000E+00   5.652E-01    0
    3.000E+00   3.953E+00    0
    6.000E+00   6.134E+01    0
    8.000E+00   3.999E+02    0
    1.000E+01   2.671E+03    0
    1.500E+01   3.281E+05    0
    2.000E+01   4.245E+07    0
   -1.000E+00  -5.652E-01    0


s18ccfe.r

 S18CCF Example Program Results

      X           Y

    4.000E-01   1.663E+00
    6.000E-01   1.417E+00
    1.400E+00   9.881E-01
    2.500E+00   7.595E-01
    1.000E+01   3.916E-01
    1.000E+03   3.963E-02


s18cdfe.r

 S18CDF Example Program Results

      X           Y

    4.000E-01   3.259E+00
    6.000E-01   2.374E+00
    1.400E+00   1.301E+00
    2.500E+00   9.002E-01
    1.000E+01   4.108E-01
    1.000E+03   3.965E-02


s18cefe.r

 S18CEF Example Program Results

      X           Y

    0.000E+00   1.000E+00
    5.000E-01   6.450E-01
    1.000E+00   4.658E-01
    3.000E+00   2.430E-01
    6.000E+00   1.667E-01
    1.000E+01   1.278E-01
    1.000E+03   1.262E-02
   -1.000E+00   4.658E-01


s18cffe.r

 S18CFF Example Program Results

      X           Y

    0.000E+00   0.000E+00
    5.000E-01   1.564E-01
    1.000E+00   2.079E-01
    3.000E+00   1.968E-01
    6.000E+00   1.521E-01
    1.000E+01   1.213E-01
    1.000E+03   1.261E-02
   -1.000E+00  -2.079E-01


s18cqfe.r

 S18CQF Example Program Results

      X           F          IVALID

    4.000E-01   1.663E+00    0
    6.000E-01   1.417E+00    0
    1.400E+00   9.881E-01    0
    2.500E+00   7.595E-01    0
    1.000E+01   3.916E-01    0
    1.000E+03   3.963E-02    0


s18crfe.r

 S18CRF Example Program Results

      X           F          IVALID

    4.000E-01   3.259E+00    0
    6.000E-01   2.374E+00    0
    1.400E+00   1.301E+00    0
    2.500E+00   9.002E-01    0
    1.000E+01   4.108E-01    0
    1.000E+03   3.965E-02    0


s18csfe.r

 S18CSF Example Program Results

      X           F

    0.000E+00   1.000E+00
    5.000E-01   6.450E-01
    1.000E+00   4.658E-01
    3.000E+00   2.430E-01
    6.000E+00   1.667E-01
    1.000E+01   1.278E-01
    1.000E+03   1.262E-02
   -1.000E+00   4.658E-01


s18ctfe.r

 S18CTF Example Program Results

      X           F

    0.000E+00   0.000E+00
    5.000E-01   1.564E-01
    1.000E+00   2.079E-01
    3.000E+00   1.968E-01
    6.000E+00   1.521E-01
    1.000E+01   1.213E-01
    1.000E+03   1.261E-02
   -1.000E+00  -2.079E-01


s18gkfe.r

 S18GKF Example Program Results

       Z           A     NL

 (  0.6, -0.8 )   0.0     3

  Requested values of J_alpha(Z)

      alpha              J_alpha(Z)
   0.0000E+00   (  1.0565E+00,  2.4811E-01 )
   1.0000E+00   (  3.5825E-01, -3.7539E-01 )
   2.0000E+00   ( -2.5974E-02, -1.2538E-01 )
   3.0000E+00   ( -1.9369E-02, -8.6380E-03 )


s19aafe.r

 S19AAF Example Program Results

      X           Y

    1.000E-01   1.000E+00
    1.000E+00   9.844E-01
    2.500E+00   4.000E-01
    5.000E+00  -6.230E+00
    1.000E+01   1.388E+02
    1.500E+01  -2.967E+03
   -1.000E+00   9.844E-01


s19abfe.r

 S19ABF Example Program Results

      X           Y

    1.000E-01   2.500E-03
    1.000E+00   2.496E-01
    2.500E+00   1.457E+00
    5.000E+00   1.160E-01
    1.000E+01   5.637E+01
    1.500E+01  -2.953E+03
   -1.000E+00   2.496E-01


s19acfe.r

 S19ACF Example Program Results

      X           Y

    1.000E-01   2.420E+00
    1.000E+00   2.867E-01
    2.500E+00  -6.969E-02
    5.000E+00  -1.151E-02
    1.000E+01   1.295E-04
    1.500E+01  -1.514E-08


s19adfe.r

 S19ADF Example Program Results

      X           Y

    0.000E+00  -7.854E-01
    1.000E-01  -7.769E-01
    1.000E+00  -4.950E-01
    2.500E+00  -1.107E-01
    5.000E+00   1.119E-02
    1.000E+01  -3.075E-04
    1.500E+01   7.963E-06


s19anfe.r

 S19ANF Example Program Results

      X           F          IVALID

    1.000E-01   1.000E+00    0
    1.000E+00   9.844E-01    0
    2.500E+00   4.000E-01    0
    5.000E+00  -6.230E+00    0
    1.000E+01   1.388E+02    0
    1.500E+01  -2.967E+03    0
   -1.000E+00   9.844E-01    0


s19apfe.r

 S19APF Example Program Results

      X           F          IVALID

    1.000E-01   2.500E-03    0
    1.000E+00   2.496E-01    0
    2.500E+00   1.457E+00    0
    5.000E+00   1.160E-01    0
    1.000E+01   5.637E+01    0
    1.500E+01  -2.953E+03    0
   -1.000E+00   2.496E-01    0


s19aqfe.r

 S19AQF Example Program Results

      X           F          IVALID

    1.000E-01   2.420E+00    0
    1.000E+00   2.867E-01    0
    2.500E+00  -6.969E-02    0
    5.000E+00  -1.151E-02    0
    1.000E+01   1.295E-04    0
    1.500E+01  -1.514E-08    0


s19arfe.r

 S19ARF Example Program Results

      X           F          IVALID

    0.000E+00  -7.854E-01    0
    1.000E-01  -7.769E-01    0
    1.000E+00  -4.950E-01    0
    2.500E+00  -1.107E-01    0
    5.000E+00   1.119E-02    0
    1.000E+01  -3.075E-04    0
    1.500E+01   7.963E-06    0


s20acfe.r

 S20ACF Example Program Results

      X          Y

    0.000E+00   0.000E+00
    5.000E-01   6.473E-02
    1.000E+00   4.383E-01
    2.000E+00   3.434E-01
    4.000E+00   4.205E-01
    5.000E+00   4.992E-01
    6.000E+00   4.470E-01
    8.000E+00   4.602E-01
    1.000E+01   4.682E-01
   -1.000E+00  -4.383E-01
    1.000E+03   4.997E-01


s20adfe.r

 S20ADF Example Program Results

      X           Y

    0.000E+00   0.000E+00
    5.000E-01   4.923E-01
    1.000E+00   7.799E-01
    2.000E+00   4.883E-01
    4.000E+00   4.984E-01
    5.000E+00   5.636E-01
    6.000E+00   4.995E-01
    8.000E+00   4.998E-01
    1.000E+01   4.999E-01
   -1.000E+00  -7.799E-01
    1.000E+03   5.000E-01


s20aqfe.r

 S20AQF Example Program Results

      X           F

    0.000E+00   0.000E+00
    5.000E-01   6.473E-02
    1.000E+00   4.383E-01
    2.000E+00   3.434E-01
    4.000E+00   4.205E-01
    5.000E+00   4.992E-01
    6.000E+00   4.470E-01
    8.000E+00   4.602E-01
    1.000E+01   4.682E-01
   -1.000E+00  -4.383E-01
    1.000E+03   4.997E-01


s20arfe.r

 S20ARF Example Program Results

      X           F

    0.000E+00   0.000E+00
    5.000E-01   4.923E-01
    1.000E+00   7.799E-01
    2.000E+00   4.883E-01
    4.000E+00   4.984E-01
    5.000E+00   5.636E-01
    6.000E+00   4.995E-01
    8.000E+00   4.998E-01
    1.000E+01   4.999E-01
   -1.000E+00  -7.799E-01
    1.000E+03   5.000E-01


s21bafe.r

 S21BAF Example Program Results

     X      Y        S21BAF

    0.50   1.00      1.1107
    1.00   1.00      1.0000
    1.50   1.00      0.9312


s21bbfe.r

 S21BBF Example Program Results

     X      Y      Z        S21BBF

    0.50   1.00   1.50      1.0281
    1.00   1.50   2.00      0.8260
    1.50   2.00   2.50      0.7116


s21bcfe.r

 S21BCF Example Program Results

     X      Y      Z        S21BCF

    0.50   0.50   1.00      1.4787
    0.50   1.00   1.00      1.2108
    0.50   1.50   1.00      1.0611
    1.00   1.00   1.00      1.0000
    1.00   1.50   1.00      0.8805
    1.50   1.50   1.00      0.7775


s21befe.r

 S21BEF Example Program Results

     PHI    DM      S21BEF

    0.52   0.25      0.5294
    1.05   0.50      1.1424
    1.57   0.75      2.1565


s21bffe.r

 S21BFF Example Program Results

     PHI    DM      S21BFF

    0.52   0.25      0.5179
    1.05   0.50      0.9650
    1.57   0.75      1.2111


s21bgfe.r

 S21BGF Example Program Results

     DN     PHI    DM      S21BGF

    0.10   0.52   0.25      0.5341
   -0.20   1.05   0.50      1.0778
    0.30   1.57   0.75      2.6568


s21bhfe.r

 S21BHF Example Program Results

     DM       S21BHF

    0.25      1.6858
    0.50      1.8541
    0.75      2.1565


s21bjfe.r

 S21BJF Example Program Results

     DM       S21BJF

    0.25      1.4675
    0.50      1.3506
    0.75      1.2111


s21cafe.r

 S21CAF Example Program Results

           U            M           SN           CN           DN
      0.2000E+00   0.3000E+00   0.1983E+00   0.9801E+00   0.9941E+00
      0.5000E+01  -0.1000E+01  -0.2440E+00   0.9698E+00   0.1029E+01
     -0.5000E+00  -0.1000E+00  -0.4812E+00   0.8766E+00   0.1012E+01
      0.1000E+02   0.1100E+02   0.2512E+00   0.9679E+00   0.5528E+00


s21cbfe.r

 S21CBF Example Program Results

           Z                    AK2
 ( -2.0000,  3.0000)           0.25

          SN                     CN                     DN
 ( -1.5865,  0.2456)    (  0.3125,  1.2468)    ( -0.6395, -0.1523)


s21ccfe.r

 S21CCF Example Program Results

  K    X     Q         Y

  2   0.7   0.4   -6.9289E-01


s21dafe.r

 S21DAF Example Program Results

      Z          AKP     A      B                 Y

 ( 1.2, 3.7 )    0.5    1.0    1.0   (  1.9713E+00,  5.0538E-01 )


s22aafe.r

 S22AAF Example Program Results

 MODE      X      M    NL

   1      0.5     2     3

 Unnormalized associated Legendre function values
  n      P(n)
  0   0.0000E+00
  1   0.0000E+00
  2   2.2500E+00
  3   5.6250E+00


s22bbfe.r

 S22BBF Example Program Results

          a          b          x          frm    scm     M(a,b,x)
    -9.9999    29.9999    25.0000  -7.7329E-01    -15  -2.3599E-05
   -10.0001    30.0001    25.0000  -7.7318E-01    -15  -2.3596E-05

 Solution product                   5.9789E-01    -30   5.5683E-10

 Solution ratio                     1.0001E+00      0   1.0001E+00


s22bffe.r

 S22BFF Example Program Results

          a          b          c          x           frf    scf  2F1(a,b;c;x)
    -9.9999     1.9999    -4.9999     0.4500  -5.44477E-01     16  -3.56828E+04
   -10.0001     2.0001    -5.0001     0.4500   5.44547E-01     16   3.56875E+04

 Solution product                  -2.96494E-01     32  -1.27343E+09

 Solution ratio                    -9.99871E-01      0  -9.99871E-01


s30aafe.r

 S30AAF Example Program Results

 Black-Scholes-Merton formula
 European Call :
  Spot       =   55.0000
  Volatility =    0.3000
  Rate       =    0.1000
  Dividend   =    0.0000

    Strike    Expiry    Option Price
   58.0000    0.7000          5.9198
   58.0000    0.8000          6.5506
   60.0000    0.7000          5.0809
   60.0000    0.8000          5.6992
   62.0000    0.7000          4.3389
   62.0000    0.8000          4.9379


s30abfe.r

 S30ABF Example Program Results

 European Put :
  Spot       =   55.0000
  Volatility =    0.3000
  Rate       =    0.1000
  Dividend   =    0.0000

 Time to Expiry :    0.7000
   Strike    Price    Delta    Gamma     Vega    Theta      Rho     CRho
  60.0000   6.0245  -0.4770   0.0289  18.3273  -0.7014 -22.5811 -18.3639
   Strike    Price    Vanna    Charm    Speed   Colour    Zomma    Vomma
  60.0000   6.0245   0.2566  -0.2137  -0.0006   0.0215  -0.0972  -0.6816


s30bafe.r

 S30BAF Example Program Results

 Floating-strike Lookback
 European Call :
  Spot       =  120.0000
  Volatility =    0.3000
  Rate       =    0.1000
  Dividend   =    0.0600

    Strike    Expiry    Option Price
  100.0000    0.5000         25.3534


s30bbfe.r

 S30BBF Example Program Results

 Floating-Strike Lookback
 European Put :
  Spot       =   87.0000
  Volatility =    0.3000
  Rate       =    0.0600
  Dividend   =    0.0400

 Time to Expiry :    0.5000
 S-Max/Min     Price     Delta     Gamma      Vega      Theta      Rho      CRho
  100.0000   18.3530   -0.3560    0.0391   45.5353  -11.6139  -32.8139  -23.6374
 S-Max/Min     Price     Vanna     Charm     Speed     Colour    Zomma     Vomma
  100.0000   18.3530    1.9141   -0.6199    0.0007    0.0221   -0.0648   76.1292


s30cafe.r

 S30CAF Example Program Results

 Binary (Digital): Cash-or-Nothing
 European Put :
  Spot       =  100.0000
  Payout     =   10.0000
  Volatility =    0.3500
  Rate       =    0.0600
  Dividend   =    0.0000

   Strike     Expiry    Option Price
   80.0000    0.7500          2.2155


s30cbfe.r

 S30CBF Example Program Results

 Binary (Digital): Cash-or-Nothing
 European Call :
  Spot       =  110.0000
  Payout     =    5.0000
  Volatility =    0.3500
  Rate       =    0.0500
  Dividend   =    0.0400

 Time to Expiry :    0.7500
   Strike    Price    Delta    Gamma     Vega    Theta     Rho      CRho
  87.0000   3.5696   0.0467  -0.0013  -4.2307   1.1142   1.1788   3.8560
   Strike    Price    Vanna    Charm    Speed   Colour    Zomma    Vomma
  87.0000   3.5696  -0.0514   0.0153   0.0000  -0.0019   0.0079  12.8874


s30ccfe.r

 S30CCF Example Program Results

 Binary (Digital): Asset-or-Nothing
 European Put :
  Spot       =   70.0000
  Volatility =    0.2700
  Rate       =    0.0700
  Dividend   =    0.0500

    Strike    Expiry    Option Price
   65.0000    0.5000         20.2069


s30cdfe.r

 S30CDF Example Program Results

 Binary (Digital): Asset-or-Nothing
 European Put :
  Spot       =   70.0000
  Volatility =    0.1500
  Rate       =    0.0500
  Dividend   =    0.0300

 Time to Expiry :    0.8000
    Strike     Price     Delta     Gamma      Vega     Theta       Rho      CRho
   65.0000   15.7211   -1.9852    0.1422   83.6424   -4.2761 -123.7497 -111.1728
    Strike     Price     Vanna     Charm     Speed    Colour     Zomma     Vomma
   65.0000   15.7211    9.3479   -1.1351    0.0118    0.2316   -2.6319 -989.9610


s30fafe.r

 S30FAF Example Program Results

 Standard Barrier Option
 Put :
 Down-and-In
  Spot       =  100.0000
  Barrier    =   95.0000
  Rebate     =    3.0000
  Volatility =    0.3000
  Rate       =    0.0800
  Dividend   =    0.0400

    Strike    Expiry    Option Price
  100.0000    0.5000          7.7988


s30jafe.r

 S30JAF Example Program Results

 Merton Jump-Diffusion Model
 European Call :
  Spot       =   45.0000
  Volatility =    0.2500
  Rate       =    0.1000
  Jumps      =    3.0000
  Jump vol   =    0.4000

    Strike    Expiry    Option Price
   55.0000    0.2500          0.2417


s30jbfe.r

 S30JBF Example Program Results

 Merton Jump-Diffusion Model
 European Call :
  Spot       =  100.0000
  Volatility =    0.2500
  Rate       =    0.0800
  Jumps      =    5.0000
  Jump vol   =    0.2500

 Time to Expiry :    0.5000
   Strike    Price    Delta    Gamma     Vega    Theta      Rho
  80.0000  23.6090   0.9431   0.0064   8.1206  -7.6718  35.3480
  90.0000  15.4193   0.8203   0.0149  18.5256  -9.9695  33.3037
   Strike    Price    Vanna    Charm    Speed   Colour    Zomma    Vomma
  80.0000  23.6090  -0.6334   0.1080  -0.0006  -0.0035   0.0315  70.6824
  90.0000  15.4193  -0.7726   0.0770  -0.0009   0.0109  -0.0186  49.7161


s30nafe.r

 S30NAF Example Program Results

 Heston's Stochastic volatility Model
 European Call :
  Spot                   =  100.0000
  Volatility of vol      =    0.2250
  Mean reversion         =    2.0000
  Correlation            =    0.0000
  Variance               =    0.0100
  Mean of variance       =    0.0100
  Risk aversion          =    1.0000
  Rate                   =    0.0500
  Dividend               =    0.0000

    Strike    Expiry    Option Price
  100.0000    0.5000          4.0851


s30nbfe.r

 S30NBF Example Program Results

 Heston's Stochastic volatility Model
 European Call :
  Spot                   =    100.0000
  Volatility of vol      =      0.5751
  Mean reversion         =      1.5768
  Correlation            =     -0.5711
  Variance               =      0.0175
  Mean of variance       =      0.0398
  Risk aversion          =      1.0000
  Rate                   =      0.0250
  Dividend               =      0.0000

 Time to Expiry :    1.0000
   Strike       Price      Delta      Gamma      Vega       Theta      Rho
   100.0000     7.2743     0.6945     0.0251    52.5461    -4.9969    62.1735
   Strike       Price      Vanna      Charm      Speed      Zomma      Vomma
   100.0000     7.2743    -0.5643    -0.0321    -0.0023    -0.1976  -321.0780


s30ncfe.r

 S30NCF Example Program Results

 Heston's Stochastic volatility Model with Term Structure
 European Call :
  Forward                =  100.0000
  Discount Factor        =    1.0000
  Variance               =    1.0000
    ts        alpha     lambda    corr      sigmat
    0.3500    2.2500    2.0000   -0.0500    0.0400
    0.6500    1.5000    1.5000    0.1000    0.1300

    Strike    Expiry       Option Price
  100.0000    1.0000       4.0074


s30qcfe.r

 S30QCF Example Program Results

 American Call :
  Spot       =  110.0000
  Volatility =    0.2000
  Rate       =    0.0800
  Dividend   =    0.1200

    Strike    Expiry    Option Price
  100.0000    0.2500         10.3340


s30safe.r

 S30SAF Example Program Results

 Asian Option: Geometric Continuous Average-Rate
 Asian Put :
  Spot          =   80.0000
  Volatility    =    0.2000
  Rate          =    0.0500
  Cost of carry =    0.0800

    Strike    Expiry    Option Price
   85.0000    0.2500          4.6922


s30sbfe.r

 S30SBF Example Program Results

 Asian Option: Geometric Continuous Average-Rate
 Asian Call :
  Spot          =   80.0000
  Volatility    =    0.2000
  Rate          =    0.0500
  Cost of carry =    0.0800

 Time to Expiry :    0.2500
   Strike    Price    Delta    Gamma     Vega     Theta     Rho     CRho
  97.0000   0.0010   0.0008   0.0006   0.0638  -0.0281   0.0079   0.0081
   Strike    Price    Vanna    Charm    Speed    Colour   Zomma    Vomma
  97.0000   0.0010   0.0443  -0.0196   0.0004  -0.0122   0.0272   3.1893


x02ajfe.r

 X02AJF Example Program Results

 (results are machine-dependent)

 The basic parameters of the model

  X02BHF =       2   (the model parameter B)
  X02BJF =      53   (the model parameter P)
  X02BKF =   -1021   (the model parameter EMIN)
  X02BLF =    1024   (the model parameter EMAX)

 Derived parameters of floating-point arithmetic

  X02AJF =  1.110223024625156540E-016   (the machine precision)
  X02AKF =  2.225073858507201383E-308   (the smallest positive model number)
  X02ALF =  1.797693134862315708E+308   (the largest positive model number)
  X02AMF =  2.225073858507201877E-308   (the real safe range parameter)
  X02ANF =  2.225073858507201877E-308   (the complex safe range parameter)

 Parameters of other aspects of the computing environment

  X02AHF =      1.42724769E+045   (largest argument for SIN and COS)
  X02BBF =           2147483647   (largest positive integer)
  X02BEF =                   15   (precision in decimal digits)


x03aafe.r

 X03AAF Example Program Results

 D1 = -5.0 D2 =  0.0


x03abfe.r

 X03ABF Example Program Results

 Result = ( 2., 3.)


x04aafe.r

 X04AAF Example Program Results

 This is a dummy error message


x04abfe.r

 X04ABF Example Program Results

 This is a dummy advisory message


x04acfe.r

 X04ACF Example Program Results
 OK file successfully opened for writing


x04adfe.r

 X04ADF Example Program Results
 OK file successfully opened for writing
 OK file successfully closed
 OK file successfully opened for reading
 OK file successfully closed


x04bafe.r

 X04BAF Example Program Results

 This record was output by X04BAF


x04bbfe.r

 X04BBF Example Program Results

    20      2.996


x04cbfe.r

 X04CBF Example Program Results

 Example 1:
             1          2          3          4          5
 1     11.0000    12.0000    13.0000    14.0000    15.0000
 2     21.0000    22.0000    23.0000    24.0000    25.0000
 3     31.0000    32.0000    33.0000    34.0000    35.0000

 Example 2:
               Un    Deux   Trois  Quatre    Cinq
     Uno    11.00   12.00   13.00   14.00   15.00
     Due            22.00   23.00   24.00   25.00
     Tre                    33.00   34.00   35.00
 Quattro                            44.00   45.00
  Cinque                                    55.00

 A = [
     11.00    0.00    0.00    0.00    0.00;
     21.00   22.00    0.00    0.00    0.00;
     31.00   32.00   33.00    0.00    0.00;
     ];


x04cdfe.r

 X04CDF Example Program Results

 Example 1:
             1          2          3          4
 1     11.0000
 2     12.0000    22.0000
 3     13.0000    23.0000    33.0000
 4     14.0000    24.0000    34.0000    44.0000

 Example 2:
               Un    Deux   Trois  Quatre    Cinq
     Uno     1.00   12.00   13.00   14.00   15.00
     Due             1.00   23.00   24.00   25.00
     Tre                     1.00   34.00   35.00
 Quattro                             1.00   45.00
  Cinque                                     1.00

 A = [
     11.00   12.00   13.00   14.00   15.00;
      0.00   22.00   23.00   24.00   25.00;
      0.00    0.00   33.00   34.00   35.00;
      0.00    0.00    0.00   44.00   45.00;
      0.00    0.00    0.00    0.00   55.00;
     ];


x04cefe.r

 X04CEF Example Program Results

 Band Matrix:
             1          2          3          4          5
 1     11.0000    12.0000
 2     21.0000    22.0000    23.0000
 3                32.0000    33.0000    34.0000
 4                           43.0000    44.0000    45.0000
 5                                      54.0000    55.0000


x04eafe.r

 X04EAF Example Program Results

 Example 1:
     1  2  3  4  5
 1  11 12 13 14 15
 2  21 22 23 24 25
 3  31 32 33 34 35

 Example 2:
     1  2  3  4  5
 1  11
 2  21 22
 3  31 32 33
 4  41 42 43 44
 5  51 52 53 54 55


x04ebfe.r

 X04EBF Example Program Results

 Example 1:
     1  2  3  4  5
 1  11 12 13 14 15
 2  21 22 23 24 25
 3  31 32 33 34 35

 Example 2:
               Un    Deux   Trois  Quatre    Cinq
     Uno       11      12      13      14      15
     Due               22      23      24      25
     Tre                       33      34      35
 Quattro                               44      45
  Cinque                                       55

 A = [
        11       0       0       0       0;
        21      22       0       0       0;
        31      32      33       0       0;
        41      42      43      44       0;
     ];


x05aafe.r

 X05AAF Example Program Results
 File created and stamped successfully.


x05abfe.r

 X05ABF Example Program Results
 Tue 14th Jul 1789 13:11:48.320


x05acfe.r

 X05ACF Example Program Results
 Thu 27th April 1989 13:15:21.320
 is later than
 Wed 26th April 1989 11:23:14.130


x05bafe.r

 X05BAF Example Program Results
 Computed 10000000 terms of the harmonic series within the allotted time limit.
 Value of partial sum is  0.16695E+02.


x06aafe.r

X06AAF Example Program Results

 Value of ICV controlling the number of threads:    5

 Number of threads outside the parallel region:     1

 Number of threads inside the parallel region:      5


x06adfe.r

 X06ADF Example Program Results

 Thread number:                      0

 In active parallel region:          0

 Number of threads:                  5

 In active parallel region:          1


x06agfe.r

 X06AGF Example Program Results

 Nesting enabled:    1

 Total number of threads requested:   15
 Total number of threads from sum:    15


x07aafe.r

 X07AAF Example Program Results

 Turn exception halting off ...
 Exception halting mode is now:   0  0  0

 Diagnosis of value "one" which prints as   1.0000E+00
 "one" is finite
 "one" is not NaN
 "one" does not compare less than zero.
 "one" does not compare equal to zero.
 "one" compares greater than zero.

 Diagnosis of value "-two" which prints as  -2.0000E+00
 "-two" is finite
 "-two" is not NaN
 "-two" compares less than zero.
 "-two" does not compare equal to zero.
 "-two" does not compare greater than zero.

 Diagnosis of value "zero" which prints as   0.0000E+00
 "zero" is finite
 "zero" is not NaN
 "zero" does not compare less than zero.
 "zero" compares equal to zero.
 "zero" does not compare greater than zero.

 Diagnosis of value "-Infinity"
 "-Infinity" is not finite
 "-Infinity" is not NaN
 "-Infinity" compares less than zero.
 "-Infinity" does not compare equal to zero.
 "-Infinity" does not compare greater than zero.

 Diagnosis of value "Quiet NaN" which prints as          NaN
 "Quiet NaN" is not finite
 "Quiet NaN" is NaN
 "Quiet NaN" does not compare less than zero.
 "Quiet NaN" does not compare equal to zero.
 "Quiet NaN" does not compare greater than zero.

 Try to cause overflow - no trap should occur:
 y = huge() * huge() > huge()

 Try to cause NaN - no trap should occur:
 y = 0.0 / 0.0 = NaN

 Try to cause division by zero - no trap should occur:
 y = 1.0 / 0.0 > huge()


a02aafe.d

A02AAF Example Program Data
 -1.7 2.6


a02abfe.d

A02ABF Example Program Data
 -1.7 2.6


a02acfe.d

A02ACF Example Program Data
 -1.7  2.6 -3.1 -0.9


c02affe.d

C02AFF Example Program Data

Example 1
 5
    5.0       6.0
   30.0      20.0
   -0.2      -6.0
   50.0  100000.0
   -2.0      40.0
   10.0       1.0

Example 2
 5
    5.0       6.0
   30.0      20.0
   -0.2      -6.0
   50.0  100000.0
   -2.0      40.0
   10.0       1.0


c02agfe.d

C02AGF Example Program Data

Example 1
 5
     1.0    2.0    3.0    4.0    5.0    6.0

Example 2
 5
     1.0    2.0    3.0    4.0    5.0    6.0


c02ahfe.d

C02AHF Example Program Data
 1.0    0.0   -3.0    1.0    8.0    1.0       :AR  AI  BR  BI  CR  CI


c02ajfe.d

C02AJF Example Program Data
 1.0    3.0   -10.0             :A  B  C


c02akfe.d

C02AKF Example Program Data
 1.0   3.0   9.0  -13.0 : Values of U, R, S and T


c02alfe.d

C02ALF Example Program Data
 1.0   2.0   6.0  -8.0  -40.0 : Values of E, A, B, C and D


c02amfe.d

C02AMF Example Program Data
 (  1.0,  0.0)
 ( -2.0,  3.0)
 (  5.0, 14.0)
 (-40.0, -5.0) : Values of U, R, S and T


c02anfe.d

C02ANF Example Program Data
 (  1.0,  0.0)
 (  0.0,  0.0)
 (  0.0, 16.0)
 ( -8.0,  8.0)
 (-65.0,  0.0) : Values of E, A, B, C and D


c05bafe.d

C05BAF Example Program Data
  0                                                     : BRANCH
  .FALSE.                                               : OFFSET
  0.5
  1.0
  4.5
  6.0
  7.0D7                                                 : X


c05bbfe.d

C05BBF Example Program Data
  0                                                     : BRANCH
  .FALSE.                                               : OFFSET
  (0.5, -1.0)
  (1.0, 2.3)
  (4.5, -0.1)
  (6.0, 6.0)                                            : Z


c06dcfe.d

C06DCF Example Program Data
   4  3                 : n, lx
   0.5  1.0  -0.2       : x
   -1.0  1.0            : xmin, xmax
   1                    : s
   1.0  1.0  0.5  0.25  : c


c06fafe.d

C06FAF Example Program Data
    7               : n
  0.34907
  0.54890
  0.74776
  0.94459
  1.13850
  1.32850
  1.51370           : x


c06fbfe.d

C06FBF Example Program Data
    7          : n
  0.34907
  0.54890
  0.74776
  0.94459
  1.13850
  1.32850
  1.51370      : x


c06fcfe.d

C06FCF Example Program Data
    7                  : n
  0.34907  -0.37168
  0.54890  -0.35669
  0.74776  -0.31175
  0.94459  -0.23702
  1.13850  -0.13274
  1.32850   0.00074
  1.51370   0.16298    : x, y


c06fkfe.d

C06FKF Example Program Data
    9                   : n
      1.00      0.50
      1.00      0.50
      1.00      0.50
      1.00      0.50
      1.00      0.00
      0.00      0.00
      0.00      0.00
      0.00      0.00
      0.00      0.00    : xa, ya


c06fpfe.d

C06FPF Example Program Data
     3     6                                                         : m, n
     0.3854    0.6772    0.1138    0.6751    0.6362    0.1424
     0.5417    0.2983    0.1181    0.7255    0.8638    0.8723
     0.9172    0.0644    0.6037    0.6430    0.0428    0.4815        : x


c06fqfe.d

C06FQF Example Program Data
     3     6                                                    : m, n
     0.3854    0.6772    0.1138    0.6751    0.6362    0.1424
     0.5417    0.2983    0.1181    0.7255    0.8638    0.8723
     0.9172    0.0644    0.6037    0.6430    0.0428    0.4815   : x


c06lafe.d

C06LAF Example Program Data
 20  200               : n, mxterm


c06lbfe.d

C06LBF Example Program Data
 514                       : mmax
 3.0  0.00001  0.0  0.0    : sigma0, epstol, sigma, b


c06pafe.d

C06PAF Example Program Data
    7      : n
  0.34907
  0.54890
  0.74776
  0.94459
  1.13850
  1.32850
  1.51370  : x


c06pcfe.d

C06PCF Example Program Data
    7                   : n
  (0.34907,  -0.37168)
  (0.54890,  -0.35669)
  (0.74776,  -0.31175)
  (0.94459,  -0.23702)
  (1.13850,  -0.13274)
  (1.32850,   0.00074)
  (1.51370,   0.16298)  : x


c06pkfe.d

C06PKF Example Program Data
    9                                           : n
      (1.0E0,-0.5E0)      (0.5E0,-0.25E0)
      (1.0E0,-0.5E0)      (0.5E0,-0.25E0)
      (1.0E0,-0.5E0)      (0.5E0,-0.25E0)
      (1.0E0,-0.5E0)      (0.5E0,-0.25E0)
      (1.0E0,-0.5E0)      (0.0E0,-0.25E0)
      (0.0E0,-0.5E0)      (0.0E0,-0.25E0)
      (0.0E0,-0.5E0)      (0.0E0,-0.25E0)
      (0.0E0,-0.5E0)      (0.0E0,-0.25E0)
      (0.0E0,-0.5E0)      (0.0E0,-0.25E0)       : xa, ya


c06ppfe.d

C06PPF Example Program Data
     3     6                                                    : m, n
     0.3854    0.6772    0.1138    0.6751    0.6362    0.1424
     0.5417    0.2983    0.1181    0.7255    0.8638    0.8723
     0.9172    0.0644    0.6037    0.6430    0.0428    0.4815   : x


c06pqfe.d

C06PQF Example Program Data
     3     6                                                    : m, n
     0.3854    0.6772    0.1138    0.6751    0.6362    0.1424
     0.5417    0.2983    0.1181    0.7255    0.8638    0.8723
     0.9172    0.0644    0.6037    0.6430    0.0428    0.4815   : x


c06pvfe.d

C06PVF Example Program Data
5  2                   : m, n
    0.010
    0.346
    1.284
    1.960
    1.754
    0.855
    0.089
    0.161
    1.004
    1.844              : x


c06rafe.d

C06RAF Example Program Data
 3  6                                    : m, n
 0.6772  0.1138  0.6751  0.6362  0.1424
 0.2983  0.1182  0.7255  0.8638  0.8723
 0.0644  0.6037  0.6430  0.0428  0.4815  : x


c06rbfe.d

C06RBF Example Program Data
3  6                                                      : m, n
 0.3854  0.6772  0.1138  0.6751  0.6362  0.1424  0.9562
 0.5417  0.2983  0.1181  0.7255  0.8638  0.8723  0.4936
 0.9172  0.0644  0.6037  0.6430  0.0428  0.4815  0.2057   : x


c06rcfe.d

C06RCF Example Program Data
 3  6                                            : m, n
 0.3854  0.6772  0.1138  0.6751  0.6362  0.1424
 0.5417  0.2983  0.1181  0.7255  0.8638  0.8723
 0.9172  0.0644  0.6037  0.6430  0.0428  0.4815  : x


c06rdfe.d

C06RDF Example Program Data
 3  6                                            : m, n
 0.3854  0.6772  0.1138  0.6751  0.6362  0.1424
 0.5417  0.2983  0.1181  0.7255  0.8638  0.8723
 0.9172  0.0644  0.6037  0.6430  0.0428  0.4815  : x


c06refe.d

C06REF Example Program Data
 3       5                               : m, n-1
 0.6772  0.1138  0.6751  0.6362  0.1424
 0.2983  0.1182  0.7255  0.8638  0.8723
 0.0644  0.6037  0.6430  0.0428  0.4815  : x


c06rffe.d

C06RFF Example Program Data
 3       7                                                : m, n+1
 0.3854  0.6772  0.1138  0.6751  0.6362  0.1424  0.9562
 0.5417  0.2983  0.1181  0.7255  0.8638  0.8723  0.4936
 0.9172  0.0644  0.6037  0.6430  0.0428  0.4815  0.2057   : x


c06rgfe.d

C06RGF Example Program Data
 3       6                                       : m, n
 0.3854  0.6772  0.1138  0.6751  0.6362  0.1424
 0.5417  0.2983  0.1181  0.7255  0.8638  0.8723
 0.9172  0.0644  0.6037  0.6430  0.0428  0.4815  : x


c06rhfe.d

C06RHF Example Program Data
 3       6                                       : m, n
 0.3854  0.6772  0.1138  0.6751  0.6362  0.1424
 0.5417  0.2983  0.1181  0.7255  0.8638  0.8723
 0.9172  0.0644  0.6037  0.6430  0.0428  0.4815  : x


c09aafe.d

C09AAF Example Program Data
 8             : n
 Haar  Zero    : wavnam, mode
 2.0
 5.0
 8.0
 9.0
 7.0
 4.0
-1.0
 1.0           : x(1:n)


c09bafe.d

C09BAF Example Program Data
 10      4               : n, nscal
 MORLET  5               : wavnam
 1    2    3    4        : scales(1:nscal)
 0.0  0.0  0.0  0.0  1.0
 0.0  0.0  0.0  0.0  0.0 : x(1:n)


c09cafe.d

C09CAF Example Program Data
 8              : n
 DB4  Zero      : wavnam, mode
 1.0
 3.0
 5.0
 7.0
 6.0
 4.0
 5.0
 2.0            : x(1:n)


c09dafe.d

C09DAF Example Program Data
 8              : n
 DB4  Periodic      : wavnam, mode
 1.0
 3.0
 5.0
 7.0
 6.0
 4.0
 5.0
 2.0            : x(1:n)


c09ezfe.d

C09EZF Example Program Data
 7, 6   : m, n
 DB6 Period : wavnam, mode
0.01 0.01 0.01 0.01 0.01 0.01
1.00 1.00 1.00 1.00 1.00 1.00
0.01 0.01 0.01 0.01 0.01 0.01
1.00 1.00 1.00 1.00 1.00 1.00
0.01 0.01 0.01 0.01 0.01 0.01
1.00 1.00 1.00 1.00 1.00 1.00
0.01 0.01 0.01 0.01 0.01 0.01


d01ahfe.d

D01AHF Example Program Data
   0.0    1.0        : a, b
   0                 : nlimit
   0.00001           : epsr


d02agfe.d

D02AGF Example Program Data
   6                    : m1
   0.1                  : h
   0.2 0.0              : param
   1.0E-5  1.0E-3       : parer
   1.0E-4               : soler

   6                    : m1, n, n1
   1.0E1                : h
   3.2E1 6.0E3 5.4E-1   : param
   1.0E-5 1.0E-4 1.0E-4 : parer
   1.0E-2               : soler


d02bgfe.d

D02BGF Example Program Data
   1                                      : m
   0.0                                    : alpha
   0.0                                    : xinit
  10.0                                    : xend
   0.5  0.5  6.28318530717958647692E-1    : yinit


d02bhfe.d

D02BHF Example Program Data
   0.0                                       : xinit
  10.0                                       : xend
   0.5  0.5  6.28318530717958647692E-1       : yinit
   0                                         : irelab


d02bjfe.d

D02BJF Example Program Data
   0.0 10.0                               : xinit
   0.5  0.5  6.28318530717958647692E-1    : yinit
   4                                      : kinit


d02cjfe.d

D02CJF Example Program Data
   0.0                                    : xinit
  10.0                                    : xend
   0.5  0.5  6.28318530717958647692E-1    : yinit
   4                                      : kinit


d02ejfe.d

D02EJF Example Program Data
   0.0 10.0             : xinit, xend
   1.0, 0.0, 0.0        : yinit
   4                    : kinit


d02gafe.d

D02GAF Example Program Data
   40                   : mnp
   1.0E-3               : tol
   26                   : np
   0.0  10.0            : a, b


d02gbfe.d

D02GBF Example Program Data
   70                   : mnp
   1.0E-3               : tol
   0                    : np
   0.0  1.0             : a, b


d02hafe.d

D02HAF Example Program Data
   6                      : m1
   0.0  5.0               : a, b


d02hbfe.d

D02HBF Example Program Data
   6 2 2                 : m1, n, n1
   0.2  0.0              : p
   1.0E-5 1.0E-3         : pe
   1.0E-4 1.0E-4         : e

   6 3 3                 : m1, n, n1
   32.0  6000.0  0.54    : p
   1.0E-5 1.0E-4 1.0E-4  : pe
   1.0E-2 1.0E-2 1.0E-2  : e


d02jafe.d

D02JAF Example Program Data
   2 8 15             : n, k1max, kpmax
   -1.0  1.0          : x0, x1


d02jbfe.d

D02JBF Example Program Data
   2 8 15             : n, k1max, kpmax
   -1.0  1.0          : x0, x1


d02kafe.d

D02KAF Example Program Data
   0.0  3.14159265358979323846       : xl, xr
   4                                 : k
   15.0  4.0                         : elam1, delam1


d02kdfe.d

D02KDF Example Program Data
   4                                 : m
   0.0  0.1  30.0  30.0              : xpoint
   1.0E-4                            : tol
   11                                : k
   14.0  1.0                         : elam, delam
   0.0                               : hmax
   0 0                               : maxit, maxfun


d02kefe.d

D02KEF Example Program Data
   5                                                 : m
   0.0  0.1  1.58740105196819947475  30.0  30.0      : xpoint
   1.0E-4                                            : tol
   11                                                : k
   14.0  1.0                                         : elam, delam
   0.0  0.0                                          : hmax
   0 0 0                                             : maxit, maxfun, match


d02lafe.d

D02LAF Example Program Data
   2                            : nwant
   .FALSE. .TRUE.               : high, onestp
   2.0                          : tinc
   0.0  20.0                    : tstart, tend
   0.5  0.0                     : yinit
   0.0  1.73205080756887729352  : ypinit


d02mvfe.d

D02MVF Example Program Data
   5  5000  5                       : maxord, maxstp, mxhnil
   1.0E-10  0.0  0.0                : hmin, hmax, h0
   1.0E-3 1.0E-6                    : rtol, atol
   0 1                              : itrace, itol
   0.0  3.14159265358979323846      : t, tout
   1.0  0.0  0.0  0.0  0.0  0.0     : initial y
   4                                : itask


d02mwfe.d

D02MWF Example Program Data
   5                                     : maxord
   0.0  1.0                              : t, tout
   1 0                                   : itol, itask
   1.0E-8 1.0E-8 1.0E-8 1.0E-8 1.0E-8    : rtol
   1.0E-8 1.0E-8 1.0E-8 1.0E-8 1.0E-8    : atol
   1.0  0.0  0.0  1.0  1.0               : y
   0.0  0.0                              : hmax, h0
   1                                     : ijac


d02mzfe.d

D02MZF Example Program Data
   5  200  5  0                     : maxord, maxstp, mxhnil, pstat
   .FALSE.                          : petzld
   1.0E-10  10.0  0.0  0.0          : hmin, hmax, h0, tcrit
   0.0  0.1                         : t, tout
   4                                : itol
   1.0  0.0  0.0                    : y
   .FALSE. .FALSE.                  : lderiv
   1.0E-4  1.0E-3  1.0E-4           : rtol
   1.0E-7  1.0E-8  1.0E-7           : atol


d02nbfe.d

D02NBF Example Program Data
   5  200  5                        : maxord, maxstp, mxhnil
   .FALSE.                          : petzld
   1.0E-10  10.0  0.0               : hmin, hmax, h0
   0.0  10.0                        : t, tout
   1                                : itol
   1.0  0.0  0.0                    : y
   1.0E-4  1.0E-7                   : rtol, atol


d02ncfe.d

D02NCF Example Program Data
   11  200  5                       : maxord, maxstp, mxhnil
   1.0E-10  10.0  0.0  0.0          : hmin, hmax, h0, tcrit
   0.0  5.0                         : t, tout
   2                                : itol
   1.0  0.0  0.0                    : y
   1.0E-4                           : rtol
   1.0E-7  1.0E-8  1.0E-7           : atol


d02ndfe.d

D02NDF Example Program Data
   5  200  5                        : maxord, maxstp, mxhnil
   1  3  6  9                       : ia
   1  2  1  2  3  1  2  3           : ja
   1.0E-10  10.0  0.0  0.0          : hmin, hmax, h0, tcrit
   1.0E-4  0.0  0.1                 : eta, sens, u
   .TRUE. .FALSE.                   : lblock, petzld
   0.0  10.0                        : t, tout
   1  0                             : itol, isplit
   1.0  0.0  0.0                    : y
   1.0E-4  1.0E-7                   : rtol, atol


d02nefe.d

D02NEF Example Program Data
   5                        : ex1   : maxord
   1  1                             : ijac, itol
   1.0E-3 1.0E-3 1.0E-3             : rtol
   1.0E-6 1.0E-6 1.0E-6             : atol
   0.0  0.0  0.0                    : ydot
   1.0  0.0  0.0                    : y
   0.0  0.0                         : hmax, h0
   0.0  0.02                        : t, tout

   5                        : ex2   : maxord
   1  1                             : ijac, itol
   0.0                              : rtol
   1.0E-8                           : atol
   0.0                              : ydot
   2.0                              : y
   0.0  0.0                         : hmax, h0
   0.0  0.2                         : t, tout


d02ngfe.d

D02NGF Example Program Data
   5  200  5                        : maxord, maxstp, mxhnil
   .FALSE.                          : petzld
   1.0E-10 10.0 0.0 0.0             : hmin, hmax, h0, tcrit
   0.0  0.1                         : t, tout
   1.0  0.0  0.0                    : y
   .FALSE. .FALSE.                  : lderiv
   4                                : itol
   1.0E-4 1.0E-3 1.0E-4             : rtol
   1.0E-7 1.0E-8 1.0E-7             : atol


d02nhfe.d

D02NHF Example Program Data
   5  200  5                   : maxord, maxstp, mxhnil
   1.0E-10  10.0  1.0E-4  0.0  : hmin, hmax, h0, tcrit
   .FALSE.                     : petzld
   0.0  10.0                   : t, tout
   1.0  0.0  0.0               : y
   .FALSE. .FALSE.             : lderiv
   2                           : itol
   1.0E-4                      : rtol
   1.0E-6 1.0E-7 1.0E-6        : atol


d02njfe.d

D02NJF Example Program Data
   5  200  5                        : maxord, maxstp, mxhnil
   1  3  6  9                       : ia
   1  2  1  2  3  1  2  3           : ja
   1.0E-10  10.0  0.0  0.0          : hmin, hmax, h0, tcrit
   1.0E-4  1.0E-6  0.1              : eta, sens, u
   .TRUE.                           : lblock
   0.0  10.0                        : t, tout
   3  0                             : itol, isplit
   1.0  0.0  0.0                    : y
   1.0E-4  1.0E-3  1.0E-4           : rtol
   1.0E-7                           : atol


d02nmfe.d

D02NMF Example Program Data
   5  200  5                  : maxord, maxstp, mxhnil
   1.0E-10  10.0  0.0  0.0    : hmin, hmax, h0, tcrit
   .FALSE.                    : petzld
   0.0  10.0                  : t, tout
   1                          : itol
   1.0  0.0  0.0              : y
   1.0E-4  1.0E-7             : rtol, atol


d02nnfe.d

D02NNF Example Program Data
   5  200  5                        : maxord, maxstp, mxhnil
   1.0E-10  10.0  1.0E-4  0.0       : hmin, hmax, h0, tcrit
   1.0E-4  1.0E-6  0.1              : eta, sens, u
   .TRUE. .TRUE.                    : lblock, petzld
   0.0  10.0                        : t, tout
   1  0                             : itol, isplit
   1.0  0.0  0.0                    : y(1:neq)
   1.0E-4  1.0E-7                   : rtol(1), atol(1)


d02pefe.d

D02PEF Example Program Data
   1                              : method
   0.0     6.28318530717958647692 : tstart, tend
   0.0     1.0                    : yinit(1:n)
   0.0                            : hstart
   1.0E-8  1.0E-8                 : thresh(1:n)


d02pffe.d

D02PFF Example Program Data
   2                              : method
   0.0  6.28318530717958647692    : tstart, tend
   0.0  1.0                       : ystart(1:n)
   0.0                            : hstart
   1.0E-8  1.0E-8                 : thres(1:n)


d02pgfe.d

D02PGF Example Program Data
   2                              : method
   0.0  6.28318530717958647692    : tstart, tend
   0.0  1.0                       : ystart(1:n)
   0.0                            : hstart
   1.0E-8  1.0E-8                 : thres(1:n)


d02prfe.d

D02PRF Example Program Data
  -3                                                   : method
   0.0                       18.8495559215387594307    : tstart, tfinal
   0.3      0.0      0.0      2.38047614284761666599   : yinit
   0.0                                                 : hstart
   1.0E-10  1.0E-10  1.0E-10  1.0E-10                  : thresh


d02psfe.d

D02PSF Example Program Data
   2  -1                              : n, method
   0.0  6.28318530717958647692        : tstart, tend
   0.0  1.0                           : yinit(1:n)
   0.0                                : hstart
   1.0E-8  1.0E-8                     : thresh(1:n)


d02pufe.d

D02PUF Example Program Data
   3                                                 : method
   0.0                        9.42477796076937971538 : tstart, tend
   0.3      0.0      0.0      2.38047614284761666599 : yinit(1:n)
   0.0      1.0E-6                                   : hstart, tol
   1.0E-10  1.0E-10  1.0E-10  1.0E-10                : thresh(1:n)


d02qffe.d

D02QFF Example Program Data
   0.0  0.0  10.0                          : hmax, tstart, tcrit
   S                                       : statef
   .TRUE. .FALSE. .TRUE. .TRUE.            : vectol, onestp, crit, sophst
   0                                       : maxstp
   1.0E-4  1.0E-4                          : rtol
   1.0E-6  1.0E-6                          : atol
   0.0  1.0                                : y


d02qgfe.d

D02QGF Example Program Data
   1  1                                    : latol, lrtol
   2.0  0.0  10.0  2.0                     : hmax, tstart, tcrit, tinc
   S                                       : statef
   .FALSE. .FALSE. .TRUE. .TRUE.           : vectol, onestp, crit, sophst
   500                                     : maxstp
   1.0E-4  1.0E-7                          : rtol, atol
   0.5  0.5  6.28318530717958647692E-1     : y


d02qzfe.d

D02QZF Example Program Data
   2.0  0.0                                            : hmax, tstart
   1.57079632679489661923  1.96349540849362077403E-1   : tcrit, tinc
   S                                                   : statef
   .TRUE. .TRUE. .TRUE.                                : vectol, onestp, crit
   500                                                 : maxstp
   1.0E-4  1.0E-4                                      : rtol
   1.0E-8  1.0E-8                                      : atol
   0.0  1.0                                            : y


d02rafe.d

D02RAF Example Program Data
   40  17              : max mesh size, initial mesh size
   1.0E-4 1.0E-1       : tol, deleps
   0  1  2  0          : init, ijac, numbeg, nummix
   0.0  10.0           : domain end-points


d02safe.d

D02SAF Example Program Data
   3                                   : npoint
   0                                   : icount
   0.0                                 : ymax
   1.0E-3 1.0E-3 1.0E-3 1.0E-3         : pe(1:m)
   1.0E-6 1.0E-6 1.0E-6 1.0E-6         : pf(1:m)
   0.0    0.0    0.0    0.0            : dp(1:m)
   1.0E-5 1.0E-5 1.0E-5                : e (1:n)
   1.2    0.032  2.5    0.02           : p (1:m)


d02tgfe.d

D02TGF Example Program Data
   8  15                : mimax, kp
   -1.0  1.0            : x0, x1


d02tkfe.d

D02TKF Example Program Data
   7  11  51                 : ncol, nmesh, mxmesh
   1.0                       : omega
   1.0E-4 1.0E-4 1.0E-4      : tol(1:neq)
   3                         : ncount
   1.0E+6                    : r


d02tlfe.d

D02TLF Example Program Data
   7  11  51                 : ncol, nmesh, mxmesh
   1.0                       : omega
   1.0E-4 1.0E-4 1.0E-4      : tol(1:neq)
   3                         : ncount
   1.0E+6                    : r


d02tvfe.d

D02TVF Example Program Data
 5  11  100                   : ncol, nmesh, mxmesh
 1575.0 0.01 0.0279 0.02      : beta0, eta, lambda, mu
 1.0E-5 1.0E-5 1.0E-5
 1.0E-5 1.0E-5 1.0E-5         : tols(1:neq)


d02txfe.d

D02TXF Example Program Data
   6  21  250    : (method parameters) ncol, nmesh, mxmesh
   1.0E-5 1.0E-5 : tolerances
   0.2 60.0 0.24 : (problem parameters) en, el_init, s_init
   3             : ncont


d02tyfe.d

D02TYF Example Program Data
   4  6  100                   : ncol, nmesh, mxmesh
   1.0                         : a
   1.0E-5                      : tol


d02tzfe.d

D02TZF Example Program Data
   5   7   50                       : ncol, nmesh, mxmesh
 -0.333333333333333333333
  0.333333333333333333333   0.001   : alpha, beta, eps
  0.0 0.15 0.3 0.5 0.7 0.85 1.0     : mesh(1:nmesh)
   1   2    1   2   1   2    1      : ipmesh(1:nmesh)
  1.0E-5                            : tol


d02udfe.d

D02UDF Example Program Data
  16              : N


d02uefe.d

D02UEF Example Program Data
  16              : N


d02uwfe.d

D02UWF Example Program Data
  64  17          : N  NIP


d02uyfe.d

D02UYF Example Program Data
  64           : N


d02uzfe.d

D02UZF Example Program Data
  16, 9              : N, M


d02zafe.d

D02ZAF Example Program Data
   5  200  5                        : maxord, maxstp, mxhnil
   1.0E-10  10.0  0.0  0.0  10.0    : hmin, hmax, h0, t, tout
   .FALSE.                          : petzld
   1                                : itol
   1.0E-4  1.0E-7                   : rtol, atol
   1.0  0.0  0.0                    : y


d03eafe.d

D03EAF Example Program Data
  2 6          : m, n
  F F          : ext, dorm
 16.0          : alpha0
  3.0  0.0
  1.5  2.0
  0.0  4.0
 -1.5  2.0
 -3.0  0.0
  0.0  0.0
  3.0  0.0
  3.0  0.0
  2.0  1.0
  0.0  1.0
 -2.0  1.0
 -1.0  2.0
  0.0  3.0
  1.0  2.0
  2.0  1.0     : x, y
  0.0  1.0
  0.0  1.0
  0.0  1.0
  0.0  1.0
  0.0  1.0
  0.0  1.0     : phi, phid
3              : npts
  2.0  1.0
  2.5  0.5
  3.0  0.0     : p, q


d03ebfe.d

D03EBF Example Program Data
  6 10 18                     : n1, n2, itmax
  0.0 1.0 3.0 6.0 10.0 15.0   : x
  0.0 1.0 3.0 6.0 10.0
  15.0 21.0 28.0 36.0 45.0    : y
  0.1E-5 0.1E-5               : conres, conchn
  1                           : ndir


d03ecfe.d

D03ECF Example Program Data
  4 5 6 18                    : n1, n2, n3, itmax
  0.0 1.0 3.0 6.0             : x
  0.0 1.0 3.0 6.0 10.0        : y
  0.0 1.0 3.0 6.0 10.0, 15.0  : z
  0.1E-5 0.1E-5               : conres, conchn
  1                           : ndir


d03edfe.d

D03EDF Example Program Data
  3                           : levels
  1.7 1.0E-4                  : alpha, acc
  15                          : maxit


d03eefe.d

D03EEF Example Program Data
  3                           : levels
  0.0 1.0                     : xmin, xmax
  0.0 1.0                     : ymin, ymax
  1.0E-6                      : acc
  50                          : maxit


d03fafe.d

D03FAF Example Program Data
  16 32 20                    : l, m, n
  -2.0                        : lambda
  0.0 1.0                     : xs, xf
  0.0 6.28318530717958647692  : ys, yf
  0.0 1.57079632679489661923  : zs, zf
  1 0 2                       : lbdcnd, mbdcnd, nbdcnd


d03mafe.d

D03MAF Example Program Data
  20 100              : sddist, sdindx
  4.0                 : h
  3 5 10              : m, n, nb


d03ncfe.d

D03NCF Example Program Data
  21  11  4                : ns, nt, ntkeep
  4                        : kopt
  50.                      : x
  'U'                      : mesh
  0.0  100.                : s(1), s(ns)
  0.0  0.4166667           : t(1), t(nt)
  1.0                      : alpha
  .FALSE. .FALSE. .FALSE.  : tdpar
  0.0  0.1  0.4            : q(1), r(1), sigma(1)


d03ndfe.d

D03NDF Example Program Data
  21  4                     : ns, nt
  2                         : kopt
  50.                       : x
  0.4166667                 : tmat
  0.0  0.1  0.4             : q(1), r(1), sigma(1)
  0.0  100.                 : s(1), s(ns)
  0.0  0.125                : t(1), t(nt)
  .FALSE. .FALSE. .FALSE.   : tdpar


d03nefe.d

D03NEF Example Program Data
  21  4  6              : ns, nt, ntd
  2                     : kopt
  50.                   : x
  0.4166667             : tmat
  0.0  100.             : s(1), s(ns)
  0.0  0.125            : t(1), t(nt)
  0.00 0.10 0.20
  0.30 0.40 0.50        : td
  0.10 0.11 0.12
  0.13 0.14 0.15        : rd
  0.30 0.46 0.54
  0.54 0.46 0.30        : sigd
  .TRUE. .FALSE. .TRUE. : tdpar
  0.0                   : q(1)


d03pcae.d

D03PCA Example Program Data
  6 20 1                    : intpts, npts, itype
  0.0 0.4 0.6 0.8 0.9 1.0   : xout(1:intpts)
  1.0E-3 1.0                : acc, alpha
  1 0                       : m, itrace
  0.0 0.1E-4                : ts, tout


d03pcfe.d

D03PCF Example Program Data
  6 20 1                    : intpts, npts, itype
  0.0 0.4 0.6 0.8 0.9 1.0   : xout(1:intpts)
  1.0E-3 1.0                : acc, alpha
  1 0                       : m, itrace
  0.0 0.1E-4                : ts, tout


d03pdae.d

D03PDA Example Program Data
  6 10 3 1                     : intpts, nbkpts, npoly, itype
  -1.0 -0.6 -0.2 0.2 0.6 1.0   : xout(1:intpts)
  1.0E-4                       : acc
  0 0                          : m, itrace
  0.0 0.1E-4                   : ts, tout


d03pdfe.d

D03PDF Example Program Data
  6 10 3 1                     : intpts, nbkpts, npoly, itype
  -1.0 -0.6 -0.2 0.2 0.6 1.0   : xout
  1.0E-4                       : acc
  0 0                          : m, itrace
  0.0 0.1E-4                   : ts, tout


d03pefe.d

D03PEF Example Program Data
  41                : npts
  0.1E-5            : acc
  0                 : itrace
  0.0 0.0           : ts, tout


d03pffe.d

D03PFF Example Program Data
 101      20      7      : (Ex1) npts, inc, outpts
   0.1E-3  0.1E-4        : acc
   0                     : itrace
   0.0                   : tsmax
   0.0                   : ts

 151        7            : (Ex2) npts, outpts
   1        4       37
  76      112      148
 151                     : iout(1:outpts)
   0.1E-4   0.1E-4       : acc
   0                     : itrace
   0.02                  : tsmax
   0.0      1.0          : ts, tout


d03phae.d

D03PHA Example Program Data
  0  101                      : m, npts
  1                           : itol
  1.0E-5, 1.0E-5              : atol(1), rtol(1)
  1.0                         : xi(1:nxi)
  A  F                        : norm, laopt


d03phfe.d

D03PHF Example Program Data
  0  101                      : m, npts
  1                           : itol (latol=1,lrtol=1)
  1.0E-5, 1.0E-5              : atol(1), rtol(1)
  1.0E-4                      : ts
  1.0                         : xi(1:nxi)
  A  F                        : norm, laopt


d03pjae.d

D03PJA Example Program Data
  0  30  3                    : m, nbkpts, npoly
  1                           : itol
  1.0E-5  1.0E-5              : atol(1), rtol(1)
  1.0                         : xi(1:nxi)
  A  F                        : norm, laopt


d03pjfe.d

D03PJF Example Program Data
  0      30       3           : m, nbkpts, npoly
  1                           : itol
  1.0E-5  1.0E-5              : atol(1), rtol(1)
  1.0E-4                      : ts
  1.0                         : xi(1:nxi)
  A       F                   : norm, laopt


d03pkfe.d

D03PKF Example Program Data
  21                          : npts
  1                           : itol
  0.1E-3  0.1E-3              : atol(1), rtol(1)
  1.0E-4                      : ts
  1.0                         : xi(1:nxi)
  A  F                        : norm, laopt


d03plfe.d

D03PLF Example Program Data
  201                         : (ex1) npts
    1                         : itol
  '1'                         : norm
    0.1E-4  0.25E-3           : atol(1), rtol(1)

  141      14                 : (ex2) npts, nskip
    1                         : itol
  '2'                         : norm
    0.5E-2  0.5E-3            : atol(1), rtol(1)


d03ppae.d

D03PPA Example Program Data
 61  5  1           : npts, intpts, itype
 1                  : itol
 0.5E-4  0.5E-4     : atol(1), rtol(1)
 0.5E-2             : e


d03ppfe.d

D03PPF Example Program Data
 61  5  1                     : npts, intpts, itype
 1                            : itol
 0.5E-4  0.5E-4               : atol(1), rtol(1)
 0.5E-2                       : e


d03prfe.d

D03PRF Example Program Data
 61   5  1                 : npts, intpts, itype
 1                         : itol
 0.5E-4  0.5E-4            : atol(1), rtol(1)
 0.0 0.25 0.5 0.75 1.0     : xout(1:intpts)
 A  F                      : norm, laopt


d03psfe.d

D03PSF Example Program Data
61  7  1                        : npts, intpts, itype
 0.2 0.3 0.4 0.5 0.6 0.7 0.8    : xout(1:intpts)
 1                              : itol
 '1'                            : norm
 0.1E-3  0.1E-3                 : atol(1), rtol(1)

61  7  1                        : npts, intpts, itype
 0.0 0.3 0.4 0.5 0.6 0.7 1.0    : xout(1:intpts)
 1                              : itol
 '1'                            : norm
 0.5E-3  0.5E-1                 : atol(1), rtol(1)


d03rafe.d

D03RAF Example Program Data
 2000                   : npts

 2000                   : npts


d03rbfe.d

D03RBF Example Program Data
 3000  5            : npts, mxlev


d03uafe.d

D03UAF Example Program Data
 6  10  10                        : n1, n2, nits
 0.0  1.0  3.0  6.0  10.0  15.0   : x
 0.0  1.0  3.0  6.0  10.0  15.0
 21.0  28.0  36.0  45.0           : y


d03ubfe.d

D03UBF Example Program Data
 4  5  6  10                      : n1, n2, n3, nits
 0.0  1.0  3.0  6.0               : x
 0.0  1.0  3.0  6.0  10.0         : y
 0.0  1.0  3.0  6.0  10.0  15.0   : z


d06aafe.d

D06AAF Example Program Data
   40  30  30   250   : nvb1, nvb2, nvb3, nvmax
   'N'                : Print mesh? 'Y' or 'N'


d06abfe.d.short

D06ABF Example Program Data
       128       40       6000        : nrae  nvint  nvmax
       'N'                            : Printing mesh? 'Y' or 'N'

  01     0.000000E+00  0.000000E+00
            .
            .
            .
 128     0.602000E-03  -.316000E-02   : RAE Aerofoil 2822


d06acfe.d

D06ACF Example Program Data
 8  2000  200                                       :NLINES (m), NVMAX, NEDMX
  0.0000   1.0000  -3.0000   6.0000   0.8000
  1.8000   1.5000   1.5000                          :(COORCH(1,1:m))
  0.0000   0.0000   0.0000   0.0000  -0.3000
 -0.3000   4.5000  -4.5000                          :(COORCH(2,1:m))
21  2  1  1   1.0000 21  1  2  2   1.0000
11  3  8  3   1.0000 11  4  7  3   1.0000
21  6  5  4   1.0000 21  5  6  5   1.0000
11  7  3  3   1.0000 11  8  4  3   1.0000 :(LINE(:,j),RATE(j),j=1,m)
 3                                    :NCOMP (n, number of contours)
-2                                     :number of lines in contour 1
 1  2                                            :lines of contour 1
 4                                     :number of lines in contour 2
 3  8  4  7                                      :lines of contour 2
-2                                     :number of lines in contour 3
 5  6                                            :lines of contour 3
'N'                                      :Printing option 'Y' or 'N'


d06cafe.d

D06CAF Example Program Data
20 20    :IMAX JMAX
87.0     :DELTA
'N'      :Printing option 'Y' or 'N'


d06dbfe.d

D06DBF Example Program Data
Example 2
  9      700      200                  : 1st geometry nlines(m), nvmax, nedmx
  2.0000   2.0000   1.0000
 -1.0000  -2.2361   0.0000
  0.0000   0.0000   0.0000             : coorch(1,1:m)
 -1.0000   1.0000   0.0000
  0.0000   0.0000  -2.2361
 -1.0000   1.0000   2.2361             : coorch(2,1:m)
 10        1        2        0     1.0
 10        2        9        2     1.0
 10        9        5        2     1.0
 10        5        6        2     1.0
 10        6        1        2     1.0
 10        3        8        1     1.0
 10        8        4        1     1.0
 10        4        7        1     1.0
 10        7        3        1     1.0 : line(1:4,j),rate(j), j=1,m
  2                                    : contours (outer+inner)
  5                                    :  lines in contour 1: outer
  1        2        3        4     5
 -4                                    :  lines in contour 2: inner
  9        8        7        6

  4                                    : 2nd geometry nlines(m)
  2.0      6.0      6.0      2.0       : coorch(1,1:m)
 -1.0     -1.0      1.0      1.0       : coorch(2,1:m)
 19        1        2        0     1.0
 10        2        3        0     1.0
 19        3        4        0     1.0
 10        4        1        0     1.0 : line(1:4,j),rate(j), j=1,m
  1                                    : contours (rectangle)
  4                                    :  lines in contour 1
  1        2        3        4


e01aafe.d

E01AAF Example Program Data
  5     0.28
    -1.00   -0.50    0.00    0.50    1.00    1.50
     0.00   -0.53   -1.00   -0.46    2.00   11.09


e01abfe.d

E01ABF Example Program Data
  3     0.56
     0.00   -0.53   -1.00   -0.46    2.00   11.09


e01aefe.d

E01AEF Example Program Data
    4      2.0    6.0            : m, xmin, xmax
    0      1      0      2       : ip(1:m), n=1+2+1+3=7
    2.0    4.0    5.0    6.0     : x(1:m)
    1.0
    2.0   -1.0
    1.0
    2.0    4.0   -2.0            : y(1:n)


e01befe.d

E01BEF Example Program Data
   9                 N, the number of data points
  7.99   0.00000E+0  X(R), F(R), independent and dependent variable
  8.09   0.27643E-4
  8.19   0.43750E-1
  8.70   0.16918E+0
  9.20   0.46943E+0
 10.00   0.94374E+0
 12.00   0.99864E+0
 15.00   0.99992E+0
 20.00   0.99999E+0  End of data points
  11                 M, the number of evaluation points


e01bffe.d

E01BFF Example Program Data
   9                             N, the number of data points
  7.990  0.00000E+0  0.00000E+0  X(R), F(R), D(R)
  8.090  0.27643E-4  5.52510E-4
  8.190  0.43749E-1  0.33587E+0
  8.700  0.16918E+0  0.34944E+0
  9.200  0.46943E+0  0.59696E+0
  10.00  0.94374E+0  6.03260E-2
  12.00  0.99864E+0  8.98335E-4
  15.00  0.99992E+0  2.93954E-5
  20.00  0.99999E+0  0.00000E+0  End of data points
   11                            M, the number of evaluation points


e01bgfe.d

E01BGF Example Program Data
   9                             N, the number of data points
  7.990  0.00000E+0  0.00000E+0  X(R), F(R), D(R)
  8.090  0.27643E-4  5.52510E-4
  8.190  0.43749E-1  0.33587E+0
  8.700  0.16918E+0  0.34944E+0
  9.200  0.46943E+0  0.59696E+0
  10.00  0.94374E+0  6.03260E-2
  12.00  0.99864E+0  8.98335E-4
  15.00  0.99992E+0  2.93954E-5
  20.00  0.99999E+0  0.00000E+0  End of data points
   11                            M, the number of evaluation points


e01bhfe.d

E01BHF Example Program Data
 9                                N, the number of data points
   7.990  0.00000E+0  0.00000E+0  X(R), F(R), D(R)
   8.090  0.27643E-4  5.52510E-4
   8.190  0.43749E-1  0.33587E+0
   8.700  0.16918E+0  0.34944E+0
   9.200  0.46943E+0  0.59696E+0
   10.00  0.94374E+0  6.03260E-2
   12.00  0.99864E+0  8.98335E-4
   15.00  0.99992E+0  2.93954E-5
   20.00  0.99999E+0  0.00000E+0
   7.99       20.0                A, B pairs until end of file
   10.0       12.0
   12.0       10.0
   15.0       15.0


e01rafe.d

E01RAF Example Program Data
   0.0     1.0     2.0     3.0     4.0
   4.0     2.0     4.0     7.0    10.4


e01rbfe.d

E01RBF Example Program Data
   4.000   1.000   0.750  -1.000
   0.000   3.000   1.000
   6.000


e01tlfe.d

E01TLF Example Program Data
1  1  1762543  43331            genid, subid, seed(1), seed(2)
30                              M the number of data points
8                               N the number of evaluation points


e01tnfe.d

E01TNF Example Program Data
1  1  1762543  43331            genid, subid, seed(1), seed(2)
30                              M the number of data points
8                               N the number of evaluation points


e01znfe.d

E01ZNF Example Program Data
1  1  1762543     : genid, subid, seed(1)
120               : M, the number of data points
9                 : N, the number of evaluation points


e02adfe.d

E02ADF Example Program Data
  11
   3   2
     1.00    10.40     1.00
     2.10     7.90     1.00
     3.10     4.70     1.00
     3.90     2.50     1.00
     4.90     1.20     1.00
     5.80     2.20     0.80
     6.50     5.10     0.80
     7.10     9.20     0.70
     7.80    16.10     0.50
     8.40    24.50     0.30
     9.00    35.30     0.20


e02aefe.d

E02AEF Example Program Data
  11
   4
     2.0000
     0.5000
     0.2500
     0.1250
     0.0625


e02affe.d

E02AFF Example Program Data
  10
     2.7182
     2.5884
     2.2456
     1.7999
     1.3620
     1.0000
     0.7341
     0.5555
     0.4452
     0.3863
     0.3678


e02agfe.d

E02AGF Example Program Data
    2                                               : MF
    1       0                                       : IP
    0.0     4.0                                     : XF
    1.0      -2.0
    9.0                                             : YF
    5                                               : M
       0.5      0.03       1.0
       1.0     -0.75       1.0
       2.0     -1.0        1.0
       2.5     -0.1        1.0
       3.0      1.75       1.0                      : X, Y, W
    4       0.0       4.0                           : K, XMIN, XMAX


e02bbfe.d

E02BBF Example Program Data
  9
   4
     1.00
     1.00
     1.00
     1.00
     3.00
     6.00
     8.00
     9.00
     9.00
     9.00
     9.00
     1.00
     2.00
     4.00
     7.00
     6.00
     4.00
     3.00


e02bcfe.d

E02BCF Example Program Data
   7   7
  0.0      0.0      0.0      0.0      1.0      3.0      3.0      3.0
  4.0      4.0      6.0      6.0      6.0      6.0
 10.0     12.0     13.0     15.0     22.0     26.0     24.0     18.0
 14.0     12.0
  0.0
  1.0
  2.0
  3.0
  4.0
  5.0
  6.0


e02bdfe.d

E02BDF Example Program Data
   7
  0.0      0.0      0.0      0.0      1.0      3.0      3.0      3.0
  4.0      4.0      6.0      6.0      6.0      6.0
 10.0     12.0     13.0     15.0     22.0     26.0     24.0     18.0
 14.0     12.0


e02befe.d

E02BEF Example Program Data
  15                              M, the number of data points
  0.0000E+00  -1.1000E+00   1.00  X, Y, W, abscissa, ordinate and weight
  5.0000E-01  -3.7200E-01   2.00
  1.0000E+00   4.3100E-01   1.50
  1.5000E+00   1.6900E+00   1.00
  2.0000E+00   2.1100E+00   3.00
  2.5000E+00   3.1000E+00   1.00
  3.0000E+00   4.2300E+00   0.50
  4.0000E+00   4.3500E+00   1.00
  4.5000E+00   4.8100E+00   2.00
  5.0000E+00   4.6100E+00   2.50
  5.5000E+00   4.7900E+00   1.00
  6.0000E+00   5.2300E+00   3.00
  7.0000E+00   6.3500E+00   1.00
  7.5000E+00   7.1900E+00   2.00
  8.0000E+00   7.9700E+00   1.00  End of data points
  1.0                             S, smoothing factor
  0.5                             S, smoothing factor
  0.1                             S, smoothing factor


e02cbfe.d

E02CBF Example Program Data
.FALSE.           : output data for plotting
   3   2   20    : k, l, m=no of output points.
15.34820
 5.15073
-2.20140
 1.14719
-0.64419
 0.30464
-0.49010
-0.00314
-6.69912
 0.00153
 3.00033
-0.00022         : Chebyshev coefficients
 0.0 4.0 0.1 4.5 : ymin ymax xmin xmax


e02gafe.d

E02GAF Example Program Data
  5
   0.0 4.501
   0.2 4.360
   0.4 4.333
   0.6 4.418
   0.8 4.625


e02gbfe.d

E02GBF Example Program Data
  6
  0.00  0.00
  0.20  0.07
  0.40  0.07
  0.60  0.11
  0.80  0.27
  1.00  0.68


e02gcfe.d

E02GCF Example Program Data
  5
   0.0 4.501
   0.2 4.360
   0.4 4.333
   0.6 4.418
   0.8 4.625


e02jdfe.d

E02JDF Example Program Data
 100                                          : number of data points to fit
  1                                           : global smoothing level
  F                                           : if C^2 smoothing, supersmooth?
  1                                           : no. points for vector evaluation
  0  0                                        : (x_i,y_i) vector to eval.
  101  101                                    : (n_x,n_y) size for mesh eval.
  0  0                                        : mesh lower-left corner
  1  1                                        : mesh upper-right corner
  F                                           : display the computed mesh vals?


e02zafe.d

E02ZAF Example Program Data
  10
   9
  10
0       0.77
0.70    1.06
1.44    0.33
0.21    0.44
1.01    0.50
1.84    0.02
0.71    1.95
1.00    1.20
0.54    0.04
1.53    0.18
1.00
0.80
1.20
0


e04dgae.d

E04DGA Example Program Data
  2                          :Value of N
 -1.0  1.0                   :End of X


e04dgfe.d

E04DGF Example Program Data
  2                          :Value of N
 -1.0  1.0                   :End of X


e04djae.d

E04DJA Example Program Data
  2                                        :Value of N
 -1.0  1.0                                 :End of X


e04djae.opt

Begin   Example options file for  E04DJF
   Iteration Limit  =  25                  *  (Default =  50)
End


e04djfe.d

E04DJF Example Program Data
  2                                        :Value of N
 -1.0  1.0                                 :End of X


e04djfe.opt

Begin   Example options file for  E04DJF
Iteration Limit  =  25                  *  (Default =  50)
Print Level      =   1                  *  (Default =  10)
End


e04mgae.opt

Begin   Example options file for  E04MGA
   Crash Tolerance  =  0.05    *  (Default = 0.01)
   Iteration Limit  =  25      *  (Default = 70)
End


e04mgfe.opt

Begin   Example options file for  E04MGF
   Crash Tolerance  =  0.05    *  (Default = 0.01)
   Iteration Limit  =  25      *  (Default = 70)
End


e04mwfe.d

E04MWF Example Program Data
 7  8                      : Values of N and M
48  8  7  9  15            : Values of NNZ, IOBJ, NCOLH, NNZH and NNAME

'...X1...'  '...X2...'  '...X3...'  '...X4...'  '...X5...'
'...X6...'  '...X7...'  '..ROW1..'  '..ROW2..'  '..ROW3..'
'..ROW4..'  '..ROW5..'  '..ROW6..'  '..ROW7..'  '..COST..' : End of array NAMES

    0.02   7   1   : Sparse matrix A, ordered by increasing column index;
    0.02   5   1   : each row contains ACOL(i), INDA(i), ICOL (= column index)
    0.03   3   1   : The row indices may be in any order. In this example
    1.00   1   1   : row 8 defines the linear objective term transpose(C)*X.
    0.70   6   1
    0.02   4   1
    0.15   2   1
 -200.00   8   1
    0.06   7   2
    0.75   6   2
    0.03   5   2
    0.04   4   2
    0.05   3   2
    0.04   2   2
    1.00   1   2
-2000.00   8   2
    0.02   2   3
    1.00   1   3
    0.01   4   3
    0.08   3   3
    0.08   7   3
    0.80   6   3
-2000.00   8   3
    1.00   1   4
    0.12   7   4
    0.02   3   4
    0.02   4   4
    0.75   6   4
    0.04   2   4
-2000.00   8   4
    0.01   5   5
    0.80   6   5
    0.02   7   5
    1.00   1   5
    0.02   2   5
    0.06   3   5
    0.02   4   5
-2000.00   8   5
    1.00   1   6
    0.01   2   6
    0.01   3   6
    0.97   6   6
    0.01   7   6
  400.00   8   6
    0.97   7   7
    0.03   2   7
    1.00   1   7
  400.00   8   7    : End of matrix A

  2.0      1   1    : Sparse matrix H, stored in a lower triangular matrix,
  2.0      2   2    : ordered by increasing column index; each row contains
  2.0      3   3    : H(i), IROWH(i), ICOL (= column index)
  2.0      4   3    : The row indices may be in any order.
  2.0      4   4
  2.0      5   5
  2.0      6   6
  2.0      7   6
  2.0      7   7    : End of matrix H

 0.0       0.0       4.0E+02   1.0E+02   0.0       0.0
 0.0       2.0E+03  -1.0E+25  -1.0E+25  -1.0E+25  -1.0E+25
 1.5E+03   2.5E+02  -1.0E+25             : End of lower bounds array BL

 2.0E+02   2.5E+03   8.0E+02   7.0E+02  1.5E+03  1.0E+25
 1.0E+25   2.0E+03   6.0E+01   1.0E+02  4.0E+01  3.0E+01
 1.0E+25   3.0E+02   1.0E+25             : End of upper bounds array BU

  0.0  0.0  0.0  0.0  0.0  0.0  0.0       : Initial vector X


e04mxfe.opt

NAME          E04MX.EX
ROWS
 L  ..ROW1..
 L  ..ROW2..
 L  ..ROW3..
 N  ..COST..
COLUMNS
    ...X1...  ..ROW1..      1.0        ..ROW2..         1.0
    ...X1...  ..ROW3..      1.0        ..COST..        -4.0
    ...X2...  ..ROW1..      1.0        ..ROW2..         2.0
    ...X2...  ..ROW3..     -1.0        ..COST..        -1.0
    ...X3...  ..ROW1..      1.0        ..ROW2..         3.0
    ...X3...  ..ROW3..      1.0        ..COST..        -1.0
    ...X4...  ..ROW1..      1.0        ..ROW2..         4.0
    ...X4...  ..ROW3..     -1.0        ..COST..        -1.0
    ...X5...  ..ROW1..      1.0        ..ROW2..        -2.0
    ...X5...  ..ROW3..      1.0        ..COST..        -1.0
    ...X6...  ..ROW1..      1.0        ..ROW2..         1.0
    ...X6...  ..ROW3..      1.0        ..COST..        -1.0
    ...X7...  ..ROW1..      1.0        ..ROW2..         1.0
    ...X7...  ..ROW3..      1.0        ..COST..        -1.0
    ...X8...  ..ROW1..      1.0        ..ROW2..         1.0
    ...X8...  ..ROW3..      1.0        ..COST..        -0.1
    ...X9...  ..ROW1..      4.0        ..ROW2..         1.0
    ...X9...  ..ROW3..      1.0        ..COST..        -0.3
RHS
    RHS1      ..ROW1..      1.5
    RHS1      ..ROW2..      1.5
    RHS1      ..ROW3..      4.0
    RHS1      ..COST..      1000.0
RANGES
    RANGE1    ..ROW1..      3.5
    RANGE1    ..ROW2..      3.5
    RANGE1    ..ROW3..      6.0
BOUNDS
 LO BOUND     ...X1...     -2.0
 LO BOUND     ...X2...     -2.0
 LO BOUND     ...X3...     -2.0
 LO BOUND     ...X4...     -2.0
 LO BOUND     ...X5...     -2.0
 LO BOUND     ...X6...     -2.0
 LO BOUND     ...X7...     -2.0
 LO BOUND     ...X8...     -2.0
 LO BOUND     ...X9...     -2.0
 UP BOUND     ...X1...      2.0
 UP BOUND     ...X2...      2.0
 UP BOUND     ...X3...      2.0
 UP BOUND     ...X4...      2.0
 UP BOUND     ...X5...      2.0
 UP BOUND     ...X6...      2.0
 UP BOUND     ...X7...      2.0
 UP BOUND     ...X8...      2.0
 UP BOUND     ...X9...      2.0
QUADOBJ
    ...X1...  ...X1...  2.00000000E0   ...X2...  1.00000000E0
    ...X1...  ...X3...  1.00000000E0   ...X4...  1.00000000E0
    ...X1...  ...X5...  1.00000000E0
    ...X2...  ...X2...  2.00000000E0   ...X3...  1.00000000E0
    ...X2...  ...X4...  1.00000000E0   ...X5...  1.00000000E0
    ...X3...  ...X3...  2.00000000E0   ...X4...  1.00000000E0
    ...X3...  ...X5...  1.00000000E0
    ...X4...  ...X4...  2.00000000E0   ...X5...  1.00000000E0
    ...X5...  ...X5...  2.00000000E0
ENDATA


e04mzfe.opt

NAME          QP
ROWS
 L  ..ROW1..
 L  ..ROW2..
 L  ..ROW3..
 N  ..COST..
COLUMNS
    ...X1...  ..ROW1..      1.0        ..ROW2..         1.0
    ...X1...  ..ROW3..      1.0        ..COST..        -4.0
    ...X2...  ..ROW1..      1.0        ..ROW2..         2.0
    ...X2...  ..ROW3..     -1.0        ..COST..        -1.0
    ...X3...  ..ROW1..      1.0        ..ROW2..         3.0
    ...X3...  ..ROW3..      1.0        ..COST..        -1.0
    ...X4...  ..ROW1..      1.0        ..ROW2..         4.0
    ...X4...  ..ROW3..     -1.0        ..COST..        -1.0
    ...X5...  ..ROW1..      1.0        ..ROW2..        -2.0
    ...X5...  ..ROW3..      1.0        ..COST..        -1.0
    ...X6...  ..ROW1..      1.0        ..ROW2..         1.0
    ...X6...  ..ROW3..      1.0        ..COST..        -1.0
    ...X7...  ..ROW1..      1.0        ..ROW2..         1.0
    ...X7...  ..ROW3..      1.0        ..COST..        -1.0
    ...X8...  ..ROW1..      1.0        ..ROW2..         1.0
    ...X8...  ..ROW3..      1.0        ..COST..        -0.1
    ...X9...  ..ROW1..      4.0        ..ROW2..         1.0
    ...X9...  ..ROW3..      1.0        ..COST..        -0.3
RHS
    RHS1      ..ROW1..      1.5
    RHS1      ..ROW2..      1.5
    RHS1      ..ROW3..      4.0
RANGES
    RANGE1    ..ROW1..      3.5
    RANGE1    ..ROW2..      3.5
    RANGE1    ..ROW3..      6.0
BOUNDS
 LO BOUND     ...X1...     -2.0
 LO BOUND     ...X2...     -2.0
 LO BOUND     ...X3...     -2.0
 LO BOUND     ...X4...     -2.0
 LO BOUND     ...X5...     -2.0
 LO BOUND     ...X6...     -2.0
 LO BOUND     ...X7...     -2.0
 LO BOUND     ...X8...     -2.0
 LO BOUND     ...X9...     -2.0
 UP BOUND     ...X1...      2.0
 UP BOUND     ...X2...      2.0
 UP BOUND     ...X3...      2.0
 UP BOUND     ...X4...      2.0
 UP BOUND     ...X5...      2.0
 UP BOUND     ...X6...      2.0
 UP BOUND     ...X7...      2.0
 UP BOUND     ...X8...      2.0
 UP BOUND     ...X9...      2.0
ENDATA


e04ndae.opt

Begin   Example options file for  E04NDA
   Iteration Limit   =  30      *  (Default =  90)
End


e04ndfe.opt

Begin   Example options file for  E04NDF
   Iteration Limit   =  30      *  (Default =  90)
End


e04ngae.opt

Begin   Example options file for  E04NGA
   Feasibility Phase Iteration Limit  =   5    *  (Default = 70)
   Optimality  Phase Iteration Limit  =  10    *  (Default = 70)
End


e04ngfe.opt

Begin   Example options file for  E04NGF
   Feasibility Phase Iteration Limit  =   5    *  (Default = 70)
   Optimality  Phase Iteration Limit  =  10    *  (Default = 70)
End


e04nlae.opt

Begin * Example options file for E04NLA
   Iteration Limit = 25  * (Default = 75)
End


e04nlfe.opt

Begin * Example options file for E04NLF
   Iteration Limit = 25  * (Default = 75)
       Print Level =  1  * (Default = 10)
End


e04nqfe.d

E04NQF Example Program Data
 7  8                      : Values of N and M
48  8  7  'C'  15          : Values of NNZ, IOBJ, NCOLH, START and NNAME

'...X1...'  '...X2...'  '...X3...'  '...X4...'  '...X5...'
'...X6...'  '...X7...'  '..ROW1..'  '..ROW2..'  '..ROW3..'
'..ROW4..'  '..ROW5..'  '..ROW6..'  '..ROW7..'  '..COST..' : End of array NAMES

    0.02   7   1   : Sparse matrix A, ordered by increasing column index;
    0.02   5   1   : each row contains ACOL(i), INDA(i), ICOL (= column index)
    0.03   3   1   : The row indices may be in any order. In this example
    1.00   1   1   : row 8 defines the linear objective term transpose(C)*X.
    0.70   6   1
    0.02   4   1
    0.15   2   1
 -200.00   8   1
    0.06   7   2
    0.75   6   2
    0.03   5   2
    0.04   4   2
    0.05   3   2
    0.04   2   2
    1.00   1   2
-2000.00   8   2
    0.02   2   3
    1.00   1   3
    0.01   4   3
    0.08   3   3
    0.08   7   3
    0.80   6   3
-2000.00   8   3
    1.00   1   4
    0.12   7   4
    0.02   3   4
    0.02   4   4
    0.75   6   4
    0.04   2   4
-2000.00   8   4
    0.01   5   5
    0.80   6   5
    0.02   7   5
    1.00   1   5
    0.02   2   5
    0.06   3   5
    0.02   4   5
-2000.00   8   5
    1.00   1   6
    0.01   2   6
    0.01   3   6
    0.97   6   6
    0.01   7   6
  400.00   8   6
    0.97   7   7
    0.03   2   7
    1.00   1   7
  400.00   8   7        : End of matrix A

 0.0       0.0       4.0E+02   1.0E+02   0.0       0.0
 0.0       2.0E+03  -1.0E+25  -1.0E+25  -1.0E+25  -1.0E+25
 1.5E+03   2.5E+02  -1.0E+25             : End of lower bounds array BL

 2.0E+02   2.5E+03   8.0E+02   7.0E+02  1.5E+03  1.0E+25
 1.0E+25   2.0E+03   6.0E+01   1.0E+02  4.0E+01  3.0E+01
 1.0E+25   3.0E+02   1.0E+25             : End of upper bounds array BU

 0    0    0    0    0    0    0         : Initial array HS
 0.0  0.0  0.0  0.0  0.0  0.0  0.0       : Initial vector X


e04nrfe.d

E04NRF Example Program Data
 7  8                      : Values of N and M
48  8  7  'C'  15          : Values of NNZ, IOBJ, NCOLH, START and NNAME

'...X1...'  '...X2...'  '...X3...'  '...X4...'  '...X5...'
'...X6...'  '...X7...'  '..ROW1..'  '..ROW2..'  '..ROW3..'
'..ROW4..'  '..ROW5..'  '..ROW6..'  '..ROW7..'  '..COST..' : End of array NAMES

    0.02   7   1   : Sparse matrix A, ordered by increasing column index;
    0.02   5   1   : each row contains ACOL(i), INDA(i), ICOL (= column index)
    0.03   3   1   : The row indices may be in any order. In this example
    1.00   1   1   : row 8 defines the linear objective term transpose(C)*X.
    0.70   6   1
    0.02   4   1
    0.15   2   1
 -200.00   8   1
    0.06   7   2
    0.75   6   2
    0.03   5   2
    0.04   4   2
    0.05   3   2
    0.04   2   2
    1.00   1   2
-2000.00   8   2
    0.02   2   3
    1.00   1   3
    0.01   4   3
    0.08   3   3
    0.08   7   3
    0.80   6   3
-2000.00   8   3
    1.00   1   4
    0.12   7   4
    0.02   3   4
    0.02   4   4
    0.75   6   4
    0.04   2   4
-2000.00   8   4
    0.01   5   5
    0.80   6   5
    0.02   7   5
    1.00   1   5
    0.02   2   5
    0.06   3   5
    0.02   4   5
-2000.00   8   5
    1.00   1   6
    0.01   2   6
    0.01   3   6
    0.97   6   6
    0.01   7   6
  400.00   8   6
    0.97   7   7
    0.03   2   7
    1.00   1   7
  400.00   8   7        : End of matrix A

 0.0       0.0       4.0E+02   1.0E+02   0.0       0.0
 0.0       2.0E+03  -1.0E+25  -1.0E+25  -1.0E+25  -1.0E+25
 1.5E+03   2.5E+02  -1.0E+25             : End of lower bounds array BL

 2.0E+02   2.5E+03   8.0E+02   7.0E+02  1.5E+03  1.0E+25
 1.0E+25   2.0E+03   6.0E+01   1.0E+02  4.0E+01  3.0E+01
 1.0E+25   3.0E+02   1.0E+25             : End of upper bounds array BU

 0    0    0    0    0    0    0         : Initial array HS
 0.0  0.0  0.0  0.0  0.0  0.0  0.0       : Initial vector X


e04nrfe.opt

Begin example options file
* Comment lines like this begin with an asterisk.
* Switch off output of timing information:
Timing level 0
* Allow elastic variables:
Elastic mode 1
* Set the feasibility tolerance:
Feasibility tolerance 1.0D-4
End


e04pcfe.d

E04PCF Example Program Data
  6  4                                : m, n
  0.05  0.05  0.25 -0.25
  0.25  0.25  0.05 -0.05
  0.35  0.35  1.75 -1.75
  1.75  1.75  0.35 -0.35
  0.30 -0.30  0.30  0.30
  0.40 -0.40  0.40  0.40              : matrix A
  1.0   2.0   3.0   4.0   5.0   6.0   : vector B
  1.0   1.0   1.0   1.0               : Lower bounds
  5.0   5.0   5.0   5.0               : Upper bounds


e04rdfe.opt

" E04RDF Example Program Data
2 =mdim
2 =nblocks
{-2, 2}
10.0 20.0
0 1 1 1 1.0
0 1 2 2 1.5
0 2 1 1 3.0
0 2 2 2 4.0
1 1 1 1 1.0
1 1 2 2 1.0
2 1 2 2 1.0
2 2 1 1 5.0
2 2 1 2 2.0
2 2 2 2 6.0


e04rffe.d

E04RFF Example Program Data
 4                         :: N
 2.0   -1.0    0.0    0.0
-1.0    2.0   -1.0    0.0
 0.0   -1.0    2.0   -1.0
 0.0    0.0   -1.0    2.0  :: End of G


e04rjfe.opt

NAME          E04RJ.EX
ROWS
 L  ..ROW1..
 L  ..ROW2..
 L  ..ROW3..
 N  ..COST..
COLUMNS
    ...X1...  ..ROW1..      1.0        ..ROW2..         1.0
    ...X1...  ..ROW3..      1.0        ..COST..        -4.0
    ...X2...  ..ROW1..      1.0        ..ROW2..         2.0
    ...X2...  ..ROW3..     -1.0        ..COST..        -1.0
    ...X3...  ..ROW1..      1.0        ..ROW2..         3.0
    ...X3...  ..ROW3..      1.0        ..COST..        -1.0
    ...X4...  ..ROW1..      1.0        ..ROW2..         4.0
    ...X4...  ..ROW3..     -1.0        ..COST..        -1.0
    ...X5...  ..ROW1..      1.0        ..ROW2..        -2.0
    ...X5...  ..ROW3..      1.0        ..COST..        -1.0
    ...X6...  ..ROW1..      1.0        ..ROW2..         1.0
    ...X6...  ..ROW3..      1.0        ..COST..        -1.0
    ...X7...  ..ROW1..      1.0        ..ROW2..         1.0
    ...X7...  ..ROW3..      1.0        ..COST..        -1.0
    ...X8...  ..ROW1..      1.0        ..ROW2..         1.0
    ...X8...  ..ROW3..      1.0        ..COST..        -0.1
    ...X9...  ..ROW1..      4.0        ..ROW2..         1.0
    ...X9...  ..ROW3..      1.0        ..COST..        -0.3
RHS
    RHS1      ..ROW1..      1.5
    RHS1      ..ROW2..      1.5
    RHS1      ..ROW3..      4.0
    RHS1      ..COST..      1000.0
RANGES
    RANGE1    ..ROW1..      3.5
    RANGE1    ..ROW2..      3.5
    RANGE1    ..ROW3..      6.0
BOUNDS
 LO BOUND     ...X1...     -2.0
 LO BOUND     ...X2...     -2.0
 LO BOUND     ...X3...     -2.0
 LO BOUND     ...X4...     -2.0
 LO BOUND     ...X5...     -2.0
 LO BOUND     ...X6...     -2.0
 LO BOUND     ...X7...     -2.0
 LO BOUND     ...X8...     -2.0
 LO BOUND     ...X9...     -2.0
 UP BOUND     ...X1...      2.0
 UP BOUND     ...X2...      2.0
 UP BOUND     ...X3...      2.0
 UP BOUND     ...X4...      2.0
 UP BOUND     ...X5...      2.0
 UP BOUND     ...X6...      2.0
 UP BOUND     ...X7...      2.0
 UP BOUND     ...X8...      2.0
 UP BOUND     ...X9...      2.0
QUADOBJ
    ...X1...  ...X1...  2.00000000E0   ...X2...  1.00000000E0
    ...X1...  ...X3...  1.00000000E0   ...X4...  1.00000000E0
    ...X1...  ...X5...  1.00000000E0
    ...X2...  ...X2...  2.00000000E0   ...X3...  1.00000000E0
    ...X2...  ...X4...  1.00000000E0   ...X5...  1.00000000E0
    ...X3...  ...X3...  2.00000000E0   ...X4...  1.00000000E0
    ...X3...  ...X5...  1.00000000E0
    ...X4...  ...X4...  2.00000000E0   ...X5...  1.00000000E0
    ...X5...  ...X5...  2.00000000E0
ENDATA


e04rpfe.d

E04RPF Example Program Data
      5                 : no of variables
      0                 : no of nonzeros in H matrix
      0         0       : no of linear constraints and nnz in B
      2                 : no of matrix constraints

    1.000000    0.000000    1.000000    0.000000
    0.000000                                            : Linear obj. vector

    2                 : beginning of matrix constr 1, its dimension
    9    8            : no of nonzeroes in all A_i, Q_ij

       2                            : number of nonzeros in A_0
       1.000000       1       1     : Upper triangle of A_0
       1.000000       2       2     : End of matrix A_0

       2                            : number of nonzeros in A_1
       2.000000       1       1     : Upper triangle of A_1
      -2.000000       1       2     : End of matrix A_1

       3                            : number of nonzeros in A_2
       6.000000       1       1     : Upper triangle of A_2
       5.000000       1       2     : in coordinate storage
      -4.000000       2       2     : End of matrix A_2

       2                            : number of nonzeros in A_3
       3.000000       1       2     : Upper triangle of A_3
       8.000000       2       2     : End of matrix A_3

       0                            : number of nonzeros in A_4
       0                            : number of nonzeros in A_5
    6                 : number of Q_ij matrices

       1       4                    : indices giving i & j for Q_ij
       1                            : number of nonzeros in Q_{1,4}
       2.000000       1       1     : End of matrix Q_{1,4}

       2       4                    : indices giving i & j for Q_ij
       2                            : number of nonzeros in Q_{2,4}
       2.000000       1       1     : Upper triangle of Q_{2,4}
       1.000000       1       2     : End of matrix Q_{2,4}

       3       4                    : indices giving i & j for Q_ij
       1                            : number of nonzeros in Q_{3,4}
       1.000000       1       2     : End of matrix Q_{3,4}

       1       5                    : indices giving i & j for Q_ij
       1                            : number of nonzeros in Q_{1,5}
       1.000000       1       2     : End of matrix Q_{1,5}

       2       5                    : indices giving i & j for Q_ij
       2                            : number of nonzeros in Q_{2,5}
       1.000000       1       2     : Upper triangle of Q_{2,5}
       2.000000       2       2     : End of matrix Q_{2,5}

       3       5                    : indices giving i & j for Q_ij
       1                            : number of nonzeros in Q_{3,5}
       2.000000       2       2     : End of matrix Q_{3,5}

    2                 : beginning of matrix constr 2, its dimension
    5    0            : no of nonzeroes in all A_i, Q_ij

       2                            : number of nonzeros in A_0
       1.000000       1       1     : Upper triangle of A_0
       1.000000       2       2     : End of matrix A_0

       1                            : number of nonzeros in A_1
       1.000000       1       1     : End of matrix A_1

       1                            : number of nonzeros in A_2
       1.000000       1       2     : End of matrix A_2

       1                            : number of nonzeros in A_3
       1.000000       2       2     : End of matrix A_3

       0                            : number of nonzeros in A_4
       0                            : number of nonzeros in A_5


e04svfe.d

E04SVF Example Program Data
10          : Number of vertices (Petersen graph)
15          : Number of edges
1 2         : List of edges, one per line,
2 3         : given as pairs i j of vertices (i<j)
3 4
4 5
1 5
1 6
2 7
3 8
4 9
5 10
6 8
6 9
7 9
7 10
8 10


e04ucae.d

E04UCA Example Program Data
  4   1   2                              :Values of N, NCLIN and NCNLN
  1.0   1.0   1.0   1.0                                 :End of matrix A
  1.0   1.0   1.0   1.0  -1.0E+25  -1.0E+25  25.0       :End of BL
  5.0   5.0   5.0   5.0  20.0      40.0       1.0E+25   :End of BU
  1.0   5.0   5.0   1.0                                 :End of X


e04ucfe.d

E04UCF Example Program Data
  4   1   2                              :Values of N, NCLIN and NCNLN
  1.0   1.0   1.0   1.0                                 :End of matrix A
  1.0   1.0   1.0   1.0  -1.0E+25  -1.0E+25  25.0       :End of BL
  5.0   5.0   5.0   5.0  20.0      40.0       1.0E+25   :End of BU
  1.0   5.0   5.0   1.0                                 :End of X


e04udae.d

E04UDA Example Program Data
  4   1   2                              :Values of N, NCLIN and NCNLN
  1.0   1.0   1.0   1.0                                 :End of matrix A
  1.0   1.0   1.0   1.0  -1.0E+25  -1.0E+25  25.0       :End of BL
  5.0   5.0   5.0   5.0  20.0      40.0       1.0E+25   :End of BU
  1.0   5.0   5.0   1.0                                 :End of X


e04udae.opt

Begin   Example options file for  E04UDA
   Major Iteration Limit   =  15      *  (Default =  50)
   Minor Iteration Limit   =  10      *  (Default =  50)
End


e04udfe.d

E04UDF Example Program Data
  4   1   2                              :Values of N, NCLIN and NCNLN
  1.0   1.0   1.0   1.0                                 :End of matrix A
  1.0   1.0   1.0   1.0  -1.0E+25  -1.0E+25  25.0       :End of BL
  5.0   5.0   5.0   5.0  20.0      40.0       1.0E+25   :End of BU
  1.0   5.0   5.0   1.0                                 :End of X


e04udfe.opt

Begin   Example options file for  E04UDF
   Major Iteration Limit   =  15      *  (Default =  50)
   Minor Iteration Limit   =  10      *  (Default =  50)
End


e04ufae.d

E04UFA Example Program Data
  4   1   2                              :Values of N, NCLIN and NCNLN
  1.0   1.0   1.0   1.0                                 :End of matrix A
  1.0   1.0   1.0   1.0  -1.0E+25  -1.0E+25  25.0       :End of BL
  5.0   5.0   5.0   5.0  20.0      40.0       1.0E+25   :End of BU
  1.0   5.0   5.0   1.0                                 :End of X


e04uffe.d

E04UFF Example Program Data
  4   1   2                              :Values of N, NCLIN and NCNLN
  1.0   1.0   1.0   1.0                                 :End of matrix A
  1.0   1.0   1.0   1.0  -1.0E+25  -1.0E+25  25.0       :End of BL
  5.0   5.0   5.0   5.0  20.0      40.0       1.0E+25   :End of BU
  1.0   5.0   5.0   1.0                                 :End of X


e04ugae.d

E04UGA Example Program Data
 4   6              :Values of N and M
 3   4   2          :Values of NCNLN, NONLN and NJNLN
14   6  'C'  10     :Values of NNZ, IOBJ, START and NNAME
'Varble 1'  'Varble 2'  'Varble 3'  'Varble 4'  'NlnCon 1'
'NlnCon 2'  'NlnCon 3'  'LinCon 1'  'LinCon 2'  'Free Row' :End of NAMES
 1.0E+25   1   1
 1.0E+25   2   1
 1.0E+25   3   1
     1.0   5   1
    -1.0   4   1
 1.0E+25   1   2
 1.0E+25   2   2
 1.0E+25   3   2
    -1.0   5   2
     1.0   4   2
     3.0   6   3
    -1.0   1   3
    -1.0   2   4
     2.0   6   4    :End of matrix A
-0.55     -0.55      0.0       0.0     -894.8   -894.8   -1294.8  -0.55
-0.55     -1.0E+25  :End of BL
 0.55      0.55      1200.0    1200.0  -894.8   -894.8   -1294.8   1.0E+25
 1.0E+25   1.0E+25  :End of BU
 0    0    0    0   :End of ISTATE
 0.0  0.0  0.0  0.0 :End of XS
 0.0  0.0  0.0      :End of CLAMDA


e04ugfe.d

E04UGF Example Program Data
 4   6              :Values of N and M
 3   4   2          :Values of NCNLN, NONLN and NJNLN
14   6  'C'  10     :Values of NNZ, IOBJ, START and NNAME
'Varble 1'  'Varble 2'  'Varble 3'  'Varble 4'  'NlnCon 1'
'NlnCon 2'  'NlnCon 3'  'LinCon 1'  'LinCon 2'  'Free Row' :End of NAMES
 1.0E+25   1   1
 1.0E+25   2   1
 1.0E+25   3   1
     1.0   5   1
    -1.0   4   1
 1.0E+25   1   2
 1.0E+25   2   2
 1.0E+25   3   2
    -1.0   5   2
     1.0   4   2
     3.0   6   3
    -1.0   1   3
    -1.0   2   4
     2.0   6   4    :End of matrix A
-0.55     -0.55      0.0       0.0     -894.8   -894.8   -1294.8  -0.55
-0.55     -1.0E+25  :End of BL
 0.55      0.55      1200.0    1200.0  -894.8   -894.8   -1294.8   1.0E+25
 1.0E+25   1.0E+25  :End of BU
 0    0    0    0   :End of ISTATE
 0.0  0.0  0.0  0.0 :End of XS
 0.0  0.0  0.0      :End of CLAMDA


e04uhae.d

E04UHA Example Program Data
  5   1              :Values of N and M
  0   5   0          :Values of NCNLN, NONLN and NJNLN
 'C'  6              :Values of START and NNAME
'Varble 1' 'Varble 2' 'Varble 3' 'Varble 4' 'Varble 5' 'DummyRow' :End of NAMES
 0.0  0.0  0.0  0.0  0.0 -1.0E+26 :End of BL
 1.0  2.0  3.0  4.0  5.0  1.0E+26 :End of BU
 0    0    0    0    0            :End of ISTATE
 2.0  2.0  2.0  2.0  2.0          :End of XS


e04uhae.opt

Begin * Example options file for E04UHA
   Check Frequency = 25   * (Default = 60 )
   Crash Tolerance = 0.05 * (Default = 0.1)
End


e04uhfe.d

E04UHF Example Program Data
  5   1              :Values of N and M
  0   5   0          :Values of NCNLN, NONLN and NJNLN
 'C'  6              :Values of START and NNAME
'Varble 1' 'Varble 2' 'Varble 3' 'Varble 4' 'Varble 5' 'DummyRow' :End of NAMES
 0.0  0.0  0.0  0.0  0.0 -1.0E+26 :End of BL
 1.0  2.0  3.0  4.0  5.0  1.0E+26 :End of BU
 0    0    0    0    0            :End of ISTATE
 2.0  2.0  2.0  2.0  2.0          :End of XS


e04uhfe.opt

Begin * Example options file for E04UHF
   Check Frequency = 25   * (Default = 60 )
   Crash Tolerance = 0.05 * (Default = 0.1)
End


e04uqae.d

E04UQA Example Program Data
  44  2                                :Values of M and N
  1   1                                :Values of NCLIN and NCNLN
  1.0   1.0                            :End of matrix A
  0.49  0.49  0.48  0.47  0.48  0.47  0.46  0.46  0.45  0.43  0.45
  0.43  0.43  0.44  0.43  0.43  0.46  0.45  0.42  0.42  0.43  0.41
  0.41  0.40  0.42  0.40  0.40  0.41  0.40  0.41  0.41  0.40  0.40
  0.40  0.38  0.41  0.40  0.40  0.41  0.38  0.40  0.40  0.39  0.39 :End of Y
  0.4      -4.0      1.0      0.0      :End of BL
  1.0E+25   1.0E+25  1.0E+25  1.0E+25  :End of BU
  0.4   0.0                            :End of X


e04uqae.opt

Begin   Example options file for  E04UQA
   Major Iteration Limit   =  15      *  (Default =  50)
   Minor Iteration Limit   =  10      *  (Default =  50)
End


e04uqfe.d

E04UQF Example Program Data
  44  2                                :Values of M and N
  1   1                                :Values of NCLIN and NCNLN
  1.0   1.0                            :End of matrix A
  0.49  0.49  0.48  0.47  0.48  0.47  0.46  0.46  0.45  0.43  0.45
  0.43  0.43  0.44  0.43  0.43  0.46  0.45  0.42  0.42  0.43  0.41
  0.41  0.40  0.42  0.40  0.40  0.41  0.40  0.41  0.41  0.40  0.40
  0.40  0.38  0.41  0.40  0.40  0.41  0.38  0.40  0.40  0.39  0.39 :End of Y
  0.4      -4.0      1.0      0.0      :End of BL
  1.0E+25   1.0E+25  1.0E+25  1.0E+25  :End of BU
  0.4   0.0                            :End of X


e04uqfe.opt

Begin   Example options file for  E04UQF
   Major Iteration Limit   =  15      *  (Default =  50)
   Minor Iteration Limit   =  10      *  (Default =  50)
End


e04usae.d

E04USA Example Program Data
  44  2                                :Values of M and N
  1   1                                :Values of NCLIN and NCNLN
  1.0   1.0                            :End of matrix A
  0.49  0.49  0.48  0.47  0.48  0.47  0.46  0.46  0.45  0.43  0.45
  0.43  0.43  0.44  0.43  0.43  0.46  0.45  0.42  0.42  0.43  0.41
  0.41  0.40  0.42  0.40  0.40  0.41  0.40  0.41  0.41  0.40  0.40
  0.40  0.38  0.41  0.40  0.40  0.41  0.38  0.40  0.40  0.39  0.39 :End of Y
  0.4      -4.0      1.0      0.0      :End of BL
  1.0E+25   1.0E+25  1.0E+25  1.0E+25  :End of BU
  0.4   0.0                            :End of X


e04usfe.d

E04USF Example Program Data
  44  2                                :Values of M and N
  1   1                                :Values of NCLIN and NCNLN
  1.0   1.0                            :End of matrix A
  0.49  0.49  0.48  0.47  0.48  0.47  0.46  0.46  0.45  0.43  0.45
  0.43  0.43  0.44  0.43  0.43  0.46  0.45  0.42  0.42  0.43  0.41
  0.41  0.40  0.42  0.40  0.40  0.41  0.40  0.41  0.41  0.40  0.40
  0.40  0.38  0.41  0.40  0.40  0.41  0.38  0.40  0.40  0.39  0.39 :End of Y
  0.4      -4.0      1.0      0.0      :End of BL
  1.0E+25   1.0E+25  1.0E+25  1.0E+25  :End of BU
  0.4   0.0                            :End of X


e04vhfe.d

E04VHF Example Program Data
 4   6          : Values of N and NF
 8   8   6   0  : Values of NEA, NEG, OBJROW and START

'X1'  'X2'  'X3'  'X4'  : XNAMES
'NlnCon 1'  'NlnCon 2'  'NlnCon 3'  'LinCon 1'  'LinCon 2'  'Objectiv' : FNAMES

1  3 -1.0E0  : Nonzero elements of sparse matrix A, the linear part of F.
2  4 -1.0E0  : Each row IAFUN(i), JAVAR(i), A(IAFUN(i),JAVAR(i)), i = 1 to NEA
4  1 -1.0E0
4  2  1.0E0
5  1  1.0E0
5  2 -1.0E0
6  3  3.0E0
6  4  2.0E0

1  1     : Nonzero row/column structure of G, IGFUN(i), JGVAR(i), i = 1 to NEG
1  2
2  1
2  2
3  1
3  2
6  3
6  4

-0.55E0    0.55E0  : Bounds on the variables, XLOW(i), XUPP(i), for i = 1 to N
-0.55E0    0.55E0
 0.0E0   1200.0E0
 0.0E0   1200.0E0

 -894.8E0 -894.8E0 : Bounds on the functions, FLOW(i), FUPP(i), for i = 1 to NF
 -894.8E0 -894.8E0
-1294.8E0 -1294.8E0
-0.55E0    1.0E25
-0.55E0    1.0E25
-1.0E25    1.0E25

 0.0  0.0  0.0  0.0           : Initial values of X(i), for i = 1 to N
 0    0    0    0             : Initial values of XSTATE(i), for i = 1 to N
 0.0  0.0  0.0  0.0           : Initial values of XMUL(i), for i = 1 to N

 0.0  0.0  0.0  0.0  0.0  0.0 : Initial values of F(i), for i = 1 to NF
 0    0    0    0    0    0   : Initial values of FSTATE(i), for i = 1 to NF
 0.0  0.0  0.0  0.0  0.0  0.0 : Initial values of FMUL(i), for i = 1 to NF


e04vjfe.d

E04VJF Example Program Data
 4   6             : Values of N and NF
-0.55D0    0.55D0  : Bounds on the variables, XLOW(i), XUPP(i), for i = 1 to N
-0.55D0    0.55D0
 0.0D0   1200.0D0
 0.0D0   1200.0D0

 6                 : Value of OBJROW
 -894.8D0 -894.8D0 : Bounds on the functions, FLOW(i), FUPP(i), for i = 1 to NF
 -894.8D0 -894.8D0
-1294.8D0 -1294.8D0
-0.55D0    1.0D25
-0.55D0    1.0D25
-1.0D25    1.0D25


e04vkfe.d

E04VKF Example Program Data
 4   6          : Values of N and NF
 8   8   6   0  : Values of NEA, NEG, OBJROW and START

'X1'  'X2'  'X3'  'X4'  : XNAMES
'NlnCon 1'  'NlnCon 2'  'NlnCon 3'  'LinCon 1'  'LinCon 2'  'Objectiv' : FNAMES

1  3 -1.0D0  : Nonzero elements of sparse matrix A, the linear part of F.
2  4 -1.0D0  : Each row IAFUN(i), JAVAR(i), A(IAFUN(i),JAVAR(i)), i = 1 to NEA
4  1 -1.0D0
4  2  1.0D0
5  1  1.0D0
5  2 -1.0D0
6  3  3.0D0
6  4  2.0D0

1  1     : Nonzero row/column structure of G, IGFUN(i), JGVAR(i), i = 1 to NEG
1  2
2  1
2  2
3  1
3  2
6  3
6  4

-0.55D0    0.55D0  : Bounds on the variables, XLOW(i), XUPP(i), for i = 1 to N
-0.55D0    0.55D0
 0.0D0   1200.0D0
 0.0D0   1200.0D0

 -894.8D0 -894.8D0 : Bounds on the functions, FLOW(i), FUPP(i), for i = 1 to NF
 -894.8D0 -894.8D0
-1294.8D0 -1294.8D0
-0.55D0    1.0D25
-0.55D0    1.0D25
-1.0D25    1.0D25

 0.0  0.0  0.0  0.0           : Initial values of X(i), for i = 1 to N
 0    0    0    0             : Initial values of XSTATE(i), for i = 1 to N
 0.0  0.0  0.0  0.0           : Initial values of XMUL(i), for i = 1 to N

 0.0  0.0  0.0  0.0  0.0  0.0 : Initial values of F(i), for i = 1 to NF
 0    0    0    0    0    0   : Initial values of FSTATE(i), for i = 1 to NF
 0.0  0.0  0.0  0.0  0.0  0.0 : Initial values of FMUL(i), for i = 1 to NF


e04vkfe.opt

Begin example options file
* Comment lines like this begin with an asterisk.
* Switch off output of timing information:
Timing level 0
* Allow elastic variables:
Elastic mode 1
* Set the feasibility tolerance:
Feasibility tolerance 1.0D-4
End


e04wdfe.d

E04WDF Example Program Data
  4   1   2                                             : N, NCLIN and NCNLN
  1.0   1.0   1.0   1.0                                 : Matrix A
  1.0   1.0   1.0   1.0  -1.0E+25  -1.0E+25  25.0       : Lower bounds BL
  5.0   5.0   5.0   5.0  20.0      40.0      1.0E+25    : Upper bounds BU
  1.0   5.0   5.0   1.0                                 : Initial vector X


e04wefe.d

E04WEF Example Program Data
  4   1   2                                             : N, NCLIN and NCNLN
  1.0   1.0   1.0   1.0                                 : Matrix A
  1.0   1.0   1.0   1.0  -1.0E+25  -1.0E+25  25.0       : Lower bounds BL
  5.0   5.0   5.0   5.0  20.0      40.0      1.0E+25    : Upper bounds BU
  1.0   5.0   5.0   1.0                                 : Initial vector X


e04wefe.opt

Begin example options file
* Comment lines like this begin with an asterisk.
* Switch off output of timing information:
Timing level 0
* Allow elastic variables:
Elastic mode 1
* Set the feasibility tolerance:
Feasibility tolerance 1.0D-4
End


e05jbfe.d

E05JBF Example Program Data
  3                                                     : SDLIST
  0                                                     : IBOUND
  -3.0   -3.0                                           : Lower bounds BL
  3.0   3.0                                             : Upper bounds BU
  0                                                     : IINIT
  .FALSE.                                               : PLOT


e05jcfe.d

E05JCF Example Program Data
  3                                                     : SDLIST
  0                                                     : IBOUND
  -3.0   -3.0                                           : Lower bounds BL
  3.0   3.0                                             : Upper bounds BU
  3                                                     : IINIT
  3   3   3                                             : NUMPTS
  -3.0   -1.0   3.0   -3.0   0.0   3.0                  : Matrix LIST
  2   2   2                                             : INITPT
  .FALSE.                                               : PLOT


e05jcfe.opt

Begin example options file
* Comment lines like this begin with an asterisk
* Set the maximum number of function evaluations
Function Evaluations Limit = 100000
* Set the local search iteration limit
Local Searches Limit = 40
End


e05ucfe.d

E05UCF Example Program Data
2 1000                                  : NB, NPTS
T                                       : REPEAT


e05usfe.d

E05USF Example Program Data
  1.0   1.0                            :End of matrix A
  0.49  0.49  0.48  0.47  0.48  0.47  0.46  0.46  0.45  0.43  0.45
  0.43  0.43  0.44  0.43  0.43  0.46  0.45  0.42  0.42  0.43  0.41
  0.41  0.40  0.42  0.40  0.40  0.41  0.40  0.41  0.41  0.40  0.40
  0.40  0.38  0.41  0.40  0.40  0.41  0.38  0.40  0.40  0.39  0.39 :End of Y
  0.4      -4.0      1.0      0.0      :End of BL
  1.0E+25   1.0E+25  1.0E+25  1.0E+25  :End of BU


f01abfe.d

F01ABF Example Program Data
   4                   : n
   5.   7.   6.   5.
   7.  10.   8.   7.
   6.   8.  10.   9.
   5.   7.   9.  10.   : a


f01adfe.d

F01ADF Example Program Data
   4                   : n
   5.   7.   6.   5.
   7.  10.   8.   7.
   6.   8.  10.   9.
   5.   7.   9.  10.   : a


f01blfe.d

F01BLF Example Program Data
   6  5                                 : m, n
   7.0   -2.0    4.0    9.0    1.8
   3.0    8.0   -4.0    6.0    1.3
   9.0    6.0    1.0    5.0    2.1
  -8.0    7.0    5.0    2.0    0.6
   4.0   -1.0    2.0    8.0    1.3
   1.0    6.0    3.0   -5.0    0.5      : a


f01brfe.d

F01BRF Example Program Data
   6 15                                                           : n, nz
   5.0  1  1   2.0  2  2  -1.0  2  3   2.0  2  4   3.0  3  3
  -2.0  4  1   1.0  4  4   1.0  4  5  -1.0  5  1  -1.0  5  4
   2.0  5  5  -3.0  5  6  -1.0  6  1  -1.0  6  2   6.0  6  6      : a


f01bufe.d

F01BUF Example Program Data
  7  3                 : n, m1
     3
    -9    31
     6    -2   123
    -4   -66   145
    15   -24    61
     4   -74    98
   -18    24     6     : a


f01bvfe.d

F01BVF Example Program Data
  9  2  2              : n, ma1, mb1
    11
    12    12
    13    13
    14    14
    15    15
    16    16
    17    17
    18    18
    19    19           : a
   101
    22   102
    23   103
    24   104
    25   105
    26   106
    27   107
    28   108
    29   109           : b
  1  3                 : m1, m2


f01ckfe.d

F01CKF Example Program Data
  2  2  3           : n, p, m


f01crfe.d

F01CRF Example Program Data
  3  7           : m, n


f01ctfe.d

F01CTF Example Program Data
Example 1:
4 3 'N'  1.0                             : nrowa, ncola, transa, alpha
4 3 'N'  1.0                             : nrowb, ncolb, transb, beta
  1.0   2.5   3.0                        : Matrix A
 -2.0   2.0  -1.5
  3.5   2.0  -2.5
  1.5  -2.0   1.0
  2.0  -2.5  -2.0                        : Matrix B
  1.0   1.0   1.0
 -1.5   2.5  -2.5
  2.0  -2.0   1.0
Example 2:
3 5 'N'  1.0                             : nrowa, ncola, transa, alpha
5 3 'T' -1.0                             : nrowb, ncolb, transb, beta
  1.0   2.5   3.0   1.5   2.5            : Matrix A
 -2.0   2.0  -1.5  -2.0  -1.0
  3.5   2.0  -2.5  -1.5   2.5
  2.0  -2.5  -2.0                        : Matrix B
  1.0   1.0   1.0
 -1.5   2.5  -2.5
  2.0  -2.0   1.0
  1.0   1.0   2.5


f01cwfe.d

F01CWF Example Program Data
Example 1:
4 3 'N'   (1.0, 0.0)                          : nrowa, ncola, transa, alpha
4 3 'N'   (1.0, 0.0)                          : nrowb, ncolb, transb, beta
  ( 1.0, 2.0)  ( 2.5,-1.5)  ( 2.5,-1.0)       : Matrix A
  (-2.0,-2.0)  ( 2.0,-1.0)  (-1.5,-1.0)
  ( 3.5,-1.5)  ( 2.0, 1.5)  ( 2.0, 3.0)
  (-2.5, 0.0)  (-3.0, 2.5)  (-2.0, 2.0)
  ( 2.0, 1.0)  (-2.5, 3.0)  (-0.5, 0.0)       : Matrix B
  ( 1.0, 0.0)  ( 1.0,-1.5)  ( 1.5,-1.5)
  (-1.5,-0.5)  ( 2.5,-2.0)  (-0.5, 1.0)
  ( 2.5,-1.5)  (-1.0, 1.5)  ( 2.0, 3.0)
Example 2:
2 3 'N'   (1.0, 0.0)                          : nrowa, ncola, transa, alpha
3 2 'T'  (-1.0, 0.0)                          : nrowb, ncolb, transb, beta
  ( 1.0, 1.0)  ( 2.5,-1.5)  ( 3.0, 1.5)       : Matrix A
  (-2.0,-0.5)  ( 2.0, 1.5)  (-1.5,-2.5)
  ( 2.0, 1.0)  (-2.5, 2.0)                    : Matrix B
  ( 1.0, 0.0)  ( 1.0, 1.5)
  (-1.5,-0.5)  ( 2.5,-1.0)


f01ecfe.d

F01ECF Example Program Data

  4                      : n

  1.0   2.0   2.0   2.0
  3.0   1.0   1.0   2.0
  3.0   2.0   1.0   2.0
  3.0   3.0   3.0   1.0  : a


f01edfe.d

F01EDF Example Program Data

  4                      : n
 'U'                     : uplo

  1.0   2.0   3.0   4.0
        1.0   2.0   3.0
              1.0   2.0
                    1.0  : a


f01effe.d

F01EFF Example Program Data

  4                      :Value of N
 'U'                     :Value of UPLO

  1.0   2.0   3.0   4.0
        1.0   2.0   3.0
              1.0   2.0
                    1.0  :End of matrix A


f01ejfe.d

F01EJF Example Program Data

4                            :Value of N

3.0    -3.0     1.0     1.0
2.0     1.0    -2.0     1.0
1.0     1.0     3.0    -1.0
2.0     0.0     2.0     0.0  :End of matrix A


f01ekfe.d

F01EKF Example Program Data

4       COS                  :Values of N and FUN

2.0     0.0     1.0     0.0
0.0     2.0    -2.0     1.0
0.0     2.0     3.0     1.0
1.0     4.0     0.0     0.0  :End of matrix A


f01elfe.d

F01ELF Example Program Data

4                             :Value of N

 3.0     0.0     1.0     2.0
-1.0     1.0     3.0     1.0
 0.0     2.0     2.0     1.0
 2.0     1.0    -1.0     1.0  :End of matrix A


f01emfe.d

F01EMF Example Program Data

 4                      :Value of N

 1.0   0.0  -2.0   1.0
-1.0   2.0   0.0   1.0
 2.0   0.0   1.0   0.0
 1.0   0.0  -1.0   2.0  :End of matrix A


f01enfe.d

F01ENF Example Program Data

4                                      :Value of N

 507.0     622.0     300.0     -202.0
 237.0     352.0     126.0      -60.0
 751.0     950.0     440.0     -286.0
-286.0    -326.0    -192.0      150.0  :End of matrix A


f01epfe.d

F01EPF Example Program Data

4                             :Value of N

6.0     4.0    -5.0     15.0
8.0     6.0    -3.0     10.0
0.0     0.0     3.0     -4.0
0.0     0.0     4.0      3.0  :End of matrix A


f01eqfe.d

F01EQF Example Program Data

4     0.2              : Values of N and P

3.0   3.0   2.0   1.0
3.0   1.0   0.0   2.0
1.0   1.0   4.0   3.0
3.0   0.0   3.0   1.0  : End of matrix A


f01fcfe.d

F01FCF Example Program Data

  4                                           :Value of N

  (1.0,1.0)  (2.0,1.0)  (2.0,1.0)  (2.0,1.0)
  (3.0,2.0)  (1.0,0.0)  (1.0,0.0)  (2.0,1.0)
  (3.0,2.0)  (2.0,1.0)  (1.0,0.0)  (2.0,1.0)
  (3.0,2.0)  (3.0,2.0)  (3.0,2.0)  (1.0,1.0)  :End of matrix A


f01fdfe.d

F01FDF Example Program Data

   4                                              :Value of N
  'U'                                             :Value of UPLO

  (1.0, 0.0)  (2.0, 1.0)  (3.0, 2.0)  (4.0, 3.0)
              (1.0, 0.0)  (2.0, 1.0)  (3.0, 2.0)
                          (1.0, 0.0)  (2.0, 1.0)
                                      (1.0, 0.0)  :End of matrix A


f01fffe.d

F01FFF Example Program Data

   4                                              :Value of N
  'U'                                             :Value of UPLO

  (1.0, 0.0)  (2.0, 1.0)  (3.0, 2.0)  (4.0, 3.0)
              (1.0, 0.0)  (2.0, 1.0)  (3.0, 2.0)
                          (1.0, 0.0)  (2.0, 1.0)
                                      (1.0, 0.0)  :End of matrix A


f01fjfe.d

F01FJF Example Program Data

   4                                            :Value of N

  (1.0, 2.0) ( 0.0, 1.0) (1.0, 0.0) (3.0, 2.0)
  (0.0, 3.0) (-2.0, 0.0) (0.0, 0.0) (1.0, 0.0)
  (1.0, 0.0) (-2.0, 0.0) (3.0, 2.0) (0.0, 3.0)
  (2.0, 0.0) ( 0.0, 1.0) (0.0, 1.0) (2.0, 3.0)  :End of matrix A


f01fkfe.d

F01FKF Example Program Data

   4         SINH                                :Values of N and FUN

  (1.0, 1.0) ( 0.0, 0.0) ( 1.0, 3.0) (0.0, 0.0)
  (0.0, 0.0) ( 2.0, 0.0) ( 0.0, 0.0) (1.0, 2.0)
  (3.0, 1.0) ( 0.0, 4.0) ( 1.0, 1.0) (0.0, 0.0)
  (1.0, 1.0) ( 0.0, 2.0) ( 0.0, 0.0) (1.0, 0.0)  :End of matrix A


f01flfe.d

F01FLF Example Program Data

   4                                               :Value of N

 ( 1.0, 0.0)  (0.0, 1.0)  ( 1.0, 0.0)  (0.0, 1.0)
 (-1.0, 0.0)  (0.0, 0.0)  ( 2.0, 1.0)  (0.0, 0.0)
 ( 0.0, 0.0)  (2.0, 1.0)  ( 0.0, 2.0)  (0.0, 1.0)
 ( 1.0, 0.0)  (1.0, 1.0)  (-1.0, 0.0)  (2.0, 1.0)  :End of matrix A


f01fmfe.d

F01FMF Example Program Data

  4                                               :Value of N

( 1.0, 0.0)  (0.0, 0.0)  ( 1.0, 0.0)  (0.0, 2.0)
( 0.0, 1.0)  (1.0, 0.0)  (-1.0, 0.0)  (1.0, 0.0)
(-1.0, 0.0)  (0.0, 1.0)  ( 0.0, 1.0)  (0.0, 1.0)
( 1.0, 1.0)  (0.0, 2.0)  (-1.0, 0.0)  (0.0, 1.0)  :End of matrix A


f01fnfe.d

F01FNF Example Program Data

4                                                          :Value of N

(105.0, 121.0) ( -21.0, 157.0) ( 42.0, 18.0) ( -4.0, -2.0)
(174.0,  72.0) (  28.0, 236.0) ( 51.0, 31.0) ( 16.0, -6.0)
(176.0,  52.0) (  37.0, 177.0) ( 23.0, 27.0) ( 25.0, 13.0)
( -9.0, 125.0) (-111.0,  67.0) ( -8.0, 30.0) (  0.0,  8.0) :End of matrix A


f01fpfe.d

F01FPF Example Program Data

4                                                     :Value of N

( 0.0,  2.0) ( 14.0,  2.0) ( 12.0,  3.0) ( 6.0, 4.0)
(-5.0, 12.0) (  6.0, 18.0) (  9.0, 16.0)
( 3.0, -4.0) ( 16.0, -4.0)
( 4.0,  0.0)                                          :End of matrix A


f01fqfe.d

F01FQF Example Program Data

4     0.2                                      : Values of N and P

(2.0,0.0)   (3.0,0.0)   (2.0,0.0)   (1.0,3.0)
(2.0,1.0)   (1.0,0.0)   (1.0,0.0)   (2.0,2.0)
(2.0,1.0)   (2.0,2.0)   (0.0,2.0)   (2.0,4.0)
(3.0,0.0)   (2.0,2.0)   (3.0,0.0)   (1.0,0.0)  : End of matrix A


f01gafe.d

F01GAF Example Program Data

4    2    1.2            :Values of N, M and T

0.7   -0.2    1.0    0.3
0.3    0.7    1.2    1.0
0.9    0.0    0.2    0.7
2.4    0.1    0.0    0.2 :End of matrix A

0.1    1.2
1.3    0.2
0.0    1.0
0.4   -0.9               :End of matrix B


f01gbfe.d

F01GBF Example Program Data

4   2  -0.2                :Values of N, M, and T

0.4   -0.2    1.3    0.6
0.3    0.8    1.0    1.0
3.0    4.8    0.2    0.7
0.5    0.0   -5.0    0.7   :End of matrix A

0.1    1.1
1.7   -0.2
0.5    1.0
0.4   -0.2                 :End of matrix B


f01hafe.d

F01HAF Example Program Data

4    2    (-0.5,0.0)                              :Values of N, M and T

(0.5,0.0)    (-0.2,0.0)    (1.0,0.1)    (0.0,0.4)
(0.3,0.0)    ( 0.5,1.2)    (3.1,0.0)    (1.0,0.2)
(0.0,2.0)    ( 0.1,0.0)    (1.2,0.2)    (0.5,0.0)
(1.0,0.3)    ( 0.0,0.2)    (0.0,0.9)    (0.5,0.0) :End of matrix A

(0.4,0.0)    ( 1.2,0.0)
(1.3,0.0)    (-0.2,0.1)
(0.0,0.3)    ( 2.1,0.0)
(0.4,0.0)    (-0.9,0.0)                           :End of matrix B


f01jafe.d

F01JAF Example Program Data

4       SINH              :Value of N and FUN

2.0    1.0    3.0    1.0
3.0   -1.0    0.0    2.0
1.0    0.0    3.0    1.0
1.0    2.0    0.0    3.0  :End of matrix A


f01jbfe.d

F01JBF Example Program Data

 4                         :Value of N

-1.0   -1.0   -2.0    1.0
 0.0    1.0   -1.0    0.0
-1.0   -2.0    1.0   -1.0
 0.0   -1.0    0.0   -1.0  :End of matrix A


f01jcfe.d

F01JCF Example Program Data

 4                         :Value of N

 0.0   -1.0   -1.0    1.0
-2.0    0.0    1.0   -1.0
 2.0   -1.0    2.0   -2.0
-1.0   -2.0    0.0   -1.0  :End of matrix A


f01jdfe.d

F01JDF Example Program Data

4                              :Value of N

-5.0     2.0     -1.0     1.0
-2.0    -3.0     19.0    27.0
-9.0     0.0     15.0    24.0
 7.0     8.0     11.0    16.0  :End of matrix A


f01jefe.d

F01JEF Example Program Data

4     0.2              : Values of N and P

3.0   3.0   2.0   1.0
1.0   1.0   0.0   2.0
1.0   4.0   4.0   2.0
3.0   1.0   3.0   1.0  : End of matrix A


f01jffe.d

F01JFF Example Program Data

4     0.2              :Values of N and P

3.0   3.0   2.0   1.0
3.0   1.0   0.0   2.0
1.0   1.0   4.0   3.0
3.0   0.0   3.0   1.0  :End of matrix A

1.0   0.0   2.0   1.0
0.0   4.0   5.0   2.0
1.0   0.0   0.0   0.0
2.0   3.0   3.0   0.0  :End of matrix E


f01jgfe.d

F01JGF Example Program Data

  4                      : N

  2.0   2.0   1.0   2.0
  3.0   1.0   4.0   0.0
  2.0   3.0   1.0   2.0
  0.0   1.0   3.0   3.0  : A


f01jhfe.d

F01JHF Example Program Data

  4                      :Value of N

  1.0   2.0   2.0   2.0
  3.0   1.0   1.0   2.0
  3.0   2.0   1.0   2.0
  3.0   3.0   3.0   1.0  :End of matrix A

  1.0   0.0   1.0   2.0
  0.0   0.0   0.0   1.0
  4.0   2.0   1.0   2.0
  0.0   3.0   2.0   1.0  :End of matrix E


f01jjfe.d

F01JJF Example Program Data

4                            :Value of N

4.0    -1.0     0.0     1.0
2.0     5.0    -2.0     2.0
1.0     1.0     3.0    -1.0
2.0     0.0     2.0     8.0  :End of matrix A


f01jkfe.d

F01JKF Example Program Data

  4                      :Value N

  4.0   2.0   0.0   2.0
  3.0   3.0   1.0   1.0
  3.0   2.0   1.0   0.0
  3.0   3.0   1.0   2.0  :End of matrix A

  1.0   2.0   2.0   2.0
  0.0   0.0   3.0   1.0
  1.0   2.0   1.0   2.0
  1.0   3.0   1.0   1.0  :End of matrix E


f01kafe.d

F01KAF Example Program Data

4             SINH                                       :Values of N and FUN

(0.0, 1.0)    (-1.0, 0.0)    ( 1.0, 0.0)    (2.0, 0.0)
(2.0, 1.0)    ( 0.0,-1.0)    ( 0.0, 0.0)    (1.0, 0.0)
(0.0, 1.0)    ( 0.0, 0.0)    ( 1.0, 1.0)    (0.0, 2.0)
(1.0, 0.0)    ( 2.0, 0.0)    (-2.0, 3.0)    (0.0, 1.0)   :End of matrix A


f01kbfe.d

F01KBF Example Program Data

4                                                      :Value of N

(2.0, 0.0)    (0.0, 1.0)    (1.0, 1.0)    (0.0, 3.0)
(1.0, 1.0)    (0.0, 2.0)    (2.0, 2.0)    (0.0, 0.0)
(0.0, 0.0)    (2.0, 0.0)    (1.0, 2.0)    (1.0, 0.0)
(1.0, 1.0)    (3.0, 0.0)    (0.0, 0.0)    (1.0, 2.0)   :End of matrix A


f01kcfe.d

F01KCF Example Program Data

4                                                     :Value of N

(1.0, 1.0)    (0.0, 1.0)    (1.0, 0.0)    (2.0, 0.0)
(0.0, 0.0)    (2.0, 0.0)    (0.0, 2.0)    (1.0, 0.0)
(0.0, 1.0)    (0.0, 1.0)    (0.0, 0.0)    (2.0, 0.0)
(1.0, 0.0)    (0.0, 1.0)    (1.0, 0.0)    (0.0, 1.0)  :End of matrix A


f01kdfe.d

F01KDF Example Program Data

4                                                       :Value of N

( 29.0, 35.0) ( 31.0, 61.0) (-38.0, 49.0) (-17.0, -6.0)
( 52.0,-59.0) ( 58.0,-29.0) ( 97.0, 39.0) (-32.0, 15.0)
( 20.0,-31.0) ( 44.0, -1.0) ( 37.0, 19.0) (-26.0, 19.0)
(-70.0, 72.0) (-90.0,  8.0) (-87.0,-43.0) ( 47.0, -5.0) :End of matrix A


f01kefe.d

F01KEF Example Program Data

4     0.4                                      : Values of N and P

(1.0,2.0)   (3.0,0.0)   (2.0,0.0)   (1.0,3.0)
(1.0,1.0)   (1.0,0.0)   (1.0,0.0)   (2.0,1.0)
(1.0,0.0)   (2.0,0.0)   (1.0,0.0)   (0.0,2.0)
(3.0,0.0)   (0.0,1.0)   (2.0,1.0)   (1.0,0.0)  : End of matrix A


f01kgfe.d

F01KGF Example Program Data

  4                                           :Value of N

  (1.0,1.0)  (2.0,1.0)  (2.0,1.0)  (2.0,1.0)
  (3.0,2.0)  (1.0,0.0)  (1.0,0.0)  (2.0,1.0)
  (3.0,2.0)  (2.0,1.0)  (1.0,0.0)  (2.0,1.0)
  (3.0,2.0)  (3.0,2.0)  (3.0,2.0)  (1.0,1.0)  :End of matrix A


f01kjfe.d

F01KJF Example Program Data

   4                                            :Value of N

  (3.0, 2.0) ( 1.0, 0.0) (1.0, 0.0) (1.0, 2.0)
  (0.0, 2.0) (-4.0, 0.0) (0.0, 0.0) (0.0, 0.0)
  (1.0, 0.0) (-2.0, 0.0) (3.0, 2.0) (0.0, 1.0)
  (1.0, 0.0) ( 0.0, 1.0) (1.0, 0.0) (2.0, 3.0)  :End of matrix A


f01lefe.d

F01LEF Example Program Data
   5                              : n
  3.0   2.3  -5.0  -0.9   7.1     : a
  2.1  -1.0   1.9   8.0           : b
  3.4   3.6   7.0  -6.0           : c
  2.7  -0.5   2.6   0.6   2.7     : y


f01lhfe.d

F01LHF Example Program Data
  5        : nbloks
  2  4  3  : Number of rows, columns and column overlap, block 1
-1.00 -0.98 -0.79 -0.15
-1.00  0.25 -0.87  0.35                            : End block 1
  4  7  4  : Number of rows, columns and column overlap, block 2
 0.78  0.31 -0.85  0.89 -0.69 -0.98 -0.76
-0.82  0.12 -0.01  0.75  0.32 -1.00 -0.53
-0.83 -0.98 -0.58  0.04  0.87  0.38 -1.00
-0.21 -0.93 -0.84  0.37 -0.94 -0.96 -1.00          : End block 2
  5  8  2  : Number of rows, columns and column overlap, block 3
-0.99 -0.91 -0.28  0.90  0.78 -0.93 -0.76  0.48
-0.87 -0.14 -1.00 -0.59 -0.99  0.21 -0.73 -0.48
-0.93 -0.91  0.10 -0.89 -0.68 -0.09 -0.58 -0.21
 0.85 -0.39  0.79 -0.71  0.39 -0.99 -0.12 -0.75
 0.17 -1.37  1.29 -1.59  1.10 -1.63 -1.01 -0.27    : End block 3
  3  6  3  : Number of rows, columns and column overlap, block 4
 0.08  0.61  0.54 -0.41  0.16 -0.46
-0.67  0.56 -0.99  0.16 -0.16  0.98
-0.24 -0.41  0.40 -0.93  0.70  0.43                : End block 4
  4  5  0  : Number of rows, columns and column overlap, block 5
 0.71 -0.97 -0.60 -0.30  0.18
-0.47 -0.98 -0.73  0.07  0.04
-0.25 -0.92 -0.52 -0.46 -0.58
 0.89 -0.94 -0.54 -1.00 -0.36                      : End block 5
  1        : Number of right hand sides
-2.92 -1.27 -1.30 -1.17 -2.10 -4.51 -1.71 -4.59
-4.19 -0.93 -3.31  0.52 -0.12 -0.05 -0.98 -2.07
-2.73 -1.95                              : End right hand side 1


f01mcfe.d

F01MCF Example Program Data
  6                                  : n
  1  2  2  1  5  3                   : nrow
   1.0
   2.0   5.0
   3.0  13.0
  16.0
   5.0  14.0  18.0   8.0  55.0
  24.0  17.0  77.0                   : a


f01qgfe.d

F01QGF Example Program Data
  3     5                       : m, n
  2.4   0.8  -1.4   3.0  -0.8
   0    1.6   0.8   0.4  -0.8
   0     0    1.0   2.0   2.0   : a


f01qjfe.d

F01QJF Example Program Data
  3     5                       : m, n
  2.0   2.0   1.6   2.0   1.2
  2.5   2.5  -0.4  -0.5  -0.3
  2.5   2.5   2.8   0.5  -2.9   : a


f01qkfe.d

F01QKF Example Program Data
  3     5                       : m, n
  2.0   2.0   1.6   2.0   1.2
  2.5   2.5  -0.4  -0.5  -0.3
  2.5   2.5   2.8   0.5  -2.9   : a


f01rgfe.d

F01RGF Example Program Data
  3     4                                             : m, n
( 2.4, 0.0 ) ( 0.8, 0.8 ) (-1.4, 0.6 ) ( 3.0,-1.0 )
(  0 ,  0  ) ( 1.6, 0.0 ) ( 0.8, 0.3 ) ( 0.4, 0.5 )
(  0 ,  0  ) (  0 ,  0  ) ( 1.0, 0.0 ) ( 2.0,-1.0 )   : a


f01vafe.d

F01VAF Example Program Data
 4 'U'                            : n, uplo
 1.1  1.2  1.3  1.4               : Unpacked Matrix A
 0.0  2.2  2.3  2.4
 0.0  0.0  3.3  3.4
 0.0  0.0  0.0  4.4


f01vbfe.d

F01VBF Example Program Data
 4 'U'                                         : n, uplo
 (1.1,1.1)  (1.2,1.2)  (1.3,1.3)  (1.4,1.4)    : Unpacked Matrix A
 (0.0,0.0)  (2.2,2.2)  (2.3,2.3)  (2.4,2.4)
 (0.0,0.0)  (0.0,0.0)  (3.3,3.3)  (3.4,3.4)
 (0.0,0.0)  (0.0,0.0)  (0.0,0.0)  (4.4,4.4)


f01vcfe.d

F01VCF Example Program Data
4 'U'                             : n, uplo
 1.1                              : Packed Matrix AP
 1.2
 2.2
 1.3
 2.3
 3.3
 1.4
 2.4
 3.4
 4.4


f01vdfe.d

F01VDF Example Program Data
 4 'U'                            : n, uplo
 (1.1,1.1)                        : Packed Matrix AP
 (1.2,1.2)
 (2.2,2.2)
 (1.3,1.3)
 (2.3,2.3)
 (3.3,3.3)
 (1.4,1.4)
 (2.4,2.4)
 (3.4,3.4)
 (4.4,4.4)


f01vefe.d

F01VEF Example Program Data
 4    'U'  'N'                    : n, uplo, transr
 1.1  1.2  1.3  1.4
      2.2  2.3  2.4
           3.3  3.4
                4.4               : Upper matrix A


f01vffe.d

F01VFF Example Program Data
  4          'U'        'N'                    : n, uplo, transr
 (1.1,1.1)  (1.2,1.2)  (1.3,1.3)  (1.4,1.4)
            (2.2,2.2)  (2.3,2.3)  (2.4,2.4)
                       (3.3,3.3)  (3.4,3.4)
                                  (4.4,4.4)    : Upper Matrix A


f01vgfe.d

F01VGF Example Program Data
 4      'U'     'N'  : n, uplo, transr
 1.30   1.40
 2.30   2.40
 3.30   3.40
 1.10   4.40
 1.20   2.20         : RFP Matrix AR


f01vhfe.d

F01VHF Example Program Data
   4     'U'     'N'             : n, uplo, transr
 ( 1.30, 1.30)   ( 1.40, 1.40)
 ( 2.30, 2.30)   ( 2.40, 2.40)
 ( 3.30, 3.30)   ( 3.40, 3.40)
 ( 1.10,-1.10)   ( 4.40, 4.40)
 ( 1.20,-1.20)   ( 2.20,-2.20)   : RFP Matrix AR


f01vjfe.d

F01VJF Example Program Data
4 'U' 'N'                        : n, uplo, transr
 1.1
 1.2
 2.2
 1.3
 2.3
 3.3
 1.4
 2.4
 3.4
 4.4                             : Packed Matrix AP


f01vkfe.d

F01VKF Example Program Data
 4 'U' 'N'                       : n, uplo, transr
 (1.1,1.1)
 (1.2,1.2)
 (2.2,2.2)
 (1.3,1.3)
 (2.3,2.3)
 (3.3,3.3)
 (1.4,1.4)
 (2.4,2.4)
 (3.4,3.4)
 (4.4,4.4)                       : Packed Matrix AP


f01vlfe.d

F01VLF Example Program Data
 4      'U'     'N'  : n, uplo, transr
 1.30   1.40
 2.30   2.40
 3.30   3.40
 1.10   4.40
 1.20   2.20         : RFP Matrix AR


f01vmfe.d

F01VMF Example Program Data
   4     'U'     'N'            : n, uplo, 'N'
 ( 1.30, 1.30)   ( 1.40, 1.40)
 ( 2.30, 2.30)   ( 2.40, 2.40)
 ( 3.30, 3.30)   ( 3.40, 3.40)
 ( 1.10,-1.10)   ( 4.40, 4.40)
 ( 1.20,-1.20)   ( 2.20,-2.20)  : RFP array AR


f01zafe.d

F01ZAF Example Program Data
 4 'U' 'N'                        : n, uplo, diag
 1.1  1.2  1.3  1.4               : Unpacked Matrix A
 0.0  2.2  2.3  2.4
 0.0  0.0  3.3  3.4
 0.0  0.0  0.0  4.4


f01zbfe.d

F01ZBF Example Program Data
 4 'U' 'N'                                     : n, uplo, diag
 (1.1,1.1)  (1.2,1.2)  (1.3,1.3)  (1.4,1.4)    : Unpacked Matrix A
 (0.0,0.0)  (2.2,2.2)  (2.3,2.3)  (2.4,2.4)
 (0.0,0.0)  (0.0,0.0)  (3.3,3.3)  (3.4,3.4)
 (0.0,0.0)  (0.0,0.0)  (0.0,0.0)  (4.4,4.4)


f01zcfe.d

F01ZCF Example Program Data
 5  5  1  1                      : m, n, kl, ku
 1.1  1.2  0.0  0.0  0.0         : Unpacked Matrix A
 2.1  2.2  2.3  0.0  0.0
 0.0  3.2  3.3  3.4  0.0
 0.0  0.0  4.3  4.4  4.5
 0.0  0.0  0.0  5.4  5.5


f02ecfe.d

F02ECF Example Program Data
  4  3  0.2  0.5              : n, mest wl, wu
  0.35   0.45  -0.14  -0.17
  0.09   0.07  -0.54   0.35
 -0.44  -0.33  -0.03   0.17
  0.25  -0.32  -0.13   0.11   : matrix A


f02ekfe.d

F02EKF Example Program Data
 10      : nx, matrix order n = nx*nx
 4       : nev, number of eigenvalues requested
 20      : ncv, size of subspace
 10.0    : rho, parameter for determining A
 5.5     : sigma, shift (want eigenvalues close to sigma)
 0       : print level
 500     : maximum number of itrerations
 1       : mode (0 = regular, 1 = shifted inverse)
 1       : imon (0 = no monitoring, 1 = monitoring on)


f02fjfe.d

F02FJF Example Program Data
 16 4 6 0.0001         : n, m, k, tol


f02fkfe.d

F02FKF Example Program Data
 20      : nx, matrix order n = nx*nx
 8       : nev, number of eigenvalues requested
 20      : ncv, size of subspace
 1.0     : sigma, shift (want eigenvalues close to sigma)
 0       : print level
 500     : maximum number of itrerations
 1       : mode (0 = regular, 1 = shifted inverse)
 0       : imon (0 = no monitoring, 1 = monitoring on)


f02jcfe.d

F02JCF Example Program Data

 3              : n

 1.0  2.0  2.0
 3.0  1.0  1.0
 3.0  2.0  1.0  : A

 3.0  2.0  1.0
 2.0  1.0  3.0
 1.0  3.0  2.0  : B

 1.0  1.0  2.0
 2.0  3.0  1.0
 3.0  1.0  2.0  : C


f02sdfe.d

F02SDF Example Program Data
  5  2  1                      : n, ma, mb
  1.0  1.0  2.0
 -1.0  2.0  1.0  2.0
  0.0 -1.0  3.0  1.0  2.0
  0.0 -1.0  4.0  1.0
  0.0 -1.0  5.0                : matrix A
  5.0  1.0
  1.0  4.0  2.0
  2.0  3.0  2.0
  2.0  2.0  1.0
  1.0  1.0                     : matrix B
      -12.33 1.0               : rmu, d(1)


f02wdfe.d

F02WDF Example Program Data
  6  4                          : m, n
  22.25  31.75 -38.25  65.50
  20.00  26.75  28.50 -26.50
 -15.25  24.25  27.75  18.50
  27.25  10.00   3.00   2.00
 -17.25 -30.75  11.25   7.50
  17.25  30.75 -11.25  -7.50    : matrix A


f02wgfe.d

F02WGF Example Program Data
 100 500 4 10         : m, n, k, ncv


f02wufe.d

F02WUF Example Program Data
   3, 1              : n, ncolb
  -4.0  -2.0  -3.0
        -3.0  -2.0
              -4.0   : matrix A
  -1.0  -1.0  -1.0   : vector B


f02xufe.d

F02XUF Example Program Data

   3     1                                     : n, ncolb

  (1.0,  0.0)   ( 1.0,  1.0)   ( 1.0,  1.0)
                (-2.0,  0.0)   (-1.0, -1.0)
                               (-3.0,  0.0)    : matrix A

  (1.0,  1.0)   (-1.0,  0.0)   (-1.0,  1.0)    : vector B


f03bafe.d

F03BAF Example Program Data
  3                   : N
   33   16   72
  -24  -10  -57
   -8   -4  -17       : A


f03bffe.d

F03BFF Example Program Data
  4                     : N
    6    7    6    5
    7   11    8    7
    6    8   11    9
    5    7    9   11    : A


f03bhfe.d

F03BHF Example Program Data
  L                                  : UPLO
  7  2                               : N, KD
    5
   -4     6
    1    -4    6
          1   -4    6
               1   -4    6
                    1   -4    6
                         1   -4    5 : AB


f03bnfe.d

F03BNF Example Program Data
  3
 (1.0, 0.0)   (1.0, 2.0)   (2.0,10.0)
 (1.0, 1.0)   (0.0, 3.0)  (-5.0,14.0)
 (1.0, 1.0)   (0.0, 5.0)  (-8.0,20.0)


f04abfe.d

F04ABF Example Program Data
    4    1             : n, m
    5    7    6    5
    7   10    8    7
    6    8   10    9
    5    7    9   10
   23   32   33   31   : matrices A and B


f04aefe.d

F04AEF Example Program Data
  3                    : n
   33   16   72
  -24  -10  -57
   -8   -4  -17
 -359  281   85        : matrices A and B


f04amfe.d

F04AMF Example Program Data
  3  2                 : m, n
  1.1  0.9    2.2
  1.2  1.0    2.3
  1.0  1.0    2.1      : matrices A and B


f04asfe.d

F04ASF Example Program Data
  4                     : n
    5    7    6    5
    7   10    8    7
    6    8   10    9
    5    7    9   10
   23   32   33   31    : matrices A and B


f04atfe.d

F04ATF Example Program Data
  3               : n
   33   16   72
  -24  -10  -57
   -8   -4  -17
 -359  281   85   : matrices A and B


f04axfe.d

F04AXF Example Program Data
  6 15                                                          : n, nz
   5.0  1  1   2.0  2  2  -1.0  2  3   2.0  2  4   3.0  3  3
  -2.0  4  1   1.0  4  4   1.0  4  5  -1.0  5  1  -1.0  5  4
   2.0  5  5  -3.0  5  6  -1.0  6  1  -1.0  6  2   6.0  6  6    : a
  15.0  12.0  18.0   3.0  -6.0   0.0                            : rhs


f04bafe.d

F04BAF Example Program Data

  4      2                  : n, nrhs

  1.80   2.88   2.05  -0.89
  5.25  -2.95  -0.95  -3.80
  1.58  -2.69  -2.90  -1.04
 -1.11  -0.66  -0.59   0.80 : matrix A

  9.52  18.47
 24.35   2.25
  0.77 -13.28
 -6.22  -6.21               : matrix B


f04bbfe.d

F04BBF Example Program Data

  4      1      2      2    : n, kl, ku, nrhs

 -0.23   2.54  -3.66
 -6.98   2.46  -2.73  -2.13
         2.56   2.46   4.07
               -4.78  -3.82 : matrix A

  4.42 -36.01
 27.13 -31.67
 -6.14  -1.16
 10.50 -25.82               : matrix B


f04bcfe.d

F04BCF Example Program Data

  5     2                      : n, nrhs

        2.1  -1.0   1.9   8.0  : superdiagonal du
  3.0   2.3  -5.0  -0.9   7.1  : diagonal d
  3.4   3.6   7.0  -6.0        : subdiagonal dl

  2.7   6.6
 -0.5  10.8
  2.6  -3.2
  0.6 -11.2
  2.7  19.1                    : matrix B


f04bdfe.d

F04BDF Example Program Data

   4      2                  :Values of N and NRHS

   4.16  -3.12   0.56  -0.10
          5.03  -0.83   1.18
                 0.76   0.34
                        1.18 :End of matrix A

   8.70   8.30
 -13.35   2.13
   1.89   1.61
  -4.14   5.00               :End of matrix B


f04befe.d

F04BEF Example Program Data

   4      2                  : n, nrhs

   4.16  -3.12   0.56  -0.10
          5.03  -0.83   1.18
                 0.76   0.34
                        1.18 : matrix A

   8.70   8.30
 -13.35   2.13
   1.89   1.61
  -4.14   5.00               : matrix B


f04bffe.d

F04BFF Example Program Data

  4      1      2           : n, kd, nrhs

  5.49   2.68
         5.63  -2.39
                2.60  -2.22
                       5.17 : matrix A

 22.09   5.10
  9.31  30.81
 -5.24 -25.82
 11.83  22.90               : matrix B


f04bgfe.d

F04BGF Example Program Data

  5     2                     :Values of N and NRHS

  4.0  10.0  29.0  25.0   5.0 :End of diagonal D
 -2.0  -6.0  15.0   8.0       :End of sub-diagonal E

  6.0  10.0
  9.0   4.0
  2.0   9.0
 14.0  65.0
  7.0  23.0                   :End of matrix B


f04bhfe.d

F04BHF Example Program Data

  4      2                  : n, nrhs

 -1.81   2.06   0.63  -1.15
         1.15   1.87   4.20
               -0.21   3.87
                       2.07 : matrix A

  0.96   3.93
  6.07  19.25
  8.38   9.90
  9.50  27.85               : matrix B


f04bjfe.d

F04BJF Example Program Data

  4      2                  :Values of N and NRHS

 -1.81   2.06   0.63  -1.15
         1.15   1.87   4.20
               -0.21   3.87
                       2.07 :End of matrix A

  0.96   3.93
  6.07  19.25
  8.38   9.90
  9.50  27.85               :End of matrix B


f04cffe.d

F04CFF Example Program Data

    4              1              2                              : n, kd, nrhs

 (  9.39,  0.00) (  1.08, -1.73)
                 (  1.69,  0.00) ( -0.04,  0.29)
                                 (  2.65,  0.00) ( -0.33,  2.24)
                                                 (  2.17,  0.00) : matrix A

 (-12.42, 68.42) ( 54.30,-56.56)
 ( -9.93,  0.88) ( 18.32,  4.76)
 (-27.30, -0.01) ( -4.40,  9.97)
 (  5.31, 23.63) (  9.43,  1.41)                                 : matrix B


f04cgfe.d

F04CGF Example Program Data

    4             2                               : n, nrhs

   16.0          41.0          46.0          21.0 : diagonal d
 ( 16.0, 16.0) ( 18.0, -9.0) (  1.0, -4.0)        : sub-diagonal e

 ( 64.0, 16.0) (-16.0,-32.0)
 ( 93.0, 62.0) ( 61.0,-66.0)
 ( 78.0,-80.0) ( 71.0,-74.0)
 ( 14.0,-27.0) ( 35.0, 15.0)                      : matrix B


f04fefe.d

F04FEF Example Program Data

   4                           : n
   4.0  3.0  2.0  1.0  0.0     : vector T


f04fffe.d

F04FFF Example Program Data

   4                   : n
   4.0  3.0  2.0  1.0  : vector T
   1.0  1.0  1.0  1.0  : vector B


f04jgfe.d

F04JGF Example Program Data
  6  4                                : m, n
  0.05  0.05  0.25 -0.25
  0.25  0.25  0.05 -0.05
  0.35  0.35  1.75 -1.75
  1.75  1.75  0.35 -0.35
  0.30 -0.30  0.30  0.30
  0.40 -0.40  0.40  0.40              : matrix A
  1.0   2.0   3.0   4.0   5.0   6.0   : vector B


f04lefe.d

F04LEF Example Program Data
   5                             : n
  3.0   2.3  -5.0  -0.9   7.1    : vector A
  2.1  -1.0   1.9   8.0          : vector B
  3.4   3.6   7.0  -6.0          : vector C
  2.7  -0.5   2.6   0.6   2.7    : vector Y


f04lhfe.d

F04LHF Example Program Data
  5        : Number of blocks
  2  4  3  : Number of rows, columns and column overlap, block 1
-1.00 -0.98 -0.79 -0.15
-1.00  0.25 -0.87  0.35                            : End block 1
  4  7  4  : Number of rows, columns and column overlap, block 2
 0.78  0.31 -0.85  0.89 -0.69 -0.98 -0.76
-0.82  0.12 -0.01  0.75  0.32 -1.00 -0.53
-0.83 -0.98 -0.58  0.04  0.87  0.38 -1.00
-0.21 -0.93 -0.84  0.37 -0.94 -0.96 -1.00          : End block 2
  5  8  2  : Number of rows, columns and column overlap, block 3
-0.99 -0.91 -0.28  0.90  0.78 -0.93 -0.76  0.48
-0.87 -0.14 -1.00 -0.59 -0.99  0.21 -0.73 -0.48
-0.93 -0.91  0.10 -0.89 -0.68 -0.09 -0.58 -0.21
 0.85 -0.39  0.79 -0.71  0.39 -0.99 -0.12 -0.75
 0.17 -1.37  1.29 -1.59  1.10 -1.63 -1.01 -0.27    : End block 3
  3  6  3  : Number of rows, columns and column overlap, block 4
 0.08  0.61  0.54 -0.41  0.16 -0.46
-0.67  0.56 -0.99  0.16 -0.16  0.98
-0.24 -0.41  0.40 -0.93  0.70  0.43                : End block 4
  4  5  0  : Number of rows, columns and column overlap, block 5
 0.71 -0.97 -0.60 -0.30  0.18
-0.47 -0.98 -0.73  0.07  0.04
-0.25 -0.92 -0.52 -0.46 -0.58
 0.89 -0.94 -0.54 -1.00 -0.36                      : End block 5
  1        : Number of right hand sides
-2.92 -1.27 -1.30 -1.17 -2.10 -4.51 -1.71 -4.59
-4.19 -0.93 -3.31  0.52 -0.12 -0.05 -0.98 -2.07
-2.73 -1.95                              : End right hand side 1


f04mcfe.d

F04MCF Example Program Data
  6  2                          : n, ir
  1  2  2  1  5  3              : vector NROW
   1.0
   2.0   5.0
   3.0  13.0
  16.0
   5.0  14.0  18.0   8.0  55.0
  24.0  17.0  77.0              : vector A
   6.0 -10.0
  15.0 -21.0
  11.0  -3.0
   0.0  24.0
  51.0 -39.0
  46.0  67.0                    : matrix B


f04mefe.d

F04MEF Example Program Data

   4                           : n
   4.0  3.0  2.0  1.0  0.0     : vector T


f04mffe.d

F04MFF Example Program Data

   4                     : n
   4.0  3.0  2.0  1.0    : vector T
   1.0  1.0  1.0  1.0    : vector B


f04qafe.d

F04QAF Example Program Data
   4   4                 : nrows, ncols


f04yafe.d

F04YAF Example Program Data
   5   3                        : n, p
 0.60  1.20  3.90
 5.00  4.00  2.50
 1.00 -4.00 -5.50
-1.00 -2.00 -6.50
-4.20 -8.40 -4.80               : matrix A
 3.0   4.0  -1.0  -5.0  -1.0    : vector Y


f04ydfe.d

F04YDF Example Program Data

Example 1

6      6      2                              :Values of M, N and t

0.7   -0.2    1.0    0.0    2.0    0.1
0.3    0.7    0.0    1.0    0.9    0.2
0.0    0.0    0.2    0.7    0.0   -1.1
0.0    3.4   -0.7    0.2    0.1    0.1
0.0   -4.0    0.0    1.0    9.0    0.0
0.4    1.2    4.3    0.0    6.2    5.9       :End of matrix A

Example 2

5      10     2                              :Values of N, NZ and t

3.0  2  1
2.0  4  1
1.0  2  2
2.0  3  2
1.0  5  2
4.0  4  3
2.0  5  3
1.0  1  4
2.0  3  4
5.0  4  5                                    :End of matrix A


f05aafe.d

F05AAF Example Program Data
 4   2    4
 1  -2    3    1
-2   1   -2   -1
 3  -2    1    5
 4   1    5    3


f06wafe.d

F06WAF Example Program Data
  6  'L' 'N'                    : N, UPLO, TRANSR
  1.0
  2.0  2.0
  3.0  3.0  3.0
  4.0  4.0  4.0  4.0
  5.0  5.0  5.0  5.0  5.0
  6.0  6.0  6.0  6.0  6.0  6.0  : Matrix A


f06wbfe.d

F06WBF Example Program Data
  6 4 'L' 'N' 'L' 4.21 'N'      : M, N, UPLO, TRANSR, SIDE, ALPHA, TRANS
  1.0
  2.0  2.0
  3.0  3.0  3.0
  4.0  4.0  4.0  4.0
  5.0  5.0  5.0  5.0  5.0
  6.0  6.0  6.0  6.0  6.0  6.0  : Matrix A
  3.22   1.37   2.31   0.29
  1.64   1.80   0.38  -1.52
  1.87   2.87   2.02  -0.80
  5.20  -2.99  -0.91  -3.87
  1.83  -2.71  -2.81  -1.13
 -1.10  -0.63  -0.50   0.81     : End of matrix B


f06wcfe.d

F06WCF Example Program Data
  6 4 'L' 'N' 4.21 0.89 'N'     : N, K, UPLO, TRANSR, ALPHA, BETA, TRANS
  1.0
  2.0  2.0
  3.0  3.0  3.0
  4.0  4.0  4.0  4.0
  5.0  5.0  5.0  5.0  5.0
  6.0  6.0  6.0  6.0  6.0  6.0  : End of matrix C
  3.21   1.32   2.31   0.25
  1.65   1.87   0.32  -1.54
  1.80   2.88   2.05  -0.89
  5.25  -2.95  -0.95  -3.80
  1.58  -2.69  -2.90  -1.04
 -1.11  -0.66  -0.59   0.80     : End of matrix A


f06wnfe.d

F06WNF Example Program Data
  6  'L' 'N'							    : N, UPLO, TRANSR
  (1.0,1.1)
  (2.0,2.1)  (2.0,2.1)
  (3.0,3.3)  (3.3,3.0)  (3.2,3.0)
  (4.0,4.4)  (4.0,4.3)  (4.0,4.2)  (4.0,4.1)
  (5.0,5.1)  (5.0,5.2)  (5.3,5.0)  (5.0,5.4)  (5.5,5.0)
  (6.9,6.0)  (6.0,6.8)  (6.7,6.0)  (6.0,6.6)  (6.5,6.0)  (6.0,6.4)  : Matrix A


f06wpfe.d

F06WPF Example Program Data
 4 3 'U' 'N' 'L' (4.21,1.28) 'N'         : M, N, UPLO,TRANSR,SIDE, ALPHA, TRANS
 (1.1,1.1) (1.2,1.2) (1.3,1.3) (1.4,1.4)
 (2.2,2.2) (2.3,2.3) (2.4,2.4)
 (3.3,3.3) (3.4,3.4)
 (4.4,4.4)                               : Unpacked Matrix A
 ( 1.80,0.59) ( 2.88, 1.23) (2.05, 0.78)
 ( 5.25,0.12) ( 1.76,-2.95) (2.20,-0.95)
 ( 1.58,2.01) (-2.69, 3.18) (0.11,-2.90)
 (-1.11,1.11) (-0.66, 1.66) (1.59,-0.59) : End of matrix B


f06wqfe.d

F06WQF Example Program Data
 4 3 'L' 'N' 2.21 2.89 'N'                 : N,K, UPLO,TRANSR, ALPHA,BETA, TRANS
 (1.0,3.0)
 (2.0,2.0) (3.0,3.0)
 (4.0,4.0) (4.0,4.0) (5.0,5.0)
 (5.0,5.0) (5.0,6.0) (6.0,6.0) (6.0,6.0)   : Unpacked matrix C
 ( 3.21, 1.32) ( 2.31, 0.25) ( 1.65, 1.87)
 ( 0.32,-1.55) ( 1.80, 1.88) ( 2.05,-0.89)
 ( 5.25,-2.95) (-1.95,-3.80) ( 1.58,-2.69)
 (-2.90,-3.04) (-1.11,-0.66) (-0.59, 0.80) : End of matrix A


f07aafe.d

F07AAF Example Program Data

  4                           :Value of N

  1.80   2.88   2.05  -0.89
  5.25  -2.95  -0.95  -3.80
  1.58  -2.69  -2.90  -1.04
 -1.11  -0.66  -0.59   0.80   :End of matrix A

  9.52  24.35   0.77  -6.22   :End of vector b


f07abfe.d

F07ABF Example Program Data

    4        2                     :Values of N and NRHS

    1.80     2.88    2.05    -0.89
  525.00  -295.00  -95.00  -380.00
    1.58    -2.69   -2.90    -1.04
   -1.11    -0.66   -0.59     0.80 :End of matrix A

    9.52    18.47
 2435.00   225.00
    0.77   -13.28
   -6.22    -6.21                  :End of matrix B


f07acfe.d

F07ACF Example Program Data

  4     1                     :Value of N, R

  1.80   2.88   2.05  -0.89
  5.25  -2.95  -0.95  -3.80
  1.58  -2.69  -2.90  -1.04
 -1.11  -0.66  -0.59   0.80   :End of matrix A

  9.52  24.35   0.77  -6.22   :End of vector b


f07adfe.d

F07ADF Example Program Data
  4  4                        :Values of M and N
  1.80   2.88   2.05  -0.89
  5.25  -2.95  -0.95  -3.80
  1.58  -2.69  -2.90  -1.04
 -1.11  -0.66  -0.59   0.80   :End of matrix A


f07aefe.d

F07AEF Example Program Data
  4  2                        :Values of N and NRHS
  1.80   2.88   2.05  -0.89
  5.25  -2.95  -0.95  -3.80
  1.58  -2.69  -2.90  -1.04
 -1.11  -0.66  -0.59   0.80   :End of matrix A
  9.52  18.47
 24.35   2.25
  0.77 -13.28
 -6.22  -6.21                 :End of matrix B


f07affe.d

F07AFF Example Program Data

  4                                         :Value of N

  1.80D+10   2.88D+10   2.05D+00  -8.90D+09
  5.25D+00  -2.95D+00  -9.50D-09  -3.80D+00
  1.58D+00  -2.69D+00  -2.90D-10  -1.04D+00
 -1.11D+00  -6.60D-01  -5.90D-11   8.00D-01 :End of matrix A


f07agfe.d

F07AGF Example Program Data
  4                           :Value of N
  1.80   2.88   2.05  -0.89
  5.25  -2.95  -0.95  -3.80
  1.58  -2.69  -2.90  -1.04
 -1.11  -0.66  -0.59   0.80   :End of matrix A


f07ahfe.d

F07AHF Example Program Data
  4  2                        :Values of N and NRHS
  1.80   2.88   2.05  -0.89
  5.25  -2.95  -0.95  -3.80
  1.58  -2.69  -2.90  -1.04
 -1.11  -0.66  -0.59   0.80   :End of matrix A
  9.52  18.47
 24.35   2.25
  0.77 -13.28
 -6.22  -6.21                 :End of matrix B


f07ajfe.d

F07AJF Example Program Data
  4                           :Value of N
  1.80   2.88   2.05  -0.89
  5.25  -2.95  -0.95  -3.80
  1.58  -2.69  -2.90  -1.04
 -1.11  -0.66  -0.59   0.80   :End of matrix A


f07arfe.d

F07ARF Example Program Data
  4  4                                                    :Values of M and N
 (-1.34, 2.55) ( 0.28, 3.17) (-6.39,-2.20) ( 0.72,-0.92)
 (-0.17,-1.41) ( 3.31,-0.15) (-0.15, 1.34) ( 1.29, 1.38)
 (-3.29,-2.39) (-1.91, 4.42) (-0.14,-1.35) ( 1.72, 1.35)
 ( 2.41, 0.39) (-0.56, 1.47) (-0.83,-0.69) (-1.96, 0.67)  :End of matrix A


f07atfe.d

F07ATF Example Program Data

  3                                                             :Value of N

 (-1.34D+00, 2.55D+00) ( 0.28D+10, 3.17D+10) (-6.39D+00,-2.20D+00)
 (-1.70D+00,-1.41D+00) ( 3.31D+10,-0.15D+10) (-0.15D+00, 1.34D+00)
 ( 2.41D-10, 0.39D-10) (-0.56D+00, 1.47D+00) (-0.83D-10,-0.69D-10)

                                                                :End of matrix A


f07aufe.d

F07AUF Example Program Data
  4                                                       :Value of N
 (-1.34, 2.55) ( 0.28, 3.17) (-6.39,-2.20) ( 0.72,-0.92)
 (-0.17,-1.41) ( 3.31,-0.15) (-0.15, 1.34) ( 1.29, 1.38)
 (-3.29,-2.39) (-1.91, 4.42) (-0.14,-1.35) ( 1.72, 1.35)
 ( 2.41, 0.39) (-0.56, 1.47) (-0.83,-0.69) (-1.96, 0.67)  :End of matrix A


f07awfe.d

F07AWF Example Program Data
  4                                                       :Value of N
 (-1.34, 2.55) ( 0.28, 3.17) (-6.39,-2.20) ( 0.72,-0.92)
 (-0.17,-1.41) ( 3.31,-0.15) (-0.15, 1.34) ( 1.29, 1.38)
 (-3.29,-2.39) (-1.91, 4.42) (-0.14,-1.35) ( 1.72, 1.35)
 ( 2.41, 0.39) (-0.56, 1.47) (-0.83,-0.69) (-1.96, 0.67)  :End of matrix A


f07bafe.d

F07BAF Example Program Data

  4  1  2                     :Values of N, KL and KU

 -0.23   2.54  -3.66
 -6.98   2.46  -2.73  -2.13
         2.56   2.46   4.07
               -4.78  -3.82   :End of matrix A

  4.42  27.13  -6.14  10.50   :End of vector B


f07bbfe.d

F07BBF Example Program Data
  4  2  1  2                  :Values of N, NRHS, KL and KU
 -0.23   2.54  -3.66
 -6.98   2.46  -2.73  -2.13
         2.56   2.46   4.07
               -4.78  -3.82   :End of matrix A
  4.42 -36.01
 27.13 -31.67
 -6.14  -1.16
 10.50 -25.82                 :End of matrix B


f07bdfe.d

F07BDF Example Program Data
  4  4  1  2                  :Values of M, N, KL and KU
 -0.23   2.54  -3.66
 -6.98   2.46  -2.73  -2.13
         2.56   2.46   4.07
               -4.78  -3.82   :End of matrix A


f07befe.d

F07BEF Example Program Data
  4  2  1  2                  :Values of N, NRHS, KL and KU
 -0.23   2.54  -3.66
 -6.98   2.46  -2.73  -2.13
         2.56   2.46   4.07
               -4.78  -3.82   :End of matrix A
  4.42 -36.01
 27.13 -31.67
 -6.14  -1.16
 10.50 -25.82                 :End of matrix B


f07bffe.d

F07BFF Example Program Data
  4  1  2                                     :Values of N, KL and KU
 -2.30D-01   2.54D+00  -3.66D-10
 -6.98D+10   2.46D+10  -2.73D+00  -2.13D+10
             2.56D+00   2.46D-10   4.07D+00
                       -4.78D-10  -3.82D+00   :End of matrix A


f07bgfe.d

F07BGF Example Program Data
  4  1  2                     :Values of N, KL and KU
 -0.23   2.54  -3.66
 -6.98   2.46  -2.73  -2.13
         2.56   2.46   4.07
               -4.78  -3.82   :End of matrix A


f07bhfe.d

F07BHF Example Program Data
  4  2  1  2                  :Values of N, NRHS, KL and KU
 -0.23   2.54  -3.66
 -6.98   2.46  -2.73  -2.13
         2.56   2.46   4.07
               -4.78  -3.82   :End of matrix A
  4.42 -36.01
 27.13 -31.67
 -6.14  -1.16
 10.50 -25.82                 :End of matrix B


f07bnfe.d

F07BNF Example Program Data
  4  1  2                                                :Values of N, KL and KU
 (-1.65,  2.26) ( -2.05, -0.85) (  0.97, -2.84)
 ( 0.00,  6.30) ( -1.48, -1.75) ( -3.99,  4.01) (  0.59, -0.48)
                ( -0.77,  2.83) ( -1.06,  1.94) (  3.33, -1.04)
                                (  4.48, -1.09) ( -0.46, -1.72) :End of matrix A
 (-1.06, 21.50) (-22.72,-53.90) ( 28.24,-38.60) (-34.56, 16.73) :End of vector B


f07brfe.d

F07BRF Example Program Data
  4  4  1  2                                          :Values of M, N, KL and KU
 (-1.65, 2.26) (-2.05,-0.85) ( 0.97,-2.84)
 ( 0.00, 6.30) (-1.48,-1.75) (-3.99, 4.01) ( 0.59,-0.48)
               (-0.77, 2.83) (-1.06, 1.94) ( 3.33,-1.04)
                             ( 4.48,-1.09) (-0.46,-1.72)  :End of matrix A


f07btfe.d

F07BTF Example Program Data
  4  1  2                                                :Values of N, KL and KU
 (-1.65, 2.26) (-2.05D-10,-8.50D-11) ( 9.70D-01,-2.84D+00)
 ( 0.00, 6.30) (-1.48D-10,-1.75D-10) (-2.99D+00, 3.01D+00) ( 0.59D+00,-0.48D+00)
               (-7.70D-01, 2.83D+00) (-1.06D+10, 1.94D+10) ( 3.33D+10,-1.04D+10)
                                     ( 4.48D+00,-1.09D+00) (-0.46D+00,-1.72D+00)
                                                                :End of matrix A


f07bufe.d

F07BUF Example Program Data
  4  1  2                                                :Values of N, KL and KU
 (-1.65, 2.26) (-2.05,-0.85) ( 0.97,-2.84)
 ( 0.00, 6.30) (-1.48,-1.75) (-3.99, 4.01) ( 0.59,-0.48)
               (-0.77, 2.83) (-1.06, 1.94) ( 3.33,-1.04)
                             ( 4.48,-1.09) (-0.46,-1.72)  :End of matrix A


f07cafe.d

F07CAF Example Program Data
  5                            :Value of N
        2.1  -1.0   1.9   8.0
  3.0   2.3  -5.0  -0.9   7.1
  3.4   3.6   7.0  -6.0        :End of matrix A
  2.7  -0.5   2.6   0.6   2.7  :End of vector B


f07cbfe.d

F07CBF Example Program Data
  5     2                      :Values of N and NRHS
        2.1  -1.0   1.9   8.0
  3.0   2.3  -5.0  -0.9   7.1
  3.4   3.6   7.0  -6.0        :End of matrix A
  2.7   6.6
 -0.5  10.8
  2.6  -3.2
  0.6 -11.2
  2.7  19.1                    :End of matrix B


f07cdfe.d

F07CDF Example Program Data
   5                           :Value of N
        2.1  -1.0   1.9   8.0
  3.0   2.3  -5.0  -0.9   7.1
  3.4   3.6   7.0  -6.0        :End of matrix A


f07cefe.d

F07CEF Example Program Data
  5     2                      :Values of N and NRHS
        2.1  -1.0   1.9   8.0
  3.0   2.3  -5.0  -0.9   7.1
  3.4   3.6   7.0  -6.0        :End of matrix A
  2.7   6.6
 -0.5  10.8
  2.6  -3.2
  0.6 -11.2
  2.7  19.1                    :End of matrix B


f07cgfe.d

F07CGF Example Program Data
   5                           :Value of N
        2.1  -1.0   1.9   8.0
  3.0   2.3  -5.0  -0.9   7.1
  3.4   3.6   7.0  -6.0        :End of matrix A


f07chfe.d

F07CHF Example Program Data
  5     2                      :Values of N and NRHS
        2.1  -1.0   1.9   8.0
  3.0   2.3  -5.0  -0.9   7.1
  3.4   3.6   7.0  -6.0        :End of matrix A
  2.7   6.6
 -0.5  10.8
  2.6  -3.2
  0.6 -11.2
  2.7  19.1                    :End of matrix B


f07cnfe.d

F07CNF Example Program Data
   5                                                     :Value of N
 (  2.0, -1.0) (  2.0,  1.0) ( -1.0,  1.0) (  1.0, -1.0) :End of DU
 ( -1.3,  1.3) ( -1.3,  1.3) ( -1.3,  3.3) ( -0.3,  4.3)
 ( -3.3,  1.3)                                           :End of D
 (  1.0, -2.0) (  1.0 , 1.0) (  2.0, -3.0) (  1.0,  1.0) :End of  DL
 (  2.4, -5.0) (  3.4, 18.2) (-14.7,  9.7) ( 31.9, -7.7)
 ( -1.0,  1.6)                                           :End of B


f07cpfe.d

F07CPF Example Program Data
   5    2                                                :Values of N and NRHS
 (  2.0, -1.0) (  2.0,  1.0) ( -1.0,  1.0) (  1.0, -1.0) :End of DU
 ( -1.3,  1.3) ( -1.3,  1.3) ( -1.3,  3.3) ( -0.3,  4.3)
 ( -3.3,  1.3)                                           :End of D
 (  1.0, -2.0) (  1.0 , 1.0) (  2.0, -3.0) (  1.0,  1.0) :End of  DL
 (  2.4, -5.0) (  2.7,  6.9)
 (  3.4, 18.2) ( -6.9, -5.3)
 (-14.7,  9.7) ( -6.0, -0.6)
 ( 31.9, -7.7) ( -3.9,  9.3)
 ( -1.0,  1.6) ( -3.0, 12.2)                             :End of B


f07crfe.d

F07CRF Example Program Data
   5                                             :Value of N
 ( 2.0,-1.0) ( 2.0, 1.0) (-1.0, 1.0) ( 1.0,-1.0) :End of DU
 (-1.3, 1.3) (-1.3, 1.3) (-1.3, 3.3) (-0.3, 4.3)
 (-3.3, 1.3)                                     :End of D
 ( 1.0,-2.0) ( 1.0, 1.0) ( 2.0,-3.0) ( 1.0, 1.0) :End of DL


f07csfe.d

F07CSF Example Program Data
   5    2                                                :Values of N and NRHS
 (  2.0, -1.0) (  2.0,  1.0) ( -1.0,  1.0) (  1.0, -1.0) :End of DU
 ( -1.3,  1.3) ( -1.3,  1.3) ( -1.3,  3.3) ( -0.3,  4.3)
 ( -3.3,  1.3)                                           :End of D
 (  1.0, -2.0) (  1.0 , 1.0) (  2.0, -3.0) (  1.0,  1.0) :End of  DL
 (  2.4, -5.0) (  2.7,  6.9)
 (  3.4, 18.2) ( -6.9, -5.3)
 (-14.7,  9.7) ( -6.0, -0.6)
 ( 31.9, -7.7) ( -3.9,  9.3)
 ( -1.0,  1.6) ( -3.0, 12.2)                             :End of B


f07cufe.d

F07CUF Example Program Data
   5                                             :Value of N
 ( 2.0,-1.0) ( 2.0, 1.0) (-1.0, 1.0) ( 1.0,-1.0) :End of DU
 (-1.3, 1.3) (-1.3, 1.3) (-1.3, 3.3) (-0.3, 4.3)
 (-3.3, 1.3)                                     :End of D
 ( 1.0,-2.0) ( 1.0, 1.0) ( 2.0,-3.0) ( 1.0, 1.0) :End of DL


f07cvfe.d

F07CVF Example Program Data
   5    2                                                :Values of N and NRHS
 (  2.0, -1.0) (  2.0,  1.0) ( -1.0,  1.0) (  1.0, -1.0) :End of DU
 ( -1.3,  1.3) ( -1.3,  1.3) ( -1.3,  3.3) ( -0.3,  4.3)
 ( -3.3,  1.3)                                           :End of D
 (  1.0, -2.0) (  1.0 , 1.0) (  2.0, -3.0) (  1.0,  1.0) :End of  DL
 (  2.4, -5.0) (  2.7,  6.9)
 (  3.4, 18.2) ( -6.9, -5.3)
 (-14.7,  9.7) ( -6.0, -0.6)
 ( 31.9, -7.7) ( -3.9,  9.3)
 ( -1.0,  1.6) ( -3.0, 12.2)                             :End of B


f07fafe.d

F07FAF Example Program Data
  4                         :Value of N
  4.16  -3.12   0.56  -0.10
         5.03  -0.83   1.18
                0.76   0.34
                       1.18 :End of matrix A
  8.70 -13.35   1.89  -4.14 :End of vector b


f07fbfe.d

F07FBF Example Program Data
  4      2                   :Values of N and NRHS
  4.16  -3.12   0.56  -0.10
         5.03  -0.83   1.18
                0.76   0.34
                       1.18 :End of matrix A
   8.70  8.30
 -13.35  2.13
   1.89  1.61
  -4.14  5.00               :End of matrix B


f07fcfe.d

F07FCF Example Program Data
  4     1                     :Value of N, R
  4.16  -3.12   0.56  -0.10
         5.03  -0.83   1.18
                0.76   0.34
                       1.18 :End of matrix A
  8.70 -13.35   1.89  -4.14 :End of vector b


f07fdfe.d

F07FDF Example Program Data
  4                           :Value of N
  'L'                         :Value of UPLO
  4.16
 -3.12   5.03
  0.56  -0.83   0.76
 -0.10   1.18   0.34   1.18   :End of matrix A


f07fefe.d

F07FEF Example Program Data
  4  2                        :Values of N and NRHS
  'L'                         :Value of UPLO
  4.16
 -3.12   5.03
  0.56  -0.83   0.76
 -0.10   1.18   0.34   1.18   :End of matrix A
  8.70   8.30
-13.35   2.13
  1.89   1.61
 -4.14   5.00                 :End of matrix B


f07fffe.d

F07FFF Example Program Data
  4                                         :Value of N
  4.16D+00  -3.12D+05   0.56D+00  -0.10D+00
             5.03D+10  -0.83D+05   1.18D+05
                        0.76D+00   0.34D+00
                                   1.18D+00 :End of matrix A


f07fgfe.d

F07FGF Example Program Data
  4                           :Value of N
  'L'                         :Value of UPLO
  4.16
 -3.12   5.03
  0.56  -0.83   0.76
 -0.10   1.18   0.34   1.18   :End of matrix A


f07fhfe.d

F07FHF Example Program Data
  4  2                        :Values of N and NRHS
  'L'                         :Value of UPLO
  4.16
 -3.12   5.03
  0.56  -0.83   0.76
 -0.10   1.18   0.34   1.18   :End of matrix A
  8.70   8.30
-13.35   2.13
  1.89   1.61
 -4.14   5.00                 :End of matrix B


f07fjfe.d

F07FJF Example Program Data
  4                           :Value of N
  'L'                         :Value of UPLO
  4.16
 -3.12   5.03
  0.56  -0.83   0.76
 -0.10   1.18   0.34   1.18   :End of matrix A


f07fnfe.d

F07FNF Example Program Data
   4                                                         :Value of N
 ( 3.23,  0.00) ( 1.51, -1.92) ( 1.90,  0.84) ( 0.42,  2.50)
                ( 3.58,  0.00) (-0.23,  1.11) (-1.18,  1.37)
                               ( 4.09,  0.00) ( 2.33, -0.14)
                                              ( 4.29,  0.00) :End of matrix A
 ( 3.93, -6.14) ( 6.17,  9.42) (-7.17,-21.83) ( 1.99,-14.38) :End of vector b


f07fpfe.d

F07FPF Example Program Data
   4      2                                             :Values of N and NRHS
 ( 3.23,  0.00) ( 1.51, -1.92) ( 1.90,  0.84) ( 0.42,  2.50)
                ( 3.58,  0.00) (-0.23,  1.11) (-1.18,  1.37)
                               ( 4.09,  0.00) ( 2.33, -0.14)
                                              ( 4.29,  0.00) :End of matrix A
 ( 3.93, -6.14) ( 1.48,  6.58)
 ( 6.17,  9.42) ( 4.65, -4.75)
 (-7.17,-21.83) (-4.91,  2.29)
 ( 1.99,-14.38) ( 7.64,-10.79)                               :End of matrix B


f07fqfe.d

F07FQF Example Program Data
   4           1                                             :Values of N, R
 ( 3.23,  0.00) ( 1.51, -1.92) ( 1.90,  0.84) ( 0.42,  2.50)
                ( 3.58,  0.00) (-0.23,  1.11) (-1.18,  1.37)
                               ( 4.09,  0.00) ( 2.33, -0.14)
                                              ( 4.29,  0.00) :End of matrix A
 ( 3.93, -6.14) ( 6.17,  9.42) (-7.17,-21.83) ( 1.99,-14.38) :End of vector b


f07frfe.d

F07FRF Example Program Data
  4                                                      :Value of N
  'L'                                                    :Value of UPLO
 (3.23, 0.00)
 (1.51, 1.92) ( 3.58, 0.00)
 (1.90,-0.84) (-0.23,-1.11) ( 4.09, 0.00)
 (0.42,-2.50) (-1.18,-1.37) ( 2.33, 0.14) ( 4.29, 0.00)  :End of matrix A


f07fsfe.d

F07FSF Example Program Data
  4  2                                                   :Values of N and NRHS
  'L'                                                    :Value of UPLO
 (3.23, 0.00)
 (1.51, 1.92) ( 3.58, 0.00)
 (1.90,-0.84) (-0.23,-1.11) ( 4.09, 0.00)
 (0.42,-2.50) (-1.18,-1.37) ( 2.33, 0.14) ( 4.29, 0.00)  :End of matrix A
 ( 3.93, -6.14) ( 1.48,  6.58)
 ( 6.17,  9.42) ( 4.65, -4.75)
 (-7.17,-21.83) (-4.91,  2.29)
 ( 1.99,-14.38) ( 7.64,-10.79)                           :End of matrix B


f07ftfe.d

F07FTF Example Program Data
   4                                                            :Value of N
 ( 3.23, 0.00) ( 1.51,-1.92) ( 1.90D+05, 0.84D+05) ( 0.42D+00, 2.50D+00)
               ( 3.58, 0.00) (-0.23D+05, 1.11D+05) (-1.18D+00, 1.37D+00)
                             ( 4.09D+10, 0.00D+00) ( 2.33D+05,-0.14D+05)
                                                   ( 4.29D+00, 0.00D+00)
                                                                :End of matrix A


f07fufe.d

F07FUF Example Program Data
  4                                                      :Value of N
  'L'                                                    :Value of UPLO
 (3.23, 0.00)
 (1.51, 1.92) ( 3.58, 0.00)
 (1.90,-0.84) (-0.23,-1.11) ( 4.09, 0.00)
 (0.42,-2.50) (-1.18,-1.37) ( 2.33, 0.14) ( 4.29, 0.00)  :End of matrix A


f07fvfe.d

F07FVF Example Program Data
  4  2                                                   :Values of N and NRHS
  'L'                                                    :Value of UPLO
 (3.23, 0.00)
 (1.51, 1.92) ( 3.58, 0.00)
 (1.90,-0.84) (-0.23,-1.11) ( 4.09, 0.00)
 (0.42,-2.50) (-1.18,-1.37) ( 2.33, 0.14) ( 4.29, 0.00)  :End of matrix A
 ( 3.93, -6.14) ( 1.48,  6.58)
 ( 6.17,  9.42) ( 4.65, -4.75)
 (-7.17,-21.83) (-4.91,  2.29)
 ( 1.99,-14.38) ( 7.64,-10.79)                           :End of matrix B


f07fwfe.d

F07FWF Example Program Data
  4                                                      :Value of N
  'L'                                                    :Value of UPLO
 (3.23, 0.00)
 (1.51, 1.92) ( 3.58, 0.00)
 (1.90,-0.84) (-0.23,-1.11) ( 4.09, 0.00)
 (0.42,-2.50) (-1.18,-1.37) ( 2.33, 0.14) ( 4.29, 0.00)  :End of matrix A


f07gafe.d

F07GAF Example Program Data
  4                         :Value of N
  4.16  -3.12   0.56  -0.10
         5.03  -0.83   1.18
                0.76   0.34
                       1.18 :End of matrix A
  8.70 -13.35   1.89  -4.14 :End of vector b


f07gbfe.d

F07GBF Example Program Data
  4      2                   :Values of N and NRHS
  4.16  -3.12   0.56  -0.10
         5.03  -0.83   1.18
                0.76   0.34
                       1.18 :End of matrix A
   8.70  8.30
 -13.35  2.13
   1.89  1.61
  -4.14  5.00               :End of matrix B


f07gdfe.d

F07GDF Example Program Data
  4                           :Value of N
  'L'                         :Value of UPLO
  4.16
 -3.12   5.03
  0.56  -0.83   0.76
 -0.10   1.18   0.34   1.18   :End of matrix A


f07gefe.d

F07GEF Example Program Data
  4  2                        :Values of N and NRHS
  'L'                         :Value of UPLO
  4.16
 -3.12   5.03
  0.56  -0.83   0.76
 -0.10   1.18   0.34   1.18   :End of matrix A
  8.70   8.30
-13.35   2.13
  1.89   1.61
 -4.14   5.00                 :End of matrix B


f07gffe.d

F07GFF Example Program Data
  4                                         :Value of N
  4.16D+00  -3.12D+05   0.56D+00  -0.10D+00
             5.03D+10  -0.83D+05   1.18D+05
                        0.76D+00   0.34D+00
                                   1.18D+00 :End of matrix A


f07ggfe.d

F07GGF Example Program Data
  4                           :Value of N
  'L'                         :Value of UPLO
  4.16
 -3.12   5.03
  0.56  -0.83   0.76
 -0.10   1.18   0.34   1.18   :End of matrix A


f07ghfe.d

F07GHF Example Program Data
  4  2                        :Values of N and NRHS
  'L'                         :Value of UPLO
  4.16
 -3.12   5.03
  0.56  -0.83   0.76
 -0.10   1.18   0.34   1.18   :End of matrix A
  8.70   8.30
-13.35   2.13
  1.89   1.61
 -4.14   5.00                 :End of matrix B


f07gjfe.d

F07GJF Example Program Data
  4                           :Value of N
  'L'                         :Value of UPLO
  4.16
 -3.12   5.03
  0.56  -0.83   0.76
 -0.10   1.18   0.34   1.18   :End of matrix A


f07gnfe.d

F07GNF Example Program Data
   4                                                         :Value of N
 ( 3.23,  0.00) ( 1.51, -1.92) ( 1.90,  0.84) ( 0.42,  2.50)
                ( 3.58,  0.00) (-0.23,  1.11) (-1.18,  1.37)
                               ( 4.09,  0.00) ( 2.33, -0.14)
                                              ( 4.29,  0.00) :End of matrix A
 ( 3.93, -6.14) ( 6.17,  9.42) (-7.17,-21.83) ( 1.99,-14.38) :End of vector b


f07gpfe.d

F07GPF Example Program Data
   4      2                                             :Values of N and NRHS
 ( 3.23,  0.00) ( 1.51, -1.92) ( 1.90,  0.84) ( 0.42,  2.50)
                ( 3.58,  0.00) (-0.23,  1.11) (-1.18,  1.37)
                               ( 4.09,  0.00) ( 2.33, -0.14)
                                              ( 4.29,  0.00) :End of matrix A
 ( 3.93, -6.14) ( 1.48,  6.58)
 ( 6.17,  9.42) ( 4.65, -4.75)
 (-7.17,-21.83) (-4.91,  2.29)
 ( 1.99,-14.38) ( 7.64,-10.79)                               :End of matrix B


f07grfe.d

F07GRF Example Program Data
  4                                                      :Value of N
  'L'                                                    :Value of UPLO
 (3.23, 0.00)
 (1.51, 1.92) ( 3.58, 0.00)
 (1.90,-0.84) (-0.23,-1.11) ( 4.09, 0.00)
 (0.42,-2.50) (-1.18,-1.37) ( 2.33, 0.14) ( 4.29, 0.00)  :End of matrix A


f07gsfe.d

F07GSF Example Program Data
  4  2                                                   :Values of N and NRHS
  'L'                                                    :Value of UPLO
 (3.23, 0.00)
 (1.51, 1.92) ( 3.58, 0.00)
 (1.90,-0.84) (-0.23,-1.11) ( 4.09, 0.00)
 (0.42,-2.50) (-1.18,-1.37) ( 2.33, 0.14) ( 4.29, 0.00)  :End of matrix A
 ( 3.93, -6.14) ( 1.48,  6.58)
 ( 6.17,  9.42) ( 4.65, -4.75)
 (-7.17,-21.83) (-4.91,  2.29)
 ( 1.99,-14.38) ( 7.64,-10.79)                           :End of matrix B


f07gtfe.d

F07GTF Example Program Data
   4                                                            :Value of N
 ( 3.23, 0.00) ( 1.51,-1.92) ( 1.90D+05, 0.84D+05) ( 0.42D+00, 2.50D+00)
               ( 3.58, 0.00) (-0.23D+05, 1.11D+05) (-1.18D+00, 1.37D+00)
                             ( 4.09D+10, 0.00D+00) ( 2.33D+05,-0.14D+05)
                                                   ( 4.29D+00, 0.00D+00)
                                                                :End of matrix A


f07gufe.d

F07GUF Example Program Data
  4                                                      :Value of N
  'L'                                                    :Value of UPLO
 (3.23, 0.00)
 (1.51, 1.92) ( 3.58, 0.00)
 (1.90,-0.84) (-0.23,-1.11) ( 4.09, 0.00)
 (0.42,-2.50) (-1.18,-1.37) ( 2.33, 0.14) ( 4.29, 0.00)  :End of matrix A


f07gvfe.d

F07GVF Example Program Data
  4  2                                                   :Values of N and NRHS
  'L'                                                    :Value of UPLO
 (3.23, 0.00)
 (1.51, 1.92) ( 3.58, 0.00)
 (1.90,-0.84) (-0.23,-1.11) ( 4.09, 0.00)
 (0.42,-2.50) (-1.18,-1.37) ( 2.33, 0.14) ( 4.29, 0.00)  :End of matrix A
 ( 3.93, -6.14) ( 1.48,  6.58)
 ( 6.17,  9.42) ( 4.65, -4.75)
 (-7.17,-21.83) (-4.91,  2.29)
 ( 1.99,-14.38) ( 7.64,-10.79)                           :End of matrix B


f07gwfe.d

F07GWF Example Program Data
  4                                                      :Value of N
  'L'                                                    :Value of UPLO
 (3.23, 0.00)
 (1.51, 1.92) ( 3.58, 0.00)
 (1.90,-0.84) (-0.23,-1.11) ( 4.09, 0.00)
 (0.42,-2.50) (-1.18,-1.37) ( 2.33, 0.14) ( 4.29, 0.00)  :End of matrix A


f07hafe.d

F07HAF Example Program Data

  4      1                  :Values of N and KD

  5.49   2.68
         5.63  -2.39
                2.60  -2.22
                       5.17 :End of matrix A

 22.09   9.31  -5.24  11.83 :End of vector b


f07hbfe.d

F07HBF Example Program Data

  4      1      2           :Values of N, KD and NRHS

  5.49   2.68
         5.63  -2.39
                2.60  -2.22
                       5.17 :End of matrix A

 22.09   5.10
  9.31  30.81
 -5.24 -25.82
 11.83  22.90               :End of matrix B


f07hdfe.d

F07HDF Example Program Data
  4  1                        :Values of N and KD
  'L'                         :Value of UPLO
  5.49
  2.68   5.63
        -2.39   2.60
               -2.22   5.17   :End of matrix A


f07hefe.d

F07HEF Example Program Data
  4  1  2                     :Values of N, KD and NRHS
  'L'                         :Value of UPLO
  5.49
  2.68   5.63
        -2.39   2.60
               -2.22   5.17   :End of matrix A
 22.09   5.10
  9.31  30.81
 -5.24 -25.82
 11.83  22.90                 :End of matrix B


f07hffe.d

F07HFF Example Program Data
  4  1                                      :Values of N and KD
  5.49E+00   2.68E+10
             5.63E+20  -2.39E+10
                        2.60E+00  -2.22E+00
                                   5.17E+00 :End of matrix A


f07hgfe.d

F07HGF Example Program Data
  4  1                        :Values of N and KD
  'L'                         :Value of UPLO
  5.49
  2.68   5.63
        -2.39   2.60
               -2.22   5.17   :End of matrix A


f07hhfe.d

F07HHF Example Program Data
  4  1  2                     :Values of N, KD and NRHS
  'L'                         :Value of UPLO
  5.49
  2.68   5.63
        -2.39   2.60
               -2.22   5.17   :End of matrix A
 22.09   5.10
  9.31  30.81
 -5.24 -25.82
 11.83  22.90                 :End of matrix B


f07hnfe.d

F07HNF Example Program Data

    4              1                                         :Values of N and KD

 (  9.39, 0.00) (  1.08,-1.73)
                (  1.69, 0.00) ( -0.04, 0.29)
                               (  2.65, 0.00) ( -0.33, 2.24)
                                              (  2.17, 0.00) :End of matrix A

 (-12.42,68.42) ( -9.93, 0.88) (-27.30,-0.01) (  5.31,23.63) :End of vector b


f07hpfe.d

F07HPF Example Program Data

    4              1              2                 :Values of N, KD and NRHS

 (  9.39, 0.00) (  1.08,-1.73)
                (  1.69, 0.00) ( -0.04, 0.29)
                               (  2.65, 0.00) ( -0.33, 2.24)
                                              (  2.17, 0.00) :End of matrix A

 (-12.42,68.42) (54.30,-56.56)
 ( -9.93, 0.88) (18.32,  4.76)
 (-27.30,-0.01) (-4.40,  9.97)
 (  5.31,23.63) ( 9.43,  1.41)                               :End of matrix B


f07hrfe.d

F07HRF Example Program Data
  4  1                                                    :Values of N and KD
  'L'                                                     :Value of UPLO
 ( 9.39, 0.00)
 ( 1.08, 1.73) ( 1.69, 0.00)
               (-0.04,-0.29) ( 2.65, 0.00)
                             (-0.33,-2.24) ( 2.17, 0.00)  :End of matrix A


f07hsfe.d

F07HSF Example Program Data
  4  1  2                                             :Values of N, KD and NRHS
  'L'                                                     :Value of UPLO
 ( 9.39, 0.00)
 ( 1.08, 1.73) ( 1.69, 0.00)
               (-0.04,-0.29) ( 2.65, 0.00)
                             (-0.33,-2.24) ( 2.17, 0.00)  :End of matrix A
 (-12.42,68.42) (54.30,-56.56)
 ( -9.93, 0.88) (18.32,  4.76)
 (-27.30,-0.01) (-4.40,  9.97)
 (  5.31,23.63) ( 9.43,  1.41)                            :End of matrix B


f07htfe.d

F07HTF Example Program Data
  4  1                                                       :Values of N and KD
 (  9.39, 0.00) (  1.08,-1.73)
                (  1.69, 0.00) ( -0.04E+10, 0.29E+10)
                               (  2.64E+20, 0.00    ) ( -0.33E+10, 2.24E+10)
                                                      (  2.17,     0.00    )
                                                             :End of matrix A


f07hufe.d

F07HUF Example Program Data
  4  1                                                    :Values of N and KD
  'L'                                                     :Value of UPLO
 ( 9.39, 0.00)
 ( 1.08, 1.73) ( 1.69, 0.00)
               (-0.04,-0.29) ( 2.65, 0.00)
                             (-0.33,-2.24) ( 2.17, 0.00)  :End of matrix A


f07hvfe.d

F07HVF Example Program Data
  4  1  2                                              :Values of N, KD and NRHS
  'L'                                                     :Value of UPLO
 ( 9.39, 0.00)
 ( 1.08, 1.73) ( 1.69, 0.00)
               (-0.04,-0.29) ( 2.65, 0.00)
                             (-0.33,-2.24) ( 2.17, 0.00)  :End of matrix A
 (-12.42,68.42) (54.30,-56.56)
 ( -9.93, 0.88) (18.32,  4.76)
 (-27.30,-0.01) (-4.40,  9.97)
 (  5.31,23.63) ( 9.43,  1.41)                            :End of matrix B


f07jafe.d

F07JAF Example Program Data
  5                           :Value of N
  4.0  10.0  29.0  25.0   5.0 :End of diagonal D
 -2.0  -6.0  15.0   8.0       :End of sub-diagonal E
  6.0   9.0   2.0  14.0   7.0 :End of vector b


f07jbfe.d

F07JBF Example Program Data
  5     2                     :Values of N and NRHS
  4.0  10.0  29.0  25.0   5.0 :End of diagonal D
 -2.0  -6.0  15.0   8.0       :End of sub-diagonal E
  6.0  10.0
  9.0   4.0
  2.0   9.0
 14.0  65.0
  7.0  23.0                   :End of matrix B


f07jdfe.d

F07JDF Example Program Data
  5                           :Value of N
  4.0  10.0  29.0  25.0   5.0 :End of diagonal D
 -2.0  -6.0  15.0   8.0       :End of sub-diagonal E


f07jefe.d

F07JEF Example Program Data
  5     2                     :Values of N and NRHS
       -2.0  -6.0  15.0   8.0 :End of super-diagonal E
  4.0  10.0  29.0  25.0   5.0 :End of diagonal D
  6.0  10.0
  9.0   4.0
  2.0   9.0
 14.0  65.0
  7.0  23.0                   :End of matrix B


f07jgfe.d

F07JGF Example Program Data
  5                           :Value of N
  4.0  10.0  29.0  25.0   5.0 :End of diagonal D
 -2.0  -6.0  15.0   8.0       :End of sub-diagonal E


f07jhfe.d

F07JHF Example Program Data
  5     2                     :Values of N and NRHS
  4.0  10.0  29.0  25.0   5.0 :End of diagonal D
 -2.0  -6.0  15.0   8.0       :End of super-diagonal E
  6.0  10.0
  9.0   4.0
  2.0   9.0
 14.0  65.0
  7.0  23.0                   :End of matrix B


f07jnfe.d

F07JNF Example Program Data
    4                                                    :Value of N
   16.0          41.0          46.0          21.0        :End of diagonal D
 ( 16.0, 16.0) ( 18.0, -9.0) (  1.0, -4.0)               :End of sub-diagonal E
 ( 64.0, 16.0) ( 93.0, 62.0) ( 78.0,-80.0) ( 14.0,-27.0) :End of vector b


f07jpfe.d

F07JPF Example Program Data
    4             2                               :Values of N and NRHS
   16.0          41.0          46.0          21.0 :End of diagonal D
 ( 16.0, 16.0) ( 18.0, -9.0) (  1.0, -4.0)        :End of sub-diagonal E
 ( 64.0, 16.0) (-16.0,-32.0)
 ( 93.0, 62.0) ( 61.0,-66.0)
 ( 78.0,-80.0) ( 71.0,-74.0)
 ( 14.0,-27.0) ( 35.0, 15.0)                      :End of matrix B


f07jrfe.d

F07JRF Example Program Data
    4                                                    :Value of N
   16.0          41.0          46.0          21.0        :End of diagonal D
 ( 16.0, 16.0) ( 18.0, -9.0) (  1.0, -4.0)               :End of sub-diagonal E


f07jsfe.d

F07JSF Example Program Data
    4             2                                      :Values of N and NRHS
               ( 16.0,-16.0) ( 18.0,  9.0) (  1.0,  4.0) :End of superdiagonal E
   16.0          41.0          46.0          21.0        :End of diagonal D
 ( 64.0, 16.0) (-16.0,-32.0)
 ( 93.0, 62.0) ( 61.0,-66.0)
 ( 78.0,-80.0) ( 71.0,-74.0)
 ( 14.0,-27.0) ( 35.0, 15.0)                             :End of matrix B


f07jufe.d

F07JUF Example Program Data
    4                                                    :Value of N
   16.0          41.0          46.0          21.0        :End of diagonal D
 ( 16.0, 16.0) ( 18.0, -9.0) (  1.0, -4.0)               :End of sub-diagonal E


f07jvfe.d

F07JVF Example Program Data
    4             2                               :Values of N and NRHS
   16.0          41.0          46.0          21.0 :End of diagonal D
 ( 16.0, 16.0) ( 18.0, -9.0) (  1.0, -4.0)        :End of sub-diagonal E
 ( 64.0, 16.0) (-16.0,-32.0)
 ( 93.0, 62.0) ( 61.0,-66.0)
 ( 78.0,-80.0) ( 71.0,-74.0)
 ( 14.0,-27.0) ( 35.0, 15.0)                      :End of matrix B


f07kdfe.d

F07KDF Example Program Data
  5 'L'                               : n, uplo
  2.51
  4.04   8.22
  3.34   7.38   7.06
  1.34   2.68   2.24   0.96
  1.29   2.44   2.14   0.80   0.74    : End of matrix A


f07krfe.d

F07KRF Example Program Data
  5 'L'                                                               : n, uplo
(12.40, 0.00)
( 2.39, 0.00) ( 1.63, 0.00)
( 5.50, 0.05) ( 1.04, 0.10) ( 2.45, 0.00)
( 4.47, 0.00) ( 1.14, 0.00) ( 1.98,-0.03) ( 1.71, 0.00)
(11.89, 0.00) ( 1.81, 0.00) ( 5.28,-0.02) ( 4.14, 0.00) (11.63, 0.00) : End of A


f07mafe.d

F07MAF Example Program Data
  4                         :Value of N
 -1.81   2.06   0.63  -1.15
         1.15   1.87   4.20
               -0.21   3.87
                       2.07 :End of matrix A
  0.96   6.07   8.38   9.50 :End of vector b


f07mbfe.d

F07MBF Example Program Data
  4      2                  :Values of N and NRHS
 -1.81   2.06   0.63  -1.15
         1.15   1.87   4.20
               -0.21   3.87
                       2.07 :End of matrix A
  0.96   3.93
  6.07  19.25
  8.38   9.90
  9.50  27.85               :End of matrix B


f07mdfe.d

F07MDF Example Program Data
  4                           :Value of N
  'L'                         :Value of UPLO
  2.07
  3.87  -0.21
  4.20   1.87   1.15
 -1.15   0.63   2.06  -1.81   :End of matrix A


f07mefe.d

F07MEF Example Program Data
  4  2                        :Values of N and NRHS
  'L'                         :Value of UPLO
  2.07
  3.87  -0.21
  4.20   1.87   1.15
 -1.15   0.63   2.06  -1.81   :End of matrix A
 -9.50  27.85
 -8.38   9.90
 -6.07  19.25
 -0.96   3.93                 :End of matrix B


f07mgfe.d

F07MGF Example Program Data
  4                           :Value of N
  'L'                         :Value of UPLO
  2.07
  3.87  -0.21
  4.20   1.87   1.15
 -1.15   0.63   2.06  -1.81   :End of matrix A


f07mhfe.d

F07MHF Example Program Data
  4  2                        :Values of N and NRHS
  'L'                         :Value of UPLO
  2.07
  3.87  -0.21
  4.20   1.87   1.15
 -1.15   0.63   2.06  -1.81   :End of matrix A
 -9.50  27.85
 -8.38   9.90
 -6.07  19.25
 -0.96   3.93                 :End of matrix B


f07mjfe.d

F07MJF Example Program Data
  4                           :Value of N
  'L'                         :Value of UPLO
  2.07
  3.87  -0.21
  4.20   1.87   1.15
 -1.15   0.63   2.06  -1.81   :End of matrix A


f07mnfe.d

F07MNF Example Program Data
    4                                                            :Value of N
 ( -1.84,  0.00) (  0.11, -0.11) ( -1.78, -1.18) (  3.91, -1.50)
                 ( -4.63 , 0.00) ( -1.84,  0.03) (  2.21,  0.21)
                                 ( -8.87,  0.00) (  1.58, -0.90)
                                                 ( -1.36 , 0.00) :End matrix A
 (  2.98,-10.18) ( -9.58,  3.88) ( -0.77,-16.05) (  7.79,  5.48) :End vector b


f07mrfe.d

F07MRF Example Program Data
  4                                                       :Value of N
  'L'                                                     :Value of UPLO
 (-1.36, 0.00)
 ( 1.58,-0.90) (-8.87, 0.00)
 ( 2.21, 0.21) (-1.84, 0.03) (-4.63, 0.00)
 ( 3.91,-1.50) (-1.78,-1.18) ( 0.11,-0.11) (-1.84, 0.00)  :End of matrix A


f07msfe.d

F07MSF Example Program Data
  4  2                                                    :Values of N and NRHS
  'L'                                                     :Value of UPLO
 (-1.36, 0.00)
 ( 1.58,-0.90) (-8.87, 0.00)
 ( 2.21, 0.21) (-1.84, 0.03) (-4.63, 0.00)
 ( 3.91,-1.50) (-1.78,-1.18) ( 0.11,-0.11) (-1.84, 0.00)  :End of matrix A
 ( 7.79,  5.48) (-35.39, 18.01)
 (-0.77,-16.05) (  4.23,-70.02)
 (-9.58,  3.88) (-24.79, -8.40)
 ( 2.98,-10.18) ( 28.68,-39.89)                           :End of matrix B


f07mufe.d

F07MUF Example Program Data
  4                                                       :Value of N
  'L'                                                     :Value of UPLO
 (-1.36, 0.00)
 ( 1.58,-0.90) (-8.87, 0.00)
 ( 2.21, 0.21) (-1.84, 0.03) (-4.63, 0.00)
 ( 3.91,-1.50) (-1.78,-1.18) ( 0.11,-0.11) (-1.84, 0.00)  :End of matrix A


f07mvfe.d

F07MVF Example Program Data
  4  2                                                    :Values of N and NRHS
  'L'                                                     :Value of UPLO
 (-1.36, 0.00)
 ( 1.58,-0.90) (-8.87, 0.00)
 ( 2.21, 0.21) (-1.84, 0.03) (-4.63, 0.00)
 ( 3.91,-1.50) (-1.78,-1.18) ( 0.11,-0.11) (-1.84, 0.00)  :End of matrix A
 ( 7.79,  5.48) (-35.39, 18.01)
 (-0.77,-16.05) (  4.23,-70.02)
 (-9.58,  3.88) (-24.79, -8.40)
 ( 2.98,-10.18) ( 28.68,-39.89)                           :End of matrix B


f07mwfe.d

F07MWF Example Program Data
  4                                                       :Value of N
  'L'                                                     :Value of UPLO
 (-1.36, 0.00)
 ( 1.58,-0.90) (-8.87, 0.00)
 ( 2.21, 0.21) (-1.84, 0.03) (-4.63, 0.00)
 ( 3.91,-1.50) (-1.78,-1.18) ( 0.11,-0.11) (-1.84, 0.00)  :End of matrix A


f07nnfe.d

F07NNF Example Program Data
    4                                                            :Value of N
 ( -0.56,  0.12) ( -1.54, -2.86) (  5.32, -1.59) (  3.80,  0.92)
                 ( -2.83 ,-0.03) ( -3.52,  0.58) ( -7.86, -2.96)
                                 (  8.86,  1.81) (  5.14, -0.64)
                                                 ( -0.39 ,-0.71) :End matrix A
 ( -6.43, 19.24) ( -0.49, -1.47) (-48.18, 66.00) (-55.64, 41.22) :End vector b


f07nrfe.d

F07NRF Example Program Data
  4                                                       :Value of N
  'L'                                                     :Value of UPLO
 (-0.39,-0.71)
 ( 5.14,-0.64) ( 8.86, 1.81)
 (-7.86,-2.96) (-3.52, 0.58) (-2.83,-0.03)
 ( 3.80, 0.92) ( 5.32,-1.59) (-1.54,-2.86) (-0.56, 0.12)  :End of matrix A


f07nsfe.d

F07NSF Example Program Data
  4  2                                                    :Values of N and NRHS
  'L'                                                     :Value of UPLO
 (-0.39,-0.71)
 ( 5.14,-0.64) ( 8.86, 1.81)
 (-7.86,-2.96) (-3.52, 0.58) (-2.83,-0.03)
 ( 3.80, 0.92) ( 5.32,-1.59) (-1.54,-2.86) (-0.56, 0.12)  :End of matrix A
 (-55.64, 41.22) (-19.09,-35.97)
 (-48.18, 66.00) (-12.08,-27.02)
 ( -0.49, -1.47) (  6.95, 20.49)
 ( -6.43, 19.24) ( -4.59,-35.53)                          :End of matrix B


f07nufe.d

F07NUF Example Program Data
  4                                                       :Value of N
  'L'                                                     :Value of UPLO
 (-0.39,-0.71)
 ( 5.14,-0.64) ( 8.86, 1.81)
 (-7.86,-2.96) (-3.52, 0.58) (-2.83,-0.03)
 ( 3.80, 0.92) ( 5.32,-1.59) (-1.54,-2.86) (-0.56, 0.12)  :End of matrix A


f07nvfe.d

F07NVF Example Program Data
  4  2                                                    :Values of N and NRHS
  'L'                                                     :Value of UPLO
 (-0.39,-0.71)
 ( 5.14,-0.64) ( 8.86, 1.81)
 (-7.86,-2.96) (-3.52, 0.58) (-2.83,-0.03)
 ( 3.80, 0.92) ( 5.32,-1.59) (-1.54,-2.86) (-0.56, 0.12)  :End of matrix A
 (-55.64, 41.22) (-19.09,-35.97)
 (-48.18, 66.00) (-12.08,-27.02)
 ( -0.49, -1.47) (  6.95, 20.49)
 ( -6.43, 19.24) ( -4.59,-35.53)                          :End of matrix B


f07nwfe.d

F07NWF Example Program Data
  4                                                       :Value of N
  'L'                                                     :Value of UPLO
 (-0.39,-0.71)
 ( 5.14,-0.64) ( 8.86, 1.81)
 (-7.86,-2.96) (-3.52, 0.58) (-2.83,-0.03)
 ( 3.80, 0.92) ( 5.32,-1.59) (-1.54,-2.86) (-0.56, 0.12)  :End of matrix A


f07pafe.d

F07PAF Example Program Data
  4                         :Value of N
 -1.81   2.06   0.63  -1.15
         1.15   1.87   4.20
               -0.21   3.87
                       2.07 :End of matrix A
  0.96   6.07   8.38   9.50 :End of vector b


f07pbfe.d

F07PBF Example Program Data
  4      2                  :Values of N and NRHS
 -1.81   2.06   0.63  -1.15
         1.15   1.87   4.20
               -0.21   3.87
                       2.07 :End of matrix A
  0.96   3.93
  6.07  19.25
  8.38   9.90
  9.50  27.85               :End of matrix B


f07pdfe.d

F07PDF Example Program Data
  4                           :Value of N
  'L'                         :Value of UPLO
  2.07
  3.87  -0.21
  4.20   1.87   1.15
 -1.15   0.63   2.06  -1.81   :End of matrix A


f07pefe.d

F07PEF Example Program Data
  4  2                        :Values of N and NRHS
  'L'                         :Value of UPLO
  2.07
  3.87  -0.21
  4.20   1.87   1.15
 -1.15   0.63   2.06  -1.81   :End of matrix A
 -9.50  27.85
 -8.38   9.90
 -6.07  19.25
 -0.96   3.93                 :End of matrix B


f07pgfe.d

F07PGF Example Program Data
  4                           :Value of N
  'L'                         :Value of UPLO
  2.07
  3.87  -0.21
  4.20   1.87   1.15
 -1.15   0.63   2.06  -1.81   :End of matrix A


f07phfe.d

F07PHF Example Program Data
  4  2                        :Values of N and NRHS
  'L'                         :Value of UPLO
  2.07
  3.87  -0.21
  4.20   1.87   1.15
 -1.15   0.63   2.06  -1.81   :End of matrix A
 -9.50  27.85
 -8.38   9.90
 -6.07  19.25
 -0.96   3.93                 :End of matrix B


f07pjfe.d

F07PJF Example Program Data
  4                           :Value of N
  'L'                         :Value of UPLO
  2.07
  3.87  -0.21
  4.20   1.87   1.15
 -1.15   0.63   2.06  -1.81   :End of matrix A


f07pnfe.d

F07PNF Example Program Data
    4                                                            :Value of N
 ( -1.84,  0.00) (  0.11, -0.11) ( -1.78, -1.18) (  3.91, -1.50)
                 ( -4.63 , 0.00) ( -1.84,  0.03) (  2.21,  0.21)
                                 ( -8.87,  0.00) (  1.58, -0.90)
                                                 ( -1.36 , 0.00) :End matrix A
 (  2.98,-10.18) ( -9.58,  3.88) ( -0.77,-16.05) (  7.79,  5.48) :End vector b


f07prfe.d

F07PRF Example Program Data
  4                                                       :Value of N
  'L'                                                     :Value of UPLO
 (-1.36, 0.00)
 ( 1.58,-0.90) (-8.87, 0.00)
 ( 2.21, 0.21) (-1.84, 0.03) (-4.63, 0.00)
 ( 3.91,-1.50) (-1.78,-1.18) ( 0.11,-0.11) (-1.84, 0.00)  :End of matrix A


f07psfe.d

F07PSF Example Program Data
  4  2                                                    :Values of N and NRHS
  'L'                                                     :Value of UPLO
 (-1.36, 0.00)
 ( 1.58,-0.90) (-8.87, 0.00)
 ( 2.21, 0.21) (-1.84, 0.03) (-4.63, 0.00)
 ( 3.91,-1.50) (-1.78,-1.18) ( 0.11,-0.11) (-1.84, 0.00)  :End of matrix A
 ( 7.79,  5.48) (-35.39, 18.01)
 (-0.77,-16.05) (  4.23,-70.02)
 (-9.58,  3.88) (-24.79, -8.40)
 ( 2.98,-10.18) ( 28.68,-39.89)                           :End of matrix B


f07pufe.d

F07PUF Example Program Data
  4                                                       :Value of N
  'L'                                                     :Value of UPLO
 (-1.36, 0.00)
 ( 1.58,-0.90) (-8.87, 0.00)
 ( 2.21, 0.21) (-1.84, 0.03) (-4.63, 0.00)
 ( 3.91,-1.50) (-1.78,-1.18) ( 0.11,-0.11) (-1.84, 0.00)  :End of matrix A


f07pvfe.d

F07PVF Example Program Data
  4  2                                                    :Values of N and NRHS
  'L'                                                     :Value of UPLO
 (-1.36, 0.00)
 ( 1.58,-0.90) (-8.87, 0.00)
 ( 2.21, 0.21) (-1.84, 0.03) (-4.63, 0.00)
 ( 3.91,-1.50) (-1.78,-1.18) ( 0.11,-0.11) (-1.84, 0.00)  :End of matrix A
 ( 7.79,  5.48) (-35.39, 18.01)
 (-0.77,-16.05) (  4.23,-70.02)
 (-9.58,  3.88) (-24.79, -8.40)
 ( 2.98,-10.18) ( 28.68,-39.89)                           :End of matrix B


f07pwfe.d

F07PWF Example Program Data
  4                                                       :Value of N
  'L'                                                     :Value of UPLO
 (-1.36, 0.00)
 ( 1.58,-0.90) (-8.87, 0.00)
 ( 2.21, 0.21) (-1.84, 0.03) (-4.63, 0.00)
 ( 3.91,-1.50) (-1.78,-1.18) ( 0.11,-0.11) (-1.84, 0.00)  :End of matrix A


f07qnfe.d

F07QNF Example Program Data
    4                                                            :Value of N
 ( -0.56,  0.12) ( -1.54, -2.86) (  5.32, -1.59) (  3.80,  0.92)
                 ( -2.83 ,-0.03) ( -3.52,  0.58) ( -7.86, -2.96)
                                 (  8.86,  1.81) (  5.14, -0.64)
                                                 ( -0.39 ,-0.71) :End matrix A
 ( -6.43, 19.24) ( -0.49, -1.47) (-48.18, 66.00) (-55.64, 41.22) :End vector b


f07qrfe.d

F07QRF Example Program Data
  4                                                       :Value of N
  'L'                                                     :Value of UPLO
 (-0.39,-0.71)
 ( 5.14,-0.64) ( 8.86, 1.81)
 (-7.86,-2.96) (-3.52, 0.58) (-2.83,-0.03)
 ( 3.80, 0.92) ( 5.32,-1.59) (-1.54,-2.86) (-0.56, 0.12)  :End of matrix A


f07qsfe.d

F07QSF Example Program Data
  4  2                                                    :Values of N and NRHS
  'L'                                                     :Value of UPLO
 (-0.39,-0.71)
 ( 5.14,-0.64) ( 8.86, 1.81)
 (-7.86,-2.96) (-3.52, 0.58) (-2.83,-0.03)
 ( 3.80, 0.92) ( 5.32,-1.59) (-1.54,-2.86) (-0.56, 0.12)  :End of matrix A
 (-55.64, 41.22) (-19.09,-35.97)
 (-48.18, 66.00) (-12.08,-27.02)
 ( -0.49, -1.47) (  6.95, 20.49)
 ( -6.43, 19.24) ( -4.59,-35.53)                          :End of matrix B


f07qufe.d

F07QUF Example Program Data
  4                                                       :Value of N
  'L'                                                     :Value of UPLO
 (-0.39,-0.71)
 ( 5.14,-0.64) ( 8.86, 1.81)
 (-7.86,-2.96) (-3.52, 0.58) (-2.83,-0.03)
 ( 3.80, 0.92) ( 5.32,-1.59) (-1.54,-2.86) (-0.56, 0.12)  :End of matrix A


f07qvfe.d

F07QVF Example Program Data
  4  2                                                    :Values of N and NRHS
  'L'                                                     :Value of UPLO
 (-0.39,-0.71)
 ( 5.14,-0.64) ( 8.86, 1.81)
 (-7.86,-2.96) (-3.52, 0.58) (-2.83,-0.03)
 ( 3.80, 0.92) ( 5.32,-1.59) (-1.54,-2.86) (-0.56, 0.12)  :End of matrix A
 (-55.64, 41.22) (-19.09,-35.97)
 (-48.18, 66.00) (-12.08,-27.02)
 ( -0.49, -1.47) (  6.95, 20.49)
 ( -6.43, 19.24) ( -4.59,-35.53)                          :End of matrix B


f07qwfe.d

F07QWF Example Program Data
  4                                                       :Value of N
  'L'                                                     :Value of UPLO
 (-0.39,-0.71)
 ( 5.14,-0.64) ( 8.86, 1.81)
 (-7.86,-2.96) (-3.52, 0.58) (-2.83,-0.03)
 ( 3.80, 0.92) ( 5.32,-1.59) (-1.54,-2.86) (-0.56, 0.12)  :End of matrix A


f07tefe.d

F07TEF Example Program Data
  4  2                        :Values of N and NRHS
  'L'                         :Value of UPLO
  4.30
 -3.96  -4.87
  0.40   0.31  -8.02
 -0.27   0.07  -5.95   0.12   :End of matrix A
-12.90 -21.50
 16.75  14.93
-17.55   6.33
-11.04   8.09                 :End of matrix B


f07tgfe.d

F07TGF Example Program Data
  4                           :Value of N
  'L'                         :Value of UPLO
  4.30
 -3.96  -4.87
  0.40   0.31  -8.02
 -0.27   0.07  -5.95   0.12   :End of matrix A


f07thfe.d

F07THF Example Program Data
  4  2                        :Values of N and NRHS
  'L'                         :Value of UPLO
  4.30
 -3.96  -4.87
  0.40   0.31  -8.02
 -0.27   0.07  -5.95   0.12   :End of matrix A
-12.90 -21.50
 16.75  14.93
-17.55   6.33
-11.04   8.09                 :End of matrix B


f07tjfe.d

F07TJF Example Program Data
  4                           :Value of N
  'L'                         :Value of UPLO
  4.30
 -3.96  -4.87
  0.40   0.31  -8.02
 -0.27   0.07  -5.95   0.12   :End of matrix A


f07tsfe.d

F07TSF Example Program Data
  4  2                                                    :Values of N and NRHS
  'L'                                                     :Value of UPLO
 ( 4.78, 4.56)
 ( 2.00,-0.30) (-4.11, 1.25)
 ( 2.89,-1.34) ( 2.36,-4.25) ( 4.15, 0.80)
 (-1.89, 1.15) ( 0.04,-3.69) (-0.02, 0.46) ( 0.33,-0.26)  :End of matrix A
 (-14.78,-32.36) (-18.02, 28.46)
 (  2.98, -2.14) ( 14.22, 15.42)
 (-20.96, 17.06) (  5.62, 35.89)
 (  9.54,  9.91) (-16.46, -1.73)                          :End of matrix B


f07tufe.d

F07TUF Example Program Data
  4                                                       :Value of N
  'L'                                                     :Value of UPLO
 ( 4.78, 4.56)
 ( 2.00,-0.30) (-4.11, 1.25)
 ( 2.89,-1.34) ( 2.36,-4.25) ( 4.15, 0.80)
 (-1.89, 1.15) ( 0.04,-3.69) (-0.02, 0.46) ( 0.33,-0.26)  :End of matrix A


f07tvfe.d

F07TVF Example Program Data
  4  2                                                    :Values of N and NRHS
  'L'                                                     :Value of UPLO
 ( 4.78, 4.56)
 ( 2.00,-0.30) (-4.11, 1.25)
 ( 2.89,-1.34) ( 2.36,-4.25) ( 4.15, 0.80)
 (-1.89, 1.15) ( 0.04,-3.69) (-0.02, 0.46) ( 0.33,-0.26)  :End of matrix A
 (-14.78,-32.36) (-18.02, 28.46)
 (  2.98, -2.14) ( 14.22, 15.42)
 (-20.96, 17.06) (  5.62, 35.89)
 (  9.54,  9.91) (-16.46, -1.73)                          :End of matrix B


f07twfe.d

F07TWF Example Program Data
  4                                                       :Value of N
  'L'                                                     :Value of UPLO
 ( 4.78, 4.56)
 ( 2.00,-0.30) (-4.11, 1.25)
 ( 2.89,-1.34) ( 2.36,-4.25) ( 4.15, 0.80)
 (-1.89, 1.15) ( 0.04,-3.69) (-0.02, 0.46) ( 0.33,-0.26)  :End of matrix A


f07uefe.d

F07UEF Example Program Data
  4  2                        :Values of N and NRHS
  'L'                         :Value of UPLO
  4.30
 -3.96  -4.87
  0.40   0.31  -8.02
 -0.27   0.07  -5.95   0.12   :End of matrix A
-12.90 -21.50
 16.75  14.93
-17.55   6.33
-11.04   8.09                 :End of matrix B


f07ugfe.d

F07UGF Example Program Data
  4                           :Value of N
  'L'                         :Value of UPLO
  4.30
 -3.96  -4.87
  0.40   0.31  -8.02
 -0.27   0.07  -5.95   0.12   :End of matrix A


f07uhfe.d

F07UHF Example Program Data
  4  2                        :Values of N and NRHS
  'L'                         :Value of UPLO
  4.30
 -3.96  -4.87
  0.40   0.31  -8.02
 -0.27   0.07  -5.95   0.12   :End of matrix A
-12.90 -21.50
 16.75  14.93
-17.55   6.33
-11.04   8.09                 :End of matrix B


f07ujfe.d

F07UJF Example Program Data
  4                           :Value of N
  'L'                         :Value of UPLO
  4.30
 -3.96  -4.87
  0.40   0.31  -8.02
 -0.27   0.07  -5.95   0.12   :End of matrix A


f07usfe.d

F07USF Example Program Data
  4  2                                                    :Values of N and NRHS
  'L'                                                     :Value of UPLO
 ( 4.78, 4.56)
 ( 2.00,-0.30) (-4.11, 1.25)
 ( 2.89,-1.34) ( 2.36,-4.25) ( 4.15, 0.80)
 (-1.89, 1.15) ( 0.04,-3.69) (-0.02, 0.46) ( 0.33,-0.26)  :End of matrix A
 (-14.78,-32.36) (-18.02, 28.46)
 (  2.98, -2.14) ( 14.22, 15.42)
 (-20.96, 17.06) (  5.62, 35.89)
 (  9.54,  9.91) (-16.46, -1.73)                          :End of matrix B


f07uufe.d

F07UUF Example Program Data
  4                                                       :Value of N
  'L'                                                     :Value of UPLO
 ( 4.78, 4.56)
 ( 2.00,-0.30) (-4.11, 1.25)
 ( 2.89,-1.34) ( 2.36,-4.25) ( 4.15, 0.80)
 (-1.89, 1.15) ( 0.04,-3.69) (-0.02, 0.46) ( 0.33,-0.26)  :End of matrix A


f07uvfe.d

F07UVF Example Program Data
  4  2                                                    :Values of N and NRHS
  'L'                                                     :Value of UPLO
 ( 4.78, 4.56)
 ( 2.00,-0.30) (-4.11, 1.25)
 ( 2.89,-1.34) ( 2.36,-4.25) ( 4.15, 0.80)
 (-1.89, 1.15) ( 0.04,-3.69) (-0.02, 0.46) ( 0.33,-0.26)  :End of matrix A
 (-14.78,-32.36) (-18.02, 28.46)
 (  2.98, -2.14) ( 14.22, 15.42)
 (-20.96, 17.06) (  5.62, 35.89)
 (  9.54,  9.91) (-16.46, -1.73)                          :End of matrix B


f07uwfe.d

F07UWF Example Program Data
  4                                                       :Value of N
  'L'                                                     :Value of UPLO
 ( 4.78, 4.56)
 ( 2.00,-0.30) (-4.11, 1.25)
 ( 2.89,-1.34) ( 2.36,-4.25) ( 4.15, 0.80)
 (-1.89, 1.15) ( 0.04,-3.69) (-0.02, 0.46) ( 0.33,-0.26)  :End of matrix A


f07vefe.d

F07VEF Example Program Data
  4  1  2                     :Values of N, KD and NRHS
  'L'                         :Value of UPLO
 -4.16
 -2.25   4.78
         5.86   6.32
               -4.82   0.16   :End of matrix A
-16.64  -4.16
-13.78 -16.59
 13.10  -4.94
-14.14  -9.96                 :End of matrix B


f07vgfe.d

F07VGF Example Program Data
  4  1                        :Values of N and KD
  'L'                         :Value of UPLO
 -4.16
 -2.25   4.78
         5.86   6.32
               -4.82   0.16   :End of matrix A


f07vhfe.d

F07VHF Example Program Data
  4  1  2                     :Values of N, KD and NRHS
  'L'                         :Value of UPLO
 -4.16
 -2.25   4.78
         5.86   6.32
               -4.82   0.16   :End of matrix A
-16.64  -4.16
-13.78 -16.59
 13.10  -4.94
-14.14  -9.96                 :End of matrix B


f07vsfe.d

F07VSF Example Program Data
  4  2  2                                              :Values of N, KD and NRHS
  'L'                                                     :Value of UPLO
 (-1.94, 4.43)
 (-3.39, 3.44) ( 4.12,-4.27)
 ( 1.62, 3.68) (-1.84, 5.53) ( 0.43,-2.66)
               (-2.77,-1.93) ( 1.74,-0.04) ( 0.44, 0.10)  :End of matrix A
 ( -8.86, -3.88) (-24.09, -5.27)
 (-15.57,-23.41) (-57.97,  8.14)
 ( -7.63, 22.78) ( 19.09,-29.51)
 (-14.74, -2.40) ( 19.17, 21.33)                          :End of matrix B


f07vufe.d

F07VUF Example Program Data
  4  2                                                    :Values of N and KD
  'L'                                                     :Value of UPLO
 (-1.94, 4.43)
 (-3.39, 3.44) ( 4.12,-4.27)
 ( 1.62, 3.68) (-1.84, 5.53) ( 0.43,-2.66)
               (-2.77,-1.93) ( 1.74,-0.04) ( 0.44, 0.10)  :End of matrix A


f07vvfe.d

F07VVF Example Program Data
  4  2  2                                              :Values of N, KD and NRHS
  'L'                                                     :Value of UPLO
 (-1.94, 4.43)
 (-3.39, 3.44) ( 4.12,-4.27)
 ( 1.62, 3.68) (-1.84, 5.53) ( 0.43,-2.66)
               (-2.77,-1.93) ( 1.74,-0.04) ( 0.44, 0.10)  :End of matrix A
 ( -8.86, -3.88) (-24.09, -5.27)
 (-15.57,-23.41) (-57.97,  8.14)
 ( -7.63, 22.78) ( 19.09,-29.51)
 (-14.74, -2.40) ( 19.17, 21.33)                          :End of matrix B


f07wdfe.d

F07WDF Example Program Data
  4       'L'      'N' : n, uplo, transr
  0.76    0.34
  4.16    1.18
 -3.12    5.03
  0.56   -0.83
 -0.10    1.18         : RFP matrix AR


f07wefe.d

F07WEF Example Program Data
  4 2     'L'     'N'    : n, nrhs, uplo, transr
  0.76    0.34
  4.16    1.18
 -3.12    5.03
  0.56   -0.83
 -0.10    1.18           : AR

  8.70   8.30
-13.35   2.13
  1.89   1.61
 -4.14   5.00            : B


f07wjfe.d

F07WJF Example Program Data
  4       'L'       'N'   : n, uplo, transr

  0.76    0.34
  4.16    1.18
 -3.12    5.03
  0.56   -0.83
 -0.10    1.18            : AR


f07wkfe.d

F07WKF Example Program Data
  4       'L'   'N'   'N' : n, uplo, transr, diag
 -8.02   -5.95
  4.30    0.12
 -3.96   -4.87
  0.40    0.31
 -0.27    0.07            : AR


f07wrfe.d

F07WRF Example Program Data
   4     'L'     'N'           : n, uplo, transr
 ( 4.09, 0.00)   ( 2.33, 0.14)
 ( 3.23, 0.00)   ( 4.29, 0.00)
 ( 1.51, 1.92)   ( 3.58, 0.00)
 ( 1.90,-0.84)   (-0.23,-1.11)
 ( 0.42,-2.50)   (-1.18,-1.37) : AR


f07wwfe.d

F07WWF Example Program Data
   4     'L'    'N'           : n, uplo, transr
 ( 4.09, 0.00)  ( 2.33,-0.14)
 ( 3.23, 0.00)  ( 4.29, 0.00)
 ( 1.51, 1.92)  ( 3.58, 0.00)
 ( 1.90,-0.84)  (-0.23,-1.11)
 ( 0.42,-2.50)  (-1.18,-1.37) : AR


f07wxfe.d

F07WXF Example Program Data
   4     'L'     'N'     'N'  : n, uplo, transr, diag
 ( 4.15,-0.80)  (-0.02,-0.46)
 ( 4.78, 4.56)  ( 0.33, 0.26)
 ( 2.00,-0.30)  (-4.11, 1.25)
 ( 2.89,-1.34)  ( 2.36,-4.25)
 (-1.89, 1.15)  ( 0.04,-3.69) : AR


f08aafe.d

F08AAF Example Program Data

  6      4                  :Values of M and N

 -0.57  -1.28  -0.39   0.25
 -1.93   1.08  -0.31  -2.14
  2.30   0.24   0.40  -0.35
 -1.93   0.64  -0.66   0.08
  0.15   0.30   0.15  -2.13
 -0.02   1.03  -1.43   0.50 :End of matrix A

 -2.67
 -0.55
  3.34
 -0.77
  0.48
  4.10                      :End of vector b


f08abfe.d

F08ABF Example Program Data

  6      4      2           : m, n and nrhs

 -0.57  -1.28  -0.39   0.25
 -1.93   1.08  -0.31  -2.14
  2.30   0.24   0.40  -0.35
 -1.93   0.64  -0.66   0.08
  0.15   0.30   0.15  -2.13
 -0.02   1.03  -1.43   0.50 : matrix A

 -2.67   0.41
 -0.55  -3.10
  3.34  -4.01
 -0.77   2.76
  0.48  -6.17
  4.10   0.21               : matrix B


f08aefe.d

F08AEF Example Program Data

  6      4      2           :Values of M, N and NRHS

 -0.57  -1.28  -0.39   0.25
 -1.93   1.08  -0.31  -2.14
  2.30   0.24   0.40  -0.35
 -1.93   0.64  -0.66   0.08
  0.15   0.30   0.15  -2.13
 -0.02   1.03  -1.43   0.50 :End of matrix A

 -2.67   0.41
 -0.55  -3.10
  3.34  -4.01
 -0.77   2.76
  0.48  -6.17
  4.10   0.21               :End of matrix B


f08affe.d

F08AFF Example Program Data
  6  4                        :Values of M and N
 -0.57  -1.28  -0.39   0.25
 -1.93   1.08  -0.31  -2.14
  2.30   0.24   0.40  -0.35
 -1.93   0.64  -0.66   0.08
  0.15   0.30   0.15  -2.13
 -0.02   1.03  -1.43   0.50   :End of matrix A


f08ahfe.d

F08AHF Example Program Data
  4  6  2                                   :Values of M, N and NRHS
 -5.42   3.28  -3.68   0.27   2.06   0.46
 -1.65  -3.40  -3.20  -1.03  -4.06  -0.01
 -0.37   2.35   1.90   4.31  -1.76   1.13
 -3.15  -0.11   1.99  -2.70   0.26   4.50   :End of matrix A
 -2.87  -5.23
  1.63   0.29
 -3.52   4.76
  0.45  -8.41                               :End of matrix B


f08ajfe.d

F08AJF Example Program Data
  4  6                                      :Values of M and N
 -5.42   3.28  -3.68   0.27   2.06   0.46
 -1.65  -3.40  -3.20  -1.03  -4.06  -0.01
 -0.37   2.35   1.90   4.31  -1.76   1.13
 -3.15  -0.11   1.99  -2.70   0.26   4.50   :End of matrix A


f08avfe.d

F08AVF Example Program Data
  3  4  2                                          :Values of M, N and NRHS
 ( 0.28,-0.36) ( 0.50,-0.86) (-0.77,-0.48) ( 1.58, 0.66)
 (-0.50,-1.10) (-1.21, 0.76) (-0.32,-0.24) (-0.27,-1.15)
 ( 0.36,-0.51) (-0.07, 1.33) (-0.75, 0.47) (-0.08, 1.01)   :End of matrix A
 (-1.35, 0.19) ( 4.83,-2.67)
 ( 9.41,-3.56) (-7.28, 3.34)
 (-7.57, 6.93) ( 0.62, 4.53)                               :End of matrix B


f08awfe.d

F08AWF Example Program Data
  3  4                                                     :Values of M and N
 ( 0.28,-0.36) ( 0.50,-0.86) (-0.77,-0.48) ( 1.58, 0.66)
 (-0.50,-1.10) (-1.21, 0.76) (-0.32,-0.24) (-0.27,-1.15)
 ( 0.36,-0.51) (-0.07, 1.33) (-0.75, 0.47) (-0.08, 1.01)   :End of matrix A


f08bafe.d

F08BAF Example Program Data

  6      5                         :Values of M and N

 -0.09   0.14  -0.46   0.68   1.29
 -1.56   0.20   0.29   1.09   0.51
 -1.48  -0.43   0.89  -0.71  -0.96
 -1.09   0.84   0.77   2.11  -1.27
  0.08   0.55  -1.13   0.14   1.74
 -1.59  -0.72   1.06   1.24   0.34 :End of matrix A

  7.4
  4.2
 -8.3
  1.8
  8.6
  2.1                              :End of vector b


f08bbfe.d

F08BBF Example Program Data

  6      4      2           : m, n and nrhs

 -0.57  -1.28  -0.39   0.25
 -1.93   1.08  -0.31  -2.14
  2.30   0.24   0.40  -0.35
 -1.93   0.64  -0.66   0.08
  0.15   0.30   0.15  -2.13
 -0.02   1.03  -1.43   0.50 : matrix A

 -2.67   0.41
 -0.55  -3.10
  3.34  -4.01
 -0.77   2.76
  0.48  -6.17
  4.10   0.21               : matrix B


f08befe.d

F08BEF Example Program Data
  6  5  2                            :Values of M, N and NRHS
 -0.09   0.14  -0.46   0.68   1.29
 -1.56   0.20   0.29   1.09   0.51
 -1.48  -0.43   0.89  -0.71  -0.96
 -1.09   0.84   0.77   2.11  -1.27
  0.08   0.55  -1.13   0.14   1.74
 -1.59  -0.72   1.06   1.24   0.34   :End of matrix A
 -0.01  -0.04
  0.04  -0.03
  0.05   0.01
 -0.03  -0.02
  0.02   0.05
 -0.06   0.07                        :End of matrix B


f08bffe.d

F08BFF Example Program Data

  6      5      2                  :Values of M, N and NRHS

 -0.09   0.14  -0.46   0.68   1.29
 -1.56   0.20   0.29   1.09   0.51
 -1.48  -0.43   0.89  -0.71  -0.96
 -1.09   0.84   0.77   2.11  -1.27
  0.08   0.55  -1.13   0.14   1.74
 -1.59  -0.72   1.06   1.24   0.34 :End of matrix A

  7.4    2.7
  4.2   -3.0
 -8.3   -9.6
  1.8    1.1
  8.6    4.0
  2.1   -5.7                       :End of matrix B


f08bhfe.d

F08BHF Example Program Data

  6  5  2                          :Values of M, N and NRHS

 -0.09   0.14  -0.46   0.68   1.29
 -1.56   0.20   0.29   1.09   0.51
 -1.48  -0.43   0.89  -0.71  -0.96
 -1.09   0.84   0.77   2.11  -1.27
  0.08   0.55  -1.13   0.14   1.74
 -1.59  -0.72   1.06   1.24   0.34 :End of matrix A

  7.4    2.7
  4.2   -3.0
 -8.3   -9.6
  1.8    1.1
  8.6    4.0
  2.1   -5.7                       :End of matrix B


f08cefe.d

F08CEF Example Program Data

  6      4      2           :Values of M, N and NRHS

 -0.57  -1.28  -0.39   0.25
 -1.93   1.08  -0.31  -2.14
  2.30   0.24   0.40  -0.35
 -1.93   0.64  -0.66   0.08
  0.15   0.30   0.15  -2.13
 -0.02   1.03  -1.43   0.50 :End of matrix A

 -2.67   0.41
 -0.55  -3.10
  3.34  -4.01
 -0.77   2.76
  0.48  -6.17
  4.10   0.21               :End of matrix B


f08cffe.d

F08CFF Example Program Data

  6      4                   :Values of M and N

 -0.57  -1.28  -0.39   0.25
 -1.93   1.08  -0.31  -2.14
  2.30   0.24   0.40  -0.35
 -1.93   0.64  -0.66   0.08
  0.15   0.30   0.15  -2.13
 -0.02   1.03  -1.43   0.50 :End of matrix A


f08chfe.d

F08CHF Example Program Data

  4      6                                :Values of M and N

 -5.42   3.28  -3.68   0.27   2.06   0.46
 -1.65  -3.40  -3.20  -1.03  -4.06  -0.01
 -0.37   2.35   1.90   4.31  -1.76   1.13
 -3.15  -0.11   1.99  -2.70   0.26   4.50 :End of matrix A

 -2.87
  1.63
 -3.52
  0.45                                    :End of vector b


f08cjfe.d

F08CJF Example Program Data

  4      6                                :Values of M and N

 -0.57  -1.93   2.30  -1.93   0.15  -0.02
 -1.28   1.08   0.24   0.64   0.30   1.03
 -0.39  -0.31   0.40  -0.66   0.15  -1.43
  0.25  -2.14  -0.35   0.08  -2.13   0.50 :End of matrix A


f08cvfe.d

F08CVF Example Program Data

   3             4                               :Values of M, N and NRHS

 ( 0.28,-0.36) ( 0.50,-0.86) (-0.77,-0.48) ( 1.58, 0.66)
 (-0.50,-1.10) (-1.21, 0.76) (-0.32,-0.24) (-0.27,-1.15)
 ( 0.36,-0.51) (-0.07, 1.33) (-0.75, 0.47) (-0.08, 1.01) :End of matrix A

 (-1.35, 0.19)
 ( 9.41,-3.56)
 (-7.57, 6.93)                                           :End of vector b


f08fafe.d

F08FAF Example Program Data

  4                  :Value of N

  1.0  2.0  3.0  4.0
       2.0  3.0  4.0
            3.0  4.0
                 4.0 :End of matrix A


f08fbfe.d

F08FBF Example Program Data
  4                  :Value of N
 -1.0  1.0           :Values of VL and VU
  1.0  2.0  3.0  4.0
       2.0  3.0  4.0
            3.0  4.0
                 4.0 :End of matrix A


f08fcfe.d

F08FCF Example Program Data
  4                         :Value of N
  'L'                       :Value of UPLO
  1.0
  2.0   2.0
  3.0   3.0   3.0
  4.0   4.0   4.0   4.0     :End of matrix A
  'V'                       :Value of JOB


f08fdfe.d

F08FDF Example Program Data

  4    2    3        :Values of N, IL and IU

  1.0  2.0  3.0  4.0
       2.0  3.0  4.0
            3.0  4.0
                 4.0 :End of matrix A


f08fefe.d

F08FEF Example Program Data
  4                           :Value of N
  'L'                         :Value of UPLO
  2.07
  3.87  -0.21
  4.20   1.87   1.15
 -1.15   0.63   2.06  -1.81   :End of matrix A


f08fffe.d

F08FFF Example Program Data
  4                           :Value of N
  'L'                         :Value of UPLO
  2.07
  3.87  -0.21
  4.20   1.87   1.15
 -1.15   0.63   2.06  -1.81   :End of matrix A


f08fgfe.d

F08FGF Example Program Data
  4                           :Value of N
  'L'                         :Value of UPLO
  2.07
  3.87  -0.21
  4.20   1.87   1.15
 -1.15   0.63   2.06  -1.81   :End of matrix A


f08fnfe.d

F08FNF Example Program Data

  4                                                :Value of N

 (1.0, 0.0)  (2.0, -1.0)  (3.0, -1.0)  (4.0, -1.0)
             (2.0,  0.0)  (3.0, -2.0)  (4.0, -2.0)
                          (3.0,  0.0)  (4.0, -3.0)
                                       (4.0,  0.0) :End of matrix A


f08fpfe.d

F08FPF Example Program Data
  4                                                :Value of N
 -2.0         2.0                                  :Values of VL and VU
 (1.0, 0.0)  (2.0, -1.0)  (3.0, -1.0)  (4.0, -1.0)
             (2.0,  0.0)  (3.0, -2.0)  (4.0, -2.0)
                          (3.0,  0.0)  (4.0, -3.0)
                                       (4.0,  0.0) :End of matrix A


f08fqfe.d

F08FQF Example Program Data
  4                                                  :Value of N
  'L'                                                :Value of UPLO
  (1.0, 0.0)
  (2.0, 1.0)  (2.0, 0.0)
  (3.0, 1.0)  (3.0, 2.0)  (3.0, 0.0)
  (4.0, 1.0)  (4.0, 2.0)  (4.0, 3.0)  (4.0, 0.0)     :End of matrix A
  'V'                                                :Value of JOB


f08frfe.d

F08FRF Example Program Data

   4           2           3                         :Values of N, IL and IU

  (1.0, 0.0)  (2.0,-1.0)  (3.0,-1.0)  (4.0,-1.0)
              (2.0, 0.0)  (3.0,-2.0)  (4.0,-2.0)
                          (3.0, 0.0)  (4.0,-3.0)
                                      (4.0, 0.0)     :End of matrix A


f08fsfe.d

F08FSF Example Program Data
  4                                                        :Value of N
  'L'                                                      :Value of UPLO
 (-2.28, 0.00)
 ( 1.78, 2.03) (-1.12, 0.00)
 ( 2.26,-0.10) ( 0.01,-0.43) (-0.37, 0.00)
 (-0.12,-2.53) (-1.07,-0.86) ( 2.31, 0.92) (-0.73, 0.00)   :End of matrix A


f08ftfe.d

F08FTF Example Program Data
  4                                                        :Value of N
  'L'                                                      :Value of UPLO
 (-2.28, 0.00)
 ( 1.78, 2.03) (-1.12, 0.00)
 ( 2.26,-0.10) ( 0.01,-0.43) (-0.37, 0.00)
 (-0.12,-2.53) (-1.07,-0.86) ( 2.31, 0.92) (-0.73, 0.00)   :End of matrix A


f08fufe.d

F08FUF Example Program Data
  4                                                        :Value of N
  'L'                                                      :Value of UPLO
 (-2.28, 0.00)
 ( 1.78, 2.03) (-1.12, 0.00)
 ( 2.26,-0.10) ( 0.01,-0.43) (-0.37, 0.00)
 (-0.12,-2.53) (-1.07,-0.86) ( 2.31, 0.92) (-0.73, 0.00)   :End of matrix A


f08gafe.d

F08GAF Example Program Data

  4                  :Value of N

  1.0  2.0  3.0  4.0
       2.0  3.0  4.0
            3.0  4.0
                 4.0 :End of matrix A


f08gbfe.d

F08GBF Example Program Data

  4                  :Value of N
 -1.0  1.0           :Values of VL and VU

  1.0  2.0  3.0  4.0
       2.0  3.0  4.0
            3.0  4.0
                 4.0 :End of matrix A


f08gcfe.d

F08GCF Example Program Data
  4                         :Value of N
  'L'                       :Value of UPLO
  1.0
  2.0   2.0
  3.0   3.0   3.0
  4.0   4.0   4.0   4.0     :End of matrix A
  'V'                       :Value of JOB


f08gefe.d

F08GEF Example Program Data
  4                           :Value of N
  'L'                         :Value of UPLO
  2.07
  3.87  -0.21
  4.20   1.87   1.15
 -1.15   0.63   2.06  -1.81   :End of matrix A


f08gffe.d

F08GFF Example Program Data
  4                           :Value of N
  'L'                         :Value of UPLO
  2.07
  3.87  -0.21
  4.20   1.87   1.15
 -1.15   0.63   2.06  -1.81   :End of matrix A


f08ggfe.d

F08GGF Example Program Data
  4                           :Value of N
  'L'                         :Value of UPLO
  2.07
  3.87  -0.21
  4.20   1.87   1.15
 -1.15   0.63   2.06  -1.81   :End of matrix A


f08gnfe.d

F08GNF Example Program Data

  4                                                :Value of N

 (1.0, 0.0)  (2.0, -1.0)  (3.0, -1.0)  (4.0, -1.0)
             (2.0,  0.0)  (3.0, -2.0)  (4.0, -2.0)
                          (3.0,  0.0)  (4.0, -3.0)
                                       (4.0,  0.0) :End of matrix A


f08gpfe.d

F08GPF Example Program Data

  4                                                :Value of N
 -2.0         2.0                                  :Values of VL and VU

 (1.0, 0.0)  (2.0, -1.0)  (3.0, -1.0)  (4.0, -1.0)
             (2.0,  0.0)  (3.0, -2.0)  (4.0, -2.0)
                          (3.0,  0.0)  (4.0, -3.0)
                                       (4.0,  0.0) :End of matrix A


f08gqfe.d

F08GQF Example Program Data
  4                                                  :Value of N
  'L'                                                :Value of UPLO
  (1.0, 0.0)
  (2.0, 1.0)  (2.0, 0.0)
  (3.0, 1.0)  (3.0, 2.0)  (3.0, 0.0)
  (4.0, 1.0)  (4.0, 2.0)  (4.0, 3.0)  (4.0, 0.0)     :End of matrix A
  'V'                                                :Value of JOB


f08gsfe.d

F08GSF Example Program Data
  4                                                        :Value of N
  'L'                                                      :Value of UPLO
 (-2.28, 0.00)
 ( 1.78, 2.03) (-1.12, 0.00)
 ( 2.26,-0.10) ( 0.01,-0.43) (-0.37, 0.00)
 (-0.12,-2.53) (-1.07,-0.86) ( 2.31, 0.92) (-0.73, 0.00)   :End of matrix A


f08gtfe.d

F08GTF Example Program Data
  4                                                        :Value of N
  'L'                                                      :Value of UPLO
 (-2.28, 0.00)
 ( 1.78, 2.03) (-1.12, 0.00)
 ( 2.26,-0.10) ( 0.01,-0.43) (-0.37, 0.00)
 (-0.12,-2.53) (-1.07,-0.86) ( 2.31, 0.92) (-0.73, 0.00)   :End of matrix A


f08gufe.d

F08GUF Example Program Data
  4                                                        :Value of N
  'L'                                                      :Value of UPLO
 (-2.28, 0.00)
 ( 1.78, 2.03) (-1.12, 0.00)
 ( 2.26,-0.10) ( 0.01,-0.43) (-0.37, 0.00)
 (-0.12,-2.53) (-1.07,-0.86) ( 2.31, 0.92) (-0.73, 0.00)   :End of matrix A


f08hafe.d

F08HAF Example Program Data

  5    2                   :Values of N and KD

  1.0  2.0  3.0
       2.0  3.0  4.0
            3.0  4.0  5.0
                 4.0  5.0
                      5.0  :End of matrix A


f08hbfe.d

F08HBF Example Program Data

  5    2                   :Values of N and KD

 -3.0  3.0                 :Values of VL and VU

  1.0  2.0  3.0
       2.0  3.0  4.0
            3.0  4.0  5.0
                 4.0  5.0
                      5.0  :End of matrix A


f08hcfe.d

F08HCF Example Program Data
  5  2                      :Values of N and KD
  'L'                       :Value of UPLO
  1.0
  2.0  2.0
  3.0  3.0  3.0
       4.0  4.0  4.0
            5.0  5.0  5.0   :End of matrix A
  'V'                       :Value of JOB


f08hefe.d

F08HEF Example Program Data
  4  2                        :Values of N and KD
  'L'                         :Value of UPLO
  4.99
  0.04   1.05
  0.22  -0.79  -2.31
         1.04  -1.30  -0.43   :End of matrix A


f08hnfe.d

F08HNF Example Program Data

   5          2                                          :Values of N and KD

  (1.0, 0.0) (2.0,-1.0) (3.0,-1.0)
             (2.0, 0.0) (3.0,-2.0) (4.0,-2.0)
                        (3.0, 0.0) (4.0,-3.0) (5.0,-3.0)
                                   (4.0, 0.0) (5.0,-4.0)
                                              (5.0, 0.0) :End of matrix A


f08hpfe.d

F08HPF Example Program Data

   5          2                                          :Values of N and KD

  -2.0        2.0                                        :Values of VL and VU

  (1.0, 0.0) (2.0,-1.0) (3.0,-1.0)
             (2.0, 0.0) (3.0,-2.0) (4.0,-2.0)
                        (3.0, 0.0) (4.0,-3.0) (5.0,-3.0)
                                   (4.0, 0.0) (5.0,-4.0)
                                              (5.0, 0.0) :End of matrix A


f08hqfe.d

F08HQF Example Program Data
  5  2                                                   :Values of N and KD
  'L'                                                    :Value of UPLO
  (1.0, 0.0)
  (2.0, 1.0) (2.0, 0.0)
  (3.0, 1.0) (3.0, 2.0) (3.0, 0.0)
             (4.0, 2.0) (4.0, 3.0) (4.0, 0.0)
                        (5.0, 3.0) (5.0, 4.0) (5.0, 0.0) :End of matrix A
  'V'                                                    :Value of JOB


f08hsfe.d

F08HSF Example Program Data
  4  2                                                     :Values of N and KD
  'L'                                                      :Value of UPLO
 (-3.13, 0.00)
 ( 1.94, 2.10) (-1.91, 0.00)
 (-3.40,-0.25) (-0.82, 0.89) (-2.87, 0.00)
               (-0.67,-0.34) (-2.10, 0.16) ( 0.50, 0.00)   :End of matrix A


f08jafe.d

F08JAF Example Program Data

  4                         :Value of N

  1.0  4.0  9.0  16.0  :End of diagonal elements
  1.0  2.0  3.0        :End of off-diagonal elements


f08jbfe.d

F08JBF Example Program Data

  4                    :Value of N

  0.0  5.0             :Values of VL and VU

  1.0  4.0  9.0  16.0  :End of diagonal elements
  1.0  2.0  3.0        :End of off-diagonal elements


f08jcfe.d

F08JCF Example Program Data
  4                         :Value of N
  1.0  4.0  9.0  16.0
  1.0  2.0  3.0             :End of T
  'V'                       :Value of JOB


f08jdfe.d

F08JDF Example Program Data

  4    2    3          :Values of N, IL and IU

  1.0  4.0  9.0  16.0  :End of diagonal elements
  1.0  2.0  3.0        :End of off-diagonal elements


f08jefe.d

F08JEF Example Program Data
  4                           :Value of N
 -6.99   7.92   2.34   0.32
 -0.44  -2.63  -1.18          :End of matrix T


f08jffe.d

F08JFF Example Program Data
  4                           :Value of N
 -6.99   7.92   2.34   0.32
 -0.44  -2.63  -1.18          :End of matrix T


f08jgfe.d

F08JGF Example Program Data
  4                           :Value of N
  4.16   5.25   1.09   0.62
  3.17  -0.97   0.55          :End of matrix T


f08jhfe.d

F08JHF Example Program Data

  4      2                   :Values of N and KD

  4.99   0.04   0.22
         1.05  -0.79   1.04
               -2.31  -1.30
                      -0.43  :End of matrix A


f08jlfe.d

F08JLF Example Program Data

  4                    :Value of N

  1.0  4.0  9.0  16.0  :End of D
  1.0  2.0  3.0        :End of E

  'V'                  :Value of JOBZ


f08jufe.d

F08JUF Example Program Data
  4                                                        :Value of N
  'L'                                                      :Value of UPLO
 ( 6.02, 0.00)
 (-0.45,-0.25) ( 2.91, 0.00)
 (-1.30,-1.74) ( 0.05,-1.56) ( 3.29, 0.00)
 ( 1.45, 0.66) (-1.04,-1.27) ( 0.14,-1.70) ( 4.18, 0.00)   :End of matrix A


f08jvfe.d

F08JVF Example Program Data

    4               2                                      :Values of N and KD

 ( -3.13 , 0.00) (  1.94, -2.10) ( -3.40,  0.25)
                 ( -1.91,  0.00) ( -0.82, -0.89) ( -0.67,  0.34)
                                 ( -2.87,  0.00) ( -2.10, -0.16)
                                                 (  0.50,  0.00) :End matrix A


f08jyfe.d

F08JYF Example Program Data

  4                    :Value of N

  1.0  4.0  9.0  16.0  :End of D
  1.0  2.0  3.0        :End of E

  'V'                  :Value of JOBZ


f08kafe.d

F08KAF Example Program Data

  6      5                         :Values of M and N

 -0.09   0.14  -0.46   0.68   1.29
 -1.56   0.20   0.29   1.09   0.51
 -1.48  -0.43   0.89  -0.71  -0.96
 -1.09   0.84   0.77   2.11  -1.27
  0.08   0.55  -1.13   0.14   1.74
 -1.59  -0.72   1.06   1.24   0.34 :End of matrix A

  7.4
  4.2
 -8.3
  1.8
  8.6
  2.1                              :End of vector b


f08kbfe.d

F08KBF Example Program Data

   6      4                   :Values of M and N

   2.27  -1.54   1.15  -1.94
   0.28  -1.67   0.94  -0.78
  -0.48  -3.09   0.99  -0.21
   1.07   1.22   0.79   0.63
  -2.35   2.93  -1.45   2.30
   0.62  -7.39   1.03  -2.57  :End of matrix A

   1.0    1.0    1.0    1.0
   1.0    1.0                 :RHS b(1:m)


f08kcfe.d

F08KCF Example Program Data

  5      6                                :Values of M and N

 -0.09  -1.56  -1.48  -1.09   0.08  -1.59
  0.14   0.20  -0.43   0.84   0.55  -0.72
 -0.46   0.29   0.89   0.77  -1.13   1.06
  0.68   1.09  -0.71   2.11   0.14   1.24
  1.29   0.51  -0.96  -1.27   1.74   0.34 :End of matrix A

  7.4
  4.3
 -8.1
  1.8
  8.7                                     :End of vector b


f08kdfe.d

F08KDF Example Program Data

   4      6                                 :Values of M and N

   2.27   0.28  -0.48   1.07  -2.35   0.62
  -1.54  -1.67  -3.09   1.22   2.93  -7.39
   1.15   0.94   0.99   0.79  -1.45   1.03
  -1.94  -0.78  -0.21   0.63   2.30  -2.57  :End of matrix A


f08kefe.d

F08KEF Example Program Data
  6  4                        :Values of M and N
 -0.57  -1.28  -0.39   0.25
 -1.93   1.08  -0.31  -2.14
  2.30   0.24   0.40  -0.35
 -1.93   0.64  -0.66   0.08
  0.15   0.30   0.15  -2.13
 -0.02   1.03  -1.43   0.50   :End of matrix A


f08kffe.d

F08KFF Example Program Data
  6  4                                      :Values of M and N, Example 1
 -0.57  -1.28  -0.39   0.25
 -1.93   1.08  -0.31  -2.14
  2.30   0.24   0.40  -0.35
 -1.93   0.64  -0.66   0.08
  0.15   0.30   0.15  -2.13
 -0.02   1.03  -1.43   0.50                 :End of matrix A
  4  6                                      :Values of M and N, Example 2
 -5.42   3.28  -3.68   0.27   2.06   0.46
 -1.65  -3.40  -3.20  -1.03  -4.06  -0.01
 -0.37   2.35   1.90   4.31  -1.76   1.13
 -3.15  -0.11   1.99  -2.70   0.26   4.50   :End of matrix A


f08kgfe.d

F08KGF Example Program Data
  6  4                                      :Values of M and N, Example 1
 -0.57  -1.28  -0.39   0.25
 -1.93   1.08  -0.31  -2.14
  2.30   0.24   0.40  -0.35
 -1.93   0.64  -0.66   0.08
  0.15   0.30   0.15  -2.13
 -0.02   1.03  -1.43   0.50                 :End of matrix A
  4  6                                      :Values of M and N, Example 2
 -5.42   3.28  -3.68   0.27   2.06   0.46
 -1.65  -3.40  -3.20  -1.03  -4.06  -0.01
 -0.37   2.35   1.90   4.31  -1.76   1.13
 -3.15  -0.11   1.99  -2.70   0.26   4.50   :End of matrix A


f08khfe.d

F08KHF Example Program Data

   6      4                   :Values of M and N

   2.27  -1.54   1.15  -1.94
   0.28  -1.67   0.94  -0.78
  -0.48  -3.09   0.99  -0.21
   1.07   1.22   0.79   0.63
  -2.35   2.93  -1.45   2.30
   0.62  -7.39   1.03  -2.57  :End of matrix A


f08kjfe.d

F08KJF Example Program Data

   6      4                   :Values of M and N

   2.27  -1.54   1.15  -1.94
   0.28  -1.67   0.94  -0.78
  -0.48  -3.09   0.99  -0.21
   1.07   1.22   0.79   0.63
  -2.35   2.93  -1.45   2.30
   0.62  -7.39   1.03  -2.57  :End of matrix A


f08kmfe.d

F08KMF Example Program Data

   6      4                   : Values of m and n

   2.27  -1.54   1.15  -1.94
   0.28  -1.67   0.94  -0.78
  -0.48  -3.09   0.99  -0.21
   1.07   1.22   0.79   0.63
  -2.35   2.93  -1.45   2.30
   0.62  -7.39   1.03  -2.57  : End of matrix A

   1.0    1.0    1.0    1.0
   1.0    1.0                 : RHS b(1:m)

   'V'                        : range
   1.00   4.00                : (vl,vu) or (il,iu)


f08lefe.d

F08LEF Example Program Data
  6  4  2  1  0               :Values of M, N, KL, KU and NCC
 -0.57  -1.28
 -1.93   1.08  -0.31
  2.30   0.24   0.40  -0.35
         0.64  -0.66   0.08
                0.15  -2.13
                       0.50   :End of matrix A


f08lsfe.d

F08LSF Example Program Data
  6  4  2  1  0                             :Values of M, N, KL, KU and NCC
 ( 0.96,-0.81) (-0.03, 0.96)
 (-0.98, 1.98) (-1.20, 0.19) (-0.66, 0.42)
 ( 0.62,-0.46) ( 1.01, 0.02) ( 0.63,-0.17) (-1.11, 0.60)
               ( 0.19,-0.54) (-0.98,-0.36) ( 0.22,-0.20)
                             (-0.17,-0.46) ( 1.47, 1.59)
                                           ( 0.26, 0.26)   :End of matrix A


f08mbfe.d

F08MBF Example Program Data

  4                          : n

  3.62  -2.41   1.92  -1.43  : diagonal elements,  d
  1.26  -1.53   1.19         : off-diagonal elements, e

  'V'
  0.00   4.00


f08mdfe.d

F08MDF Example Program Data

  4                          :Value of N

  3.62  -2.41   1.92  -1.43  :End of diagonal elements
  1.26  -1.53   1.19         :End of off-diagonal elements


f08mefe.d

F08MEF Example Program Data
  4                           :Value of N
  3.62  -2.41   1.92  -1.43
  1.26  -1.53   1.19          :End of matrix B
  'U'                         :Value of UPLO


f08nafe.d

F08NAF Example Program Data

  4                         :Value of N

  0.35   0.45  -0.14  -0.17
  0.09   0.07  -0.54   0.35
 -0.44  -0.33  -0.03   0.17
  0.25  -0.32  -0.13   0.11 :End of matrix A


f08nbfe.d

F08NBF Example Program Data
  4                         :Value of N
  0.35   0.45  -0.14  -0.17
  0.09   0.07  -0.54   0.35
 -0.44  -0.33  -0.03   0.17
  0.25  -0.32  -0.13   0.11 :End of matrix A


f08nefe.d

F08NEF Example Program Data
  4                           :Value of N
  0.35   0.45  -0.14  -0.17
  0.09   0.07  -0.54   0.35
 -0.44  -0.33  -0.03   0.17
  0.25  -0.32  -0.13   0.11   :End of matrix A


f08nffe.d

F08NFF Example Program Data
  4                           :Value of N
  0.35   0.45  -0.14  -0.17
  0.09   0.07  -0.54   0.35
 -0.44  -0.33  -0.03   0.17
  0.25  -0.32  -0.13   0.11   :End of matrix A


f08ngfe.d

F08NGF Example Program Data
  4                           :Value of N
  0.35   0.45  -0.14  -0.17
  0.09   0.07  -0.54   0.35
 -0.44  -0.33  -0.03   0.17
  0.25  -0.32  -0.13   0.11   :End of matrix A
  0.0                         :Value of THRESH


f08nhfe.d

F08NHF Example Program Data
  4                         :Value of N
 5.14  0.91   0.00 -32.80
 0.91  0.20   0.00  34.50
 1.90  0.80  -0.40  -3.00
-0.33  0.35   0.00   0.66   :End of matrix A


f08nnfe.d

F08NNF Example Program Data

  4                                                            :Value of N

(-3.97, -5.04)  (-4.11,  3.70)  (-0.34,  1.01)  ( 1.29, -0.86)
( 0.34, -1.50)  ( 1.52, -0.43)  ( 1.88, -5.38)  ( 3.36,  0.65)
( 3.31, -3.85)  ( 2.50,  3.45)  ( 0.88, -1.08)  ( 0.64, -1.48)
(-1.10,  0.82)  ( 1.81, -1.59)  ( 3.25,  1.33)  ( 1.57, -3.44) :End of matrix A


f08npfe.d

F08NPF Example Program Data
  4                                                            :Value of N
(-3.97, -5.04)  (-4.11,  3.70)  (-0.34,  1.01)  ( 1.29, -0.86)
( 0.34, -1.50)  ( 1.52, -0.43)  ( 1.88, -5.38)  ( 3.36,  0.65)
( 3.31, -3.85)  ( 2.50,  3.45)  ( 0.88, -1.08)  ( 0.64, -1.48)
(-1.10,  0.82)  ( 1.81, -1.59)  ( 3.25,  1.33)  ( 1.57, -3.44) :End of matrix A


f08nsfe.d

F08NSF Example Program Data
  4                                                        :Value of N
 (-3.97,-5.04) (-4.11, 3.70) (-0.34, 1.01) ( 1.29,-0.86)
 ( 0.34,-1.50) ( 1.52,-0.43) ( 1.88,-5.38) ( 3.36, 0.65)
 ( 3.31,-3.85) ( 2.50, 3.45) ( 0.88,-1.08) ( 0.64,-1.48)
 (-1.10, 0.82) ( 1.81,-1.59) ( 3.25, 1.33) ( 1.57,-3.44)   :End of matrix A


f08ntfe.d

F08NTF Example Program Data
  4                                                        :Value of N
 (-3.97,-5.04) (-4.11, 3.70) (-0.34, 1.01) ( 1.29,-0.86)
 ( 0.34,-1.50) ( 1.52,-0.43) ( 1.88,-5.38) ( 3.36, 0.65)
 ( 3.31,-3.85) ( 2.50, 3.45) ( 0.88,-1.08) ( 0.64,-1.48)
 (-1.10, 0.82) ( 1.81,-1.59) ( 3.25, 1.33) ( 1.57,-3.44)   :End of matrix A


f08nufe.d

F08NUF Example Program Data
  4                                                        :Value of N
 (-3.97,-5.04) (-4.11, 3.70) (-0.34, 1.01) ( 1.29,-0.86)
 ( 0.34,-1.50) ( 1.52,-0.43) ( 1.88,-5.38) ( 3.36, 0.65)
 ( 3.31,-3.85) ( 2.50, 3.45) ( 0.88,-1.08) ( 0.64,-1.48)
 (-1.10, 0.82) ( 1.81,-1.59) ( 3.25, 1.33) ( 1.57,-3.44)   :End of matrix A
  0.0                                                      :Value of THRESH


f08nvfe.d

F08NVF Example Program Data
  4                                                         :Value of N
 ( 1.50,-2.75) ( 0.00, 0.00) ( 0.00, 0.00) ( 0.00, 0.00)
 (-8.06,-1.24) (-2.50,-0.50) ( 0.00, 0.00) (-0.75, 0.50)
 (-2.09, 7.56) ( 1.39, 3.97) (-1.25, 0.75) (-4.82,-5.67)
 ( 6.18, 9.79) (-0.92,-0.62) ( 0.00, 0.00) (-2.50,-0.50)   :End of matrix A


f08pafe.d

F08PAF Example Program Data

  4                         :Value of N

  0.35   0.45  -0.14  -0.17
  0.09   0.07  -0.54   0.35
 -0.44  -0.33  -0.03   0.17
  0.25  -0.32  -0.13   0.11 :End of matrix A


f08pbfe.d

F08PBF Example Program Data

  4                         :Value of N

  0.35   0.45  -0.14  -0.17
  0.09   0.07  -0.54   0.35
 -0.44  -0.33  -0.03   0.17
  0.25  -0.32  -0.13   0.11 :End of matrix A


f08pefe.d

F08PEF Example Program Data
  4                                   :Value of N
  0.3500  -0.1160  -0.3886  -0.2942
 -0.5140   0.1225   0.1004   0.1126
  0.0000   0.6443  -0.1357  -0.0977
  0.0000   0.0000   0.4262   0.1632   :End of matrix H


f08pnfe.d

F08PNF Example Program Data

  4                                                            :Value of N

(-3.97, -5.04)  (-4.11,  3.70)  (-0.34,  1.01)  ( 1.29, -0.86)
( 0.34, -1.50)  ( 1.52, -0.43)  ( 1.88, -5.38)  ( 3.36,  0.65)
( 3.31, -3.85)  ( 2.50,  3.45)  ( 0.88, -1.08)  ( 0.64, -1.48)
(-1.10,  0.82)  ( 1.81, -1.59)  ( 3.25,  1.33)  ( 1.57, -3.44) :End of matrix A


f08ppfe.d

F08PPF Example Program Data

  4                                                            :Value of N

(-3.97, -5.04)  (-4.11,  3.70)  (-0.34,  1.01)  ( 1.29, -0.86)
( 0.34, -1.50)  ( 1.52, -0.43)  ( 1.88, -5.38)  ( 3.36,  0.65)
( 3.31, -3.85)  ( 2.50,  3.45)  ( 0.88, -1.08)  ( 0.64, -1.48)
(-1.10,  0.82)  ( 1.81, -1.59)  ( 3.25,  1.33)  ( 1.57, -3.44) :End of matrix A


f08qffe.d

F08QFF Example Program Data
  4                           :Value of N
  0.80  -0.11   0.01   0.03
  0.00  -0.10   0.25   0.35
  0.00  -0.65  -0.10   0.20
  0.00   0.00   0.00  -0.10   :End of matrix T
  2  1                        :Values of IFST and ILST


f08qgfe.d

F08QGF Example Program Data
  4                                   :Value of N
  0.7995  -0.1144   0.0060   0.0336
  0.0000  -0.0994   0.2478   0.3474
  0.0000  -0.6483  -0.0994   0.2026
  0.0000   0.0000   0.0000  -0.1007   :End of matrix T
  0.6551   0.1037   0.3450   0.6641
  0.5236  -0.5807  -0.6141  -0.1068
 -0.5362  -0.3073  -0.2935   0.7293
  0.0956   0.7467  -0.6463   0.1249   :End of matrix Q
  T   F   F   T                       :End of SELECT


f08qhfe.d

F08QHF Example Program Data
  4  4                        :Values of M and N
  0.10   0.50   0.68  -0.21
 -0.50   0.10  -0.24   0.67
  0.00   0.00   0.19  -0.35
  0.00   0.00   0.00  -0.72   :End of matrix A
 -0.99  -0.17   0.39   0.58
  0.00   0.48  -0.84  -0.15
  0.00   0.00   0.75   0.25
  0.00   0.00  -0.25   0.75   :End of matrix B
  0.63  -0.56   0.08  -0.23
 -0.45  -0.31   0.27   1.21
  0.20  -0.35   0.41   0.84
  0.49  -0.05  -0.52  -0.08   :End of matrix C


f08qlfe.d

F08QLF Example Program Data
  4                                   :Value of N
  0.7995  -0.1144   0.0060   0.0336
  0.0000  -0.0994   0.2478   0.3474
  0.0000  -0.6483  -0.0994   0.2026
  0.0000   0.0000   0.0000  -0.1007   :End of matrix T


f08qtfe.d

F08QTF Example Program Data
  4                                                        :Value of N
 (-6.00,-7.00) ( 0.36,-0.36) (-0.19, 0.48) ( 0.88,-0.25)
 ( 0.00, 0.00) (-5.00, 2.00) (-0.03,-0.72) (-0.23, 0.13)
 ( 0.00, 0.00) ( 0.00, 0.00) ( 8.00,-1.00) ( 0.94, 0.53)
 ( 0.00, 0.00) ( 0.00, 0.00) ( 0.00, 0.00) ( 3.00,-4.00)   :End of matrix T
  1  4                                             :Values of IFST and ILST


f08rafe.d

F08RAF Example Program Data
  5     3      2                         : m, p, q
 -0.7576  0.3697  0.3838  0.2126 -0.3112
 -0.4077 -0.1552 -0.1129  0.2676  0.8517
 -0.0488  0.7240 -0.6730 -0.1301  0.0602
 -0.2287  0.0088  0.2235 -0.9235  0.2120
  0.4530  0.5612  0.5806  0.1162  0.3595 : orthogonal matrix X


f08safe.d

F08SAF Example Program Data

  4                         :Value of N

  0.24   0.39   0.42  -0.16
        -0.11   0.79   0.63
               -0.25   0.48
                      -0.03 :End of matrix A

  4.16  -3.12   0.56  -0.10
         5.03  -0.83   1.09
                0.76   0.34
                       1.18 :End of matrix B


f08sbfe.d

F08SBF Example Program Data

  4                         :Value of N

 -1.0    1.0                :Values of VL and VU

  0.24   0.39   0.42  -0.16
        -0.11   0.79   0.63
               -0.25   0.48
                      -0.03 :End of matrix A

  4.16  -3.12   0.56  -0.10
         5.03  -0.83   1.09
                0.76   0.34
                       1.18 :End of matrix B


f08scfe.d

F08SCF Example Program Data

  4                         :Value of N

  0.24   0.39   0.42  -0.16
        -0.11   0.79   0.63
               -0.25   0.48
                      -0.03 :End of matrix A

  4.16  -3.12   0.56  -0.10
         5.03  -0.83   1.09
                0.76   0.34
                       1.18 :End of matrix B


f08sefe.d

F08SEF Example Program Data
  4                           :Value of N
  'L'                         :Value of UPLO
  0.24
  0.39  -0.11
  0.42   0.79  -0.25
 -0.16   0.63   0.48  -0.03   :End of matrix A
  4.16
 -3.12   5.03
  0.56  -0.83   0.76
 -0.10   1.09   0.34   1.18   :End of matrix B


f08spfe.d

F08SPF Example Program Data

   4                                                        :Value of N

  -3.0           3.0                                        :Values of VL and VU

 (-7.36, 0.00) ( 0.77, -0.43) (-0.64, -0.92) ( 3.01, -6.97)
               ( 3.49,  0.00) ( 2.19,  4.45) ( 1.90,  3.73)
                              ( 0.12,  0.00) ( 2.88, -3.17)
                                             (-2.54,  0.00) :End of matrix A

 ( 3.23, 0.00) ( 1.51, -1.92) ( 1.90,  0.84) ( 0.42,  2.50)
               ( 3.58,  0.00) (-0.23,  1.11) (-1.18,  1.37)
                              ( 4.09,  0.00) ( 2.33, -0.14)
                                             ( 4.29,  0.00) :End of matrix B


f08ssfe.d

F08SSF Example Program Data
  4                                                       :Value of N
  'L'                                                     :Value of UPLO
 (-7.36, 0.00)
 ( 0.77, 0.43) ( 3.49, 0.00)
 (-0.64, 0.92) ( 2.19,-4.45) ( 0.12, 0.00)
 ( 3.01, 6.97) ( 1.90,-3.73) ( 2.88, 3.17) (-2.54, 0.00)  :End of matrix A
 ( 3.23, 0.00)
 ( 1.51, 1.92) ( 3.58, 0.00)
 ( 1.90,-0.84) (-0.23,-1.11) ( 4.09, 0.00)
 ( 0.42,-2.50) (-1.18,-1.37) ( 2.33, 0.14) ( 4.29, 0.00)  :End of matrix B


f08tafe.d

F08TAF Example Program Data

  4                         :Value of N

  0.24   0.39   0.42  -0.16
        -0.11   0.79   0.63
               -0.25   0.48
                      -0.03 :End of matrix A

  4.16  -3.12   0.56  -0.10
         5.03  -0.83   1.09
                0.76   0.34
                       1.18 :End of matrix B


f08tbfe.d

F08TBF Example Program Data

  4                          :Value of N

 -1.0    1.0                 :Values of VL and VU

  0.24   0.39   0.42  -0.16
        -0.11   0.79   0.63
               -0.25   0.48
                      -0.03  :End of matrix A

  4.16  -3.12   0.56  -0.10
         5.03  -0.83   1.09
                0.76   0.34
                       1.18  :End of matrix B


f08tcfe.d

F08TCF Example Program Data

  4                         :Value of N

  0.24   0.39   0.42  -0.16
        -0.11   0.79   0.63
               -0.25   0.48
                      -0.03 :End of matrix A

  4.16  -3.12   0.56  -0.10
         5.03  -0.83   1.09
                0.76   0.34
                       1.18 :End of matrix B


f08tefe.d

F08TEF Example Program Data
  4                           :Value of N
  'L'                         :Value of UPLO
  0.24
  0.39  -0.11
  0.42   0.79  -0.25
 -0.16   0.63   0.48  -0.03   :End of matrix A
  4.16
 -3.12   5.03
  0.56  -0.83   0.76
 -0.10   1.09   0.34   1.18   :End of matrix B


f08tpfe.d

F08TPF Example Program Data

   4                                                        :Value of N

  -3.0           3.0                                        :Values of VL and VU

 (-7.36, 0.00) ( 0.77, -0.43) (-0.64, -0.92) ( 3.01, -6.97)
               ( 3.49,  0.00) ( 2.19,  4.45) ( 1.90,  3.73)
                              ( 0.12,  0.00) ( 2.88, -3.17)
                                             (-2.54,  0.00) :End of matrix A

 ( 3.23, 0.00) ( 1.51, -1.92) ( 1.90,  0.84) ( 0.42,  2.50)
               ( 3.58,  0.00) (-0.23,  1.11) (-1.18,  1.37)
                              ( 4.09,  0.00) ( 2.33, -0.14)
                                             ( 4.29,  0.00) :End of matrix B


f08tsfe.d

F08TSF Example Program Data
  4                                                       :Value of N
  'L'                                                     :Value of UPLO
 (-7.36, 0.00)
 ( 0.77, 0.43) ( 3.49, 0.00)
 (-0.64, 0.92) ( 2.19,-4.45) ( 0.12, 0.00)
 ( 3.01, 6.97) ( 1.90,-3.73) ( 2.88, 3.17) (-2.54, 0.00)  :End of matrix A
 ( 3.23, 0.00)
 ( 1.51, 1.92) ( 3.58, 0.00)
 ( 1.90,-0.84) (-0.23,-1.11) ( 4.09, 0.00)
 ( 0.42,-2.50) (-1.18,-1.37) ( 2.33, 0.14) ( 4.29, 0.00)  :End of matrix B


f08uafe.d

F08UAF Example Program Data

  4      2      1            :Values of N, KA and KB

  0.24   0.39   0.42
        -0.11   0.79   0.63
               -0.25   0.48
                      -0.03  :End of matrix A
  2.07   0.95
         1.69  -0.29
                0.65  -0.33
                       1.17  :End of matrix B


f08ubfe.d

F08UBF Example Program Data

  4      2      1            :Values of N, KA and KB

  0.0    1.0                 :Values of VL and VU

  0.24   0.39   0.42
        -0.11   0.79   0.63
               -0.25   0.48
                      -0.03  :End of matrix A
  2.07   0.95
         1.69  -0.29
                0.65  -0.33
                       1.17  :End of matrix B


f08ucfe.d

F08UCF Example Program Data

  4      2      1            :Values of N, KA and KB

  0.24   0.39   0.42
        -0.11   0.79   0.63
               -0.25   0.48
                      -0.03  :End of matrix A
  2.07   0.95
         1.69  -0.29
                0.65  -0.33
                       1.17  :End of matrix B


f08uefe.d

F08UEF Example Program Data
  4  2  1                     :Values of N, KA and KB
  'L'                         :Value of UPLO
  0.24
  0.39  -0.11
  0.42   0.79  -0.25
         0.63   0.48  -0.03   :End of matrix A
  2.07
  0.95   1.69
        -0.29   0.65
               -0.33   1.17   :End of matrix B


f08unfe.d

F08UNF Example Program Data

   4             2             1                         :Values of N, KA and KB

 (-1.13, 0.00) ( 1.94,-2.10) (-1.40, 0.25)
               (-1.91, 0.00) (-0.82,-0.89) (-0.67, 0.34)
                             (-1.87, 0.00) (-1.10,-0.16)
                                           ( 0.50, 0.00) :End of matrix A

 ( 9.89, 0.00) ( 1.08,-1.73)
               ( 1.69, 0.00) (-0.04, 0.29)
                             ( 2.65, 0.00) (-0.33, 2.24)
                                           ( 2.17, 0.00) :End of matrix B


f08upfe.d

F08UPF Example Program Data

   4             2             1                         :Values of N, KA and KB

   0.0           2.0                                     :Values of VL and VU

 (-1.13, 0.00) ( 1.94,-2.10) (-1.40, 0.25)
               (-1.91, 0.00) (-0.82,-0.89) (-0.67, 0.34)
                             (-1.87, 0.00) (-1.10,-0.16)
                                           ( 0.50, 0.00) :End of matrix A

 ( 9.89, 0.00) ( 1.08,-1.73)
               ( 1.69, 0.00) (-0.04, 0.29)
                             ( 2.65, 0.00) (-0.33, 2.24)
                                           ( 2.17, 0.00) :End of matrix B


f08uqfe.d

F08UQF Example Program Data

   4             2             1                         :Values of N, KA and KB

 (-1.13, 0.00) ( 1.94,-2.10) (-1.40, 0.25)
               (-1.91, 0.00) (-0.82,-0.89) (-0.67, 0.34)
                             (-1.87, 0.00) (-1.10,-0.16)
                                           ( 0.50, 0.00) :End of matrix A

 ( 9.89, 0.00) ( 1.08,-1.73)
               ( 1.69, 0.00) (-0.04, 0.29)
                             ( 2.65, 0.00) (-0.33, 2.24)
                                           ( 2.17, 0.00) :End of matrix B


f08usfe.d

F08USF Example Program Data
  4  2  1                                            :Values of N, KA and KB
  'L'                                                :Value of UPLO
 (-1.13, 0.00)
 ( 1.94, 2.10) (-1.91, 0.00)
 (-1.40,-0.25) (-0.82, 0.89) (-1.87, 0.00)
               (-0.67,-0.34) (-1.10, 0.16) ( 0.50, 0.00)    :End of matrix A
 ( 9.89, 0.00)
 ( 1.08, 1.73) ( 1.69, 0.00)
               (-0.04,-0.29) ( 2.65, 0.00)
                             (-0.33,-2.24) ( 2.17, 0.00)    :End of matrix B


f08vafe.d

F08VAF Example Program Data

  4    3    2   :Values of M, N and P

  1.0  2.0  3.0
  3.0  2.0  1.0
  4.0  5.0  6.0
  7.0  8.0  8.0 :End of matrix A

 -2.0 -3.0  3.0
  4.0  6.0  5.0 :End of matrix B


f08vcfe.d

F08VCF Example Program Data

  4    3    2   :Values of M, N and P

  1.0  2.0  3.0
  3.0  2.0  1.0
  4.0  5.0  6.0
  7.0  8.0  8.0 :End of matrix A

 -2.0 -3.0  3.0
  4.0  6.0  5.0 :End of matrix B


f08vefe.d

F08VEF Example Program Data

  4    3    2   :Values of M, N and P

  1.0  2.0  3.0
  3.0  2.0  1.0
  4.0  5.0  6.0
  7.0  8.0  8.0 :End of matrix A

 -2.0 -3.0  3.0
  4.0  6.0  5.0 :End of matrix B


f08vgfe.d

F08VGF Example Program Data

  4    3    2   :Values of M, N and P

  1.0  2.0  3.0
  3.0  2.0  1.0
  4.0  5.0  6.0
  7.0  8.0  8.0 :End of matrix A

 -2.0 -3.0  3.0
  4.0  6.0  5.0 :End of matrix B


f08wafe.d

F08WAF Example Program Data
   4                     :Value of N
   3.9  12.5 -34.5  -0.5
   4.3  21.5 -47.5   7.5
   4.3  21.5 -43.5   3.5
   4.4  26.0 -46.0   6.0 :End of matrix A
   1.0   2.0  -3.0   1.0
   1.0   3.0  -5.0   4.0
   1.0   3.0  -4.0   3.0
   1.0   3.0  -4.0   4.0 :End of matrix B


f08wbfe.d

F08WBF Example Program Data
   4                     :Value of N
   3.9  12.5 -34.5  -0.5
   4.3  21.5 -47.5   7.5
   4.3  21.5 -43.5   3.5
   4.4  26.0 -46.0   6.0 :End of matrix A
   1.0   2.0  -3.0   1.0
   1.0   3.0  -5.0   4.0
   1.0   3.0  -4.0   3.0
   1.0   3.0  -4.0   4.0 :End of matrix B


f08wcfe.d

F08WCF Example Program Data
   4                     :Value of N
   3.9  12.5 -34.5  -0.5
   4.3  21.5 -47.5   7.5
   4.3  21.5 -43.5   3.5
   4.4  26.0 -46.0   6.0 :End of matrix A
   1.0   2.0  -3.0   1.0
   1.0   3.0  -5.0   4.0
   1.0   3.0  -4.0   3.0
   1.0   3.0  -4.0   4.0 :End of matrix B


f08xafe.d

F08XAF Example Program Data
   4                     :Value of N
   3.9  12.5 -34.5  -0.5
   4.3  21.5 -47.5   7.5
   4.3  21.5 -43.5   3.5
   4.4  26.0 -46.0   6.0 :End of matrix A
   1.0   2.0  -3.0   1.0
   1.0   3.0  -5.0   4.0
   1.0   3.0  -4.0   3.0
   1.0   3.0  -4.0   4.0 :End of matrix B


f08xbfe.d

F08XBF Example Program Data
   4                     :Value of N
   3.9  12.5 -34.5  -0.5
   4.3  21.5 -47.5   7.5
   4.3  21.5 -43.5   3.5
   4.4  26.0 -46.0   6.0 :End of matrix A
   1.0   2.0  -3.0   1.0
   1.0   3.0  -5.0   4.0
   1.0   3.0  -4.0   3.0
   1.0   3.0  -4.0   4.0 :End of matrix B


f08xcfe.d

F08XCF Example Program Data
   4                     :Value of N
   3.9  12.5 -34.5  -0.5
   4.3  21.5 -47.5   7.5
   4.3  21.5 -43.5   3.5
   4.4  26.0 -46.0   6.0 :End of matrix A
   1.0   2.0  -3.0   1.0
   1.0   3.0  -5.0   4.0
   1.0   3.0  -4.0   3.0
   1.0   3.0  -4.0   4.0 :End of matrix B


f08yefe.d

F08YEF Example Program Data

  4    3    2   :Values of M, N and P

  1.0  2.0  3.0
  3.0  2.0  1.0
  4.0  5.0  6.0
  7.0  8.0  8.0 :End of matrix A

 -2.0 -3.0  3.0
  4.0  6.0  5.0 :End of matrix B


f08yffe.d

F08YFF Example Program Data
  4                    :Value of N
  4.0  1.0  1.0  2.0
  0.0  3.0  4.0  1.0
  0.0  1.0  3.0  1.0
  0.0  0.0  0.0  6.0   :End of matrix A
  2.0  1.0  1.0  3.0
  0.0  1.0  2.0  1.0
  0.0  0.0  1.0  1.0
  0.0  0.0  0.0  2.0   :End of matrix B
  2  1                 :Values of IFST and ILST


f08ygfe.d

F08YGF Example Program Data
  4                    :Value of N
  4.0  1.0  1.0  2.0
  0.0  3.0  4.0  1.0
  0.0  1.0  3.0  1.0
  0.0  0.0  0.0  6.0   :End of matrix A
  2.0  1.0  1.0  3.0
  0.0  1.0  2.0  1.0
  0.0  0.0  1.0  1.0
  0.0  0.0  0.0  2.0   :End of matrix B
  1.0  0.0  0.0  0.0
  0.0  1.0  0.0  0.0
  0.0  0.0  1.0  0.0
  0.0  0.0  0.0  1.0   :End of matrix Q
  1.0  0.0  0.0  0.0
  0.0  1.0  0.0  0.0
  0.0  0.0  1.0  0.0
  0.0  0.0  0.0  1.0   :End of matrix Z
  T    F    F    T     :End of SELECT


f08yhfe.d

F08YHF Example Program Data
  4  4                        :Values of M and N
  4.0   1.0   1.0   2.0
  0.0   3.0   4.0   1.0
  0.0   1.0   3.0   1.0
  0.0   0.0   0.0   6.0   :End of matrix A
  1.0   1.0   1.0   1.0
  0.0   3.0   4.0   1.0
  0.0   1.0   3.0   1.0
  0.0   0.0   0.0   4.0   :End of matrix B
  2.0   1.0   1.0   3.0
  0.0   1.0   2.0   1.0
  0.0   0.0   1.0   1.0
  0.0   0.0   0.0   2.0   :End of matrix D
  1.0   1.0   1.0   2.0
  0.0   1.0   4.0   1.0
  0.0   0.0   1.0   1.0
  0.0   0.0   0.0   1.0   :End of matrix E
 -4.0   7.0   1.0  12.0
 -9.0   2.0  -2.0  -2.0
 -4.0   2.0  -2.0   8.0
 -7.0   7.0  -6.0  19.0   :End of matrix C
 -7.0   5.0   0.0   7.0
 -5.0   1.0  -8.0   0.0
 -1.0   2.0  -3.0   5.0
 -3.0   2.0   0.0   5.0   :End of matrix F


f08ylfe.d

F08YLF Example Program Data
  4                    :Value of N
  4.0  1.0  1.0  2.0
  0.0  3.0 -1.0  1.0
  0.0  1.0  3.0  1.0
  0.0  0.0  0.0  6.0   :End of matrix A
  2.0  1.0  1.0  3.0
  0.0  1.0  0.0  1.0
  0.0  0.0  1.0  1.0
  0.0  0.0  0.0  2.0   :End of matrix B


f08zafe.d

F08ZAF Example Program Data

  6      4      2           :Values of M, N and P

 -0.57  -1.28  -0.39   0.25
 -1.93   1.08  -0.31  -2.14
  2.30   0.24   0.40  -0.35
 -1.93   0.64  -0.66   0.08
  0.15   0.30   0.15  -2.13
 -0.02   1.03  -1.43   0.50 :End of matrix A

  1.00   0.00  -1.00   0.00
  0.00   1.00   0.00  -1.00 :End of matrix B

 -1.50
 -2.14
  1.23
 -0.54
 -1.68
  0.82                      :End of vector c

  0.00
  0.00                      :End of vector d


f08zbfe.d

F08ZBF Example Program Data

  4      3      4           :Values of M, N and P

 -0.57  -1.28  -0.39
 -1.93   1.08  -0.31
  2.30   0.24  -0.40
 -0.02   1.03  -1.43        :End of matrix A

  0.50   0.00   0.00   0.00
  0.00   1.00   0.00   0.00
  0.00   0.00   2.00   0.00
  0.00   0.00   0.00   5.00 :End of matrix B

  1.32
 -4.00
  5.52
  3.24                      :End of vector d


f08zefe.d

F08ZEF Example Program Data

  4      3      4           :Values of N, M and P

 -0.57  -1.28  -0.39
 -1.93   1.08  -0.31
  2.30   0.24  -0.40
 -0.02   1.03  -1.43        :End of matrix A

  0.50   0.00   0.00   0.00
  0.00   1.00   0.00   0.00
  0.00   0.00   2.00   0.00
  0.00   0.00   0.00   5.00 :End of matrix B

  1.32
 -4.00
  5.52
  3.24                      :End of vector d


f11bdfe.d

F11BDF Example Program Data
  8                      N
 24                      NNZ
  'BICGSTAB'             METHOD
  'P'  '1'  'N'  1       PRECON, NORM, WEIGHT, ITERM
  1  1.0D-8   20         M, TOL, MAXITN
  1                      MONIT
  0  0.0                 LFILL, DTOL
  'N'  'C'               MILU, PSTRAT
  2.   1    1
 -1.   1    4
  1.   1    8
  4.   2    1
 -3.   2    2
  2.   2    5
 -7.   3    3
  2.   3    6
  3.   4    1
 -4.   4    3
  5.   4    4
  5.   4    7
 -1.   5    2
  8.   5    5
 -3.   5    7
 -6.   6    1
  5.   6    3
  2.   6    6
 -5.   7    3
 -1.   7    5
  6.   7    7
 -1.   8    2
  2.   8    6
  3.   8    8         A(I), IROW(I), ICOL(I), I=1,...,NNZ
  6.   8.  -9.  46.
 17.  21.  22.  34.   B(I), I=1,...,N
  0.   0.   0.   0.
  0.   0.   0.   0.   X(I), I=1,...,N


f11dafe.d

F11DAF Example Program Data
  4                   N
  11                  NNZ
  0 0.0               LFILL, DTOL
  'C'                 PSTRAT
  'N'                 MILU
  1.   1    2
  1.   1    3
 -1.   2    1
  2.   2    3
  2.   2    4
  3.   3    1
 -2.   3    4
  1.   4    1
 -2.   4    2
  1.   4    3
  1.   4    4        A(I), IROW(I), ICOL(I), I=1,...,NNZ


f11dbfe.d

F11DBF Example Program Data
  4                      N
 11                      NNZ
  1.   1    2
  1.   1    3
 -1.   2    1
  2.   2    3
  2.   2    4
  3.   3    1
 -2.   3    4
  1.   4    1
 -2.   4    2
  1.   4    3
  1.   4    4           A(I), IROW(I), ICOL(I), I=1,...,NNZ
  5.0  13.0 -5.0  4.0   Y(I), I=1,...,N


f11dcfe.d

F11DCF Example Program Data
  8 4                    N, M
  24                     NNZ
  'CGS'                  METHOD
  0  0.0                 LFILL, DTOL
  'C'                    PSTRAT
  'N'                    MILU
  1.0D-12   100          TOL, MAXITN
  2.   1    1
 -1.   1    4
  1.   1    8
  4.   2    1
 -3.   2    2
  2.   2    5
 -7.   3    3
  2.   3    6
  3.   4    1
 -4.   4    3
  5.   4    4
  5.   4    7
 -1.   5    2
  8.   5    5
 -3.   5    7
 -6.   6    1
  5.   6    3
  2.   6    6
 -5.   7    3
 -1.   7    5
  6.   7    7
 -1.   8    2
  2.   8    6
  3.   8    8         A(I), IROW(I), ICOL(I), I=1,...,NNZ
  6.   8.  -9.  46.
 17.  21.  22.  34.   B(I), I=1,...,N
  0.   0.   0.   0.
  0.   0.   0.   0.   X(I), I=1,...,N


f11ddfe.d

F11DDF Example Program Data
  5  2                N, M
 16                   NNZ
 'RGMRES'             METHOD
 'P' 'I' 1            PRECON, NORM, ITERM
 1.D-10 1000          TOL, MAXITN
 0.D0 0.D0            ANORM, SIGMAX
 1.1D0                OMEGA
  2.   1    1
  1.   1    2
 -1.   1    4
 -3.   2    2
 -2.   2    3
  1.   2    5
  1.   3    1
  5.   3    3
  3.   3    4
  1.   3    5
 -2.   4    1
 -3.   4    4
 -1.   4    5
  4.   5    2
 -2.   5    3
 -6.   5    5         A(I), IROW(I), ICOL(I), I=1,...,NNZ
  0.  -7.  33.
-19. -28.             B(I), I=1,...,N
  0.   0.   0.
  0.   0.             X(I), I=1,...,N


f11defe.d

F11DEF Example Program Data
  5   1               N, M
 16                   NNZ
  'RGMRES' 'S'        METHOD, PRECON
  1.05                OMEGA
  1.D-10 1000         TOL, MAXITN
  2.   1    1
  1.   1    2
 -1.   1    4
 -3.   2    2
 -2.   2    3
  1.   2    5
  1.   3    1
  5.   3    3
  3.   3    4
  1.   3    5
 -2.   4    1
 -3.   4    4
 -1.   4    5
  4.   5    2
 -2.   5    3
 -6.   5    5         A(I), IROW(I), ICOL(I), I=1,...,NNZ
  0.  -7.  33.
-19. -28.             B(I), I=1,...,N
  0.   0.   0.
  0.   0.             X(I), I=1,...,N


f11dffe.d

F11DFF Example Program Data
  9			 : n
  33 	     	      	 : nnz
  64.0      1       1
 -20.0      1       2
 -20.0      1       4
 -12.0      2       1
  64.0      2       2
 -20.0      2       3
 -20.0      2       5
 -12.0      3       2
  64.0      3       3
 -20.0      3       6
 -12.0      4       1
  64.0      4       4
 -20.0      4       5
 -20.0      4       7
 -12.0      5       2
 -12.0      5       4
  64.0      5       5
 -20.0      5       6
 -20.0      5       8
 -12.0      6       3
 -12.0      6       5
  64.0      6       6
 -20.0      6       9
 -12.0      7       4
  64.0      7       7
 -20.0      7       8
 -12.0      8       5
 -12.0      8       7
  64.0      8       8
 -20.0      8       9
 -12.0      9       6
 -12.0      9       8
  64.0      9       9    : a(i), irow(i), icol(i) for i=1,nnz
  0   0.0             	 : lfillg, dtolg
 'N'                  	 : pstrag
 'N'                  	 : milug
  3   1               	 : nb, nover


f11dgfe.d

F11DGF Example Program Data
  9                      : n
  33			 : nnz
  64.0     1     1
 -20.0     1     2
 -20.0     1     4
 -12.0     2     1
  64.0     2     2
 -20.0     2     3
 -20.0     2     5
 -12.0     3     2
  64.0     3     3
 -20.0     3     6
 -12.0     4     1
  64.0     4     4
 -20.0     4     5
 -20.0     4     7
 -12.0     5     2
 -12.0     5     4
  64.0     5     5
 -20.0     5     6
 -20.0     5     8
 -12.0     6     3
 -12.0     6     5
  64.0     6     6
 -20.0     6     9
 -12.0     7     4
  64.0     7     7
 -20.0     7     8
 -12.0     8     5
 -12.0     8     7
  64.0     8     8
 -20.0     8     9
 -12.0     9     6
 -12.0     9     8
  64.0     9     9	 : a(i), irow(i), icol(i) for i=1,nnz
 100.0
 100.0
 100.0
 100.0
 100.0
 100.0
 100.0
 100.0
 100.0			 : b(i) for i=1,n
 'BICGSTAB'              : method
 0   0.0                 : lfillg, dtolg
 'N'                 	 : pstrag
 'N'                 	 : milug
 2   1.D-6  100      	 : m, tol, maxitn
 3   1               	 : nb, nover


f11dkfe.d

F11DKF Example Program Data
  8                      N
 24                      NNZ
  'BICGSTAB'             METHOD
  'P'  '1'  'N'  1       PRECON, NORM, WEIGHT, ITERM
  2  1.0D-6   20         M, TOL, MAXITN
  1                      MONIT
  4                      NITER
  4.   1    1
 -1.   1    4
  1.   1    8
  4.   2    1
 -5.   2    2
  2.   2    5
 -7.   3    3
  2.   3    6
  2.   4    1
 -1.   4    3
  6.   4    4
  2.   4    7
 -1.   5    2
  8.   5    5
 -2.   5    7
 -2.   6    1
  5.   6    3
  8.   6    6
 -2.   7    3
 -1.   7    5
  7.   7    7
 -1.   8    2
  2.   8    6
  6.   8    8         A(I), IROW(I), ICOL(I), I=1,...,NNZ
  6.   8.  -9.  46.
 17.  21.  22.  34.   B(I), I=1,...,N
  0.   0.   0.   0.
  0.   0.   0.   0.   X(I), I=1,...,N


f11dnfe.d

F11DNF Example Program Data
  4                   N
  11                  NNZ
  0 0.0               LFILL, DTOL
  'C'                 PSTRAT
  'N'                 MILU
 ( 1., 3.)   1    2
 ( 1., 0.)   1    3
 (-1.,-2.)   2    1
 ( 2.,-2.)   2    3
 ( 2., 1.)   2    4
 ( 0., 5.)   3    1
 (-2., 0.)   3    4
 ( 1., 1.)   4    1
 (-2., 4.)   4    2
 ( 1.,-3.)   4    3
 ( 0., 7.)   4    4   A(I), IROW(I), ICOL(I), I=1,...,NNZ


f11dpfe.d

F11DPF Example Program Data
  4                     N
 11                     NNZ
 ( 1., 2.)   1    2
 ( 1., 3.)   1    3
 (-1.,-3.)   2    1
 ( 2., 0.)   2    3
 ( 0., 4.)   2    4
 ( 3., 4.)   3    1
 (-2., 0.)   3    4
 ( 1.,-1.)   4    1
 (-2.,-1.)   4    2
 ( 1., 0.)   4    3
 ( 1., 3.)   4    4     A(I), IROW(I), ICOL(I), I=1,...,NNZ
 (  5.0, 14.0)
 ( 21.0,  5.0)
 (-21.0, 18.0)
 ( 14.0,  4.0)          Y(I), I=1,...,N


f11drfe.d

F11DRF Example Program Data
  5   2                  N, M
 16                      NNZ
 'CGS'                   METHOD
 'P' 'I' 1               PRECON, NORM, ITERM
 1.D-10 1000             TOL, MAXITN
 0.D0 0.D0               ANORM, SIGMAX
 1.4D0                   OMEGA
 ( 2., 3.)   1    1
 ( 1.,-1.)   1    2
 (-1., 0.)   1    4
 ( 0., 2.)   2    2
 (-2., 1.)   2    3
 ( 1., 0.)   2    5
 ( 0.,-1.)   3    1
 ( 5., 4.)   3    3
 ( 3.,-1.)   3    4
 ( 1., 0.)   3    5
 (-2., 2.)   4    1
 (-3., 1.)   4    4
 ( 0., 3.)   4    5
 ( 4.,-2.)   5    2
 (-2., 0.)   5    3
 (-6., 1.)   5    5      A(I), IROW(I), ICOL(I), I=1,...,NNZ
 ( -3., 3.)
 (-11., 5.)
 ( 23.,48.)
 (-41., 2.)
 (-28.,-31.)             B(I), I=1,...,N
 ( 0., 0.)
 ( 0., 0.)
 ( 0., 0.)
 ( 0., 0.)
 ( 0., 0.)               X(I), I=1,...,N


f11gdfe.d

F11GDF Example Program Data
  7                      N
 16                      NNZ
  'CG'                   METHOD
  'P'  'S'  '1'  'N'  1  PRECON, SIGCMP, NORM, WEIGHT, ITERM
  1.0D-6   20            TOL, MAXITN
  2                      MONIT
  0  0.0                 LFILL, DTOL
  'N'  0.0               MIC, DSCALE
  'M'                    PSTRAT
  4.   1    1
  1.   2    1
  5.   2    2
  2.   3    3
  2.   4    2
  3.   4    4
 -1.   5    1
  1.   5    4
  4.   5    5
  1.   6    2
 -2.   6    5
  3.   6    6
  2.   7    1
 -1.   7    2
 -2.   7    3
  5.   7    7         A(I), IROW(I), ICOL(I), I=1,...,NNZ
 15.  18.  -8.  21.
 11.  10.  29.        B(I), I=1,...,N
  0.   0.   0.   0.
  0.   0.   0.        X(I), I=1,...,N


f11jafe.d

F11JAF Example Program Data
  7                   N
 16                   NNZ
  0 0.0               LFILL, DTOL
  'N' 0.0             MIC, DSCALE
  'M'                 PSTRAT
  4.   1    1
  1.   2    1
  5.   2    2
  2.   3    3
  2.   4    2
  3.   4    4
 -1.   5    1
  1.   5    4
  4.   5    5
  1.   6    2
 -2.   6    5
  3.   6    6
  2.   7    1
 -1.   7    2
 -2.   7    3
  5.   7    7        A(I), IROW(I), ICOL(I), I=1,...,NNZ


f11jbfe.d

F11JBF Example Program Data
  9                   N
 23                   NNZ
  4.   1    1
 -1.   2    1
  6.   2    2
  1.   3    2
  2.   3    3
  3.   4    4
  2.   5    1
  4.   5    5
  1.   6    3
  2.   6    4
  6.   6    6
 -4.   7    2
  1.   7    5
 -1.   7    6
  6.   7    7
 -1.   8    4
 -1.   8    6
  3.   8    8
  1.   9    1
  1.   9    5
 -1.   9    6
  1.   9    8
  4.   9    9          A(I), IROW(I), ICOL(I), I=1,...,NNZ
  4.10 -2.94  1.41
  2.53  4.35  1.29
  5.01  0.52  4.57     Y(I), I=1,...,N


f11jcfe.d

F11JCF Example Program Data
  7                   N
  16                  NNZ
 'CG'                 METHOD
  1 0.0               LFILL, DTOL
  'N' 0.0             MIC, DSCALE
  'M'                 PSTRAT
  1.0D-6 100          TOL, MAXITN
  4.   1    1
  1.   2    1
  5.   2    2
  2.   3    3
  2.   4    2
  3.   4    4
 -1.   5    1
  1.   5    4
  4.   5    5
  1.   6    2
 -2.   6    5
  3.   6    6
  2.   7    1
 -1.   7    2
 -2.   7    3
  5.   7    7         A(I), IROW(I), ICOL(I), I=1,...,NNZ
 15.  18.  -8.  21.
 11.  10.  29.        B(I), I=1,...,N
  0.   0.   0.   0.
  0.   0.   0.        X(I), I=1,...,N


f11jdfe.d

F11JDF Example Program Data
  7                   N
 16                   NNZ
 'CG'                 METHOD
 'P' 'N' 'I' 1        PRECON, SIGCMP, NORM, ITERM
 1.0D-6 100           TOL, MAXITN
 0.0D0 0.0D0          ANORM, SIGMAX
 0.0D0 10             SIGTOL, MAXITS
 1.0D0                OMEGA
  4.   1    1
  1.   2    1
  5.   2    2
  2.   3    3
  2.   4    2
  3.   4    4
 -1.   5    1
  1.   5    4
  4.   5    5
  1.   6    2
 -2.   6    5
  3.   6    6
  2.   7    1
 -1.   7    2
 -2.   7    3
  5.   7    7         A(I), IROW(I), ICOL(I), I=1,...,NNZ
 15.  18.  -8.   21.
 11.  10.   29.       B(I), I=1,...,N
  0.   0.   0.    0.
  0.   0.   0.        X(I), I=1,...,N


f11jefe.d

F11JEF Example Program Data
  7                   N
  16                  NNZ
 'CG' 'SSOR'          METHOD, PRECON
  1.1                 OMEGA
  1.0D-6 100          TOL, MAXITN
  4.   1    1
  1.   2    1
  5.   2    2
  2.   3    3
  2.   4    2
  3.   4    4
 -1.   5    1
  1.   5    4
  4.   5    5
  1.   6    2
 -2.   6    5
  3.   6    6
  2.   7    1
 -1.   7    2
 -2.   7    3
  5.   7    7         A(I), IROW(I), ICOL(I), I=1,...,NNZ
 15.  18.  -8.  21.
 11.  10.  29.        B(I), I=1,...,N
  0.   0.   0.   0.
  0.   0.   0.        X(I), I=1,...,N


f11jnfe.d

F11JNF Example Program Data
  7                   N
 16                   NNZ
  0 0.0               LFILL, DTOL
  'N' 0.0             MIC, DSCALE
  'M'                 PSTRAT
  ( 6., 0.)   1    1
  ( 1.,-2.)   2    1
  ( 9., 0.)   2    2
  ( 4., 0.)   3    3
  ( 2., 2.)   4    2
  ( 5., 0.)   4    4
  ( 0.,-1.)   5    1
  ( 1., 0.)   5    4
  ( 4., 0.)   5    5
  ( 1., 3.)   6    2
  ( 0.,-2.)   6    5
  ( 3., 0.)   6    6
  ( 2., 1.)   7    1
  (-1., 0.)   7    2
  (-3.,-1.)   7    3
  ( 5., 0.)   7    7  A(I), IROW(I), ICOL(I), I=1,...,NNZ


f11mdfe.d

F11MDF Example Program Data
  5   N
 1
 3
 5
 7
 9
 12   ICOLZP(I) I=1,..,N+1
 1
 3
 1
 5
 2
 3
 2
 4
 3
 4
 5    IROWIX(I) I=1,...,NNZ


f11mefe.d

F11MEF Example Program Data
  5                 N
 1
 3
 5
 7
 9
 12   ICOLZP(I) I=1,..,N+1
  2.   1
  4.   3
  1.   1
 -2.   5
  1.   2
  1.   3
 -1.   2
  1.   4
  1.   3
  2.   4
  3.   5    A(I), IROWIX(I) I=1,...,NNZ


f11mffe.d

F11MFF Example Program Data
  5 2  N, NRHS
 1
 3
 5
 7
 9
 12   ICOLZP(I) I=1,..,N+1
  2.   1
  4.   3
  1.   1
 -2.   5
  1.   2
  1.   3
 -1.   2
  1.   4
  1.   3
  2.   4
  3.   5    A(I), IROWIX(I) I=1,NNZ
 1.56 -.25 3.6 1.33 .52
 3.12 -.50 7.2 2.66 1.04 B(I,J) J=1,NRHS I=1,N


f11mgfe.d

F11MGF Example Program Data
  5  N
 1
 3
 5
 7
 9
 12   ICOLZP(I) I=1,..,N+1
  2.   1
  4.   3
  1.   1
 -2.   5
  1.   2
  1.   3
 -1.   2
  1.   4
  1.   3
  2.   4
  3.   5    A(I), IROWIX(I) I=1,NNZ


f11mhfe.d

F11MHF Example Program Data
  5 2  N, NRHS
 1
 3
 5
 7
 9
 12   ICOLZP(I) I=1,..,N+1
  2.   1
  4.   3
  1.   1
 -2.   5
  1.   2
  1.   3
 -1.   2
  1.   4
  1.   3
  2.   4
  3.   5    A(I), IROWIX(I) I=1,NNZ
 1.56 -.25 3.6 1.33 .52
 3.12 -.50 7.2 2.66 1.04 X(I,J) J=1,NRHS I=1,N


f11mkfe.d

F11MKF Example Program Data
  5 2                 N, M
 1
 3
 5
 7
 9
 12   ICOLZP(I) I=1,..,N+1
  2.   1
  4.   3
  1.   1
 -2.   5
  1.   2
  1.   3
 -1.   2
  1.   4
  1.   3
  2.   4
  3.   5    A(I), IROWIX(I) I=1,...,NNZ
 0.70 0.16 0.52  0.77 0.28
 1.40 0.32 1.04  1.54 0.56     matrix B


f11mlfe.d

F11MLF Example Program Data
  5  N
 1
 3
 5
 7
 9
 12   ICOLZP(I) I=1,..,N+1
  2.   1
  4.   3
  1.   1
 -2.   5
  1.   2
  1.   3
 -1.   2
  1.   4
  1.   3
  2.   4
  3.   5    A(I), IROWIX(I) I=1,NNZ


f11mmfe.d

F11MMF Example Program Data
  5  N
 1
 3
 5
 7
 9
 12   ICOLZP(I) I=1,..,N+1
  2.   1
  4.   3
  1.   1
 -2.   5
  1.   2
  1.   3
 -1.   2
  1.   4
  1.   3
  2.   4
  3.   5    A(I), IROWIX(I) I=1,NNZ


f11xafe.d

F11XAF Example Program Data
  5                   N
 11                   NNZ
  2.   1    1
  1.   1    2
  1.   2    3
 -1.   2    4
  4.   3    1
  1.   3    3
  1.   3    5
  1.   4    4
  2.   4    5
 -2.   5    2
  3.   5    5         A(I), IROW(I), ICOL(I), I=1,...,NNZ
 0.70 0.16 0.52
 0.77 0.28            X(I), I=1,...,N


f11xefe.d

F11XEF Example Program Data
  9                   N
 23                   NNZ
  4.   1    1
 -1.   2    1
  6.   2    2
  1.   3    2
  2.   3    3
  3.   4    4
  2.   5    1
  4.   5    5
  1.   6    3
  2.   6    4
  6.   6    6
 -4.   7    2
  1.   7    5
 -1.   7    6
  6.   7    7
 -1.   8    4
 -1.   8    6
  3.   8    8
  1.   9    1
  1.   9    5
 -1.   9    6
  1.   9    8
  4.   9    9         A(I), IROW(I), ICOL(I), I=1,...,NNZ
 0.70 0.16 0.52
 0.77 0.28 0.21
 0.93 0.20 0.90       X(I), I=1,...,N


f11xnfe.d

F11XNF Example Program Data
  5                      N
 11                      NNZ
  ( 2., 3.)   1    1
  ( 1.,-4.)   1    2
  ( 1., 0.)   2    3
  (-1.,-2.)   2    4
  ( 4., 1.)   3    1
  ( 0., 1.)   3    3
  ( 1., 3.)   3    5
  ( 0.,-1.)   4    4
  ( 2.,-6.)   4    5
  (-2., 0.)   5    2
  ( 3., 1.)   5    5     A(I), IROW(I), ICOL(I), I=1,...,NNZ
 ( 0.70, 0.21)
 ( 0.16,-0.43)
 ( 0.52, 0.97)
 ( 0.77, 0.00)
 ( 0.28,-0.64)           X(I), I=1,...,N


f11zafe.d

F11ZAF Example Program Data
  5                   N
  15                  NNZ
  4.   3    1
 -2.   5    2
  1.   4    4
 -2    4    2
 -3    5    5
  1.   1    2
  0.   1    5
  1.   3    5
 -1.   2    4
  6.   5    5
  2.   1    1
  2.   4    2
  1.   2    3
  1.   3    3
  2.   4    5         A(I), IROW(I), ICOL(I), I=1,...,NNZ


f11zbfe.d

F11ZBF Example Program Data
  4                   N
  9                   NNZ
  1.   3    2
  0.   2    1
  1.   3    2
  3.   4    4
  4.   1    1
  6.   2    2
  2.   3    3
  1.   3    2
  1.   3    2         A(I), IROW(I), ICOL(I), I=1,...,NNZ


f11znfe.d

F11ZNF Example Program Data
  5                     N
  15                    NNZ
  ( 4., 1.)   3    1
  (-2., 6.)   5    2
  ( 1.,-3.)   4    4
  (-2.,-1.)   4    2
  (-3., 0.)   5    5
  ( 1., 2.)   1    2
  ( 0., 0.)   1    5
  ( 1., 3.)   3    5
  (-1.,-1.)   2    4
  ( 6.,-3.)   5    5
  ( 2., 6.)   1    1
  ( 2., 1.)   4    2
  ( 1., 0.)   2    3
  ( 0.,-3.)   3    3
  ( 2., 2.)   4    5    A(I), IROW(I), ICOL(I), I=1,...,NNZ


f11zpfe.d

F11ZPF Example Program Data
  4                   N
  9                   NNZ
  (1., 2.)   3    2
  (0., 0.)   2    1
  (0., 3.)   3    2
  (3.,-5.)   4    4
  (4., 2.)   1    1
  (0., 3.)   2    2
  (2., 4.)   3    3
  (1.,-1.)   3    2
  (1., 3.)   3    2   A(I), IROW(I), ICOL(I), I=1,...,NNZ


f12aafe.d

F12AAF Example Program Data
 10 10 30 : Values for NX NEV and NCV


f12abfe.d

F12ABF Example Program Data
 10 4 20 10.0 1.0 0.0 : Values for NX NEV NCV RHO SIGMAR and SIGMAI


f12acfe.d

F12ACF Example Program Data
 10 4 20 10.0 : Values for NX NEV NCV RHO


f12adfe.d

F12ADF Example Program Data
 10 4 10 10.0 1.0 0.0 : Values for NX NEV NCV RHO SIGMAR and SIGMAI


f12aefe.d

F12AEF Example Program Data
 100 4 20 4.0D-1 6.0D-1 : Values for NX NEV NCV SIGMAR SIGMAI


f12agfe.d

F12AGF Example Program Data
 10 4 10 0.4 0.6 : Values for NX NEV NCV SIGMAR SIGMAI


f12anfe.d

F12ANF Example Program Data
 10 4 20 : Vaues for NX NEV and NCV


f12apfe.d

F12APF Example Program Data
 10 4 20 : Vaues for NX NEV and NCV


f12aqfe.d

F12AQF Example Program Data
 10 4 20 : Vaues for NX NEV and NCV


f12arfe.d

F12ARF Example Program Data
 10 4 20 : Vaues for NX NEV and NCV


f12asfe.d

F12ASF Example Program Data
 16 4 10 : Vaues for NX NEV and NCV


f12aufe.d

F12AUF Example Program Data
  10    4    10              : nx nev ncv
 ( 0.4, 0.6)                 : sigma


f12fafe.d

F12FAF Example Program Data
 10 4 10 : Values for NX NEV and NCV


f12fbfe.d

F12FBF Example Program Data
Example 1
 100 4 10 : Values for N NEV and NCV
Example 2
 500 100 4 10 : Values for M N NEV and NCV


f12fcfe.d

F12FCF Example Program Data
 100 4 10 : Values for N NEV and NCV


f12fdfe.d

F12FDF Example Program Data
 100 4 10 : Values for N NEV and NCV


f12fefe.d

F12FEF Example Program Data
 100 4 10 : Values for N NEV and NCV


f12fgfe.d

F12FGF Example Program Data
 10 4 10 : Values for NX NEV and NCV


f16dlfe.d

F16DLF Example Program Data
  5   1                                                 : n and incx
  1
  10
  11
  -2
  9                                                     : Vector x


f16dnfe.d

F16DNF Example Program Data
  5   1                                                 : n and incx
  1
  10
  11
  -2
  9                                                     : Vector x


f16dpfe.d

F16DPF Example Program Data
  5   1                                                 : n and incx
  1
  10
  11
  -2
  9                                                     : Vector x


f16dqfe.d

F16DQF Example Program Data
  5   1                                                 : n and incx
  1
  10
  11
  -2
  9                                                     : Vector x


f16drfe.d

F16DRF Example Program Data
  5   1                                                 : n and incx
  1
  10
  11
  -2
  9                                                     : Vector x


f16eafe.d

F16EAF Example Program Data

   5                                       : first dot product, n
   1    -1                                 : incx and incy
   0.3                                     : alpha
   1.0
   2.0
   3.0
   4.0
   5.0                                     : Vector x
  -5.0
  -4.0
   3.0
   2.0
   1.0                                     : Vector y

   4                                       : second dot product, n
  -2    -1                                 : incx and incy
  -7.0                                     : alpha
   0.4
   0.3
   0.2
   0.1                                     : Vector x
   0.4
   0.3
   0.2
   0.1                                     : Vector y


f16ecfe.d

F16ECF Example Program Data
   5                                   : n
  -1    -1                             : incx and incy
   3.0  -1.0                           : alpha and beta
  -6.0
   4.5
   3.7
   2.1
  -4.0                                 : Vector x
  -5.1
  -5.0
   6.4
  -2.4
  -3.0                                 : Vector y


f16ehfe.d

F16EHF Example Program Data
   5                                 : n
  -1     -1    -1                    : incx, incy and incw
   3.0   -1.0                        : alpha and beta
  -6.0
   4.5
   3.7
   2.1
  -4.0                               : Vector x
  -5.1
  -5.0
   6.4
  -2.4
  -3.0                               : Vector y


f16elfe.d

F16ELF Example Program Data
  5   1                                                 : n and incx
  1.1
 10.2
 11.5
 -2.7
  9.2                                                   : Vector x


f16gcfe.d

F16GCF Example Program Data
    3                                       : n
   -1           -1                          : incx and incy
  ( 3., 2.0)   ( 0.0,-1.0)                  : alpha and beta
  (-6.0, 1.2)
  ( 3.7, 4.5)
  (-4., 2.1)                                : Vector x
  (-5.1, 0.0)
  ( 6.4,-5.0)
  (-3.,-2.4)                                : Vector y


f16ghfe.d

F16GHF Example Program Data
    3                                     : n
   -1           -1           -1           : incx, incy and incw
  ( 3.0, 2.0)  ( 0.0,-1.0)                : alpha and beta
  (-6.0, 1.2)
  ( 3.7, 4.5)
  (-4.0, 2.1)                             : Vector x
  (-5.1, 0.0)
  ( 6.4,-5.0)
  (-3.0,-2.4)                             : Vector y


f16glfe.d

F16GLF Example Program Data
  3   1                                                 : n and incx
  ( 1.1, 10.2)
  ( 11.5,-2.7)
  ( 9.2, 0.)                                            : Vector x


f16jnfe.d

F16JNF Example Program Data
  5   1                                                 : n and incx
  1.0
  10.0
  11.0
  -2.0
  9.0                                                   : Vector x


f16jpfe.d

F16JPF Example Program Data
  5   1                                                 : n and incx
  1.0
  10.0
  11.0
  -2.0
  9.0                                                   : Vector x


f16jqfe.d

F16JQF Example Program Data
  5   1                                                 : n and incx
  1.0
  10.0
  11.0
  -2.0
  9.0                                                   : Vector x


f16jrfe.d

F16JRF Example Program Data
  5   1                                                 : n and incx
  1.0
  10.0
  11.0
  -2.0
  9.0                                                   : Vector x


f16jsfe.d

F16JSF Example Program Data
  3  1                                                  : n and incx
  (-4., 2.1)
  ( 3.7, 4.5)
  (-6., 1.2)                                            : Vector x


f16jtfe.d

F16JTF Example Program Data
  3  1                                                  : n and incx
  (-4., 2.1)
  ( 3.7, 4.5)
  (-6., 1.2)                                            : Vector x


f16rbfe.d

F16RBF Example Program Data
  6 4 2 1                                                : M, N, KL, KU
   1.0  1.0
   2.0  2.0  2.0
   3.0  3.0  3.0  3.0
        4.0  4.0  4.0
             5.0  5.0
                  6.0                                    : AB


f16ubfe.d

F16UBF Example Program Data
  6 4 2 1                                          : M, N, KL, KU
  ( 1.0, 1.0) ( 1.0, 2.0)
  ( 2.0, 1.0) ( 2.0, 2.0) ( 2.0, 3.0)
  ( 3.0, 1.0) ( 3.0, 2.0) ( 3.0, 3.0) ( 3.0, 4.0)
              ( 4.0, 2.0) ( 4.0, 3.0) ( 4.0, 4.0)
                          ( 5.0, 3.0) ( 5.0, 4.0)
                                      ( 6.0, 4.0)  : AB


g01adfe.d

G01ADF Example Program Data
14
     9.3       3      12      19      14      52      16      96
      18     121      20     115      22      86      24      70
      26      49      28      31      30      16      32       6
      34       8      36       7    39.7


g01affe.d

G01AFF Example Program Data
   2   3   0
    86    51    13
   130   115    41


g01ahfe.d

G01AHF Example Program Data
25 50 40 1
  0.35  0.10  0.95 -0.53  0.33
  0.30  0.39  0.26 -0.45  0.12
 -1.58  0.90  0.53 -0.58  0.54
 -0.09  0.79 -0.41  0.54  0.48
 -0.28 -0.71 -1.10 -0.41 -0.44
Plot of normal scores (Y) against standardised residuals (X)


g01alfe.d

G01ALF Example Program Data
 12
 12.0  9.0  2.0  5.0  6.0  8.0  2.0  7.0  3.0  1.0  11.0  10.0


g01amfe.d

G01AMF Example Program Data
11 3                                        : N and NQ
4.9 7.0 3.9 9.5 1.3 3.1 9.7 0.3 8.5 0.6 6.2 : The N data values
0.25 0.5 1.0                                : The NQ required quantiles


g01arfe.d

G01ARF Example Program Data
 30 0.0 72 0
  31.0 1.0 2.0 3.0 4.0 5.0 6.0 7.0 8.0 -9.0
   1.0 2.0 3.0 4.0 5.0 6.0 7.0 8.0 2.0  3.0
   4.0 5.0 6.0 7.0 3.0 4.0 5.0 6.0 4.0  5.0


g01asfe.d

G01ASF Example Program Data
5  55  21                                         : M, NSTEPX, NSTEPY
5   6   8   8   7                                 : N(i)
 -9.0 -7.3 -4.9 -2.4 -0.6
 -5.6 12.0 -9.0 -3.9 -2.4 -7.3
 -9.0 12.0 -6.0 -3.0  0.0  3.0  6.0  9.0
 12.0 10.0 10.0  8.0  6.0  4.0  4.0 -9.0
 -5.0  8.0  1.5 -3.2 -3.2  6.2  6.2               :X(i,j)


g01bjfe.d

G01BJF Example Program Data
   4  0.50    2   : N, P, K
  19  0.44   13
 100  0.75   67
2000  0.33  700


g01bkfe.d

G01BKF Example Program Data
  0.75     3     : RLAMDA, K
  9.20    12
 34.00    25
175.00   175


g01blfe.d

G01BLF Example Program Data
  10   2   5   1    : N, L, M, K
  40  10   3   2
 155  35 122  22
1000 444 500 220


g01dhfe.d

G01DHF Example Program Data
Savage Average 5  :: SCORES,TIES,N
2 0 2 2 0         :: End of X


g01eafe.d

G01EAF Example Program Data
 'L'  1.96 : TAIL X
 'U'  1.96
 'C'  1.96
 'S'  1.96


g01ebfe.d

G01EBF Example Program Data
'L' 0.85  20.0 : TAIL T DF
'S' 0.85  20.0
'C' 0.85  20.0
'U' 0.85  20.0


g01ecfe.d

G01ECF Example Program Data
'L'  8.26   20.0 : TAIL X DF
'L'  6.2     7.5
'L' 55.76   45.0


g01edfe.d

G01EDF Example Program Data
'L'  5.5   1.5   25.5 : TAIL F DF1 DF2
'L' 39.9   1.0    1.0
'L' 2.5   20.25   1.0


g01eefe.d

G01EEF Example Program Data
 0.25  1.0  2.0
 0.75  1.5  1.5
 0.5   2.0  1.0


g01effe.d

G01EFF Example Program Data
'L' 15.5   4.0   2.0 :TAIL G A B
'L'  0.5   4.0   1.0
'L' 10.0   1.0   2.0
'L'  5.0   2.0   2.0


g01emfe.d

G01EMF Example Program Data
4.6543  10.0   5
2.8099  60.0  12
4.2636   5.0   4


g01epfe.d

G01EPF Example Program Data
 10 2 0.9238


g01erfe.d

G01ERF Example Program Data
 7.0  0.0
 2.8  2.4
 1.0  1.0
-1.4  1.3


g01etfe.d

G01ETF Example Program Data
 0.5  : Value of X


g01eufe.d

G01EUF Example Program Data
 0.1  2.5  0.7 : Values of X, RKAPPA and BETA2


g01eyfe.d

G01EYF Example Program Data
10  0.323
10  0.369
10  0.409
10  0.457
10  0.489
400 0.0535
400 0.061
400 0.068
400 0.076
400 0.0815


g01ezfe.d

G01EZF Example Program Data
  5   10   0.5
 10   10   0.5
 20   10   0.5
 20   15   0.4833
400  200   0.1412
200   20   0.2861
1000  20   0.2113
200   50   0.1796
 15  200   0.18
100  100   0.18


g01fafe.d

G01FAF Example Program Data
 'L' 0.975
 'U' 0.025
 'C' 0.95
 'S' 0.05


g01fbfe.d

G01FBF Example Program Data
0.0100  20.0  'S'         :P DF TAIL
0.01     7.5  'L'         :P DF TAIL
0.99    45.0  'C'         :P DF TAIL


g01fcfe.d

G01FCF Example Program Data
0.0100 20.0                 :P DF
0.4279 7.5                  :P DF
0.8694 45.0                 :P DF


g01fdfe.d

G01FDF Example Program Data
0.9837  10.0   25.5          :P DF1 DF2
0.9000  1.0    1.0           :P DF1 DF2
0.5342  20.25  1.0           :P DF1 DF2


g01fefe.d

G01FEF Example Program Data
0.5000  1.0  2.0         :P A B
0.9900  1.5  1.5         :P A B
0.2500 20.0 10.0         :P A B


g01fffe.d

G01FFF Example Program Data
 0.0100   1.0 20.0         :P A B
 0.4279   7.5  0.1         :P A B
 0.8694  45.0 10.0         :P A B


g01fmfe.d

G01FMF Example Program Data
0.95 10.0  5
0.3  60.0 12
0.9   5.0  4


g01ftfe.d

G01FTF Example Program Data
 0.5  : Value of X


g01gbfe.d

G01GBF Example Program Data
 -1.528  20.0  2.0           :T DF DELTA
 -0.188   7.5  1.0           :T DF DELTA
  1.138  45.0  0.0           :T DF DELTA


g01gcfe.d

G01GCF Example Program Data
  8.26   20.0   3.5            :X DF RLAMDA
  6.2     7.5   2.0            :X DF RLAMDA
 55.76   45.0   1.0            :X DF RLAMDA


g01gdfe.d

G01GDF Example Program Data
  5.5   1.5    25.5   3.0          :F DF1 DF2 RLAMDA
 39.9   1.0     1.0   2.0          :F DF1 DF2 RLAMDA
  2.5  20.25    1.0   0.0          :F DF1 DF2 RLAMDA


g01gefe.d

G01GEF Example Program Data
 0.25  1.0  2.0  1.0         :X A B RLAMDA
 0.75  1.5  1.5  0.5         :X A B RLAMDA
 0.5   2.0  1.0  0.0         :X A B RLAMDA


g01hafe.d

G01HAF Example Program Data
  1.7  23.1   0.0         :X Y RHO
  0.0   0.0   0.1         :X Y RHO
  3.3  11.1   0.54        :X Y RHO
  9.1   9.1   0.17        :X Y RHO


g01hbfe.d

G01HBF Example Program Data
 4  0.00001 'c'
 0.0  0.0  0.0  0.0
 1.0  0.9  0.9  0.9
 0.9  1.0  0.9  0.9
 0.9  0.9  1.0  0.9
 0.9  0.9  0.9  1.0
-2.0 -2.0 -2.0 -2.0
 2.0  2.0  2.0  2.0


g01hcfe.d

G01HCF Example Program Data
L 8 0.6 4.0 0.8                 :LOWER_TAIL DF RHO B(1) B(2)
C 12 -0.2 -40.0 2.0 0.0 4.0     :CENTRAL DF RHO A(1) B(1) A(2) B(2)
U 2 0.3 -2.0 8.0                :UPPER_TAIL DF RHO A(1) A(2)


g01hdfe.d

G01HDF Example Program Data
5 1 : n iscov
Example 1
10.0  : nu
U U U U U : tails
-1.0e-1 -1.0e-1 -1.0e-1 -1.0e-1 -1.0e-1 : lower bounds
 888  888  888  888  888 : upper bounds
 0.0  0.0  0.0  0.0  0.0 : delta
1.0   0.75  0.75  0.75  0.75
0.75  1.0   0.75  0.75  0.75
0.75  0.75  1.0   0.75  0.75
0.75  0.75  0.75  1.0   0.75
0.75  0.75  0.75  0.75  1.0  : correlation matrix
Example 2
3.0  : nu
L L L L L : tails
 888  888  888  888  888 : lower bounds
-1.0e-1 -1.0e-1 -1.0e-1 -1.0e-1 -1.0e-1 : upper bounds
 1.0  2.0  3.0  3.0  3.0 : delta
1.0   0.75  0.75  0.75  0.75
0.75  1.0   0.75  0.75  0.75
0.75  0.75  1.0   0.75  0.75
0.75  0.75  0.75  1.0   0.75
0.75  0.75  0.75  0.75  1.0  : correlation matrix


g01jcfe.d

G01JCF Example Program Data
 3    20.0                      :N  C
 6.0   3.0  1.0                 :A(I), I=1,N
 1     1    1                   :MULT(I), I=1,N
 0.0   0.0  0.0                 :RLAMDA(I), I=1,N
 2    10.0                      :N  C
 7.0   3.0                      :A(I), I=1,N
 1     1                        :MULT(I), I=1,N
 6.0   2.0                      :RLAMDA(I), I=1,N


g01jdfe.d

G01JDF Example Program Data
10 'P' 1.0 0.0
 -9.0 -7.0 -5.0 -3.0 -1.0 2.0 4.0 6.0 8.0 10.0


g01kafe.d

G01KAF Example Program Data
1.0E0  0.0E0 1.0E0
4.0E0  2.0E0 1.0E0
1.0E-1 0.0E0 1.0E-2
1.0E0  0.0E0 1.0E1                             : X, XMEAN, XSTD


g01kffe.d

G01KFF Example Program Data
1.0E-1 3.0E0 2.0E0
3.0E0 1.0E1 1.1E1
6.0E0 5.0E0 1.0E0
4.0E0 1.0E1 1.0E-1
9.0E0 9.0E0 5.0E-1
1.6E1 3.5E0 2.5E0                                           : X, A, B


g01kkfe.d

G01KKF Example Program Data
0                       :: ILOG
5                       :: LX
0.1 3.0 6.0 4.0 9.0     :: X
5                       :: LA
3.0 10.0 5.0 10.0 9.0   :: A
5                       :: LB
2.0 11.0 1.0 0.1 0.5    :: B


g01kqfe.d

G01KQF Example Program Data
0                       :: ILOG
4                       :: LX
1.0 4.0 0.1 1.0         :: X
4                       :: LXMU
0.0 2.0 0.0 0.0         :: XMU
4                       :: LXSTD
1.0 1.0 0.01 10.0       :: XSTD


g01lbfe.d

G01LBF Example Program Data
  2  4  1  0                  : K,N,IULD,ILOG
  0.10   0.20   0.30   0.40   : End XMU
  4.16
 -3.12   5.03
  0.56  -0.83   0.76
 -0.10   1.18   0.34   1.18   : End SIG
  1.00   1.00   1.00   1.00
  1.00   2.00   3.00   4.00   : End of X


g01mbfe.d

G01MBF Example Program Data
0.0 0.0 1.0
-2.0 1.0 2.5
10.3 9.0 1.6


g01mtfe.d

G01MTF Example Program Data
 0.5  : Value of X


g01mufe.d

G01MUF Example Program Data
 2.5  0.4  0.1 : Values of X, RKAPPA and BETA2


g01nafe.d

G01NAF Example Program Data
0.8  1.0   : BETA, CON
10   4     : N, L


g01nbfe.d

G01NBF Example Program Data
0.8 1.0     : Beta Y0
10  1   3   : N  L1  L1


g01ptfe.d

G01PTF Example Program Data
 0.5  : Value of X


g01qtfe.d

G01QTF Example Program Data
 0.5  : Value of X


g01rtfe.d

G01RTF Example Program Data
 0.5  : Value of X


g01safe.d

G01SAF Example Program Data
4                       :: LTAIL
'L' 'U' 'C' 'S'         :: TAIL
1                       :: LX
1.96                    :: X
1                       :: LXMU
0.0                     :: XMU
1                       :: LXSTD
1.0                     :: XSTD


g01sbfe.d

G01SBF Example Program Data
4                       :: LTAIL
'L' 'S' 'C' 'U'         :: TAIL
1                       :: LT
0.85                    :: T
1                       :: LDF
20.0                    :: DF


g01scfe.d

G01SCF Example Program Data
1                       :: LTAIL
'L'                     :: TAIL
3                       :: LX
8.26 6.2 55.76          :: X
3                       :: LDF
20.0 7.5 45.0           :: DF


g01sdfe.d

G01SDF Example Program Data
1                       :: LTAIL
'L'                     :: TAIL
3                       :: LF1
5.5 39.9 2.5            :: F
3                       :: LDF1
1.5 1.0 20.25           :: DF1
3                       :: LDF2
25.5 1.0 1.0            :: DF2


g01sefe.d

G01SEF Example Program Data
1                       :: LTAIL
'L'                     :: TAIL
3                       :: LBETA
0.26 0.75 0.5           :: BETA
3                       :: LA
1.0 1.5 2.0             :: A
3                       :: LB
2.0 1.5 1.0             :: B


g01sffe.d

G01SFF Example Program Data
1                       :: LTAIL
'L'                     :: TAIL
4                       :: LG
15.5 0.5 10.0 5.0       :: G
4                       :: LA
 4.0 4.0 1.0 2.0        :: A
4                       :: LB
2.0 1.0 2.0 2.0         :: B


g01sjfe.d

G01SJF Example Program Data
4                       :: LN
4 19 100 2000           :: N
4                       :: LP
0.500 0.440 0.750 0.330 :: P
4                       :: LK
2 13 67 700             :: K


g01skfe.d

G01SKF Example Program Data
4                       :: LL
0.75 9.20 34.0 175.0    :: L
4                       :: LK
3 12 25 175             :: K


g01slfe.d

G01SLF Example Program Data
4                       :: LN
10 40 155 1000          :: N
4                       :: LL
2 10 35 444             :: L
4                       :: LM
5 3 122 500             :: M
4                       :: LK
1 2 22 220              :: K


g01tafe.d

G01TAF Example Program Data
4                       :: LTAIL
'L' 'U' 'C' 'S'         :: TAIL
4                       :: LP
0.975 0.025 0.95 0.05   :: P
1                       :: LXMU
0.0                     :: XMU
1                       :: LXSTD
1.0                     :: XSTD


g01tbfe.d

G01TBF Example Program Data
3                       :: LTAIL
'S' 'L' 'C'             :: TAIL
3                       :: LP
0.01 0.01 0.99          :: P
3                       :: LDF
20.0 7.5 45.0           :: DF


g01tcfe.d

G01TCF Example Program Data
1                       :: LTAIL
'L'                     :: TAIL
3                       :: LP
0.01 0.428 0.869        :: P
3                       :: LDF
20.0 7.5 45.0           :: DF


g01tdfe.d

G01TDF Example Program Data
1                       :: LTAIL
'L'                     :: TAIL
3                       :: LP
0.984 0.9 0.534         :: P
3                       :: LDF1
10.0 1.0 20.25          :: DF1
3                       :: LDF2
25.5 1.0 1.0            :: DF2


g01tefe.d

G01TEF Example Program Data
0.0                     :: TOL
1                       :: LTAIL
'L'                     :: TAIL
3                       :: LP
0.5 0.99 0.25           :: P
3                       :: LA
1.0 1.5 20.0            :: A
3                       :: LB
2.0 1.5 10.0            :: B


g01tffe.d

G01TFF Example Program Data
0.0                     :: TOL
1                       :: LTAIL
'L'                     :: TAIL
3                       :: LP
0.01 0.428 0.869        :: P
3                       :: LA
1.0 7.500 45.0          :: A
3                       :: LB
20.0 0.1 10.0           :: B


g01wafe.d

G01WAF Example Program Data
2 15                                     :: IWT,M
FALSE                                    :: If TRUE sd's are calculated
-3.0 -6.0 -5.0 3.0 21.0 46.0 67.0
74.0 67.0 46.0 21.0 3.0 -5.0 -6.0 -3.0   :: WT
5                                        :: NB
 -2170.0 -1770.0 -1660.0 -1360.0 -1100.0 :: End of X for first block
10                                       :: NB
  -950.0  -640.0  -370.0  -140.0  -250.0
  -510.0  -620.0  -730.0  -880.0 -1130.0 :: End of X for second block
15                                       :: NB
 -1200.0  -830.0  -330.0  -190.0   210.0
   170.0   440.0   440.0   780.0   880.0
  1220.0  1260.0  1140.0   850.0   640.0 :: End of X for third block


g02aafe.d

G02AAF Example Program Data
 4                         :: N
 2.0   -1.0    0.0    0.0
-1.0    2.0   -1.0    0.0
 0.0   -1.0    2.0   -1.0
 0.0    0.0   -1.0    2.0  :: End of G


g02abfe.d

G02ABF Example Program Data
 4 'B' 0.02                  :: N, OPT, ALPHA
   2.0   -1.0    0.0    0.0
  -1.0    2.0   -1.0    0.0
   0.0   -1.0    2.0   -1.0
   0.0    0.0   -1.0    2.0  :: End of G
 100.0   20.0   20.0   20.0  :: W


g02aefe.d

G02AEF Example Program Data
 4                         :: N
 2.0   -1.0    0.0    0.0
-1.0    2.0   -1.0    0.0
 0.0   -1.0    2.0   -1.0
 0.0    0.0   -1.0    2.0  :: End of G


g02ajfe.d

G02AJF Example Program Data
 4  0.04                     :: N, ALPHA
   2.0   -1.0    0.0    0.0
  -1.0    2.0   -1.0    0.0
   0.0   -1.0    2.0   -1.0
   0.0    0.0   -1.0    2.0  :: End of G
   0.0   10.0    0.0    0.0
  10.0    0.0    1.5    1.5
   0.0    1.5    0.0    0.0
   0.0    1.5    0.0    0.0  :: End of H


g02bafe.d

G02BAF Example Program Data
5  3                       :: N, M
 2.0    3.0    3.0
 4.0    6.0    4.0
 9.0    9.0    0.0
 0.0   12.0    2.0
12.0   -1.0    5.0         :: End of X


g02bbfe.d

G02BBF Example Program Data
5  3                       :: N, M
 2.0    3.0    3.0
 4.0    6.0    4.0
 9.0    9.0    0.0
 0.0   12.0    2.0
12.0   -1.0    5.0         :: End of X
  1      0      1          :: MISS
 0.0    0.0    0.0         :: XMISS


g02bcfe.d

G02BCF Example Program Data
5  3                       :: N, M
 2.0    3.0    3.0
 4.0    6.0    4.0
 9.0    9.0    0.0
 0.0   12.0    2.0
12.0   -1.0    5.0         :: End of X
  1      1      1          :: MISS
 0.0   -1.0    0.0         :: XMISS


g02bdfe.d

G02BDF Example Program Data
5  3                       :: N, M
 2.0    3.0    3.0
 4.0    6.0    4.0
 9.0    9.0    0.0
 0.0   12.0    2.0
12.0   -1.0    5.0         :: End of X


g02befe.d

G02BEF Example Program Data
5  3                       :: N, M
 2.0    3.0    3.0
 4.0    6.0    4.0
 9.0    9.0    0.0
 0.0   12.0    2.0
12.0   -1.0    5.0         :: End of X
  1      0      1          :: MISS
 0.0    0.0    0.0         :: XMISS


g02bffe.d

G02BFF Example Program Data
5  3                       :: N, M
 2.0    3.0    3.0
 4.0    6.0    4.0
 9.0    9.0    0.0
 0.0   12.0    2.0
12.0   -1.0    5.0         :: End of X
  1      1      1          :: MISS
 0.0   -1.0    0.0         :: XMISS


g02bgfe.d

G02BGF Example Program Data
5  4  3                    :: N, M, NVARS
 3.0    3.0    1.0    2.0
 6.0    4.0   -1.0    4.0
 9.0    0.0    5.0    9.0
12.0    2.0    0.0    0.0
-1.0    5.0    4.0   12.0  :: End of X
4  1  2                    :: KVARS


g02bhfe.d

G02BHF Example Program Data
5  4  3  0                 :: N, M, NVARS, MISTYP
 3.0    3.0    1.0    2.0
 6.0    4.0   -1.0    4.0
 9.0    0.0    5.0    9.0
12.0    2.0    0.0    0.0
-1.0    5.0    4.0   12.0  :: End of X
  0      1      0      1   :: MISS
 0.0    0.0    0.0    0.0  :: XMISS
4  1  2                    :: KVAR


g02bjfe.d

G02BJF Example Program Data
5  4  3                    :: N, M, NVARS
 3.0    3.0    1.0    2.0
 6.0    4.0   -1.0    4.0
 9.0    0.0    5.0    9.0
12.0    2.0    0.0    0.0
-1.0    5.0    4.0   12.0  :: End of X
  1      1      0      1   :: MISS
-1.0    0.0    0.0    0.0  :: XMISS
4  1  2                    :: KVAR


g02bkfe.d

G02BKF Example Program Data
5  4  3                    :: N, M, NVARS
 3.0    3.0    1.0    2.0
 6.0    4.0   -1.0    4.0
 9.0    0.0    5.0    9.0
12.0    2.0    0.0    0.0
-1.0    5.0    4.0   12.0  :: End of X
4  1  2                    :: KVAR


g02blfe.d

G02BLF Example Program Data
5  4  3  0                 :: N, M, NVARS, MISTYP
 3.0    3.0    1.0    2.0
 6.0    4.0   -1.0    4.0
 9.0    0.0    5.0    9.0
12.0    2.0    0.0    0.0
-1.0    5.0    4.0   12.0  :: End of X
  0      1      0      1   :: MISS
 0.0    0.0    0.0    0.0  :: XMISS
4  1  2                    :: KVAR


g02bmfe.d

G02BMF Example Program Data
5  4  3                    :: N, M, NVARS
 3.0    3.0    1.0    2.0
 6.0    4.0   -1.0    4.0
 9.0    0.0    5.0    9.0
12.0    2.0    0.0    0.0
-1.0    5.0    4.0   12.0  :: End of X
  1      1      0      1   :: MISS
-1.0    0.0    0.0    0.0  :: XMISS
4  1  2                    :: KVAR


g02bnfe.d

G02BNF Example Program Data
9  3  0                    :: N, M, ITYPE
 1.70   1.00   0.50
 2.80   4.00   3.00
 0.60   6.00   2.50
 1.80   9.00   6.00
 0.99   4.00   2.50
 1.40   2.00   5.50
 1.80   9.00   7.50
 2.50   7.00   0.00
 0.99   5.00   3.00        :: End of X


g02bpfe.d

G02BPF Example Program Data
9  3  0                    :: N, M, ITYPE
 1.70   1.00   0.50
 2.80   4.00   3.00
 0.60   6.00   2.50
 1.80   9.00   6.00
 0.99   4.00   2.50
 1.40   2.00   5.50
 1.80   9.00   7.50
 2.50   7.00   0.00
 0.99   5.00   3.00        :: End of X
 1      0       1          :: MISS
0.99   0.0     0.0         :: XMISS


g02bqfe.d

G02BQF Example Program Data
9  3  0                    :: N, M, ITYPE
 1.70   1.00   0.50
 2.80   4.00   3.00
 0.60   6.00   2.50
 1.80   9.00   6.00
 0.99   4.00   2.50
 1.40   2.00   5.50
 1.80   9.00   7.50
 2.50   7.00   0.00
 0.99   5.00   3.00        :: End of X


g02brfe.d

G02BRF Example Program Data
9  3  0                   :: N, M, ITYPE
 1.70   1.00   0.50
 2.80   4.00   3.00
 0.60   6.00   2.50
 1.80   9.00   6.00
 0.99   4.00   2.50
 1.40   2.00   5.50
 1.80   9.00   7.50
 2.50   7.00   0.00
 0.99   5.00   3.00        :: End of X
  1      0      1          :: MISS
 0.99   0.00   0.00        :: XMISS


g02bsfe.d

G02BSF Example Program Data
9  3  0                    :: N, M, ITYPE
 1.70   1.00   0.50
 2.80   4.00   3.00
 0.60   6.00   2.50
 1.80   9.00   6.00
 0.99   4.00   2.50
 1.40   2.00   5.50
 1.80   9.00   7.50
 2.50   7.00   0.00
 0.99   5.00   3.00        :: End of X
  1      1      1          :: MISS
 0.99   9.00   0.00        :: XMISS


g02btfe.d

G02BTF Example Program Data
  'M'  3  3 3
  0.1300   9.1231   3.7011   4.5230
  1.3070   0.9310   0.0900   0.8870
  0.3700   0.0009   0.0099   0.0999


g02bufe.d

G02BUF Example Program Data
 'M'      'W'     3     3
  0.1300   1.3070   0.3700
  9.1231   3.7011   4.5230
  0.9310   0.0900   0.8870
  0.0009   0.0099   0.0999


g02bwfe.d

G02BWF Example Program Data
 'M'     'W'      3     3
  0.1300   1.3070   0.3700
  9.1231   3.7011   4.5230
  0.9310   0.0900   0.8870
  0.0009   0.0099   0.0999


g02byfe.d

G02BYF Example Program Data
'u' 15 3               :: WEIGHT,N,M (G02BXF)
112 0.30 0.09
140 0.49 0.16
143 0.61 0.22
120 0.49 0.14
196 2.64 0.75
294 3.45 0.86
513 4.46 1.34
518 4.46 1.34
430 1.22 0.47
274 1.22 0.47
255 0.32 0.22
236 0.29 0.23
256 0.50 0.26
222 0.32 0.16
213 0.32 0.16          :: End of X (G02BXF)
 2  1                  :: NY,NX
-1 -1  1               :: ISZ


g02bzfe.d

G02BZF Example Program Data
M  5                                  :: MEAN,M
4 U                                   :: N,WEIGHT (1st block)
-1.10  4.06  -0.95  8.53 10.41
 1.63 -3.22  -1.15 -1.30  3.78
-2.23 -8.19  -3.50  4.31 -1.11
 0.92  0.33  -1.60  5.80 -1.15        :: End of X for 1st block
5 W                                   :: N,WEIGHT (2nd block)
 2.12  5.00 -11.69 -1.22  2.86 2.00
 4.82 -7.23  -4.67  0.83  3.46 0.89
-0.51 -1.12  -1.76  1.45  0.26 0.32
-4.32  4.89   1.34 -1.12 -2.49 4.19
 0.02 -0.74   0.94 -0.99 -2.61 4.33   :: End of X,WT for 2nd block
3 U                                   :: N,WEIGHT (3rd block)
 1.37  0.00  -0.53 -7.98  3.32
 4.15 -2.81  -4.09 -7.96 -2.13
13.09 -1.43   5.16 -1.83  1.58        :: End of X for 3rd block


g02cafe.d

G02CAF Example Program Data
8               :: N
1.0       20.0
0.0       15.5
4.0       28.3
7.5       45.0
2.5       24.5
0.0       10.0
10.0      99.0
5.0       31.2  :: End of X,Y


g02cbfe.d

G02CBF Example Program Data
8                 :: N
1.0       20.0
0.0       15.5
4.0       28.3
7.5       45.0
2.5       24.5
0.0       10.0
10.0      99.0
5.0       31.2    :: End of X,Y


g02ccfe.d

G02CCF Example Program Data
8              :: N
1.0       20.0
0.0       15.5
4.0       28.3
7.5       45.0
2.5       24.5
0.0       10.0
10.0      99.0
5.0       31.2 :: End of X, Y
0.0       99.0 :: XMISS, YMISS


g02cdfe.d

G02CDF Example Program Data
8              :: N
1.0       20.0
0.0       15.5
4.0       28.3
7.5       45.0
2.5       24.5
0.0       10.0
10.0      99.0
5.0       31.2  :: End of X, Y
0.0       99.0  :: XMISS, YMISS


g02cffe.d

G02CFF Example Program Data
3                              :: N
  5.4000     5.8000     2.8000 :: XBAR
  4.9800     5.0695     1.9240 :: STD
 99.2000   -57.6000     6.4000
-57.6000   102.8000   -29.2000
  6.4000   -29.2000    14.8000 :: End of SSP
  1.0000    -0.5704     0.1670
 -0.5704     1.0000    -0.7486
  0.1670    -0.7486     1.0000 :: End of R
1  3  2                        :: KORDER


g02cgfe.d

G02CGF Example Program Data
5 2                               :: N, K
  5.4000      5.8000      2.8000  :: XBAR
 99.2000    -57.6000      6.4000
-57.6000    102.8000    -29.2000
  6.4000    -29.2000     14.8000  :: End of SSP
  1.0000     -0.5704      0.1670
 -0.5704      1.0000     -0.7486
  0.1670     -0.7486      1.0000  :: End of R


g02chfe.d

G02CHF Example Program Data
5  2                           :: N, K
245.0000    99.0000    82.0000
 99.0000   271.0000    52.0000
 82.0000    52.0000    54.0000 :: End of SSPZ
  1.0000     0.3842     0.7129
  0.3842     1.0000     0.4299
  0.7129     0.4299     1.0000 :: End of RZ


g02dcfe.d

G02DCF Example Program Data
 12 4  'U' 'Z'                :: N, M, MEAN, WEIGHT
1.0 0.0 0.0 0.0 33.63
0.0 0.0 0.0 1.0 39.62
0.0 1.0 0.0 0.0 38.18
0.0 0.0 1.0 0.0 41.46
0.0 0.0 0.0 1.0 38.02
0.0 1.0 0.0 0.0 35.83
0.0 0.0 0.0 1.0 35.99
1.0 0.0 0.0 0.0 36.58
0.0 0.0 1.0 0.0 42.92
1.0 0.0 0.0 0.0 37.80
0.0 0.0 1.0 0.0 40.43
1.0 1.0 1.0 1.0 37.89        :: End of X, Y
 1   1   1   1               :: ISX
'D'                          :: UPDATE (delete observation)
1.0 1.0 1.0 1.0 37.89        :: X and Y for observation to be deleted
'A'                          :: UPDATE (add observation)
0.0 1.0 0.0 0.0 37.89        :: X and Y for observation to be added


g02defe.d

G02DEF Example Program Data
 12 5 'U'                     :: N, M (max. number of variables), WEIGHT
4.32 5.21 6.49 7.10 7.94 8.53
8.84 9.02 9.27 9.43 9.68 9.83 :: End of Y
1.0  1.0  1.0  1.0  1.0  1.0
1.0  1.0  1.0  1.0  1.0  1.0  :: End of X0 (intercept)
1.0  1.5  2.0  2.5  3.0  3.5
4.0  4.5  5.0  5.5  6.0  6.5  :: End of X1
0.0  0.0  0.0  0.0  0.0  0.0
1.0  1.0  1.0  1.0  1.0  1.0  :: End of X2
0.0  0.0  0.0  0.0  0.0  0.0
4.0  4.5  5.0  5.5  6.0  6.5  :: End of X3
1.4  2.2  4.5  6.1  7.1  7.7
8.3  8.6  8.8  9.0  9.3  9.2  :: End of X4


g02dffe.d

G02DFF Example Program Data
 12 4 'U' 'M'        :: N, M, WEIGHT, MEAN
1.0 1.4 0.0 0.0 4.32
1.5 2.2 0.0 0.0 5.21
2.0 4.5 0.0 0.0 6.49
2.5 6.1 0.0 0.0 7.10
3.0 7.1 0.0 0.0 7.94
3.5 7.7 0.0 0.0 8.53
4.0 8.3 1.0 4.0 8.84
4.5 8.6 1.0 4.5 9.02
5.0 8.8 1.0 5.0 9.27
5.5 9.0 1.0 5.5 9.43
6.0 9.3 1.0 6.0 9.68
6.5 9.2 1.0 6.5 9.83 :: End of X, Y
2                    :: Start of variables to drop
4


g02dgfe.d

G02DGF Example Program Data
 12 4 'U' 'M'                  :: N, M, MEAN, WEIGHT
1.0 0.0 0.0 0.0 33.63
0.0 0.0 0.0 1.0 39.62
0.0 1.0 0.0 0.0 38.18
0.0 0.0 1.0 0.0 41.46
0.0 0.0 0.0 1.0 38.02
0.0 1.0 0.0 0.0 35.83
0.0 0.0 0.0 1.0 35.99
1.0 0.0 0.0 0.0 36.58
0.0 0.0 1.0 0.0 42.92
1.0 0.0 0.0 0.0 37.80
0.0 0.0 1.0 0.0 40.43
0.0 1.0 0.0 0.0 37.89          :: End of X, OY (original dependent variable)
 1   1   1   1                 :: ISX
63.0 69.0 68.0 71.0 68.0 65.0
65.0 66.0 72.0 67.0 70.0 67.0  :: Y (new dependent variable)


g02dnfe.d

G02DNF Example Program Data
 12 4 'U' 'M'              :: N, M, WEIGHT, MEAN
1.0 0.0 0.0 0.0 33.63
0.0 0.0 0.0 1.0 39.62
0.0 1.0 0.0 0.0 38.18
0.0 0.0 1.0 0.0 41.46
0.0 0.0 0.0 1.0 38.02
0.0 1.0 0.0 0.0 35.83
0.0 0.0 0.0 1.0 35.99
1.0 0.0 0.0 0.0 36.58
0.0 0.0 1.0 0.0 42.92
1.0 0.0 0.0 0.0 37.80
0.0 0.0 1.0 0.0 40.43
0.0 1.0 0.0 0.0 37.89      :: End of X, Y
 1   1   1   1             :: ISX
 1.0 1.0  0.0 0.0 0.0      :: Estimable function 1
 0.0 1.0 -1.0 0.0 0.0      :: Estimable function 2
 0.0 1.0  0.0 0.0 0.0      :: Estimable function 3


g02fcfe.d

G02FCF Example Program Data
10  2                                                  :: N, IP
 3.735719   0.912755   0.683626   0.416693   1.990200
-0.444816  -1.283088  -3.666035  -0.426357  -1.918697  :: End of RES


g02gafe.d

G02GAF Example Program Data
'R' 'M' 'N' 'U' 5 1  0.0 :: LINK,MEAN,OFFSET,WEIGHT,N,M,S
1.0 25.0
2.0 10.0
3.0  6.0
4.0  4.0
5.0  3.0                 :: End of X,Y
 1                       :: ISX
0  1.0E-6  5.0E-5  10    :: IPRINT,EPS,TOL,MAXIT


g02gbfe.d

G02GBF Example Program Data
'G' 'M' 'N' 'U' 3 1    :: LINK,OFFSET,WEIGHT,N,M
 1.0 19. 516.
 0.0 29. 560.
-1.0 24. 293.          :: End of X,Y,T
  1                    :: ISX
0  1.0E-6  5.0E-5  10  :: IPRINT,EPS,TOL,MAXIT


g02gdfe.d

G02GDF Example Program Data
'R' 'M' 'N' 'U' 10 1 0.0 :: LINK,MEAN,OFFSET,WEIGHT,N,M,S
1.0  1.0
1.0  0.3
1.0 10.5
1.0  9.7
1.0 10.9
0.0 0.62
0.0 0.12
0.0 0.09
0.0 0.50
0.0 2.14                 :: End of X,Y
 1                       :: ISX
0  1.0E-6  5.0E-5  0     :: IPRINT,EPS,TOL,MAXIT


g02gpfe.d

G02GPF Example Program Data
Training Data
'R' 'M' 'N' 'U' 5 1  0.0   :: LINK,MEAN,OFFSET,WEIGHT,N,M,S
1.0 25.0
2.0 10.0
3.0  6.0
4.0  4.0
5.0  3.0                   :: End of X,Y
1                          :: ISX
0  1.0E-6  5.0E-5  0       :: IPRINT,EPS,TOL,MAXIT
Prediction Data
2 .TRUE. 'N' 'U'           :: N,VFOBS,OFFSET,WEIGHT
32.0
18.0                       :: End of X


g02hafe.d

G02HAF Example Program Data
 8  3                       : N,M
 1. -1. -1. 2.1
 1. -1.  1. 3.6
 1.  1. -1. 4.5
 1.  1.  1. 6.1
 1. -2.  0. 1.3
 1.  0. -2. 1.9
 1.  2.  0. 6.7
 1.  0.  2. 5.5             : End of X1 X2 X3 and Y values
 1  2  1 0 50 1.0E-5        : INDW,IPSI,ISIGMA,NITMON,MAXIT,TOL
 3.0  0                     : CUCV,INDC
 1.5 3.0 4.5                : H1,H2,H3
 1.5                        : DCHI
 1.0                        : Initial value for SIGMA
 0.0 0.0 0.0                : Initial values for THETA


g02hbfe.d

G02HBF Example Program Data
    5    3                   : N,M
  1.0 -1.0 -1.0
  1.0 -1.0  1.0
  1.0  1.0 -1.0
  1.0  1.0  1.0
  1.0  0.0  3.0              : End of X1,X2 and X3 values
  1.0 0.0 1.0 0.0 0.0 1.0    : Initial values for A
0 0.9 0.9 50 5.0E-5          : NITMON,BL,BD,MAXIT,TOL


g02hdfe.d

G02HDF Example Program Data
  5    3                    :: N,M
 -1.0  -1.0   10.5   0.4039
 -1.0   1.0   11.3   0.5012
  1.0  -1.0   12.6   0.4039
  1.0   1.0   13.4   0.5012
  0.0   3.0   17.1   0.3862 :: End of X,Y and WT
  1.0                       :: PSIP0
  1  1  0  50 1.0E-5 1.0E-5 :: INDW,ISIGMA,NITMON,MAXIT,TOL,EPS
  1.0                       :: SIGMA
  0.0  0.0  0.0             :: THETA


g02hffe.d

G02HFF Example Program Data
    5    3             : N  M
  1.0 -1.0 -1.0
  1.0 -1.0  1.0
  1.0  1.0 -1.0
  1.0  1.0  1.0
  1.0  0.0  3.0        : End of X1 X2 and X3 values
    20.7783            : SIGMA
    0.4039    0.5643
    0.5012   -1.1286
    0.4039    0.5643
    0.5012   -1.1286
    0.3862    1.1286   : End of weights and residuals, WGT and RS
 1  1                  : INDW,INDC


g02hkfe.d

G02HKF Example Program Data
    10    3                   : N  M
  3.4  6.9  12.2
  6.4  2.5  15.1
  4.9  5.5  14.2
  7.3  1.9  18.2
  8.8  3.6  11.7
  8.4  1.3  17.9
  5.3  3.1  15.0
  2.7  8.1   7.7
  6.1  3.0  21.9
  5.3  2.2  13.9              : End of X1 X2 and X3 values
0 100 5.0E-5  0.1             : NITMON,MAXIT,TOL,EPS


g02hlfe.d

G02HLF Example Program Data
    10    3                   : N,M
  3.4  6.9  12.2
  6.4  2.5  15.1
  4.9  5.5  14.2
  7.3  1.9  18.2
  8.8  3.6  11.7
  8.4  1.3  17.9
  5.3  3.1  15.0
  2.7  8.1   7.7
  6.1  3.0  21.9
  5.3  2.2  13.9              : End of X
  1.0 0.0 1.0 0.0 0.0 1.0     : A
  0.0 0.0 0.0                 : THETA
  4.0 2.0                     : RUSER
1 0 0.9 0.9 50 5.0E-5         : INDM,NITMON,BL,BD,MAXIT,TOL


g02hmfe.d

G02HMF Example Program Data
    10    3                   : N,M
  3.4  6.9  12.2
  6.4  2.5  15.1
  4.9  5.5  14.2
  7.3  1.9  18.2
  8.8  3.6  11.7
  8.4  1.3  17.9
  5.3  3.1  15.0
  2.7  8.1   7.7
  6.1  3.0  21.9
  5.3  2.2  13.9              : End of X
  1.0 0.0 1.0 0.0 0.0 1.0     : A
  0.0 0.0 0.0                 : THETA
  4.0 2.0                     : RUSER
1 0 0.9 0.9 50 5.0E-5         : INDM,NITMON,BL,BD,MAXIT,TOL


g03aafe.d

G03AAF Example Program Data
 'V' 'E' 'U' 10 3
7.0 4.0 3.0
4.0 1.0 8.0
6.0 3.0 5.0
8.0 6.0 1.0
8.0 5.0 7.0
7.0 2.0 9.0
5.0 3.0 3.0
9.0 5.0 8.0
7.0 4.0 5.0
8.0 2.0 2.0
 1   1   1


g03acfe.d

G03ACF Example Program Data
 9 3 3 3 'U'
 13.3 10.6 21.2 1
 13.6 10.2 21.0 2
 14.2 10.7 21.1 3
 13.4  9.4 21.0 1
 13.2  9.6 20.1 2
 13.9 10.4 19.8 3
 12.9 10.0 20.5 1
 12.2  9.9 20.7 2
 13.9 11.0 19.1 3
  1    1    1


g03bcfe.d

G03BCF Example Program Data
 3 2 'c' 's'
 0.63 0.58
 1.36 0.39
 1.01 1.76
 0.0 0.0
 1.0 0.0
 0.0 2.0


g03bdfe.d

G03BDF Example Program Data
5 2 1 'S' 1.0E-5 200 3.0 : N,M,G,STAND,ACC,MAXIT,POWER
0.74215 -0.57806
0.71370 -0.55515
0.87899 -0.15847
0.62533  0.76621
0.71447  0.67936         :: End of FP


g03eafe.d

G03EAF Example Program Data
5 3          : N,M
'I' 'S' 'U'  : UPDATE,DIST,SCAL
1.0 1.0 1.0
2.0 1.0 2.0
3.0 6.0 3.0
4.0 8.0 2.0
5.0 8.0 0.0  : End of X
 0   1   1   : ISX


g03ecfe.d

G03ECF Example Program Data
5 3                  : N,M (G03EAF)
'I' 'S' 'U'          : UPDATE,DIST,SCAL (G03EAF)
 1  5.0 2.0
 2  1.0 1.0
 3  4.0 3.0
 4  1.0 2.0
 5  5.0 0.0          : End of X (G03EAF)
 0   1   1           : ISX (G03EAF)
5                    : METHOD (G03ECF)
'A' 'B' 'C' 'D' 'E'  : Row names (ROW_NAME)


g03ehfe.d

G03EHF Example Program Data
5 3               : N,M (G03EAF)
'I' 'S' 'U'       : UPDATE,DIST,SCALE (G03EAF)
1 1.0 1.0
2 1.0 2.0
3 6.0 3.0
4 8.0 2.0
5 8.0 0.0         : End of X (G03EAF)
0 1 1             : ISX (G03EAF)
5                 : METHOD (G03ECF)
'E' 0.0 1.1 40    : ORIENT,DMIN,DSTEP,NSYM (First dendogram)
'S' 0.0 1.0 40    : ORIENT,DMIN,DSTEP,NSYM (Second dendogram)


g03ejfe.d

G03EJF Example Program Data
5 3                  : N,M (G03EAF)
'I' 'S' 'U'          : UPDATE,DIST,SCAL (G03EAF)
 1  5.0 2.0
 2  1.0 1.0
 3  4.0 3.0
 4  1.0 2.0
 5  5.0 0.0          : End of X (G03EAF)
 0   1   1           : ISX
5                    : METHOD (G03ECF)
'A' 'B' 'C' 'D' 'E'  : Row names (NAME)
2 0.0                : K, DLEVEL


g03zafe.d

G03ZAF Example Program Data
4 3               :: N, M
15.0 0.0 1500.0
12.0 1.0 1000.0
18.0 2.0 1200.0
14.0 3.0  500.0   :: End of X
 1      0    1    :: ISX
14.75 0.0 1050.0  :: E
 2.50 0.0  420.3  :: S


g04agfe.d

G04AGF Example Program Data
 2                             :: K (number of groups)
 5 3                           :: LSUB (number of subgroups per group)
 5 3 3 3 2 3 5 3               :: NOBS (number of observations per subgroup)
 2.1 2.4 2.0 2.0 2.0
 2.4 2.1 2.2 2.4 2.2
 2.6 2.4 2.4 2.5 1.9
 1.7 2.1 1.5 2.0 1.9
 1.7 1.9 1.9 1.9 2.0 2.1 2.3   :: Y (observed data)


g04bbfe.d

G04BBF Example Program Data
30 6 10                     : N, NT, IBLOCK
1 5 4
5 10 6
2 9 3
4 8 6
2 4 7
6 7 5
5 7 2
7 2 4
8 4 2
10 8 7                      : End of Y
1 2 3
1 2 4
1 3 5
1 4 6
1 5 6
2 3 6
2 4 5
2 5 6
3 4 5
3 4 6                       : End of IT


g04bcfe.d

G04BCF Example Program Data
1 5 5 5
6.67  7.15  8.29  8.95  9.62
5.40  4.77  5.40  7.54  6.93
7.32  8.53  8.50  9.99  9.68
4.92  5.00  7.29  7.85  7.08
4.88  6.16  7.83  5.38  8.51
5  4  1  3  2
2  5  4  1  3
3  2  5  4  1
1  3  2  5  4
4  1  3  2  5


g04cafe.d

G04CAF Example Program Data
54 3 2 2  : N NBLOCK NFAC INTER
6 3       : LFAC
274 361 253 325 317 339 326 402 336 379 345 361 352 334 318 339 393 358
350 340 203 397 356 298 382 376 355 418 387 379 432 339 293 322 417 342
 82 297 133 306 352 361 220 333 270 388 379 274 336 307 266 389 333 353


g04dafe.d

G04DAF Example Program Data
32 7 1                               :: N, NT, IBLOCK (see G04BBF)
12 10 24 29 30 18 32 26
9 9 16 4 30 7 21 9 16 10 18 18
18 24 12 19 10 4 4 5 17 7 16 17      :: End of Y (see G04BBF)
1 1 1 1 1 1 1 1
2 2 2 2 3 3 3 3 4 4 4 4
5 5 5 5 6 6 6 6 7 7 7 7              :: End of IT (see G04BBF)
2                                    :: NC
6 -1 -1 -1 -1 -1 -1                  :: First contrast
 Cntl v S                            :: Name of first contrast
0 1 -1 1 -1 1 -1                     :: Second contrast
 Spring v A                          :: Name of second contrast


g04dbfe.d

G04DBF Example Program Data
26 4 1                            :: N, NT, IBLOCK (G04BBF)
 3  2  4  3  1  5
 7  8  4 10  6
 3  2  1  2  4  2  3  1
10 12  8  5 12 10  9              :: End of Y (G04BBF)
1 1 1 1 1 1
2 2 2 2 2
3 3 3 3 3 3 3 3
4 4 4 4 4 4 4                     :: End of IT (G04BBF)
'T' .95                           :: TYP, CLEVEL


g04eafe.d

G04EAF Example Program Data
 12 4 'C' 'U' 'M'
1 33.63
4 39.62
2 38.18
3 41.46
4 38.02
2 35.83
4 35.99
1 36.58
3 42.92
1 37.80
3 40.43
2 37.89


g05kffe.d

G05KFF Example Program Data
1  1  1762543     :: GENID,SUBID,SEED(1)
5                 :: N


g05khfe.d

G05KHF Example Program Data
1  1  1762543     :: GENID,SUBID,SEED(1)
3  5              :: N,NV


g05kjfe.d

G05KJF Example Program Data
1  1  1762543     :: GENID,SUBID,SEED(1)
50  5             :: N,NV


g05kkfe.d

G05KKF Example Program Data
1  1  1762543     :: GENID,SUBID,SEED(1)
17  5             :: N,NV


g05ncfe.d

G05NCF Example Program Data
1  1  1762543     :: GENID,SUBID,SEED(1)
8  10             :: N,NPERM


g05ndfe.d

G05NDF Example Program Data
1  1  1762543     :: GENID,SUBID,SEED(1)
8                 :: N
1                 :: List of sample sizes (M)
2
3
4
5
6
7
8


g05nefe.d

G05NEF Example Program Data
3  0  1762543   :: GENID,SUBID,SEED(1)
25 10 'S'       :: N,M,POP
'U'             :: ORDER
171  85.54
 52  71.78
172 118.13
139  13.68
196 153.60
125 165.35
 36 122.35
 70  35.87
 25 151.78
 86 128.33
 76 178.27
 37 183.37
185 165.81
 40 101.41
 90 145.16
 27  42.01
 79  59.08
118  17.53
142  87.14
127  69.20
101  31.13
 22  60.26
 41  21.00
199  85.06
 59 119.73      :: End of IPOP,WT


g05pdfe.d

G05PDF Example Program Data
1  1  1762543      :: GENID,SUBID,SEED(1)
10  2              :: NUM,NREAL
0  3               :: IP,IQ
'N'
0.8  0.6  0.2  0.1 :: THETA
-0.4               :: GAMMA


g05pefe.d

G05PEF Example Program Data
1  1  1762543      :: GENID,SUBID,SEED(1)
10  2              :: NUM,NREAL
1  1               :: IP,IQ
'N'
0.08 0.2 0.7       :: THETA
-0.4               :: GAMMA


g05pffe.d

G05PFF Example Program Data
1  1  1762543      :: GENID,SUBID,SEED(1)
10 2               :: NUM,NREAL
1  1               :: IP,IQ
'N'
0.4 0.1 0.7        :: THETA
0.1                :: GAMMA


g05pgfe.d

G05PGF Example Program Data
1  1  1762543      :: GENID,SUBID,SEED(1)
10 2               :: NUM,NREAL
1  1               :: IP,IQ
'N'
0.1 -0.3 0.1 0.9   :: THETA


g05phfe.d

G05PHF Example Program Data
1  1  1762543     :: GENID,SUBID,SEED(1)
10                :: N
2  0              :: IP,IQ
0.0               :: XMEAN
0.4  0.2          :: PHI
1.0               :: AVAR


g05pjfe.d

G05PJF Example Program Data
1  1  1762543     :: GENID,SUBID,SEED(1)
48 2              :: N,NREAL
2  1  0           :: K, IP, IQ
0.80  0.07
0.00  0.58        :: End of PHI
5.00  9.00        :: XMEAN
2.97
0.64  5.38        :: End of VAR (lower triangle)


g05pmfe.d

G05PMF Example Program Data
1  1  1762543                               :: GENID,SUBID,SEED(1)
2 3 11 5 100 0.05                           :: MODE,ITYPE,N,NF,NSIM,ALPHA
180 135 213 181 148 204 228 225 198 200 187 :: Y
0.01 1.0 1.0                                :: PARAM
11                                          :: K


g05pxfe.d

G05PXF Example Program Data
1  1  1762543      :: GENID,SUBID,SEED(1)
4  4               :: N,M
'R'  'I'           :: SIDE,INIT


g05pyfe.d

G05PYF Example Program Data
1  1  1762543      :: GENID,SUBID,SEED(1)
3   1.0E-5         :: N,EPS
0.7 0.9 1.4        :: D


g05pzfe.d

G05PZF Example Program Data
1  1  1762543      :: GENID,SUBID,SEED(1)
4  3               :: NROW,NCOL
9   11   7   23    :: TOTR
16  17  17         :: TOTC


g05rcfe.d

G05RCF Example Program Data
1  1  1762543          :: GENID,SUBID,SEED(1)
10  4                  :: N,M
10                     :: DF
1.69  0.39 -1.86  0.07
     98.01 -7.07 -0.71
           11.56  0.03
                  0.01 :: End of C (upper triangular part)


g05rdfe.d

G05RDF Example Program Data
1  1  1762543          :: GENID,SUBID,SEED(1)
10  4                  :: N,M
1.69  0.39 -1.86  0.07
     98.01 -7.07 -0.71
           11.56  0.03
                  0.01 :: End of C (upper triangular part)


g05refe.d

G05REF Example Program Data
1  1  1762543          :: GENID,SUBID,SEED(1)
13  1                  :: N, SORDER
-0.8                   :: THETA


g05rffe.d

G05RFF Example Program Data
1  1  1762543          :: GENID,SUBID,SEED(1)
13  1                  :: N,SORDER
-12.0                  :: THETA


g05rgfe.d

G05RGF Example Program Data
1  1  1762543          :: GENID,SUBID,SEED(1)
13  1                  :: N,SORDER
2.0                    :: THETA


g05rhfe.d

G05RHF Example Program Data
1  1  1762543          :: GENID,SUBID,SEED(1)
13  4  1               :: N,M,SORDER
1.3                    :: THETA


g05rjfe.d

G05RJF Example Program Data
1  1  1762543          :: GENID,SUBID,SEED(1)
13  4  1               :: N,M,SORDER
4.0                    :: THETA


g05rkfe.d

G05RKF Example Program Data
1  1  1762543          :: GENID,SUBID,SEED(1)
13  4  1               :: N,M,SORDER
2.4                    :: THETA


g05ryfe.d

G05RYF Example Program Data
1  1  1762543          :: GENID,SUBID,SEED(1)
10  4                  :: N,M
10                     :: DF
1.0   2.0  -3.0   0.0  :: XMU
1.69  0.39 -1.86  0.07
     98.01 -7.07 -0.71
           11.56  0.03
                  0.01 :: End of C (upper triangular part)


g05rzfe.d

G05RZF Example Program Data
1  1  1762543          :: GENID,SUBID,SEED(1)
10  4                  :: N,M
1.0   2.0  -3.0   0.0  :: XMU
1.69  0.39 -1.86  0.07
     98.01 -7.07 -0.71
           11.56  0.03
                  0.01 :: End of C (upper triangular part)


g05safe.d

G05SAF Example Program Data
1  1  1762543     :: GENID,SUBID,SEED(1)
5                 :: N


g05sbfe.d

G05SBF Example Program Data
1  1  1762543     :: GENID,SUBID,SEED(1)
5                 :: N
2.0 2.0           :: A,B


g05scfe.d

G05SCF Example Program Data
1  1  1762543     :: GENID,SUBID,SEED(1)
5                 :: N
1.0 2.0           :: XMED,SEMIQR


g05sdfe.d

G05SDF Example Program Data
1  1  1762543     :: GENID,SUBID,SEED(1)
5                 :: N
5                 :: DF


g05sefe.d

G05SEF Example Program Data
1  1  1762543     :: GENID,SUBID,SEED(1)
5 4               :: N,M
2.0 2.0 2.0 2.0   :: A


g05sffe.d

G05SFF Example Program Data
1  1  1762543     :: GENID,SUBID,SEED(1)
5                 :: N
1.0               :: A


g05sgfe.d

G05SGF Example Program Data
1  1  1762543     :: GENID,SUBID,SEED(1)
5 3               :: N,NMIX
1.0 5.0 2.0       :: A
0.5 0.3 0.2       :: WGT


g05shfe.d

G05SHF Example Program Data
1  1  1762543     :: GENID,SUBID,SEED(1)
5 3               :: N,NMIX
2 3               :: DF1,DF2


g05sjfe.d

G05SJF Example Program Data
1  1  1762543     :: GENID,SUBID,SEED(1)
5 3               :: N,NMIX
5.0 1.0           :: A,B


g05skfe.d

G05SKF Example Program Data
1  1  1762543     :: GENID,SUBID,SEED(1)
5                 :: N
1.0 1.5           :: XMU,VAR


g05slfe.d

G05SLF Example Program Data
1  1  1762543     :: GENID,SUBID,SEED(1)
5 3               :: N,NMIX
1.0 2.0           :: A,B


g05smfe.d

G05SMF Example Program Data
1  1  1762543     :: GENID,SUBID,SEED(1)
5 3               :: N,NMIX
1.0 2.0           :: XMU,VAR


g05snfe.d

G05SNF Example Program Data
1  1  1762543     :: GENID,SUBID,SEED(1)
5 3               :: N,NMIX
5                 :: DF


g05spfe.d

G05SPF Example Program Data
1  1  1762543     :: GENID,SUBID,SEED(1)
5 3               :: N,NMIX
-1.0 0.5 1.0      :: XMIN,XMED,XMAX


g05sqfe.d

G05SQF Example Program Data
1  1  1762543     :: GENID,SUBID,SEED(1)
5 3               :: N,NMIX
-1.0 1.0          :: A,B


g05srfe.d

G05SRF Example Program Data
1  1  1762543     :: GENID,SUBID,SEED(1)
5 3               :: N,NMIX
1.0               :: VK


g05ssfe.d

G05SSF Example Program Data
1  1  1762543     :: GENID,SUBID,SEED(1)
5 3               :: N,NMIX
1.0 2.0           :: A,B


g05tafe.d

G05TAF Example Program Data
1  1  1762543     :: GENID,SUBID,SEED(1)
20                :: N
0.8 6000          :: P,M


g05tbfe.d

G05TBF Example Program Data
1  1  1762543     :: GENID,SUBID,SEED(1)
20                :: N
0.5               :: P


g05tcfe.d

G05TCF Example Program Data
1  1  1762543     :: GENID,SUBID,SEED(1)
10                :: N
0.001             :: P


g05tdfe.d

G05TDF Example Program Data
1  1  1762543                :: GENID,SUBID,SEED(1)
20                           :: N
11  -5  1                    :: NP,IP1,ITYPE
0.01 0.02 0.04 0.08 0.2  0.3
0.2  0.08 0.04 0.02 0.01     :: End of P


g05tefe.d

G05TEF Example Program Data
1  1  1762543     :: GENID,SUBID,SEED(1)
20                :: N
500  900  1000    :: NS,M,NP
10 5 100
100 2500 10000
9780 50 10000


g05tffe.d

G05TFF Example Program Data
1  1  1762543     :: GENID,SUBID,SEED(1)
10                :: N
0.9999            :: A


g05tgfe.d

G05TGF Example Program Data
1  1  1762543     :: GENID,SUBID,SEED(1)
20                :: N
6000  4           :: M,K
0.08 0.1 0.8 0.02 :: P


g05thfe.d

G05THF Example Program Data
1  1  1762543     :: GENID,SUBID,SEED(1)
20                :: N
0.999  60         :: P,M


g05tjfe.d

G05TJF Example Program Data
1  1  1762543     :: GENID,SUBID,SEED(1)
10                :: N
20.0              :: LAMBDA


g05tkfe.d

G05TKF Example Program Data
1  1  1762543             :: GENID,SUBID,SEED(1)
10                        :: N
5                         :: M
0.5 5.0 10.0 500.0 1000.0 :: LAMBDA


g05tlfe.d

G05TLF Example Program Data
1  1  1762543           :: GENID,SUBID,SEED(1)
5                       :: N
-5 5                    :: A,B


g05yjfe.d

G05YJF Example Program Data
1               :: GENID
5  4  1000      :: N,IDIM,ISKIP
1.0 2.0 3.0 4.0 :: XMEAN
1.0 1.0 1.0 1.0 :: XSTD


g05ykfe.d

G05YKF Example Program Data
1               :: GENID
5  4  1000      :: N,IDIM,ISKIP
1.0 2.0 3.0 4.0 :: XMEAN
1.0 1.0 1.0 1.0 :: XSTD


g05ymfe.d

G05YMF Example Program Data
1                 :: GENID
200  8  1000      :: N,IDIM,ISKIP
5                 :: DN


g05ynfe.d

G05YNF Example Program Data
1  1  1762543     :: PGENID,PSUBID,SEED(1)
1  1  0           :: GENID,STYPE,NSDIGI
200  8  1000      :: N,IDIM,ISKIP
5                 :: DN


g05zmfe.d

G05ZMF Example Program Data
 0.1    1.2    : l, nu
 0.5           : var
-1.0    1.0    : xmin, xmax
 8             : ns
 2048          : maxm
 2             : icorr
 1             : pad


g05znfe.d

G05ZNF Example Program Data
 1             : icov1  (icov=1, symmetric stable)
 2             : np     (icov=1, 2 parameters)
 0.1   1.2     : params (icov=1, l and nu)
 0.5           : var
-1     1       : xmin, xmax
 8             : ns
 2048          : maxm
 2             : icorr
 1             : pad


g05zpfe.d

G05ZPF Example Program Data
 1             : icov1  (icov=1, symmetric stable)
 2             : np     (icov=1, 2 parameters)
 0.1   1.2     : params (icov=1, l and nu)
 0.5           : var
-1     1       : xmin, xmax
 8             : ns
 2048          : maxm
 2             : icorr
 1             : pad
 5             : s


g05zqfe.d

G05ZQF Example Program Data
  2    0.1   0.15 1.2 : norm, l1, l2, nu
  0.5                 : var
 -1    1              : xmin, xmax
 -0.5  0.5            : ymin, ymax
  5    5              : ns
 81   81              : maxm
  2                   : icorr
  1                   : pad


g05zrfe.d

G05ZRF Example Program Data
  1               : icov2  (icov2=1, symmetric stable)
  3               : np     (icov2=1, 3 parameters)
  0.1   0.15  1.2 : params (icov2=1, l1, l2  and nu)
  2               : norm
  0.5             : var
 -1.0   1.0       : xmin, xmax
 -0.5   0.5       : ymin, ymax
  5     5         : ns
 64    64         : maxm
  2               : icorr
  1               : pad


g05zsfe.d

G05ZSF Example Program Data
  1                : icov2  (icov2=1, symmetric stable)
  3                : np     (icov2=1, 3 parameters)
  0.1   0.15  1.2  : params (icov2=1, l1, l2  and nu)
  2                : norm
  0.5              : var
 -1 1              : xmin, xmax
 -0.5   0.5        : ymin, ymax
  5     5          : ns(1:2)
 64    64          : maxm(1:2)
  2                : icorr
  1                : pad
  5                : s


g05ztfe.d

G05ZTF Example Program Data
    0.35       : h
    2          : xmax
   10          : ns
 2048          : maxm
    2          : icorr
    1          : pad
    5          : s


g07aafe.d

G07AAF Example Program Data
    1067     117    0.95           : N, K, CLEVEL
     402      54    0.95


g07abfe.d

G07ABF Example Program Data
0 3
1 17
2 26
3 16
4 18
5 9
6 3
7 5
8 0
9 1
10 0


g07bbfe.d

G07BBF Example Program Data
18 'N' 4.0 1.0 0.00005 50
4.5 0.0 0 5.4 0.0 0 3.9 0.0 0 5.1 0.0 0 4.6 0.0 0 4.8 0.0 0
2.9 0.0 0 6.3 0.0 0 5.5 0.0 0 4.6 0.0 0 4.1 0.0 0 5.2 0.0 0
3.2 0.0 1 4.0 0.0 1 3.1 0.0 1 5.1 0.0 2 3.8 0.0 2 2.2 2.5 3


g07befe.d

G07BEF Example Program Data
'N' 20 0.0 0            :: CENS,N,TOL,MAXIT
1.1 1.4 1.3 1.7 1.9
1.8 1.6 2.2 1.7 2.7
4.1 1.8 1.5 1.2 1.4
3.0 1.7 2.3 1.6 2.0     :: End of X
0.0                     :: GAMMA (initial estimate are calculated from data)


g07bffe.d

G07BFF Example Program Data
23 2
1.5800
0.1390
2.3624
2.9435
0.1363
0.9688
0.6585
2.8011
0.9880
1.7887
0.0630
0.3862
1.5130
0.0669
1.3659
0.4256
0.3485
27.8760
5.2503
1.1028
0.5273
1.3189
0.6490


g07cafe.d

G07CAF Example Program Data
4 25.0 0.8185     :: NX,XMEAN,XSTD
8 21.0 4.2083     :: NY,YMEAN,YSTD
0.95  'T' 'E'     :: CLEVEL,TAIL,EQUAL
0.95  'T' 'U'     :: CLEVEL,TAIL,EQUAL


g07dafe.d

G07DAF Example Program Data
11           : N, NUMBER OF OBSERVATIONS
13.0 11.0 16.0 5.0 3.0 18.0 9.0 8.0 6.0 27.0 7.0  : X, OBSERVATIONS


g07dbfe.d

G07DBF Example Program Data
11                                :: N
13.0 11.0 16.0  5.0 3.0 18.0
 9.0  8.0  6.0 27.0 7.0           :: End of X
 2   1.5  50                      :: IPSI,DCHI,MAXIT
1.5  3.0 4.5                      :: H1,H2,H3
  1     -1.0    0.0   0.0001      :: ISIGMA,SIGMA,THETA,TOL
  1      7.0    2.0   0.0001      :: ISIGMA,SIGMA,THETA,TOL
  0     -1.0    0.0   0.0001      :: ISIGMA,SIGMA,THETA,TOL
  0      7.0    2.0   0.0001      :: ISIGMA,SIGMA,THETA,TOL


g07dcfe.d

G07DCF Example Program Data
11   0.3892326   50              :: N,BETA,MAXIT
13.0 11.0 16.0  5.0 3.0 18.0
 9.0  8.0  6.0 27.0 7.0          :: End of X
  1     -1.0    0.0   0.0001     :: ISIGMA,SIGMA,THETA,TOL
  1      7.0    2.0   0.0001     :: ISIGMA,SIGMA,THETA,TOL
  0     -1.0    0.0   0.0001     :: ISIGMA,SIGMA,THETA,TOL
  0      7.0    2.0   0.0001     :: ISIGMA,SIGMA,THETA,TOL


g07ddfe.d

G07DDF Example Program Data
 16  0.15             :: N,ALPHA
 26.0 12.0  9.0  2.0
  5.0  6.0  8.0 14.0
  7.0  3.0  1.0 11.0
 10.0  4.0 17.0 21.0  :: End of X


g07gafe.d

G07GAF Example Program Data
15 2 1 :: N,P,LDIFF
-0.30
 0.48
 0.63
-0.22
 0.18
-0.44
-0.24
-0.13
-0.05
 0.39
 1.01
 0.06
-1.40
 0.20
 0.10  :: Y


g07gbfe.d

G07GBF Example Program Data
15 -1.40 0.303 0.161   :: N, E, VAR1, VAR2
14  1.01 0.161 0.103   :: N, E, VAR1, VAR2
13  0.63 0.103 0.080   :: N, E, VAR1, VAR2


g08aafe.d

G08AAF Example Program Data
 17                                 :: N
4.0 4.0 5.0 5.0 3.0 2.0 5.0 3.0 1.0
5.0 5.0 5.0 4.0 5.0 5.0 5.0 5.0     :: End of X
2.0 3.0 3.0 3.0 3.0 3.0 3.0 3.0 2.0
3.0 2.0 2.0 5.0 2.0 5.0 3.0 1.0     :: End of Y


g08acfe.d

G08ACF Example Program Data
39  16                              :: N,N1
13.0  6.0 12.0  7.0 12.0  7.0 10.0
 7.0 10.0  7.0 10.0  7.0 10.0  8.0
 9.0  8.0 17.0  6.0 16.0  8.0 15.0
 8.0 15.0 10.0 15.0 10.0 14.0 10.0
14.0 11.0 14.0 11.0 13.0 12.0 13.0
12.0 13.0 12.0 12.0                 :: End of X


g08aefe.d

G08AEF Example Program Data
3  18                                 :: K,N
 1.0 2.0 1.0 1.0 3.0 2.0 3.0 1.0 3.0
 3.0 2.0 2.0 3.0 2.0 2.5 3.0 3.0 2.0
 3.0 3.0 3.0 2.0 1.0 3.0 2.0 3.0 1.0
 1.0 3.0 3.0 2.0 3.0 2.5 2.0 2.0 3.0
 2.0 1.0 2.0 3.0 2.0 1.0 1.0 2.0 2.0
 2.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0  :: End of X


g08affe.d

G08AFF Example Program Data
 5                               :: K
 5 8 6 8 8                       :: L
23.0 27.0 26.0 19.0 30.0 29.0
25.0 33.0 36.0 32.0 28.0 30.0
31.0 38.0 31.0 28.0 35.0 33.0
36.0 30.0 27.0 28.0 22.0 33.0
34.0 34.0 32.0 31.0 33.0 31.0
28.0 30.0 24.0 29.0 30.0        :: End of X


g08agfe.d

G08AGF Example Program Data
 8  0.0  'T' 'N'                         :: N,XME,TAIL,ZER
82.0 69.0 73.0 43.0 58.0 56.0 76.0 65.0  :: X
63.0 42.0 74.0 37.0 51.0 43.0 80.0 62.0  :: Y


g08ahfe.d

G08AHF Example Program Data
 16  23  'L'                                     :: N1,N2,TAIL
 13.0  6.0 12.0  7.0 12.0  7.0 10.0  7.0
 10.0  7.0 16.0  7.0 10.0  8.0  9.0  8.0         :: End of X
 17.0  6.0 10.0  8.0 15.0  8.0 15.0 10.0
 15.0 10.0 14.0 10.0 14.0 11.0 14.0 11.0
 13.0 12.0 13.0 12.0 13.0 12.0 12.0              :: End if Y


g08ajfe.d

G08AJF Example Program Data
 16  23  'L'                             :: N1,N2,TAIL
 13.0  5.8 11.7  6.5 12.3  6.7  9.2  6.9
 10.0  7.3 16.0  7.0 10.5  8.5  9.0  7.5 :: End of X
 17.0  6.2 10.1  8.0 15.3  8.2 15.0  9.6
 14.9 10.4 14.2  9.8 13.8 11.0 14.0 11.1
 12.9 11.6 12.8 12.0 13.1 12.4 11.9      :: End of Y


g08akfe.d

G08AKF Example Program Data
 16  23  'L'                               :: N1,N2,TAIL
 13.0  6.0 12.0  7.0 12.0  7.0 10.0  7.0
 10.0  7.0 16.0  7.0 10.0  8.0  9.0  8.0   :: End of X
 17.0  6.0 10.0  8.0 15.0  8.0 15.0 10.0
 15.0 10.0 14.0 10.0 14.0 11.0 14.0 11.0
 13.0 12.0 13.0 12.0 13.0 12.0 12.0        :: End of Y


g08alfe.d

G08ALF Example Program Data
 12  3
 1 1 1
 1 1 1
 0 1 0
 1 1 0
 0 0 0
 1 1 1
 1 1 1
 1 1 0
 0 0 1
 0 1 0
 1 1 1
 1 1 1


g08bafe.d

G08BAF Example Program Data
12  6  0                       :: N,N1,ITEST
  6.0  9.0 12.0  4.0 10.0 11.0
  8.0  1.0  3.0  7.0  2.0  5.0 :: End of X


g08cbfe.d

G08CBF Example Program Data
 30   1                                            :: N,NTYPE
 0.01 0.30 0.20 0.90 1.20 0.09 1.30 0.18 0.90 0.48
 1.98 0.03 0.50 0.07 0.70 0.60 0.95 1.00 0.31 1.45
 1.04 1.25 0.15 0.75 0.85 0.22 1.56 0.81 0.57 0.55 :: End of X
'N' 'E'                                            :: DIST,ESTIMA


g08ccfe.d

G08CCF Example Program Data
 30  1                                             :: N,NTYPE
 0.01 0.30 0.20 0.90 1.20 0.09 1.30 0.18 0.90 0.48
 1.98 0.03 0.50 0.07 0.70 0.60 0.95 1.00 0.31 1.45
 1.04 1.25 0.15 0.75 0.85 0.22 1.56 0.81 0.57 0.55 :: End of X


g08dafe.d

G08DAF Example Program Data
3  10                                               : K,N
  1.0  4.5  2.0  4.5  3.0  7.5  6.0  9.0  7.5 10.0
  2.5  1.0  2.5  4.5  4.5  8.0  9.0  6.5 10.0  6.5
  2.0  1.0  4.5  4.5  4.5  4.5  8.0  8.0  8.0 10.0  : End of X


g10zafe.d

G10ZAF Example Program Data
'U' 10    :: WEIGHT,N
1.0 4.0
3.0 4.0
5.0 1.0
5.0 2.0
3.0 5.0
4.0 3.0
9.0 4.0
6.0 9.0
9.0 7.0
9.0 4.0   :: End of X,Y


g11aafe.d

G11AAF Example Program Data
3 3                        : NROW NCOL
23  9  6
21  4  3
34 24 17                   : End of NOBS


g11cafe.d

G11CAF Example Program Data
7 2 2 10 0 1.0E-5 :: N,M,NS,MAXIT,IPRINT,TOL
1 0 0 1
1 0 1 2
1 1 0 1
1 1 1 3
2 0 0 1
2 1 1 0
2 1 0 2           :: End of ISI,IC,Z
1 1               :: ISZ
0.0 0.0           :: B


g11safe.d

G11SAF Example Program Data
 4  1000  16              :: IP,N,NS
 F  -1  1.0E-4 1000  T  7 :: GPROB,IPRINT,CGETOL,MAXIT,CHISQR,ISHOW
154 F F F F
 11 T F F F
 42 F F F T
 49 F T F F
  2 T F F T
 10 T T F F
 27 F T F T
 84 F F T F
 10 T T F T
 25 T F T F
 75 F F T T
129 F T T F
 30 T F T T
 50 T T T F
181 F T T T
121 T T T T               :: End of IRL,X
0.5  0.5  0.5  0.5        :: A (initial values)
0.0  0.0  0.0  0.0        :: C (initial values)


g11sbfe.d

G11SBF Example Program Data
10 3
F F F
F T F
T T T
F F F
F F T
F F F
F F F
T T F
F F T
F T T


g12aafe.d

G12AAF Example Program Data
18 'F'
 6.0 1 1  6.0 0 3  7.0 0 1  9.0 1 1 10.0 0 1 10.0 1 1
11.0 1 1 13.0 0 1 16.0 0 1 17.0 1 1 19.0 1 1 20.0 1 1
22.0 0 1 23.0 0 1 25.0 1 1 32.0 1 2 34.0 1 1 35.0 1 1


g12bafe.d

G12BAF Example Program Data
42 1 0 20 0 'N'   : N,M,NS,MAXIT,IPRINT,OFFSET
 1 0 0
 1 0 0
 2 0 0
 2 0 0
 3 0 0
 4 0 0
 4 0 0
 5 0 0
 5 0 0
 8 0 0
 8 0 0
 8 0 0
 8 0 0
11 0 0
11 0 0
12 0 0
12 0 0
15 0 0
17 0 0
22 0 0
23 0 0
 6 1 0
 6 1 0
 6 1 0
 7 1 0
10 1 0
13 1 0
16 1 0
22 1 0
23 1 0
 6 1 1
 9 1 1
10 1 1
11 1 1
17 1 1
19 1 1
20 1 1
25 1 1
32 1 1
32 1 1
34 1 1
35 1 1            : T,Z,IC
   1              : ISZ


g12zafe.d

G12ZAF Example Program Data
42 1 0 20 0       : N,M,NS,MAXIT,IPRINT
 1 0 0
 1 0 0
 2 0 0
 2 0 0
 3 0 0
 4 0 0
 4 0 0
 5 0 0
 5 0 0
 8 0 0
 8 0 0
 8 0 0
 8 0 0
11 0 0
11 0 0
12 0 0
12 0 0
15 0 0
17 0 0
22 0 0
23 0 0
 6 1 0
 6 1 0
 6 1 0
 7 1 0
10 1 0
13 1 0
16 1 0
22 1 0
23 1 0
 6 1 1
 9 1 1
10 1 1
11 1 1
17 1 1
19 1 1
20 1 1
25 1 1
32 1 1
32 1 1
34 1 1
35 1 1            : T,Z,IC
1                 : ISZ
0.0 0.0           : B (G11CAF)


g13aafe.d

G13AAF Example Program Data
 20  2  1  4
 120.0 108.0  98.0 118.0 135.0
 131.0 118.0 125.0 121.0 100.0
  82.0  82.0  89.0  88.0  86.0
  96.0 108.0 110.0  99.0 105.0


g13acfe.d

G13ACF Example Program Data
 10  5
    0.8004    0.4355    0.0328   -0.2835   -0.4505
   -0.4242   -0.2419   -0.0550    0.3783    0.5857


g13aefe.d

G13AEF Example Program Data
 30 1 0.0                                           :: NX,KFC,C
 1  1  2  0  0  0  0                                :: MR
 -217 -177 -166 -136 -110  -95  -64  -37  -14  -25
  -51  -62  -73  -88 -113 -120  -83  -33  -19   21
   17   44   44   78   88  122  126  114   85   64  :: X
0.0 0.0 0.0                                         :: PAR (initial values)
0 25 1                                              :: KPIV,NIT,KZSP
0.001 10.0 1000.0 0.0001                            :: ZSP


g13affe.d

G13AFF Example Program Data
 30  1 0.0                                          :: NX,KFC,C
1  1  2  0  0  0  0                                 :: MR
 -217 -177 -166 -136 -110  -95  -64  -37  -14  -25
  -51  -62  -73  -88 -113 -120  -83  -33  -19   21
   17   44   44   78   88  122  126  114   85   64  :: End of X
0.0 0.0 0.0                                         :: PAR (initial values)
0  50                                               :: KPIV,NIT


g13ajfe.d

G13AJF Example Program Data
 30  5  1  9.9807                                   :: NX,NFV,KFC,C
 1  1  2  0  0  0  0                                :: MR
 -217 -177 -166 -136 -110  -95  -64  -37  -14  -25
  -51  -62  -73  -88 -113 -120  -83  -33  -19   21
   17   44   44   78   88  122  126  114   85   64  :: End of X
 -0.0547 -0.5568 -0.6636                            :: PAR


g13amfe.d

G13AMF Example Program Data
2 3 11 5                                    : MODE,ITYPE,N,NF
180 135 213 181 148 204 228 225 198 200 187 : Y
0.01 1.0 1.0                                : PARAM(1:3) (since ITYPE=3)
11                                          : K (since MODE=2)


g13asfe.d

G13ASF Example Program Data
30  1  0.0                                              : NX,KFC,C
1  1  2  0  0  0  0                                     : MR
-217.0 -177.0 -166.0 -136.0 -110.0  -95.0  -64.0  -37.0
 -14.0  -25.0  -51.0  -62.0  -73.0  -88.0 -113.0 -120.0
 -83.0  -33.0  -19.0   21.0   17.0   44.0   44.0   78.0
  88.0  122.0  126.0  114.0   85.0   64.0               : End of X
0.0 0.0 0.0                                             : PAR (initial values)
0  50                                                   : KPIV,NIT
10  1                                                   : M,ISHOW


g13awfe.d

G13AWF Example Program Data
 30  1 1                                           :: N,TYPE,P
 -217 -177 -166 -136 -110  -95  -64  -37  -14  -25
  -51  -62  -73  -88 -113 -120  -83  -33  -19   21
   17   44   44   78   88  122  126  114   85   64 :: End of Y


g13bdfe.d

G13BDF Example Program Data
     6   -0.0155                                  :: NL,R0
  0.0339 -0.0374 -0.2895 -0.3430 -0.4518 -0.2787  :: R
     3     2     1                                :: NNA
  1.9256                                          :: S


g13bgfe.d

G13BGF Example Program Data
10  2  4  1                              :: NSTTF,NSER,NNV,KZEF
 1  0  0  0  1  1  4                     :: MR
 1  0  1  3                              :: Transfer fun. for series 1, MT(:,1)
  6.0530 184.4749 -80.0885 -75.1704
-76.9481 -81.4749   0.7776  -2.6190
 -2.3054  -1.1963                        :: STTF
  0.5158   0.9994   8.6343   0.6726
 -0.3172                                 :: PARA
  5.9410  96.0000
  5.3860  95.0000
  5.8110  80.0000
  6.7160  88.0000                        :: End of XXYN


g13bhfe.d

G13BHF Example Program Data
   10    2    4    1                    :: NSTTF,NSER,NFV,KZEF
    1    0    0    0    1    1    4     :: MR
1 0 1 3                                 :: Transfer fun. for series 1, MT(:,1)
  6.7160 158.3022 -80.3352 -74.8937
-80.7694 -70.3022   0.8476  -2.0234
 -5.8080  10.2943                       :: STTF
  0.5158   0.9994   8.6343   0.6726
 -0.3172                                :: PARA
   6.923
   6.939
   6.705
   6.914                                :: Input series, XXYN(:,1:(NSER-1))
2 0 2 0 1 1 4                           :: Order for input series 1, MRX(:,1)
1.6743 -0.9505 1.4605 -0.4862 0.8993    :: Params for input series 1, PARX(:,1)
0.1720 22.9256                          :: RMSXY


g13dxfe.d

G13DXF Example Program Data
 2 1                     :: K,IP
 0.802 0.065 0.000 0.575 :: PAR


g13ejfe.d

G13EJF Example Program Data
0.1
0.0 0.1
0.0 0.0 0.1           :: End of LX
0.01
0.0 0.01              :: End of LY
0.0 0.0 0.0           :: Initial value for X
0.1
0.0 0.1
0.0 0.0 0.1           :: End of initial value for ST
15                    :: Number of time points
3.0 4.0 5.814  0.464  :: r, d, Delta, A
 1    0.4    0.1
      5.262  5.923
 2    0.4    0.1
      4.347  5.783
 3    0.4    0.1
      3.818  6.181
 4    0.4    0.1
      2.706  0.085
 5    0.4    0.1
      1.878  0.442
 6    0.4    0.1
      0.684  0.836
 7    0.4    0.1
      0.752  1.300
 8    0.4    0.1
      0.464  1.700
 9    0.4    0.1
      0.597  1.781
10    0.4    0.1
      0.842  2.040
11    0.4    0.1
      1.412  2.286
12    0.4    0.1
      1.527  2.820
13    0.4    0.1
      2.399  3.147
14    0.4    0.1
      2.661  3.569
15    0.4    0.1
      3.327  3.659    :: t, phi_rt, phi_lt, Y = (delta_t, alpha_a)


g13ekfe.d

G13EKF Example Program Data
0.1
0.0 0.1
0.0 0.0 0.1           :: End of LX
0.01
0.0 0.01              :: End of LY
0.0 0.0 0.0           :: Initial value for X
0.1
0.0 0.1
0.0 0.0 0.1           :: End of initial value for ST
15                    :: Number of time points
3.0 4.0 5.814  0.464  :: r, d, Delta, A
 1    0.4    0.1
      5.262  5.923
 2    0.4    0.1
      4.347  5.783
 3    0.4    0.1
      3.818  6.181
 4    0.4    0.1
      2.706  0.085
 5    0.4    0.1
      1.878  0.442
 6    0.4    0.1
      0.684  0.836
 7    0.4    0.1
      0.752  1.300
 8    0.4    0.1
      0.464  1.700
 9    0.4    0.1
      0.597  1.781
10    0.4    0.1
      0.842  2.040
11    0.4    0.1
      1.412  2.286
12    0.4    0.1
      1.527  2.820
13    0.4    0.1
      2.399  3.147
14    0.4    0.1
      2.661  3.569
15    0.4    0.1
      3.327  3.659    :: t, phi_rt, phi_lt, Y = (delta_t, alpha_a)


g13mefe.d

G13MEF Example Program Data
2                                        :: M
3 2   2.0                                :: INTER(1:2),TAU
5.0 0.5 0.5 0.5                          :: SINIT

5                                        :: NB
 7.5  0.6
 8.2  0.6
18.1  0.8
22.8  0.1
25.8  0.2                                :: End of T and IEMA for first block

10                                       :: NB
26.8  0.2
31.1  0.5
38.4  0.7
45.9  0.1
48.2  0.4
48.9  0.7
57.9  0.8
58.5  0.3
63.9  0.2
65.2  0.5                                :: End of T and IEMA for second block

15                                       :: NB
66.6  0.2
67.4  0.3
69.3  0.8
69.9  0.6
73.0  0.1
75.6  0.7
77.0  0.9
84.7  0.6
86.8  0.3
88.0  0.1
88.5  0.1
91.0  0.4
93.0  1.0
93.7  1.0
94.0  0.1                                :: End of T and IEMA for third block


g13mffe.d

G13MFF Example Program Data
2                                        :: SORDER
2 6                                      :: M1,M2
1  1.0   3 2   2.0                       :: FTYPE,P,INTER(1:2),TAU
0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0          :: SINIT

5                                        :: NB
 7.5  0.6
 8.2  0.6
18.1  0.8
22.8  0.1
25.8  0.2                                :: End of T and Z for first block

10                                       :: NB
26.8  0.2
31.1  0.5
38.4  0.7
45.9  0.1
48.2  0.4
48.9  0.7
57.9  0.8
58.5  0.3
63.9  0.2
65.2  0.5                                :: End of T and Z for second block

15                                       :: NB
66.6  0.2
67.4  0.3
69.3  0.8
69.9  0.6
73.0  0.1
75.6  0.7
77.0  0.9
84.7  0.6
86.8  0.3
88.0  0.1
88.5  0.1
91.0  0.4
93.0  1.0
93.7  1.0
94.0  0.1                                :: End of T and Z for third block


g13mgfe.d

G13MGF Example Program Data
1 2                                      :: M1,M2
1  1.0   3 2   2.0                       :: FTYPE,P,INTER(1:2),TAU
0.0 0.0 0.0 0.0                          :: SINIT

5                                        :: NB
 7.5  0.6
 8.2  0.6
18.1  0.8
22.8  0.1
25.8  0.2                                :: End of T and Z for first block

10                                       :: NB
26.8  0.2
31.1  0.5
38.4  0.7
45.9  0.1
48.2  0.4
48.9  0.7
57.9  0.8
58.5  0.3
63.9  0.2
65.2  0.5                                :: End of T and Z for second block

15                                       :: NB
66.6  0.2
67.4  0.3
69.3  0.8
69.9  0.6
73.0  0.1
75.6  0.7
77.0  0.9
84.7  0.6
86.8  0.3
88.0  0.1
88.5  0.1
91.0  0.4
93.0  1.0
93.7  1.0
94.0  0.1                                :: End of T and Z for third block


h02bbfe.d

H02BBF Example Program Data
  2  3                                           :Values of N and M
  0  10                                          :Values of ITMAX and MSGLVL
  0                                              :Value of MAXNOD
  0  4                                           :Values of INTFST and MAXDPT
  0.0   0.0                                      :Values of TOLFES and TOLIV
 -3.0  -4.0                                      :End of CVEC
  2.0   5.0
  2.0  -2.0
  3.0   2.0                                      :End of matrix A
  1.0E+20                                        :Value of BIGBND
  0.0      0.0      -1.0E+20  -1.0E+20  5.0      :End of BL
  1.0E+20  1.0E+20  15.0       5.0      1.0E+20  :End of BU
  1     1                                        :End of INTVAR
  1.0   1.0                                      :End of X


h02bffe.opt

NAME          DIET
ROWS
 G  ENERGY
 G  PROTEIN
 G  CALCIUM
 N  COST
COLUMNS
    OATMEAL   ENERGY      110.0
    OATMEAL   PROTEIN     4.0
    OATMEAL   CALCIUM     2.0
    OATMEAL   COST        3.0
    CHICKEN   ENERGY      205.0
    CHICKEN   PROTEIN     32.0
    CHICKEN   CALCIUM     12.0
    CHICKEN   COST        24.0
    INTEGER   'MARKER'                 'INTORG'
    EGGS      ENERGY      160.0
    EGGS      PROTEIN     13.0
    EGGS      CALCIUM     54.0
    EGGS      COST        13.0
    MILK      ENERGY      160.0
    MILK      PROTEIN     8.0
    MILK      CALCIUM     285.0
    MILK      COST        9.0
    PIE       ENERGY      420.0
    PIE       PROTEIN     4.0
    PIE       CALCIUM     22.0
    PIE       COST        20.0
    INTEGER   'MARKER'                 'INTEND'
    BACON     ENERGY      260.0
    BACON     PROTEIN     14.0
    BACON     CALCIUM     80.0
    BACON     COST        19.0
RHS
    DEMANDS   ENERGY      2000.0
    DEMANDS   PROTEIN     55.0
    DEMANDS   CALCIUM     800.0
BOUNDS
 UI SERVINGS  OATMEAL     4.0
 UI SERVINGS  CHICKEN     3.0
 UP SERVINGS  EGGS        2.0
 UP SERVINGS  MILK        8.0
 UP SERVINGS  PIE         2.0
 UI SERVINGS  BACON       2.0
ENDATA


h02bufe.opt

NAME          DIET
ROWS
 G  ENERGY
 G  PROTEIN
 G  CALCIUM
 N  COST
COLUMNS
    OATMEAL   ENERGY      110.0
    OATMEAL   PROTEIN     4.0
    OATMEAL   CALCIUM     2.0
    OATMEAL   COST        3.0
    CHICKEN   ENERGY      205.0
    CHICKEN   PROTEIN     32.0
    CHICKEN   CALCIUM     12.0
    CHICKEN   COST        24.0
    EGGS      ENERGY      160.0
    EGGS      PROTEIN     13.0
    EGGS      CALCIUM     54.0
    EGGS      COST        13.0
    MILK      ENERGY      160.0
    MILK      PROTEIN     8.0
    MILK      CALCIUM     285.0
    MILK      COST        9.0
    PIE       ENERGY      420.0
    PIE       PROTEIN     4.0
    PIE       CALCIUM     22.0
    PIE       COST        20.0
    BACON     ENERGY      260.0
    BACON     PROTEIN     14.0
    BACON     CALCIUM     80.0
    BACON     COST        19.0
RHS
    DEMANDS   ENERGY      2000.0
    DEMANDS   PROTEIN     55.0
    DEMANDS   CALCIUM     800.0
BOUNDS
 UI SERVINGS  OATMEAL     4.0
 UI SERVINGS  CHICKEN     3.0
 UP SERVINGS  EGGS        2.0
 UP SERVINGS  MILK        8.0
 UP SERVINGS  PIE         2.0
 UI SERVINGS  BACON       2.0
ENDATA


h02bzfe.d

H02BZF Example Program Data
 6  3                                           :Values of N and M
 0  0                                           :Values of ITMAX and MSGLVL
 0                                              :Value of MAXNOD
 0  9                                           :Values of INTFST and MAXDPT
 0.0  0.0                                       :Values of TOLFES and TOLIV
 3.0  24.0  13.0  9.0  20.0  19.0               :End of CVEC
 'Oatmeal'    110.0    4.0      2.0
 'Chicken'    205.0   32.0     12.0
 'Eggs'       160.0   13.0     54.0
 'Milk'       160.0    8.0    285.0
 'Pie'        420.0    4.0     22.0
 'Bacon'      260.0   14.0     80.0                      :End of matrix A
 1.0E+20                                                 :Value of BIGBND
 0.0  0.0  0.0  0.0  0.0  0.0
 'Energy'  2000.0  'Protein'  55.0  'Calcium'  800.0     :End of BL
 4.0  3.0  2.0  8.0  2.0  2.0  1.0E+20  1.0E+20  1.0E+20 :End of BU
 1    1    1    1    1    1                              :End of INTVAR
 0.0  0.0  0.0  0.0  0.0  0.0                            :End of X
 2200.0                                        :Change 'Energy' in RHS


h02ccfe.opt

Begin   Example options file for H02CCF
   Feasibility Phase Iteration Limit = 5  *  (Default = 70)
   Optimality Phase Iteration Limit = 10  *  (Default = 70)
End


h02cffe.opt

Begin
  Iteration Limit = 125 * (Default = 75)
  Print Level = 1      * (Default = 10)
End


h03abfe.d

H03ABF Example Program Data
    3    3
    1    5    6    4    4    4
    8    8   11
    5    8   14
    4    3   10


h03adfe.d

H03ADF Example Program Data
11  1  11  20  F   :Values of N, NS, NE, NNZ and DIRECT
6.0   6   8
1.0   8   9
2.0   9  11
4.0   2   5
1.0   3   4
6.0   1   3
4.0   3   6
1.0   4   6
2.0   2   3
3.0   4   7
5.0   1   2
7.0   6  10
1.0   5   6
4.0   8  11
9.0   5   9
1.0   6   7
8.0   7   9
4.0  10  11
2.0   9  10
5.0   1   4        :End of D, IROW, ICOL


m01cafe.d

M01CAF Example Program Data
16
1.3 5.9 4.1 2.3 0.5 5.8 1.3 6.5
2.3 0.5 6.5 9.9 2.1 1.1 1.2 8.6


m01cbfe.d

M01CBF Example Program Data
16
23 45 45 67 69 90 999 1
78 112 24 69 96 99 45 78


m01ccfe.d

M01CCF Example Program Data
11
A02AAF   289
A02ABF   523
A02ACF   531
C02ADF   169
C02AEF   599
C05AUF  1351
C05AVF   240
C05AWF   136
C05AXF   211
C05AYF   183
C05AZF  2181


m01dafe.d

M01DAF Example Program Data
12
5.3 4.6 7.8 1.7 5.3 9.9 3.2 4.3 7.8 4.5 1.2 7.6


m01dbfe.d

M01DBF Example Program Data
12
34 44 89 64 69 69 23 1 999 65 22 76


m01dcfe.d

M01DCF Example Program Data
11
A02AAF   289
A02ABF   523
A02ACF   531
C02ADF   169
C02AEF   599
C05AUF  1351
C05AVF   240
C05AWF   136
C05AXF   211
C05AYF   183
C05AZF  2181


m01defe.d

M01DEF Example Program Data
12 3
6.0 5.0 4.0
5.0 2.0 1.0
2.0 4.0 9.0
4.0 9.0 6.0
4.0 9.0 5.0
4.0 1.0 2.0
3.0 4.0 1.0
2.0 4.0 6.0
1.0 6.0 4.0
9.0 3.0 2.0
6.0 2.0 5.0
4.0 9.0 6.0


m01dffe.d

M01DFF Example Program Data
12 3
6 5 4
5 2 1
2 4 9
4 9 6
4 9 5
4 1 2
3 4 1
2 4 6
1 6 4
9 3 2
6 2 5
4 9 6


m01djfe.d

M01DJF Example Program Data
3 12
5.0 4.0 3.0 2.0 2.0 1.0 9.0 4.0 4.0 2.0 2.0 1.0
3.0 8.0 2.0 5.0 5.0 6.0 9.0 8.0 9.0 5.0 4.0 1.0
9.0 1.0 6.0 1.0 2.0 4.0 8.0 1.0 2.0 2.0 6.0 2.0


m01dkfe.d

M01DKF Example Program Data
3 12
5 4 3 2 2 1 9 4 4 2 2 1
3 8 2 5 5 6 9 8 9 5 4 1
9 1 6 1 2 4 8 1 2 2 6 2


m01dzfe.d

M01DZF Example Program Data
12
 2   3.0
 1   4.0
-1   6.0
 0   5.0
 2   2.0
-2   7.0
 0   4.0
 1   3.0
 1   5.0
-1   2.0
 1   0.0
 2   1.0


m01eafe.d

M01EAF Example Program Data
12 3 1
6.0 5.0 4.0
5.0 2.0 1.0
2.0 4.0 9.0
4.0 9.0 6.0
4.0 9.0 5.0
4.0 1.0 2.0
3.0 4.0 1.0
2.0 4.0 6.0
1.0 6.0 4.0
9.0 3.0 2.0
6.0 2.0 5.0
4.0 9.0 6.0


m01ebfe.d

M01EBF Example Program Data
12 3 1
6 5 4
5 2 1
2 4 9
4 9 6
4 9 5
4 1 2
3 4 1
2 4 6
1 6 4
9 3 2
6 2 5
4 9 6


m01ecfe.d

M01ECF Example Program Data
11
A02AAF   289
A02ABF   523
A02ACF   531
C02ADF   169
C02AEF   599
C05AUF  1351
C05AVF   240
C05AWF   136
C05AXF   211
C05AYF   183
C05AZF  2181


m01nafe.d

M01NAF Example Program Data
16                                                   : M2
0.5 0.6 1.1 1.2 1.3 1.3 2.1 2.3
2.3 4.1 5.8 5.9 6.5 6.5 8.6 9.9                      : RV
2.1                                                  : Item 1
0.4                                                  : Item 2
7.1                                                  : Item 3
10.0                                                 : Item 4


m01nbfe.d

M01NBF Example Program Data
16                                                   : M2
5 6 11 12 13 13 21 23
23 41 58 59 65 65 86 99                              : IV
21                                                   : Item 1
4                                                    : Item 2
71                                                   : Item 3
100                                                  : Item 4


m01ncfe.d

M01NCF Example Program Data
10                                                   : M2
A02AAF A02ABF A02ACF C02ADF C02AEF
C05AUF C05AVF C05AWF C05AXF C05AYF                   : CH
C02ADF                                               : Item 1
A01AAF                                               : Item 2
C04AYF                                               : Item 3
D01NBF                                               : Item 4


m01zafe.d

M01ZAF Example Program Data
12 3
6.0 5.0 4.0
5.0 2.0 1.0
2.0 4.0 9.0
4.0 9.0 6.0
4.0 9.0 5.0
4.0 1.0 2.0
3.0 4.0 1.0
2.0 4.0 6.0
1.0 6.0 4.0
9.0 3.0 2.0
6.0 2.0 5.0
4.0 9.0 6.0


m01zbfe.d

M01ZBF Example Program Data
12
5.3 4.6 7.8 1.7 5.3 9.9 3.2 4.3 7.8 4.5 1.2 7.6
  7   6  10   2   8  12   3   4  11   5   1   9


m01zcfe.d

M01ZCF Example Program Data
3 12 3
5.0 4.0 3.0 2.0 2.0 1.0 9.0 4.0 4.0 2.0 2.0 1.0
3.0 8.0 2.0 5.0 5.0 6.0 9.0 8.0 9.0 5.0 4.0 1.0
9.0 1.0 6.0 1.0 2.0 4.0 8.0 1.0 2.0 2.0 6.0 2.0


s01bafe.d

S01BAF Example Program Data
  2.50E+0
  1.25E-1
 -9.06E-1
  1.29E-3
 -7.83E-6
  1.00E-9


s01eafe.d

S01EAF Example Program Data
( 1.0, 0.0)
(-0.5, 2.0)
( 0.0,-2.0)
(-2.5,-1.5)


s07aafe.d

S07AAF Example Program Data
            -2.0
            -0.5
             1.0
             3.0
             1.5708


s09aafe.d

S09AAF Example Program Data
            -0.5
             0.1
             0.9


s09abfe.d

S09ABF Example Program Data
            -0.5
             0.1
             0.9


s10aafe.d

S10AAF Example Program Data
           -20.0
            -5.0
             0.5
             5.0


s10abfe.d

S10ABF Example Program Data
           -10.0
            -0.5
             0.0
             0.5
            25.0


s10acfe.d

S10ACF Example Program Data
           -10.0
            -0.5
             0.0
             0.5
            25.0


s11aafe.d

S11AAF Example Program Data
            -0.5
             0.0
             0.5
            -0.9999


s11abfe.d

S11ABF Example Program Data
            -2.0
            -0.5
             1.0
             6.0


s11acfe.d

S11ACF Example Program Data
             1.00
             2.0
             5.0
            10.0


s13aafe.d

S13AAF Example Program Data
             2.0
            -1.0


s13acfe.d

S13ACF Example Program Data
             0.2
             0.4
             0.6
             0.8
             1.0


s13adfe.d

S13ADF Example Program Data
             0.0
             0.2
             0.4
             0.6
             0.8
             1.0


s14aafe.d

S14AAF Example Program Data
             1.0
             1.25
             1.5
             1.75
             2.0
             5.0
             10.0
             -1.5


s14abfe.d

S14ABF Example Program Data
             1.0
             1.25
             1.5
             1.75
             2.0
             5.0
             10.0
             20.0
             1000.0


s14acfe.d

S14ACF Example Program Data
0.1
0.5
3.6
8.0


s14adfe.d

S14ADF Example Program Data
0.1
0.5
3.6
8.0


s14aefe.d

S14AEF Example Program Data
 2.5   2  : Values of X and K


s14affe.d

S14AFF Example Program Data
 (-1.5, 2.5)   1  : Values of Z and K


s14agfe.d

S14AGF Example Program Data
 (-1.5, 2.5)  : Value of Z


s14ahfe.d

S14AHF Example Program Data
             1.0
             1.25
             1.5
             1.75
             2.0
             5.0
             10.0
             20.0
             1000.0


s14bafe.d

S14BAF Example Program Data
  2.0   3.0
  7.0   1.0
  0.5  99.0
 20.0  21.0
 21.0  20.0


s14cbfe.d

S14CBF Example Program Data
0.2   1.0
0.4   1.0
0.6   1.0
0.8   1.0
1.0   0.2
1.0   0.4
1.0   1.0
2.0   2.0
3.0   3.0
4.0   4.0
5.0   5.0
6.0   2.0
6.0   3.0
6.0   4.0
6.0   5.0
6.0   6.0
7.0   7.0       : A, B


s14ccfe.d

S14CCF Example Program Data
5.3   10.1  0.01
5.3   10.1  0.02
5.3   10.1  0.03
5.3   10.1  0.04
5.3   10.1  0.05
5.3   10.1  0.06
5.3   10.1  0.07
5.3   10.1  0.08
5.3   10.1  0.09
5.3   10.1  0.10 : A,B,X


s15abfe.d

S15ABF Example Program Data
           -20.0
            -1.0
             0.0
             1.0
             2.0
            20.0


s15acfe.d

S15ACF Example Program Data
           -20.0
            -1.0
             0.0
             1.0
             2.0
            20.0


s15adfe.d

S15ADF Example Program Data
           -10.0
            -1.0
             0.0
             1.0
            10.0


s15aefe.d

S15AEF Example Program Data
            -6.0
            -4.5
            -1.0
             1.0
             4.5
             6.0


s15affe.d

S15AFF Example Program Data
            -2.0
            -0.5
             1.0
             1.5
             2.0
             5.0
            10.0


s15agfe.d

S15AGF Example Program Data
            -6.0
            -4.5
            -1.0
             1.0
             4.5
             6.0


s15ddfe.d

S15DDF Example Program Data
 ( 1.00E0,   0.00E0)       - Values for Z.
 (-3.01E0,   0.75E0)
 ( 2.75E0,  -1.52E0)
 (-1.33E0,  -0.54E0)


s17acfe.d

S17ACF Example Program Data
             0.5
             1.0
             3.0
             6.0
             8.0
             10.0
             1000.0


s17adfe.d

S17ADF Example Program Data
             0.5
             1.0
             3.0
             6.0
             8.0
             10.0
             1000.0


s17aefe.d

S17AEF Example Program Data
             0.0
             0.5
             1.0
             3.0
             6.0
             8.0
             10.0
             -1.0
             1000.0


s17affe.d

S17AFF Example Program Data
             0.0
             0.5
             1.0
             3.0
             6.0
             8.0
             10.0
             -1.0
             1000.0


s17agfe.d

S17AGF Example Program Data
             -10.0
             -1.0
             0.0
             1.0
             5.0
             10.0
             20.0


s17ahfe.d

S17AHF Example Program Data
             -10.0
             -1.0
             0.0
             1.0
             5.0
             10.0
             20.0


s17ajfe.d

S17AJF Example Program Data
             -10.0
             -1.0
             0.0
             1.0
             5.0
             10.0
             20.0


s17akfe.d

S17AKF Example Program Data
             -10.0
             -1.0
             0.0
             1.0
             5.0
             10.0
             20.0


s17alfe.d

S17ALF Example Program Data
 0.0  5  1 : Values of A, N and MODE


s17aqfe.d

S17AQF Example Program Data

7

0.5 1.0 3.0 6.0 8.0 10.0 1000.0


s17arfe.d

S17ARF Example Program Data

7

0.5 1.0 3.0 6.0 8.0 10.0 1000.0


s17asfe.d

S17ASF Example Program Data

9

0.0 0.5 1.0 3.0 6.0 8.0 10.0 -1.0 1000.0


s17atfe.d

S17ATF Example Program Data

9

0.0 0.5 1.0 3.0 6.0 8.0 10.0 -1.0 1000.0


s17aufe.d

S17AUF Example Program Data

7

-10.0 -1.0 0.0 1.0 5.0 10.0 20.0


s17avfe.d

S17AVF Example Program Data

7

-10.0 -1.0 0.0 1.0 5.0 10.0 20.0


s17awfe.d

S17AWF Example Program Data

7

-10.0 -1.0 0.0 1.0 5.0 10.0 20.0


s17axfe.d

S17AXF Example Program Data

7

-10.0 -1.0 0.0 1.0 5.0 10.0 20.0


s17dcfe.d

S17DCF Example Program Data
 0.00    ( 0.3,  0.4)    'U'
 2.30    ( 2.0,  0.0)    'U'
 2.12    (-1.0,  0.0)    'U'
 1.58    (-2.3,  5.6)    'U'
 1.58    (-2.3,  5.6)    'S'


s17defe.d

S17DEF Example Program Data
 0.00    ( 0.3,  0.4)    'U'
 2.30    ( 2.0,  0.0)    'U'
 2.12    (-1.0,  0.0)    'U'
 1.58    (-2.3,  5.6)    'U'
 1.58    (-2.3,  5.6)    'S'


s17dgfe.d

S17DGF Example Program Data
 'F'   ( 0.3,  0.4)    'U'
 'F'   ( 0.2,  0.0)    'U'
 'F'   ( 1.1, -6.6)    'U'
 'F'   ( 1.1, -6.6)    'S'
 'D'   (-1.0,  0.0)    'U'


s17dhfe.d

S17DHF Example Program Data
 'F'   ( 0.3,  0.4)    'U'
 'F'   ( 0.2,  0.0)    'U'
 'F'   ( 1.1, -6.6)    'U'
 'F'   ( 1.1, -6.6)    'S'
 'D'   (-1.0,  0.0)    'U'


s17dlfe.d

S17DLF Example Program Data
 1    0.00    ( 0.3,  0.4)    'U'
 1    2.30    ( 2.0,  0.0)    'U'
 1    2.12    (-1.0,  0.0)    'U'
 2    6.00    ( 3.1, -1.6)    'U'
 2    6.00    ( 3.1, -1.6)    'S'


s18acfe.d

S18ACF Example Program Data
             0.4
             0.6
             1.4
             1.6
             2.5
             3.5
             6.0
             8.0
             10.0
             1000.0


s18adfe.d

S18ADF Example Program Data
             0.4
             0.6
             1.4
             1.6
             2.5
             3.5
             6.0
             8.0
             10.0
             1000.0


s18aefe.d

S18AEF Example Program Data
             0.0
             0.5
             1.0
             3.0
             6.0
             8.0
             10.0
             15.0
             20.0
             -1.0


s18affe.d

S18AFF Example Program Data
             0.0
             0.5
             1.0
             3.0
             6.0
             8.0
             10.0
             15.0
             20.0
             -1.0


s18aqfe.d

S18AQF Example Program Data

10

0.4 0.6 1.4 1.6 2.5 3.5 6.0 8.0 10.0 1000.0


s18arfe.d

S18ARF Example Program Data

10

0.4 0.6 1.4 1.6 2.5 3.5 6.0 8.0 10.0 1000.0


s18asfe.d

S18ASF Example Program Data

10

0.0 0.5 1.0 3.0 6.0 8.0 10.0 15.0 20.0 -1.0


s18atfe.d

S18ATF Example Program Data

10

0.0 0.5 1.0 3.0 6.0 8.0 10.0 15.0 20.0 -1.0


s18ccfe.d

S18CCF Example Program Data
             0.4
             0.6
             1.4
             2.5
             10.0
             1000.0


s18cdfe.d

S18CDF Example Program Data
             0.4
             0.6
             1.4
             2.5
             10.0
             1000.0


s18cefe.d

S18CEF Example Program Data
             0.0
             0.5
             1.0
             3.0
             6.0
             10.0
             1000.0
             -1.0


s18cffe.d

S18CFF Example Program Data
             0.0
             0.5
             1.0
             3.0
             6.0
             10.0
             1000.0
             -1.0


s18cqfe.d

S18CQF Example Program Data

6

0.4 0.6 1.4 2.5 10.0 1000.0


s18crfe.d

S18CRF Example Program Data

6

0.4 0.6 1.4 2.5 10.0 1000.0


s18csfe.d

S18CSF Example Program Data

8

0.0 0.5 1.0 3.0 6.0 10.0 1000.0 -1.0


s18ctfe.d

S18CTF Example Program Data

8

0.0 0.5 1.0 3.0 6.0 10.0 1000.0 -1.0


s18dcfe.d

S18DCF Example Program Data
 0.00    ( 0.3,  0.4)    'U'
 2.30    ( 2.0,  0.0)    'U'
 2.12    (-1.0,  0.0)    'U'
 5.10    ( 3.0,  2.0)    'U'
 5.10    ( 3.0,  2.0)    'S'


s18defe.d

S18DEF Example Program Data
 0.00    ( 0.3, -0.4)    'U'
 2.30    ( 2.0,  0.0)    'U'
 2.12    (-1.0,  0.0)    'U'
 5.50    (-6.1,  9.8)    'U'
 5.50    (-6.1,  9.8)    'S'


s18gkfe.d

S18GKF Example Program Data
 ( 0.6,-0.8)   0.0   3 : Values of Z, A and NL


s19aafe.d

S19AAF Example Program Data
             0.1
             1.0
             2.5
             5.0
             10.0
             15.0
             -1.0


s19abfe.d

S19ABF Example Program Data
             0.1
             1.0
             2.5
             5.0
             10.0
             15.0
             -1.0


s19acfe.d

S19ACF Example Program Data
             0.1
             1.0
             2.5
             5.0
             10.0
             15.0


s19adfe.d

S19ADF Example Program Data
             0.0
             0.1
             1.0
             2.5
             5.0
             10.0
             15.0


s19anfe.d

S19ANF Example Program Data

7

0.1 1.0 2.5 5.0 10.0 15.0 -1.0


s19apfe.d

S19APF Example Program Data

7

0.1 1.0 2.5 5.0 10.0 15.0 -1.0


s19aqfe.d

S19AQF Example Program Data

6

0.1 1.0 2.5 5.0 10.0 15.0


s19arfe.d

S19ARF Example Program Data

7

0.0 0.1 1.0 2.5 5.0 10.0 15.0


s20acfe.d

S20ACF Example Program Data
             0.0
             0.5
             1.0
             2.0
             4.0
             5.0
             6.0
             8.0
             10.0
             -1.0
             1000.0


s20adfe.d

S20ADF Example Program Data
             0.0
             0.5
             1.0
             2.0
             4.0
             5.0
             6.0
             8.0
             10.0
             -1.0
             1000.0


s20aqfe.d

S20AQF Example Program Data

11

0.0 0.5 1.0 2.0 4.0 5.0 6.0 8.0 10.0 -1.0 1000.0


s20arfe.d

S20ARF Example Program Data

11

0.0 0.5 1.0 2.0 4.0 5.0 6.0 8.0 10.0 -1.0 1000.0


s21cafe.d

S21CAF Example Program Data
  0.2   0.3
  5.0  -1.0
 -0.5  -0.1
 10.0  11.0


s21cbfe.d

S21CBF Example Program Data
 (-2.0, 3.0)  0.25 : Values of Z and AK2


s21ccfe.d

S21CCF Example Program Data
 2  0.7  0.4  : Values of K, X and Q


s21dafe.d

S21DAF Example Program Data
 (1.2, 3.7)  0.5  1.0  1.0 : Values of Z, AKP, A and B


s22aafe.d

S22AAF Example Program Data
 1   0.5   2   3  : Values of MODE, X, M and NL


s30aafe.d

S30AAF Example Program Data
 'C'                 : Call = 'C', Put = 'P'
 55.0 0.3 0.1 0.0    : S, SIGMA, R, Q
 3 2                 : M, N
58.0
60.0
62.0                 : X(I), I = 1,2,...M
0.7
0.8                  : T(I), I = 1,2,...N


s30abfe.d

S30ABF Example Program Data
 'P'                 : Call = 'C', Put = 'P'
 55.0 0.3 0.1 0.0    : S, SIGMA, R, Q
 1 1                 : M, N
60.0                 : X(I), I = 1,2,...M
0.7                  : T(I), I = 1,2,...N


s30bafe.d

S30BAF Example Program Data
 'C'                  : Call = 'C', Put = 'P'
 120.0 0.3 0.1 0.06   : S, SIGMA, R, Q
 1 1                  : M, N
 100.0                : SM(I), I = 1,2,...M
 0.5                  : T(I), I = 1,2,...N


s30bbfe.d

S30BBF Example Program Data
 'P'                  : Call = 'C', Put = 'P'
 87.0 0.3 0.06 0.04   : S, SIGMA, R, Q
 1 1                  : M, N
 100.0                : SM(I), I = 1,2,...M
 0.5                  : T(I), I = 1,2,...N


s30cafe.d

S30CAF Example Program Data
 'P'                      : Call = 'C', Put = 'P'
 100.0 10.0 0.35 0.06 0.0 : S, K, SIGMA, R, Q
 1 1                      : M, N
 80.0                     : X(I), I = 1,2,...M
 0.75                     : T(I), I = 1,2,...N


s30cbfe.d

S30CBF Example Program Data
 'C'                      : Call = 'C', Put = 'P'
 110.0 5.0 0.35 0.05 0.04 : S, K, SIGMA, R, Q
 1 1                      : M, N
 87.0                     : X(I), I = 1,2,...M
 0.75                     : T(I), I = 1,2,...N


s30ccfe.d

S30CCF Example Program Data
 'P'                 : Call = 'C', Put = 'P'
 70.0 0.27 0.07 0.05 : S, SIGMA, R, Q
 1 1                 : M, N
 65.0                : X(I), I = 1,2,...M
 0.5                 : T(I), I = 1,2,...N


s30cdfe.d

S30CDF Example Program Data
 'P'                 : Call = 'C', Put = 'P'
 70.0 0.15 0.05 0.03 : S, SIGMA, R, Q
 1 1                 : M, N
 65.0                : X(I), I = 1,2,...M
 0.8                 : T(I), I = 1,2,...N


s30fafe.d

S30FAF Example Program Data
 'P'  'DI'                    : Call = 'C', Put = 'P', Type
 100.0 95.0 3.0 0.3 0.08 0.04 : S, H, K, SIGMA, R, Q
 1 1                          : M, N
 100.0                        : X(I), I = 1,2,...M
 0.5                          : T(I), I = 1,2,...N


s30jafe.d

S30JAF Example Program Data
 'C'                     : Call = 'C', Put = 'P'
 3.0                     : LAMBDA (jumps)
 45.0 0.25 0.1 0.4       : S, SIGMA, R, JVOL
 1 1                     : M, N
 55.0                    : X(I), I = 1,2,...M
 0.25                    : T(I), I = 1,2,...N


s30jbfe.d

S30JBF Example Program Data
 'C'                     : Call = 'C', Put = 'P'
 5.0                     : LAMBDA (jumps)
 100.0 0.25 0.08 0.25    : S, SIGMA, R, JVOL
 2 1                     : M, N
 80.0
 90.0                    : X(I), I = 1,2,...M
 0.5                     : T(I), I = 1,2,...N


s30nafe.d

S30NAF Example Program Data
 'C'                         : Call = 'C', Put = 'P'
 100.0 0.05 0.0              : S, R, Q
 2.0 0.01 0.01 0.225 0.0 1.0 : KAPPA, ETA, VAR0, SIGMAV, CORR, GRISK
 1 1                         : M, N
 100.0                       : X(I), I = 1,2,...N
 0.5                         : T(I), I = 1,2,...M


s30nbfe.d

S30NBF Example Program Data
 'C'                         : Call = 'C', Put = 'P'
 100.0 0.025 0.0              : S, R, Q
 1.5768 0.0398 0.0175 0.5751 -0.5711 1.0 : KAPPA, ETA, VAR0, SIGMAV, CORR, GRISK
 1 1                         : M, N
 100.0                       : X(I), I = 1,2,...N
 1.0                         : T(I), I = 1,2,...M


s30ncfe.d

S30NCF Example Program Data
 'C'                         : Call = 'C', Put = 'P'
 1 2                         : M, NUMTS
 100.0 1.0 1.0               : FWD, DISC, VAR0
 100.0                       : X(I), I = 1,2,...M
 0.35 0.65                   : TS(I), I = 1,2,...NUMTS
 1.0                         : T
 2.25 1.5                    : ALPHA(I), I = 1,2,...NUMTS
 -0.05 0.1                   : CORR(I), I = 1,2,...NUMTS
 2.0 1.5                     : LAMBDA(I), I = 1,2,...NUMTS
 0.04 0.13                   : SIGMAT(I), I = 1,2,...NUMTS


s30qcfe.d

S30QCF Example Program Data
 'C'                 : Call = 'C', Put = 'P'
 110.0 0.2 0.08 0.12 : S, SIGMA, R, Q
 1 1                 : M, N
 100.0               : X(I), I = 1,2,...M
 0.25                : T(I), I = 1,2,...N


s30safe.d

S30SAF Example Program Data
 'P'                : Call = 'C', Put = 'P'
 80.0 0.2 0.05 0.08 : S, SIGMA, R, B
 1 1                : M, N
 85.0               : X(I), I = 1,2,...M
 0.25               : T(I), I = 1,2,...N


s30sbfe.d

S30SBF Example Program Data
 'C'                : Call = 'C', Put = 'P'
 80.0 0.2 0.05 0.08 : S, SIGMA, R, B
 1 1                : M, N
 97.0               : X(I), I = 1,2,...M
 0.25               : T(I), I = 1,2,...N


x03aafe.d

X03AAF Example Program Data
   -2   -3    7
    2   -5    3
   -9    1    0
    8   -4   -2


x03abfe.d

X03ABF Example Program Data
 (-1.0, 0.0) ( 0.0, -1.0) (1.0,  0.0)
 ( 2.0, 3.0) ( 0.0,  1.0) (0.0,  2.0)
 ( 0.0, 0.0) (-1.0, -1.0) (1.0, -2.0)
 ( 0.0, 1.0) ( 1.0, -1.0) (0.0, -1.0)


x04bbfe.d

X04BBF Example Program Data
 20  2.996


x05abfe.d

X05ABF Example Program Data
1789 7 14 13 11 48 320


x05acfe.d

X05ACF Example Program Data
'Thu 27th April 1989 13:15:21.320'
'Wed 26th April 1989 11:23:14.130'


a00aafe.f90

    Program a00aafe

!     A00AAF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: a00aaf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nout = 6
!     .. Executable Statements ..
      Write (nout,*) 'A00AAF Example Program Results'

      Write (nout,*)
      Flush (nout)

      Call a00aaf

    End Program a00aafe


a00acfe.f90

    Program a00acfe

!     A00ACF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: a00acf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nout = 6
!     .. Local Scalars ..
      Logical                          :: lmok
!     .. Executable Statements ..
      Write (nout,*) 'A00ACF Example Program Results'

      Write (nout,*)

      lmok = a00acf()

      If (lmok) Then
        Write (nout,*) 'A valid licence key is available'
      Else
        Write (nout,*) 'No valid licence key was found'
      End If

    End Program a00acfe


a00adfe.f90

    Program a00adfe

!     A00ADF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: a00adf, x05aaf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: msglen = 15, nout = 6
!     .. Local Scalars ..
      Integer                          :: i, mkmaj, mkmin
      Logical                          :: licval
      Character (80)                   :: fcomp, hdware, impl, opsys, pcode,   &
                                          prec, vend
!     .. Local Arrays ..
      Integer                          :: itime(7)
      Character (102)                  :: msg(msglen)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: trim
!     .. Executable Statements ..
      Write (nout,*) 'A00ADF Example Program Results'

      Call a00adf(impl,prec,pcode,mkmaj,mkmin,hdware,opsys,fcomp,vend,licval)

!     Print implementation details.

      Write (nout,*)

      msg(1) = '*** Start of NAG Library implementation details ***'
      msg(2) = ''
      msg(3) = 'Implementation title: ' // impl
      msg(4) = '           Precision: ' // prec
      msg(5) = '        Product Code: ' // pcode

      If (mkmin<10) Then
        Write (msg(6),99999) mkmaj, mkmin
      Else
        Write (msg(6),99998) mkmaj, mkmin
      End If

      If (vend=='(self-contained)') Then
        msg(7) = '      Vendor Library: None'
      Else
        msg(7) = '      Vendor Library: ' // vend
      End If

      msg(8) = 'Applicable to:'
      msg(9) = '            hardware: ' // hdware
      msg(10) = '    operating system: ' // opsys
      msg(11) = '    Fortran compiler: ' // fcomp
      msg(12) = 'and compatible systems.'

      If (.Not. licval) Then
        msg(13) = '       Licence query: Unsuccessful'
      Else
        msg(13) = '       Licence query: Successful'
      End If

      msg(14) = ''
      msg(15) = '*** End of NAG Library implementation details ***'

      Do i = 1, msglen
        Write (nout,'(A)') trim(msg(i))
      End Do

!     Print the date.

      Write (nout,*)
      Write (nout,*) 'This program was run on the following date:'

      Call x05aaf(itime)

      Write (nout,99997) itime

      Write (nout,*) '*** ----------------------------------------- ***'

99999 Format ('                Mark: ',I2,'.',I1,1X,A)
99998 Format ('                Mark: ',I2,'.',I2,1X,A)
99997 Format (3X,I4.4,2I2.2,'-',3(I2.2,':'),I3.3)
    End Program a00adfe


a02aafe.f90

    Program a02aafe

!     A02AAF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: a02aaf, nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: xi, xr, yi, yr
!     .. Executable Statements ..
      Write (nout,*) 'A02AAF Example Program Results'

!     Skip heading in data file
      Read (nin,*)

      Read (nin,*) xr, xi

!     Compute square root of (XR,XI) and return in (YR,YI)

      Call a02aaf(xr,xi,yr,yi)

      Write (nout,*)
      Write (nout,*) '   XR    XI      YR       YI'
      Write (nout,99999) xr, xi, yr, yi

99999 Format (1X,2F6.1,2F9.4)
    End Program a02aafe


a02abfe.f90

    Program a02abfe

!     A02ABF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: a02abf, nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: xi, xr, y
!     .. Executable Statements ..
      Write (nout,*) 'A02ABF Example Program Results'

!     Skip heading in data file
      Read (nin,*)

      Read (nin,*) xr, xi

!     Return absolute value of (XR,XI)

      y = a02abf(xr,xi)

      Write (nout,*)
      Write (nout,*) '   XR    XI       Y'
      Write (nout,99999) xr, xi, y

99999 Format (1X,2F6.1,F9.4)
    End Program a02abfe


a02acfe.f90

    Program a02acfe

!     A02ACF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: a02acf, nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: xi, xr, yi, yr, zi, zr
!     .. Executable Statements ..
      Write (nout,*) 'A02ACF Example Program Results'

!     Skip heading in data file
      Read (nin,*)

      Read (nin,*) xr, xi, yr, yi

!     Compute (XR,XI)/(YR,YI) = (ZR,ZI)

      Call a02acf(xr,xi,yr,yi,zr,zi)

      Write (nout,*)
      Write (nout,*) '   XR    XI    YR    YI      ZR       ZI'
      Write (nout,99999) xr, xi, yr, yi, zr, zi

99999 Format (1X,4F6.1,2F9.4)
    End Program a02acfe


c02affe.f90

!   C02AFF Example Program Text
!   Mark 26 Release. NAG Copyright 2016.

    Module c02affe_mod

!     C02AFF Example Program Module:
!            Parameters

!     .. Implicit None Statement ..
      Implicit None
!     .. Accessibility Statements ..
      Private
!     .. Parameters ..
      Integer, Parameter, Public       :: nin = 5, nout = 6
      Logical, Parameter, Public       :: scal = .True.
    End Module c02affe_mod
    Program c02affe

!     C02AFF Example Main Program

!     .. Use Statements ..
      Use c02affe_mod, Only: nout
!     .. Implicit None Statement ..
      Implicit None
!     .. Executable Statements ..
      Write (nout,*) 'C02AFF Example Program Results'

      Call ex1

      Call ex2

    Contains
      Subroutine ex1

!       .. Use Statements ..
        Use nag_library, Only: c02aff, nag_wp
        Use c02affe_mod, Only: nin, scal
!       .. Local Scalars ..
        Integer                        :: i, ifail, n
!       .. Local Arrays ..
        Real (Kind=nag_wp), Allocatable :: a(:,:), w(:), z(:,:)
!       .. Executable Statements ..
        Write (nout,*)
        Write (nout,*)
        Write (nout,*) 'Example 1'

!       Skip heading in data file
        Read (nin,*)
        Read (nin,*)
        Read (nin,*)

        Read (nin,*) n
        Allocate (a(2,0:n),w(4*(n+1)),z(2,n))

        Read (nin,*)(a(1,i),a(2,i),i=0,n)

        ifail = 0
        Call c02aff(a,n,scal,z,w,ifail)

        Write (nout,*)
        Write (nout,99999) 'Degree of polynomial = ', n
        Write (nout,*)
        Write (nout,*) 'Computed roots of polynomial'
        Write (nout,*)

        Do i = 1, n
          Write (nout,99998) 'z = ', z(1,i), z(2,i), '*i'
        End Do

99999   Format (1X,A,I4)
99998   Format (1X,A,1P,E12.4,Sp,E12.4,A)
      End Subroutine ex1
      Subroutine ex2

!       .. Use Statements ..
        Use nag_library, Only: a02abf, c02aff, nag_wp, x02ajf, x02alf
        Use c02affe_mod, Only: nin, scal
!       .. Local Scalars ..
        Real (Kind=nag_wp)             :: deltac, deltai, di, eps, epsbar, f,  &
                                          r1, r2, r3, rmax
        Integer                        :: i, ifail, j, jmin, n
!       .. Local Arrays ..
        Real (Kind=nag_wp), Allocatable :: a(:,:), abar(:,:), r(:), w(:),      &
                                          z(:,:), zbar(:,:)
        Integer, Allocatable           :: m(:)
!       .. Intrinsic Procedures ..
        Intrinsic                      :: abs, max, min
!       .. Executable Statements ..
        Write (nout,*)
        Write (nout,*)
        Write (nout,*) 'Example 2'

!       Skip heading in data file
        Read (nin,*)
        Read (nin,*)

        Read (nin,*) n
        Allocate (a(2,0:n),abar(2,0:n),r(n),w(4*(n+1)),z(2,n),zbar(2,n),m(n))

!       Read in the coefficients of the original polynomial.

        Read (nin,*)(a(1,i),a(2,i),i=0,n)

!       Compute the roots of the original polynomial.

        ifail = 0
        Call c02aff(a,n,scal,z,w,ifail)

!       Form the coefficients of the perturbed polynomial.

        eps = x02ajf()
        epsbar = 3.0E0_nag_wp*eps

        Do i = 0, n

          If (a(1,i)/=0.0E0_nag_wp) Then
            f = 1.0E0_nag_wp + epsbar
            epsbar = -epsbar
            abar(1,i) = f*a(1,i)

            If (a(2,i)/=0.0E0_nag_wp) Then
              abar(2,i) = f*a(2,i)
            Else
              abar(2,i) = 0.0E0_nag_wp
            End If

          Else
            abar(1,i) = 0.0E0_nag_wp

            If (a(2,i)/=0.0E0_nag_wp) Then
              f = 1.0E0_nag_wp + epsbar
              epsbar = -epsbar
              abar(2,i) = f*a(2,i)
            Else
              abar(2,i) = 0.0E0_nag_wp
            End If
          End If

        End Do

!       Compute the roots of the perturbed polynomial.

        ifail = 0
        Call c02aff(abar,n,scal,zbar,w,ifail)

!       Perform error analysis.

!       Initialize markers to 0 (unmarked).

        m(1:n) = 0

        rmax = x02alf()

!       Loop over all unperturbed roots (stored in Z).

        Do i = 1, n
          deltai = rmax
          r1 = a02abf(z(1,i),z(2,i))

!         Loop over all perturbed roots (stored in ZBAR).

          Do j = 1, n

!           Compare the current unperturbed root to all unmarked
!           perturbed roots.

            If (m(j)==0) Then
              r2 = a02abf(zbar(1,j),zbar(2,j))
              deltac = abs(r1-r2)

              If (deltac<deltai) Then
                deltai = deltac
                jmin = j
              End If

            End If

          End Do

!         Mark the selected perturbed root.

          m(jmin) = 1

!         Compute the relative error.

          If (r1/=0.0E0_nag_wp) Then
            r3 = a02abf(zbar(1,jmin),zbar(2,jmin))
            di = min(r1,r3)
            r(i) = max(deltai/max(di,deltai/rmax),eps)
          Else
            r(i) = 0.0E0_nag_wp
          End If

        End Do

        Write (nout,*)
        Write (nout,99999) 'Degree of polynomial = ', n
        Write (nout,*)
        Write (nout,*) 'Computed roots of polynomial   ', '  Error estimates'
        Write (nout,*) '                            ',                         &
          '   (machine-dependent)'
        Write (nout,*)

        Do i = 1, n
          Write (nout,99998) 'z = ', z(1,i), z(2,i), '*i', r(i)
        End Do

99999   Format (1X,A,I4)
99998   Format (1X,A,1P,E12.4,Sp,E12.4,A,5X,Ss,E9.1)
      End Subroutine ex2
    End Program c02affe


c02agfe.f90

!   C02AGF Example Program Text
!   Mark 26 Release. NAG Copyright 2016.

    Module c02agfe_mod

!     C02AGF Example Program Module:
!            Parameters

!     .. Implicit None Statement ..
      Implicit None
!     .. Accessibility Statements ..
      Private
!     .. Parameters ..
      Integer, Parameter, Public       :: nin = 5, nout = 6
      Logical, Parameter, Public       :: scal = .True.
    End Module c02agfe_mod
    Program c02agfe

!     C02AGF Example Main Program

!     .. Use Statements ..
      Use c02agfe_mod, Only: nout
!     .. Implicit None Statement ..
      Implicit None
!     .. Executable Statements ..
      Write (nout,*) 'C02AGF Example Program Results'

      Call ex1

      Call ex2

    Contains
      Subroutine ex1

!       .. Use Statements ..
        Use nag_library, Only: c02agf, nag_wp
        Use c02agfe_mod, Only: nin, scal
!       .. Local Scalars ..
        Real (Kind=nag_wp)             :: zi, zr
        Integer                        :: i, ifail, n, nroot
!       .. Local Arrays ..
        Real (Kind=nag_wp), Allocatable :: a(:), w(:), z(:,:)
!       .. Intrinsic Procedures ..
        Intrinsic                      :: abs
!       .. Executable Statements ..
        Write (nout,*)
        Write (nout,*)
        Write (nout,*) 'Example 1'

!       Skip heading in data file
        Read (nin,*)
        Read (nin,*)
        Read (nin,*)

        Read (nin,*) n
        Allocate (a(0:n),w(2*(n+1)),z(2,n))

        Read (nin,*)(a(i),i=0,n)

        Write (nout,*)
        Write (nout,99999) 'Degree of polynomial = ', n

        ifail = 0
        Call c02agf(a,n,scal,z,w,ifail)

        Write (nout,99998) 'Computed roots of polynomial'

        nroot = 1

        Do While (nroot<=n)

          zr = z(1,nroot)
          zi = z(2,nroot)
          If (zi==0.0E0_nag_wp) Then
            Write (nout,99997) 'z = ', zr
            nroot = nroot + 1
          Else
            Write (nout,99997) 'z = ', zr, ' +/- ', abs(zi), '*i'
            nroot = nroot + 2
          End If

        End Do

99999   Format (/,1X,A,I4)
99998   Format (/,1X,A,/)
99997   Format (1X,A,1P,E12.4,A,E12.4,A)
      End Subroutine ex1
      Subroutine ex2

!       .. Use Statements ..
        Use nag_library, Only: a02abf, c02agf, nag_wp, x02ajf, x02alf
        Use c02agfe_mod, Only: nin, scal
!       .. Local Scalars ..
        Real (Kind=nag_wp)             :: deltac, deltai, di, eps, epsbar, f,  &
                                          r1, r2, r3, rmax
        Integer                        :: i, ifail, j, jmin, n
!       .. Local Arrays ..
        Real (Kind=nag_wp), Allocatable :: a(:), abar(:), r(:), w(:), z(:,:),  &
                                          zbar(:,:)
        Integer, Allocatable           :: m(:)
!       .. Intrinsic Procedures ..
        Intrinsic                      :: abs, max, min
!       .. Executable Statements ..
        Write (nout,*)
        Write (nout,*)
        Write (nout,*) 'Example 2'

!       Skip heading in data file
        Read (nin,*)
        Read (nin,*)

        Read (nin,*) n
        Allocate (a(0:n),abar(0:n),r(n),w(2*(n+1)),z(2,n),zbar(2,n),m(n))

!       Read in the coefficients of the original polynomial.

        Read (nin,*)(a(i),i=0,n)

!       Compute the roots of the original polynomial.

        ifail = 0
        Call c02agf(a,n,scal,z,w,ifail)

!       Form the coefficients of the perturbed polynomial.

        eps = x02ajf()
        epsbar = 3.0_nag_wp*eps

        Do i = 0, n

          If (a(i)/=0.0_nag_wp) Then
            f = 1.0_nag_wp + epsbar
            epsbar = -epsbar
            abar(i) = f*a(i)
          Else
            abar(i) = 0.0E0_nag_wp
          End If

        End Do

!       Compute the roots of the perturbed polynomial.

        ifail = 0
        Call c02agf(abar,n,scal,zbar,w,ifail)

!       Perform error analysis.

!       Initialize markers to 0 (unmarked).

        m(1:n) = 0

        rmax = x02alf()

!       Loop over all unperturbed roots (stored in Z).

        Do i = 1, n
          deltai = rmax
          r1 = a02abf(z(1,i),z(2,i))

!         Loop over all perturbed roots (stored in ZBAR).

          Do j = 1, n

!           Compare the current unperturbed root to all unmarked
!           perturbed roots.

            If (m(j)==0) Then
              r2 = a02abf(zbar(1,j),zbar(2,j))
              deltac = abs(r1-r2)

              If (deltac<deltai) Then
                deltai = deltac
                jmin = j
              End If

            End If

          End Do

!         Mark the selected perturbed root.

          m(jmin) = 1

!         Compute the relative error.

          If (r1/=0.0E0_nag_wp) Then
            r3 = a02abf(zbar(1,jmin),zbar(2,jmin))
            di = min(r1,r3)
            r(i) = max(deltai/max(di,deltai/rmax),eps)
          Else
            r(i) = 0.0_nag_wp
          End If

        End Do

        Write (nout,*)
        Write (nout,99999) 'Degree of polynomial = ', n
        Write (nout,*)
        Write (nout,*) 'Computed roots of polynomial   ', '  Error estimates'
        Write (nout,*) '                            ',                         &
          '   (machine-dependent)'
        Write (nout,*)

        Do i = 1, n
          Write (nout,99998) 'z = ', z(1,i), z(2,i), '*i', r(i)
        End Do

99999   Format (1X,A,I4)
99998   Format (1X,A,1P,E12.4,Sp,E12.4,A,5X,Ss,E9.1)
      End Subroutine ex2
    End Program c02agfe


c02ahfe.f90

    Program c02ahfe

!     C02AHF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: c02ahf, nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: ai, ar, bi, br, ci, cr
      Integer                          :: ifail
!     .. Local Arrays ..
      Real (Kind=nag_wp)               :: zlg(2), zsm(2)
!     .. Executable Statements ..
      Write (nout,*) 'C02AHF Example Program Results'

!     Skip heading in data file
      Read (nin,*)

      Read (nin,*) ar, ai, br, bi, cr, ci

      ifail = -1
      Call c02ahf(ar,ai,br,bi,cr,ci,zsm,zlg,ifail)

      If (ifail==0) Then
        Write (nout,*)
        Write (nout,*) 'Roots of quadratic equation'
        Write (nout,*)
        Write (nout,99999) 'z = ', zsm(1), zsm(2), '*i'
        Write (nout,99999) 'z = ', zlg(1), zlg(2), '*i'
      End If

99999 Format (1X,A,1P,E12.4,Sp,E14.4,A)
    End Program c02ahfe


c02ajfe.f90

    Program c02ajfe

!     C02AJF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: c02ajf, nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: a, b, c
      Integer                          :: ifail
!     .. Local Arrays ..
      Real (Kind=nag_wp)               :: zlg(2), zsm(2)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: abs
!     .. Executable Statements ..
      Write (nout,*) 'C02AJF Example Program Results'

!     Skip heading in data file
      Read (nin,*)

      Read (nin,*) a, b, c

      ifail = -1
      Call c02ajf(a,b,c,zsm,zlg,ifail)

      If (ifail==0) Then
        Write (nout,*)
        Write (nout,*) 'Roots of quadratic equation'
        Write (nout,*)

        If (zsm(2)==0.0E0_nag_wp) Then

!         2 real roots.

          Write (nout,99999) 'z = ', zsm(1)
          Write (nout,99999) 'z = ', zlg(1)
        Else

!         2 complex roots.

          Write (nout,99998) 'z = ', zsm(1), ' +/- ', abs(zsm(2)), '*i'
        End If

      End If

99999 Format (1X,A,1P,E12.4)
99998 Format (1X,A,1P,E12.4,A,E12.4,A)
    End Program c02ajfe


c02akfe.f90

    Program c02akfe

!     C02AKF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: c02akf, nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: r, s, t, u
      Integer                          :: i, ifail
!     .. Local Arrays ..
      Real (Kind=nag_wp)               :: errest(3), zeroi(3), zeror(3)
!     .. Executable Statements ..
      Write (nout,*) 'C02AKF Example Program Results'

!     Skip heading in data file
      Read (nin,*)

      Read (nin,*) u, r, s, t

      ifail = 0
      Call c02akf(u,r,s,t,zeror,zeroi,errest,ifail)

      Write (nout,*)
      Write (nout,*) ' Roots of cubic equation     ',                          &
        '        Error estimates'
      Write (nout,*) '                             ',                          &
        '      (machine-dependent)'
      Write (nout,*)

      Do i = 1, 3
        Write (nout,99999) ' z = ', zeror(i), zeroi(i), '*i', errest(i)
      End Do

99999 Format (1X,A,1P,E12.4,Sp,E12.4,A,8X,Ss,E9.1)
    End Program c02akfe


c02alfe.f90

    Program c02alfe

!     C02ALF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: c02alf, nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: a, b, c, d, e
      Integer                          :: i, ifail
!     .. Local Arrays ..
      Real (Kind=nag_wp)               :: errest(4), zeroi(4), zeror(4)
!     .. Executable Statements ..
      Write (nout,*) 'C02ALF Example Program Results'

!     Skip heading in data file
      Read (nin,*)

      Read (nin,*) e, a, b, c, d

      ifail = 0
      Call c02alf(e,a,b,c,d,zeror,zeroi,errest,ifail)

      Write (nout,*)
      Write (nout,*) ' Roots of quartic equation   ',                          &
        '        Error estimates'
      Write (nout,*) '                             ',                          &
        '      (machine-dependent)'
      Write (nout,*)

      Do i = 1, 4
        Write (nout,99999) ' z = ', zeror(i), zeroi(i), '*i', errest(i)
      End Do

99999 Format (1X,A,1P,E12.4,Sp,E12.4,A,8X,Ss,E9.1)
    End Program c02alfe


c02amfe.f90

    Program c02amfe

!     C02AMF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: c02amf, nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Complex (Kind=nag_wp)            :: r, s, t, u
      Integer                          :: i, ifail
!     .. Local Arrays ..
      Real (Kind=nag_wp)               :: errest(3), zeroi(3), zeror(3)
!     .. Executable Statements ..
      Write (nout,*) 'C02AMF Example Program Results'

!     Skip heading in data file
      Read (nin,*)

      Read (nin,*) u, r, s, t

      ifail = 0
      Call c02amf(u,r,s,t,zeror,zeroi,errest,ifail)

      Write (nout,*)
      Write (nout,*) ' Roots of cubic equation     ',                          &
        '        Error estimates'
      Write (nout,*) '                             ',                          &
        '      (machine-dependent)'
      Write (nout,*)

      Do i = 1, 3
        Write (nout,99999) ' z = ', zeror(i), zeroi(i), '*i', errest(i)
      End Do

99999 Format (1X,A,1P,E12.4,Sp,E12.4,A,8X,Ss,E9.1)
    End Program c02amfe


c02anfe.f90

    Program c02anfe

!     C02ANF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: c02anf, nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Complex (Kind=nag_wp)            :: a, b, c, d, e
      Integer                          :: i, ifail
!     .. Local Arrays ..
      Real (Kind=nag_wp)               :: errest(4), zeroi(4), zeror(4)
!     .. Executable Statements ..
      Write (nout,*) 'C02ANF Example Program Results'

!     Skip heading in data file
      Read (nin,*)

      Read (nin,*) e, a, b, c, d

      ifail = 0
      Call c02anf(e,a,b,c,d,zeror,zeroi,errest,ifail)

      Write (nout,*)
      Write (nout,*) ' Roots of quartic equation   ',                          &
        '        Error estimates'
      Write (nout,*) '                             ',                          &
        '      (machine-dependent)'
      Write (nout,*)

      Do i = 1, 4
        Write (nout,99999) ' z = ', zeror(i), zeroi(i), '*i', errest(i)
      End Do

99999 Format (1X,A,1P,E12.4,Sp,E12.4,A,8X,Ss,E9.1)
    End Program c02anfe


c05aufe.f90

!   C05AUF Example Program Text
!   Mark 26 Release. NAG Copyright 2016.

    Module c05aufe_mod

!     C05AUF Example Program Module:
!            Parameters and User-defined Routines

!     .. Use Statements ..
      Use nag_library, Only: nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Accessibility Statements ..
      Private
      Public                           :: f
!     .. Parameters ..
      Integer, Parameter, Public       :: nout = 6
    Contains
      Function f(x,iuser,ruser)

!       .. Function Return Value ..
        Real (Kind=nag_wp)             :: f
!       .. Scalar Arguments ..
        Real (Kind=nag_wp), Intent (In) :: x
!       .. Array Arguments ..
        Real (Kind=nag_wp), Intent (Inout) :: ruser(*)
        Integer, Intent (Inout)        :: iuser(*)
!       .. Intrinsic Procedures ..
        Intrinsic                      :: exp
!       .. Executable Statements ..
        f = x - exp(-x)

        Return

      End Function f
    End Module c05aufe_mod
    Program c05aufe

!     C05AUF Example Main Program

!     .. Use Statements ..
      Use nag_library, Only: c05auf, nag_wp
      Use c05aufe_mod, Only: f, nout
!     .. Implicit None Statement ..
      Implicit None
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: a, b, eps, eta, h, x
      Integer                          :: ifail
!     .. Local Arrays ..
      Real (Kind=nag_wp)               :: ruser(1)
      Integer                          :: iuser(1)
!     .. Executable Statements ..
      Write (nout,*) 'C05AUF Example Program Results'

      x = 1.0E0_nag_wp
      h = 0.1E0_nag_wp
      eps = 1.0E-5_nag_wp
      eta = 0.0E0_nag_wp

      ifail = -1
      Call c05auf(x,h,eps,eta,f,a,b,iuser,ruser,ifail)

      Write (nout,*)

      Select Case (ifail)
      Case (0)
        Write (nout,99999) 'Root is ', x
        Write (nout,99998) 'Interval searched is [', a, ',', b, ']'
      Case (3,4)
        Write (nout,99999) 'Final value = ', x
      End Select

99999 Format (1X,A,F13.5)
99998 Format (1X,A,2(F8.5,A))
    End Program c05aufe


c05avfe.f90

    Program c05avfe

!     C05AVF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: c05avf, nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: boundl, boundu, fx, h, x, y
      Integer                          :: ifail, ind
!     .. Local Arrays ..
      Real (Kind=nag_wp)               :: c(11)
!     .. Executable Statements ..
      Write (nout,*) 'C05AVF Example Program Results'

      Write (nout,*)

      x = 3.0E0_nag_wp
      h = 0.1E0_nag_wp
      boundl = 0.0E0_nag_wp
      boundu = 4.0E0_nag_wp
      ind = 1
      ifail = -1

revcomm: Do

        Call c05avf(x,fx,h,boundl,boundu,y,c,ind,ifail)

        If (ind==0) Then
          Exit revcomm
        End If

        fx = x*x - 3.0E0_nag_wp*x + 2.0E0_nag_wp
      End Do revcomm

      If (ifail==0) Then
        Write (nout,*) 'Interval containing root is [X,Y], where'
        Write (nout,99999) 'X =', x, '   Y =', y
        Write (nout,*) 'Values of f at X and Y are'
        Write (nout,99999) 'f(X) =', fx, '   f(Y) =', c(1)
      End If

99999 Format (1X,2(A,F12.4))
    End Program c05avfe


c05awfe.f90

!   C05AWF Example Program Text
!   Mark 26 Release. NAG Copyright 2016.

    Module c05awfe_mod

!     C05AWF Example Program Module:
!            Parameters and User-defined Routines

!     .. Use Statements ..
      Use nag_library, Only: nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Accessibility Statements ..
      Private
      Public                           :: f
!     .. Parameters ..
      Integer, Parameter, Public       :: nout = 6
    Contains
      Function f(x,iuser,ruser)

!       .. Function Return Value ..
        Real (Kind=nag_wp)             :: f
!       .. Scalar Arguments ..
        Real (Kind=nag_wp), Intent (In) :: x
!       .. Array Arguments ..
        Real (Kind=nag_wp), Intent (Inout) :: ruser(*)
        Integer, Intent (Inout)        :: iuser(*)
!       .. Intrinsic Procedures ..
        Intrinsic                      :: exp
!       .. Executable Statements ..
        f = exp(-x) - x

        Return

      End Function f
    End Module c05awfe_mod
    Program c05awfe

!     C05AWF Example Main Program

!     .. Use Statements ..
      Use nag_library, Only: c05awf, nag_wp
      Use c05awfe_mod, Only: f, nout
!     .. Implicit None Statement ..
      Implicit None
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: eps, eta, x
      Integer                          :: ifail, k, nfmax
!     .. Local Arrays ..
      Real (Kind=nag_wp)               :: ruser(1)
      Integer                          :: iuser(1)
!     .. Executable Statements ..
      Write (nout,*) 'C05AWF Example Program Results'

      Write (nout,*)

!     Repeat with tolerance eps set to varying powers of 10:

loop: Do k = 3, 4
        eps = 10.0E0_nag_wp**(-k)
        x = 1.0E0_nag_wp
        eta = 0.0E0_nag_wp
        nfmax = 200

        ifail = -1
        Call c05awf(x,eps,eta,f,nfmax,iuser,ruser,ifail)

        Select Case (ifail)
        Case (0)
          Write (nout,99999) 'With EPS = ', eps, '   root = ', x
        Case (:-1)
          Exit loop
        Case (3,4)
          Write (nout,99999) 'With EPS = ', eps, ' final value = ', x
        End Select

      End Do loop

99999 Format (1X,A,E10.2,A,F14.5)
    End Program c05awfe


c05axfe.f90

    Program c05axfe

!     C05AXF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: c05axf, nag_wp, x02ajf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: fx, scal, tol, x
      Integer                          :: i, ifail, ind, ir
!     .. Local Arrays ..
      Real (Kind=nag_wp)               :: c(26)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: exp, sqrt
!     .. Executable Statements ..
      Write (nout,*) 'C05AXF Example Program Results'

      scal = sqrt(x02ajf())
      ir = 0

loop: Do i = 3, 4
        tol = 10.0E0_nag_wp**(-i)
        Write (nout,*)
        Write (nout,99999) 'TOL =', tol
        Write (nout,*)
        x = 1.0E0_nag_wp
        ind = 1
        ifail = -1

revcomm: Do
          Call c05axf(x,fx,tol,ir,scal,c,ind,ifail)

          If (ind==0) Then
            Exit revcomm
          End If

          fx = x - exp(-x)
        End Do revcomm

        Select Case (ifail)
        Case (:-1)
          Exit loop
        Case (4,6)
          Write (nout,99998) 'Final value = ', x, ' THETA = ', c(5)
        Case (0)
          Write (nout,99998) 'Root is ', x
        End Select

      End Do loop

99999 Format (1X,A,E11.4)
99998 Format (1X,A,F14.5,A,F10.2)
    End Program c05axfe


c05ayfe.f90

!   C05AYF Example Program Text
!   Mark 26 Release. NAG Copyright 2016.

    Module c05ayfe_mod

!     C05AYF Example Program Module:
!            Parameters and User-defined Routines

!     .. Use Statements ..
      Use nag_library, Only: nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Accessibility Statements ..
      Private
      Public                           :: f
!     .. Parameters ..
      Integer, Parameter, Public       :: nout = 6
    Contains
      Function f(x,iuser,ruser)

!       .. Function Return Value ..
        Real (Kind=nag_wp)             :: f
!       .. Scalar Arguments ..
        Real (Kind=nag_wp), Intent (In) :: x
!       .. Array Arguments ..
        Real (Kind=nag_wp), Intent (Inout) :: ruser(*)
        Integer, Intent (Inout)        :: iuser(*)
!       .. Intrinsic Procedures ..
        Intrinsic                      :: exp
!       .. Executable Statements ..
        f = exp(-x) - x

        Return

      End Function f
    End Module c05ayfe_mod
    Program c05ayfe

!     C05AYF Example Main Program

!     .. Use Statements ..
      Use nag_library, Only: c05ayf, nag_wp
      Use c05ayfe_mod, Only: f, nout
!     .. Implicit None Statement ..
      Implicit None
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: a, b, eps, eta, x
      Integer                          :: ifail
!     .. Local Arrays ..
      Real (Kind=nag_wp)               :: ruser(1)
      Integer                          :: iuser(1)
!     .. Executable Statements ..
      Write (nout,*) 'C05AYF Example Program Results'

      a = 0.0E0_nag_wp
      b = 1.0E0_nag_wp
      eps = 1.0E-5_nag_wp
      eta = 0.0E0_nag_wp

      ifail = -1
      Call c05ayf(a,b,eps,eta,f,x,iuser,ruser,ifail)

      Write (nout,*)

      Select Case (ifail)
      Case (0)
        Write (nout,99999) 'Zero at X =', x
      Case (2,3)
        Write (nout,99999) 'Final point = ', x
      End Select

99999 Format (1X,A,F12.5)
    End Program c05ayfe


c05azfe.f90

!   C05AZF Example Program Text
!   Mark 26 Release. NAG Copyright 2016.

    Module c05azfe_mod

!     C05AZF Example Program Module:
!            Parameters and User-defined Routines

!     .. Use Statements ..
      Use nag_library, Only: nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Accessibility Statements ..
      Private
      Public                           :: f
!     .. Parameters ..
      Real (Kind=nag_wp), Parameter, Public :: tolx = 1.0E-5_nag_wp
      Integer, Parameter, Public       :: ir = 0, nout = 6
    Contains
      Function f(x)

!       .. Function Return Value ..
        Real (Kind=nag_wp)             :: f
!       .. Scalar Arguments ..
        Real (Kind=nag_wp), Intent (In) :: x
!       .. Intrinsic Procedures ..
        Intrinsic                      :: exp
!       .. Executable Statements ..
        f = exp(-x) - x

        Return

      End Function f
    End Module c05azfe_mod
    Program c05azfe

!     C05AZF Example Main Program

!     .. Use Statements ..
      Use nag_library, Only: c05azf, nag_wp
      Use c05azfe_mod, Only: f, ir, nout, tolx
!     .. Implicit None Statement ..
      Implicit None
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: fx, x, y
      Integer                          :: ifail, ind
!     .. Local Arrays ..
      Real (Kind=nag_wp)               :: c(17)
!     .. Executable Statements ..
      Write (nout,*) 'C05AZF Example Program Results'

      Write (nout,*)
      Write (nout,*) ' Iterations'
      Write (nout,*)

!     Initial values, root in [0,1].
      x = 0.0_nag_wp
      y = 1.0_nag_wp
      ind = 1
      ifail = -1

!       Reverse communication loop
revcom: Do
        Call c05azf(x,y,fx,tolx,ir,c,ind,ifail)

        If (ind==0) Then
          Exit revcom
        End If

        fx = f(x)
        Write (nout,99999) ' X =', x, '   FX =', fx, '   IND =', ind
      End Do revcom

!     Results
      Select Case (ifail)
      Case (0)
        Write (nout,*)
        Write (nout,*) ' Solution'
        Write (nout,*)
        Write (nout,99998) ' X =', x, '   Y =', y
      Case (4,5)
        Write (nout,99998) 'X =', x, '  Y =', y
      End Select

99999 Format (1X,A,F8.5,A,E12.4,A,I2)
99998 Format (1X,2(A,F8.5))
    End Program c05azfe


c05bafe.f90

    Program c05bafe

!     C05BAF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: c05baf, nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: w, x
      Integer                          :: branch, ifail, ioerr
      Logical                          :: offset
!     .. Executable Statements ..
      Write (nout,*) 'C05BAF Example Program Results'

!     Skip heading in data file
      Read (nin,*)

      Read (nin,*) branch
      Read (nin,*) offset

      Write (nout,*)
      Write (nout,99998) 'BRANCH = ', branch

      If (offset) Then
        Write (nout,99997) 'OFFSET = .TRUE.'
      Else
        Write (nout,99997) 'OFFSET = .FALSE.'
      End If

      Write (nout,*)
      Write (nout,*) '        X           W(X)     IFAIL'
      Write (nout,*)

data: Do
        Read (nin,*,Iostat=ioerr) x

        If (ioerr<0) Then
          Exit data
        End If

        ifail = -1
        w = c05baf(x,branch,offset,ifail)

        If (ifail<0) Then
          Exit data
        End If

        Write (nout,99999) x, w, ifail
      End Do data

99999 Format (1X,1P,2(1X,E13.5),1X,I5)
99998 Format (1X,A,I3)
99997 Format (1X,A)
    End Program c05bafe


c05bbfe.f90

    Program c05bbfe

!     C05BBF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: c05bbf, nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Complex (Kind=nag_wp)            :: w, z
      Real (Kind=nag_wp)               :: resid
      Integer                          :: branch, ifail, ioerr
      Logical                          :: offset
!     .. Executable Statements ..
      Write (nout,*) 'C05BBF Example Program Results'

!     Skip heading in data file
      Read (nin,*)

      Read (nin,*) branch
      Read (nin,*) offset

      Write (nout,*)
      Write (nout,99997) 'BRANCH = ', branch

      If (offset) Then
        Write (nout,99996) 'OFFSET = .TRUE.'
      Else
        Write (nout,99996) 'OFFSET = .FALSE.'
      End If

      Write (nout,*)
      Write (nout,99999)
      Write (nout,*)

data: Do
        Read (nin,*,Iostat=ioerr) z

        If (ioerr<0) Then
          Exit data
        End If

        ifail = -1
        Call c05bbf(branch,offset,z,w,resid,ifail)

        If (ifail<0) Then
          Exit data
        End If

        Write (nout,99998) z, w, resid, ifail
      End Do data

99999 Format (1X,14X,'Z',28X,'W(Z)',18X,'RESID',4X,'IFAIL')
99998 Format (1X,1P,2('(',E13.5,',',E13.5,')',1X),E13.5,1X,I5)
99997 Format (1X,A,I3)
99996 Format (1X,A)
    End Program c05bbfe


c05qbfe.f90

!   C05QBF Example Program Text
!   Mark 26 Release. NAG Copyright 2016.

    Module c05qbfe_mod

!     C05QBF Example Program Module:
!            Parameters and User-defined Routines

!     .. Use Statements ..
      Use nag_library, Only: nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Accessibility Statements ..
      Private
      Public                           :: fcn
!     .. Parameters ..
      Integer, Parameter, Public       :: n = 9, nout = 6
    Contains
      Subroutine fcn(n,x,fvec,iuser,ruser,iflag)

!       .. Scalar Arguments ..
        Integer, Intent (Inout)        :: iflag
        Integer, Intent (In)           :: n
!       .. Array Arguments ..
        Real (Kind=nag_wp), Intent (Out) :: fvec(n)
        Real (Kind=nag_wp), Intent (Inout) :: ruser(*)
        Real (Kind=nag_wp), Intent (In) :: x(n)
        Integer, Intent (Inout)        :: iuser(*)
!       .. Executable Statements ..
        fvec(1:n) = (3.0_nag_wp-2.0_nag_wp*x(1:n))*x(1:n) + 1.0_nag_wp
        fvec(2:n) = fvec(2:n) - x(1:(n-1))
        fvec(1:(n-1)) = fvec(1:(n-1)) - 2.0_nag_wp*x(2:n)
!       Set iflag negative to terminate execution for any reason.
        iflag = 0
        Return
      End Subroutine fcn
    End Module c05qbfe_mod
    Program c05qbfe

!     C05QBF Example Main Program

!     .. Use Statements ..
      Use nag_library, Only: c05qbf, dnrm2, nag_wp, x02ajf
      Use c05qbfe_mod, Only: fcn, n, nout
!     .. Implicit None Statement ..
      Implicit None
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: fnorm, xtol
      Integer                          :: i, ifail
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: fvec(:), x(:)
      Real (Kind=nag_wp)               :: ruser(1)
      Integer                          :: iuser(1)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: sqrt
!     .. Executable Statements ..
      Write (nout,*) 'C05QBF Example Program Results'

      Allocate (fvec(n),x(n))

!     The following starting values provide a rough solution.

      x(1:n) = -1.0E0_nag_wp
      xtol = sqrt(x02ajf())

      ifail = -1
      Call c05qbf(fcn,n,x,fvec,xtol,iuser,ruser,ifail)

      If (ifail==0 .Or. ifail==2 .Or. ifail==3 .Or. ifail==4) Then
        If (ifail==0) Then
!         The NAG name equivalent of dnrm2 is f06ejf
          fnorm = dnrm2(n,fvec,1)
          Write (nout,*)
          Write (nout,99999) 'Final 2-norm of the residuals =', fnorm
          Write (nout,*)
          Write (nout,*) 'Final approximate solution'
        Else
          Write (nout,*)
          Write (nout,*) 'Approximate solution'
        End If
        Write (nout,*)
        Write (nout,99998)(x(i),i=1,n)
      End If

99999 Format (1X,A,E12.4)
99998 Format (1X,3F12.4)
    End Program c05qbfe


c05qcfe.f90

!   C05QCF Example Program Text
!   Mark 26 Release. NAG Copyright 2016.

    Module c05qcfe_mod

!     C05QCF Example Program Module:
!            Parameters and User-defined Routines

!     .. Use Statements ..
      Use nag_library, Only: nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Accessibility Statements ..
      Private
      Public                           :: fcn
!     .. Parameters ..
      Real (Kind=nag_wp), Parameter, Public :: epsfcn = 0.0_nag_wp
      Real (Kind=nag_wp), Parameter, Public :: factor = 100.0_nag_wp
      Integer, Parameter, Public       :: maxfev = 2000, ml = 1, mode = 2,     &
                                          mu = 1, n = 9, nout = 6, nprint = 0
    Contains
      Subroutine fcn(n,x,fvec,iuser,ruser,iflag)

!       .. Scalar Arguments ..
        Integer, Intent (Inout)        :: iflag
        Integer, Intent (In)           :: n
!       .. Array Arguments ..
        Real (Kind=nag_wp), Intent (Inout) :: fvec(n), ruser(*)
        Real (Kind=nag_wp), Intent (In) :: x(n)
        Integer, Intent (Inout)        :: iuser(*)
!       .. Executable Statements ..
        If (iflag==0) Then
          If (nprint>0) Then
!           Insert print statements here if desired.
            Continue
          End If
        Else
          fvec(1:n) = (3.0_nag_wp-2.0_nag_wp*x(1:n))*x(1:n) + 1.0_nag_wp
          fvec(2:n) = fvec(2:n) - x(1:(n-1))
          fvec(1:(n-1)) = fvec(1:(n-1)) - 2.0_nag_wp*x(2:n)
        End If
!       Set iflag negative to terminate execution for any reason.
        iflag = 0
        Return
      End Subroutine fcn
    End Module c05qcfe_mod
    Program c05qcfe

!     C05QCF Example Main Program

!     .. Use Statements ..
      Use nag_library, Only: c05qcf, dnrm2, nag_wp, x02ajf
      Use c05qcfe_mod, Only: epsfcn, factor, fcn, maxfev, ml, mode, mu, n,     &
                             nout, nprint
!     .. Implicit None Statement ..
      Implicit None
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: fnorm, xtol
      Integer                          :: i, ifail, nfev
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: diag(:), fjac(:,:), fvec(:), qtf(:), &
                                          r(:), x(:)
      Real (Kind=nag_wp)               :: ruser(1)
      Integer                          :: iuser(1)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: sqrt
!     .. Executable Statements ..
      Write (nout,*) 'C05QCF Example Program Results'

      Allocate (diag(n),fjac(n,n),fvec(n),qtf(n),r(n*(n+1)/2),x(n))

!     The following starting values provide a rough solution.

      x(1:n) = -1.0_nag_wp
      xtol = sqrt(x02ajf())
      diag(1:n) = 1.0_nag_wp

      ifail = -1
      Call c05qcf(fcn,n,x,fvec,xtol,maxfev,ml,mu,epsfcn,mode,diag,factor,      &
        nprint,nfev,fjac,r,qtf,iuser,ruser,ifail)

      If (ifail==0 .Or. ifail==2 .Or. ifail==3 .Or. ifail==4 .Or. ifail==5)    &
        Then
        If (ifail==0) Then
!         The NAG name equivalent of dnrm2 is f06ejf
          fnorm = dnrm2(n,fvec,1)
          Write (nout,*)
          Write (nout,99999) 'Final 2-norm of the residuals =', fnorm
          Write (nout,*)
          Write (nout,99998) 'Number of function evaluations =', nfev
          Write (nout,*)
          Write (nout,*) 'Final approximate solution'
        Else
          Write (nout,*)
          Write (nout,*) 'Approximate solution'
        End If
        Write (nout,*)
        Write (nout,99997)(x(i),i=1,n)
      End If

99999 Format (1X,A,E12.4)
99998 Format (1X,A,I10)
99997 Format (1X,3F12.4)
    End Program c05qcfe


c05qdfe.f90

    Program c05qdfe

!     C05QDF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: c05qdf, dnrm2, nag_wp, x02ajf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: n = 9, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: epsfcn, factor, fnorm, xtol
      Integer                          :: i, icount, ifail, irevcm, ml, mode,  &
                                          mu
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: diag(:), fjac(:,:), fvec(:), qtf(:), &
                                          r(:), rwsav(:), x(:)
      Integer, Allocatable             :: iwsav(:)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: sqrt
!     .. Executable Statements ..
      Write (nout,*) 'C05QDF Example Program Results'

      Allocate (diag(n),fjac(n,n),fvec(n),qtf(n),r(n*(n+                       &
        1)/2),rwsav(4*n+10),iwsav(17),x(n))

!     The following starting values provide a rough solution.

      x(1:n) = -1.0E0_nag_wp
      xtol = sqrt(x02ajf())
      diag(1:n) = 1.0E0_nag_wp
      ml = 1
      mu = 1
      epsfcn = 0.0E0_nag_wp
      mode = 2
      factor = 100.0E0_nag_wp
      icount = 0
      irevcm = 0
      ifail = -1

revcomm: Do

        Call c05qdf(irevcm,n,x,fvec,xtol,ml,mu,epsfcn,mode,diag,factor,fjac,r, &
          qtf,iwsav,rwsav,ifail)

        Select Case (irevcm)
        Case (1)
          icount = icount + 1

!         Insert print statements here to monitor progress if desired.

          Cycle revcomm
        Case (2)

!         Evaluate functions at given point

          fvec(1:n) = (3.0E0_nag_wp-2.0E0_nag_wp*x(1:n))*x(1:n) + 1.0E0_nag_wp
          fvec(2:n) = fvec(2:n) - x(1:(n-1))
          fvec(1:(n-1)) = fvec(1:(n-1)) - 2.0E0_nag_wp*x(2:n)
          Cycle revcomm
        Case Default
          Exit revcomm
        End Select

      End Do revcomm

      If (ifail==0 .Or. ifail==3 .Or. ifail==4 .Or. ifail==5) Then
        If (ifail==0) Then
!         The NAG name equivalent of dnrm2 is f06ejf
          fnorm = dnrm2(n,fvec,1)
          Write (nout,*)
          Write (nout,99999) 'Final 2-norm of the residuals after', icount,    &
            ' iterations is ', fnorm
          Write (nout,*)
          Write (nout,*) 'Final approximate solution'
        Else
          Write (nout,*)
          Write (nout,*) 'Approximate solution'
        End If
        Write (nout,*)
        Write (nout,99998)(x(i),i=1,n)
      End If

99999 Format (1X,A,I4,A,E12.4)
99998 Format (5X,3F12.4)
    End Program c05qdfe


c05qsfe.f90

!   C05QSF Example Program Text
!   Mark 26 Release. NAG Copyright 2016.

    Module c05qsfe_mod

!     C05QSF Example Program Module:
!            Parameters and User-defined Routines

!     .. Use Statements ..
      Use nag_library, Only: nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Accessibility Statements ..
      Private
      Public                           :: fcn
!     .. Parameters ..
      Integer, Parameter, Public       :: n = 9, nout = 6
    Contains
      Subroutine fcn(n,lindf,indf,x,fvec,iuser,ruser,iflag)

!       .. Parameters ..
        Real (Kind=nag_wp), Parameter  :: one = 1.0E0_nag_wp
        Real (Kind=nag_wp), Parameter  :: three = 3.0E0_nag_wp
        Real (Kind=nag_wp), Parameter  :: two = 2.0E0_nag_wp
        Real (Kind=nag_wp), Parameter  :: alpha = (one/two)**7
!       .. Scalar Arguments ..
        Integer, Intent (Inout)        :: iflag
        Integer, Intent (In)           :: lindf, n
!       .. Array Arguments ..
        Real (Kind=nag_wp), Intent (Out) :: fvec(n)
        Real (Kind=nag_wp), Intent (Inout) :: ruser(*)
        Real (Kind=nag_wp), Intent (In) :: x(n)
        Integer, Intent (In)           :: indf(lindf)
        Integer, Intent (Inout)        :: iuser(*)
!       .. Local Scalars ..
        Real (Kind=nag_wp)             :: theta
        Integer                        :: i, ind
!       .. Intrinsic Procedures ..
        Intrinsic                      :: real
!       .. Executable Statements ..
        iflag = 0
        theta = real(iuser(1),kind=nag_wp)*alpha
        Do ind = 1, lindf
          i = indf(ind)
          fvec(i) = (three-(two+theta)*x(i))*x(i) + one
          If (i>1) Then
            fvec(i) = fvec(i) - x(i-1)
          End If
          If (i<n) Then
            fvec(i) = fvec(i) - two*x(i+1)
          End If
        End Do
        Return

      End Subroutine fcn
    End Module c05qsfe_mod
    Program c05qsfe

!     .. Use Statements ..
      Use nag_library, Only: c05qsf, dnrm2, nag_wp, x02ajf
      Use c05qsfe_mod, Only: fcn, n, nout
!     .. Implicit None Statement ..
      Implicit None
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: fnorm, xtol
      Integer                          :: i, ifail, j, licomm, lrcomm
      Logical                          :: init
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: fvec(:), rcomm(:), x(:)
      Real (Kind=nag_wp)               :: ruser(1)
      Integer, Allocatable             :: icomm(:)
      Integer                          :: iuser(1)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: sqrt
!     .. Executable Statements ..
      Write (nout,*) 'C05QSF Example Program Results'

      xtol = sqrt(x02ajf())
      lrcomm = 12 + 3*n
      licomm = 8*n + 19 + 3*n

      Allocate (fvec(n),x(n),rcomm(lrcomm),icomm(licomm))

!     The following starting values provide a rough solution.
      x(1:n) = -1.0E0_nag_wp

      Do i = 0, 1
        ifail = -1

!       Perturb the system?
        iuser(1) = i

        init = (i==0)
        Call c05qsf(fcn,n,x,fvec,xtol,init,rcomm,lrcomm,icomm,licomm,iuser,    &
          ruser,ifail)

        Select Case (ifail)
        Case (0)
!         The NAG name equivalent of dnrm2 is f06ejf
          fnorm = dnrm2(n,fvec,1)
          Write (nout,*)
          Write (nout,99999) 'Final 2-norm of the residuals =', fnorm
          Write (nout,*)
          Write (nout,*) 'Final approximate solution'
          Write (nout,*)
          Write (nout,99998)(x(j),j=1,n)
        Case (2:4)
          Write (nout,*)
          Write (nout,*) 'Approximate solution'
          Write (nout,*)
          Write (nout,99998)(x(j),j=1,n)
        End Select
      End Do

99999 Format (1X,A,E12.4)
99998 Format (1X,3F12.4)
    End Program c05qsfe


c05rbfe.f90

!   C05RBF Example Program Text
!   Mark 26 Release. NAG Copyright 2016.

    Module c05rbfe_mod

!     C05RBF Example Program Module:
!            Parameters and User-defined Routines

!     .. Use Statements ..
      Use nag_library, Only: nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Accessibility Statements ..
      Private
      Public                           :: fcn
!     .. Parameters ..
      Integer, Parameter, Public       :: n = 9, nout = 6
    Contains
      Subroutine fcn(n,x,fvec,fjac,iuser,ruser,iflag)

!       .. Parameters ..
        Real (Kind=nag_wp), Parameter  :: coeff(5) = (/-1.0_nag_wp,3.0_nag_wp, &
                                          -2.0_nag_wp,-2.0_nag_wp,             &
                                          -1.0_nag_wp/)
!       .. Scalar Arguments ..
        Integer, Intent (Inout)        :: iflag
        Integer, Intent (In)           :: n
!       .. Array Arguments ..
        Real (Kind=nag_wp), Intent (Inout) :: fjac(n,n), fvec(n), ruser(*)
        Real (Kind=nag_wp), Intent (In) :: x(n)
        Integer, Intent (Inout)        :: iuser(*)
!       .. Local Scalars ..
        Integer                        :: k
!       .. Executable Statements ..
        If (iflag/=2) Then
          fvec(1:n) = (coeff(2)+coeff(3)*x(1:n))*x(1:n) - coeff(5)
          fvec(2:n) = fvec(2:n) + coeff(1)*x(1:(n-1))
          fvec(1:(n-1)) = fvec(1:(n-1)) + coeff(4)*x(2:n)
        Else
          fjac(1:n,1:n) = 0.0_nag_wp
          fjac(1,1) = coeff(2) + 2.0_nag_wp*coeff(3)*x(1)
          fjac(1,2) = coeff(4)
          Do k = 2, n - 1
            fjac(k,k-1) = coeff(1)
            fjac(k,k) = coeff(2) + 2.0_nag_wp*coeff(3)*x(k)
            fjac(k,k+1) = coeff(4)
          End Do
          fjac(n,n-1) = coeff(1)
          fjac(n,n) = coeff(2) + 2.0_nag_wp*coeff(3)*x(n)
        End If
!       Set iflag negative to terminate execution for any reason.
        iflag = 0
        Return
      End Subroutine fcn
    End Module c05rbfe_mod
    Program c05rbfe

!     C05RBF Example Main Program

!     .. Use Statements ..
      Use nag_library, Only: c05rbf, dnrm2, nag_wp, x02ajf
      Use c05rbfe_mod, Only: fcn, n, nout
!     .. Implicit None Statement ..
      Implicit None
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: fnorm, xtol
      Integer                          :: i, ifail
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: fjac(:,:), fvec(:), x(:)
      Real (Kind=nag_wp)               :: ruser(1)
      Integer                          :: iuser(1)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: sqrt
!     .. Executable Statements ..
      Write (nout,*) 'C05RBF Example Program Results'

      Allocate (fjac(n,n),fvec(n),x(n))

!     The following starting values provide a rough solution.

      x(1:n) = -1.0E0_nag_wp

      xtol = sqrt(x02ajf())

      ifail = -1
      Call c05rbf(fcn,n,x,fvec,fjac,xtol,iuser,ruser,ifail)

      If (ifail==0 .Or. ifail==2 .Or. ifail==3 .Or. ifail==4) Then
        If (ifail==0) Then
!         The NAG name equivalent of dnrm2 is f06ejf
          fnorm = dnrm2(n,fvec,1)
          Write (nout,*)
          Write (nout,99999) 'Final 2-norm of the residuals =', fnorm
          Write (nout,*)
          Write (nout,*) 'Final approximate solution'
        Else
          Write (nout,*)
          Write (nout,*) 'Approximate solution'
        End If
        Write (nout,*)
        Write (nout,99998)(x(i),i=1,n)
      End If

99999 Format (1X,A,E12.4)
99998 Format (1X,3F12.4)
    End Program c05rbfe


c05rcfe.f90

!   C05RCF Example Program Text
!   Mark 26 Release. NAG Copyright 2016.

    Module c05rcfe_mod

!     C05RCF Example Program Module:
!            Parameters and User-defined Routines

!     .. Use Statements ..
      Use nag_library, Only: nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Accessibility Statements ..
      Private
      Public                           :: fcn
!     .. Parameters ..
      Real (Kind=nag_wp), Parameter, Public :: factor = 100.0_nag_wp
      Integer, Parameter, Public       :: maxfev = 1000, mode = 2, n = 9,      &
                                          nout = 6, nprint = 0
    Contains
      Subroutine fcn(n,x,fvec,fjac,iuser,ruser,iflag)

!       .. Parameters ..
        Real (Kind=nag_wp), Parameter  :: coeff(5) = (/-1.0_nag_wp,3.0_nag_wp, &
                                          -2.0_nag_wp,-2.0_nag_wp,             &
                                          -1.0_nag_wp/)
!       .. Scalar Arguments ..
        Integer, Intent (Inout)        :: iflag
        Integer, Intent (In)           :: n
!       .. Array Arguments ..
        Real (Kind=nag_wp), Intent (Inout) :: fjac(n,n), fvec(n), ruser(*)
        Real (Kind=nag_wp), Intent (In) :: x(n)
        Integer, Intent (Inout)        :: iuser(*)
!       .. Local Scalars ..
        Integer                        :: k
!       .. Executable Statements ..
        If (iflag==0) Then
          If (nprint>0) Then
!           Insert print statements here if desired.
            Continue
          End If
        Else If (iflag/=2) Then
          fvec(1:n) = (coeff(2)+coeff(3)*x(1:n))*x(1:n) - coeff(5)
          fvec(2:n) = fvec(2:n) + coeff(1)*x(1:(n-1))
          fvec(1:(n-1)) = fvec(1:(n-1)) + coeff(4)*x(2:n)
        Else
          fjac(1:n,1:n) = 0.0_nag_wp
          fjac(1,1) = coeff(2) + 2.0_nag_wp*coeff(3)*x(1)
          fjac(1,2) = coeff(4)
          Do k = 2, n - 1
            fjac(k,k-1) = coeff(1)
            fjac(k,k) = coeff(2) + 2.0_nag_wp*coeff(3)*x(k)
            fjac(k,k+1) = coeff(4)
          End Do
          fjac(n,n-1) = coeff(1)
          fjac(n,n) = coeff(2) + 2.0_nag_wp*coeff(3)*x(n)
        End If
!       Set iflag negative to terminate execution for any reason.
        iflag = 0
        Return
      End Subroutine fcn
    End Module c05rcfe_mod
    Program c05rcfe

!     C05RCF Example Main Program

!     .. Use Statements ..
      Use nag_library, Only: c05rcf, dnrm2, nag_wp, x02ajf
      Use c05rcfe_mod, Only: factor, fcn, maxfev, mode, n, nout, nprint
!     .. Implicit None Statement ..
      Implicit None
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: fnorm, xtol
      Integer                          :: i, ifail, nfev, njev
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: diag(:), fjac(:,:), fvec(:), qtf(:), &
                                          r(:), x(:)
      Real (Kind=nag_wp)               :: ruser(1)
      Integer                          :: iuser(1)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: sqrt
!     .. Executable Statements ..
      Write (nout,*) 'C05RCF Example Program Results'

      Allocate (diag(n),fjac(n,n),fvec(n),qtf(n),r(n*(n+1)/2),x(n))

!     The following starting values provide a rough solution.

      x(1:n) = -1.0_nag_wp

      xtol = sqrt(x02ajf())
      diag(1:n) = 1.0_nag_wp

      ifail = -1
      Call c05rcf(fcn,n,x,fvec,fjac,xtol,maxfev,mode,diag,factor,nprint,nfev,  &
        njev,r,qtf,iuser,ruser,ifail)

      If (ifail==0 .Or. ifail==2 .Or. ifail==3 .Or. ifail==4 .Or. ifail==5)    &
        Then
        If (ifail==0) Then
!         The NAG name equivalent of dnrm2 is f06ejf
          fnorm = dnrm2(n,fvec,1)
          Write (nout,*)
          Write (nout,99999) 'Final 2-norm of the residuals =', fnorm
          Write (nout,*)
          Write (nout,*) 'Final approximate solution'
        Else
          Write (nout,*)
          Write (nout,*) 'Approximate solution:'
        End If
        Write (nout,*)
        Write (nout,99998)(x(i),i=1,n)
      End If

99999 Format (1X,A,E12.4)
99998 Format (1X,3F12.4)
    End Program c05rcfe


c05rdfe.f90

    Program c05rdfe

!     C05RDF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: c05rdf, dnrm2, nag_wp, x02ajf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: n = 9, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: factor, fnorm, xtol
      Integer                          :: i, icount, ifail, irevcm, k, mode
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: diag(:), fjac(:,:), fvec(:), qtf(:), &
                                          r(:), rwsav(:), x(:)
      Integer, Allocatable             :: iwsav(:)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: sqrt
!     .. Executable Statements ..
      Write (nout,*) 'C05RDF Example Program Results'

      Allocate (diag(n),fjac(n,n),fvec(n),qtf(n),r(n*(n+                       &
        1)/2),rwsav(4*n+10),iwsav(17),x(n))

!     The following starting values provide a rough solution.

      x(1:n) = -1.0E0_nag_wp

      xtol = sqrt(x02ajf())
      diag(1:n) = 1.0E0_nag_wp
      mode = 2
      factor = 100.0E0_nag_wp
      icount = 0
      irevcm = 0
      ifail = -1

revcomm: Do

        Call c05rdf(irevcm,n,x,fvec,fjac,xtol,mode,diag,factor,r,qtf,iwsav,    &
          rwsav,ifail)

        Select Case (irevcm)
        Case (1)
          icount = icount + 1

!         Insert print statements here to monitor progress if desired.

          Cycle revcomm
        Case (2)

!         Evaluate functions at given point

          fvec(1:n) = (3.0E0_nag_wp-2.0E0_nag_wp*x(1:n))*x(1:n) + 1.0E0_nag_wp
          fvec(2:n) = fvec(2:n) - x(1:(n-1))
          fvec(1:(n-1)) = fvec(1:(n-1)) - 2.0E0_nag_wp*x(2:n)
          Cycle revcomm
        Case (3)

!         Evaluate Jacobian at current point

          fjac(1:n,1:n) = 0.0E0_nag_wp

          Do k = 1, n
            fjac(k,k) = 3.0E0_nag_wp - 4.0E0_nag_wp*x(k)

            If (k/=1) Then
              fjac(k,k-1) = -1.0E0_nag_wp
            End If

            If (k/=n) Then
              fjac(k,k+1) = -2.0E0_nag_wp
            End If

          End Do

          Cycle revcomm
        Case Default
          Exit revcomm
        End Select

      End Do revcomm

      If (ifail==0 .Or. ifail==3 .Or. ifail==4 .Or. ifail==5) Then
        If (ifail==0) Then
!         The NAG name equivalent of dnrm2 is f06ejf
          fnorm = dnrm2(n,fvec,1)
          Write (nout,*)
          Write (nout,99999) 'Final 2-norm of the residuals after', icount,    &
            ' iterations is ', fnorm
          Write (nout,*)
          Write (nout,*) 'Final approximate solution'
        Else
          Write (nout,*)
          Write (nout,*) 'Approximate solution'
        End If
        Write (nout,*)
        Write (nout,99998)(x(i),i=1,n)
      End If

99999 Format (1X,A,I4,A,E12.4)
99998 Format (5X,3F12.4)
    End Program c05rdfe


c05zdfe.f90

!   C05ZDF Example Program Text
!   Mark 26 Release. NAG Copyright 2016.

    Module c05zdfe_mod

!     C05ZDF Example Program Module:
!            Parameters and User-defined Routines

!     .. Use Statements ..
      Use nag_library, Only: nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Accessibility Statements ..
      Private
      Public                           :: get_fjac, get_fvec
!     .. Parameters ..
      Integer, Parameter, Public       :: m = 15, n = 3, nout = 6
    Contains
      Subroutine get_fvec(x,fvec)

!       .. Array Arguments ..
        Real (Kind=nag_wp), Intent (Out) :: fvec(:)
        Real (Kind=nag_wp), Intent (In) :: x(:)
!       .. Local Scalars ..
        Real (Kind=nag_wp)             :: u, v, w
        Integer                        :: i
!       .. Local Arrays ..
        Real (Kind=nag_wp), Allocatable :: y(:)
!       .. Intrinsic Procedures ..
        Intrinsic                      :: min, real
!       .. Executable Statements ..
        Allocate (y(m))

        y(1:m) = real((/14,18,22,25,29,32,35,39,47,58,73,96,134,210,439/),     &
          kind=nag_wp)
        y(1:m) = y(1:m)*0.01_nag_wp

        Do i = 1, m
          u = real(i,kind=nag_wp)
          v = real(m+1-i,kind=nag_wp)
          w = min(u,v)
          fvec(i) = y(i) - (x(1)+u/(v*x(2)+w*x(3)))
        End Do

        Return
      End Subroutine get_fvec
      Subroutine get_fjac(x,fjac)

!       .. Array Arguments ..
        Real (Kind=nag_wp), Intent (Inout) :: fjac(:,:)
        Real (Kind=nag_wp), Intent (In) :: x(:)
!       .. Local Scalars ..
        Real (Kind=nag_wp)             :: denom, u, v, w
        Integer                        :: i
!       .. Intrinsic Procedures ..
        Intrinsic                      :: min, real
!       .. Executable Statements ..
        Do i = 1, m
          u = real(i,kind=nag_wp)
          v = real(m+1-i,kind=nag_wp)
          w = min(u,v)
          denom = (v*x(2)+w*x(3))**(-2)
          fjac(i,1:n) = (/-1.0E0_nag_wp,u*v*denom,u*w*denom/)
        End Do

        Return
      End Subroutine get_fjac
    End Module c05zdfe_mod
    Program c05zdfe

!     C05ZDF Example Main Program

!     .. Use Statements ..
      Use nag_library, Only: c05zdf, nag_wp
      Use c05zdfe_mod, Only: get_fjac, get_fvec, m, n, nout
!     .. Implicit None Statement ..
      Implicit None
!     .. Local Scalars ..
      Integer                          :: i, ifail, mode
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: err(:), fjac(:,:), fvec(:),          &
                                          fvecp(:), x(:), xp(:)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: any
!     .. Executable Statements ..
      Write (nout,*) 'C05ZDF Example Program Results'

      Allocate (err(m),fjac(m,n),fvec(m),fvecp(m),x(n),xp(n))

!     Point at which to check gradients:

      x(1:n) = (/0.92_nag_wp,0.13_nag_wp,0.54_nag_wp/)

      mode = 1

      ifail = 0
      Call c05zdf(mode,m,n,x,fvec,fjac,xp,fvecp,err,ifail)

      Call get_fvec(x,fvec)

      Call get_fvec(xp,fvecp)

      Call get_fjac(x,fjac)

      mode = 2

      ifail = 0
      Call c05zdf(mode,m,n,x,fvec,fjac,xp,fvecp,err,ifail)

      Write (nout,*)
      Write (nout,99999) 'At point ', (x(i),i=1,n), ','

      If (any(err(1:m)<=0.5_nag_wp)) Then

        Do i = 1, m

          If (err(i)<=0.5_nag_wp) Then
            Write (nout,99998) 'suspicious gradient number ', i,               &
              ' with error measure ', err(i)
          End If

        End Do

      Else
        Write (nout,99997) 'gradients appear correct'
      End If

99999 Format (1X,A,3F12.4,A)
99998 Format (1X,A,I5,A,F12.4)
99997 Format (1X,A)
    End Program c05zdfe


c06bafe.f90

    Program c06bafe

!     C06BAF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: c06baf, nag_wp, x01aaf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: lwork = 16, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: abserr, ans, error, pi, r, result,   &
                                          seqn, sig
      Integer                          :: i, ifail, ncall
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: work(:)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: real
!     .. Executable Statements ..
      Write (nout,*) 'C06BAF Example Program Results'
      Write (nout,*)

      Allocate (work(lwork))

      pi = x01aaf(pi)
      ans = pi**2/12.0_nag_wp
      ncall = 0
      sig = 1.0_nag_wp
      seqn = 0.0_nag_wp
      Write (nout,99999) 'Estimated       Actual'
      Write (nout,99998) 'I       SEQN       RESULT', 'abs error        error'
      Write (nout,*)
      Do i = 1, 10
        r = real(i,kind=nag_wp)
        seqn = seqn + sig/(r**2)

!       ifail: behaviour on error exit
!              =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
        ifail = 0
        Call c06baf(seqn,ncall,result,abserr,work,lwork,ifail)

        error = result - ans
        sig = -sig
        If (i<=3) Then
!         First three calls of C06BAF return no error estimate
          Write (nout,99997) i, seqn, result, error
        Else
          Write (nout,99996) i, seqn, result, abserr, error
        End If
      End Do

99999 Format (36X,A)
99998 Format (3X,A25,8X,A)
99997 Format (1X,I4,2F12.4,3X,10X,'-   ',E14.2)
99996 Format (1X,I4,2F12.4,3X,2E14.2)
    End Program c06bafe


c06dcfe.f90

    Program c06dcfe

!     C06DCF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: c06dcf, nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: xmax, xmin
      Integer                          :: i, ifail, lx, n, s
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: c(:), res(:), x(:)
!     .. Executable Statements ..
      Write (nout,*) 'C06DCF Example Program Results'
!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) n, lx
      Allocate (c(n),res(lx),x(lx))

      Read (nin,*) x(1:lx)
      Read (nin,*) xmin, xmax
      Read (nin,*) s
      Read (nin,*) c(1:n)

!     ifail: behaviour on error exit
!             =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
      ifail = 0
      Call c06dcf(x,lx,xmin,xmax,c,n,s,res,ifail)

      Write (nout,*)
      Write (nout,*) '    x       sum of series'
      Write (nout,*)
      Write (nout,99999)(x(i),res(i),i=1,lx)

99999 Format (1X,F8.4,4X,F8.4)
    End Program c06dcfe


c06fafe.f90

    Program c06fafe

!     C06FAF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: c06faf, c06fbf, nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Integer                          :: ieof, ifail, j, n
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: a(:), b(:), work(:), x(:), xx(:)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: mod
!     .. Executable Statements ..
      Write (nout,*) 'C06FAF Example Program Results'
!     Skip heading in data file
      Read (nin,*)
loop: Do
        Read (nin,*,Iostat=ieof) n
        If (ieof<0) Then
          Exit loop
        End If
        Allocate (a(0:n-1),b(0:n-1),x(0:n-1),xx(0:n-1),work(n))
        Read (nin,*) x(0:n-1)
        xx(0:n-1) = x(0:n-1)

!       ifail: behaviour on error exit
!              =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
        ifail = 0
        Call c06faf(x,n,work,ifail)

        Write (nout,*)
        Write (nout,*) 'Components of discrete Fourier transform'
        Write (nout,*)
        Write (nout,*) '          Real      Imag'
        Write (nout,*)

!       Convert x to separated real and imaginary parts for printing.
        a(0:n/2) = x(0:n/2)
        a(n-1:n/2+1:-1) = x(1:n/2)
        b(0) = 0.0_nag_wp
        b(1:(n-1)/2) = x(n-1:n-(n-1)/2:-1)
        b(n-(n-1)/2:n-1) = -b((n-1)/2:1:-1)
        If (mod(n,2)==0) Then
          b(n/2) = 0.0_nag_wp
        End If

        Write (nout,99999)(j,a(j),b(j),j=0,n-1)

        x(n/2+1:n-1) = -x(n/2+1:n-1)
        Call c06fbf(x,n,work,ifail)

        Write (nout,*)
        Write (nout,*) 'Original sequence as restored by inverse transform'
        Write (nout,*)
        Write (nout,*) '        Original  Restored'
        Write (nout,*)
        Write (nout,99999)(j,xx(j),x(j),j=0,n-1)
        Deallocate (a,b,x,xx,work)
      End Do loop

99999 Format (1X,I5,2F10.5)
    End Program c06fafe


c06fbfe.f90

    Program c06fbfe

!     C06FBF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: c06faf, c06fbf, nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Integer                          :: ieof, ifail, j, n
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: u(:), v(:), work(:), x(:), xx(:)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: mod
!     .. Executable Statements ..
      Write (nout,*) 'C06FBF Example Program Results'
!     Skip heading in data file
      Read (nin,*)
loop: Do
        Read (nin,*,Iostat=ieof) n
        If (ieof<0) Then
          Exit loop
        End If
        Allocate (u(0:n-1),v(0:n-1),x(0:n-1),xx(0:n-1),work(n))
        Read (nin,*) x(0:n-1)
        xx(0:n-1) = x(0:n-1)

!       Convert x to separated real and imaginary parts for printing.
        u(0:n/2) = x(0:n/2)
        u(n-1:n/2+1:-1) = x(1:n/2)
        v(0) = 0.0_nag_wp
        v(1:(n-1)/2) = x(n-1:n-(n-1)/2:-1)
        v(n-(n-1)/2:n-1) = -v((n-1)/2:1:-1)
        If (mod(n,2)==0) Then
          v(n/2) = 0.0_nag_wp
        End If

!       ifail: behaviour on error exit
!              =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
        ifail = 0
        Call c06fbf(x,n,work,ifail)

        Write (nout,*)
        Write (nout,*) 'Original sequence and corresponding complex sequence'
        Write (nout,*)
        Write (nout,*) '         Data           Real      Imag'
        Write (nout,*)
        Write (nout,99999)(j,xx(j),'     ',u(j),v(j),j=0,n-1)
        Write (nout,*)
        Write (nout,*) 'Components of discrete Fourier transform'
        Write (nout,*)
        Write (nout,99998)(j,x(j),j=0,n-1)

        Call c06faf(x,n,work,ifail)
        x(n/2+1:n-1) = -x(n/2+1:n-1)

        Write (nout,*)
        Write (nout,*) 'Original sequence as restored by inverse transform'
        Write (nout,*)
        Write (nout,*) '        Original  Restored'
        Write (nout,*)
        Write (nout,99997)(j,xx(j),x(j),j=0,n-1)
        Deallocate (u,v,x,xx,work)
      End Do loop

99999 Format (1X,I5,F10.5,A,2F10.5)
99998 Format (1X,I5,F10.5)
99997 Format (1X,I5,2F10.5)
    End Program c06fbfe


c06fcfe.f90

    Program c06fcfe

!     C06FCF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: c06fcf, nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Integer                          :: ieof, ifail, j, n
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: work(:), x(:), xx(:), y(:), yy(:)
!     .. Executable Statements ..
      Write (nout,*) 'C06FCF Example Program Results'
!     Skip heading in data file
      Read (nin,*)
loop: Do
        Read (nin,*,Iostat=ieof) n
        If (ieof<0) Then
          Exit loop
        End If

        Allocate (x(0:n-1),xx(0:n-1),y(0:n-1),yy(0:n-1),work(n))
        Read (nin,*)(x(j),y(j),j=0,n-1)
        xx(0:n-1) = x(0:n-1)
        yy(0:n-1) = y(0:n-1)

!       ifail: behaviour on error exit
!              =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
        ifail = 0
        Call c06fcf(x,y,n,work,ifail)

        Write (nout,*)
        Write (nout,*) 'Components of discrete Fourier transform'
        Write (nout,*)
        Write (nout,*) '          Real      Imag'
        Write (nout,*)
        Write (nout,99999)(j,x(j),y(j),j=0,n-1)

        y = -y
        Call c06fcf(x,y,n,work,ifail)
        y = -y

        Write (nout,*)
        Write (nout,*) 'Original sequence as restored by inverse transform'
        Write (nout,*)
        Write (nout,*) '             Original                 Restored'
        Write (nout,*) '          Real      Imag           Real      Imag'
        Write (nout,*)
        Write (nout,99998)(j,xx(j),yy(j),x(j),y(j),j=0,n-1)
        Deallocate (x,xx,y,yy,work)
      End Do loop

99999 Format (1X,I5,2F10.5)
99998 Format (1X,I5,2F10.5,5X,2F10.5)
    End Program c06fcfe


c06fffe.f90

!   C06FFF Example Program Text
!   Mark 26 Release. NAG Copyright 2016.

    Module c06fffe_mod

!     C06FFF Example Program Module:
!            Parameters and User-defined Routines

!     .. Use Statements ..
      Use nag_library, Only: nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Accessibility Statements ..
      Private
      Public                           :: readxy, writxy
!     .. Parameters ..
      Integer, Parameter, Public       :: nin = 5, nout = 6
    Contains
      Subroutine readxy(nin,x,y,n1,n2)
!       Read 2-dimensional complex data

!       .. Scalar Arguments ..
        Integer, Intent (In)           :: n1, n2, nin
!       .. Array Arguments ..
        Real (Kind=nag_wp), Intent (Out) :: x(n1,n2), y(n1,n2)
!       .. Local Scalars ..
        Integer                        :: i, j
!       .. Executable Statements ..
        Do i = 1, n1
          Read (nin,*)(x(i,j),j=1,n2)
          Read (nin,*)(y(i,j),j=1,n2)
        End Do
        Return
      End Subroutine readxy

      Subroutine writxy(nout,x,y,n1,n2)
!       Print 2-dimensional complex data

!       .. Scalar Arguments ..
        Integer, Intent (In)           :: n1, n2, nout
!       .. Array Arguments ..
        Real (Kind=nag_wp), Intent (In) :: x(n1,n2), y(n1,n2)
!       .. Local Scalars ..
        Integer                        :: i, j
!       .. Executable Statements ..
        Do i = 1, n1
          Write (nout,*)
          Write (nout,99999) 'Real ', (x(i,j),j=1,n2)
          Write (nout,99999) 'Imag ', (y(i,j),j=1,n2)
        End Do
        Return

99999   Format (1X,A,7F10.3,/,(6X,7F10.3))
      End Subroutine writxy
    End Module c06fffe_mod

    Program c06fffe

!     C06FFF Example Main Program

!     .. Use Statements ..
      Use nag_library, Only: c06fff, nag_wp
      Use c06fffe_mod, Only: nin, nout, readxy, writxy
!     .. Implicit None Statement ..
      Implicit None
!     .. Local Scalars ..
      Integer                          :: ieof, ifail, l, lwork, n, ndim
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: work(:), x(:), y(:)
      Integer, Allocatable             :: nd(:)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: product
!     .. Executable Statements ..
      Write (nout,*) 'C06FFF Example Program Results'
!     Skip heading in data file
      Read (nin,*)
loop: Do
        Read (nin,*,Iostat=ieof) ndim
        If (ieof<0) Then
          Exit loop
        End If

        Allocate (nd(ndim))

        Read (nin,*) nd(1:ndim), l

        n = product(nd(1:ndim))
        lwork = 3*nd(l)
        Allocate (x(n),y(n),work(lwork))

        Call readxy(nin,x,y,nd(1),nd(2))

        Write (nout,*)
        Write (nout,*) 'Original data'
        Call writxy(nout,x,y,nd(1),nd(2))

!       ifail: behaviour on error exit
!              =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft

!       Compute transform
        ifail = 0
        Call c06fff(ndim,l,nd,n,x,y,work,lwork,ifail)

        Write (nout,*)
        Write (nout,99999) 'Discrete Fourier transform of variable ', l
        Call writxy(nout,x,y,nd(1),nd(2))

!       Compute inverse transform
        y(1:n) = -y(1:n)
        Call c06fff(ndim,l,nd,n,x,y,work,lwork,ifail)
        y(1:n) = -y(1:n)

        Write (nout,*)
        Write (nout,*) 'Original sequence as restored by inverse transform'
        Call writxy(nout,x,y,nd(1),nd(2))
        Deallocate (x,y,work,nd)
      End Do loop

99999 Format (1X,A,I1)
    End Program c06fffe


c06fjfe.f90

!   C06FJF Example Program Text
!   Mark 26 Release. NAG Copyright 2016.

    Module c06fjfe_mod

!     C06FJF Example Program Module:
!            Parameters and User-defined Routines

!     .. Use Statements ..
      Use nag_library, Only: nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Accessibility Statements ..
      Private
      Public                           :: readxy, writxy
!     .. Parameters ..
      Integer, Parameter, Public       :: nin = 5, nout = 6
    Contains
      Subroutine readxy(nin,x,y,n1,n2)
!       Read 2-dimensional complex data

!       .. Scalar Arguments ..
        Integer, Intent (In)           :: n1, n2, nin
!       .. Array Arguments ..
        Real (Kind=nag_wp), Intent (Out) :: x(n1,n2), y(n1,n2)
!       .. Local Scalars ..
        Integer                        :: i, j
!       .. Executable Statements ..
        Do i = 1, n1
          Read (nin,*)(x(i,j),j=1,n2)
          Read (nin,*)(y(i,j),j=1,n2)
        End Do
        Return
      End Subroutine readxy

      Subroutine writxy(nout,x,y,n1,n2)
!       Print 2-dimensional complex data

!       .. Scalar Arguments ..
        Integer, Intent (In)           :: n1, n2, nout
!       .. Array Arguments ..
        Real (Kind=nag_wp), Intent (In) :: x(n1,n2), y(n1,n2)
!       .. Local Scalars ..
        Integer                        :: i, j
!       .. Executable Statements ..
        Do i = 1, n1
          Write (nout,*)
          Write (nout,99999) 'Real ', (x(i,j),j=1,n2)
          Write (nout,99999) 'Imag ', (y(i,j),j=1,n2)
        End Do
        Return

99999   Format (1X,A,7F10.3,/,(6X,7F10.3))
      End Subroutine writxy
    End Module c06fjfe_mod

    Program c06fjfe

!     C06FJF Example Main Program

!     .. Use Statements ..
      Use nag_library, Only: c06fjf, nag_wp
      Use c06fjfe_mod, Only: nin, nout, readxy, writxy
!     .. Implicit None Statement ..
      Implicit None
!     .. Local Scalars ..
      Integer                          :: ieof, ifail, lwork, n, ndim
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: work(:), x(:), y(:)
      Integer, Allocatable             :: nd(:)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: maxval, product
!     .. Executable Statements ..
      Write (nout,*) 'C06FJF Example Program Results'
!     Skip heading in data file
      Read (nin,*)
loop: Do
        Read (nin,*,Iostat=ieof) ndim
        If (ieof<0) Then
          Exit loop
        End If

        Allocate (nd(ndim))
        Read (nin,*) nd(1:ndim)
        n = product(nd(1:ndim))
        lwork = 3*maxval(nd(1:ndim))
        Allocate (x(n),y(n),work(lwork))

        Call readxy(nin,x,y,nd(1),nd(2))
        Write (nout,*)
        Write (nout,*) 'Original data values'
        Call writxy(nout,x,y,nd(1),nd(2))

!       ifail: behaviour on error exit
!              =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
        ifail = 0
!       Compute transform
        Call c06fjf(ndim,nd,n,x,y,work,lwork,ifail)

        Write (nout,*)
        Write (nout,*) 'Components of discrete Fourier transform'
        Call writxy(nout,x,y,nd(1),nd(2))

!       Compute inverse transform
        y(1:n) = -y(1:n)
        Call c06fjf(ndim,nd,n,x,y,work,lwork,ifail)
        y(1:n) = -y(1:n)

        Write (nout,*)
        Write (nout,*) 'Original sequence as restored by inverse transform'
        Call writxy(nout,x,y,nd(1),nd(2))
        Deallocate (x,y,work,nd)

      End Do loop

    End Program c06fjfe


c06fkfe.f90

    Program c06fkfe

!     C06FKF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: c06fkf, nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Integer                          :: ieof, ifail, j, n
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: work(:), xa(:), xb(:), ya(:), yb(:)
!     .. Executable Statements ..
      Write (nout,*) 'C06FKF Example Program Results'
      Write (nout,*)
!     Skip heading in data file
      Read (nin,*)
loop: Do
        Read (nin,*,Iostat=ieof) n
        If (ieof<0) Then
          Exit loop
        End If

        Allocate (work(n),xa(n),xb(n),ya(n),yb(n))
        Read (nin,*)(xa(j),ya(j),j=1,n)
        xb(1:n) = xa(1:n)
        yb(1:n) = ya(1:n)

!       ifail: behaviour on error exit
!              =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
        ifail = 0
        Call c06fkf(1,xa,ya,n,work,ifail)

        Call c06fkf(2,xb,yb,n,work,ifail)

        Write (nout,*) '        Convolution  Correlation'
        Write (nout,*)
        Write (nout,99999)(j-1,xa(j),xb(j),j=1,n)
        Deallocate (xa,xb,ya,yb,work)
      End Do loop

99999 Format (1X,I5,2F13.5)
    End Program c06fkfe


c06fpfe.f90

    Program c06fpfe

!     C06FPF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: c06fpf, c06fqf, nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Integer                          :: i, ieof, ifail, j, m, n
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: trig(:), u(:), v(:), work(:), x(:)
!     .. Executable Statements ..
      Write (nout,*) 'C06FPF Example Program Results'
!     Skip heading in data file
      Read (nin,*)
loop: Do
        Read (nin,*,Iostat=ieof) m, n
        If (ieof<0) Then
          Exit loop
        End If

        Allocate (trig(2*n),u(n),v(n),work(2*m*n),x(m*n))
        Do j = 1, m
          Read (nin,*)(x(i*m+j),i=0,n-1)
        End Do
        Write (nout,*)
        Write (nout,*) 'Original data values'
        Write (nout,*)
        Write (nout,99999)('     ',(x(i*m+j),i=0,n-1),j=1,m)

!       ifail: behaviour on error exit
!              =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
        ifail = 0
        Call c06fpf(m,n,x,'Initial',trig,work,ifail)

        Write (nout,*)
        Write (nout,*) 'Discrete Fourier transforms in Hermitian format'
        Write (nout,*)
        Write (nout,99999)('     ',(x(i*m+j),i=0,n-1),j=1,m)
        Write (nout,*)
        Write (nout,*) 'Fourier transforms in full complex form'

        Do j = 1, m
          u(1:n) = x(j:m*n:m)
          v(1:n) = 0.0_nag_wp
          v(2:(n+1)/2) = u(n:n-(n-1)/2+1:-1)
          u(n:n-(n-1)/2+1:-1) = u(2:(n+1)/2)
          v(n-(n-1)/2+1:n) = -v((n+1)/2:2:-1)
          Write (nout,*)
          Write (nout,99999) 'Real ', u(1:n)
          Write (nout,99999) 'Imag ', v(1:n)
        End Do

        x((n/2+1)*m+1:m*n) = -x((n/2+1)*m+1:m*n)
        Call c06fqf(m,n,x,'Subsequent',trig,work,ifail)

        Write (nout,*)
        Write (nout,*) 'Original data as restored by inverse transform'
        Write (nout,*)
        Write (nout,99999)('     ',(x(i*m+j),i=0,n-1),j=1,m)
        Deallocate (trig,u,v,work,x)
      End Do loop

99999 Format (1X,A,6F10.4)
    End Program c06fpfe


c06fqfe.f90

    Program c06fqfe

!     C06FQF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: c06fpf, c06fqf, nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Integer                          :: i, ieof, ifail, j, m, n
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: trig(:), u(:), v(:), work(:), x(:)
!     .. Executable Statements ..
      Write (nout,*) 'C06FQF Example Program Results'
!     Skip heading in data file
      Read (nin,*)
loop: Do
        Read (nin,*,Iostat=ieof) m, n
        If (ieof<0) Then
          Exit loop
        End If

        Allocate (trig(2*n),u(n),v(n),work(2*m*n),x(m*n))
        Do j = 1, m
          Read (nin,*)(x(i*m+j),i=0,n-1)
        End Do
        Write (nout,*)
        Write (nout,*) 'Original data values'
        Write (nout,*)
        Write (nout,99999)('     ',(x(i*m+j),i=0,n-1),j=1,m)
        Write (nout,*)
        Write (nout,*) 'Original data written in full complex form'

        Do j = 1, m
          u(1:n) = x(j:m*n:m)
          v(1:n) = 0.0_nag_wp
          v(2:(n+1)/2) = u(n:n-(n-1)/2+1:-1)
          u(n:n-(n-1)/2+1:-1) = u(2:(n+1)/2)
          v(n-(n-1)/2+1:n) = -v((n+1)/2:2:-1)
          Write (nout,*)
          Write (nout,99999) 'Real ', u(1:n)
          Write (nout,99999) 'Imag ', v(1:n)
        End Do

        ifail = 0
        Call c06fqf(m,n,x,'Initial',trig,work,ifail)

        Write (nout,*)
        Write (nout,*) 'Discrete Fourier transforms (real values)'
        Write (nout,*)
        Write (nout,99999)('     ',(x(i*m+j),i=0,n-1),j=1,m)

        Call c06fpf(m,n,x,'Subsequent',trig,work,ifail)
        x((n/2+1)*m+1:m*n) = -x((n/2+1)*m+1:m*n)

        Write (nout,*)
        Write (nout,*) 'Original data as restored by inverse transform'
        Write (nout,*)
        Write (nout,99999)('     ',(x(i*m+j),i=0,n-1),j=1,m)
        Deallocate (trig,u,v,work,x)
      End Do loop

99999 Format (1X,A,6F10.4)
    End Program c06fqfe


c06fxfe.f90

!   C06FXF Example Program Text
!   Mark 26 Release. NAG Copyright 2016.

    Module c06fxfe_mod

!     C06FXF Example Program Module:
!            Parameters and User-defined Routines

!     .. Use Statements ..
      Use nag_library, Only: nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Accessibility Statements ..
      Private
      Public                           :: readxy, writxy
!     .. Parameters ..
      Integer, Parameter, Public       :: nin = 5, nout = 6
    Contains
      Subroutine readxy(nin,x,y,n1,n2,n3)
!       Read 3-dimensional complex data

!       .. Scalar Arguments ..
        Integer, Intent (In)           :: n1, n2, n3, nin
!       .. Array Arguments ..
        Real (Kind=nag_wp), Intent (Out) :: x(n1,n2,n3), y(n1,n2,n3)
!       .. Local Scalars ..
        Integer                        :: i, j, k
!       .. Executable Statements ..
        Do i = 1, n1
          Do j = 1, n2
            Read (nin,*)(x(i,j,k),k=1,n3)
            Read (nin,*)(y(i,j,k),k=1,n3)
          End Do
        End Do
        Return
      End Subroutine readxy

      Subroutine writxy(nout,x,y,n1,n2,n3)
!       Print 3-dimensional complex data

!       .. Scalar Arguments ..
        Integer, Intent (In)           :: n1, n2, n3, nout
!       .. Array Arguments ..
        Real (Kind=nag_wp), Intent (In) :: x(n1,n2,n3), y(n1,n2,n3)
!       .. Local Scalars ..
        Integer                        :: i, j, k
!       .. Executable Statements ..
        Do i = 1, n1
          Write (nout,*)
          Write (nout,99998) 'z(i,j,k) for i =', i
          Do j = 1, n2
            Write (nout,*)
            Write (nout,99999) 'Real ', (x(i,j,k),k=1,n3)
            Write (nout,99999) 'Imag ', (y(i,j,k),k=1,n3)
          End Do
        End Do
        Return

99999   Format (1X,A,7F10.3,/,(6X,7F10.3))
99998   Format (1X,A,I6)
      End Subroutine writxy
    End Module c06fxfe_mod

    Program c06fxfe

!     C06FXF Example Main Program

!     .. Use Statements ..
      Use nag_library, Only: c06fxf, nag_wp
      Use c06fxfe_mod, Only: nin, nout, readxy, writxy
!     .. Implicit None Statement ..
      Implicit None
!     .. Local Scalars ..
      Integer                          :: ieof, ifail, n, n1, n2, n3
      Character (1)                    :: cdum
!     .. Local Arrays ..
      Real (Kind=nag_wp)               :: dum(1)
      Real (Kind=nag_wp), Allocatable  :: x(:), y(:)
!     .. Executable Statements ..
      Write (nout,*) 'C06FXF Example Program Results'
!     Skip heading in data file
      Read (nin,*)

loop: Do
        Read (nin,*,Iostat=ieof) n1, n2, n3
        If (ieof<0) Then
          Exit loop
        End If

        n = n1*n2*n3
        Allocate (x(n),y(n))

        Call readxy(nin,x,y,n1,n2,n3)
        Write (nout,*)
        Write (nout,*) 'Original data values'
        Call writxy(nout,x,y,n1,n2,n3)

!       ifail: behaviour on error exit
!              =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
        ifail = 0
!       -- Compute transform
        Call c06fxf(n1,n2,n3,x,y,cdum,dum,dum,dum,dum,ifail)

        Write (nout,*)
        Write (nout,*) 'Components of discrete Fourier transform'
        Call writxy(nout,x,y,n1,n2,n3)

!       -- Compute inverse transform
        y(1:n) = -y(1:n)
        Call c06fxf(n1,n2,n3,x,y,cdum,dum,dum,dum,dum,ifail)
        y(1:n) = -y(1:n)

        Write (nout,*)
        Write (nout,*) 'Original sequence as restored by inverse transform'
        Call writxy(nout,x,y,n1,n2,n3)
        Deallocate (x,y)
      End Do loop

    End Program c06fxfe


c06lafe.f90

!   C06LAF Example Program Text
!   Mark 26 Release. NAG Copyright 2016.

    Module c06lafe_mod

!     C06LAF Example Program Module:
!            Parameters and User-defined Routines

!     .. Use Statements ..
      Use nag_library, Only: nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Accessibility Statements ..
      Private
      Public                           :: fun
!     .. Parameters ..
      Integer, Parameter, Public       :: nin = 5, nout = 6
    Contains
      Subroutine fun(pr,pi,fr,fi)
!       Function to be inverted

!       .. Use Statements ..
        Use nag_library, Only: a02acf
!       .. Scalar Arguments ..
        Real (Kind=nag_wp), Intent (Out) :: fi, fr
        Real (Kind=nag_wp), Intent (In) :: pi, pr
!       .. Local Scalars ..
        Real (Kind=nag_wp)             :: xi, xr, yi, yr
!       .. Executable Statements ..
        xr = 1.0_nag_wp
        xi = 0.0_nag_wp
        yr = pr + 0.5_nag_wp
        yi = pi

        Call a02acf(xr,xi,yr,yi,fr,fi)

        Return
      End Subroutine fun
    End Module c06lafe_mod

    Program c06lafe

!     C06LAF Example Main Program

!     .. Use Statements ..
      Use nag_library, Only: c06laf, nag_wp
      Use c06lafe_mod, Only: fun, nin, nout
!     .. Implicit None Statement ..
      Implicit None
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: ahigh, alow, alphab, relerr, tfac
      Integer                          :: i, ifail, itest, mxterm, n, n1, na,  &
                                          nfeval, nterms
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: errest(:), t(:), trurel(:),          &
                                          trures(:), valinv(:), work(:)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: abs, exp, real
!     .. Executable Statements ..
      Write (nout,*) 'C06LAF Example Program Results'
      Write (nout,*)
      Write (nout,*) '(results may be machine-dependent)'
!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) n, mxterm
      Allocate (errest(n),t(n),trurel(n),trures(n),valinv(n),work(4*mxterm+2))

      t(1) = 1.0_nag_wp
      alphab = -0.5_nag_wp

tests: Do itest = 1, 3

        Select Case (itest)
        Case (1)
!         Test for values of a close to alphab
          relerr = 0.01E0_nag_wp
          tfac = 7.5E0_nag_wp
          n1 = 1
          Write (nout,99997) t(1)
        Case (2)
!         Test for larger values of a
          relerr = 1.0E-3_nag_wp
          tfac = 0.8E0_nag_wp
          n1 = 1
          Write (nout,99997) t(1)
        Case (3)
          Write (nout,'(/1x,A/)') 'Compute inverse'
          n1 = 5
          Do i = 1, n1
            t(i) = real(i,kind=nag_wp)
          End Do
        End Select
        Write (nout,99999) mxterm, tfac, alphab, relerr

        ifail = -1
        Call c06laf(fun,n1,t,valinv,errest,relerr,alphab,tfac,mxterm,nterms,   &
          na,alow,ahigh,nfeval,work,ifail)

        If (ifail==0 .Or. ifail>=5) Then
          Write (nout,*)
          Write (nout,*) '   T        Result        exp(-T/2)   ',             &
            'Relative error  Error estimate'
          trures(1:n1) = exp(-0.5_nag_wp*t(1:n1))
          trurel(1:n1) = abs((valinv(1:n1)-trures(1:n1))/trures(1:n1))
          Write (nout,99998)(t(i),valinv(i),trures(i),trurel(i),errest(i),i=1, &
            n1)
        Else
          Exit tests
        End If
      End Do tests
      If (ifail>=0) Then
        Write (nout,99996) nterms, nfeval, alow, ahigh, ifail
      End If

99999 Format (1X,'  MXTERM =',I4,'  TFAC =',F6.2,'  ALPHAB =',F6.2,            &
        '  RELERR =',1P,E8.1)
99998 Format (1X,F4.1,7X,F6.3,9X,F6.3,8X,E8.1,8X,E8.1)
99997 Format (/,1X,'Test with T(1) =',F4.1,/)
99996 Format (/,1X,' NTERMS =',I4,'  NFEVAL =',I4,'  ALOW =',F7.2,'  AHIGH =', &
        F7.2,'  IFAIL =',I2)
    End Program c06lafe


c06lbfe.f90

!   C06LBF Example Program Text
!   Mark 26 Release. NAG Copyright 2016.

    Module c06lbfe_mod

!     C06LBF Example Program Module:
!            Parameters and User-defined Routines

!     .. Use Statements ..
      Use nag_library, Only: nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Accessibility Statements ..
      Private
      Public                           :: f
!     .. Parameters ..
      Integer, Parameter, Public       :: nin = 5, nout = 6
    Contains
      Function f(s)

!       .. Function Return Value ..
        Complex (Kind=nag_wp)          :: f
!       .. Scalar Arguments ..
        Complex (Kind=nag_wp), Intent (In) :: s
!       .. Intrinsic Procedures ..
        Intrinsic                      :: cmplx
!       .. Executable Statements ..
        f = cmplx(3.0E0_nag_wp,kind=nag_wp)/(s**2-cmplx(9.0E0_nag_wp,kind=     &
          nag_wp))
        Return
      End Function f
    End Module c06lbfe_mod

    Program c06lbfe

!     C06LBF Example Main Program

!     .. Use Statements ..
      Use nag_library, Only: c06lbf, c06lcf, nag_wp
      Use c06lbfe_mod, Only: f, nin, nout
!     .. Implicit None Statement ..
      Implicit None
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: b, epstol, exact, finv, pserr,       &
                                          sigma, sigma0, t
      Integer                          :: ifail, j, m, mmax
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: acoef(:)
      Real (Kind=nag_wp)               :: errvec(8)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: abs, exp, real, sinh
!     .. Executable Statements ..
      Write (nout,*) 'C06LBF Example Program Results'
!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) mmax
      Allocate (acoef(mmax))
      Read (nin,*) sigma0, epstol, sigma, b

!     ifail: behaviour on error exit
!             =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
      ifail = 0
!     Compute inverse transform
      Call c06lbf(f,sigma0,sigma,b,epstol,mmax,m,acoef,errvec,ifail)

      Write (nout,*)
      Write (nout,99999) 'No. of coefficients returned by C06LBF =', m
      Write (nout,*)
      Write (nout,99998) ' ', 'Computed', 'Exact', 'Pseudo'
      Write (nout,99998) 'T', '    f(T)', ' f(T)', ' error'
      Write (nout,*)

!     Evaluate inverse transform for different values of t
      Do j = 0, 5
        t = real(j,kind=nag_wp)

        Call c06lcf(t,sigma,b,m,acoef,errvec,finv,ifail)

        exact = sinh(3.0E0_nag_wp*t)
        pserr = abs(finv-exact)/exp(sigma*t)
        Write (nout,99997) t, finv, exact, pserr
      End Do

99999 Format (1X,A,I6)
99998 Format (1X,A10,A15,A15,A12)
99997 Format (1X,1P,E10.2,2E15.4,E12.1)
    End Program c06lbfe


c06pafe.f90

    Program c06pafe

!     C06PAF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: c06paf, nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Integer                          :: ieof, ifail, j, n, nj
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: work(:), x(:), xx(:)
!     .. Executable Statements ..
      Write (nout,*) 'C06PAF Example Program Results'
!     Skip heading in data file
      Read (nin,*)
loop: Do
        Read (nin,*,Iostat=ieof) n
        If (ieof<0) Then
          Exit loop
        End If

        Allocate (work(3*n+100),x(0:n+1),xx(0:n-1))
        Read (nin,*) x(0:n-1)
        xx(0:n-1) = x(0:n-1)

!       ifail: behaviour on error exit
!              =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
        ifail = 0
        Call c06paf('F',x,n,work,ifail)

        Write (nout,*)
        Write (nout,*) 'Components of discrete Fourier transform'
        Write (nout,*)
        Write (nout,*) '          Real      Imag'
        Write (nout,*)
        Write (nout,99999)(j,x(2*j),x(2*j+1),j=0,n/2)
        Do j = n/2 + 1, n - 1
          nj = n - j
          Write (nout,99999) j, x(2*nj), -x(2*nj+1)
        End Do

        Call c06paf('B',x,n,work,ifail)

        Write (nout,*)
        Write (nout,*) 'Original sequence as restored by inverse transform'
        Write (nout,*)
        Write (nout,*) '        Original  Restored'
        Write (nout,*)
        Write (nout,99999)(j,xx(j),x(j),j=0,n-1)
        Deallocate (work,x,xx)
      End Do loop

99999 Format (1X,I5,2F10.5)
    End Program c06pafe


c06pcfe.f90

    Program c06pcfe

!     C06PCF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: c06pcf, nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Integer                          :: ieof, ifail, j, n
!     .. Local Arrays ..
      Complex (Kind=nag_wp), Allocatable :: work(:), x(:), xx(:)
!     .. Executable Statements ..
      Write (nout,*) 'C06PCF Example Program Results'
!     Skip heading in data file
      Read (nin,*)
loop: Do
        Read (nin,*,Iostat=ieof) n
        If (ieof<0) Then
          Exit loop
        End If

        Allocate (work(2*n+15),x(0:n-1),xx(0:n-1))
        Read (nin,*) x(0:n-1)
        xx(0:n-1) = x(0:n-1)

!       ifail: behaviour on error exit
!              =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
        ifail = 0
        Call c06pcf('F',x,n,work,ifail)

        Write (nout,*)
        Write (nout,*) 'Components of discrete Fourier transform'
        Write (nout,*)
        Write (nout,*) '              Real      Imag'
        Write (nout,*)
        Do j = 0, n - 1
          Write (nout,99999) j, x(j)
        End Do

        Call c06pcf('B',x,n,work,ifail)

        Write (nout,*)
        Write (nout,*) 'Original sequence as restored by inverse transform'
        Write (nout,*)
        Write (nout,*) '                 Original                 Restored'
        Write (nout,*) '              Real      Imag           Real      Imag'
        Write (nout,*)
        Do j = 0, n - 1
          Write (nout,99999) j, xx(j), x(j)
        End Do
        Deallocate (work,x,xx)
      End Do loop

99999 Format (1X,I5,2(:,5X,'(',F8.5,',',F8.5,')'))
    End Program c06pcfe


c06pffe.f90

!   C06PFF Example Program Text
!   Mark 26 Release. NAG Copyright 2016.

    Module c06pffe_mod

!     C06PFF Example Program Module:
!            Parameters and User-defined Routines

!     .. Use Statements ..
      Use nag_library, Only: nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Accessibility Statements ..
      Private
      Public                           :: readx, writx
!     .. Parameters ..
      Integer, Parameter, Public       :: nin = 5, nout = 6
    Contains
      Subroutine readx(nin,x,n1,n2)
!       Read 2-dimensional complex data

!       .. Scalar Arguments ..
        Integer, Intent (In)           :: n1, n2, nin
!       .. Array Arguments ..
        Complex (Kind=nag_wp), Intent (Out) :: x(n1,n2)
!       .. Local Scalars ..
        Integer                        :: i, j
!       .. Executable Statements ..
        Do i = 1, n1
          Read (nin,*)(x(i,j),j=1,n2)
        End Do
        Return
      End Subroutine readx

      Subroutine writx(nout,x,n1,n2)
!       Print 2-dimensional complex data

!       .. Scalar Arguments ..
        Integer, Intent (In)           :: n1, n2, nout
!       .. Array Arguments ..
        Complex (Kind=nag_wp), Intent (In) :: x(n1,n2)
!       .. Local Scalars ..
        Integer                        :: i, j
!       .. Executable Statements ..
        Do i = 1, n1
          Write (nout,*)
          Write (nout,99999)(x(i,j),j=1,n2)
        End Do
        Return

99999   Format (1X,7(:,1X,'(',F6.3,',',F6.3,')'))
      End Subroutine writx
    End Module c06pffe_mod

    Program c06pffe

!     C06PFF Example Main Program

!     .. Use Statements ..
      Use nag_library, Only: c06pff, nag_wp
      Use c06pffe_mod, Only: nin, nout, readx, writx
!     .. Implicit None Statement ..
      Implicit None
!     .. Local Scalars ..
      Integer                          :: ieof, ifail, l, lwork, n, ndim
!     .. Local Arrays ..
      Complex (Kind=nag_wp), Allocatable :: work(:), x(:)
      Integer, Allocatable             :: nd(:)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: product
!     .. Executable Statements ..
      Write (nout,*) 'C06PFF Example Program Results'
!     Skip heading in data file
      Read (nin,*)
loop: Do
        Read (nin,*,Iostat=ieof) ndim
        If (ieof<0) Then
          Exit loop
        End If
        Allocate (nd(ndim))
        Read (nin,*) nd(1:ndim), l
        n = product(nd(1:ndim))
        lwork = n + nd(l) + 15
        Allocate (x(n),work(lwork))
        Call readx(nin,x,nd(1),nd(2))
        Write (nout,*)
        Write (nout,*) 'Original data'
        Call writx(nout,x,nd(1),nd(2))

!       ifail: behaviour on error exit
!              =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
        ifail = 0
!       Compute transform
        Call c06pff('F',ndim,l,nd,n,x,work,lwork,ifail)

        Write (nout,*)
        Write (nout,99999) 'Discrete Fourier transform of variable ', l
        Call writx(nout,x,nd(1),nd(2))

!       Compute inverse transform
        Call c06pff('B',ndim,l,nd,n,x,work,lwork,ifail)

        Write (nout,*)
        Write (nout,*) 'Original sequence as restored by inverse transform'
        Call writx(nout,x,nd(1),nd(2))
        Deallocate (nd,x,work)

      End Do loop

99999 Format (1X,A,I1)
    End Program c06pffe


c06pjfe.f90

!   C06PJF Example Program Text
!   Mark 26 Release. NAG Copyright 2016.

    Module c06pjfe_mod

!     C06PJF Example Program Module:
!            Parameters and User-defined Routines

!     .. Use Statements ..
      Use nag_library, Only: nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Accessibility Statements ..
      Private
      Public                           :: readx, writx
!     .. Parameters ..
      Integer, Parameter, Public       :: nin = 5, nout = 6
    Contains
      Subroutine readx(nin,x,n1,n2)
!       Read 2-dimensional complex data

!       .. Scalar Arguments ..
        Integer, Intent (In)           :: n1, n2, nin
!       .. Array Arguments ..
        Complex (Kind=nag_wp), Intent (Out) :: x(n1,n2)
!       .. Local Scalars ..
        Integer                        :: i, j
!       .. Executable Statements ..
        Do i = 1, n1
          Read (nin,*)(x(i,j),j=1,n2)
        End Do
        Return
      End Subroutine readx

      Subroutine writx(nout,x,n1,n2)
!       Print 2-dimensional complex data

!       .. Scalar Arguments ..
        Integer, Intent (In)           :: n1, n2, nout
!       .. Array Arguments ..
        Complex (Kind=nag_wp), Intent (In) :: x(n1,n2)
!       .. Local Scalars ..
        Integer                        :: i, j
!       .. Executable Statements ..
        Do i = 1, n1
          Write (nout,*)
          Write (nout,99999)(x(i,j),j=1,n2)
        End Do
        Return

99999   Format (1X,7(:,1X,'(',F6.3,',',F6.3,')'))
      End Subroutine writx
    End Module c06pjfe_mod

    Program c06pjfe

!     C06PJF Example Main Program

!     .. Use Statements ..
      Use nag_library, Only: c06pjf, nag_wp
      Use c06pjfe_mod, Only: nin, nout, readx, writx
!     .. Implicit None Statement ..
      Implicit None
!     .. Local Scalars ..
      Integer                          :: ieof, ifail, lwork, n, ndim
!     .. Local Arrays ..
      Complex (Kind=nag_wp), Allocatable :: work(:), x(:)
      Integer, Allocatable             :: nd(:)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: maxval, product
!     .. Executable Statements ..
      Write (nout,*) 'C06PJF Example Program Results'
!     Skip heading in data file
      Read (nin,*)
loop: Do
        Read (nin,*,Iostat=ieof) ndim
        If (ieof<0) Then
          Exit loop
        End If
        Allocate (nd(ndim))
        Read (nin,*) nd(1:ndim)
        n = product(nd(1:ndim))
        lwork = n + 3*maxval(nd(1:ndim)) + 15
        Allocate (x(n),work(lwork))
        Call readx(nin,x,nd(1),nd(2))
        Write (nout,*)
        Write (nout,*) 'Original data values'
        Call writx(nout,x,nd(1),nd(2))

!       ifail: behaviour on error exit
!              =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
        ifail = 0
!       Compute transform
        Call c06pjf('F',ndim,nd,n,x,work,lwork,ifail)

        Write (nout,*)
        Write (nout,*) 'Components of discrete Fourier transform'
        Call writx(nout,x,nd(1),nd(2))

!       Compute inverse transform
        Call c06pjf('B',ndim,nd,n,x,work,lwork,ifail)

        Write (nout,*)
        Write (nout,*) 'Original sequence as restored by inverse transform'
        Call writx(nout,x,nd(1),nd(2))
        Deallocate (nd,x,work)
      End Do loop

    End Program c06pjfe


c06pkfe.f90

    Program c06pkfe

!     C06PKF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: c06pkf, nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Integer                          :: ieof, ifail, j, n
!     .. Local Arrays ..
      Complex (Kind=nag_wp), Allocatable :: work(:), xa(:), xb(:), ya(:),      &
                                          yb(:)
!     .. Executable Statements ..
      Write (nout,*) 'C06PKF Example Program Results'
      Write (nout,*)
!     Skip heading in data file
      Read (nin,*)
loop: Do
        Read (nin,*,Iostat=ieof) n
        If (ieof<0) Then
          Exit loop
        End If

        Allocate (work(2*n+15),xa(n),xb(n),ya(n),yb(n))
        Read (nin,*)(xa(j),ya(j),j=1,n)
        xb(1:n) = xa(1:n)
        yb(1:n) = ya(1:n)

!       ifail: behaviour on error exit
!              =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
        ifail = 0
        Call c06pkf(1,xa,ya,n,work,ifail)

        Call c06pkf(2,xb,yb,n,work,ifail)

        Write (nout,*) '        Convolution            Correlation'
        Write (nout,*)
        Do j = 0, n - 1
          Write (nout,99999) j, xa(j+1), xb(j+1)
        End Do
        Deallocate (work,xa,xb,ya,yb)
      End Do loop

99999 Format (1X,I5,2(1X,'(',F9.5,',',F9.5,')'))
    End Program c06pkfe


c06ppfe.f90

    Program c06ppfe

!     C06PPF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: c06ppf, nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Integer                          :: i, ieof, ifail, j, m, n
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: work(:), x(:)
!     .. Executable Statements ..
      Write (nout,*) 'C06PPF Example Program Results'
!     Skip heading in data file
      Read (nin,*)
loop: Do
        Read (nin,*,Iostat=ieof) m, n
        If (ieof<0) Then
          Exit loop
        End If

        Allocate (work((m+2)*(n+2)+11),x(m*(n+2)))
        Do j = 1, m
          Read (nin,*)(x(i*m+j),i=0,n-1)
        End Do
        Write (nout,*)
        Write (nout,*) 'Original data values'
        Write (nout,*)
        Do j = 1, m
          Write (nout,99999) '     ', (x(i*m+j),i=0,n-1)
        End Do

!       ifail: behaviour on error exit
!              =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
        ifail = 0
        Call c06ppf('F',m,n,x,work,ifail)

        Write (nout,*)
        Write (nout,*)                                                         &
          'Discrete Fourier transforms in complex Hermitian format'
        Do j = 1, m
          Write (nout,*)
          Write (nout,99999) 'Real ', (x(2*i*m+j),i=0,n/2)
          Write (nout,99999) 'Imag ', (x((2*i+1)*m+j),i=0,n/2)
        End Do
        Write (nout,*)
        Write (nout,*) 'Fourier transforms in full complex form'

        Do j = 1, m
          Write (nout,*)
          Write (nout,99999) 'Real ', (x(2*i*m+j),i=0,n/2),                    &
            (x(2*(n-i)*m+j),i=n/2+1,n-1)
          Write (nout,99999) 'Imag ', (x((2*i+1)*m+j),i=0,n/2),                &
            (-x((2*(n-i)+1)*m+j),i=n/2+1,n-1)
        End Do

        Call c06ppf('B',m,n,x,work,ifail)

        Write (nout,*)
        Write (nout,*) 'Original data as restored by inverse transform'
        Write (nout,*)
        Do j = 1, m
          Write (nout,99999) '     ', (x(i*m+j),i=0,n-1)
        End Do
        Deallocate (x,work)
      End Do loop

99999 Format (1X,A,9(:,1X,F10.4))
    End Program c06ppfe


c06pqfe.f90

    Program c06pqfe

!     C06PQF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: c06pqf, nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Integer                          :: i, ieof, ifail, j, m, n
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: work(:), x(:)
!     .. Executable Statements ..
      Write (nout,*) 'C06PQF Example Program Results'
!     Skip heading in data file
      Read (nin,*)
loop: Do
        Read (nin,*,Iostat=ieof) m, n
        If (ieof<0) Then
          Exit loop
        End If

        Allocate (work((m+2)*n+15),x(m*(n+2)))
        Do j = 1, m*(n+2), n + 2
          Read (nin,*)(x(j+i),i=0,n-1)
        End Do
        Write (nout,*)
        Write (nout,*) 'Original data values'
        Write (nout,*)
        Do j = 1, m*(n+2), n + 2
          Write (nout,99999) '     ', (x(j+i),i=0,n-1)
        End Do

!       ifail: behaviour on error exit
!              =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
        ifail = 0
        Call c06pqf('F',n,m,x,work,ifail)

        Write (nout,*)
        Write (nout,*)                                                         &
          'Discrete Fourier transforms in complex Hermitian format'
        Do j = 1, m*(n+2), n + 2
          Write (nout,*)
          Write (nout,99999) 'Real ', (x(j+2*i),i=0,n/2)
          Write (nout,99999) 'Imag ', (x(j+2*i+1),i=0,n/2)
        End Do
        Write (nout,*)
        Write (nout,*) 'Fourier transforms in full complex form'

        Do j = 1, m*(n+2), n + 2
          Write (nout,*)
          Write (nout,99999) 'Real ', (x(j+2*i),i=0,n/2),                      &
            (x(j+2*(n-i)),i=n/2+1,n-1)
          Write (nout,99999) 'Imag ', (x(j+2*i+1),i=0,n/2),                    &
            (-x(j+2*(n-i)+1),i=n/2+1,n-1)
        End Do

        Call c06pqf('B',n,m,x,work,ifail)

        Write (nout,*)
        Write (nout,*) 'Original data as restored by inverse transform'
        Write (nout,*)
        Do j = 1, m*(n+2), n + 2
          Write (nout,99999) '     ', (x(j+i),i=0,n-1)
        End Do
        Deallocate (x,work)
      End Do loop

99999 Format (1X,A,9(:,1X,F10.4))
    End Program c06pqfe


c06prfe.f90

    Program c06prfe

!     C06PRF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: c06prf, nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Integer                          :: i, ieof, ifail, j, m, n
!     .. Local Arrays ..
      Complex (Kind=nag_wp), Allocatable :: work(:), x(:)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: aimag, real
!     .. Executable Statements ..
      Write (nout,*) 'C06PRF Example Program Results'
!     Skip heading in data file
      Read (nin,*)
loop: Do
        Read (nin,*,Iostat=ieof) m, n
        If (ieof<0) Then
          Exit loop
        End If

        Allocate (work((m+2)*n+15),x(m*n))
        Do j = 1, m
          Read (nin,*)(x(i*m+j),i=0,n-1)
        End Do
        Write (nout,*)
        Write (nout,*) 'Original data values'
        Do j = 1, m
          Write (nout,*)
          Write (nout,99999) 'Real ', (real(x(i*m+j)),i=0,n-1)
          Write (nout,99999) 'Imag ', (aimag(x(i*m+j)),i=0,n-1)
        End Do

!       ifail: behaviour on error exit
!              =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
        ifail = 0
        Call c06prf('F',m,n,x,work,ifail)

        Write (nout,*)
        Write (nout,*) 'Discrete Fourier transforms'
        Do j = 1, m
          Write (nout,*)
          Write (nout,99999) 'Real ', (real(x(i*m+j)),i=0,n-1)
          Write (nout,99999) 'Imag ', (aimag(x(i*m+j)),i=0,n-1)
        End Do

        ifail = 0
        Call c06prf('B',m,n,x,work,ifail)

        Write (nout,*)
        Write (nout,*) 'Original data as restored by inverse transform'
        Do j = 1, m
          Write (nout,*)
          Write (nout,99999) 'Real ', (real(x(i*m+j)),i=0,n-1)
          Write (nout,99999) 'Imag ', (aimag(x(i*m+j)),i=0,n-1)
        End Do
        Deallocate (x,work)
      End Do loop

99999 Format (1X,A,6F10.4)
    End Program c06prfe


c06psfe.f90

    Program c06psfe

!     C06PSF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: c06psf, nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Integer                          :: i, ieof, ifail, j, m, n
!     .. Local Arrays ..
      Complex (Kind=nag_wp), Allocatable :: work(:), x(:)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: aimag, real
!     .. Executable Statements ..
      Write (nout,*) 'C06PSF Example Program Results'
!     Skip heading in data file
      Read (nin,*)
loop: Do
        Read (nin,*,Iostat=ieof) m, n
        If (ieof<0) Then
          Exit loop
        End If

        Allocate (work(n*m+n+15),x(m*n))
        Do j = 1, m*n, n
          Read (nin,*)(x(j+i),i=0,n-1)
        End Do
        Write (nout,*)
        Write (nout,*) 'Original data values'
        Do j = 1, m*n, n
          Write (nout,*)
          Write (nout,99999) 'Real ', (real(x(j+i)),i=0,n-1)
          Write (nout,99999) 'Imag ', (aimag(x(j+i)),i=0,n-1)
        End Do

!       ifail: behaviour on error exit
!              =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
        ifail = 0
        Call c06psf('F',n,m,x,work,ifail)

        Write (nout,*)
        Write (nout,*) 'Discrete Fourier transforms'
        Do j = 1, m*n, n
          Write (nout,*)
          Write (nout,99999) 'Real ', (real(x(j+i)),i=0,n-1)
          Write (nout,99999) 'Imag ', (aimag(x(j+i)),i=0,n-1)
        End Do

        Call c06psf('B',n,m,x,work,ifail)

        Write (nout,*)
        Write (nout,*) 'Original data as restored by inverse transform'
        Do j = 1, m*n, n
          Write (nout,*)
          Write (nout,99999) 'Real ', (real(x(j+i)),i=0,n-1)
          Write (nout,99999) 'Imag ', (aimag(x(j+i)),i=0,n-1)
        End Do
        Deallocate (x,work)
      End Do loop

99999 Format (1X,A,6F10.4)
    End Program c06psfe


c06pufe.f90

!   C06PUF Example Program Text
!   Mark 26 Release. NAG Copyright 2016.

    Module c06pufe_mod

!     C06PUF Example Program Module:
!            Parameters and User-defined Routines

!     .. Use Statements ..
      Use nag_library, Only: nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Accessibility Statements ..
      Private
      Public                           :: readx, writx
!     .. Parameters ..
      Integer, Parameter, Public       :: nin = 5, nout = 6
    Contains
      Subroutine readx(nin,x,n1,n2)
!       Read 2-dimensional complex data

!       .. Scalar Arguments ..
        Integer, Intent (In)           :: n1, n2, nin
!       .. Array Arguments ..
        Complex (Kind=nag_wp), Intent (Out) :: x(n1,n2)
!       .. Local Scalars ..
        Integer                        :: i, j
!       .. Executable Statements ..
        Do i = 1, n1
          Read (nin,*)(x(i,j),j=1,n2)
        End Do
        Return
      End Subroutine readx

      Subroutine writx(nout,x,n1,n2)
!       Print 2-dimensional complex data

!       .. Scalar Arguments ..
        Integer, Intent (In)           :: n1, n2, nout
!       .. Array Arguments ..
        Complex (Kind=nag_wp), Intent (In) :: x(n1,n2)
!       .. Local Scalars ..
        Integer                        :: i, j
!       .. Intrinsic Procedures ..
        Intrinsic                      :: aimag, real
!       .. Executable Statements ..
        Do i = 1, n1
          Write (nout,*)
          Write (nout,99999) 'Real ', (real(x(i,j)),j=1,n2)
          Write (nout,99999) 'Imag ', (aimag(x(i,j)),j=1,n2)
        End Do
        Return

99999   Format (1X,A,7F10.3,/,(6X,7F10.3))
      End Subroutine writx
    End Module c06pufe_mod

    Program c06pufe

!     C06PUF Example Main Program

!     .. Use Statements ..
      Use nag_library, Only: c06puf, nag_wp
      Use c06pufe_mod, Only: nin, nout, readx, writx
!     .. Implicit None Statement ..
      Implicit None
!     .. Local Scalars ..
      Integer                          :: ieof, ifail, m, n
!     .. Local Arrays ..
      Complex (Kind=nag_wp), Allocatable :: work(:), x(:)
!     .. Executable Statements ..
      Write (nout,*) 'C06PUF Example Program Results'
!     Skip heading in data file
      Read (nin,*)
loop: Do
        Read (nin,*,Iostat=ieof) m, n
        If (ieof<0) Then
          Exit loop
        End If
        Allocate (work(m*n+n+m+30),x(m*n))
        Call readx(nin,x,m,n)
        Write (nout,*)
        Write (nout,*) 'Original data values'
        Call writx(nout,x,m,n)

!       ifail: behaviour on error exit
!              =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
        ifail = 0
!       -- Compute transform
        Call c06puf('F',m,n,x,work,ifail)

        Write (nout,*)
        Write (nout,*) 'Components of discrete Fourier transform'
        Call writx(nout,x,m,n)

!       -- Compute inverse transform
        Call c06puf('B',m,n,x,work,ifail)

        Write (nout,*)
        Write (nout,*) 'Original sequence as restored by inverse transform'
        Call writx(nout,x,m,n)
        Deallocate (x,work)

      End Do loop

    End Program c06pufe


c06pvfe.f90

!   C06PVF Example Program Text
!   Mark 26 Release. NAG Copyright 2016.

    Module c06pvfe_mod

!     C06PVF Example Program Module:
!            Parameters and User-defined Routines

!     .. Use Statements ..
      Use nag_library, Only: nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Accessibility Statements ..
      Private
      Public                           :: readx, writx, writy
!     .. Parameters ..
      Integer, Parameter, Public       :: nin = 5, nout = 6
    Contains
      Subroutine readx(nin,x,n1,n2)
!       Read 2-dimensional real data

!       .. Scalar Arguments ..
        Integer, Intent (In)           :: n1, n2, nin
!       .. Array Arguments ..
        Real (Kind=nag_wp), Intent (Out) :: x(n1,n2)
!       .. Local Scalars ..
        Integer                        :: i, j
!       .. Executable Statements ..
        Do i = 1, n1
          Read (nin,*)(x(i,j),j=1,n2)
        End Do
        Return
      End Subroutine readx

      Subroutine writx(nout,x,n1,n2)
!       Print 2-dimensional real data

!       .. Scalar Arguments ..
        Integer, Intent (In)           :: n1, n2, nout
!       .. Array Arguments ..
        Real (Kind=nag_wp), Intent (In) :: x(n1,n2)
!       .. Local Scalars ..
        Integer                        :: i, j
!       .. Executable Statements ..
        Do i = 1, n1
          Write (nout,*)
          Write (nout,99999) 'Real ', (x(i,j),j=1,n2)
        End Do
        Return

99999   Format (1X,A,3F10.3)
      End Subroutine writx

      Subroutine writy(nout,y,n1,n2)
!       Print 2-dimensional complex data

!       .. Scalar Arguments ..
        Integer, Intent (In)           :: n1, n2, nout
!       .. Array Arguments ..
        Complex (Kind=nag_wp), Intent (In) :: y(n1,n2)
!       .. Local Scalars ..
        Integer                        :: i, j
!       .. Intrinsic Procedures ..
        Intrinsic                      :: aimag, real
!       .. Executable Statements ..
        Do i = 1, n1
          Write (nout,*)
          Write (nout,99999) 'Real ', (real(y(i,j)),j=1,n2)
          Write (nout,99999) 'Imag ', (aimag(y(i,j)),j=1,n2)
        End Do
        Return

99999   Format (1X,A,7F10.3,/,(6X,7F10.3))
      End Subroutine writy
    End Module c06pvfe_mod

    Program c06pvfe

!     C06PVF Example Main Program

!     .. Use Statements ..
      Use nag_library, Only: c06pvf, c06pwf, nag_wp
      Use c06pvfe_mod, Only: nin, nout, readx, writx, writy
!     .. Implicit None Statement ..
      Implicit None
!     .. Local Scalars ..
      Integer                          :: ieof, ifail, m, n
!     .. Local Arrays ..
      Complex (Kind=nag_wp), Allocatable :: y(:)
      Real (Kind=nag_wp), Allocatable  :: x(:)
!     .. Executable Statements ..
      Write (nout,*) 'C06PVF Example Program Results'
!     Skip heading in data file
      Read (nin,*)
loop: Do
        Read (nin,*,Iostat=ieof) m, n
        If (ieof<0) Then
          Exit loop
        End If
        Allocate (x(m*n),y((m/2+1)*n))

        Call readx(nin,x,m,n)
        Write (nout,*)
        Write (nout,*) 'Original data values'
        Call writx(nout,x,m,n)

!       ifail: behaviour on error exit
!              =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
        ifail = 0
!       -- Compute transform
        Call c06pvf(m,n,x,y,ifail)

        Write (nout,*)
        Write (nout,*) 'Components of discrete Fourier transform'
        Call writy(nout,y,m/2+1,n)

!       -- Compute inverse transform
        x = 0._nag_wp
        Call c06pwf(m,n,y,x,ifail)

        Write (nout,*)
        Write (nout,*) 'Original sequence as restored by inverse transform'
        Call writx(nout,x,m,n)
        Deallocate (x,y)

      End Do loop

    End Program c06pvfe


c06pxfe.f90

!   C06PXF Example Program Text
!   Mark 26 Release. NAG Copyright 2016.

    Module c06pxfe_mod

!     C06PXF Example Program Module:
!            Parameters and User-defined Routines

!     .. Use Statements ..
      Use nag_library, Only: nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Accessibility Statements ..
      Private
      Public                           :: readx, writx
!     .. Parameters ..
      Integer, Parameter, Public       :: nin = 5, nout = 6
    Contains
      Subroutine readx(nin,x,n1,n2,n3)
!       Read 3-dimensional complex data

!       .. Scalar Arguments ..
        Integer, Intent (In)           :: n1, n2, n3, nin
!       .. Array Arguments ..
        Complex (Kind=nag_wp), Intent (Out) :: x(n1,n2,n3)
!       .. Local Scalars ..
        Integer                        :: i, j, k
!       .. Executable Statements ..
        Do i = 1, n1
          Do j = 1, n2
            Read (nin,*)(x(i,j,k),k=1,n3)
          End Do
        End Do
        Return
      End Subroutine readx

      Subroutine writx(nout,x,n1,n2,n3)
!       Print 3-dimensional complex data

!       .. Scalar Arguments ..
        Integer, Intent (In)           :: n1, n2, n3, nout
!       .. Array Arguments ..
        Complex (Kind=nag_wp), Intent (In) :: x(n1,n2,n3)
!       .. Local Scalars ..
        Integer                        :: i, j, k
!       .. Intrinsic Procedures ..
        Intrinsic                      :: aimag, real
!       .. Executable Statements ..
        Do i = 1, n1
          Write (nout,*)
          Write (nout,99998) 'z(i,j,k) for i =', i
          Do j = 1, n2
            Write (nout,*)
            Write (nout,99999) 'Real ', (real(x(i,j,k)),k=1,n3)
            Write (nout,99999) 'Imag ', (aimag(x(i,j,k)),k=1,n3)
          End Do
        End Do
        Return

99999   Format (1X,A,7F10.3,/,(6X,7F10.3))
99998   Format (1X,A,I6)
      End Subroutine writx
    End Module c06pxfe_mod

    Program c06pxfe

!     C06PXF Example Main Program

!     .. Use Statements ..
      Use nag_library, Only: c06pxf, nag_wp
      Use c06pxfe_mod, Only: nin, nout, readx, writx
!     .. Implicit None Statement ..
      Implicit None
!     .. Local Scalars ..
      Integer                          :: ieof, ifail, n, n1, n2, n3
!     .. Local Arrays ..
      Complex (Kind=nag_wp), Allocatable :: work(:), x(:)
!     .. Executable Statements ..
      Write (nout,*) 'C06PXF Example Program Results'
!     Skip heading in data file
      Read (nin,*)
loop: Do
        Read (nin,*,Iostat=ieof) n1, n2, n3
        If (ieof<0) Then
          Exit loop
        End If
        n = n1*n2*n3
        Allocate (x(n),work(n+n1+n2+n3+45))
        Call readx(nin,x,n1,n2,n3)
        Write (nout,*)
        Write (nout,*) 'Original data values'
        Call writx(nout,x,n1,n2,n3)

!       ifail: behaviour on error exit
!              =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
        ifail = 0
!       -- Compute transform
        Call c06pxf('F',n1,n2,n3,x,work,ifail)

        Write (nout,*)
        Write (nout,*) 'Components of discrete Fourier transform'
        Call writx(nout,x,n1,n2,n3)

!       -- Compute inverse transform
        Call c06pxf('B',n1,n2,n3,x,work,ifail)

        Write (nout,*)
        Write (nout,*) 'Original sequence as restored by inverse transform'
        Call writx(nout,x,n1,n2,n3)
        Deallocate (x,work)
      End Do loop

    End Program c06pxfe


c06pyfe.f90

!   C06PYF Example Program Text
!   Mark 26 Release. NAG Copyright 2016.

    Module c06pyfe_mod

!     C06PYF Example Program Module:
!            Parameters and User-defined Routines

!     .. Use Statements ..
      Use nag_library, Only: nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Accessibility Statements ..
      Private
      Public                           :: readx, writx, writy
!     .. Parameters ..
      Integer, Parameter, Public       :: nin = 5, nout = 6
    Contains
      Subroutine readx(nin,x,n1,n2,n3)
!       Read 3-dimensional real data

!       .. Scalar Arguments ..
        Integer, Intent (In)           :: n1, n2, n3, nin
!       .. Array Arguments ..
        Real (Kind=nag_wp), Intent (Out) :: x(n1,n2,n3)
!       .. Local Scalars ..
        Integer                        :: i, j, k
!       .. Executable Statements ..
        Do i = 1, n1
          Do j = 1, n2
            Read (nin,*)(x(i,j,k),k=1,n3)
          End Do
        End Do
        Return
      End Subroutine readx

      Subroutine writx(nout,x,n1,n2,n3)
!       Print 3-dimensional real data

!       .. Scalar Arguments ..
        Integer, Intent (In)           :: n1, n2, n3, nout
!       .. Array Arguments ..
        Real (Kind=nag_wp), Intent (In) :: x(n1,n2,n3)
!       .. Local Scalars ..
        Integer                        :: i, j, k
!       .. Executable Statements ..
        Do i = 1, n1
          Write (nout,*)
          Write (nout,99998) 'x(i,j,k) for i =', i
          Do j = 1, n2
            Write (nout,*)
            Write (nout,99999) 'Real ', (x(i,j,k),k=1,n3)
          End Do
        End Do
        Return

99999   Format (1X,A,4F10.3)
99998   Format (1X,A,I6)
      End Subroutine writx

      Subroutine writy(nout,y,n1,n2,n3)
!       Print 3-dimensional complex data

!       .. Scalar Arguments ..
        Integer, Intent (In)           :: n1, n2, n3, nout
!       .. Array Arguments ..
        Complex (Kind=nag_wp), Intent (In) :: y(n1,n2,n3)
!       .. Local Scalars ..
        Integer                        :: i, j, k
!       .. Intrinsic Procedures ..
        Intrinsic                      :: aimag, real
!       .. Executable Statements ..
        Do i = 1, n1
          Write (nout,*)
          Write (nout,99998) 'y(i,j,k) for i =', i
          Do j = 1, n2
            Write (nout,*)
            Write (nout,99999) 'Real ', (real(y(i,j,k)),k=1,n3)
            Write (nout,99999) 'Imag ', (aimag(y(i,j,k)),k=1,n3)
          End Do
        End Do
        Return

99999   Format (1X,A,4F10.3)
99998   Format (1X,A,I6)
      End Subroutine writy
    End Module c06pyfe_mod

    Program c06pyfe

!     C06PYF Example Main Program

!     .. Use Statements ..
      Use nag_library, Only: c06pyf, c06pzf, nag_wp
      Use c06pyfe_mod, Only: nin, nout, readx, writx, writy
!     .. Implicit None Statement ..
      Implicit None
!     .. Local Scalars ..
      Integer                          :: ieof, ifail, n1, n2, n3
!     .. Local Arrays ..
      Complex (Kind=nag_wp), Allocatable :: y(:)
      Real (Kind=nag_wp), Allocatable  :: x(:)
!     .. Executable Statements ..
      Write (nout,*) 'C06PYF Example Program Results'
!     Skip heading in data file
      Read (nin,*)
loop: Do
        Read (nin,*,Iostat=ieof) n1, n2, n3
        If (ieof<0) Then
          Exit loop
        End If

        Allocate (x(n1*n2*n3),y((n1/2+1)*n2*n3))

        Call readx(nin,x,n1,n2,n3)
        Write (nout,*)
        Write (nout,*) 'Original data values'
        Call writx(nout,x,n1,n2,n3)

!       ifail: behaviour on error exit
!              =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
        ifail = 0
!       -- Compute transform
        Call c06pyf(n1,n2,n3,x,y,ifail)

        Write (nout,*)
        Write (nout,*) 'Components of discrete Fourier transform'
        Call writy(nout,y,n1/2+1,n2,n3)

!       -- Compute inverse transform
        x = 0._nag_wp
        Call c06pzf(n1,n2,n3,y,x,ifail)

        Write (nout,*)
        Write (nout,*) 'Original sequence as restored by inverse transform'
        Call writx(nout,x,n1,n2,n3)
        Deallocate (x,y)

      End Do loop

    End Program c06pyfe


c06rafe.f90

    Program c06rafe

!     C06RAF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: c06raf, nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Integer                          :: i, ieof, ifail, j, m, n
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: work(:), x(:)
!     .. Executable Statements ..
      Write (nout,*) 'C06RAF Example Program Results'
!     Skip heading in data file
      Read (nin,*)
loop: Do
        Read (nin,*,Iostat=ieof) m, n
        If (ieof<0) Then
          Exit loop
        End If

        Allocate (x(m*(n+2)),work(m*n+2*n+2*m+15))
        Do j = 1, m
          Read (nin,*)(x((i-1)*m+j),i=1,n-1)
        End Do
        Write (nout,*)
        Write (nout,*) 'Original data values'
        Write (nout,*)
        Do j = 1, m
          Write (nout,99999)(x((i-1)*m+j),i=1,n-1)
        End Do

!       ifail: behaviour on error exit
!              =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
        ifail = 0
!       -- Compute transform
        Call c06raf(m,n,x,work,ifail)

        Write (nout,*)
        Write (nout,*) 'Discrete Fourier sine transforms'
        Write (nout,*)
        Do j = 1, m
          Write (nout,99999)(x((i-1)*m+j),i=1,n-1)
        End Do

!       -- Compute inverse transform
        Call c06raf(m,n,x,work,ifail)

        Write (nout,*)
        Write (nout,*) 'Original data as restored by inverse transform'
        Write (nout,*)
        Do j = 1, m
          Write (nout,99999)(x((i-1)*m+j),i=1,n-1)
        End Do
        Deallocate (x,work)
      End Do loop

99999 Format (6X,6F10.4)
    End Program c06rafe


c06rbfe.f90

    Program c06rbfe

!     C06RBF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: c06rbf, nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Integer                          :: i, ieof, ifail, j, m, n
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: work(:), x(:)
!     .. Executable Statements ..
      Write (nout,*) 'C06RBF Example Program Results'
!     Skip heading in data file
      Read (nin,*)
loop: Do
        Read (nin,*,Iostat=ieof) m, n
        If (ieof<0) Then
          Exit loop
        End If

        Allocate (x(m*(n+3)),work(m*n+2*n+2*m+15))
        Do j = 1, m
          Read (nin,*)(x(i*m+j),i=0,n)
        End Do
        Write (nout,*)
        Write (nout,*) 'Original data values'
        Write (nout,*)
        Do j = 1, m
          Write (nout,99999)(x(i*m+j),i=0,n)
        End Do

!       ifail: behaviour on error exit
!              =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
        ifail = 0
!       -- Compute transform
        Call c06rbf(m,n,x,work,ifail)

        Write (nout,*)
        Write (nout,*) 'Discrete Fourier cosine transforms'
        Write (nout,*)
        Do j = 1, m
          Write (nout,99999)(x(i*m+j),i=0,n)
        End Do

!       -- Compute inverse transform
        Call c06rbf(m,n,x,work,ifail)

        Write (nout,*)
        Write (nout,*) 'Original data as restored by inverse transform'
        Write (nout,*)
        Do j = 1, m
          Write (nout,99999)(x(i*m+j),i=0,n)
        End Do
        Deallocate (x,work)
      End Do loop

99999 Format (6X,7F10.4)
    End Program c06rbfe


c06rcfe.f90

    Program c06rcfe

!     C06RCF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: c06rcf, nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Integer                          :: i, ieof, ifail, j, m, n
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: work(:), x(:)
!     .. Executable Statements ..
      Write (nout,*) 'C06RCF Example Program Results'
!     Skip heading in data file
      Read (nin,*)
loop: Do
        Read (nin,*,Iostat=ieof) m, n
        If (ieof<0) Then
          Exit loop
        End If

        Allocate (x(m*(n+2)),work(m*n+2*n+2*m+15))
        Do j = 1, m
          Read (nin,*)(x(i*m+j),i=0,n-1)
        End Do
        Write (nout,*)
        Write (nout,*) 'Original data values'
        Write (nout,*)
        Do j = 1, m
          Write (nout,99999)(x(i*m+j),i=0,n-1)
        End Do

!       ifail: behaviour on error exit
!              =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
        ifail = 0
!       -- Compute transform
        Call c06rcf('Forward',m,n,x,work,ifail)

        Write (nout,*)
        Write (nout,*) 'Discrete quarter-wave Fourier sine transforms'
        Write (nout,*)
        Do j = 1, m
          Write (nout,99999)(x(i*m+j),i=0,n-1)
        End Do

!       -- Compute inverse transform
        Call c06rcf('Backward',m,n,x,work,ifail)

        Write (nout,*)
        Write (nout,*) 'Original data as restored by inverse transform'
        Write (nout,*)
        Do j = 1, m
          Write (nout,99999)(x(i*m+j),i=0,n-1)
        End Do
        Deallocate (x,work)
      End Do loop

99999 Format (6X,7F10.4)
    End Program c06rcfe


c06rdfe.f90

    Program c06rdfe

!     C06RDF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: c06rdf, nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Integer                          :: i, ieof, ifail, j, m, n
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: work(:), x(:)
!     .. Executable Statements ..
      Write (nout,*) 'C06RDF Example Program Results'
!     Skip heading in data file
      Read (nin,*)
loop: Do
        Read (nin,*,Iostat=ieof) m, n
        If (ieof<0) Then
          Exit loop
        End If

        Allocate (x(m*(n+2)),work(m*n+2*n+2*m+15))
        Do j = 1, m
          Read (nin,*)(x(i*m+j),i=0,n-1)
        End Do
        Write (nout,*)
        Write (nout,*) 'Original data values'
        Write (nout,*)
        Do j = 1, m
          Write (nout,99999)(x(i*m+j),i=0,n-1)
        End Do

!       ifail: behaviour on error exit
!              =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
        ifail = 0
!       -- Compute transform
        Call c06rdf('Forward',m,n,x,work,ifail)

        Write (nout,*)
        Write (nout,*) 'Discrete quarter-wave Fourier cosine transforms'
        Write (nout,*)
        Do j = 1, m
          Write (nout,99999)(x(i*m+j),i=0,n-1)
        End Do

!       -- Compute inverse transform
        Call c06rdf('Backward',m,n,x,work,ifail)

        Write (nout,*)
        Write (nout,*) 'Original data as restored by inverse transform'
        Write (nout,*)
        Do j = 1, m
          Write (nout,99999)(x(i*m+j),i=0,n-1)
        End Do
        Deallocate (x,work)
      End Do loop

99999 Format (6X,7F10.4)
    End Program c06rdfe


c06refe.f90

    Program c06refe

!     C06REF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: c06ref, nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Integer                          :: ieof, ifail, j, m, n, n1
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: x(:,:)
!     .. Executable Statements ..
      Write (nout,*) 'C06REF Example Program Results'
!     Skip heading in data file
      Read (nin,*)
loop: Do
        Read (nin,*,Iostat=ieof) m, n1
        n = n1 + 1
        If (ieof<0) Then
          Exit loop
        End If

        Allocate (x(n1,m))
        Read (nin,*)(x(1:n1,j),j=1,m)
        Write (nout,*)
        Write (nout,*) 'Original data values'
        Write (nout,*)
        Write (nout,99999)(x(1:n1,j),j=1,m)

!       ifail: behaviour on error exit
!              =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
        ifail = 0
!       -- Compute transform
        Call c06ref(m,n,x,ifail)

        Write (nout,*)
        Write (nout,*) 'Discrete Fourier sine transforms'
        Write (nout,*)
        Write (nout,99999)(x(1:n1,j),j=1,m)

!       -- Compute inverse transform
        Call c06ref(m,n,x,ifail)

        Write (nout,*)
        Write (nout,*) 'Original data as restored by inverse transform'
        Write (nout,*)
        Write (nout,99999)(x(1:n1,j),j=1,m)
        Deallocate (x)
      End Do loop

99999 Format (1X,5F10.4)
    End Program c06refe


c06rffe.f90

    Program c06rffe

!     C06RFF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: c06rff, nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Integer                          :: ieof, ifail, j, m, n, n1
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: x(:,:)
!     .. Executable Statements ..
      Write (nout,*) 'C06RFF Example Program Results'
!     Skip heading in data file
      Read (nin,*)
loop: Do
        Read (nin,*,Iostat=ieof) m, n1
        n = n1 - 1
        If (ieof<0) Then
          Exit loop
        End If

        Allocate (x(n1,m))
        Read (nin,*)(x(1:n1,j),j=1,m)
        Write (nout,*)
        Write (nout,*) 'Original data values'
        Write (nout,*)
        Write (nout,99999)(x(1:n1,j),j=1,m)

!       ifail: behaviour on error exit
!              =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
        ifail = 0
!       -- Compute transform
        Call c06rff(m,n,x,ifail)

        Write (nout,*)
        Write (nout,*) 'Discrete Fourier cosine transforms'
        Write (nout,*)
        Write (nout,99999)(x(1:n1,j),j=1,m)

!       -- Compute inverse transform
        Call c06rff(m,n,x,ifail)

        Write (nout,*)
        Write (nout,*) 'Original data as restored by inverse transform'
        Write (nout,*)
        Write (nout,99999)(x(1:n1,j),j=1,m)
        Deallocate (x)
      End Do loop

99999 Format (1X,7F10.4)
    End Program c06rffe


c06rgfe.f90

    Program c06rgfe

!     C06RGF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: c06rgf, nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Integer                          :: idir, ieof, ifail, j, m, n
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: x(:,:)
!     .. Executable Statements ..
      Write (nout,*) 'C06RGF Example Program Results'
!     Skip heading in data file
      Read (nin,*)
loop: Do
        Read (nin,*,Iostat=ieof) m, n
        If (ieof<0) Then
          Exit loop
        End If

        Allocate (x(n,m))
        Read (nin,*)(x(1:n,j),j=1,m)
        Write (nout,*)
        Write (nout,*) 'Original data values'
        Write (nout,*)
        Write (nout,99999)(x(1:n,j),j=1,m)

!       ifail: behaviour on error exit
!              =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
        ifail = 0
!       -- Compute transform
        idir = 1
        Call c06rgf(idir,m,n,x,ifail)

        Write (nout,*)
        Write (nout,*) 'Discrete quarter-wave Fourier sine transforms'
        Write (nout,*)
        Write (nout,99999)(x(1:n,j),j=1,m)

!       -- Compute inverse transform
        idir = -1
        Call c06rgf(idir,m,n,x,ifail)

        Write (nout,*)
        Write (nout,*) 'Original data as restored by inverse transform'
        Write (nout,*)
        Write (nout,99999)(x(1:n,j),j=1,m)
        Deallocate (x)
      End Do loop

99999 Format (1X,6F10.4)
    End Program c06rgfe


c06rhfe.f90

    Program c06rhfe

!     C06RHF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: c06rhf, nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Integer                          :: idir, ieof, ifail, j, m, n
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: x(:,:)
!     .. Executable Statements ..
      Write (nout,*) 'C06RHF Example Program Results'
!     Skip heading in data file
      Read (nin,*)
loop: Do
        Read (nin,*,Iostat=ieof) m, n
        If (ieof<0) Then
          Exit loop
        End If

        Allocate (x(0:n-1,m))
        Read (nin,*)(x(0:n-1,j),j=1,m)
        Write (nout,*)
        Write (nout,*) 'Original data values'
        Write (nout,*)
        Write (nout,99999)(x(0:n-1,j),j=1,m)

!       ifail: behaviour on error exit
!              =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
        ifail = 0
!       -- Compute transform
        idir = 1
        Call c06rhf(idir,m,n,x,ifail)

        Write (nout,*)
        Write (nout,*) 'Discrete quarter-wave Fourier cosine transforms'
        Write (nout,*)
        Write (nout,99999)(x(0:n-1,j),j=1,m)

!       -- Compute inverse transform
        idir = -1
        Call c06rhf(idir,m,n,x,ifail)

        Write (nout,*)
        Write (nout,*) 'Original data as restored by inverse transform'
        Write (nout,*)
        Write (nout,99999)(x(0:n-1,j),j=1,m)
        Deallocate (x)
      End Do loop

99999 Format (1X,6F10.4)
    End Program c06rhfe


c09aafe.f90

    Program c09aafe

!     C09AAF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: c09aaf, c09ccf, c09cdf, nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Integer                          :: ifail, lenc, n, nf, nnz, nwc,        &
                                          nwlmax, ny
      Character (10)                   :: mode, wavnam, wtrans
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: c(:), x(:), y(:)
      Integer, Allocatable             :: dwtlev(:)
      Integer                          :: icomm(100)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: sum
!     .. Executable Statements ..
      Write (nout,*) 'C09AAF Example Program Results'
      Write (nout,*)
!     Skip heading in data file
      Read (nin,*)
!     Read problem parameters
      Read (nin,*) n
      Read (nin,*) wavnam, mode
      Allocate (x(n),y(n))

      Write (nout,99999) wavnam, mode, n

!     Read data array and write it out

      Read (nin,*) x(1:n)

      Write (nout,*) ' Input Data           X :'
      Write (nout,99998) x(1:n)

!     Query wavelet filter dimensions
!     For Multi-Resolution Analysis, decomposition, wtrans = 'M'
      wtrans = 'Multilevel'

!     ifail: behaviour on error exit
!             =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
      ifail = 0
      Call c09aaf(wavnam,wtrans,mode,n,nwlmax,nf,nwc,icomm,ifail)

      lenc = nwc
      Allocate (c(lenc),dwtlev(nwlmax+1))

!     Perform Discrete Wavelet transform
      ifail = 0
      Call c09ccf(n,x,lenc,c,nwlmax,dwtlev,icomm,ifail)

      Write (nout,*)
      Write (nout,99997) nf
      Write (nout,99996) nwlmax
      Write (nout,99995)
      Write (nout,99994) dwtlev(1:nwlmax+1)
      Write (nout,99993) nwc
      nnz = sum(dwtlev(1:nwlmax+1))
      Write (nout,*)
      Write (nout,99992)
      Write (nout,99998) c(1:nnz)

!     Reconstruct original data
      ny = n

      ifail = 0
      Call c09cdf(nwlmax,lenc,c,ny,y,icomm,ifail)

      Write (nout,*)
      Write (nout,99991)
      Write (nout,99998) y(1:ny)

99999 Format (1X,' Parameters read from file :: ',/,'     Wavelet : ',A10,     &
        ' End mode : ',A10,' N = ',I10)
99998 Format (8(F8.3,1X),:)
99997 Format (1X,' Length of wavelet filter :             ',I10)
99996 Format (1X,' Number of Levels :                     ',I10)
99995 Format (1X,' Number of coefficients in each level : ')
99994 Format (16X,8(I8,1X),:)
99993 Format (1X,' Total number of wavelet coefficients : ',I10)
99992 Format (1X,' Wavelet coefficients C : ')
99991 Format (1X,' Reconstruction       Y : ')
    End Program c09aafe


c09abfe.f90

    Program c09abfe

!     C09ABF Example Program Text
!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: c09abf, c09ecf, c09edf, c09eyf, nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Integer                          :: i, ifail, lda, ldb, lenc, m, n, nf,  &
                                          nwcm, nwcn, nwct, nwl, nwlmax,       &
                                          want_coeffs, want_level
      Character (10)                   :: mode, wavnam, wtrans
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: a(:,:), b(:,:), c(:), d(:,:)
      Integer, Allocatable             :: dwtlevm(:), dwtlevn(:)
      Integer                          :: icomm(180)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: sum
!     .. Executable Statements ..
      Continue
      Write (nout,*) 'C09ABF Example Program Results'
      Write (nout,*)
!     Skip heading in data file
      Read (nin,*)
!     Read problem parameters
      Read (nin,*) m, n
      lda = m
      ldb = m
      Read (nin,*) wavnam, mode
      Allocate (a(lda,n),b(ldb,n))

      Write (nout,99999) wavnam, mode, m, n

!     Read data array and write it out
      Do i = 1, m
        Read (nin,*) a(i,1:n)
      End Do

      Write (nout,*) ' Input Data           A :'
      Do i = 1, m
        Write (nout,99998) a(i,1:n)
      End Do

!     Query wavelet filter dimensions
!     For Multi-Resolution Analysis, decomposition, wtrans = 'M'
      wtrans = 'Multilevel'

!     ifail: behaviour on error exit
!             =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
      ifail = 0
      Call c09abf(wavnam,wtrans,mode,m,n,nwlmax,nf,nwct,nwcn,icomm,ifail)

      lenc = nwct
      Allocate (c(lenc),dwtlevm(nwlmax),dwtlevn(nwlmax))

!     Calculate one less than the max possible number of levels
      nwl = nwlmax - 1

!     Perform Discrete Wavelet transform
      ifail = 0
      Call c09ecf(m,n,a,lda,lenc,c,nwl,dwtlevm,dwtlevn,icomm,ifail)

!     c09abf returns nwct based on max levels, so recalculate.
      nwct = sum(3*dwtlevm(1:nwl)*dwtlevn(1:nwl))
      nwct = nwct + dwtlevm(1)*dwtlevn(1)

!     Print the details of the transform.
      Write (nout,*)
      Write (nout,99997) nf
      Write (nout,99996) nwl
      Write (nout,99995)
      Write (nout,99994) dwtlevm(1:nwl)
      Write (nout,99993)
      Write (nout,99994) dwtlevn(1:nwl)
      Write (nout,99992) nwct
      Write (nout,*)
      Write (nout,99991)
      Write (nout,99998) c(1:nwct)

!     Now select a nominated matrix of coefficients at a nominated level.
!     Remember that level 0 is input data, 1 first coeffs and so on up to nwl,
!     which is the deepest level and contains approx. coefficients.
      want_level = nwl - 1
!     Print only vertical detail coeffs at selected level.
      want_coeffs = 1
      nwcm = dwtlevm(nwl-want_level+1)
      nwcn = dwtlevn(nwl-want_level+1)
      Allocate (d(nwcm,nwcn))

!     Extract the selected set of coefficients.
      Call c09eyf(want_level,want_coeffs,lenc,c,d,nwcm,icomm,ifail)

!     Print out the selected coefficients
      Write (nout,*)
      Write (nout,99989) want_coeffs, want_level
      Do i = 1, nwcm
        Write (nout,99998) d(i,1:nwcn)
      End Do

!     Reconstruct original data
      ifail = 0
      Call c09edf(nwl,lenc,c,m,n,b,ldb,icomm,ifail)

      Write (nout,*)
      Write (nout,99990)
      Do i = 1, m
        Write (nout,99998) b(i,1:n)
      End Do

99999 Format (1X,' Parameters read from file :: ',/,'     Wavelet : ',A10,     &
        ' End mode : ',A10,' M = ',I10,' N = ',I10)
99998 Format (8(F8.4,1X),:)
99997 Format (1X,' Length of wavelet filter :             ',I10)
99996 Format (1X,' Number of Levels :                     ',I10)
99995 Format (1X,                                                              &
        ' Number of coefficients in first dimension for each level : ')
99994 Format (16X,8(I8,1X),:)
99993 Format (1X,                                                              &
        ' Number of coefficients in second dimension for each level : ')
99992 Format (1X,' Total number of wavelet coefficients : ',I10)
99991 Format (1X,' All Wavelet coefficients C : ')
99990 Format (1X,' Reconstruction       B : ')
99989 Format (1X,' Type ',I1,' coefficients at selected wavelet level, ',I4,   &
        ': ')
    End Program c09abfe


c09acfe.f90

    Program c09acfe

!     C09ACF Example Program Text
!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: c09acf, c09fcf, c09fdf, c09fyf, nag_wp, x02ajf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: eps, esq, frob
      Integer                          :: fr, i, ifail, j, k, lda, ldb, ldd,   &
                                          lenc, m, n, nf, nwcfr, nwcm, nwcn,   &
                                          nwct, nwl, nwlmax, sda, sdb, sdd,    &
                                          want_coeffs, want_level
      Character (10)                   :: mode, wavnam, wtrans
      Character (33)                   :: title
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: a(:,:,:), b(:,:,:), c(:), d(:,:,:),  &
                                          e(:,:,:)
      Integer, Allocatable             :: dwtlvfr(:), dwtlvm(:), dwtlvn(:)
      Integer                          :: icomm(260)
      Character (3)                    :: cpass(0:7)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: max, real, sqrt, sum
!     .. Executable Statements ..
      Continue
      Write (nout,*) 'C09ACF Example Program Results'
      Write (nout,*)
!     Skip heading in data file
      Read (nin,*)
!     Read problem parameters
      Read (nin,*) m, n, fr
      Read (nin,*) wavnam, mode
      lda = m
      sda = n
      ldb = m
      sdb = n
      Allocate (a(lda,sda,fr),b(ldb,sdb,fr),e(ldb,sdb,fr))

      Write (nout,99999) wavnam, mode, m, n, fr

!     Read data array and write it out

      Do j = 1, fr
        Do i = 1, m
          Read (nin,*) a(i,1:n,j)
        End Do
        If (j<fr) Then
          Read (nin,*)
        End If
      End Do

      Write (nout,*) ' Input Data     A :'
      Do j = 1, fr
        Do i = 1, m
          Write (nout,99998) a(i,1:n,j)
        End Do
        Write (nout,*)
      End Do

!     Query wavelet filter dimensions
!     For Multi-Resolution Analysis, decomposition, wtrans = 'M'
      wtrans = 'Multilevel'
      ifail = 0
      Call c09acf(wavnam,wtrans,mode,m,n,fr,nwlmax,nf,nwct,nwcn,nwcfr,icomm,   &
        ifail)

!     Transform one less than the max possible number of levels.
      nwl = nwlmax - 1

      lenc = nwct
      Allocate (c(lenc),dwtlvm(nwl),dwtlvn(nwl),dwtlvfr(nwl))

!     Perform Discrete Wavelet transform
      ifail = 0
      Call c09fcf(m,n,fr,a,lda,sda,lenc,c,nwl,dwtlvm,dwtlvn,dwtlvfr,icomm,     &
        ifail)

!     c09acf returns nwct based on max levels, so recalculate.
      nwct = sum(7*dwtlvm(1:nwl)*dwtlvn(1:nwl)*dwtlvfr(1:nwl))
      nwct = nwct + dwtlvm(1)*dwtlvn(1)*dwtlvfr(1)

      Write (nout,99997) nwl
      Write (nout,99988) nf
      Write (nout,99987) nwct
      Write (nout,99996)
      Write (nout,99995) dwtlvm(1:nwl)
      Write (nout,99994)
      Write (nout,99995) dwtlvn(1:nwl)
      Write (nout,99993)
      Write (nout,99995) dwtlvfr(1:nwl)

!     Select the deepest level.
      want_level = nwl
!     Select the approximation coefficients.
      want_coeffs = 0

      nwcm = dwtlvm(nwl-want_level+1)
      nwcn = dwtlvn(nwl-want_level+1)
      nwcfr = dwtlvfr(nwl-want_level+1)

!     Allocate space to store the coefficients
      ldd = nwcm
      sdd = nwcn
      Allocate (d(ldd,sdd,nwcfr))

      Write (nout,99986) want_level, nwcm, nwcn, nwcfr

      cpass(0:7) = (/'LLL','LLH','LHL','LHH','HLL','HLH','HHL','HHH'/)
      If (want_coeffs==0) Then
        title = 'Approximation coefficients (LLL) '
      Else
        title = 'Detail coefficients (' // cpass(want_coeffs) // ')  '
      End If

!     Extract the required coefficients
      Call c09fyf(want_level,want_coeffs,lenc,c,d,ldd,sdd,icomm,ifail)

!     Print out the selected set of coefficients
      Write (nout,99985) title
      Write (nout,99989) want_level, want_coeffs
      Do k = 1, nwcfr
        Write (nout,99990) k
        Do i = 1, nwcm
          Write (nout,99991) d(i,1:nwcn,k)
        End Do
      End Do

      Deallocate (d)

!     Reconstruct original data
      ifail = 0
      Call c09fdf(nwl,lenc,c,m,n,fr,b,ldb,sdb,icomm,ifail)

!     Check reconstruction matches original
      eps = 10.0_nag_wp*real(m,kind=nag_wp)*real(n,kind=nag_wp)*               &
        real(fr,kind=nag_wp)*x02ajf()

      e(1:m,1:n,1:fr) = b(1:m,1:n,1:fr) - a(1:m,1:n,1:fr)
      frob = 0.0_nag_wp
      Do k = 1, fr
        esq = 0.0_nag_wp
        Do j = 1, n
          Do i = 1, m
            esq = esq + e(i,j,k)**2
          End Do
        End Do
        frob = max(frob,sqrt(esq))
      End Do

      If (frob>eps) Then
        Write (nout,99992)
      Else
        Write (nout,99992)
      End If

99999 Format (1X,' MLDWT :: Wavelet  : ',A,/,1X,'          End mode : ',A,/,   &
        1X,'          M        : ',I4,/,1X,'          N        : ',I4,/,1X,    &
        '          FR       : ',I4,/)
99998 Format (8(F8.4,1X),:)
99997 Format (/,1X,' Number of Levels :         ',I10)
99996 Format (1X,' Number of coefficients in 1st dimension for each level :')
99995 Format (8(I8,1X),:)
99994 Format (1X,' Number of coefficients in 2nd dimension for each level :')
99993 Format (1X,' Number of coefficients in 3rd dimension for each level :')
99992 Format (/,1X,' Success: the reconstruction matches the original.')
99991 Format (1X,8(F8.4,1X),:)
99990 Format (1X,' Frame ',I2,' : ')
99989 Format (1X,' Level ',I2,', Coefficients ',I2,' : ')
99988 Format (1X,' Length of wavelet filter : ',I10)
99987 Format (1X,' Total number of wavelet coefficients : ',I10)
99986 Format (/,1X,70('-'),/,1X,'Level : ',I10,'; output is ',I10,' by ',I10,  &
        ' by ',I10,/,1X,70('-'))
99985 Format (/,1X,A)
    End Program c09acfe


c09bafe.f90

    Program c09bafe

!     C09BAF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: c09baf, nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Integer                          :: ifail, j, n, nscal, wparam
      Character (10)                   :: wavnam
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: c(:,:), x(:)
      Integer, Allocatable             :: scales(:)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: trim
!     .. Executable Statements ..
      Write (nout,*) 'C09BAF Example Program Results'
      Write (nout,*)
!     Skip heading in data file
      Read (nin,*)
!     Read problem parameters
      Read (nin,*) n, nscal
      Allocate (c(nscal,n),scales(nscal),x(n))
      Read (nin,*) wavnam, wparam
      Write (nout,99999) trim(wavnam), wparam, n, nscal

!     Read data array and write it out

      Read (nin,*) scales(1:nscal)
      Read (nin,*) x(1:n)

      Write (nout,99998) scales(1:nscal)
      Write (nout,99997) x(1:n)

!     ifail: behaviour on error exit
!             =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
      ifail = 0
      Call c09baf(wavnam,wparam,n,x,nscal,scales,c,ifail)

      Write (nout,99996) nscal
      Write (nout,99995) scales(1:nscal)
      Do j = 1, n
        Write (nout,99994) c(1:nscal,j)
      End Do

99999 Format (2X,'Parameters read from file ::',/,4X,'Wavelet : ',A,           &
        ',  wparam : ',I6,/,10X,'n : ',I6,',   nscal : ',I6)
99998 Format (/,2X,'Input Data ::',/,4X,' Scales :',5(I8,1X),:)
99997 Format (5X,'     x :',5(F8.3,1X),(/,13X,5(F8.3,1X)),:)
99996 Format (/,2X,'Number of Scales :      ',I10)
99995 Format (2X,'Wavelet coefficients C ::',/,4X,'Scale :',I7,3I13)
99994 Format (10X,4(1P,E11.4,2X),:)
    End Program c09bafe


c09cafe.f90

    Program c09cafe

!     C09CAF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: c09aaf, c09caf, c09cbf, nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Integer                          :: ifail, n, nf, nwc, nwl, ny
      Character (12)                   :: mode, wavnam, wtrans
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: ca(:), cd(:), x(:), y(:)
      Integer                          :: icomm(100)
!     .. Executable Statements ..
      Write (nout,*) 'C09CAF Example Program Results'
!     Skip heading in data file
      Read (nin,*)
!     Read problem parameters.
      Read (nin,*) n
      Read (nin,*) wavnam, mode
      Allocate (x(n),y(n))

      Write (nout,99999) wavnam, mode
!     Read array
      Read (nin,*) x(1:n)
      Write (nout,*) 'Input Data      X :'
      Write (nout,99997) x(1:n)
!     Query wavelet filter dimensions
      wtrans = 'Single Level'

!     ifail: behaviour on error exit
!            =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
      ifail = 0
      Call c09aaf(wavnam,wtrans,mode,n,nwl,nf,nwc,icomm,ifail)

      Allocate (ca(nwc),cd(nwc))

      ifail = 0
      Call c09caf(n,x,nwc,ca,cd,icomm,ifail)

      Write (nout,99998)
      Write (nout,99997) ca(1:nwc)
      Write (nout,99996)
      Write (nout,99997) cd(1:nwc)

      ny = n

      ifail = 0
      Call c09cbf(nwc,ca,cd,ny,y,icomm,ifail)

      Write (nout,99995)
      Write (nout,99997) y(1:ny)

99999 Format (1X,'DWT :: Wavelet: ',A,', End mode: ',A)
99998 Format (1X,'Approximation coefficients CA : ')
99997 Format (1X,8(F8.4,1X),:)
99996 Format (1X,'Detail coefficients        CD : ')
99995 Format (1X,'Reconstruction              Y : ')
    End Program c09cafe


c09ccfe.f90

    Program c09ccfe

!     C09CCF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: c09aaf, c09ccf, c09cdf, nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Integer                          :: ifail, lenc, n, nf, nnz, nwc, nwl,   &
                                          nwlinv, nwlmax
      Character (10)                   :: mode, wavnam, wtrans
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: c(:), x(:), y(:)
      Integer, Allocatable             :: dwtlev(:)
      Integer                          :: icomm(100)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: sum
!     .. Executable Statements ..
      Write (nout,*) 'C09CCF Example Program Results'
!     Skip heading in data file
      Read (nin,*)
!     Read problem parameters
      Read (nin,*) n
      Read (nin,*) wavnam, mode
      Allocate (x(n),y(n))

      Write (nout,99999) wavnam, mode, n

!     Read data array and write it out

      Read (nin,*) x(1:n)

      Write (nout,*) ' Input Data      X :'
      Write (nout,99998) x(1:n)

!     Query wavelet filter dimensions
!     For Multi-Resolution Analysis, decomposition, wtrans = 'M'
      wtrans = 'Multilevel'

!     ifail: behaviour on error exit
!            =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
      ifail = 0
      Call c09aaf(wavnam,wtrans,mode,n,nwlmax,nf,nwc,icomm,ifail)

      lenc = nwc
      Allocate (c(lenc),dwtlev(nwlmax+1))

      nwl = nwlmax

!     Perform Discrete Wavelet transform
      ifail = 0
      Call c09ccf(n,x,lenc,c,nwl,dwtlev,icomm,ifail)

      Write (nout,99997) nwl
      Write (nout,99996)
      Write (nout,99995) dwtlev(1:nwl+1)
      nnz = sum(dwtlev(1:nwl+1))
      Write (nout,99994)
      Write (nout,99998) c(1:nnz)

!     Reconstruct original data
      nwlinv = nwl

      ifail = 0
      Call c09cdf(nwlinv,lenc,c,n,y,icomm,ifail)

      Write (nout,99993)
      Write (nout,99998) y(1:n)

99999 Format (1X,' MLDWT :: Wavelet : ',A10,', End mode : ',A10,' N = ',I10)
99998 Format (8(F8.4,1X),:)
99997 Format (1X,' Number of Levels : ',I10)
99996 Format (1X,' Number of coefficients in each level : ')
99995 Format (8(I8,1X),:)
99994 Format (1X,' Wavelet coefficients C : ')
99993 Format (1X,' Reconstruction              Y : ')
    End Program c09ccfe


c09dafe.f90

    Program c09dafe

!     C09DAF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: c09aaf, c09daf, c09dbf, nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Integer                          :: ifail, n, nf, nwc, nwl, ny
      Character (14)                   :: mode, wavnam, wtrans
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: ca(:), cd(:), x(:), y(:)
      Integer                          :: icomm(100)
!     .. Executable Statements ..

!     .. Executable Statements ..
      Write (nout,*) 'C09DAF Example Program Results'
!     Skip heading in data file
      Read (nin,*)
!     Read problem parameters.
      Read (nin,*) n
      Read (nin,*) wavnam, mode
      Allocate (x(n),y(n))

      Write (nout,99999) wavnam, mode
!     Read array
      Read (nin,*) x(1:n)
      Write (nout,*) 'Input Data      X :'
      Write (nout,99997) x(1:n)
!     Query wavelet filter dimensions
      wtrans = 'Time invariant'

!     ifail: behaviour on error exit
!            =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
      ifail = 0
      Call c09aaf(wavnam,wtrans,mode,n,nwl,nf,nwc,icomm,ifail)

      Allocate (ca(nwc),cd(nwc))

      ifail = 0
      Call c09daf(n,x,nwc,ca,cd,icomm,ifail)

      Write (nout,99998)
      Write (nout,99997) ca(1:nwc)
      Write (nout,99996)
      Write (nout,99997) cd(1:nwc)

      ny = n

      ifail = 0
      Call c09dbf(nwc,ca,cd,ny,y,icomm,ifail)

      Write (nout,99995)
      Write (nout,99997) y(1:ny)

99999 Format (1X,'MODWT :: Wavelet: ',A,', End mode: ',A)
99998 Format (1X,'Approximation coefficients CA : ')
99997 Format (1X,8(F8.4,1X),:)
99996 Format (1X,'Detail coefficients        CD : ')
99995 Format (1X,'Reconstruction              Y : ')
    End Program c09dafe


c09dcfe.f90

    Program c09dcfe

!     C09DCF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: c09aaf, c09dcf, c09ddf, nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Integer                          :: ifail, lenc, n, na, nf, nwc, nwl, ny
      Character (10)                   :: keepa, mode, wavnam, wtrans
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: c(:), x(:), y(:)
      Integer                          :: icomm(100)
!     .. Executable Statements ..
      Write (nout,*) 'C09DCF Example Program Results'
!     Skip heading in data file
      Read (nin,*)
!     Read problem parameters
      Read (nin,*) n
      Read (nin,*) wavnam, mode, keepa
      Allocate (x(n),y(n))

      Write (nout,99999) wavnam, mode, n
      Write (nout,99998) keepa

!     Read data array and write it out
      Read (nin,*) x(1:n)

      Write (nout,*) ' Input Data      X :'
      Write (nout,99997) x(1:n)

!     Query wavelet filter dimensions
!     For Multi-Resolution Analysis, decomposition, wtrans = 'U'
      wtrans = 'U'

!     ifail: behaviour on error exit
!            =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
      ifail = 0
      Call c09aaf(wavnam,wtrans,mode,n,nwl,nf,nwc,icomm,ifail)
!     Choose to decompose over two levels
      nwl = 2
      nwc = (nwl+1)*n
      If (keepa=='Final') Then
        lenc = nwc
      Else
        lenc = 2*n*nwl
      End If

      Allocate (c(lenc))

!     Perform Discrete Wavelet transform
      ifail = 0
      Call c09dcf(n,x,keepa,lenc,c,nwl,na,icomm,ifail)

      Write (nout,99996) nwl
      Write (nout,99995) na
      Write (nout,99994)
      Write (nout,99997) c(1:lenc)

!     Reconstruct original data
      ny = n

      ifail = 0
      Call c09ddf(nwl,keepa,lenc,c,ny,y,icomm,ifail)

      Write (nout,99993)
      Write (nout,99997) y(1:ny)

99999 Format (1X,' MLMODWT :: Wavelet : ',A10,', End mode : ',A10,' N = ',I10)
99998 Format (1X,'         :: Keepa   : ',A10)
99997 Format (8(F8.4,1X),:)
99996 Format (1X,' Number of Levels : ',I10)
99995 Format (1X,' Number of coefficients in each level : ',I10)
99994 Format (1X,' Wavelet coefficients C : ')
99993 Format (1X,' Reconstruction              Y : ')
    End Program c09dcfe


c09eafe.f90

    Program c09eafe

!     C09EAF Example Program Text
!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: c09abf, c09eaf, c09ebf, nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Integer                          :: i, ifail, lda, ldb, ldca, ldcd,      &
                                          ldch, ldcv, m, n, nf, nwcm, nwcn,    &
                                          nwct, nwl
      Character (12)                   :: mode, wavnam, wtrans
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: a(:,:), b(:,:), ca(:,:), cd(:,:),    &
                                          ch(:,:), cv(:,:)
      Integer                          :: icomm(180)
!     .. Executable Statements ..
      Write (nout,*) 'C09EAF Example Program Results'

!     Skip heading in data file
      Read (nin,*)
!     Read problem parameters.
      Read (nin,*) m, n
      Read (nin,*) wavnam, mode
      Write (nout,99999) wavnam, mode

      lda = m
      ldb = m
      Allocate (a(lda,n),b(ldb,n))

!     Read data array
      Do i = 1, m
        Read (nin,*) a(i,1:n)
      End Do

      Write (nout,99998) 'Input Data                    A'
      Do i = 1, m
        Write (nout,99997) a(i,1:n)
      End Do

!     Query wavelet filter dimensions
      wtrans = 'Single Level'

!     ifail: behaviour on error exit
!     =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
      ifail = 0
      Call c09abf(wavnam,wtrans,mode,m,n,nwl,nf,nwct,nwcn,icomm,ifail)
      nwcm = nwct/(4*nwcn)

      Allocate (ca(nwcm,nwcn),cd(nwcm,nwcn),cv(nwcm,nwcn),ch(nwcm,nwcn))
      ldca = nwcm
      ldch = nwcm
      ldcv = nwcm
      ldcd = nwcm

      ifail = 0
      Call c09eaf(m,n,a,lda,ca,ldca,ch,ldch,cv,ldcv,cd,ldcd,icomm,ifail)

      Write (nout,99998) 'Approximation coefficients   CA'
      Do i = 1, nwcm
        Write (nout,99997) ca(i,1:nwcn)
      End Do
      Write (nout,99998) 'Diagonal coefficients        CD'
      Do i = 1, nwcm
        Write (nout,99997) cd(i,1:nwcn)
      End Do
      Write (nout,99998) 'Horizontal coefficients      CH'
      Do i = 1, nwcm
        Write (nout,99997) ch(i,1:nwcn)
      End Do
      Write (nout,99998) 'Vertical coefficients        CV'
      Do i = 1, nwcm
        Write (nout,99997) cv(i,1:nwcn)
      End Do

      ifail = 0
      Call c09ebf(m,n,ca,ldca,ch,ldch,cv,ldcv,cd,ldcd,b,ldb,icomm,ifail)

      Write (nout,99998) 'Reconstruction                B'
      Do i = 1, m
        Write (nout,99997) b(i,1:n)
      End Do

99999 Format (/,1X,'DWT ::',/,1X,'       Wavelet : ',A,/,1X,                   &
        '       End mode: ',A)
99998 Format (/,1X,A,' : ')
99997 Format (1X,8(F8.4,1X),:)
    End Program c09eafe


c09ecfe.f90

    Program c09ecfe

!     C09ECF Example Program Text
!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: c09abf, c09ecf, c09edf, c09eyf, nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Integer                          :: i, i1, ifail, ilevel, itype_coeffs,  &
                                          j1, lda, ldb, ldcoefs, lenc, m, n,   &
                                          nf, nwcn, nwct, nwl, nwlinv, nwlmax
      Character (10)                   :: mode, wavnam, wtrans
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: a(:,:), b(:,:), c(:), coefs(:,:)
      Integer, Allocatable             :: dwtlvm(:), dwtlvn(:)
      Integer                          :: icomm(180)
!     .. Executable Statements ..
      Write (nout,*) 'C09ECF Example Program Results'
      Write (nout,*)
!     Skip heading in data file
      Read (nin,*)
!     Read problem parameters
      Read (nin,*) m, n
      Read (nin,*) wavnam, mode
      lda = m
      ldb = m
      Allocate (a(lda,n),b(ldb,n))

      Write (nout,99999) wavnam, mode, m, n

!     Read data array and write it out

      Do i = 1, m
        Read (nin,*) a(i,1:n)
      End Do

      Write (nout,*) ' Input Data     A :'
      Do i = 1, m
        Write (nout,99998) a(i,1:n)
      End Do

!     Query wavelet filter dimensions
!     For Multi-Resolution Analysis, decomposition, wtrans = 'M'
      wtrans = 'Multilevel'
      ifail = 0
      Call c09abf(wavnam,wtrans,mode,m,n,nwlmax,nf,nwct,nwcn,icomm,ifail)

      lenc = nwct
      Allocate (c(lenc),dwtlvm(nwlmax),dwtlvn(nwlmax))

      nwl = nwlmax

!     Perform Discrete Wavelet transform
      ifail = 0
      Call c09ecf(m,n,a,lda,lenc,c,nwl,dwtlvm,dwtlvn,icomm,ifail)

      Write (nout,99997) nwl
      Write (nout,99996)
      Write (nout,99995) dwtlvm(1:nwl)
      Write (nout,99994)
      Write (nout,99995) dwtlvn(1:nwl)

!     Allocate an array in which to extract coefficients
      ldcoefs = dwtlvm(nwl)
      Allocate (coefs(ldcoefs,dwtlvn(nwl)))

!     Extract each set of coefficients, working from the deepest level
      Write (nout,99993)
      Do ilevel = nwl, 1, -1
        Write (nout,99992) ilevel, dwtlvm(nwl-ilevel+1), dwtlvn(nwl-ilevel+1)

        Do itype_coeffs = 0, 3
          Select Case (itype_coeffs)
          Case (0)
            If (ilevel==nwl) Then
              Write (nout,99991) 'Approximation coefficients '
            End If
          Case (1)
            Write (nout,99991) 'Vertical coefficients      '
          Case (2)
            Write (nout,99991) 'Horizontal coefficients    '
          Case (3)
            Write (nout,99991) 'Diagonal coefficients      '
          End Select
          If (itype_coeffs>0 .Or. ilevel==nwl) Then
!           Call the 2D extraction routine c09eaf
            Call c09eyf(ilevel,itype_coeffs,lenc,c,coefs,ldcoefs,icomm,ifail)
            Do i1 = 1, dwtlvm(nwl-ilevel+1)
              Write (nout,99989)(coefs(i1,j1),j1=1,dwtlvn(nwl-ilevel+1))
            End Do
          End If
        End Do
      End Do

      nwlinv = nwl

!     Reconstruct original data
      ifail = 0
      Call c09edf(nwlinv,lenc,c,m,n,b,ldb,icomm,ifail)

      Write (nout,99990)
      Do i = 1, m
        Write (nout,99998) b(i,1:n)
      End Do

99999 Format (1X,' MLDWT :: Wavelet  : ',A,/,1X,'          End mode : ',A,/,   &
        1X,'          M        : ',I4,/,1X,'          N        : ',I4,/)
99998 Format (8(F8.4,1X),:)
99997 Format (/,1X,' Number of Levels : ',I10)
99996 Format (1X,' Number of coefficients in 1st dimension for each level :')
99995 Format (8(I8,1X),:)
99994 Format (1X,' Number of coefficients in 2nd dimension for each level :')
99993 Format (/,1X,' Wavelet coefficients C : ')
99992 Format (1X,55('-'),/,1X,' Level : ',I10,'; output is ',I10,' by ',I10,/, &
        1X,55('-'))
99991 Format (1X,A28,': ')
99990 Format (/,1X,' Reconstruction           B : ')
99989 Format (4X,5(F8.4,1X),:)
    End Program c09ecfe


c09ezfe.f90

    Program c09ezfe

!     C09EZF Example Program Text
!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: c09abf, c09ecf, c09edf, c09eyf, c09ezf, dnrm2,    &
                             nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: mse, thresh
      Integer                          :: cindex, denoised, i, ifail, ilev, j, &
                                          lda, ldb, ldd, lenc, m, n, nf, nwcn, &
                                          nwct, nwl
      Character (10)                   :: mode, wavnam, wtrans
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: a(:,:), an(:,:), b(:,:), c(:),       &
                                          d(:,:), e(:,:)
      Integer, Allocatable             :: dwtlvm(:), dwtlvn(:)
      Integer                          :: icomm(180)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: abs, log, real, sqrt
!     .. Executable Statements ..
      Write (nout,*) 'C09EZF Example Program Results'
      Write (nout,*)
!     Skip heading in data file
      Read (nin,*)
!     Read problem parameters
      Read (nin,*) m, n
      Read (nin,*) wavnam, mode
      Write (nout,99999) wavnam, mode, m, n

!     Allocate arrays to hold the original data, A, original data plus noise,
!     AN, reconstruction using denoised coefficients, B, and randomly
!     generated noise, X.
      lda = m
      ldb = m
      Allocate (a(lda,n),an(lda,n),b(ldb,n),e(m,n))

!     Read in the original data
      Do i = 1, m
        Read (nin,*) a(i,1:n)
      End Do

!     Output the original data
      Write (nout,99997)
      Do i = 1, m
        Write (nout,99998) a(i,1:n)
      End Do

!     Fill the array AN with the original data in A plus some noise
!     and return a VisuShrink denoising threshold, thresh.
      Call create_noise(a,an,lda,m,n,thresh)

!     Output the noisy data
      Write (nout,99996)
      Do i = 1, m
        Write (nout,99998) an(i,1:n)
      End Do

!     Query wavelet filter dimensions
!     For Multi-Resolution Analysis, decomposition, wtrans = 'M'
      wtrans = 'Multilevel'
      ifail = 0
      Call c09abf(wavnam,wtrans,mode,m,n,nwl,nf,nwct,nwcn,icomm,ifail)

!     Allocate arrays to hold the coefficients, C, and the dimensions
!     of the coefficients at each level, DWTLVM, DWTLVN
      lenc = nwct
      Allocate (c(lenc),dwtlvm(nwl),dwtlvn(nwl))

!     Perform a forwards multi-level transform on the noisy data
      ifail = 0
      Call c09ecf(m,n,an,lda,lenc,c,nwl,dwtlvm,dwtlvn,icomm,ifail)

!     Reconstruct without thresholding of detail coefficients
      ifail = 0
      Call c09edf(nwl,lenc,c,m,n,b,ldb,icomm,ifail)

!     Calculate the Mean Square Error of the noisy reconstruction
      e(:,:) = a(:,:) - b(:,:)
      mse = dnrm2(m*n,e,1)
      mse = mse**2
      mse = mse/real(m*n,kind=nag_wp)
      Write (nout,99995) mse

!     Now perform the denoising by extracting each of the detail
!     coefficients at each level and applying hard thresholding

!     Allocate a 2D array to hold the detail coefficients
      ldd = dwtlvm(nwl)
      Allocate (d(ldd,dwtlvn(nwl)))

      denoised = 0
!     For each level
      Do ilev = nwl, 1, -1

!       Select detail coefficients
        Do cindex = 1, 3

!         Extract coefficients into the 2D array D
          ifail = 0
          Call c09eyf(ilev,cindex,lenc,c,d,ldd,icomm,ifail)

!         Perform the hard thresholding operation
          Do j = 1, dwtlvn(nwl-ilev+1)
            Do i = 1, dwtlvm(nwl-ilev+1)
              If (abs(d(i,j))<thresh) Then
                d(i,j) = 0.0_nag_wp
                denoised = denoised + 1
              End If
            End Do
          End Do

!         Insert the denoised coefficients back into C
          ifail = 0
          Call c09ezf(ilev,cindex,lenc,c,d,ldd,icomm,ifail)

        End Do

      End Do

!     Output the number of coefficients that were set to zero
      Write (nout,99994) denoised, nwct - dwtlvm(1)*dwtlvn(1)

!     Reconstruct original data following thresholding of detail coefficients
      ifail = 0
      Call c09edf(nwl,lenc,c,m,n,b,ldb,icomm,ifail)

!     Calculate the Mean Square Error of the denoised reconstruction
      e(:,:) = a(:,:) - b(:,:)
      mse = dnrm2(m*n,e,1)
      mse = mse**2
      mse = mse/real(m*n,kind=nag_wp)
      Write (nout,99993) mse

!     Output the denoised reconstruction
      Write (nout,99992)
      Do i = 1, m
        Write (nout,99998) b(i,1:n)
      End Do

99999 Format (1X,' MLDWT :: Wavelet  : ',A,/,1X,'          End mode : ',A,/,   &
        1X,'          M        : ',I4,/,1X,'          N        : ',I4)
99998 Format (8(F8.4,1X),:)
99997 Format (/,1X,' Original data            A  : ')
99996 Format (/,1X,' Original data plus noise AN : ')
99995 Format (/,1X,' Without denoising Mean Square Error is ',F9.6)
99994 Format (/,1X,' Number of coefficients denoised is ',I3,' out of ',I3)
99993 Format (/,1X,' With denoising Mean Square Error is ',F9.6)
99992 Format (/,1X,' Reconstruction of denoised input D : ')

    Contains

!     Subroutine fills the output array AN with the data in A
!     plus some noise taken from a normal distribution, and
!     returns the VisuShrink denoising threshold, thresh.

      Subroutine create_noise(a,an,lda,m,n,thresh)

!       .. Use Statements ..
        Use nag_library, Only: g05kff, g05skf
!       .. Parameters ..
        Integer, Parameter             :: lseed = 1
!       .. Scalar Arguments ..
        Real (Kind=nag_wp), Intent (Out) :: thresh
        Integer, Intent (In)           :: lda, m, n
!       .. Array Arguments ..
        Real (Kind=nag_wp), Intent (In) :: a(lda,n)
        Real (Kind=nag_wp), Intent (Out) :: an(lda,n)
!       .. Local Scalars ..
        Real (Kind=nag_wp)             :: var, xmu
        Integer                        :: genid, i, ifail, lstate, subid
!       .. Local Arrays ..
        Real (Kind=nag_wp), Allocatable :: x(:,:)
        Integer                        :: seed(lseed)
        Integer, Allocatable           :: state(:)
!       .. Executable Statements ..

!       Set up call to g05skf in order to create some random noise from
!       a normal distribution to add to the original data.
!       Initial call to RNG initializer to get size of STATE array
        seed(1) = 642521
        genid = 3
        subid = 0
        lstate = 0
        Allocate (state(lstate))
        ifail = 0
        Call g05kff(genid,subid,seed,lseed,state,lstate,ifail)

!       Reallocate STATE
        Deallocate (state)
        Allocate (state(lstate))

!       Initialize the generator to a repeatable sequence
        ifail = 0
        Call g05kff(genid,subid,seed,lseed,state,lstate,ifail)

!       Set the distribution parameters for the random noise.
        xmu = 0.0_nag_wp
        var = 0.1E-3_nag_wp

        Allocate (x(m,n))

!       Generate the noise variates
        ifail = 0
        Do i = 1, n
          Call g05skf(m,xmu,var,state,x(1,i),ifail)
        End Do

!       Add the noise to the original input and save in AN
        an(:,:) = a(:,:) + x(:,:)

!       Calculate the threshold based on VisuShrink denoising
        thresh = sqrt(var)*sqrt(2._nag_wp*log(real(m*n,kind=nag_wp)))

      End Subroutine create_noise

    End Program c09ezfe


c09fafe.f90

    Program c09fafe

!     C09FAF Example Program Text
!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: c09acf, c09faf, c09fbf, c09fyf, nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Integer                          :: cindex, fr, i, ifail, j, lda, ldb,   &
                                          ldd, lenc, m, n, nf, nwcfr, nwcm,    &
                                          nwcn, nwct, nwl, sda, sdb, sdd
      Character (12)                   :: mode, wavnam, wtrans
      Character (33)                   :: title
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: a(:,:,:), b(:,:,:), c(:), d(:,:,:)
      Integer                          :: icomm(260)
      Character (3)                    :: cpass(0:7)
!     .. Executable Statements ..
      Continue
      Write (nout,*) 'C09FAF Example Program Results'

!     Skip heading in data file
      Read (nin,*)
!     Read problem parameters.
      Read (nin,*) m, n, fr
      Read (nin,*) wavnam, mode
      Write (nout,99999) wavnam, mode

      lda = m
      sda = n
      Allocate (a(lda,sda,fr))
      ldb = m
      sdb = n
      Allocate (b(ldb,sdb,fr))

!     Read data array
      Do j = 1, fr
        Read (nin,*)
        Read (nin,*)(a(i,1:n,j),i=1,m)
      End Do

      Write (nout,99998) 'Input Data                    A'
      Do j = 1, fr
        Write (nout,99996) j
        Do i = 1, m
          Write (nout,99997) a(i,1:n,j)
        End Do
      End Do

!     Query wavelet filter dimensions
      wtrans = 'Single Level'

!     ifail: behaviour on error exit
!     =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
      ifail = 0
      Call c09acf(wavnam,wtrans,mode,m,n,fr,nwl,nf,nwct,nwcn,nwcfr,icomm,      &
        ifail)
      nwcm = nwct/(8*nwcn*nwcfr)
      lenc = nwct
      Allocate (c(lenc))

!     3D DWT decomposition
      ifail = 0
      Call c09faf(m,n,fr,a,lda,sda,lenc,c,icomm,ifail)

      ldd = nwcm
      sdd = nwcn
      Allocate (d(ldd,sdd,nwcfr))

!     Loop over low/high passes from LLL to HHH
      cpass(0:7) = (/'LLL','LLH','LHL','LHH','HLL','HLH','HHL','HHH'/)
      Do cindex = 0, 7
        If (cindex==0) Then
          title = 'Approximation coefficients (LLL)'
        Else
          title = 'Detail coefficients (' // cpass(cindex) // ')'
        End If

!       Extract coefficients
        Call c09fyf(0,cindex,lenc,c,d,ldd,sdd,icomm,ifail)

        Write (nout,99992) title
        Write (nout,99995)('Frame ',j,j=1,nwcfr)
        Write (nout,99994) cindex, (d(1,1:nwcn,j),j=1,nwcfr)
        Do i = 2, nwcm
          Write (nout,99993)(d(i,1:nwcn,j),j=1,nwcfr)
        End Do
      End Do

!     3D DWT reconstruction
      ifail = 0
      Call c09fbf(m,n,fr,lenc,c,b,ldb,sdb,icomm,ifail)

      Write (nout,99998) 'Output Data                    B'
      Do j = 1, fr
        Write (nout,99996) j
        Do i = 1, m
          Write (nout,99997) b(i,1:n,j)
        End Do
      End Do

99999 Format (/,1X,'DWT ::',/,1X,'       Wavelet : ',A,/,1X,                   &
        '       End mode: ',A)
99998 Format (/,1X,A,' : ')
99997 Format (1X,8(F8.4,1X),:)
99996 Format (1X,'Frame ',I2,' : ')
99995 Format (11X,6(10X,A,I2))
99994 Format (4X,I4,6X,8(1X,F8.4))
99993 Format (14X,8(1X,F8.4))
99992 Format (/,1X,A)
    End Program c09fafe


c09fcfe.f90

    Program c09fcfe

!     C09FCF Example Program Text
!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: c09acf, c09fcf, c09fdf, c09fyf, nag_wp, x02ajf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: eps, esq, frob
      Integer                          :: fr, i, ifail, j, k, lda, ldb, ldd,   &
                                          lenc, m, n, nf, nwcfr, nwcm, nwcn,   &
                                          nwct, nwl, nwlinv, nwlmax, sda, sdb, &
                                          sdd, want_coeffs, want_level
      Character (10)                   :: mode, wavnam, wtrans
      Character (33)                   :: title
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: a(:,:,:), b(:,:,:), c(:), d(:,:,:),  &
                                          e(:,:,:)
      Integer, Allocatable             :: dwtlvfr(:), dwtlvm(:), dwtlvn(:)
      Integer                          :: icomm(260)
      Character (3)                    :: cpass(0:7)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: max, real, sqrt
!     .. Executable Statements ..
      Continue
      Write (nout,*) 'C09FCF Example Program Results'
      Write (nout,*)
!     Skip heading in data file
      Read (nin,*)
!     Read problem parameters
      Read (nin,*) m, n, fr
      Read (nin,*) wavnam, mode
      lda = m
      sda = n
      ldb = m
      sdb = n
      Allocate (a(lda,sda,fr),b(ldb,sdb,fr),e(m,n,fr))

      Write (nout,99999) wavnam, mode, m, n, fr

!     Read data array and write it out

      Do j = 1, fr
        Do i = 1, m
          Read (nin,*) a(i,1:n,j)
        End Do
        If (j<fr) Then
          Read (nin,*)
        End If
      End Do

      Write (nout,*) ' Input Data     A :'
      Do j = 1, fr
        Write (nout,99997) j
        Do i = 1, m
          Write (nout,99998) a(i,1:n,j)
        End Do
      End Do

!     Query wavelet filter dimensions
!     For Multi-Resolution Analysis, decomposition, wtrans = 'M'
      wtrans = 'Multilevel'
      ifail = 0
      Call c09acf(wavnam,wtrans,mode,m,n,fr,nwlmax,nf,nwct,nwcn,nwcfr,icomm,   &
        ifail)

      lenc = nwct
      Allocate (c(lenc),dwtlvm(nwlmax),dwtlvn(nwlmax),dwtlvfr(nwlmax))

      nwl = nwlmax

!     Perform Discrete Wavelet transform
      ifail = 0
      Call c09fcf(m,n,fr,a,lda,sda,lenc,c,nwl,dwtlvm,dwtlvn,dwtlvfr,icomm,     &
        ifail)

      Write (nout,99996) nwl
      Write (nout,99995)
      Write (nout,99992) dwtlvm(1:nwl)
      Write (nout,99994)
      Write (nout,99992) dwtlvn(1:nwl)
      Write (nout,99993)
      Write (nout,99992) dwtlvfr(1:nwl)

!     Print the first level HLL coefficients
      want_level = 1
      want_coeffs = 4

      nwcm = dwtlvm(nwl-want_level+1)
      nwcn = dwtlvn(nwl-want_level+1)
      nwcfr = dwtlvfr(nwl-want_level+1)

!     Allocate space to store the selected coefficients
      ldd = nwcm
      sdd = nwcn
      Allocate (d(ldd,sdd,nwcfr))

      Write (nout,99987) want_level, nwcm, nwcn, nwcfr

      cpass(0:7) = (/'LLL','LLH','LHL','LHH','HLL','HLH','HHL','HHH'/)
      If (want_coeffs==0) Then
        title = 'Approximation coefficients (LLL)'
      Else
        title = 'Detail coefficients (' // cpass(want_coeffs) // ')'
      End If

!     Extract coefficients
      Call c09fyf(want_level,want_coeffs,lenc,c,d,ldd,sdd,icomm,ifail)

!     Print out the selected set of coefficients
      Write (nout,99986) title
      Write (nout,99989) want_level, want_coeffs
      Do k = 1, nwcfr
        Write (nout,99988) k
        Do i = 1, nwcm
          Write (nout,99998) d(i,1:nwcn,k)
        End Do
      End Do

      nwlinv = nwl

!     Reconstruct original data
      ifail = 0
      Call c09fdf(nwlinv,lenc,c,m,n,fr,b,ldb,sdb,icomm,ifail)

!     Check reconstruction matches original
      eps = 10.0_nag_wp*real(m,kind=nag_wp)*real(n,kind=nag_wp)*               &
        real(fr,kind=nag_wp)*x02ajf()

      e(1:m,1:n,1:fr) = b(1:m,1:n,1:fr) - a(1:m,1:n,1:fr)
      frob = 0.0_nag_wp
      Do k = 1, fr
        esq = 0.0_nag_wp
        Do j = 1, n
          Do i = 1, m
            esq = esq + e(i,j,k)**2
          End Do
        End Do
        frob = max(frob,sqrt(esq))
      End Do

      If (frob>eps) Then
        Write (nout,99991)
      Else
        Write (nout,99990)
      End If

99999 Format (1X,' MLDWT :: Wavelet  : ',A,/,1X,'          End mode : ',A,/,   &
        1X,'          M        : ',I4,/,1X,'          N        : ',I4,/,1X,    &
        '          FR       : ',I4,/)
99998 Format (8(F8.4,1X),:)
99997 Format (1X,' Frame ',I2,' : ')
99996 Format (/,1X,' Number of Levels : ',I10)
99995 Format (1X,' Number of coefficients in 1st dimension for each level :')
99994 Format (1X,' Number of coefficients in 2nd dimension for each level :')
99993 Format (1X,' Number of coefficients in 3rd dimension for each level :')
99992 Format (8(I8,1X),:)
99991 Format (/,1X,' Fail: Frobenius norm of B-A, where A is the original ',/, &
        1X,' data and B is the reconstrucion, is too large.')
99990 Format (/,1X,' Success: the reconstruction matches the original.')
99989 Format (1X,' Level ',I2,', Coefficients ',I2,' : ')
99988 Format (1X,' Frame ',I2,' : ')
99987 Format (/,1X,70('-'),/,1X,'Level : ',I10,'; output is ',I10,' by ',I10,  &
        ' by ',I10,/,1X,70('-'))
99986 Format (/,1X,A)
    End Program c09fcfe


c09fzfe.f90

    Program c09fzfe

!     C09FZF Example Program Text
!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: c09acf, c09fcf, c09fdf, c09fyf, c09fzf, dnrm2,    &
                             nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: mse, thresh
      Integer                          :: cindex, denoised, fr, i, ifail,      &
                                          ilev, j, k, lda, ldb, ldd, lenc, m,  &
                                          n, nf, nwcfr, nwcn, nwct, nwl, sda,  &
                                          sdb, sdd
      Character (10)                   :: mode, wavnam, wtrans
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: a(:,:,:), an(:,:,:), b(:,:,:), c(:), &
                                          d(:,:,:), e(:,:,:)
      Integer, Allocatable             :: dwtlvfr(:), dwtlvm(:), dwtlvn(:)
      Integer                          :: icomm(260)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: abs, log, real, sqrt
!     .. Executable Statements ..
      Write (nout,*) 'C09FZF Example Program Results'
      Write (nout,*)
!     Skip heading in data file
      Read (nin,*)
!     Read problem parameters
      Read (nin,*) m, n, fr
      Read (nin,*) wavnam, mode
      Write (nout,99999) wavnam, mode, m, n, fr

!     Allocate arrays to hold the original data, A, original data plus noise,
!     AN, reconstruction using denoised coefficients, B, and randomly
!     generated noise, X.
      lda = m
      ldb = m
      sda = n
      sdb = n
      Allocate (a(lda,lda,fr),an(lda,lda,fr),b(ldb,ldb,fr),e(m,n,fr))

!     Read in the original data
      Do k = 1, fr
        Do i = 1, m
          Read (nin,*) a(i,1:n,k)
        End Do
        If (k<fr) Then
          Read (nin,*)
        End If
      End Do

!     Output the original data
      Write (nout,99997)
      Do k = 1, fr
        Write (nout,99991) k
        Do i = 1, m
          Write (nout,99998) a(i,1:n,k)
        End Do
      End Do

!     Fill the array AN with the original data in A plus some noise
!     and return a VisuShrink denoising threshold, thresh.
      Call create_noise(a,an,lda,sda,m,n,fr,thresh)

!     Output the noisy data
      Write (nout,99996)
      Do k = 1, fr
        Write (nout,99991) k
        Do i = 1, m
          Write (nout,99998) an(i,1:n,k)
        End Do
      End Do

!     Query wavelet filter dimensions
!     For Multi-Resolution Analysis, decomposition, wtrans = 'M'
      wtrans = 'Multilevel'
      ifail = 0
      Call c09acf(wavnam,wtrans,mode,m,n,fr,nwl,nf,nwct,nwcn,nwcfr,icomm,      &
        ifail)

!     Allocate arrays to hold the coefficients, C, and the dimensions
!     of the coefficients at each level, DWTLVM, DWTLVN, DWTLVFR
      lenc = nwct
      Allocate (c(lenc),dwtlvm(nwl),dwtlvn(nwl),dwtlvfr(nwl))

!     Perform a forwards multi-level transform on the noisy data
      ifail = 0
      Call c09fcf(m,n,fr,an,lda,sda,lenc,c,nwl,dwtlvm,dwtlvn,dwtlvfr,icomm,    &
        ifail)

!     Reconstruct without thresholding of detail coefficients
      ifail = 0
      Call c09fdf(nwl,lenc,c,m,n,fr,b,ldb,sdb,icomm,ifail)

!     Calculate the Mean Square Error of the noisy reconstruction
      e(:,:,:) = a(:,:,:) - b(:,:,:)
      mse = dnrm2(m*n*fr,e,1)
      mse = mse**2
      mse = mse/real(m*n*fr,kind=nag_wp)
      Write (nout,99995) mse

!     Now perform the denoising by extracting each of the detail
!     coefficients at each level and applying hard thresholding

!     Allocate a 3D array to hold the detail coefficients
      ldd = dwtlvm(nwl)
      sdd = dwtlvn(nwl)
      Allocate (d(ldd,sdd,dwtlvn(nwl)))

      denoised = 0
!     For each level
      Do ilev = nwl, 1, -1

!       Select detail coefficients
        Do cindex = 1, 7

!         Extract coefficients into the 3D array D
          ifail = 0
          Call c09fyf(ilev,cindex,lenc,c,d,ldd,sdd,icomm,ifail)

!         Perform the hard thresholding operation
          Do k = 1, dwtlvfr(nwl-ilev+1)
            Do j = 1, dwtlvn(nwl-ilev+1)
              Do i = 1, dwtlvm(nwl-ilev+1)
                If (abs(d(i,j,k))<thresh) Then
                  d(i,j,k) = 0.0_nag_wp
                  denoised = denoised + 1
                End If
              End Do
            End Do
          End Do

!         Insert the denoised coefficients back into C
          ifail = 0
          Call c09fzf(ilev,cindex,lenc,c,d,ldd,sdd,icomm,ifail)

        End Do

      End Do

!     Output the number of coefficients that were set to zero
      Write (nout,99994) denoised, nwct - dwtlvm(1)*dwtlvn(1)*dwtlvfr(1)

!     Reconstruct original data following thresholding of detail coefficients
      ifail = 0
      Call c09fdf(nwl,lenc,c,m,n,fr,b,ldb,sdb,icomm,ifail)

!     Calculate the Mean Square Error of the denoised reconstruction
      e(:,:,:) = a(:,:,:) - b(:,:,:)
      mse = dnrm2(m*n*fr,e,1)
      mse = mse**2
      mse = mse/real(m*n*fr,kind=nag_wp)
      Write (nout,99993) mse

!     Output the denoised reconstruction
      Write (nout,99992)
      Do k = 1, fr
        Write (nout,99991) k
        Do i = 1, m
          Write (nout,99998) b(i,1:n,k)
        End Do
      End Do

99999 Format (1X,' MLDWT :: Wavelet  : ',A,/,1X,'          End mode : ',A,/,   &
        1X,'          M        : ',I4,/,1X,'          N        : ',I4,/,1X,    &
        '          FR       : ',I4)
99998 Format (8(F8.4,1X),:)
99997 Format (/,1X,' Original data            A  : ')
99996 Format (/,1X,' Original data plus noise AN : ')
99995 Format (/,1X,' Without denoising Mean Square Error is ',F9.6)
99994 Format (/,1X,' Number of coefficients denoised is ',I3,' out of ',I3)
99993 Format (/,1X,' With denoising Mean Square Error is ',F9.6)
99992 Format (/,1X,' Reconstruction of denoised input D : ')
99991 Format (1X,' Frame ',I2,' : ')

    Contains

!     Subroutine fills the output array AN with the data in A
!     plus some noise taken from a normal distribution, and
!     returns the VisuShrink denoising threshold, thresh.

      Subroutine create_noise(a,an,lda,sda,m,n,fr,thresh)

!       .. Use Statements ..
        Use nag_library, Only: g05kff, g05skf
!       .. Parameters ..
        Integer, Parameter             :: lseed = 1
!       .. Scalar Arguments ..
        Real (Kind=nag_wp), Intent (Out) :: thresh
        Integer, Intent (In)           :: fr, lda, m, n, sda
!       .. Array Arguments ..
        Real (Kind=nag_wp), Intent (In) :: a(lda,sda,fr)
        Real (Kind=nag_wp), Intent (Out) :: an(lda,sda,fr)
!       .. Local Scalars ..
        Real (Kind=nag_wp)             :: var, xmu
        Integer                        :: genid, i, ifail, j, lstate, subid
!       .. Local Arrays ..
        Real (Kind=nag_wp), Allocatable :: x(:,:,:)
        Integer                        :: seed(lseed)
        Integer, Allocatable           :: state(:)
!       .. Executable Statements ..

!       Set up call to g05skf in order to create some random noise from
!       a normal distribution to add to the original data.
!       Initial call to RNG initializer to get size of STATE array
        seed(1) = 642521
        genid = 3
        subid = 0
        lstate = 0
        Allocate (state(lstate))
        ifail = 0
        Call g05kff(genid,subid,seed,lseed,state,lstate,ifail)

!       Reallocate STATE
        Deallocate (state)
        Allocate (state(lstate))

!       Initialize the generator to a repeatable sequence
        ifail = 0
        Call g05kff(genid,subid,seed,lseed,state,lstate,ifail)

!       Set the distribution parameters for the random noise.
        xmu = 0.0_nag_wp
        var = 0.1E-3_nag_wp

        Allocate (x(m,n,fr))

!       Generate the noise variates
        ifail = 0
        Do j = 1, fr
          Do i = 1, n
            Call g05skf(m,xmu,var,state,x(1,i,j),ifail)
          End Do
        End Do

!       Add the noise to the original input and save in AN
        an(:,:,:) = a(:,:,:) + x(:,:,:)

!       Calculate the threshold based on VisuShrink denoising
        thresh = sqrt(var)*sqrt(2._nag_wp*log(real(m*n*fr,kind=nag_wp)))

      End Subroutine create_noise

    End Program c09fzfe


d01ahfe.f90

!   D01AHF Example Program Text
!   Mark 26 Release. NAG Copyright 2016.

    Module d01ahfe_mod

!     D01AHF Example Program Module:
!            Parameters and User-defined Routines

!     .. Use Statements ..
      Use nag_library, Only: nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Accessibility Statements ..
      Private
      Public                           :: f
!     .. Parameters ..
      Integer, Parameter, Public       :: nin = 5, nout = 6
    Contains
      Function f(x)

!       .. Function Return Value ..
        Real (Kind=nag_wp)             :: f
!       .. Scalar Arguments ..
        Real (Kind=nag_wp), Intent (In) :: x
!       .. Executable Statements ..
        f = 4.0E0_nag_wp/(1.0E0_nag_wp+x*x)

        Return

      End Function f
    End Module d01ahfe_mod
    Program d01ahfe

!     D01AHF Example Main Program

!     .. Use Statements ..
      Use nag_library, Only: d01ahf, nag_wp
      Use d01ahfe_mod, Only: f, nin, nout
!     .. Implicit None Statement ..
      Implicit None
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: a, ans, b, epsr, relerr
      Integer                          :: ifail, nlimit, npts
!     .. Executable Statements ..
      Write (nout,*) 'D01AHF Example Program Results'

      Read (nin,*)
      Read (nin,*) a, b
      Read (nin,*) nlimit
      Read (nin,*) epsr

      ifail = -1
      ans = d01ahf(a,b,epsr,npts,relerr,f,nlimit,ifail)

      Select Case (ifail)
      Case (0:2)
        Write (nout,*)
        Write (nout,99999) 'Integral = ', ans
        Write (nout,*)
        Write (nout,99998) 'Estimated relative error = ', relerr
        Write (nout,*)
        Write (nout,99997) 'Number of function evaluations = ', npts
      End Select

99999 Format (1X,A,F8.5)
99998 Format (1X,A,E10.2)
99997 Format (1X,A,I5)
    End Program d01ahfe


d01ajfe.f90

!   D01AJF Example Program Text
!   Mark 26 Release. NAG Copyright 2016.

    Module d01ajfe_mod

!     D01AJF Example Program Module:
!            Parameters and User-defined Routines

!     .. Use Statements ..
      Use nag_library, Only: nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Accessibility Statements ..
      Private
      Public                           :: f
!     .. Parameters ..
      Integer, Parameter, Public       :: lw = 800, nout = 6
      Integer, Parameter, Public       :: liw = lw/4
!     .. Local Scalars ..
      Real (Kind=nag_wp), Public, Save :: pi
    Contains
      Function f(x)

!       .. Function Return Value ..
        Real (Kind=nag_wp)             :: f
!       .. Scalar Arguments ..
        Real (Kind=nag_wp), Intent (In) :: x
!       .. Intrinsic Procedures ..
        Intrinsic                      :: sin, sqrt
!       .. Executable Statements ..
        f = x*sin(30.0E0_nag_wp*x)/sqrt(1.0E0_nag_wp-x**2/(4.0E0_nag_wp*pi**2) &
          )

        Return

      End Function f
    End Module d01ajfe_mod
    Program d01ajfe

!     D01AJF Example Main Program

!     .. Use Statements ..
      Use nag_library, Only: d01ajf, nag_wp, x01aaf
      Use d01ajfe_mod, Only: f, liw, lw, nout, pi
!     .. Implicit None Statement ..
      Implicit None
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: a, abserr, b, epsabs, epsrel, result
      Integer                          :: ifail
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: w(:)
      Integer, Allocatable             :: iw(:)
!     .. Executable Statements ..
      Write (nout,*) 'D01AJF Example Program Results'

      Allocate (w(lw),iw(liw))

      pi = x01aaf(pi)
      epsabs = 0.0E0_nag_wp
      epsrel = 1.0E-04_nag_wp
      a = 0.0E0_nag_wp
      b = 2.0E0_nag_wp*pi

      ifail = -1
      Call d01ajf(f,a,b,epsabs,epsrel,result,abserr,w,lw,iw,liw,ifail)

      If (ifail>=0) Then
        Write (nout,*)
        Write (nout,99999) 'A     ', 'lower limit of integration', a
        Write (nout,99999) 'B     ', 'upper limit of integration', b
        Write (nout,99998) 'EPSABS', 'absolute accuracy requested', epsabs
        Write (nout,99998) 'EPSREL', 'relative accuracy requested', epsrel
      End If

      If (ifail>=0 .And. ifail<=5) Then
        Write (nout,*)
        Write (nout,99997) 'RESULT', 'approximation to the integral', result
        Write (nout,99998) 'ABSERR', 'estimate of the absolute error', abserr
        Write (nout,99996) 'IW(1) ', 'number of subintervals used', iw(1)
      End If

99999 Format (1X,A6,' - ',A32,' = ',F10.4)
99998 Format (1X,A6,' - ',A32,' = ',E9.2)
99997 Format (1X,A6,' - ',A32,' = ',F9.5)
99996 Format (1X,A6,' - ',A32,' = ',I4)
    End Program d01ajfe


d01akfe.f90

!   D01AKF Example Program Text
!   Mark 26 Release. NAG Copyright 2016.

    Module d01akfe_mod

!     D01AKF Example Program Module:
!            Parameters and User-defined Routines

!     .. Use Statements ..
      Use nag_library, Only: nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Accessibility Statements ..
      Private
      Public                           :: f
!     .. Parameters ..
      Integer, Parameter, Public       :: lw = 800, nout = 6
      Integer, Parameter, Public       :: liw = lw/4
    Contains
      Function f(x)

!       .. Function Return Value ..
        Real (Kind=nag_wp)             :: f
!       .. Scalar Arguments ..
        Real (Kind=nag_wp), Intent (In) :: x
!       .. Intrinsic Procedures ..
        Intrinsic                      :: cos, sin
!       .. Executable Statements ..
        f = x*(sin(30.0E0_nag_wp*x))*cos(x)

        Return

      End Function f
    End Module d01akfe_mod
    Program d01akfe

!     D01AKF Example Main Program

!     .. Use Statements ..
      Use nag_library, Only: d01akf, nag_wp, x01aaf
      Use d01akfe_mod, Only: f, liw, lw, nout
!     .. Implicit None Statement ..
      Implicit None
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: a, abserr, b, epsabs, epsrel, pi,    &
                                          result
      Integer                          :: ifail
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: w(:)
      Integer, Allocatable             :: iw(:)
!     .. Executable Statements ..
      Write (nout,*) 'D01AKF Example Program Results'

      Allocate (w(lw),iw(liw))

      pi = x01aaf(pi)
      epsabs = 0.0E0_nag_wp
      epsrel = 1.0E-03_nag_wp
      a = 0.0E0_nag_wp
      b = 2.0E0_nag_wp*pi

      ifail = -1
      Call d01akf(f,a,b,epsabs,epsrel,result,abserr,w,lw,iw,liw,ifail)

      If (ifail>=0) Then
        Write (nout,*)
        Write (nout,99999) 'A     ', 'lower limit of integration', a
        Write (nout,99999) 'B     ', 'upper limit of integration', b
        Write (nout,99998) 'EPSABS', 'absolute accuracy requested', epsabs
        Write (nout,99998) 'EPSREL', 'relative accuracy requested', epsrel
      End If

      If (ifail>=0 .And. ifail<=3) Then
        Write (nout,*)
        Write (nout,99997) 'RESULT', 'approximation to the integral', result
        Write (nout,99998) 'ABSERR', 'estimate of the absolute error', abserr
        Write (nout,99996) 'IW(1) ', 'number of subintervals used', iw(1)
      End If

99999 Format (1X,A6,' - ',A32,' = ',F10.4)
99998 Format (1X,A6,' - ',A32,' = ',E9.2)
99997 Format (1X,A6,' - ',A32,' = ',F9.5)
99996 Format (1X,A6,' - ',A32,' = ',I4)
    End Program d01akfe


d01alfe.f90

!   D01ALF Example Program Text
!   Mark 26 Release. NAG Copyright 2016.

    Module d01alfe_mod

!     D01ALF Example Program Module:
!            Parameters and User-defined Routines

!     .. Use Statements ..
      Use nag_library, Only: nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Accessibility Statements ..
      Private
      Public                           :: f
!     .. Parameters ..
      Integer, Parameter, Public       :: lw = 800, nout = 6, npts = 1
      Integer, Parameter, Public       :: liw = lw/2
    Contains
      Function f(x)

!       .. Function Return Value ..
        Real (Kind=nag_wp)             :: f
!       .. Scalar Arguments ..
        Real (Kind=nag_wp), Intent (In) :: x
!       .. Local Scalars ..
        Real (Kind=nag_wp)             :: a
!       .. Intrinsic Procedures ..
        Intrinsic                      :: abs
!       .. Executable Statements ..
        a = abs(x-1.0E0_nag_wp/7.0E0_nag_wp)

        If (a/=0.0E0_nag_wp) Then
          f = a**(-0.5E0_nag_wp)
        Else
          f = 0.0E0_nag_wp
        End If

        Return

      End Function f
    End Module d01alfe_mod
    Program d01alfe

!     D01ALF Example Main Program

!     .. Use Statements ..
      Use nag_library, Only: d01alf, nag_wp
      Use d01alfe_mod, Only: f, liw, lw, nout, npts
!     .. Implicit None Statement ..
      Implicit None
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: a, abserr, b, epsabs, epsrel, result
      Integer                          :: ifail
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: points(:), w(:)
      Integer, Allocatable             :: iw(:)
!     .. Executable Statements ..
      Write (nout,*) 'D01ALF Example Program Results'

      Allocate (points(npts),w(lw),iw(liw))

      epsabs = 0.0E0_nag_wp
      epsrel = 1.0E-03_nag_wp
      a = 0.0E0_nag_wp
      b = 1.0E0_nag_wp
      points(1) = 1.0E0_nag_wp/7.0E0_nag_wp

      ifail = -1
      Call d01alf(f,a,b,npts,points,epsabs,epsrel,result,abserr,w,lw,iw,liw,   &
        ifail)

      If (ifail>=0) Then
        Write (nout,*)
        Write (nout,99999) 'A     ', 'lower limit of integration', a
        Write (nout,99999) 'B     ', 'upper limit of integration', b
        Write (nout,99998) 'EPSABS', 'absolute accuracy requested', epsabs
        Write (nout,99998) 'EPSREL', 'relative accuracy requested', epsrel
        Write (nout,99995) 'POINTS(1)', 'given break-point', points(1)
      End If

      If (ifail>=0 .And. ifail<=5) Then
        Write (nout,*)
        Write (nout,99997) 'RESULT', 'approximation to the integral', result
        Write (nout,99998) 'ABSERR', 'estimate of the absolute error', abserr
        Write (nout,99996) 'IW(1) ', 'number of subintervals used', iw(1)
      End If

99999 Format (1X,A6,'    - ',A32,' = ',F10.4)
99998 Format (1X,A6,'    - ',A32,' = ',E9.2)
99997 Format (1X,A6,'    - ',A32,' = ',F9.5)
99996 Format (1X,A6,'    - ',A32,' = ',I4)
99995 Format (1X,A9,' - ',A32,' = ',F10.4)

    End Program d01alfe


d01amfe.f90

!   D01AMF Example Program Text
!   Mark 26 Release. NAG Copyright 2016.

    Module d01amfe_mod

!     D01AMF Example Program Module:
!            Parameters and User-defined Routines

!     .. Use Statements ..
      Use nag_library, Only: nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Accessibility Statements ..
      Private
      Public                           :: f
!     .. Parameters ..
      Integer, Parameter, Public       :: lw = 800, nout = 6
      Integer, Parameter, Public       :: liw = lw/4
    Contains
      Function f(x)

!       .. Function Return Value ..
        Real (Kind=nag_wp)             :: f
!       .. Scalar Arguments ..
        Real (Kind=nag_wp), Intent (In) :: x
!       .. Intrinsic Procedures ..
        Intrinsic                      :: sqrt
!       .. Executable Statements ..
        f = 1.0E0_nag_wp/((x+1.0E0_nag_wp)*sqrt(x))

        Return

      End Function f
    End Module d01amfe_mod
    Program d01amfe

!     D01AMF Example Main Program

!     .. Use Statements ..
      Use nag_library, Only: d01amf, nag_wp
      Use d01amfe_mod, Only: f, liw, lw, nout
!     .. Implicit None Statement ..
      Implicit None
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: abserr, bound, epsabs, epsrel,       &
                                          result
      Integer                          :: ifail, inf
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: w(:)
      Integer, Allocatable             :: iw(:)
!     .. Executable Statements ..
      Write (nout,*) 'D01AMF Example Program Results'

      Allocate (w(lw),iw(liw))

      epsabs = 0.0E0_nag_wp
      epsrel = 1.0E-04_nag_wp
      bound = 0.0E0_nag_wp
      inf = 1

      ifail = -1
      Call d01amf(f,bound,inf,epsabs,epsrel,result,abserr,w,lw,iw,liw,ifail)

      If (ifail>=0) Then
        Write (nout,*)
        Write (nout,99999) 'A     ', 'lower limit of integration', bound
        Write (nout,99995) 'B     ', 'upper limit of integration', 'infinity'
        Write (nout,99998) 'EPSABS', 'absolute accuracy requested', epsabs
        Write (nout,99998) 'EPSREL', 'relative accuracy requested', epsrel
      End If

      If (ifail>=0 .And. ifail<=5) Then
        Write (nout,*)
        Write (nout,99997) 'RESULT', 'approximation to the integral', result
        Write (nout,99998) 'ABSERR', 'estimate of the absolute error', abserr
        Write (nout,99996) 'IW(1) ', 'number of subintervals used', iw(1)
      End If

99999 Format (1X,A6,' - ',A32,' = ',F10.4)
99998 Format (1X,A6,' - ',A32,' = ',E9.2)
99997 Format (1X,A6,' - ',A32,' = ',F9.5)
99996 Format (1X,A6,' - ',A32,' = ',I4)
99995 Format (1X,A6,' - ',A32,' = ',A8)
    End Program d01amfe


d01anfe.f90

!   D01ANF Example Program Text
!   Mark 26 Release. NAG Copyright 2016.

    Module d01anfe_mod

!     D01ANF Example Program Module:
!            Parameters and User-defined Routines

!     .. Use Statements ..
      Use nag_library, Only: nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Accessibility Statements ..
      Private
      Public                           :: g
!     .. Parameters ..
      Integer, Parameter, Public       :: lw = 800, nout = 6
      Integer, Parameter, Public       :: liw = lw/2
    Contains
      Function g(x)

!       .. Function Return Value ..
        Real (Kind=nag_wp)             :: g
!       .. Scalar Arguments ..
        Real (Kind=nag_wp), Intent (In) :: x
!       .. Intrinsic Procedures ..
        Intrinsic                      :: log
!       .. Executable Statements ..
        If (x>0.0E0_nag_wp) Then
          g = log(x)
        Else
          g = 0.0E0_nag_wp
        End If

        Return

      End Function g
    End Module d01anfe_mod
    Program d01anfe

!     D01ANF Example Main Program

!     .. Use Statements ..
      Use nag_library, Only: d01anf, nag_wp, x01aaf
      Use d01anfe_mod, Only: g, liw, lw, nout
!     .. Implicit None Statement ..
      Implicit None
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: a, abserr, b, epsabs, epsrel, omega, &
                                          pi, result
      Integer                          :: ifail, key
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: w(:)
      Integer, Allocatable             :: iw(:)
!     .. Executable Statements ..
      Write (nout,*) 'D01ANF Example Program Results'

      Allocate (w(lw),iw(liw))

      epsrel = 1.0E-04_nag_wp
      epsabs = 0.0E+00_nag_wp
      a = 0.0E0_nag_wp
      b = 1.0E0_nag_wp
      omega = 10.0E0_nag_wp*x01aaf(pi)
      key = 2

      ifail = -1
      Call d01anf(g,a,b,omega,key,epsabs,epsrel,result,abserr,w,lw,iw,liw,     &
        ifail)

      If (ifail>=0) Then
        Write (nout,*)
        Write (nout,99999) 'A     ', 'lower limit of integration', a
        Write (nout,99999) 'B     ', 'upper limit of integration', b
        Write (nout,99998) 'EPSABS', 'absolute accuracy requested', epsabs
        Write (nout,99998) 'EPSREL', 'relative accuracy requested', epsrel
      End If

      If (ifail>=0 .And. ifail<=5) Then
        Write (nout,*)
        Write (nout,99997) 'RESULT', 'approximation to the integral', result
        Write (nout,99998) 'ABSERR', 'estimate of the absolute error', abserr
        Write (nout,99996) 'IW(1) ', 'number of subintervals used', iw(1)
      End If

99999 Format (1X,A6,' - ',A32,' = ',F10.4)
99998 Format (1X,A6,' - ',A32,' = ',E9.2)
99997 Format (1X,A6,' - ',A32,' = ',F9.5)
99996 Format (1X,A6,' - ',A32,' = ',I4)
    End Program d01anfe


d01apfe.f90

!   D01APF Example Program Text
!   Mark 26 Release. NAG Copyright 2016.

    Module d01apfe_mod

!     D01APF Example Program Module:
!            Parameters and User-defined Routines

!     .. Use Statements ..
      Use nag_library, Only: nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Accessibility Statements ..
      Private
      Public                           :: g1, g2
!     .. Parameters ..
      Integer, Parameter, Public       :: lw = 800, nout = 6
      Integer, Parameter, Public       :: liw = lw/4
    Contains
      Function g1(x)

!       .. Use Statements ..
        Use nag_library, Only: x01aaf
!       .. Function Return Value ..
        Real (Kind=nag_wp)             :: g1
!       .. Scalar Arguments ..
        Real (Kind=nag_wp), Intent (In) :: x
!       .. Local Scalars ..
        Real (Kind=nag_wp)             :: a, pi
!       .. Intrinsic Procedures ..
        Intrinsic                      :: cos
!       .. Executable Statements ..
        pi = x01aaf(pi)
        a = 10.0E0_nag_wp*pi
        g1 = cos(a*x)

        Return

      End Function g1
      Function g2(x)

!       .. Function Return Value ..
        Real (Kind=nag_wp)             :: g2
!       .. Scalar Arguments ..
        Real (Kind=nag_wp), Intent (In) :: x
!       .. Local Scalars ..
        Real (Kind=nag_wp)             :: omega
!       .. Intrinsic Procedures ..
        Intrinsic                      :: sin
!       .. Executable Statements ..
        omega = 10.0E0_nag_wp
        g2 = sin(omega*x)

        Return

      End Function g2
    End Module d01apfe_mod
    Program d01apfe

!     D01APF Example Main Program

!     .. Use Statements ..
      Use nag_library, Only: d01apf, nag_wp
      Use d01apfe_mod, Only: g1, g2, liw, lw, nout
!     .. Implicit None Statement ..
      Implicit None
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: a, abserr, alpha, b, beta, epsabs,   &
                                          epsrel, result
      Integer                          :: ifail, key, nof
!     .. Local Arrays ..
      Real (Kind=nag_wp)               :: alpha_a(2), beta_a(2)
      Real (Kind=nag_wp), Allocatable  :: w(:)
      Integer, Allocatable             :: iw(:)
      Integer                          :: key_a(2)
!     .. Executable Statements ..
      Write (nout,*) 'D01APF Example Program Results'

      Allocate (w(lw),iw(liw))

      alpha_a = (/0.0_nag_wp,-0.5_nag_wp/)
      beta_a = (/0.0_nag_wp,-0.5_nag_wp/)
      key_a = (/2,1/)

      epsabs = 0.0_nag_wp
      epsrel = 1.0E-04_nag_wp
      a = 0.0_nag_wp
      b = 1.0_nag_wp

funs: Do nof = 1, 2

        alpha = alpha_a(nof)
        beta = beta_a(nof)
        key = key_a(nof)

        ifail = -1
        If (nof==1) Then
          Call d01apf(g1,a,b,alpha,beta,key,epsabs,epsrel,result,abserr,w,lw,  &
            iw,liw,ifail)
        Else
          Call d01apf(g2,a,b,alpha,beta,key,epsabs,epsrel,result,abserr,w,lw,  &
            iw,liw,ifail)
        End If

        If (ifail<0) Then
          Exit funs
        End If

        Write (nout,*)
        Write (nout,99999) 'A     ', 'lower limit of integration', a
        Write (nout,99999) 'B     ', 'upper limit of integration', b
        Write (nout,99998) 'EPSABS', 'absolute accuracy requested', epsabs
        Write (nout,99998) 'EPSREL', 'relative accuracy requested', epsrel
        Write (nout,*)
        Write (nout,99998) 'ALPHA ', 'parameter in the weight function', alpha
        Write (nout,99998) 'BETA  ', 'parameter in the weight function', beta
        Write (nout,99997) 'KEY   ', 'which weight function is used', key

        If (ifail>3) Then
          Cycle funs
        End If
        Write (nout,*)
        Write (nout,99996) 'RESULT', 'approximation to the integral', result
        Write (nout,99998) 'ABSERR', 'estimate of the absolute error', abserr
        Write (nout,99997) 'IW(1)', 'number of subintervals used ', iw(1)

      End Do funs

99999 Format (1X,A6,' - ',A32,' = ',F10.4)
99998 Format (1X,A6,' - ',A32,' = ',E9.2)
99997 Format (1X,A6,' - ',A32,' = ',I4)
99996 Format (1X,A6,' - ',A32,' = ',F9.5)
    End Program d01apfe


d01aqfe.f90

!   D01AQF Example Program Text
!   Mark 26 Release. NAG Copyright 2016.

    Module d01aqfe_mod

!     D01AQF Example Program Module:
!            Parameters and User-defined Routines

!     .. Use Statements ..
      Use nag_library, Only: nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Accessibility Statements ..
      Private
      Public                           :: g
!     .. Parameters ..
      Integer, Parameter, Public       :: lw = 800, nout = 6
      Integer, Parameter, Public       :: liw = lw/4
    Contains
      Function g(x)

!       .. Function Return Value ..
        Real (Kind=nag_wp)             :: g
!       .. Scalar Arguments ..
        Real (Kind=nag_wp), Intent (In) :: x
!       .. Local Scalars ..
        Real (Kind=nag_wp)             :: aa
!       .. Executable Statements ..
        aa = 0.01E0_nag_wp
        g = 1.0E0_nag_wp/(x**2+aa**2)

        Return

      End Function g
    End Module d01aqfe_mod
    Program d01aqfe

!     D01AQF Example Main Program

!     .. Use Statements ..
      Use nag_library, Only: d01aqf, nag_wp
      Use d01aqfe_mod, Only: g, liw, lw, nout
!     .. Implicit None Statement ..
      Implicit None
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: a, abserr, b, c, epsabs, epsrel,     &
                                          result
      Integer                          :: ifail
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: w(:)
      Integer, Allocatable             :: iw(:)
!     .. Executable Statements ..
      Write (nout,*) 'D01AQF Example Program Results'

      Allocate (w(lw),iw(liw))

      epsabs = 0.0E0_nag_wp
      epsrel = 1.0E-04_nag_wp
      a = -1.0E0_nag_wp
      b = 1.0E0_nag_wp
      c = 0.5E0_nag_wp

      ifail = -1
      Call d01aqf(g,a,b,c,epsabs,epsrel,result,abserr,w,lw,iw,liw,ifail)

      If (ifail>=0) Then
        Write (nout,*)
        Write (nout,99999) 'A     ', 'lower limit of integration', a
        Write (nout,99999) 'B     ', 'upper limit of integration', b
        Write (nout,99998) 'EPSABS', 'absolute accuracy requested', epsabs
        Write (nout,99998) 'EPSREL', 'relative accuracy requested', epsrel
        Write (nout,99998) 'C     ', 'weight function parameter', c
      End If

      If (ifail>=0 .And. ifail<=3) Then
        Write (nout,*)
        Write (nout,99997) 'RESULT', 'approximation to the integral', result
        Write (nout,99998) 'ABSERR', 'estimate of the absolute error', abserr
        Write (nout,99996) 'IW(1) ', 'number of subintervals used', iw(1)
      End If

99999 Format (1X,A6,' - ',A32,' = ',F10.4)
99998 Format (1X,A6,' - ',A32,' = ',E9.2)
99997 Format (1X,A6,' - ',A32,' = ',F9.2)
99996 Format (1X,A6,' - ',A32,' = ',I4)
    End Program d01aqfe


d01arfe.f90

!   D01ARF Example Program Text
!   Mark 26 Release. NAG Copyright 2016.

    Module d01arfe_mod

!     D01ARF Example Program Module:
!            Parameters and User-defined Routines

!     .. Use Statements ..
      Use nag_library, Only: nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Accessibility Statements ..
      Private
      Public                           :: f1, f2
!     .. Parameters ..
      Integer, Parameter, Public       :: maxrul = 0, nout = 6
    Contains
      Function f1(x)

!       .. Function Return Value ..
        Real (Kind=nag_wp)             :: f1
!       .. Scalar Arguments ..
        Real (Kind=nag_wp), Intent (In) :: x
!       .. Executable Statements ..
        f1 = 4.0E0_nag_wp/(1.0E0_nag_wp+x*x)

        Return

      End Function f1
      Function f2(x)

!       .. Function Return Value ..
        Real (Kind=nag_wp)             :: f2
!       .. Scalar Arguments ..
        Real (Kind=nag_wp), Intent (In) :: x
!       .. Executable Statements ..
        f2 = x**0.125E0_nag_wp

        Return

      End Function f2
    End Module d01arfe_mod
    Program d01arfe

!     D01ARF Example Main Program

!     .. Use Statements ..
      Use nag_library, Only: d01arf, nag_wp
      Use d01arfe_mod, Only: f1, f2, maxrul, nout
!     .. Implicit None Statement ..
      Implicit None
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: a, absacc, acc, ans, b, relacc
      Integer                          :: ifail, iparm, n
!     .. Local Arrays ..
      Real (Kind=nag_wp)               :: alpha(390)
!     .. Executable Statements ..
      Write (nout,*) 'D01ARF Example Program Results'

      relacc = 0.0E0_nag_wp
      absacc = 1.0E-5_nag_wp

!     Definite integral of F1(x) - no expansion

      iparm = 0
      a = 0.0E0_nag_wp
      b = 1.0E0_nag_wp

      Write (nout,*)
      Write (nout,*) 'Definite integral of 4/(1+x*x) over (0,1)'

      ifail = -1
      Call d01arf(a,b,f1,relacc,absacc,maxrul,iparm,acc,ans,n,alpha,ifail)

      Select Case (ifail)
      Case (:-1)
        Go To 100
      Case (0,1)
        Write (nout,99999) 'Estimated value of the integral =', ans
        Write (nout,99998) 'Estimated absolute error =', acc
        Write (nout,99997) 'Number of points used =', n
      End Select

!     Definite integral of F2(x) - with expansion

      iparm = 1
      a = 1.0E0_nag_wp
      b = 2.0E0_nag_wp

      Write (nout,*)
      Write (nout,*) 'Definite integral of x**(1/8) over (1,2)'

      ifail = -1
      Call d01arf(a,b,f2,relacc,absacc,maxrul,iparm,acc,ans,n,alpha,ifail)

      Select Case (ifail)
      Case (:-1)
        Go To 100
      Case (0,1)
        Write (nout,99999) 'Estimated value of the integral =', ans
        Write (nout,99998) 'Estimated absolute error =', acc
        Write (nout,99997) 'Number of points used =', n
      End Select

!     Indefinite integral of F2(x)

      iparm = 2
      a = 1.2E0_nag_wp
      b = 1.8E0_nag_wp

      Write (nout,*)
      Write (nout,*) 'Indefinite integral of x**(1/8) over (1.2,1.8)'

      ifail = 0
      Call d01arf(a,b,f2,relacc,absacc,maxrul,iparm,acc,ans,n,alpha,ifail)

      Write (nout,99999) 'Estimated value of the integral =', ans

100   Continue

99999 Format (1X,A,F9.5)
99998 Format (1X,A,E10.2)
99997 Format (1X,A,I4)
    End Program d01arfe


d01asfe.f90

!   D01ASF Example Program Text
!   Mark 26 Release. NAG Copyright 2016.

    Module d01asfe_mod

!     D01ASF Example Program Module:
!            Parameters and User-defined Routines

!     .. Use Statements ..
      Use nag_library, Only: nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Accessibility Statements ..
      Private
      Public                           :: g
!     .. Parameters ..
      Integer, Parameter, Public       :: limlst = 50, lw = 800, nout = 6
      Integer, Parameter, Public       :: liw = lw/2
    Contains
      Function g(x)

!       .. Function Return Value ..
        Real (Kind=nag_wp)             :: g
!       .. Scalar Arguments ..
        Real (Kind=nag_wp), Intent (In) :: x
!       .. Intrinsic Procedures ..
        Intrinsic                      :: sqrt
!       .. Executable Statements ..
        If (x>0.0E0_nag_wp) Then
          g = 1.0E0_nag_wp/sqrt(x)
        Else
          g = 0.0E0_nag_wp
        End If

        Return

      End Function g
    End Module d01asfe_mod
    Program d01asfe

!     D01ASF Example Main Program

!     .. Use Statements ..
      Use nag_library, Only: d01asf, nag_wp, x01aaf
      Use d01asfe_mod, Only: g, limlst, liw, lw, nout
!     .. Implicit None Statement ..
      Implicit None
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: a, abserr, epsabs, omega, result
      Integer                          :: ifail, key, lst
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: erlst(:), rslst(:), w(:)
      Integer, Allocatable             :: ierlst(:), iw(:)
!     .. Executable Statements ..
      Write (nout,*) 'D01ASF Example Program Results'

      Allocate (erlst(limlst),rslst(limlst),w(lw),ierlst(limlst),iw(liw))

      epsabs = 1.0E-03_nag_wp
      a = 0.0E0_nag_wp
      omega = 0.5E0_nag_wp*x01aaf(omega)
      key = 1

      ifail = -1
      Call d01asf(g,a,omega,key,epsabs,result,abserr,limlst,lst,erlst,rslst,   &
        ierlst,w,lw,iw,liw,ifail)

      If (ifail>=0) Then
        Write (nout,*)
        Write (nout,99999) 'A      - lower limit of integration = ', a
        Write (nout,*) 'B      - upper limit of integration =  infinity'
        Write (nout,99998) 'EPSABS - absolute accuracy requested = ', epsabs

        If (ifail/=6 .And. ifail/=10) Then
          Write (nout,*)
          Write (nout,99997) 'RESULT - approximation to the integral = ',      &
            result
          Write (nout,99998) 'ABSERR - estimate of the absolute error = ',     &
            abserr
          Write (nout,99996) 'LST    - number of intervals used = ', lst
          Write (nout,99996)                                                   &
            'IW(1)  - max. no. of subintervals used in any one interval = ',   &
            iw(1)
        End If

      End If

99999 Format (1X,A,F10.4)
99998 Format (1X,A,E9.2)
99997 Format (1X,A,F9.5)
99996 Format (1X,A,I4)
    End Program d01asfe


d01atfe.f90

!   D01ATF Example Program Text
!   Mark 26 Release. NAG Copyright 2016.

    Module d01atfe_mod

!     D01ATF Example Program Module:
!            Parameters and User-defined Routines

!     .. Use Statements ..
      Use nag_library, Only: nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Accessibility Statements ..
      Private
      Public                           :: f
!     .. Parameters ..
      Integer, Parameter, Public       :: lw = 800, nout = 6
      Integer, Parameter, Public       :: liw = lw/4
!     .. Local Scalars ..
      Real (Kind=nag_wp), Public, Save :: pi
    Contains
      Subroutine f(x,fv,n)

!       .. Scalar Arguments ..
        Integer, Intent (In)           :: n
!       .. Array Arguments ..
        Real (Kind=nag_wp), Intent (Out) :: fv(n)
        Real (Kind=nag_wp), Intent (In) :: x(n)
!       .. Intrinsic Procedures ..
        Intrinsic                      :: sin, sqrt
!       .. Executable Statements ..
        fv(1:n) = x(1:n)*sin(30.0E0_nag_wp*x(1:n))/sqrt(1.0E0_nag_wp-x(1:n)**2 &
          /(4.0E0_nag_wp*pi**2))

        Return

      End Subroutine f
    End Module d01atfe_mod
    Program d01atfe

!     D01ATF Example Main Program

!     .. Use Statements ..
      Use nag_library, Only: d01atf, nag_wp, x01aaf
      Use d01atfe_mod, Only: f, liw, lw, nout, pi
!     .. Implicit None Statement ..
      Implicit None
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: a, abserr, b, epsabs, epsrel, result
      Integer                          :: ifail
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: w(:)
      Integer, Allocatable             :: iw(:)
!     .. Executable Statements ..
      Write (nout,*) 'D01ATF Example Program Results'

      Allocate (w(lw),iw(liw))

      pi = x01aaf(pi)
      epsabs = 0.0_nag_wp
      epsrel = 1.0E-04_nag_wp
      a = 0.0_nag_wp
      b = 2.0_nag_wp*pi

      ifail = -1
      Call d01atf(f,a,b,epsabs,epsrel,result,abserr,w,lw,iw,liw,ifail)

      If (ifail>=0) Then
        Write (nout,*)
        Write (nout,99999) 'A     ', 'lower limit of integration', a
        Write (nout,99999) 'B     ', 'upper limit of integration', b
        Write (nout,99998) 'EPSABS', 'absolute accuracy requested', epsabs
        Write (nout,99998) 'EPSREL', 'relative accuracy requested', epsrel
      End If
      If (ifail>=0 .And. ifail<=5) Then
        Write (nout,*)
        Write (nout,99997) 'RESULT', 'approximation to the integral', result
        Write (nout,99998) 'ABSERR', 'estimate of the absolute error', abserr
        Write (nout,99996) 'IW(1) ', 'number of subintervals used', iw(1)
      End If

99999 Format (1X,A6,' - ',A30,' = ',F10.4)
99998 Format (1X,A6,' - ',A30,' = ',E9.2)
99997 Format (1X,A6,' - ',A30,' = ',F9.5)
99996 Format (1X,A6,' - ',A30,' = ',I4)
    End Program d01atfe


d01aufe.f90

!   D01AUF Example Program Text
!   Mark 26 Release. NAG Copyright 2016.

    Module d01aufe_mod

!     D01AUF Example Program Module:
!            Parameters and User-defined Routines

!     .. Use Statements ..
      Use nag_library, Only: nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Accessibility Statements ..
      Private
      Public                           :: f
!     .. Parameters ..
      Integer, Parameter, Public       :: lw = 800, nout = 6
      Integer, Parameter, Public       :: liw = lw/4
    Contains
      Subroutine f(x,fv,n)

!       .. Scalar Arguments ..
        Integer, Intent (In)           :: n
!       .. Array Arguments ..
        Real (Kind=nag_wp), Intent (Out) :: fv(n)
        Real (Kind=nag_wp), Intent (In) :: x(n)
!       .. Intrinsic Procedures ..
        Intrinsic                      :: cos, sin
!       .. Executable Statements ..
        fv(1:n) = x(1:n)*(sin(30.0E0_nag_wp*x(1:n)))*cos(x(1:n))

        Return

      End Subroutine f
    End Module d01aufe_mod
    Program d01aufe

!     D01AUF Example Main Program

!     .. Use Statements ..
      Use nag_library, Only: d01auf, nag_wp, x01aaf
      Use d01aufe_mod, Only: f, liw, lw, nout
!     .. Implicit None Statement ..
      Implicit None
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: a, abserr, b, epsabs, epsrel, pi,    &
                                          result
      Integer                          :: ifail, key
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: w(:)
      Integer, Allocatable             :: iw(:)
!     .. Executable Statements ..
      Write (nout,*) 'D01AUF Example Program Results'

      Allocate (w(lw),iw(liw))

      pi = x01aaf(pi)
      epsabs = 0.0E0_nag_wp
      epsrel = 1.0E-03_nag_wp
      a = 0.0E0_nag_wp
      b = 2.0E0_nag_wp*pi
      key = 6

      ifail = -1
      Call d01auf(f,a,b,key,epsabs,epsrel,result,abserr,w,lw,iw,liw,ifail)

      If (ifail>=0) Then
        Write (nout,*)
        Write (nout,99999) 'A     ', 'lower limit of integration', a
        Write (nout,99999) 'B     ', 'upper limit of integration', b
        Write (nout,99998) 'EPSABS', 'absolute accuracy requested', epsabs
        Write (nout,99998) 'EPSREL', 'relative accuracy requested', epsrel
      End If
      If (ifail>=0 .And. ifail<=3) Then
        Write (nout,*)
        Write (nout,99997) 'RESULT', 'approximation to the integral', result
        Write (nout,99998) 'ABSERR', 'estimate of the absolute error', abserr
        Write (nout,99996) 'IW(1) ', 'number of subintervals used', iw(1)
      End If

99999 Format (1X,A6,' - ',A30,' = ',F10.4)
99998 Format (1X,A6,' - ',A30,' = ',E9.2)
99997 Format (1X,A6,' - ',A30,' = ',F9.5)
99996 Format (1X,A6,' - ',A30,' = ',I4)
    End Program d01aufe


d01bcfe.f90

    Program d01bcfe

!     D01BCF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: d01bcf, nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: n = 7, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: a, b, c, d
      Integer                          :: ifail, itype, j
!     .. Local Arrays ..
      Real (Kind=nag_wp)               :: abscis(n), weight(n)
!     .. Executable Statements ..
      Write (nout,*) 'D01BCF Example Program Results'

      a = 0.0E0_nag_wp
      b = 1.0E0_nag_wp
      c = 0.0E0_nag_wp
      d = 0.0E0_nag_wp
      itype = -3

      ifail = 0
      Call d01bcf(itype,a,b,c,d,n,weight,abscis,ifail)

      Write (nout,*)
      Write (nout,99999) 'Laguerre formula,', n, ' points'
      Write (nout,*)
      Write (nout,*) '      Abscissae             Weights'
      Write (nout,*)
      Write (nout,99998)(abscis(j),weight(j),j=1,n)

99999 Format (1X,A,I3,A)
99998 Format (1X,E15.5,5X,E15.5)
    End Program d01bcfe


d01bdfe.f90

!   D01BDF Example Program Text
!   Mark 26 Release. NAG Copyright 2016.

    Module d01bdfe_mod

!     D01BDF Example Program Module:
!            Parameters and User-defined Routines

!     .. Use Statements ..
      Use nag_library, Only: nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Accessibility Statements ..
      Private
      Public                           :: f
!     .. Parameters ..
      Integer, Parameter, Public       :: nout = 6
    Contains
      Function f(x)

!       .. Use Statements ..
        Use nag_library, Only: x01aaf
!       .. Function Return Value ..
        Real (Kind=nag_wp)             :: f
!       .. Scalar Arguments ..
        Real (Kind=nag_wp), Intent (In) :: x
!       .. Intrinsic Procedures ..
        Intrinsic                      :: sin
!       .. Executable Statements ..
        f = (x**2)*sin(10.0E0_nag_wp*x01aaf(f)*x)

        Return

      End Function f
    End Module d01bdfe_mod
    Program d01bdfe

!     D01BDF Example Main Program

!     .. Use Statements ..
      Use nag_library, Only: d01bdf, nag_wp
      Use d01bdfe_mod, Only: f, nout
!     .. Implicit None Statement ..
      Implicit None
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: a, abserr, b, epsabs, epsrel, result
!     .. Intrinsic Procedures ..
      Intrinsic                        :: abs, max
!     .. Executable Statements ..
      Write (nout,*) 'D01BDF Example Program Results'

      epsabs = 0.0E0_nag_wp
      epsrel = 1.0E-04_nag_wp
      a = 0.0E0_nag_wp
      b = 1.0E0_nag_wp

      Call d01bdf(f,a,b,epsabs,epsrel,result,abserr)

      Write (nout,*)
      Write (nout,99999) 'A      - lower limit of integration = ', a
      Write (nout,99999) 'B      - upper limit of integration = ', b
      Write (nout,99998) 'EPSABS - absolute accuracy requested = ', epsabs
      Write (nout,99998) 'EPSREL - relative accuracy requested = ', epsrel
      Write (nout,*)
      Write (nout,99997) 'RESULT - approximation to the integral = ', result
      Write (nout,99998) 'ABSERR - estimate to the absolute error = ', abserr
      Write (nout,*)

      If (abserr>max(epsabs,epsrel*abs(result))) Then
        Write (nout,*)                                                         &
          'Warning - requested accuracy may not have been achieved'
      End If

99999 Format (1X,A,F10.4)
99998 Format (1X,A,E9.2)
99997 Format (1X,A,F9.5)
    End Program d01bdfe


d01dafe.f90

!   D01DAF Example Program Text
!   Mark 26 Release. NAG Copyright 2016.

    Module d01dafe_mod

!     D01DAF Example Program Module:
!            Parameters and User-defined Routines

!     .. Use Statements ..
      Use nag_library, Only: nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Accessibility Statements ..
      Private
      Public                           :: fa, fb, phi1, phi2a, phi2b
!     .. Parameters ..
      Integer, Parameter, Public       :: nout = 6
    Contains
      Function phi1(y)

!       .. Function Return Value ..
        Real (Kind=nag_wp)             :: phi1
!       .. Scalar Arguments ..
        Real (Kind=nag_wp), Intent (In) :: y
!       .. Executable Statements ..
        phi1 = 0.0E0_nag_wp

        Return

      End Function phi1
      Function phi2a(y)

!       .. Function Return Value ..
        Real (Kind=nag_wp)             :: phi2a
!       .. Scalar Arguments ..
        Real (Kind=nag_wp), Intent (In) :: y
!       .. Intrinsic Procedures ..
        Intrinsic                      :: sqrt
!       .. Executable Statements ..
        phi2a = sqrt(1.0E0_nag_wp-y*y)

        Return

      End Function phi2a
      Function fa(x,y)

!       .. Function Return Value ..
        Real (Kind=nag_wp)             :: fa
!       .. Scalar Arguments ..
        Real (Kind=nag_wp), Intent (In) :: x, y
!       .. Executable Statements ..
        fa = x + y

        Return

      End Function fa
      Function phi2b(y)

!       .. Use Statements ..
        Use nag_library, Only: x01aaf
!       .. Function Return Value ..
        Real (Kind=nag_wp)             :: phi2b
!       .. Scalar Arguments ..
        Real (Kind=nag_wp), Intent (In) :: y
!       .. Executable Statements ..
        phi2b = 0.5E0_nag_wp*x01aaf(y)

        Return

      End Function phi2b
      Function fb(x,y)

!       .. Function Return Value ..
        Real (Kind=nag_wp)             :: fb
!       .. Scalar Arguments ..
        Real (Kind=nag_wp), Intent (In) :: x, y
!       .. Intrinsic Procedures ..
        Intrinsic                      :: cos, sin
!       .. Executable Statements ..
        fb = y*y*(cos(x)+sin(x))

        Return

      End Function fb
    End Module d01dafe_mod
    Program d01dafe

!     D01DAF Example Main Program

!     .. Use Statements ..
      Use nag_library, Only: d01daf, nag_wp
      Use d01dafe_mod, Only: fa, fb, nout, phi1, phi2a, phi2b
!     .. Implicit None Statement ..
      Implicit None
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: absacc, ans, ya, yb
      Integer                          :: ifail, npts
!     .. Executable Statements ..
      Write (nout,*) 'D01DAF Example Program Results'

      ya = 0.0E0_nag_wp
      yb = 1.0E0_nag_wp
      absacc = 1.0E-6_nag_wp

      ifail = 0
      Call d01daf(ya,yb,phi1,phi2a,fa,absacc,ans,npts,ifail)

      Write (nout,*)
      Write (nout,*) 'First formulation'
      Write (nout,99999) 'Integral =', ans
      Write (nout,99998) 'Number of function evaluations =', npts

      ifail = 0
      Call d01daf(ya,yb,phi1,phi2b,fb,absacc,ans,npts,ifail)

      Write (nout,*)
      Write (nout,*) 'Second formulation'
      Write (nout,99999) 'Integral =', ans
      Write (nout,99998) 'Number of function evaluations =', npts

99999 Format (1X,A,F9.4)
99998 Format (1X,A,I5)
    End Program d01dafe


d01eafe.f90

!   D01EAF Example Program Text
!   Mark 26 Release. NAG Copyright 2016.

    Module d01eafe_mod

!     D01EAF Example Program Module:
!            Parameters and User-defined Routines

!     .. Use Statements ..
      Use nag_library, Only: nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Accessibility Statements ..
      Private
      Public                           :: funsub
!     .. Parameters ..
      Integer, Parameter               :: mulcls = 1
      Integer, Parameter, Public       :: ndim = 4, nfun = 10, nout = 6
      Integer, Parameter               :: ircls = 2**ndim + 2*ndim*(ndim+1) +  &
                                          1
      Integer, Parameter, Public       :: lenwrk = (ndim+nfun+2)*(10+mulcls)
      Integer, Parameter, Public       :: mxcls = mulcls*ircls
    Contains
      Subroutine funsub(ndim,z,nfun,f)

!       .. Scalar Arguments ..
        Integer, Intent (In)           :: ndim, nfun
!       .. Array Arguments ..
        Real (Kind=nag_wp), Intent (Out) :: f(nfun)
        Real (Kind=nag_wp), Intent (In) :: z(ndim)
!       .. Local Scalars ..
        Real (Kind=nag_wp)             :: sum
        Integer                        :: i, n
!       .. Intrinsic Procedures ..
        Intrinsic                      :: log, real, sin
!       .. Executable Statements ..
        sum = 0.0E0_nag_wp

        Do n = 1, ndim
          sum = sum + real(n,kind=nag_wp)*z(n)
        End Do

        Do i = 1, nfun
          f(i) = log(sum)*sin(real(i,kind=nag_wp)+sum)
        End Do

        Return

      End Subroutine funsub
    End Module d01eafe_mod
    Program d01eafe

!     D01EAF Example Main Program

!     .. Use Statements ..
      Use nag_library, Only: d01eaf, nag_wp
      Use d01eafe_mod, Only: funsub, lenwrk, mxcls, ndim, nfun, nout
!     .. Implicit None Statement ..
      Implicit None
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: absreq, relreq
      Integer                          :: i, ifail, maxcls, mincls, mulfac
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: a(:), absest(:), b(:), finest(:),    &
                                          wrkstr(:)
!     .. Executable Statements ..
      Write (nout,*) 'D01EAF Example Program Results'
      Flush (nout)

      Allocate (a(ndim),absest(nfun),b(ndim),finest(nfun),wrkstr(lenwrk))

      a(1:ndim) = 0.0_nag_wp
      b(1:ndim) = 1.0_nag_wp
      mincls = 0
      maxcls = mxcls
      absreq = 0.0_nag_wp
      relreq = 1.0E-3_nag_wp

      If (ndim<=10) Then
        mulfac = 2**ndim
      Else
        mulfac = 2*ndim**3
      End If

loop: Do

        ifail = -1
        Call d01eaf(ndim,a,b,mincls,maxcls,nfun,funsub,absreq,relreq,lenwrk,   &
          wrkstr,finest,absest,ifail)

        Select Case (ifail)
        Case (1,3)
          Write (nout,*)
          Write (nout,99999) mincls
          Write (nout,99998)

          Do i = 1, nfun
            Write (nout,99997) i, finest(i), absest(i)
          End Do

          Write (nout,*)
          Flush (nout)
          mincls = -1
          maxcls = maxcls*mulfac
        Case (0)
          Write (nout,*)
          Write (nout,99996) mincls
          Write (nout,99998)

          Do i = 1, nfun
            Write (nout,99997) i, finest(i), absest(i)
          End Do

          Exit loop
        Case Default
          Exit loop
        End Select

      End Do loop

99999 Format (1X,'Results so far (',I7,' FUNSUB calls in last call of D01EAF)' &
        )
99998 Format (/,1X,'   I       Integral   Estimated error')
99997 Format (1X,I4,2F14.4)
99996 Format (1X,'Final Results (',I7,' FUNSUB calls in last call of D01EAF)')
    End Program d01eafe


d01esfe.f90

!   D01ESF Example Program Text
!   Mark 26 Release. NAG Copyright 2016.

    Module d01esfe_mod

!     D01ESF Example Program Module:
!            User-defined Routines

!     .. Use Statements ..
      Use nag_library, Only: nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Accessibility Statements ..
      Private
      Public                           :: f
    Contains
      Subroutine f(ni,ndim,nx,xtr,nntr,icolzp,irowix,xs,qs,fm,iflag,iuser,     &
        ruser)

!       .. Use Statements ..
        Use nag_library, Only: x06adf
!       .. Scalar Arguments ..
        Real (Kind=nag_wp), Intent (In) :: xtr
        Integer, Intent (Inout)        :: iflag
        Integer, Intent (In)           :: ndim, ni, nntr, nx
!       .. Array Arguments ..
        Real (Kind=nag_wp), Intent (Out) :: fm(ni,nx)
        Real (Kind=nag_wp), Intent (Inout) :: ruser(*)
        Real (Kind=nag_wp), Intent (In) :: xs(nntr)
        Integer, Intent (In)           :: icolzp(nx+1), irowix(nntr), qs(nntr)
        Integer, Intent (Inout)        :: iuser(*)
!       .. Local Scalars ..
        Real (Kind=nag_wp)             :: s_ntr, s_tr
        Integer                        :: i, j, logs_hi, logs_lo, s_hi, s_lo,  &
                                          tid
!       .. Intrinsic Procedures ..
        Intrinsic                      :: log, real, sin, sum
!       .. Executable Statements ..

!       For each evaluation point x_i, i = 1, ..., nx, return in fm the
!       computed values of the ni integrands f_j, j = 1, ..., ni defined by

!         fm(j,i) = f_j(x_i)
!                                                         ndim
!                 = sin(j + S(i))*log(S(i)), where S(i) =  Sum  k*x_i(k).
!                                                          k=1

!       Split the S expression into two components, one involving only the
!       'trivial' value xtr:

!                ndim             ndim
!         S(i) =  Sum  (k*xtr)  +  Sum  (k*(x_i(k)-xtr))
!                 k=1              k=1

!                      ndim*(ndim+1)   ndim
!              = xtr * ------------- +  Sum  (k*(x_i(k)-xtr))
!                           2           k=1

!             := s_tr                + s_ntr(i)

!       By definition the summands in the s_ntr(i) term on the right-hand side
!       are zero for those k outside the range of indices defined in irowix.

!       As a demonstration of safely operating with the user arrays iuser and
!       ruser when running in parallel, 'partition' these based on the current
!       thread number. Store some of the s_tr and s_ntr computations in these
!       array sections.

!       The thread number, converted to 1-based numbering.
        tid = x06adf() + 1

        s_lo = iuser(tid)
        s_hi = s_lo + nx - 1
        logs_lo = s_hi + 1
        logs_hi = logs_lo + nx - 1

        If (iflag==0) Then
!         First call: nx=1, no non-trivial dimensions.
!         The constant s_tr can be reused by all subsequent calculations.
          s_tr = 0.5E0_nag_wp*xtr*real(ndim*(ndim+1),kind=nag_wp)
          ruser(1) = s_tr
          ruser(s_lo) = s_tr
          ruser(logs_lo) = log(s_tr)
        Else
!         Calculate S(i) = s_tr + s_ntr(i).
          s_tr = ruser(1)
          Do i = 1, nx
            s_ntr = sum(real(irowix(icolzp(i):icolzp(i+1)-                     &
              1),kind=nag_wp)*(xs(icolzp(i):icolzp(i+1)-1)-xtr))
            ruser(s_lo+i-1) = s_ntr + s_tr
            ruser(logs_lo+i-1) = log(s_ntr+s_tr)
          End Do
        End If

!       Finally we obtain fm(j,:) = sin(j+S(:))*log(S(:))
        Do j = 1, ni
          fm(j,:) = sin(real(j,kind=nag_wp)+ruser(s_lo:s_hi))*                 &
            ruser(logs_lo:logs_hi)
        End Do

        Return
      End Subroutine f
    End Module d01esfe_mod
    Program d01esfe

!     .. Use Statements ..
      Use nag_library, Only: d01esf, d01zkf, d01zlf, nag_wp, x06acf
      Use d01esfe_mod, Only: f
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: rvalue
      Integer                          :: ifail, j, liuser, lruser, maxnx,     &
                                          ndim, ni, optype, smpthd
      Character (16)                   :: cvalue
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: dinest(:), errest(:), opts(:),       &
                                          ruser(:)
      Integer, Allocatable             :: iopts(:), iuser(:), ivalid(:),       &
                                          maxdlv(:)
!     .. Executable Statements ..
      Write (nout,*) 'D01ESF Example Program Results'
      Write (nout,*)
      ni = 10
      ndim = 4

      Allocate (iopts(100),opts(100),ivalid(ni),dinest(ni),errest(ni),         &
        maxdlv(ndim))

!     Initialize option arrays.
      ifail = 0
      Call d01zkf('Initialize = D01ESF',iopts,100,opts,100,ifail)

!     Set any required options.
      Call d01zkf('Absolute Tolerance = 0.0',iopts,100,opts,100,ifail)
      Call d01zkf('Relative Tolerance = 1.0e-3',iopts,100,opts,100,ifail)
      Call d01zkf('Maximum Level = 6',iopts,100,opts,100,ifail)
      Call d01zkf('Index Level = 5',iopts,100,opts,100,ifail)

!     Set any required maximum dimension levels.
      maxdlv(:) = 0

!     As a demonstration of safely operating with the user arrays iuser and
!     ruser when running in parallel, we will 'partition' these in the user-
!     supplied function f based on the current thread number.
!     The size of these arrays is a function of Maximum Nx and the maximum
!     allowed number of OpenMP threads.

      ifail = 0
      Call d01zlf('Maximum Nx',maxnx,rvalue,cvalue,optype,iopts,opts,ifail)

      smpthd = x06acf()

      lruser = 1 + 2*maxnx*smpthd
      liuser = smpthd
      Allocate (iuser(liuser),ruser(lruser))

!     iuser stores the partition indices for ruser:
      iuser(1) = 2
      Do j = 2, smpthd
        iuser(j) = iuser(j-1) + 2*maxnx
      End Do

!     Approximate the integrals.
      ifail = -1
      Call d01esf(ni,ndim,f,maxdlv,dinest,errest,ivalid,iopts,opts,iuser,      &
        ruser,ifail)
      Select Case (ifail)
      Case (0,1,2,-1)
!       0: The result returned satisfies the requested accuracy requirements.
!       1, 2: The result returned is inaccurate for at least one integral.
!       -1: Exit was requested by setting iflag negative in f.
!           A result will be returned if at least one call to f was
!           successful.
        Write (nout,99999)
        Do j = 1, ni
          Write (nout,99998) j, dinest(j), errest(j), ivalid(j)
        End Do
      Case Default
!       If internal memory allocation failed consider reducing the options
!       'Maximum Nx' and 'Index Level', or run with fewer threads.
        Write (nout,99997) ifail
      End Select

99999 Format (1X,'Integral # | Estimated value | Error estimate | ',           &
        'Final state of integral')
99998 Format (1X,I11,'|',Es17.5,'|',Es16.5,'|',I8)
99997 Format (1X,'D01ESF exited with IFAIL = ',I8)
    End Program d01esfe


d01fbfe.f90

!   D01FBF Example Program Text
!   Mark 26 Release. NAG Copyright 2016.

    Module d01fbfe_mod

!     D01FBF Example Program Module:
!            Parameters and User-defined Routines

!     .. Use Statements ..
      Use nag_library, Only: nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Accessibility Statements ..
      Private
      Public                           :: fun
!     .. Parameters ..
      Integer, Parameter, Public       :: ndim = 4, nout = 6
    Contains
      Function fun(ndim,x)

!       .. Function Return Value ..
        Real (Kind=nag_wp)             :: fun
!       .. Scalar Arguments ..
        Integer, Intent (In)           :: ndim
!       .. Array Arguments ..
        Real (Kind=nag_wp), Intent (In) :: x(ndim)
!       .. Intrinsic Procedures ..
        Intrinsic                      :: exp
!       .. Executable Statements ..
        fun = (x(1)*x(2)*x(3))**6/(x(4)+2.0E0_nag_wp)**8*                      &
          exp(-2.0E0_nag_wp*x(2)-0.5E0_nag_wp*x(3)*x(3))

        Return

      End Function fun
    End Module d01fbfe_mod
    Program d01fbfe

!     D01FBF Example Main Program

!     .. Use Statements ..
      Use nag_library, Only: d01fbf, d01tbf, nag_wp
      Use d01fbfe_mod, Only: fun, ndim, nout
!     .. Implicit None Statement ..
      Implicit None
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: a, ans, b
      Integer                          :: i, ifail, j, lwa
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: abscis(:), weight(:)
      Integer                          :: nptvec(ndim)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: sum
!     .. Executable Statements ..
      Write (nout,*) 'D01FBF Example Program Results'

      nptvec(1:ndim) = (/4,4,4,4/)
      lwa = sum(nptvec(1:ndim))
      Allocate (abscis(lwa),weight(lwa))

      j = 1

      Do i = 1, 4

        ifail = 0
        Select Case (i)
        Case (1)
          a = 1.0E0_nag_wp
          b = 2.0E0_nag_wp
          Call d01tbf(0,a,b,nptvec(i),weight(j),abscis(j),ifail)
        Case (2)
          a = 0.0E0_nag_wp
          b = 2.0E0_nag_wp
          Call d01tbf(-3,a,b,nptvec(i),weight(j),abscis(j),ifail)
        Case (3)
          a = 0.0E0_nag_wp
          b = 0.5E0_nag_wp
          Call d01tbf(-4,a,b,nptvec(i),weight(j),abscis(j),ifail)
        Case (4)
          a = 1.0E0_nag_wp
          b = 2.0E0_nag_wp
          Call d01tbf(-5,a,b,nptvec(i),weight(j),abscis(j),ifail)
        End Select

        j = j + nptvec(i)
      End Do

      ifail = 0
      ans = d01fbf(ndim,nptvec,lwa,weight,abscis,fun,ifail)

      Write (nout,*)
      Write (nout,99999) 'Answer = ', ans

99999 Format (1X,A,F10.5)
    End Program d01fbfe


d01fcfe.f90

!   D01FCF Example Program Text
!   Mark 26 Release. NAG Copyright 2016.

    Module d01fcfe_mod

!     D01FCF Example Program Module:
!            Parameters and User-defined Routines

!     .. Use Statements ..
      Use nag_library, Only: nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Accessibility Statements ..
      Private
      Public                           :: functn
!     .. Parameters ..
      Integer, Parameter, Public       :: ndim = 4, nout = 6
      Integer, Parameter, Public       :: maxpts = 1000*ndim
      Integer, Parameter, Public       :: lenwrk = (ndim+2)*(1+maxpts/(2**ndim &
                                          +2*ndim*ndim+2*ndim+1))
    Contains
      Function functn(ndim,z)

!       .. Function Return Value ..
        Real (Kind=nag_wp)             :: functn
!       .. Scalar Arguments ..
        Integer, Intent (In)           :: ndim
!       .. Array Arguments ..
        Real (Kind=nag_wp), Intent (In) :: z(ndim)
!       .. Intrinsic Procedures ..
        Intrinsic                      :: exp
!       .. Executable Statements ..
        functn = 4.0E0_nag_wp*z(1)*z(3)*z(3)*exp(2.0E0_nag_wp*z(1)*z(3))/      &
          (1.0E0_nag_wp+z(2)+z(4))**2

        Return

      End Function functn
    End Module d01fcfe_mod
    Program d01fcfe

!     D01FCF Example Main Program

!     .. Use Statements ..
      Use nag_library, Only: d01fcf, nag_wp
      Use d01fcfe_mod, Only: functn, lenwrk, maxpts, ndim, nout
!     .. Implicit None Statement ..
      Implicit None
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: acc, eps, finval
      Integer                          :: ifail, minpts
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: a(:), b(:), wrkstr(:)
!     .. Executable Statements ..
      Write (nout,*) 'D01FCF Example Program Results'

      Allocate (a(ndim),b(ndim),wrkstr(lenwrk))

      a(1:ndim) = 0.0E0_nag_wp
      b(1:ndim) = 1.0E0_nag_wp
      eps = 0.0001E0_nag_wp
      minpts = 0

      ifail = -1
      Call d01fcf(ndim,a,b,minpts,maxpts,functn,eps,acc,lenwrk,wrkstr,finval,  &
        ifail)

      Select Case (ifail)
      Case (0,2:)
        Write (nout,*)
        Write (nout,99999) 'Requested accuracy = ', eps
        Write (nout,99998) 'Estimated value    = ', finval
        Write (nout,99999) 'Estimated accuracy = ', acc
      End Select

99999 Format (1X,A,E12.2)
99998 Format (1X,A,F12.4)
    End Program d01fcfe


d01fdfe.f90

!   D01FDF Example Program Text
!   Mark 26 Release. NAG Copyright 2016.

    Module d01fdfe_mod

!     D01FDF Example Program Module:
!            Parameters and User-defined Routines

!     .. Use Statements ..
      Use nag_library, Only: nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Accessibility Statements ..
      Private
      Public                           :: f, region
!     .. Parameters ..
      Integer, Parameter, Public       :: nout = 6
    Contains
      Function f(ndim,x)

!       .. Function Return Value ..
        Real (Kind=nag_wp)             :: f
!       .. Scalar Arguments ..
        Integer, Intent (In)           :: ndim
!       .. Array Arguments ..
        Real (Kind=nag_wp), Intent (In) :: x(ndim)
!       .. Intrinsic Procedures ..
        Intrinsic                      :: abs, sqrt, sum
!       .. Executable Statements ..
        f = 1.0E0_nag_wp/sqrt(abs(2.25E0_nag_wp-sum(x(1:ndim)**2)))

        Return

      End Function f
      Subroutine region(ndim,x,j,c,d)

!       .. Scalar Arguments ..
        Real (Kind=nag_wp), Intent (Out) :: c, d
        Integer, Intent (In)           :: j, ndim
!       .. Array Arguments ..
        Real (Kind=nag_wp), Intent (In) :: x(ndim)
!       .. Intrinsic Procedures ..
        Intrinsic                      :: abs, sqrt, sum
!       .. Executable Statements ..
        If (j>1) Then
          d = sqrt(abs(2.25E0_nag_wp-sum(x(1:(j-1))**2)))
          c = -d
        Else
          c = -1.5E0_nag_wp
          d = 1.5E0_nag_wp
        End If

        Return

      End Subroutine region
    End Module d01fdfe_mod
    Program d01fdfe

!     D01FDF Example Main Program

!     .. Use Statements ..
      Use nag_library, Only: d01fdf, d01fdv, nag_wp
      Use d01fdfe_mod, Only: f, nout, region
!     .. Implicit None Statement ..
      Implicit None
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: r0, result, sigma, u
      Integer                          :: ifail, limit, ncalls, ndim
!     .. Executable Statements ..
      Write (nout,*) 'D01FDF Example Program Results'

      ndim = 3
      limit = 8000
      u = 1.5E0_nag_wp
      sigma = 1.5E0_nag_wp
      r0 = 0.9E0_nag_wp

      ifail = 0
      Call d01fdf(ndim,f,sigma,d01fdv,limit,r0,u,result,ncalls,ifail)

      Write (nout,*)
      Write (nout,*) 'Sphere-to-sphere transformation'
      Write (nout,*)
      Write (nout,99999) 'Estimated value of the integral = ', result
      Write (nout,99998) 'Number of integrand evaluations = ', ncalls
      Write (nout,*)
      Write (nout,*) 'Product region transformation'

      sigma = -1.0E0_nag_wp
      r0 = 0.8E0_nag_wp

      ifail = 0
      Call d01fdf(ndim,f,sigma,region,limit,r0,u,result,ncalls,ifail)

      Write (nout,*)
      Write (nout,99999) 'Estimated value of the integral = ', result
      Write (nout,99998) 'Number of integrand evaluations = ', ncalls

99999 Format (1X,A,F9.3)
99998 Format (1X,A,I5)
    End Program d01fdfe


d01gafe.f90

    Program d01gafe

!     D01GAF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: d01gaf, nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: ans, er
      Integer                          :: i, ifail, n
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: x(:), y(:)
!     .. Executable Statements ..
      Write (nout,*) 'D01GAF Example Program Results'

!     Skip heading in data file
      Read (nin,*)

      Read (nin,*) n
      Allocate (x(n),y(n))

      Read (nin,*)(x(i),y(i),i=1,n)

      ifail = -1
      Call d01gaf(x,y,n,ans,er,ifail)

      Select Case (ifail)
      Case (0)
        Write (nout,*)
        Write (nout,99999) 'Integral = ', ans, '     Estimated error = ', er
      Case (1)
        Write (nout,*)
        Write (nout,*) 'Less than 4 points supplied'
      Case (2)
        Write (nout,*)
        Write (nout,*) 'Points not in increasing or decreasing order'
      Case (3)
        Write (nout,*)
        Write (nout,*) 'Points not all distinct'
      End Select

99999 Format (1X,A,F7.4,A,F7.4)
    End Program d01gafe


d01gbfe.f90

!   D01GBF Example Program Text
!   Mark 26 Release. NAG Copyright 2016.

    Module d01gbfe_mod

!     D01GBF Example Program Module:
!            Parameters and User-defined Routines

!     .. Use Statements ..
      Use nag_library, Only: nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Accessibility Statements ..
      Private
      Public                           :: functn
!     .. Parameters ..
      Integer, Parameter, Public       :: lenwrk = 500, maxcls = 20000,        &
                                          ndim = 4, nout = 6
    Contains
      Function functn(ndim,x)

!       .. Function Return Value ..
        Real (Kind=nag_wp)             :: functn
!       .. Scalar Arguments ..
        Integer, Intent (In)           :: ndim
!       .. Array Arguments ..
        Real (Kind=nag_wp), Intent (In) :: x(ndim)
!       .. Intrinsic Procedures ..
        Intrinsic                      :: exp
!       .. Executable Statements ..
        functn = 4.0E0_nag_wp*x(1)*x(3)**2*exp(2.0E0_nag_wp*x(1)*x(3))/        &
          (1.0E0_nag_wp+x(2)+x(4))**2

        Return

      End Function functn
    End Module d01gbfe_mod
    Program d01gbfe

!     D01GBF Example Main Program

!     .. Use Statements ..
      Use nag_library, Only: d01gbf, nag_wp
      Use d01gbfe_mod, Only: functn, lenwrk, maxcls, ndim, nout
!     .. Implicit None Statement ..
      Implicit None
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: acc, eps, finest
      Integer                          :: ifail, mincls
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: a(:), b(:), wrkstr(:)
!     .. Executable Statements ..
      Write (nout,*) 'D01GBF Example Program Results'

      Allocate (a(ndim),b(ndim),wrkstr(lenwrk))

      a(1:ndim) = 0.0E0_nag_wp
      b(1:ndim) = 1.0E0_nag_wp
      eps = 0.01E0_nag_wp
      mincls = 1000

      ifail = -1
      Call d01gbf(ndim,a,b,mincls,maxcls,functn,eps,acc,lenwrk,wrkstr,finest,  &
        ifail)

      Select Case (ifail)
      Case (0,2)
        Write (nout,*)
        Write (nout,99998) 'Requested accuracy    = ', eps
        Write (nout,99997) 'Estimated value       = ', finest
        Write (nout,99998) 'Estimated accuracy    = ', acc
        Write (nout,99999) 'Number of evaluations = ', mincls
      End Select

99999 Format (1X,A,I5)
99998 Format (1X,A,E13.2)
99997 Format (1X,A,F13.5)
    End Program d01gbfe


d01gcfe.f90

!   D01GCF Example Program Text
!   Mark 26 Release. NAG Copyright 2016.

    Module d01gcfe_mod

!     D01GCF Example Program Module:
!            Parameters and User-defined Routines

!     .. Use Statements ..
      Use nag_library, Only: nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Accessibility Statements ..
      Private
      Public                           :: f, region
!     .. Parameters ..
      Integer, Parameter, Public       :: ndim = 4, nout = 6
    Contains
      Subroutine region(ndim,x,j,c,d)

!       .. Scalar Arguments ..
        Real (Kind=nag_wp), Intent (Out) :: c, d
        Integer, Intent (In)           :: j, ndim
!       .. Array Arguments ..
        Real (Kind=nag_wp), Intent (In) :: x(ndim)
!       .. Executable Statements ..
        c = 0.0E0_nag_wp
        d = 1.0E0_nag_wp

        Return

      End Subroutine region
      Function f(ndim,x)

!       .. Function Return Value ..
        Real (Kind=nag_wp)             :: f
!       .. Scalar Arguments ..
        Integer, Intent (In)           :: ndim
!       .. Array Arguments ..
        Real (Kind=nag_wp), Intent (In) :: x(ndim)
!       .. Intrinsic Procedures ..
        Intrinsic                      :: cos, real, sum
!       .. Executable Statements ..
        f = cos(0.5E0_nag_wp+2.0E0_nag_wp*sum(x(1:ndim))-real(ndim,kind=nag_wp &
          ))

        Return

      End Function f
    End Module d01gcfe_mod
    Program d01gcfe

!     D01GCF Example Main Program

!     .. Use Statements ..
      Use nag_library, Only: d01gcf, nag_wp
      Use d01gcfe_mod, Only: f, ndim, nout, region
!     .. Implicit None Statement ..
      Implicit None
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: err, res
      Integer                          :: ifail, itrans, npts, nrand
!     .. Local Arrays ..
      Real (Kind=nag_wp)               :: vk(ndim)
!     .. Executable Statements ..
      Write (nout,*) 'D01GCF Example Program Results'

      npts = 2
      itrans = 0
      nrand = 4

      ifail = 0
      Call d01gcf(ndim,f,region,npts,vk,nrand,itrans,res,err,ifail)

      Write (nout,*)
      Write (nout,99999) 'Result =', res, '  Standard error =', err

99999 Format (1X,A,F13.5,A,E10.2)
    End Program d01gcfe


d01gdfe.f90

!   D01GDF Example Program Text
!   Mark 26 Release. NAG Copyright 2016.

    Module d01gdfe_mod

!     D01GDF Example Program Module:
!            Parameters and User-defined Routines

!     .. Use Statements ..
      Use nag_library, Only: nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Accessibility Statements ..
      Private
      Public                           :: vecfun, vecreg
!     .. Parameters ..
      Integer, Parameter, Public       :: ndim = 4, nout = 6
    Contains
      Subroutine vecfun(ndim,x,fv,m)

!       .. Scalar Arguments ..
        Integer, Intent (In)           :: m, ndim
!       .. Array Arguments ..
        Real (Kind=nag_wp), Intent (Out) :: fv(m)
        Real (Kind=nag_wp), Intent (In) :: x(m,ndim)
!       .. Local Scalars ..
        Integer                        :: i
!       .. Intrinsic Procedures ..
        Intrinsic                      :: cos, real, sum
!       .. Executable Statements ..
        Do i = 1, m
          fv(i) = cos(0.5E0_nag_wp+2.0E0_nag_wp*sum(x(i,                       &
            1:ndim))-real(ndim,kind=nag_wp))
        End Do

        Return

      End Subroutine vecfun
      Subroutine vecreg(ndim,x,j,c,d,m)

!       .. Scalar Arguments ..
        Integer, Intent (In)           :: j, m, ndim
!       .. Array Arguments ..
        Real (Kind=nag_wp), Intent (Out) :: c(m), d(m)
        Real (Kind=nag_wp), Intent (In) :: x(m,ndim)
!       .. Executable Statements ..
        c(1:m) = 0.0E0_nag_wp
        d(1:m) = 1.0E0_nag_wp

        Return

      End Subroutine vecreg
    End Module d01gdfe_mod
    Program d01gdfe

!     D01GDF Example Main Program

!     .. Use Statements ..
      Use nag_library, Only: d01gdf, nag_wp
      Use d01gdfe_mod, Only: ndim, nout, vecfun, vecreg
!     .. Implicit None Statement ..
      Implicit None
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: err, res
      Integer                          :: ifail, itrans, npts, nrand
!     .. Local Arrays ..
      Real (Kind=nag_wp)               :: vk(ndim)
!     .. Executable Statements ..
      Write (nout,*) 'D01GDF Example Program Results'

      npts = 2
      itrans = 0
      nrand = 4

      ifail = 0
      Call d01gdf(ndim,vecfun,vecreg,npts,vk,nrand,itrans,res,err,ifail)

      Write (nout,*)
      Write (nout,99999) 'Result = ', res, ', standard error = ', err

99999 Format (1X,A,F13.5,A,E10.2)
    End Program d01gdfe


d01gyfe.f90

    Program d01gyfe

!     D01GYF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: d01gyf, nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: ndim = 4, nout = 6
!     .. Local Scalars ..
      Integer                          :: ifail, npts
!     .. Local Arrays ..
      Real (Kind=nag_wp)               :: vk(20)
!     .. Executable Statements ..
      Write (nout,*) 'D01GYF Example Program Results'

      npts = 631

      ifail = 0
      Call d01gyf(ndim,npts,vk,ifail)

      Write (nout,*)
      Write (nout,99999) 'NDIM =', ndim, ' NPTS =', npts
      Write (nout,*)
      Write (nout,99998) 'Coefficients =', vk(1:ndim)

99999 Format (1X,A,I3,A,I6)
99998 Format (1X,A,4F6.0)
    End Program d01gyfe


d01gzfe.f90

    Program d01gzfe

!     D01GZF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: d01gzf, nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: ndim = 4, nout = 6
!     .. Local Scalars ..
      Integer                          :: ifail, np1, np2
!     .. Local Arrays ..
      Real (Kind=nag_wp)               :: vk(ndim)
!     .. Executable Statements ..
      Write (nout,*) 'D01GZF Example Program Results'

      np1 = 89
      np2 = 11

      ifail = 0
      Call d01gzf(ndim,np1,np2,vk,ifail)

      Write (nout,*)
      Write (nout,99999) 'NDIM =', ndim, ' NP1 =', np1, ' NP2 =', np2
      Write (nout,*)
      Write (nout,99998) 'Coefficients =', vk(1:ndim)

99999 Format (1X,A,I3,A,I6,A,I6)
99998 Format (1X,A,4F6.0)
    End Program d01gzfe


d01jafe.f90

!   D01JAF Example Program Text
!   Mark 26 Release. NAG Copyright 2016.

    Module d01jafe_mod

!     D01JAF Example Program Module:
!            Parameters and User-defined Routines

!     .. Use Statements ..
      Use nag_library, Only: nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Accessibility Statements ..
      Private
      Public                           :: f
!     .. Parameters ..
      Integer, Parameter, Public       :: nout = 6
    Contains
      Function f(ndim,x)

!       .. Function Return Value ..
        Real (Kind=nag_wp)             :: f
!       .. Scalar Arguments ..
        Integer, Intent (In)           :: ndim
!       .. Array Arguments ..
        Real (Kind=nag_wp), Intent (In) :: x(ndim)
!       .. Local Scalars ..
        Real (Kind=nag_wp)             :: a, rho
!       .. Intrinsic Procedures ..
        Intrinsic                      :: sqrt
!       .. Executable Statements ..
        rho = x(1)
        a = (1.0E0_nag_wp-rho)*(1.0E0_nag_wp+rho)

        If (a/=0.0E0_nag_wp) Then
          f = 1.0E0_nag_wp/sqrt(a)
        Else
          f = 0.0E0_nag_wp
        End If

        Return

      End Function f
    End Module d01jafe_mod
    Program d01jafe

!     D01JAF Example Main Program

!     .. Use Statements ..
      Use nag_library, Only: d01jaf, nag_wp
      Use d01jafe_mod, Only: f, nout
!     .. Implicit None Statement ..
      Implicit None
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: epsa, epsr, esterr, radius, relest,  &
                                          result
      Integer                          :: icoord, ifail, method, ndim, nevals
!     .. Executable Statements ..
      Write (nout,*) 'D01JAF Example Program Results'

      radius = 1.0E0_nag_wp
      method = 0
      icoord = 1
      epsa = 0.0E0_nag_wp
      epsr = 0.5E-4_nag_wp

test: Do ndim = 2, 4, 2

        ifail = -1
        Call d01jaf(f,ndim,radius,epsa,epsr,method,icoord,result,esterr,       &
          nevals,ifail)

        Select Case (ifail)
        Case (:-1)
          Exit test
        Case (0:3)
          relest = esterr/result
          Write (nout,*)
          Write (nout,99999) 'Dimension of the sphere       =', ndim
          Write (nout,99998) 'Requested relative tolerance  =', epsr
          Write (nout,99997) 'Approximation to the integral =', result
          Write (nout,99999) 'No. of function evaluations   =', nevals
          Write (nout,99998) 'Estimated relative error      =', relest
        End Select

      End Do test

99999 Format (1X,A,I5)
99998 Format (1X,A,E9.2)
99997 Format (1X,A,F9.5)
    End Program d01jafe


d01pafe.f90

!   D01PAF Example Program Text
!   Mark 26 Release. NAG Copyright 2016.

    Module d01pafe_mod

!     D01PAF Example Program Module:
!            Parameters and User-defined Routines

!     .. Use Statements ..
      Use nag_library, Only: nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Accessibility Statements ..
      Private
      Public                           :: functn
!     .. Parameters ..
      Integer, Parameter, Public       :: mxord = 5, ndim = 3, nout = 6
      Integer, Parameter, Public       :: sdvert = 2*(ndim+1)
      Integer, Parameter, Public       :: ldvert = ndim + 1
    Contains
      Function functn(ndim,x)

!       .. Function Return Value ..
        Real (Kind=nag_wp)             :: functn
!       .. Scalar Arguments ..
        Integer, Intent (In)           :: ndim
!       .. Array Arguments ..
        Real (Kind=nag_wp), Intent (In) :: x(ndim)
!       .. Intrinsic Procedures ..
        Intrinsic                      :: cos, exp
!       .. Executable Statements ..
        functn = exp(x(1)+x(2)+x(3))*cos(x(1)+x(2)+x(3))

        Return

      End Function functn
    End Module d01pafe_mod
    Program d01pafe

!     D01PAF Example Main Program

!     .. Use Statements ..
      Use nag_library, Only: d01paf, nag_wp
      Use d01pafe_mod, Only: functn, ldvert, mxord, ndim, nout, sdvert
!     .. Implicit None Statement ..
      Implicit None
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: esterr
      Integer                          :: ifail, j, maxord, minord, nevals
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: finvls(:), vert(:,:)
!     .. Executable Statements ..
      Write (nout,*) 'D01PAF Example Program Results'

      Allocate (finvls(mxord),vert(ldvert,sdvert))

      vert(1:ldvert,1:ndim) = 0.0_nag_wp
      Do j = 2, ldvert
        vert(j,j-1) = 1.0_nag_wp
      End Do

      minord = 0
      nevals = 1

      Do maxord = 1, mxord

        ifail = 0
        Call d01paf(ndim,vert,ldvert,sdvert,functn,minord,maxord,finvls,       &
          esterr,ifail)

        If (maxord==1) Then
          Write (nout,99999)
        End If
        Write (nout,99998) maxord, finvls(maxord), esterr, nevals

        nevals = (nevals*(maxord+ndim+1))/maxord
      End Do

99999 Format (/,1X,'MAXORD   Estimated      Estimated         Integrand',/,1X, &
        '           value         accuracy        evaluations')
99998 Format (1X,I4,F13.5,E16.3,I15)
    End Program d01pafe


d01rafe.f90

!   D01RAF Example Program Text
!   Mark 26 Release. NAG Copyright 2016.
    Module d01rafe_mod

!     .. Use Statements ..
      Use nag_library, Only: nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Accessibility Statements ..
      Private
      Public                           :: display_integration_details,         &
                                          display_option
!     .. Parameters ..
      Integer, Parameter, Public       :: nout = 6
      Logical, Parameter, Public       :: disp_integration_info = .True.
    Contains
      Subroutine display_integration_details(ni,iopts,opts,icom,licom,com,     &
        lcom)

!       .. Use Statements ..
        Use nag_library, Only: d01zlf
!       .. Implicit None Statement ..
        Implicit None
!       .. Scalar Arguments ..
        Integer, Intent (In)           :: lcom, licom, ni
!       .. Array Arguments ..
        Real (Kind=nag_wp), Intent (In) :: com(lcom), opts(100)
        Integer, Intent (In)           :: icom(licom), iopts(100)
!       .. Local Scalars ..
        Real (Kind=nag_wp)             :: rvalue
        Integer                        :: dsp, esp, evalsp, fcp, ifail, index, &
                                          ldi, ldr, nsdiv, nseg, optype,       &
                                          sinfoip, sinforp
        Character (16)                 :: cvalue
!       .. Executable Statements ..

!       Request communication array indices.
        ifail = 0
        Call d01zlf('Index nseg',index,rvalue,cvalue,optype,iopts,opts,ifail)
        nseg = icom(index)
        Call d01zlf('Index nsdiv',index,rvalue,cvalue,optype,iopts,opts,ifail)
        nsdiv = icom(index)
        Call d01zlf('Index ldi',index,rvalue,cvalue,optype,iopts,opts,ifail)
        ldi = icom(index)
        Call d01zlf('Index ldr',index,rvalue,cvalue,optype,iopts,opts,ifail)
        ldr = icom(index)
        Call d01zlf('Index fcp',index,rvalue,cvalue,optype,iopts,opts,ifail)
        fcp = icom(index)
        Call d01zlf('Index evalsp',index,rvalue,cvalue,optype,iopts,opts,      &
          ifail)
        evalsp = icom(index)
        Call d01zlf('Index sinfoip',index,rvalue,cvalue,optype,iopts,opts,     &
          ifail)
        sinfoip = icom(index)
        Call d01zlf('Index dsp',index,rvalue,cvalue,optype,iopts,opts,ifail)
        dsp = icom(index)
        Call d01zlf('Index esp',index,rvalue,cvalue,optype,iopts,opts,ifail)
        esp = icom(index)
        Call d01zlf('Index sinforp',index,rvalue,cvalue,optype,iopts,opts,     &
          ifail)
        sinforp = icom(index)

        Write (nout,*)
        Write (nout,99999)
        Write (nout,99998) ni, nseg, nsdiv
        Call display_subdivision_strategy(ni,nseg,icom(fcp),icom(sinfoip),     &
          icom(evalsp),ldi,com(sinforp),com(dsp),com(esp),ldr)

        Return
99999   Format (' Information on integration: ')
99998   Format (' NI = ',I3,', nseg = ',I3,', nsdiv = ',I3,'.')
      End Subroutine display_integration_details
      Subroutine display_subdivision_strategy(ni,nseg,fcount,sinfoi,evals,ldi, &
        sinfor,ds,es,ldr)

!       .. Scalar Arguments ..
        Integer, Intent (In)           :: ldi, ldr, ni, nseg
!       .. Array Arguments ..
        Real (Kind=nag_wp), Intent (In) :: ds(ldr,*), es(ldr,*), sinfor(ldr,*)
        Integer, Intent (In)           :: evals(ldi,*), fcount(ni),            &
                                          sinfoi(ldi,*)
!       .. Local Scalars ..
        Real (Kind=nag_wp)             :: lbnd, ubnd
        Integer                        :: child1, child2, j, k, level, parent, &
                                          sid
!       .. Executable Statements ..

!       Display information on individual segments.
        Do j = 1, ni
          Write (nout,99991) j, fcount(j)
        End Do
        Write (nout,*)
        Write (nout,99992)
        Do k = 1, nseg
          Write (nout,*)
          sid = sinfoi(1,k)
          parent = sinfoi(2,k)
          child1 = sinfoi(3,k)
          child2 = sinfoi(4,k)
          level = sinfoi(5,k)
          lbnd = sinfor(1,k)
          ubnd = sinfor(2,k)
          Write (nout,99999) k
          Write (nout,99998) sid, parent, level
          If (child1>0) Then
            Write (nout,99997) child1, child2
          End If
          Write (nout,99996) lbnd, ubnd
          Do j = 1, ni
            If (evals(j,k)/=0) Then
              Write (nout,99995) j, ds(j,k)
              Write (nout,99994) j, es(j,k)
              If (evals(j,k)==3) Then
                Write (nout,99993) j
              End If
            End If
          End Do
        End Do
        Return
99999   Format (' Segment ',I3,'.')
99998   Format (' Sid = ',I3,', Parent = ',I3,', Level = ',I3,'.')
99997   Format (' Children = (',I3,',',I3,').')
99996   Format (' Bounds (',Es11.4,',',Es11.4,').')
99995   Format (' Integral ',I2,' approximation :',1X,Es11.4,'.')
99994   Format (' Integral ',I2,' error estimate:',1X,Es11.4,'.')
99993   Format (' Integral ',I2,                                               &
          ' evaluation has been superseded by descendants.')
99992   Format (' Information on subdivision and evaluations over segments.')
99991   Format (' Integral ',I2,' total approximations: ',I3,'.')
      End Subroutine display_subdivision_strategy
      Subroutine display_option(optstr,optype,ivalue,rvalue,cvalue)
!       Subroutine to query optype and print the appropriate option values

!       .. Scalar Arguments ..
        Real (Kind=nag_wp), Intent (In) :: rvalue
        Integer, Intent (In)           :: ivalue, optype
        Character (*), Intent (In)     :: cvalue, optstr
!       .. Executable Statements ..

        Select Case (optype)
        Case (1)
          Write (nout,99999) optstr, ivalue
        Case (2)
          Write (nout,99998) optstr, rvalue
        Case (3)
          Write (nout,99997) optstr, cvalue
        Case (4)
          Write (nout,99996) optstr, ivalue, cvalue
        Case (5)
          Write (nout,99995) optstr, rvalue, cvalue
        Case Default
        End Select

        Flush (nout)

        Return
99999   Format (3X,A30,' : ',I16)
99998   Format (3X,A30,' : ',Es16.4)
99997   Format (3X,A30,' : ',12X,A16)
99996   Format (3X,A30,' : ',I16,3X,A16)
99995   Format (3X,A30,' : ',Es16.4,3X,A16)
      End Subroutine display_option
    End Module d01rafe_mod

    Program d01rafe

!     .. Use Statements ..
      Use nag_library, Only: d01raf, d01rcf, d01zkf, d01zlf, nag_wp, x01aaf
      Use d01rafe_mod, Only: display_integration_details, display_option,      &
                             disp_integration_info, nout
!     .. Implicit None Statement ..
      Implicit None
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: a, b, pi, rvalue
      Integer                          :: ifail, irevcm, ivalue, j, lcmax,     &
                                          lcmin, lcom, ldfm, ldfmrq, lenx,     &
                                          lenxrq, licmax, licmin, licom, ni,   &
                                          nx, optype, sdfm, sdfmrq, sid
      Character (16)                   :: cvalue
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: com(:), dinest(:), errest(:),        &
                                          fm(:,:), opts(:), x(:)
      Integer, Allocatable             :: icom(:), iopts(:), needi(:)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: cos, sin
!     .. Executable Statements ..
      Continue
      Write (nout,*) 'D01RAF Example Program Results'
      Write (nout,*)

      pi = x01aaf(pi)

!     Setup phase.

!     Set problem parameters
      ni = 2
!     Lower (a) and upper (b) bounds
      a = 0.0E0_nag_wp
      b = pi
      Allocate (opts(100),iopts(100))

!     Initialize option arrays
      ifail = 0
      Call d01zkf('Initialize = d01raf',iopts,100,opts,100,ifail)
!     Set any non-default options required
      Call d01zkf('Quadrature Rule = gk41',iopts,100,opts,100,ifail)
      Call d01zkf('Absolute Tolerance = 1.0e-7',iopts,100,opts,100,ifail)
      Call d01zkf('Relative Tolerance = 1.0e-7',iopts,100,opts,100,ifail)

!     Determine maximum required array lengths
      ifail = -1
      Call d01rcf(ni,lenxrq,ldfmrq,sdfmrq,licmin,licmax,lcmin,lcmax,iopts,     &
        opts,ifail)
      ldfm = ldfmrq
      sdfm = sdfmrq
      lenx = lenxrq
      licom = licmax
      lcom = lcmax

!     Allocate remaining arrays
      Allocate (icom(licom),needi(ni),com(lcom),fm(ldfm,sdfm),dinest(ni),      &
        errest(ni),x(lenx))

!       Solve phase.
!       Use D01RAF to evaluate the definite integrals of:
!       f_1 = (x*sin(2*x))*cos(15*x)
!       f_2 = (x*sin(2*x))*(x*cos(50*x))

!     Set initial irevcm
      irevcm = 1
      ifail = -1

      Do While (irevcm/=0)

        Call d01raf(irevcm,ni,a,b,sid,needi,x,lenx,nx,fm,ldfm,dinest,errest,   &
          iopts,opts,icom,licom,com,lcom,ifail)

        Select Case (irevcm)
        Case (11)
!             Initial returns.
!             These will occur during the non-adaptive phase.
!             All values must be supplied.
!             DINEST and ERREST do not contain approximations
!              over the complete interval at this stage.

!         Calculate x*sin(2*x), storing the result in fm(2,1:nx) for re-use.
          fm(2,1:nx) = x(1:nx)*sin(2.0E0_nag_wp*x(1:nx))

!         Calculate f1
          fm(1,1:nx) = fm(2,1:nx)*cos(15.0E0_nag_wp*x(1:nx))

!         Complete f2 calculation.
          fm(2,1:nx) = fm(2,1:nx)*x(1:nx)*cos(50.0E0_nag_wp*x(1:nx))

        Case (12)
!             Intermediate returns.
!             These will occur during the adaptive phase.
!             All requested values must be supplied.
!             DINEST and ERREST do not contain approximations
!              over the complete interval at this stage.

!             Calculate x*sin(2*x).
          fm(2,1:nx) = x(1:nx)*sin(2.0E0_nag_wp*x(1:nx))

!         Calculate f1 if required.
          If (needi(1)==1) Then
            fm(1,1:nx) = fm(2,1:nx)*cos(15.0E0_nag_wp*x(1:nx))
          End If

!         Complete f2 calculation if required.
          If (needi(2)==1) Then
            fm(2,1:nx) = fm(2,1:nx)*x(1:nx)*cos(50.0E0_nag_wp*x(1:nx))
          End If
        Case (0)
!         Final return. Test IFAIL.
          Select Case (ifail)
          Case (0:3)
!           Useful information has been returned.
          Case Default
!           An unrecoverable error has been detected.
            Go To 100
          End Select
        End Select

      End Do

!     Query some currently set options and statistics.
      ifail = 0
      Call d01zlf('Quadrature rule',ivalue,rvalue,cvalue,optype,iopts,opts,    &
        ifail)
      Call display_option('Quadrature rule',optype,ivalue,rvalue,cvalue)

      Call d01zlf('Maximum Subdivisions',ivalue,rvalue,cvalue,optype,iopts,    &
        opts,ifail)
      Call display_option('Maximum Subdivisions',optype,ivalue,rvalue,cvalue)

      Call d01zlf('Extrapolation',ivalue,rvalue,cvalue,optype,iopts,opts,      &
        ifail)
      Call display_option('Extrapolation',optype,ivalue,rvalue,cvalue)

      Call d01zlf('Extrapolation Safeguard',ivalue,rvalue,cvalue,optype,iopts, &
        opts,ifail)
      Call display_option('Extrapolation safeguard',optype,ivalue,rvalue,      &
        cvalue)

!     Print solution
      Write (nout,*)
      Write (nout,99999)
      Do j = 1, ni
        Write (nout,99998) j, needi(j), dinest(j), errest(j)
      End Do

!     Investigate integration strategy
      If (disp_integration_info) Then
        Call display_integration_details(ni,iopts,opts,icom,licom,com,lcom)
      End If

100   Continue

99999 Format (' Integral |  NEEDI  |   DINEST   |   ERREST   ')
99998 Format (2(1X,I9),2(1X,Es12.4))
    End Program d01rafe


d01rgfe.f90

!   D01RGF Example Program Text
!   Mark 26 Release. NAG Copyright 2016.

    Module d01rgfe_mod

!     D01ATF Example Program Module:
!            Parameters and User-defined Routines

!     .. Use Statements ..
      Use nag_library, Only: nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Accessibility Statements ..
      Private
      Public                           :: f
!     .. Parameters ..
      Integer, Parameter, Public       :: nout = 6
    Contains
      Subroutine f(x,nx,fv,iflag,iuser,ruser)

!       .. Scalar Arguments ..
        Integer, Intent (Inout)        :: iflag
        Integer, Intent (In)           :: nx
!       .. Array Arguments ..
        Real (Kind=nag_wp), Intent (Out) :: fv(nx)
        Real (Kind=nag_wp), Intent (Inout) :: ruser(*)
        Real (Kind=nag_wp), Intent (In) :: x(nx)
        Integer, Intent (Inout)        :: iuser(*)
!       .. Intrinsic Procedures ..
        Intrinsic                      :: log, sin
!       .. Executable Statements ..
        fv = sin(x)/x*log(10.0_nag_wp*(1.0_nag_wp-x))
        Return
      End Subroutine f
    End Module d01rgfe_mod
    Program d01rgfe

!     D01RGF Example Main Program

!     .. Use Statements ..
      Use nag_library, Only: d01rgf, nag_wp, x07caf, x07cbf
      Use d01rgfe_mod, Only: f, nout
!     .. Implicit None Statement ..
      Implicit None
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: a, b, dinest, epsabs, epsrel, errest
      Integer                          :: ifail, nevals
!     .. Local Arrays ..
      Real (Kind=nag_wp)               :: ruser(1)
      Integer                          :: exmode(3), exmode_old(3), iuser(1)
!     .. Executable Statements ..
      Write (nout,*) 'D01RGF Example Program Results'

!     The example function can raise various exceptions - it contains
!     a division by zero and a log singularity - although its integral
!     is well behaved.

!     Save the original halting mode
      Call x07caf(exmode_old)

!     Turn exception halting mode off for the three common exceptions
!     overflow, division-by-zero, and invalid operation.
      exmode = (/0,0,0/)
      Call x07cbf(exmode)

      epsabs = 0.0_nag_wp
      epsrel = 1.0E-04_nag_wp
      a = -1.0_nag_wp
      b = 1.0_nag_wp

!     Evaluate the integral
      ifail = -1
      Call d01rgf(a,b,f,epsabs,epsrel,dinest,errest,nevals,iuser,ruser,ifail)

      Write (nout,*)
      Write (nout,99999) 'A     ', 'lower limit of integration', a
      Write (nout,99999) 'B     ', 'upper limit of integration', b
      Write (nout,99998) 'EPSABS', 'absolute accuracy requested', epsabs
      Write (nout,99998) 'EPSREL', 'relative accuracy requested', epsrel
      Write (nout,*)
      If (ifail>=0) Then
        Write (nout,99997) 'DINEST', 'approximation to the integral', dinest
        Write (nout,99998) 'ERREST', 'estimate of the absolute error', errest
        Write (nout,99996) 'NEVALS', 'number of function evaluations', nevals
      End If

!     Restore the original halting mode
      Call x07cbf(exmode_old)

99999 Format (1X,A6,' - ',A30,' = ',F10.4)
99998 Format (1X,A6,' - ',A30,' = ',E10.2)
99997 Format (1X,A6,' - ',A30,' = ',F10.5)
99996 Format (1X,A6,' - ',A30,' = ',I10)
    End Program d01rgfe


d01tbfe.f90

    Program d01tbfe

!     D01TBF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: d01tbf, nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: n = 6, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: a, b
      Integer                          :: ifail, j, key
!     .. Local Arrays ..
      Real (Kind=nag_wp)               :: abscis(n), weight(n)
!     .. Executable Statements ..
      Write (nout,*) 'D01TBF Example Program Results'

      a = 0.0E0_nag_wp
      b = 1.0E0_nag_wp

      key = -3
      ifail = 0
      Call d01tbf(key,a,b,n,weight,abscis,ifail)

      Write (nout,*)
      Write (nout,99998) 'Laguerre formula,', n, ' points'
      Write (nout,*)
      Write (nout,*) '    Abscissae        Weights'
      Write (nout,*)
      Write (nout,99999)(abscis(j),weight(j),j=1,n)

99999 Format (1X,2E15.6)
99998 Format (1X,A,I3,A)
    End Program d01tbfe


d01tdfe.f90

!   D01TDF Example Program Text
!   Mark 26 Release. NAG Copyright 2016.
    Module d01tdfe_mod

!     D01TDF Example Program Module:
!            Parameters and User-defined Routines

!     .. Use Statements ..
      Use nag_library, Only: nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Accessibility Statements ..
      Private
      Public                           :: basic_types
!     .. Parameters ..
      Integer, Parameter, Public       :: chebyshev1 = 2, chebyshev2 = 3,      &
                                          hermite = 6, jacobi = 4,             &
                                          laguerre = 5, legendre = 1
    Contains
      Subroutine basic_types(rulekind,alpha,beta,n,a,b,c,muzero)
!       This procedure supplies the coefficients of the three term
!       recurrence relationship for various classical orthogonal
!       polynomials.

!       .. Use Statements ..
        Use nag_library, Only: s14aaf, x01aaf
!       .. Scalar Arguments ..
        Real (Kind=nag_wp), Intent (In) :: alpha, beta
        Real (Kind=nag_wp), Intent (Out) :: muzero
        Integer, Intent (In)           :: n, rulekind
!       .. Array Arguments ..
        Real (Kind=nag_wp), Intent (Out) :: a(1:n), b(1:n), c(1:n)
!       .. Local Scalars ..
        Real (Kind=nag_wp)             :: abl, mypi
        Integer                        :: i, ifail
!       .. Intrinsic Procedures ..
        Intrinsic                      :: real, sqrt
!       .. Executable Statements ..
        mypi = x01aaf(mypi)

        Select Case (rulekind)

        Case (legendre)
          muzero = 2.0_nag_wp
!         P(x) in [-1, 1), w(x) = 1.0
          Do i = 1, n
            a(i) = (real(2*i-1,kind=nag_wp))/real(i,kind=nag_wp)
            b(i) = 0.0_nag_wp
            c(i) = real(i-1,kind=nag_wp)/real(i,kind=nag_wp)
          End Do

        Case (chebyshev1)

          muzero = mypi
!         c(i)= (i-1)/i
!         T (x) in [-1,1], w(x) = (1-x**2)**(-0.5)
          Do i = 1, n
            a(i) = 2.0_nag_wp
            b(i) = 0.0_nag_wp
            c(i) = 1.0_nag_wp
          End Do
          If (n>0) Then
            a(1) = 1.0_nag_wp
          End If

        Case (chebyshev2)

          muzero = mypi/2.0_nag_wp
!         u(x) in [-1, 11, W(x) = (1-x**2)** 0.5;
          Do i = 1, n
            a(i) = 2.0_nag_wp
            b(i) = 0.0_nag_wp
            c(i) = 1.0_nag_wp
          End Do

        Case (jacobi)
          ifail = 0
          muzero = 2**(alpha+beta+1)*s14aaf(alpha+1,ifail)*                    &
            s14aaf(beta+1,ifail)/s14aaf(alpha+beta+2,ifail)
!         P(alpha,beta)(x) in [-1, 11, w(x) = (1-x)**alpha*(l+x)**beta
!         alpha> -1 and beta > -1
          If (n>0) Then
            a(1) = 0.5_nag_wp*(alpha+beta+2)
            b(1) = 0.5_nag_wp*(alpha-beta)
            c(1) = 0.0_nag_wp
          End If
          Do i = 2, n
            abl = 2.0_nag_wp*real(i,kind=nag_wp)*(real(i,kind=nag_wp)+alpha+   &
              beta)
            a(i) = (2.0_nag_wp*real(i,kind=nag_wp)+alpha+beta-1.0_nag_wp)*     &
              (2.0_nag_wp*real(i,kind=nag_wp)+alpha+beta)/abl
            abl = (2.0_nag_wp*real(i,kind=nag_wp)+alpha+beta-2.0_nag_wp)*abl
            b(i) = (2.0_nag_wp*real(i,kind=nag_wp)+alpha+beta-1.0_nag_wp)*     &
              (alpha**2-beta**2)/abl
            c(i) = 2.0_nag_wp*(real(i,kind=nag_wp)-1.0_nag_wp+alpha)*          &
              (real(i,kind=nag_wp)-1.0_nag_wp+beta)*                           &
              (2.0_nag_wp*real(i,kind=nag_wp)+alpha+beta)/abl
          End Do

        Case (laguerre)
          ifail = 0
          muzero = s14aaf(alpha+1.0_nag_wp,ifail)
!         L(alpha)(x) in [0, infinity), w(x) = exp(-x)*x**alpha,
!         alpha > -1
          Do i = 1, n
            a(i) = -1.0_nag_wp/real(i,kind=nag_wp)
            b(i) = (2.0_nag_wp*real(i,kind=nag_wp)-1.0_nag_wp+alpha)/          &
              real(i,kind=nag_wp)
            c(i) = (real(i,kind=nag_wp)-1.0_nag_wp+alpha)/real(i,kind=nag_wp)
          End Do

        Case (hermite)
          muzero = sqrt(mypi)
!         H(x) in (-infinity,+infinity), w(x) = exp(-x**2)
          Do i = 1, n
            a(i) = 2.0_nag_wp
            b(i) = 0.0_nag_wp
            c(i) = 2.0_nag_wp*real(i-1,kind=nag_wp)
          End Do

        End Select
      End Subroutine basic_types
    End Module d01tdfe_mod

    Program d01tdfe
!     D01TDF Example Program Text

!     .. Use Statements ..
      Use nag_library, Only: d01tdf, nag_wp
      Use d01tdfe_mod, Only: basic_types, chebyshev1, chebyshev2, hermite,     &
                             jacobi, laguerre, legendre
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: n = 4, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: alpha, beta, muzero
      Integer                          :: ifail, j, rule
!     .. Local Arrays ..
      Real (Kind=nag_wp)               :: a(1:n), b(1:n), c(1:n), t(1:n),      &
                                          w(1:n)
!     .. Executable Statements ..

      Write (nout,*) 'D01TDF Example Program Results '
      Write (6,*)
      rule = legendre
      Do rule = 1, 6
        ifail = -1

        Select Case (rule)

        Case (legendre)
          Call basic_types(rule,alpha,beta,n,a,b,c,muzero)
          Write (nout,*) 'Using the Gauss-Legendre Rule'
          Call d01tdf(n,a,b,c,muzero,w,t,ifail)
          If (ifail==0) Then
            Write (nout,99998)
            Write (nout,99997)(j,t(j),w(j),j=1,n)
            Write (6,*)
          End If

        Case (chebyshev1)
          Call basic_types(rule,alpha,beta,n,a,b,c,muzero)
          Write (nout,*) 'Using the Chebyshev Rule 1'
          Call d01tdf(n,a,b,c,muzero,w,t,ifail)
          If (ifail==0) Then
            Write (nout,99998)
            Write (nout,99997)(j,t(j),w(j),j=1,n)
            Write (6,*)
          End If

        Case (chebyshev2)
          Call basic_types(rule,alpha,beta,n,a,b,c,muzero)
          Write (nout,*) 'Using the Chebyshev Rule 2'
          Call d01tdf(n,a,b,c,muzero,w,t,ifail)
          If (ifail==0) Then
            Write (nout,99998)
            Write (nout,99997)(j,t(j),w(j),j=1,n)
            Write (6,*)
          End If

        Case (jacobi)
          alpha = 0.5_nag_wp
          beta = 0.5_nag_wp
          Call basic_types(rule,alpha,beta,n,a,b,c,muzero)
          Write (nout,99999) alpha, beta
          Call d01tdf(n,a,b,c,muzero,w,t,ifail)
          If (ifail==0) Then
            Write (nout,99998)
            Write (nout,99997)(j,t(j),w(j),j=1,n)
            Write (6,*)
          End If

        Case (laguerre)
          Call basic_types(rule,alpha,beta,n,a,b,c,muzero)
          Write (nout,*) 'Using the Laguerre Rule'
          Call d01tdf(n,a,b,c,muzero,w,t,ifail)
          If (ifail==0) Then
            Write (nout,99998)
            Write (nout,99997)(j,t(j),w(j),j=1,n)
            Write (6,*)
          End If

        Case (hermite)
          Call basic_types(rule,alpha,beta,n,a,b,c,muzero)
          Write (nout,*) 'Using the Hermite Rule'
          Call d01tdf(n,a,b,c,muzero,w,t,ifail)
          If (ifail==0) Then
            Write (nout,99998)
            Write (nout,99997)(j,t(j),w(j),j=1,n)
            Write (6,*)
          End If

        End Select

      End Do
99999 Format (' Using the Jacobi Rule: alpha = ',F10.5,'  beta = ',F10.5)

99998 Format (/,'   j    ','         Abscissa        ','          Weight')
99997 Format (I8,D25.15,D25.15)
    End Program d01tdfe


d01tefe.f90

    Program d01tefe
!     D01TEF Example Program Text
!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: d01tdf, d01tef, nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: n = 4, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: muzero
      Integer                          :: i, ifail
!     .. Local Arrays ..
      Real (Kind=nag_wp)               :: a(1:n), abscissae(1:n), b(1:n),      &
                                          c(1:n), mu(0:2*n), weights(1:n)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: real
!     .. Executable Statements ..
      Write (nout,*) 'D01TEF Example Program Results'
      Do i = 0, 2*n
        mu(i) = 0.0_nag_wp
      End Do
      Do i = 0, 2*n, 2
        mu(i) = 2.0_nag_wp/real(i+1,kind=nag_wp)
      End Do

      ifail = 0
      Call d01tef(n,mu,a,b,c,ifail)
      muzero = mu(0)
      Write (nout,*)
      Write (nout,*) '      a         b         c'
      Write (nout,99999)(a(i),b(i),c(i),i=1,n)
99999 Format (1X,3F10.5)

      ifail = 0
      Call d01tdf(n,a,b,c,muzero,weights,abscissae,ifail)
      Write (nout,*)
      Write (6,*) '   weights       abscissae '
      Write (6,99998)(weights(i),abscissae(i),i=1,4)
      Write (nout,*)
99998 Format (1X,F10.5,5X,F10.5)
    End Program d01tefe


d01uafe.f90

!   D01UAF Example Program Text
!   Mark 26 Release. NAG Copyright 2016.

    Module d01uafe_mod

!     D01UAF Example Program Module:
!            Parameters and User-defined Routines

!     .. Use Statements ..
      Use nag_library, Only: nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Accessibility Statements ..
      Private
      Public                           :: d01uaf_f
!     .. Parameters ..
      Integer, Parameter, Public       :: i_funid = 1
      Integer, Parameter, Public       :: liuser = i_funid
      Integer, Parameter, Public       :: lruser = 1
    Contains
      Subroutine d01uaf_f(x,nx,fv,iflag,iuser,ruser)

!       .. Implicit None Statement ..
        Implicit None
!       .. Scalar Arguments ..
        Integer, Intent (Inout)        :: iflag
        Integer, Intent (In)           :: nx
!       .. Array Arguments ..
        Real (Kind=nag_wp), Intent (Out) :: fv(nx)
        Real (Kind=nag_wp), Intent (Inout) :: ruser(*)
        Real (Kind=nag_wp), Intent (In) :: x(nx)
        Integer, Intent (Inout)        :: iuser(*)
!       .. Intrinsic Procedures ..
        Intrinsic                      :: exp, log
!       .. Executable Statements ..
        Select Case (iuser(i_funid))
        Case (1)
          fv = 4.0E0_nag_wp/(1.0E0_nag_wp+x*x)
        Case (2)
          fv = 1.0E0_nag_wp/(x*x*log(x))
        Case (3)
          fv = exp(-x)/x
        Case (4)
          fv = 1.0E0_nag_wp/x
        Case (5)
          fv = exp(-3.0E0_nag_wp*x*x-4.0E0_nag_wp*x-1.0E0_nag_wp)
        Case (6)
          fv = exp(2.0E0_nag_wp*x+2.0E0_nag_wp)
        Case Default
          iflag = -1
        End Select
      End Subroutine d01uaf_f
    End Module d01uafe_mod
    Program d01uafe

!     D01UAF Example Main Program

!     .. Use Statements ..
      Use nag_library, Only: d01uaf, nag_wp
      Use d01uafe_mod, Only: d01uaf_f, i_funid, liuser, lruser
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: a, b, dinest
      Integer                          :: funid, i, ifail, key, nstor
!     .. Local Arrays ..
      Real (Kind=nag_wp)               :: ruser(lruser)
      Integer                          :: iuser(liuser)
!     .. Executable Statements ..
      Write (nout,*) 'D01UAF Example Program Results'

cases: Do funid = 1, 6
        Write (nout,*)
        Select Case (funid)
        Case (1)
          Write (nout,*) 'Gauss-Legendre example'
          a = 0.0_nag_wp
          b = 1.0_nag_wp
          key = 0
        Case (2)
          Write (nout,*) 'Rational Gauss example'
          a = 2.0_nag_wp
          b = 0.0_nag_wp
          key = -5
        Case (3)
          Write (nout,*) 'Gauss-Laguerre example (adjusted weights)'
          a = 2.0_nag_wp
          b = 1.0_nag_wp
          key = -3
        Case (4)
          Write (nout,*) 'Gauss-Laguerre example (normal weights)'
          a = 2.0_nag_wp
          b = 1.0_nag_wp
          key = 3
        Case (5)
          Write (nout,*) 'Gauss-Hermite example (adjusted weights)'
          a = -1.0_nag_wp
          b = 3.0_nag_wp
          key = -4
        Case (6)
          Write (nout,*) 'Gauss-Hermite example (normal weights)'
          a = -1.0_nag_wp
          b = 3.0_nag_wp
          key = 4
        End Select
        iuser(i_funid) = funid

        Do i = 1, 6
          nstor = 2**(i)
          ifail = -1
          Call d01uaf(key,a,b,nstor,d01uaf_f,dinest,iuser,ruser,ifail)
          Select Case (ifail)
          Case (:-1)
!           Error flag returned by d01uaf_f
            Exit cases
          Case (0,1)
!           The definite integral has been estimated.
            Write (nout,99999) nstor, dinest
          Case Default
!           Illegal parameters on entry to d01uaf
            Exit cases
          End Select
        End Do
        Write (nout,*)

      End Do cases

99999 Format (1X,I5,' Points     Answer = ',F10.5)
    End Program d01uafe


d01ubfe.f90

!   Mark 26 Release. NAG Copyright 2016.

    Module d01ubfe_mod
!     D01UBF Example Program Module:
!            Parameters and User-defined Routines

!     .. Use Statements ..
      Use nag_library, Only: nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Accessibility Statements ..
      Private
      Public                           :: fun
!     .. Parameters ..
      Integer, Parameter, Public       :: nout = 6
    Contains
      Subroutine fun(x,f,n,iuser,ruser,ifail)

!       .. Scalar Arguments ..
        Integer, Intent (Inout)        :: ifail
        Integer, Intent (In)           :: n
!       .. Array Arguments ..
        Real (Kind=nag_wp), Intent (Out) :: f(n)
        Real (Kind=nag_wp), Intent (Inout) :: ruser(*)
        Real (Kind=nag_wp), Intent (In) :: x(n)
        Integer, Intent (Inout)        :: iuser(*)
!       .. Executable Statements ..
        f = x
      End Subroutine fun

    End Module d01ubfe_mod

    Program d01ubfe

!     .. Use Statements ..
      Use nag_library, Only: d01ubf, nag_wp
      Use d01ubfe_mod, Only: fun, nout
!     .. Implicit None Statement ..
      Implicit None
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: ans
      Integer                          :: ifail, n
!     .. Local Arrays ..
      Real (Kind=nag_wp)               :: ruser(1)
      Integer                          :: iuser(1)
!     .. Executable Statements ..
      Write (nout,*) 'D01UBF Example Program Results'
      n = 10
      ifail = 0
      Call d01ubf(fun,n,ans,iuser,ruser,ifail)
      Write (nout,*)
      Write (nout,99999) 'Approximation to the integral = ', ans

99999 Format (1X,A,F12.5)
    End Program d01ubfe


d02agfe.f90

!   D02AGF Example Program Text
!   Mark 26 Release. NAG Copyright 2016.

    Module d02agfe_mod

!     D02AGF Example Program Module:
!            Parameters and User-defined Routines

!     iprint:    set iprint = 1 for output at each Newton iteration.
!     nin:       the input channel number
!     nout:      the output channel number

!     For Example 1:
!     n_ex1 : number of differential equations,
!     n1_ex1: number of parameters.

!     For Example 2:
!     n_ex2 : number of differential equations,
!     n1_ex2: number of parameters.

!     .. Use Statements ..
      Use nag_library, Only: nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Accessibility Statements ..
      Private
      Public                           :: aux1, aux2, bcaux1, bcaux2, prsol1,  &
                                          prsol2, raaux1, raaux2
!     .. Parameters ..
      Integer, Parameter               :: iprint = 0
      Integer, Parameter, Public       :: n1_ex1 = 2, n1_ex2 = 3, nin = 5,     &
                                          nout = 6, n_ex1 = 2, n_ex2 = 3
    Contains
      Subroutine aux1(f,y,x,param)

!       .. Scalar Arguments ..
        Real (Kind=nag_wp), Intent (In) :: x
!       .. Array Arguments ..
        Real (Kind=nag_wp), Intent (Out) :: f(*)
        Real (Kind=nag_wp), Intent (In) :: param(*), y(*)
!       .. Executable Statements ..
        f(1) = y(2)
        f(2) = (y(1)**3-y(2))/(2.0_nag_wp*x)
        Return
      End Subroutine aux1
      Subroutine raaux1(x0,x1,r,param)

!       .. Scalar Arguments ..
        Real (Kind=nag_wp), Intent (Out) :: r, x0, x1
!       .. Array Arguments ..
        Real (Kind=nag_wp), Intent (In) :: param(*)
!       .. Executable Statements ..
        x0 = 0.1_nag_wp
        x1 = 16.0_nag_wp
        r = 16.0_nag_wp
        Return
      End Subroutine raaux1
      Subroutine bcaux1(g0,g1,param)

!       .. Array Arguments ..
        Real (Kind=nag_wp), Intent (Out) :: g0(*), g1(*)
        Real (Kind=nag_wp), Intent (In) :: param(*)
!       .. Local Scalars ..
        Real (Kind=nag_wp)             :: z
!       .. Intrinsic Procedures ..
        Intrinsic                      :: sqrt
!       .. Executable Statements ..
        z = 0.1_nag_wp
        g0(1) = 0.1_nag_wp + param(1)*sqrt(z)*0.1_nag_wp + 0.01_nag_wp*z
        g0(2) = param(1)*0.05_nag_wp/sqrt(z) + 0.01_nag_wp
        g1(1) = 1.0_nag_wp/6.0_nag_wp
        g1(2) = param(2)
        Return
      End Subroutine bcaux1
      Subroutine prsol1(param,res,n1,err)

!       .. Scalar Arguments ..
        Real (Kind=nag_wp), Intent (In) :: res
        Integer, Intent (In)           :: n1
!       .. Array Arguments ..
        Real (Kind=nag_wp), Intent (In) :: err(n1), param(n1)
!       .. Local Scalars ..
        Integer                        :: i
!       .. Executable Statements ..
        If (iprint/=0) Then
          Write (nout,99999) 'Current parameters   ', (param(i),i=1,n1)
          Write (nout,99998) 'Residuals   ', (err(i),i=1,n1)
          Write (nout,99998) 'Sum of residuals squared  ', res
          Write (nout,*)
        End If
        Return

99999   Format (1X,A,6(E14.6,2X))
99998   Format (1X,A,6(E12.4,1X))
      End Subroutine prsol1
      Subroutine aux2(f,y,x,param)

!       .. Parameters ..
        Real (Kind=nag_wp), Parameter  :: eps = 2.0E-5_nag_wp
!       .. Scalar Arguments ..
        Real (Kind=nag_wp), Intent (In) :: x
!       .. Array Arguments ..
        Real (Kind=nag_wp), Intent (Out) :: f(*)
        Real (Kind=nag_wp), Intent (In) :: param(*), y(*)
!       .. Local Scalars ..
        Real (Kind=nag_wp)             :: c, s
!       .. Intrinsic Procedures ..
        Intrinsic                      :: cos, sin
!       .. Executable Statements ..
        c = cos(y(3))
        s = sin(y(3))
        f(1) = s/c
        f(2) = -(param(1)*s+eps*y(2)*y(2))/(y(2)*c)
        f(3) = -param(1)/(y(2)*y(2))
        Return
      End Subroutine aux2
      Subroutine raaux2(x0,x1,r,param)

!       .. Scalar Arguments ..
        Real (Kind=nag_wp), Intent (Out) :: r, x0, x1
!       .. Array Arguments ..
        Real (Kind=nag_wp), Intent (In) :: param(*)
!       .. Executable Statements ..
        x0 = 0.0_nag_wp
        x1 = param(2)
        r = param(2)
        Return
      End Subroutine raaux2
      Subroutine bcaux2(g0,g1,param)

!       .. Array Arguments ..
        Real (Kind=nag_wp), Intent (Out) :: g0(*), g1(*)
        Real (Kind=nag_wp), Intent (In) :: param(*)
!       .. Executable Statements ..
        g0(1) = 0.0E0_nag_wp
        g0(2) = 500.0E0_nag_wp
        g0(3) = 0.5E0_nag_wp
        g1(1) = 0.0E0_nag_wp
        g1(2) = 450.0E0_nag_wp
        g1(3) = param(3)
        Return
      End Subroutine bcaux2
      Subroutine prsol2(param,res,n1,err)

!       .. Scalar Arguments ..
        Real (Kind=nag_wp), Intent (In) :: res
        Integer, Intent (In)           :: n1
!       .. Array Arguments ..
        Real (Kind=nag_wp), Intent (In) :: err(n1), param(n1)
!       .. Local Scalars ..
        Integer                        :: i
!       .. Executable Statements ..
        If (iprint/=0) Then
          Write (nout,99999) 'Current parameters   ', (param(i),i=1,n1)
          Write (nout,99998) 'Residuals   ', (err(i),i=1,n1)
          Write (nout,99998) 'Sum of residuals squared  ', res
          Write (nout,*)
        End If
        Return

99999   Format (1X,A,6(E14.6,2X))
99998   Format (1X,A,6(E12.4,1X))
      End Subroutine prsol2
    End Module d02agfe_mod
    Program d02agfe

!     D02AGF Example Main Program

!     .. Use Statements ..
      Use d02agfe_mod, Only: nout
!     .. Implicit None Statement ..
      Implicit None
!     .. Executable Statements ..
      Write (nout,*) 'D02AGF Example Program Results'

      Call ex1

      Call ex2

    Contains
      Subroutine ex1

!       .. Use Statements ..
        Use nag_library, Only: d02agf, nag_wp
        Use d02agfe_mod, Only: aux1, bcaux1, n1_ex1, nin, n_ex1, prsol1,       &
                               raaux1
!       .. Local Scalars ..
        Real (Kind=nag_wp)             :: h, r, soler, x, x1, xx
        Integer                        :: i, ifail, j, m1
!       .. Local Arrays ..
        Real (Kind=nag_wp), Allocatable :: c(:,:), e(:), mat(:,:), param(:),   &
                                          parerr(:), wspac1(:), wspac2(:),     &
                                          wspace(:,:)
        Real (Kind=nag_wp)             :: dummy(1,1)
!       .. Intrinsic Procedures ..
        Intrinsic                      :: real
!       .. Executable Statements ..
!       Skip heading in data file
        Read (nin,*)
!       m1: final solution calculated at m1 points in range including
!       end points.
        Read (nin,*) m1
        Allocate (c(m1,n_ex1),e(n_ex1),mat(n_ex1,n_ex1),param(n_ex1),          &
          parerr(n_ex1),wspac1(n_ex1),wspac2(n_ex1),wspace(n_ex1,9))
!       h: step size estimate,
!       param: initial parameter estimates,
!       parerr: Newton iteration tolerances,
!       soler: bound on the local error.
        Read (nin,*) h
        Read (nin,*) param(1:n1_ex1)
        Read (nin,*) parerr(1:n1_ex1)
        Read (nin,*) soler
        e(1:n_ex1) = soler
        Write (nout,*)
        Write (nout,*)
        Write (nout,*) 'Case 1'
        Write (nout,*)

!       ifail: behaviour on error exit
!              =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
        ifail = 0
        Call d02agf(h,e,parerr,param,c,n_ex1,n1_ex1,m1,aux1,bcaux1,raaux1,     &
          prsol1,mat,dummy,wspace,wspac1,wspac2,ifail)

        Write (nout,*) 'Final parameters'
        Write (nout,99999)(param(i),i=1,n1_ex1)
        Write (nout,*)
        Write (nout,*) 'Final solution'
        Write (nout,*) 'X-value     Components of solution'
        Call raaux1(x,x1,r,param)
        h = (x1-x)/real(m1-1,kind=nag_wp)
        xx = x
        Do i = 1, m1
          Write (nout,99998) xx, (c(i,j),j=1,n_ex1)
          xx = xx + h
        End Do

        Return

99999   Format (1X,3E16.6)
99998   Format (1X,F7.2,3E13.4)
      End Subroutine ex1
      Subroutine ex2

!       .. Use Statements ..
        Use nag_library, Only: d02agf, nag_wp
        Use d02agfe_mod, Only: aux2, bcaux2, n1_ex2, nin, n_ex2, prsol2,       &
                               raaux2
!       .. Local Scalars ..
        Real (Kind=nag_wp)             :: h, r, soler, x, x1, xx
        Integer                        :: i, ifail, j, m1
!       .. Local Arrays ..
        Real (Kind=nag_wp), Allocatable :: c(:,:), e(:), mat(:,:), param(:),   &
                                          parerr(:), wspac1(:), wspac2(:),     &
                                          wspace(:,:)
        Real (Kind=nag_wp)             :: dummy(1,1)
!       .. Executable Statements ..
        Read (nin,*)
!       Read in problem parameters
!       m1: final solution calculated at m1 points in range including
!       end points.
        Read (nin,*) m1
        Allocate (c(m1,n_ex2),e(n_ex2),mat(n_ex2,n_ex2),param(n_ex2),          &
          parerr(n_ex2),wspac1(n_ex2),wspac2(n_ex2),wspace(n_ex2,9))
        Write (nout,*)
        Write (nout,*)
        Write (nout,*) 'Case 2'
        Write (nout,*)
!       h: step size estimate,
!       param: initial parameter estimates,
!       parerr: Newton iteration tolerances,
!       soler: bound on the local error.
        Read (nin,*) h
        Read (nin,*) param(1:n1_ex2)
        Read (nin,*) parerr(1:n1_ex2)
        Read (nin,*) soler
        e(1:n_ex2) = soler

!       ifail: behaviour on error exit
!              =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
        ifail = 0
        Call d02agf(h,e,parerr,param,c,n_ex2,n1_ex2,m1,aux2,bcaux2,raaux2,     &
          prsol2,mat,dummy,wspace,wspac1,wspac2,ifail)

        Write (nout,*) 'Final parameters'
        Write (nout,99999)(param(i),i=1,n_ex2)
        Write (nout,*)
        Write (nout,*) 'Final solution'
        Write (nout,*) 'X-value     Components of solution'
        Call raaux2(x,x1,r,param)
        h = (x1-x)/5.0E0_nag_wp
        xx = x
        Do i = 1, 6
          Write (nout,99998) xx, (c(i,j),j=1,n_ex2)
          xx = xx + h
        End Do

        Return

99999   Format (1X,3E16.6)
99998   Format (1X,F7.0,3E13.4)
      End Subroutine ex2
    End Program d02agfe


d02bgfe.f90

!   D02BGF Example Program Text
!   Mark 26 Release. NAG Copyright 2016.

    Module d02bgfe_mod

!     D02BGF Example Program Module:
!            Parameters and User-defined Routines

!     .. Use Statements ..
      Use nag_library, Only: nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Accessibility Statements ..
      Private
      Public                           :: fcn
!     .. Parameters ..
      Integer, Parameter, Public       :: n = 3, nin = 5, nout = 6
!     n: number of differential equations
    Contains
      Subroutine fcn(x,y,f)

!       .. Scalar Arguments ..
        Real (Kind=nag_wp), Intent (In) :: x
!       .. Array Arguments ..
        Real (Kind=nag_wp), Intent (Out) :: f(*)
        Real (Kind=nag_wp), Intent (In) :: y(*)
!       .. Intrinsic Procedures ..
        Intrinsic                      :: cos, tan
!       .. Executable Statements ..
        f(1) = tan(y(3))
        f(2) = -0.032E0_nag_wp*tan(y(3))/y(2) - 0.02E0_nag_wp*y(2)/cos(y(3))
        f(3) = -0.032E0_nag_wp/y(2)**2
        Return
      End Subroutine fcn
    End Module d02bgfe_mod

    Program d02bgfe

!     D02BGF Example Main Program

!     .. Use Statements ..
      Use nag_library, Only: d02bgf, nag_wp
      Use d02bgfe_mod, Only: fcn, n, nin, nout
!     .. Implicit None Statement ..
      Implicit None
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: alpha, hmax, tol, val, x, xend,      &
                                          xinit
      Integer                          :: i, ifail, m
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: w(:,:), y(:), yinit(:)
!     .. Executable Statements ..
      Write (nout,*) 'D02BGF Example Program Results'
!     Skip heading in data file
      Read (nin,*)
!     m: index of mode of solution to attain value alpha
      Read (nin,*) m
      Allocate (w(n,10),y(n),yinit(n))
!     xinit: initial x value,     xend : final x value.
!     alpha: attain y(m) = alpha, yinit: initial solution values.
      Read (nin,*) alpha
      Read (nin,*) xinit
      Read (nin,*) xend
      Read (nin,*) yinit(1:n)
      hmax = 0.0E0_nag_wp
      val = alpha
      Do i = 4, 5
        tol = 10.0E0_nag_wp**(-i)
        x = xinit
        y(1:n) = yinit(1:n)

!       ifail: behaviour on error exit
!              =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
        ifail = 0
        Call d02bgf(x,xend,n,y,tol,hmax,m,val,fcn,w,ifail)

        Write (nout,*)
        Write (nout,99999) 'Calculation with TOL =', tol
        Write (nout,99998) ' Y(M) changes sign at X = ', x
        If (tol<0.0E0_nag_wp) Then
          Write (nout,*) ' Over one-third steps controlled by HMAX'
        End If
      End Do

99999 Format (1X,A,E8.1)
99998 Format (1X,A,F7.4)
    End Program d02bgfe


d02bhfe.f90

!   D02BHF Example Program Text
!   Mark 26 Release. NAG Copyright 2016.

    Module d02bhfe_mod

!     D02BHF Example Program Module:
!            Parameters and User-defined Routines

!     .. Use Statements ..
      Use nag_library, Only: nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Accessibility Statements ..
      Private
      Public                           :: fcn, g
!     .. Parameters ..
      Integer, Parameter, Public       :: n = 3, nin = 5, nout = 6
!     n: number of differential equations
    Contains
      Subroutine fcn(x,y,f)

!       .. Parameters ..
        Real (Kind=nag_wp), Parameter  :: alpha = -0.032E0_nag_wp
        Real (Kind=nag_wp), Parameter  :: beta = -0.02E0_nag_wp
!       .. Scalar Arguments ..
        Real (Kind=nag_wp), Intent (In) :: x
!       .. Array Arguments ..
        Real (Kind=nag_wp), Intent (Out) :: f(*)
        Real (Kind=nag_wp), Intent (In) :: y(*)
!       .. Intrinsic Procedures ..
        Intrinsic                      :: cos, tan
!       .. Executable Statements ..
        f(1) = tan(y(3))
        f(2) = alpha*tan(y(3))/y(2) + beta*y(2)/cos(y(3))
        f(3) = alpha/y(2)**2
        Return
      End Subroutine fcn

      Function g(x,y)

!       .. Function Return Value ..
        Real (Kind=nag_wp)             :: g
!       .. Scalar Arguments ..
        Real (Kind=nag_wp), Intent (In) :: x
!       .. Array Arguments ..
        Real (Kind=nag_wp), Intent (In) :: y(*)
!       .. Executable Statements ..
        g = y(1)
        Return
      End Function g
    End Module d02bhfe_mod

    Program d02bhfe

!     D02BHF Example Main Program

!     .. Use Statements ..
      Use nag_library, Only: d02bhf, nag_wp
      Use d02bhfe_mod, Only: fcn, g, n, nin, nout
!     .. Implicit None Statement ..
      Implicit None
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: hmax, tol, x, xend, xinit
      Integer                          :: i, ifail, irelab, j
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: w(:,:), y(:), yinit(:)
!     .. Executable Statements ..
      Write (nout,*) 'D02BHF Example Program Results'
      Allocate (w(n,7),y(n),yinit(n))
!     Skip heading in data file
      Read (nin,*)
!     xinit: initial x value,         xend  : final x value.
!     yinit: initial solution values, irelab: type of error control.
      Read (nin,*) xinit
      Read (nin,*) xend
      Read (nin,*) yinit(1:n)
      Read (nin,*) irelab
      hmax = 0.0E0_nag_wp
      Do i = 4, 5
        tol = 10.0E0_nag_wp**(-i)
        x = xinit
        y(1:n) = yinit(1:n)

!       ifail: behaviour on error exit
!              =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
        ifail = 0
        Call d02bhf(x,xend,n,y,tol,irelab,hmax,fcn,g,w,ifail)

        Write (nout,*)
        Write (nout,99999) 'Calculation with TOL =', tol
        Write (nout,99998) ' Root of Y(1) at', x
        Write (nout,99997) ' Solution is', (y(j),j=1,n)
        If (tol<0.0E0_nag_wp) Then
          Write (nout,*) ' Over one-third steps controlled by HMAX'
        End If
      End Do

99999 Format (1X,A,E8.1)
99998 Format (1X,A,F7.4)
99997 Format (1X,A,3F13.5)
    End Program d02bhfe


d02bjfe.f90

!   D02BJF Example Program Text
!   Mark 26 Release. NAG Copyright 2016.

    Module d02bjfe_mod

!     Data for D02BJF example program

!     .. Use Statements ..
      Use nag_library, Only: nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Accessibility Statements ..
      Private
      Public                           :: fcn, g, output
!     .. Parameters ..
      Integer, Parameter, Public       :: n = 3, nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp), Public, Save :: h, xend
!     n: number of differential equations
    Contains
      Subroutine output(xsol,y)

!       .. Scalar Arguments ..
        Real (Kind=nag_wp), Intent (Inout) :: xsol
!       .. Array Arguments ..
        Real (Kind=nag_wp), Intent (In) :: y(*)
!       .. Local Scalars ..
        Integer                        :: j
!       .. Intrinsic Procedures ..
        Intrinsic                      :: abs
!       .. Executable Statements ..
        Write (nout,99999) xsol, (y(j),j=1,n)
        xsol = xsol + h
!       Make sure we exactly hit xsol = xend
        If (abs(xsol-xend)<h/4.0E0_nag_wp) Then
          xsol = xend
        End If
        Return

99999   Format (1X,F8.2,3F13.4)
      End Subroutine output
      Subroutine fcn(x,y,f)

!       .. Parameters ..
        Real (Kind=nag_wp), Parameter  :: alpha = -0.032E0_nag_wp
        Real (Kind=nag_wp), Parameter  :: beta = -0.02E0_nag_wp
!       .. Scalar Arguments ..
        Real (Kind=nag_wp), Intent (In) :: x
!       .. Array Arguments ..
        Real (Kind=nag_wp), Intent (Out) :: f(*)
        Real (Kind=nag_wp), Intent (In) :: y(*)
!       .. Intrinsic Procedures ..
        Intrinsic                      :: cos, tan
!       .. Executable Statements ..
        f(1) = tan(y(3))
        f(2) = alpha*tan(y(3))/y(2) + beta*y(2)/cos(y(3))
        f(3) = alpha/y(2)**2
        Return
      End Subroutine fcn
      Function g(x,y)

!       .. Function Return Value ..
        Real (Kind=nag_wp)             :: g
!       .. Scalar Arguments ..
        Real (Kind=nag_wp), Intent (In) :: x
!       .. Array Arguments ..
        Real (Kind=nag_wp), Intent (In) :: y(*)
!       .. Executable Statements ..
        g = y(1)
        Return
      End Function g
    End Module d02bjfe_mod
    Program d02bjfe

!     D02BJF Example Main Program

!     .. Use Statements ..
      Use nag_library, Only: d02bjf, d02bjw, d02bjx, nag_wp
      Use d02bjfe_mod, Only: fcn, g, h, n, nin, nout, output, xend
!     .. Implicit None Statement ..
      Implicit None
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: tol, x, xinit
      Integer                          :: i, icase, ifail, iw, j, kinit
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: w(:), y(:), yinit(:)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: real
!     .. Executable Statements ..
      Write (nout,*) 'D02BJF Example Program Results'
      iw = 20*n
      Allocate (w(iw),y(n),yinit(n))
!     Skip heading in data file
      Read (nin,*)
!     xinit: initial x value,        xend: final x value.
!     yinit: initial solution values
      Read (nin,*) xinit, xend
      Read (nin,*) yinit(1:n)
      Read (nin,*) kinit
      Do icase = 1, 4
        Write (nout,*)
        Select Case (icase)
        Case (1)
          Write (nout,99995) icase, 'intermediate output, root-finding'
        Case (2)
          Write (nout,99995) icase, 'no intermediate output, root-finding'
        Case (3)
          Write (nout,99995) icase, 'intermediate output, no root-finding'
        Case (4)
          Write (nout,99995) icase,                                            &
            'no intermediate output, no root-finding ( integrate to XEND)'
        End Select
        Do j = 4, 5
          tol = 10.0E0_nag_wp**(-j)
          Write (nout,*)
          Write (nout,99999) ' Calculation with TOL =', tol
          x = xinit
          y(1:n) = yinit(1:n)
          If (icase/=2) Then
            Write (nout,*) '     X         Y(1)         Y(2)         Y(3)'
            h = (xend-x)/real(kinit+1,kind=nag_wp)
          End If
!         ifail: behaviour on error exit
!                =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
          ifail = 0
          Select Case (icase)
          Case (1)
            Call d02bjf(x,xend,n,y,fcn,tol,'Default',output,g,w,ifail)
            Write (nout,99998) '  Root of Y(1) = 0.0 at', x
            Write (nout,99997) '  Solution is', (y(i),i=1,n)
          Case (2)
            Call d02bjf(x,xend,n,y,fcn,tol,'Default',d02bjx,g,w,ifail)
            Write (nout,99998) '  Root of Y(1) = 0.0 at', x
            Write (nout,99997) '  Solution is', (y(i),i=1,n)
          Case (3)
            Call d02bjf(x,xend,n,y,fcn,tol,'Default',output,d02bjw,w,ifail)
          Case (4)
            Write (nout,99996) x, (y(i),i=1,n)
            Call d02bjf(x,xend,n,y,fcn,tol,'Default',d02bjx,d02bjw,w,ifail)
            Write (nout,99996) x, (y(i),i=1,n)
          End Select
        End Do
        If (icase<4) Then
          Write (nout,*)
        End If
      End Do

99999 Format (1X,A,E8.1)
99998 Format (1X,A,F7.3)
99997 Format (1X,A,3F13.4)
99996 Format (1X,F8.2,3F13.4)
99995 Format (1X,'Case ',I1,': ',A)
    End Program d02bjfe


d02cjfe.f90

!   D02CJF Example Program Text
!   Mark 26 Release. NAG Copyright 2016.

    Module d02cjfe_mod

!     Data for D02CJF example program

!     .. Use Statements ..
      Use nag_library, Only: nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Accessibility Statements ..
      Private
      Public                           :: fcn, g, output
!     .. Parameters ..
      Integer, Parameter, Public       :: n = 3, nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp), Public, Save :: h, xend
!     n: number of differential equations
    Contains
      Subroutine output(xsol,y)

!       .. Scalar Arguments ..
        Real (Kind=nag_wp), Intent (Inout) :: xsol
!       .. Array Arguments ..
        Real (Kind=nag_wp), Intent (In) :: y(*)
!       .. Local Scalars ..
        Integer                        :: j
!       .. Intrinsic Procedures ..
        Intrinsic                      :: abs
!       .. Executable Statements ..
        Write (nout,99999) xsol, (y(j),j=1,n)
        xsol = xsol + h
!       Make sure we exactly hit xsol = xend
        If (abs(xsol-xend)<h/4.0E0_nag_wp) Then
          xsol = xend
        End If
        Return

99999   Format (1X,F8.2,3F13.5)
      End Subroutine output
      Subroutine fcn(x,y,f)

!       .. Parameters ..
        Real (Kind=nag_wp), Parameter  :: alpha = -0.032E0_nag_wp
        Real (Kind=nag_wp), Parameter  :: beta = -0.02E0_nag_wp
!       .. Scalar Arguments ..
        Real (Kind=nag_wp), Intent (In) :: x
!       .. Array Arguments ..
        Real (Kind=nag_wp), Intent (Out) :: f(*)
        Real (Kind=nag_wp), Intent (In) :: y(*)
!       .. Intrinsic Procedures ..
        Intrinsic                      :: cos, tan
!       .. Executable Statements ..
        f(1) = tan(y(3))
        f(2) = alpha*tan(y(3))/y(2) + beta*y(2)/cos(y(3))
        f(3) = alpha/y(2)**2
        Return
      End Subroutine fcn
      Function g(x,y)

!       .. Function Return Value ..
        Real (Kind=nag_wp)             :: g
!       .. Scalar Arguments ..
        Real (Kind=nag_wp), Intent (In) :: x
!       .. Array Arguments ..
        Real (Kind=nag_wp), Intent (In) :: y(*)
!       .. Executable Statements ..
        g = y(1)
        Return
      End Function g
    End Module d02cjfe_mod
    Program d02cjfe

!     D02CJF Example Main Program

!     .. Use Statements ..
      Use nag_library, Only: d02cjf, d02cjw, d02cjx, nag_wp
      Use d02cjfe_mod, Only: fcn, g, h, n, nin, nout, output, xend
!     .. Implicit None Statement ..
      Implicit None
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: tol, x, xinit
      Integer                          :: i, icase, ifail, iw, j, kinit
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: w(:), y(:), yinit(:)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: real
!     .. Executable Statements ..
      Write (nout,*) 'D02CJF Example Program Results'
      iw = 21*n + 28
      Allocate (w(iw),y(n),yinit(n))
!     Skip heading in data file
      Read (nin,*)
!     xinit: initial x value, xend: final x value.
      Read (nin,*) xinit
      Read (nin,*) xend
      Read (nin,*) yinit(1:n)
      Read (nin,*) kinit
      Do icase = 1, 4
        Write (nout,*)
        Select Case (icase)
        Case (1)
          Write (nout,99995) icase, 'intermediate output, root-finding'
        Case (2)
          Write (nout,99995) icase, 'no intermediate output, root-finding'
        Case (3)
          Write (nout,99995) icase, 'intermediate output, no root-finding'
        Case (4)
          Write (nout,99995) icase,                                            &
            'no intermediate output, no root-finding ( integrate to XEND)'
        End Select
        Do j = 4, 5
          tol = 10.0E0_nag_wp**(-j)
          Write (nout,*)
          Write (nout,99999) ' Calculation with TOL =', tol
          x = xinit
          y(1:n) = yinit(1:n)
          If (icase/=2) Then
            Write (nout,*) '     X         Y(1)         Y(2)         Y(3)'
            h = (xend-x)/real(kinit+1,kind=nag_wp)
          End If
!         ifail: behaviour on error exit
!                =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
          ifail = 0
          Select Case (icase)
          Case (1)
            Call d02cjf(x,xend,n,y,fcn,tol,'Default',output,g,w,ifail)
            Write (nout,99998) '  Root of Y(1) = 0.0 at', x
            Write (nout,99997) '  Solution is', (y(i),i=1,n)
          Case (2)
            Call d02cjf(x,xend,n,y,fcn,tol,'Default',d02cjx,g,w,ifail)
            Write (nout,99998) '  Root of Y(1) = 0.0 at', x
            Write (nout,99997) '  Solution is', (y(i),i=1,n)
          Case (3)
            Call d02cjf(x,xend,n,y,fcn,tol,'Default',output,d02cjw,w,ifail)
          Case (4)
            Write (nout,99996) x, (y(i),i=1,n)
            Call d02cjf(x,xend,n,y,fcn,tol,'Default',d02cjx,d02cjw,w,ifail)
            Write (nout,99996) x, (y(i),i=1,n)
          End Select
        End Do
        If (icase<4) Then
          Write (nout,*)
        End If
      End Do

99999 Format (1X,A,E8.1)
99998 Format (1X,A,F7.3)
99997 Format (1X,A,3F13.5)
99996 Format (1X,F8.2,3F13.5)
99995 Format (1X,'Case ',I1,': ',A)
    End Program d02cjfe


d02ejfe.f90

!   D02EJF Example Program Text
!   Mark 26 Release. NAG Copyright 2016.

    Module d02ejfe_mod

!     Data for D02EJF example program

!     .. Use Statements ..
      Use nag_library, Only: nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Accessibility Statements ..
      Private
      Public                           :: fcn, g, output, pederv
!     .. Parameters ..
      Real (Kind=nag_wp), Parameter    :: alpha = 0.04_nag_wp
      Real (Kind=nag_wp), Parameter    :: beta = 1.0E4_nag_wp
      Real (Kind=nag_wp), Parameter    :: gamma = 3.0E7_nag_wp
      Real (Kind=nag_wp), Parameter    :: zero = 0.0_nag_wp
      Integer, Parameter, Public       :: n = 3, nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp), Public, Save :: h, xend
    Contains
      Subroutine fcn(x,y,f)

!       .. Scalar Arguments ..
        Real (Kind=nag_wp), Intent (In) :: x
!       .. Array Arguments ..
        Real (Kind=nag_wp), Intent (Inout) :: f(*)
        Real (Kind=nag_wp), Intent (In) :: y(*)
!       .. Executable Statements ..
        f(1) = -alpha*y(1) + beta*y(2)*y(3)
        f(2) = alpha*y(1) - beta*y(2)*y(3) - gamma*y(2)*y(2)
        f(3) = gamma*y(2)*y(2)
        Return
      End Subroutine fcn
      Subroutine pederv(x,y,pw)

!       .. Scalar Arguments ..
        Real (Kind=nag_wp), Intent (In) :: x
!       .. Array Arguments ..
        Real (Kind=nag_wp), Intent (Out) :: pw(*)
        Real (Kind=nag_wp), Intent (In) :: y(*)
!       .. Executable Statements ..
        pw(1) = -alpha
        pw(2) = alpha
        pw(3) = zero
        pw(4) = beta*y(3)
        pw(5) = -beta*y(3) - 2.0_nag_wp*gamma*y(2)
        pw(6) = 2.0_nag_wp*gamma*y(2)
        pw(7) = beta*y(2)
        pw(8) = -beta*y(2)
        pw(9) = zero
        Return
      End Subroutine pederv
      Function g(x,y)

!       .. Function Return Value ..
        Real (Kind=nag_wp)             :: g
!       .. Scalar Arguments ..
        Real (Kind=nag_wp), Intent (In) :: x
!       .. Array Arguments ..
        Real (Kind=nag_wp), Intent (In) :: y(*)
!       .. Executable Statements ..
        g = y(1) - 0.9E0_nag_wp
        Return
      End Function g
      Subroutine output(xsol,y)

!       .. Scalar Arguments ..
        Real (Kind=nag_wp), Intent (Inout) :: xsol
!       .. Array Arguments ..
        Real (Kind=nag_wp), Intent (In) :: y(*)
!       .. Local Scalars ..
        Integer                        :: j
!       .. Intrinsic Procedures ..
        Intrinsic                      :: abs
!       .. Executable Statements ..
        Write (nout,99999) xsol, (y(j),j=1,n)
        xsol = xsol + h
!       Make sure we exactly hit xsol = xend
        If (abs(xsol-xend)<h/4.0E0_nag_wp) Then
          xsol = xend
        End If
        Return

99999   Format (1X,F8.2,3F13.5)
      End Subroutine output
    End Module d02ejfe_mod
    Program d02ejfe

!     D02EJF Example Main Program

!     .. Use Statements ..
      Use nag_library, Only: d02ejf, d02ejw, d02ejx, d02ejy, nag_wp
      Use d02ejfe_mod, Only: fcn, g, h, n, nin, nout, output, pederv, xend
!     .. Implicit None Statement ..
      Implicit None
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: tol, x, xinit
      Integer                          :: i, icase, ifail, iw, j, kinit
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: w(:), y(:), yinit(:)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: real
!     .. Executable Statements ..
      Write (nout,*) 'D02EJF Example Program Results'
      iw = (12+n)*n + 50
      Allocate (w(iw),y(n),yinit(n))
!     Skip heading in data file
      Read (nin,*)
!     xinit: initial x value, xend: final x value
!     y: initial solution values
      Read (nin,*) xinit, xend
      Read (nin,*) yinit(1:n)
      Read (nin,*) kinit
      Do icase = 1, 5
        If (icase/=2) Then
          Write (nout,99995) icase, 'Jacobian internally'
        Else
          Write (nout,99995) icase, 'Jacobian by PEDERV'
        End If
        Select Case (icase)
        Case (1,2)
          Write (nout,99994) 'intermediate output, root-finding'
        Case (3)
          Write (nout,99994) 'no intermediate output, root-finding'
        Case (4)
          Write (nout,99994) 'intermediate output, no root-finding'
        Case (5)
          Write (nout,99994)                                                   &
            'no intermediate output, no root-finding (integrate to XEND)'
        End Select
        Do j = 3, 4
          tol = 10.0E0_nag_wp**(-j)
          Write (nout,99999) ' Calculation with TOL =', tol
          x = xinit
          y(1:n) = yinit(1:n)
          If (icase/=3) Then
            Write (nout,*) '     X         Y(1)         Y(2)         Y(3)'
            h = (xend-x)/real(kinit+1,kind=nag_wp)
          End If
          ifail = 0
          Select Case (icase)
          Case (1)
            Call d02ejf(x,xend,n,y,fcn,d02ejy,tol,'Default',output,g,w,iw,     &
              ifail)
            Write (nout,99998) '  Root of Y(1)-0.9 at', x
            Write (nout,99997) '  Solution is', (y(i),i=1,n)
          Case (2)
            Call d02ejf(x,xend,n,y,fcn,pederv,tol,'Default',output,g,w,iw,     &
              ifail)
            Write (nout,99998) '  Root of Y(1)-0.9 at', x
            Write (nout,99997) '  Solution is', (y(i),i=1,n)
          Case (3)
            Call d02ejf(x,xend,n,y,fcn,d02ejy,tol,'Default',d02ejx,g,w,iw,     &
              ifail)
            Write (nout,99998) '  Root of Y(1)-0.9 at', x
            Write (nout,99997) '  Solution is', (y(i),i=1,n)
          Case (4)
            ifail = 0
            Call d02ejf(x,xend,n,y,fcn,d02ejy,tol,'Default',output,d02ejw,w,   &
              iw,ifail)
          Case (5)
            Write (nout,99996) x, (y(i),i=1,n)
            Call d02ejf(x,xend,n,y,fcn,d02ejy,tol,'Default',d02ejx,d02ejw,w,   &
              iw,ifail)
            Write (nout,99996) x, (y(i),i=1,n)
          End Select
          If (tol<0.0E0_nag_wp) Then
            Write (nout,*) '  Range too short for TOL'
          End If
        End Do
        If (icase<5) Then
          Write (nout,*)
        End If
      End Do

99999 Format (/,1X,A,E8.1)
99998 Format (1X,A,F7.3)
99997 Format (1X,A,3F13.5)
99996 Format (1X,F8.2,3F13.5)
99995 Format (/,1X,'Case ',I1,': calculating ',A,',')
99994 Format (8X,A)
    End Program d02ejfe


d02gafe.f90

!   D02GAF Example Program Text
!   Mark 26 Release. NAG Copyright 2016.

    Module d02gafe_mod

!     Data for D02GAF example program

!     .. Use Statements ..
      Use nag_library, Only: nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Accessibility Statements ..
      Private
      Public                           :: fcn
!     .. Parameters ..
      Real (Kind=nag_wp), Parameter, Public :: one = 1.0_nag_wp
      Real (Kind=nag_wp), Parameter, Public :: zero = 0.0_nag_wp
      Integer, Parameter, Public       :: iset = 1, n = 4, nin = 5, nout = 6
    Contains
      Subroutine fcn(x,y,f)

!       .. Scalar Arguments ..
        Real (Kind=nag_wp), Intent (In) :: x
!       .. Array Arguments ..
        Real (Kind=nag_wp), Intent (Out) :: f(*)
        Real (Kind=nag_wp), Intent (In) :: y(*)
!       .. Executable Statements ..
        f(1) = y(2)
        f(2) = y(3)
        f(3) = -y(1)*y(3) - y(4)*(1.0E0_nag_wp-y(2)*y(2))
        f(4) = 0.0_nag_wp
        Return
      End Subroutine fcn
    End Module d02gafe_mod
    Program d02gafe

!     D02GAF Example Main Program

!     .. Use Statements ..
      Use nag_library, Only: d02gaf, nag_wp, x04abf
      Use d02gafe_mod, Only: fcn, iset, n, nin, nout, one, zero
!     .. Implicit None Statement ..
      Implicit None
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: a, b, beta, h, tol
      Integer                          :: i, ifail, j, k, liw, lw, mnp, np,    &
                                          outchn
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: u(:,:), v(:,:), w(:), x(:), y(:,:)
      Integer, Allocatable             :: iw(:)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: real
!     .. Executable Statements ..
      Write (nout,*) 'D02GAF Example Program Results'
!     Skip heading in data file
      Read (nin,*)
!     n: number of differential equations
!     mnp: maximum permitted number of mesh points.
      Read (nin,*) mnp
      liw = mnp*(2*n+1) + n*n + 4*n + 2
      lw = mnp*(3*n*n+6*n+2) + 4*n*n + 4*n
      Allocate (iw(liw),u(n,2),v(n,2),w(lw),x(mnp),y(n,mnp))
!     tol: positive absolute error tolerance
!     np : determines whether a default or user-supplied mesh is used.
!     a  : left-hand boundary point, b: right-hand boundary point.
      Read (nin,*) tol
      Read (nin,*) np
      Read (nin,*) a, b
      outchn = nout
      Call x04abf(iset,outchn)
      beta = zero
      u(1:n,1:2) = zero
      v(1:n,1:2) = zero
      v(1,2) = one
      v(3,1) = one
      v(3,2) = one
      v(4,2) = one
      u(2,2) = one
      u(1,2) = b
      x(1) = a
      h = (b-a)/real(np-1,kind=nag_wp)
      Do i = 2, np - 1
        x(i) = x(i-1) + h
      End Do
      x(np) = b
      beta = zero
loop: Do k = 1, 2
        u(4,1) = beta
        u(4,2) = beta
!       ifail: behaviour on error exit
!              =1 for quiet-soft exit
!       * Set ifail to 111 to obtain monitoring information *
        ifail = 1
        Call d02gaf(u,v,n,a,b,tol,fcn,mnp,x,y,np,w,lw,iw,liw,ifail)

        If (ifail>=0) Then
          Write (nout,99999) 'Problem with BETA = ', beta
        End If
        If (ifail==0 .Or. ifail==3) Then
          Write (nout,*)
          If (ifail==3) Then
            Write (nout,*) ' IFAIL = 3'
          End If
          Write (nout,99998) np
          Write (nout,99997)
          Write (nout,99996)(x(i),(y(j,i),j=1,3),i=1,np)
          beta = beta + 0.2E0_nag_wp
        Else
          Write (nout,99995) ifail
          Exit loop
        End If
      End Do loop

99999 Format (/,1X,A,F7.2)
99998 Format (1X,'Solution on final mesh of ',I2,' points')
99997 Format (1X,'      X(I)        Y1(I)        Y2(I)        Y3(I)')
99996 Format (1X,F11.3,3F13.4)
99995 Format (1X,/,1X,' ** D02GAF returned with IFAIL = ',I5)
    End Program d02gafe


d02gbfe.f90

!   D02GBF Example Program Text
!   Mark 26 Release. NAG Copyright 2016.

    Module d02gbfe_mod

!     Data for D02GBF example program

!     .. Use Statements ..
      Use nag_library, Only: nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Accessibility Statements ..
      Private
      Public                           :: fcnf, fcng
!     .. Parameters ..
      Real (Kind=nag_wp), Parameter, Public :: one = 1.0_nag_wp
      Real (Kind=nag_wp), Parameter, Public :: zero = 0.0_nag_wp
      Integer, Parameter, Public       :: iset = 1, n = 2, nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp), Public, Save :: eps
    Contains
      Subroutine fcnf(x,f)

!       .. Scalar Arguments ..
        Real (Kind=nag_wp), Intent (In) :: x
!       .. Array Arguments ..
        Real (Kind=nag_wp), Intent (Out) :: f(*)
!       .. Executable Statements ..
        f(1:2) = 0.0E0_nag_wp
        f(3) = 1.0E0_nag_wp
        f(4) = -1.0E0_nag_wp/eps
        Return
      End Subroutine fcnf
      Subroutine fcng(x,g)

!       .. Scalar Arguments ..
        Real (Kind=nag_wp), Intent (In) :: x
!       .. Array Arguments ..
        Real (Kind=nag_wp), Intent (Out) :: g(*)
!       .. Executable Statements ..
        g(1:2) = 0.0E0_nag_wp
        Return
      End Subroutine fcng
    End Module d02gbfe_mod
    Program d02gbfe

!     D02GBF Example Main Program

!     .. Use Statements ..
      Use nag_library, Only: d02gbf, nag_wp, x04abf
      Use d02gbfe_mod, Only: eps, fcnf, fcng, iset, n, nin, nout, one, zero
!     .. Implicit None Statement ..
      Implicit None
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: a, b, tol
      Integer                          :: i, ifail, j, liw, lw, mnp, np,       &
                                          outchn
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: c(:,:), d(:,:), gam(:), w(:), x(:),  &
                                          y(:,:)
      Integer, Allocatable             :: iw(:)
!     .. Executable Statements ..
      Write (nout,*) 'D02GBF Example Program Results'
!     Skip heading in data file
      Read (nin,*)
!     mnp: maximum permitted number of mesh points.
      Read (nin,*) mnp
      liw = mnp*(2*n+1) + n
      lw = mnp*(3*n*n+5*n+2) + 3*n*n + 5*n
      Allocate (iw(liw),c(n,n),d(n,n),gam(n),w(lw),x(mnp),y(n,mnp))
!     tol: positive absolute error tolerance
!     np : determines whether a default or user-supplied mesh is used.
!     a  : left-hand boundary point, b: right-hand boundary point.
      Read (nin,*) tol
      Read (nin,*) np
      Read (nin,*) a, b
      outchn = nout
      Call x04abf(iset,outchn)
      gam(1:n) = zero
      c(1:n,1:n) = zero
      d(1:n,1:n) = zero
      c(1,1) = one
      d(2,1) = one
      gam(2) = one
loop: Do i = 1, 2
        eps = 10.0E0_nag_wp**(-i)
        Write (nout,*)
!       ifail: behaviour on error exit
!              =1 for quiet-soft exit
!       * Set ifail to 111 to obtain monitoring information *
        ifail = 1
        Call d02gbf(a,b,n,tol,fcnf,fcng,c,d,gam,mnp,x,y,np,w,lw,iw,liw,ifail)

        If (ifail>=0) Then
          Write (nout,99999) 'Problem with epsilon = ', eps
        End If
        If (ifail==0) Then
          Write (nout,99998) np
          Write (nout,*) '       X(I)     Y(1,I)'
          Write (nout,99997)(x(j),y(1,j),j=1,np)
        Else
          Write (nout,99996) ifail
          Exit loop
        End If
      End Do loop

99999 Format (1X,A,E10.2)
99998 Format (/,1X,'Approximate solution on final mesh of ',I2,' points')
99997 Format (1X,2F11.4)
99996 Format (1X,/,1X,' ** D02GBF returned with IFAIL = ',I5)
    End Program d02gbfe


d02hafe.f90

!   D02HAF Example Program Text
!   Mark 26 Release. NAG Copyright 2016.

    Module d02hafe_mod

!     D02HAF Example Program Module:
!            Parameters and User-defined Routines

!     .. Use Statements ..
      Use nag_library, Only: nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Accessibility Statements ..
      Private
      Public                           :: fcn
!     .. Parameters ..
      Real (Kind=nag_wp), Parameter, Public :: one = 1.0_nag_wp
      Real (Kind=nag_wp), Parameter, Public :: zero = 0.0_nag_wp
      Integer, Parameter, Public       :: iset = 1, n = 3, nin = 5, nout = 6
      Integer, Parameter, Public       :: sdw = 3*n + 17 + max(11,n)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: max
    Contains
      Subroutine fcn(x,y,f)

!       .. Scalar Arguments ..
        Real (Kind=nag_wp), Intent (In) :: x
!       .. Array Arguments ..
        Real (Kind=nag_wp), Intent (Out) :: f(*)
        Real (Kind=nag_wp), Intent (In) :: y(*)
!       .. Intrinsic Procedures ..
        Intrinsic                      :: cos, tan
!       .. Executable Statements ..
        f(1) = tan(y(3))
        f(2) = -0.032_nag_wp*tan(y(3))/y(2) - 0.02_nag_wp*y(2)/cos(y(3))
        f(3) = -0.032_nag_wp/y(2)**2
        Return
      End Subroutine fcn
    End Module d02hafe_mod

    Program d02hafe

!     D02HAF Example Main Program

!     .. Use Statements ..
      Use nag_library, Only: d02haf, nag_wp, x04abf
      Use d02hafe_mod, Only: fcn, iset, n, nin, nout, one, sdw, zero
!     .. Implicit None Statement ..
      Implicit None
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: a, b, dx, tol
      Integer                          :: i, ifail, l, m1, outchn
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: soln(:,:), x(:)
      Real (Kind=nag_wp)               :: u(n,2), v(n,2), w(n,sdw)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: real
!     .. Executable Statements ..
      Write (nout,*) 'D02HAF Example Program Results'
!     Skip heading in data file
      Read (nin,*)
!     m1: solution is returned and printed for m1-1 grid points on [a, b].
      Read (nin,*) m1
      Allocate (soln(n,m1),x(m1))
!     a: left-hand boundary point, b: right-hand boundary point.
      Read (nin,*) a, b

!     Evaluate solution points x.
      x(1) = a
      dx = (b-a)/real(m1-1,kind=nag_wp)
      Do i = 2, m1 - 1
        x(i) = x(i-1) + dx
      End Do
      x(m1) = b

!     Set output channel for monitoring information.
      outchn = nout
      Call x04abf(iset,outchn)

!     Flag known (zero) and estimated (one) values in u
      v(1:2,1:2) = zero
      v(2,2) = one
      v(3,1:2) = one
!     Set known values of u
      u(1,1:2) = zero
      u(2,1) = 0.5_nag_wp

loop: Do l = 4, 5
        tol = 5.0_nag_wp*10.0_nag_wp**(-l)
        Write (nout,*)
!       Set estimates of u
        u(2,2) = 0.46_nag_wp
        u(3,1) = 1.15_nag_wp
        u(3,2) = -1.2_nag_wp

!       ifail: behaviour on error exit
!              =1 for quiet-soft exit
!       * Set ifail to 111 to obtain monitoring information *
        ifail = 1
        Call d02haf(u,v,n,a,b,tol,fcn,soln,m1,w,sdw,ifail)

        If (ifail>=0) Then
          Write (nout,99999) 'Results with TOL = ', tol
          Write (nout,*)
          If (ifail==0) Then
            Write (nout,*) ' X-value and final solution'
            Do i = 1, m1
              If (l==4) Then
                Write (nout,99998) x(i), soln(1:n,i)
              Else
                Write (nout,99997) x(i), soln(1:n,i)
              End If
            End Do
          Else
            Write (nout,99996) ' IFAIL =', ifail
          End If
        Else
          Write (nout,99995) ifail
          Exit loop
        End If
      End Do loop

99999 Format (1X,A,E10.3)
99998 Format (1X,F4.1,3(1X,F9.3))
99997 Format (1X,F4.1,1X,3F10.4)
99996 Format (1X,A,I4)
99995 Format (1X,/,1X,' ** D02HAF returned with IFAIL = ',I5)
    End Program d02hafe


d02hbfe.f90

!   D02HBF Example Program Text
!   Mark 26 Release. NAG Copyright 2016.

    Module d02hbfe_mod

!     Data for D02HBF example programs

!     .. Use Statements ..
      Use nag_library, Only: nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Accessibility Statements ..
      Private
      Public                           :: bc1, bc2, fcn1, fcn2, range1, range2
!     .. Parameters ..
      Integer, Parameter, Public       :: iset = 1, nin = 5, nout = 6
    Contains
      Subroutine fcn1(x,y,f,p)

!       .. Scalar Arguments ..
        Real (Kind=nag_wp), Intent (In) :: x
!       .. Array Arguments ..
        Real (Kind=nag_wp), Intent (Out) :: f(*)
        Real (Kind=nag_wp), Intent (In) :: p(*), y(*)
!       .. Executable Statements ..
        f(1) = y(2)
        f(2) = (y(1)**3-y(2))/(2.0E0_nag_wp*x)
        Return
      End Subroutine fcn1
      Subroutine range1(a,b,p)

!       .. Scalar Arguments ..
        Real (Kind=nag_wp), Intent (Out) :: a, b
!       .. Array Arguments ..
        Real (Kind=nag_wp), Intent (In) :: p(*)
!       .. Executable Statements ..
        a = 0.1E0_nag_wp
        b = 16.0E0_nag_wp
        Return
      End Subroutine range1
      Subroutine bc1(g1,g2,p)

!       .. Array Arguments ..
        Real (Kind=nag_wp), Intent (Out) :: g1(*), g2(*)
        Real (Kind=nag_wp), Intent (In) :: p(*)
!       .. Local Scalars ..
        Real (Kind=nag_wp)             :: z
!       .. Intrinsic Procedures ..
        Intrinsic                      :: sqrt
!       .. Executable Statements ..
        z = 0.1E0_nag_wp
        g1(1) = 0.1E0_nag_wp + p(1)*sqrt(z)*0.1E0_nag_wp + 0.01E0_nag_wp*z
        g1(2) = p(1)*0.05E0_nag_wp/sqrt(z) + 0.01E0_nag_wp
        g2(1) = 1.0E0_nag_wp/6.0E0_nag_wp
        g2(2) = p(2)
        Return
      End Subroutine bc1
      Subroutine fcn2(x,y,f,p)

!       .. Scalar Arguments ..
        Real (Kind=nag_wp), Intent (In) :: x
!       .. Array Arguments ..
        Real (Kind=nag_wp), Intent (Out) :: f(*)
        Real (Kind=nag_wp), Intent (In) :: p(*), y(*)
!       .. Intrinsic Procedures ..
        Intrinsic                      :: cos, tan
!       .. Executable Statements ..
        f(1) = tan(y(3))
        f(2) = -p(1)*tan(y(3))/y(2) - 0.00002E0_nag_wp*y(2)/cos(y(3))
        f(3) = -p(1)/y(2)**2
        Return
      End Subroutine fcn2
      Subroutine range2(a,b,p)

!       .. Scalar Arguments ..
        Real (Kind=nag_wp), Intent (Out) :: a, b
!       .. Array Arguments ..
        Real (Kind=nag_wp), Intent (In) :: p(*)
!       .. Executable Statements ..
        a = 0.0E0_nag_wp
        b = p(2)
        Return
      End Subroutine range2
      Subroutine bc2(g1,g2,p)

!       .. Array Arguments ..
        Real (Kind=nag_wp), Intent (Out) :: g1(*), g2(*)
        Real (Kind=nag_wp), Intent (In) :: p(*)
!       .. Executable Statements ..
        g1(1) = 0.0E0_nag_wp
        g1(2) = 500.0E0_nag_wp
        g1(3) = 0.5E0_nag_wp
        g2(1) = 0.0E0_nag_wp
        g2(2) = 450.0E0_nag_wp
        g2(3) = p(3)
        Return
      End Subroutine bc2
    End Module d02hbfe_mod
    Program d02hbfe

!     D02HBF Example Main Program

!     .. Use Statements ..
      Use d02hbfe_mod, Only: nout
!     .. Implicit None Statement ..
      Implicit None
!     .. Executable Statements ..
      Write (nout,*) 'D02HBF Example Program Results'

      Call ex1

      Call ex2

    Contains
      Subroutine ex1

!       .. Use Statements ..
        Use nag_library, Only: d02hbf, nag_wp, x04abf
        Use d02hbfe_mod, Only: bc1, fcn1, iset, nin, range1
!       .. Local Scalars ..
        Real (Kind=nag_wp)             :: h, x, x1, xh
        Integer                        :: i, ifail, m1, n, n1, outchn, sdw
!       .. Local Arrays ..
        Real (Kind=nag_wp), Allocatable :: e(:), p(:), pe(:), soln(:,:),       &
                                          w(:,:)
!       .. Intrinsic Procedures ..
        Intrinsic                      :: real
!       .. Executable Statements ..
!       Skip heading in data file
        Read (nin,*)
!       m1: controls exit values,  n: number of differential equations,
!       n1: number of parameters.
        Read (nin,*) m1, n, n1
        sdw = 3*n + 14 + 11
        Allocate (e(n),p(n1),pe(n1),soln(n,m1),w(n,sdw))
        Write (nout,*)
        outchn = nout
        Write (nout,*)
        Call x04abf(iset,outchn)
!       p: estimates for the parameters p,  e: bound on the local error.
        Read (nin,*) p(1:n1)
        Read (nin,*) pe(1:n1)
        Read (nin,*) e(1:n)

        Write (nout,*) 'Case 1'
        Write (nout,*)
!       ifail: behaviour on error exit
!              =1 for quiet-soft exit
!       * Set ifail to 111 to obtain monitoring information *
        ifail = 1
        Call d02hbf(p,n1,pe,e,n,soln,m1,fcn1,bc1,range1,w,sdw,ifail)

        If (ifail==0) Then
          Write (nout,*) 'Final parameters'
          Write (nout,99999)(p(i),i=1,n1)
          Write (nout,*)
          Write (nout,*) 'Final solution'
          Write (nout,*) 'X-value     Components of solution'
          Call range1(x,x1,p)
          h = (x1-x)/real(m1-1,kind=nag_wp)
          xh = x
          Do i = 1, m1
            Write (nout,99998) xh, soln(1:n,i)
            xh = xh + h
          End Do
        Else
          Write (nout,99996) ifail
          If (ifail>1 .And. ifail<=5) Then
            Write (nout,99997) w(1,2), (w(i,1),i=1,n)
          End If
        End If

        Return

99999   Format (1X,1P,3E15.3)
99998   Format (1X,F7.2,2F13.4)
99997   Format (/,1X,'W(1,2) = ',F9.4,' W(.,1) = ',10E10.3)
99996   Format (1X,/,1X,' ** D02HBF returned with IFAIL = ',I5)
      End Subroutine ex1
      Subroutine ex2

!       .. Use Statements ..
        Use nag_library, Only: d02hbf, nag_wp, x04abf
        Use d02hbfe_mod, Only: bc2, fcn2, iset, nin, range2
!       .. Local Scalars ..
        Real (Kind=nag_wp)             :: h, x, x1, xh
        Integer                        :: i, ifail, m1, n, n1, outchn, sdw
!       .. Local Arrays ..
        Real (Kind=nag_wp), Allocatable :: e(:), p(:), pe(:), soln(:,:),       &
                                          w(:,:)
!       .. Intrinsic Procedures ..
        Intrinsic                      :: real
!       .. Executable Statements ..
        Read (nin,*)
!       m1: controls exit values,  n: number of differential equations,
!       n1: number of parameters.
        Read (nin,*) m1, n, n1
        sdw = 3*n + 14 + 11
        Allocate (e(n),p(n1),pe(n1),soln(n,m1),w(n,sdw))
        outchn = nout
        Call x04abf(iset,outchn)
!       p: estimates for the parameters p,  e: bound on the local error.
        Read (nin,*) p(1:n1)
        Read (nin,*) pe(1:n1)
        Read (nin,*) e(1:n)

        Write (nout,*)
        Write (nout,*)
        Write (nout,*) 'Case 2'
        Write (nout,*)
!       ifail: behaviour on error exit
!              =1 for quiet-soft exit
!       * Set ifail to 111 to obtain monitoring information *
        ifail = 1
        Call d02hbf(p,n1,pe,e,n,soln,m1,fcn2,bc2,range2,w,sdw,ifail)

        If (ifail==0) Then
          Write (nout,*) 'Final parameters'
          Write (nout,99999)(p(i),i=1,n1)
          Write (nout,*)
          Write (nout,*) 'Final solution'
          Write (nout,*) 'X-value     Components of solution'
          Call range2(x,x1,p)
          h = (x1-x)/real(m1-1,kind=nag_wp)
          xh = x
          Do i = 1, m1
            Write (nout,99998) xh, soln(1:n,i)
            xh = xh + h
          End Do
        Else
          Write (nout,99996) ifail
          If (ifail>1 .And. ifail<=5) Then
            Write (nout,99997) w(1,2), (w(i,1),i=1,n)
          End If
        End If

        Return

99999   Format (1X,1P,3E15.3)
99998   Format (1X,F7.0,2F13.1,F13.3)
99997   Format (/,1X,'W(1,2) = ',F9.4,' W(.,1) = ',10E10.3)
99996   Format (1X,/,1X,' ** D02HBF returned with IFAIL = ',I5)
      End Subroutine ex2
    End Program d02hbfe


d02jafe.f90

!   D02JAF Example Program Text
!   Mark 26 Release. NAG Copyright 2016.

    Module d02jafe_mod

!     D02JAF Example Program Module:
!            Parameters and User-defined Routines

!     .. Use Statements ..
      Use nag_library, Only: nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Accessibility Statements ..
      Private
      Public                           :: bc, cf
!     .. Parameters ..
      Integer, Parameter, Public       :: nin = 5, nout = 6
    Contains
      Function cf(j,x)

!       .. Function Return Value ..
        Real (Kind=nag_wp)             :: cf
!       .. Scalar Arguments ..
        Real (Kind=nag_wp), Intent (In) :: x
        Integer, Intent (In)           :: j
!       .. Executable Statements ..
        If (j==2) Then
          cf = 0.0E0_nag_wp
        Else
          cf = 1.0E0_nag_wp
        End If
        Return
      End Function cf

      Subroutine bc(i,j,rhs)

!       .. Scalar Arguments ..
        Real (Kind=nag_wp), Intent (Out) :: rhs
        Integer, Intent (In)           :: i
        Integer, Intent (Out)          :: j
!       .. Executable Statements ..
        rhs = 0.0E0_nag_wp
        If (i==1) Then
          j = 1
        Else
          j = -1
        End If
        Return
      End Subroutine bc
    End Module d02jafe_mod

    Program d02jafe

!     D02JAF Example Main Program

!     .. Use Statements ..
      Use nag_library, Only: d02jaf, e02akf, nag_wp
      Use d02jafe_mod, Only: bc, cf, nin, nout
!     .. Implicit None Statement ..
      Implicit None
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: dx, x, x0, x1, y
      Integer                          :: i, ia1, ifail, k1, k1max, kp, kpmax, &
                                          lw, m, n
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: c(:), w(:)
      Integer, Allocatable             :: iw(:)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: real
!     .. Executable Statements ..
      Write (nout,*) 'D02JAF Example Program Results'
!     Skip heading in data file
      Read (nin,*)
!     n: order of the differential equation
!     k1: number of coefficients to be returned
!     kp: number of collocation points
      Read (nin,*) n, k1max, kpmax
      lw = 2*(kpmax+n)*(k1max+1) + 7*k1max
      Allocate (iw(k1max),c(k1max),w(lw))
!     x0: left-hand boundary, x1: right-hand boundary.
      Read (nin,*) x0, x1
      Write (nout,*)
      Write (nout,*) ' KP  K1   Chebyshev coefficients'
      Do kp = 10, kpmax, 5
        Do k1 = 4, k1max, 2

!         ifail: behaviour on error exit
!                =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
          ifail = 0
          Call d02jaf(n,cf,bc,x0,x1,k1,kp,c,w,lw,iw,ifail)

          Write (nout,99999) kp, k1, c(1:k1)
        End Do
      End Do
      k1 = 8
      m = 9
      ia1 = 1
      Write (nout,*)
      Write (nout,99998) 'Last computed solution evaluated at', m,             &
        ' equally spaced points'
      Write (nout,*)
      Write (nout,*) '      X         Y'
      dx = (x1-x0)/real(m-1,kind=nag_wp)
      x = x0
      Do i = 1, m
        ifail = 0
        Call e02akf(k1,x0,x1,c,ia1,k1max,x,y,ifail)

        Write (nout,99997) x, y
        x = x + dx
      End Do

99999 Format (1X,2(I3,1X),8F8.4)
99998 Format (1X,A,I5,A)
99997 Format (1X,2F10.4)
    End Program d02jafe


d02jbfe.f90

!   D02JBF Example Program Text
!   Mark 26 Release. NAG Copyright 2016.

    Module d02jbfe_mod

!     D02JBF Example Program Module:
!            Parameters and User-defined Routines

!     .. Use Statements ..
      Use nag_library, Only: nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Accessibility Statements ..
      Private
      Public                           :: bc, cf
!     .. Parameters ..
      Integer, Parameter, Public       :: nin = 5, nout = 6
    Contains
      Function cf(i,j,x)

!       .. Function Return Value ..
        Real (Kind=nag_wp)             :: cf
!       .. Parameters ..
        Integer, Parameter             :: n = 2
        Real (Kind=nag_wp), Parameter  :: a(n,n) = reshape((/0.0E0_nag_wp,     &
                                          -1.0E0_nag_wp,1.0E0_nag_wp,          &
                                          0.0E0_nag_wp/),(/n,n/))
        Real (Kind=nag_wp), Parameter  :: r(n) = (/0.0E0_nag_wp,1.0E0_nag_wp/)
!       .. Scalar Arguments ..
        Real (Kind=nag_wp), Intent (In) :: x
        Integer, Intent (In)           :: i, j
!       .. Intrinsic Procedures ..
        Intrinsic                      :: reshape
!       .. Executable Statements ..
        If (j>0) Then
          cf = a(i,j)
        End If
        If (j==0) Then
          cf = r(i)
        End If
        Return
      End Function cf

      Subroutine bc(i,j,rhs)

!       .. Scalar Arguments ..
        Real (Kind=nag_wp), Intent (Out) :: rhs
        Integer, Intent (In)           :: i
        Integer, Intent (Out)          :: j
!       .. Executable Statements ..
        rhs = 0.0E0_nag_wp
        If (i>1) Then
          j = -1
        Else
          j = 1
        End If
        Return
      End Subroutine bc
    End Module d02jbfe_mod

    Program d02jbfe

!     D02JBF Example Main Program

!     .. Use Statements ..
      Use nag_library, Only: d02jbf, e02akf, nag_wp
      Use d02jbfe_mod, Only: bc, cf, nin, nout
!     .. Implicit None Statement ..
      Implicit None
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: dx, x, x0, x1
      Integer                          :: i, ia1, ifail, j, k1, k1max, kp,     &
                                          kpmax, ldc, liw, lw, m, n
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: c(:,:), w(:), y(:)
      Integer, Allocatable             :: iw(:)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: real
!     .. Executable Statements ..
      Write (nout,*) 'D02JBF Example Program Results'
!     Skip heading in data file
      Read (nin,*)
!     n: order of the system of differential equations
!     k1: number of coefficients to be returned
!     kp: number of collocation points
      Read (nin,*) n, k1max, kpmax
      ldc = k1max
      liw = n*(k1max+2)
      lw = 2*n*(kpmax+1)*(n*k1max+1) + 7*n*k1max
      Allocate (iw(liw),c(ldc,n),w(lw),y(n))
!     x0: left-hand boundary, x1: right-hand boundary.
      Read (nin,*) x0, x1
      Write (nout,*)
      Write (nout,*) ' KP  K1   Chebyshev coefficients'
      Do kp = 10, kpmax, 5
        Do k1 = 4, k1max, 2

!         ifail: behaviour on error exit
!                =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
          ifail = 0
          Call d02jbf(n,cf,bc,x0,x1,k1,kp,c,ldc,w,lw,iw,liw,ifail)

          Write (nout,99999) kp, k1, c(1:k1,1)
          Write (nout,99998)(c(1:k1,j),j=2,n)
          Write (nout,*)
        End Do
      End Do
      k1 = 8
      m = 9
      ia1 = 1
      Write (nout,99997) 'Last computed solution evaluated at', m,             &
        '  equally spaced points'
      Write (nout,*)
      Write (nout,99996) '      X ', (j,j=1,n)
      dx = (x1-x0)/real(m-1,kind=nag_wp)
      x = x0
      Do i = 1, m
        Do j = 1, n

          ifail = 0
          Call e02akf(k1,x0,x1,c(1,j),ia1,ldc,x,y(j),ifail)

        End Do
        Write (nout,99995) x, y(1:n)
        x = x + dx
      End Do

99999 Format (1X,2(I3,1X),8F8.4)
99998 Format (9X,8F8.4)
99997 Format (1X,A,I5,A)
99996 Format (1X,A,2('      Y(',I1,')'))
99995 Format (1X,3F10.4)
    End Program d02jbfe


d02kafe.f90

!   D02KAF Example Program Text
!   Mark 26 Release. NAG Copyright 2016.

    Module d02kafe_mod

!     Data for D02KAF example program

!     .. Use Statements ..
      Use nag_library, Only: nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Accessibility Statements ..
      Private
      Public                           :: coeffn, monit
!     .. Parameters ..
      Real (Kind=nag_wp), Parameter, Public :: one = 1.0_nag_wp
      Real (Kind=nag_wp), Parameter, Public :: zero = 0.0_nag_wp
      Real (Kind=nag_wp), Parameter    :: two = 2.0_nag_wp
      Integer, Parameter, Public       :: nin = 5, nout = 6, qq = 5
    Contains
      Subroutine coeffn(p,q,dqdl,x,elam,jint)

!       .. Scalar Arguments ..
        Real (Kind=nag_wp), Intent (Out) :: dqdl, p, q
        Real (Kind=nag_wp), Intent (In) :: elam, x
        Integer, Intent (In)           :: jint
!       .. Intrinsic Procedures ..
        Intrinsic                      :: cos, real
!       .. Executable Statements ..
        p = one
        dqdl = one
        q = elam - two*real(qq,kind=nag_wp)*cos(two*x)
        Return
      End Subroutine coeffn
      Subroutine monit(nit,iflag,elam,finfo)

!       .. Scalar Arguments ..
        Real (Kind=nag_wp), Intent (In) :: elam
        Integer, Intent (In)           :: iflag, nit
!       .. Array Arguments ..
        Real (Kind=nag_wp), Intent (In) :: finfo(15)
!       .. Executable Statements ..
        If (nit==14) Then
          Write (nout,*)
          Write (nout,*) 'Output from MONIT'
        End If
        Write (nout,99999) nit, iflag, elam, finfo(1:4)
        Return

99999   Format (1X,2I4,F10.3,2E12.2,2F8.1)
      End Subroutine monit
    End Module d02kafe_mod
    Program d02kafe

!     D02KAF Example Main Program

!     .. Use Statements ..
      Use nag_library, Only: d02kaf, nag_wp
      Use d02kafe_mod, Only: coeffn, monit, nin, nout, one, qq, zero
!     .. Implicit None Statement ..
      Implicit None
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: delam, delam1, elam, elam1, tol, xl, &
                                          xr
      Integer                          :: i, ifail, k
!     .. Local Arrays ..
      Real (Kind=nag_wp)               :: bcond(3,2)
!     .. Executable Statements ..
      Write (nout,*) 'D02KAF Example Program Results'
!     Skip heading in data file
      Read (nin,*)
!     xl: left-hand end point,  xr: right-hand end point,
!     k: index of the required eigenvalue
!     elam1: initial estimate of the eigenvalue
!     delam1: initial search step
      Read (nin,*) xl, xr
      Read (nin,*) k
      Read (nin,*) elam1, delam1
      bcond(1,1:2) = one
      bcond(2,1:2) = zero
      Do i = 5, 6
        tol = 10.0_nag_wp**(-i)
        elam = elam1
        delam = delam1

!       ifail: behaviour on error exit
!              =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
        ifail = 0
        Call d02kaf(xl,xr,coeffn,bcond,k,tol,elam,delam,monit,ifail)

        Write (nout,*)
        Write (nout,99999) 'Calculation with TOL =', tol
        Write (nout,*)
        Write (nout,*) ' Final results'
        Write (nout,*)
        Write (nout,99998) k, qq, elam, delam
        Write (nout,99997) bcond(3,1), bcond(3,2)
        Write (nout,*)
      End Do

99999 Format (1X,A,E16.4)
99998 Format (1X,' K =',I3,'  QQ =',I3,'  ELAM =',F12.3,'    DELAM =',E12.2)
99997 Format (1X,' BCOND(3,1) =',E12.4,'    BCOND(3,2) =',E12.4)
    End Program d02kafe


d02kdfe.f90

!   D02KDF Example Program Text
!   Mark 26 Release. NAG Copyright 2016.

    Module d02kdfe_mod

!     Data for D02KDF example program

!     .. Use Statements ..
      Use nag_library, Only: nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Accessibility Statements ..
      Private
      Public                           :: bdyval, coeffn, monit
!     .. Parameters ..
      Real (Kind=nag_wp), Parameter    :: one = 1.0_nag_wp
      Real (Kind=nag_wp), Parameter    :: two = 2.0_nag_wp
      Integer, Parameter, Public       :: nin = 5, nout = 6
    Contains
      Subroutine coeffn(p,q,dqdl,x,elam,jint)

!       .. Scalar Arguments ..
        Real (Kind=nag_wp), Intent (Out) :: dqdl, p, q
        Real (Kind=nag_wp), Intent (In) :: elam, x
        Integer, Intent (In)           :: jint
!       .. Executable Statements ..
        p = one
        q = elam - x - two/(x*x)
        dqdl = one
        Return
      End Subroutine coeffn
      Subroutine bdyval(xl,xr,elam,yl,yr)

!       .. Scalar Arguments ..
        Real (Kind=nag_wp), Intent (In) :: elam, xl, xr
!       .. Array Arguments ..
        Real (Kind=nag_wp), Intent (Out) :: yl(3), yr(3)
!       .. Intrinsic Procedures ..
        Intrinsic                      :: sqrt
!       .. Executable Statements ..
        yl(1) = xl
        yl(2) = two
        yr(1) = one
        yr(2) = -sqrt(xr-elam)
        Return
      End Subroutine bdyval
      Subroutine monit(nit,iflag,elam,finfo)

!       .. Scalar Arguments ..
        Real (Kind=nag_wp), Intent (In) :: elam
        Integer, Intent (In)           :: iflag, nit
!       .. Array Arguments ..
        Real (Kind=nag_wp), Intent (In) :: finfo(15)
!       .. Executable Statements ..
        If (nit==-1) Then
          Write (nout,*)
          Write (nout,*) 'Output from MONIT'
        End If
        Write (nout,99999) nit, iflag, elam, finfo(1:4)
        Return

99999   Format (1X,2I4,F10.3,2E12.2,2F8.1)
      End Subroutine monit
    End Module d02kdfe_mod
    Program d02kdfe

!     D02KDF Example Main Program

!     .. Use Statements ..
      Use nag_library, Only: d02kdf, nag_wp
      Use d02kdfe_mod, Only: bdyval, coeffn, monit, nin, nout
!     .. Implicit None Statement ..
      Implicit None
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: delam, elam, tol
      Integer                          :: ifail, k, m, maxfun, maxit
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: hmax(:,:), xpoint(:)
!     .. Executable Statements ..
      Write (nout,*) 'D02KDF Example Program Results'
      Write (nout,*)
!     Skip heading in data file
      Read (nin,*)
!     m: number of points in xpoint
      Read (nin,*) m
      Allocate (hmax(2,m),xpoint(m))
!     xpoint: points where the boundary conditions are to be imposed
!              and any break points,
!     tol: tolerance parameter which determines the accuracy of the
!           computed eigenvalue,
!     k: index of the required eigenvalue,  hmax: maximum step size,
!     elam: initial estimate of the eigenvalue,  delam: initial search step,
!     maxit: number of root-finding iterations allowed,
!     maxfun: number of calls to coeffn in any one root-finding iteration.
      Read (nin,*) xpoint(1:m)
      Read (nin,*) tol
      Read (nin,*) k
      Read (nin,*) elam, delam
      Read (nin,*) hmax(1,1:m-3)
      Read (nin,*) maxit, maxfun

!     ifail: behaviour on error exit
!             =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
      ifail = 0
      Call d02kdf(xpoint,m,coeffn,bdyval,k,tol,elam,delam,hmax,maxit,maxfun,   &
        monit,ifail)

      Write (nout,*) 'A singular problem'
      Write (nout,*)
      Write (nout,*) 'Final results'
      Write (nout,*)
      Write (nout,99999) k, elam, delam
      Write (nout,99998) hmax(1,m-1), hmax(1,m)

99999 Format (1X,'K =',I3,'  ELAM =',F12.3,'  DELAM =',E12.2)
99998 Format (1X,'HMAX(1,M-1) =',F10.3,'    HMAX(1,M) =',F10.3)
    End Program d02kdfe


d02kefe.f90

!   D02KEF Example Program Text
!   Mark 26 Release. NAG Copyright 2016.

    Module d02kefe_mod

!     Data for D02KEF example program

!     .. Use Statements ..
      Use nag_library, Only: nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Accessibility Statements ..
      Private
      Public                           :: bdyval, coeffn, monit, report
!     .. Parameters ..
      Real (Kind=nag_wp), Parameter    :: one = 1.0_nag_wp
      Real (Kind=nag_wp), Parameter    :: two = 2.0_nag_wp
      Real (Kind=nag_wp), Parameter    :: zero = 0.0_nag_wp
      Integer, Parameter, Public       :: nin = 5, nout = 6
    Contains
      Subroutine coeffn(p,q,dqdl,x,elam,jint)

!       .. Scalar Arguments ..
        Real (Kind=nag_wp), Intent (Out) :: dqdl, p, q
        Real (Kind=nag_wp), Intent (In) :: elam, x
        Integer, Intent (In)           :: jint
!       .. Executable Statements ..
        p = one
        q = elam - x - two/(x*x)
        dqdl = one
        Return
      End Subroutine coeffn
      Subroutine bdyval(xl,xr,elam,yl,yr)

!       .. Scalar Arguments ..
        Real (Kind=nag_wp), Intent (In) :: elam, xl, xr
!       .. Array Arguments ..
        Real (Kind=nag_wp), Intent (Out) :: yl(3), yr(3)
!       .. Intrinsic Procedures ..
        Intrinsic                      :: sqrt
!       .. Executable Statements ..
        yl(1) = xl
        yl(2) = two
        yr(1) = one
        yr(2) = -sqrt(xr-elam)
        Return
      End Subroutine bdyval
      Subroutine report(x,v,jint)

!       .. Use Statements ..
        Use nag_library, Only: x02amf
!       .. Scalar Arguments ..
        Real (Kind=nag_wp), Intent (In) :: x
        Integer, Intent (In)           :: jint
!       .. Array Arguments ..
        Real (Kind=nag_wp), Intent (In) :: v(3)
!       .. Local Scalars ..
        Real (Kind=nag_wp)             :: pyp, r, sqrtb, y
!       .. Intrinsic Procedures ..
        Intrinsic                      :: cos, exp, log, sin, sqrt
!       .. Executable Statements ..
        If (jint==0) Then
          Write (nout,*)
          Write (nout,*) ' Eigenfunction values'
          Write (nout,*) '       X          Y           PYP'
        End If
        sqrtb = sqrt(v(1))
!       Avoid underflow in call of EXP
        If (0.5_nag_wp*v(3)>=log(x02amf())) Then
          r = exp(0.5_nag_wp*v(3))
        Else
          r = zero
        End If
        pyp = r*sqrtb*cos(0.5_nag_wp*v(2))
        y = r/sqrtb*sin(0.5_nag_wp*v(2))
        Write (nout,99999) x, y, pyp
        Return

99999   Format (1X,F10.3,1P,2F12.4)
      End Subroutine report
      Subroutine monit(nit,iflag,elam,finfo)

!       .. Scalar Arguments ..
        Real (Kind=nag_wp), Intent (In) :: elam
        Integer, Intent (In)           :: iflag, nit
!       .. Array Arguments ..
        Real (Kind=nag_wp), Intent (In) :: finfo(15)
!       .. Executable Statements ..
        If (nit==-1) Then
          Write (nout,*)
          Write (nout,*) 'Output from MONIT'
        End If
        Write (nout,99999) nit, iflag, elam, finfo(1:4)
        Return

99999   Format (1X,2I4,F10.3,2E12.2,2F8.1)
      End Subroutine monit
    End Module d02kefe_mod
    Program d02kefe

!     D02KEF Example Main Program

!     .. Use Statements ..
      Use nag_library, Only: d02kef, nag_wp
      Use d02kefe_mod, Only: bdyval, coeffn, monit, nin, nout, report
!     .. Implicit None Statement ..
      Implicit None
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: delam, elam, tol
      Integer                          :: ifail, k, m, match, maxfun, maxit
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: hmax(:,:), xpoint(:)
!     .. Executable Statements ..
      Write (nout,*) 'D02KEF Example Program Results'
      Write (nout,*)
      Write (nout,*) 'A singular problem'
!     Skip heading in data file
      Read (nin,*)
!     m: number of points in xpoint
      Read (nin,*) m
      Allocate (hmax(2,m),xpoint(m))
!     xpoint: points where the boundary conditions are to be imposed
!             and any break points,
!     tol: tolerance parameter which determines the accuracy of the
!          computed eigenvalue,
!     k: index of the required eigenvalue,  hmax: maximum step size,
!     elam: initial estimate of the eigenvalue,  delam: initial search step,
!     maxit: number of root-finding iterations allowed,
!     maxfun: number of calls to coeffn in any one root-finding iteration,
!     match: index of the break point.
      Read (nin,*) xpoint(1:m)
      Read (nin,*) tol
      Read (nin,*) k
      Read (nin,*) elam, delam
      Read (nin,*) hmax(1,1:m-3)
      Read (nin,*) maxit, maxfun, match

!     ifail: behaviour on error exit
!            =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
      ifail = 0
      Call d02kef(xpoint,m,match,coeffn,bdyval,k,tol,elam,delam,hmax,maxit,    &
        maxfun,monit,report,ifail)

      Write (nout,*)
      Write (nout,*) 'Final results'
      Write (nout,*)
      Write (nout,99999) k, elam, delam
      Write (nout,99998) hmax(1,m-1), hmax(1,m)

99999 Format (1X,'K =',I3,'  ELAM =',F12.3,'  DELAM =',E12.2)
99998 Format (1X,'HMAX(1,M-1) =',F10.3,'    HMAX(1,M) =',F10.3)
    End Program d02kefe


d02lafe.f90

!   D02LAF Example Program Text
!   Mark 26 Release. NAG Copyright 2016.

    Module d02lafe_mod

!     D02LAF Example Program Module:
!            Parameters and User-defined Routines

!     .. Use Statements ..
      Use nag_library, Only: nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Accessibility Statements ..
      Private
      Public                           :: fcn
!     .. Parameters ..
      Real (Kind=nag_wp), Parameter, Public :: zero = 0.0_nag_wp
      Integer, Parameter, Public       :: neq = 2, nin = 5, nout = 6
      Integer, Parameter, Public       :: lrwork = 16 + 20*neq
    Contains
      Subroutine fcn(neq,t,y,f)

!       Derivatives for two body problem in  y'' = f(t,y)  form

!       .. Scalar Arguments ..
        Real (Kind=nag_wp), Intent (In) :: t
        Integer, Intent (In)           :: neq
!       .. Array Arguments ..
        Real (Kind=nag_wp), Intent (Out) :: f(neq)
        Real (Kind=nag_wp), Intent (In) :: y(neq)
!       .. Local Scalars ..
        Real (Kind=nag_wp)             :: r
!       .. Intrinsic Procedures ..
        Intrinsic                      :: sqrt
!       .. Executable Statements ..
        r = sqrt(y(1)**2+y(2)**2)**3
        f(1) = -y(1)/r
        f(2) = -y(2)/r
        Return
      End Subroutine fcn
    End Module d02lafe_mod

    Program d02lafe

!     D02LAF Example Main Program

!     .. Use Statements ..
      Use nag_library, Only: d02laf, d02lxf, d02lyf, d02lzf, nag_wp
      Use d02lafe_mod, Only: fcn, lrwork, neq, nin, nout, zero
!     .. Implicit None Statement ..
      Implicit None
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: h, hnext, hstart, hused, t, tend,    &
                                          tinc, tnext, tol, tstart
      Integer                          :: i, ifail, itol, maxstp, natt, nfail, &
                                          nsucc, nwant
      Logical                          :: high, onestp, start
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: rwork(:), thres(:), thresp(:), y(:), &
                                          ydp(:), yinit(:), yp(:), ypinit(:),  &
                                          ypwant(:), ywant(:)
!     .. Executable Statements ..
      Write (nout,*) 'D02LAF Example Program Results'
!     Skip heading in data file
      Read (nin,*)
!     neq: number of second-order ordinary differential equations
      Read (nin,*) nwant
      Allocate (rwork(lrwork),thres(neq),thresp(neq),y(neq),ydp(neq),          &
        yinit(neq),yp(neq),ypinit(neq),ypwant(nwant),ywant(nwant))
      Read (nin,*) high, onestp
      Read (nin,*) tinc

!     Initial conditions
      Read (nin,*) tstart, tend
      Read (nin,*) yinit(1:neq)
      Read (nin,*) ypinit(1:neq)

loop1: Do itol = 4, 5
        tol = 10.0_nag_wp**(-itol)
        Write (nout,*)

!       Call D02LXF with default THRES,THRESP,MAXSTP and H

        thres(1) = zero
        thresp(1) = zero
        h = zero
        maxstp = 0
        start = .True.

!       ifail: behaviour on error exit
!              =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
        ifail = 0
        Call d02lxf(neq,h,tol,thres,thresp,maxstp,start,onestp,high,rwork,     &
          lrwork,ifail)

        Write (nout,99999) 'Calculation with TOL = ', tol
        Write (nout,99995)(i,i=1,neq)

!       Set initial values

        y(1:neq) = yinit(1:neq)
        yp(1:neq) = ypinit(1:neq)
        t = tstart
        tnext = t + tinc
        Write (nout,99998) t, y(1:neq)

!       Loop point for one-step mode
loop2:  Do

          ifail = -1
          Call d02laf(fcn,neq,t,tend,y,yp,ydp,rwork,lrwork,ifail)

          If (ifail>0) Then
            Write (nout,99997) ifail, t
            Exit loop1
          End If

!         Loop point for interpolation
          Do While (tnext<=t)

            ifail = 0
            Call d02lzf(neq,t,y,yp,neq,tnext,ywant,ypwant,rwork,lrwork,ifail)

            Write (nout,99998) tnext, ywant(1:neq)
            tnext = tnext + tinc
          End Do

          If (t>=tend) Then
            Exit loop2
          End If

        End Do loop2

        ifail = 0
        Call d02lyf(neq,hnext,hused,hstart,nsucc,nfail,natt,thres,thresp,      &
          rwork,lrwork,ifail)

        Write (nout,*)
        Write (nout,99996) ' Number of successful steps = ', nsucc
        Write (nout,99996) ' Number of   failed   steps = ', nfail
      End Do loop1

99999 Format (1X,A,1P,E9.1)
99998 Format (1X,F5.1,2(2X,F9.5))
99997 Format (/,1X,'D02LAF returned with IFAIL = ',I2,'  at T = ',1P,E10.3)
99996 Format (1X,A,I5)
99995 Format (/,'   T ',2('     Y(',I1,')  '))
    End Program d02lafe


d02mvfe.f90

!   D02MVF Example Program Text
!   Mark 26 Release. NAG Copyright 2016.

    Module d02mvfe_mod

!     D02MVF Example Program Module:
!            Parameters and User-defined Routines

!     .. Use Statements ..
      Use nag_library, Only: nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Accessibility Statements ..
      Private
      Public                           :: jac, resid
!     .. Parameters ..
      Real (Kind=nag_wp), Parameter, Public :: one = 1.0_nag_wp
      Real (Kind=nag_wp), Parameter    :: two = 2.0_nag_wp
      Integer, Parameter, Public       :: iset = 1, neq = 6, nin = 5, nout = 6
      Integer, Parameter, Public       :: nrw = 50 + 4*neq
      Integer, Parameter, Public       :: nwkjac = neq*(neq+1)
      Integer, Parameter, Public       :: sdysav = 8
      Integer, Parameter, Public       :: ldysav = neq
    Contains
      Subroutine resid(neq,t,y,ydot,r,ires)

!       .. Scalar Arguments ..
        Real (Kind=nag_wp), Intent (In) :: t
        Integer, Intent (Inout)        :: ires
        Integer, Intent (In)           :: neq
!       .. Array Arguments ..
        Real (Kind=nag_wp), Intent (Out) :: r(neq)
        Real (Kind=nag_wp), Intent (In) :: y(neq), ydot(neq)
!       .. Executable Statements ..
        If (ires==-1) Then
          r(1) = -ydot(1)
          r(2) = -ydot(2)
          r(3) = -ydot(3)
          r(4) = -ydot(4)
          r(5:6) = 0.0E0_nag_wp
        Else
          r(1) = y(3) - y(6)*y(1) - ydot(1)
          r(2) = y(4) - y(6)*y(2) - ydot(2)
          r(3) = -y(5)*y(1) - ydot(3)
          r(4) = -y(5)*y(2) - one - ydot(4)
          r(5) = y(1)*y(3) + y(2)*y(4)
          r(6) = y(1)**2 + y(2)**2 - one
        End If
        Return
      End Subroutine resid

      Subroutine jac(neq,t,y,ydot,h,d,p)

!       .. Scalar Arguments ..
        Real (Kind=nag_wp), Intent (In) :: d, h, t
        Integer, Intent (In)           :: neq
!       .. Array Arguments ..
        Real (Kind=nag_wp), Intent (Inout) :: p(neq,neq)
        Real (Kind=nag_wp), Intent (In) :: y(neq), ydot(neq)
!       .. Local Scalars ..
        Real (Kind=nag_wp)             :: hxd
!       .. Executable Statements ..
        hxd = h*d
        p(1,1) = (one+hxd*y(6))
        p(1,3) = -hxd
        p(1,6) = hxd*y(1)
        p(2,2) = (one+hxd*y(6))
        p(2,4) = -hxd
        p(2,6) = hxd*y(2)
        p(3,1) = hxd*y(5)
        p(3,3) = one
        p(3,5) = hxd*y(1)
        p(4,2) = hxd*y(5)
        p(4,4) = one
        p(4,5) = hxd*y(2)
        p(5,1) = -hxd*y(3)
        p(5,2) = -hxd*y(4)
        p(5,3) = -hxd*y(1)
        p(5,4) = -hxd*y(2)
        p(6,1) = -two*hxd*y(1)
        p(6,2) = -two*hxd*y(2)
        Return
      End Subroutine jac
    End Module d02mvfe_mod

    Program d02mvfe

!     D02MVF Example Main Program

!     .. Use Statements ..
      Use nag_library, Only: d02mvf, d02nby, d02ngf, d02nsf, nag_wp, x04abf
      Use d02mvfe_mod, Only: iset, jac, ldysav, neq, nin, nout, nrw, nwkjac,   &
                             one, resid, sdysav
!     .. Implicit None Statement ..
      Implicit None
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: h0, hmax, hmin, t, tcrit, tout
      Integer                          :: i, ifail, itask, itol, itrace,       &
                                          maxord, maxstp, mxhnil, outchn
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: atol(:), rtol(:), rwork(:),          &
                                          wkjac(:), y(:), ydot(:), ysav(:,:)
      Real (Kind=nag_wp)               :: con(3)
      Integer                          :: inform(23)
      Logical                          :: lderiv(2)
!     .. Executable Statements ..
      Write (nout,*) 'D02MVF Example Program Results'
!     Skip heading in data file
      Read (nin,*)
!     Allocations based on number of differential equations (neq)

      Allocate (atol(neq),rtol(neq),rwork(nrw),wkjac(nwkjac),y(neq),ydot(neq), &
        ysav(ldysav,sdysav))

!     Read algorithmic parameters
      Read (nin,*) maxord, maxstp, mxhnil
      Read (nin,*) hmin, hmax, h0
      Read (nin,*) rtol(1), atol(1)
      Read (nin,*) itrace, itol
      Read (nin,*) t, tout
      Read (nin,*) y(1:neq)
      Read (nin,*) itask

!     Set initial derivatives and other values
      outchn = nout
      Call x04abf(iset,outchn)
      con(1:3) = 0.0_nag_wp
      ydot(1) = y(3) - y(6)*y(1)
      ydot(2) = y(4) - y(6)*y(2)
      ydot(3) = -y(5)*y(1)
      ydot(4) = -y(5)*y(2) - one
      ydot(5) = -3.0_nag_wp*y(4)
      ydot(6) = 0.0_nag_wp
      tcrit = tout

!     ifail: behaviour on error exit
!             =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
      ifail = 0
      Call d02mvf(neq,sdysav,maxord,con,tcrit,hmin,hmax,h0,maxstp,mxhnil,      &
        'AVERAGE-L2',rwork,ifail)

      Write (nout,*)
      Write (nout,99999) 'Pendulum problem with relative tolerance', rtol(1)
      Write (nout,99999) '                  and absolute tolerance', atol(1)
      Write (nout,99998)(i,i=1,neq)
      Write (nout,99997) t, y(1:neq)

      ifail = 0
      Call d02nsf(neq,neq,'ANALYTIC',nwkjac,rwork,ifail)

      lderiv(1) = .True.
      lderiv(2) = .True.

      ifail = 0
      Call d02ngf(neq,ldysav,t,tout,y,ydot,rwork,rtol,atol,itol,inform,resid,  &
        ysav,sdysav,jac,wkjac,nwkjac,d02nby,lderiv,itask,itrace,ifail)

      Write (nout,99997) t, y(1:neq)

99999 Format (1X,A40,' =',1P,E8.1)
99998 Format (/,1X,'  t ',3X,6('      y',I1))
99997 Format (1X,F7.4,2X,6(F8.4))
    End Program d02mvfe


d02mwfe.f90

!   D02MWF Example Program Text
!   Mark 26 Release. NAG Copyright 2016.

    Module d02mwfe_mod

!     D02MWF Example Program Module:
!            Parameters and User-defined Routines

!     .. Use Statements ..
      Use nag_library, Only: nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Accessibility Statements ..
      Private
      Public                           :: jac, res
!     .. Parameters ..
      Integer, Parameter, Public       :: iset = 1, neq = 5, nin = 5, nout = 6
      Integer, Parameter, Public       :: licom = 50 + neq
    Contains
      Subroutine res(neq,t,y,ydot,r,ires,iuser,ruser)

!       .. Scalar Arguments ..
        Real (Kind=nag_wp), Intent (In) :: t
        Integer, Intent (Inout)        :: ires
        Integer, Intent (In)           :: neq
!       .. Array Arguments ..
        Real (Kind=nag_wp), Intent (Out) :: r(neq)
        Real (Kind=nag_wp), Intent (Inout) :: ruser(*)
        Real (Kind=nag_wp), Intent (In) :: y(neq), ydot(neq)
        Integer, Intent (Inout)        :: iuser(*)
!       .. Executable Statements ..
        r(1) = y(3) - ydot(1)
        r(2) = y(4) - ydot(2)
        r(3) = -y(5)*y(1) - ydot(3)
        r(4) = -y(5)*y(2) - 1.0_nag_wp - ydot(4)
        r(5) = y(3)**2 + y(4)**2 - y(5) - y(2)
        Return
      End Subroutine res

      Subroutine jac(neq,t,y,ydot,pd,cj,iuser,ruser)

!       .. Scalar Arguments ..
        Real (Kind=nag_wp), Intent (In) :: cj, t
        Integer, Intent (In)           :: neq
!       .. Array Arguments ..
        Real (Kind=nag_wp), Intent (Inout) :: pd(*), ruser(*)
        Real (Kind=nag_wp), Intent (In) :: y(neq), ydot(neq)
        Integer, Intent (Inout)        :: iuser(*)
!       .. Executable Statements ..
        pd(1) = -cj
        pd(3) = -y(5)
        pd(7) = -cj
        pd(9) = -y(5)
        pd(10) = -1.0_nag_wp
        pd(11) = 1.0_nag_wp
        pd(13) = -cj
        pd(15) = 2.0_nag_wp*y(3)
        pd(17) = 1.0_nag_wp
        pd(19) = -cj
        pd(20) = 2.0_nag_wp*y(4)
        pd(23) = -y(1)
        pd(24) = -y(2)
        pd(25) = -1.0_nag_wp
        Return
      End Subroutine jac
    End Module d02mwfe_mod

    Program d02mwfe

!     D02MWF Example Main Program

!     .. Use Statements ..
      Use nag_library, Only: d02mwf, d02nef, nag_wp, x04abf
      Use d02mwfe_mod, Only: iset, jac, licom, neq, nin, nout, res
!     .. Implicit None Statement ..
      Implicit None
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: g1, g2, h0, hmax, t, tout
      Integer                          :: i, ifail, ijac, itask, itol, lcom,   &
                                          maxord, nadv
      Character (8)                    :: jceval
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: atol(:), com(:), rtol(:), y(:),      &
                                          ydot(:)
      Real (Kind=nag_wp)               :: ruser(1)
      Integer, Allocatable             :: icom(:)
      Integer                          :: iuser(1)
!     .. Executable Statements ..
      Write (nout,*) 'D02MWF Example Program Results'
      Write (nout,*)
!     Skip heading in data file
      Read (nin,*)
!     neq: number of differential-algebraic equations
      Read (nin,*) maxord
      lcom = 40 + (maxord+4)*neq + neq**2
      Allocate (atol(neq),com(lcom),rtol(neq),y(neq),ydot(neq),icom(licom))
      nadv = nout
      Call x04abf(iset,nadv)
      Read (nin,*) t, tout
      Read (nin,*) itol, itask
      Read (nin,*) rtol(1:neq)
      Read (nin,*) atol(1:neq)
!     Set initial values
      Read (nin,*) y(1:neq)
      Read (nin,*) hmax, h0
      Read (nin,*) ijac
      If (ijac==1) Then
        jceval = 'Analytic'
      Else
        jceval = 'Numeric'
      End If

!     ifail: behaviour on error exit
!            =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
      ifail = 0
      Call d02mwf(neq,maxord,jceval,hmax,h0,itol,icom,licom,com,lcom,ifail)

      Write (nout,99995)(i,i=1,neq)
      Write (nout,99998) t, y(1:neq)
      ydot(1:neq) = 0.0_nag_wp

loop: Do
        Call d02nef(neq,t,tout,y,ydot,rtol,atol,itask,res,jac,icom,com,lcom,   &
          iuser,ruser,ifail)

        Write (nout,99998) t, y(1:neq)
        Write (nout,99999) itask
        If ((itask>=0) .And. (itask<=3)) Then
          If (t>=tout) Then
            g1 = y(1)**2 + y(2)**2 - 1.0_nag_wp
            g2 = y(1)*y(3) + y(2)*y(4)
            Write (nout,99997) g1
            Write (nout,99996) g2
            Exit loop
          End If
        Else
          Exit loop
        End If
      End Do loop

99999 Format (/,' D02NEF returned with ITASK = ',I4,/)
99998 Format (1X,F7.4,2X,5(F11.6))
99997 Format (1X,'The position-level constraint G1 = ',E12.4)
99996 Format (1X,'The velocity-level constraint G2 = ',E12.4)
99995 Format (/,1X,'  t ',3X,5('       y(',I1,')'))
    End Program d02mwfe


d02mzfe.f90

!   D02MZF Example Program Text
!   Mark 26 Release. NAG Copyright 2016.

    Module d02mzfe_mod

!     D02MZF Example Program Module:
!            Parameters and User-defined Routines

!     .. Use Statements ..
      Use nag_library, Only: nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Accessibility Statements ..
      Private
      Public                           :: resid
!     .. Parameters ..
      Real (Kind=nag_wp), Parameter, Public :: tstep = 0.02_nag_wp
      Integer, Parameter, Public       :: iset = 1, neq = 3, nin = 5, nout = 6
      Integer, Parameter, Public       :: nrw = 50 + 4*neq
      Integer, Parameter, Public       :: nwkjac = neq*(neq+1)
      Integer, Parameter, Public       :: sdysav = 6
      Integer, Parameter, Public       :: ldysav = neq
    Contains
      Subroutine resid(neq,t,y,ydot,r,ires)

!       .. Parameters ..
        Real (Kind=nag_wp), Parameter  :: alpha = 0.04_nag_wp
        Real (Kind=nag_wp), Parameter  :: beta = 1.0E4_nag_wp
        Real (Kind=nag_wp), Parameter  :: gamma = 3.0E7_nag_wp
!       .. Scalar Arguments ..
        Real (Kind=nag_wp), Intent (In) :: t
        Integer, Intent (Inout)        :: ires
        Integer, Intent (In)           :: neq
!       .. Array Arguments ..
        Real (Kind=nag_wp), Intent (Out) :: r(neq)
        Real (Kind=nag_wp), Intent (In) :: y(neq), ydot(neq)
!       .. Executable Statements ..
        r(1:3) = -ydot(1:3)
        If (ires==1) Then
          r(1) = -alpha*y(1) + beta*y(2)*y(3) + r(1)
          r(2) = alpha*y(1) - beta*y(2)*y(3) - gamma*y(2)*y(2) + r(2)
          r(3) = gamma*y(2)*y(2) + r(3)
        End If
        Return
      End Subroutine resid
    End Module d02mzfe_mod

    Program d02mzfe

!     D02MZF Example Main Program

!     .. Use Statements ..
      Use nag_library, Only: d02mzf, d02nby, d02ngf, d02ngz, d02nsf, d02nvf,   &
                             d02nyf, nag_wp, x04abf
      Use d02mzfe_mod, Only: iset, ldysav, neq, nin, nout, nrw, nwkjac, resid, &
                             sdysav, tstep
!     .. Implicit None Statement ..
      Implicit None
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: h, h0, hmax, hmin, hu, t, tcrit,     &
                                          tcur, tolsf, tout, xout
      Integer                          :: i, ifail, imxer, iout, itask, itol,  &
                                          itrace, maxord, maxstp, mxhnil,      &
                                          niter, nje, nq, nqu, nre, nst,       &
                                          outchn, pstat
      Logical                          :: petzld
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: atol(:), rtol(:), rwork(:), sol(:),  &
                                          wkjac(:), y(:), ydot(:), ysav(:,:)
      Real (Kind=nag_wp)               :: con(6)
      Integer                          :: inform(23)
      Logical, Allocatable             :: algequ(:)
      Logical                          :: lderiv(2)
!     .. Executable Statements ..
      Write (nout,*) 'D02MZF Example Program Results'
!     Skip heading in data file
      Read (nin,*)

!     Allocations based on number of differential equations (neq)
      Allocate (atol(neq),rtol(neq),rwork(nrw),sol(neq),wkjac(nwkjac),y(neq),  &
        ydot(neq),ysav(ldysav,sdysav),algequ(neq))

!     Read algorithmic parameters
      Read (nin,*) maxord, maxstp, mxhnil, pstat
      Read (nin,*) petzld
      Read (nin,*) hmin, hmax, h0, tcrit
      Read (nin,*) t, tout
      Read (nin,*) itol
      Read (nin,*) y(1:neq)
      Read (nin,*) lderiv(1:2)
      Read (nin,*) rtol(1:neq)
      Read (nin,*) atol(1:neq)

      outchn = nout
      Call x04abf(iset,outchn)
      con(1:6) = 0.0_nag_wp
      itask = 2
      itrace = 0

!     ifail: behaviour on error exit
!             =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
      ifail = 0
      Call d02nvf(neq,sdysav,maxord,'Functional-iteration',petzld,con,tcrit,   &
        hmin,hmax,h0,maxstp,mxhnil,'Average-L2',rwork,ifail)

!     Linear algebra setup.
      ifail = 0
      Call d02nsf(neq,neq,'Numerical',nwkjac,rwork,ifail)

      Write (nout,99994)(i,i=1,neq)
      Write (nout,99999) t, y(1:neq)

!     First value of t to interpolate and print solution at.
      iout = 1
      xout = tstep

!      Integrate one step at a time and overshoot tout (itask=2).
steps: Do
        ifail = 0
        Call d02ngf(neq,ldysav,t,tout,y,ydot,rwork,rtol,atol,itol,inform,      &
          resid,ysav,sdysav,d02ngz,wkjac,nwkjac,d02nby,lderiv,itask,itrace,    &
          ifail)

!       Get Current value of t (tcur) and last step used (hu)
        Call d02nyf(neq,neq,hu,h,tcur,tolsf,rwork,nst,nre,nje,nqu,nq,niter,    &
          imxer,algequ,inform,ifail)

interp: Do
          If (tcur-hu<xout .And. xout<=tcur) Then
!           xout is in interval of last step, so interpolate.
            ifail = 0
            Call d02mzf(xout,sol,neq,ldysav,neq,ysav,sdysav,rwork,ifail)

            Write (nout,99999) xout, sol(1:neq)
            iout = iout + 1
            If (iout>=6) Then
!             Final solution point printed. Print stats if required.
              If (pstat==1) Then
                Write (nout,*)
                Write (nout,99998) hu, h, tcur
                Write (nout,99997) nst, nre, nje
                Write (nout,99996) nqu, nq, niter
                Write (nout,99995) ' Max err comp = ', imxer
              End If
              Exit steps
            End If
!           Set next xout. This might also be in last step, so keep
!           looping for interpolation.
            xout = xout + tstep
            Cycle interp
          Else
!           Take another step.
            Cycle steps
          End If
        End Do interp
      End Do steps

99999 Format (1X,F8.3,3(F13.5,2X))
99998 Format (1X,' HUSED = ',E12.5,'  HNEXT = ',E12.5,'  TCUR = ',E12.5)
99997 Format (1X,' NST = ',I6,'    NRE = ',I6,'    NJE = ',I6)
99996 Format (1X,' NQU = ',I6,'    NQ  = ',I6,'  NITER = ',I6)
99995 Format (1X,A,I4)
99994 Format (/,1X,'    X ',3('         Y(',I1,')  '))
    End Program d02mzfe


d02nbfe.f90

!   D02NBF Example Program Text
!   Mark 26 Release. NAG Copyright 2016.

    Module d02nbfe_mod

!     D02NBF Example Program Module:
!            Parameters and User-defined Routines

!     .. Use Statements ..
      Use nag_library, Only: nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Accessibility Statements ..
      Private
      Public                           :: fcn, jac
!     .. Parameters ..
      Real (Kind=nag_wp), Parameter    :: alpha = 0.04_nag_wp
      Real (Kind=nag_wp), Parameter    :: beta = 1.0E4_nag_wp
      Real (Kind=nag_wp), Parameter    :: gamma = 3.0E7_nag_wp
      Real (Kind=nag_wp), Parameter    :: one = 1.0_nag_wp
      Real (Kind=nag_wp), Parameter    :: two = 2.0_nag_wp
      Integer, Parameter, Public       :: iset = 1, itrace = 0, neq = 3,       &
                                          nin = 5, nout = 6
      Integer, Parameter, Public       :: nrw = 50 + 4*neq
      Integer, Parameter, Public       :: nwkjac = neq*(neq+1)
      Integer, Parameter, Public       :: ldysav = neq
    Contains
      Subroutine fcn(neq,t,y,f,ires)

!       .. Scalar Arguments ..
        Real (Kind=nag_wp), Intent (In) :: t
        Integer, Intent (Inout)        :: ires
        Integer, Intent (In)           :: neq
!       .. Array Arguments ..
        Real (Kind=nag_wp), Intent (Out) :: f(neq)
        Real (Kind=nag_wp), Intent (In) :: y(neq)
!       .. Executable Statements ..
        f(1) = -alpha*y(1) + beta*y(2)*y(3)
        f(2) = alpha*y(1) - beta*y(2)*y(3) - gamma*y(2)*y(2)
        f(3) = gamma*y(2)*y(2)
        Return
      End Subroutine fcn

      Subroutine jac(neq,t,y,h,d,p)

!       .. Scalar Arguments ..
        Real (Kind=nag_wp), Intent (In) :: d, h, t
        Integer, Intent (In)           :: neq
!       .. Array Arguments ..
        Real (Kind=nag_wp), Intent (Inout) :: p(neq,neq)
        Real (Kind=nag_wp), Intent (In) :: y(neq)
!       .. Local Scalars ..
        Real (Kind=nag_wp)             :: hxd
!       .. Executable Statements ..
        hxd = h*d
        p(1,1) = one - hxd*(-alpha)
        p(1,2) = -hxd*(beta*y(3))
        p(1,3) = -hxd*(beta*y(2))
        p(2,1) = -hxd*(alpha)
        p(2,2) = one - hxd*(-beta*y(3)-two*gamma*y(2))
        p(2,3) = -hxd*(-beta*y(2))
!       Do not need to set P(3,1) since Jacobian preset to zero
!       P(3,1) =       - HXD*(0.0E0)
        p(3,2) = -hxd*(two*gamma*y(2))
        p(3,3) = one - hxd*(0.0_nag_wp)
        Return
      End Subroutine jac
    End Module d02nbfe_mod

    Program d02nbfe

!     D02NBF Example Main Program

!     .. Use Statements ..
      Use nag_library, Only: d02nbf, d02nby, d02nbz, d02nsf, d02nvf, d02nyf,   &
                             nag_wp, x04abf
      Use d02nbfe_mod, Only: fcn, iset, itrace, jac, ldysav, neq, nin, nout,   &
                             nrw, nwkjac
!     .. Implicit None Statement ..
      Implicit None
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: h, h0, hmax, hmin, hu, t, tcrit,     &
                                          tcur, tinit, tolsf, tout
      Integer                          :: i, icase, ifail, imxer, itask, itol, &
                                          maxord, maxstp, mxhnil, niter, nje,  &
                                          nq, nqu, nre, nst, outchn, sdysav
      Logical                          :: petzld
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: atol(:), rtol(:), rwork(:),          &
                                          wkjac(:), y(:), ydot(:), yinit(:),   &
                                          ysav(:,:)
      Real (Kind=nag_wp)               :: con(6)
      Integer                          :: inform(23)
      Logical, Allocatable             :: algequ(:)
!     .. Executable Statements ..
      Write (nout,*) 'D02NBF Example Program Results'
!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) maxord, maxstp, mxhnil
      sdysav = maxord + 1
      Allocate (atol(neq),rtol(neq),rwork(nrw),wkjac(nwkjac),y(neq),           &
        yinit(neq),ydot(neq),ysav(ldysav,sdysav),algequ(neq))
      outchn = nout
      Call x04abf(iset,outchn)

      Read (nin,*) petzld
      Read (nin,*) hmin, hmax, h0
      Read (nin,*) tinit, tout
      Read (nin,*) itol
      Read (nin,*) yinit(1:neq)
      Read (nin,*) rtol(1), atol(1)

!     Two cases. In both cases:
!                integrate to tout without passing tout;
!                use B.D.F formulae with a Newton method;
!                use default values for the array con;
!                use scalar tolerances;
!                use NAG dummy routine D02NBY in place of MONITR subroutine.
      con(1:6) = 0.0_nag_wp
      tcrit = tout
      itask = 4

cases: Do icase = 1, 2

        t = tinit
        y(1:neq) = yinit(1:neq)

!       ifail: behaviour on error exit
!              =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
        ifail = 0
        Call d02nvf(neq,sdysav,maxord,'Newton',petzld,con,tcrit,hmin,hmax,h0,  &
          maxstp,mxhnil,'Average-L2',rwork,ifail)

        Write (nout,*)
        ifail = 0
        Select Case (icase)
        Case (1)
!         First case. The Jacobian is evaluated internally.
          Call d02nsf(neq,neq,'Numerical',nwkjac,rwork,ifail)

          Write (nout,*) '  Numerical Jacobian'
        Case (2)
!         Second case. The Jacobian is evaluated by jac.
          Call d02nsf(neq,neq,'Analytical',nwkjac,rwork,ifail)

          Write (nout,*) '  Analytic Jacobian'
        End Select

        Write (nout,99993)(i,i=1,neq)
        Write (nout,99999) t, y(1:neq)

!       Soft fail and error messages only

        ifail = -1
        Select Case (icase)
        Case (1)
          Call d02nbf(neq,ldysav,t,tout,y,ydot,rwork,rtol,atol,itol,inform,    &
            fcn,ysav,sdysav,d02nbz,wkjac,nwkjac,d02nby,itask,itrace,ifail)
        Case (2)
          Call d02nbf(neq,ldysav,t,tout,y,ydot,rwork,rtol,atol,itol,inform,    &
            fcn,ysav,sdysav,jac,wkjac,nwkjac,d02nby,itask,itrace,ifail)
        End Select

        If (ifail==0) Then
          Write (nout,99999) t, y(1:neq)

          ifail = 0
          Call d02nyf(neq,neq,hu,h,tcur,tolsf,rwork,nst,nre,nje,nqu,nq,niter,  &
            imxer,algequ,inform,ifail)

          Write (nout,*)
          Write (nout,99997) hu, h, tcur
          Write (nout,99996) nst, nre, nje
          Write (nout,99995) nqu, nq, niter
          Write (nout,99994) ' Max Err Comp = ', imxer
          Write (nout,*)
        Else
          Write (nout,*)
          Write (nout,99998) 'Exit D02NBF with IFAIL = ', ifail, '  and T = ', &
            t
        End If
      End Do cases

99999 Format (1X,F8.3,3(F13.5,2X))
99998 Format (1X,A,I2,A,E12.5)
99997 Format (1X,' HUSED = ',E12.5,'  HNEXT = ',E12.5,'  TCUR = ',E12.5)
99996 Format (1X,' NST = ',I6,'    NRE = ',I6,'    NJE = ',I6)
99995 Format (1X,' NQU = ',I6,'    NQ  = ',I6,'  NITER = ',I6)
99994 Format (1X,A,I4)
99993 Format (/,1X,'    X ',3('         Y(',I1,')  '))
    End Program d02nbfe


d02ncfe.f90

!   D02NCF Example Program Text
!   Mark 26 Release. NAG Copyright 2016.

    Module d02ncfe_mod

!     D02NCF Example Program Module:
!            Parameters and User-defined Routines

!     .. Use Statements ..
      Use nag_library, Only: nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Accessibility Statements ..
      Private
      Public                           :: fcn, jac
!     .. Parameters ..
      Real (Kind=nag_wp), Parameter    :: alpha = 0.04_nag_wp
      Real (Kind=nag_wp), Parameter    :: beta = 1.0E4_nag_wp
      Real (Kind=nag_wp), Parameter    :: gamma = 3.0E7_nag_wp
      Real (Kind=nag_wp), Parameter    :: one = 1.0_nag_wp
      Real (Kind=nag_wp), Parameter    :: two = 2.0_nag_wp
      Integer, Parameter, Public       :: iset = 1, itrace = 0, ml = 1,        &
                                          mu = 2, neq = 3, nin = 5
      Integer, Parameter, Public       :: njcpvt = neq
      Integer, Parameter, Public       :: nout = 6
      Integer, Parameter, Public       :: nrw = 50 + 4*neq
      Integer, Parameter, Public       :: nwkjac = neq*(2*ml+mu+1)
      Integer, Parameter, Public       :: ldysav = neq
    Contains
      Subroutine fcn(neq,t,y,f,ires)

!       .. Scalar Arguments ..
        Real (Kind=nag_wp), Intent (In) :: t
        Integer, Intent (Inout)        :: ires
        Integer, Intent (In)           :: neq
!       .. Array Arguments ..
        Real (Kind=nag_wp), Intent (Out) :: f(neq)
        Real (Kind=nag_wp), Intent (In) :: y(neq)
!       .. Executable Statements ..
        f(1) = -alpha*y(1) + beta*y(2)*y(3)
        f(2) = alpha*y(1) - beta*y(2)*y(3) - gamma*y(2)*y(2)
        f(3) = gamma*y(2)*y(2)
        Return
      End Subroutine fcn

      Subroutine jac(neq,t,y,h,d,ml,mu,p)

!       .. Scalar Arguments ..
        Real (Kind=nag_wp), Intent (In) :: d, h, t
        Integer, Intent (In)           :: ml, mu, neq
!       .. Array Arguments ..
        Real (Kind=nag_wp), Intent (Inout) :: p(ml+mu+1,neq)
        Real (Kind=nag_wp), Intent (In) :: y(neq)
!       .. Local Scalars ..
        Real (Kind=nag_wp)             :: hxd
!       .. Executable Statements ..
        hxd = h*d

        p(1,1) = one - hxd*(-alpha)
        p(2,1) = -hxd*(beta*y(3))
        p(3,1) = -hxd*(beta*y(2))

        p(1,2) = -hxd*(alpha)
        p(2,2) = one - hxd*(-beta*y(3)-two*gamma*y(2))
        p(3,2) = -hxd*(-beta*y(2))

        p(1,3) = -hxd*(two*gamma*y(2))
        p(2,3) = one - hxd*(0.0_nag_wp)
        Return
      End Subroutine jac
    End Module d02ncfe_mod

    Program d02ncfe

!     D02NCF Example Main Program

!     .. Use Statements ..
      Use nag_library, Only: d02nby, d02ncf, d02ntf, d02nwf, d02nyf, d02nzf,   &
                             nag_wp, x04abf
      Use d02ncfe_mod, Only: fcn, iset, itrace, jac, ldysav, ml, mu, neq, nin, &
                             njcpvt, nout, nrw, nwkjac
!     .. Implicit None Statement ..
      Implicit None
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: h, h0, hmax, hmin, hu, t, tcrit,     &
                                          tcur, tolsf, tout
      Integer                          :: i, ifail, imxer, itask, itol,        &
                                          maxord, maxstp, mxhnil, niter, nje,  &
                                          nq, nqu, nre, nst, outchn, sdysav
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: atol(:), rtol(:), rwork(:),          &
                                          wkjac(:), y(:), ydot(:), ysav(:,:)
      Real (Kind=nag_wp)               :: con(6)
      Integer                          :: inform(23)
      Integer, Allocatable             :: jacpvt(:)
      Logical, Allocatable             :: algequ(:)
!     .. Executable Statements ..
      Write (nout,*) 'D02NCF Example Program Results'
!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) maxord, maxstp, mxhnil
      sdysav = maxord + 3
      Allocate (atol(neq),rtol(neq),rwork(nrw),wkjac(nwkjac),y(neq),ydot(neq), &
        ysav(ldysav,sdysav),jacpvt(njcpvt),algequ(neq))
      outchn = nout
      Call x04abf(iset,outchn)

!     Integrate to tout (itask=1 i.e. overshooting and internal interpolation)
!     using the blend method. Default values for the array con are used.
!     Employ scalar relative tolerance and vector absolute tolerance.
!     The Jacobian is evaluated by jac.
!     monitr subroutine replaced by NAG dummy routine D02NBY.

      Read (nin,*) hmin, hmax, h0, tcrit
      Read (nin,*) t, tout
      Read (nin,*) itol
      Read (nin,*) y(1:neq)
      Read (nin,*) rtol(1)
      Read (nin,*) atol(1:neq)
      con(1:6) = 0.0_nag_wp
      itask = 1

!     ifail: behaviour on error exit
!             =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
      ifail = 0
      Call d02nwf(neq,sdysav,maxord,con,tcrit,hmin,hmax,h0,maxstp,mxhnil,      &
        'Average-L2',rwork,ifail)

      ifail = 0
      Call d02ntf(neq,neq,'Analytical',ml,mu,nwkjac,njcpvt,rwork,ifail)

      Write (nout,99993)(i,i=1,neq)
      Write (nout,99999) t, (y(i),i=1,neq)

!     Soft fail and error messages only

      ifail = -1
      Call d02ncf(neq,ldysav,t,tout,y,ydot,rwork,rtol,atol,itol,inform,fcn,    &
        ysav,sdysav,jac,wkjac,nwkjac,jacpvt,njcpvt,d02nby,itask,itrace,ifail)

      If (ifail==0) Then
        Write (nout,99999) t, (y(i),i=1,neq)
      Else
        Write (nout,*)
        Write (nout,99998) 'Exit D02NCF with IFAIL = ', ifail, '  and T = ', t
      End If
!     Reset tout and call D02NZF to override internal choice for step size.
!     No changes to other parameters.
      h = 0.7_nag_wp

      ifail = 0
      Call d02nzf(neq,tcrit,h,hmin,hmax,maxstp,mxhnil,rwork,ifail)

      tout = 10.0_nag_wp

      ifail = -1
      Call d02ncf(neq,ldysav,t,tout,y,ydot,rwork,rtol,atol,itol,inform,fcn,    &
        ysav,sdysav,jac,wkjac,nwkjac,jacpvt,njcpvt,d02nby,itask,itrace,ifail)

      If (ifail==0) Then
        Write (nout,99999) t, (y(i),i=1,neq)

        ifail = 0
        Call d02nyf(neq,neq,hu,h,tcur,tolsf,rwork,nst,nre,nje,nqu,nq,niter,    &
          imxer,algequ,inform,ifail)

        Write (nout,*)
        Write (nout,99997) hu, h, tcur
        Write (nout,99996) nst, nre, nje
        Write (nout,99995) nqu, nq, niter
        Write (nout,99994) ' Max Err Comp = ', imxer
        Write (nout,*)
      Else
        Write (nout,*)
        Write (nout,99998) 'Exit D02NCF with IFAIL = ', ifail, '  and T = ', t
      End If

99999 Format (1X,F8.3,3(F13.5,2X))
99998 Format (1X,A,I2,A,E12.5)
99997 Format (1X,' HUSED = ',E12.5,'  HNEXT = ',E12.5,'  TCUR = ',E12.5)
99996 Format (1X,' NST = ',I6,'    NRE = ',I6,'    NJE = ',I6)
99995 Format (1X,' NQU = ',I6,'    NQ  = ',I6,'  NITER = ',I6)
99994 Format (1X,A,I4)
99993 Format (/,1X,'    X ',3('         Y(',I1,')  '))
    End Program d02ncfe


d02ndfe.f90

!   D02NDF Example Program Text
!   Mark 26 Release. NAG Copyright 2016.

    Module d02ndfe_mod

!     D02NDF Example Program Module:
!            Parameters and User-defined Routines

!     .. Use Statements ..
      Use nag_library, Only: nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Accessibility Statements ..
      Private
      Public                           :: fcn, monitr
!     .. Parameters ..
      Integer, Parameter, Public       :: iset = 1, neq = 3
      Integer, Parameter, Public       :: nia = neq + 1
      Integer, Parameter, Public       :: nin = 5
      Integer, Parameter, Public       :: njcpvt = 20*neq + 100
      Integer, Parameter, Public       :: nout = 6
      Integer, Parameter, Public       :: nrw = 50 + 4*neq
      Integer, Parameter, Public       :: nwkjac = 4*neq + 100
      Integer, Parameter, Public       :: sdysav = 6
      Integer, Parameter, Public       :: ldysav = neq
    Contains
      Subroutine fcn(neq,t,y,f,ires)

!       .. Parameters ..
        Real (Kind=nag_wp), Parameter  :: alpha = 0.04_nag_wp
        Real (Kind=nag_wp), Parameter  :: beta = 1.0E4_nag_wp
        Real (Kind=nag_wp), Parameter  :: gamma = 3.0E7_nag_wp
!       .. Scalar Arguments ..
        Real (Kind=nag_wp), Intent (In) :: t
        Integer, Intent (Inout)        :: ires
        Integer, Intent (In)           :: neq
!       .. Array Arguments ..
        Real (Kind=nag_wp), Intent (Out) :: f(neq)
        Real (Kind=nag_wp), Intent (In) :: y(neq)
!       .. Executable Statements ..
        f(1) = -alpha*y(1) + beta*y(2)*y(3)
        f(2) = alpha*y(1) - beta*y(2)*y(3) - gamma*y(2)*y(2)
        f(3) = gamma*y(2)*y(2)
        Return
      End Subroutine fcn
      Subroutine monitr(neq,ldysav,t,hlast,hnext,y,ydot,ysav,r,acor,imon,inln, &
        hmin,hmax,nqu)

!       .. Use Statements ..
        Use nag_library, Only: d02xkf
!       .. Scalar Arguments ..
        Real (Kind=nag_wp), Intent (In) :: hlast, t
        Real (Kind=nag_wp), Intent (Inout) :: hmax, hmin, hnext
        Integer, Intent (Inout)        :: imon
        Integer, Intent (Out)          :: inln
        Integer, Intent (In)           :: ldysav, neq, nqu
!       .. Array Arguments ..
        Real (Kind=nag_wp), Intent (In) :: acor(neq,2), r(neq), ydot(neq),     &
                                          ysav(ldysav,*)
        Real (Kind=nag_wp), Intent (Inout) :: y(neq)
!       .. Local Scalars ..
        Real (Kind=nag_wp)             :: xout
        Integer                        :: i, ifail
!       .. Local Arrays ..
        Real (Kind=nag_wp), Allocatable :: z(:)
!       .. Executable Statements ..
        inln = 3

        If (imon==1) Then
          Allocate (z(neq))

!         Interpolate at multiples of 2.0 between t-hlast and t
          xout = 2.0E0_nag_wp
          Do While (xout<=t-hlast)
            xout = xout + 2.0E0_nag_wp
          End Do
loop:     Do While (t-hlast<xout .And. xout<=t)

!           C1 interpolation

            ifail = 1
            Call d02xkf(xout,z,neq,ysav,ldysav,sdysav,acor(1,2),neq,t,nqu,     &
              hlast,hnext,ifail)

            If (ifail/=0) Then
              imon = -2
              Exit loop
            End If

            Write (nout,99999) xout, (z(i),i=1,neq)
            xout = xout + 2.0E0_nag_wp

            If (xout>=10.0E0_nag_wp) Then
              Exit loop
            End If

          End Do loop

        End If

        Deallocate (z)
        Return

99999   Format (1X,F8.3,3(F13.5,2X))
      End Subroutine monitr
    End Module d02ndfe_mod

    Program d02ndfe

!     D02NDF Example Main Program

!     .. Use Statements ..
      Use nag_library, Only: d02ndf, d02ndz, d02nuf, d02nvf, d02nxf, d02nyf,   &
                             nag_wp, x04abf
      Use d02ndfe_mod, Only: fcn, iset, ldysav, monitr, neq, nia, nin, njcpvt, &
                             nout, nrw, nwkjac, sdysav
!     .. Implicit None Statement ..
      Implicit None
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: eta, h, h0, hmax, hmin, hu, sens, t, &
                                          tcrit, tcur, tinit, tolsf, tout, u
      Integer                          :: i, icall, icase, ifail, igrow,       &
                                          imxer, isplit, isplt, itask, itol,   &
                                          itrace, liwreq, liwusd, lrwreq,      &
                                          lrwusd, maxord, maxstp, mxhnil,      &
                                          nblock, ngp, niter, nja, nje, nlu,   &
                                          nnz, nq, nqu, nre, nst, outchn
      Logical                          :: lblock, petzld
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: atol(:), rtol(:), rwork(:),          &
                                          wkjac(:), y(:), ydot(:), yinit(:),   &
                                          ysav(:,:)
      Real (Kind=nag_wp)               :: con(6)
      Integer, Allocatable             :: ia(:), ja(:), jacpvt(:)
      Integer                          :: inform(23)
      Logical, Allocatable             :: algequ(:)
!     .. Executable Statements ..
      Write (nout,*) 'D02NDF Example Program Results'
!     Skip heading in data file
      Read (nin,*)

!     Allocations based on number of differential equations (neq)
      Allocate (atol(neq),rtol(neq),rwork(nrw),wkjac(nwkjac),y(neq),           &
        yinit(neq),ydot(neq),ysav(ldysav,sdysav),ia(nia),jacpvt(njcpvt),       &
        algequ(neq))

      Read (nin,*) maxord, maxstp, mxhnil
      Read (nin,*) ia(1:nia)

      nja = ia(nia) - 1
      Allocate (ja(nja))
      Read (nin,*) ja(1:nja)

!     Read algorithmic parameters
      Read (nin,*) hmin, hmax, h0, tcrit
      Read (nin,*) eta, sens, u
      Read (nin,*) lblock, petzld
      Read (nin,*) tinit, tout
      Read (nin,*) itol, isplt
      Read (nin,*) yinit(1:neq)
      Read (nin,*) rtol(1), atol(1)

      outchn = nout
      Call x04abf(iset,outchn)

      Do icase = 1, 2
        t = tinit
        isplit = isplt
        y(1:neq) = yinit(1:neq)

!       In both cases: integrate to tout by overshooting (itask=1) using BDF
!       with Newton; use default con values, scalar tolerances and numerical
!       Jacobian; interpolate using MONITR and D02XKF.

        con(1:6) = 0.0_nag_wp
        itask = 1
        ifail = 0
        Call d02nvf(neq,sdysav,maxord,'Newton',petzld,con,tcrit,hmin,hmax,h0,  &
          maxstp,mxhnil,'Average-L2',rwork,ifail)
        Write (nout,*)

        Select Case (icase)
        Case (1)
!         No Jacobian Structure Supplied.
          ifail = 0
          Call d02nuf(neq,neq,'Numerical',nwkjac,ia,nia,ja,nja,jacpvt,njcpvt,  &
            sens,u,eta,lblock,isplit,rwork,ifail)
          Write (nout,*) '  Numerical Jacobian, structure not supplied'
        Case (2)
!         Jacobian Structure Supplied.
          ifail = 0
          Call d02nuf(neq,neq,'Structural',nwkjac,ia,nia,ja,nja,jacpvt,njcpvt, &
            sens,u,eta,lblock,isplit,rwork,ifail)
          Write (nout,*) '  Numerical Jacobian, structure supplied'
        End Select

        Write (nout,99988)(i,i=1,neq)
        Write (nout,99999) t, (y(i),i=1,neq)

!       Soft fail and error messages only
        itrace = 0

        ifail = -1
        Call d02ndf(neq,ldysav,t,tout,y,ydot,rwork,rtol,atol,itol,inform,fcn,  &
          ysav,sdysav,d02ndz,wkjac,nwkjac,jacpvt,njcpvt,monitr,itask,itrace,   &
          ifail)

        If (ifail==0) Then

          ifail = 0
          Call d02nyf(neq,neq,hu,h,tcur,tolsf,rwork,nst,nre,nje,nqu,nq,niter,  &
            imxer,algequ,inform,ifail)

          Write (nout,*)
          Write (nout,99997) hu, h, tcur
          Write (nout,99996) nst, nre, nje
          Write (nout,99995) nqu, nq, niter
          Write (nout,99994) ' Max err comp = ', imxer
          Write (nout,*)

          icall = 0
          Call d02nxf(icall,liwreq,liwusd,lrwreq,lrwusd,nlu,nnz,ngp,isplit,    &
            igrow,lblock,nblock,inform)

          Write (nout,*)
          Write (nout,99993) liwreq, liwusd
          Write (nout,99992) lrwreq, lrwusd
          Write (nout,99991) nlu, nnz
          Write (nout,99990) ngp, isplit
          Write (nout,99989) igrow, nblock
        Else If (ifail==10) Then
          Write (nout,*)
          Write (nout,99998) 'Exit D02NDF with IFAIL = ', ifail, '  and T = ', &
            t

          icall = 1
          Call d02nxf(icall,liwreq,liwusd,lrwreq,lrwusd,nlu,nnz,ngp,isplit,    &
            igrow,lblock,nblock,inform)

          Write (nout,*)
          Write (nout,99993) liwreq, liwusd
          Write (nout,99992) lrwreq, lrwusd
        Else
          Write (nout,*)
          Write (nout,99998) 'Exit D02NDF with IFAIL = ', ifail, '  and T = ', &
            t
        End If
      End Do

99999 Format (1X,F8.3,3(F13.5,2X))
99998 Format (1X,A,I5,A,E12.5)
99997 Format (1X,' HUSED = ',E12.5,'  HNEXT = ',E12.5,'  TCUR = ',E12.5)
99996 Format (1X,' NST = ',I6,'    NRE = ',I6,'    NJE = ',I6)
99995 Format (1X,' NQU = ',I6,'    NQ  = ',I6,'  NITER = ',I6)
99994 Format (1X,A,I4)
99993 Format (1X,' NJCPVT (required ',I4,'  used ',I8,')')
99992 Format (1X,' NWKJAC (required ',I4,'  used ',I8,')')
99991 Format (1X,' No. of LU-decomps ',I4,'  No. of nonzeros ',I8)
99990 Format (1X,' No. of FCN calls to form Jacobian ',I4,'  Try ISPLIT ',I4)
99989 Format (1X,' Growth est ',I8,'  No. of blocks on diagonal ',I4)
99988 Format (/,1X,'    X ',3('         Y(',I1,')  '))
    End Program d02ndfe


d02nefe.f90

!   D02NEF Example Program Text
!   Mark 26 Release. NAG Copyright 2016.

    Module d02nefe_mod

!     D02NEF Example Program Module:
!            Parameters and User-defined Routines

!     .. Use Statements ..
      Use nag_library, Only: nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Accessibility Statements ..
      Private
      Public                           :: jac1, jac2, res1, res2
!     .. Parameters ..
      Real (Kind=nag_wp), Parameter    :: alpha = 0.04_nag_wp
      Real (Kind=nag_wp), Parameter    :: beta = 1.0E4_nag_wp
      Real (Kind=nag_wp), Parameter    :: gamma = 3.0E7_nag_wp
      Real (Kind=nag_wp), Parameter    :: two = 2.0_nag_wp
      Integer, Parameter, Public       :: ml = 1, mu = 2, neq1 = 3, neq2 = 1,  &
                                          nin = 5, nout = 6
    Contains
      Subroutine myjac1(neq,ml,mu,t,y,ydot,pd,cj)

!       .. Scalar Arguments ..
        Real (Kind=nag_wp), Intent (In) :: cj, t
        Integer, Intent (In)           :: ml, mu, neq
!       .. Array Arguments ..
        Real (Kind=nag_wp), Intent (Out) :: pd(2*ml+mu+1,neq)
        Real (Kind=nag_wp), Intent (In) :: y(neq), ydot(neq)
!       .. Local Scalars ..
        Integer                        :: md, ms
!       .. Executable Statements ..
!       Main diagonal pdfull(i,i), i=1,neq
        md = mu + ml + 1
        pd(md,1) = -alpha - cj
        pd(md,2) = -beta*y(3) - two*gamma*y(2) - cj
        pd(md,3) = -cj
!       1 Subdiagonal pdfull(i+1:i), i=1,neq-1
        ms = md + 1
        pd(ms,1) = alpha
        pd(ms,2) = two*gamma*y(2)
!       First superdiagonal pdfull(i-1,i), i=2, neq
        ms = md - 1
        pd(ms,2) = beta*y(3)
        pd(ms,3) = -beta*y(2)
!       Second superdiagonal pdfull(i-2,i), i=3, neq
        ms = md - 2
        pd(ms,3) = beta*y(2)

        Return
      End Subroutine myjac1
      Subroutine myjac2(neq,t,y,ydot,pd,cj)

!       .. Scalar Arguments ..
        Real (Kind=nag_wp), Intent (In) :: cj, t
        Integer, Intent (In)           :: neq
!       .. Array Arguments ..
        Real (Kind=nag_wp), Intent (Out) :: pd(neq*neq)
        Real (Kind=nag_wp), Intent (In) :: y(neq), ydot(neq)
!       .. Intrinsic Procedures ..
        Intrinsic                      :: exp
!       .. Executable Statements ..
        pd(1) = -two*y(1) + 0.1E0_nag_wp*t*y(1)*exp(y(1))

        Return
      End Subroutine myjac2

      Subroutine res1(neq,t,y,ydot,r,ires,iuser,ruser)

!       .. Scalar Arguments ..
        Real (Kind=nag_wp), Intent (In) :: t
        Integer, Intent (Inout)        :: ires
        Integer, Intent (In)           :: neq
!       .. Array Arguments ..
        Real (Kind=nag_wp), Intent (Out) :: r(neq)
        Real (Kind=nag_wp), Intent (Inout) :: ruser(*)
        Real (Kind=nag_wp), Intent (In) :: y(neq), ydot(neq)
        Integer, Intent (Inout)        :: iuser(*)
!       .. Executable Statements ..
        r(1) = -alpha*y(1) + beta*y(2)*y(3) - ydot(1)
        r(2) = alpha*y(1) - beta*y(2)*y(3) - gamma*y(2)*y(2) - ydot(2)
        r(3) = gamma*y(2)*y(2) - ydot(3)
        Return
      End Subroutine res1
      Subroutine jac1(neq,t,y,ydot,pd,cj,iuser,ruser)

!       .. Use Statements ..
        Use nag_library, Only: d02nez
!       .. Scalar Arguments ..
        Real (Kind=nag_wp), Intent (In) :: cj, t
        Integer, Intent (In)           :: neq
!       .. Array Arguments ..
        Real (Kind=nag_wp), Intent (Inout) :: pd(*), ruser(*)
        Real (Kind=nag_wp), Intent (In) :: y(neq), ydot(neq)
        Integer, Intent (Inout)        :: iuser(*)
!       .. Local Scalars ..
        Integer                        :: ijac, ml, mu
!       .. Executable Statements ..
        ml = iuser(1)
        mu = iuser(2)
        ijac = iuser(3)

        If (ijac==1) Then
          Call myjac1(neq,ml,mu,t,y,ydot,pd,cj)
        Else
          Call d02nez(neq,t,y,ydot,pd,cj,iuser,ruser)
        End If

        Return
      End Subroutine jac1
      Subroutine res2(neq,t,y,ydot,r,ires,iuser,ruser)

!       .. Scalar Arguments ..
        Real (Kind=nag_wp), Intent (In) :: t
        Integer, Intent (Inout)        :: ires
        Integer, Intent (In)           :: neq
!       .. Array Arguments ..
        Real (Kind=nag_wp), Intent (Out) :: r(neq)
        Real (Kind=nag_wp), Intent (Inout) :: ruser(*)
        Real (Kind=nag_wp), Intent (In) :: y(neq), ydot(neq)
        Integer, Intent (Inout)        :: iuser(*)
!       .. Intrinsic Procedures ..
        Intrinsic                      :: exp
!       .. Executable Statements ..
        r(1) = 4.0_nag_wp - y(1)**2 + t*0.1E0_nag_wp*exp(y(1))
        Return
      End Subroutine res2
      Subroutine jac2(neq,t,y,ydot,pd,cj,iuser,ruser)

!       .. Use Statements ..
        Use nag_library, Only: d02nez
!       .. Scalar Arguments ..
        Real (Kind=nag_wp), Intent (In) :: cj, t
        Integer, Intent (In)           :: neq
!       .. Array Arguments ..
        Real (Kind=nag_wp), Intent (Inout) :: pd(*), ruser(*)
        Real (Kind=nag_wp), Intent (In) :: y(neq), ydot(neq)
        Integer, Intent (Inout)        :: iuser(*)
!       .. Local Scalars ..
        Integer                        :: ijac
!       .. Executable Statements ..
        ijac = iuser(1)

        If (ijac==1) Then
          Call myjac2(neq,t,y,ydot,pd,cj)
        Else
          Call d02nez(neq,t,y,ydot,pd,cj,iuser,ruser)
        End If

        Return
      End Subroutine jac2
    End Module d02nefe_mod
    Program d02nefe

!     D02NEF Example Main Program

!     .. Use Statements ..
      Use d02nefe_mod, Only: nout
!     .. Implicit None Statement ..
      Implicit None
!     .. Executable Statements ..
      Write (nout,*) 'D02NEF Example Program Results'

      Call ex1

      Call ex2

    Contains
      Subroutine ex1

!       .. Use Statements ..
        Use nag_library, Only: d02mcf, d02mwf, d02nef, d02npf, nag_wp
        Use d02nefe_mod, Only: jac1, ml, mu, neq1, nin, res1
!       .. Local Scalars ..
        Real (Kind=nag_wp)             :: h0, hmax, t, tout
        Integer                        :: i, ifail, ijac, itask, itol, j,      &
                                          lcom, licom, maxord, neq
        Character (8)                  :: jceval
!       .. Local Arrays ..
        Real (Kind=nag_wp), Allocatable :: atol(:), com(:), rtol(:), y(:),     &
                                          ydot(:)
        Real (Kind=nag_wp)             :: ruser(1)
        Integer, Allocatable           :: icom(:)
        Integer                        :: iuser(3)
!       .. Executable Statements ..
        Write (nout,*)
        Write (nout,*) 'D02NEF Example 1'
!       Skip heading in data file
        Read (nin,*)
        Read (nin,*) maxord
        neq = neq1
        lcom = 40 + (maxord+4)*neq + (2*ml+mu+1)*neq + 2*(neq/(ml+mu+1)+1)
        licom = 50 + neq
        Allocate (atol(neq),com(lcom),rtol(neq),y(neq),ydot(neq),icom(licom))
        Read (nin,*) ijac, itol
        Read (nin,*) rtol(1:neq)
        Read (nin,*) atol(1:neq)
        Read (nin,*) ydot(1:neq)
        If (ijac==1) Then
          jceval = 'Analytic'
        Else
          jceval = 'Numeric'
        End If
!       Set initial values
        Read (nin,*) y(1:neq)

!       Initialize the problem, specifying that the Jacobian is to be
!       evaluated analytically using the provided routine jac.

        Read (nin,*) hmax, h0
        Read (nin,*) t, tout

!       ifail: behaviour on error exit
!              =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
        ifail = 0
        Call d02mwf(neq,maxord,jceval,hmax,h0,itol,icom,licom,com,lcom,ifail)

!       Specify that the Jacobian is banded.

        ifail = 0
        Call d02npf(neq,ml,mu,icom,licom,ifail)

!       Use the iuser array to pass the band dimensions through to jac.
!       An alternative would be to hard code values for ml and mu in jac.

        iuser(1) = ml
        iuser(2) = mu
        iuser(3) = ijac

        Write (nout,99999)(i,i=1,neq)
        Write (nout,99998) t, (y(i),i=1,neq)
        itask = 0

!       Obtain the solution at 5 equally spaced values of T.

loop:   Do j = 1, 5
          ifail = -1
          Call d02nef(neq,t,tout,y,ydot,rtol,atol,itask,res1,jac1,icom,com,    &
            lcom,iuser,ruser,ifail)
          Write (nout,99998) t, (y(i),i=1,neq)
          If (ifail/=0) Then
            Write (nout,99997) ifail
            Exit loop
          End If
          tout = tout + 0.02_nag_wp
          Call d02mcf(icom)
        End Do loop

        Write (nout,*)
        Write (nout,99996) itask

99999   Format (/,1X,'    t ',5X,3('      Y(',I1,')  '))
99998   Format (1X,F8.4,3X,3(F12.6))
99997   Format (1X,' ** D02NEF returned with IFAIL = ',I5)
99996   Format (1X,'The integrator completed task, ITASK = ',I4)
      End Subroutine ex1
      Subroutine ex2

!       .. Use Statements ..
        Use nag_library, Only: d02mcf, d02mwf, d02nef, nag_wp
        Use d02nefe_mod, Only: jac2, neq2, nin, res2
!       .. Local Scalars ..
        Real (Kind=nag_wp)             :: h0, hmax, t, tout
        Integer                        :: i, ifail, ijac, itask, itol, j,      &
                                          lcom, licom, maxord, neq
        Character (8)                  :: jceval
!       .. Local Arrays ..
        Real (Kind=nag_wp), Allocatable :: atol(:), com(:), rtol(:), y(:),     &
                                          ydot(:)
        Real (Kind=nag_wp)             :: ruser(1)
        Integer, Allocatable           :: icom(:)
        Integer                        :: iuser(1)
!       .. Executable Statements ..
        Write (nout,*)
        Write (nout,*) 'D02NEF Example 2'
        Write (nout,*)
        Read (nin,*)
        Read (nin,*) maxord
        neq = neq2
        lcom = 40 + (maxord+4)*neq + neq*neq
        licom = 50 + neq
        Allocate (atol(neq),com(lcom),rtol(neq),y(neq),ydot(neq),icom(licom))
        Read (nin,*) ijac, itol
        Read (nin,*) rtol(1:neq)
        Read (nin,*) atol(1:neq)
        Read (nin,*) ydot(1:neq)
        If (ijac==1) Then
          jceval = 'Analytic'
        Else
          jceval = 'Numeric'
        End If

!       Initialize the problem, specifying that the Jacobian is to be
!       evaluated analytically using the provided routine jac.

        Read (nin,*) y(1:neq)
        Read (nin,*) hmax, h0
        Read (nin,*) t, tout

        ifail = 0
        Call d02mwf(neq,maxord,jceval,hmax,h0,itol,icom,licom,com,lcom,ifail)

!       Use the iuser array to pass whether numerical or analytic Jacobian
!       is to be used.

        iuser(1) = ijac

        Write (nout,99999)(i,i=1,neq)
        Write (nout,99998) t, y(1:neq)
        itask = 0

!       Obtain the solution at 5 equally spaced values of t.

loop:   Do j = 1, 5

          ifail = -1
          Call d02nef(neq,t,tout,y,ydot,rtol,atol,itask,res2,jac2,icom,com,    &
            lcom,iuser,ruser,ifail)

          Write (nout,99998) t, y(1:neq)
          If (ifail/=0) Then
            Write (nout,99997) ifail
            Exit loop
          End If
          tout = tout + 0.2_nag_wp
          Call d02mcf(icom)
        End Do loop

        Write (nout,*)
        Write (nout,99996) itask

99999   Format (/,1X,'    t            y(',I1,')')
99998   Format (1X,F8.4,3X,3(F12.6))
99997   Format (1X,' ** D02NEF returned with IFAIL = ',I5)
99996   Format (1X,'The integrator completed task, ITASK = ',I4)
      End Subroutine ex2
    End Program d02nefe


d02ngfe.f90

!   D02NGF Example Program Text
!   Mark 26 Release. NAG Copyright 2016.

    Module d02ngfe_mod

!     D02NGF Example Program Module:
!            Parameters and User-defined Routines

!     .. Use Statements ..
      Use nag_library, Only: nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Accessibility Statements ..
      Private
      Public                           :: resid
!     .. Parameters ..
      Real (Kind=nag_wp), Parameter    :: alpha = 0.04_nag_wp
      Real (Kind=nag_wp), Parameter    :: beta = 1.0E4_nag_wp
      Real (Kind=nag_wp), Parameter    :: gamma = 3.0E7_nag_wp
      Integer, Parameter, Public       :: iset = 1, itrace = 0, neq = 3,       &
                                          nin = 5, nout = 6
      Integer, Parameter, Public       :: nrw = 50 + 4*neq
      Integer, Parameter, Public       :: nwkjac = neq*(neq+1)
      Integer, Parameter, Public       :: ldysav = neq
    Contains
      Subroutine resid(neq,t,y,ydot,r,ires)

!       .. Scalar Arguments ..
        Real (Kind=nag_wp), Intent (In) :: t
        Integer, Intent (Inout)        :: ires
        Integer, Intent (In)           :: neq
!       .. Array Arguments ..
        Real (Kind=nag_wp), Intent (Out) :: r(neq)
        Real (Kind=nag_wp), Intent (In) :: y(neq), ydot(neq)
!       .. Executable Statements ..
        r(1) = -ydot(1)
        r(2) = -ydot(2)
        r(3) = -ydot(3)

        If (ires==1) Then
          r(1) = -alpha*y(1) + beta*y(2)*y(3) + r(1)
          r(2) = alpha*y(1) - beta*y(2)*y(3) - gamma*y(2)*y(2) + r(2)
          r(3) = gamma*y(2)*y(2) + r(3)
        End If
        Return
      End Subroutine resid
    End Module d02ngfe_mod

    Program d02ngfe

!     D02NGF Example Main Program

!     .. Use Statements ..
      Use nag_library, Only: d02nby, d02ngf, d02ngz, d02nsf, d02nvf, d02nyf,   &
                             d02xjf, nag_wp, x04abf
      Use d02ngfe_mod, Only: iset, itrace, ldysav, neq, nin, nout, nrw,        &
                             nwkjac, resid
!     .. Implicit None Statement ..
      Implicit None
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: h, h0, hmax, hmin, hu, t, tcrit,     &
                                          tcur, tolsf, tout, xout
      Integer                          :: i, ifail, imxer, iout, itask, itol,  &
                                          maxord, maxstp, mxhnil, niter, nje,  &
                                          nq, nqu, nre, nst, outchn, sdysav
      Logical                          :: petzld
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: atol(:), rtol(:), rwork(:), sol(:),  &
                                          wkjac(:), y(:), ydot(:), ysav(:,:)
      Real (Kind=nag_wp)               :: con(6)
      Integer                          :: inform(23)
      Logical, Allocatable             :: algequ(:)
      Logical                          :: lderiv(2)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: real
!     .. Executable Statements ..
      Write (nout,*) 'D02NGF Example Program Results'
!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) maxord, maxstp, mxhnil
      sdysav = maxord + 1
      Allocate (atol(neq),rtol(neq),rwork(nrw),sol(neq),wkjac(nwkjac),y(neq),  &
        ydot(neq),ysav(ldysav,sdysav),algequ(neq))
      outchn = nout
      Call x04abf(iset,outchn)

!     Integrate to tout by overshooting tout in one step mode (itask=2)
!     using B.D.F formulae with a functional iteration method.
!     Default values for the array con are used. Employ vector
!     tolerances and the Jacobian is evaluated internally, if necessary.
!     monitr subroutine replaced by NAG dummy routine D02NBY.
!     Interpolation outside D02NGF using D02XJF.

      itask = 2
      Read (nin,*) petzld
      Read (nin,*) hmin, hmax, h0, tcrit
      Read (nin,*) t, tout
      Read (nin,*) y(1:neq)
      Read (nin,*) lderiv(1:2)
      Read (nin,*) itol
      Read (nin,*) rtol(1:neq)
      Read (nin,*) atol(1:neq)
      con(1:6) = 0.0_nag_wp

!     ifail: behaviour on error exit
!             =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
      ifail = 0
      Call d02nvf(neq,sdysav,maxord,'Functional-iteration',petzld,con,tcrit,   &
        hmin,hmax,h0,maxstp,mxhnil,'Average-L2',rwork,ifail)

!     Linear algebra setup required (in case functional iteration
!     encounters any difficulty).
      ifail = 0
      Call d02nsf(neq,neq,'Numerical',nwkjac,rwork,ifail)

      xout = 0.02E0_nag_wp
      iout = 1

      Write (nout,99993)(i,i=1,neq)
      Write (nout,99999) t, (y(i),i=1,neq)

!      Soft fail and error messages only

loop1: Do
        ifail = -1
        Call d02ngf(neq,ldysav,t,tout,y,ydot,rwork,rtol,atol,itol,inform,      &
          resid,ysav,sdysav,d02ngz,wkjac,nwkjac,d02nby,lderiv,itask,itrace,    &
          ifail)

        If (ifail==0) Then

          ifail = 0
          Call d02nyf(neq,neq,hu,h,tcur,tolsf,rwork,nst,nre,nje,nqu,nq,niter,  &
            imxer,algequ,inform,ifail)

loop2:    Do
            If (tcur-hu<xout .And. xout<=tcur) Then

!             C0 interpolation
              ifail = 0
              Call d02xjf(xout,sol,neq,ysav,ldysav,sdysav,neq,tcur,nqu,hu,h,   &
                ifail)

              Write (nout,99999) xout, (sol(i),i=1,neq)
              iout = iout + 1
              xout = real(iout,kind=nag_wp)*0.02E0_nag_wp
              If (iout>=6) Then
                Write (nout,*)
                Write (nout,99997) hu, h, tcur
                Write (nout,99996) nst, nre, nje
                Write (nout,99995) nqu, nq, niter
                Write (nout,99994) ' Max err comp = ', imxer
                Exit loop1
              End If
            Else
              Exit loop2
            End If
          End Do loop2
        Else
          Write (nout,*)
          Write (nout,99998) 'Exit D02NGF with IFAIL = ', ifail, '  and T = ', &
            t
        End If
      End Do loop1

99999 Format (1X,F8.3,3(F13.5,2X))
99998 Format (1X,A,I2,A,E12.5)
99997 Format (1X,' HUSED = ',E12.5,'  HNEXT = ',E12.5,'  TCUR = ',E12.5)
99996 Format (1X,' NST = ',I6,'    NRE = ',I6,'    NJE = ',I6)
99995 Format (1X,' NQU = ',I6,'    NQ  = ',I6,'  NITER = ',I6)
99994 Format (1X,A,I4)
99993 Format (/,1X,'    X ',3('         Y(',I1,')  '))
    End Program d02ngfe


d02nhfe.f90

!   D02NHF Example Program Text
!   Mark 26 Release. NAG Copyright 2016.

    Module d02nhfe_mod

!     D02NHF Example Program Module:
!            Parameters and User-defined Routines

!     .. Use Statements ..
      Use nag_library, Only: nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Accessibility Statements ..
      Private
      Public                           :: resid
!     .. Parameters ..
      Real (Kind=nag_wp), Parameter    :: alpha = 0.04_nag_wp
      Real (Kind=nag_wp), Parameter    :: beta = 1.0E4_nag_wp
      Real (Kind=nag_wp), Parameter    :: gamma = 3.0E7_nag_wp
      Integer, Parameter, Public       :: iset = 1, itrace = 0, ml = 1,        &
                                          mu = 2, neq = 3, nin = 5
      Integer, Parameter, Public       :: njcpvt = neq
      Integer, Parameter, Public       :: nout = 6
      Integer, Parameter, Public       :: nrw = 50 + 4*neq
      Integer, Parameter, Public       :: nwkjac = neq*(2*ml+mu+1)
      Integer, Parameter, Public       :: ldysav = neq
    Contains
      Subroutine resid(neq,t,y,ydot,r,ires)

!       .. Scalar Arguments ..
        Real (Kind=nag_wp), Intent (In) :: t
        Integer, Intent (Inout)        :: ires
        Integer, Intent (In)           :: neq
!       .. Array Arguments ..
        Real (Kind=nag_wp), Intent (Out) :: r(neq)
        Real (Kind=nag_wp), Intent (In) :: y(neq), ydot(neq)
!       .. Executable Statements ..
        r(1) = -ydot(1) - ydot(2) - ydot(3)
        r(2) = -ydot(2)
        r(3) = -ydot(3)
        If (ires==1) Then
          r(1) = r(1)
          r(2) = alpha*y(1) - beta*y(2)*y(3) - gamma*y(2)*y(2) + r(2)
          r(3) = gamma*y(2)*y(2) + r(3)
        End If
        Return
      End Subroutine resid
    End Module d02nhfe_mod

    Program d02nhfe

!     D02NHF Example Main Program

!     .. Use Statements ..
      Use nag_library, Only: d02nby, d02nhf, d02nhz, d02ntf, d02nvf, d02nyf,   &
                             nag_wp, x04abf
      Use d02nhfe_mod, Only: iset, itrace, ldysav, ml, mu, neq, nin, njcpvt,   &
                             nout, nrw, nwkjac, resid
!     .. Implicit None Statement ..
      Implicit None
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: h, h0, hmax, hmin, hu, t, tcrit,     &
                                          tcur, tolsf, tout, tout1
      Integer                          :: i, ifail, imxer, itask, itol,        &
                                          maxord, maxstp, mxhnil, niter, nje,  &
                                          nq, nqu, nre, nst, outchn, sdysav
      Logical                          :: petzld
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: atol(:), rtol(:), rwork(:),          &
                                          wkjac(:), y(:), ydot(:), ysav(:,:)
      Real (Kind=nag_wp)               :: con(6)
      Integer                          :: inform(23)
      Integer, Allocatable             :: jacpvt(:)
      Logical, Allocatable             :: algequ(:)
      Logical                          :: lderiv(2)
!     .. Executable Statements ..
      Write (nout,*) 'D02NHF Example Program Results'
      Flush (nout)

!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) maxord, maxstp, mxhnil
      sdysav = maxord + 1
      Allocate (atol(neq),rtol(neq),rwork(nrw),wkjac(nwkjac),y(neq),ydot(neq), &
        ysav(ldysav,sdysav),jacpvt(njcpvt),algequ(neq))

      outchn = nout
      Call x04abf(iset,outchn)

!     Set itask=6 to provide initial estimates of solution and its
!     time derivative. Default values for the array con are used.
!     Use the B.D.F. formulae with a Newton method.
!     Employ scalar relative tolerance and vector absolute tolerance.
!     The Jacobian is evaluated internally.
!     monitr subroutine replaced by NAG dummy routine D02NBY.

      Read (nin,*) hmin, hmax, h0, tcrit
      Read (nin,*) petzld
      Read (nin,*) t, tout1
      Read (nin,*) y(1:neq)
      Read (nin,*) lderiv(1:2)
      Read (nin,*) itol
      Read (nin,*) rtol(1)
      Read (nin,*) atol(1:neq)
      itask = 6
      tout = tout1
      con(1:6) = 0.0_nag_wp

      ifail = 0
      Call d02nvf(neq,sdysav,maxord,'Newton',petzld,con,tcrit,hmin,hmax,h0,    &
        maxstp,mxhnil,'Average-L2',rwork,ifail)

      ifail = 0
      Call d02ntf(neq,neq,'Numerical',ml,mu,nwkjac,njcpvt,rwork,ifail)

!     Hard fail on initial and subsequent tasks.
      ifail = 0
      Call d02nhf(neq,ldysav,t,tout,y,ydot,rwork,rtol,atol,itol,inform,resid,  &
        ysav,sdysav,d02nhz,wkjac,nwkjac,jacpvt,njcpvt,d02nby,lderiv,itask,     &
        itrace,ifail)

      Write (nout,*)
      Write (nout,99999) ' Initial    Y : ', y(1:neq)
      Write (nout,99999) ' Initial YDOT : ', ydot(1:neq)
      Flush (nout)

!     Use these initial estimates and integrate to tout (overshoot and
!     interpolate)
      itask = 1
      tout = tout1

      ifail = 0
      Call d02nhf(neq,ldysav,t,tout,y,ydot,rwork,rtol,atol,itol,inform,resid,  &
        ysav,sdysav,d02nhz,wkjac,nwkjac,jacpvt,njcpvt,d02nby,lderiv,itask,     &
        itrace,ifail)

      Write (nout,99993)(i,i=1,neq)
      Write (nout,99998) tout, y(1:neq)

      ifail = 0
      Call d02nyf(neq,neq,hu,h,tcur,tolsf,rwork,nst,nre,nje,nqu,nq,niter,      &
        imxer,algequ,inform,ifail)

      Write (nout,*)
      Write (nout,99997) hu, h, tcur
      Write (nout,99996) nst, nre, nje
      Write (nout,99995) nqu, nq, niter
      Write (nout,99994) ' Max err comp = ', imxer

99999 Format (1X,A,3(F11.4,2X))
99998 Format (1X,F8.3,3(F13.5,2X))
99997 Format (1X,' HUSED = ',E12.5,'  HNEXT = ',E12.5,'  TCUR = ',E12.5)
99996 Format (1X,' NST = ',I6,'    NRE = ',I6,'    NJE = ',I6)
99995 Format (1X,' NQU = ',I6,'    NQ  = ',I6,'  NITER = ',I6)
99994 Format (1X,A,I4)
99993 Format (/,1X,'    X ',3('         Y(',I1,')  '))
    End Program d02nhfe


d02njfe.f90

!   D02NJF Example Program Text
!   Mark 26 Release. NAG Copyright 2016.

    Module d02njfe_mod

!     D02NJF Example Program Module:
!            Parameters and User-defined Routines

!     .. Use Statements ..
      Use nag_library, Only: nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Accessibility Statements ..
      Private
      Public                           :: jac, monitr, resid
!     .. Parameters ..
      Real (Kind=nag_wp), Parameter    :: alpha = 0.04_nag_wp
      Real (Kind=nag_wp), Parameter    :: beta = 1.0E4_nag_wp
      Real (Kind=nag_wp), Parameter    :: gamma = 3.0E7_nag_wp
      Real (Kind=nag_wp), Parameter    :: one = 1.0_nag_wp
      Real (Kind=nag_wp), Parameter    :: two = 2.0_nag_wp
      Real (Kind=nag_wp), Parameter    :: zero = 0.0_nag_wp
      Integer, Parameter, Public       :: iset = 1, itrace = 0, neq = 3
      Integer, Parameter, Public       :: nia = neq + 1
      Integer, Parameter, Public       :: nin = 5, nout = 6
      Integer, Parameter, Public       :: nrw = 50 + 4*neq
      Integer, Parameter, Public       :: ldysav = neq
      Integer, Parameter               :: nelts = 8
      Integer, Parameter, Public       :: nja = nelts
      Integer, Parameter, Public       :: njcpvt = 20*neq + 12*nelts
      Integer, Parameter, Public       :: nwkjac = 4*neq + 12*nelts
    Contains
      Subroutine resid(neq,t,y,ydot,r,ires)

!       .. Scalar Arguments ..
        Real (Kind=nag_wp), Intent (In) :: t
        Integer, Intent (Inout)        :: ires
        Integer, Intent (In)           :: neq
!       .. Array Arguments ..
        Real (Kind=nag_wp), Intent (Out) :: r(neq)
        Real (Kind=nag_wp), Intent (In) :: y(neq), ydot(neq)
!       .. Executable Statements ..
        r(1) = zero
        r(2) = -ydot(2)
        r(3) = -ydot(3)
        If (ires==1) Then
          r(1) = y(1) + y(2) + y(3) - one + r(1)
          r(2) = alpha*y(1) - beta*y(2)*y(3) - gamma*y(2)*y(2) + r(2)
          r(3) = gamma*y(2)*y(2) + r(3)
        End If
        Return
      End Subroutine resid

      Subroutine jac(neq,t,y,ydot,h,d,j,pdj)

!       .. Scalar Arguments ..
        Real (Kind=nag_wp), Intent (In) :: d, h, t
        Integer, Intent (In)           :: j, neq
!       .. Array Arguments ..
        Real (Kind=nag_wp), Intent (Inout) :: pdj(neq)
        Real (Kind=nag_wp), Intent (In) :: y(neq), ydot(neq)
!       .. Local Scalars ..
        Real (Kind=nag_wp)             :: hxd
!       .. Executable Statements ..
!       8 nonzero elements in total
        hxd = h*d
        If (j==1) Then
          pdj(1) = zero - hxd*(one)
          pdj(2) = zero - hxd*(alpha)
!         note: pdj(3) is zero
        Else If (j==2) Then
          pdj(1) = zero - hxd*(one)
          pdj(2) = one - hxd*(-beta*y(3)-two*gamma*y(2))
          pdj(3) = zero - hxd*(two*gamma*y(2))
        Else If (j==3) Then
          pdj(1) = zero - hxd*(one)
          pdj(2) = zero - hxd*(-beta*y(2))
          pdj(3) = one - hxd*(zero)
        End If
        Return
      End Subroutine jac

      Subroutine monitr(neq,ldysav,t,hlast,hnext,y,ydot,ysav,r,acor,imon,inln, &
        hmin,hmax,nqu)

!       .. Scalar Arguments ..
        Real (Kind=nag_wp), Intent (In) :: hlast, t
        Real (Kind=nag_wp), Intent (Inout) :: hmax, hmin, hnext
        Integer, Intent (Inout)        :: imon
        Integer, Intent (Out)          :: inln
        Integer, Intent (In)           :: ldysav, neq, nqu
!       .. Array Arguments ..
        Real (Kind=nag_wp), Intent (In) :: acor(neq,2), r(neq), ydot(neq),     &
                                          ysav(ldysav,*)
        Real (Kind=nag_wp), Intent (Inout) :: y(neq)
!       .. Executable Statements ..
        inln = 3
        If (y(1)<=0.9_nag_wp) Then
          imon = -2
        End If
        Return
      End Subroutine monitr
    End Module d02njfe_mod

    Program d02njfe

!     D02NJF Example Main Program

!     .. Use Statements ..
      Use nag_library, Only: d02njf, d02nuf, d02nvf, d02nxf, d02nyf, nag_wp,   &
                             x04abf
      Use d02njfe_mod, Only: iset, itrace, jac, ldysav, monitr, neq, nia, nin, &
                             nja, njcpvt, nout, nrw, nwkjac, resid
!     .. Implicit None Statement ..
      Implicit None
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: eta, h, h0, hmax, hmin, hu, sens, t, &
                                          tcrit, tcur, tinit, tolsf, tout, u
      Integer                          :: i, icall, icase, ifail, igrow,       &
                                          imxer, isplit, isplt, itask, itol,   &
                                          liwreq, liwusd, lrwreq, lrwusd,      &
                                          maxord, maxstp, mxhnil, nblock, ngp, &
                                          niter, nje, nlu, nnz, nq, nqu, nre,  &
                                          nst, outchn, sdysav
      Logical                          :: lblock, petzld
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: atol(:), rtol(:), rwork(:),          &
                                          wkjac(:), y(:), ydot(:), yinit(:),   &
                                          ysav(:,:)
      Real (Kind=nag_wp)               :: con(6)
      Integer, Allocatable             :: ia(:), ja(:), jacpvt(:)
      Integer                          :: inform(23)
      Logical, Allocatable             :: algequ(:)
      Logical                          :: lderiv(2)
!     .. Executable Statements ..
      Write (nout,*) 'D02NJF Example Program Results'
!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) maxord, maxstp, mxhnil
      sdysav = maxord + 1
      Allocate (atol(neq),rtol(neq),rwork(nrw),wkjac(nwkjac),y(neq),           &
        yinit(neq),ydot(neq),ysav(ldysav,sdysav),ia(nia),ja(nja),              &
        jacpvt(njcpvt),algequ(neq))
      Read (nin,*) ia(1:nia)
      Read (nin,*) ja(1:nja)

      outchn = nout
      Call x04abf(iset,outchn)

!     Two cases. In both cases:
!          integrate to tout by overshooting (itask=1);
!          use B.D.F formulae with a Newton method;
!          use the Petzold error test (differential algebraic system);
!          use default values for the array con;
!          employ vector relative tolerance and scalar absolute tolerance.
!          the Jacobian is supplied by jac;
!          the monitr routine is used to force a return when y(1) < 0.9.

      Read (nin,*) hmin, hmax, h0, tcrit
      Read (nin,*) eta, sens, u
      Read (nin,*) lblock
      Read (nin,*) tinit, tout
      Read (nin,*) itol, isplt
      Read (nin,*) yinit(1:neq)
      Read (nin,*) rtol(1:neq)
      Read (nin,*) atol(1)

      con(1:6) = 0.0_nag_wp
      itask = 1
      petzld = .True.

cases: Do icase = 1, 2

!       Initialize
        t = tinit
        isplit = isplt
        y(1:neq) = yinit(1:neq)
        lderiv(1:2) = .False.

        ifail = 0
        Call d02nvf(neq,sdysav,maxord,'Newton',petzld,con,tcrit,hmin,hmax,h0,  &
          maxstp,mxhnil,'Average-L2',rwork,ifail)
        Write (nout,*)

        Select Case (icase)
        Case (1)
!         First case. The Jacobian structure is determined internally by
!                     calls to jac.
          ifail = 0
          Call d02nuf(neq,neq,'Analytical',nwkjac,ia,nia,ja,nja,jacpvt,njcpvt, &
            sens,u,eta,lblock,isplit,rwork,ifail)
          Write (nout,*) '  Analytic Jacobian, structure not supplied'
        Case (2)
!         Second case. The Jacobian structure is supplied.
          ifail = 0
          Call d02nuf(neq,neq,'Full info',nwkjac,ia,nia,ja,nja,jacpvt,njcpvt,  &
            sens,u,eta,lblock,isplit,rwork,ifail)
          Write (nout,*) '  Analytic Jacobian, structure supplied'
        End Select

        Write (nout,99988)(i,i=1,neq)
        Write (nout,99999) t, (y(i),i=1,neq)

!       Soft fail and error messages only

        ifail = 1
        Call d02njf(neq,ldysav,t,tout,y,ydot,rwork,rtol,atol,itol,inform,      &
          resid,ysav,sdysav,jac,wkjac,nwkjac,jacpvt,njcpvt,monitr,lderiv,      &
          itask,itrace,ifail)

        If (ifail==0 .Or. ifail==12) Then
          Write (nout,99999) t, (y(i),i=1,neq)

          ifail = 0
          Call d02nyf(neq,neq,hu,h,tcur,tolsf,rwork,nst,nre,nje,nqu,nq,niter,  &
            imxer,algequ,inform,ifail)

          Write (nout,*)
          Write (nout,99997) hu, h, tcur
          Write (nout,99996) nst, nre, nje
          Write (nout,99995) nqu, nq, niter
          Write (nout,99994) ' Max err comp = ', imxer
          icall = 0

          Call d02nxf(icall,liwreq,liwusd,lrwreq,lrwusd,nlu,nnz,ngp,isplit,    &
            igrow,lblock,nblock,inform)

          Write (nout,*)
          Write (nout,99993) liwreq, liwusd
          Write (nout,99992) lrwreq, lrwusd
          Write (nout,99991) nlu, nnz
          Write (nout,99990) ngp, isplit
          Write (nout,99989) igrow, nblock
        Else If (ifail==10) Then
          icall = 1

          Call d02nxf(icall,liwreq,liwusd,lrwreq,lrwusd,nlu,nnz,ngp,isplit,    &
            igrow,lblock,nblock,inform)

          Write (nout,*)
          Write (nout,99993) liwreq, liwusd
          Write (nout,99992) lrwreq, lrwusd
        Else
          Write (nout,*)
          Write (nout,99998) 'Exit D02NJF with IFAIL = ', ifail, '  and T = ', &
            t
        End If
      End Do cases

99999 Format (1X,F8.3,3(F13.5,2X))
99998 Format (1X,A,I5,A,E12.5)
99997 Format (1X,' HUSED = ',E12.5,'  HNEXT = ',E12.5,'  TCUR = ',E12.5)
99996 Format (1X,' NST = ',I6,'    NRE = ',I6,'    NJE = ',I6)
99995 Format (1X,' NQU = ',I6,'    NQ  = ',I6,'  NITER = ',I6)
99994 Format (1X,A,I4)
99993 Format (1X,' NJCPVT (required ',I4,'  used ',I8,')')
99992 Format (1X,' NWKJAC (required ',I4,'  used ',I8,')')
99991 Format (1X,' No. of LU-decomps ',I4,'  No. of nonzeros ',I8)
99990 Format (1X,' No. of FCN calls to form Jacobian ',I4,'  Try ISPLIT ',I4)
99989 Format (1X,' Growth est ',I8,'  No. of blocks on diagonal ',I4)
99988 Format (/,1X,'    X ',3('         Y(',I1,')  '))
    End Program d02njfe


d02nmfe.f90

    Program d02nmfe

!     D02NMF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: d02nmf, d02nsf, d02nvf, d02nyf, d02xkf, nag_wp,   &
                             x04abf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Real (Kind=nag_wp), Parameter    :: tstep = 2.0E0_nag_wp
      Integer, Parameter               :: iset = 1, neq = 3, nin = 5,          &
                                          njcpvt = 1, nout = 6
      Integer, Parameter               :: nrw = 50 + 4*neq
      Integer, Parameter               :: nwkjac = neq*(neq+1)
      Integer, Parameter               :: sdysav = 6
      Integer, Parameter               :: ldysav = neq
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: h, h0, hlast, hmax, hmin, hnext, hu, &
                                          t, tc, tcrit, tcur, tolsf, tout,     &
                                          xout
      Integer                          :: i, ifail, iflag, imon, imxer, inln,  &
                                          ires, irevcm, itask, itol, itrace,   &
                                          lacor1, lacor2, lacor3, lacorb,      &
                                          lsavr1, lsavr2, lsavr3, lsavrb,      &
                                          maxord, maxstp, mxhnil, niter, nje,  &
                                          nq, nqu, nre, nst, outchn
      Logical                          :: petzld
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: atol(:), rtol(:), rwork(:),          &
                                          wkjac(:), y(:), ydot(:), ysav(:,:)
      Real (Kind=nag_wp)               :: con(6)
      Integer                          :: inform(23)
      Integer, Allocatable             :: jacpvt(:)
      Logical, Allocatable             :: algequ(:)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: int
!     .. Executable Statements ..
      Write (nout,*) 'D02NMF Example Program Results'
      Write (nout,*)
!     Skip heading in data file
      Read (nin,*)
!     neq: number of differential equations
      Allocate (atol(neq),rtol(neq),rwork(nrw),wkjac(nwkjac),y(neq),ydot(neq), &
        ysav(ldysav,sdysav),jacpvt(njcpvt),algequ(neq))

!     Integrate to tout by overshooting tout (itask=1) using B.D.F.
!     formulae with a Newton method. Default values for the array con
!     are used. Employ scalar tolerances and the Jacobian is evaluated
!     internally. On the reverse communication call equivalent to the
!     monitr call in forward communication routines carry out
!     interpolation using D02XKF.

      Read (nin,*) maxord, maxstp, mxhnil
      Read (nin,*) hmin, hmax, h0, tcrit
      Read (nin,*) petzld
      Read (nin,*) t, tout
      Read (nin,*) itol
      Read (nin,*) y(1:neq)
      Read (nin,*) rtol(1), atol(1)

      outchn = nout
      Call x04abf(iset,outchn)
      itask = 1
      xout = tstep
      con(1:6) = 0.0E0_nag_wp

      ifail = 0
      Call d02nvf(neq,sdysav,maxord,'Newton',petzld,con,tcrit,hmin,hmax,h0,    &
        maxstp,mxhnil,'Average-L2',rwork,ifail)

      ifail = 0
      Call d02nsf(neq,neq,'Numerical',nwkjac,rwork,ifail)

      lacorb = 50 + neq
      lacor1 = lacorb + 1
      lacor2 = lacorb + 2
      lacor3 = lacorb + 3
      lsavrb = lacorb + neq
      lsavr1 = lsavrb + 1
      lsavr2 = lsavrb + 2
      lsavr3 = lsavrb + 3
      Write (nout,*) '    X          Y(1)           Y(2)           Y(3)'
      Write (nout,99999) t, (y(i),i=1,neq)

!     Soft fail and error messages only
      irevcm = 0
      itrace = 0

steps: Do
        ifail = 1
        Call d02nmf(neq,ldysav,t,tout,y,ydot,rwork,rtol,atol,itol,inform,ysav, &
          sdysav,wkjac,nwkjac,jacpvt,njcpvt,imon,inln,ires,irevcm,itask,       &
          itrace,ifail)

        Select Case (irevcm)
        Case (0)
          Exit steps
        Case (1,3)
!         Equivalent to fcn evaluation in forward communication
!         routines
          rwork(lsavr1) = -0.04E0_nag_wp*y(1) + 1.0E4_nag_wp*y(2)*y(3)
          rwork(lsavr2) = 0.04E0_nag_wp*y(1) - 1.0E4_nag_wp*y(2)*y(3) -        &
            3.0E7_nag_wp*y(2)*y(2)
          rwork(lsavr3) = 3.0E7_nag_wp*y(2)*y(2)
        Case (4)
!         Equivalent to fcn evaluation in forward communication
!         routines
          rwork(lacor1) = -0.04E0_nag_wp*y(1) + 1.0E4_nag_wp*y(2)*y(3)
          rwork(lacor2) = 0.04E0_nag_wp*y(1) - 1.0E4_nag_wp*y(2)*y(3) -        &
            3.0E7_nag_wp*y(2)*y(2)
          rwork(lacor3) = 3.0E7_nag_wp*y(2)*y(2)
        Case (5)
!         Equivalent to fcn evaluation in forward communication
!         routines
          ydot(1) = -0.04E0_nag_wp*y(1) + 1.0E4_nag_wp*y(2)*y(3)
          ydot(2) = 0.04E0_nag_wp*y(1) - 1.0E4_nag_wp*y(2)*y(3) -              &
            3.0E7_nag_wp*y(2)*y(2)
          ydot(3) = 3.0E7_nag_wp*y(2)*y(2)
        Case (9)
!         Equivalent to monitr call in forward communication routines
          If (imon==1) Then
            tc = rwork(19)
            hlast = rwork(15)
            hnext = rwork(16)
            nqu = int(rwork(10))
interp:     Do
              If (tc-hlast<xout .And. xout<=tc) Then
                iflag = 1

                Call d02xkf(xout,rwork(lsavr1),neq,ysav,ldysav,sdysav,         &
                  rwork(lacor1),neq,tc,nqu,hlast,hnext,iflag)

                If (iflag/=0) Then
                  imon = -2
                  Exit interp
                Else
                  Write (nout,99999) xout, (rwork(lsavrb+i),i=1,neq)
                  xout = xout + tstep
                  If (xout>tout) Then
                    Exit interp
                  End If
                End If
              Else
                Exit interp
              End If
            End Do interp
          End If
        Case (2,6:8)
          Write (nout,*)
          Write (nout,99994) 'Illegal value of IREVCM = ', irevcm
          Exit steps
        End Select
      End Do steps
      If (ifail==0) Then

        iflag = 0
        Call d02nyf(neq,neq,hu,h,tcur,tolsf,rwork,nst,nre,nje,nqu,nq,niter,    &
          imxer,algequ,inform,iflag)

        Write (nout,*)
        Write (nout,99997) hu, h, tcur
        Write (nout,99996) nst, nre, nje
        Write (nout,99995) nqu, nq, niter
        Write (nout,99994) ' Max err comp = ', imxer
        Write (nout,*)
      Else
        Write (nout,*)
        Write (nout,99998) 'Exit D02NMF with IFAIL = ', ifail, '  and T = ', t
      End If

99999 Format (1X,F8.3,3(F13.5,2X))
99998 Format (1X,A,I2,A,E12.5)
99997 Format (1X,' HUSED = ',E12.5,'  HNEXT = ',E12.5,'  TCUR = ',E12.5)
99996 Format (1X,' NST = ',I6,'    NRE = ',I6,'    NJE = ',I6)
99995 Format (1X,' NQU = ',I6,'    NQ  = ',I6,'  NITER = ',I6)
99994 Format (1X,A,I4)
    End Program d02nmfe


d02nnfe.f90

    Program d02nnfe

!     D02NNF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: d02mzf, d02nnf, d02nrf, d02nuf, d02nvf, d02nxf,   &
                             d02nyf, nag_wp, x04abf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Real (Kind=nag_wp), Parameter    :: alpha = 0.04_nag_wp
      Real (Kind=nag_wp), Parameter    :: beta = 1.0E4_nag_wp
      Real (Kind=nag_wp), Parameter    :: gamma = 3.0E7_nag_wp
      Real (Kind=nag_wp), Parameter    :: one = 1.0_nag_wp
      Real (Kind=nag_wp), Parameter    :: zero = 0.0_nag_wp
      Real (Kind=nag_wp), Parameter    :: gamm2 = 2.0_nag_wp*gamma
      Integer, Parameter               :: iset = 1, itrace = 0, nelts = 8,     &
                                          neq = 3, nia = 1, nin = 5, nja = 1
      Integer, Parameter               :: njcpvt = 20*neq + 12*nelts
      Integer, Parameter               :: nout = 6
      Integer, Parameter               :: nrw = 50 + 4*neq
      Integer, Parameter               :: nwkjac = 4*neq + 12*nelts
      Integer, Parameter               :: ldysav = neq
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: eta, h, h0, hmax, hmin, hu, hxd,     &
                                          sens, t, tcrit, tcur, tolsf, tout, u
      Integer                          :: i, icall, ifail, igrow, imon, imxer, &
                                          indd, indr, inln, iplace, ires,      &
                                          irevcm, isplit, itask, itol, j,      &
                                          liwreq, liwusd, lrwreq, lrwusd,      &
                                          maxord, maxstp, mxhnil, nblock,      &
                                          nfails, ngp, niter, nje, nlu, nnz,   &
                                          nq, nqu, nre, nst, outchn, sdysav
      Logical                          :: lblock, petzld
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: atol(:), rtol(:), rwork(:),          &
                                          wkjac(:), y(:), ydot(:), ysav(:,:)
      Real (Kind=nag_wp)               :: con(6)
      Integer                          :: ia(nia), inform(23), ja(nja)
      Integer, Allocatable             :: jacpvt(:)
      Logical, Allocatable             :: algequ(:)
      Logical                          :: lderiv(2)
!     .. Executable Statements ..
      Write (nout,*) 'D02NNF Example Program Results'
!     Skip heading in data file
      Read (nin,*)
!     neq: number of differential equations
      Read (nin,*) maxord, maxstp, mxhnil
      sdysav = maxord + 1
      Allocate (atol(neq),rtol(neq),rwork(nrw),wkjac(nwkjac),y(neq),ydot(neq), &
        ysav(ldysav,sdysav),jacpvt(njcpvt),algequ(neq))

      outchn = nout
      Write (nout,*)
      Call x04abf(iset,outchn)

!     Integrate towards tout stopping at the first mesh point beyond
!     tout (itask=3) using the B.D.F. formulae with a Newton method.
!     Employ scalar tolerances and the Jacobian is supplied, but its
!     structure is evaluated internally by calls to the Jacobian
!     forming part of the program (irevcm=8). Default values for the
!     array con are used. Also count the number of step failures
!     (irevcm=10). The solution is interpolated using D02MZF to give
!     the solution at tout.

      Read (nin,*) hmin, hmax, h0, tcrit
      Read (nin,*) eta, sens, u
      Read (nin,*) lblock, petzld
      Read (nin,*) t, tout
      Read (nin,*) itol, isplit
      Read (nin,*) y(1:neq)
      Select Case (itol)
      Case (1)
        Read (nin,*) rtol(1), atol(1)
      Case (2)
        Read (nin,*) rtol(1), atol(1:neq)
      Case (3)
        Read (nin,*) rtol(1:neq), atol(1)
      Case (4)
        Read (nin,*) rtol(1:neq), atol(1:neq)
      End Select

      itask = 3
      lderiv(1:2) = .False.
      con(1:6) = zero
      nfails = 0

!     ifail: behaviour on error exit
!             =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
      ifail = 0
      Call d02nvf(neq,sdysav,maxord,'Newton',petzld,con,tcrit,hmin,hmax,h0,    &
        maxstp,mxhnil,'Average-l2',rwork,ifail)

      ifail = 0
      Call d02nuf(neq,neq,'Analytical',nwkjac,ia,nia,ja,nja,jacpvt,njcpvt,     &
        sens,u,eta,lblock,isplit,rwork,ifail)

      irevcm = 0
      Write (nout,*) '    X          Y(1)           Y(2)           Y(3)'
      Write (nout,99999) t, (y(i),i=1,neq)
      Flush (nout)

revcm: Do
        ifail = -1
        Call d02nnf(neq,ldysav,t,tout,y,ydot,rwork,rtol,atol,itol,inform,ysav, &
          sdysav,wkjac,nwkjac,jacpvt,njcpvt,imon,inln,ires,irevcm,lderiv,      &
          itask,itrace,ifail)

        Select Case (irevcm)
        Case (0)
!         Final exit.
          Exit revcm
        Case (1,3,4,6,7,11)
          If (irevcm==4 .Or. irevcm==7) Then
            indr = 50 + neq
          Else
            indr = 50 + 2*neq
          End If
!         Return residual in rwork(indr+1:indr+neq) using y' in ydot.
          rwork(indr+1) = -ydot(1) - ydot(2) - ydot(3)
          rwork(indr+2) = -ydot(2)
          rwork(indr+3) = -ydot(3)
          If (ires==1) Then
            rwork(indr+1) = rwork(indr+1) + zero
            rwork(indr+2) = rwork(indr+2) + alpha*y(1) - beta*y(2)*y(3) -      &
              gamma*y(2)*y(2)
            rwork(indr+3) = rwork(indr+3) + gamma*y(2)*y(2)
          End If
        Case (2)
!         Return residual in rwork(51+2*neq:) using y' in rwork(51+neq:).
          indd = 50 + neq
          indr = 50 + 2*neq
          rwork(indr+1) = -rwork(indd+1) - rwork(indd+2) - rwork(indd+3)
          rwork(indr+2) = -rwork(indd+2)
          rwork(indr+3) = -rwork(indd+3)
        Case (5)
!         Return residual in ydot, using y' in rwork(51+2*neq:).
          indd = 50 + 2*neq
          ydot(1) = -rwork(indd+1) - rwork(indd+2) - rwork(indd+3)
          ydot(2) = -rwork(indd+2)
          ydot(3) = -rwork(indd+3)
          ydot(1) = ydot(1) + zero
          ydot(2) = ydot(2) + alpha*y(1) - beta*y(2)*y(3) - gamma*y(2)*y(2)
          ydot(3) = ydot(3) + gamma*y(2)*y(2)
        Case (8)
!         Return Jacobian in rwork(51+neq:) or rwork(51+2*neq:).

!         Get index J for Jacoban evaluation.
          Call d02nrf(j,iplace,inform)

          hxd = rwork(16)*rwork(20)
          If (iplace<2) Then
!           return Jacobian in rwork(51+2*neq:).
            indr = 50 + 2*neq
          Else
!           return Jacobian in rwork(51+neq:).
            indr = 50 + neq
          End If
!         8 nonzero elements in Jacobian.
          If (j<2) Then
            rwork(indr+1) = one - hxd*(zero)
            rwork(indr+2) = zero - hxd*(alpha)
!           rwork(indr+3) = zero - hxd*(zero)
          Else If (j==2) Then
            rwork(indr+1) = one - hxd*(zero)
            rwork(indr+2) = one - hxd*(-beta*y(3)-gamm2*y(2))
            rwork(indr+3) = zero - hxd*(gamm2*y(2))
          Else If (j>2) Then
            rwork(indr+1) = one - hxd*(zero)
            rwork(indr+2) = zero - hxd*(-beta*y(2))
            rwork(indr+3) = one - hxd*(zero)
          End If
        Case (10)
!         Step failure
          nfails = nfails + 1
        End Select
      End Do revcm

!     Print solution and statistics.
      If (ifail==0) Then

        Call d02nyf(neq,neq,hu,h,tcur,tolsf,rwork,nst,nre,nje,nqu,nq,niter,    &
          imxer,algequ,inform,ifail)

        ifail = 0
        Call d02mzf(tout,y,neq,ldysav,neq,ysav,sdysav,rwork,ifail)

        Write (nout,99999) tout, (y(i),i=1,neq)
        Write (nout,99997) hu, h, tcur
        Write (nout,99996) nst, nre, nje
        Write (nout,99995) nqu, nq, niter
        Write (nout,99994) imxer, nfails
        icall = 0

        Call d02nxf(icall,liwreq,liwusd,lrwreq,lrwusd,nlu,nnz,ngp,isplit,      &
          igrow,lblock,nblock,inform)

        Write (nout,99993) liwreq, liwusd
        Write (nout,99992) lrwreq, lrwusd
        Write (nout,99991) nlu, nnz
        Write (nout,99990) ngp, isplit
        Write (nout,99989) igrow, nblock
      Else If (ifail==10) Then
        icall = 1

        Call d02nxf(icall,liwreq,liwusd,lrwreq,lrwusd,nlu,nnz,ngp,isplit,      &
          igrow,lblock,nblock,inform)

        Write (nout,99993) liwreq, liwusd
        Write (nout,99992) lrwreq, lrwusd
      Else
        Write (nout,99998) ifail, t
      End If

99999 Format (1X,F8.3,3(F13.5,2X))
99998 Format (/,1X,'Exit D02NNF with IFAIL = ',I5,'  and T = ',E12.5)
99997 Format (/,1X,' HUSED = ',E12.5,'  HNEXT = ',E12.5,'  TCUR = ',E12.5)
99996 Format (1X,' NST = ',I6,'    NRE = ',I6,'    NJE = ',I6)
99995 Format (1X,' NQU = ',I6,'    NQ  = ',I6,'  NITER = ',I6)
99994 Format (1X,' Max err comp = ',I4,'   No. of failed steps = ',I4)
99993 Format (/,1X,' NJCPVT (required ',I4,'  used ',I8,')')
99992 Format (1X,' NWKJAC (required ',I4,'  used ',I8,')')
99991 Format (1X,' No. of LU-decomps ',I4,'  No. of nonzeros ',I8)
99990 Format (1X,' No. of FCN calls to form Jacobian ',I4,'  Try ISPLIT ',I4)
99989 Format (1X,' Growth est ',I8,'  No. of blocks on diagonal ',I4)
    End Program d02nnfe


d02pefe.f90

!   D02PEF Example Program Text
!   Mark 26 Release. NAG Copyright 2016.

    Module d02pefe_mod

!     D02PEF Example Program Module:
!            Parameters and User-defined Routines

!     .. Use Statements ..
      Use nag_library, Only: nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Accessibility Statements ..
      Private
      Public                           :: f
!     .. Parameters ..
      Real (Kind=nag_wp), Parameter, Public :: tol0 = 1.0E-3_nag_wp
      Integer, Parameter, Public       :: liwsav = 130, n = 2, nin = 5,        &
                                          nout = 6, npts = 8
      Integer, Parameter, Public       :: lrwsav = 350 + 32*n
    Contains

      Subroutine f(t,n,y,yp,iuser,ruser)

!       .. Scalar Arguments ..
        Real (Kind=nag_wp), Intent (In) :: t
        Integer, Intent (In)           :: n
!       .. Array Arguments ..
        Real (Kind=nag_wp), Intent (Inout) :: ruser(*)
        Real (Kind=nag_wp), Intent (In) :: y(n)
        Real (Kind=nag_wp), Intent (Out) :: yp(n)
        Integer, Intent (Inout)        :: iuser(*)
!       .. Executable Statements ..
        yp(1) = y(2)
        yp(2) = -y(1)
        Return
      End Subroutine f
    End Module d02pefe_mod

    Program d02pefe

!     D02PEF Example Main Program

!     .. Use Statements ..
      Use nag_library, Only: d02pef, d02pqf, d02ptf, nag_wp
      Use d02pefe_mod, Only: f, liwsav, lrwsav, n, nin, nout, npts, tol0
!     .. Implicit None Statement ..
      Implicit None
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: hnext, hstart, tend, tgot, tinc,     &
                                          tol, tstart, twant, waste
      Integer                          :: fevals, i, ifail, j, method,         &
                                          stepcost, stepsok
!     .. Local Arrays ..
      Real (Kind=nag_wp)               :: ruser(1), thresh(n), ygot(n),        &
                                          yinit(n), ymax(n), ypgot(n)
      Real (Kind=nag_wp), Allocatable  :: rwsav(:)
      Integer                          :: iuser(1)
      Integer, Allocatable             :: iwsav(:)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: real
!     .. Executable Statements ..
      Write (nout,*) 'D02PEF Example Program Results'

      Allocate (iwsav(liwsav),rwsav(lrwsav))

!     Set initial conditions and input for D02PQF

!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) method
      Read (nin,*) tstart, tend
      Read (nin,*) yinit(1:n)
      Read (nin,*) hstart
      Read (nin,*) thresh(1:n)

!     Set control for output

      tinc = (tend-tstart)/real(npts,kind=nag_wp)

      tol = 10.0_nag_wp*tol0

loop: Do i = 1, 2
        tol = tol*0.1_nag_wp

!       ifail: behaviour on error exit
!              =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
        ifail = 0
        Call d02pqf(n,tstart,tend,yinit,tol,thresh,method,hstart,iwsav,rwsav,  &
          ifail)

        Write (nout,99999) tol
        Write (nout,99998)
        Write (nout,99997) tstart, yinit(1:n)
        twant = tstart
        Do j = 1, npts
          twant = twant + tinc

          ifail = 0
          Call d02pef(f,n,twant,tgot,ygot,ypgot,ymax,iuser,ruser,iwsav,rwsav,  &
            ifail)

          Write (nout,99997) tgot, ygot(1:n)
        End Do

        ifail = 0
        Call d02ptf(fevals,stepcost,waste,stepsok,hnext,iwsav,rwsav,ifail)
        Write (nout,99996) fevals

      End Do loop

99999 Format (/,' Calculation with TOL = ',1P,E8.1)
99998 Format (/,'    t         y1        y2',/)
99997 Format (1X,F6.3,2(3X,F7.3))
99996 Format (/,' Cost of the integration in evaluations of F is',I6)
    End Program d02pefe


d02pffe.f90

!   D02PFF Example Program Text
!   Mark 26 Release. NAG Copyright 2016.

    Module d02pffe_mod

!     D02PFF Example Program Module:
!            Parameters and User-defined Routines

!     .. Use Statements ..
      Use nag_library, Only: nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Accessibility Statements ..
      Private
      Public                           :: f
!     .. Parameters ..
      Real (Kind=nag_wp), Parameter, Public :: tol1 = 1.0E-4_nag_wp
      Real (Kind=nag_wp), Parameter, Public :: tol2 = 1.0E-5_nag_wp
      Integer, Parameter, Public       :: liwsav = 130, n = 2, nin = 5,        &
                                          nout = 6
      Integer, Parameter, Public       :: lrwsav = 350 + 32*n
    Contains
      Subroutine f(t,n,y,yp,iuser,ruser)

!       .. Scalar Arguments ..
        Real (Kind=nag_wp), Intent (In) :: t
        Integer, Intent (In)           :: n
!       .. Array Arguments ..
        Real (Kind=nag_wp), Intent (Inout) :: ruser(*)
        Real (Kind=nag_wp), Intent (In) :: y(n)
        Real (Kind=nag_wp), Intent (Out) :: yp(n)
        Integer, Intent (Inout)        :: iuser(*)
!       .. Executable Statements ..
        yp(1) = y(2)
        yp(2) = -y(1)
        Return
      End Subroutine f
    End Module d02pffe_mod

    Program d02pffe

!     D02PFF Example Main Program

!     .. Use Statements ..
      Use nag_library, Only: d02pff, d02pqf, d02ptf, nag_wp
      Use d02pffe_mod, Only: f, liwsav, lrwsav, n, nin, nout, tol1, tol2
!     .. Implicit None Statement ..
      Implicit None
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: hnext, hstart, tend, tnow, tol,      &
                                          tstart, waste
      Integer                          :: i, ifail, method, stpcst, stpsok,    &
                                          totf
!     .. Local Arrays ..
      Real (Kind=nag_wp)               :: ruser(1)
      Real (Kind=nag_wp), Allocatable  :: rwsav(:), thres(:), ynow(:),         &
                                          ypnow(:), ystart(:)
      Integer                          :: iuser(1)
      Integer, Allocatable             :: iwsav(:)
!     .. Executable Statements ..
      Write (nout,*) 'D02PFF Example Program Results'
!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) method
      Allocate (thres(n),iwsav(liwsav),rwsav(lrwsav),ynow(n),ypnow(n),         &
        ystart(n))

!     Set initial conditions and input for D02PQF

      Read (nin,*) tstart, tend
      Read (nin,*) ystart(1:n)
      Read (nin,*) hstart
      Read (nin,*) thres(1:n)

      Do i = 1, 2
        If (i==1) Then
          tol = tol1
        End If
        If (i==2) Then
          tol = tol2
        End If

!       ifail: behaviour on error exit
!              =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
        ifail = 0
        Call d02pqf(n,tstart,tend,ystart,tol,thres,method,hstart,iwsav,rwsav,  &
          ifail)

        Write (nout,99999) tol
        Write (nout,99998)
        Write (nout,99997) tstart, ystart(1:n)

loop:   Do
          ifail = 0
          Call d02pff(f,n,tnow,ynow,ypnow,iuser,ruser,iwsav,rwsav,ifail)

          If (ifail==0) Then
            Write (nout,99997) tnow, ynow(1:n)
            If (tnow>=tend) Then
              Exit loop
            End If
          Else
            Exit loop
          End If

        End Do loop

        ifail = 0
        Call d02ptf(totf,stpcst,waste,stpsok,hnext,iwsav,rwsav,ifail)
        Write (nout,99996) totf
      End Do

99999 Format (/,' Calculation with TOL = ',E8.1)
99998 Format (/,'    t         y1        y2',/)
99997 Format (1X,F6.3,2(3X,F8.4))
99996 Format (/,' Cost of the integration in evaluations of F is',I6)
    End Program d02pffe


d02pgfe.f90

!   D02PGF Example Program Text
!   Mark 26 Release. NAG Copyright 2016.

    Module d02pgfe_mod

!     D02PGF Example Program Module:
!            Parameters

!     .. Use Statements ..
      Use nag_library, Only: nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Accessibility Statements ..
      Private
!     .. Parameters ..
      Real (Kind=nag_wp), Parameter, Public :: tol = 1.0E-5_nag_wp
      Integer, Parameter, Public       :: liwsav = 130, n = 2, nin = 5,        &
                                          nout = 6
      Integer, Parameter, Public       :: lrwsav = 350 + 32*n
      Integer, Parameter, Public       :: lwcomm = 6*n
    End Module d02pgfe_mod

    Program d02pgfe

!     D02PGF Example Main Program

!     .. Use Statements ..
      Use nag_library, Only: c05azf, d02pgf, d02phf, d02pjf, d02pqf, d02ptf,   &
                             nag_wp
      Use d02pgfe_mod, Only: liwsav, lrwsav, lwcomm, n, nin, nout, tol
!     .. Implicit None Statement ..
      Implicit None
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: hnext, hstart, t, t1, t2, tend,      &
                                          tnow, tout, tprev, waste
      Integer                          :: i, icheck, ifail, ind, irevcm, j,    &
                                          method, nchange, stpcst, stpsok,     &
                                          totf
!     .. Local Arrays ..
      Real (Kind=nag_wp)               :: c(17)
      Real (Kind=nag_wp), Allocatable  :: rwsav(:), thres(:), troot(:),        &
                                          wcomm(:), y(:), ynow(:), yout(:),    &
                                          yp(:), ypnow(:), yprev(:)
      Integer, Allocatable             :: iroot(:), iwsav(:)
!     .. Executable Statements ..
      Write (nout,*) 'D02PGF Example Program Results'
!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) method
      Allocate (thres(n),iwsav(liwsav),rwsav(lrwsav),ynow(n),ypnow(n),         &
        yprev(n),wcomm(lwcomm),yout(n),iroot(n),y(n),yp(n),troot(n))

!     Set initial conditions and input for D02PQF

      Read (nin,*) t, tend
      Read (nin,*) ynow(1:n)
      Read (nin,*) hstart
      Read (nin,*) thres(1:n)

!     ifail: behaviour on error exit
!            =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
      ifail = 0
      Call d02pqf(n,t,tend,ynow,tol,thres,method,hstart,iwsav,rwsav,ifail)

      Write (nout,99999) tol
      Write (nout,99998)
      Write (nout,99997) t, ynow(1:n)

      tout = 0.1_nag_wp
      tnow = t
      Do While (tnow<tend)
!       Integrate by one time step using reverse communication
        tprev = tnow
        yprev(1:n) = ynow(1:n)
        ifail = 1
        irevcm = 0
        Do While (irevcm>=0)
          Call d02pgf(irevcm,n,tnow,ynow,ypnow,iwsav,rwsav,ifail)
          If (irevcm>0) Then
            ypnow(1) = ynow(2)
            ypnow(2) = -ynow(1)
          End If
        End Do
        If (ifail==1 .Or. ifail>4) Then
          Write (6,99996) ifail, tnow
          Go To 100
        End If

!       Detect sign changes in last step
        iroot(1:n) = 0
        nchange = 0
        Do i = 1, n
          If (ynow(i)*yprev(i)<0.0_nag_wp) Then
            nchange = nchange + 1
            iroot(nchange) = i
          End If
        End Do

!       Interpolate for values of t at increments of 0.1 within step and
!       find roots of components of y.
        If (tnow>=tout .Or. nchange>0) Then
!         Set up interpolation by reverse communication
          ifail = 0
          irevcm = 0
          Do While (irevcm>=0)
            ifail = 0
            Call d02phf(irevcm,n,n,t,y,yp,wcomm,lwcomm,iwsav,rwsav,ifail)
            If (irevcm>0) Then
              yp(1) = y(2)
              yp(2) = -y(1)
            End If
          End Do

          icheck = 1
!         If there are sign changes: find roots
          Do i = 1, nchange
            j = iroot(i)
            t1 = tprev
            t2 = tnow
            ind = 1
            ifail = 0
            Do While (ind/=0)
              Call c05azf(t1,t2,y(j),tol,1,c,ind,ifail)
              If (ind>1) Then
                ifail = 0
                Call d02pjf(icheck,n,n,t1,0,y,wcomm,lwcomm,iwsav,rwsav,ifail)
                icheck = 0
              End If
            End Do
            troot(i) = t1
          End Do
!         Evaluate Interpolant at increments and print any contained roots
          ifail = 0
          Do While (tnow>=tout)
            Do i = 1, nchange
              If (troot(i)<tout .And. iroot(i)>0) Then
                Write (nout,99995) iroot(i), troot(i)
                iroot(i) = -iroot(i)
              End If
            End Do
            Call d02pjf(icheck,n,n,tout,0,yout,wcomm,lwcomm,iwsav,rwsav,ifail)
            icheck = 0
            Write (nout,99997) tout, yout(1:n)
            tout = tout + 0.1_nag_wp
          End Do
!         Print any remaining roots up to current time
          Do i = 1, nchange
            If (iroot(i)>0) Then
              Write (nout,99995) iroot(i), troot(i)
            End If
          End Do
        End If
      End Do

!     Print some integration statistics
      ifail = 0
      Call d02ptf(totf,stpcst,waste,stpsok,hnext,iwsav,rwsav,ifail)
      Write (nout,99994) totf
100   Continue

99999 Format (/,' Calculation with TOL = ',E8.1)
99998 Format (/,'    t         y1        y2',/)
99997 Format (1X,F6.3,2(3X,F8.4))
99996 Format (/,'D02PGF returned with ifail = ',I3,' at t = ',E12.5,'.')
99995 Format ('Component ',I2,' has a root at t = ',F7.4)
99994 Format (/,' Cost of the integration in evaluations of F is',I6)
    End Program d02pgfe


d02prfe.f90

!   D02PRF Example Program Text
!   Mark 26 Release. NAG Copyright 2016.

    Module d02prfe_mod

!     D02PRF Example Program Module:
!            Parameters and User-defined Routines

!     .. Use Statements ..
      Use nag_library, Only: nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Accessibility Statements ..
      Private
      Public                           :: f
!     .. Parameters ..
      Real (Kind=nag_wp), Parameter, Public :: tol0 = 1.0E-4_nag_wp
      Integer, Parameter, Public       :: n = 4, nin = 5, nout = 6, npts = 6
      Integer, Parameter, Public       :: lrwsav = 350 + 32*n
    Contains
      Subroutine f(t,n,y,yp,iuser,ruser)

!       .. Scalar Arguments ..
        Real (Kind=nag_wp), Intent (In) :: t
        Integer, Intent (In)           :: n
!       .. Array Arguments ..
        Real (Kind=nag_wp), Intent (Inout) :: ruser(*)
        Real (Kind=nag_wp), Intent (In) :: y(n)
        Real (Kind=nag_wp), Intent (Out) :: yp(n)
        Integer, Intent (Inout)        :: iuser(*)
!       .. Local Scalars ..
        Real (Kind=nag_wp)             :: r
!       .. Intrinsic Procedures ..
        Intrinsic                      :: sqrt
!       .. Executable Statements ..
        r = sqrt(y(1)**2+y(2)**2)
        yp(1) = y(3)
        yp(2) = y(4)
        yp(3) = -y(1)/r**3
        yp(4) = -y(2)/r**3
        Return
      End Subroutine f
    End Module d02prfe_mod

    Program d02prfe

!     D02PRF Example Main Program

!     .. Use Statements ..
      Use nag_library, Only: d02pff, d02pqf, d02prf, d02ptf, nag_wp
      Use d02prfe_mod, Only: f, lrwsav, n, nin, nout, npts, tol0
!     .. Implicit None Statement ..
      Implicit None
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: hnext, hstart, tendnu, tfinal, tinc, &
                                          tnow, tol, tstart, waste
      Integer                          :: fevals, i, ifail, method, stepcost,  &
                                          stepsok
!     .. Local Arrays ..
      Real (Kind=nag_wp)               :: ruser(1)
      Real (Kind=nag_wp), Allocatable  :: rwsav(:), thresh(:), yinit(:),       &
                                          ynow(:), ypnow(:)
      Integer                          :: iuser(1)
      Integer, Allocatable             :: iwsav(:)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: real
!     .. Executable Statements ..
      Write (nout,*) 'D02PRF Example Program Results'
!     Skip heading in data file
      Read (nin,*)
!     n: number of differential equations
      Allocate (thresh(n),iwsav(130),rwsav(lrwsav),ynow(n),ypnow(n),yinit(n))

!     Set initial conditions and input for D02PQF

      Read (nin,*) method
      Read (nin,*) tstart, tfinal
      Read (nin,*) yinit(1:n)
      Read (nin,*) hstart
      Read (nin,*) thresh(1:n)

!     Set output control

      tinc = (tfinal-tstart)/real(npts,kind=nag_wp)

      tol = 10.0_nag_wp*tol0
      Do i = 1, 2
        tol = tol*0.1_nag_wp

        tendnu = tstart + tinc

!       ifail: behaviour on error exit
!              =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
        ifail = 0
        Call d02pqf(n,tstart,tendnu,yinit,tol,thresh,method,hstart,iwsav,      &
          rwsav,ifail)

        Write (nout,99999) tol
        Write (nout,99998)
        Write (nout,99997) tstart, yinit(1:n)

tstep:  Do
          ifail = 0
          Call d02pff(f,n,tnow,ynow,ypnow,iuser,ruser,iwsav,rwsav,ifail)

          If (tnow==tendnu) Then
            Write (nout,99997) tnow, ynow(1:n)

            If (tnow>=tfinal) Then
              Exit tstep
            End If
            tendnu = tendnu + tinc
            Call d02prf(tendnu,iwsav,rwsav,ifail)
          End If

        End Do tstep

        ifail = 0
        Call d02ptf(fevals,stepcost,waste,stepsok,hnext,iwsav,rwsav,ifail)
        Write (nout,99996) fevals
      End Do

99999 Format (/,' Calculation with TOL = ',1P,E8.1)
99998 Format (/,'    t         y1         y2         y3         y4',/)
99997 Format (1X,F6.3,4(3X,F8.4))
99996 Format (/,' Cost of the integration in evaluations of F is',I6)

    End Program d02prfe


d02psfe.f90

!   D02PSF Example Program Text
!   Mark 26 Release. NAG Copyright 2016.

    Module d02psfe_mod

!     D02PSF Example Program Module:
!            Parameters and User-defined Routines

!     .. Use Statements ..
      Use nag_library, Only: nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Accessibility Statements ..
      Private
      Public                           :: f
!     .. Parameters ..
      Real (Kind=nag_wp), Parameter, Public :: tol0 = 1.0E-3_nag_wp
      Integer, Parameter, Public       :: n = 2, nin = 5, nout = 6, npts = 16, &
                                          nwant = 1
      Integer, Parameter, Public       :: lrwsav = 350 + 32*n
    Contains
      Subroutine f(t,n,y,yp,iuser,ruser)

!       .. Scalar Arguments ..
        Real (Kind=nag_wp), Intent (In) :: t
        Integer, Intent (In)           :: n
!       .. Array Arguments ..
        Real (Kind=nag_wp), Intent (Inout) :: ruser(*)
        Real (Kind=nag_wp), Intent (In) :: y(n)
        Real (Kind=nag_wp), Intent (Out) :: yp(n)
        Integer, Intent (Inout)        :: iuser(*)
!       .. Executable Statements ..
        yp(1) = y(2)
        yp(2) = -y(1)
        Return
      End Subroutine f
    End Module d02psfe_mod

    Program d02psfe

!     D02PSF Example Main Program

!     .. Use Statements ..
      Use nag_library, Only: d02pff, d02pqf, d02psf, d02ptf, nag_wp
      Use d02psfe_mod, Only: f, lrwsav, n, nin, nout, npts, nwant, tol0
!     .. Implicit None Statement ..
      Implicit None
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: hnext, hstart, tend, tinc, tnow,     &
                                          tol, tstart, twant, waste
      Integer                          :: fevals, i, ideriv, ifail, lwcomm,    &
                                          method, stepcost, stepsok
!     .. Local Arrays ..
      Real (Kind=nag_wp)               :: ruser(1), thresh(n), yinit(n),       &
                                          ynow(n), ypnow(n), ypwant(nwant),    &
                                          ywant(nwant)
      Real (Kind=nag_wp), Allocatable  :: rwsav(:), wcomm(:)
      Integer                          :: iuser(1), iwsav(130)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: real
!     .. Executable Statements ..
      Write (nout,*) 'D02PSF Example Program Results'
!     Skip heading in data file
      Read (nin,*)

      lwcomm = n + 5*nwant
      Allocate (rwsav(lrwsav),wcomm(lwcomm))

      wcomm(1:lwcomm) = 0.0_nag_wp

!     Set initial conditions and input for D02PQF

      Read (nin,*) method
      Read (nin,*) tstart, tend
      Read (nin,*) yinit(1:n)
      Read (nin,*) hstart
      Read (nin,*) thresh(1:n)

!     Set output control

      tinc = (tend-tstart)/real(npts,kind=nag_wp)

      tol = tol0*10.0_nag_wp
      Do i = 1, 2
        tol = tol*0.1_nag_wp

!       Set up integration.
        ifail = 0
        Call d02pqf(n,tstart,tend,yinit,tol,thresh,method,hstart,iwsav,rwsav,  &
          ifail)

        Write (nout,99999) tol
        Write (nout,99998)
        Write (nout,99997) tstart, yinit(1:n)

!       Set up first point at which solution is desired.
        twant = tstart + tinc
        tnow = tstart

!       Integrate by steps until tend is reached or error is encountered.

integ:  Do While (tnow<tend)

!         Integrate one step to tnow.
          ifail = 0
          Call d02pff(f,n,tnow,ynow,ypnow,iuser,ruser,iwsav,rwsav,ifail)

!         Interpolate at required additional points up to tnow.
interp:   Do While (twant<=tnow)

!           Interpolate and print solution at t = twant.

            ideriv = 2
            ifail = 0
            Call d02psf(n,twant,ideriv,nwant,ywant,ypwant,f,wcomm,lwcomm,      &
              iuser,ruser,iwsav,rwsav,ifail)
            Write (nout,99997) twant, ywant(1), ypwant(1)

!           Set next required solution point
            twant = twant + tinc
          End Do interp

        End Do integ

!       Get integration statistics.
        ifail = 0
        Call d02ptf(fevals,stepcost,waste,stepsok,hnext,iwsav,rwsav,ifail)

        Write (nout,99996) fevals

      End Do
99999 Format (/,' Calculation with TOL = ',1P,E8.1)
99998 Format (/,'    t         y1         y1''',/)
99997 Format (1X,F6.3,2(3X,F8.4))
99996 Format (/,' Cost of the integration in evaluations of F is',I6)

    End Program d02psfe


d02pufe.f90

!   D02PUF Example Program Text
!   Mark 26 Release. NAG Copyright 2016.

    Module d02pufe_mod

!     D02PUF Example Program Module:
!            Parameters and User-defined Routines

!     .. Use Statements ..
      Use nag_library, Only: nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Accessibility Statements ..
      Private
      Public                           :: f
!     .. Parameters ..
      Integer, Parameter, Public       :: liwsav = 130, n = 4, nin = 5,        &
                                          nout = 6
      Integer, Parameter, Public       :: lrwsav = 350 + 32*n
    Contains
      Subroutine f(t,n,y,yp,iuser,ruser)

!       .. Scalar Arguments ..
        Real (Kind=nag_wp), Intent (In) :: t
        Integer, Intent (In)           :: n
!       .. Array Arguments ..
        Real (Kind=nag_wp), Intent (Inout) :: ruser(*)
        Real (Kind=nag_wp), Intent (In) :: y(n)
        Real (Kind=nag_wp), Intent (Out) :: yp(n)
        Integer, Intent (Inout)        :: iuser(*)
!       .. Local Scalars ..
        Real (Kind=nag_wp)             :: r
!       .. Intrinsic Procedures ..
        Intrinsic                      :: sqrt
!       .. Executable Statements ..
        r = sqrt(y(1)**2+y(2)**2)
        yp(1) = y(3)
        yp(2) = y(4)
        yp(3) = -y(1)/r**3
        yp(4) = -y(2)/r**3
        Return
      End Subroutine f
    End Module d02pufe_mod

    Program d02pufe

!     D02PUF Example Main Program

!     .. Use Statements ..
      Use nag_library, Only: d02pef, d02pqf, d02ptf, d02puf, nag_wp
      Use d02pufe_mod, Only: f, liwsav, lrwsav, n, nin, nout
!     .. Implicit None Statement ..
      Implicit None
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: errmax, hnext, hstart, tend, terrmx, &
                                          tgot, tol, tstart, twant, waste
      Integer                          :: fevals, ifail, method, stepcost,     &
                                          stepsok
!     .. Local Arrays ..
      Real (Kind=nag_wp)               :: rmserr(n), ruser(1), thresh(n),      &
                                          ygot(n), yinit(n), ymax(n), ypgot(n)
      Real (Kind=nag_wp), Allocatable  :: rwsav(:)
      Integer                          :: iuser(1)
      Integer, Allocatable             :: iwsav(:)
!     .. Executable Statements ..
      Write (nout,*) 'D02PUF Example Program Results'

      Allocate (rwsav(lrwsav),iwsav(liwsav))

!     Set initial conditions and input for D02PQF

!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) method
      Read (nin,*) tstart, tend
      Read (nin,*) yinit(1:n)
      Read (nin,*) hstart, tol
      Read (nin,*) thresh(1:n)

!     ifail: behaviour on error exit
!             =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
      ifail = 0
      Call d02pqf(n,tstart,tend,yinit,tol,thresh,method,hstart,iwsav,rwsav,    &
        ifail)

      Write (nout,99999) tol
      Write (nout,99998)
      Write (nout,99997) tstart, yinit(1:n)

      twant = tend

integ: Do
        ifail = -1
        Call d02pef(f,n,twant,tgot,ygot,ypgot,ymax,iuser,ruser,iwsav,rwsav,    &
          ifail)

        If (ifail<2 .Or. ifail>4) Then
          Exit integ
        End If

      End Do integ

      If (ifail==0) Then

!       Print solution.
        Write (nout,99997) tgot, ygot(1:n)

!       Compute and print error estimates.
        ifail = 0
        Call d02puf(n,rmserr,errmax,terrmx,iwsav,rwsav,ifail)

        Write (nout,99996) rmserr(1:n)
        Write (nout,99995) errmax, terrmx

        ifail = 0
        Call d02ptf(fevals,stepcost,waste,stepsok,hnext,iwsav,rwsav,ifail)

        Write (nout,99994) fevals
      End If

99999 Format (/,' Calculation with TOL = ',E8.1)
99998 Format (/,'    t         y1         y2         y3         y4',/)
99997 Format (1X,F6.3,4(3X,F8.4))
99996 Format (/,' Componentwise error assessment',/,9X,4(2X,E9.2))
99995 Format (/,' Worst global error observed was ',E9.2,                      &
        ' - it occurred at T = ',F6.3)
99994 Format (/,' Cost of the integration in evaluations of F is',I6)
    End Program d02pufe


d02qffe.f90

!   D02QFF Example Program Text
!   Mark 26 Release. NAG Copyright 2016.

    Module d02qffe_mod

!     D02QFF Example Program Module:
!            Parameters and User-defined Routines

!     .. Use Statements ..
      Use nag_library, Only: nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Accessibility Statements ..
      Private
      Public                           :: fcn, g
!     .. Parameters ..
      Integer, Parameter, Public       :: neqf = 2, neqg = 2, nin = 5,         &
                                          nout = 6
      Integer, Parameter, Public       :: latol = neqf
      Integer, Parameter, Public       :: liwork = 21 + 4*neqg
      Integer, Parameter, Public       :: lrtol = neqf
      Integer, Parameter, Public       :: lrwork = 23 + 23*neqf + 14*neqg
    Contains
      Subroutine fcn(neqf,x,y,f)

!       .. Scalar Arguments ..
        Real (Kind=nag_wp), Intent (In) :: x
        Integer, Intent (In)           :: neqf
!       .. Array Arguments ..
        Real (Kind=nag_wp), Intent (Out) :: f(neqf)
        Real (Kind=nag_wp), Intent (In) :: y(neqf)
!       .. Executable Statements ..
        f(1) = y(2)
        f(2) = -y(1)
        Return
      End Subroutine fcn

      Function g(neqf,x,y,yp,k)

!       .. Function Return Value ..
        Real (Kind=nag_wp)             :: g
!       .. Scalar Arguments ..
        Real (Kind=nag_wp), Intent (In) :: x
        Integer, Intent (In)           :: k, neqf
!       .. Array Arguments ..
        Real (Kind=nag_wp), Intent (In) :: y(neqf), yp(neqf)
!       .. Executable Statements ..
        If (k==1) Then
          g = yp(1)
        Else
          g = y(1)
        End If
        Return
      End Function g
    End Module d02qffe_mod

    Program d02qffe

!     D02QFF Example Main Program

!     .. Use Statements ..
      Use nag_library, Only: d02qff, d02qwf, d02qxf, d02qyf, nag_wp
      Use d02qffe_mod, Only: fcn, g, latol, liwork, lrtol, lrwork, neqf, neqg, &
                             nin, nout
!     .. Implicit None Statement ..
      Implicit None
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: hlast, hmax, hnext, t, tcrit, tcurr, &
                                          tolfac, tout, tstart
      Integer                          :: badcmp, i, ifail, index, maxstp,     &
                                          nfail, nsucc, odlast, odnext, type
      Logical                          :: alterg, crit, onestp, root, sophst,  &
                                          vectol
      Character (1)                    :: statef
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: atol(:), resids(:), rtol(:),         &
                                          rwork(:), y(:), yp(:)
      Integer, Allocatable             :: events(:), iwork(:)
!     .. Executable Statements ..
      Write (nout,*) 'D02QFF Example Program Results'
!     Skip heading in data file
      Read (nin,*)
      Allocate (atol(latol),resids(neqg),rtol(lrtol),rwork(lrwork),y(neqf),    &
        yp(neqf),events(neqg),iwork(liwork))
      Read (nin,*) hmax, tstart, tcrit
      Read (nin,*) statef
      Read (nin,*) vectol, onestp, crit, sophst
      Read (nin,*) maxstp
      Read (nin,*) rtol(1:neqf)
      Read (nin,*) atol(1:neqf)

!     Initialize
      ifail = 0
      Call d02qwf(statef,neqf,vectol,atol,latol,rtol,lrtol,onestp,crit,tcrit,  &
        hmax,maxstp,neqg,alterg,sophst,rwork,lrwork,iwork,liwork,ifail)

      t = tstart
      tout = tcrit
      Read (nin,*) y(1:neqf)

!      Cycle through roots and print info when encountered.
findr: Do
        ifail = -1
        Call d02qff(fcn,neqf,t,y,tout,g,neqg,root,rwork,lrwork,iwork,liwork,   &
          ifail)

        If (ifail/=0) Then
          Exit findr
        End If

        ifail = 0
        Call d02qxf(neqf,yp,tcurr,hlast,hnext,odlast,odnext,nsucc,nfail,       &
          tolfac,badcmp,rwork,lrwork,iwork,liwork,ifail)

        If (.Not. root) Then
          Exit findr
        End If

        ifail = 0
        Call d02qyf(neqg,index,type,events,resids,rwork,lrwork,iwork,liwork,   &
          ifail)

        Write (nout,99999) t
        Write (nout,99998) index, type, resids(index)
        Write (nout,99997) y(1), yp(1)

        Do i = 1, neqg
          If (i/=index) Then
            If (events(i)/=0) Then
              Write (nout,99996) i, events(i), resids(i)
            End If
          End If
        End Do

        If (tcurr>=tout) Then
          Exit findr
        End If

      End Do findr

99999 Format (/,1X,'Root at ',1P,E13.5)
99998 Format (1X,'for event equation ',I2,' with type',I3,' and residual ',1P, &
        E13.5)
99997 Format (1X,' Y(1) = ',1P,E13.5,'   Y''(1) = ',1P,E13.5)
99996 Format (1X,'and also for event equation ',I2,' with type',I3,            &
        ' and residual ',1P,E13.5)
    End Program d02qffe


d02qgfe.f90

    Program d02qgfe

!     D02QGF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: d02qgf, d02qwf, nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Real (Kind=nag_wp), Parameter    :: alpha = -0.032_nag_wp
      Real (Kind=nag_wp), Parameter    :: beta = -0.02_nag_wp
      Integer, Parameter               :: neqf = 3, neqg = 1, nin = 5,         &
                                          nout = 6
      Integer, Parameter               :: liwork = 21 + 4*neqg
      Integer, Parameter               :: lrwork = 23 + 23*neqf + 14*neqg
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: grvcm, hmax, t, tcrit, tinc, tout,   &
                                          trvcm, tstart
      Integer                          :: i, ifail, irevcm, j, kgrvcm, latol,  &
                                          lrtol, maxstp, yprvcm, yrvcm
      Logical                          :: alterg, crit, onestp, root, sophst,  &
                                          vectol
      Character (1)                    :: statef
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: atol(:), rtol(:), rwork(:), y(:)
      Integer, Allocatable             :: iwork(:)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: cos, tan
!     .. Executable Statements ..
      Write (nout,*) 'D02QGF Example Program Results'
!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) latol, lrtol

      Allocate (atol(latol),rtol(lrtol),rwork(lrwork),y(neqf),iwork(liwork))

      Read (nin,*) hmax, tstart, tcrit, tinc
      Read (nin,*) statef
      Read (nin,*) vectol, onestp, crit, sophst
      Read (nin,*) maxstp
      Read (nin,*) rtol(1:lrtol), atol(1:latol)
      Read (nin,*) y(1:neqf)

      t = tstart

!     ifail: behaviour on error exit
!             =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
      ifail = 0
      Call d02qwf(statef,neqf,vectol,atol,latol,rtol,lrtol,onestp,crit,tcrit,  &
        hmax,maxstp,neqg,alterg,sophst,rwork,lrwork,iwork,liwork,ifail)

      Write (nout,*)
      Write (nout,*) '  T         Y(1)     Y(2)     Y(3)'
      Write (nout,99999) t, (y(i),i=1,neqf)
      j = 1
      tout = tinc
      irevcm = 0

revcm: Do
        ifail = -1
        Call d02qgf(neqf,t,y,tout,neqg,root,irevcm,trvcm,yrvcm,yprvcm,grvcm,   &
          kgrvcm,rwork,lrwork,iwork,liwork,ifail)

        Select Case (irevcm)
        Case (0)
          If (ifail==0) Then
!           Print solution at current t
            Write (nout,99999) t, (y(i),i=1,neqf)
            If (t==tout .And. j<5) Then
!             Increment tout and cycle to find solution at this new time.
              j = j + 1
              tout = tout + tinc
              Cycle revcm
            End If
          End If
          Exit revcm
        Case (1:7)
          If (yrvcm==0) Then
            rwork(yprvcm) = tan(y(3))
            rwork(yprvcm+1) = alpha*tan(y(3))/y(2) + beta*y(2)/cos(y(3))
            rwork(yprvcm+2) = alpha/y(2)**2
          Else
            rwork(yprvcm) = tan(rwork(yrvcm+2))
            rwork(yprvcm+1) = alpha*tan(rwork(yrvcm+2))/rwork(yrvcm+1) +       &
              beta*rwork(yrvcm+1)/cos(rwork(yrvcm+2))
            rwork(yprvcm+2) = alpha/rwork(yrvcm+1)**2
          End If
        Case (9:)
          grvcm = y(1)
        End Select
      End Do revcm

99999 Format (1X,F7.4,2X,3(F7.4,2X))
    End Program d02qgfe


d02qzfe.f90

!   D02QZF Example Program Text
!   Mark 26 Release. NAG Copyright 2016.

    Module d02qzfe_mod

!     D02QZF Example Program Module:
!            Parameters and User-defined Routines

!     .. Use Statements ..
      Use nag_library, Only: nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Accessibility Statements ..
      Private
      Public                           :: fcn
!     .. Parameters ..
      Integer, Parameter, Public       :: neqf = 2, neqg = 0, nin = 5,         &
                                          nout = 6
      Integer, Parameter, Public       :: latol = neqf
      Integer, Parameter, Public       :: liwork = 21 + 4*neqg
      Integer, Parameter, Public       :: lrtol = neqf
      Integer, Parameter, Public       :: lrwork = 23 + 23*neqf + 14*neqg
    Contains
      Subroutine fcn(neqf,x,y,f)

!       .. Scalar Arguments ..
        Real (Kind=nag_wp), Intent (In) :: x
        Integer, Intent (In)           :: neqf
!       .. Array Arguments ..
        Real (Kind=nag_wp), Intent (Out) :: f(neqf)
        Real (Kind=nag_wp), Intent (In) :: y(neqf)
!       .. Executable Statements ..
        f(1) = y(2)
        f(2) = -y(1)
        Return
      End Subroutine fcn
    End Module d02qzfe_mod

    Program d02qzfe

!     D02QZF Example Main Program

!     .. Use Statements ..
      Use nag_library, Only: d02qff, d02qfz, d02qwf, d02qzf, nag_wp
      Use d02qzfe_mod, Only: fcn, latol, liwork, lrtol, lrwork, neqf, neqg,    &
                             nin, nout
!     .. Implicit None Statement ..
      Implicit None
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: hmax, t, tcrit, tinc, tout, tstart,  &
                                          twant
      Integer                          :: ifail, maxstp, nwant
      Logical                          :: alterg, crit, onestp, root, sophst,  &
                                          vectol
      Character (1)                    :: statef
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: atol(:), rtol(:), rwork(:), y(:),    &
                                          ypwant(:), ywant(:)
      Integer, Allocatable             :: iwork(:)
!     .. Executable Statements ..
      Write (nout,*) 'D02QZF Example Program Results'
!     Skip heading in data file
      Read (nin,*)
      Allocate (atol(latol),rtol(lrtol),rwork(lrwork),y(neqf),ypwant(neqf),    &
        ywant(neqf),iwork(liwork))

      Read (nin,*) hmax, tstart
      Read (nin,*) tcrit, tinc
      Read (nin,*) statef
      Read (nin,*) vectol, onestp, crit
      Read (nin,*) maxstp
      Read (nin,*) rtol(1:neqf)
      Read (nin,*) atol(1:neqf)
      Read (nin,*) y(1:neqf)
      tout = tcrit
      t = tstart
      twant = tstart + tinc
      nwant = neqf

!     Set up integration.
      ifail = 0
      Call d02qwf(statef,neqf,vectol,atol,latol,rtol,lrtol,onestp,crit,tcrit,  &
        hmax,maxstp,neqg,alterg,sophst,rwork,lrwork,iwork,liwork,ifail)

      Write (nout,*)
      Write (nout,*) '  T         Y(1)     Y(2)'
      Write (nout,99999) t, y(1), y(2)

integ: Do While (t<tout)
        ifail = -1
        Call d02qff(fcn,neqf,t,y,tout,d02qfz,neqg,root,rwork,lrwork,iwork,     &
          liwork,ifail)

        If (ifail/=0) Then
          Exit integ
        End If

!       Interpolate at wanted time values up to time = t.
        Do While (twant<=t)
          ifail = 0
          Call d02qzf(neqf,twant,nwant,ywant,ypwant,rwork,lrwork,iwork,liwork, &
            ifail)
          Write (nout,99999) twant, ywant(1), ywant(2)
          twant = twant + tinc
        End Do
      End Do integ

99999 Format (1X,F7.4,2X,2(F7.4,2X))
    End Program d02qzfe


d02rafe.f90

!   D02RAF Example Program Text
!   Mark 26 Release. NAG Copyright 2016.

    Module d02rafe_mod

!     D02RAF Example Program Module:
!            Parameters and User-defined Routines

!     .. Use Statements ..
      Use nag_library, Only: nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Accessibility Statements ..
      Private
      Public                           :: fcn, g, jaceps, jacgep, jacobf,      &
                                          jacobg
!     .. Parameters ..
      Real (Kind=nag_wp), Parameter    :: one = 1.0_nag_wp
      Real (Kind=nag_wp), Parameter    :: two = 2.0_nag_wp
      Real (Kind=nag_wp), Parameter    :: zero = 0.0_nag_wp
      Integer, Parameter, Public       :: iset = 1, n = 3, nin = 5, nout = 6
    Contains
      Subroutine fcn(x,eps,y,f,n)

!       .. Scalar Arguments ..
        Real (Kind=nag_wp), Intent (In) :: eps, x
        Integer, Intent (In)           :: n
!       .. Array Arguments ..
        Real (Kind=nag_wp), Intent (Out) :: f(n)
        Real (Kind=nag_wp), Intent (In) :: y(n)
!       .. Executable Statements ..
        f(1) = y(2)
        f(2) = y(3)
        f(3) = -y(1)*y(3) - two*(one-y(2)*y(2))*eps
        Return
      End Subroutine fcn

      Subroutine g(eps,ya,yb,bc,n)

!       .. Scalar Arguments ..
        Real (Kind=nag_wp), Intent (In) :: eps
        Integer, Intent (In)           :: n
!       .. Array Arguments ..
        Real (Kind=nag_wp), Intent (Out) :: bc(n)
        Real (Kind=nag_wp), Intent (In) :: ya(n), yb(n)
!       .. Executable Statements ..
        bc(1) = ya(1)
        bc(2) = ya(2)
        bc(3) = yb(2) - one
        Return
      End Subroutine g

      Subroutine jaceps(x,eps,y,f,n)

!       .. Scalar Arguments ..
        Real (Kind=nag_wp), Intent (In) :: eps, x
        Integer, Intent (In)           :: n
!       .. Array Arguments ..
        Real (Kind=nag_wp), Intent (Out) :: f(n)
        Real (Kind=nag_wp), Intent (In) :: y(n)
!       .. Executable Statements ..
        f(1:2) = zero
        f(3) = -two*(one-y(2)*y(2))
        Return
      End Subroutine jaceps

      Subroutine jacgep(eps,ya,yb,bcep,n)

!       .. Scalar Arguments ..
        Real (Kind=nag_wp), Intent (In) :: eps
        Integer, Intent (In)           :: n
!       .. Array Arguments ..
        Real (Kind=nag_wp), Intent (Out) :: bcep(n)
        Real (Kind=nag_wp), Intent (In) :: ya(n), yb(n)
!       .. Executable Statements ..
        bcep(1:n) = zero
        Return
      End Subroutine jacgep

      Subroutine jacobf(x,eps,y,f,n)

!       .. Scalar Arguments ..
        Real (Kind=nag_wp), Intent (In) :: eps, x
        Integer, Intent (In)           :: n
!       .. Array Arguments ..
        Real (Kind=nag_wp), Intent (Out) :: f(n,n)
        Real (Kind=nag_wp), Intent (In) :: y(n)
!       .. Executable Statements ..
        f(1:n,1:n) = zero
        f(1,2) = one
        f(2,3) = one
        f(3,1) = -y(3)
        f(3,2) = two*two*y(2)*eps
        f(3,3) = -y(1)
        Return
      End Subroutine jacobf

      Subroutine jacobg(eps,ya,yb,aj,bj,n)

!       .. Scalar Arguments ..
        Real (Kind=nag_wp), Intent (In) :: eps
        Integer, Intent (In)           :: n
!       .. Array Arguments ..
        Real (Kind=nag_wp), Intent (Out) :: aj(n,n), bj(n,n)
        Real (Kind=nag_wp), Intent (In) :: ya(n), yb(n)
!       .. Executable Statements ..
        aj(1:n,1:n) = zero
        bj(1:n,1:n) = zero
        aj(1,1) = one
        aj(2,2) = one
        bj(3,2) = one
        Return
      End Subroutine jacobg
    End Module d02rafe_mod

    Program d02rafe

!     D02RAF Example Main Program

!     .. Use Statements ..
      Use nag_library, Only: d02raf, nag_wp, x04abf
      Use d02rafe_mod, Only: fcn, g, iset, jaceps, jacgep, jacobf, jacobg, n,  &
                             nin, nout
!     .. Implicit None Statement ..
      Implicit None
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: deleps, tol
      Integer                          :: ifail, ijac, init, j, ldy, liwork,   &
                                          lwork, mnp, np, numbeg, nummix,      &
                                          outchn
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: abt(:), work(:), x(:), y(:,:)
      Integer, Allocatable             :: iwork(:)
!     .. Executable Statements ..
      Write (nout,*) 'D02RAF Example Program Results'
!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) mnp, np
      ldy = n
      liwork = mnp*(2*n+1) + n
      lwork = mnp*(3*n*n+6*n+2) + 4*n*n + 3*n
      Allocate (abt(n),work(lwork),x(mnp),y(ldy,mnp),iwork(liwork))

      outchn = nout
      Write (nout,*)
      Call x04abf(iset,outchn)
      Read (nin,*) tol, deleps
      Read (nin,*) init, ijac, numbeg, nummix
      Read (nin,*) x(1), x(np)

!     ifail: behaviour on error exit
!             =1 for quiet-soft exit
!     * Set IFAIL to 111 to obtain monitoring information *
      ifail = 1
      Call d02raf(n,mnp,np,numbeg,nummix,tol,init,x,y,ldy,abt,fcn,g,ijac,      &
        jacobf,jacobg,deleps,jaceps,jacgep,work,lwork,iwork,liwork,ifail)

      If (ifail==0 .Or. ifail==4) Then
        Write (nout,*) 'Calculation using analytic Jacobians'
        If (ifail==4) Then
          Write (nout,99996) 'On exit from D02RAF IFAIL = 4'
        End If
        Write (nout,*)
        Write (nout,99999) 'Solution on final mesh of ', np, ' points'
        Write (nout,*) '      X(I)        Y1(I)        Y2(I)        Y3(I)'
        Write (nout,99998)(x(j),y(1:n,j),j=1,np)
        Write (nout,*)
        Write (nout,*) 'Maximum estimated error by components'
        Write (nout,99997) abt(1:n)
      Else
        Write (nout,99996) ' ** D02RAF returned with IFAIL = ', ifail
      End If

99999 Format (1X,A,I2,A)
99998 Format (1X,F10.6,3F13.4)
99997 Format (11X,1P,3E13.2)
99996 Format (1X,A,I5)
    End Program d02rafe


d02safe.f90

!   D02SAF Example Program Text
!   Mark 26 Release. NAG Copyright 2016.

    Module d02safe_mod

!     D02SAF Example Program Module:
!            Parameters and User-defined Routines

!     .. Use Statements ..
      Use nag_library, Only: nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Accessibility Statements ..
      Private
      Public                           :: bc, constr, eqn, fcn, prsol, range
!     .. Parameters ..
      Real (Kind=nag_wp), Parameter    :: alpha = 0.032_nag_wp
      Real (Kind=nag_wp), Parameter    :: beta = 0.02_nag_wp
      Real (Kind=nag_wp), Parameter    :: xend = 5.0_nag_wp
      Integer, Parameter, Public       :: iset = 1, m = 4, n = 3, nin = 5,     &
                                          nout = 6
    Contains
      Subroutine eqn(e,q,p,m)

!       .. Scalar Arguments ..
        Integer, Intent (In)           :: m, q
!       .. Array Arguments ..
        Real (Kind=nag_wp), Intent (Out) :: e(q)
        Real (Kind=nag_wp), Intent (In) :: p(m)
!       .. Executable Statements ..
        e(1) = 0.02_nag_wp - p(4) - 1.0E-5_nag_wp*p(3)
        Return
      End Subroutine eqn
      Subroutine fcn(x,y,f,n,p,m,i)

!       .. Scalar Arguments ..
        Real (Kind=nag_wp), Intent (In) :: x
        Integer, Intent (In)           :: i, m, n
!       .. Array Arguments ..
        Real (Kind=nag_wp), Intent (Out) :: f(n)
        Real (Kind=nag_wp), Intent (In) :: p(m), y(n)
!       .. Intrinsic Procedures ..
        Intrinsic                      :: cos, tan
!       .. Executable Statements ..
        f(1) = tan(y(3))
        If (i==1) Then
          f(2) = -alpha*tan(y(3))/y(2) - beta*y(2)/cos(y(3))
          f(3) = -alpha/y(2)**2
        Else
          f(2) = -p(2)*tan(y(3))/y(2) - p(4)*y(2)/cos(y(3))
          f(3) = -p(2)/y(2)**2
        End If
        Return
      End Subroutine fcn
      Subroutine bc(g1,g2,p,m,n)

!       .. Scalar Arguments ..
        Integer, Intent (In)           :: m, n
!       .. Array Arguments ..
        Real (Kind=nag_wp), Intent (Out) :: g1(n), g2(n)
        Real (Kind=nag_wp), Intent (In) :: p(m)
!       .. Executable Statements ..
        g1(1) = 0.0_nag_wp
        g1(2) = 0.5_nag_wp
        g1(3) = p(1)
        g2(1) = 0.0_nag_wp
        g2(2) = 0.45_nag_wp
        g2(3) = -1.2_nag_wp
        Return
      End Subroutine bc
      Subroutine range(x,npoint,p,m)

!       .. Scalar Arguments ..
        Integer, Intent (In)           :: m, npoint
!       .. Array Arguments ..
        Real (Kind=nag_wp), Intent (In) :: p(m)
        Real (Kind=nag_wp), Intent (Out) :: x(npoint)
!       .. Executable Statements ..
        x(1) = 0.0_nag_wp
        x(2) = p(3)
        x(3) = xend
        Return
      End Subroutine range
      Subroutine prsol(z,y,n)

!       .. Scalar Arguments ..
        Real (Kind=nag_wp), Intent (Inout) :: z
        Integer, Intent (In)           :: n
!       .. Array Arguments ..
        Real (Kind=nag_wp), Intent (In) :: y(n)
!       .. Local Scalars ..
        Integer                        :: i
!       .. Intrinsic Procedures ..
        Intrinsic                      :: abs
!       .. Executable Statements ..
        If (z==0.0E0_nag_wp) Then
          Write (nout,*)
          Write (nout,*) '      Z       Y(1)      Y(2)      Y(3)'
        End If
        Write (nout,99999) z, (y(i),i=1,n)
        z = z + 0.5_nag_wp
        If (abs(z-xend)<0.25_nag_wp) Then
          z = xend
        End If
        Return

99999   Format (1X,F9.3,3F10.4)
      End Subroutine prsol
      Function constr(p,m)

!       .. Function Return Value ..
        Logical                        :: constr
!       .. Scalar Arguments ..
        Integer, Intent (In)           :: m
!       .. Array Arguments ..
        Real (Kind=nag_wp), Intent (In) :: p(m)
!       .. Intrinsic Procedures ..
        Intrinsic                      :: any
!       .. Executable Statements ..
        If (any(p(1:m)<0.0_nag_wp) .Or. p(3)>5.0_nag_wp) Then
          constr = .False.
        Else
          constr = .True.
        End If
        Return
      End Function constr
    End Module d02safe_mod
    Program d02safe

!     D02SAF Example Main Program

!     .. Use Statements ..
      Use nag_library, Only: d02saf, d02sas, nag_wp, x04abf
      Use d02safe_mod, Only: bc, constr, eqn, fcn, iset, m, n, nin, nout,      &
                             prsol, range
!     .. Implicit None Statement ..
      Implicit None
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: ymax
      Integer                          :: i, icount, ifail, ldswp, ldw, n1,    &
                                          npoint, outchn, sdw
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: dp(:), e(:), p(:), pe(:), pf(:),     &
                                          swp(:,:), w(:,:)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: max
!     .. Executable Statements ..
      Write (nout,*) 'D02SAF Example Program Results'
!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) npoint
      n1 = n
      sdw = 3*m + 23
      ldswp = npoint
      ldw = max(m,n)
      Allocate (dp(m),e(n),p(m),pe(m),pf(m),swp(ldswp,6),w(ldw,sdw))

      outchn = nout
      Read (nin,*) icount
      Read (nin,*) ymax
      Read (nin,*) pe(1:m)
      Read (nin,*) pf(1:m)
      Read (nin,*) dp(1:m)
      Read (nin,*) e(1:n)
      Call x04abf(iset,outchn)
      swp(1:npoint-1,1:3) = 0.0_nag_wp
      Read (nin,*) p(1:m)

!     * To obtain monitoring information, replace the name d02sas by d02hbx
!     in the next statement and USE nag_library : d02hbx

!     ifail: behaviour on error exit
!             =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
      ifail = 1
      Call d02saf(p,m,n,n1,pe,pf,e,dp,npoint,swp,ldswp,icount,range,bc,fcn,    &
        eqn,constr,ymax,d02sas,prsol,w,ldw,sdw,ifail)

      If (ifail/=0) Then
        Write (nout,99999) ifail
      End If
      If (ifail>=4 .And. ifail<=12) Then
        Write (nout,99998) 'SWP(NPOINT,1) = ', swp(npoint,1)
        If (ifail<=6) Then
          Write (nout,99998) 'SWP(1,5) = ', swp(1,5)
          Write (nout,*) '  i     W(i,1) '
          Write (nout,99997)(i,w(i,1),i=1,n)
        End If
      End If

99999 Format (1X,/,1X,' ** D02SAF returned with IFAIL = ',I5)
99998 Format (1X,A,F10.4)
99997 Format (1X,I4,1X,E10.3)
    End Program d02safe


d02tgfe.f90

!   D02TGF Example Program Text
!   Mark 26 Release. NAG Copyright 2016.

    Module d02tgfe_mod

!     D02TGF Example Program Module:
!            Parameters and User-defined Routines

!     .. Use Statements ..
      Use nag_library, Only: nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Accessibility Statements ..
      Private
      Public                           :: bdyc, coeff
!     .. Parameters ..
      Real (Kind=nag_wp), Parameter, Public :: coeff_tol = 1.0E-5_nag_wp
      Real (Kind=nag_wp), Parameter    :: one = 1.0_nag_wp
      Real (Kind=nag_wp), Parameter    :: two = 2.0_nag_wp
      Integer, Parameter, Public       :: n = 2, nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp), Public, Save :: x0, x1
      Integer, Public, Save            :: k1
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable, Public, Save :: b(:,:)
      Integer, Public, Save            :: l(n) = (/1,2/)
      Integer, Public, Save            :: m(n) = (/1,2/)
    Contains
      Subroutine coeff(x,i,a,ia,ia1,rhs)

!       .. Use Statements ..
        Use nag_library, Only: e02akf
!       .. Scalar Arguments ..
        Real (Kind=nag_wp), Intent (Inout) :: rhs
        Real (Kind=nag_wp), Intent (In) :: x
        Integer, Intent (In)           :: i, ia, ia1
!       .. Array Arguments ..
        Real (Kind=nag_wp), Intent (Inout) :: a(ia,ia1)
!       .. Local Scalars ..
        Real (Kind=nag_wp)             :: z1, z2
        Integer                        :: ifail
!       .. Executable Statements ..
        If (i<=1) Then

!         Evaluate z1, z2 at x using previous coeffs b.
          ifail = 0
          Call e02akf(k1,x0,x1,b(1,1),1,k1,x,z1,ifail)
          Call e02akf(k1,x0,x1,b(1,2),1,k1,x,z2,ifail)

          a(1,1) = z2*z2 - one
          a(1,2) = two
          a(2,1) = two*z1*z2 + one
          rhs = two*z1*z2*z2
        Else
          a(1,2) = -one
          a(2,3) = two
        End If
        Return
      End Subroutine coeff
      Subroutine bdyc(x,i,j,a,ia,ia1,rhs)

!       .. Scalar Arguments ..
        Real (Kind=nag_wp), Intent (Inout) :: rhs
        Real (Kind=nag_wp), Intent (Out) :: x
        Integer, Intent (In)           :: i, ia, ia1, j
!       .. Array Arguments ..
        Real (Kind=nag_wp), Intent (Inout) :: a(ia,ia1)
!       .. Executable Statements ..
        x = -one
        a(i,j) = one
        If (i==2 .And. j==1) Then
          rhs = 3.0_nag_wp
        End If
        Return
      End Subroutine bdyc
    End Module d02tgfe_mod
    Program d02tgfe

!     D02TGF Example Main Program

!     .. Use Statements ..
      Use nag_library, Only: d02tgf, e02akf, nag_wp
      Use d02tgfe_mod, Only: b, bdyc, coeff, coeff_tol, k1, l, m, n, nin,      &
                             nout, x0, x1
!     .. Implicit None Statement ..
      Implicit None
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: emax, x, xinc
      Integer                          :: i, ia1, ifail, iter, j, k, kp, ldc,  &
                                          liw, lsum, lw, mimax
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: c(:,:), w(:), y(:)
      Integer, Allocatable             :: iw(:)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: abs, max, real, sum
!     .. Executable Statements ..
      Write (nout,*) 'D02TGF Example Program Results'
!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) mimax, kp
      Read (nin,*) x0, x1

      lsum = sum(l(1:n))
      k1 = mimax + 1
      ldc = k1
      liw = n*k1
      lw = 2*(n*kp+lsum)*(n*k1+1) + 7*n*k1
      Allocate (b(k1,n),c(ldc,n),w(lw),y(n),iw(liw))

!     Initialize coefficients b(:,:) such that z1 = 0 and z2 = 3.
      b(1:k1,1:n) = 0.0_nag_wp
      b(1,2) = 6.0_nag_wp

!     Iterate until coefficients of linearized systems converge.
      iter = 0
      emax = 1.0_nag_wp
iters: Do While (emax>=coeff_tol)
        iter = iter + 1
        Write (nout,*)
        Write (nout,99999) ' Iteration', iter, ' Chebyshev coefficients are'

!       ifail: behaviour on error exit
!              =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
        ifail = 0
        Call d02tgf(n,m,l,x0,x1,k1,kp,c,ldc,coeff,bdyc,w,lw,iw,liw,ifail)

        Write (nout,99998)(c(1:k1,j),j=1,n)
        emax = 0.0_nag_wp
        Do j = 1, n
          Do i = 1, k1
            emax = max(emax,abs(c(i,j)-b(i,j)))
          End Do
        End Do
        b(1:k1,1:n) = c(1:k1,1:n)
      End Do iters

      Deallocate (b)

!     Print solution on uniform mesh.
      k = 9
      ia1 = 1
      Write (nout,*)
      Write (nout,99999) 'Solution evaluated at', k, '  equally spaced points'
      Write (nout,*)
      Write (nout,99997) '      X ', (j,j=1,n)
      xinc = (x1-x0)/real(k-1,kind=nag_wp)
      x = x0
      Do i = 1, k
        Do j = 1, n
          ifail = 0
          Call e02akf(k1,x0,x1,c(1,j),ia1,k1,x,y(j),ifail)
        End Do
        Write (nout,99996) x, (y(j),j=1,n)
        x = x + xinc
      End Do

99999 Format (1X,A,I3,A)
99998 Format (1X,9F8.4)
99997 Format (1X,A,2('      Y(',I1,')'))
99996 Format (1X,3F10.4)
    End Program d02tgfe


d02tkfe.f90

!   D02TKF Example Program Text
!   Mark 26 Release. NAG Copyright 2016.

    Module d02tkfe_mod

!     D02TKF Example Program Module:
!            Parameters and User-defined Routines

!     .. Use Statements ..
      Use nag_library, Only: nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Accessibility Statements ..
      Private
      Public                           :: ffun, fjac, gafun, gajac, gbfun,     &
                                          gbjac, guess
!     .. Parameters ..
      Integer, Parameter, Public       :: mmax = 3, neq = 3, nin = 5,          &
                                          nlbc = 3, nout = 6, nrbc = 3
!     .. Local Scalars ..
      Real (Kind=nag_wp), Public, Save :: omega
      Real (Kind=nag_wp), Public, Save :: one = 1.0_nag_wp
      Real (Kind=nag_wp), Public, Save :: sqrofr
!     .. Local Arrays ..
      Integer, Public, Save            :: m(neq) = (/1,3,2/)
    Contains
      Subroutine ffun(x,y,neq,m,f)

!       .. Scalar Arguments ..
        Real (Kind=nag_wp), Intent (In) :: x
        Integer, Intent (In)           :: neq
!       .. Array Arguments ..
        Real (Kind=nag_wp), Intent (Out) :: f(neq)
        Real (Kind=nag_wp), Intent (In) :: y(neq,0:*)
        Integer, Intent (In)           :: m(neq)
!       .. Executable Statements ..
        f(1) = y(2,0)
        f(2) = -(y(1,0)*y(2,2)+y(3,0)*y(3,1))*sqrofr
        f(3) = (y(2,0)*y(3,0)-y(1,0)*y(3,1))*sqrofr
        Return
      End Subroutine ffun
      Subroutine fjac(x,y,neq,m,dfdy)

!       .. Scalar Arguments ..
        Real (Kind=nag_wp), Intent (In) :: x
        Integer, Intent (In)           :: neq
!       .. Array Arguments ..
        Real (Kind=nag_wp), Intent (Inout) :: dfdy(neq,neq,0:*)
        Real (Kind=nag_wp), Intent (In) :: y(neq,0:*)
        Integer, Intent (In)           :: m(neq)
!       .. Executable Statements ..
        dfdy(1,2,0) = one
        dfdy(2,1,0) = -y(2,2)*sqrofr
        dfdy(2,2,2) = -y(1,0)*sqrofr
        dfdy(2,3,0) = -y(3,1)*sqrofr
        dfdy(2,3,1) = -y(3,0)*sqrofr
        dfdy(3,1,0) = -y(3,1)*sqrofr
        dfdy(3,2,0) = y(3,0)*sqrofr
        dfdy(3,3,0) = y(2,0)*sqrofr
        dfdy(3,3,1) = -y(1,0)*sqrofr
        Return
      End Subroutine fjac
      Subroutine gafun(ya,neq,m,nlbc,ga)

!       .. Scalar Arguments ..
        Integer, Intent (In)           :: neq, nlbc
!       .. Array Arguments ..
        Real (Kind=nag_wp), Intent (Out) :: ga(nlbc)
        Real (Kind=nag_wp), Intent (In) :: ya(neq,0:*)
        Integer, Intent (In)           :: m(neq)
!       .. Executable Statements ..
        ga(1) = ya(1,0)
        ga(2) = ya(2,0)
        ga(3) = ya(3,0) - omega
        Return
      End Subroutine gafun
      Subroutine gbfun(yb,neq,m,nrbc,gb)

!       .. Scalar Arguments ..
        Integer, Intent (In)           :: neq, nrbc
!       .. Array Arguments ..
        Real (Kind=nag_wp), Intent (Out) :: gb(nrbc)
        Real (Kind=nag_wp), Intent (In) :: yb(neq,0:*)
        Integer, Intent (In)           :: m(neq)
!       .. Executable Statements ..
        gb(1) = yb(1,0)
        gb(2) = yb(2,0)
        gb(3) = yb(3,0) + omega
        Return
      End Subroutine gbfun
      Subroutine gajac(ya,neq,m,nlbc,dgady)

!       .. Scalar Arguments ..
        Integer, Intent (In)           :: neq, nlbc
!       .. Array Arguments ..
        Real (Kind=nag_wp), Intent (Inout) :: dgady(nlbc,neq,0:*)
        Real (Kind=nag_wp), Intent (In) :: ya(neq,0:*)
        Integer, Intent (In)           :: m(neq)
!       .. Executable Statements ..
        dgady(1,1,0) = one
        dgady(2,2,0) = one
        dgady(3,3,0) = one
        Return
      End Subroutine gajac
      Subroutine gbjac(yb,neq,m,nrbc,dgbdy)

!       .. Scalar Arguments ..
        Integer, Intent (In)           :: neq, nrbc
!       .. Array Arguments ..
        Real (Kind=nag_wp), Intent (Inout) :: dgbdy(nrbc,neq,0:*)
        Real (Kind=nag_wp), Intent (In) :: yb(neq,0:*)
        Integer, Intent (In)           :: m(neq)
!       .. Executable Statements ..
        dgbdy(1,1,0) = one
        dgbdy(2,2,0) = one
        dgbdy(3,3,0) = one
        Return
      End Subroutine gbjac
      Subroutine guess(x,neq,m,y,dym)

!       .. Scalar Arguments ..
        Real (Kind=nag_wp), Intent (In) :: x
        Integer, Intent (In)           :: neq
!       .. Array Arguments ..
        Real (Kind=nag_wp), Intent (Out) :: dym(neq)
        Real (Kind=nag_wp), Intent (Inout) :: y(neq,0:*)
        Integer, Intent (In)           :: m(neq)
!       .. Executable Statements ..
        y(1,0) = -(x-0.5_nag_wp)*(x*(x-one))**2
        y(2,0) = -x*(x-one)*(5._nag_wp*x*(x-one)+one)
        y(2,1) = -(2._nag_wp*x-one)*(10._nag_wp*x*(x-one)+one)
        y(2,2) = -12.0_nag_wp*(5._nag_wp*x*(x-one)+x)
        y(3,0) = -8.0_nag_wp*omega*(x-0.5_nag_wp)**3
        y(3,1) = -24.0_nag_wp*omega*(x-0.5_nag_wp)**2
        dym(1) = y(2,0)
        dym(2) = -120.0_nag_wp*(x-0.5_nag_wp)
        dym(3) = -56.0_nag_wp*omega*(x-0.5_nag_wp)
        Return
      End Subroutine guess
    End Module d02tkfe_mod
    Program d02tkfe

!     D02TKF Example Main Program

!     .. Use Statements ..
      Use nag_library, Only: d02tkf, d02tvf, d02txf, d02tyf, d02tzf, nag_wp
      Use d02tkfe_mod, Only: ffun, fjac, gafun, gajac, gbfun, gbjac, guess, m, &
                             mmax, neq, nin, nlbc, nout, nrbc, omega, one,     &
                             sqrofr
!     .. Implicit None Statement ..
      Implicit None
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: dx, ermx, r
      Integer                          :: i, iermx, ifail, ijermx, j, licomm,  &
                                          lrcomm, mxmesh, ncol, ncont, nmesh
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: mesh(:), tol(:), work(:), y(:,:)
      Integer, Allocatable             :: icomm(:), ipmesh(:)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: real, sqrt
!     .. Executable Statements ..
      Write (nout,*) 'D02TKF Example Program Results'
      Write (nout,*)
!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) ncol, nmesh, mxmesh

      licomm = 23 + neq + mxmesh
      lrcomm = mxmesh*(109*neq**2+78*neq+7)
      Allocate (mesh(mxmesh),tol(neq),work(lrcomm),y(neq,0:mmax-1),            &
        ipmesh(mxmesh),icomm(licomm))

      Read (nin,*) omega
      Read (nin,*) tol(1:neq)

      dx = one/real(nmesh-1,kind=nag_wp)
      mesh(1) = 0.0_nag_wp
      Do i = 2, nmesh - 1
        mesh(i) = mesh(i-1) + dx
      End Do
      mesh(nmesh) = one

      ipmesh(1) = 1
      ipmesh(2:nmesh-1) = 2
      ipmesh(nmesh) = 1

!     Initial integrator for given problem.
      ifail = 0
      Call d02tvf(neq,m,nlbc,nrbc,ncol,tol,mxmesh,nmesh,mesh,ipmesh,work,      &
        lrcomm,icomm,licomm,ifail)

!     Number of continuation steps (last r=100**ncont, sqrofr=10**ncont)
      Read (nin,*) ncont
!     Initialize problem continuation parameter.
      Read (nin,*) r
      sqrofr = sqrt(r)

contn: Do j = 1, ncont
        Write (nout,99999) tol(1), r

!       Solve problem.
        ifail = -1
        Call d02tkf(ffun,fjac,gafun,gbfun,gajac,gbjac,guess,work,icomm,ifail)

!       Extract mesh
        ifail = -1
        Call d02tzf(mxmesh,nmesh,mesh,ipmesh,ermx,iermx,ijermx,work,icomm,     &
          ifail)
        If (ifail==1) Then
          Exit contn
        End If

!       Print mesh and error statistics.
        Write (nout,99998) nmesh, ermx, iermx, ijermx
        Write (nout,99997)(i,ipmesh(i),mesh(i),i=1,nmesh)
!       Print solution components on mesh.
        Write (nout,99996)
        Do i = 1, nmesh
          ifail = 0
          Call d02tyf(mesh(i),y,neq,mmax,work,icomm,ifail)
          Write (nout,99995) mesh(i), y(1:neq,0)
        End Do

        If (j==ncont) Then
          Exit contn
        End If

!       Modify continuation parameter.
        r = 100.0_nag_wp*r
        sqrofr = sqrt(r)
!       Select mesh for continuation and call continuation primer routine.
        ipmesh(2:nmesh-1) = 2
        ifail = 0
        Call d02txf(mxmesh,nmesh,mesh,ipmesh,work,icomm,ifail)

      End Do contn

99999 Format (/,' Tolerance = ',1P,E8.1,'  R = ',E10.3)
99998 Format (/,' Used a mesh of ',I4,' points',/,' Maximum error = ',1P,      &
        E10.2,'  in interval ',I4,' for component ',I4,/)
99997 Format (/,' Mesh points:',/,4(I4,'(',I1,')',1P,E10.3))
99996 Format (/,'      x        f        f''       g')
99995 Format (' ',F8.3,1X,3F9.4)
    End Program d02tkfe


d02tlfe.f90

!   D02TLF Example Program Text
!   Mark 26 Release. NAG Copyright 2016.

    Module d02tlfe_mod

!     D02TLF Example Program Module:
!            Parameters and User-defined Routines

!     .. Use Statements ..
      Use nag_library, Only: nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Accessibility Statements ..
      Private
      Public                           :: ffun, fjac, gafun, gajac, gbfun,     &
                                          gbjac, guess
!     .. Parameters ..
      Integer, Parameter, Public       :: mmax = 3, neq = 3, nin = 5,          &
                                          nlbc = 3, nout = 6, nrbc = 3
!     .. Local Scalars ..
      Real (Kind=nag_wp), Public, Save :: omega
      Real (Kind=nag_wp), Public, Save :: one = 1.0_nag_wp
      Real (Kind=nag_wp), Public, Save :: sqrofr
!     .. Local Arrays ..
      Integer, Public, Save            :: m(neq) = (/1,3,2/)
    Contains
      Subroutine ffun(x,y,neq,m,f,iuser,ruser)

!       .. Scalar Arguments ..
        Real (Kind=nag_wp), Intent (In) :: x
        Integer, Intent (In)           :: neq
!       .. Array Arguments ..
        Real (Kind=nag_wp), Intent (Out) :: f(neq)
        Real (Kind=nag_wp), Intent (Inout) :: ruser(*)
        Real (Kind=nag_wp), Intent (In) :: y(neq,0:*)
        Integer, Intent (Inout)        :: iuser(*)
        Integer, Intent (In)           :: m(neq)
!       .. Executable Statements ..
        f(1) = y(2,0)
        f(2) = -(y(1,0)*y(2,2)+y(3,0)*y(3,1))*sqrofr
        f(3) = (y(2,0)*y(3,0)-y(1,0)*y(3,1))*sqrofr
        Return
      End Subroutine ffun
      Subroutine fjac(x,y,neq,m,dfdy,iuser,ruser)

!       .. Scalar Arguments ..
        Real (Kind=nag_wp), Intent (In) :: x
        Integer, Intent (In)           :: neq
!       .. Array Arguments ..
        Real (Kind=nag_wp), Intent (Inout) :: dfdy(neq,neq,0:*), ruser(*)
        Real (Kind=nag_wp), Intent (In) :: y(neq,0:*)
        Integer, Intent (Inout)        :: iuser(*)
        Integer, Intent (In)           :: m(neq)
!       .. Executable Statements ..
        dfdy(1,2,0) = one
        dfdy(2,1,0) = -y(2,2)*sqrofr
        dfdy(2,2,2) = -y(1,0)*sqrofr
        dfdy(2,3,0) = -y(3,1)*sqrofr
        dfdy(2,3,1) = -y(3,0)*sqrofr
        dfdy(3,1,0) = -y(3,1)*sqrofr
        dfdy(3,2,0) = y(3,0)*sqrofr
        dfdy(3,3,0) = y(2,0)*sqrofr
        dfdy(3,3,1) = -y(1,0)*sqrofr
        Return
      End Subroutine fjac
      Subroutine gafun(ya,neq,m,nlbc,ga,iuser,ruser)

!       .. Scalar Arguments ..
        Integer, Intent (In)           :: neq, nlbc
!       .. Array Arguments ..
        Real (Kind=nag_wp), Intent (Out) :: ga(nlbc)
        Real (Kind=nag_wp), Intent (Inout) :: ruser(*)
        Real (Kind=nag_wp), Intent (In) :: ya(neq,0:*)
        Integer, Intent (Inout)        :: iuser(*)
        Integer, Intent (In)           :: m(neq)
!       .. Executable Statements ..
        ga(1) = ya(1,0)
        ga(2) = ya(2,0)
        ga(3) = ya(3,0) - omega
        Return
      End Subroutine gafun
      Subroutine gbfun(yb,neq,m,nrbc,gb,iuser,ruser)

!       .. Scalar Arguments ..
        Integer, Intent (In)           :: neq, nrbc
!       .. Array Arguments ..
        Real (Kind=nag_wp), Intent (Out) :: gb(nrbc)
        Real (Kind=nag_wp), Intent (Inout) :: ruser(*)
        Real (Kind=nag_wp), Intent (In) :: yb(neq,0:*)
        Integer, Intent (Inout)        :: iuser(*)
        Integer, Intent (In)           :: m(neq)
!       .. Executable Statements ..
        gb(1) = yb(1,0)
        gb(2) = yb(2,0)
        gb(3) = yb(3,0) + omega
        Return
      End Subroutine gbfun
      Subroutine gajac(ya,neq,m,nlbc,dgady,iuser,ruser)

!       .. Scalar Arguments ..
        Integer, Intent (In)           :: neq, nlbc
!       .. Array Arguments ..
        Real (Kind=nag_wp), Intent (Inout) :: dgady(nlbc,neq,0:*), ruser(*)
        Real (Kind=nag_wp), Intent (In) :: ya(neq,0:*)
        Integer, Intent (Inout)        :: iuser(*)
        Integer, Intent (In)           :: m(neq)
!       .. Executable Statements ..
        dgady(1,1,0) = one
        dgady(2,2,0) = one
        dgady(3,3,0) = one
        Return
      End Subroutine gajac
      Subroutine gbjac(yb,neq,m,nrbc,dgbdy,iuser,ruser)

!       .. Scalar Arguments ..
        Integer, Intent (In)           :: neq, nrbc
!       .. Array Arguments ..
        Real (Kind=nag_wp), Intent (Inout) :: dgbdy(nrbc,neq,0:*), ruser(*)
        Real (Kind=nag_wp), Intent (In) :: yb(neq,0:*)
        Integer, Intent (Inout)        :: iuser(*)
        Integer, Intent (In)           :: m(neq)
!       .. Executable Statements ..
        dgbdy(1,1,0) = one
        dgbdy(2,2,0) = one
        dgbdy(3,3,0) = one
        Return
      End Subroutine gbjac
      Subroutine guess(x,neq,m,y,dym,iuser,ruser)

!       .. Scalar Arguments ..
        Real (Kind=nag_wp), Intent (In) :: x
        Integer, Intent (In)           :: neq
!       .. Array Arguments ..
        Real (Kind=nag_wp), Intent (Out) :: dym(neq)
        Real (Kind=nag_wp), Intent (Inout) :: ruser(*), y(neq,0:*)
        Integer, Intent (Inout)        :: iuser(*)
        Integer, Intent (In)           :: m(neq)
!       .. Executable Statements ..
        y(1,0) = -(x-0.5_nag_wp)*(x*(x-one))**2
        y(2,0) = -x*(x-one)*(5._nag_wp*x*(x-one)+one)
        y(2,1) = -(2._nag_wp*x-one)*(10.0_nag_wp*x*(x-one)+one)
        y(2,2) = -12.0_nag_wp*(5._nag_wp*x*(x-one)+x)
        y(3,0) = -8.0_nag_wp*omega*(x-0.5_nag_wp)**3
        y(3,1) = -24.0_nag_wp*omega*(x-0.5_nag_wp)**2
        dym(1) = y(2,0)
        dym(2) = -120.0_nag_wp*(x-0.5_nag_wp)
        dym(3) = -56.0_nag_wp*omega*(x-0.5_nag_wp)
        Return
      End Subroutine guess
    End Module d02tlfe_mod
    Program d02tlfe

!     D02TLF Example Main Program

!     .. Use Statements ..
      Use nag_library, Only: d02tlf, d02tvf, d02txf, d02tyf, d02tzf, nag_wp
      Use d02tlfe_mod, Only: ffun, fjac, gafun, gajac, gbfun, gbjac, guess, m, &
                             mmax, neq, nin, nlbc, nout, nrbc, omega, one,     &
                             sqrofr
!     .. Implicit None Statement ..
      Implicit None
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: dx, ermx, r
      Integer                          :: i, iermx, ifail, ijermx, j, licomm,  &
                                          lrcomm, mxmesh, ncol, ncont, nmesh
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: mesh(:), rcomm(:), tol(:), y(:,:)
      Real (Kind=nag_wp)               :: ruser(1)
      Integer, Allocatable             :: icomm(:), ipmesh(:)
      Integer                          :: iuser(2)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: real, sqrt
!     .. Executable Statements ..
      Write (nout,*) 'D02TLF Example Program Results'
      Write (nout,*)
!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) ncol, nmesh, mxmesh

      Allocate (mesh(mxmesh),tol(neq),y(neq,0:mmax-1),ipmesh(mxmesh))

      Read (nin,*) omega
      Read (nin,*) tol(1:neq)

      dx = one/real(nmesh-1,kind=nag_wp)
      mesh(1) = 0.0_nag_wp
      Do i = 2, nmesh - 1
        mesh(i) = mesh(i-1) + dx
      End Do
      mesh(nmesh) = one

      ipmesh(1) = 1
      ipmesh(2:nmesh-1) = 2
      ipmesh(nmesh) = 1

!     Workspace query to get size of rcomm and icomm
      ifail = 0
      Call d02tvf(neq,m,nlbc,nrbc,ncol,tol,mxmesh,nmesh,mesh,ipmesh,ruser,0,   &
        iuser,2,ifail)
      lrcomm = iuser(1)
      licomm = iuser(2)
      Allocate (rcomm(lrcomm),icomm(licomm))

!     Initialize integrator for given problem.
      ifail = 0
      Call d02tvf(neq,m,nlbc,nrbc,ncol,tol,mxmesh,nmesh,mesh,ipmesh,rcomm,     &
        lrcomm,icomm,licomm,ifail)

!     Number of continuation steps (last r=100**ncont, sqrofr=10**ncont)
      Read (nin,*) ncont
!     Initialize problem continuation parameter.
      Read (nin,*) r
      sqrofr = sqrt(r)

contn: Do j = 1, ncont
        Write (nout,99999) tol(1), r

!       Solve problem.
        ifail = -1
        Call d02tlf(ffun,fjac,gafun,gbfun,gajac,gbjac,guess,rcomm,icomm,iuser, &
          ruser,ifail)

!       Extract mesh
        ifail = -1
        Call d02tzf(mxmesh,nmesh,mesh,ipmesh,ermx,iermx,ijermx,rcomm,icomm,    &
          ifail)
        If (ifail==1) Then
          Exit contn
        End If

!       Print mesh and error statistics.
        Write (nout,99998) nmesh, ermx, iermx, ijermx
        Write (nout,99997)(i,ipmesh(i),mesh(i),i=1,nmesh)
!       Print solution components on mesh.
        Write (nout,99996)
        Do i = 1, nmesh
          ifail = 0
          Call d02tyf(mesh(i),y,neq,mmax,rcomm,icomm,ifail)
          Write (nout,99995) mesh(i), y(1:neq,0)
        End Do

        If (j==ncont) Then
          Exit contn
        End If

!       Modify continuation parameter.
        r = 100.0_nag_wp*r
        sqrofr = sqrt(r)
!       Select mesh for continuation and call continuation primer routine.
        ipmesh(2:nmesh-1) = 2
        ifail = 0
        Call d02txf(mxmesh,nmesh,mesh,ipmesh,rcomm,icomm,ifail)

      End Do contn

99999 Format (/,' Tolerance = ',1P,E8.1,'  R = ',E10.3)
99998 Format (/,' Used a mesh of ',I4,' points',/,' Maximum error = ',E10.2,   &
        '  in interval ',I4,' for component ',I4,/)
99997 Format (/,' Mesh points:',/,4(I4,'(',I1,')',E11.4))
99996 Format (/,'      x        f        f''       g')
99995 Format (' ',F8.3,1X,3F9.4)
    End Program d02tlfe


d02tvfe.f90

!   D02TVF Example Program Text
!   Mark 26 Release. NAG Copyright 2016.

    Module d02tvfe_mod

!     D02TVF Example Program Module:
!            Parameters and User-defined Routines

!     .. Use Statements ..
      Use nag_library, Only: nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Accessibility Statements ..
      Private
      Public                           :: ffun, fjac, gafun, gajac, gbfun,     &
                                          gbjac, guess
!     .. Parameters ..
      Real (Kind=nag_wp), Parameter, Public :: one = 1.0_nag_wp
      Real (Kind=nag_wp), Parameter    :: two = 2.0_nag_wp
      Real (Kind=nag_wp), Parameter    :: zero = 0.0_nag_wp
      Integer, Parameter, Public       :: mmax = 1, neq = 6, nin = 5,          &
                                          nlbc = 3, nout = 6, nrbc = 3
!     .. Local Scalars ..
      Real (Kind=nag_wp), Public, Save :: beta0, eta, lambda, mu
!     .. Local Arrays ..
      Integer, Public, Save            :: m(neq) = (/1,1,1,1,1,1/)
    Contains
      Subroutine ffun(x,y,neq,m,f,iuser,ruser)

!       .. Use Statements ..
        Use nag_library, Only: x01aaf
!       .. Scalar Arguments ..
        Real (Kind=nag_wp), Intent (In) :: x
        Integer, Intent (In)           :: neq
!       .. Array Arguments ..
        Real (Kind=nag_wp), Intent (Out) :: f(neq)
        Real (Kind=nag_wp), Intent (Inout) :: ruser(*)
        Real (Kind=nag_wp), Intent (In) :: y(neq,0:*)
        Integer, Intent (Inout)        :: iuser(*)
        Integer, Intent (In)           :: m(neq)
!       .. Local Scalars ..
        Real (Kind=nag_wp)             :: beta
!       .. Intrinsic Procedures ..
        Intrinsic                      :: cos
!       .. Executable Statements ..
        beta = beta0*(one+cos(two*x01aaf(beta)*x))
        f(1) = mu - beta*y(1,0)*y(3,0)
        f(2) = beta*y(1,0)*y(3,0) - y(2,0)/lambda
        f(3) = y(2,0)/lambda - y(3,0)/eta
        f(4:6) = zero
        Return
      End Subroutine ffun
      Subroutine fjac(x,y,neq,m,dfdy,iuser,ruser)

!       .. Use Statements ..
        Use nag_library, Only: x01aaf
!       .. Scalar Arguments ..
        Real (Kind=nag_wp), Intent (In) :: x
        Integer, Intent (In)           :: neq
!       .. Array Arguments ..
        Real (Kind=nag_wp), Intent (Inout) :: dfdy(neq,neq,0:*), ruser(*)
        Real (Kind=nag_wp), Intent (In) :: y(neq,0:*)
        Integer, Intent (Inout)        :: iuser(*)
        Integer, Intent (In)           :: m(neq)
!       .. Local Scalars ..
        Real (Kind=nag_wp)             :: beta
!       .. Intrinsic Procedures ..
        Intrinsic                      :: cos
!       .. Executable Statements ..
        beta = beta0*(one+cos(two*x01aaf(beta)*x))
        dfdy(1,1,0) = -beta*y(3,0)
        dfdy(1,3,0) = -beta*y(1,0)
        dfdy(2,1,0) = beta*y(3,0)
        dfdy(2,2,0) = -one/lambda
        dfdy(2,3,0) = beta*y(1,0)
        dfdy(3,2,0) = one/lambda
        dfdy(3,3,0) = -one/eta
        Return
      End Subroutine fjac
      Subroutine gafun(ya,neq,m,nlbc,ga,iuser,ruser)

!       .. Scalar Arguments ..
        Integer, Intent (In)           :: neq, nlbc
!       .. Array Arguments ..
        Real (Kind=nag_wp), Intent (Out) :: ga(nlbc)
        Real (Kind=nag_wp), Intent (Inout) :: ruser(*)
        Real (Kind=nag_wp), Intent (In) :: ya(neq,0:*)
        Integer, Intent (Inout)        :: iuser(*)
        Integer, Intent (In)           :: m(neq)
!       .. Executable Statements ..
        ga(1) = ya(1,0) - ya(4,0)
        ga(2) = ya(2,0) - ya(5,0)
        ga(3) = ya(3,0) - ya(6,0)
        Return
      End Subroutine gafun
      Subroutine gbfun(yb,neq,m,nrbc,gb,iuser,ruser)

!       .. Scalar Arguments ..
        Integer, Intent (In)           :: neq, nrbc
!       .. Array Arguments ..
        Real (Kind=nag_wp), Intent (Out) :: gb(nrbc)
        Real (Kind=nag_wp), Intent (Inout) :: ruser(*)
        Real (Kind=nag_wp), Intent (In) :: yb(neq,0:*)
        Integer, Intent (Inout)        :: iuser(*)
        Integer, Intent (In)           :: m(neq)
!       .. Executable Statements ..
        gb(1) = yb(1,0) - yb(4,0)
        gb(2) = yb(2,0) - yb(5,0)
        gb(3) = yb(3,0) - yb(6,0)
        Return
      End Subroutine gbfun
      Subroutine gajac(ya,neq,m,nlbc,dgady,iuser,ruser)

!       .. Scalar Arguments ..
        Integer, Intent (In)           :: neq, nlbc
!       .. Array Arguments ..
        Real (Kind=nag_wp), Intent (Inout) :: dgady(nlbc,neq,0:*), ruser(*)
        Real (Kind=nag_wp), Intent (In) :: ya(neq,0:*)
        Integer, Intent (Inout)        :: iuser(*)
        Integer, Intent (In)           :: m(neq)
!       .. Executable Statements ..
        dgady(1,1,0) = one
        dgady(1,4,0) = -one
        dgady(2,2,0) = one
        dgady(2,5,0) = -one
        dgady(3,3,0) = one
        dgady(3,6,0) = -one
        Return
      End Subroutine gajac
      Subroutine gbjac(yb,neq,m,nrbc,dgbdy,iuser,ruser)

!       .. Scalar Arguments ..
        Integer, Intent (In)           :: neq, nrbc
!       .. Array Arguments ..
        Real (Kind=nag_wp), Intent (Inout) :: dgbdy(nrbc,neq,0:*), ruser(*)
        Real (Kind=nag_wp), Intent (In) :: yb(neq,0:*)
        Integer, Intent (Inout)        :: iuser(*)
        Integer, Intent (In)           :: m(neq)
!       .. Executable Statements ..
        dgbdy(1,1,0) = one
        dgbdy(1,4,0) = -one
        dgbdy(2,2,0) = one
        dgbdy(2,5,0) = -one
        dgbdy(3,3,0) = one
        dgbdy(3,6,0) = -one
        Return
      End Subroutine gbjac
      Subroutine guess(x,neq,m,y,dym,iuser,ruser)

!       .. Scalar Arguments ..
        Real (Kind=nag_wp), Intent (In) :: x
        Integer, Intent (In)           :: neq
!       .. Array Arguments ..
        Real (Kind=nag_wp), Intent (Out) :: dym(neq)
        Real (Kind=nag_wp), Intent (Inout) :: ruser(*), y(neq,0:*)
        Integer, Intent (Inout)        :: iuser(*)
        Integer, Intent (In)           :: m(neq)
!       .. Executable Statements ..
        y(1:3,0) = one
        y(4,0) = y(1,0)
        y(5,0) = y(2,0)
        y(6,0) = y(3,0)
        dym(1:neq) = zero
        Return
      End Subroutine guess
    End Module d02tvfe_mod
    Program d02tvfe

!     D02TVF Example Main Program

!     .. Use Statements ..
      Use nag_library, Only: d02tlf, d02tvf, d02tyf, d02tzf, nag_wp
      Use d02tvfe_mod, Only: beta0, eta, ffun, fjac, gafun, gajac, gbfun,      &
                             gbjac, guess, lambda, m, mmax, mu, neq, nin,      &
                             nlbc, nout, nrbc, one
!     .. Implicit None Statement ..
      Implicit None
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: dx, ermx
      Integer                          :: i, iermx, ifail, ijermx, licomm,     &
                                          lrcomm, mxmesh, ncol, nmesh
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: mesh(:), rcomm(:), tols(:), y(:,:)
      Real (Kind=nag_wp)               :: ruser(1)
      Integer, Allocatable             :: icomm(:), ipmesh(:)
      Integer                          :: iuser(2)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: real
!     .. Executable Statements ..
      Write (nout,*) 'D02TVF Example Program Results'
      Write (nout,*)
!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) ncol, nmesh, mxmesh
      Allocate (mesh(mxmesh),tols(neq),y(neq,0:mmax-1),ipmesh(mxmesh))

      Read (nin,*) beta0, eta, lambda, mu
      Read (nin,*) tols(1:neq)

      dx = one/real(nmesh-1,kind=nag_wp)
      mesh(1) = 0.0_nag_wp
      Do i = 2, nmesh - 1
        mesh(i) = mesh(i-1) + dx
      End Do
      mesh(nmesh) = one

      ipmesh(1) = 1
      ipmesh(2:nmesh-1) = 2
      ipmesh(nmesh) = 1

!     Workspace query to get size of rcomm and icomm
      ifail = 0
      Call d02tvf(neq,m,nlbc,nrbc,ncol,tols,mxmesh,nmesh,mesh,ipmesh,ruser,0,  &
        iuser,2,ifail)
      lrcomm = iuser(1)
      licomm = iuser(2)
      Allocate (rcomm(lrcomm),icomm(licomm))

!     Initialize
      ifail = 0
      Call d02tvf(neq,m,nlbc,nrbc,ncol,tols,mxmesh,nmesh,mesh,ipmesh,rcomm,    &
        lrcomm,icomm,licomm,ifail)

!     Solve
      ifail = -1
      Call d02tlf(ffun,fjac,gafun,gbfun,gajac,gbjac,guess,rcomm,icomm,iuser,   &
        ruser,ifail)

!     Extract mesh.
      ifail = -1
      Call d02tzf(mxmesh,nmesh,mesh,ipmesh,ermx,iermx,ijermx,rcomm,icomm,      &
        ifail)

      If (ifail/=1) Then
!       Print mesh statistics
        Write (nout,99999) nmesh, ermx, iermx, ijermx
        Write (nout,99998)(i,ipmesh(i),mesh(i),i=1,nmesh)

!       Print solution on mesh.
        Write (nout,99997)
        Do i = 1, nmesh

          ifail = 0
          Call d02tyf(mesh(i),y,neq,mmax,rcomm,icomm,ifail)
          Write (nout,99996) mesh(i), y(1:3,0)

        End Do
      End If

99999 Format (/,' Used a mesh of ',I4,' points',/,' Maximum error = ',E10.2,   &
        '  in interval ',I4,' for component ',I4,/)
99998 Format (/,' Mesh points:',/,4(I4,'(',I1,')',F7.4))
99997 Format (/,' Computed solution at mesh points',/,'    x       y1   ',     &
        '      y2         y3')
99996 Format (1X,F6.3,1X,3E11.3)
    End Program d02tvfe


d02txfe.f90

!   D02TXF Example Program Text
!   Mark 26 Release. NAG Copyright 2016.

    Module d02txfe_mod

!     D02TXF Example Program Module:
!            Parameters and User-defined Routines

!     .. Use Statements ..
      Use nag_library, Only: nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Accessibility Statements ..
      Private
      Public                           :: ffun, fjac, gafun, gajac, gbfun,     &
                                          gbjac, guess
!     .. Parameters ..
      Real (Kind=nag_wp), Parameter    :: half = 0.5_nag_wp
      Real (Kind=nag_wp), Parameter    :: three = 3.0_nag_wp
      Real (Kind=nag_wp), Parameter, Public :: one = 1.0_nag_wp
      Real (Kind=nag_wp), Parameter, Public :: two = 2.0_nag_wp
      Real (Kind=nag_wp), Parameter, Public :: xsplit = 30.0_nag_wp
      Integer, Parameter, Public       :: m1 = 3, m2 = 2, mmax = 3, neq = 2,   &
                                          nin = 5, nlbc = 3, nleft = 15,       &
                                          nout = 6, nrbc = 2, nright = 10
!     .. Local Scalars ..
      Real (Kind=nag_wp), Public, Save :: el, en, s
    Contains
      Subroutine ffun(x,y,neq,m,f,iuser,ruser)

!       .. Scalar Arguments ..
        Real (Kind=nag_wp), Intent (In) :: x
        Integer, Intent (In)           :: neq
!       .. Array Arguments ..
        Real (Kind=nag_wp), Intent (Out) :: f(neq)
        Real (Kind=nag_wp), Intent (Inout) :: ruser(*)
        Real (Kind=nag_wp), Intent (In) :: y(neq,0:*)
        Integer, Intent (Inout)        :: iuser(*)
        Integer, Intent (In)           :: m(neq)
!       .. Local Scalars ..
        Real (Kind=nag_wp)             :: t1, y11, y20
!       .. Executable Statements ..
        t1 = half*(three-en)*y(1,0)
        y11 = y(1,1)
        y20 = y(2,0)
        f(1) = (el**3)*(one-y20**2) + (el**2)*s*y11 - el*(t1*y(1,2)+en*y11**2)
        f(2) = (el**2)*s*(y20-one) - el*(t1*y(2,1)+(en-one)*y11*y20)
        Return
      End Subroutine ffun
      Subroutine fjac(x,y,neq,m,dfdy,iuser,ruser)

!       .. Scalar Arguments ..
        Real (Kind=nag_wp), Intent (In) :: x
        Integer, Intent (In)           :: neq
!       .. Array Arguments ..
        Real (Kind=nag_wp), Intent (Inout) :: dfdy(neq,neq,0:*), ruser(*)
        Real (Kind=nag_wp), Intent (In) :: y(neq,0:*)
        Integer, Intent (Inout)        :: iuser(*)
        Integer, Intent (In)           :: m(neq)
!       .. Executable Statements ..
        dfdy(1,2,0) = -two*el**3*y(2,0)
        dfdy(1,1,0) = -el*half*(three-en)*y(1,2)
        dfdy(1,1,1) = el**2*s - el*two*en*y(1,1)
        dfdy(1,1,2) = -el*half*(three-en)*y(1,0)
        dfdy(2,2,0) = el**2*s - el*(en-one)*y(1,1)
        dfdy(2,2,1) = -el*half*(three-en)*y(1,0)
        dfdy(2,1,0) = -el*half*(three-en)*y(2,1)
        dfdy(2,1,1) = -el*(en-one)*y(2,0)
        Return
      End Subroutine fjac
      Subroutine gafun(ya,neq,m,nlbc,ga,iuser,ruser)

!       .. Scalar Arguments ..
        Integer, Intent (In)           :: neq, nlbc
!       .. Array Arguments ..
        Real (Kind=nag_wp), Intent (Out) :: ga(nlbc)
        Real (Kind=nag_wp), Intent (Inout) :: ruser(*)
        Real (Kind=nag_wp), Intent (In) :: ya(neq,0:*)
        Integer, Intent (Inout)        :: iuser(*)
        Integer, Intent (In)           :: m(neq)
!       .. Executable Statements ..
        ga(1) = ya(1,0)
        ga(2) = ya(1,1)
        ga(3) = ya(2,0)
        Return
      End Subroutine gafun
      Subroutine gbfun(yb,neq,m,nrbc,gb,iuser,ruser)

!       .. Scalar Arguments ..
        Integer, Intent (In)           :: neq, nrbc
!       .. Array Arguments ..
        Real (Kind=nag_wp), Intent (Out) :: gb(nrbc)
        Real (Kind=nag_wp), Intent (Inout) :: ruser(*)
        Real (Kind=nag_wp), Intent (In) :: yb(neq,0:*)
        Integer, Intent (Inout)        :: iuser(*)
        Integer, Intent (In)           :: m(neq)
!       .. Executable Statements ..
        gb(1) = yb(1,1)
        gb(2) = yb(2,0) - one
        Return
      End Subroutine gbfun
      Subroutine gajac(ya,neq,m,nlbc,dgady,iuser,ruser)

!       .. Scalar Arguments ..
        Integer, Intent (In)           :: neq, nlbc
!       .. Array Arguments ..
        Real (Kind=nag_wp), Intent (Inout) :: dgady(nlbc,neq,0:*), ruser(*)
        Real (Kind=nag_wp), Intent (In) :: ya(neq,0:*)
        Integer, Intent (Inout)        :: iuser(*)
        Integer, Intent (In)           :: m(neq)
!       .. Executable Statements ..
        dgady(1,1,0) = one
        dgady(2,1,1) = one
        dgady(3,2,0) = one
        Return
      End Subroutine gajac
      Subroutine gbjac(yb,neq,m,nrbc,dgbdy,iuser,ruser)

!       .. Scalar Arguments ..
        Integer, Intent (In)           :: neq, nrbc
!       .. Array Arguments ..
        Real (Kind=nag_wp), Intent (Inout) :: dgbdy(nrbc,neq,0:*), ruser(*)
        Real (Kind=nag_wp), Intent (In) :: yb(neq,0:*)
        Integer, Intent (Inout)        :: iuser(*)
        Integer, Intent (In)           :: m(neq)
!       .. Executable Statements ..
        dgbdy(1,1,1) = one
        dgbdy(2,2,0) = one
        Return
      End Subroutine gbjac
      Subroutine guess(x,neq,m,y,dym,iuser,ruser)

!       .. Scalar Arguments ..
        Real (Kind=nag_wp), Intent (In) :: x
        Integer, Intent (In)           :: neq
!       .. Array Arguments ..
        Real (Kind=nag_wp), Intent (Out) :: dym(neq)
        Real (Kind=nag_wp), Intent (Inout) :: ruser(*), y(neq,0:*)
        Integer, Intent (Inout)        :: iuser(*)
        Integer, Intent (In)           :: m(neq)
!       .. Local Scalars ..
        Real (Kind=nag_wp)             :: ex, expmx
!       .. Intrinsic Procedures ..
        Intrinsic                      :: exp
!       .. Executable Statements ..
        ex = x*el
        expmx = exp(-ex)
        y(1,0) = -ex**2*expmx
        y(1,1) = (-two*ex+ex**2)*expmx
        y(1,2) = (-two+4.0E0_nag_wp*ex-ex**2)*expmx
        y(2,0) = one - expmx
        y(2,1) = expmx
        dym(1) = (6.0E0_nag_wp-6.0E0_nag_wp*ex+ex**2)*expmx
        dym(2) = -expmx
        Return
      End Subroutine guess
    End Module d02txfe_mod
    Program d02txfe

!     D02TXF Example Main Program

!     .. Use Statements ..
      Use nag_library, Only: d02tlf, d02tvf, d02txf, d02tyf, d02tzf, nag_wp
      Use d02txfe_mod, Only: el, en, ffun, fjac, gafun, gajac, gbfun, gbjac,   &
                             guess, m1, m2, mmax, neq, nin, nlbc, nleft, nout, &
                             nrbc, nright, one, s, two, xsplit
!     .. Implicit None Statement ..
      Implicit None
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: dx, el_init, ermx, s_init, xx
      Integer                          :: i, iermx, ifail, ijermx, j, licomm,  &
                                          lrcomm, mxmesh, ncol, ncont, nmesh
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: mesh(:), rcomm(:)
      Real (Kind=nag_wp)               :: ruser(1), tol(neq), y(neq,0:mmax-1)
      Integer, Allocatable             :: icomm(:), ipmesh(:)
      Integer                          :: iuser(2), m(neq)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: min, real
!     .. Executable Statements ..
      Write (nout,*) 'D02TXF Example Program Results'
      Write (nout,*)
!     Skip heading in data file
      Read (nin,*)
!     Read method parameters
      Read (nin,*) ncol, nmesh, mxmesh
      Read (nin,*) tol(1:neq)

      Allocate (mesh(mxmesh),ipmesh(mxmesh))
!     Read problem (initial) parameters
      Read (nin,*) en, el_init, s_init
!     Initialize data
      el = el_init
      s = s_init
      m(1) = m1
      m(2) = m2

      dx = one/real(nmesh-1,kind=nag_wp)
      mesh(1) = 0.0_nag_wp
      Do i = 2, nmesh - 1
        mesh(i) = mesh(i-1) + dx
      End Do
      mesh(nmesh) = 1.0_nag_wp

      ipmesh(1) = 1
      ipmesh(2:nmesh-1) = 2
      ipmesh(nmesh) = 1

!     Workspace query to get size of rcomm and icomm
      ifail = 0
      Call d02tvf(neq,m,nlbc,nrbc,ncol,tol,mxmesh,nmesh,mesh,ipmesh,ruser,0,   &
        iuser,2,ifail)
      lrcomm = iuser(1)
      licomm = iuser(2)
      Allocate (rcomm(lrcomm),icomm(licomm))

!     ifail: behaviour on error exit
!             =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
      ifail = 0
      Call d02tvf(neq,m,nlbc,nrbc,ncol,tol,mxmesh,nmesh,mesh,ipmesh,rcomm,     &
        lrcomm,icomm,licomm,ifail)

!     Initialize number of continuation steps in el and s
      Read (nin,*) ncont
cont: Do j = 1, ncont
        Write (nout,99997) tol(1), el, s

!       Solve
        ifail = -1
        Call d02tlf(ffun,fjac,gafun,gbfun,gajac,gbjac,guess,rcomm,icomm,iuser, &
          ruser,ifail)
        If (ifail/=0) Then
          Exit cont
        End If

!       Extract mesh
        ifail = 0
        Call d02tzf(mxmesh,nmesh,mesh,ipmesh,ermx,iermx,ijermx,rcomm,icomm,    &
          ifail)

        Write (nout,99996) nmesh, ermx, iermx, ijermx
!       Print solution components on mesh
        Write (nout,99999)

!       Left side domain [0,xsplit], evaluate at nleft+1 uniform grid points.
        dx = xsplit/real(nleft,kind=nag_wp)/el
        xx = 0.0_nag_wp
        Do i = 0, nleft
          ifail = 0
          Call d02tyf(xx,y,neq,mmax,rcomm,icomm,ifail)
          Write (nout,99998) xx*el, y(1,0), y(2,0)
          xx = xx + dx
        End Do

!       Right side domain (xsplit,L], evaluate at nright uniform grid points.
        dx = (el-xsplit)/real(nright,kind=nag_wp)/el
        xx = xsplit/el
        Do i = 1, nright
          xx = min(1.0_nag_wp,xx+dx)
          ifail = 0
          Call d02tyf(xx,y,neq,mmax,rcomm,icomm,ifail)
          Write (nout,99998) xx*el, y(1,0), y(2,0)
        End Do

!       Select mesh for continuation and update continuation parameters.
        If (j<ncont) Then
          el = two*el
          s = 0.6_nag_wp*s
          nmesh = (nmesh+1)/2
          ifail = 0
          Call d02txf(mxmesh,nmesh,mesh,ipmesh,rcomm,icomm,ifail)
        End If
      End Do cont

99999 Format (/,' Solution on original interval:',/,6X,'x',8X,'f',10X,'g')
99998 Format (1X,F8.2,2(1X,F10.4))
99997 Format (/,/,' Tolerance = ',E8.1,'  L = ',F8.3,'  S =',F7.4)
99996 Format (/,' Used a mesh of ',I4,' points',/,' Maximum error = ',E10.2,   &
        '  in interval ',I4,' for component ',I4)
    End Program d02txfe


d02tyfe.f90

!   D02TYF Example Program Text
!   Mark 26 Release. NAG Copyright 2016.

    Module d02tyfe_mod

!     D02TYF Example Program Module:
!            Parameters and User-defined Routines

!     .. Use Statements ..
      Use nag_library, Only: nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Accessibility Statements ..
      Private
      Public                           :: ffun, fjac, gafun, gajac, gbfun,     &
                                          gbjac, guess
!     .. Parameters ..
      Integer, Parameter, Public       :: mmax = 2, neq = 1, nin = 5,          &
                                          nlbc = 1, nmesh_out = 11, nout = 6,  &
                                          nrbc = 1
!     .. Local Scalars ..
      Real (Kind=nag_wp), Public, Save :: a
!     .. Local Arrays ..
      Integer, Public, Save            :: m(1) = (/2/)
    Contains
      Subroutine ffun(x,y,neq,m,f,iuser,ruser)

!       .. Scalar Arguments ..
        Real (Kind=nag_wp), Intent (In) :: x
        Integer, Intent (In)           :: neq
!       .. Array Arguments ..
        Real (Kind=nag_wp), Intent (Out) :: f(neq)
        Real (Kind=nag_wp), Intent (Inout) :: ruser(*)
        Real (Kind=nag_wp), Intent (In) :: y(neq,0:*)
        Integer, Intent (Inout)        :: iuser(*)
        Integer, Intent (In)           :: m(neq)
!       .. Intrinsic Procedures ..
        Intrinsic                      :: sqrt
!       .. Executable Statements ..
        If (y(1,0)<=0.0E0_nag_wp) Then
          f(1) = 0.0_nag_wp
        Else
          f(1) = (y(1,0))**1.5_nag_wp/sqrt(x)
        End If
        Return
      End Subroutine ffun
      Subroutine fjac(x,y,neq,m,dfdy,iuser,ruser)

!       .. Scalar Arguments ..
        Real (Kind=nag_wp), Intent (In) :: x
        Integer, Intent (In)           :: neq
!       .. Array Arguments ..
        Real (Kind=nag_wp), Intent (Inout) :: dfdy(neq,neq,0:*), ruser(*)
        Real (Kind=nag_wp), Intent (In) :: y(neq,0:*)
        Integer, Intent (Inout)        :: iuser(*)
        Integer, Intent (In)           :: m(neq)
!       .. Intrinsic Procedures ..
        Intrinsic                      :: sqrt
!       .. Executable Statements ..
        If (y(1,0)<=0.0E0_nag_wp) Then
          dfdy(1,1,0) = 0.0_nag_wp
        Else
          dfdy(1,1,0) = 1.5_nag_wp*sqrt(y(1,0))/sqrt(x)
        End If
        Return
      End Subroutine fjac
      Subroutine gafun(ya,neq,m,nlbc,ga,iuser,ruser)

!       .. Scalar Arguments ..
        Integer, Intent (In)           :: neq, nlbc
!       .. Array Arguments ..
        Real (Kind=nag_wp), Intent (Out) :: ga(nlbc)
        Real (Kind=nag_wp), Intent (Inout) :: ruser(*)
        Real (Kind=nag_wp), Intent (In) :: ya(neq,0:*)
        Integer, Intent (Inout)        :: iuser(*)
        Integer, Intent (In)           :: m(neq)
!       .. Executable Statements ..
        ga(1) = ya(1,0) - 1.0_nag_wp
        Return
      End Subroutine gafun
      Subroutine gbfun(yb,neq,m,nrbc,gb,iuser,ruser)

!       .. Scalar Arguments ..
        Integer, Intent (In)           :: neq, nrbc
!       .. Array Arguments ..
        Real (Kind=nag_wp), Intent (Out) :: gb(nrbc)
        Real (Kind=nag_wp), Intent (Inout) :: ruser(*)
        Real (Kind=nag_wp), Intent (In) :: yb(neq,0:*)
        Integer, Intent (Inout)        :: iuser(*)
        Integer, Intent (In)           :: m(neq)
!       .. Executable Statements ..
        gb(1) = yb(1,0)
        Return
      End Subroutine gbfun
      Subroutine gajac(ya,neq,m,nlbc,dgady,iuser,ruser)

!       .. Scalar Arguments ..
        Integer, Intent (In)           :: neq, nlbc
!       .. Array Arguments ..
        Real (Kind=nag_wp), Intent (Inout) :: dgady(nlbc,neq,0:*), ruser(*)
        Real (Kind=nag_wp), Intent (In) :: ya(neq,0:*)
        Integer, Intent (Inout)        :: iuser(*)
        Integer, Intent (In)           :: m(neq)
!       .. Executable Statements ..
        dgady(1,1,0) = 1.0_nag_wp
        Return
      End Subroutine gajac
      Subroutine gbjac(yb,neq,m,nrbc,dgbdy,iuser,ruser)

!       .. Scalar Arguments ..
        Integer, Intent (In)           :: neq, nrbc
!       .. Array Arguments ..
        Real (Kind=nag_wp), Intent (Inout) :: dgbdy(nrbc,neq,0:*), ruser(*)
        Real (Kind=nag_wp), Intent (In) :: yb(neq,0:*)
        Integer, Intent (Inout)        :: iuser(*)
        Integer, Intent (In)           :: m(neq)
!       .. Executable Statements ..
        dgbdy(1,1,0) = 1.0_nag_wp
        Return
      End Subroutine gbjac
      Subroutine guess(x,neq,m,y,dym,iuser,ruser)

!       .. Scalar Arguments ..
        Real (Kind=nag_wp), Intent (In) :: x
        Integer, Intent (In)           :: neq
!       .. Array Arguments ..
        Real (Kind=nag_wp), Intent (Out) :: dym(neq)
        Real (Kind=nag_wp), Intent (Inout) :: ruser(*), y(neq,0:*)
        Integer, Intent (Inout)        :: iuser(*)
        Integer, Intent (In)           :: m(neq)
!       .. Executable Statements ..
        y(1,0) = 1.0_nag_wp - x/a
        y(1,1) = -1.0_nag_wp/a
        dym(1) = 0.0_nag_wp
        Return
      End Subroutine guess
    End Module d02tyfe_mod
    Program d02tyfe

!     D02TYF Example Main Program

!     .. Use Statements ..
      Use nag_library, Only: d02tlf, d02tvf, d02tyf, d02tzf, nag_wp
      Use d02tyfe_mod, Only: a, ffun, fjac, gafun, gajac, gbfun, gbjac, guess, &
                             m, mmax, neq, nin, nlbc, nmesh_out, nout, nrbc
!     .. Implicit None Statement ..
      Implicit None
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: ainc, ermx, x
      Integer                          :: i, iermx, ifail, ijermx, licomm,     &
                                          lrcomm, mxmesh, ncol, nmesh
      Logical                          :: failed
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: mesh(:), rcomm(:), tol(:), y(:,:)
      Real (Kind=nag_wp)               :: ruser(1)
      Integer, Allocatable             :: icomm(:), ipmesh(:)
      Integer                          :: iuser(2)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: real
!     .. Executable Statements ..
      Write (nout,*) 'D02TYF Example Program Results'
      Write (nout,*)
!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) ncol, nmesh, mxmesh
      Allocate (mesh(mxmesh),tol(neq),y(neq,0:mmax-1),ipmesh(mxmesh))

      Read (nin,*) a
      Read (nin,*) tol(1:neq)

      ainc = a/real(nmesh-1,kind=nag_wp)
      mesh(1) = 0.0E0_nag_wp
      Do i = 2, nmesh - 1
        mesh(i) = mesh(i-1) + ainc
      End Do
      mesh(nmesh) = a

      ipmesh(1) = 1
      ipmesh(2:nmesh-1) = 2
      ipmesh(nmesh) = 1

!     Workspace query to get size of rcomm and icomm
      ifail = 0
      Call d02tvf(neq,m,nlbc,nrbc,ncol,tol,mxmesh,nmesh,mesh,ipmesh,ruser,0,   &
        iuser,2,ifail)
      lrcomm = iuser(1)
      licomm = iuser(2)
      Allocate (rcomm(lrcomm),icomm(licomm))

!     Initialize
      ifail = 0
      Call d02tvf(neq,m,nlbc,nrbc,ncol,tol,mxmesh,nmesh,mesh,ipmesh,rcomm,     &
        lrcomm,icomm,licomm,ifail)

      Write (nout,99999) tol(1), a

!     Solve
      ifail = -1
      Call d02tlf(ffun,fjac,gafun,gbfun,gajac,gbjac,guess,rcomm,icomm,iuser,   &
        ruser,ifail)

      failed = ifail /= 0

!     Extract mesh.
      ifail = -1
      Call d02tzf(mxmesh,nmesh,mesh,ipmesh,ermx,iermx,ijermx,rcomm,icomm,      &
        ifail)

      If (ifail/=1) Then
!       Print mesh statistics
        Write (nout,99998) nmesh, ermx, iermx, ijermx
        Write (nout,99997)(i,ipmesh(i),mesh(i),i=1,nmesh)
      End If
      If (.Not. failed) Then
!       Print solution on output mesh.
        Write (nout,99996)
        x = 0.0_nag_wp
        ainc = a/real(nmesh_out-1,kind=nag_wp)
        Do i = 1, nmesh_out
          ifail = 0
          Call d02tyf(x,y,neq,mmax,rcomm,icomm,ifail)
          Write (nout,99995) x, y(1,0:1)
          x = x + ainc
        End Do
      End If

99999 Format (/,/,' Tolerance = ',E8.1,' A = ',F8.2)
99998 Format (/,' Used a mesh of ',I4,' points',/,' Maximum error = ',E10.2,   &
        '  in interval ',I4,' for component ',I4,/)
99997 Format (/,' Mesh points:',/,4(I4,'(',I1,')',E11.4))
99996 Format (/,' Computed solution',/,'       x     solution   derivative')
99995 Format (' ',F8.2,2F11.5)

    End Program d02tyfe


d02tzfe.f90

!   D02TZF Example Program Text
!   Mark 26 Release. NAG Copyright 2016.

    Module d02tzfe_mod

!     D02TZF Example Program Module:
!            Parameters and User-defined Routines

!     .. Use Statements ..
      Use nag_library, Only: nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Accessibility Statements ..
      Private
      Public                           :: ffun, fjac, gafun, gajac, gbfun,     &
                                          gbjac, guess
!     .. Parameters ..
      Integer, Parameter, Public       :: mmax = 2, neq = 1, nin = 5,          &
                                          nlbc = 1, nout = 6, nrbc = 1
!     .. Local Scalars ..
      Real (Kind=nag_wp), Public, Save :: alpha, beta, eps
!     .. Local Arrays ..
      Integer, Public, Save            :: m(1) = (/2/)
    Contains
      Subroutine ffun(x,y,neq,m,f,iuser,ruser)

!       .. Scalar Arguments ..
        Real (Kind=nag_wp), Intent (In) :: x
        Integer, Intent (In)           :: neq
!       .. Array Arguments ..
        Real (Kind=nag_wp), Intent (Out) :: f(neq)
        Real (Kind=nag_wp), Intent (Inout) :: ruser(*)
        Real (Kind=nag_wp), Intent (In) :: y(neq,0:*)
        Integer, Intent (Inout)        :: iuser(*)
        Integer, Intent (In)           :: m(neq)
!       .. Executable Statements ..
        f(1) = (y(1,0)-y(1,0)*y(1,1))/eps
        Return
      End Subroutine ffun
      Subroutine fjac(x,y,neq,m,dfdy,iuser,ruser)

!       .. Use Statements ..
        Use nag_library, Only: x02ajf
!       .. Scalar Arguments ..
        Real (Kind=nag_wp), Intent (In) :: x
        Integer, Intent (In)           :: neq
!       .. Array Arguments ..
        Real (Kind=nag_wp), Intent (Inout) :: dfdy(neq,neq,0:*), ruser(*)
        Real (Kind=nag_wp), Intent (In) :: y(neq,0:*)
        Integer, Intent (Inout)        :: iuser(*)
        Integer, Intent (In)           :: m(neq)
!       .. Local Scalars ..
        Real (Kind=nag_wp)             :: epsh, fac, ptrb
        Integer                        :: i, j, k
!       .. Local Arrays ..
        Real (Kind=nag_wp)             :: f1(1), f2(1), yp(1,0:3)
!       .. Intrinsic Procedures ..
        Intrinsic                      :: abs, max, sqrt
!       .. Executable Statements ..
        epsh = 100.0_nag_wp*x02ajf()
        fac = sqrt(x02ajf())
        Do i = 1, neq
          Do j = 0, m(i) - 1
            yp(i,j) = y(i,j)
          End Do
        End Do
        Do i = 1, neq
          Do j = 0, m(i) - 1
            ptrb = max(epsh,fac*abs(y(i,j)))
            yp(i,j) = y(i,j) + ptrb
            Call ffun(x,yp,neq,m,f1,iuser,ruser)
            yp(i,j) = y(i,j) - ptrb
            Call ffun(x,yp,neq,m,f2,iuser,ruser)
            Do k = 1, neq
              dfdy(k,i,j) = 0.5_nag_wp*(f1(k)-f2(k))/ptrb
            End Do
            yp(i,j) = y(i,j)
          End Do
        End Do
        Return
      End Subroutine fjac
      Subroutine gafun(ya,neq,m,nlbc,ga,iuser,ruser)

!       .. Scalar Arguments ..
        Integer, Intent (In)           :: neq, nlbc
!       .. Array Arguments ..
        Real (Kind=nag_wp), Intent (Out) :: ga(nlbc)
        Real (Kind=nag_wp), Intent (Inout) :: ruser(*)
        Real (Kind=nag_wp), Intent (In) :: ya(neq,0:*)
        Integer, Intent (Inout)        :: iuser(*)
        Integer, Intent (In)           :: m(neq)
!       .. Executable Statements ..
        ga(1) = ya(1,0) - alpha
        Return
      End Subroutine gafun
      Subroutine gbfun(yb,neq,m,nrbc,gb,iuser,ruser)

!       .. Scalar Arguments ..
        Integer, Intent (In)           :: neq, nrbc
!       .. Array Arguments ..
        Real (Kind=nag_wp), Intent (Out) :: gb(nrbc)
        Real (Kind=nag_wp), Intent (Inout) :: ruser(*)
        Real (Kind=nag_wp), Intent (In) :: yb(neq,0:*)
        Integer, Intent (Inout)        :: iuser(*)
        Integer, Intent (In)           :: m(neq)
!       .. Executable Statements ..
        gb(1) = yb(1,0) - beta
        Return
      End Subroutine gbfun
      Subroutine gajac(ya,neq,m,nlbc,dgady,iuser,ruser)

!       .. Parameters ..
        Real (Kind=nag_wp), Parameter  :: one = 1.0_nag_wp
!       .. Scalar Arguments ..
        Integer, Intent (In)           :: neq, nlbc
!       .. Array Arguments ..
        Real (Kind=nag_wp), Intent (Inout) :: dgady(nlbc,neq,0:*), ruser(*)
        Real (Kind=nag_wp), Intent (In) :: ya(neq,0:*)
        Integer, Intent (Inout)        :: iuser(*)
        Integer, Intent (In)           :: m(neq)
!       .. Executable Statements ..
        dgady(1,1,0) = one
        Return
      End Subroutine gajac
      Subroutine gbjac(yb,neq,m,nrbc,dgbdy,iuser,ruser)

!       .. Parameters ..
        Real (Kind=nag_wp), Parameter  :: one = 1.0_nag_wp
!       .. Scalar Arguments ..
        Integer, Intent (In)           :: neq, nrbc
!       .. Array Arguments ..
        Real (Kind=nag_wp), Intent (Inout) :: dgbdy(nrbc,neq,0:*), ruser(*)
        Real (Kind=nag_wp), Intent (In) :: yb(neq,0:*)
        Integer, Intent (Inout)        :: iuser(*)
        Integer, Intent (In)           :: m(neq)
!       .. Executable Statements ..
        dgbdy(1,1,0) = one
        Return
      End Subroutine gbjac
      Subroutine guess(x,neq,m,y,dym,iuser,ruser)

!       .. Scalar Arguments ..
        Real (Kind=nag_wp), Intent (In) :: x
        Integer, Intent (In)           :: neq
!       .. Array Arguments ..
        Real (Kind=nag_wp), Intent (Out) :: dym(neq)
        Real (Kind=nag_wp), Intent (Inout) :: ruser(*), y(neq,0:*)
        Integer, Intent (Inout)        :: iuser(*)
        Integer, Intent (In)           :: m(neq)
!       .. Executable Statements ..
        y(1,0) = alpha + (beta-alpha)*x
        y(1,1) = (beta-alpha)
        dym(1) = 0.0_nag_wp
        Return
      End Subroutine guess
    End Module d02tzfe_mod
    Program d02tzfe

!     D02TZF Example Main Program

!     .. Use Statements ..
      Use nag_library, Only: d02tlf, d02tvf, d02txf, d02tyf, d02tzf, nag_wp
      Use d02tzfe_mod, Only: alpha, beta, eps, ffun, fjac, gafun, gajac,       &
                             gbfun, gbjac, guess, m, mmax, neq, nin, nlbc,     &
                             nout, nrbc
!     .. Implicit None Statement ..
      Implicit None
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: ermx
      Integer                          :: i, iermx, ifail, ijermx, j, licomm,  &
                                          lrcomm, mxmesh, ncol, nmesh
      Logical                          :: failed
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: mesh(:), rcomm(:), tol(:), y(:,:)
      Real (Kind=nag_wp)               :: ruser(1)
      Integer, Allocatable             :: icomm(:), ipmesh(:)
      Integer                          :: iuser(2)
!     .. Executable Statements ..
      Write (nout,*) 'D02TZF Example Program Results'
      Write (nout,*)
!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) ncol, nmesh, mxmesh
      Allocate (mesh(mxmesh),tol(neq),y(neq,0:mmax-1),ipmesh(mxmesh))

      Read (nin,*) alpha, beta, eps
      Read (nin,*) mesh(1:nmesh)
      Read (nin,*) ipmesh(1:nmesh)
      Read (nin,*) tol(1:neq)

!     Workspace query to get size of rcomm and icomm
      ifail = 0
      Call d02tvf(neq,m,nlbc,nrbc,ncol,tol,mxmesh,nmesh,mesh,ipmesh,ruser,0,   &
        iuser,2,ifail)
      lrcomm = iuser(1)
      licomm = iuser(2)
      Allocate (rcomm(lrcomm),icomm(licomm))

!     Initialize
      ifail = 0
      Call d02tvf(neq,m,nlbc,nrbc,ncol,tol,mxmesh,nmesh,mesh,ipmesh,rcomm,     &
        lrcomm,icomm,licomm,ifail)

      eps = 0.1_nag_wp*eps

contn: Do j = 1, 2
        Write (nout,99997) tol(1), eps

!       Solve
        ifail = -1
        Call d02tlf(ffun,fjac,gafun,gbfun,gajac,gbjac,guess,rcomm,icomm,iuser, &
          ruser,ifail)
        failed = ifail /= 0

!       Extract mesh.
        ifail = -1
        Call d02tzf(mxmesh,nmesh,mesh,ipmesh,ermx,iermx,ijermx,rcomm,icomm,    &
          ifail)

!       Print mesh statistics.
        Write (nout,99996) nmesh, ermx, iermx, ijermx

        If (failed) Then
          Exit contn
        End If

!       Print solution at every second point on final mesh.
        Write (nout,99999)
        Do i = 1, nmesh, 2
          ifail = -1
          Call d02tyf(mesh(i),y,neq,mmax,rcomm,icomm,ifail)
          Write (nout,99998) mesh(i), y(1,0), y(1,1)
        End Do

        If (j==1) Then
!         Halve final mesh for new initial mesh and set up for continuation.
          nmesh = (nmesh+1)/2
          ifail = 0
          Call d02txf(mxmesh,nmesh,mesh,ipmesh,rcomm,icomm,ifail)
!         Reduce continuation parameter.
          eps = 0.1_nag_wp*eps
        End If
      End Do contn

99999 Format (/,' Solution and derivative at every second point:',/,           &
        '      x        u          u''')
99998 Format (' ',F8.4,2F11.5)
99997 Format (/,/,' Tolerance = ',E8.1,'  EPS = ',E10.3)
99996 Format (/,' Used a mesh of ',I4,' points',/,' Maximum error = ',E10.2,   &
        '  in interval ',I4,' for component ',I4)
    End Program d02tzfe


d02udfe.f90

!   D02UDF Example Program Text
!   Mark 26 Release. NAG Copyright 2016.

    Module d02udfe_mod

!     D02UDF Example Program Module:
!            Parameters and User-defined Routines

!     .. Use Statements ..
      Use nag_library, Only: nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Accessibility Statements ..
      Private
      Public                           :: deriv, fcn
!     .. Parameters ..
      Real (Kind=nag_wp), Parameter, Public :: a = 0.0_nag_wp
      Real (Kind=nag_wp), Parameter, Public :: b = 1.5_nag_wp
      Real (Kind=nag_wp), Parameter    :: one = 1.0_nag_wp
      Integer, Parameter, Public       :: nin = 5, nout = 6
      Logical, Parameter, Public       :: reqerr = .False.
    Contains
      Function fcn(x)

!       .. Function Return Value ..
        Real (Kind=nag_wp)             :: fcn
!       .. Scalar Arguments ..
        Real (Kind=nag_wp), Intent (In) :: x
!       .. Intrinsic Procedures ..
        Intrinsic                      :: exp
!       .. Executable Statements ..
        fcn = (one+one)*x + exp(-x)
        Return
      End Function fcn
      Function deriv(x)

!       .. Function Return Value ..
        Real (Kind=nag_wp)             :: deriv
!       .. Scalar Arguments ..
        Real (Kind=nag_wp), Intent (In) :: x
!       .. Intrinsic Procedures ..
        Intrinsic                      :: exp
!       .. Executable Statements ..
        deriv = one + one - exp(-x)
        Return
      End Function deriv

    End Module d02udfe_mod
    Program d02udfe

!     D02UDF Example Main Program

!     .. Use Statements ..
      Use nag_library, Only: d02ucf, d02udf, nag_wp, x02ajf
      Use d02udfe_mod, Only: a, b, deriv, fcn, nin, nout, reqerr
!     .. Implicit None Statement ..
      Implicit None
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: scale, teneps, uxerr
      Integer                          :: i, ifail, n
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: f(:), fd(:), x(:)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: abs, int, max
!     .. Executable Statements ..
      Write (nout,*) ' D02UDF Example Program Results '
      Write (nout,*)

      Read (nin,*)
      Read (nin,*) n

      Allocate (f(n+1),fd(n+1),x(n+1))

!     Set up solution grid
      ifail = 0
      Call d02ucf(n,a,b,x,ifail)

!     Evaluate fcn on Chebyshev grid.
      Do i = 1, n + 1
        f(i) = fcn(x(i))
      End Do

!     Calculate derivative of fcn.
      ifail = 0
      Call d02udf(n,f,fd,ifail)

      scale = 2.0_nag_wp/(b-a)
      fd(1:n+1) = scale*fd(1:n+1)

!     Print function and its derivative
      Write (nout,*) ' Original Function F and numerical derivative Fx'
      Write (nout,*)
      Write (nout,99999)
      Write (nout,99998)(x(i),f(i),fd(i),i=1,n+1)

      If (reqerr) Then
        uxerr = 0.0_nag_wp
        Do i = 1, n + 1
          uxerr = max(uxerr,abs(fd(i)-deriv(x(i))))
        End Do
        teneps = 100.0_nag_wp*x02ajf()
        Write (nout,99997) 100*(int(uxerr/teneps)+1)
      End If

99999 Format (1X,T8,'X',T18,'F',T28,'Fx')
99998 Format (1X,3F10.4)
99997 Format (1X,'Fx is within a multiple ',I8,' of machine precision.')

    End Program d02udfe


d02uefe.f90

!   D02UEF Example Program Text
!   Mark 26 Release. NAG Copyright 2016.

    Module d02uefe_mod

!     D02UEF Example Program Module:
!            Parameters and User-defined Routines

!     .. Use Statements ..
      Use nag_library, Only: nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Accessibility Statements ..
      Private
      Public                           :: bndary, exact, pdedef
!     .. Parameters ..
      Real (Kind=nag_wp), Parameter    :: four = 4.0_nag_wp
      Real (Kind=nag_wp), Parameter    :: one = 1.0_nag_wp
      Real (Kind=nag_wp), Parameter    :: three = 3.0_nag_wp
      Real (Kind=nag_wp), Parameter, Public :: two = 2.0_nag_wp
      Real (Kind=nag_wp), Parameter, Public :: zero = 0.0_nag_wp
      Integer, Parameter, Public       :: m = 3, nin = 5, nout = 6
      Logical, Parameter, Public       :: reqerr = .False.
!     .. Local Scalars ..
      Real (Kind=nag_wp), Public, Save :: a, b
    Contains
      Function exact(x,q)

!       .. Function Return Value ..
        Real (Kind=nag_wp)             :: exact
!       .. Scalar Arguments ..
        Real (Kind=nag_wp), Intent (In) :: x
        Integer, Intent (In)           :: q
!       .. Intrinsic Procedures ..
        Intrinsic                      :: cos, sin
!       .. Executable Statements ..
        Select Case (q)
        Case (0)
          exact = cos(x)
        Case (1)
          exact = -sin(x)
        Case (2)
          exact = -cos(x)
        Case (3)
          exact = sin(x)
        End Select
      End Function exact
      Subroutine bndary(m,y,bmat,bvec)

!       .. Scalar Arguments ..
        Integer, Intent (In)           :: m
!       .. Array Arguments ..
        Real (Kind=nag_wp), Intent (Out) :: bmat(m,m+1), bvec(m), y(m)
!       .. Executable Statements ..
!       Boundary condition on left side of domain
        y(1:2) = a
        y(3) = b
!       Set up Dirichlet condition using exact solution
        bmat(1:m,1:m+1) = zero
        bmat(1:3,1) = one
        bmat(2:3,2) = two
        bmat(2:3,3) = three
        bvec(1) = zero
        bvec(2) = two
        bvec(3) = -two
        Return
      End Subroutine bndary
      Subroutine pdedef(m,f)

!       .. Scalar Arguments ..
        Integer, Intent (In)           :: m
!       .. Array Arguments ..
        Real (Kind=nag_wp), Intent (Out) :: f(m+1)
!       .. Executable Statements ..
        f(1) = one
        f(2) = two
        f(3) = three
        f(4) = four
        Return
      End Subroutine pdedef
    End Module d02uefe_mod
    Program d02uefe

!     D02UEF Example Main Program

!     .. Use Statements ..
      Use nag_library, Only: d02uaf, d02ubf, d02ucf, d02uef, nag_wp, x01aaf,   &
                             x02ajf
      Use d02uefe_mod, Only: a, b, bndary, exact, m, nin, nout, pdedef,        &
                             reqerr, two, zero
!     .. Implicit None Statement ..
      Implicit None
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: pi, resid, teneps
      Integer                          :: i, ifail, n, q, q1
!     .. Local Arrays ..
      Real (Kind=nag_wp)               :: bmat(m,m+1), bvec(m), f(m+1),        &
                                          uerr(m+1), y(m)
      Real (Kind=nag_wp), Allocatable  :: c(:), f0(:), u(:,:), uc(:,:), x(:)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: abs, cos, int, max, sin
!     .. Executable Statements ..
      Write (nout,*) ' D02UEF Example Program Results '
      Write (nout,*)

      Read (nin,*)
      Read (nin,*) n

      Allocate (u(n+1,m+1),f0(n+1),c(n+1),uc(n+1,m+1),x(n+1))

!     Set up domain, boundary conditions and definition
      pi = x01aaf(zero)
      a = -pi/two
      b = pi/two
      Call bndary(m,y,bmat,bvec)
      Call pdedef(m,f)

!     Set up solution grid.
      ifail = 0
      Call d02ucf(n,a,b,x,ifail)

!     Set up problem right hand sides for grid and transform.
      f0(1:n+1) = two*sin(x(1:n+1)) - two*cos(x(1:n+1))
      ifail = 0
      Call d02uaf(n,f0,c,ifail)

!     Solve in coefficient space.
      ifail = 0
      Call d02uef(n,a,b,m,c,bmat,y,bvec,f,uc,resid,ifail)
!     Evaluate solution and derivatives on Chebyshev grid.
      Do q = 0, m
        ifail = 0
        Call d02ubf(n,a,b,q,uc(1,q+1),u(1,q+1),ifail)
      End Do
!     Print solution
      Write (nout,*) ' Numerical Solution U and its first three derivatives'
      Write (nout,*)
      Write (nout,99999)
      Write (nout,99998)(x(i),u(i,1:m+1),i=1,n+1)

      If (reqerr) Then
        uerr(1:m+1) = zero
        Do i = 1, n + 1
          Do q = 0, m
            q1 = q + 1
            uerr(q1) = max(uerr(q1),abs(u(i,q1)-exact(x(i),q)))
          End Do
        End Do
        teneps = 10.0_nag_wp*x02ajf()
        Write (nout,'(//)')
        Write (nout,99997)(q,10*(int(uerr(q+1)/teneps)+1),q=0,m)
      End If

99999 Format (1X,T8,'X',T18,'U',T28,'Ux',T37,'Uxx',T47,'Uxxx')
99998 Format (1X,5F10.4)
99997 Format (1X,'Error in the order ',I1,' derivative of U is < ',I8,         &
        ' * machine precision.')

    End Program d02uefe


d02uwfe.f90

!   D02UWF Example Program Text
!   Mark 26 Release. NAG Copyright 2016.

    Module d02uwfe_mod

!     D02UWF Example Program Module:
!            Parameters and User-defined Routines

!     .. Use Statements ..
      Use nag_library, Only: nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Accessibility Statements ..
      Private
      Public                           :: exact
!     .. Parameters ..
      Real (Kind=nag_wp), Parameter, Public :: a = -1.0_nag_wp
      Real (Kind=nag_wp), Parameter, Public :: b = 1.0_nag_wp
      Real (Kind=nag_wp), Parameter, Public :: zero = 0.0_nag_wp
      Integer, Parameter, Public       :: nin = 5, nout = 6
      Logical, Parameter, Public       :: reqerr = .False.
    Contains
      Function exact(x)

!       .. Function Return Value ..
        Real (Kind=nag_wp)             :: exact
!       .. Scalar Arguments ..
        Real (Kind=nag_wp), Intent (In) :: x
!       .. Intrinsic Procedures ..
        Intrinsic                      :: cos
!       .. Executable Statements ..
        exact = x + cos(5.0_nag_wp*x)
        Return
      End Function exact
    End Module d02uwfe_mod
    Program d02uwfe

!     D02UWF Example Main Program

!     .. Use Statements ..
      Use nag_library, Only: d02ucf, d02uwf, nag_wp, x02ajf
      Use d02uwfe_mod, Only: a, b, exact, nin, nout, reqerr, zero
!     .. Implicit None Statement ..
      Implicit None
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: uerr
      Integer                          :: i, ifail, iu, n, nip
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: f(:), fip(:), x(:), xip(:)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: abs, int, max
!     .. Executable Statements ..
      Write (nout,*) ' D02UWF Example Program Results '
      Write (nout,*)

      Read (nin,*)
      Read (nin,*) n, nip

      Allocate (f(n+1),fip(nip),xip(nip),x(n+1))

!     Set up solution grid
      ifail = 0
      Call d02ucf(n,a,b,x,ifail)

!     Set up problem right hand sides for grid
      Do i = 1, n + 1
        f(i) = exact(x(i))
      End Do

!     Map to an equally spaced grid
      ifail = 0
      Call d02uwf(n,nip,x,f,xip,fip,ifail)

!     Print solution
      Write (nout,*) ' Numerical solution F'
      Write (nout,*)
      Write (nout,99999)
      Write (nout,99998)(xip(i),fip(i),i=1,nip)

      If (reqerr) Then
        uerr = zero
        Do i = 1, nip
          uerr = max(uerr,abs(fip(i)-exact(xip(i))))
        End Do
        iu = 10*(int(uerr/10.0_nag_wp/x02ajf())+1)
        Write (nout,99997) iu
      End If

99999 Format (1X,T8,'X',T19,'F')
99998 Format (1X,F10.4,1X,F10.4)
99997 Format (/,/,1X,'F  is within a multiple ',I8,' of machine precision.')
    End Program d02uwfe


d02uyfe.f90

!   D02UYF Example Program Text
!   Mark 26 Release. NAG Copyright 2016.

    Module d02uyfe_mod

!     D02UYF Example Program Module:
!            Parameters and User-defined Routines

!     .. Use Statements ..
      Use nag_library, Only: nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Accessibility Statements ..
      Private
      Public                           :: exact
!     .. Parameters ..
      Real (Kind=nag_wp), Parameter, Public :: a = -1.0_nag_wp
      Real (Kind=nag_wp), Parameter, Public :: b = 3.0_nag_wp
      Integer, Parameter, Public       :: nin = 5, nout = 6
      Logical, Parameter, Public       :: reqerr = .False., reqwgt = .False.
    Contains
      Function exact(x)

!       .. Function Return Value ..
        Real (Kind=nag_wp)             :: exact
!       .. Scalar Arguments ..
        Real (Kind=nag_wp), Intent (In) :: x
!       .. Executable Statements ..
        exact = 3.0_nag_wp*x**2
        Return
      End Function exact
    End Module d02uyfe_mod
    Program d02uyfe

!     D02UYF Example Main Program

!     .. Use Statements ..
      Use nag_library, Only: d02ucf, d02uyf, ddot, nag_wp, x02ajf
      Use d02uyfe_mod, Only: a, b, exact, nin, nout, reqerr, reqwgt
!     .. Implicit None Statement ..
      Implicit None
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: integ, scale, uerr
      Integer                          :: i, ifail, iu, n
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: f(:), w(:), x(:)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: abs, int
!     .. Executable Statements ..
      Write (nout,*) ' D02UYF Example Program Results '
      Write (nout,*)

      Read (nin,*)
      Read (nin,*) n

      Allocate (f(n+1),w(n+1),x(n+1))

!     Set up solution grid
      ifail = 0
      Call d02ucf(n,a,b,x,ifail)

!     Set up problem right hand sides for grid
      Do i = 1, n + 1
        f(i) = exact(x(i))
      End Do
      scale = 0.5_nag_wp*(b-a)

!     Solve on equally spaced grid
      ifail = 0
      Call d02uyf(n,w,ifail)
!     The NAG name equivalent of ddot is f06eaf
      integ = ddot(n+1,w,1,f,1)*scale

!     Print function values and weights if required
      If (reqwgt) Then
        Write (nout,*) ' f(x) and Integral weights'
        Write (nout,*)
        Write (nout,99999)
        Write (nout,99998)(x(i),f(i),w(i),i=1,n+1)
      End If

!     Print approximation to integral
      Write (nout,99996) a, b, integ

      If (reqerr) Then
        uerr = abs(integ-28.0_nag_wp)
        iu = 10*(int(uerr/10.0_nag_wp/x02ajf())+1)
        Write (nout,99997) iu
      End If

99999 Format (1X,T8,'X',T18,'f(X)',T28,'W')
99998 Format (1X,3F10.4)
99997 Format (/,1X,'Integral is within a multiple ',I8,                        &
        ' of machine precision.')
99996 Format (/,1X,'Integral of f(x) from ',F6.1,' to ',F6.2,' = ',F13.5,'.',  &
        /)
    End Program d02uyfe


d02uzfe.f90

!   D02UZF Example Program Text
!   Mark 26 Release. NAG Copyright 2016.

    Module d02uzfe_mod

!     D02UZF Example Program Module:
!            Parameters and User-defined Routines

!     .. Use Statements ..
      Use nag_library, Only: nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Accessibility Statements ..
      Private
      Public                           :: exact
!     .. Parameters ..
      Real (Kind=nag_wp), Parameter, Public :: one = 1.0_nag_wp
      Real (Kind=nag_wp), Parameter, Public :: two = 2.0_nag_wp
      Real (Kind=nag_wp), Parameter, Public :: zero = 0.0_nag_wp
      Integer, Parameter, Public       :: nin = 5, nout = 6
      Logical, Parameter, Public       :: reqerr = .False.
!     .. Local Scalars ..
      Real (Kind=nag_wp), Public, Save :: a, b
    Contains
      Function exact(x)

!       .. Function Return Value ..
        Real (Kind=nag_wp)             :: exact
!       .. Scalar Arguments ..
        Real (Kind=nag_wp), Intent (In) :: x
!       .. Intrinsic Procedures ..
        Intrinsic                      :: exp
!       .. Executable Statements ..
        exact = x + exp(-x)
        Return
      End Function exact
    End Module d02uzfe_mod
    Program d02uzfe

!     D02UZF Example Main Program

!     .. Use Statements ..
      Use nag_library, Only: d02uaf, d02ucf, d02uzf, nag_wp, x01aaf, x02ajf
      Use d02uzfe_mod, Only: a, b, exact, nin, nout, one, reqerr, two, zero
!     .. Implicit None Statement ..
      Implicit None
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: deven, dmap, fseries, pi, t, teneps, &
                                          uerr, xeven, xmap
      Integer                          :: i, ifail, k, m, n
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: c(:), f(:), x(:)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: abs, int, max, min, real
!     .. Executable Statements ..
      Write (nout,*) ' D02UZF Example Program Results '
      Write (nout,*)

      Read (nin,*)
      Read (nin,*) n, m

      Allocate (f(n+1),c(n+1),x(n+1))

!     Set up problem boundary conditions and definition
      pi = x01aaf(pi)
      a = -0.24_nag_wp*pi
      b = pi/two

!     Set up Chebyshev grid
      ifail = 0
      Call d02ucf(n,a,b,x,ifail)

!     Evaluate function on grid and get interpolating Chebyshev coefficients.
      Do i = 1, n + 1
        f(i) = exact(x(i))
      End Do
      ifail = 0
      Call d02uaf(n,f,c,ifail)

!     Evaluate Chebyshev series manually by evaluating each Chebyshev
!     polynomial in turn at new equispaced (m+1) grid points.
!     Chebyshev series on [-1,1] map of [a,b].
      xmap = -one
      dmap = two/real(m-1,kind=nag_wp)
      xeven = a
      deven = (b-a)/real(m-1,kind=nag_wp)

      Write (nout,99999)
      uerr = zero
      Do i = 1, m
        fseries = zero
        Do k = 0, n
          ifail = 0
          Call d02uzf(k,xmap,t,ifail)
          fseries = fseries + c(k+1)*t
        End Do
        uerr = max(uerr,abs(fseries-exact(xeven)))
        Write (nout,99998) xmap, xeven, fseries
        xmap = min(one,xmap+dmap)
        xeven = xeven + deven
      End Do

      If (reqerr) Then
        teneps = 10.0_nag_wp*x02ajf()
        Write (nout,'(//)')
        Write (nout,99997) 10*(int(uerr/teneps)+1)
      End If

99999 Format (1X,T6,'x_even',T17,'x_map',T28,'Sum')
99998 Format (1X,3F10.4)
99997 Format (1X,'Error in coefficient sum is < ',I8,' * machine precision.')

    End Program d02uzfe


d02zafe.f90

!   D02ZAF Example Program Text
!   Mark 26 Release. NAG Copyright 2016.

    Module d02zafe_mod

!     D02ZAF Example Program Module:
!            Parameters and User-defined Routines

!     .. Use Statements ..
      Use nag_library, Only: nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Accessibility Statements ..
      Private
      Public                           :: fcn, jac, monitr
!     .. Parameters ..
      Integer, Parameter, Public       :: iset = 1, itrace = 0, neq = 3,       &
                                          nin = 5, nout = 6
      Integer, Parameter, Public       :: nrw = 50 + 4*neq
      Integer, Parameter, Public       :: nwkjac = neq*(neq+1)
      Integer, Parameter, Public       :: ldysav = neq
    Contains
      Subroutine fcn(neq,t,y,f,ires)

!       .. Scalar Arguments ..
        Real (Kind=nag_wp), Intent (In) :: t
        Integer, Intent (Inout)        :: ires
        Integer, Intent (In)           :: neq
!       .. Array Arguments ..
        Real (Kind=nag_wp), Intent (Out) :: f(neq)
        Real (Kind=nag_wp), Intent (In) :: y(neq)
!       .. Executable Statements ..
        f(1) = -0.04E0_nag_wp*y(1) + 1.0E4_nag_wp*y(2)*y(3)
        f(2) = 0.04E0_nag_wp*y(1) - 1.0E4_nag_wp*y(2)*y(3) -                   &
          3.0E7_nag_wp*y(2)*y(2)
        f(3) = 3.0E7_nag_wp*y(2)*y(2)
        Return
      End Subroutine fcn
      Subroutine jac(neq,t,y,h,d,p)

!       .. Scalar Arguments ..
        Real (Kind=nag_wp), Intent (In) :: d, h, t
        Integer, Intent (In)           :: neq
!       .. Array Arguments ..
        Real (Kind=nag_wp), Intent (Inout) :: p(neq,neq)
        Real (Kind=nag_wp), Intent (In) :: y(neq)
!       .. Local Scalars ..
        Real (Kind=nag_wp)             :: hxd
!       .. Executable Statements ..
        hxd = h*d
        p(1,1) = 1.0E0_nag_wp - hxd*(-0.04E0_nag_wp)
        p(1,2) = -hxd*(1.0E4_nag_wp*y(3))
        p(1,3) = -hxd*(1.0E4_nag_wp*y(2))
        p(2,1) = -hxd*(0.04E0_nag_wp)
        p(2,2) = 1.0E0_nag_wp - hxd*(-1.0E4_nag_wp*y(3)-6.0E7_nag_wp*y(2))
        p(2,3) = -hxd*(-1.0E4_nag_wp*y(2))
!       Do not need to set P(3,1) since Jacobian preset to zero
!       P(3,1) =       - HXD*(0.0E0)
        p(3,2) = -hxd*(6.0E7_nag_wp*y(2))
        p(3,3) = 1.0E0_nag_wp - hxd*(0.0E0_nag_wp)
        Return
      End Subroutine jac
      Subroutine monitr(neq,ldysav,t,hlast,hnext,y,ydot,ysav,r,acor,imon,inln, &
        hmin,hmax,nqu)

!       .. Use Statements ..
        Use nag_library, Only: d02zaf
!       .. Scalar Arguments ..
        Real (Kind=nag_wp), Intent (In) :: hlast, t
        Real (Kind=nag_wp), Intent (Inout) :: hmax, hmin, hnext
        Integer, Intent (Inout)        :: imon
        Integer, Intent (Out)          :: inln
        Integer, Intent (In)           :: ldysav, neq, nqu
!       .. Array Arguments ..
        Real (Kind=nag_wp), Intent (In) :: acor(neq,2), r(neq), ydot(neq),     &
                                          ysav(ldysav,*)
        Real (Kind=nag_wp), Intent (Inout) :: y(neq)
!       .. Local Scalars ..
        Real (Kind=nag_wp)             :: errloc
        Integer                        :: i, ifail
!       .. Executable Statements ..
        inln = 3
        If (imon==1) Then

          ifail = -1
          errloc = d02zaf(neq,acor(1,2),acor(1,1),ifail)

          If (ifail/=0) Then
            imon = -2
          Else If (errloc>5.0E0_nag_wp) Then
            Write (nout,99999) t, (y(i),i=1,neq), errloc
          Else
            Write (nout,99998) t, (y(i),i=1,neq)
          End If
        End If

        Return

99999   Format (1X,F10.6,3(F13.7,2X),/,1X,' ** WARNING scaled local error = ', &
          F13.5)
99998   Format (1X,F10.6,3(F13.7,2X))
      End Subroutine monitr
    End Module d02zafe_mod
    Program d02zafe

!     D02ZAF Example Main Program

!     .. Use Statements ..
      Use nag_library, Only: d02nbf, d02nsf, d02nvf, d02nyf, nag_wp, x04abf
      Use d02zafe_mod, Only: fcn, iset, itrace, jac, ldysav, monitr, neq, nin, &
                             nout, nrw, nwkjac
!     .. Implicit None Statement ..
      Implicit None
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: h, h0, hmax, hmin, hu, t, tcrit,     &
                                          tcur, tolsf, tout
      Integer                          :: i, ifail, imxer, itask, itol,        &
                                          maxord, maxstp, mxhnil, niter, nje,  &
                                          nq, nqu, nre, nst, outchn, sdysav
      Logical                          :: petzld
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: atol(:), rtol(:), rwork(:),          &
                                          wkjac(:), y(:), ydot(:), ysav(:,:)
      Real (Kind=nag_wp)               :: con(6)
      Integer                          :: inform(23)
      Logical, Allocatable             :: algequ(:)
!     .. Executable Statements ..
      Write (nout,*) 'D02ZAF Example Program Results'
!     Skip heading in data file
      Read (nin,*)
!     neq: number of differential equations
      Read (nin,*) maxord, maxstp, mxhnil
      sdysav = maxord + 1
      Allocate (atol(neq),rtol(neq),rwork(nrw),wkjac(nwkjac),y(neq),ydot(neq), &
        ysav(ldysav,sdysav),algequ(neq))
      outchn = nout
      Call x04abf(iset,outchn)

!     Set algorithmic and problem parameters

      Read (nin,*) hmin, hmax, h0, t, tout
      Read (nin,*) petzld

!     Initialization

!     Integrate to tout without passing tout.
      tcrit = tout
      itask = 4

!     Use default values for the array con.
      con(1:6) = 0.0_nag_wp

!     Use BDF formulae with modified Newton method.
!     Use averaged L2 norm for local error control.
      ifail = 0
      Call d02nvf(neq,sdysav,maxord,'Newton',petzld,con,tcrit,hmin,hmax,h0,    &
        maxstp,mxhnil,'Average-L2',rwork,ifail)

!     Setup for using analytic Jacobian
      ifail = 0
      Call d02nsf(neq,neq,'Analytical',nwkjac,rwork,ifail)

      Write (nout,*)
      Write (nout,*) '  Analytic Jacobian'
      Write (nout,*)

!     Set tolerances.
      Read (nin,*) itol
      Read (nin,*) rtol(1), atol(1)

!     Initial values for Y.
      Read (nin,*) y(1:neq)

      Write (nout,*) '    X          Y(1)           Y(2)           Y(3)'
      Write (nout,99999) t, (y(i),i=1,neq)

!     Solve the problem using MONITR to output intermediate results.
      ifail = -1
      Call d02nbf(neq,ldysav,t,tout,y,ydot,rwork,rtol,atol,itol,inform,fcn,    &
        ysav,sdysav,jac,wkjac,nwkjac,monitr,itask,itrace,ifail)

      If (ifail==0) Then

!       Get integration statistics.
        Call d02nyf(neq,neq,hu,h,tcur,tolsf,rwork,nst,nre,nje,nqu,nq,niter,    &
          imxer,algequ,inform,ifail)

        Write (nout,*)
        Write (nout,99997) hu, h, tcur
        Write (nout,99996) nst, nre, nje
        Write (nout,99995) nqu, nq, niter
        Write (nout,99994) ' Max Err Comp = ', imxer
        Write (nout,*)
      Else
        Write (nout,*)
        Write (nout,99998) 'Exit D02NBF with IFAIL = ', ifail, '  and T = ', t
      End If

99999 Format (1X,F10.6,3(F13.7,2X))
99998 Format (1X,A,I2,A,E12.5)
99997 Format (1X,' HUSED = ',E12.5,'  HNEXT = ',E12.5,'  TCUR = ',E12.5)
99996 Format (1X,' NST = ',I6,'    NRE = ',I6,'    NJE = ',I6)
99995 Format (1X,' NQU = ',I6,'    NQ  = ',I6,'  NITER = ',I6)
99994 Format (1X,A,I4)
    End Program d02zafe


d03eafe.f90

    Program d03eafe

!     D03EAF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: d03eaf, nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: alpha, alpha0, alpsav, p, q
      Integer                          :: i, ifail, j, ldc, m, n, n1, n1p1,    &
                                          np1, np4, npts
      Logical                          :: dorm, ext, stage1
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: c(:,:), phi(:), phid(:), x(:), y(:)
      Integer, Allocatable             :: icint(:)
!     .. Executable Statements ..
      Write (nout,*) 'D03EAF Example Program Results'
!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) m, n
      n1 = 2*(n+m) - 2
      n1p1 = n1 + 1
      np1 = n + 1
      np4 = n + 4
      ldc = n + 1
      Allocate (c(ldc,np4),phi(n),phid(n),x(n1p1),y(n1p1),icint(np1))
      Read (nin,*) ext, dorm
      If (.Not. dorm) Then
        Read (nin,*) alpha0
        alpha = alpha0
      End If
      Read (nin,*)(x(i),y(i),i=1,n1+1)
      Read (nin,*)(phi(i),phid(i),i=1,n)

      stage1 = .True.

!     ifail: behaviour on error exit
!            =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
      ifail = 0
      Call d03eaf(stage1,ext,dorm,n,p,q,x,y,n1p1,phi,phid,alpha,c,ldc,np4,     &
        icint,np1,ifail)

      alpsav = alpha
      Write (nout,*)
      If (.Not. dorm) Then
        If (ext) Then
          Write (nout,*) 'Exterior Neumann problem'
          Write (nout,*)
          Write (nout,99998) 'C=', alpha0
        Else
          Write (nout,*) 'Interior Neumann problem'
          Write (nout,*)
          Write (nout,99999) 'Total integral =', alpha0
        End If
      Else If (ext) Then
        Write (nout,*)
        Write (nout,*) 'Exterior problem'
        Write (nout,*)
        Write (nout,99999) 'Computed C =', alpsav
      End If
      j = 2
      Write (nout,*)
      Write (nout,*) 'Nodes'
      Write (nout,99996) 'X', 'Y', 'PHI', 'PHID'
      Do i = 1, n
        If (x(j)==x(j-1) .And. y(j)==y(j-1)) Then
          j = j + 2
        End If
        Write (nout,99997) x(j), y(j), phi(i), phid(i)
        j = j + 2
      End Do
      stage1 = .False.
      Write (nout,*)
      Write (nout,*) 'Selected points'
      Write (nout,*) '           X              Y              PHI'
      Read (nin,*) npts
      Do i = 1, npts
        Read (nin,*) p, q
        alpha = alpsav

        ifail = 0
        Call d03eaf(stage1,ext,dorm,n,p,q,x,y,n1p1,phi,phid,alpha,c,ldc,np4,   &
          icint,np1,ifail)

        Write (nout,99997) p, q, alpha
      End Do

99999 Format (1X,A,F15.2)
99998 Format (1X,A,E15.4)
99997 Format (1X,4F15.2)
99996 Format (1X,A12,A15,A17,A16)
    End Program d03eafe


d03ebfe.f90

    Program d03ebfe

!     D03EBF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: d03ebf, nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Real (Kind=nag_wp), Parameter    :: one = 1.0_nag_wp
      Real (Kind=nag_wp), Parameter    :: two = 2.0_nag_wp
      Real (Kind=nag_wp), Parameter    :: zero = 0.0_nag_wp
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: aparam, conchn, conres
      Integer                          :: i, ifail, itcoun, itmax, itused,     &
                                          ixn, iyn, j, lda, n1, n2, ndir
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: a(:,:), b(:,:), c(:,:), chngs(:),    &
                                          d(:,:), e(:,:), q(:,:), resids(:),   &
                                          t(:,:), wrksp1(:,:), wrksp2(:,:),    &
                                          wrksp3(:,:), x(:), y(:)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: cos, exp
!     .. Executable Statements ..
      Write (nout,*) 'D03EBF Example Program Results'
      Write (nout,*)
!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) n1, n2, itmax
      lda = n1
      Allocate (a(lda,n2),b(lda,n2),c(lda,n2),chngs(itmax),d(lda,n2),          &
        e(lda,n2),q(lda,n2),resids(itmax),t(lda,n2),wrksp1(lda,n2),            &
        wrksp2(lda,n2),wrksp3(lda,n2),x(n1),y(n2))

      Read (nin,*) x(1:n1)
      Read (nin,*) y(1:n2)
      Read (nin,*) conres, conchn
      Read (nin,*) ndir
      aparam = one
      itcoun = 0
!     Set up difference equation coefficients, source terms and
!     initial conditions.
      a(1:n1,1:n2) = zero
      b(1:n1,1:n2) = zero
      c(1:n1,1:n2) = zero
      d(1:n1,1:n2) = zero
      e(1:n1,1:n2) = zero
      q(1:n1,1:n2) = zero
      t(1:n1,1:n2) = zero
!     Non-zero specification for internal nodes
      Do j = 2, n2 - 1
        Do i = 2, n1 - 1
          a(i,j) = two/((y(j)-y(j-1))*(y(j+1)-y(j-1)))
          e(i,j) = two/((y(j+1)-y(j))*(y(j+1)-y(j-1)))
          b(i,j) = two/((x(i)-x(i-1))*(x(i+1)-x(i-1)))
          d(i,j) = two/((x(i+1)-x(i))*(x(i+1)-x(i-1)))
          c(i,j) = -a(i,j) - b(i,j) - d(i,j) - e(i,j)
        End Do
      End Do
!     Non-zero specification for boundary nodes
      q(1:n1,1) = exp((x(1:n1)+one)/y(n2))*cos(y(1)/y(n2))
      q(1:n1,n2) = exp((x(1:n1)+one)/y(n2))*cos(y(n2)/y(n2))
      q(1,1:n2) = exp((x(1)+one)/y(n2))*cos(y(1:n2)/y(n2))
      q(n1,1:n2) = exp((x(n1)+one)/y(n2))*cos(y(1:n2)/y(n2))

!     ifail: behaviour on error exit
!            =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
      ifail = 0
      Call d03ebf(n1,n2,lda,a,b,c,d,e,q,t,aparam,itmax,itcoun,itused,ndir,ixn, &
        iyn,conres,conchn,resids,chngs,wrksp1,wrksp2,wrksp3,ifail)

      Write (nout,*) 'Iteration      Maximum        Maximum'
      Write (nout,*) ' number        residual        change'
      Write (nout,99999)(i,resids(i),chngs(i),i=1,itused)
      Write (nout,*)
      Write (nout,*) 'Table of calculated function values'
      Write (nout,*)
      Write (nout,99998)(i,i=1,6)
      Write (nout,*) ' J'
      Do j = 1, n2
        Write (nout,99997) j, (t(i,j),i=1,n1)
      End Do

99999 Format (2X,I2,10X,E11.4,4X,E11.4)
99998 Format (1X,' I',1X,6(I4,7X))
99997 Format (1X,I2,1X,6(F9.3,2X))
    End Program d03ebfe


d03ecfe.f90

    Program d03ecfe

!     D03ECF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: d03ecf, nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Real (Kind=nag_wp), Parameter    :: one = 1.0_nag_wp
      Real (Kind=nag_wp), Parameter    :: two = 2.0_nag_wp
      Real (Kind=nag_wp), Parameter    :: zero = 0.0_nag_wp
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: aparam, conchn, conres, root2, x1,   &
                                          x2, y1, y2, yy, z1, z2
      Integer                          :: i, ifail, itcoun, itmax, itused,     &
                                          ixn, iyn, izn, j, k, lda, n1, n2,    &
                                          n3, ndir, sda
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: a(:,:,:), b(:,:,:), c(:,:,:),        &
                                          chngs(:), d(:,:,:), e(:,:,:),        &
                                          f(:,:,:), g(:,:,:), q(:,:,:),        &
                                          resids(:), t(:,:,:), wrksp1(:,:,:),  &
                                          wrksp2(:,:,:), wrksp3(:,:,:),        &
                                          wrksp4(:,:,:), x(:), y(:), z(:)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: cos, exp, sqrt
!     .. Executable Statements ..
      Write (nout,*) 'D03ECF Example Program Results'
      Write (nout,*)
!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) n1, n2, n3, itmax
      lda = n1
      sda = n2
      Allocate (a(lda,sda,n3),b(lda,sda,n3),c(lda,sda,n3),chngs(itmax),        &
        d(lda,sda,n3),e(lda,sda,n3),f(lda,sda,n3),g(lda,sda,n3),q(lda,sda,n3), &
        resids(itmax),t(lda,sda,n3),wrksp1(lda,sda,n3),wrksp2(lda,sda,n3),     &
        wrksp3(lda,sda,n3),wrksp4(lda,sda,n3),x(n1),y(n2),z(n3))

      Read (nin,*) x(1:n1)
      Read (nin,*) y(1:n2)
      Read (nin,*) z(1:n3)
      Read (nin,*) conres, conchn
      Read (nin,*) ndir
      root2 = sqrt(two)
      aparam = one
      itcoun = 0
!     Set up difference equation coefficients, source terms and
!     initial approximation.
      a(1:n1,1:n2,1:n3) = zero
      b(1:n1,1:n2,1:n3) = zero
      c(1:n1,1:n2,1:n3) = zero
      d(1:n1,1:n2,1:n3) = zero
      e(1:n1,1:n2,1:n3) = zero
      f(1:n1,1:n2,1:n3) = zero
      g(1:n1,1:n2,1:n3) = zero
      q(1:n1,1:n2,1:n3) = zero
      t(1:n1,1:n2,1:n3) = zero
!     Non-zero Specification for internal nodes
      Do k = 2, n3 - 1
        Do j = 2, n2 - 1
          Do i = 2, n1 - 1
            a(i,j,k) = two/((z(k)-z(k-1))*(z(k+1)-z(k-1)))
            g(i,j,k) = two/((z(k+1)-z(k))*(z(k+1)-z(k-1)))
            b(i,j,k) = two/((y(j)-y(j-1))*(y(j+1)-y(j-1)))
            f(i,j,k) = two/((y(j+1)-y(j))*(y(j+1)-y(j-1)))
            c(i,j,k) = two/((x(i)-x(i-1))*(x(i+1)-x(i-1)))
            e(i,j,k) = two/((x(i+1)-x(i))*(x(i+1)-x(i-1)))
            d(i,j,k) = -a(i,j,k) - b(i,j,k) - c(i,j,k) - e(i,j,k) - f(i,j,k) - &
              g(i,j,k)
          End Do
        End Do
      End Do
!     Non-zero specification for boundary nodes
      yy = one/y(n2)
      x1 = (x(1)+one)*yy
      x2 = (x(n1)+one)*yy
      Do j = 1, n2
        y1 = root2*y(j)*yy
        q(1,j,1:n3) = exp(x1)*cos(y1)*exp((-z(1:n3)-one)*yy)
        q(n1,j,1:n3) = exp(x2)*cos(y1)*exp((-z(1:n3)-one)*yy)
      End Do
      y1 = root2*y(1)*yy
      y2 = root2*y(n2)*yy
      Do i = 1, n1
        x1 = (x(i)+one)*yy
        q(i,1,1:n3) = exp(x1)*cos(y1)*exp((-z(1:n3)-one)*yy)
        q(i,n2,1:n3) = exp(x1)*cos(y2)*exp((-z(1:n3)-one)*yy)
      End Do
      z1 = (-z(1)-one)*yy
      z2 = (-z(n3)-one)*yy
      Do i = 1, n1
        x1 = (x(i)+one)*yy
        q(i,1:n2,1) = exp(x1)*cos(root2*y(1:n2)*yy)*exp(z1)
        q(i,1:n2,n3) = exp(x1)*cos(root2*y(1:n2)*yy)*exp(z2)
      End Do

!     ifail: behaviour on error exit
!            =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
      ifail = 0
      Call d03ecf(n1,n2,n3,lda,sda,a,b,c,d,e,f,g,q,t,aparam,itmax,itcoun,      &
        itused,ndir,ixn,iyn,izn,conres,conchn,resids,chngs,wrksp1,wrksp2,      &
        wrksp3,wrksp4,ifail)

      Write (nout,*) 'Iteration      Maximum        Maximum'
      Write (nout,*) ' number        residual        change'
      If (itused/=0) Then
        Write (nout,99999)(i,resids(i),chngs(i),i=1,itused)
      End If
      Write (nout,*)
      Write (nout,*) 'Table of calculated function values'
      Write (nout,*)
      Write (nout,99998)
      Do k = 1, n3
        Do j = 1, n2
          Write (nout,99997) k, j, (i,t(i,j,k),i=1,n1)
        End Do
      End Do

99999 Format (2X,I3,9X,E11.4,4X,E11.4)
99998 Format (1X,'K  J  ',4(' (I      T   )'))
99997 Format (1X,I1,2X,I1,1X,4(1X,I3,2X,F8.3))
    End Program d03ecfe


d03edfe.f90

    Program d03edfe

!     D03EDF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: d03edf, nag_wp, x04abf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Real (Kind=nag_wp), Parameter    :: four = 4.0_nag_wp
      Real (Kind=nag_wp), Parameter    :: half = 0.5_nag_wp
      Real (Kind=nag_wp), Parameter    :: one = 1.0_nag_wp
      Real (Kind=nag_wp), Parameter    :: zero = 0.0_nag_wp
      Integer, Parameter               :: iset = 1, nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: acc, alpha, hx, hy
      Integer                          :: i, ifail, iout, ix, iy1, iy2, j, k,  &
                                          lda, levels, maxit, ngx, ngy, numit, &
                                          outchn
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: a(:,:), rhs(:), u(:), ub(:), us(:)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: real
!     .. Executable Statements ..
      Write (nout,*) 'D03EDF Example Program Results'
!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) levels
      ngx = 2**levels + 1
      ngy = ngx
      lda = 4*(ngx+1)*(ngy+1)/3
      Allocate (a(lda,7),rhs(lda),u(lda),ub(ngx*ngy),us(lda))

      outchn = nout
      Write (nout,*)
      Read (nin,*) alpha, acc
      Read (nin,*) maxit
      Call x04abf(iset,outchn)
!     ** Set iout > 2 to obtain intermediate output **
      iout = 0
      hx = one/real(ngx+1,kind=nag_wp)
      hy = one/real(ngy+1,kind=nag_wp)

!     Set up operator, right-hand side and initial guess for
!     step-lengths HX and HY
      a(1:ngx*ngy,1) = one - half*alpha
      a(1:ngx*ngy,2) = half*alpha
      a(1:ngx*ngy,3) = one - half*alpha
      a(1:ngx*ngy,4) = -four + alpha
      a(1:ngx*ngy,5) = one - half*alpha
      a(1:ngx*ngy,6) = half*alpha
      a(1:ngx*ngy,7) = one - half*alpha
      rhs(1:ngx*ngy) = -four*hx*hy
      ub(1:ngx*ngy) = zero

!     Correction for the boundary conditions
!         Horizontal boundaries --
!            Boundary condition on Y=0 -- U=0
      a(2:ngx-1,1:2) = zero
!     Boundary condition on Y=1 -- U=0
      ix = (ngy-1)*ngx
      a(ix+1:ix+ngx-1,6:7) = zero

!     Vertical boundaries --
      iy1 = 1
      iy2 = ngx
      Do j = 2, ngy - 1
!       Boundary condition on X=0 -- U=0
        iy1 = iy1 + ngx
        a(iy1,3) = zero
        a(iy1,6) = zero
!       Boundary condition on X=1 -- U=1
        iy2 = iy2 + ngx
        rhs(iy2) = rhs(iy2) - a(iy2,5) - a(iy2,2)
        a(iy2,2) = zero
        a(iy2,5) = zero
      End Do

!     Now the four corners --
!     Bottom left corner
      a(1,1:3) = zero
      a(1,6) = zero
!     Top left corner
      a(ix+1,3) = zero
      a(ix+1,6:7) = zero
!     Bottom right corner
!     Use average value at discontinuity ( = 0.5 )
      k = ngx
      rhs(k) = rhs(k) - a(k,2)*half - a(k,5)
      a(k,1:2) = zero
      a(k,5) = zero
!     Top right corner
      k = ngx*ngy
      rhs(k) = rhs(k) - a(k,2) - a(k,5)
      a(k,2) = zero
      a(k,5:7) = zero

!     Solve the equations
!     ifail: behaviour on error exit
!             =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
      ifail = 0
      Call d03edf(ngx,ngy,lda,a,rhs,ub,maxit,acc,us,u,iout,numit,ifail)

      Write (nout,99999) ngx, ngy, acc, maxit
      Write (nout,*)
      Write (nout,99998) 'Residual norm =', us(1)
      Write (nout,99997) 'Number of iterations =', numit
      Write (nout,*)
      Write (nout,*) 'Solution'
      Write (nout,*)
      Write (nout,99996) '  I/J', (i,i=1,ngx)
      Do j = 1, ngy
        Write (nout,99995) j, (u(i+(j-1)*ngx),i=1,ngx)
      End Do

99999 Format (1X,'NGX = ',I3,'  NGY = ',I3,'  ACC =',1P,E10.2,'  MAXIT',' = ', &
        I3)
99998 Format (1X,A,1P,E12.2)
99997 Format (1X,A,I5)
99996 Format (1X,A,10I7,:)
99995 Format (1X,I3,2X,10F7.3,:)
    End Program d03edfe


d03eefe.f90

!   D03EEF Example Program Text
!   Mark 26 Release. NAG Copyright 2016.

    Module d03eefe_mod

!     D03EEF Example Program Module:
!            Parameters and User-defined Routines

!     .. Use Statements ..
      Use nag_library, Only: nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Accessibility Statements ..
      Private
      Public                           :: bndy, fexact, pdef
!     .. Parameters ..
      Real (Kind=nag_wp), Parameter    :: one = 1.0_nag_wp
      Real (Kind=nag_wp), Parameter, Public :: zero = 0.0_nag_wp
      Integer, Parameter, Public       :: nin = 5, nout = 6
    Contains
      Subroutine pdef(x,y,alpha,beta,gamma,delta,epslon,phi,psi)

!       .. Scalar Arguments ..
        Real (Kind=nag_wp), Intent (Out) :: alpha, beta, delta, epslon, gamma, &
                                          phi, psi
        Real (Kind=nag_wp), Intent (In) :: x, y
!       .. Intrinsic Procedures ..
        Intrinsic                      :: cos, sin
!       .. Executable Statements ..
        alpha = one
        beta = zero
        gamma = one
        delta = 50.0_nag_wp
        epslon = 50.0_nag_wp
        phi = zero

        psi = sin(x)*((-alpha-gamma+phi)*sin(y)+epslon*cos(y)) +               &
          cos(x)*(delta*sin(y)+beta*cos(y))

        Return
      End Subroutine pdef
      Subroutine bndy(x,y,a,b,c,ibnd)

!       .. Parameters ..
        Integer, Parameter             :: bottom = 0, left = 3, right = 1,     &
                                          top = 2
!       .. Scalar Arguments ..
        Real (Kind=nag_wp), Intent (Out) :: a, b, c
        Real (Kind=nag_wp), Intent (In) :: x, y
        Integer, Intent (In)           :: ibnd
!       .. Intrinsic Procedures ..
        Intrinsic                      :: sin
!       .. Executable Statements ..
        If (ibnd==top .Or. ibnd==right) Then

!         Solution prescribed

          a = one
          b = zero
          c = sin(x)*sin(y)
        Else If (ibnd==bottom) Then

!         Derivative prescribed

          a = zero
          b = one
          c = -sin(x)
        Else If (ibnd==left) Then

!         Derivative prescribed

          a = zero
          b = one
          c = -sin(y)
        End If

        Return
      End Subroutine bndy
      Function fexact(x,y)

!       .. Function Return Value ..
        Real (Kind=nag_wp)             :: fexact
!       .. Scalar Arguments ..
        Real (Kind=nag_wp), Intent (In) :: x, y
!       .. Intrinsic Procedures ..
        Intrinsic                      :: sin
!       .. Executable Statements ..
        fexact = sin(x)*sin(y)
        Return
      End Function fexact
    End Module d03eefe_mod

    Program d03eefe

!     D03EEF Example Main Program

!     .. Use Statements ..
      Use nag_library, Only: d03edf, d03eef, nag_wp
      Use d03eefe_mod, Only: bndy, fexact, nin, nout, pdef, zero
!     .. Implicit None Statement ..
      Implicit None
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: acc, hx, hy, rmserr, xmax, xmin, xx, &
                                          ymax, ymin, yy
      Integer                          :: i, icase, ifail, iout, ix, j, lda,   &
                                          levels, maxit, ngx, ngxy, ngy, numit
      Character (7)                    :: scheme
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: a(:,:), rhs(:), u(:), ub(:), us(:),  &
                                          x(:), y(:)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: real, sqrt
!     .. Executable Statements ..
      Write (nout,*) 'D03EEF Example Program Results'
      Write (nout,*)
      Flush (nout)

!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) levels
      ngx = 2**levels + 1
      ngy = ngx
      lda = 4*(ngx+1)*(ngy+1)/3
      ngxy = ngx*ngy
      Allocate (a(lda,7),rhs(lda),u(lda),ub(ngxy),us(lda),x(ngxy),y(ngxy))
      Read (nin,*) xmin, xmax
      Read (nin,*) ymin, ymax
      hx = (xmax-xmin)/real(ngx-1,kind=nag_wp)
      Do i = 1, ngx
        xx = xmin + real(i-1,kind=nag_wp)*hx
        x(i:ngxy:ngx) = xx
      End Do
      hy = (ymax-ymin)/real(ngy-1,kind=nag_wp)
      Do j = 1, ngy
        yy = ymin + real(j-1,kind=nag_wp)*hy
        y((j-1)*ngx+1:j*ngx) = yy
      End Do
!     ** set iout > 2 to obtain intermediate output from D03EDF **
      iout = 0
      Read (nin,*) acc
      Read (nin,*) maxit

cases: Do icase = 1, 2

        Select Case (icase)
        Case (1)
!         Central differences
          scheme = 'Central'
        Case (2)
!         Upwind differences
          scheme = 'Upwind'
        End Select
!       Discretize the equations
!       ifail: behaviour on error exit
!              =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
        ifail = -1
        Call d03eef(xmin,xmax,ymin,ymax,pdef,bndy,ngx,ngy,lda,a,rhs,scheme,    &
          ifail)

        If (ifail<0) Then
          Write (nout,99995) ifail
          Exit cases
        End If

!       Set the initial guess to zero
        ub(1:ngxy) = zero

!       Solve the equations
        ifail = 0
        Call d03edf(ngx,ngy,lda,a,rhs,ub,maxit,acc,us,u,iout,numit,ifail)

!       Print out the solution
        Write (nout,*)
        Write (nout,*) 'Exact solution above computed solution'
        Write (nout,*)
        Write (nout,99998) '  I/J', (i,i=1,ngx)
        rmserr = zero
        Do j = ngy, 1, -1
          ix = (j-1)*ngx
          Write (nout,*)
          Write (nout,99999) j, (fexact(x(ix+i),y(ix+i)),i=1,ngx)
          Write (nout,99999) j, u(ix+1:ix+ngx)
          Do i = 1, ngx
            rmserr = rmserr + (fexact(x(ix+i),y(ix+i))-u(ix+i))**2
          End Do
        End Do
        rmserr = sqrt(rmserr/real(ngxy,kind=nag_wp))
        Write (nout,*)
        Write (nout,99997) 'Number of Iterations = ', numit
        Write (nout,99996) 'RMS Error = ', rmserr
      End Do cases

99999 Format (1X,I3,2X,10F7.3,:,/,(6X,10F7.3))
99998 Format (1X,A,10I7,:,/,(6X,10I7))
99997 Format (1X,A,I3)
99996 Format (1X,A,1P,E10.2)
99995 Format (1X,' ** D03EEF returned with IFAIL = ',I5)
    End Program d03eefe


d03fafe.f90

    Program d03fafe

!     D03FAF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: d03faf, nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: dx, dy, dz, error, lambda, pertrb,   &
                                          t, xf, xs, yf, ys, yy, zf, zs, zz
      Integer                          :: i, ifail, j, k, l, lbdcnd, ldf,      &
                                          ldf2, lwrk, m, mbdcnd, n, nbdcnd
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: bdxf(:,:), bdxs(:,:), bdyf(:,:),     &
                                          bdys(:,:), bdzf(:,:), bdzs(:,:),     &
                                          f(:,:,:), x(:), y(:), z(:)
      Real (Kind=nag_wp)               :: w(0)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: abs, cos, real, sin
!     .. Executable Statements ..
      Write (nout,*) 'D03FAF Example Program Results'
!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) l, m, n
      ldf = l + 1
      ldf2 = m + 1
      lwrk = 0
      Allocate (bdxf(ldf2,n+1),bdxs(ldf2,n+1),bdyf(ldf,n+1),bdys(ldf,n+1),     &
        bdzf(ldf,m+1),bdzs(ldf,m+1),f(ldf,ldf2,n+1),x(l+1),y(m+1),z(n+1))
      Read (nin,*) lambda
      Read (nin,*) xs, xf
      Read (nin,*) ys, yf
      Read (nin,*) zs, zf
      Read (nin,*) lbdcnd, mbdcnd, nbdcnd

!     Define the grid points for later use.

      dx = (xf-xs)/real(l,kind=nag_wp)
      Do i = 1, l + 1
        x(i) = xs + real(i-1,kind=nag_wp)*dx
      End Do
      dy = (yf-ys)/real(m,kind=nag_wp)
      Do j = 1, m + 1
        y(j) = ys + real(j-1,kind=nag_wp)*dy
      End Do
      dz = (zf-zs)/real(n,kind=nag_wp)
      Do k = 1, n + 1
        z(k) = zs + real(k-1,kind=nag_wp)*dz
      End Do

!     Define the array of derivative boundary values.

      Do j = 1, m + 1
        yy = sin(y(j))
        bdzf(1:l+1,j) = -yy*x(1:l+1)**4
      End Do

!     Note that for this example all other boundary arrays are
!     dummy variables.

!     We define the function boundary values in the F array.

      f(1,1:m+1,1:n+1) = 0.0_nag_wp
      Do k = 1, n + 1
        zz = cos(z(k))
        Do j = 1, m + 1
          f(l+1,j,k) = zz*sin(y(j))
        End Do
      End Do
      f(1:l+1,1:m+1,1) = -bdzf(1:l+1,1:m+1)

!     Define the values of the right hand side of the Helmholtz
!     equation.

      Do k = 2, n + 1
        zz = 4.0_nag_wp*cos(z(k))
        Do j = 1, m + 1
          yy = sin(y(j))*zz
          Do i = 2, l
            f(i,j,k) = yy*x(i)**2*(3.0_nag_wp-x(i)**2)
          End Do
        End Do
      End Do

!     Call D03FAF to generate and solve the finite difference equation.
!     ifail: behaviour on error exit
!            =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
      ifail = 0
      Call d03faf(xs,xf,l,lbdcnd,bdxs,bdxf,ys,yf,m,mbdcnd,bdys,bdyf,zs,zf,n,   &
        nbdcnd,bdzs,bdzf,lambda,ldf,ldf2,f,pertrb,w,lwrk,ifail)

!     Compute discretization error.  The exact solution to the
!     problem is

!     U(X,Y,Z) = X**4*SIN(Y)*COS(Z)

      error = 0.0_nag_wp
      Do k = 1, n + 1
        zz = cos(z(k))
        Do j = 1, m + 1
          yy = sin(y(j))*zz
          Do i = 1, l + 1
            t = abs(f(i,j,k)-yy*x(i)**4)
            If (t>error) Then
              error = t
            End If
          End Do
        End Do
      End Do
      Write (nout,*)
      Write (nout,99999) error

99999 Format (1X,'Maximum component of discretization error =',1P,E13.6)
    End Program d03fafe


d03mafe.f90

!   D03MAF Example Program Text
!   Mark 26 Release. NAG Copyright 2016.

    Module d03mafe_mod

!     D03MAF Example Program Module:
!            Parameters and User-defined Routines

!     .. Use Statements ..
      Use nag_library, Only: nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Accessibility Statements ..
      Private
      Public                           :: isin
!     .. Parameters ..
      Real (Kind=nag_wp), Parameter    :: rad = 6.0_nag_wp
      Real (Kind=nag_wp), Parameter    :: xmid = 7.0_nag_wp
      Real (Kind=nag_wp), Parameter    :: ymid = 7.0_nag_wp
      Integer, Parameter, Public       :: nin = 5, nout = 6
    Contains
      Function isin(x,y)
!       Circular domain

!       .. Function Return Value ..
        Integer                        :: isin
!       .. Scalar Arguments ..
        Real (Kind=nag_wp), Intent (In) :: x, y
!       .. Executable Statements ..
        If ((x-xmid)**2+(y-ymid)**2<=rad**2) Then
          isin = 1
        Else
          isin = 0
        End If
        Return
      End Function isin
    End Module d03mafe_mod

    Program d03mafe

!     D03MAF Example Main Program

!     .. Use Statements ..
      Use nag_library, Only: d03maf, nag_wp
      Use d03mafe_mod, Only: isin, nin, nout
!     .. Implicit None Statement ..
      Implicit None
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: h
      Integer                          :: i, ifail, m, n, nb, npts, sddist,    &
                                          sdindx
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: dist(:,:), places(:,:)
      Integer, Allocatable             :: indx(:,:)
!     .. Executable Statements ..
      Write (nout,*) 'D03MAF Example Program Results'
      Write (nout,*)
!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) sddist, sdindx
      Allocate (dist(4,sddist),places(2,sdindx),indx(4,sdindx))

      Read (nin,*) h
      Read (nin,*) m, n, nb

!     ifail: behaviour on error exit
!            =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
      ifail = 0
      Call d03maf(h,m,n,nb,npts,places,indx,sdindx,isin,dist,sddist,ifail)

      Write (nout,*) '  I    X(I)      Y(I)'
      Do i = 1, npts
        Write (nout,99999) i, places(1,i), places(2,i)
      End Do
      Write (nout,*)
      Write (nout,*) 'INDX'
      Write (nout,99998)(indx(1:4,i),i=1,npts)

99999 Format (1X,I3,2F10.6)
99998 Format (1X,4I5)
    End Program d03mafe


d03ncfe.f90

!   D03NCF Example Program Text
!   Mark 26 Release. NAG Copyright 2016.

    Module d03ncfe_mod

!     D03NCF Example Program Module:
!            Parameters and User-defined Routines

!     .. Use Statements ..
      Use nag_library, Only: nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Accessibility Statements ..
      Private
      Public                           :: print_greek
!     .. Parameters ..
      Integer, Parameter, Public       :: nin = 5, nout = 6
    Contains
      Subroutine print_greek(ns,ntkeep,nt,s,t,grname,greek)

!       .. Scalar Arguments ..
        Integer, Intent (In)           :: ns, nt, ntkeep
        Character (*), Intent (In)     :: grname
!       .. Array Arguments ..
        Real (Kind=nag_wp), Intent (In) :: greek(ns,ntkeep), s(ns), t(nt)
!       .. Local Scalars ..
        Integer                        :: i, j
!       .. Intrinsic Procedures ..
        Intrinsic                      :: len
!       .. Executable Statements ..
        Write (nout,*)
        Write (nout,*) grname
        Write (nout,*)('-',i=1,len(grname))
        Write (nout,*) '  Stock Price  |   Time to Maturity (months)'
        Write (nout,99999) '|', (12.0_nag_wp*(t(nt)-t(i)),i=1,ntkeep)
        Write (nout,*) ' -----------------', ('------------',i=1,ntkeep)
        Do i = 1, ns
          Write (nout,99998) s(i), '|', (greek(i,j),j=1,ntkeep)
        End Do

        Return

99999   Format (16X,A,1X,12(1P,E12.4))
99998   Format (1X,1P,E12.4,3X,A,1X,12(1P,E12.4))
      End Subroutine print_greek
    End Module d03ncfe_mod

    Program d03ncfe

!     D03NCF Example Main Program

!     .. Use Statements ..
      Use nag_library, Only: d03ncf, nag_wp
      Use d03ncfe_mod, Only: nin, nout, print_greek
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Logical, Parameter               :: gprnt(5) = .True.
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: alpha, x
      Integer                          :: ifail, kopt, ldf, ns, nt, ntkeep
      Character (1)                    :: mesh
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: delta(:,:), f(:,:), gamma(:,:),      &
                                          lambda(:,:), rho(:,:), s(:), t(:),   &
                                          theta(:,:), work(:)
      Real (Kind=nag_wp)               :: q(3), r(3), sigma(3)
      Integer, Allocatable             :: iwork(:)
      Logical                          :: tdpar(3)
!     .. Executable Statements ..
      Write (nout,*) 'D03NCF Example Program Results'
      Write (nout,*)
!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) ns, nt, ntkeep
      ldf = ns

      Allocate (delta(ldf,ntkeep),f(ldf,ntkeep),gamma(ldf,ntkeep),             &
        lambda(ldf,ntkeep),rho(ldf,ntkeep),s(ldf),t(nt),theta(ldf,ntkeep),     &
        work(4*ns),iwork(ns))

!     Read problem parameters

      Read (nin,*) kopt
      Read (nin,*) x
      Read (nin,*) mesh
      Read (nin,*) s(1), s(ns)
      Read (nin,*) t(1), t(nt)
      Read (nin,*) alpha

!     Set up input parameters for D03NCF

      Read (nin,*) tdpar(1:3)
      Read (nin,*) q(1), r(1), sigma(1)

!     Call Black-Scholes solver
      ifail = 0
      Call d03ncf(kopt,x,mesh,ns,s,nt,t,tdpar,r,q,sigma,alpha,ntkeep,f,theta,  &
        delta,gamma,lambda,rho,ldf,work,iwork,ifail)

!     Output option values and possibly Greeks.

      Call print_greek(ns,ntkeep,nt,s,t,'Option Values',f)

      If (gprnt(1)) Then
        Call print_greek(ns,ntkeep,nt,s,t,'Theta',theta)
      End If
      If (gprnt(2)) Then
        Call print_greek(ns,ntkeep,nt,s,t,'Delta',delta)
      End If
      If (gprnt(3)) Then
        Call print_greek(ns,ntkeep,nt,s,t,'Gamma',gamma)
      End If
      If (gprnt(4)) Then
        Call print_greek(ns,ntkeep,nt,s,t,'Lambda',lambda)
      End If
      If (gprnt(5)) Then
        Call print_greek(ns,ntkeep,nt,s,t,'Rho',rho)
      End If

    End Program d03ncfe


d03ndfe.f90

!   D03NDF Example Program Text
!   Mark 26 Release. NAG Copyright 2016.

    Module d03ndfe_mod

!     D03NDF Example Program Module:
!            Parameters and User-defined Routines

!     .. Use Statements ..
      Use nag_library, Only: nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Accessibility Statements ..
      Private
      Public                           :: print_greek
!     .. Parameters ..
      Integer, Parameter, Public       :: nin = 5, nout = 6
    Contains
      Subroutine print_greek(ns,nt,tmat,s,t,grname,greek)

!       .. Scalar Arguments ..
        Real (Kind=nag_wp), Intent (In) :: tmat
        Integer, Intent (In)           :: ns, nt
        Character (*), Intent (In)     :: grname
!       .. Array Arguments ..
        Real (Kind=nag_wp), Intent (In) :: greek(ns,nt), s(ns), t(nt)
!       .. Local Scalars ..
        Integer                        :: i, j
!       .. Intrinsic Procedures ..
        Intrinsic                      :: len
!       .. Executable Statements ..
        Write (nout,*)
        Write (nout,*) grname
        Write (nout,*)('-',i=1,len(grname))
        Write (nout,*) '  Stock Price  |   Time to Maturity (months)'
        Write (nout,99999) '|', (12.0_nag_wp*(tmat-t(i)),i=1,nt)
        Write (nout,*) ' -----------------', ('------------',i=1,nt)
        Do i = 1, ns
          Write (nout,99998) s(i), '|', (greek(i,j),j=1,nt)
        End Do

        Return

99999   Format (16X,A,1X,12(1P,E12.4))
99998   Format (1X,1P,E12.4,3X,A,1X,12(1P,E12.4))
      End Subroutine print_greek
    End Module d03ndfe_mod

    Program d03ndfe

!     D03NDF Example Main Program

!     .. Use Statements ..
      Use nag_library, Only: d03ndf, nag_wp
      Use d03ndfe_mod, Only: nin, nout, print_greek
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Logical, Parameter               :: gprnt(5) = .True.
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: ds, dt, tmat, x
      Integer                          :: i, ifail, j, kopt, ns, nt
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: delta(:,:), f(:,:), gamma(:,:),      &
                                          lambda(:,:), rho(:,:), s(:), t(:),   &
                                          theta(:,:)
      Real (Kind=nag_wp)               :: q(3), r(3), sigma(3)
      Logical                          :: tdpar(3)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: real
!     .. Executable Statements ..
      Write (nout,*) 'D03NDF Example Program Results'
      Write (nout,*)

!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) ns, nt

      Allocate (delta(ns,nt),f(ns,nt),gamma(ns,nt),lambda(ns,nt),rho(ns,nt),   &
        s(ns),t(nt),theta(ns,nt))

!     Read problem parameters

      Read (nin,*) kopt
      Read (nin,*) x
      Read (nin,*) tmat
      Read (nin,*) q(1), r(1), sigma(1)
      Read (nin,*) s(1), s(ns)
      Read (nin,*) t(1), t(nt)
      Read (nin,*) tdpar(1:3)

      If (ns<2) Then
        Write (nout,*) 'NS invalid.'
      Else If (nt<2) Then
        Write (nout,*) 'NT invalid.'
      Else

        ds = (s(ns)-s(1))/real(ns-1,kind=nag_wp)
        dt = (t(nt)-t(1))/real(nt-1,kind=nag_wp)

!       Loop over times
        Do j = 1, nt
          t(j) = t(1) + real(j-1,kind=nag_wp)*dt

!         Loop over stock prices
          Do i = 1, ns
            s(i) = s(1) + real(i-1,kind=nag_wp)*ds

!           Call Black-Scholes solver
            ifail = 0
            Call d03ndf(kopt,x,s(i),t(j),tmat,tdpar,r,q,sigma,f(i,j),          &
              theta(i,j),delta(i,j),gamma(i,j),lambda(i,j),rho(i,j),ifail)

          End Do
        End Do

!       Output option values and possibly Greeks.

        Call print_greek(ns,nt,tmat,s,t,'Option Values',f)

        If (gprnt(1)) Then
          Call print_greek(ns,nt,tmat,s,t,'Theta',theta)
        End If
        If (gprnt(2)) Then
          Call print_greek(ns,nt,tmat,s,t,'Delta',delta)
        End If
        If (gprnt(3)) Then
          Call print_greek(ns,nt,tmat,s,t,'Gamma',gamma)
        End If
        If (gprnt(4)) Then
          Call print_greek(ns,nt,tmat,s,t,'Lambda',lambda)
        End If
        If (gprnt(5)) Then
          Call print_greek(ns,nt,tmat,s,t,'Rho',rho)
        End If

      End If

    End Program d03ndfe


d03nefe.f90

!   D03NEF Example Program Text
!   Mark 26 Release. NAG Copyright 2016.

    Module d03nefe_mod

!     D03NEF Example Program Module:
!            Parameters and User-defined Routines

!     .. Use Statements ..
      Use nag_library, Only: nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Accessibility Statements ..
      Private
      Public                           :: print_greek
!     .. Parameters ..
      Integer, Parameter, Public       :: nin = 5, nout = 6
    Contains
      Subroutine print_greek(ns,nt,tmat,s,t,grname,greek)

!       .. Scalar Arguments ..
        Real (Kind=nag_wp), Intent (In) :: tmat
        Integer, Intent (In)           :: ns, nt
        Character (*), Intent (In)     :: grname
!       .. Array Arguments ..
        Real (Kind=nag_wp), Intent (In) :: greek(ns,nt), s(ns), t(nt)
!       .. Local Scalars ..
        Integer                        :: i, j
!       .. Intrinsic Procedures ..
        Intrinsic                      :: len
!       .. Executable Statements ..
        Write (nout,*)
        Write (nout,*) grname
        Write (nout,*)('-',i=1,len(grname))
        Write (nout,*) '  Stock Price  |   Time to Maturity (months)'
        Write (nout,99999) '|', (12.0_nag_wp*(tmat-t(i)),i=1,nt)
        Write (nout,*) ' -----------------', ('------------',i=1,nt)
        Do i = 1, ns
          Write (nout,99998) s(i), '|', (greek(i,j),j=1,nt)
        End Do

        Return

99999   Format (16X,A,1X,12(1P,E12.4))
99998   Format (1X,1P,E12.4,3X,A,1X,12(1P,E12.4))
      End Subroutine print_greek
    End Module d03nefe_mod

    Program d03nefe

!     D03NEF Example Main Program

!     .. Use Statements ..
      Use nag_library, Only: d03ndf, d03nef, nag_wp
      Use d03nefe_mod, Only: nin, nout, print_greek
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Logical, Parameter               :: gprnt(5) = .True.
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: ds, dt, tmat, x
      Integer                          :: i, ifail, j, kopt, lwork, ns, nt,    &
                                          ntd
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: delta(:,:), f(:,:), gamma(:,:),      &
                                          lambda(:,:), rd(:), rho(:,:), s(:),  &
                                          sigd(:), t(:), td(:), theta(:,:),    &
                                          work(:)
      Real (Kind=nag_wp)               :: q(3), ra(3), siga(3)
      Logical                          :: tdpar(3)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: real
!     .. Executable Statements ..
      Write (nout,*) 'D03NEF Example Program Results'
      Write (nout,*)

!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) ns, nt, ntd
      lwork = 9*ntd + 24

      Allocate (delta(ns,nt),f(ns,nt),gamma(ns,nt),lambda(ns,nt),rd(ntd),      &
        rho(ns,nt),s(ns),sigd(ntd),t(nt),td(ntd),theta(ns,nt),work(lwork))

!     Read problem parameters

      Read (nin,*) kopt
      Read (nin,*) x
      Read (nin,*) tmat
      Read (nin,*) s(1), s(ns)
      Read (nin,*) t(1), t(nt)
      Read (nin,*) td(1:ntd)
      Read (nin,*) rd(1:ntd)
      Read (nin,*) sigd(1:ntd)
      Read (nin,*) tdpar(1:3)
      Read (nin,*) q(1)

      If (ns<2) Then
        Write (nout,*) 'NS invalid.'
      Else If (nt<2) Then
        Write (nout,*) 'NT invalid.'
      Else

        ds = (s(ns)-s(1))/real(ns-1,kind=nag_wp)
        dt = (t(nt)-t(1))/real(nt-1,kind=nag_wp)

!       Loop over times

        Do j = 1, nt

          t(j) = t(1) + real(j-1,kind=nag_wp)*dt

!         Find average values of r and sigma
          ifail = 0
          Call d03nef(t(j),tmat,ntd,td,rd,ra,work,lwork,ifail)

          ifail = 0
          Call d03nef(t(j),tmat,ntd,td,sigd,siga,work,lwork,ifail)

!         Loop over stock prices

          Do i = 1, ns

            s(i) = s(1) + real(i-1,kind=nag_wp)*ds

!           Evaluate analytic solution of Black-Scholes equation
            ifail = 0
            Call d03ndf(kopt,x,s(i),t(j),tmat,tdpar,ra,q,siga,f(i,j),          &
              theta(i,j),delta(i,j),gamma(i,j),lambda(i,j),rho(i,j),ifail)

          End Do
        End Do

!       Output option values and possibly Greeks.

        Call print_greek(ns,nt,tmat,s,t,'Option Values',f)

        If (gprnt(1)) Then
          Call print_greek(ns,nt,tmat,s,t,'Theta',theta)
        End If
        If (gprnt(2)) Then
          Call print_greek(ns,nt,tmat,s,t,'Delta',delta)
        End If
        If (gprnt(3)) Then
          Call print_greek(ns,nt,tmat,s,t,'Gamma',gamma)
        End If
        If (gprnt(4)) Then
          Call print_greek(ns,nt,tmat,s,t,'Lambda',lambda)
        End If
        If (gprnt(5)) Then
          Call print_greek(ns,nt,tmat,s,t,'Rho',rho)
        End If

      End If

    End Program d03nefe


d03pcae.f90

!   D03PCA Example Program Text
!   Mark 26 Release. NAG Copyright 2016.

    Module d03pcae_mod

!     D03PCA Example Program Module:
!            Parameters and User-defined Routines

!     .. Use Statements ..
      Use nag_library, Only: nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Accessibility Statements ..
      Private
      Public                           :: bndary, pdedef, uinit
!     .. Parameters ..
      Integer, Parameter, Public       :: nin = 5, nout = 6, npde = 2
    Contains
      Subroutine pdedef(npde,t,x,u,ux,p,q,r,ires,iuser,ruser)

!       .. Scalar Arguments ..
        Real (Kind=nag_wp), Intent (In) :: t, x
        Integer, Intent (Inout)        :: ires
        Integer, Intent (In)           :: npde
!       .. Array Arguments ..
        Real (Kind=nag_wp), Intent (Out) :: p(npde,npde), q(npde), r(npde)
        Real (Kind=nag_wp), Intent (Inout) :: ruser(*)
        Real (Kind=nag_wp), Intent (In) :: u(npde), ux(npde)
        Integer, Intent (Inout)        :: iuser(*)
!       .. Local Scalars ..
        Real (Kind=nag_wp)             :: alpha
!       .. Executable Statements ..
        alpha = ruser(1)
        q(1) = 4.0_nag_wp*alpha*(u(2)+x*ux(2))
        q(2) = 0.0_nag_wp
        r(1) = x*ux(1)
        r(2) = ux(2) - u(1)*u(2)
        p(1,1:2) = 0.0_nag_wp
        p(2,1) = 0.0_nag_wp
        p(2,2) = 1.0_nag_wp - x*x
        Return
      End Subroutine pdedef
      Subroutine bndary(npde,t,u,ux,ibnd,beta,gamma,ires,iuser,ruser)

!       .. Scalar Arguments ..
        Real (Kind=nag_wp), Intent (In) :: t
        Integer, Intent (In)           :: ibnd, npde
        Integer, Intent (Inout)        :: ires
!       .. Array Arguments ..
        Real (Kind=nag_wp), Intent (Out) :: beta(npde), gamma(npde)
        Real (Kind=nag_wp), Intent (Inout) :: ruser(*)
        Real (Kind=nag_wp), Intent (In) :: u(npde), ux(npde)
        Integer, Intent (Inout)        :: iuser(*)
!       .. Executable Statements ..
        If (ibnd==0) Then
          beta(1) = 0.0_nag_wp
          beta(2) = 1.0_nag_wp
          gamma(1) = u(1)
          gamma(2) = -u(1)*u(2)
        Else
          beta(1) = 1.0_nag_wp
          beta(2) = 0.0_nag_wp
          gamma(1) = -u(1)
          gamma(2) = u(2)
        End If
        Return
      End Subroutine bndary
      Subroutine uinit(u,x,npts,iuser,ruser)
!       Routine for PDE initial conditon

!       .. Scalar Arguments ..
        Integer, Intent (In)           :: npts
!       .. Array Arguments ..
        Real (Kind=nag_wp), Intent (Inout) :: ruser(*)
        Real (Kind=nag_wp), Intent (Out) :: u(2,npts)
        Real (Kind=nag_wp), Intent (In) :: x(npts)
        Integer, Intent (Inout)        :: iuser(*)
!       .. Local Scalars ..
        Real (Kind=nag_wp)             :: alpha
        Integer                        :: i
!       .. Executable Statements ..
        alpha = ruser(1)
        Do i = 1, npts
          u(1,i) = 2.0_nag_wp*alpha*x(i)
          u(2,i) = 1.0_nag_wp
        End Do
        Return
      End Subroutine uinit
    End Module d03pcae_mod
    Program d03pcae

!     D03PCA Example Main Program

!     .. Use Statements ..
      Use nag_library, Only: d03pca, d03pzf, nag_wp, x01aaf
      Use d03pcae_mod, Only: bndary, nin, nout, npde, pdedef, uinit
!     .. Implicit None Statement ..
      Implicit None
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: acc, alpha, hx, pi, piby2, tout, ts
      Integer                          :: i, ifail, ind, intpts, it, itask,    &
                                          itrace, itype, m, neqn, niw, npts,   &
                                          nw, nwk
!     .. Local Arrays ..
      Real (Kind=nag_wp)               :: ruser(1), rwsav(1100)
      Real (Kind=nag_wp), Allocatable  :: u(:,:), uout(:,:,:), w(:), x(:),     &
                                          xout(:)
      Integer                          :: iuser(1), iwsav(505)
      Integer, Allocatable             :: iw(:)
      Logical                          :: lwsav(100)
      Character (80)                   :: cwsav(10)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: real, sin
!     .. Executable Statements ..
      Write (nout,*) 'D03PCA Example Program Results'
!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) intpts, npts, itype
      neqn = npde*npts
      niw = neqn + 24
      nwk = (10+6*npde)*neqn
      nw = nwk + (21+3*npde)*npde + 7*npts + 54

      Allocate (u(npde,npts),uout(npde,intpts,itype),w(nw),x(npts),            &
        xout(intpts),iw(niw))

      Read (nin,*) xout(1:intpts)
      Read (nin,*) acc, alpha
      Read (nin,*) m, itrace
      ruser(1) = alpha
      ind = 0
      itask = 1

!     Set spatial mesh points

      piby2 = 0.5_nag_wp*x01aaf(pi)
      hx = piby2/real(npts-1,kind=nag_wp)
      x(1) = 0.0_nag_wp
      x(npts) = 1.0_nag_wp
      Do i = 2, npts - 1
        x(i) = sin(hx*real(i-1,kind=nag_wp))
      End Do

!     Set initial conditions

      Read (nin,*) ts, tout

!     Set the initial values

      Call uinit(u,x,npts,iuser,ruser)
      Do it = 1, 5

        tout = 10.0_nag_wp*tout

!       ifail: behaviour on error exit
!              =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
        ifail = 0
        Call d03pca(npde,m,ts,tout,pdedef,bndary,u,npts,x,acc,w,nw,iw,niw,     &
          itask,itrace,ind,iuser,ruser,cwsav,lwsav,iwsav,rwsav,ifail)

        If (it==1) Then
          Write (nout,99999) acc, alpha
          Write (nout,99998) xout(1:6)
        End If

!       Interpolate at required spatial points
        ifail = 0
        Call d03pzf(npde,m,u,npts,x,xout,intpts,itype,uout,ifail)

        Write (nout,99996) tout, uout(1,1:intpts,1)
        Write (nout,99995) uout(2,1:intpts,1)
      End Do

!     Print integration statistics

      Write (nout,99997) iw(1), iw(2), iw(3), iw(5)

99999 Format (/,/,' Accuracy requirement  = ',E12.5,/,' Parameter ALPHA =',    &
        '       ',E12.3,/)
99998 Format ('   T  /  X   ',6F8.4,/)
99997 Format (' Number of integration steps in time                   ',I4,/,  &
        ' Number of residual evaluations of resulting ODE system',I4,/,        &
        ' Number of Jacobian evaluations                        ',I4,/,        &
        ' Number of iterations of nonlinear solver              ',I4)
99996 Format (1X,F7.4,' U(1)',6F8.4)
99995 Format (9X,'U(2)',6F8.4,/)
    End Program d03pcae


d03pcfe.f90

!   D03PCF Example Program Text
!   Mark 26 Release. NAG Copyright 2016.

    Module d03pcfe_mod

!     D03PCF Example Program Module:
!            Parameters and User-defined Routines

!     .. Use Statements ..
      Use nag_library, Only: nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Accessibility Statements ..
      Private
      Public                           :: bndary, pdedef, uinit
!     .. Parameters ..
      Integer, Parameter, Public       :: nin = 5, nout = 6, npde = 2
!     .. Local Scalars ..
      Real (Kind=nag_wp), Public, Save :: alpha
    Contains
      Subroutine pdedef(npde,t,x,u,ux,p,q,r,ires)

!       .. Scalar Arguments ..
        Real (Kind=nag_wp), Intent (In) :: t, x
        Integer, Intent (Inout)        :: ires
        Integer, Intent (In)           :: npde
!       .. Array Arguments ..
        Real (Kind=nag_wp), Intent (Out) :: p(npde,npde), q(npde), r(npde)
        Real (Kind=nag_wp), Intent (In) :: u(npde), ux(npde)
!       .. Executable Statements ..
        q(1) = 4.0_nag_wp*alpha*(u(2)+x*ux(2))
        q(2) = 0.0_nag_wp
        r(1) = x*ux(1)
        r(2) = ux(2) - u(1)*u(2)
        p(1,1) = 0.0_nag_wp
        p(1,2) = 0.0_nag_wp
        p(2,1) = 0.0_nag_wp
        p(2,2) = 1.0_nag_wp - x*x
        Return
      End Subroutine pdedef
      Subroutine bndary(npde,t,u,ux,ibnd,beta,gamma,ires)

!       .. Scalar Arguments ..
        Real (Kind=nag_wp), Intent (In) :: t
        Integer, Intent (In)           :: ibnd, npde
        Integer, Intent (Inout)        :: ires
!       .. Array Arguments ..
        Real (Kind=nag_wp), Intent (Out) :: beta(npde), gamma(npde)
        Real (Kind=nag_wp), Intent (In) :: u(npde), ux(npde)
!       .. Executable Statements ..
        If (ibnd==0) Then
          beta(1) = 0.0_nag_wp
          beta(2) = 1.0_nag_wp
          gamma(1) = u(1)
          gamma(2) = -u(1)*u(2)
        Else
          beta(1) = 1.0_nag_wp
          beta(2) = 0.0_nag_wp
          gamma(1) = -u(1)
          gamma(2) = u(2)
        End If
        Return
      End Subroutine bndary
      Subroutine uinit(u,x,npts)

!       Routine for PDE initial condition

!       .. Scalar Arguments ..
        Integer, Intent (In)           :: npts
!       .. Array Arguments ..
        Real (Kind=nag_wp), Intent (Out) :: u(2,npts)
        Real (Kind=nag_wp), Intent (In) :: x(npts)
!       .. Local Scalars ..
        Integer                        :: i
!       .. Executable Statements ..
        Do i = 1, npts
          u(1,i) = 2.0_nag_wp*alpha*x(i)
          u(2,i) = 1.0_nag_wp
        End Do
        Return
      End Subroutine uinit
    End Module d03pcfe_mod
    Program d03pcfe

!     D03PCF Example Main Program

!     .. Use Statements ..
      Use nag_library, Only: d03pcf, d03pzf, nag_wp, x01aaf
      Use d03pcfe_mod, Only: alpha, bndary, nin, nout, npde, pdedef, uinit
!     .. Implicit None Statement ..
      Implicit None
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: acc, hx, pi, piby2, tout, ts
      Integer                          :: i, ifail, ind, intpts, it, itask,    &
                                          itrace, itype, lisave, lrsave, m,    &
                                          neqn, npts, nwk
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: rsave(:), u(:,:), uout(:,:,:), x(:), &
                                          xout(:)
      Integer, Allocatable             :: isave(:)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: real, sin
!     .. Executable Statements ..
      Write (nout,*) 'D03PCF Example Program Results'
!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) intpts, npts, itype
      neqn = npde*npts
      lisave = neqn + 24
      nwk = (10+6*npde)*neqn
      lrsave = nwk + (21+3*npde)*npde + 7*npts + 54
      Allocate (rsave(lrsave),u(npde,npts),uout(npde,intpts,itype),x(npts),    &
        xout(intpts),isave(lisave))

      Read (nin,*) xout(1:intpts)
      Read (nin,*) acc, alpha
      Read (nin,*) m, itrace
      ind = 0
      itask = 1

!     Set spatial mesh points

      piby2 = 0.5_nag_wp*x01aaf(pi)
      hx = piby2/real(npts-1,kind=nag_wp)
      x(1) = 0.0_nag_wp
      x(npts) = 1.0_nag_wp
      Do i = 2, npts - 1
        x(i) = sin(hx*real(i-1,kind=nag_wp))
      End Do

!     Set initial conditions
      Read (nin,*) ts, tout

!     Set the initial values
      Call uinit(u,x,npts)

      Do it = 1, 5
        tout = 10.0_nag_wp*tout

!       ifail: behaviour on error exit
!              =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
        ifail = 0
        Call d03pcf(npde,m,ts,tout,pdedef,bndary,u,npts,x,acc,rsave,lrsave,    &
          isave,lisave,itask,itrace,ind,ifail)

        If (it==1) Then
          Write (nout,99999) acc, alpha
          Write (nout,99998) xout(1:6)
        End If

!       Interpolate at required spatial points

        ifail = 0
        Call d03pzf(npde,m,u,npts,x,xout,intpts,itype,uout,ifail)

        Write (nout,99996) tout, uout(1,1:intpts,1)
        Write (nout,99995) uout(2,1:intpts,1)
      End Do

!     Print integration statistics

      Write (nout,99997) isave(1), isave(2), isave(3), isave(5)

99999 Format (/,/,' Accuracy requirement  = ',E12.5,/,' Parameter ALPHA =',    &
        '       ',E12.3,/)
99998 Format ('   T  /  X   ',6F8.4,/)
99997 Format (' Number of integration steps in time                  ',I4,/,   &
        ' Number of residual evaluations of resulting ODE system',I4,/,        &
        ' Number of Jacobian evaluations                        ',I4,/,        &
        ' Number of iterations of nonlinear solver              ',I4)
99996 Format (1X,F7.4,' U(1)',6F8.4)
99995 Format (9X,'U(2)',6F8.4,/)
    End Program d03pcfe


d03pdae.f90

!   D03PDA Example Program Text
!   Mark 26 Release. NAG Copyright 2016.

    Module d03pdae_mod

!     D03PDA Example Program Module:
!            Parameters and User-defined Routines

!     .. Use Statements ..
      Use nag_library, Only: nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Accessibility Statements ..
      Private
      Public                           :: bndary, pdedef, uinit
!     .. Parameters ..
      Integer, Parameter, Public       :: nin = 5, nout = 6, npde = 2
    Contains

      Subroutine pdedef(npde,t,x,nptl,u,ux,p,q,r,ires,iuser,ruser)

!       .. Scalar Arguments ..
        Real (Kind=nag_wp), Intent (In) :: t
        Integer, Intent (Inout)        :: ires
        Integer, Intent (In)           :: npde, nptl
!       .. Array Arguments ..
        Real (Kind=nag_wp), Intent (Out) :: p(npde,npde,nptl), q(npde,nptl),   &
                                          r(npde,nptl)
        Real (Kind=nag_wp), Intent (Inout) :: ruser(*)
        Real (Kind=nag_wp), Intent (In) :: u(npde,nptl), ux(npde,nptl),        &
                                          x(nptl)
        Integer, Intent (Inout)        :: iuser(*)
!       .. Local Scalars ..
        Integer                        :: i
!       .. Executable Statements ..
        Do i = 1, nptl
          q(1,i) = u(2,i)
          q(2,i) = u(1,i)*ux(2,i) - ux(1,i)*u(2,i)
          r(1,i) = ux(1,i)
          r(2,i) = ux(2,i)
          p(1,1:2,i) = 0.0_nag_wp
          p(2,1,i) = 0.0_nag_wp
          p(2,2,i) = 1.0_nag_wp
        End Do
        Return
      End Subroutine pdedef

      Subroutine bndary(npde,t,u,ux,ibnd,beta,gamma,ires,iuser,ruser)

!       .. Scalar Arguments ..
        Real (Kind=nag_wp), Intent (In) :: t
        Integer, Intent (In)           :: ibnd, npde
        Integer, Intent (Inout)        :: ires
!       .. Array Arguments ..
        Real (Kind=nag_wp), Intent (Out) :: beta(npde), gamma(npde)
        Real (Kind=nag_wp), Intent (Inout) :: ruser(*)
        Real (Kind=nag_wp), Intent (In) :: u(npde), ux(npde)
        Integer, Intent (Inout)        :: iuser(*)
!       .. Executable Statements ..
        If (ibnd==0) Then
          beta(1) = 1.0_nag_wp
          gamma(1) = 0.0_nag_wp
          beta(2) = 0.0_nag_wp
          gamma(2) = u(1) - 1.0_nag_wp
        Else
          beta(1) = 1.0_nag_wp
          gamma(1) = 0.0_nag_wp
          beta(2) = 0.0_nag_wp
          gamma(2) = u(1) + 1.0_nag_wp
        End If
        Return
      End Subroutine bndary

      Subroutine uinit(npde,npts,x,u,iuser,ruser)

!       .. Scalar Arguments ..
        Integer, Intent (In)           :: npde, npts
!       .. Array Arguments ..
        Real (Kind=nag_wp), Intent (Inout) :: ruser(*)
        Real (Kind=nag_wp), Intent (Out) :: u(npde,npts)
        Real (Kind=nag_wp), Intent (In) :: x(npts)
        Integer, Intent (Inout)        :: iuser(*)
!       .. Local Scalars ..
        Real (Kind=nag_wp)             :: piby2
        Integer                        :: i
!       .. Intrinsic Procedures ..
        Intrinsic                      :: sin
!       .. Executable Statements ..
        piby2 = ruser(1)
        Do i = 1, npts
          u(1,i) = -sin(piby2*x(i))
          u(2,i) = -piby2*piby2*u(1,i)
        End Do
        Return
      End Subroutine uinit
    End Module d03pdae_mod

    Program d03pdae

!     D03PDA Example Main Program

!     .. Use Statements ..
      Use nag_library, Only: d03pda, d03pyf, nag_wp, x01aaf
      Use d03pdae_mod, Only: bndary, nin, nout, npde, pdedef, uinit
!     .. Implicit None Statement ..
      Implicit None
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: acc, dx, pi, piby2, tout, ts
      Integer                          :: i, ifail, ind, intpts, it, itask,    &
                                          itrace, itype, lenode, m, mu,        &
                                          nbkpts, nel, neqn, niw, npl1, npoly, &
                                          npts, nw, nwkres
!     .. Local Arrays ..
      Real (Kind=nag_wp)               :: ruser(1), rwsav(1100)
      Real (Kind=nag_wp), Allocatable  :: u(:,:), uout(:,:,:), w(:), x(:),     &
                                          xbkpts(:), xout(:)
      Integer                          :: iuser(1), iwsav(505)
      Integer, Allocatable             :: iw(:)
      Logical                          :: lwsav(100)
      Character (80)                   :: cwsav(10)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: real
!     .. Executable Statements ..
      Write (nout,*) 'D03PDA Example Program Results'
!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) intpts, nbkpts, npoly, itype
      nel = nbkpts - 1
      npts = nel*npoly + 1
      mu = npde*(npoly+1) - 1
      neqn = npde*npts
      niw = neqn + 24
      npl1 = npoly + 1
      nwkres = 3*npl1*npl1 + npl1*(npde*npde+6*npde+nbkpts+1) + 13*npde + 5
      lenode = (3*mu+1)*neqn
      nw = 11*neqn + 50 + nwkres + lenode

      Allocate (u(npde,npts),uout(npde,intpts,itype),w(nw),x(npts),            &
        xbkpts(nbkpts),xout(intpts),iw(niw))

      Read (nin,*) xout(1:intpts)
      Read (nin,*) acc
      Read (nin,*) m, itrace
      piby2 = 0.5_nag_wp*x01aaf(pi)
      ruser(1) = piby2

!     Set the break-points

      dx = 2.0_nag_wp/real(nbkpts-1,kind=nag_wp)
      xbkpts(1) = -1.0_nag_wp
      Do i = 2, nbkpts - 1
        xbkpts(i) = xbkpts(i-1) + dx
      End Do
      xbkpts(nbkpts) = 1.0_nag_wp

      ind = 0
      itask = 1
      Read (nin,*) ts, tout

!     Loop over output values of t

      Do it = 1, 5
        tout = 10.0_nag_wp*tout

!       ifail: behaviour on error exit
!              =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
        ifail = 0
        Call d03pda(npde,m,ts,tout,pdedef,bndary,u,nbkpts,xbkpts,npoly,npts,x, &
          uinit,acc,w,nw,iw,niw,itask,itrace,ind,iuser,ruser,cwsav,lwsav,      &
          iwsav,rwsav,ifail)

        If (it==1) Then
          Write (nout,99999) npoly, nel
          Write (nout,99998) acc, npts
          Write (nout,99997) xout(1:6)
        End If

!       Interpolate at required spatial points

        ifail = 0
        Call d03pyf(npde,u,nbkpts,xbkpts,npoly,npts,xout,intpts,itype,uout,w,  &
          nw,ifail)

        Write (nout,99996) ts, uout(1,1:intpts,1)
        Write (nout,99995) uout(2,1:intpts,1)
      End Do

!     Print integration statistics

      Write (nout,99994) iw(1), iw(2), iw(3), iw(5)

99999 Format (' Polynomial degree =',I4,'   No. of elements = ',I4)
99998 Format (' Accuracy requirement =',E10.3,'  Number of points = ',I5,/)
99997 Format ('  T /   X    ',6F8.4,/)
99996 Format (1X,F7.4,' U(1)',6F8.4)
99995 Format (9X,'U(2)',6F8.4,/)
99994 Format (' Number of integration steps in time                   ',I4,/,  &
        ' Number of residual evaluations of resulting ODE system',I4,/,        &
        ' Number of Jacobian evaluations                        ',I4,/,        &
        ' Number of iterations of nonlinear solver              ',I4)
    End Program d03pdae


d03pdfe.f90

!   D03PDF Example Program Text
!   Mark 26 Release. NAG Copyright 2016.

    Module d03pdfe_mod

!     D03PDF Example Program Module:
!            Parameters and User-defined Routines

!     .. Use Statements ..
      Use nag_library, Only: nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Accessibility Statements ..
      Private
      Public                           :: bndary, pdedef, uinit
!     .. Parameters ..
      Integer, Parameter, Public       :: nin = 5, nout = 6, npde = 2
    Contains
      Subroutine uinit(npde,npts,x,u)

!       .. Use Statements ..
        Use nag_library, Only: x01aaf
!       .. Scalar Arguments ..
        Integer, Intent (In)           :: npde, npts
!       .. Array Arguments ..
        Real (Kind=nag_wp), Intent (Out) :: u(npde,npts)
        Real (Kind=nag_wp), Intent (In) :: x(npts)
!       .. Local Scalars ..
        Real (Kind=nag_wp)             :: piby2
        Integer                        :: i
!       .. Intrinsic Procedures ..
        Intrinsic                      :: sin
!       .. Executable Statements ..
        piby2 = 0.5_nag_wp*x01aaf(piby2)
        Do i = 1, npts
          u(1,i) = -sin(piby2*x(i))
          u(2,i) = -piby2*piby2*u(1,i)
        End Do
        Return
      End Subroutine uinit

      Subroutine pdedef(npde,t,x,nptl,u,ux,p,q,r,ires)

!       .. Scalar Arguments ..
        Real (Kind=nag_wp), Intent (In) :: t
        Integer, Intent (Inout)        :: ires
        Integer, Intent (In)           :: npde, nptl
!       .. Array Arguments ..
        Real (Kind=nag_wp), Intent (Out) :: p(npde,npde,nptl), q(npde,nptl),   &
                                          r(npde,nptl)
        Real (Kind=nag_wp), Intent (In) :: u(npde,nptl), ux(npde,nptl),        &
                                          x(nptl)
!       .. Local Scalars ..
        Integer                        :: i
!       .. Executable Statements ..
        Do i = 1, nptl
          q(1,i) = u(2,i)
          q(2,i) = u(1,i)*ux(2,i) - ux(1,i)*u(2,i)
          r(1,i) = ux(1,i)
          r(2,i) = ux(2,i)
          p(1,1,i) = 0.0_nag_wp
          p(1,2,i) = 0.0_nag_wp
          p(2,1,i) = 0.0_nag_wp
          p(2,2,i) = 1.0_nag_wp
        End Do
        Return
      End Subroutine pdedef

      Subroutine bndary(npde,t,u,ux,ibnd,beta,gamma,ires)

!       .. Scalar Arguments ..
        Real (Kind=nag_wp), Intent (In) :: t
        Integer, Intent (In)           :: ibnd, npde
        Integer, Intent (Inout)        :: ires
!       .. Array Arguments ..
        Real (Kind=nag_wp), Intent (Out) :: beta(npde), gamma(npde)
        Real (Kind=nag_wp), Intent (In) :: u(npde), ux(npde)
!       .. Executable Statements ..
        If (ibnd==0) Then
          beta(1) = 1.0_nag_wp
          gamma(1) = 0.0_nag_wp
          beta(2) = 0.0_nag_wp
          gamma(2) = u(1) - 1.0_nag_wp
        Else
          beta(1) = 1.0E+0_nag_wp
          gamma(1) = 0.0_nag_wp
          beta(2) = 0.0_nag_wp
          gamma(2) = u(1) + 1.0_nag_wp
        End If
        Return
      End Subroutine bndary
    End Module d03pdfe_mod

    Program d03pdfe

!     D03PDF Example Main Program

!     .. Use Statements ..
      Use nag_library, Only: d03pdf, d03pyf, nag_wp
      Use d03pdfe_mod, Only: bndary, nin, nout, npde, pdedef, uinit
!     .. Implicit None Statement ..
      Implicit None
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: acc, dx, tout, ts
      Integer                          :: i, ifail, ind, intpts, it, itask,    &
                                          itrace, itype, lenode, lisave,       &
                                          lrsave, m, mu, nbkpts, nel, neqn,    &
                                          npl1, npoly, npts, nwkres
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: rsave(:), u(:,:), uout(:,:,:), x(:), &
                                          xbkpts(:), xout(:)
      Integer, Allocatable             :: isave(:)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: real
!     .. Executable Statements ..
      Write (nout,*) 'D03PDF Example Program Results'
!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) intpts, nbkpts, npoly, itype

      nel = nbkpts - 1
      npts = nel*npoly + 1
      mu = npde*(npoly+1) - 1
      neqn = npde*npts
      lisave = neqn + 24
      npl1 = npoly + 1
      nwkres = 3*npl1*npl1 + npl1*(npde*npde+6*npde+nbkpts+1) + 13*npde + 5
      lenode = (3*mu+1)*neqn
      lrsave = 11*neqn + 50 + nwkres + lenode

      Allocate (u(npde,npts),uout(npde,intpts,itype),rsave(lrsave),x(npts),    &
        xbkpts(nbkpts),xout(intpts),isave(lisave))

      Read (nin,*) xout(1:intpts)
      Read (nin,*) acc
      Read (nin,*) m, itrace

!     Set the break-points

      dx = 2.0_nag_wp/real(nbkpts-1,kind=nag_wp)
      xbkpts(1) = -1.0_nag_wp
      Do i = 2, nbkpts - 1
        xbkpts(i) = xbkpts(i-1) + dx
      End Do
      xbkpts(nbkpts) = 1.0_nag_wp

      ind = 0
      itask = 1
      Read (nin,*) ts, tout

!     Loop over output values of t

      Do it = 1, 5
        tout = 10.0_nag_wp*tout

!       ifail: behaviour on error exit
!              =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
        ifail = 0
        Call d03pdf(npde,m,ts,tout,pdedef,bndary,u,nbkpts,xbkpts,npoly,npts,x, &
          uinit,acc,rsave,lrsave,isave,lisave,itask,itrace,ind,ifail)

        If (it==1) Then
          Write (nout,99999) npoly, nel
          Write (nout,99998) acc, npts
          Write (nout,99997) xout(1:6)
        End If

!       Interpolate at required spatial points

        ifail = 0
        Call d03pyf(npde,u,nbkpts,xbkpts,npoly,npts,xout,intpts,itype,uout,    &
          rsave,lrsave,ifail)

        Write (nout,99996) ts, uout(1,1:intpts,1)
        Write (nout,99995) uout(2,1:intpts,1)
      End Do

!     Print integration statistics

      Write (nout,99994) isave(1), isave(2), isave(3), isave(5)

99999 Format (' Polynomial degree =',I4,'   No. of elements = ',I4)
99998 Format (' Accuracy requirement =',E10.3,'  Number of points = ',I5,/)
99997 Format ('  T /   X    ',6F8.4,/)
99996 Format (1X,F7.4,' U(1)',6F8.4)
99995 Format (9X,'U(2)',6F8.4,/)
99994 Format (' Number of integration steps in time                   ',I4,/,  &
        ' Number of residual evaluations of resulting ODE system',I4,/,        &
        ' Number of Jacobian evaluations                        ',I4,/,        &
        ' Number of iterations of nonlinear solver              ',I4)
    End Program d03pdfe


d03pefe.f90

!   D03PEF Example Program Text
!   Mark 26 Release. NAG Copyright 2016.

    Module d03pefe_mod

!     D03PEF Example Program Module:
!            Parameters and User-defined Routines

!     .. Use Statements ..
      Use nag_library, Only: nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Accessibility Statements ..
      Private
      Public                           :: bndary, exact, pdedef, uinit
!     .. Parameters ..
      Real (Kind=nag_wp), Parameter    :: half = 0.5_nag_wp
      Real (Kind=nag_wp), Parameter    :: one = 1.0_nag_wp
      Integer, Parameter, Public       :: nin = 5, nleft = 1, nout = 6,        &
                                          npde = 2
    Contains
      Subroutine uinit(npde,npts,x,u)
!       Routine for PDE initial values

!       .. Scalar Arguments ..
        Integer, Intent (In)           :: npde, npts
!       .. Array Arguments ..
        Real (Kind=nag_wp), Intent (Out) :: u(npde,npts)
        Real (Kind=nag_wp), Intent (In) :: x(npts)
!       .. Local Scalars ..
        Integer                        :: i
!       .. Intrinsic Procedures ..
        Intrinsic                      :: exp, sin
!       .. Executable Statements ..
        Do i = 1, npts
          u(1,i) = exp(x(i))
          u(2,i) = sin(x(i))
        End Do
        Return
      End Subroutine uinit
      Subroutine pdedef(npde,t,x,u,ut,ux,res,ires)

!       .. Scalar Arguments ..
        Real (Kind=nag_wp), Intent (In) :: t, x
        Integer, Intent (Inout)        :: ires
        Integer, Intent (In)           :: npde
!       .. Array Arguments ..
        Real (Kind=nag_wp), Intent (Out) :: res(npde)
        Real (Kind=nag_wp), Intent (In) :: u(npde), ut(npde), ux(npde)
!       .. Executable Statements ..
        If (ires==-1) Then
          res(1) = ut(1)
          res(2) = ut(2)
        Else
          res(1) = ut(1) + ux(1) + ux(2)
          res(2) = ut(2) + 4.0_nag_wp*ux(1) + ux(2)
        End If
        Return
      End Subroutine pdedef
      Subroutine bndary(npde,t,ibnd,nobc,u,ut,res,ires)

!       .. Scalar Arguments ..
        Real (Kind=nag_wp), Intent (In) :: t
        Integer, Intent (In)           :: ibnd, nobc, npde
        Integer, Intent (Inout)        :: ires
!       .. Array Arguments ..
        Real (Kind=nag_wp), Intent (Out) :: res(nobc)
        Real (Kind=nag_wp), Intent (In) :: u(npde), ut(npde)
!       .. Local Scalars ..
        Real (Kind=nag_wp)             :: t1, t3
!       .. Intrinsic Procedures ..
        Intrinsic                      :: exp, sin
!       .. Executable Statements ..
        If (ires==-1) Then
          res(1) = 0.0_nag_wp
        Else If (ibnd==0) Then
          t3 = -3.0_nag_wp*t
          t1 = t
          res(1) = u(1) - half*((exp(t3)+exp(t1))+half*(sin(t3)-sin(t1)))
        Else
          t3 = one - 3.0_nag_wp*t
          t1 = one + t
          res(1) = u(2) - ((exp(t3)-exp(t1))+half*(sin(t3)+sin(t1)))
        End If
        Return
      End Subroutine bndary
      Subroutine exact(t,npde,npts,x,u)
!       Exact solution (for comparison purposes)

!       .. Scalar Arguments ..
        Real (Kind=nag_wp), Intent (In) :: t
        Integer, Intent (In)           :: npde, npts
!       .. Array Arguments ..
        Real (Kind=nag_wp), Intent (Out) :: u(npde,npts)
        Real (Kind=nag_wp), Intent (In) :: x(npts)
!       .. Local Scalars ..
        Real (Kind=nag_wp)             :: xt, xt3
        Integer                        :: i
!       .. Intrinsic Procedures ..
        Intrinsic                      :: exp, sin
!       .. Executable Statements ..
        Do i = 1, npts
          xt3 = x(i) - 3.0_nag_wp*t
          xt = x(i) + t
          u(1,i) = half*((exp(xt3)+exp(xt))+half*(sin(xt3)-sin(xt)))
          u(2,i) = (exp(xt3)-exp(xt)) + half*(sin(xt3)+sin(xt))
        End Do
        Return
      End Subroutine exact
    End Module d03pefe_mod
    Program d03pefe

!     D03PEF Example Main Program

!     .. Use Statements ..
      Use nag_library, Only: d03pef, nag_wp
      Use d03pefe_mod, Only: bndary, exact, nin, nleft, nout, npde, pdedef,    &
                             uinit
!     .. Implicit None Statement ..
      Implicit None
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: acc, tout, ts
      Integer                          :: i, ifail, ind, it, itask, itrace,    &
                                          lisave, lrsave, neqn, npts, nwkres
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: eu(:,:), rsave(:), u(:,:), x(:)
      Integer, Allocatable             :: isave(:)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: real
!     .. Executable Statements ..
      Write (nout,*) 'D03PEF Example Program Results'
!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) npts
      nwkres = npde*(npts+21+3*npde) + 7*npts + 4
      neqn = npde*npts
      lisave = neqn + 24
      lrsave = 11*neqn + (4*npde+nleft+2)*neqn + 50 + nwkres

      Allocate (eu(npde,npts),rsave(lrsave),u(npde,npts),x(npts),              &
        isave(lisave))
      Read (nin,*) acc
      Read (nin,*) itrace

!     Set spatial-mesh points

      Do i = 1, npts
        x(i) = real(i-1,kind=nag_wp)/real(npts-1,kind=nag_wp)
      End Do

      ind = 0
      itask = 1

      Call uinit(npde,npts,x,u)

!     Loop over output value of t
      Read (nin,*) ts, tout

      Do it = 1, 5
        tout = 0.2_nag_wp*real(it,kind=nag_wp)

!       ifail: behaviour on error exit
!              =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
        ifail = 0
        Call d03pef(npde,ts,tout,pdedef,bndary,u,npts,x,nleft,acc,rsave,       &
          lrsave,isave,lisave,itask,itrace,ind,ifail)

        If (it==1) Then
          Write (nout,99997) acc, npts
          Write (nout,99999) x(5), x(13), x(21), x(29), x(37)
        End If

!       Check against the exact solution

        Call exact(tout,npde,npts,x,eu)

        Write (nout,99998) ts
        Write (nout,99995) u(1,5:37:8)
        Write (nout,99994) eu(1,5:37:8)
        Write (nout,99993) u(2,5:37:8)
        Write (nout,99992) eu(2,5:37:8)
      End Do
      Write (nout,99996) isave(1), isave(2), isave(3), isave(5)

99999 Format (' X        ',5F10.4,/)
99998 Format (' T = ',F5.2)
99997 Format (/,/,'  Accuracy requirement =',E10.3,' Number of points = ',I3,  &
        /)
99996 Format (' Number of integration steps in time = ',I6,/,' Number o',      &
        'f function evaluations = ',I6,/,' Number of Jacobian eval',           &
        'uations =',I6,/,' Number of iterations = ',I6)
99995 Format (' Approx U1',5F10.4)
99994 Format (' Exact  U1',5F10.4)
99993 Format (' Approx U2',5F10.4)
99992 Format (' Exact  U2',5F10.4,/)
    End Program d03pefe


d03pffe.f90

!   D03PFF Example Program Text
!   Mark 26 Release. NAG Copyright 2016.

    Module d03pffe_mod

!     D03PFF Example Program Module:
!            Parameters and User-defined Routines

!     .. Use Statements ..
      Use nag_library, Only: nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Accessibility Statements ..
      Private
      Public                           :: bndry1, bndry2, exact, nmflx1,       &
                                          nmflx2, pdedef
!     .. Parameters ..
      Integer, Parameter, Public       :: nin = 5, nout = 6, npde1 = 2,        &
                                          npde2 = 1
    Contains
      Subroutine exact(t,u,npde,x,npts)
!       Exact solution (for comparison and b.c. purposes)

!       .. Use Statements ..
        Use nag_library, Only: x01aaf
!       .. Parameters ..
        Real (Kind=nag_wp), Parameter  :: half = 0.5_nag_wp
        Real (Kind=nag_wp), Parameter  :: two = 2.0_nag_wp
!       .. Scalar Arguments ..
        Real (Kind=nag_wp), Intent (In) :: t
        Integer, Intent (In)           :: npde, npts
!       .. Array Arguments ..
        Real (Kind=nag_wp), Intent (Out) :: u(npde,npts)
        Real (Kind=nag_wp), Intent (In) :: x(npts)
!       .. Local Scalars ..
        Real (Kind=nag_wp)             :: pi, px1, px2, x1, x2
        Integer                        :: i
!       .. Intrinsic Procedures ..
        Intrinsic                      :: exp, sin
!       .. Executable Statements ..
        pi = x01aaf(pi)

        Do i = 1, npts
          x1 = x(i) + t
          x2 = x(i) - 3.0_nag_wp*t
          px1 = half*sin(two*pi*x1**2)
          px2 = half*sin(two*pi*x2**2)
          u(1,i) = half*(exp(x2)+exp(x1)+px2-px1) - t*(x1+x2)
          u(2,i) = (exp(x2)-exp(x1)+px2+px1) + x1*x2 + 8.0_nag_wp*t**2
        End Do
        Return
      End Subroutine exact
      Subroutine bndry1(npde,npts,t,x,u,ibnd,g,ires)

!       .. Parameters ..
        Real (Kind=nag_wp), Parameter  :: one = 1.0_nag_wp
        Real (Kind=nag_wp), Parameter  :: two = 2.0_nag_wp
!       .. Scalar Arguments ..
        Real (Kind=nag_wp), Intent (In) :: t
        Integer, Intent (In)           :: ibnd, npde, npts
        Integer, Intent (Inout)        :: ires
!       .. Array Arguments ..
        Real (Kind=nag_wp), Intent (Out) :: g(npde)
        Real (Kind=nag_wp), Intent (In) :: u(npde,3), x(npts)
!       .. Local Scalars ..
        Real (Kind=nag_wp)             :: c, exu1, exu2
!       .. Local Arrays ..
        Real (Kind=nag_wp)             :: ue(2,1)
!       .. Executable Statements ..
        If (ibnd==0) Then
          Call exact(t,ue,npde,x(1),1)
          c = (x(2)-x(1))/(x(3)-x(2))
          exu1 = (one+c)*u(1,2) - c*u(1,3)
          exu2 = (one+c)*u(2,2) - c*u(2,3)
          g(1) = two*u(1,1) + u(2,1) - two*ue(1,1) - ue(2,1)
          g(2) = two*u(1,1) - u(2,1) - two*exu1 + exu2
        Else
          Call exact(t,ue,npde,x(npts),1)
          c = (x(npts)-x(npts-1))/(x(npts-1)-x(npts-2))
          exu1 = (one+c)*u(1,2) - c*u(1,3)
          exu2 = (one+c)*u(2,2) - c*u(2,3)
          g(1) = two*u(1,1) - u(2,1) - two*ue(1,1) + ue(2,1)
          g(2) = two*u(1,1) + u(2,1) - two*exu1 - exu2
        End If
        Return
      End Subroutine bndry1
      Subroutine nmflx1(npde,t,x,uleft,uright,flux,ires)

!       .. Parameters ..
        Real (Kind=nag_wp), Parameter  :: half = 0.5_nag_wp
!       .. Scalar Arguments ..
        Real (Kind=nag_wp), Intent (In) :: t, x
        Integer, Intent (Inout)        :: ires
        Integer, Intent (In)           :: npde
!       .. Array Arguments ..
        Real (Kind=nag_wp), Intent (Out) :: flux(npde)
        Real (Kind=nag_wp), Intent (In) :: uleft(npde), uright(npde)
!       .. Local Scalars ..
        Real (Kind=nag_wp)             :: ltmp, rtmp
!       .. Executable Statements ..
        ltmp = 3.0_nag_wp*uleft(1) + 1.5_nag_wp*uleft(2)
        rtmp = uright(1) - half*uright(2)
        flux(1) = half*(ltmp-rtmp)
        flux(2) = ltmp + rtmp
        Return
      End Subroutine nmflx1
      Subroutine pdedef(npde,t,x,u,ux,p,c,d,s,ires)

!       .. Scalar Arguments ..
        Real (Kind=nag_wp), Intent (In) :: t, x
        Integer, Intent (Inout)        :: ires
        Integer, Intent (In)           :: npde
!       .. Array Arguments ..
        Real (Kind=nag_wp), Intent (Out) :: c(npde), d(npde), p(npde,npde),    &
                                          s(npde)
        Real (Kind=nag_wp), Intent (In) :: u(npde), ux(npde)
!       .. Executable Statements ..
        p(1,1) = 1.0_nag_wp
        c(1) = 0.01_nag_wp
        d(1) = ux(1)
        s(1) = u(1)
        Return
      End Subroutine pdedef
      Subroutine bndry2(npde,npts,t,x,u,ibnd,g,ires)

!       .. Scalar Arguments ..
        Real (Kind=nag_wp), Intent (In) :: t
        Integer, Intent (In)           :: ibnd, npde, npts
        Integer, Intent (Inout)        :: ires
!       .. Array Arguments ..
        Real (Kind=nag_wp), Intent (Out) :: g(npde)
        Real (Kind=nag_wp), Intent (In) :: u(npde,3), x(npts)
!       .. Executable Statements ..
        If (ibnd==0) Then
          g(1) = u(1,1) - 3.0_nag_wp
        Else
          g(1) = u(1,1) - 5.0_nag_wp
        End If
        Return
      End Subroutine bndry2
      Subroutine nmflx2(npde,t,x,uleft,uright,flux,ires)

!       .. Scalar Arguments ..
        Real (Kind=nag_wp), Intent (In) :: t, x
        Integer, Intent (Inout)        :: ires
        Integer, Intent (In)           :: npde
!       .. Array Arguments ..
        Real (Kind=nag_wp), Intent (Out) :: flux(npde)
        Real (Kind=nag_wp), Intent (In) :: uleft(npde), uright(npde)
!       .. Executable Statements ..
        If (x>=0.0E0_nag_wp) Then
          flux(1) = x*uleft(1)
        Else
          flux(1) = x*uright(1)
        End If
        Return
      End Subroutine nmflx2
    End Module d03pffe_mod
    Program d03pffe

!     D03PFF Example Main Program

!     .. Use Statements ..
      Use d03pffe_mod, Only: nout
!     .. Implicit None Statement ..
      Implicit None
!     .. Executable Statements ..
      Write (nout,*) 'D03PFF Example Program Results'

      Call ex1

      Call ex2

    Contains
      Subroutine ex1

!       .. Use Statements ..
        Use nag_library, Only: d03pff, d03pfp, nag_wp
        Use d03pffe_mod, Only: bndry1, exact, nin, nmflx1, npde1
!       .. Local Scalars ..
        Real (Kind=nag_wp)             :: dx, tout, ts, tsmax
        Integer                        :: i, ifail, inc, ind, it, itask,       &
                                          itrace, lisave, lrsave, nfuncs,      &
                                          niters, njacs, nop, npde, npts,      &
                                          nsteps, outpts
!       .. Local Arrays ..
        Real (Kind=nag_wp)             :: acc(2)
        Real (Kind=nag_wp), Allocatable :: rsave(:), u(:,:), ue(:,:), x(:),    &
                                          xout(:)
        Integer, Allocatable           :: isave(:)
!       .. Intrinsic Procedures ..
        Intrinsic                      :: real
!       .. Executable Statements ..
        Write (nout,*)
        Write (nout,*)
        Write (nout,*) 'Example 1'
        Write (nout,*)
!       Skip heading in data file
        npde = npde1
        Read (nin,*)
        Read (nin,*) npts, inc, outpts
        lisave = 24 + npde*npts
        lrsave = (11+9*npde)*npde*npts + (32+3*npde)*npde + 7*npts + 54

        Allocate (rsave(lrsave),u(npde,npts),ue(npde,outpts),x(npts),          &
          xout(outpts),isave(lisave))
        Read (nin,*) acc(1:2)
        Read (nin,*) itrace
        Read (nin,*) tsmax

!       Initialize mesh
        dx = 1.0_nag_wp/real(npts-1,kind=nag_wp)
        Do i = 1, npts
          x(i) = real(i-1,kind=nag_wp)*dx
        End Do

!       Set initial values
        Read (nin,*) ts
        Call exact(ts,u,npde,x,npts)

        ind = 0
        itask = 1

        Write (nout,99992) npts
        Write (nout,99991) acc(1)
        Write (nout,99990) acc(2)
        Write (nout,99999)

        Do it = 1, 2
          tout = 0.1E0_nag_wp*real(it,kind=nag_wp)

!         ifail: behaviour on error exit
!                =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
          ifail = 0
          Call d03pff(npde,ts,tout,d03pfp,nmflx1,bndry1,u,npts,x,acc,tsmax,    &
            rsave,lrsave,isave,lisave,itask,itrace,ind,ifail)

!         Set output points

          nop = 0
          Do i = 1, npts, inc
            nop = nop + 1
            xout(nop) = x(i)
          End Do

!         Check against exact solution

          Call exact(tout,ue,npde,xout,nop)
          nop = 1
          i = 1
          Write (nout,99998) ts, xout(nop), u(1,i), ue(1,nop), u(2,i),         &
            ue(2,nop)
          Do i = inc + 1, npts, inc
            nop = nop + 1
            Write (nout,99997) xout(nop), u(1,i), ue(1,nop), u(2,i), ue(2,nop)
          End Do
        End Do

!       Print integration statistics (reasonably rounded)
        nsteps = 5*((isave(1)+2)/5)
        nfuncs = 50*((isave(2)+25)/50)
        njacs = 10*((isave(3)+5)/10)
        niters = 50*((isave(5)+25)/50)
        Write (nout,99996) nsteps
        Write (nout,99995) nfuncs
        Write (nout,99994) njacs
        Write (nout,99993) niters

        Return

99999   Format (/,5X,'t',9X,'x',8X,'Approx u',4X,'Exact u',5X,'Approx v',4X,   &
          'Exact v')
99998   Format (/,1X,F6.3,5(3X,F9.4))
99997   Format (7X,5(3X,F9.4))
99996   Format (/,' Number of time steps           (nearest 5)  = ',I6)
99995   Format (' Number of function evaluations (nearest 50) = ',I6)
99994   Format (' Number of Jacobian evaluations (nearest 10) = ',I6)
99993   Format (' Number of iterations           (nearest 50) = ',I6)
99992   Format (/,' Number of mesh points used = ',I4)
99991   Format (' Relative tolerance used    = ',E10.3)
99990   Format (' Absolute tolerance used    = ',E10.3)
      End Subroutine ex1
      Subroutine ex2

!       .. Use Statements ..
        Use nag_library, Only: d03pff, nag_wp
        Use d03pffe_mod, Only: bndry2, nin, nmflx2, npde2, pdedef
!       .. Local Scalars ..
        Real (Kind=nag_wp)             :: dx, tout, ts, tsmax
        Integer                        :: i, ifail, ind, it, itask, itrace,    &
                                          lisave, lrsave, nfuncs, niters,      &
                                          njacs, npde, npts, nsteps, outpts
!       .. Local Arrays ..
        Real (Kind=nag_wp)             :: acc(2)
        Real (Kind=nag_wp), Allocatable :: rsave(:), u(:,:), x(:), xout(:)
        Integer, Allocatable           :: iout(:), isave(:)
!       .. Intrinsic Procedures ..
        Intrinsic                      :: real
!       .. Executable Statements ..
        Write (nout,*)
        Write (nout,*)
        Write (nout,*) 'Example 2'
        Write (nout,*)
        npde = npde2
        Read (nin,*)
        Read (nin,*) npts, outpts
        lisave = 24 + npde*npts
        lrsave = (11+9*npde)*npde*npts + (32+3*npde)*npde + 7*npts + 54

        Allocate (rsave(lrsave),u(npde,npts),x(npts),xout(outpts),             &
          isave(lisave),iout(outpts))
        Read (nin,*) iout(1:outpts)
        Read (nin,*) acc(1:2)
        Read (nin,*) itrace
        Read (nin,*) tsmax

!       Initialize mesh
        dx = 2.0_nag_wp/real(npts-1,kind=nag_wp)
        Do i = 1, npts
          x(i) = -1.0_nag_wp + real(i-1,kind=nag_wp)*dx
        End Do

!       Set initial values
        u(1,1:npts) = x(1:npts) + 4.0_nag_wp

        ind = 0
        itask = 1

!       Set output points from inout indices
        Do i = 1, outpts
          xout(i) = x(iout(i))
        End Do

!       Two output value of t: tout read from file and 10.0

        Read (nin,*) ts, tout

        Write (nout,99995) npts
        Write (nout,99994) acc(1)
        Write (nout,99993) acc(2)
        Write (nout,99992) xout(1:outpts)

        Do it = 1, 2

          ifail = 0
          Call d03pff(npde,ts,tout,pdedef,nmflx2,bndry2,u,npts,x,acc,tsmax,    &
            rsave,lrsave,isave,lisave,itask,itrace,ind,ifail)

          Write (nout,99991) ts, (u(1,iout(i)),i=1,outpts)
          tout = 10.0_nag_wp

        End Do

!       Print integration statistics (reasonably rounded)
        nsteps = 5*((isave(1)+2)/5)
        nfuncs = 50*((isave(2)+25)/50)
        njacs = 10*((isave(3)+5)/10)
        niters = 50*((isave(5)+25)/50)
        Write (nout,99999) nsteps
        Write (nout,99998) nfuncs
        Write (nout,99997) njacs
        Write (nout,99996) niters

        Return

99999   Format (/,' Number of time steps           (nearest 5)  = ',I6)
99998   Format (' Number of function evaluations (nearest 50) = ',I6)
99997   Format (' Number of Jacobian evaluations (nearest 10) = ',I6)
99996   Format (' Number of iterations           (nearest 50) = ',I6)
99995   Format (/,' Number of mesh points used = ',I4)
99994   Format (' Relative tolerance used    = ',E10.3)
99993   Format (' Absolute tolerance used    = ',E10.3)
99992   Format (/,1X,'x',10X,7F9.4)
99991   Format (1X,'u(t=',F6.3,')',7F9.4)
      End Subroutine ex2
    End Program d03pffe


d03phae.f90

!   D03PHA Example Program Text
!   Mark 26 Release. NAG Copyright 2016.

    Module d03phae_mod

!     D03PHA Example Program Module:
!            Parameters and User-defined Routines

!     .. Use Statements ..
      Use nag_library, Only: nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Accessibility Statements ..
      Private
      Public                           :: bndary, odedef, pdedef, uvinit
!     .. Parameters ..
      Real (Kind=nag_wp), Parameter    :: one = 1.0_nag_wp
      Integer, Parameter, Public       :: itrace = 0, ncode = 1, nin = 5,      &
                                          nout = 6, npde = 1, nxi = 1
      Logical, Parameter, Public       :: print_stat = .False.
    Contains
      Subroutine uvinit(npde,npts,x,u,ncode,neqn,iuser,ruser)

!       Routine for PDE initial values

!       .. Scalar Arguments ..
        Integer, Intent (In)           :: ncode, neqn, npde, npts
!       .. Array Arguments ..
        Real (Kind=nag_wp), Intent (Inout) :: ruser(*)
        Real (Kind=nag_wp), Intent (Out) :: u(neqn)
        Real (Kind=nag_wp), Intent (In) :: x(npts)
        Integer, Intent (Inout)        :: iuser(*)
!       .. Local Scalars ..
        Real (Kind=nag_wp)             :: ts
        Integer                        :: i
!       .. Intrinsic Procedures ..
        Intrinsic                      :: exp
!       .. Executable Statements ..
        ts = ruser(1)
        Do i = 1, npts
          u(i) = exp(ts*(one-x(i))) - one
        End Do
        u(neqn) = ts
        Return
      End Subroutine uvinit
      Subroutine odedef(npde,t,ncode,v,vdot,nxi,xi,ucp,ucpx,rcp,ucpt,ucptx,f,  &
        ires,iuser,ruser)

!       .. Scalar Arguments ..
        Real (Kind=nag_wp), Intent (In) :: t
        Integer, Intent (Inout)        :: ires
        Integer, Intent (In)           :: ncode, npde, nxi
!       .. Array Arguments ..
        Real (Kind=nag_wp), Intent (Out) :: f(ncode)
        Real (Kind=nag_wp), Intent (In) :: rcp(npde,*), ucp(npde,*),           &
                                          ucpt(npde,*), ucptx(npde,*),         &
                                          ucpx(npde,*), v(ncode), vdot(ncode), &
                                          xi(nxi)
        Real (Kind=nag_wp), Intent (Inout) :: ruser(*)
        Integer, Intent (Inout)        :: iuser(*)
!       .. Executable Statements ..
        If (ires==1) Then
          f(1) = vdot(1) - v(1)*ucp(1,1) - ucpx(1,1) - one - t
        Else If (ires==-1) Then
          f(1) = vdot(1)
        End If
        Return
      End Subroutine odedef
      Subroutine pdedef(npde,t,x,u,ux,ncode,v,vdot,p,q,r,ires,iuser,ruser)

!       .. Scalar Arguments ..
        Real (Kind=nag_wp), Intent (In) :: t, x
        Integer, Intent (Inout)        :: ires
        Integer, Intent (In)           :: ncode, npde
!       .. Array Arguments ..
        Real (Kind=nag_wp), Intent (Out) :: p(npde,npde), q(npde), r(npde)
        Real (Kind=nag_wp), Intent (Inout) :: ruser(*)
        Real (Kind=nag_wp), Intent (In) :: u(npde), ux(npde), v(ncode),        &
                                          vdot(ncode)
        Integer, Intent (Inout)        :: iuser(*)
!       .. Executable Statements ..
        p(1,1) = v(1)*v(1)
        r(1) = ux(1)
        q(1) = -x*ux(1)*v(1)*vdot(1)
        Return
      End Subroutine pdedef
      Subroutine bndary(npde,t,u,ux,ncode,v,vdot,ibnd,beta,gamma,ires,iuser,   &
        ruser)

!       .. Scalar Arguments ..
        Real (Kind=nag_wp), Intent (In) :: t
        Integer, Intent (In)           :: ibnd, ncode, npde
        Integer, Intent (Inout)        :: ires
!       .. Array Arguments ..
        Real (Kind=nag_wp), Intent (Out) :: beta(npde), gamma(npde)
        Real (Kind=nag_wp), Intent (Inout) :: ruser(*)
        Real (Kind=nag_wp), Intent (In) :: u(npde), ux(npde), v(ncode),        &
                                          vdot(ncode)
        Integer, Intent (Inout)        :: iuser(*)
!       .. Intrinsic Procedures ..
        Intrinsic                      :: exp
!       .. Executable Statements ..
        beta(1) = one
        If (ibnd==0) Then
          gamma(1) = -v(1)*exp(t)
        Else
          gamma(1) = -v(1)*vdot(1)
        End If
        Return
      End Subroutine bndary
    End Module d03phae_mod
    Program d03phae

!     D03PHA Example Main Program

!     .. Use Statements ..
      Use nag_library, Only: d03pha, nag_wp
      Use d03phae_mod, Only: bndary, itrace, ncode, nin, nout, npde, nxi,      &
                             odedef, pdedef, print_stat, uvinit
!     .. Implicit None Statement ..
      Implicit None
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: tout, ts
      Integer                          :: i, ifail, ind, it, itask, itol,      &
                                          latol, lenode, lrtol, m, neqn, niw,  &
                                          npts, nw, nwkres
      Logical                          :: theta
      Character (1)                    :: laopt, norm
!     .. Local Arrays ..
      Real (Kind=nag_wp)               :: algopt(30), ruser(1), rwsav(1100),   &
                                          xi(nxi)
      Real (Kind=nag_wp), Allocatable  :: atol(:), rtol(:), u(:), w(:), x(:)
      Integer                          :: iuser(1), iwsav(505)
      Integer, Allocatable             :: iw(:)
      Logical                          :: lwsav(100)
      Character (80)                   :: cwsav(10)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: mod, real
!     .. Executable Statements ..
      Write (nout,*) 'D03PHA Example Program Results'
!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) m, npts
      neqn = npde*npts + ncode
      nwkres = npde*(npts+6*nxi+3*npde+15) + ncode + nxi + 7*npts + 2
      lenode = 11*neqn + 50
      nw = neqn*neqn + neqn + nwkres + lenode
      niw = 25*neqn + 24

      Allocate (u(neqn),w(nw),x(npts),iw(niw))

      Read (nin,*) itol
      latol = 1
      lrtol = 1
      If (itol>2) Then
        latol = neqn
      End If
      If (mod(itol,2)==0) Then
        lrtol = neqn
      End If
      Allocate (atol(latol),rtol(lrtol))
      Read (nin,*) atol(1:latol), rtol(1:lrtol)

      ts = 1.0E-4_nag_wp

!     Set break-points
      Do i = 1, npts
        x(i) = real(i-1,kind=nag_wp)/real(npts-1,kind=nag_wp)
      End Do

      Read (nin,*) xi(1:nxi)
      Read (nin,*) norm, laopt
      ind = 0
      itask = 1

!     Set theta to .TRUE. if the Theta integrator is required
      theta = .False.
      algopt(1:30) = 0.0_nag_wp
      If (theta) Then
        algopt(1) = 2.0_nag_wp
      End If

!     Loop over output value of t

      ruser(1) = ts
      Call uvinit(npde,npts,x,u,ncode,neqn,iuser,ruser)

      Write (nout,99998)
      Write (nout,99997) atol
      Write (nout,99996) npts
      Write (nout,99999)

      tout = 0.2_nag_wp
      Do it = 1, 5

!       ifail: behaviour on error exit
!              =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
        ifail = 0
        Call d03pha(npde,m,ruser(1),tout,pdedef,bndary,u,npts,x,ncode,odedef,  &
          nxi,xi,neqn,rtol,atol,itol,norm,laopt,algopt,w,nw,iw,niw,itask,      &
          itrace,ind,iuser,ruser,cwsav,lwsav,iwsav,rwsav,ifail)

        Write (nout,99995) ruser(1), u(1)
!       Select next time to solve to for output.
        tout = 2.0_nag_wp*tout
      End Do
!     Print integration statistics (reasonably rounded)
      If (print_stat) Then
        Write (nout,*)
        Write (nout,99994) 'time steps', iw(1)
        Write (nout,99994) 'function evaluations', iw(2)
        Write (nout,99994) 'Jacobian evaluations', iw(3)
        Write (nout,99994) 'iterations', iw(5)
      End If
99999 Format (3X,'time',8X,'solution at x=0')
99998 Format (/,/,' Simple coupled PDE using BDF')
99997 Format (' Local Accuracy        = ',1P,E12.3)
99996 Format (' Number of mesh points = ',I4,/)
99995 Format (1X,F6.1,14X,F6.2)
99994 Format (' Number of ',A20,' = ',I6)
    End Program d03phae


d03phfe.f90

!   D03PHF Example Program Text
!   Mark 26 Release. NAG Copyright 2016.

    Module d03phfe_mod

!     D03PHF Example Program Module:
!            Parameters and User-defined Routines

!     .. Use Statements ..
      Use nag_library, Only: nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Accessibility Statements ..
      Private
      Public                           :: bndary, odedef, pdedef, uvinit
!     .. Parameters ..
      Real (Kind=nag_wp), Parameter    :: one = 1.0_nag_wp
      Integer, Parameter, Public       :: itrace = 0, ncode = 1, nin = 5,      &
                                          nout = 6, npde = 1, nxi = 1
      Logical, Parameter, Public       :: print_stat = .False.
!     .. Local Scalars ..
      Real (Kind=nag_wp), Public, Save :: ts
    Contains
      Subroutine odedef(npde,t,ncode,v,vdot,nxi,xi,ucp,ucpx,rcp,ucpt,ucptx,f,  &
        ires)

!       .. Scalar Arguments ..
        Real (Kind=nag_wp), Intent (In) :: t
        Integer, Intent (Inout)        :: ires
        Integer, Intent (In)           :: ncode, npde, nxi
!       .. Array Arguments ..
        Real (Kind=nag_wp), Intent (Out) :: f(ncode)
        Real (Kind=nag_wp), Intent (In) :: rcp(npde,*), ucp(npde,*),           &
                                          ucpt(npde,*), ucptx(npde,*),         &
                                          ucpx(npde,*), v(ncode), vdot(ncode), &
                                          xi(nxi)
!       .. Executable Statements ..
        If (ires==1) Then
          f(1) = vdot(1) - v(1)*ucp(1,1) - ucpx(1,1) - one - t
        Else If (ires==-1) Then
          f(1) = vdot(1)
        End If
        Return
      End Subroutine odedef
      Subroutine pdedef(npde,t,x,u,ux,ncode,v,vdot,p,q,r,ires)

!       .. Scalar Arguments ..
        Real (Kind=nag_wp), Intent (In) :: t, x
        Integer, Intent (Inout)        :: ires
        Integer, Intent (In)           :: ncode, npde
!       .. Array Arguments ..
        Real (Kind=nag_wp), Intent (Out) :: p(npde,npde), q(npde), r(npde)
        Real (Kind=nag_wp), Intent (In) :: u(npde), ux(npde), v(ncode),        &
                                          vdot(ncode)
!       .. Executable Statements ..
        p(1,1) = v(1)*v(1)
        r(1) = ux(1)
        q(1) = -x*ux(1)*v(1)*vdot(1)
        Return
      End Subroutine pdedef
      Subroutine bndary(npde,t,u,ux,ncode,v,vdot,ibnd,beta,gamma,ires)

!       .. Scalar Arguments ..
        Real (Kind=nag_wp), Intent (In) :: t
        Integer, Intent (In)           :: ibnd, ncode, npde
        Integer, Intent (Inout)        :: ires
!       .. Array Arguments ..
        Real (Kind=nag_wp), Intent (Out) :: beta(npde), gamma(npde)
        Real (Kind=nag_wp), Intent (In) :: u(npde), ux(npde), v(ncode),        &
                                          vdot(ncode)
!       .. Intrinsic Procedures ..
        Intrinsic                      :: exp
!       .. Executable Statements ..
        beta(1) = one
        If (ibnd==0) Then
          gamma(1) = -v(1)*exp(t)
        Else
          gamma(1) = -v(1)*vdot(1)
        End If
        Return
      End Subroutine bndary
      Subroutine uvinit(npde,npts,x,u,ncode,neqn)

!       Routine for PDE initial values

!       .. Scalar Arguments ..
        Integer, Intent (In)           :: ncode, neqn, npde, npts
!       .. Array Arguments ..
        Real (Kind=nag_wp), Intent (Out) :: u(neqn)
        Real (Kind=nag_wp), Intent (In) :: x(npts)
!       .. Local Scalars ..
        Integer                        :: i
!       .. Intrinsic Procedures ..
        Intrinsic                      :: exp
!       .. Executable Statements ..
        Do i = 1, npts
          u(i) = exp(ts*(one-x(i))) - one
        End Do
        u(neqn) = ts
        Return
      End Subroutine uvinit
    End Module d03phfe_mod
    Program d03phfe

!     D03PHF Example Main Program

!     .. Use Statements ..
      Use nag_library, Only: d03phf, nag_wp
      Use d03phfe_mod, Only: bndary, itrace, ncode, nin, nout, npde, nxi,      &
                             odedef, pdedef, print_stat, ts, uvinit
!     .. Implicit None Statement ..
      Implicit None
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: tout
      Integer                          :: i, ifail, ind, it, itask, itol,      &
                                          latol, lenode, lisave, lrsave,       &
                                          lrtol, m, neqn, npts, nwkres
      Logical                          :: theta
      Character (1)                    :: laopt, norm
!     .. Local Arrays ..
      Real (Kind=nag_wp)               :: algopt(30), xi(nxi)
      Real (Kind=nag_wp), Allocatable  :: atol(:), rsave(:), rtol(:), u(:),    &
                                          x(:)
      Integer, Allocatable             :: isave(:)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: mod, real
!     .. Executable Statements ..
      Write (nout,*) 'D03PHF Example Program Results'
!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) m, npts
      neqn = npde*npts + ncode
      nwkres = npde*(npts+6*nxi+3*npde+15) + ncode + nxi + 7*npts + 2
      lenode = 11*neqn + 50
      lrsave = neqn*neqn + neqn + nwkres + lenode
      lisave = 25*neqn + 24

      Allocate (u(neqn),rsave(lrsave),x(npts),isave(lisave))

      Read (nin,*) itol
      latol = 1
      lrtol = 1
      If (itol>2) Then
        latol = neqn
      End If
      If (mod(itol,2)==0) Then
        lrtol = neqn
      End If
      Allocate (atol(latol),rtol(lrtol))
      Read (nin,*) atol(1:latol), rtol(1:lrtol)

      Read (nin,*) ts

!     Set break-points
      Do i = 1, npts
        x(i) = real(i-1,kind=nag_wp)/real(npts-1,kind=nag_wp)
      End Do

      Read (nin,*) xi(1:nxi)
      Read (nin,*) norm, laopt
      ind = 0
      itask = 1

!     Set theta to .TRUE. if the Theta integrator is required
      theta = .False.
      algopt(1:30) = 0.0_nag_wp
      If (theta) Then
        algopt(1) = 2.0_nag_wp
      End If

!     Loop over output value of t

      Call uvinit(npde,npts,x,u,ncode,neqn)

      Write (nout,99998)
      Write (nout,99997) atol
      Write (nout,99996) npts
      Write (nout,99999)

      tout = 0.2_nag_wp
      Do it = 1, 5

!       ifail: behaviour on error exit
!              =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
        ifail = 0
        Call d03phf(npde,m,ts,tout,pdedef,bndary,u,npts,x,ncode,odedef,nxi,xi, &
          neqn,rtol,atol,itol,norm,laopt,algopt,rsave,lrsave,isave,lisave,     &
          itask,itrace,ind,ifail)

        Write (nout,99995) ts, u(1)
        tout = 2.0_nag_wp*tout
      End Do
      If (print_stat) Then
        Write (nout,*)
        Write (nout,99994) 'time steps', isave(1)
        Write (nout,99994) 'function evaluations', isave(2)
        Write (nout,99994) 'Jacobian evaluations', isave(3)
        Write (nout,99994) 'iterations', isave(5)
      End If

99999 Format (3X,'time',8X,'solution at x=0')
99998 Format (/,/,' Simple coupled PDE using BDF')
99997 Format (' Local Accuracy        = ',1P,E12.3)
99996 Format (' Number of mesh points = ',I4,/)
99995 Format (1X,F6.1,14X,F6.2)
99994 Format (' Number of ',A20,' = ',I6)
    End Program d03phfe


d03pjae.f90

!   D03PJA Example Program Text
!   Mark 26 Release. NAG Copyright 2016.

    Module d03pjae_mod

!     D03PJA Example Program Module:
!            Parameters and User-defined Routines

!     .. Use Statements ..
      Use nag_library, Only: nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Accessibility Statements ..
      Private
      Public                           :: bndary, odedef, pdedef, uvinit
!     .. Parameters ..
      Real (Kind=nag_wp), Parameter    :: one = 1.0_nag_wp
      Integer, Parameter, Public       :: itrace = 0, ncode = 1, nin = 5,      &
                                          nout = 6, npde = 1, nxi = 1
      Logical, Parameter, Public       :: print_stat = .False.
    Contains
      Subroutine uvinit(npde,npts,x,u,ncode,v,iuser,ruser)
!       Routine for PDE initial values (start time is 0.1D-6)

!       .. Scalar Arguments ..
        Integer, Intent (In)           :: ncode, npde, npts
!       .. Array Arguments ..
        Real (Kind=nag_wp), Intent (Inout) :: ruser(*)
        Real (Kind=nag_wp), Intent (Out) :: u(npde,npts), v(ncode)
        Real (Kind=nag_wp), Intent (In) :: x(npts)
        Integer, Intent (Inout)        :: iuser(*)
!       .. Local Scalars ..
        Real (Kind=nag_wp)             :: ts
        Integer                        :: i
!       .. Intrinsic Procedures ..
        Intrinsic                      :: exp
!       .. Executable Statements ..
        ts = ruser(1)
        v(1) = ts
        Do i = 1, npts
          u(1,i) = exp(ts*(one-x(i))) - one
        End Do
        Return
      End Subroutine uvinit
      Subroutine odedef(npde,t,ncode,v,vdot,nxi,xi,ucp,ucpx,rcp,ucpt,ucptx,f,  &
        ires,iuser,ruser)

!       .. Scalar Arguments ..
        Real (Kind=nag_wp), Intent (In) :: t
        Integer, Intent (Inout)        :: ires
        Integer, Intent (In)           :: ncode, npde, nxi
!       .. Array Arguments ..
        Real (Kind=nag_wp), Intent (Out) :: f(ncode)
        Real (Kind=nag_wp), Intent (In) :: rcp(npde,*), ucp(npde,*),           &
                                          ucpt(npde,*), ucptx(npde,*),         &
                                          ucpx(npde,*), v(ncode), vdot(ncode), &
                                          xi(nxi)
        Real (Kind=nag_wp), Intent (Inout) :: ruser(*)
        Integer, Intent (Inout)        :: iuser(*)
!       .. Executable Statements ..
        If (ires==1) Then
          f(1) = vdot(1) - v(1)*ucp(1,1) - ucpx(1,1) - one - t
        Else If (ires==-1) Then
          f(1) = vdot(1)
        End If
        Return
      End Subroutine odedef
      Subroutine pdedef(npde,t,x,nptl,u,ux,ncode,v,vdot,p,q,r,ires,iuser,      &
        ruser)

!       .. Scalar Arguments ..
        Real (Kind=nag_wp), Intent (In) :: t
        Integer, Intent (Inout)        :: ires
        Integer, Intent (In)           :: ncode, npde, nptl
!       .. Array Arguments ..
        Real (Kind=nag_wp), Intent (Out) :: p(npde,npde,nptl), q(npde,nptl),   &
                                          r(npde,nptl)
        Real (Kind=nag_wp), Intent (Inout) :: ruser(*)
        Real (Kind=nag_wp), Intent (In) :: u(npde,nptl), ux(npde,nptl),        &
                                          v(ncode), vdot(ncode), x(nptl)
        Integer, Intent (Inout)        :: iuser(*)
!       .. Local Scalars ..
        Integer                        :: i
!       .. Executable Statements ..
        Do i = 1, nptl
          p(1,1,i) = v(1)*v(1)
          r(1,i) = ux(1,i)
          q(1,i) = -x(i)*ux(1,i)*v(1)*vdot(1)
        End Do
        Return
      End Subroutine pdedef
      Subroutine bndary(npde,t,u,ux,ncode,v,vdot,ibnd,beta,gamma,ires,iuser,   &
        ruser)

!       .. Scalar Arguments ..
        Real (Kind=nag_wp), Intent (In) :: t
        Integer, Intent (In)           :: ibnd, ncode, npde
        Integer, Intent (Inout)        :: ires
!       .. Array Arguments ..
        Real (Kind=nag_wp), Intent (Out) :: beta(npde), gamma(npde)
        Real (Kind=nag_wp), Intent (Inout) :: ruser(*)
        Real (Kind=nag_wp), Intent (In) :: u(npde), ux(npde), v(ncode),        &
                                          vdot(ncode)
        Integer, Intent (Inout)        :: iuser(*)
!       .. Intrinsic Procedures ..
        Intrinsic                      :: exp
!       .. Executable Statements ..
        beta(1) = one
        If (ibnd==0) Then
          gamma(1) = -v(1)*exp(t)
        Else
          gamma(1) = -v(1)*vdot(1)
        End If
        Return
      End Subroutine bndary
    End Module d03pjae_mod
    Program d03pjae

!     D03PJA Example Main Program

!     .. Use Statements ..
      Use nag_library, Only: d03pja, nag_wp
      Use d03pjae_mod, Only: bndary, itrace, ncode, nin, nout, npde, nxi,      &
                             odedef, pdedef, print_stat, uvinit
!     .. Implicit None Statement ..
      Implicit None
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: tout, ts
      Integer                          :: i, ifail, ind, it, itask, itol,      &
                                          latol, lenode, lrtol, m, nbkpts,     &
                                          nel, neqn, niw, npl1, npoly, npts,   &
                                          nw, nwkres
      Logical                          :: theta
      Character (1)                    :: laopt, norm
!     .. Local Arrays ..
      Real (Kind=nag_wp)               :: algopt(30), ruser(1), rwsav(1100),   &
                                          xi(nxi)
      Real (Kind=nag_wp), Allocatable  :: atol(:), rtol(:), u(:), w(:), x(:),  &
                                          xbkpts(:)
      Integer                          :: iuser(1), iwsav(505)
      Integer, Allocatable             :: iw(:)
      Logical                          :: lwsav(100)
      Character (80)                   :: cwsav(10)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: mod, real
!     .. Executable Statements ..
      Write (nout,*) 'D03PJA Example Program Results'
!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) m, nbkpts, npoly

      nel = nbkpts - 1
      npts = nel*npoly + 1
      neqn = npde*npts + ncode
      npl1 = npoly + 1
      nwkres = 3*npl1*npl1 + npl1*(npde*npde+6*npde+nbkpts+1) + 8*npde +       &
        nxi*(5*npde+1) + ncode + 3
      lenode = 11*neqn + 50
      nw = neqn*neqn + neqn + nwkres + lenode
      niw = 25*neqn + 24
      Allocate (u(neqn),w(nw),x(npts),xbkpts(nbkpts),iw(niw))

      Read (nin,*) itol
      latol = 1
      lrtol = 1
      If (itol>2) Then
        latol = neqn
      End If
      If (mod(itol,2)==0) Then
        lrtol = neqn
      End If
      Allocate (atol(latol),rtol(lrtol))
      Read (nin,*) atol(1:latol), rtol(1:lrtol)
!     Set break-points
      Do i = 1, nbkpts
        xbkpts(i) = real(i-1,kind=nag_wp)/real(nbkpts-1,kind=nag_wp)
      End Do

      Read (nin,*) xi(1:nxi)
      Read (nin,*) norm, laopt
      ind = 0
      itask = 1

!     Set theta to .TRUE. if the Theta integrator is required

      theta = .False.
      algopt(1:30) = 0.0E0_nag_wp
      If (theta) Then
        algopt(1) = 2.0E0_nag_wp
      End If
      ruser(1) = 1.0E-4_nag_wp

      Write (nout,99998)
      Write (nout,99997) atol(1)
      Write (nout,99996) npoly
      Write (nout,99995) nel
      Write (nout,99994) npts
      Write (nout,99999)

      rwsav(1:1100) = 0.0_nag_wp
!     Output value solution at t = 0.1*(2**k) for k=1,2,...,5

      tout = 0.1E0_nag_wp
      Do it = 1, 5
        tout = tout + tout

!       ifail: behaviour on error exit
!              =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
        ifail = 0
        Call d03pja(npde,m,ruser(1),tout,pdedef,bndary,u,nbkpts,xbkpts,npoly,  &
          npts,x,ncode,odedef,nxi,xi,neqn,uvinit,rtol,atol,itol,norm,laopt,    &
          algopt,w,nw,iw,niw,itask,itrace,ind,iuser,ruser,cwsav,lwsav,iwsav,   &
          rwsav,ifail)

        ts = ruser(1)
        Write (nout,99993) ts, u(1)
      End Do

!     Print integration statistics (reasonably rounded)
      If (print_stat) Then
        Write (nout,*)
        Write (nout,99992) 'time steps', iw(1)
        Write (nout,99992) 'function evaluations', iw(2)
        Write (nout,99992) 'Jacobian evaluations', iw(3)
        Write (nout,99992) 'iterations', iw(5)
      End If

99999 Format (3X,'time',8X,'solution at x=0')
99998 Format (/,/,' Simple coupled PDE using BDF')
99997 Format (' Local Accuracy        = ',1P,E12.3)
99996 Format (' Degree of Polynomial  = ',I4)
99995 Format (' Number of elements    = ',I4)
99994 Format (' Number of mesh points = ',I4,/)
99993 Format (1X,F6.1,14X,F6.2)
99992 Format (' Number of ',A20,' = ',I6)
    End Program d03pjae


d03pjfe.f90

!   D03PJF Example Program Text
!   Mark 26 Release. NAG Copyright 2016.

    Module d03pjfe_mod

!     D03PJF Example Program Module:
!            Parameters and User-defined Routines

!     .. Use Statements ..
      Use nag_library, Only: nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Accessibility Statements ..
      Private
      Public                           :: bndary, odedef, pdedef, uvinit
!     .. Parameters ..
      Real (Kind=nag_wp), Parameter    :: one = 1.0_nag_wp
      Integer, Parameter, Public       :: itrace = 0, ncode = 1, nin = 5,      &
                                          nout = 6, npde = 1, nxi = 1
      Logical, Parameter, Public       :: print_stat = .False.
!     .. Local Scalars ..
      Real (Kind=nag_wp), Public, Save :: ts
    Contains
      Subroutine uvinit(npde,npts,x,u,ncode,v)

!       Routine for PDE initial values (start time is 0.1D-6)

!       .. Scalar Arguments ..
        Integer, Intent (In)           :: ncode, npde, npts
!       .. Array Arguments ..
        Real (Kind=nag_wp), Intent (Out) :: u(npde,npts), v(ncode)
        Real (Kind=nag_wp), Intent (In) :: x(npts)
!       .. Local Scalars ..
        Integer                        :: i
!       .. Intrinsic Procedures ..
        Intrinsic                      :: exp
!       .. Executable Statements ..
        v(1) = ts
        Do i = 1, npts
          u(1,i) = exp(ts*(one-x(i))) - one
        End Do
        Return
      End Subroutine uvinit
      Subroutine odedef(npde,t,ncode,v,vdot,nxi,xi,ucp,ucpx,rcp,ucpt,ucptx,f,  &
        ires)

!       .. Scalar Arguments ..
        Real (Kind=nag_wp), Intent (In) :: t
        Integer, Intent (Inout)        :: ires
        Integer, Intent (In)           :: ncode, npde, nxi
!       .. Array Arguments ..
        Real (Kind=nag_wp), Intent (Out) :: f(ncode)
        Real (Kind=nag_wp), Intent (In) :: rcp(npde,*), ucp(npde,*),           &
                                          ucpt(npde,*), ucptx(npde,*),         &
                                          ucpx(npde,*), v(ncode), vdot(ncode), &
                                          xi(nxi)
!       .. Executable Statements ..
        If (ires==1) Then
          f(1) = vdot(1) - v(1)*ucp(1,1) - ucpx(1,1) - one - t
        Else If (ires==-1) Then
          f(1) = vdot(1)
        End If
        Return
      End Subroutine odedef
      Subroutine pdedef(npde,t,x,nptl,u,ux,ncode,v,vdot,p,q,r,ires)

!       .. Scalar Arguments ..
        Real (Kind=nag_wp), Intent (In) :: t
        Integer, Intent (Inout)        :: ires
        Integer, Intent (In)           :: ncode, npde, nptl
!       .. Array Arguments ..
        Real (Kind=nag_wp), Intent (Out) :: p(npde,npde,nptl), q(npde,nptl),   &
                                          r(npde,nptl)
        Real (Kind=nag_wp), Intent (In) :: u(npde,nptl), ux(npde,nptl),        &
                                          v(ncode), vdot(ncode), x(nptl)
!       .. Local Scalars ..
        Integer                        :: i
!       .. Executable Statements ..
        Do i = 1, nptl
          p(1,1,i) = v(1)*v(1)
          r(1,i) = ux(1,i)
          q(1,i) = -x(i)*ux(1,i)*v(1)*vdot(1)
        End Do
        Return
      End Subroutine pdedef
      Subroutine bndary(npde,t,u,ux,ncode,v,vdot,ibnd,beta,gamma,ires)

!       .. Scalar Arguments ..
        Real (Kind=nag_wp), Intent (In) :: t
        Integer, Intent (In)           :: ibnd, ncode, npde
        Integer, Intent (Inout)        :: ires
!       .. Array Arguments ..
        Real (Kind=nag_wp), Intent (Out) :: beta(npde), gamma(npde)
        Real (Kind=nag_wp), Intent (In) :: u(npde), ux(npde), v(ncode),        &
                                          vdot(ncode)
!       .. Intrinsic Procedures ..
        Intrinsic                      :: exp
!       .. Executable Statements ..
        beta(1) = 1.0E0_nag_wp
        If (ibnd==0) Then
          gamma(1) = -v(1)*exp(t)
        Else
          gamma(1) = -v(1)*vdot(1)
        End If
        Return
      End Subroutine bndary
    End Module d03pjfe_mod
    Program d03pjfe

!     D03PJF Example Main Program

!     .. Use Statements ..
      Use nag_library, Only: d03pjf, nag_wp
      Use d03pjfe_mod, Only: bndary, itrace, ncode, nin, nout, npde, nxi,      &
                             odedef, pdedef, print_stat, ts, uvinit
!     .. Implicit None Statement ..
      Implicit None
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: tout
      Integer                          :: i, ifail, ind, it, itask, itol,      &
                                          latol, lenode, lisave, lrsave,       &
                                          lrtol, m, nbkpts, nel, neqn, np1,    &
                                          npoly, npts, nwkres
      Logical                          :: theta
      Character (1)                    :: laopt, norm
!     .. Local Arrays ..
      Real (Kind=nag_wp)               :: algopt(30), xi(nxi)
      Real (Kind=nag_wp), Allocatable  :: atol(:), rsave(:), rtol(:), u(:),    &
                                          x(:), xbkpts(:)
      Integer, Allocatable             :: isave(:)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: mod, real
!     .. Executable Statements ..
      Write (nout,*) 'D03PJF Example Program Results'
!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) m, nbkpts, npoly

      nel = nbkpts - 1
      npts = nel*npoly + 1
      neqn = npde*npts + ncode
      np1 = npoly + 1
      nwkres = np1*(3*np1+npde*npde+6*npde+nbkpts+1)
      nwkres = nwkres + 8*npde + nxi*(5*npde+1) + ncode + 3
      lenode = 11*neqn + 50
      lisave = 25*neqn + 24
      lrsave = neqn*neqn + neqn + nwkres + lenode
      Allocate (u(neqn),rsave(lrsave),x(npts),xbkpts(nbkpts),isave(lisave))

      Read (nin,*) itol
      latol = 1
      lrtol = 1
      If (itol>2) Then
        latol = neqn
      End If
      If (mod(itol,2)==0) Then
        lrtol = neqn
      End If
      Allocate (atol(latol),rtol(lrtol))
      Read (nin,*) atol(1:latol), rtol(1:lrtol)

      Read (nin,*) ts

!     Set break-points
      Do i = 1, nbkpts
        xbkpts(i) = real(i-1,kind=nag_wp)/real(nbkpts-1,kind=nag_wp)
      End Do

      Read (nin,*) xi(1:nxi)
      Read (nin,*) norm, laopt
      ind = 0
      itask = 1

!     Set theta to .TRUE. if the Theta integrator is required
      theta = .False.
      algopt(1:30) = 0.0_nag_wp
      If (theta) Then
        algopt(1) = 2.0_nag_wp
      End If

      Write (nout,99998)
      Write (nout,99997) atol
      Write (nout,99996) npoly
      Write (nout,99995) nel
      Write (nout,99994) npts
      Write (nout,99999)

!     Output value solution at t = 0.1*(2**k) for k=1,2,...,5

      tout = 0.1_nag_wp
      Do it = 1, 5
        tout = tout + tout

!       ifail: behaviour on error exit
!              =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
        ifail = 0
        Call d03pjf(npde,m,ts,tout,pdedef,bndary,u,nbkpts,xbkpts,npoly,npts,x, &
          ncode,odedef,nxi,xi,neqn,uvinit,rtol,atol,itol,norm,laopt,algopt,    &
          rsave,lrsave,isave,lisave,itask,itrace,ind,ifail)

        Write (nout,99993) ts, u(1)
      End Do

      If (print_stat) Then
        Write (nout,*)
        Write (nout,99992) 'time steps', isave(1)
        Write (nout,99992) 'function evaluations', isave(2)
        Write (nout,99992) 'Jacobian evaluations', isave(3)
        Write (nout,99992) 'iterations', isave(5)
      End If

99999 Format (3X,'time',8X,'solution at x=0')
99998 Format (/,/,' Simple coupled PDE using BDF')
99997 Format (' Accuracy requirement  = ',1P,E12.3)
99996 Format (' Degree of Polynomial  = ',I4)
99995 Format (' Number of elements    = ',I4)
99994 Format (' Number of mesh points = ',I4,/)
99993 Format (1X,F6.1,14X,F6.2)
99992 Format (' Number of ',A20,' = ',I6)
    End Program d03pjfe


d03pkfe.f90

!   D03PKF Example Program Text
!   Mark 26 Release. NAG Copyright 2016.

    Module d03pkfe_mod

!     D03PKF Example Program Module:
!            Parameters and User-defined Routines

!     .. Use Statements ..
      Use nag_library, Only: nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Accessibility Statements ..
      Private
      Public                           :: bndary, exact, odedef, pdedef,       &
                                          uvinit
!     .. Parameters ..
      Real (Kind=nag_wp), Parameter, Public :: one = 1.0_nag_wp
      Integer, Parameter, Public       :: itrace = 0, ncode = 1, nin = 5,      &
                                          nleft = 1, nout = 6, npde = 2,       &
                                          nxi = 1
!     .. Local Scalars ..
      Real (Kind=nag_wp), Public, Save :: ts
    Contains
      Subroutine odedef(npde,t,ncode,v,vdot,nxi,xi,ucp,ucpx,ucpt,r,ires)

!       .. Scalar Arguments ..
        Real (Kind=nag_wp), Intent (In) :: t
        Integer, Intent (Inout)        :: ires
        Integer, Intent (In)           :: ncode, npde, nxi
!       .. Array Arguments ..
        Real (Kind=nag_wp), Intent (Out) :: r(ncode)
        Real (Kind=nag_wp), Intent (In) :: ucp(npde,*), ucpt(npde,*),          &
                                          ucpx(npde,*), v(ncode), vdot(ncode), &
                                          xi(nxi)
!       .. Executable Statements ..
        If (ires==-1) Then
          r(1) = vdot(1)
        Else
          r(1) = vdot(1) - v(1)*ucp(1,1) - ucp(2,1) - one - t
        End If
        Return
      End Subroutine odedef
      Subroutine pdedef(npde,t,x,u,ut,ux,ncode,v,vdot,res,ires)

!       .. Scalar Arguments ..
        Real (Kind=nag_wp), Intent (In) :: t, x
        Integer, Intent (Inout)        :: ires
        Integer, Intent (In)           :: ncode, npde
!       .. Array Arguments ..
        Real (Kind=nag_wp), Intent (Out) :: res(npde)
        Real (Kind=nag_wp), Intent (In) :: u(npde), ut(npde), ux(npde),        &
                                          v(ncode), vdot(ncode)
!       .. Executable Statements ..
        If (ires==-1) Then
          res(1) = v(1)*v(1)*ut(1) - x*u(2)*v(1)*vdot(1)
          res(2) = 0.0_nag_wp
        Else
          res(1) = v(1)*v(1)*ut(1) - x*u(2)*v(1)*vdot(1) - ux(2)
          res(2) = u(2) - ux(1)
        End If
        Return
      End Subroutine pdedef
      Subroutine bndary(npde,t,ibnd,nobc,u,ut,ncode,v,vdot,res,ires)

!       .. Scalar Arguments ..
        Real (Kind=nag_wp), Intent (In) :: t
        Integer, Intent (In)           :: ibnd, ncode, nobc, npde
        Integer, Intent (Inout)        :: ires
!       .. Array Arguments ..
        Real (Kind=nag_wp), Intent (Out) :: res(nobc)
        Real (Kind=nag_wp), Intent (In) :: u(npde), ut(npde), v(ncode),        &
                                          vdot(ncode)
!       .. Intrinsic Procedures ..
        Intrinsic                      :: exp
!       .. Executable Statements ..
        If (ibnd==0) Then
          If (ires==-1) Then
            res(1) = 0.0_nag_wp
          Else
            res(1) = u(2) + v(1)*exp(t)
          End If
        Else
          If (ires==-1) Then
            res(1) = v(1)*vdot(1)
          Else
            res(1) = u(2) + v(1)*vdot(1)
          End If
        End If
        Return
      End Subroutine bndary
      Subroutine uvinit(npde,npts,x,u,ncode,neqn)

!       Routine for PDE initial values

!       .. Scalar Arguments ..
        Integer, Intent (In)           :: ncode, neqn, npde, npts
!       .. Array Arguments ..
        Real (Kind=nag_wp), Intent (Out) :: u(neqn)
        Real (Kind=nag_wp), Intent (In) :: x(npts)
!       .. Local Scalars ..
        Integer                        :: i, k
!       .. Intrinsic Procedures ..
        Intrinsic                      :: exp
!       .. Executable Statements ..
        k = 1
        Do i = 1, npts
          u(k) = exp(ts*(one-x(i))) - one
          u(k+1) = -ts*exp(ts*(one-x(i)))
          k = k + 2
        End Do
        u(neqn) = ts
        Return
      End Subroutine uvinit
      Subroutine exact(time,neqn,npts,x,u)
!       Exact solution (for comparison purposes)

!       .. Scalar Arguments ..
        Real (Kind=nag_wp), Intent (In) :: time
        Integer, Intent (In)           :: neqn, npts
!       .. Array Arguments ..
        Real (Kind=nag_wp), Intent (Out) :: u(neqn)
        Real (Kind=nag_wp), Intent (In) :: x(npts)
!       .. Local Scalars ..
        Integer                        :: i, k
!       .. Intrinsic Procedures ..
        Intrinsic                      :: exp
!       .. Executable Statements ..
        k = 1
        Do i = 1, npts
          u(k) = exp(time*(one-x(i))) - one
          k = k + 2
        End Do
        Return
      End Subroutine exact
    End Module d03pkfe_mod
    Program d03pkfe

!     .. Use Statements ..
      Use nag_library, Only: d03pkf, nag_wp
      Use d03pkfe_mod, Only: bndary, exact, itrace, ncode, nin, nleft, nout,   &
                             npde, nxi, odedef, one, pdedef, ts, uvinit
!     .. Implicit None Statement ..
      Implicit None
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: tout
      Integer                          :: i, ifail, ind, it, itask, itol,      &
                                          latol, lenode, lisave, lrsave,       &
                                          lrtol, neqn, npts, nwkres
      Character (1)                    :: laopt, norm
!     .. Local Arrays ..
      Real (Kind=nag_wp)               :: algopt(30), xi(nxi)
      Real (Kind=nag_wp), Allocatable  :: atol(:), exy(:), rsave(:), rtol(:),  &
                                          u(:), x(:)
      Integer, Allocatable             :: isave(:)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: mod, real
!     .. Executable Statements ..
      Write (nout,*) 'D03PKF Example Program Results'
!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) npts
      neqn = npde*npts + ncode
      nwkres = npde*(npts+6*nxi+3*npde+15) + ncode + nxi + 7*npts + 2
      lenode = 11*neqn + 50
      lisave = 25*neqn + 24
      lrsave = neqn*neqn + neqn + nwkres + lenode
      Allocate (exy(neqn),u(neqn),rsave(lrsave),x(npts),isave(lisave))

      Read (nin,*) itol
      latol = 1
      lrtol = 1
      If (itol>2) Then
        latol = neqn
      End If
      If (mod(itol,2)==0) Then
        lrtol = neqn
      End If
      Allocate (atol(latol),rtol(lrtol))
      Read (nin,*) atol(1:latol), rtol(1:lrtol)
      Read (nin,*) ts

!     Set spatial-mesh points
      Do i = 1, npts
        x(i) = real(i-1,kind=nag_wp)/real(npts-1,kind=nag_wp)
      End Do

      Read (nin,*) xi(1:nxi)
      Read (nin,*) norm, laopt
      ind = 0
      itask = 1

      algopt(1:30) = 0.0_nag_wp
      algopt(1) = one
      algopt(13) = 0.005_nag_wp

!     Loop over output value of t

      Call uvinit(npde,npts,x,u,ncode,neqn)

      tout = 0.2_nag_wp
      Do it = 1, 5
!       ifail: behaviour on error exit
!              =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
        ifail = 0
        Call d03pkf(npde,ts,tout,pdedef,bndary,u,npts,x,nleft,ncode,odedef,    &
          nxi,xi,neqn,rtol,atol,itol,norm,laopt,algopt,rsave,lrsave,isave,     &
          lisave,itask,itrace,ind,ifail)

        If (it==1) Then
          Write (nout,99997) atol, npts
          Write (nout,99999)(x(i),i=1,13,4), x(npts)
        End If

!       Check against the exact solution

        Call exact(tout,neqn,npts,x,exy)

        Write (nout,99998) ts
        Write (nout,99995)(u(i),i=1,25,4*npde), u(neqn-2), u(neqn)
        Write (nout,99994)(exy(i),i=1,25,4*npde), exy(neqn-2), ts
        tout = 2.0_nag_wp*tout
      End Do
      Write (nout,99996) isave(1), isave(2), isave(3), isave(5)

99999 Format ('  X        ',5F9.3,/)
99998 Format (' T = ',F6.3)
99997 Format (/,/,'  Accuracy requirement =',E10.3,' Number of points = ',I3,  &
        /)
99996 Format (' Number of integration steps in time = ',I6,/,' Number o',      &
        'f function evaluations = ',I6,/,' Number of Jacobian eval',           &
        'uations =',I6,/,' Number of iterations = ',I6)
99995 Format (1X,'App.  sol.  ',F7.3,4F9.3,'  ODE sol. =',F8.3)
99994 Format (1X,'Exact sol.  ',F7.3,4F9.3,'  ODE sol. =',F8.3,/)
    End Program d03pkfe


d03plfe.f90

!   D03PLF Example Program Text
!   Mark 26 Release. NAG Copyright 2016.

    Module d03plfe_mod

!     D03PLF Example Program Module:
!            Parameters and User-defined Routines

!     .. Use Statements ..
      Use nag_library, Only: nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Accessibility Statements ..
      Private
      Public                           :: bndry1, bndry2, exact, nmflx1,       &
                                          nmflx2, odedef, pdedef, uvinit
!     .. Parameters ..
      Real (Kind=nag_wp), Parameter, Public :: el0 = 2.5_nag_wp
      Real (Kind=nag_wp), Parameter, Public :: er0 = 0.25_nag_wp
      Real (Kind=nag_wp), Parameter, Public :: gamma = 1.4_nag_wp
      Real (Kind=nag_wp), Parameter, Public :: rl0 = 1.0_nag_wp
      Real (Kind=nag_wp), Parameter, Public :: rr0 = 0.125_nag_wp
      Integer, Parameter, Public       :: itrace = 0, ncode1 = 2, ncode2 = 0,  &
                                          nin = 5, nout = 6, npde1 = 2,        &
                                          npde2 = 3, nxi1 = 2, nxi2 = 0
    Contains
      Subroutine exact(t,u,npde,x,npts)
!       Exact solution (for comparison and b.c. purposes)

!       .. Use Statements ..
        Use nag_library, Only: x01aaf
!       .. Scalar Arguments ..
        Real (Kind=nag_wp), Intent (In) :: t
        Integer, Intent (In)           :: npde, npts
!       .. Array Arguments ..
        Real (Kind=nag_wp), Intent (Out) :: u(npde,npts)
        Real (Kind=nag_wp), Intent (In) :: x(*)
!       .. Local Scalars ..
        Real (Kind=nag_wp)             :: f, g, pi, pi2, x1, x3
        Integer                        :: i
!       .. Intrinsic Procedures ..
        Intrinsic                      :: cos, exp, sin
!       .. Executable Statements ..
        f = 0.0_nag_wp
        pi = x01aaf(f)
        pi2 = 2.0_nag_wp*pi
        Do i = 1, npts
          x1 = x(i) + t
          x3 = x(i) - 3.0_nag_wp*t
          f = exp(pi*x3)*sin(pi2*x3)
          g = exp(-pi2*x1)*cos(pi2*x1)
          u(1,i) = f + g
          u(2,i) = f - g
        End Do
        Return
      End Subroutine exact
      Subroutine pdedef(npde,t,x,u,ux,ncode,v,vdot,p,c,d,s,ires)

!       .. Scalar Arguments ..
        Real (Kind=nag_wp), Intent (In) :: t, x
        Integer, Intent (Inout)        :: ires
        Integer, Intent (In)           :: ncode, npde
!       .. Array Arguments ..
        Real (Kind=nag_wp), Intent (Out) :: c(npde), d(npde), p(npde,npde),    &
                                          s(npde)
        Real (Kind=nag_wp), Intent (In) :: u(npde), ux(npde), v(ncode),        &
                                          vdot(ncode)
!       .. Local Scalars ..
        Integer                        :: i
!       .. Executable Statements ..
        c(1:npde) = 1.0_nag_wp
        d(1:npde) = 0.0_nag_wp
        s(1:npde) = 0.0_nag_wp
        p(1:npde,1:npde) = 0.0_nag_wp
        Do i = 1, npde
          p(i,i) = 1.0_nag_wp
        End Do
        Return
      End Subroutine pdedef
      Subroutine bndry1(npde,npts,t,x,u,ncode,v,vdot,ibnd,g,ires)

!       .. Scalar Arguments ..
        Real (Kind=nag_wp), Intent (In) :: t
        Integer, Intent (In)           :: ibnd, ncode, npde, npts
        Integer, Intent (Inout)        :: ires
!       .. Array Arguments ..
        Real (Kind=nag_wp), Intent (Out) :: g(npde)
        Real (Kind=nag_wp), Intent (In) :: u(npde,npts), v(ncode),             &
                                          vdot(ncode), x(npts)
!       .. Local Scalars ..
        Real (Kind=nag_wp)             :: dudx
        Integer                        :: i
!       .. Local Arrays ..
        Real (Kind=nag_wp)             :: ue(2,1)
!       .. Executable Statements ..
        If (ibnd==0) Then
          i = 1
          Call exact(t,ue,npde,x(i),1)
          g(1) = u(1,i) + u(2,i) - ue(1,1) - ue(2,1)
          dudx = (u(1,i+1)-u(2,i+1)-u(1,i)+u(2,i))/(x(i+1)-x(i))
          g(2) = vdot(1) - dudx
        Else
          i = npts
          Call exact(t,ue,npde,x(i),1)
          g(1) = u(1,i) - u(2,i) - ue(1,1) + ue(2,1)
          dudx = (u(1,i)+u(2,i)-u(1,i-1)-u(2,i-1))/(x(i)-x(i-1))
          g(2) = vdot(2) + 3.0_nag_wp*dudx
        End If
        Return
      End Subroutine bndry1
      Subroutine nmflx1(npde,t,x,ncode,v,uleft,uright,flux,ires)

!       .. Scalar Arguments ..
        Real (Kind=nag_wp), Intent (In) :: t, x
        Integer, Intent (Inout)        :: ires
        Integer, Intent (In)           :: ncode, npde
!       .. Array Arguments ..
        Real (Kind=nag_wp), Intent (Out) :: flux(npde)
        Real (Kind=nag_wp), Intent (In) :: uleft(npde), uright(npde), v(ncode)
!       .. Local Scalars ..
        Real (Kind=nag_wp)             :: tmpl, tmpr
!       .. Executable Statements ..
        tmpl = 3.0_nag_wp*(uleft(1)+uleft(2))
        tmpr = uright(1) - uright(2)
        flux(1) = 0.5_nag_wp*(tmpl-tmpr)
        flux(2) = 0.5_nag_wp*(tmpl+tmpr)
        Return
      End Subroutine nmflx1
      Subroutine odedef(npde,t,ncode,v,vdot,nxi,xi,ucp,ucpx,ucpt,r,ires)

!       .. Scalar Arguments ..
        Real (Kind=nag_wp), Intent (In) :: t
        Integer, Intent (Inout)        :: ires
        Integer, Intent (In)           :: ncode, npde, nxi
!       .. Array Arguments ..
        Real (Kind=nag_wp), Intent (Out) :: r(ncode)
        Real (Kind=nag_wp), Intent (In) :: ucp(npde,*), ucpt(npde,*),          &
                                          ucpx(npde,*), v(ncode), vdot(ncode), &
                                          xi(nxi)
!       .. Executable Statements ..
        If (ires==-1) Then
          r(1) = 0.0_nag_wp
          r(2) = 0.0_nag_wp
        Else
          r(1) = v(1) - ucp(1,1) + ucp(2,1)
          r(2) = v(2) - ucp(1,2) - ucp(2,2)
        End If
        Return
      End Subroutine odedef
      Subroutine bndry2(npde,npts,t,x,u,ncode,v,vdot,ibnd,g,ires)

!       .. Scalar Arguments ..
        Real (Kind=nag_wp), Intent (In) :: t
        Integer, Intent (In)           :: ibnd, ncode, npde, npts
        Integer, Intent (Inout)        :: ires
!       .. Array Arguments ..
        Real (Kind=nag_wp), Intent (Out) :: g(npde)
        Real (Kind=nag_wp), Intent (In) :: u(npde,npts), v(ncode),             &
                                          vdot(ncode), x(npts)
!       .. Executable Statements ..
        If (ibnd==0) Then
          g(1) = u(1,1) - rl0
          g(2) = u(2,1)
          g(3) = u(3,1) - el0
        Else
          g(1) = u(1,npts) - rr0
          g(2) = u(2,npts)
          g(3) = u(3,npts) - er0
        End If
        Return
      End Subroutine bndry2
      Subroutine nmflx2(npde,t,x,ncode,v,uleft,uright,flux,ires)

!       .. Use Statements ..
        Use nag_library, Only: d03puf, d03pvf
!       .. Scalar Arguments ..
        Real (Kind=nag_wp), Intent (In) :: t, x
        Integer, Intent (Inout)        :: ires
        Integer, Intent (In)           :: ncode, npde
!       .. Array Arguments ..
        Real (Kind=nag_wp), Intent (Out) :: flux(npde)
        Real (Kind=nag_wp), Intent (In) :: uleft(npde), uright(npde), v(ncode)
!       .. Local Scalars ..
        Integer                        :: ifail
        Character (1)                  :: path, solver
!       .. Executable Statements ..
        ifail = 0
        solver = 'R'
        If (solver=='R') Then
!         ROE scheme ..
          Call d03puf(uleft,uright,gamma,flux,ifail)
        Else
!         OSHER scheme ..
          path = 'P'
          Call d03pvf(uleft,uright,gamma,path,flux,ifail)
        End If
        Return
      End Subroutine nmflx2
      Subroutine uvinit(npde,npts,x,u)

!       .. Scalar Arguments ..
        Integer, Intent (In)           :: npde, npts
!       .. Array Arguments ..
        Real (Kind=nag_wp), Intent (Out) :: u(npde,npts)
        Real (Kind=nag_wp), Intent (In) :: x(npts)
!       .. Local Scalars ..
        Integer                        :: i
!       .. Executable Statements ..
        Do i = 1, npts
          If (x(i)<0.5_nag_wp) Then
            u(1,i) = rl0
            u(2,i) = 0.0_nag_wp
            u(3,i) = el0
          Else If (x(i)==0.5_nag_wp) Then
            u(1,i) = 0.5_nag_wp*(rl0+rr0)
            u(2,i) = 0.0_nag_wp
            u(3,i) = 0.5_nag_wp*(el0+er0)
          Else
            u(1,i) = rr0
            u(2,i) = 0.0_nag_wp
            u(3,i) = er0
          End If
        End Do
        Return
      End Subroutine uvinit
    End Module d03plfe_mod
    Program d03plfe

!     D03PLF Example Main Program

!     .. Use Statements ..
      Use d03plfe_mod, Only: nout
!     .. Implicit None Statement ..
      Implicit None
!     .. Executable Statements ..
      Write (nout,*) 'D03PLF Example Program Results'

      Call ex1

      Call ex2

    Contains
      Subroutine ex1

!       .. Use Statements ..
        Use nag_library, Only: d03plf, nag_wp
        Use d03plfe_mod, Only: bndry1, exact, itrace, ncode1, nin, nmflx1,     &
                               npde1, nxi1, odedef, pdedef
!       .. Local Scalars ..
        Real (Kind=nag_wp)             :: errmax, lerr, lwgt, tout, ts
        Integer                        :: i, ifail, ind, itask, itol, j,       &
                                          lenode, lisave, lrsave, ncode, neqn, &
                                          nfuncs, niters, njacs, npde, npts,   &
                                          nsteps, nwkres, nxi
        Character (1)                  :: laopt, norm
!       .. Local Arrays ..
        Real (Kind=nag_wp)             :: algopt(30), atol(1), rtol(1)
        Real (Kind=nag_wp), Allocatable :: rsave(:), u(:), ue(:,:), x(:),      &
                                          xi(:)
        Integer, Allocatable           :: isave(:)
!       .. Intrinsic Procedures ..
        Intrinsic                      :: abs, int, max, real
!       .. Executable Statements ..
        Write (nout,*)
        Write (nout,*)
        Write (nout,*) 'Example 1'
        Write (nout,*)
!       Skip heading in data file
        Read (nin,*)
        Read (nin,*) npts
        npde = npde1
        ncode = ncode1
        nxi = nxi1
        neqn = npde*npts + ncode
        lisave = 25*neqn + 24
        nwkres = npde*(2*npts+6*nxi+3*npde+26) + nxi + ncode + 7*npts + 2
        lenode = 11*neqn + 50
        lrsave = 4*neqn + 11*neqn/2 + 1 + nwkres + lenode
        lisave = lisave*4
        lrsave = lrsave*4
        Allocate (rsave(lrsave),u(neqn),ue(npde,npts),x(npts),xi(nxi),         &
          isave(lisave))

        Read (nin,*) itol
        Read (nin,*) norm
        Read (nin,*) atol(1), rtol(1)

!       Initialize mesh
        Do i = 1, npts
          x(i) = real(i-1,kind=nag_wp)/real(npts-1,kind=nag_wp)
        End Do
        xi(1) = 0.0_nag_wp
        xi(2) = 1.0_nag_wp

!       Set initial values ..
        ts = 0.0_nag_wp
        Call exact(ts,u,npde,x,npts)
        u(neqn-1) = u(1) - u(2)
        u(neqn) = u(neqn-2) + u(neqn-3)

        laopt = 'S'
        ind = 0
        itask = 1

        algopt(1:30) = 0.0_nag_wp
!       Theta integration
        algopt(1) = 1.0_nag_wp
!       Sparse matrix algebra parameters
        algopt(29) = 0.1_nag_wp
        algopt(30) = 1.1_nag_wp

        tout = 0.5_nag_wp

!       ifail: behaviour on error exit
!              =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
        ifail = 0
        Call d03plf(npde,ts,tout,pdedef,nmflx1,bndry1,u,npts,x,ncode,odedef,   &
          nxi,xi,neqn,rtol,atol,itol,norm,laopt,algopt,rsave,lrsave,isave,     &
          lisave,itask,itrace,ind,ifail)

        Write (nout,99992)
        Write (nout,99991) npts
        Write (nout,99990) rtol(1)
        Write (nout,99989) atol(1)

!       Calculate global error at t=tout : max (||u-ue||, over x)

!       Get exact solution at t=tout
        Call exact(tout,ue,npde,x,npts)
        errmax = -1.0_nag_wp
        Do i = 2, npts
          lerr = 0.0_nag_wp
          Do j = 1, npde
            lwgt = rtol(1)*abs(ue(j,i)) + atol(1)
            lerr = lerr + abs(u((i-1)*npde+j)-ue(j,i))/lwgt
          End Do
          lerr = lerr/real(npde,kind=nag_wp)
          errmax = max(errmax,lerr)
        End Do
        Write (nout,99999)
        Write (nout,99998) 100*int(errmax/100.0_nag_wp) + 100

!       Print integration statistics (reasonably rounded)
        nsteps = 50*((isave(1)+25)/50)
        nfuncs = 100*((isave(2)+50)/100)
        njacs = 20*((isave(3)+10)/20)
        niters = 100*((isave(5)+50)/100)
        Write (nout,99997)
        Write (nout,99996) nsteps
        Write (nout,99995) nfuncs
        Write (nout,99994) njacs
        Write (nout,99993) niters

        Return

99999   Format (/,1X,'Integration Results:')
99998   Format (2X,'Global error is less than ',I3,                            &
          ' times the local error tolerance.')
99997   Format (/,1X,'Integration Statistics:')
99996   Format (2X,'Number of time steps           (nearest  50) = ',I6)
99995   Format (2X,'Number of function evaluations (nearest 100) = ',I6)
99994   Format (2X,'Number of Jacobian evaluations (nearest  20) = ',I6)
99993   Format (2X,'Number of iterations           (nearest 100) = ',I6)
99992   Format (/,1X,'Method Parameters:')
99991   Format (2X,'Number of mesh points used = ',I4)
99990   Format (2X,'Relative tolerance used    = ',E10.3)
99989   Format (2X,'Absolute tolerance used    = ',E10.3)
      End Subroutine ex1
      Subroutine ex2

!       .. Use Statements ..
        Use nag_library, Only: d03pek, d03plf, d03plp, nag_wp
        Use d03plfe_mod, Only: bndry2, el0, er0, gamma, itrace, ncode2, nin,   &
                               nmflx2, npde2, nxi2, rl0, rr0, uvinit
!       .. Local Scalars ..
        Real (Kind=nag_wp)             :: d, p, tout, ts, v
        Integer                        :: i, ifail, ind, it, itask, itol,      &
                                          lenode, lisave, lrsave, mlu, ncode,  &
                                          neqn, nfuncs, niters, njacs, npde,   &
                                          npts, nskip, nsteps, nwkres, nxi
        Character (1)                  :: laopt, norm
!       .. Local Arrays ..
        Real (Kind=nag_wp)             :: algopt(30), atol(1), rtol(1), xi(1)
        Real (Kind=nag_wp), Allocatable :: rsave(:), u(:,:), x(:)
        Integer, Allocatable           :: isave(:)
!       .. Intrinsic Procedures ..
        Intrinsic                      :: real
!       .. Executable Statements ..
        Write (nout,*)
        Write (nout,*)
        Write (nout,*) 'Example 2'
        Write (nout,*)
        Read (nin,*)
        Read (nin,*) npts, nskip

        npde = npde2
        ncode = ncode2
        nxi = nxi2
        nwkres = npde*(2*npts+3*npde+32) + 7*npts + 4
        mlu = 3*npde - 1
        neqn = npde*npts + ncode
        lenode = 9*neqn + 50
        lisave = neqn + 24
        lrsave = (3*mlu+1)*neqn + nwkres + lenode

        Allocate (rsave(lrsave),u(npde,npts),x(npts),isave(lisave))

!       Print problem parameters
        Write (nout,99997)
        Write (nout,99996) gamma
        Write (nout,99995) el0, er0
        Write (nout,99994) rl0, rr0

!       Read and print method parameters
        Read (nin,*) itol
        Read (nin,*) norm
        Read (nin,*) atol(1), rtol(1)

        Write (nout,99987)
        Write (nout,99986) npts
        Write (nout,99985) rtol(1)
        Write (nout,99984) atol(1)

!       Initialize mesh
        Do i = 1, npts
          x(i) = real(i-1,kind=nag_wp)/real(npts-1,kind=nag_wp)
        End Do

!       Initial values of variables
        Call uvinit(npde,npts,x,u)

        xi(1) = 0.0_nag_wp
        laopt = 'B'
        ind = 0
        itask = 1

        algopt(1:30) = 0.0_nag_wp
!       Theta integration
        algopt(1) = 2.0_nag_wp
        algopt(6) = 2.0_nag_wp
        algopt(7) = 2.0_nag_wp
!       Max. time step
        algopt(13) = 0.5E-2_nag_wp

        Write (nout,99999)
        Write (nout,99998)

        ts = 0.0_nag_wp
        tout = ts
        Do it = 1, 2
          tout = tout + 0.1_nag_wp

!         ifail: behaviour on error exit
!                =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
          ifail = 0
          Call d03plf(npde,ts,tout,d03plp,nmflx2,bndry2,u,npts,x,ncode,d03pek, &
            nxi,xi,neqn,rtol,atol,itol,norm,laopt,algopt,rsave,lrsave,isave,   &
            lisave,itask,itrace,ind,ifail)

!         Calculate density, velocity and pressure ..
          Do i = 1, npts, nskip
            d = u(1,i)
            v = u(2,i)/d
            p = d*(gamma-1.0_nag_wp)*(u(3,i)/d-0.5_nag_wp*v**2)
            If (i==1) Then
              Write (nout,99993) ts, x(i), d, v, p
            Else
              Write (nout,99992) x(i), d, v, p
            End If
          End Do
          Write (nout,*)
        End Do

!       Print integration statistics (reasonably rounded)
        nsteps = 50*((isave(1)+25)/50)
        nfuncs = 50*((isave(2)+25)/50)
        njacs = isave(3)
        niters = isave(5)
        Write (nout,99991) nsteps
        Write (nout,99990) nfuncs
        Write (nout,99989) njacs
        Write (nout,99988) niters

        Return

99999   Format (/,1X,'Solution')
99998   Format (4X,'t',6X,'x',5X,'density',1X,'velocity',1X,'pressure')
99997   Format (/,' Problem Parameter and initial conditions:')
99996   Format ('  gamma          =',F6.3)
99995   Format ('      e(x<0.5,0) =',F6.3,'    e(x>0.5,0) =',F6.3)
99994   Format ('    rho(x>0.5,0) =',F6.3,'  rho(x>0.5,0) =',F6.3)
99993   Format (1X,F6.3,1X,F7.4,3(2X,F7.4))
99992   Format (8X,F7.3,3(2X,F7.4))
99991   Format (/,' Number of time steps           (nearest 50) = ',I6)
99990   Format (' Number of function evaluations (nearest 50) = ',I6)
99989   Format (' Number of Jacobian evaluations (nearest  1) = ',I6)
99988   Format (' Number of iterations           (nearest  1) = ',I6)
99987   Format (/,' Method Parameters:')
99986   Format ('  Number of mesh points used = ',I4)
99985   Format ('  Relative tolerance used    = ',E10.3)
99984   Format ('  Absolute tolerance used    = ',E10.3)
      End Subroutine ex2
    End Program d03plfe


d03ppae.f90

!   D03PPA Example Program Text
!   Mark 26 Release. NAG Copyright 2016.

    Module d03ppae_mod

!     D03PPA Example Program Module:
!            Parameters and User-defined Routines

!     .. Use Statements ..
      Use nag_library, Only: nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Accessibility Statements ..
      Private
      Public                           :: bndary, exact, monitf, pdedef,       &
                                          uvinit
!     .. Parameters ..
      Real (Kind=nag_wp), Parameter    :: four = 4.0_nag_wp
      Real (Kind=nag_wp), Parameter    :: one = 1.0_nag_wp
      Real (Kind=nag_wp), Parameter    :: ptone = 0.1_nag_wp
      Real (Kind=nag_wp), Parameter, Public :: half = 0.5_nag_wp
      Real (Kind=nag_wp), Parameter, Public :: two = 2.0_nag_wp
      Real (Kind=nag_wp), Parameter, Public :: zero = 0.0_nag_wp
      Integer, Parameter, Public       :: itrace = 0, m = 0, ncode = 0,        &
                                          nin = 5, nout = 6, npde = 1,         &
                                          nxfix = 0, nxi = 0
    Contains
      Subroutine uvinit(npde,npts,nxi,x,xi,u,ncode,v,iuser,ruser)

!       .. Scalar Arguments ..
        Integer, Intent (In)           :: ncode, npde, npts, nxi
!       .. Array Arguments ..
        Real (Kind=nag_wp), Intent (Inout) :: ruser(*)
        Real (Kind=nag_wp), Intent (Out) :: u(npde,npts), v(ncode)
        Real (Kind=nag_wp), Intent (In) :: x(npts), xi(nxi)
        Integer, Intent (Inout)        :: iuser(*)
!       .. Local Scalars ..
        Real (Kind=nag_wp)             :: a, b, c, e, t
        Integer                        :: i
!       .. Intrinsic Procedures ..
        Intrinsic                      :: exp
!       .. Executable Statements ..
        e = ruser(1)
        t = zero
        Do i = 1, npts
          a = (x(i)-0.25_nag_wp-0.75_nag_wp*t)/(four*e)
          b = (0.9_nag_wp*x(i)-0.325_nag_wp-0.495_nag_wp*t)/(two*e)
          If (a>zero .And. a>b) Then
            a = exp(-a)
            c = (0.8_nag_wp*x(i)-0.4_nag_wp-0.24_nag_wp*t)/(four*e)
            c = exp(c)
            u(1,i) = (half+ptone*c+a)/(one+c+a)
          Else If (b>zero .And. b>=a) Then
            b = exp(-b)
            c = (-0.8_nag_wp*x(i)+0.4_nag_wp+0.24_nag_wp*t)/(four*e)
            c = exp(c)
            u(1,i) = (ptone+half*c+b)/(one+c+b)
          Else
            a = exp(a)
            b = exp(b)
            u(1,i) = (one+half*a+ptone*b)/(one+a+b)
          End If
        End Do
        Return
      End Subroutine uvinit
      Subroutine pdedef(npde,t,x,u,ux,ncode,v,vdot,p,q,r,ires,iuser,ruser)

!       .. Scalar Arguments ..
        Real (Kind=nag_wp), Intent (In) :: t, x
        Integer, Intent (Inout)        :: ires
        Integer, Intent (In)           :: ncode, npde
!       .. Array Arguments ..
        Real (Kind=nag_wp), Intent (Out) :: p(npde,npde), q(npde), r(npde)
        Real (Kind=nag_wp), Intent (Inout) :: ruser(*)
        Real (Kind=nag_wp), Intent (In) :: u(npde), ux(npde), v(ncode),        &
                                          vdot(ncode)
        Integer, Intent (Inout)        :: iuser(*)
!       .. Local Scalars ..
        Real (Kind=nag_wp)             :: e
!       .. Executable Statements ..
        e = ruser(1)
        p(1,1) = one
        r(1) = e*ux(1)
        q(1) = u(1)*ux(1)
        Return
      End Subroutine pdedef
      Subroutine bndary(npde,t,u,ux,ncode,v,vdot,ibnd,beta,gamma,ires,iuser,   &
        ruser)

!       .. Scalar Arguments ..
        Real (Kind=nag_wp), Intent (In) :: t
        Integer, Intent (In)           :: ibnd, ncode, npde
        Integer, Intent (Inout)        :: ires
!       .. Array Arguments ..
        Real (Kind=nag_wp), Intent (Out) :: beta(npde), gamma(npde)
        Real (Kind=nag_wp), Intent (Inout) :: ruser(*)
        Real (Kind=nag_wp), Intent (In) :: u(npde), ux(npde), v(ncode),        &
                                          vdot(ncode)
        Integer, Intent (Inout)        :: iuser(*)
!       .. Local Scalars ..
        Real (Kind=nag_wp)             :: a, b, c, e, ue, x
!       .. Intrinsic Procedures ..
        Intrinsic                      :: exp
!       .. Executable Statements ..
        e = ruser(1)
        beta(1) = zero
        If (ibnd==0) Then
          x = zero
          a = (x-0.25_nag_wp-0.75_nag_wp*t)/(four*e)
          b = (0.9_nag_wp*x-0.325_nag_wp-0.495_nag_wp*t)/(two*e)
          If (a>zero .And. a>b) Then
            a = exp(-a)
            c = (0.8_nag_wp*x-0.4_nag_wp-0.24_nag_wp*t)/(four*e)
            c = exp(c)
            ue = (half+ptone*c+a)/(one+c+a)
          Else If (b>zero .And. b>=a) Then
            b = exp(-b)
            c = (-0.8_nag_wp*x+0.4_nag_wp+0.24_nag_wp*t)/(four*e)
            c = exp(c)
            ue = (ptone+half*c+b)/(one+c+b)
          Else
            a = exp(a)
            b = exp(b)
            ue = (one+half*a+ptone*b)/(one+a+b)
          End If
        Else
          x = one
          a = (x-0.25_nag_wp-0.75_nag_wp*t)/(four*e)
          b = (0.9_nag_wp*x-0.325_nag_wp-0.495_nag_wp*t)/(two*e)
          If (a>zero .And. a>b) Then
            a = exp(-a)
            c = (0.8_nag_wp*x-0.4_nag_wp-0.24_nag_wp*t)/(four*e)
            c = exp(c)
            ue = (half+ptone*c+a)/(one+c+a)
          Else If (b>zero .And. b>=a) Then
            b = exp(-b)
            c = (-0.8_nag_wp*x+0.4_nag_wp+0.24_nag_wp*t)/(four*e)
            c = exp(c)
            ue = (ptone+half*c+b)/(one+c+b)
          Else
            a = exp(a)
            b = exp(b)
            ue = (one+half*a+ptone*b)/(one+a+b)
          End If
        End If
        gamma(1) = u(1) - ue
        Return
      End Subroutine bndary
      Subroutine monitf(t,npts,npde,x,u,r,fmon,iuser,ruser)

!       .. Scalar Arguments ..
        Real (Kind=nag_wp), Intent (In) :: t
        Integer, Intent (In)           :: npde, npts
!       .. Array Arguments ..
        Real (Kind=nag_wp), Intent (Out) :: fmon(npts)
        Real (Kind=nag_wp), Intent (In) :: r(npde,npts), u(npde,npts), x(npts)
        Real (Kind=nag_wp), Intent (Inout) :: ruser(*)
        Integer, Intent (Inout)        :: iuser(*)
!       .. Local Scalars ..
        Real (Kind=nag_wp)             :: drdx, h
        Integer                        :: i, k, l
!       .. Intrinsic Procedures ..
        Intrinsic                      :: abs, max, min
!       .. Executable Statements ..
        Do i = 1, npts - 1
          k = max(1,i-1)
          l = min(npts,i+1)
          h = (x(l)-x(k))*half
!         Second derivative ..
          drdx = (r(1,i+1)-r(1,i))/h
          fmon(i) = abs(drdx)
        End Do
        fmon(npts) = fmon(npts-1)
        Return
      End Subroutine monitf
      Subroutine exact(t,x,npts,u,iuser,ruser)
!       Exact solution (for comparison purposes)

!       .. Scalar Arguments ..
        Real (Kind=nag_wp), Intent (In) :: t
        Integer, Intent (In)           :: npts
!       .. Array Arguments ..
        Real (Kind=nag_wp), Intent (Inout) :: ruser(*)
        Real (Kind=nag_wp), Intent (Out) :: u(npts)
        Real (Kind=nag_wp), Intent (In) :: x(npts)
        Integer, Intent (Inout)        :: iuser(*)
!       .. Local Scalars ..
        Real (Kind=nag_wp)             :: a, b, c, e
        Integer                        :: i
!       .. Intrinsic Procedures ..
        Intrinsic                      :: exp
!       .. Executable Statements ..
        e = ruser(1)
        Do i = 1, npts
          a = (x(i)-0.25_nag_wp-0.75_nag_wp*t)/(four*e)
          b = (0.9_nag_wp*x(i)-0.325_nag_wp-0.495_nag_wp*t)/(two*e)
          If (a>zero .And. a>b) Then
            a = exp(-a)
            c = (0.8_nag_wp*x(i)-0.4_nag_wp-0.24_nag_wp*t)/(four*e)
            c = exp(c)
            u(i) = (half+ptone*c+a)/(one+c+a)
          Else If (b>zero .And. b>=a) Then
            b = exp(-b)
            c = (-0.8_nag_wp*x(i)+0.4_nag_wp+0.24_nag_wp*t)/(four*e)
            c = exp(c)
            u(i) = (ptone+half*c+b)/(one+c+b)
          Else
            a = exp(a)
            b = exp(b)
            u(i) = (one+half*a+ptone*b)/(one+a+b)
          End If
        End Do
        Return
      End Subroutine exact
    End Module d03ppae_mod
    Program d03ppae

!     D03PPA Example Main Program

!     .. Use Statements ..
      Use nag_library, Only: d03ppa, d03pzf, d53pck, nag_wp
      Use d03ppae_mod, Only: bndary, exact, half, itrace, m, monitf, ncode,    &
                             nin, nout, npde, nxfix, nxi, pdedef, two, uvinit, &
                             zero
!     .. Implicit None Statement ..
      Implicit None
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: con, dx, dxmesh, e, tout, trmesh,    &
                                          ts, x0, xmid, xratio
      Integer                          :: i, ifail, ind, intpts, ipminf, it,   &
                                          itask, itol, itype, lenode, neqn,    &
                                          niw, npts, nrmesh, nw, nwkres
      Logical                          :: remesh, theta
      Character (1)                    :: laopt, norm
!     .. Local Arrays ..
      Real (Kind=nag_wp)               :: algopt(30), atol(1), rtol(1),        &
                                          ruser(1), rwsav(1100), xfix(1),      &
                                          xi(1)
      Real (Kind=nag_wp), Allocatable  :: u(:), ue(:), uout(:,:,:), w(:),      &
                                          x(:), xout(:)
      Integer                          :: iuser(1), iwsav(505)
      Integer, Allocatable             :: iw(:)
      Logical                          :: lwsav(100)
      Character (80)                   :: cwsav(10)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: min, real
!     .. Executable Statements ..
      Write (nout,*) 'D03PPA Example Program Results'
!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) npts, intpts, itype
      neqn = npde*npts + ncode
      niw = 25 + nxfix
      nwkres = npde*(npts+3*npde+21) + 7*npts + nxfix + 3
      lenode = 11*neqn + 50
      nw = neqn*neqn + neqn + nwkres + lenode

      Allocate (u(neqn),ue(intpts),uout(npde,intpts,itype),w(nw),x(npts),      &
        xout(intpts),iw(niw))
      Read (nin,*) itol
      Read (nin,*) atol(1), rtol(1)
      Read (nin,*) e
      ruser(1) = e

!     Initialise mesh
      Do i = 1, npts
        x(i) = real(i-1,kind=nag_wp)/real(npts-1,kind=nag_wp)
      End Do

!     Set remesh parameters
      remesh = .True.
      nrmesh = 3
      dxmesh = half
      con = two/real(npts-1,kind=nag_wp)
      xratio = 1.5_nag_wp
      ipminf = 0

      xi(1) = zero
      norm = 'A'
      laopt = 'F'
      ind = 0
      itask = 1

!     Set theta to .TRUE. if the Theta integrator is required
      theta = .False.
      algopt(1:30) = zero
      If (theta) Then
        algopt(1) = two
      End If

!     Loop over output value of t
      ts = zero
      tout = zero
      Do it = 1, 5
        xmid = half + half*tout
        tout = 0.2_nag_wp*real(it,kind=nag_wp)

!       ifail: behaviour on error exit
!              =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
        ifail = 0
        Call d03ppa(npde,m,ts,tout,pdedef,bndary,uvinit,u,npts,x,ncode,d53pck, &
          nxi,xi,neqn,rtol,atol,itol,norm,laopt,algopt,remesh,nxfix,xfix,      &
          nrmesh,dxmesh,trmesh,ipminf,xratio,con,monitf,w,nw,iw,niw,itask,     &
          itrace,ind,iuser,ruser,cwsav,lwsav,iwsav,rwsav,ifail)

        If (it==1) Then
          Write (nout,99998) atol, npts
          Write (nout,99993) nrmesh
          Write (nout,99992) e
          Write (nout,*)
        End If

!       Set output points
        dx = 0.1_nag_wp
        If (tout>half) Then
          dx = 0.05_nag_wp
        End If

        x0 = xmid - half*real(intpts-1,kind=nag_wp)*dx
        Do i = 1, intpts
          xout(i) = x0
          x0 = x0 + dx
        End Do
        xout(intpts) = min(xout(intpts),x(npts))

        Write (nout,99999) ts
        Write (nout,99996) xout(1:intpts)

!       Interpolate at output points
        ifail = 0
        Call d03pzf(npde,m,u,npts,x,xout,intpts,itype,uout,ifail)

!       Check against exact solution

        Call exact(ts,xout,intpts,ue,iuser,ruser)

        Write (nout,99995) uout(1,1:intpts,1)
        Write (nout,99994) ue(1:intpts)

      End Do
      Write (nout,99997) iw(1), iw(2), iw(3), iw(5)

99999 Format (' T = ',F6.3)
99998 Format (/,/,'  Accuracy requirement =',E10.3,' Number of points = ',I3,  &
        /)
99997 Format (' Number of integration steps in time = ',I6,/,' Number o',      &
        'f function evaluations = ',I6,/,' Number of Jacobian eval',           &
        'uations =',I6,/,' Number of iterations = ',I6)
99996 Format (1X,'X           ',5F9.4)
99995 Format (1X,'Approx sol. ',5F9.4)
99994 Format (1X,'Exact  sol. ',5F9.4,/)
99993 Format (2X,'Remeshing every',I3,' time steps',/)
99992 Format (2X,'E =',F8.3)
    End Program d03ppae


d03ppfe.f90

!   D03PPF Example Program Text
!   Mark 26 Release. NAG Copyright 2016.

    Module d03ppfe_mod

!     D03PPF Example Program Module:
!            Parameters and User-defined Routines

!     .. Use Statements ..
      Use nag_library, Only: nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Accessibility Statements ..
      Private
      Public                           :: bndary, exact, monitf, pdedef,       &
                                          uvinit
!     .. Parameters ..
      Real (Kind=nag_wp), Parameter    :: four = 4.0_nag_wp
      Real (Kind=nag_wp), Parameter    :: one = 1.0_nag_wp
      Real (Kind=nag_wp), Parameter    :: ptone = 0.1_nag_wp
      Real (Kind=nag_wp), Parameter, Public :: half = 0.5_nag_wp
      Real (Kind=nag_wp), Parameter, Public :: two = 2.0_nag_wp
      Real (Kind=nag_wp), Parameter, Public :: zero = 0.0_nag_wp
      Integer, Parameter, Public       :: itrace = 0, m = 0, ncode = 0,        &
                                          nin = 5, nout = 6, npde = 1,         &
                                          nxfix = 0, nxi = 0
!     .. Local Scalars ..
      Real (Kind=nag_wp), Public, Save :: e
    Contains
      Subroutine uvinit(npde,npts,nxi,x,xi,u,ncode,v)

!       .. Scalar Arguments ..
        Integer, Intent (In)           :: ncode, npde, npts, nxi
!       .. Array Arguments ..
        Real (Kind=nag_wp), Intent (Out) :: u(npde,npts), v(ncode)
        Real (Kind=nag_wp), Intent (In) :: x(npts), xi(nxi)
!       .. Local Scalars ..
        Real (Kind=nag_wp)             :: a, b, c, t
        Integer                        :: i
!       .. Intrinsic Procedures ..
        Intrinsic                      :: exp
!       .. Executable Statements ..
        t = zero
        Do i = 1, npts
          a = (x(i)-0.25_nag_wp-0.75_nag_wp*t)/(four*e)
          b = (0.9_nag_wp*x(i)-0.325_nag_wp-0.495_nag_wp*t)/(two*e)
          If (a>zero .And. a>b) Then
            a = exp(-a)
            c = (0.8_nag_wp*x(i)-0.4_nag_wp-0.24_nag_wp*t)/(four*e)
            c = exp(c)
            u(1,i) = (half+ptone*c+a)/(one+c+a)
          Else If (b>zero .And. b>=a) Then
            b = exp(-b)
            c = (-0.8_nag_wp*x(i)+0.4_nag_wp+0.24_nag_wp*t)/(four*e)
            c = exp(c)
            u(1,i) = (ptone+half*c+b)/(one+c+b)
          Else
            a = exp(a)
            b = exp(b)
            u(1,i) = (one+half*a+ptone*b)/(one+a+b)
          End If
        End Do
        Return
      End Subroutine uvinit
      Subroutine pdedef(npde,t,x,u,ux,ncode,v,vdot,p,q,r,ires)

!       .. Scalar Arguments ..
        Real (Kind=nag_wp), Intent (In) :: t, x
        Integer, Intent (Inout)        :: ires
        Integer, Intent (In)           :: ncode, npde
!       .. Array Arguments ..
        Real (Kind=nag_wp), Intent (Out) :: p(npde,npde), q(npde), r(npde)
        Real (Kind=nag_wp), Intent (In) :: u(npde), ux(npde), v(ncode),        &
                                          vdot(ncode)
!       .. Executable Statements ..
        p(1,1) = one
        r(1) = e*ux(1)
        q(1) = u(1)*ux(1)
        Return
      End Subroutine pdedef
      Subroutine bndary(npde,t,u,ux,ncode,v,vdot,ibnd,beta,gamma,ires)

!       .. Scalar Arguments ..
        Real (Kind=nag_wp), Intent (In) :: t
        Integer, Intent (In)           :: ibnd, ncode, npde
        Integer, Intent (Inout)        :: ires
!       .. Array Arguments ..
        Real (Kind=nag_wp), Intent (Out) :: beta(npde), gamma(npde)
        Real (Kind=nag_wp), Intent (In) :: u(npde), ux(npde), v(ncode),        &
                                          vdot(ncode)
!       .. Local Scalars ..
        Real (Kind=nag_wp)             :: a, b, c, ue, x
!       .. Intrinsic Procedures ..
        Intrinsic                      :: exp
!       .. Executable Statements ..
        beta(1) = zero
        If (ibnd==0) Then
          x = zero
          a = (x-0.25_nag_wp-0.75_nag_wp*t)/(four*e)
          b = (0.9_nag_wp*x-0.325_nag_wp-0.495_nag_wp*t)/(two*e)
          If (a>zero .And. a>b) Then
            a = exp(-a)
            c = (0.8_nag_wp*x-0.4_nag_wp-0.24_nag_wp*t)/(four*e)
            c = exp(c)
            ue = (half+ptone*c+a)/(one+c+a)
          Else If (b>zero .And. b>=a) Then
            b = exp(-b)
            c = (-0.8_nag_wp*x+0.4_nag_wp+0.24_nag_wp*t)/(four*e)
            c = exp(c)
            ue = (ptone+half*c+b)/(one+c+b)
          Else
            a = exp(a)
            b = exp(b)
            ue = (one+half*a+ptone*b)/(one+a+b)
          End If
        Else
          x = one
          a = (x-0.25_nag_wp-0.75_nag_wp*t)/(four*e)
          b = (0.9_nag_wp*x-0.325_nag_wp-0.495_nag_wp*t)/(two*e)
          If (a>zero .And. a>b) Then
            a = exp(-a)
            c = (0.8_nag_wp*x-0.4_nag_wp-0.24_nag_wp*t)/(four*e)
            c = exp(c)
            ue = (half+ptone*c+a)/(one+c+a)
          Else If (b>zero .And. b>=a) Then
            b = exp(-b)
            c = (-0.8_nag_wp*x+0.4_nag_wp+0.24_nag_wp*t)/(four*e)
            c = exp(c)
            ue = (ptone+half*c+b)/(one+c+b)
          Else
            a = exp(a)
            b = exp(b)
            ue = (one+half*a+ptone*b)/(one+a+b)
          End If
        End If
        gamma(1) = u(1) - ue
        Return
      End Subroutine bndary
      Subroutine monitf(t,npts,npde,x,u,r,fmon)

!       .. Scalar Arguments ..
        Real (Kind=nag_wp), Intent (In) :: t
        Integer, Intent (In)           :: npde, npts
!       .. Array Arguments ..
        Real (Kind=nag_wp), Intent (Out) :: fmon(npts)
        Real (Kind=nag_wp), Intent (In) :: r(npde,npts), u(npde,npts), x(npts)
!       .. Local Scalars ..
        Real (Kind=nag_wp)             :: drdx, h
        Integer                        :: i
!       .. Intrinsic Procedures ..
        Intrinsic                      :: abs
!       .. Executable Statements ..
        fmon(1) = abs((r(1,2)-r(1,1))/((x(2)-x(1))*half))
        Do i = 2, npts - 1
          h = (x(i+1)-x(i-1))*half
!         Second derivative ..
          drdx = (r(1,i+1)-r(1,i))/h
          fmon(i) = abs(drdx)
        End Do
        fmon(npts) = fmon(npts-1)
        Return
      End Subroutine monitf
      Subroutine exact(t,x,npts,u)

!       Exact solution (for comparison purposes)

!       .. Scalar Arguments ..
        Real (Kind=nag_wp), Intent (In) :: t
        Integer, Intent (In)           :: npts
!       .. Array Arguments ..
        Real (Kind=nag_wp), Intent (Out) :: u(npts)
        Real (Kind=nag_wp), Intent (In) :: x(npts)
!       .. Local Scalars ..
        Real (Kind=nag_wp)             :: a, b, c
        Integer                        :: i
!       .. Intrinsic Procedures ..
        Intrinsic                      :: exp
!       .. Executable Statements ..
        Do i = 1, npts
          a = (x(i)-0.25_nag_wp-0.75_nag_wp*t)/(four*e)
          b = (0.9_nag_wp*x(i)-0.325_nag_wp-0.495_nag_wp*t)/(two*e)
          If (a>zero .And. a>b) Then
            a = exp(-a)
            c = (0.8_nag_wp*x(i)-0.4_nag_wp-0.24_nag_wp*t)/(four*e)
            c = exp(c)
            u(i) = (half+ptone*c+a)/(one+c+a)
          Else If (b>zero .And. b>=a) Then
            b = exp(-b)
            c = (-0.8_nag_wp*x(i)+0.4_nag_wp+0.24_nag_wp*t)/(four*e)
            c = exp(c)
            u(i) = (ptone+half*c+b)/(one+c+b)
          Else
            a = exp(a)
            b = exp(b)
            u(i) = (one+half*a+ptone*b)/(one+a+b)
          End If
        End Do
        Return
      End Subroutine exact
    End Module d03ppfe_mod
    Program d03ppfe

!     D03PPF Example Main Program

!     .. Use Statements ..
      Use nag_library, Only: d03pck, d03ppf, d03pzf, nag_wp
      Use d03ppfe_mod, Only: bndary, e, exact, half, itrace, m, monitf, ncode, &
                             nin, nout, npde, nxfix, nxi, pdedef, two, uvinit, &
                             zero
!     .. Implicit None Statement ..
      Implicit None
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: con, dx, dxmesh, tout, trmesh, ts,   &
                                          x0, xmid, xratio
      Integer                          :: i, ifail, ind, intpts, ipminf, it,   &
                                          itask, itol, itype, lenode, lisave,  &
                                          lrsave, neqn, npts, nrmesh, nwkres
      Logical                          :: remesh, theta
      Character (1)                    :: laopt, norm
!     .. Local Arrays ..
      Real (Kind=nag_wp)               :: algopt(30), atol(1), rtol(1),        &
                                          xfix(1), xi(1)
      Real (Kind=nag_wp), Allocatable  :: rsave(:), u(:), ue(:), uout(:,:,:),  &
                                          x(:), xout(:)
      Integer, Allocatable             :: isave(:)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: min, real
!     .. Executable Statements ..
      Write (nout,*) 'D03PPF Example Program Results'
!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) npts, intpts, itype
      lisave = 25 + nxfix
      neqn = npde*npts + ncode
      nwkres = npde*(npts+3*npde+21) + 7*npts + nxfix + 3
      lenode = 11*neqn + 50
      lrsave = neqn*neqn + neqn + nwkres + lenode

      Allocate (u(neqn),ue(intpts),uout(npde,intpts,itype),rsave(lrsave),      &
        x(npts),xout(intpts),isave(lisave))
      Read (nin,*) itol
      Read (nin,*) atol(1), rtol(1)
      Read (nin,*) e

!     Initialize mesh
      Do i = 1, npts
        x(i) = real(i-1,kind=nag_wp)/real(npts-1,kind=nag_wp)
      End Do

!     Set remesh parameters
      remesh = .True.
      nrmesh = 3
      dxmesh = half
      con = two/real(npts-1,kind=nag_wp)
      xratio = 1.5_nag_wp
      ipminf = 0

      xi(1) = zero
      norm = 'A'
      laopt = 'F'
      ind = 0
      itask = 1

!     Set theta to .TRUE. if the Theta integrator is required

      theta = .False.
      algopt(1:30) = zero
      If (theta) Then
        algopt(1) = two
      Else
        algopt(1) = zero
      End If

!     Loop over output value of t

      ts = zero
      tout = zero
      Do it = 1, 5
        xmid = half + half*tout
        tout = 0.2_nag_wp*real(it,kind=nag_wp)

!       ifail: behaviour on error exit
!              =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
        ifail = 0
        Call d03ppf(npde,m,ts,tout,pdedef,bndary,uvinit,u,npts,x,ncode,d03pck, &
          nxi,xi,neqn,rtol,atol,itol,norm,laopt,algopt,remesh,nxfix,xfix,      &
          nrmesh,dxmesh,trmesh,ipminf,xratio,con,monitf,rsave,lrsave,isave,    &
          lisave,itask,itrace,ind,ifail)

        If (it==1) Then
          Write (nout,99998) atol, npts
          Write (nout,99993) nrmesh
          Write (nout,99992) e
          Write (nout,*)
        End If

!       Set output points ..
        dx = 0.1_nag_wp
        If (tout>half) Then
          dx = 0.05_nag_wp
        End If

        x0 = xmid - half*real(intpts-1,kind=nag_wp)*dx
        Do i = 1, intpts
          xout(i) = x0
          x0 = x0 + dx
        End Do
        xout(intpts) = min(xout(intpts),x(npts))

        Write (nout,99999) ts
        Write (nout,99996) xout(1:intpts)

!       Interpolate at output points ..
        ifail = 0
        Call d03pzf(npde,m,u,npts,x,xout,intpts,itype,uout,ifail)

!       Check against exact solution ..
        Call exact(ts,xout,intpts,ue)

        Write (nout,99995) uout(1,1:intpts,1)
        Write (nout,99994) ue(1:intpts)

      End Do
      Write (nout,99997) isave(1), isave(2), isave(3), isave(5)

99999 Format (' T = ',F6.3)
99998 Format (/,/,'  Accuracy requirement =',E10.3,' Number of points = ',I3,  &
        /)
99997 Format (' Number of integration steps in time = ',I6,/,' Number o',      &
        'f function evaluations = ',I6,/,' Number of Jacobian eval',           &
        'uations =',I6,/,' Number of iterations = ',I6)
99996 Format (1X,'X           ',5F9.4)
99995 Format (1X,'Approx sol. ',5F9.4)
99994 Format (1X,'Exact  sol. ',5F9.4,/)
99993 Format (2X,'Remeshing every',I3,' time steps',/)
99992 Format (2X,'E =',F8.3)
    End Program d03ppfe


d03prfe.f90

!   D03PRF Example Program Text
!   Mark 26 Release. NAG Copyright 2016.

    Module d03prfe_mod

!     D03PRF Example Program Module:
!            Parameters and User-defined Routines

!     .. Use Statements ..
      Use nag_library, Only: nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Accessibility Statements ..
      Private
      Public                           :: bndary, exact, monitf, pdedef,       &
                                          uvinit
!     .. Parameters ..
      Real (Kind=nag_wp), Parameter    :: half = 0.5_nag_wp
      Real (Kind=nag_wp), Parameter    :: two = 2.0_nag_wp
      Integer, Parameter, Public       :: itrace = 0, ncode = 0, nin = 5,      &
                                          nleft = 1, nout = 6, npde = 2,       &
                                          nxfix = 0, nxi = 0
    Contains
      Subroutine uvinit(npde,npts,nxi,x,xi,u,ncode,v)

!       .. Use Statements ..
        Use nag_library, Only: x01aaf
!       .. Scalar Arguments ..
        Integer, Intent (In)           :: ncode, npde, npts, nxi
!       .. Array Arguments ..
        Real (Kind=nag_wp), Intent (Out) :: u(npde,npts), v(ncode)
        Real (Kind=nag_wp), Intent (In) :: x(npts), xi(nxi)
!       .. Local Scalars ..
        Real (Kind=nag_wp)             :: pi
        Integer                        :: i
!       .. Intrinsic Procedures ..
        Intrinsic                      :: exp, sin
!       .. Executable Statements ..
        pi = x01aaf(pi)
        Do i = 1, npts
          u(1,i) = exp(x(i))
          u(2,i) = x(i)**2 + sin(two*pi*x(i)**2)
        End Do
        Return
      End Subroutine uvinit
      Subroutine pdedef(npde,t,x,u,udot,ux,ncode,v,vdot,res,ires)

!       .. Scalar Arguments ..
        Real (Kind=nag_wp), Intent (In) :: t, x
        Integer, Intent (Inout)        :: ires
        Integer, Intent (In)           :: ncode, npde
!       .. Array Arguments ..
        Real (Kind=nag_wp), Intent (Out) :: res(npde)
        Real (Kind=nag_wp), Intent (In) :: u(npde), udot(npde), ux(npde),      &
                                          v(ncode), vdot(ncode)
!       .. Executable Statements ..
        If (ires==-1) Then
          res(1) = udot(1)
          res(2) = udot(2)
        Else
          res(1) = udot(1) + ux(1) + ux(2)
          res(2) = udot(2) + 4.0_nag_wp*ux(1) + ux(2)
        End If
        Return
      End Subroutine pdedef
      Subroutine bndary(npde,t,ibnd,nobc,u,udot,ncode,v,vdot,res,ires)

!       .. Use Statements ..
        Use nag_library, Only: x01aaf
!       .. Scalar Arguments ..
        Real (Kind=nag_wp), Intent (In) :: t
        Integer, Intent (In)           :: ibnd, ncode, nobc, npde
        Integer, Intent (Inout)        :: ires
!       .. Array Arguments ..
        Real (Kind=nag_wp), Intent (Out) :: res(nobc)
        Real (Kind=nag_wp), Intent (In) :: u(npde), udot(npde), v(ncode),      &
                                          vdot(ncode)
!       .. Local Scalars ..
        Real (Kind=nag_wp)             :: pp, ppt1, ppt3, t1, t3
!       .. Intrinsic Procedures ..
        Intrinsic                      :: exp, sin
!       .. Executable Statements ..
        If (ires==-1) Then
          res(1) = 0.0_nag_wp
        Else
          pp = two*x01aaf(pp)
          t1 = t
          t3 = -3.0_nag_wp*t
          If (ibnd==0) Then
            ppt3 = sin(pp*t3**2)
            ppt1 = sin(pp*t1**2)
            res(1) = u(1) - half*(exp(t3)+exp(t1)+half*(ppt3-ppt1))
            res(1) = res(1) - 2.0_nag_wp*t**2
          Else
            t3 = t3 + 1.0_nag_wp
            t1 = t1 + 1.0_nag_wp
            ppt3 = sin(pp*t3**2)
            ppt1 = sin(pp*t1**2)
            res(1) = u(2) - (exp(t3)-exp(t1)+half*(ppt3+ppt1))
            res(1) = res(1) - (1.0_nag_wp+5.0_nag_wp*t**2-2.0_nag_wp*t)
          End If
        End If
        Return
      End Subroutine bndary
      Subroutine monitf(t,npts,npde,x,u,fmon)

!       .. Scalar Arguments ..
        Real (Kind=nag_wp), Intent (In) :: t
        Integer, Intent (In)           :: npde, npts
!       .. Array Arguments ..
        Real (Kind=nag_wp), Intent (Out) :: fmon(npts)
        Real (Kind=nag_wp), Intent (In) :: u(npde,npts), x(npts)
!       .. Local Scalars ..
        Real (Kind=nag_wp)             :: d2x1, d2x2, h1, h2, h3
        Integer                        :: i
!       .. Intrinsic Procedures ..
        Intrinsic                      :: abs, max
!       .. Executable Statements ..
        Do i = 2, npts - 1
          h1 = x(i) - x(i-1)
          h2 = x(i+1) - x(i)
          h3 = half*(x(i+1)-x(i-1))
!         Second derivatives ..
          d2x1 = abs(((u(1,i+1)-u(1,i))/h2-(u(1,i)-u(1,i-1))/h1)/h3)
          d2x2 = abs(((u(2,i+1)-u(2,i))/h2-(u(2,i)-u(2,i-1))/h1)/h3)
          fmon(i) = max(d2x1,d2x2)
        End Do
        fmon(1) = fmon(2)
        fmon(npts) = fmon(npts-1)
        Return
      End Subroutine monitf
      Subroutine exact(t,npde,npts,x,u)

!       Exact solution (for comparison purposes)

!       .. Use Statements ..
        Use nag_library, Only: x01aaf
!       .. Scalar Arguments ..
        Real (Kind=nag_wp), Intent (In) :: t
        Integer, Intent (In)           :: npde, npts
!       .. Array Arguments ..
        Real (Kind=nag_wp), Intent (Out) :: u(npde,npts)
        Real (Kind=nag_wp), Intent (In) :: x(npts)
!       .. Local Scalars ..
        Real (Kind=nag_wp)             :: pp, ppt1, ppt3, x1, x3
        Integer                        :: i
!       .. Intrinsic Procedures ..
        Intrinsic                      :: exp, sin
!       .. Executable Statements ..
        pp = 2.0_nag_wp*x01aaf(pp)
        Do i = 1, npts
          x1 = x(i) + t
          x3 = x(i) - 3.0_nag_wp*t
          ppt3 = sin(pp*x3**2)
          ppt1 = sin(pp*x1**2)
          u(1,i) = half*(exp(x3)+exp(x1)+half*(ppt3-ppt1)) - two*x(i)*t +      &
            two*t**2
          u(2,i) = (exp(x3)-exp(x1)+half*(ppt3+ppt1)) - two*x(i)*t + x(i)**2 + &
            5.0_nag_wp*t**2
        End Do
        Return
      End Subroutine exact
    End Module d03prfe_mod
    Program d03prfe

!     D03PRF Example Main Program

!     .. Use Statements ..
      Use nag_library, Only: d03pek, d03prf, d03pzf, nag_wp
      Use d03prfe_mod, Only: bndary, exact, itrace, monitf, ncode, nin, nleft, &
                             nout, npde, nxfix, nxi, pdedef, uvinit
!     .. Implicit None Statement ..
      Implicit None
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: con, dxmesh, tout, trmesh, ts,       &
                                          xratio
      Integer                          :: i, ifail, ind, intpts, ipminf, it,   &
                                          itask, itol, itype, lenode, lisave,  &
                                          lrsave, neqn, npts, nrmesh, nwkres
      Logical                          :: remesh, theta
      Character (1)                    :: laopt, norm
!     .. Local Arrays ..
      Real (Kind=nag_wp)               :: algopt(30), atol(1), rtol(1),        &
                                          xfix(1), xi(1)
      Real (Kind=nag_wp), Allocatable  :: rsave(:), u(:,:), ue(:,:),           &
                                          uout(:,:,:), x(:), xout(:)
      Integer, Allocatable             :: isave(:)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: real
!     .. Executable Statements ..
      Write (nout,*) 'D03PRF Example Program Results'
!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) npts, intpts, itype
      lisave = 25 + nxfix
      neqn = npde*npts + ncode
      nwkres = npde*(npts+21+3*npde) + 7*npts + nxfix + 3
      lenode = 11*neqn + 50
      lrsave = neqn*neqn + neqn + nwkres + lenode

      Allocate (rsave(lrsave),u(npde,npts),ue(npde,npts),                      &
        uout(npde,intpts,itype),x(npts),xout(intpts),isave(lisave))
      Read (nin,*) itol
      Read (nin,*) atol(1), rtol(1)

!     Set remesh parameters
      remesh = .True.
      nrmesh = 3
      dxmesh = 0.0_nag_wp
      con = 5.0_nag_wp/real(npts-1,kind=nag_wp)
      xratio = 1.2_nag_wp
      ipminf = 0

!     Initialize mesh
      Do i = 1, npts
        x(i) = real(i-1,kind=nag_wp)/real(npts-1,kind=nag_wp)
      End Do
      xi(1) = 0.0_nag_wp

      Read (nin,*) xout(1:intpts)
      Read (nin,*) norm, laopt
      ind = 0
      itask = 1

!     Set theta to .TRUE. if the Theta integrator is required
      theta = .False.
      algopt(1:30) = 0.0_nag_wp
      If (theta) Then
        algopt(1) = 2.0_nag_wp
        algopt(6) = 2.0_nag_wp
        algopt(7) = 1.0_nag_wp
      End If

!     Loop over output value of t
      ts = 0.0_nag_wp
      tout = 0.0_nag_wp

      Do it = 1, 5
        tout = 0.05_nag_wp*real(it,kind=nag_wp)

!       ifail: behaviour on error exit
!              =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
        ifail = 0
        Call d03prf(npde,ts,tout,pdedef,bndary,uvinit,u,npts,x,nleft,ncode,    &
          d03pek,nxi,xi,neqn,rtol,atol,itol,norm,laopt,algopt,remesh,nxfix,    &
          xfix,nrmesh,dxmesh,trmesh,ipminf,xratio,con,monitf,rsave,lrsave,     &
          isave,lisave,itask,itrace,ind,ifail)

        If (it==1) Then
          Write (nout,99996) atol, npts
          Write (nout,99999) nrmesh
          Write (nout,99998) xout(1:intpts)
        End If

!       Interpolate at output points ..
        ifail = 0
        Call d03pzf(npde,0,u,npts,x,xout,intpts,itype,uout,ifail)

!       Check against exact solution ..
        Call exact(ts,npde,intpts,xout,ue)

        Write (nout,99997) ts
        Write (nout,99994) uout(1,1:intpts,1)
        Write (nout,99993) ue(1,1:intpts)
        Write (nout,99992) uout(2,1:intpts,1)
        Write (nout,99991) ue(2,1:intpts)

      End Do
      Write (nout,99995) isave(1), isave(2), isave(3), isave(5)

99999 Format (' Remeshing every ',I3,' time steps',/)
99998 Format (' X        ',5F10.4,/)
99997 Format (' T = ',F6.3)
99996 Format (/,/,'  Accuracy requirement =',E10.3,' Number of points = ',I3,  &
        /)
99995 Format (' Number of integration steps in time = ',I6,/,' Number o',      &
        'f function evaluations = ',I6,/,' Number of Jacobian eval',           &
        'uations =',I6,/,' Number of iterations = ',I6)
99994 Format (' Approx U1',5F10.4)
99993 Format (' Exact  U1',5F10.4)
99992 Format (' Approx U2',5F10.4)
99991 Format (' Exact  U2',5F10.4,/)
    End Program d03prfe


d03psfe.f90

!   D03PSF Example Program Text
!   Mark 26 Release. NAG Copyright 2016.

    Module d03psfe_mod

!     D03PSF Example Program Module:
!            Parameters and User-defined Routines

!     .. Use Statements ..
      Use nag_library, Only: nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Accessibility Statements ..
      Private
      Public                           :: bndry1, bndry2, exact, monit1,       &
                                          monit2, nmflx1, nmflx2, pdef1,       &
                                          pdef2, uvin1, uvin2
!     .. Parameters ..
      Real (Kind=nag_wp), Parameter    :: half = 0.5_nag_wp
      Real (Kind=nag_wp), Parameter, Public :: one = 1.0_nag_wp
      Real (Kind=nag_wp), Parameter, Public :: zero = 0.0_nag_wp
      Integer, Parameter, Public       :: itrace = 0, ncode = 0, nin = 5,      &
                                          nout = 6, npde = 1, nxfix = 0,       &
                                          nxi = 0
    Contains
      Subroutine exact(t,u,x,npts)
!       Exact solution (for comparison and b.c. purposes)

!       .. Scalar Arguments ..
        Real (Kind=nag_wp), Intent (In) :: t
        Integer, Intent (In)           :: npts
!       .. Array Arguments ..
        Real (Kind=nag_wp), Intent (Out) :: u(1,npts)
        Real (Kind=nag_wp), Intent (In) :: x(*)
!       .. Local Scalars ..
        Real (Kind=nag_wp)             :: del, psi, rm, rn, s
        Integer                        :: i
!       .. Executable Statements ..
        s = 0.1_nag_wp
        del = 0.01_nag_wp
        rm = -one/del
        rn = one + s/del
        Do i = 1, npts
          psi = x(i) - t
          If (psi<s) Then
            u(1,i) = one
          Else If (psi>(del+s)) Then
            u(1,i) = zero
          Else
            u(1,i) = rm*psi + rn
          End If
        End Do
        Return
      End Subroutine exact
      Subroutine uvin1(npde,npts,nxi,x,xi,u,ncode,v)

!       .. Use Statements ..
        Use nag_library, Only: x01aaf
!       .. Scalar Arguments ..
        Integer, Intent (In)           :: ncode, npde, npts, nxi
!       .. Array Arguments ..
        Real (Kind=nag_wp), Intent (Out) :: u(npde,npts), v(ncode)
        Real (Kind=nag_wp), Intent (In) :: x(npts), xi(nxi)
!       .. Local Scalars ..
        Real (Kind=nag_wp)             :: pi, tmp
        Integer                        :: i
!       .. Intrinsic Procedures ..
        Intrinsic                      :: sin
!       .. Executable Statements ..
        tmp = zero
        pi = x01aaf(tmp)
        Do i = 1, npts
          If (x(i)>0.2_nag_wp .And. x(i)<=0.4_nag_wp) Then
            tmp = pi*(5.0_nag_wp*x(i)-one)
            u(1,i) = sin(tmp)
          Else
            u(1,i) = zero
          End If
        End Do
        Return
      End Subroutine uvin1
      Subroutine pdef1(npde,t,x,u,ux,ncode,v,vdot,p,c,d,s,ires)

!       .. Scalar Arguments ..
        Real (Kind=nag_wp), Intent (In) :: t, x
        Integer, Intent (Inout)        :: ires
        Integer, Intent (In)           :: ncode, npde
!       .. Array Arguments ..
        Real (Kind=nag_wp), Intent (Out) :: c(npde), d(npde), p(npde,npde),    &
                                          s(npde)
        Real (Kind=nag_wp), Intent (In) :: u(npde), ux(npde), v(ncode),        &
                                          vdot(ncode)
!       .. Executable Statements ..
        p(1,1) = one
        c(1) = 0.002_nag_wp
        d(1) = ux(1)
        s(1) = zero
        Return
      End Subroutine pdef1
      Subroutine bndry1(npde,npts,t,x,u,ncode,v,vdot,ibnd,g,ires)

!       Zero solution at both boundaries

!       .. Scalar Arguments ..
        Real (Kind=nag_wp), Intent (In) :: t
        Integer, Intent (In)           :: ibnd, ncode, npde, npts
        Integer, Intent (Inout)        :: ires
!       .. Array Arguments ..
        Real (Kind=nag_wp), Intent (Out) :: g(npde)
        Real (Kind=nag_wp), Intent (In) :: u(npde,npts), v(ncode),             &
                                          vdot(ncode), x(npts)
!       .. Executable Statements ..
        If (ibnd==0) Then
          g(1) = u(1,1)
        Else
          g(1) = u(1,npts)
        End If
        Return
      End Subroutine bndry1
      Subroutine monit1(t,npts,npde,x,u,fmon)

!       .. Scalar Arguments ..
        Real (Kind=nag_wp), Intent (In) :: t
        Integer, Intent (In)           :: npde, npts
!       .. Array Arguments ..
        Real (Kind=nag_wp), Intent (Out) :: fmon(npts)
        Real (Kind=nag_wp), Intent (In) :: u(npde,npts), x(npts)
!       .. Local Scalars ..
        Real (Kind=nag_wp)             :: h1, h2, h3
        Integer                        :: i
!       .. Intrinsic Procedures ..
        Intrinsic                      :: abs
!       .. Executable Statements ..
        Do i = 2, npts - 1
          h1 = x(i) - x(i-1)
          h2 = x(i+1) - x(i)
          h3 = half*(x(i+1)-x(i-1))
!         Second derivatives ..
          fmon(i) = abs(((u(1,i+1)-u(1,i))/h2-(u(1,i)-u(1,i-1))/h1)/h3)
        End Do
        fmon(1) = fmon(2)
        fmon(npts) = fmon(npts-1)
        Return
      End Subroutine monit1
      Subroutine nmflx1(npde,t,x,ncode,v,uleft,uright,flux,ires)

!       .. Scalar Arguments ..
        Real (Kind=nag_wp), Intent (In) :: t, x
        Integer, Intent (Inout)        :: ires
        Integer, Intent (In)           :: ncode, npde
!       .. Array Arguments ..
        Real (Kind=nag_wp), Intent (Out) :: flux(npde)
        Real (Kind=nag_wp), Intent (In) :: uleft(npde), uright(npde), v(ncode)
!       .. Executable Statements ..
        flux(1) = uleft(1)
        Return
      End Subroutine nmflx1
      Subroutine uvin2(npde,npts,nxi,x,xi,u,ncode,v)

!       .. Scalar Arguments ..
        Integer, Intent (In)           :: ncode, npde, npts, nxi
!       .. Array Arguments ..
        Real (Kind=nag_wp), Intent (Out) :: u(npde,npts), v(ncode)
        Real (Kind=nag_wp), Intent (In) :: x(npts), xi(nxi)
!       .. Local Scalars ..
        Real (Kind=nag_wp)             :: t
!       .. Executable Statements ..
        t = zero
        Call exact(t,u,x,npts)
        Return
      End Subroutine uvin2
      Subroutine pdef2(npde,t,x,u,ux,ncode,v,vdot,p,c,d,s,ires)

!       .. Scalar Arguments ..
        Real (Kind=nag_wp), Intent (In) :: t, x
        Integer, Intent (Inout)        :: ires
        Integer, Intent (In)           :: ncode, npde
!       .. Array Arguments ..
        Real (Kind=nag_wp), Intent (Out) :: c(npde), d(npde), p(npde,npde),    &
                                          s(npde)
        Real (Kind=nag_wp), Intent (In) :: u(npde), ux(npde), v(ncode),        &
                                          vdot(ncode)
!       .. Executable Statements ..
        p(1,1) = one
        c(1) = zero
        d(1) = zero
        s(1) = -100.0_nag_wp*u(1)*(u(1)-one)*(u(1)-half)
        Return
      End Subroutine pdef2
      Subroutine bndry2(npde,npts,t,x,u,ncode,v,vdot,ibnd,g,ires)

!       .. Scalar Arguments ..
        Real (Kind=nag_wp), Intent (In) :: t
        Integer, Intent (In)           :: ibnd, ncode, npde, npts
        Integer, Intent (Inout)        :: ires
!       .. Array Arguments ..
        Real (Kind=nag_wp), Intent (Out) :: g(npde)
        Real (Kind=nag_wp), Intent (In) :: u(npde,npts), v(ncode),             &
                                          vdot(ncode), x(npts)
!       .. Local Arrays ..
        Real (Kind=nag_wp)             :: ue(1,1)
!       .. Executable Statements ..
!       Solution known to be constant at both boundaries
        If (ibnd==0) Then
          Call exact(t,ue,x(1),1)
          g(1) = ue(1,1) - u(1,1)
        Else
          Call exact(t,ue,x(npts),1)
          g(1) = ue(1,1) - u(1,npts)
        End If
        Return
      End Subroutine bndry2
      Subroutine nmflx2(npde,t,x,ncode,v,uleft,uright,flux,ires)

!       .. Scalar Arguments ..
        Real (Kind=nag_wp), Intent (In) :: t, x
        Integer, Intent (Inout)        :: ires
        Integer, Intent (In)           :: ncode, npde
!       .. Array Arguments ..
        Real (Kind=nag_wp), Intent (Out) :: flux(npde)
        Real (Kind=nag_wp), Intent (In) :: uleft(npde), uright(npde), v(ncode)
!       .. Executable Statements ..
        flux(1) = uleft(1)
        Return
      End Subroutine nmflx2
      Subroutine monit2(t,npts,npde,x,u,fmon)

!       .. Use Statements ..
        Use nag_library, Only: x01aaf
!       .. Scalar Arguments ..
        Real (Kind=nag_wp), Intent (In) :: t
        Integer, Intent (In)           :: npde, npts
!       .. Array Arguments ..
        Real (Kind=nag_wp), Intent (Out) :: fmon(npts)
        Real (Kind=nag_wp), Intent (In) :: u(npde,npts), x(npts)
!       .. Local Scalars ..
        Real (Kind=nag_wp)             :: h1, pi, ux, uxmax, xa, xl, xmax, xr, &
                                          xx
        Integer                        :: i
!       .. Intrinsic Procedures ..
        Intrinsic                      :: abs, cos
!       .. Executable Statements ..
        xx = zero
        pi = x01aaf(xx)
!       Locate shock ..
        uxmax = zero
        xmax = zero
        Do i = 2, npts - 1
          h1 = x(i) - x(i-1)
          ux = abs((u(1,i)-u(1,i-1))/h1)
          If (ux>uxmax) Then
            uxmax = ux
            xmax = x(i)
          End If
        End Do

!       Desired width of nonzero region of monitor function
        xa = 7.0_nag_wp/60.0_nag_wp

        xl = xmax - xa
        xr = xmax + xa
!       Assign monitor function ..
        Do i = 1, npts
          If (x(i)>xl .And. x(i)<xr) Then
            fmon(i) = one + cos(pi*(x(i)-xmax)/xa)
          Else
            fmon(i) = zero
          End If
        End Do
        Return
      End Subroutine monit2
    End Module d03psfe_mod
    Program d03psfe

!     D03PSF Example Main Program

!     .. Use Statements ..
      Use d03psfe_mod, Only: nout
!     .. Implicit None Statement ..
      Implicit None
!     .. Executable Statements ..
      Write (nout,*) 'D03PSF Example Program Results'

      Call ex1

      Call ex2

    Contains
      Subroutine ex1

!       .. Use Statements ..
        Use nag_library, Only: d03pek, d03psf, d03pzf, nag_wp
        Use d03psfe_mod, Only: bndry1, itrace, monit1, ncode, nin, nmflx1,     &
                               npde, nxfix, nxi, one, pdef1, uvin1, zero
!       .. Local Scalars ..
        Real (Kind=nag_wp)             :: con, dxmesh, tout, trmesh, ts,       &
                                          xratio
        Integer                        :: i, ifail, ind, intpts, ipminf, it,   &
                                          itask, itol, itype, lenode, lisave,  &
                                          lrsave, m, mlu, neqn, npts, nrmesh,  &
                                          nwkres
        Logical                        :: remesh
        Character (1)                  :: laopt, norm
!       .. Local Arrays ..
        Real (Kind=nag_wp)             :: algopt(30), atol(1), rtol(1),        &
                                          xfix(1), xi(1)
        Real (Kind=nag_wp), Allocatable :: rsave(:), u(:,:), uout(:,:,:),      &
                                          x(:), xout(:)
        Integer, Allocatable           :: isave(:)
!       .. Intrinsic Procedures ..
        Intrinsic                      :: real
!       .. Executable Statements ..
        Write (nout,*)
        Write (nout,*)
        Write (nout,*) 'Example 1'
!       Skip heading in data file
        Read (nin,*)
        Read (nin,*) npts, intpts, itype
        nwkres = npde*(3*npts+3*npde+32) + 7*npts + 3
        mlu = 3*npde - 1
        neqn = npde*npts + ncode
        lenode = 11*neqn + 50
        lisave = 25 + nxfix + neqn
        lrsave = (3*mlu+1)*neqn + nwkres + lenode

        Allocate (rsave(lrsave),u(npde,npts),uout(npde,intpts,itype),x(npts),  &
          xout(intpts),isave(lisave))
        Read (nin,*) xout(1:intpts)
        Read (nin,*) itol
        Read (nin,*) norm
        Read (nin,*) atol(1), rtol(1)

!       Initialize mesh
        Do i = 1, npts
          x(i) = real(i-1,kind=nag_wp)/real(npts-1,kind=nag_wp)
        End Do
        xfix(1) = zero

!       Set remesh parameters
        remesh = .True.
        nrmesh = 3
        dxmesh = zero
        trmesh = zero
        con = 2.0_nag_wp/real(npts-1,kind=nag_wp)
        xratio = 1.5_nag_wp
        ipminf = 0

        xi(1) = zero
        laopt = 'B'
        ind = 0
        itask = 1

        algopt(1:30) = zero
!       b.d.f. integration
        algopt(1) = one
        algopt(13) = 0.005_nag_wp

!       Loop over output value of t

        ts = zero
        tout = zero
        Do it = 1, 3
          tout = real(it,kind=nag_wp)*0.1_nag_wp

!         ifail: behaviour on error exit
!                =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
          ifail = 0
          Call d03psf(npde,ts,tout,pdef1,nmflx1,bndry1,uvin1,u,npts,x,ncode,   &
            d03pek,nxi,xi,neqn,rtol,atol,itol,norm,laopt,algopt,remesh,nxfix,  &
            xfix,nrmesh,dxmesh,trmesh,ipminf,xratio,con,monit1,rsave,lrsave,   &
            isave,lisave,itask,itrace,ind,ifail)

          If (it==1) Then
            Write (nout,*)
            Write (nout,99998) npts, atol, rtol
          End If

          Write (nout,99999) ts
          Write (nout,99996) xout(1:intpts)
!         Interpolate at output points ..
          m = 0

          ifail = 0
          Call d03pzf(npde,m,u,npts,x,xout,intpts,itype,uout,ifail)

          Write (nout,99995) uout(1,1:intpts,1)
        End Do

        Write (nout,99997) isave(1), isave(2), isave(3), isave(5)

        Return

99999   Format (' T = ',F6.3)
99998   Format (/,'  NPTS = ',I4,' ATOL = ',E10.3,' RTOL = ',E10.3,/)
99997   Format (' Number of integration steps in time = ',I6,/,' Number ',     &
          'of function evaluations = ',I6,/,' Number of Jacobian ',            &
          'evaluations =',I6,/,' Number of iterations = ',I6)
99996   Format (1X,'X        ',7F9.4)
99995   Format (1X,'Approx U ',7F9.4,/)
      End Subroutine ex1
      Subroutine ex2

!       .. Use Statements ..
        Use nag_library, Only: d03pek, d03psf, d03pzf, nag_wp
        Use d03psfe_mod, Only: bndry2, exact, itrace, monit2, ncode, nin,      &
                               nmflx2, npde, nxfix, nxi, one, pdef2, uvin2,    &
                               zero
!       .. Local Scalars ..
        Real (Kind=nag_wp)             :: con, dxmesh, tout, trmesh, ts,       &
                                          xratio
        Integer                        :: i, ifail, ind, intpts, ipminf, it,   &
                                          itask, itol, itype, lenode, lisave,  &
                                          lrsave, m, mlu, neqn, npts, nrmesh,  &
                                          nwkres
        Logical                        :: remesh
        Character (1)                  :: laopt, norm
!       .. Local Arrays ..
        Real (Kind=nag_wp)             :: algopt(30), atol(1), rtol(1),        &
                                          xfix(1), xi(1)
        Real (Kind=nag_wp), Allocatable :: rsave(:), u(:), ue(:,:),            &
                                          uout(:,:,:), x(:), xout(:)
        Integer, Allocatable           :: isave(:)
!       .. Intrinsic Procedures ..
        Intrinsic                      :: real
!       .. Executable Statements ..
        Write (nout,*)
        Write (nout,*)
        Write (nout,*) 'Example 2'
!       Skip heading in data file
        Read (nin,*)
        Read (nin,*) npts, intpts, itype
        nwkres = npde*(3*npts+3*npde+32) + 7*npts + 3
        mlu = 3*npde - 1
        neqn = npde*npts + ncode
        lenode = 11*neqn + 50
        lisave = 25 + nxfix + neqn
        lrsave = (3*mlu+1)*neqn + nwkres + lenode

        Allocate (rsave(lrsave),u(neqn),ue(1,intpts),uout(1,intpts,itype),     &
          x(npts),xout(intpts),isave(lisave))

        Read (nin,*) xout(1:intpts)
        Read (nin,*) itol
        Read (nin,*) norm
        Read (nin,*) atol(1), rtol(1)

!       Initialize mesh
        Do i = 1, npts
          x(i) = real(i-1,kind=nag_wp)/real(npts-1,kind=nag_wp)
        End Do
        xfix(1) = zero

!       Set remesh parameters
        remesh = .True.
        nrmesh = 5
        dxmesh = zero
        con = one/real(npts-1,kind=nag_wp)
        xratio = 1.5_nag_wp
        ipminf = 0

        xi(1) = zero
        laopt = 'B'
        ind = 0
        itask = 1

        algopt(1:30) = zero
!       Theta integration ..
        algopt(1) = 2.0_nag_wp
        algopt(6) = 2.0_nag_wp
        algopt(7) = 2.0_nag_wp
!       Max. time step ..
        algopt(13) = 2.5E-3_nag_wp

        ts = zero
        tout = zero
        Do it = 1, 2
          tout = real(it,kind=nag_wp)*0.2_nag_wp

          ifail = 0
          Call d03psf(npde,ts,tout,pdef2,nmflx2,bndry2,uvin2,u,npts,x,ncode,   &
            d03pek,nxi,xi,neqn,rtol,atol,itol,norm,laopt,algopt,remesh,nxfix,  &
            xfix,nrmesh,dxmesh,trmesh,ipminf,xratio,con,monit2,rsave,lrsave,   &
            isave,lisave,itask,itrace,ind,ifail)

          If (it==1) Then
            Write (nout,*)
            Write (nout,99998) npts, atol, rtol
          End If

          Write (nout,99999) ts
          Write (nout,99996)
!         Interpolate at output points ..
          m = 0

          ifail = 0
          Call d03pzf(npde,m,u,npts,x,xout,intpts,itype,uout,ifail)

!         Check against exact solution ..
          Call exact(tout,ue,xout,intpts)
          Do i = 1, intpts
            Write (nout,99995) xout(i), uout(1,i,1), ue(1,i)
          End Do
        End Do

        Write (nout,99997) isave(1), isave(2), isave(3), isave(5)

        Return

99999   Format (' T = ',F6.3)
99998   Format (/,' NPTS = ',I4,' ATOL = ',E10.3,' RTOL = ',E10.3,/)
99997   Format (/,' Number of integration steps in time = ',I6,/,' Number ',   &
          'of function evaluations = ',I6,/,' Number of Jacobian ',            &
          'evaluations =',I6,/,' Number of iterations = ',I6)
99996   Format (8X,'X',8X,'Approx U',4X,'Exact U',/)
99995   Format (3(3X,F9.4))
      End Subroutine ex2
    End Program d03psfe


d03pwfe.f90

!   D03PWF Example Program Text
!   Mark 26 Release. NAG Copyright 2016.

    Module d03pwfe_mod

!     D03PWF Example Program Module:
!            Parameters and User-defined Routines

!     .. Use Statements ..
      Use nag_library, Only: nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Accessibility Statements ..
      Private
      Public                           :: bndary, numflx
!     .. Parameters ..
      Real (Kind=nag_wp), Parameter, Public :: alpha_l = 460.894_nag_wp
      Real (Kind=nag_wp), Parameter, Public :: alpha_r = 46.095_nag_wp
      Real (Kind=nag_wp), Parameter, Public :: beta_l = 19.5975_nag_wp
      Real (Kind=nag_wp), Parameter, Public :: beta_r = 6.19633_nag_wp
      Real (Kind=nag_wp), Parameter, Public :: half = 0.5_nag_wp
      Integer, Parameter, Public       :: itrace = 0, ncode = 0, nin = 5,      &
                                          nout = 6, npde = 3, nxi = 0
!     .. Local Scalars ..
      Real (Kind=nag_wp), Public, Save :: el0, er0, gamma, rl0, rr0, ul0, ur0
    Contains
      Subroutine bndary(npde,npts,t,x,u,ncode,v,vdot,ibnd,g,ires)

!       .. Scalar Arguments ..
        Real (Kind=nag_wp), Intent (In) :: t
        Integer, Intent (In)           :: ibnd, ncode, npde, npts
        Integer, Intent (Inout)        :: ires
!       .. Array Arguments ..
        Real (Kind=nag_wp), Intent (Out) :: g(npde)
        Real (Kind=nag_wp), Intent (In) :: u(npde,npts), v(ncode),             &
                                          vdot(ncode), x(npts)
!       .. Executable Statements ..
        If (ibnd==0) Then
          g(1) = u(1,1) - rl0
          g(2) = u(2,1) - ul0
          g(3) = u(3,1) - el0
        Else
          g(1) = u(1,npts) - rr0
          g(2) = u(2,npts) - ur0
          g(3) = u(3,npts) - er0
        End If
        Return
      End Subroutine bndary
      Subroutine numflx(npde,t,x,ncode,v,uleft,uright,flux,ires)

!       .. Use Statements ..
        Use nag_library, Only: d03pwf
!       .. Scalar Arguments ..
        Real (Kind=nag_wp), Intent (In) :: t, x
        Integer, Intent (Inout)        :: ires
        Integer, Intent (In)           :: ncode, npde
!       .. Array Arguments ..
        Real (Kind=nag_wp), Intent (Out) :: flux(npde)
        Real (Kind=nag_wp), Intent (In) :: uleft(npde), uright(npde), v(ncode)
!       .. Local Scalars ..
        Integer                        :: ifail
!       .. Executable Statements ..
        ifail = 0
        Call d03pwf(uleft,uright,gamma,flux,ifail)
        Return
      End Subroutine numflx
    End Module d03pwfe_mod
    Program d03pwfe

!     D03PWF Example Main Program

!     .. Use Statements ..
      Use nag_library, Only: d03pek, d03plf, d03plp, nag_wp
      Use d03pwfe_mod, Only: alpha_l, alpha_r, beta_l, beta_r, bndary, el0,    &
                             er0, gamma, half, itrace, ncode, nin, nout, npde, &
                             numflx, nxi, rl0, rr0, ul0, ur0
!     .. Implicit None Statement ..
      Implicit None
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: d, p, tout, ts, v
      Integer                          :: i, ifail, ind, itask, itol, k,       &
                                          lenode, mlu, neqn, niw, npts, nw,    &
                                          nwkres
      Character (1)                    :: laopt, norm
!     .. Local Arrays ..
      Real (Kind=nag_wp)               :: algopt(30), atol(1), rtol(1),        &
                                          ue(3,9), xi(1)
      Real (Kind=nag_wp), Allocatable  :: u(:,:), w(:), x(:)
      Integer, Allocatable             :: iw(:)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: real
!     .. Executable Statements ..
      Write (nout,*) 'D03PWF Example Program Results'
!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) npts

      nwkres = npde*(2*npts+3*npde+32) + 7*npts + 4
      mlu = 3*npde - 1
      neqn = npde*npts + ncode
      niw = neqn + 24
      lenode = 9*neqn + 50
      nw = (3*mlu+1)*neqn + nwkres + lenode
      Allocate (u(npde,npts),w(nw),x(npts),iw(niw))

      Read (nin,*) gamma, rl0, rr0, ul0, ur0

      el0 = alpha_l/(gamma-1.0_nag_wp) + half*rl0*beta_l**2
      er0 = alpha_r/(gamma-1.0_nag_wp) + half*rr0*beta_r**2

!     Initialize mesh
      Do i = 1, npts
        x(i) = real(i-1,kind=nag_wp)/real(npts-1,kind=nag_wp)
      End Do
      xi(1) = 0.0_nag_wp

!     Initial values

      Do i = 1, npts
        If (x(i)<half) Then
          u(1,i) = rl0
          u(2,i) = ul0
          u(3,i) = el0
        Else If (x(i)==half) Then
          u(1,i) = half*(rl0+rr0)
          u(2,i) = half*(ul0+ur0)
          u(3,i) = half*(el0+er0)
        Else
          u(1,i) = rr0
          u(2,i) = ur0
          u(3,i) = er0
        End If
      End Do

      Read (nin,*) itol
      Read (nin,*) norm
      Read (nin,*) atol(1), rtol(1)
      Read (nin,*) laopt
      ind = 0
      itask = 1
      algopt(1:30) = 0.0_nag_wp

!     Theta integration
      algopt(1) = 2.0_nag_wp
      algopt(6) = 2.0_nag_wp
      algopt(7) = 2.0_nag_wp

!     Max. time step
      algopt(13) = 0.5E-2_nag_wp

      ts = 0.0_nag_wp
      tout = 0.035_nag_wp

!     ifail: behaviour on error exit
!            =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
      ifail = 0
      Call d03plf(npde,ts,tout,d03plp,numflx,bndary,u,npts,x,ncode,d03pek,nxi, &
        xi,neqn,rtol,atol,itol,norm,laopt,algopt,w,nw,iw,niw,itask,itrace,ind, &
        ifail)

      Write (nout,99998) ts
      Write (nout,99999)

!     Read exact data at output points

      Do i = 1, 9
        Read (nin,*) ue(1:3,i)
      End Do

!     Calculate density, velocity and pressure

      k = 0
      Do i = 15, npts - 14, 14
        d = u(1,i)
        v = u(2,i)/d
        p = d*(gamma-1.0_nag_wp)*(u(3,i)/d-half*v**2)
        k = k + 1
        Write (nout,99996) x(i), d, ue(1,k), v, ue(2,k), p, ue(3,k)
      End Do

      Write (nout,99997) iw(1), iw(2), iw(3), iw(5)

99999 Format (4X,'X',7X,'APPROX D',3X,'EXACT D',4X,'APPROX V',3X,'EXAC','T V', &
        4X,'APPROX P',3X,'EXACT P')
99998 Format (/,' T = ',F6.3,/)
99997 Format (/,' Number of integration steps in time = ',I6,/,' Number ',     &
        'of function evaluations = ',I6,/,' Number of Jacobian ',              &
        'evaluations =',I6,/,' Number of iterations = ',I6)
99996 Format (1X,E9.2,6(E11.4))
    End Program d03pwfe


d03pxfe.f90

!   D03PXF Example Program Text
!   Mark 26 Release. NAG Copyright 2016.

    Module d03pxfe_mod

!     D03PXF Example Program Module:
!            Parameters and User-defined Routines

!     .. Use Statements ..
      Use nag_library, Only: nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Accessibility Statements ..
      Private
      Public                           :: bndary, numflx
!     .. Parameters ..
      Real (Kind=nag_wp), Parameter, Public :: alpha_l = 460.894_nag_wp
      Real (Kind=nag_wp), Parameter, Public :: alpha_r = 46.095_nag_wp
      Real (Kind=nag_wp), Parameter, Public :: beta_l = 19.5975_nag_wp
      Real (Kind=nag_wp), Parameter, Public :: beta_r = 6.19633_nag_wp
      Real (Kind=nag_wp), Parameter, Public :: half = 0.5_nag_wp
      Integer, Parameter, Public       :: itrace = 0, ncode = 0, nin = 5,      &
                                          nout = 6, npde = 3, nxi = 0
!     .. Local Scalars ..
      Real (Kind=nag_wp), Public, Save :: el0, er0, gamma, rl0, rr0, ul0, ur0
    Contains
      Subroutine bndary(npde,npts,t,x,u,ncode,v,vdot,ibnd,g,ires)

!       .. Scalar Arguments ..
        Real (Kind=nag_wp), Intent (In) :: t
        Integer, Intent (In)           :: ibnd, ncode, npde, npts
        Integer, Intent (Inout)        :: ires
!       .. Array Arguments ..
        Real (Kind=nag_wp), Intent (Out) :: g(npde)
        Real (Kind=nag_wp), Intent (In) :: u(npde,npts), v(ncode),             &
                                          vdot(ncode), x(npts)
!       .. Executable Statements ..
        If (ibnd==0) Then
          g(1) = u(1,1) - rl0
          g(2) = u(2,1) - ul0
          g(3) = u(3,1) - el0
        Else
          g(1) = u(1,npts) - rr0
          g(2) = u(2,npts) - ur0
          g(3) = u(3,npts) - er0
        End If
        Return
      End Subroutine bndary
      Subroutine numflx(npde,t,x,ncode,v,uleft,uright,flux,ires)

!       .. Use Statements ..
        Use nag_library, Only: d03pxf
!       .. Scalar Arguments ..
        Real (Kind=nag_wp), Intent (In) :: t, x
        Integer, Intent (Inout)        :: ires
        Integer, Intent (In)           :: ncode, npde
!       .. Array Arguments ..
        Real (Kind=nag_wp), Intent (Out) :: flux(npde)
        Real (Kind=nag_wp), Intent (In) :: uleft(npde), uright(npde), v(ncode)
!       .. Local Scalars ..
        Real (Kind=nag_wp)             :: tol
        Integer                        :: ifail, niter
!       .. Executable Statements ..
        tol = 0.0_nag_wp
        niter = 0

        ifail = 0
        Call d03pxf(uleft,uright,gamma,tol,niter,flux,ifail)

        Return
      End Subroutine numflx
    End Module d03pxfe_mod
    Program d03pxfe

!     D03PXF Example Main Program

!     .. Use Statements ..
      Use nag_library, Only: d03pek, d03plf, d03plp, nag_wp
      Use d03pxfe_mod, Only: alpha_l, alpha_r, beta_l, beta_r, bndary, el0,    &
                             er0, gamma, half, itrace, ncode, nin, nout, npde, &
                             numflx, nxi, rl0, rr0, ul0, ur0
!     .. Implicit None Statement ..
      Implicit None
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: d, p, tout, ts, v
      Integer                          :: i, ifail, ind, itask, itol, k,       &
                                          lenode, mlu, neqn, niw, npts, nw,    &
                                          nwkres
      Character (1)                    :: laopt, norm
!     .. Local Arrays ..
      Real (Kind=nag_wp)               :: algopt(30), atol(1), rtol(1),        &
                                          ue(3,9), xi(1)
      Real (Kind=nag_wp), Allocatable  :: u(:,:), w(:), x(:)
      Integer, Allocatable             :: iw(:)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: real
!     .. Executable Statements ..
      Write (nout,*) 'D03PXF Example Program Results'
!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) npts

      nwkres = npde*(2*npts+3*npde+32) + 7*npts + 4
      mlu = 3*npde - 1
      neqn = npde*npts + ncode
      niw = neqn + 24
      lenode = 9*neqn + 50
      nw = (3*mlu+1)*neqn + nwkres + lenode
      Allocate (u(npde,npts),w(nw),x(npts),iw(niw))

      Read (nin,*) gamma, rl0, rr0, ul0, ur0

      el0 = alpha_l/(gamma-1.0_nag_wp) + half*rl0*beta_l**2
      er0 = alpha_r/(gamma-1.0_nag_wp) + half*rr0*beta_r**2

!     Initialize mesh
      Do i = 1, npts
        x(i) = real(i-1,kind=nag_wp)/real(npts-1,kind=nag_wp)
      End Do
      xi(1) = 0.0_nag_wp

!     Initial values
      Do i = 1, npts
        If (x(i)<half) Then
          u(1,i) = rl0
          u(2,i) = ul0
          u(3,i) = el0
        Else If (x(i)==half) Then
          u(1,i) = half*(rl0+rr0)
          u(2,i) = half*(ul0+ur0)
          u(3,i) = half*(el0+er0)
        Else
          u(1,i) = rr0
          u(2,i) = ur0
          u(3,i) = er0
        End If
      End Do

      Read (nin,*) itol
      Read (nin,*) norm
      Read (nin,*) atol(1), rtol(1)
      Read (nin,*) laopt

      ind = 0
      itask = 1
      algopt(1:30) = 0.0_nag_wp

!     Theta integration
      algopt(1) = 2.0_nag_wp
      algopt(6) = 2.0_nag_wp
      algopt(7) = 2.0_nag_wp

!     Max. time step
      algopt(13) = 0.5E-2_nag_wp

      ts = 0.0_nag_wp
      tout = 0.035_nag_wp

!     ifail: behaviour on error exit
!            =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
      ifail = 0
      Call d03plf(npde,ts,tout,d03plp,numflx,bndary,u,npts,x,ncode,d03pek,nxi, &
        xi,neqn,rtol,atol,itol,norm,laopt,algopt,w,nw,iw,niw,itask,itrace,ind, &
        ifail)

      Write (nout,99998) ts
      Write (nout,99999)

!     Read exact data at output points

      Do i = 1, 9
        Read (nin,*) ue(1:3,i)
      End Do

!     Calculate density, velocity and pressure

      k = 0
      Do i = 15, npts - 14, 14
        d = u(1,i)
        v = u(2,i)/d
        p = d*(gamma-1.0_nag_wp)*(u(3,i)/d-half*v**2)
        k = k + 1
        Write (nout,99996) x(i), d, ue(1,k), v, ue(2,k), p, ue(3,k)
      End Do

      Write (nout,99997) iw(1), iw(2), iw(3), iw(5)

99999 Format (4X,'X',7X,'APPROX D',3X,'EXACT D',4X,'APPROX V',3X,'EXAC','T V', &
        4X,'APPROX P',3X,'EXACT P')
99998 Format (/,' T = ',F6.3,/)
99997 Format (/,' Number of integration steps in time = ',I6,/,' Number ',     &
        'of function evaluations = ',I6,/,' Number of Jacobian ',              &
        'evaluations =',I6,/,' Number of iterations = ',I6)
99996 Format (1X,E9.2,6(E11.4))
    End Program d03pxfe


d03rafe.f90

!   D03RAF Example Program Text
!   Mark 26 Release. NAG Copyright 2016.

    Module d03rafe_mod

!     D03RAF Example Program Module:
!            Parameters and User-defined Routines

!     .. Use Statements ..
      Use nag_library, Only: nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Accessibility Statements ..
      Private
      Public                           :: bndry1, bndry2,                      &
                                          compute_wkspace_lens, monit1,        &
                                          monit2, monit_dummy, pdedef1,        &
                                          pdedef2, pdeiv1, pdeiv2,             &
                                          print_statistics
!     .. Parameters ..
      Real (Kind=nag_wp), Parameter    :: alpha = 50.0_nag_wp
      Real (Kind=nag_wp), Parameter    :: beta = 300.0_nag_wp
      Real (Kind=nag_wp), Parameter, Public :: one = 1.0_nag_wp
      Real (Kind=nag_wp), Parameter, Public :: xmax = one
      Real (Kind=nag_wp), Parameter, Public :: ymax = one
      Real (Kind=nag_wp), Parameter, Public :: zero = 0.0_nag_wp
      Real (Kind=nag_wp), Parameter, Public :: xmin = zero
      Real (Kind=nag_wp), Parameter, Public :: ymin = zero
      Integer, Parameter, Public       :: itrace = 0, nin = 5, nout = 6,       &
                                          npde1 = 1, npde2 = 2
    Contains
      Subroutine pdeiv1(npts,npde,t,x,y,u)

!       .. Scalar Arguments ..
        Real (Kind=nag_wp), Intent (In) :: t
        Integer, Intent (In)           :: npde, npts
!       .. Array Arguments ..
        Real (Kind=nag_wp), Intent (Out) :: u(npts,npde)
        Real (Kind=nag_wp), Intent (In) :: x(npts), y(npts)
!       .. Executable Statements ..
        u(1:npts,1:npde) = one
        Return
      End Subroutine pdeiv1
      Subroutine pdedef1(npts,npde,t,x,y,u,ut,ux,uy,uxx,uxy,uyy,res)

!       .. Parameters ..
        Real (Kind=nag_wp), Parameter  :: activ_energy = 20.0_nag_wp
        Real (Kind=nag_wp), Parameter  :: diffusion = 0.1_nag_wp
        Real (Kind=nag_wp), Parameter  :: heat_release = 1.0_nag_wp
        Real (Kind=nag_wp), Parameter  :: reaction_rate = 5.0_nag_wp
!       .. Scalar Arguments ..
        Real (Kind=nag_wp), Intent (In) :: t
        Integer, Intent (In)           :: npde, npts
!       .. Array Arguments ..
        Real (Kind=nag_wp), Intent (Out) :: res(npts,npde)
        Real (Kind=nag_wp), Intent (In) :: u(npts,npde), ut(npts,npde),        &
                                          ux(npts,npde), uxx(npts,npde),       &
                                          uxy(npts,npde), uy(npts,npde),       &
                                          uyy(npts,npde), x(npts), y(npts)
!       .. Local Scalars ..
        Real (Kind=nag_wp)             :: damkohler
        Integer                        :: i
!       .. Intrinsic Procedures ..
        Intrinsic                      :: exp
!       .. Executable Statements ..
        damkohler = reaction_rate*exp(activ_energy)/                           &
          (heat_release*activ_energy)
        !$Omp Do
        Do i = 1, npts
          res(i,1:npde) = ut(i,1:npde) - diffusion*(uxx(i,1:npde)+uyy(i,1:npde &
            )) - damkohler*(1.0E0_nag_wp+heat_release-u(i,1:npde))*exp(        &
            -activ_energy/u(i,1:npde))
        End Do
        !$Omp End Do
        Return
      End Subroutine pdedef1
      Subroutine bndry1(npts,npde,t,x,y,u,ut,ux,uy,nbpts,lbnd,res)

!       .. Use Statements ..
        Use nag_library, Only: x02ajf
!       .. Scalar Arguments ..
        Real (Kind=nag_wp), Intent (In) :: t
        Integer, Intent (In)           :: nbpts, npde, npts
!       .. Array Arguments ..
        Real (Kind=nag_wp), Intent (Inout) :: res(npts,npde)
        Real (Kind=nag_wp), Intent (In) :: u(npts,npde), ut(npts,npde),        &
                                          ux(npts,npde), uy(npts,npde),        &
                                          x(npts), y(npts)
        Integer, Intent (In)           :: lbnd(nbpts)
!       .. Local Scalars ..
        Real (Kind=nag_wp)             :: tol
        Integer                        :: i, j
!       .. Intrinsic Procedures ..
        Intrinsic                      :: abs
!       .. Executable Statements ..
        tol = 10._nag_wp*x02ajf()

        Do i = 1, nbpts
          j = lbnd(i)

          If (abs(x(j))<=tol) Then
            res(j,1:npde) = ux(j,1:npde)
          Else If (abs(x(j)-one)<=tol) Then
            res(j,1:npde) = u(j,1:npde) - one
          Else If (abs(y(j))<=tol) Then
            res(j,1:npde) = uy(j,1:npde)
          Else If (abs(y(j)-one)<=tol) Then
            res(j,1:npde) = u(j,1:npde) - one
          End If
        End Do

        Return
      End Subroutine bndry1
      Subroutine monit1(npde,t,dt,dtnew,tlast,nlev,ngpts,xpts,ypts,lsol,sol,   &
        ierr)

!       .. Scalar Arguments ..
        Real (Kind=nag_wp), Intent (In) :: dt, dtnew, t
        Integer, Intent (Inout)        :: ierr
        Integer, Intent (In)           :: nlev, npde
        Logical, Intent (In)           :: tlast
!       .. Array Arguments ..
        Real (Kind=nag_wp), Intent (In) :: sol(*), xpts(*), ypts(*)
        Integer, Intent (In)           :: lsol(nlev), ngpts(nlev)
!       .. Local Scalars ..
        Integer                        :: i, ipsol, k, level, npts
!       .. Intrinsic Procedures ..
        Intrinsic                      :: sum
!       .. Executable Statements ..
        If (tlast) Then

!         Print solution

          level = nlev
          Write (nout,99999) level, t
          Write (nout,99998)
          npts = ngpts(level)
          ipsol = lsol(level)
          k = sum(ngpts(1:nlev-1))
          Do i = 1, npts, 4
            Write (nout,99997) xpts(k+i), ypts(k+i), sol(ipsol+i)
          End Do

          Write (nout,*)

        End If

        Return
99999   Format (1X,'Solution at every 4th grid point in level',I10,            &
          ' at time ',F8.4,':')
99998   Format (1X,/,7X,'x',10X,'y',8X,'approx u',/)
99997   Format (1X,1P,E11.4,2(1X,1P,E11.3))
      End Subroutine monit1
      Subroutine pdeiv2(npts,npde,t,x,y,u)

!       .. Use Statements ..
        Use nag_library, Only: x01aaf
!       .. Scalar Arguments ..
        Real (Kind=nag_wp), Intent (In) :: t
        Integer, Intent (In)           :: npde, npts
!       .. Array Arguments ..
        Real (Kind=nag_wp), Intent (Out) :: u(npts,npde)
        Real (Kind=nag_wp), Intent (In) :: x(npts), y(npts)
!       .. Local Scalars ..
        Real (Kind=nag_wp)             :: fourpi
!       .. Intrinsic Procedures ..
        Intrinsic                      :: sin
!       .. Executable Statements ..
        fourpi = 4.0_nag_wp*x01aaf(fourpi)
        u(1:npts,1) = 10.0_nag_wp + (16.0_nag_wp*x(1:npts)*(one-x(1:npts))*y(1 &
          :npts)*(one-y(1:npts)))**2
        u(1:npts,2) = -one - alpha*x(1:npts)*y(1:npts) -                       &
          beta*sin(fourpi*x(1:npts))*sin(fourpi*y(1:npts)) +                   &
          1.0E4_nag_wp*u(1:npts,1)
        Return
      End Subroutine pdeiv2
      Subroutine pdedef2(npts,npde,t,x,y,u,ut,ux,uy,uxx,uxy,uyy,res)

!       .. Use Statements ..
        Use nag_library, Only: x01aaf
!       .. Scalar Arguments ..
        Real (Kind=nag_wp), Intent (In) :: t
        Integer, Intent (In)           :: npde, npts
!       .. Array Arguments ..
        Real (Kind=nag_wp), Intent (Out) :: res(npts,npde)
        Real (Kind=nag_wp), Intent (In) :: u(npts,npde), ut(npts,npde),        &
                                          ux(npts,npde), uxx(npts,npde),       &
                                          uxy(npts,npde), uy(npts,npde),       &
                                          uyy(npts,npde), x(npts), y(npts)
!       .. Local Scalars ..
        Real (Kind=nag_wp)             :: b1, fourpi
        Integer                        :: i
!       .. Intrinsic Procedures ..
        Intrinsic                      :: sin
!       .. Executable Statements ..
        fourpi = 4.0_nag_wp*x01aaf(fourpi)
        Do i = 1, npts
          b1 = 1.0E0_nag_wp + alpha*x(i)*y(i) + beta*sin(fourpi*x(i))*sin(     &
            fourpi*y(i))
          res(i,1) = ut(i,1) - (uxx(i,1)+uyy(i,1)) -                           &
            u(i,1)*(b1-u(i,1)-0.5E-6_nag_wp*u(i,2))
          res(i,2) = -0.05E0_nag_wp*(uxx(i,2)+uyy(i,2)) -                      &
            u(i,2)*(-b1+1.0E4_nag_wp*u(i,1)-u(i,2))
        End Do
        Return
      End Subroutine pdedef2
      Subroutine bndry2(npts,npde,t,x,y,u,ut,ux,uy,nbpts,lbnd,res)

!       .. Use Statements ..
        Use nag_library, Only: x02ajf
!       .. Scalar Arguments ..
        Real (Kind=nag_wp), Intent (In) :: t
        Integer, Intent (In)           :: nbpts, npde, npts
!       .. Array Arguments ..
        Real (Kind=nag_wp), Intent (Inout) :: res(npts,npde)
        Real (Kind=nag_wp), Intent (In) :: u(npts,npde), ut(npts,npde),        &
                                          ux(npts,npde), uy(npts,npde),        &
                                          x(npts), y(npts)
        Integer, Intent (In)           :: lbnd(nbpts)
!       .. Local Scalars ..
        Real (Kind=nag_wp)             :: tol
        Integer                        :: i, j
!       .. Intrinsic Procedures ..
        Intrinsic                      :: abs
!       .. Executable Statements ..
        tol = 10.0_nag_wp*x02ajf()

        Do i = 1, nbpts
          j = lbnd(i)

          If (abs(x(j))<=tol .Or. abs(x(j)-one)<=tol) Then
            res(j,1:npde) = ux(j,1:npde)
          Else If (abs(y(j))<=tol .Or. abs(y(j)-one)<=tol) Then
            res(j,1:npde) = uy(j,1:npde)
          End If
        End Do

        Return
      End Subroutine bndry2
      Subroutine monit2(npde,t,dt,dtnew,tlast,nlev,ngpts,xpts,ypts,lsol,sol,   &
        ierr)

!       .. Scalar Arguments ..
        Real (Kind=nag_wp), Intent (In) :: dt, dtnew, t
        Integer, Intent (Inout)        :: ierr
        Integer, Intent (In)           :: nlev, npde
        Logical, Intent (In)           :: tlast
!       .. Array Arguments ..
        Real (Kind=nag_wp), Intent (In) :: sol(*), xpts(*), ypts(*)
        Integer, Intent (In)           :: lsol(nlev), ngpts(nlev)
!       .. Local Scalars ..
        Integer                        :: i, ipsol, k, level, npts
!       .. Intrinsic Procedures ..
        Intrinsic                      :: sum
!       .. Executable Statements ..
        If (tlast) Then

!         Print solution

          level = nlev
          Write (nout,99999) level, t
          Write (nout,99998)
          npts = ngpts(level)
          ipsol = lsol(level)
          k = sum(ngpts(1:nlev-1))

          Do i = 1, npts, 2
            Write (nout,99997) xpts(k+i), ypts(k+i), sol(ipsol+i),             &
              sol(ipsol+npts+i)
          End Do

          Write (nout,*)

        End If

        Return
99999   Format (1X,'Solution at every 2nd grid point in level',I10,            &
          ' at time ',F8.4,':')
99998   Format (1X,/,7X,'x',10X,'y',9X,'approx c1',3X,'approx c2',/)
99997   Format (1P,2(1X,E11.3),2X,E11.3,2X,E11.3)
      End Subroutine monit2
      Subroutine monit_dummy(npde,t,dt,dtnew,tlast,nlev,ngpts,xpts,ypts,lsol,  &
        sol,ierr)

!       .. Scalar Arguments ..
        Real (Kind=nag_wp), Intent (In) :: dt, dtnew, t
        Integer, Intent (Inout)        :: ierr
        Integer, Intent (In)           :: nlev, npde
        Logical, Intent (In)           :: tlast
!       .. Array Arguments ..
        Real (Kind=nag_wp), Intent (In) :: sol(*), xpts(*), ypts(*)
        Integer, Intent (In)           :: lsol(nlev), ngpts(nlev)
!       .. Executable Statements ..
        Return
      End Subroutine monit_dummy
      Subroutine compute_wkspace_lens(maxlev,npde,maxpts,lenrwk,leniwk,lenlwk)

!       Returns suitable workspace lengths for the two problems
!       being solved, based on trial-and-error.

!       .. Scalar Arguments ..
        Integer, Intent (Out)          :: leniwk, lenlwk, lenrwk
        Integer, Intent (In)           :: maxlev, maxpts, npde
!       .. Executable Statements ..
        lenrwk = 2*maxpts*npde*(5*maxlev+18*npde+9) + 2*maxpts
        leniwk = 2*maxpts*(14+5*maxlev) + 7*maxlev + 2
        lenlwk = 2*maxpts + 400
        Return
      End Subroutine compute_wkspace_lens
      Subroutine print_statistics(ts,iwk,maxlev)

!       .. Scalar Arguments ..
        Real (Kind=nag_wp), Intent (In) :: ts
        Integer, Intent (In)           :: maxlev
!       .. Array Arguments ..
        Integer, Intent (In)           :: iwk(6*maxlev+2)
!       .. Local Scalars ..
        Integer                        :: i, j
!       .. Local Arrays ..
        Integer                        :: istats(4)
!       .. Executable Statements ..
        Write (nout,'(1X,A)') 'Statistics:'
        Write (nout,99999) 'Time = ', ts
        Write (nout,99998) 'Total number of accepted timesteps =', iwk(1)
        Write (nout,99998) 'Total number of rejected timesteps =', iwk(2)
        Write (nout,'(1X,4(/,A))')                                             &
          '             Total  number (rounded) of     ',                      &
          '          Residual  Jacobian    Newton   Lin sys',                  &
          '             evals     evals     iters     iters', ' At level '

        Do j = 1, maxlev
          If (iwk(j+2)/=0) Then
            istats(1:4) = iwk(j+2:j+2+3*maxlev:maxlev)
            Call round_statistics(istats)
            Write (nout,99997) j, istats(1:4)
          End If
        End Do

        Write (nout,'(1X,3(/,A))') '             Maximum  number of   ',       &
          '              Newton iters    Lin sys iters ', ' At level '

        Do j = 1, maxlev
          If (iwk(j+2)/=0) Then
            Write (nout,99996) j, (iwk(j+2+i*maxlev),i=4,5)
          End If
        End Do
        Write (nout,*)

        Return
99999   Format (1X,A,F8.4)
99998   Format (1X,A,I5)
99997   Format (I8,4I10)
99996   Format (I8,2I14)
      End Subroutine print_statistics
      Subroutine round_statistics(istat)

!       .. Array Arguments ..
        Integer, Intent (Inout)        :: istat(4)
!       .. Local Scalars ..
        Real (Kind=nag_wp)             :: lt
        Integer                        :: i, k
!       .. Intrinsic Procedures ..
        Intrinsic                      :: int, log, real
!       .. Executable Statements ..
        lt = log(10.0_nag_wp)
        Do i = 1, 4
          k = int(log(real(istat(i),kind=nag_wp))/lt)
          k = 10**k
          istat(i) = k*((istat(i)+k/2)/k)
        End Do
      End Subroutine round_statistics
    End Module d03rafe_mod
    Program d03rafe

!     D03RAF Example Main Program

!     .. Use Statements ..
      Use d03rafe_mod, Only: nout
!     .. Implicit None Statement ..
      Implicit None
!     .. Executable Statements ..
      Write (nout,*) 'D03RAF Example Program Results'

      Call ex1

      Call ex2

    Contains
      Subroutine ex1

!       .. Use Statements ..
        Use nag_library, Only: d03raf, nag_wp
        Use d03rafe_mod, Only: bndry1, compute_wkspace_lens, itrace, monit1,   &
                               monit_dummy, nin, npde1, one, pdedef1, pdeiv1,  &
                               print_statistics, xmax, xmin, ymax, ymin, zero
!       .. Local Scalars ..
        Real (Kind=nag_wp)             :: tols, tolt, tout, ts
        Integer                        :: i, ifail, ind, leniwk, lenlwk,       &
                                          lenrwk, maxlev, npde, npts, nx, ny
!       .. Local Arrays ..
        Real (Kind=nag_wp)             :: dt(3), twant(2)
        Real (Kind=nag_wp), Allocatable :: optr(:,:), rwk(:)
        Integer, Allocatable           :: iwk(:)
        Integer                        :: opti(4)
        Logical, Allocatable           :: lwk(:)
!       .. Intrinsic Procedures ..
        Intrinsic                      :: max
!       .. Executable Statements ..
        Write (nout,*)
        Write (nout,*)
        Write (nout,*) 'Example 1'
        Write (nout,*)
!       Skip heading in data file
        Read (nin,*)
        Read (nin,*) npts

        npde = npde1

        dt(1:3) = (/0.1E-2_nag_wp,zero,zero/)
        twant(1:2) = (/0.24_nag_wp,0.25_nag_wp/)
        ts = zero

!       Specify that we are starting the integration in time (ind = 0
!       normally).
!       Note: we have parallelized the loop in the function pdedef1 using
!       OpenMP so set alternative value of ind to indicate that this can be
!       run in parallel if we are using a multithreaded implementation.
!       Either option is OK for serial NAG Library implementations from
!       Mark 25 onwards.
        ind = 10

        nx = 41
        ny = 41
        tols = 0.5_nag_wp
        tolt = 0.01_nag_wp
        opti(1) = 6
        opti(2:4) = 0
        maxlev = max(opti(1),3)

        Call compute_wkspace_lens(maxlev,npde,npts,lenrwk,leniwk,lenlwk)

        Allocate (rwk(lenrwk),iwk(leniwk),lwk(lenlwk),optr(3,npde))
        optr(1:3,1:npde) = one

        Do i = 1, 2
          tout = twant(i)

!         ifail: behaviour on error exit
!                =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
          ifail = 0
          If (i==1) Then
!           Use monit_dummy to avoid output first time around
            Call d03raf(npde,ts,tout,dt,xmin,xmax,ymin,ymax,nx,ny,tols,tolt,   &
              pdedef1,bndry1,pdeiv1,monit_dummy,opti,optr,rwk,lenrwk,iwk,      &
              leniwk,lwk,lenlwk,itrace,ind,ifail)
          Else
            Call d03raf(npde,ts,tout,dt,xmin,xmax,ymin,ymax,nx,ny,tols,tolt,   &
              pdedef1,bndry1,pdeiv1,monit1,opti,optr,rwk,lenrwk,iwk,leniwk,    &
              lwk,lenlwk,itrace,ind,ifail)
          End If

          Call print_statistics(ts,iwk,maxlev)

        End Do

        Return
      End Subroutine ex1
      Subroutine ex2

!       .. Use Statements ..
        Use nag_library, Only: d03raf, nag_wp
        Use d03rafe_mod, Only: bndry2, compute_wkspace_lens, itrace, monit2,   &
                               monit_dummy, nin, npde2, one, pdedef2, pdeiv2,  &
                               print_statistics, xmax, xmin, ymax, ymin, zero
!       .. Parameters ..
        Integer, Parameter             :: opti(4) = (/4,0,0,0/)
!       .. Local Scalars ..
        Real (Kind=nag_wp)             :: tols, tolt, tout, ts
        Integer                        :: i, ifail, ind, leniwk, lenlwk,       &
                                          lenrwk, maxlev, npde, npts, nx, ny
!       .. Local Arrays ..
        Real (Kind=nag_wp)             :: dt(3), twant(2)
        Real (Kind=nag_wp), Allocatable :: optr(:,:), rwk(:)
        Integer, Allocatable           :: iwk(:)
        Logical, Allocatable           :: lwk(:)
!       .. Intrinsic Procedures ..
        Intrinsic                      :: max
!       .. Executable Statements ..
        Write (nout,*)
        Write (nout,*)
        Write (nout,*) 'Example 2'
        Write (nout,*)
        Read (nin,*)
        Read (nin,*) npts

        npde = npde2
        dt(1:3) = (/0.5E-3_nag_wp,1.0E-6_nag_wp,zero/)
        twant(1:2) = (/0.01_nag_wp,0.025_nag_wp/)
        ts = zero

!       Specify that we are starting the integration in time (ind = 0
!       normally).
!       Note: In this second example we have not added OpenMP directives to
!       parallelize the loop in the function pdedef2. Thus the alternative
!       ind=10 must not be specified here, as this will not function correctly
!       if a multithreaded implementation of the NAG Library is used. Adding
!       OpenMP to pdedef2, that would enable ind=10 to be used here safely, is
!       left as an exercise for the reader.
        ind = 0

        nx = 11
        ny = 11
        tols = 0.1_nag_wp
        tolt = 0.1_nag_wp
        maxlev = max(opti(1),3)

        Call compute_wkspace_lens(maxlev,npde,npts,lenrwk,leniwk,lenlwk)

        Allocate (rwk(lenrwk),iwk(leniwk),lwk(lenlwk),optr(3,npde))
        optr(1,1:npde) = (/250.0_nag_wp,1.5E6_nag_wp/)
        optr(2:3,1:npde) = one

        Do i = 1, 2
          tout = twant(i)

          ifail = 0
          If (i==1) Then
!           Use monit_dummy to avoid output first time around
            Call d03raf(npde,ts,tout,dt,xmin,xmax,ymin,ymax,nx,ny,tols,tolt,   &
              pdedef2,bndry2,pdeiv2,monit_dummy,opti,optr,rwk,lenrwk,iwk,      &
              leniwk,lwk,lenlwk,itrace,ind,ifail)
          Else
            Call d03raf(npde,ts,tout,dt,xmin,xmax,ymin,ymax,nx,ny,tols,tolt,   &
              pdedef2,bndry2,pdeiv2,monit2,opti,optr,rwk,lenrwk,iwk,leniwk,    &
              lwk,lenlwk,itrace,ind,ifail)
          End If

          Call print_statistics(ts,iwk,maxlev)

        End Do

        Return
      End Subroutine ex2
    End Program d03rafe


d03rbfe.f90

!   D03RBF Example Program Text
!   Mark 26 Release. NAG Copyright 2016.

    Module d03rbfe_mod

!     D03RBF Example Program Module:
!            Parameters and User-defined Routines

!     .. Use Statements ..
      Use nag_library, Only: nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Accessibility Statements ..
      Private
      Public                           :: bndary, inidom, monitr, pdedef,      &
                                          pdeiv
!     .. Parameters ..
      Real (Kind=nag_wp), Parameter, Public :: one = 1.0_nag_wp
      Real (Kind=nag_wp), Parameter, Public :: zero = 0.0_nag_wp
      Real (Kind=nag_wp), Parameter, Public :: twant(2) = (/0.25_nag_wp,one/)
      Integer, Parameter, Public       :: itrace = 0, nin = 5, nout = 6,       &
                                          npde = 2
!     .. Local Scalars ..
      Integer, Public, Save            :: iout
    Contains
      Subroutine pdeiv(npts,npde,t,x,y,u)

!       .. Parameters ..
        Real (Kind=nag_wp), Parameter  :: eps = 0.001_nag_wp
!       .. Scalar Arguments ..
        Real (Kind=nag_wp), Intent (In) :: t
        Integer, Intent (In)           :: npde, npts
!       .. Array Arguments ..
        Real (Kind=nag_wp), Intent (Out) :: u(npts,npde)
        Real (Kind=nag_wp), Intent (In) :: x(npts), y(npts)
!       .. Local Scalars ..
        Real (Kind=nag_wp)             :: a
        Integer                        :: i
!       .. Intrinsic Procedures ..
        Intrinsic                      :: exp
!       .. Executable Statements ..
        Do i = 1, npts
          a = (4.0_nag_wp*(y(i)-x(i))-t)/(32.0_nag_wp*eps)
          If (a<=zero) Then
            u(i,1) = 0.75_nag_wp - 0.25_nag_wp/(one+exp(a))
            u(i,2) = 0.75_nag_wp + 0.25_nag_wp/(one+exp(a))
          Else
            a = -a
            u(i,1) = 0.75_nag_wp - 0.25_nag_wp*exp(a)/(one+exp(a))
            u(i,2) = 0.75_nag_wp + 0.25_nag_wp*exp(a)/(one+exp(a))
          End If
        End Do

        Return
      End Subroutine pdeiv
      Subroutine inidom(maxpts,xmin,xmax,ymin,ymax,nx,ny,npts,nrows,nbnds,     &
        nbpts,lrow,irow,icol,llbnd,ilbnd,lbnd,ierr)

!       .. Use Statements ..
        Use nag_library, Only: d03ryf
!       .. Scalar Arguments ..
        Real (Kind=nag_wp), Intent (Out) :: xmax, xmin, ymax, ymin
        Integer, Intent (Inout)        :: ierr
        Integer, Intent (In)           :: maxpts
        Integer, Intent (Out)          :: nbnds, nbpts, npts, nrows, nx, ny
!       .. Array Arguments ..
        Integer, Intent (Inout)        :: icol(*), ilbnd(*), irow(*), lbnd(*), &
                                          llbnd(*), lrow(*)
!       .. Local Scalars ..
        Integer                        :: i, ifail, j, leniwk
!       .. Local Arrays ..
        Integer                        :: icold(105), ilbndd(28), irowd(11),   &
                                          iwk(122), lbndd(72), llbndd(28),     &
                                          lrowd(11)
        Character (33)                 :: pgrid(11)
!       .. Executable Statements ..
        icold(1:105) = (/0,1,2,0,1,2,3,4,5,6,7,8,9,10,0,1,2,3,4,5,6,7,8,9,10,  &
          0,1,2,3,4,5,6,7,8,9,10,0,1,2,3,4,5,8,9,10,0,1,2,3,4,5,6,7,8,9,10,0,  &
          1,2,3,4,5,6,7,8,9,10,0,1,2,3,4,5,6,7,8,9,10,0,1,2,3,4,5,6,7,8,0,1,2, &
          3,4,5,6,7,8,0,1,2,3,4,5,6,7,8/)
        ilbndd(1:28) = (/1,2,3,4,1,4,1,2,3,4,3,4,1,2,12,23,34,41,14,41,12,23,  &
          34,41,43,14,21,32/)
        irowd(1:11) = (/0,1,2,3,4,5,6,7,8,9,10/)

        lbndd(1:72) = (/2,4,15,26,37,46,57,68,79,88,98,99,100,101,102,103,104, &
          96,86,85,84,83,82,70,59,48,39,28,17,6,8,9,10,11,12,13,18,29,40,49,   &
          60,72,73,74,75,76,77,67,56,45,36,25,33,32,42,52,53,43,1,97,105,87,   &
          81,3,7,71,78,14,31,51,54,34/)

        llbndd(1:28) = (/1,2,11,18,19,24,31,37,42,48,53,55,56,58,59,60,61,62,  &
          63,64,65,66,67,68,69,70,71,72/)
        lrowd(1:11) = (/1,4,15,26,37,46,57,68,79,88,97/)

        nx = 11
        ny = 11

!       Check MAXPTS against rough estimate of NPTS

        npts = nx*ny
        If (maxpts<npts) Then
          ierr = -1
          Return
        End If

        xmin = zero
        ymin = zero
        xmax = one
        ymax = one

        nrows = 11
        npts = 105
        nbnds = 28
        nbpts = 72

        Do i = 1, nrows
          lrow(i) = lrowd(i)
          irow(i) = irowd(i)
        End Do

        Do i = 1, nbnds
          llbnd(i) = llbndd(i)
          ilbnd(i) = ilbndd(i)
        End Do

        Do i = 1, nbpts
          lbnd(i) = lbndd(i)
        End Do

        Do i = 1, npts
          icol(i) = icold(i)
        End Do

        Write (nout,*) 'Base grid:'
        Write (nout,*)
        leniwk = 122
        ifail = -1

        Call d03ryf(nx,ny,npts,nrows,nbnds,nbpts,lrow,irow,icol,llbnd,ilbnd,   &
          lbnd,iwk,leniwk,pgrid,ifail)

        If (ifail==0) Then
          Write (nout,*) ' '
          Do j = 1, ny
            Write (nout,*) pgrid(j)
            Write (nout,*) ' '
          End Do
          Write (nout,*) ' '
        End If

        Return
      End Subroutine inidom
      Subroutine pdedef(npts,npde,t,x,y,u,ut,ux,uy,uxx,uxy,uyy,res)

!       .. Parameters ..
        Real (Kind=nag_wp), Parameter  :: eps = 1E-3_nag_wp
!       .. Scalar Arguments ..
        Real (Kind=nag_wp), Intent (In) :: t
        Integer, Intent (In)           :: npde, npts
!       .. Array Arguments ..
        Real (Kind=nag_wp), Intent (Out) :: res(npts,npde)
        Real (Kind=nag_wp), Intent (In) :: u(npts,npde), ut(npts,npde),        &
                                          ux(npts,npde), uxx(npts,npde),       &
                                          uxy(npts,npde), uy(npts,npde),       &
                                          uyy(npts,npde), x(npts), y(npts)
!       .. Local Scalars ..
        Integer                        :: i
!       .. Executable Statements ..
        !$Omp Do
        Do i = 1, npts
          res(i,1) = -u(i,1)*ux(i,1) - u(i,2)*uy(i,1) +                        &
            eps*(uxx(i,1)+uyy(i,1))
          res(i,2) = -u(i,1)*ux(i,2) - u(i,2)*uy(i,2) +                        &
            eps*(uxx(i,2)+uyy(i,2))
          res(i,1) = ut(i,1) - res(i,1)
          res(i,2) = ut(i,2) - res(i,2)
        End Do
        !$Omp End Do

        Return
      End Subroutine pdedef
      Subroutine bndary(npts,npde,t,x,y,u,ut,ux,uy,nbnds,nbpts,llbnd,ilbnd,    &
        lbnd,res)

!       .. Parameters ..
        Real (Kind=nag_wp), Parameter  :: eps = 1E-3_nag_wp
!       .. Scalar Arguments ..
        Real (Kind=nag_wp), Intent (In) :: t
        Integer, Intent (In)           :: nbnds, nbpts, npde, npts
!       .. Array Arguments ..
        Real (Kind=nag_wp), Intent (Inout) :: res(npts,npde)
        Real (Kind=nag_wp), Intent (In) :: u(npts,npde), ut(npts,npde),        &
                                          ux(npts,npde), uy(npts,npde),        &
                                          x(npts), y(npts)
        Integer, Intent (In)           :: ilbnd(nbnds), lbnd(nbpts),           &
                                          llbnd(nbnds)
!       .. Local Scalars ..
        Real (Kind=nag_wp)             :: a
        Integer                        :: i, k
!       .. Intrinsic Procedures ..
        Intrinsic                      :: exp
!       .. Executable Statements ..
        Do k = llbnd(1), nbpts
          i = lbnd(k)
          a = (-4.0_nag_wp*x(i)+4.0_nag_wp*y(i)-t)/(32.0_nag_wp*eps)
          If (a<=zero) Then
            res(i,1) = 0.75_nag_wp - 0.25_nag_wp/(one+exp(a))
            res(i,2) = 0.75_nag_wp + 0.25_nag_wp/(one+exp(a))
          Else
            a = -a
            res(i,1) = 0.75_nag_wp - 0.25_nag_wp*exp(a)/(one+exp(a))
            res(i,2) = 0.75_nag_wp + 0.25_nag_wp*exp(a)/(one+exp(a))
          End If
          res(i,1:2) = u(i,1:2) - res(i,1:2)
        End Do

        Return
      End Subroutine bndary
      Subroutine monitr(npde,t,dt,dtnew,tlast,nlev,xmin,ymin,dxb,dyb,lgrid,    &
        istruc,lsol,sol,ierr)

!       .. Use Statements ..
        Use nag_library, Only: d03rzf
!       .. Parameters ..
        Integer, Parameter             :: maxpts = 2500, nout = 6
!       .. Scalar Arguments ..
        Real (Kind=nag_wp), Intent (In) :: dt, dtnew, dxb, dyb, t, xmin, ymin
        Integer, Intent (Inout)        :: ierr
        Integer, Intent (In)           :: nlev, npde
        Logical, Intent (In)           :: tlast
!       .. Array Arguments ..
        Real (Kind=nag_wp), Intent (In) :: sol(*)
        Integer, Intent (In)           :: istruc(*), lgrid(*), lsol(nlev)
!       .. Local Scalars ..
        Integer                        :: i, ifail, ipsol, level, npts
!       .. Local Arrays ..
        Real (Kind=nag_wp)             :: uex(105,2), x(maxpts), y(maxpts)
!       .. Executable Statements ..
        ifail = -1
levels: Do level = 1, nlev
          If (.Not. tlast) Then
            Exit levels
          End If
          ipsol = lsol(level)

!         Get grid information

          Call d03rzf(level,nlev,xmin,ymin,dxb,dyb,lgrid,istruc,npts,x,y,      &
            maxpts,ifail)
          If (ifail/=0) Then
            ierr = 1
            Exit levels
          End If

!         Skip printing if iout<2 or level>1.
          If (iout/=2 .Or. level/=1) Then
            Cycle levels
          End If

!         Get exact solution
          Call pdeiv(npts,npde,t,x,y,uex)
          Write (nout,*)
          Write (nout,99999) t
          Write (nout,*)
          Write (nout,99998) 'x', 'y', 'approx u', 'exact u', 'approx v',      &
            'exact v'
          Write (nout,*)
          ipsol = lsol(level)
          Do i = 1, npts, 2
            Write (nout,99997) x(i), y(i), sol(ipsol+i), uex(i,1),             &
              sol(ipsol+npts+i), uex(i,2)
          End Do
          Write (nout,*)

        End Do levels

        Return
99999   Format (' Solution at every 2nd grid point in level 1 at time ',F8.4,  &
          ':')
99998   Format (7X,A,9X,A,6X,A,2X,A,2X,A,2X,A)
99997   Format (6(1X,F9.2))
      End Subroutine monitr
    End Module d03rbfe_mod
    Program d03rbfe

!     D03RBF Example Main Program

!     .. Use Statements ..
      Use nag_library, Only: d03rbf, nag_wp
      Use d03rbfe_mod, Only: bndary, inidom, iout, itrace, monitr, nin, nout,  &
                             npde, one, pdedef, pdeiv, twant, zero
!     .. Implicit None Statement ..
      Implicit None
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: tols, tolt, tout, ts
      Integer                          :: i, ifail, ind, j, leniwk, lenlwk,    &
                                          lenrwk, maxlev, mxlev, npts
!     .. Local Arrays ..
      Real (Kind=nag_wp)               :: dt(3)
      Real (Kind=nag_wp), Allocatable  :: optr(:,:), rwk(:)
      Integer, Allocatable             :: iwk(:)
      Integer                          :: opti(4)
      Logical, Allocatable             :: lwk(:)
!     .. Executable Statements ..
      Write (nout,*) 'D03RBF Example Program Results'
!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) npts, mxlev

      leniwk = npts*(5*mxlev+14) + 2 + 7*mxlev
      lenlwk = 2*npts
      lenrwk = npts*npde*(5*mxlev+9+18*npde) + 2*npts
      Allocate (rwk(lenrwk),iwk(leniwk),lwk(lenlwk),optr(3,npde))

!     Specify that we are starting the integration in time (ind = 0 normally).
!     Note: we have parallelized the loop in the function pdedef using OpenMP
!     so set the alternative value of ind to indicate that this can be run in
!     parallel if we are using a multithreaded implementation. Either option
!     is OK for serial NAG Library implementations from Mark 25 onwards.
      ind = 10

      ts = zero
      dt(1) = 0.001_nag_wp
      dt(2) = 1.0E-7_nag_wp
      dt(3) = zero
      tols = 0.1_nag_wp
      tolt = 0.05_nag_wp
      opti(1) = 5
      maxlev = opti(1)
      opti(2:4) = 0
      optr(1:3,1:npde) = one

!     Call main routine
      Do iout = 1, 2
        tout = twant(iout)

!       ifail: behaviour on error exit
!              =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
        ifail = 0
        Call d03rbf(npde,ts,tout,dt,tols,tolt,inidom,pdedef,bndary,pdeiv,      &
          monitr,opti,optr,rwk,lenrwk,iwk,leniwk,lwk,lenlwk,itrace,ind,ifail)

!       Print statistics

        Write (nout,99999) 'Statistics:'
        Write (nout,99998) 'Time = ', ts
        Write (nout,99997) 'Total number of accepted timesteps =', iwk(1)
        Write (nout,99997) 'Total number of rejected timesteps =', iwk(2)
        Write (nout,'(1X,4(/,A,A))') '            Total  number  of     ',     &
          '  maximum  number  of     ',                                        &
          '       Residual Jacobian    Newton   ', '      Newton   ',          &
          '        evals     evals     iters   ', '       iters   ', ' Level '

        maxlev = opti(1)
        Do j = 1, maxlev
          If (iwk(j+2)/=0) Then
            Write (nout,'(I4,4I10)') j, (iwk(j+2+i*maxlev),i=0,2),             &
              iwk(j+2+4*maxlev)
          End If
        End Do
        Write (nout,*)

      End Do

99999 Format (1X,A)
99998 Format (1X,A,F8.4)
99997 Format (1X,A,I5)
    End Program d03rbfe


d03uafe.f90

    Program d03uafe

!     D03UAF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: d03uaf, nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Real (Kind=nag_wp), Parameter    :: one = 1.0_nag_wp
      Real (Kind=nag_wp), Parameter    :: two = 2.0_nag_wp
      Real (Kind=nag_wp), Parameter    :: zero = 0.0_nag_wp
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: adel, aparam, ares, delmax, delmn,   &
                                          resmax, resmn
      Integer                          :: i, ifail, it, j, lda, n1, n2, nits
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: a(:,:), b(:,:), c(:,:), d(:,:),      &
                                          e(:,:), q(:,:), r(:,:), t(:,:),      &
                                          wrksp1(:,:), wrksp2(:,:), x(:), y(:)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: abs, cos, exp, max, real
!     .. Executable Statements ..
      Write (nout,*) 'D03UAF Example Program Results'
      Write (nout,*)
!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) n1, n2, nits
      lda = n1
      Allocate (a(lda,n2),b(lda,n2),c(lda,n2),d(lda,n2),e(lda,n2),q(lda,n2),   &
        r(lda,n2),t(lda,n2),wrksp1(lda,n2),wrksp2(lda,n2),x(n1),y(n2))
      Read (nin,*) x(1:n1)
      Read (nin,*) y(1:n2)
      aparam = one

!     Set up difference equation coefficients, source terms and
!     initial S
      a(1:n1,1:n2) = zero
      b(1:n1,1:n2) = zero
      d(1:n1,1:n2) = zero
      e(1:n1,1:n2) = zero
      q(1:n1,1:n2) = zero
      t(1:n1,1:n2) = zero
!     Specification for internal nodes
      Do j = 2, n2 - 1
        a(2:n1-1,j) = two/((y(j)-y(j-1))*(y(j+1)-y(j-1)))
        e(2:n1-1,j) = two/((y(j+1)-y(j))*(y(j+1)-y(j-1)))
      End Do
      Do i = 2, n1 - 1
        b(i,2:n2-1) = two/((x(i)-x(i-1))*(x(i+1)-x(i-1)))
        d(i,2:n2-1) = two/((x(i+1)-x(i))*(x(i+1)-x(i-1)))
      End Do
      c(1:n1,1:n2) = -a(1:n1,1:n2) - b(1:n1,1:n2) - d(1:n1,1:n2) -             &
        e(1:n1,1:n2)
!     Specification for boundary nodes
      Do j = 1, n2
        q(1,j) = exp((x(1)+one)/y(n2))*cos(y(j)/y(n2))
        q(n1,j) = exp((x(n1)+one)/y(n2))*cos(y(j)/y(n2))
      End Do
      Do i = 1, n1
        q(i,1) = exp((x(i)+one)/y(n2))*cos(y(1)/y(n2))
        q(i,n2) = exp((x(i)+one)/y(n2))*cos(y(n2)/y(n2))
      End Do

!     Iterative loop
      Do it = 1, nits
!       Calculate the residuals
        resmax = zero
        resmn = zero
        Do j = 1, n2
          Do i = 1, n1
            If (c(i,j)/=zero) Then
!             Five point molecule formula
              r(i,j) = q(i,j) - a(i,j)*t(i,j-1) - b(i,j)*t(i-1,j) -            &
                c(i,j)*t(i,j) - d(i,j)*t(i+1,j) - e(i,j)*t(i,j+1)
            Else
!             Explicit equation
              r(i,j) = q(i,j) - t(i,j)
            End If
            ares = abs(r(i,j))
            resmax = max(resmax,ares)
            resmn = resmn + ares
          End Do
        End Do
        resmn = resmn/(real(n1*n2,kind=nag_wp))

!       ifail: behaviour on error exit
!              =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
        ifail = 0
        Call d03uaf(n1,n2,lda,a,b,c,d,e,aparam,it,r,wrksp1,wrksp2,ifail)

        If (it==1) Then
          Write (nout,99997) 'Iteration', 'Residual', 'Change'
          Write (nout,99996) 'No', 'Max.', 'Mean', 'Max.', 'Mean'
        End If

!       Update the dependent variable
        delmax = zero
        delmn = zero
        Do j = 1, n2
          Do i = 1, n1
            t(i,j) = t(i,j) + r(i,j)
            adel = abs(r(i,j))
            delmax = max(delmax,adel)
            delmn = delmn + adel
          End Do
        End Do
        delmn = delmn/(real(n1*n2,kind=nag_wp))
        Write (nout,99999) it, resmax, resmn, delmax, delmn
!       Convergence tests here if required
      End Do
!     End of iterative loop
      Write (nout,*)
      Write (nout,*) 'Table of calculated function values'
      Write (nout,*)
      Write (nout,99995) 'I', 1, (i,i=2,6)
      Write (nout,*) ' J'
      Do j = 1, n2
        Write (nout,99998) j, (t(i,j),i=1,n1)
      End Do

99999 Format (1X,I3,4(2X,E11.4))
99998 Format (1X,I2,1X,6(F9.3,2X))
99997 Format (1X,A,6X,A,19X,A)
99996 Format (3X,A,7X,A,8X,A,11X,A,6X,A,/)
99995 Format (4X,A,4X,I1,5I11)
    End Program d03uafe


d03ubfe.f90

    Program d03ubfe

!     D03UBF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: d03ubf, nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Real (Kind=nag_wp), Parameter    :: one = 1.0_nag_wp
      Real (Kind=nag_wp), Parameter    :: two = 2.0_nag_wp
      Real (Kind=nag_wp), Parameter    :: zero = 0.0_nag_wp
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: adel, aparam, ares, delmax, delmn,   &
                                          resmax, resmn, root2, x1, x2, y1,    &
                                          y2, yy, z1, z2
      Integer                          :: i, ifail, it, j, k, lda, n1, n2, n3, &
                                          nits, sda
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: a(:,:,:), b(:,:,:), c(:,:,:),        &
                                          d(:,:,:), e(:,:,:), f(:,:,:),        &
                                          g(:,:,:), q(:,:,:), r(:,:,:),        &
                                          t(:,:,:), wrksp1(:,:,:),             &
                                          wrksp2(:,:,:), wrksp3(:,:,:), x(:),  &
                                          y(:), z(:)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: abs, cos, exp, max, real, sqrt
!     .. Executable Statements ..
      Write (nout,*) 'D03UBF Example Program Results'
      Write (nout,*)
!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) n1, n2, n3, nits
      lda = n1
      sda = n2
      Allocate (a(lda,sda,n3),b(lda,sda,n3),c(lda,sda,n3),d(lda,sda,n3),       &
        e(lda,sda,n3),f(lda,sda,n3),g(lda,sda,n3),q(lda,sda,n3),r(lda,sda,n3), &
        t(lda,sda,n3),wrksp1(lda,sda,n3),wrksp2(lda,sda,n3),                   &
        wrksp3(lda,sda,n3),x(n1),y(n2),z(n3))

      Read (nin,*) x(1:n1)
      Read (nin,*) y(1:n2)
      Read (nin,*) z(1:n3)
      root2 = sqrt(two)
      aparam = one
!     Set up difference equation coefficients, source terms and
!     initial approximation
      a(1:n1,1:n2,1:n3) = zero
      b(1:n1,1:n2,1:n3) = zero
      c(1:n1,1:n2,1:n3) = zero
      e(1:n1,1:n2,1:n3) = zero
      f(1:n1,1:n2,1:n3) = zero
      g(1:n1,1:n2,1:n3) = zero
      q(1:n1,1:n2,1:n3) = zero
      t(1:n1,1:n2,1:n3) = zero
!     Specification for internal nodes
      Do k = 2, n3 - 1
        a(2:n1-1,2:n2-1,k) = two/((z(k)-z(k-1))*(z(k+1)-z(k-1)))
        g(2:n1-1,2:n2-1,k) = two/((z(k+1)-z(k))*(z(k+1)-z(k-1)))
      End Do
      Do j = 2, n2 - 1
        b(2:n1-1,j,2:n3-1) = two/((y(j)-y(j-1))*(y(j+1)-y(j-1)))
        f(2:n1-1,j,2:n3-1) = two/((y(j+1)-y(j))*(y(j+1)-y(j-1)))
      End Do
      Do i = 2, n1 - 1
        c(i,2:n2-1,2:n3-1) = two/((x(i)-x(i-1))*(x(i+1)-x(i-1)))
        e(i,2:n2-1,2:n3-1) = two/((x(i+1)-x(i))*(x(i+1)-x(i-1)))
      End Do
      d(1:n1,1:n2,1:n3) = -a(1:n1,1:n2,1:n3) - b(1:n1,1:n2,1:n3) -             &
        c(1:n1,1:n2,1:n3) - e(1:n1,1:n2,1:n3) - f(1:n1,1:n2,1:n3) -            &
        g(1:n1,1:n2,1:n3)
!     Specification for boundary nodes
      yy = one/y(n2)
      x1 = (x(1)+one)*yy
      x2 = (x(n1)+one)*yy
      Do j = 1, n2
        y1 = root2*y(j)*yy
        q(1,j,1:n3) = exp(x1)*cos(y1)*exp((-z(1:n3)-one)*yy)
        q(n1,j,1:n3) = exp(x2)*cos(y1)*exp((-z(1:n3)-one)*yy)
      End Do
      y1 = root2*y(1)*yy
      y2 = root2*y(n2)*yy
      Do i = 1, n1
        x1 = (x(i)+one)*yy
        q(i,1,1:n3) = exp(x1)*cos(y1)*exp((-z(1:n3)-one)*yy)
        q(i,n2,1:n3) = exp(x1)*cos(y2)*exp((-z(1:n3)-one)*yy)
      End Do
      z1 = (-z(1)-one)*yy
      z2 = (-z(n3)-one)*yy
      Do i = 1, n1
        x1 = (x(i)+one)*yy
        q(i,1:n2,1) = exp(x1)*cos(root2*y(1:n2)*yy)*exp(z1)
        q(i,1:n2,n3) = exp(x1)*cos(root2*y(1:n2)*yy)*exp(z2)
      End Do
!     Iterative loop
      Do it = 1, nits
        resmax = zero
        resmn = zero
        Do k = 1, n3
          Do j = 1, n2
            Do i = 1, n1
              If (d(i,j,k)/=zero) Then
!               Seven point molecule formula
                r(i,j,k) = q(i,j,k) - a(i,j,k)*t(i,j,k-1) -                    &
                  b(i,j,k)*t(i,j-1,k) - c(i,j,k)*t(i-1,j,k) -                  &
                  d(i,j,k)*t(i,j,k) - e(i,j,k)*t(i+1,j,k) -                    &
                  f(i,j,k)*t(i,j+1,k) - g(i,j,k)*t(i,j,k+1)
              Else
!               Explicit equation
                r(i,j,k) = q(i,j,k) - t(i,j,k)
              End If
              ares = abs(r(i,j,k))
              resmax = max(resmax,ares)
              resmn = resmn + ares
            End Do
          End Do
        End Do
        resmn = resmn/(real(n1*n2*n3,kind=nag_wp))

!       ifail: behaviour on error exit
!              =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
        ifail = 0
        Call d03ubf(n1,n2,n3,lda,sda,a,b,c,d,e,f,g,aparam,it,r,wrksp1,wrksp2,  &
          wrksp3,ifail)

        If (it==1) Then
          Write (nout,99997) 'Iteration', 'Residual', 'Change'
          Write (nout,99996) 'No', 'Max.', 'Mean', 'Max.', 'Mean'
        End If

!       Update the dependent variable
        delmax = zero
        delmn = zero
        Do k = 1, n3
          Do j = 1, n2
            Do i = 1, n1
              t(i,j,k) = t(i,j,k) + r(i,j,k)
              adel = abs(r(i,j,k))
              delmax = max(delmax,adel)
              delmn = delmn + adel
            End Do
          End Do
        End Do
        delmn = delmn/(real(n1*n2*n3,kind=nag_wp))
        Write (nout,99999) it, resmax, resmn, delmax, delmn
!       Convergence tests here if required
      End Do
!     End of iterative loop
      Write (nout,*)
      Write (nout,*) 'Table of calculated function values'
      Write (nout,99995)
      Write (nout,*)
      Write (nout,99998)((k,j,(i,t(i,j,k),i=1,n1),j=1,n2),k=1,n3)

99999 Format (1X,I5,4(2X,E11.4))
99998 Format ((1X,I1,I3,1X,4(1X,I3,2X,F8.3)))
99997 Format (1X,A,6X,A,19X,A)
99996 Format (2X,A,7X,A,8X,A,11X,A,6X,A,/)
99995 Format (1X,'K  J',2X,4(1X,'(I      T   )'))
    End Program d03ubfe


d04aafe.f90

!   D04AAF Example Program Text
!   Mark 26 Release. NAG Copyright 2016.

    Module d04aafe_mod

!     D04AAF Example Program Module:
!            Parameters and User-defined Routines

!     nder:     abs(nder) is largest order derivative required;
!               nder < 0 means only odd or even derivatives.
!     h_init:   initial step size.
!     h_reduce: reduction factor applied to successive step sizes.
!     xval:     derivatives evaluated at x=xval.

!     .. Use Statements ..
      Use nag_library, Only: nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Accessibility Statements ..
      Private
      Public                           :: fun
!     .. Parameters ..
      Real (Kind=nag_wp), Parameter, Public :: h_init = 0.5_nag_wp
      Real (Kind=nag_wp), Parameter, Public :: h_reduce = 0.1_nag_wp
      Real (Kind=nag_wp), Parameter, Public :: xval = 0.5_nag_wp
      Integer, Parameter, Public       :: nder = -7, nout = 6
    Contains
      Function fun(x)

!       .. Function Return Value ..
        Real (Kind=nag_wp)             :: fun
!       .. Scalar Arguments ..
        Real (Kind=nag_wp), Intent (In) :: x
!       .. Intrinsic Procedures ..
        Intrinsic                      :: exp
!       .. Executable Statements ..
        fun = 0.5_nag_wp*exp(2.0_nag_wp*x-1.0_nag_wp)
        Return
      End Function fun
    End Module d04aafe_mod
    Program d04aafe

!     D04AAF Example Main Program

!     .. Use Statements ..
      Use nag_library, Only: d04aaf, nag_wp
      Use d04aafe_mod, Only: fun, h_init, h_reduce, nder, nout, xval
!     .. Implicit None Statement ..
      Implicit None
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: hbase
      Integer                          :: i, ifail, j, k, l
!     .. Local Arrays ..
      Real (Kind=nag_wp)               :: der(14), erest(14)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: abs, merge
!     .. Executable Statements ..
      Write (nout,*) 'D04AAF Example Program Results'

      Write (nout,*)
      Write (nout,*)                                                           &
        'Four separate runs to calculate the first four odd order ',           &
        'derivatives of'
      Write (nout,*) '   FUN(X) = 0.5*exp(2.0*X-1.0) at X = 0.5.'
      Write (nout,*) 'The exact results are 1, 4, 16 and 64'
      Write (nout,*)
      Write (nout,*) 'Input parameters common to all four runs'
      Write (nout,99999) '  XVAL = ', xval, '    NDER = ', nder,               &
        '    IFAIL = 0'
      Write (nout,*)

      hbase = h_init
      l = abs(nder)

      If (nder>=0) Then
        j = 1
      Else
        j = 2
      End If

      Do k = 1, 4

        ifail = 0
        Call d04aaf(xval,nder,hbase,der,erest,fun,ifail)

        Write (nout,*)
        Write (nout,99998) 'with step length', hbase, '  the results are'
        Write (nout,*) 'Order        Derivative       Questionable?'

        Do i = 1, l, j
          Write (nout,99997) i, der(i), merge('Yes','No ',erest(i)<0._nag_wp)
        End Do

        hbase = hbase*h_reduce
      End Do

99999 Format (1X,A,F4.1,A,I2,A)
99998 Format (1X,A,F9.4,A)
99997 Format (1X,I2,E21.4,13X,A)
    End Program d04aafe


d04bafe.f90

    Program d04bafe

!     D04BAF Example Program Text
!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: d04baf, d04bbf, nag_wp, s14aef, x04cbf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Real (Kind=nag_wp), Parameter    :: x_0 = 0.05_nag_wp
      Integer, Parameter               :: indent = 0, ncols = 80, nout = 6,    &
                                          n_der_comp = 3, n_display = 3,       &
                                          n_hbase = 4, zeroth = 0
      Character (1), Parameter         :: chlabel = 'C', diag = 'N',           &
                                          form = ' ', matrix = 'G',            &
                                          nolabel = 'N'
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: hbase
      Integer                          :: ifail, j, k
      Character (50)                   :: title
!     .. Local Arrays ..
      Real (Kind=nag_wp)               :: actder(n_display), der(14),          &
                                          der_comp(n_hbase,n_der_comp,14),     &
                                          erest(14), fval(21), xval(21)
      Character (10)                   :: clabs(n_der_comp), rlabs(1)
!     .. Executable Statements ..
      Write (nout,*) 'D04BAF Example Program Results'
      Write (nout,*)
      Write (nout,*) ' Find the derivatives of the polygamma (psi) function'
      Write (nout,*) ' using function values generated by S14AEF.'
      Write (nout,*)
      Write (nout,*) ' Demonstrate the effect of successively reducing HBASE.'
      Write (nout,*)
!     Select an initial separation distance HBASE.
      hbase = 0.0025_nag_wp

!     Compute the actual derivatives at target location x_0 using s14aef for
!     comparison.
      Do j = 1, n_display
        ifail = 0
        actder(j) = s14aef(x_0,j,ifail)
      End Do

!     Attempt N_HBASE approximations, reducing HBASE by factor 0.1 each time.
      Do j = 1, n_hbase

!       Generate the abscissa XVAL using D04BBF
        Call d04bbf(x_0,hbase,xval)

!       Calculate the corresponding objective function values.
        Do k = 1, 21
          ifail = 0
          fval(k) = s14aef(xval(k),zeroth,ifail)
        End Do

!       Call D04BAF to calculate the derivative estimates
        ifail = 0
        Call d04baf(xval,fval,der,erest,ifail)

!       Store results in DER_COMP
        der_comp(j,1,1:14) = hbase
        der_comp(j,2,1:14) = der(1:14)
        der_comp(j,3,1:14) = erest(1:14)

!       Decrease hbase for next loop
        hbase = hbase*0.1_nag_wp
      End Do

!     Display Results for first N_DISPLAY derivatives

      Do j = 1, n_display
        Write (nout,99996) j, actder(j)
        Write (clabs(1),99997) 'hbase     '
        Write (clabs(2),99998) 'DER', j, '   '
        Write (clabs(3),99999) 'EREST', j
        Write (title,99999) ' Derivative and error estimates for derivative ', &
          j
        Flush (nout)

!       Use X04CBF to display the matrix
        ifail = 0
        Call x04cbf(matrix,diag,n_hbase,n_der_comp,der_comp(1,1,j),n_hbase,    &
          form,title,nolabel,rlabs,chlabel,clabs,ncols,indent,ifail)
        Write (nout,*)
      End Do

99999 Format (A,'(',I1,')')
99998 Format (A,'(',I1,')',A)
99997 Format (A)
99996 Format (1X,' Derivative (',I1,') calculated using S14AEF :',1X,Es11.4)
    End Program d04bafe


d05aafe.f90

!   D05AAF Example Program Text
!   Mark 26 Release. NAG Copyright 2016.

    Module d05aafe_mod

!     D05AAF Example Program Module:
!            Parameters and User-defined Routines

!     .. Use Statements ..
      Use nag_library, Only: nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Accessibility Statements ..
      Private
      Public                           :: g, k1, k2
!     .. Parameters ..
      Real (Kind=nag_wp), Parameter, Public :: a = 0.0_nag_wp
      Real (Kind=nag_wp), Parameter, Public :: b = 1.0_nag_wp
      Real (Kind=nag_wp), Parameter, Public :: lambda = 1.0_nag_wp
      Real (Kind=nag_wp), Parameter, Public :: xval = 0.1_nag_wp
      Integer, Parameter, Public       :: ind = 2, n = 5, nout = 6
      Integer, Parameter, Public       :: ldw1 = n
      Integer, Parameter, Public       :: ldw2 = 2*n + 2
    Contains
      Function k1(x,s)

!       .. Function Return Value ..
        Real (Kind=nag_wp)             :: k1
!       .. Scalar Arguments ..
        Real (Kind=nag_wp), Intent (In) :: s, x
!       .. Executable Statements ..
        k1 = s*(1.0_nag_wp-x)

        Return
      End Function k1
      Function k2(x,s)

!       .. Function Return Value ..
        Real (Kind=nag_wp)             :: k2
!       .. Scalar Arguments ..
        Real (Kind=nag_wp), Intent (In) :: s, x
!       .. Executable Statements ..
        k2 = x*(1.0_nag_wp-s)

        Return
      End Function k2
      Function g(x)

!       .. Use Statements ..
        Use nag_library, Only: x01aaf
!       .. Function Return Value ..
        Real (Kind=nag_wp)             :: g
!       .. Scalar Arguments ..
        Real (Kind=nag_wp), Intent (In) :: x
!       .. Local Scalars ..
        Real (Kind=nag_wp)             :: pi
!       .. Intrinsic Procedures ..
        Intrinsic                      :: sin
!       .. Executable Statements ..
        pi = x01aaf(pi)
        g = sin(pi*x)*(1.0_nag_wp-1.0_nag_wp/(pi*pi))

        Return
      End Function g
    End Module d05aafe_mod
    Program d05aafe

!     D05AAF Example Main Program

!     .. Use Statements ..
      Use nag_library, Only: c06dcf, d05aaf, nag_wp
      Use d05aafe_mod, Only: a, b, g, ind, k1, k2, lambda, ldw1, ldw2, n,      &
                             nout, xval
!     .. Implicit None Statement ..
      Implicit None
!     .. Local Scalars ..
      Integer                          :: ifail, is
!     .. Local Arrays ..
      Real (Kind=nag_wp)               :: ans(1), x(1)
      Real (Kind=nag_wp), Allocatable  :: c(:), f(:), w1(:,:), w2(:,:), wd(:)
!     .. Executable Statements ..
      Write (nout,*) 'D05AAF Example Program Results'

      Allocate (c(n),f(n),w1(ldw1,ldw2),w2(ldw2,4),wd(ldw2))

      ifail = 0
      Call d05aaf(lambda,a,b,k1,k2,g,f,c,n,ind,w1,w2,wd,ldw1,ldw2,ifail)

      Write (nout,99999)
      Write (nout,99998) c(1:n)

      x(1) = xval

      Select Case (ind)
      Case (1)
        is = 3
      Case (2)
        is = 2
      Case Default
        is = 1
      End Select

      ifail = 0
      Call c06dcf(x,1,a,b,c,n,is,ans,ifail)

      Write (nout,99997) 'X=', x, '    ANS=', ans

99999 Format (/,1X,'Kernel is centro-symmetric and G is even so the ',         &
        'solution is even',/,/,1X,'Chebyshev coefficients',/)
99998 Format (1X,5E14.4,/)
99997 Format (1X,A,F5.2,A,1F10.4)
    End Program d05aafe


d05abfe.f90

!   D05ABF Example Program Text
!   Mark 26 Release. NAG Copyright 2016.

    Module d05abfe_mod

!     D05ABF Example Program Module:
!            Parameters and User-defined Routines

!     .. Use Statements ..
      Use nag_library, Only: nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Accessibility Statements ..
      Private
      Public                           :: g, k
!     .. Parameters ..
      Integer, Parameter, Public       :: nmax = 10, nout = 6
    Contains
      Function k(x,s)

!       .. Function Return Value ..
        Real (Kind=nag_wp)             :: k
!       .. Parameters ..
        Real (Kind=nag_wp), Parameter  :: alpha = 1.0_nag_wp
        Real (Kind=nag_wp), Parameter  :: w = alpha**2
!       .. Scalar Arguments ..
        Real (Kind=nag_wp), Intent (In) :: s, x
!       .. Executable Statements ..
        k = alpha/(w+(x-s)*(x-s))

        Return
      End Function k
      Function g(x)

!       .. Function Return Value ..
        Real (Kind=nag_wp)             :: g
!       .. Scalar Arguments ..
        Real (Kind=nag_wp), Intent (In) :: x
!       .. Executable Statements ..
        g = 1.0_nag_wp

        Return
      End Function g
    End Module d05abfe_mod
    Program d05abfe

!     D05ABF Example Main Program

!     .. Use Statements ..
      Use nag_library, Only: c06dcf, d05abf, nag_wp, x01aaf
      Use d05abfe_mod, Only: g, k, nmax, nout
!     .. Implicit None Statement ..
      Implicit None
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: a, b, lambda, x0
      Integer                          :: i, ifail, ldcm, lx, n, nt2p1, ss
      Logical                          :: ev, odorev
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: c(:), chebr(:), cm(:,:), f(:),       &
                                          f1(:,:), wk(:,:), x(:)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: cos, int, real
!     .. Executable Statements ..
      Write (nout,*) 'D05ABF Example Program Results'

      odorev = .True.
      ev = .True.
      lambda = -0.3183_nag_wp
      a = -1.0_nag_wp
      b = 1.0_nag_wp

      If (odorev) Then
        Write (nout,*)
        If (ev) Then
          Write (nout,*) 'Solution is even'
          ss = 2
        Else
          Write (nout,*) 'Solution is odd'
          ss = 3
        End If
        x0 = 0.5_nag_wp*(a+b)
      Else
        ss = 1
        x0 = a
      End If

!     Set up uniform grid to evaluate Chebyshev polynomials.
      lx = int(4.000001_nag_wp*(b-x0)) + 1
      Allocate (x(lx),chebr(lx))
      x(1) = x0
      Do i = 2, lx
        x(i) = x(i-1) + 0.25_nag_wp
      End Do

      Do n = 5, nmax, 5
        ldcm = n
        nt2p1 = 2*n + 1
        Allocate (c(n),cm(ldcm,ldcm),f(n),f1(ldcm,1),wk(2,nt2p1))

        ifail = -1
        Call d05abf(k,g,lambda,a,b,odorev,ev,n,cm,f1,wk,ldcm,nt2p1,f,c,ifail)

        If (ifail==0) Then
          Write (nout,*)
          Write (nout,99999) 'Results for N =', n
          Write (nout,*)
          Write (nout,99996) 'Solution on first ', n,                          &
            ' Chebyshev points and Chebyshev coefficients'
          Write (nout,*) '  I           X             F(I)         C(I)'
          Write (nout,99998)(i,cos(x01aaf(a)*real(i,kind=nag_wp)/real(2*n-1,   &
            kind=nag_wp)),f(i),c(i),i=1,n)

!         Evaluate and print solution on uniform grid.
          ifail = 0
          Call c06dcf(x,lx,a,b,c,n,ss,chebr,ifail)

          Write (nout,*)
          Write (nout,*) 'Solution on evenly spaced grid'
          Write (nout,*) '     X           F(X)'
          Write (nout,99997)(x(i),chebr(i),i=1,lx)

        End If

        Deallocate (c,cm,f,f1,wk)
      End Do
      Deallocate (x,chebr)

99999 Format (1X,A,I3)
99998 Format (1X,I3,2F15.5,E15.5)
99997 Format (1X,F8.4,F15.5)
99996 Format (1X,A,I2,A)
    End Program d05abfe


d05bafe.f90

!   D05BAF Example Program Text
!   Mark 26 Release. NAG Copyright 2016.
    Module d05bafe_mod

!     D05BAF Example Program Module:
!            Parameters and User-defined Routines

!     .. Use Statements ..
      Use nag_library, Only: nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Accessibility Statements ..
      Private
      Public                           :: cf, cg, ck, sol
!     .. Parameters ..
      Integer, Parameter, Public       :: nmesh = 6, nout = 6
    Contains
      Function sol(t)

!       .. Function Return Value ..
        Real (Kind=nag_wp)             :: sol
!       .. Scalar Arguments ..
        Real (Kind=nag_wp), Intent (In) :: t
!       .. Intrinsic Procedures ..
        Intrinsic                      :: exp, log
!       .. Executable Statements ..
        sol = log(t+exp(1.0_nag_wp))

        Return

      End Function sol
      Function cf(t)

!       .. Function Return Value ..
        Real (Kind=nag_wp)             :: cf
!       .. Scalar Arguments ..
        Real (Kind=nag_wp), Intent (In) :: t
!       .. Intrinsic Procedures ..
        Intrinsic                      :: exp
!       .. Executable Statements ..
        cf = exp(-t)

        Return

      End Function cf
      Function ck(t)

!       .. Function Return Value ..
        Real (Kind=nag_wp)             :: ck
!       .. Scalar Arguments ..
        Real (Kind=nag_wp), Intent (In) :: t
!       .. Intrinsic Procedures ..
        Intrinsic                      :: exp
!       .. Executable Statements ..
        ck = exp(-t)

        Return

      End Function ck
      Function cg(s,y)

!       .. Function Return Value ..
        Real (Kind=nag_wp)             :: cg
!       .. Scalar Arguments ..
        Real (Kind=nag_wp), Intent (In) :: s, y
!       .. Intrinsic Procedures ..
        Intrinsic                      :: exp
!       .. Executable Statements ..
        cg = y + exp(-y)

        Return

      End Function cg
    End Module d05bafe_mod
    Program d05bafe

!     D05BAF Example Main Program

!     .. Use Statements ..
      Use nag_library, Only: d05baf, nag_wp, x02ajf
      Use d05bafe_mod, Only: cf, cg, ck, nmesh, nout, sol
!     .. Implicit None Statement ..
      Implicit None
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: alim, h, hi, si, thresh, tlim, tol
      Integer                          :: i, ifail, iorder, lwk
      Character (1)                    :: method
!     .. Local Arrays ..
      Real (Kind=nag_wp)               :: errest(nmesh), yn(nmesh)
      Real (Kind=nag_wp), Allocatable  :: work(:)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: abs, int, real
!     .. Executable Statements ..
      Write (nout,*) 'D05BAF Example Program Results'

      method = 'A'
      iorder = 6
      alim = 0.0_nag_wp
      tlim = 20.0_nag_wp
      h = (tlim-alim)/real(nmesh,kind=nag_wp)
      tol = 1.E-3_nag_wp
      thresh = x02ajf()
      lwk = 10*nmesh + 6
      Allocate (work(lwk))

!     Loop until the supplied workspace is big enough

loop: Do

        ifail = 1
        Call d05baf(ck,cg,cf,method,iorder,alim,tlim,yn,errest,nmesh,tol,      &
          thresh,work,lwk,ifail)

        Select Case (ifail)
        Case (5,6)
          lwk = int(work(1))
          Deallocate (work)
          Allocate (work(lwk))
        Case Default
          Exit loop
        End Select

      End Do loop

      If (ifail/=0) Then
        Write (nout,99996) 'D05BAF exited with IFAIL =', ifail
        Go To 100
      End If

      Write (nout,*)
      Write (nout,99999) 'Size of workspace =', lwk
      Write (nout,99998) 'Tolerance         =', tol
      Write (nout,*)
      Write (nout,*)                                                           &
        '   T        Approx. Sol.  True Sol.    Est. Error    Actual Error'
      Do i = 1, nmesh
        hi = real(i,kind=nag_wp)*h
        si = sol(hi)
        Write (nout,99997) alim + hi, yn(i), si, errest(i), abs((yn(i)-si)/si)
      End Do

100   Continue

99999 Format (1X,A,I12)
99998 Format (1X,A,E12.4)
99997 Format (F7.2,2F14.5,2E15.5)
99996 Format (1X,A,I5)
    End Program d05bafe


d05bdfe.f90

!   D05BDF Example Program Text
!   Mark 26 Release. NAG Copyright 2016.
    Module d05bdfe_mod

!     D05BDF Example Program Module:
!            Parameters and User-defined Routines

!     .. Use Statements ..
      Use nag_library, Only: nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Accessibility Statements ..
      Private
      Public                           :: cf1, cf2, cg1, cg2, ck1, ck2
!     .. Parameters ..
      Integer, Parameter, Public       :: iorder = 4
      Integer, Parameter, Public       :: nmesh = 2**6 + 2*iorder - 1
      Integer, Parameter, Public       :: nout = 6
      Integer, Parameter, Public       :: lct = nmesh/32 + 1
      Integer, Parameter, Public       :: lwk = (2*iorder+6)*nmesh + 8*iorder* &
                                          iorder - 16*iorder + 1
    Contains
      Function ck1(t)

!       .. Use Statements ..
        Use nag_library, Only: x01aaf
!       .. Function Return Value ..
        Real (Kind=nag_wp)             :: ck1
!       .. Scalar Arguments ..
        Real (Kind=nag_wp), Intent (In) :: t
!       .. Local Scalars ..
        Real (Kind=nag_wp)             :: pi
!       .. Intrinsic Procedures ..
        Intrinsic                      :: sqrt
!       .. Executable Statements ..
        ck1 = -sqrt(x01aaf(pi))

        Return

      End Function ck1
      Function cf1(t)

!       .. Use Statements ..
        Use nag_library, Only: x01aaf
!       .. Function Return Value ..
        Real (Kind=nag_wp)             :: cf1
!       .. Scalar Arguments ..
        Real (Kind=nag_wp), Intent (In) :: t
!       .. Local Scalars ..
        Real (Kind=nag_wp)             :: pi
!       .. Intrinsic Procedures ..
        Intrinsic                      :: sqrt
!       .. Executable Statements ..
        cf1 = sqrt(t) + (3.0_nag_wp/8.0_nag_wp)*t*t*x01aaf(pi)

        Return

      End Function cf1
      Function cg1(s,y)

!       .. Function Return Value ..
        Real (Kind=nag_wp)             :: cg1
!       .. Scalar Arguments ..
        Real (Kind=nag_wp), Intent (In) :: s, y
!       .. Executable Statements ..
        cg1 = y*y*y

        Return

      End Function cg1
      Function ck2(t)

!       .. Use Statements ..
        Use nag_library, Only: x01aaf
!       .. Function Return Value ..
        Real (Kind=nag_wp)             :: ck2
!       .. Scalar Arguments ..
        Real (Kind=nag_wp), Intent (In) :: t
!       .. Local Scalars ..
        Real (Kind=nag_wp)             :: pi
!       .. Intrinsic Procedures ..
        Intrinsic                      :: sqrt
!       .. Executable Statements ..
        ck2 = -sqrt(x01aaf(pi))

        Return

      End Function ck2
      Function cf2(t)

!       .. Function Return Value ..
        Real (Kind=nag_wp)             :: cf2
!       .. Scalar Arguments ..
        Real (Kind=nag_wp), Intent (In) :: t
!       .. Intrinsic Procedures ..
        Intrinsic                      :: sqrt
!       .. Executable Statements ..
        cf2 = (3.0_nag_wp-t)*sqrt(t)

        Return

      End Function cf2
      Function cg2(s,y)

!       .. Function Return Value ..
        Real (Kind=nag_wp)             :: cg2
!       .. Scalar Arguments ..
        Real (Kind=nag_wp), Intent (In) :: s, y
!       .. Intrinsic Procedures ..
        Intrinsic                      :: exp
!       .. Executable Statements ..
        cg2 = exp(s*(1.0_nag_wp-s)*(1.0_nag_wp-s)-y*y)

        Return

      End Function cg2
    End Module d05bdfe_mod
    Program d05bdfe

!     D05BDF Example Main Program

!     .. Use Statements ..
      Use nag_library, Only: d05bdf, nag_wp, x02ajf
      Use d05bdfe_mod, Only: cf1, cf2, cg1, cg2, ck1, ck2, iorder, lct, lwk,   &
                             nmesh, nout
!     .. Implicit None Statement ..
      Implicit None
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: h, t, tlim, tolnl
      Integer                          :: i, ifail
!     .. Local Arrays ..
      Real (Kind=nag_wp)               :: work(lwk), yn(nmesh)
      Integer                          :: nct(lct)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: mod, real, sqrt
!     .. Executable Statements ..
      Write (nout,*) 'D05BDF Example Program Results'

      tlim = 7.0_nag_wp
      tolnl = sqrt(x02ajf())
      h = tlim/real(nmesh-1,kind=nag_wp)

      ifail = 0
      Call d05bdf(ck1,cf1,cg1,'Initial',iorder,tlim,tolnl,nmesh,yn,work,lwk,   &
        nct,ifail)

      Write (nout,*)
      Write (nout,*) 'Example 1'
      Write (nout,*)
      Write (nout,99998) h
      Write (nout,*)
      Write (nout,*) '     T        Approximate'
      Write (nout,*) '                Solution '
      Write (nout,*)

      Do i = 1, nmesh
        t = real(i-1,kind=nag_wp)*h

        If (mod(i,5)==1) Then
          Write (nout,99999) t, yn(i)
        End If

      End Do

      tlim = 5.0_nag_wp
      h = tlim/real(nmesh-1,kind=nag_wp)

      ifail = 0
      Call d05bdf(ck2,cf2,cg2,'Subsequent',iorder,tlim,tolnl,nmesh,yn,work,    &
        lwk,nct,ifail)

      Write (nout,*)
      Write (nout,*) 'Example 2'
      Write (nout,*)
      Write (nout,99998) h
      Write (nout,*)
      Write (nout,*) '     T        Approximate'
      Write (nout,*) '                Solution '
      Write (nout,*)

      Do i = 1, nmesh
        t = real(i-1,kind=nag_wp)*h

        If (mod(i,7)==1) Then
          Write (nout,99999) t, yn(i)
        End If

      End Do

99999 Format (1X,F8.4,F15.4)
99998 Format (' The stepsize h = ',F8.4)
    End Program d05bdfe


d05befe.f90

!   D05BEF Example Program Text
!   Mark 26 Release. NAG Copyright 2016.
    Module d05befe_mod

!     D05BEF Example Program Module:
!            Parameters and User-defined Routines

!     .. Use Statements ..
      Use nag_library, Only: nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Accessibility Statements ..
      Private
      Public                           :: cf1, cf2, cg1, cg2, ck1, ck2, sol1,  &
                                          sol2
!     .. Parameters ..
      Integer, Parameter, Public       :: iorder = 4
      Integer, Parameter, Public       :: nmesh = 2**6 + 2*iorder - 1
      Integer, Parameter, Public       :: nout = 6
      Integer, Parameter, Public       :: lct = nmesh/32 + 1
      Integer, Parameter, Public       :: lwk = (2*iorder+6)*nmesh + 8*iorder* &
                                          iorder - 16*iorder + 1
    Contains
      Function sol1(t)

!       .. Use Statements ..
        Use nag_library, Only: x01aaf
!       .. Function Return Value ..
        Real (Kind=nag_wp)             :: sol1
!       .. Scalar Arguments ..
        Real (Kind=nag_wp), Intent (In) :: t
!       .. Local Scalars ..
        Real (Kind=nag_wp)             :: c, pi, t1
!       .. Intrinsic Procedures ..
        Intrinsic                      :: exp, sqrt
!       .. Executable Statements ..
        t1 = 1.0_nag_wp + t
        c = 1.0_nag_wp/sqrt(2.0_nag_wp*x01aaf(pi))
        sol1 = c*(1.0_nag_wp/(t**1.5_nag_wp))*exp(-t1*t1/(2.0_nag_wp*t))

        Return

      End Function sol1
      Function sol2(t)

!       .. Function Return Value ..
        Real (Kind=nag_wp)             :: sol2
!       .. Scalar Arguments ..
        Real (Kind=nag_wp), Intent (In) :: t
!       .. Executable Statements ..
        sol2 = 1.0_nag_wp/(1.0_nag_wp+t)

        Return

      End Function sol2
      Function ck1(t)

!       .. Function Return Value ..
        Real (Kind=nag_wp)             :: ck1
!       .. Scalar Arguments ..
        Real (Kind=nag_wp), Intent (In) :: t
!       .. Intrinsic Procedures ..
        Intrinsic                      :: exp
!       .. Executable Statements ..
        ck1 = exp(-0.5_nag_wp*t)

        Return

      End Function ck1
      Function cf1(t)

!       .. Use Statements ..
        Use nag_library, Only: x01aaf
!       .. Function Return Value ..
        Real (Kind=nag_wp)             :: cf1
!       .. Scalar Arguments ..
        Real (Kind=nag_wp), Intent (In) :: t
!       .. Local Scalars ..
        Real (Kind=nag_wp)             :: a, pi, t1
!       .. Intrinsic Procedures ..
        Intrinsic                      :: exp, sqrt
!       .. Executable Statements ..
        t1 = 1.0_nag_wp + t
        a = 1.0_nag_wp/sqrt(x01aaf(pi)*t)
        cf1 = -a*exp(-0.5_nag_wp*t1*t1/t)

        Return

      End Function cf1
      Function cg1(s,y)

!       .. Function Return Value ..
        Real (Kind=nag_wp)             :: cg1
!       .. Scalar Arguments ..
        Real (Kind=nag_wp), Intent (In) :: s, y
!       .. Executable Statements ..
        cg1 = y

        Return

      End Function cg1
      Function ck2(t)

!       .. Use Statements ..
        Use nag_library, Only: x01aaf
!       .. Function Return Value ..
        Real (Kind=nag_wp)             :: ck2
!       .. Scalar Arguments ..
        Real (Kind=nag_wp), Intent (In) :: t
!       .. Local Scalars ..
        Real (Kind=nag_wp)             :: pi
!       .. Intrinsic Procedures ..
        Intrinsic                      :: sqrt
!       .. Executable Statements ..
        ck2 = sqrt(x01aaf(pi))

        Return

      End Function ck2
      Function cf2(t)

!       .. Function Return Value ..
        Real (Kind=nag_wp)             :: cf2
!       .. Scalar Arguments ..
        Real (Kind=nag_wp), Intent (In) :: t
!       .. Local Scalars ..
        Real (Kind=nag_wp)             :: st1
!       .. Intrinsic Procedures ..
        Intrinsic                      :: log, sqrt
!       .. Executable Statements ..
        st1 = sqrt(1.0_nag_wp+t)
        cf2 = -2.0_nag_wp*log(st1+sqrt(t))/st1

        Return

      End Function cf2
      Function cg2(s,y)

!       .. Function Return Value ..
        Real (Kind=nag_wp)             :: cg2
!       .. Scalar Arguments ..
        Real (Kind=nag_wp), Intent (In) :: s, y
!       .. Executable Statements ..
        cg2 = y

        Return

      End Function cg2
    End Module d05befe_mod
    Program d05befe

!     D05BEF Example Main Program

!     .. Use Statements ..
      Use nag_library, Only: d05bef, nag_wp, x02ajf
      Use d05befe_mod, Only: cf1, cf2, cg1, cg2, ck1, ck2, iorder, lct, lwk,   &
                             nmesh, nout, sol1, sol2
!     .. Implicit None Statement ..
      Implicit None
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: err, errmax, h, hi1, soln, t, tlim,  &
                                          tolnl
      Integer                          :: i, ifail
!     .. Local Arrays ..
      Real (Kind=nag_wp)               :: work(lwk), yn(nmesh)
      Integer                          :: nct(lct)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: abs, mod, real, sqrt
!     .. Executable Statements ..
      Write (nout,*) 'D05BEF Example Program Results'

      tlim = 7.0_nag_wp
      tolnl = sqrt(x02ajf())
      h = tlim/real(nmesh-1,kind=nag_wp)
      yn(1) = 0.0_nag_wp

      ifail = 0
      Call d05bef(ck1,cf1,cg1,'Initial',iorder,tlim,tolnl,nmesh,yn,work,lwk,   &
        nct,ifail)

      Write (nout,*)
      Write (nout,*) 'Example 1'
      Write (nout,*)
      Write (nout,99997) h
      Write (nout,*)
      Write (nout,*) '     T        Approximate'
      Write (nout,*) '                Solution '
      Write (nout,*)

      errmax = 0.0_nag_wp

      Do i = 2, nmesh
        hi1 = real(i-1,kind=nag_wp)*h
        err = abs(yn(i)-sol1(hi1))

        If (err>errmax) Then
          errmax = err
          t = hi1
          soln = yn(i)
        End If

        If (i>5 .And. mod(i,5)==1) Then
          Write (nout,99998) hi1, yn(i)
        End If

      End Do

      Write (nout,*)
      Write (nout,99999) errmax, t, soln
      Write (nout,*)

      tlim = 5.0_nag_wp
      h = tlim/real(nmesh-1,kind=nag_wp)
      yn(1) = 1.0_nag_wp

      ifail = 0
      Call d05bef(ck2,cf2,cg2,'Subsequent',iorder,tlim,tolnl,nmesh,yn,work,    &
        lwk,nct,ifail)

      Write (nout,*)
      Write (nout,*) 'Example 2'
      Write (nout,*)
      Write (nout,99997) h
      Write (nout,*)
      Write (nout,*) '     T        Approximate'
      Write (nout,*) '                Solution '
      Write (nout,*)

      errmax = 0.0_nag_wp

      Do i = 1, nmesh
        hi1 = real(i-1,kind=nag_wp)*h
        err = abs(yn(i)-sol2(hi1))

        If (err>errmax) Then
          errmax = err
          t = hi1
          soln = yn(i)
        End If

        If (i>7 .And. mod(i,7)==1) Then
          Write (nout,99998) hi1, yn(i)
        End If

      End Do

      Write (nout,*)
      Write (nout,99999) errmax, t, soln

99999 Format (' The maximum absolute error, ',E10.2,', occurred at T =',F8.4,  &
        /,' with solution ',F8.4)
99998 Format (1X,F8.4,F15.4)
99997 Format (' The stepsize h = ',F8.4)
    End Program d05befe


d05bwfe.f90

    Program d05bwfe

!     D05BWF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: d05bwf, nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: iorder = 4, nomg = 10, nout = 6
      Integer, Parameter               :: nwt = iorder
      Integer, Parameter               :: ldsw = nomg + iorder - 1
!     .. Local Scalars ..
      Integer                          :: ifail, lensw, n
!     .. Local Arrays ..
      Real (Kind=nag_wp)               :: omega(nomg), sw(ldsw,nwt)
!     .. Executable Statements ..
      Write (nout,*) 'D05BWF Example Program Results'

      ifail = 0
      Call d05bwf('BDF',iorder,omega,nomg,lensw,sw,ldsw,nwt,ifail)

      Write (nout,*)
      Write (nout,*) 'The convolution weights'
      Write (nout,*)

      Do n = 1, nomg
        Write (nout,99999) n - 1, omega(n)
      End Do

      Write (nout,*)
      Write (nout,*) 'The weights W'
      Write (nout,*)

      Do n = 1, lensw
        Write (nout,99999) n, sw(n,1:nwt)
      End Do

99999 Format (1X,I3,4X,6F10.4)
    End Program d05bwfe


d05byfe.f90

    Program d05byfe

!     D05BYF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: d05byf, nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: iorder = 4, iq = 3
      Integer, Parameter               :: itiq = 2**(iq+1)
      Integer, Parameter               :: itpmt = 2*iorder - 1
      Integer, Parameter               :: ldsw = itiq + itpmt
      Integer, Parameter               :: lenfw = 2*itiq
      Integer, Parameter               :: lwk = 4*itiq
      Integer, Parameter               :: nout = 6
!     .. Local Scalars ..
      Integer                          :: i, ifail
!     .. Local Arrays ..
      Real (Kind=nag_wp)               :: sw(ldsw,itpmt), work(lwk), wt(lenfw)
!     .. Executable Statements ..
      Write (nout,*) 'D05BYF Example Program Results'

      ifail = 0
      Call d05byf(iorder,iq,lenfw,wt,sw,ldsw,work,lwk,ifail)

      Write (nout,*)
      Write (nout,*) 'Fractional convolution weights'
      Write (nout,*)

      Do i = 1, itiq
        Write (nout,99999) i - 1, wt(i)
      End Do

      Write (nout,*)
      Write (nout,*) 'Fractional starting weights'
      Write (nout,*)

      Do i = 1, ldsw
        Write (nout,99999) i - 1, sw(i,1:itpmt)
      End Do

99999 Format (1X,I5,7F9.4)
    End Program d05byfe


d06aafe.f90

    Program d06aafe

!     D06AAF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: d06aaf, nag_wp, x01aaf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: meshout = 7, nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: coef, pi2, power, r, theta, theta_i, &
                                          x0, y0
      Integer                          :: i, ifail, itrace, liwork, lrwork,    &
                                          nedge, nelt, nv, nvb, nvb1, nvb2,    &
                                          nvb3, nvmax
      Logical                          :: smooth
      Character (1)                    :: pmesh
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: bspace(:), coor(:,:), rwork(:)
      Integer, Allocatable             :: conn(:,:), edge(:,:), iwork(:)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: cos, max, real, sin
!     .. Executable Statements ..
      Write (nout,*) 'D06AAF Example Program Results'

!     Skip heading in data file
      Read (nin,*)

!     Reading of the geometry
!     Coordinates of the boundary mesh vertices and
!     edges references.

      Read (nin,*) nvb1, nvb2, nvb3, nvmax
      nvb = nvb1 + nvb2 + nvb3
      nedge = nvb

      lrwork = nvmax
      liwork = 16*nvmax + 2*nedge + max(4*nvmax+2,nedge-14)
      Allocate (bspace(nvb),coor(2,nvmax),rwork(lrwork),conn(3,2*(nvmax-       &
        1)),edge(3,nedge),iwork(liwork))

!     Outer circle
      pi2 = 2.0_nag_wp*x01aaf(theta)
      theta = pi2/real(nvb1,kind=nag_wp)
      r = 1.0_nag_wp
      x0 = 0.0_nag_wp
      y0 = 0.0_nag_wp
      Do i = 1, nvb1
        theta_i = theta*real(i,kind=nag_wp)
        coor(1,i) = x0 + r*cos(theta_i)
        coor(2,i) = y0 + r*sin(theta_i)
      End Do
!     Larger inner circle
      theta = pi2/real(nvb2,kind=nag_wp)
      r = 0.49_nag_wp
      x0 = -0.5_nag_wp
      y0 = 0.0_nag_wp
      Do i = 1, nvb2
        theta_i = theta*real(i,kind=nag_wp)
        coor(1,nvb1+i) = x0 + r*cos(theta_i)
        coor(2,nvb1+i) = y0 + r*sin(theta_i)
      End Do
!     Smaller inner circle
      theta = pi2/real(nvb3,kind=nag_wp)
      r = 0.15_nag_wp
      x0 = -0.5_nag_wp
      y0 = 0.65_nag_wp
      Do i = 1, nvb3
        theta_i = theta*real(i,kind=nag_wp)
        coor(1,nvb1+nvb2+i) = x0 + r*cos(theta_i)
        coor(2,nvb1+nvb2+i) = y0 + r*sin(theta_i)
      End Do

!     Boundary edges

      Do i = 1, nedge
        edge(1,i) = i
        edge(2,i) = i + 1
        edge(3,i) = 1
      End Do
      edge(2,nvb1) = 1
      edge(2,nvb1+nvb2) = nvb1 + 1
      edge(2,nvb) = nvb1 + nvb2 + 1

!     Initialize mesh control parameters

      bspace(1:nvb) = 0.05E0_nag_wp
      smooth = .True.
      itrace = 0
      coef = 0.75E0_nag_wp
      power = 0.25E0_nag_wp

!     Call to the mesh generator

      ifail = 0
      Call d06aaf(nvb,nvmax,nedge,edge,nv,nelt,coor,conn,bspace,smooth,coef,   &
        power,itrace,rwork,lrwork,iwork,liwork,ifail)

      Write (nout,*)
      Read (nin,*) pmesh

      Select Case (pmesh)
      Case ('N')
        Write (nout,99999) 'NV   =', nv
        Write (nout,99999) 'NELT =', nelt
      Case ('Y')

!       Output the mesh in a form suitable for printing

        Write (meshout,*) '# D06ABF Example Program Mesh results'
        Do i = 1, nelt
          Write (meshout,99998) coor(1,conn(1,i)), coor(2,conn(1,i))
          Write (meshout,99998) coor(1,conn(2,i)), coor(2,conn(2,i))
          Write (meshout,99998) coor(1,conn(3,i)), coor(2,conn(3,i))
          Write (meshout,99998) coor(1,conn(1,i)), coor(2,conn(1,i))
          Write (meshout,*)
        End Do
        Write (meshout,*)
      Case Default
        Write (nout,*) 'Problem with the printing option Y or N'
      End Select

99999 Format (1X,A,I6)
99998 Format (2(2X,E13.6))
    End Program d06aafe


d06abfe.f90

    Program d06abfe

!     D06ABF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: d06abf, f06epf, nag_wp, x01aaf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: meshout = 7, nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: c, d, dnvint, r, s, theta, theta_i
      Integer                          :: i, i1, ic, ifail, itrace, j, liwork, &
                                          lrwork, nearest, nedge, nelt,        &
                                          nelt_near, npropa, nrae, nv, nvb,    &
                                          nvint, nvmax, nv_near
      Character (1)                    :: pmesh
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: coor(:,:), rwork(:), weight(:)
      Real (Kind=nag_wp)               :: t(2)
      Integer, Allocatable             :: conn(:,:), edge(:,:), iwork(:)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: cos, real, sin, tan
!     .. Executable Statements ..
      Write (nout,*) 'D06ABF Example Program Results'

!     Skip heading in data file
      Read (nin,*)

!     Reading of the geometry:
!          number of points on RAE aerofoil data;
!          number of points on circular boundary;
!          maximum number of vertices.

      Read (nin,*) nrae, nvint, nvmax
      Read (nin,*) pmesh

      nvb = nvint + 2*nrae
      nedge = nvb

      lrwork = 12*nvmax + 15
      liwork = 6*nedge + 32*nvmax + 2*nvb + 78
      Allocate (coor(2,nvmax),rwork(lrwork),weight(nvint),conn(3,2*nvmax+5),   &
        edge(3,nedge),iwork(liwork))

!     Circular outer boundary, radius 3 and centre (1,0)
      theta = 2.0_nag_wp*x01aaf(r)/real(nvint,kind=nag_wp)
      r = 3.0_nag_wp
      t(1) = 1.0_nag_wp
      Do i = 1, nvint
        theta_i = theta*real(i-1,kind=nag_wp)
        coor(1,i) = r*cos(theta_i) + t(1)
        coor(2,i) = r*sin(theta_i)
      End Do

!     Read data for aerofoil RAE 2822
      Do i = 1, nrae
        Read (nin,*) i1, coor(1,nvint+i), coor(2,nvint+i)
      End Do

!     Transform RAE 2822 for secondary foil
      theta = x01aaf(theta)/12.0_nag_wp
      c = cos(theta)
      s = sin(theta)
      ic = nvint + nrae
!     Copy and rotate coordinates by theta = pi/12
      coor(1:2,ic+1:ic+nrae) = coor(1:2,nvint+1:ic)
      Call f06epf(nrae,coor(1,ic+1),2,coor(2,ic+1),2,c,s)
!     Reduce by 0.4 and translate to distance 0.25 from intercept at (0.75,0)
      d = 0.4_nag_wp
      t(1) = 0.75_nag_wp + 0.25_nag_wp*c
      t(2) = -0.25_nag_wp*s
      Do i = 1, nrae
        coor(1:2,ic+i) = d*coor(1:2,ic+i) + t(1:2)
      End Do

!     Boundary edges
      Do i = 1, nedge
        edge(1,i) = i
        edge(2,i) = i + 1
        edge(3,i) = 0
      End Do
!     Tie up end of three boundary edges
      edge(2,nvint) = 1
      edge(2,nvint+nrae) = nvint + 1
      edge(2,nedge) = nvint + nrae + 1

!     Initialize mesh control parameters

      itrace = 0

!     Generation of interior vertices on the
!     RAE airfoil's wake

      dnvint = 2.5E0_nag_wp/real(nvint+1,kind=nag_wp)

      Do i = 1, nvint
        i1 = nvb + i
        coor(1,i1) = 1.38E0_nag_wp + real(i,kind=nag_wp)*dnvint
        coor(2,i1) = -tan(theta)*(coor(1,i1)-0.75_nag_wp)
      End Do

      weight(1:nvint) = 0.01E0_nag_wp

      Write (nout,*)

!      Loop on the propagation coef

pcoef: Do j = 1, 4

        nearest = 250
        Select Case (j)
        Case (1)
          npropa = -5
        Case (2)
          npropa = -1
        Case (3)
          npropa = 1
        Case Default
          npropa = 5
        End Select

!       Call to the 2D Delaunay-Voronoi mesh generator

        ifail = 0
        Call d06abf(nvb,nvint,nvmax,nedge,edge,nv,nelt,coor,conn,weight,       &
          npropa,itrace,rwork,lrwork,iwork,liwork,ifail)

        Write (nout,99999) 'Mesh characteristics with NPROPA =', npropa
        nv_near = ((nv+nearest/2)/nearest)*nearest
        nelt_near = ((nelt+nearest/2)/nearest)*nearest
        Write (nout,99998) 'NV  ', nv_near, nearest
        Write (nout,99998) 'NELT', nelt_near, nearest

        If (pmesh=='Y') Then
!         Output the mesh in a form suitable for printing

          If (j==1) Then
            Write (meshout,*) '# D06ABF Example Program Mesh results'
          End If
          Write (meshout,99999) '# Mesh line segments for NPROPA =', npropa
          Do i = 1, nelt
            Write (meshout,99997) coor(1,conn(1,i)), coor(2,conn(1,i))
            Write (meshout,99997) coor(1,conn(2,i)), coor(2,conn(2,i))
            Write (meshout,99997) coor(1,conn(3,i)), coor(2,conn(3,i))
            Write (meshout,99997) coor(1,conn(1,i)), coor(2,conn(1,i))
            Write (meshout,*)
          End Do
          Write (meshout,*)
        End If

      End Do pcoef

99999 Format (1X,A,I6)
99998 Format (1X,A5,' = ',I10,' to the nearest ',I3)
99997 Format (2(2X,E13.6))
    End Program d06abfe


d06acfe.f90

!   D06ACF Example Program Text
!   Mark 26 Release. NAG Copyright 2016.
    Module d06acfe_mod

!     D06ACF Example Program Module:
!            Parameters and User-defined Routines

!     .. Use Statements ..
      Use nag_library, Only: nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Accessibility Statements ..
      Private
      Public                           :: fbnd
!     .. Parameters ..
      Integer, Parameter, Public       :: nin = 5, nout = 6
    Contains
      Function fbnd(i,x,y,ruser,iuser)

!       .. Function Return Value ..
        Real (Kind=nag_wp)             :: fbnd
!       .. Scalar Arguments ..
        Real (Kind=nag_wp), Intent (In) :: x, y
        Integer, Intent (In)           :: i
!       .. Array Arguments ..
        Real (Kind=nag_wp), Intent (Inout) :: ruser(*)
        Integer, Intent (Inout)        :: iuser(*)
!       .. Local Scalars ..
        Real (Kind=nag_wp)             :: c, radius, x0, x1, y0, y1
!       .. Intrinsic Procedures ..
        Intrinsic                      :: sqrt
!       .. Executable Statements ..
        fbnd = 0.0_nag_wp

        Select Case (i)
        Case (1)

!         upper NACA0012 wing beginning at the origin

          c = 1.008930411365_nag_wp
          fbnd = 0.6_nag_wp*(0.2969_nag_wp*sqrt(c*x)-0.126_nag_wp*c*x-         &
            0.3516_nag_wp*(c*x)**2+0.2843_nag_wp*(c*x)**3-                     &
            0.1015_nag_wp*(c*x)**4) - c*y
        Case (2)

!         lower NACA0012 wing beginning at the origin

          c = 1.008930411365_nag_wp
          fbnd = 0.6_nag_wp*(0.2969_nag_wp*sqrt(c*x)-0.126_nag_wp*c*x-         &
            0.3516_nag_wp*(c*x)**2+0.2843_nag_wp*(c*x)**3-                     &
            0.1015_nag_wp*(c*x)**4) + c*y
        Case (3)
          x0 = ruser(1)
          y0 = ruser(2)
          radius = ruser(3)
          fbnd = (x-x0)**2 + (y-y0)**2 - radius**2
        Case (4)

!         upper NACA0012 wing beginning at (X1;Y1)

          c = 1.008930411365_nag_wp
          x1 = ruser(4)
          y1 = ruser(5)
          fbnd = 0.6_nag_wp*(0.2969_nag_wp*sqrt(c*(x-                          &
            x1))-0.126_nag_wp*c*(x-x1)-0.3516_nag_wp*(c*(x-                    &
            x1))**2+0.2843_nag_wp*(c*(x-x1))**3-0.1015_nag_wp*(c*(x-x1))**4) - &
            c*(y-y1)
        Case (5)

!         lower NACA0012 wing beginning at (X1;Y1)

          c = 1.008930411365_nag_wp
          x1 = ruser(4)
          y1 = ruser(5)
          fbnd = 0.6_nag_wp*(0.2969_nag_wp*sqrt(c*(x-                          &
            x1))-0.126_nag_wp*c*(x-x1)-0.3516_nag_wp*(c*(x-                    &
            x1))**2+0.2843_nag_wp*(c*(x-x1))**3-0.1015_nag_wp*(c*(x-x1))**4) + &
            c*(y-y1)
        End Select

        Return

      End Function fbnd
    End Module d06acfe_mod
    Program d06acfe

!     D06ACF Example Main Program

!     .. Use Statements ..
      Use nag_library, Only: d06acf, d06baf, f16dnf, nag_wp
      Use d06acfe_mod, Only: fbnd, nin, nout
!     .. Implicit None Statement ..
      Implicit None
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: dnvint, radius, x0, x1, y0, y1
      Integer                          :: i, ifail, itrace, j, k, liwork,      &
                                          lrwork, maxind, maxval, ncomp,       &
                                          nedge, nedmx, nelt, nlines, nv, nvb, &
                                          nvint, nvint2, nvmax, reftk, sdcrus
      Character (1)                    :: pmesh
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: coor(:,:), coorch(:,:), crus(:,:),   &
                                          rate(:), rwork(:), weight(:)
      Real (Kind=nag_wp)               :: ruser(5)
      Integer, Allocatable             :: conn(:,:), edge(:,:), iwork(:),      &
                                          lcomp(:), lined(:,:), nlcomp(:)
      Integer                          :: iuser(1)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: abs, real
!     .. Executable Statements ..
      Write (nout,*) 'D06ACF Example Program Results'

!     Skip heading in data file
      Read (nin,*)

!     Initialize boundary mesh inputs:
!     the number of line and of the characteristic points of
!     the boundary mesh

      Read (nin,*) nlines, nvmax, nedmx
      Allocate (coor(2,nvmax),coorch(2,nlines),rate(nlines),edge(3,nedmx),     &
        lcomp(nlines),lined(4,nlines))

      Read (nin,*) coorch(1,1:nlines)
      Read (nin,*) coorch(2,1:nlines)

!     The Lines of the boundary mesh

      Read (nin,*)(lined(1:4,j),rate(j),j=1,nlines)

      sdcrus = 0

      Do i = 1, nlines

        If (lined(4,i)<0) Then
          sdcrus = sdcrus + lined(1,i) - 2
        End If

      End Do

      liwork = 8*nlines + nvmax + 3*nedmx + 3*sdcrus

!     Get max(LINED(1,:)) for computing LRWORK

      Call f16dnf(nlines,lined,4,maxind,maxval)

      lrwork = 2*nlines + sdcrus + 2*maxval*nlines

!     The number of connected components to the boundary
!     and their information

      Read (nin,*) ncomp
      Allocate (crus(2,sdcrus),nlcomp(ncomp),iwork(liwork),rwork(lrwork))

      j = 1

      Do i = 1, ncomp
        Read (nin,*) nlcomp(i)
        k = j + abs(nlcomp(i)) - 1
        Read (nin,*) lcomp(j:k)
        j = k + 1
      End Do

!     Data passed to the user-supplied function

      x0 = 1.5_nag_wp
      y0 = 0.0_nag_wp
      radius = 4.5_nag_wp
      x1 = 0.8_nag_wp
      y1 = -0.3_nag_wp

      ruser(1:5) = (/x0,y0,radius,x1,y1/)
      iuser(1) = 0

      itrace = 0

!     Call to the 2D boundary mesh generator

      ifail = 0
      Call d06baf(nlines,coorch,lined,fbnd,crus,sdcrus,rate,ncomp,nlcomp,      &
        lcomp,nvmax,nedmx,nvb,coor,nedge,edge,itrace,ruser,iuser,rwork,lrwork, &
        iwork,liwork,ifail)

      Write (nout,*)
      Read (nin,*) pmesh

      Select Case (pmesh)
      Case ('N')
        Write (nout,*) 'Boundary mesh characteristics'
        Write (nout,99999) 'NVB   =', nvb
        Write (nout,99999) 'NEDGE =', nedge
      Case ('Y')

!       Output the mesh

        Write (nout,99998) nvb, nedge

        Do i = 1, nvb
          Write (nout,99997) i, coor(1:2,i)
        End Do

        Do i = 1, nedge
          Write (nout,99996) i, edge(1:3,i)
        End Do
      Case Default
        Write (nout,*) 'Problem with the printing option Y or N'
        Go To 100
      End Select

      Deallocate (rwork,iwork)

!     Initialize mesh control parameters

      itrace = 0

!     Generation of interior vertices
!     for the wake of the first NACA

      nvint = 40
      lrwork = 12*nvmax + 30015
      liwork = 8*nedge + 53*nvmax + 2*nvb + 10078
      Allocate (weight(nvint),rwork(lrwork),conn(3,2*nvmax+5),iwork(liwork))

      nvint2 = 20
      dnvint = 5.0_nag_wp/real(nvint2+1,kind=nag_wp)

      Do i = 1, nvint2
        reftk = nvb + i
        coor(1,reftk) = 1.0_nag_wp + real(i,kind=nag_wp)*dnvint
        coor(2,reftk) = 0.0_nag_wp
      End Do

      weight(1:nvint2) = 0.05_nag_wp

!     for the wake of the second one

      dnvint = 4.19_nag_wp/real(nvint2+1,kind=nag_wp)

      Do i = nvint2 + 1, nvint
        reftk = nvb + i
        coor(1,reftk) = 1.8_nag_wp + real(i-nvint2,kind=nag_wp)*dnvint
        coor(2,reftk) = -0.3_nag_wp
      End Do

      weight((nvint2+1):nvint) = 0.05_nag_wp

!     Call to the 2D Advancing front mesh generator

      ifail = 0
      Call d06acf(nvb,nvint,nvmax,nedge,edge,nv,nelt,coor,conn,weight,itrace,  &
        rwork,lrwork,iwork,liwork,ifail)

      Select Case (pmesh)
      Case ('N')
        Write (nout,*) 'Complete mesh characteristics'
        Write (nout,99999) 'NV (rounded to nearest 10)   =', 10*((nv+5)/10)
        Write (nout,99999) 'NELT (rounded to nearest 10) =', 10*((nelt+5)/10)
      Case ('Y')

!       Output the mesh

        Write (nout,99998) nv, nelt

        Do i = 1, nv
          Write (nout,99995) coor(1:2,i)
        End Do

        reftk = 0

        Do k = 1, nelt
          Write (nout,99994) conn(1:3,k), reftk
        End Do

      End Select

100   Continue

99999 Format (1X,A,I6)
99998 Format (1X,2I10)
99997 Format (2X,I4,2(2X,E13.6))
99996 Format (1X,4I4)
99995 Format (2(2X,E13.6))
99994 Format (1X,4I10)
    End Program d06acfe


d06bafe.f90

!   D06BAF Example Program Text
!   Mark 26 Release. NAG Copyright 2016.
    Module d06bafe_mod

!     D06BAF Example Program Module:
!            Parameters and User-defined Routines

!     .. Use Statements ..
      Use nag_library, Only: nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Accessibility Statements ..
      Private
      Public                           :: fbnd
!     .. Parameters ..
      Integer, Parameter, Public       :: nin = 5, nout = 6
    Contains
      Function fbnd(i,x,y,ruser,iuser)

!       .. Function Return Value ..
        Real (Kind=nag_wp)             :: fbnd
!       .. Scalar Arguments ..
        Real (Kind=nag_wp), Intent (In) :: x, y
        Integer, Intent (In)           :: i
!       .. Array Arguments ..
        Real (Kind=nag_wp), Intent (Inout) :: ruser(*)
        Integer, Intent (Inout)        :: iuser(*)
!       .. Local Scalars ..
        Real (Kind=nag_wp)             :: radius2, x0, xa, xb, y0
!       .. Executable Statements ..
        xa = ruser(1)
        xb = ruser(2)
        x0 = ruser(3)
        y0 = ruser(4)

        fbnd = 0.0_nag_wp

        Select Case (i)
        Case (1)

!         line 1,2,3, and 4: ellipse centred in (X0,Y0) with
!         XA and XB as coefficients

          fbnd = ((x-x0)/xa)**2 + ((y-y0)/xb)**2 - 1.0_nag_wp
        Case (2)

!         line 7, lower arc on letter n, is a circle centred in (X0,Y0)
!         with radius SQRT(RADIUS2)

          x0 = 0.5_nag_wp
          y0 = 6.25_nag_wp
          radius2 = 20.3125_nag_wp
          fbnd = (x-x0)**2 + (y-y0)**2 - radius2
        Case (3)

!         line 11, upper arc on letter n, is a circle centred in (X0,Y0)
!         with radius SQRT(RADIUS2)

          x0 = 1.0_nag_wp
          y0 = 4.0_nag_wp
          radius2 = 9.0_nag_wp + (11.0_nag_wp-y0)**2
          fbnd = (x-x0)**2 + (y-y0)**2 - radius2
        Case (4)

!         line 15, upper arc on letter a, is a circle centred in (X0,Y0)
!         with radius SQRT(RADIUS2) touching point (5,11).

          x0 = 8.5_nag_wp
          y0 = 2.75_nag_wp
          radius2 = (x0-5.0_nag_wp)**2 + (11.0_nag_wp-y0)**2
          fbnd = (x-x0)**2 + (y-y0)**2 - radius2
        Case (5)

!         line 25, lower arc on hat of 'a', is a circle centred in (X0,Y0)
!         with radius SQRT(RADIUS2) touching point (11,10).

          x0 = 8.5_nag_wp
          y0 = 4.0_nag_wp
          radius2 = 2.5_nag_wp**2 + (10.0_nag_wp-y0)**2
          fbnd = (x-x0)**2 + (y-y0)**2 - radius2
        Case (6)

!         lines 20, 21 and 22, belly of letter a, is an ellipse centered
!         in (X0, Y0) with semi-axes 3.5 and 2.75.

          x0 = 8.5_nag_wp
          y0 = 5.75_nag_wp
          fbnd = ((x-x0)/3.5_nag_wp)**2 + ((y-y0)/2.75_nag_wp)**2 - 1.0_nag_wp
        Case (7)

!         lines 43, 44 and 45, outer curve on bottom of 'g', is an ellipse
!         centered in (X0, Y0) with semi-axes 3.5 and 2.5.

          x0 = 17.5_nag_wp
          y0 = 2.5_nag_wp
          fbnd = ((x-x0)/3.5_nag_wp)**2 + ((y-y0)/2.5_nag_wp)**2 - 1.0_nag_wp
        Case (8)

!         lines 28, 29 and 30, inner curve on bottom of 'g', is an ellipse
!         centered in (X0, Y0) with semi-axes 2.0 and 1.5.

          x0 = 17.5_nag_wp
          y0 = 2.5_nag_wp
          fbnd = ((x-x0)/2.0_nag_wp)**2 + ((y-y0)/1.5_nag_wp)**2 - 1.0_nag_wp
        Case (9)

!         line 42, inner curve on lower middle of 'g', is an ellipse
!         centered in (X0, Y0) with semi-axes 1.5 and 0.5.

          x0 = 17.5_nag_wp
          y0 = 5.5_nag_wp
          fbnd = ((x-x0)/1.5_nag_wp)**2 + ((y-y0)/0.5_nag_wp)**2 - 1.0_nag_wp
        Case (10)

!         line 31, outer curve on lower middle of 'g', is an ellipse
!         centered in (X0, Y0) with semi-axes 2.0 and 1.5.

          x0 = 17.5_nag_wp
          y0 = 5.5_nag_wp
          fbnd = ((x-x0)/3.0_nag_wp)**2 + ((y-y0)/1.5_nag_wp)**2 - 1.0_nag_wp
        Case (11)

!         line 41, inner curve on upper middle of 'g', is an ellipse
!         centered in (X0, Y0) with semi-axes 1.0 and 1.0.

          x0 = 17.0_nag_wp
          y0 = 5.5_nag_wp
          fbnd = ((x-x0)/1.0_nag_wp)**2 + ((y-y0)/1.0_nag_wp)**2 - 1.0_nag_wp
        Case (12)

!         line 32, outer curve on upper middle of 'g', is an ellipse
!         centered in (X0, Y0) with semi-axes 1.5 and 1.1573.

          x0 = 16.0_nag_wp
          y0 = 5.5_nag_wp
          fbnd = ((x-x0)/1.5_nag_wp)**2 + ((y-y0)/1.1573_nag_wp)**2 -          &
            1.0_nag_wp
        Case (13)

!         lines 33, 33, 34, 39 and 40, upper portion of 'g', is an ellipse
!         centered in (X0, Y0) with semi-axes 3.0 and 2.75.
          x0 = 17.0_nag_wp
          y0 = 9.25_nag_wp
          fbnd = ((x-x0)/3.0_nag_wp)**2 + ((y-y0)/2.75_nag_wp)**2 - 1.0_nag_wp
        End Select

        Return

      End Function fbnd
    End Module d06bafe_mod
    Program d06bafe

!     D06BAF Example Main Program

!     .. Use Statements ..
      Use nag_library, Only: d06abf, d06acf, d06baf, f16dnf, nag_wp
      Use d06bafe_mod, Only: fbnd, nin, nout
!     .. Implicit None Statement ..
      Implicit None
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: x0, xa, xb, xmax, xmin, y0, ymax,    &
                                          ymin
      Integer                          :: i, ifail, itrace, j, k, liwork,      &
                                          lrwork, maxind, maxval, ncomp,       &
                                          nedge, nedmx, nelt, nlines, npropa,  &
                                          nv, nvb, nvint, nvmax, reftk, sdcrus
      Character (1)                    :: pmesh
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: coor(:,:), coorch(:,:), crus(:,:),   &
                                          rate(:), rwork(:), weight(:)
      Real (Kind=nag_wp)               :: ruser(4)
      Integer, Allocatable             :: conn(:,:), edge(:,:), iwork(:),      &
                                          lcomp(:), lined(:,:), nlcomp(:)
      Integer                          :: iuser(1)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: abs
!     .. Executable Statements ..
      Write (nout,*) 'D06BAF Example Program Results'
      Flush (nout)

!     Skip heading in data file
      Read (nin,*)

!     Initialize boundary mesh inputs:
!     the number of line and of the characteristic points of
!     the boundary mesh

      Read (nin,*) nlines, nvmax, nedmx
      Allocate (coor(2,nvmax),coorch(2,nlines),rate(nlines),edge(3,nedmx),     &
        lcomp(nlines),lined(4,nlines))

!     The Lines of the boundary mesh

      Read (nin,*)(lined(1:4,j),rate(j),j=1,nlines)

      sdcrus = 0

      Do i = 1, nlines

        If (lined(4,i)<0) Then
          sdcrus = sdcrus + lined(1,i) - 2
        End If

      End Do

      liwork = 8*nlines + nvmax + 3*nedmx + 3*sdcrus

!     Get max(LINED(1,:)) for computing LRWORK

      Call f16dnf(nlines,lined,4,maxind,maxval)

      lrwork = 2*(nlines+sdcrus) + 2*maxval*nlines

      Allocate (crus(2,sdcrus),iwork(liwork),rwork(lrwork))

!     The ellipse boundary which envelops the NAG Logo
!     the N, the A and the G

      Read (nin,*) coorch(1,1:nlines)
      Read (nin,*) coorch(2,1:nlines)

      Read (nin,*) crus(1,1:sdcrus)
      Read (nin,*) crus(2,1:sdcrus)

!     The number of connected components to the boundary
!     and their information

      Read (nin,*) ncomp
      Allocate (nlcomp(ncomp))

      j = 1

      Do i = 1, ncomp
        Read (nin,*) nlcomp(i)
        k = j + abs(nlcomp(i)) - 1
        Read (nin,*) lcomp(j:k)
        j = k + 1
      End Do

!     Data passed to the user-supplied function

      xmin = coorch(1,4)
      xmax = coorch(1,2)
      ymin = coorch(2,1)
      ymax = coorch(2,3)

      xa = (xmax-xmin)/2.0_nag_wp
      xb = (ymax-ymin)/2.0_nag_wp

      x0 = (xmin+xmax)/2.0_nag_wp
      y0 = (ymin+ymax)/2.0_nag_wp

      ruser(1:4) = (/xa,xb,x0,y0/)
      iuser(1) = 0

      itrace = -1

      Write (nout,*)
      Flush (nout)

!     Call to the boundary mesh generator

      ifail = 0
      Call d06baf(nlines,coorch,lined,fbnd,crus,sdcrus,rate,ncomp,nlcomp,      &
        lcomp,nvmax,nedmx,nvb,coor,nedge,edge,itrace,ruser,iuser,rwork,lrwork, &
        iwork,liwork,ifail)

      Read (nin,*) pmesh

      Select Case (pmesh)
      Case ('N')
        Write (nout,*) 'Boundary mesh characteristics'
        Write (nout,99999) 'NVB   =', nvb
        Write (nout,99999) 'NEDGE =', nedge
      Case ('Y')

!       Output the mesh

        Write (nout,99998) nvb, nedge

        Do i = 1, nvb
          Write (nout,99997) i, coor(1:2,i)
        End Do

        Do i = 1, nedge
          Write (nout,99996) i, edge(1:3,i)
        End Do

        Flush (nout)

      Case Default
        Write (nout,*) 'Problem with the printing option Y or N'
        Go To 100
      End Select

      Deallocate (rwork,iwork)

!     Initialize mesh control parameters

      itrace = 0
      npropa = 1
      nvint = 0
      lrwork = 12*nvmax + 15
      liwork = 6*nedge + 32*nvmax + 2*nvb + 78
      Allocate (weight(nvint),rwork(lrwork),iwork(liwork),conn(3,2*nvmax+5))

!     Call to the 2D Delaunay-Voronoi mesh generator

      ifail = 0
      Call d06abf(nvb,nvint,nvmax,nedge,edge,nv,nelt,coor,conn,weight,npropa,  &
        itrace,rwork,lrwork,iwork,liwork,ifail)

      Select Case (pmesh)
      Case ('N')
        Write (nout,*) 'Complete mesh (via the 2D Delaunay-Voronoi'
        Write (nout,*) 'mesh generator) characteristics'
        Write (nout,99999) 'NV (rounded to nearest 10)   =', 10*((nv+5)/10)
        Write (nout,99999) 'NELT (rounded to nearest 10) =', 10*((nelt+5)/10)
      Case ('Y')

!       Output the mesh

        Write (nout,99998) nv, nelt

        Do i = 1, nv
          Write (nout,99995) coor(1:2,i)
        End Do

        reftk = 0

        Do k = 1, nelt
          Write (nout,99994) conn(1:3,k), reftk
        End Do

        Flush (nout)

      End Select

      Deallocate (rwork,iwork)
      lrwork = 12*nvmax + 30015
      liwork = 8*nedge + 53*nvmax + 2*nvb + 10078
      Allocate (rwork(lrwork),iwork(liwork))

!     Call to the 2D Advancing front mesh generator

      ifail = 0
      Call d06acf(nvb,nvint,nvmax,nedge,edge,nv,nelt,coor,conn,weight,itrace,  &
        rwork,lrwork,iwork,liwork,ifail)

      Select Case (pmesh)
      Case ('N')
        Write (nout,*) 'Complete mesh (via the 2D Advancing front mesh'
        Write (nout,*) 'generator) characteristics'
        Write (nout,99999) 'NV (rounded to nearest 10)   =', 10*((nv+5)/10)
        Write (nout,99999) 'NELT (rounded to nearest 10) =', 10*((nelt+5)/10)
      Case ('Y')

!       Output the mesh

        Write (nout,99998) nv, nelt

        Do i = 1, nv
          Write (nout,99995) coor(1:2,i)
        End Do

        reftk = 0

        Do k = 1, nelt
          Write (nout,99994) conn(1:3,k), reftk
        End Do

      End Select

100   Continue

99999 Format (1X,A,I6)
99998 Format (1X,2I10)
99997 Format (2X,I4,2(2X,E13.6))
99996 Format (1X,4I4)
99995 Format (2(2X,E13.6))
99994 Format (1X,4I10)
    End Program d06bafe


d06cafe.f90

    Program d06cafe

!     D06CAF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: d06caf, g05kff, g05sqf, nag_wp, x01aaf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: delta, hx, hy, pi2, r, rad, sk,      &
                                          theta, x1, x2, x3, y1, y2, y3
      Integer                          :: genid, i, ifail, imax, ind, itrace,  &
                                          j, jmax, k, liwork, lrwork, lseed,   &
                                          lstate, me1, me2, me3, nedge, nelt,  &
                                          nqint, nv, nvfix, reftk, subid
      Character (1)                    :: pmesh
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: coor(:,:), rwork(:), variates(:)
      Integer, Allocatable             :: conn(:,:), edge(:,:), iwork(:),      &
                                          numfix(:), seed(:), state(:)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: cos, min, real, sin
!     .. Executable Statements ..
      Write (nout,*) 'D06CAF Example Program Results'
      Flush (nout)

!     Skip heading in data file
      Read (nin,*)

!     Read IMAX and JMAX, the number of vertices
!     in the x and y directions respectively.

      Read (nin,*) imax, jmax
      nv = imax*jmax
      nelt = 2*(imax-1)*(jmax-1)
      nedge = 2*(imax-1) + 2*(jmax-1)
      liwork = 8*nelt + 2*nv
      lrwork = 2*nv + nelt

!     The array VARIATES will be used when distorting the mesh

      Allocate (variates(2*nv),coor(2,nv),conn(3,nelt),edge(3,nedge),          &
        iwork(liwork),rwork(lrwork))

!     Read distortion percentage and calculate radius
!     of distortion neighbourhood so that cross-over
!     can only occur at 100% or greater.

      Read (nin,*) delta

      hx = 1.0E0_nag_wp/real(imax-1,kind=nag_wp)
      hy = 1.0E0_nag_wp/real(jmax-1,kind=nag_wp)
      rad = 0.005E0_nag_wp*delta*min(hx,hy)
      pi2 = 2.0E0_nag_wp*x01aaf(pi2)

!     GENID identifies the base generator

      genid = 1
      subid = 1

!     For GENID = 1 only one seed is required
!     The initializer is first called in query mode to get the value of
!     LSTATE for the chosen base generator

      lseed = 1
      lstate = -1
      Allocate (seed(lseed),state(lstate))

!     Initialize the seed

      seed(1:lseed) = (/1762541/)

      ifail = 0
      Call g05kff(genid,subid,seed,lseed,state,lstate,ifail)

      Deallocate (state)
      Allocate (state(lstate))

!     Initialize the generator to a repeatable sequence

      ifail = 0
      Call g05kff(genid,subid,seed,lseed,state,lstate,ifail)

!     Generate two sets of uniform random variates

      ifail = 0
      Call g05sqf(nv,0.0E0_nag_wp,rad,state,variates,ifail)

      ifail = 0
      Call g05sqf(nv,0.0E0_nag_wp,pi2,state,variates(nv+1),ifail)

!     Generate a simple uniform mesh and then distort it
!     randomly within the distortion neighbourhood of each
!     node.

      k = 0
      ind = 0

      Do j = 1, jmax

        Do i = 1, imax
          k = k + 1
          r = variates(k)
          theta = variates(nv+k)

          If (i==1 .Or. i==imax .Or. j==1 .Or. j==jmax) Then
            r = 0.E0_nag_wp
          End If

          coor(1,k) = real(i-1,kind=nag_wp)*hx + r*cos(theta)
          coor(2,k) = real(j-1,kind=nag_wp)*hy + r*sin(theta)

          If (i<imax .And. j<jmax) Then
            ind = ind + 1
            conn(1,ind) = k
            conn(2,ind) = k + 1
            conn(3,ind) = k + imax + 1
            ind = ind + 1
            conn(1,ind) = k
            conn(2,ind) = k + imax + 1
            conn(3,ind) = k + imax
          End If

        End Do

      End Do

      Read (nin,*) pmesh

      Write (nout,*)

      Select Case (pmesh)
      Case ('N')
        Write (nout,*) 'The complete distorted mesh characteristics'
        Write (nout,99999) 'Number of vertices =', nv
        Write (nout,99999) 'Number of elements =', nelt
      Case ('Y')

!       Output the mesh

        Write (nout,99998) nv, nelt

        Do i = 1, nv
          Write (nout,99997) coor(1,i), coor(2,i)
        End Do

      Case Default
        Write (nout,*) 'Problem: the printing option must be Y or N'
        Go To 100
      End Select

      reftk = 0

      Do k = 1, nelt
        me1 = conn(1,k)
        me2 = conn(2,k)
        me3 = conn(3,k)

        x1 = coor(1,me1)
        x2 = coor(1,me2)
        x3 = coor(1,me3)
        y1 = coor(2,me1)
        y2 = coor(2,me2)
        y3 = coor(2,me3)

        sk = ((x2-x1)*(y3-y1)-(y2-y1)*(x3-x1))/2.E0_nag_wp

        If (sk<0.E0_nag_wp) Then
          Write (nout,*) 'Error: the surface of the element is negative'
          Write (nout,99999) 'element number  = ', k
          Write (nout,99995) 'element surface = ', sk
          Go To 100
        End If

        If (pmesh=='Y') Then
          Write (nout,99996) conn(1,k), conn(2,k), conn(3,k), reftk
        End If

      End Do
      Flush (nout)

!     Boundary edges

      Do i = 1, imax - 1
        edge(1,i) = i
        edge(2,i) = i + 1
      End Do

      Do i = 1, jmax - 1
        edge(1,imax-1+i) = i*imax
        edge(2,imax-1+i) = (i+1)*imax
      End Do

      Do i = 1, imax - 1
        edge(1,imax-1+jmax-1+i) = imax*jmax - i + 1
        edge(2,imax-1+jmax-1+i) = imax*jmax - i
      End Do

      Do i = 1, jmax - 1
        edge(1,2*(imax-1)+jmax-1+i) = (jmax-i)*imax + 1
        edge(2,2*(imax-1)+jmax-1+i) = (jmax-i-1)*imax + 1
      End Do

      edge(3,1:nedge) = 0

      nvfix = 0
      Allocate (numfix(nvfix))

      itrace = 1
      nqint = 10

!     Call the smoothing routine

      ifail = 0
      Call d06caf(nv,nelt,nedge,coor,edge,conn,nvfix,numfix,itrace,nqint,      &
        iwork,liwork,rwork,lrwork,ifail)

      Select Case (pmesh)
      Case ('N')
        Write (nout,*)
        Write (nout,*) 'The complete smoothed mesh characteristics'
        Write (nout,99999) 'Number of vertices =', nv
        Write (nout,99999) 'Number of elements =', nelt
      Case ('Y')

!       Output the mesh

        Write (nout,99998) nv, nelt

        Do i = 1, nv
          Write (nout,99997) coor(1,i), coor(2,i)
        End Do

        reftk = 0

        Do k = 1, nelt
          Write (nout,99996) conn(1,k), conn(2,k), conn(3,k), reftk
        End Do

      End Select

100   Continue

99999 Format (1X,A,I6)
99998 Format (1X,2I10)
99997 Format (2(2X,E13.6))
99996 Format (1X,4I10)
99995 Format (1X,A,E13.6)
    End Program d06cafe


d06ccfe.f90

!   D06CCF Example Program Text
!   Mark 26 Release. NAG Copyright 2016.
    Module d06ccfe_mod

!     D06CCF Example Program Module:
!            Parameters and User-defined Routines

!     .. Use Statements ..
      Use nag_library, Only: nag_wp, x01aaf
!     .. Implicit None Statement ..
      Implicit None
!     .. Accessibility Statements ..
      Private
      Public                           :: create_mesh
!     .. Parameters ..
      Integer, Parameter, Public       :: matout = 7, nout = 6, nvb1 = 40,     &
                                          nvb2 = 30, nvb3 = 30, nvmax = 260
      Integer, Parameter, Public       :: nvb = nvb1 + nvb2 + nvb3
      Integer, Parameter, Public       :: nedge = nvb
      Logical, Parameter, Public       :: pmesh = .False.

    Contains
      Subroutine create_mesh(edge,coor,nv,nelt,conn)

!       .. Use Statements ..
        Use nag_library, Only: d06aaf
!       .. Scalar Arguments ..
        Integer, Intent (Out)          :: nelt, nv
!       .. Array Arguments ..
        Real (Kind=nag_wp), Intent (Out) :: coor(2,nvmax)
        Integer, Intent (Out)          :: conn(3,2*nvmax-2), edge(3,nedge)
!       .. Local Scalars ..
        Real (Kind=nag_wp)             :: coef, pi2, power, r, theta, theta_i, &
                                          x0, y0
        Integer                        :: i, ifail, itrace, liwork, lrwork
        Logical                        :: smooth
!       .. Local Arrays ..
        Real (Kind=nag_wp), Allocatable :: bspace(:), rwork(:)
        Integer, Allocatable           :: iwork(:)
!       .. Intrinsic Procedures ..
        Intrinsic                      :: cos, max, real, sin
!       .. Executable Statements ..

        lrwork = nvmax
        liwork = 16*nvmax + 2*nedge + max(4*nvmax+2,nedge-14)
        Allocate (bspace(nvb),rwork(lrwork),iwork(liwork))

!       Outer circle
        pi2 = 2.0_nag_wp*x01aaf(theta)
        theta = pi2/real(nvb1,kind=nag_wp)
        r = 1.0_nag_wp
        x0 = 0.0_nag_wp
        y0 = 0.0_nag_wp
        Do i = 1, nvb1
          theta_i = theta*real(i,kind=nag_wp)
          coor(1,i) = x0 + r*cos(theta_i)
          coor(2,i) = y0 + r*sin(theta_i)
        End Do
!       Larger inner circle
        theta = pi2/real(nvb2,kind=nag_wp)
        r = 0.49_nag_wp
        x0 = -0.5_nag_wp
        y0 = 0.0_nag_wp
        Do i = 1, nvb2
          theta_i = theta*real(i,kind=nag_wp)
          coor(1,nvb1+i) = x0 + r*cos(theta_i)
          coor(2,nvb1+i) = y0 + r*sin(theta_i)
        End Do
!       Smaller inner circle
        theta = pi2/real(nvb3,kind=nag_wp)
        r = 0.15_nag_wp
        x0 = -0.5_nag_wp
        y0 = 0.65_nag_wp
        Do i = 1, nvb3
          theta_i = theta*real(i,kind=nag_wp)
          coor(1,nvb1+nvb2+i) = x0 + r*cos(theta_i)
          coor(2,nvb1+nvb2+i) = y0 + r*sin(theta_i)
        End Do

!       Boundary edges
        Do i = 1, nedge
          edge(1,i) = i
          edge(2,i) = i + 1
          edge(3,i) = 1
        End Do
        edge(2,nvb1) = 1
        edge(2,nvb1+nvb2) = nvb1 + 1
        edge(2,nvb) = nvb1 + nvb2 + 1

!       Initialize mesh control parameters
        bspace(1:nvb) = 0.05E0_nag_wp
        smooth = .True.
        itrace = 0
        coef = 0.75E0_nag_wp
        power = 0.25E0_nag_wp

!       Call to the mesh generator
        ifail = 0
        Call d06aaf(nvb,nvmax,nedge,edge,nv,nelt,coor,conn,bspace,smooth,coef, &
          power,itrace,rwork,lrwork,iwork,liwork,ifail)

        Deallocate (bspace,rwork,iwork)

        Return
      End Subroutine create_mesh
    End Module d06ccfe_mod
    Program d06ccfe

!     D06CCF Example Main Program

!     .. Use Statements ..
      Use nag_library, Only: d06cbf, d06ccf, nag_wp
      Use d06ccfe_mod, Only: create_mesh, matout, nedge, nout, nvmax, pmesh
!     .. Implicit None Statement ..
      Implicit None
!     .. Local Scalars ..
      Integer                          :: i, ifail, itrace, liwork, lrwork,    &
                                          nelt, nnz, nnzmax, nv
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: coor(:,:), rwork(:)
      Integer, Allocatable             :: conn(:,:), edge(:,:), icol(:),       &
                                          irow(:), iwork(:)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: max
!     .. Executable Statements ..
      Write (nout,*) 'D06CCF Example Program Results'
      Flush (nout)

!     Allocate arrays defining mesh
      Allocate (conn(3,2*nvmax-2),edge(3,nedge),coor(2,nvmax))

!     Define boundary mesh and Generate interior mesh
      Call create_mesh(edge,coor,nv,nelt,conn)

      nnzmax = nv**2
      liwork = max(nnzmax,20*nv)
      lrwork = nv
      Allocate (irow(nnzmax),icol(nnzmax),iwork(liwork),rwork(lrwork))

!     Compute the sparsity of the FE matrix
!     from the input geometry

      ifail = 0
      Call d06cbf(nv,nelt,nnzmax,conn,nnz,irow,icol,ifail)

      Write (nout,*)

      If (pmesh) Then

!       Output the sparsity of the mesh
        Write (matout,99998)(irow(i),icol(i),i=1,nnz)

      Else
        Write (nout,*) 'Matrix Sparsity characteristics before renumbering'
        Write (nout,99999) 'nv   =', nv
        Write (nout,99999) 'nnz  =', nnz
        Write (nout,99999) 'nelt =', nelt
      End If
      Flush (nout)

!     Call the renumbering routine and get the new sparsity

      itrace = 1

      ifail = 0
      Call d06ccf(nv,nelt,nedge,nnzmax,nnz,coor,edge,conn,irow,icol,itrace,    &
        iwork,liwork,rwork,lrwork,ifail)

      If (pmesh) Then

!       Output the sparsity of the renumbered mesh
        Write (matout,*)
        Write (matout,*)
        Write (matout,99998)(irow(i),icol(i),i=1,nnz)

!       Output the renumbered mesh
        Write (nout,99998) nv, nelt
        Write (nout,99997)(coor(1:2,i),i=1,nv)
        Write (nout,99996)(conn(1:3,i),i=1,nelt)

      Else
        Write (nout,*)
        Write (nout,*) 'Matrix Sparsity characteristics after renumbering'
        Write (nout,99999) 'nv   =', nv
        Write (nout,99999) 'nnz  =', nnz
        Write (nout,99999) 'nelt =', nelt
      End If

99999 Format (1X,A,I6)
99998 Format (1X,2I10)
99997 Format (2(2X,E13.6))
99996 Format (1X,3I10)
    End Program d06ccfe


d06dbfe.f90

!   D06DBF Example Program Text
!   Mark 26 Release. NAG Copyright 2016.
    Module d06dbfe_mod

!     D06DBF Example Program Module:
!            Parameters and User-defined Routines

!     .. Use Statements ..
      Use nag_library, Only: nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Accessibility Statements ..
      Private
      Public                           :: fbnd
!     .. Parameters ..
      Integer, Parameter, Public       :: meshout = 7, nin = 5, nout = 6,      &
                                          nvb1 = 19
      Logical, Parameter, Public       :: pmesh = .False.
    Contains
      Function fbnd(i,x,y,ruser,iuser)

!       .. Function Return Value ..
        Real (Kind=nag_wp)             :: fbnd
!       .. Scalar Arguments ..
        Real (Kind=nag_wp), Intent (In) :: x, y
        Integer, Intent (In)           :: i
!       .. Array Arguments ..
        Real (Kind=nag_wp), Intent (Inout) :: ruser(*)
        Integer, Intent (Inout)        :: iuser(*)
!       .. Local Scalars ..
        Real (Kind=nag_wp)             :: radius2, x0, y0
!       .. Executable Statements ..
        fbnd = 0.0_nag_wp

        Select Case (i)
        Case (1)

!         inner circle

          x0 = 0.0_nag_wp
          y0 = 0.0_nag_wp
          radius2 = 1.0_nag_wp
          fbnd = (x-x0)**2 + (y-y0)**2 - radius2
        Case (2)

!         outer circle

          x0 = 0.0_nag_wp
          y0 = 0.0_nag_wp
          radius2 = 5.0_nag_wp
          fbnd = (x-x0)**2 + (y-y0)**2 - radius2
        End Select

        Return

      End Function fbnd
    End Module d06dbfe_mod
    Program d06dbfe

!     D06DBF Example Main Program

!     .. Use Statements ..
      Use d06dbfe_mod, Only: nout
!     .. Implicit None Statement ..
      Implicit None
!     .. Executable Statements ..
      Write (nout,*) 'D06DBF Example Program Results'

      Call ex1

      Call ex2

    Contains
      Subroutine ex1

!       .. Use Statements ..
        Use nag_library, Only: d06daf, d06dbf, nag_wp, x01aaf
        Use d06dbfe_mod, Only: meshout, nout, nvb1, pmesh
!       .. Local Scalars ..
        Real (Kind=nag_wp)             :: ddx, ddy, dx, eps, pi2, pi4, r_i,    &
                                          r_j
        Integer                        :: i, ifail, imax, itrace, itrans, j,   &
                                          jmax, jtrans, k, ktrans, l, liwork,  &
                                          lrwork, nedge1, nedge2, nedge3,      &
                                          nelt1, nelt2, nelt3, ntrans, nv1,    &
                                          nv2, nv3
!       .. Local Arrays ..
        Real (Kind=nag_wp), Allocatable :: coor1(:,:), coor2(:,:), coor3(:,:), &
                                          rwork(:), trans(:,:)
        Integer, Allocatable           :: conn1(:,:), conn2(:,:), conn3(:,:),  &
                                          edge1(:,:), edge2(:,:), edge3(:,:),  &
                                          itype(:), iwork(:), reft1(:),        &
                                          reft2(:), reft3(:)
!       .. Intrinsic Procedures ..
        Intrinsic                      :: real, sin
!       .. Executable Statements ..
        Write (nout,*)
        Write (nout,*) 'Example 1'
        Write (nout,*)

        imax = nvb1 + 1
        jmax = imax
        nedge1 = 2*(imax-1) + 2*(jmax-1)
        nedge2 = nedge1
        nedge3 = nedge1 + nedge2
        ntrans = 1
        lrwork = 12*ntrans

!       Allocate for mesh : coordinates and connectivity of the 1st domain,
!                           2nd translated domain and restitched domain.

        nv1 = (nvb1+1)**2
        nelt1 = 2*nvb1*nvb1
        nv2 = nv1
        nv3 = nv1 + nv2
        nelt2 = nelt1
        nelt3 = nelt1 + nelt2
        liwork = 2*nv1 + 3*nv2 + nelt1 + nelt2 + nedge1 + nedge2 + 1024
        Allocate (coor1(2,nv1),coor2(2,nv2),coor3(2,nv3),conn1(3,nelt1),       &
          conn2(3,nelt2),conn3(3,nelt3),reft1(nelt1),reft2(nelt2),             &
          reft3(nelt3),edge1(3,nedge1),edge2(3,nedge2),edge3(3,nedge3),        &
          itype(ntrans),trans(6,ntrans),rwork(lrwork),iwork(liwork))

!       Set up interior mesh as small perturbations on regular grid
!       with regularity on the boundary of square on [0,1]x[0,1].
        dx = 1.0_nag_wp/real(nvb1,kind=nag_wp)
        pi2 = x01aaf(dx) + x01aaf(dx)
        pi4 = pi2 + pi2
        k = 0
        Do j = 1, jmax
          ddy = real(j-1,kind=nag_wp)*dx
          Do i = 1, imax
            k = k + 1
            ddx = real(i-1,kind=nag_wp)*dx
            coor1(1,k) = ddx + dx*0.05_nag_wp*sin(pi4*ddx)*sin(pi4*ddy)
            coor1(2,k) = ddy + dx*0.05_nag_wp*sin(pi2*ddx)*sin(pi2*ddy)
          End Do
        End Do

!       Triangulate using skew-diagonals on grid squares
        k = 0
        l = 0
        Do i = 1, nvb1
          Do j = 1, nvb1
            l = l + 1
            k = k + 1
            conn1(1,k) = l
            conn1(2,k) = l + 1
            conn1(3,k) = l + nvb1 + 2
            k = k + 1
            conn1(1,k) = l
            conn1(2,k) = l + nvb1 + 2
            conn1(3,k) = l + nvb1 + 1
          End Do
          l = l + 1
        End Do

        reft1(1:nelt1) = 1
        reft2(1:nelt2) = 2

!       Define the edges of the boundary
        Do i = 1, nvb1
          edge1(1,i) = i
          edge1(2,i) = i + 1
        End Do
        Do i = 1, nvb1
          edge1(1,nvb1+i) = i*imax
          edge1(2,nvb1+i) = (i+1)*imax
        End Do
        Do i = 1, nvb1
          edge1(1,2*nvb1+i) = imax*jmax - i + 1
          edge1(2,2*nvb1+i) = imax*jmax - i
        End Do
        Do i = 1, nvb1
          edge1(1,3*nvb1+i) = (jmax-i)*imax + 1
          edge1(2,3*nvb1+i) = (jmax-i-1)*imax + 1
        End Do
        edge1(3,1:nedge1) = 1

        If (pmesh) Then
!         Print interior mesh of single square
          Do i = 1, nelt1
            Write (meshout,99997) coor1(1,conn1(1,i)), coor1(2,conn1(1,i))
            Write (meshout,99997) coor1(1,conn1(2,i)), coor1(2,conn1(2,i))
            Write (meshout,99997) coor1(1,conn1(3,i)), coor1(2,conn1(3,i))
            Write (meshout,99997) coor1(1,conn1(1,i)), coor1(2,conn1(1,i))
            Write (meshout,*)
          End Do
          Write (meshout,*)
        End If

        Do ktrans = 1, 2

!         Translation of the 1st domain to obtain the 2nd domain
!         KTRANS = 1 leading to a domains (4x2) overlapping
!         KTRANS = 2 leading to a domains partition

          If (ktrans==1) Then
            itrans = nvb1 - 4
            jtrans = nvb1 - 2
          Else
            itrans = nvb1
            jtrans = 0
          End If

          itype(1:ntrans) = (/1/)
          r_i = real(itrans,kind=nag_wp)/real(nvb1,kind=nag_wp)
          r_j = real(jtrans,kind=nag_wp)/real(nvb1,kind=nag_wp)
          trans(1,1:ntrans) = (/r_i/)
          trans(2,1:ntrans) = (/r_j/)
          itrace = 0

          ifail = 0
          Call d06daf(nv2,nedge2,nelt2,ntrans,itype,trans,coor1,edge1,conn1,   &
            coor2,edge2,conn2,itrace,rwork,lrwork,ifail)

          edge2(3,1:nedge2) = 2

!         Call to the restitching driver

          itrace = 0
          eps = 1.E-2_nag_wp

          ifail = 0
          Call d06dbf(eps,nv1,nelt1,nedge1,coor1,edge1,conn1,reft1,nv2,nelt2,  &
            nedge2,coor2,edge2,conn2,reft2,nv3,nelt3,nedge3,coor3,edge3,conn3, &
            reft3,itrace,iwork,liwork,ifail)

          If (pmesh) Then

!           Output the overlapping or partitioned mesh

            Write (nout,99998) nv3, nelt3, nedge3

            Do i = 1, nelt3
              Write (meshout,99997) coor3(1,conn3(1,i)), coor3(2,conn3(1,i))
              Write (meshout,99997) coor3(1,conn3(2,i)), coor3(2,conn3(2,i))
              Write (meshout,99997) coor3(1,conn3(3,i)), coor3(2,conn3(3,i))
              Write (meshout,99997) coor3(1,conn3(1,i)), coor3(2,conn3(1,i))
              Write (meshout,*)
            End Do
            Write (meshout,*)

            Do k = 1, nelt3
              Write (nout,99996) conn3(1:3,k), reft3(k)
            End Do

            Do k = 1, nedge3
              Write (nout,99998) edge3(1:3,k)
            End Do
          Else

            If (ktrans==1) Then
              Write (nout,*)                                                   &
                'The restitched mesh characteristics in the overlapping case'
            Else
              Write (nout,*)                                                   &
                'The restitched mesh characteristics in the partition case'
            End If

            Write (nout,99999) 'nv    =', nv3
            Write (nout,99999) 'nelt  =', nelt3
            Write (nout,99999) 'nedge =', nedge3
          End If
        End Do

99999   Format (1X,A,I6)
99998   Format (1X,3I10)
99997   Format (2(2X,E13.6))
99996   Format (1X,4I10)
      End Subroutine ex1
      Subroutine ex2

!       .. Use Statements ..
        Use nag_library, Only: d06abf, d06acf, d06baf, d06caf, d06daf, d06dbf, &
                               f16dnf, nag_wp
        Use d06dbfe_mod, Only: fbnd, meshout, nin, nout, pmesh
!       .. Local Scalars ..
        Real (Kind=nag_wp)             :: eps
        Integer                        :: i, ifail, itrace, j, k, liwork,      &
                                          lrwork, maxind, maxval, ncomp,       &
                                          nedge1, nedge2, nedge3, nedge4,      &
                                          nedge5, nedmx, nelt1, nelt2, nelt3,  &
                                          nelt4, nelt5, nlines, npropa, nqint, &
                                          ntrans, nv1, nv2, nv3, nv4, nv5,     &
                                          nvb1, nvb2, nvfix, nvint, nvmax,     &
                                          sdcrus
!       .. Local Arrays ..
        Real (Kind=nag_wp), Allocatable :: coor1(:,:), coor2(:,:), coor3(:,:), &
                                          coor4(:,:), coor5(:,:), coorch(:,:), &
                                          crus(:,:), rate(:), rwork(:),        &
                                          trans(:,:), weight(:)
        Real (Kind=nag_wp)             :: ruser(1)
        Integer, Allocatable           :: conn1(:,:), conn2(:,:), conn3(:,:),  &
                                          conn4(:,:), conn5(:,:), edge1(:,:),  &
                                          edge2(:,:), edge3(:,:), edge4(:,:),  &
                                          edge5(:,:), itype(:), iwork(:),      &
                                          lcomp(:), lined(:,:), nlcomp(:),     &
                                          numfix(:), reft1(:), reft2(:),       &
                                          reft3(:), reft4(:), reft5(:)
        Integer                        :: iuser(1)
!       .. Intrinsic Procedures ..
        Intrinsic                      :: abs
!       .. Executable Statements ..
        Write (nout,*)
        Write (nout,*) 'Example 2'
        Write (nout,*)

!       Skip headings in data file
        Read (nin,*)
        Read (nin,*)

!       Build and mesh two domains and rotate/translate second to create
!       third.

!       ----------------------------------------------
!       1st domain: Annulus with straight right edge.
!         First two points are end of straight edge.
!         The mesh for inner circle is defined by four NWSE points with mesh
!             points on the quarter-circle between each pair (fbnd, i=1).
!         The mesh for the incomplete outer circle  is defined by three NWS
!             points and the edge points, mesh points computed using fbnd,
!             i=2.

!       The number of lines (1+4+4).
        Read (nin,*) nlines, nvmax, nedmx
        Allocate (coor1(2,nvmax),edge1(3,nedmx),lined(4,nlines),lcomp(nlines), &
          coorch(2,nlines),rate(nlines))

!       Characteristic points of the boundary geometry.
        Read (nin,*) coorch(1,1:nlines)
        Read (nin,*) coorch(2,1:nlines)

!       The Lines of the boundary mesh
        Read (nin,*)(lined(1:4,j),rate(j),j=1,nlines)

!       Allocate workspace for d06baf.

!       sdcrus = 0 in this case.
        sdcrus = 0
        Do i = 1, nlines
          If (lined(4,i)<0) Then
            sdcrus = sdcrus + lined(1,i) - 2
          End If
        End Do
!       Get max(LINED(1,:)) for computing lrwork
        Call f16dnf(nlines,lined,4,maxind,maxval)
        liwork = 8*nlines + nvmax + 3*nedmx + 3*sdcrus
        lrwork = 2*(nlines+sdcrus) + 2*maxval*nlines
        Allocate (crus(2,sdcrus),rwork(lrwork),iwork(liwork))

!       The number of connected components (outer circle/edge and inner
!       circle)
        Read (nin,*) ncomp
        Allocate (nlcomp(ncomp))

!       Read the lines comprising each connected component
        j = 1
        Do i = 1, ncomp
          Read (nin,*) nlcomp(i)
          k = j + abs(nlcomp(i)) - 1
          Read (nin,*) lcomp(j:k)
          j = k + 1
        End Do

        itrace = 0
!       Call to the 2D boundary mesh generator
        ifail = 0
        Call d06baf(nlines,coorch,lined,fbnd,crus,sdcrus,rate,ncomp,nlcomp,    &
          lcomp,nvmax,nedmx,nvb1,coor1,nedge1,edge1,itrace,ruser,iuser,rwork,  &
          lrwork,iwork,liwork,ifail)

        Deallocate (rwork,iwork)

!       Generate mesh using Delaunay-Voronoi method

!       Initialize mesh control parameters and allocate workspace.
        itrace = 0
        npropa = 1
        nvint = 0
        lrwork = 12*nvmax + 15
        liwork = 6*nedge1 + 32*nvmax + 2*nvb1 + 78
        Allocate (weight(nvint),rwork(lrwork),iwork(liwork),                   &
          conn1(3,2*nvmax+5))

!       Call to the 2D Delaunay-Voronoi mesh generator
        ifail = 0
        Call d06abf(nvb1,nvint,nvmax,nedge1,edge1,nv1,nelt1,coor1,conn1,       &
          weight,npropa,itrace,rwork,lrwork,iwork,liwork,ifail)

        Deallocate (rwork,iwork)

!       Call the smoothing routine
        nvfix = 0
        nqint = 10
        lrwork = 2*nv1 + nelt1
        liwork = 8*nelt1 + 2*nv1
        Allocate (numfix(nvfix),rwork(lrwork),iwork(liwork))
        ifail = 0
        Call d06caf(nv1,nelt1,nedge1,coor1,edge1,conn1,nvfix,numfix,itrace,    &
          nqint,iwork,liwork,rwork,lrwork,ifail)

        Deallocate (rwork,iwork,coorch,lined,lcomp,rate,nlcomp,crus)

!       ----------------------------------------------
!       2nd domain: a rectangle (4 by 2) abutting straight edge of 1st domain.

        Read (nin,*) nlines
        Allocate (lined(4,nlines),lcomp(nlines),coorch(2,nlines),rate(nlines), &
          coor2(2,nvmax),edge2(3,nedmx))

!       Characteristic points of the boundary geometry
        Read (nin,*) coorch(1,1:nlines)
        Read (nin,*) coorch(2,1:nlines)

!       The Lines of the boundary mesh
        Read (nin,*)(lined(1:4,j),rate(j),j=1,nlines)

!       sdcrus = 0 again here.
        sdcrus = 0
        Do i = 1, nlines
          If (lined(4,i)<0) Then
            sdcrus = sdcrus + lined(1,i) - 2
          End If
        End Do

!       Generate initial mesh using Delaunay-Voronoi method

        liwork = 8*nlines + nvmax + 3*nedmx + 3*sdcrus
        Call f16dnf(nlines,lined,4,maxind,maxval)
        lrwork = 2*(nlines+sdcrus) + 2*maxval*nlines

        Allocate (crus(2,sdcrus),rwork(lrwork),iwork(liwork))

!       The number of connected components (1 rectangle)
        Read (nin,*) ncomp
        Allocate (nlcomp(ncomp))

!       Four lines of rectangle
        j = 1
        Do i = 1, ncomp
          Read (nin,*) nlcomp(i)
          k = j + abs(nlcomp(i)) - 1
          Read (nin,*) lcomp(j:k)
          j = k + 1
        End Do

        itrace = 0
!       Call to the 2D boundary mesh generator
        ifail = 0
        Call d06baf(nlines,coorch,lined,fbnd,crus,sdcrus,rate,ncomp,nlcomp,    &
          lcomp,nvmax,nedmx,nvb2,coor2,nedge2,edge2,itrace,ruser,iuser,rwork,  &
          lrwork,iwork,liwork,ifail)

        Deallocate (rwork,iwork,weight)

!       Remesh 2nd domain using the advancing front method

!       Initialize mesh control parameters
        itrace = 0
        nvint = 0
        lrwork = 12*nvmax + 30015
        liwork = 8*nedge2 + 53*nvmax + 2*nvb2 + 10078
        Allocate (weight(nvint),rwork(lrwork),iwork(liwork),                   &
          conn2(3,2*nvmax+5))

!       Call to the 2D Advancing front mesh generator
        ifail = 0
        Call d06acf(nvb2,nvint,nvmax,nedge2,edge2,nv2,nelt2,coor2,conn2,       &
          weight,itrace,rwork,lrwork,iwork,liwork,ifail)

        Deallocate (rwork,iwork)

!       ----------------------------------------------
!       3rd domain: rotation and translation of the 2nd domain mesh

        ntrans = 1
        lrwork = 12*ntrans
        Allocate (rwork(lrwork),itype(ntrans),trans(6,ntrans),coor3(2,nv2),    &
          edge3(3,nedge2),conn3(3,nelt2))

        itype(1:ntrans) = (/3/)
        trans(1,1:ntrans) = (/6.0_nag_wp/)
        trans(2,1:ntrans) = (/-1.0_nag_wp/)
        trans(3,1:ntrans) = (/-90.0_nag_wp/)
        itrace = 0

        ifail = 0
        Call d06daf(nv2,nedge2,nelt2,ntrans,itype,trans,coor2,edge2,conn2,     &
          coor3,edge3,conn3,itrace,rwork,lrwork,ifail)

        Deallocate (rwork)

!       ----------------------------------------------
!       Combine Meshes

        nv3 = nv2
        nelt3 = nelt2
        nedge3 = nedge2

        nv4 = nv1 + nv2
        nelt4 = nelt1 + nelt2
        nedge4 = nedge1 + nedge2
        liwork = 2*nv1 + 3*nv2 + nelt1 + nelt2 + nedge1 + nedge2 + 1024
        Allocate (iwork(liwork),coor4(2,nv4),edge4(3,nedge4),conn4(3,nelt4),   &
          reft4(nelt4),reft1(nelt1),reft2(nelt2))

!       Restitching of the mesh 1 and 2 to form the mesh 4
        reft1(1:nelt1) = 1
        reft2(1:nelt2) = 2
        eps = 1.E-3_nag_wp
        itrace = 0
        ifail = 0
        Call d06dbf(eps,nv1,nelt1,nedge1,coor1,edge1,conn1,reft1,nv2,nelt2,    &
          nedge2,coor2,edge2,conn2,reft2,nv4,nelt4,nedge4,coor4,edge4,conn4,   &
          reft4,itrace,iwork,liwork,ifail)

        Deallocate (iwork)

        nv5 = nv4 + nv3
        nelt5 = nelt4 + nelt3
        nedge5 = nedge4 + nedge3
        liwork = 2*nv4 + 3*nv3 + nelt4 + nelt3 + nedge4 + nedge3 + 1024
        Allocate (iwork(liwork),coor5(2,nv5),edge5(3,nedge5),conn5(3,nelt5),   &
          reft5(nelt5),reft3(nelt3))

!       Restitching of the mesh 3 and 4 to form the mesh 5
        reft3(1:nelt3) = 3
        itrace = 0
        ifail = 0
        Call d06dbf(eps,nv4,nelt4,nedge4,coor4,edge4,conn4,reft4,nv3,nelt3,    &
          nedge3,coor3,edge3,conn3,reft3,nv5,nelt5,nedge5,coor5,edge5,conn5,   &
          reft5,itrace,iwork,liwork,ifail)

        If (pmesh) Then
!         Output the mesh
          Do i = 1, nelt5
            Write (meshout,99997) coor5(1,conn5(1,i)), coor5(2,conn5(1,i))
            Write (meshout,99997) coor5(1,conn5(2,i)), coor5(2,conn5(2,i))
            Write (meshout,99997) coor5(1,conn5(3,i)), coor5(2,conn5(3,i))
            Write (meshout,99997) coor5(1,conn5(1,i)), coor5(2,conn5(1,i))
            Write (meshout,*)
          End Do
          Write (meshout,*)

          Write (nout,99998) nv5, nelt5, nedge5
          Do i = 1, nv5
            Write (nout,99997) coor5(1:2,i)
          End Do
          Do k = 1, nelt5
            Write (nout,99996) conn5(1,k), conn5(2,k), conn5(3,k), reft5(k)
          End Do
          Do k = 1, nedge5
            Write (nout,99998) edge5(1:3,k)
          End Do
        Else
          Write (nout,*) 'The restitched mesh characteristics'
          Write (nout,99999) 'nv    =', nv5
          Write (nout,99999) 'nelt  =', nelt5
          Write (nout,99999) 'nedge =', nedge5
        End If

99999   Format (1X,A,I6)
99998   Format (1X,3I10)
99997   Format (2(2X,E13.6))
99996   Format (1X,4I10)
      End Subroutine ex2
    End Program d06dbfe


e01aafe.f90

    Program e01aafe

!     E01AAF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: e01aaf, nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: x
      Integer                          :: i, j, k, n, n1, n2
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: a(:), b(:), c(:)
!     .. Executable Statements ..
      Write (nout,*) 'E01AAF Example Program Results'

!     Skip heading in data file
      Read (nin,*)

      Read (nin,*) n, x
      n1 = n + 1
      n2 = n*(n+1)/2
      Allocate (a(n1),b(n1),c(n2))

      Read (nin,*)(a(i),i=1,n1)
      Read (nin,*)(b(i),i=1,n1)

      Call e01aaf(a,b,c,n1,n2,n,x)

      Write (nout,*)
      Write (nout,*) 'Interpolated values'

      k = 1

      Do i = 1, n - 1
        Write (nout,99999)(c(j),j=k,k+n-i)
        k = k + n - i + 1
      End Do

      Write (nout,*)
      Write (nout,99998) 'Interpolation point = ', x
      Write (nout,*)
      Write (nout,99998) 'Function value at interpolation point = ', c(n2)

99999 Format (1X,6F12.5)
99998 Format (1X,A,F12.5)
    End Program e01aafe


e01abfe.f90

    Program e01abfe

!     E01ABF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: e01abf, nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: p
      Integer                          :: i, ifail, n, n1, n2, r
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: a(:), g(:)
!     .. Executable Statements ..
      Write (nout,*) 'E01ABF Example Program Results'

!     Skip heading in data file
      Read (nin,*)

      Read (nin,*) n, p
      n1 = 2*n
      n2 = n1 + 1
      Allocate (a(n1),g(n2))

      Read (nin,*)(a(i),i=1,n1)

      ifail = 0
      Call e01abf(n,p,a,g,n1,n2,ifail)

      Write (nout,*)

      Do r = 0, n - 1
        Write (nout,99999) 'Central differences order ', r, ' of Y0 =',        &
          g(2*r+1)
        Write (nout,99998) '                               Y1 =', g(2*r+2)
      End Do

      Write (nout,*)
      Write (nout,99998) 'Function value at interpolation point =', g(n2)

99999 Format (1X,A,I1,A,F12.5)
99998 Format (1X,A,F12.5)
    End Program e01abfe


e01aefe.f90

    Program e01aefe

!     E01AEF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: e01aef, f16dnf, nag_wp, x02ajf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: restol, xmax, xmin
      Integer                          :: i, ifail, ipmax, ires, itmax, itmin, &
                                          iy, j, k, liwrk, lwrk, m, n
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: a(:), wrk(:), x(:), y(:)
      Integer, Allocatable             :: ip(:), iwrk(:)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: abs, sum
!     .. Executable Statements ..
      Write (nout,*) 'E01AEF Example Program Results'

!     Skip heading in data file
      Read (nin,*)

      itmin = -1
      itmax = -1

      Read (nin,*) m, xmin, xmax
      liwrk = 2*(m+1)
      Allocate (ip(m),x(m),iwrk(liwrk))

      Read (nin,*)(ip(i),i=1,m)
      Read (nin,*)(x(i),i=1,m)

      n = m + sum(ip(1:m))

!     Get the maximum value of IP

      Call f16dnf(m,ip,1,k,ipmax)

      lwrk = 7*n + 5*ipmax + m + 7
      Allocate (a(n),y(n),wrk(lwrk))

      j = 0

      Do i = 1, m
        Read (nin,*)(y(k),k=j+1,j+ip(i)+1)
        j = j + ip(i) + 1
      End Do

      ifail = -1
      Call e01aef(m,xmin,xmax,x,y,ip,n,itmin,itmax,a,wrk,lwrk,iwrk,liwrk,      &
        ifail)

      Write (nout,*)

      Select Case (ifail)
      Case (0,4:)
        Write (nout,99999) 'Total number of interpolating conditions =', n
        Write (nout,*)
        Write (nout,*) 'Interpolating polynomial'
        Write (nout,*)
        Write (nout,*) '   i                a_i'

        Do i = 0, n - 1
          Write (nout,99998) i, a(i+1)
        End Do

        Write (nout,*)
        Write (nout,*) '  i   x_i    order(k)   y^(k)    Residual'

!       Residuals less than 100 times machine precision are not printed.
        restol = x02ajf()*100.0_nag_wp
        iy = 0
        ires = ipmax + 1

        Do i = 1, m

          iy = iy + 1
          ires = ires + 1
          If (abs(wrk(ires))>restol) Then
            Write (nout,99996) i, x(i), 0, y(iy), wrk(ires)
          Else
            Write (nout,99995) i, x(i), 0, y(iy), ' - '
          End If
          Do j = 1, ip(i)
            iy = iy + 1
            ires = ires + 1
            If (abs(wrk(ires))>restol) Then
              Write (nout,99997) j, y(iy), wrk(ires)
            Else
              Write (nout,99994) j, y(iy), ' - '
            End If
          End Do

        End Do

      End Select

99999 Format (1X,A,I4)
99998 Format (1X,I4,F20.4)
99997 Format (10X,I7,F11.1,E19.10)
99996 Format (1X,I3,F6.1,I7,F11.1,E19.10)
99995 Format (1X,I3,F6.1,I7,F11.1,A11)
99994 Format (10X,I7,F11.1,A11)
    End Program e01aefe


e01bafe.f90

    Program e01bafe

!     E01BAF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: e01baf, e02bbf, nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: m = 7, nout = 6
      Integer, Parameter               :: lck = m + 4
      Integer, Parameter               :: lwrk = 6*m + 16
      Real (Kind=nag_wp), Parameter    :: x(m) = (/0.0E0_nag_wp,0.2E0_nag_wp,  &
                                          0.4E0_nag_wp,0.6E0_nag_wp,           &
                                          0.75E0_nag_wp,0.9E0_nag_wp,          &
                                          1.0E0_nag_wp/)
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: fit, xarg
      Integer                          :: ifail, j, r
!     .. Local Arrays ..
      Real (Kind=nag_wp)               :: c(lck), lamda(lck), wrk(lwrk), y(m)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: exp
!     .. Executable Statements ..
      Write (nout,*) 'E01BAF Example Program Results'

      y(1:m) = exp(x(1:m))

      ifail = 0
      Call e01baf(m,x,y,lamda,c,lck,wrk,lwrk,ifail)

      Write (nout,*)
      Write (nout,*) '   J    Knot LAMDA(J+2)   B-spline coeff C(J)'
      Write (nout,*)

      j = 1
      Write (nout,99998) j, c(1)

      Do j = 2, m - 1
        Write (nout,99999) j, lamda(j+2), c(j)
      End Do

      Write (nout,99998) m, c(m)
      Write (nout,*)
      Write (nout,*)                                                           &
        '   R        Abscissa            Ordinate             Spline'
      Write (nout,*)

      Do r = 1, m

        ifail = 0
        Call e02bbf(m+4,lamda,c,x(r),fit,ifail)

        Write (nout,99999) r, x(r), y(r), fit

        If (r<m) Then
          xarg = 0.5E0_nag_wp*(x(r)+x(r+1))

          ifail = 0
          Call e02bbf(m+4,lamda,c,xarg,fit,ifail)

          Write (nout,99997) xarg, fit
        End If

      End Do

99999 Format (1X,I4,F15.4,2F20.4)
99998 Format (1X,I4,F35.4)
99997 Format (1X,F19.4,F40.4)
    End Program e01bafe


e01befe.f90

    Program e01befe

!     E01BEF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: e01bef, e01bff, nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: step
      Integer                          :: i, ifail, m, n, r
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: d(:), f(:), pf(:), px(:), x(:)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: min, real
!     .. Executable Statements ..
      Write (nout,*) 'E01BEF Example Program Results'

!     Skip heading in data file
      Read (nin,*)

      Read (nin,*) n
      Allocate (d(n),f(n),x(n))

      Do r = 1, n
        Read (nin,*) x(r), f(r)
      End Do

      ifail = 0
      Call e01bef(n,x,f,d,ifail)

      Read (nin,*) m
      Allocate (pf(m),px(m))

!     Compute M equally spaced points from X(1) to X(N).

      step = (x(n)-x(1))/real(m-1,kind=nag_wp)

      Do i = 1, m
        px(i) = min(x(1)+real(i-1,kind=nag_wp)*step,x(n))
      End Do

      ifail = 0
      Call e01bff(n,x,f,d,m,px,pf,ifail)

      Write (nout,*)
      Write (nout,*) '                Interpolated'
      Write (nout,*) '     Abscissa          Value'

      Do i = 1, m
        Write (nout,99999) px(i), pf(i)
      End Do

99999 Format (1X,F13.4,2X,F13.4)
    End Program e01befe


e01bffe.f90

    Program e01bffe

!     E01BFF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: e01bff, nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: step
      Integer                          :: i, ifail, m, n, r
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: d(:), f(:), pf(:), px(:), x(:)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: min, real
!     .. Executable Statements ..
      Write (nout,*) 'E01BFF Example Program Results'

!     Skip heading in data file
      Read (nin,*)

      Read (nin,*) n
      Allocate (d(n),f(n),x(n))

      Do r = 1, n
        Read (nin,*) x(r), f(r), d(r)
      End Do

      Read (nin,*) m
      Allocate (pf(m),px(m))

!     Compute M equally spaced points from X(1) to X(N).

      step = (x(n)-x(1))/real(m-1,kind=nag_wp)

      Do i = 1, m
        px(i) = min(x(1)+real(i-1,kind=nag_wp)*step,x(n))
      End Do

      ifail = 0
      Call e01bff(n,x,f,d,m,px,pf,ifail)

      Write (nout,*)
      Write (nout,*) '                  Interpolated'
      Write (nout,*) '       Abscissa          Value'

      Do i = 1, m
        Write (nout,99999) px(i), pf(i)
      End Do

99999 Format (1X,3F15.4)
    End Program e01bffe


e01bgfe.f90

    Program e01bgfe

!     E01BGF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: e01bgf, nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: step
      Integer                          :: i, ifail, m, n, r
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: d(:), f(:), pd(:), pf(:), px(:),     &
                                          x(:)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: min, real
!     .. Executable Statements ..
      Write (nout,*) 'E01BGF Example Program Results'

!     Skip heading in data file
      Read (nin,*)

      Read (nin,*) n
      Allocate (d(n),f(n),x(n))

      Do r = 1, n
        Read (nin,*) x(r), f(r), d(r)
      End Do

      Read (nin,*) m
      Allocate (pd(m),pf(m),px(m))

!     Compute M equally spaced points from X(1) to X(N).

      step = (x(n)-x(1))/real(m-1,kind=nag_wp)

      Do i = 1, m
        px(i) = min(x(1)+real(i-1,kind=nag_wp)*step,x(n))
      End Do

      ifail = 0
      Call e01bgf(n,x,f,d,m,px,pf,pd,ifail)

      Write (nout,*)
      Write (nout,*) '                  Interpolated   Interpolated'
      Write (nout,*) '       Abscissa          Value     Derivative'

      Do i = 1, m
        Write (nout,99999) px(i), pf(i), pd(i)
      End Do

99999 Format (1X,2F15.4,1P,E15.3)
    End Program e01bgfe


e01bhfe.f90

    Program e01bhfe

!     E01BHF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: e01bhf, nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: a, b, pint
      Integer                          :: ifail, ioerr, n, r
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: d(:), f(:), x(:)
!     .. Executable Statements ..
      Write (nout,*) 'E01BHF Example Program Results'

!     Skip heading in data file
      Read (nin,*)

      Read (nin,*) n
      Allocate (d(n),f(n),x(n))

      Do r = 1, n
        Read (nin,*) x(r), f(r), d(r)
      End Do

      Write (nout,*)
      Write (nout,*) '                               Integral'
      Write (nout,*) '          A            B     over (A,B)'

data: Do
        Read (nin,*,Iostat=ioerr) a, b

        If (ioerr<0) Then
          Exit data
        End If

        ifail = 0
        Call e01bhf(n,x,f,d,a,b,pint,ifail)

        Write (nout,99999) a, b, pint
      End Do data

99999 Format (1X,3F13.4)
    End Program e01bhfe


e01dafe.f90

    Program e01dafe

!     E01DAF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: e01daf, e02dff, nag_wp, x04cbf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: indent = 0, ncols = 80, nin = 5,     &
                                          nout = 6
      Character (1), Parameter         :: chlabel = 'C', diag = 'N',           &
                                          matrix = 'G'
      Character (4), Parameter         :: form = 'F8.3'
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: step, xhi, xlo, yhi, ylo
      Integer                          :: i, ifail, j, liwrk, lwrk, mx, my,    &
                                          nx, ny, px, py
      Character (54)                   :: title
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: c(:), f(:,:), fg(:), lamda(:),       &
                                          mu(:), tx(:), ty(:), wrk(:), x(:),   &
                                          y(:)
      Integer, Allocatable             :: iwrk(:)
      Character (10), Allocatable      :: clabs(:), rlabs(:)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: min, real
!     .. Executable Statements ..
      Write (nout,*) 'E01DAF Example Program Results'

!     Skip heading in data file
      Read (nin,*)

!     Read the number of X points, MX, and the values of the
!     X co-ordinates.

      Read (nin,*) mx
      Allocate (x(mx),lamda(mx+4))

      Read (nin,*) x(1:mx)

!     Read the number of Y points, MY, and the values of the
!     Y co-ordinates.

      Read (nin,*) my
      Allocate (y(my),mu(my+4),c(mx*my),f(my,mx),wrk((mx+6)*(my+6)))

      Read (nin,*) y(1:my)

!     Read the function values at the grid points.

      Do j = 1, my
        Read (nin,*) f(j,1:mx)
      End Do

!     Generate the (X,Y,F) interpolating bicubic B-spline.

      ifail = 0
      Call e01daf(mx,my,x,y,f,px,py,lamda,mu,c,wrk,ifail)

!     Print the knot sets, LAMDA and MU.

      Write (nout,*)
      Write (nout,*) '               I   Knot LAMDA(I)      J     Knot MU(J)'
      Write (nout,99997)(j,lamda(j),j,mu(j),j=4,min(px,py)-3)
      If (px>py) Then
        Write (nout,99997)(j,lamda(j),j=py-2,px-3)
      Else If (px<py) Then
        Write (nout,99996)(j,mu(j),j=px-2,py-3)
      End If

!     Print the spline coefficients.

      Write (nout,*)
      Write (nout,*) 'The B-Spline coefficients:'
      Write (nout,99999)(c(i),i=1,mx*my)
      Write (nout,*)
      Flush (nout)

!     Evaluate the spline on a regular rectangular grid at nx*ny points
!     over the domain [xlo,xhi] x [ylo,yhi].

      Deallocate (wrk)

      Read (nin,*) nx, xlo, xhi
      Read (nin,*) ny, ylo, yhi
      lwrk = min(4*nx+px,4*ny+py)

      If (4*nx+px>4*ny+py) Then
        liwrk = ny + py - 4
      Else
        liwrk = nx + px - 4
      End If

      Allocate (tx(nx),ty(ny),fg(nx*ny),wrk(lwrk),iwrk(liwrk))

!     Generate nx/ny equispaced x/y co-ordinates.

      step = (xhi-xlo)/real(nx-1,kind=nag_wp)
      tx(1) = xlo
      Do i = 2, nx - 1
        tx(i) = tx(i-1) + step
      End Do
      tx(nx) = xhi

      step = (yhi-ylo)/real(ny-1,kind=nag_wp)
      ty(1) = ylo
      Do i = 2, ny - 1
        ty(i) = ty(i-1) + step
      End Do
      ty(ny) = yhi

!     Evaluate the spline.
      ifail = 0
      Call e02dff(nx,ny,px,py,tx,ty,lamda,mu,c,fg,wrk,lwrk,iwrk,liwrk,ifail)

!     Generate row and column labels and title for printing results.
      Allocate (clabs(nx),rlabs(ny))
      Do i = 1, nx
        Write (clabs(i),99998) tx(i)
      End Do
      Do i = 1, ny
        Write (rlabs(i),99998) ty(i)
        Flush (nout)
      End Do
      title = 'Spline evaluated on a regular mesh (X across, Y down):'

!     Print the results.
      ifail = 0
      Call x04cbf(matrix,diag,ny,nx,fg,ny,form,title,chlabel,rlabs,chlabel,    &
        clabs,ncols,indent,ifail)

99999 Format (1X,8F9.4)
99998 Format (F5.2)
99997 Format (1X,I16,F12.4,I11,F12.4)
99996 Format (1X,I39,F12.4)
    End Program e01dafe


e01eafe.f90

    Program e01eafe

!     E01EAF Example Program Text
!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: e01eaf, e01ebf, nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
      Logical, Parameter               :: pr_tr = .False.
!     .. Local Scalars ..
      Integer                          :: i, ifail, m, n
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: f(:), pf(:), px(:), py(:), x(:),     &
                                          y(:)
      Integer, Allocatable             :: triang(:)
!     .. Executable Statements ..

      Write (nout,*) 'E01EAF Example Program Results'

!     Skip heading in data file
      Read (nin,*)

      Read (nin,*) n
      Allocate (x(n),y(n),f(n),triang(7*n))
      Read (nin,*)(x(i),y(i),f(i),i=1,n)

!     Triangulate data
      ifail = 0
      Call e01eaf(n,x,y,triang,ifail)

      Read (nin,*) m
      Allocate (px(m),py(m),pf(m))
      Read (nin,*)(px(i),py(i),i=1,m)

!     Interpolate data
      ifail = 0
      Call e01ebf(m,n,x,y,f,triang,px,py,pf,ifail)

!     Display results
      Write (nout,*)
      Write (nout,99999) 'px', 'py', 'Interpolated Value'
      Write (nout,99998)(px(i),py(i),pf(i),i=1,m)

      If (pr_tr) Then
        Call print_triang
      End If

99999 Format (2X,A4,4X,A4,4X,A19)
99998 Format (1X,F7.4,1X,F7.4,8X,F7.4)

    Contains
      Subroutine print_triang

!       .. Implicit None Statement ..
        Implicit None
!       .. Local Scalars ..
        Integer                        :: i_k, j, j_k, k
!       .. Executable Statements ..

!       Print a sequence of unique line segments for plotting triangulation
        Write (nout,*)
        Write (nout,*) '  Triangulation as a set of line segments'
        Write (nout,*)
        j_k = 0
        Do k = 1, n
          i_k = j_k + 1
          j_k = triang(6*n+k)
          Do j = i_k, j_k
            If (triang(j)>k) Then
              Write (nout,99999) x(k), y(k)
              Write (nout,99999) x(triang(j)), y(triang(j))
              Write (nout,*)
            End If
          End Do
        End Do
        Return
99999   Format (1X,F7.4,1X,F7.4)
      End Subroutine print_triang

    End Program e01eafe


e01rafe.f90

    Program e01rafe

!     E01RAF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: e01raf, nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: n = 5, nin = 5, nout = 6
!     .. Local Scalars ..
      Integer                          :: i, ifail, m
!     .. Local Arrays ..
      Real (Kind=nag_wp)               :: a(n), f(n), u(n), x(n)
      Integer                          :: iw(n)
!     .. Executable Statements ..
      Write (nout,*) 'E01RAF Example Program Results'

!     Skip heading in data file
      Read (nin,*)

      Read (nin,*)(x(i),i=1,n)
      Read (nin,*)(f(i),i=1,n)

      ifail = 0
      Call e01raf(n,x,f,m,a,u,iw,ifail)

      Write (nout,*)
      Write (nout,*) 'The values of U(J) are'
      Write (nout,99999)(u(i),i=1,m-1)
      Write (nout,*)
      Write (nout,*) 'The Thiele coefficients A(J) are'
      Write (nout,99999)(a(i),i=1,m)

99999 Format (1X,1P,4E12.4)
    End Program e01rafe


e01rbfe.f90

    Program e01rbfe

!     E01RBF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: e01rbf, nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: m = 4, nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: f, x
      Integer                          :: i, ifail
!     .. Local Arrays ..
      Real (Kind=nag_wp)               :: a(m), u(m)
!     .. Executable Statements ..
      Write (nout,*) 'E01RBF Example Program Results'

!     Skip heading in data file
      Read (nin,*)

      Read (nin,*)(a(i),i=1,m)
      Read (nin,*)(u(i),i=1,m-1)
      Read (nin,*) x

      ifail = 0
      Call e01rbf(m,a,u,x,f,ifail)

      Write (nout,*)
      Write (nout,99999) 'X =', x
      Write (nout,*)
      Write (nout,99999) 'The value of R(X) is ', f

99999 Format (1X,A,1P,E12.4)
    End Program e01rbfe


e01safe.f90

    Program e01safe

!     E01SAF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: e01saf, e01sbf, nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: hx, hy, xhi, xlo, yhi, ylo
      Integer                          :: i, ifail, j, m, nx, ny
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: f(:), grads(:,:), pf(:), px(:),      &
                                          py(:), x(:), y(:)
      Integer, Allocatable             :: triang(:)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: real
!     .. Executable Statements ..
      Write (nout,*) 'E01SAF Example Program Results'

!     Skip heading in data file
      Read (nin,*)

      Read (nin,*) m
      Allocate (x(m),y(m),f(m),grads(2,m),triang(7*m))

      Do i = 1, m
        Read (nin,*) x(i), y(i), f(i)
      End Do

!     Generate the triangulation and gradients.

      ifail = 0
      Call e01saf(m,x,y,f,triang,grads,ifail)

!     Evaluate the interpolant on a rectangular grid at NX*NY
!     points over the domain (XLO to XHI) x (YLO to YHI).

      Read (nin,*) nx, xlo, xhi
      Read (nin,*) ny, ylo, yhi
      Allocate (px(nx),py(ny),pf(nx))

      hx = (xhi-xlo)/real(nx-1,kind=nag_wp)
      px(1) = xlo

      Do i = 2, nx
        px(i) = px(i-1) + hx
      End Do

      hy = (yhi-ylo)/real(ny-1,kind=nag_wp)
      py(1) = ylo

      Do i = 2, ny
        py(i) = py(i-1) + hy
      End Do

      Write (nout,*)
      Write (nout,99999) '          X', (px(i),i=1,nx)
      Write (nout,*) '     Y'

      Do i = ny, 1, -1

        Do j = 1, nx

          ifail = 0
          Call e01sbf(m,x,y,f,triang,grads,px(j),py(i),pf(j),ifail)

        End Do

        Write (nout,99998) py(i), (pf(j),j=1,nx)
      End Do

99999 Format (1X,A,7F8.2)
99998 Format (1X,F8.2,3X,7F8.2)
    End Program e01safe


e01sgfe.f90

    Program e01sgfe

!     E01SGF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: e01sgf, e01shf, nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Integer                          :: i, ifail, liq, lrq, m, n, nq, nw
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: f(:), q(:), qx(:), qy(:), rq(:),     &
                                          u(:), v(:), x(:), y(:)
      Integer, Allocatable             :: iq(:)
!     .. Executable Statements ..
      Write (nout,*) 'E01SGF Example Program Results'

!     Skip heading in data file
      Read (nin,*)

!     Input the number of data points

      Read (nin,*) m
      liq = 2*m + 1
      lrq = 6*m + 5
      Allocate (x(m),y(m),f(m),iq(liq),rq(lrq))

      Do i = 1, m
        Read (nin,*) x(i), y(i), f(i)
      End Do

!     Generate the interpolant.

      nq = 0
      nw = 0

      ifail = 0
      Call e01sgf(m,x,y,f,nw,nq,iq,liq,rq,lrq,ifail)

!     Input the number of evaluation points.

      Read (nin,*) n
      Allocate (u(n),v(n),q(n),qx(n),qy(n))

      Do i = 1, n
        Read (nin,*) u(i), v(i)
      End Do

!     Evaluate the interpolant using E01SHF.

      ifail = 0
      Call e01shf(m,x,y,f,iq,liq,rq,lrq,n,u,v,q,qx,qy,ifail)

      Write (nout,*)
      Write (nout,*) '     I      U(I)      V(I)      Q(I)'

      Do i = 1, n
        Write (nout,99999) i, u(i), v(i), q(i)
      End Do

99999 Format (1X,I6,3F10.2)
    End Program e01sgfe


e01tgfe.f90

    Program e01tgfe

!     E01TGF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: e01tgf, e01thf, nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Integer                          :: i, ifail, liq, lrq, m, n, nq, nw
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: f(:), q(:), qx(:), qy(:), qz(:),     &
                                          rq(:), u(:), v(:), w(:), x(:), y(:), &
                                          z(:)
      Integer, Allocatable             :: iq(:)
!     .. Executable Statements ..
      Write (nout,*) 'E01TGF Example Program Results'

!     Skip heading in data file
      Read (nin,*)

!     Input the number of nodes.

      Read (nin,*) m
      liq = 2*m + 1
      lrq = 10*m + 7
      Allocate (x(m),y(m),z(m),f(m),iq(liq),rq(lrq))

      Do i = 1, m
        Read (nin,*) x(i), y(i), z(i), f(i)
      End Do

!     Generate the interpolant.

      nq = 0
      nw = 0

      ifail = 0
      Call e01tgf(m,x,y,z,f,nw,nq,iq,liq,rq,lrq,ifail)

!     Input the number of evaluation points.

      Read (nin,*) n
      Allocate (u(n),v(n),w(n),q(n),qx(n),qy(n),qz(n))

!     Input the evaluation points.

      Do i = 1, n
        Read (nin,*) u(i), v(i), w(i)
      End Do

!     Evaluate the interpolant using E01THF.

      ifail = -0
      Call e01thf(m,x,y,z,f,iq,liq,rq,lrq,n,u,v,w,q,qx,qy,qz,ifail)

      Write (nout,*)
      Write (nout,*) '     I     U(I)      V(I)      W(I)      Q(I)'

      Do i = 1, n
        Write (nout,99999) i, u(i), v(i), w(i), q(i)
      End Do

99999 Format (1X,I6,4F10.4)
    End Program e01tgfe


e01tkfe.f90

    Program e01tkfe

!     E01TKF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: e01tkf, e01tlf, nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Integer                          :: i, ifail, liq, lrq, m, n, nq, nw
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: f(:), q(:), qx(:,:), rq(:), x(:,:),  &
                                          xe(:,:)
      Integer, Allocatable             :: iq(:)
!     .. Executable Statements ..
      Write (nout,*) 'E01TKF Example Program Results'

!     Skip heading in data file
      Read (nin,*)

!     Input the number of nodes.
      Read (nin,*) m
      liq = 2*m + 1
      lrq = 15*m + 9
      Allocate (x(4,m),f(m),iq(liq),rq(lrq))

!     Input the data points X and F.
      Do i = 1, m
        Read (nin,*) x(1:4,i), f(i)
      End Do

!     Generate the interpolant.
      nq = 0
      nw = 0

      ifail = 0
      Call e01tkf(m,x,f,nw,nq,iq,rq,ifail)

!     Input the number of evaluation points.
      Read (nin,*) n
      Allocate (xe(4,n),q(n),qx(4,n))

!     Input the evaluation points.
      Do i = 1, n
        Read (nin,*) xe(1:4,i)
      End Do

!     Evaluate the interpolant using E01TLF.
      ifail = 1
      Call e01tlf(m,x,f,iq,rq,n,xe,q,qx,ifail)
      If (ifail==0 .Or. ifail==3) Then
        If (ifail==3) Then
          Write (nout,*) 'Some values below have been extrapolated'
          Write (nout,*)
        End If
        Write (nout,99998) 'Interpolated Evaluation Points', 'Values'
        Write (nout,99997)
        Write (nout,99996)(i,i=1,4)
        Write (nout,99997)
        Do i = 1, n
          Write (nout,99999) i, xe(1:4,i), q(i)
        End Do
      Else
        Write (nout,99995) 'Evaluation routine returned with IFAIL = ', ifail
      End If

99999 Format (1X,I4,1X,4F10.4,1X,F10.4)
99998 Format (/,4X,'   |',5X,A31,5X,'|',A7)
99997 Format (4X,'---|',41('-'),'+',8('-'))
99996 Format (4X,'I  |',4(2X,'XE(I,',I1,')',1X),1X,'|',2X,'Q(I)')
99995 Format (1X,A,I4)
    End Program e01tkfe


e01tlfe.f90

!   E01TLF Example Program Text
!   Mark 26 Release. NAG Copyright 2016.

    Module e01tlfe_mod

!     E01TLF Example Program Module:
!            Parameters and User-defined Routines

!     .. Use Statements ..
      Use nag_library, Only: nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Accessibility Statements ..
      Private
      Public                           :: funct
!     .. Parameters ..
      Real (Kind=nag_wp), Parameter    :: one = 1.0_nag_wp
      Real (Kind=nag_wp), Parameter    :: six = 6.0_nag_wp
      Real (Kind=nag_wp), Parameter    :: three = 3.0_nag_wp
      Integer, Parameter, Public       :: nin = 5, nout = 6
    Contains
      Subroutine funct(m,x,f)
!       This subroutine evaluates the 4D function funct.

!       .. Scalar Arguments ..
        Integer, Intent (In)           :: m
!       .. Array Arguments ..
        Real (Kind=nag_wp), Intent (Out) :: f(m)
        Real (Kind=nag_wp), Intent (In) :: x(4,m)
!       .. Local Scalars ..
        Real (Kind=nag_wp)             :: c1, c2, c3, c4
        Integer                        :: i
!       .. Intrinsic Procedures ..
        Intrinsic                      :: cos
!       .. Executable Statements ..
        Do i = 1, m
          c1 = cos(six*x(1,i))
          c2 = cos(six*x(2,i))
          c3 = six + six*(three*x(3,i)-one)**2
          c4 = 1.25_nag_wp + cos(5.4_nag_wp*x(4,i))
          f(i) = c4*c1*c2/c3
        End Do
        Return
      End Subroutine funct
    End Module e01tlfe_mod
    Program e01tlfe

!     E01TLF Example Main Program

!     .. Use Statements ..
      Use nag_library, Only: e01tkf, e01tlf, g05kff, g05saf, nag_wp
      Use e01tlfe_mod, Only: funct, nin, nout
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: lseed = 1
!     .. Local Scalars ..
      Integer                          :: genid, i, ifail, liq, lrq, lstate,   &
                                          m, n, nq, nw, subid
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: f(:), fun(:), q(:), qx(:,:), rq(:),  &
                                          x(:,:), xe(:,:)
      Integer, Allocatable             :: iq(:), state(:)
      Integer                          :: seed(lseed), seed2(lseed)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: abs
!     .. Executable Statements ..
      Write (nout,*) 'E01TLF Example Program Results'

!     Skip heading in data file
      Read (nin,*)

!     Read in the base generator information and seeds
      Read (nin,*) genid, subid, seed(1), seed2(1)

!     Initial call to initializer to get size of STATE array
      lstate = 0
      Allocate (state(lstate))
      ifail = 0
      Call g05kff(genid,subid,seed,lseed,state,lstate,ifail)

!     Reallocate STATE
      Deallocate (state)
      Allocate (state(lstate))

!     Initialize the generator to a repeatable sequence
      ifail = 0
      Call g05kff(genid,subid,seed,lseed,state,lstate,ifail)

!     Input the number of nodes.
      Read (nin,*) m
      liq = 2*m + 1
      lrq = 15*m + 9
      Allocate (x(4,m),f(m),iq(liq),rq(lrq))

!     Generate the data points X
      ifail = 0
      Call g05saf(4*m,state,x,ifail)

!     Evaluate F
      Call funct(m,x,f)

!     Generate the interpolant using E01TKF.
      nq = 0
      nw = 0

      ifail = 0
      Call e01tkf(m,x,f,nw,nq,iq,rq,ifail)

!     Input the number of evaluation points.
      Read (nin,*) n
      Allocate (xe(4,n),q(n),qx(4,n),fun(n))

!     Generate repeatable evaluation points.
      ifail = 0
      Call g05kff(genid,subid,seed2,lseed,state,lstate,ifail)
      ifail = 0
      Call g05saf(4*n,state,xe,ifail)

!     Evaluate the interpolant.
      ifail = 0
      Call e01tlf(m,x,f,iq,rq,n,xe,q,qx,ifail)

      Write (nout,99997)
      Write (nout,99998)
      Call funct(n,xe,fun)
      Write (nout,99999)(i,fun(i),q(i),abs(fun(i)-q(i)),i=1,n)

99999 Format (1X,I4,1X,2F10.4,2X,F10.4)
99998 Format (4X,'---+',20('-'),'+',11('-'),'+')
99997 Format (/,4X,'I  |',2X,'F(I)',6X,'Q(I)',4X,'|',1X,'|F(I)-Q(I)|')
    End Program e01tlfe


e01tmfe.f90

    Program e01tmfe

!     E01TMF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: e01tmf, e01tnf, nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Integer                          :: i, ifail, liq, lrq, m, n, nq, nw
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: f(:), q(:), qx(:,:), rq(:), x(:,:),  &
                                          xe(:,:)
      Integer, Allocatable             :: iq(:)
!     .. Executable Statements ..
      Write (nout,*) 'E01TMF Example Program Results'

!     Skip heading in data file
      Read (nin,*)

!     Input the number of nodes.
      Read (nin,*) m
      liq = 2*m + 1
      lrq = 21*m + 11
      Allocate (x(5,m),f(m),iq(liq),rq(lrq))

!     Input the data points X and F.
      Do i = 1, m
        Read (nin,*) x(1:5,i), f(i)
      End Do

!     Generate the interpolant.
      nq = 0
      nw = 0

      ifail = 0
      Call e01tmf(m,x,f,nw,nq,iq,rq,ifail)

!     Input the number of evaluation points.
      Read (nin,*) n
      Allocate (xe(5,n),q(n),qx(5,n))

!     Input the evaluation points.
      Do i = 1, n
        Read (nin,*) xe(1:5,i)
      End Do

!     Evaluate the interpolant using E01TNF.
      ifail = 0
      Call e01tnf(m,x,f,iq,rq,n,xe,q,qx,ifail)

      Write (nout,99998) 'Interpolated Evaluation Points', 'Values'
      Write (nout,99997)
      Write (nout,99996)(i,i=1,5)
      Write (nout,99997)
      Write (nout,99999)(i,xe(1:5,i),q(i),i=1,n)

99999 Format (1X,I4,1X,6F10.4)
99998 Format (/,4X,'   |',10X,A31,10X,'|',A7)
99997 Format (4X,'---|',51('-'),'+',7('-'))
99996 Format (4X,'I  |',5(2X,'XE(',I1,',I)',1X),1X,'|',3X,'Q(I)')
    End Program e01tmfe


e01tnfe.f90

!   E01TNF Example Program Text
!   Mark 26 Release. NAG Copyright 2016.

    Module e01tnfe_mod

!     E01TNF Example Program Module:
!            Parameters and User-defined Routines

!     .. Use Statements ..
      Use nag_library, Only: nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Accessibility Statements ..
      Private
      Public                           :: funct
!     .. Parameters ..
      Real (Kind=nag_wp), Parameter    :: one = 1.0_nag_wp
      Real (Kind=nag_wp), Parameter    :: six = 6.0_nag_wp
      Real (Kind=nag_wp), Parameter    :: three = 3.0_nag_wp
      Integer, Parameter, Public       :: nin = 5, nout = 6
    Contains
      Function funct(x)
!       This function evaluates the 5D function funct.

!       .. Function Return Value ..
        Real (Kind=nag_wp)             :: funct
!       .. Array Arguments ..
        Real (Kind=nag_wp), Intent (In) :: x(5)
!       .. Intrinsic Procedures ..
        Intrinsic                      :: cos
!       .. Executable Statements ..
        funct = ((1.25_nag_wp+cos(5.4_nag_wp*x(5)))*cos(six*x(1))*cos(six*x(2) &
          )*cos(six*x(3)))/(six+six*(three*x(4)-one)**2)

        Return
      End Function funct
    End Module e01tnfe_mod
    Program e01tnfe

!     E01TNF Example Main Program

!     .. Use Statements ..
      Use nag_library, Only: e01tmf, e01tnf, g05kff, g05saf, nag_wp
      Use e01tnfe_mod, Only: funct, nin, nout
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: lseed = 1
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: fun
      Integer                          :: genid, i, ifail, liq, lrq, lstate,   &
                                          m, n, nq, nw, subid
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: f(:), q(:), qx(:,:), rq(:), x(:,:),  &
                                          xe(:,:)
      Integer, Allocatable             :: iq(:), state(:)
      Integer                          :: seed(lseed), seed2(lseed)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: abs
!     .. Executable Statements ..
      Write (nout,*) 'E01TNF Example Program Results'

!     Skip heading in data file
      Read (nin,*)

!     Read in the base generator information and seeds
      Read (nin,*) genid, subid, seed(1), seed2(1)

!     Initial call to initializer to get size of STATE array
      lstate = 0
      Allocate (state(lstate))
      ifail = 0
      Call g05kff(genid,subid,seed,lseed,state,lstate,ifail)

!     Reallocate STATE
      Deallocate (state)
      Allocate (state(lstate))

!     Initialize the generator to a repeatable sequence
      ifail = 0
      Call g05kff(genid,subid,seed,lseed,state,lstate,ifail)

!     Input the number of nodes.
      Read (nin,*) m
      liq = 2*m + 1
      lrq = 21*m + 11
      Allocate (x(5,m),f(m),iq(liq),rq(lrq))

!     Generate the data points X
      ifail = 0
      Call g05saf(5*m,state,x,ifail)

!     Evaluate F
      Do i = 1, m
        f(i) = funct(x(1,i))
      End Do

!     Generate the interpolant using E01TMF.
      nq = 0
      nw = 0

      ifail = 0
      Call e01tmf(m,x,f,nw,nq,iq,rq,ifail)

!     Input the number of evaluation points.
      Read (nin,*) n
      Allocate (xe(5,n),q(n),qx(5,n))

!     Generate repeatable evaluation points.
      ifail = 0
      Call g05kff(genid,subid,seed2,lseed,state,lstate,ifail)
      ifail = 0
      Call g05saf(5*n,state,xe,ifail)

!     Evaluate the interpolant.
      ifail = 0
      Call e01tnf(m,x,f,iq,rq,n,xe,q,qx,ifail)

      Write (nout,99997)
      Write (nout,99998)
      Do i = 1, n
        fun = funct(xe(1,i))
        Write (nout,99999) i, fun, q(i), abs(fun-q(i))
      End Do

99999 Format (1X,I4,1X,3F10.4)
99998 Format (4X,'---|',20('-'),'+',15('-'))
99997 Format (/,4X,'I  |',2X,'F(I)',6X,'Q(I)',4X,'|',1X,'|F(I)-Q(I)|')
    End Program e01tnfe


e01zmfe.f90

    Program e01zmfe

!     E01ZMF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: e01zmf, e01znf, nag_wp, x04caf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Integer                          :: d, i, ifail, liq, lrq, m, n, nq, nw
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: f(:), q(:), qx(:,:), rq(:), x(:,:),  &
                                          xe(:,:)
      Integer, Allocatable             :: iq(:)
!     .. Executable Statements ..
      Write (nout,*) 'E01ZMF Example Program Results'

!     Skip heading in data file
      Read (nin,*)

!     Input the number of nodes.
      Read (nin,*) d, m
      liq = 2*m + 1
      lrq = (d+1)*(d+2)/2*m + 2*d + 1
      Allocate (x(d,m),f(m),iq(liq),rq(lrq))

!     Input the data points X and F.
      Do i = 1, m
        Read (nin,*) x(1:d,i), f(i)
      End Do

!     Generate the interpolant.
      nq = 0
      nw = 0

      ifail = 0
      Call e01zmf(d,m,x,f,nw,nq,iq,rq,ifail)

!     Input the number of evaluation points.
      Read (nin,*) n
      Allocate (xe(d,n),q(n),qx(d,n))

!     Input the evaluation points.
      Do i = 1, n
        Read (nin,*) xe(1:d,i)
      End Do

!     Evaluate the interpolant using E01ZNF.
      ifail = 1
      Call e01znf(d,m,x,f,iq,rq,n,xe,q,qx,ifail)
      If (ifail==0 .Or. ifail==3) Then
        If (ifail==3) Then
          Write (nout,*) 'Some values below have been extrapolated'
          Write (nout,*)
        End If
        Write (nout,*)
        ifail = 0
        Call x04caf('General',' ',d,n,xe,d,                                    &
          'Interpolated Evaluation Points (columns)',ifail)
        Write (nout,*)
        Call x04caf('General',' ',1,n,q,1,'Interpolated values',ifail)
      Else
        Write (nout,99999) 'Evaluation routine returned with IFAIL = ', ifail
      End If

99999 Format (1X,A,I4)
    End Program e01zmfe


e01znfe.f90

!   E01ZNF Example Program Text
!   Mark 26 Release. NAG Copyright 2016.

    Module e01znfe_mod

!     E01ZNF Example Program Module:
!            Parameters and User-defined Routines

!     .. Use Statements ..
      Use nag_library, Only: nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Accessibility Statements ..
      Private
      Public                           :: funct
!     .. Parameters ..
      Real (Kind=nag_wp), Parameter    :: one = 1.0_nag_wp
      Real (Kind=nag_wp), Parameter    :: two = 2.0_nag_wp
      Integer, Parameter, Public       :: d = 6, nin = 5, nout = 6
    Contains
      Function funct(x)
!       This function evaluates the 6D function funct.

!       .. Function Return Value ..
        Real (Kind=nag_wp)             :: funct
!       .. Array Arguments ..
        Real (Kind=nag_wp), Intent (In) :: x(d)
!       .. Executable Statements ..
        funct = x(1)*x(2)*x(3)/(one+two*x(4)*x(5)*x(6))

        Return
      End Function funct
    End Module e01znfe_mod
    Program e01znfe

!     E01ZNF Example Main Program

!     .. Use Statements ..
      Use nag_library, Only: e01zmf, e01znf, g05kff, g05saf, nag_wp
      Use e01znfe_mod, Only: d, funct, nin, nout
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: lseed = 1
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: fun
      Integer                          :: genid, i, ifail, liq, lrq, lstate,   &
                                          m, n, nq, nw, subid
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: f(:), q(:), qx(:,:), rq(:), x(:,:),  &
                                          xe(:,:)
      Integer, Allocatable             :: iq(:), state(:)
      Integer                          :: seed(lseed)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: abs, real
!     .. Executable Statements ..
      Write (nout,*) 'E01ZNF Example Program Results'

!     Skip heading in data file
      Read (nin,*)

!     Read in the base generator information and seeds
      Read (nin,*) genid, subid, seed(1)

!     Initial call to initializer to get size of STATE array
      lstate = 0
      Allocate (state(lstate))
      ifail = 0
      Call g05kff(genid,subid,seed,lseed,state,lstate,ifail)

!     Reallocate STATE
      Deallocate (state)
      Allocate (state(lstate))

!     Initialize the generator to a repeatable sequence
      ifail = 0
      Call g05kff(genid,subid,seed,lseed,state,lstate,ifail)

!     Input the number of nodes.
      Read (nin,*) m
      liq = 2*m + 1
      lrq = (d+1)*(d+2)/2*m + 2*d + 1
      Allocate (x(d,m),f(m),iq(liq),rq(lrq))

!     Generate the data points X
      ifail = 0
      Call g05saf(d*m,state,x,ifail)

!     Evaluate F
      Do i = 1, m
        f(i) = funct(x(1,i))
      End Do

!     Generate the interpolant using E01ZMF.
      nq = 0
      nw = 0

      ifail = 0
      Call e01zmf(d,m,x,f,nw,nq,iq,rq,ifail)

!     Input the number of evaluation points.
      Read (nin,*) n
      Allocate (xe(d,n),q(n),qx(d,n))

!     Generate a set of evaluation points lying on diagonal line
!     xe(1:d,i) = xe(1,i) = i/(n+1).
      Do i = 1, n
        xe(1:d,i) = real(i,kind=nag_wp)/real(n+1,kind=nag_wp)
      End Do

!     Evaluate the interpolant.
      ifail = 0
      Call e01znf(d,m,x,f,iq,rq,n,xe,q,qx,ifail)

      Write (nout,99997)
      Write (nout,99998)
      Do i = 1, n
        fun = funct(xe(1,i))
        Write (nout,99999) i, fun, q(i), abs(fun-q(i))
      End Do

99999 Format (1X,I4,1X,3F10.4)
99998 Format (4X,'---|',20('-'),'+',15('-'))
99997 Format (/,4X,'I  |',2X,'F(I)',6X,'Q(I)',4X,'|',1X,'|F(I)-Q(I)|')
    End Program e01znfe


e02acfe.f90

    Program e02acfe

!     E02ACF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: e02acf, nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: m1 = 6, n = 21, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: ref, s, t, z
      Integer                          :: i, j
!     .. Local Arrays ..
      Real (Kind=nag_wp)               :: a(m1), x(n), y(n)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: exp, real
!     .. Executable Statements ..
      Write (nout,*) 'E02ACF Example Program Results'

      x(1:n) = real((/(i-1,i=1,n)/),kind=nag_wp)/real(n-1,kind=nag_wp)
      y(1:n) = exp(x(1:n))

      Call e02acf(x,y,n,a,m1,ref)

      Write (nout,*)
      Write (nout,*) '   Polynomial coefficients'
      Write (nout,99998)(a(i),i=1,m1)
      Write (nout,*)
      Write (nout,99997) '   Reference deviation = ', ref
      Write (nout,*)
      Write (nout,*) '  X     exp(X)    Fit     Residual'

      Do j = 1, n, 2
        z = x(j)

        s = a(m1)

        Do i = m1 - 1, 1, -1
          s = s*z + a(i)
        End Do

        t = y(j)
        Write (nout,99999) z, s, t, s - t
      End Do

99999 Format (1X,F5.2,2F9.4,E11.2)
99998 Format (6X,E12.4)
99997 Format (1X,A,E10.2)
    End Program e02acfe


e02adfe.f90

    Program e02adfe

!     E02ADF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: e02adf, e02aef, nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: fit, x1, xarg, xcapr, xm
      Integer                          :: i, ifail, iwght, j, k, kplus1, lda,  &
                                          m, r
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: a(:,:), ak(:), s(:), w(:), work1(:), &
                                          work2(:), x(:), y(:)
!     .. Executable Statements ..
      Write (nout,*) 'E02ADF Example Program Results'

!     Skip heading in data file
      Read (nin,*)

      Read (nin,*) m
      Read (nin,*) k, iwght
      kplus1 = k + 1
      lda = kplus1
      Allocate (a(lda,kplus1),s(kplus1),w(m),work1(3*m),work2(2*kplus1),x(m),  &
        y(m))

      Do r = 1, m

        If (iwght/=1) Then
          Read (nin,*) x(r), y(r), w(r)
        Else
          Read (nin,*) x(r), y(r)
          w(r) = 1.0E0_nag_wp
        End If

      End Do

      ifail = 0
      Call e02adf(m,kplus1,lda,x,y,w,work1,work2,a,s,ifail)

      Do i = 0, k
        Write (nout,*)
        Write (nout,99998) 'Degree', i, '   R.M.S. residual =', s(i+1)
        Write (nout,*)
        Write (nout,*) '  J  Chebyshev coeff A(J)'
        Write (nout,99997)(j,a(i+1,j),j=1,i+1)
      End Do

      Allocate (ak(kplus1))

      ak(1:kplus1) = a(kplus1,1:kplus1)
      x1 = x(1)
      xm = x(m)

      Write (nout,*)
      Write (nout,99996) 'Polynomial approximation and residuals for degree',  &
        k
      Write (nout,*)
      Write (nout,*)                                                           &
        '  R   Abscissa     Weight   Ordinate  Polynomial  Residual'

      Do r = 1, m
        xcapr = ((x(r)-x1)-(xm-x(r)))/(xm-x1)

        ifail = 0
        Call e02aef(kplus1,ak,xcapr,fit,ifail)

        Write (nout,99999) r, x(r), w(r), y(r), fit, fit - y(r)

        If (r<m) Then
          xarg = 0.5E0_nag_wp*(x(r)+x(r+1))
          xcapr = ((xarg-x1)-(xm-xarg))/(xm-x1)

          ifail = 0
          Call e02aef(kplus1,ak,xcapr,fit,ifail)

          Write (nout,99995) xarg, fit
        End If

      End Do

99999 Format (1X,I3,4F11.4,E11.2)
99998 Format (1X,A,I4,A,E12.2)
99997 Format (1X,I3,F15.4)
99996 Format (1X,A,I4)
99995 Format (4X,F11.4,22X,F11.4)
    End Program e02adfe


e02aefe.f90

    Program e02aefe

!     E02AEF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: e02aef, nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: p, xcap
      Integer                          :: i, ifail, m, n, nplus1, r
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: a(:)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: real
!     .. Executable Statements ..
      Write (nout,*) 'E02AEF Example Program Results'

!     Skip heading in data file
      Read (nin,*)

      Read (nin,*) m
      Read (nin,*) n
      nplus1 = n + 1
      Allocate (a(nplus1))

      Read (nin,*)(a(i),i=1,nplus1)

      Do r = 1, m
        xcap = real(2*r-m-1,kind=nag_wp)/real(m-1,kind=nag_wp)

        ifail = 0
        Call e02aef(nplus1,a,xcap,p,ifail)

        If (r==1) Then
          Write (nout,*)
          Write (nout,*) '  R       Argument       Value of polynomial'
        End If

        Write (nout,99999) r, xcap, p
      End Do

99999 Format (1X,I3,F14.4,4X,F14.4)
    End Program e02aefe


e02affe.f90

    Program e02affe

!     E02AFF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: e02aef, e02aff, nag_wp, x01aaf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: fit, pi, piby2n
      Integer                          :: i, ifail, j, n, nplus1, r
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: a(:), f(:), xcap(:)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: real, sin
!     .. Executable Statements ..
      Write (nout,*) 'E02AFF Example Program Results'

!     Skip heading in data file
      Read (nin,*)

      Read (nin,*) n
      nplus1 = n + 1
      Allocate (a(nplus1),f(nplus1),xcap(nplus1))

      piby2n = 0.5E0_nag_wp*x01aaf(pi)/real(n,kind=nag_wp)

      Read (nin,*)(f(r),r=1,nplus1)

      Do r = 1, nplus1
        i = r - 1

!       The following method of evaluating  XCAP = cos(PI*I/N)
!       ensures that the computed value has a small relative error
!       and, moreover, is bounded in modulus by unity for all
!       I = 0, 1, ..., N.  (It is assumed that the sine routine
!       produces a result with a small relative error for values
!       of the argument between  -PI/4  and  PI/4).

        If (4*i<=n) Then
          xcap(i+1) = 1.0E0_nag_wp - 2.0E0_nag_wp*sin(piby2n*real(i,kind=      &
            nag_wp))**2
        Else If (4*i>3*n) Then
          xcap(i+1) = 2.0E0_nag_wp*sin(piby2n*real(n-i,kind=nag_wp))**2 -      &
            1.0E0_nag_wp
        Else
          xcap(i+1) = sin(piby2n*real(n-2*i,kind=nag_wp))
        End If

      End Do

      ifail = 0
      Call e02aff(nplus1,f,a,ifail)

      Write (nout,*)
      Write (nout,*) '         Chebyshev'
      Write (nout,*) '  J   coefficient A(J)'
      Write (nout,99998)(j,a(j),j=1,nplus1)
      Write (nout,*)
      Write (nout,*) '  R    Abscissa   Ordinate      Fit'

      Do r = 1, nplus1

        ifail = 0
        Call e02aef(nplus1,a,xcap(r),fit,ifail)

        Write (nout,99999) r, xcap(r), f(r), fit
      End Do

99999 Format (1X,I3,3F11.4)
99998 Format (1X,I3,F14.7)
    End Program e02affe


e02agfe.f90

    Program e02agfe

!     E02AGF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: e02agf, e02akf, f16dnf, nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: fiti, xmax, xmin
      Integer                          :: i, ifail, ipmax, k, kplus1, la, lda, &
                                          liwrk, lwrk, lyf, m, mf, n, np1
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: a(:,:), s(:), w(:), wrk(:), x(:),    &
                                          xf(:), y(:), yf(:)
      Integer, Allocatable             :: ip(:), iwrk(:)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: max, sum
!     .. Executable Statements ..
      Write (nout,*) 'E02AGF Example Program Results'

!     Skip heading in data file
      Read (nin,*)

      Read (nin,*) mf
      liwrk = 2*mf + 2
      Allocate (ip(mf),xf(mf),iwrk(liwrk))

      Read (nin,*) ip(1:mf)

!     Get max(IP) for later use

      Call f16dnf(mf,ip,1,i,ipmax)

      Read (nin,*) xf(1:mf)

      lyf = mf + sum(ip(1:mf))
      Allocate (yf(lyf))

      Read (nin,*) yf(1:lyf)

      Read (nin,*) m
      Allocate (x(m),y(m),w(m))

      Read (nin,*)(x(i),y(i),w(i),i=1,m)

      Read (nin,*) k, xmin, xmax
      kplus1 = k + 1
      n = lyf
      np1 = n + 1
      lwrk = max(4*m+3*kplus1,8*n+5*ipmax+mf+10) + 2*n + 2
      lda = kplus1
      Allocate (wrk(lwrk),a(lda,kplus1),s(kplus1))

      ifail = 0
      Call e02agf(m,kplus1,lda,xmin,xmax,x,y,w,mf,xf,yf,lyf,ip,a,s,np1,wrk,    &
        lwrk,iwrk,liwrk,ifail)

      Write (nout,*)
      Write (nout,*) 'Degree  RMS residual'
      Write (nout,99999)(i,s(i+1),i=np1-1,k)
      Write (nout,*)
      Write (nout,99996) 'Details of the fit of degree ', k
      Write (nout,*)
      Write (nout,*) '  Index   Coefficient'

      Do i = 1, kplus1
        Write (nout,99997) i - 1, a(kplus1,i)
      End Do

      Write (nout,*)
      Write (nout,*) '     I      X(I)       Y(I)       Fit     Residual'

      Do i = 1, m
        la = lda*kplus1 - k

        ifail = 0
        Call e02akf(kplus1,xmin,xmax,a(kplus1,1),lda,la,x(i),fiti,ifail)

        Write (nout,99998) i, x(i), y(i), fiti, fiti - y(i)
      End Do

99999 Format (1X,I4,1P,E15.2)
99998 Format (1X,I6,3F11.4,E11.2)
99997 Format (1X,I6,F11.4)
99996 Format (1X,A,I2)
    End Program e02agfe


e02ahfe.f90

    Program e02ahfe

!     E02AHF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: e02ahf, e02akf, nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Real (Kind=nag_wp), Parameter    :: xmax = 2.5E0_nag_wp
      Real (Kind=nag_wp), Parameter    :: xmin = -0.5E0_nag_wp
      Integer, Parameter               :: nout = 6, np1 = 7
      Integer, Parameter               :: la = np1
      Integer, Parameter               :: ladif = np1
      Real (Kind=nag_wp), Parameter    :: a(la) = (/2.53213E0_nag_wp,          &
                                          1.13032E0_nag_wp,0.27150E0_nag_wp,   &
                                          0.04434E0_nag_wp,0.00547E0_nag_wp,   &
                                          0.00054E0_nag_wp,0.00004E0_nag_wp/)
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: deriv, deriv2, patm1, x
      Integer                          :: i, ifail, m
!     .. Local Arrays ..
      Real (Kind=nag_wp)               :: adif(ladif), adif2(ladif)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: real
!     .. Executable Statements ..
      Write (nout,*) 'E02AHF Example Program Results'

      ifail = 0
      Call e02ahf(np1,xmin,xmax,a,1,la,patm1,adif,1,ladif,ifail)

      ifail = 0
      Call e02ahf(np1-1,xmin,xmax,adif,1,ladif,patm1,adif2,1,ladif,ifail)

      m = 4

      Write (nout,*)
      Write (nout,*) '   I  Argument    1st deriv    2nd deriv'

      Do i = 1, m
        x = (xmin*real(m-i,kind=nag_wp)+xmax*real(i-1,kind=nag_wp))/           &
          real(m-1,kind=nag_wp)

        ifail = 0
        Call e02akf(np1-1,xmin,xmax,adif,1,ladif,x,deriv,ifail)

        ifail = 0
        Call e02akf(np1-2,xmin,xmax,adif2,1,ladif,x,deriv2,ifail)

        Write (nout,99999) i, x, deriv, deriv2
      End Do

99999 Format (1X,I4,F9.4,2(4X,F9.4))
    End Program e02ahfe


e02ajfe.f90

    Program e02ajfe

!     E02AJF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: e02ajf, e02akf, nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Real (Kind=nag_wp), Parameter    :: xmax = 2.5E0_nag_wp
      Real (Kind=nag_wp), Parameter    :: xmin = -0.5E0_nag_wp
      Integer, Parameter               :: nout = 6, np1 = 7
      Integer, Parameter               :: la = np1
      Integer, Parameter               :: laint = np1 + 1
      Real (Kind=nag_wp), Parameter    :: a(la) = (/2.53213E0_nag_wp,          &
                                          1.13032E0_nag_wp,0.27150E0_nag_wp,   &
                                          0.04434E0_nag_wp,0.00547E0_nag_wp,   &
                                          0.00054E0_nag_wp,0.00004E0_nag_wp/)
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: ra, rb, res, xa, xb
      Integer                          :: ifail
!     .. Local Arrays ..
      Real (Kind=nag_wp)               :: aintc(laint)
!     .. Executable Statements ..
      Write (nout,*) 'E02AJF Example Program Results'

      ifail = 0
      Call e02ajf(np1,xmin,xmax,a,1,la,0.0E0_nag_wp,aintc,1,laint,ifail)

      xa = 0.0E0_nag_wp
      xb = 2.0E0_nag_wp

      ifail = 0
      Call e02akf(np1+1,xmin,xmax,aintc,1,laint,xa,ra,ifail)

      ifail = 0
      Call e02akf(np1+1,xmin,xmax,aintc,1,laint,xb,rb,ifail)

      res = rb - ra

      Write (nout,*)
      Write (nout,99999) 'Value of definite integral is ', res

99999 Format (1X,A,F10.4)
    End Program e02ajfe


e02akfe.f90

    Program e02akfe

!     E02AKF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: e02akf, nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Real (Kind=nag_wp), Parameter    :: xmax = 2.5E0_nag_wp
      Real (Kind=nag_wp), Parameter    :: xmin = -0.5E0_nag_wp
      Integer, Parameter               :: nout = 6, np1 = 7
      Integer, Parameter               :: la = np1
      Real (Kind=nag_wp), Parameter    :: a(la) = (/2.53213E0_nag_wp,          &
                                          1.13032E0_nag_wp,0.27150E0_nag_wp,   &
                                          0.04434E0_nag_wp,0.00547E0_nag_wp,   &
                                          0.00054E0_nag_wp,0.00004E0_nag_wp/)
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: res, x
      Integer                          :: i, ifail, m
!     .. Intrinsic Procedures ..
      Intrinsic                        :: real
!     .. Executable Statements ..
      Write (nout,*) 'E02AKF Example Program Results'

      m = 4

      Do i = 1, m
        x = (xmin*real(m-i,kind=nag_wp)+xmax*real(i-1,kind=nag_wp))/           &
          real(m-1,kind=nag_wp)

        ifail = 0
        Call e02akf(np1,xmin,xmax,a,1,la,x,res,ifail)

        If (i==1) Then
          Write (nout,*)
          Write (nout,*) '   I   Argument  Value of polynomial'
        End If

        Write (nout,99999) i, x, res
      End Do

99999 Format (1X,I4,F10.4,4X,F9.4)
    End Program e02akfe


e02alfe.f90

    Program e02alfe

!     E02ALF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: e02alf, nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: dxx, ref, s, t, xx
      Integer                          :: i, ifail, j, m, n, neval
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: a(:), x(:), y(:)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: exp, real
!     .. Executable Statements ..
      Write (nout,*) 'E02ALF Example Program Results'

!     Skip heading in data file
      Read (nin,*)

      Read (nin,*) n, m, neval
      Allocate (a(m+1),x(n),y(n))

      Read (nin,*)(x(i),y(i),i=1,n)

      ifail = 0
      Call e02alf(n,x,y,m,a,ref,ifail)

      Write (nout,*)
      Write (nout,*) '   Polynomial coefficients'
      Write (nout,99998)(a(i),i=1,m+1)
      Write (nout,*)
      Write (nout,99997) '   Reference deviation = ', ref
      Write (nout,*)
      Write (nout,*) '  x     Fit      exp(x)   Residual'

!     The neval evaluation points are equispaced on [0,1].
      dxx = 1.0_nag_wp/real(neval-1,kind=nag_wp)

      Do j = 1, neval
        xx = real(j-1,kind=nag_wp)*dxx

        s = a(m+1)

        Do i = m, 1, -1
          s = s*xx + a(i)
        End Do

        t = exp(xx)
        Write (nout,99999) xx, s, t, s - t
      End Do

99999 Format (1X,F5.2,2F9.4,E11.2)
99998 Format (6X,E12.4)
99997 Format (1X,A,E10.2)
    End Program e02alfe


e02bafe.f90

    Program e02bafe

!     E02BAF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: e02baf, e02bbf, nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: fit, ss, xarg
      Integer                          :: ifail, iwght, j, m, ncap, ncap7, r
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: c(:), lamda(:), w(:), work1(:),      &
                                          work2(:), x(:), y(:)
!     .. Executable Statements ..
      Write (nout,*) 'E02BAF Example Program Results'

!     Skip heading in data file
      Read (nin,*)

      Read (nin,*) m
      Read (nin,*) ncap, iwght
      ncap7 = ncap + 7
      Allocate (x(m),y(m),w(m),lamda(ncap7),c(ncap7),work1(m),work2(4*ncap7))

      Read (nin,*) lamda(5:(ncap+3))

      Do r = 1, m

        If (iwght==1) Then
          Read (nin,*) x(r), y(r)
          w(r) = 1.0E0_nag_wp
        Else
          Read (nin,*) x(r), y(r), w(r)
        End If

      End Do

      ifail = 0
      Call e02baf(m,ncap7,x,y,w,lamda,work1,work2,c,ss,ifail)

      Write (nout,*)
      Write (nout,*) '  J       LAMDA(J+2)     B-spline coeff C(J)'
      Write (nout,*)

      j = 1
      Write (nout,99998) j, c(1)

      Do j = 2, ncap + 2
        Write (nout,99999) j, lamda(j+2), c(j)
      End Do

      Write (nout,99998) ncap + 3, c(ncap+3)
      Write (nout,*)
      Write (nout,99997) 'Residual sum of squares = ', ss
      Write (nout,*)
      Write (nout,*) 'Cubic spline approximation and residuals'
      Write (nout,*)
      Write (nout,*)                                                           &
        '  R   Abscissa     Weight   Ordinate     Spline  Residual'
      Write (nout,*)

      Do r = 1, m

        ifail = 0
        Call e02bbf(ncap7,lamda,c,x(r),fit,ifail)

        Write (nout,99995) r, x(r), w(r), y(r), fit, fit - y(r)

        If (r<m) Then
          xarg = 0.5E0_nag_wp*(x(r)+x(r+1))

          ifail = 0
          Call e02bbf(ncap7,lamda,c,xarg,fit,ifail)

          Write (nout,99996) xarg, fit
        End If

      End Do

99999 Format (1X,I3,F15.4,F20.4)
99998 Format (1X,I3,F35.4)
99997 Format (1X,A,E12.2)
99996 Format (1X,F14.4,F33.4)
99995 Format (1X,I3,4F11.4,E10.2)
    End Program e02bafe


e02bbfe.f90

    Program e02bbfe

!     E02BBF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: e02bbf, nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: a, b, s, x
      Integer                          :: ifail, j, m, ncap, ncap7, r
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: c(:), lamda(:)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: real
!     .. Executable Statements ..
      Write (nout,*) 'E02BBF Example Program Results'

!     Skip heading in data file
      Read (nin,*)

      Read (nin,*) m
      Read (nin,*) ncap
      ncap7 = ncap + 7
      Allocate (lamda(ncap7),c(ncap7))

      Read (nin,*) lamda(1:ncap7)
      Read (nin,*) c(1:ncap+3)

      a = lamda(4)
      b = lamda(ncap+4)

      Do r = 1, m
        x = (real(m-r,kind=nag_wp)*a+real(r-1,kind=nag_wp)*b)/                 &
          real(m-1,kind=nag_wp)

        ifail = 0
        Call e02bbf(ncap7,lamda,c,x,s,ifail)

        If (r==1) Then
          Write (nout,*)
          Write (nout,*) '  J       LAMDA(J)    B-spline coefficient (J-2)'
          Write (nout,*)

          Do j = 1, ncap7

            If (j<3 .Or. j>ncap+5) Then
              Write (nout,99999) j, lamda(j)
            Else
              Write (nout,99999) j, lamda(j), c(j-2)
            End If

          End Do

          Write (nout,*)
          Write (nout,*) '  R       Argument      Value of cubic spline'
          Write (nout,*)
        End If

        Write (nout,99999) r, x, s
      End Do

99999 Format (1X,I3,F14.4,F21.4)
    End Program e02bbfe


e02bcfe.f90

    Program e02bcfe

!     E02BCF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: e02bcf, nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: x
      Integer                          :: i, ifail, l, left, m, ncap, ncap7
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: c(:), lamda(:)
      Real (Kind=nag_wp)               :: s(4)
!     .. Executable Statements ..
      Write (nout,*) 'E02BCF Example Program Results'

!     Skip heading in data file
      Read (nin,*)

      Read (nin,*) ncap, m
      ncap7 = ncap + 7
      Allocate (lamda(ncap7),c(ncap7))

      Read (nin,*) lamda(1:ncap7)
      Read (nin,*) c(1:(ncap+3))

      Do i = 1, m
        Read (nin,*) x

        Do left = 1, 2

          ifail = 0
          Call e02bcf(ncap7,lamda,c,x,left,s,ifail)

          If (left==1) Then

            If (i==1) Then
              Write (nout,*)
              Write (nout,*)                                                   &
                '      X             Spline    1st deriv   2nd deriv   ',      &
                '3rd deriv'
            End If

            Write (nout,*)
            Write (nout,99999) x, '  LEFT', (s(l),l=1,4)
          Else
            Write (nout,99999) x, ' RIGHT', (s(l),l=1,4)
          End If

        End Do

      End Do

99999 Format (1X,E10.2,A,4E12.4)
    End Program e02bcfe


e02bdfe.f90

    Program e02bdfe

!     E02BDF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: e02bdf, nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: dint
      Integer                          :: ifail, ncap, ncap7
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: c(:), lamda(:)
!     .. Executable Statements ..
      Write (nout,*) 'E02BDF Example Program Results'

!     Skip heading in data file
      Read (nin,*)

      Read (nin,*) ncap
      ncap7 = ncap + 7
      Allocate (lamda(ncap7),c(ncap7))

      Read (nin,*) lamda(1:ncap7)
      Read (nin,*) c(1:(ncap+3))

      ifail = 0
      Call e02bdf(ncap7,lamda,c,dint,ifail)

      Write (nout,*)
      Write (nout,99999) 'Definite integral = ', dint

99999 Format (1X,A,E11.3)
    End Program e02bdfe


e02befe.f90

    Program e02befe

!     E02BEF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: e02bbf, e02bef, nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: fp, s, txr
      Integer                          :: ifail, ioerr, j, lwrk, m, n, nest, r
      Character (1)                    :: start
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: c(:), lamda(:), sp(:), w(:), wrk(:), &
                                          x(:), y(:)
      Integer, Allocatable             :: iwrk(:)
!     .. Executable Statements ..
      Write (nout,*) 'E02BEF Example Program Results'

!     Skip heading in data file
      Read (nin,*)

!     Input the number of data points, followed by the data points (X),
!     the function values (Y) and the weights (W).

      Read (nin,*) m
      nest = m + 4
      lwrk = 4*m + 16*nest + 41
      Allocate (x(m),y(m),w(m),iwrk(nest),lamda(nest),wrk(lwrk),c(nest),       &
        sp(2*m-1))

      Do r = 1, m
        Read (nin,*) x(r), y(r), w(r)
      End Do

      start = 'C'

!     Read in successive values of S until end of data file.

data: Do
        Read (nin,*,Iostat=ioerr) s

        If (ioerr<0) Then
          Exit data
        End If

!       Determine the spline approximation.

        ifail = 0
        Call e02bef(start,m,x,y,w,s,nest,n,lamda,c,fp,wrk,lwrk,iwrk,ifail)

!       Evaluate the spline at each X point and midway between
!       X points, saving the results in SP.

        Do r = 1, m

          ifail = 0
          Call e02bbf(n,lamda,c,x(r),sp((r-1)*2+1),ifail)

        End Do

        Do r = 1, m - 1
          txr = (x(r)+x(r+1))/2.0E0_nag_wp

          ifail = 0
          Call e02bbf(n,lamda,c,txr,sp(r*2),ifail)

        End Do

!       Output the results.

        Write (nout,*)
        Write (nout,99999) 'Calling with smoothing factor S =', s
        Write (nout,*)
        Write (nout,*) '                                           B-Spline'
        Write (nout,*)                                                         &
          '             J       Knot LAMDA(J+2)   Coefficient C(J)'
        Write (nout,99998) 1, c(1)

        Do j = 2, n - 5
          Write (nout,99997) j, lamda(j+2), c(j)
        End Do

        Write (nout,99998) n - 4, c(n-4)
        Write (nout,*)
        Write (nout,99999) 'Weighted sum of squared residuals FP =', fp

        If (fp==0.0E0_nag_wp) Then
          Write (nout,*) '(The spline is an interpolating spline)'
        Else If (n==8) Then
          Write (nout,*)                                                       &
            '(The spline is the weighted least squares cubic polynomial)'
        End If

        Write (nout,*)
        start = 'W'
      End Do data

99999 Format (1X,A,1P,E12.3)
99998 Format (11X,I4,20X,F16.4)
99997 Format (11X,I4,2F18.4)
    End Program e02befe


e02bffe.f90

    Program e02bffe

!     E02BFF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: e02bef, e02bff, nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: fp, sfac
      Integer                          :: deriv, ifail, ifail_e02bef, lds,     &
                                          liwrk, lwrk, m, ncap7, nest, nx, r,  &
                                          sd2, start, xord
      Character (1)                    :: cstart
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: c(:), lamda(:), s(:,:), wdata(:),    &
                                          wrk(:), x(:), xdata(:), ydata(:)
      Integer, Allocatable             :: iwrk(:), ixloc(:)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: abs, min
!     .. Executable Statements ..
      Write (nout,*) 'E02BFF Example Program Results'

!     Skip heading in data file
      Read (nin,*)

!     Input the number of data points for the spline,
!     followed by the data points (XDATA), the function values (YDATA)
!     and the weights (WDATA).

      Read (nin,*) m
      nest = m + 4
      lwrk = 4*m + 16*nest + 41
!     allocate memory for generating the spline
      Allocate (xdata(m),ydata(m),wdata(m),iwrk(nest),lamda(nest),wrk(lwrk),   &
        c(nest))

      Read (nin,*)(xdata(r),ydata(r),wdata(r),r=1,m)

      cstart = 'C'

!     Read in the requested smoothing factor.
      Read (nin,*) sfac

!     Determine the spline approximation.

      ifail_e02bef = 0
      Call e02bef(cstart,m,xdata,ydata,wdata,sfac,nest,ncap7,lamda,c,fp,wrk,   &
        lwrk,iwrk,ifail_e02bef)
      If (ifail_e02bef/=0) Then
        Write (nout,99997)                                                     &
          'Failed to generate spline using data set provided.'
        Write (nout,99996) 'E02BEF returned IFAIL = ', ifail_e02bef
        Go To 100
      End If
      Deallocate (iwrk)

!     Read in the number of sample points requested.
      Read (nin,*) nx

!     Allocate memory for sample point locations and
!      function and derivative approximations.
      lds = nx
      liwrk = 3 + 3*nx
      Allocate (x(nx),s(lds,4),ixloc(nx),iwrk(liwrk))

!     Read in sample points.
      Read (nin,*) x(1:nx)

      xord = 0
      start = 0
      deriv = 3
      ifail = 1
      Call e02bff(start,ncap7,lamda,c,deriv,xord,x,ixloc,nx,s,lds,iwrk,liwrk,  &
        ifail)
      If (ifail>1) Then
        Write (nout,99996) ' E02BFF detected a fatal error. IFAIL =  ', ifail
        Go To 100
      End If

!     Output the results.
      Write (nout,*)
      Write (nout,99999)

      sd2 = min(abs(deriv),3) + 1
      Do r = 1, nx
        If (ixloc(r)>=4 .And. ixloc(r)<=ncap7-3) Then
          Write (nout,99998) x(r), ixloc(r), s(r,1:sd2)
        Else
          Write (nout,99998) x(r), ixloc(r)
        End If
      End Do

100   Continue
99999 Format (                                                                 &
        '        x   ixloc         s(x)        ds/dx      d2s/dx2      d3s/dx3'&
        )
99998 Format (1X,F8.4,3X,I5,4(1X,Es12.4))
99997 Format (1X,A)
99996 Format (1X,A,1X,I5)
    End Program e02bffe


e02cafe.f90

    Program e02cafe

!     E02CAF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: e02caf, e02cbf, nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: ymax
      Integer                          :: i, ifail, inuxp1, inuyp1, j, k, l,   &
                                          mi, mtot, n, na, nwork, r, t
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: a(:), f(:), ff(:), nux(:), nuy(:),   &
                                          w(:), work(:), x(:), xmax(:),        &
                                          xmin(:), y(:)
      Integer, Allocatable             :: m(:)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: max, sum
!     .. Executable Statements ..
      Write (nout,*) 'E02CAF Example Program Results'

!     Skip heading in data file
      Read (nin,*)

!     Input the number of lines Y = Y(I) on which data is given,
!     and the required degree of fit in the X and Y directions

      Read (nin,*) n, k, l
      inuxp1 = 1
      inuyp1 = 1
      na = (k+1)*(l+1)
      Allocate (a(na),m(n),y(n),xmin(n),xmax(n),nux(inuxp1),nuy(inuyp1))

!     Input Y(I), the number of data points on Y = Y(I) and the
!     range of X-values on this line, for I = 1,2,...N

      Do i = 1, n
        Read (nin,*) y(i), m(i), xmin(i), xmax(i)
      End Do

      mtot = sum(m(1:n))
      nwork = 3*mtot + 2*n*(k+2) + 5*(1+max(k,l))
      Allocate (x(mtot),f(mtot),w(mtot),ff(mtot),work(nwork))

!     Input the X-values and function values, F, together with
!     their weights, W.

      Read (nin,*)(x(i),f(i),w(i),i=1,mtot)

!     Evaluate the coefficients, A, of the fit to this set of data

      ifail = 0
      Call e02caf(m,n,k,l,x,y,f,w,mtot,a,na,xmin,xmax,nux,inuxp1,nuy,inuyp1,   &
        work,nwork,ifail)

      mi = 0

      Write (nout,*)
      Write (nout,*) '     Data Y     Data X     Data F   Fitted F   Residual'
      Write (nout,*)

      Do r = 1, n
        t = mi + 1
        mi = mi + m(r)
        ymax = y(n)

        If (n==1) Then
          ymax = ymax + 1.0E0_nag_wp
        End If

!       Evaluate the fitted polynomial at each of the data points
!       on the line Y = Y(R)

        ifail = 0
        Call e02cbf(t,mi,k,l,x,xmin(r),xmax(r),y(r),y(1),ymax,ff,a,na,work,    &
          nwork,ifail)

!       Output the data and fitted values on the line Y = Y(R)

        Do i = t, mi
          Write (nout,99999) y(r), x(i), f(i), ff(i), ff(i) - f(i)
        End Do

        Write (nout,*)
      End Do

!     Output the Chebyshev coefficients of the fit

      Write (nout,*) 'Chebyshev coefficients of the fit'
      Write (nout,*)

      Do j = 1, k + 1
        Write (nout,99998)(a(i),i=1+(j-1)*(l+1),j*(l+1))
      End Do

99999 Format (3X,4F11.4,E11.2)
99998 Format (1X,6F11.4)
    End Program e02cafe


e02cbfe.f90

    Program e02cbfe

!     E02CBF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: e02cbf, nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: xmax, xmin, y, ymax, ymin
      Integer                          :: i, ifail, j, k, l, m, m1, m2,        &
                                          mfirst, mlast, na, nwork
      Logical                          :: plot
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: a(:), ff(:), work(:), x(:)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: min, real
!     .. Executable Statements ..
!     Skip heading in data file
      Read (nin,*)

      Read (nin,*) plot

      If (.Not. plot) Then
        Write (nout,*) 'E02CBF Example Program Results'
      End If

      Read (nin,*) k, l, m

      If (plot) Then
        m1 = 1
        m2 = m
        mlast = m
      Else
        m1 = (2*m+3)/7
        m2 = (6*m+3)/7 + 1
        mlast = min(5,m)
      End If

      na = (k+1)*(l+1)
      nwork = k + 1
      Allocate (x(mlast),ff(mlast),a(na),work(nwork))

      Read (nin,*) a(1:na)
      Read (nin,*) ymin, ymax, xmin, xmax

      Do j = 1, mlast
        x(j) = xmin + (xmax-xmin)*real(j-1,kind=nag_wp)/real(mlast-1,kind=     &
          nag_wp)
      End Do
      mfirst = 1

      Do i = m1, m2, m1
        y = ymin + ((ymax-ymin)*real(i-1,kind=nag_wp))/real(m-1,kind=nag_wp)

        ifail = 0
        Call e02cbf(mfirst,mlast,k,l,x,xmin,xmax,y,ymin,ymax,ff,a,na,work,     &
          nwork,ifail)

        If (plot) Then

          Do j = 1, mlast
            Write (nout,99998) y, x(j), ff(j)
          End Do

          Write (nout,*)
        Else
          Write (nout,*)
          Write (nout,99999) 'Y = ', y
          Write (nout,*)
          Write (nout,*) '  I     X(I)      Poly(X(I),Y)'

          Do j = 1, mlast
            Write (nout,99997) j, x(j), ff(j)
          End Do

        End If

      End Do

99999 Format (1X,A,E13.4)
99998 Format (1X,1P,2E13.4,1P,2E13.4)
99997 Format (1X,I3,1P,2E13.4)
    End Program e02cbfe


e02dafe.f90

    Program e02dafe

!     E02DAF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: e02daf, e02def, e02zaf, nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
      Character (1), Parameter         :: label(2) = (/'X','Y'/)
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: eps, sigma, sum, temp
      Integer                          :: i, iadres, ifail, itemp, j, m,       &
                                          nadres, nc, npoint, nws, px, py,     &
                                          rank
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: c(:), dl(:), f(:), ff(:), lamda(:),  &
                                          mu(:), w(:), wrk(:), ws(:), x(:),    &
                                          y(:)
      Integer, Allocatable             :: adres(:), iwrk(:), point(:)
!     .. Executable Statements ..
      Write (nout,*) 'E02DAF Example Program Results'

!     Skip heading in data file
      Read (nin,*)

!     Read data, interchanging X and Y axes if PX < PY

      Read (nin,*) eps
      Read (nin,*) m
      Read (nin,*) px, py

      If (px<py) Then
        itemp = px
        px = py
        py = itemp
        itemp = 1
      Else
        itemp = 0
      End If

      nadres = (px-7)*(py-7)
      npoint = m + (px-7)*(py-7)
      nc = (px-4)*(py-4)
      nws = (2*nc+1)*(3*py-6) - 2
      Allocate (lamda(px),mu(py),x(m),y(m),f(m),ff(m),w(m),dl(nc),c(nc),       &
        ws(nws),point(npoint),adres(nadres),wrk(py-4),iwrk(py-4))

      If (itemp==1) Then
        Read (nin,*)(y(i),x(i),f(i),w(i),i=1,m)

        If (py>8) Then
          Read (nin,*) mu(5:(py-4))
        End If

        If (px>8) Then
          Read (nin,*) lamda(5:(px-4))
        End If

      Else
        Read (nin,*)(x(i),y(i),f(i),w(i),i=1,m)

        If (px>8) Then
          Read (nin,*) lamda(5:(px-4))
        End If

        If (py>8) Then
          Read (nin,*) mu(5:(py-4))
        End If

      End If

!     Sort points into panel order

      ifail = 0
      Call e02zaf(px,py,lamda,mu,m,x,y,point,npoint,adres,nadres,ifail)

      Write (nout,*)
      Write (nout,99995) 'Interior ', label(itemp+1), '-knots'

      If (px==8) Then
        Write (nout,*) 'None'
      Else

        Do j = 5, px - 4
          Write (nout,99996) lamda(j)
        End Do

      End If

      Write (nout,*)
      Write (nout,99995) 'Interior ', label(2-itemp), '-knots'

      If (py==8) Then
        Write (nout,*) 'None'
      Else

        Do j = 5, py - 4
          Write (nout,99996) mu(j)
        End Do

      End If

!     Fit bicubic spline to data points

      ifail = 0
      Call e02daf(m,px,py,x,y,f,w,lamda,mu,point,npoint,dl,c,nc,ws,nws,eps,    &
        sigma,rank,ifail)

      Write (nout,*)
      Write (nout,99999) 'Sum of squares of residual RHS', sigma
      Write (nout,*)
      Write (nout,99998) 'Rank', rank

!     Evaluate spline at the data points

      ifail = 0
      Call e02def(m,px,py,x,y,lamda,mu,c,ff,wrk,iwrk,ifail)

      sum = 0.0E0_nag_wp

      If (itemp==1) Then
        Write (nout,*)
        Write (nout,*) 'X and Y have been interchanged'
      End If

!     Output data points, fitted values and residuals

      Write (nout,*)
      Write (nout,*) '      X          Y          Data       Fit     Residual'

      Do i = 1, nadres
        iadres = i + m

loop:   Do
          iadres = point(iadres)

          If (iadres<=0) Then
            Exit loop
          End If

          temp = ff(iadres) - f(iadres)
          Write (nout,99997) x(iadres), y(iadres), f(iadres), ff(iadres), temp
          sum = sum + (temp*w(iadres))**2
        End Do loop

      End Do

      Write (nout,*)
      Write (nout,99999) 'Sum of squared residuals', sum
      Write (nout,*)
      Write (nout,*) 'Spline coefficients'

      Do i = 1, px - 4
        Write (nout,99996)(c((i-1)*(py-4)+j),j=1,py-4)
      End Do

99999 Format (1X,A,1P,E16.2)
99998 Format (1X,A,I5)
99997 Format (1X,4F11.4,E11.2)
99996 Format (1X,6F11.4)
99995 Format (1X,A,A1,A)
    End Program e02dafe


e02dcfe.f90

!   E02DCF Example Program Text
!   Mark 26 Release. NAG Copyright 2016.
    Module e02dcfe_mod

!     E02DCF Example Program Module:
!            Parameters and User-defined Routines

!     .. Use Statements ..
      Use nag_library, Only: nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Accessibility Statements ..
      Private
      Public                           :: cprint
!     .. Parameters ..
      Integer, Parameter, Public       :: nin = 5, nout = 6
    Contains
      Subroutine cprint(c,ny,nx,nout)

!       .. Scalar Arguments ..
        Integer, Intent (In)           :: nout, nx, ny
!       .. Array Arguments ..
        Real (Kind=nag_wp), Intent (In) :: c(ny-4,nx-4)
!       .. Local Scalars ..
        Integer                        :: i
!       .. Executable Statements ..
        Write (nout,*)
        Write (nout,*) 'The B-spline coefficients:'
        Write (nout,*)

        Do i = 1, ny - 4
          Write (nout,99999) c(i,1:(nx-4))
        End Do

        Return

99999   Format (1X,8F9.4)
      End Subroutine cprint
    End Module e02dcfe_mod
    Program e02dcfe

!     E02DCF Example Main Program

!     .. Use Statements ..
      Use nag_library, Only: e02dcf, e02dff, nag_wp
      Use e02dcfe_mod, Only: cprint, nin, nout
!     .. Implicit None Statement ..
      Implicit None
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: delta, fp, s, xhi, xlo, yhi, ylo
      Integer                          :: i, ifail, j, liwrk, lwrk, mx, my,    &
                                          npx, npy, nx, nxest, ny, nyest
      Character (1)                    :: start
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: c(:), f(:), fg(:), lamda(:), mu(:),  &
                                          px(:), py(:), wrk(:), x(:), y(:)
      Integer, Allocatable             :: iwrk(:)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: max, min, real
!     .. Executable Statements ..
      Write (nout,*) 'E02DCF Example Program Results'

!     Skip heading in data file
      Read (nin,*)

!     Input the number of X, Y co-ordinates MX, MY.

      Read (nin,*) mx, my
      nxest = mx + 4
      nyest = my + 4
      lwrk = 4*(mx+my) + 11*(nxest+nyest) + nxest*my + max(my,nxest) + 54
      liwrk = 3 + mx + my + nxest + nyest
      Allocate (x(mx),y(my),f(mx*my),lamda(nxest),mu(nyest),wrk(lwrk),         &
        iwrk(liwrk),c((nxest-4)*(nyest-4)))

      Read (nin,*) x(1:mx)
      Read (nin,*) y(1:my)

!     Input the MX*MY function values F at the grid points.

      Read (nin,*) f(1:mx*my)

      start = 'C'

      Read (nin,*) s

!     Determine the spline approximation.

      ifail = 0
      Call e02dcf(start,mx,x,my,y,f,s,nxest,nyest,nx,lamda,ny,mu,c,fp,wrk,     &
        lwrk,iwrk,liwrk,ifail)

      Deallocate (wrk,iwrk)

      Write (nout,*)
      Write (nout,99999) 'Calling with smoothing factor S =', s, ': NX =', nx, &
        ', NY =', ny, '.'
      Write (nout,*)
      Write (nout,*) '               I   Knot LAMDA(I)      J     Knot MU(J)'
      Write (nout,*)

      Do j = 4, max(nx,ny) - 3

        If (j<=nx-3 .And. j<=ny-3) Then
          Write (nout,99997) j, lamda(j), j, mu(j)
        Else If (j<=nx-3) Then
          Write (nout,99997) j, lamda(j)
        Else If (j<=ny-3) Then
          Write (nout,99996) j, mu(j)
        End If

      End Do

      Call cprint(c,ny,nx,nout)

      Write (nout,*)
      Write (nout,99998) 'Sum of squared residuals FP =', fp

      If (fp==0.0E+0_nag_wp) Then
        Write (nout,*) '(The spline is an interpolating spline)'
      Else If (nx==8 .And. ny==8) Then
        Write (nout,*) '(The spline is the least squares bi-cubic polynomial)'
      End If

!     Evaluate the spline on a rectangular grid at NPX*NPY points
!     over the domain (XLO to XHI) x (YLO to YHI).

      Read (nin,*) npx, xlo, xhi
      Read (nin,*) npy, ylo, yhi

      lwrk = min(4*npx+nx,4*npy+ny)

      If (4*npx+nx>4*npy+ny) Then
        liwrk = npy + ny - 4
      Else
        liwrk = npx + nx - 4
      End If

      Allocate (px(npx),py(npy),fg(npx*npy),wrk(lwrk),iwrk(liwrk))

      delta = (xhi-xlo)/real(npx-1,kind=nag_wp)

      Do i = 1, npx
        px(i) = min(xlo+real(i-1,kind=nag_wp)*delta,xhi)
      End Do

      delta = (yhi-ylo)/real(npy-1,kind=nag_wp)

      Do i = 1, npy
        py(i) = min(ylo+real(i-1,kind=nag_wp)*delta,yhi)
      End Do

      ifail = 0
      Call e02dff(npx,npy,nx,ny,px,py,lamda,mu,c,fg,wrk,lwrk,iwrk,liwrk,ifail)

      Write (nout,*)
      Write (nout,*) 'Values of computed spline:'
      Write (nout,*)
      Write (nout,99995) '          X', (px(i),i=1,npx)
      Write (nout,*) '     Y'

      Do i = npy, 1, -1
        Write (nout,99994) py(i), (fg(npy*(j-1)+i),j=1,npx)
      End Do

99999 Format (1X,A,1P,E13.4,A,I5,A,I5,A)
99998 Format (1X,A,1P,E13.4)
99997 Format (1X,I16,F12.4,I11,F12.4)
99996 Format (1X,I39,F12.4)
99995 Format (1X,A,7F8.2)
99994 Format (1X,F8.2,3X,7F8.2)
    End Program e02dcfe


e02ddfe.f90

!   E02DDF Example Program Text
!   Mark 26 Release. NAG Copyright 2016.
    Module e02ddfe_mod

!     E02DDF Example Program Module:
!            Parameters and User-defined Routines

!     .. Use Statements ..
      Use nag_library, Only: nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Accessibility Statements ..
      Private
      Public                           :: cprint
!     .. Parameters ..
      Integer, Parameter, Public       :: nin = 5, nout = 6
    Contains
      Subroutine cprint(c,ny,nx,nout)

!       .. Scalar Arguments ..
        Integer, Intent (In)           :: nout, nx, ny
!       .. Array Arguments ..
        Real (Kind=nag_wp), Intent (In) :: c(ny-4,nx-4)
!       .. Local Scalars ..
        Integer                        :: i
!       .. Executable Statements ..
        Write (nout,*)
        Write (nout,*) 'The B-spline coefficients:'
        Write (nout,*)

        Do i = 1, ny - 4
          Write (nout,99999) c(i,1:(nx-4))
        End Do

        Return

99999   Format (1X,7F9.2)
      End Subroutine cprint
    End Module e02ddfe_mod
    Program e02ddfe

!     E02DDF Example Main Program

!     .. Use Statements ..
      Use nag_library, Only: e02ddf, e02dff, nag_wp
      Use e02ddfe_mod, Only: cprint, nin, nout
!     .. Implicit None Statement ..
      Implicit None
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: delta, fp, s, xhi, xlo, yhi, ylo
      Integer                          :: i, ifail, j, liwrk, lwrk, m, npx,    &
                                          npy, nx, nxest, ny, nyest, rank, u,  &
                                          v, ww
      Character (1)                    :: start
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: c(:), f(:), fg(:), lamda(:), mu(:),  &
                                          px(:), py(:), w(:), wrk(:), x(:),    &
                                          y(:)
      Integer, Allocatable             :: iwrk(:)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: max, min, real
!     .. Executable Statements ..
      Write (nout,*) 'E02DDF Example Program Results'

!     Skip heading in data file
      Read (nin,*)

      Read (nin,*) m
      nxest = m
      nyest = nxest
      liwrk = m + 2*(nxest-7)*(nyest-7)
      u = nxest - 4
      v = nyest - 4
      ww = max(u,v)
      lwrk = (7*u*v+25*ww)*(ww+1) + 2*(u+v+4*m) + 23*ww + 56
      Allocate (x(m),y(m),f(m),w(m),lamda(nxest),mu(nyest),c((nxest-4)*(nyest- &
        4)),iwrk(liwrk),wrk(lwrk))

!     Input the data-points and the weights.

      Do i = 1, m
        Read (nin,*) x(i), y(i), f(i), w(i)
      End Do

      start = 'C'

      Read (nin,*) s

!     Determine the spline approximation.

      ifail = 0
      Call e02ddf(start,m,x,y,f,w,s,nxest,nyest,nx,lamda,ny,mu,c,fp,rank,wrk,  &
        lwrk,iwrk,liwrk,ifail)

      Deallocate (wrk,iwrk)

      Write (nout,*)
      Write (nout,99999) 'Calling with smoothing factor S =', s, ': NX =', nx, &
        ', NY =', ny, ','
      Write (nout,99998) 'rank deficiency =', (nx-4)*(ny-4) - rank
      Write (nout,*)
      Write (nout,*) '               I   Knot LAMDA(I)      J     Knot MU(J)'
      Write (nout,*)

      Do j = 4, max(nx,ny) - 3

        If (j<=nx-3 .And. j<=ny-3) Then
          Write (nout,99996) j, lamda(j), j, mu(j)
        Else If (j<=nx-3) Then
          Write (nout,99996) j, lamda(j)
        Else If (j<=ny-3) Then
          Write (nout,99995) j, mu(j)
        End If

      End Do

      Call cprint(c,ny,nx,nout)

      Write (nout,*)
      Write (nout,99997) ' Sum of squared residuals FP =', fp

      If (nx==8 .And. ny==8) Then
        Write (nout,*)                                                         &
          ' ( The spline is the least squares bi-cubic polynomial )'
      End If

!     Evaluate the spline on a rectangular grid at NPX*NPY points
!     over the domain (XLO to XHI) x (YLO to YHI).

      Read (nin,*) npx, xlo, xhi
      Read (nin,*) npy, ylo, yhi

      lwrk = min(4*npx+nx,4*npy+ny)

      If (4*npx+nx>4*npy+ny) Then
        liwrk = npy + ny - 4
      Else
        liwrk = npx + nx - 4
      End If

      Allocate (px(npx),py(npy),fg(npx*npy),wrk(lwrk),iwrk(liwrk))

      delta = (xhi-xlo)/real(npx-1,kind=nag_wp)

      Do i = 1, npx
        px(i) = min(xlo+real(i-1,kind=nag_wp)*delta,xhi)
      End Do

      Do i = 1, npy
        py(i) = min(ylo+real(i-1,kind=nag_wp)*delta,yhi)
      End Do

      ifail = 0
      Call e02dff(npx,npy,nx,ny,px,py,lamda,mu,c,fg,wrk,lwrk,iwrk,liwrk,ifail)

      Write (nout,*)
      Write (nout,*) 'Values of computed spline:'
      Write (nout,*)
      Write (nout,99994) '          X', (px(i),i=1,npx)
      Write (nout,*) '     Y'

      Do i = npy, 1, -1
        Write (nout,99993) py(i), (fg(npy*(j-1)+i),j=1,npx)
      End Do

99999 Format (1X,A,1P,E13.4,A,I5,A,I5,A)
99998 Format (1X,A,I5)
99997 Format (1X,A,1P,E13.4,A)
99996 Format (1X,I16,F12.4,I11,F12.4)
99995 Format (1X,I39,F12.4)
99994 Format (1X,A,7F8.2)
99993 Format (1X,F8.2,3X,7F8.2)
    End Program e02ddfe


e02defe.f90

    Program e02defe

!     E02DEF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: e02def, nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Integer                          :: i, ifail, m, px, py
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: c(:), ff(:), lamda(:), mu(:),        &
                                          wrk(:), x(:), y(:)
      Integer, Allocatable             :: iwrk(:)
!     .. Executable Statements ..
      Write (nout,*) 'E02DEF Example Program Results'

!     Skip heading in data file
      Read (nin,*)

!     Read PX and PY, the number of knots in the X and Y directions.

      Read (nin,*) px, py
      Allocate (lamda(px),mu(py),c((px-4)*(py-4)),wrk(py-4),iwrk(py-4))

!     Read the knots LAMDA(1) .. LAMDA(PX) and MU(1) .. MU(PY).

      Read (nin,*) lamda(1:px)
      Read (nin,*) mu(1:py)

!     Read C, the bicubic spline coefficients.

      Read (nin,*) c(1:(px-4)*(py-4))

!     Read M, the number of spline evaluation points.

      Read (nin,*) m
      Allocate (x(m),y(m),ff(m))

!     Read the X and Y co-ordinates of the evaluation points.

      Do i = 1, m
        Read (nin,*) x(i), y(i)
      End Do

!     Evaluate the spline at the M points.

      ifail = 0
      Call e02def(m,px,py,x,y,lamda,mu,c,ff,wrk,iwrk,ifail)

      Write (nout,*)
      Write (nout,*) '      I       X(I)       Y(I)      FF(I)'
      Write (nout,99999)(i,x(i),y(i),ff(i),i=1,m)

99999 Format (1X,I7,3F11.3)
    End Program e02defe


e02dffe.f90

    Program e02dffe

!     E02DFF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: e02dff, nag_wp, x04cbf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: indent = 0, ncols = 80, nin = 5,     &
                                          nout = 6
      Character (1), Parameter         :: chlabel = 'C', diag = 'N',           &
                                          matrix = 'G'
      Character (4), Parameter         :: form = 'F8.3'
!     .. Local Scalars ..
      Integer                          :: ifail, liwrk, lwrk, mx, my, px, py
      Character (48)                   :: title
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: c(:), ff(:), lamda(:), mu(:),        &
                                          wrk(:), x(:), y(:)
      Integer, Allocatable             :: iwrk(:)
      Character (10), Allocatable      :: clabs(:), rlabs(:)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: min
!     .. Executable Statements ..
      Write (nout,*) 'E02DFF Example Program Results'
      Flush (nout)

!     Skip heading in data file
      Read (nin,*)

!     Read PX and PY, the number of knots in the X and Y directions.

      Read (nin,*) px, py
      Allocate (lamda(px),mu(py),c((px-4)*(py-4)))

!     Read the knots LAMDA(1) .. LAMDA(PX) and MU(1) .. MU(PY).

      Read (nin,*) lamda(1:px)
      Read (nin,*) mu(1:py)

!     Read C, the bicubic spline coefficients.

      Read (nin,*) c(1:(px-4)*(py-4))

!     Read MX and MY, the number of grid points in the X and Y
!     directions respectively.

      Read (nin,*) mx, my
      lwrk = min(4*mx+px,4*my+py)
      liwrk = mx + px - 4
      Allocate (clabs(mx),rlabs(my),x(mx),y(my),ff(mx*my),wrk(lwrk),           &
        iwrk(liwrk))

!     Read the X and Y co-ordinates defining the evaluation grid.

      Read (nin,*) x(1:mx)
      Read (nin,*) y(1:my)

!     Evaluate the spline at the MX by MY points.

      ifail = 0
      Call e02dff(mx,my,px,py,x,y,lamda,mu,c,ff,wrk,lwrk,iwrk,liwrk,ifail)

!     Generate column and row labels to print the results with.

      Write (clabs(1:mx),99999) x(1:mx)
      Write (rlabs(1:my),99999) y(1:my)

      Write (nout,*)
      Flush (nout)

!     Print the result array.
      title = 'Spline evaluated on X-Y grid (X across, Y down):'
      Call x04cbf(matrix,diag,my,mx,ff,my,form,title,chlabel,rlabs,chlabel,    &
        clabs,ncols,indent,ifail)

99999 Format ((F5.1))
    End Program e02dffe


e02dhfe.f90

!   E02DHF Example Program Text
!   Mark 26 Release. NAG Copyright 2016.
    Module e02dhfe_mod

!     E02DHF Example Program Module:
!            Parameters and User-defined Routines

!     .. Use Statements ..
      Use nag_library, Only: nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Accessibility Statements ..
      Private
      Public                           :: print_spline
!     .. Parameters ..
      Integer, Parameter, Public       :: nin = 5, nout = 6
    Contains
      Subroutine print_spline(ngx,gridx,ngy,gridy,z,zder)

!       Print spline function and spline derivative evaluation

!       .. Use Statements ..
        Use nag_library, Only: x04cbf
!       .. Parameters ..
        Integer, Parameter             :: indent = 0, ncols = 80
        Character (1), Parameter       :: chlabel = 'C', diag = 'N',           &
                                          matrix = 'G'
        Character (4), Parameter       :: form = 'F8.3'
!       .. Scalar Arguments ..
        Integer, Intent (In)           :: ngx, ngy
!       .. Array Arguments ..
        Real (Kind=nag_wp), Intent (In) :: gridx(ngx), gridy(ngy), z(ngx*ngy), &
                                          zder(ngx*ngy)
!       .. Local Scalars ..
        Integer                        :: i, ifail
        Character (48)                 :: title
!       .. Local Arrays ..
        Character (10), Allocatable    :: clabs(:), rlabs(:)
!       .. Executable Statements ..
!       Allocate for row and column label
        Allocate (clabs(ngx),rlabs(ngy))
!       Generate column and row labels to print the results with.
        Do i = 1, ngx
          Write (clabs(i),99999) gridx(i)
        End Do
        Do i = 1, ngy
          Write (rlabs(i),99999) gridy(i)
        End Do

!       Print the spline evaluations.
        title = 'Spline evaluated on X-Y grid (X across, Y down):'
        Write (nout,*)
        Flush (nout)
        ifail = 0
        Call x04cbf(matrix,diag,ngy,ngx,z,ngy,form,title,chlabel,rlabs,        &
          chlabel,clabs,ncols,indent,ifail)

!       Print the spline derivative evaluations.
        title = 'Spline derivative evaluated on X-Y grid:'
        Write (nout,*)
        Flush (nout)
        ifail = 0
        Call x04cbf(matrix,diag,ngy,ngx,zder,ngy,form,title(1:40),chlabel,     &
          rlabs,chlabel,clabs,ncols,indent,ifail)

        Deallocate (clabs,rlabs)

99999   Format (F5.2)
      End Subroutine print_spline
    End Module e02dhfe_mod
    Program e02dhfe

!     E02DHF Example Main Program

!     .. Use Statements ..
      Use nag_library, Only: e02dcf, e02dhf, nag_wp
      Use e02dhfe_mod, Only: nin, nout, print_spline
!     .. Implicit None Statement ..
      Implicit None
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: delta, fp, s, xhi, xlo, yhi, ylo
      Integer                          :: i, ifail, liwrk, lwrk, mx, my, nc,   &
                                          ngx, ngy, nux, nuy, nx, nxest, ny,   &
                                          nyest
      Character (1)                    :: start
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: c(:), f(:), gridx(:), gridy(:),      &
                                          lamda(:), mu(:), wrk(:), x(:), y(:), &
                                          z(:), zder(:)
      Integer, Allocatable             :: iwrk(:)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: max, real
!     .. Executable Statements ..
      Write (nout,*) 'E02DHF Example Program Results'

!     Skip heading in data file
      Read (nin,*)

!     Input the number of X, Y co-ordinates MX, MY.

      Read (nin,*) mx, my
      nxest = mx + 4
      nyest = my + 4
      nc = (nxest-4)*(nyest-4)

!     Allocations for spline fit
      Allocate (lamda(nxest),mu(nyest),c(nc))

!     Allocations for e02dcf only
      lwrk = 4*(mx+my) + 11*(nxest+nyest) + nxest*my + max(my,nxest) + 54
      liwrk = 3 + mx + my + nxest + nyest
      Allocate (x(mx),y(my),f(mx*my),wrk(lwrk),iwrk(liwrk))

      Read (nin,*) x(1:mx)
      Read (nin,*) y(1:my)

!     Input the MX*MY function values F at grid points and smoothing factor.

      Read (nin,*) f(1:mx*my)
      Read (nin,*) s

!     Determine the spline approximation.
      start = 'C'
      ifail = 0
      Call e02dcf(start,mx,x,my,y,f,s,nxest,nyest,nx,lamda,ny,mu,c,fp,wrk,     &
        lwrk,iwrk,liwrk,ifail)

      Deallocate (x,y,f,wrk,iwrk)

      Write (nout,*)
      Write (nout,99999) 'Spline fit used smoothing factor S =', s, '.'
      Write (nout,99998) 'Number of knots in each direction  =', nx, ny
      Write (nout,*)
      Write (nout,99999) 'Sum of squared residuals           =', fp, '.'

!     Spline and its derivative to be evaluated on rectangular grid with
!     ngx*ngy points on the domain [xlo,xhi]x[ylo,yhi].

      Read (nin,*) ngx, xlo, xhi
      Read (nin,*) ngy, ylo, yhi

!     Allocations for e02dhf (spline evaluation).
      Allocate (gridx(ngx),gridy(ngy),z(ngx*ngy),zder(ngx*ngy))

      delta = (xhi-xlo)/real(ngx-1,kind=nag_wp)
      gridx(1) = xlo
      Do i = 2, ngx - 1
        gridx(i) = gridx(i-1) + delta
      End Do
      gridx(ngx) = xhi

      delta = (yhi-ylo)/real(ngy-1,kind=nag_wp)
      gridy(1) = ylo
      Do i = 2, ngy - 1
        gridy(i) = gridy(i-1) + delta
      End Do
      gridy(ngy) = yhi

!     Evaluate spline (nux=nuy=0)
      nux = 0
      nuy = 0
      ifail = 0
      Call e02dhf(ngx,ngy,nx,ny,gridx,gridy,lamda,mu,c,nux,nuy,z,ifail)
!     Evaluate spline partial derivative of order (nux,nuy)
      Read (nin,*) nux, nuy
      Write (nout,*)
      Write (nout,99998) 'Derivative of spline has order nux, nuy =', nux, nuy
      ifail = 0
      Call e02dhf(ngx,ngy,nx,ny,gridx,gridy,lamda,mu,c,nux,nuy,zder,ifail)

!     Print tabulated spline and derivative evaluations.
      Call print_spline(ngx,gridx,ngy,gridy,z,zder)

99999 Format (1X,A,1P,E13.4,A)
99998 Format (1X,A,I5,',',I5,'.')
    End Program e02dhfe


e02gafe.f90

    Program e02gafe

!     E02GAF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: e02gaf, nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6, nplus2 = 5
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: resid, t, toler
      Integer                          :: i, ifail, irank, iter, lda, m
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: a(:,:), b(:), x(:)
      Integer, Allocatable             :: iwork(:)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: exp
!     .. Executable Statements ..
      Write (nout,*) 'E02GAF Example Program Results'

!     Skip heading in data file
      Read (nin,*)

      Read (nin,*) m
      lda = m + 2
      Allocate (a(lda,nplus2),iwork(m),b(m),x(nplus2))

      Do i = 1, m
        Read (nin,*) t, b(i)
        a(i,1) = exp(t)
        a(i,2) = exp(-t)
      End Do

      a(1:m,3) = 1.0E0_nag_wp
      toler = 0.0E0_nag_wp

      ifail = -1
      Call e02gaf(m,a,lda,b,nplus2,toler,x,resid,irank,iter,iwork,ifail)

      Select Case (ifail)
      Case (0,1)
        Write (nout,*)
        Write (nout,99999) 'Resid = ', resid, '  Rank = ', irank,              &
          '  Iterations = ', iter, '  IFAIL =', ifail
        Write (nout,*)
        Write (nout,*) 'Solution'
        Write (nout,99998) x(1:(nplus2-2))
      End Select

99999 Format (1X,A,E10.2,A,I5,A,I5,A,I5)
99998 Format (1X,6F10.4)
    End Program e02gafe


e02gbfe.f90

!   E02GBF Example Program Text
!   Mark 26 Release. NAG Copyright 2016.
    Module e02gbfe_mod

!     E02GBF Example Program Module:
!            Parameters and User-defined Routines

!     .. Use Statements ..
      Use nag_library, Only: nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Accessibility Statements ..
      Private
      Public                           :: monit
!     .. Parameters ..
      Integer, Parameter, Public       :: n = 4, nin = 5, nout = 6
    Contains
      Subroutine monit(n,x,niter,k,el1n)

!       .. Scalar Arguments ..
        Real (Kind=nag_wp), Intent (In) :: el1n
        Integer, Intent (In)           :: k, n, niter
!       .. Array Arguments ..
        Real (Kind=nag_wp), Intent (In) :: x(n)
!       .. Executable Statements ..
        Write (nout,*)
        Write (nout,99999) 'Results at iteration ', niter
        Write (nout,*) 'X-values'
        Write (nout,99998) x
        Write (nout,99997) 'Norm of residuals =', el1n

        Return

99999   Format (1X,A,I5)
99998   Format (1X,4F15.4)
99997   Format (1X,A,E12.5)
      End Subroutine monit
    End Module e02gbfe_mod
    Program e02gbfe

!     E02GBF Example Main Program

!     .. Use Statements ..
      Use nag_library, Only: e02gbf, nag_wp
      Use e02gbfe_mod, Only: monit, n, nin, nout
!     .. Implicit None Statement ..
      Implicit None
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: el1n, t
      Integer                          :: i, ifail, iprint, iw, k, l, lde, m,  &
                                          mpl, mxs
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: e(:,:), f(:), w(:), x(:)
      Integer, Allocatable             :: indx(:)
!     .. Executable Statements ..
      Write (nout,*) 'E02GBF Example Program Results'

!     Skip heading in data file
      Read (nin,*)

      Read (nin,*) m
      lde = n
      l = m
      mpl = m + l
      iw = 3*mpl + 5*n + n**2 + (n+1)*(n+2)/2
      Allocate (e(lde,mpl),f(mpl),x(n),indx(mpl),w(iw))

      Do i = 1, m
        Read (nin,*) t, f(i)
        e(1:4,i) = (/1.0_nag_wp,t,t*t,t*t*t/)
        e(1:4,m+i) = (/0.0_nag_wp,1.0_nag_wp,2.0_nag_wp*t,3.0_nag_wp*t*t/)
        f(m+i) = 0.0_nag_wp
      End Do

      x(1:n) = 0.0_nag_wp
      mxs = 50

!     * Set IPRINT=1 to obtain output from MONIT at each iteration *
      iprint = 0

      ifail = -1
      Call e02gbf(m,n,m+l,e,lde,f,x,mxs,monit,iprint,k,el1n,indx,w,iw,ifail)

    End Program e02gbfe


e02gcfe.f90

    Program e02gcfe

!     E02GCF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: e02gcf, nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: n = 3, nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: relerr, resmax, t, tol
      Integer                          :: i, ifail, irank, iter, lda, m, sda
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: a(:,:), b(:), x(:)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: exp
!     .. Executable Statements ..
      Write (nout,*) 'E02GCF Example Program Results'

!     Skip heading in data file
      Read (nin,*)

      Read (nin,*) m
      lda = n + 3
      sda = m + 1
      Allocate (a(lda,sda),b(m),x(n))

      Do i = 1, m
        Read (nin,*) t, b(i)
        a(1,i) = exp(t)
        a(2,i) = exp(-t)
        a(3,i) = 1.0E0_nag_wp
      End Do

      tol = 0.0E0_nag_wp
      relerr = 0.0E0_nag_wp

      ifail = -1
      Call e02gcf(m,n,sda,lda,a,b,tol,relerr,x,resmax,irank,iter,ifail)

      Select Case (ifail)
      Case (0,1)
        Write (nout,*)
        Write (nout,99999) 'RESMAX = ', resmax, '  Rank = ', irank,            &
          '  Iterations = ', iter, '  IFAIL =', ifail
        Write (nout,*)
        Write (nout,*) 'Solution'
        Write (nout,99998) x(1:n)
      End Select

99999 Format (1X,A,E10.2,3(A,I5))
99998 Format (1X,6F10.4)
    End Program e02gcfe


e02jdfe.f90

    Program e02jdfe

!     E02JDF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: e02jdf, nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: liopts = 100, lopts = 100, nin = 5,  &
                                          nout = 6
!     .. Local Scalars ..
      Integer                          :: gsmoothness, ifail, lcoefs, lsmaxp,  &
                                          lsminp, n, nxcels, nycels
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: coefs(:), f(:), x(:), y(:)
      Real (Kind=nag_wp)               :: opts(lopts), pmax(2), pmin(2)
      Integer                          :: iopts(liopts)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: maxval, minval
!     .. Executable Statements ..
      Write (nout,*) 'E02JDF Example Program Results'

!     Generate the data to fit and set the compulsory algorithmic control
!     parameters.

      Call generate_data(n,x,y,f,lsminp,lsmaxp,nxcels,nycels,lcoefs,coefs,     &
        gsmoothness)

!     Initialize the options arrays and set/get some options.

      Call handle_options(iopts,liopts,opts,lopts)

!     Compute the spline coefficients.

      ifail = 0
      Call e02jdf(n,x,y,f,lsminp,lsmaxp,nxcels,nycels,lcoefs,coefs,iopts,opts, &
        ifail)

!     pmin and pmax form the bounding box of the spline. We must not attempt
!     to evaluate the spline outside this box.

      pmin(:) = (/minval(x),minval(y)/)
      pmax(:) = (/maxval(x),maxval(y)/)

      Deallocate (x,y,f)

!     Evaluate the approximation at a vector of values.

      Call evaluate_at_vector(coefs,iopts,opts,pmin,pmax)

!     Evaluate the approximation on a mesh.

      Call evaluate_on_mesh(coefs,iopts,opts,pmin,pmax)

    Contains
      Subroutine generate_data(n,x,y,f,lsminp,lsmaxp,nxcels,nycels,lcoefs,     &
        coefs,gsmoothness)

!       Reads n from a data file and then generates an x and a y vector of n
!       pseudorandom uniformly-distributed values on (0,1]. These are passed
!       to the bivariate function of R. Franke to create the data set to fit.
!       The remaining input data for E02JDF are set to suitable values for
!       this problem, as discussed by Davydov and Zeilfelder.
!       Reads the global smoothing level from a data file. This value
!       determines the minimum required length of the array of spline
!       coefficients, coefs.

!       .. Use Statements ..
        Use nag_library, Only: g05kff, g05saf
!       .. Implicit None Statement ..
        Implicit None
!       .. Parameters ..
        Integer, Parameter             :: lseed = 4, mstate = 21
!       .. Scalar Arguments ..
        Integer, Intent (Out)          :: gsmoothness, lcoefs, lsmaxp, lsminp, &
                                          n, nxcels, nycels
!       .. Array Arguments ..
        Real (Kind=nag_wp), Allocatable, Intent (Out) :: coefs(:), f(:), x(:), &
                                          y(:)
!       .. Local Scalars ..
        Integer                        :: genid, ifail, lstate, subid
!       .. Local Arrays ..
        Integer                        :: seed(lseed), state(mstate)
!       .. Intrinsic Procedures ..
        Intrinsic                      :: exp
!       .. Executable Statements ..
        Continue

!       Read the size of the data set to be generated and fitted.
!       (Skip the heading in the data file.)

        Read (nin,*)
        Read (nin,*) n
        Allocate (x(n),y(n),f(n))

!       Initialize the random number generator and then generate the data.

        genid = 2
        subid = 53
        seed(:) = (/32958,39838,881818,45812/)
        lstate = mstate

        ifail = 0
        Call g05kff(genid,subid,seed,lseed,state,lstate,ifail)

        ifail = 0
        Call g05saf(n,state,x,ifail)

        ifail = 0
        Call g05saf(n,state,y,ifail)

!       Ensure that the bounding box stretches all the way to (0,0) and (1,1).

        x(1) = 0.0_nag_wp
        y(1) = 0.0_nag_wp
        x(n) = 1.0_nag_wp
        y(n) = 1.0_nag_wp

        f(:) = 0.75_nag_wp*exp(-((9._nag_wp*x(:)-2._nag_wp)**2+(9._nag_wp*y(:) &
          -2._nag_wp)**2)/4._nag_wp) + 0.75_nag_wp*exp(-(9._nag_wp*x(:)+       &
          1._nag_wp)**2/49._nag_wp-(9._nag_wp*y(:)+1._nag_wp)/10._nag_wp) +    &
          0.5_nag_wp*exp(-((9._nag_wp*x(:)-7._nag_wp)**2+(9._nag_wp*y(:)-      &
          3._nag_wp)**2)/4._nag_wp) - 0.2_nag_wp*exp(-(9._nag_wp*x(:)-         &
          4._nag_wp)**2-(9._nag_wp*y(:)-7._nag_wp)**2)

!       Set the grid size for the approximation.

        nxcels = 6
        nycels = nxcels

!       Read the required level of global smoothing.

        Read (nin,*) gsmoothness

!       Identify the computation.

        Write (nout,*)
        Write (nout,99998) 'Computing the coefficients of a C^', gsmoothness,  &
          ' spline approximation to Franke''s function'
        Write (nout,99999) 'Using a ', nxcels, ' by ', nycels, ' grid'

!       Set the local-approximation control parameters.

        lsminp = 3
        lsmaxp = 100

!       Set up the array to hold the computed spline coefficients.

        Select Case (gsmoothness)
        Case (1)
          lcoefs = (((nxcels+2)*(nycels+2)+1)/2)*10 + 1
        Case (2)
          lcoefs = 28*(nxcels+2)*(nycels+2)*4 + 1
        Case Default
          lcoefs = 0
        End Select

        Allocate (coefs(lcoefs))

        Return
99999   Format (1X,A,I2,A,I2,A)
99998   Format (1X,A,I1,A)
      End Subroutine generate_data
      Subroutine handle_options(iopts,liopts,opts,lopts)

!       Auxiliary routine for initializing the options arrays and
!       for demonstrating how to set and get optional parameters.

!       .. Use Statements ..
        Use nag_library, Only: e02zkf, e02zlf
!       .. Scalar Arguments ..
        Integer, Intent (In)           :: liopts, lopts
!       .. Array Arguments ..
        Real (Kind=nag_wp), Intent (Out) :: opts(lopts)
        Integer, Intent (Out)          :: iopts(liopts)
!       .. Local Scalars ..
        Real (Kind=nag_wp)             :: rvalue
        Integer                        :: ifail, ivalue, optype
        Logical                        :: supersmooth
        Character (16)                 :: cvalue
        Character (80)                 :: optstr
!       .. Executable Statements ..
        ifail = 0
        Call e02zkf('Initialize = E02JDF',iopts,liopts,opts,lopts,ifail)

!       Configure the global approximation method.

        Write (optstr,99998) 'Global Smoothing Level = ', gsmoothness

        ifail = 0
        Call e02zkf(optstr,iopts,liopts,opts,lopts,ifail)

!       If C^2 smoothing is requested, compute the spline using additional
!       super-smoothness constraints?
!       (The default is 'No'.)

        Read (nin,*) supersmooth

        If (gsmoothness==2 .And. supersmooth) Then

          ifail = 0
          Call e02zkf('Supersmooth C2 = Yes',iopts,liopts,opts,lopts,ifail)

        End If

        ifail = 0
        Call e02zkf('Averaged Spline = Yes',iopts,liopts,opts,lopts,ifail)

!       Configure the local approximation method.
!       (The default is 'Polynomial'.)

        ifail = 0
        Call e02zkf('Local Method = Polynomial',iopts,liopts,opts,lopts,ifail)

        Write (optstr,99999) 'Minimum Singular Value LPA = ',                  &
          1._nag_wp/32._nag_wp

        ifail = 0
        Call e02zkf(optstr,iopts,liopts,opts,lopts,ifail)

        Select Case (gsmoothness)
        Case (1)
          optstr = 'Polynomial Starting Degree = 3'
        Case (2)

          If (supersmooth) Then

!           We can benefit from starting with local polynomials of greater
!           degree than with regular C^2 smoothing.

            Write (nout,*) 'Using super-smoothing'
            optstr = 'Polynomial Starting Degree = 6'
          Else
            optstr = 'Polynomial Starting Degree = 5'
          End If

        End Select

        ifail = 0
        Call e02zkf(optstr,iopts,liopts,opts,lopts,ifail)

!       As an example of how to get the value of an optional parameter,
!       display whether averaging of local approximations is in operation.

        ifail = 0
        Call e02zlf('Averaged Spline',ivalue,rvalue,cvalue,optype,iopts,opts,  &
          ifail)

        If (cvalue=='YES') Then
          Write (nout,*) 'Using an averaged local approximation'
        End If

        Return
99999   Format (A,E16.9)
99998   Format (A,I1)
      End Subroutine handle_options
      Subroutine evaluate_at_vector(coefs,iopts,opts,pmin,pmax)

!       Evaluates the approximation at a vector of values.

!       .. Use Statements ..
        Use nag_library, Only: e02jef
!       .. Array Arguments ..
        Real (Kind=nag_wp), Intent (In) :: coefs(*), opts(*), pmax(2), pmin(2)
        Integer, Intent (In)           :: iopts(*)
!       .. Local Scalars ..
        Integer                        :: i, ifail, nevalv
!       .. Local Arrays ..
        Real (Kind=nag_wp), Allocatable :: fevalv(:), xevalv(:), yevalv(:)
!       .. Intrinsic Procedures ..
        Intrinsic                      :: max, min
!       .. Executable Statements ..
        Read (nin,*) nevalv
        Allocate (xevalv(nevalv),yevalv(nevalv),fevalv(nevalv))

        Read (nin,*)(xevalv(i),yevalv(i),i=1,nevalv)

!       Force the points to be within the bounding box of the spline.

        Do i = 1, nevalv
          xevalv(i) = max(xevalv(i),pmin(1))
          xevalv(i) = min(xevalv(i),pmax(1))
          yevalv(i) = max(yevalv(i),pmin(2))
          yevalv(i) = min(yevalv(i),pmax(2))
        End Do

        ifail = 0
        Call e02jef(nevalv,xevalv,yevalv,coefs,fevalv,iopts,opts,ifail)

        Write (nout,*)
        Write (nout,*) 'Values of computed spline at (x_i,y_i):'
        Write (nout,*)
        Write (nout,99999) 'x_i', 'y_i', 'f(x_i,y_i)'
        Write (nout,99998)(xevalv(i),yevalv(i),fevalv(i),i=1,nevalv)

        Return
99999   Format (1X,3A12)
99998   Format (1X,3F12.2)
      End Subroutine evaluate_at_vector
      Subroutine evaluate_on_mesh(coefs,iopts,opts,pmin,pmax)

!       Evaluates the approximation on a mesh of n_x * n_y values.

!       .. Use Statements ..
        Use nag_library, Only: e02jff
!       .. Implicit None Statement ..
        Implicit None
!       .. Array Arguments ..
        Real (Kind=nag_wp), Intent (In) :: coefs(*), opts(*), pmax(2), pmin(2)
        Integer, Intent (In)           :: iopts(*)
!       .. Local Scalars ..
        Integer                        :: i, ifail, j, nxeval, nyeval
        Logical                        :: print_mesh
!       .. Local Arrays ..
        Real (Kind=nag_wp), Allocatable :: fevalm(:,:), xevalm(:), yevalm(:)
        Real (Kind=nag_wp)             :: h(2), ll_corner(2), ur_corner(2)
!       .. Intrinsic Procedures ..
        Intrinsic                      :: max, min, real
!       .. Executable Statements ..
        Read (nin,*) nxeval, nyeval
        Allocate (xevalm(nxeval),yevalm(nyeval),fevalm(nxeval,nyeval))

!       Define the mesh by its lower-left and upper-right corners.

        Read (nin,*) ll_corner(1:2)
        Read (nin,*) ur_corner(1:2)

!       Set the mesh spacing and the evaluation points.
!       Force the points to be within the bounding box of the spline.

        h(1) = (ur_corner(1)-ll_corner(1))/real(nxeval-1,nag_wp)
        h(2) = (ur_corner(2)-ll_corner(2))/real(nyeval-1,nag_wp)

        Do i = 1, nxeval
          xevalm(i) = ll_corner(1) + real(i-1,nag_wp)*h(1)
          xevalm(i) = max(xevalm(i),pmin(1))
          xevalm(i) = min(xevalm(i),pmax(1))
        End Do

        Do j = 1, nyeval
          yevalm(j) = ll_corner(2) + real(j-1,nag_wp)*h(2)
          yevalm(j) = max(yevalm(j),pmin(2))
          yevalm(j) = min(yevalm(j),pmax(2))
        End Do

!       Evaluate.

        ifail = 0
        Call e02jff(nxeval,nyeval,xevalm,yevalm,coefs,fevalm,iopts,opts,ifail)

!       Output the computed function values?

        Read (nin,*) print_mesh

        If (.Not. print_mesh) Then
          Write (nout,*)
          Write (nout,*)                                                       &
            'Outputting of the function values on the mesh is disabled'
        Else
          Write (nout,*)
          Write (nout,*) 'Values of computed spline at (x_i,y_j):'
          Write (nout,*)
          Write (nout,99999) 'x_i', 'y_j', 'f(x_i,y_j)'
          Write (nout,99998)((xevalm(i),yevalm(j),fevalm(i,                    &
            j),i=1,nxeval),j=1,nyeval)
        End If

        Return
99999   Format (1X,3A12)
99998   Format (1X,3F12.2)
      End Subroutine evaluate_on_mesh
    End Program e02jdfe


e02rafe.f90

    Program e02rafe

!     E02RAF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: c02agf, e02raf, nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: l = 4, m = 4, nout = 6
      Integer, Parameter               :: ia = l + 1
      Integer, Parameter               :: ib = m + 1
      Integer, Parameter               :: ic = ia + ib - 1
      Integer, Parameter               :: jw = ib*(2*ib+3)
      Logical, Parameter               :: scale = .True.
!     .. Local Scalars ..
      Integer                          :: i, ifail
!     .. Local Arrays ..
      Real (Kind=nag_wp)               :: a(ia), b(ib), c(ic), dd(ia+ib),      &
                                          w(jw), work(2*(l+m+1)), z(2,l+m)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: real
!     .. Executable Statements ..
      Write (nout,*) 'E02RAF Example Program Results'

!     Power series coefficients in C

      c(1) = 1.0E0_nag_wp

      Do i = 1, ic - 1
        c(i+1) = c(i)/real(i,kind=nag_wp)
      End Do

      ifail = 0
      Call e02raf(ia,ib,c,ic,a,b,w,jw,ifail)

      Write (nout,*)
      Write (nout,*) 'The given series coefficients are'
      Write (nout,99999) c(1:ic)
      Write (nout,*)
      Write (nout,*) 'Numerator coefficients'
      Write (nout,99999) a(1:ia)
      Write (nout,*)
      Write (nout,*) 'Denominator coefficients'
      Write (nout,99999) b(1:ib)

!     Calculate zeros of the approximant using C02AGF
!     First need to reverse order of coefficients

      dd(ia:1:-1) = a(1:ia)

      ifail = 0
      Call c02agf(dd,l,scale,z,work,ifail)

      Write (nout,*)
      Write (nout,*) 'Zeros of approximant are at'
      Write (nout,*)
      Write (nout,*) '    Real part    Imag part'
      Write (nout,99998)(z(1,i),z(2,i),i=1,l)

!     Calculate poles of the approximant using C02AGF
!     Reverse order of coefficients

      dd(ib:1:-1) = b(1:ib)

      ifail = 0
      Call c02agf(dd,m,scale,z,work,ifail)

      Write (nout,*)
      Write (nout,*) 'Poles of approximant are at'
      Write (nout,*)
      Write (nout,*) '    Real part    Imag part'
      Write (nout,99998)(z(1,i),z(2,i),i=1,m)

99999 Format (1X,5E13.4)
99998 Format (1X,2E13.4)
    End Program e02rafe


e02rbfe.f90

    Program e02rbfe

!     E02RBF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: e02raf, e02rbf, nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: l = 4, m = 4, nout = 6
      Integer, Parameter               :: ia = l + 1
      Integer, Parameter               :: ib = m + 1
      Integer, Parameter               :: ic = ia + ib - 1
      Integer, Parameter               :: iw = ib*(2*ib+3)
      Logical, Parameter               :: plot = .False.
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: ans, tval, x
      Integer                          :: i, ifail, nx
!     .. Local Arrays ..
      Real (Kind=nag_wp)               :: a(ia), b(ib), cc(ic), w(iw)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: abs, exp, real
!     .. Executable Statements ..
      If (.Not. plot) Then
        Write (nout,*) 'E02RBF Example Program Results'
        nx = 10
      Else
        nx = 30
      End If

      cc(1) = 1.0E0_nag_wp

      Do i = 1, ic - 1
        cc(i+1) = cc(i)/real(i,kind=nag_wp)
      End Do

      ifail = 0
      Call e02raf(ia,ib,cc,ic,a,b,w,iw,ifail)

      If (.Not. plot) Then
        Write (nout,*)
        Write (nout,*) '    X         Pade          True'
      End If

      Do i = 1, nx
        x = real(i,kind=nag_wp)/10.0_nag_wp

        ifail = 0
        Call e02rbf(a,ia,b,ib,x,ans,ifail)

        tval = exp(x)

        If (plot) Then
          Write (nout,99999) x, ans, tval, abs(tval-ans)/tval
        Else
          Write (nout,99998) x, ans, tval
        End If
      End Do

99999 Format (1X,F6.1,4E19.9)
99998 Format (1X,F6.1,3E15.5)
    End Program e02rbfe


e02zafe.f90

    Program e02zafe

!     E02ZAF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: e02zaf, nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Integer                          :: i, iadres, ifail, m, nadres, npoint, &
                                          px, py
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: lamda(:), mu(:), x(:), y(:)
      Integer, Allocatable             :: adres(:), point(:)
!     .. Executable Statements ..
      Write (nout,*) 'E02ZAF Example Program Results'

!     Skip heading in data file
      Read (nin,*)

      Read (nin,*) m
      Read (nin,*) px, py
      nadres = (px-7)*(py-7)
      npoint = m + nadres
      Allocate (adres(nadres),lamda(px),mu(py),x(m),y(m),point(npoint))

!     Read data points and intercepts of panel sides

      Read (nin,*)(x(i),y(i),i=1,m)

      If (px>8) Then
        Read (nin,*) lamda(5:(px-4))
      End If

      If (py>8) Then
        Read (nin,*) mu(5:(py-4))
      End If

!     Sort points into panel order

      ifail = 0
      Call e02zaf(px,py,lamda,mu,m,x,y,point,npoint,adres,nadres,ifail)

!     Output points in panel order

      Do i = 1, nadres
        Write (nout,*)
        Write (nout,99999) 'Panel', i
        iadres = m + i

loop:   Do
          iadres = point(iadres)

          If (iadres<=0) Then
            Exit loop
          End If

          Write (nout,99998) x(iadres), y(iadres)
        End Do loop

      End Do

99999 Format (1X,A,I4)
99998 Format (1X,2F7.2)
    End Program e02zafe


e04abae.f90

!   E04ABA Example Program Text
!   Mark 26 Release. NAG Copyright 2016.
    Module e04abae_mod

!     E04ABA Example Program Module:
!            Parameters and User-defined Routines

!     .. Use Statements ..
      Use nag_library, Only: nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Accessibility Statements ..
      Private
      Public                           :: funct
!     .. Parameters ..
      Integer, Parameter, Public       :: nout = 6
    Contains
      Subroutine funct(xc,fc,iuser,ruser)
!       Routine to evaluate F(x) at any point in (A, B)

!       .. Scalar Arguments ..
        Real (Kind=nag_wp), Intent (Out) :: fc
        Real (Kind=nag_wp), Intent (In) :: xc
!       .. Array Arguments ..
        Real (Kind=nag_wp), Intent (Inout) :: ruser(*)
        Integer, Intent (Inout)        :: iuser(*)
!       .. Intrinsic Procedures ..
        Intrinsic                      :: sin
!       .. Executable Statements ..
        fc = sin(xc)/xc

        Return

      End Subroutine funct
    End Module e04abae_mod
    Program e04abae

!     E04ABA Example Main Program

!     .. Use Statements ..
      Use nag_library, Only: e04aba, nag_wp
      Use e04abae_mod, Only: funct, nout
!     .. Implicit None Statement ..
      Implicit None
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: a, b, e1, e2, f, x
      Integer                          :: ifail, maxcal
!     .. Local Arrays ..
      Real (Kind=nag_wp)               :: ruser(1)
      Integer                          :: iuser(1)
!     .. Executable Statements ..
      Write (nout,*) 'E04ABA Example Program Results'

!     E1 and E2 are set to zero so that E04ABA will reset them to
!     their default values

      e1 = 0.0_nag_wp
      e2 = 0.0_nag_wp

!     The minimum is known to lie in the range (3.5, 5.0)

      a = 3.5_nag_wp
      b = 5.0_nag_wp

!     Allow 30 calls of FUNCT

      maxcal = 30

      ifail = -1
      Call e04aba(funct,e1,e2,a,b,maxcal,x,f,iuser,ruser,ifail)

      Select Case (ifail)
      Case (0,2)
        Write (nout,*)
        Write (nout,99999) 'The minimum lies in the interval', a, ' to', b
        Write (nout,99999) 'Its estimated position is', x, ','
        Write (nout,99998) 'where the function value is ', f
        Write (nout,99997) maxcal, 'function evaluations were required'
      End Select

99999 Format (1X,A,F11.8,A,F11.8)
99998 Format (1X,A,F7.4)
99997 Format (1X,I2,1X,A)
    End Program e04abae


e04abfe.f90

!   E04ABF Example Program Text
!   Mark 26 Release. NAG Copyright 2016.
    Module e04abfe_mod

!     E04ABF Example Program Module:
!            Parameters and User-defined Routines

!     .. Use Statements ..
      Use nag_library, Only: nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Accessibility Statements ..
      Private
      Public                           :: funct
!     .. Parameters ..
      Integer, Parameter, Public       :: nout = 6
    Contains
      Subroutine funct(xc,fc)
!       Routine to evaluate F(x) at any point in (A, B)

!       .. Scalar Arguments ..
        Real (Kind=nag_wp), Intent (Out) :: fc
        Real (Kind=nag_wp), Intent (In) :: xc
!       .. Intrinsic Procedures ..
        Intrinsic                      :: sin
!       .. Executable Statements ..
        fc = sin(xc)/xc

        Return

      End Subroutine funct
    End Module e04abfe_mod
    Program e04abfe

!     E04ABF Example Main Program

!     .. Use Statements ..
      Use nag_library, Only: e04abf, nag_wp
      Use e04abfe_mod, Only: funct, nout
!     .. Implicit None Statement ..
      Implicit None
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: a, b, e1, e2, f, x
      Integer                          :: ifail, maxcal
!     .. Executable Statements ..
      Write (nout,*) 'E04ABF Example Program Results'

!     E1 and E2 are set to zero so that E04ABF will reset them to
!     their default values

      e1 = 0.0_nag_wp
      e2 = 0.0_nag_wp

!     The minimum is known to lie in the range (3.5, 5.0)

      a = 3.5_nag_wp
      b = 5.0_nag_wp

!     Allow 30 calls of FUNCT

      maxcal = 30

      ifail = -1
      Call e04abf(funct,e1,e2,a,b,maxcal,x,f,ifail)

      Select Case (ifail)
      Case (0,2)
        Write (nout,*)
        Write (nout,99999) 'The minimum lies in the interval', a, ' to', b
        Write (nout,99999) 'Its estimated position is', x, ','
        Write (nout,99998) 'where the function value is ', f
        Write (nout,99997) maxcal, 'function evaluations were required'
      End Select

99999 Format (1X,A,F11.8,A,F11.8)
99998 Format (1X,A,F7.4)
99997 Format (1X,I2,1X,A)
    End Program e04abfe


e04bbae.f90

!   E04BBA Example Program Text
!   Mark 26 Release. NAG Copyright 2016.
    Module e04bbae_mod

!     E04BBA Example Program Module:
!            Parameters and User-defined Routines

!     .. Use Statements ..
      Use nag_library, Only: nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Accessibility Statements ..
      Private
      Public                           :: funct
!     .. Parameters ..
      Integer, Parameter, Public       :: nout = 6
    Contains
      Subroutine funct(xc,fc,gc,iuser,ruser)
!       Routine to evaluate F(x) and dF/dx at any point in (A, B)

!       .. Scalar Arguments ..
        Real (Kind=nag_wp), Intent (Out) :: fc, gc
        Real (Kind=nag_wp), Intent (In) :: xc
!       .. Array Arguments ..
        Real (Kind=nag_wp), Intent (Inout) :: ruser(*)
        Integer, Intent (Inout)        :: iuser(*)
!       .. Intrinsic Procedures ..
        Intrinsic                      :: cos, sin
!       .. Executable Statements ..
        fc = sin(xc)/xc
        gc = (cos(xc)-fc)/xc

        Return

      End Subroutine funct
    End Module e04bbae_mod
    Program e04bbae

!     E04BBA Example Main Program

!     .. Use Statements ..
      Use nag_library, Only: e04bba, nag_wp
      Use e04bbae_mod, Only: funct, nout
!     .. Implicit None Statement ..
      Implicit None
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: a, b, e1, e2, f, g, x
      Integer                          :: ifail, maxcal
!     .. Local Arrays ..
      Real (Kind=nag_wp)               :: ruser(1)
      Integer                          :: iuser(1)
!     .. Executable Statements ..
      Write (nout,*) 'E04BBA Example Program Results'

!     E1 and E2 are set to zero so that E04BBA will reset them to
!     their default values

      e1 = 0.0_nag_wp
      e2 = 0.0_nag_wp

!     The minimum is known to lie in the range (3.5, 5.0)

      a = 3.5_nag_wp
      b = 5.0_nag_wp

!     Allow 30 calls of FUNCT

      maxcal = 30

      ifail = -1
      Call e04bba(funct,e1,e2,a,b,maxcal,x,f,g,iuser,ruser,ifail)

      Select Case (ifail)
      Case (0,2)
        Write (nout,*)
        Write (nout,99999) 'The minimum lies in the interval', a, ' to', b
        Write (nout,99999) 'Its estimated position is', x, ','
        Write (nout,99998) 'where the function value is ', f
        Write (nout,99997) 'and the gradient is ', g, ' (machine dependent)'
        Write (nout,99996) maxcal, ' calls of FUNCT were required'
      End Select

99999 Format (1X,A,F11.8,A,F11.8)
99998 Format (1X,A,F7.4)
99997 Format (1X,A,1P,E8.1,A)
99996 Format (1X,I2,A)
    End Program e04bbae


e04bbfe.f90

!   E04BBF Example Program Text
!   Mark 26 Release. NAG Copyright 2016.
    Module e04bbfe_mod

!     E04BBF Example Program Module:
!            Parameters and User-defined Routines

!     .. Use Statements ..
      Use nag_library, Only: nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Accessibility Statements ..
      Private
      Public                           :: funct
!     .. Parameters ..
      Integer, Parameter, Public       :: nout = 6
    Contains
      Subroutine funct(xc,fc,gc)
!       Routine to evaluate F(x) and dF/dx at any point in (A, B)

!       .. Scalar Arguments ..
        Real (Kind=nag_wp), Intent (Out) :: fc, gc
        Real (Kind=nag_wp), Intent (In) :: xc
!       .. Intrinsic Procedures ..
        Intrinsic                      :: cos, sin
!       .. Executable Statements ..
        fc = sin(xc)/xc
        gc = (cos(xc)-fc)/xc

        Return

      End Subroutine funct
    End Module e04bbfe_mod
    Program e04bbfe

!     E04BBF Example Main Program

!     .. Use Statements ..
      Use nag_library, Only: e04bbf, nag_wp
      Use e04bbfe_mod, Only: funct, nout
!     .. Implicit None Statement ..
      Implicit None
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: a, b, e1, e2, f, g, x
      Integer                          :: ifail, maxcal
!     .. Executable Statements ..
      Write (nout,*) 'E04BBF Example Program Results'

!     E1 and E2 are set to zero so that E04BBF will reset them to
!     their default values

      e1 = 0.0_nag_wp
      e2 = 0.0_nag_wp

!     The minimum is known to lie in the range (3.5, 5.0)

      a = 3.5_nag_wp
      b = 5.0_nag_wp

!     Allow 30 calls of FUNCT

      maxcal = 30

      ifail = -1
      Call e04bbf(funct,e1,e2,a,b,maxcal,x,f,g,ifail)

      Select Case (ifail)
      Case (0,2)
        Write (nout,*)
        Write (nout,99999) 'The minimum lies in the interval', a, ' to', b
        Write (nout,99999) 'Its estimated position is', x, ','
        Write (nout,99998) 'where the function value is ', f
        Write (nout,99997) 'and the gradient is ', g, ' (machine dependent)'
        Write (nout,99996) maxcal, ' calls of FUNCT were required'
      End Select

99999 Format (1X,A,F11.8,A,F11.8)
99998 Format (1X,A,F7.4)
99997 Format (1X,A,1P,E8.1,A)
99996 Format (1X,I2,A)
    End Program e04bbfe


e04cbfe.f90

!   E04CBF Example Program Text
!   Mark 26 Release. NAG Copyright 2016.
    Module e04cbfe_mod

!     E04CBF Example Program Module:
!            Parameters and User-defined Routines

!     .. Use Statements ..
      Use nag_library, Only: nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Accessibility Statements ..
      Private
      Public                           :: funct, monit
!     .. Parameters ..
      Integer, Parameter, Public       :: nout = 6
    Contains
      Subroutine funct(n,xc,fc,iuser,ruser)

!       .. Scalar Arguments ..
        Real (Kind=nag_wp), Intent (Out) :: fc
        Integer, Intent (In)           :: n
!       .. Array Arguments ..
        Real (Kind=nag_wp), Intent (Inout) :: ruser(*)
        Real (Kind=nag_wp), Intent (In) :: xc(n)
        Integer, Intent (Inout)        :: iuser(*)
!       .. Intrinsic Procedures ..
        Intrinsic                      :: exp
!       .. Executable Statements ..
        fc = exp(xc(1))*(4.0_nag_wp*xc(1)*(xc(1)+xc(2))+2.0_nag_wp*xc(2)*(xc(2 &
          )+1.0_nag_wp)+1.0_nag_wp)

        Return

      End Subroutine funct
      Subroutine monit(fmin,fmax,sim,n,ncall,serror,vratio,iuser,ruser)

!       .. Scalar Arguments ..
        Real (Kind=nag_wp), Intent (In) :: fmax, fmin, serror, vratio
        Integer, Intent (In)           :: n, ncall
!       .. Array Arguments ..
        Real (Kind=nag_wp), Intent (Inout) :: ruser(*)
        Real (Kind=nag_wp), Intent (In) :: sim(n+1,n)
        Integer, Intent (Inout)        :: iuser(*)
!       .. Executable Statements ..
        Write (nout,*)
        Write (nout,99999) ncall
        Write (nout,99998) fmin
        Write (nout,99997)
        Write (nout,99996) sim(1:(n+1),1:n)
        Write (nout,99995) serror
        Write (nout,99994) vratio

        Return

99999   Format (1X,'There have been',I5,' function calls')
99998   Format (1X,'The smallest function value is',F10.4)
99997   Format (1X,'The simplex is')
99996   Format (1X,2F10.4)
99995   Format (1X,'The standard deviation in function values at the ',        &
          'vertices of the simplex is',F10.4)
99994   Format (1X,'The linearized volume ratio of the current simplex',       &
          ' to the starting one is',F10.4)
      End Subroutine monit
    End Module e04cbfe_mod
    Program e04cbfe

!     E04CBF Example Main Program

!     .. Use Statements ..
      Use nag_library, Only: e04cbf, e04cbk, nag_wp, x02ajf
      Use e04cbfe_mod, Only: funct, monit, nout
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: n = 2
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: f, tolf, tolx
      Integer                          :: ifail, maxcal
      Logical                          :: monitoring
!     .. Local Arrays ..
      Real (Kind=nag_wp)               :: ruser(1), x(n)
      Integer                          :: iuser(1)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: sqrt
!     .. Executable Statements ..
      Write (nout,*) 'E04CBF Example Program Results'

!     Set MONITORING to .TRUE. to obtain monitoring information

      monitoring = .False.

      x(1:n) = (/-1.0_nag_wp,1.0_nag_wp/)
      tolf = sqrt(x02ajf())
      tolx = sqrt(tolf)
      maxcal = 100

      ifail = 0

      If (.Not. monitoring) Then

        Call e04cbf(n,x,f,tolf,tolx,funct,e04cbk,maxcal,iuser,ruser,ifail)

      Else

        Call e04cbf(n,x,f,tolf,tolx,funct,monit,maxcal,iuser,ruser,ifail)

      End If

      Write (nout,*)
      Write (nout,99999) f
      Write (nout,99998) x(1:n)

99999 Format (1X,'The final function value is',F12.4)
99998 Format (1X,'at the point',2F12.4)
    End Program e04cbfe


e04dgae.f90

!   E04DGA Example Program Text
!   Mark 26 Release. NAG Copyright 2016.
    Module e04dgae_mod

!     E04DGA Example Program Module:
!            Parameters and User-defined Routines

!     .. Use Statements ..
      Use nag_library, Only: nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Accessibility Statements ..
      Private
      Public                           :: objfun
!     .. Parameters ..
      Integer, Parameter, Public       :: lcwsav = 1, liwsav = 610,            &
                                          llwsav = 120, lrwsav = 475, nin = 5, &
                                          nout = 6
    Contains
      Subroutine objfun(mode,n,x,objf,objgrd,nstate,iuser,ruser)
!       Routine to evaluate F(x) and its 1st derivatives.

!       .. Scalar Arguments ..
        Real (Kind=nag_wp), Intent (Out) :: objf
        Integer, Intent (Inout)        :: mode
        Integer, Intent (In)           :: n, nstate
!       .. Array Arguments ..
        Real (Kind=nag_wp), Intent (Out) :: objgrd(n)
        Real (Kind=nag_wp), Intent (Inout) :: ruser(*)
        Real (Kind=nag_wp), Intent (In) :: x(n)
        Integer, Intent (Inout)        :: iuser(*)
!       .. Local Scalars ..
        Real (Kind=nag_wp)             :: expx1, x1, x2
!       .. Intrinsic Procedures ..
        Intrinsic                      :: exp
!       .. Executable Statements ..
        x1 = x(1)
        x2 = x(2)
        expx1 = exp(x1)
        objf = expx1*(4.0_nag_wp*x1**2+2.0_nag_wp*x2**2+4.0_nag_wp*x1*x2+      &
          2.0_nag_wp*x2+1.0_nag_wp)

        If (mode==2) Then
          objgrd(1:n) = (/4.0_nag_wp*expx1*(2.0_nag_wp*x1+x2)+objf,            &
            2.0_nag_wp*expx1*(2.0_nag_wp*x2+2.0_nag_wp*x1+1.0_nag_wp)/)
        End If

        Return

      End Subroutine objfun
    End Module e04dgae_mod
    Program e04dgae

!     E04DGA Example Main Program

!     .. Use Statements ..
      Use nag_library, Only: e04dga, e04wbf, nag_wp
      Use e04dgae_mod, Only: lcwsav, liwsav, llwsav, lrwsav, nin, nout, objfun
!     .. Implicit None Statement ..
      Implicit None
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: objf
      Integer                          :: i, ifail, iter, n
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: objgrd(:), work(:), x(:)
      Real (Kind=nag_wp)               :: rwsav(lrwsav), user(1)
      Integer                          :: iuser(1), iwsav(liwsav)
      Integer, Allocatable             :: iwork(:)
      Logical                          :: lwsav(llwsav)
      Character (80)                   :: cwsav(lcwsav)
!     .. Executable Statements ..
      Write (nout,*) 'E04DGA Example Program Results'

!     Skip heading in data file
      Read (nin,*)

      Read (nin,*) n
      Allocate (iwork(n+1),objgrd(n),x(n),work(13*n))

      Read (nin,*) x(1:n)

!     Initialise E04DGA

      ifail = 0
      Call e04wbf('E04DGA',cwsav,lcwsav,lwsav,llwsav,iwsav,liwsav,rwsav,       &
        lrwsav,ifail)

!     Solve the problem

      ifail = -1
      Call e04dga(n,objfun,iter,objf,objgrd,x,iwork,work,iuser,user,lwsav,     &
        iwsav,rwsav,ifail)

      Select Case (ifail)
      Case (0:8)
        Write (nout,*)
        Write (nout,99999)
        Write (nout,*)

        Do i = 1, n
          Write (nout,99998) i, x(i), objgrd(i)
        End Do

        Write (nout,*)
        Write (nout,*)
        Write (nout,99997) objf
      End Select

99999 Format (1X,'Variable',10X,'Value',8X,'Gradient value')
99998 Format (1X,'Varbl',1X,I3,4X,1P,G15.7,4X,1P,G9.1)
99997 Format (1X,'Final objective value = ',G15.7)
    End Program e04dgae


e04dgfe.f90

!   E04DGF Example Program Text
!   Mark 26 Release. NAG Copyright 2016.
    Module e04dgfe_mod

!     E04DGF Example Program Module:
!            Parameters and User-defined Routines

!     .. Use Statements ..
      Use nag_library, Only: nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Accessibility Statements ..
      Private
      Public                           :: objfun
!     .. Parameters ..
      Integer, Parameter, Public       :: nin = 5, nout = 6
    Contains
      Subroutine objfun(mode,n,x,objf,objgrd,nstate,iuser,ruser)
!       Routine to evaluate F(x) and its 1st derivatives.

!       .. Scalar Arguments ..
        Real (Kind=nag_wp), Intent (Out) :: objf
        Integer, Intent (Inout)        :: mode
        Integer, Intent (In)           :: n, nstate
!       .. Array Arguments ..
        Real (Kind=nag_wp), Intent (Out) :: objgrd(n)
        Real (Kind=nag_wp), Intent (Inout) :: ruser(*)
        Real (Kind=nag_wp), Intent (In) :: x(n)
        Integer, Intent (Inout)        :: iuser(*)
!       .. Local Scalars ..
        Real (Kind=nag_wp)             :: expx1, x1, x2
!       .. Intrinsic Procedures ..
        Intrinsic                      :: exp
!       .. Executable Statements ..
        x1 = x(1)
        x2 = x(2)
        expx1 = exp(x1)
        objf = expx1*(4.0_nag_wp*x1**2+2.0_nag_wp*x2**2+4.0_nag_wp*x1*x2+      &
          2.0_nag_wp*x2+1.0_nag_wp)

        If (mode==2) Then
          objgrd(1:n) = (/4.0_nag_wp*expx1*(2.0_nag_wp*x1+x2)+objf,            &
            2.0_nag_wp*expx1*(2.0_nag_wp*x2+2.0_nag_wp*x1+1.0_nag_wp)/)
        End If

        Return

      End Subroutine objfun
    End Module e04dgfe_mod
    Program e04dgfe

!     E04DGF Example Main Program

!     .. Use Statements ..
      Use nag_library, Only: e04dgf, nag_wp
      Use e04dgfe_mod, Only: nin, nout, objfun
!     .. Implicit None Statement ..
      Implicit None
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: objf
      Integer                          :: ifail, iter, n
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: objgrd(:), work(:), x(:)
      Real (Kind=nag_wp)               :: ruser(1)
      Integer                          :: iuser(1)
      Integer, Allocatable             :: iwork(:)
!     .. Executable Statements ..
      Write (nout,*) 'E04DGF Example Program Results'
      Flush (nout)

!     Skip heading in data file
      Read (nin,*)

      Read (nin,*) n
      Allocate (iwork(n+1),objgrd(n),x(n),work(13*n))

      Read (nin,*) x(1:n)

!     Solve the problem

      ifail = -1
      Call e04dgf(n,objfun,iter,objf,objgrd,x,iwork,work,iuser,ruser,ifail)

    End Program e04dgfe


e04djae.f90

!   E04DJA Example Program Text
!   Mark 26 Release. NAG Copyright 2016.
    Module e04djae_mod

!     E04DJA Example Program Module:
!            Parameters and User-defined Routines

!     .. Use Statements ..
      Use nag_library, Only: nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Accessibility Statements ..
      Private
      Public                           :: objfn1
!     .. Parameters ..
      Integer, Parameter, Public       :: iset = 1, lcwsav = 1, liwsav = 610,  &
                                          llwsav = 120, lrwsav = 475, nin = 5, &
                                          ninopt = 7, nout = 6
    Contains
      Subroutine objfn2(mode,n,x,objf,objgrd,nstate,iuser,ruser)
!       Routine to evaluate F(x)

!       .. Scalar Arguments ..
        Real (Kind=nag_wp), Intent (Out) :: objf
        Integer, Intent (Inout)        :: mode
        Integer, Intent (In)           :: n, nstate
!       .. Array Arguments ..
        Real (Kind=nag_wp), Intent (Out) :: objgrd(n)
        Real (Kind=nag_wp), Intent (Inout) :: ruser(*)
        Real (Kind=nag_wp), Intent (In) :: x(n)
        Integer, Intent (Inout)        :: iuser(*)
!       .. Local Scalars ..
        Real (Kind=nag_wp)             :: x1, x2
!       .. Intrinsic Procedures ..
        Intrinsic                      :: exp
!       .. Executable Statements ..
        x1 = x(1)
        x2 = x(2)

        objf = exp(x1)*(4.0_nag_wp*x1**2+2.0_nag_wp*x2**2+4.0_nag_wp*x1*x2+    &
          2.0_nag_wp*x2+1.0_nag_wp)

        Return

      End Subroutine objfn2
      Subroutine objfn1(mode,n,x,objf,objgrd,nstate,iuser,ruser)
!       Routine to evaluate F(x) and approximate its 1st derivatives

!       .. Use Statements ..
        Use nag_library, Only: e04xaf
!       .. Scalar Arguments ..
        Real (Kind=nag_wp), Intent (Out) :: objf
        Integer, Intent (Inout)        :: mode
        Integer, Intent (In)           :: n, nstate
!       .. Array Arguments ..
        Real (Kind=nag_wp), Intent (Out) :: objgrd(n)
        Real (Kind=nag_wp), Intent (Inout) :: ruser(*)
        Real (Kind=nag_wp), Intent (In) :: x(n)
        Integer, Intent (Inout)        :: iuser(*)
!       .. Local Scalars ..
        Real (Kind=nag_wp)             :: epsrf
        Integer                        :: ifail, imode, iwarn, ldh, msglvl
!       .. Local Arrays ..
        Real (Kind=nag_wp), Allocatable :: h(:,:), hcntrl(:), hforw(:),        &
                                          work(:), xcopy(:)
        Integer, Allocatable           :: info(:)
!       .. Executable Statements ..
        Select Case (mode)
        Case (0)

!         Evaluate F(x) only

          Call objfn2(mode,n,x,objf,objgrd,nstate,iuser,ruser)

        Case (2)

!         Evaluate F(x) and approximate its 1st derivatives

          imode = 0
          ldh = n
          Allocate (info(n),hforw(n),hcntrl(n),h(ldh,1),work(n),xcopy(n))
          xcopy(1:n) = x(1:n)
          hforw(1:n) = 0.0_nag_wp
          msglvl = 0
          epsrf = 0.0_nag_wp

          ifail = 1
          Call e04xaf(msglvl,n,epsrf,xcopy,imode,objfn2,ldh,hforw,objf,objgrd, &
            hcntrl,h,iwarn,work,iuser,ruser,info,ifail)

        End Select

        Return

      End Subroutine objfn1
    End Module e04djae_mod
    Program e04djae

!     E04DJA Example Main Program

!     .. Use Statements ..
      Use nag_library, Only: e04dga, e04dja, e04dka, e04wbf, nag_wp, x04abf,   &
                             x04acf, x04baf
      Use e04djae_mod, Only: iset, lcwsav, liwsav, llwsav, lrwsav, nin,        &
                             ninopt, nout, objfn1
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Character (*), Parameter         :: fname = 'e04djae.opt'
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: objf
      Integer                          :: i, ifail, inform, iter, mode, n,     &
                                          outchn
      Character (80)                   :: rec
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: objgrd(:), work(:), x(:)
      Real (Kind=nag_wp)               :: ruser(1), rwsav(lrwsav)
      Integer                          :: iuser(1), iwsav(liwsav)
      Integer, Allocatable             :: iwork(:)
      Logical                          :: lwsav(llwsav)
      Character (80)                   :: cwsav(lcwsav)
!     .. Executable Statements ..
      Write (rec,99995) 'E04DJA Example Program Results'
      Call x04baf(nout,rec)

!     Skip heading in data file
      Read (nin,*)

      Read (nin,*) n
      Allocate (iwork(n+1),objgrd(n),x(n),work(13*n))

!     Set the unit number for advisory messages to OUTCHN

      outchn = nout
      Call x04abf(iset,outchn)

      Read (nin,*) x(1:n)

!     Initialise using E04WBF

      ifail = 0
      Call e04wbf('E04DGA',cwsav,lcwsav,lwsav,llwsav,iwsav,liwsav,rwsav,       &
        lrwsav,ifail)

!     Set two options using E04DKA

      Call e04dka(' Verify Level = -1 ',lwsav,iwsav,rwsav,inform)

      If (inform==0) Then

        Call e04dka(' Maximum Step Length = 100.0 ',lwsav,iwsav,rwsav,inform)

      End If

      If (inform/=0) Then
        Write (rec,99996) 'E04DKA terminated with INFORM = ', inform

        Call x04baf(nout,rec)

        Go To 100
      End If

!     Open the options file for reading

      mode = 0

      ifail = 0
      Call x04acf(ninopt,fname,mode,ifail)

!     Read the options file for the remaining options

      Call e04dja(ninopt,lwsav,iwsav,rwsav,inform)

      If (inform/=0) Then
        Write (rec,99996) 'E04DJA terminated with INFORM = ', inform

        Call x04baf(nout,rec)

        Go To 100
      End If

!     Solve the problem

      ifail = -1
      Call e04dga(n,objfn1,iter,objf,objgrd,x,iwork,work,iuser,ruser,lwsav,    &
        iwsav,rwsav,ifail)

      Select Case (ifail)
      Case (0:8)
        Write (rec,'()')
        Call x04baf(nout,rec)
        Write (rec,99999)
        Call x04baf(nout,rec)
        Write (rec,'()')
        Call x04baf(nout,rec)

        Do i = 1, n
          Write (rec,99998) i, x(i), objgrd(i)
          Call x04baf(nout,rec)
        End Do

        Write (rec,'()')
        Call x04baf(nout,rec)
        Write (rec,'()')
        Call x04baf(nout,rec)
        Write (rec,99997) objf
        Call x04baf(nout,rec)
      End Select

100   Continue

99999 Format (1X,'Variable',10X,'Value',8X,'Gradient value')
99998 Format (1X,'Varbl',1X,I3,4X,1P,G15.7,4X,1P,G9.1)
99997 Format (1X,'Final objective value = ',G15.7)
99996 Format (1X,A,I5)
99995 Format (1X,A)
    End Program e04djae


e04djfe.f90

!   E04DJF Example Program Text
!   Mark 26 Release. NAG Copyright 2016.
    Module e04djfe_mod

!     E04DJF Example Program Module:
!            Parameters and User-defined Routines

!     .. Use Statements ..
      Use nag_library, Only: nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Accessibility Statements ..
      Private
      Public                           :: objfn1
!     .. Parameters ..
      Integer, Parameter, Public       :: nin = 5, ninopt = 7, nout = 6
    Contains
      Subroutine objfn2(mode,n,x,objf,objgrd,nstate,iuser,ruser)
!       Routine to evaluate F(x)

!       .. Scalar Arguments ..
        Real (Kind=nag_wp), Intent (Out) :: objf
        Integer, Intent (Inout)        :: mode
        Integer, Intent (In)           :: n, nstate
!       .. Array Arguments ..
        Real (Kind=nag_wp), Intent (Out) :: objgrd(n)
        Real (Kind=nag_wp), Intent (Inout) :: ruser(*)
        Real (Kind=nag_wp), Intent (In) :: x(n)
        Integer, Intent (Inout)        :: iuser(*)
!       .. Local Scalars ..
        Real (Kind=nag_wp)             :: x1, x2
!       .. Intrinsic Procedures ..
        Intrinsic                      :: exp
!       .. Executable Statements ..
        x1 = x(1)
        x2 = x(2)

        objf = exp(x1)*(4.0_nag_wp*x1**2+2.0_nag_wp*x2**2+4.0_nag_wp*x1*x2+    &
          2.0_nag_wp*x2+1.0_nag_wp)

        Return

      End Subroutine objfn2
      Subroutine objfn1(mode,n,x,objf,objgrd,nstate,iuser,ruser)
!       Routine to evaluate F(x) and approximate its 1st derivatives

!       .. Use Statements ..
        Use nag_library, Only: e04xaf
!       .. Scalar Arguments ..
        Real (Kind=nag_wp), Intent (Out) :: objf
        Integer, Intent (Inout)        :: mode
        Integer, Intent (In)           :: n, nstate
!       .. Array Arguments ..
        Real (Kind=nag_wp), Intent (Out) :: objgrd(n)
        Real (Kind=nag_wp), Intent (Inout) :: ruser(*)
        Real (Kind=nag_wp), Intent (In) :: x(n)
        Integer, Intent (Inout)        :: iuser(*)
!       .. Local Scalars ..
        Real (Kind=nag_wp)             :: epsrf
        Integer                        :: ifail, imode, iwarn, ldh, msglvl
!       .. Local Arrays ..
        Real (Kind=nag_wp), Allocatable :: h(:,:), hcntrl(:), hforw(:),        &
                                          work(:), xcopy(:)
        Integer, Allocatable           :: info(:)
!       .. Executable Statements ..
        Select Case (mode)
        Case (0)

!         Evaluate F(x) only

          Call objfn2(mode,n,x,objf,objgrd,nstate,iuser,ruser)

        Case (2)

!         Evaluate F(x) and approximate its 1st derivatives

          imode = 0
          ldh = n
          Allocate (info(n),hforw(n),hcntrl(n),h(ldh,1),work(n),xcopy(n))
          xcopy(1:n) = x(1:n)
          hforw(1:n) = 0.0_nag_wp
          msglvl = 0
          epsrf = 0.0_nag_wp

          ifail = 1
          Call e04xaf(msglvl,n,epsrf,xcopy,imode,objfn2,ldh,hforw,objf,objgrd, &
            hcntrl,h,iwarn,work,iuser,ruser,info,ifail)

        End Select

        Return

      End Subroutine objfn1
    End Module e04djfe_mod
    Program e04djfe

!     E04DJF Example Main Program

!     .. Use Statements ..
      Use nag_library, Only: e04dgf, e04djf, e04dkf, nag_wp, x04abf, x04acf,   &
                             x04baf
      Use e04djfe_mod, Only: nin, ninopt, nout, objfn1
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Character (*), Parameter         :: fname = 'e04djfe.opt'
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: objf
      Integer                          :: ifail, inform, iter, mode, n, outchn
      Character (80)                   :: rec
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: objgrd(:), work(:), x(:)
      Real (Kind=nag_wp)               :: ruser(1)
      Integer                          :: iuser(1)
      Integer, Allocatable             :: iwork(:)
!     .. Executable Statements ..
      Write (rec,99998) 'E04DJF Example Program Results'
      Call x04baf(nout,rec)

!     Skip heading in data file
      Read (nin,*)

      Read (nin,*) n
      Allocate (iwork(n+1),objgrd(n),x(n),work(13*n))

!     Set the unit number for advisory messages to OUTCHN

      outchn = nout
      Call x04abf(1,outchn)

      Read (nin,*) x(1:n)

!     Set two options using E04DKF

      Call e04dkf(' Verify Level = -1 ')

      Call e04dkf(' Maximum Step Length = 100.0 ')

!     Open the options file for reading

      mode = 0

      ifail = 0
      Call x04acf(ninopt,fname,mode,ifail)

!     Read the options file for the remaining options

      Call e04djf(ninopt,inform)

      If (inform/=0) Then
        Write (rec,99999) 'E04DJF terminated with INFORM = ', inform

        Call x04baf(nout,rec)

        Go To 100
      End If

!     Solve the problem

      ifail = -1
      Call e04dgf(n,objfn1,iter,objf,objgrd,x,iwork,work,iuser,ruser,ifail)

100   Continue

99999 Format (1X,A,I5)
99998 Format (1X,A)
    End Program e04djfe


e04fcfe.f90

!   E04FCF Example Program Text
!   Mark 26 Release. NAG Copyright 2016.
    Module e04fcfe_mod

!     E04FCF Example Program Module:
!            Parameters and User-defined Routines

!     .. Use Statements ..
      Use nag_library, Only: nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Accessibility Statements ..
      Private
      Public                           :: lsqfun, lsqgrd, lsqmon
!     .. Parameters ..
      Real (Kind=nag_wp), Parameter    :: one = 1.0_nag_wp
      Real (Kind=nag_wp), Parameter    :: two = 2.0_nag_wp
      Real (Kind=nag_wp), Parameter    :: zero = 0.0_nag_wp
      Integer, Parameter               :: inc1 = 1
      Integer, Parameter, Public       :: liw = 1, m = 15, n = 3, nin = 5,     &
                                          nout = 6, nt = 3
      Integer, Parameter, Public       :: ldfjac = m
      Integer, Parameter, Public       :: ldv = n
      Integer, Parameter, Public       :: lw = 6*n + m*n + 2*m + n*(n-1)/2
      Character (1), Parameter         :: trans = 'T'
!     .. Local Arrays ..
      Real (Kind=nag_wp), Public, Save :: t(m,nt), y(m)
    Contains
      Subroutine lsqgrd(m,n,fvec,fjac,ldfjac,g)
!       Routine to evaluate gradient of the sum of squares

!       .. Use Statements ..
        Use nag_library, Only: dgemv
!       .. Scalar Arguments ..
        Integer, Intent (In)           :: ldfjac, m, n
!       .. Array Arguments ..
        Real (Kind=nag_wp), Intent (In) :: fjac(ldfjac,n), fvec(m)
        Real (Kind=nag_wp), Intent (Out) :: g(n)
!       .. Executable Statements ..
!       The NAG name equivalent of dgemv is f06paf
        Call dgemv(trans,m,n,one,fjac,ldfjac,fvec,inc1,zero,g,inc1)

        g(1:n) = two*g(1:n)

        Return

      End Subroutine lsqgrd
      Subroutine lsqfun(iflag,m,n,xc,fvec,iw,liw,w,lw)

!       Routine to evaluate the residuals

!       .. Scalar Arguments ..
        Integer, Intent (Inout)        :: iflag
        Integer, Intent (In)           :: liw, lw, m, n
!       .. Array Arguments ..
        Real (Kind=nag_wp), Intent (Out) :: fvec(m)
        Real (Kind=nag_wp), Intent (Inout) :: w(lw)
        Real (Kind=nag_wp), Intent (In) :: xc(n)
        Integer, Intent (Inout)        :: iw(liw)
!       .. Executable Statements ..
        fvec(1:m) = xc(1) + t(1:m,1)/(xc(2)*t(1:m,2)+xc(3)*t(1:m,3)) - y(1:m)

        Return

      End Subroutine lsqfun
      Subroutine lsqmon(m,n,xc,fvec,fjac,ldfjac,s,igrade,niter,nf,iw,liw,w,lw)
!       Monitoring routine

!       .. Use Statements ..
        Use nag_library, Only: ddot
!       .. Parameters ..
        Integer, Parameter             :: ndec = 3
!       .. Scalar Arguments ..
        Integer, Intent (In)           :: igrade, ldfjac, liw, lw, m, n, nf,   &
                                          niter
!       .. Array Arguments ..
        Real (Kind=nag_wp), Intent (In) :: fjac(ldfjac,n), fvec(m), s(n),      &
                                          xc(n)
        Real (Kind=nag_wp), Intent (Inout) :: w(lw)
        Integer, Intent (Inout)        :: iw(liw)
!       .. Local Scalars ..
        Real (Kind=nag_wp)             :: fsumsq, gtg
        Integer                        :: j
!       .. Local Arrays ..
        Real (Kind=nag_wp)             :: g(ndec)
!       .. Executable Statements ..
!       The NAG name equivalent of ddot is f06eaf
        fsumsq = ddot(m,fvec,inc1,fvec,inc1)

        Call lsqgrd(m,n,fvec,fjac,ldfjac,g)

        gtg = ddot(n,g,inc1,g,inc1)

        Write (nout,*)
        Write (nout,*)                                                         &
          '  Itn      F evals        SUMSQ             GTG        Grade'
        Write (nout,99999) niter, nf, fsumsq, gtg, igrade
        Write (nout,*)
        Write (nout,*)                                                         &
          '       X                    G           Singular values'

        Write (nout,99998)(xc(j),g(j),s(j),j=1,n)

        Return

99999   Format (1X,I4,6X,I5,6X,1P,E13.5,6X,1P,E9.1,6X,I3)
99998   Format (1X,1P,E13.5,10X,1P,E9.1,10X,1P,E9.1)
      End Subroutine lsqmon
    End Module e04fcfe_mod
    Program e04fcfe

!     E04FCF Example Main Program

!     .. Use Statements ..
      Use nag_library, Only: e04fcf, nag_wp, x02ajf
      Use e04fcfe_mod, Only: ldfjac, ldv, liw, lsqfun, lsqgrd, lsqmon, lw, m,  &
                             n, nin, nout, nt, t, y
!     .. Implicit None Statement ..
      Implicit None
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: eta, fsumsq, stepmx, xtol
      Integer                          :: i, ifail, iprint, maxcal, nf, niter
!     .. Local Arrays ..
      Real (Kind=nag_wp)               :: fjac(m,n), fvec(m), g(n), s(n),      &
                                          v(ldv,n), w(lw), x(n)
      Integer                          :: iw(liw)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: sqrt
!     .. Executable Statements ..
      Write (nout,*) 'E04FCF Example Program Results'

!     Skip heading in data file
      Read (nin,*)

!     Observations of TJ (J = 1, 2, ..., nt) are held in T(I, J)
!     (I = 1, 2, ..., m)

      Do i = 1, m
        Read (nin,*) y(i), t(i,1:nt)
      End Do

!     Set IPRINT to 1 to obtain output from LSQMON at each iteration

      iprint = -1

      maxcal = 400*n
      eta = 0.5_nag_wp
      xtol = 10.0_nag_wp*sqrt(x02ajf())

!     We estimate that the minimum will be within 10 units of the
!     starting point

      stepmx = 10.0_nag_wp

!     Set up the starting point

      x(1:nt) = (/0.5_nag_wp,1.0_nag_wp,1.5_nag_wp/)

      ifail = -1
      Call e04fcf(m,n,lsqfun,lsqmon,iprint,maxcal,eta,xtol,stepmx,x,fsumsq,    &
        fvec,fjac,ldfjac,s,v,ldv,niter,nf,iw,liw,w,lw,ifail)

      Select Case (ifail)
      Case (0,2:)
        Write (nout,*)
        Write (nout,99999) 'On exit, the sum of squares is', fsumsq
        Write (nout,99999) 'at the point', x(1:n)

        Call lsqgrd(m,n,fvec,fjac,ldfjac,g)

        Write (nout,99998) 'The estimated gradient is', g(1:n)
        Write (nout,*) '                           (machine dependent)'
        Write (nout,*) 'and the residuals are'
        Write (nout,99997) fvec(1:m)
      End Select

99999 Format (1X,A,3F12.4)
99998 Format (1X,A,1P,3E12.3)
99997 Format (1X,1P,E9.1)
    End Program e04fcfe


e04fyfe.f90

!   E04FYF Example Program Text
!   Mark 26 Release. NAG Copyright 2016.
    Module e04fyfe_mod

!     E04FYF Example Program Module:
!            Parameters and User-defined Routines

!     .. Use Statements ..
      Use nag_library, Only: nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Accessibility Statements ..
      Private
      Public                           :: lsfun1
!     .. Parameters ..
      Integer, Parameter, Public       :: m = 15, n = 3, nin = 5, nout = 6,    &
                                          nt = 3
      Integer, Parameter, Public       :: lw = 7*n + n*n + 2*m*n + 3*m + n*(n- &
                                          1)/2
!     .. Local Arrays ..
      Real (Kind=nag_wp), Public, Save :: t(m,nt), y(m)
    Contains
      Subroutine lsfun1(m,n,xc,fvec,iuser,ruser)

!       .. Scalar Arguments ..
        Integer, Intent (In)           :: m, n
!       .. Array Arguments ..
        Real (Kind=nag_wp), Intent (Out) :: fvec(m)
        Real (Kind=nag_wp), Intent (Inout) :: ruser(*)
        Real (Kind=nag_wp), Intent (In) :: xc(n)
        Integer, Intent (Inout)        :: iuser(*)
!       .. Executable Statements ..
        fvec(1:m) = xc(1) + t(1:m,1)/(xc(2)*t(1:m,2)+xc(3)*t(1:m,3)) - y(1:m)

        Return

      End Subroutine lsfun1
    End Module e04fyfe_mod
    Program e04fyfe

!     E04FYF Example Main Program

!     .. Use Statements ..
      Use nag_library, Only: e04fyf, nag_wp
      Use e04fyfe_mod, Only: lsfun1, lw, m, n, nin, nout, nt, t, y
!     .. Implicit None Statement ..
      Implicit None
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: fsumsq
      Integer                          :: i, ifail
!     .. Local Arrays ..
      Real (Kind=nag_wp)               :: ruser(1), w(lw), x(n)
      Integer                          :: iuser(1)
!     .. Executable Statements ..
      Write (nout,*) 'E04FYF Example Program Results'

!     Skip heading in data file
      Read (nin,*)

!     Observations of TJ (J = 1, 2, ..., nt) are held in T(I, J)
!     (I = 1, 2, ..., m)

      Do i = 1, m
        Read (nin,*) y(i), t(i,1:nt)
      End Do

      x(1:nt) = (/0.5_nag_wp,1.0_nag_wp,1.5_nag_wp/)

      ifail = -1
      Call e04fyf(m,n,lsfun1,x,fsumsq,w,lw,iuser,ruser,ifail)

      Select Case (ifail)
      Case (0,2:)
        Write (nout,*)
        Write (nout,99999) 'On exit, the sum of squares is', fsumsq
        Write (nout,99999) 'at the point', x(1:n)
      End Select

99999 Format (1X,A,3F12.4)
    End Program e04fyfe


e04gbfe.f90

!   E04GBF Example Program Text
!   Mark 26 Release. NAG Copyright 2016.
    Module e04gbfe_mod

!     E04GBF Example Program Module:
!            Parameters and User-defined Routines

!     .. Use Statements ..
      Use nag_library, Only: nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Accessibility Statements ..
      Private
      Public                           :: lsqfun, lsqgrd, lsqmon
!     .. Parameters ..
      Real (Kind=nag_wp), Parameter    :: one = 1.0_nag_wp
      Real (Kind=nag_wp), Parameter    :: two = 2.0_nag_wp
      Real (Kind=nag_wp), Parameter    :: zero = 0.0_nag_wp
      Integer, Parameter               :: inc1 = 1
      Integer, Parameter, Public       :: liw = 1, m = 15, n = 3, nin = 5,     &
                                          nout = 6, nt = 3
      Integer, Parameter, Public       :: ldfjac = m
      Integer, Parameter, Public       :: ldv = n
      Integer, Parameter, Public       :: lw = 7*n + m*n + 2*m + n*n
      Character (1), Parameter         :: trans = 'T'
!     .. Local Arrays ..
      Real (Kind=nag_wp), Public, Save :: t(m,nt), y(m)
    Contains
      Subroutine lsqgrd(m,n,fvec,fjac,ldfjac,g)
!       Routine to evaluate gradient of the sum of squares

!       .. Use Statements ..
        Use nag_library, Only: dgemv
!       .. Scalar Arguments ..
        Integer, Intent (In)           :: ldfjac, m, n
!       .. Array Arguments ..
        Real (Kind=nag_wp), Intent (In) :: fjac(ldfjac,n), fvec(m)
        Real (Kind=nag_wp), Intent (Out) :: g(n)
!       .. Executable Statements ..
!       The NAG name equivalent of dgemv is f06paf
        Call dgemv(trans,m,n,one,fjac,ldfjac,fvec,inc1,zero,g,inc1)

        g(1:n) = two*g(1:n)

        Return

      End Subroutine lsqgrd
      Subroutine lsqfun(iflag,m,n,xc,fvec,fjac,ldfjac,iw,liw,w,lw)

!       Routine to evaluate the residuals and their 1st derivatives.
!       This routine is also suitable for use when E04FCV is used as
!       LSQLIN, since it can deal with IFLAG = 0 as well as IFLAG = 2.

!       .. Scalar Arguments ..
        Integer, Intent (Inout)        :: iflag
        Integer, Intent (In)           :: ldfjac, liw, lw, m, n
!       .. Array Arguments ..
        Real (Kind=nag_wp), Intent (Inout) :: fjac(ldfjac,n), w(lw)
        Real (Kind=nag_wp), Intent (Out) :: fvec(m)
        Real (Kind=nag_wp), Intent (In) :: xc(n)
        Integer, Intent (Inout)        :: iw(liw)
!       .. Local Scalars ..
        Real (Kind=nag_wp)             :: denom, dummy
        Integer                        :: i
!       .. Executable Statements ..
        Do i = 1, m
          denom = xc(2)*t(i,2) + xc(3)*t(i,3)
          fvec(i) = xc(1) + t(i,1)/denom - y(i)

          If (iflag/=0) Then
            fjac(i,1) = one
            dummy = -one/(denom*denom)
            fjac(i,2) = t(i,1)*t(i,2)*dummy
            fjac(i,3) = t(i,1)*t(i,3)*dummy
          End If

        End Do

        Return

      End Subroutine lsqfun
      Subroutine lsqmon(m,n,xc,fvec,fjac,ldfjac,s,igrade,niter,nf,iw,liw,w,lw)
!       Monitoring routine

!       .. Use Statements ..
        Use nag_library, Only: ddot
!       .. Parameters ..
        Integer, Parameter             :: ndec = 3
!       .. Scalar Arguments ..
        Integer, Intent (In)           :: igrade, ldfjac, liw, lw, m, n, nf,   &
                                          niter
!       .. Array Arguments ..
        Real (Kind=nag_wp), Intent (In) :: fjac(ldfjac,n), fvec(m), s(n),      &
                                          xc(n)
        Real (Kind=nag_wp), Intent (Inout) :: w(lw)
        Integer, Intent (Inout)        :: iw(liw)
!       .. Local Scalars ..
        Real (Kind=nag_wp)             :: fsumsq, gtg
        Integer                        :: j
!       .. Local Arrays ..
        Real (Kind=nag_wp)             :: g(ndec)
!       .. Executable Statements ..
!       The NAG name equivalent of ddot is f06eaf
        fsumsq = ddot(m,fvec,inc1,fvec,inc1)

        Call lsqgrd(m,n,fvec,fjac,ldfjac,g)

        gtg = ddot(n,g,inc1,g,inc1)

        Write (nout,*)
        Write (nout,*)                                                         &
          '  Itn      F evals        SUMSQ             GTG        Grade'
        Write (nout,99999) niter, nf, fsumsq, gtg, igrade
        Write (nout,*)
        Write (nout,*)                                                         &
          '       X                    G           Singular values'

        Write (nout,99998)(xc(j),g(j),s(j),j=1,n)

        Return

99999   Format (1X,I4,6X,I5,6X,1P,E13.5,6X,1P,E9.1,6X,I3)
99998   Format (1X,1P,E13.5,10X,1P,E9.1,10X,1P,E9.1)
      End Subroutine lsqmon
    End Module e04gbfe_mod
    Program e04gbfe

!     E04GBF Example Main Program

!     .. Use Statements ..
      Use nag_library, Only: e04gbf, e04hev, e04yaf, nag_wp, x02ajf
      Use e04gbfe_mod, Only: ldfjac, ldv, liw, lsqfun, lsqgrd, lsqmon, lw, m,  &
                             n, nin, nout, nt, t, y
!     .. Implicit None Statement ..
      Implicit None
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: eta, fsumsq, stepmx, xtol
      Integer                          :: i, ifail, iprint, maxcal, nf, niter
!     .. Local Arrays ..
      Real (Kind=nag_wp)               :: fjac(ldfjac,n), fvec(m), g(n), s(n), &
                                          v(ldv,n), w(lw), x(n)
      Integer                          :: iw(liw)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: sqrt
!     .. Executable Statements ..
      Write (nout,*) 'E04GBF Example Program Results'

!     Skip heading in data file
      Read (nin,*)

!     Observations of TJ (J = 1, 2, ..., nt) are held in T(I, J)
!     (I = 1, 2, . . . , m)

      Do i = 1, m
        Read (nin,*) y(i), t(i,1:nt)
      End Do

!     Check LSQFUN by calling E04YAF at an arbitrary point

      x(1:nt) = (/0.19_nag_wp,-1.34_nag_wp,0.88_nag_wp/)

      ifail = 0
      Call e04yaf(m,n,lsqfun,x,fvec,fjac,ldfjac,iw,liw,w,lw,ifail)

!     Continue setting parameters for E04GBF

!     Set IPRINT to 1 to obtain output from LSQMON at each iteration
      iprint = -1

      maxcal = 50*n

!     Since E04HEV is being used as LSQLIN, we set ETA to 0.9

      eta = 0.9_nag_wp

      xtol = 10.0_nag_wp*sqrt(x02ajf())

!     We estimate that the minimum will be within 10 units of the
!     starting point

      stepmx = 10.0_nag_wp

!     Set up the starting point

      x(1:nt) = (/0.5_nag_wp,1.0_nag_wp,1.5_nag_wp/)

      ifail = -1
      Call e04gbf(m,n,e04hev,lsqfun,lsqmon,iprint,maxcal,eta,xtol,stepmx,x,    &
        fsumsq,fvec,fjac,ldfjac,s,v,ldv,niter,nf,iw,liw,w,lw,ifail)

      Select Case (ifail)
      Case (0,2:)
        Write (nout,*)
        Write (nout,99999) 'On exit, the sum of squares is', fsumsq
        Write (nout,99999) 'at the point', x(1:n)

        Call lsqgrd(m,n,fvec,fjac,ldfjac,g)

        Write (nout,99998) 'The corresponding gradient is', g(1:n)
        Write (nout,*) '                           (machine dependent)'
        Write (nout,*) 'and the residuals are'
        Write (nout,99997) fvec(1:m)
      End Select

99999 Format (1X,A,3F12.4)
99998 Format (1X,A,1P,3E12.3)
99997 Format (1X,1P,E9.1)
    End Program e04gbfe


e04gdfe.f90

!   E04GDF Example Program Text
!   Mark 26 Release. NAG Copyright 2016.
    Module e04gdfe_mod

!     E04GDF Example Program Module:
!            Parameters and User-defined Routines

!     .. Use Statements ..
      Use nag_library, Only: nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Accessibility Statements ..
      Private
      Public                           :: lsqfun, lsqgrd, lsqmon
!     .. Parameters ..
      Real (Kind=nag_wp), Parameter    :: one = 1.0_nag_wp
      Real (Kind=nag_wp), Parameter    :: two = 2.0_nag_wp
      Real (Kind=nag_wp), Parameter    :: zero = 0.0_nag_wp
      Integer, Parameter               :: inc1 = 1
      Integer, Parameter, Public       :: liw = 1, m = 15, n = 3, nin = 5,     &
                                          nout = 6, nt = 3
      Integer, Parameter, Public       :: ldfjac = m
      Integer, Parameter, Public       :: ldv = n
      Integer, Parameter, Public       :: lw = 7*n + m*n + 2*m + n*n
      Character (1), Parameter         :: trans = 'T'
!     .. Local Arrays ..
      Real (Kind=nag_wp), Public, Save :: t(m,nt), y(m)
    Contains
      Subroutine lsqgrd(m,n,fvec,fjac,ldfjac,g)
!       Routine to evaluate gradient of the sum of squares

!       .. Use Statements ..
        Use nag_library, Only: dgemv
!       .. Scalar Arguments ..
        Integer, Intent (In)           :: ldfjac, m, n
!       .. Array Arguments ..
        Real (Kind=nag_wp), Intent (In) :: fjac(ldfjac,n), fvec(m)
        Real (Kind=nag_wp), Intent (Out) :: g(n)
!       .. Executable Statements ..
!       The NAG name equivalent of dgemv is f06paf
        Call dgemv(trans,m,n,one,fjac,ldfjac,fvec,inc1,zero,g,inc1)

        g(1:n) = two*g(1:n)

        Return

      End Subroutine lsqgrd
      Subroutine lsqfun(iflag,m,n,xc,fvec,fjac,ldfjac,iw,liw,w,lw)

!       Routine to evaluate the residuals and their 1st derivatives.
!       A global variable could be updated here to count the
!       number of calls of LSQFUN with IFLAG set to 1 (since NF
!       in LSQMON only counts calls with IFLAG set to 2)

!       .. Scalar Arguments ..
        Integer, Intent (Inout)        :: iflag
        Integer, Intent (In)           :: ldfjac, liw, lw, m, n
!       .. Array Arguments ..
        Real (Kind=nag_wp), Intent (Inout) :: fjac(ldfjac,n), w(lw)
        Real (Kind=nag_wp), Intent (Out) :: fvec(m)
        Real (Kind=nag_wp), Intent (In) :: xc(n)
        Integer, Intent (Inout)        :: iw(liw)
!       .. Local Scalars ..
        Real (Kind=nag_wp)             :: denom, dummy
        Integer                        :: i
!       .. Executable Statements ..
        Do i = 1, m
          denom = xc(2)*t(i,2) + xc(3)*t(i,3)

          If (iflag==2) Then
            fvec(i) = xc(1) + t(i,1)/denom - y(i)
          End If

          fjac(i,1) = one
          dummy = -one/(denom*denom)
          fjac(i,2) = t(i,1)*t(i,2)*dummy
          fjac(i,3) = t(i,1)*t(i,3)*dummy
        End Do

        Return

      End Subroutine lsqfun
      Subroutine lsqmon(m,n,xc,fvec,fjac,ldfjac,s,igrade,niter,nf,iw,liw,w,lw)
!       Monitoring routine

!       .. Use Statements ..
        Use nag_library, Only: ddot
!       .. Parameters ..
        Integer, Parameter             :: ndec = 3
!       .. Scalar Arguments ..
        Integer, Intent (In)           :: igrade, ldfjac, liw, lw, m, n, nf,   &
                                          niter
!       .. Array Arguments ..
        Real (Kind=nag_wp), Intent (In) :: fjac(ldfjac,n), fvec(m), s(n),      &
                                          xc(n)
        Real (Kind=nag_wp), Intent (Inout) :: w(lw)
        Integer, Intent (Inout)        :: iw(liw)
!       .. Local Scalars ..
        Real (Kind=nag_wp)             :: fsumsq, gtg
        Integer                        :: j
!       .. Local Arrays ..
        Real (Kind=nag_wp)             :: g(ndec)
!       .. Executable Statements ..
!       The NAG name equivalent of ddot is f06eaf
        fsumsq = ddot(m,fvec,inc1,fvec,inc1)

        Call lsqgrd(m,n,fvec,fjac,ldfjac,g)

        gtg = ddot(n,g,inc1,g,inc1)

!       A global variable giving the number of calls of
!       LSQFUN with IFLAG set to 1 could be printed here

        Write (nout,*)
        Write (nout,*)                                                         &
          ' Itns    F evals          SUMSQ             GTG        grade'
        Write (nout,99999) niter, nf, fsumsq, gtg, igrade
        Write (nout,*)
        Write (nout,*)                                                         &
          '       X                    G           Singular values'

        Write (nout,99998)(xc(j),g(j),s(j),j=1,n)

        Return

99999   Format (1X,I4,6X,I5,6X,1P,E13.5,6X,1P,E9.1,6X,I3)
99998   Format (1X,1P,E13.5,10X,1P,E9.1,10X,1P,E9.1)
      End Subroutine lsqmon
    End Module e04gdfe_mod
    Program e04gdfe

!     E04GDF Example Main Program

!     .. Use Statements ..
      Use nag_library, Only: e04gdf, e04yaf, nag_wp, x02ajf
      Use e04gdfe_mod, Only: ldfjac, ldv, liw, lsqfun, lsqgrd, lsqmon, lw, m,  &
                             n, nin, nout, nt, t, y
!     .. Implicit None Statement ..
      Implicit None
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: eta, fsumsq, stepmx, xtol
      Integer                          :: i, ifail, iprint, maxcal, nf, niter
!     .. Local Arrays ..
      Real (Kind=nag_wp)               :: fjac(ldfjac,n), fvec(m), g(n), s(n), &
                                          v(ldv,n), w(lw), x(n)
      Integer                          :: iw(liw)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: sqrt
!     .. Executable Statements ..
      Write (nout,*) 'E04GDF Example Program Results'

!     Skip heading in data file
      Read (nin,*)

!     Observations of TJ (J = 1, 2, ..., nt) are held in T(I, J)
!     (I = 1, 2, ... , m)

      Do i = 1, m
        Read (nin,*) y(i), t(i,1:nt)
      End Do

!     Check LSQFUN by calling E04YAF at an arbitrary point. Since
!     E04YAF only checks the derivatives calculated when IFLAG = 2,
!     a separate program should be run before using E04YAF or
!     E04GDF to check that LSQFUN gives the same values for the
!     elements of FJAC when IFLAG is set to 1 as when IFLAG is
!     set to 2.

      x(1:nt) = (/0.19_nag_wp,-1.34_nag_wp,0.88_nag_wp/)

      ifail = 0
      Call e04yaf(m,n,lsqfun,x,fvec,fjac,ldfjac,iw,liw,w,lw,ifail)

!     Continue setting parameters for E04GDF

!     Set IPRINT to 1 to obtain output from LSQMON at each iteration

      iprint = -1

      maxcal = 50*n
      eta = 0.9_nag_wp
      xtol = 10.0_nag_wp*sqrt(x02ajf())

!     We estimate that the minimum will be within 10 units of the
!     starting point

      stepmx = 10.0_nag_wp

!     Set up the starting point

      x(1:nt) = (/0.5_nag_wp,1.0_nag_wp,1.5_nag_wp/)

      ifail = -1
      Call e04gdf(m,n,lsqfun,lsqmon,iprint,maxcal,eta,xtol,stepmx,x,fsumsq,    &
        fvec,fjac,ldfjac,s,v,ldv,niter,nf,iw,liw,w,lw,ifail)

      Select Case (ifail)
      Case (0,2:)
        Write (nout,*)
        Write (nout,99999) 'On exit, the sum of squares is', fsumsq
        Write (nout,99999) 'at the point', x(1:n)

        Call lsqgrd(m,n,fvec,fjac,ldfjac,g)

        Write (nout,99998) 'The corresponding gradient is', g(1:n)
        Write (nout,*) '                           (machine dependent)'
        Write (nout,*) 'and the residuals are'
        Write (nout,99997) fvec(1:m)
      End Select

99999 Format (1X,A,3F12.4)
99998 Format (1X,A,1P,3E12.3)
99997 Format (1X,1P,E9.1)
    End Program e04gdfe


e04gyfe.f90

!   E04GYF Example Program Text
!   Mark 26 Release. NAG Copyright 2016.
    Module e04gyfe_mod

!     E04GYF Example Program Module:
!            Parameters and User-defined Routines

!     .. Use Statements ..
      Use nag_library, Only: nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Accessibility Statements ..
      Private
      Public                           :: lsfun2
!     .. Parameters ..
      Integer, Parameter, Public       :: m = 15, n = 3, nin = 5, nout = 6,    &
                                          nt = 3
      Integer, Parameter, Public       :: lw = 8*n + 2*n*n + 2*m*n + 3*m
!     .. Local Arrays ..
      Real (Kind=nag_wp), Public, Save :: t(m,nt), y(m)
    Contains
      Subroutine lsfun2(m,n,xc,fvec,fjac,ldfjac,iuser,ruser)
!       Routine to evaluate the residuals and their 1st derivatives.

!       .. Scalar Arguments ..
        Integer, Intent (In)           :: ldfjac, m, n
!       .. Array Arguments ..
        Real (Kind=nag_wp), Intent (Inout) :: fjac(ldfjac,n), ruser(*)
        Real (Kind=nag_wp), Intent (Out) :: fvec(m)
        Real (Kind=nag_wp), Intent (In) :: xc(n)
        Integer, Intent (Inout)        :: iuser(*)
!       .. Local Scalars ..
        Real (Kind=nag_wp)             :: denom, dummy
        Integer                        :: i
!       .. Executable Statements ..
        Do i = 1, m
          denom = xc(2)*t(i,2) + xc(3)*t(i,3)
          fvec(i) = xc(1) + t(i,1)/denom - y(i)
          fjac(i,1) = 1.0_nag_wp
          dummy = -1.0_nag_wp/(denom*denom)
          fjac(i,2) = t(i,1)*t(i,2)*dummy
          fjac(i,3) = t(i,1)*t(i,3)*dummy
        End Do

        Return

      End Subroutine lsfun2
    End Module e04gyfe_mod
    Program e04gyfe

!     E04GYF Example Main Program

!     .. Use Statements ..
      Use nag_library, Only: e04gyf, nag_wp
      Use e04gyfe_mod, Only: lsfun2, lw, m, n, nin, nout, nt, t, y
!     .. Implicit None Statement ..
      Implicit None
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: fsumsq
      Integer                          :: i, ifail
!     .. Local Arrays ..
      Real (Kind=nag_wp)               :: ruser(1), w(lw), x(n)
      Integer                          :: iuser(1)
!     .. Executable Statements ..
      Write (nout,*) 'E04GYF Example Program Results'

!     Skip heading in data file
      Read (nin,*)

!     Observations of TJ (J = 1, 2, ..., nt) are held in T(I, J)
!     (I = 1, 2, ..., m)

      Do i = 1, m
        Read (nin,*) y(i), t(i,1:nt)
      End Do

      x(1:nt) = (/0.5_nag_wp,1.0_nag_wp,1.5_nag_wp/)

      ifail = -1
      Call e04gyf(m,n,lsfun2,x,fsumsq,w,lw,iuser,ruser,ifail)

      Select Case (ifail)
      Case (0,2:8,10:)
        Write (nout,*)
        Write (nout,99999) 'On exit, the sum of squares is', fsumsq
        Write (nout,99999) 'at the point', x(1:n)
      End Select

99999 Format (1X,A,3F12.4)
    End Program e04gyfe


e04gzfe.f90

!   E04GZF Example Program Text
!   Mark 26 Release. NAG Copyright 2016.
    Module e04gzfe_mod

!     E04GZF Example Program Module:
!            Parameters and User-defined Routines

!     .. Use Statements ..
      Use nag_library, Only: nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Accessibility Statements ..
      Private
      Public                           :: lsfun2
!     .. Parameters ..
      Integer, Parameter, Public       :: m = 15, n = 3, nin = 5, nout = 6,    &
                                          nt = 3
      Integer, Parameter, Public       :: lw = 8*n + 2*n*n + 2*m*n + 3*m
!     .. Local Arrays ..
      Real (Kind=nag_wp), Public, Save :: t(m,nt), y(m)
    Contains
      Subroutine lsfun2(m,n,xc,fvec,fjac,ldfjac,iuser,ruser)
!       Routine to evaluate the residuals and their 1st derivatives.

!       .. Scalar Arguments ..
        Integer, Intent (In)           :: ldfjac, m, n
!       .. Array Arguments ..
        Real (Kind=nag_wp), Intent (Inout) :: fjac(ldfjac,n), ruser(*)
        Real (Kind=nag_wp), Intent (Out) :: fvec(m)
        Real (Kind=nag_wp), Intent (In) :: xc(n)
        Integer, Intent (Inout)        :: iuser(*)
!       .. Local Scalars ..
        Real (Kind=nag_wp)             :: denom, dummy
        Integer                        :: i
!       .. Executable Statements ..
        Do i = 1, m
          denom = xc(2)*t(i,2) + xc(3)*t(i,3)
          fvec(i) = xc(1) + t(i,1)/denom - y(i)
          fjac(i,1) = 1.0E0_nag_wp
          dummy = -1.0E0_nag_wp/(denom*denom)
          fjac(i,2) = t(i,1)*t(i,2)*dummy
          fjac(i,3) = t(i,1)*t(i,3)*dummy
        End Do

        Return

      End Subroutine lsfun2
    End Module e04gzfe_mod
    Program e04gzfe

!     E04GZF Example Main Program

!     .. Use Statements ..
      Use nag_library, Only: e04gzf, nag_wp
      Use e04gzfe_mod, Only: lsfun2, lw, m, n, nin, nout, nt, t, y
!     .. Implicit None Statement ..
      Implicit None
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: fsumsq
      Integer                          :: i, ifail
!     .. Local Arrays ..
      Real (Kind=nag_wp)               :: ruser(1), w(lw), x(n)
      Integer                          :: iuser(1)
!     .. Executable Statements ..
      Write (nout,*) 'E04GZF Example Program Results'

!     Skip heading in data file
      Read (nin,*)

!     Observations of TJ (J = 1, 2, ..., nt) are held in T(I, J)
!     (I = 1, 2, ..., m)

      Do i = 1, m
        Read (nin,*) y(i), t(i,1:nt)
      End Do

      x(1:nt) = (/0.5E0_nag_wp,1.0E0_nag_wp,1.5E0_nag_wp/)

      ifail = -1
      Call e04gzf(m,n,lsfun2,x,fsumsq,w,lw,iuser,ruser,ifail)

      Select Case (ifail)
      Case (0,2:8,10:)
        Write (nout,*)
        Write (nout,99999) 'On exit, the sum of squares is', fsumsq
        Write (nout,99999) 'at the point', x(1:n)
      End Select

99999 Format (1X,A,3F12.4)
    End Program e04gzfe


e04hcfe.f90

!   E04HCF Example Program Text
!   Mark 26 Release. NAG Copyright 2016.
    Module e04hcfe_mod

!     E04HCF Example Program Module:
!            Parameters and User-defined Routines

!     .. Use Statements ..
      Use nag_library, Only: nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Accessibility Statements ..
      Private
      Public                           :: funct
!     .. Parameters ..
      Integer, Parameter, Public       :: liw = 1, n = 4, nout = 6
      Integer, Parameter, Public       :: lw = 3*n
    Contains
      Subroutine funct(iflag,n,xc,fc,gc,iw,liw,w,lw)
!       Routine to evaluate objective function and its 1st derivatives.

!       .. Scalar Arguments ..
        Real (Kind=nag_wp), Intent (Out) :: fc
        Integer, Intent (Inout)        :: iflag
        Integer, Intent (In)           :: liw, lw, n
!       .. Array Arguments ..
        Real (Kind=nag_wp), Intent (Out) :: gc(n)
        Real (Kind=nag_wp), Intent (Inout) :: w(lw)
        Real (Kind=nag_wp), Intent (In) :: xc(n)
        Integer, Intent (Inout)        :: iw(liw)
!       .. Executable Statements ..
        fc = (xc(1)+10.0_nag_wp*xc(2))**2 + 5.0_nag_wp*(xc(3)-xc(4))**2 +      &
          (xc(2)-2.0_nag_wp*xc(3))**4 + 10.0_nag_wp*(xc(1)-xc(4))**4
        gc(1) = 2.0_nag_wp*(xc(1)+10.0_nag_wp*xc(2)) +                         &
          40.0_nag_wp*(xc(1)-xc(4))**3
        gc(2) = 20.0_nag_wp*(xc(1)+10.0_nag_wp*xc(2)) +                        &
          4.0_nag_wp*(xc(2)-2.0_nag_wp*xc(3))**3
        gc(3) = 10.0_nag_wp*(xc(3)-xc(4)) - 8.0_nag_wp*(xc(2)-2.0_nag_wp*xc(3) &
          )**3
        gc(4) = 10.0_nag_wp*(xc(4)-xc(3)) - 40.0_nag_wp*(xc(1)-xc(4))**3

        Return

      End Subroutine funct
    End Module e04hcfe_mod
    Program e04hcfe

!     E04HCF Example Main Program

!     .. Use Statements ..
      Use nag_library, Only: e04hcf, nag_wp
      Use e04hcfe_mod, Only: funct, liw, lw, n, nout
!     .. Implicit None Statement ..
      Implicit None
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: f
      Integer                          :: ifail
!     .. Local Arrays ..
      Real (Kind=nag_wp)               :: g(n), w(lw), x(n)
      Integer                          :: iw(liw)
!     .. Executable Statements ..
      Write (nout,*) 'E04HCF Example Program Results'

!     Set up an arbitrary point at which to check the 1st derivatives

      x(1:n) = (/1.46_nag_wp,-0.82_nag_wp,0.57_nag_wp,1.21_nag_wp/)

      Write (nout,*)
      Write (nout,*) 'The test point is'
      Write (nout,99999) x(1:n)

      ifail = -1
      Call e04hcf(n,funct,x,f,g,iw,liw,w,lw,ifail)

      If (ifail>=0) Then
        Write (nout,*)

        If (ifail==0) Then
          Write (nout,*) '1st derivatives are consistent with function values'
        Else
          Write (nout,*) 'Probable error in calculation of 1st derivatives'
        End If

        Write (nout,*)
        Write (nout,99998) 'At the test point, FUNCT gives the function value' &
          , f
        Write (nout,*) 'and the 1st derivatives'
        Write (nout,99997) g(1:n)
      End If

99999 Format (1X,4F10.4)
99998 Format (1X,A,1P,E12.4)
99997 Format (1X,1P,4E12.3)
    End Program e04hcfe


e04hdfe.f90

!   E04HDF Example Program Text
!   Mark 26 Release. NAG Copyright 2016.
    Module e04hdfe_mod

!     E04HDF Example Program Module:
!            Parameters and User-defined Routines

!     .. Use Statements ..
      Use nag_library, Only: nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Accessibility Statements ..
      Private
      Public                           :: funct, h
!     .. Parameters ..
      Integer, Parameter, Public       :: liw = 1, n = 4, nout = 6
      Integer, Parameter, Public       :: lh = n*(n-1)/2
      Integer, Parameter, Public       :: lw = 5*n
    Contains
      Subroutine funct(iflag,n,xc,fc,gc,iw,liw,w,lw)
!       Routine to evaluate objective function and its 1st derivatives.

!       .. Scalar Arguments ..
        Real (Kind=nag_wp), Intent (Out) :: fc
        Integer, Intent (Inout)        :: iflag
        Integer, Intent (In)           :: liw, lw, n
!       .. Array Arguments ..
        Real (Kind=nag_wp), Intent (Out) :: gc(n)
        Real (Kind=nag_wp), Intent (Inout) :: w(lw)
        Real (Kind=nag_wp), Intent (In) :: xc(n)
        Integer, Intent (Inout)        :: iw(liw)
!       .. Executable Statements ..
        fc = (xc(1)+10.0_nag_wp*xc(2))**2 + 5.0_nag_wp*(xc(3)-xc(4))**2 +      &
          (xc(2)-2.0_nag_wp*xc(3))**4 + 10.0_nag_wp*(xc(1)-xc(4))**4
        gc(1) = 2.0_nag_wp*(xc(1)+10.0_nag_wp*xc(2)) +                         &
          40.0_nag_wp*(xc(1)-xc(4))**3
        gc(2) = 20.0_nag_wp*(xc(1)+10.0_nag_wp*xc(2)) +                        &
          4.0_nag_wp*(xc(2)-2.0_nag_wp*xc(3))**3
        gc(3) = 10.0_nag_wp*(xc(3)-xc(4)) - 8.0_nag_wp*(xc(2)-2.0_nag_wp*xc(3) &
          )**3
        gc(4) = 10.0_nag_wp*(xc(4)-xc(3)) - 40.0_nag_wp*(xc(1)-xc(4))**3

        Return

      End Subroutine funct
      Subroutine h(iflag,n,xc,fhesl,lh,fhesd,iw,liw,w,lw)
!       Routine to evaluate 2nd derivatives

!       .. Scalar Arguments ..
        Integer, Intent (Inout)        :: iflag
        Integer, Intent (In)           :: lh, liw, lw, n
!       .. Array Arguments ..
        Real (Kind=nag_wp), Intent (Inout) :: fhesd(n), w(lw)
        Real (Kind=nag_wp), Intent (Out) :: fhesl(lh)
        Real (Kind=nag_wp), Intent (In) :: xc(n)
        Integer, Intent (Inout)        :: iw(liw)
!       .. Executable Statements ..
        fhesd(1) = 2.0_nag_wp + 120.0_nag_wp*(xc(1)-xc(4))**2
        fhesd(2) = 200.0_nag_wp + 12.0_nag_wp*(xc(2)-2.0_nag_wp*xc(3))**2
        fhesd(3) = 10.0_nag_wp + 48.0_nag_wp*(xc(2)-2.0_nag_wp*xc(3))**2
        fhesd(4) = 10.0_nag_wp + 120.0_nag_wp*(xc(1)-xc(4))**2

        fhesl(1) = 20.0_nag_wp
        fhesl(2) = 0.0_nag_wp
        fhesl(3) = -24.0_nag_wp*(xc(2)-2.0_nag_wp*xc(3))**2
        fhesl(4) = -120.0_nag_wp*(xc(1)-xc(4))**2
        fhesl(5) = 0.0_nag_wp
        fhesl(6) = -10.0_nag_wp

        Return

      End Subroutine h
    End Module e04hdfe_mod
    Program e04hdfe

!     E04HDF Example Main Program

!     .. Use Statements ..
      Use nag_library, Only: e04hcf, e04hdf, nag_wp
      Use e04hdfe_mod, Only: funct, h, lh, liw, lw, n, nout
!     .. Implicit None Statement ..
      Implicit None
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: f
      Integer                          :: i, ifail, k
!     .. Local Arrays ..
      Real (Kind=nag_wp)               :: g(n), hesd(n), hesl(lh), w(lw), x(n)
      Integer                          :: iw(liw)
!     .. Executable Statements ..
      Write (nout,*) 'E04HDF Example Program Results'

!     Set up an arbitrary point at which to check the derivatives

      x(1:n) = (/1.46_nag_wp,-0.82_nag_wp,0.57_nag_wp,1.21_nag_wp/)

      Write (nout,*)
      Write (nout,*) 'The test point is'
      Write (nout,99999) x(1:n)

!     Check the 1st derivatives

      ifail = 0
      Call e04hcf(n,funct,x,f,g,iw,liw,w,lw,ifail)

!     Check the 2nd derivatives

      ifail = -1
      Call e04hdf(n,funct,h,x,g,hesl,lh,hesd,iw,liw,w,lw,ifail)

      If (ifail>=0) Then
        Write (nout,*)

        If (ifail==0) Then
          Write (nout,*) '2nd derivatives are consistent with 1st derivatives'
        Else If (ifail==2) Then
          Write (nout,*) 'Probable error in calculation of 2nd derivatives'
        End If

        Write (nout,*)
        Write (nout,99998) 'At the test point, FUNCT gives the function value' &
          , f
        Write (nout,*) 'and the 1st derivatives'
        Write (nout,99997) g(1:n)
        Write (nout,*)
        Write (nout,*) 'H gives the lower triangle of the Hessian matrix'
        Write (nout,99996) hesd(1)

        k = 1

        Do i = 2, n
          Write (nout,99996) hesl(k:(k+i-2)), hesd(i)
          k = k + i - 1
        End Do

      End If

99999 Format (1X,4F9.4)
99998 Format (1X,A,1P,E12.4)
99997 Format (1X,1P,4E12.3)
99996 Format (1X,1P,4E12.3)
    End Program e04hdfe


e04hefe.f90

!   E04HEF Example Program Text
!   Mark 26 Release. NAG Copyright 2016.
    Module e04hefe_mod

!     E04HEF Example Program Module:
!            Parameters and User-defined Routines

!     .. Use Statements ..
      Use nag_library, Only: nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Accessibility Statements ..
      Private
      Public                           :: lsqfun, lsqgrd, lsqhes, lsqmon
!     .. Parameters ..
      Integer, Parameter, Public       :: liw = 1, m = 15, n = 3, nin = 5,     &
                                          nout = 6, nt = 3
      Integer, Parameter, Public       :: lb = n*(n+1)/2
      Integer, Parameter, Public       :: ldfjac = m
      Integer, Parameter, Public       :: ldv = n
      Integer, Parameter, Public       :: lw = 7*n + m*n + 2*m + n*n
!     .. Local Arrays ..
      Real (Kind=nag_wp), Public, Save :: t(m,nt), y(m)
    Contains
      Subroutine lsqgrd(m,n,fvec,fjac,ldfjac,g)
!       Routine to evaluate gradient of the sum of squares

!       .. Use Statements ..
        Use nag_library, Only: dgemv
!       .. Scalar Arguments ..
        Integer, Intent (In)           :: ldfjac, m, n
!       .. Array Arguments ..
        Real (Kind=nag_wp), Intent (In) :: fjac(ldfjac,n), fvec(m)
        Real (Kind=nag_wp), Intent (Out) :: g(n)
!       .. Executable Statements ..
!       The NAG name equivalent of dgemv is f06paf
        Call dgemv('T',m,n,1.0_nag_wp,fjac,ldfjac,fvec,1,0.0_nag_wp,g,1)

        g(1:n) = 2.0_nag_wp*g(1:n)

        Return

      End Subroutine lsqgrd
      Subroutine lsqfun(iflag,m,n,xc,fvec,fjac,ldfjac,iw,liw,w,lw)

!       Routine to evaluate the residuals and their 1st derivatives

!       .. Scalar Arguments ..
        Integer, Intent (Inout)        :: iflag
        Integer, Intent (In)           :: ldfjac, liw, lw, m, n
!       .. Array Arguments ..
        Real (Kind=nag_wp), Intent (Inout) :: fjac(ldfjac,n), w(lw)
        Real (Kind=nag_wp), Intent (Out) :: fvec(m)
        Real (Kind=nag_wp), Intent (In) :: xc(n)
        Integer, Intent (Inout)        :: iw(liw)
!       .. Local Scalars ..
        Real (Kind=nag_wp)             :: denom, dummy
        Integer                        :: i
!       .. Executable Statements ..
        Do i = 1, m
          denom = xc(2)*t(i,2) + xc(3)*t(i,3)
          fvec(i) = xc(1) + t(i,1)/denom - y(i)
          fjac(i,1) = 1.0_nag_wp
          dummy = -1.0_nag_wp/(denom*denom)
          fjac(i,2) = t(i,1)*t(i,2)*dummy
          fjac(i,3) = t(i,1)*t(i,3)*dummy
        End Do

        Return

      End Subroutine lsqfun
      Subroutine lsqhes(iflag,m,n,fvec,xc,b,lb,iw,liw,w,lw)

!       Routine to compute the lower triangle of the matrix B
!       (stored by rows in the array B)

!       .. Scalar Arguments ..
        Integer, Intent (Inout)        :: iflag
        Integer, Intent (In)           :: lb, liw, lw, m, n
!       .. Array Arguments ..
        Real (Kind=nag_wp), Intent (Out) :: b(lb)
        Real (Kind=nag_wp), Intent (In) :: fvec(m), xc(n)
        Real (Kind=nag_wp), Intent (Inout) :: w(lw)
        Integer, Intent (Inout)        :: iw(liw)
!       .. Local Scalars ..
        Real (Kind=nag_wp)             :: dummy, sum22, sum32, sum33
        Integer                        :: i
!       .. Executable Statements ..
        b(1) = 0.0_nag_wp
        b(2) = 0.0_nag_wp
        sum22 = 0.0_nag_wp
        sum32 = 0.0_nag_wp
        sum33 = 0.0_nag_wp

        Do i = 1, m
          dummy = 2.0_nag_wp*t(i,1)/(xc(2)*t(i,2)+xc(3)*t(i,3))**3
          sum22 = sum22 + fvec(i)*dummy*t(i,2)**2
          sum32 = sum32 + fvec(i)*dummy*t(i,2)*t(i,3)
          sum33 = sum33 + fvec(i)*dummy*t(i,3)**2
        End Do

        b(3) = sum22
        b(4) = 0.0_nag_wp
        b(5) = sum32
        b(6) = sum33

        Return

      End Subroutine lsqhes
      Subroutine lsqmon(m,n,xc,fvec,fjac,ldfjac,s,igrade,niter,nf,iw,liw,w,lw)
!       Monitoring routine

!       .. Use Statements ..
        Use nag_library, Only: f06eaf
!       .. Parameters ..
        Integer, Parameter             :: ndec = 3
!       .. Scalar Arguments ..
        Integer, Intent (In)           :: igrade, ldfjac, liw, lw, m, n, nf,   &
                                          niter
!       .. Array Arguments ..
        Real (Kind=nag_wp), Intent (In) :: fjac(ldfjac,n), fvec(m), s(n),      &
                                          xc(n)
        Real (Kind=nag_wp), Intent (Inout) :: w(lw)
        Integer, Intent (Inout)        :: iw(liw)
!       .. Local Scalars ..
        Real (Kind=nag_wp)             :: fsumsq, gtg
        Integer                        :: j
!       .. Local Arrays ..
        Real (Kind=nag_wp)             :: g(ndec)
!       .. Executable Statements ..
        fsumsq = f06eaf(m,fvec,1,fvec,1)

        Call lsqgrd(m,n,fvec,fjac,ldfjac,g)

        gtg = f06eaf(n,g,1,g,1)

        Write (nout,*)
        Write (nout,*)                                                         &
          ' Itns    F evals          SUMSQ             GTG        grade'
        Write (nout,99999) niter, nf, fsumsq, gtg, igrade
        Write (nout,*)
        Write (nout,*)                                                         &
          '       X                    G           Singular values'

        Do j = 1, n
          Write (nout,99998) xc(j), g(j), s(j)
        End Do

        Return

99999   Format (1X,I4,6X,I5,6X,1P,E13.5,6X,1P,E9.1,6X,I3)
99998   Format (1X,1P,E13.5,10X,1P,E9.1,10X,1P,E9.1)
      End Subroutine lsqmon
    End Module e04hefe_mod
    Program e04hefe

!     E04HEF Example Main Program

!     .. Use Statements ..
      Use nag_library, Only: e04hef, e04yaf, e04ybf, nag_wp, x02ajf
      Use e04hefe_mod, Only: lb, ldfjac, ldv, liw, lsqfun, lsqgrd, lsqhes,     &
                             lsqmon, lw, m, n, nin, nout, nt, t, y
!     .. Implicit None Statement ..
      Implicit None
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: eta, fsumsq, stepmx, xtol
      Integer                          :: i, ifail, iprint, maxcal, nf, niter
!     .. Local Arrays ..
      Real (Kind=nag_wp)               :: b(lb), fjac(ldfjac,n), fvec(m),      &
                                          g(n), s(n), v(ldv,n), w(lw), x(n)
      Integer                          :: iw(liw)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: sqrt
!     .. Executable Statements ..
      Write (nout,*) 'E04HEF Example Program Results'

!     Skip heading in data file
      Read (nin,*)

!     Observations of TJ (J = 1, 2, ..., nt) are held in T(I, J)
!     (I = 1, 2, ..., m)

      Do i = 1, m
        Read (nin,*) y(i), t(i,1:nt)
      End Do

!     Set up an arbitrary point at which to check the derivatives

      x(1:nt) = (/0.19_nag_wp,-1.34_nag_wp,0.88_nag_wp/)

!     Check the 1st derivatives

      ifail = 0
      Call e04yaf(m,n,lsqfun,x,fvec,fjac,ldfjac,iw,liw,w,lw,ifail)

!     Check the evaluation of B

      ifail = 0
      Call e04ybf(m,n,lsqfun,lsqhes,x,fvec,fjac,ldfjac,b,lb,iw,liw,w,lw,ifail)

!     Continue setting parameters for E04HEF

!     Set IPRINT to 1 to obtain output from LSQMON at each iteration

      iprint = -1

      maxcal = 50*n
      eta = 0.9_nag_wp
      xtol = 10.0_nag_wp*sqrt(x02ajf())

!     We estimate that the minimum will be within 10 units of the
!     starting point

      stepmx = 10.0_nag_wp

!     Set up the starting point

      x(1:nt) = (/0.5_nag_wp,1.0_nag_wp,1.5_nag_wp/)

      ifail = -1
      Call e04hef(m,n,lsqfun,lsqhes,lsqmon,iprint,maxcal,eta,xtol,stepmx,x,    &
        fsumsq,fvec,fjac,ldfjac,s,v,ldv,niter,nf,iw,liw,w,lw,ifail)

      Select Case (ifail)
      Case (0,2:)
        Write (nout,*)
        Write (nout,99999) 'On exit, the sum of squares is', fsumsq
        Write (nout,99999) 'at the point', x(1:n)

        Call lsqgrd(m,n,fvec,fjac,ldfjac,g)

        Write (nout,99998) 'The corresponding gradient is', g(1:n)
        Write (nout,*) '                           (machine dependent)'
        Write (nout,*) 'and the residuals are'
        Write (nout,99997) fvec(1:m)
      End Select

99999 Format (1X,A,3F12.4)
99998 Format (1X,A,1P,3E12.3)
99997 Format (1X,1P,E9.1)
    End Program e04hefe


e04hyfe.f90

!   E04HYF Example Program Text
!   Mark 26 Release. NAG Copyright 2016.
    Module e04hyfe_mod

!     E04HYF Example Program Module:
!            Parameters and User-defined Routines

!     .. Use Statements ..
      Use nag_library, Only: nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Accessibility Statements ..
      Private
      Public                           :: lsfun2, lshes2
!     .. Parameters ..
      Integer, Parameter, Public       :: m = 15, n = 3, nin = 5, nout = 6,    &
                                          nt = 3
      Integer, Parameter, Public       :: lw = 8*n + 2*n*n + 2*m*n + 3*m
!     .. Local Arrays ..
      Real (Kind=nag_wp), Public, Save :: t(m,nt), y(m)
    Contains
      Subroutine lsfun2(m,n,xc,fvec,fjac,ldfjac,iuser,ruser)
!       Routine to evaluate the residuals and their 1st derivatives.

!       .. Scalar Arguments ..
        Integer, Intent (In)           :: ldfjac, m, n
!       .. Array Arguments ..
        Real (Kind=nag_wp), Intent (Inout) :: fjac(ldfjac,n), ruser(*)
        Real (Kind=nag_wp), Intent (Out) :: fvec(m)
        Real (Kind=nag_wp), Intent (In) :: xc(n)
        Integer, Intent (Inout)        :: iuser(*)
!       .. Local Scalars ..
        Real (Kind=nag_wp)             :: denom, dummy
        Integer                        :: i
!       .. Executable Statements ..
        Do i = 1, m
          denom = xc(2)*t(i,2) + xc(3)*t(i,3)
          fvec(i) = xc(1) + t(i,1)/denom - y(i)
          fjac(i,1) = 1.0E0_nag_wp
          dummy = -1.0E0_nag_wp/(denom*denom)
          fjac(i,2) = t(i,1)*t(i,2)*dummy
          fjac(i,3) = t(i,1)*t(i,3)*dummy
        End Do

        Return

      End Subroutine lsfun2
      Subroutine lshes2(m,n,fvec,xc,b,lb,iuser,ruser)
!       Routine to compute the lower triangle of the matrix B
!       (stored by rows in the array B).

!       .. Scalar Arguments ..
        Integer, Intent (In)           :: lb, m, n
!       .. Array Arguments ..
        Real (Kind=nag_wp), Intent (Out) :: b(lb)
        Real (Kind=nag_wp), Intent (In) :: fvec(m), xc(n)
        Real (Kind=nag_wp), Intent (Inout) :: ruser(*)
        Integer, Intent (Inout)        :: iuser(*)
!       .. Local Scalars ..
        Real (Kind=nag_wp)             :: dummy, sum22, sum32, sum33
        Integer                        :: i
!       .. Executable Statements ..
        b(1) = 0.0E0_nag_wp
        b(2) = 0.0E0_nag_wp
        sum22 = 0.0E0_nag_wp
        sum32 = 0.0E0_nag_wp
        sum33 = 0.0E0_nag_wp

        Do i = 1, m
          dummy = 2.0E0_nag_wp*t(i,1)/(xc(2)*t(i,2)+xc(3)*t(i,3))**3
          sum22 = sum22 + fvec(i)*dummy*t(i,2)**2
          sum32 = sum32 + fvec(i)*dummy*t(i,2)*t(i,3)
          sum33 = sum33 + fvec(i)*dummy*t(i,3)**2
        End Do

        b(3) = sum22
        b(4) = 0.0E0_nag_wp
        b(5) = sum32
        b(6) = sum33

        Return

      End Subroutine lshes2
    End Module e04hyfe_mod
    Program e04hyfe

!     E04HYF Example Main Program

!     .. Use Statements ..
      Use nag_library, Only: e04hyf, nag_wp
      Use e04hyfe_mod, Only: lsfun2, lshes2, lw, m, n, nin, nout, nt, t, y
!     .. Implicit None Statement ..
      Implicit None
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: fsumsq
      Integer                          :: i, ifail
!     .. Local Arrays ..
      Real (Kind=nag_wp)               :: ruser(1), w(lw), x(n)
      Integer                          :: iuser(1)
!     .. Executable Statements ..
      Write (nout,*) 'E04HYF Example Program Results'

!     Skip heading in data file
      Read (nin,*)

!     Observations of TJ (J = 1, 2, ..., nt) are held in T(I, J)
!     (I = 1, 2, ..., m)

      Do i = 1, m
        Read (nin,*) y(i), t(i,1:nt)
      End Do

      x(1:nt) = (/0.5E0_nag_wp,1.0E0_nag_wp,1.5E0_nag_wp/)

      ifail = -1
      Call e04hyf(m,n,lsfun2,lshes2,x,fsumsq,w,lw,iuser,ruser,ifail)

      Select Case (ifail)
      Case (0,2:8,10:)
        Write (nout,*)
        Write (nout,99999) 'On exit, the sum of squares is', fsumsq
        Write (nout,99999) 'at the point', x(1:n)
      End Select

99999 Format (1X,A,3F12.4)
    End Program e04hyfe


e04jcfe.f90

!   E04JCF Example Program Text
!   Mark 26 Release. NAG Copyright 2016.
    Module e04jcfe_mod

!     E04JCF Example Program Module:
!            Parameters and User-defined Routines

!     .. Use Statements ..
      Use nag_library, Only: nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Accessibility Statements ..
      Private
      Public                           :: monfun, objfun
!     .. Parameters ..
      Integer, Parameter, Public       :: nout = 6
    Contains
      Subroutine objfun(n,x,f,iuser,ruser,inform)

!       .. Parameters ..
        Real (Kind=nag_wp), Parameter  :: five = 5.0_nag_wp
        Real (Kind=nag_wp), Parameter  :: ten = 1.0E1_nag_wp
        Real (Kind=nag_wp), Parameter  :: two = 2.0_nag_wp
!       .. Scalar Arguments ..
        Real (Kind=nag_wp), Intent (Out) :: f
        Integer, Intent (Out)          :: inform
        Integer, Intent (In)           :: n
!       .. Array Arguments ..
        Real (Kind=nag_wp), Intent (Inout) :: ruser(*)
        Real (Kind=nag_wp), Intent (In) :: x(n)
        Integer, Intent (Inout)        :: iuser(*)
!       .. Executable Statements ..
        inform = 0

        f = (x(1)+ten*x(2))**2 + five*(x(3)-x(4))**2 + (x(2)-two*x(3))**4 +    &
          ten*(x(1)-x(4))**4

        Return

      End Subroutine objfun
      Subroutine monfun(n,nf,x,f,rho,iuser,ruser,inform)

!       .. Scalar Arguments ..
        Real (Kind=nag_wp), Intent (In) :: f, rho
        Integer, Intent (Out)          :: inform
        Integer, Intent (In)           :: n, nf
!       .. Array Arguments ..
        Real (Kind=nag_wp), Intent (Inout) :: ruser(*)
        Real (Kind=nag_wp), Intent (In) :: x(n)
        Integer, Intent (Inout)        :: iuser(*)
!       .. Local Scalars ..
        Logical                        :: verbose_output
!       .. Executable Statements ..
        inform = 0

        Write (nout,Fmt=99999) 'Monitoring: new trust region radius =', rho

!       Set this to .True. to get more detailed output
        verbose_output = .False.

        If (verbose_output) Then
          Write (nout,Fmt=99998) 'Number of function calls =', nf
          Write (nout,Fmt=99997) 'Current function value =', f
          Write (nout,Fmt=99996) 'The corresponding X is:', x(1:n)
        End If

        Return
99999   Format (/,4X,A,1P,E13.3)
99998   Format (4X,A,I16)
99997   Format (4X,A,1P,E12.4)
99996   Format (4X,A,/,(4X,5E12.4))
      End Subroutine monfun
    End Module e04jcfe_mod
    Program e04jcfe

!     Example problem for E04JCF.

!     .. Use Statements ..
      Use nag_library, Only: e04jcf, nag_wp, x02alf
      Use e04jcfe_mod, Only: monfun, nout, objfun
!     .. Implicit None Statement ..
      Implicit None
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: f, infbnd, rhobeg, rhoend
      Integer                          :: ifail, maxcal, n, nf, npt
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: bl(:), bu(:), x(:)
      Real (Kind=nag_wp)               :: ruser(1)
      Integer                          :: iuser(1)
!     .. Executable Statements ..
      Write (nout,*) 'E04JCF Example Program Results'

      maxcal = 500
      rhobeg = 1.0E-1_nag_wp
      rhoend = 1.0E-6_nag_wp
      n = 4
      npt = 2*n + 1

!     x(3) is unconstrained, so we're going to set bl(3) to a large
!     negative number and bu(3) to a large positive number.

      infbnd = x02alf()**0.25_nag_wp

      Allocate (bl(n),bu(n),x(n))

      bl(1:n) = (/1.0_nag_wp,-2.0_nag_wp,-infbnd,1.0_nag_wp/)
      bu(1:n) = (/3.0_nag_wp,0.0_nag_wp,infbnd,3.0_nag_wp/)
      x(1:n) = (/3.0_nag_wp,-1.0_nag_wp,0.0_nag_wp,1.0_nag_wp/)

      ifail = -1
      Call e04jcf(objfun,n,npt,x,bl,bu,rhobeg,rhoend,monfun,maxcal,f,nf,iuser, &
        ruser,ifail)

      Select Case (ifail)
      Case (0,2:5)

        If (ifail==0) Then
          Write (nout,Fmt=99999) 'Successful exit from E04JCF.',               &
            'Function value at lowest point found =', f
        Else
          Write (nout,Fmt=99998)                                               &
            'On exit from E04JCF, function value at lowest point found =', f
        End If

        Write (nout,Fmt=99997) 'The corresponding X is:', x(1:n)
      End Select

99999 Format (2(/,1X,A),1P,E13.3)
99998 Format (/,1X,A,1P,E13.3)
99997 Format (1X,A,/,(2X,5E13.3))
    End Program e04jcfe


e04jyfe.f90

!   E04JYF Example Program Text
!   Mark 26 Release. NAG Copyright 2016.
    Module e04jyfe_mod

!     E04JYF Example Program Module:
!            Parameters and User-defined Routines

!     .. Use Statements ..
      Use nag_library, Only: nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Accessibility Statements ..
      Private
      Public                           :: funct1
!     .. Parameters ..
      Integer, Parameter, Public       :: n = 4, nout = 6
      Integer, Parameter, Public       :: liw = n + 2
      Integer, Parameter, Public       :: lw = n*(n-1)/2 + 12*n
    Contains
      Subroutine funct1(n,xc,fc,iuser,ruser)
!       Routine to evaluate objective function.

!       .. Scalar Arguments ..
        Real (Kind=nag_wp), Intent (Out) :: fc
        Integer, Intent (In)           :: n
!       .. Array Arguments ..
        Real (Kind=nag_wp), Intent (Inout) :: ruser(*)
        Real (Kind=nag_wp), Intent (In) :: xc(n)
        Integer, Intent (Inout)        :: iuser(*)
!       .. Local Scalars ..
        Real (Kind=nag_wp)             :: x1, x2, x3, x4
!       .. Executable Statements ..
        x1 = xc(1)
        x2 = xc(2)
        x3 = xc(3)
        x4 = xc(4)
        fc = (x1+10.0_nag_wp*x2)**2 + 5.0_nag_wp*(x3-x4)**2 +                  &
          (x2-2.0_nag_wp*x3)**4 + 10.0_nag_wp*(x1-x4)**4

        Return

      End Subroutine funct1
    End Module e04jyfe_mod
    Program e04jyfe

!     E04JYF Example Main Program

!     .. Use Statements ..
      Use nag_library, Only: e04jyf, nag_wp
      Use e04jyfe_mod, Only: funct1, liw, lw, n, nout
!     .. Implicit None Statement ..
      Implicit None
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: f
      Integer                          :: ibound, ifail
!     .. Local Arrays ..
      Real (Kind=nag_wp)               :: bl(n), bu(n), ruser(n), w(lw), x(n)
      Integer                          :: iuser(n), iw(6)
!     .. Executable Statements ..
      Write (nout,*) 'E04JYF Example Program Results'
      Flush (nout)

      x(1:n) = (/3.0_nag_wp,-1.0_nag_wp,0.0_nag_wp,1.0_nag_wp/)
      ibound = 0

!     X(3) is unconstrained, so we set BL(3) to a large negative
!     number and BU(3) to a large positive number.

      bl(1:n) = (/1.0_nag_wp,-2.0_nag_wp,-1.0E6_nag_wp,1.0_nag_wp/)
      bu(1:n) = (/3.0_nag_wp,0.0_nag_wp,1.0E6_nag_wp,3.0_nag_wp/)

      ifail = -1
      Call e04jyf(n,ibound,funct1,bl,bu,x,f,iw,liw,w,lw,iuser,ruser,ifail)

      Select Case (ifail)
      Case (0,2:)
        Write (nout,*)
        Write (nout,99999) 'Function value on exit is ', f
        Write (nout,99998) 'at the point', x(1:n)
      End Select

99999 Format (1X,A,F8.4)
99998 Format (1X,A,4F9.4)
    End Program e04jyfe


e04kdfe.f90

!   E04KDF Example Program Text
!   Mark 26 Release. NAG Copyright 2016.
    Module e04kdfe_mod

!     E04KDF Example Program Module:
!            Parameters and User-defined Routines

!     .. Use Statements ..
      Use nag_library, Only: nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Accessibility Statements ..
      Private
      Public                           :: funct, monit
!     .. Parameters ..
      Integer, Parameter, Public       :: liw = 2, n = 4, nout = 6
      Integer, Parameter, Public       :: lh = n*(n-1)/2
      Integer, Parameter, Public       :: lw = 7*n + n*(n-1)/2
    Contains
      Subroutine funct(iflag,n,xc,fc,gc,iw,liw,w,lw)
!       Routine to evaluate objective function and its 1st derivatives.
!       A global variable could be updated here to count the number of
!       calls of FUNCT with IFLAG = 1 (since NF in MONIT only counts
!       calls with IFLAG = 2)

!       .. Scalar Arguments ..
        Real (Kind=nag_wp), Intent (Out) :: fc
        Integer, Intent (Inout)        :: iflag
        Integer, Intent (In)           :: liw, lw, n
!       .. Array Arguments ..
        Real (Kind=nag_wp), Intent (Out) :: gc(n)
        Real (Kind=nag_wp), Intent (Inout) :: w(lw)
        Real (Kind=nag_wp), Intent (In) :: xc(n)
        Integer, Intent (Inout)        :: iw(liw)
!       .. Executable Statements ..
        If (iflag/=1) Then
          fc = (xc(1)+10.0_nag_wp*xc(2))**2 + 5.0_nag_wp*(xc(3)-xc(4))**2 +    &
            (xc(2)-2.0_nag_wp*xc(3))**4 + 10.0_nag_wp*(xc(1)-xc(4))**4
        End If

        gc(1) = 2.0_nag_wp*(xc(1)+10.0_nag_wp*xc(2)) +                         &
          40.0_nag_wp*(xc(1)-xc(4))**3
        gc(2) = 20.0_nag_wp*(xc(1)+10.0_nag_wp*xc(2)) +                        &
          4.0_nag_wp*(xc(2)-2.0_nag_wp*xc(3))**3
        gc(3) = 10.0_nag_wp*(xc(3)-xc(4)) - 8.0_nag_wp*(xc(2)-2.0_nag_wp*xc(3) &
          )**3
        gc(4) = 10.0_nag_wp*(xc(4)-xc(3)) - 40.0_nag_wp*(xc(1)-xc(4))**3

        Return

      End Subroutine funct
      Subroutine monit(n,xc,fc,gc,istate,gpjnrm,cond,posdef,niter,nf,iw,liw,w, &
        lw)
!       Monitoring routine

!       .. Scalar Arguments ..
        Real (Kind=nag_wp), Intent (In) :: cond, fc, gpjnrm
        Integer, Intent (In)           :: liw, lw, n, nf, niter
        Logical, Intent (In)           :: posdef
!       .. Array Arguments ..
        Real (Kind=nag_wp), Intent (In) :: gc(n), xc(n)
        Real (Kind=nag_wp), Intent (Inout) :: w(lw)
        Integer, Intent (In)           :: istate(n)
        Integer, Intent (Inout)        :: iw(liw)
!       .. Local Scalars ..
        Integer                        :: isj, j
!       .. Executable Statements ..
        Write (nout,*)
        Write (nout,*) ' Itn     Fn evals              Fn value' //            &
          '            Norm of proj gradient'
        Write (nout,99999) niter, nf, fc, gpjnrm
        Write (nout,*)
        Write (nout,*)                                                         &
          ' J           X(J)                G(J)           Status'

        Do j = 1, n
          isj = istate(j)

          Select Case (isj)
          Case (1:)
            Write (nout,99998) j, xc(j), gc(j), '    Free'
          Case (-1)
            Write (nout,99998) j, xc(j), gc(j), '    Upper Bound'
          Case (-2)
            Write (nout,99998) j, xc(j), gc(j), '    Lower Bound'
          Case (-3)
            Write (nout,99998) j, xc(j), gc(j), '    Constant'
          End Select

        End Do

        If (cond/=0.0_nag_wp) Then

          If (cond>1.0E6_nag_wp) Then
            Write (nout,*)
            Write (nout,*)                                                     &
              'Estimated condition number of projected Hessian is more than ', &
              '1.0E+6'
          Else
            Write (nout,*)
            Write (nout,99997)                                                 &
              'Estimated condition number of projected Hessian = ', cond
          End If

          If (.Not. posdef) Then
            Write (nout,*)
            Write (nout,*) 'Projected Hessian matrix is not positive definite'
          End If

        End If

        Return

99999   Format (1X,I3,6X,I5,2(6X,1P,E20.4))
99998   Format (1X,I2,1X,1P,2E20.4,A)
99997   Format (1X,A,1P,E10.2)
      End Subroutine monit
    End Module e04kdfe_mod
    Program e04kdfe

!     E04KDF Example Main Program

!     .. Use Statements ..
      Use nag_library, Only: e04hcf, e04kdf, nag_wp
      Use e04kdfe_mod, Only: funct, lh, liw, lw, monit, n, nout
!     .. Implicit None Statement ..
      Implicit None
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: delta, eta, f, stepmx, xtol
      Integer                          :: ibound, ifail, iprint, maxcal
!     .. Local Arrays ..
      Real (Kind=nag_wp)               :: bl(n), bu(n), g(n), hesd(n),         &
                                          hesl(lh), w(lw), x(n)
      Integer                          :: istate(n), iw(liw)
!     .. Executable Statements ..
      Write (nout,*) 'E04KDF Example Program Results'
      Flush (nout)

!     Check FUNCT by calling E04HCF at an arbitrary point. Since E04HCF
!     only checks the derivatives calculated when IFLAG = 2, a separate
!     program should be run before using E04HCF or E04KDF to check that
!     FUNCT gives the same values for the GC(J) when IFLAG is set to 1
!     as when IFLAG is set to 2.

      x(1:n) = (/1.46_nag_wp,-0.82_nag_wp,0.57_nag_wp,1.21_nag_wp/)

      ifail = 0
      Call e04hcf(n,funct,x,f,g,iw,liw,w,lw,ifail)

!     Continue setting parameters for E04KDF

!     Set IPRINT to 1 to obtain output from MONIT at each iteration
      iprint = -1

      maxcal = 50*n
      eta = 0.5_nag_wp

!     Set XTOL and DELTA to zero so that E04KDF will use the default
!     values

      xtol = 0.0_nag_wp
      delta = 0.0_nag_wp

!     We estimate that the minimum will be within 4 units of the
!     starting point

      stepmx = 4.0_nag_wp

      ibound = 0

!     X(3) is not bounded, so we set BL(3) to a large negative
!     number and BU(3) to a large positive number

      bl(1:n) = (/1.0_nag_wp,-2.0_nag_wp,-1.0E6_nag_wp,1.0_nag_wp/)
      bu(1:n) = (/3.0_nag_wp,0.0_nag_wp,1.0E6_nag_wp,3.0_nag_wp/)

!     Set up starting point

      x(1:n) = (/3.0_nag_wp,-1.0_nag_wp,0.0_nag_wp,1.0_nag_wp/)

      ifail = -1
      Call e04kdf(n,funct,monit,iprint,maxcal,eta,xtol,delta,stepmx,ibound,bl, &
        bu,x,hesl,lh,hesd,istate,f,g,iw,liw,w,lw,ifail)

      Select Case (ifail)
      Case (0,2:)
        Write (nout,*)
        Write (nout,99999) 'Function value on exit is ', f
        Write (nout,99999) 'at the point', x(1:n)
        Write (nout,*) 'The corresponding (machine dependent) gradient is'
        Write (nout,99998) g(1:n)
        Write (nout,99997) 'ISTATE contains', istate(1:n)
        Write (nout,99996) 'and HESD contains', hesd(1:n)
      End Select

99999 Format (1X,A,4F12.4)
99998 Format (24X,1P,4E12.3)
99997 Format (1X,A,4I5)
99996 Format (1X,A,4E12.4)
    End Program e04kdfe


e04kyfe.f90

!   E04KYF Example Program Text
!   Mark 26 Release. NAG Copyright 2016.
    Module e04kyfe_mod

!     E04KYF Example Program Module:
!            Parameters and User-defined Routines

!     .. Use Statements ..
      Use nag_library, Only: nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Accessibility Statements ..
      Private
      Public                           :: funct2
!     .. Parameters ..
      Integer, Parameter, Public       :: n = 4, nout = 6
      Integer, Parameter, Public       :: liw = n + 2
      Integer, Parameter, Public       :: lw = 10*n + n*(n-1)/2
    Contains
      Subroutine funct2(n,xc,fc,gc,iuser,ruser)
!       Routine to evaluate objective function and its 1st derivatives.

!       .. Scalar Arguments ..
        Real (Kind=nag_wp), Intent (Out) :: fc
        Integer, Intent (In)           :: n
!       .. Array Arguments ..
        Real (Kind=nag_wp), Intent (Out) :: gc(n)
        Real (Kind=nag_wp), Intent (Inout) :: ruser(*)
        Real (Kind=nag_wp), Intent (In) :: xc(n)
        Integer, Intent (Inout)        :: iuser(*)
!       .. Local Scalars ..
        Real (Kind=nag_wp)             :: x1, x2, x3, x4
!       .. Executable Statements ..
        x1 = xc(1)
        x2 = xc(2)
        x3 = xc(3)
        x4 = xc(4)
        fc = (x1+10.0_nag_wp*x2)**2 + 5.0_nag_wp*(x3-x4)**2 +                  &
          (x2-2.0_nag_wp*x3)**4 + 10.0_nag_wp*(x1-x4)**4
        gc(1) = 2.0_nag_wp*(x1+10.0_nag_wp*x2) + 40.0_nag_wp*(x1-x4)**3
        gc(2) = 20.0_nag_wp*(x1+10.0_nag_wp*x2) + 4.0_nag_wp*(x2-2.0_nag_wp*x3 &
          )**3
        gc(3) = 10.0_nag_wp*(x3-x4) - 8.0_nag_wp*(x2-2.0_nag_wp*x3)**3
        gc(4) = -10.0_nag_wp*(x3-x4) - 40.0_nag_wp*(x1-x4)**3

        Return

      End Subroutine funct2
    End Module e04kyfe_mod
    Program e04kyfe

!     E04KYF Example Main Program

!     .. Use Statements ..
      Use nag_library, Only: e04kyf, nag_wp
      Use e04kyfe_mod, Only: funct2, liw, lw, n, nout
!     .. Implicit None Statement ..
      Implicit None
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: f
      Integer                          :: ibound, ifail
!     .. Local Arrays ..
      Real (Kind=nag_wp)               :: bl(n), bu(n), g(n), ruser(1), w(lw), &
                                          x(n)
      Integer                          :: iuser(1), iw(liw)
!     .. Executable Statements ..
      Write (nout,*) 'E04KYF Example Program Results'

      x(1:n) = (/3.0_nag_wp,-1.0_nag_wp,0.0_nag_wp,1.0_nag_wp/)
      ibound = 0

!     X(3) is unconstrained, so we set BL(3) to a large negative
!     number and BU(3) to a large positive number.

      bl(1:n) = (/1.0_nag_wp,-2.0_nag_wp,-1.0E6_nag_wp,1.0_nag_wp/)
      bu(1:n) = (/3.0_nag_wp,0.0_nag_wp,1.0E6_nag_wp,3.0_nag_wp/)

      ifail = -1
      Call e04kyf(n,ibound,funct2,bl,bu,x,f,g,iw,liw,w,lw,iuser,ruser,ifail)

      Select Case (ifail)
      Case (0,2:)
        Write (nout,*)
        Write (nout,99999) 'Function value on exit is ', f
        Write (nout,99998) 'at the point', x(1:n)
        Write (nout,*) 'The corresponding (machine dependent) gradient is'
        Write (nout,99997) g(1:n)
      End Select

99999 Format (1X,A,F9.4)
99998 Format (1X,A,4F9.4)
99997 Format (13X,4E12.4)
    End Program e04kyfe


e04kzfe.f90

!   E04KZF Example Program Text
!   Mark 26 Release. NAG Copyright 2016.
    Module e04kzfe_mod

!     E04KZF Example Program Module:
!            Parameters and User-defined Routines

!     .. Use Statements ..
      Use nag_library, Only: nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Accessibility Statements ..
      Private
      Public                           :: funct2
!     .. Parameters ..
      Integer, Parameter, Public       :: n = 4, nout = 6
      Integer, Parameter, Public       :: liw = n + 2
      Integer, Parameter, Public       :: lw = n*(n+7)
    Contains
      Subroutine funct2(n,xc,fc,gc,iuser,ruser)
!       Routine to evaluate objective function and its 1st derivatives.

!       .. Scalar Arguments ..
        Real (Kind=nag_wp), Intent (Out) :: fc
        Integer, Intent (In)           :: n
!       .. Array Arguments ..
        Real (Kind=nag_wp), Intent (Out) :: gc(n)
        Real (Kind=nag_wp), Intent (Inout) :: ruser(*)
        Real (Kind=nag_wp), Intent (In) :: xc(n)
        Integer, Intent (Inout)        :: iuser(*)
!       .. Local Scalars ..
        Real (Kind=nag_wp)             :: x1, x2, x3, x4
!       .. Executable Statements ..
        x1 = xc(1)
        x2 = xc(2)
        x3 = xc(3)
        x4 = xc(4)
        fc = (x1+10.0_nag_wp*x2)**2 + 5.0_nag_wp*(x3-x4)**2 +                  &
          (x2-2.0_nag_wp*x3)**4 + 10.0_nag_wp*(x1-x4)**4
        gc(1) = 2.0_nag_wp*(x1+10.0_nag_wp*x2) + 40.0_nag_wp*(x1-x4)**3
        gc(2) = 20.0_nag_wp*(x1+10.0_nag_wp*x2) + 4.0_nag_wp*(x2-2.0_nag_wp*x3 &
          )**3
        gc(3) = 10.0_nag_wp*(x3-x4) - 8.0_nag_wp*(x2-2.0_nag_wp*x3)**3
        gc(4) = -10.0_nag_wp*(x3-x4) - 40.0_nag_wp*(x1-x4)**3

        Return

      End Subroutine funct2
    End Module e04kzfe_mod
    Program e04kzfe

!     E04KZF Example Main Program

!     .. Use Statements ..
      Use nag_library, Only: e04kzf, nag_wp
      Use e04kzfe_mod, Only: funct2, liw, lw, n, nout
!     .. Implicit None Statement ..
      Implicit None
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: f
      Integer                          :: ibound, ifail
!     .. Local Arrays ..
      Real (Kind=nag_wp)               :: bl(n), bu(n), g(n), ruser(1), w(lw), &
                                          x(n)
      Integer                          :: iuser(1), iw(liw)
!     .. Executable Statements ..
      Write (nout,*) 'E04KZF Example Program Results'
      Flush (nout)

      x(1:n) = (/3.0_nag_wp,-1.0_nag_wp,0.0_nag_wp,1.0_nag_wp/)

      ibound = 0

!     X(3) is unconstrained, so we set BL(3) to a large negative
!     number and BU(3) to a large positive number.

      bl(1:n) = (/1.0_nag_wp,-2.0_nag_wp,-1.0E6_nag_wp,1.0_nag_wp/)
      bu(1:n) = (/3.0_nag_wp,0.0_nag_wp,1.0E6_nag_wp,3.0_nag_wp/)

      ifail = -1
      Call e04kzf(n,ibound,funct2,bl,bu,x,f,g,iw,liw,w,lw,iuser,ruser,ifail)

      Select Case (ifail)
      Case (0,2:)
        Write (nout,*)
        Write (nout,99999) 'Function value on exit is ', f
        Write (nout,99999) 'at the point', x(1:n)
        Write (nout,*) 'the corresponding (machine dependent) gradient is'
        Write (nout,99998) g(1:n)
      End Select

99999 Format (1X,A,4F12.4)
99998 Format (13X,4E12.4)
    End Program e04kzfe


e04lbfe.f90

!   E04LBF Example Program Text
!   Mark 26 Release. NAG Copyright 2016.
    Module e04lbfe_mod

!     E04LBF Example Program Module:
!            Parameters and User-defined Routines

!     .. Use Statements ..
      Use nag_library, Only: nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Accessibility Statements ..
      Private
      Public                           :: funct, h, monit
!     .. Parameters ..
      Integer, Parameter, Public       :: liw = 2, n = 4, nout = 6
      Integer, Parameter, Public       :: lh = n*(n-1)/2
      Integer, Parameter, Public       :: lw = 7*n + n*(n-1)/2
    Contains
      Subroutine funct(iflag,n,xc,fc,gc,iw,liw,w,lw)
!       Routine to evaluate objective function and its 1st derivatives.

!       .. Scalar Arguments ..
        Real (Kind=nag_wp), Intent (Out) :: fc
        Integer, Intent (Inout)        :: iflag
        Integer, Intent (In)           :: liw, lw, n
!       .. Array Arguments ..
        Real (Kind=nag_wp), Intent (Out) :: gc(n)
        Real (Kind=nag_wp), Intent (Inout) :: w(lw)
        Real (Kind=nag_wp), Intent (In) :: xc(n)
        Integer, Intent (Inout)        :: iw(liw)
!       .. Executable Statements ..
        fc = (xc(1)+10.0_nag_wp*xc(2))**2 + 5.0_nag_wp*(xc(3)-xc(4))**2 +      &
          (xc(2)-2.0_nag_wp*xc(3))**4 + 10.0_nag_wp*(xc(1)-xc(4))**4
        gc(1) = 2.0_nag_wp*(xc(1)+10.0_nag_wp*xc(2)) +                         &
          40.0_nag_wp*(xc(1)-xc(4))**3
        gc(2) = 20.0_nag_wp*(xc(1)+10.0_nag_wp*xc(2)) +                        &
          4.0_nag_wp*(xc(2)-2.0_nag_wp*xc(3))**3
        gc(3) = 10.0_nag_wp*(xc(3)-xc(4)) - 8.0_nag_wp*(xc(2)-2.0_nag_wp*xc(3) &
          )**3
        gc(4) = 10.0_nag_wp*(xc(4)-xc(3)) - 40.0_nag_wp*(xc(1)-xc(4))**3

        Return

      End Subroutine funct
      Subroutine h(iflag,n,xc,fhesl,lh,fhesd,iw,liw,w,lw)
!       Routine to evaluate 2nd derivatives

!       .. Scalar Arguments ..
        Integer, Intent (Inout)        :: iflag
        Integer, Intent (In)           :: lh, liw, lw, n
!       .. Array Arguments ..
        Real (Kind=nag_wp), Intent (Inout) :: fhesd(n), w(lw)
        Real (Kind=nag_wp), Intent (Out) :: fhesl(lh)
        Real (Kind=nag_wp), Intent (In) :: xc(n)
        Integer, Intent (Inout)        :: iw(liw)
!       .. Executable Statements ..
        fhesd(1) = 2.0_nag_wp + 120.0_nag_wp*(xc(1)-xc(4))**2
        fhesd(2) = 200.0_nag_wp + 12.0_nag_wp*(xc(2)-2.0_nag_wp*xc(3))**2
        fhesd(3) = 10.0_nag_wp + 48.0_nag_wp*(xc(2)-2.0_nag_wp*xc(3))**2
        fhesd(4) = 10.0_nag_wp + 120.0_nag_wp*(xc(1)-xc(4))**2
        fhesl(1) = 20.0_nag_wp
        fhesl(2) = 0.0_nag_wp
        fhesl(3) = -24.0_nag_wp*(xc(2)-2.0_nag_wp*xc(3))**2
        fhesl(4) = -120.0_nag_wp*(xc(1)-xc(4))**2
        fhesl(5) = 0.0_nag_wp
        fhesl(6) = -10.0_nag_wp

        Return

      End Subroutine h
      Subroutine monit(n,xc,fc,gc,istate,gpjnrm,cond,posdef,niter,nf,iw,liw,w, &
        lw)
!       Monitoring routine

!       .. Scalar Arguments ..
        Real (Kind=nag_wp), Intent (In) :: cond, fc, gpjnrm
        Integer, Intent (In)           :: liw, lw, n, nf, niter
        Logical, Intent (In)           :: posdef
!       .. Array Arguments ..
        Real (Kind=nag_wp), Intent (In) :: gc(n), xc(n)
        Real (Kind=nag_wp), Intent (Inout) :: w(lw)
        Integer, Intent (In)           :: istate(n)
        Integer, Intent (Inout)        :: iw(liw)
!       .. Local Scalars ..
        Integer                        :: isj, j
!       .. Executable Statements ..
        Write (nout,*)
        Write (nout,*) ' Itn     Fn evals              Fn value            ',  &
          'Norm of proj gradient'
        Write (nout,99999) niter, nf, fc, gpjnrm
        Write (nout,*)
        Write (nout,*)                                                         &
          ' J           X(J)                G(J)           Status'

        Do j = 1, n
          isj = istate(j)

          Select Case (isj)
          Case (1:)
            Write (nout,99998) j, xc(j), gc(j), '    Free'
          Case (-1)
            Write (nout,99998) j, xc(j), gc(j), '    Upper Bound'
          Case (-2)
            Write (nout,99998) j, xc(j), gc(j), '    Lower Bound'
          Case (-3)
            Write (nout,99998) j, xc(j), gc(j), '    Constant'
          End Select

        End Do

        If (cond/=0.0_nag_wp) Then

          If (cond>1.0E6_nag_wp) Then
            Write (nout,*)
            Write (nout,*)                                                     &
              'Estimated condition number of projected Hessian is more than ', &
              '1.0E+6'
          Else
            Write (nout,*)
            Write (nout,99997)                                                 &
              'Estimated condition number of projected Hessian = ', cond
          End If

          If (.Not. posdef) Then
            Write (nout,*)
            Write (nout,*) 'Projected Hessian matrix is not positive definite'
          End If

        End If

        Return

99999   Format (1X,I3,6X,I5,2(6X,1P,E20.4))
99998   Format (1X,I2,1X,1P,2E20.4,A)
99997   Format (1X,A,1P,E10.2)
      End Subroutine monit
    End Module e04lbfe_mod
    Program e04lbfe

!     E04LBF Example Main Program

!     .. Use Statements ..
      Use nag_library, Only: e04hcf, e04hdf, e04lbf, nag_wp
      Use e04lbfe_mod, Only: funct, h, lh, liw, lw, monit, n, nout
!     .. Implicit None Statement ..
      Implicit None
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: eta, f, stepmx, xtol
      Integer                          :: ibound, ifail, iprint, maxcal, nz
!     .. Local Arrays ..
      Real (Kind=nag_wp)               :: bl(n), bu(n), g(n), hesd(n),         &
                                          hesl(lh), w(lw), x(n)
      Integer                          :: istate(n), iw(liw)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: count
!     .. Executable Statements ..
      Write (nout,*) 'E04LBF Example Program Results'
      Flush (nout)

!     Set up an arbitrary point at which to check the derivatives

      x(1:n) = (/1.46_nag_wp,-0.82_nag_wp,0.57_nag_wp,1.21_nag_wp/)

!     Check the 1st derivatives

      ifail = 0
      Call e04hcf(n,funct,x,f,g,iw,liw,w,lw,ifail)

!     Check the 2nd derivatives

      ifail = 0
      Call e04hdf(n,funct,h,x,g,hesl,lh,hesd,iw,liw,w,lw,ifail)

!     Continue setting parameters for E04LBF

!     Set IPRINT to 1 to obtain output from MONIT at each iteration
      iprint = -1

      maxcal = 50*n
      eta = 0.9_nag_wp

!     Set XTOL to zero so that E04LBF will use the default tolerance

      xtol = 0.0_nag_wp

!     We estimate that the minimum will be within 4 units of the
!     starting point

      stepmx = 4.0_nag_wp

      ibound = 0

!     X(3) is unconstrained, so we set BL(3) to a large negative
!     number and BU(3) to a large positive number.

      bl(1:n) = (/1.0_nag_wp,-2.0_nag_wp,-1.0E6_nag_wp,1.0_nag_wp/)
      bu(1:n) = (/3.0_nag_wp,0.0_nag_wp,1.0E6_nag_wp,3.0_nag_wp/)

!     Set up starting point

      x(1:n) = (/3.0_nag_wp,-1.0_nag_wp,0.0_nag_wp,1.0_nag_wp/)

      ifail = -1
      Call e04lbf(n,funct,h,monit,iprint,maxcal,eta,xtol,stepmx,ibound,bl,bu,  &
        x,hesl,lh,hesd,istate,f,g,iw,liw,w,lw,ifail)

      Select Case (ifail)
      Case (0,2:)
        Write (nout,*)
        Write (nout,99999) 'Function value on exit is ', f
        Write (nout,99998) 'at the point', x(1:n)
        Write (nout,*) 'The corresponding (machine dependent) gradient is'
        Write (nout,99997) g(1:n)
        Write (nout,99996) 'ISTATE contains', istate(1:n)

        nz = count(istate(1:n)>0)

        Write (nout,99995) 'and HESD contains', hesd(1:nz)
      End Select

99999 Format (1X,A,F9.4)
99998 Format (1X,A,4F9.4)
99997 Format (23X,1P,4E12.3)
99996 Format (1X,A,4I5)
99995 Format (1X,A,4E12.4)
    End Program e04lbfe


e04lyfe.f90

!   E04LYF Example Program Text
!   Mark 26 Release. NAG Copyright 2016.
    Module e04lyfe_mod

!     E04LYF Example Program Module:
!            Parameters and User-defined Routines

!     .. Use Statements ..
      Use nag_library, Only: nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Accessibility Statements ..
      Private
      Public                           :: funct2, hess2
!     .. Parameters ..
      Integer, Parameter, Public       :: n = 4, nout = 6
      Integer, Parameter, Public       :: liw = n + 2
      Integer, Parameter, Public       :: lw = n*(n+7)
    Contains
      Subroutine funct2(n,xc,fc,gc,iuser,ruser)
!       Routine to evaluate objective function and its 1st derivatives.

!       .. Scalar Arguments ..
        Real (Kind=nag_wp), Intent (Out) :: fc
        Integer, Intent (In)           :: n
!       .. Array Arguments ..
        Real (Kind=nag_wp), Intent (Out) :: gc(n)
        Real (Kind=nag_wp), Intent (Inout) :: ruser(*)
        Real (Kind=nag_wp), Intent (In) :: xc(n)
        Integer, Intent (Inout)        :: iuser(*)
!       .. Local Scalars ..
        Real (Kind=nag_wp)             :: x1, x2, x3, x4
!       .. Executable Statements ..
        x1 = xc(1)
        x2 = xc(2)
        x3 = xc(3)
        x4 = xc(4)
        fc = (x1+10.0_nag_wp*x2)**2 + 5.0_nag_wp*(x3-x4)**2 +                  &
          (x2-2.0_nag_wp*x3)**4 + 10.0_nag_wp*(x1-x4)**4
        gc(1) = 2.0_nag_wp*(x1+10.0_nag_wp*x2) + 40.0_nag_wp*(x1-x4)**3
        gc(2) = 20.0_nag_wp*(x1+10.0_nag_wp*x2) + 4.0_nag_wp*(x2-2.0_nag_wp*x3 &
          )**3
        gc(3) = 10.0_nag_wp*(x3-x4) - 8.0_nag_wp*(x2-2.0_nag_wp*x3)**3
        gc(4) = -10.0_nag_wp*(x3-x4) - 40.0_nag_wp*(x1-x4)**3

        Return

      End Subroutine funct2
      Subroutine hess2(n,xc,heslc,lh,hesdc,iuser,ruser)
!       Routine to evaluate 2nd derivatives.

!       .. Scalar Arguments ..
        Integer, Intent (In)           :: lh, n
!       .. Array Arguments ..
        Real (Kind=nag_wp), Intent (Out) :: hesdc(n), heslc(lh)
        Real (Kind=nag_wp), Intent (Inout) :: ruser(*)
        Real (Kind=nag_wp), Intent (In) :: xc(n)
        Integer, Intent (Inout)        :: iuser(*)
!       .. Local Scalars ..
        Real (Kind=nag_wp)             :: x1, x2, x3, x4
!       .. Executable Statements ..
        x1 = xc(1)
        x2 = xc(2)
        x3 = xc(3)
        x4 = xc(4)
        hesdc(1) = 2.0_nag_wp + 120.0_nag_wp*(x1-x4)**2
        hesdc(2) = 200.0_nag_wp + 12.0_nag_wp*(x2-2.0_nag_wp*x3)**2
        hesdc(3) = 10.0_nag_wp + 48.0_nag_wp*(x2-2.0_nag_wp*x3)**2
        hesdc(4) = 10.0_nag_wp + 120.0_nag_wp*(x1-x4)**2
        heslc(1) = 20.0_nag_wp
        heslc(2) = 0.0_nag_wp
        heslc(3) = -24.0_nag_wp*(x2-2.0_nag_wp*x3)**2
        heslc(4) = -120.0_nag_wp*(x1-x4)**2
        heslc(5) = 0.0_nag_wp
        heslc(6) = -10.0_nag_wp

        Return

      End Subroutine hess2
    End Module e04lyfe_mod
    Program e04lyfe

!     E04LYF Example Main Program

!     .. Use Statements ..
      Use nag_library, Only: e04lyf, nag_wp
      Use e04lyfe_mod, Only: funct2, hess2, liw, lw, n, nout
!     .. Implicit None Statement ..
      Implicit None
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: f
      Integer                          :: ibound, ifail
!     .. Local Arrays ..
      Real (Kind=nag_wp)               :: bl(n), bu(n), g(n), ruser(1), w(lw), &
                                          x(n)
      Integer                          :: iuser(1), iw(liw)
!     .. Executable Statements ..
      Write (nout,*) 'E04LYF Example Program Results'
      Flush (nout)

      ibound = 0

!     X(3) is unconstrained, so we set BL(3) to a large negative
!     number and BU(3) to a large positive number.

      bl(1:n) = (/1.0_nag_wp,-2.0_nag_wp,-1.0E6_nag_wp,1.0_nag_wp/)
      bu(1:n) = (/3.0_nag_wp,0.0_nag_wp,1.0E6_nag_wp,3.0_nag_wp/)

!     Set up starting point

      x(1:n) = (/3.0_nag_wp,-1.0_nag_wp,0.0_nag_wp,1.0_nag_wp/)

      ifail = -1
      Call e04lyf(n,ibound,funct2,hess2,bl,bu,x,f,g,iw,liw,w,lw,iuser,ruser,   &
        ifail)

      Select Case (ifail)
      Case (0,2:)
        Write (nout,*)
        Write (nout,99999) 'Function value on exit is ', f
        Write (nout,99999) 'at the point', x(1:n)
        Write (nout,*) 'The corresponding (machine dependent) gradient is'
        Write (nout,99998) g(1:n)
      End Select

99999 Format (1X,A,4F9.4)
99998 Format (13X,4E12.4)
    End Program e04lyfe


e04mfae.f90

    Program e04mfae

!     E04MFA Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: e04mfa, e04wbf, nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: lcwsav = 1, liwsav = 610,            &
                                          llwsav = 120, lrwsav = 475, nin = 5, &
                                          nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: obj
      Integer                          :: i, ifail, iter, j, lda, liwork,      &
                                          lwork, n, nclin, sda
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: a(:,:), ax(:), bl(:), bu(:),         &
                                          clamda(:), cvec(:), work(:), x(:)
      Real (Kind=nag_wp)               :: rwsav(lrwsav)
      Integer, Allocatable             :: istate(:), iwork(:)
      Integer                          :: iwsav(liwsav)
      Logical                          :: lwsav(llwsav)
      Character (80)                   :: cwsav(lcwsav)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: max
!     .. Executable Statements ..
      Write (nout,*) 'E04MFA Example Program Results'

!     Skip heading in data file

      Read (nin,*)
      Read (nin,*) n, nclin
      liwork = 2*n + 3

!     The minimum LWORK for an LP problem:

      If (0<nclin .And. nclin<n) Then
        lwork = 2*(nclin+1)**2 + 7*n + 5*nclin
      Else If (nclin>=n) Then
        lwork = 2*n**2 + 7*n + 5*nclin
      Else
        lwork = 7*n + 1
      End If

      lda = max(1,nclin)

      If (nclin>0) Then
        sda = n
      Else
        sda = 1
      End If

      Allocate (istate(n+nclin),iwork(liwork),a(lda,sda),bl(n+nclin),          &
        bu(n+nclin),cvec(n),x(n),ax(max(1,nclin)),clamda(n+nclin),work(lwork))

      Read (nin,*) cvec(1:n)
      Read (nin,*)(a(i,1:sda),i=1,nclin)
      Read (nin,*) bl(1:(n+nclin))
      Read (nin,*) bu(1:(n+nclin))
      Read (nin,*) x(1:n)

!     Initialise E04MFA using E04WBF

      ifail = 0
      Call e04wbf('E04MFA',cwsav,lcwsav,lwsav,llwsav,iwsav,liwsav,rwsav,       &
        lrwsav,ifail)

!     Solve the problem

      ifail = -1
      Call e04mfa(n,nclin,a,lda,bl,bu,cvec,istate,x,iter,obj,ax,clamda,iwork,  &
        liwork,work,lwork,lwsav,iwsav,rwsav,ifail)

      Select Case (ifail)
      Case (0:5,7:)
        Write (nout,*)
        Write (nout,99999)
        Write (nout,*)

        Do i = 1, n
          Write (nout,99998) i, istate(i), x(i), clamda(i)
        End Do

        If (nclin>0) Then
          Write (nout,*)
          Write (nout,99997)
          Write (nout,*)

          Do i = n + 1, n + nclin
            j = i - n
            Write (nout,99996) j, istate(i), ax(j), clamda(i)
          End Do

        End If

        Write (nout,*)
        Write (nout,99995) obj
      End Select

99999 Format (1X,'Varbl',3X,'Istate',4X,'Value',9X,'Lagr Mult')
99998 Format (1X,'V',2(1X,I3),4X,1P,E14.3,2X,1P,E12.3)
99997 Format (1X,'L Con',3X,'Istate',4X,'Value',9X,'Lagr Mult')
99996 Format (1X,'L',2(1X,I3),4X,1P,E14.3,2X,1P,E12.3)
99995 Format (1X,'Final objective value = ',1P,E15.3)
    End Program e04mfae


e04mffe.f90

    Program e04mffe

!     E04MFF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: e04mff, e04mhf, nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: obj
      Integer                          :: i, ifail, iter, j, lda, liwork,      &
                                          lwork, n, nclin, sda
      Logical                          :: verbose_output
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: a(:,:), ax(:), bl(:), bu(:),         &
                                          clamda(:), cvec(:), work(:), x(:)
      Integer, Allocatable             :: istate(:), iwork(:)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: max
!     .. Executable Statements ..
      Write (nout,*) 'E04MFF Example Program Results'

!     Skip heading in data file

      Read (nin,*)
      Read (nin,*) n, nclin
      liwork = 2*n + 3

!     The minimum LWORK for an LP problem:

      If (0<nclin .And. nclin<n) Then
        lwork = 2*(nclin+1)**2 + 7*n + 5*nclin
      Else If (nclin>=n) Then
        lwork = 2*n**2 + 7*n + 5*nclin
      Else
        lwork = 7*n + 1
      End If

      lda = max(1,nclin)

      If (nclin>0) Then
        sda = n
      Else
        sda = 1
      End If

      Allocate (istate(n+nclin),iwork(liwork),a(lda,sda),bl(n+nclin),          &
        bu(n+nclin),cvec(n),x(n),ax(max(1,nclin)),clamda(n+nclin),work(lwork))

      Read (nin,*) cvec(1:n)
      Read (nin,*)(a(i,1:sda),i=1,nclin)
      Read (nin,*) bl(1:(n+nclin))
      Read (nin,*) bu(1:(n+nclin))
      Read (nin,*) x(1:n)

!     Set this to .True. to cause e04nqf to produce intermediate
!     progress output
      verbose_output = .False.

      If (.Not. verbose_output) Then
!       Turn off intermediate output from e04mff - it is on by default
        Call e04mhf('Nolist')
        Call e04mhf('Print Level = 0')
      End If

!     Solve the problem

      ifail = 0
      Call e04mff(n,nclin,a,lda,bl,bu,cvec,istate,x,iter,obj,ax,clamda,iwork,  &
        liwork,work,lwork,ifail)

      Select Case (ifail)
      Case (0:5,7:)
        Write (nout,*)
        Write (nout,99999)
        Do i = 1, n
          Write (nout,99998) i, istate(i), x(i), clamda(i)
        End Do

        If (nclin>0) Then
          Write (nout,*)
          Write (nout,99997)
          Do i = n + 1, n + nclin
            j = i - n
            Write (nout,99996) j, istate(i), ax(j), clamda(i)
          End Do

        End If

        Write (nout,*)
        Write (nout,99995) obj
      End Select

99999 Format (1X,'Varbl',3X,'Istate',4X,'Value',9X,'Lagr Mult')
99998 Format (1X,'V',2(1X,I3),4X,1P,E14.3,2X,1P,E12.3)
99997 Format (1X,'L Con',3X,'Istate',4X,'Value',9X,'Lagr Mult')
99996 Format (1X,'L',2(1X,I3),4X,1P,E14.3,2X,1P,E12.3)
99995 Format (1X,'Final objective value = ',1P,E15.3)
    End Program e04mffe


e04mgae.f90

    Program e04mgae

!     E04MGA Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: e04mfa, e04mga, e04mha, e04wbf, nag_wp, x04abf,   &
                             x04acf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: iset = 1, lcwsav = 1, liwsav = 610,  &
                                          llwsav = 120, lrwsav = 475, nin = 5, &
                                          ninopt = 7, nout = 6
      Character (*), Parameter         :: fname = 'e04mgae.opt'
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: obj
      Integer                          :: i, ifail, inform, iter, j, lda,      &
                                          liwork, lwork, mode, n, nclin,       &
                                          outchn, sda
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: a(:,:), ax(:), bl(:), bu(:),         &
                                          clamda(:), cvec(:), work(:), x(:)
      Real (Kind=nag_wp)               :: rwsav(lrwsav)
      Integer, Allocatable             :: istate(:), iwork(:)
      Integer                          :: iwsav(liwsav)
      Logical                          :: lwsav(llwsav)
      Character (80)                   :: cwsav(lcwsav)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: max
!     .. Executable Statements ..
      Write (nout,*) 'E04MGA Example Program Results'

!     Skip heading in data file
      Read (nin,*)

      Read (nin,*) n, nclin

      liwork = 2*n + 3

!     The minimum LWORK for an LP problem:

      If (0<nclin .And. nclin<n) Then
        lwork = 2*(nclin+1)**2 + 7*n + 5*nclin
      Else If (nclin>=n) Then
        lwork = 2*n**2 + 7*n + 5*nclin
      Else
        lwork = 7*n + 1
      End If

      lda = max(1,nclin)

      If (nclin>0) Then
        sda = n
      Else
        sda = 1
      End If

      Allocate (istate(n+nclin),iwork(liwork),a(lda,sda),bl(n+nclin),          &
        bu(n+nclin),cvec(n),x(n),ax(max(1,nclin)),clamda(n+nclin),work(lwork))

      Read (nin,*) cvec(1:n)
      Read (nin,*)(a(i,1:sda),i=1,nclin)
      Read (nin,*) bl(1:(n+nclin))
      Read (nin,*) bu(1:(n+nclin))
      Read (nin,*) x(1:n)

!     Set the unit number for advisory messages to OUTCHN

      outchn = nout
      Call x04abf(iset,outchn)

!     Initialise E04MFA using E04WBF

      ifail = 0
      Call e04wbf('E04MFA',cwsav,lcwsav,lwsav,llwsav,iwsav,liwsav,rwsav,       &
        lrwsav,ifail)

!     Set two options using E04MHA

      Call e04mha(' Check Frequency = 10 ',lwsav,iwsav,rwsav,inform)

      If (inform==0) Then

        Call e04mha(' Infinite Bound Size = 1.0D+25 ',lwsav,iwsav,rwsav,       &
          inform)

      End If

      If (inform/=0) Then
        Write (nout,99999) 'E04MHA terminated with INFORM = ', inform
        Go To 100
      End If

!     Open the options file for reading

      mode = 0

      ifail = 0
      Call x04acf(ninopt,fname,mode,ifail)

!     Read the options file for the remaining options

      Call e04mga(ninopt,lwsav,iwsav,rwsav,inform)

      If (inform/=0) Then
        Write (nout,99999) 'E04MGA terminated with INFORM = ', inform
        Go To 100
      End If

!     Solve the problem

      ifail = -1
      Call e04mfa(n,nclin,a,lda,bl,bu,cvec,istate,x,iter,obj,ax,clamda,iwork,  &
        liwork,work,lwork,lwsav,iwsav,rwsav,ifail)

      Select Case (ifail)
      Case (0:5,7:)
        Write (nout,*)
        Write (nout,99998)
        Write (nout,*)

        Do i = 1, n
          Write (nout,99997) i, istate(i), x(i), clamda(i)
        End Do

        If (nclin>0) Then
          Write (nout,*)
          Write (nout,99996)
          Write (nout,*)

          Do i = n + 1, n + nclin
            j = i - n
            Write (nout,99995) j, istate(i), ax(j), clamda(i)
          End Do
        End If

        Write (nout,*)
        Write (nout,99994) obj
      End Select

100   Continue

99999 Format (1X,A,I5)
99998 Format (1X,'Varbl',3X,'Istate',4X,'Value',9X,'Lagr Mult')
99997 Format (1X,'V',2(1X,I3),4X,1P,E14.3,2X,1P,E12.3)
99996 Format (1X,'L Con',3X,'Istate',4X,'Value',9X,'Lagr Mult')
99995 Format (1X,'L',2(1X,I3),4X,1P,E14.3,2X,1P,E12.3)
99994 Format (1X,'Final objective value = ',1P,E15.3)
    End Program e04mgae


e04mgfe.f90

    Program e04mgfe

!     E04MGF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: e04mff, e04mgf, e04mhf, nag_wp, x04abf, x04acf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: iset = 1, nin = 5, ninopt = 7,       &
                                          nout = 6
      Character (*), Parameter         :: fname = 'e04mgfe.opt'
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: obj
      Integer                          :: i, ifail, inform, iter, j, lda,      &
                                          liwork, lwork, mode, n, nclin,       &
                                          outchn, sda
      Logical                          :: verbose_output
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: a(:,:), ax(:), bl(:), bu(:),         &
                                          clamda(:), cvec(:), work(:), x(:)
      Integer, Allocatable             :: istate(:), iwork(:)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: max
!     .. Executable Statements ..
      Write (nout,*) 'E04MGF Example Program Results'

!     Skip heading in data file
      Read (nin,*)

      Read (nin,*) n, nclin

      liwork = 2*n + 3

!     The minimum LWORK for an LP problem:

      If (0<nclin .And. nclin<n) Then
        lwork = 2*(nclin+1)**2 + 7*n + 5*nclin
      Else If (nclin>=n) Then
        lwork = 2*n**2 + 7*n + 5*nclin
      Else
        lwork = 7*n + 1
      End If

      lda = max(1,nclin)

      If (nclin>0) Then
        sda = n
      Else
        sda = 1
      End If

      Allocate (istate(n+nclin),iwork(liwork),a(lda,sda),bl(n+nclin),          &
        bu(n+nclin),cvec(n),x(n),ax(max(1,nclin)),clamda(n+nclin),work(lwork))

      Read (nin,*) cvec(1:n)
      Read (nin,*)(a(i,1:sda),i=1,nclin)
      Read (nin,*) bl(1:(n+nclin))
      Read (nin,*) bu(1:(n+nclin))
      Read (nin,*) x(1:n)

!     Set the unit number for advisory messages to OUTCHN

      outchn = nout
      Call x04abf(iset,outchn)

!     Set this to .True. to cause e04nqf to produce intermediate
!     progress output
      verbose_output = .False.

      If (.Not. verbose_output) Then
!       Turn off intermediate output from e04mff - it is on by default
        Call e04mhf('Print Level = 0')
      End If

!     Set some other options using E04MHF

      Call e04mhf('Check Frequency = 10')

      Call e04mhf('Infinite Bound Size = 1.0D+25')

!     Open the options file for reading

      mode = 0

      ifail = 0
      Call x04acf(ninopt,fname,mode,ifail)

!     Read the options file for the remaining options

      Call e04mgf(ninopt,inform)

      If (inform/=0) Then
        Write (nout,99999) 'E04MGF terminated with INFORM = ', inform
        Go To 100
      End If

!     Solve the problem

      ifail = 0
      Call e04mff(n,nclin,a,lda,bl,bu,cvec,istate,x,iter,obj,ax,clamda,iwork,  &
        liwork,work,lwork,ifail)

      Select Case (ifail)
      Case (0:5,7:)
        Write (nout,*)
        Write (nout,99998)
        Do i = 1, n
          Write (nout,99997) i, istate(i), x(i), clamda(i)
        End Do

        If (nclin>0) Then
          Write (nout,*)
          Write (nout,99996)
          Do i = n + 1, n + nclin
            j = i - n
            Write (nout,99995) j, istate(i), ax(j), clamda(i)
          End Do

        End If

        Write (nout,*)
        Write (nout,99994) obj
      End Select

100   Continue

99999 Format (1X,A,I5)
99998 Format (1X,'Varbl',3X,'Istate',4X,'Value',9X,'Lagr Mult')
99997 Format (1X,'V',2(1X,I3),4X,1P,E14.3,2X,1P,E12.3)
99996 Format (1X,'L Con',3X,'Istate',4X,'Value',9X,'Lagr Mult')
99995 Format (1X,'L',2(1X,I3),4X,1P,E14.3,2X,1P,E12.3)
99994 Format (1X,'Final objective value = ',1P,E15.3)
    End Program e04mgfe


e04mwfe.f90

!   E04MWF Example Program Text
!   Mark 26 Release. NAG Copyright 2016.

    Module e04mwfe_mod

!     E04MWF Example Program Module:
!            Parameters and User-defined Routines

!     .. Use Statements ..
      Use nag_library, Only: nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Accessibility Statements ..
      Private
      Public                           :: qphx
    Contains
      Subroutine qphx(ncolh,x,hx,nstate,cuser,iuser,ruser)

!       Subroutine to compute H*x.

!       Note: IUSER and RUSER contain the following data:
!       RUSER(1:NNZH) = H(1:NNZH)
!       IUSER(1:NCOLH+1) = ICCOLH(1:NCOLH+1)
!       IUSER(NCOLH+2:NNZH+NCOLH+1) = IROWH(1:NNZH)

!       .. Scalar Arguments ..
        Integer, Intent (In)           :: ncolh, nstate
!       .. Array Arguments ..
        Real (Kind=nag_wp), Intent (Out) :: hx(ncolh)
        Real (Kind=nag_wp), Intent (Inout) :: ruser(*)
        Real (Kind=nag_wp), Intent (In) :: x(ncolh)
        Integer, Intent (Inout)        :: iuser(*)
        Character (8), Intent (Inout)  :: cuser(*)
!       .. Local Scalars ..
        Integer                        :: icol, idx, iend, irow, istart
!       .. Executable Statements ..
        hx(1:ncolh) = 0.0E0_nag_wp

        Do icol = 1, ncolh
          istart = iuser(icol)
          iend = iuser(icol+1) - 1

          Do idx = istart, iend
            irow = iuser(ncolh+1+idx)
            hx(irow) = hx(irow) + x(icol)*ruser(idx)
            If (irow/=icol) Then
              hx(icol) = hx(icol) + x(irow)*ruser(idx)
            End If
          End Do
        End Do
        Return

      End Subroutine qphx
    End Module e04mwfe_mod

    Program e04mwfe

!     E04MWF Example Main Program

!     .. Use Statements ..
      Use nag_library, Only: e04mwf, e04npf, e04nqf, e04ntf, x04acf, x04adf
      Use e04mwfe_mod, Only: qphx
      Use nag_precisions, Only: wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: lencw = 600, leniw = 600,            &
                                          lenrw = 600, nin = 5, nout = 6,      &
                                          outfile = 42
      Character (*), Parameter         :: outfile_name = 'e04mwfe.mps'
!     .. Local Scalars ..
      Real (Kind=wp)                   :: obj, objadd, sinf
      Integer                          :: i, icol, ierr, ifail, iobj, jcol,    &
                                          lenc, lintvar, m, minmax, n, ncolh,  &
                                          ne, ninf, nname, nnzh, ns
      Logical                          :: verbose_output
      Character (1)                    :: istart
      Character (8)                    :: prob
!     .. Local Arrays ..
      Real (Kind=wp), Allocatable      :: acol(:), bl(:), bu(:), c(:), h(:),   &
                                          pi(:), rc(:), ruser(:), x(:)
      Real (Kind=wp)                   :: rw(lenrw)
      Integer, Allocatable             :: helast(:), hs(:), iccolh(:),         &
                                          idxc(:), inda(:), intvar(:),         &
                                          irowh(:), iuser(:), loca(:)
      Integer                          :: iw(leniw)
      Character (8)                    :: cuser(1), cw(lencw), pnames(5)
      Character (8), Allocatable       :: names(:)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: max
!     .. Executable Statements ..
      Write (nout,*) 'E04MWF Example Program Results'

!     Skip heading in data file.
      Read (nin,*)

      Read (nin,*) n, m
      Read (nin,*) ne, iobj, ncolh, nnzh, nname
      Allocate (inda(ne),loca(n+1),helast(n+m),hs(n+m),acol(ne),bl(n+m),       &
        bu(n+m),x(n+m),pi(m),rc(n+m),names(nname),h(nnzh),irowh(nnzh),         &
        iccolh(ncolh+1))

!     Read array of names
      Read (nin,*) names(1:nname)

!     Read the matrix ACOL from data file. Set up LOCA.
      jcol = 1
      loca(jcol) = 1

      Do i = 1, ne
!       Element ( INDA( I ), ICOL ) is stored in ACOL( I ).
        Read (nin,*) acol(i), inda(i), icol

        If (icol<jcol) Then
!         Elements not ordered by increasing column index.
          Write (nout,99998) 'Element in column', icol,                        &
            ' found after element in column', jcol, '. Problem', ' abandoned.'
          Go To 100
        Else If (icol==jcol+1) Then
!         Index in ACOL of the start of the ICOL-th column equals I.
          loca(icol) = i
          jcol = icol
        Else If (icol>jcol+1) Then
!         Columns JCOL+1,JCOL+2,...,ICOL-1 are empty. Set the
!         corresponding elements of LOCA to I.
          loca((jcol+1):icol) = i
          jcol = icol
        End If
      End Do

      loca(n+1) = ne + 1

!     Columns N,N-1,...,ICOL+1 are empty. Set the corresponding
!     elements of LOCA accordingly.
      Do i = n, icol + 1, -1
        loca(i) = loca(i+1)
      End Do

!     Read the matrix H from data file. Set up ICCOLH.
      jcol = 1
      iccolh(1) = 1

      Do i = 1, nnzh
!       Element ( IROWH( I ), ICOL ) is stored in H( I ).
        Read (nin,*) h(i), irowh(i), icol

        If (icol<jcol) Then
!         Elements not ordered by increasing column index
          Write (nout,99998) 'Element in column', icol,                        &
            ' found after element in column', jcol, '. Problem', ' abandoned.'
          Go To 100
        Else If (icol==jcol+1) Then
!         Index in ICCOLH of the start of the ICOL-th column equals I.
          iccolh(icol) = i
          jcol = icol
        Else If (icol>jcol+1) Then
!         Columns JCOL+1,JCOL+2,...,ICOL-1 are empty. Set the
!         corresponding elements of ICCOLH to I.
          iccolh((jcol+1):icol) = i
          jcol = icol
        End If
      End Do

      iccolh(ncolh+1) = nnzh + 1

!     Columns N,N-1,...,ICOL+1 are empty. Set the corresponding
!     elements of ICCOLH accordingly.
      Do i = n, icol + 1, -1
        iccolh(i) = iccolh(i+1)
      End Do

!     Read lower and upper bounds
      Read (nin,*) bl(1:(n+m))
      Read (nin,*) bu(1:(n+m))

!     Set cold start
      istart = 'C'
      hs(1:(n+m)) = 0.0_wp

!     Read the initial point x_0
      Read (nin,*) x(1:n)

!     Print dimensions of the QP problem
      Write (nout,99999) n, m

!     Call e04npf to initialize E04NQF.
      ifail = 0
      Call e04npf(cw,lencw,iw,leniw,rw,lenrw,ifail)

!     Set this to .True. to cause e04nqf to produce intermediate
!     progress output
      verbose_output = .False.

      If (verbose_output) Then
!       By default e04nqf does not print monitoring
!       information. Set the print file unit or the summary
!       file unit to get information.
        ifail = 0
        Call e04ntf('Print file',nout,cw,iw,rw,ifail)
      End If

!     We have no explicit objective vector so set LENC = 0; the
!     objective vector is stored in row IOBJ of ACOL.
      lenc = 0
      Allocate (c(max(1,lenc)),iuser(ncolh+1+nnzh),ruser(nnzh))

      objadd = 0.0E0_wp
      prob = ' '

!     Do not allow any elastic variables (i.e. they cannot be
!     infeasible). If we'd set optional argument "Elastic mode" to 0,
!     we wouldn't need to set the individual elements of array HELAST.
      helast(1:(n+m)) = 0

      If (ncolh>0) Then
!       Store the non zeros of H in ruser for use by qphx
        ruser(1:nnzh) = h(1:nnzh)

!       Store iccolh and irowh in iuser for use by qphx
        iuser(1:ncolh+1) = iccolh(1:ncolh+1)
        iuser(ncolh+2:nnzh+ncolh+1) = irowh(1:nnzh)
      End If

!     Call e04nqf to solve the problem.
      ifail = 0
      Call e04nqf(istart,qphx,m,n,ne,nname,lenc,ncolh,iobj,objadd,prob,acol,   &
        inda,loca,bl,bu,c,names,helast,hs,x,pi,rc,ns,ninf,sinf,obj,cw,lencw,   &
        iw,leniw,rw,lenrw,cuser,iuser,ruser,ifail)

!     Print objective function and optimal x*
      Write (nout,*)
      Write (nout,99997) obj
      Write (nout,99996) x(1:n)

!     Set the rest of inputs for e04mwf. Due to IOBJ > 0, LENC = 0 and
!     C and IDXC will not be referenced.
      lintvar = 0
      Allocate (idxc(lenc),intvar(lintvar))
      c(:) = 0
      idxc(:) = 0
      intvar(:) = 0
      pnames(:) = '        '
      pnames(1) = 'USRPNAME'
      pnames(2) = 'OBJ.....'
      minmax = -1

!     Open data file for writing
      ifail = 0
      Call x04acf(outfile,outfile_name,1,ifail)

!     Call e04mwf to store the problem in a MPS file with fixed format.
      ifail = 0
      Call e04mwf(outfile,n,m,lenc,ne,ncolh,nnzh,lintvar,idxc,c,iobj,acol,     &
        inda,loca,bl,bu,pnames,nname,names,h,irowh,iccolh,minmax,intvar,ifail)

      Write (nout,99995) outfile_name

!     Close data file
      ierr = 0
      Call x04adf(outfile,ierr)

100   Continue

99999 Format (1X,/,1X,'QP problem contains ',I3,' variables and ',I3,          &
        ' linear constraints')
99998 Format (1X,A,I5,A,I5,A,A)
99997 Format (1X,'Final objective value = ',1P,E11.3)
99996 Format (1X,'Optimal X = ',7F9.2)
99995 Format (1X,/,1X,'MPS file was written: ',A)

    End Program e04mwfe


e04mxfe.f90

!   E04MXF Example Program Text
!   Mark 26 Release. NAG Copyright 2016.

    Module e04mxfe_mod

!     E04MXF Example Program Module:
!            Parameters and User-defined Routines

!     .. Use Statements ..
      Use nag_library, Only: nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Accessibility Statements ..
      Private
      Public                           :: qphx
    Contains
      Subroutine qphx(ncolh,x,hx,nstate,cuser,iuser,ruser)

!       Subroutine to compute H*x.

!       Note: IUSER and RUSER contain the following data:
!       RUSER(1:NNZH) = H(1:NNZH)
!       IUSER(1:NCOLH+1) = ICCOLH(1:NCOLH+1)
!       IUSER(NCOLH+2:NNZH+NCOLH+1) = IROWH(1:NNZH)

!       .. Scalar Arguments ..
        Integer, Intent (In)           :: ncolh, nstate
!       .. Array Arguments ..
        Real (Kind=nag_wp), Intent (Out) :: hx(ncolh)
        Real (Kind=nag_wp), Intent (Inout) :: ruser(*)
        Real (Kind=nag_wp), Intent (In) :: x(ncolh)
        Integer, Intent (Inout)        :: iuser(*)
        Character (8), Intent (Inout)  :: cuser(*)
!       .. Local Scalars ..
        Integer                        :: end, icol, idx, irow, start
!       .. Executable Statements ..
        hx(1:ncolh) = 0.0E0_nag_wp

        Do icol = 1, ncolh
          start = iuser(icol)
          end = iuser(icol+1) - 1

          Do idx = start, end
            irow = iuser(ncolh+1+idx)
            hx(irow) = hx(irow) + x(icol)*ruser(idx)
            If (irow/=icol) Then
              hx(icol) = hx(icol) + x(irow)*ruser(idx)
            End If

          End Do

        End Do

        Return
      End Subroutine qphx
    End Module e04mxfe_mod

    Program e04mxfe

!     .. Use Statements ..
      Use nag_library, Only: e04mxf, e04npf, e04nqf, e04nsf, e04ntf, nag_wp,   &
                             x04acf, x04adf
      Use e04mxfe_mod, Only: qphx
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: lencw = 600, leniw = 600,            &
                                          lenrw = 600, mpslst = 1, nin = 7,    &
                                          nout = 6
      Logical, Parameter               :: readints = .False.
      Character (*), Parameter         :: fname = 'e04mxfe.opt'
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: obj, objadd, sinf
      Integer                          :: i, ifail, iobj, lenc, lintvar, m,    &
                                          maxlintvar, maxm, maxn, maxncolh,    &
                                          maxnnz, maxnnzh, minmax, mode, n,    &
                                          ncolh, ninf, nname, nnz, nnzh, ns
      Character (1)                    :: start
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: a(:), bl(:), bu(:), c(:), h(:),      &
                                          pi(:), rc(:), ruser(:), rw(:), x(:)
      Integer, Allocatable             :: helast(:), hs(:), iccola(:),         &
                                          iccolh(:), intvar(:), irowa(:),      &
                                          irowh(:), iuser(:), iw(:)
      Character (8), Allocatable       :: crname(:), cw(:)
      Character (8)                    :: cuser(1), pnames(5)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: max, min
!     .. Executable Statements ..
      Write (nout,*) 'E04MXF Example Program Results'
      Flush (nout)

!     Initialize
      pnames(1:5) = '        '
      maxm = 0
      maxn = 0
      maxnnz = 0
      maxnnzh = 0
      maxncolh = 0
      maxlintvar = 0

!     Open the data file for reading
      mode = 0
      ifail = 0
      Call x04acf(nin,fname,mode,ifail)

!     Call e04mxf in query mode
      Allocate (a(maxnnz),irowa(maxnnz),iccola(maxn+1),bl(maxn+maxm),          &
        bu(maxn+maxm),crname(maxn+maxm),h(maxnnzh),irowh(maxnnzh),             &
        iccolh(maxncolh+1),intvar(maxlintvar))
      ifail = 0
      Call e04mxf(nin,maxn,maxm,maxnnz,maxncolh,maxnnzh,maxlintvar,mpslst,n,m, &
        nnz,ncolh,nnzh,lintvar,iobj,a,irowa,iccola,bl,bu,pnames,nname,crname,  &
        h,irowh,iccolh,minmax,intvar,ifail)
      Deallocate (a,irowa,iccola,bl,bu,crname,h,irowh,iccolh,intvar)

!     Close the data file
      ifail = 0
      Call x04adf(nin,ifail)

!     set maxm maxn and maxnnz
      maxm = m
      maxn = n
      maxnnz = nnz
      maxnnzh = nnzh
      maxncolh = ncolh
      If (readints) Then
        maxlintvar = lintvar
      Else
        maxlintvar = -1
      End If

!     Allocate memory
      Allocate (irowa(maxnnz),iccola(maxn+1),a(maxnnz),bl(maxn+maxm),          &
        bu(maxn+maxm),crname(maxn+maxm),irowh(maxnnzh),iccolh(maxncolh+1),     &
        h(maxnnzh),intvar(maxlintvar))

!     Open the data file for reading
      mode = 0
      ifail = 0
      Call x04acf(nin,fname,mode,ifail)

!     Call e04mxf to read the problem
      ifail = 0
      Call e04mxf(nin,maxn,maxm,maxnnz,maxncolh,maxnnzh,maxlintvar,mpslst,n,m, &
        nnz,ncolh,nnzh,lintvar,iobj,a,irowa,iccola,bl,bu,pnames,nname,crname,  &
        h,irowh,iccolh,minmax,intvar,ifail)

!     Close the data file
      ifail = 0
      Call x04adf(nin,ifail)

!     Data has been read. Set up and run the solver

      Allocate (iw(leniw),rw(lenrw),cw(lencw))

!     Call e04npf to initialize workspace
      ifail = 0
      Call e04npf(cw,lencw,iw,leniw,rw,lenrw,ifail)

!     Call option setter e04nsf to change the direction of optimization.
!     Minimization is assumed by default.
      If (minmax==1) Then
        ifail = 0
        Call e04nsf('Maximize',cw,iw,rw,ifail)
      Else If (minmax==0) Then
        ifail = 0
        Call e04nsf('Feasible Point',cw,iw,rw,ifail)
      End If

!     By default E04NQF does not print monitoring
!     information. Set the print file unit or the summary
!     file unit to get information.
      ifail = 0
      Call e04ntf('Print file',nout,cw,iw,rw,ifail)

!     We have no explicit objective vector so set LENC = 0; the
!     objective vector is stored in row IOBJ of ACOL.
      lenc = 0
      objadd = 0.0E0_nag_wp
      start = 'C'

      Allocate (c(max(1,lenc)),helast(n+m),x(n+m),pi(m),rc(n+m),hs(n+m),iuser( &
        ncolh+1+nnzh),ruser(nnzh))

      helast(1:n+m) = 0
      hs(1:n+m) = 0
      Do i = 1, n + m
        x(i) = min(max(0.0E0_nag_wp,bl(i)),bu(i))
      End Do

      If (ncolh>0) Then
!       Store the non zeros of H in ruser for use by qphx
        ruser(1:nnzh) = h(1:nnzh)

!       Store iccolh and irowh in iuser for use by qphx
        iuser(1:ncolh+1) = iccolh(1:ncolh+1)
        iuser(ncolh+2:nnzh+ncolh+1) = irowh(1:nnzh)
      End If

!     Call e04nqf to solve the problem
      ifail = 0
      Call e04nqf(start,qphx,m,n,nnz,nname,lenc,ncolh,iobj,objadd,pnames(1),a, &
        irowa,iccola,bl,bu,c,crname,helast,hs,x,pi,rc,ns,ninf,sinf,obj,cw,     &
        lencw,iw,leniw,rw,lenrw,cuser,iuser,ruser,ifail)

    End Program e04mxfe


e04mzfe.f90

!   E04MZF Example Program Text
!   Mark 26 Release. NAG Copyright 2016.
    Module e04mzfe_mod

!     E04MZF Example Program Module:
!            Parameters and User-defined Routines

!     .. Use Statements ..
      Use nag_library, Only: nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Accessibility Statements ..
      Private
      Public                           :: qphx
!     .. Parameters ..
      Real (Kind=nag_wp), Parameter, Public :: xbldef = 0.0_nag_wp
      Real (Kind=nag_wp), Parameter, Public :: xbudef = 1.0E+20_nag_wp
      Integer, Parameter, Public       :: iset = 1, lencw = 600, leniw = 600,  &
                                          lenrw = 600, maxm = 10000,           &
                                          maxn = 10000, maxnnz = 100000,       &
                                          nindat = 7, nout = 6
    Contains
      Subroutine qphx(ncolh,x,hx,nstate,cuser,iuser,ruser)

!       Routine to compute H*x. (In this version of QPHX, the Hessian
!       matrix H is not referenced explicitly.)

!       .. Scalar Arguments ..
        Integer, Intent (In)           :: ncolh, nstate
!       .. Array Arguments ..
        Real (Kind=nag_wp), Intent (Out) :: hx(ncolh)
        Real (Kind=nag_wp), Intent (Inout) :: ruser(*)
        Real (Kind=nag_wp), Intent (In) :: x(ncolh)
        Integer, Intent (Inout)        :: iuser(*)
        Character (8), Intent (Inout)  :: cuser(*)
!       .. Executable Statements ..
        If (nstate==1) Then

!         First entry. You may perform any required one-time
!         operations here.

        End If

        hx(1) = 2.0_nag_wp*x(1) + x(2) + x(3) + x(4) + x(5)
        hx(2) = x(1) + 2.0_nag_wp*x(2) + x(3) + x(4) + x(5)
        hx(3) = x(1) + x(2) + 2.0_nag_wp*x(3) + x(4) + x(5)
        hx(4) = x(1) + x(2) + x(3) + 2.0_nag_wp*x(4) + x(5)
        hx(5) = x(1) + x(2) + x(3) + x(4) + 2.0_nag_wp*x(5)

        If (nstate>=2) Then

!         Final entry. You may perform any required clean up
!         operations here.

        End If

        Return

      End Subroutine qphx
    End Module e04mzfe_mod
    Program e04mzfe

!     E04MZF Example Main Program

!     .. Use Statements ..
      Use nag_library, Only: e04mzf, e04npf, e04nqf, e04ntf, nag_wp, x04abf,   &
                             x04acf
      Use e04mzfe_mod, Only: iset, lencw, leniw, lenrw, maxm, maxn, maxnnz,    &
                             nindat, nout, qphx, xbldef, xbudef
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Character (*), Parameter         :: fname = 'e04mzfe.opt'
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: obj, objadd, sinf
      Integer                          :: i, ifail, infile, iobj, lenc, m,     &
                                          mode, n, ncolh, ninf, nname, nnz,    &
                                          ns, outchn
      Logical                          :: mpslst, verbose_output
      Character (8)                    :: prob
      Character (1)                    :: start
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: a(:), bl(:), bu(:), c(:), pi(:),     &
                                          rc(:), xs(:)
      Real (Kind=nag_wp)               :: ruser(1), rw(lenrw)
      Integer, Allocatable             :: ha(:), helast(:), istate(:), ka(:)
      Integer                          :: iuser(1), iw(leniw)
      Character (8), Allocatable       :: crname(:)
      Character (8)                    :: cuser(1), cw(lencw), names(5)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: max
!     .. Executable Statements ..
      Write (nout,*) 'E04MZF Example Program Results'

      Allocate (ha(maxnnz),ka(maxn+1),istate(maxn+maxm),a(maxnnz),             &
        bl(maxn+maxm),bu(maxn+maxm),xs(maxn+maxm),crname(maxn+maxm))

!     Open the data file for reading

      mode = 0

      ifail = 0
      Call x04acf(nindat,fname,mode,ifail)

!     Initialize parameters.

      infile = nindat
      mpslst = .False.
      names(1:5) = '        '

!     Convert the MPSX data file for use by E04NQF.

      Write (nout,99999)

      ifail = 0
      Call e04mzf(infile,maxn,maxm,maxnnz,xbldef,xbudef,mpslst,n,m,nnz,iobj,   &
        ncolh,a,ha,ka,bl,bu,start,names,nname,crname,xs,istate,ifail)

      Write (nout,99998) n, m

!     Set the unit number for advisory messages to OUTCHN.

      outchn = nout
      Call x04abf(iset,outchn)

!     Set the value of NCOLH (the number of columns of the Hessian matrix)

      ncolh = 5

!     Call E04NPF to initialize E04NQF.

      ifail = 0
      Call e04npf(cw,lencw,iw,leniw,rw,lenrw,ifail)

!     Set this to .True. to cause e04nqf to produce intermediate
!     progress output
      verbose_output = .False.
      If (verbose_output) Then
        Call e04ntf('Print file',nout,cw,iw,rw,ifail)
      End If

!     We have no explicit objective vector so set LENC = 0; the
!     objective vector is stored in row IOBJ of A.

      lenc = 0
      Allocate (c(max(1,lenc)),helast(n+m),pi(m),rc(n+m))

      objadd = 0.0_nag_wp
      prob = ' '

!     Do not allow any elastic variables (i.e. they cannot be
!     infeasible).

      helast(1:(n+m)) = 0

      Write (nout,99997)
      ifail = 0
      Call e04nqf(start,qphx,m,n,nnz,nname,lenc,ncolh,iobj,objadd,prob,a,ha,   &
        ka,bl,bu,c,crname,helast,istate,xs,pi,rc,ns,ninf,sinf,obj,cw,lencw,iw, &
        leniw,rw,lenrw,cuser,iuser,ruser,ifail)

      Write (nout,99996) obj
      Write (nout,99995)
      Write (nout,99994)(i,xs(i),i=1,n)

99999 Format (1X,/,1X,'Reading MPSX file:')
99998 Format (1X,'MPSX file contains ',I3,' variables and ',I3,                &
        ' linear constraints')
99997 Format (1X,/,1X,'Solving QP problem:')
99996 Format (1X,'Optimal objective value: ',1P,E11.3)
99995 Format (1X,'Optimal X:')
99994 Format (1X,'  X(',I2,') =',F10.4)
    End Program e04mzfe


e04ncae.f90

    Program e04ncae

!     E04NCA Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: dgemv, e04nca, e04wbf, nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Real (Kind=nag_wp), Parameter    :: one = 1.0_nag_wp
      Real (Kind=nag_wp), Parameter    :: zero = 0.0_nag_wp
      Integer, Parameter               :: inc1 = 1, lcwsav = 1, liwsav = 610,  &
                                          llwsav = 120, lrwsav = 475, nin = 5, &
                                          nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: obj
      Integer                          :: i, ifail, iter, lda, ldc, liwork,    &
                                          lwork, m, n, nclin, sdc
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: a(:,:), b(:), bl(:), bu(:), c(:,:),  &
                                          clamda(:), cvec(:), work(:), x(:)
      Real (Kind=nag_wp)               :: rwsav(lrwsav)
      Integer, Allocatable             :: istate(:), iwork(:), kx(:)
      Integer                          :: iwsav(liwsav)
      Logical                          :: lwsav(llwsav)
      Character (80)                   :: cwsav(lcwsav)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: max
!     .. Executable Statements ..
      Write (nout,*) 'E04NCA Example Program Results'

!     Skip heading in data file
      Read (nin,*)

      Read (nin,*) m, n, nclin
      liwork = n
      ldc = max(1,nclin)
      lda = max(1,m)

      If (nclin>0) Then
        sdc = n
      Else
        sdc = 1
      End If

!     This particular example problem is of type LS1, so we allocate
!     A(LDA,N), CVEC(1), B(M) and define LWORK as below

      If (nclin>0) Then
        lwork = 2*n**2 + 9*n + 6*nclin
      Else
        lwork = 9*n
      End If

      Allocate (istate(n+nclin),kx(n),iwork(liwork),c(ldc,sdc),bl(n+nclin),    &
        bu(n+nclin),cvec(1),x(n),a(lda,n),b(m),clamda(n+nclin),work(lwork))

      Read (nin,*)(a(i,1:n),i=1,m)
      Read (nin,*) b(1:m)
      Read (nin,*)(c(i,1:sdc),i=1,nclin)
      Read (nin,*) bl(1:(n+nclin))
      Read (nin,*) bu(1:(n+nclin))
      Read (nin,*) x(1:n)

!     Initialise E04NCA

      ifail = 0
      Call e04wbf('E04NCA',cwsav,lcwsav,lwsav,llwsav,iwsav,liwsav,rwsav,       &
        lrwsav,ifail)

!     Solve the problem

      ifail = -1
      Call e04nca(m,n,nclin,ldc,lda,c,bl,bu,cvec,istate,kx,x,a,b,iter,obj,     &
        clamda,iwork,liwork,work,lwork,lwsav,iwsav,rwsav,ifail)

      Select Case (ifail)
      Case (0:5,7:)
!       Print variable headers
        Write (nout,99999)

        Do i = 1, n
          Write (nout,99998) i, istate(i), x(i), clamda(i)
        End Do

        If (nclin>0) Then

!         C*x --> work
!         The NAG name equivalent of dgemv is f06paf
          Call dgemv('N',nclin,n,one,c,ldc,x,inc1,zero,work,inc1)

!         Print constraint headers
          Write (nout,99997)

          Do i = 1, nclin
            Write (nout,99996) i, istate(i+n), work(i), clamda(i+n)
          End Do

        End If

        Write (nout,99995) obj
      End Select

99999 Format (/,1X,'Varbl',3X,'Istate',4X,'Value',9X,'Lagr Mult')
99998 Format (1X,'V',2(1X,I3),4X,1P,E14.3,2X,1P,E12.3)
99997 Format (/,1X,'L Con',3X,'Istate',4X,'Value',9X,'Lagr Mult')
99996 Format (1X,'L',2(1X,I3),4X,1P,E14.3,2X,1P,E12.3)
99995 Format (/,1X,'Final objective value = ',1P,E15.3)
    End Program e04ncae


e04ncfe.f90

    Program e04ncfe

!     E04NCF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: dgemv, e04ncf, e04nef, nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Real (Kind=nag_wp), Parameter    :: one = 1.0_nag_wp
      Real (Kind=nag_wp), Parameter    :: zero = 0.0_nag_wp
      Integer, Parameter               :: inc1 = 1, nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: obj
      Integer                          :: i, ifail, iter, lda, ldc, liwork,    &
                                          lwork, m, n, nclin, sdc
      Logical                          :: verbose_output
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: a(:,:), b(:), bl(:), bu(:), c(:,:),  &
                                          clamda(:), cvec(:), work(:), x(:)
      Integer, Allocatable             :: istate(:), iwork(:), kx(:)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: max
!     .. Executable Statements ..
      Write (nout,*) 'E04NCF Example Program Results'

!     Skip heading in data file
      Read (nin,*)

      Read (nin,*) m, n, nclin
      liwork = n
      ldc = max(1,nclin)
      lda = max(1,m)

      If (nclin>0) Then
        sdc = n
      Else
        sdc = 1
      End If

!     This particular example problem is of type LS1, so we allocate
!     A(LDA,N), CVEC(1), B(M) and define LWORK as below

      If (nclin>0) Then
        lwork = 2*n**2 + 9*n + 6*nclin
      Else
        lwork = 9*n
      End If

      Allocate (istate(n+nclin),kx(n),iwork(liwork),c(ldc,sdc),bl(n+nclin),    &
        bu(n+nclin),cvec(1),x(n),a(lda,n),b(m),clamda(n+nclin),work(lwork))

      Read (nin,*)(a(i,1:n),i=1,m)
      Read (nin,*) b(1:m)
      Read (nin,*)(c(i,1:sdc),i=1,nclin)
      Read (nin,*) bl(1:(n+nclin))
      Read (nin,*) bu(1:(n+nclin))
      Read (nin,*) x(1:n)

!     Set this to .True. to cause e04nqf to produce intermediate
!     progress output
      verbose_output = .False.
      If (.Not. verbose_output) Then
!       Switch off intermediate output from e04ncf
        Call e04nef('Nolist')
        Call e04nef('Print level = 0')
      End If

!     Solve the problem

      ifail = -1
      Call e04ncf(m,n,nclin,ldc,lda,c,bl,bu,cvec,istate,kx,x,a,b,iter,obj,     &
        clamda,iwork,liwork,work,lwork,ifail)

      Select Case (ifail)
      Case (0:5,7:)
!       Print variable headers
        Write (nout,99999)

        Do i = 1, n
          Write (nout,99998) i, istate(i), x(i), clamda(i)
        End Do

        If (nclin>0) Then

!         C*x --> work
!         The NAG name equivalent of dgemv is f06paf
          Call dgemv('N',nclin,n,one,c,ldc,x,inc1,zero,work,inc1)

!         Print constraint headers
          Write (nout,99997)

          Do i = 1, nclin
            Write (nout,99996) i, istate(i+n), work(i), clamda(i+n)
          End Do

        End If

        Write (nout,99995) obj
      End Select

99999 Format (/,1X,'Varbl',3X,'Istate',4X,'Value',9X,'Lagr Mult')
99998 Format (1X,'V',2(1X,I3),4X,1P,E14.3,2X,1P,E12.3)
99997 Format (/,1X,'L Con',3X,'Istate',4X,'Value',9X,'Lagr Mult')
99996 Format (1X,'L',2(1X,I3),4X,1P,E14.3,2X,1P,E12.3)
99995 Format (/,1X,'Final objective value = ',1P,E15.3)
    End Program e04ncfe


e04ndae.f90

    Program e04ndae

!     E04NDA Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: dgemv, e04nca, e04nda, e04nea, e04wbf, nag_wp,    &
                             x04abf, x04acf, x04baf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Real (Kind=nag_wp), Parameter    :: one = 1.0_nag_wp
      Real (Kind=nag_wp), Parameter    :: zero = 0.0_nag_wp
      Integer, Parameter               :: inc1 = 1, iset = 1, lcwsav = 1,      &
                                          liwsav = 610, llwsav = 120,          &
                                          lrwsav = 475, nin = 5, ninopt = 7,   &
                                          nout = 6
      Character (*), Parameter         :: fname = 'e04ndae.opt'
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: obj
      Integer                          :: i, ifail, inform, iter, j, lda, ldc, &
                                          liwork, lwork, m, mode, n, nclin,    &
                                          outchn, sdc
      Character (80)                   :: rec
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: a(:,:), b(:), bl(:), bu(:), c(:,:),  &
                                          clamda(:), cvec(:), work(:), x(:)
      Real (Kind=nag_wp)               :: rwsav(lrwsav)
      Integer, Allocatable             :: istate(:), iwork(:), kx(:)
      Integer                          :: iwsav(liwsav)
      Logical                          :: lwsav(llwsav)
      Character (80)                   :: cwsav(lcwsav)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: max
!     .. Executable Statements ..
      Write (rec,99993) 'E04NDA Example Program Results'
      Call x04baf(nout,rec)

!     Skip heading in data file
      Read (nin,*)

      Read (nin,*) m, n, nclin
      liwork = n
      ldc = max(1,nclin)
      lda = max(1,m)

      If (nclin>0) Then
        sdc = n
      Else
        sdc = 1
      End If

!     This particular example problem is of type QP2, so we allocate
!     A(LDA,N), CVEC(N), B(1) and define LWORK as below

      If (nclin>0) Then
        lwork = 2*n**2 + 10*n + 6*nclin
      Else
        lwork = 10*n
      End If

      Allocate (istate(n+nclin),kx(n),iwork(liwork),c(ldc,sdc),bl(n+nclin),    &
        bu(n+nclin),cvec(n),x(n),a(lda,n),b(1),clamda(n+nclin),work(lwork))

      Read (nin,*) cvec(1:n)
      Read (nin,*)(a(i,1:n),i=1,m)
      Read (nin,*)(c(i,1:sdc),i=1,nclin)
      Read (nin,*) bl(1:(n+nclin))
      Read (nin,*)
      Read (nin,*) bu(1:(n+nclin))
      Read (nin,*)
      Read (nin,*) x(1:n)

!     Set the unit number for advisory messages to OUTCHN

      outchn = nout
      Call x04abf(iset,outchn)

!     Initialise E04NCA

      ifail = 0
      Call e04wbf('E04NCA',cwsav,lcwsav,lwsav,llwsav,iwsav,liwsav,rwsav,       &
        lrwsav,ifail)

!     Set one option using E04NEA

      Call e04nea(' Problem Type = QP2 ',lwsav,iwsav,rwsav,inform)

      If (inform/=0) Then
        Write (rec,99999) ' ** E04NEA terminated with INFORM = ', inform
        Call x04baf(nout,rec)
        Go To 100
      End If

!     Open the options file for reading

      mode = 0

      ifail = 0
      Call x04acf(ninopt,fname,mode,ifail)

!     Read the options file for the remaining options

      Call e04nda(ninopt,lwsav,iwsav,rwsav,inform)

      If (inform/=0) Then
        Write (rec,99999) ' ** E04NDA terminated with INFORM =', inform
        Call x04baf(nout,rec)
        Go To 100
      End If

!     Solve the problem

      ifail = -1
      Call e04nca(m,n,nclin,ldc,lda,c,bl,bu,cvec,istate,kx,x,a,b,iter,obj,     &
        clamda,iwork,liwork,work,lwork,lwsav,iwsav,rwsav,ifail)

      Select Case (ifail)
      Case (0:5,7:)
        Write (rec,'()')
        Call x04baf(nout,rec)
        Write (rec,99998)
        Call x04baf(nout,rec)
        Write (rec,'()')
        Call x04baf(nout,rec)

        Do i = 1, n
          Write (rec,99997) i, istate(i), x(i), clamda(i)
          Call x04baf(nout,rec)
        End Do

        If (nclin>0) Then

!         C*x --> work.
!         The NAG name equivalent of dgemv is f06paf
          Call dgemv('N',nclin,n,one,c,ldc,x,inc1,zero,work,inc1)

          Write (rec,'()')
          Call x04baf(nout,rec)
          Write (rec,'()')
          Call x04baf(nout,rec)
          Write (rec,99996)
          Call x04baf(nout,rec)
          Write (rec,'()')
          Call x04baf(nout,rec)

          Do i = n + 1, n + nclin
            j = i - n
            Write (rec,99995) j, istate(i), work(j), clamda(i)
            Call x04baf(nout,rec)
          End Do

        End If

        Write (rec,'()')
        Call x04baf(nout,rec)
        Write (rec,'()')
        Call x04baf(nout,rec)
        Write (rec,99994) obj
        Call x04baf(nout,rec)
      End Select

100   Continue

99999 Format (1X,A,I5)
99998 Format (1X,'Varbl',2X,'Istate',3X,'Value',9X,'Lagr Mult')
99997 Format (1X,'V',2(1X,I3),4X,1P,G14.6,2X,1P,G12.4)
99996 Format (1X,'L Con',2X,'Istate',3X,'Value',9X,'Lagr Mult')
99995 Format (1X,'L',2(1X,I3),4X,1P,G14.6,2X,1P,G12.4)
99994 Format (1X,'Final objective value = ',G15.7)
99993 Format (1X,A)
    End Program e04ndae


e04ndfe.f90

    Program e04ndfe

!     E04NDF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: e04ncf, e04ndf, e04nef, nag_wp, x04abf, x04acf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: iset = 1, nin = 5, ninopt = 7,       &
                                          nout = 6
      Character (*), Parameter         :: fname = 'e04ndfe.opt'
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: obj
      Integer                          :: i, ifail, inform, iter, lda, ldc,    &
                                          liwork, lwork, m, mode, n, nclin,    &
                                          outchn, sdc
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: a(:,:), b(:), bl(:), bu(:), c(:,:),  &
                                          clamda(:), cvec(:), work(:), x(:)
      Integer, Allocatable             :: istate(:), iwork(:), kx(:)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: max
!     .. Executable Statements ..
      Write (nout,99998) 'E04NDF Example Program Results'
      Flush (nout)

!     Skip heading in data file
      Read (nin,*)

      Read (nin,*) m, n, nclin
      liwork = n
      ldc = max(1,nclin)
      lda = max(1,m)

      If (nclin>0) Then
        sdc = n
      Else
        sdc = 1
      End If

!     This particular example problem is of type QP2, so we allocate
!     A(LDA,N), CVEC(N), B(1) and define LWORK as below

      If (nclin>0) Then
        lwork = 2*n**2 + 10*n + 6*nclin
      Else
        lwork = 10*n
      End If

      Allocate (istate(n+nclin),kx(n),iwork(liwork),c(ldc,sdc),bl(n+nclin),    &
        bu(n+nclin),cvec(n),x(n),a(lda,n),b(1),clamda(n+nclin),work(lwork))

      Read (nin,*) cvec(1:n)
      Read (nin,*)(a(i,1:n),i=1,m)
      Read (nin,*)(c(i,1:sdc),i=1,nclin)
      Read (nin,*) bl(1:(n+nclin))
      Read (nin,*)
      Read (nin,*) bu(1:(n+nclin))
      Read (nin,*)
      Read (nin,*) x(1:n)

!     Set the unit number for advisory messages to OUTCHN

      outchn = nout
      Call x04abf(iset,outchn)

!     Set one option using E04NEF

      Call e04nef(' Problem Type = QP2 ')

!     Open the options file for reading

      mode = 0

      ifail = 0
      Call x04acf(ninopt,fname,mode,ifail)

!     Read the options file for the remaining options

      Call e04ndf(ninopt,inform)

      If (inform/=0) Then
        Write (nout,99999) ' ** E04NDF terminated with INFORM =', inform
        Flush (nout)
        Go To 100
      End If

!     Solve the problem

      ifail = 0
      Call e04ncf(m,n,nclin,ldc,lda,c,bl,bu,cvec,istate,kx,x,a,b,iter,obj,     &
        clamda,iwork,liwork,work,lwork,ifail)

100   Continue

99999 Format (1X,A,I5)
99998 Format (1X,A)
    End Program e04ndfe


e04nfae.f90

    Program e04nfae

!     E04NFA Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: e04nfa, e04wbf, e54nfu, nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: lcwsav = 1, liwsav = 610,            &
                                          llwsav = 120, lrwsav = 475, nin = 5, &
                                          nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: obj
      Integer                          :: i, ifail, iter, j, lda, ldh, liwork, &
                                          lwork, n, nclin, sda
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: a(:,:), ax(:), bl(:), bu(:),         &
                                          clamda(:), cvec(:), h(:,:), work(:), &
                                          x(:)
      Real (Kind=nag_wp)               :: ruser(1), rwsav(lrwsav)
      Integer, Allocatable             :: istate(:), iwork(:)
      Integer                          :: iwsav(liwsav)
      Logical                          :: lwsav(llwsav)
      Character (80)                   :: cwsav(lcwsav)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: max
!     .. Executable Statements ..
      Write (nout,*) 'E04NFA Example Program Results'

!     Skip heading in data file
      Read (nin,*)

      Read (nin,*) n, nclin
      liwork = 2*n + 3
      lda = max(1,nclin)

      If (nclin>0) Then
        sda = n
      Else
        sda = 1
      End If

!     This particular example problem is of type QP2 with H stored explicitly,
!     so we allocate CVEC(N) and H(LDH,N), and define LDH and LWORK as below

      ldh = n

      If (nclin>0) Then
        lwork = 2*n**2 + 8*n + 5*nclin
      Else
        lwork = n**2 + 8*n
      End If

      Allocate (istate(n+nclin),ax(max(1,nclin)),iwork(liwork),h(ldh,n),bl(n+  &
        nclin),bu(n+nclin),cvec(n),x(n),a(lda,sda),clamda(n+nclin),            &
        work(lwork))

      Read (nin,*) cvec(1:n)
      Read (nin,*)(a(i,1:sda),i=1,nclin)
      Read (nin,*) bl(1:(n+nclin))
      Read (nin,*) bu(1:(n+nclin))
      Read (nin,*) x(1:n)
      Read (nin,*)(h(i,1:n),i=1,n)

!     Initialise E04NFA

      ifail = 0
      Call e04wbf('E04NFA',cwsav,lcwsav,lwsav,llwsav,iwsav,liwsav,rwsav,       &
        lrwsav,ifail)

!     Solve the problem

      ifail = -1
      Call e04nfa(n,nclin,a,lda,bl,bu,cvec,h,ldh,e54nfu,istate,x,iter,obj,ax,  &
        clamda,iwork,liwork,work,lwork,iwsav,ruser,lwsav,iwsav,rwsav,ifail)

      Select Case (ifail)
      Case (0:5,7:)
        Write (nout,*)
        Write (nout,99999)
        Write (nout,*)

        Do i = 1, n
          Write (nout,99998) i, istate(i), x(i), clamda(i)
        End Do

        If (nclin>0) Then
          Write (nout,*)
          Write (nout,*)
          Write (nout,99997)
          Write (nout,*)

          Do i = n + 1, n + nclin
            j = i - n
            Write (nout,99996) j, istate(i), ax(j), clamda(i)
          End Do

        End If

        Write (nout,*)
        Write (nout,*)
        Write (nout,99995) obj
        Write (nout,*)
        Write (nout,*)
        Write (nout,99994) iter
      End Select

99999 Format (1X,'Varbl',2X,'Istate',3X,'Value',9X,'Lagr Mult')
99998 Format (1X,'V',2(1X,I3),4X,1P,G14.6,2X,1P,G12.4)
99997 Format (1X,'L Con',2X,'Istate',3X,'Value',9X,'Lagr Mult')
99996 Format (1X,'L',2(1X,I3),4X,1P,G14.6,2X,1P,G12.4)
99995 Format (1X,'Final objective value = ',G15.7)
99994 Format (1X,'Exit from problem after',1X,I6,1X,'iterations.')
    End Program e04nfae


e04nffe.f90

    Program e04nffe

!     E04NFF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: e04nff, e04nfu, nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: obj
      Integer                          :: i, ifail, iter, lda, ldh, liwork,    &
                                          lwork, n, nclin, sda
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: a(:,:), ax(:), bl(:), bu(:),         &
                                          clamda(:), cvec(:), h(:,:), work(:), &
                                          x(:)
      Integer, Allocatable             :: istate(:), iwork(:)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: max
!     .. Executable Statements ..
      Write (nout,*) 'E04NFF Example Program Results'
      Flush (nout)

!     Skip heading in data file
      Read (nin,*)

      Read (nin,*) n, nclin
      liwork = 2*n + 3
      lda = max(1,nclin)

      If (nclin>0) Then
        sda = n
      Else
        sda = 1
      End If

!     This particular example problem is of type QP2 with H stored explicitly,
!     so we allocate CVEC(N) and H(LDH,N), and define LDH and LWORK as below

      ldh = n

      If (nclin>0) Then
        lwork = 2*n**2 + 8*n + 5*nclin
      Else
        lwork = n**2 + 8*n
      End If

      Allocate (istate(n+nclin),ax(max(1,nclin)),iwork(liwork),h(ldh,n),bl(n+  &
        nclin),bu(n+nclin),cvec(n),x(n),a(lda,sda),clamda(n+nclin),            &
        work(lwork))

      Read (nin,*) cvec(1:n)
      Read (nin,*)(a(i,1:sda),i=1,nclin)
      Read (nin,*) bl(1:(n+nclin))
      Read (nin,*) bu(1:(n+nclin))
      Read (nin,*) x(1:n)
      Read (nin,*)(h(i,1:n),i=1,n)

!     Solve the problem

      ifail = 0
      Call e04nff(n,nclin,a,lda,bl,bu,cvec,h,ldh,e04nfu,istate,x,iter,obj,ax,  &
        clamda,iwork,liwork,work,lwork,ifail)

    End Program e04nffe


e04ngae.f90

!   E04NGA Example Program Text
!   Mark 26 Release. NAG Copyright 2016.

    Module e04ngae_mod

!     E04NGA Example Program Module:
!            Parameters and User-defined Routines

!     .. Use Statements ..
      Use nag_library, Only: nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Accessibility Statements ..
      Private
      Public                           :: qphess
!     .. Parameters ..
      Integer, Parameter, Public       :: iset = 1, lcwsav = 1, liwsav = 610,  &
                                          llwsav = 120, lrwsav = 475, nin = 5, &
                                          ninopt = 7, nout = 6
    Contains
      Subroutine qphess(n,jthcol,h,ldh,x,hx,iuser,ruser,iwsav)
!       In this version of QPHESS, the lower triangle of matrix H is
!       stored in packed form (by columns) in array H.
!       More precisely, the lower triangle of matrix H must be stored with
!       matrix element H(i,j) in array element H(i+(2*N-j)*(j-1)/2,1),
!       for i .ge. j.
!       Note that storing the lower triangle of matrix H in packed form (by
!       columns) is equivalent to storing the upper triangle of matrix H in
!       packed form (by rows).
!       Note also that LDH is used to define the size of array H, and
!       must therefore be at least N*(N+1)/2.

!       .. Scalar Arguments ..
        Integer, Intent (In)           :: jthcol, ldh, n
!       .. Array Arguments ..
        Real (Kind=nag_wp), Intent (In) :: h(ldh,*), x(n)
        Real (Kind=nag_wp), Intent (Out) :: hx(n)
        Real (Kind=nag_wp), Intent (Inout) :: ruser(*)
        Integer, Intent (Inout)        :: iuser(*), iwsav(610)
!       .. Local Scalars ..
        Real (Kind=nag_wp)             :: s
        Integer                        :: i, inc, j, l, lp1
!       .. Executable Statements ..
        If (jthcol/=0) Then

!         Special case -- extract one column of  H.

          l = jthcol
          inc = n

          Do i = 1, jthcol
            hx(i) = h(l,1)
            inc = inc - 1
            l = l + inc
          End Do

          l = l - inc + 1

          If (jthcol<n) Then
            lp1 = l

            Do i = jthcol + 1, n
              hx(i) = h(lp1,1)
              lp1 = lp1 + 1
            End Do

          End If

        Else

!         Normal case.

          l = 0

          Do i = 1, n
            s = 0.0E0_nag_wp

            Do j = i, n
              l = l + 1
              s = s + h(l,1)*x(j)
            End Do

            hx(i) = s
          End Do

          l = 0

          Do j = 1, n - 1
            l = l + 1

            Do i = j + 1, n
              l = l + 1
              hx(i) = hx(i) + h(l,1)*x(j)
            End Do

          End Do

        End If

        Return

      End Subroutine qphess
    End Module e04ngae_mod
    Program e04ngae

!     E04NGA Example Main Program

!     .. Use Statements ..
      Use nag_library, Only: e04nfa, e04nga, e04nha, e04wbf, nag_wp, x04abf,   &
                             x04acf, x04baf
      Use e04ngae_mod, Only: iset, lcwsav, liwsav, llwsav, lrwsav, nin,        &
                             ninopt, nout, qphess
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Character (*), Parameter         :: fname = 'e04ngae.opt'
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: obj
      Integer                          :: i, ifail, inform, iter, j, lda, ldh, &
                                          liwork, lwork, mode, n, nclin,       &
                                          outchn, sda
      Character (80)                   :: rec
      Character (1)                    :: uplo
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: a(:,:), ax(:), bl(:), bu(:),         &
                                          clamda(:), cvec(:), h(:,:), work(:), &
                                          x(:)
      Real (Kind=nag_wp)               :: ruser(1), rwsav(lrwsav)
      Integer, Allocatable             :: istate(:), iwork(:)
      Integer                          :: iuser(1), iwsav(liwsav)
      Logical                          :: lwsav(llwsav)
      Character (80)                   :: cwsav(lcwsav)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: max
!     .. Executable Statements ..
      Write (rec,99992) 'E04NGA Example Program Results'
      Call x04baf(nout,rec)

!     Skip heading in data file
      Read (nin,*)

      Read (nin,*) n, nclin
      liwork = 2*n + 3
      lda = max(1,nclin)

      If (nclin>0) Then
        sda = n
      Else
        sda = 1
      End If

!     This particular example problem is of type QP2 with a nondefault QPHESS,
!     so we allocate CVEC(N) and H(LDH,1), and define LDH and LWORK as below

      ldh = n*(n+1)/2

      If (nclin>0) Then
        lwork = 2*n**2 + 8*n + 5*nclin
      Else
        lwork = n**2 + 8*n
      End If

      Allocate (istate(n+nclin),ax(max(1,nclin)),iwork(liwork),h(ldh,1),bl(n+  &
        nclin),bu(n+nclin),cvec(n),x(n),a(lda,sda),clamda(n+nclin),            &
        work(lwork))

      Read (nin,*) cvec(1:n)
      Read (nin,*)(a(i,1:n),i=1,nclin)
      Read (nin,*) bl(1:(n+nclin))
      Read (nin,*) bu(1:(n+nclin))
      Read (nin,*) x(1:n)
      Read (nin,*) uplo

      If (uplo=='U') Then

!       Read the upper triangle of H

        Read (nin,*)((h(j+(2*n-i)*(i-1)/2,1),j=i,n),i=1,n)
      Else If (uplo=='L') Then

!       Read the lower triangle of H

        Read (nin,*)((h(i+(2*n-j)*(j-1)/2,1),j=1,i),i=1,n)
      End If

      ldh = n*(n+1)/2

!     Set the unit number for advisory messages to OUTCHN

      outchn = nout
      Call x04abf(iset,outchn)

!     Initialise E04NFA

      ifail = 0
      Call e04wbf('E04NFA',cwsav,lcwsav,lwsav,llwsav,iwsav,liwsav,rwsav,       &
        lrwsav,ifail)

!     Set three options using E04NHA

      Call e04nha(' Check Frequency = 10 ',lwsav,iwsav,rwsav,inform)

      If (inform==0) Then

        Call e04nha(' Crash Tolerance = 0.05 ',lwsav,iwsav,rwsav,inform)

        If (inform==0) Then

          Call e04nha(' Infinite Bound Size = 1.0D+25 ',lwsav,iwsav,rwsav,     &
            inform)

        End If

      End If

      If (inform/=0) Then
        Write (rec,99999) 'E04NHA terminated with INFORM = ', inform
        Call x04baf(nout,rec)
        Go To 100
      End If

!     Open the options file for reading

      mode = 0

      ifail = 0
      Call x04acf(ninopt,fname,mode,ifail)

!     Read the options file for the remaining options

      Call e04nga(ninopt,lwsav,iwsav,rwsav,inform)

      If (inform/=0) Then
        Write (rec,99999) 'E04NGA terminated with INFORM =', inform
        Call x04baf(nout,rec)
        Go To 100
      End If

!     Solve the problem

      ifail = -1
      Call e04nfa(n,nclin,a,lda,bl,bu,cvec,h,ldh,qphess,istate,x,iter,obj,ax,  &
        clamda,iwork,liwork,work,lwork,iuser,ruser,lwsav,iwsav,rwsav,ifail)

      Select Case (ifail)
      Case (0:5,7:)
        Write (rec,'()')
        Call x04baf(nout,rec)
        Write (rec,99998)
        Call x04baf(nout,rec)
        Write (rec,'()')
        Call x04baf(nout,rec)

        Do i = 1, n
          Write (rec,99997) i, istate(i), x(i), clamda(i)
          Call x04baf(nout,rec)
        End Do

        If (nclin>0) Then
          Write (rec,'()')
          Call x04baf(nout,rec)
          Write (rec,'()')
          Call x04baf(nout,rec)
          Write (rec,99996)
          Call x04baf(nout,rec)
          Write (rec,'()')
          Call x04baf(nout,rec)

          Do i = n + 1, n + nclin
            j = i - n
            Write (rec,99995) j, istate(i), ax(j), clamda(i)
            Call x04baf(nout,rec)
          End Do

        End If

        Write (rec,'()')
        Call x04baf(nout,rec)
        Write (rec,'()')
        Call x04baf(nout,rec)
        Write (rec,99994) obj
        Call x04baf(nout,rec)
        Write (rec,'()')
        Call x04baf(nout,rec)
        Write (rec,'()')
        Call x04baf(nout,rec)
        Write (rec,99993) iter
        Call x04baf(nout,rec)
      End Select

100   Continue

99999 Format (1X,A,I5)
99998 Format (1X,'Varbl',2X,'Istate',3X,'Value',9X,'Lagr Mult')
99997 Format (1X,'V',2(1X,I3),4X,1P,G14.6,2X,1P,G12.4)
99996 Format (1X,'L Con',2X,'Istate',3X,'Value',9X,'Lagr Mult')
99995 Format (1X,'L',2(1X,I3),4X,1P,G14.6,2X,1P,G12.4)
99994 Format (1X,'Final objective value = ',G15.7)
99993 Format (1X,'Exit from problem after',1X,I6,1X,'iterations.')
99992 Format (1X,A)
    End Program e04ngae


e04ngfe.f90

!   E04NGF Example Program Text
!   Mark 26 Release. NAG Copyright 2016.

    Module e04ngfe_mod

!     E04NGF Example Program Module:
!            Parameters and User-defined Routines

!     .. Use Statements ..
      Use nag_library, Only: nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Accessibility Statements ..
      Private
      Public                           :: qphess
!     .. Parameters ..
      Integer, Parameter, Public       :: iset = 1, nin = 5, ninopt = 7,       &
                                          nout = 6
    Contains
      Subroutine qphess(n,jthcol,h,ldh,x,hx)
!       In this version of QPHESS, the lower triangle of matrix H is
!       stored in packed form (by columns) in array H.
!       More precisely, the lower triangle of matrix H must be stored with
!       matrix element H(i,j) in array element H(i+(2*N-j)*(j-1)/2,1),
!       for i .ge. j.
!       Note that storing the lower triangle of matrix H in packed form (by
!       columns) is equivalent to storing the upper triangle of matrix H in
!       packed form (by rows).
!       Note also that LDH is used to define the size of array H, and
!       must therefore be at least N*(N+1)/2.

!       .. Scalar Arguments ..
        Integer, Intent (In)           :: jthcol, ldh, n
!       .. Array Arguments ..
        Real (Kind=nag_wp), Intent (In) :: h(ldh,*), x(n)
        Real (Kind=nag_wp), Intent (Out) :: hx(n)
!       .. Local Scalars ..
        Real (Kind=nag_wp)             :: s
        Integer                        :: i, inc, j, l, lp1
!       .. Executable Statements ..
        If (jthcol/=0) Then

!         Special case -- extract one column of  H.

          l = jthcol
          inc = n

          Do i = 1, jthcol
            hx(i) = h(l,1)
            inc = inc - 1
            l = l + inc
          End Do

          l = l - inc + 1

          If (jthcol<n) Then
            lp1 = l

            Do i = jthcol + 1, n
              hx(i) = h(lp1,1)
              lp1 = lp1 + 1
            End Do

          End If

        Else

!         Normal case.

          l = 0

          Do i = 1, n
            s = 0.0E0_nag_wp

            Do j = i, n
              l = l + 1
              s = s + h(l,1)*x(j)
            End Do

            hx(i) = s
          End Do

          l = 0

          Do j = 1, n - 1
            l = l + 1

            Do i = j + 1, n
              l = l + 1
              hx(i) = hx(i) + h(l,1)*x(j)
            End Do

          End Do

        End If

        Return

      End Subroutine qphess
    End Module e04ngfe_mod
    Program e04ngfe

!     E04NGF Example Main Program

!     .. Use Statements ..
      Use nag_library, Only: e04nff, e04ngf, e04nhf, nag_wp, x04abf, x04acf,   &
                             x04baf
      Use e04ngfe_mod, Only: iset, nin, ninopt, nout, qphess
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Character (*), Parameter         :: fname = 'e04ngfe.opt'
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: obj
      Integer                          :: i, ifail, inform, iter, j, lda, ldh, &
                                          liwork, lwork, mode, n, nclin,       &
                                          outchn, sda
      Character (80)                   :: rec
      Character (1)                    :: uplo
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: a(:,:), ax(:), bl(:), bu(:),         &
                                          clamda(:), cvec(:), h(:,:), work(:), &
                                          x(:)
      Integer, Allocatable             :: istate(:), iwork(:)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: max
!     .. Executable Statements ..
      Write (rec,99998) 'E04NGF Example Program Results'
      Call x04baf(nout,rec)

!     Skip heading in data file
      Read (nin,*)

      Read (nin,*) n, nclin
      liwork = 2*n + 3
      lda = max(1,nclin)

      If (nclin>0) Then
        sda = n
      Else
        sda = 1
      End If

!     This particular example problem is of type QP2 with a nondefault QPHESS,
!     so we allocate CVEC(N) and H(LDH,1), and define LDH and LWORK as below

      ldh = n*(n+1)/2

      If (nclin>0) Then
        lwork = 2*n**2 + 8*n + 5*nclin
      Else
        lwork = n**2 + 8*n
      End If

      Allocate (istate(n+nclin),ax(max(1,nclin)),iwork(liwork),h(ldh,1),bl(n+  &
        nclin),bu(n+nclin),cvec(n),x(n),a(lda,sda),clamda(n+nclin),            &
        work(lwork))

      Read (nin,*) cvec(1:n)
      Read (nin,*)(a(i,1:n),i=1,nclin)
      Read (nin,*) bl(1:(n+nclin))
      Read (nin,*) bu(1:(n+nclin))
      Read (nin,*) x(1:n)
      Read (nin,*) uplo

      If (uplo=='U') Then

!       Read the upper triangle of H

        Read (nin,*)((h(j+(2*n-i)*(i-1)/2,1),j=i,n),i=1,n)
      Else If (uplo=='L') Then

!       Read the lower triangle of H

        Read (nin,*)((h(i+(2*n-j)*(j-1)/2,1),j=1,i),i=1,n)
      End If

      ldh = n*(n+1)/2

!     Set the unit number for advisory messages to OUTCHN

      outchn = nout
      Call x04abf(iset,outchn)

!     Set four options using E04NHF

      Call e04nhf(' Print Level = 1 ')

      Call e04nhf(' Check Frequency = 10 ')

      Call e04nhf(' Crash Tolerance = 0.05 ')

      Call e04nhf(' Infinite Bound Size = 1.0D+25 ')

!     Open the options file for reading

      mode = 0

      ifail = 0
      Call x04acf(ninopt,fname,mode,ifail)

!     Read the options file for the remaining options

      Call e04ngf(ninopt,inform)

      If (inform/=0) Then
        Write (rec,99999) 'E04NGF terminated with INFORM =', inform
        Call x04baf(nout,rec)
        Go To 100
      End If

!     Solve the problem

      ifail = 0
      Call e04nff(n,nclin,a,lda,bl,bu,cvec,h,ldh,qphess,istate,x,iter,obj,ax,  &
        clamda,iwork,liwork,work,lwork,ifail)

100   Continue

99999 Format (1X,A,I5)
99998 Format (1X,A)
    End Program e04ngfe


e04nkae.f90

!   E04NKA Example Program Text
!   Mark 26 Release. NAG Copyright 2016.

    Module e04nkae_mod

!     E04NKA Example Program Module:
!            Parameters and User-defined Routines

!     .. Use Statements ..
      Use nag_library, Only: nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Accessibility Statements ..
      Private
      Public                           :: qphx
!     .. Parameters ..
      Integer, Parameter, Public       :: lcwsav = 1, liwsav = 380,            &
                                          llwsav = 20, lrwsav = 285, nin = 5,  &
                                          nout = 6
    Contains
      Subroutine qphx(nstate,ncolh,x,hx,iuser,ruser)

!       Routine to compute H*x. (In this version of QPHX, the Hessian
!       matrix H is not referenced explicitly.)

!       .. Scalar Arguments ..
        Integer, Intent (In)           :: ncolh, nstate
!       .. Array Arguments ..
        Real (Kind=nag_wp), Intent (Out) :: hx(ncolh)
        Real (Kind=nag_wp), Intent (Inout) :: ruser(*)
        Real (Kind=nag_wp), Intent (In) :: x(ncolh)
        Integer, Intent (Inout)        :: iuser(*)
!       .. Executable Statements ..
        hx(1) = 2.0E0_nag_wp*x(1)
        hx(2) = 2.0E0_nag_wp*x(2)
        hx(3) = 2.0E0_nag_wp*(x(3)+x(4))
        hx(4) = hx(3)
        hx(5) = 2.0E0_nag_wp*x(5)
        hx(6) = 2.0E0_nag_wp*(x(6)+x(7))
        hx(7) = hx(6)

        Return

      End Subroutine qphx
    End Module e04nkae_mod
    Program e04nkae

!     E04NKA Example Main Program

!     .. Use Statements ..
      Use nag_library, Only: e04nka, e04wbf, nag_wp
      Use e04nkae_mod, Only: lcwsav, liwsav, llwsav, lrwsav, nin, nout, qphx
!     .. Implicit None Statement ..
      Implicit None
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: obj, sinf
      Integer                          :: i, icol, ifail, iobj, jcol, leniz,   &
                                          lenz, m, miniz, minz, n, ncolh,      &
                                          ninf, nname, nnz, ns
      Character (1)                    :: start
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: a(:), bl(:), bu(:), clamda(:),       &
                                          xs(:), z(:)
      Real (Kind=nag_wp)               :: ruser(1), rwsav(lrwsav)
      Integer, Allocatable             :: ha(:), istate(:), iz(:), ka(:)
      Integer                          :: iuser(1), iwsav(liwsav)
      Logical                          :: lwsav(llwsav)
      Character (8), Allocatable       :: crname(:)
      Character (80)                   :: cwsav(lcwsav)
      Character (8)                    :: names(5)
!     .. Executable Statements ..
      Write (nout,*) 'E04NKA Example Program Results'
      Flush (nout)

!     Skip heading in data file.
      Read (nin,*)

      Read (nin,*) n, m
      Read (nin,*) nnz, iobj, ncolh, start, nname
      Allocate (ha(nnz),ka(n+1),istate(n+m),a(nnz),bl(n+m),bu(n+m),xs(n+m),    &
        clamda(n+m),crname(nname))

      Read (nin,*) names(1:5)
      Read (nin,*) crname(1:nname)

!     Read the matrix A from data file. Set up KA.

      jcol = 1
      ka(jcol) = 1

      Do i = 1, nnz

!       Element ( HA( I ), ICOL ) is stored in A( I ).

        Read (nin,*) a(i), ha(i), icol

        If (icol<jcol) Then

!         Elements not ordered by increasing column index.

          Write (nout,99999) 'Element in column', icol,                        &
            ' found after element in column', jcol, '. Problem', ' abandoned.'
          Go To 100
        Else If (icol==jcol+1) Then

!         Index in A of the start of the ICOL-th column equals I.

          ka(icol) = i
          jcol = icol
        Else If (icol>jcol+1) Then

!         Index in A of the start of the ICOL-th column equals I,
!         but columns JCOL+1,JCOL+2,...,ICOL-1 are empty. Set the
!         corresponding elements of KA to I.

          ka((jcol+1):icol) = i
          jcol = icol
        End If

      End Do

      ka(n+1) = nnz + 1

!     Columns N,N-1,...,ICOL+1 are empty. Set the corresponding
!     elements of KA accordingly.

      Do i = n, icol + 1, -1
        ka(i) = ka(i+1)
      End Do

      Read (nin,*) bl(1:(n+m))
      Read (nin,*) bu(1:(n+m))

      If (start=='C') Then
        Read (nin,*) istate(1:n)
      Else If (start=='W') Then
        Read (nin,*) istate(1:(n+m))
      End If

      Read (nin,*) xs(1:n)

!     Initialise E04NKA

      ifail = 0
      Call e04wbf('E04NKA',cwsav,lcwsav,lwsav,llwsav,iwsav,liwsav,rwsav,       &
        lrwsav,ifail)

!     Solve the QP problem.
!     First call is a workspace query

      leniz = 1
      lenz = 1
      Allocate (iz(leniz),z(lenz))

      ifail = 1
      Call e04nka(n,m,nnz,iobj,ncolh,qphx,a,ha,ka,bl,bu,start,names,nname,     &
        crname,ns,xs,istate,miniz,minz,ninf,sinf,obj,clamda,iz,leniz,z,lenz,   &
        iuser,ruser,lwsav,iwsav,rwsav,ifail)

      If (ifail/=0 .And. ifail/=12 .And. ifail/=13) Then
        Write (nout,99993) 'Query call to E04NKA failed with IFAIL =', ifail
        Go To 100
      End If

      Deallocate (iz,z)

      lenz = minz
      leniz = miniz
      Allocate (iz(leniz),z(lenz))

      ifail = -1
      Call e04nka(n,m,nnz,iobj,ncolh,qphx,a,ha,ka,bl,bu,start,names,nname,     &
        crname,ns,xs,istate,miniz,minz,ninf,sinf,obj,clamda,iz,leniz,z,lenz,   &
        iuser,ruser,lwsav,iwsav,rwsav,ifail)

      Select Case (ifail)
      Case (0:6,8:)
        Write (nout,*)
        Write (nout,99998)
        Write (nout,*)

        Do i = 1, n
          Write (nout,99997) crname(i), istate(i), xs(i), clamda(i)
        End Do

        If (m>0) Then
          Write (nout,*)
          Write (nout,*)
          Write (nout,99996)
          Write (nout,*)

          Do i = n + 1, n + m
            Write (nout,99995) crname(i), istate(i), xs(i), clamda(i)
          End Do

        End If

        Write (nout,*)
        Write (nout,*)
        Write (nout,99994) obj
      End Select

100   Continue

99999 Format (/,1X,A,I5,A,I5,A,A)
99998 Format (1X,'Variable',2X,'Istate',5X,'Value',9X,'Lagr Mult')
99997 Format (1X,1X,A,1X,I3,4X,1P,G14.6,2X,1P,G12.4)
99996 Format (1X,'Constrnt',2X,'Istate',5X,'Value',9X,'Lagr Mult')
99995 Format (1X,1X,A,1X,I3,4X,1P,G14.6,2X,1P,G12.4)
99994 Format (1X,'Final objective value = ',G15.7)
99993 Format (1X,A,I5)
    End Program e04nkae


e04nkfe.f90

!   E04NKF Example Program Text
!   Mark 26 Release. NAG Copyright 2016.

    Module e04nkfe_mod

!     E04NKF Example Program Module:
!            Parameters and User-defined Routines

!     .. Use Statements ..
      Use nag_library, Only: nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Accessibility Statements ..
      Private
      Public                           :: qphx
!     .. Parameters ..
      Integer, Parameter, Public       :: nin = 5, nout = 6
    Contains
      Subroutine qphx(nstate,ncolh,x,hx)

!       Routine to compute H*x. (In this version of QPHX, the Hessian
!       matrix H is not referenced explicitly.)

!       .. Scalar Arguments ..
        Integer, Intent (In)           :: ncolh, nstate
!       .. Array Arguments ..
        Real (Kind=nag_wp), Intent (Out) :: hx(ncolh)
        Real (Kind=nag_wp), Intent (In) :: x(ncolh)
!       .. Executable Statements ..
        hx(1) = 2.0E0_nag_wp*x(1)
        hx(2) = 2.0E0_nag_wp*x(2)
        hx(3) = 2.0E0_nag_wp*(x(3)+x(4))
        hx(4) = hx(3)
        hx(5) = 2.0E0_nag_wp*x(5)
        hx(6) = 2.0E0_nag_wp*(x(6)+x(7))
        hx(7) = hx(6)

        Return

      End Subroutine qphx
    End Module e04nkfe_mod
    Program e04nkfe

!     E04NKF Example Main Program

!     .. Use Statements ..
      Use nag_library, Only: e04nkf, nag_wp
      Use e04nkfe_mod, Only: nin, nout, qphx
!     .. Implicit None Statement ..
      Implicit None
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: obj, sinf
      Integer                          :: i, icol, ifail, iobj, jcol, leniz,   &
                                          lenz, m, miniz, minz, n, ncolh,      &
                                          ninf, nname, nnz, ns
      Character (1)                    :: start
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: a(:), bl(:), bu(:), clamda(:),       &
                                          xs(:), z(:)
      Integer, Allocatable             :: ha(:), istate(:), iz(:), ka(:)
      Character (8), Allocatable       :: crname(:)
      Character (8)                    :: names(5)
!     .. Executable Statements ..
      Write (nout,*) 'E04NKF Example Program Results'
      Flush (nout)

!     Skip heading in data file.
      Read (nin,*)

      Read (nin,*) n, m
      Read (nin,*) nnz, iobj, ncolh, start, nname
      Allocate (ha(nnz),ka(n+1),istate(n+m),a(nnz),bl(n+m),bu(n+m),xs(n+m),    &
        clamda(n+m),crname(nname))

      Read (nin,*) names(1:5)
      Read (nin,*) crname(1:nname)

!     Read the matrix A from data file. Set up KA.

      jcol = 1
      ka(jcol) = 1

      Do i = 1, nnz

!       Element ( HA( I ), ICOL ) is stored in A( I ).

        Read (nin,*) a(i), ha(i), icol

        If (icol<jcol) Then

!         Elements not ordered by increasing column index.

          Write (nout,99999) 'Element in column', icol,                        &
            ' found after element in column', jcol, '. Problem', ' abandoned.'
          Go To 100
        Else If (icol==jcol+1) Then

!         Index in A of the start of the ICOL-th column equals I.

          ka(icol) = i
          jcol = icol
        Else If (icol>jcol+1) Then

!         Index in A of the start of the ICOL-th column equals I,
!         but columns JCOL+1,JCOL+2,...,ICOL-1 are empty. Set the
!         corresponding elements of KA to I.

          ka((jcol+1):icol) = i
          jcol = icol
        End If

      End Do

      ka(n+1) = nnz + 1

!     Columns N,N-1,...,ICOL+1 are empty. Set the corresponding
!     elements of KA accordingly.

      Do i = n, icol + 1, -1
        ka(i) = ka(i+1)
      End Do

      Read (nin,*) bl(1:(n+m))
      Read (nin,*) bu(1:(n+m))

      If (start=='C') Then
        Read (nin,*) istate(1:n)
      Else If (start=='W') Then
        Read (nin,*) istate(1:(n+m))
      End If

      Read (nin,*) xs(1:n)

!     Solve the QP problem.
!     First call is a workspace query

      leniz = 1
      lenz = 1
      Allocate (iz(leniz),z(lenz))

      ifail = 1
      Call e04nkf(n,m,nnz,iobj,ncolh,qphx,a,ha,ka,bl,bu,start,names,nname,     &
        crname,ns,xs,istate,miniz,minz,ninf,sinf,obj,clamda,iz,leniz,z,lenz,   &
        ifail)

      If (ifail/=0 .And. ifail/=12 .And. ifail/=13) Then
        Write (nout,99998) 'Query call to E04NKF failed with IFAIL =', ifail
        Go To 100
      End If

      Deallocate (iz,z)

      lenz = minz
      leniz = miniz
      Allocate (iz(leniz),z(lenz))

      ifail = 0
      Call e04nkf(n,m,nnz,iobj,ncolh,qphx,a,ha,ka,bl,bu,start,names,nname,     &
        crname,ns,xs,istate,miniz,minz,ninf,sinf,obj,clamda,iz,leniz,z,lenz,   &
        ifail)

100   Continue

99999 Format (/,1X,A,I5,A,I5,A,A)
99998 Format (1X,A,I5)
    End Program e04nkfe


e04nlae.f90

!   E04NLA Example Program Text
!   Mark 26 Release. NAG Copyright 2016.

    Module e04nlae_mod

!     E04NLA Example Program Module:
!            Parameters and User-defined Routines

!     .. Use Statements ..
      Use nag_library, Only: nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Accessibility Statements ..
      Private
      Public                           :: qphx
!     .. Parameters ..
      Integer, Parameter, Public       :: iset = 1, lcwsav = 1, liwsav = 380,  &
                                          llwsav = 20, lrwsav = 285, nin = 5,  &
                                          ninopt = 7, nout = 6
    Contains
      Subroutine qphx(nstate,ncolh,x,hx,iuser,ruser)

!       Routine to compute H*x. (In this version of QPHX, the Hessian
!       matrix H is not referenced explicitly.)

!       .. Scalar Arguments ..
        Integer, Intent (In)           :: ncolh, nstate
!       .. Array Arguments ..
        Real (Kind=nag_wp), Intent (Out) :: hx(ncolh)
        Real (Kind=nag_wp), Intent (Inout) :: ruser(*)
        Real (Kind=nag_wp), Intent (In) :: x(ncolh)
        Integer, Intent (Inout)        :: iuser(*)
!       .. Executable Statements ..
        If (nstate==1) Then

!         First entry.

          Write (nout,*)
          Write (nout,99999) ncolh
          Flush (nout)
        End If

        hx(1) = 2.0E0_nag_wp*x(1)
        hx(2) = 2.0E0_nag_wp*x(2)
        hx(3) = 2.0E0_nag_wp*(x(3)+x(4))
        hx(4) = hx(3)
        hx(5) = 2.0E0_nag_wp*x(5)
        hx(6) = 2.0E0_nag_wp*(x(6)+x(7))
        hx(7) = hx(6)

        If (nstate>=2) Then

!         Final entry.

          Write (nout,*)
          Write (nout,99998)
          Flush (nout)
        End If

        Return

99999   Format (1X,'This is the E04NLA example.   NCOLH =',I4,'.')
99998   Format (1X,'Finished the E04NLA example.')
      End Subroutine qphx
    End Module e04nlae_mod
    Program e04nlae

!     E04NLA Example Main Program

!     .. Use Statements ..
      Use nag_library, Only: e04nka, e04nla, e04nma, e04wbf, nag_wp, x04abf,   &
                             x04acf
      Use e04nlae_mod, Only: iset, lcwsav, liwsav, llwsav, lrwsav, nin,        &
                             ninopt, nout, qphx
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Character (*), Parameter         :: fname = 'e04nlae.opt'
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: obj, sinf
      Integer                          :: i, icol, ifail, inform, iobj, jcol,  &
                                          leniz, lenz, m, miniz, minz, mode,   &
                                          n, ncolh, ninf, nname, nnz, ns,      &
                                          outchn
      Character (1)                    :: start
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: a(:), bl(:), bu(:), clamda(:),       &
                                          xs(:), z(:)
      Real (Kind=nag_wp)               :: ruser(1), rwsav(lrwsav)
      Integer, Allocatable             :: ha(:), istate(:), iz(:), ka(:)
      Integer                          :: iuser(1), iwsav(liwsav)
      Logical                          :: lwsav(llwsav)
      Character (8), Allocatable       :: crname(:)
      Character (80)                   :: cwsav(lcwsav)
      Character (8)                    :: names(5)
!     .. Executable Statements ..
      Write (nout,99992) 'E04NLA Example Program Results'
      Flush (nout)

!     Skip heading in data file.
      Read (nin,*)

      Read (nin,*) n, m
      Read (nin,*) nnz, iobj, ncolh, start, nname

      Allocate (ha(nnz),ka(n+1),istate(n+m),a(nnz),bl(n+m),bu(n+m),xs(n+m),    &
        clamda(n+m),crname(nname))

      Read (nin,*) names(1:5)
      Read (nin,*) crname(1:nname)

!     Read the matrix A from data file. Set up KA.

      jcol = 1
      ka(jcol) = 1

      Do i = 1, nnz

!       Element ( HA( I ), ICOL ) is stored in A( I ).

        Read (nin,*) a(i), ha(i), icol

        If (icol<jcol) Then

!         Elements not ordered by increasing column index.

          Write (nout,*)
          Write (nout,99998) 'Element in column', icol,                        &
            ' found after element in column', jcol, '. Problem', ' abandoned.'
          Flush (nout)
          Go To 100
        Else If (icol==jcol+1) Then

!         Index in A of the start of the ICOL-th column equals I.

          ka(icol) = i
          jcol = icol
        Else If (icol>jcol+1) Then

!         Index in A of the start of the ICOL-th column equals I,
!         but columns JCOL+1,JCOL+2,...,ICOL-1 are empty. Set the
!         corresponding elements of KA to I.

          ka((jcol+1):icol) = i
          jcol = icol
        End If

      End Do

      ka(n+1) = nnz + 1

!     Columns N,N-1,...,ICOL+1 are empty. Set the corresponding
!     elements of KA accordingly.

      Do i = n, icol + 1, -1
        ka(i) = ka(i+1)
      End Do

      Read (nin,*) bl(1:(n+m))
      Read (nin,*) bu(1:(n+m))

      If (start=='C') Then
        Read (nin,*) istate(1:n)
      Else If (start=='W') Then
        Read (nin,*) istate(1:(n+m))
      End If

      Read (nin,*) xs(1:n)

!     Set the unit number for advisory messages to OUTCHN.

      outchn = nout
      Call x04abf(iset,outchn)

!     Initialise E04NKA

      ifail = 0
      Call e04wbf('E04NKA',cwsav,lcwsav,lwsav,llwsav,iwsav,liwsav,rwsav,       &
        lrwsav,ifail)

!     Set three options using E04NMF.

      Call e04nma(' Check Frequency = 10 ',lwsav,iwsav,rwsav,inform)

      If (inform==0) Then

        Call e04nma(' Crash Tolerance = 0.05 ',lwsav,iwsav,rwsav,inform)

        If (inform==0) Then

          Call e04nma(' Infinite Bound Size = 1.0E+25 ',lwsav,iwsav,rwsav,     &
            inform)

        End If

      End If

      If (inform/=0) Then
        Write (nout,99999) 'E04NMA terminated with INFORM = ', inform
        Flush (nout)
        Go To 100
      End If

!     Open the options file for reading

      mode = 0

      ifail = 0
      Call x04acf(ninopt,fname,mode,ifail)

!     Read the options file for the remaining options.

      Call e04nla(ninopt,lwsav,iwsav,rwsav,inform)

      If (inform/=0) Then
        Write (nout,99999) 'E04NLA terminated with INFORM = ', inform
        Flush (nout)
        Go To 100
      End If

!     Solve the QP problem.
!     First call is a workspace query

      leniz = 1
      lenz = 1
      Allocate (iz(leniz),z(lenz))

      ifail = 1
      Call e04nka(n,m,nnz,iobj,ncolh,qphx,a,ha,ka,bl,bu,start,names,nname,     &
        crname,ns,xs,istate,miniz,minz,ninf,sinf,obj,clamda,iz,leniz,z,lenz,   &
        iuser,ruser,lwsav,iwsav,rwsav,ifail)

      If (ifail/=0 .And. ifail/=12 .And. ifail/=13) Then
        Write (nout,99999) 'Query call to E04NKA failed with IFAIL =', ifail
        Go To 100
      End If

      Deallocate (iz,z)

      lenz = minz
      leniz = miniz
      Allocate (iz(leniz),z(lenz))

      ifail = -1
      Call e04nka(n,m,nnz,iobj,ncolh,qphx,a,ha,ka,bl,bu,start,names,nname,     &
        crname,ns,xs,istate,miniz,minz,ninf,sinf,obj,clamda,iz,leniz,z,lenz,   &
        iuser,ruser,lwsav,iwsav,rwsav,ifail)

      Select Case (ifail)
      Case (0:6,8:)
        Write (nout,*)
        Write (nout,99997)
        Write (nout,*)
        Flush (nout)

        Do i = 1, n
          Write (nout,99996) crname(i), istate(i), xs(i), clamda(i)
          Flush (nout)
        End Do

        If (m>0) Then
          Write (nout,*)
          Write (nout,*)
          Write (nout,99995)
          Write (nout,'()')

          Do i = n + 1, n + m
            Write (nout,99994) crname(i), istate(i), xs(i), clamda(i)
          End Do
          Flush (nout)

        End If

        Write (nout,*)
        Write (nout,*)
        Write (nout,99993) obj
        Flush (nout)
      End Select

100   Continue

99999 Format (1X,A,I5)
99998 Format (1X,A,I5,A,I5,A,A)
99997 Format (1X,'Variable',2X,'Istate',5X,'Value',9X,'Lagr Mult')
99996 Format (1X,1X,A,1X,I3,4X,1P,G14.6,2X,1P,G12.4)
99995 Format (1X,'Constrnt',2X,'Istate',5X,'Value',9X,'Lagr Mult')
99994 Format (1X,1X,A,1X,I3,4X,1P,G14.6,2X,1P,G12.4)
99993 Format (1X,'Final objective value = ',G15.7)
99992 Format (1X,A)
    End Program e04nlae


e04nlfe.f90

!   E04NLF Example Program Text
!   Mark 26 Release. NAG Copyright 2016.

    Module e04nlfe_mod

!     E04NLF Example Program Module:
!            Parameters and User-defined Routines

!     .. Use Statements ..
      Use nag_library, Only: nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Accessibility Statements ..
      Private
      Public                           :: qphx
!     .. Parameters ..
      Integer, Parameter, Public       :: iset = 1, nin = 5, ninopt = 7,       &
                                          nout = 6
    Contains
      Subroutine qphx(nstate,ncolh,x,hx)

!       Routine to compute H*x. (In this version of QPHX, the Hessian
!       matrix H is not referenced explicitly.)

!       .. Scalar Arguments ..
        Integer, Intent (In)           :: ncolh, nstate
!       .. Array Arguments ..
        Real (Kind=nag_wp), Intent (Out) :: hx(ncolh)
        Real (Kind=nag_wp), Intent (In) :: x(ncolh)
!       .. Executable Statements ..
        If (nstate==1) Then

!         First entry.

          Write (nout,*)
          Write (nout,99999) ncolh
          Flush (nout)
        End If

        hx(1) = 2.0E0_nag_wp*x(1)
        hx(2) = 2.0E0_nag_wp*x(2)
        hx(3) = 2.0E0_nag_wp*(x(3)+x(4))
        hx(4) = hx(3)
        hx(5) = 2.0E0_nag_wp*x(5)
        hx(6) = 2.0E0_nag_wp*(x(6)+x(7))
        hx(7) = hx(6)

        If (nstate>=2) Then

!         Final entry.

          Write (nout,*)
          Write (nout,99998)
          Flush (nout)
        End If

        Return

99999   Format (1X,'This is the E04NLF example.   NCOLH =',I4,'.')
99998   Format (1X,'Finished the E04NLF example.')
      End Subroutine qphx
    End Module e04nlfe_mod
    Program e04nlfe

!     E04NLF Example Main Program

!     .. Use Statements ..
      Use nag_library, Only: e04nkf, e04nlf, e04nmf, nag_wp, x04abf, x04acf
      Use e04nlfe_mod, Only: iset, nin, ninopt, nout, qphx
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Character (*), Parameter         :: fname = 'e04nlfe.opt'
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: obj, sinf
      Integer                          :: i, icol, ifail, inform, iobj, jcol,  &
                                          leniz, lenz, m, miniz, minz, mode,   &
                                          n, ncolh, ninf, nname, nnz, ns,      &
                                          outchn
      Character (1)                    :: start
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: a(:), bl(:), bu(:), clamda(:),       &
                                          xs(:), z(:)
      Integer, Allocatable             :: ha(:), istate(:), iz(:), ka(:)
      Character (8), Allocatable       :: crname(:)
      Character (8)                    :: names(5)
!     .. Executable Statements ..
      Write (nout,99997) 'E04NLF Example Program Results'
      Flush (nout)

!     Skip heading in data file.
      Read (nin,*)

      Read (nin,*) n, m
      Read (nin,*) nnz, iobj, ncolh, start, nname

      Allocate (ha(nnz),ka(n+1),istate(n+m),a(nnz),bl(n+m),bu(n+m),xs(n+m),    &
        clamda(n+m),crname(nname))

      Read (nin,*) names(1:5)
      Read (nin,*) crname(1:nname)

!     Read the matrix A from data file. Set up KA.

      jcol = 1
      ka(jcol) = 1

      Do i = 1, nnz

!       Element ( HA( I ), ICOL ) is stored in A( I ).

        Read (nin,*) a(i), ha(i), icol

        If (icol<jcol) Then

!         Elements not ordered by increasing column index.

          Write (nout,*)
          Flush (nout)
          Write (nout,99998) 'Element in column', icol,                        &
            ' found after element in column', jcol, '. Problem', ' abandoned.'
          Flush (nout)
          Go To 100
        Else If (icol==jcol+1) Then

!         Index in A of the start of the ICOL-th column equals I.

          ka(icol) = i
          jcol = icol
        Else If (icol>jcol+1) Then

!         Index in A of the start of the ICOL-th column equals I,
!         but columns JCOL+1,JCOL+2,...,ICOL-1 are empty. Set the
!         corresponding elements of KA to I.

          ka((jcol+1):icol) = i
          jcol = icol
        End If

      End Do

      ka(n+1) = nnz + 1

!     Columns N,N-1,...,ICOL+1 are empty. Set the corresponding
!     elements of KA accordingly.

      Do i = n, icol + 1, -1
        ka(i) = ka(i+1)
      End Do

      Read (nin,*) bl(1:(n+m))
      Read (nin,*) bu(1:(n+m))

      If (start=='C') Then
        Read (nin,*) istate(1:n)
      Else If (start=='W') Then
        Read (nin,*) istate(1:(n+m))
      End If

      Read (nin,*) xs(1:n)

!     Set the unit number for advisory messages to OUTCHN.

      outchn = nout
      Call x04abf(iset,outchn)

!     Set three options using E04NMF.

      Call e04nmf(' Check Frequency = 10 ')

      Call e04nmf(' Crash Tolerance = 0.05 ')

      Call e04nmf(' Infinite Bound Size = 1.0E+25 ')

!     Open the options file for reading

      mode = 0

      ifail = 0
      Call x04acf(ninopt,fname,mode,ifail)

!     Read the options file for the remaining options.

      Call e04nlf(ninopt,inform)

      If (inform/=0) Then
        Write (nout,99999) 'E04NLF terminated with INFORM = ', inform
        Flush (nout)
        Go To 100
      End If

!     Solve the QP problem.
!     First call is a workspace query

      leniz = 1
      lenz = 1
      Allocate (iz(leniz),z(lenz))

      ifail = 1
      Call e04nkf(n,m,nnz,iobj,ncolh,qphx,a,ha,ka,bl,bu,start,names,nname,     &
        crname,ns,xs,istate,miniz,minz,ninf,sinf,obj,clamda,iz,leniz,z,lenz,   &
        ifail)

      If (ifail/=0 .And. ifail/=12 .And. ifail/=13) Then
        Write (nout,99999) 'Query call to E04NKF failed with IFAIL =', ifail
        Go To 100
      End If

      Deallocate (iz,z)

      lenz = minz
      leniz = miniz
      Allocate (iz(leniz),z(lenz))

      ifail = 0
      Call e04nkf(n,m,nnz,iobj,ncolh,qphx,a,ha,ka,bl,bu,start,names,nname,     &
        crname,ns,xs,istate,miniz,minz,ninf,sinf,obj,clamda,iz,leniz,z,lenz,   &
        ifail)

100   Continue

99999 Format (1X,A,I5)
99998 Format (1X,A,I5,A,I5,A,A)
99997 Format (1X,A)
    End Program e04nlfe


e04nqfe.f90

!   E04NQF Example Program Text
!   Mark 26 Release. NAG Copyright 2016.

    Module e04nqfe_mod

!     E04NQF Example Program Module:
!            Parameters and User-defined Routines

!     .. Use Statements ..
      Use nag_library, Only: nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Accessibility Statements ..
      Private
      Public                           :: qphx
!     .. Parameters ..
      Integer, Parameter, Public       :: lencw = 600, leniw = 600,            &
                                          lenrw = 600, nin = 5, nout = 6
    Contains
      Subroutine qphx(ncolh,x,hx,nstate,cuser,iuser,ruser)
!       Routine to compute H*x. (In this version of QPHX, the Hessian
!       matrix H is not referenced explicitly.)

!       .. Scalar Arguments ..
        Integer, Intent (In)           :: ncolh, nstate
!       .. Array Arguments ..
        Real (Kind=nag_wp), Intent (Out) :: hx(ncolh)
        Real (Kind=nag_wp), Intent (Inout) :: ruser(*)
        Real (Kind=nag_wp), Intent (In) :: x(ncolh)
        Integer, Intent (Inout)        :: iuser(*)
        Character (8), Intent (Inout)  :: cuser(*)
!       .. Executable Statements ..
        hx(1) = 2.0E0_nag_wp*x(1)
        hx(2) = 2.0E0_nag_wp*x(2)
        hx(3) = 2.0E0_nag_wp*(x(3)+x(4))
        hx(4) = hx(3)
        hx(5) = 2.0E0_nag_wp*x(5)
        hx(6) = 2.0E0_nag_wp*(x(6)+x(7))
        hx(7) = hx(6)

        Return

      End Subroutine qphx
    End Module e04nqfe_mod
    Program e04nqfe

!     E04NQF Example Main Program

!     .. Use Statements ..
      Use nag_library, Only: e04npf, e04nqf, e04ntf, nag_wp
      Use e04nqfe_mod, Only: lencw, leniw, lenrw, nin, nout, qphx
!     .. Implicit None Statement ..
      Implicit None
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: obj, objadd, sinf
      Integer                          :: i, icol, ifail, iobj, jcol, lenc, m, &
                                          n, ncolh, ne, ninf, nname, ns
      Logical                          :: verbose_output
      Character (8)                    :: prob
      Character (1)                    :: start
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: acol(:), bl(:), bu(:), c(:), pi(:),  &
                                          rc(:), x(:)
      Real (Kind=nag_wp)               :: ruser(1), rw(lenrw)
      Integer, Allocatable             :: helast(:), hs(:), inda(:), loca(:)
      Integer                          :: iuser(1), iw(leniw)
      Character (8)                    :: cuser(1), cw(lencw)
      Character (8), Allocatable       :: names(:)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: max
!     .. Executable Statements ..
      Write (nout,*) 'E04NQF Example Program Results'

!     Skip heading in data file.
      Read (nin,*)

      Read (nin,*) n, m
      Read (nin,*) ne, iobj, ncolh, start, nname
      Allocate (inda(ne),loca(n+1),helast(n+m),hs(n+m),acol(ne),bl(n+m),       &
        bu(n+m),x(n+m),pi(m),rc(n+m),names(nname))

      Read (nin,*) names(1:nname)

!     Read the matrix ACOL from data file. Set up LOCA.

      jcol = 1
      loca(jcol) = 1

      Do i = 1, ne

!       Element ( INDA( I ), ICOL ) is stored in ACOL( I ).

        Read (nin,*) acol(i), inda(i), icol

        If (icol<jcol) Then

!         Elements not ordered by increasing column index.

          Write (nout,99998) 'Element in column', icol,                        &
            ' found after element in column', jcol, '. Problem', ' abandoned.'
          Go To 100
        Else If (icol==jcol+1) Then

!         Index in ACOL of the start of the ICOL-th column equals I.

          loca(icol) = i
          jcol = icol
        Else If (icol>jcol+1) Then

!         Index in ACOL of the start of the ICOL-th column equals I,
!         but columns JCOL+1,JCOL+2,...,ICOL-1 are empty. Set the
!         corresponding elements of LOCA to I.

          loca((jcol+1):icol) = i
          jcol = icol
        End If

      End Do

      loca(n+1) = ne + 1

!     Columns N,N-1,...,ICOL+1 are empty. Set the corresponding
!     elements of LOCA accordingly.

      Do i = n, icol + 1, -1
        loca(i) = loca(i+1)
      End Do

      Read (nin,*) bl(1:(n+m))
      Read (nin,*) bu(1:(n+m))

      If (start=='C') Then
        Read (nin,*) hs(1:n)
      Else If (start=='W') Then
        Read (nin,*) hs(1:(n+m))
      End If

      Read (nin,*) x(1:n)

      Write (nout,99999) n, m

!     Call E04NPF to initialize E04NQF.

      ifail = 0
      Call e04npf(cw,lencw,iw,leniw,rw,lenrw,ifail)

!     Set this to .True. to cause e04nqf to produce intermediate
!     progress output
      verbose_output = .False.

      If (verbose_output) Then
!       By default e04nqf does not print monitoring
!       information. Set the print file unit or the summary
!       file unit to get information.
        ifail = 0
        Call e04ntf('Print file',nout,cw,iw,rw,ifail)
      End If

!     We have no explicit objective vector so set LENC = 0; the
!     objective vector is stored in row IOBJ of ACOL.

      lenc = 0
      Allocate (c(max(1,lenc)))

      objadd = 0.0E0_nag_wp
      prob = ' '

!     Do not allow any elastic variables (i.e. they cannot be
!     infeasible). If we'd set optional argument "Elastic mode" to 0,
!     we wouldn't need to set the individual elements of array HELAST.

      helast(1:(n+m)) = 0

!     Solve the QP problem.

      ifail = 0
      Call e04nqf(start,qphx,m,n,ne,nname,lenc,ncolh,iobj,objadd,prob,acol,    &
        inda,loca,bl,bu,c,names,helast,hs,x,pi,rc,ns,ninf,sinf,obj,cw,lencw,   &
        iw,leniw,rw,lenrw,cuser,iuser,ruser,ifail)

      Write (nout,*)
      Write (nout,99997) obj
      Write (nout,99996) x(1:n)

100   Continue

99999 Format (1X,/,1X,'QP problem contains ',I3,' variables and ',I3,          &
        ' linear constraints')
99998 Format (1X,A,I5,A,I5,A,A)
99997 Format (1X,'Final objective value = ',1P,E11.3)
99996 Format (1X,'Optimal X = ',7F9.2)

    End Program e04nqfe


e04nrfe.f90

!   E04NRF Example Program Text
!   Mark 26 Release. NAG Copyright 2016.

    Module e04nrfe_mod

!     E04NRF Example Program Module:
!            Parameters and User-defined Routines

!     .. Use Statements ..
      Use nag_library, Only: nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Accessibility Statements ..
      Private
      Public                           :: qphx
!     .. Parameters ..
      Integer, Parameter, Public       :: lencw = 600, leniw = 600,            &
                                          lenrw = 600, nin = 5, ninopt = 7,    &
                                          nout = 6
    Contains
      Subroutine qphx(ncolh,x,hx,nstate,cuser,iuser,ruser)
!       Routine to compute H*x. (In this version of QPHX, the Hessian
!       matrix H is not referenced explicitly.)

!       .. Scalar Arguments ..
        Integer, Intent (In)           :: ncolh, nstate
!       .. Array Arguments ..
        Real (Kind=nag_wp), Intent (Out) :: hx(ncolh)
        Real (Kind=nag_wp), Intent (Inout) :: ruser(*)
        Real (Kind=nag_wp), Intent (In) :: x(ncolh)
        Integer, Intent (Inout)        :: iuser(*)
        Character (8), Intent (Inout)  :: cuser(*)
!       .. Executable Statements ..
        hx(1) = 2.0E0_nag_wp*x(1)
        hx(2) = 2.0E0_nag_wp*x(2)
        hx(3) = 2.0E0_nag_wp*(x(3)+x(4))
        hx(4) = hx(3)
        hx(5) = 2.0E0_nag_wp*x(5)
        hx(6) = 2.0E0_nag_wp*(x(6)+x(7))
        hx(7) = hx(6)

        Return

      End Subroutine qphx
    End Module e04nrfe_mod
    Program e04nrfe

!     E04NRF Example Main Program

!     .. Use Statements ..
      Use nag_library, Only: e04npf, e04nqf, e04nrf, e04nsf, e04ntf, e04nuf,   &
                             e04nxf, e04nyf, nag_wp, x04acf
      Use e04nrfe_mod, Only: lencw, leniw, lenrw, nin, ninopt, nout, qphx
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Character (*), Parameter         :: fname = 'e04nrfe.opt'
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: bndinf, featol, obj, objadd, sinf
      Integer                          :: elmode, i, icol, ifail, iobj, jcol,  &
                                          lenc, m, mode, n, ncolh, ne, ninf,   &
                                          nname, ns
      Logical                          :: verbose_output
      Character (8)                    :: prob
      Character (1)                    :: start
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: acol(:), bl(:), bu(:), c(:), pi(:),  &
                                          rc(:), x(:)
      Real (Kind=nag_wp)               :: ruser(1), rw(lenrw)
      Integer, Allocatable             :: helast(:), hs(:), inda(:), loca(:)
      Integer                          :: iuser(1), iw(leniw)
      Character (8)                    :: cuser(1), cw(lencw)
      Character (8), Allocatable       :: names(:)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: max
!     .. Executable Statements ..
      Write (nout,*) 'E04NRF Example Program Results'

!     This program demonstrates the use of routines to set and
!     get values of optional parameters associated with E04NQF.

!     Skip heading in data file.
      Read (nin,*)

      Read (nin,*) n, m
      Read (nin,*) ne, iobj, ncolh, start, nname

      Allocate (inda(ne),loca(n+1),helast(n+m),hs(n+m),acol(ne),bl(n+m),       &
        bu(n+m),x(n+m),pi(m),rc(n+m),names(nname))

      Read (nin,*) names(1:nname)

!     Read the matrix ACOL from data file. Set up LOCA.

      jcol = 1
      loca(jcol) = 1

      Do i = 1, ne

!       Element ( INDA( I ), ICOL ) is stored in ACOL( I ).

        Read (nin,*) acol(i), inda(i), icol

        If (icol<jcol) Then

!         Elements not ordered by increasing column index.

          Write (nout,99999) 'Element in column', icol,                        &
            ' found after element in column', jcol, '. Problem', ' abandoned.'
          Go To 100
        Else If (icol==jcol+1) Then

!         Index in ACOL of the start of the ICOL-th column equals I.

          loca(icol) = i
          jcol = icol
        Else If (icol>jcol+1) Then

!         Index in ACOL of the start of the ICOL-th column equals I,
!         but columns JCOL+1,JCOL+2,...,ICOL-1 are empty. Set the
!         corresponding elements of LOCA to I.

          loca((jcol+1):icol) = i
          jcol = icol
        End If

      End Do

      loca(n+1) = ne + 1

      If (n>icol) Then

!       Columns N,N-1,...,ICOL+1 are empty. Set the corresponding
!       elements of LOCA accordingly.

        Do i = n, icol + 1, -1
          loca(i) = loca(i+1)
        End Do

      End If

      Read (nin,*) bl(1:(n+m))
      Read (nin,*) bu(1:(n+m))

      If (start=='C') Then
        Read (nin,*) hs(1:n)
      Else If (start=='W') Then
        Read (nin,*) hs(1:(n+m))
      End If

      Read (nin,*) x(1:n)

!     We have no explicit objective vector so set LENC = 0; the
!     objective vector is stored in row IOBJ of ACOL.

      lenc = 0
      Allocate (c(max(1,lenc)))

      objadd = 0.0E0_nag_wp
      prob = ' '

      Write (nout,99998) n, m

!     Call E04NPF to initialize E04NQF.

      ifail = 0
      Call e04npf(cw,lencw,iw,leniw,rw,lenrw,ifail)

!     Set this to .True. to cause e04nqf to produce intermediate
!     progress output
      verbose_output = .False.

      If (verbose_output) Then
!       By default E04NQF does not print monitoring information.
!       Use E04NTF to set the integer-valued option 'Print file'
!       unit number to get information.
        ifail = 0
        Call e04ntf('Print file',nout,cw,iw,rw,ifail)
      End If

!     Open the options file for reading

      mode = 0

      ifail = 0
      Call x04acf(ninopt,fname,mode,ifail)

!     Use E04NRF to read the options file for the remaining
!     options

      ifail = 0
      Call e04nrf(ninopt,cw,iw,rw,ifail)

      Write (nout,*)

!     Use E04NXF to find the value of integer-valued option
!     'Elastic mode'.

      ifail = 0
      Call e04nxf('Elastic mode',elmode,cw,iw,rw,ifail)

      Write (nout,99997) elmode

!     If Elastic Mode is nonzero, set HELAST.

      If (elmode/=0) Then
        helast(1:(n+m)) = 0
      End If

!     Use E04NUF to set the value of real-valued option
!     'Infinite bound size'.

      bndinf = 1.0E10_nag_wp

      ifail = 0
      Call e04nuf('Infinite bound size',bndinf,cw,iw,rw,ifail)

!     Use E04NYF to find the value of real-valued option
!     'Feasibility tolerance'.

      ifail = 0
      Call e04nyf('Feasibility tolerance',featol,cw,iw,rw,ifail)

      Write (nout,99996) featol

!     Use E04NSF to set the option 'Iterations limit'.

      ifail = 0
      Call e04nsf('Iterations limit 50',cw,iw,rw,ifail)

!     Solve the QP problem.

      ifail = 0
      Call e04nqf(start,qphx,m,n,ne,nname,lenc,ncolh,iobj,objadd,prob,acol,    &
        inda,loca,bl,bu,c,names,helast,hs,x,pi,rc,ns,ninf,sinf,obj,cw,lencw,   &
        iw,leniw,rw,lenrw,cuser,iuser,ruser,ifail)

      Write (nout,*)
      Write (nout,99995) obj
      Write (nout,99994) x(1:n)

100   Continue

99999 Format (1X,A,I5,A,I5,A,A)
99998 Format (1X,/,1X,'QP problem contains ',I3,' variables and ',I3,          &
        ' linear constraints')
99997 Format (1X,'Option ''Elastic mode'' has the value ',I3,'.')
99996 Format (1X,'Option ''Feasibility tolerance'' has the value ',1P,E11.3,   &
        '.')
99995 Format (1X,'Final objective value = ',1P,E11.3)
99994 Format (1X,'Optimal X = ',7F9.2)
    End Program e04nrfe


e04pcfe.f90

    Program e04pcfe
!     E04PCF Example Program Text
!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: e04pcf, nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Real (Kind=nag_wp), Parameter    :: tol = 0.0_nag_wp
      Integer, Parameter               :: itype = 1, nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: rnorm
      Integer                          :: i, ifail, lda, lw, m, n, nfree
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: a(:,:), b(:), bl(:), bu(:), w(:),    &
                                          x(:)
      Integer, Allocatable             :: indx(:)
!     .. Executable Statements ..
      Write (nout,*) 'E04PCF Example Program Results'
      Write (nout,*)
!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) m, n
      lda = m
      lw = n
      Allocate (a(lda,n),b(m),w(lw),bl(n),bu(n),x(n))
      Allocate (indx(n))
      Read (nin,*)(a(i,1:n),i=1,m)
      Read (nin,*) b(1:m)
      Read (nin,*) bl(1:n)
      Read (nin,*) bu(1:n)
      ifail = 0
      Call e04pcf(itype,m,n,a,lda,b,bl,bu,tol,x,rnorm,nfree,w,indx,ifail)

      Write (nout,99999) 'Solution vector', x(1:n)
      Write (nout,*)
      Write (nout,99999) 'Dual Solution', w(1:n)
      Write (nout,*)
      Write (nout,99998) 'Residual', rnorm

99999 Format (1X,A,/,1X,8F9.4)
99998 Format (1X,A,1X,1F9.4)
    End Program e04pcfe


e04rdfe.f90

    Program e04rdfe

!     E04RDF Example Program Text
!     Mark 26 Release. NAG Copyright 2016.

!     Load a linear semidefinite programming problem from a sparse SDPA
!     file, formulate the problem via a handle, pass it to the solver
!     and print both primal and dual variables.

!     .. Use Statements ..
      Use nag_library, Only: e04raf, e04rdf, e04ref, e04rnf, e04ryf, e04rzf,   &
                             e04svf, e04zmf, nag_wp, x04acf, x04adf, x04ccf
      Use, Intrinsic                   :: iso_c_binding, Only: c_ptr
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: filelst = 0, infile = 42, nout = 6
      Character (*), Parameter         :: fname_default = 'e04rdfe.opt'
!     .. Local Scalars ..
      Type (c_ptr)                     :: handle
      Integer                          :: idblk, idx, ifail, ifail_e04rd,      &
                                          inform, k, maxnblk, maxnnz, maxnvar, &
                                          nblk, nnz, nnzu, nnzua, nnzuc,       &
                                          ntests, nvar
      Character (256)                  :: fname
      Character (60)                   :: title
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: a(:), cvec(:), u(:), ua(:), uc(:),   &
                                          x(:)
      Real (Kind=nag_wp)               :: rinfo(32), stats(32)
      Integer, Allocatable             :: blksizea(:), icola(:), irowa(:),     &
                                          nnza(:)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: command_argument_count,              &
                                          get_command_argument, sum, trim
!     .. Executable Statements ..
      Continue

      Write (nout,*) 'E04RDF Example Program Results'
      Write (nout,*)

!     Use the first command line argument as the filename or
!     choose default hard-coded filename in 'fname_default'.
      ntests = command_argument_count()
      If (ntests==0) Then
!       Assume the default filename.
        fname = fname_default
      Else
        Call get_command_argument(1,fname)
      End If

      Write (nout,*) 'Reading SDPA file: ', trim(fname)
      Flush (nout)

!     Open the input file.
      ifail = 0
      Call x04acf(infile,fname,0,ifail)

!     Go through the file and find the dimension of the problem.
!     Unless the file format is wrong, the routine should finish
!     with IFAIL = 1 (not enough space).
      maxnvar = 0
      maxnblk = 0
      maxnnz = 0
      Allocate (cvec(maxnvar),nnza(maxnvar+1),irowa(maxnnz),icola(maxnnz),     &
        a(maxnnz),blksizea(maxnblk))
      ifail_e04rd = -1
      Call e04rdf(infile,maxnvar,maxnblk,maxnnz,filelst,nvar,nblk,nnz,cvec,    &
        nnza,irowa,icola,a,blksizea,ifail_e04rd)
      Deallocate (cvec,nnza,irowa,icola,a,blksizea)

!     Close the file, it will need to be reopened later.
      ifail = 0
      Call x04adf(infile,ifail)

      If (ifail_e04rd/=1) Then
!       Possible problem with formatting, etc.
        Write (nout,99999) 'Reading the SDPA file failed with IFAIL = ', ifail
99999   Format (1X,A,I3)
        Write (nout,*) 'Terminating the example program.'
        Go To 100
      End If

!     Allocate the right size of arrays for the data.
      Write (nout,*) 'Allocating space for the problem.'
      Write (nout,Fmt=99998) 'NVAR = ', nvar
      Write (nout,Fmt=99998) 'NBLK = ', nblk
      Write (nout,Fmt=99998) 'NNZ  = ', nnz
99998 Format (6X,A,I7)
      Flush (nout)

      maxnvar = nvar
      maxnblk = nblk
      maxnnz = nnz

      Allocate (cvec(maxnvar),nnza(maxnvar+1),irowa(maxnnz),icola(maxnnz),     &
        a(maxnnz),blksizea(maxnblk))

!     Reopen the file.
      ifail = 0
      Call x04acf(infile,fname,0,ifail)

!     Read the problem data, there should be enough space this time.
      ifail = 0
      Call e04rdf(infile,maxnvar,maxnblk,maxnnz,filelst,nvar,nblk,nnz,cvec,    &
        nnza,irowa,icola,a,blksizea,ifail)

!     Close the file.
      ifail = 0
      Call x04adf(infile,ifail)

!     Problem was successfully decoded.
      Write (nout,*)                                                           &
        'Linear SDP problem was read, start formulating the problem'
      Flush (nout)

!     Initialize the handle of the problem.
      ifail = 0
      Call e04raf(handle,nvar,ifail)

!     Add the linear objective function to the formulation.
      ifail = 0
      Call e04ref(handle,nvar,cvec,ifail)

!     Add all linear matrix constraints to the formulation.
      idblk = 0
      ifail = 0
      Call e04rnf(handle,nvar,sum(blksizea(1:nblk)),nnza,nnz,irowa,icola,a,    &
        nblk,blksizea,idblk,ifail)

      Write (nout,*) 'The problem formulation in a handle is completed.'
      Write (nout,*)
      Flush (nout)

!     Print overview of the handle.
      ifail = 0
      Call e04ryf(handle,nout,'Overview',ifail)

!     Set optional arguments.
      ifail = 0
      Call e04zmf(handle,'DIMACS Measures = Check',ifail)
      ifail = 0
      Call e04zmf(handle,'Initial X = Automatic',ifail)

!     Compute memory needed for primal & dual variables.

!     There are no box constraints or linear constraints set
!     by E04RHF or E04RJF, neither second order cone constraints.
      nnzu = 0
      nnzuc = 0

!     Count size of the matrix multipliers, stored as packed
!     triangle respecting the block structure.
      nnzua = 0
      Do k = 1, nblk
        nnzua = nnzua + blksizea(k)*(blksizea(k)+1)/2
      End Do

      Allocate (x(nvar),ua(nnzua),u(nnzu),uc(nnzuc))

!     Call the solver.
      ifail = 0
      Call e04svf(handle,nvar,x,nnzu,u,nnzuc,uc,nnzua,ua,rinfo,stats,inform,   &
        ifail)

!     Print results.

      Write (nout,*)
      Write (nout,*) 'Optimal solution:'
      Write (nout,99997) x(1:nvar)
99997 Format (1X,'X = ',2F9.2)
      Flush (nout)

!     Print packed lower triangles of the Lagrangian multipliers.
      idx = 1
      Do k = 1, nblk
        Write (title,99996) 'Lagrangian multiplier for A_', k
99996   Format (A,I0)
        nnz = blksizea(k)*(blksizea(k)+1)/2
        ifail = 0
        Call x04ccf('Lower','N',blksizea(k),ua(idx:idx+nnz-1),title,ifail)
        idx = idx + nnz
      End Do

!     Deallocate memory within the handle.
      ifail = 0
      Call e04rzf(handle,ifail)

100   Continue
    End Program e04rdfe


e04rffe.f90

    Program e04rffe

!     E04RFF Example Program Text

!     Compute the nearest correlation matrix in Frobenius norm
!     using nonlinear semidefinite programming. By default,
!     preserve the nonzero structure of the input matrix
!     (preserve_structure = .True.).

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: e04raf, e04rff, e04rnf, e04rzf, e04svf, e04zmf,   &
                             nag_wp, x04caf
      Use, Intrinsic                   :: iso_c_binding, Only: c_null_ptr,     &
                                          c_ptr
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
      Logical, Parameter               :: preserve_structure = .True.
!     .. Local Scalars ..
      Type (c_ptr)                     :: h
      Integer                          :: dima, i, idblk, idx, ifail, inform,  &
                                          j, n, nblk, nnzasum, nnzc, nnzh,     &
                                          nnzu, nnzua, nnzuc, nvar
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: a(:), g(:,:), hmat(:), x(:)
      Real (Kind=nag_wp)               :: rdummy(1), rinfo(32), stats(32)
      Integer, Allocatable             :: blksizea(:), icola(:), icolh(:),     &
                                          irowa(:), irowh(:), nnza(:)
      Integer                          :: idummy(1)
!     .. Executable Statements ..
      Continue

      Write (nout,*) 'E04RFF Example Program Results'
      Write (nout,*)
      Flush (nout)

!     Skip heading in data file.
      Read (nin,*)

!     Read in the problem size.
      Read (nin,*) n

      Allocate (g(n,n))

!     Read in the matrix G.
      Read (nin,*)(g(i,1:n),i=1,n)

!     Symmetrize G:  G = (G + G')/2
      Do j = 2, n
        Do i = 1, j - 1
          g(i,j) = (g(i,j)+g(j,i))/2.0_nag_wp
          g(j,i) = g(i,j)
        End Do
      End Do

!     Initialize handle.
      h = c_null_ptr

!     There are as many variables as nonzeros above the main diagonal in
!     the input matrix. The variables are corrections of these elements.
      nvar = 0
      Do j = 2, n
        Do i = 1, j - 1
          If (.Not. preserve_structure .Or. g(i,j)/=0.0_nag_wp) Then
            nvar = nvar + 1
          End If
        End Do
      End Do
      Allocate (x(nvar))

!     Initialize an empty problem handle with NVAR variables.
      ifail = 0
      Call e04raf(h,nvar,ifail)

!     Set up the objective - minimize Frobenius norm of the corrections.
!     Our variables are stored as a vector thus, just minimize
!     sum of squares of the corrections --> H is identity matrix, c = 0.
      nnzc = 0
      nnzh = nvar
      Allocate (irowh(nnzh),icolh(nnzh),hmat(nnzh))
      Do i = 1, nvar
        irowh(i) = i
        icolh(i) = i
        hmat(i) = 1.0_nag_wp
      End Do

!     Add the quadratic objective to the handle.
      ifail = 0
      Call e04rff(h,nnzc,idummy,rdummy,nnzh,irowh,icolh,hmat,ifail)

!     Construct linear matrix inequality to request that
!     matrix G with corrections X is positive semidefinite.
!     (Don't forget the sign at A_0!)

!     How many nonzeros do we need? Full triangle for A_0 and
!     one nonzero element for each A_i.
      nnzasum = n*(n+1)/2 + nvar

      Allocate (nnza(nvar+1),irowa(nnzasum),icola(nnzasum),a(nnzasum))
      nnza(1) = n*(n+1)/2
      nnza(2:nvar+1) = 1

!     Copy G to A_0, only upper triangle with different sign (because -A_0)
!     and set the diagonal to 1.0 as that's what we want independently
!     of what was in G.
      idx = 1
      Do j = 1, n
        Do i = 1, j - 1
          irowa(idx) = i
          icola(idx) = j
          a(idx) = -g(i,j)
          idx = idx + 1
        End Do
!       Unit diagonal.
        irowa(idx) = j
        icola(idx) = j
        a(idx) = -1.0_nag_wp
        idx = idx + 1
      End Do
!     A_i has just one nonzero - it binds x_i with its position as
!     a correction.
      Do j = 2, n
        Do i = 1, j - 1
          If (.Not. preserve_structure .Or. g(i,j)/=0.0_nag_wp) Then
            irowa(idx) = i
            icola(idx) = j
            a(idx) = 1.0_nag_wp
            idx = idx + 1
          End If
        End Do
      End Do

!     Just one matrix inequality of the dimension of the original matrix.
      nblk = 1
      Allocate (blksizea(nblk))
      dima = n
      blksizea(:) = (/dima/)

!     Add the constraint to the problem formulation.
      idblk = 0
      ifail = 0
      Call e04rnf(h,nvar,dima,nnza,nnzasum,irowa,icola,a,nblk,blksizea,idblk,  &
        ifail)

!     Set optional arguments of the solver.
      ifail = 0
      Call e04zmf(h,'Print Options = No',ifail)
      ifail = 0
      Call e04zmf(h,'Initial X = Automatic',ifail)

!     Pass the handle to the solver, we are not interested in
!     Lagrangian multipliers.
      nnzu = 0
      nnzuc = 0
      nnzua = 0
      ifail = 0
      Call e04svf(h,nvar,x,nnzu,rdummy,nnzuc,rdummy,nnzua,rdummy,rinfo,stats,  &
        inform,ifail)

!     Destroy the handle.
      ifail = 0
      Call e04rzf(h,ifail)

!     Form the new nearest correlation matrix as the sum
!     of G and the correction X.
      idx = 1
      Do j = 1, n
        Do i = 1, j - 1
          If (.Not. preserve_structure .Or. g(i,j)/=0.0_nag_wp) Then
            g(i,j) = g(i,j) + x(idx)
            idx = idx + 1
          End If
        End Do
        g(j,j) = 1.0_nag_wp
      End Do

!     Print the matrix.
      ifail = 0
      Call x04caf('Upper','N',n,n,g,n,'Nearest Correlation Matrix',ifail)

    End Program e04rffe


e04rhfe.f90

    Program e04rhfe

!     E04RHF Example Program Text
!     Mark 26 Release. NAG Copyright 2016.

!     Matrix completion problem (rank minimization) solved approximately
!     by SDP via nuclear norm minimization formulated as:
!        min    trace(X1) + trace(X2)
!        s.t.   [ X1, Y; Y', X2 ] >=0
!               0 <= Y_ij <= 1

!     .. Use Statements ..
      Use nag_library, Only: e04raf, e04rff, e04rhf, e04rnf, e04rzf, e04svf,   &
                             e04zmf, f08kbf, nag_wp, x04cbf
      Use, Intrinsic                   :: iso_c_binding, Only: c_null_ptr,     &
                                          c_ptr
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Real (Kind=nag_wp), Parameter    :: stol = 1E-5_nag_wp
      Real (Kind=nag_wp), Parameter    :: time_limit = 120.0_nag_wp
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Type (c_ptr)                     :: h
      Integer                          :: dima, i, idblk, idx, idxobj, idxx,   &
                                          ifail, info, inform, j, lwork, m, n, &
                                          nblk, nnz, nnzasum, nnzc, nnzh,      &
                                          nnzu, nnzua, nnzuc, nvar, rank
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: a(:), bl(:), bu(:), c(:), s(:),      &
                                          work(:), x(:), y(:,:)
      Real (Kind=nag_wp)               :: rdummy(1), rinfo(32), stats(32)
      Integer, Allocatable             :: blksizea(:), icola(:), idxc(:),      &
                                          irowa(:), nnza(:)
      Integer                          :: idummy(1)
      Character (1)                    :: cdummy(1)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: int, max, min, sum
!     .. Executable Statements ..
      Continue

      Write (nout,*) 'E04RHF Example Program Results'
      Write (nout,*)
      Flush (nout)

!     Skip heading in data file.
      Read (nin,*)

!     Read in the problem size and allocate space for the input data.
      Read (nin,*) m, n
      Allocate (y(m,n))

!     Read in the matrix Y.
      Read (nin,*)(y(i,1:n),i=1,m)

!     Count the number of specified elements (i.e., nonnegative)
      nnz = 0
      Do i = 1, m
        Do j = 1, n
          If (y(i,j)>=0.0_nag_wp) Then
            nnz = nnz + 1
          End If
        End Do
      End Do

!     Initialize handle.
      h = c_null_ptr

!     There are as many variables as missing entries in the Y matrix
!     plus two full symmetric matrices m x m and n x n.
      nvar = m*(m+1)/2 + n*(n+1)/2 + m*n - nnz
      Allocate (x(nvar),bl(nvar),bu(nvar))

!     Initialize an empty problem handle with NVAR variables.
      ifail = 0
      Call e04raf(h,nvar,ifail)

!     Create bounds for the missing entries in Y matrix to be between 0 and 1
      bl(:) = -1E+20_nag_wp
      bu(:) = 1E+20_nag_wp
      bl(m*(m+1)/2+n*(n+1)/2+1:nvar) = 0.0_nag_wp
      bu(m*(m+1)/2+n*(n+1)/2+1:nvar) = 1.0_nag_wp
      ifail = 0
      Call e04rhf(h,nvar,bl,bu,ifail)

!     Allocate space for the objective - minimize trace of the matrix
!     constraint. There is no quadratic part in the objective.
      nnzc = m + n
      nnzh = 0
      Allocate (idxc(nnzc),c(nnzc))

!     Construct linear matrix inequality to request that
!     [ X1, Y; Y', X2] is positive semidefinite.

!     How many nonzeros do we need? As many as number of variables
!     and the number of specified elements together.
      nnzasum = m*(m+1)/2 + n*(n+1)/2 + m*n

      Allocate (nnza(nvar+1),irowa(nnzasum),icola(nnzasum),a(nnzasum))
      nnza(1) = nnz
      nnza(2:nvar+1) = 1

!     Copy Y to the upper block of A_0 with the different sign
!     (because of the sign at A_0!)
!     (upper triangle)
      idx = 1
      Do i = 1, m
        Do j = 1, n
          If (y(i,j)>=0.0_nag_wp) Then
            irowa(idx) = i
            icola(idx) = m + j
            a(idx) = -y(i,j)
            idx = idx + 1
          End If
        End Do
      End Do
!     One matrix for each variable, A_i has just one nonzero - it binds
!     x_i with its position in the matrix constraint. Set also the objective.
!     1,1 - block, X1 matrix (mxm)
      idxobj = 1
      idxx = 1
      Do i = 1, m
!       the next element is diagonal ==> part of the objective as a trace()
        idxc(idxobj) = idxx
        c(idxobj) = 1.0_nag_wp
        idxobj = idxobj + 1
        Do j = i, m
          irowa(idx) = i
          icola(idx) = j
          a(idx) = 1.0_nag_wp
          idx = idx + 1
          idxx = idxx + 1
        End Do
      End Do
!     2,2 - block, X2 matrix (nxn)
      Do i = 1, n
!       the next element is diagonal ==> part of the objective as a trace()
        idxc(idxobj) = idxx
        c(idxobj) = 1.0_nag_wp
        idxobj = idxobj + 1
        Do j = i, n
          irowa(idx) = m + i
          icola(idx) = m + j
          a(idx) = 1.0_nag_wp
          idx = idx + 1
          idxx = idxx + 1
        End Do
      End Do
!     1,2 - block, missing element in Y we are after
      Do i = 1, m
        Do j = 1, n
          If (y(i,j)<0.0_nag_wp) Then
            irowa(idx) = i
            icola(idx) = m + j
            a(idx) = 1.0_nag_wp
            idx = idx + 1
          End If
        End Do
      End Do

!     Add the sparse linear objective to the handle.
      ifail = 0
      Call e04rff(h,nnzc,idxc,c,nnzh,idummy,idummy,rdummy,ifail)

!     Just one matrix inequality of the dimension of the extended matrix.
      nblk = 1
      Allocate (blksizea(nblk))
      dima = m + n
      blksizea(:) = (/dima/)

!     Add the constraint to the problem formulation.
      idblk = 0
      ifail = 0
      Call e04rnf(h,nvar,dima,nnza,nnzasum,irowa,icola,a,nblk,blksizea,idblk,  &
        ifail)

!     Set optional arguments of the solver.
!     Completely turn off printing, allow timing and
!     turn on the monitor mode to stop every iteration.
      ifail = 0
      Call e04zmf(h,'Print File = -1',ifail)
      ifail = 0
      Call e04zmf(h,'Stats Time = Yes',ifail)
      ifail = 0
      Call e04zmf(h,'Monitor Frequency = 1',ifail)
      ifail = 0
      Call e04zmf(h,'Initial X = Automatic',ifail)
      ifail = 0
      Call e04zmf(h,'Dimacs = Check',ifail)

!     Pass the handle to the solver, we are not interested in
!     Lagrangian multipliers.
      nnzu = 0
      nnzuc = 0
      nnzua = 0
loop: Do
        ifail = -1
        Call e04svf(h,nvar,x,nnzu,rdummy,nnzuc,rdummy,nnzua,rdummy,rinfo,      &
          stats,inform,ifail)

        If (inform==1) Then
!         Monitor stop
          Write (nout,99998) int(stats(1)), rinfo(1),                          &
            sum(rinfo(2:4))/3.0_nag_wp
          Flush (nout)

!         Check time limit and possibly stop the solver.
          If (stats(8)>time_limit) Then
            inform = 0
          End If
        Else
!         Final exit, solver finished.
          Write (nout,99997) int(stats(1)), rinfo(1),                          &
            sum(rinfo(2:4))/3.0_nag_wp
          Flush (nout)
          Exit loop
        End If

      End Do loop

      If (ifail==0 .Or. ifail==50) Then
!       Successful run, fill the missing elements in the matrix Y.
        idx = m*(m+1)/2 + n*(n+1)/2 + 1
        Do i = 1, m
          Do j = 1, n
            If (y(i,j)<0.0_nag_wp) Then
              y(i,j) = x(idx)
              idx = idx + 1
            End If
          End Do
        End Do

!       Print the matrix.
        ifail = 0
        Call x04cbf('General','N',m,n,y,m,'F7.1','Completed Matrix','Integer', &
          cdummy,'Integer',cdummy,80,0,ifail)

!       Compute rank of the matrix via SVD, use the fact that the order
!       of the singular values is descending.
        lwork = 20*max(m,n)
        Allocate (s(min(m,n)),work(lwork))
        Call f08kbf('No','No',m,n,y,m,s,rdummy,1,rdummy,1,work,lwork,info)
        If (info==0) Then
lp_rank:  Do rank = 1, min(m,n)
            If (s(rank)<=stol) Then
              Exit lp_rank
            End If
          End Do lp_rank
          Write (nout,99999) 'Rank is', rank - 1
99999     Format (1X,A,I20)
        End If
      Else If (ifail==20) Then
        Write (nout,*) 'The given time limit was reached, run aborted.'
      End If

!     Destroy the handle.
      ifail = 0
      Call e04rzf(h,ifail)

99998 Format (1X,'Monitor at iteration  ',I2,': objective ',F7.2,              &
        ', avg.error ',Es9.2e2)
99997 Format (1X,'Finished at iteration ',I2,': objective ',F7.2,              &
        ', avg.error ',Es9.2e2)
    End Program e04rhfe


e04rjfe.f90

    Program e04rjfe

!     E04RJF Example Program Text

!     Read in LP/QP problem stored in a MPS file, formulated it
!     as a handle and pass it to the solver.

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: e04mxf, e04raf, e04rff, e04rhf, e04rjf, e04rzf,   &
                             e04svf, e04zmf, nag_wp, x04acf, x04adf
      Use, Intrinsic                   :: iso_c_binding, Only: c_null_ptr,     &
                                          c_ptr
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: mpslst = 1, nin = 7, nout = 6
      Character (*), Parameter         :: fname_default = 'e04rjfe.opt'
!     .. Local Scalars ..
      Type (c_ptr)                     :: handle
      Integer                          :: idlc, idx, idx_c, idx_dest, ifail,   &
                                          inform, iobj, j, lintvar, m,         &
                                          maxlintvar, maxm, maxn, maxncolh,    &
                                          maxnnz, maxnnzh, minmax, mode, n,    &
                                          nargs, ncolh, nname, nnz, nnzc,      &
                                          nnzh, nnzu, nnzua, nnzuc
      Character (256)                  :: fname
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: a(:), bl(:), bu(:), c(:), h(:),      &
                                          u(:), ua(:), uc(:), x(:)
      Real (Kind=nag_wp)               :: rinfo(32), stats(32)
      Integer, Allocatable             :: iccola(:), iccolh(:), icola(:),      &
                                          icolh(:), idxc(:), intvar(:),        &
                                          irowa(:), irowh(:)
      Character (8), Allocatable       :: crname(:)
      Character (8)                    :: pnames(5)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: command_argument_count, count,       &
                                          get_command_argument, trim
!     .. Executable Statements ..
      Continue

      Write (nout,*) 'E04RJF Example Program Results'
      Write (nout,*)

!     Use the first command line argument as the filename or
!     choose default hard-coded filename in 'fname_default'.
      nargs = command_argument_count()
      If (nargs>=1) Then
        Call get_command_argument(1,fname)
      Else
        fname = fname_default
      End If

      Write (nout,*) 'Reading MPS file:  ', trim(fname)
      Flush (nout)

!     Read the input MPS file.
      pnames(1:5) = '        '
      maxm = 0
      maxn = 0
      maxnnz = 0
      maxnnzh = 0
      maxncolh = 0
      maxlintvar = -1

!     Open the data file for reading.
      mode = 0
      ifail = 0
      Call x04acf(nin,fname,mode,ifail)

!     Call E04MXF in query mode to obtain an approximate problem size.
      Allocate (a(maxnnz),irowa(maxnnz),iccola(maxn+1),bl(maxn+maxm),          &
        bu(maxn+maxm),crname(maxn+maxm),h(maxnnzh),irowh(maxnnzh),             &
        iccolh(maxncolh+1),intvar(maxlintvar))
      ifail = 0
      Call e04mxf(nin,maxn,maxm,maxnnz,maxncolh,maxnnzh,maxlintvar,mpslst,n,m, &
        nnz,ncolh,nnzh,lintvar,iobj,a,irowa,iccola,bl,bu,pnames,nname,crname,  &
        h,irowh,iccolh,minmax,intvar,ifail)
      Deallocate (a,irowa,iccola,bl,bu,crname,h,irowh,iccolh)

!     Close the data file.
      ifail = 0
      Call x04adf(nin,ifail)

!     Set maximal problem size.
      maxm = m
      maxn = n
      maxnnz = nnz
      maxnnzh = nnzh
      maxncolh = ncolh

      Allocate (irowa(maxnnz),iccola(maxn+1),a(maxnnz),bl(maxn+maxm),          &
        bu(maxn+maxm),crname(maxn+maxm),irowh(maxnnzh),iccolh(maxncolh+1),     &
        h(maxnnzh),x(maxn),icolh(maxnnzh),icola(maxnnz))

!     Open the data file for reading.
      mode = 0
      ifail = 0
      Call x04acf(nin,fname,mode,ifail)

!     Call E04MXF to read the problem.
      ifail = 0
      Call e04mxf(nin,maxn,maxm,maxnnz,maxncolh,maxnnzh,maxlintvar,mpslst,n,m, &
        nnz,ncolh,nnzh,lintvar,iobj,a,irowa,iccola,bl,bu,pnames,nname,crname,  &
        h,irowh,iccolh,minmax,intvar,ifail)

      Write (nout,*) 'MPS/QPS file read'
      Flush (nout)

!     Close the data file.
      ifail = 0
      Call x04adf(nin,ifail)

!     Data has been read. Set up the problem to the solver.

!     Initialize handle.
      handle = c_null_ptr
      ifail = 0
      Call e04raf(handle,n,ifail)

!     Move linear objective from A to C.
      If (iobj>0) Then
!       Shift bounds.
        Do j = iobj, m - 1
          bl(n+j) = bl(n+j+1)
          bu(n+j) = bu(n+j+1)
        End Do
        m = m - 1
!       Extract row IOBJ.
!       Count how many nonzeros will be needed in C.
        nnzc = count(irowa(1:nnz)==iobj)
        Allocate (idxc(nnzc),c(nnzc))
        idx = 1
        idx_c = 1
        idx_dest = 1
        Do j = 1, n
          Do idx = idx, iccola(j+1) - 1
            If (irowa(idx)<iobj) Then
              a(idx_dest) = a(idx)
              irowa(idx_dest) = irowa(idx)
              idx_dest = idx_dest + 1
            Else If (irowa(idx)==iobj) Then
              idxc(idx_c) = j
              c(idx_c) = a(idx)
              idx_c = idx_c + 1
            Else
              a(idx_dest) = a(idx)
              irowa(idx_dest) = irowa(idx) - 1
              idx_dest = idx_dest + 1
            End If
          End Do
          iccola(j+1) = idx_dest
        End Do
        nnz = idx_dest - 1
      Else
!       There is no linear part of the objective function.
        nnzc = 0
        Allocate (idxc(nnzc),c(nnzc))
      End If
!     Convert (decompress) ICCOLA() to ICOLA().
      Do j = 1, n
        icola(iccola(j):iccola(j+1)-1) = j
      End Do

!     Add objective function to the problem formulation.
      If (nnzh==0) Then
!       The objective is a (sparse) linear function.
        ifail = 0
        Call e04rff(handle,nnzc,idxc,c,nnzh,irowh,icolh,h,ifail)
      Else
!       The objective is a quadratic function.
!       Transform (decompress) ICCOLH() -> ICOLH().
        Do j = 1, ncolh
          icolh(iccolh(j):iccolh(j+1)-1) = j
        End Do
!       E04MX returned L triangle, E04RFF needs U triangle -> swap.
        ifail = 0
        Call e04rff(handle,nnzc,idxc,c,nnzh,icolh,irowh,h,ifail)
      End If

!     Add box constraints to the formulation.
      ifail = 0
      Call e04rhf(handle,n,bl,bu,ifail)

!     Add linear constraints.
      idlc = 0
      ifail = 0
      Call e04rjf(handle,m,bl(n+1:n+m),bu(n+1:n+m),nnz,irowa,icola,a,idlc,     &
        ifail)

      Write (nout,*) 'The problem was set-up'
      Flush (nout)

!     Call the solver.

!     Set optional arguments.
      ifail = 0
      Call e04zmf(handle,'Print Options = No',ifail)

!     Set up a starting point and call the solver.
!     Let's ignore Lagrangian multipliers U/UA.
      x(:) = 0.0_nag_wp
      nnzu = 0
      nnzuc = 0
      nnzua = 0
      Allocate (u(nnzu),uc(nnzuc),ua(nnzua))

      ifail = 0
      Call e04svf(handle,n,x,nnzu,u,nnzuc,uc,nnzua,ua,rinfo,stats,inform,      &
        ifail)

      Write (nout,*)
      Write (nout,*) 'Optimal solution:'
      Write (nout,99999) x(1:n)
99999 Format (1X,'X = ',3F9.2)
      Flush (nout)

!     Destroy the handle.
      ifail = 0
      Call e04rzf(handle,ifail)

    End Program e04rjfe


e04rnfe.f90

    Program e04rnfe

!     E04RNF Example Program Text
!     Mark 26 Release. NAG Copyright 2016.

!     Compute E-optimal experiment design via semidefinite programming,
!     this can be done as follows
!       max {lambda_min(A) | A = sum x_i*v_i*v_i^T, x_i>=0, sum x_i = 1}
!     where v_i are given vectors.

!     Use nag_library

!     .. Use Statements ..
      Use nag_library, Only: e04raf, e04rff, e04rhf, e04rjf, e04rnf, e04rzf,   &
                             e04svf, e04zmf, nag_wp
      Use, Intrinsic                   :: iso_c_binding, Only: c_null_ptr,     &
                                          c_ptr
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Real (Kind=nag_wp), Parameter    :: big = 1E+20_nag_wp
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Type (c_ptr)                     :: h
      Real (Kind=nag_wp)               :: tol
      Integer                          :: dima, i, idblk, idlc, idx, ifail,    &
                                          inform, j, k, m, nblk, nnzasum,      &
                                          nnzb, nnzc, nnzu, nnzua, nnzuc,      &
                                          nvar, p
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: a(:), b(:), bl(:), bu(:), c(:),      &
                                          v(:,:), x(:)
      Real (Kind=nag_wp)               :: rdummy(1), rinfo(32), stats(32)
      Integer, Allocatable             :: blksizea(:), icola(:), icolb(:),     &
                                          idxc(:), irowa(:), irowb(:), nnza(:)
      Integer                          :: idummy(1)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: repeat
!     .. Executable Statements ..
      Continue

      Write (nout,*) 'E04RNF Example Program Results'
      Write (nout,*)
      Flush (nout)

!     Skip heading in data file.
      Read (nin,*)

!     Read in the number of vectors and their size.
      Read (nin,*) m
      Read (nin,*) p

      Allocate (v(p,m))

!     Read in the vectors v_j.
      Do j = 1, m
        Read (nin,*)(v(i,j),i=1,p)
      End Do

!     Initialize handle.
      h = c_null_ptr

!     Variables of the problem will be x_1, ..., x_m (weights of the vectors)
!     and t (artificial variable for minimum eigenvalue).
      nvar = m + 1

!     Initialize an empty problem handle with NVAR variables.
      ifail = 0
      Call e04raf(h,nvar,ifail)

!     Add the objective function to the handle: max t.
      nnzc = 1
      Allocate (idxc(nnzc),c(nnzc))
      idxc(:) = (/m+1/)
      c(:) = (/1._nag_wp/)

      ifail = 0
      Call e04rff(h,nnzc,idxc,c,0,idummy,idummy,rdummy,ifail)

      Allocate (bl(nvar),bu(nvar))
      bl(1:m) = 0.0_nag_wp
      bl(m+1) = -big
      bu(1:m+1) = big

!     Add simple bounds on variables, x_i>=0.
      ifail = 0
      Call e04rhf(h,nvar,bl,bu,ifail)

      nnzb = m
      Allocate (irowb(nnzb),icolb(nnzb),b(nnzb))
      irowb(:) = 1
      icolb(:) = (/(j,j=1,m)/)
      b(:) = 1.0_nag_wp

!     Add the linear constraint: sum x_i = 1.
      idlc = 0
      ifail = 0
      Call e04rjf(h,1,(/1.0_nag_wp/),(/1.0_nag_wp/),nnzb,irowb,icolb,b,idlc,   &
        ifail)

!     Generate matrix constraint as:
!       sum_{i=1}^m x_i*v_i*v_i^T - t*I >=0

      nblk = 1
      dima = p

!     Total number of nonzeros
      nnzasum = p + m*(p+1)*p/2

      Allocate (nnza(nvar+1),irowa(nnzasum),icola(nnzasum),a(nnzasum),x(nvar))
!     A_0 is empty
      nnza(1) = 0
!     A_1, A_2, ..., A_m are v_i*v_i^T
      nnza(2:m+1) = (p+1)*p/2
      idx = 0
      Do k = 1, m
        Do i = 1, p
          Do j = i, p
            idx = idx + 1
            irowa(idx) = i
            icola(idx) = j
            a(idx) = v(i,k)*v(j,k)
          End Do
        End Do
      End Do
!     A_{m+1} is the -identity
      nnza(m+2) = p
      Do i = 1, p
        idx = idx + 1
        irowa(idx) = i
        icola(idx) = i
        a(idx) = -1.0_nag_wp
      End Do

!     Add the constraint to the problem formulation.
      Allocate (blksizea(nblk))
      blksizea(:) = (/dima/)

      idblk = 0
      ifail = 0
      Call e04rnf(h,nvar,dima,nnza,nnzasum,irowa,icola,a,nblk,blksizea,idblk,  &
        ifail)

!     Set optional arguments of the solver.
      ifail = 0
      Call e04zmf(h,'Task = Maximize',ifail)
      ifail = 0
      Call e04zmf(h,'Initial X = Automatic',ifail)

!     Pass the handle to the solver, we are not interested in
!     Lagrangian multipliers.
      nnzu = 0
      nnzuc = 0
      nnzua = 0

      ifail = 0
      Call e04svf(h,nvar,x,nnzu,rdummy,nnzuc,rdummy,nnzua,rdummy,rinfo,stats,  &
        inform,ifail)

!     Print results
      Write (nout,*)
      tol = 0.00001_nag_wp
      Write (nout,*) '  Weight        Row of design matrix'
      Write (nout,*) repeat('-',13+p*8)
      Do j = 1, m
        If (x(j)>tol) Then
          Write (*,99999) x(j), v(1:p,j)
        End If
      End Do
      Write (nout,99998) 'only those rows with a weight > ', tol, ' are shown'

!     Destroy the handle.
      ifail = 0
      Call e04rzf(h,ifail)

99999 Format (1X,F7.2,5X,10(1X,F7.2))
99998 Format (1X,A,E8.1,A)
    End Program e04rnfe


e04rpfe.f90

    Program e04rpfe

!     E04RPF Example Program Text

!     Read a 'generic' LMI/BMI SDP problem from the input file,
!     formulate the problem via a handle and pass it to the solver.

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: e04raf, e04ref, e04rff, e04rjf, e04rnf, e04rpf,   &
                             e04ryf, e04rzf, e04svf, nag_wp
      Use, Intrinsic                   :: iso_c_binding, Only: c_ptr
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Type (c_ptr)                     :: handle
      Integer                          :: blkidx, dimaq, idblk, idlc, idx,     &
                                          idxend, ifail, inform, midx, nblk,   &
                                          nclin, nnzasum, nnzb, nnzc, nnzh,    &
                                          nnzqsum, nnzu, nnzua, nnzuc, nq,     &
                                          nvar
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: a(:), b(:), bl(:), bu(:), cvec(:),   &
                                          h(:), q(:), x(:)
      Real (Kind=nag_wp)               :: rdummy(1), rinfo(32), stats(32)
      Integer, Allocatable             :: icola(:), icolb(:), icolh(:),        &
                                          icolq(:), idxc(:), irowa(:),         &
                                          irowb(:), irowh(:), irowq(:),        &
                                          nnza(:), nnzq(:), qi(:), qj(:)
      Integer                          :: idummy(1)
!     .. Executable Statements ..
      Continue

      Write (nout,*) 'E04RPF Example Program Results'
      Write (nout,*)
      Flush (nout)

!     Skip heading in the data file.
      Read (nin,*)

!     Read the problem size.
      Read (nin,*) nvar
      Read (nin,*) nnzh
      Read (nin,*) nclin, nnzb
      Read (nin,*) nblk

!     Initialize handle to an empty problem.
      ifail = 0
      Call e04raf(handle,nvar,ifail)

!     Read the linear part of the objective function.
      Allocate (cvec(nvar))
      Read (nin,*) cvec(1:nvar)

      If (nnzh==0) Then
!       Add the linear objective function to the problem formulation.
        ifail = 0
        Call e04ref(handle,nvar,cvec,ifail)
        Deallocate (cvec)

      Else
!       The linear part of the objective was read in as dense, E04RFF needs
!       the sparse format.
        nnzc = nvar
        Allocate (idxc(nnzc))
        Do idx = 1, nvar
          idxc(idx) = idx
        End Do

!       Read nonzeros for H (quadratic part of the objective) if present.
        Allocate (irowh(nnzh),icolh(nnzh),h(nnzh))
        Do idx = 1, nnzh
          Read (nin,*) h(idx), irowh(idx), icolh(idx)
        End Do

!       Add the quadratic objective function to the problem formulation.
        ifail = 0
        Call e04rff(handle,nnzc,idxc,cvec,nnzh,irowh,icolh,h,ifail)
        Deallocate (idxc,cvec,irowh,icolh,h)
      End If

!     Read a block of linear constraints and its bounds if present.
      If (nclin>0 .And. nnzb>0) Then
        Allocate (irowb(nnzb),icolb(nnzb),b(nnzb),bl(nclin),bu(nclin))
        Do idx = 1, nnzb
          Read (nin,*) b(idx), irowb(idx), icolb(idx)
        End Do
        Read (nin,*) bl(1:nclin)
        Read (nin,*) bu(1:nclin)

!       Add the block of linear constraints.
        idlc = 0
        ifail = 0
        Call e04rjf(handle,nclin,bl,bu,nnzb,irowb,icolb,b,idlc,ifail)
        Deallocate (irowb,icolb,b,bl,bu)
      End If

!     Read all matrix inequalities.
      Do blkidx = 1, nblk
        Read (nin,*) dimaq
        Read (nin,*) nnzasum, nnzqsum
        idblk = 0

        If (nnzasum>0) Then
!         Read a linear matrix inequality composed of (NVAR+1) matrices.
          Allocate (nnza(nvar+1),irowa(nnzasum),icola(nnzasum),a(nnzasum))
          idx = 1
          Do midx = 1, nvar + 1
!           Read matrix A_{midx-1}.
            Read (nin,*) nnza(midx)
            idxend = idx + nnza(midx) - 1
            Do idx = idx, idxend
              Read (nin,*) a(idx), irowa(idx), icola(idx)
            End Do
          End Do

!         Add the linear matrix inequality to the problem formulation.
          idblk = 0
          ifail = 0
          Call e04rnf(handle,nvar,dimaq,nnza,nnzasum,irowa,icola,a,1,idummy,   &
            idblk,ifail)
          Deallocate (nnza,irowa,icola,a)
        End If

        If (nnzqsum>0) Then
!         Read bilinear part of the matrix inequality composed of NQ matrices.
          Read (nin,*) nq
          Allocate (qi(nq),qj(nq),nnzq(nq),irowq(nnzqsum),icolq(nnzqsum),      &
            q(nnzqsum))
          idx = 1
          Do midx = 1, nq
!           Read matrix Q_ij where i=QI(midx), j=QJ(midx).
            Read (nin,*) qi(midx), qj(midx)
            Read (nin,*) nnzq(midx)
            idxend = idx + nnzq(midx) - 1
            Do idx = idx, idxend
              Read (nin,*) q(idx), irowq(idx), icolq(idx)
            End Do
          End Do

!         Expand the existing linear matrix inequality with the bilinear terms
!         or (if linear part was not present) create a new matrix inequality.
          ifail = 0
          Call e04rpf(handle,nq,qi,qj,dimaq,nnzq,nnzqsum,irowq,icolq,q,idblk,  &
            ifail)
          Deallocate (qi,qj,nnzq,irowq,icolq,q)
        End If

      End Do

!     Problem was successfully decoded.
      Write (nout,*) 'SDP problem was read, passing it to the solver.'
      Write (nout,*)
      Flush (nout)

!     Print overview of the handle.
      ifail = 0
      Call e04ryf(handle,nout,'Overview,Matrix Constraints',ifail)

!     Allocate memory for the solver.
      Allocate (x(nvar))

!     Call the solver, ignore Lagrangian multipliers.
      nnzu = 0
      nnzuc = 0
      nnzua = 0
      inform = 0
      x(:) = 0.0_nag_wp

      ifail = 0
      Call e04svf(handle,nvar,x,nnzu,rdummy,nnzuc,rdummy,nnzua,rdummy,rinfo,   &
        stats,inform,ifail)

!     Destroy the handle.
      ifail = 0
      Call e04rzf(handle,ifail)

    End Program e04rpfe


e04ryfe.f90

    Program e04ryfe

!     E04RYF Example Program Text

!     Demonstrate the life-cycle of a handle of a typical BMI-SDP problem
!     by printing the evolution of the HANDLE in certain stages.

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: e04raf, e04ref, e04rhf, e04rnf, e04rpf, e04ryf,   &
                             e04rzf, e04svf, e04zmf, nag_wp
      Use, Intrinsic                   :: iso_c_binding, Only: c_null_ptr,     &
                                          c_ptr
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: maxnnz = 6, maxnvar = 2, nout = 6
!     .. Local Scalars ..
      Type (c_ptr)                     :: h
      Integer                          :: dima, idblk, ifail, inform, nblk,    &
                                          nnzasum, nvar
!     .. Local Arrays ..
      Real (Kind=nag_wp)               :: a(maxnnz), rdummy(1), rinfo(32),     &
                                          stats(32), x(maxnvar)
      Integer                          :: icola(maxnnz), idummy(1),            &
                                          irowa(maxnnz), nnza(maxnvar+1)
!     .. Executable Statements ..
      Continue

      Write (nout,*) 'E04RYF Example Program Results'
      Write (nout,*)
      Flush (nout)

      h = c_null_ptr

!     Start a problem formulation with 2 variables.
      nvar = 2
      ifail = 0
      Call e04raf(h,nvar,ifail)

!     Anything can be defined at this phase.
      Write (nout,*) 'Freshly created handle'
      Flush (nout)
      ifail = 0
      Call e04ryf(h,nout,'Overview',ifail)

!     Define linear objective (min y).
      ifail = 0
      Call e04ref(h,nvar,(/0.0_nag_wp,1.0_nag_wp/),ifail)

!     Add simple bounds (x>=0, -3<=y<=3).
      ifail = 0
      Call e04rhf(h,nvar,(/0.0_nag_wp,-3.0_nag_wp/),                           &
        (/1E20_nag_wp,3.0_nag_wp/),ifail)

!     The simple bounds and the objective are set and cannot be changed.
      Write (nout,*)
      Write (nout,*)                                                           &
        'Handle after definition of simple bounds and the objective'
      Flush (nout)
      ifail = 0
      Call e04ryf(h,nout,'Overview,Objective,Simple Bounds',ifail)

!     Definition of the first (linear) matrix constraint
!        ( 1   x-1   y )
!        (x-1  3/4   0 )  >= 0
!        ( y    0   16 )
!     only upper triangles, thus we have matrices
!           ( 1  -1  0 )        ( 0  1  0 )       ( 0  0  1 )
!     A0 = -(   3/4  0 ),  A1 = (    0  0 ), A2 = (    0  0 )
!           (       16 )        (       0 )       (       0 )
!     Note: don't forget the minus at A0 term!
      dima = 3
      nnzasum = 6
      nblk = 1
!     A0
      irowa(1:4) = (/1,1,2,3/)
      icola(1:4) = (/1,2,2,3/)
      a(1:4) = (/-1.0_nag_wp,1.0_nag_wp,-0.75_nag_wp,-16.0_nag_wp/)
      nnza(1) = 4
!     A1
      irowa(5:5) = (/1/)
      icola(5:5) = (/2/)
      a(5:5) = (/1.0_nag_wp/)
      nnza(2) = 1
!     A2
      irowa(6:6) = (/1/)
      icola(6:6) = (/3/)
      a(6:6) = (/1.0_nag_wp/)
      nnza(3) = 1

      idblk = 0
      ifail = 0
      Call e04rnf(h,nvar,dima,nnza,nnzasum,irowa,icola,a,nblk,idummy,idblk,    &
        ifail)

!     It is possible to add or extend existing matrix constraints.
      Write (nout,*)
      Write (nout,*) 'Handle after definition of the 1st matrix constraint'
      Flush (nout)
      ifail = 0
      Call e04ryf(h,nout,'Overview,Matrix Constraints',ifail)

!     Definition of the absolute term and linear part of BMI
!        (  x   -xy )
!        (-xy    1  ) >= 0
!     thus
!           ( 0  0 )        ( 1  0 )
!     A0 = -(    1 ),  A1 = (    0 ), A2 = zero
!     Note: don't forget the minus at A0 term!
      dima = 2
      nnzasum = 2
      nblk = 1
!     A0
      irowa(1:1) = (/2/)
      icola(1:1) = (/2/)
      a(1:1) = (/-1.0_nag_wp/)
      nnza(1) = 1
!     A1
      irowa(2:2) = (/1/)
      icola(2:2) = (/1/)
      a(2:2) = (/1.0_nag_wp/)
      nnza(2) = 1
!     A2
      nnza(3) = 0

      idblk = 0
      ifail = 0
      Call e04rnf(h,nvar,dima,nnza,nnzasum,irowa,icola,a,nblk,idummy,idblk,    &
        ifail)

!     It is possible to add or extend existing matrix constraints.
      Write (nout,*)
      Write (nout,*)                                                           &
        'Handle after partial definition of the 2nd matrix constraint'
      Flush (nout)
      ifail = 0
      Call e04ryf(h,nout,'Matrix Constraints',ifail)

!     Extending current matrix constraint (with IDBLK) by bilinear term
!           ( 0  -1 )
!     Q12 = ( 0   0 ).
      dima = 2
      nnzasum = 1
      nnza(1) = 1
      irowa(1:1) = (/1/)
      icola(1:1) = (/2/)
      a(1:1) = (/-1.0_nag_wp/)
      ifail = 0
      Call e04rpf(h,1,(/1/),(/2/),dima,nnza,nnzasum,irowa,icola,a,idblk,ifail)

!     Our problem completely defined.
      Write (nout,*)
      Write (nout,*) 'Handle with the complete problem formulation'
      Flush (nout)
      ifail = 0
      Call e04ryf(h,nout,'Overview,Matrix Constraints,Multipliers Sizes',      &
        ifail)
      ifail = 0
      Call e04ryf(h,nout,'Matrix Constraints Detailed',ifail)

!     Set optional arguments for the solver.
      ifail = 0
      Call e04zmf(h,'Print Options = No',ifail)
      ifail = 0
      Call e04zmf(h,'Initial X = Automatic',ifail)

!     Options can be printed even outside the solver.
      Write (nout,*)
      Flush (nout)
      ifail = 0
      Call e04ryf(h,nout,'Options',ifail)

!     Call the solver.
      ifail = 0
      Call e04svf(h,nvar,x,0,rdummy,0,rdummy,0,rdummy,rinfo,stats,inform,      &
        ifail)

!     After solver finished.
      Write (nout,*)
      Write (nout,*) 'Problem solved'
      Flush (nout)
      ifail = 0
      Call e04ryf(h,nout,'Overview',ifail)

!     Print result.
      Write (nout,*)
      Write (nout,'(1X,A,F9.2)') 'Final objective value = ', rinfo(1)
      Write (nout,'(1X,A,2F9.2)') 'Final X = ', x(1:nvar)

!     release all memory held in the handle
      ifail = 0
      Call e04rzf(h,ifail)

    End Program e04ryfe


e04stfe.f90

!   E04STF Example Program Text
!   Mark 26 Release. NAG Copyright 2016.

!   NLP example : Linear objective + Linear constraint + Non-Linear constraint

    Module e04stfe_mod

!     .. Use Statements ..
      Use nag_library, Only: nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Accessibility Statements ..
      Private
      Public                           :: confun, congrd, hess, mon, objfun,   &
                                          objgrd
    Contains
      Subroutine objfun(nvar,x,fx,inform,iuser,ruser,cpuser)

!       .. Use Statements ..
        Use, Intrinsic                 :: iso_c_binding, Only: c_ptr
        Use nag_library, Only: f06eaf
!       .. Scalar Arguments ..
        Type (c_ptr), Intent (Inout)   :: cpuser
        Real (Kind=nag_wp), Intent (Out) :: fx
        Integer, Intent (Inout)        :: inform
        Integer, Intent (In)           :: nvar
!       .. Array Arguments ..
        Real (Kind=nag_wp), Intent (Inout) :: ruser(*)
        Real (Kind=nag_wp), Intent (In) :: x(nvar)
        Integer, Intent (Inout)        :: iuser(*)
!       .. Executable Statements ..
        fx = f06eaf(4,x,1,ruser,1)
        Return
      End Subroutine objfun
      Subroutine objgrd(nvar,x,nnzfd,fdx,inform,iuser,ruser,cpuser)

!       .. Use Statements ..
        Use, Intrinsic                 :: iso_c_binding, Only: c_ptr
!       .. Scalar Arguments ..
        Type (c_ptr), Intent (Inout)   :: cpuser
        Integer, Intent (Inout)        :: inform
        Integer, Intent (In)           :: nnzfd, nvar
!       .. Array Arguments ..
        Real (Kind=nag_wp), Intent (Out) :: fdx(nnzfd)
        Real (Kind=nag_wp), Intent (Inout) :: ruser(*)
        Real (Kind=nag_wp), Intent (In) :: x(nvar)
        Integer, Intent (Inout)        :: iuser(*)
!       .. Executable Statements ..
        Continue
        fdx(1:nnzfd) = ruser(1:nnzfd)
        Return
      End Subroutine objgrd
      Subroutine confun(nvar,x,ncnln,gx,inform,iuser,ruser,cpuser)

!       .. Use Statements ..
        Use, Intrinsic                 :: iso_c_binding, Only: c_ptr
!       .. Scalar Arguments ..
        Type (c_ptr), Intent (Inout)   :: cpuser
        Integer, Intent (Inout)        :: inform
        Integer, Intent (In)           :: ncnln, nvar
!       .. Array Arguments ..
        Real (Kind=nag_wp), Intent (Out) :: gx(ncnln)
        Real (Kind=nag_wp), Intent (Inout) :: ruser(*)
        Real (Kind=nag_wp), Intent (In) :: x(nvar)
        Integer, Intent (Inout)        :: iuser(*)
!       .. Intrinsic Procedures ..
        Intrinsic                      :: sqrt
!       .. Executable Statements ..
        Continue
        gx(1) = 12.0_nag_wp*x(1) + 11.9_nag_wp*x(2) + 41.8_nag_wp*x(3) +       &
          52.1_nag_wp*x(4) - 1.645_nag_wp*sqrt(.28_nag_wp*x(1)**2+.19_nag_wp*x &
          (2)**2+20.5_nag_wp*x(3)**2+.62_nag_wp*x(4)**2)
        Return
      End Subroutine confun
      Subroutine congrd(nvar,x,nnzgd,gdx,inform,iuser,ruser,cpuser)

!       .. Use Statements ..
        Use, Intrinsic                 :: iso_c_binding, Only: c_ptr
!       .. Scalar Arguments ..
        Type (c_ptr), Intent (Inout)   :: cpuser
        Integer, Intent (Inout)        :: inform
        Integer, Intent (In)           :: nnzgd, nvar
!       .. Array Arguments ..
        Real (Kind=nag_wp), Intent (Out) :: gdx(nnzgd)
        Real (Kind=nag_wp), Intent (Inout) :: ruser(*)
        Real (Kind=nag_wp), Intent (In) :: x(nvar)
        Integer, Intent (Inout)        :: iuser(*)
!       .. Local Scalars ..
        Real (Kind=nag_wp)             :: tmp
!       .. Intrinsic Procedures ..
        Intrinsic                      :: sqrt
!       .. Executable Statements ..
        Continue
        tmp = sqrt(0.62_nag_wp*x(4)**2+20.5_nag_wp*x(3)**2+                    &
          0.19_nag_wp*x(2)**2+0.28_nag_wp*x(1)**2)
        gdx(1) = (12.0_nag_wp*tmp-0.4606_nag_wp*x(1))/tmp
        gdx(2) = (11.9_nag_wp*tmp-0.31255_nag_wp*x(2))/tmp
        gdx(3) = (41.8_nag_wp*tmp-33.7225_nag_wp*x(3))/tmp
        gdx(4) = (52.1_nag_wp*tmp-1.0199_nag_wp*x(4))/tmp
        Return
      End Subroutine congrd
      Subroutine hess(nvar,x,ncnln,idf,sigma,lambda,nnzh,hx,inform,iuser,      &
        ruser,cpuser)

!       .. Use Statements ..
        Use, Intrinsic                 :: iso_c_binding, Only: c_ptr
!       .. Scalar Arguments ..
        Type (c_ptr), Intent (Inout)   :: cpuser
        Real (Kind=nag_wp), Intent (In) :: sigma
        Integer, Intent (In)           :: idf, ncnln, nnzh, nvar
        Integer, Intent (Inout)        :: inform
!       .. Array Arguments ..
        Real (Kind=nag_wp), Intent (Out) :: hx(nnzh)
        Real (Kind=nag_wp), Intent (In) :: lambda(ncnln), x(nvar)
        Real (Kind=nag_wp), Intent (Inout) :: ruser(*)
        Integer, Intent (Inout)        :: iuser(*)
!       .. Local Scalars ..
        Real (Kind=nag_wp)             :: tmp
!       .. Intrinsic Procedures ..
        Intrinsic                      :: sqrt
!       .. Executable Statements ..
        inform = -1
        hx = 0.0_nag_wp
        Select Case (idf)
        Case (0)
          inform = 0
        Case (1,-1)
          tmp = sqrt(0.62_nag_wp*x(4)**2+20.5_nag_wp*x(3)**2+                  &
            0.19_nag_wp*x(2)**2+0.28_nag_wp*x(1)**2)
          tmp = tmp*(x(4)**2+33.064516129032258064_nag_wp*x(3)**2+             &
            0.30645161290322580645_nag_wp*x(2)**2+                             &
            0.45161290322580645161_nag_wp*x(1)**2)
!         1,1..4
          hx(1) = (-0.4606_nag_wp*x(4)**2-15.229516129032258064_nag_wp*x(3)**2 &
            -0.14115161290322580645_nag_wp*x(2)**2)/tmp
          hx(2) = (0.14115161290322580645_nag_wp*x(1)*x(2))/tmp
          hx(3) = (15.229516129032258064_nag_wp*x(1)*x(3))/tmp
          hx(4) = (0.4606_nag_wp*x(1)*x(4))/tmp
!         2,2..4
          hx(5) = (-0.31255_nag_wp*x(4)**2-10.334314516129032258_nag_wp*x(3)** &
            2-0.14115161290322580645_nag_wp*x(1)**2)/tmp
          hx(6) = (10.334314516129032258_nag_wp*x(2)*x(3))/tmp
          hx(7) = (0.31255_nag_wp*x(2)*x(4))/tmp
!         3,3..4
          hx(8) = (-33.7225_nag_wp*x(4)**2-10.334314516129032258_nag_wp*x(2)** &
            2-15.229516129032258065_nag_wp*x(1)**2)/tmp
          hx(9) = (33.7225_nag_wp*x(3)*x(4))/tmp
!         4,4
          hx(10) = (-33.7225_nag_wp*x(3)**2-0.31255_nag_wp*x(2)**2-            &
            0.4606_nag_wp*x(1)**2)/tmp
          If (idf==-1) Then
            hx = lambda(1)*hx
          End If
          inform = 0
        Case Default
        End Select
        Return
      End Subroutine hess
      Subroutine mon(nvar,x,nnzu,u,inform,rinfo,stats,iuser,ruser,cpuser)

!       .. Use Statements ..
        Use, Intrinsic                 :: iso_c_binding, Only: c_ptr
!       .. Scalar Arguments ..
        Type (c_ptr), Intent (Inout)   :: cpuser
        Integer, Intent (Inout)        :: inform
        Integer, Intent (In)           :: nnzu, nvar
!       .. Array Arguments ..
        Real (Kind=nag_wp), Intent (In) :: rinfo(32), stats(32), u(nnzu),      &
                                          x(nvar)
        Real (Kind=nag_wp), Intent (Inout) :: ruser(*)
        Integer, Intent (Inout)        :: iuser(*)
!       .. Local Scalars ..
        Integer                        :: i, io_unit
!       .. Executable Statements ..
        Continue
        io_unit = iuser(2)
        Write (io_unit,99999)
        Write (io_unit,99998) x
        Write (io_unit,99997)
        Write (io_unit,99998) u
        Write (io_unit,99996)
        Write (io_unit,99995)(i,rinfo(i),i=1,32)
        Write (io_unit,99994)
        Write (io_unit,99995)(i,stats(i),i=1,32)
99999   Format ('Monitoring...',/,'   X(*)')
99998   Format (1P,E14.6)
99997   Format ('   U(*)')
99996   Format ('   RINFO(32)')
99995   Format (4(I2,1P,E14.6,1X))
99994   Format ('   STATS(32)')
        Return
      End Subroutine mon
    End Module e04stfe_mod

    Program e04stfe

!     .. Use Statements ..
      Use nag_library, Only: e04raf, e04ref, e04rgf, e04rhf, e04rjf, e04rkf,   &
                             e04rlf, e04ryf, e04rzf, e04stf, e04zmf, nag_wp,   &
                             x04acf
      Use e04stfe_mod, Only: confun, congrd, hess, mon, objfun, objgrd
      Use, Intrinsic                   :: iso_c_binding, Only: c_null_ptr,     &
                                          c_ptr
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Real (Kind=nag_wp), Parameter    :: solve_timeout = 5._nag_wp
      Integer, Parameter               :: nout = 6
!     .. Local Scalars ..
      Type (c_ptr)                     :: cpuser, handle
      Real (Kind=nag_wp)               :: bigbnd
      Integer                          :: i, idlc, idx, ifail, ilinear, j,     &
                                          nclin, ncnln, nnzu, nvar, ry_ifail
      Character (60)                   :: opt_s
!     .. Local Arrays ..
      Real (Kind=nag_wp)               :: b(8), bl(4), bu(4), linbl(2),        &
                                          linbu(2), nlnbl(1), nlnbu(1),        &
                                          rinfo(32), ruser(4), stats(32), x(4)
      Real (Kind=nag_wp), Allocatable  :: u(:)
      Integer                          :: icolb(8), icolgd(4), icolh(10),      &
                                          idxfd(4), irowb(8), irowgd(4),       &
                                          irowh(10), iuser(2)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: int
!     .. Executable Statements ..

      Write (nout,*) 'E04STF Example Program Results'
      Write (nout,*)
      Flush (nout)

      ifail = 0
      Call x04acf(66,'e04stf.out',1,ifail)
      Call x04acf(67,'e04stf.mon',1,ifail)
      Call x04acf(68,'e04stf.umon',1,ifail)

      Do ilinear = 0, 1
        handle = c_null_ptr
        bigbnd = 1.0E40_nag_wp
        nvar = 4
        nnzu = 0
        Call e04raf(handle,nvar,ifail)

        Write (opt_s,99992) bigbnd
        Call e04zmf(handle,opt_s,ifail)

!       Add simple bounds (x_i>=0).
        bl(1:4) = 0.0_nag_wp
        bu(1:4) = bigbnd
        nnzu = nnzu + 2*nvar
        Call e04rhf(handle,nvar,bl,bu,ifail)

        iuser(1) = ilinear

!       Add linear objective
        ruser(1:4) = (/24.55_nag_wp,26.75_nag_wp,39.00_nag_wp,40.50_nag_wp/)
        If (ilinear==1) Then
          Call e04ref(handle,4,ruser(1:4),ifail)
        Else
          idxfd(1:4) = (/1,2,3,4/)
          Call e04rgf(handle,4,idxfd,ifail)
        End If

!       Add two linear constraints
        nclin = 2
        nnzu = nnzu + 2*nclin
        linbl(1:2) = (/5.0_nag_wp,1.0_nag_wp/)
        linbu(1:2) = (/bigbnd,1.0_nag_wp/)
        irowb(1:8) = (/1,1,1,1,2,2,2,2/)
        icolb(1:8) = (/1,2,3,4,1,2,3,4/)
        b(1:8) = (/2.3_nag_wp,5.6_nag_wp,11.1_nag_wp,1.3_nag_wp,1.0_nag_wp,    &
          1.0_nag_wp,1.0_nag_wp,1.0_nag_wp/)
        idlc = 0
        Call e04rjf(handle,nclin,linbl,linbu,nclin*nvar,irowb,icolb,b,idlc,    &
          ifail)

!       Add one nonlinear constraint
        ncnln = 1
        nnzu = nnzu + 2*ncnln
        nlnbl(1:1) = (/21.0_nag_wp/)
        nlnbu(1:1) = (/bigbnd/)
        irowgd(1:4) = (/1,1,1,1/)
        icolgd(1:4) = (/1,2,3,4/)
        Call e04rkf(handle,ncnln,nlnbl,nlnbu,4,irowgd,icolgd,ifail)

!       Define dense structure of the Hessian
        idx = 1
        Do i = 1, nvar
          Do j = i, nvar
            icolh(idx) = j
            irowh(idx) = i
            idx = idx + 1
          End Do
        End Do

!       Hessian of nonlinear constraint
        Call e04rlf(handle,1,idx-1,irowh,icolh,ifail)
        If (ilinear/=1) Then
          Call e04rlf(handle,0,idx-1,irowh,icolh,ifail)
        End If

        Call e04ryf(handle,nout,'Overview',ifail)

!       call solver
        x = (/1.0_nag_wp,1.0_nag_wp,1.0_nag_wp,1.0_nag_wp/)
        Allocate (u(nnzu))

        iuser(2) = 68
        Call e04zmf(handle,'Monitoring File = 67',ifail)
        Call e04zmf(handle,'Monitoring Level = 5',ifail)
        Call e04zmf(handle,'Outer Iteration Limit = 26',ifail)
        Call e04zmf(handle,'Print File = 66',ifail)
        Call e04zmf(handle,'Print Level = 2',ifail)
        Call e04zmf(handle,'Stop Tolerance 1 = 2.5e-8',ifail)
        Call e04zmf(handle,'Time Limit = 60',ifail)

        ifail = -1
        Call e04stf(handle,objfun,objgrd,confun,congrd,hess,mon,nvar,x,nnzu,u, &
          rinfo,stats,iuser,ruser,cpuser,ifail)

        ry_ifail = 0
        Call e04ryf(handle,nout,'Options',ry_ifail)

        If (ifail==0) Then
          Write (nout,99999)
          Write (nout,99995)(i,x(i),i=1,nvar)
          Write (nout,99998)
          Write (nout,99993)(i,u(2*i-1),i,u(2*i),i=1,nvar)
          Write (nout,99997)
          Write (nout,99994)(i,u(2*i-1+2*nvar),i,u(2*i+2*nvar),i=1,nclin)
          Write (nout,99996)
          Write (nout,99994)(i,u(2*i-1+2*nvar+2*nclin),i,                      &
            u(2*i+2*nvar+2*nclin),i=1,ncnln)
          Write (nout,99991) rinfo(1)
          Write (nout,99990) rinfo(2)
          Write (nout,99989) rinfo(3)
          Write (nout,99988) rinfo(4)
          Write (nout,99987) rinfo(5)
          If (stats(8)<solve_timeout) Then
            Write (nout,99986)
          Else
            Write (nout,99985) stats(8)
          End If
          Write (nout,99984) int(stats(1))
          Write (nout,99983) int(stats(19))
          Write (nout,99982) int(stats(5))
          Write (nout,99981) int(stats(20))
          Write (nout,99980) int(stats(21))
          Write (nout,99979) int(stats(4))
        End If

        ifail = 0
        Call e04ryf(handle,nout,'Overview',ifail)

99999   Format (/,'Variables')
99998   Format ('Variable bound Lagrange multipliers')
99997   Format ('Linear constraints Lagrange multipliers')
99996   Format ('Nonlinear constraints Lagrange multipliers')
99995   Format (5X,'x(',I10,')',17X,'=',1P,E20.6)
99994   Format (5X,'l+(',I10,')',16X,'=',1P,E20.6,/,5X,'l-(',I10,')',16X,'=',  &
          1P,E20.6)
99993   Format (5X,'zL(',I10,')',16X,'=',1P,E20.6,/,5X,'zU(',I10,')',16X,'=',  &
          1P,E20.6)
99992   Format ('Infinite Bound Size               = ',1P,E14.6)
99991   Format ('At solution, Objective minimum     =',1P,E20.7)
99990   Format ('             Constraint violation  =',1P,E20.2)
99989   Format ('             Dual infeasibility    =',1P,E20.2)
99988   Format ('             Complementarity       =',1P,E20.2)
99987   Format ('             KKT error             =',1P,E20.2)
99986   Format ('Solved in allotted time limit')
99985   Format ('Solution took ',E10.3,' sec, which is longer than expected')
99984   Format ('    after iterations                        :',I11)
99983   Format ('    after objective evaluations             :',I11)
99982   Format ('    after objective gradient evaluations    :',I11)
99981   Format ('    after constraint evaluations            :',I11)
99980   Format ('    after constraint gradient evaluations   :',I11)
99979   Format ('    after hessian evaluations               :',I11)
        Deallocate (u)
!       release all memory held in the handle
        Call e04rzf(handle,ifail)
        Write (nout,*) '---------------------------------------------'
      End Do
    End Program e04stfe


e04svfe.f90

    Program e04svfe

!     E04SVF Example Program Text
!     Mark 26 Release. NAG Copyright 2016.

!     Compute Lovasz theta number of the given graph G on the input
!     via semidefinite programming as
!       min {lambda_max(H) | H is nv x nv symmetric matrix where
!                            h_ij=1 if ij is not an edge or if i==j}

!     .. Use Statements ..
      Use nag_library, Only: e04raf, e04rff, e04rnf, e04rzf, e04svf, e04zmf,   &
                             e04znf, nag_wp
      Use, Intrinsic                   :: iso_c_binding, Only: c_null_ptr,     &
                                          c_ptr
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Type (c_ptr)                     :: h
      Real (Kind=nag_wp)               :: rvalue
      Integer                          :: dima, i, idblk, idx, ifail, inform,  &
                                          ivalue, j, maxe, nblk, ne, nnzasum,  &
                                          nnzu, nnzua, nnzuc, nv, nvar, optype
      Character (40)                   :: cvalue
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: a(:), x(:)
      Real (Kind=nag_wp)               :: rdummy(1), rinfo(32), stats(32)
      Integer, Allocatable             :: blksizea(:), icola(:), irowa(:),     &
                                          nnza(:), va(:), vb(:)
      Integer                          :: idummy(1)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: trim
!     .. Executable Statements ..
      Continue

      Write (nout,*) 'E04SVF Example Program Results'
      Write (nout,*)
      Flush (nout)

!     Skip heading in data file.
      Read (nin,*)

!     Read in the number of vertices and edges of the graph.
      Read (nin,*) nv
      Read (nin,*) ne

      Allocate (va(ne),vb(ne))

!     Read in edges of the graph, accept only 1<=i<j<=nv.
      maxe = ne
      ne = 0
      Do idx = 1, maxe
        Read (nin,*) i, j
        If (i>=1 .And. i<j .And. j<=nv) Then
          ne = ne + 1
          va(ne) = i
          vb(ne) = j
        End If
      End Do

!     Initialize handle.
      h = c_null_ptr

!     Number of variables (same as edges in the graph plus one).
      nvar = ne + 1

!     Initialize an empty problem handle with NVAR variables.
      ifail = 0
      Call e04raf(h,nvar,ifail)

!     Add the objective function to the handle.
      ifail = 0
      Call e04rff(h,1,(/1/),(/1.0_nag_wp/),0,idummy,idummy,rdummy,ifail)

!     Generate matrix constraint as:
!       sum_{ij is edge in G} x_ij*E_ij + t*I - J >=0
!     where J is the all-ones matrix.

!     Just one matrix inequality.
      nblk = 1
      dima = nv

!     Total number of nonzeros
      nnzasum = ne + nv + (nv+1)*nv/2

      Allocate (nnza(nvar+1),irowa(nnzasum),icola(nnzasum),a(nnzasum),x(nvar))
!     A_0 is all ones matrix
      nnza(1) = (nv+1)*nv/2
      idx = 0
      Do i = 1, nv
        Do j = i, nv
          idx = idx + 1
          irowa(idx) = i
          icola(idx) = j
          a(idx) = 1.0_nag_wp
        End Do
      End Do
!     A_1 is the identity
      nnza(2) = nv
      Do i = 1, nv
        idx = idx + 1
        irowa(idx) = i
        icola(idx) = i
        a(idx) = 1.0_nag_wp
      End Do
!     A_2, A_3, ..., A_{ne+1} match the E_ij matrices
      nnza(3:ne+2) = 1
      Do i = 1, ne
        idx = idx + 1
        irowa(idx) = va(i)
        icola(idx) = vb(i)
        a(idx) = 1.0_nag_wp
      End Do

!     Add the constraint to the problem formulation.
      Allocate (blksizea(nblk))
      blksizea(:) = (/dima/)

      idblk = 0
      ifail = 0
      Call e04rnf(h,nvar,dima,nnza,nnzasum,irowa,icola,a,nblk,blksizea,idblk,  &
        ifail)

!     Set optional arguments of the solver.
      ifail = 0
      Call e04zmf(h,'Initial X = Automatic',ifail)

!     Pass the handle to the solver, we are not interested in
!     Lagrangian multipliers.
      nnzu = 0
      nnzuc = 0
      nnzua = 0
      ifail = -1
      Call e04svf(h,nvar,x,nnzu,rdummy,nnzuc,rdummy,nnzua,rdummy,rinfo,stats,  &
        inform,ifail)

      If (ifail==0 .Or. ifail==50) Then
!       Retrieve some of the settings
        ifail = 0
        Call e04znf(h,'Hessian Density',ivalue,rvalue,cvalue,optype,ifail)
        Write (nout,*) 'The solver chose to use ', trim(cvalue), ' hessian'
        ifail = 0
        Call e04znf(h,'Linesearch Mode',ivalue,rvalue,cvalue,optype,ifail)
        Write (nout,*) 'and ', trim(cvalue), ' as linesearch.'

        Write (nout,Fmt=99999) 'Lovasz theta number of the given graph is',    &
          rinfo(1)
      End If

!     Destroy the handle.
      ifail = 0
      Call e04rzf(h,ifail)

99999 Format (1X,A,1X,F7.2)
    End Program e04svfe


e04ucae.f90

!   E04UCA Example Program Text
!   Mark 26 Release. NAG Copyright 2016.

    Module e04ucae_mod

!     E04UCA Example Program Module:
!            Parameters and User-defined Routines

!     .. Use Statements ..
      Use nag_library, Only: nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Accessibility Statements ..
      Private
      Public                           :: confun, objfun
!     .. Parameters ..
      Real (Kind=nag_wp), Parameter, Public :: one = 1.0_nag_wp
      Real (Kind=nag_wp), Parameter, Public :: zero = 0.0_nag_wp
      Integer, Parameter, Public       :: inc1 = 1, lcwsav = 1, liwsav = 610,  &
                                          llwsav = 120, lrwsav = 475, nin = 5, &
                                          nout = 6
    Contains
      Subroutine objfun(mode,n,x,objf,objgrd,nstate,iuser,ruser)
!       Routine to evaluate objective function and its 1st derivatives.

!       .. Scalar Arguments ..
        Real (Kind=nag_wp), Intent (Out) :: objf
        Integer, Intent (Inout)        :: mode
        Integer, Intent (In)           :: n, nstate
!       .. Array Arguments ..
        Real (Kind=nag_wp), Intent (Inout) :: objgrd(n), ruser(*)
        Real (Kind=nag_wp), Intent (In) :: x(n)
        Integer, Intent (Inout)        :: iuser(*)
!       .. Executable Statements ..
        If (mode==0 .Or. mode==2) Then
          objf = x(1)*x(4)*(x(1)+x(2)+x(3)) + x(3)
        End If

        If (mode==1 .Or. mode==2) Then
          objgrd(1) = x(4)*(x(1)+x(1)+x(2)+x(3))
          objgrd(2) = x(1)*x(4)
          objgrd(3) = x(1)*x(4) + one
          objgrd(4) = x(1)*(x(1)+x(2)+x(3))
        End If

        Return

      End Subroutine objfun
      Subroutine confun(mode,ncnln,n,ldcj,needc,x,c,cjac,nstate,iuser,ruser)
!       Routine to evaluate the nonlinear constraints and their 1st
!       derivatives.

!       .. Scalar Arguments ..
        Integer, Intent (In)           :: ldcj, n, ncnln, nstate
        Integer, Intent (Inout)        :: mode
!       .. Array Arguments ..
        Real (Kind=nag_wp), Intent (Out) :: c(ncnln)
        Real (Kind=nag_wp), Intent (Inout) :: cjac(ldcj,n), ruser(*)
        Real (Kind=nag_wp), Intent (In) :: x(n)
        Integer, Intent (Inout)        :: iuser(*)
        Integer, Intent (In)           :: needc(ncnln)
!       .. Executable Statements ..
        If (nstate==1) Then

!         First call to CONFUN.  Set all Jacobian elements to zero.
!         Note that this will only work when 'Derivative Level = 3'
!         (the default; see Section 11.2).

          cjac(1:ncnln,1:n) = zero
        End If

        If (needc(1)>0) Then

          If (mode==0 .Or. mode==2) Then
            c(1) = x(1)**2 + x(2)**2 + x(3)**2 + x(4)**2
          End If

          If (mode==1 .Or. mode==2) Then
            cjac(1,1) = x(1) + x(1)
            cjac(1,2) = x(2) + x(2)
            cjac(1,3) = x(3) + x(3)
            cjac(1,4) = x(4) + x(4)
          End If

        End If

        If (needc(2)>0) Then

          If (mode==0 .Or. mode==2) Then
            c(2) = x(1)*x(2)*x(3)*x(4)
          End If

          If (mode==1 .Or. mode==2) Then
            cjac(2,1) = x(2)*x(3)*x(4)
            cjac(2,2) = x(1)*x(3)*x(4)
            cjac(2,3) = x(1)*x(2)*x(4)
            cjac(2,4) = x(1)*x(2)*x(3)
          End If

        End If

        Return

      End Subroutine confun
    End Module e04ucae_mod
    Program e04ucae

!     E04UCA Example Main Program

!     .. Use Statements ..
      Use nag_library, Only: dgemv, e04uca, e04wbf, nag_wp
      Use e04ucae_mod, Only: confun, inc1, lcwsav, liwsav, llwsav, lrwsav,     &
                             nin, nout, objfun, one, zero
!     .. Implicit None Statement ..
      Implicit None
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: objf
      Integer                          :: i, ifail, iter, j, lda, ldcj, ldr,   &
                                          liwork, lwork, n, nclin, ncnln, sda, &
                                          sdcjac
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: a(:,:), bl(:), bu(:), c(:),          &
                                          cjac(:,:), clamda(:), objgrd(:),     &
                                          r(:,:), work(:), x(:)
      Real (Kind=nag_wp)               :: ruser(1), rwsav(lrwsav)
      Integer, Allocatable             :: istate(:), iwork(:)
      Integer                          :: iuser(1), iwsav(liwsav)
      Logical                          :: lwsav(llwsav)
      Character (80)                   :: cwsav(lcwsav)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: max
!     .. Executable Statements ..
      Write (nout,*) 'E04UCA Example Program Results'

!     Skip heading in data file
      Read (nin,*)

      Read (nin,*) n, nclin, ncnln
      liwork = 3*n + nclin + 2*ncnln
      lda = max(1,nclin)

      If (nclin>0) Then
        sda = n
      Else
        sda = 1
      End If

      ldcj = max(1,ncnln)

      If (ncnln>0) Then
        sdcjac = n
      Else
        sdcjac = 1
      End If

      ldr = n

      If (ncnln==0 .And. nclin>0) Then
        lwork = 2*n**2 + 20*n + 11*nclin
      Else If (ncnln>0 .And. nclin>=0) Then
        lwork = 2*n**2 + n*nclin + 2*n*ncnln + 20*n + 11*nclin + 21*ncnln
      Else
        lwork = 20*n
      End If

      Allocate (istate(n+nclin+ncnln),iwork(liwork),a(lda,sda),                &
        bl(n+nclin+ncnln),bu(n+nclin+ncnln),c(max(1,                           &
        ncnln)),cjac(ldcj,sdcjac),clamda(n+nclin+ncnln),objgrd(n),r(ldr,n),    &
        x(n),work(lwork))

      If (nclin>0) Then
        Read (nin,*)(a(i,1:sda),i=1,nclin)
      End If

      Read (nin,*) bl(1:(n+nclin+ncnln))
      Read (nin,*) bu(1:(n+nclin+ncnln))
      Read (nin,*) x(1:n)

!     Initialise E04UCA

      ifail = 0
      Call e04wbf('E04UCA',cwsav,lcwsav,lwsav,llwsav,iwsav,liwsav,rwsav,       &
        lrwsav,ifail)

!     Solve the problem

      ifail = -1
      Call e04uca(n,nclin,ncnln,lda,ldcj,ldr,a,bl,bu,confun,objfun,iter,       &
        istate,c,cjac,clamda,objf,objgrd,r,x,iwork,liwork,work,lwork,iuser,    &
        ruser,lwsav,iwsav,rwsav,ifail)

      Select Case (ifail)
      Case (0:6,8)
        Write (nout,*)
        Write (nout,99999)
        Write (nout,*)

        Do i = 1, n
          Write (nout,99998) i, istate(i), x(i), clamda(i)
        End Do

        If (nclin>0) Then

!         A*x --> work.
!         The NAG name equivalent of dgemv is f06paf
          Call dgemv('N',nclin,n,one,a,lda,x,inc1,zero,work,inc1)

          Write (nout,*)
          Write (nout,*)
          Write (nout,99997)
          Write (nout,*)

          Do i = n + 1, n + nclin
            j = i - n
            Write (nout,99996) j, istate(i), work(j), clamda(i)
          End Do

        End If

        If (ncnln>0) Then
          Write (nout,*)
          Write (nout,*)
          Write (nout,99995)
          Write (nout,*)

          Do i = n + nclin + 1, n + nclin + ncnln
            j = i - n - nclin
            Write (nout,99994) j, istate(i), c(j), clamda(i)
          End Do

        End If

        Write (nout,*)
        Write (nout,*)
        Write (nout,99993) objf
      End Select

99999 Format (1X,'Varbl',2X,'Istate',3X,'Value',9X,'Lagr Mult')
99998 Format (1X,'V',2(1X,I3),4X,1P,G14.6,2X,1P,G12.4)
99997 Format (1X,'L Con',2X,'Istate',3X,'Value',9X,'Lagr Mult')
99996 Format (1X,'L',2(1X,I3),4X,1P,G14.6,2X,1P,G12.4)
99995 Format (1X,'N Con',2X,'Istate',3X,'Value',9X,'Lagr Mult')
99994 Format (1X,'N',2(1X,I3),4X,1P,G14.6,2X,1P,G12.4)
99993 Format (1X,'Final objective value = ',1P,G15.7)
    End Program e04ucae


e04ucfe.f90

!   E04UCF Example Program Text
!   Mark 26 Release. NAG Copyright 2016.

    Module e04ucfe_mod

!     E04UCF Example Program Module:
!            Parameters and User-defined Routines

!     .. Use Statements ..
      Use nag_library, Only: nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Accessibility Statements ..
      Private
      Public                           :: confun, objfun
!     .. Parameters ..
      Integer, Parameter, Public       :: nin = 5, nout = 6
    Contains
      Subroutine objfun(mode,n,x,objf,objgrd,nstate,iuser,ruser)
!       Routine to evaluate objective function and its 1st derivatives.

!       .. Scalar Arguments ..
        Real (Kind=nag_wp), Intent (Out) :: objf
        Integer, Intent (Inout)        :: mode
        Integer, Intent (In)           :: n, nstate
!       .. Array Arguments ..
        Real (Kind=nag_wp), Intent (Inout) :: objgrd(n), ruser(*)
        Real (Kind=nag_wp), Intent (In) :: x(n)
        Integer, Intent (Inout)        :: iuser(*)
!       .. Executable Statements ..
        If (mode==0 .Or. mode==2) Then
          objf = x(1)*x(4)*(x(1)+x(2)+x(3)) + x(3)
        End If

        If (mode==1 .Or. mode==2) Then
          objgrd(1) = x(4)*(2.0E0_nag_wp*x(1)+x(2)+x(3))
          objgrd(2) = x(1)*x(4)
          objgrd(3) = x(1)*x(4) + 1.0E0_nag_wp
          objgrd(4) = x(1)*(x(1)+x(2)+x(3))
        End If

        Return

      End Subroutine objfun
      Subroutine confun(mode,ncnln,n,ldcj,needc,x,c,cjac,nstate,iuser,ruser)
!       Routine to evaluate the nonlinear constraints and their 1st
!       derivatives.

!       .. Scalar Arguments ..
        Integer, Intent (In)           :: ldcj, n, ncnln, nstate
        Integer, Intent (Inout)        :: mode
!       .. Array Arguments ..
        Real (Kind=nag_wp), Intent (Out) :: c(ncnln)
        Real (Kind=nag_wp), Intent (Inout) :: cjac(ldcj,n), ruser(*)
        Real (Kind=nag_wp), Intent (In) :: x(n)
        Integer, Intent (Inout)        :: iuser(*)
        Integer, Intent (In)           :: needc(ncnln)
!       .. Executable Statements ..
        If (nstate==1) Then

!         First call to CONFUN.  Set all Jacobian elements to zero.
!         Note that this will only work when 'Derivative Level = 3'
!         (the default; see Section 11.2).

          cjac(1:ncnln,1:n) = 0.0E0_nag_wp
        End If

        If (needc(1)>0) Then

          If (mode==0 .Or. mode==2) Then
            c(1) = x(1)**2 + x(2)**2 + x(3)**2 + x(4)**2
          End If

          If (mode==1 .Or. mode==2) Then
            cjac(1,1) = 2.0E0_nag_wp*x(1)
            cjac(1,2) = 2.0E0_nag_wp*x(2)
            cjac(1,3) = 2.0E0_nag_wp*x(3)
            cjac(1,4) = 2.0E0_nag_wp*x(4)
          End If

        End If

        If (needc(2)>0) Then

          If (mode==0 .Or. mode==2) Then
            c(2) = x(1)*x(2)*x(3)*x(4)
          End If

          If (mode==1 .Or. mode==2) Then
            cjac(2,1) = x(2)*x(3)*x(4)
            cjac(2,2) = x(1)*x(3)*x(4)
            cjac(2,3) = x(1)*x(2)*x(4)
            cjac(2,4) = x(1)*x(2)*x(3)
          End If

        End If

        Return

      End Subroutine confun
    End Module e04ucfe_mod
    Program e04ucfe

!     E04UCF Example Main Program

!     .. Use Statements ..
      Use nag_library, Only: e04ucf, nag_wp
      Use e04ucfe_mod, Only: confun, nin, nout, objfun
!     .. Implicit None Statement ..
      Implicit None
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: objf
      Integer                          :: i, ifail, iter, lda, ldcj, ldr,      &
                                          liwork, lwork, n, nclin, ncnln, sda, &
                                          sdcjac
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: a(:,:), bl(:), bu(:), c(:),          &
                                          cjac(:,:), clamda(:), objgrd(:),     &
                                          r(:,:), work(:), x(:)
      Real (Kind=nag_wp)               :: ruser(1)
      Integer, Allocatable             :: istate(:), iwork(:)
      Integer                          :: iuser(1)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: max
!     .. Executable Statements ..
      Write (nout,*) 'E04UCF Example Program Results'
      Flush (nout)

!     Skip heading in data file
      Read (nin,*)

      Read (nin,*) n, nclin, ncnln
      liwork = 3*n + nclin + 2*ncnln
      lda = max(1,nclin)

      If (nclin>0) Then
        sda = n
      Else
        sda = 1
      End If

      ldcj = max(1,ncnln)

      If (ncnln>0) Then
        sdcjac = n
      Else
        sdcjac = 1
      End If

      ldr = n

      If (ncnln==0 .And. nclin>0) Then
        lwork = 2*n**2 + 20*n + 11*nclin
      Else If (ncnln>0 .And. nclin>=0) Then
        lwork = 2*n**2 + n*nclin + 2*n*ncnln + 20*n + 11*nclin + 21*ncnln
      Else
        lwork = 20*n
      End If

      Allocate (istate(n+nclin+ncnln),iwork(liwork),a(lda,sda),                &
        bl(n+nclin+ncnln),bu(n+nclin+ncnln),c(max(1,                           &
        ncnln)),cjac(ldcj,sdcjac),clamda(n+nclin+ncnln),objgrd(n),r(ldr,n),    &
        x(n),work(lwork))

      If (nclin>0) Then
        Read (nin,*)(a(i,1:sda),i=1,nclin)
      End If

      Read (nin,*) bl(1:(n+nclin+ncnln))
      Read (nin,*) bu(1:(n+nclin+ncnln))
      Read (nin,*) x(1:n)

      ifail = 0
      Call e04ucf(n,nclin,ncnln,lda,ldcj,ldr,a,bl,bu,confun,objfun,iter,       &
        istate,c,cjac,clamda,objf,objgrd,r,x,iwork,liwork,work,lwork,iuser,    &
        ruser,ifail)

    End Program e04ucfe


e04udae.f90

!   E04UDA Example Program Text
!   Mark 26 Release. NAG Copyright 2016.

    Module e04udae_mod

!     E04UDA Example Program Module:
!            Parameters and User-defined Routines

!     .. Use Statements ..
      Use nag_library, Only: nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Accessibility Statements ..
      Private
      Public                           :: confun, objfun
!     .. Parameters ..
      Real (Kind=nag_wp), Parameter, Public :: one = 1.0_nag_wp
      Real (Kind=nag_wp), Parameter, Public :: zero = 0.0_nag_wp
      Integer, Parameter, Public       :: inc1 = 1, iset = 1, lcwsav = 1,      &
                                          liwsav = 610, llwsav = 120,          &
                                          lrwsav = 475, nin = 5, ninopt = 7,   &
                                          nout = 6
    Contains
      Subroutine objfun(mode,n,x,objf,objgrd,nstate,iuser,ruser)
!       Routine to evaluate objective function and its 1st derivatives.

!       .. Scalar Arguments ..
        Real (Kind=nag_wp), Intent (Out) :: objf
        Integer, Intent (Inout)        :: mode
        Integer, Intent (In)           :: n, nstate
!       .. Array Arguments ..
        Real (Kind=nag_wp), Intent (Inout) :: objgrd(n), ruser(*)
        Real (Kind=nag_wp), Intent (In) :: x(n)
        Integer, Intent (Inout)        :: iuser(*)
!       .. Executable Statements ..
        If (mode==0 .Or. mode==2) Then
          objf = x(1)*x(4)*(x(1)+x(2)+x(3)) + x(3)
        End If

        If (mode==1 .Or. mode==2) Then
          objgrd(1) = x(4)*(x(1)+x(1)+x(2)+x(3))
          objgrd(2) = x(1)*x(4)
          objgrd(3) = x(1)*x(4) + one
          objgrd(4) = x(1)*(x(1)+x(2)+x(3))
        End If

        Return

      End Subroutine objfun
      Subroutine confun(mode,ncnln,n,ldcj,needc,x,c,cjac,nstate,iuser,ruser)
!       Routine to evaluate the nonlinear constraints and their 1st
!       derivatives.

!       .. Scalar Arguments ..
        Integer, Intent (In)           :: ldcj, n, ncnln, nstate
        Integer, Intent (Inout)        :: mode
!       .. Array Arguments ..
        Real (Kind=nag_wp), Intent (Out) :: c(ncnln)
        Real (Kind=nag_wp), Intent (Inout) :: cjac(ldcj,n), ruser(*)
        Real (Kind=nag_wp), Intent (In) :: x(n)
        Integer, Intent (Inout)        :: iuser(*)
        Integer, Intent (In)           :: needc(ncnln)
!       .. Executable Statements ..
        If (nstate==1) Then

!         First call to CONFUN.  Set all Jacobian elements to zero.
!         Note that this will only work when 'Derivative Level = 3'
!         (the default; see Section 11.2).

          cjac(1:ncnln,1:n) = zero
        End If

        If (needc(1)>0) Then

          If (mode==0 .Or. mode==2) Then
            c(1) = x(1)**2 + x(2)**2 + x(3)**2 + x(4)**2
          End If

          If (mode==1 .Or. mode==2) Then
            cjac(1,1) = x(1) + x(1)
            cjac(1,2) = x(2) + x(2)
            cjac(1,3) = x(3) + x(3)
            cjac(1,4) = x(4) + x(4)
          End If

        End If

        If (needc(2)>0) Then

          If (mode==0 .Or. mode==2) Then
            c(2) = x(1)*x(2)*x(3)*x(4)
          End If

          If (mode==1 .Or. mode==2) Then
            cjac(2,1) = x(2)*x(3)*x(4)
            cjac(2,2) = x(1)*x(3)*x(4)
            cjac(2,3) = x(1)*x(2)*x(4)
            cjac(2,4) = x(1)*x(2)*x(3)
          End If

        End If

        Return

      End Subroutine confun
    End Module e04udae_mod
    Program e04udae

!     E04UDA Example Main Program

!     .. Use Statements ..
      Use nag_library, Only: dgemv, e04uca, e04uda, e04uea, e04wbf, nag_wp,    &
                             x04abf, x04acf, x04baf
      Use e04udae_mod, Only: confun, inc1, iset, lcwsav, liwsav, llwsav,       &
                             lrwsav, nin, ninopt, nout, objfun, one, zero
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Character (*), Parameter         :: fname = 'e04udae.opt'
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: objf
      Integer                          :: i, ifail, inform, iter, j, lda,      &
                                          ldcj, ldr, liwork, lwork, mode, n,   &
                                          nclin, ncnln, outchn, sda, sdcjac
      Character (80)                   :: rec
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: a(:,:), bl(:), bu(:), c(:),          &
                                          cjac(:,:), clamda(:), objgrd(:),     &
                                          r(:,:), work(:), x(:)
      Real (Kind=nag_wp)               :: ruser(1), rwsav(lrwsav)
      Integer, Allocatable             :: istate(:), iwork(:)
      Integer                          :: iuser(1), iwsav(liwsav)
      Logical                          :: lwsav(llwsav)
      Character (80)                   :: cwsav(lcwsav)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: max
!     .. Executable Statements ..
      Write (rec,99991) 'E04UDA Example Program Results'
      Call x04baf(nout,rec)

!     Skip heading in data file
      Read (nin,*)

      Read (nin,*) n, nclin, ncnln
      liwork = 3*n + nclin + 2*ncnln
      lda = max(1,nclin)

      If (nclin>0) Then
        sda = n
      Else
        sda = 1
      End If

      ldcj = max(1,ncnln)

      If (ncnln>0) Then
        sdcjac = n
      Else
        sdcjac = 1
      End If

      ldr = n

      If (ncnln==0 .And. nclin>0) Then
        lwork = 2*n**2 + 20*n + 11*nclin
      Else If (ncnln>0 .And. nclin>=0) Then
        lwork = 2*n**2 + n*nclin + 2*n*ncnln + 20*n + 11*nclin + 21*ncnln
      Else
        lwork = 20*n
      End If

      Allocate (istate(n+nclin+ncnln),iwork(liwork),a(lda,sda),                &
        bl(n+nclin+ncnln),bu(n+nclin+ncnln),c(max(1,                           &
        ncnln)),cjac(ldcj,sdcjac),clamda(n+nclin+ncnln),objgrd(n),r(ldr,n),    &
        x(n),work(lwork))

      If (nclin>0) Then
        Read (nin,*)(a(i,1:sda),i=1,nclin)
      End If

      Read (nin,*) bl(1:(n+nclin+ncnln))
      Read (nin,*) bu(1:(n+nclin+ncnln))
      Read (nin,*) x(1:n)

!     Set the unit number for advisory messages to OUTCHN

      outchn = nout
      Call x04abf(iset,outchn)

!     Initialise E04UCA

      ifail = 0
      Call e04wbf('E04UCA',cwsav,lcwsav,lwsav,llwsav,iwsav,liwsav,rwsav,       &
        lrwsav,ifail)

!     Set two options using E04UEA

      Call e04uea(' Infinite Bound Size = 1.0D+25 ',lwsav,iwsav,rwsav,inform)

      If (inform==0) Then

        Call e04uea(' Verify Level = -1 ',lwsav,iwsav,rwsav,inform)

      End If

      If (inform/=0) Then
        Write (rec,99999) 'E04UEA terminated with ' // 'INFORM = ', inform
        Call x04baf(nout,rec)
        Go To 100
      End If

!     Open the options file for reading

      mode = 0

      ifail = 0
      Call x04acf(ninopt,fname,mode,ifail)

!     Read the options file for the remaining options

      Call e04uda(ninopt,lwsav,iwsav,rwsav,inform)

      If (inform/=0) Then
        Write (rec,99999) 'E04UDA terminated with ' // 'INFORM = ', inform
        Call x04baf(nout,rec)
      End If

!     Solve the problem

      ifail = -1
      Call e04uca(n,nclin,ncnln,lda,ldcj,ldr,a,bl,bu,confun,objfun,iter,       &
        istate,c,cjac,clamda,objf,objgrd,r,x,iwork,liwork,work,lwork,iuser,    &
        ruser,lwsav,iwsav,rwsav,ifail)

      Select Case (ifail)
      Case (0:6,8)
        Write (rec,'()')
        Call x04baf(nout,rec)
        Write (rec,99998)
        Call x04baf(nout,rec)
        Write (rec,'()')
        Call x04baf(nout,rec)

        Do i = 1, n
          Write (rec,99997) i, istate(i), x(i), clamda(i)
          Call x04baf(nout,rec)
        End Do

        If (nclin>0) Then

!         A*x --> work.
!         The NAG name equivalent of dgemv is f06paf
          Call dgemv('N',nclin,n,one,a,lda,x,inc1,zero,work,inc1)

          Write (rec,'()')
          Call x04baf(nout,rec)
          Write (rec,'()')
          Call x04baf(nout,rec)
          Write (rec,99996)
          Call x04baf(nout,rec)
          Write (rec,'()')
          Call x04baf(nout,rec)

          Do i = n + 1, n + nclin
            j = i - n
            Write (rec,99995) j, istate(i), work(j), clamda(i)
            Call x04baf(nout,rec)
          End Do

        End If

        If (ncnln>0) Then
          Write (rec,'()')
          Call x04baf(nout,rec)
          Write (rec,'()')
          Call x04baf(nout,rec)
          Write (rec,99994)
          Call x04baf(nout,rec)
          Write (rec,'()')
          Call x04baf(nout,rec)

          Do i = n + nclin + 1, n + nclin + ncnln
            j = i - n - nclin
            Write (rec,99993) j, istate(i), c(j), clamda(i)
            Call x04baf(nout,rec)
          End Do

        End If

        Write (rec,'()')
        Call x04baf(nout,rec)
        Write (rec,'()')
        Call x04baf(nout,rec)
        Write (rec,99992) objf
        Call x04baf(nout,rec)
      End Select

100   Continue

99999 Format (1X,A,I5)
99998 Format (1X,'Varbl',2X,'Istate',3X,'Value',9X,'Lagr Mult')
99997 Format (1X,'V',2(1X,I3),4X,1P,G14.6,2X,1P,G12.4)
99996 Format (1X,'L Con',2X,'Istate',3X,'Value',9X,'Lagr Mult')
99995 Format (1X,'L',2(1X,I3),4X,1P,G14.6,2X,1P,G12.4)
99994 Format (1X,'N Con',2X,'Istate',3X,'Value',9X,'Lagr Mult')
99993 Format (1X,'N',2(1X,I3),4X,1P,G14.6,2X,1P,G12.4)
99992 Format (1X,'Final objective value = ',1P,G15.7)
99991 Format (1X,A)
    End Program e04udae


e04udfe.f90

!   E04UDF Example Program Text
!   Mark 26 Release. NAG Copyright 2016.

    Module e04udfe_mod

!     E04UDF Example Program Module:
!            Parameters and User-defined Routines

!     .. Use Statements ..
      Use nag_library, Only: nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Accessibility Statements ..
      Private
      Public                           :: confun, objfun
!     .. Parameters ..
      Integer, Parameter, Public       :: iset = 1, nin = 5, ninopt = 7,       &
                                          nout = 6
    Contains
      Subroutine objfun(mode,n,x,objf,objgrd,nstate,iuser,ruser)
!       Routine to evaluate objective function and its 1st derivatives.

!       .. Scalar Arguments ..
        Real (Kind=nag_wp), Intent (Out) :: objf
        Integer, Intent (Inout)        :: mode
        Integer, Intent (In)           :: n, nstate
!       .. Array Arguments ..
        Real (Kind=nag_wp), Intent (Inout) :: objgrd(n), ruser(*)
        Real (Kind=nag_wp), Intent (In) :: x(n)
        Integer, Intent (Inout)        :: iuser(*)
!       .. Executable Statements ..
        If (mode==0 .Or. mode==2) Then
          objf = x(1)*x(4)*(x(1)+x(2)+x(3)) + x(3)
        End If

        If (mode==1 .Or. mode==2) Then
          objgrd(1) = x(4)*(2.0E0_nag_wp*x(1)+x(2)+x(3))
          objgrd(2) = x(1)*x(4)
          objgrd(3) = x(1)*x(4) + 1.0E0_nag_wp
          objgrd(4) = x(1)*(x(1)+x(2)+x(3))
        End If

        Return

      End Subroutine objfun
      Subroutine confun(mode,ncnln,n,ldcj,needc,x,c,cjac,nstate,iuser,ruser)
!       Routine to evaluate the nonlinear constraints and their 1st
!       derivatives.

!       .. Scalar Arguments ..
        Integer, Intent (In)           :: ldcj, n, ncnln, nstate
        Integer, Intent (Inout)        :: mode
!       .. Array Arguments ..
        Real (Kind=nag_wp), Intent (Out) :: c(ncnln)
        Real (Kind=nag_wp), Intent (Inout) :: cjac(ldcj,n), ruser(*)
        Real (Kind=nag_wp), Intent (In) :: x(n)
        Integer, Intent (Inout)        :: iuser(*)
        Integer, Intent (In)           :: needc(ncnln)
!       .. Executable Statements ..
        If (nstate==1) Then

!         First call to CONFUN.  Set all Jacobian elements to zero.
!         Note that this will only work when 'Derivative Level = 3'
!         (the default; see Section 11.2).

          cjac(1:ncnln,1:n) = 0.0E0_nag_wp
        End If

        If (needc(1)>0) Then

          If (mode==0 .Or. mode==2) Then
            c(1) = x(1)**2 + x(2)**2 + x(3)**2 + x(4)**2
          End If

          If (mode==1 .Or. mode==2) Then
            cjac(1,1) = 2.0E0_nag_wp*x(1)
            cjac(1,2) = 2.0E0_nag_wp*x(2)
            cjac(1,3) = 2.0E0_nag_wp*x(3)
            cjac(1,4) = 2.0E0_nag_wp*x(4)
          End If

        End If

        If (needc(2)>0) Then

          If (mode==0 .Or. mode==2) Then
            c(2) = x(1)*x(2)*x(3)*x(4)
          End If

          If (mode==1 .Or. mode==2) Then
            cjac(2,1) = x(2)*x(3)*x(4)
            cjac(2,2) = x(1)*x(3)*x(4)
            cjac(2,3) = x(1)*x(2)*x(4)
            cjac(2,4) = x(1)*x(2)*x(3)
          End If

        End If

        Return

      End Subroutine confun
    End Module e04udfe_mod
    Program e04udfe

!     E04UDF Example Main Program

!     .. Use Statements ..
      Use nag_library, Only: e04ucf, e04udf, e04uef, nag_wp, x04abf, x04acf,   &
                             x04baf
      Use e04udfe_mod, Only: confun, iset, nin, ninopt, nout, objfun
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Character (*), Parameter         :: fname = 'e04udfe.opt'
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: objf
      Integer                          :: i, ifail, inform, iter, lda, ldcj,   &
                                          ldr, liwork, lwork, mode, n, nclin,  &
                                          ncnln, outchn, sda, sdcjac
      Character (80)                   :: rec
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: a(:,:), bl(:), bu(:), c(:),          &
                                          cjac(:,:), clamda(:), objgrd(:),     &
                                          r(:,:), work(:), x(:)
      Real (Kind=nag_wp)               :: ruser(1)
      Integer, Allocatable             :: istate(:), iwork(:)
      Integer                          :: iuser(1)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: max
!     .. Executable Statements ..
      Write (rec,99998) 'E04UDF Example Program Results'
      Call x04baf(nout,rec)

!     Skip heading in data file
      Read (nin,*)

      Read (nin,*) n, nclin, ncnln
      liwork = 3*n + nclin + 2*ncnln
      lda = max(1,nclin)

      If (nclin>0) Then
        sda = n
      Else
        sda = 1
      End If

      ldcj = max(1,ncnln)

      If (ncnln>0) Then
        sdcjac = n
      Else
        sdcjac = 1
      End If

      ldr = n

      If (ncnln==0 .And. nclin>0) Then
        lwork = 2*n**2 + 20*n + 11*nclin
      Else If (ncnln>0 .And. nclin>=0) Then
        lwork = 2*n**2 + n*nclin + 2*n*ncnln + 20*n + 11*nclin + 21*ncnln
      Else
        lwork = 20*n
      End If

      Allocate (istate(n+nclin+ncnln),iwork(liwork),a(lda,sda),                &
        bl(n+nclin+ncnln),bu(n+nclin+ncnln),c(max(1,                           &
        ncnln)),cjac(ldcj,sdcjac),clamda(n+nclin+ncnln),objgrd(n),r(ldr,n),    &
        x(n),work(lwork))

      If (nclin>0) Then
        Read (nin,*)(a(i,1:sda),i=1,nclin)
      End If

      Read (nin,*) bl(1:(n+nclin+ncnln))
      Read (nin,*) bu(1:(n+nclin+ncnln))
      Read (nin,*) x(1:n)

!     Set the unit number for advisory messages to OUTCHN

      outchn = nout
      Call x04abf(iset,outchn)

!     Set three options using E04UEF

      Call e04uef(' Infinite Bound Size = 1.0D+25 ')

      Call e04uef(' Print Level = 1 ')

      Call e04uef(' Verify Level = -1 ')

!     Open the options file for reading

      mode = 0

      ifail = 0
      Call x04acf(ninopt,fname,mode,ifail)

!     Read the options file for the remaining options

      Call e04udf(ninopt,inform)

      If (inform/=0) Then
        Write (rec,99999) 'E04UDF terminated with ' // 'INFORM = ', inform
        Call x04baf(nout,rec)
      End If

!     Solve the problem

      ifail = 0
      Call e04ucf(n,nclin,ncnln,lda,ldcj,ldr,a,bl,bu,confun,objfun,iter,       &
        istate,c,cjac,clamda,objf,objgrd,r,x,iwork,liwork,work,lwork,iuser,    &
        ruser,ifail)

99999 Format (1X,A,I5)
99998 Format (1X,A)
    End Program e04udfe


e04ufae.f90

    Program e04ufae

!     E04UFA Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: dgemv, e04ufa, e04wbf, nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Real (Kind=nag_wp), Parameter    :: one = 1.0_nag_wp
      Real (Kind=nag_wp), Parameter    :: zero = 0.0_nag_wp
      Integer, Parameter               :: inc1 = 1, lcwsav = 5, liwsav = 610,  &
                                          llwsav = 120, lrwsav = 475, nin = 5, &
                                          nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: objf
      Integer                          :: i, ifail, irevcm, iter, j, lda,      &
                                          ldcj, ldr, liwork, lwork, n, nclin,  &
                                          ncnln, sda, sdcjac
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: a(:,:), bl(:), bu(:), c(:),          &
                                          cjac(:,:), clamda(:), objgrd(:),     &
                                          r(:,:), work(:), x(:)
      Real (Kind=nag_wp)               :: rwsav(lrwsav)
      Integer, Allocatable             :: istate(:), iwork(:), needc(:)
      Integer                          :: iwsav(liwsav)
      Logical                          :: lwsav(llwsav)
      Character (80)                   :: cwsav(lcwsav)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: max
!     .. Executable Statements ..
      Write (nout,*) 'E04UFA Example Program Results'

!     Skip heading in data file.
      Read (nin,*)

      Read (nin,*) n, nclin, ncnln
      liwork = 3*n + nclin + 2*ncnln
      lda = max(1,nclin)

      If (nclin>0) Then
        sda = n
      Else
        sda = 1
      End If

      ldcj = max(1,ncnln)

      If (ncnln>0) Then
        sdcjac = n
      Else
        sdcjac = 1
      End If

      ldr = n

      If (ncnln==0 .And. nclin>0) Then
        lwork = 2*n**2 + 21*n + 11*nclin + 2
      Else If (ncnln>0 .And. nclin>=0) Then
        lwork = 2*n**2 + n*nclin + 2*n*ncnln + 21*n + 11*nclin + 22*ncnln + 1
      Else
        lwork = 21*n + 2
      End If

      Allocate (istate(n+nclin+ncnln),iwork(liwork),a(lda,sda),                &
        bl(n+nclin+ncnln),bu(n+nclin+ncnln),c(max(1,                           &
        ncnln)),cjac(ldcj,sdcjac),clamda(n+nclin+ncnln),objgrd(n),r(ldr,n),    &
        x(n),work(lwork),needc(max(1,ncnln)))

      If (nclin>0) Then
        Read (nin,*)(a(i,1:n),i=1,nclin)
      End If

      Read (nin,*) bl(1:(n+nclin+ncnln))
      Read (nin,*) bu(1:(n+nclin+ncnln))
      Read (nin,*) x(1:n)

!     Set all constraint Jacobian elements to zero.
!     Note that this will only work when 'Derivative Level = 3'
!     (the default; see Section 11.2).

      cjac(1:ncnln,1:n) = zero

!     Initialise E04UFA

      ifail = 0
      Call e04wbf('E04UFA',cwsav,lcwsav,lwsav,llwsav,iwsav,liwsav,rwsav,       &
        lrwsav,ifail)

!     Solve the problem.

      irevcm = 0
      ifail = -1

revcomm: Do

        Call e04ufa(irevcm,n,nclin,ncnln,lda,ldcj,ldr,a,bl,bu,iter,istate,c,   &
          cjac,clamda,objf,objgrd,r,x,needc,iwork,liwork,work,lwork,cwsav,     &
          lwsav,iwsav,rwsav,ifail)

!       On intermediate exit IFAIL should not have been changed
!       and IREVCM should be > 0.

        If (irevcm==0) Then
          Exit revcomm
        End If

        If (irevcm==1 .Or. irevcm==3) Then

!         Evaluate the objective function.

          objf = x(1)*x(4)*(x(1)+x(2)+x(3)) + x(3)
        End If

        If (irevcm==2 .Or. irevcm==3) Then

!         Evaluate the objective gradient.

          objgrd(1) = x(4)*(x(1)+x(1)+x(2)+x(3))
          objgrd(2) = x(1)*x(4)
          objgrd(3) = x(1)*x(4) + one
          objgrd(4) = x(1)*(x(1)+x(2)+x(3))
        End If

        If (irevcm==4 .Or. irevcm==6) Then

!         Evaluate the nonlinear constraint functions.

          If (needc(1)>0) Then
            c(1) = x(1)**2 + x(2)**2 + x(3)**2 + x(4)**2
          End If

          If (needc(2)>0) Then
            c(2) = x(1)*x(2)*x(3)*x(4)
          End If

        End If

        If (irevcm==5 .Or. irevcm==6) Then

!         Evaluate the constraint Jacobian.

          If (needc(1)>0) Then
            cjac(1,1) = x(1) + x(1)
            cjac(1,2) = x(2) + x(2)
            cjac(1,3) = x(3) + x(3)
            cjac(1,4) = x(4) + x(4)
          End If

          If (needc(2)>0) Then
            cjac(2,1) = x(2)*x(3)*x(4)
            cjac(2,2) = x(1)*x(3)*x(4)
            cjac(2,3) = x(1)*x(2)*x(4)
            cjac(2,4) = x(1)*x(2)*x(3)
          End If

        End If

      End Do revcomm

      Select Case (ifail)
      Case (0:6,8)
        Write (nout,*)
        Write (nout,99999)
        Write (nout,*)

        Do i = 1, n
          Write (nout,99998) i, istate(i), x(i), clamda(i)
        End Do

        If (nclin>0) Then

!         A*x --> work.
!         The NAG name equivalent of dgemv is f06paf
          Call dgemv('N',nclin,n,one,a,lda,x,inc1,zero,work,inc1)

          Write (nout,*)
          Write (nout,*)
          Write (nout,99997)
          Write (nout,*)

          Do i = n + 1, n + nclin
            j = i - n
            Write (nout,99996) j, istate(i), work(j), clamda(i)
          End Do

        End If

        If (ncnln>0) Then
          Write (nout,*)
          Write (nout,*)
          Write (nout,99995)
          Write (nout,*)

          Do i = n + nclin + 1, n + nclin + ncnln
            j = i - n - nclin
            Write (nout,99994) j, istate(i), c(j), clamda(i)
          End Do

        End If

        Write (nout,*)
        Write (nout,*)
        Write (nout,99993) objf
      End Select

99999 Format (1X,'Varbl',2X,'Istate',3X,'Value',9X,'Lagr Mult')
99998 Format (1X,'V',2(1X,I3),4X,1P,G14.6,2X,1P,G12.4)
99997 Format (1X,'L Con',2X,'Istate',3X,'Value',9X,'Lagr Mult')
99996 Format (1X,'L',2(1X,I3),4X,1P,G14.6,2X,1P,G12.4)
99995 Format (1X,'N Con',2X,'Istate',3X,'Value',9X,'Lagr Mult')
99994 Format (1X,'N',2(1X,I3),4X,1P,G14.6,2X,1P,G12.4)
99993 Format (1X,'Final objective value = ',1P,G15.7)
    End Program e04ufae


e04uffe.f90

    Program e04uffe

!     E04UFF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: e04uff, nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: objf
      Integer                          :: i, ifail, irevcm, iter, lda, ldcj,   &
                                          ldr, liwork, lwork, n, nclin, ncnln, &
                                          sda, sdcjac
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: a(:,:), bl(:), bu(:), c(:),          &
                                          cjac(:,:), clamda(:), objgrd(:),     &
                                          r(:,:), work(:), x(:)
      Integer, Allocatable             :: istate(:), iwork(:), needc(:)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: max
!     .. Executable Statements ..
      Write (nout,*) 'E04UFF Example Program Results'
      Flush (nout)

!     Skip heading in data file.
      Read (nin,*)

      Read (nin,*) n, nclin, ncnln
      liwork = 3*n + nclin + 2*ncnln
      lda = max(1,nclin)

      If (nclin>0) Then
        sda = n
      Else
        sda = 1
      End If

      ldcj = max(1,ncnln)

      If (ncnln>0) Then
        sdcjac = n
      Else
        sdcjac = 1
      End If

      ldr = n

      If (ncnln==0 .And. nclin>0) Then
        lwork = 2*n**2 + 21*n + 11*nclin + 2
      Else If (ncnln>0 .And. nclin>=0) Then
        lwork = 2*n**2 + n*nclin + 2*n*ncnln + 21*n + 11*nclin + 22*ncnln + 1
      Else
        lwork = 21*n + 2
      End If

      Allocate (istate(n+nclin+ncnln),iwork(liwork),a(lda,sda),                &
        bl(n+nclin+ncnln),bu(n+nclin+ncnln),c(max(1,                           &
        ncnln)),cjac(ldcj,sdcjac),clamda(n+nclin+ncnln),objgrd(n),r(ldr,n),    &
        x(n),work(lwork),needc(max(1,ncnln)))

      If (nclin>0) Then
        Read (nin,*)(a(i,1:n),i=1,nclin)
      End If

      Read (nin,*) bl(1:(n+nclin+ncnln))
      Read (nin,*) bu(1:(n+nclin+ncnln))
      Read (nin,*) x(1:n)

!     Set all constraint Jacobian elements to zero.
!     Note that this will only work when 'Derivative Level = 3'
!     (the default; see Section 11.2).

      cjac(1:ncnln,1:n) = 0.0E0_nag_wp

!     Solve the problem.

      irevcm = 0
      ifail = 0

revcomm: Do

        Call e04uff(irevcm,n,nclin,ncnln,lda,ldcj,ldr,a,bl,bu,iter,istate,c,   &
          cjac,clamda,objf,objgrd,r,x,needc,iwork,liwork,work,lwork,ifail)

!       On intermediate exit IFAIL should not have been changed
!       and IREVCM should be > 0.

        If (irevcm==0) Then
          Exit revcomm
        End If

        If (irevcm==1 .Or. irevcm==3) Then

!         Evaluate the objective function.

          objf = x(1)*x(4)*(x(1)+x(2)+x(3)) + x(3)
        End If

        If (irevcm==2 .Or. irevcm==3) Then

!         Evaluate the objective gradient.

          objgrd(1) = x(4)*(2.0E0_nag_wp*x(1)+x(2)+x(3))
          objgrd(2) = x(1)*x(4)
          objgrd(3) = x(1)*x(4) + 1.0E0_nag_wp
          objgrd(4) = x(1)*(x(1)+x(2)+x(3))
        End If

        If (irevcm==4 .Or. irevcm==6) Then

!         Evaluate the nonlinear constraint functions.

          If (needc(1)>0) Then
            c(1) = x(1)**2 + x(2)**2 + x(3)**2 + x(4)**2
          End If

          If (needc(2)>0) Then
            c(2) = x(1)*x(2)*x(3)*x(4)
          End If

        End If

        If (irevcm==5 .Or. irevcm==6) Then

!         Evaluate the constraint Jacobian.

          If (needc(1)>0) Then
            cjac(1,1) = 2.0E0_nag_wp*x(1)
            cjac(1,2) = 2.0E0_nag_wp*x(2)
            cjac(1,3) = 2.0E0_nag_wp*x(3)
            cjac(1,4) = 2.0E0_nag_wp*x(4)
          End If

          If (needc(2)>0) Then
            cjac(2,1) = x(2)*x(3)*x(4)
            cjac(2,2) = x(1)*x(3)*x(4)
            cjac(2,3) = x(1)*x(2)*x(4)
            cjac(2,4) = x(1)*x(2)*x(3)
          End If

        End If

      End Do revcomm

    End Program e04uffe


e04ugae.f90

!   E04UGA Example Program Text
!   Mark 26 Release. NAG Copyright 2016.

    Module e04ugae_mod

!     E04UGA Example Program Module:
!            Parameters and User-defined Routines

!     .. Use Statements ..
      Use nag_library, Only: nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Accessibility Statements ..
      Private
      Public                           :: confun, objfun
!     .. Parameters ..
      Integer, Parameter, Public       :: lcwsav = 1, liwsav = 550,            &
                                          llwsav = 20, lrwsav = 550, nin = 5,  &
                                          nout = 6
    Contains
      Subroutine confun(mode,ncnln,njnln,nnzjac,x,f,fjac,nstate,iuser,ruser)
!       Computes the nonlinear constraint functions and their Jacobian.

!       .. Scalar Arguments ..
        Integer, Intent (Inout)        :: mode
        Integer, Intent (In)           :: ncnln, njnln, nnzjac, nstate
!       .. Array Arguments ..
        Real (Kind=nag_wp), Intent (Out) :: f(ncnln)
        Real (Kind=nag_wp), Intent (Inout) :: fjac(nnzjac), ruser(*)
        Real (Kind=nag_wp), Intent (In) :: x(njnln)
        Integer, Intent (Inout)        :: iuser(*)
!       .. Intrinsic Procedures ..
        Intrinsic                      :: cos, sin
!       .. Executable Statements ..
        If (mode==0 .Or. mode==2) Then
          f(1) = 1000.0E+0_nag_wp*sin(-x(1)-0.25E+0_nag_wp) +                  &
            1000.0E+0_nag_wp*sin(-x(2)-0.25E+0_nag_wp)
          f(2) = 1000.0E+0_nag_wp*sin(x(1)-0.25E+0_nag_wp) +                   &
            1000.0E+0_nag_wp*sin(x(1)-x(2)-0.25E+0_nag_wp)
          f(3) = 1000.0E+0_nag_wp*sin(x(2)-x(1)-0.25E+0_nag_wp) +              &
            1000.0E+0_nag_wp*sin(x(2)-0.25E+0_nag_wp)
        End If

        If (mode==1 .Or. mode==2) Then

!         Nonlinear Jacobian elements for column 1.

          fjac(1) = -1000.0E+0_nag_wp*cos(-x(1)-0.25E+0_nag_wp)
          fjac(2) = 1000.0E+0_nag_wp*cos(x(1)-0.25E+0_nag_wp) +                &
            1000.0E+0_nag_wp*cos(x(1)-x(2)-0.25E+0_nag_wp)
          fjac(3) = -1000.0E+0_nag_wp*cos(x(2)-x(1)-0.25E+0_nag_wp)

!         Nonlinear Jacobian elements for column 2.

          fjac(4) = -1000.0E+0_nag_wp*cos(-x(2)-0.25E+0_nag_wp)
          fjac(5) = -1000.0E+0_nag_wp*cos(x(1)-x(2)-0.25E+0_nag_wp)
          fjac(6) = 1000.0E+0_nag_wp*cos(x(2)-x(1)-0.25E+0_nag_wp) +           &
            1000.0E+0_nag_wp*cos(x(2)-0.25E+0_nag_wp)
        End If

        Return

      End Subroutine confun
      Subroutine objfun(mode,nonln,x,objf,objgrd,nstate,iuser,ruser)
!       Computes the nonlinear part of the objective function and its
!       gradient

!       .. Scalar Arguments ..
        Real (Kind=nag_wp), Intent (Out) :: objf
        Integer, Intent (Inout)        :: mode
        Integer, Intent (In)           :: nonln, nstate
!       .. Array Arguments ..
        Real (Kind=nag_wp), Intent (Inout) :: objgrd(nonln), ruser(*)
        Real (Kind=nag_wp), Intent (In) :: x(nonln)
        Integer, Intent (Inout)        :: iuser(*)
!       .. Executable Statements ..
        If (mode==0 .Or. mode==2) Then
          objf = 1.0E-6_nag_wp*x(3)**3 + 2.0E-6_nag_wp*x(4)**3/3.0E+0_nag_wp
        End If

        If (mode==1 .Or. mode==2) Then
          objgrd(1) = 0.0E+0_nag_wp
          objgrd(2) = 0.0E+0_nag_wp
          objgrd(3) = 3.0E-6_nag_wp*x(3)**2
          objgrd(4) = 2.0E-6_nag_wp*x(4)**2
        End If

        Return

      End Subroutine objfun
    End Module e04ugae_mod
    Program e04ugae

!     E04UGA Example Main Program

!     .. Use Statements ..
      Use nag_library, Only: e04uga, e04wbf, nag_wp
      Use e04ugae_mod, Only: confun, lcwsav, liwsav, llwsav, lrwsav, nin,      &
                             nout, objfun
!     .. Implicit None Statement ..
      Implicit None
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: obj, sinf
      Integer                          :: i, icol, ifail, iobj, j, jcol,       &
                                          leniz, lenz, m, miniz, minz, n,      &
                                          ncnln, ninf, njnln, nname, nnz,      &
                                          nonln, ns
      Character (1)                    :: start
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: a(:), bl(:), bu(:), clamda(:),       &
                                          xs(:), z(:)
      Real (Kind=nag_wp)               :: rwsav(lrwsav), user(1)
      Integer, Allocatable             :: ha(:), istate(:), iz(:), ka(:)
      Integer                          :: iuser(1), iwsav(liwsav)
      Logical                          :: lwsav(llwsav)
      Character (80)                   :: cwsav(lcwsav)
      Character (8), Allocatable       :: names(:)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: max
!     .. Executable Statements ..
      Write (nout,*) 'E04UGA Example Program Results'

!     Skip heading in data file.
      Read (nin,*)

      Read (nin,*) n, m
      Read (nin,*) ncnln, nonln, njnln
      Read (nin,*) nnz, iobj, start, nname
      Allocate (ha(nnz),ka(n+1),istate(n+m),a(nnz),bl(n+m),bu(n+m),xs(n+m),    &
        clamda(n+m),names(nname))

      Read (nin,*) names(1:nname)

!     Read the matrix A from data file. Set up KA.

      jcol = 1
      ka(jcol) = 1

      Do i = 1, nnz

!       Element ( HA( I ), ICOL ) is stored in A( I ).

        Read (nin,*) a(i), ha(i), icol

        If (icol<jcol) Then

!         Elements not ordered by increasing column index.

          Write (nout,99999) 'Element in column', icol,                        &
            ' found after element in column', jcol, '. Problem', ' abandoned.'
          Go To 100
        Else If (icol==jcol+1) Then

!         Index in A of the start of the ICOL-th column equals I.

          ka(icol) = i
          jcol = icol
        Else If (icol>jcol+1) Then

!         Index in A of the start of the ICOL-th column equals I,
!         but columns JCOL+1,JCOL+2,...,ICOL-1 are empty. Set the
!         corresponding elements of KA to I.

          ka((jcol+1):icol) = i
          jcol = icol
        End If

      End Do

      ka(n+1) = nnz + 1

!     Columns N,N-1,...,ICOL+1 are empty. Set the corresponding
!     elements of KA accordingly.

      Do i = n, icol + 1, -1
        ka(i) = ka(i+1)
      End Do

      Read (nin,*) bl(1:(n+m))
      Read (nin,*) bu(1:(n+m))

      If (start=='C') Then
        Read (nin,*) istate(1:n)
      Else If (start=='W') Then
        Read (nin,*) istate(1:(n+m))
      End If

      Read (nin,*) xs(1:n)

      If (ncnln>0) Then
        Read (nin,*) clamda((n+1):(n+ncnln))
      End If

!     Initialise E04UGA

      ifail = 0
      Call e04wbf('E04UGA',cwsav,lcwsav,lwsav,llwsav,iwsav,liwsav,rwsav,       &
        lrwsav,ifail)

!     Solve the problem.
!     First call is a workspace query

      leniz = max(500,n+m)
      lenz = 500
      Allocate (iz(leniz),z(lenz))

      ifail = 1
      Call e04uga(confun,objfun,n,m,ncnln,nonln,njnln,iobj,nnz,a,ha,ka,bl,bu,  &
        start,nname,names,ns,xs,istate,clamda,miniz,minz,ninf,sinf,obj,iz,     &
        leniz,z,lenz,iuser,user,lwsav,iwsav,rwsav,ifail)

      If (ifail/=0 .And. ifail/=15 .And. ifail/=16) Then
        Write (nout,99990) 'Query call to E04UGA failed with IFAIL =', ifail
        Go To 100
      End If

      Deallocate (iz,z)

!     The length of the workspace required for the basis factors in this
!     problem is longer than the minimum returned by the query

      lenz = 2*minz
      leniz = 2*miniz
      Allocate (iz(leniz),z(lenz))

      ifail = -1
      Call e04uga(confun,objfun,n,m,ncnln,nonln,njnln,iobj,nnz,a,ha,ka,bl,bu,  &
        start,nname,names,ns,xs,istate,clamda,miniz,minz,ninf,sinf,obj,iz,     &
        leniz,z,lenz,iuser,user,lwsav,iwsav,rwsav,ifail)

      Select Case (ifail)
      Case (0:6)
        Write (nout,*)
        Write (nout,99998)
        Write (nout,*)

        Do i = 1, n
          Write (nout,99997) i, istate(i), xs(i), clamda(i)
        End Do

        Write (nout,*)
        Write (nout,*)
        Write (nout,99995)
        Write (nout,*)

        If (ncnln>0) Then

          Do i = n + 1, n + ncnln
            j = i - n
            Write (nout,99994) j, istate(i), xs(i), clamda(i)
          End Do

        End If

        If ((ncnln==0) .And. (m==1) .And. (a(1)==0.0E0_nag_wp)) Then
          Write (nout,99992) istate(n+1), xs(n+1), clamda(n+1)
        Else If (m>ncnln) Then

          Do i = n + ncnln + 1, n + m
            j = i - n - ncnln

            If (i-n==iobj) Then
              Write (nout,99993) istate(i), xs(i), clamda(i)
            Else
              Write (nout,99996) j, istate(i), xs(i), clamda(i)
            End If

          End Do

        End If

        Write (nout,*)
        Write (nout,*)
        Write (nout,99991) obj
      End Select

100   Continue

99999 Format (/,1X,A,I5,A,I5,A,A)
99998 Format (1X,'Variable',2X,'Istate',5X,'Value',9X,'Lagr Mult')
99997 Format (1X,'Varble',1X,I2,1X,I3,4X,1P,G14.6,2X,1P,G12.4)
99996 Format (1X,'LinCon',1X,I2,1X,I3,4X,1P,G14.6,2X,1P,G12.4)
99995 Format (1X,'Constrnt',2X,'Istate',5X,'Value',9X,'Lagr Mult')
99994 Format (1X,'NlnCon',1X,I2,1X,I3,4X,1P,G14.6,2X,1P,G12.4)
99993 Format (1X,'Free Row',2X,I3,4X,1P,G14.6,2X,1P,G12.4)
99992 Format (1X,'DummyRow',2X,I3,4X,1P,G14.6,2X,1P,G12.4)
99991 Format (1X,'Final objective value = ',1P,G15.7)
99990 Format (1X,A,I5)
    End Program e04ugae


e04ugfe.f90

!   E04UGF Example Program Text
!   Mark 26 Release. NAG Copyright 2016.

    Module e04ugfe_mod

!     E04UGF Example Program Module:
!            Parameters and User-defined Routines

!     .. Use Statements ..
      Use nag_library, Only: nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Accessibility Statements ..
      Private
      Public                           :: confun, objfun
!     .. Parameters ..
      Integer, Parameter, Public       :: nin = 5, nout = 6
    Contains
      Subroutine confun(mode,ncnln,njnln,nnzjac,x,f,fjac,nstate,iuser,ruser)
!       Computes the nonlinear constraint functions and their Jacobian.

!       .. Scalar Arguments ..
        Integer, Intent (Inout)        :: mode
        Integer, Intent (In)           :: ncnln, njnln, nnzjac, nstate
!       .. Array Arguments ..
        Real (Kind=nag_wp), Intent (Out) :: f(ncnln)
        Real (Kind=nag_wp), Intent (Inout) :: fjac(nnzjac), ruser(*)
        Real (Kind=nag_wp), Intent (In) :: x(njnln)
        Integer, Intent (Inout)        :: iuser(*)
!       .. Intrinsic Procedures ..
        Intrinsic                      :: cos, sin
!       .. Executable Statements ..
        If (mode==0 .Or. mode==2) Then
          f(1) = 1000.0E+0_nag_wp*sin(-x(1)-0.25E+0_nag_wp) +                  &
            1000.0E+0_nag_wp*sin(-x(2)-0.25E+0_nag_wp)
          f(2) = 1000.0E+0_nag_wp*sin(x(1)-0.25E+0_nag_wp) +                   &
            1000.0E+0_nag_wp*sin(x(1)-x(2)-0.25E+0_nag_wp)
          f(3) = 1000.0E+0_nag_wp*sin(x(2)-x(1)-0.25E+0_nag_wp) +              &
            1000.0E+0_nag_wp*sin(x(2)-0.25E+0_nag_wp)
        End If

        If (mode==1 .Or. mode==2) Then

!         Nonlinear Jacobian elements for column 1.

          fjac(1) = -1000.0E+0_nag_wp*cos(-x(1)-0.25E+0_nag_wp)
          fjac(2) = 1000.0E+0_nag_wp*cos(x(1)-0.25E+0_nag_wp) +                &
            1000.0E+0_nag_wp*cos(x(1)-x(2)-0.25E+0_nag_wp)
          fjac(3) = -1000.0E+0_nag_wp*cos(x(2)-x(1)-0.25E+0_nag_wp)

!         Nonlinear Jacobian elements for column 2.

          fjac(4) = -1000.0E+0_nag_wp*cos(-x(2)-0.25E+0_nag_wp)
          fjac(5) = -1000.0E+0_nag_wp*cos(x(1)-x(2)-0.25E+0_nag_wp)
          fjac(6) = 1000.0E+0_nag_wp*cos(x(2)-x(1)-0.25E+0_nag_wp) +           &
            1000.0E+0_nag_wp*cos(x(2)-0.25E+0_nag_wp)
        End If

        Return

      End Subroutine confun
      Subroutine objfun(mode,nonln,x,objf,objgrd,nstate,iuser,ruser)
!       Computes the nonlinear part of the objective function and its
!       gradient

!       .. Scalar Arguments ..
        Real (Kind=nag_wp), Intent (Out) :: objf
        Integer, Intent (Inout)        :: mode
        Integer, Intent (In)           :: nonln, nstate
!       .. Array Arguments ..
        Real (Kind=nag_wp), Intent (Inout) :: objgrd(nonln), ruser(*)
        Real (Kind=nag_wp), Intent (In) :: x(nonln)
        Integer, Intent (Inout)        :: iuser(*)
!       .. Executable Statements ..
        If (mode==0 .Or. mode==2) Then
          objf = 1.0E-6_nag_wp*x(3)**3 + 2.0E-6_nag_wp*x(4)**3/3.0E+0_nag_wp
        End If

        If (mode==1 .Or. mode==2) Then
          objgrd(1) = 0.0E+0_nag_wp
          objgrd(2) = 0.0E+0_nag_wp
          objgrd(3) = 3.0E-6_nag_wp*x(3)**2
          objgrd(4) = 2.0E-6_nag_wp*x(4)**2
        End If

        Return

      End Subroutine objfun
    End Module e04ugfe_mod
    Program e04ugfe

!     E04UGF Example Main Program

!     .. Use Statements ..
      Use nag_library, Only: e04ugf, nag_wp
      Use e04ugfe_mod, Only: confun, nin, nout, objfun
!     .. Implicit None Statement ..
      Implicit None
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: obj, sinf
      Integer                          :: i, icol, ifail, iobj, jcol, leniz,   &
                                          lenz, m, miniz, minz, n, ncnln,      &
                                          ninf, njnln, nname, nnz, nonln, ns
      Character (1)                    :: start
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: a(:), bl(:), bu(:), clamda(:),       &
                                          xs(:), z(:)
      Real (Kind=nag_wp)               :: user(1)
      Integer, Allocatable             :: ha(:), istate(:), iz(:), ka(:)
      Integer                          :: iuser(1)
      Character (8), Allocatable       :: names(:)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: max
!     .. Executable Statements ..
      Write (nout,*) 'E04UGF Example Program Results'
      Flush (nout)

!     Skip heading in data file.
      Read (nin,*)

      Read (nin,*) n, m
      Read (nin,*) ncnln, nonln, njnln
      Read (nin,*) nnz, iobj, start, nname
      Allocate (ha(nnz),ka(n+1),istate(n+m),a(nnz),bl(n+m),bu(n+m),xs(n+m),    &
        clamda(n+m),names(nname))

      Read (nin,*) names(1:nname)

!     Read the matrix A from data file. Set up KA.

      jcol = 1
      ka(jcol) = 1

      Do i = 1, nnz

!       Element ( HA( I ), ICOL ) is stored in A( I ).

        Read (nin,*) a(i), ha(i), icol

        If (icol<jcol) Then

!         Elements not ordered by increasing column index.

          Write (nout,99999) 'Element in column', icol,                        &
            ' found after element in column', jcol, '. Problem', ' abandoned.'
          Go To 100
        Else If (icol==jcol+1) Then

!         Index in A of the start of the ICOL-th column equals I.

          ka(icol) = i
          jcol = icol
        Else If (icol>jcol+1) Then

!         Index in A of the start of the ICOL-th column equals I,
!         but columns JCOL+1,JCOL+2,...,ICOL-1 are empty. Set the
!         corresponding elements of KA to I.

          ka((jcol+1):icol) = i
          jcol = icol
        End If

      End Do

      ka(n+1) = nnz + 1

!     Columns N,N-1,...,ICOL+1 are empty. Set the corresponding
!     elements of KA accordingly.

      Do i = n, icol + 1, -1
        ka(i) = ka(i+1)
      End Do

      Read (nin,*) bl(1:(n+m))
      Read (nin,*) bu(1:(n+m))

      If (start=='C') Then
        Read (nin,*) istate(1:n)
      Else If (start=='W') Then
        Read (nin,*) istate(1:(n+m))
      End If

      Read (nin,*) xs(1:n)

      If (ncnln>0) Then
        Read (nin,*) clamda((n+1):(n+ncnln))
      End If

!     Solve the problem.
!     First call is a workspace query

      leniz = max(500,n+m)
      lenz = 500
      Allocate (iz(leniz),z(lenz))

      ifail = 1
      Call e04ugf(confun,objfun,n,m,ncnln,nonln,njnln,iobj,nnz,a,ha,ka,bl,bu,  &
        start,nname,names,ns,xs,istate,clamda,miniz,minz,ninf,sinf,obj,iz,     &
        leniz,z,lenz,iuser,user,ifail)

      If (ifail/=0 .And. ifail/=15 .And. ifail/=16) Then
        Write (nout,99998) 'Query call to E04UGF failed with IFAIL =', ifail
        Go To 100
      End If

      Deallocate (iz,z)

!     The length of the workspace required for the basis factors in this
!     problem is longer than the minimum returned by the query

      lenz = 2*minz
      leniz = 2*miniz
      Allocate (iz(leniz),z(lenz))

      ifail = -1
      Call e04ugf(confun,objfun,n,m,ncnln,nonln,njnln,iobj,nnz,a,ha,ka,bl,bu,  &
        start,nname,names,ns,xs,istate,clamda,miniz,minz,ninf,sinf,obj,iz,     &
        leniz,z,lenz,iuser,user,ifail)

100   Continue

99999 Format (/,1X,A,I5,A,I5,A,A)
99998 Format (1X,A,I5)
    End Program e04ugfe


e04uhae.f90

!   E04UHA Example Program Text
!   Mark 26 Release. NAG Copyright 2016.

    Module e04uhae_mod

!     E04UHA Example Program Module:
!            Parameters and User-defined Routines

!     .. Use Statements ..
      Use nag_library, Only: nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Accessibility Statements ..
      Private
      Public                           :: objfun
!     .. Parameters ..
      Integer, Parameter, Public       :: iset = 1, lcwsav = 1, liwsav = 550,  &
                                          llwsav = 20, lrwsav = 550, nin = 5,  &
                                          ninopt = 7, nout = 6
    Contains
      Subroutine objfun(mode,nonln,x,objf,objgrd,nstate,iuser,ruser)
!       Computes the nonlinear part of the objective function and its
!       gradient

!       .. Scalar Arguments ..
        Real (Kind=nag_wp), Intent (Out) :: objf
        Integer, Intent (Inout)        :: mode
        Integer, Intent (In)           :: nonln, nstate
!       .. Array Arguments ..
        Real (Kind=nag_wp), Intent (Inout) :: objgrd(nonln), ruser(*)
        Real (Kind=nag_wp), Intent (In) :: x(nonln)
        Integer, Intent (Inout)        :: iuser(*)
!       .. Executable Statements ..
        If (mode==0 .Or. mode==2) Then
          objf = 2.0E+0_nag_wp - x(1)*x(2)*x(3)*x(4)*x(5)/120.0E+0_nag_wp
        End If

        If (mode==1 .Or. mode==2) Then
          objgrd(1) = -x(2)*x(3)*x(4)*x(5)/120.0E+0_nag_wp
          objgrd(2) = -x(1)*x(3)*x(4)*x(5)/120.0E+0_nag_wp
          objgrd(3) = -x(1)*x(2)*x(4)*x(5)/120.0E+0_nag_wp
          objgrd(4) = -x(1)*x(2)*x(3)*x(5)/120.0E+0_nag_wp
          objgrd(5) = -x(1)*x(2)*x(3)*x(4)/120.0E+0_nag_wp
        End If

        Return

      End Subroutine objfun
    End Module e04uhae_mod
    Program e04uhae

!     E04UHA Example Main Program

!     .. Use Statements ..
      Use nag_library, Only: e04uga, e04ugm, e04uha, e04uja, e04wbf, nag_wp,   &
                             x04abf, x04acf, x04baf
      Use e04uhae_mod, Only: iset, lcwsav, liwsav, llwsav, lrwsav, nin,        &
                             ninopt, nout, objfun
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Character (*), Parameter         :: fname = 'e04uhae.opt'
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: obj, sinf
      Integer                          :: i, ifail, inform, iobj, j, leniz,    &
                                          lenz, m, miniz, minz, mode, n,       &
                                          ncnln, ninf, njnln, nname, nnz,      &
                                          nonln, ns, outchn
      Character (80)                   :: rec
      Character (1)                    :: start
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: a(:), bl(:), bu(:), clamda(:),       &
                                          xs(:), z(:)
      Real (Kind=nag_wp)               :: rwsav(lrwsav), user(1)
      Integer, Allocatable             :: ha(:), istate(:), iz(:), ka(:)
      Integer                          :: iuser(1), iwsav(liwsav)
      Logical                          :: lwsav(llwsav)
      Character (80)                   :: cwsav(lcwsav)
      Character (8), Allocatable       :: names(:)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: max
!     .. Executable Statements ..
      Write (rec,99990) 'E04UHA Example Program Results'
      Call x04baf(nout,rec)

!     Skip heading in data file.
      Read (nin,*)
      Read (nin,*) n, m
      Read (nin,*) ncnln, nonln, njnln
      Read (nin,*) start, nname
      nnz = 1
      Allocate (ha(nnz),ka(n+1),istate(n+m),a(nnz),bl(n+m),bu(n+m),xs(n+m),    &
        clamda(n+m),names(nname))

      Read (nin,*) names(1:nname)

!     Define the matrix A to contain a dummy `free' row that consists
!     of a single (zero) element subject to `infinite' upper and
!     lower bounds. Set up KA.

      iobj = -1

      ka(1) = 1

      a(1) = 0.0E+0_nag_wp
      ha(1) = 1

!     Columns 2,3,...,N of A are empty. Set the corresponding element
!     of KA to 2.

      ka(2:n) = 2
      ka(n+1) = nnz + 1

      Read (nin,*) bl(1:(n+m))
      Read (nin,*) bu(1:(n+m))

      If (start=='C') Then
        Read (nin,*) istate(1:n)
      Else If (start=='W') Then
        Read (nin,*) istate(1:(n+m))
      End If

      Read (nin,*) xs(1:n)

!     Set the unit number for advisory messages to OUTCHN.

      outchn = nout
      Call x04abf(iset,outchn)

!     Initialise E04UGA

      ifail = 0
      Call e04wbf('E04UGA',cwsav,lcwsav,lwsav,llwsav,iwsav,liwsav,rwsav,       &
        lrwsav,ifail)

!     Set three options using E04UJA.

      Call e04uja(' Verify Level = -1 ',lwsav,iwsav,rwsav,inform)

      If (inform==0) Then

        Call e04uja(' Major Iteration Limit = 25 ',lwsav,iwsav,rwsav,inform)

        If (inform==0) Then

          Call e04uja(' Infinite Bound Size = 1.0D+25 ',lwsav,iwsav,rwsav,     &
            inform)

        End If

      End If

      If (inform/=0) Then
        Write (rec,99991) 'E04UJA terminated with INFORM = ', inform
        Call x04baf(nout,rec)
        Go To 100
      End If

!     Open the options file for reading

      mode = 0

      ifail = 0
      Call x04acf(ninopt,fname,mode,ifail)

!     Read the options file for the remaining options.

      Call e04uha(ninopt,lwsav,iwsav,rwsav,inform)

      If (inform/=0) Then
        Write (rec,99991) 'E04UJA terminated with INFORM = ', inform
        Call x04baf(nout,rec)
        Go To 100
      End If

!     Solve the problem.
!     First call is a workspace query

      leniz = max(500,n+m)
      lenz = 500
      Allocate (iz(leniz),z(lenz))

      ifail = 1
      Call e04uga(e04ugm,objfun,n,m,ncnln,nonln,njnln,iobj,nnz,a,ha,ka,bl,bu,  &
        start,nname,names,ns,xs,istate,clamda,miniz,minz,ninf,sinf,obj,iz,     &
        leniz,z,lenz,iuser,user,lwsav,iwsav,rwsav,ifail)

      If (ifail/=0 .And. ifail/=15 .And. ifail/=16) Then
        Write (nout,99991) 'Query call to E04UGA failed with IFAIL =', ifail
        Go To 100
      End If

      Deallocate (iz,z)

!     The length of the workspace required for the basis factors in this
!     problem is longer than the minimum returned by the query

      lenz = 2*minz
      leniz = 2*miniz
      Allocate (iz(leniz),z(lenz))

      ifail = -1
      Call e04uga(e04ugm,objfun,n,m,ncnln,nonln,njnln,iobj,nnz,a,ha,ka,bl,bu,  &
        start,nname,names,ns,xs,istate,clamda,miniz,minz,ninf,sinf,obj,iz,     &
        leniz,z,lenz,iuser,user,lwsav,iwsav,rwsav,ifail)

      Select Case (ifail)
      Case (0:6)
        Write (rec,'()')
        Call x04baf(nout,rec)
        Write (rec,99999)
        Call x04baf(nout,rec)
        Write (rec,'()')
        Call x04baf(nout,rec)

        Do i = 1, n
          Write (rec,99998) i, istate(i), xs(i), clamda(i)
          Call x04baf(nout,rec)
        End Do

        Write (rec,'()')
        Call x04baf(nout,rec)
        Write (rec,'()')
        Call x04baf(nout,rec)
        Write (rec,99996)
        Call x04baf(nout,rec)
        Write (rec,'()')
        Call x04baf(nout,rec)

        If (ncnln>0) Then

          Do i = n + 1, n + ncnln
            j = i - n
            Write (rec,99995) j, istate(i), xs(i), clamda(i)
            Call x04baf(nout,rec)
          End Do

        End If

        If (ncnln==0 .And. m==1 .And. a(1)==0.0E0_nag_wp) Then
          Write (rec,99993) istate(n+1), xs(n+1), clamda(n+1)
          Call x04baf(nout,rec)
        Else If (m>ncnln) Then

          Do i = n + ncnln + 1, n + m
            j = i - n - ncnln

            If (i-n==iobj) Then
              Write (rec,99994) istate(i), xs(i), clamda(i)
              Call x04baf(nout,rec)
            Else
              Write (rec,99997) j, istate(i), xs(i), clamda(i)
              Call x04baf(nout,rec)
            End If

          End Do

        End If

        Write (rec,'()')
        Call x04baf(nout,rec)
        Write (rec,'()')
        Call x04baf(nout,rec)
        Write (rec,99992) obj
        Call x04baf(nout,rec)
      End Select

100   Continue

99999 Format (1X,'Variable',2X,'Istate',5X,'Value',9X,'Lagr Mult')
99998 Format (1X,'Varble',1X,I2,1X,I3,4X,1P,G14.6,2X,1P,G12.4)
99997 Format (1X,'LinCon',1X,I2,1X,I3,4X,1P,G14.6,2X,1P,G12.4)
99996 Format (1X,'Constrnt',2X,'Istate',5X,'Value',9X,'Lagr Mult')
99995 Format (1X,'NlnCon',1X,I2,1X,I3,4X,1P,G14.6,2X,1P,G12.4)
99994 Format (1X,'Free Row',2X,I3,4X,1P,G14.6,2X,1P,G12.4)
99993 Format (1X,'DummyRow',2X,I3,4X,1P,G14.6,2X,1P,G12.4)
99992 Format (1X,'Final objective value = ',1P,G15.7)
99991 Format (1X,A,I5)
99990 Format (1X,A)
    End Program e04uhae


e04uhfe.f90

!   E04UHF Example Program Text
!   Mark 26 Release. NAG Copyright 2016.

    Module e04uhfe_mod

!     E04UHF Example Program Module:
!            Parameters and User-defined Routines

!     .. Use Statements ..
      Use nag_library, Only: nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Accessibility Statements ..
      Private
      Public                           :: objfun
!     .. Parameters ..
      Integer, Parameter, Public       :: iset = 1, nin = 5, ninopt = 7,       &
                                          nout = 6
    Contains
      Subroutine objfun(mode,nonln,x,objf,objgrd,nstate,iuser,ruser)
!       Computes the nonlinear part of the objective function and its
!       gradient

!       .. Scalar Arguments ..
        Real (Kind=nag_wp), Intent (Out) :: objf
        Integer, Intent (Inout)        :: mode
        Integer, Intent (In)           :: nonln, nstate
!       .. Array Arguments ..
        Real (Kind=nag_wp), Intent (Inout) :: objgrd(nonln), ruser(*)
        Real (Kind=nag_wp), Intent (In) :: x(nonln)
        Integer, Intent (Inout)        :: iuser(*)
!       .. Executable Statements ..
        If (mode==0 .Or. mode==2) Then
          objf = 2.0E+0_nag_wp - x(1)*x(2)*x(3)*x(4)*x(5)/120.0E+0_nag_wp
        End If

        If (mode==1 .Or. mode==2) Then
          objgrd(1) = -x(2)*x(3)*x(4)*x(5)/120.0E+0_nag_wp
          objgrd(2) = -x(1)*x(3)*x(4)*x(5)/120.0E+0_nag_wp
          objgrd(3) = -x(1)*x(2)*x(4)*x(5)/120.0E+0_nag_wp
          objgrd(4) = -x(1)*x(2)*x(3)*x(5)/120.0E+0_nag_wp
          objgrd(5) = -x(1)*x(2)*x(3)*x(4)/120.0E+0_nag_wp
        End If

        Return

      End Subroutine objfun
    End Module e04uhfe_mod
    Program e04uhfe

!     E04UHF Example Main Program

!     .. Use Statements ..
      Use nag_library, Only: e04ugf, e04ugm, e04uhf, e04ujf, nag_wp, x04abf,   &
                             x04acf, x04baf
      Use e04uhfe_mod, Only: iset, nin, ninopt, nout, objfun
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Character (*), Parameter         :: fname = 'e04uhfe.opt'
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: obj, sinf
      Integer                          :: ifail, inform, iobj, leniz, lenz, m, &
                                          miniz, minz, mode, n, ncnln, ninf,   &
                                          njnln, nname, nnz, nonln, ns, outchn
      Character (80)                   :: rec
      Character (1)                    :: start
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: a(:), bl(:), bu(:), clamda(:),       &
                                          xs(:), z(:)
      Real (Kind=nag_wp)               :: user(1)
      Integer, Allocatable             :: ha(:), istate(:), iz(:), ka(:)
      Integer                          :: iuser(1)
      Character (8), Allocatable       :: names(:)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: max
!     .. Executable Statements ..
      Write (rec,99998) 'E04UHF Example Program Results'
      Call x04baf(nout,rec)

!     Skip heading in data file.
      Read (nin,*)
      Read (nin,*) n, m
      Read (nin,*) ncnln, nonln, njnln
      Read (nin,*) start, nname
      nnz = 1
      Allocate (ha(nnz),ka(n+1),istate(n+m),a(nnz),bl(n+m),bu(n+m),xs(n+m),    &
        clamda(n+m),names(nname))

      Read (nin,*) names(1:nname)

!     Define the matrix A to contain a dummy `free' row that consists
!     of a single (zero) element subject to `infinite' upper and
!     lower bounds. Set up KA.

      iobj = -1

      ka(1) = 1

      a(1) = 0.0E+0_nag_wp
      ha(1) = 1

!     Columns 2,3,...,N of A are empty. Set the corresponding element
!     of KA to 2.

      ka(2:n) = 2
      ka(n+1) = nnz + 1

      Read (nin,*) bl(1:(n+m))
      Read (nin,*) bu(1:(n+m))

      If (start=='C') Then
        Read (nin,*) istate(1:n)
      Else If (start=='W') Then
        Read (nin,*) istate(1:(n+m))
      End If

      Read (nin,*) xs(1:n)

!     Set the unit number for advisory messages to OUTCHN.

      outchn = nout
      Call x04abf(iset,outchn)

!     Set three options using E04UJF.

      Call e04ujf(' Verify Level = -1 ')

      Call e04ujf(' Major Iteration Limit = 25 ')

      Call e04ujf(' Infinite Bound Size = 1.0D+25 ')

!     Open the options file for reading

      mode = 0

      ifail = 0
      Call x04acf(ninopt,fname,mode,ifail)

!     Read the options file for the remaining options.

      Call e04uhf(ninopt,inform)

      If (inform/=0) Then
        Write (rec,99999) 'E04UJF terminated with INFORM = ', inform
        Call x04baf(nout,rec)
        Go To 100
      End If

!     Solve the problem.
!     First call is a workspace query

      leniz = max(500,n+m)
      lenz = 500
      Allocate (iz(leniz),z(lenz))

      ifail = 1
      Call e04ugf(e04ugm,objfun,n,m,ncnln,nonln,njnln,iobj,nnz,a,ha,ka,bl,bu,  &
        start,nname,names,ns,xs,istate,clamda,miniz,minz,ninf,sinf,obj,iz,     &
        leniz,z,lenz,iuser,user,ifail)

      If (ifail/=0 .And. ifail/=15 .And. ifail/=16) Then
        Write (nout,99999) 'Query call to E04UGF failed with IFAIL =', ifail
        Go To 100
      End If

      Deallocate (iz,z)

!     The length of the workspace required for the basis factors in this
!     problem is longer than the minimum returned by the query

      lenz = 2*minz
      leniz = 2*miniz
      Allocate (iz(leniz),z(lenz))

      ifail = 0
      Call e04ugf(e04ugm,objfun,n,m,ncnln,nonln,njnln,iobj,nnz,a,ha,ka,bl,bu,  &
        start,nname,names,ns,xs,istate,clamda,miniz,minz,ninf,sinf,obj,iz,     &
        leniz,z,lenz,iuser,user,ifail)
100   Continue

99999 Format (1X,A,I5)
99998 Format (1X,A)
    End Program e04uhfe


e04uqae.f90

!   E04UQA Example Program Text
!   Mark 26 Release. NAG Copyright 2016.

    Module e04uqae_mod

!     E04UQA Example Program Module:
!            Parameters and User-defined Routines

!     .. Use Statements ..
      Use nag_library, Only: nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Accessibility Statements ..
      Private
      Public                           :: confun, objfun
!     .. Parameters ..
      Real (Kind=nag_wp), Parameter, Public :: one = 1.0_nag_wp
      Real (Kind=nag_wp), Parameter, Public :: zero = 0.0_nag_wp
      Integer, Parameter, Public       :: inc1 = 1, iset = 1, lcwsav = 1,      &
                                          liwsav = 610, llwsav = 120,          &
                                          lrwsav = 475, nin = 5, ninopt = 7,   &
                                          nout = 6
    Contains
      Subroutine objfun(mode,m,n,ldfj,needfi,x,f,fjac,nstate,iuser,ruser)
!       Routine to evaluate the subfunctions and their 1st derivatives.

!       .. Parameters ..
        Real (Kind=nag_wp), Parameter  :: a(44) = (/8.0_nag_wp,8.0_nag_wp,     &
                                          10.0_nag_wp,10.0_nag_wp,10.0_nag_wp, &
                                          10.0_nag_wp,12.0_nag_wp,12.0_nag_wp, &
                                          12.0_nag_wp,12.0_nag_wp,14.0_nag_wp, &
                                          14.0_nag_wp,14.0_nag_wp,16.0_nag_wp, &
                                          16.0_nag_wp,16.0_nag_wp,18.0_nag_wp, &
                                          18.0_nag_wp,20.0_nag_wp,20.0_nag_wp, &
                                          20.0_nag_wp,22.0_nag_wp,22.0_nag_wp, &
                                          22.0_nag_wp,24.0_nag_wp,24.0_nag_wp, &
                                          24.0_nag_wp,26.0_nag_wp,26.0_nag_wp, &
                                          26.0_nag_wp,28.0_nag_wp,28.0_nag_wp, &
                                          30.0_nag_wp,30.0_nag_wp,30.0_nag_wp, &
                                          32.0_nag_wp,32.0_nag_wp,34.0_nag_wp, &
                                          36.0_nag_wp,36.0_nag_wp,38.0_nag_wp, &
                                          38.0_nag_wp,40.0_nag_wp,             &
                                          42.0_nag_wp/)
!       .. Scalar Arguments ..
        Integer, Intent (In)           :: ldfj, m, n, needfi, nstate
        Integer, Intent (Inout)        :: mode
!       .. Array Arguments ..
        Real (Kind=nag_wp), Intent (Out) :: f(m)
        Real (Kind=nag_wp), Intent (Inout) :: fjac(ldfj,n), ruser(*)
        Real (Kind=nag_wp), Intent (In) :: x(n)
        Integer, Intent (Inout)        :: iuser(*)
!       .. Local Scalars ..
        Real (Kind=nag_wp)             :: ai, temp, x1, x2
        Integer                        :: i
        Logical                        :: mode02, mode12
!       .. Intrinsic Procedures ..
        Intrinsic                      :: exp
!       .. Executable Statements ..
        x1 = x(1)
        x2 = x(2)

        mode02 = (mode==0 .Or. mode==2)
        mode12 = (mode==1 .Or. mode==2)

loop:   Do i = 1, m

          If (needfi==i) Then
            f(i) = x1 + (0.49_nag_wp-x1)*exp(-x2*(a(i)-8.0_nag_wp))
            Exit loop
          End If

          ai = a(i)
          temp = exp(-x2*(ai-8.0_nag_wp))

          If (mode02) Then
            f(i) = x1 + (0.49_nag_wp-x1)*temp
          End If

          If (mode12) Then
            fjac(i,1) = one - temp
            fjac(i,2) = -(0.49_nag_wp-x1)*(ai-8.0_nag_wp)*temp
          End If

        End Do loop

        Return

      End Subroutine objfun
      Subroutine confun(mode,ncnln,n,ldcj,needc,x,c,cjac,nstate,iuser,ruser)
!       Routine to evaluate the nonlinear constraint and its 1st
!       derivatives.

!       .. Scalar Arguments ..
        Integer, Intent (In)           :: ldcj, n, ncnln, nstate
        Integer, Intent (Inout)        :: mode
!       .. Array Arguments ..
        Real (Kind=nag_wp), Intent (Out) :: c(ncnln)
        Real (Kind=nag_wp), Intent (Inout) :: cjac(ldcj,n), ruser(*)
        Real (Kind=nag_wp), Intent (In) :: x(n)
        Integer, Intent (Inout)        :: iuser(*)
        Integer, Intent (In)           :: needc(ncnln)
!       .. Executable Statements ..
        If (nstate==1) Then

!         First call to CONFUN.  Set all Jacobian elements to zero.
!         Note that this will only work when 'Derivative Level = 3'
!         (the default; see Section 11.2).

          cjac(1:ncnln,1:n) = zero
        End If

        If (needc(1)>0) Then

          If (mode==0 .Or. mode==2) Then
            c(1) = -0.09_nag_wp - x(1)*x(2) + 0.49_nag_wp*x(2)
          End If

          If (mode==1 .Or. mode==2) Then
            cjac(1,1) = -x(2)
            cjac(1,2) = -x(1) + 0.49_nag_wp
          End If

        End If

        Return

      End Subroutine confun
    End Module e04uqae_mod
    Program e04uqae

!     E04UQA Example Main Program

!     .. Use Statements ..
      Use nag_library, Only: dgemv, e04uqa, e04ura, e04usa, e04wbf, nag_wp,    &
                             x04abf, x04acf, x04baf
      Use e04uqae_mod, Only: confun, inc1, iset, lcwsav, liwsav, llwsav,       &
                             lrwsav, nin, ninopt, nout, objfun, one, zero
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Character (*), Parameter         :: fname = 'e04uqae.opt'
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: objf
      Integer                          :: i, ifail, inform, iter, j, lda,      &
                                          ldcj, ldfj, ldr, liwork, lwork, m,   &
                                          mode, n, nclin, ncnln, outchn, sda,  &
                                          sdcjac
      Character (80)                   :: rec
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: a(:,:), bl(:), bu(:), c(:),          &
                                          cjac(:,:), clamda(:), f(:),          &
                                          fjac(:,:), r(:,:), work(:), x(:),    &
                                          y(:)
      Real (Kind=nag_wp)               :: rwsav(lrwsav), user(1)
      Integer, Allocatable             :: istate(:), iwork(:)
      Integer                          :: iuser(1), iwsav(liwsav)
      Logical                          :: lwsav(llwsav)
      Character (80)                   :: cwsav(lcwsav)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: max
!     .. Executable Statements ..
      Write (rec,99991) 'E04UQA Example Program Results'
      Call x04baf(nout,rec)

!     Skip heading in data file
      Read (nin,*)

      Read (nin,*) m, n
      Read (nin,*) nclin, ncnln
      liwork = 3*n + nclin + 2*ncnln
      lda = max(1,nclin)

      If (nclin>0) Then
        sda = n
      Else
        sda = 1
      End If

      ldcj = max(1,ncnln)

      If (ncnln>0) Then
        sdcjac = n
      Else
        sdcjac = 1
      End If

      ldfj = m
      ldr = n

      If (ncnln==0 .And. nclin>0) Then
        lwork = 20*n + m*(n+3) + 2*n**2 + 11*nclin
      Else If (ncnln>0 .And. nclin>=0) Then
        lwork = 20*n + m*(n+3) + 2*n**2 + 11*nclin + n*nclin + 2*n*ncnln +     &
          21*ncnln
      Else
        lwork = 20*n + m*(n+3)
      End If

      Allocate (istate(n+nclin+ncnln),iwork(liwork),a(lda,sda),                &
        bl(n+nclin+ncnln),bu(n+nclin+ncnln),y(m),c(max(1,                      &
        ncnln)),cjac(ldcj,sdcjac),f(m),fjac(ldfj,n),clamda(n+nclin+ncnln),     &
        r(ldr,n),x(n),work(lwork))

      If (nclin>0) Then
        Read (nin,*)(a(i,1:sda),i=1,nclin)
      End If

      Read (nin,*) y(1:m)
      Read (nin,*) bl(1:(n+nclin+ncnln))
      Read (nin,*) bu(1:(n+nclin+ncnln))
      Read (nin,*) x(1:n)

!     Set the unit number for advisory messages to OUTCHN

      outchn = nout
      Call x04abf(iset,outchn)

!     Initialise E04USA

      ifail = 0
      Call e04wbf('E04USA',cwsav,lcwsav,lwsav,llwsav,iwsav,liwsav,rwsav,       &
        lrwsav,ifail)

!     Set two options using E04URF

      Call e04ura(' Infinite Bound Size = 1.0D+25 ',lwsav,iwsav,rwsav,inform)

      If (inform==0) Then

        Call e04ura(' Verify Level = -1 ',lwsav,iwsav,rwsav,inform)

      End If

      If (inform/=0) Then
        Write (rec,99992) 'E04URA terminated with INFORM = ', inform
        Call x04baf(nout,rec)
        Go To 100
      End If

!     Open the options file for reading

      mode = 0

      ifail = 0
      Call x04acf(ninopt,fname,mode,ifail)

!     Read the options file for the remaining options

      Call e04uqa(ninopt,lwsav,iwsav,rwsav,inform)

      If (inform/=0) Then
        Write (rec,99992) 'E04UQA terminated with INFORM = ', inform
        Call x04baf(nout,rec)
        Go To 100
      End If

!     Solve the problem

      ifail = -1
      Call e04usa(m,n,nclin,ncnln,lda,ldcj,ldfj,ldr,a,bl,bu,y,confun,objfun,   &
        iter,istate,c,cjac,f,fjac,clamda,objf,r,x,iwork,liwork,work,lwork,     &
        iuser,user,lwsav,iwsav,rwsav,ifail)

      Select Case (ifail)
      Case (0:8)
        Write (rec,'()')
        Call x04baf(nout,rec)
        Write (rec,99999)
        Call x04baf(nout,rec)
        Write (rec,'()')
        Call x04baf(nout,rec)

        Do i = 1, n
          Write (rec,99998) i, istate(i), x(i), clamda(i)
          Call x04baf(nout,rec)
        End Do

        If (nclin>0) Then

!         A*x --> work
!         The NAG name equivalent of dgemv is f06paf
          Call dgemv('N',nclin,n,one,a,lda,x,inc1,zero,work,inc1)

          Write (rec,'()')
          Call x04baf(nout,rec)
          Write (rec,'()')
          Call x04baf(nout,rec)
          Write (rec,99997)
          Call x04baf(nout,rec)
          Write (rec,'()')
          Call x04baf(nout,rec)

          Do i = n + 1, n + nclin
            j = i - n
            Write (rec,99996) j, istate(i), work(j), clamda(i)
            Call x04baf(nout,rec)
          End Do

        End If

        If (ncnln>0) Then
          Write (rec,'()')
          Call x04baf(nout,rec)
          Write (rec,'()')
          Call x04baf(nout,rec)
          Write (rec,99995)
          Call x04baf(nout,rec)
          Write (rec,'()')
          Call x04baf(nout,rec)

          Do i = n + nclin + 1, n + nclin + ncnln
            j = i - n - nclin
            Write (rec,99994) j, istate(i), c(j), clamda(i)
            Call x04baf(nout,rec)
          End Do

        End If

        Write (rec,'()')
        Call x04baf(nout,rec)
        Write (rec,'()')
        Call x04baf(nout,rec)
        Write (rec,99993) objf
        Call x04baf(nout,rec)
      End Select

100   Continue

99999 Format (1X,'Varbl',2X,'Istate',3X,'Value',9X,'Lagr Mult')
99998 Format (1X,'V',2(1X,I3),4X,1P,G14.6,2X,1P,G12.4)
99997 Format (1X,'L Con',2X,'Istate',3X,'Value',9X,'Lagr Mult')
99996 Format (1X,'L',2(1X,I3),4X,1P,G14.6,2X,1P,G12.4)
99995 Format (1X,'N Con',2X,'Istate',3X,'Value',9X,'Lagr Mult')
99994 Format (1X,'N',2(1X,I3),4X,1P,G14.6,2X,1P,G12.4)
99993 Format (1X,'Final objective value = ',G15.7)
99992 Format (1X,A,I5)
99991 Format (1X,A)
    End Program e04uqae


e04uqfe.f90

!   E04UQF Example Program Text
!   Mark 26 Release. NAG Copyright 2016.

    Module e04uqfe_mod

!     E04UQF Example Program Module:
!            Parameters and User-defined Routines

!     .. Use Statements ..
      Use nag_library, Only: nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Accessibility Statements ..
      Private
      Public                           :: confun, objfun
!     .. Parameters ..
      Integer, Parameter, Public       :: iset = 1, nin = 5, ninopt = 7,       &
                                          nout = 6
    Contains
      Subroutine objfun(mode,m,n,ldfj,needfi,x,f,fjac,nstate,iuser,ruser)
!       Routine to evaluate the subfunctions and their 1st derivatives.

!       .. Parameters ..
        Real (Kind=nag_wp), Parameter  :: a(44) = (/8.0E0_nag_wp,8.0E0_nag_wp, &
                                          10.0E0_nag_wp,10.0E0_nag_wp,         &
                                          10.0E0_nag_wp,10.0E0_nag_wp,         &
                                          12.0E0_nag_wp,12.0E0_nag_wp,         &
                                          12.0E0_nag_wp,12.0E0_nag_wp,         &
                                          14.0E0_nag_wp,14.0E0_nag_wp,         &
                                          14.0E0_nag_wp,16.0E0_nag_wp,         &
                                          16.0E0_nag_wp,16.0E0_nag_wp,         &
                                          18.0E0_nag_wp,18.0E0_nag_wp,         &
                                          20.0E0_nag_wp,20.0E0_nag_wp,         &
                                          20.0E0_nag_wp,22.0E0_nag_wp,         &
                                          22.0E0_nag_wp,22.0E0_nag_wp,         &
                                          24.0E0_nag_wp,24.0E0_nag_wp,         &
                                          24.0E0_nag_wp,26.0E0_nag_wp,         &
                                          26.0E0_nag_wp,26.0E0_nag_wp,         &
                                          28.0E0_nag_wp,28.0E0_nag_wp,         &
                                          30.0E0_nag_wp,30.0E0_nag_wp,         &
                                          30.0E0_nag_wp,32.0E0_nag_wp,         &
                                          32.0E0_nag_wp,34.0E0_nag_wp,         &
                                          36.0E0_nag_wp,36.0E0_nag_wp,         &
                                          38.0E0_nag_wp,38.0E0_nag_wp,         &
                                          40.0E0_nag_wp,42.0E0_nag_wp/)
!       .. Scalar Arguments ..
        Integer, Intent (In)           :: ldfj, m, n, needfi, nstate
        Integer, Intent (Inout)        :: mode
!       .. Array Arguments ..
        Real (Kind=nag_wp), Intent (Out) :: f(m)
        Real (Kind=nag_wp), Intent (Inout) :: fjac(ldfj,n), ruser(*)
        Real (Kind=nag_wp), Intent (In) :: x(n)
        Integer, Intent (Inout)        :: iuser(*)
!       .. Local Scalars ..
        Real (Kind=nag_wp)             :: ai, temp, x1, x2
        Integer                        :: i
        Logical                        :: mode02, mode12
!       .. Intrinsic Procedures ..
        Intrinsic                      :: exp
!       .. Executable Statements ..
        x1 = x(1)
        x2 = x(2)

        mode02 = (mode==0 .Or. mode==2)
        mode12 = (mode==1 .Or. mode==2)

loop:   Do i = 1, m

          If (needfi==i) Then
            f(i) = x1 + (0.49E0_nag_wp-x1)*exp(-x2*(a(i)-8.0E0_nag_wp))
            Exit loop
          End If

          ai = a(i)
          temp = exp(-x2*(ai-8.0E0_nag_wp))

          If (mode02) Then
            f(i) = x1 + (0.49E0_nag_wp-x1)*temp
          End If

          If (mode12) Then
            fjac(i,1) = 1.0E0_nag_wp - temp
            fjac(i,2) = -(0.49E0_nag_wp-x1)*(ai-8.0E0_nag_wp)*temp
          End If

        End Do loop

        Return

      End Subroutine objfun
      Subroutine confun(mode,ncnln,n,ldcj,needc,x,c,cjac,nstate,iuser,ruser)
!       Routine to evaluate the nonlinear constraint and its 1st
!       derivatives.

!       .. Scalar Arguments ..
        Integer, Intent (In)           :: ldcj, n, ncnln, nstate
        Integer, Intent (Inout)        :: mode
!       .. Array Arguments ..
        Real (Kind=nag_wp), Intent (Out) :: c(ncnln)
        Real (Kind=nag_wp), Intent (Inout) :: cjac(ldcj,n), ruser(*)
        Real (Kind=nag_wp), Intent (In) :: x(n)
        Integer, Intent (Inout)        :: iuser(*)
        Integer, Intent (In)           :: needc(ncnln)
!       .. Executable Statements ..
        If (nstate==1) Then

!         First call to CONFUN.  Set all Jacobian elements to zero.
!         Note that this will only work when 'Derivative Level = 3'
!         (the default; see Section 11.2).

          cjac(1:ncnln,1:n) = 0.0E0_nag_wp
        End If

        If (needc(1)>0) Then

          If (mode==0 .Or. mode==2) Then
            c(1) = -0.09E0_nag_wp - x(1)*x(2) + 0.49E0_nag_wp*x(2)
          End If

          If (mode==1 .Or. mode==2) Then
            cjac(1,1) = -x(2)
            cjac(1,2) = -x(1) + 0.49E0_nag_wp
          End If

        End If

        Return

      End Subroutine confun
    End Module e04uqfe_mod
    Program e04uqfe

!     E04UQF Example Main Program

!     .. Use Statements ..
      Use nag_library, Only: e04uqf, e04urf, e04usf, nag_wp, x04abf, x04acf,   &
                             x04baf
      Use e04uqfe_mod, Only: confun, iset, nin, ninopt, nout, objfun
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Character (*), Parameter         :: fname = 'e04uqfe.opt'
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: objf
      Integer                          :: i, ifail, inform, iter, lda, ldcj,   &
                                          ldfj, ldr, liwork, lwork, m, mode,   &
                                          n, nclin, ncnln, outchn, sda, sdcjac
      Character (80)                   :: rec
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: a(:,:), bl(:), bu(:), c(:),          &
                                          cjac(:,:), clamda(:), f(:),          &
                                          fjac(:,:), r(:,:), work(:), x(:),    &
                                          y(:)
      Real (Kind=nag_wp)               :: user(1)
      Integer, Allocatable             :: istate(:), iwork(:)
      Integer                          :: iuser(1)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: max
!     .. Executable Statements ..
      Write (rec,99998) 'E04UQF Example Program Results'
      Call x04baf(nout,rec)

!     Skip heading in data file
      Read (nin,*)

      Read (nin,*) m, n
      Read (nin,*) nclin, ncnln
      liwork = 3*n + nclin + 2*ncnln
      lda = max(1,nclin)

      If (nclin>0) Then
        sda = n
      Else
        sda = 1
      End If

      ldcj = max(1,ncnln)

      If (ncnln>0) Then
        sdcjac = n
      Else
        sdcjac = 1
      End If

      ldfj = m
      ldr = n

      If (ncnln==0 .And. nclin>0) Then
        lwork = 2*n**2 + 20*n + 11*nclin + m*(n+3)
      Else If (ncnln>0 .And. nclin>=0) Then
        lwork = 2*n**2 + n*nclin + 2*n*ncnln + 20*n + 11*nclin + 21*ncnln +    &
          m*(n+3)
      Else
        lwork = 20*n + m*(n+3)
      End If

      Allocate (istate(n+nclin+ncnln),iwork(liwork),a(lda,sda),                &
        bl(n+nclin+ncnln),bu(n+nclin+ncnln),y(m),c(max(1,                      &
        ncnln)),cjac(ldcj,sdcjac),f(m),fjac(ldfj,n),clamda(n+nclin+ncnln),     &
        r(ldr,n),x(n),work(lwork))

      If (nclin>0) Then
        Read (nin,*)(a(i,1:sda),i=1,nclin)
      End If

      Read (nin,*) y(1:m)
      Read (nin,*) bl(1:(n+nclin+ncnln))
      Read (nin,*) bu(1:(n+nclin+ncnln))
      Read (nin,*) x(1:n)

!     Set the unit number for advisory messages to OUTCHN

      outchn = nout
      Call x04abf(iset,outchn)

!     Set three options using E04URF

      Call e04urf(' Infinite Bound Size = 1.0D+25 ')

      Call e04urf(' Print Level = 1 ')

      Call e04urf(' Verify Level = -1 ')

!     Open the options file for reading

      mode = 0

      ifail = 0
      Call x04acf(ninopt,fname,mode,ifail)

!     Read the options file for the remaining options

      Call e04uqf(ninopt,inform)

      If (inform/=0) Then
        Write (rec,99999) 'E04UQF terminated with INFORM = ', inform
        Call x04baf(nout,rec)
        Go To 100
      End If

!     Solve the problem

      ifail = 0
      Call e04usf(m,n,nclin,ncnln,lda,ldcj,ldfj,ldr,a,bl,bu,y,confun,objfun,   &
        iter,istate,c,cjac,f,fjac,clamda,objf,r,x,iwork,liwork,work,lwork,     &
        iuser,user,ifail)

100   Continue

99999 Format (1X,A,I5)
99998 Format (1X,A)
    End Program e04uqfe


e04usae.f90

!   E04USA Example Program Text
!   Mark 26 Release. NAG Copyright 2016.

    Module e04usae_mod

!     E04USA Example Program Module:
!            Parameters and User-defined Routines

!     .. Use Statements ..
      Use nag_library, Only: nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Accessibility Statements ..
      Private
      Public                           :: confun, objfun
!     .. Parameters ..
      Real (Kind=nag_wp), Parameter, Public :: one = 1.0_nag_wp
      Real (Kind=nag_wp), Parameter, Public :: zero = 0.0_nag_wp
      Integer, Parameter, Public       :: inc1 = 1, lcwsav = 1, liwsav = 610,  &
                                          llwsav = 120, lrwsav = 475, nin = 5, &
                                          nout = 6
    Contains
      Subroutine objfun(mode,m,n,ldfj,needfi,x,f,fjac,nstate,iuser,ruser)
!       Routine to evaluate the subfunctions and their 1st derivatives.

!       .. Parameters ..
        Real (Kind=nag_wp), Parameter  :: a(44) = (/8.0_nag_wp,8.0_nag_wp,     &
                                          10.0_nag_wp,10.0_nag_wp,10.0_nag_wp, &
                                          10.0_nag_wp,12.0_nag_wp,12.0_nag_wp, &
                                          12.0_nag_wp,12.0_nag_wp,14.0_nag_wp, &
                                          14.0_nag_wp,14.0_nag_wp,16.0_nag_wp, &
                                          16.0_nag_wp,16.0_nag_wp,18.0_nag_wp, &
                                          18.0_nag_wp,20.0_nag_wp,20.0_nag_wp, &
                                          20.0_nag_wp,22.0_nag_wp,22.0_nag_wp, &
                                          22.0_nag_wp,24.0_nag_wp,24.0_nag_wp, &
                                          24.0_nag_wp,26.0_nag_wp,26.0_nag_wp, &
                                          26.0_nag_wp,28.0_nag_wp,28.0_nag_wp, &
                                          30.0_nag_wp,30.0_nag_wp,30.0_nag_wp, &
                                          32.0_nag_wp,32.0_nag_wp,34.0_nag_wp, &
                                          36.0_nag_wp,36.0_nag_wp,38.0_nag_wp, &
                                          38.0_nag_wp,40.0_nag_wp,             &
                                          42.0_nag_wp/)
!       .. Scalar Arguments ..
        Integer, Intent (In)           :: ldfj, m, n, needfi, nstate
        Integer, Intent (Inout)        :: mode
!       .. Array Arguments ..
        Real (Kind=nag_wp), Intent (Out) :: f(m)
        Real (Kind=nag_wp), Intent (Inout) :: fjac(ldfj,n), ruser(*)
        Real (Kind=nag_wp), Intent (In) :: x(n)
        Integer, Intent (Inout)        :: iuser(*)
!       .. Local Scalars ..
        Real (Kind=nag_wp)             :: ai, temp, x1, x2
        Integer                        :: i
        Logical                        :: mode02, mode12
!       .. Intrinsic Procedures ..
        Intrinsic                      :: exp
!       .. Executable Statements ..
        x1 = x(1)
        x2 = x(2)

        mode02 = (mode==0 .Or. mode==2)
        mode12 = (mode==1 .Or. mode==2)

loop:   Do i = 1, m

          If (needfi==i) Then
            f(i) = x1 + (0.49_nag_wp-x1)*exp(-x2*(a(i)-8.0_nag_wp))
            Exit loop
          End If

          ai = a(i)
          temp = exp(-x2*(ai-8.0_nag_wp))

          If (mode02) Then
            f(i) = x1 + (0.49_nag_wp-x1)*temp
          End If

          If (mode12) Then
            fjac(i,1) = one - temp
            fjac(i,2) = -(0.49_nag_wp-x1)*(ai-8.0_nag_wp)*temp
          End If

        End Do loop

        Return

      End Subroutine objfun
      Subroutine confun(mode,ncnln,n,ldcj,needc,x,c,cjac,nstate,iuser,ruser)
!       Routine to evaluate the nonlinear constraint and its 1st
!       derivatives.

!       .. Scalar Arguments ..
        Integer, Intent (In)           :: ldcj, n, ncnln, nstate
        Integer, Intent (Inout)        :: mode
!       .. Array Arguments ..
        Real (Kind=nag_wp), Intent (Out) :: c(ncnln)
        Real (Kind=nag_wp), Intent (Inout) :: cjac(ldcj,n), ruser(*)
        Real (Kind=nag_wp), Intent (In) :: x(n)
        Integer, Intent (Inout)        :: iuser(*)
        Integer, Intent (In)           :: needc(ncnln)
!       .. Executable Statements ..
        If (nstate==1) Then

!         First call to CONFUN.  Set all Jacobian elements to zero.
!         Note that this will only work when 'Derivative Level = 3'
!         (the default; see Section 11.2).

          cjac(1:ncnln,1:n) = zero
        End If

        If (needc(1)>0) Then

          If (mode==0 .Or. mode==2) Then
            c(1) = -0.09_nag_wp - x(1)*x(2) + 0.49_nag_wp*x(2)
          End If

          If (mode==1 .Or. mode==2) Then
            cjac(1,1) = -x(2)
            cjac(1,2) = -x(1) + 0.49_nag_wp
          End If

        End If

        Return

      End Subroutine confun
    End Module e04usae_mod
    Program e04usae

!     E04USA Example Main Program

!     .. Use Statements ..
      Use nag_library, Only: dgemv, e04usa, e04wbf, nag_wp
      Use e04usae_mod, Only: confun, inc1, lcwsav, liwsav, llwsav, lrwsav,     &
                             nin, nout, objfun, one, zero
!     .. Implicit None Statement ..
      Implicit None
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: objf
      Integer                          :: i, ifail, iter, j, lda, ldcj, ldfj,  &
                                          ldr, liwork, lwork, m, n, nclin,     &
                                          ncnln, sda, sdcjac
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: a(:,:), bl(:), bu(:), c(:),          &
                                          cjac(:,:), clamda(:), f(:),          &
                                          fjac(:,:), r(:,:), work(:), x(:),    &
                                          y(:)
      Real (Kind=nag_wp)               :: rwsav(lrwsav), user(1)
      Integer, Allocatable             :: istate(:), iwork(:)
      Integer                          :: iuser(1), iwsav(liwsav)
      Logical                          :: lwsav(llwsav)
      Character (80)                   :: cwsav(lcwsav)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: max
!     .. Executable Statements ..
      Write (nout,*) 'E04USA Example Program Results'

!     Skip heading in data file
      Read (nin,*)

      Read (nin,*) m, n
      Read (nin,*) nclin, ncnln
      liwork = 3*n + nclin + 2*ncnln
      lda = max(1,nclin)

      If (nclin>0) Then
        sda = n
      Else
        sda = 1
      End If

      ldcj = max(1,ncnln)

      If (ncnln>0) Then
        sdcjac = n
      Else
        sdcjac = 1
      End If

      ldfj = m
      ldr = n

      If (ncnln==0 .And. nclin>0) Then
        lwork = 2*n**2 + 20*n + 11*nclin + m*(n+3)
      Else If (ncnln>0 .And. nclin>=0) Then
        lwork = 2*n**2 + n*nclin + 2*n*ncnln + 20*n + 11*nclin + 21*ncnln +    &
          m*(n+3)
      Else
        lwork = 20*n + m*(n+3)
      End If

      Allocate (istate(n+nclin+ncnln),iwork(liwork),a(lda,sda),                &
        bl(n+nclin+ncnln),bu(n+nclin+ncnln),y(m),c(max(1,                      &
        ncnln)),cjac(ldcj,sdcjac),f(m),fjac(ldfj,n),clamda(n+nclin+ncnln),     &
        r(ldr,n),x(n),work(lwork))

      If (nclin>0) Then
        Read (nin,*)(a(i,1:sda),i=1,nclin)
      End If

      Read (nin,*) y(1:m)
      Read (nin,*) bl(1:(n+nclin+ncnln))
      Read (nin,*) bu(1:(n+nclin+ncnln))
      Read (nin,*) x(1:n)

!     Initialise E04USA

      ifail = 0
      Call e04wbf('E04USA',cwsav,lcwsav,lwsav,llwsav,iwsav,liwsav,rwsav,       &
        lrwsav,ifail)

!     Solve the problem

      ifail = -1
      Call e04usa(m,n,nclin,ncnln,lda,ldcj,ldfj,ldr,a,bl,bu,y,confun,objfun,   &
        iter,istate,c,cjac,f,fjac,clamda,objf,r,x,iwork,liwork,work,lwork,     &
        iuser,user,lwsav,iwsav,rwsav,ifail)

      Select Case (ifail)
      Case (0:8)
        Write (nout,*)
        Write (nout,99999)
        Write (nout,*)

        Do i = 1, n
          Write (nout,99998) i, istate(i), x(i), clamda(i)
        End Do

        If (nclin>0) Then

!         A*x --> work
!         The NAG name equivalent of dgemv is f06paf
          Call dgemv('N',nclin,n,one,a,lda,x,inc1,zero,work,inc1)

          Write (nout,*)
          Write (nout,*)
          Write (nout,99997)
          Write (nout,*)

          Do i = n + 1, n + nclin
            j = i - n
            Write (nout,99996) j, istate(i), work(j), clamda(i)
          End Do

        End If

        If (ncnln>0) Then
          Write (nout,*)
          Write (nout,*)
          Write (nout,99995)
          Write (nout,*)

          Do i = n + nclin + 1, n + nclin + ncnln
            j = i - n - nclin
            Write (nout,99994) j, istate(i), c(j), clamda(i)
          End Do

        End If

        Write (nout,*)
        Write (nout,*)
        Write (nout,99993) objf
      End Select

99999 Format (1X,'Varbl',2X,'Istate',3X,'Value',9X,'Lagr Mult')
99998 Format (1X,'V',2(1X,I3),4X,1P,G14.6,2X,1P,G12.4)
99997 Format (1X,'L Con',2X,'Istate',3X,'Value',9X,'Lagr Mult')
99996 Format (1X,'L',2(1X,I3),4X,1P,G14.6,2X,1P,G12.4)
99995 Format (1X,'N Con',2X,'Istate',3X,'Value',9X,'Lagr Mult')
99994 Format (1X,'N',2(1X,I3),4X,1P,G14.6,2X,1P,G12.4)
99993 Format (1X,'Final objective value = ',G15.7)
    End Program e04usae


e04usfe.f90

!   E04USF Example Program Text
!   Mark 26 Release. NAG Copyright 2016.

    Module e04usfe_mod

!     E04USF Example Program Module:
!            Parameters and User-defined Routines

!     .. Use Statements ..
      Use nag_library, Only: nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Accessibility Statements ..
      Private
      Public                           :: confun, objfun
!     .. Parameters ..
      Integer, Parameter, Public       :: nin = 5, nout = 6
    Contains
      Subroutine objfun(mode,m,n,ldfj,needfi,x,f,fjac,nstate,iuser,ruser)
!       Routine to evaluate the subfunctions and their 1st derivatives.

!       .. Parameters ..
        Real (Kind=nag_wp), Parameter  :: a(44) = (/8.0E0_nag_wp,8.0E0_nag_wp, &
                                          10.0E0_nag_wp,10.0E0_nag_wp,         &
                                          10.0E0_nag_wp,10.0E0_nag_wp,         &
                                          12.0E0_nag_wp,12.0E0_nag_wp,         &
                                          12.0E0_nag_wp,12.0E0_nag_wp,         &
                                          14.0E0_nag_wp,14.0E0_nag_wp,         &
                                          14.0E0_nag_wp,16.0E0_nag_wp,         &
                                          16.0E0_nag_wp,16.0E0_nag_wp,         &
                                          18.0E0_nag_wp,18.0E0_nag_wp,         &
                                          20.0E0_nag_wp,20.0E0_nag_wp,         &
                                          20.0E0_nag_wp,22.0E0_nag_wp,         &
                                          22.0E0_nag_wp,22.0E0_nag_wp,         &
                                          24.0E0_nag_wp,24.0E0_nag_wp,         &
                                          24.0E0_nag_wp,26.0E0_nag_wp,         &
                                          26.0E0_nag_wp,26.0E0_nag_wp,         &
                                          28.0E0_nag_wp,28.0E0_nag_wp,         &
                                          30.0E0_nag_wp,30.0E0_nag_wp,         &
                                          30.0E0_nag_wp,32.0E0_nag_wp,         &
                                          32.0E0_nag_wp,34.0E0_nag_wp,         &
                                          36.0E0_nag_wp,36.0E0_nag_wp,         &
                                          38.0E0_nag_wp,38.0E0_nag_wp,         &
                                          40.0E0_nag_wp,42.0E0_nag_wp/)
!       .. Scalar Arguments ..
        Integer, Intent (In)           :: ldfj, m, n, needfi, nstate
        Integer, Intent (Inout)        :: mode
!       .. Array Arguments ..
        Real (Kind=nag_wp), Intent (Out) :: f(m)
        Real (Kind=nag_wp), Intent (Inout) :: fjac(ldfj,n), ruser(*)
        Real (Kind=nag_wp), Intent (In) :: x(n)
        Integer, Intent (Inout)        :: iuser(*)
!       .. Local Scalars ..
        Real (Kind=nag_wp)             :: ai, temp, x1, x2
        Integer                        :: i
        Logical                        :: mode02, mode12
!       .. Intrinsic Procedures ..
        Intrinsic                      :: exp
!       .. Executable Statements ..
        x1 = x(1)
        x2 = x(2)

        If (mode==0 .And. needfi>0) Then
          f(needfi) = x1 + (0.49E0_nag_wp-x1)*exp(-x2*(a(needfi)-8.0E0_nag_wp) &
            )
        Else

          mode02 = (mode==0 .Or. mode==2)
          mode12 = (mode==1 .Or. mode==2)

          Do i = 1, m

            ai = a(i)
            temp = exp(-x2*(ai-8.0E0_nag_wp))

            If (mode02) Then
              f(i) = x1 + (0.49E0_nag_wp-x1)*temp
            End If

            If (mode12) Then
              fjac(i,1) = 1.0E0_nag_wp - temp
              fjac(i,2) = -(0.49E0_nag_wp-x1)*(ai-8.0E0_nag_wp)*temp
            End If

          End Do
        End If

        Return

      End Subroutine objfun
      Subroutine confun(mode,ncnln,n,ldcj,needc,x,c,cjac,nstate,iuser,ruser)
!       Routine to evaluate the nonlinear constraint and its 1st
!       derivatives.

!       .. Scalar Arguments ..
        Integer, Intent (In)           :: ldcj, n, ncnln, nstate
        Integer, Intent (Inout)        :: mode
!       .. Array Arguments ..
        Real (Kind=nag_wp), Intent (Out) :: c(ncnln)
        Real (Kind=nag_wp), Intent (Inout) :: cjac(ldcj,n), ruser(*)
        Real (Kind=nag_wp), Intent (In) :: x(n)
        Integer, Intent (Inout)        :: iuser(*)
        Integer, Intent (In)           :: needc(ncnln)
!       .. Executable Statements ..
        If (nstate==1) Then

!         First call to CONFUN.  Set all Jacobian elements to zero.
!         Note that this will only work when 'Derivative Level = 3'
!         (the default; see Section 11.2).

          cjac(1:ncnln,1:n) = 0.0E0_nag_wp
        End If

        If (needc(1)>0) Then

          If (mode==0 .Or. mode==2) Then
            c(1) = -0.09E0_nag_wp - x(1)*x(2) + 0.49E0_nag_wp*x(2)
          End If

          If (mode==1 .Or. mode==2) Then
            cjac(1,1) = -x(2)
            cjac(1,2) = -x(1) + 0.49E0_nag_wp
          End If

        End If

        Return

      End Subroutine confun
    End Module e04usfe_mod
    Program e04usfe

!     E04USF Example Main Program

!     .. Use Statements ..
      Use nag_library, Only: e04usf, nag_wp
      Use e04usfe_mod, Only: confun, nin, nout, objfun
!     .. Implicit None Statement ..
      Implicit None
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: objf
      Integer                          :: i, ifail, iter, lda, ldcj, ldfj,     &
                                          ldr, liwork, lwork, m, n, nclin,     &
                                          ncnln, sda, sdcjac
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: a(:,:), bl(:), bu(:), c(:),          &
                                          cjac(:,:), clamda(:), f(:),          &
                                          fjac(:,:), r(:,:), work(:), x(:),    &
                                          y(:)
      Real (Kind=nag_wp)               :: user(1)
      Integer, Allocatable             :: istate(:), iwork(:)
      Integer                          :: iuser(1)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: max
!     .. Executable Statements ..
      Write (nout,*) 'E04USF Example Program Results'
      Flush (nout)

!     Skip heading in data file
      Read (nin,*)

      Read (nin,*) m, n
      Read (nin,*) nclin, ncnln
      liwork = 3*n + nclin + 2*ncnln
      lda = max(1,nclin)

      If (nclin>0) Then
        sda = n
      Else
        sda = 1
      End If

      ldcj = max(1,ncnln)

      If (ncnln>0) Then
        sdcjac = n
      Else
        sdcjac = 1
      End If

      ldfj = m
      ldr = n

      If (ncnln==0 .And. nclin>0) Then
        lwork = 2*n**2 + 20*n + 11*nclin + m*(n+3)
      Else If (ncnln>0 .And. nclin>=0) Then
        lwork = 2*n**2 + n*nclin + 2*n*ncnln + 20*n + 11*nclin + 21*ncnln +    &
          m*(n+3)
      Else
        lwork = 20*n + m*(n+3)
      End If

      Allocate (istate(n+nclin+ncnln),iwork(liwork),a(lda,sda),                &
        bl(n+nclin+ncnln),bu(n+nclin+ncnln),y(m),c(max(1,                      &
        ncnln)),cjac(ldcj,sdcjac),f(m),fjac(ldfj,n),clamda(n+nclin+ncnln),     &
        r(ldr,n),x(n),work(lwork))

      If (nclin>0) Then
        Read (nin,*)(a(i,1:sda),i=1,nclin)
      End If

      Read (nin,*) y(1:m)
      Read (nin,*) bl(1:(n+nclin+ncnln))
      Read (nin,*) bu(1:(n+nclin+ncnln))
      Read (nin,*) x(1:n)

!     Solve the problem

      ifail = 0
      Call e04usf(m,n,nclin,ncnln,lda,ldcj,ldfj,ldr,a,bl,bu,y,confun,objfun,   &
        iter,istate,c,cjac,f,fjac,clamda,objf,r,x,iwork,liwork,work,lwork,     &
        iuser,user,ifail)

    End Program e04usfe


e04vhfe.f90

!   E04VHF Example Program Text
!   Mark 26 Release. NAG Copyright 2016.

    Module e04vhfe_mod

!     E04VHF Example Program Module:
!            Parameters and User-defined Routines

!     .. Use Statements ..
      Use nag_library, Only: nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Accessibility Statements ..
      Private
      Public                           :: usrfun
!     .. Parameters ..
      Integer, Parameter, Public       :: lencw = 600, leniw = 600,            &
                                          lenrw = 600, nin = 5, nout = 6
    Contains
      Subroutine usrfun(status,n,x,needf,nf,f,needg,leng,g,cuser,iuser,ruser)

!       .. Scalar Arguments ..
        Integer, Intent (In)           :: leng, n, needf, needg, nf
        Integer, Intent (Inout)        :: status
!       .. Array Arguments ..
        Real (Kind=nag_wp), Intent (Inout) :: f(nf), g(leng), ruser(*)
        Real (Kind=nag_wp), Intent (In) :: x(n)
        Integer, Intent (Inout)        :: iuser(*)
        Character (8), Intent (Inout)  :: cuser(*)
!       .. Intrinsic Procedures ..
        Intrinsic                      :: cos, sin
!       .. Executable Statements ..
        If (needf>0) Then

!         The nonlinear components of f_i(x) need to be assigned,
!         for i = 1 to NF

          f(1) = 1000.0E+0_nag_wp*sin(-x(1)-0.25E+0_nag_wp) +                  &
            1000.0E+0_nag_wp*sin(-x(2)-0.25E+0_nag_wp)
          f(2) = 1000.0E+0_nag_wp*sin(x(1)-0.25E+0_nag_wp) +                   &
            1000.0E+0_nag_wp*sin(x(1)-x(2)-0.25E+0_nag_wp)
          f(3) = 1000.0E+0_nag_wp*sin(x(2)-x(1)-0.25E+0_nag_wp) +              &
            1000.0E+0_nag_wp*sin(x(2)-0.25E+0_nag_wp)

!         N.B. in this example there is no need to assign for the wholly
!         linear components f_4(x) and f_5(x).

          f(6) = 1.0E-6_nag_wp*x(3)**3 + 2.0E-6_nag_wp*x(4)**3/3.0E+0_nag_wp
        End If

        If (needg>0) Then

!         The derivatives of the function f_i(x) need to be assigned.
!         G(k) should be set to partial derivative df_i(x)/dx_j where
!         i = IGFUN(k) and j = IGVAR(k), for k = 1 to LENG.

          g(1) = -1000.0E+0_nag_wp*cos(-x(1)-0.25E+0_nag_wp)
          g(2) = -1000.0E+0_nag_wp*cos(-x(2)-0.25E+0_nag_wp)
          g(3) = 1000.0E+0_nag_wp*cos(x(1)-0.25E+0_nag_wp) +                   &
            1000.0E+0_nag_wp*cos(x(1)-x(2)-0.25E+0_nag_wp)
          g(4) = -1000.0E+0_nag_wp*cos(x(1)-x(2)-0.25E+0_nag_wp)
          g(5) = -1000.0E+0_nag_wp*cos(x(2)-x(1)-0.25E+0_nag_wp)
          g(6) = 1000.0E+0_nag_wp*cos(x(2)-x(1)-0.25E+0_nag_wp) +              &
            1000.0E+0_nag_wp*cos(x(2)-0.25E+0_nag_wp)
          g(7) = 3.0E-6_nag_wp*x(3)**2
          g(8) = 2.0E-6_nag_wp*x(4)**2
        End If

        Return

      End Subroutine usrfun
    End Module e04vhfe_mod
    Program e04vhfe

!     E04VHF Example Main Program

!     .. Use Statements ..
      Use nag_library, Only: e04vgf, e04vhf, e04vmf, nag_wp
      Use e04vhfe_mod, Only: lencw, leniw, lenrw, nin, nout, usrfun
!     .. Implicit None Statement ..
      Implicit None
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: objadd, sinf
      Integer                          :: i, ifail, lena, leng, n, nea, neg,   &
                                          nf, nfname, ninf, ns, nxname,        &
                                          objrow, start
      Logical                          :: verbose_output
      Character (8)                    :: prob
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: a(:), f(:), flow(:), fmul(:),        &
                                          fupp(:), x(:), xlow(:), xmul(:),     &
                                          xupp(:)
      Real (Kind=nag_wp)               :: ruser(1), rw(lenrw)
      Integer, Allocatable             :: fstate(:), iafun(:), igfun(:),       &
                                          javar(:), jgvar(:), xstate(:)
      Integer                          :: iuser(1), iw(leniw)
      Character (8)                    :: cuser(1), cw(lencw)
      Character (8), Allocatable       :: fnames(:), xnames(:)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: max
!     .. Executable Statements ..
      Write (nout,*) 'E04VHF Example Program Results'

!     Skip heading in data file
      Read (nin,*)

      Read (nin,*) n, nf
      Read (nin,*) nea, neg, objrow, start
      lena = max(1,nea)
      leng = max(1,neg)
      nxname = n
      nfname = nf
      Allocate (iafun(lena),javar(lena),igfun(leng),jgvar(leng),xstate(n),     &
        fstate(nf),a(lena),xlow(n),xupp(n),flow(nf),fupp(nf),x(n),xmul(n),     &
        f(nf),fmul(nf),xnames(nxname),fnames(nfname))

!     Read the variable names

      Read (nin,*) xnames(1:nxname)

!     Read the function names

      Read (nin,*) fnames(1:nfname)

!     Read the sparse matrix A, the linear part of F

      Do i = 1, nea

!       For each element read row, column, A(row,column)

        Read (nin,*) iafun(i), javar(i), a(i)
      End Do

!     Read the structure of sparse matrix G, the nonlinear part of F

      Do i = 1, neg

!       For each element read row, column

        Read (nin,*) igfun(i), jgvar(i)
      End Do

!     Read the lower and upper bounds on the variables

      Do i = 1, n
        Read (nin,*) xlow(i), xupp(i)
      End Do

!     Read the lower and upper bounds on the functions

      Do i = 1, nf
        Read (nin,*) flow(i), fupp(i)
      End Do

!     Initialize X, XSTATE, XMUL, F, FSTATE, FMUL

      Read (nin,*) x(1:n)
      Read (nin,*) xstate(1:n)
      Read (nin,*) xmul(1:n)
      Read (nin,*) f(1:nf)
      Read (nin,*) fstate(1:nf)
      Read (nin,*) fmul(1:nf)

      objadd = 0.0E0_nag_wp
      prob = ' '

      Write (nout,99999) n

!     Call E04VGF to initialize E04VHF.

      ifail = 0
      Call e04vgf(cw,lencw,iw,leniw,rw,lenrw,ifail)

!     Set this to .True. to cause e04nqf to produce intermediate
!     progress output
      verbose_output = .False.

      If (verbose_output) Then
!       By default e04vhf does not print monitoring
!       information. Set the print file unit or the summary
!       file unit to get information.
        ifail = 0
        Call e04vmf('Print file',nout,cw,iw,rw,ifail)
      End If

!     Solve the problem.

      ifail = 0
      Call e04vhf(start,nf,n,nxname,nfname,objadd,objrow,prob,usrfun,iafun,    &
        javar,a,lena,nea,igfun,jgvar,leng,neg,xlow,xupp,xnames,flow,fupp,      &
        fnames,x,xstate,xmul,f,fstate,fmul,ns,ninf,sinf,cw,lencw,iw,leniw,rw,  &
        lenrw,cuser,iuser,ruser,ifail)

      Write (nout,*)
      Write (nout,99998) f(objrow)
      Write (nout,99997) x(1:n)

99999 Format (1X,/,1X,'NLP problem contains ',I3,' variables')
99998 Format (1X,'Final objective value = ',F11.1)
99997 Format (1X,'Optimal X = ',7F10.3)
    End Program e04vhfe


e04vjfe.f90

!   E04VJF Example Program Text
!   Mark 26 Release. NAG Copyright 2016.

    Module e04vjfe_mod

!     E04VJF Example Program Module:
!            Parameters and User-defined Routines

!     .. Use Statements ..
      Use nag_library, Only: nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Accessibility Statements ..
      Private
      Public                           :: usrfun
!     .. Parameters ..
      Integer, Parameter, Public       :: lencw = 600, leniw = 600,            &
                                          lenrw = 600, nin = 5, nout = 6
    Contains
      Subroutine usrfun(status,n,x,needf,nf,f,needg,leng,g,cuser,iuser,ruser)

!       .. Scalar Arguments ..
        Integer, Intent (In)           :: leng, n, needf, needg, nf
        Integer, Intent (Inout)        :: status
!       .. Array Arguments ..
        Real (Kind=nag_wp), Intent (Inout) :: f(nf), g(leng), ruser(*)
        Real (Kind=nag_wp), Intent (In) :: x(n)
        Integer, Intent (Inout)        :: iuser(*)
        Character (8), Intent (Inout)  :: cuser(*)
!       .. Intrinsic Procedures ..
        Intrinsic                      :: sin
!       .. Executable Statements ..
        If (needf>0) Then
          f(1) = 1000.0E+0_nag_wp*sin(-x(1)-0.25E+0_nag_wp) +                  &
            1000.0E+0_nag_wp*sin(-x(2)-0.25E+0_nag_wp) - x(3)
          f(2) = 1000.0E+0_nag_wp*sin(x(1)-0.25E+0_nag_wp) +                   &
            1000.0E+0_nag_wp*sin(x(1)-x(2)-0.25E+0_nag_wp) - x(4)
          f(3) = 1000.0E+0_nag_wp*sin(x(2)-x(1)-0.25E+0_nag_wp) +              &
            1000.0E+0_nag_wp*sin(x(2)-0.25E+0_nag_wp)
          f(4) = -x(1) + x(2)
          f(5) = x(1) - x(2)
          f(6) = 1.0E-6_nag_wp*x(3)**3 + 2.0E-6_nag_wp*x(4)**3/3.0E+0_nag_wp + &
            3.0E0_nag_wp*x(3) + 2.0E0_nag_wp*x(4)
        End If

        Return

      End Subroutine usrfun
    End Module e04vjfe_mod
    Program e04vjfe

!     E04VJF Example Main Program

!     .. Use Statements ..
      Use nag_library, Only: e04vgf, e04vhf, e04vjf, e04vlf, e04vmf, nag_wp
      Use e04vjfe_mod, Only: lencw, leniw, lenrw, nin, nout, usrfun
!     .. Implicit None Statement ..
      Implicit None
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: objadd, sinf
      Integer                          :: i, ifail, lena, leng, n, nea, neg,   &
                                          nf, nfname, ninf, ns, nxname,        &
                                          objrow, start
      Logical                          :: verbose_output
      Character (8)                    :: prob
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: a(:), f(:), flow(:), fmul(:),        &
                                          fupp(:), x(:), xlow(:), xmul(:),     &
                                          xupp(:)
      Real (Kind=nag_wp)               :: ruser(1), rw(lenrw)
      Integer, Allocatable             :: fstate(:), iafun(:), igfun(:),       &
                                          javar(:), jgvar(:), xstate(:)
      Integer                          :: iuser(1), iw(leniw)
      Character (8)                    :: cuser(1), cw(lencw)
      Character (8), Allocatable       :: fnames(:), xnames(:)
!     .. Executable Statements ..
      Write (nout,*) 'E04VJF Example Program Results'

!     Skip heading in data file
      Read (nin,*)

      Read (nin,*) n, nf
      lena = 300
      leng = 300
      nxname = 1
      nfname = 1
      Allocate (iafun(lena),javar(lena),igfun(leng),jgvar(leng),xstate(n),     &
        fstate(nf),a(lena),xlow(n),xupp(n),flow(nf),fupp(nf),x(n),xmul(n),     &
        f(nf),fmul(nf),xnames(nxname),fnames(nfname))

      Write (nout,99999) n

!     Call E04VGF to initialise E04VJF.

      ifail = 0
      Call e04vgf(cw,lencw,iw,leniw,rw,lenrw,ifail)

!     Read the bounds on the variables.

      Do i = 1, n
        Read (nin,*) xlow(i), xupp(i)
      End Do

      x(1:n) = 0.0E0_nag_wp

!     Determine the Jacobian structure.

      ifail = 0
      Call e04vjf(nf,n,usrfun,iafun,javar,a,lena,nea,igfun,jgvar,leng,neg,x,   &
        xlow,xupp,cw,lencw,iw,leniw,rw,lenrw,cuser,iuser,ruser,ifail)

!     Print the Jacobian structure.

      Write (nout,*)
      Write (nout,99998) nea
      Write (nout,99997)
      Write (nout,99996)

      Do i = 1, nea
        Write (nout,99995) i, iafun(i), javar(i), a(i)
      End Do

      Write (nout,*)
      Write (nout,99994) neg
      Write (nout,99993)
      Write (nout,99992)

      Do i = 1, neg
        Write (nout,99991) i, igfun(i), jgvar(i)
      End Do

!     Now that we have the determined the structure of the
!     Jacobian, set up the information necessary to solve
!     the optimization problem.

      start = 0
      prob = ' '
      objadd = 0.0E0_nag_wp
      x(1:n) = 0.0E0_nag_wp
      xstate(1:n) = 0
      xmul(1:n) = 0.0E0_nag_wp
      f(1:nf) = 0.0E0_nag_wp
      fstate(1:nf) = 0
      fmul(1:nf) = 0.0E0_nag_wp

!     The row containing the objective function.

      Read (nin,*) objrow

!     Read the bounds on the functions.

      Do i = 1, nf
        Read (nin,*) flow(i), fupp(i)
      End Do

!     Set this to .True. to cause e04nqf to produce intermediate
!     progress output
      verbose_output = .False.

      If (verbose_output) Then
!       By default E04VHF does not print monitoring
!       information. Set the print file unit or the summary
!       file unit to get information.
        ifail = 0
        Call e04vmf('Print file',nout,cw,iw,rw,ifail)
      End If

!     Tell E04VHF that we supply no derivatives in USRFUN.

      ifail = 0
      Call e04vlf('Derivative option 0',cw,iw,rw,ifail)

!     Solve the problem.

      ifail = -1
      Call e04vhf(start,nf,n,nxname,nfname,objadd,objrow,prob,usrfun,iafun,    &
        javar,a,lena,nea,igfun,jgvar,leng,neg,xlow,xupp,xnames,flow,fupp,      &
        fnames,x,xstate,xmul,f,fstate,fmul,ns,ninf,sinf,cw,lencw,iw,leniw,rw,  &
        lenrw,cuser,iuser,ruser,ifail)

      Select Case (ifail)
      Case (0,4)
        Write (nout,*)
        Write (nout,99990) f(objrow)
        Write (nout,99989)(x(i),i=1,n)
      End Select

99999 Format (1X,/,1X,'NLP problem contains ',I3,' variables')
99998 Format (1X,'NEA (the number of nonzero entries in A) = ',I3)
99997 Format (1X,'  I     IAFUN(I)   JAVAR(I)          A(I)')
99996 Format (1X,'----    --------   --------   -----------')
99995 Format (1X,I3,2I10,1P,E18.4)
99994 Format (1X,'NEG (the number of nonzero entries in G) = ',I3)
99993 Format (1X,'  I     IGFUN(I)   JGVAR(I)')
99992 Format (1X,'----    --------   --------')
99991 Format (1X,I3,2I10)
99990 Format (1X,'Final objective value = ',F11.1)
99989 Format (1X,'Optimal X = ',1P,7E12.3)
    End Program e04vjfe


e04vkfe.f90

!   E04VKF Example Program Text
!   Mark 26 Release. NAG Copyright 2016.

    Module e04vkfe_mod

!     E04VKF Example Program Module:
!            Parameters and User-defined Routines

!     .. Use Statements ..
      Use nag_library, Only: nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Accessibility Statements ..
      Private
      Public                           :: usrfun
!     .. Parameters ..
      Integer, Parameter, Public       :: lencw = 600, leniw = 600,            &
                                          lenrw = 600, nin = 5, ninopt = 7,    &
                                          nout = 6
    Contains
      Subroutine usrfun(status,n,x,needf,nf,f,needg,leng,g,cuser,iuser,ruser)

!       .. Scalar Arguments ..
        Integer, Intent (In)           :: leng, n, needf, needg, nf
        Integer, Intent (Inout)        :: status
!       .. Array Arguments ..
        Real (Kind=nag_wp), Intent (Inout) :: f(nf), g(leng), ruser(*)
        Real (Kind=nag_wp), Intent (In) :: x(n)
        Integer, Intent (Inout)        :: iuser(*)
        Character (8), Intent (Inout)  :: cuser(*)
!       .. Intrinsic Procedures ..
        Intrinsic                      :: cos, sin
!       .. Executable Statements ..
        If (needf>0) Then

!         The nonlinear components of f_i(x) need to be assigned,
!         for i = 1 to NF

          f(1) = 1000.0E+0_nag_wp*sin(-x(1)-0.25E+0_nag_wp) +                  &
            1000.0E+0_nag_wp*sin(-x(2)-0.25E+0_nag_wp)
          f(2) = 1000.0E+0_nag_wp*sin(x(1)-0.25E+0_nag_wp) +                   &
            1000.0E+0_nag_wp*sin(x(1)-x(2)-0.25E+0_nag_wp)
          f(3) = 1000.0E+0_nag_wp*sin(x(2)-x(1)-0.25E+0_nag_wp) +              &
            1000.0E+0_nag_wp*sin(x(2)-0.25E+0_nag_wp)

!         N.B. in this example there is no need to assign for the wholly
!         linear components f_4(x) and f_5(x).

          f(6) = 1.0E-6_nag_wp*x(3)**3 + 2.0E-6_nag_wp*x(4)**3/3.0E+0_nag_wp
        End If

        If (needg>0) Then

!         The derivatives of the function f_i(x) need to be assigned.
!         G(k) should be set to partial derivative df_i(x)/dx_j where
!         i = IGFUN(k) and j = IGVAR(k), for k = 1 to LENG.

          g(1) = -1000.0E+0_nag_wp*cos(-x(1)-0.25E+0_nag_wp)
          g(2) = -1000.0E+0_nag_wp*cos(-x(2)-0.25E+0_nag_wp)
          g(3) = 1000.0E+0_nag_wp*cos(x(1)-0.25E+0_nag_wp) +                   &
            1000.0E+0_nag_wp*cos(x(1)-x(2)-0.25E+0_nag_wp)
          g(4) = -1000.0E+0_nag_wp*cos(x(1)-x(2)-0.25E+0_nag_wp)
          g(5) = -1000.0E+0_nag_wp*cos(x(2)-x(1)-0.25E+0_nag_wp)
          g(6) = 1000.0E+0_nag_wp*cos(x(2)-x(1)-0.25E+0_nag_wp) +              &
            1000.0E+0_nag_wp*cos(x(2)-0.25E+0_nag_wp)
          g(7) = 3.0E-6_nag_wp*x(3)**2
          g(8) = 2.0E-6_nag_wp*x(4)**2
        End If

        Return

      End Subroutine usrfun
    End Module e04vkfe_mod
    Program e04vkfe

!     E04VKF Example Main Program

!     .. Use Statements ..
      Use nag_library, Only: e04vgf, e04vhf, e04vkf, e04vlf, e04vmf, e04vnf,   &
                             e04vrf, e04vsf, nag_wp, x04acf
      Use e04vkfe_mod, Only: lencw, leniw, lenrw, nin, ninopt, nout, usrfun
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Character (*), Parameter         :: fname = 'e04vkfe.opt'
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: bndinf, featol, objadd, sinf
      Integer                          :: elmode, i, ifail, lena, leng, mode,  &
                                          n, nea, neg, nf, nfname, ninf, ns,   &
                                          nxname, objrow, start
      Logical                          :: verbose_output
      Character (8)                    :: prob
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: a(:), f(:), flow(:), fmul(:),        &
                                          fupp(:), x(:), xlow(:), xmul(:),     &
                                          xupp(:)
      Real (Kind=nag_wp)               :: ruser(1), rw(lenrw)
      Integer, Allocatable             :: fstate(:), iafun(:), igfun(:),       &
                                          javar(:), jgvar(:), xstate(:)
      Integer                          :: iuser(1), iw(leniw)
      Character (8)                    :: cuser(1), cw(lencw)
      Character (8), Allocatable       :: fnames(:), xnames(:)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: max
!     .. Executable Statements ..
      Write (nout,*) 'E04VKF Example Program Results'

!     This program demonstrates the use of routines to set and
!     get values of optional parameters associated with E04VHF.

!     Skip heading in data file
      Read (nin,*)

      Read (nin,*) n, nf
      Read (nin,*) nea, neg, objrow, start
      lena = max(1,nea)
      leng = max(1,neg)
      nxname = n
      nfname = nf
      Allocate (iafun(lena),javar(lena),igfun(leng),jgvar(leng),xstate(n),     &
        fstate(nf),a(lena),xlow(n),xupp(n),flow(nf),fupp(nf),x(n),xmul(n),     &
        f(nf),fmul(nf),xnames(nxname),fnames(nfname))

!     Read the variable names

      Read (nin,*) xnames(1:nxname)

!     Read the function names

      Read (nin,*) fnames(1:nfname)

!     Read the sparse matrix A, the linear part of F

      Do i = 1, nea

!       For each element read row, column, A(row,column)

        Read (nin,*) iafun(i), javar(i), a(i)
      End Do

!     Read the structure of sparse matrix G, the nonlinear part of F

      Do i = 1, neg

!       For each element read row, column

        Read (nin,*) igfun(i), jgvar(i)
      End Do

!     Read the lower and upper bounds on the variables

      Do i = 1, n
        Read (nin,*) xlow(i), xupp(i)
      End Do

!     Read the lower and upper bounds on the functions

      Do i = 1, nf
        Read (nin,*) flow(i), fupp(i)
      End Do

!     Initialize X, XSTATE, XMUL, F, FSTATE, FMUL

      Read (nin,*) x(1:n)
      Read (nin,*) xstate(1:n)
      Read (nin,*) xmul(1:n)
      Read (nin,*) f(1:nf)
      Read (nin,*) fstate(1:nf)
      Read (nin,*) fmul(1:nf)

      objadd = 0.0E0_nag_wp
      prob = ' '

      Write (nout,99999) n

!     Call E04VGF to initialize E04VHF.

      ifail = 0
      Call e04vgf(cw,lencw,iw,leniw,rw,lenrw,ifail)

!     Set this to .True. to cause e04nqf to produce intermediate
!     progress output
      verbose_output = .False.

      If (verbose_output) Then
!       By default E04VHF does not print monitoring
!       information. Set the print file unit or the summary
!       file unit to get information.
        ifail = 0
        Call e04vmf('Print file',nout,cw,iw,rw,ifail)
      End If

!     Open the options file for reading

      mode = 0

      ifail = 0
      Call x04acf(ninopt,fname,mode,ifail)

!     Use E04VKF to read some options from the options file

      ifail = 0
      Call e04vkf(ninopt,cw,iw,rw,ifail)

      Write (nout,*)

!     Use E04VRF to find the value of integer-valued option
!     'Elastic mode'.

      ifail = 0
      Call e04vrf('Elastic mode',elmode,cw,iw,rw,ifail)

      Write (nout,99998) elmode

!     Use E04VNF to set the value of real-valued option
!     'Infinite bound size'.

      bndinf = 1.0E10_nag_wp

      ifail = 0
      Call e04vnf('Infinite bound size',bndinf,cw,iw,rw,ifail)

!     Use E04VSF to find the value of real-valued option
!     'Feasibility tolerance'.

      ifail = 0
      Call e04vsf('Feasibility tolerance',featol,cw,iw,rw,ifail)

      Write (nout,99997) featol

!     Use E04VLF to set the option 'Major iterations limit'.

      ifail = 0
      Call e04vlf('Major iterations limit 50',cw,iw,rw,ifail)

!     Solve the problem.

      ifail = 0
      Call e04vhf(start,nf,n,nxname,nfname,objadd,objrow,prob,usrfun,iafun,    &
        javar,a,lena,nea,igfun,jgvar,leng,neg,xlow,xupp,xnames,flow,fupp,      &
        fnames,x,xstate,xmul,f,fstate,fmul,ns,ninf,sinf,cw,lencw,iw,leniw,rw,  &
        lenrw,cuser,iuser,ruser,ifail)

      Write (nout,*)
      Write (nout,99996) f(objrow)
      Write (nout,99995) x(1:n)

99999 Format (1X,/,1X,'NLP problem contains ',I3,' variables')
99998 Format (1X,'Option ''Elastic mode'' has the value ',I3,'.')
99997 Format (1X,'Option ''Feasibility tolerance'' has the value ',1P,E11.3,   &
        '.')
99996 Format (1X,'Final objective value = ',F11.1)
99995 Format (1X,'Optimal X = ',1P,7E12.3)
    End Program e04vkfe


e04wdfe.f90

!   E04WDF Example Program Text
!   Mark 26 Release. NAG Copyright 2016.

    Module e04wdfe_mod

!     E04WDF Example Program Module:
!            Parameters and User-defined Routines

!     .. Use Statements ..
      Use nag_library, Only: nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Accessibility Statements ..
      Private
      Public                           :: confun, objfun
!     .. Parameters ..
      Integer, Parameter, Public       :: leniw = 600, lenrw = 600, nin = 5,   &
                                          nout = 6
    Contains
      Subroutine objfun(mode,n,x,objf,grad,nstate,iuser,ruser)
!       Routine to evaluate objective function and its 1st derivatives.

!       .. Scalar Arguments ..
        Real (Kind=nag_wp), Intent (Out) :: objf
        Integer, Intent (Inout)        :: mode
        Integer, Intent (In)           :: n, nstate
!       .. Array Arguments ..
        Real (Kind=nag_wp), Intent (Inout) :: grad(n), ruser(*)
        Real (Kind=nag_wp), Intent (In) :: x(n)
        Integer, Intent (Inout)        :: iuser(*)
!       .. Executable Statements ..
        If (mode==0 .Or. mode==2) Then
          objf = x(1)*x(4)*(x(1)+x(2)+x(3)) + x(3)
        End If

        If (mode==1 .Or. mode==2) Then
          grad(1) = x(4)*(2.0E0_nag_wp*x(1)+x(2)+x(3))
          grad(2) = x(1)*x(4)
          grad(3) = x(1)*x(4) + 1.0E0_nag_wp
          grad(4) = x(1)*(x(1)+x(2)+x(3))
        End If

        Return

      End Subroutine objfun
      Subroutine confun(mode,ncnln,n,ldcj,needc,x,ccon,cjac,nstate,iuser,      &
        ruser)
!       Routine to evaluate the nonlinear constraints and their 1st
!       derivatives.

!       .. Scalar Arguments ..
        Integer, Intent (In)           :: ldcj, n, ncnln, nstate
        Integer, Intent (Inout)        :: mode
!       .. Array Arguments ..
        Real (Kind=nag_wp), Intent (Out) :: ccon(max(1,ncnln))
        Real (Kind=nag_wp), Intent (Inout) :: cjac(ldcj,n), ruser(*)
        Real (Kind=nag_wp), Intent (In) :: x(n)
        Integer, Intent (Inout)        :: iuser(*)
        Integer, Intent (In)           :: needc(ncnln)
!       .. Intrinsic Procedures ..
        Intrinsic                      :: max
!       .. Executable Statements ..
        If (nstate==1) Then

!         First call to CONFUN.  Set all Jacobian elements to zero.
!         Note that this will only work when 'Derivative Level = 3'
!         (the default; see Section 11.2).

          cjac(1:ncnln,1:n) = 0.0E0_nag_wp
        End If

        If (needc(1)>0) Then

          If (mode==0 .Or. mode==2) Then
            ccon(1) = x(1)**2 + x(2)**2 + x(3)**2 + x(4)**2
          End If

          If (mode==1 .Or. mode==2) Then
            cjac(1,1) = 2.0E0_nag_wp*x(1)
            cjac(1,2) = 2.0E0_nag_wp*x(2)
            cjac(1,3) = 2.0E0_nag_wp*x(3)
            cjac(1,4) = 2.0E0_nag_wp*x(4)
          End If

        End If

        If (needc(2)>0) Then

          If (mode==0 .Or. mode==2) Then
            ccon(2) = x(1)*x(2)*x(3)*x(4)
          End If

          If (mode==1 .Or. mode==2) Then
            cjac(2,1) = x(2)*x(3)*x(4)
            cjac(2,2) = x(1)*x(3)*x(4)
            cjac(2,3) = x(1)*x(2)*x(4)
            cjac(2,4) = x(1)*x(2)*x(3)
          End If

        End If

        Return

      End Subroutine confun
    End Module e04wdfe_mod
    Program e04wdfe

!     E04WDF Example Main Program

!     .. Use Statements ..
      Use nag_library, Only: e04wcf, e04wdf, e04wgf, nag_wp
      Use e04wdfe_mod, Only: confun, leniw, lenrw, nin, nout, objfun
!     .. Implicit None Statement ..
      Implicit None
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: objf
      Integer                          :: i, ifail, lda, ldcj, ldh, majits, n, &
                                          nclin, ncnln, sda, sdcjac
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: a(:,:), bl(:), bu(:), ccon(:),       &
                                          cjac(:,:), clamda(:), grad(:),       &
                                          h(:,:), x(:)
      Real (Kind=nag_wp)               :: ruser(1), rw(lenrw)
      Integer, Allocatable             :: istate(:)
      Integer                          :: iuser(1), iw(leniw)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: max
!     .. Executable Statements ..
      Write (nout,*) 'E04WDF Example Program Results'
      Flush (nout)

!     Skip heading in data file
      Read (nin,*)

      Read (nin,*) n, nclin, ncnln
      lda = max(1,nclin)

      If (nclin>0) Then
        sda = n
      Else
        sda = 1
      End If

      ldcj = max(1,ncnln)

      If (ncnln>0) Then
        sdcjac = n
      Else
        sdcjac = 1
      End If

      ldh = n
      Allocate (istate(n+nclin+ncnln),a(lda,sda),bl(n+nclin+ncnln),            &
        bu(n+nclin+ncnln),ccon(max(1,ncnln)),cjac(ldcj,sdcjac),clamda(n+nclin+ &
        ncnln),grad(n),h(ldh,n),x(n))

      If (nclin>0) Then
        Read (nin,*)(a(i,1:sda),i=1,nclin)
      End If

      Read (nin,*) bl(1:(n+nclin+ncnln))
      Read (nin,*) bu(1:(n+nclin+ncnln))
      Read (nin,*) x(1:n)

!     Call E04WCF to initialize E04WDF.

      ifail = 0
      Call e04wcf(iw,leniw,rw,lenrw,ifail)

!     By default E04WDF does not print monitoring
!     information. Set the print file unit or the summary
!     file unit to get information.

      ifail = 0
      Call e04wgf('Print file',nout,iw,rw,ifail)

!     Solve the problem.

      ifail = 0
      Call e04wdf(n,nclin,ncnln,lda,ldcj,ldh,a,bl,bu,confun,objfun,majits,     &
        istate,ccon,cjac,clamda,objf,grad,h,x,iw,leniw,rw,lenrw,iuser,ruser,   &
        ifail)

      Write (nout,*)
      Write (nout,99999) objf
      Write (nout,99998) x(1:n)

99999 Format (1X,'Final objective value = ',F11.3)
99998 Format (1X,'Optimal X = ',7F9.2)
    End Program e04wdfe


e04wefe.f90

!   E04WEF Example Program Text
!   Mark 26 Release. NAG Copyright 2016.

    Module e04wefe_mod

!     E04WEF Example Program Module:
!            Parameters and User-defined Routines

!     .. Use Statements ..
      Use nag_library, Only: nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Accessibility Statements ..
      Private
      Public                           :: confun, objfun
!     .. Parameters ..
      Integer, Parameter, Public       :: leniw = 600, lenrw = 600, nin = 5,   &
                                          ninopt = 7, nout = 6
    Contains
      Subroutine objfun(mode,n,x,objf,grad,nstate,iuser,ruser)
!       Routine to evaluate objective function and its 1st derivatives.

!       .. Scalar Arguments ..
        Real (Kind=nag_wp), Intent (Out) :: objf
        Integer, Intent (Inout)        :: mode
        Integer, Intent (In)           :: n, nstate
!       .. Array Arguments ..
        Real (Kind=nag_wp), Intent (Inout) :: grad(n), ruser(*)
        Real (Kind=nag_wp), Intent (In) :: x(n)
        Integer, Intent (Inout)        :: iuser(*)
!       .. Executable Statements ..
        If (mode==0 .Or. mode==2) Then
          objf = x(1)*x(4)*(x(1)+x(2)+x(3)) + x(3)
        End If

        If (mode==1 .Or. mode==2) Then
          grad(1) = x(4)*(2.0E0_nag_wp*x(1)+x(2)+x(3))
          grad(2) = x(1)*x(4)
          grad(3) = x(1)*x(4) + 1.0E0_nag_wp
          grad(4) = x(1)*(x(1)+x(2)+x(3))
        End If

        Return

      End Subroutine objfun
      Subroutine confun(mode,ncnln,n,ldcj,needc,x,ccon,cjac,nstate,iuser,      &
        ruser)
!       Routine to evaluate the nonlinear constraints and their 1st
!       derivatives.

!       .. Scalar Arguments ..
        Integer, Intent (In)           :: ldcj, n, ncnln, nstate
        Integer, Intent (Inout)        :: mode
!       .. Array Arguments ..
        Real (Kind=nag_wp), Intent (Out) :: ccon(max(1,ncnln))
        Real (Kind=nag_wp), Intent (Inout) :: cjac(ldcj,n), ruser(*)
        Real (Kind=nag_wp), Intent (In) :: x(n)
        Integer, Intent (Inout)        :: iuser(*)
        Integer, Intent (In)           :: needc(ncnln)
!       .. Intrinsic Procedures ..
        Intrinsic                      :: max
!       .. Executable Statements ..
        If (nstate==1) Then

!         First call to CONFUN.  Set all Jacobian elements to zero.
!         Note that this will only work when 'Derivative Level = 3'
!         (the default; see Section 11.2).

          cjac(1:ncnln,1:n) = 0.0E0_nag_wp
        End If

        If (needc(1)>0) Then

          If (mode==0 .Or. mode==2) Then
            ccon(1) = x(1)**2 + x(2)**2 + x(3)**2 + x(4)**2
          End If

          If (mode==1 .Or. mode==2) Then
            cjac(1,1) = 2.0E0_nag_wp*x(1)
            cjac(1,2) = 2.0E0_nag_wp*x(2)
            cjac(1,3) = 2.0E0_nag_wp*x(3)
            cjac(1,4) = 2.0E0_nag_wp*x(4)
          End If

        End If

        If (needc(2)>0) Then

          If (mode==0 .Or. mode==2) Then
            ccon(2) = x(1)*x(2)*x(3)*x(4)
          End If

          If (mode==1 .Or. mode==2) Then
            cjac(2,1) = x(2)*x(3)*x(4)
            cjac(2,2) = x(1)*x(3)*x(4)
            cjac(2,3) = x(1)*x(2)*x(4)
            cjac(2,4) = x(1)*x(2)*x(3)
          End If

        End If

        Return

      End Subroutine confun
    End Module e04wefe_mod
    Program e04wefe

!     E04WEF Example Main Program

!     .. Use Statements ..
      Use nag_library, Only: e04wcf, e04wdf, e04wef, e04wff, e04wgf, e04whf,   &
                             e04wkf, e04wlf, nag_wp, x04acf, x04baf
      Use e04wefe_mod, Only: confun, leniw, lenrw, nin, ninopt, nout, objfun
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Character (*), Parameter         :: fname = 'e04wefe.opt'
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: bndinf, featol, objf
      Integer                          :: elmode, i, ifail, lda, ldcj, ldh,    &
                                          majits, mode, n, nclin, ncnln, sda,  &
                                          sdcjac
      Character (80)                   :: rec
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: a(:,:), bl(:), bu(:), ccon(:),       &
                                          cjac(:,:), clamda(:), grad(:),       &
                                          h(:,:), x(:)
      Real (Kind=nag_wp)               :: ruser(1), rw(lenrw)
      Integer, Allocatable             :: istate(:)
      Integer                          :: iuser(1), iw(leniw)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: max
!     .. Executable Statements ..
      Write (rec,99995) 'E04WEF Example Program Results'
      Call x04baf(nout,rec)

!     This program demonstrates the use of routines to set and
!     get values of optional parameters associated with E04WDF.

!     Skip heading in data file
      Read (nin,*)

      Read (nin,*) n, nclin, ncnln
      lda = max(1,nclin)

      If (nclin>0) Then
        sda = n
      Else
        sda = 1
      End If

      ldcj = max(1,ncnln)

      If (ncnln>0) Then
        sdcjac = n
      Else
        sdcjac = 1
      End If

      ldh = n
      Allocate (istate(n+nclin+ncnln),a(lda,sda),bl(n+nclin+ncnln),            &
        bu(n+nclin+ncnln),ccon(max(1,ncnln)),cjac(ldcj,sdcjac),clamda(n+nclin+ &
        ncnln),grad(n),h(ldh,n),x(n))

      If (nclin>0) Then
        Read (nin,*)(a(i,1:sda),i=1,nclin)
      End If

      Read (nin,*) bl(1:(n+nclin+ncnln))
      Read (nin,*) bu(1:(n+nclin+ncnln))
      Read (nin,*) x(1:n)

!     Call E04WCF to initialize E04WDF.

      ifail = 0
      Call e04wcf(iw,leniw,rw,lenrw,ifail)

!     By default E04WDF does not print monitoring
!     information. Set the print file unit or the summary
!     file unit to get information.

      ifail = 0
      Call e04wgf('Print file',nout,iw,rw,ifail)

!     Open the options file for reading

      mode = 0

      ifail = 0
      Call x04acf(ninopt,fname,mode,ifail)

!     Use E04WEF to read some options from the options file

      ifail = 0
      Call e04wef(ninopt,iw,rw,ifail)

      Write (rec,'()')
      Call x04baf(nout,rec)

!     Use E04WKF to find the value of integer-valued option
!     'Elastic mode'.

      ifail = 0
      Call e04wkf('Elastic mode',elmode,iw,rw,ifail)

      Write (rec,99999) elmode
      Call x04baf(nout,rec)

!     Use E04WHF to set the value of real-valued option
!     'Infinite bound size'.

      bndinf = 1.0E10_nag_wp

      ifail = 0
      Call e04whf('Infinite bound size',bndinf,iw,rw,ifail)

!     Use E04WLF to find the value of real-valued option
!     'Feasibility tolerance'.

      ifail = 0
      Call e04wlf('Feasibility tolerance',featol,iw,rw,ifail)

      Write (rec,99998) featol
      Call x04baf(nout,rec)

!     Use E04WFF to set the option 'Major iterations limit'.

      ifail = 0
      Call e04wff('Major iterations limit 50',iw,rw,ifail)

!     Solve the problem.

      ifail = 0
      Call e04wdf(n,nclin,ncnln,lda,ldcj,ldh,a,bl,bu,confun,objfun,majits,     &
        istate,ccon,cjac,clamda,objf,grad,h,x,iw,leniw,rw,lenrw,iuser,ruser,   &
        ifail)

      Write (rec,'()')
      Call x04baf(nout,rec)
      Write (rec,99997) objf
      Call x04baf(nout,rec)
      Write (rec,99996)(x(i),i=1,n)
      Call x04baf(nout,rec)

99999 Format (1X,'Option ''Elastic mode'' has the value ',I3,'.')
99998 Format (1X,'Option ''Feasibility tolerance'' has the value ',1P,E13.5,   &
        '.')
99997 Format (1X,'Final objective value = ',F11.3)
99996 Format (1X,'Optimal X = ',7F9.2)
99995 Format (1X,A)
    End Program e04wefe


e04xaae.f90

!   E04XAA Example Program Text
!   Mark 26 Release. NAG Copyright 2016.

    Module e04xaae_mod

!     E04XAA Example Program Module:
!            Parameters and User-defined Routines

!     .. Use Statements ..
      Use nag_library, Only: nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Accessibility Statements ..
      Private
      Public                           :: objfun
!     .. Parameters ..
      Integer, Parameter, Public       :: n = 4, nout = 6
      Integer, Parameter, Public       :: lhes = n
      Integer, Parameter, Public       :: lwork = n*n + n
    Contains
      Subroutine objfun(mode,n,x,objf,objgrd,nstate,iuser,ruser)

!       .. Scalar Arguments ..
        Real (Kind=nag_wp), Intent (Out) :: objf
        Integer, Intent (Inout)        :: mode
        Integer, Intent (In)           :: n, nstate
!       .. Array Arguments ..
        Real (Kind=nag_wp), Intent (Out) :: objgrd(n)
        Real (Kind=nag_wp), Intent (Inout) :: ruser(*)
        Real (Kind=nag_wp), Intent (In) :: x(n)
        Integer, Intent (Inout)        :: iuser(*)
!       .. Local Scalars ..
        Real (Kind=nag_wp)             :: a, b, c, d
!       .. Executable Statements ..
        a = x(1) + 10.0E0_nag_wp*x(2)
        b = x(3) - x(4)
        c = x(2) - 2.0E0_nag_wp*x(3)
        d = x(1) - x(4)
        objf = a**2 + 5.0E0_nag_wp*b**2 + c**4 + 10.0E0_nag_wp*d**4

        If (mode==1) Then
          objgrd(1) = 4.0E1_nag_wp*x(1)**3 + 2.0E0_nag_wp*x(1) -               &
            1.2E2_nag_wp*x(4)*x(1)**2 + 1.2E2_nag_wp*x(1)*x(4)**2 +            &
            2.0E1_nag_wp*x(2) - 4.0E1_nag_wp*x(4)**3
          objgrd(2) = 2.0E2_nag_wp*x(2) + 2.0E1_nag_wp*x(1) +                  &
            4.0E0_nag_wp*x(2)**3 + 4.8E1_nag_wp*x(2)*x(3)**2 -                 &
            2.4E1_nag_wp*x(3)*x(2)**2 - 32.0E0_nag_wp*x(3)**3
          objgrd(3) = 1.0E1_nag_wp*x(3) - 1.0E1_nag_wp*x(4) -                  &
            8.0E0_nag_wp*x(2)**3 + 4.8E1_nag_wp*x(3)*x(2)**2 -                 &
            9.6E1_nag_wp*x(2)*x(3)**2 + 6.4E1_nag_wp*x(3)**3
          objgrd(4) = 1.0E1_nag_wp*x(4) - 1.0E1_nag_wp*x(3) -                  &
            4.0E1_nag_wp*x(1)**3 + 1.2E2_nag_wp*x(4)*x(1)**2 -                 &
            1.2E2_nag_wp*x(1)*x(4)**2 + 4.0E1_nag_wp*x(4)**3
        End If

        Return

      End Subroutine objfun
    End Module e04xaae_mod
    Program e04xaae

!     E04XAA Example Main Program

!     .. Use Statements ..
      Use nag_library, Only: e04xaa, nag_wp
      Use e04xaae_mod, Only: lhes, lwork, n, nout, objfun
!     .. Implicit None Statement ..
      Implicit None
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: epsrf, objf
      Integer                          :: i, ifail, imode, iwarn, mode, msglvl
!     .. Local Arrays ..
      Real (Kind=nag_wp)               :: hcntrl(n), hesian(lhes,n), hforw(n), &
                                          objgrd(n), rwsav(1), user(1),        &
                                          work(lwork), x(n)
      Integer                          :: info(n), iuser(1), iwsav(1)
      Logical                          :: lwsav(1)
      Character (80)                   :: rc(3)
!     .. Executable Statements ..
      Write (nout,*) 'E04XAA Example Program Results'

      msglvl = 0

!     Set the point at which the derivatives are to be estimated.

      x(1:n) = (/2.0E0_nag_wp,-1.0E0_nag_wp,1.0E0_nag_wp,1.0E0_nag_wp/)

      rc(1) = 'Find gradients and Hessian diagonals given function only'
      rc(2) = 'Find Hessian matrix given function and gradients'
      rc(3) = 'Find gradients and Hessian matrix given function only'

!     Take default value of EPSRF.

      epsrf = -1.0E0_nag_wp

!     Illustrate the different values of MODE.

loop: Do imode = 0, 2
        mode = imode

!       Set HFORW(I) = -1.0 so that E04XAA computes the initial trial
!       interval.

        hforw(1:n) = -1.0E0_nag_wp

        ifail = -1
        Call e04xaa(msglvl,n,epsrf,x,mode,objfun,lhes,hforw,objf,objgrd,       &
          hcntrl,hesian,iwarn,work,iuser,user,info,lwsav,iwsav,rwsav,ifail)

        Select Case (ifail)
        Case (0,2)
          Write (nout,99999) rc(mode+1), mode
          Write (nout,99998) 'Function value is ', objf

          If (mode==1) Then
            Write (nout,*) 'Gradient vector is'
            Write (nout,99997) objgrd(1:n)
          Else
            Write (nout,*) 'Estimated gradient vector is'
            Write (nout,99997) objgrd(1:n)
          End If

          If (mode==0) Then
            Write (nout,*) 'Estimated Hessian matrix diagonal is'
            Write (nout,99997) hesian(1:n,1)
          Else
            Write (nout,*) 'Estimated Hessian matrix (machine dependent) is'
            Write (nout,99997)(hesian(i,1:n),i=1,n)
          End If

        Case Default
          Exit loop
        End Select

      End Do loop

99999 Format (1X,/,1X,A,/,1X,'( i.e. MODE =',I2,' ).')
99998 Format (1X,A,1P,E12.3)
99997 Format (4(1X,1P,E12.3))
    End Program e04xaae


e04xafe.f90

!   E04XAF Example Program Text
!   Mark 26 Release. NAG Copyright 2016.

    Module e04xafe_mod

!     E04XAF Example Program Module:
!            Parameters and User-defined Routines

!     .. Use Statements ..
      Use nag_library, Only: nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Accessibility Statements ..
      Private
      Public                           :: objfun
!     .. Parameters ..
      Integer, Parameter, Public       :: n = 4, nout = 6
      Integer, Parameter, Public       :: lhes = n
      Integer, Parameter, Public       :: lwork = n*n + n
    Contains
      Subroutine objfun(mode,n,x,objf,objgrd,nstate,iuser,ruser)

!       .. Scalar Arguments ..
        Real (Kind=nag_wp), Intent (Out) :: objf
        Integer, Intent (Inout)        :: mode
        Integer, Intent (In)           :: n, nstate
!       .. Array Arguments ..
        Real (Kind=nag_wp), Intent (Out) :: objgrd(n)
        Real (Kind=nag_wp), Intent (Inout) :: ruser(*)
        Real (Kind=nag_wp), Intent (In) :: x(n)
        Integer, Intent (Inout)        :: iuser(*)
!       .. Local Scalars ..
        Real (Kind=nag_wp)             :: a, b, c, d
!       .. Executable Statements ..
        a = x(1) + 10.0E0_nag_wp*x(2)
        b = x(3) - x(4)
        c = x(2) - 2.0E0_nag_wp*x(3)
        d = x(1) - x(4)
        objf = a**2 + 5.0E0_nag_wp*b**2 + c**4 + 10.0E0_nag_wp*d**4

        If (mode==1) Then
          objgrd(1) = 4.0E1_nag_wp*x(1)**3 + 2.0E0_nag_wp*x(1) -               &
            1.2E2_nag_wp*x(4)*x(1)**2 + 1.2E2_nag_wp*x(1)*x(4)**2 +            &
            2.0E1_nag_wp*x(2) - 4.0E1_nag_wp*x(4)**3
          objgrd(2) = 2.0E2_nag_wp*x(2) + 2.0E1_nag_wp*x(1) +                  &
            4.0E0_nag_wp*x(2)**3 + 4.8E1_nag_wp*x(2)*x(3)**2 -                 &
            2.4E1_nag_wp*x(3)*x(2)**2 - 32.0E0_nag_wp*x(3)**3
          objgrd(3) = 1.0E1_nag_wp*x(3) - 1.0E1_nag_wp*x(4) -                  &
            8.0E0_nag_wp*x(2)**3 + 4.8E1_nag_wp*x(3)*x(2)**2 -                 &
            9.6E1_nag_wp*x(2)*x(3)**2 + 6.4E1_nag_wp*x(3)**3
          objgrd(4) = 1.0E1_nag_wp*x(4) - 1.0E1_nag_wp*x(3) -                  &
            4.0E1_nag_wp*x(1)**3 + 1.2E2_nag_wp*x(4)*x(1)**2 -                 &
            1.2E2_nag_wp*x(1)*x(4)**2 + 4.0E1_nag_wp*x(4)**3
        End If

        Return

      End Subroutine objfun
    End Module e04xafe_mod
    Program e04xafe

!     E04XAF Example Main Program

!     .. Use Statements ..
      Use nag_library, Only: e04xaf, nag_wp
      Use e04xafe_mod, Only: lhes, lwork, n, nout, objfun
!     .. Implicit None Statement ..
      Implicit None
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: epsrf, objf
      Integer                          :: i, ifail, imode, iwarn, mode, msglvl
!     .. Local Arrays ..
      Real (Kind=nag_wp)               :: hcntrl(n), hesian(lhes,n), hforw(n), &
                                          objgrd(n), user(1), work(lwork),     &
                                          x(n)
      Integer                          :: info(n), iuser(1)
      Character (80)                   :: rc(3)
!     .. Executable Statements ..
      Write (nout,*) 'E04XAF Example Program Results'

      msglvl = 0

!     Set the point at which the derivatives are to be estimated.

      x(1:n) = (/2.0E0_nag_wp,-1.0E0_nag_wp,1.0E0_nag_wp,1.0E0_nag_wp/)

      rc(1) = 'Find gradients and Hessian diagonals given function only'
      rc(2) = 'Find Hessian matrix given function and gradients'
      rc(3) = 'Find gradients and Hessian matrix given function only'

!     Take default value of EPSRF.

      epsrf = -1.0E0_nag_wp

!     Illustrate the different values of MODE.

loop: Do imode = 0, 2
        mode = imode

!       Set HFORW(I) = -1.0 so that E04XAF computes the initial trial
!       interval.

        hforw(1:n) = -1.0E0_nag_wp

        ifail = -1
        Call e04xaf(msglvl,n,epsrf,x,mode,objfun,lhes,hforw,objf,objgrd,       &
          hcntrl,hesian,iwarn,work,iuser,user,info,ifail)

        Select Case (ifail)
        Case (0,2)
          Write (nout,99999) rc(mode+1), mode
          Write (nout,99998) 'Function value is ', objf

          If (mode==1) Then
            Write (nout,*) 'Gradient vector is'
            Write (nout,99997) objgrd(1:n)
          Else
            Write (nout,*) 'Estimated gradient vector is'
            Write (nout,99997) objgrd(1:n)
          End If

          If (mode==0) Then
            Write (nout,*) 'Estimated Hessian matrix diagonal is'
            Write (nout,99997) hesian(1:n,1)
          Else
            Write (nout,*) 'Estimated Hessian matrix (machine dependent) is'
            Write (nout,99997)(hesian(i,1:n),i=1,n)
          End If

        Case Default
          Exit loop
        End Select

      End Do loop

99999 Format (1X,/,1X,A,/,1X,'( i.e. MODE =',I2,' ).')
99998 Format (1X,A,1P,E12.3)
99997 Format (4(1X,1P,E12.3))
    End Program e04xafe


e04yafe.f90

!   E04YAF Example Program Text
!   Mark 26 Release. NAG Copyright 2016.

    Module e04yafe_mod

!     E04YAF Example Program Module:
!            Parameters and User-defined Routines

!     .. Use Statements ..
      Use nag_library, Only: nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Accessibility Statements ..
      Private
      Public                           :: lsqfun
!     .. Parameters ..
      Integer, Parameter, Public       :: liw = 1, mdec = 15, ndec = 3,        &
                                          nin = 5, nout = 6
      Integer, Parameter, Public       :: ldfjac = mdec
      Integer, Parameter, Public       :: lw = 3*ndec + mdec + mdec*ndec
!     .. Local Arrays ..
      Real (Kind=nag_wp), Public, Save :: t(mdec,ndec), y(mdec)
    Contains
      Subroutine lsqfun(iflag,m,n,xc,fvec,fjac,ldfjac,iw,liw,w,lw)

!       Routine to evaluate the residuals and their 1st derivatives

!       .. Scalar Arguments ..
        Integer, Intent (Inout)        :: iflag
        Integer, Intent (In)           :: ldfjac, liw, lw, m, n
!       .. Array Arguments ..
        Real (Kind=nag_wp), Intent (Inout) :: fjac(ldfjac,n), w(lw)
        Real (Kind=nag_wp), Intent (Out) :: fvec(m)
        Real (Kind=nag_wp), Intent (In) :: xc(n)
        Integer, Intent (Inout)        :: iw(liw)
!       .. Local Scalars ..
        Real (Kind=nag_wp)             :: denom, dummy
        Integer                        :: i
!       .. Executable Statements ..
        Do i = 1, m
          denom = xc(2)*t(i,2) + xc(3)*t(i,3)

          If (iflag/=1) Then
            fvec(i) = xc(1) + t(i,1)/denom - y(i)
          End If

          If (iflag/=0) Then
            fjac(i,1) = 1.0E0_nag_wp
            dummy = -1.0E0_nag_wp/(denom*denom)
            fjac(i,2) = t(i,1)*t(i,2)*dummy
            fjac(i,3) = t(i,1)*t(i,3)*dummy
          End If

        End Do

        Return

      End Subroutine lsqfun
    End Module e04yafe_mod
    Program e04yafe

!     E04YAF Example Main Program

!     .. Use Statements ..
      Use nag_library, Only: e04yaf, nag_wp
      Use e04yafe_mod, Only: ldfjac, liw, lsqfun, lw, mdec, ndec, nin, nout,   &
                             t, y
!     .. Implicit None Statement ..
      Implicit None
!     .. Local Scalars ..
      Integer                          :: i, ifail, m, n
!     .. Local Arrays ..
      Real (Kind=nag_wp)               :: fjac(ldfjac,ndec), fvec(mdec),       &
                                          w(lw), x(ndec)
      Integer                          :: iw(liw)
!     .. Executable Statements ..
      Write (nout,*) 'E04YAF Example Program Results'

!     Skip heading in data file
      Read (nin,*)

      n = ndec
      m = mdec

!     Observations of TJ (J = 1, 2, ..., n) are held in T(I, J)
!     (I = 1, 2, ..., m)

      Do i = 1, m
        Read (nin,*) y(i), t(i,1:n)
      End Do

!     Set up an arbitrary point at which to check the 1st
!     derivatives

      x(1:n) = (/0.19E0_nag_wp,-1.34E0_nag_wp,0.88E0_nag_wp/)

      Write (nout,*)
      Write (nout,*) 'The test point is'
      Write (nout,99999) x(1:n)

      ifail = -1
      Call e04yaf(m,n,lsqfun,x,fvec,fjac,ldfjac,iw,liw,w,lw,ifail)

      If (ifail>=0 .And. ifail/=1) Then

        Select Case (ifail)
        Case (0)
          Write (nout,*)
          Write (nout,*) '1st derivatives are consistent with residual values'
        Case (2)
          Write (nout,*)
          Write (nout,*) 'Probable error in calculation of 1st derivatives'
        End Select

        Write (nout,*)
        Write (nout,*) 'At the test point, LSQFUN gives'
        Write (nout,*)
        Write (nout,*) '      Residuals                   1st derivatives'
        Write (nout,99998)(fvec(i),fjac(i,1:n),i=1,m)
      End If

99999 Format (1X,4F10.5)
99998 Format (1X,1P,4E15.3)
    End Program e04yafe


e04ybfe.f90

!   E04YBF Example Program Text
!   Mark 26 Release. NAG Copyright 2016.

    Module e04ybfe_mod

!     E04YBF Example Program Module:
!            Parameters and User-defined Routines

!     .. Use Statements ..
      Use nag_library, Only: nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Accessibility Statements ..
      Private
      Public                           :: lsqfun, lsqhes
!     .. Parameters ..
      Integer, Parameter, Public       :: liw = 1, mdec = 15, ndec = 3,        &
                                          nin = 5, nout = 6
      Integer, Parameter, Public       :: lb = ndec*(ndec+1)/2
      Integer, Parameter, Public       :: ldfjac = mdec
      Integer, Parameter, Public       :: lw = 5*ndec + mdec + mdec*ndec +     &
                                          ndec*(ndec-1)/2
!     .. Local Arrays ..
      Real (Kind=nag_wp), Public, Save :: t(mdec,ndec), y(mdec)
    Contains
      Subroutine lsqfun(iflag,m,n,xc,fvec,fjac,ldfjac,iw,liw,w,lw)

!       Routine to evaluate the residuals and their 1st derivatives

!       .. Scalar Arguments ..
        Integer, Intent (Inout)        :: iflag
        Integer, Intent (In)           :: ldfjac, liw, lw, m, n
!       .. Array Arguments ..
        Real (Kind=nag_wp), Intent (Inout) :: fjac(ldfjac,n), w(lw)
        Real (Kind=nag_wp), Intent (Out) :: fvec(m)
        Real (Kind=nag_wp), Intent (In) :: xc(n)
        Integer, Intent (Inout)        :: iw(liw)
!       .. Local Scalars ..
        Real (Kind=nag_wp)             :: denom, dummy
        Integer                        :: i
!       .. Executable Statements ..
        Do i = 1, m
          denom = xc(2)*t(i,2) + xc(3)*t(i,3)
          fvec(i) = xc(1) + t(i,1)/denom - y(i)
          fjac(i,1) = 1.0E0_nag_wp
          dummy = -1.0E0_nag_wp/(denom*denom)
          fjac(i,2) = t(i,1)*t(i,2)*dummy
          fjac(i,3) = t(i,1)*t(i,3)*dummy
        End Do

        Return

      End Subroutine lsqfun
      Subroutine lsqhes(iflag,m,n,fvec,xc,b,lb,iw,liw,w,lw)

!       Routine to compute the lower triangle of the matrix B
!       (stored by rows in the array B)

!       .. Scalar Arguments ..
        Integer, Intent (Inout)        :: iflag
        Integer, Intent (In)           :: lb, liw, lw, m, n
!       .. Array Arguments ..
        Real (Kind=nag_wp), Intent (Out) :: b(lb)
        Real (Kind=nag_wp), Intent (In) :: fvec(m), xc(n)
        Real (Kind=nag_wp), Intent (Inout) :: w(lw)
        Integer, Intent (Inout)        :: iw(liw)
!       .. Local Scalars ..
        Real (Kind=nag_wp)             :: dummy, sum22, sum32, sum33
        Integer                        :: i
!       .. Executable Statements ..
        b(1) = 0.0E0_nag_wp
        b(2) = 0.0E0_nag_wp
        sum22 = 0.0E0_nag_wp
        sum32 = 0.0E0_nag_wp
        sum33 = 0.0E0_nag_wp

        Do i = 1, m
          dummy = 2.0E0_nag_wp*t(i,1)/(xc(2)*t(i,2)+xc(3)*t(i,3))**3
          sum22 = sum22 + fvec(i)*dummy*t(i,2)**2
          sum32 = sum32 + fvec(i)*dummy*t(i,2)*t(i,3)
          sum33 = sum33 + fvec(i)*dummy*t(i,3)**2
        End Do

        b(3) = sum22
        b(4) = 0.0E0_nag_wp
        b(5) = sum32
        b(6) = sum33

        Return

      End Subroutine lsqhes
    End Module e04ybfe_mod
    Program e04ybfe

!     E04YBF Example Main Program

!     .. Use Statements ..
      Use nag_library, Only: e04yaf, e04ybf, nag_wp
      Use e04ybfe_mod, Only: lb, ldfjac, liw, lsqfun, lsqhes, lw, mdec, ndec,  &
                             nin, nout, t, y
!     .. Implicit None Statement ..
      Implicit None
!     .. Local Scalars ..
      Integer                          :: i, ifail, k, m, n
!     .. Local Arrays ..
      Real (Kind=nag_wp)               :: b(lb), fjac(ldfjac,ndec),            &
                                          fvec(mdec), w(lw), x(ndec)
      Integer                          :: iw(liw)
!     .. Executable Statements ..
      Write (nout,*) 'E04YBF Example Program Results'

!     Skip heading in data file
      Read (nin,*)

      m = mdec
      n = ndec

!     Observations of TJ (J = 1, 2, ..., n) are held in T(I, J)
!     (I = 1, 2, ..., m)

      Do i = 1, m
        Read (nin,*) y(i), t(i,1:n)
      End Do

!     Set up an arbitrary point at which to check the derivatives

      x(1:n) = (/0.19E0_nag_wp,-1.34E0_nag_wp,0.88E0_nag_wp/)

!     Check the 1st derivatives

      ifail = 0
      Call e04yaf(m,n,lsqfun,x,fvec,fjac,ldfjac,iw,liw,w,lw,ifail)

      Write (nout,*)
      Write (nout,*) 'The test point is'
      Write (nout,99999) x(1:n)

!     Check the evaluation of B

      ifail = -1
      Call e04ybf(m,n,lsqfun,lsqhes,x,fvec,fjac,ldfjac,b,lb,iw,liw,w,lw,ifail)

      If (ifail>=0 .And. ifail/=1) Then

        Select Case (ifail)
        Case (0)
          Write (nout,*)
          Write (nout,*) 'The matrix B is consistent with 1st derivatives'
        Case (2)
          Write (nout,*)
          Write (nout,*) 'Probable error in calculation of the matrix B'
        End Select

        Write (nout,*)
        Write (nout,*) 'At the test point, LSQFUN gives'
        Write (nout,*)
        Write (nout,*) '      Residuals                   1st derivatives'
        Write (nout,99998)(fvec(i),fjac(i,1:n),i=1,m)
        Write (nout,*)
        Write (nout,*) 'and LSQHES gives the lower triangle of the matrix B'
        Write (nout,*)

        k = 1

        Do i = 1, n
          Write (nout,99998) b(k:(k+i-1))
          k = k + i
        End Do

      End If

99999 Format (1X,4F10.5)
99998 Format (1X,1P,4E15.3)
    End Program e04ybfe


e04ycfe.f90

!   E04YCF Example Program Text
!   Mark 26 Release. NAG Copyright 2016.

    Module e04ycfe_mod

!     E04YCF Example Program Module:
!            Parameters and User-defined Routines

!     .. Use Statements ..
      Use nag_library, Only: nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Accessibility Statements ..
      Private
      Public                           :: lsfun1
!     .. Parameters ..
      Integer, Parameter, Public       :: mdec = 15, ndec = 3, nin = 5,        &
                                          nout = 6
      Integer, Parameter, Public       :: lwork = 7*ndec + ndec*ndec + 2*mdec* &
                                          ndec + 3*mdec + ndec*(ndec-1)/2
!     .. Local Arrays ..
      Real (Kind=nag_wp), Public, Save :: t(mdec,ndec), y(mdec)
    Contains
      Subroutine lsfun1(m,n,xc,fvec,iuser,ruser)
!       Routine to evaluate the residuals

!       .. Scalar Arguments ..
        Integer, Intent (In)           :: m, n
!       .. Array Arguments ..
        Real (Kind=nag_wp), Intent (Out) :: fvec(m)
        Real (Kind=nag_wp), Intent (Inout) :: ruser(*)
        Real (Kind=nag_wp), Intent (In) :: xc(n)
        Integer, Intent (Inout)        :: iuser(*)
!       .. Executable Statements ..
        fvec(1:m) = xc(1) + t(1:m,1)/(xc(2)*t(1:m,2)+xc(3)*t(1:m,3)) - y(1:m)

        Return

      End Subroutine lsfun1
    End Module e04ycfe_mod
    Program e04ycfe

!     E04YCF Example Main Program

!     .. Use Statements ..
      Use nag_library, Only: e04fyf, e04ycf, nag_wp
      Use e04ycfe_mod, Only: lsfun1, lwork, mdec, ndec, nin, nout, t, y
!     .. Implicit None Statement ..
      Implicit None
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: fsumsq
      Integer                          :: i, ifail, job, ldv, m, n, ns, nv
!     .. Local Arrays ..
      Real (Kind=nag_wp)               :: cj(ndec), ruser(1), work(lwork),     &
                                          x(ndec)
      Integer                          :: iuser(1)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: max
!     .. Executable Statements ..
      Write (nout,*) 'E04YCF Example Program Results'

!     Skip heading in data file
      Read (nin,*)

      m = mdec
      n = ndec

!     Observations of TJ (J = 1, 2, ..., n) are held in T(I, J)
!     (I = 1, 2, ..., m)

      Do i = 1, m
        Read (nin,*) y(i), t(i,1:n)
      End Do

      x(1:n) = (/0.5E0_nag_wp,1.0E0_nag_wp,1.5E0_nag_wp/)

      ifail = -1
      Call e04fyf(m,n,lsfun1,x,fsumsq,work,lwork,iuser,ruser,ifail)

      Select Case (ifail)
      Case (0,2:)
        Write (nout,*)
        Write (nout,99999) 'On exit, the sum of squares is', fsumsq
        Write (nout,*) 'at the point'
        Write (nout,99998) x(1:n)

!       Compute estimates of the variances of the sample regression
!       coefficients at the final point.
!       Since NS is greater than N we can use the first N elements
!       of the array WORK for the dummy argument WORK.

        ns = 6*n + 2*m + m*n + 1 + max(1,(n*(n-1))/2)
        nv = ns + n
        job = 0
        ldv = n

        ifail = -1
        Call e04ycf(job,m,n,fsumsq,work(ns),work(nv),ldv,cj,work,ifail)

        Select Case (ifail)
        Case (0,3:)
          Write (nout,*)
          Write (nout,*) 'and estimates of the variances of the sample'
          Write (nout,*) 'regression coefficients are'
          Write (nout,99998) cj(1:n)
        End Select

      End Select

99999 Format (1X,A,F12.4)
99998 Format (1X,3F12.4)
    End Program e04ycfe


e05jbfe.f90

!   E05JBF Example Program Text
!   Mark 26 Release. NAG Copyright 2016.

    Module e05jbfe_mod

!     E05JBF Example Program Module:
!            Parameters and User-defined Routines

!     .. Use Statements ..
      Use nag_library, Only: nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Accessibility Statements ..
      Private
      Public                           :: monit, objfun
!     .. Parameters ..
      Integer, Parameter, Public       :: lcomm = 100, nin = 5, nout = 6
!     .. Local Scalars ..
      Logical, Public, Save            :: plot
    Contains
      Subroutine outbox(boxl,boxu)

!       Displays edges of box with bounds BOXL and BOXU in format suitable
!       for plotting.

!       .. Array Arguments ..
        Real (Kind=nag_wp), Intent (In) :: boxl(2), boxu(2)
!       .. Executable Statements ..
        Write (nout,99999) boxl(1), boxl(2)
        Write (nout,99999) boxl(1), boxu(2)
        Write (nout,99998)
        Write (nout,99999) boxl(1), boxl(2)
        Write (nout,99999) boxu(1), boxl(2)
        Write (nout,99998)
        Write (nout,99999) boxl(1), boxu(2)
        Write (nout,99999) boxu(1), boxu(2)
        Write (nout,99998)
        Write (nout,99999) boxu(1), boxl(2)
        Write (nout,99999) boxu(1), boxu(2)
        Write (nout,99998)

        Return

99999   Format (F20.15,1X,F20.15)
99998   Format (A)
      End Subroutine outbox
      Subroutine objfun(n,x,f,nstate,iuser,ruser,inform)

!       Routine to evaluate E05JBF objective function.

!       .. Scalar Arguments ..
        Real (Kind=nag_wp), Intent (Out) :: f
        Integer, Intent (Out)          :: inform
        Integer, Intent (In)           :: n, nstate
!       .. Array Arguments ..
        Real (Kind=nag_wp), Intent (Inout) :: ruser(*)
        Real (Kind=nag_wp), Intent (In) :: x(n)
        Integer, Intent (Inout)        :: iuser(*)
!       .. Local Scalars ..
        Real (Kind=nag_wp)             :: x1, x2
!       .. Intrinsic Procedures ..
        Intrinsic                      :: exp
!       .. Executable Statements ..

!       This is a two-dimensional objective function.
!       As an example of using the inform mechanism,
!       terminate if any other problem size is supplied.

        If (n/=2) Then
          inform = -1
        Else
          inform = 0

          If (inform>=0) Then

!           If INFORM>=0 then we're prepared to evaluate OBJFUN
!           at the current X

            If (nstate==1) Then

!             This is the first call to OBJFUN

              Write (nout,*)
              Write (nout,99999)
            End If

            x1 = x(1)
            x2 = x(2)

            f = 3.0E0_nag_wp*(1.0E0_nag_wp-x1)**2*exp(-(x1**2)-(x2+            &
              1.0E0_nag_wp)**2) - 1.0E1_nag_wp*(x1/5.0E0_nag_wp-x1**3-x2**5)*  &
              exp(-x1**2-x2**2) - 1.0E0_nag_wp/3.0E0_nag_wp*exp(-(x1+          &
              1.0E0_nag_wp)**2-x2**2)
          End If

        End If

        Return

99999   Format (1X,'(OBJFUN was just called for the first time)')
      End Subroutine objfun
      Subroutine monit(n,ncall,xbest,icount,ninit,list,numpts,initpt,nbaskt,   &
        xbaskt,boxl,boxu,nstate,iuser,ruser,inform)

!       Monitoring routine for E05JBF.

!       .. Scalar Arguments ..
        Integer, Intent (Out)          :: inform
        Integer, Intent (In)           :: n, nbaskt, ncall, ninit, nstate
!       .. Array Arguments ..
        Real (Kind=nag_wp), Intent (In) :: boxl(n), boxu(n), list(n,ninit),    &
                                          xbaskt(n,nbaskt), xbest(n)
        Real (Kind=nag_wp), Intent (Inout) :: ruser(*)
        Integer, Intent (In)           :: icount(6), initpt(n), numpts(n)
        Integer, Intent (Inout)        :: iuser(*)
!       .. Local Scalars ..
        Integer                        :: i
!       .. Executable Statements ..
        inform = 0

        If (inform>=0) Then

!         We are going to allow the iterations to continue.

          If (nstate==0 .Or. nstate==1) Then

!           When NSTATE==1, MONIT is called for the first time. When
!           NSTATE==0, MONIT is called for the first AND last time.
!           Display a welcome message

            Write (nout,*)
            Write (nout,99999)
            Write (nout,*)

            Write (nout,99998)

            Do i = 1, n
              Write (nout,99997)
              Write (nout,99996) i
              Write (nout,99995) numpts(i)
              Write (nout,99994)
              Write (nout,99993) list(i,1:numpts(i))
              Write (nout,99992) initpt(i)
            End Do

            If (plot .And. (n==2)) Then
              Write (nout,99991)
              Write (nout,*)
            End If

          End If

          If (plot .And. (n==2)) Then

!           Display the coordinates of the edges of the current search
!           box

            Call outbox(boxl,boxu)

          End If

          If (nstate<=0) Then

!           MONIT is called for the last time

            If (plot .And. (n==2)) Then
              Write (nout,99990)
              Write (nout,*)
            End If

            Write (nout,99989) icount(1)
            Write (nout,99988) 10*((ncall+5)/10)
            Write (nout,99987) 10*((icount(2)+5)/10)
            Write (nout,99986) icount(3)
            Write (nout,99985) icount(4)
            Write (nout,99984) icount(5)
            Write (nout,99983) icount(6)
            Write (nout,99982) nbaskt
            Write (nout,99981)

            Do i = 1, n
              Write (nout,99980) i, xbaskt(i,1:nbaskt)
            End Do

            Write (nout,99979)
            Write (nout,99978) xbest(1:n)

            Write (nout,*)
            Write (nout,99977)
            Write (nout,*)
          End If

        End If

        Return

99999   Format (1X,'*** Begin monitoring information ***')
99998   Format (1X,'Values controlling initial splitting of a box:')
99997   Format (1X,'**')
99996   Format (1X,'In dimension ',I5)
99995   Format (1X,'Extent of initialization list in this dimension =',I5)
99994   Format (1X,'Initialization points in this dimension:')
99993   Format (1X,'LIST(I,1:NUMPTS(I)) =',(6F9.5))
99992   Format (1X,'Initial point in this dimension: LIST(I,',I5,')')
99991   Format (1X,'<Begin displaying search boxes>')
99990   Format (1X,'<End displaying search boxes>')
99989   Format (1X,'Total sub-boxes =',I5)
99988   Format (1X,'Total function evaluations (rounded to nearest 10) =',I5)
99987   Format (1X,'Total function evaluations used in local search (rounded', &
          /,3X,'to nearest 10) =',I5)
99986   Format (1X,'Total points used in local search =',I5)
99985   Format (1X,'Total sweeps through levels =',I5)
99984   Format (1X,'Total splits by init. list =',I5)
99983   Format (1X,'Lowest level with nonsplit boxes =',I5)
99982   Format (1X,'Number of candidate minima in the "shopping basket','" =', &
          I5)
99981   Format (1X,'Shopping basket:')
99980   Format (1X,'XBASKT(',I3,',:) =',(6F9.5))
99979   Format (1X,'Best point:')
99978   Format (1X,'XBEST =',(6F9.5))
99977   Format (1X,'*** End monitoring information ***')
      End Subroutine monit
    End Module e05jbfe_mod
    Program e05jbfe

!     E05JBF Example Main Program

!     .. Use Statements ..
      Use nag_library, Only: e05jaf, e05jbf, nag_wp
      Use e05jbfe_mod, Only: lcomm, monit, nin, nout, objfun, plot
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: n = 2
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: obj
      Integer                          :: i, ibound, ifail, iinit, sdlist
!     .. Local Arrays ..
      Real (Kind=nag_wp)               :: bl(n), bu(n), comm(lcomm), ruser(1), &
                                          x(n)
      Real (Kind=nag_wp), Allocatable  :: list(:,:)
      Integer                          :: initpt(n), iuser(1), numpts(n)
!     .. Executable Statements ..
      Write (nout,*) 'E05JBF Example Program Results'

!     Skip heading in data file
      Read (nin,*)

      Read (nin,*) sdlist
      Allocate (list(n,sdlist))

      Read (nin,*) ibound

      If (ibound==0) Then

!       Read in the whole of each bound

        Read (nin,*)(bl(i),i=1,n)
        Read (nin,*)(bu(i),i=1,n)
      Else If (ibound==3) Then

!       Bounds are uniform: read in only the first entry of each

        Read (nin,*) bl(1)
        Read (nin,*) bu(1)
      End If

      Read (nin,*) iinit

!     PLOT determines whether MONIT displays information on the
!     current search box:

      Read (nin,*) plot

!     The first argument to E05JAF is a legacy argument and has no
!     significance.

      ifail = 0
      Call e05jaf(0,comm,lcomm,ifail)

!     Solve the problem.

      ifail = 0
      Call e05jbf(n,objfun,ibound,iinit,bl,bu,sdlist,list,numpts,initpt,monit, &
        x,obj,comm,lcomm,iuser,ruser,ifail)

      Write (nout,*)
      Write (nout,99999) obj
      Write (nout,99998)(x(i),i=1,n)

99999 Format (1X,'Final objective value =',F11.5)
99998 Format (1X,'Global optimum X =',2F9.5)
    End Program e05jbfe


e05jcfe.f90

!   E05JCF Example Program Text
!   Mark 26 Release. NAG Copyright 2016.

    Module e05jcfe_mod

!     E05JCF Example Program Module:
!            Parameters and User-defined Routines

!     .. Use Statements ..
      Use nag_library, Only: nag_wp, x04baf
!     .. Implicit None Statement ..
      Implicit None
!     .. Accessibility Statements ..
      Private
      Public                           :: monit, objfun
!     .. Parameters ..
      Integer, Parameter, Public       :: lcomm = 100, nin = 5, ninopt = 7,    &
                                          nout = 6
!     .. Local Scalars ..
      Logical, Public, Save            :: plot
    Contains
      Subroutine outbox(boxl,boxu)

!       Displays edges of box with bounds BOXL and BOXU in format suitable
!       for plotting.

!       .. Array Arguments ..
        Real (Kind=nag_wp), Intent (In) :: boxl(2), boxu(2)
!       .. Local Scalars ..
        Character (80)                 :: rec
!       .. Executable Statements ..
        Write (rec,99999) boxl(1), boxl(2)
        Call x04baf(nout,rec)
        Write (rec,99999) boxl(1), boxu(2)
        Call x04baf(nout,rec)
        Write (rec,'()')
        Call x04baf(nout,rec)
        Write (rec,99999) boxl(1), boxl(2)
        Call x04baf(nout,rec)
        Write (rec,99999) boxu(1), boxl(2)
        Call x04baf(nout,rec)
        Write (rec,'()')
        Call x04baf(nout,rec)
        Write (rec,99999) boxl(1), boxu(2)
        Call x04baf(nout,rec)
        Write (rec,99999) boxu(1), boxu(2)
        Call x04baf(nout,rec)
        Write (rec,'()')
        Call x04baf(nout,rec)
        Write (rec,99999) boxu(1), boxl(2)
        Call x04baf(nout,rec)
        Write (rec,99999) boxu(1), boxu(2)
        Call x04baf(nout,rec)
        Write (rec,'()')
        Call x04baf(nout,rec)

        Return

99999   Format (F20.15,1X,F20.15)
      End Subroutine outbox
      Subroutine objfun(n,x,f,nstate,iuser,ruser,inform)

!       Routine to evaluate E05JBF objective function.

!       .. Scalar Arguments ..
        Real (Kind=nag_wp), Intent (Out) :: f
        Integer, Intent (Out)          :: inform
        Integer, Intent (In)           :: n, nstate
!       .. Array Arguments ..
        Real (Kind=nag_wp), Intent (Inout) :: ruser(*)
        Real (Kind=nag_wp), Intent (In) :: x(n)
        Integer, Intent (Inout)        :: iuser(*)
!       .. Local Scalars ..
        Real (Kind=nag_wp)             :: x1, x2
        Character (80)                 :: rec
!       .. Intrinsic Procedures ..
        Intrinsic                      :: exp
!       .. Executable Statements ..

!       This is a two-dimensional objective function.
!       As an example of using the inform mechanism,
!       terminate if any other problem size is supplied.

        If (n/=2) Then
          inform = -1
        Else
          inform = 0

          If (inform>=0) Then

!           If INFORM >= 0 then we're prepared to evaluate OBJFUN
!           at the current X

            If (nstate==1) Then

!             This is the first call to OBJFUN

              Write (rec,'()')
              Call x04baf(nout,rec)
              Write (rec,99999)
              Call x04baf(nout,rec)
            End If

            x1 = x(1)
            x2 = x(2)

            f = 3.0E0_nag_wp*(1.0E0_nag_wp-x1)**2*exp(-(x1**2)-(x2+            &
              1.0E0_nag_wp)**2) - 1.0E1_nag_wp*(x1/5.0E0_nag_wp-x1**3-x2**5)*  &
              exp(-x1**2-x2**2) - 1.0E0_nag_wp/3.0E0_nag_wp*exp(-(x1+          &
              1.0E0_nag_wp)**2-x2**2)
          End If

        End If

        Return

99999   Format (1X,'(OBJFUN was just called for the first time)')
      End Subroutine objfun
      Subroutine monit(n,ncall,xbest,icount,ninit,list,numpts,initpt,nbaskt,   &
        xbaskt,boxl,boxu,nstate,iuser,ruser,inform)

!       Monitoring routine for E05JBF.

!       .. Scalar Arguments ..
        Integer, Intent (Out)          :: inform
        Integer, Intent (In)           :: n, nbaskt, ncall, ninit, nstate
!       .. Array Arguments ..
        Real (Kind=nag_wp), Intent (In) :: boxl(n), boxu(n), list(n,ninit),    &
                                          xbaskt(n,nbaskt), xbest(n)
        Real (Kind=nag_wp), Intent (Inout) :: ruser(*)
        Integer, Intent (In)           :: icount(6), initpt(n), numpts(n)
        Integer, Intent (Inout)        :: iuser(*)
!       .. Local Scalars ..
        Integer                        :: i
        Character (80)                 :: rec
!       .. Executable Statements ..
        inform = 0

        If (inform>=0) Then

!         We are going to allow the iterations to continue.

          If (nstate==0 .Or. nstate==1) Then

!           When NSTATE==1, MONIT is called for the first time. When
!           NSTATE==0, MONIT is called for the first AND last time.
!           Display a welcome message

            Write (rec,'()')
            Call x04baf(nout,rec)
            Write (rec,99999)
            Call x04baf(nout,rec)
            Write (rec,'()')
            Call x04baf(nout,rec)

            Write (rec,99998)
            Call x04baf(nout,rec)

            Do i = 1, n
              Write (rec,99997)
              Call x04baf(nout,rec)
              Write (rec,99996) i
              Call x04baf(nout,rec)
              Write (rec,99995) numpts(i)
              Call x04baf(nout,rec)
              Write (rec,99994)
              Call x04baf(nout,rec)
              Write (rec,99993) list(i,1:numpts(i))
              Call x04baf(nout,rec)
              Write (rec,99992) initpt(i)
              Call x04baf(nout,rec)
            End Do

            If (plot .And. (n==2)) Then
              Write (rec,99991)
              Call x04baf(nout,rec)
              Write (rec,'()')
              Call x04baf(nout,rec)
            End If

          End If

          If (plot .And. (n==2)) Then

!           Display the coordinates of the edges of the current search
!           box

            Call outbox(boxl,boxu)

          End If

          If (nstate<=0) Then

!           MONIT is called for the last time

            If (plot .And. (n==2)) Then
              Write (rec,99990)
              Call x04baf(nout,rec)
              Write (rec,'()')
              Call x04baf(nout,rec)
            End If

            Write (rec,99989) icount(1)
            Call x04baf(nout,rec)
            Write (rec,99988) 10*((ncall+5)/10)
            Call x04baf(nout,rec)
            Write (rec,99987)
            Call x04baf(nout,rec)
            Write (rec,99986) 10*((icount(2)+5)/10)
            Call x04baf(nout,rec)
            Write (rec,99985) icount(3)
            Call x04baf(nout,rec)
            Write (rec,99984) icount(4)
            Call x04baf(nout,rec)
            Write (rec,99983) icount(5)
            Call x04baf(nout,rec)
            Write (rec,99982) icount(6)
            Call x04baf(nout,rec)
            Write (rec,99981) nbaskt
            Call x04baf(nout,rec)
            Write (rec,99980)
            Call x04baf(nout,rec)

            Do i = 1, n
              Write (rec,99979) i, xbaskt(i,1:nbaskt)
              Call x04baf(nout,rec)
            End Do

            Write (rec,99978)
            Call x04baf(nout,rec)
            Write (rec,99977) xbest(1:n)
            Call x04baf(nout,rec)

            Write (rec,'()')
            Call x04baf(nout,rec)
            Write (rec,99976)
            Call x04baf(nout,rec)
            Write (rec,'()')
            Call x04baf(nout,rec)
          End If

        End If

        Return

99999   Format (1X,'*** Begin monitoring information ***')
99998   Format (1X,'Values controlling initial splitting of a box:')
99997   Format (1X,'**')
99996   Format (1X,'In dimension ',I5)
99995   Format (1X,'Extent of initialization list in this dimension =',I5)
99994   Format (1X,'Initialization points in this dimension:')
99993   Format (1X,'LIST(I,1:NUMPTS(I)) =',(6F9.5))
99992   Format (1X,'Initial point in this dimension: LIST(I,',I5,')')
99991   Format (1X,'<Begin displaying search boxes>')
99990   Format (1X,'<End displaying search boxes>')
99989   Format (1X,'Total sub-boxes =',I5)
99988   Format (1X,'Total function evaluations (rounded to nearest 10) =',I5)
99987   Format (1X,'Total function evaluations used in local search (rounded')
99986   Format (3X,'to nearest 10) =',I5)
99985   Format (1X,'Total points used in local search =',I5)
99984   Format (1X,'Total sweeps through levels =',I5)
99983   Format (1X,'Total splits by init. list =',I5)
99982   Format (1X,'Lowest level with nonsplit boxes =',I5)
99981   Format (1X,'Number of candidate minima in the "shopping basket','" =', &
          I5)
99980   Format (1X,'Shopping basket:')
99979   Format (1X,'XBASKT(',I3,',:) =',(6F9.5))
99978   Format (1X,'Best point:')
99977   Format (1X,'XBEST =',(6F9.5))
99976   Format (1X,'*** End monitoring information ***')
      End Subroutine monit
    End Module e05jcfe_mod
    Program e05jcfe

!     E05JCF Example Main Program

!     This program demonstrates the use of routines to set and get
!     values of optional parameters associated with E05JBF

!     .. Use Statements ..
      Use nag_library, Only: e05jaf, e05jbf, e05jcf, e05jdf, e05jef, e05jff,   &
                             e05jgf, e05jhf, e05jjf, e05jkf, e05jlf, nag_wp,   &
                             x04acf, x04baf
      Use e05jcfe_mod, Only: lcomm, monit, nin, ninopt, nout, objfun, plot
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: n = 2
      Character (*), Parameter         :: fname = 'e05jcfe.opt'
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: loctol, obj
      Integer                          :: i, ibdchk, ibound, ifail, iinit, j,  &
                                          loclim, mode, n_r, sdlist, stclim
      Character (3)                    :: lcsrch
      Character (80)                   :: rec
!     .. Local Arrays ..
      Real (Kind=nag_wp)               :: bl(n), bu(n), comm(lcomm), ruser(1), &
                                          x(n)
      Real (Kind=nag_wp), Allocatable  :: list(:,:)
      Integer                          :: initpt(n), iuser(1), numpts(n)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: count, sqrt, trim
!     .. Executable Statements ..
      Write (rec,99992) 'E05JCF Example Program Results'
      Call x04baf(nout,rec)

!     Skip heading in data file
      Read (nin,*)

      Read (nin,*) sdlist
      Allocate (list(n,sdlist))

      Read (nin,*) ibound

      If (ibound==0) Then

!       Read in the whole of each bound

        Read (nin,*)(bl(i),i=1,n)
        Read (nin,*)(bu(i),i=1,n)
      Else If (ibound==3) Then

!       Bounds are uniform: read in only the first entry of each

        Read (nin,*) bl(1)
        Read (nin,*) bu(1)
      End If

      Read (nin,*) iinit

      If (iinit==3) Then

!       User is specifying the initialization list

        Read (nin,*)(numpts(i),i=1,n)
        Read (nin,*)((list(i,j),j=1,numpts(i)),i=1,n)
        Read (nin,*)(initpt(i),i=1,n)
      End If

!     PLOT determines whether MONIT displays information on
!     the current search box:

      Read (nin,*) plot

!     The first argument to E05JAF is a legacy argument and has no
!     significance.

      ifail = 0
      Call e05jaf(0,comm,lcomm,ifail)

!     Open the options file for reading

      mode = 0

      ifail = 0
      Call x04acf(ninopt,fname,mode,ifail)

!     Use E05JCF to read some options from the options file

      ifail = 0
      Call e05jcf(ninopt,comm,lcomm,ifail)

      Write (rec,'()')
      Call x04baf(nout,rec)

!     Use E05JKF to find the value of the integer-valued option
!     'Local Searches Limit'

      ifail = 0
      Call e05jkf('Local Searches Limit',loclim,comm,lcomm,ifail)

      Write (rec,99999) loclim
      Call x04baf(nout,rec)

!     Compute the number of free variables, then use E05JFF to set the value
!     of the integer-valued option 'Static Limit'

      n_r = count(bl(1:n)/=bu(1:n))
      stclim = 4*n_r

      ifail = 0
      Call e05jff('Static Limit',stclim,comm,lcomm,ifail)

!     Use E05JHF to determine whether the real-valued option
!     'Infinite Bound Size' has been set by us (in which case
!     E05JHF returns 1) or whether it holds its default value
!     (E05JHF returns 0)

      ifail = 0
      ibdchk = e05jhf('Infinite Bound Size',comm,lcomm,ifail)

      If (ibdchk==1) Then
        Write (rec,99998)
        Call x04baf(nout,rec)
      Else If (ibdchk==0) Then
        Write (rec,99997)
        Call x04baf(nout,rec)
      End If

!     Use E05JLF/E05JGF to set the real-valued option
!     'Local Searches Tolerance' to the square root of its default

      ifail = 0
      Call e05jlf('Local Searches Tolerance',loctol,comm,lcomm,ifail)

      ifail = 0
      Call e05jgf('Local Searches Tolerance',sqrt(loctol),comm,lcomm,ifail)

!     Use E05JLF to get the new value of 'Local Searches Tolerance'

      ifail = 0
      Call e05jlf('Local Searches Tolerance',loctol,comm,lcomm,ifail)

      Write (rec,99996) loctol
      Call x04baf(nout,rec)

!     Use E05JDF to set the option 'Minimize' (which is the default)

      ifail = 0
      Call e05jdf('Minimize',comm,lcomm,ifail)

!     Use E05JEF to set the option 'Local Searches' to 'On' (also
!     the default)

      lcsrch = 'On'

      ifail = 0
      Call e05jef('Local Searches',lcsrch,comm,lcomm,ifail)

!     Get that value of 'Local Searches' using E05JJF

      ifail = 0
      Call e05jjf('Local Searches',lcsrch,comm,lcomm,ifail)

      Write (rec,99995) trim(lcsrch)
      Call x04baf(nout,rec)

!     Solve the problem.

      ifail = 0
      Call e05jbf(n,objfun,ibound,iinit,bl,bu,sdlist,list,numpts,initpt,monit, &
        x,obj,comm,lcomm,iuser,ruser,ifail)

      Write (rec,'()')
      Call x04baf(nout,rec)
      Write (rec,99994) obj
      Call x04baf(nout,rec)
      Write (rec,99993)(x(i),i=1,n)
      Call x04baf(nout,rec)

99999 Format (1X,'Option "Local Searches Limit" has the value ',I6,'.')
99998 Format (1X,'Option "Infinite Bound Size" has been set by us.')
99997 Format (1X,'Option "Infinite Bound Size" holds its default value.')
99996 Format (1X,'Option "Local Searches Tolerance" has the value ',E13.5,'.')
99995 Format (1X,'Option "Local Searches" has the value "',A,'".')
99994 Format (1X,'Final objective value =',F11.5)
99993 Format (1X,'Global optimum X =',2F9.5)
99992 Format (1X,A)
    End Program e05jcfe


e05safe.f90

!   E05SAF Example Program Text
!   Mark 26 Release. NAG Copyright 2016.

    Module e05safe_mod

!     E05SAF Example Program Module:
!            Parameters and User-defined Routines

!     .. Use Statements ..
      Use nag_library, Only: nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Accessibility Statements ..
      Private
      Public                           :: display_option, display_result,      &
                                          monmod, objfun_schwefel
!     .. Parameters ..
      Real (Kind=nag_wp), Parameter, Public :: f_target =                      &
                                          -837.9657745448674_nag_wp
      Integer, Parameter               :: detail_level = 0, report_freq = 100
      Integer, Parameter, Public       :: liopts = 100, liuser = 1,            &
                                          lopts = 100, lruser = 1, ndim = 2,   &
                                          nout = 6, npar = 5
      Real (Kind=nag_wp), Parameter    :: x_target(ndim) =                     &
                                          -420.9687463599820_nag_wp
    Contains
      Subroutine objfun_schwefel(mode,ndim,x,objf,vecout,nstate,iuser,ruser)
!       Objfun routine for the Schwefel function for E05SAF.

!       .. Scalar Arguments ..
        Real (Kind=nag_wp), Intent (Inout) :: objf
        Integer, Intent (Inout)        :: mode
        Integer, Intent (In)           :: ndim, nstate
!       .. Array Arguments ..
        Real (Kind=nag_wp), Intent (Inout) :: ruser(*), vecout(ndim)
        Real (Kind=nag_wp), Intent (In) :: x(ndim)
        Integer, Intent (Inout)        :: iuser(*)
!       .. Local Scalars ..
        Logical                        :: evalobjf, evalobjg
!       .. Intrinsic Procedures ..
        Intrinsic                      :: abs, cos, sin, sqrt, sum
!       .. Executable Statements ..
!       Test NSTATE to indicate what stage of computation has been reached.
        Select Case (nstate)
        Case (2)
!         OBJFUN is called for the very first time.
        Case (1)
!         OBJFUN is called on entry to a NAG local minimizer.
        Case Default
!         This will be the normal value of NSTATE.
        End Select

!       Test MODE to determine whether to calculate OBJF and/or OBJGRD.
        evalobjf = .False.
        evalobjg = .False.
        Select Case (mode)
        Case (0,5)
!         Only the value of the objective function is needed.
          evalobjf = .True.
        Case (1,6)
!         Only the values of the NDIM gradients are required.
          evalobjg = .True.
        Case (2,7)
!         Both the objective function and the NDIM gradients are required.
          evalobjf = .True.
          evalobjg = .True.
        End Select

        If (evalobjf) Then
!         Evaluate the objective function.
          objf = sum(x(1:ndim)*sin(sqrt(abs(x(1:ndim)))))
        End If

        If (evalobjg) Then
!         Calculate the gradient of the objective function,
!         and return the result in VECOUT.
          vecout = sqrt(abs(x))
          vecout = sin(vecout) + 0.5E0_nag_wp*vecout*cos(vecout)
        End If

        Return

      End Subroutine objfun_schwefel
      Subroutine monmod(ndim,npar,x,xb,fb,xbest,fbest,itt,iuser,ruser,inform)

!       .. Scalar Arguments ..
        Real (Kind=nag_wp), Intent (In) :: fb
        Integer, Intent (Inout)        :: inform
        Integer, Intent (In)           :: ndim, npar
!       .. Array Arguments ..
        Real (Kind=nag_wp), Intent (In) :: fbest(npar), xb(ndim),              &
                                          xbest(ndim,npar)
        Real (Kind=nag_wp), Intent (Inout) :: ruser(*), x(ndim,npar)
        Integer, Intent (In)           :: itt(6)
        Integer, Intent (Inout)        :: iuser(*)
!       .. Local Scalars ..
        Integer                        :: indent, j
!       .. Intrinsic Procedures ..
        Intrinsic                      :: modulo, repeat
!       .. Executable Statements ..
        If (detail_level>=2) Then
!         Report on the first iteration, and every report_freq iterations.
          If (itt(1)==1 .Or. modulo(itt(1),report_freq)==0) Then
            Write (nout,*) '* Locations of particles'
            indent = 2
            Do j = 1, npar
              Write (nout,99999) repeat(' ',indent), j
              Write (nout,99998) repeat(' ',indent), x(1:ndim,j)
            End Do
            Write (nout,*) '* Cognitive memory'
            Do j = 1, npar
              Write (nout,99999) repeat(' ',indent), j
              Write (nout,*) repeat(' ',indent*2), '* Best position'
              Write (nout,99998) repeat(' ',indent*2), xbest(1:ndim,j)
              Write (nout,*) repeat(' ',indent*2),                             &
                '* Function value at best position'
              Write (nout,99997) repeat(' ',indent*2), fbest(j)
            End Do
            Write (nout,*) '* Current global optimum candidate'
            Write (nout,99998) repeat(' ',indent), xb(1:ndim)
            Write (nout,*) '* Current global optimum value'
            Write (nout,99997) repeat(' ',indent), fb
          End If
        End If

!       If required set INFORM<0 to force exit
        inform = 0
        Flush (nout)

        Return
99999   Format (1X,A,'* Particle ',I3)
99998   Format (1X,A,(6F13.5))
99997   Format (1X,A,F13.5)
      End Subroutine monmod
      Subroutine display_option(optstr,optype,ivalue,rvalue,cvalue)
!       Subroutine to query optype and print the appropriate option values

!       .. Scalar Arguments ..
        Real (Kind=nag_wp), Intent (In) :: rvalue
        Integer, Intent (In)           :: ivalue, optype
        Character (*), Intent (In)     :: cvalue, optstr
!       .. Executable Statements ..
        Select Case (optype)
        Case (1)
          Write (nout,99999) optstr, ivalue
        Case (2)
          Write (nout,99998) optstr, rvalue
        Case (3)
          Write (nout,99997) optstr, cvalue
        Case (4)
          Write (nout,99996) optstr, ivalue, cvalue
        Case (5)
          Write (nout,99995) optstr, rvalue, cvalue
        Case Default
        End Select

        Flush (nout)

        Return
99999   Format (3X,A36,' : ',I13)
99998   Format (3X,A36,' : ',F13.4)
99997   Format (3X,A36,' : ',16X,A16)
99996   Format (3X,A36,' : ',I13,3X,A16)
99995   Format (3X,A36,' : ',F13.4,3X,A16)
      End Subroutine display_option

      Subroutine display_result(ndim,xb,fb,itt,inform)
!       Display final results in comparison to known global optimum.

!       .. Use Statements ..
        Use nag_library, Only: x04cbf
!       .. Parameters ..
        Integer, Parameter             :: indent = 1, ncols = 79
        Character (10), Parameter      :: clabs(1:2) = (/'x_target  ',         &
                                          'xb        '/)
        Character (1), Parameter       :: diag = 'N', labcol = 'C',            &
                                          labrow = 'I', matrix = 'G'
        Character (5), Parameter       :: form = 'F12.2'
!       .. Scalar Arguments ..
        Real (Kind=nag_wp), Intent (In) :: fb
        Integer, Intent (In)           :: inform, ndim
!       .. Array Arguments ..
        Real (Kind=nag_wp), Intent (In) :: xb(ndim)
        Integer, Intent (In)           :: itt(6)
!       .. Local Scalars ..
        Integer                        :: ifail, ldxcom
        Character (ncols)              :: title
!       .. Local Arrays ..
        Real (Kind=nag_wp), Allocatable :: xcom(:,:)
!       .. Executable Statements ..
!       Display final counters.
        Write (nout,*) ' Algorithm Statistics'
        Write (nout,*) ' --------------------'
        Write (nout,99997) 'Total complete iterations             : ', itt(1)
        Write (nout,99997) 'Complete iterations since improvement : ', itt(2)
        Write (nout,99997) 'Total particles converged to xb       : ', itt(3)
        Write (nout,99997) 'Total improvements to global optimum  : ', itt(4)
        Write (nout,99997) 'Total function evaluations            : ', itt(5)
        Write (nout,99997) 'Total particles re-initialized        : ', itt(6)

!       Display why finalization occurred.
        Write (nout,*)
        Select Case (inform)
        Case (1)
          Write (nout,99996) 'Target value achieved'
        Case (2)
          Write (nout,99996) 'Minimum swarm standard deviation obtained'
        Case (3)
          Write (nout,99996) 'Sufficient particles converged'
        Case (4)
          Write (nout,99996) 'Maximum static iterations attained'
        Case (5)
          Write (nout,99996) 'Maximum complete iterations attained'
        Case (6)
          Write (nout,99996) 'Maximum function evaluations exceeded'
        Case (:-1)
          Write (nout,99995) inform
        Case Default
        End Select

!       Display final objective value and location.
        Write (nout,*)
        Write (nout,99999) f_target
        Write (nout,99998) fb
        Flush (nout)

        ldxcom = ndim
        Allocate (xcom(ldxcom,2))
        xcom(1:ndim,1) = x_target(1:ndim)
        xcom(1:ndim,2) = xb(1:ndim)

        Write (nout,*)
        title = 'Comparison between known and achieved optima.'
        ifail = 0
        Call x04cbf(matrix,diag,ndim,2,xcom,ldxcom,form,title,labrow,clabs,    &
          labcol,clabs,ncols,indent,ifail)

        Deallocate (xcom)

        Write (nout,*)

        Return
99999   Format ('  Known objective optimum ',13X,' : ',F13.5)
99998   Format ('  Achieved objective value',13X,' : ',F13.5)
99997   Format (2X,A40,I13)
99996   Format (2X,'Solution Status : ',A43)
99995   Format ('  User termination case                    :',I16)
      End Subroutine display_result
    End Module e05safe_mod
    Program e05safe
!     E05SAF Example Main Program

!     This example program demonstrates how to use E05SAF in standard
!       execution, and with a selection of coupled local minimizers.
!     The non-default option 'REPEATABILITY ON' is used here, giving
!       repeatable results.

!     .. Use Statements ..
      Use nag_library, Only: e05saf, e05zkf, e05zlf, nag_wp
      Use e05safe_mod, Only: display_option, display_result, f_target, liopts, &
                             liuser, lopts, lruser, monmod, ndim, nout, npar,  &
                             objfun_schwefel
!     .. Implicit None Statement ..
      Implicit None
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: fb, rvalue
      Integer                          :: ifail, inform, ivalue, optype
      Character (16)                   :: cvalue
      Character (80)                   :: optstr
!     .. Local Arrays ..
      Real (Kind=nag_wp)               :: bl(ndim), bu(ndim), opts(lopts),     &
                                          ruser(lruser), xb(ndim)
      Integer                          :: iopts(liopts), itt(6), iuser(liuser)
!     .. Executable Statements ..
!     Print advisory information.
      Write (nout,*) 'E05SAF Example Program Results'
      Write (nout,*)
      Write (nout,*) 'Minimization of the Schwefel function.'
      Write (nout,*)

!     Set problem specific values.
!     Set box bounds.
      bl(1:ndim) = -500.0_nag_wp
      bu(1:ndim) = 500.0_nag_wp

!     Initialize the option arrays for E05SAF.
      ifail = 0
      Call e05zkf('Initialize = E05SAF',iopts,liopts,opts,lopts,ifail)

!     Query some default option values.
      Write (nout,*) '  Default Option Queries:'
      Write (nout,*)
      ifail = 0
      optstr = 'Boundary'
      Call e05zlf(optstr,ivalue,rvalue,cvalue,optype,iopts,opts,ifail)
      Call display_option(optstr,optype,ivalue,rvalue,cvalue)

      ifail = 0
      optstr = 'Maximum Iterations Completed'
      Call e05zlf(optstr,ivalue,rvalue,cvalue,optype,iopts,opts,ifail)
      Call display_option(optstr,optype,ivalue,rvalue,cvalue)

      ifail = 0
      optstr = 'Distance Tolerance'
      Call e05zlf(optstr,ivalue,rvalue,cvalue,optype,iopts,opts,ifail)
      Call display_option(optstr,optype,ivalue,rvalue,cvalue)
      Write (nout,*)

!     ------------------------------------------------------------------
      Write (nout,*) '1. Solution without using coupled local minimizer.'
      Write (nout,*)

!     Set various options to non-default values if required.
      ifail = 0
      Call e05zkf('Repeatability = On',iopts,liopts,opts,lopts,ifail)
      ifail = 0
      Call e05zkf('Verify Gradients = Off',iopts,liopts,opts,lopts,ifail)
      ifail = 0
      Call e05zkf('Boundary = Hyperspherical',iopts,liopts,opts,lopts,ifail)
      ifail = 0
      Call e05zkf('Maximum iterations static = 150',iopts,liopts,opts,lopts,   &
        ifail)
      ifail = 0
      Call e05zkf('Repulsion Initialize = 30',iopts,liopts,opts,lopts,ifail)
      ifail = 0
      Call e05zkf('Repulsion Finalize = 30',iopts,liopts,opts,lopts,ifail)

!     Call E05SAF to search for the global optimum.
!     Non-zero IFAIL expected on exit here, so use IFAIL=1 (quiet) on entry.
      ifail = 1
      Call e05saf(ndim,npar,xb,fb,bl,bu,objfun_schwefel,monmod,iopts,opts,     &
        iuser,ruser,itt,inform,ifail)

!     It is essential to test IFAIL on exit.
      Select Case (ifail)
      Case (0,1)
!       No errors, best found optimum at xb returned in fb.
        Call display_result(ndim,xb,fb,itt,inform)
      Case (3)
!       Exit flag set in OBJFUN or MONMOD and returned in INFORM.
        Call display_result(ndim,xb,fb,itt,inform)
      Case Default
!       An error was detected. Print message since IFAIL=1 on entry.
        Write (nout,99998) '** E05SAF returned with an error, IFAIL = ', ifail
        Continue
      End Select

!     ------------------------------------------------------------------
      Write (nout,*) '2. Solution using coupled local minimizer E04CBF'
      Write (nout,*)

!     Set an objective target.
      ifail = 0
      Write (optstr,99999) 'Target Objective Value', f_target
      Call e05zkf(optstr,iopts,liopts,opts,lopts,ifail)
      ifail = 0
      Write (optstr,99999) 'Target Objective Tolerance', 1.0E-5_nag_wp
      Call e05zkf(optstr,iopts,liopts,opts,lopts,ifail)
      ifail = 0
      Write (optstr,99999) 'Target Objective Safeguard', 1.0E-8_nag_wp
      Call e05zkf(optstr,iopts,liopts,opts,lopts,ifail)

!     Set the local minimizer to be E04CBF and set corresponding options.
      ifail = 0
      Call e05zkf('Local Minimizer = E04CBF',iopts,liopts,opts,lopts,ifail)
      ifail = 0
      Call e05zkf('Local Interior Iterations = 10',iopts,liopts,opts,lopts,    &
        ifail)
      ifail = 0
      Call e05zkf('Local Exterior Iterations = 20',iopts,liopts,opts,lopts,    &
        ifail)
      ifail = 0
      Write (optstr,99999) 'Local Interior Tolerance', 1.0E-4_nag_wp
      Call e05zkf(optstr,iopts,liopts,opts,lopts,ifail)
      ifail = 0
      Write (optstr,99999) 'Local Exterior Tolerance', 1.0E-4_nag_wp
      Call e05zkf(optstr,iopts,liopts,opts,lopts,ifail)

!     Call E05SAF to search for the global optimum.
      ifail = -1
      Call e05saf(ndim,npar,xb,fb,bl,bu,objfun_schwefel,monmod,iopts,opts,     &
        iuser,ruser,itt,inform,ifail)

!     It is essential to test IFAIL on exit.
      Select Case (ifail)
      Case (0,1)
!       No errors, best found optimum at xb returned in fb.
        Call display_result(ndim,xb,fb,itt,inform)
      Case (3)
!       Exit flag set in OBJFUN or MONMOD and returned in INFORM.
        Call display_result(ndim,xb,fb,itt,inform)
      Case Default
!       An error was detected.
        Continue
      End Select

!     -----------------------------------------------------------------
      Write (nout,*) '3. Solution using coupled local minimizer E04DGF'
      Write (nout,*)

!     Set the local minimizer to be E04DGF and set corresponding options.
      ifail = 0
      Call e05zkf('Local Minimizer = E04DGF',iopts,liopts,opts,lopts,ifail)
      ifail = 0
      Call e05zkf('Local Interior Iterations = 5',iopts,liopts,opts,lopts,     &
        ifail)
      ifail = 0
      Call e05zkf('Local Exterior Iterations = 20',iopts,liopts,opts,lopts,    &
        ifail)

!     Call E05SAF to search for the global optimum.
      ifail = -1
      Call e05saf(ndim,npar,xb,fb,bl,bu,objfun_schwefel,monmod,iopts,opts,     &
        iuser,ruser,itt,inform,ifail)

!     It is essential to test IFAIL on exit.
      Select Case (ifail)
      Case (0,1)
!       No errors, best found optimum at xb returned in fb.
        Call display_result(ndim,xb,fb,itt,inform)
      Case (3)
!       Exit flag set in OBJFUN or MONMOD and returned in INFORM.
        Call display_result(ndim,xb,fb,itt,inform)
      Case Default
!       An error was detected.
        Continue
      End Select

99999 Format (A,' = ',E32.16)
99998 Format (1X,A,I6)
    End Program e05safe


e05safe_smp.f90

!   E05SAF Example Program Text
!   Mark 26 Release. NAG Copyright 2015.

    Module e05safe_mod

!     E05SAF Example Program Module:
!            Parameters and User-defined Routines

!     .. Use Statements ..
      Use nag_library, Only: nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Real (Kind=nag_wp), Parameter    :: f_target =                           &
                                          -4.189828872724337E2_nag_wp
      Real (Kind=nag_wp), Parameter    :: one = 1.0E0_nag_wp
      Real (Kind=nag_wp), Parameter    :: zero = 0.0_nag_wp
      Integer, Parameter               :: detail_level = 0,                    &
                                          iuser_reference = 1, liopts = 100,   &
                                          lopts = 100, ndim = 20, nout = 6,    &
                                          report_freq = 100, ruser_global = 1
      Real (Kind=nag_wp), Parameter    :: x_target(1:ndim) =                   &
                                          -420.9687463599820_nag_wp
    Contains
      Subroutine objfun_schwefel_objective(ndim,x,f,w)
!       subroutine to calculate the objective using provided workspace

!       .. Use Statements ..
        Use nag_library, Only: ddot
!       .. Scalar Arguments ..
        Real (Kind=nag_wp), Intent (Out) :: f
        Integer, Intent (In)           :: ndim
!       .. Array Arguments ..
        Real (Kind=nag_wp), Intent (Out) :: w(ndim)
        Real (Kind=nag_wp), Intent (In) :: x(ndim)
!       .. Intrinsic Procedures ..
        Intrinsic                      :: abs, sin, sqrt
!       .. Executable Statements ..
        w = abs(x)
        w = sqrt(w)
        w = sin(w)
        f = ddot(ndim,x,1,w,1)

        Return
      End Subroutine objfun_schwefel_objective
      Subroutine objfun_schwefel_gradient(ndim,x,g,w1,w2)
!       subroutine to calculate the gradient of the objective function with provided workspace

!       .. Use Statements ..
        Use nag_library, Only: dscal
!       .. Scalar Arguments ..
        Integer, Intent (In)           :: ndim
!       .. Array Arguments ..
        Real (Kind=nag_wp), Intent (Out) :: g(ndim), w1(ndim), w2(ndim)
        Real (Kind=nag_wp), Intent (In) :: x(ndim)
!       .. Intrinsic Procedures ..
        Intrinsic                      :: abs, cos, sin, sqrt
!       .. Executable Statements ..
        Continue

        w1 = sqrt(abs(x))
        w2 = cos(w1)
        g = sin(w1)
        Call dscal(ndim,0.5E0_nag_wp,w1,1)
        g = g + w1*w2

        Return
      End Subroutine objfun_schwefel_gradient
      Subroutine objfun_schwefel(mode,ndim,x,objf,vecout,nstate,iuser,ruser)
!       Objfun routine for the Schwefel function for E05SAF.

!       .. Use Statements ..
        Use nag_library, Only: x06adf
!       .. Scalar Arguments ..
        Real (Kind=nag_wp), Intent (Inout) :: objf
        Integer, Intent (Inout)        :: mode
        Integer, Intent (In)           :: ndim, nstate
!       .. Array Arguments ..
        Real (Kind=nag_wp), Intent (Inout) :: ruser(*), vecout(ndim)
        Real (Kind=nag_wp), Intent (In) :: x(ndim)
        Integer, Intent (Inout)        :: iuser(*)
!       .. Local Scalars ..
        Integer                        :: threadno, work_1, work_2
        Logical                        :: evalobjf, evalobjg
!       .. Intrinsic Procedures ..
        Intrinsic                      :: real
!       .. Executable Statements ..
!       Get the current thread number.
        threadno = x06adf()

!       Test NSTATE to indicate what stage of computation has been reached.
        Select Case (nstate)
        Case (2)

!         OBJFUN is called for the very first time.
!         This occurs in serial on thread 0 only.

!         Set up any constant global variables required in RUSER and IUSER
!         This may also be done prior to calling E05SAF
          ruser(ruser_global) = -f_target*real(ndim,nag_wp)

!         Set reference index for thread 0 workspace in IUSER
          iuser(iuser_reference+threadno) = ruser_global + 1

        Case (3)
!         OBJFUN has been called for the first time on a new thread.

!         This occurs at the start of the main parallel region.
!         This will not occur on thread 0.

!         In this example we take the opportunity to set the reference index for this
!         threads unique section of RUSER workspace in IUSER.

!         Each thead requires 2*ndim real numbers.
          iuser(iuser_reference+threadno) = iuser(iuser_reference) +           &
            2*ndim*threadno

        Case (1)
!         OBJFUN is called on entry to a NAG local minimizer.
        Case (0)
!         This will be the normal value of NSTATE.
        Case Default
!         This is extremely unlikely, and indicates that an error has
!         occurred on the system
          mode = -1
          If (detail_level>=2) Then
            Write (nout,99999)
          End If
          Go To 100
        End Select

!       Test MODE to determine whether to calculate OBJF and/or OBJGRD.
        evalobjf = .False.
        evalobjg = .False.
        Select Case (mode)
        Case (0,5)
!         Only the value of the objective function is needed.
          evalobjf = .True.
        Case (1,6)
!         Only the values of the NDIM gradients are required.
          evalobjg = .True.
        Case (2,7)
!         Both the objective function and the NDIM gradients are required.
          evalobjf = .True.
          evalobjg = .True.
        Case Default
          mode = -1
          Write (nout,99999)
          Go To 100
        End Select

!       Set work_1 and work_2 to point to the section of RUSER reserved
!       for this thread
        work_1 = iuser(iuser_reference+threadno)
        work_2 = work_1 + ndim

        If (evalobjf) Then
!         Evaluate the objective function.
!         objf = const + sum( x*sin(abs(sqrt(x))))

!         Pass thread-safe workspace to objfun_schwefel_objective
          Call objfun_schwefel_objective(ndim,x,objf,ruser(work_1))
!         Use constant safely available to all threads.
          objf = objf + ruser(ruser_global)

        End If

        If (evalobjg) Then
!         Calculate the gradient of the objective function,
!         and return the result in VECOUT.
!         gradient = sin(sqrt(abs(x)))
!                    + sign(cos(sqrt(abs(x)))/2.0*sqrt(abs(x)),x)

          Call objfun_schwefel_gradient(ndim,x,vecout,ruser(work_1),           &
            ruser(work_2))
        End If

100     Continue
        Return

99999   Format (1X,'** ERROR DETECTED ')

      End Subroutine objfun_schwefel
      Subroutine monmod(ndim,npar,x,xb,fb,xbest,fbest,itt,iuser,ruser,inform)
!       Example monitor function.

!       .. Scalar Arguments ..
        Real (Kind=nag_wp), Intent (In) :: fb
        Integer, Intent (Inout)        :: inform
        Integer, Intent (In)           :: ndim, npar
!       .. Array Arguments ..
        Real (Kind=nag_wp), Intent (In) :: fbest(npar), xb(ndim),              &
                                          xbest(ndim,npar)
        Real (Kind=nag_wp), Intent (Inout) :: ruser(*), x(ndim,npar)
        Integer, Intent (In)           :: itt(6)
        Integer, Intent (Inout)        :: iuser(*)
!       .. Local Scalars ..
        Integer                        :: k
!       .. Intrinsic Procedures ..
        Intrinsic                      :: modulo
!       .. Executable Statements ..
        If (detail_level>=2) Then
!         Report on the first iteration, and every report_freq iterations.
          If (itt(1)==1 .Or. modulo(itt(1),report_freq)==0) Then
            Write (nout,*)
            Write (nout,*) '* Current global optimum candidate:'
            Do k = 1, ndim
              Write (nout,99999) k, xb(k)
            End Do
            Write (nout,*) '* Current global optimum value:'
            Write (nout,99998) fb
          End If
        End If

!       If required set INFORM<0 to force exit
        Flush (nout)

        Return
99999   Format (1X,'* xb(',I3,') = ',F9.2)
99998   Format (1X,'* fb = ',F9.5)

      End Subroutine monmod
      Subroutine display_result(ndim,xb,fb,itt,inform,ruser)
!       Display final results in comparison to known global optimum.

!       .. Use Statements ..
        Use nag_library, Only: x04cbf
!       .. Parameters ..
        Integer, Parameter             :: indent = 0, ncols = 80
        Character (10), Parameter      :: clabs(1:2) = (/'x_target  ',         &
                                          'xb        '/)
        Character (1), Parameter       :: diag = 'N', labcol = 'C',            &
                                          labrow = 'I', matrix = 'G'
        Character (4), Parameter       :: form = 'f9.2'
!       .. Scalar Arguments ..
        Real (Kind=nag_wp), Intent (In) :: fb
        Integer, Intent (In)           :: inform, ndim
!       .. Array Arguments ..
        Real (Kind=nag_wp), Intent (In) :: ruser(*), xb(ndim)
        Integer, Intent (In)           :: itt(6)
!       .. Local Scalars ..
        Integer                        :: ifail, ldxcom
        Character (ncols)              :: title
!       .. Local Arrays ..
        Real (Kind=nag_wp), Allocatable :: xcom(:,:)
!       .. Executable Statements ..
!       Display final counters.
        Write (nout,99996) 'Total complete iterations             : ', itt(1)
        Write (nout,99996) 'Complete iterations since improvement : ', itt(2)
        Write (nout,99996) 'Total particles converged to xb       : ', itt(3)
        Write (nout,99996) 'Total improvements to global optimum  : ', itt(4)
        Write (nout,99996) 'Total function evaluations            : ', itt(5)
        Write (nout,99996) 'Total particles re-initialized        : ', itt(6)

!       Display why finalization occurred.
        Write (nout,*)
        Select Case (inform)
        Case (1)
          Write (nout,99995) 'Target value achieved'
        Case (2)
          Write (nout,99995) 'Minimum swarm standard deviation obtained'
        Case (3)
          Write (nout,99995) 'Sufficient particles converged'
        Case (4)
          Write (nout,99995) 'No improvement in preset iteration limit'
        Case (5)
          Write (nout,99995) 'Maximum complete iterations attained'
        Case (6)
          Write (nout,99995) 'Maximum function evaluations exceeded'
        Case (:-1)
          Write (nout,99994) inform
        Case Default
        End Select

!       Display final objective value and location.
        Write (nout,*)
        Write (nout,99999) 0.0E0_nag_wp
        Write (nout,99998) fb
        Flush (nout)

        ldxcom = ndim
        Allocate (xcom(ldxcom,2))
        xcom(1:ndim,1) = x_target(1:ndim)
        xcom(1:ndim,2) = xb(1:ndim)

        title = ' Comparison between known and achieved optima.'
        ifail = 0
        Call x04cbf(matrix,diag,ndim,2,xcom,ldxcom,form,title,labrow,clabs,    &
          labcol,clabs,ncols,indent,ifail)

        Deallocate (xcom)

        Write (nout,99997)

        Return
99999   Format ('  Known objective optimum  : ',F13.5)
99998   Format ('  Achieved objective value : ',F13.5)
99997   Format ('**--------------------**--------------------**',/)
99996   Format (2X,A40,I16)
99995   Format (2X,A43)
99994   Format ('  User termination case                    :',I16)
      End Subroutine display_result
    End Module e05safe_mod

    Program e05safe
!     E05SAF Example Main Program

!     This example program demonstrates how to use E05SAF in standard
!       execution, and with a selection of coupled local minimizers.
!     The non-default option 'REPEATABILITY ON' is used here, giving
!       repeatable results.

!     .. Use Statements ..
      Use nag_library, Only: e05saf, e05zkf, x06acf
      Use e05safe_mod, Only: display_result, iuser_reference, liopts, lopts,   &
                             monmod, nag_wp, ndim, nout, objfun_schwefel,      &
                             ruser_global
!     .. Implicit None Statement ..
      Implicit None
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: fb
      Integer                          :: ifail, inform, liuser, lruser,       &
                                          max_threads, npar
      Character (80)                   :: optstr
!     .. Local Arrays ..
      Real (Kind=nag_wp)               :: bl(ndim), bu(ndim), opts(lopts),     &
                                          xb(ndim)
      Real (Kind=nag_wp), Allocatable  :: ruser(:)
      Integer                          :: iopts(liopts), itt(6)
      Integer, Allocatable             :: iuser(:)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: max
!     .. Executable Statements ..
!     Print advisory information.
      Write (nout,*) 'E05SAF Example Program Results'
      Write (nout,*)
      Write (nout,*) 'Minimization of the Schwefel function.'
      Write (nout,*)

!     Set problem specific values.
!     Set box bounds.
      bl(1:ndim) = -500.0_nag_wp
      bu(1:ndim) = 500.0_nag_wp

!     Determine the number of threads to be used in the simulation
      max_threads = x06acf()

!     Ensure NPAR is sufficient for the number of threads
      npar = max(4000,5*max_threads)

!     Assign sufficient sizes for iuser and ruser.
!     In this example, RUSER will be split into workspace unique to each thread,
!     and IUSER will be used to store the indexes to the first element of
!     workspace for each thread.

      liuser = max(30,iuser_reference+max_threads)
      lruser = ruser_global + 2*max_threads*ndim
      Allocate (iuser(liuser),ruser(lruser))

      Write (nout,*) '* Solution without using coupled local minimizer *'

!     Call E05ZKF to initialize the option arrays
      ifail = 0
      Call e05zkf('Initialize = E05SAF',iopts,liopts,opts,lopts,ifail)

!     Set the option SMP Callback Thread Safe to indicate the callback functions
!     are indeed threadsafe.  This must be done if using multiple threads.

      ifail = 0
      Call e05zkf('SMP Callback Thread Safe = Yes',iopts,liopts,opts,lopts,    &
        ifail)

!     Set various options to non-default values if required.
      ifail = 0
      Call e05zkf('Repeatability = On',iopts,liopts,opts,lopts,ifail)
      ifail = 0
      Call e05zkf('Verify Gradients = Off',iopts,liopts,opts,lopts,ifail)
      ifail = 0
      Call e05zkf('Boundary = Hyperspherical',iopts,liopts,opts,lopts,ifail)
      ifail = 0
      Call e05zkf('Maximum iterations static = 150',iopts,liopts,opts,lopts,   &
        ifail)
      ifail = 0
      Call e05zkf('Maximum function evaluations = 50000000',iopts,liopts,opts, &
        lopts,ifail)
      ifail = 0
      Call e05zkf('Repulsion Initialize = 50',iopts,liopts,opts,lopts,ifail)
      ifail = 0
      Call e05zkf('Repulsion Finalize = 30',iopts,liopts,opts,lopts,ifail)

!     Set an objective target.
      ifail = 0
      Write (optstr,99999) 'Target Objective Value', 1.0E0_nag_wp
      Call e05zkf(optstr,iopts,liopts,opts,lopts,ifail)
      ifail = 0
      Write (optstr,99999) 'Target Objective Tolerance', 1.0E-5_nag_wp
      Call e05zkf(optstr,iopts,liopts,opts,lopts,ifail)
      ifail = 0
      Write (optstr,99999) 'Target Objective Safeguard', 1.0E-2_nag_wp
      Call e05zkf(optstr,iopts,liopts,opts,lopts,ifail)

!     Set some additional SMP library options if required.
      ifail = 0
      Call e05zkf('SMP thread overrun = 100',iopts,liopts,opts,lopts,ifail)

      ifail = 0
      Write (optstr,99998) 'SMP Subswarm', max_threads
      Call e05zkf(optstr,iopts,liopts,opts,lopts,ifail)

!     Call E05SAF to search for the global optimum.
!     As guaranteed success cannot by default be achieved, IFAIL=1,-1 is
!     recommended on entry.
      ifail = -1
      Call e05saf(ndim,npar,xb,fb,bl,bu,objfun_schwefel,monmod,iopts,opts,     &
        iuser,ruser,itt,inform,ifail)
!     It is essential to test IFAIL on exit.
      Select Case (ifail)
      Case (0,1)
!       E05SAF encountered no errors during operation,
!       and will have returned the best found optimum.
        Call display_result(ndim,xb,fb,itt,inform,ruser)
      Case (-999,-399,2:)
!       An error was detected.
        Continue
      Case Default
!       An instruction to exit was received by E05SAF from OBJFUN or MONMOD.
!       The exit flag will have been returned in INFORM.
        Call display_result(ndim,xb,fb,itt,inform,ruser)
      End Select

!     ------------------------------------------------------------------
      Write (nout,*) '* Solution using coupled local minimizer E04JYF *'

!     Set the local minimizer to be E04JYF and set corresponding options.
      ifail = 0
      Call e05zkf('Local Minimizer = E04JYF',iopts,liopts,opts,lopts,ifail)
      ifail = 0
      Call e05zkf('Local Interior Iterations = 30',iopts,liopts,opts,lopts,    &
        ifail)
      ifail = 0
      Call e05zkf('Local Exterior Iterations = 200',iopts,liopts,opts,lopts,   &
        ifail)
      ifail = 0
      Write (optstr,99999) 'Local Interior Tolerance', 1.0E-4_nag_wp
      Call e05zkf(optstr,iopts,liopts,opts,lopts,ifail)
      ifail = 0
      Write (optstr,99999) 'Local Exterior Tolerance', 1.0E-8_nag_wp
      Call e05zkf(optstr,iopts,liopts,opts,lopts,ifail)

!     Call E05SAF to search for the global optimum.
      ifail = -1
      Call e05saf(ndim,npar,xb,fb,bl,bu,objfun_schwefel,monmod,iopts,opts,     &
        iuser,ruser,itt,inform,ifail)

!     It is essential to test IFAIL on exit.
      Select Case (ifail)
      Case (0,1)
!       E05SAF encountered no errors during operation,
!       and will have returned the best found optimum.
        Call display_result(ndim,xb,fb,itt,inform,ruser)
      Case (-999,-399,2:)
!       An error was detected.
        Continue
      Case Default
!       An instruction to exit was received by E05SAF from OBJFUN or MONMOD.
!       The exit flag will have been returned in INFORM.
        Call display_result(ndim,xb,fb,itt,inform,ruser)
      End Select

!     -----------------------------------------------------------------
      Write (nout,*) '* Solution using coupled local minimizer E04UCF *'

!     Set the local minimizer to be E04UCF and set corresponding options.
      ifail = 0
      Call e05zkf('Local Minimizer = E04UCF',iopts,liopts,opts,lopts,ifail)
      ifail = 0
      Call e05zkf('Local Interior Iterations = 10',iopts,liopts,opts,lopts,    &
        ifail)
      ifail = 0
      Call e05zkf('Local Exterior Iterations = 100',iopts,liopts,opts,lopts,   &
        ifail)

!     Call E05SAF to search for the global optimum.
      ifail = -1
      Call e05saf(ndim,npar,xb,fb,bl,bu,objfun_schwefel,monmod,iopts,opts,     &
        iuser,ruser,itt,inform,ifail)

!     It is essential to test IFAIL on exit.
      Select Case (ifail)
      Case (0,1)
!       E05SAF encountered no errors during operation,
!       and will have returned the best found optimum.
        Call display_result(ndim,xb,fb,itt,inform,ruser)
      Case (-999,-399,2:)
!       An error was detected.
        Continue
      Case Default
!       An instruction to exit was received by E05SAF from OBJFUN or MONMOD.
!       The exit flag will have been returned in INFORM.
        Call display_result(ndim,xb,fb,itt,inform,ruser)
      End Select

99999 Format (A,' = ',E32.16)
99998 Format (A,' = ',I20)
    End Program e05safe


e05sbfe.f90

!   E05SBF Example Program Text
!   Mark 26 Release. NAG Copyright 2016.

    Module e05sbfe_mod

!     E05SBF Example Program Module:
!            Parameters and User-defined Routines

!     .. Use Statements ..
      Use nag_library, Only: nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Accessibility Statements ..
      Private
      Public                           :: confun_non_linear, display_option,   &
                                          display_result, monmod,              &
                                          objfun_schwefel
!     .. Parameters ..
      Real (Kind=nag_wp), Parameter, Public :: f_target_c =                    &
                                          -731.70709230672696_nag_wp
      Real (Kind=nag_wp), Parameter, Public :: zero = 0.0_nag_wp
      Real (Kind=nag_wp), Parameter    :: f_target_u =                         &
                                          -837.9657745448674_nag_wp
      Real (Kind=nag_wp), Parameter    :: x_target = -420.9687463599820_nag_wp
      Integer, Parameter               :: detail_level = 0, report_freq = 100
      Integer, Parameter, Public       :: liopts = 100, liuser = 1,            &
                                          lopts = 100, lruser = 1, ncon = 3,   &
                                          ndim = 2, nout = 6, npar = 20
      Real (Kind=nag_wp), Parameter    :: c_scale(ncon) = (/2490.0_nag_wp,     &
                                          750000.0_nag_wp,0.1_nag_wp/)
      Real (Kind=nag_wp), Parameter    :: c_target_c(ncon) = 0._nag_wp
      Real (Kind=nag_wp), Parameter    :: c_target_u(ncon) = (/zero,           &
                                          31644.05623568455_nag_wp,            &
                                          0.07574889943398055_nag_wp/)
      Real (Kind=nag_wp), Parameter    :: x_target_c(ndim) = (/                &
                                          -394.1470221120988_nag_wp,           &
                                          -433.48214189947606_nag_wp/)
      Real (Kind=nag_wp), Parameter    :: x_target_u(ndim) = (/x_target,       &
                                          x_target/)
    Contains
      Subroutine objfun_schwefel(mode,ndim,x,objf,vecout,nstate,iuser,ruser)
!       Objfun routine for the Schwefel function for E05SBF.

!       .. Scalar Arguments ..
        Real (Kind=nag_wp), Intent (Inout) :: objf
        Integer, Intent (Inout)        :: mode
        Integer, Intent (In)           :: ndim, nstate
!       .. Array Arguments ..
        Real (Kind=nag_wp), Intent (Inout) :: ruser(*), vecout(ndim)
        Real (Kind=nag_wp), Intent (In) :: x(ndim)
        Integer, Intent (Inout)        :: iuser(*)
!       .. Local Scalars ..
        Logical                        :: evalobjf, evalobjg
!       .. Intrinsic Procedures ..
        Intrinsic                      :: abs, cos, sin, sqrt, sum
!       .. Executable Statements ..
!       Test NSTATE to indicate what stage of computation has been reached.
        Select Case (nstate)
        Case (2)
!         OBJFUN is called for the very first time.
        Case (1)
!         OBJFUN is called on entry to a NAG local minimizer.
        Case (0)
!         This will be the normal value of NSTATE.
        End Select

!       Test MODE to determine whether to calculate OBJF and/or OBJGRD.
        evalobjf = .False.
        evalobjg = .False.
        Select Case (mode)
        Case (0,5)
!         Only the value of the objective function is needed.
          evalobjf = .True.
        Case (1,6)
!         Only the values of the NDIM gradients are required.
          evalobjg = .True.
        Case (2,7)
!         Both the objective function and the NDIM gradients are required.
          evalobjf = .True.
          evalobjg = .True.
        End Select

        If (evalobjf) Then
!         Evaluate the objective function.
          objf = sum(x(1:ndim)*sin(sqrt(abs(x(1:ndim)))))
        End If

        If (evalobjg) Then
!         Calculate the gradient of the objective function.
          vecout = sqrt(abs(x))
          vecout = sin(vecout) + 0.5E0_nag_wp*vecout*cos(vecout)
        End If

        Return

      End Subroutine objfun_schwefel
      Subroutine confun_non_linear(mode,ncon,ndim,ldcj,needc,x,c,cjac,nstate,  &
        iuser,ruser)
!       Subroutine used to supply constraints

!       .. Scalar Arguments ..
        Integer, Intent (In)           :: ldcj, ncon, ndim, nstate
        Integer, Intent (Inout)        :: mode
!       .. Array Arguments ..
        Real (Kind=nag_wp), Intent (Out) :: c(ncon)
        Real (Kind=nag_wp), Intent (Inout) :: cjac(ldcj,ndim), ruser(*)
        Real (Kind=nag_wp), Intent (In) :: x(ndim)
        Integer, Intent (Inout)        :: iuser(*)
        Integer, Intent (In)           :: needc(ncon)
!       .. Local Scalars ..
        Integer                        :: k
        Logical                        :: evalc, evalcjac
!       .. Intrinsic Procedures ..
        Intrinsic                      :: cos
!       .. Executable Statements ..
!       Test NSTATE to determine whether the local minimizer is being called
!       for the first time from a new start point
        If (nstate==1) Then
!         Set any constant elements of the Jacobian matrix.
          cjac(1,1) = 3.0_nag_wp
          cjac(1,2) = -2.0_nag_wp
        End If

!       MODE: are constraints, derivatives, or both are required?
        evalc = mode == 0 .Or. mode == 2
        evalcjac = mode == 1 .Or. mode == 2

loop_constraints: Do k = 1, ncon
!         Only those for which needc is nonzero need be set.
          If (needc(k)<=0) Then
            Cycle loop_constraints
          End If

          If (evalc) Then
!           Constraint values are required.
            Select Case (k)
            Case (1)
              c(k) = 3.0_nag_wp*x(1) - 2.0_nag_wp*x(2)
            Case (2)
              c(k) = x(1)**2 - x(2)**2 + 3.0_nag_wp*x(1)*x(2)
            Case (3)
              c(k) = cos((x(1)/200.0_nag_wp)**2+(x(2)/100.0_nag_wp))
            Case Default
!             This constraint is not coded (there are only three).
!             Terminate.
              mode = -1
              Exit loop_constraints
            End Select
          End If

          If (evalcjac) Then
!           Constraint derivatives (CJAC) are required.
            Select Case (k)
            Case (1)
!             Constant derivatives set when NSTATE=1 remain throughout
!             the local minimization.
              Continue
            Case (2)
!             If the constraint derivatives are known and are readily
!             calculated, populate CJAC when required.
              cjac(k,1) = 2.0_nag_wp*x(1) + 3.0_nag_wp*x(2)
              cjac(k,2) = -2.0_nag_wp*x(2) + 3.0_nag_wp*x(1)
            Case Default
!             Any elements of CJAC left unaltered will be approximated
!             using finite differences when required.
              Continue
            End Select
          End If

        End Do loop_constraints

        Return

      End Subroutine confun_non_linear
      Subroutine monmod(ndim,ncon,npar,x,xb,fb,cb,xbest,fbest,cbest,itt,iuser, &
        ruser,inform)

!       .. Scalar Arguments ..
        Real (Kind=nag_wp), Intent (In) :: fb
        Integer, Intent (Inout)        :: inform
        Integer, Intent (In)           :: ncon, ndim, npar
!       .. Array Arguments ..
        Real (Kind=nag_wp), Intent (In) :: cb(ncon), cbest(ncon,npar),         &
                                          fbest(npar), xb(ndim),               &
                                          xbest(ndim,npar)
        Real (Kind=nag_wp), Intent (Inout) :: ruser(*), x(ndim,npar)
        Integer, Intent (In)           :: itt(7)
        Integer, Intent (Inout)        :: iuser(*)
!       .. Local Scalars ..
        Integer                        :: indent, j
!       .. Intrinsic Procedures ..
        Intrinsic                      :: modulo, repeat
!       .. Executable Statements ..
        If (detail_level>=2) Then
!         Report on the first iteration, and every report_freq iterations.
          If (itt(1)==1 .Or. modulo(itt(1),report_freq)==0) Then
            Write (nout,*) '* Locations of particles'
            indent = 2
            Do j = 1, npar
              Write (nout,99999) repeat(' ',indent), j
              Write (nout,99998) repeat(' ',indent), x(1:ndim,j)
            End Do
            Write (nout,*) '* Cognitive memory'
            Do j = 1, npar
              Write (nout,99999) repeat(' ',indent), j
              Write (nout,*) repeat(' ',indent*2), '* Best position'
              Write (nout,99998) repeat(' ',indent*2), xbest(1:ndim,j)
              Write (nout,*) repeat(' ',indent*2),                             &
                '* Function value at best position'
              Write (nout,99997) repeat(' ',indent*2), fbest(j)
              Write (nout,*) repeat(' ',indent*2),                             &
                '* Best constraint violations'
              Write (nout,99998) repeat(' ',indent*2), cbest(1:ncon,j)
            End Do
            Write (nout,*) '* Current global optimum candidate'
            Write (nout,99998) repeat(' ',indent), xb(1:ndim)
            Write (nout,*) '* Current global optimum value'
            Write (nout,99997) repeat(' ',indent), fb
            Write (nout,*) '* Constraint violations of candidate'
            Write (nout,99998) repeat(' ',indent), cb(1:ncon)
          End If
        End If

!       If required set INFORM<0 to force exit
        inform = 0

        Return
99999   Format (1X,A,'* Particle ',I3)
99998   Format (1X,A,(6F13.5))
99997   Format (1X,A,F13.5)
      End Subroutine monmod
      Subroutine display_option(optstr,optype,ivalue,rvalue,cvalue)
!       Subroutine to query optype and print the appropriate option values

!       .. Scalar Arguments ..
        Real (Kind=nag_wp), Intent (In) :: rvalue
        Integer, Intent (In)           :: ivalue, optype
        Character (*), Intent (In)     :: cvalue, optstr
!       .. Executable Statements ..
        Select Case (optype)
        Case (1)
          Write (nout,99999) optstr, ivalue
        Case (2)
          Write (nout,99998) optstr, rvalue
        Case (3)
          Write (nout,99997) optstr, cvalue
        Case (4)
          Write (nout,99996) optstr, ivalue, cvalue
        Case (5)
          Write (nout,99995) optstr, rvalue, cvalue
        End Select

        Flush (nout)

        Return
99999   Format (3X,A39,' : ',I13)
99998   Format (3X,A39,' : ',F13.4)
99997   Format (3X,A39,' : ',16X,A16)
99996   Format (3X,A39,' : ',I13,3X,A16)
99995   Format (3X,A39,' : ',F13.4,3X,A16)
      End Subroutine display_option

      Subroutine display_result(ndim,ncon,xb,fb,cb,itt,inform)
!       Display final results in comparison to known global optimum.

!       .. Use Statements ..
        Use nag_library, Only: x04cbf
!       .. Parameters ..
        Integer, Parameter             :: indent = 1, ncols = 79
        Character (11), Parameter      :: clabs(1:6) = (/'x_target_u ',        &
                                          'x_target_c ','xb         ',         &
                                          'c_target_u ','c_target_c ',         &
                                          'cb         '/)
        Character (1), Parameter       :: diag = 'D', labcol = 'C',            &
                                          labrow = 'I', matrix = 'G'
        Character (5), Parameter       :: fmtc = 'f12.5', fmtx = 'f12.2'
!       .. Scalar Arguments ..
        Real (Kind=nag_wp), Intent (In) :: fb
        Integer, Intent (In)           :: inform, ncon, ndim
!       .. Array Arguments ..
        Real (Kind=nag_wp), Intent (In) :: cb(ncon), xb(ndim)
        Integer, Intent (In)           :: itt(7)
!       .. Local Scalars ..
        Integer                        :: ifail, ldcom
        Character (ncols)              :: titlec, titlex
!       .. Local Arrays ..
        Real (Kind=nag_wp), Allocatable :: ccom(:,:), xcom(:,:)
!       .. Executable Statements ..
!       Display final counters.
        Write (nout,*) ' Algorithm Statistics'
        Write (nout,*) ' --------------------'
        Write (nout,99994) 'Total complete iterations               ', itt(1)
        Write (nout,99994) 'Complete iterations since improvement   ', itt(2)
        Write (nout,99994) 'Total particles converged to xb         ', itt(3)
        Write (nout,99994) 'Total improvements to global optimum    ', itt(4)
        Write (nout,99994) 'Total function evaluations              ', itt(5)
        Write (nout,99994) 'Total particles re-initialized          ', itt(6)
        Write (nout,99994) 'Total constraints violated              ', itt(7)

!       Display why finalization occurred.
        Write (nout,*)
        Select Case (inform)
        Case (1)
          Write (nout,99999) 'Target value achieved'
        Case (2)
          Write (nout,99999) 'Minimum swarm standard deviation obtained'
        Case (3)
          Write (nout,99999) 'Sufficient particles converged'
        Case (4)
          Write (nout,99999) 'No improvement in preset iteration limit'
        Case (5)
          Write (nout,99999) 'Maximum complete iterations attained'
        Case (6)
          Write (nout,99999) 'Maximum function evaluations exceeded'
        Case (7)
          Write (nout,99999) 'Constrained point located'
        Case (:-1)
          Write (nout,99998) inform
          Go To 100
        End Select

!       Display final objective value and location.
        Write (nout,*)
        Write (nout,99997) f_target_u
        Write (nout,99996) f_target_c
        Write (nout,99995) fb
        Flush (nout)

        ldcom = ndim
        Allocate (xcom(ldcom,3))
        xcom(1:ndim,1) = x_target_u(1:ndim)
        xcom(1:ndim,2) = x_target_c(1:ndim)
        xcom(1:ndim,3) = xb(1:ndim)

        Write (nout,*)
        titlex = 'Comparison between known and achieved optima.'
        ifail = 0
        Call x04cbf(matrix,diag,ndim,3,xcom,ldcom,fmtx,titlex,labrow,clabs,    &
          labcol,clabs,ncols,indent,ifail)

        Deallocate (xcom)

        If (ncon>0) Then
          ldcom = ncon
          Allocate (ccom(ldcom,3))
          ccom(1:ncon,1) = c_target_u(1:ncon)/c_scale(1:ncon)
          ccom(1:ncon,2) = c_target_c(1:ncon)/c_scale(1:ncon)
          ccom(1:ncon,3) = cb(1:ncon)/c_scale(1:ncon)

          Write (nout,*)
          Flush (nout)
          titlec = 'Comparison between scaled constraint violations.'
          ifail = 0
          Call x04cbf(matrix,diag,ncon,3,ccom,ldcom,fmtc,titlec,labrow,clabs,  &
            labcol,clabs(4:6),ncols,indent,ifail)

          Deallocate (ccom)
        End If

100     Continue

        Write (nout,*)

        Return
99999   Format (2X,'Solution Status : ',A38)
99998   Format ('  User termination case                    : ',I13)
99997   Format ('  Known unconstrained objective minimum    : ',F13.3)
99996   Format ('  Best Known constrained objective minimum : ',F13.3)
99995   Format ('  Achieved objective value                 : ',F13.3)
99994   Format (2X,A40,' :',I13)
      End Subroutine display_result
    End Module e05sbfe_mod
    Program e05sbfe
!     E05SBF Example Main Program

!     This example program demonstrates how to use E05SBF in standard
!       execution, and with E04UCF as a coupled local minimizer.
!     The non-default option 'REPEATABILITY ON' is used here, giving
!       repeatable results.

!     .. Use Statements ..
      Use nag_library, Only: e05sbf, e05zkf, e05zlf, nag_wp
      Use e05sbfe_mod, Only: confun_non_linear, display_option,                &
                             display_result, f_target_c, liopts, liuser,       &
                             lopts, lruser, monmod, ncon, ndim, nout, npar,    &
                             objfun_schwefel, zero
!     .. Implicit None Statement ..
      Implicit None
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: fb, rvalue
      Integer                          :: ifail, inform, ivalue, optype
      Character (16)                   :: cvalue
      Character (80)                   :: optstr
!     .. Local Arrays ..
      Real (Kind=nag_wp)               :: bl(ndim+ncon), bu(ndim+ncon),        &
                                          cb(ncon), cbest(ncon,npar),          &
                                          fbest(ndim,npar), opts(lopts),       &
                                          ruser(lruser), xb(ndim),             &
                                          xbest(ndim,npar)
      Integer                          :: iopts(liopts), itt(7), iuser(liuser)
!     .. Executable Statements ..
!     Print advisory information.
      Write (nout,*) 'E05SBF Example Program Results'
      Write (nout,*)
      Write (nout,*) 'Minimization of the Schwefel function.'
      Write (nout,*) 'Subject to one linear and two nonlinear constraints.'
      Write (nout,*)

      xbest = zero
      fbest = zero
      cbest = zero

!     Set problem specific values.
!     Set box bounds.
      bl(1:ndim) = -500.0_nag_wp
      bu(1:ndim) = 500.0_nag_wp
!     Set constraint bounds.
      bl((ndim+1):(ndim+ncon)) = (/-1.0E6_nag_wp,-1.0_nag_wp,-0.9_nag_wp/)
      bu((ndim+1):(ndim+ncon)) = (/10.0_nag_wp,5.0E5_nag_wp,0.9_nag_wp/)

!     Initialize the option arrays for E05SBF.
      ifail = 0
      Call e05zkf('Initialize = E05SBF',iopts,liopts,opts,lopts,ifail)

!     Query some default option values.
      Write (nout,*) '  Default Option Queries:'
      Write (nout,*)
      ivalue = 0
      rvalue = 0.0_nag_wp
      ifail = 0
      optstr = 'Constraint Norm'
      Call e05zlf(optstr,ivalue,rvalue,cvalue,optype,iopts,opts,ifail)
      Call display_option(optstr,optype,ivalue,rvalue,cvalue)

      ifail = 0
      optstr = 'Maximum Iterations Completed'
      Call e05zlf(optstr,ivalue,rvalue,cvalue,optype,iopts,opts,ifail)
      Call display_option(optstr,optype,ivalue,rvalue,cvalue)

      ifail = 0
      optstr = 'Distance Tolerance'
      Call e05zlf(optstr,ivalue,rvalue,cvalue,optype,iopts,opts,ifail)
      Call display_option(optstr,optype,ivalue,rvalue,cvalue)

!     ------------------------------------------------------------------
      Write (nout,*)
      Write (nout,*) '1. Solution without using coupled local minimizer'
      Write (nout,*)
!     Set various options to non-default values if required.
      ifail = 0
      Write (optstr,99999) 'Distance Tolerance', rvalue*0.1_nag_wp
      Call e05zkf(optstr,iopts,liopts,opts,lopts,ifail)
      ifail = 0
      Write (optstr,99999) 'Constraint Tolerance', 1.0E-4_nag_wp
      Call e05zkf(optstr,iopts,liopts,opts,lopts,ifail)
      ifail = 0
      Call e05zkf('Constraint Norm = Euclidean',iopts,liopts,opts,lopts,ifail)
      ifail = 0
      Call e05zkf('Repeatability = On',iopts,liopts,opts,lopts,ifail)
      ifail = 0
      Write (optstr,99999) 'Target Objective Value', f_target_c
      Call e05zkf(optstr,iopts,liopts,opts,lopts,ifail)
      ifail = 0
      Write (optstr,99999) 'Target Objective Tolerance', 1.0E-4_nag_wp
      Call e05zkf(optstr,iopts,liopts,opts,lopts,ifail)

!     Call E05SBF to search for the global optimum.
!     Non-zero IFAIL expected on exit here, so use IFAIL=1 (quiet) on entry.
      ifail = 1
      Call e05sbf(ndim,ncon,npar,xb,fb,cb,bl,bu,xbest,fbest,cbest,             &
        objfun_schwefel,confun_non_linear,monmod,iopts,opts,iuser,ruser,itt,   &
        inform,ifail)

!     It is essential to test IFAIL on exit.
      Select Case (ifail)
      Case (0,1)
!       No errors, best found optimum at xb returned in fb.
        Call display_result(ndim,ncon,xb,fb,cb,itt,inform)
      Case (3)
!       Exit flag set in OBJFUN, CONFUN or MONMOD and returned in INFORM.
        Call display_result(ndim,ncon,xb,fb,cb,itt,inform)
      Case Default
!       An error was detected. Print message since IFAIL=1 on entry.
        Write (nout,99998) '** E05SBF returned with an error, IFAIL = ', ifail
        Continue
      End Select

!     ------------------------------------------------------------------
      Write (nout,*) '2. Solution using coupled local minimizer E04UCF'
      Write (nout,*)

!     Set the local minimizer to be E04UCF and set corresponding options.
      ifail = 0
      Call e05zkf('Local Minimizer = E04UCF',iopts,liopts,opts,lopts,ifail)
      ifail = 0
      Call e05zkf('Local Interior Major Iterations = 15',iopts,liopts,opts,    &
        lopts,ifail)
      ifail = 0
      Call e05zkf('Local Interior Minor Iterations = 5',iopts,liopts,opts,     &
        lopts,ifail)
      ifail = 0
      Call e05zkf('Local Exterior Major Iterations = 50',iopts,liopts,opts,    &
        lopts,ifail)
      ifail = 0
      Call e05zkf('Local Exterior Minor Iterations = 15',iopts,liopts,opts,    &
        lopts,ifail)

!     Query the option Distance Tolerance
      ifail = 0
      optstr = 'Distance Tolerance'
      Call e05zlf(optstr,ivalue,rvalue,cvalue,optype,iopts,opts,ifail)
!     Adjust Distance Tolerance dependent upon its current value
      Write (optstr,99999) 'Distance Tolerance', rvalue*10.0_nag_wp
      ifail = 0
      Call e05zkf(optstr,iopts,liopts,opts,lopts,ifail)
      ifail = 0
      Write (optstr,99999) 'Local Interior Tolerance', rvalue
      Call e05zkf(optstr,iopts,liopts,opts,lopts,ifail)
      ifail = 0
      Write (optstr,99999) 'Local Exterior Tolerance', rvalue*1.0E-4_nag_wp
      Call e05zkf(optstr,iopts,liopts,opts,lopts,ifail)

!     Call E05SBF to search for the global optimum.
      ifail = 1
      Call e05sbf(ndim,ncon,npar,xb,fb,cb,bl,bu,xbest,fbest,cbest,             &
        objfun_schwefel,confun_non_linear,monmod,iopts,opts,iuser,ruser,itt,   &
        inform,ifail)

!     It is essential to test IFAIL on exit.
      Select Case (ifail)
      Case (0,1)
!       E05SBF encountered no errors during operation,
!       and will have returned the best found optimum.
        Call display_result(ndim,ncon,xb,fb,cb,itt,inform)
      Case (3)
!       Exit flag set in OBJFUN, CONFUN or MONMOD and returned in INFORM.
        Call display_result(ndim,ncon,xb,fb,cb,itt,inform)
      Case Default
!       An error was detected. Print message since IFAIL=1 on entry.
        Write (nout,99998) '** E05SBF returned with an error, IFAIL = ', ifail
        Continue
      End Select

99999 Format (A,' = ',E32.16)
99998 Format (1X,A,I6)
    End Program e05sbfe


e05ucfe.f90

!   E05UCF Example Program Text
!   Mark 26 Release. NAG Copyright 2016.

    Module e05ucfe_mod

!     E05UCF Example Program Module:
!            Parameters and User-defined Routines

!     .. Use Statements ..
      Use nag_library, Only: nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Accessibility Statements ..
      Private
      Public                           :: mystart, schwefel_confun,            &
                                          schwefel_obj
    Contains
      Subroutine schwefel_obj(mode,n,x,objf,objgrd,nstate,iuser,ruser)

!       .. Scalar Arguments ..
        Real (Kind=nag_wp), Intent (Out) :: objf
        Integer, Intent (Inout)        :: mode
        Integer, Intent (In)           :: n, nstate
!       .. Array Arguments ..
        Real (Kind=nag_wp), Intent (Inout) :: objgrd(n), ruser(*)
        Real (Kind=nag_wp), Intent (In) :: x(n)
        Integer, Intent (Inout)        :: iuser(*)
!       .. Intrinsic Procedures ..
        Intrinsic                      :: abs, cos, sin, sqrt, sum
!       .. Executable Statements ..
        If (nstate==1) Then
!         This is the first call.
!         Take any special action here if desired.
          Continue
        End If
        If (mode==0 .Or. mode==2) Then
!         Evaluate the objective function.
          objf = sum(x(1:n)*sin(sqrt(abs(x(1:n)))))
        End If

        If (mode==1 .Or. mode==2) Then
!         Calculate the gradient of the objective function.
          objgrd(1:n) = sin(sqrt(abs(x(1:n)))) + 0.5_nag_wp*sqrt(abs(x(1:n)))* &
            cos(sqrt(abs(x(1:n))))
        End If

        Return
      End Subroutine schwefel_obj
      Subroutine schwefel_confun(mode,ncnln,n,ldcjsl,needc,x,c,cjsl,nstate,    &
        iuser,ruser)

!       .. Scalar Arguments ..
        Integer, Intent (In)           :: ldcjsl, n, ncnln, nstate
        Integer, Intent (Inout)        :: mode
!       .. Array Arguments ..
        Real (Kind=nag_wp), Intent (Out) :: c(ncnln)
        Real (Kind=nag_wp), Intent (Inout) :: cjsl(ldcjsl,n), ruser(*)
        Real (Kind=nag_wp), Intent (In) :: x(n)
        Integer, Intent (Inout)        :: iuser(*)
        Integer, Intent (In)           :: needc(ncnln)
!       .. Local Scalars ..
        Real (Kind=nag_wp)             :: t1, t2
        Integer                        :: k
        Logical                        :: evalc, evalcjsl
!       .. Intrinsic Procedures ..
        Intrinsic                      :: cos, sin
!       .. Executable Statements ..
        If (nstate==1) Then
!         This is the first call.
!         Take any special action here if desired.
          Continue
        End If

!       mode: what is required - constraints, derivatives, or both?
        evalc = (mode==0 .Or. mode==2)
        evalcjsl = (mode==1 .Or. mode==2)

loop_constraints: Do k = 1, ncnln

          If (needc(k)<=0) Then
            Cycle loop_constraints
          End If

          If (evalc) Then
!           Constraint values are required.
            Select Case (k)
            Case (1)
              c(k) = x(1)**2 - x(2)**2 + 3.0_nag_wp*x(1)*x(2)
            Case (2)
              c(k) = cos((x(1)/200.0_nag_wp)**2+(x(2)/100.0_nag_wp))
            Case Default
!             This constraint is not coded (there are only two).
!             Terminate.
              mode = -1
              Exit loop_constraints
            End Select
          End If

          If (evalcjsl) Then
!           Constraint derivatives are required.
            Select Case (k)
            Case (1)
              cjsl(k,1) = 2.0_nag_wp*x(1) + 3.0_nag_wp*x(2)
              cjsl(k,2) = -2.0_nag_wp*x(2) + 3.0_nag_wp*x(1)
            Case (2)
              t1 = x(1)/200.0_nag_wp
              t2 = x(2)/100.0_nag_wp
              cjsl(k,1) = -sin(t1**2+t2)*2.0_nag_wp*t1/200.0_nag_wp
              cjsl(k,2) = -sin(t1**2+t2)/100.0_nag_wp
            End Select
          End If

        End Do loop_constraints

        Return
      End Subroutine schwefel_confun
      Subroutine mystart(npts,quas,n,repeat,bl,bu,iuser,ruser,mode)

!       Sets the initial points.
!       A typical user-defined start procedure.
!       Only nonzero elements of quas need to be specified here.

!       .. Use Statements ..
        Use nag_library, Only: g05kgf, g05saf
!       .. Scalar Arguments ..
        Integer, Intent (Inout)        :: mode
        Integer, Intent (In)           :: n, npts
        Logical, Intent (In)           :: repeat
!       .. Array Arguments ..
        Real (Kind=nag_wp), Intent (In) :: bl(n), bu(n)
        Real (Kind=nag_wp), Intent (Inout) :: quas(n,npts), ruser(*)
        Integer, Intent (Inout)        :: iuser(*)
!       .. Local Scalars ..
        Integer                        :: genid, i, ifail, lstate, subid
!       .. Local Arrays ..
        Integer, Allocatable           :: state(:)
!       .. Intrinsic Procedures ..
        Intrinsic                      :: real
!       .. Executable Statements ..
        If (repeat) Then
!         Generate a uniform spread of points between bl and bu.
          Do i = 1, npts
            quas(1:n,i) = bl(1:n) + (bu(1:n)-bl(1:n))*real(i-1,kind=nag_wp)/   &
              real(npts-1,kind=nag_wp)
          End Do
        Else
!         Generate a non-repeatable spread of points between bl and bu.
          genid = 2
          subid = 53
          lstate = -1
          Allocate (state(lstate))
          ifail = 0
          Call g05kgf(genid,subid,state,lstate,ifail)
          Deallocate (state)
          Allocate (state(lstate))
          ifail = 0
          Call g05kgf(genid,subid,state,lstate,ifail)
          Do i = 1, npts
            ifail = 0
            Call g05saf(n,state,quas(1,i),ifail)
            quas(1:n,i) = bl(1:n) + (bu(1:n)-bl(1:n))*quas(1:n,i)
          End Do
          Deallocate (state)
        End If
!       Set mode negative to terminate execution for any reason.
        mode = 0
        Return
      End Subroutine mystart
    End Module e05ucfe_mod
    Program e05ucfe

!     E05UCF Example Main Program

!     .. Use Statements ..
      Use nag_library, Only: dgemv, e05ucf, e05zkf, nag_wp
      Use e05ucfe_mod, Only: mystart, schwefel_confun, schwefel_obj
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: n = 2, nclin = 1, ncnln = 2,         &
                                          nin = 5, nout = 6
!     .. Local Scalars ..
      Integer                          :: i, ifail, j, k, l, lda, ldc, ldcjac, &
                                          ldclda, ldobjd, ldr, ldx, liopts,    &
                                          listat, lopts, nb, npts, sda,        &
                                          sdcjac, sdr
      Logical                          :: repeat
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: a(:,:), bl(:), bu(:), c(:,:),        &
                                          cjac(:,:,:), clamda(:,:), objf(:),   &
                                          objgrd(:,:), opts(:), r(:,:,:),      &
                                          work(:), x(:,:)
      Real (Kind=nag_wp)               :: ruser(1)
      Integer, Allocatable             :: info(:), iopts(:), istate(:,:),      &
                                          iter(:)
      Integer                          :: iuser(1)
!     .. Executable Statements ..
      Write (nout,*) 'E05UCF Example Program Results'
      Flush (nout)

!     Skip heading in data file
      Read (nin,*)

      Read (nin,*) nb, npts
      Read (nin,*) repeat

      lda = nclin

      If (nclin>0) Then
        sda = n
      Else
        sda = 1
      End If

      ldx = n
      ldobjd = n
      ldc = ncnln
      ldcjac = ncnln

      If (ncnln>0) Then
        sdcjac = n
      Else
        sdcjac = 0
      End If

      ldr = n
      sdr = n
      ldclda = n + nclin + ncnln
      listat = n + nclin + ncnln
      liopts = 740
      lopts = 485
      Allocate (a(lda,sda),bl(n+nclin+ncnln),bu(n+nclin+ncnln),x(ldx,nb),      &
        objf(nb),objgrd(ldobjd,nb),iter(nb),c(ldc,nb),cjac(ldcjac,sdcjac,nb),  &
        r(ldr,sdr,nb),clamda(ldclda,nb),istate(listat,nb),iopts(liopts),       &
        opts(lopts),info(nb),work(nclin))

      bl(1:n+nclin+ncnln) = (/-500.0_nag_wp,-500.0_nag_wp,-10000.0_nag_wp,     &
        -1.0_nag_wp,-0.9_nag_wp/)
      bu(1:n+nclin+ncnln) = (/500.0_nag_wp,500.0_nag_wp,10.0_nag_wp,           &
        500000.0_nag_wp,0.9_nag_wp/)

      a(1,1) = 3.0_nag_wp
      a(1,2) = -2.0_nag_wp

!     Initialize the solver.

      ifail = 0
      Call e05zkf('Initialize = E05UCF',iopts,liopts,opts,lopts,ifail)

!     Solve the problem.

      ifail = -1
      Call e05ucf(n,nclin,ncnln,a,lda,bl,bu,schwefel_confun,schwefel_obj,npts, &
        x,ldx,mystart,repeat,nb,objf,objgrd,ldobjd,iter,c,ldc,cjac,ldcjac,     &
        sdcjac,r,ldr,sdr,clamda,ldclda,istate,listat,iopts,opts,iuser,ruser,   &
        info,ifail)

      Select Case (ifail)
      Case (0)
        l = nb
      Case (8)
        l = info(nb)
        Write (nout,99992) iter(nb)
      Case Default
        Go To 100
      End Select

loop: Do i = 1, l
        Write (nout,99999) i
        Write (nout,99998) info(i)
        Write (nout,99997) 'Varbl'
        Do j = 1, n
          Write (nout,99996) 'V', j, istate(j,i), x(j,i), clamda(j,i)
        End Do
        If (nclin>0) Then
          Write (nout,99997) 'L Con'

!         Below is a call to the level 2 BLAS routine DGEMV.
!         This performs the matrix vector multiplication A*X
!         (linear constraint values) and puts the result in
!         the first NCLIN locations of WORK.

          Call dgemv('N',nclin,n,1.0_nag_wp,a,lda,x(1,i),1,0.0_nag_wp,work,1)

          Do k = n + 1, n + nclin
            j = k - n
            Write (nout,99996) 'L', j, istate(k,i), work(j), clamda(k,i)
          End Do
        End If
        If (ncnln>0) Then
          Write (nout,99997) 'N Con'
          Do k = n + nclin + 1, n + nclin + ncnln
            j = k - n - nclin
            Write (nout,99996) 'N', j, istate(k,i), c(j,i), clamda(k,i)
          End Do
        End If
        Write (nout,99995) objf(i)
        Write (nout,99994)
        Write (nout,99993)(clamda(k,i),k=1,n+nclin+ncnln)

        If (l==1) Then
          Exit loop
        End If

        Write (nout,*)

        Write (nout,*)                                                         &
          ' ------------------------------------------------------ '

      End Do loop

100   Continue

99999 Format (/,1X,'Solution number',I16)
99998 Format (/,1X,'Local minimization exited with code',I5)
99997 Format (/,1X,A,2X,'Istate',3X,'Value',9X,'Lagr Mult',/)
99996 Format (1X,A,2(1X,I3),4X,F12.4,2X,F12.4)
99995 Format (/,1X,'Final objective value = ',1X,F12.4)
99994 Format (/,1X,'QP multipliers')
99993 Format (1X,F12.4)
99992 Format (1X,I16,' starting points converged')
    End Program e05ucfe


e05usfe.f90

!   E05USF Example Program Text
!   Mark 26 Release. NAG Copyright 2016.

    Module e05usfe_mod

!     E05USF Example Program Module:
!            Parameters and User-defined Routines

!     .. Use Statements ..
      Use nag_library, Only: nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Accessibility Statements ..
      Private
      Public                           :: confun, objfun, start
    Contains
      Subroutine objfun(mode,m,n,ldfjsl,needfi,x,f,fjsl,nstate,iuser,ruser)
!       Evaluates the subfunctions and their 1st derivatives.

!       .. Parameters ..
        Real (Kind=nag_wp), Parameter  :: a(44) = (/8._nag_wp,8._nag_wp,       &
                                          10._nag_wp,10._nag_wp,10._nag_wp,    &
                                          10._nag_wp,12._nag_wp,12._nag_wp,    &
                                          12._nag_wp,12._nag_wp,14._nag_wp,    &
                                          14._nag_wp,14._nag_wp,16._nag_wp,    &
                                          16._nag_wp,16._nag_wp,18._nag_wp,    &
                                          18._nag_wp,20._nag_wp,20._nag_wp,    &
                                          20._nag_wp,22._nag_wp,22._nag_wp,    &
                                          22._nag_wp,24._nag_wp,24._nag_wp,    &
                                          24._nag_wp,26._nag_wp,26._nag_wp,    &
                                          26._nag_wp,28._nag_wp,28._nag_wp,    &
                                          30._nag_wp,30._nag_wp,30._nag_wp,    &
                                          32._nag_wp,32._nag_wp,34._nag_wp,    &
                                          36._nag_wp,36._nag_wp,38._nag_wp,    &
                                          38._nag_wp,40._nag_wp,42._nag_wp/)
!       .. Scalar Arguments ..
        Integer, Intent (In)           :: ldfjsl, m, n, needfi, nstate
        Integer, Intent (Inout)        :: mode
!       .. Array Arguments ..
        Real (Kind=nag_wp), Intent (Out) :: f(m)
        Real (Kind=nag_wp), Intent (Inout) :: fjsl(ldfjsl,*), ruser(*)
        Real (Kind=nag_wp), Intent (In) :: x(n)
        Integer, Intent (Inout)        :: iuser(*)
!       .. Local Scalars ..
        Real (Kind=nag_wp)             :: temp
        Integer                        :: i
!       .. Intrinsic Procedures ..
        Intrinsic                      :: exp
!       .. Executable Statements ..

!       This is a two-dimensional objective function.
!       As an example of using the mode mechanism,
!       terminate if any other problem size is supplied.

        If (n/=2) Then
          mode = -1
        End If

        If (nstate==1) Then
!         This is the first call.
!         Take any special action here if desired.
          Continue
        End If

        If (mode==0 .And. needfi>0) Then
          f(needfi) = x(1) + (0.49_nag_wp-x(1))*exp(-x(2)*(a(needfi)-          &
            8.0_nag_wp))
        Else
          Do i = 1, m
            temp = exp(-x(2)*(a(i)-8._nag_wp))

            If (mode==0 .Or. mode==2) Then
              f(i) = x(1) + (0.49_nag_wp-x(1))*temp
            End If

            If (mode==1 .Or. mode==2) Then
              fjsl(i,1) = 1._nag_wp - temp
              fjsl(i,2) = -(0.49_nag_wp-x(1))*(a(i)-8._nag_wp)*temp
            End If

          End Do
        End If

        Return
      End Subroutine objfun
      Subroutine confun(mode,ncnln,n,ldcjsl,needc,x,c,cjsl,nstate,iuser,ruser)
!       Evaluates the nonlinear constraints and their 1st derivatives.

!       .. Scalar Arguments ..
        Integer, Intent (In)           :: ldcjsl, n, ncnln, nstate
        Integer, Intent (Inout)        :: mode
!       .. Array Arguments ..
        Real (Kind=nag_wp), Intent (Out) :: c(ncnln)
        Real (Kind=nag_wp), Intent (Inout) :: cjsl(ldcjsl,*), ruser(*)
        Real (Kind=nag_wp), Intent (In) :: x(n)
        Integer, Intent (Inout)        :: iuser(*)
        Integer, Intent (In)           :: needc(ncnln)
!       .. Executable Statements ..

!       This problem has only one constraint.
!       As an example of using the mode mechanism,
!       terminate if any other size is supplied.

        If (ncnln/=1) Then
          mode = -1
        End If

        If (nstate==1) Then

!         First call to CONFUN.  Set all Jacobian elements to zero.
!         Note that this will only work when 'Derivative Level = 3'
!         (the default; see Section 11.1 of the E04USA document).

          cjsl(1:ncnln,1:n) = 0._nag_wp
        End If

        If (needc(1)>0) Then

          If (mode==0 .Or. mode==2) Then
            c(1) = -0.09_nag_wp - x(1)*x(2) + 0.49_nag_wp*x(2)
          End If

          If (mode==1 .Or. mode==2) Then
            cjsl(1,1) = -x(2)
            cjsl(1,2) = -x(1) + 0.49_nag_wp
          End If

        End If

        Return
      End Subroutine confun
      Subroutine start(npts,quas,n,repeat1,bl,bu,iuser,ruser,mode)

!       Sets the initial points.
!       A typical user-defined start procedure.

!       .. Use Statements ..
        Use nag_library, Only: g05kgf, g05saf
!       .. Scalar Arguments ..
        Integer, Intent (Inout)        :: mode
        Integer, Intent (In)           :: n, npts
        Logical, Intent (In)           :: repeat1
!       .. Array Arguments ..
        Real (Kind=nag_wp), Intent (In) :: bl(n), bu(n)
        Real (Kind=nag_wp), Intent (Inout) :: quas(n,npts), ruser(*)
        Integer, Intent (Inout)        :: iuser(*)
!       .. Local Scalars ..
        Integer                        :: genid, i, ifail, lstate, subid
!       .. Local Arrays ..
        Integer, Allocatable           :: state(:)
!       .. Executable Statements ..
!       quas is pre-assigned to zero.
        If (repeat1) Then
          quas(1,1) = 0.4_nag_wp
          quas(2,2) = 1._nag_wp
        Else
!         Generate a non-repeatable spread of points between bl and bu.
          genid = 2
          subid = 53
          lstate = -1
          Allocate (state(lstate))
          ifail = 0
          Call g05kgf(genid,subid,state,lstate,ifail)
          Deallocate (state)
          Allocate (state(lstate))
          ifail = 0
          Call g05kgf(genid,subid,state,lstate,ifail)
          Do i = 1, npts
            ifail = 0
            Call g05saf(n,state,quas(1,i),ifail)
            quas(1:n,i) = bl(1:n) + (bu(1:n)-bl(1:n))*quas(1:n,i)
          End Do
          Deallocate (state)
        End If
!       Set mode negative to terminate execution for any reason.
        mode = 0
        Return
      End Subroutine start
    End Module e05usfe_mod
    Program e05usfe

!     E05USF Example Main Program

!     .. Use Statements ..
      Use nag_library, Only: dgemv, e05usf, e05zkf, nag_wp
      Use e05usfe_mod, Only: confun, objfun, start
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: liopts = 740, lopts = 485, m = 44,   &
                                          n = 2, nb = 1, nclin = 1, ncnln = 1, &
                                          nin = 5, nout = 6, npts = 3
      Integer, Parameter               :: sdfjac = n
      Integer, Parameter               :: lda = nclin
      Integer, Parameter               :: ldc = ncnln
      Integer, Parameter               :: ldcjac = ncnln
      Integer, Parameter               :: ldclda = n + nclin + ncnln
      Integer, Parameter               :: ldfjac = m
      Integer, Parameter               :: ldx = n
      Integer, Parameter               :: listat = n + nclin + ncnln
      Logical, Parameter               :: repeat1 = .True.
!     .. Local Scalars ..
      Integer                          :: i, ifail, j, k, l, sda, sdcjac
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: a(:,:), bl(:), bu(:), c(:,:),        &
                                          cjac(:,:,:), clamda(:,:), f(:,:),    &
                                          fjac(:,:,:), work(:), x(:,:), y(:)
      Real (Kind=nag_wp)               :: objf(nb), opts(lopts), ruser(1)
      Integer                          :: info(nb), iopts(liopts), iter(nb),   &
                                          iuser(1)
      Integer, Allocatable             :: istate(:,:)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: max
!     .. Executable Statements ..
      Write (nout,*) 'E05USF Example Program Results'
      Flush (nout)

!     Skip heading in data file.
      Read (nin,*)

      If (nclin>0) Then
        sda = n
      Else
        sda = 1
      End If

      If (ncnln>0) Then
        sdcjac = n
      Else
        sdcjac = 0
      End If

      Allocate (a(lda,sda),bl(n+nclin+ncnln),bu(n+nclin+ncnln),y(m),c(ldc,nb), &
        cjac(ldcjac,sdcjac,nb),f(m,nb),fjac(ldfjac,sdfjac,nb),                 &
        clamda(ldclda,nb),istate(listat,nb),x(ldx,nb),work(max(1,nclin)))

      If (nclin>0) Then
        Read (nin,*)(a(i,1:sda),i=1,nclin)
      End If

      Read (nin,*) y(1:m)
      Read (nin,*) bl(1:(n+nclin+ncnln))
      Read (nin,*) bu(1:(n+nclin+ncnln))

!     Initialize the solver.

      ifail = 0
      Call e05zkf('Initialize = E05USF',iopts,liopts,opts,lopts,ifail)

!     Solve the problem.

      ifail = -1
      Call e05usf(m,n,nclin,ncnln,a,lda,bl,bu,y,confun,objfun,npts,x,ldx,      &
        start,repeat1,nb,objf,f,fjac,ldfjac,sdfjac,iter,c,ldc,cjac,ldcjac,     &
        sdcjac,clamda,ldclda,istate,listat,iopts,opts,iuser,ruser,info,ifail)

      Select Case (ifail)
      Case (0)
        l = nb
      Case (8)
        l = info(nb)
        Write (nout,99999) iter(nb)
      Case Default
        Go To 100
      End Select

loop: Do i = 1, l
        Write (nout,99998) i
        Write (nout,99997) info(i)
        Write (nout,99996) 'Varbl'
        Do j = 1, n
          Write (nout,99995) 'V', j, istate(j,i), x(j,i), clamda(j,i)
        End Do
        If (nclin>0) Then
          Write (nout,99996) 'L Con'

!         Below is a call to the level 2 BLAS routine DGEMV.
!         This performs the matrix vector multiplication A*X
!         (linear constraint values) and puts the result in
!         the first NCLIN locations of WORK.

          Call dgemv('N',nclin,n,1.0_nag_wp,a,lda,x(1,i),1,0.0_nag_wp,work,1)

          Do k = n + 1, n + nclin
            j = k - n
            Write (nout,99995) 'L', j, istate(k,i), work(j), clamda(k,i)
          End Do
        End If
        If (ncnln>0) Then
          Write (nout,99996) 'N Con'
          Do k = n + nclin + 1, n + nclin + ncnln
            j = k - n - nclin
            Write (nout,99995) 'N', j, istate(k,i), c(j,i), clamda(k,i)
          End Do
        End If
        Write (nout,99994) objf(i)
        Write (nout,99993)
        Write (nout,99992)(clamda(k,i),k=1,n+nclin+ncnln)

        If (l==1) Then
          Exit loop
        End If

        Write (nout,*)

        Write (nout,*)                                                         &
          ' ------------------------------------------------------ '

      End Do loop

100   Continue

99999 Format (1X,I20,'starting points converged')
99998 Format (/,1X,'Solution number',I16)
99997 Format (/,1X,'Local minimization exited with code',I5)
99996 Format (/,1X,A,2X,'Istate',3X,'Value',9X,'Lagr Mult',/)
99995 Format (1X,A,2(1X,I3),4X,F12.4,2X,F12.4)
99994 Format (/,1X,'Final objective value = ',1X,F12.4)
99993 Format (/,1X,'QP multipliers')
99992 Format (1X,F12.4)
    End Program e05usfe


f01abfe.f90

    Program f01abfe

!     F01ABF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: f01abf, nag_wp, x04caf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Integer                          :: i, ifail, lda, ldb, n
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: a(:,:), b(:,:), z(:)
!     .. Executable Statements ..
      Write (nout,*) 'F01ABF Example Program Results'
      Write (nout,*)
      Flush (nout)
!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) n
      lda = n + 1
      ldb = n
      Allocate (a(lda,n),b(ldb,n),z(n))
      Read (nin,*)(a(i,1:n),i=1,n)

!     ifail: behaviour on error exit
!             =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
      ifail = 0
      Call f01abf(a,lda,n,b,ldb,z,ifail)

!     Print the result matrix B
      Call x04caf('L','N',ldb,n,b,ldb,'Lower triangle of inverse',ifail)

    End Program f01abfe


f01adfe.f90

    Program f01adfe

!     F01ADF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: f01adf, nag_wp, x04caf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Integer                          :: i, ifail, lda, n
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: a(:,:)
!     .. Executable Statements ..
      Write (nout,*) 'F01ADF Example Program Results'
      Write (nout,*)
      Flush (nout)
!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) n
      lda = n + 1
      Allocate (a(lda,n))
      Read (nin,*)(a(i,1:n),i=1,n)

!     ifail: behaviour on error exit
!             =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
      ifail = 0
      Call f01adf(n,a,lda,ifail)

!     Print the result matrix A
      Call x04caf('L','B',lda,n,a,lda,'Lower triangle of inverse',ifail)

    End Program f01adfe


f01blfe.f90

    Program f01blfe

!     F01BLF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: f01blf, f06raf, nag_wp, x02ajf, x04cbf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: indent = 0, ncols = 80, nin = 5,     &
                                          nout = 6
      Character (1), Parameter         :: diag = 'N', matrix = 'G',            &
                                          nolabel = 'N'
      Character (8), Parameter         :: form = '1P,E12.4'
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: anorm, t
      Integer                          :: i, ifail, irank, lda, ldu, m, n
      Character (9)                    :: norm
      Character (27)                   :: title
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: a(:,:), aijmax(:), d(:), du(:),      &
                                          u(:,:)
      Real (Kind=nag_wp)               :: work(1)
      Integer, Allocatable             :: inc(:)
      Character (1)                    :: dummy(1)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: min
!     .. Executable Statements ..
      Write (nout,*) 'F01BLF Example Program Results'
      Write (nout,*)
!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) m, n
      lda = m
      ldu = n
      Allocate (a(lda,n),aijmax(n),d(m),du(n),u(ldu,n),inc(n))
      Read (nin,*)(a(i,1:n),i=1,m)
!     Set t = eps times norm of A.
      norm = 'Frobenius'
      anorm = f06raf(norm,m,n,a,lda,work)
      t = anorm*x02ajf()

!     ifail: behaviour on error exit
!             =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
      ifail = 0
      Call f01blf(m,n,t,a,lda,aijmax,irank,inc,d,u,ldu,du,ifail)

      Write (nout,*) 'Maximum element in A(K) for I.GE.K and J.GE.K'
      Write (nout,*)
      Write (nout,*) '   K    Modulus'
      Write (nout,99999)(i,aijmax(i),i=1,min(n,irank+1))
      Write (nout,*)
      Write (nout,99998) 'Rank = ', irank
      Write (nout,*)
      Write (nout,99997) 'T = ', t, '  (machine dependent)'
      Write (nout,*)
      Flush (nout)
!     Print the result matrix A.
      title = 'Transpose of pseudo-inverse'
      ifail = 0
      Call x04cbf(matrix,diag,m,n,a,lda,form,title,nolabel,dummy,nolabel,      &
        dummy,ncols,indent,ifail)

99999 Format (1X,I4,2X,1P,E12.4)
99998 Format (1X,A,I5)
99997 Format (1X,A,1P,E11.4,A)
    End Program f01blfe


f01brfe.f90

    Program f01brfe

!     F01BRF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: f01brf, nag_wp, x04abf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: iset = 1, nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: pivot
      Integer                          :: i, ifail, licn, lirn, n, nz, outchn
      Logical                          :: grow, lblock
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: a(:), w(:)
      Integer, Allocatable             :: icn(:), ikeep(:,:), irn(:), iw(:,:)
      Integer                          :: idisp(10)
      Logical                          :: abort(4)
!     .. Executable Statements ..
      Write (nout,*) 'F01BRF Example Program Results'
      outchn = nout
!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) n, nz
      licn = 3*nz
      lirn = 3*nz/2
      Allocate (a(licn),w(n),icn(licn),ikeep(n,5),irn(lirn),iw(n,8))
      Call x04abf(iset,outchn)
      Read (nin,*)(a(i),irn(i),icn(i),i=1,nz)
      pivot = 0.1E0_nag_wp
      lblock = .True.
      grow = .True.
      abort(1) = .True.
      abort(2) = .True.
      abort(3) = .False.
      abort(4) = .True.

!     ifail: behaviour on error exit
!            =110 for noisy, hard exit
      ifail = 110
      Call f01brf(n,nz,a,licn,irn,lirn,icn,pivot,ikeep,iw,w,lblock,grow,abort, &
        idisp,ifail)

      Write (nout,*)
      Write (nout,99999) 'Number of nonzeros in decomposition         =',      &
        idisp(2)
      Write (nout,99999) 'Minimum size of array IRN                    =',     &
        idisp(6)
      Write (nout,99999) 'Minimum size of arrays A and ICN             =',     &
        idisp(7)
      Write (nout,99999) 'Number of compresses on IRN (IDISP(3))       =',     &
        idisp(3)
      Write (nout,99999) 'Number of compresses on A and ICN (IDISP(4)) =',     &
        idisp(4)
      If (grow) Then
        Write (nout,*)
        Write (nout,99998) 'Value of W(1) =', w(1)
      End If
      If (lblock) Then
        Write (nout,*)
        Write (nout,99999) 'Structural rank                =', idisp(8)
        Write (nout,99999) 'Number of diagonal blocks      =', idisp(9)
        Write (nout,99999) 'Size of largest diagonal block =', idisp(10)
      End If

99999 Format (1X,A,I5,A,I5)
99998 Format (1X,A,F8.4)
    End Program f01brfe


f01bsfe.f90

    Program f01bsfe

!     F01BSF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: f01brf, f01bsf, nag_wp, x04abf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: iset = 1, nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: eta, rpmin, u
      Integer                          :: i, ifail, licn, lirn, n, nz, outchn
      Logical                          :: grow, lblock
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: a(:), w(:)
      Integer, Allocatable             :: icn(:), ikeep(:,:), irn(:),          &
                                          ivect(:), iw(:,:), jvect(:)
      Integer                          :: idisp(10)
      Logical                          :: abort(4)
!     .. Executable Statements ..
      Write (nout,*) 'F01BSF Example Program Results'
      outchn = nout
!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) n, nz
      licn = 3*nz
      lirn = 3*nz/2
      Allocate (a(licn),w(n),icn(licn),ikeep(n,5),irn(lirn),ivect(nz),iw(n,8), &
        jvect(nz))
      Call x04abf(iset,outchn)
      Write (nout,*)
      Read (nin,*)(a(i),irn(i),icn(i),i=1,nz)
      u = 0.1E0_nag_wp
      lblock = .True.
      grow = .True.
      abort(1) = .True.
      abort(2) = .True.
      abort(3) = .False.
      abort(4) = .True.

!     ifail: behaviour on error exit
!             =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
      ifail = 0
      Call f01brf(n,nz,a,licn,irn,lirn,icn,u,ikeep,iw,w,lblock,grow,abort,     &
        idisp,ifail)

      If (grow) Then
        Write (nout,*) 'On exit from F01BRF'
        Write (nout,99999) 'Value of W(1)  = ', w(1)
      End If
      Read (nin,*)(a(i),ivect(i),jvect(i),i=1,nz)
      eta = 0.1E0_nag_wp

!     ifail: behaviour on error exit
!            =110 for noisy, hard exit
      ifail = 110
      Call f01bsf(n,nz,a,licn,ivect,jvect,icn,ikeep,iw,w,grow,eta,rpmin,       &
        abort(4),idisp,ifail)

      If (grow) Then
        Write (nout,*)
        Write (nout,*) 'On exit from F01BSF'
        Write (nout,99999) 'Value of W(1)  = ', w(1)
      End If
      If (eta<1.0E0_nag_wp) Then
        Write (nout,*)
        Write (nout,99999) 'Value of RPMIN = ', rpmin
      End If

99999 Format (1X,A,F7.4)
    End Program f01bsfe


f01bufe.f90

    Program f01bufe

!     F01BUF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: f01buf, nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Integer                          :: i, ifail, j, k, lda, m, m1, n
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: a(:,:), w(:)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: max
!     .. Executable Statements ..
      Write (nout,*) 'F01BUF Example Program Results'
!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) n, m1
      lda = m1
      Allocate (a(lda,n),w(m1))
      Read (nin,*)((a(j,i),j=max(1,m1+1-i),m1),i=1,n)
      m = m1 - 1
      k = ((n+m)/(2*m))*m

!     ifail: behaviour on error exit
!             =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
      ifail = 0
      Call f01buf(n,m1,k,a,lda,w,ifail)

      Write (nout,*)
      Write (nout,*) 'Computed upper triangular matrix'
      Write (nout,*)
      Do i = 1, n
        Write (nout,99999)(a(j,i),j=max(1,m1+1-i),m1)
      End Do

99999 Format (1X,8F9.4)
    End Program f01bufe


f01bvfe.f90

    Program f01bvfe

!     F01BVF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: dsbtrd, dstebz, f01buf, f01bvf, nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Real (Kind=nag_wp), Parameter    :: zero = 0.0_nag_wp
      Integer, Parameter               :: inc1 = 1, nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: abstol
      Integer                          :: i, ifail, info, j, k, lda, ldb, ldv, &
                                          m, m1, m2, m3, ma1, mb1, n, nsplit
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: a(:,:), b(:,:), d(:), e(:), r(:),    &
                                          v(:,:), w(:), work(:)
      Integer, Allocatable             :: iblock(:), isplit(:), iwork(:)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: max
!     .. Executable Statements ..
      Write (nout,*) 'F01BVF Example Program Results'
!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) n, ma1, mb1
      lda = ma1
      ldb = mb1
      ldv = ma1 + mb1 - 2
      m3 = 3*ma1 + mb1 - 4
      Allocate (a(lda,n),b(ldb,n),d(n),e(n),r(n),v(ldv,m3),w(m3),work(4*n),    &
        iblock(n),isplit(n),iwork(3*n))
      Read (nin,*)((a(j,i),j=max(1,ma1+1-i),ma1),i=1,n)
      Read (nin,*)((b(j,i),j=max(1,mb1+1-i),mb1),i=1,n)
      k = n/2

!     ifail: behaviour on error exit
!             =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
      ifail = 0
      Call f01buf(n,mb1,k,b,ldb,w,ifail)

      ifail = 0
      Call f01bvf(n,ma1,mb1,m3,k,a,lda,b,ldb,v,ldv,w,ifail)

!     The NAG name equivalent of dsbtrd is f08hef
      Call dsbtrd('N','U',n,ma1-1,a,lda,d,e,w,inc1,work,info)

      abstol = zero
      Read (nin,*) m1, m2

!     The NAG name equivalent of dstebz is f08jjf
      Call dstebz('I','E',n,zero,zero,m1,m2,abstol,d,e,m,nsplit,r,iblock,      &
        isplit,work,iwork,info)

      Write (nout,*)
      Write (nout,*) 'Selected eigenvalues'
      Write (nout,99999) r(1:m)

99999 Format (1X,8F9.4)
    End Program f01bvfe


f01ckfe.f90

    Program f01ckfe

!     F01CKF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: f01ckf, nag_wp, x04cbf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: indent = 0, iz = 1, ncols = 80,      &
                                          nin = 5, nout = 6, opt = 1
      Character (1), Parameter         :: diag = 'N', matrix = 'G',            &
                                          nolabel = 'N'
      Character (4), Parameter         :: form = 'F7.1'
!     .. Local Scalars ..
      Integer                          :: i, ifail, j, m, n, p
      Character (8)                    :: title
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: a(:,:), b(:,:), c(:,:)
      Real (Kind=nag_wp)               :: z(iz)
      Character (1)                    :: dummy(1)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: real
!     .. Executable Statements ..
      Write (nout,*) 'F01CKF Example Program Results'
!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) n, p, m

      Allocate (a(n,p),b(n,m),c(m,p))

!     Set up example B and C matrices
      Do i = 1, m
        Do j = 1, n
          b(j,i) = real(i+j-2,kind=nag_wp)
        End Do
        Do j = 1, p
          c(i,j) = real(i+j-2,kind=nag_wp)
        End Do
      End Do

!     ifail: behaviour on error exit
!             =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
      ifail = 0
      Call f01ckf(a,b,c,n,p,m,z,iz,opt,ifail)

!     Print the result matrix A
      title = 'Matrix A'
      Write (nout,*)
      Flush (nout)
      ifail = 0
      Call x04cbf(matrix,diag,n,p,a,n,form,title,nolabel,dummy,nolabel,dummy,  &
        ncols,indent,ifail)

    End Program f01ckfe


f01crfe.f90

    Program f01crfe

!     F01CRF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: f01crf, nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Integer                          :: i, ifail, lmove, m, mn, n
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: a(:)
      Integer, Allocatable             :: move(:)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: real
!     .. Executable Statements ..
      Write (nout,*) 'F01CRF Example Program Results'
!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) m, n
      mn = m*n
      lmove = (m+n)/2
      Allocate (a(mn),move(lmove))
      Do i = 1, mn
        a(i) = real(i,kind=nag_wp)
      End Do

!     ifail: behaviour on error exit
!            =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
      ifail = 0
      Call f01crf(a,m,n,mn,move,lmove,ifail)

      Write (nout,*)
      Write (nout,99999) a(1:mn)

99999 Format (1X,7F7.1)
    End Program f01crfe


f01ctfe.f90

    Program f01ctfe

!     F01CTF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: f01ctf, nag_wp, x04caf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: alpha, beta
      Integer                          :: i, ifail, lda, ldb, ldc, m, n,       &
                                          ncola, ncolb, nrowa, nrowb
      Character (1)                    :: transa, transb
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: a(:,:), b(:,:), c(:,:)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: max
!     .. Executable Statements ..
      Write (nout,*) 'F01CTF Example Program Results'
!     Skip heading in data file
      Read (nin,*)
100   Continue
!     Skip Subexample heading
      Read (nin,*,End=110)
      Read (nin,*) nrowa, ncola, transa, alpha
      Read (nin,*) nrowb, ncolb, transb, beta
      lda = max(nrowa,ncola)
      ldb = max(nrowb,ncolb)
      ldc = lda
      Allocate (a(lda,max(nrowa,ncola)),b(ldb,max(nrowb,                       &
        ncolb)),c(ldc,max(nrowa,ncola)))
!     Read matrices A and B.
      Do i = 1, nrowa
        Read (nin,*) a(i,1:ncola)
      End Do
      Do i = 1, nrowb
        Read (nin,*) b(i,1:ncolb)
      End Do
      If (transa=='N' .Or. transa=='n') Then
        m = nrowa
        n = ncola
      Else
        m = ncola
        n = nrowa
      End If

!     ifail: behaviour on error exit
!            =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
      ifail = 0
!     Add the two matrices A and B.
      Call f01ctf(transa,transb,m,n,alpha,a,lda,beta,b,ldb,c,ldc,ifail)

!     Print the result matrix C.
      Write (nout,99999) transa, transb, alpha, beta
      Flush (nout)
      Call x04caf('G','X',m,n,c,ldc,'Matrix C:',ifail)
      Write (nout,*)
      Deallocate (a,b,c)
      Go To 100
110   Continue

99999 Format (1X,/,1X,'TRANSA = ''',A,''', TRANSB = ''',A,''', ALPHA = ',1P,   &
        E11.3,', BETA = ',E11.3)
    End Program f01ctfe


f01cwfe.f90

    Program f01cwfe

!     F01CWF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: f01cwf, nag_wp, x04daf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Complex (Kind=nag_wp)            :: alpha, beta
      Integer                          :: i, ifail, lda, ldb, ldc, m, n,       &
                                          ncola, ncolb, nrowa, nrowb
      Character (1)                    :: transa, transb
!     .. Local Arrays ..
      Complex (Kind=nag_wp), Allocatable :: a(:,:), b(:,:), c(:,:)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: max
!     .. Executable Statements ..
      Write (nout,*) 'F01CWF Example Program Results'
      Write (nout,*)
!     Skip heading in data file
      Read (nin,*)
100   Continue
!     Skip Subexample heading
      Read (nin,*,End=110)
      Read (nin,*) nrowa, ncola, transa, alpha
      Read (nin,*) nrowb, ncolb, transb, beta
      lda = max(nrowa,ncola)
      ldb = max(nrowb,ncolb)
      ldc = lda
      Allocate (a(lda,max(nrowa,ncola)),b(ldb,max(nrowb,                       &
        ncolb)),c(ldc,max(nrowa,ncola)))
!     Read matrices A and B.
      Do i = 1, nrowa
        Read (nin,*) a(i,1:ncola)
      End Do
      Do i = 1, nrowb
        Read (nin,*) b(i,1:ncolb)
      End Do
      If (transa=='N' .Or. transa=='n') Then
        m = nrowa
        n = ncola
      Else
        m = ncola
        n = nrowa
      End If

!     ifail: behaviour on error exit
!            =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
      ifail = 0
!     Add the two matrices A and B.
      Call f01cwf(transa,transb,m,n,alpha,a,lda,beta,b,ldb,c,ldc,ifail)

!     Print the result matrix C.
      Write (nout,99999) transa, transb
      Write (nout,99998) alpha, beta
      Flush (nout)
      Call x04daf('G','X',m,n,c,ldc,'Matrix C:',ifail)
      Write (nout,*)
      Deallocate (a,b,c)
      Go To 100
110   Continue

99999 Format (1X,'TRANSA = ''',A,''', TRANSB = ''',A,''',')
99998 Format (1X,'ALPHA = (',1P,E11.4,',',E11.4,'), BETA = (',E11.4,',',E11.4, &
        ')')
    End Program f01cwfe


f01ecfe.f90

    Program f01ecfe

!     F01ECF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: f01ecf, nag_wp, x04caf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Integer                          :: i, ifail, lda, n
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: a(:,:)
!     .. Executable Statements ..
      Write (nout,*) 'F01ECF Example Program Results'
      Write (nout,*)
      Flush (nout)
!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) n
      lda = n
      Allocate (a(lda,n))
!     Read A from data file
      Read (nin,*)(a(i,1:n),i=1,n)

!     ifail: behaviour on error exit
!             =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
      ifail = 0
!     Find exp( A )
      Call f01ecf(n,a,lda,ifail)

!     Print solution
      Call x04caf('General',' ',n,n,a,lda,'Exp(A)',ifail)

    End Program f01ecfe


f01edfe.f90

    Program f01edfe

!     F01EDF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: f01edf, nag_wp, x04caf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Integer                          :: i, ifail, lda, n
      Character (1)                    :: uplo
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: a(:,:)
!     .. Executable Statements ..
      Write (nout,*) 'F01EDF Example Program Results'
      Write (nout,*)
      Flush (nout)
!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) n
      Read (nin,*) uplo
      lda = n
      Allocate (a(lda,n))
!     Read A from data file
      If (uplo=='U' .Or. uplo=='u') Then
        Read (nin,*)(a(i,i:n),i=1,n)
      Else
        Read (nin,*)(a(i,1:i),i=1,n)
      End If

!     ifail: behaviour on error exit
!            =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
      ifail = 0
!     Find exp( A )
      Call f01edf(uplo,n,a,lda,ifail)

!     Print solution
      Call x04caf(uplo,'N',n,n,a,lda,'Symmetric Exp(A)',ifail)

    End Program f01edfe


f01effe.f90

!   F01EFF Example Program Text
!   Mark 26 Release. NAG Copyright 2016.

    Module f01effe_mod

!     F01EFF Example Program Module:
!            Parameters and User-defined Routines

!     nin:       the input channel number
!     nout:      the output channel number

!     .. Use Statements ..
      Use nag_library, Only: nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Accessibility Statements ..
      Private
      Public                           :: f
!     .. Parameters ..
      Integer, Parameter, Public       :: nin = 5, nout = 6
    Contains
      Subroutine f(iflag,n,x,fx,iuser,ruser)

!       .. Scalar Arguments ..
        Integer, Intent (Inout)        :: iflag
        Integer, Intent (In)           :: n
!       .. Array Arguments ..
        Real (Kind=nag_wp), Intent (Out) :: fx(n)
        Real (Kind=nag_wp), Intent (Inout) :: ruser(*)
        Real (Kind=nag_wp), Intent (In) :: x(n)
        Integer, Intent (Inout)        :: iuser(*)
!       .. Intrinsic Procedures ..
        Intrinsic                      :: cos
!       .. Executable Statements ..
        fx(1:n) = cos(x(1:n))

        Return
      End Subroutine f
    End Module f01effe_mod
    Program f01effe

!     F01EFF Example Main Program

!     .. Use Statements ..
      Use nag_library, Only: f01eff, nag_wp, x04caf
      Use f01effe_mod, Only: f, nin, nout
!     .. Implicit None Statement ..
      Implicit None
!     .. Local Scalars ..
      Integer                          :: i, ierr, ifail, iflag, lda, n
      Character (1)                    :: uplo
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: a(:,:)
      Real (Kind=nag_wp)               :: ruser(1)
      Integer                          :: iuser(1)
!     .. Executable Statements ..
      Write (nout,*) 'F01EFF Example Program Results'
      Write (nout,*)
      Flush (nout)
!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) n
      Read (nin,*) uplo

      lda = n
      Allocate (a(lda,n))

!     Read A from data file

      If (uplo=='U' .Or. uplo=='u') Then
        Read (nin,*)(a(i,i:n),i=1,n)
      Else
        Read (nin,*)(a(i,1:i),i=1,n)
      End If

!     Find f( A )

      ifail = 0
      Call f01eff(uplo,n,a,lda,f,iuser,ruser,iflag,ifail)

!     Print solution

      ierr = 0
      Call x04caf(uplo,'N',n,n,a,lda,'Symmetric f(A)',ierr)

    End Program f01effe


f01ejfe.f90

    Program f01ejfe

!     F01EJF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: f01ejf, nag_wp, x04caf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: imnorm
      Integer                          :: i, ifail, lda, n
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: a(:,:)
!     .. Executable Statements ..
      Write (nout,*) 'F01EJF Example Program Results'
      Write (nout,*)
      Flush (nout)

!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) n

      lda = n
      Allocate (a(lda,n))

!     Read A from data file
      Read (nin,*)(a(i,1:n),i=1,n)

!     ifail: behaviour on error exit
!             =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
      ifail = 0

!     Find log( A )
      Call f01ejf(n,a,lda,imnorm,ifail)

!     Print solution
      ifail = 0
      Call x04caf('G','N',n,n,a,lda,'log(A)',ifail)

    End Program f01ejfe


f01ekfe.f90

    Program f01ekfe

!     F01EKF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: f01ekf, nag_wp, x04caf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: imnorm
      Integer                          :: i, ifail, lda, n
      Character (4)                    :: fun
      Character (20)                   :: fun_name
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: a(:,:)
!     .. Executable Statements ..
      Write (nout,*) 'F01EKF Example Program Results'
      Write (nout,*)
      Flush (nout)

!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) n, fun

      lda = n
      Allocate (a(lda,n))

!     Read A from data file
      Read (nin,*)(a(i,1:n),i=1,n)

!     Find f( A )
      ifail = 0
      Call f01ekf(fun,n,a,lda,imnorm,ifail)

!     Print solution
      Write (fun_name,Fmt='(3(A))') 'F(A) = ', fun, '(A)'
      Write (nout,*)

      ifail = 0
      Call x04caf('G','N',n,n,a,lda,fun_name,ifail)

!     Print the norm of the imaginary part to check it is small
      Write (nout,*)
      Write (nout,Fmt='(1X,A,F6.2)') 'Imnorm =', imnorm

    End Program f01ekfe


f01elfe.f90

!   F01ELF Example Program Text

!   Mark 26 Release. NAG Copyright 2016.

    Module f01elfe_mod

!     F01ELF Example Program Module:
!            Parameters and User-defined Routines

!     .. Use Statements ..
      Use nag_library, Only: nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Accessibility Statements ..
      Private
      Public                           :: fcos2
    Contains
      Subroutine fcos2(iflag,nz,z,fz,iuser,ruser)

!       .. Scalar Arguments ..
        Integer, Intent (Inout)        :: iflag
        Integer, Intent (In)           :: nz
!       .. Array Arguments ..
        Complex (Kind=nag_wp), Intent (Out) :: fz(nz)
        Complex (Kind=nag_wp), Intent (In) :: z(nz)
        Real (Kind=nag_wp), Intent (Inout) :: ruser(*)
        Integer, Intent (Inout)        :: iuser(*)
!       .. Intrinsic Procedures ..
        Intrinsic                      :: cos
!       .. Executable Statements ..
        Continue
        fz(1:nz) = cos((2.0E0_nag_wp,0.0E0_nag_wp)*z(1:nz))
!       Set iflag nonzero to terminate execution for any reason.
        iflag = 0
        Return
      End Subroutine fcos2
    End Module f01elfe_mod
    Program f01elfe

!     F01ELF Example Main Program

!     .. Use Statements ..
      Use nag_library, Only: f01elf, nag_wp, x04caf
      Use f01elfe_mod, Only: fcos2
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: imnorm
      Integer                          :: i, ifail, iflag, lda, n
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: a(:,:)
      Real (Kind=nag_wp)               :: ruser(1)
      Integer                          :: iuser(1)
!     .. Executable Statements ..
      Write (nout,*) 'F01ELF Example Program Results'
      Write (nout,*)
      Flush (nout)

!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) n

      lda = n
      Allocate (a(lda,n))

!     Read A from data file
      Read (nin,*)(a(i,1:n),i=1,n)

!     Find f( A )
      ifail = 0
      Call f01elf(n,a,lda,fcos2,iuser,ruser,iflag,imnorm,ifail)

!     Print solution
      ifail = 0
      Call x04caf('G','N',n,n,a,lda,'F(A) = COS(2A)',ifail)

!     Print the norm of the imaginary part to check it is small
      Write (nout,*)
      Write (nout,Fmt='(1X,A,F6.2)') 'Imnorm =', imnorm
    End Program f01elfe


f01emfe.f90

!   F01EMF Example Program Text

!   Mark 26 Release. NAG Copyright 2016.

    Module f01emfe_mod

!     F01EMF Example Program Module:
!            Parameters and User-defined Routines

!     .. Use Statements ..
      Use nag_library, Only: nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Accessibility Statements ..
      Private
      Public                           :: fexp2
    Contains
      Subroutine fexp2(m,iflag,nz,z,fz,iuser,ruser)

!       .. Parameters ..
        Complex (Kind=nag_wp), Parameter :: two = (2.0E0_nag_wp,0.0E0_nag_wp)
!       .. Scalar Arguments ..
        Integer, Intent (Inout)        :: iflag
        Integer, Intent (In)           :: m, nz
!       .. Array Arguments ..
        Complex (Kind=nag_wp), Intent (Out) :: fz(nz)
        Complex (Kind=nag_wp), Intent (In) :: z(nz)
        Real (Kind=nag_wp), Intent (Inout) :: ruser(*)
        Integer, Intent (Inout)        :: iuser(*)
!       .. Intrinsic Procedures ..
        Intrinsic                      :: exp
!       .. Executable Statements ..
        Continue
        fz(1:nz) = (two**m)*exp(two*z(1:nz))
!       Set iflag nonzero to terminate execution for any reason.
        iflag = 0
        Return
      End Subroutine fexp2
    End Module f01emfe_mod
    Program f01emfe

!     F01EMF Example Main Program

!     .. Use Statements ..
      Use nag_library, Only: f01emf, nag_wp, x04caf
      Use f01emfe_mod, Only: fexp2
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: imnorm
      Integer                          :: i, ifail, iflag, lda, n
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: a(:,:)
      Real (Kind=nag_wp)               :: ruser(1)
      Integer                          :: iuser(1)
!     .. Executable Statements ..
      Write (nout,*) 'F01EMF Example Program Results'
      Write (nout,*)
      Flush (nout)

!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) n

      lda = n
      Allocate (a(lda,n))

!     Read A from data file
      Read (nin,*)(a(i,1:n),i=1,n)

!     Find f( A )
      ifail = 0
      Call f01emf(n,a,lda,fexp2,iuser,ruser,iflag,imnorm,ifail)

!     Print solution
      ifail = 0
      Call x04caf('G','N',n,n,a,lda,'F(A) = EXP(2A)',ifail)

!     Print the norm of the imaginary part to check it is small
      Write (nout,*)
      Write (nout,Fmt='(1X,A,F6.2)') 'Imnorm =', imnorm
    End Program f01emfe


f01enfe.f90

    Program f01enfe

!     F01ENF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: f01enf, nag_wp, x04caf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Integer                          :: i, ifail, lda, n
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: a(:,:)
!     .. Executable Statements ..
      Write (nout,*) 'F01ENF Example Program Results'
      Write (nout,*)
!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) n

      lda = n
      Allocate (a(lda,n))

!     Read A from data file
      Read (nin,*)(a(i,1:n),i=1,n)

!     ifail: behaviour on error exit
!             =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
      ifail = 0

!     Find sqrt(A)
      Call f01enf(n,a,lda,ifail)

!     Print solution
      If (ifail==0) Then
        ifail = 0
        Call x04caf('G','N',n,n,a,lda,'sqrt(A)',ifail)
      End If

    End Program f01enfe


f01epfe.f90

    Program f01epfe

!     F01EPF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: f01epf, nag_wp, x04caf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Integer                          :: i, ifail, lda, n
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: a(:,:)
!     .. Executable Statements ..
      Write (nout,*) 'F01EPF Example Program Results'
      Write (nout,*)
!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) n

      lda = n
      Allocate (a(lda,n))

!     Read A from data file
      Read (nin,*)(a(i,1:n),i=1,n)

!     ifail: behaviour on error exit
!             =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
      ifail = 0

!     Find sqrt(A)
      Call f01epf(n,a,lda,ifail)

!     Print solution
      If (ifail==0) Then
        ifail = 0
        Call x04caf('G','N',n,n,a,lda,'sqrt(A)',ifail)
      End If

    End Program f01epfe


f01eqfe.f90

    Program f01eqfe

!     F01EQF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: f01eqf, nag_wp, x04caf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: p
      Integer                          :: i, ifail, lda, n
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: a(:,:)
!     .. Executable Statements ..
      Write (nout,*) 'F01EQF Example Program Results'
      Write (nout,*)
      Flush (nout)
!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) n, p
      lda = n
      Allocate (a(lda,n))
!     Read A from data file
      Read (nin,*)(a(i,1:n),i=1,n)

!     ifail: behaviour on error exit
!             =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
      ifail = 0

!     Find A^p
      Call f01eqf(n,a,lda,p,ifail)

!     Print solution
      If (ifail==0) Then
        ifail = 0
        Call x04caf('G','N',n,n,a,lda,'A^p',ifail)
      End If

    End Program f01eqfe


f01fcfe.f90

    Program f01fcfe

!     F01FCF Example Program Text
!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: f01fcf, nag_wp, x04daf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Integer                          :: i, ierr, ifail, lda, n
!     .. Local Arrays ..
      Complex (Kind=nag_wp), Allocatable :: a(:,:)
!     .. Executable Statements ..
      Write (nout,*) 'F01FCF Example Program Results'
      Write (nout,*)
      Flush (nout)
!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) n

      lda = n
      Allocate (a(lda,n))

!     Read A from data file

      Read (nin,*)(a(i,1:n),i=1,n)

!     ifail: behaviour on error exit
!             =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
      ifail = 0

!     Find exp( A )
      Call f01fcf(n,a,lda,ifail)

!     Print solution

      ierr = 0
      Call x04daf('General',' ',n,n,a,lda,'Exp(A)',ierr)

    End Program f01fcfe


f01fdfe.f90

    Program f01fdfe

!     F01FDF Example Program Text
!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: f01fdf, nag_wp, x04daf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Integer                          :: i, ierr, ifail, lda, n
      Character (1)                    :: uplo
!     .. Local Arrays ..
      Complex (Kind=nag_wp), Allocatable :: a(:,:)
!     .. Executable Statements ..
      Write (nout,*) 'F01FDF Example Program Results'
      Write (nout,*)
      Flush (nout)
!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) n
      Read (nin,*) uplo

      lda = n
      Allocate (a(lda,n))

!     Read A from data file

      If (uplo=='U' .Or. uplo=='u') Then
        Read (nin,*)(a(i,i:n),i=1,n)
      Else
        Read (nin,*)(a(i,1:i),i=1,n)
      End If

!     Find exp( A )

      ifail = 0
      Call f01fdf(uplo,n,a,lda,ifail)

!     Print solution

      ierr = 0
      Call x04daf(uplo,'N',n,n,a,lda,'Hermitian Exp(A)',ierr)

    End Program f01fdfe


f01fffe.f90

!   F01FFF Example Program Text
!   Mark 26 Release. NAG Copyright 2016.

    Module f01fffe_mod

!     F01FFF Example Program Module:
!            Parameters and User-defined Routines

!     nin:       the input channel number
!     nout:      the output channel number

!     .. Use Statements ..
      Use nag_library, Only: nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Accessibility Statements ..
      Private
      Public                           :: f
!     .. Parameters ..
      Integer, Parameter, Public       :: nin = 5, nout = 6
    Contains
      Subroutine f(iflag,n,x,fx,iuser,ruser)

!       .. Scalar Arguments ..
        Integer, Intent (Inout)        :: iflag
        Integer, Intent (In)           :: n
!       .. Array Arguments ..
        Real (Kind=nag_wp), Intent (Out) :: fx(n)
        Real (Kind=nag_wp), Intent (Inout) :: ruser(*)
        Real (Kind=nag_wp), Intent (In) :: x(n)
        Integer, Intent (Inout)        :: iuser(*)
!       .. Intrinsic Procedures ..
        Intrinsic                      :: cos
!       .. Executable Statements ..
        fx(1:n) = cos(x(1:n))

        Return
      End Subroutine f
    End Module f01fffe_mod
    Program f01fffe

!     F01FFF Example Main Program

!     .. Use Statements ..
      Use nag_library, Only: f01fff, nag_wp, x04daf
      Use f01fffe_mod, Only: f, nin, nout
!     .. Implicit None Statement ..
      Implicit None
!     .. Local Scalars ..
      Integer                          :: i, ierr, ifail, iflag, lda, n
      Character (1)                    :: uplo
!     .. Local Arrays ..
      Complex (Kind=nag_wp), Allocatable :: a(:,:)
      Real (Kind=nag_wp)               :: ruser(1)
      Integer                          :: iuser(1)
!     .. Executable Statements ..
      Write (nout,*) 'F01FFF Example Program Results'
      Write (nout,*)
      Flush (nout)
!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) n
      Read (nin,*) uplo

      lda = n
      Allocate (a(lda,n))

!     Read A from data file

      If (uplo=='U' .Or. uplo=='u') Then
        Read (nin,*)(a(i,i:n),i=1,n)
      Else
        Read (nin,*)(a(i,1:i),i=1,n)
      End If

!     Find f( A )

      ifail = 0
      Call f01fff(uplo,n,a,lda,f,iuser,ruser,iflag,ifail)

!     Print solution

      ierr = 0
      Call x04daf(uplo,'N',n,n,a,lda,'Hermitian f(A)',ierr)

    End Program f01fffe


f01fjfe.f90

    Program f01fjfe

!     F01FJF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: f01fjf, nag_wp, x04daf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Integer                          :: i, ifail, lda, n
!     .. Local Arrays ..
      Complex (Kind=nag_wp), Allocatable :: a(:,:)
!     .. Executable Statements ..
      Write (nout,*) 'F01FJF Example Program Results'
      Write (nout,*)
      Flush (nout)

!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) n

      lda = n
      Allocate (a(lda,n))

!     Read A from data file
      Read (nin,*)(a(i,1:n),i=1,n)

!     ifail: behaviour on error exit
!             =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
      ifail = 0

!     Find log( A )
      Call f01fjf(n,a,lda,ifail)

!     Print solution
      ifail = 0
      Call x04daf('G','N',n,n,a,lda,'log(A)',ifail)

    End Program f01fjfe


f01fkfe.f90

    Program f01fkfe

!     F01FKF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: f01fkf, nag_wp, x04daf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Integer                          :: i, ifail, lda, n
      Character (4)                    :: fun
      Character (20)                   :: fun_name
!     .. Local Arrays ..
      Complex (Kind=nag_wp), Allocatable :: a(:,:)
!     .. Executable Statements ..
      Write (nout,*) 'F01FKF Example Program Results'
      Write (nout,*)
      Flush (nout)

!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) n, fun

      lda = n
      Allocate (a(lda,n))

!     Read A from data file
      Read (nin,*)(a(i,1:n),i=1,n)

!     Find f( A )
      ifail = 0
      Call f01fkf(fun,n,a,lda,ifail)

!     Print solution
      Write (fun_name,Fmt='(3(A))') 'F(A) = ', fun, '(A)'
      Write (nout,*)

      ifail = 0
      Call x04daf('G','N',n,n,a,lda,fun_name,ifail)

    End Program f01fkfe


f01flfe.f90

!   F01FLF Example Program Text

!   Mark 26 Release. NAG Copyright 2016.

    Module f01flfe_mod

!     F01FLF Example Program Module:
!            Parameters and User-defined Routines

!     .. Use Statements ..
      Use nag_library, Only: nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Accessibility Statements ..
      Private
      Public                           :: fsin2
    Contains
      Subroutine fsin2(iflag,nz,z,fz,iuser,ruser)

!       .. Scalar Arguments ..
        Integer, Intent (Inout)        :: iflag
        Integer, Intent (In)           :: nz
!       .. Array Arguments ..
        Complex (Kind=nag_wp), Intent (Out) :: fz(nz)
        Complex (Kind=nag_wp), Intent (In) :: z(nz)
        Real (Kind=nag_wp), Intent (Inout) :: ruser(*)
        Integer, Intent (Inout)        :: iuser(*)
!       .. Intrinsic Procedures ..
        Intrinsic                      :: sin
!       .. Executable Statements ..
        Continue
        fz(1:nz) = sin((2.0E0_nag_wp,0.0E0_nag_wp)*z(1:nz))
!       Set iflag nonzero to terminate execution for any reason.
        iflag = 0
        Return
      End Subroutine fsin2
    End Module f01flfe_mod
    Program f01flfe

!     F01FLF Example Main Program

!     .. Use Statements ..
      Use nag_library, Only: f01flf, nag_wp, x04daf
      Use f01flfe_mod, Only: fsin2
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Integer                          :: i, ifail, iflag, lda, n
!     .. Local Arrays ..
      Complex (Kind=nag_wp), Allocatable :: a(:,:)
      Real (Kind=nag_wp)               :: ruser(1)
      Integer                          :: iuser(1)
!     .. Executable Statements ..
      Write (nout,*) 'F01FLF Example Program Results'
      Write (nout,*)
      Flush (nout)

!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) n

      lda = n
      Allocate (a(lda,n))

!     Read A from data file
      Read (nin,*)(a(i,1:n),i=1,n)

!     Find f( A )
      ifail = 0
      Call f01flf(n,a,lda,fsin2,iuser,ruser,iflag,ifail)

!     Print solution
      ifail = 0
      Call x04daf('G','N',n,n,a,lda,'F(A) = SIN(2A)',ifail)

    End Program f01flfe


f01fmfe.f90

!   F01FMF Example Program Text

!   Mark 26 Release. NAG Copyright 2016.

    Module f01fmfe_mod

!     F01FMF Example Program Module:
!            Parameters and User-defined Routines

!     .. Use Statements ..
      Use nag_library, Only: nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Accessibility Statements ..
      Private
      Public                           :: fexp3
    Contains
      Subroutine fexp3(m,iflag,nz,z,fz,iuser,ruser)

!       .. Parameters ..
        Complex (Kind=nag_wp), Parameter :: three = (3.0E0_nag_wp,0.0E0_nag_wp &
                                          )
!       .. Scalar Arguments ..
        Integer, Intent (Inout)        :: iflag
        Integer, Intent (In)           :: m, nz
!       .. Array Arguments ..
        Complex (Kind=nag_wp), Intent (Out) :: fz(nz)
        Complex (Kind=nag_wp), Intent (In) :: z(nz)
        Real (Kind=nag_wp), Intent (Inout) :: ruser(*)
        Integer, Intent (Inout)        :: iuser(*)
!       .. Intrinsic Procedures ..
        Intrinsic                      :: exp
!       .. Executable Statements ..
        Continue
        fz(1:nz) = (three**m)*exp(three*z(1:nz))
!       Set iflag nonzero to terminate execution for any reason.
        iflag = 0
        Return
      End Subroutine fexp3
    End Module f01fmfe_mod
    Program f01fmfe

!     F01FMF Example Main Program

!     .. Use Statements ..
      Use nag_library, Only: f01fmf, nag_wp, x04daf
      Use f01fmfe_mod, Only: fexp3
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Integer                          :: i, ifail, iflag, lda, n
!     .. Local Arrays ..
      Complex (Kind=nag_wp), Allocatable :: a(:,:)
      Real (Kind=nag_wp)               :: ruser(1)
      Integer                          :: iuser(1)
!     .. Executable Statements ..
      Write (nout,*) 'F01FMF Example Program Results'
      Write (nout,*)
      Flush (nout)

!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) n

      lda = n
      Allocate (a(lda,n))

!     Read A from data file
      Read (nin,*)(a(i,1:n),i=1,n)

!     Find f( A )
      ifail = 0
      Call f01fmf(n,a,lda,fexp3,iuser,ruser,iflag,ifail)

!     Print solution
      ifail = 0
      Call x04daf('G','N',n,n,a,lda,'F(A) = EXP(3A)',ifail)

    End Program f01fmfe


f01fnfe.f90

    Program f01fnfe

!     F01FNF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: f01fnf, nag_wp, x04daf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Integer                          :: i, ifail, lda, n
!     .. Local Arrays ..
      Complex (Kind=nag_wp), Allocatable :: a(:,:)
!     .. Executable Statements ..
      Write (nout,*) 'F01FNF Example Program Results'
      Write (nout,*)
!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) n

      lda = n
      Allocate (a(lda,n))

!     Read A from data file
      Read (nin,*)(a(i,1:n),i=1,n)

!     ifail: behaviour on error exit
!             =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
      ifail = 0

!     Find sqrt(A)
      Call f01fnf(n,a,lda,ifail)

!     Print solution
      If (ifail==0) Then
        ifail = 0
        Call x04daf('G','N',n,n,a,lda,'sqrt(A)',ifail)
      End If

    End Program f01fnfe


f01fpfe.f90

    Program f01fpfe

!     F01FPF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: f01fpf, nag_wp, x04daf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Integer                          :: i, ifail, lda, n
!     .. Local Arrays ..
      Complex (Kind=nag_wp), Allocatable :: a(:,:)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: cmplx
!     .. Executable Statements ..
      Write (nout,*) 'F01FPF Example Program Results'
      Write (nout,*)
!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) n

      lda = n
      Allocate (a(lda,n))
      a(1:lda,1:n) = cmplx(0,kind=nag_wp)

!     Read A from data file
      Read (nin,*)(a(i,i:n),i=1,n)

!     ifail: behaviour on error exit
!             =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
      ifail = 0

!     Find sqrt(A)
      Call f01fpf(n,a,lda,ifail)

!     Print solution
      If (ifail==0) Then
        ifail = 0
        Call x04daf('G','N',n,n,a,lda,'sqrt(A)',ifail)
      End If

    End Program f01fpfe


f01fqfe.f90

    Program f01fqfe

!     F01FQF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: f01fqf, nag_wp, x04daf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: p
      Integer                          :: i, ifail, lda, n
!     .. Local Arrays ..
      Complex (Kind=nag_wp), Allocatable :: a(:,:)
!     .. Executable Statements ..
      Write (nout,*) 'F01FQF Example Program Results'
      Write (nout,*)
      Flush (nout)
!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) n, p
      lda = n
      Allocate (a(lda,n))
!     Read A from data file
      Read (nin,*)(a(i,1:n),i=1,n)

!     ifail: behaviour on error exit
!             =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
      ifail = 0

!     Find A^p
      Call f01fqf(n,a,lda,p,ifail)

!     Print solution
      If (ifail==0) Then
        ifail = 0
        Call x04daf('G','N',n,n,a,lda,'A^p',ifail)
      End If

    End Program f01fqfe


f01gafe.f90

    Program f01gafe

!     F01GAF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: f01gaf, nag_wp, x04caf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: t
      Integer                          :: i, ifail, lda, ldb, m, n
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: a(:,:), b(:,:)
!     .. Executable Statements ..
      Write (nout,*) 'F01GAF Example Program Results'
      Write (nout,*)
      Flush (nout)

!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) n, m, t

      lda = n
      ldb = n

      Allocate (a(lda,n))
      Allocate (b(ldb,m))

!     Read A from data file
      Read (nin,*)(a(i,1:n),i=1,n)

!     Read B from data file
      Read (nin,*)(b(i,1:m),i=1,n)

!     Find exp(tA)B
      ifail = 0
      Call f01gaf(n,m,a,lda,b,ldb,t,ifail)

      If (ifail==0) Then
!       Print solution
        ifail = 0
        Call x04caf('G','N',n,m,b,ldb,'exp(tA)B',ifail)
      End If

    End Program f01gafe


f01gbfe.f90

    Program f01gbfe

!     F01GBF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: dgemm, f01gbf, nag_wp, x04caf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: t, tr
      Integer                          :: i, ifail, irevcm, lda, ldb, ldb2,    &
                                          ldx, ldy, m, n
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: a(:,:), b(:,:), b2(:,:), comm(:),    &
                                          p(:), r(:), x(:,:), y(:,:), z(:)
      Integer, Allocatable             :: icomm(:)
!     .. Executable Statements ..
      Write (nout,*) 'F01GBF Example Program Results'
      Write (nout,*)
      Flush (nout)

!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) n, m, t

      lda = n
      ldb = n
      ldb2 = n
      ldx = n
      ldy = n

!     Allocate required memory
      Allocate (a(lda,n))
      Allocate (b(ldb,m))
      Allocate (b2(ldb2,m))
      Allocate (comm(n*m+3*n+12))
      Allocate (x(ldx,2))
      Allocate (y(ldy,2))
      Allocate (icomm(2*n+40))
      Allocate (p(n))
      Allocate (r(n))
      Allocate (z(n))

!     Read A from data file
      Read (nin,*)(a(i,1:n),i=1,n)

!     Read B from data file
      Read (nin,*)(b(i,1:m),i=1,n)

!     Compute the trace of A
      tr = 0.0_nag_wp
      Do i = 1, n
        tr = tr + a(i,i)
      End Do

!     Find exp(tA)B
      irevcm = 0
      ifail = 0

!      Initial call to f01gbf reverse communication interface
revcm: Do
        Call f01gbf(irevcm,n,m,b,ldb,t,tr,b2,ldb2,x,ldx,y,ldy,p,r,z,comm,      &
          icomm,ifail)
        If (irevcm==0) Then
          Exit revcm

        Else If (irevcm==1) Then
!         Compute AB and store in B2
          Call dgemm('N','N',n,m,n,1.0_nag_wp,a,lda,b,ldb,0.0_nag_wp,b2,ldb2)

        Else If (irevcm==2) Then
!         Compute AX and store in Y
          Call dgemm('N','N',n,2,n,1.0_nag_wp,a,lda,x,ldx,0.0_nag_wp,y,ldy)

        Else If (irevcm==3) Then
!         Compute A^T Y and store in X
          Call dgemm('T','N',n,2,n,1.0_nag_wp,a,lda,y,ldy,0.0_nag_wp,x,ldx)

        Else If (irevcm==4) Then
!         Compute AZ and store in P
          Call dgemm('N','N',n,1,n,1.0_nag_wp,a,lda,z,n,0.0_nag_wp,p,n)

        Else
!         Compute A^T Z and store in R
          Call dgemm('T','N',n,1,n,1.0_nag_wp,a,lda,z,n,0.0_nag_wp,r,n)
        End If

      End Do revcm

      If (ifail==0) Then
!       Print solution
        ifail = 0
        Call x04caf('G','N',n,m,b,ldb,'exp(tA)B',ifail)
      End If

    End Program f01gbfe


f01hafe.f90

    Program f01hafe

!     F01HAF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: f01haf, nag_wp, x04daf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Complex (Kind=nag_wp)            :: t
      Integer                          :: i, ifail, lda, ldb, m, n
!     .. Local Arrays ..
      Complex (Kind=nag_wp), Allocatable :: a(:,:), b(:,:)
!     .. Executable Statements ..
      Write (nout,*) 'F01HAF Example Program Results'
      Write (nout,*)
      Flush (nout)

!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) n, m, t

      lda = n
      ldb = n

      Allocate (a(lda,n))
      Allocate (b(ldb,m))

!     Read A from data file
      Read (nin,*)(a(i,1:n),i=1,n)

!     Read B from data file
      Read (nin,*)(b(i,1:m),i=1,n)

!     Find exp(tA)B
      ifail = 0
      Call f01haf(n,m,a,lda,b,ldb,t,ifail)

      If (ifail==0) Then
!       Print solution
        ifail = 0
        Call x04daf('G','N',n,m,b,ldb,'exp(tA)B',ifail)
      End If
    End Program f01hafe


f01hbfe.f90

    Program f01hbfe

!     F01HBF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: f01hbf, nag_wp, x04daf, zgemm
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Complex (Kind=nag_wp)            :: t, tr
      Integer                          :: i, ifail, irevcm, lda, ldb, ldb2,    &
                                          ldx, ldy, m, n
!     .. Local Arrays ..
      Complex (Kind=nag_wp), Allocatable :: a(:,:), b(:,:), b2(:,:), ccomm(:), &
                                          p(:), r(:), x(:,:), y(:,:), z(:)
      Real (Kind=nag_wp), Allocatable  :: comm(:)
      Integer, Allocatable             :: icomm(:)
!     .. Executable Statements ..
      Write (nout,*) 'F01HBF Example Program Results'
      Write (nout,*)
      Flush (nout)

!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) n, m, t

      lda = n
      ldb = n
      ldb2 = n
      ldx = n
      ldy = n

!     Allocate required space
      Allocate (a(lda,n))
      Allocate (b(ldb,m))
      Allocate (b2(ldb2,m))
      Allocate (ccomm(n*(m+2)))
      Allocate (x(ldx,2))
      Allocate (y(ldy,2))
      Allocate (icomm(2*n+40))
      Allocate (comm(14+3*n))
      Allocate (p(n))
      Allocate (r(n))
      Allocate (z(n))

!     Read A from data file
      Read (nin,*)(a(i,1:n),i=1,n)

!     Read B from data file
      Read (nin,*)(b(i,1:m),i=1,n)

!     Compute the trace of A
      tr = (0.0_nag_wp,0.0_nag_wp)
      Do i = 1, n
        tr = tr + a(i,i)
      End Do

!     Find exp(tA)B

      irevcm = 0
      ifail = 0

!      Initial call to reverse communication interface f01hbf
revcm: Do
        Call f01hbf(irevcm,n,m,b,ldb,t,tr,b2,ldb2,x,ldx,y,ldy,p,r,z,ccomm,     &
          comm,icomm,ifail)
        If (irevcm==0) Then
          Exit revcm

        Else If (irevcm==1) Then
!         Compute AB and store in B2
          Call zgemm('N','N',n,m,n,(1.0_nag_wp,0.0_nag_wp),a,lda,b,ldb,        &
            (0.0_nag_wp,0.0_nag_wp),b2,ldb2)

        Else If (irevcm==2) Then
!         Compute AX and store in Y
          Call zgemm('N','N',n,2,n,(1.0_nag_wp,0.0_nag_wp),a,lda,x,ldx,        &
            (0.0_nag_wp,0.0_nag_wp),y,ldy)

        Else If (irevcm==3) Then
!         Compute A^H Y and store in X
          Call zgemm('C','N',n,2,n,(1.0_nag_wp,0.0_nag_wp),a,lda,y,ldy,        &
            (0.0_nag_wp,0.0_nag_wp),x,ldx)

        Else If (irevcm==4) Then
!         Compute Az and store in p
          Call zgemm('N','N',n,1,n,(1.0_nag_wp,0.0_nag_wp),a,lda,z,n,          &
            (0.0_nag_wp,0.0_nag_wp),p,n)

        Else If (irevcm==5) Then
!         Compute A^H z and store in r
          Call zgemm('C','N',n,1,n,(1.0_nag_wp,0.0_nag_wp),a,lda,z,n,          &
            (0.0_nag_wp,0.0_nag_wp),r,n)
        End If

!       Return to f01hbf
      End Do revcm

      If (ifail==0) Then
!       Print solution
        ifail = 0
        Call x04daf('G','N',n,m,b,ldb,'exp(tA)B',ifail)
      End If

    End Program f01hbfe


f01jafe.f90

    Program f01jafe

!     F01JAF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: f01jaf, nag_wp, x02ajf, x04caf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: conda, cond_rel, eps, norma, normfa
      Integer                          :: i, ifail, lda, n
      Character (4)                    :: fun
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: a(:,:)
!     .. Executable Statements ..
      Write (nout,*) 'F01JAF Example Program Results'
      Write (nout,*)
      Flush (nout)

!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) n, fun

      lda = n
      Allocate (a(lda,n))

!     Read A from data file
      Read (nin,*)(a(i,1:n),i=1,n)

!     Display A
      ifail = 0
      Call x04caf('G','N',n,n,a,lda,'A',ifail)

!     Find absolute condition number estimate
      ifail = 0
      Call f01jaf(fun,n,a,lda,conda,norma,normfa,ifail)

      If (ifail==0) Then
!       Print solution
        Write (nout,*)
        Write (nout,*) 'F(A) = ', fun, '(A)'
        Write (nout,99999) 'Estimated absolute condition number is: ', conda

!       Find relative condition number estimate
        eps = x02ajf()
        If (normfa>eps) Then
          cond_rel = conda*norma/normfa
          Write (nout,99999) 'Estimated relative condition number is: ',       &
            cond_rel
        Else
          Write (nout,99998) 'The estimated norm of f(A) is effectively zero', &
            'and so the relative condition number is undefined.'
        End If
      End If

99999 Format (1X,A,F7.2)
99998 Format (/,1X,A,/,1X,A)

    End Program f01jafe


f01jbfe.f90

!   F01JBF Example Program Text
!   Mark 26 Release. NAG Copyright 2016.

    Module f01jbfe_mod

!     .. Use Statements ..
      Use nag_library, Only: nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Accessibility Statements ..
      Private
      Public                           :: fcos2
    Contains
      Subroutine fcos2(iflag,nz,z,fz,iuser,ruser)

!       .. Scalar Arguments ..
        Integer, Intent (Inout)        :: iflag
        Integer, Intent (In)           :: nz
!       .. Array Arguments ..
        Complex (Kind=nag_wp), Intent (Out) :: fz(nz)
        Complex (Kind=nag_wp), Intent (In) :: z(nz)
        Real (Kind=nag_wp), Intent (Inout) :: ruser(*)
        Integer, Intent (Inout)        :: iuser(*)
!       .. Intrinsic Procedures ..
        Intrinsic                      :: cos
!       .. Executable Statements ..
        Continue
        fz(1:nz) = cos((2.0E0_nag_wp,0.0E0_nag_wp)*z(1:nz))
!       Set iflag nonzero to terminate execution for any reason.
        iflag = 0
        Return
      End Subroutine fcos2
    End Module f01jbfe_mod
    Program f01jbfe

!     F01JBF Example Main Program

!     .. Use Statements ..
      Use nag_library, Only: f01jbf, nag_wp, x02ajf, x04caf
      Use f01jbfe_mod, Only: fcos2
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: conda, cond_rel, eps, norma, normfa
      Integer                          :: i, ifail, iflag, lda, n
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: a(:,:)
      Real (Kind=nag_wp)               :: ruser(1)
      Integer                          :: iuser(1)
!     .. Executable Statements ..
      Write (nout,*) 'F01JBF Example Program Results'
      Write (nout,*)
      Flush (nout)

!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) n

      lda = n
      Allocate (a(lda,n))

!     Read A from data file
      Read (nin,*)(a(i,1:n),i=1,n)

!     Display A
      ifail = 0
      Call x04caf('G','N',n,n,a,lda,'A',ifail)

!     Find absolute condition number estimate
      ifail = 0
      Call f01jbf(n,a,lda,fcos2,iuser,ruser,iflag,conda,norma,normfa,ifail)

      If (ifail==0) Then
!       Print solution
        Write (nout,*)
        Write (nout,*) 'F(A) = cos(2A)'
        Write (nout,99999) 'Estimated absolute condition number is: ', conda

!       Find relative condition number estimate
        eps = x02ajf()
        If (normfa>eps) Then
          cond_rel = conda*norma/normfa
          Write (nout,99999) 'Estimated relative condition number is: ',       &
            cond_rel
        Else
          Write (nout,99998) 'The estimated norm of f(A) is effectively zero', &
            'and so the relative condition number is undefined.'
        End If

      End If

99999 Format (1X,A,F6.2)
99998 Format (/,1X,A,/,1X,A)
    End Program f01jbfe


f01jcfe.f90

!   F01JCF Example Program Text
!   Mark 26 Release. NAG Copyright 2016.

    Module f01jcfe_mod

!     .. Use Statements ..
      Use nag_library, Only: nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Accessibility Statements ..
      Private
      Public                           :: fexp2
    Contains
      Subroutine fexp2(m,iflag,nz,z,fz,iuser,ruser)

!       .. Scalar Arguments ..
        Integer, Intent (Inout)        :: iflag
        Integer, Intent (In)           :: m, nz
!       .. Array Arguments ..
        Complex (Kind=nag_wp), Intent (Out) :: fz(nz)
        Complex (Kind=nag_wp), Intent (In) :: z(nz)
        Real (Kind=nag_wp), Intent (Inout) :: ruser(*)
        Integer, Intent (Inout)        :: iuser(*)
!       .. Intrinsic Procedures ..
        Intrinsic                      :: cmplx, exp
!       .. Executable Statements ..
        Continue
        fz(1:nz) = (cmplx(2.0E0_nag_wp,0.0_nag_wp,kind=nag_wp)**m)*            &
          exp((2.0E0_nag_wp,0.0E0_nag_wp)*z(1:nz))
!       Set iflag nonzero to terminate execution for any reason.
        iflag = 0
        Return
      End Subroutine fexp2
    End Module f01jcfe_mod
    Program f01jcfe

!     F01JCF Example Main Program

!     .. Use Statements ..
      Use nag_library, Only: f01jcf, nag_wp, x02ajf, x04caf
      Use f01jcfe_mod, Only: fexp2
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: conda, cond_rel, eps, norma, normfa
      Integer                          :: i, ifail, iflag, lda, n
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: a(:,:)
      Real (Kind=nag_wp)               :: ruser(1)
      Integer                          :: iuser(1)
!     .. Executable Statements ..
      Write (nout,*) 'F01JCF Example Program Results'
      Write (nout,*)
      Flush (nout)

!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) n

      lda = n
      Allocate (a(lda,n))

!     Read A from data file
      Read (nin,*)(a(i,1:n),i=1,n)

!     Display A
      ifail = 0
      Call x04caf('G','N',n,n,a,lda,'A',ifail)

!     Find absolute condition number estimate
      ifail = 0
      Call f01jcf(n,a,lda,fexp2,iuser,ruser,iflag,conda,norma,normfa,ifail)

      If (ifail==0) Then
!       Print solution
        Write (nout,*)
        Write (nout,*) 'F(A) = exp(2A)'
        Write (nout,99999) 'Estimated absolute condition number is: ', conda

!       Find relative condition number estimate
        eps = x02ajf()
        If (normfa>eps) Then
          cond_rel = conda*norma/normfa
          Write (nout,99999) 'Estimated relative condition number is: ',       &
            cond_rel
        Else
          Write (nout,99998) 'The estimated norm of f(A) is effectively zero', &
            'and so the relative condition number is undefined.'
        End If

      End If

99999 Format (1X,A,F7.2)
99998 Format (/,1X,A,/,1X,A)
    End Program f01jcfe


f01jdfe.f90

    Program f01jdfe

!     F01JDF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: f01jdf, nag_wp, x04caf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: alpha, condsa
      Integer                          :: i, ifail, lda, n
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: a(:,:)
!     .. Executable Statements ..
      Write (nout,*) 'F01JDF Example Program Results'
      Write (nout,*)
!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) n

      lda = n
      Allocate (a(lda,n))

!     Read A from data file
      Read (nin,*)(a(i,1:n),i=1,n)

!     ifail: behaviour on error exit
!             =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
      ifail = 0

!     Find sqrt(A)
      Call f01jdf(n,a,lda,alpha,condsa,ifail)

!     Print solution
      ifail = 0
      Call x04caf('G','N',n,n,a,lda,'sqrt(A)',ifail)

      Write (nout,*)
      Write (nout,99999) 'Estimated relative condition number is: ', condsa
      Write (nout,99999) 'Condition number for the relative residual is: ',    &
        alpha

99999 Format (1X,A,F6.2)

    End Program f01jdfe


f01jefe.f90

    Program f01jefe

!     F01JEF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: f01jef, nag_wp, x04caf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: condpa, p
      Integer                          :: i, ifail, lda, n
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: a(:,:)
!     .. Executable Statements ..
      Write (nout,*) 'F01JEF Example Program Results'
      Write (nout,*)
      Flush (nout)
!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) n, p
      lda = n
      Allocate (a(lda,n))
!     Read A from data file
      Read (nin,*)(a(i,1:n),i=1,n)

!     ifail: behaviour on error exit
!             =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
      ifail = 0

!     Find A^p
      Call f01jef(n,a,lda,p,condpa,ifail)

!     Print solution
      Call x04caf('General',' ',n,n,a,lda,'A^p',ifail)

      Write (nout,*)
      Write (nout,99999) 'Estimated condition number is: ', condpa
99999 Format (1X,A,F6.2)
    End Program f01jefe


f01jffe.f90

    Program f01jffe

!     F01JFF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: f01jff, nag_wp, x04caf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: p
      Integer                          :: i, ifail, lda, lde, n
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: a(:,:), e(:,:)
!     .. Executable Statements ..
      Write (nout,*) 'F01JFF Example Program Results'
      Write (nout,*)
      Flush (nout)
!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) n, p
      lda = n
      lde = n
      Allocate (a(lda,n))
      Allocate (e(lde,n))
!     Read A from data file
      Read (nin,*)(a(i,1:n),i=1,n)
!     Read E from data file
      Read (nin,*)(e(i,1:n),i=1,n)

!     ifail: behaviour on error exit
!             =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
      ifail = 0

!     Find A^p and L_p(A,E)
      Call f01jff(n,a,lda,e,lde,p,ifail)

!     Print solution
      Call x04caf('General',' ',n,n,a,lda,'A^p',ifail)
      Write (nout,*)
      Call x04caf('General',' ',n,n,e,lde,'L_p(A,E)',ifail)

    End Program f01jffe


f01jgfe.f90

    Program f01jgfe

!     F01JGF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: f01jgf, nag_wp, x04caf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: condea
      Integer                          :: i, ifail, lda, n
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: a(:,:)
!     .. Executable Statements ..
      Write (nout,*) 'F01JGF Example Program Results'
      Write (nout,*)
      Flush (nout)
!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) n
      lda = n
      Allocate (a(lda,n))
!     Read A from data file
      Read (nin,*)(a(i,1:n),i=1,n)

!     ifail: behaviour on error exit
!             =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
      ifail = 0
!     Find exp( A ) and the condition estimate
      Call f01jgf(n,a,lda,condea,ifail)

!     Print solution
      Call x04caf('General',' ',n,n,a,lda,'Exp(A)',ifail)

      Write (nout,*)
      Write (nout,99999) 'Estimated condition number is: ', condea
99999 Format (1X,A,F6.2)
    End Program f01jgfe


f01jhfe.f90

    Program f01jhfe

!     F01JHF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: f01jhf, nag_wp, x04caf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Integer                          :: i, ifail, lda, lde, n
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: a(:,:), e(:,:)
!     .. Executable Statements ..
      Write (nout,*) 'F01JHF Example Program Results'
      Write (nout,*)
      Flush (nout)
!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) n
      lda = n
      lde = n
      Allocate (a(lda,n))
      Allocate (e(lde,n))
!     Read A from data file
      Read (nin,*)(a(i,1:n),i=1,n)
!     Read E from data file
      Read (nin,*)(e(i,1:n),i=1,n)

!     ifail: behaviour on error exit
!             =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
      ifail = 0

!     Find exp( A ) and L_exp(A,E)
      Call f01jhf(n,a,lda,e,lde,ifail)

!     Print solution
      Call x04caf('General',' ',n,n,a,lda,'Exp(A)',ifail)
      Write (nout,*)
      Call x04caf('General',' ',n,n,e,lde,'L_exp(A,E)',ifail)

    End Program f01jhfe


f01jjfe.f90

    Program f01jjfe

!     F01JJF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: f01jjf, nag_wp, x04caf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: condla
      Integer                          :: i, ifail, lda, n
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: a(:,:)
!     .. Executable Statements ..
      Write (nout,*) 'F01JJF Example Program Results'
      Write (nout,*)
!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) n

      lda = n
      Allocate (a(lda,n))

!     Read A from data file
      Read (nin,*)(a(i,1:n),i=1,n)

!     ifail: behaviour on error exit
!             =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
      ifail = 0

!     Find log( A )
      Call f01jjf(n,a,lda,condla,ifail)

!     Print solution
      ifail = 0
      Call x04caf('G','N',n,n,a,lda,'log(A)',ifail)

      Write (nout,*)
      Write (nout,99999) 'Estimated condition number is: ', condla
99999 Format (1X,A,F6.2)
    End Program f01jjfe


f01jkfe.f90

    Program f01jkfe

!     F01JKF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: f01jkf, nag_wp, x04caf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Integer                          :: i, ifail, lda, lde, n
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: a(:,:), e(:,:)
!     .. Executable Statements ..
      Write (nout,*) 'F01JKF Example Program Results'
      Write (nout,*)
      Flush (nout)
!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) n
      lda = n
      lde = n
      Allocate (a(lda,n))
      Allocate (e(lde,n))
!     Read A from data file
      Read (nin,*)(a(i,1:n),i=1,n)
!     Read E from data file
      Read (nin,*)(e(i,1:n),i=1,n)

!     ifail: behaviour on error exit
!             =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
      ifail = 0

!     Find log( A ) and L_log(A,E)
      Call f01jkf(n,a,lda,e,lde,ifail)

!     Print solution
      Call x04caf('General',' ',n,n,a,lda,'Log(A)',ifail)
      Write (nout,*)
      Call x04caf('General',' ',n,n,e,lde,'L_log(A,E)',ifail)

    End Program f01jkfe


f01kafe.f90

    Program f01kafe

!     F01KAF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: f01kaf, nag_wp, x02ajf, x04daf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: conda, cond_rel, eps, norma, normfa
      Integer                          :: i, ifail, lda, n
      Character (4)                    :: fun
!     .. Local Arrays ..
      Complex (Kind=nag_wp), Allocatable :: a(:,:)
!     .. Executable Statements ..
      Write (nout,*) 'F01KAF Example Program Results'
      Write (nout,*)
      Flush (nout)

!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) n, fun

      lda = n
      Allocate (a(lda,n))

!     Read A from data file
      Read (nin,*)(a(i,1:n),i=1,n)

!     Display A
      ifail = 0
      Call x04daf('G','N',n,n,a,lda,'A',ifail)

!     Find absolute condition number estimate
      ifail = 0
      Call f01kaf(fun,n,a,lda,conda,norma,normfa,ifail)

      If (ifail==0) Then
!       Print solution
        Write (nout,*)
        Write (nout,*) 'F(A) = ', fun, '(A)'
        Write (nout,99999) 'Estimated absolute condition number is: ', conda

!       Find relative condition number estimate
        eps = x02ajf()
        If (normfa>eps) Then
          cond_rel = conda*norma/normfa
          Write (nout,99999) 'Estimated relative condition number is: ',       &
            cond_rel
        Else
          Write (nout,99998) 'The estimated norm of f(A) is effectively zero', &
            'and so the relative condition number is undefined.'
        End If
      End If

99999 Format (1X,A,F6.2)
99998 Format (/,1X,A,/,1X,A)

    End Program f01kafe


f01kbfe.f90

!   F01KBF Example Program Text
!   Mark 26 Release. NAG Copyright 2016.

    Module f01kbfe_mod

!     .. Use Statements ..
      Use nag_library, Only: nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Accessibility Statements ..
      Private
      Public                           :: fsin2
    Contains
      Subroutine fsin2(iflag,nz,z,fz,iuser,ruser)

!       .. Scalar Arguments ..
        Integer, Intent (Inout)        :: iflag
        Integer, Intent (In)           :: nz
!       .. Array Arguments ..
        Complex (Kind=nag_wp), Intent (Out) :: fz(nz)
        Complex (Kind=nag_wp), Intent (In) :: z(nz)
        Real (Kind=nag_wp), Intent (Inout) :: ruser(*)
        Integer, Intent (Inout)        :: iuser(*)
!       .. Intrinsic Procedures ..
        Intrinsic                      :: sin
!       .. Executable Statements ..
        Continue
        fz(1:nz) = sin((2.0E0_nag_wp,0.0E0_nag_wp)*z(1:nz))
!       Set iflag nonzero to terminate execution for any reason.
        iflag = 0
        Return
      End Subroutine fsin2
    End Module f01kbfe_mod
    Program f01kbfe

!     F01KBF Example Main Program

!     .. Use Statements ..
      Use nag_library, Only: f01kbf, nag_wp, x02ajf, x04daf
      Use f01kbfe_mod, Only: fsin2
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: conda, cond_rel, eps, norma, normfa
      Integer                          :: i, ifail, iflag, lda, n
!     .. Local Arrays ..
      Complex (Kind=nag_wp), Allocatable :: a(:,:)
      Real (Kind=nag_wp)               :: ruser(1)
      Integer                          :: iuser(1)
!     .. Executable Statements ..
      Write (nout,*) 'F01KBF Example Program Results'
      Write (nout,*)
      Flush (nout)

!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) n

      lda = n
      Allocate (a(lda,n))

!     Read A from data file
      Read (nin,*)(a(i,1:n),i=1,n)

!     Display A
      ifail = 0
      Call x04daf('G','N',n,n,a,lda,'A',ifail)

!     Find absolute condition number estimate
      ifail = 0
      Call f01kbf(n,a,lda,fsin2,iuser,ruser,iflag,conda,norma,normfa,ifail)

      If (ifail==0) Then
!       Print solution
        Write (nout,*)
        Write (nout,*) 'F(A) = sin(2A)'
        Write (nout,99999) 'Estimated absolute condition number is: ', conda

!       Find relative condition number estimate
        eps = x02ajf()
        If (normfa>eps) Then
          cond_rel = conda*norma/normfa
          Write (nout,99999) 'Estimated relative condition number is: ',       &
            cond_rel
        Else
          Write (nout,99998) 'The estimated norm of f(A) is effectively zero', &
            'and so the relative condition number is undefined.'
        End If

      End If

99999 Format (1X,A,F7.2)
99998 Format (/,1X,A,/,1X,A)
    End Program f01kbfe


f01kcfe.f90

!   F01KCF Example Program Text
!   Mark 26 Release. NAG Copyright 2016.

    Module f01kcfe_mod

!     .. Use Statements ..
      Use nag_library, Only: nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Accessibility Statements ..
      Private
      Public                           :: fexp3
    Contains
      Subroutine fexp3(m,iflag,nz,z,fz,iuser,ruser)

!       .. Scalar Arguments ..
        Integer, Intent (Inout)        :: iflag
        Integer, Intent (In)           :: m, nz
!       .. Array Arguments ..
        Complex (Kind=nag_wp), Intent (Out) :: fz(nz)
        Complex (Kind=nag_wp), Intent (In) :: z(nz)
        Real (Kind=nag_wp), Intent (Inout) :: ruser(*)
        Integer, Intent (Inout)        :: iuser(*)
!       .. Intrinsic Procedures ..
        Intrinsic                      :: cmplx, exp
!       .. Executable Statements ..
        Continue
        fz(1:nz) = (cmplx(3.0E0_nag_wp,0.0_nag_wp,kind=nag_wp)**m)*            &
          exp((3.0E0_nag_wp,0.0E0_nag_wp)*z(1:nz))
!       Set iflag nonzero to terminate execution for any reason.
        iflag = 0
        Return
      End Subroutine fexp3
    End Module f01kcfe_mod
    Program f01kcfe

!     F01KCF Example Main Program

!     .. Use Statements ..
      Use nag_library, Only: f01kcf, nag_wp, x02ajf, x04daf
      Use f01kcfe_mod, Only: fexp3
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: conda, cond_rel, eps, norma, normfa
      Integer                          :: i, ifail, iflag, lda, n
!     .. Local Arrays ..
      Complex (Kind=nag_wp), Allocatable :: a(:,:)
      Real (Kind=nag_wp)               :: ruser(1)
      Integer                          :: iuser(1)
!     .. Executable Statements ..
      Write (nout,*) 'F01KCF Example Program Results'
      Write (nout,*)
      Flush (nout)

!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) n

      lda = n
      Allocate (a(lda,n))

!     Read A from data file
      Read (nin,*)(a(i,1:n),i=1,n)

!     Display A
      ifail = 0
      Call x04daf('G','N',n,n,a,lda,'A',ifail)

!     Find absolute condition number estimate
      ifail = 0
      Call f01kcf(n,a,lda,fexp3,iuser,ruser,iflag,conda,norma,normfa,ifail)

      If (ifail==0) Then
!       Print solution
        Write (nout,*)
        Write (nout,*) 'F(A) = exp(3A)'
        Write (nout,99999) 'Estimated absolute condition number is: ', conda

!       Find relative condition number estimate
        eps = x02ajf()
        If (normfa>eps) Then
          cond_rel = conda*norma/normfa
          Write (nout,99999) 'Estimated relative condition number is: ',       &
            cond_rel
        Else
          Write (nout,99998) 'The estimated norm of f(A) is effectively zero', &
            'and so the relative condition number is undefined.'
        End If

      End If

99999 Format (1X,A,F7.2)
99998 Format (/,1X,A,/,1X,A)
    End Program f01kcfe


f01kdfe.f90

    Program f01kdfe

!     F01KDF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: f01kdf, nag_wp, x04daf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: alpha, condsa
      Integer                          :: i, ifail, lda, n
!     .. Local Arrays ..
      Complex (Kind=nag_wp), Allocatable :: a(:,:)
!     .. Executable Statements ..
      Write (nout,*) 'F01KDF Example Program Results'
      Write (nout,*)
!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) n

      lda = n
      Allocate (a(lda,n))

!     Read A from data file
      Read (nin,*)(a(i,1:n),i=1,n)

!     ifail: behaviour on error exit
!             =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
      ifail = 0

!     Find sqrt(A)
      Call f01kdf(n,a,lda,alpha,condsa,ifail)

!     Print solution
      ifail = 0
      Call x04daf('G','N',n,n,a,lda,'sqrt(A)',ifail)

      Write (nout,*)
      Write (nout,99999) 'Estimated relative condition number is: ', condsa
      Write (nout,99999) 'Condition number for the relative residual is: ',    &
        alpha

99999 Format (1X,A,F6.2)

    End Program f01kdfe


f01kefe.f90

    Program f01kefe

!     F01KEF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: f01kef, nag_wp, x04daf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: condpa, p
      Integer                          :: i, ifail, lda, n
!     .. Local Arrays ..
      Complex (Kind=nag_wp), Allocatable :: a(:,:)
!     .. Executable Statements ..
      Write (nout,*) 'F01KEF Example Program Results'
      Write (nout,*)
      Flush (nout)
!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) n, p
      lda = n
      Allocate (a(lda,n))
!     Read A from data file
      Read (nin,*)(a(i,1:n),i=1,n)

!     ifail: behaviour on error exit
!             =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
      ifail = 0

!     Find A^p
      Call f01kef(n,a,lda,p,condpa,ifail)

!     Print solution
      Call x04daf('General',' ',n,n,a,lda,'A^p',ifail)

      Write (nout,*)
      Write (nout,99999) 'Estimated condition number is: ', condpa
99999 Format (1X,A,F6.2)
    End Program f01kefe


f01kffe.f90

    Program f01kffe

!     F01KFF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: f01kff, nag_wp, x04daf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: p
      Integer                          :: i, ifail, lda, lde, n
!     .. Local Arrays ..
      Complex (Kind=nag_wp), Allocatable :: a(:,:), e(:,:)
!     .. Executable Statements ..
      Write (nout,*) 'F01KFF Example Program Results'
      Write (nout,*)
      Flush (nout)
!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) n, p
      lda = n
      lde = n
      Allocate (a(lda,n))
      Allocate (e(lde,n))
!     Read A from data file
      Read (nin,*)(a(i,1:n),i=1,n)
!     Read E from data file
      Read (nin,*)(e(i,1:n),i=1,n)

!     ifail: behaviour on error exit
!             =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
      ifail = 0

!     Find A^p and L_p(A,E)
      Call f01kff(n,a,lda,e,lde,p,ifail)

!     Print solution
      Call x04daf('General',' ',n,n,a,lda,'A^p',ifail)
      Write (nout,*)
      Call x04daf('General',' ',n,n,e,lde,'L_p(A,E)',ifail)

    End Program f01kffe


f01kgfe.f90

    Program f01kgfe

!     F01KGF Example Program Text
!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: f01kgf, nag_wp, x04daf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: condea
      Integer                          :: i, ierr, ifail, lda, n
!     .. Local Arrays ..
      Complex (Kind=nag_wp), Allocatable :: a(:,:)
!     .. Executable Statements ..
      Write (nout,*) 'F01KGF Example Program Results'
      Write (nout,*)
      Flush (nout)
!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) n

      lda = n
      Allocate (a(lda,n))

!     Read A from data file

      Read (nin,*)(a(i,1:n),i=1,n)

!     Find exp( A ) and the condition estimate

      ifail = 0
      Call f01kgf(n,a,lda,condea,ifail)

!     Print solution

      ierr = 0
      Call x04daf('General',' ',n,n,a,lda,'Exp(A)',ierr)

      Write (nout,*)
      Write (nout,99999) 'Estimated condition number is: ', condea
99999 Format (1X,A,F6.2)
    End Program f01kgfe


f01khfe.f90

    Program f01khfe

!     F01KHF Example Program Text
!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: f01khf, nag_wp, x04daf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Integer                          :: i, ierr, ifail, lda, lde, n
!     .. Local Arrays ..
      Complex (Kind=nag_wp), Allocatable :: a(:,:), e(:,:)
!     .. Executable Statements ..
      Write (nout,*) 'F01KHF Example Program Results'
      Write (nout,*)
      Flush (nout)
!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) n

      lda = n
      lde = n
      Allocate (a(lda,n))
      Allocate (e(lde,n))

!     Read A from data file

      Read (nin,*)(a(i,1:n),i=1,n)

!     Read E from data file

      Read (nin,*)(e(i,1:n),i=1,n)

!     ifail: behaviour on error exit
!             =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
      ifail = 0

!     Find exp( A ) and L_exp(A,E)
      Call f01khf(n,a,lda,e,lde,ifail)

!     Print solution

      ierr = 0
      Call x04daf('General',' ',n,n,a,lda,'Exp(A)',ierr)
      Write (nout,*)
      Call x04daf('General',' ',n,n,e,lde,'L_exp(A,E)',ierr)

    End Program f01khfe


f01kjfe.f90

    Program f01kjfe

!     F01KJF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: f01kjf, nag_wp, x04daf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: condla
      Integer                          :: i, ifail, lda, n
!     .. Local Arrays ..
      Complex (Kind=nag_wp), Allocatable :: a(:,:)
!     .. Executable Statements ..
      Write (nout,*) 'F01KJF Example Program Results'
      Write (nout,*)
!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) n

      lda = n
      Allocate (a(lda,n))

!     Read A from data file
      Read (nin,*)(a(i,1:n),i=1,n)

!     ifail: behaviour on error exit
!             =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
      ifail = 0

!     Find log( A )
      Call f01kjf(n,a,lda,condla,ifail)

!     Print solution
      ifail = 0
      Call x04daf('G','N',n,n,a,lda,'log(A)',ifail)

      Write (nout,*)
      Write (nout,99999) 'Estimated condition number is: ', condla
99999 Format (1X,A,F6.2)
    End Program f01kjfe


f01kkfe.f90

    Program f01kkfe

!     F01KKF Example Program Text
!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: f01kkf, nag_wp, x04daf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Integer                          :: i, ierr, ifail, lda, lde, n
!     .. Local Arrays ..
      Complex (Kind=nag_wp), Allocatable :: a(:,:), e(:,:)
!     .. Executable Statements ..
      Write (nout,*) 'F01KKF Example Program Results'
      Write (nout,*)
      Flush (nout)
!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) n

      lda = n
      lde = n
      Allocate (a(lda,n))
      Allocate (e(lde,n))

!     Read A from data file

      Read (nin,*)(a(i,1:n),i=1,n)

!     Read E from data file

      Read (nin,*)(e(i,1:n),i=1,n)

!     ifail: behaviour on error exit
!             =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
      ifail = 0

!     Find log( A ) and L_log(A,E)
      Call f01kkf(n,a,lda,e,lde,ifail)

!     Print solution

      ierr = 0
      Call x04daf('General',' ',n,n,a,lda,'Log(A)',ierr)
      Write (nout,*)
      Call x04daf('General',' ',n,n,e,lde,'L_log(A,E)',ierr)

    End Program f01kkfe


f01lefe.f90

    Program f01lefe

!     F01LEF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: f01lef, f04lef, nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: lambda, tol
      Integer                          :: ifail, job, n
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: a(:), b(:), c(:), d(:), y(:)
      Integer, Allocatable             :: ipiv(:)
!     .. Executable Statements ..
      Write (nout,*) 'F01LEF Example Program Results'
      Write (nout,*)
!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) n
      Allocate (a(n),b(n),c(n),d(n),y(n),ipiv(n))
      Read (nin,*) a(1:n)
      Read (nin,*) b(2:n)
      Read (nin,*) c(2:n)
      tol = 0.00005E0_nag_wp
      lambda = 0.0E0_nag_wp

!     ifail: behaviour on error exit
!             =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
      ifail = 0
      Call f01lef(n,a,lambda,b,c,tol,d,ipiv,ifail)

      If (ipiv(n)/=0) Then
        Write (nout,*) 'Matrix is singular or nearly singular'
        Write (nout,99999) 'Diagonal element', ipiv(n), 'is small'
      Else
        Write (nout,*) 'Details of factorization'
        Write (nout,*)
        Write (nout,*) ' Main diagonal of U'
        Write (nout,99998) a(1:n)
        Write (nout,*)
        Write (nout,*) ' First superdiagonal of U'
        Write (nout,99998) b(2:n)
        Write (nout,*)
        Write (nout,*) ' Second superdiagonal of U'
        Write (nout,99998) d(3:n)
        Write (nout,*)
        Write (nout,*) ' Multipliers'
        Write (nout,99998) c(2:n)
        Write (nout,*)
        Write (nout,*) ' Vector of interchanges'
        Write (nout,99997) ipiv(1:(n-1))

        Read (nin,*) y(1:n)
        job = 1

        ifail = 0
        Call f04lef(job,n,a,b,c,d,ipiv,y,tol,ifail)

        Write (nout,*)
        Write (nout,*) ' Solution vector'
        Write (nout,99998) y(1:n)
      End If

99999 Format (1X,A,I4,A)
99998 Format (1X,8F9.4)
99997 Format (1X,5I9)
    End Program f01lefe


f01lhfe.f90

    Program f01lhfe

!     F01LHF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: f01lhf, f04lhf, nag_wp, x04caf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: lena = 200, nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: tol
      Integer                          :: i, ifail, ir, j, k, kpivot, ldb, n,  &
                                          nbasek, nbloks
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: a(:), b(:,:)
      Integer, Allocatable             :: blkstr(:,:), pivot(:)
!     .. Executable Statements ..
      Write (nout,*) 'F01LHF Example Program Results'
      Write (nout,*)
      Flush (nout)
!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) nbloks
      Allocate (a(lena),blkstr(3,nbloks))
      nbasek = 0
      n = 0
      Do i = 1, nbloks
        Read (nin,*) blkstr(1:3,i)
        If (nbasek+blkstr(2,i)*blkstr(1,i)>lena) Then
          Write (nout,*) ' Array A is too small for this problem'
          Go To 100
        Else
          Do k = 1, blkstr(1,i)
            Read (nin,*)(a(nbasek+(j-1)*blkstr(1,i)+k),j=1,blkstr(2,i))
          End Do
        End If
        nbasek = nbasek + blkstr(2,i)*blkstr(1,i)
        n = n + blkstr(1,i)
      End Do
      ldb = n
      Read (nin,*) ir
      Allocate (b(ldb,ir),pivot(n))
      tol = 0.0E0_nag_wp

!     ifail: behaviour on error exit
!            =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
      ifail = 0
      Call f01lhf(n,nbloks,blkstr,a,lena,pivot,tol,kpivot,ifail)

      Read (nin,*)(b(1:n,j),j=1,ir)

      ifail = 0
      Call f04lhf('N',n,nbloks,blkstr,a,lena,pivot,b,ldb,ir,ifail)

      Call x04caf('G','X',n,ir,b,ldb,'Component Solution',ifail)
100   Continue

    End Program f01lhfe


f01mcfe.f90

    Program f01mcfe

!     F01MCF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: f01mcf, nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Integer                          :: i, ifail, k1, k2, lal, n
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: a(:), al(:), d(:)
      Integer, Allocatable             :: nrow(:)
!     .. Executable Statements ..
      Write (nout,*) 'F01MCF Example Program Results'
!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) n
      Allocate (d(n),nrow(n))
      Read (nin,*) nrow(1:n)
      lal = 0
      Do i = 1, n
        lal = lal + nrow(i)
      End Do
      Allocate (a(lal),al(lal))
      k2 = 0
      Do i = 1, n
        k1 = k2 + 1
        k2 = k2 + nrow(i)
        Read (nin,*) a(k1:k2)
      End Do

!     ifail: behaviour on error exit
!            =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
      ifail = 0
      Call f01mcf(n,a,lal,nrow,al,d,ifail)

      Write (nout,*)
      Write (nout,*) '  I    D(I)   Row I of unit lower triangle'
      Write (nout,*)
      k2 = 0
      Do i = 1, n
        k1 = k2 + 1
        k2 = k2 + nrow(i)
        Write (nout,99999) i, d(i), al(k1:k2)
      End Do

99999 Format (1X,I3,7F8.3)
    End Program f01mcfe


f01qgfe.f90

    Program f01qgfe

!     F01QGF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: f01qgf, nag_wp, x04cbf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: indent = 0, ncols = 80, nin = 5,     &
                                          nout = 6
      Character (1), Parameter         :: diag = 'N', matrix = 'G',            &
                                          nolabel = 'N'
      Character (4), Parameter         :: form = 'F8.4'
!     .. Local Scalars ..
      Integer                          :: i, ifail, lda, m, n
      Character (63)                   :: title
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: a(:,:), zeta(:)
      Character (1)                    :: dummy(1)
!     .. Executable Statements ..
      Write (nout,*) 'F01QGF Example Program Results'
      Write (nout,*)
!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) m, n
      lda = m
      Allocate (a(lda,n),zeta(m))
      Read (nin,*)(a(i,1:n),i=1,m)

!     ifail: behaviour on error exit
!             =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
      ifail = 0
!     Find the RQ factorization of A
      Call f01qgf(m,n,a,lda,zeta,ifail)

      Write (nout,*) 'RQ factorization of A'
      Write (nout,*)
      Write (nout,*) 'Vector ZETA'
      Write (nout,99999) zeta(1:m)
      Write (nout,*)
      Flush (nout)
      title =                                                                  &
        'Matrix A after factorization (R is in left-hand upper triangle)'
      ifail = 0
      Call x04cbf(matrix,diag,m,n,a,lda,form,title,nolabel,dummy,nolabel,      &
        dummy,ncols,indent,ifail)

99999 Format (5(1X,F8.4))
    End Program f01qgfe


f01qjfe.f90

    Program f01qjfe

!     F01QJF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: f01qjf, nag_wp, x04cbf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Integer                          :: i, ifail, lda, m, n
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: a(:,:), zeta(:)
      Character (1)                    :: dummy(1)
!     .. Executable Statements ..
      Write (nout,*) 'F01QJF Example Program Results'
      Write (nout,*)
!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) m, n
      lda = n
      Allocate (a(lda,n),zeta(m))
      Read (nin,*)(a(i,1:n),i=1,m)

!     ifail: behaviour on error exit
!             =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
      ifail = 0
!     Find the RQ factorization of A
      Call f01qjf(m,n,a,lda,zeta,ifail)

      Write (nout,*) 'RQ factorization of A'
      Write (nout,*)
      Write (nout,*) 'Vector ZETA'
      Write (nout,99999) zeta(1:m)
      Write (nout,*)
      Flush (nout)
      Call x04cbf('G',' ',m,n,a,lda,'F8.4',                                    &
        'Matrix A after factorization (R is in left-hand upper triangle)','N', &
        dummy,'N',dummy,80,0,ifail)

99999 Format (5(1X,F8.4))
    End Program f01qjfe


f01qkfe.f90

    Program f01qkfe

!     F01QKF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: f01qjf, f01qkf, nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Integer                          :: i, ifail, lda, ldpt, m, n, nrowp
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: a(:,:), pt(:,:), work(:), zeta(:)
!     .. Executable Statements ..
      Write (nout,*) 'F01QKF Example Program Results'
      Write (nout,*)
!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) m, n
      lda = m
      ldpt = n
      Allocate (a(lda,n),pt(ldpt,n),work(n),zeta(n))
      Read (nin,*)(a(i,1:n),i=1,m)

!     ifail: behaviour on error exit
!             =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
      ifail = 0
!     Find the RQ factorization of A
      Call f01qjf(m,n,a,lda,zeta,ifail)

!     Copy array A into PT and form the n by n matrix conjg(P')
      pt(1:m,1:n) = a(1:m,1:n)
      nrowp = n

      ifail = 0
      Call f01qkf('Separate',m,n,nrowp,pt,ldpt,zeta,work,ifail)

      Write (nout,*) 'Matrix  P'
      Write (nout,99999) pt(1:nrowp,1:n)

99999 Format (5(1X,F8.4))
    End Program f01qkfe


f01rgfe.f90

    Program f01rgfe

!     F01RGF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: f01rgf, nag_wp, x04dbf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Integer                          :: i, ifail, lda, m, n
!     .. Local Arrays ..
      Complex (Kind=nag_wp), Allocatable :: a(:,:), theta(:)
      Character (1)                    :: dummy(1)
!     .. Executable Statements ..
      Write (nout,*) 'F01RGF Example Program Results'
!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) m, n
      Write (nout,*)
      lda = m
      Allocate (a(lda,n),theta(m))
      Read (nin,*)(a(i,1:n),i=1,m)

!     ifail: behaviour on error exit
!             =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
      ifail = 0
!     Find the RQ factorization of A
      Call f01rgf(m,n,a,lda,theta,ifail)

      Write (nout,*)
      Write (nout,*) 'RQ factorization of A'
      Write (nout,*)
      Write (nout,*) 'Vector THETA'
      Write (nout,99999) theta(1:m)
      Write (nout,*)
      Flush (nout)

      Call x04dbf('G',' ',m,n,a,lda,'B','F7.4',                                &
        'Matrix A after factorization (R is in left-hand upper triangle)','N', &
        dummy,'N',dummy,80,0,ifail)

99999 Format (1X,4(' (',F7.4,',',F8.4,')',:))
    End Program f01rgfe


f01rjfe.f90

    Program f01rjfe

!     F01RJF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: f01rjf, nag_wp, x04dbf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Integer                          :: i, ifail, lda, m, n
!     .. Local Arrays ..
      Complex (Kind=nag_wp), Allocatable :: a(:,:), theta(:)
      Character (1)                    :: dummy(1)
!     .. Executable Statements ..
      Write (nout,*) 'F01RJF Example Program Results'
!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) m, n
      Write (nout,*)
      lda = m
      Allocate (a(lda,n),theta(m))
      Read (nin,*)(a(i,1:n),i=1,m)

!     ifail: behaviour on error exit
!             =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
      ifail = 0
!     Find the RQ factorization of A
      Call f01rjf(m,n,a,lda,theta,ifail)

      Write (nout,*) 'RQ factorization of A'
      Write (nout,*)
      Write (nout,*) 'Vector THETA'
      Write (nout,99999) theta(1:m)
      Write (nout,*)
      Flush (nout)

      Call x04dbf('G',' ',m,n,a,lda,'B','F6.3',                                &
        'Matrix A after factorization (R is in left-hand upper triangle)','N', &
        dummy,'N',dummy,132,0,ifail)

99999 Format (5(' (',F6.3,',',F6.3,')',:))
    End Program f01rjfe


f01rkfe.f90

    Program f01rkfe

!     F01RKF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: f01rjf, f01rkf, nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Integer                          :: i, ifail, lda, ldph, m, n, nrowp
!     .. Local Arrays ..
      Complex (Kind=nag_wp), Allocatable :: a(:,:), ph(:,:), theta(:), work(:)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: conjg
!     .. Executable Statements ..
      Write (nout,*) 'F01RKF Example Program Results'
      Write (nout,*)
!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) m, n
      lda = m
      ldph = n
      Allocate (a(lda,n),ph(ldph,n),theta(n),work(n))
      Read (nin,*)(a(i,1:n),i=1,m)
!     ifail: behaviour on error exit
!             =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
      ifail = 0
!     Find the RQ factorization of A
      Call f01rjf(m,n,a,lda,theta,ifail)

!     Copy array A into PH and form the n by n matrix conjg(P')
      ph(1:m,1:n) = a(1:m,1:n)
      nrowp = n

      ifail = 0
      Call f01rkf('Separate',m,n,nrowp,ph,ldph,theta,work,ifail)

      Write (nout,*) 'Matrix  P'
      Write (nout,99999)(conjg(ph(1:nrowp,i)),i=1,n)

99999 Format (5(' (',F6.3,',',F6.3,')',:))
    End Program f01rkfe


f01vafe.f90

    Program f01vafe

!     F01VAF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: dtrttp, nag_wp, x04cbf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: inc1 = 1, indent = 0, ncols = 80,    &
                                          nin = 5, nout = 6
      Character (1), Parameter         :: diag = 'N', intlabel = 'I',          &
                                          matrix = 'G', nolabel = 'N'
      Character (4), Parameter         :: form = 'F5.2'
!     .. Local Scalars ..
      Integer                          :: i, ifail, info, lda, lenap, n
      Character (18)                   :: title
      Character (1)                    :: uplo
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: a(:,:), ap(:)
      Character (1)                    :: clabs(1), rlabs(1)
!     .. Executable Statements ..
      Write (nout,*) 'F01VAF Example Program Results'
!     Skip heading in data file
      Read (nin,*)
      Write (nout,*)
      Flush (nout)
      Read (nin,*) n, uplo
      lda = n
      lenap = (n*(n+1))/2
      Allocate (a(lda,n),ap(lenap))

!     Read a triangular matrix of order n
      Do i = 1, n
        Read (nin,*) a(i,1:n)
      End Do

!     Print the unpacked matrix
      title = 'Unpacked Matrix A:'
      ifail = 0
      Call x04cbf(uplo,diag,n,n,a,lda,form,title,intlabel,rlabs,intlabel,      &
        clabs,ncols,indent,ifail)

      Write (nout,*)
      Flush (nout)

!     Convert to packed vector form
!     The NAG name equivalent of dtrttp is f01vaf
      Call dtrttp(uplo,n,a,lda,ap,info)

!     Print the packed vector
      title = 'Packed Matrix AP: '
      ifail = 0
      Call x04cbf(matrix,diag,lenap,inc1,ap,lenap,form,title,intlabel,rlabs,   &
        nolabel,clabs,ncols,indent,ifail)

    End Program f01vafe


f01vbfe.f90

    Program f01vbfe

!     F01VBF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: nag_wp, x04dbf, ztrttp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: inc1 = 1, indent = 0, ncols = 80,    &
                                          nin = 5, nout = 6
      Character (1), Parameter         :: brac = 'B', diag = 'N',              &
                                          intlabel = 'I', matrix = 'G',        &
                                          nolabel = 'N'
      Character (4), Parameter         :: form = 'F5.2'
!     .. Local Scalars ..
      Integer                          :: i, ifail, info, lda, lenap, n
      Character (18)                   :: title
      Character (1)                    :: uplo
!     .. Local Arrays ..
      Complex (Kind=nag_wp), Allocatable :: a(:,:), ap(:)
      Character (1)                    :: clabs(1), rlabs(1)
!     .. Executable Statements ..
      Write (nout,*) 'F01VBF Example Program Results'
!     Skip heading in data file
      Read (nin,*)
      Write (nout,*)
      Flush (nout)
      Read (nin,*) n, uplo
      lda = n
      lenap = (n*(n+1))/2
      Allocate (a(lda,n),ap(lenap))

!     Read a triangular matrix of order n
      Do i = 1, n
        Read (nin,*) a(i,1:n)
      End Do

!     Print the unpacked matrix
      title = 'Unpacked Matrix A:'
      ifail = 0
      Call x04dbf(uplo,diag,n,n,a,lda,brac,form,title,intlabel,rlabs,intlabel, &
        clabs,ncols,indent,ifail)

      Write (nout,*)
      Flush (nout)

!     Convert to packed vector form
!     The NAG name equivalent of ztrttp is f01vbf
      Call ztrttp(uplo,n,a,lda,ap,info)

!     Print the packed vector
      title = 'Packed Matrix AP: '
      ifail = 0
      Call x04dbf(matrix,diag,lenap,inc1,ap,lenap,brac,form,title,intlabel,    &
        rlabs,nolabel,clabs,ncols,indent,ifail)

    End Program f01vbfe


f01vcfe.f90

    Program f01vcfe

!     F01VCF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: dtpttr, nag_wp, x04cbf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: inc1 = 1, indent = 0, ncols = 80,    &
                                          nin = 5, nout = 6
      Character (1), Parameter         :: diag = 'N', intlabel = 'I',          &
                                          matrix = 'G', nolabel = 'N'
      Character (4), Parameter         :: form = 'F5.2'
!     .. Local Scalars ..
      Integer                          :: i, ifail, info, lda, lenap, n
      Character (18)                   :: title
      Character (1)                    :: uplo
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: a(:,:), ap(:)
      Character (1)                    :: clabs(1), rlabs(1)
!     .. Executable Statements ..
      Write (nout,*) 'F01VCF Example Program Results'
!     Skip heading in data file
      Read (nin,*)
      Write (nout,*)
      Flush (nout)
      Read (nin,*) n, uplo
      lda = n
      lenap = (n*(n+1))/2
      Allocate (a(lda,n),ap(lenap))

!     Read a packed vector of order n
      Do i = 1, lenap
        Read (nin,*) ap(i)
      End Do

!     Print the packed vector
      title = 'Packed Matrix AP: '
      ifail = 0
      Call x04cbf(matrix,diag,lenap,inc1,ap,lenap,form,title,intlabel,rlabs,   &
        nolabel,clabs,ncols,indent,ifail)

      Write (nout,*)
      Flush (nout)

!     Convert to triangular form
!     The NAG name equivalent of dtpttr is f01vcf
      Call dtpttr(uplo,n,ap,a,lda,info)

!     Print the unpacked matrix
      title = 'Unpacked Matrix A:'
      ifail = 0
      Call x04cbf(uplo,diag,n,n,a,lda,form,title,intlabel,rlabs,intlabel,      &
        clabs,ncols,indent,ifail)

    End Program f01vcfe


f01vdfe.f90

    Program f01vdfe

!     F01VDF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: nag_wp, x04dbf, ztpttr
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: inc1 = 1, indent = 0, ncols = 80,    &
                                          nin = 5, nout = 6
      Character (1), Parameter         :: brac = 'B', diag = 'N',              &
                                          intlabel = 'I', matrix = 'G',        &
                                          nolabel = 'N'
      Character (4), Parameter         :: form = 'F5.2'
!     .. Local Scalars ..
      Integer                          :: i, ifail, info, lda, lenap, n
      Character (18)                   :: title
      Character (1)                    :: uplo
!     .. Local Arrays ..
      Complex (Kind=nag_wp), Allocatable :: a(:,:), ap(:)
      Character (1)                    :: clabs(1), rlabs(1)
!     .. Executable Statements ..
      Write (nout,*) 'F01VDF Example Program Results'
!     Skip heading in data file
      Read (nin,*)
      Write (nout,*)
      Flush (nout)
      Read (nin,*) n, uplo
      lda = n
      lenap = (n*(n+1))/2
      Allocate (a(lda,n),ap(lenap))

!     Read a packed vector of order n
      Do i = 1, lenap
        Read (nin,*) ap(i)
      End Do

!     Print the packed vector
      title = 'Packed Matrix AP: '
      ifail = 0
      Call x04dbf(matrix,diag,lenap,inc1,ap,lenap,brac,form,title,intlabel,    &
        rlabs,nolabel,clabs,ncols,indent,ifail)

      Write (nout,*)
      Flush (nout)

!     Convert to triangular form
!     The NAG name equivalent of ztpttr is f01vdf
      Call ztpttr(uplo,n,ap,a,lda,info)

!     Print the unpacked matrix
      title = 'Unpacked Matrix A:'
      ifail = 0
      Call x04dbf(uplo,diag,n,n,a,lda,brac,form,title,intlabel,rlabs,intlabel, &
        clabs,ncols,indent,ifail)

    End Program f01vdfe


f01vefe.f90

    Program f01vefe

!     F01VEF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: dtrttf, nag_wp, x04cbf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: inc1 = 1, indent = 0, ncols = 80,    &
                                          nin = 5, nout = 6
      Character (1), Parameter         :: diag = 'N', intlabel = 'I',          &
                                          matrix = 'G', nolabel = 'N'
      Character (4), Parameter         :: form = 'F5.2'
!     .. Local Scalars ..
      Integer                          :: i, ifail, info, k, lar1, lar2, lda,  &
                                          lenar, n, q
      Character (47)                   :: title
      Character (1)                    :: transr, uplo
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: a(:,:), ar(:)
      Character (1)                    :: clabs(1), rlabs(1)
!     .. Executable Statements ..
      Write (nout,*) 'F01VEF Example Program Results'
!     Skip heading in data file
      Read (nin,*)
      Write (nout,*)
      Flush (nout)
      Read (nin,*) n, uplo, transr
      lda = n
      lenar = n*(n+1)/2
      Allocate (a(lda,n),ar(lenar))

!     Read a triangular matrix of order n into array A
      Do i = 1, n
        Read (nin,*) a(i,i:n)
      End Do

!     Print the unpacked array A
      title = 'Unpacked Matrix A:'
      ifail = 0
      Call x04cbf(uplo,diag,n,n,a,lda,form,title,intlabel,rlabs,intlabel,      &
        clabs,ncols,indent,ifail)

      Write (nout,*)
      Flush (nout)

!     Convert to Rectangular Full Packed form
!     The NAG name equivalent of dtrttf is f01vef
      Call dtrttf(transr,uplo,n,a,lda,ar,info)

!     Print the Rectangular Full Packed array
      title = 'RFP Packed Array AR:'
      ifail = 0
      Call x04cbf(matrix,diag,lenar,inc1,ar,lenar,form,title,intlabel,rlabs,   &
        nolabel,clabs,ncols,indent,ifail)

      Write (nout,*)
      Flush (nout)

!     Print the Rectangular Full Packed array showing how the elements are
!     arranged.
      title = 'RFP Packed Array AR (graphical representation):'
      k = n/2
      q = n - k
      If (transr=='N' .Or. transr=='n') Then
        lar1 = 2*k + 1
        lar2 = q
      Else
        lar1 = q
        lar2 = 2*k + 1
      End If

      ifail = 0
      Call x04cbf(matrix,diag,lar1,lar2,ar,lar1,form,title,intlabel,rlabs,     &
        intlabel,clabs,ncols,indent,ifail)

    End Program f01vefe


f01vffe.f90

    Program f01vffe

!     F01VFF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: nag_wp, x04dbf, ztrttf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: inc1 = 1, indent = 0, ncols = 80,    &
                                          nin = 5, nout = 6
      Character (1), Parameter         :: brac = 'B', diag = 'N',              &
                                          intlabel = 'I', matrix = 'G',        &
                                          nolabel = 'N'
      Character (4), Parameter         :: form = 'F5.2'
!     .. Local Scalars ..
      Integer                          :: i, ifail, info, k, lar1, lar2, lda,  &
                                          lenar, n, q
      Character (47)                   :: title
      Character (1)                    :: transr, uplo
!     .. Local Arrays ..
      Complex (Kind=nag_wp), Allocatable :: a(:,:), ar(:)
      Character (1)                    :: clabs(1), rlabs(1)
!     .. Executable Statements ..
      Write (nout,*) 'F01VFF Example Program Results'
      Write (nout,*)
      Flush (nout)
!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) n, uplo, transr
      lda = n
      lenar = n*(n+1)/2
      Allocate (a(lda,n),ar(lenar))

!     Read a triangular matrix of order n into array A
      Do i = 1, n
        Read (nin,*) a(i,i:n)
      End Do

!     Print the unpacked array
      title = 'Unpacked Matrix A:'
      ifail = 0
      Call x04dbf(uplo,diag,n,n,a,lda,brac,form,title,intlabel,rlabs,intlabel, &
        clabs,ncols,indent,ifail)

      Write (nout,*)
      Flush (nout)

!     Convert to Rectangular Full Packed form
!     The NAG name equivalent of ztrttf is f01vff
      Call ztrttf(transr,uplo,n,a,lda,ar,info)

!     Print the Rectangular Full Packed array
      title = 'RFP Packed Array AR:'
      ifail = 0
      Call x04dbf(matrix,diag,lenar,inc1,ar,lenar,brac,form,title,intlabel,    &
        rlabs,nolabel,clabs,ncols,indent,ifail)

      Write (nout,*)
      Flush (nout)

!     Print the Rectangular Full Packed array showing how the elements are
!     arranged.
      title = 'RFP Packed Array AR (graphical representation):'
      k = n/2
      q = n - k
      If (transr=='N' .Or. transr=='n') Then
        lar1 = 2*k + 1
        lar2 = q
      Else
        lar1 = q
        lar2 = 2*k + 1
      End If

      ifail = 0
      Call x04dbf(matrix,diag,lar1,lar2,ar,lar1,brac,form,title,intlabel,      &
        rlabs,intlabel,clabs,ncols,indent,ifail)

    End Program f01vffe


f01vgfe.f90

    Program f01vgfe

!     F01VGF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: dtfttr, nag_wp, x04cbf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: inc1 = 1, indent = 0, ncols = 80,    &
                                          nin = 5, nout = 6
      Character (1), Parameter         :: diag = 'N', intlabel = 'I',          &
                                          matrix = 'G', nolabel = 'N'
      Character (4), Parameter         :: form = 'F5.2'
!     .. Local Scalars ..
      Integer                          :: i, ifail, info, k, lar1, lda, lenar, &
                                          n, q
      Character (21)                   :: title
      Character (1)                    :: transr, uplo
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: a(:,:), ar(:)
      Character (1)                    :: clabs(1), rlabs(1)
!     .. Executable Statements ..
      Write (nout,*) 'F01VGF Example Program Results'
!     Skip heading in data file
      Read (nin,*)
      Write (nout,*)
      Flush (nout)
      Read (nin,*) n, uplo, transr
      lda = n
      lenar = n*(n+1)/2
      Allocate (a(lda,n),ar(lenar))

!     Setup notional dimensions of RFP matrix AR
      k = n/2
      q = n - k
      If (transr=='N' .Or. transr=='n') Then
        lar1 = 2*k + 1
      Else
        lar1 = q
      End If

!     Read an RFP matrix into array AR
      Do i = 1, lar1
        Read (nin,*) ar(i:lenar:lar1)
      End Do

!     Print the Rectangular Full Packed array
      title = 'RFP Packed Array AR:'
      ifail = 0
      Call x04cbf(matrix,diag,lenar,inc1,ar,lenar,form,title,intlabel,rlabs,   &
        nolabel,clabs,ncols,indent,ifail)
      Write (nout,*)
      Flush (nout)

!     Convert to triangular form
!     The NAG name equivalent of dtfttr is f01vgf
      Call dtfttr(transr,uplo,n,ar,a,lda,info)

!     Print the unpacked array
      ifail = 0
      title = 'Unpacked Matrix A:'
      ifail = 0
      Call x04cbf(uplo,diag,n,n,a,lda,form,title,intlabel,rlabs,intlabel,      &
        clabs,ncols,indent,ifail)

    End Program f01vgfe


f01vhfe.f90

    Program f01vhfe

!     F01VHF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: nag_wp, x04dbf, ztfttr
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: inc1 = 1, indent = 0, ncols = 80,    &
                                          nin = 5, nout = 6
      Character (1), Parameter         :: brac = 'B', diag = 'N',              &
                                          intlabel = 'I', matrix = 'G',        &
                                          nolabel = 'N'
      Character (4), Parameter         :: form = 'F5.2'
!     .. Local Scalars ..
      Integer                          :: i, ifail, info, k, lar1, lda, lenar, &
                                          n, q
      Character (21)                   :: title
      Character (1)                    :: transr, uplo
!     .. Local Arrays ..
      Complex (Kind=nag_wp), Allocatable :: a(:,:), ar(:)
      Character (1)                    :: clabs(1), rlabs(1)
!     .. Executable Statements ..
      Write (nout,*) 'F01VHF Example Program Results'
!     Skip heading in data file
      Read (nin,*)
      Write (nout,*)
      Flush (nout)
      Read (nin,*) n, uplo, transr
      lda = n
      lenar = n*(n+1)/2
      Allocate (a(lda,n),ar(lenar))

!     Setup notional dimensions of RFP matrix AR
      k = n/2
      q = n - k
      If (transr=='N' .Or. transr=='n') Then
        lar1 = 2*k + 1
      Else
        lar1 = q
      End If

!     Read an RFP matrix into array AR
      Do i = 1, lar1
        Read (nin,*) ar(i:lenar:lar1)
      End Do

!     Print the Rectangular Full Packed array
      title = 'RFP Packed Array AR:'
      ifail = 0
      Call x04dbf(matrix,diag,lenar,inc1,ar,lenar,brac,form,title,intlabel,    &
        rlabs,nolabel,clabs,ncols,indent,ifail)

      Write (nout,*)
      Flush (nout)

!     Convert to triangular form
!     The NAG name equivalent of ztfttr is f01vhf
      Call ztfttr(transr,uplo,n,ar,a,lda,info)

!     Print the unpacked array
      title = 'Unpacked Matrix A:'
      ifail = 0
      Call x04dbf(uplo,diag,n,n,a,lda,brac,form,title,intlabel,rlabs,intlabel, &
        clabs,ncols,indent,ifail)

    End Program f01vhfe


f01vjfe.f90

    Program f01vjfe

!     F01VJF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: dtpttf, nag_wp, x04cbf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: inc1 = 1, indent = 0, ncols = 80,    &
                                          nin = 5, nout = 6
      Character (1), Parameter         :: diag = 'N', intlabel = 'I',          &
                                          matrix = 'G', nolabel = 'N'
      Character (4), Parameter         :: form = 'F5.2'
!     .. Local Scalars ..
      Integer                          :: ifail, info, k, lar1, lar2, lenap,   &
                                          lenar, n, q
      Character (47)                   :: title
      Character (1)                    :: transr, uplo
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: ap(:), ar(:)
      Character (1)                    :: clabs(1), rlabs(1)
!     .. Executable Statements ..
      Write (nout,*) 'F01VJF Example Program Results'
!     Skip heading in data file
      Read (nin,*)
      Write (nout,*)
      Flush (nout)
      Read (nin,*) n, uplo, transr
      lenap = (n*(n+1))/2
      lenar = lenap

      Allocate (ap(lenap),ar(lenar))

!     Read an order n matrix packed into a 1-D array
      Read (nin,*) ap(1:lenap)

!     Print the packed array
      title = 'Packed Array AP:'
      ifail = 0
      Call x04cbf(matrix,diag,lenap,inc1,ap,lenap,form,title,intlabel,rlabs,   &
        nolabel,clabs,ncols,indent,ifail)

      Write (nout,*)
      Flush (nout)

!     Convert to Rectangular Full Packed form
!     The NAG name equivalent of dtpttf is f01vjf
      Call dtpttf(transr,uplo,n,ap,ar,info)

!     Print the Rectangular Full Packed array
      title = 'RFP Packed Array AR:'
      ifail = 0
      Call x04cbf(matrix,diag,lenar,inc1,ar,lenar,form,title,intlabel,rlabs,   &
        nolabel,clabs,ncols,indent,ifail)

      Write (nout,*)
      Flush (nout)

!     Print the Rectangular Full Packed array showing how the elements are
!     arranged.
      title = 'RFP Packed Array AR (graphical representation):'
      k = n/2
      q = n - k
      If (transr=='N' .Or. transr=='n') Then
        lar1 = 2*k + 1
        lar2 = q
      Else
        lar1 = q
        lar2 = 2*k + 1
      End If

      ifail = 0
      Call x04cbf(matrix,diag,lar1,lar2,ar,lar1,form,title,intlabel,rlabs,     &
        intlabel,clabs,ncols,indent,ifail)

    End Program f01vjfe


f01vkfe.f90

    Program f01vkfe

!     F01VKF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: nag_wp, x04dbf, ztpttf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: inc1 = 1, indent = 0, ncols = 80,    &
                                          nin = 5, nout = 6
      Character (1), Parameter         :: brac = 'B', diag = 'N',              &
                                          intlabel = 'I', matrix = 'G',        &
                                          nolabel = 'N'
      Character (4), Parameter         :: form = 'F5.2'
!     .. Local Scalars ..
      Integer                          :: ifail, info, k, lar1, lar2, lenap,   &
                                          lenar, n, q
      Character (47)                   :: title
      Character (1)                    :: transr, uplo
!     .. Local Arrays ..
      Complex (Kind=nag_wp), Allocatable :: ap(:), ar(:)
      Character (1)                    :: clabs(1), rlabs(1)
!     .. Executable Statements ..
      Write (nout,*) 'F01VKF Example Program Results'
!     Skip heading in data file
      Read (nin,*)
      Write (nout,*)
      Flush (nout)
      Read (nin,*) n, uplo, transr
      lenap = (n*(n+1))/2
      lenar = lenap

      Allocate (ap(lenap),ar(lenar))

!     Read an order n matrix packed into a 1-D array
      Read (nin,*) ap

!     Print the packed vector
      title = 'Packed Array AP:'
      ifail = 0
      Call x04dbf(matrix,diag,lenap,inc1,ap,lenap,brac,form,title,intlabel,    &
        rlabs,nolabel,clabs,ncols,indent,ifail)

      Write (nout,*)
      Flush (nout)

!     Convert to Rectangular Full Packed form
!     The NAG name equivalent of ztpttf is f01vkf
      Call ztpttf(transr,uplo,n,ap,ar,info)

!     Print the Rectangular Full Packed array
      title = 'RFP Packed Array AR:'
      ifail = 0
      Call x04dbf(matrix,diag,lenar,inc1,ar,lenar,brac,form,title,intlabel,    &
        rlabs,nolabel,clabs,ncols,indent,ifail)

      Write (nout,*)
      Flush (nout)

!     Print the Rectangular Full Packed array showing how the elements are
!     arranged.
      title = 'RFP Packed Array AR (graphical representation):'
      k = n/2
      q = n - k
      If (transr=='N' .Or. transr=='n') Then
        lar1 = 2*k + 1
        lar2 = q
      Else
        lar1 = q
        lar2 = 2*k + 1
      End If

      ifail = 0
      Call x04dbf(matrix,diag,lar1,lar2,ar,lar1,brac,form,title,intlabel,      &
        rlabs,intlabel,clabs,ncols,indent,ifail)

    End Program f01vkfe


f01vlfe.f90

    Program f01vlfe

!     F01VLF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: dtfttp, nag_wp, x04cbf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: inc1 = 1, indent = 0, ncols = 80,    &
                                          nin = 5, nout = 6
      Character (1), Parameter         :: diag = 'N', intlabel = 'I',          &
                                          matrix = 'G', nolabel = 'N'
      Character (4), Parameter         :: form = 'F5.2'
!     .. Local Scalars ..
      Integer                          :: i, ifail, info, k, lar1, lenap,      &
                                          lenar, n, q
      Character (21)                   :: title
      Character (1)                    :: transr, uplo
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: ap(:), ar(:)
      Character (1)                    :: clabs(1), rlabs(1)
!     .. Executable Statements ..
      Write (nout,*) 'F01VLF Example Program Results'
!     Skip heading in data file
      Read (nin,*)
      Write (nout,*)
      Flush (nout)
      Read (nin,*) n, uplo, transr
      lenap = (n*(n+1))/2
      lenar = lenap

      Allocate (ap(lenap),ar(lenar))

!     Setup notional dimensions of RFP matrix AR
      k = n/2
      q = n - k
      If (transr=='N' .Or. transr=='n') Then
        lar1 = 2*k + 1
      Else
        lar1 = q
      End If

!     Read an RFP matrix into array AR
      Do i = 1, lar1
        Read (nin,*) ar(i:lenar:lar1)
      End Do

!     Print the Rectangular Full Packed array
      title = 'RFP Packed Array AR:'
      ifail = 0
      Call x04cbf(matrix,diag,lenar,inc1,ar,lenar,form,title,intlabel,rlabs,   &
        nolabel,clabs,ncols,indent,ifail)

      Write (nout,*)
      Flush (nout)

!     Convert to packed vector form
!     The NAG name equivalent of dtfttp is f01vlf
      Call dtfttp(transr,uplo,n,ar,ap,info)

!     Print the packed vector
      title = 'Packed Array AP:'
      ifail = 0
      Call x04cbf(matrix,diag,lenap,inc1,ap,lenap,form,title,intlabel,rlabs,   &
        nolabel,clabs,ncols,indent,ifail)

    End Program f01vlfe


f01vmfe.f90

    Program f01vmfe

!     F01VMF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: nag_wp, x04dbf, ztfttp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: inc1 = 1, indent = 0, ncols = 80,    &
                                          nin = 5, nout = 6
      Character (1), Parameter         :: brac = 'B', diag = 'N',              &
                                          intlabel = 'I', matrix = 'G',        &
                                          nolabel = 'N'
      Character (4), Parameter         :: form = 'F5.2'
!     .. Local Scalars ..
      Integer                          :: i, ifail, info, k, lar1, lenap,      &
                                          lenar, n, q
      Character (21)                   :: title
      Character (1)                    :: transr, uplo
!     .. Local Arrays ..
      Complex (Kind=nag_wp), Allocatable :: ap(:), ar(:)
      Character (1)                    :: clabs(1), rlabs(1)
!     .. Executable Statements ..
      Write (nout,*) 'F01VMF Example Program Results'
!     Skip heading in data file
      Read (nin,*)
      Write (nout,*)
      Flush (nout)
      Read (nin,*) n, uplo, transr
      lenap = (n*(n+1))/2
      lenar = lenap

      Allocate (ap(lenap),ar(lenar))

!     Setup notional dimensions of RFP matrix AR
      k = n/2
      q = n - k
      If (transr=='N' .Or. transr=='n') Then
        lar1 = 2*k + 1
      Else
        lar1 = q
      End If

!     Read an RFP matrix into array AR
      Do i = 1, lar1
        Read (nin,*) ar(i:lenar:lar1)
      End Do

!     Print the Rectangular Full Packed array
      title = 'RFP Packed Array AR:'
      ifail = 0
      Call x04dbf(matrix,diag,lenar,inc1,ar,lenar,brac,form,title,intlabel,    &
        rlabs,nolabel,clabs,ncols,indent,ifail)

      Write (nout,*)
      Flush (nout)

!     Convert to packed vector form
!     The NAG name equivalent of ztfttp is f01vmf
      Call ztfttp(transr,uplo,n,ar,ap,info)

!     Print the packed vector
      title = 'Packed Array AP:'
      ifail = 0
      Call x04dbf(matrix,diag,lenap,inc1,ap,lenap,brac,form,title,intlabel,    &
        rlabs,nolabel,clabs,ncols,indent,ifail)

    End Program f01vmfe


f01zafe.f90

    Program f01zafe

!     F01ZAF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: f01zaf, nag_wp, x04cbf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Integer                          :: i, ifail, lb, lda, lenb, n
      Character (1)                    :: diag, uplo
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: a(:,:), b(:)
      Character (1)                    :: clabs(1), rlabs(1)
!     .. Executable Statements ..
      Write (nout,*) 'F01ZAF Example Program Results'
!     Skip heading in data file
      Read (nin,*)
      Write (nout,*)
      Flush (nout)
      Read (nin,*) n, uplo, diag
      lda = n
      lenb = (n*(n+1))/2
      Allocate (a(lda,n),b(lenb))
!     Read a triangular matrix of order n
      Do i = 1, n
        Read (nin,*) a(i,1:n)
      End Do

!     ifail: behaviour on error exit
!             =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
      ifail = 0
!     Print the unpacked matrix
      Call x04cbf(uplo,diag,n,n,a,lda,'F5.2','Unpacked Matrix A:','I',rlabs,   &
        'I',clabs,80,0,ifail)

      Write (nout,*)
      Flush (nout)

!     Convert to packed vector form
      ifail = 0
      Call f01zaf('Pack',uplo,diag,n,a,lda,b,ifail)

      lb = n*(n+1)/2

!     Print the packed vector
      ifail = 0
      Call x04cbf('G','X',lb,1,b,lb,'F5.2','Packed Vector B:','I',rlabs,'N',   &
        clabs,80,0,ifail)

    End Program f01zafe


f01zbfe.f90

    Program f01zbfe

!     F01ZBF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: f01zbf, nag_wp, x04dbf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Integer                          :: i, ifail, lb, lda, lenb, n
      Character (1)                    :: diag, uplo
!     .. Local Arrays ..
      Complex (Kind=nag_wp), Allocatable :: a(:,:), b(:)
      Character (1)                    :: clabs(1), rlabs(1)
!     .. Executable Statements ..
      Write (nout,*) 'F01ZBF Example Program Results'
!     Skip heading in data file
      Read (nin,*)
      Write (nout,*)
      Flush (nout)
      Read (nin,*) n, uplo, diag
      lda = n
      lenb = (n*(n+1))/2
      Allocate (a(lda,n),b(lenb))
!     Read a triangular matrix of order n
      Do i = 1, n
        Read (nin,*) a(i,1:n)
      End Do

!     ifail: behaviour on error exit
!             =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
      ifail = 0
!     Print the unpacked matrix
      Call x04dbf(uplo,diag,n,n,a,lda,'B','F5.2','Unpacked Matrix A:','I',     &
        rlabs,'I',clabs,80,0,ifail)

      Write (nout,*)
      Flush (nout)

!     Convert to packed vector form
      ifail = 0
      Call f01zbf('Pack',uplo,diag,n,a,lda,b,ifail)

      lb = n*(n+1)/2

!     Print the packed vector
      ifail = 0
      Call x04dbf('G','X',lb,1,b,lb,'B','F5.2','Packed Vector B:','I',rlabs,   &
        'N',clabs,80,0,ifail)

    End Program f01zbfe


f01zcfe.f90

    Program f01zcfe

!     F01ZCF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: f01zcf, nag_wp, x04caf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Integer                          :: i, ifail, kl, ku, lda, ldb, m, n
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: a(:,:), b(:,:)
!     .. Executable Statements ..
      Write (nout,*) 'F01ZCF Example Program Results'
!     Skip heading in data file
      Read (nin,*)
      Write (nout,*)
      Flush (nout)
      Read (nin,*) m, n, kl, ku
      lda = n
      ldb = lda
      Allocate (a(lda,n),b(ldb,n))
!     Read a banded matrix of size m by n. kl is the number of
!     subdiagonals, ku the number of superdiagonals.
      Do i = 1, n
        Read (nin,*) a(i,1:n)
      End Do
!     Clear the packed matrix array B, so that no elements are
!     unassigned when we print B later.
      b(1:(kl+ku+1),1:n) = 0.0E+0_nag_wp
!     ifail: behaviour on error exit
!             =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
      ifail = 0
!     Print the unpacked matrix
      Call x04caf('G','X',n,n,a,lda,'Unpacked Matrix A:',ifail)

      Write (nout,*)
      Flush (nout)

!     Convert to packed matrix form
      ifail = 0
      Call f01zcf('Pack',m,n,kl,ku,a,lda,b,ldb,ifail)

!     Print the packed matrix
      ifail = 0
      Call x04caf('G','X',kl+ku+1,n,b,ldb,'Packed Matrix B:',ifail)

    End Program f01zcfe


f01zdfe.f90

    Program f01zdfe

!     F01ZDF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: f01zdf, nag_wp, x04daf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Integer                          :: i, ifail, kl, ku, lda, ldb, m, n
!     .. Local Arrays ..
      Complex (Kind=nag_wp), Allocatable :: a(:,:), b(:,:)
!     .. Executable Statements ..
      Write (nout,*) 'F01ZDF Example Program Results'
!     Skip heading in data file
      Read (nin,*)
      Write (nout,*)
      Flush (nout)
      Read (nin,*) m, n, kl, ku
      lda = n
      ldb = lda
      Allocate (a(lda,n),b(ldb,n))
!     Read a banded matrix of size m by n. kl is the number of
!     subdiagonals, ku the number of superdiagonals.
      Do i = 1, n
        Read (nin,*) a(i,1:n)
      End Do
!     Clear the packed matrix array B, so that no elements are
!     unassigned when we print B later.
      b(1:(kl+ku+1),1:n) = (0.0E+0_nag_wp,0.0E+0_nag_wp)

!     ifail: behaviour on error exit
!             =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
      ifail = 0
!     Print the unpacked matrix
      Call x04daf('G','X',n,n,a,lda,'Unpacked Matrix A:',ifail)

      Write (nout,*)
      Flush (nout)

!     Convert to packed matrix form
      ifail = 0
      Call f01zdf('Pack',m,n,kl,ku,a,lda,b,ldb,ifail)

!     Print the packed matrix
      ifail = 0
      Call x04daf('G','X',kl+ku+1,n,b,ldb,'Packed Matrix B:',ifail)

    End Program f01zdfe


f02ecfe.f90

    Program f02ecfe

!     F02ECF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: f02ecf, nag_wp, x04dbf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: wl, wu
      Integer                          :: i, ifail, j, lda, ldv, ldvi, ldvr,   &
                                          lwork, m, mest, n
!     .. Local Arrays ..
      Complex (Kind=nag_wp), Allocatable :: v(:,:)
      Real (Kind=nag_wp), Allocatable  :: a(:,:), vi(:,:), vr(:,:), wi(:),     &
                                          work(:), wr(:)
      Integer, Allocatable             :: iwork(:)
      Logical, Allocatable             :: bwork(:)
      Character (1)                    :: clabs(1), rlabs(1)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: cmplx
!     .. Executable Statements ..
      Write (nout,*) 'F02ECF Example Program Results'
!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) n, mest, wl, wu
      lda = n
      ldv = n
      ldvi = n
      ldvr = n
      lwork = 64*n
      Allocate (v(ldv,n),a(lda,n),vi(ldvi,mest),vr(ldvr,mest),wi(n),           &
        work(lwork),wr(n),iwork(n),bwork(n))

!     Read A from data file

      Read (nin,*)(a(i,1:n),i=1,n)

!     Compute selected eigenvalues and eigenvectors of A

!     ifail: behaviour on error exit
!            =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
      ifail = 0
      Call f02ecf('Moduli',n,a,lda,wl,wu,mest,m,wr,wi,vr,ldvr,vi,ldvi,work,    &
        lwork,iwork,bwork,ifail)

      Write (nout,*)
      Write (nout,*) 'Eigenvalues'
      Write (nout,99999)(' (',wr(i),',',wi(i),')',i=1,m)
      Write (nout,*)
      Flush (nout)
      Do j = 1, m
        Do i = 1, n
          v(i,j) = cmplx(vr(i,j),vi(i,j),kind=nag_wp)
        End Do
      End Do

      ifail = 0
      Call x04dbf('General',' ',n,m,v,ldv,'Bracketed','F7.4','Eigenvectors',   &
        'Integer',rlabs,'Integer',clabs,80,0,ifail)

99999 Format ((3X,4(A,F7.4,A,F7.4,A,:)))
    End Program f02ecfe


f02ekfe.f90

!   F02EKF Example Program Text
!   Mark 26 Release. NAG Copyright 2016.
    Module f02ekfe_mod

!     F02EKF Example Program Module:
!            Parameters and User-defined Routines

!     .. Use Statements ..
      Use nag_library, Only: nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Accessibility Statements ..
      Private
      Public                           :: mymonit, myoption
!     .. Parameters ..
      Integer, Parameter, Public       :: nin = 5, nout = 6
    Contains
      Subroutine myoption(icomm,comm,istat,iuser,ruser)

!       .. Use Statements ..
        Use nag_library, Only: f12adf
!       .. Implicit None Statement ..
        Implicit None
!       .. Scalar Arguments ..
        Integer, Intent (Inout)        :: istat
!       .. Array Arguments ..
        Real (Kind=nag_wp), Intent (Inout) :: comm(*), ruser(*)
        Integer, Intent (Inout)        :: icomm(*), iuser(*)
!       .. Local Scalars ..
        Integer                        :: ifail1
        Character (25)                 :: rec
!       .. Intrinsic Procedures ..
        Intrinsic                      :: max
!       .. Executable Statements ..
        Continue

        istat = 0

        If (iuser(1)>0) Then
          Write (rec,99999) 'Print Level=', iuser(1)
          ifail1 = 1
          Call f12adf(rec,icomm,comm,ifail1)
          istat = max(istat,ifail1)
        End If
        If (iuser(2)>100) Then
          Write (rec,99999) 'Iteration Limit=', iuser(2)
          ifail1 = 1
          Call f12adf(rec,icomm,comm,ifail1)
          istat = max(istat,ifail1)
        End If
        If (iuser(3)>0) Then
          ifail1 = 1
          Call f12adf('Shifted Inverse Real',icomm,comm,ifail1)
          istat = max(istat,ifail1)
        End If
99999   Format (A,I5)
      End Subroutine myoption
      Subroutine mymonit(ncv,niter,nconv,w,rzest,istat,iuser,ruser)

!       .. Implicit None Statement ..
        Implicit None
!       .. Scalar Arguments ..
        Integer, Intent (Inout)        :: istat
        Integer, Intent (In)           :: nconv, ncv, niter
!       .. Array Arguments ..
        Complex (Kind=nag_wp), Intent (In) :: w(ncv)
        Real (Kind=nag_wp), Intent (Inout) :: ruser(*)
        Real (Kind=nag_wp), Intent (In) :: rzest(ncv)
        Integer, Intent (Inout)        :: iuser(*)
!       .. Local Scalars ..
        Integer                        :: i
!       .. Executable Statements ..
        Continue

        If (iuser(4)>0) Then
          If (niter==1 .And. iuser(3)>0) Then
            Write (nout,99999) ' Arnoldi basis vectors used:', ncv
            Write (nout,*)                                                     &
              ' The following Ritz values (mu) are related to the'
            Write (nout,*)                                                     &
              ' true eigenvalues (lambda) by lambda = sigma + 1/mu'
          End If
          Write (nout,*)
          Write (nout,99999) ' Iteration number ', niter
          Write (nout,99998) ' Ritz values converged so far (', nconv,         &
            ') and their Ritz estimates:'
          Do i = 1, nconv
            Write (nout,99997) i, w(i), rzest(i)
          End Do
          Write (nout,*) ' Next (unconverged) Ritz value:'
          Write (nout,99996) nconv + 1, w(nconv+1)
        End If
        istat = 0
99999   Format (1X,A,I4)
99998   Format (1X,A,I4,A)
99997   Format (1X,1X,I4,1X,'(',E13.5,',',E13.5,')',1X,E13.5)
99996   Format (1X,1X,I4,1X,'(',E13.5,',',E13.5,')')
      End Subroutine mymonit
    End Module f02ekfe_mod
    Program f02ekfe

!     Example problem for F02EKF.

!     .. Use Statements ..
      Use nag_library, Only: f02ekf, nag_wp, x02ajf
      Use f02ekfe_mod, Only: mymonit, myoption, nin, nout
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Real (Kind=nag_wp), Parameter    :: one = 1.0_nag_wp
      Real (Kind=nag_wp), Parameter    :: three = 3.0_nag_wp
      Real (Kind=nag_wp), Parameter    :: two = 2.0_nag_wp
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: h, rho, s, sigma
      Integer                          :: i, ifail, imon, k, ldv, maxit, mode, &
                                          n, nconv, ncv, nev, nnz, nx, prtlvl
!     .. Local Arrays ..
      Complex (Kind=nag_wp), Allocatable :: w(:)
      Real (Kind=nag_wp), Allocatable  :: a(:), resid(:), v(:,:)
      Real (Kind=nag_wp)               :: ruser(1)
      Integer, Allocatable             :: icolzp(:), irowix(:)
      Integer                          :: iuser(4)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: real
!     .. Executable Statements ..
      Write (nout,*) 'F02EKF Example Program Results'
      Write (nout,*)
!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) nx
      Read (nin,*) nev
      Read (nin,*) ncv
      Read (nin,*) rho
      Read (nin,*) sigma

      n = nx*nx
      nnz = 3*n - 2
      ldv = n

      Allocate (resid(ncv),a(nnz),icolzp(n+1),irowix(nnz),w(ncv),v(ldv,ncv))

!     Construct  A in compressed column storage (CCS) format where:
!      A_{i,i}   = 2 + i
!      A_{i+1,i) = 3
!      A_{i,i+1} = rho/(2n+2) - 1

      h = one/real(n+1,kind=nag_wp)
      s = rho*h/two - one

      a(1) = two + one
      a(2) = three
      icolzp(1) = 1
      irowix(1) = 1
      irowix(2) = 2
      k = 3
      Do i = 2, n - 1
        icolzp(i) = k
        irowix(k) = i - 1
        irowix(k+1) = i
        irowix(k+2) = i + 1
        a(k) = s
        a(k+1) = two + real(i,kind=nag_wp)
        a(k+2) = three
        k = k + 3
      End Do
      icolzp(n) = k
      icolzp(n+1) = k + 2
      irowix(k) = n - 1
      irowix(k+1) = n
      a(k) = s
      a(k+1) = two + real(n,kind=nag_wp)

!     Set some options via iuser array and routine argument OPTION.
!     iuser(1) = print level, iuser(2) = iteration limit,
!     iuser(3)>0 means shifted-invert mode
!     iuser(4)>0 means print monitoring info

      Read (nin,*) prtlvl
      Read (nin,*) maxit
      Read (nin,*) mode
      Read (nin,*) imon

      If (prtlvl>0) Then
        imon = 0
      End If

      iuser(1) = prtlvl
      iuser(2) = maxit
      iuser(3) = mode
      iuser(4) = imon

!     ifail: behaviour on error exit
!             =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
      ifail = 0
      Call f02ekf(n,nnz,a,icolzp,irowix,nev,ncv,sigma,mymonit,myoption,nconv,  &
        w,v,ldv,resid,iuser,ruser,ifail)

      Write (nout,99999) nconv, sigma
      Do i = 1, nconv
        If (resid(i)>real(100*n,kind=nag_wp)*x02ajf()) Then
          Write (nout,99998) i, w(i), resid(i)
        Else
          Write (nout,99998) i, w(i)
        End If
      End Do

99999 Format (1X,/,' The ',I4,' Ritz values of closest to ',E13.5,' are:',/)
99998 Format (1X,I8,5X,'( ',E13.5,' , ',E13.5,' )',5X,E13.5)
    End Program f02ekfe


f02fjfe.f90

!   F02FJF Example Program Text
!   Mark 26 Release. NAG Copyright 2016.

    Module f02fjfe_mod

!     F02FJF Example Program Module:
!            Parameters and User-defined Routines

!     .. Use Statements ..
      Use nag_library, Only: nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Accessibility Statements ..
      Private
      Public                           :: dot, image, monit
!     .. Parameters ..
      Real (Kind=nag_wp), Parameter    :: half = 0.5_nag_wp
      Real (Kind=nag_wp), Parameter, Public :: zero = 0.0_nag_wp
      Integer, Parameter, Public       :: nin = 5, nout = 6
    Contains
      Function dot(iflag,n,z,w,ruser,lruser,iuser,liuser)
!       This function implements the dot product - transpose(W)*B*Z.
!       DOT assumes that N is at least 3.

!       .. Function Return Value ..
        Real (Kind=nag_wp)             :: dot
!       .. Scalar Arguments ..
        Integer, Intent (Inout)        :: iflag
        Integer, Intent (In)           :: liuser, lruser, n
!       .. Array Arguments ..
        Real (Kind=nag_wp), Intent (Inout) :: ruser(lruser)
        Real (Kind=nag_wp), Intent (In) :: w(n), z(n)
        Integer, Intent (Inout)        :: iuser(liuser)
!       .. Local Scalars ..
        Real (Kind=nag_wp)             :: s
        Integer                        :: i
!       .. Executable Statements ..
        s = zero
        s = s + (z(1)-half*z(2))*w(1)
        s = s + (-half*z(n-1)+z(n))*w(n)
        Do i = 2, n - 1
          s = s + (-half*z(i-1)+z(i)-half*z(i+1))*w(i)
        End Do
        dot = s
!       Set iflag negative to terminate execution for any reason.
        iflag = 0
        Return
      End Function dot
      Subroutine image(iflag,n,z,w,ruser,lruser,iuser,liuser)
!       This routine solves  A*W = B*Z  for W.
!       The routine assumes that N is at least 3.

!       The data A, NNZ, LA, IROW, ICOL, IPIV and ISTR on exit from
!       F11JAF have been packed into the xUSER communication arrays in
!       the following way:
!       IUSER(1:2) = (/NNZ, LA/)
!       RUSER(1:LA) = A
!       IUSER(3:(2*LA+2*N+3)) = (/IROW, ICOL, IPIV, ISTR/)
!       We'll also use RUSER((LA+1):(LA+N)) as space for F11JCF's dummy
!       arg. B, and RUSER((LA+N+1):(LA+7*N+120)) as space for F11JCF's
!       dummy arg. WORK

!       .. Use Statements ..
        Use nag_library, Only: f11jcf, x02ajf
!       .. Scalar Arguments ..
        Integer, Intent (Inout)        :: iflag
        Integer, Intent (In)           :: liuser, lruser, n
!       .. Array Arguments ..
        Real (Kind=nag_wp), Intent (Inout) :: ruser(lruser)
        Real (Kind=nag_wp), Intent (Out) :: w(n)
        Real (Kind=nag_wp), Intent (In) :: z(n)
        Integer, Intent (Inout)        :: iuser(liuser)
!       .. Local Scalars ..
        Real (Kind=nag_wp)             :: rnorm, tol
        Integer                        :: ifail, itn, j, la, lwork, maxitn,    &
                                          nnz
        Character (2)                  :: method
!       .. Executable Statements ..
        nnz = iuser(1)
        la = iuser(2)

!       Form B*Z in RUSER((LA+1):(LA+N)) and initialize W to
!       zero.
        w(1:n) = zero
        ruser(la+1) = z(1) - half*z(2)
        Do j = 2, n - 1
          ruser(la+j) = -half*z(j-1) + z(j) - half*z(j+1)
        End Do
        ruser(la+n) = -half*z(n-1) + z(n)

!       Call F11JCF to solve the equations  A*W = B*Z.
        method = 'CG'
        tol = x02ajf()
        maxitn = 100
        lwork = 6*n + 120

!       ifail: behaviour on error exit
!              =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
        ifail = 1
        Call f11jcf(method,n,nnz,ruser,la,iuser(3),iuser(la+3),iuser(2*la+3),  &
          iuser(2*la+n+3),ruser(la+1),tol,maxitn,w,rnorm,itn,ruser(la+n+1),    &
          lwork,ifail)

        If (ifail>0) Then
          iflag = -ifail
        End If
        Return
      End Subroutine image
      Subroutine monit(istate,nextit,nevals,nevecs,k,f,d)
!       Monitoring routine for F02FJF.

!       .. Parameters ..
        Integer, Parameter             :: nout = 6
!       .. Scalar Arguments ..
        Integer, Intent (In)           :: istate, k, nevals, nevecs, nextit
!       .. Array Arguments ..
        Real (Kind=nag_wp), Intent (In) :: d(k), f(k)
!       .. Local Scalars ..
        Integer                        :: i
!       .. Executable Statements ..
        If (istate/=0) Then
          Write (nout,*)
          Write (nout,99999) '  ISTATE = ', istate, ' NEXTIT = ', nextit
          Write (nout,99999) '  NEVALS = ', nevals, ' NEVECS = ', nevecs
          Write (nout,*) '       F           D'
          Write (nout,99998)(f(i),d(i),i=1,k)
        End If
        Return

99999   Format (1X,A,I4,A,I4)
99998   Format (1X,1P,E11.3,3X,E11.3)
      End Subroutine monit
    End Module f02fjfe_mod
    Program f02fjfe

!     F02FJF Example Main Program

!     .. Use Statements ..
      Use nag_library, Only: f02fjf, f06fef, f11jaf, nag_wp, x04cbf
      Use f02fjfe_mod, Only: dot, image, monit, nin, nout, zero
!     .. Implicit None Statement ..
      Implicit None
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: dscale, dtol, tol
      Integer                          :: i, ifail, k, l, la, ldx, lfill,      &
                                          liuser, lruser, lwork, m, n, nnz,    &
                                          nnzc, noits, novecs, npivm
      Character (1)                    :: mic, pstrat
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: a(:), d(:), ruser(:), work(:),       &
                                          x(:,:)
      Integer, Allocatable             :: icol(:), ipiv(:), irow(:), istr(:),  &
                                          iuser(:)
      Character (1)                    :: clabs(1), rlabs(1)
!     .. Executable Statements ..
      Write (nout,*) 'F02FJF Example Program Results'
      Write (nout,*)
      Flush (nout)
!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) n, m, k, tol
      la = 10*n
      ldx = n
      liuser = 2*la + 2*n + 3
      lruser = la + 7*n + 120
      lwork = 5*k + 2*n
      Allocate (a(la),d(n),ruser(lruser),work(lwork),x(ldx,k),icol(la),        &
        ipiv(n),irow(la),istr(n+1),iuser(liuser))

!     Set up the sparse symmetric coefficient matrix A.
      l = 0
      Do i = 1, n
        If (i>=5) Then
          l = l + 1
          a(l) = -0.25_nag_wp
          irow(l) = i
          icol(l) = i - 4
        End If
        If (i>=2) Then
          l = l + 1
          a(l) = -0.25_nag_wp
          irow(l) = i
          icol(l) = i - 1
        End If
        l = l + 1
        a(l) = 1.0_nag_wp
        irow(l) = i
        icol(l) = i
      End Do
      nnz = l

!     Call F11JAF to find an incomplete Cholesky factorization of A.
      lfill = 2
      dtol = zero
      mic = 'M'
      dscale = zero
      pstrat = 'M'

!     ifail: behaviour on error exit
!             =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
      ifail = 0
      Call f11jaf(n,nnz,a,la,irow,icol,lfill,dtol,mic,dscale,pstrat,ipiv,istr, &
        nnzc,npivm,iuser,liuser,ifail)

!     Call F02FJF to find eigenvalues and eigenvectors.

      noits = 1000
      novecs = 0

!     Communicate A, NNZ, LA, IROW, ICOL, IPIV and ISTR to IMAGE
!     thread-safely using RUSER and IUSER.
!     In addition to using RUSER for storing A, we'll also use
!     7*N+120 elements of RUSER in place of local arrays in IMAGE.

!     Initialized A goes into ruser.
      ruser(1:nnz+nnzc) = a(1:nnz+nnzc)

!     NNZ, LA, IROW, ICOL, IPIV and ISTR go into IUSER, in that order.
!     Only the first NNZ+NNZC elements of IROW and ICOL will have been
!     initialized:
      iuser(1) = nnz
      iuser(2) = la
      iuser(3:2+nnz+nnzc) = irow(1:nnz+nnzc)
      iuser(la+3:la+2+nnz+nnzc) = icol(1:nnz+nnzc)
      iuser(2*la+3:2*la+2+n) = ipiv(1:n)
      iuser(liuser-n:liuser) = istr(1:n+1)

      ifail = -1
      Call f02fjf(n,m,k,noits,tol,dot,image,monit,novecs,x,ldx,d,work,lwork,   &
        ruser,lruser,iuser,liuser,ifail)

      If (ifail>=0) Then
        If (ifail/=1 .And. ifail<=4 .And. m>=1) Then
          Do i = 1, m
            d(i) = 1.0_nag_wp/d(i)
          End Do
          Write (nout,*) 'Final results'
          Write (nout,*)
          Write (nout,*) '  Eigenvalues'
          Write (nout,99999) d(1:m)
          Write (nout,*)
          Flush (nout)
!         Normalize eigenvectors
          Do i = 1, m
            Call f06fef(n,x(1,i),x(1,i),1)
          End Do
          Call x04cbf('General',' ',n,m,x,ldx,'1P,E12.3','  Eigenvectors','N', &
            rlabs,'N',clabs,80,0,ifail)
        End If
      End If

99999 Format (1X,1P,4E12.3)
    End Program f02fjfe


f02fkfe.f90

!   F02FKF Example Program Text
!   Mark 26 Release. NAG Copyright 2016.
    Module f02fkfe_mod

!     F02FKF Example Program Module:
!            Parameters and User-defined Routines

!     .. Use Statements ..
      Use nag_library, Only: nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Accessibility Statements ..
      Private
      Public                           :: mymonit, myoption
!     .. Parameters ..
      Integer, Parameter, Public       :: nin = 5, nout = 6
    Contains
      Subroutine myoption(icomm,comm,istat,iuser,ruser)

!       .. Use Statements ..
        Use nag_library, Only: f12fdf
!       .. Implicit None Statement ..
        Implicit None
!       .. Scalar Arguments ..
        Integer, Intent (Inout)        :: istat
!       .. Array Arguments ..
        Real (Kind=nag_wp), Intent (Inout) :: comm(*), ruser(*)
        Integer, Intent (Inout)        :: icomm(*), iuser(*)
!       .. Local Scalars ..
        Integer                        :: ifail1
        Character (25)                 :: rec
!       .. Intrinsic Procedures ..
        Intrinsic                      :: max
!       .. Executable Statements ..
        Continue

        istat = 0

        If (iuser(1)>0) Then
          Write (rec,99999) 'Print Level=', iuser(1)
          ifail1 = 1
          Call f12fdf(rec,icomm,comm,ifail1)
          istat = max(istat,ifail1)
        End If
        If (iuser(2)>100) Then
          Write (rec,99999) 'Iteration Limit=', iuser(2)
          ifail1 = 1
          Call f12fdf(rec,icomm,comm,ifail1)
          istat = max(istat,ifail1)
        End If
        If (iuser(3)>0) Then
          ifail1 = 1
          Call f12fdf('Shifted Inverse',icomm,comm,ifail1)
          istat = max(istat,ifail1)
        End If
99999   Format (A,I5)
      End Subroutine myoption

      Subroutine mymonit(ncv,niter,nconv,w,rzest,istat,iuser,ruser)

!       .. Implicit None Statement ..
        Implicit None
!       .. Scalar Arguments ..
        Integer, Intent (Inout)        :: istat
        Integer, Intent (In)           :: nconv, ncv, niter
!       .. Array Arguments ..
        Real (Kind=nag_wp), Intent (Inout) :: ruser(*)
        Real (Kind=nag_wp), Intent (In) :: rzest(ncv), w(ncv)
        Integer, Intent (Inout)        :: iuser(*)
!       .. Local Scalars ..
        Integer                        :: i
!       .. Executable Statements ..
        Continue

        If (iuser(4)>0) Then
          If (niter==1 .And. iuser(3)>0) Then
            Write (nout,99999) ' Arnoldi basis vectors used:', ncv
            Write (nout,*)                                                     &
              ' The following Ritz values (mu) are related to the'
            Write (nout,*)                                                     &
              ' true eigenvalues (lambda) by lambda = sigma + 1/mu'
          End If
          Write (nout,*)
          Write (nout,99999) ' Iteration number ', niter
          Write (nout,99998) ' Ritz values converged so far (', nconv,         &
            ') and their Ritz estimates:'
          Do i = 1, nconv
            Write (nout,99997) i, w(i), rzest(i)
          End Do
          Write (nout,*) ' Next (unconverged) Ritz value:'
          Write (nout,99996) nconv + 1, w(nconv+1)
        End If
        istat = 0
99999   Format (1X,A,I4)
99998   Format (1X,A,I4,A)
99997   Format (1X,1X,I4,1X,E13.5,1X,E13.5)
99996   Format (1X,1X,I4,1X,E13.5)
      End Subroutine mymonit
    End Module f02fkfe_mod
    Program f02fkfe

!     Example problem for F02FKF.

!     .. Use Statements ..
      Use nag_library, Only: f02fkf, nag_wp, x04abf, x04caf
      Use f02fkfe_mod, Only: mymonit, myoption, nin, nout
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Real (Kind=nag_wp), Parameter    :: one = 1.0_nag_wp
      Integer, Parameter               :: iset = 1
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: h2, sigma
      Integer                          :: i, ifail, imon, j, k, ldv, lo,       &
                                          maxit, mode, n, nconv, ncv, nev,     &
                                          nnz, nx, outchn, prtlvl
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: a(:), d_print(:,:), resid(:),        &
                                          v(:,:), w(:)
      Real (Kind=nag_wp)               :: ruser(1)
      Integer, Allocatable             :: icol(:), irow(:)
      Integer                          :: iuser(4)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: real
!     .. Executable Statements ..
      Write (nout,*) 'F02FKF Example Program Results'
      Write (nout,*)

!     Skip heading in data file
      Read (nin,*)

      Read (nin,*) nx
      Read (nin,*) nev
      Read (nin,*) ncv
      Read (nin,*) sigma

!     Construct the matrix A in sparse form and store in A.
!     The main diagonal of A is full and there are two subdiagonals of A:
!     the first and the nx-th.

      n = nx*nx
      nnz = 3*n - 2*nx
      Allocate (a(nnz),irow(nnz),icol(nnz))

!     Zero out A.

      a(1:nnz) = 0.0_nag_wp

!     Main diagonal of A.
      h2 = one/real((nx+1)*(nx+1),kind=nag_wp)
      a(1:n) = 4.0_nag_wp/h2
      Do i = 1, n
        irow(i) = i
        icol(i) = i
      End Do

!     First subdiagonal of A.
      k = n
      Do i = 1, nx
        lo = (i-1)*nx
        Do j = lo + 1, lo + nx - 1
          k = k + 1
          irow(k) = j + 1
          icol(k) = j
          a(k) = -one/h2
        End Do
      End Do

!     nx-th subdiagonal
      Do i = 1, nx - 1
        lo = (i-1)*nx
        Do j = lo + 1, lo + nx
          k = k + 1
          irow(k) = j + nx
          icol(k) = j
          a(k) = -one/h2
        End Do
      End Do

!     Set some options via iuser array and routine argument OPTION.
!     iuser(1) = print level, iuser(2) = iteration limit,
!     iuser(3)>0 means shifted-invert mode
!     iuser(4)>0 means print monitoring info

      Read (nin,*) prtlvl
      Read (nin,*) maxit
      Read (nin,*) mode
      Read (nin,*) imon
      ruser(1) = one
      iuser(1) = prtlvl
      iuser(2) = maxit
      iuser(3) = mode
      iuser(4) = imon

!     Find eigenvalues of largest magnitude and the corresponding
!     eigenvectors.

      ldv = n
      Allocate (w(ncv),v(ldv,ncv),resid(n))

      ifail = -1
      Call f02fkf(n,nnz,a,irow,icol,nev,ncv,sigma,mymonit,myoption,nconv,w,v,  &
        ldv,resid,iuser,ruser,ifail)

      If (ifail/=0) Then
        Go To 100
      End If

!     Print Eigenvalues and the residual norm  ||A*x - lambda*x||.

      Allocate (d_print(nconv,2))
      d_print(1:nconv,1) = w(1:nconv)
      d_print(1:nconv,2) = resid(1:nconv)

      Write (nout,*)
      Flush (nout)

      outchn = nout
      Call x04abf(iset,outchn)

      ifail = 0
      Call x04caf('G','N',nconv,2,d_print,nconv,' Ritz values and residuals',  &
        ifail)

100   Continue
    End Program f02fkfe


f02gcfe.f90

    Program f02gcfe

!     F02GCF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: f02gcf, nag_wp, x04dbf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: wl, wu
      Integer                          :: i, ifail, lda, ldv, lwork, m, mest,  &
                                          n
!     .. Local Arrays ..
      Complex (Kind=nag_wp), Allocatable :: a(:,:), v(:,:), w(:), work(:)
      Real (Kind=nag_wp), Allocatable  :: rwork(:)
      Integer, Allocatable             :: iwork(:)
      Logical, Allocatable             :: bwork(:)
      Character (1)                    :: clabs(1), rlabs(1)
!     .. Executable Statements ..
      Write (nout,*) 'F02GCF Example Program Results'
!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) n, mest, wl, wu
      lda = n
      ldv = n
      lwork = 64*n
      Allocate (a(lda,n),v(ldv,n),w(n),work(lwork),rwork(2*n),iwork(n),        &
        bwork(n))
!     Read A from data file
      Read (nin,*)(a(i,1:n),i=1,n)

!     Compute selected eigenvalues and eigenvectors of A

!     ifail: behaviour on error exit
!            =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
      ifail = 0
      Call f02gcf('Moduli',n,a,lda,wl,wu,mest,m,w,v,ldv,work,lwork,rwork,      &
        iwork,bwork,ifail)

      Write (nout,*)
      Write (nout,*) 'Eigenvalues'
      Write (nout,99999) w(1:m)
      Write (nout,*)
      Flush (nout)
      ifail = 0
      Call x04dbf('General',' ',n,m,v,ldv,'Bracketed','F7.4','Eigenvectors',   &
        'Integer',rlabs,'Integer',clabs,80,0,ifail)

99999 Format ((3X,4(' (',F7.4,',',F7.4,')',:)))
    End Program f02gcfe


f02jcfe.f90

    Program f02jcfe

!     F02JCF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: f02jcf, x02alf, x04caf
      Use nag_precisions, Only: wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Real (Kind=wp), Parameter        :: one = 1.0_wp
      Real (Kind=wp), Parameter        :: tol = 0.0E0_wp
      Real (Kind=wp), Parameter        :: zero = 0.0_wp
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=wp)                   :: inf, tmp
      Integer                          :: i, ifail, iwarn, j, lda, ldb, ldc,   &
                                          ldvl, ldvr, n, scal, sense, tdvl,    &
                                          tdvr
!     .. Local Arrays ..
      Real (Kind=wp), Allocatable      :: a(:,:), alphai(:), alphar(:),        &
                                          b(:,:), beta(:), bevl(:), bevr(:),   &
                                          c(:,:), ei(:), er(:), s(:), vl(:,:), &
                                          vr(:,:)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: abs
!     .. Executable Statements ..
      Write (nout,*) 'F02JCF Example Program Results'
!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) n
      lda = n
      ldb = n
      ldc = n
      ldvl = n
      ldvr = n
      tdvl = 2*n
      tdvr = 2*n
      Allocate (a(lda,n),b(ldb,n),c(ldc,n),alphai(2*n),alphar(2*n),beta(2*n),  &
        ei(2*n),er(2*n),vl(ldvl,tdvl),vr(ldvr,tdvr),s(2*n),bevr(2*n),          &
        bevl(2*n))

!     Read in the matrices A, B and C
      Read (nin,*)(a(i,1:n),i=1,n)
      Read (nin,*)(b(i,1:n),i=1,n)
      Read (nin,*)(c(i,1:n),i=1,n)

!     Use default scaling and compute eigenvalue condition numbers and
!     backward errors for both left and right eigenpairs
      scal = 1
      sense = 7

!     Solve the quadratic eigenvalue problem

      ifail = -1
      Call f02jcf(scal,'V','V',sense,tol,n,a,lda,b,ldb,c,ldc,alphar,alphai,    &
        beta,vl,ldvl,vr,ldvr,s,bevl,bevr,iwarn,ifail)

      If (iwarn/=0) Then
        Write (nout,*)
        Write (nout,99999) 'Warning from f02jcf. IWARN =', iwarn
      End If

      Write (nout,*)
      If (ifail/=0) Then
        Write (nout,99999) 'Failure in f02jcf. IFAIL =', ifail
      Else
!       Infinity
        inf = x02alf()
        Do j = 1, 2*n
          If (beta(j)>=one) Then
            er(j) = alphar(j)/beta(j)
            ei(j) = alphai(j)/beta(j)
          Else
            tmp = inf*beta(j)
            If ((abs(alphar(j))<tmp) .And. (abs(alphai(j))<tmp)) Then
              er(j) = alphar(j)/beta(j)
              ei(j) = alphai(j)/beta(j)
            Else
              er(j) = inf
              ei(j) = zero
            End If
          End If
          If (er(j)<inf) Then
            Write (nout,99998) 'Eigenvalue(', j, ') = (', er(j), ', ', ei(j),  &
              ')'
          Else
            Write (nout,99997) 'Eigenvalue(', j, ') is infinite'
          End If
        End Do

        Write (nout,*)
        ifail = 0
        Call x04caf('General',' ',n,2*n,vr,ldvr,                               &
          'Right eigenvectors (matrix VR)',ifail)

        Write (nout,*)
        ifail = 0
        Call x04caf('General',' ',n,2*n,vl,ldvl,                               &
          'Left eigenvectors (matrix VL)',ifail)

        Write (nout,*)
        Write (nout,*) 'Eigenvalue Condition numbers'
        Do j = 1, 2*n
          Write (nout,99996) s(j)
        End Do

        Write (nout,*)
        Write (nout,*)                                                         &
          'Backward errors for eigenvalues and right eigenvectors'
        Do j = 1, 2*n
          Write (nout,99996) bevr(j)
        End Do

        Write (nout,*)
        Write (nout,*) 'Backward errors for eigenvalues and left eigenvectors'
        Do j = 1, 2*n
          Write (nout,99996) bevl(j)
        End Do
      End If

99999 Format (1X,A,I4)
99998 Format (1X,A,I3,A,1P,E11.4,A,1P,E11.4,A)
99997 Format (1X,A,I3,A)
99996 Format (1X,1P,E11.4)
    End Program f02jcfe


f02jqfe.f90

    Program f02jqfe

!     F02JQF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: f02jqf, m01def, m01edf, nag_wp, x04caf, x04daf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Real (Kind=nag_wp), Parameter    :: tol = 0.0E0_nag_wp
      Real (Kind=nag_wp), Parameter    :: zero = 0.0E+0_nag_wp
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: t0, t1
      Integer                          :: i, ifail, iwarn, j, lda, ldb, ldc,   &
                                          ldvl, ldvr, n, scal, sense, tdvl,    &
                                          tdvr
      Character (1)                    :: jobvl, jobvr
!     .. Local Arrays ..
      Complex (Kind=nag_wp), Allocatable :: a(:,:), alpha(:), b(:,:), beta(:), &
                                          c(:,:), cvr(:), e(:), vl(:,:),       &
                                          vr(:,:)
      Real (Kind=nag_wp), Allocatable  :: bevl(:), bevr(:), ea(:,:), s(:)
      Integer, Allocatable             :: irank(:)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: abs, all, maxval, real
!     .. Executable Statements ..
      Write (nout,*) 'F02JQF Example Program Results'
!     Skip heading in data file and read in n, scal, sense, jobVL and jobVR
      Read (nin,*)
      Read (nin,*) n, scal, sense
      Read (nin,*) jobvl, jobvr

      lda = n
      ldb = n
      ldc = n
      ldvl = n
      ldvr = n
      tdvl = 2*n
      tdvr = 2*n
      Allocate (a(lda,n),b(ldb,n),c(ldc,n),alpha(2*n),beta(2*n),e(2*n),        &
        vl(ldvl,tdvl),vr(ldvr,tdvr),s(2*n),bevr(2*n),bevl(2*n),cvr(n),         &
        ea(2*n,2),irank(2*n))

!     Read in the matrices A, B and C

      Read (nin,*)(a(i,1:n),i=1,n)
      Read (nin,*)(b(i,1:n),i=1,n)
      Read (nin,*)(c(i,1:n),i=1,n)

!     Solve the quadratic eigenvalue problem
      ifail = -1
      Call f02jqf(scal,jobvl,jobvr,sense,tol,n,a,lda,b,ldb,c,ldc,alpha,beta,   &
        vl,ldvl,vr,ldvr,s,bevl,bevr,iwarn,ifail)
      If (iwarn/=0) Then
        Write (nout,*)
        Write (nout,99999) 'Warning from f02jqf. IWARN =', iwarn
      End If

      Write (nout,*)
      If (ifail/=0) Then
        Write (nout,99999) 'Failure in f02jqf. IFAIL =', ifail
        Go To 100
      End If

      If (all(real(beta(1:2*n))>zero)) Then
        e(1:2*n) = alpha(1:2*n)/beta(1:2*n)
!       Sort eigenvalues by absolute value and then by real part.
!       Add 1000.0 to tie differences of small orders of epsilon.
        ea(1:2*n,1) = 1000.0_nag_wp + abs(e(1:2*n))
        ea(1:2*n,2) = real(e(1:2*n))
        ifail = 0
        Call m01def(ea,2*n,1,2*n,1,2,'Descending',irank,ifail)
        Call m01edf(e,1,2*n,irank,ifail)

!       Print Eigenvalues
        ifail = 0
        Call x04daf('General',' ',1,2*n,e,1,'Eigenvalues:',ifail)

        If (jobvr=='V' .Or. jobvr=='v') Then
!         Sort right eigenvectors using irank
          Do j = 1, n
            e(1:2*n) = vr(j,1:2*n)
            Call m01edf(e,1,2*n,irank,ifail)
            vr(j,1:2*n) = e(1:2*n)
          End Do
        End If
        If (jobvl=='V' .Or. jobvl=='v') Then
!         Sort left eigenvectors using irank
          Do j = 1, n
            e(1:2*n) = vl(j,1:2*n)
            Call m01edf(e,1,2*n,irank,ifail)
            vl(j,1:2*n) = e(1:2*n)
          End Do
        End If
      Else
!       Some eigenvalues are infinite
!       Print alpha and beta
        ifail = 0
        Call x04daf('General',' ',1,2*n,alpha,1,'Alpha:',ifail)
        ifail = 0
        Call x04daf('General',' ',1,2*n,beta,1,'Beta:',ifail)

      End If
      If (jobvr=='V' .Or. jobvr=='v') Then
!       Print Right Eigenvectors
        Write (nout,*)
        ifail = 0
        Call x04daf('G',' ',n,2*n,vr,n,'Right Eigenvectors (columns):',ifail)
      End If
      If (jobvl=='V' .Or. jobvl=='v') Then
!       Print Left Eigenvectors
        Write (nout,*)
        ifail = 0
        Call x04daf('G',' ',n,2*n,vl,n,'Left Eigenvectors (columns):',ifail)
      End If

      If (sense==1 .Or. sense>4) Then
        Write (nout,*)
!       Print Eigenvalues
        ifail = 0
        Call x04caf('G',' ',1,2*n,s,1,'Eigenvalue Condition numbers:',ifail)
      End If

      If (sense==3 .Or. sense==4 .Or. sense>5) Then
        t0 = maxval(bevr)
        Write (nout,*)
        Write (nout,99998)                                                     &
          'Max backward error for eigenvalues and right eigenvectors', t0
      End If

      If (sense==2 .Or. sense==4 .Or. sense==5 .Or. sense==7) Then
        t1 = maxval(bevl)
        Write (nout,*)
        Write (nout,99998)                                                     &
          'Max backward error for eigenvalues and left eigenvectors ', t1
      End If

100   Continue

99999 Format (1X,3(A,I4))
99998 Format (1X,A,1P,E11.1)
    End Program f02jqfe


f02sdfe.f90

    Program f02sdfe

!     F02SDF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: f02sdf, nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: relep, rmu
      Integer                          :: i, ifail, j, k, k1, k2, lda, ldb,    &
                                          lwork, ma, mb, n
      Logical                          :: sym
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: a(:,:), b(:,:), vec(:), work(:)
      Real (Kind=nag_wp)               :: d(30)
      Integer, Allocatable             :: iwork(:)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: min
!     .. Executable Statements ..
      Write (nout,*) 'F02SDF Example Program Results'
!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) n, ma, mb
      lda = 2*ma + 1
      ldb = 2*mb + 1
      lwork = n*(ma+2)
      Allocate (a(lda,n),b(ldb,n),vec(n),work(lwork),iwork(n))
      Do i = 1, n
        k1 = ma + 1 - min(ma,i-1)
        k2 = ma + 1 + min(ma,n-i)
        Read (nin,*)(a(k,i),k=k1,k2)
      End Do
      Do i = 1, n
        k1 = mb + 1 - min(mb,i-1)
        k2 = mb + 1 + min(mb,n-i)
        Read (nin,*)(b(k,i),k=k1,k2)
      End Do
      Read (nin,*) rmu, d(1)
      sym = .False.
      relep = 0.0E0_nag_wp

!     ifail: behaviour on error exit
!             =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
      ifail = 1
      Call f02sdf(n,ma+1,mb+1,a,lda,b,ldb,sym,relep,rmu,vec,d,iwork,work,      &
        lwork,ifail)

      Write (nout,*)
      If (ifail==0) Then
        Write (nout,99999) 'Corrected eigenvalue = ', rmu + d(30)
        Write (nout,*)
        Write (nout,*) 'Eigenvector is'
        Write (nout,99998) vec(1:n)
      Else If (ifail>0) Then
        Write (nout,99997) 'Error in F02SDF. IFAIL =', ifail
        If (ifail==7 .Or. ifail==9) Then
          Write (nout,*)
          Write (nout,*) 'Successive corrections to RMU were'
          Write (nout,*)
          Do j = 1, 29
            If (d(j)==0.0E0_nag_wp) Then
              Go To 100
            End If
            Write (nout,99996) d(j)
          End Do
        End If
      Else
        Write (nout,99995) ifail
      End If
100   Continue

99999 Format (1X,A,F8.4)
99998 Format (1X,5F9.4)
99997 Format (1X,A,I5)
99996 Format (1X,E20.4)
99995 Format (1X,' ** F02SDF returned with IFAIL = ',I5)
    End Program f02sdfe


f02wdfe.f90

    Program f02wdfe

!     F02WDF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: f02wdf, nag_wp, x04cbf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: tol
      Integer                          :: i, ifail, irank, lda, ldpt, ldr,     &
                                          lwork, m, n
      Logical                          :: svd, wantb, wantpt, wantr
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: a(:,:), pt(:,:), r(:,:), sv(:),      &
                                          work(:), z(:)
      Character (1)                    :: clabs(1), rlabs(1)
!     .. Executable Statements ..
      Write (nout,*) 'F02WDF Example Program Results'
!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) m, n
      Write (nout,*)
      lda = m
      ldpt = n
      ldr = n
      lwork = 3*n
      Allocate (a(lda,n),pt(ldpt,n),r(ldr,n),sv(n),work(lwork),z(n))
      svd = .True.
      tol = 5.0E-4_nag_wp
      Read (nin,*)(a(i,1:n),i=1,m)
      wantb = .False.
      wantr = .True.
      wantpt = .True.

!     ifail: behaviour on error exit
!             =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
      ifail = 0
      Call f02wdf(m,n,a,lda,wantb,work,tol,svd,irank,z,sv,wantr,r,ldr,wantpt,  &
        pt,ldpt,work,lwork,ifail)

      Write (nout,99999) 'Rank of A is', irank
      Write (nout,*)
      Flush (nout)

      ifail = 0
      Call x04cbf('General',' ',m,n,a,lda,'F9.3','Details of QU factorization' &
        ,'N',rlabs,'N',clabs,80,0,ifail)

      Write (nout,*)
      Write (nout,*) 'Vector Z'
      Write (nout,99998) z(1:n)
      Write (nout,*)
      Flush (nout)

      ifail = 0
      Call x04cbf('General',' ',n,n,r,ldr,'F9.3','Matrix R','N',rlabs,'N',     &
        clabs,80,0,ifail)

      Write (nout,*)
      Write (nout,*) 'Singular values'
      Write (nout,99998) sv(1:n)
      Write (nout,*)
      Flush (nout)

      ifail = 0
      Call x04cbf('General',' ',n,n,pt,ldpt,'F9.3','Matrix P**T','N',rlabs,    &
        'N',clabs,80,0,ifail)

99999 Format (1X,A,I5,A,I5)
99998 Format (1X,8F9.3)
    End Program f02wdfe


f02wgfe.f90

!   F02WGF Example Program Text
!   Mark 26 Release. NAG Copyright 2016.

    Module f02wgfe_mod

!     F02WGF Example Program Module:
!            Parameters and User-defined Routines

!     .. Use Statements ..
      Use nag_library, Only: nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Accessibility Statements ..
      Private
      Public                           :: av
!     .. Parameters ..
      Integer, Parameter, Public       :: nin = 5, nout = 6
    Contains
!     Matrix vector subroutines

      Subroutine av(iflag,m,n,x,ax,iuser,ruser)

!       Computes  w <- A*x or w <- Trans(A)*x.

!       .. Parameters ..
        Real (Kind=nag_wp), Parameter  :: one = 1.0_nag_wp
        Real (Kind=nag_wp), Parameter  :: zero = 0.0_nag_wp
!       .. Scalar Arguments ..
        Integer, Intent (Inout)        :: iflag
        Integer, Intent (In)           :: m, n
!       .. Array Arguments ..
        Real (Kind=nag_wp), Intent (Inout) :: ax(*), ruser(*)
        Real (Kind=nag_wp), Intent (In) :: x(*)
        Integer, Intent (Inout)        :: iuser(*)
!       .. Local Scalars ..
        Real (Kind=nag_wp)             :: h, k, s, t
        Integer                        :: i, j
!       .. Intrinsic Procedures ..
        Intrinsic                      :: min, real
!       .. Executable Statements ..
        h = one/real(m+1,kind=nag_wp)
        k = one/real(n+1,kind=nag_wp)
        If (iflag==1) Then
          ax(1:m) = zero
          t = zero

          Do j = 1, n
            t = t + k
            s = zero
            Do i = 1, min(j,m)
              s = s + h
              ax(i) = ax(i) + k*s*(t-one)*x(j)
            End Do
            Do i = j + 1, m
              s = s + h
              ax(i) = ax(i) + k*t*(s-one)*x(j)
            End Do
          End Do
        Else
          ax(1:n) = zero
          t = zero

          Do j = 1, n
            t = t + k
            s = zero
            Do i = 1, min(j,m)
              s = s + h
              ax(j) = ax(j) + k*s*(t-one)*x(i)
            End Do
            Do i = j + 1, m
              s = s + h
              ax(j) = ax(j) + k*t*(s-one)*x(i)
            End Do
          End Do
        End If

        Return
      End Subroutine av
    End Module f02wgfe_mod
    Program f02wgfe

!     F02WGF Example Main Program

!     .. Use Statements ..
      Use nag_library, Only: f02wgf, nag_wp
      Use f02wgfe_mod, Only: av, nin, nout
!     .. Implicit None Statement ..
      Implicit None
!     .. Local Scalars ..
      Integer                          :: i, ifail, k, ldu, ldv, m, n, nconv,  &
                                          ncv
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: resid(:), sigma(:), u(:,:), v(:,:)
      Real (Kind=nag_wp)               :: ruser(1)
      Integer                          :: iuser(1)
!     .. Executable Statements ..
      Write (nout,*) 'F02WGF Example Program Results'
      Write (nout,*)
!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) m, n, k, ncv
      ldu = m
      ldv = n
      Allocate (resid(ncv),sigma(ncv),u(ldu,ncv),v(ldv,ncv))

!     ifail: behaviour on error exit
!             =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
      ifail = 0
      Call f02wgf(m,n,k,ncv,av,nconv,sigma,u,ldu,v,ldv,resid,iuser,ruser,      &
        ifail)

!     Print computed residuals
      Write (nout,*) '  Singular Value    Residual'
      Write (nout,99999)(sigma(i),resid(i),i=1,nconv)

99999 Format (1X,F10.5,8X,G10.2)
    End Program f02wgfe


f02wufe.f90

    Program f02wufe

!     F02WUF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: f02wuf, nag_wp, x04cbf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Integer                          :: i, ifail, lda, ldb, ldq, lwork, n,   &
                                          ncolb
      Logical                          :: wantp, wantq
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: a(:,:), b(:), q(:,:), sv(:), work(:)
      Character (1)                    :: clabs(1), rlabs(1)
!     .. Executable Statements ..
      Write (nout,*) 'F02WUF Example Program Results'
      Write (nout,*)
!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) n, ncolb
      lda = n
      ldb = n
      ldq = n
      lwork = 5*(n-1)
      Allocate (a(lda,n),b(ldb),q(ldq,n),sv(n),work(lwork))
      Read (nin,*)(a(i,i:n),i=1,n)
      Read (nin,*) b(1:n)
      wantq = .True.
      wantp = .True.

!     ifail: behaviour on error exit
!             =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
      ifail = 0
!     Find the SVD of A
      Call f02wuf(n,a,lda,ncolb,b,ldb,wantq,q,ldq,sv,wantp,work,ifail)

      Write (nout,*) 'Singular value decomposition of A'
      Write (nout,*)
      Write (nout,*) 'Singular values'
      Write (nout,99999) sv(1:n)
      Write (nout,*)
      Flush (nout)

      ifail = 0
      Call x04cbf('General',' ',n,n,q,ldq,'F8.4',                              &
        'Left-hand singular vectors, by column','N',rlabs,'N',clabs,80,0,      &
        ifail)

      Write (nout,*)
      Write (nout,*) 'Right-hand singular vectors, by column'
      Do i = 1, n
        Write (nout,99999) a(1:n,i)
      End Do
      Write (nout,*)
      Write (nout,*) 'Vector Q''*B'
      Write (nout,99999) b(1:n)

99999 Format (1X,3(1X,F8.4))
    End Program f02wufe


f02xufe.f90

    Program f02xufe

!     F02XUF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: f02xuf, nag_wp, x04dbf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Integer                          :: i, ifail, lcwork, lda, ldb, ldq,     &
                                          lrwork, n, ncolb
      Logical                          :: wantp, wantq
!     .. Local Arrays ..
      Complex (Kind=nag_wp), Allocatable :: a(:,:), b(:), cwork(:), q(:,:)
      Real (Kind=nag_wp), Allocatable  :: rwork(:), sv(:)
      Character (1)                    :: clabs(1), rlabs(1)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: conjg
!     .. Executable Statements ..
      Write (nout,*) 'F02XUF Example Program Results'
      Write (nout,*)
      Flush (nout)
!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) n, ncolb
      lcwork = n - 1
      lda = n
      ldb = n
      ldq = n
      lrwork = 5*(n-1)
      Allocate (a(lda,n),b(ldb),cwork(lcwork),q(ldq,n),rwork(lrwork),sv(n))
      Read (nin,*)(a(i,i:n),i=1,n)
      Read (nin,*) b(1:n)
!     Find the SVD of A.
      wantq = .True.
      wantp = .True.

!     ifail: behaviour on error exit
!             =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
      ifail = 0
      Call f02xuf(n,a,lda,ncolb,b,ldb,wantq,q,ldq,sv,wantp,rwork,cwork,ifail)

      Write (nout,*) 'Singular value decomposition of A'
      Write (nout,*)
      Write (nout,*) 'Singular values'
      Write (nout,99999) sv(1:n)
      Write (nout,*)
      Flush (nout)

      ifail = 0
      Call x04dbf('General',' ',n,n,q,ldq,'Bracketed','F7.4',                  &
        'Left-hand singular vectors, by column','N',rlabs,'N',clabs,80,0,      &
        ifail)

      Write (nout,*)
      Write (nout,*) 'Right-hand singular vectors, by column'
      Do i = 1, n
        Write (nout,99998) conjg(a(1:n,i))
      End Do
      Write (nout,*)
      Write (nout,*) 'Vector conjg( Q'' )*B'
      Write (nout,99998) b(1:n)

99999 Format (1X,3F9.4)
99998 Format (3X,3('(',F7.4,',',F8.4,') ',:))
    End Program f02xufe


f03bafe.f90

    Program f03bafe

!     F03BAF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: dgetrf, f03baf, nag_wp, x04caf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: d
      Integer                          :: i, id, ifail, info, lda, n
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: a(:,:)
      Integer, Allocatable             :: ipiv(:)
!     .. Executable Statements ..
      Write (nout,*) 'F03BAF Example Program Results'

!     Skip heading in data file
      Read (nin,*)

      Read (nin,*) n
      lda = n
      Allocate (a(lda,n),ipiv(n))

      Read (nin,*)(a(i,1:n),i=1,n)

!     LU Factorize A
!     The NAG name equivalent of dgetrf is f07adf
      Call dgetrf(n,n,a,lda,ipiv,info)

      Write (nout,*)
      Flush (nout)
      ifail = 0
      Call x04caf('G','N',n,n,a,lda,'Array A after factorization',ifail)

      Write (nout,*)
      Write (nout,*) 'Pivots'
      Write (nout,99999) ipiv(1:n)
      Write (nout,*)
      Flush (nout)

      ifail = 0
      Call f03baf(n,a,lda,ipiv,d,id,ifail)

      Write (nout,99998) d, id
      Write (nout,*)
      Write (nout,99997) d*2.0_nag_wp**id

99999 Format (1X,8(1X,I13))
99998 Format (1X,'D = ',F13.5,' ID = ',I12)
99997 Format (1X,'Value of determinant = ',E13.5)
    End Program f03bafe


f03bffe.f90

    Program f03bffe

!     F03BFF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: dpotrf, f03bff, nag_wp, x04caf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
      Character (1), Parameter         :: uplo = 'l'
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: d
      Integer                          :: i, id, ifail, info, lda, n
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: a(:,:)
!     .. Executable Statements ..
      Write (nout,*) 'F03BFF Example Program Results'

!     Skip heading in data file
      Read (nin,*)

      Read (nin,*) n
      lda = n
      Allocate (a(lda,n))

      Read (nin,*)(a(i,1:n),i=1,n)

!     Factorize A
!     The NAG name equivalent of dpotrf is f07fdf
      Call dpotrf(uplo,n,a,lda,info)

      Write (nout,*)
      Flush (nout)
      ifail = 0
      Call x04caf('L','N',n,n,a,lda,'Array A after factorization',ifail)

      ifail = 0
      Call f03bff(n,a,lda,d,id,ifail)

      Write (nout,*)
      Write (nout,99999) d, id
      Write (nout,*)
      Write (nout,99998) d*2.0_nag_wp**id

99999 Format (1X,'D = ',F13.5,' ID = ',I12)
99998 Format (1X,'Value of determinant = ',E13.5)
    End Program f03bffe


f03bhfe.f90

    Program f03bhfe

!     F03BHF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: dpbtrf, f03bhf, nag_wp, x04cef
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: d
      Integer                          :: i, id, ifail, info, j, kd, kl, ku,   &
                                          ldab, n
      Character (1)                    :: uplo
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: ab(:,:)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: index, max, min
!     .. Executable Statements ..
      Write (nout,*) 'F03BHF Example Program Results'

!     Skip heading in data file
      Read (nin,*)

      Read (nin,*) uplo

      Read (nin,*) n, kd
      ldab = kd + 1
      Allocate (ab(ldab,n))

      If (index('Ll',uplo)<=0) Then
!       Read in upper triangular banded matrix
        ku = kd
        kl = 0
        Do i = 1, n
          Read (nin,*)(ab(kd+1+i-j,j),j=i,min(i+kd,n))
        End Do
      Else
!       Read in lower triangular banded matrix
        ku = 0
        kl = kd
        Do i = 1, n
          Read (nin,*)(ab(1+i-j,j),j=max(1,i-kd),i)
        End Do
      End If
!     Factorize A
!     The NAG name equivalent of dpbtrf is f07hdf
      Call dpbtrf(uplo,n,kd,ab,ldab,info)

      If (info==0) Then
        Write (nout,*)
        Flush (nout)
        ifail = 0
        Call x04cef(n,n,kl,ku,ab,ldab,'Array AB after factorization',ifail)

        ifail = 0
        Call f03bhf(uplo,n,kd,ab,ldab,d,id,ifail)

        Write (nout,*)
        Write (nout,99999) d, id
        Write (nout,*)
        Write (nout,99998) d*2.0E0_nag_wp**id
      Else
        Write (nout,99997) info
      End If

99999 Format (1X,'D = ',F13.5,' ID = ',I0)
99998 Format (1X,'Value of determinant = ',E13.5)
99997 Format (' ** Factorization routine return error flag info = ',I0,'.')
    End Program f03bhfe


f03bnfe.f90

    Program f03bnfe

!     F03BNF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: f03bnf, nag_wp, x04daf, zgetrf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Real (Kind=nag_wp), Parameter    :: two = 2.0_nag_wp
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Complex (Kind=nag_wp)            :: d
      Integer                          :: i, ifail, info, lda, n
!     .. Local Arrays ..
      Complex (Kind=nag_wp), Allocatable :: a(:,:)
      Integer                          :: id(2)
      Integer, Allocatable             :: ipiv(:)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: aimag, real
!     .. Executable Statements ..
      Write (nout,*) 'F03BNF Example Program Results'

!     Skip heading in data file
      Read (nin,*)

      Read (nin,*) n
      lda = n
      Allocate (a(lda,n),ipiv(n))

      Read (nin,*)(a(i,1:n),i=1,n)

!     LU Factorize A
!     The NAG name equivalent of zgetrf is f07arf
      Call zgetrf(n,n,a,lda,ipiv,info)
      Write (nout,*)
      Flush (nout)

      ifail = 0
      Call x04daf('g','n',n,n,a,lda,'Array A after factorization',ifail)

      Write (nout,*)
      Write (nout,*) 'Pivots'
      Write (nout,99999) ipiv(1:n)
      Write (nout,*)
      Flush (nout)

      ifail = 0
      Call f03bnf(n,a,lda,ipiv,d,id,ifail)

      Write (nout,99998) d, id
      Write (nout,*)
      Write (nout,99997) two**id(1)*real(d), two**id(2)*aimag(d)

99999 Format (1X,8(1X,I13))
99998 Format (1X,'D = (',F13.5,',',F13.5,'), ID = (',I0,', ',I0,')')
99997 Format (1X,'Value of determinant = (',E13.5,',',E13.5,')')
    End Program f03bnfe


f04abfe.f90

    Program f04abfe

!     F04ABF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: f04abf, nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Integer                          :: i, ifail, lda, ldb, ldbb, ldc, m, n
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: a(:,:), b(:,:), bb(:,:), c(:,:),     &
                                          wkspce(:)
!     .. Executable Statements ..
      Write (nout,*) 'F04ABF Example Program Results'
      Write (nout,*)
!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) n, m
      lda = n
      ldb = n
      ldbb = n
      ldc = n
      Allocate (a(lda,n),b(ldb,m),bb(ldbb,m),c(ldc,m),wkspce(n))
      Read (nin,*)(a(i,1:n),i=1,n), (b(i,1:m),i=1,n)

!     ifail: behaviour on error exit
!             =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
      ifail = 0
      Call f04abf(a,lda,b,ldb,n,m,c,ldc,wkspce,bb,ldbb,ifail)

      Write (nout,*) ' Solution'
      Write (nout,99999)(c(i,1:m),i=1,n)

99999 Format (1X,F9.4)
    End Program f04abfe


f04aefe.f90

    Program f04aefe

!     F04AEF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: f04aef, nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Integer                          :: i, ifail, lda, ldaa, ldb, ldbb, ldc, &
                                          m, n
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: a(:,:), aa(:,:), b(:,:), bb(:,:),    &
                                          c(:,:), wkspce(:)
!     .. Executable Statements ..
      Write (nout,*) 'F04AEF Example Program Results'
      Write (nout,*)
!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) n
      lda = n
      ldaa = n
      ldb = n
      ldbb = n
      ldc = n
      m = 1
      Allocate (a(lda,n),aa(ldaa,n),b(ldb,1),bb(ldbb,1),c(ldc,1),wkspce(n))
      Read (nin,*)(a(i,1:n),i=1,n), (b(i,1),i=1,n)

!     ifail: behaviour on error exit
!             =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
      ifail = 0
      Call f04aef(a,lda,b,ldb,n,m,c,ldc,wkspce,aa,ldaa,bb,ldbb,ifail)

      Write (nout,*) ' Solution'
      Write (nout,99999)(c(i,1),i=1,n)

99999 Format (1X,F9.4)
    End Program f04aefe


f04amfe.f90

    Program f04amfe

!     F04AMF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: f04amf, nag_wp, x02ajf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: eps
      Integer                          :: i, ifail, ir, lda, ldb, ldqr, ldx,   &
                                          m, n
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: a(:,:), alpha(:), b(:,:), e(:),      &
                                          qr(:,:), r(:), x(:,:), y(:), z(:)
      Integer, Allocatable             :: ipiv(:)
!     .. Executable Statements ..
      Write (nout,*) 'F04AMF Example Program Results'
      Write (nout,*)
!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) m, n
      ir = 1
      lda = m
      ldb = m
      ldqr = m
      ldx = n
      Allocate (a(lda,n),alpha(n),b(ldb,ir),e(n),qr(ldqr,n),r(m),x(ldx,ir),    &
        y(n),z(n),ipiv(n))
      Read (nin,*)(a(i,1:n),b(i,1:ir),i=1,m)
      eps = x02ajf()

!     ifail: behaviour on error exit
!             =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
      ifail = 0
      Call f04amf(a,lda,x,ldx,b,ldb,m,n,ir,eps,qr,ldqr,alpha,e,y,z,r,ipiv,     &
        ifail)

      Write (nout,*) ' Solution'
      Do i = 1, n
        Write (nout,99999) x(i,1:ir)
      End Do

99999 Format (1X,8F9.4)
    End Program f04amfe


f04asfe.f90

    Program f04asfe

!     F04ASF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: f04asf, nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Integer                          :: i, ifail, lda, n
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: a(:,:), b(:), c(:), wk1(:), wk2(:)
!     .. Executable Statements ..
      Write (nout,*) 'F04ASF Example Program Results'
      Write (nout,*)
!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) n
      lda = n
      Allocate (a(lda,n),b(n),c(n),wk1(n),wk2(n))
      Read (nin,*)(a(i,1:n),i=1,n), b(1:n)

!     ifail: behaviour on error exit
!             =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
      ifail = 0
      Call f04asf(a,lda,b,n,c,wk1,wk2,ifail)

      Write (nout,*) ' Solution'
      Write (nout,99999) c(1:n)

99999 Format (1X,F9.4)
    End Program f04asfe


f04atfe.f90

    Program f04atfe

!     F04ATF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: f04atf, nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Integer                          :: i, ifail, lda, ldaa, n
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: a(:,:), aa(:,:), b(:), c(:),         &
                                          wks1(:), wks2(:)
!     .. Executable Statements ..
      Write (nout,*) 'F04ATF Example Program Results'
      Write (nout,*)
!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) n
      lda = n
      ldaa = n
      Allocate (a(lda,n),aa(ldaa,n),b(n),c(n),wks1(n),wks2(n))
      Read (nin,*)(a(i,1:n),i=1,n), b(1:n)

!     ifail: behaviour on error exit
!             =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
      ifail = 0
      Call f04atf(a,lda,b,n,c,aa,ldaa,wks1,wks2,ifail)

      Write (nout,*) ' Solution'
      Write (nout,99999) c(1:n)

99999 Format (1X,F9.4)
    End Program f04atfe


f04axfe.f90

    Program f04axfe

!     F04AXF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: f01brf, f04axf, nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: resid, u
      Integer                          :: i, ifail, licn, lirn, mtype, n, nz
      Logical                          :: grow, lblock
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: a(:), rhs(:), w(:)
      Integer, Allocatable             :: icn(:), ikeep(:,:), irn(:), iw(:,:)
      Integer                          :: idisp(10)
      Logical                          :: abort(4)
!     .. Executable Statements ..
      Write (nout,*) 'F04AXF Example Program Results'
      Write (nout,*)
!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) n, nz
      licn = 3*nz
      lirn = 3*nz/2
      Allocate (a(licn),rhs(n),w(n),icn(licn),ikeep(n,5),irn(lirn),iw(n,8))
      Read (nin,*)(a(i),irn(i),icn(i),i=1,nz)
      u = 0.1E0_nag_wp
      lblock = .True.
      grow = .True.
      abort(1) = .True.
      abort(2) = .True.
      abort(3) = .False.
      abort(4) = .True.

!     ifail: behaviour on error exit
!             =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
      ifail = 0
!     Decomposition of sparse matrix
      Call f01brf(n,nz,a,licn,irn,lirn,icn,u,ikeep,iw,w,lblock,grow,abort,     &
        idisp,ifail)

      If (grow) Then
        Write (nout,*) 'On exit from F01BRF'
        Write (nout,99999) 'Value of W(1) = ', w(1)
      End If
      Read (nin,*) rhs(1:n)
      mtype = 1

!     Approximate solution of sparse linear equations
      Call f04axf(n,a,licn,icn,ikeep,rhs,w,mtype,idisp,resid)

      Write (nout,*)
      Write (nout,*) 'On exit from F04AXF'
      Write (nout,*) ' Solution'
      Write (nout,99998) rhs(1:n)

99999 Format (1X,A,F9.4)
99998 Format (1X,F9.4)
    End Program f04axfe


f04bafe.f90

    Program f04bafe

!     F04BAF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: f04baf, nag_wp, x04caf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: errbnd, rcond
      Integer                          :: i, ierr, ifail, lda, ldb, n, nrhs
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: a(:,:), b(:,:)
      Integer, Allocatable             :: ipiv(:)
!     .. Executable Statements ..
      Write (nout,*) 'F04BAF Example Program Results'
      Write (nout,*)
      Flush (nout)
!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) n, nrhs
      lda = n
      ldb = n
      Allocate (a(lda,n),b(ldb,nrhs),ipiv(n))
!     Read A and B from data file

      Read (nin,*)(a(i,1:n),i=1,n)
      Read (nin,*)(b(i,1:nrhs),i=1,n)

!     Solve the equations AX = B for X

!     ifail: behaviour on error exit
!            =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
      ifail = 1
      Call f04baf(n,nrhs,a,lda,ipiv,b,ldb,rcond,errbnd,ifail)

      If (ifail==0) Then
!       Print solution, estimate of condition number and approximate
!       error bound

        ierr = 0
        Call x04caf('General',' ',n,nrhs,b,ldb,'Solution',ierr)

        Write (nout,*)
        Write (nout,*) 'Estimate of condition number'
        Write (nout,99999) 1.0E0_nag_wp/rcond
        Write (nout,*)
        Write (nout,*) 'Estimate of error bound for computed solutions'
        Write (nout,99999) errbnd
      Else If (ifail==n+1) Then
!       Matrix A is numerically singular.  Print estimate of
!       reciprocal of condition number and solution

        Write (nout,*)
        Write (nout,*) 'Estimate of reciprocal of condition number'
        Write (nout,99999) rcond
        Write (nout,*)
        Flush (nout)

        ierr = 0
        Call x04caf('General',' ',n,nrhs,b,ldb,'Solution',ierr)

      Else If (ifail>0 .And. ifail<=n) Then
!       The upper triangular matrix U is exactly singular.  Print
!       details of factorization
        Write (nout,*)
        Flush (nout)

        ierr = 0
        Call x04caf('General',' ',n,n,a,lda,'Details of factorization',ierr)

!       Print pivot indices
        Write (nout,*)
        Write (nout,*) 'Pivot indices'
        Write (nout,99998) ipiv(1:n)
      Else
        Write (nout,99997) ifail
      End If

99999 Format (6X,1P,E9.1)
99998 Format ((1X,7I11))
99997 Format (1X,' ** F04BAF returned with IFAIL = ',I5)
    End Program f04bafe


f04bbfe.f90

    Program f04bbfe

!     F04BBF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: f04bbf, nag_wp, x04caf, x04cef
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: errbnd, rcond
      Integer                          :: i, ierr, ifail, j, k, kl, ku, ldab,  &
                                          ldb, n, nrhs
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: ab(:,:), b(:,:)
      Integer, Allocatable             :: ipiv(:)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: max, min
!     .. Executable Statements ..
      Write (nout,*) 'F04BBF Example Program Results'
      Write (nout,*)
      Flush (nout)
!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) n, kl, ku, nrhs
      ldab = 2*kl + ku + 1
      ldb = n
      Allocate (ab(ldab,n),b(ldb,nrhs),ipiv(n))
!     Read A and B from data file
      k = kl + ku + 1
      Read (nin,*)((ab(k+i-j,j),j=max(i-kl,1),min(i+ku,n)),i=1,n)
      Read (nin,*)(b(i,1:nrhs),i=1,n)

!     Solve the equations AX = B for X

!     ifail: behaviour on error exit
!            =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
      ifail = 1
      Call f04bbf(n,kl,ku,nrhs,ab,ldab,ipiv,b,ldb,rcond,errbnd,ifail)

      If (ifail==0) Then

!       Print solution, estimate of condition number and approximate
!       error bound

        ierr = 0
        Call x04caf('General',' ',n,nrhs,b,ldb,'Solution',ierr)

        Write (nout,*)
        Write (nout,*) 'Estimate of condition number'
        Write (nout,99999) 1.0E0_nag_wp/rcond
        Write (nout,*)
        Write (nout,*) 'Estimate of error bound for computed solutions'
        Write (nout,99999) errbnd
      Else If (ifail==n+1) Then

!       Matrix A is numerically singular.  Print estimate of
!       reciprocal of condition number and solution

        Write (nout,*)
        Write (nout,*) 'Estimate of reciprocal of condition number'
        Write (nout,99999) rcond
        Write (nout,*)
        Flush (nout)

        ierr = 0
        Call x04caf('General',' ',n,nrhs,b,ldb,'Solution',ierr)

      Else If (ifail>0 .And. ifail<=n) Then

!       The upper triangular matrix U is exactly singular.  Print
!       details of factorization
        Write (nout,*)
        Flush (nout)

        ierr = 0
        Call x04cef(n,n,kl,kl+ku,ab,ldab,'Details of factorization',ierr)

!       Print pivot indices
        Write (nout,*)
        Write (nout,*) 'Pivot indices'
        Write (nout,99998) ipiv(1:n)
      Else
        Write (nout,99997) ifail
      End If

99999 Format (6X,1P,E9.1)
99998 Format ((1X,7I11))
99997 Format (1X,' ** F04BBF returned with IFAIL = ',I5)
    End Program f04bbfe


f04bcfe.f90

    Program f04bcfe

!     F04BCF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: f04bcf, nag_wp, x04caf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: errbnd, rcond
      Integer                          :: i, ierr, ifail, ldb, n, nrhs
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: b(:,:), d(:), dl(:), du(:), du2(:)
      Integer, Allocatable             :: ipiv(:)
!     .. Executable Statements ..
      Write (nout,*) 'F04BCF Example Program Results'
      Write (nout,*)
      Flush (nout)
!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) n, nrhs
      ldb = n
      Allocate (b(ldb,nrhs),d(n),dl(n-1),du(n-1),du2(n-2),ipiv(n))
!     Read A and B from data file

      Read (nin,*) du(1:n-1)
      Read (nin,*) d(1:n)
      Read (nin,*) dl(1:n-1)
      Read (nin,*)(b(i,1:nrhs),i=1,n)

!     Solve the equations AX = B for X

!     ifail: behaviour on error exit
!            =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
      ifail = 1
      Call f04bcf(n,nrhs,dl,d,du,du2,ipiv,b,ldb,rcond,errbnd,ifail)

      If (ifail==0) Then
!       Print solution, estimate of condition number and approximate
!       error bound

        ierr = 0
        Call x04caf('General',' ',n,nrhs,b,ldb,'Solution',ierr)

        Write (nout,*)
        Write (nout,*) 'Estimate of condition number'
        Write (nout,99999) 1.0E0_nag_wp/rcond
        Write (nout,*)
        Write (nout,*) 'Estimate of error bound for computed solutions'
        Write (nout,99999) errbnd
      Else If (ifail==n+1) Then
!       Matrix A is numerically singular.  Print estimate of
!       reciprocal of condition number and solution

        Write (nout,*)
        Write (nout,*) 'Estimate of reciprocal of condition number'
        Write (nout,99999) rcond

        Write (nout,*)
        Flush (nout)
        ierr = 0
        Call x04caf('General',' ',n,nrhs,b,ldb,'Solution',ierr)

      Else If (ifail>0 .And. ifail<=n) Then
!       The upper triangular matrix U is exactly singular.  Print
!       details of factorization

        Write (nout,*) 'Details of factorization'
        Write (nout,*)
        Write (nout,*) ' Second superdiagonal of U'
        Write (nout,99998) du2(1:n-2)
        Write (nout,*)
        Write (nout,*) ' First superdiagonal of U'
        Write (nout,99998) du(1:n-1)
        Write (nout,*)
        Write (nout,*) ' Main diagonal of U'
        Write (nout,99998) d(1:n)
        Write (nout,*)
        Write (nout,*) ' Multipliers'
        Write (nout,99998) dl(1:n-1)
        Write (nout,*)
        Write (nout,*) ' Vector of interchanges'
        Write (nout,99997) ipiv(1:n)
      Else
        Write (nout,99996) ifail
      End If

99999 Format (6X,1P,E9.1)
99998 Format (1X,8F9.4)
99997 Format (1X,8I9)
99996 Format (1X,' ** F04BCF returned with IFAIL = ',I5)
    End Program f04bcfe


f04bdfe.f90

    Program f04bdfe

!     F04BDF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: f04bdf, nag_wp, x04caf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: errbnd, rcond
      Integer                          :: i, ierr, ifail, lda, ldb, n, nrhs
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: a(:,:), b(:,:)
!     .. Executable Statements ..
      Write (nout,*) 'F04BDF Example Program Results'
      Write (nout,*)
      Flush (nout)
!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) n, nrhs
      lda = n
      ldb = n
      Allocate (a(lda,n),b(ldb,nrhs))
!     Read the upper triangular part of A from data file
      Read (nin,*)(a(i,i:n),i=1,n)

!     Read B from data file
      Read (nin,*)(b(i,1:nrhs),i=1,n)

!     Solve the equations AX = B for X

!     ifail: behaviour on error exit
!            =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
      ifail = 1
      Call f04bdf('Upper',n,nrhs,a,lda,b,ldb,rcond,errbnd,ifail)

      If (ifail==0) Then
!       Print solution, estimate of condition number and approximate
!       error bound

        ierr = 0
        Call x04caf('General',' ',n,nrhs,b,ldb,'Solution',ierr)

        Write (nout,*)
        Write (nout,*) 'Estimate of condition number'
        Write (nout,99999) 1.0E0_nag_wp/rcond
        Write (nout,*)
        Write (nout,*) 'Estimate of error bound for computed solutions'
        Write (nout,99999) errbnd
      Else If (ifail==n+1) Then
!       Matrix A is numerically singular.  Print estimate of
!       reciprocal of condition number and solution
        Write (nout,*)
        Write (nout,*) 'Estimate of reciprocal of condition number'
        Write (nout,99999) rcond
        Write (nout,*)
        Flush (nout)

        ierr = 0
        Call x04caf('General',' ',n,nrhs,b,ldb,'Solution',ierr)

      Else If (ifail>0 .And. ifail<=n) Then
!       The matrix A is not positive definite to working precision
        Write (nout,99998) 'The leading minor of order ', ifail,               &
          ' is not positive definite'
      Else
        Write (nout,99997) ifail
      End If

99999 Format (6X,1P,E9.1)
99998 Format (1X,A,I3,A)
99997 Format (1X,' ** F04BDF returned with IFAIL = ',I5)
    End Program f04bdfe


f04befe.f90

    Program f04befe

!     F04BEF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: f04bef, nag_wp, x04caf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
      Character (1), Parameter         :: uplo = 'U'
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: errbnd, rcond
      Integer                          :: i, ierr, ifail, j, ldb, n, nrhs
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: ap(:), b(:,:)
!     .. Executable Statements ..
      Write (nout,*) 'F04BEF Example Program Results'
      Write (nout,*)
      Flush (nout)
!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) n, nrhs
      ldb = n
      Allocate (ap((n*(n+1))/2),b(ldb,nrhs))

!     Read the upper or lower triangular part of the matrix A from
!     data file

      If (uplo=='U') Then
        Read (nin,*)((ap(i+(j*(j-1))/2),j=i,n),i=1,n)
      Else If (uplo=='L') Then
        Read (nin,*)((ap(i+((2*n-j)*(j-1))/2),j=1,i),i=1,n)
      End If

!     Read B from data file
      Read (nin,*)(b(i,1:nrhs),i=1,n)

!     Solve the equations AX = B for X

!     ifail: behaviour on error exit
!            =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
      ifail = 1
      Call f04bef(uplo,n,nrhs,ap,b,ldb,rcond,errbnd,ifail)

      If (ifail==0) Then
!       Print solution, estimate of condition number and approximate
!       error bound

        ierr = 0
        Call x04caf('General',' ',n,nrhs,b,ldb,'Solution',ierr)

        Write (nout,*)
        Write (nout,*) 'Estimate of condition number'
        Write (nout,99999) 1.0E0_nag_wp/rcond
        Write (nout,*)
        Write (nout,*) 'Estimate of error bound for computed solutions'
        Write (nout,99999) errbnd
      Else If (ifail==n+1) Then
!       Matrix A is numerically singular.  Print estimate of
!       reciprocal of condition number and solution
        Write (nout,*)
        Write (nout,*) 'Estimate of reciprocal of condition number'
        Write (nout,99999) rcond
        Write (nout,*)
        Flush (nout)

        ierr = 0
        Call x04caf('General',' ',n,nrhs,b,ldb,'Solution',ierr)

      Else If (ifail>0 .And. ifail<=n) Then
!       The matrix A is not positive definite to working precision
        Write (nout,99998) 'The leading minor of order ', ifail,               &
          ' is not positive definite'
      Else
        Write (nout,99997) ifail
      End If

99999 Format (6X,1P,E9.1)
99998 Format (1X,A,I3,A)
99997 Format (1X,' ** F04BEF returned with IFAIL = ',I5)
    End Program f04befe


f04bffe.f90

    Program f04bffe

!     F04BFF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: f04bff, nag_wp, x04caf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
      Character (1), Parameter         :: uplo = 'U'
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: errbnd, rcond
      Integer                          :: i, ierr, ifail, j, kd, ldab, ldb, n, &
                                          nrhs
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: ab(:,:), b(:,:)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: max, min
!     .. Executable Statements ..
      Write (nout,*) 'F04BFF Example Program Results'
      Write (nout,*)
      Flush (nout)
!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) n, kd, nrhs
      ldab = kd + 1
      ldb = n
      Allocate (ab(ldab,n),b(ldb,nrhs))
!     Read the upper or lower triangular part of the band matrix A
!     from data file
      If (uplo=='U') Then
        Do i = 1, n
          Read (nin,*)(ab(kd+1+i-j,j),j=i,min(n,i+kd))
        End Do
      Else If (uplo=='L') Then
        Do i = 1, n
          Read (nin,*)(ab(1+i-j,j),j=max(1,i-kd),i)
        End Do
      End If

!     Read B from data file
      Read (nin,*)(b(i,1:nrhs),i=1,n)

!     Solve the equations AX = B for X

!     ifail: behaviour on error exit
!            =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
      ifail = 1
      Call f04bff(uplo,n,kd,nrhs,ab,ldab,b,ldb,rcond,errbnd,ifail)

      If (ifail==0) Then
!       Print solution, estimate of condition number and approximate
!       error bound

        ierr = 0
        Call x04caf('General',' ',n,nrhs,b,ldb,'Solution',ierr)

        Write (nout,*)
        Write (nout,*) 'Estimate of condition number'
        Write (nout,99999) 1.0E0_nag_wp/rcond
        Write (nout,*)
        Write (nout,*) 'Estimate of error bound for computed solutions'
        Write (nout,99999) errbnd
      Else If (ifail==n+1) Then
!       Matrix A is numerically singular.  Print estimate of
!       reciprocal of condition number and solution
        Write (nout,*)
        Write (nout,*) 'Estimate of reciprocal of condition number'
        Write (nout,99999) rcond
        Write (nout,*)
        Flush (nout)

        ierr = 0
        Call x04caf('General',' ',n,nrhs,b,ldb,'Solution',ierr)

      Else If (ifail>0 .And. ifail<=n) Then
!       The matrix A is not positive definite to working precision
        Write (nout,99998) 'The leading minor of order ', ifail,               &
          ' is not positive definite'
      Else
        Write (nout,99997) ifail
      End If

99999 Format (6X,1P,E9.1)
99998 Format (1X,A,I3,A)
99997 Format (1X,' ** F04BFF returned with IFAIL = ',I5)
    End Program f04bffe


f04bgfe.f90

    Program f04bgfe

!     F04BGF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: f04bgf, nag_wp, x04caf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: errbnd, rcond
      Integer                          :: i, ierr, ifail, ldb, n, nrhs
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: b(:,:), d(:), e(:)
!     .. Executable Statements ..
      Write (nout,*) 'F04BGF Example Program Results'
      Write (nout,*)
      Flush (nout)
!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) n, nrhs
      ldb = n
      Allocate (b(ldb,nrhs),d(n),e(n-1))
!     Read A from data file
      Read (nin,*) d(1:n)
      Read (nin,*) e(1:n-1)

!     Read B from data file
      Read (nin,*)(b(i,1:nrhs),i=1,n)

!     Solve the equations AX = B for X

!     ifail: behaviour on error exit
!            =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
      ifail = 1
      Call f04bgf(n,nrhs,d,e,b,ldb,rcond,errbnd,ifail)

      If (ifail==0) Then
!       Print solution, estimate of condition number and approximate
!       error bound

        ierr = 0
        Call x04caf('General',' ',n,nrhs,b,ldb,'Solution',ierr)

        Write (nout,*)
        Write (nout,*) 'Estimate of condition number'
        Write (nout,99999) 1.0E0_nag_wp/rcond
        Write (nout,*)
        Write (nout,*) 'Estimate of error bound for computed solutions'
        Write (nout,99999) errbnd
      Else If (ifail==n+1) Then
!       Matrix A is numerically singular.  Print estimate of
!       reciprocal of condition number and solution
        Write (nout,*)
        Write (nout,*) 'Estimate of reciprocal of condition number'
        Write (nout,99999) rcond
        Write (nout,*)
        Flush (nout)

        ierr = 0
        Call x04caf('General',' ',n,nrhs,b,ldb,'Solution',ierr)

      Else If (ifail>0 .And. ifail<=n) Then
        Write (nout,99998) 'The leading minor of order ', ifail,               &
          ' is not positive definite'
      Else
        Write (nout,99997) ifail
      End If

99999 Format (6X,1P,E9.1)
99998 Format (1X,A,I3,A)
99997 Format (1X,' ** F04BGF returned with IFAIL = ',I5)
    End Program f04bgfe


f04bhfe.f90

    Program f04bhfe

!     F04BHF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: f04bhf, nag_wp, x04caf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: errbnd, rcond
      Integer                          :: i, ierr, ifail, lda, ldb, n, nrhs
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: a(:,:), b(:,:)
      Integer, Allocatable             :: ipiv(:)
!     .. Executable Statements ..
      Write (nout,*) 'F04BHF Example Program Results'
      Write (nout,*)
      Flush (nout)
!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) n, nrhs
      lda = n
      ldb = n
      Allocate (a(lda,n),b(ldb,nrhs),ipiv(n))
!     Read the upper triangular part of A from data file
      Read (nin,*)(a(i,i:n),i=1,n)

!     Read B from data file
      Read (nin,*)(b(i,1:nrhs),i=1,n)

!     Solve the equations AX = B for X

!     ifail: behaviour on error exit
!            =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
      ifail = 1
      Call f04bhf('Upper',n,nrhs,a,lda,ipiv,b,ldb,rcond,errbnd,ifail)

      If (ifail==0) Then
!       Print solution, estimate of condition number and approximate
!       error bound

        ierr = 0
        Call x04caf('General',' ',n,nrhs,b,ldb,'Solution',ierr)

        Write (nout,*)
        Write (nout,*) 'Estimate of condition number'
        Write (nout,99999) 1.0E0_nag_wp/rcond
        Write (nout,*)
        Write (nout,*) 'Estimate of error bound for computed solutions'
        Write (nout,99999) errbnd
      Else If (ifail==n+1) Then
!       Matrix A is numerically singular.  Print estimate of
!       reciprocal of condition number and solution
        Write (nout,*)
        Write (nout,*) 'Estimate of reciprocal of condition number'
        Write (nout,99999) rcond
        Write (nout,*)
        Flush (nout)

        ierr = 0
        Call x04caf('General',' ',n,nrhs,b,ldb,'Solution',ierr)

      Else If (ifail>0 .And. ifail<=n) Then
!       The upper triangular matrix U is exactly singular.  Print
!       details of factorization
        Write (nout,*)
        Flush (nout)

        ierr = 0
        Call x04caf('Upper','Non-unit diagonal',n,n,a,lda,                     &
          'Details of factorization',ierr)

!       Print pivot indices
        Write (nout,*)
        Write (nout,*) 'Pivot indices'
        Write (nout,99998) ipiv(1:n)
      Else
        Write (nout,99997) ifail
      End If

99999 Format (6X,1P,E9.1)
99998 Format ((1X,7I11))
99997 Format (1X,' ** F04BHF returned with IFAIL = ',I5)
    End Program f04bhfe


f04bjfe.f90

    Program f04bjfe

!     F04BJF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: f04bjf, nag_wp, x04caf, x04ccf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
      Character (1), Parameter         :: uplo = 'U'
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: errbnd, rcond
      Integer                          :: i, ierr, ifail, j, ldb, n, nrhs
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: ap(:), b(:,:)
      Integer, Allocatable             :: ipiv(:)
!     .. Executable Statements ..
      Write (nout,*) 'F04BJF Example Program Results'
      Write (nout,*)
      Flush (nout)
!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) n, nrhs
      ldb = n
      Allocate (ap((n*(n+1))/2),b(ldb,nrhs),ipiv(n))
!     Read the upper or lower triangular part of the matrix A from
!     data file
      If (uplo=='U') Then
        Read (nin,*)((ap(i+(j*(j-1))/2),j=i,n),i=1,n)
      Else If (uplo=='L') Then
        Read (nin,*)((ap(i+((2*n-j)*(j-1))/2),j=1,i),i=1,n)
      End If

!     Read B from data file
      Read (nin,*)(b(i,1:nrhs),i=1,n)

!     Solve the equations AX = B for X

!     ifail: behaviour on error exit
!            =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
      ifail = 1
      Call f04bjf(uplo,n,nrhs,ap,ipiv,b,ldb,rcond,errbnd,ifail)

      If (ifail==0) Then
!       Print solution, estimate of condition number and approximate
!       error bound

        ierr = 0
        Call x04caf('General',' ',n,nrhs,b,ldb,'Solution',ierr)

        Write (nout,*)
        Write (nout,*) 'Estimate of condition number'
        Write (nout,99999) 1.0E0_nag_wp/rcond
        Write (nout,*)
        Write (nout,*) 'Estimate of error bound for computed solutions'
        Write (nout,99999) errbnd
      Else If (ifail==n+1) Then
!       Matrix A is numerically singular.  Print estimate of
!       reciprocal of condition number and solution
        Write (nout,*)
        Write (nout,*) 'Estimate of reciprocal of condition number'
        Write (nout,99999) rcond
        Write (nout,*)
        Flush (nout)

        ierr = 0
        Call x04caf('General',' ',n,nrhs,b,ldb,'Solution',ierr)

      Else If (ifail>0 .And. ifail<=n) Then
!       The upper triangular matrix U is exactly singular.  Print
!       details of factorization
        Write (nout,*)
        Flush (nout)

        ierr = 0
        Call x04ccf(uplo,'Non-unit diagonal',n,ap,'Details of factorization',  &
          ierr)

!       Print pivot indices
        Write (nout,*)
        Write (nout,*) 'Pivot indices'
        Write (nout,99998) ipiv(1:n)
      Else
        Write (nout,99997) ifail
      End If

99999 Format (6X,1P,E9.1)
99998 Format ((3X,7I11))
99997 Format (1X,' ** F04BJF returned with IFAIL = ',I5)
    End Program f04bjfe


f04cafe.f90

    Program f04cafe

!     F04CAF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: f04caf, nag_wp, x04dbf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: errbnd, rcond
      Integer                          :: i, ierr, ifail, lda, ldb, n, nrhs
!     .. Local Arrays ..
      Complex (Kind=nag_wp), Allocatable :: a(:,:), b(:,:)
      Integer, Allocatable             :: ipiv(:)
      Character (1)                    :: clabs(1), rlabs(1)
!     .. Executable Statements ..
      Write (nout,*) 'F04CAF Example Program Results'
      Write (nout,*)
      Flush (nout)
!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) n, nrhs
      lda = n
      ldb = n
      Allocate (a(lda,n),b(ldb,nrhs),ipiv(n))
!     Read A and B from data file

      Read (nin,*)(a(i,1:n),i=1,n)
      Read (nin,*)(b(i,1:nrhs),i=1,n)

!     Solve the equations AX = B for X

!     ifail: behaviour on error exit
!            =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
      ifail = 1
      Call f04caf(n,nrhs,a,lda,ipiv,b,ldb,rcond,errbnd,ifail)

      If (ifail==0) Then
!       Print solution, estimate of condition number and approximate
!       error bound

        ierr = 0
        Call x04dbf('General',' ',n,nrhs,b,ldb,'Bracketed',' ','Solution',     &
          'Integer',rlabs,'Integer',clabs,80,0,ierr)

        Write (nout,*)
        Write (nout,*) 'Estimate of condition number'
        Write (nout,99999) 1.0E0_nag_wp/rcond
        Write (nout,*)
        Write (nout,*) 'Estimate of error bound for computed solutions'
        Write (nout,99999) errbnd
      Else If (ifail==n+1) Then
!       Matrix is numerically singular.  Print estimate of
!       reciprocal of condition number and solution
        Write (nout,*)
        Write (nout,*) 'Estimate of reciprocal of condition number'
        Write (nout,99999) rcond
        Write (nout,*)
        Flush (nout)

        ierr = 0
        Call x04dbf('General',' ',n,nrhs,b,ldb,'Bracketed',' ','Solution',     &
          'Integer',rlabs,'Integer',clabs,80,0,ierr)

      Else If (ifail>0 .And. ifail<=n) Then
!       The upper triangular matrix U is exactly singular.  Print
!       details of factorization
        Write (nout,*)
        Flush (nout)

        ierr = 0
        Call x04dbf('General',' ',n,n,a,lda,'Bracketed','F7.4',                &
          'Details of factorization','Integer',rlabs,'Integer',clabs,80,0,     &
          ierr)

!       Print pivot indices
        Write (nout,*)
        Write (nout,*) 'Pivot indices'
        Write (nout,99998) ipiv(1:n)
      Else
        Write (nout,99997) ifail
      End If

99999 Format (8X,1P,E9.1)
99998 Format ((1X,7I11))
99997 Format (1X,' ** F04CAF returned with IFAIL = ',I5)
    End Program f04cafe


f04cbfe.f90

    Program f04cbfe

!     F04CBF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: f04cbf, nag_wp, x04dbf, x04dff
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: errbnd, rcond
      Integer                          :: i, ierr, ifail, j, k, kl, ku, ldab,  &
                                          ldb, n, nrhs
!     .. Local Arrays ..
      Complex (Kind=nag_wp), Allocatable :: ab(:,:), b(:,:)
      Integer, Allocatable             :: ipiv(:)
      Character (1)                    :: clabs(1), rlabs(1)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: max, min
!     .. Executable Statements ..
      Write (nout,*) 'F04CBF Example Program Results'
      Write (nout,*)
      Flush (nout)
!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) n, kl, ku, nrhs
      ldab = 2*kl + ku + 1
      ldb = n
      Allocate (ab(ldab,n),b(ldb,nrhs),ipiv(n))
!     Read A and B from data file

      k = kl + ku + 1
      Read (nin,*)((ab(k+i-j,j),j=max(i-kl,1),min(i+ku,n)),i=1,n)
      Read (nin,*)(b(i,1:nrhs),i=1,n)

!     Solve the equations AX = B for X

!     ifail: behaviour on error exit
!            =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
      ifail = 1
      Call f04cbf(n,kl,ku,nrhs,ab,ldab,ipiv,b,ldb,rcond,errbnd,ifail)

      If (ifail==0) Then
!       Print solution, estimate of condition number and approximate
!       error bound

        ierr = 0
        Call x04dbf('General',' ',n,nrhs,b,ldb,'Bracketed','F7.4','Solution',  &
          'Integer',rlabs,'Integer',clabs,80,0,ierr)

        Write (nout,*)
        Write (nout,*) 'Estimate of condition number'
        Write (nout,99999) 1.0E0_nag_wp/rcond
        Write (nout,*)
        Write (nout,*) 'Estimate of error bound for computed solutions'
        Write (nout,99999) errbnd
      Else If (ifail==n+1) Then
!       Matrix A is numerically singular.  Print estimate of
!       reciprocal of condition number and solution
        Write (nout,*)
        Write (nout,*) 'Estimate of reciprocal of condition number'
        Write (nout,99999) rcond
        Write (nout,*)
        Flush (nout)

        ierr = 0
        Call x04dbf('General',' ',n,nrhs,b,ldb,'Bracketed','F7.4','Solution',  &
          'Integer',rlabs,'Integer',clabs,80,0,ierr)

      Else If (ifail>0 .And. ifail<=n) Then
!       The upper triangular matrix U is exactly singular.  Print
!       details of factorization
        Write (nout,*)
        Flush (nout)

        ierr = 0
        Call x04dff(n,n,kl,kl+ku,ab,ldab,'Bracketed','F7.4',                   &
          'Details of factorization','None',rlabs,'None',clabs,80,0,ierr)

!       Print pivot indices
        Write (nout,*)
        Write (nout,*) 'Pivot indices'
        Write (nout,99998) ipiv(1:n)
      Else
        Write (nout,99997) ifail
      End If

99999 Format (4X,1P,E9.1)
99998 Format ((1X,7I11))
99997 Format (1X,' ** F04CBF returned with IFAIL = ',I5)
    End Program f04cbfe


f04ccfe.f90

    Program f04ccfe

!     F04CCF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: f04ccf, nag_wp, x04dbf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: errbnd, rcond
      Integer                          :: i, ierr, ifail, ldb, n, nrhs
!     .. Local Arrays ..
      Complex (Kind=nag_wp), Allocatable :: b(:,:), d(:), dl(:), du(:), du2(:)
      Integer, Allocatable             :: ipiv(:)
      Character (1)                    :: clabs(1), rlabs(1)
!     .. Executable Statements ..
      Write (nout,*) 'F04CCF Example Program Results'
      Write (nout,*)
      Flush (nout)
!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) n, nrhs
      ldb = n
      Allocate (b(ldb,nrhs),d(n),dl(n-1),du(n-1),du2(n-2),ipiv(n))
!     Read A and B from data file

      Read (nin,*) du(1:n-1)
      Read (nin,*) d(1:n)
      Read (nin,*) dl(1:n-1)
      Read (nin,*)(b(i,1:nrhs),i=1,n)

!     Solve the equations AX = B for X

!     ifail: behaviour on error exit
!            =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
      ifail = 1
      Call f04ccf(n,nrhs,dl,d,du,du2,ipiv,b,ldb,rcond,errbnd,ifail)

      If (ifail==0) Then
!       Print solution, estimate of condition number and approximate
!       error bound

        ierr = 0
        Call x04dbf('General',' ',n,nrhs,b,ldb,'Bracketed',' ','Solution',     &
          'Integer',rlabs,'Integer',clabs,80,0,ierr)

        Write (nout,*)
        Write (nout,*) 'Estimate of condition number'
        Write (nout,99999) 1.0E0_nag_wp/rcond
        Write (nout,*)
        Write (nout,*) 'Estimate of error bound for computed solutions'
        Write (nout,99999) errbnd
      Else If (ifail==n+1) Then
!       Matrix A is numerically singular.  Print estimate of
!       reciprocal of condition number and solution
        Write (nout,*)
        Write (nout,*) 'Estimate of reciprocal of condition number'
        Write (nout,99999) rcond
        Write (nout,*)
        Flush (nout)

        ierr = 0
        Call x04dbf('General',' ',n,nrhs,b,ldb,'Bracketed',' ','Solution',     &
          'Integer',rlabs,'Integer',clabs,80,0,ierr)

      Else If (ifail>0 .And. ifail<=n) Then
!       The upper triangular matrix U is exactly singular.  Print
!       details of factorization
        Write (nout,*) 'Details of factorization'
        Write (nout,*)
        Write (nout,*) ' Second superdiagonal of U'
        Write (nout,99998) du2(1:n-2)
        Write (nout,*)
        Write (nout,*) ' First superdiagonal of U'
        Write (nout,99998) du(1:n-1)
        Write (nout,*)
        Write (nout,*) ' Main diagonal of U'
        Write (nout,99998) d(1:n)
        Write (nout,*)
        Write (nout,*) ' Multipliers'
        Write (nout,99998) dl(1:n-1)
        Write (nout,*)
        Write (nout,*) ' Vector of interchanges'
        Write (nout,99997) ipiv(1:n)
      Else
        Write (nout,99996) ifail
      End If

99999 Format (8X,1P,E9.1)
99998 Format (4(1X,'(',F7.4,',',F7.4,')',:))
99997 Format (1X,8I9)
99996 Format (1X,' ** F04CCF returned with IFAIL = ',I5)
    End Program f04ccfe


f04cdfe.f90

    Program f04cdfe

!     F04CDF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: f04cdf, nag_wp, x04dbf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: errbnd, rcond
      Integer                          :: i, ierr, ifail, lda, ldb, n, nrhs
!     .. Local Arrays ..
      Complex (Kind=nag_wp), Allocatable :: a(:,:), b(:,:)
      Character (1)                    :: clabs(1), rlabs(1)
!     .. Executable Statements ..
      Write (nout,*) 'F04CDF Example Program Results'
      Write (nout,*)
      Flush (nout)
!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) n, nrhs
      lda = n
      ldb = n
      Allocate (a(lda,n),b(ldb,nrhs))
!     Read the upper triangular part of A from data file
      Read (nin,*)(a(i,i:n),i=1,n)

!     Read B from data file
      Read (nin,*)(b(i,1:nrhs),i=1,n)

!     Solve the equations AX = B for X

!     ifail: behaviour on error exit
!            =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
      ifail = 1
      Call f04cdf('Upper',n,nrhs,a,lda,b,ldb,rcond,errbnd,ifail)

      If (ifail==0) Then
!       Print solution, estimate of condition number and approximate
!       error bound

        ierr = 0
        Call x04dbf('General',' ',n,nrhs,b,ldb,'Bracketed',' ','Solution',     &
          'Integer',rlabs,'Integer',clabs,80,0,ierr)

        Write (nout,*)
        Write (nout,*) 'Estimate of condition number'
        Write (nout,99999) 1.0E0_nag_wp/rcond
        Write (nout,*)
        Write (nout,*) 'Estimate of error bound for computed solutions'
        Write (nout,99999) errbnd
      Else If (ifail==n+1) Then
!       Matrix A is numerically singular.  Print estimate of
!       reciprocal of condition number and solution
        Write (nout,*)
        Write (nout,*) 'Estimate of reciprocal of condition number'
        Write (nout,99999) rcond
        Write (nout,*)
        Flush (nout)

        ierr = 0
        Call x04dbf('General',' ',n,nrhs,b,ldb,'Bracketed',' ','Solution',     &
          'Integer',rlabs,'Integer',clabs,80,0,ierr)

      Else If (ifail>0 .And. ifail<=n) Then
!       The matrix A is not positive definite to working precision
        Write (nout,99998) 'The leading minor of order ', ifail,               &
          ' is not positive definite'
      Else
        Write (nout,99997) ifail
      End If

99999 Format (8X,1P,E9.1)
99998 Format (1X,A,I3,A)
99997 Format (1X,' ** F04CDF returned with IFAIL = ',I5)
    End Program f04cdfe


f04cefe.f90

    Program f04cefe

!     F04CEF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: f04cef, nag_wp, x04dbf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
      Character (1), Parameter         :: uplo = 'U'
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: errbnd, rcond
      Integer                          :: i, ierr, ifail, j, ldb, n, nrhs
!     .. Local Arrays ..
      Complex (Kind=nag_wp), Allocatable :: ap(:), b(:,:)
      Character (1)                    :: clabs(1), rlabs(1)
!     .. Executable Statements ..
      Write (nout,*) 'F04CEF Example Program Results'
      Write (nout,*)
      Flush (nout)
!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) n, nrhs
      ldb = n
      Allocate (ap((n*(n+1))/2),b(ldb,nrhs))
!     Read the upper or lower triangular part of the matrix A from
!     data file
      If (uplo=='U') Then
        Read (nin,*)((ap(i+(j*(j-1))/2),j=i,n),i=1,n)
      Else If (uplo=='L') Then
        Read (nin,*)((ap(i+((2*n-j)*(j-1))/2),j=1,i),i=1,n)
      End If

!     Read B from data file
      Read (nin,*)(b(i,1:nrhs),i=1,n)

!     Solve the equations AX = B for X

!     ifail: behaviour on error exit
!            =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
      ifail = 1
      Call f04cef(uplo,n,nrhs,ap,b,ldb,rcond,errbnd,ifail)

      If (ifail==0) Then
!       Print solution, estimate of condition number and approximate
!       error bound

        ierr = 0
        Call x04dbf('General',' ',n,nrhs,b,ldb,'Bracketed','F7.4','Solution',  &
          'Integer',rlabs,'Integer',clabs,80,0,ierr)

        Write (nout,*)
        Write (nout,*) 'Estimate of condition number'
        Write (nout,99999) 1.0E0_nag_wp/rcond
        Write (nout,*)
        Write (nout,*) 'Estimate of error bound for computed solutions'
        Write (nout,99999) errbnd
      Else If (ifail==n+1) Then
!       Matrix A is numerically singular.  Print estimate of
!       reciprocal of condition number and solution
        Write (nout,*)
        Write (nout,*) 'Estimate of reciprocal of condition number'
        Write (nout,99999) rcond
        Write (nout,*)
        Flush (nout)

        ierr = 0
        Call x04dbf('General',' ',n,nrhs,b,ldb,'Bracketed','F7.4','Solution',  &
          'Integer',rlabs,'Integer',clabs,80,0,ierr)

      Else If (ifail>0 .And. ifail<=n) Then
!       The matrix A is not positive definite to working precision
        Write (nout,99998) 'The leading minor of order ', ifail,               &
          ' is not positive definite'
      Else
        Write (nout,99997) ifail
      End If

99999 Format (4X,1P,E9.1)
99998 Format (1X,A,I3,A)
99997 Format (1X,' ** F04CEF returned with IFAIL = ',I5)
    End Program f04cefe


f04cffe.f90

    Program f04cffe

!     F04CFF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: f04cff, nag_wp, x04dbf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
      Character (1), Parameter         :: uplo = 'U'
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: errbnd, rcond
      Integer                          :: i, ierr, ifail, j, kd, ldab, ldb, n, &
                                          nrhs
!     .. Local Arrays ..
      Complex (Kind=nag_wp), Allocatable :: ab(:,:), b(:,:)
      Character (1)                    :: clabs(1), rlabs(1)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: max, min
!     .. Executable Statements ..
      Write (nout,*) 'F04CFF Example Program Results'
      Write (nout,*)
      Flush (nout)
!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) n, kd, nrhs
      ldab = kd + 1
      ldb = n
      Allocate (ab(ldab,n),b(ldb,nrhs))
!     Read the upper or lower triangular part of the band matrix A
!     from data file
      If (uplo=='U') Then
        Do i = 1, n
          Read (nin,*)(ab(kd+1+i-j,j),j=i,min(n,i+kd))
        End Do
      Else If (uplo=='L') Then
        Do i = 1, n
          Read (nin,*)(ab(1+i-j,j),j=max(1,i-kd),i)
        End Do
      End If

!     Read B from data file
      Read (nin,*)(b(i,1:nrhs),i=1,n)

!     Solve the equations AX = B for X

!     ifail: behaviour on error exit
!            =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
      ifail = 1
      Call f04cff(uplo,n,kd,nrhs,ab,ldab,b,ldb,rcond,errbnd,ifail)

      If (ifail==0) Then
!       Print solution, estimate of condition number and approximate
!       error bound

        ierr = 0
        Call x04dbf('General',' ',n,nrhs,b,ldb,'Bracketed','F7.4','Solution',  &
          'Integer',rlabs,'Integer',clabs,80,0,ierr)

        Write (nout,*)
        Write (nout,*) 'Estimate of condition number'
        Write (nout,99999) 1.0E0_nag_wp/rcond
        Write (nout,*)
        Write (nout,*) 'Estimate of error bound for computed solutions'
        Write (nout,99999) errbnd
      Else If (ifail==n+1) Then
!       Matrix A is numerically singular.  Print estimate of
!       reciprocal of condition number and solution
        Write (nout,*)
        Write (nout,*) 'Estimate of reciprocal of condition number'
        Write (nout,99999) rcond
        Write (nout,*)
        Flush (nout)

        ierr = 0
        Call x04dbf('General',' ',n,nrhs,b,ldb,'Bracketed','F7.4','Solution',  &
          'Integer',rlabs,'Integer',clabs,80,0,ierr)

      Else If (ifail>0 .And. ifail<=n) Then
!       The matrix A is not positive definite to working precision
        Write (nout,99998) 'The leading minor of order ', ifail,               &
          ' is not positive definite'
      Else
        Write (nout,99997) ifail
      End If

99999 Format (4X,1P,E9.1)
99998 Format (1X,A,I3,A)
99997 Format (1X,' ** F04CFF returned with IFAIL = ',I5)
    End Program f04cffe


f04cgfe.f90

    Program f04cgfe

!     F04CGF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: f04cgf, nag_wp, x04dbf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: errbnd, rcond
      Integer                          :: i, ierr, ifail, ldb, n, nrhs
!     .. Local Arrays ..
      Complex (Kind=nag_wp), Allocatable :: b(:,:), e(:)
      Real (Kind=nag_wp), Allocatable  :: d(:)
      Character (1)                    :: clabs(1), rlabs(1)
!     .. Executable Statements ..
      Write (nout,*) 'F04CGF Example Program Results'
      Write (nout,*)
      Flush (nout)
!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) n, nrhs
      ldb = n
      Allocate (b(ldb,nrhs),e(n-1),d(n))
!     Read A from data file
      Read (nin,*) d(1:n)
      Read (nin,*) e(1:n-1)

!     Read B from data file
      Read (nin,*)(b(i,1:nrhs),i=1,n)

!     Solve the equations AX = B for X

!     ifail: behaviour on error exit
!            =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
      ifail = 1
      Call f04cgf(n,nrhs,d,e,b,ldb,rcond,errbnd,ifail)

      If (ifail==0) Then
!       Print solution, estimate of condition number and approximate
!       error bound

        ierr = 0
        Call x04dbf('General',' ',n,nrhs,b,ldb,'Bracketed',' ','Solution',     &
          'Integer',rlabs,'Integer',clabs,80,0,ierr)

        Write (nout,*)
        Write (nout,*) 'Estimate of condition number'
        Write (nout,99999) 1.0E0_nag_wp/rcond
        Write (nout,*)
        Write (nout,*) 'Estimate of error bound for computed solutions'
        Write (nout,99999) errbnd
      Else If (ifail==n+1) Then
!       Matrix A is numerically singular.  Print estimate of
!       reciprocal of condition number and solution
        Write (nout,*)
        Write (nout,*) 'Estimate of reciprocal of condition number'
        Write (nout,99999) rcond
        Write (nout,*)
        Flush (nout)

        ierr = 0
        Call x04dbf('General',' ',n,nrhs,b,ldb,'Bracketed',' ','Solution',     &
          'Integer',rlabs,'Integer',clabs,80,0,ierr)

      Else If (ifail>0 .And. ifail<=n) Then
        Write (nout,99998) 'The leading minor of order ', ifail,               &
          ' is not positive definite'
      Else
        Write (nout,99997) ifail
      End If

99999 Format (8X,1P,E9.1)
99998 Format (1X,A,I3,A)
99997 Format (1X,' ** F04CGF returned with IFAIL = ',I5)
    End Program f04cgfe


f04chfe.f90

    Program f04chfe

!     F04CHF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: f04chf, nag_wp, x04dbf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: errbnd, rcond
      Integer                          :: i, ierr, ifail, lda, ldb, n, nrhs
!     .. Local Arrays ..
      Complex (Kind=nag_wp), Allocatable :: a(:,:), b(:,:)
      Integer, Allocatable             :: ipiv(:)
      Character (1)                    :: clabs(1), rlabs(1)
!     .. Executable Statements ..
      Write (nout,*) 'F04CHF Example Program Results'
      Write (nout,*)
      Flush (nout)
!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) n, nrhs
      lda = n
      ldb = n
      Allocate (a(lda,n),b(ldb,nrhs),ipiv(n))
!     Read the upper triangular part of A from data file
      Read (nin,*)(a(i,i:n),i=1,n)

!     Read B from data file
      Read (nin,*)(b(i,1:nrhs),i=1,n)

!     Solve the equations AX = B for X

!     ifail: behaviour on error exit
!            =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
      ifail = 1
      Call f04chf('Upper',n,nrhs,a,lda,ipiv,b,ldb,rcond,errbnd,ifail)

      If (ifail==0) Then
!       Print solution, estimate of condition number and approximate
!       error bound

        ierr = 0
        Call x04dbf('General',' ',n,nrhs,b,ldb,'Bracketed',' ','Solution',     &
          'Integer',rlabs,'Integer',clabs,80,0,ierr)

        Write (nout,*)
        Write (nout,*) 'Estimate of condition number'
        Write (nout,99999) 1.0E0_nag_wp/rcond
        Write (nout,*)
        Write (nout,*) 'Estimate of error bound for computed solutions'
        Write (nout,99999) errbnd
      Else If (ifail==n+1) Then
!       Matrix A is numerically singular.  Print estimate of
!       reciprocal of condition number and solution
        Write (nout,*)
        Write (nout,*) 'Estimate of reciprocal of condition number'
        Write (nout,99999) rcond
        Write (nout,*)
        Flush (nout)

        ierr = 0
        Call x04dbf('General',' ',n,nrhs,b,ldb,'Bracketed',' ','Solution',     &
          'Integer',rlabs,'Integer',clabs,80,0,ierr)

      Else If (ifail>0 .And. ifail<=n) Then
!       The upper triangular matrix U is exactly singular.  Print
!       details of factorization
        Write (nout,*)
        Flush (nout)

        ierr = 0
        Call x04dbf('Upper','Non-unit diagonal',n,n,a,lda,'Bracketed',' ',     &
          'Details of factorization','Integer',rlabs,'Integer',clabs,80,0,     &
          ierr)

!       Print pivot indices
        Write (nout,*)
        Write (nout,*) 'Pivot indices'
        Write (nout,99998) ipiv(1:n)
      Else
        Write (nout,99997) ifail
      End If

99999 Format (8X,1P,E9.1)
99998 Format ((1X,7I11))
99997 Format (1X,' ** F04CHF returned with IFAIL = ',I5)
    End Program f04chfe


f04cjfe.f90

    Program f04cjfe

!     F04CJF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: f04cjf, nag_wp, x04dbf, x04ddf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
      Character (1), Parameter         :: uplo = 'U'
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: errbnd, rcond
      Integer                          :: i, ierr, ifail, j, ldb, n, nrhs
!     .. Local Arrays ..
      Complex (Kind=nag_wp), Allocatable :: ap(:), b(:,:)
      Integer, Allocatable             :: ipiv(:)
      Character (1)                    :: clabs(1), rlabs(1)
!     .. Executable Statements ..
      Write (nout,*) 'F04CJF Example Program Results'
      Write (nout,*)
      Flush (nout)
!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) n, nrhs
      ldb = n
      Allocate (ap((n*(n+1))/2),b(ldb,nrhs),ipiv(n))
!     Read the upper or lower triangular part of the matrix A from
!     data file
      If (uplo=='U') Then
        Read (nin,*)((ap(i+(j*(j-1))/2),j=i,n),i=1,n)
      Else If (uplo=='L') Then
        Read (nin,*)((ap(i+((2*n-j)*(j-1))/2),j=1,i),i=1,n)
      End If

!     Read B from data file
      Read (nin,*)(b(i,1:nrhs),i=1,n)

!     Solve the equations AX = B for X

!     ifail: behaviour on error exit
!            =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
      ifail = 1
      Call f04cjf(uplo,n,nrhs,ap,ipiv,b,ldb,rcond,errbnd,ifail)

      If (ifail==0) Then
!       Print solution, estimate of condition number and approximate
!       error bound

        ierr = 0
        Call x04dbf('General',' ',n,nrhs,b,ldb,'Bracketed',' ','Solution',     &
          'Integer',rlabs,'Integer',clabs,80,0,ierr)

        Write (nout,*)
        Write (nout,*) 'Estimate of condition number'
        Write (nout,99999) 1.0E0_nag_wp/rcond
        Write (nout,*)
        Write (nout,*) 'Estimate of error bound for computed solutions'
        Write (nout,99999) errbnd
      Else If (ifail==n+1) Then
!       Matrix A is numerically singular.  Print estimate of
!       reciprocal of condition number and solution
        Write (nout,*)
        Write (nout,*) 'Estimate of reciprocal of condition number'
        Write (nout,99999) rcond
        Write (nout,*)
        Flush (nout)

        ierr = 0
        Call x04dbf('General',' ',n,nrhs,b,ldb,'Bracketed',' ','Solution',     &
          'Integer',rlabs,'Integer',clabs,80,0,ierr)

      Else If (ifail>0 .And. ifail<=n) Then
!       The upper triangular matrix U is exactly singular.  Print
!       details of factorization
        Write (nout,*)
        Flush (nout)

        ierr = 0
        Call x04ddf(uplo,'Non-unit diagonal',n,ap,'Bracketed',' ',             &
          'Details of factorization','Integer',rlabs,'Integer',clabs,80,0,     &
          ierr)

!       Print pivot indices
        Write (nout,*)
        Write (nout,*) 'Pivot indices'
        Write (nout,99998) ipiv(1:n)
      Else
        Write (nout,99997) ifail
      End If

99999 Format (8X,1P,E9.1)
99998 Format ((1X,7I11))
99997 Format (1X,' ** F04CJF returned with IFAIL = ',I5)
    End Program f04cjfe


f04dhfe.f90

    Program f04dhfe

!     F04DHF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: f04dhf, nag_wp, x04dbf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: errbnd, rcond
      Integer                          :: i, ierr, ifail, lda, ldb, n, nrhs
!     .. Local Arrays ..
      Complex (Kind=nag_wp), Allocatable :: a(:,:), b(:,:)
      Integer, Allocatable             :: ipiv(:)
      Character (1)                    :: clabs(1), rlabs(1)
!     .. Executable Statements ..
      Write (nout,*) 'F04DHF Example Program Results'
      Write (nout,*)
      Flush (nout)
!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) n, nrhs
      lda = n
      ldb = n
      Allocate (a(lda,n),b(ldb,nrhs),ipiv(n))
!     Read the upper triangular part of A from data file
      Read (nin,*)(a(i,i:n),i=1,n)

!     Read B from data file
      Read (nin,*)(b(i,1:nrhs),i=1,n)

!     Solve the equations AX = B for X

!     ifail: behaviour on error exit
!            =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
      ifail = 1
      Call f04dhf('Upper',n,nrhs,a,lda,ipiv,b,ldb,rcond,errbnd,ifail)

      If (ifail==0) Then
!       Print solution, estimate of condition number and approximate
!       error bound

        ierr = 0
        Call x04dbf('General',' ',n,nrhs,b,ldb,'Bracketed',' ','Solution',     &
          'Integer',rlabs,'Integer',clabs,80,0,ierr)

        Write (nout,*)
        Write (nout,*) 'Estimate of condition number'
        Write (nout,99999) 1.0E0_nag_wp/rcond
        Write (nout,*)
        Write (nout,*) 'Estimate of error bound for computed solutions'
        Write (nout,99999) errbnd
      Else If (ifail==n+1) Then
!       Matrix A is numerically singular.  Print estimate of
!       reciprocal of condition number and solution
        Write (nout,*)
        Write (nout,*) 'Estimate of reciprocal of condition number'
        Write (nout,99999) rcond
        Write (nout,*)
        Flush (nout)

        ierr = 0
        Call x04dbf('General',' ',n,nrhs,b,ldb,'Bracketed',' ','Solution',     &
          'Integer',rlabs,'Integer',clabs,80,0,ierr)

      Else If (ifail>0 .And. ifail<=n) Then
!       The upper triangular matrix U is exactly singular.  Print
!       details of factorization
        Write (nout,*)
        Flush (nout)

        ierr = 0
        Call x04dbf('Upper','Non-unit diagonal',n,n,a,lda,'Bracketed',' ',     &
          'Details of factorization','Integer',rlabs,'Integer',clabs,80,0,     &
          ierr)

!       Print pivot indices
        Write (nout,*)
        Write (nout,*) 'Pivot indices'
        Write (nout,99998) ipiv(1:n)
      Else
        Write (nout,99997) ifail
      End If

99999 Format (8X,1P,E9.1)
99998 Format ((3X,7I11))
99997 Format (1X,' ** F04DHF returned with IFAIL = ',I5)
    End Program f04dhfe


f04djfe.f90

    Program f04djfe

!     F04DJF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: f04djf, nag_wp, x04dbf, x04ddf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
      Character (1), Parameter         :: uplo = 'U'
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: errbnd, rcond
      Integer                          :: i, ierr, ifail, j, ldb, n, nrhs
!     .. Local Arrays ..
      Complex (Kind=nag_wp), Allocatable :: ap(:), b(:,:)
      Integer, Allocatable             :: ipiv(:)
      Character (1)                    :: clabs(1), rlabs(1)
!     .. Executable Statements ..
      Write (nout,*) 'F04DJF Example Program Results'
      Write (nout,*)
      Flush (nout)
!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) n, nrhs
      ldb = n
      Allocate (ap((n*(n+1))/2),b(ldb,nrhs),ipiv(n))
!     Read the upper or lower triangular part of the matrix A from
!     data file
      If (uplo=='U') Then
        Read (nin,*)((ap(i+(j*(j-1))/2),j=i,n),i=1,n)
      Else If (uplo=='L') Then
        Read (nin,*)((ap(i+((2*n-j)*(j-1))/2),j=1,i),i=1,n)
      End If

!     Read B from data file
      Read (nin,*)(b(i,1:nrhs),i=1,n)

!     Solve the equations AX = B for X

!     ifail: behaviour on error exit
!            =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
      ifail = 1
      Call f04djf(uplo,n,nrhs,ap,ipiv,b,ldb,rcond,errbnd,ifail)

      If (ifail==0) Then
!       Print solution, estimate of condition number and approximate
!       error bound

        ierr = 0
        Call x04dbf('General',' ',n,nrhs,b,ldb,'Bracketed',' ','Solution',     &
          'Integer',rlabs,'Integer',clabs,80,0,ierr)

        Write (nout,*)
        Write (nout,*) 'Estimate of condition number'
        Write (nout,99999) 1.0E0_nag_wp/rcond
        Write (nout,*)
        Write (nout,*) 'Estimate of error bound for computed solutions'
        Write (nout,99999) errbnd
      Else If (ifail==n+1) Then
!       Matrix A is numerically singular.  Print estimate of
!       reciprocal of condition number and solution
        Write (nout,*)
        Write (nout,*) 'Estimate of reciprocal of condition number'
        Write (nout,99999) rcond
        Write (nout,*)
        Flush (nout)

        ierr = 0
        Call x04dbf('General',' ',n,nrhs,b,ldb,'Bracketed',' ','Solution',     &
          'Integer',rlabs,'Integer',clabs,80,0,ierr)

      Else If (ifail>0 .And. ifail<=n) Then
!       The upper triangular matrix U is exactly singular.  Print
!       details of factorization
        Write (nout,*)
        Flush (nout)

        ierr = 0
        Call x04ddf(uplo,'Non-unit diagonal',n,ap,'Bracketed',' ',             &
          'Details of factorization','Integer',rlabs,'Integer',clabs,80,0,     &
          ierr)

!       Print pivot indices
        Write (nout,*)
        Write (nout,*) 'Pivot indices'
        Write (nout,99998) ipiv(1:n)
      Else
        Write (nout,99997) ifail
      End If

99999 Format (8X,1P,E9.1)
99998 Format ((1X,7I11))
99997 Format (1X,' ** F04DJF returned with IFAIL = ',I5)
    End Program f04djfe


f04fefe.f90

    Program f04fefe

!     F04FEF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: f04fef, nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: vlast
      Integer                          :: ifail, n
      Logical                          :: wantp, wantv
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: p(:), t(:), v(:), work(:), x(:)
!     .. Executable Statements ..
      Write (nout,*) 'F04FEF Example Program Results'
!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) n
      Write (nout,*)

      Allocate (p(n),t(0:n),v(n),work(n-1),x(n))
      Read (nin,*) t(0:n)
      wantp = .True.
      wantv = .True.

!     ifail: behaviour on error exit
!             =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
      ifail = 1
      Call f04fef(n,t,x,wantp,p,wantv,v,vlast,work,ifail)

      If (ifail==0) Then
        Write (nout,*)
        Write (nout,*) 'Solution vector'
        Write (nout,99998) x(1:n)
        If (wantp) Then
          Write (nout,*)
          Write (nout,*) 'Reflection coefficients'
          Write (nout,99998) p(1:n)
        End If
        If (wantv) Then
          Write (nout,*)
          Write (nout,*) 'Mean square prediction errors'
          Write (nout,99998) v(1:n)
        End If
      Else If (ifail>0) Then
        Write (nout,*)
        Write (nout,99999) 'Solution for system of order', ifail
        Write (nout,99998) x(1:ifail)
        If (wantp) Then
          Write (nout,*)
          Write (nout,*) 'Reflection coefficients'
          Write (nout,99998) p(1:ifail)
        End If
        If (wantv) Then
          Write (nout,*)
          Write (nout,*) 'Mean square prediction errors'
          Write (nout,99998) v(1:ifail)
        End If
      Else
        Write (nout,99997) ifail
      End If

99999 Format (1X,A,I5)
99998 Format (1X,5F9.4)
99997 Format (1X,' ** F04FEF returned with IFAIL = ',I5)
    End Program f04fefe


f04fffe.f90

    Program f04fffe

!     F04FFF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: f04fff, nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Integer                          :: ifail, n
      Logical                          :: wantp
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: b(:), p(:), t(:), work(:), x(:)
!     .. Executable Statements ..
      Write (nout,*) 'F04FFF Example Program Results'
!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) n
      Write (nout,*)
      Allocate (b(n),p(n-1),t(0:n-1),work(2*(n-1)),x(n))
      Read (nin,*) t(0:n-1)
      Read (nin,*) b(1:n)
      wantp = .True.

!     ifail: behaviour on error exit
!             =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
      ifail = 1
      Call f04fff(n,t,b,x,wantp,p,work,ifail)

      If (ifail==0) Then
        Write (nout,*)
        Write (nout,*) 'Solution vector'
        Write (nout,99998) x(1:n)
        If (wantp) Then
          Write (nout,*)
          Write (nout,*) 'Reflection coefficients'
          Write (nout,99998) p(1:n-1)
        End If
      Else If (ifail>0) Then
        Write (nout,*)
        Write (nout,99999) 'Solution for system of order', ifail - 1
        Write (nout,99998) x(1:ifail-1)
        If (wantp) Then
          Write (nout,*)
          Write (nout,*) 'Reflection coefficients'
          Write (nout,99998) p(1:ifail-1)
        End If
      Else
        Write (nout,99997) ifail
      End If

99999 Format (1X,A,I5)
99998 Format (1X,5F9.4)
99997 Format (1X,' ** F04FFF returned with IFAIL = ',I5)
    End Program f04fffe


f04jgfe.f90

    Program f04jgfe

!     F04JGF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: f04jgf, nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: sigma, tol
      Integer                          :: i, ifail, irank, lda, lwork, m, n
      Logical                          :: svd
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: a(:,:), b(:), work(:)
!     .. Executable Statements ..
      Write (nout,*) 'F04JGF Example Program Results'
      Write (nout,*)
!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) m, n
      tol = 5.0E-4_nag_wp
      lda = m
      lwork = 4*n
      Allocate (a(lda,n),b(m),work(lwork))
      Read (nin,*)(a(i,1:n),i=1,m)
      Read (nin,*) b(1:m)

!     ifail: behaviour on error exit
!             =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
      ifail = 0
      Call f04jgf(m,n,a,lda,b,tol,svd,sigma,irank,work,lwork,ifail)

      Write (nout,*) 'Solution vector'
      Write (nout,99997) b(1:n)
      Write (nout,*)
      Write (nout,99999) 'Standard error = ', sigma, '    Rank = ', irank
      Write (nout,*)
      Write (nout,99998) 'SVD = ', svd

99999 Format (1X,A,F6.3,A,I2)
99998 Format (1X,A,L2)
99997 Format (1X,8F9.3)
    End Program f04jgfe


f04lefe.f90

    Program f04lefe

!     F04LEF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: f01lef, f04lef, nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: lambda, tol
      Integer                          :: ifail, job, n
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: a(:), b(:), c(:), d(:), y(:), z(:)
      Integer, Allocatable             :: ipiv(:)
!     .. Executable Statements ..
      Write (nout,*) 'F04LEF Example Program Results'
      Write (nout,*)
!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) n
      Allocate (a(n),b(n),c(n),d(n),y(n),z(n),ipiv(n))
      Read (nin,*) a(1:n)
      If (n>1) Then
        Read (nin,*) b(2:n)
        Read (nin,*) c(2:n)
      End If
      tol = 5.0E-5_nag_wp
      lambda = 0.0E0_nag_wp

!     ifail: behaviour on error exit
!             =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
      ifail = 0
      Call f01lef(n,a,lambda,b,c,tol,d,ipiv,ifail)

      If (ipiv(n)/=0) Then
        Write (nout,*) 'Matrix is singular or nearly singular'
        Write (nout,99999) 'Diagonal element', ipiv(n), 'is small'
      Else
        Read (nin,*) y(1:n)
        z(1:n) = y(1:n)
        job = 1

        ifail = 0
        Call f04lef(job,n,a,b,c,d,ipiv,y,tol,ifail)

        Write (nout,*)
        Write (nout,*) 'Solution vector for T*X = Y'
        Write (nout,99998) y(1:n)
        job = 2

        ifail = 0
        Call f04lef(job,n,a,b,c,d,ipiv,z,tol,ifail)

        Write (nout,*)
        Write (nout,*) 'Solution vector for transpose(T)*X = Y'
        Write (nout,99998) z(1:n)
      End If

99999 Format (1X,A,I4,A)
99998 Format (1X,5F9.3)
    End Program f04lefe


f04lhfe.f90

    Program f04lhfe

!     F04LHF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: f01lhf, f04lhf, nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: lena = 200, nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: tol
      Integer                          :: i, ifail, index, ir, j, k, ldb, n,   &
                                          nbasek, nbloks
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: a(:), b(:,:)
      Integer, Allocatable             :: blkstr(:,:), pivot(:)
!     .. Executable Statements ..
      Write (nout,*) 'F04LHF Example Program Results'
      Write (nout,*)
!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) nbloks
      Allocate (a(lena),blkstr(3,nbloks))
      nbasek = 0
      n = 0
      Do i = 1, nbloks
        Read (nin,*) blkstr(1:3,i)
        Do k = 1, blkstr(1,i)
          If (nbasek+blkstr(2,i)*blkstr(1,i)>lena) Then
            Write (nout,*) ' Array A is too small for this problem'
            Go To 100
          Else
            Read (nin,*)(a(nbasek+(j-1)*blkstr(1,i)+k),j=1,blkstr(2,i))
          End If
        End Do
        nbasek = nbasek + blkstr(2,i)*blkstr(1,i)
        n = n + blkstr(1,i)
      End Do
      Read (nin,*) ir
      ldb = n
      Allocate (b(ldb,ir),pivot(n))
      tol = 0.0E0_nag_wp

!     ifail: behaviour on error exit
!             =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
      ifail = 0
      Call f01lhf(n,nbloks,blkstr,a,lena,pivot,tol,index,ifail)

      Read (nin,*)(b(1:n,j),j=1,ir)

      ifail = 0
      Call f04lhf('N',n,nbloks,blkstr,a,lena,pivot,b,ldb,ir,ifail)

      Write (nout,*) 'Component Solution'
      Do i = 1, n
        Write (nout,99999) i, b(i,1:ir)
      End Do
100   Continue

99999 Format (1X,I5,6X,5F7.4)
    End Program f04lhfe


f04mcfe.f90

    Program f04mcfe

!     F04MCF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: f01mcf, f04mcf, nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Integer                          :: i, ifail, ir, iselct, k1, k2, lal,   &
                                          ldb, ldx, n
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: a(:), al(:), b(:,:), d(:), x(:,:)
      Integer, Allocatable             :: nrow(:)
!     .. Executable Statements ..
      Write (nout,*) 'F04MCF Example Program Results'
      Write (nout,*)
!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) n, ir
      ldb = n
      ldx = n
      Allocate (b(ldb,ir),d(n),x(ldx,ir),nrow(n))
      Read (nin,*) nrow(1:n)
      lal = 0
      Do i = 1, n
        lal = lal + nrow(i)
      End Do
      Allocate (a(lal),al(lal))
      k2 = 0
      Do i = 1, n
        k1 = k2 + 1
        k2 = k2 + nrow(i)
        Read (nin,*) a(k1:k2)
      End Do
      Read (nin,*)(b(i,1:ir),i=1,n)

!     ifail: behaviour on error exit
!             =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
      ifail = 0
      Call f01mcf(n,a,lal,nrow,al,d,ifail)

      iselct = 1

      ifail = 0
      Call f04mcf(n,al,lal,d,nrow,ir,b,ldb,iselct,x,ldx,ifail)

      Write (nout,*) ' Solution'
      Do i = 1, n
        Write (nout,99999) x(i,1:ir)
      End Do

99999 Format (1X,8F9.3)
    End Program f04mcfe


f04mefe.f90

    Program f04mefe

!     F04MEF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: f04mef, nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: v
      Integer                          :: ifail, k, n
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: t(:), work(:), x(:)
!     .. Executable Statements ..
      Write (nout,*) 'F04MEF Example Program Results'
      Write (nout,*)
!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) n
      Allocate (t(0:n),work(n-1),x(n))
      Read (nin,*) t(0:n)

      Do k = 1, n

!       ifail: behaviour on error exit
!              =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
        ifail = 0
        Call f04mef(k,t,x,v,work,ifail)

        Write (nout,*)
        Write (nout,99999) 'Solution for system of order', k
        Write (nout,99998) x(1:k)
        Write (nout,*) 'Mean square prediction error'
        Write (nout,99998) v
      End Do

99999 Format (1X,A,I5)
99998 Format (1X,5F9.4)
    End Program f04mefe


f04mffe.f90

    Program f04mffe

!     F04MFF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: f04mff, nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: p
      Integer                          :: ifail, k, n
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: b(:), t(:), work(:), x(:)
!     .. Executable Statements ..
      Write (nout,*) 'F04MFF Example Program Results'
      Write (nout,*)
!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) n
      Allocate (b(n),t(0:n-1),work(2*n-1),x(n))
      Read (nin,*) t(0:n-1)
      Read (nin,*) b(1:n)
      Do k = 1, n
!       ifail: behaviour on error exit
!              =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
        ifail = 0
        Call f04mff(k,t,b,x,p,work,ifail)

        Write (nout,*)
        Write (nout,99999) 'Solution for system of order', k
        Write (nout,99998) x(1:k)
        If (k>1) Then
          Write (nout,*) 'Reflection coefficient'
          Write (nout,99998) p
        End If
      End Do

99999 Format (1X,A,I5)
99998 Format (1X,5F9.4)
    End Program f04mffe


f04qafe.f90

!   F04QAF Example Program Text
!   Mark 26 Release. NAG Copyright 2016.

    Module f04qafe_mod
!     F04QAF Example Program Module:
!            Parameters and User-defined Routines

!     .. Use Statements ..
      Use nag_library, Only: nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Accessibility Statements ..
      Private
      Public                           :: aprod
!     .. Parameters ..
      Integer, Parameter, Public       :: iset = 1, liuser = 1, lruser = 1,    &
                                          nin = 5, nout = 6
!     .. Local Scalars ..
      Integer, Public, Save            :: ncols, nrows
    Contains
      Subroutine atimes(n,x,y)
!       Called by routine aprod. Returns Y = Y + A*X,
!       where A is not stored explicitly.

!       .. Scalar Arguments ..
        Integer, Intent (In)           :: n
!       .. Array Arguments ..
        Real (Kind=nag_wp), Intent (In) :: x(n)
        Real (Kind=nag_wp), Intent (Inout) :: y(n)
!       .. Local Scalars ..
        Integer                        :: i, i1, i2, i3, il, j
!       .. Executable Statements ..
        Do j = 1, nrows - 2
          y(j) = y(j) + x(j) - x(j+nrows-1)
        End Do
        Do j = 1, ncols - 2
          i = j*nrows - 1
          y(i) = y(i) + x(i) - x(i+1)
          i1 = i + 1
          il = i1 + nrows - 3
          Do i = i1, il
            i2 = i - nrows
            If (j==1) Then
              i2 = i2 + 1
            End If
            i3 = i + nrows
            If (j==ncols-2) Then
              i3 = i3 - 1
            End If
            y(i) = y(i) - x(i2) - x(i-1) + 4.0_nag_wp*x(i) - x(i+1) - x(i3)
          End Do
          i = il + 1
          y(i) = y(i) - x(i-1) + x(i)
        End Do
        Do j = n - nrows + 3, n
          y(j) = y(j) - x(j-nrows+1) + x(j)
        End Do
        Return
      End Subroutine atimes
      Subroutine aprod(mode,m,n,x,y,ruser,lruser,iuser,liuser)

!       APROD returns
!       Y = Y + A*X          when MODE = 1
!       X = X + ( A**T )*Y   when MODE = 2
!       for a given X and Y.

!       .. Scalar Arguments ..
        Integer, Intent (In)           :: liuser, lruser, m, n
        Integer, Intent (Inout)        :: mode
!       .. Array Arguments ..
        Real (Kind=nag_wp), Intent (Inout) :: ruser(lruser), x(n), y(m)
        Integer, Intent (Inout)        :: iuser(liuser)
!       .. Local Scalars ..
        Integer                        :: j, j1, j2
!       .. Executable Statements ..
        If (mode/=2) Then
          Call atimes(n,x,y)
          Do j = 1, nrows - 2
            y(m) = y(m) + x(j)
          End Do
          Do j = 1, ncols - 2
            y(m) = y(m) + x(j*nrows-1) + x(j*nrows+nrows-2)
          End Do
          Do j = m - nrows + 2, n
            y(m) = y(m) + x(j)
          End Do
        Else
          Call atimes(n,y,x)
          Do j = 1, nrows - 2
            x(j) = x(j) + y(m)
          End Do
          Do j = 1, ncols - 2
            j1 = j*nrows - 1
            j2 = j1 + nrows - 1
            x(j1) = x(j1) + y(m)
            x(j2) = x(j2) + y(m)
          End Do
          Do j = m - nrows + 2, n
            x(j) = x(j) + y(m)
          End Do
        End If
        Return
      End Subroutine aprod
    End Module f04qafe_mod
    Program f04qafe

!     F04QAF Example Main Program

!     .. Use Statements ..
      Use nag_library, Only: f04qaf, nag_wp, x04abf
      Use f04qafe_mod, Only: aprod, iset, liuser, lruser, ncols, nin, nout,    &
                             nrows
!     .. Implicit None Statement ..
      Implicit None
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: acond, anorm, arnorm, atol, btol, c, &
                                          conlim, damp, h, rnorm, xnorm
      Integer                          :: i1, ifail, inform, itn, itnlim, k,   &
                                          m, msglvl, n, outchn
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: b(:), se(:), work(:,:), x(:)
      Real (Kind=nag_wp)               :: ruser(lruser)
      Integer                          :: iuser(liuser)
!     .. Executable Statements ..
      Write (nout,*) 'F04QAF Example Program Results'
      Write (nout,*)
      Flush (nout)
!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) nrows, ncols
      n = ncols*nrows - 4
      m = n + 1
      Allocate (b(m),se(n),work(n,2),x(n))
      outchn = nout
      Call x04abf(iset,outchn)

      h = 0.1_nag_wp
!     Initialize rhs and other quantities required by F04QAF.
!     Convergence will be sooner if we do not regard A as exact,
!     so atol is not set to zero.
      b(1:n) = 0.0_nag_wp
      c = -h**2
      i1 = nrows
      Do k = 3, ncols
        b(i1:(i1+nrows-3)) = c
        i1 = i1 + nrows
      End Do
      b(m) = 1.0_nag_wp/h
      damp = 0.0_nag_wp
      atol = 1.0E-5_nag_wp
      btol = 1.0E-4_nag_wp
      conlim = 1.0_nag_wp/atol
      itnlim = 100
!     * Set msglvl to 2 to get output at each iteration *
      msglvl = 1

!     ifail: behaviour on error exit
!             =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
      ifail = 0
      Call f04qaf(m,n,b,x,se,aprod,damp,atol,btol,conlim,itnlim,msglvl,itn,    &
        anorm,acond,rnorm,arnorm,xnorm,work,ruser,lruser,iuser,liuser,inform,  &
        ifail)

      Write (nout,*)
      Write (nout,*) 'Solution returned by F04QAF'
      Write (nout,99999) x(1:n)
      Write (nout,*)
      Write (nout,99998) 'Norm of the residual = ', rnorm

99999 Format (1X,5F9.3)
99998 Format (1X,A,1P,E12.2)
    End Program f04qafe


f04yafe.f90

    Program f04yafe

!     F04YAF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: f04jgf, f04yaf, nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: sigma, tol
      Integer                          :: i, ifail, irank, job, lda, lwork, n, &
                                          p
      Logical                          :: svd
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: a(:,:), cj(:), work(:), y(:)
!     .. Executable Statements ..
      Write (nout,*) 'F04YAF Example Program Results'
!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) n, p
      lda = n
      lwork = 4*p
      Allocate (a(lda,p),cj(p),work(lwork),y(n))
      tol = 5.0E-4_nag_wp
      Read (nin,*)(a(i,1:p),i=1,n)
      Read (nin,*) y(1:n)

!     ifail: behaviour on error exit
!             =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
      ifail = 0
      Call f04jgf(n,p,a,lda,y,tol,svd,sigma,irank,work,lwork,ifail)

      Write (nout,*)
      Write (nout,99999) 'SIGMA =', sigma, '  Rank =', irank, '  SVD =', svd
      Write (nout,*)
      Write (nout,*) 'Solution vector'
      Write (nout,99998) y(1:p)
      job = 0

      ifail = 0
      Call f04yaf(job,p,sigma,a,lda,svd,irank,work,cj,work(p+1),ifail)

      Write (nout,*)
      Write (nout,*) 'Estimated variances of regression coefficients'
      Write (nout,99998) cj(1:p)

99999 Format (1X,A,F9.4,A,I3,A,L3)
99998 Format (1X,7F9.4)
    End Program f04yafe


f04ydfe.f90

    Program f04ydfe

!     F04YDF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nout = 6
!     .. Executable Statements ..
      Write (nout,*) 'F04YDF Example Program Results'

      Call ex1

      Call ex2

    Contains
      Subroutine ex1

!       .. Use Statements ..
        Use nag_library, Only: dgetrf, dgetrs, f04ydf, f06raf, nag_wp
!       .. Implicit None Statement ..
        Implicit None
!       .. Parameters ..
        Integer, Parameter             :: nin = 5, nout = 6
!       .. Local Scalars ..
        Real (Kind=nag_wp)             :: cond, nrma, nrminv
        Integer                        :: i, ifail, irevcm, lda, ldx, ldy, m,  &
                                          n, seed, t
!       .. Local Arrays ..
        Real (Kind=nag_wp), Allocatable :: a(:,:), work(:), x(:,:), y(:,:)
        Integer, Allocatable           :: ipiv(:), iwork(:)
!       .. Executable Statements ..
        Write (nout,*) 'Example 1'
        Write (nout,*)
!       Skip heading in data file
        Read (nin,'(///A)')
        Read (nin,*) m, n, t

        lda = m
        ldx = n
        ldy = m
        Allocate (a(lda,n),x(ldx,t),y(ldy,t),work(m*t),iwork(2*n+5*t+20),      &
          ipiv(n))

!       Read A from data file
        Read (nin,*)(a(i,1:n),i=1,m)

!       Compute 1-norm of A
        nrma = f06raf('1',m,n,a,lda,work)
        Write (nout,99999) 'The norm of A is: ', nrma

!       Estimate the norm of A^(-1) without explicitly forming A^(-1)

!       Perform an LU factorization so that A=LU where L and U are lower
!       and upper triangular.
        ifail = 0

!       The NAG name equivalent of dgetrf is f07adf
        Call dgetrf(m,n,a,lda,ipiv,ifail)

        seed = 354
        irevcm = 0
loop:   Do
          Call f04ydf(irevcm,m,n,x,ldx,y,ldy,nrminv,t,seed,work,iwork,ifail)
          If (irevcm==0) Then
            Exit loop
          Else If (irevcm==1) Then
!           Compute y = inv(A)*x

!           The NAG name equivalent of dgetrs is f07aef
            Call dgetrs('N',n,t,a,lda,ipiv,x,ldx,ifail)
!           x was overwritten by dgetrs, so set y=x
            y(1:n,1:t) = x(1:n,1:t)
          Else
!           Compute x = transpose(inv(A))*y

!           The NAG name equivalent of dgetrs is f07aef
            Call dgetrs('T',n,t,a,lda,ipiv,y,ldy,ifail)
!           y was overwritten by dgetrs so set x=y
            x(1:n,1:t) = y(1:n,1:t)
          End If
        End Do loop

        Write (nout,99999) 'The estimated norm of inverse(A) is: ', nrminv

!       Compute and print the estimated condition number
        cond = nrminv*nrma
        Write (nout,*)
        Write (nout,99999) 'Estimated condition number of A: ', cond
        Write (nout,*)

99999   Format (1X,A,F6.2)

      End Subroutine ex1

      Subroutine ex2

!       .. Use Statements ..
        Use nag_library, Only: f01brf, f04axf, f04ydf, nag_wp
!       .. Implicit None Statement ..
        Implicit None
!       .. Parameters ..
        Real (Kind=nag_wp), Parameter  :: zero = 0.0_nag_wp
!       .. Local Scalars ..
        Real (Kind=nag_wp)             :: asum, cond, nrma, nrminv, pivot,     &
                                          resid
        Integer                        :: i, ifail, irevcm, j, ldx, ldy, licn, &
                                          lirn, n, nin, nout, nz, seed, t
        Logical                        :: grow, lblock
!       .. Local Arrays ..
        Real (Kind=nag_wp), Allocatable :: a(:), w(:), work(:), x(:,:), y(:,:)
        Integer, Allocatable           :: icn(:), ikeep(:), irn(:), iw(:),     &
                                          iwork(:)
        Integer                        :: idisp(10)
        Logical                        :: abort(4)
!       .. Intrinsic Procedures ..
        Intrinsic                      :: abs, max
!       .. Executable Statements ..
        Continue
        nout = 6
        nin = 5
        Write (nout,'(//1X,A/)') 'Example 2'

!       Skip heading in data file
        Read (nin,'(//A)')

!       Input N, the order of the matrix A, and NZ the number of nonzero
!       elements of A, together with t the norm estimation parameter.
        Read (nin,*) n, nz, t
        licn = 4*nz
        lirn = 2*nz
        ldx = n
        ldy = n

!       Allocate the required memory
        Allocate (a(licn),icn(licn),irn(lirn),x(ldx,t),y(ldy,t),work(n*t),     &
          ikeep(5*n),iwork(2*n+5*t+20),iw(8*n),w(n))

!       Input the elements of A, along with row and column information.
        Read (nin,*)(a(i),irn(i),icn(i),i=1,nz)

!       Compute 1-norm of A
        nrma = zero
        Do i = 1, n
          asum = zero
          Do j = 1, nz
            If (icn(j)==i) Then
              asum = asum + abs(a(j))
            End If
          End Do
          nrma = max(nrma,asum)
        End Do
        Write (nout,99999) 'The norm of A is: ', nrma

!       Perform an LU factorization so that A=LU where L and U are lower
!       and upper triangular, using F01BRF
        pivot = 0.1_nag_wp
        grow = .True.
        lblock = .True.
        abort(1) = .True.
        abort(2) = .True.
        abort(3) = .False.
        abort(4) = .True.

        ifail = 0
        Call f01brf(n,nz,a,licn,irn,lirn,icn,pivot,ikeep,iw,w,lblock,grow,     &
          abort,idisp,ifail)

!       Compute an estimate of the 1-norm of inv(A)
        seed = 412
        irevcm = 0
loop:   Do
          Call f04ydf(irevcm,n,n,x,ldx,y,ldy,nrminv,t,seed,work,iwork,ifail)
          If (irevcm==0) Then
            Exit loop
          Else If (irevcm==1) Then
!           Compute y = inv(A)*x
            Do i = 1, t
              Call f04axf(n,a,licn,icn,ikeep,x(1,i),w,irevcm,idisp,resid)
            End Do
!           x was overwritten by f04axf, so set y=x
            y(1:n,1:t) = x(1:n,1:t)
          Else
!           Compute x = transpose(inv(A))*y
            Do i = 1, t
              Call f04axf(n,a,licn,icn,ikeep,y(1,i),w,irevcm,idisp,resid)
            End Do
!           y was overwritten by f04axf so set x=y
            x(1:n,1:t) = y(1:n,1:t)
          End If
        End Do loop

        Write (nout,99999) 'The estimated norm of inverse(A) is: ', nrminv

!       Compute and print the estimated condition number
        cond = nrminv*nrma
        Write (nout,*)
        Write (nout,99999) 'Estimated condition number of A: ', cond
        Write (nout,*)

99999   Format (1X,A,F6.2)

      End Subroutine ex2
    End Program f04ydfe


f04zdfe.f90

    Program f04zdfe

!     F04ZDF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: f04zdf, f06uaf, nag_wp, zgetrf, zgetrs
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: cond, nrma, nrminv
      Integer                          :: i, ifail, irevcm, lda, ldx, ldy, m,  &
                                          n, seed, t
!     .. Local Arrays ..
      Complex (Kind=nag_wp), Allocatable :: a(:,:), work(:), x(:,:), y(:,:)
      Real (Kind=nag_wp), Allocatable  :: rwork(:)
      Real (Kind=nag_wp)               :: workr(1)
      Integer, Allocatable             :: ipiv(:), iwork(:)
!     .. Executable Statements ..
      Write (nout,*) 'F04ZDF Example Program Results'
      Write (nout,*)
!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) m, n, t

      lda = m
      ldx = n
      ldy = m
      Allocate (a(lda,n))
      Allocate (x(ldx,t))
      Allocate (y(ldy,t))
      Allocate (work(m*t))
      Allocate (rwork(2*n))
      Allocate (iwork(2*n+5*t+20))
      Allocate (ipiv(n))

!     Read A from data file
      Read (nin,*)(a(i,1:n),i=1,m)

!     Compute 1-norm of A
      nrma = f06uaf('1',m,n,a,lda,workr)
      Write (nout,99999) 'The norm of A is: ', nrma

!     Estimate the norm of A^(-1) without forming A^(-1)
      irevcm = 0
      ifail = 0

      seed = 652

!     Perform an LU factorization so that A=LU where L and U are lower
!     and upper triangular.

!     The NAG name equivalent of zgetrf is f07arf
      Call zgetrf(m,n,a,lda,ipiv,ifail)

loop: Do
        Call f04zdf(irevcm,m,n,x,ldx,y,ldy,nrminv,t,seed,work,rwork,iwork,     &
          ifail)
        If (irevcm/=0) Then
          If (irevcm==1) Then
!           Compute Y = inv(A)*X

!           The NAG name equivalent of zgetrf is f07asf
            Call zgetrs('N',n,t,a,lda,ipiv,x,ldx,ifail)
!           X was overwritten by ZGETRS, so set Y=X
            y(1:n,1:t) = x(1:n,1:t)
          Else
!           Compute X = herm(inv(A))*Y

!           The NAG name equivalent of zgetrf is f07asf
            Call zgetrs('C',n,t,a,lda,ipiv,y,ldy,ifail)
!           Y was overwritten by ZGETRS, so set X=Y
            x(1:n,1:t) = y(1:n,1:t)
          End If
        Else

          Write (nout,99999) 'The estimated norm of inverse(A) is: ', nrminv

!         Compute and print the estimated condition number
          cond = nrminv*nrma
          Write (nout,*)
          Write (nout,99999) 'Estimated condition number of A: ', cond
          Write (nout,*)
          Exit loop
        End If
      End Do loop
99999 Format (1X,A,F6.2)

    End Program f04zdfe


f05aafe.f90

    Program f05aafe

!     F05AAF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: f05aaf, nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: cc
      Integer                          :: i, icol, ifail, lda, m, n1, n2
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: a(:,:), s(:)
!     .. Executable Statements ..
      Write (nout,*) 'F05AAF Example Program Results'

!     Skip heading in data file
      Read (nin,*)

      Read (nin,*) m, n1, n2
      lda = m
      Allocate (a(lda,n2),s(n2))

      Read (nin,*)(a(i,1:n2),i=1,m)

      ifail = 0
      Call f05aaf(a,lda,m,n1,n2,s,cc,icol,ifail)

      Write (nout,*)
      Write (nout,99999) 'N1 = ', n1, '  N2 = ', n2
      Write (nout,*)
      Write (nout,99998) 'CC = ', cc, ' ICOL = ', icol
      Write (nout,*)
      Write (nout,*) 'Final vectors'
      Write (nout,99997)(a(i,n1:n2),i=1,m)

99999 Format (1X,A,I2,A,I2)
99998 Format (1X,A,F7.4,A,I2)
99997 Format (1X,3F9.4)
    End Program f05aafe


f06wafe.f90

    Program f06wafe

!     F06WAF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: dlansf, dtrttf, nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: r_fro, r_inf, r_max, r_one
      Integer                          :: i, info, lda, n
      Character (1)                    :: transr, uplo
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: a(:,:), ar(:), work(:)
!     .. Executable Statements ..
      Write (nout,*) 'F06WAF Example Program Results'

!     Skip heading in data file
      Read (nin,*)

      Read (nin,*) n, uplo, transr

      lda = n
      Allocate (a(lda,n),ar((n*(n+1))/2),work(n))

!     Read upper or lower triangle of matrix A from data file

      If (uplo=='L' .Or. uplo=='l') Then
        Do i = 1, n
          Read (nin,*) a(i,1:i)
        End Do
      Else
        Do i = 1, n
          Read (nin,*) a(i,i:n)
        End Do
      End If

!     Convert A to rectangular full packed storage in ar

!     The NAG name equivalent of dtrttf is f01vef
      Call dtrttf(transr,uplo,n,a,lda,ar,info)

      Write (nout,*)
      Write (nout,99999)                                                       &
        'Norms of symmetric matrix stored in RFP format in ar:'
      Write (nout,*)

!     The NAG name equivalent of dlansf is f06waf
      r_one = dlansf('1-norm',transr,uplo,n,ar,work)
      Write (nout,99998) 'One norm           = ', r_one

      r_inf = dlansf('Infinity',transr,uplo,n,ar,work)
      Write (nout,99998) 'Infinity norm      = ', r_inf

      r_fro = dlansf('Frobenius',transr,uplo,n,ar,work)
      Write (nout,99998) 'Frobenius norm     = ', r_fro

      r_max = dlansf('Max norm',transr,uplo,n,ar,work)
      Write (nout,99998) 'Maximum norm       = ', r_max

99999 Format (1X,A)
99998 Format (1X,A,F9.4)
    End Program f06wafe


f06wbfe.f90

    Program f06wbfe

!     F06WBF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: dtfsm, dtrttf, nag_wp, x04caf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: alpha
      Integer                          :: i, ifail, info, lda, ldb, m, n
      Character (1)                    :: side, trans, transr, uplo
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: a(:,:), ar(:), b(:,:), work(:)
!     .. Executable Statements ..
      Write (nout,*) 'F06WBF Example Program Results'

!     Skip heading in data file
      Read (nin,*)

      Read (nin,*) m, n, uplo, transr, side, alpha, trans

      lda = m
      ldb = m
      Allocate (a(lda,m),ar((m*(m+1))/2),work(m),b(ldb,n))

!     Read upper or lower triangle of matrix A from data file

      If (uplo=='L' .Or. uplo=='l') Then
        Do i = 1, m
          Read (nin,*) a(i,1:i)
        End Do
      Else
        Do i = 1, m
          Read (nin,*) a(i,i:m)
        End Do
      End If

!     Read matrix B from data file

      Read (nin,*)(b(i,1:n),i=1,m)

!     Convert A to rectangular full packed storage in ar

!     The NAG name equivalent of dtrttf is f01vef
      Call dtrttf(transr,uplo,m,a,lda,ar,info)

      Write (nout,*)
      Flush (nout)

!     Perform the matrix-matrix operation

!     The NAG name equivalent of dtfsm is f06wbf
      Call dtfsm(transr,side,uplo,trans,'N',m,n,alpha,ar,b,ldb)

!     Print the result

      ifail = 0
      Call x04caf('General',' ',m,n,b,ldb,'The Solution',ifail)

    End Program f06wbfe


f06wcfe.f90

    Program f06wcfe

!     F06WCF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: dsfrk, dtfttr, dtrttf, nag_wp, x04caf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: alpha, beta
      Integer                          :: i, ifail, info, k, lda, n
      Character (1)                    :: trans, transr, uplo
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: a(:,:), c(:,:), cr(:)
!     .. Executable Statements ..
      Write (nout,*) 'F06WCF Example Program Results'

!     Skip heading in data file
      Read (nin,*)

      Read (nin,*) n, k, uplo, transr, alpha, beta, trans

      lda = n
      Allocate (c(lda,n),cr((n*(n+1))/2),a(lda,k))

!     Read upper or lower triangle of matrix C from data file

      If (uplo=='L' .Or. uplo=='l') Then
        Do i = 1, n
          Read (nin,*) c(i,1:i)
        End Do
      Else
        Do i = 1, n
          Read (nin,*) c(i,i:n)
        End Do
      End If

!     Read matrix A from data file

      Read (nin,*)(a(i,1:k),i=1,n)

!     Convert C to rectangular full packed storage in cr

!     The NAG name equivalent of dtrttf is f01vef
      Call dtrttf(transr,uplo,n,c,lda,cr,info)

      Write (nout,*)
      Flush (nout)

!     Perform the rank-k update

!     The NAG name equivalent of dsfrk is f06wcf
      Call dsfrk(transr,uplo,trans,n,k,alpha,a,lda,beta,cr)

!     Convert cr back from rectangular full packed to standard format in C

!     The NAG name equivalent of dtfttr is f01vgf
      Call dtfttr(transr,uplo,n,cr,c,lda,info)

!     Print out the result, stored in the lower triangle of matrix C

      ifail = 0
      Call x04caf('Lower','N',n,n,c,lda,'The Solution',ifail)

    End Program f06wcfe


f06wnfe.f90

    Program f06wnfe

!     F06WNF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: nag_wp, zlanhf, ztrttf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: r_fro, r_inf, r_max, r_one
      Integer                          :: i, info, lda, n
      Character (1)                    :: transr, uplo
!     .. Local Arrays ..
      Complex (Kind=nag_wp), Allocatable :: a(:,:), ar(:)
      Real (Kind=nag_wp), Allocatable  :: work(:)
!     .. Executable Statements ..
      Write (nout,*) 'F06WNF Example Program Results'

!     Skip heading in data file
      Read (nin,*)

      Read (nin,*) n, uplo, transr

      lda = n
      Allocate (a(lda,n),ar((n*(n+1))/2),work(n))

!     Read upper or lower triangle of matrix A from data file

      If (uplo=='L' .Or. uplo=='l') Then
        Do i = 1, n
          Read (nin,*) a(i,1:i)
        End Do
      Else
        Do i = 1, n
          Read (nin,*) a(i,i:n)
        End Do
      End If

!     Convert A to rectangular full packed storage in ar

!     The NAG name equivalent of ztrttf is f01vff
      Call ztrttf(transr,uplo,n,a,lda,ar,info)

      Write (nout,*)
      Write (nout,99999)                                                       &
        'Norms of Hermitian matrix stored in RFP format in ar:'
      Write (nout,*)

!     The NAG name equivalent of zlanhf is f06wnf
      r_one = zlanhf('1-norm',transr,uplo,n,ar,work)
      Write (nout,99998) 'One norm           = ', r_one

      r_inf = zlanhf('Infinity',transr,uplo,n,ar,work)
      Write (nout,99998) 'Infinity norm      = ', r_inf

      r_fro = zlanhf('Frobenius',transr,uplo,n,ar,work)
      Write (nout,99998) 'Frobenius norm     = ', r_fro

      r_max = zlanhf('Max norm',transr,uplo,n,ar,work)
      Write (nout,99998) 'Maximum norm       = ', r_max

99999 Format (1X,A)
99998 Format (1X,A,F9.4)
    End Program f06wnfe


f06wpfe.f90

    Program f06wpfe

!     F06WPF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: nag_wp, x04daf, ztfsm, ztrttf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Complex (Kind=nag_wp)            :: alpha
      Integer                          :: i, ifail, info, lda, ldb, m, n
      Character (1)                    :: side, trans, transr, uplo
!     .. Local Arrays ..
      Complex (Kind=nag_wp), Allocatable :: a(:,:), ar(:), b(:,:), work(:)
!     .. Executable Statements ..
      Write (nout,*) 'F06WPF Example Program Results'

!     Skip heading in data file
      Read (nin,*)

      Read (nin,*) m, n, uplo, transr, side, alpha, trans

      lda = m
      ldb = m
      Allocate (a(lda,m),ar((m*(m+1))/2),work(m),b(ldb,n))

!     Read upper or lower triangle of matrix A from data file

      If (uplo=='L' .Or. uplo=='l') Then
        Do i = 1, m
          Read (nin,*) a(i,1:i)
        End Do
      Else
        Do i = 1, m
          Read (nin,*) a(i,i:m)
        End Do
      End If

!     Read matrix B from data file

      Read (nin,*)(b(i,1:n),i=1,m)

!     Convert A to rectangular full packed storage in ar

!     The NAG name equivalent of ztrttf is f01vff
      Call ztrttf(transr,uplo,m,a,lda,ar,info)

      Write (nout,*)
      Flush (nout)

!     Perform the matrix-matrix operation

!     The NAG name equivalent of ztfsm is f06wpf
      Call ztfsm(transr,side,uplo,trans,'N',m,n,alpha,ar,b,ldb)

!     Print the result

      ifail = 0
      Call x04daf('General',' ',m,n,b,ldb,'The Solution',ifail)

    End Program f06wpfe


f06wqfe.f90

    Program f06wqfe

!     F06WQF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: nag_wp, x04daf, zhfrk, ztfttr, ztrttf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: alpha, beta
      Integer                          :: i, ifail, info, k, lda, n
      Character (1)                    :: trans, transr, uplo
!     .. Local Arrays ..
      Complex (Kind=nag_wp), Allocatable :: a(:,:), c(:,:), cr(:)
!     .. Executable Statements ..
      Write (nout,*) 'F06WQF Example Program Results'

!     Skip heading in data file
      Read (nin,*)

      Read (nin,*) n, k, uplo, transr, alpha, beta, trans

      lda = n
      Allocate (c(lda,n),cr((n*(n+1))/2),a(lda,k))

!     Read upper or lower triangle of matrix C from data file

      If (uplo=='L' .Or. uplo=='l') Then
        Do i = 1, n
          Read (nin,*) c(i,1:i)
        End Do
      Else
        Do i = 1, n
          Read (nin,*) c(i,i:n)
        End Do
      End If

!     Read matrix A from data file

      Read (nin,*)(a(i,1:k),i=1,n)

!     Convert C to rectangular full packed storage in cr

!     The NAG name equivalent of ztrttf is f01vff
      Call ztrttf(transr,uplo,n,c,lda,cr,info)

      Write (nout,*)
      Flush (nout)

!     Perform the rank-k update

!     The NAG name equivalent of zhfrk is f06wqf
      Call zhfrk(transr,uplo,trans,n,k,alpha,a,lda,beta,cr)

!     Convert cr back from rectangular full packed to standard format in C

!     The NAG name equivalent of ztfttr is f01vhf
      Call ztfttr(transr,uplo,n,cr,c,lda,info)

!     Print out the result, stored in the lower triangle of matrix C

      ifail = 0
      Call x04daf('Lower','N',n,n,c,lda,'The Solution',ifail)

    End Program f06wqfe


f07aafe.f90

    Program f07aafe

!     F07AAF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: dgesv, nag_wp, x04caf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Integer                          :: i, ifail, info, lda, ldb, n
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: a(:,:), b(:)
      Integer, Allocatable             :: ipiv(:)
!     .. Executable Statements ..
      Write (nout,*) 'F07AAF Example Program Results'
      Write (nout,*)
!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) n
      lda = n
      ldb = n
      Allocate (a(lda,n),b(ldb),ipiv(n))

!     Read A and B from data file

      Read (nin,*)(a(i,1:n),i=1,n)
      Read (nin,*) b(1:n)

!     Solve the equations Ax = b for x

!     The NAG name equivalent of dgesv is f07aaf
      Call dgesv(n,1,a,lda,ipiv,b,ldb,info)

      If (info==0) Then

!       Print solution

        Write (nout,*) 'Solution'
        Write (nout,99999) b(1:n)

!       Print details of factorization

        Write (nout,*)
        Flush (nout)

!       ifail: behaviour on error exit
!              =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
        ifail = 0
        Call x04caf('General',' ',n,n,a,lda,'Details of factorization',ifail)

!       Print pivot indices

        Write (nout,*)
        Write (nout,*) 'Pivot indices'
        Write (nout,99998) ipiv(1:n)

      Else
        Write (nout,99997) 'The (', info, ',', info, ')',                      &
          ' element of the factor U is zero'
      End If

99999 Format ((3X,7F11.4))
99998 Format ((3X,7I11))
99997 Format (1X,A,I3,A,I3,A,A)
    End Program f07aafe


f07abfe.f90

    Program f07abfe

!     F07ABF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: dgesvx, nag_wp, x04caf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: rcond
      Integer                          :: i, ifail, info, lda, ldaf, ldb, ldx, &
                                          n, nrhs
      Character (1)                    :: equed
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: a(:,:), af(:,:), b(:,:), berr(:),    &
                                          c(:), ferr(:), r(:), work(:), x(:,:)
      Integer, Allocatable             :: ipiv(:), iwork(:)
!     .. Executable Statements ..
      Write (nout,*) 'F07ABF Example Program Results'
      Write (nout,*)
      Flush (nout)
!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) n, nrhs
      lda = n
      ldaf = n
      ldb = n
      ldx = n
      Allocate (a(lda,n),af(ldaf,n),b(ldb,nrhs),berr(nrhs),c(n),ferr(nrhs),    &
        r(n),work(4*n),x(ldx,nrhs),ipiv(n),iwork(n))

!     Read A and B from data file

      Read (nin,*)(a(i,1:n),i=1,n)
      Read (nin,*)(b(i,1:nrhs),i=1,n)

!     Solve the equations AX = B for X

!     The NAG name equivalent of dgesvx is f07abf
      Call dgesvx('Equilibration','No transpose',n,nrhs,a,lda,af,ldaf,ipiv,    &
        equed,r,c,b,ldb,x,ldx,rcond,ferr,berr,work,iwork,info)

      If ((info==0) .Or. (info==n+1)) Then

!       Print solution, error bounds, condition number, the form
!       of equilibration and the pivot growth factor

!       ifail: behaviour on error exit
!              =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
        ifail = 0
        Call x04caf('General',' ',n,nrhs,x,ldx,'Solution(s)',ifail)

        Write (nout,*)
        Write (nout,*) 'Backward errors (machine-dependent)'
        Write (nout,99999) berr(1:nrhs)
        Write (nout,*)
        Write (nout,*) 'Estimated forward error bounds (machine-dependent)'
        Write (nout,99999) ferr(1:nrhs)
        Write (nout,*)
        If (equed=='N') Then
          Write (nout,*) 'A has not been equilibrated'
        Else If (equed=='R') Then
          Write (nout,*) 'A has been row scaled as diag(R)*A'
        Else If (equed=='C') Then
          Write (nout,*) 'A has been column scaled as A*diag(C)'
        Else If (equed=='B') Then
          Write (nout,*)                                                       &
            'A has been row and column scaled as diag(R)*A*diag(C)'
        End If
        Write (nout,*)
        Write (nout,*) 'Reciprocal condition number estimate of scaled matrix'
        Write (nout,99999) rcond
        Write (nout,*)
        Write (nout,*) 'Estimate of reciprocal pivot growth factor'
        Write (nout,99999) work(1)

        If (info==n+1) Then
          Write (nout,*)
          Write (nout,*) 'The matrix A is singular to working precision'
        End If
      Else
        Write (nout,99998) 'The (', info, ',', info, ')',                      &
          ' element of the factor U is zero'
      End If

99999 Format ((3X,1P,7E11.1))
99998 Format (1X,A,I3,A,I3,A,A)
    End Program f07abfe


f07acfe.f90

    Program f07acfe

!     F07ACF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: dsgesv, nag_rp, nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Integer                          :: i, info, iter, lda, ldb, ldx, n, r
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: a(:,:), b(:,:), work(:), x(:,:)
      Real (Kind=nag_rp), Allocatable  :: swork(:)
      Integer, Allocatable             :: ipiv(:)
!     .. Executable Statements ..
      Write (nout,*) 'F07ACF Example Program Results'
      Write (nout,*)
!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) n, r
      lda = n
      ldb = n
      ldx = n
      Allocate (a(lda,n),b(n,r),work(n*r),x(ldx,r),swork(n*(n+r)),ipiv(n))

!     Read A and B from data file

      Read (nin,*)(a(i,1:n),i=1,n)
      Read (nin,*)(b(i,1:r),i=1,n)

!     Solve the equations Ax = b for x

!     The NAG name equivalent of dsgesv is f07acf
      Call dsgesv(n,r,a,lda,ipiv,b,ldb,x,ldx,work,swork,iter,info)

      If (info==0) Then

!       Print solution

        Write (nout,*) 'Solution'
        Write (nout,99999)(x(i,1:r),i=1,n)

!       Print pivot indices

        Write (nout,*)
        Write (nout,*) 'Pivot indices'
        Write (nout,99998) ipiv(1:n)

      Else
        Write (nout,99997) 'The (', info, ',', info, ')',                      &
          ' element of the factor U is zero'
      End If

99999 Format ((3X,7F11.4))
99998 Format ((3X,7I11))
99997 Format (1X,A,I3,A,I3,A,A)
    End Program f07acfe


f07adfe.f90

    Program f07adfe

!     F07ADF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: dgetrf, nag_wp, x04caf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Integer                          :: i, ifail, info, lda, m, n
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: a(:,:)
      Integer, Allocatable             :: ipiv(:)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: min
!     .. Executable Statements ..
      Write (nout,*) 'F07ADF Example Program Results'
!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) m, n
      lda = m
      Allocate (a(lda,n),ipiv(n))

!     Read A from data file

      Read (nin,*)(a(i,1:n),i=1,m)

!     Factorize A

!     The NAG name equivalent of dgetrf is f07adf
      Call dgetrf(m,n,a,lda,ipiv,info)

!     Print details of factorization

      Write (nout,*)
      Flush (nout)

!     ifail: behaviour on error exit
!             =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
      ifail = 0
      Call x04caf('General',' ',m,n,a,lda,'Details of factorization',ifail)

!     Print pivot indices

      Write (nout,*)
      Write (nout,*) 'IPIV'
      Write (nout,99999) ipiv(1:min(m,n))

      If (info/=0) Then
        Write (nout,*) 'The factor U is singular'
      End If

99999 Format ((3X,7I11))
    End Program f07adfe


f07aefe.f90

    Program f07aefe

!     F07AEF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: dgetrf, dgetrs, nag_wp, x04caf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
      Character (1), Parameter         :: trans = 'N'
!     .. Local Scalars ..
      Integer                          :: i, ifail, info, lda, ldb, n, nrhs
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: a(:,:), b(:,:)
      Integer, Allocatable             :: ipiv(:)
!     .. Executable Statements ..
      Write (nout,*) 'F07AEF Example Program Results'
!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) n, nrhs
      lda = n
      ldb = n
      Allocate (a(lda,n),b(ldb,nrhs),ipiv(n))

!     Read A and B from data file

      Read (nin,*)(a(i,1:n),i=1,n)
      Read (nin,*)(b(i,1:nrhs),i=1,n)

!     Factorize A

!     The NAG name equivalent of dgetrf is f07adf
      Call dgetrf(n,n,a,lda,ipiv,info)

      Write (nout,*)
      Flush (nout)
      If (info==0) Then

!       Compute solution

!       The NAG name equivalent of dgetrs is f07aef
        Call dgetrs(trans,n,nrhs,a,lda,ipiv,b,ldb,info)

!       Print solution

!       ifail: behaviour on error exit
!              =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
        ifail = 0
        Call x04caf('General',' ',n,nrhs,b,ldb,'Solution(s)',ifail)
      Else
        Write (nout,*) 'The factor U is singular'
      End If

    End Program f07aefe


f07affe.f90

    Program f07affe

!     F07AFF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: dgeequ, dscal, f06fcf, nag_wp, x02ajf, x02amf,    &
                             x02bhf, x04caf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Real (Kind=nag_wp), Parameter    :: one = 1.0_nag_wp
      Real (Kind=nag_wp), Parameter    :: thresh = 0.1_nag_wp
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: amax, big, colcnd, rowcnd, small
      Integer                          :: i, ifail, info, j, lda, n
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: a(:,:), c(:), r(:)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: real
!     .. Executable Statements ..
      Write (nout,*) 'F07AFF Example Program Results'
      Write (nout,*)
      Flush (nout)
!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) n
      lda = n
      Allocate (a(lda,n),c(n),r(n))

!     Read the N by N matrix A from data file

      Read (nin,*)(a(i,1:n),i=1,n)

!     Print the matrix A

!     ifail: behaviour on error exit
!             =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
      ifail = 0
      Call x04caf('General',' ',n,n,a,lda,'Matrix A',ifail)
      Write (nout,*)

!     Compute row and column scaling factors

!     The NAG name equivalent of dgeequ is f07aff
      Call dgeequ(n,n,a,lda,r,c,rowcnd,colcnd,amax,info)

      If (info>0) Then
        If (info<=n) Then
          Write (nout,99999) 'Row ', info, ' of A is exactly zero'
        Else
          Write (nout,99999) 'Column ', info - n, ' of A is exactly zero'
        End If
      Else

!       Print ROWCND, COLCND, AMAX and the scale factors

        Write (nout,99998) 'ROWCND =', rowcnd, ', COLCND =', colcnd,           &
          ', AMAX =', amax
        Write (nout,*)
        Write (nout,*) 'Row scale factors'
        Write (nout,99997) r(1:n)
        Write (nout,*)
        Write (nout,*) 'Column scale factors'
        Write (nout,99997) c(1:n)
        Write (nout,*)
        Flush (nout)

!       Compute values close to underflow and overflow

        small = x02amf()/(x02ajf()*real(x02bhf(),kind=nag_wp))
        big = one/small
        If ((rowcnd>=thresh) .And. (amax>=small) .And. (amax<=big)) Then
          If (colcnd<thresh) Then

!           Just column scale A
!           The NAG name equivalent of dscal is f06edf
            Do j = 1, n
              Call dscal(n,c(j),a(1,j),1)
            End Do

          End If
        Else If (colcnd>=thresh) Then

!         Just row scale A
          Do j = 1, n
            Call f06fcf(n,r,1,a(1,j),1)
          End Do

        Else

!         Row and column scale A
          Do j = 1, n
            Call dscal(n,c(j),a(1,j),1)
            Call f06fcf(n,r,1,a(1,j),1)
          End Do

        End If

!       Print the scaled matrix
        ifail = 0
        Call x04caf('General',' ',n,n,a,lda,'Scaled matrix',ifail)

      End If

99999 Format (1X,A,I4,A)
99998 Format (1X,3(A,1P,E8.1))
99997 Format ((1X,1P,7E11.2))
    End Program f07affe


f07agfe.f90

    Program f07agfe

!     F07AGF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: dgecon, dgetrf, dlange => f06raf, nag_wp, x02ajf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
      Character (1), Parameter         :: norm = '1'
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: anorm, rcond
      Integer                          :: i, info, lda, n
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: a(:,:), work(:)
      Integer, Allocatable             :: ipiv(:), iwork(:)
!     .. Executable Statements ..
      Write (nout,*) 'F07AGF Example Program Results'
!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) n
      lda = n
      Allocate (a(lda,n),work(4*n),ipiv(n),iwork(n))

!     Read A from data file

      Read (nin,*)(a(i,1:n),i=1,n)

!     Compute norm of A

!     f06raf is the NAG name equivalent of the LAPACK auxiliary dlange
      anorm = dlange(norm,n,n,a,lda,work)

!     Factorize A
!     The NAG name equivalent of dgetrf is f07adf
      Call dgetrf(n,n,a,lda,ipiv,info)

      Write (nout,*)
      If (info==0) Then

!       Estimate condition number

!       The NAG name equivalent of dgecon is f07agf
        Call dgecon(norm,n,a,lda,anorm,rcond,work,iwork,info)

        If (rcond>=x02ajf()) Then
          Write (nout,99999) 'Estimate of condition number =',                 &
            1.0E0_nag_wp/rcond
        Else
          Write (nout,*) 'A is singular to working precision'
        End If
      Else
        Write (nout,*) 'The factor U is singular'
      End If

99999 Format (1X,A,1P,E10.2)
    End Program f07agfe


f07ahfe.f90

    Program f07ahfe

!     F07AHF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: dgerfs, dgetrf, dgetrs, nag_wp, x04caf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
      Character (1), Parameter         :: trans = 'N'
!     .. Local Scalars ..
      Integer                          :: i, ifail, info, lda, ldaf, ldb, ldx, &
                                          n, nrhs
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: a(:,:), af(:,:), b(:,:), berr(:),    &
                                          ferr(:), work(:), x(:,:)
      Integer, Allocatable             :: ipiv(:), iwork(:)
!     .. Executable Statements ..
      Write (nout,*) 'F07AHF Example Program Results'
!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) n, nrhs
      lda = n
      ldaf = n
      ldb = n
      ldx = n
      Allocate (a(lda,n),af(ldaf,n),b(ldb,nrhs),berr(nrhs),ferr(nrhs),         &
        work(3*n),x(ldx,n),ipiv(n),iwork(n))

!     Read A and B from data file, and copy A to AF and B to X

      Read (nin,*)(a(i,1:n),i=1,n)
      Read (nin,*)(b(i,1:nrhs),i=1,n)

      af(1:n,1:n) = a(1:n,1:n)
      x(1:n,1:nrhs) = b(1:n,1:nrhs)

!     Factorize A in the array AF

!     The NAG name equivalent of dgetrf is f07adf
      Call dgetrf(n,n,af,ldaf,ipiv,info)

      Write (nout,*)
      Flush (nout)
      If (info==0) Then

!       Compute solution in the array X

!       The NAG name equivalent of dgetrs is f07aef
        Call dgetrs(trans,n,nrhs,af,ldaf,ipiv,x,ldx,info)

!       Improve solution, and compute backward errors and
!       estimated bounds on the forward errors

!       The NAG name equivalent of dgerfs is f07ahf
        Call dgerfs(trans,n,nrhs,a,lda,af,ldaf,ipiv,b,ldb,x,ldx,ferr,berr,     &
          work,iwork,info)

!       Print solution

!       ifail: behaviour on error exit
!              =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
        ifail = 0

        Call x04caf('General',' ',n,nrhs,x,ldx,'Solution(s)',ifail)

        Write (nout,*)
        Write (nout,*) 'Backward errors (machine-dependent)'
        Write (nout,99999) berr(1:nrhs)
        Write (nout,*) 'Estimated forward error bounds (machine-dependent)'
        Write (nout,99999) ferr(1:nrhs)
      Else
        Write (nout,*) 'The factor U is singular'
      End If

99999 Format ((3X,1P,7E11.1))
    End Program f07ahfe


f07ajfe.f90

    Program f07ajfe

!     F07AJF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: dgetrf, dgetri, nag_wp, x04caf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Integer                          :: i, ifail, info, lda, lwork, n
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: a(:,:), work(:)
      Integer, Allocatable             :: ipiv(:)
!     .. Executable Statements ..
      Write (nout,*) 'F07AJF Example Program Results'
!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) n
      lda = n
      lwork = 64*n
      Allocate (a(lda,n),work(lwork),ipiv(n))

!     Read A from data file

      Read (nin,*)(a(i,1:n),i=1,n)

!     Factorize A

!     The NAG name equivalent of dgetrf is f07adf
      Call dgetrf(n,n,a,lda,ipiv,info)

      Write (nout,*)
      Flush (nout)
      If (info==0) Then

!       Compute inverse of A

!       The NAG name equivalent of dgetri is f07ajf
        Call dgetri(n,a,lda,ipiv,work,lwork,info)

!       Print inverse

!       ifail: behaviour on error exit
!              =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
        ifail = 0
        Call x04caf('General',' ',n,n,a,lda,'Inverse',ifail)

      Else
        Write (nout,*) 'The factor U is singular'
      End If

    End Program f07ajfe


f07anfe.f90

    Program f07anfe

!     F07ANF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: nag_wp, x04dbf, zgesv
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Integer                          :: i, ifail, info, lda, ldb, n
!     .. Local Arrays ..
      Complex (Kind=nag_wp), Allocatable :: a(:,:), b(:)
      Integer, Allocatable             :: ipiv(:)
      Character (1)                    :: clabs(1), rlabs(1)
!     .. Executable Statements ..
      Write (nout,*) 'F07ANF Example Program Results'
      Write (nout,*)
!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) n
      lda = n
      ldb = n
      Allocate (a(lda,n),b(ldb),ipiv(n))

!     Read A and B from data file

      Read (nin,*)(a(i,1:n),i=1,n)
      Read (nin,*) b(1:n)

!     Solve the equations Ax = b for x

!     The NAG name equivalent of zgesv is f07anf
      Call zgesv(n,1,a,lda,ipiv,b,ldb,info)

      If (info==0) Then

!       Print solution

        Write (nout,*) 'Solution'
        Write (nout,99999) b(1:n)

!       Print details of factorization

        Write (nout,*)
        Flush (nout)

!       ifail: behaviour on error exit
!              =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
        ifail = 0
        Call x04dbf('General',' ',n,n,a,lda,'Bracketed','F7.4',                &
          'Details of factorization','Integer',rlabs,'Integer',clabs,80,0,     &
          ifail)

!       Print pivot indices

        Write (nout,*)
        Write (nout,*) 'Pivot indices'
        Write (nout,99998) ipiv(1:n)
      Else
        Write (nout,99997) 'The (', info, ',', info, ')',                      &
          ' element of the factor U is zero'
      End If

99999 Format ((3X,4(' (',F7.4,',',F7.4,')',:)))
99998 Format (1X,7I11)
99997 Format (1X,A,I3,A,I3,A,A)
    End Program f07anfe


f07apfe.f90

    Program f07apfe

!     F07APF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: nag_wp, x04dbf, zgesvx
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: rcond
      Integer                          :: i, ifail, info, lda, ldaf, ldb, ldx, &
                                          n, nrhs
      Character (1)                    :: equed
!     .. Local Arrays ..
      Complex (Kind=nag_wp), Allocatable :: a(:,:), af(:,:), b(:,:), work(:),  &
                                          x(:,:)
      Real (Kind=nag_wp), Allocatable  :: berr(:), c(:), ferr(:), r(:),        &
                                          rwork(:)
      Integer, Allocatable             :: ipiv(:)
      Character (1)                    :: clabs(1), rlabs(1)
!     .. Executable Statements ..
      Write (nout,*) 'F07APF Example Program Results'
      Write (nout,*)
      Flush (nout)
!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) n, nrhs
      lda = n
      ldaf = n
      ldb = n
      ldx = n
      Allocate (a(lda,n),af(ldaf,n),b(ldb,nrhs),work(2*n),x(ldx,nrhs),         &
        berr(nrhs),c(n),ferr(nrhs),r(n),rwork(2*n),ipiv(n))

!     Read A and B from data file

      Read (nin,*)(a(i,1:n),i=1,n)
      Read (nin,*)(b(i,1:nrhs),i=1,n)

!     Solve the equations AX = B for X

!     The NAG name equivalent of zgesvx is f07apf
      Call zgesvx('Equilibrate','No transpose',n,nrhs,a,lda,af,ldaf,ipiv,      &
        equed,r,c,b,ldb,x,ldx,rcond,ferr,berr,work,rwork,info)

      If ((info==0) .Or. (info==n+1)) Then

!       Print solution, error bounds, condition number, the form
!       of equilibration and the pivot growth factor

!       ifail: behaviour on error exit
!              =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
        ifail = 0
        Call x04dbf('General',' ',n,nrhs,x,ldx,'Bracketed','F7.4',             &
          'Solution(s)','Integer',rlabs,'Integer',clabs,80,0,ifail)

        Write (nout,*)
        Write (nout,*) 'Backward errors (machine-dependent)'
        Write (nout,99999) berr(1:nrhs)
        Write (nout,*)
        Write (nout,*) 'Estimated forward error bounds (machine-dependent)'
        Write (nout,99999) ferr(1:nrhs)
        Write (nout,*)
        If (equed=='N') Then
          Write (nout,*) 'A has not been equilibrated'
        Else If (equed=='R') Then
          Write (nout,*) 'A has been row scaled as diag(R)*A'
        Else If (equed=='C') Then
          Write (nout,*) 'A has been column scaled as A*diag(C)'
        Else If (equed=='B') Then
          Write (nout,*)                                                       &
            'A has been row and column scaled as diag(R)*A*diag(C)'
        End If
        Write (nout,*)
        Write (nout,*) 'Reciprocal condition number estimate of scaled matrix'
        Write (nout,99999) rcond
        Write (nout,*)
        Write (nout,*) 'Estimate of reciprocal pivot growth factor'
        Write (nout,99999) rwork(1)

        If (info==n+1) Then
          Write (nout,*)
          Write (nout,*) 'The matrix A is singular to working precision'
        End If
      Else
        Write (nout,99998) 'The (', info, ',', info, ')',                      &
          ' element of the factor U is zero'
      End If

99999 Format ((3X,1P,7E11.1))
99998 Format (1X,A,I3,A,I3,A,A)
    End Program f07apfe


f07aqfe.f90

    Program f07aqfe

!     F07AQF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: nag_rp, nag_wp, zcgesv
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Integer                          :: i, info, iter, j, lda, ldb, ldx, n,  &
                                          r
!     .. Local Arrays ..
      Complex (Kind=nag_wp), Allocatable :: a(:,:), b(:,:), work(:), x(:,:)
      Complex (Kind=nag_rp), Allocatable :: swork(:)
      Real (Kind=nag_wp), Allocatable  :: rwork(:)
      Integer, Allocatable             :: ipiv(:)
!     .. Executable Statements ..
      Write (nout,*) 'F07AQF Example Program Results'
      Write (nout,*)
!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) n, r
      lda = n
      ldb = n
      ldx = n
      Allocate (a(lda,n),b(ldb,r),work(n*r),x(ldx,r),swork(n*(n+               &
        r)),ipiv(n),rwork(n))

!     Read A and B from data file

      Read (nin,*)(a(i,1:n),i=1,n)
      Read (nin,*)(b(i,1:r),i=1,n)

!     Solve the equations Ax = b for x

!     The NAG name equivalent of zcgesv is f07aqf
      Call zcgesv(n,r,a,lda,ipiv,b,ldb,x,ldx,work,swork,rwork,iter,info)

      If (info==0) Then

!       Print solution

        Write (nout,*) 'Solution'
        Write (nout,99999)((x(i,r),j=1,r),i=1,n)

!       Print pivot indices

        Write (nout,*)
        Write (nout,*) 'Pivot indices'
        Write (nout,99998) ipiv(1:n)

      Else
        Write (nout,99997) 'The (', info, ',', info, ')',                      &
          ' element of the factor U is zero'
      End If

99999 Format ((3X,4(' (',F7.4,',',F7.4,')',:)))
99998 Format (1X,7I11)
99997 Format (1X,A,I3,A,I3,A,A)
    End Program f07aqfe


f07arfe.f90

    Program f07arfe

!     F07ARF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: nag_wp, x04dbf, zgetrf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Integer                          :: i, ifail, info, lda, m, n
!     .. Local Arrays ..
      Complex (Kind=nag_wp), Allocatable :: a(:,:)
      Integer, Allocatable             :: ipiv(:)
      Character (1)                    :: clabs(1), rlabs(1)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: min
!     .. Executable Statements ..
      Write (nout,*) 'F07ARF Example Program Results'
!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) m, n
      lda = m
      Allocate (a(lda,n),ipiv(n))

!     Read A from data file

      Read (nin,*)(a(i,1:n),i=1,m)

!     Factorize A

!     The NAG name equivalent of zgetrf is f07arf
      Call zgetrf(m,n,a,lda,ipiv,info)

!     Print details of factorization

      Write (nout,*)
      Flush (nout)

!     ifail: behaviour on error exit
!             =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
      ifail = 0
      Call x04dbf('General',' ',m,n,a,lda,'Bracketed','F7.4',                  &
        'Details of factorization','Integer',rlabs,'Integer',clabs,80,0,ifail)

!     Print pivot indices

      Write (nout,*)
      Write (nout,*) 'IPIV'
      Write (nout,99999) ipiv(1:min(m,n))

      If (info/=0) Then
        Write (nout,*) 'The factor U is singular'
      End If

99999 Format ((1X,I12,3I18))
    End Program f07arfe


f07asfe.f90

    Program f07asfe

!     F07ASF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: nag_wp, x04dbf, zgetrf, zgetrs
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
      Character (1), Parameter         :: trans = 'N'
!     .. Local Scalars ..
      Integer                          :: i, ifail, info, lda, ldb, n, nrhs
!     .. Local Arrays ..
      Complex (Kind=nag_wp), Allocatable :: a(:,:), b(:,:)
      Integer, Allocatable             :: ipiv(:)
      Character (1)                    :: clabs(1), rlabs(1)
!     .. Executable Statements ..
      Write (nout,*) 'F07ASF Example Program Results'
!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) n, nrhs
      lda = n
      ldb = n
      Allocate (a(lda,n),b(ldb,nrhs),ipiv(n))

!     Read A and B from data file

      Read (nin,*)(a(i,1:n),i=1,n)
      Read (nin,*)(b(i,1:nrhs),i=1,n)

!     Factorize A

!     The NAG name equivalent of zgetrf is f07arf
      Call zgetrf(n,n,a,lda,ipiv,info)

      Write (nout,*)
      Flush (nout)
      If (info==0) Then

!       Compute solution

!       The NAG name equivalent of zgetrs is f07asf
        Call zgetrs(trans,n,nrhs,a,lda,ipiv,b,ldb,info)

!       Print solution

!       ifail: behaviour on error exit
!              =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
        ifail = 0
        Call x04dbf('General',' ',n,nrhs,b,ldb,'Bracketed','F7.4',             &
          'Solution(s)','Integer',rlabs,'Integer',clabs,80,0,ifail)

      Else
        Write (nout,*) 'The factor U is singular'
      End If

    End Program f07asfe


f07atfe.f90

    Program f07atfe

!     F07ATF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: f06kcf, nag_wp, x02ajf, x02amf, x02bhf, x04dbf,   &
                             zdscal, zgeequ
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Real (Kind=nag_wp), Parameter    :: one = 1.0_nag_wp
      Real (Kind=nag_wp), Parameter    :: thresh = 0.1_nag_wp
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: amax, big, colcnd, rowcnd, small
      Integer                          :: i, ifail, info, j, lda, n
!     .. Local Arrays ..
      Complex (Kind=nag_wp), Allocatable :: a(:,:)
      Real (Kind=nag_wp), Allocatable  :: c(:), r(:)
      Character (1)                    :: clabs(1), rlabs(1)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: real
!     .. Executable Statements ..
      Write (nout,*) 'F07ATF Example Program Results'
      Write (nout,*)
      Flush (nout)
!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) n
      lda = n
      Allocate (a(lda,n),c(n),r(n))

!     Read the N by N matrix A from data file

      Read (nin,*)(a(i,1:n),i=1,n)

!     Print the matrix A

!     ifail: behaviour on error exit
!             =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
      ifail = 0
      Call x04dbf('General',' ',n,n,a,lda,'Bracketed','1P,E10.2','Matrix A',   &
        'Integer',rlabs,'Integer',clabs,80,0,ifail)

      Write (nout,*)

!     Compute row and column scaling factors

!     The NAG name equivalent of zgeequ is f07atf
      Call zgeequ(n,n,a,lda,r,c,rowcnd,colcnd,amax,info)

      If (info>0) Then
        If (info<=n) Then
          Write (nout,99999) 'Row ', info, ' of A is exactly zero'
        Else
          Write (nout,99999) 'Column ', info - n, ' of A is exactly zero'
        End If
      Else

!       Print ROWCND, COLCND, AMAX and the scale factors

        Write (nout,99998) 'ROWCND =', rowcnd, ', COLCND =', colcnd,           &
          ', AMAX =', amax
        Write (nout,*)
        Write (nout,*) 'Row scale factors'
        Write (nout,99997) r(1:n)
        Write (nout,*)
        Write (nout,*) 'Column scale factors'
        Write (nout,99997) c(1:n)
        Write (nout,*)
        Flush (nout)

!       Compute values close to underflow and overflow

        small = x02amf()/(x02ajf()*real(x02bhf(),kind=nag_wp))
        big = one/small
        If ((rowcnd>=thresh) .And. (amax>=small) .And. (amax<=big)) Then
          If (colcnd<thresh) Then

!           Just column scale A
!           The NAG name equivalent of zdscal is f06jdf
            Do j = 1, n
              Call zdscal(n,c(j),a(1,j),1)
            End Do

          End If
        Else If (colcnd>=thresh) Then

!         Just row scale A
          Do j = 1, n
            Call f06kcf(n,r,1,a(1,j),1)
          End Do

        Else

!         Row and column scale A
          Do j = 1, n
            Call zdscal(n,c(j),a(1,j),1)
            Call f06kcf(n,r,1,a(1,j),1)
          End Do

        End If

!       Print the scaled matrix
        ifail = 0
        Call x04dbf('General',' ',n,n,a,lda,'Bracketed',' ','Scaled matrix',   &
          'Integer',rlabs,'Integer',clabs,80,0,ifail)

      End If

99999 Format (1X,A,I4,A)
99998 Format (1X,3(A,1P,E8.1))
99997 Format ((1X,1P,7E11.2))
    End Program f07atfe


f07aufe.f90

    Program f07aufe

!     F07AUF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: nag_wp, x02ajf, zgecon, zgetrf, zlange => f06uaf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
      Character (1), Parameter         :: norm = '1'
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: anorm, rcond
      Integer                          :: i, info, lda, n
!     .. Local Arrays ..
      Complex (Kind=nag_wp), Allocatable :: a(:,:), work(:)
      Real (Kind=nag_wp), Allocatable  :: rwork(:)
      Integer, Allocatable             :: ipiv(:)
!     .. Executable Statements ..
      Write (nout,*) 'F07AUF Example Program Results'
!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) n
      lda = n
      Allocate (a(lda,n),work(2*n),rwork(2*n),ipiv(n))

!     Read A from data file

      Read (nin,*)(a(i,1:n),i=1,n)

!     Compute norm of A
!     f06uaf is the NAG name equivalent of the LAPACK auxiliary zlange
      anorm = zlange(norm,n,n,a,lda,rwork)

!     Factorize A
!     The NAG name equivalent of zgetrf is f07arf
      Call zgetrf(n,n,a,lda,ipiv,info)

      Write (nout,*)
      If (info==0) Then

!       Estimate condition number

!       The NAG name equivalent of zgecon is f07auf
        Call zgecon(norm,n,a,lda,anorm,rcond,work,rwork,info)

        If (rcond>=x02ajf()) Then
          Write (nout,99999) 'Estimate of condition number =',                 &
            1.0_nag_wp/rcond
        Else
          Write (nout,*) 'A is singular to working precision'
        End If
      Else
        Write (nout,*) 'The factor U is singular'
      End If

99999 Format (1X,A,1P,E10.2)
    End Program f07aufe


f07avfe.f90

    Program f07avfe

!     F07AVF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: nag_wp, x04dbf, zgerfs, zgetrf, zgetrs
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
      Character (1), Parameter         :: trans = 'N'
!     .. Local Scalars ..
      Integer                          :: i, ifail, info, lda, ldaf, ldb, ldx, &
                                          n, nrhs
!     .. Local Arrays ..
      Complex (Kind=nag_wp), Allocatable :: a(:,:), af(:,:), b(:,:), work(:),  &
                                          x(:,:)
      Real (Kind=nag_wp), Allocatable  :: berr(:), ferr(:), rwork(:)
      Integer, Allocatable             :: ipiv(:)
      Character (1)                    :: clabs(1), rlabs(1)
!     .. Executable Statements ..
      Write (nout,*) 'F07AVF Example Program Results'
!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) n, nrhs
      lda = n
      ldaf = n
      ldb = n
      ldx = n
      Allocate (a(lda,n),af(ldaf,n),b(ldb,nrhs),work(2*n),x(ldx,n),berr(nrhs), &
        ferr(nrhs),rwork(n),ipiv(n))

!     Read A and B from data file, and copy A to AF and B to X

      Read (nin,*)(a(i,1:n),i=1,n)
      Read (nin,*)(b(i,1:nrhs),i=1,n)

      af(1:n,1:n) = a(1:n,1:n)
      x(1:n,1:nrhs) = b(1:n,1:nrhs)

!     Factorize A in the array AF
!     The NAG name equivalent of zgetrf is f07arf
      Call zgetrf(n,n,af,ldaf,ipiv,info)

      Write (nout,*)
      Flush (nout)
      If (info==0) Then

!       Compute solution in the array X

!       The NAG name equivalent of zgetrs is f07asf
        Call zgetrs(trans,n,nrhs,af,ldaf,ipiv,x,ldx,info)

!       Improve solution, and compute backward errors and
!       estimated bounds on the forward errors

!       The NAG name equivalent of zgerfs is f07avf
        Call zgerfs(trans,n,nrhs,a,lda,af,ldaf,ipiv,b,ldb,x,ldx,ferr,berr,     &
          work,rwork,info)

!       Print solution

!       ifail: behaviour on error exit
!              =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
        ifail = 0
        Call x04dbf('General',' ',n,nrhs,x,ldx,'Bracketed','F7.4',             &
          'Solution(s)','Integer',rlabs,'Integer',clabs,80,0,ifail)

        Write (nout,*)
        Write (nout,*) 'Backward errors (machine-dependent)'
        Write (nout,99999) berr(1:nrhs)
        Write (nout,*) 'Estimated forward error bounds (machine-dependent)'
        Write (nout,99999) ferr(1:nrhs)
      Else
        Write (nout,*) 'The factor U is singular'
      End If

99999 Format ((5X,1P,4(E11.1,7X)))
    End Program f07avfe


f07awfe.f90

    Program f07awfe

!     F07AWF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: nag_wp, x04dbf, zgetrf, zgetri
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Integer                          :: i, ifail, info, lda, lwork, n
!     .. Local Arrays ..
      Complex (Kind=nag_wp), Allocatable :: a(:,:), work(:)
      Integer, Allocatable             :: ipiv(:)
      Character (1)                    :: clabs(1), rlabs(1)
!     .. Executable Statements ..
      Write (nout,*) 'F07AWF Example Program Results'
!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) n
      lda = n
      lwork = 64*n
      Allocate (a(lda,n),work(lwork),ipiv(n))

!     Read A from data file

      Read (nin,*)(a(i,1:n),i=1,n)

!     Factorize A
!     The NAG name equivalent of zgetrf is f07arf
      Call zgetrf(n,n,a,lda,ipiv,info)

      Write (nout,*)
      Flush (nout)
      If (info==0) Then

!       Compute inverse of A
!       The NAG name equivalent of zgetri is f07awf
        Call zgetri(n,a,lda,ipiv,work,lwork,info)

!       Print inverse

!       ifail: behaviour on error exit
!              =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
        ifail = 0
        Call x04dbf('General',' ',n,n,a,lda,'Bracketed','F7.4','Inverse',      &
          'Integer',rlabs,'Integer',clabs,80,0,ifail)

      Else
        Write (nout,*) 'The factor U is singular'
      End If

    End Program f07awfe


f07bafe.f90

    Program f07bafe

!     F07BAF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: dgbsv, nag_wp, x04cef
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Integer                          :: i, ifail, info, j, k, kl, ku, ldab,  &
                                          n
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: ab(:,:), b(:)
      Integer, Allocatable             :: ipiv(:)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: max, min
!     .. Executable Statements ..
      Write (nout,*) 'F07BAF Example Program Results'
      Write (nout,*)
!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) n, kl, ku
      ldab = 2*kl + ku + 1
      Allocate (ab(ldab,n),b(n),ipiv(n))

!     Read the band matrix A and the right hand side b from data file

      k = kl + ku + 1
      Read (nin,*)((ab(k+i-j,j),j=max(i-kl,1),min(i+ku,n)),i=1,n)
      Read (nin,*) b(1:n)

!     Solve the equations Ax = b for x
!     The NAG name equivalent of dgbsv is f07baf
      Call dgbsv(n,kl,ku,1,ab,ldab,ipiv,b,n,info)

      If (info==0) Then

!       Print solution

        Write (nout,*) 'Solution'
        Write (nout,99999) b(1:n)

!       Print details of the factorization

        Write (nout,*)
        Flush (nout)

!       ifail: behaviour on error exit
!              =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
        ifail = 0
        Call x04cef(n,n,kl,kl+ku,ab,ldab,'Details of factorization',ifail)

!       Print pivot indices'

        Write (nout,*)
        Write (nout,*) 'Pivot indices'
        Write (nout,99998) ipiv(1:n)

      Else
        Write (nout,99997) 'The (', info, ',', info, ')',                      &
          ' element of the factor U is zero'
      End If

99999 Format ((3X,7F11.4))
99998 Format ((3X,7I11))
99997 Format (1X,A,I3,A,I3,A,A)
    End Program f07bafe


f07bbfe.f90

    Program f07bbfe

!     F07BBF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: dgbsvx, nag_wp, x04caf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: rcond
      Integer                          :: i, ifail, info, j, k, kl, ku, ldab,  &
                                          ldafb, ldb, ldx, n, nrhs
      Character (1)                    :: equed
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: ab(:,:), afb(:,:), b(:,:), berr(:),  &
                                          c(:), ferr(:), r(:), work(:), x(:,:)
      Integer, Allocatable             :: ipiv(:), iwork(:)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: max, min
!     .. Executable Statements ..
      Write (nout,*) 'F07BBF Example Program Results'
      Write (nout,*)
      Flush (nout)
!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) n, nrhs, kl, ku
      ldb = n
      ldx = n
      ldab = kl + ku + 1
      ldafb = ldab + kl
      Allocate (ab(ldab,n),afb(ldafb,n),b(ldb,nrhs),berr(nrhs),c(n),           &
        ferr(nrhs),r(n),work(3*n),x(ldx,nrhs),ipiv(n),iwork(n))

!     Read the band matrix A and B from data file

      k = ku + 1
      Read (nin,*)((ab(k+i-j,j),j=max(i-kl,1),min(i+ku,n)),i=1,n)
      Read (nin,*)(b(i,1:nrhs),i=1,n)

!     Solve the equations AX = B for X
!     The NAG name equivalent of dgbsvx is f07bbf
      Call dgbsvx('Equilibration','No transpose',n,kl,ku,nrhs,ab,ldab,afb,     &
        ldafb,ipiv,equed,r,c,b,ldb,x,ldx,rcond,ferr,berr,work,iwork,info)

      If ((info==0) .Or. (info==n+1)) Then

!       Print solution, error bounds, condition number, the form
!       of equilibration and the pivot growth factor

!       ifail: behaviour on error exit
!              =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
        ifail = 0
        Call x04caf('General',' ',n,nrhs,x,ldx,'Solution(s)',ifail)

        Write (nout,*)
        Write (nout,*) 'Backward errors (machine-dependent)'
        Write (nout,99999) berr(1:nrhs)
        Write (nout,*)
        Write (nout,*) 'Estimated forward error bounds (machine-dependent)'
        Write (nout,99999) ferr(1:nrhs)
        Write (nout,*)
        Write (nout,*) 'Estimate of reciprocal condition number'
        Write (nout,99999) rcond
        Write (nout,*)
        If (equed=='N') Then
          Write (nout,*) 'A has not been equilibrated'
        Else If (equed=='R') Then
          Write (nout,*) 'A has been row scaled as diag(R)*A'
        Else If (equed=='C') Then
          Write (nout,*) 'A has been column scaled as A*diag(C)'
        Else If (equed=='B') Then
          Write (nout,*)                                                       &
            'A has been row and column scaled as diag(R)*A*diag(C)'
        End If
        Write (nout,*)
        Write (nout,*) 'Estimate of reciprocal pivot growth factor'
        Write (nout,99999) work(1)

        If (info==n+1) Then
          Write (nout,*)
          Write (nout,*) 'The matrix A is singular to working precision'
        End If
      Else
        Write (nout,99998) 'The (', info, ',', info, ')',                      &
          ' element of the factor U is zero'
      End If

99999 Format ((3X,1P,7E11.1))
99998 Format (1X,A,I3,A,I3,A,A)
    End Program f07bbfe


f07bdfe.f90

    Program f07bdfe

!     F07BDF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: dgbtrf, nag_wp, x04cef
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Integer                          :: i, ifail, info, j, k, kl, ku, ldab,  &
                                          m, n
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: ab(:,:)
      Integer, Allocatable             :: ipiv(:)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: max, min
!     .. Executable Statements ..
      Write (nout,*) 'F07BDF Example Program Results'
!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) m, n, kl, ku
      ldab = 2*kl + ku + 1
      Allocate (ab(ldab,n),ipiv(n))

!     Read A from data file

      k = kl + ku + 1
      Read (nin,*)((ab(k+i-j,j),j=max(i-kl,1),min(i+ku,n)),i=1,m)

!     Factorize A
!     The NAG name equivalent of dgbtrf is f07bdf
      Call dgbtrf(m,n,kl,ku,ab,ldab,ipiv,info)

!     Print details of factorization

      Write (nout,*)
      Flush (nout)

!     ifail: behaviour on error exit
!             =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
      ifail = 0
      Call x04cef(m,n,kl,kl+ku,ab,ldab,'Details of factorization',ifail)

!     Print pivot indices

      Write (nout,*)
      Write (nout,*) 'IPIV'
      Write (nout,99999) ipiv(1:min(m,n))

      If (info/=0) Then
        Write (nout,*) 'The factor U is singular'
      End If

99999 Format ((3X,7I11))
    End Program f07bdfe


f07befe.f90

    Program f07befe

!     F07BEF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: dgbtrf, dgbtrs, nag_wp, x04caf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
      Character (1), Parameter         :: trans = 'N'
!     .. Local Scalars ..
      Integer                          :: i, ifail, info, j, k, kl, ku, ldab,  &
                                          ldb, n, nrhs
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: ab(:,:), b(:,:)
      Integer, Allocatable             :: ipiv(:)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: max, min
!     .. Executable Statements ..
      Write (nout,*) 'F07BEF Example Program Results'
!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) n, nrhs, kl, ku
      ldab = 2*kl + ku + 1
      ldb = n
      Allocate (ab(ldab,n),b(ldb,nrhs),ipiv(n))

!     Read A and B from data file

      k = kl + ku + 1
      Read (nin,*)((ab(k+i-j,j),j=max(i-kl,1),min(i+ku,n)),i=1,n)
      Read (nin,*)(b(i,1:nrhs),i=1,n)

!     Factorize A
!     The NAG name equivalent of dgbtrf is f07bdf
      Call dgbtrf(n,n,kl,ku,ab,ldab,ipiv,info)

      Write (nout,*)
      Flush (nout)
      If (info==0) Then

!       Compute solution
!       The NAG name equivalent of dgbtrs is f07bef
        Call dgbtrs(trans,n,kl,ku,nrhs,ab,ldab,ipiv,b,ldb,info)

!       Print solution

!       ifail: behaviour on error exit
!              =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
        ifail = 0
        Call x04caf('General',' ',n,nrhs,b,ldb,'Solution(s)',ifail)

      Else
        Write (nout,*) 'The factor U is singular'
      End If

    End Program f07befe


f07bffe.f90

    Program f07bffe

!     F07BFF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: dgbequ, dscal, f06fcf, nag_wp, x02ajf, x02amf,    &
                             x02bhf, x04cef
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Real (Kind=nag_wp), Parameter    :: one = 1.0_nag_wp
      Real (Kind=nag_wp), Parameter    :: thresh = 0.1_nag_wp
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: amax, big, colcnd, rowcnd, small
      Integer                          :: i, i0, i1, ifail, ilen, info, j, k,  &
                                          kl, ku, ldab, n
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: ab(:,:), c(:), r(:)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: max, min, real
!     .. Executable Statements ..
      Write (nout,*) 'F07BFF Example Program Results'
      Write (nout,*)
      Flush (nout)
!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) n, kl, ku
      ldab = kl + ku + 1
      Allocate (ab(ldab,n),c(n),r(n))

!     Read the band matrix A from data file

      k = ku + 1
      Read (nin,*)((ab(k+i-j,j),j=max(i-kl,1),min(i+ku,n)),i=1,n)

!     Print the matrix A

!     ifail: behaviour on error exit
!             =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
      ifail = 0
      Call x04cef(n,n,kl,ku,ab,ldab,'Matrix A',ifail)

      Write (nout,*)

!     Compute row and column scaling factors

!     The NAG name equivalent of dgbequ is f07bff
      Call dgbequ(n,n,kl,ku,ab,ldab,r,c,rowcnd,colcnd,amax,info)

      If (info>0) Then
        If (info<=n) Then
          Write (nout,99999) 'Row ', info, ' of A is exactly zero'
        Else
          Write (nout,99999) 'Column ', info - n, ' of A is exactly zero'
        End If
      Else

!       Print ROWCND, COLCND, AMAX and the scale factors

        Write (nout,99998) 'ROWCND =', rowcnd, ', COLCND =', colcnd,           &
          ', AMAX =', amax
        Write (nout,*)
        Write (nout,*) 'Row scale factors'
        Write (nout,99997) r(1:n)
        Write (nout,*)
        Write (nout,*) 'Column scale factors'
        Write (nout,99997) c(1:n)
        Write (nout,*)
        Flush (nout)

!       Compute values close to underflow and overflow

        small = x02amf()/(x02ajf()*real(x02bhf(),kind=nag_wp))
        big = one/small
        If ((rowcnd>=thresh) .And. (amax>=small) .And. (amax<=big)) Then
          If (colcnd<thresh) Then
!           Just column scale A
!           The NAG name equivalent of dscal is f06edf
            Do j = 1, n
              i1 = 1 + max(1,j-ku) - (j-ku)
              ilen = min(n,j+kl) - max(1,j-ku) + 1
              Call dscal(ilen,c(j),ab(i1,j),1)
            End Do

          End If
        Else If (colcnd>=thresh) Then

!         Just row scale A
          Do j = 1, n
            i0 = max(1,j-ku)
            i1 = 1 + i0 - (j-ku)
            ilen = min(n,j+kl) - i0 + 1
            Call f06fcf(ilen,r(i0),1,ab(i1,j),1)
          End Do

        Else

!         Row and column scale A
          Do j = 1, n
            i0 = max(1,j-ku)
            i1 = 1 + i0 - (j-ku)
            ilen = min(n,j+kl) - i0 + 1
            Call dscal(ilen,c(j),ab(i1,j),1)
            Call f06fcf(ilen,r(i0),1,ab(i1,j),1)
          End Do

        End If

!       Print the scaled matrix
        ifail = 0
        Call x04cef(n,n,kl,ku,ab,ldab,'Scaled matrix',ifail)

      End If

99999 Format (1X,A,I4,A)
99998 Format (1X,3(A,1P,E8.1))
99997 Format ((1X,1P,7E11.2))
    End Program f07bffe


f07bgfe.f90

    Program f07bgfe

!     F07BGF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: dgbcon, dgbtrf, dlangb => f06rbf, nag_wp, x02ajf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
      Character (1), Parameter         :: norm = '1'
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: anorm, rcond
      Integer                          :: i, info, j, k, kl, ku, ldab, n
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: ab(:,:), work(:)
      Integer, Allocatable             :: ipiv(:), iwork(:)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: max, min
!     .. Executable Statements ..
      Write (nout,*) 'F07BGF Example Program Results'
!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) n, kl, ku
      ldab = 2*kl + ku + 1
      Allocate (ab(ldab,n),work(3*n),ipiv(n),iwork(n))

!     Read A from data file

      k = kl + ku + 1
      Read (nin,*)((ab(k+i-j,j),j=max(i-kl,1),min(i+ku,n)),i=1,n)

!     Compute norm of A
!     f06rbf is the NAG name equivalent of the LAPACK auxiliary dlangb
      anorm = dlangb(norm,n,kl,ku,ab(kl+1,1),ldab,work)

!     Factorize A

!     The NAG name equivalent of dgbtrf id f07bdf
      Call dgbtrf(n,n,kl,ku,ab,ldab,ipiv,info)

      Write (nout,*)
      If (info==0) Then

!       Estimate condition number

!       The NAG name equivalent of dgbcon is f07bgf
        Call dgbcon(norm,n,kl,ku,ab,ldab,ipiv,anorm,rcond,work,iwork,info)

        If (rcond>=x02ajf()) Then
          Write (nout,99999) 'Estimate of condition number =',                 &
            1.0_nag_wp/rcond
        Else
          Write (nout,*) 'A is singular to working precision'
        End If
      Else
        Write (nout,*) 'The factor U is singular'
      End If

99999 Format (1X,A,1P,E10.2)
    End Program f07bgfe


f07bhfe.f90

    Program f07bhfe

!     F07BHF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: dgbrfs, dgbtrf, dgbtrs, nag_wp, x04caf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Real (Kind=nag_wp), Parameter    :: zero = 0.0E0_nag_wp
      Integer, Parameter               :: nin = 5, nout = 6
      Character (1), Parameter         :: trans = 'N'
!     .. Local Scalars ..
      Integer                          :: i, ifail, info, j, k, kl, ku, ldab,  &
                                          ldafb, ldb, ldx, n, nrhs
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: ab(:,:), afb(:,:), b(:,:), berr(:),  &
                                          ferr(:), work(:), x(:,:)
      Integer, Allocatable             :: ipiv(:), iwork(:)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: max, min
!     .. Executable Statements ..
      Write (nout,*) 'F07BHF Example Program Results'
!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) n, nrhs, kl, ku
      ldab = kl + ku + 1
      ldafb = 2*kl + ku + 1
      ldb = n
      ldx = n
      Allocate (ab(ldab,n),afb(ldafb,n),b(ldb,nrhs),berr(nrhs),ferr(nrhs),     &
        work(3*n),x(ldx,n),ipiv(n),iwork(n))

!     Set A to zero to avoid referencing uninitialized elements

      ab(1:kl+ku+1,1:n) = zero

!     Read A and B from data file, and copy A to AFB and B to X

      k = ku + 1
      Read (nin,*)((ab(k+i-j,j),j=max(i-kl,1),min(i+ku,n)),i=1,n)
      Read (nin,*)(b(i,1:nrhs),i=1,n)

      afb(kl+1:2*kl+ku+1,1:n) = ab(1:kl+ku+1,1:n)
      x(1:n,1:nrhs) = b(1:n,1:nrhs)

!     Factorize A in the array AFB
!     The NAG name equivalent of dgbtrf is f07bdf
      Call dgbtrf(n,n,kl,ku,afb,ldafb,ipiv,info)

      Write (nout,*)
      Flush (nout)
      If (info==0) Then

!       Compute solution in the array X
!       The NAG name equivalent of dgbtrs is f07bef
        Call dgbtrs(trans,n,kl,ku,nrhs,afb,ldafb,ipiv,x,ldx,info)

!       Improve solution, and compute backward errors and
!       estimated bounds on the forward errors

!       The NAG name equivalent of dgbrfs is f07bhf
        Call dgbrfs(trans,n,kl,ku,nrhs,ab,ldab,afb,ldafb,ipiv,b,ldb,x,ldx,     &
          ferr,berr,work,iwork,info)

!       Print solution

!       ifail: behaviour on error exit
!              =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
        ifail = 0
        Call x04caf('General',' ',n,nrhs,x,ldx,'Solution(s)',ifail)

        Write (nout,*)
        Write (nout,*) 'Backward errors (machine-dependent)'
        Write (nout,99999) berr(1:nrhs)
        Write (nout,*) 'Estimated forward error bounds (machine-dependent)'
        Write (nout,99999) ferr(1:nrhs)
      Else
        Write (nout,*) 'The factor U is singular'
      End If

99999 Format ((3X,1P,7E11.1))
    End Program f07bhfe


f07bnfe.f90

    Program f07bnfe

!     F07BNF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: nag_wp, x04dff, zgbsv
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Integer                          :: i, ifail, info, j, k, kl, ku, ldab,  &
                                          n
!     .. Local Arrays ..
      Complex (Kind=nag_wp), Allocatable :: ab(:,:), b(:)
      Integer, Allocatable             :: ipiv(:)
      Character (1)                    :: clabs(1), rlabs(1)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: max, min
!     .. Executable Statements ..
      Write (nout,*) 'F07BNF Example Program Results'
      Write (nout,*)
!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) n, kl, ku
      ldab = 2*kl + ku + 1
      Allocate (ab(ldab,n),b(n),ipiv(n))

!     Read the band matrix A and the right hand side b from data file

      k = kl + ku + 1
      Read (nin,*)((ab(k+i-j,j),j=max(i-kl,1),min(i+ku,n)),i=1,n)
      Read (nin,*) b(1:n)

!     Solve the equations Ax = b for x
!     The NAG name equivalent of zgbsv is f07bnf
      Call zgbsv(n,kl,ku,1,ab,ldab,ipiv,b,n,info)

      If (info==0) Then

!       Print solution

        Write (nout,*) 'Solution'
        Write (nout,99999) b(1:n)

!       Print details of the factorization

        Write (nout,*)
        Flush (nout)

!       ifail: behaviour on error exit
!              =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
        ifail = 0
        Call x04dff(n,n,kl,kl+ku,ab,ldab,'Bracketed','F7.4',                   &
          'Details of factorization','None',rlabs,'None',clabs,80,0,ifail)

!       Print pivot indices'

        Write (nout,*)
        Write (nout,*) 'Pivot indices'
        Write (nout,99998) ipiv(1:n)

      Else
        Write (nout,99997) 'The (', info, ',', info, ')',                      &
          ' element of the factor U is zero'
      End If

99999 Format ((3X,4(' (',F7.4,',',F7.4,')',:)))
99998 Format (1X,I5,3I18)
99997 Format (1X,A,I3,A,I3,A,A)
    End Program f07bnfe


f07bpfe.f90

    Program f07bpfe

!     F07BPF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: nag_wp, x04dbf, zgbsvx
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: rcond
      Integer                          :: i, ifail, info, j, k, kl, ku, ldab,  &
                                          ldafb, ldb, ldx, n, nrhs
      Character (1)                    :: equed
!     .. Local Arrays ..
      Complex (Kind=nag_wp), Allocatable :: ab(:,:), afb(:,:), b(:,:),         &
                                          work(:), x(:,:)
      Real (Kind=nag_wp), Allocatable  :: berr(:), c(:), ferr(:), r(:),        &
                                          rwork(:)
      Integer, Allocatable             :: ipiv(:)
      Character (1)                    :: clabs(1), rlabs(1)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: max, min
!     .. Executable Statements ..
      Write (nout,*) 'F07BPF Example Program Results'
      Write (nout,*)
      Flush (nout)
!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) n, nrhs, kl, ku
      ldb = n
      ldx = n
      ldab = kl + ku + 1
      ldafb = ldab + kl
      Allocate (ab(ldab,n),afb(ldafb,n),b(ldb,nrhs),work(2*n),x(ldx,nrhs),     &
        berr(nrhs),c(n),ferr(nrhs),r(n),rwork(n),ipiv(n))

!     Read the band matrix A and B from data file

      k = ku + 1
      Read (nin,*)((ab(k+i-j,j),j=max(i-kl,1),min(i+ku,n)),i=1,n)
      Read (nin,*)(b(i,1:nrhs),i=1,n)

!     Solve the equations AX = B for X

!     The NAG name equivalent of zgbsvx is f07bpf
      Call zgbsvx('Equilibration','No transpose',n,kl,ku,nrhs,ab,ldab,afb,     &
        ldafb,ipiv,equed,r,c,b,ldb,x,ldx,rcond,ferr,berr,work,rwork,info)

      If ((info==0) .Or. (info==n+1)) Then

!       Print solution, error bounds, condition number, the form
!       of equilibration and the pivot growth factor

!       ifail: behaviour on error exit
!              =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
        ifail = 0
        Call x04dbf('General',' ',n,nrhs,x,ldx,'Bracketed','F7.4',             &
          'Solution(s)','Integer',rlabs,'Integer',clabs,80,0,ifail)

        Write (nout,*)
        Write (nout,*) 'Backward errors (machine-dependent)'
        Write (nout,99999) berr(1:nrhs)
        Write (nout,*)
        Write (nout,*) 'Estimated forward error bounds (machine-dependent)'
        Write (nout,99999) ferr(1:nrhs)
        Write (nout,*)
        Write (nout,*) 'Estimate of reciprocal condition number'
        Write (nout,99999) rcond
        Write (nout,*)
        If (equed=='N') Then
          Write (nout,*) 'A has not been equilibrated'
        Else If (equed=='R') Then
          Write (nout,*) 'A has been row scaled as diag(R)*A'
        Else If (equed=='C') Then
          Write (nout,*) 'A has been column scaled as A*diag(C)'
        Else If (equed=='B') Then
          Write (nout,*)                                                       &
            'A has been row and column scaled as diag(R)*A*diag(C)'
        End If
        Write (nout,*)
        Write (nout,*) 'Estimate of reciprocal pivot growth factor'
        Write (nout,99999) rwork(1)

        If (info==n+1) Then
          Write (nout,*)
          Write (nout,*) 'The matrix A is singular to working precision'
        End If
      Else
        Write (nout,99998) 'The (', info, ',', info, ')',                      &
          ' element of the factor U is zero'
      End If

99999 Format ((3X,1P,7E11.1))
99998 Format (1X,A,I3,A,I3,A,A)
    End Program f07bpfe


f07brfe.f90

    Program f07brfe

!     F07BRF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: nag_wp, x04dff, zgbtrf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Integer                          :: i, ifail, info, j, k, kl, ku, ldab,  &
                                          m, n
!     .. Local Arrays ..
      Complex (Kind=nag_wp), Allocatable :: ab(:,:)
      Integer, Allocatable             :: ipiv(:)
      Character (1)                    :: clabs(1), rlabs(1)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: max, min
!     .. Executable Statements ..
      Write (nout,*) 'F07BRF Example Program Results'
!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) m, n, kl, ku
      ldab = 2*kl + ku + 1
      Allocate (ab(ldab,n),ipiv(n))

!     Read A from data file

      k = kl + ku + 1
      Read (nin,*)((ab(k+i-j,j),j=max(i-kl,1),min(i+ku,n)),i=1,m)

!     Factorize A
!     The NAG name equivalent of zgbtrf is f07brf
      Call zgbtrf(m,n,kl,ku,ab,ldab,ipiv,info)

!     Print details of factorization

      Write (nout,*)
      Flush (nout)

!     ifail: behaviour on error exit
!             =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
      ifail = 0
      Call x04dff(m,n,kl,kl+ku,ab,ldab,'Bracketed','F7.4',                     &
        'Details of factorization','Integer',rlabs,'Integer',clabs,80,0,ifail)

!     Print pivot indices

      Write (nout,*)
      Write (nout,*) 'IPIV'
      Write (nout,99999) ipiv(1:min(m,n))

      If (info/=0) Then
        Write (nout,*) 'The factor U is singular'
      End If

99999 Format ((1X,I12,3I18))
    End Program f07brfe


f07bsfe.f90

    Program f07bsfe

!     F07BSF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: nag_wp, x04dbf, zgbtrf, zgbtrs
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
      Character (1), Parameter         :: trans = 'N'
!     .. Local Scalars ..
      Integer                          :: i, ifail, info, j, k, kl, ku, ldab,  &
                                          ldb, n, nrhs
!     .. Local Arrays ..
      Complex (Kind=nag_wp), Allocatable :: ab(:,:), b(:,:)
      Integer, Allocatable             :: ipiv(:)
      Character (1)                    :: clabs(1), rlabs(1)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: max, min
!     .. Executable Statements ..
      Write (nout,*) 'F07BSF Example Program Results'
!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) n, nrhs, kl, ku
      ldab = 2*kl + ku + 1
      ldb = n
      Allocate (ab(ldab,n),b(ldb,nrhs),ipiv(n))

!     Read A and B from data file

      k = kl + ku + 1
      Read (nin,*)((ab(k+i-j,j),j=max(i-kl,1),min(i+ku,n)),i=1,n)
      Read (nin,*)(b(i,1:nrhs),i=1,n)

!     Factorize A

!     The NAG name equivalent of zgbtrf is f07brf
      Call zgbtrf(n,n,kl,ku,ab,ldab,ipiv,info)

      Write (nout,*)
      Flush (nout)
      If (info==0) Then

!       Compute solution
!       The NAG name equivalent of zgbtrs is f07bsf
        Call zgbtrs(trans,n,kl,ku,nrhs,ab,ldab,ipiv,b,ldb,info)

!       Print solution

!       ifail: behaviour on error exit
!              =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
        ifail = 0
        Call x04dbf('General',' ',n,nrhs,b,ldb,'Bracketed','F7.4',             &
          'Solution(s)','Integer',rlabs,'Integer',clabs,80,0,ifail)

      Else
        Write (nout,*) 'The factor U is singular'
      End If

    End Program f07bsfe


f07btfe.f90

    Program f07btfe

!     F07BTF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: f06kcf, nag_wp, x02ajf, x02amf, x02bhf, x04def,   &
                             zdscal, zgbequ
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Real (Kind=nag_wp), Parameter    :: one = 1.0_nag_wp
      Real (Kind=nag_wp), Parameter    :: thresh = 0.1_nag_wp
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: amax, big, colcnd, rowcnd, small
      Integer                          :: i, i0, i1, ifail, ilen, info, j, k,  &
                                          kl, ku, ldab, n
!     .. Local Arrays ..
      Complex (Kind=nag_wp), Allocatable :: ab(:,:)
      Real (Kind=nag_wp), Allocatable  :: c(:), r(:)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: max, min, real
!     .. Executable Statements ..
      Write (nout,*) 'F07BTF Example Program Results'
      Write (nout,*)
      Flush (nout)
!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) n, kl, ku
      ldab = kl + ku + 1
      Allocate (ab(ldab,n),c(n),r(n))

!     Read the band matrix A from data file

      k = ku + 1
      Read (nin,*)((ab(k+i-j,j),j=max(i-kl,1),min(i+ku,n)),i=1,n)

!     Print the matrix A

!     ifail: behaviour on error exit
!             =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
      ifail = 0
      Call x04def(n,n,kl,ku,ab,ldab,'Matrix A',ifail)

      Write (nout,*)

!     Compute row and column scaling factors

!     The NAG name equivalent of zgbequ is f07btf
      Call zgbequ(n,n,kl,ku,ab,ldab,r,c,rowcnd,colcnd,amax,info)

      If (info>0) Then
        If (info<=n) Then
          Write (nout,99999) 'Row ', info, ' of A is exactly zero'
        Else
          Write (nout,99999) 'Column ', info - n, ' of A is exactly zero'
        End If
      Else

!       Print ROWCND, COLCND, AMAX and the scale factors

        Write (nout,99998) 'ROWCND =', rowcnd, ', COLCND =', colcnd,           &
          ', AMAX =', amax
        Write (nout,*)
        Write (nout,*) 'Row scale factors'
        Write (nout,99997) r(1:n)
        Write (nout,*)
        Write (nout,*) 'Column scale factors'
        Write (nout,99997) c(1:n)
        Write (nout,*)
        Flush (nout)

!       Compute values close to underflow and overflow

        small = x02amf()/(x02ajf()*real(x02bhf(),kind=nag_wp))
        big = one/small
        If ((rowcnd>=thresh) .And. (amax>=small) .And. (amax<=big)) Then
          If (colcnd<thresh) Then

!           Just column scale A
!           The NAG name equivalent of zdscal is f06jdf
            Do j = 1, n
              i1 = 1 + max(1,j-ku) - (j-ku)
              ilen = min(n,j+kl) - max(1,j-ku) + 1
              Call zdscal(ilen,c(j),ab(i1,j),1)
            End Do

          End If
        Else If (colcnd>=thresh) Then

!         Just row scale A
          Do j = 1, n
            i0 = max(1,j-ku)
            i1 = 1 + i0 - (j-ku)
            ilen = min(n,j+kl) - i0 + 1
            Call f06kcf(ilen,r(i0),1,ab(i1,j),1)
          End Do

        Else

!         Row and column scale A
          Do j = 1, n
            i0 = max(1,j-ku)
            i1 = 1 + i0 - (j-ku)
            ilen = min(n,j+kl) - i0 + 1
            Call zdscal(ilen,c(j),ab(i1,j),1)
            Call f06kcf(ilen,r(i0),1,ab(i1,j),1)
          End Do

        End If

!       Print the scaled matrix
        ifail = 0
        Call x04def(n,n,kl,ku,ab,ldab,'Scaled matrix',ifail)

      End If

99999 Format (1X,A,I4,A)
99998 Format (1X,3(A,1P,E8.1))
99997 Format ((1X,1P,7E11.2))
    End Program f07btfe


f07bufe.f90

    Program f07bufe

!     F07BUF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: nag_wp, x02ajf, zgbcon, zgbtrf, zlangb => f06ubf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
      Character (1), Parameter         :: norm = '1'
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: anorm, rcond
      Integer                          :: i, info, j, k, kl, ku, ldab, n
!     .. Local Arrays ..
      Complex (Kind=nag_wp), Allocatable :: ab(:,:), work(:)
      Real (Kind=nag_wp), Allocatable  :: rwork(:)
      Integer, Allocatable             :: ipiv(:)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: max, min
!     .. Executable Statements ..
      Write (nout,*) 'F07BUF Example Program Results'
!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) n, kl, ku
      ldab = 2*kl + ku + 1
      Allocate (ab(ldab,n),work(2*n),rwork(n),ipiv(n))

!     Read A from data file

      k = kl + ku + 1
      Read (nin,*)((ab(k+i-j,j),j=max(i-kl,1),min(i+ku,n)),i=1,n)

!     f06ubf is the NAG name equivalent of the LAPACK auxiliary zlangb
      anorm = zlangb(norm,n,kl,ku,ab(kl+1,1),ldab,rwork)

!     Factorize A
!     The NAG name equivalent of zgbtrf is f07brf
      Call zgbtrf(n,n,kl,ku,ab,ldab,ipiv,info)

      Write (nout,*)
      If (info==0) Then

!       Estimate condition number
!       The NAG name equivalent of zgbcon is f07buf
        Call zgbcon(norm,n,kl,ku,ab,ldab,ipiv,anorm,rcond,work,rwork,info)

        If (rcond>=x02ajf()) Then
          Write (nout,99999) 'Estimate of condition number =',                 &
            1.0E0_nag_wp/rcond
        Else
          Write (nout,*) 'A is singular to working precision'
        End If
      Else
        Write (nout,*) 'The factor U is singular'
      End If

99999 Format (1X,A,1P,E10.2)
    End Program f07bufe


f07bvfe.f90

    Program f07bvfe

!     F07BVF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: nag_wp, x04dbf, zgbrfs, zgbtrf, zgbtrs
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Complex (Kind=nag_wp), Parameter :: zero = (0.0_nag_wp,0.0_nag_wp)
      Integer, Parameter               :: nin = 5, nout = 6
      Character (1), Parameter         :: trans = 'N'
!     .. Local Scalars ..
      Integer                          :: i, ifail, info, j, k, kl, ku, ldab,  &
                                          ldafb, ldb, ldx, n, nrhs
!     .. Local Arrays ..
      Complex (Kind=nag_wp), Allocatable :: ab(:,:), afb(:,:), b(:,:),         &
                                          work(:), x(:,:)
      Real (Kind=nag_wp), Allocatable  :: berr(:), ferr(:), rwork(:)
      Integer, Allocatable             :: ipiv(:)
      Character (1)                    :: clabs(1), rlabs(1)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: max, min
!     .. Executable Statements ..
      Write (nout,*) 'F07BVF Example Program Results'
!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) n, nrhs, kl, ku
      ldb = n
      ldx = n
      ldab = kl + ku + 1
      ldafb = 2*kl + ku + 1
      Allocate (ab(ldab,n),afb(ldafb,n),b(ldb,nrhs),work(2*n),x(ldx,n),        &
        berr(nrhs),ferr(nrhs),rwork(n),ipiv(n))

!     Set A to zero to avoid referencing uninitialized elements

      ab(1:kl+ku+1,1:n) = zero

!     Read A and B from data file, and copy A to AFB and B to X

      k = ku + 1
      Read (nin,*)((ab(k+i-j,j),j=max(i-kl,1),min(i+ku,n)),i=1,n)
      Read (nin,*)(b(i,1:nrhs),i=1,n)

      afb(kl+1:2*kl+ku+1,1:n) = ab(1:kl+ku+1,1:n)
      x(1:n,1:nrhs) = b(1:n,1:nrhs)

!     Factorize A in the array AFB
!     The NAG name equivalent of zgbtrf is f07brf
      Call zgbtrf(n,n,kl,ku,afb,ldafb,ipiv,info)

      Write (nout,*)
      Flush (nout)
      If (info==0) Then

!       Compute solution in the array X
!       The NAG name equivalent of zgbtrs is f07bsf
        Call zgbtrs(trans,n,kl,ku,nrhs,afb,ldafb,ipiv,x,ldx,info)

!       Improve solution, and compute backward errors and
!       estimated bounds on the forward errors
!       The NAG name equivalent of zgbrfs is f07bvf
        Call zgbrfs(trans,n,kl,ku,nrhs,ab,ldab,afb,ldafb,ipiv,b,ldb,x,ldx,     &
          ferr,berr,work,rwork,info)

!       Print solution

!       ifail: behaviour on error exit
!              =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
        ifail = 0
        Call x04dbf('General',' ',n,nrhs,x,ldx,'Bracketed','F7.4',             &
          'Solution(s)','Integer',rlabs,'Integer',clabs,80,0,ifail)

        Write (nout,*)
        Write (nout,*) 'Backward errors (machine-dependent)'
        Write (nout,99999) berr(1:nrhs)
        Write (nout,*) 'Estimated forward error bounds (machine-dependent)'
        Write (nout,99999) ferr(1:nrhs)
      Else
        Write (nout,*) 'The factor U is singular'
      End If

99999 Format ((5X,1P,4(E11.1,7X)))
    End Program f07bvfe


f07cafe.f90

    Program f07cafe

!     F07CAF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: dgtsv, nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Integer                          :: info, n
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: b(:), d(:), dl(:), du(:)
!     .. Executable Statements ..
      Write (nout,*) 'F07CAF Example Program Results'
      Write (nout,*)
!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) n

      Allocate (b(n),d(n),dl(n-1),du(n-1))

!     Read the tridiagonal matrix A and the right hand side B from
!     data file

      Read (nin,*) du(1:n-1)
      Read (nin,*) d(1:n)
      Read (nin,*) dl(1:n-1)
      Read (nin,*) b(1:n)

!     Solve the equations Ax = b for x

!     The NAG name equivalent of dgtsv is f07caf
      Call dgtsv(n,1,dl,d,du,b,n,info)

      If (info==0) Then

!       Print solution

        Write (nout,*) 'Solution'
        Write (nout,99999) b(1:n)

      Else
        Write (nout,99998) 'The (', info, ',', info, ')',                      &
          ' element of the factor U is zero'
      End If

99999 Format ((1X,7F11.4))
99998 Format (1X,A,I3,A,I3,A,A)
    End Program f07cafe


f07cbfe.f90

    Program f07cbfe

!     F07CBF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: dgtsvx, nag_wp, x04caf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: rcond
      Integer                          :: i, ifail, info, ldb, ldx, n, nrhs
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: b(:,:), berr(:), d(:), df(:), dl(:), &
                                          dlf(:), du(:), du2(:), duf(:),       &
                                          ferr(:), work(:), x(:,:)
      Integer, Allocatable             :: ipiv(:), iwork(:)
!     .. Executable Statements ..
      Write (nout,*) 'F07CBF Example Program Results'
      Write (nout,*)
      Flush (nout)
!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) n, nrhs
      ldb = n
      ldx = n
      Allocate (b(ldb,nrhs),berr(nrhs),d(n),df(n),dl(n-1),dlf(n-1),du(n-1),    &
        du2(n-2),duf(n-1),ferr(nrhs),work(3*n),x(ldx,nrhs),ipiv(n),iwork(n))

!     Read the tridiagonal matrix A from data file

      Read (nin,*) du(1:n-1)
      Read (nin,*) d(1:n)
      Read (nin,*) dl(1:n-1)

!     Read the right hand matrix B

      Read (nin,*)(b(i,1:nrhs),i=1,n)

!     Solve the equations AX = B

!     The NAG name equivalent of dgtsvx is f07cbf
      Call dgtsvx('No factors','No transpose',n,nrhs,dl,d,du,dlf,df,duf,du2,   &
        ipiv,b,ldb,x,ldx,rcond,ferr,berr,work,iwork,info)

      If ((info==0) .Or. (info==n+1)) Then

!       Print solution, error bounds and condition number

!       ifail: behaviour on error exit
!              =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
        ifail = 0
        Call x04caf('General',' ',n,nrhs,x,ldx,'Solution(s)',ifail)

        Write (nout,*)
        Write (nout,*) 'Backward errors (machine-dependent)'
        Write (nout,99999) berr(1:nrhs)
        Write (nout,*)
        Write (nout,*) 'Estimated forward error bounds (machine-dependent)'
        Write (nout,99999) ferr(1:nrhs)
        Write (nout,*)
        Write (nout,*) 'Estimate of reciprocal condition number'
        Write (nout,99999) rcond

        If (info==n+1) Then
          Write (nout,*)
          Write (nout,*) 'The matrix A is singular to working precision'
        End If
      Else
        Write (nout,99998) 'The (', info, ',', info, ')',                      &
          ' element of the factor U is zero'
      End If

99999 Format ((3X,1P,7E11.1))
99998 Format (1X,A,I3,A,I3,A,A)
    End Program f07cbfe


f07cdfe.f90

    Program f07cdfe

!     F07CDF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: dgttrf, nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Integer                          :: info, n
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: d(:), dl(:), du(:), du2(:)
      Integer, Allocatable             :: ipiv(:)
!     .. Executable Statements ..
      Write (nout,*) 'F07CDF Example Program Results'
      Write (nout,*)
!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) n

      Allocate (d(n),dl(n-1),du(n-1),du2(n-2),ipiv(n))

!     Read the tridiagonal matrix A from data file

      Read (nin,*) du(1:n-1)
      Read (nin,*) d(1:n)
      Read (nin,*) dl(1:n-1)

!     Factorize the tridiagonal matrix A
!     The NAG name equivalent of dgttrf is f06cdf
      Call dgttrf(n,dl,d,du,du2,ipiv,info)

      If (info>0) Then
        Write (nout,99999) 'The (', info, ',', info, ')',                      &
          ' element of the factor U is zero'
      End If

!     Print details of the factorization

      Write (nout,*) 'Details of factorization'
      Write (nout,*)
      Write (nout,*) ' Second superdiagonal of U'
      Write (nout,99998) du2(1:n-2)
      Write (nout,*)
      Write (nout,*) ' First superdiagonal of U'
      Write (nout,99998) du(1:n-1)
      Write (nout,*)
      Write (nout,*) ' Main diagonal of U'
      Write (nout,99998) d(1:n)
      Write (nout,*)
      Write (nout,*) ' Multipliers'
      Write (nout,99998) dl(1:n-1)
      Write (nout,*)
      Write (nout,*) ' Vector of interchanges'
      Write (nout,99997) ipiv(1:n)

99999 Format (1X,A,I3,A,I3,A,A)
99998 Format (1X,8F9.4)
99997 Format (1X,5I9)
    End Program f07cdfe


f07cefe.f90

    Program f07cefe

!     F07CEF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: dgttrf, dgttrs, nag_wp, x04caf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Integer                          :: i, ifail, info, ldb, n, nrhs
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: b(:,:), d(:), dl(:), du(:), du2(:)
      Integer, Allocatable             :: ipiv(:)
!     .. Executable Statements ..
      Write (nout,*) 'F07CEF Example Program Results'
      Write (nout,*)
      Flush (nout)
!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) n, nrhs
      ldb = n
      Allocate (b(ldb,nrhs),d(n),dl(n-1),du(n-1),du2(n-2),ipiv(n))

!     Read the tridiagonal matrix A from data file

      Read (nin,*) du(1:n-1)
      Read (nin,*) d(1:n)
      Read (nin,*) dl(1:n-1)

!     Read the right hand matrix B
      Read (nin,*)(b(i,1:nrhs),i=1,n)

!     Factorize the tridiagonal matrix A
!     The NAG name equivalent of dgttrf is f07cdf
      Call dgttrf(n,dl,d,du,du2,ipiv,info)

      If (info==0) Then

!       Solve the equations AX = B
!       The NAG name equivalent of dgttrs is f07cef
        Call dgttrs('No transpose',n,nrhs,dl,d,du,du2,ipiv,b,ldb,info)

!       Print the solution

!       ifail: behaviour on error exit
!              =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
        ifail = 0
        Call x04caf('General',' ',n,nrhs,b,ldb,'Solution(s)',ifail)

      Else
        Write (nout,99999) 'The (', info, ',', info, ')',                      &
          ' element of the factor U is zero'
      End If

99999 Format (1X,A,I3,A,I3,A,A)
    End Program f07cefe


f07cgfe.f90

    Program f07cgfe

!     F07CGF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: dgtcon, dgttrf, f06rnf, nag_wp, x02ajf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: anorm, rcond
      Integer                          :: info, n
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: d(:), dl(:), du(:), du2(:), work(:)
      Integer, Allocatable             :: ipiv(:), iwork(:)
!     .. Executable Statements ..
      Write (nout,*) 'F07CGF Example Program Results'
      Write (nout,*)
!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) n

      Allocate (d(n),dl(n-1),du(n-1),du2(n-2),work(2*n),ipiv(n),iwork(n))

!     Read the tridiagonal matrix A from data file

      Read (nin,*) du(1:n-1)
      Read (nin,*) d(1:n)
      Read (nin,*) dl(1:n-1)

!     Compute the 1-norm of A
      anorm = f06rnf('1-norm',n,dl,d,du)

!     Factorize the tridiagonal matrix A
!     The NAG name equivalent of dgttrf is f07cdf
      Call dgttrf(n,dl,d,du,du2,ipiv,info)

      If (info==0) Then

!       Estimate the condition number of A
!       The NAG name equivalent of dgtcon is f07cgf
        Call dgtcon('1-norm',n,dl,d,du,du2,ipiv,anorm,rcond,work,iwork,info)

!       Print the estimated condition number

        If (rcond>=x02ajf()) Then
          Write (nout,99999) 'Estimate of condition number = ',                &
            1.0_nag_wp/rcond
        Else
          Write (nout,99999) 'A is singular to working precision. RCOND = ',   &
            rcond
        End If

      Else
        Write (nout,99998) 'The (', info, ',', info, ')',                      &
          ' element of the factor U is zero'
      End If

99999 Format (1X,A,1P,E10.2)
99998 Format (1X,A,I3,A,I3,A,A)
    End Program f07cgfe


f07chfe.f90

    Program f07chfe

!     F07CHF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: dgtrfs, dgttrf, dgttrs, nag_wp, x04caf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Integer                          :: i, ifail, info, ldb, ldx, n, nrhs
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: b(:,:), berr(:), d(:), df(:), dl(:), &
                                          dlf(:), du(:), du2(:), duf(:),       &
                                          ferr(:), work(:), x(:,:)
      Integer, Allocatable             :: ipiv(:), iwork(:)
!     .. Executable Statements ..
      Write (nout,*) 'F07CHF Example Program Results'
      Write (nout,*)
      Flush (nout)
!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) n, nrhs
      ldb = n
      ldx = n
      Allocate (b(ldb,nrhs),berr(nrhs),d(n),df(n),dl(n-1),dlf(n-1),du(n-1),    &
        du2(n-2),duf(n-1),ferr(nrhs),work(3*n),x(ldx,nrhs),ipiv(n),iwork(n))

!     Read the tridiagonal matrix A from data file

      Read (nin,*) du(1:n-1)
      Read (nin,*) d(1:n)
      Read (nin,*) dl(1:n-1)

!     Read the right hand matrix B

      Read (nin,*)(b(i,1:nrhs),i=1,n)

!     Copy A into DUF, DF and DLF, and copy B into X

      duf(1:n-1) = du(1:n-1)
      df(1:n) = d(1:n)
      dlf(1:n-1) = dl(1:n-1)
      x(1:n,1:nrhs) = b(1:n,1:nrhs)

!     Factorize the copy of the tridiagonal matrix A
!     The NAG name equivalent of dgttrf is f07cdf
      Call dgttrf(n,dlf,df,duf,du2,ipiv,info)

      If (info==0) Then

!       Solve the equations AX = B
!       The NAG name equivalent of dgttrs is f07cef
        Call dgttrs('No transpose',n,nrhs,dlf,df,duf,du2,ipiv,x,ldx,info)

!       Improve the solution and compute error estimates
!       The NAG name equivalent of dgtrfs is f07chf
        Call dgtrfs('No transpose',n,nrhs,dl,d,du,dlf,df,duf,du2,ipiv,b,ldb,x, &
          ldx,ferr,berr,work,iwork,info)

!       Print the solution and the forward and backward error
!       estimates

!       ifail: behaviour on error exit
!              =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
        ifail = 0
        Call x04caf('General',' ',n,nrhs,x,ldx,'Solution(s)',ifail)

        Write (nout,*)
        Write (nout,*) 'Backward errors (machine-dependent)'
        Write (nout,99999) berr(1:nrhs)
        Write (nout,*)
        Write (nout,*) 'Estimated forward error bounds (machine-dependent)'
        Write (nout,99999) ferr(1:nrhs)
      Else
        Write (nout,99998) 'The (', info, ',', info, ')',                      &
          ' element of the factor U is zero'
      End If

99999 Format ((3X,1P,7E11.1))
99998 Format (1X,A,I3,A,I3,A,A)
    End Program f07chfe


f07cnfe.f90

    Program f07cnfe

!     F07CNF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: nag_wp, zgtsv
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Integer                          :: info, n
!     .. Local Arrays ..
      Complex (Kind=nag_wp), Allocatable :: b(:), d(:), dl(:), du(:)
!     .. Executable Statements ..
      Write (nout,*) 'F07CNF Example Program Results'
      Write (nout,*)
!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) n

      Allocate (b(n),d(n),dl(n-1),du(n-1))

!     Read the tridiagonal matrix A and the right hand side B from
!     data file

      Read (nin,*) du(1:n-1)
      Read (nin,*) d(1:n)
      Read (nin,*) dl(1:n-1)
      Read (nin,*) b(1:n)

!     Solve the equations Ax = b for x
!     The NAG name equivalent of zgtsv is f07cnf
      Call zgtsv(n,1,dl,d,du,b,n,info)

      If (info==0) Then

!       Print solution

        Write (nout,*) 'Solution'
        Write (nout,99999) b(1:n)

      Else
        Write (nout,99998) 'The (', info, ',', info, ')',                      &
          ' element of the factor U is zero'
      End If

99999 Format (4(' (',F8.4,',',F8.4,')',:))
99998 Format (1X,A,I3,A,I3,A,A)
    End Program f07cnfe


f07cpfe.f90

    Program f07cpfe

!     F07CPF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: nag_wp, x04dbf, zgtsvx
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: rcond
      Integer                          :: i, ifail, info, ldb, ldx, n, nrhs
!     .. Local Arrays ..
      Complex (Kind=nag_wp), Allocatable :: b(:,:), d(:), df(:), dl(:),        &
                                          dlf(:), du(:), du2(:), duf(:),       &
                                          work(:), x(:,:)
      Real (Kind=nag_wp), Allocatable  :: berr(:), ferr(:), rwork(:)
      Integer, Allocatable             :: ipiv(:)
      Character (1)                    :: clabs(1), rlabs(1)
!     .. Executable Statements ..
      Write (nout,*) 'F07CPF Example Program Results'
      Write (nout,*)
      Flush (nout)
!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) n, nrhs
      ldb = n
      ldx = n
      Allocate (b(ldb,nrhs),d(n),df(n),dl(n-1),dlf(n-1),du(n-1),du2(n-2),      &
        duf(n-1),work(2*n),x(ldx,nrhs),berr(nrhs),ferr(nrhs),rwork(n),ipiv(n))

!     Read the tridiagonal matrix A from data file

      Read (nin,*) du(1:n-1)
      Read (nin,*) d(1:n)
      Read (nin,*) dl(1:n-1)

!     Read the right hand matrix B

      Read (nin,*)(b(i,1:nrhs),i=1,n)

!     Solve the equations AX = B
!     The NAG name equivalent of zgtsvx is f07cpf
      Call zgtsvx('No factors','No transpose',n,nrhs,dl,d,du,dlf,df,duf,du2,   &
        ipiv,b,ldb,x,ldx,rcond,ferr,berr,work,rwork,info)

      If ((info==0) .Or. (info==n+1)) Then

!       Print solution, error bounds and condition number

!       ifail: behaviour on error exit
!              =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
        ifail = 0
        Call x04dbf('General',' ',n,nrhs,x,ldx,'Bracketed','F7.4',             &
          'Solution(s)','Integer',rlabs,'Integer',clabs,80,0,ifail)

        Write (nout,*)
        Write (nout,*) 'Backward errors (machine-dependent)'
        Write (nout,99999) berr(1:nrhs)
        Write (nout,*)
        Write (nout,*) 'Estimated forward error bounds (machine-dependent)'
        Write (nout,99999) ferr(1:nrhs)
        Write (nout,*)
        Write (nout,*) 'Estimate of reciprocal condition number'
        Write (nout,99999) rcond

        If (info==n+1) Then
          Write (nout,*)
          Write (nout,*) 'The matrix A is singular to working precision'
        End If
      Else
        Write (nout,99998) 'The (', info, ',', info, ')',                      &
          ' element of the factor U is zero'
      End If

99999 Format ((3X,1P,7E11.1))
99998 Format (1X,A,I3,A,I3,A,A)
    End Program f07cpfe


f07crfe.f90

    Program f07crfe

!     F07CRF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: nag_wp, zgttrf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Integer                          :: info, n
!     .. Local Arrays ..
      Complex (Kind=nag_wp), Allocatable :: d(:), dl(:), du(:), du2(:)
      Integer, Allocatable             :: ipiv(:)
!     .. Executable Statements ..
      Write (nout,*) 'F07CRF Example Program Results'
      Write (nout,*)
!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) n

      Allocate (d(n),dl(n-1),du(n-1),du2(n-2),ipiv(n))

!     Read the tridiagonal matrix A from data file

      Read (nin,*) du(1:n-1)
      Read (nin,*) d(1:n)
      Read (nin,*) dl(1:n-1)

!     Factorize the tridiagonal matrix A
!     The NAG name equivalent of zgttrf is f07crf
      Call zgttrf(n,dl,d,du,du2,ipiv,info)

      If (info>0) Then
        Write (nout,99999) 'The (', info, ',', info, ')',                      &
          ' element of the factor U is zero'
      End If

!     Print details of the factorization

      Write (nout,*) 'Details of factorization'
      Write (nout,*)
      Write (nout,*) ' Second superdiagonal of U'
      Write (nout,99998) du2(1:n-2)
      Write (nout,*)
      Write (nout,*) ' First superdiagonal of U'
      Write (nout,99998) du(1:n-1)
      Write (nout,*)
      Write (nout,*) ' Main diagonal of U'
      Write (nout,99998) d(1:n)
      Write (nout,*)
      Write (nout,*) ' Multipliers'
      Write (nout,99998) dl(1:n-1)
      Write (nout,*)
      Write (nout,*) ' Vector of interchanges'
      Write (nout,99997) ipiv(1:n)

99999 Format (1X,A,I3,A,I3,A,A)
99998 Format (4(' (',F8.4,',',F8.4,')',:))
99997 Format (1X,5I7)
    End Program f07crfe


f07csfe.f90

    Program f07csfe

!     F07CSF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: nag_wp, x04dbf, zgttrf, zgttrs
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Integer                          :: i, ifail, info, ldb, n, nrhs
!     .. Local Arrays ..
      Complex (Kind=nag_wp), Allocatable :: b(:,:), d(:), dl(:), du(:), du2(:)
      Integer, Allocatable             :: ipiv(:)
      Character (1)                    :: clabs(1), rlabs(1)
!     .. Executable Statements ..
      Write (nout,*) 'F07CSF Example Program Results'
      Write (nout,*)
      Flush (nout)
!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) n, nrhs
      ldb = n
      Allocate (b(ldb,nrhs),d(n),dl(n-1),du(n-1),du2(n-2),ipiv(n))

!     Read the tridiagonal matrix A from data file

      Read (nin,*) du(1:n-1)
      Read (nin,*) d(1:n)
      Read (nin,*) dl(1:n-1)

!     Read the right hand matrix B

      Read (nin,*)(b(i,1:nrhs),i=1,n)

!     Factorize the tridiagonal matrix A
!     The NAG name equivalent of zgttrf is f07crf
      Call zgttrf(n,dl,d,du,du2,ipiv,info)

      If (info==0) Then

!       Solve the equations AX = B
!       The NAG name equivalent of zgttrs is f07csf
        Call zgttrs('No transpose',n,nrhs,dl,d,du,du2,ipiv,b,ldb,info)

!       Print the solution

!       ifail: behaviour on error exit
!              =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
        ifail = 0
        Call x04dbf('General',' ',n,nrhs,b,ldb,'Bracketed','F7.4',             &
          'Solution(s)','Integer',rlabs,'Integer',clabs,80,0,ifail)

      Else
        Write (nout,99999) 'The (', info, ',', info, ')',                      &
          ' element of the factor U is zero'
      End If

99999 Format (1X,A,I3,A,I3,A,A)
    End Program f07csfe


f07cufe.f90

    Program f07cufe

!     F07CUF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: f06unf, nag_wp, x02ajf, zgtcon, zgttrf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: anorm, rcond
      Integer                          :: info, n
!     .. Local Arrays ..
      Complex (Kind=nag_wp), Allocatable :: d(:), dl(:), du(:), du2(:),        &
                                          work(:)
      Integer, Allocatable             :: ipiv(:)
!     .. Executable Statements ..
      Write (nout,*) 'F07CUF Example Program Results'
      Write (nout,*)
!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) n

      Allocate (d(n),dl(n-1),du(n-1),du2(n-2),work(2*n),ipiv(n))

!     Read the tridiagonal matrix A from data file

      Read (nin,*) du(1:n-1)
      Read (nin,*) d(1:n)
      Read (nin,*) dl(1:n-1)

!     Compute the 1-norm of A
      anorm = f06unf('1-norm',n,dl,d,du)

!     Factorize the tridiagonal matrix A
!     The NAG name equivalent of zgttrf is f07crf
      Call zgttrf(n,dl,d,du,du2,ipiv,info)

      If (info==0) Then

!       Estimate the condition number of A
!       The NAG name equivalent of zgtcon is f07cuf
        Call zgtcon('1-norm',n,dl,d,du,du2,ipiv,anorm,rcond,work,info)

!       Print the estimated condition number

        If (rcond>=x02ajf()) Then
          Write (nout,99999) 'Estimate of condition number = ',                &
            1.0E0_nag_wp/rcond
        Else
          Write (nout,99999) 'A is singular to working precision. RCOND = ',   &
            rcond
        End If

      Else
        Write (nout,99998) 'The (', info, ',', info, ')',                      &
          ' element of the factor U is zero'
      End If

99999 Format (1X,A,1P,E10.2)
99998 Format (1X,A,I3,A,I3,A,A)
    End Program f07cufe


f07cvfe.f90

    Program f07cvfe

!     F07CVF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: nag_wp, x04dbf, zgtrfs, zgttrf, zgttrs
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Integer                          :: i, ifail, info, ldb, ldx, n, nrhs
!     .. Local Arrays ..
      Complex (Kind=nag_wp), Allocatable :: b(:,:), d(:), df(:), dl(:),        &
                                          dlf(:), du(:), du2(:), duf(:),       &
                                          work(:), x(:,:)
      Real (Kind=nag_wp), Allocatable  :: berr(:), ferr(:), rwork(:)
      Integer, Allocatable             :: ipiv(:)
      Character (1)                    :: clabs(1), rlabs(1)
!     .. Executable Statements ..
      Write (nout,*) 'F07CVF Example Program Results'
      Write (nout,*)
      Flush (nout)
!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) n, nrhs
      ldb = n
      ldx = n
      Allocate (b(ldb,nrhs),d(n),df(n),dl(n-1),dlf(n-1),du(n-1),du2(n-2),      &
        duf(n-1),work(2*n),x(ldx,nrhs),berr(nrhs),ferr(nrhs),rwork(n),ipiv(n))

!     Read the tridiagonal matrix A from data file

      Read (nin,*) du(1:n-1)
      Read (nin,*) d(1:n)
      Read (nin,*) dl(1:n-1)

!     Read the right hand matrix B

      Read (nin,*)(b(i,1:nrhs),i=1,n)

!     Copy A into DUF, DF and DLF, and copy B into X

      duf(1:n-1) = du(1:n-1)
      df(1:n) = d(1:n)
      dlf(1:n-1) = dl(1:n-1)
      x(1:n,1:nrhs) = b(1:n,1:nrhs)

!     Factorize the copy of the tridiagonal matrix A
!     The NAG name equivalent of zgttrf is f07crf
      Call zgttrf(n,dlf,df,duf,du2,ipiv,info)

      If (info==0) Then

!       Solve the equations AX = B
!       The NAG name equivalent of zgttrs is f07csf
        Call zgttrs('No transpose',n,nrhs,dlf,df,duf,du2,ipiv,x,ldx,info)

!       Improve the solution and compute error estimates
!       The NAG name equivalent of zgtrfs is f07cvf
        Call zgtrfs('No transpose',n,nrhs,dl,d,du,dlf,df,duf,du2,ipiv,b,ldb,x, &
          ldx,ferr,berr,work,rwork,info)

!       Print the solution and the forward and backward error
!       estimates

!       ifail: behaviour on error exit
!              =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
        ifail = 0
        Call x04dbf('General',' ',n,nrhs,x,ldx,'Bracketed','F7.4',             &
          'Solution(s)','Integer',rlabs,'Integer',clabs,80,0,ifail)

        Write (nout,*)
        Write (nout,*) 'Backward errors (machine-dependent)'
        Write (nout,99999) berr(1:nrhs)
        Write (nout,*)
        Write (nout,*) 'Estimated forward error bounds (machine-dependent)'
        Write (nout,99999) ferr(1:nrhs)
      Else
        Write (nout,99998) 'The (', info, ',', info, ')',                      &
          ' element of the factor U is zero'
      End If

99999 Format ((3X,1P,7E11.1))
99998 Format (1X,A,I3,A,I3,A,A)
    End Program f07cvfe


f07fafe.f90

    Program f07fafe

!     F07FAF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: dposv, nag_wp, x04caf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Integer                          :: i, ifail, info, lda, n
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: a(:,:), b(:)
!     .. Executable Statements ..
      Write (nout,*) 'F07FAF Example Program Results'
      Write (nout,*)
!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) n
      lda = n
      Allocate (a(lda,n),b(n))

!     Read the upper triangular part of A from data file

      Read (nin,*)(a(i,i:n),i=1,n)

!     Read b from data file

      Read (nin,*) b(1:n)

!     Solve the equations Ax = b for x
!     The NAG name equivalent of dposv is f07faf
      Call dposv('Upper',n,1,a,lda,b,n,info)

      If (info==0) Then

!       Print solution

        Write (nout,*) 'Solution'
        Write (nout,99999) b(1:n)

!       Print details of factorization

        Write (nout,*)
        Flush (nout)

!       ifail: behaviour on error exit
!              =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
        ifail = 0
        Call x04caf('Upper','Non-unit diagonal',n,n,a,lda,'Cholesky factor U', &
          ifail)

      Else
        Write (nout,99998) 'The leading minor of order ', info,                &
          ' is not positive definite'
      End If

99999 Format ((3X,7F11.4))
99998 Format (1X,A,I3,A)
    End Program f07fafe


f07fbfe.f90

    Program f07fbfe

!     F07FBF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: dposvx, nag_wp, x04caf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: rcond
      Integer                          :: i, ifail, info, lda, ldaf, ldb, ldx, &
                                          n, nrhs
      Character (1)                    :: equed
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: a(:,:), af(:,:), b(:,:), berr(:),    &
                                          ferr(:), s(:), work(:), x(:,:)
      Integer, Allocatable             :: iwork(:)
!     .. Executable Statements ..
      Write (nout,*) 'F07FBF Example Program Results'
      Write (nout,*)
      Flush (nout)
!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) n, nrhs
      lda = n
      ldaf = n
      ldb = n
      ldx = n
      Allocate (a(lda,n),af(ldaf,n),b(ldb,nrhs),berr(nrhs),ferr(nrhs),s(n),    &
        work(3*n),x(ldx,nrhs),iwork(n))

!     Read the upper triangular part of A from data file

      Read (nin,*)(a(i,i:n),i=1,n)

!     Read B from data file

      Read (nin,*)(b(i,1:nrhs),i=1,n)

!     Solve the equations AX = B for X
!     The NAG name equivalent of dposvx is f07fbf
      Call dposvx('Equilibration','Upper',n,nrhs,a,lda,af,ldaf,equed,s,b,ldb,  &
        x,ldx,rcond,ferr,berr,work,iwork,info)

      If ((info==0) .Or. (info==n+1)) Then

!       Print solution, error bounds, condition number and the form
!       of equilibration

!       ifail: behaviour on error exit
!              =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
        ifail = 0
        Call x04caf('General',' ',n,nrhs,x,ldx,'Solution(s)',ifail)

        Write (nout,*)
        Write (nout,*) 'Backward errors (machine-dependent)'
        Write (nout,99999) berr(1:nrhs)
        Write (nout,*)
        Write (nout,*) 'Estimated forward error bounds (machine-dependent)'
        Write (nout,99999) ferr(1:nrhs)
        Write (nout,*)
        Write (nout,*) 'Estimate of reciprocal condition number'
        Write (nout,99999) rcond
        Write (nout,*)
        If (equed=='N') Then
          Write (nout,*) 'A has not been equilibrated'
        Else If (equed=='Y') Then
          Write (nout,*)                                                       &
            'A has been row and column scaled as diag(S)*A*diag(S)'
        End If

        If (info==n+1) Then
          Write (nout,*)
          Write (nout,*) 'The matrix A is singular to working precision'
        End If
      Else
        Write (nout,99998) 'The leading minor of order ', info,                &
          ' is not positive definite'
      End If

99999 Format ((3X,1P,7E11.1))
99998 Format (1X,A,I3,A)
    End Program f07fbfe


f07fcfe.f90

    Program f07fcfe

!     F07FCF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: dsposv, nag_rp, nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Integer                          :: i, info, iter, lda, ldb, ldx, n, r
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: a(:,:), b(:,:), work(:,:), x(:,:)
      Real (Kind=nag_rp), Allocatable  :: swork(:)
!     .. Executable Statements ..
      Write (nout,*) 'F07FCF Example Program Results'
      Write (nout,*)
!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) n, r
      lda = n
      ldb = n
      ldx = n
      Allocate (a(lda,n),b(n,r),work(n,r),x(ldx,r),swork(n*(n+r)))

!     Read the upper triangular part of A from data file

      Read (nin,*)(a(i,i:n),i=1,n)

!     Read B from data file

      Read (nin,*)(b(i,1:r),i=1,n)

!     Solve the equations Ax = b for x
!     The NAG name equivalent of dsposv is f07fcf
      Call dsposv('U',n,r,a,lda,b,ldb,x,ldx,work,swork,iter,info)

      If (info==0) Then

!       Print solution

        Write (nout,*) 'Solution'
        Write (nout,99999)(x(i,1:r),i=1,n)
      Else
        Write (nout,99998) 'The leading minor of order ', info,                &
          ' is not positive definite'
      End If

99999 Format ((3X,7F11.4))
99998 Format ((1X,A,I3,A))
    End Program f07fcfe


f07fdfe.f90

    Program f07fdfe

!     F07FDF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: dpotrf, nag_wp, x04caf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Integer                          :: i, ifail, info, lda, n
      Character (1)                    :: uplo
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: a(:,:)
!     .. Executable Statements ..
      Write (nout,*) 'F07FDF Example Program Results'
!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) n
      lda = n
      Allocate (a(lda,n))

!     Read A from data file

      Read (nin,*) uplo
      If (uplo=='U') Then
        Read (nin,*)(a(i,i:n),i=1,n)
      Else If (uplo=='L') Then
        Read (nin,*)(a(i,1:i),i=1,n)
      End If

!     Factorize A
!     The NAG name equivalent of dpotrf is f07fdf
      Call dpotrf(uplo,n,a,lda,info)

      Write (nout,*)
      Flush (nout)
      If (info==0) Then

!       Print factor

!       ifail: behaviour on error exit
!              =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
        ifail = 0
        Call x04caf(uplo,'Nonunit',n,n,a,lda,'Factor',ifail)

      Else
        Write (nout,*) 'A is not positive definite'
      End If

    End Program f07fdfe


f07fefe.f90

    Program f07fefe

!     F07FEF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: dpotrf, dpotrs, nag_wp, x04caf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Integer                          :: i, ifail, info, lda, ldb, n, nrhs
      Character (1)                    :: uplo
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: a(:,:), b(:,:)
!     .. Executable Statements ..
      Write (nout,*) 'F07FEF Example Program Results'
!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) n, nrhs
      lda = n
      ldb = n
      Allocate (a(lda,n),b(ldb,nrhs))

!     Read A and B from data file

      Read (nin,*) uplo
      If (uplo=='U') Then
        Read (nin,*)(a(i,i:n),i=1,n)
      Else If (uplo=='L') Then
        Read (nin,*)(a(i,1:i),i=1,n)
      End If
      Read (nin,*)(b(i,1:nrhs),i=1,n)

!     Factorize A
!     The NAG name equivalent of dpotrf is f07fdf
      Call dpotrf(uplo,n,a,lda,info)

      Write (nout,*)
      Flush (nout)
      If (info==0) Then

!       Compute solution
!       The NAG name equivalent of dpotrs is f07fef
        Call dpotrs(uplo,n,nrhs,a,lda,b,ldb,info)

!       Print solution

!       ifail: behaviour on error exit
!              =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
        ifail = 0
        Call x04caf('General',' ',n,nrhs,b,ldb,'Solution(s)',ifail)
      Else
        Write (nout,*) 'A is not positive definite'
      End If

    End Program f07fefe


f07fffe.f90

    Program f07fffe

!     F07FFF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: dpoequ, dscal, f06fcf, nag_wp, x02ajf, x02amf,    &
                             x02bhf, x04caf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Real (Kind=nag_wp), Parameter    :: one = 1.0_nag_wp
      Real (Kind=nag_wp), Parameter    :: thresh = 0.1_nag_wp
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: amax, big, scond, small
      Integer                          :: i, ifail, info, j, lda, n
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: a(:,:), s(:)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: real
!     .. Executable Statements ..
      Write (nout,*) 'F07FFF Example Program Results'
      Write (nout,*)
      Flush (nout)
!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) n
      lda = n
      Allocate (a(lda,n),s(n))

!     Read the upper triangular part of the matrix A from data file

      Read (nin,*)(a(i,i:n),i=1,n)

!     Print the matrix A

!     ifail: behaviour on error exit
!             =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
      ifail = 0
      Call x04caf('Upper','Non-unit',n,n,a,lda,'Matrix A',ifail)

      Write (nout,*)

!     Compute diagonal scaling factors
!     The NAG name equivalent of dpoequ is f07fff
      Call dpoequ(n,a,lda,s,scond,amax,info)

      If (info>0) Then
        Write (nout,99999) 'Diagonal element', info, ' of A is non positive'
      Else

!       Print SCOND, AMAX and the scale factors

        Write (nout,99998) 'SCOND =', scond, ', AMAX =', amax
        Write (nout,*)
        Write (nout,*) 'Diagonal scaling factors'
        Write (nout,99997) s(1:n)
        Write (nout,*)
        Flush (nout)

!       Compute values close to underflow and overflow

        small = x02amf()/(x02ajf()*real(x02bhf(),kind=nag_wp))
        big = one/small
        If ((scond<thresh) .Or. (amax<small) .Or. (amax>big)) Then

!         Scale A
!         The NAG name equivalent of dscal is f06edf
          Do j = 1, n
            Call dscal(j,s(j),a(1,j),1)
            Call f06fcf(j,s,1,a(1,j),1)
          End Do

!         Print the scaled matrix

          ifail = 0
          Call x04caf('Upper','Non-unit',n,n,a,lda,'Scaled matrix',ifail)

        End If
      End If

99999 Format (1X,A,I4,A)
99998 Format (1X,2(A,1P,E8.1))
99997 Format ((1X,1P,7E11.1))
    End Program f07fffe


f07fgfe.f90

    Program f07fgfe

!     F07FGF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: dlansy => f06rcf, dpocon, dpotrf, nag_wp, x02ajf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: anorm, rcond
      Integer                          :: i, info, lda, n
      Character (1)                    :: uplo
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: a(:,:), work(:)
      Integer, Allocatable             :: iwork(:)
!     .. Executable Statements ..
      Write (nout,*) 'F07FGF Example Program Results'
!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) n
      lda = n
      Allocate (a(lda,n),work(3*n),iwork(n))

!     Read A from data file

      Read (nin,*) uplo
      If (uplo=='U') Then
        Read (nin,*)(a(i,i:n),i=1,n)
      Else If (uplo=='L') Then
        Read (nin,*)(a(i,1:i),i=1,n)
      End If

!     Compute norm of A
!     f06rcf is the NAG name equivalent of the LAPACK auxiliary dlansy
      anorm = dlansy('1-norm',uplo,n,a,lda,work)

!     Factorize A
!     The NAG name equivalent of dpotrf is f06fdf
      Call dpotrf(uplo,n,a,lda,info)

      Write (nout,*)
      If (info==0) Then

!       Estimate condition number

!       The NAG name equivalent of dpocon is f07fgf
        Call dpocon(uplo,n,a,lda,anorm,rcond,work,iwork,info)

        If (rcond>=x02ajf()) Then
          Write (nout,99999) 'Estimate of condition number =',                 &
            1.0_nag_wp/rcond
        Else
          Write (nout,*) 'A is singular to working precision'
        End If
      Else
        Write (nout,*) 'A is not positive definite'
      End If

99999 Format (1X,A,1P,E10.2)
    End Program f07fgfe


f07fhfe.f90

    Program f07fhfe

!     F07FHF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: dporfs, dpotrf, dpotrs, f06qff, nag_wp, x04caf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Integer                          :: i, ifail, info, lda, ldaf, ldb, ldx, &
                                          n, nrhs
      Character (1)                    :: uplo
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: a(:,:), af(:,:), b(:,:), berr(:),    &
                                          ferr(:), work(:), x(:,:)
      Integer, Allocatable             :: iwork(:)
!     .. Executable Statements ..
      Write (nout,*) 'F07FHF Example Program Results'
!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) n, nrhs
      lda = n
      ldaf = n
      ldb = n
      ldx = n
      Allocate (a(lda,n),af(ldaf,n),b(ldb,nrhs),berr(nrhs),ferr(nrhs),         &
        work(3*n),x(ldx,n),iwork(n))

!     Read A and B from data file, and copy A to AF and B to X

      Read (nin,*) uplo
      If (uplo=='U') Then
        Read (nin,*)(a(i,i:n),i=1,n)
      Else If (uplo=='L') Then
        Read (nin,*)(a(i,1:i),i=1,n)
      End If
      Read (nin,*)(b(i,1:nrhs),i=1,n)

      Call f06qff(uplo,n,n,a,lda,af,ldaf)

      x(1:n,1:nrhs) = b(1:n,1:nrhs)

!     Factorize A in the array AF
!     The NAG name equivalent of dpotrf is f07fdf
      Call dpotrf(uplo,n,af,ldaf,info)

      Write (nout,*)
      Flush (nout)
      If (info==0) Then

!       Compute solution in the array X
!       The NAG name equivalent of dpotrs is f07fef
        Call dpotrs(uplo,n,nrhs,af,ldaf,x,ldx,info)

!       Improve solution, and compute backward errors and
!       estimated bounds on the forward errors

!       The NAG name equivalent of dporfs is f07fhf
        Call dporfs(uplo,n,nrhs,a,lda,af,ldaf,b,ldb,x,ldx,ferr,berr,work,      &
          iwork,info)

!       Print solution

!       ifail: behaviour on error exit
!              =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
        ifail = 0
        Call x04caf('General',' ',n,nrhs,x,ldx,'Solution(s)',ifail)

        Write (nout,*)
        Write (nout,*) 'Backward errors (machine-dependent)'
        Write (nout,99999) berr(1:nrhs)
        Write (nout,*) 'Estimated forward error bounds (machine-dependent)'
        Write (nout,99999) ferr(1:nrhs)
      Else
        Write (nout,*) 'A is not positive definite'
      End If

99999 Format ((3X,1P,7E11.1))
    End Program f07fhfe


f07fjfe.f90

    Program f07fjfe

!     F07FJF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: dpotrf, dpotri, nag_wp, x04caf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Integer                          :: i, ifail, info, lda, n
      Character (1)                    :: uplo
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: a(:,:)
!     .. Executable Statements ..
      Write (nout,*) 'F07FJF Example Program Results'
!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) n
      lda = n
      Allocate (a(lda,n))

!     Read A from data file

      Read (nin,*) uplo
      If (uplo=='U') Then
        Read (nin,*)(a(i,i:n),i=1,n)
      Else If (uplo=='L') Then
        Read (nin,*)(a(i,1:i),i=1,n)
      End If

!     Factorize A
!     The NAG name equivalent of dpotrf is f07fdf
      Call dpotrf(uplo,n,a,lda,info)

      Write (nout,*)
      Flush (nout)
      If (info==0) Then

!       Compute inverse of A
!       The NAG name equivalent of dpotri is f07fjf
        Call dpotri(uplo,n,a,lda,info)

!       Print inverse

!       ifail: behaviour on error exit
!              =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
        ifail = 0
        Call x04caf(uplo,'Nonunit',n,n,a,lda,'Inverse',ifail)

      Else
        Write (nout,*) 'A is not positive definite'
      End If

    End Program f07fjfe


f07fnfe.f90

    Program f07fnfe

!     F07FNF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: nag_wp, x04dbf, zposv
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Integer                          :: i, ifail, info, lda, n
!     .. Local Arrays ..
      Complex (Kind=nag_wp), Allocatable :: a(:,:), b(:)
      Character (1)                    :: clabs(1), rlabs(1)
!     .. Executable Statements ..
      Write (nout,*) 'F07FNF Example Program Results'
      Write (nout,*)
      Flush (nout)
!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) n
      lda = n
      Allocate (a(lda,n),b(n))

!     Read the upper triangular part of A from data file

      Read (nin,*)(a(i,i:n),i=1,n)

!     Read b from data file

      Read (nin,*) b(1:n)

!     Solve the equations Ax = b for x
!     The NAG name equivalent of zposv is f07fnf
      Call zposv('Upper',n,1,a,lda,b,n,info)

      If (info==0) Then

!       Print solution

        Write (nout,*) 'Solution'
        Write (nout,99999) b(1:n)

!       Print details of factorization

        Write (nout,*)
        Flush (nout)

!       ifail: behaviour on error exit
!              =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
        ifail = 0
        Call x04dbf('Upper','Non-unit diagonal',n,n,a,lda,'Bracketed','F7.4',  &
          'Cholesky factor U','Integer',rlabs,'Integer',clabs,80,0,ifail)

      Else
        Write (nout,99998) 'The leading minor of order ', info,                &
          ' is not positive definite'
      End If

99999 Format ((3X,4(' (',F7.4,',',F7.4,')',:)))
99998 Format (1X,A,I3,A)
    End Program f07fnfe


f07fpfe.f90

    Program f07fpfe

!     F07FPF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: nag_wp, x04dbf, zposvx
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: rcond
      Integer                          :: i, ifail, info, lda, ldaf, ldb, ldx, &
                                          n, nrhs
      Character (1)                    :: equed
!     .. Local Arrays ..
      Complex (Kind=nag_wp), Allocatable :: a(:,:), af(:,:), b(:,:), work(:),  &
                                          x(:,:)
      Real (Kind=nag_wp), Allocatable  :: berr(:), ferr(:), rwork(:), s(:)
      Character (1)                    :: clabs(1), rlabs(1)
!     .. Executable Statements ..
      Write (nout,*) 'F07FPF Example Program Results'
      Write (nout,*)
      Flush (nout)
!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) n, nrhs
      lda = n
      ldaf = n
      ldb = n
      ldx = n
      Allocate (a(lda,n),af(ldaf,n),b(ldb,nrhs),work(2*n),x(ldx,nrhs),         &
        berr(nrhs),ferr(nrhs),rwork(n),s(n))

!     Read the upper triangular part of A from data file

      Read (nin,*)(a(i,i:n),i=1,n)

!     Read B from data file

      Read (nin,*)(b(i,1:nrhs),i=1,n)

!     Solve the equations AX = B for X
!     The NAG name equivalent of zposvx is f07fpf
      Call zposvx('Equilibration','Upper',n,nrhs,a,lda,af,ldaf,equed,s,b,ldb,  &
        x,ldx,rcond,ferr,berr,work,rwork,info)

      If ((info==0) .Or. (info==n+1)) Then

!       Print solution, error bounds, condition number and the form
!       of equilibration

!       ifail: behaviour on error exit
!              =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
        ifail = 0
        Call x04dbf('General',' ',n,nrhs,x,ldx,'Bracketed','F7.4',             &
          'Solution(s)','Integer',rlabs,'Integer',clabs,80,0,ifail)

        Write (nout,*)
        Write (nout,*) 'Backward errors (machine-dependent)'
        Write (nout,99999) berr(1:nrhs)
        Write (nout,*)
        Write (nout,*) 'Estimated forward error bounds (machine-dependent)'
        Write (nout,99999) ferr(1:nrhs)
        Write (nout,*)
        Write (nout,*) 'Estimate of reciprocal condition number'
        Write (nout,99999) rcond
        Write (nout,*)
        If (equed=='N') Then
          Write (nout,*) 'A has not been equilibrated'
        Else If (equed=='Y') Then
          Write (nout,*)                                                       &
            'A has been row and column scaled as diag(S)*A*diag(S)'
        End If

        If (info==n+1) Then
          Write (nout,*)
          Write (nout,*) 'The matrix A is singular to working precision'
        End If
      Else
        Write (nout,99998) 'The leading minor of order ', info,                &
          ' is not positive definite'
      End If

99999 Format ((3X,1P,7E11.1))
99998 Format (1X,A,I3,A)
    End Program f07fpfe


f07fqfe.f90

    Program f07fqfe

!     F07FQF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: nag_rp, nag_wp, zcposv
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Integer                          :: i, info, iter, lda, ldb, ldx, n, r
!     .. Local Arrays ..
      Complex (Kind=nag_wp), Allocatable :: a(:,:), b(:,:), work(:,:), x(:,:)
      Complex (Kind=nag_rp), Allocatable :: swork(:)
      Real (Kind=nag_wp), Allocatable  :: rwork(:)
!     .. Executable Statements ..
      Write (nout,*) 'F07FQF Example Program Results'
      Write (nout,*)
!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) n, r
      lda = n
      ldb = n
      ldx = n
      Allocate (a(lda,n),b(ldb,r),work(n,r),x(ldx,r),swork(n*(n+r)),rwork(n))

!     Read A and B from data file

      Read (nin,*)(a(i,i:n),i=1,n)
      Read (nin,*)(b(i,1:r),i=1,n)

!     Solve the equations Ax = b for x
!     The NAG name equivalent of zcposv is f07fqf
      Call zcposv('U',n,r,a,lda,b,ldb,x,ldx,work,swork,rwork,iter,info)

      If (info==0) Then

!       Print solution

        Write (nout,*) 'Solution'
        Write (nout,99999)(x(i,1:r),i=1,n)

      Else
        Write (nout,99998) 'The leading minor of order ', info,                &
          ' is not positive definite'
      End If

99999 Format ((3X,4(' (',F7.4,',',F7.4,')',:)))
99998 Format (1X,A,I3,A)
    End Program f07fqfe


f07frfe.f90

    Program f07frfe

!     F07FRF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: nag_wp, x04dbf, zpotrf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Integer                          :: i, ifail, info, lda, n
      Character (1)                    :: uplo
!     .. Local Arrays ..
      Complex (Kind=nag_wp), Allocatable :: a(:,:)
      Character (1)                    :: clabs(1), rlabs(1)
!     .. Executable Statements ..
      Write (nout,*) 'F07FRF Example Program Results'
!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) n
      lda = n
      Allocate (a(lda,n))

!     Read A from data file

      Read (nin,*) uplo
      If (uplo=='U') Then
        Read (nin,*)(a(i,i:n),i=1,n)
      Else If (uplo=='L') Then
        Read (nin,*)(a(i,1:i),i=1,n)
      End If

!     Factorize A
!     The NAG name equivalent of zpotrf is f07frf
      Call zpotrf(uplo,n,a,lda,info)

      Write (nout,*)
      Flush (nout)
      If (info==0) Then

!       Print factor

!       ifail: behaviour on error exit
!              =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
        ifail = 0
        Call x04dbf(uplo,'Nonunit',n,n,a,lda,'Bracketed','F7.4','Factor',      &
          'Integer',rlabs,'Integer',clabs,80,0,ifail)

      Else
        Write (nout,*) 'A is not positive definite'
      End If

    End Program f07frfe


f07fsfe.f90

    Program f07fsfe

!     F07FSF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: nag_wp, x04dbf, zpotrf, zpotrs
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Integer                          :: i, ifail, info, lda, ldb, n, nrhs
      Character (1)                    :: uplo
!     .. Local Arrays ..
      Complex (Kind=nag_wp), Allocatable :: a(:,:), b(:,:)
      Character (1)                    :: clabs(1), rlabs(1)
!     .. Executable Statements ..
      Write (nout,*) 'F07FSF Example Program Results'
!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) n, nrhs
      lda = n
      ldb = n
      Allocate (a(lda,n),b(ldb,nrhs))

!     Read A and B from data file

      Read (nin,*) uplo
      If (uplo=='U') Then
        Read (nin,*)(a(i,i:n),i=1,n)
      Else If (uplo=='L') Then
        Read (nin,*)(a(i,1:i),i=1,n)
      End If
      Read (nin,*)(b(i,1:nrhs),i=1,n)

!     Factorize A
!     The NAG name equivalent of zpotrf is f07frf
      Call zpotrf(uplo,n,a,lda,info)

      Write (nout,*)
      Flush (nout)
      If (info==0) Then

!       Compute solution
!       The NAG name equivalent of zpotrs is f07fsf
        Call zpotrs(uplo,n,nrhs,a,lda,b,ldb,info)

!       Print solution

!       ifail: behaviour on error exit
!              =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
        ifail = 0
        Call x04dbf('General',' ',n,nrhs,b,ldb,'Bracketed','F7.4',             &
          'Solution(s)','Integer',rlabs,'Integer',clabs,80,0,ifail)

      Else
        Write (nout,*) 'A is not positive definite'
      End If

    End Program f07fsfe


f07ftfe.f90

    Program f07ftfe

!     F07FTF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: f06kcf, nag_wp, x02ajf, x02amf, x02bhf, x04dbf,   &
                             zdscal, zpoequ
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Real (Kind=nag_wp), Parameter    :: one = 1.0_nag_wp
      Real (Kind=nag_wp), Parameter    :: thresh = 0.1_nag_wp
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: amax, big, scond, small
      Integer                          :: i, ifail, info, j, lda, n
!     .. Local Arrays ..
      Complex (Kind=nag_wp), Allocatable :: a(:,:)
      Real (Kind=nag_wp), Allocatable  :: s(:)
      Character (1)                    :: clabs(1), rlabs(1)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: real
!     .. Executable Statements ..
      Write (nout,*) 'F07FTF Example Program Results'
      Write (nout,*)
      Flush (nout)
!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) n
      lda = n
      Allocate (a(lda,n),s(n))

!     Read the upper triangular part of the matrix A from data file

      Read (nin,*)(a(i,i:n),i=1,n)

!     Print the matrix A

!     ifail: behaviour on error exit
!             =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
      ifail = 0
      Call x04dbf('Upper','Non-unit',n,n,a,lda,'Bracketed','1P,E10.2',         &
        'Matrix A','Integer',rlabs,'Integer',clabs,80,0,ifail)

      Write (nout,*)

!     Compute diagonal scaling factors

!     The NAG name equivalent of zpoequ is f07ftf
      Call zpoequ(n,a,lda,s,scond,amax,info)

      If (info>0) Then
        Write (nout,99999) 'Diagonal element', info, ' of A is non positive'
      Else

!       Print SCOND, AMAX and the scale factors

        Write (nout,99998) 'SCOND =', scond, ', AMAX =', amax
        Write (nout,*)
        Write (nout,*) 'Diagonal scaling factors'
        Write (nout,99997) s(1:n)
        Write (nout,*)
        Flush (nout)

!       Compute values close to underflow and overflow

        small = x02amf()/(x02ajf()*real(x02bhf(),kind=nag_wp))
        big = one/small
        If ((scond<thresh) .Or. (amax<small) .Or. (amax>big)) Then

!         Scale A
!         The NAG name equivalent of zdscal is f06jdf
          Do j = 1, n
            Call zdscal(j,s(j),a(1,j),1)
            Call f06kcf(j,s,1,a(1,j),1)
          End Do

!         Print the scaled matrix

          ifail = 0
          Call x04dbf('Upper','Non-unit',n,n,a,lda,'Bracketed','F8.4',         &
            'Scaled matrix','Integer',rlabs,'Integer',clabs,80,0,ifail)

        End If
      End If

99999 Format (1X,A,I4,A)
99998 Format (1X,2(A,1P,E8.1))
99997 Format ((1X,1P,7E11.1))
    End Program f07ftfe


f07fufe.f90

    Program f07fufe

!     F07FUF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: nag_wp, x02ajf, zlanhe => f06ucf, zpocon, zpotrf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: anorm, rcond
      Integer                          :: i, info, lda, n
      Character (1)                    :: uplo
!     .. Local Arrays ..
      Complex (Kind=nag_wp), Allocatable :: a(:,:), work(:)
      Real (Kind=nag_wp), Allocatable  :: rwork(:)
!     .. Executable Statements ..
      Write (nout,*) 'F07FUF Example Program Results'
!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) n
      lda = n
      Allocate (a(lda,n),work(2*n),rwork(n))

!     Read A from data file

      Read (nin,*) uplo
      If (uplo=='U') Then
        Read (nin,*)(a(i,i:n),i=1,n)
      Else If (uplo=='L') Then
        Read (nin,*)(a(i,1:i),i=1,n)
      End If

!     Compute norm of A
!     f06ucf is the NAG name equivalent of the LAPACK auxiliary zlanhe
      anorm = zlanhe('1-norm',uplo,n,a,lda,rwork)

!     Factorize A
!     The NAG name equivalent of zpotrf is f07frf
      Call zpotrf(uplo,n,a,lda,info)

      Write (nout,*)
      If (info==0) Then

!       Estimate condition number
!       The NAG name equivalent of zpocon is f07fuf
        Call zpocon(uplo,n,a,lda,anorm,rcond,work,rwork,info)

        If (rcond>=x02ajf()) Then
          Write (nout,99999) 'Estimate of condition number =',                 &
            1.0E0_nag_wp/rcond
        Else
          Write (nout,*) 'A is singular to working precision'
        End If
      Else
        Write (nout,*) 'A is not positive definite'
      End If

99999 Format (1X,A,1P,E10.2)
    End Program f07fufe


f07fvfe.f90

    Program f07fvfe

!     F07FVF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: f06tff, nag_wp, x04dbf, zporfs, zpotrf, zpotrs
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Integer                          :: i, ifail, info, lda, ldaf, ldb, ldx, &
                                          n, nrhs
      Character (1)                    :: uplo
!     .. Local Arrays ..
      Complex (Kind=nag_wp), Allocatable :: a(:,:), af(:,:), b(:,:), work(:),  &
                                          x(:,:)
      Real (Kind=nag_wp), Allocatable  :: berr(:), ferr(:), rwork(:)
      Character (1)                    :: clabs(1), rlabs(1)
!     .. Executable Statements ..
      Write (nout,*) 'F07FVF Example Program Results'
!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) n, nrhs
      lda = n
      ldaf = n
      ldb = n
      ldx = n
      Allocate (a(lda,n),af(ldaf,n),b(ldb,nrhs),work(2*n),x(ldx,n),berr(nrhs), &
        ferr(nrhs),rwork(n))

!     Read A and B from data file, and copy A to AF and B to X

      Read (nin,*) uplo
      If (uplo=='U') Then
        Read (nin,*)(a(i,i:n),i=1,n)
      Else If (uplo=='L') Then
        Read (nin,*)(a(i,1:i),i=1,n)
      End If
      Read (nin,*)(b(i,1:nrhs),i=1,n)

      Call f06tff(uplo,n,n,a,lda,af,ldaf)
      x(1:n,1:nrhs) = b(1:n,1:nrhs)

!     Factorize A in the array AF
!     The NAG name equivalent of zpotrf is f07frf
      Call zpotrf(uplo,n,af,ldaf,info)

      Write (nout,*)
      Flush (nout)
      If (info==0) Then

!       Compute solution in the array X
!       The NAG name equivalent of zpotrs is f07fsf
        Call zpotrs(uplo,n,nrhs,af,ldaf,x,ldx,info)

!       Improve solution, and compute backward errors and
!       estimated bounds on the forward errors

!       The NAG name equivalent of zporfs is f07fvf
        Call zporfs(uplo,n,nrhs,a,lda,af,ldaf,b,ldb,x,ldx,ferr,berr,work,      &
          rwork,info)

!       Print solution

!       ifail: behaviour on error exit
!              =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
        ifail = 0
        Call x04dbf('General',' ',n,nrhs,x,ldx,'Bracketed','F7.4',             &
          'Solution(s)','Integer',rlabs,'Integer',clabs,80,0,ifail)

        Write (nout,*)
        Write (nout,*) 'Backward errors (machine-dependent)'
        Write (nout,99999) berr(1:nrhs)
        Write (nout,*) 'Estimated forward error bounds (machine-dependent)'
        Write (nout,99999) ferr(1:nrhs)
      Else
        Write (nout,*) 'A is not positive definite'
      End If

99999 Format ((5X,1P,4(E11.1,7X)))
    End Program f07fvfe


f07fwfe.f90

    Program f07fwfe

!     F07FWF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: nag_wp, x04dbf, zpotrf, zpotri
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Integer                          :: i, ifail, info, lda, n
      Character (1)                    :: uplo
!     .. Local Arrays ..
      Complex (Kind=nag_wp), Allocatable :: a(:,:)
      Character (1)                    :: clabs(1), rlabs(1)
!     .. Executable Statements ..
      Write (nout,*) 'F07FWF Example Program Results'
!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) n
      lda = n
      Allocate (a(lda,n))

!     Read A from data file

      Read (nin,*) uplo
      If (uplo=='U') Then
        Read (nin,*)(a(i,i:n),i=1,n)
      Else If (uplo=='L') Then
        Read (nin,*)(a(i,1:i),i=1,n)
      End If

!     Factorize A
!     The NAG name equivalent of zpotrf is f07frf
      Call zpotrf(uplo,n,a,lda,info)

      Write (nout,*)
      Flush (nout)
      If (info==0) Then

!       Compute inverse of A
!       The NAG name equivalent of zpotri is f07fwf
        Call zpotri(uplo,n,a,lda,info)

!       Print inverse

!       ifail: behaviour on error exit
!              =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
        ifail = 0
        Call x04dbf(uplo,'Nonunit',n,n,a,lda,'Bracketed','F7.4','Inverse',     &
          'Integer',rlabs,'Integer',clabs,80,0,ifail)
      Else
        Write (nout,*) 'A is not positive definite'
      End If

    End Program f07fwfe


f07gafe.f90

    Program f07gafe

!     F07GAF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: dppsv, nag_wp, x04ccf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
      Character (1), Parameter         :: uplo = 'U'
!     .. Local Scalars ..
      Integer                          :: i, ifail, info, j, n
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: ap(:), b(:)
!     .. Executable Statements ..
      Write (nout,*) 'F07GAF Example Program Results'
      Write (nout,*)
!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) n

      Allocate (ap((n*(n+1))/2),b(n))

!     Read the upper or lower triangular part of the matrix A from
!     data file

      If (uplo=='U') Then
        Read (nin,*)((ap(i+(j*(j-1))/2),j=i,n),i=1,n)
      Else If (uplo=='L') Then
        Read (nin,*)((ap(i+((2*n-j)*(j-1))/2),j=1,i),i=1,n)
      End If

!     Read b from data file

      Read (nin,*) b(1:n)

!     Solve the equations Ax = b for x
!     The NAG name equivalent of dppsv is f07gaf
      Call dppsv(uplo,n,1,ap,b,n,info)

      If (info==0) Then

!       Print solution

        Write (nout,*) 'Solution'
        Write (nout,99999) b(1:n)

!       Print details of factorization

        Write (nout,*)
        Flush (nout)

!       ifail: behaviour on error exit
!              =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
        ifail = 0
        Call x04ccf(uplo,'Non-unit diagonal',n,ap,'Cholesky factor',ifail)

      Else
        Write (nout,99998) 'The leading minor of order ', info,                &
          ' is not positive definite'
      End If

99999 Format ((3X,7F11.4))
99998 Format (1X,A,I3,A)
    End Program f07gafe


f07gbfe.f90

    Program f07gbfe

!     F07GBF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: dppsvx, nag_wp, x04caf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
      Character (1), Parameter         :: uplo = 'U'
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: rcond
      Integer                          :: i, ifail, info, j, ldb, ldx, n, nrhs
      Character (1)                    :: equed
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: afp(:), ap(:), b(:,:), berr(:),      &
                                          ferr(:), s(:), work(:), x(:,:)
      Integer, Allocatable             :: iwork(:)
!     .. Executable Statements ..
      Write (nout,*) 'F07GBF Example Program Results'
      Write (nout,*)
      Flush (nout)
!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) n, nrhs
      ldb = n
      ldx = n
      Allocate (afp((n*(n+1))/2),ap((n*(n+1))/2),b(ldb,nrhs),berr(nrhs),ferr(  &
        nrhs),s(n),work(3*n),x(ldx,nrhs),iwork(n))

!     Read the upper or lower triangular part of the matrix A from
!     data file

      If (uplo=='U') Then
        Read (nin,*)((ap(i+(j*(j-1))/2),j=i,n),i=1,n)
      Else If (uplo=='L') Then
        Read (nin,*)((ap(i+((2*n-j)*(j-1))/2),j=1,i),i=1,n)
      End If

!     Read B from data file

      Read (nin,*)(b(i,1:nrhs),i=1,n)

!     Solve the equations AX = B for X
!     The NAG name equivalent of dppsvx is f07gbf
      Call dppsvx('Equilibration',uplo,n,nrhs,ap,afp,equed,s,b,ldb,x,ldx,      &
        rcond,ferr,berr,work,iwork,info)

      If ((info==0) .Or. (info==n+1)) Then

!       Print solution, error bounds, condition number and the form
!       of equilibration

!       ifail: behaviour on error exit
!              =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
        ifail = 0
        Call x04caf('General',' ',n,nrhs,x,ldx,'Solution(s)',ifail)

        Write (nout,*)
        Write (nout,*) 'Backward errors (machine-dependent)'
        Write (nout,99999) berr(1:nrhs)
        Write (nout,*)
        Write (nout,*) 'Estimated forward error bounds (machine-dependent)'
        Write (nout,99999) ferr(1:nrhs)
        Write (nout,*)
        Write (nout,*) 'Estimate of reciprocal condition number'
        Write (nout,99999) rcond
        Write (nout,*)
        If (equed=='N') Then
          Write (nout,*) 'A has not been equilibrated'
        Else If (equed=='Y') Then
          Write (nout,*)                                                       &
            'A has been row and column scaled as diag(S)*A*diag(S)'
        End If

        If (info==n+1) Then
          Write (nout,*)
          Write (nout,*) 'The matrix A is singular to working precision'
        End If
      Else
        Write (nout,99998) 'The leading minor of order ', info,                &
          ' is not positive definite'
      End If

99999 Format ((3X,1P,7E11.1))
99998 Format (1X,A,I3,A)
    End Program f07gbfe


f07gdfe.f90

    Program f07gdfe

!     F07GDF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: dpptrf, nag_wp, x04ccf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Integer                          :: i, ifail, info, j, n
      Character (1)                    :: uplo
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: ap(:)
!     .. Executable Statements ..
      Write (nout,*) 'F07GDF Example Program Results'
!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) n

      Allocate (ap(n*(n+1)/2))

!     Read A from data file

      Read (nin,*) uplo
      If (uplo=='U') Then
        Read (nin,*)((ap(i+j*(j-1)/2),j=i,n),i=1,n)
      Else If (uplo=='L') Then
        Read (nin,*)((ap(i+(2*n-j)*(j-1)/2),j=1,i),i=1,n)
      End If

!     Factorize A
!     The NAG name equivalent of dpptrf is f07gdf
      Call dpptrf(uplo,n,ap,info)

      Write (nout,*)
      Flush (nout)
      If (info==0) Then

!       Print factor

!       ifail: behaviour on error exit
!              =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
        ifail = 0
        Call x04ccf(uplo,'Nonunit',n,ap,'Factor',ifail)

      Else
        Write (nout,*) 'A is not positive definite'
      End If

    End Program f07gdfe


f07gefe.f90

    Program f07gefe

!     F07GEF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: dpptrf, dpptrs, nag_wp, x04caf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Integer                          :: i, ifail, info, j, ldb, n, nrhs
      Character (1)                    :: uplo
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: ap(:), b(:,:)
!     .. Executable Statements ..
      Write (nout,*) 'F07GEF Example Program Results'
!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) n, nrhs
      ldb = n
      Allocate (ap(n*(n+1)/2),b(ldb,nrhs))

!     Read A and B from data file

      Read (nin,*) uplo
      If (uplo=='U') Then
        Read (nin,*)((ap(i+j*(j-1)/2),j=i,n),i=1,n)
      Else If (uplo=='L') Then
        Read (nin,*)((ap(i+(2*n-j)*(j-1)/2),j=1,i),i=1,n)
      End If
      Read (nin,*)(b(i,1:nrhs),i=1,n)

!     Factorize A
!     The NAG name equivalent of dpptrf is f07gdf
      Call dpptrf(uplo,n,ap,info)

      Write (nout,*)
      Flush (nout)
      If (info==0) Then

!       Compute solution
!       The NAG name equivalent of dpptrs is f07gef
        Call dpptrs(uplo,n,nrhs,ap,b,ldb,info)

!       Print solution

!       ifail: behaviour on error exit
!              =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
        ifail = 0
        Call x04caf('General',' ',n,nrhs,b,ldb,'Solution(s)',ifail)

      Else
        Write (nout,*) 'A is not positive definite'
      End If

    End Program f07gefe


f07gffe.f90

    Program f07gffe

!     F07GFF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: dppequ, dscal, f06fcf, nag_wp, x02ajf, x02amf,    &
                             x02bhf, x04ccf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Real (Kind=nag_wp), Parameter    :: one = 1.0_nag_wp
      Real (Kind=nag_wp), Parameter    :: thresh = 0.1_nag_wp
      Integer, Parameter               :: nin = 5, nout = 6
      Character (1), Parameter         :: uplo = 'U'
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: amax, big, scond, small
      Integer                          :: i, ifail, info, j, jinc, jj, n
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: ap(:), s(:)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: real
!     .. Executable Statements ..
      Write (nout,*) 'F07GFF Example Program Results'
      Write (nout,*)
      Flush (nout)
!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) n

      Allocate (ap((n*(n+1))/2),s(n))

!     Read the upper or lower triangular part of the matrix A from
!     data file

      If (uplo=='U') Then
        Read (nin,*)((ap(i+(j*(j-1))/2),j=i,n),i=1,n)
      Else If (uplo=='L') Then
        Read (nin,*)((ap(i+((2*n-j)*(j-1))/2),j=1,i),i=1,n)
      End If

!     Print the matrix A

!     ifail: behaviour on error exit
!             =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
      ifail = 0
      Call x04ccf(uplo,'Non-unit diagonal',n,ap,'Matrix A',ifail)

      Write (nout,*)

!     Compute diagonal scaling factors
!     The NAG name equivalent of dppequ is f07gff
      Call dppequ(uplo,n,ap,s,scond,amax,info)

      If (info>0) Then
        Write (nout,99999) 'Diagonal element', info, ' of A is non positive'
      Else

!       Print SCOND, AMAX and the scale factors

        Write (nout,99998) 'SCOND =', scond, ', AMAX =', amax
        Write (nout,*)
        Write (nout,*) 'Diagonal scaling factors'
        Write (nout,99997) s(1:n)
        Write (nout,*)
        Flush (nout)

!       Compute values close to underflow and overflow

        small = x02amf()/(x02ajf()*real(x02bhf(),kind=nag_wp))
        big = one/small
        If ((scond<thresh) .Or. (amax<small) .Or. (amax>big)) Then

!         Scale A

          If (uplo=='U') Then
!           The NAG name equivalent of dscal is f06edf
            jj = 1
            Do j = 1, n
              Call dscal(j,s(j),ap(jj),1)
              Call f06fcf(j,s,1,ap(jj),1)
              jj = jj + j
            End Do
          Else If (uplo=='L') Then
            jj = 1
            jinc = n
            Do j = 1, n
              Call dscal(jinc,s(j),ap(jj),1)
              Call f06fcf(jinc,s(j),1,ap(jj),1)
              jj = jj + jinc
              jinc = jinc - 1
            End Do
          End If

!         Print the scaled matrix

          ifail = 0
          Call x04ccf(uplo,'Non-unit diagonal',n,ap,'Scaled matrix',ifail)

        End If
      End If

99999 Format (1X,A,I4,A)
99998 Format (1X,2(A,1P,E8.1))
99997 Format ((1X,1P,7E11.1))
    End Program f07gffe


f07ggfe.f90

    Program f07ggfe

!     F07GGF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: dlansp => f06rdf, dppcon, dpptrf, nag_wp, x02ajf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: anorm, rcond
      Integer                          :: i, info, j, n
      Character (1)                    :: uplo
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: ap(:), work(:)
      Integer, Allocatable             :: iwork(:)
!     .. Executable Statements ..
      Write (nout,*) 'F07GGF Example Program Results'
!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) n

      Allocate (ap(n*(n+1)/2),work(3*n),iwork(n))

!     Read A from data file

      Read (nin,*) uplo
      If (uplo=='U') Then
        Read (nin,*)((ap(i+j*(j-1)/2),j=i,n),i=1,n)
      Else If (uplo=='L') Then
        Read (nin,*)((ap(i+(2*n-j)*(j-1)/2),j=1,i),i=1,n)
      End If

!     Compute norm of A
!     f06rdf is the NAG name equivalent of the LAPACK auxiliary dlansp
      anorm = dlansp('1-norm',uplo,n,ap,work)

!     Factorize A
!     The NAG name equivalent of dppcon is f07gdf
      Call dpptrf(uplo,n,ap,info)

      Write (nout,*)
      If (info==0) Then

!       Estimate condition number

!       The NAG name equivalent of dppcon is f07ggf
        Call dppcon(uplo,n,ap,anorm,rcond,work,iwork,info)

        If (rcond>=x02ajf()) Then
          Write (nout,99999) 'Estimate of condition number =',                 &
            1.0_nag_wp/rcond
        Else
          Write (nout,*) 'A is singular to working precision'
        End If
      Else
        Write (nout,*) 'A is not positive definite'
      End If

99999 Format (1X,A,1P,E10.2)
    End Program f07ggfe


f07ghfe.f90

    Program f07ghfe

!     F07GHF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: dpprfs, dpptrf, dpptrs, nag_wp, x04caf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Integer                          :: aplen, i, ifail, info, j, ldb, ldx,  &
                                          n, nrhs
      Character (1)                    :: uplo
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: afp(:), ap(:), b(:,:), berr(:),      &
                                          ferr(:), work(:), x(:,:)
      Integer, Allocatable             :: iwork(:)
!     .. Executable Statements ..
      Write (nout,*) 'F07GHF Example Program Results'
!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) n, nrhs
      ldb = n
      ldx = n
      aplen = n*(n+1)/2
      Allocate (afp(aplen),ap(aplen),b(ldb,nrhs),berr(nrhs),ferr(nrhs),        &
        work(3*n),x(ldx,n),iwork(n))

!     Read A and B from data file, and copy A to AFP and B to X

      Read (nin,*) uplo
      If (uplo=='U') Then
        Read (nin,*)((ap(i+j*(j-1)/2),j=i,n),i=1,n)
      Else If (uplo=='L') Then
        Read (nin,*)((ap(i+(2*n-j)*(j-1)/2),j=1,i),i=1,n)
      End If
      Read (nin,*)(b(i,1:nrhs),i=1,n)

      afp(1:aplen) = ap(1:aplen)
      x(1:n,1:nrhs) = b(1:n,1:nrhs)

!     Factorize A in the array AFP
!     The NAG name equivalent of dpptrf is f07gdf
      Call dpptrf(uplo,n,afp,info)

      Write (nout,*)
      Flush (nout)
      If (info==0) Then

!       Compute solution in the array X
!       The NAG name equivalent of dpptrs is f07gef
        Call dpptrs(uplo,n,nrhs,afp,x,ldx,info)

!       Improve solution, and compute backward errors and
!       estimated bounds on the forward errors

!       The NAG name equivalent of dpprfs is f07ghf
        Call dpprfs(uplo,n,nrhs,ap,afp,b,ldb,x,ldx,ferr,berr,work,iwork,info)

!       Print solution

!       ifail: behaviour on error exit
!              =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
        ifail = 0
        Call x04caf('General',' ',n,nrhs,x,ldx,'Solution(s)',ifail)

        Write (nout,*)
        Write (nout,*) 'Backward errors (machine-dependent)'
        Write (nout,99999) berr(1:nrhs)
        Write (nout,*) 'Estimated forward error bounds (machine-dependent)'
        Write (nout,99999) ferr(1:nrhs)
      Else
        Write (nout,*) 'A is not positive definite'
      End If

99999 Format ((3X,1P,7E11.1))
    End Program f07ghfe


f07gjfe.f90

    Program f07gjfe

!     F07GJF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: dpptrf, dpptri, nag_wp, x04ccf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Integer                          :: i, ifail, info, j, n
      Character (1)                    :: uplo
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: ap(:)
!     .. Executable Statements ..
      Write (nout,*) 'F07GJF Example Program Results'
!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) n

      Allocate (ap(n*(n+1)/2))

!     Read A from data file

      Read (nin,*) uplo
      If (uplo=='U') Then
        Read (nin,*)((ap(i+j*(j-1)/2),j=i,n),i=1,n)
      Else If (uplo=='L') Then
        Read (nin,*)((ap(i+(2*n-j)*(j-1)/2),j=1,i),i=1,n)
      End If

!     Factorize A
!     The NAG name equivalent of dpptrf is f07gdf
      Call dpptrf(uplo,n,ap,info)

      Write (nout,*)
      Flush (nout)
      If (info==0) Then

!       Compute inverse of A
!       The NAG name equivalent of dpptri is f07gjf
        Call dpptri(uplo,n,ap,info)

!       Print inverse

!       ifail: behaviour on error exit
!              =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
        ifail = 0
        Call x04ccf(uplo,'Nonunit',n,ap,'Inverse',ifail)

      Else
        Write (nout,*) 'A is not positive definite'
      End If

    End Program f07gjfe


f07gnfe.f90

    Program f07gnfe

!     F07GNF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: nag_wp, x04ddf, zppsv
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
      Character (1), Parameter         :: uplo = 'U'
!     .. Local Scalars ..
      Integer                          :: i, ifail, info, j, n
!     .. Local Arrays ..
      Complex (Kind=nag_wp), Allocatable :: ap(:), b(:)
      Character (1)                    :: clabs(1), rlabs(1)
!     .. Executable Statements ..
      Write (nout,*) 'F07GNF Example Program Results'
      Write (nout,*)
!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) n

      Allocate (ap((n*(n+1))/2),b(n))

!     Read the upper or lower triangular part of the matrix A from
!     data file

      If (uplo=='U') Then
        Read (nin,*)((ap(i+(j*(j-1))/2),j=i,n),i=1,n)
      Else If (uplo=='L') Then
        Read (nin,*)((ap(i+((2*n-j)*(j-1))/2),j=1,i),i=1,n)
      End If

!     Read b from data file

      Read (nin,*) b(1:n)

!     Solve the equations Ax = b for x
!     The NAG name equivalent of zppsv is f07gnf
      Call zppsv(uplo,n,1,ap,b,n,info)

      If (info==0) Then

!       Print solution

        Write (nout,*) 'Solution'
        Write (nout,99999) b(1:n)

!       Print details of factorization

        Write (nout,*)
        Flush (nout)

!       ifail: behaviour on error exit
!              =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
        ifail = 0
        Call x04ddf(uplo,'Non-unit diagonal',n,ap,'Bracketed','F7.4',          &
          'Cholesky factor','Integer',rlabs,'Integer',clabs,80,0,ifail)

      Else
        Write (nout,99998) 'The leading minor of order ', info,                &
          ' is not positive definite'
      End If

99999 Format ((3X,4(' (',F7.4,',',F7.4,')',:)))
99998 Format (1X,A,I3,A)
    End Program f07gnfe


f07gpfe.f90

    Program f07gpfe

!     F07GPF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: nag_wp, x04dbf, zppsvx
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
      Character (1), Parameter         :: uplo = 'U'
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: rcond
      Integer                          :: i, ifail, info, j, ldb, ldx, n, nrhs
      Character (1)                    :: equed
!     .. Local Arrays ..
      Complex (Kind=nag_wp), Allocatable :: afp(:), ap(:), b(:,:), work(:),    &
                                          x(:,:)
      Real (Kind=nag_wp), Allocatable  :: berr(:), ferr(:), rwork(:), s(:)
      Character (1)                    :: clabs(1), rlabs(1)
!     .. Executable Statements ..
      Write (nout,*) 'F07GPF Example Program Results'
      Write (nout,*)
      Flush (nout)
!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) n, nrhs
      ldb = n
      ldx = n
      Allocate (afp((n*(n+1))/2),ap((n*(n+1))/2),b(ldb,nrhs),work(2*n),x(ldx,  &
        nrhs),berr(nrhs),ferr(nrhs),rwork(n),s(n))

!     Read the upper or lower triangular part of the matrix A from
!     data file

      If (uplo=='U') Then
        Read (nin,*)((ap(i+(j*(j-1))/2),j=i,n),i=1,n)
      Else If (uplo=='L') Then
        Read (nin,*)((ap(i+((2*n-j)*(j-1))/2),j=1,i),i=1,n)
      End If

!     Read B from data file

      Read (nin,*)(b(i,1:nrhs),i=1,n)

!     Solve the equations AX = B for X
!     The NAG name equivalent of zppsvx is f07gpf
      Call zppsvx('Equilibration',uplo,n,nrhs,ap,afp,equed,s,b,ldb,x,ldx,      &
        rcond,ferr,berr,work,rwork,info)

      If ((info==0) .Or. (info==n+1)) Then

!       Print solution, error bounds, condition number and the form
!       of equilibration

!       ifail: behaviour on error exit
!              =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
        ifail = 0
        Call x04dbf('General',' ',n,nrhs,x,ldx,'Bracketed','F7.4',             &
          'Solution(s)','Integer',rlabs,'Integer',clabs,80,0,ifail)

        Write (nout,*)
        Write (nout,*) 'Backward errors (machine-dependent)'
        Write (nout,99999) berr(1:nrhs)
        Write (nout,*)
        Write (nout,*) 'Estimated forward error bounds (machine-dependent)'
        Write (nout,99999) ferr(1:nrhs)
        Write (nout,*)
        Write (nout,*) 'Estimate of reciprocal condition number'
        Write (nout,99999) rcond
        Write (nout,*)
        If (equed=='N') Then
          Write (nout,*) 'A has not been equilibrated'
        Else If (equed=='Y') Then
          Write (nout,*)                                                       &
            'A has been row and column scaled as diag(S)*A*diag(S)'
        End If

        If (info==n+1) Then
          Write (nout,*)
          Write (nout,*) 'The matrix A is singular to working precision'
        End If
      Else
        Write (nout,99998) 'The leading minor of order ', info,                &
          ' is not positive definite'
      End If

99999 Format ((3X,1P,7E11.1))
99998 Format (1X,A,I3,A)
    End Program f07gpfe


f07grfe.f90

    Program f07grfe

!     F07GRF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: nag_wp, x04ddf, zpptrf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Integer                          :: i, ifail, info, j, n
      Character (1)                    :: uplo
!     .. Local Arrays ..
      Complex (Kind=nag_wp), Allocatable :: ap(:)
      Character (1)                    :: clabs(1), rlabs(1)
!     .. Executable Statements ..
      Write (nout,*) 'F07GRF Example Program Results'
!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) n

      Allocate (ap(n*(n+1)/2))

!     Read A from data file

      Read (nin,*) uplo
      If (uplo=='U') Then
        Read (nin,*)((ap(i+j*(j-1)/2),j=i,n),i=1,n)
      Else If (uplo=='L') Then
        Read (nin,*)((ap(i+(2*n-j)*(j-1)/2),j=1,i),i=1,n)
      End If

!     Factorize A
!     The NAG name equivalent of zpptrf is f07grf
      Call zpptrf(uplo,n,ap,info)

      Write (nout,*)
      Flush (nout)
      If (info==0) Then

!       Print factor

!       ifail: behaviour on error exit
!              =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
        ifail = 0
        Call x04ddf(uplo,'Nonunit',n,ap,'Bracketed','F7.4','Factor','Integer', &
          rlabs,'Integer',clabs,80,0,ifail)

      Else
        Write (nout,*) 'A is not positive definite'
      End If

    End Program f07grfe


f07gsfe.f90

    Program f07gsfe

!     F07GSF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: nag_wp, x04dbf, zpptrf, zpptrs
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Integer                          :: i, ifail, info, j, ldb, n, nrhs
      Character (1)                    :: uplo
!     .. Local Arrays ..
      Complex (Kind=nag_wp), Allocatable :: ap(:), b(:,:)
      Character (1)                    :: clabs(1), rlabs(1)
!     .. Executable Statements ..
      Write (nout,*) 'F07GSF Example Program Results'
!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) n, nrhs
      ldb = n
      Allocate (ap(n*(n+1)/2),b(ldb,nrhs))

!     Read A and B from data file

      Read (nin,*) uplo
      If (uplo=='U') Then
        Read (nin,*)((ap(i+j*(j-1)/2),j=i,n),i=1,n)
      Else If (uplo=='L') Then
        Read (nin,*)((ap(i+(2*n-j)*(j-1)/2),j=1,i),i=1,n)
      End If
      Read (nin,*)(b(i,1:nrhs),i=1,n)

!     Factorize A
!     The NAG name equivalent of zpptrf is f07grf
      Call zpptrf(uplo,n,ap,info)

      Write (nout,*)
      Flush (nout)
      If (info==0) Then

!       Compute solution
!       The NAG name equivalent of zpptrs is f07gsf
        Call zpptrs(uplo,n,nrhs,ap,b,ldb,info)

!       Print solution

!       ifail: behaviour on error exit
!              =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
        ifail = 0
        Call x04dbf('General',' ',n,nrhs,b,ldb,'Bracketed','F7.4',             &
          'Solution(s)','Integer',rlabs,'Integer',clabs,80,0,ifail)

      Else
        Write (nout,*) 'A is not positive definite'
      End If

    End Program f07gsfe


f07gtfe.f90

    Program f07gtfe

!     F07GTF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: f06kcf, nag_wp, x02ajf, x02amf, x02bhf, x04ddf,   &
                             zdscal, zppequ
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Real (Kind=nag_wp), Parameter    :: one = 1.0_nag_wp
      Real (Kind=nag_wp), Parameter    :: thresh = 0.1_nag_wp
      Integer, Parameter               :: nin = 5, nout = 6
      Character (1), Parameter         :: uplo = 'U'
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: amax, big, scond, small
      Integer                          :: i, ifail, info, j, jinc, jj, n
!     .. Local Arrays ..
      Complex (Kind=nag_wp), Allocatable :: ap(:)
      Real (Kind=nag_wp), Allocatable  :: s(:)
      Character (1)                    :: clabs(1), rlabs(1)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: real
!     .. Executable Statements ..
      Write (nout,*) 'F07GTF Example Program Results'
      Write (nout,*)
      Flush (nout)
!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) n

      Allocate (ap((n*(n+1))/2),s(n))

!     Read the upper or lower triangular part of the matrix A from
!     data file

      If (uplo=='U') Then
        Read (nin,*)((ap(i+(j*(j-1))/2),j=i,n),i=1,n)
      Else If (uplo=='L') Then
        Read (nin,*)((ap(i+((2*n-j)*(j-1))/2),j=1,i),i=1,n)
      End If

!     Print the matrix A

!     ifail: behaviour on error exit
!             =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
      ifail = 0
      Call x04ddf(uplo,'Non-unit diagonal',n,ap,'Bracketed','1P,E10.2',        &
        'Matrix A','Integer',rlabs,'Integer',clabs,80,0,ifail)

      Write (nout,*)

!     Compute diagonal scaling factors
!     The NAG name equivalent of zppequ is f07gtf
      Call zppequ(uplo,n,ap,s,scond,amax,info)

      If (info>0) Then
        Write (nout,99999) 'Diagonal element', info, ' of A is non positive'
      Else

!       Print SCOND, AMAX and the scale factors

        Write (nout,99998) 'SCOND =', scond, ', AMAX =', amax
        Write (nout,*)
        Write (nout,*) 'Diagonal scaling factors'
        Write (nout,99997) s(1:n)
        Write (nout,*)
        Flush (nout)

!       Compute values close to underflow and overflow

        small = x02amf()/(x02ajf()*real(x02bhf(),kind=nag_wp))
        big = one/small
        If ((scond<thresh) .Or. (amax<small) .Or. (amax>big)) Then

!         Scale A

          If (uplo=='U') Then

!           The NAG name equivalent of zdscal is f06jdf
            jj = 1
            Do j = 1, n
              Call zdscal(j,s(j),ap(jj),1)
              Call f06kcf(j,s,1,ap(jj),1)
              jj = jj + j
            End Do
          Else If (uplo=='L') Then
            jj = 1
            jinc = n
            Do j = 1, n
              Call zdscal(jinc,s(j),ap(jj),1)
              Call f06kcf(jinc,s(j),1,ap(jj),1)
              jj = jj + jinc
              jinc = jinc - 1
            End Do
          End If

!         Print the scaled matrix

          ifail = 0
          Call x04ddf(uplo,'Non-unit diagonal',n,ap,'Bracketed','F8.4',        &
            'Scaled matrix','Integer',rlabs,'Integer',clabs,80,0,ifail)

        End If
      End If

99999 Format (1X,A,I4,A)
99998 Format (1X,2(A,1P,E8.1))
99997 Format ((1X,1P,7E11.1))
    End Program f07gtfe


f07gufe.f90

    Program f07gufe

!     F07GUF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: nag_wp, x02ajf, zlanhp => f06udf, zppcon, zpptrf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: anorm, rcond
      Integer                          :: i, info, j, n
      Character (1)                    :: uplo
!     .. Local Arrays ..
      Complex (Kind=nag_wp), Allocatable :: ap(:), work(:)
      Real (Kind=nag_wp), Allocatable  :: rwork(:)
!     .. Executable Statements ..
      Write (nout,*) 'F07GUF Example Program Results'
!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) n

      Allocate (ap(n*(n+1)/2),work(2*n),rwork(n))

!     Read A from data file

      Read (nin,*) uplo
      If (uplo=='U') Then
        Read (nin,*)((ap(i+j*(j-1)/2),j=i,n),i=1,n)
      Else If (uplo=='L') Then
        Read (nin,*)((ap(i+(2*n-j)*(j-1)/2),j=1,i),i=1,n)
      End If

!     Compute norm of A
!     f06udf is the NAG name equivalent of the LAPACK auxiliary zlanhp
      anorm = zlanhp('1-norm',uplo,n,ap,rwork)

!     Factorize A
!     The NAG name equivalent of zpptrf is f07grf
      Call zpptrf(uplo,n,ap,info)

      Write (nout,*)
      If (info==0) Then

!       Estimate condition number

!       The NAG name equivalent of zppcon is f07guf
        Call zppcon(uplo,n,ap,anorm,rcond,work,rwork,info)

        If (rcond>=x02ajf()) Then
          Write (nout,99999) 'Estimate of condition number =',                 &
            1.0_nag_wp/rcond
        Else
          Write (nout,*) 'A is singular to working precision'
        End If
      Else
        Write (nout,*) 'A is not positive definite'
      End If

99999 Format (1X,A,1P,E10.2)
    End Program f07gufe


f07gvfe.f90

    Program f07gvfe

!     F07GVF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: nag_wp, x04dbf, zpprfs, zpptrf, zpptrs
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Integer                          :: aplen, i, ifail, info, j, ldb, ldx,  &
                                          n, nrhs
      Character (1)                    :: uplo
!     .. Local Arrays ..
      Complex (Kind=nag_wp), Allocatable :: afp(:), ap(:), b(:,:), work(:),    &
                                          x(:,:)
      Real (Kind=nag_wp), Allocatable  :: berr(:), ferr(:), rwork(:)
      Character (1)                    :: clabs(1), rlabs(1)
!     .. Executable Statements ..
      Write (nout,*) 'F07GVF Example Program Results'
!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) n, nrhs
      ldb = n
      ldx = n
      aplen = n*(n+1)/2
      Allocate (afp(aplen),ap(aplen),b(ldb,nrhs),work(2*n),x(ldx,n),           &
        berr(nrhs),ferr(nrhs),rwork(n))

!     Read A and B from data file, and copy A to AFP and B to X

      Read (nin,*) uplo
      If (uplo=='U') Then
        Read (nin,*)((ap(i+j*(j-1)/2),j=i,n),i=1,n)
      Else If (uplo=='L') Then
        Read (nin,*)((ap(i+(2*n-j)*(j-1)/2),j=1,i),i=1,n)
      End If
      Read (nin,*)(b(i,1:nrhs),i=1,n)

      afp(1:aplen) = ap(1:aplen)
      x(1:n,1:nrhs) = b(1:n,1:nrhs)

!     Factorize A in the array AFP
!     The NAG name equivalent of zpptrf is f07grf
      Call zpptrf(uplo,n,afp,info)

      Write (nout,*)
      Flush (nout)
      If (info==0) Then

!       Compute solution in the array X
!       The NAG name equivalent of zpptrs is f07gsf
        Call zpptrs(uplo,n,nrhs,afp,x,ldx,info)

!       Improve solution, and compute backward errors and
!       estimated bounds on the forward errors

!       The NAG name equivalent of zpprfs is f07gvf
        Call zpprfs(uplo,n,nrhs,ap,afp,b,ldb,x,ldx,ferr,berr,work,rwork,info)

!       Print solution

!       ifail: behaviour on error exit
!              =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
        ifail = 0
        Call x04dbf('General',' ',n,nrhs,x,ldx,'Bracketed','F7.4',             &
          'Solution(s)','Integer',rlabs,'Integer',clabs,80,0,ifail)

        Write (nout,*)
        Write (nout,*) 'Backward errors (machine-dependent)'
        Write (nout,99999) berr(1:nrhs)
        Write (nout,*) 'Estimated forward error bounds (machine-dependent)'
        Write (nout,99999) ferr(1:nrhs)
      Else
        Write (nout,*) 'A is not positive definite'
      End If

99999 Format ((5X,1P,4(E11.1,7X)))
    End Program f07gvfe


f07gwfe.f90

    Program f07gwfe

!     F07GWF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: nag_wp, x04ddf, zpptrf, zpptri
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Integer                          :: i, ifail, info, j, n
      Character (1)                    :: uplo
!     .. Local Arrays ..
      Complex (Kind=nag_wp), Allocatable :: ap(:)
      Character (1)                    :: clabs(1), rlabs(1)
!     .. Executable Statements ..
      Write (nout,*) 'F07GWF Example Program Results'
!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) n

      Allocate (ap(n*(n+1)/2))

!     Read A from data file

      Read (nin,*) uplo
      If (uplo=='U') Then
        Read (nin,*)((ap(i+j*(j-1)/2),j=i,n),i=1,n)
      Else If (uplo=='L') Then
        Read (nin,*)((ap(i+(2*n-j)*(j-1)/2),j=1,i),i=1,n)
      End If

!     Factorize A
!     The NAG name equivalent of zpptrf is f07grf
      Call zpptrf(uplo,n,ap,info)

      Write (nout,*)
      Flush (nout)
      If (info==0) Then

!       Compute inverse of A
!       The NAG name equivalent of zpptri is f07gwf
        Call zpptri(uplo,n,ap,info)

!       Print inverse

!       ifail: behaviour on error exit
!              =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
        ifail = 0
        Call x04ddf(uplo,'Nonunit',n,ap,'Bracketed','F7.4','Inverse',          &
          'Integer',rlabs,'Integer',clabs,80,0,ifail)

      Else
        Write (nout,*) 'A is not positive definite'
      End If

    End Program f07gwfe


f07hafe.f90

    Program f07hafe

!     F07HAF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: dpbsv, nag_wp, x04cef
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
      Character (1), Parameter         :: uplo = 'U'
!     .. Local Scalars ..
      Integer                          :: i, ifail, info, j, kd, ldab, n
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: ab(:,:), b(:)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: max, min
!     .. Executable Statements ..
      Write (nout,*) 'F07HAF Example Program Results'
      Write (nout,*)
!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) n, kd
      ldab = kd + 1
      Allocate (ab(ldab,n),b(n))

!     Read the upper or lower triangular part of the band matrix A
!     from data file

      If (uplo=='U') Then
        Read (nin,*)((ab(kd+1+i-j,j),j=i,min(n,i+kd)),i=1,n)
      Else If (uplo=='L') Then
        Read (nin,*)((ab(1+i-j,j),j=max(1,i-kd),i),i=1,n)
      End If

!     Read b from data file

      Read (nin,*) b(1:n)

!     Solve the equations Ax = b for x
!     The NAG name equivalent of dpbsv is f07haf
      Call dpbsv(uplo,n,kd,1,ab,ldab,b,n,info)

      If (info==0) Then

!       Print solution

        Write (nout,*) 'Solution'
        Write (nout,99999) b(1:n)

!       Print details of factorization

        Write (nout,*)
        Flush (nout)

!       ifail: behaviour on error exit
!              =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
        ifail = 0
        If (uplo=='U') Then
          Call x04cef(n,n,0,kd,ab,ldab,'Cholesky factor U',ifail)
        Else If (uplo=='L') Then
          Call x04cef(n,n,kd,0,ab,ldab,'Cholesky factor L',ifail)
        End If

      Else
        Write (nout,99998) 'The leading minor of order ', info,                &
          ' is not positive definite'
      End If

99999 Format ((3X,7F11.4))
99998 Format (1X,A,I3,A)
    End Program f07hafe


f07hbfe.f90

    Program f07hbfe

!     F07HBF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: dpbsvx, nag_wp, x04caf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
      Character (1), Parameter         :: uplo = 'U'
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: rcond
      Integer                          :: i, ifail, info, j, kd, ldab, ldafb,  &
                                          ldb, ldx, n, nrhs
      Character (1)                    :: equed
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: ab(:,:), afb(:,:), b(:,:), berr(:),  &
                                          ferr(:), s(:), work(:), x(:,:)
      Integer, Allocatable             :: iwork(:)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: max, min
!     .. Executable Statements ..
      Write (nout,*) 'F07HBF Example Program Results'
      Write (nout,*)
      Flush (nout)
!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) n, kd, nrhs
      ldb = n
      ldx = n
      ldab = kd + 1
      ldafb = kd + 1
      Allocate (ab(ldab,n),afb(ldafb,n),b(ldb,nrhs),berr(nrhs),ferr(nrhs),     &
        s(n),work(3*n),x(ldx,nrhs),iwork(n))

!     Read the upper or lower triangular part of the band matrix A
!     from data file

      If (uplo=='U') Then
        Read (nin,*)((ab(kd+1+i-j,j),j=i,min(n,i+kd)),i=1,n)
      Else If (uplo=='L') Then
        Read (nin,*)((ab(1+i-j,j),j=max(1,i-kd),i),i=1,n)
      End If

!     Read B from data file

      Read (nin,*)(b(i,1:nrhs),i=1,n)

!     Solve the equations AX = B for X
!     The NAG name equivalent of dpbsvx is f07hbf
      Call dpbsvx('Equilibration',uplo,n,kd,nrhs,ab,ldab,afb,ldafb,equed,s,b,  &
        ldb,x,ldx,rcond,ferr,berr,work,iwork,info)

      If ((info==0) .Or. (info==n+1)) Then

!       Print solution, error bounds, condition number and the form
!       of equilibration

!       ifail: behaviour on error exit
!              =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
        ifail = 0
        Call x04caf('General',' ',n,nrhs,x,ldx,'Solution(s)',ifail)

        Write (nout,*)
        Write (nout,*) 'Backward errors (machine-dependent)'
        Write (nout,99999) berr(1:nrhs)
        Write (nout,*)
        Write (nout,*) 'Estimated forward error bounds (machine-dependent)'
        Write (nout,99999) ferr(1:nrhs)
        Write (nout,*)
        Write (nout,*) 'Estimate of reciprocal condition number'
        Write (nout,99999) rcond
        Write (nout,*)
        If (equed=='N') Then
          Write (nout,*) 'A has not been equilibrated'
        Else If (equed=='Y') Then
          Write (nout,*)                                                       &
            'A has been row and column scaled as diag(S)*A*diag(S)'
        End If

        If (info==n+1) Then
          Write (nout,*)
          Write (nout,*) 'The matrix A is singular to working precision'
        End If
      Else
        Write (nout,99998) 'The leading minor of order ', info,                &
          ' is not positive definite'
      End If

99999 Format ((3X,1P,7E11.1))
99998 Format (1X,A,I3,A)
    End Program f07hbfe


f07hdfe.f90

    Program f07hdfe

!     F07HDF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: dpbtrf, nag_wp, x04cef
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Integer                          :: i, ifail, info, j, kd, ldab, n
      Character (1)                    :: uplo
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: ab(:,:)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: max, min
!     .. Executable Statements ..
      Write (nout,*) 'F07HDF Example Program Results'
!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) n, kd
      ldab = kd + 1
      Allocate (ab(ldab,n))

!     Read A from data file

      Read (nin,*) uplo
      If (uplo=='U') Then
        Do i = 1, n
          Read (nin,*)(ab(kd+1+i-j,j),j=i,min(n,i+kd))
        End Do
      Else If (uplo=='L') Then
        Do i = 1, n
          Read (nin,*)(ab(1+i-j,j),j=max(1,i-kd),i)
        End Do
      End If

!     Factorize A
!     The NAG name equivalent of dpbtrf is f07hdf
      Call dpbtrf(uplo,n,kd,ab,ldab,info)

      Write (nout,*)
      Flush (nout)
      If (info==0) Then

!       Print factor

!       ifail: behaviour on error exit
!              =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
        ifail = 0

        If (uplo=='U') Then

          Call x04cef(n,n,0,kd,ab,ldab,'Factor',ifail)

        Else If (uplo=='L') Then

          Call x04cef(n,n,kd,0,ab,ldab,'Factor',ifail)

        End If

      Else
        Write (nout,*) 'A is not positive definite'
      End If

    End Program f07hdfe


f07hefe.f90

    Program f07hefe

!     F07HEF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: dpbtrf, dpbtrs, nag_wp, x04caf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Integer                          :: i, ifail, info, j, kd, ldab, ldb, n, &
                                          nrhs
      Character (1)                    :: uplo
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: ab(:,:), b(:,:)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: max, min
!     .. Executable Statements ..
      Write (nout,*) 'F07HEF Example Program Results'
!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) n, kd, nrhs
      ldab = kd + 1
      ldb = n
      Allocate (ab(ldab,n),b(ldb,nrhs))

!     Read A and B from data file

      Read (nin,*) uplo
      If (uplo=='U') Then
        Do i = 1, n
          Read (nin,*)(ab(kd+1+i-j,j),j=i,min(n,i+kd))
        End Do
      Else If (uplo=='L') Then
        Do i = 1, n
          Read (nin,*)(ab(1+i-j,j),j=max(1,i-kd),i)
        End Do
      End If
      Read (nin,*)(b(i,1:nrhs),i=1,n)

!     Factorize A
!     The NAG name equivalent of dpbtrf is f07hdf
      Call dpbtrf(uplo,n,kd,ab,ldab,info)

      Write (nout,*)
      Flush (nout)
      If (info==0) Then

!       Compute solution
!       The NAG name equivalent of dpbtrs is f07hef
        Call dpbtrs(uplo,n,kd,nrhs,ab,ldab,b,ldb,info)

!       Print solution

!       ifail: behaviour on error exit
!              =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
        ifail = 0
        Call x04caf('General',' ',n,nrhs,b,ldb,'Solution(s)',ifail)

      Else
        Write (nout,*) 'A is not positive definite'
      End If

    End Program f07hefe


f07hffe.f90

    Program f07hffe

!     F07HFF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: dpbequ, dscal, f06fcf, nag_wp, x02ajf, x02amf,    &
                             x02bhf, x04cef
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Real (Kind=nag_wp), Parameter    :: one = 1.0_nag_wp
      Real (Kind=nag_wp), Parameter    :: thresh = 0.1_nag_wp
      Integer, Parameter               :: nin = 5, nout = 6
      Character (1), Parameter         :: uplo = 'U'
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: amax, big, scond, small
      Integer                          :: i, i0, i1, ifail, ilen, info, j, kd, &
                                          ldab, n
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: ab(:,:), s(:)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: max, min, real
!     .. Executable Statements ..
      Write (nout,*) 'F07HFF Example Program Results'
      Write (nout,*)
      Flush (nout)
!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) n, kd
      ldab = kd + 1
      Allocate (ab(ldab,n),s(n))

!     Read the upper or lower triangular part of the band matrix A
!     from data file

      If (uplo=='U') Then
        Do i = 1, n
          Read (nin,*)(ab(kd+1+i-j,j),j=i,min(n,i+kd))
        End Do
      Else If (uplo=='L') Then
        Do i = 1, n
          Read (nin,*)(ab(1+i-j,j),j=max(1,i-kd),i)
        End Do
      End If

!     Print the matrix A

!     ifail: behaviour on error exit
!             =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
      ifail = 0
      If (uplo=='U') Then
        Call x04cef(n,n,0,kd,ab,ldab,'Matrix A',ifail)
      Else If (uplo=='L') Then
        Call x04cef(n,n,kd,0,ab,ldab,'Matrix A',ifail)
      End If

      Write (nout,*)

!     Compute diagonal scaling factors
!     The NAG name equivalent of dpbequ is f07hff
      Call dpbequ(uplo,n,kd,ab,ldab,s,scond,amax,info)

      If (info>0) Then
        Write (nout,99999) 'Diagonal element', info, ' of A is non positive'
      Else

!       Print SCOND, AMAX and the scale factors

        Write (nout,99998) 'SCOND =', scond, ', AMAX =', amax
        Write (nout,*)
        Write (nout,*) 'Diagonal scaling factors'
        Write (nout,99997) s(1:n)
        Write (nout,*)
        Flush (nout)

!       Compute values close to underflow and overflow

        small = x02amf()/(x02ajf()*real(x02bhf(),kind=nag_wp))
        big = one/small
        If ((scond<thresh) .Or. (amax<small) .Or. (amax>big)) Then

!         Scale A
          If (uplo=='U') Then

!           The NAG name equivalent of dscal is f06edf
            Do j = 1, n
              i0 = max(1,j-kd)
              i1 = 1 + i0 - (j-kd)
              ilen = j - i0 + 1
              Call dscal(ilen,s(j),ab(i1,j),1)
              Call f06fcf(ilen,s(i0),1,ab(i1,j),1)
            End Do

          Else If (uplo=='L') Then
            Do j = 1, n
              i1 = 1
              ilen = min(n,j+kd) - j + 1
              Call dscal(ilen,s(j),ab(i1,j),1)
              Call f06fcf(ilen,s(j),1,ab(i1,j),1)
            End Do
          End If

!         Print the scaled matrix

          ifail = 0
          If (uplo=='U') Then
            Call x04cef(n,n,0,kd,ab,ldab,'Scaled matrix',ifail)
          Else If (uplo=='L') Then
            Call x04cef(n,n,kd,0,ab,ldab,'Scaled matrix',ifail)
          End If
        End If
      End If

99999 Format (1X,A,I4,A)
99998 Format (1X,2(A,1P,E8.1))
99997 Format ((1X,1P,7E11.1))
    End Program f07hffe


f07hgfe.f90

    Program f07hgfe

!     F07HGF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: dlansb => f06ref, dpbcon, dpbtrf, nag_wp, x02ajf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: anorm, rcond
      Integer                          :: i, info, j, kd, ldab, n
      Character (1)                    :: uplo
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: ab(:,:), work(:)
      Integer, Allocatable             :: iwork(:)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: max, min
!     .. Executable Statements ..
      Write (nout,*) 'F07HGF Example Program Results'
!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) n, kd
      ldab = kd + 1
      Allocate (ab(ldab,n),work(3*n),iwork(n))

!     Read A from data file

      Read (nin,*) uplo
      If (uplo=='U') Then
        Do i = 1, n
          Read (nin,*)(ab(kd+1+i-j,j),j=i,min(n,i+kd))
        End Do
      Else If (uplo=='L') Then
        Do i = 1, n
          Read (nin,*)(ab(1+i-j,j),j=max(1,i-kd),i)
        End Do
      End If

!     Compute norm of A

!     f06ref is the NAG name equivalent of the LAPACK auxiliary dlansb
      anorm = dlansb('1-norm',uplo,n,kd,ab,ldab,work)

!     Factorize A
!     The NAG name equivalent of dpbtrf is f07hdf
      Call dpbtrf(uplo,n,kd,ab,ldab,info)

      Write (nout,*)
      If (info==0) Then

!       Estimate condition number
!       The NAG name equivalent of dpbcon is f07hgf
        Call dpbcon(uplo,n,kd,ab,ldab,anorm,rcond,work,iwork,info)

        If (rcond>=x02ajf()) Then
          Write (nout,99999) 'Estimate of condition number =',                 &
            1.0_nag_wp/rcond
        Else
          Write (nout,*) 'A is singular to working precision'
        End If
      Else
        Write (nout,*) 'A is not positive definite'
      End If

99999 Format (1X,A,1P,E10.2)
    End Program f07hgfe


f07hhfe.f90

    Program f07hhfe

!     F07HHF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: dpbrfs, dpbtrf, dpbtrs, nag_wp, x04caf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Real (Kind=nag_wp), Parameter    :: zero = 0.0E0_nag_wp
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Integer                          :: i, ifail, info, j, kd, ldab, ldafb,  &
                                          ldb, ldx, n, nrhs
      Character (1)                    :: uplo
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: ab(:,:), afb(:,:), b(:,:), berr(:),  &
                                          ferr(:), work(:), x(:,:)
      Integer, Allocatable             :: iwork(:)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: max, min
!     .. Executable Statements ..
      Write (nout,*) 'F07HHF Example Program Results'
!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) n, kd, nrhs
      ldab = kd + 1
      ldafb = kd + 1
      ldb = n
      ldx = n
      Allocate (ab(ldab,n),afb(ldafb,n),b(ldb,nrhs),berr(nrhs),ferr(nrhs),     &
        work(3*n),x(ldx,n),iwork(n))

!     Set A to zero to avoid referencing uninitialized elements

      ab(1:kd+1,1:n) = zero

!     Read A and B from data file, and copy A to AFB and B to X

      Read (nin,*) uplo
      If (uplo=='U') Then
        Do i = 1, n
          Read (nin,*)(ab(kd+1+i-j,j),j=i,min(n,i+kd))
        End Do
      Else If (uplo=='L') Then
        Do i = 1, n
          Read (nin,*)(ab(1+i-j,j),j=max(1,i-kd),i)
        End Do
      End If
      Read (nin,*)(b(i,1:nrhs),i=1,n)

      afb(1:kd+1,1:n) = ab(1:kd+1,1:n)
      x(1:n,1:nrhs) = b(1:n,1:nrhs)

!     Factorize A in the array AFB
!     The NAG name equivalent of dpbtrf is f07hdf
      Call dpbtrf(uplo,n,kd,afb,ldafb,info)

      Write (nout,*)
      Flush (nout)
      If (info==0) Then

!       Compute solution in the array X
!       The NAG name equivalent of dpbtrs is f07hef
        Call dpbtrs(uplo,n,kd,nrhs,afb,ldafb,x,ldx,info)

!       Improve solution, and compute backward errors and
!       estimated bounds on the forward errors

!       The NAG name equivalent of dpbrfs is f07hhf
        Call dpbrfs(uplo,n,kd,nrhs,ab,ldab,afb,ldafb,b,ldb,x,ldx,ferr,berr,    &
          work,iwork,info)

!       Print solution

!       ifail: behaviour on error exit
!              =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
        ifail = 0
        Call x04caf('General',' ',n,nrhs,x,ldx,'Solution(s)',ifail)

        Write (nout,*)
        Write (nout,*) 'Backward errors (machine-dependent)'
        Write (nout,99999) berr(1:nrhs)
        Write (nout,*) 'Estimated forward error bounds (machine-dependent)'
        Write (nout,99999) ferr(1:nrhs)
      Else
        Write (nout,*) 'A is not positive definite'
      End If

99999 Format ((3X,1P,7E11.1))
    End Program f07hhfe


f07hnfe.f90

    Program f07hnfe

!     F07HNF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: nag_wp, x04dff, zpbsv
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
      Character (1), Parameter         :: uplo = 'U'
!     .. Local Scalars ..
      Integer                          :: i, ifail, info, j, kd, ldab, n
!     .. Local Arrays ..
      Complex (Kind=nag_wp), Allocatable :: ab(:,:), b(:)
      Character (1)                    :: clabs(1), rlabs(1)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: max, min
!     .. Executable Statements ..
      Write (nout,*) 'F07HNF Example Program Results'
      Write (nout,*)
!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) n, kd
      ldab = kd + 1
      Allocate (ab(ldab,n),b(n))

!     Read the upper or lower triangular part of the band matrix A
!     from data file

      If (uplo=='U') Then
        Read (nin,*)((ab(kd+1+i-j,j),j=i,min(n,i+kd)),i=1,n)
      Else If (uplo=='L') Then
        Read (nin,*)((ab(1+i-j,j),j=max(1,i-kd),i),i=1,n)
      End If

!     Read b from data file

      Read (nin,*) b(1:n)

!     Solve the equations Ax = b for x
!     The NAG name equivalent of zpbsv is f07hnf
      Call zpbsv(uplo,n,kd,1,ab,ldab,b,n,info)

      If (info==0) Then

!       Print solution

        Write (nout,*) 'Solution'
        Write (nout,99999) b(1:n)

!       Print details of factorization

        Write (nout,*)
        Flush (nout)

!       ifail: behaviour on error exit
!              =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
        ifail = 0
        If (uplo=='U') Then
          Call x04dff(n,n,0,kd,ab,ldab,'Bracketed','F7.4','Cholesky factor U', &
            'Integer',rlabs,'Integer',clabs,80,0,ifail)
        Else If (uplo=='L') Then
          Call x04dff(n,n,kd,0,ab,ldab,'Bracketed','F7.4','Cholesky factor L', &
            'Integer',rlabs,'Integer',clabs,80,0,ifail)
        End If

      Else
        Write (nout,99998) 'The leading minor of order ', info,                &
          ' is not positive definite'
      End If

99999 Format ((3X,4(' (',F7.4,',',F7.4,')',:)))
99998 Format (1X,A,I3,A)
    End Program f07hnfe


f07hpfe.f90

    Program f07hpfe

!     F07HPF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: nag_wp, x04dbf, zpbsvx
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
      Character (1), Parameter         :: uplo = 'U'
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: rcond
      Integer                          :: i, ifail, info, j, kd, ldab, ldafb,  &
                                          ldb, ldx, n, nrhs
      Character (1)                    :: equed
!     .. Local Arrays ..
      Complex (Kind=nag_wp), Allocatable :: ab(:,:), afb(:,:), b(:,:),         &
                                          work(:), x(:,:)
      Real (Kind=nag_wp), Allocatable  :: berr(:), ferr(:), rwork(:), s(:)
      Character (1)                    :: clabs(1), rlabs(1)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: max, min
!     .. Executable Statements ..
      Write (nout,*) 'F07HPF Example Program Results'
      Write (nout,*)
      Flush (nout)
!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) n, kd, nrhs
      ldab = kd + 1
      ldafb = kd + 1
      ldb = n
      ldx = n
      Allocate (ab(ldab,n),afb(ldafb,n),b(ldb,nrhs),work(3*n),x(ldx,nrhs),     &
        berr(nrhs),ferr(nrhs),rwork(n),s(n))

!     Read the upper or lower triangular part of the band matrix A
!     from data file

      If (uplo=='U') Then
        Read (nin,*)((ab(kd+1+i-j,j),j=i,min(n,i+kd)),i=1,n)
      Else If (uplo=='L') Then
        Read (nin,*)((ab(1+i-j,j),j=max(1,i-kd),i),i=1,n)
      End If

!     Read B from data file

      Read (nin,*)(b(i,1:nrhs),i=1,n)

!     Solve the equations AX = B for X
!     The NAG name equivalent of zpbsvx is f07hpf
      Call zpbsvx('Equilibration',uplo,n,kd,nrhs,ab,ldab,afb,ldafb,equed,s,b,  &
        ldb,x,ldx,rcond,ferr,berr,work,rwork,info)

      If ((info==0) .Or. (info==n+1)) Then

!       Print solution, error bounds, condition number and the form
!       of equilibration

!       ifail: behaviour on error exit
!              =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
        ifail = 0
        Call x04dbf('General',' ',n,nrhs,x,ldx,'Bracketed','F7.4',             &
          'Solution(s)','Integer',rlabs,'Integer',clabs,80,0,ifail)

        Write (nout,*)
        Write (nout,*) 'Backward errors (machine-dependent)'
        Write (nout,99999) berr(1:nrhs)
        Write (nout,*)
        Write (nout,*) 'Estimated forward error bounds (machine-dependent)'
        Write (nout,99999) ferr(1:nrhs)
        Write (nout,*)
        Write (nout,*) 'Estimate of reciprocal condition number'
        Write (nout,99999) rcond
        Write (nout,*)
        If (equed=='N') Then
          Write (nout,*) 'A has not been equilibrated'
        Else If (equed=='Y') Then
          Write (nout,*)                                                       &
            'A has been row and column scaled as diag(S)*A*diag(S)'
        End If

        If (info==n+1) Then
          Write (nout,*)
          Write (nout,*) 'The matrix A is singular to working precision'
        End If
      Else
        Write (nout,99998) 'The leading minor of order ', info,                &
          ' is not positive definite'
      End If

99999 Format ((3X,1P,7E11.1))
99998 Format (1X,A,I3,A)
    End Program f07hpfe


f07hrfe.f90

    Program f07hrfe

!     F07HRF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: nag_wp, x04dff, zpbtrf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Integer                          :: i, ifail, info, j, kd, ldab, n
      Character (1)                    :: uplo
!     .. Local Arrays ..
      Complex (Kind=nag_wp), Allocatable :: ab(:,:)
      Character (1)                    :: clabs(1), rlabs(1)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: max, min
!     .. Executable Statements ..
      Write (nout,*) 'F07HRF Example Program Results'
!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) n, kd
      ldab = kd + 1
      Allocate (ab(ldab,n))

!     Read A from data file

      Read (nin,*) uplo
      If (uplo=='U') Then
        Do i = 1, n
          Read (nin,*)(ab(kd+1+i-j,j),j=i,min(n,i+kd))
        End Do
      Else If (uplo=='L') Then
        Do i = 1, n
          Read (nin,*)(ab(1+i-j,j),j=max(1,i-kd),i)
        End Do
      End If

!     Factorize A
!     The NAG name equivalent of zpbtrf is f07hrf
      Call zpbtrf(uplo,n,kd,ab,ldab,info)

      Write (nout,*)
      Flush (nout)
      If (info==0) Then

!       Print factor

!       ifail: behaviour on error exit
!              =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
        ifail = 0
        If (uplo=='U') Then

          Call x04dff(n,n,0,kd,ab,ldab,'Bracketed','F7.4','Factor','Integer',  &
            rlabs,'Integer',clabs,80,0,ifail)

        Else If (uplo=='L') Then

          Call x04dff(n,n,kd,0,ab,ldab,'Bracketed','F7.4','Factor','Integer',  &
            rlabs,'Integer',clabs,80,0,ifail)

        End If

      Else
        Write (nout,*) 'A is not positive definite'
      End If

    End Program f07hrfe


f07hsfe.f90

    Program f07hsfe

!     F07HSF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: nag_wp, x04dbf, zpbtrf, zpbtrs
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Integer                          :: i, ifail, info, j, kd, ldab, ldb, n, &
                                          nrhs
      Character (1)                    :: uplo
!     .. Local Arrays ..
      Complex (Kind=nag_wp), Allocatable :: ab(:,:), b(:,:)
      Character (1)                    :: clabs(1), rlabs(1)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: max, min
!     .. Executable Statements ..
      Write (nout,*) 'F07HSF Example Program Results'
!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) n, kd, nrhs
      ldab = kd + 1
      ldb = n
      Allocate (ab(ldab,n),b(ldb,nrhs))

!     Read A and B from data file

      Read (nin,*) uplo
      If (uplo=='U') Then
        Do i = 1, n
          Read (nin,*)(ab(kd+1+i-j,j),j=i,min(n,i+kd))
        End Do
      Else If (uplo=='L') Then
        Do i = 1, n
          Read (nin,*)(ab(1+i-j,j),j=max(1,i-kd),i)
        End Do
      End If
      Read (nin,*)(b(i,1:nrhs),i=1,n)

!     Factorize A
!     The NAG name equivalent of zpbtrf is f07hrf
      Call zpbtrf(uplo,n,kd,ab,ldab,info)

      Write (nout,*)
      Flush (nout)
      If (info==0) Then

!       Compute solution
!       The NAG name equivalent of zpbtrs is f07hsf
        Call zpbtrs(uplo,n,kd,nrhs,ab,ldab,b,ldb,info)

!       Print solution

!       ifail: behaviour on error exit
!              =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
        ifail = 0
        Call x04dbf('General',' ',n,nrhs,b,ldb,'Bracketed','F7.4',             &
          'Solution(s)','Integer',rlabs,'Integer',clabs,80,0,ifail)

      Else
        Write (nout,*) 'A is not positive definite'
      End If

    End Program f07hsfe


f07htfe.f90

    Program f07htfe

!     F07HTF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: f06kcf, nag_wp, x02ajf, x02amf, x02bhf, x04dff,   &
                             zdscal, zpbequ
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Real (Kind=nag_wp), Parameter    :: one = 1.0_nag_wp
      Real (Kind=nag_wp), Parameter    :: thresh = 0.1_nag_wp
      Integer, Parameter               :: nin = 5, nout = 6
      Character (1), Parameter         :: uplo = 'U'
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: amax, big, scond, small
      Integer                          :: i, i0, i1, ifail, ilen, info, j, kd, &
                                          ldab, n
!     .. Local Arrays ..
      Complex (Kind=nag_wp), Allocatable :: ab(:,:)
      Real (Kind=nag_wp), Allocatable  :: s(:)
      Character (1)                    :: clabs(1), rlabs(1)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: max, min, real
!     .. Executable Statements ..
      Write (nout,*) 'F07HTF Example Program Results'
      Write (nout,*)
      Flush (nout)
!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) n, kd
      ldab = kd + 1
      Allocate (ab(ldab,n),s(n))

!     Read the upper or lower triangular part of the band matrix A
!     from data file

      If (uplo=='U') Then
        Do i = 1, n
          Read (nin,*)(ab(kd+1+i-j,j),j=i,min(n,i+kd))
        End Do
      Else If (uplo=='L') Then
        Do i = 1, n
          Read (nin,*)(ab(1+i-j,j),j=max(1,i-kd),i)
        End Do
      End If

!     Print the matrix A

!     ifail: behaviour on error exit
!             =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
      ifail = 0
      If (uplo=='U') Then
        Call x04dff(n,n,0,kd,ab,ldab,'Bracketed','1P,E10.2','Matrix A',        &
          'Integer',rlabs,'Integer',clabs,80,0,ifail)
      Else If (uplo=='L') Then
        Call x04dff(n,n,kd,0,ab,ldab,'Bracketed','1P,E10.2','Matrix A',        &
          'Integer',rlabs,'Integer',clabs,80,0,ifail)
      End If

      Write (nout,*)

!     Compute diagonal scaling factors

!     The NAG name equivalent of zpbequ is f07htf
      Call zpbequ(uplo,n,kd,ab,ldab,s,scond,amax,info)

      If (info>0) Then
        Write (nout,99999) 'Diagonal element', info, ' of A is non positive'
      Else

!       Print SCOND, AMAX and the scale factors

        Write (nout,99998) 'SCOND =', scond, ', AMAX =', amax
        Write (nout,*)
        Write (nout,*) 'Diagonal scaling factors'
        Write (nout,99997) s(1:n)
        Write (nout,*)
        Flush (nout)

!       Compute values close to underflow and overflow

        small = x02amf()/(x02ajf()*real(x02bhf(),kind=nag_wp))
        big = one/small
        If ((scond<thresh) .Or. (amax<small) .Or. (amax>big)) Then

!         Scale A

          If (uplo=='U') Then
!           The NAG name equivalent of zdscal is f06jdf
            Do j = 1, n
              i0 = max(1,j-kd)
              i1 = 1 + i0 - (j-kd)
              ilen = j - i0 + 1
              Call zdscal(ilen,s(j),ab(i1,j),1)
              Call f06kcf(ilen,s(i0),1,ab(i1,j),1)
            End Do

          Else If (uplo=='L') Then
            Do j = 1, n
              i1 = 1
              ilen = min(n,j+kd) - j + 1
              Call zdscal(ilen,s(j),ab(i1,j),1)
              Call f06kcf(ilen,s(j),1,ab(i1,j),1)
            End Do
          End If

!         Print the scaled matrix

          ifail = 0
          If (uplo=='U') Then
            Call x04dff(n,n,0,kd,ab,ldab,'Bracketed','F7.4','Scaled matrix',   &
              'Integer',rlabs,'Integer',clabs,80,0,ifail)
          Else If (uplo=='L') Then
            Call x04dff(n,n,kd,0,ab,ldab,'Bracketed','F7.4','Scaled matrix',   &
              'Integer',rlabs,'Integer',clabs,80,0,ifail)
          End If
        End If
      End If

99999 Format (1X,A,I4,A)
99998 Format (1X,2(A,1P,E8.1))
99997 Format ((1X,1P,7E11.1))
    End Program f07htfe


f07hufe.f90

    Program f07hufe

!     F07HUF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: nag_wp, x02ajf, zlanhb => f06uef, zpbcon, zpbtrf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: anorm, rcond
      Integer                          :: i, info, j, kd, ldab, n
      Character (1)                    :: uplo
!     .. Local Arrays ..
      Complex (Kind=nag_wp), Allocatable :: ab(:,:), work(:)
      Real (Kind=nag_wp), Allocatable  :: rwork(:)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: max, min
!     .. Executable Statements ..
      Write (nout,*) 'F07HUF Example Program Results'
!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) n, kd
      ldab = kd + 1
      Allocate (ab(ldab,n),work(2*n),rwork(n))

!     Read A from data file

      Read (nin,*) uplo
      If (uplo=='U') Then
        Do i = 1, n
          Read (nin,*)(ab(kd+1+i-j,j),j=i,min(n,i+kd))
        End Do
      Else If (uplo=='L') Then
        Do i = 1, n
          Read (nin,*)(ab(1+i-j,j),j=max(1,i-kd),i)
        End Do
      End If

!     Compute norm of A
!     f06uef is the NAG name equivalent of the LAPACK auxiliary zlanhb
      anorm = zlanhb('1-norm',uplo,n,kd,ab,ldab,rwork)

!     Factorize A
!     The NAG name equivalent of zpbtrf is f07hrf
      Call zpbtrf(uplo,n,kd,ab,ldab,info)

      Write (nout,*)
      If (info==0) Then

!       Estimate condition number
!       The NAG name equivalent of zpbcon is f07huf
        Call zpbcon(uplo,n,kd,ab,ldab,anorm,rcond,work,rwork,info)

        If (rcond>=x02ajf()) Then
          Write (nout,99999) 'Estimate of condition number =',                 &
            1.0_nag_wp/rcond
        Else
          Write (nout,*) 'A is singular to working precision'
        End If
      Else
        Write (nout,*) 'A is not positive definite'
      End If

99999 Format (1X,A,1P,E10.2)
    End Program f07hufe


f07hvfe.f90

    Program f07hvfe

!     F07HVF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: nag_wp, x04dbf, zpbrfs, zpbtrf, zpbtrs
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Complex (Kind=nag_wp), Parameter :: zero = (0.0E0_nag_wp,0.0E0_nag_wp)
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Integer                          :: i, ifail, info, j, kd, ldab, ldafb,  &
                                          ldb, ldx, n, nrhs
      Character (1)                    :: uplo
!     .. Local Arrays ..
      Complex (Kind=nag_wp), Allocatable :: ab(:,:), afb(:,:), b(:,:),         &
                                          work(:), x(:,:)
      Real (Kind=nag_wp), Allocatable  :: berr(:), ferr(:), rwork(:)
      Character (1)                    :: clabs(1), rlabs(1)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: max, min
!     .. Executable Statements ..
      Write (nout,*) 'F07HVF Example Program Results'
!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) n, kd, nrhs
      ldab = kd + 1
      ldafb = kd + 1
      ldb = n
      ldx = n
      Allocate (ab(ldab,n),afb(ldafb,n),b(ldb,nrhs),work(2*n),x(ldx,n),        &
        berr(nrhs),ferr(nrhs),rwork(n))

!     Set A to zero to avoid referencing uninitialized elements

      ab(1:kd+1,1:n) = zero

!     Read A and B from data file, and copy A to AFB and B to X

      Read (nin,*) uplo
      If (uplo=='U') Then
        Do i = 1, n
          Read (nin,*)(ab(kd+1+i-j,j),j=i,min(n,i+kd))
        End Do
      Else If (uplo=='L') Then
        Do i = 1, n
          Read (nin,*)(ab(1+i-j,j),j=max(1,i-kd),i)
        End Do
      End If
      Read (nin,*)(b(i,1:nrhs),i=1,n)

      afb(1:kd+1,1:n) = ab(1:kd+1,1:n)
      x(1:n,1:nrhs) = b(1:n,1:nrhs)

!     Factorize A in the array AFB

      Call zpbtrf(uplo,n,kd,afb,ldafb,info)

      Write (nout,*)
      Flush (nout)
      If (info==0) Then

!       Compute solution in the array X

        Call zpbtrs(uplo,n,kd,nrhs,afb,ldafb,x,ldx,info)

!       Improve solution, and compute backward errors and
!       estimated bounds on the forward errors

        Call zpbrfs(uplo,n,kd,nrhs,ab,ldab,afb,ldafb,b,ldb,x,ldx,ferr,berr,    &
          work,rwork,info)

!       Print solution

!       ifail: behaviour on error exit
!              =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
        ifail = 0
        Call x04dbf('General',' ',n,nrhs,x,ldx,'Bracketed','F7.4',             &
          'Solution(s)','Integer',rlabs,'Integer',clabs,80,0,ifail)

        Write (nout,*)
        Write (nout,*) 'Backward errors (machine-dependent)'
        Write (nout,99999) berr(1:nrhs)
        Write (nout,*) 'Estimated forward error bounds (machine-dependent)'
        Write (nout,99999) ferr(1:nrhs)
      Else
        Write (nout,*) 'A is not positive definite'
      End If

99999 Format ((5X,1P,4(E11.1,7X)))
    End Program f07hvfe


f07jafe.f90

    Program f07jafe

!     F07JAF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: dptsv, nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Integer                          :: info, n
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: b(:), d(:), e(:)
!     .. Executable Statements ..
      Write (nout,*) 'F07JAF Example Program Results'
      Write (nout,*)
!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) n

      Allocate (b(n),d(n),e(n-1))

!     Read the lower bidiagonal part of the tridiagonal matrix A and
!     the right hand side b from data file

      Read (nin,*) d(1:n)
      Read (nin,*) e(1:n-1)
      Read (nin,*) b(1:n)

!     Solve the equations Ax = b for x

!     The NAG name equivalent of dptsv is f07jaf
      Call dptsv(n,1,d,e,b,n,info)

      If (info==0) Then

!       Print solution

        Write (nout,*) 'Solution'
        Write (nout,99999) b(1:n)

!       Print details of factorization

        Write (nout,*)
        Write (nout,*) 'Diagonal elements of the diagonal matrix D'
        Write (nout,99999) d(1:n)
        Write (nout,*)
        Write (nout,*) 'Subdiagonal elements of the Cholesky factor L'
        Write (nout,99999) e(1:n-1)

      Else
        Write (nout,99998) 'The leading minor of order ', info,                &
          ' is not positive definite'
      End If

99999 Format (1X,7F11.4)
99998 Format (1X,A,I3,A)
    End Program f07jafe


f07jbfe.f90

    Program f07jbfe

!     F07JBF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: dptsvx, nag_wp, x04caf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: rcond
      Integer                          :: i, ifail, info, ldb, ldx, n, nrhs
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: b(:,:), berr(:), d(:), df(:), e(:),  &
                                          ef(:), ferr(:), work(:), x(:,:)
!     .. Executable Statements ..
      Write (nout,*) 'F07JBF Example Program Results'
      Write (nout,*)
      Flush (nout)
!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) n, nrhs
      ldb = n
      ldx = n
      Allocate (b(ldb,nrhs),berr(nrhs),d(n),df(n),e(n-1),ef(n-1),ferr(nrhs),   &
        work(2*n),x(ldx,nrhs))

!     Read the lower bidiagonal part of the tridiagonal matrix A and
!     the right hand side b from data file

      Read (nin,*) d(1:n)
      Read (nin,*) e(1:n-1)
      Read (nin,*)(b(i,1:nrhs),i=1,n)

!     Solve the equations AX = B for X

!     The NAG name equivalent of dptsvx is f07jbf
      Call dptsvx('Not factored',n,nrhs,d,e,df,ef,b,ldb,x,ldx,rcond,ferr,berr, &
        work,info)

      If ((info==0) .Or. (info==n+1)) Then

!       Print solution, error bounds and condition number

!       ifail: behaviour on error exit
!              =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
        ifail = 0
        Call x04caf('General',' ',n,nrhs,x,ldx,'Solution(s)',ifail)

        Write (nout,*)
        Write (nout,*) 'Backward errors (machine-dependent)'
        Write (nout,99999) berr(1:nrhs)
        Write (nout,*)
        Write (nout,*) 'Estimated forward error bounds (machine-dependent)'
        Write (nout,99999) ferr(1:nrhs)
        Write (nout,*)
        Write (nout,*) 'Estimate of reciprocal condition number'
        Write (nout,99999) rcond

        If (info==n+1) Then
          Write (nout,*)
          Write (nout,*) 'The matrix A is singular to working precision'
        End If
      Else
        Write (nout,99998) 'The leading minor of order ', info,                &
          ' is not positive definite'
      End If

99999 Format (1X,1P,7E11.1)
99998 Format (1X,A,I3,A)
    End Program f07jbfe


f07jdfe.f90

    Program f07jdfe

!     F07JDF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: dpttrf, nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Integer                          :: info, n
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: d(:), e(:)
!     .. Executable Statements ..
      Write (nout,*) 'F07JDF Example Program Results'
      Write (nout,*)
!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) n

      Allocate (d(n),e(n-1))

!     Read the lower bidiagonal part of the tridiagonal matrix A from
!     data file

      Read (nin,*) d(1:n)
      Read (nin,*) e(1:n-1)

!     Factorize the tridiagonal matrix A

!     The NAG name equivalent of dpttrf is f07jdf
      Call dpttrf(n,d,e,info)

      If (info>0) Then
        Write (nout,99999) 'The leading minor of order ', info,                &
          ' is not positive definite'
      End If

!     Print details of the factorization

      Write (nout,*) 'Details of factorization'
      Write (nout,*)
      Write (nout,*) ' The diagonal elements of D'
      Write (nout,99998) d(1:n)
      Write (nout,*)
      Write (nout,*) ' Subdiagonal elements of the Cholesky factor L'
      Write (nout,99998) e(1:n-1)

99999 Format (1X,A,I3,A)
99998 Format (1X,8F9.4)
    End Program f07jdfe


f07jefe.f90

    Program f07jefe

!     F07JEF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: dpttrf, dpttrs, nag_wp, x04caf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Integer                          :: i, ifail, info, ldb, n, nrhs
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: b(:,:), d(:), e(:)
!     .. Executable Statements ..
      Write (nout,*) 'F07JEF Example Program Results'
      Write (nout,*)
      Flush (nout)
!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) n, nrhs
      ldb = n
      Allocate (b(ldb,nrhs),d(n),e(n-1))

!     Read the upper bidiagonal part of the tridiagonal matrix A from
!     data file

      Read (nin,*) e(1:n-1)
      Read (nin,*) d(1:n)

!     Read the right hand matrix B

      Read (nin,*)(b(i,1:nrhs),i=1,n)

!     Factorize the tridiagonal matrix A
!     The NAG name equivalent of dpttrf is f07jdf
      Call dpttrf(n,d,e,info)

      If (info==0) Then

!       Solve the equations AX = B
!       The NAG name equivalent of dpttrs is f07jef
        Call dpttrs(n,nrhs,d,e,b,ldb,info)

!       Print the solution

!       ifail: behaviour on error exit
!              =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
        ifail = 0
        Call x04caf('General',' ',n,nrhs,b,ldb,'Solution(s)',ifail)

      Else
        Write (nout,99999) 'The leading minor of order ', info,                &
          ' is not positive definite'
      End If

99999 Format (1X,A,I3,A)
    End Program f07jefe


f07jgfe.f90

    Program f07jgfe

!     F07JGF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: dptcon, dpttrf, f06rpf, nag_wp, x02ajf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: anorm, rcond
      Integer                          :: info, n
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: d(:), e(:), work(:)
!     .. Executable Statements ..
      Write (nout,*) 'F07JGF Example Program Results'
      Write (nout,*)
!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) n

      Allocate (d(n),e(n-1),work(n))

!     Read the lower bidiagonal part of the tridiagonal matrix A from
!     data file

      Read (nin,*) d(1:n)
      Read (nin,*) e(1:n-1)

!     Compute the 1-norm of A
      anorm = f06rpf('1-norm',n,d,e)

!     Factorize the tridiagonal matrix A
!     The NAG name equivalent of dpttrf is f07jdf
      Call dpttrf(n,d,e,info)

      If (info==0) Then

!       Estimate the condition number of A
!       The NAG name equivalent of dptcon is f07jgf
        Call dptcon(n,d,e,anorm,rcond,work,info)

!       Print the estimated condition number

        If (rcond>=x02ajf()) Then
          Write (nout,99999) 'Estimate of condition number = ',                &
            1.0_nag_wp/rcond
        Else
          Write (nout,99999) 'A is singular to working precision. RCOND = ',   &
            rcond
        End If

      Else
        Write (nout,99998) 'The leading minor of order ', info,                &
          ' is not positive definite'
      End If

99999 Format (1X,A,1P,E10.2)
99998 Format (1X,A,I3,A)
    End Program f07jgfe


f07jhfe.f90

    Program f07jhfe

!     F07JHF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: dptrfs, dpttrf, dpttrs, nag_wp, x04caf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Integer                          :: i, ifail, info, ldb, ldx, n, nrhs
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: b(:,:), berr(:), d(:), df(:), e(:),  &
                                          ef(:), ferr(:), work(:), x(:,:)
!     .. Executable Statements ..
      Write (nout,*) 'F07JHF Example Program Results'
      Write (nout,*)
      Flush (nout)
!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) n, nrhs
      ldb = n
      ldx = n
      Allocate (b(ldb,nrhs),berr(nrhs),d(n),df(n),e(n-1),ef(n-1),ferr(nrhs),   &
        work(2*n),x(ldx,nrhs))

!     Read the lower bidiagonal part of the tridiagonal matrix A from
!     data file

      Read (nin,*) d(1:n)
      Read (nin,*) e(1:n-1)

!     Read the right hand matrix B

      Read (nin,*)(b(i,1:nrhs),i=1,n)

!     Copy A into DF and EF, and copy B into X

      df(1:n) = d(1:n)
      ef(1:n-1) = e(1:n-1)
      x(1:n,1:nrhs) = b(1:n,1:nrhs)

!     Factorize the copy of the tridiagonal matrix A
!     The NAG name equivalent of dpttrf is f07jdf
      Call dpttrf(n,df,ef,info)

      If (info==0) Then

!       Solve the equations AX = B
!       The NAG name equivalent of dpttrs is f07jef
        Call dpttrs(n,nrhs,df,ef,x,ldx,info)

!       Improve the solution and compute error estimates
!       The NAG name equivalent of dptrfs is f07jhf
        Call dptrfs(n,nrhs,d,e,df,ef,b,ldb,x,ldx,ferr,berr,work,info)

!       Print the solution and the forward and backward error
!       estimates

!       ifail: behaviour on error exit
!              =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
        ifail = 0
        Call x04caf('General',' ',n,nrhs,x,ldx,'Solution(s)',ifail)

        Write (nout,*)
        Write (nout,*) 'Backward errors (machine-dependent)'
        Write (nout,99999) berr(1:nrhs)
        Write (nout,*)
        Write (nout,*) 'Estimated forward error bounds (machine-dependent)'
        Write (nout,99999) ferr(1:nrhs)
      Else
        Write (nout,99998) 'The leading minor of order ', info,                &
          ' is not positive definite'
      End If

99999 Format ((3X,1P,7E11.1))
99998 Format (1X,A,I3,A)
    End Program f07jhfe


f07jnfe.f90

    Program f07jnfe

!     F07JNF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: nag_wp, zptsv
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Integer                          :: info, n
!     .. Local Arrays ..
      Complex (Kind=nag_wp), Allocatable :: b(:), e(:)
      Real (Kind=nag_wp), Allocatable  :: d(:)
!     .. Executable Statements ..
      Write (nout,*) 'F07JNF Example Program Results'
      Write (nout,*)
!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) n

      Allocate (b(n),e(n-1),d(n))

!     Read the lower bidiagonal part of the tridiagonal matrix A and
!     the right hand side b from data file

      Read (nin,*) d(1:n)
      Read (nin,*) e(1:n-1)
      Read (nin,*) b(1:n)

!     Solve the equations Ax = b for x
!     The NAG name equivalent of zptsv is f07jnf
      Call zptsv(n,1,d,e,b,n,info)

      If (info==0) Then

!       Print solution

        Write (nout,*) 'Solution'
        Write (nout,99999) b(1:n)

!       Print details of factorization

        Write (nout,*)
        Write (nout,*) 'Diagonal elements of the diagonal matrix D'
        Write (nout,99998) d(1:n)
        Write (nout,*)
        Write (nout,*) 'Subdiagonal elements of the Cholesky factor L'
        Write (nout,99999) e(1:n-1)

      Else
        Write (nout,99997) 'The leading minor of order ', info,                &
          ' is not positive definite'
      End If

99999 Format (4(' (',F8.4,',',F8.4,')',:))
99998 Format ((2X,F7.4,3(11X,F7.4)))
99997 Format (1X,A,I3,A)
    End Program f07jnfe


f07jpfe.f90

    Program f07jpfe

!     F07JPF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: nag_wp, x04dbf, zptsvx
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: rcond
      Integer                          :: i, ifail, info, ldb, ldx, n, nrhs
!     .. Local Arrays ..
      Complex (Kind=nag_wp), Allocatable :: b(:,:), e(:), ef(:), work(:),      &
                                          x(:,:)
      Real (Kind=nag_wp), Allocatable  :: berr(:), d(:), df(:), ferr(:),       &
                                          rwork(:)
      Character (1)                    :: clabs(1), rlabs(1)
!     .. Executable Statements ..
      Write (nout,*) 'F07JPF Example Program Results'
      Write (nout,*)
      Flush (nout)
!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) n, nrhs
      ldb = n
      ldx = n
      Allocate (b(ldb,nrhs),e(n-1),ef(n-1),work(n),x(ldx,nrhs),berr(nrhs),     &
        d(n),df(n),ferr(nrhs),rwork(n))

!     Read the lower bidiagonal part of the tridiagonal matrix A and
!     the right hand side b from data file

      Read (nin,*) d(1:n)
      Read (nin,*) e(1:n-1)
      Read (nin,*)(b(i,1:nrhs),i=1,n)

!     Solve the equations AX = B for X
!     The NAG name equivalent of zptsvx is f07jpf
      Call zptsvx('Not factored',n,nrhs,d,e,df,ef,b,ldb,x,ldx,rcond,ferr,berr, &
        work,rwork,info)

      If ((info==0) .Or. (info==n+1)) Then

!       Print solution, error bounds and condition number

!       ifail: behaviour on error exit
!              =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
        ifail = 0
        Call x04dbf('General',' ',n,nrhs,x,ldx,'Bracketed','F7.4',             &
          'Solution(s)','Integer',rlabs,'Integer',clabs,80,0,ifail)

        Write (nout,*)
        Write (nout,*) 'Backward errors (machine-dependent)'
        Write (nout,99999) berr(1:nrhs)
        Write (nout,*)
        Write (nout,*) 'Estimated forward error bounds (machine-dependent)'
        Write (nout,99999) ferr(1:nrhs)
        Write (nout,*)
        Write (nout,*) 'Estimate of reciprocal condition number'
        Write (nout,99999) rcond

        If (info==n+1) Then
          Write (nout,*)
          Write (nout,*) 'The matrix A is singular to working precision'
        End If
      Else
        Write (nout,99998) 'The leading minor of order ', info,                &
          ' is not positive definite'
      End If

99999 Format (1X,1P,7E11.1)
99998 Format (1X,A,I3,A)
    End Program f07jpfe


f07jrfe.f90

    Program f07jrfe

!     F07JRF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: nag_wp, zpttrf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Integer                          :: info, n
!     .. Local Arrays ..
      Complex (Kind=nag_wp), Allocatable :: e(:)
      Real (Kind=nag_wp), Allocatable  :: d(:)
!     .. Executable Statements ..
      Write (nout,*) 'F07JRF Example Program Results'
      Write (nout,*)
!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) n

      Allocate (e(n-1),d(n))

!     Read the lower bidiagonal part of the tridiagonal matrix A from
!     data file

      Read (nin,*) d(1:n)
      Read (nin,*) e(1:n-1)

!     Factorize the tridiagonal matrix A
!     The NAG name equivalent of zpttrf is f07jrf
      Call zpttrf(n,d,e,info)

      If (info>0) Then
        Write (nout,99999) 'The leading minor of order ', info,                &
          ' is not positive definite'
      End If

!     Print details of the factorization

      Write (nout,*) 'Details of factorization'
      Write (nout,*)
      Write (nout,*) ' The diagonal elements of D'
      Write (nout,99998) d(1:n)
      Write (nout,*)
      Write (nout,*) ' Subdiagonal elements of the Cholesky factor L'
      Write (nout,99998) e(1:n-1)

99999 Format (1X,A,I3,A)
99998 Format (1X,8F9.4)
    End Program f07jrfe


f07jsfe.f90

    Program f07jsfe

!     F07JSF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: nag_wp, x04dbf, zpttrf, zpttrs
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
      Character (1), Parameter         :: uplo = 'U'
!     .. Local Scalars ..
      Integer                          :: i, ifail, info, ldb, n, nrhs
!     .. Local Arrays ..
      Complex (Kind=nag_wp), Allocatable :: b(:,:), e(:)
      Real (Kind=nag_wp), Allocatable  :: d(:)
      Character (1)                    :: clabs(1), rlabs(1)
!     .. Executable Statements ..
      Write (nout,*) 'F07JSF Example Program Results'
      Write (nout,*)
      Flush (nout)
!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) n, nrhs
      ldb = n
      Allocate (b(ldb,nrhs),e(n-1),d(n))

!     Read the upper bidiagonal part of the tridiagonal matrix A from
!     data file

      Read (nin,*) e(1:n-1)
      Read (nin,*) d(1:n)

!     Read the right hand matrix B

      Read (nin,*)(b(i,1:nrhs),i=1,n)

!     Factorize the tridiagonal matrix A
!     The NAG name equivalent of zpttrf is f07jrf
      Call zpttrf(n,d,e,info)

      If (info==0) Then

!       Solve the equations AX = B
!       The NAG name equivalent of zpttrs is f07jsf
        Call zpttrs(uplo,n,nrhs,d,e,b,ldb,info)

!       Print the solution

!       ifail: behaviour on error exit
!              =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
        ifail = 0
        Call x04dbf('General',' ',n,nrhs,b,ldb,'Bracketed',' ','Solution(s)',  &
          'Integer',rlabs,'Integer',clabs,80,0,ifail)

      Else
        Write (nout,99999) 'The leading minor of order ', info,                &
          ' is not positive definite'
      End If

99999 Format (1X,A,I3,A)
    End Program f07jsfe


f07jufe.f90

    Program f07jufe

!     F07JUF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: f06upf, nag_wp, x02ajf, zptcon, zpttrf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: anorm, rcond
      Integer                          :: info, n
!     .. Local Arrays ..
      Complex (Kind=nag_wp), Allocatable :: e(:)
      Real (Kind=nag_wp), Allocatable  :: d(:), rwork(:)
!     .. Executable Statements ..
      Write (nout,*) 'F07JUF Example Program Results'
      Write (nout,*)
!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) n

      Allocate (e(n-1),d(n),rwork(n))

!     Read the lower bidiagonal part of the tridiagonal matrix A from
!     data file

      Read (nin,*) d(1:n)
      Read (nin,*) e(1:n-1)

!     Compute the 1-norm of A
      anorm = f06upf('1-norm',n,d,e)

!     Factorize the tridiagonal matrix A
!     The NAG name equivalent of zpttrf is f07jrf
      Call zpttrf(n,d,e,info)

      If (info==0) Then

!       Estimate the condition number of A
!       The NAG name equivalent of zptcon is f07juf
        Call zptcon(n,d,e,anorm,rcond,rwork,info)

!       Print the estimated condition number

        If (rcond>=x02ajf()) Then
          Write (nout,99999) 'Estimate of condition number = ',                &
            1.0E0_nag_wp/rcond
        Else
          Write (nout,99999) 'A is singular to working precision. RCOND = ',   &
            rcond
        End If

      Else
        Write (nout,99998) 'The leading minor of order ', info,                &
          ' is not positive definite'
      End If

99999 Format (1X,A,1P,E10.2)
99998 Format (1X,A,I3,A)
    End Program f07jufe


f07jvfe.f90

    Program f07jvfe

!     F07JVF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: nag_wp, x04dbf, zptrfs, zpttrf, zpttrs
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Integer                          :: i, ifail, info, ldb, ldx, n, nrhs
!     .. Local Arrays ..
      Complex (Kind=nag_wp), Allocatable :: b(:,:), e(:), ef(:), work(:),      &
                                          x(:,:)
      Real (Kind=nag_wp), Allocatable  :: berr(:), d(:), df(:), ferr(:),       &
                                          rwork(:)
      Character (1)                    :: clabs(1), rlabs(1)
!     .. Executable Statements ..
      Write (nout,*) 'F07JVF Example Program Results'
      Write (nout,*)
      Flush (nout)
!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) n, nrhs
      ldb = n
      ldx = n
      Allocate (b(ldb,nrhs),e(n-1),ef(n-1),work(n),x(ldx,nrhs),berr(nrhs),     &
        d(n),df(n),ferr(nrhs),rwork(n))

!     Read the lower bidiagonal part of the tridiagonal matrix A from
!     data file

      Read (nin,*) d(1:n)
      Read (nin,*) e(1:n-1)

!     Read the right hand matrix B

      Read (nin,*)(b(i,1:nrhs),i=1,n)

!     Copy A into DF and EF, and copy B into X
      df(1:n) = d(1:n)
      ef(1:n-1) = e(1:n-1)
      x(1:n,1:nrhs) = b(1:n,1:nrhs)

!     Factorize the copy of the tridiagonal matrix A
!     The NAG name equivalent of zptrrf is f07jrf
      Call zpttrf(n,df,ef,info)

      If (info==0) Then

!       Solve the equations AX = B
!       The NAG name equivalent of zptrrs is f07jsf
        Call zpttrs('Lower',n,nrhs,df,ef,x,ldx,info)

!       Improve the solution and compute error estimates
!       The NAG name equivalent of zptrfs is f07jvf
        Call zptrfs('Lower',n,nrhs,d,e,df,ef,b,ldb,x,ldx,ferr,berr,work,rwork, &
          info)

!       Print the solution and the forward and backward error estimates

!       ifail: behaviour on error exit
!              =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
        ifail = 0
        Call x04dbf('General',' ',n,nrhs,x,ldx,'Bracketed','F7.4',             &
          'Solution(s)','Integer',rlabs,'Integer',clabs,80,0,ifail)

        Write (nout,*)
        Write (nout,*) 'Backward errors (machine-dependent)'
        Write (nout,99999) berr(1:nrhs)
        Write (nout,*)
        Write (nout,*) 'Estimated forward error bounds (machine-dependent)'
        Write (nout,99999) ferr(1:nrhs)
      Else
        Write (nout,99998) 'The leading minor of order ', info,                &
          ' is not positive definite'
      End If

99999 Format ((3X,1P,7E11.1))
99998 Format (1X,A,I3,A)
    End Program f07jvfe


f07kdfe.f90

    Program f07kdfe

!     F07KDF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: dpstrf, nag_wp, x04caf, x04ebf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Real (Kind=nag_wp), Parameter    :: zero = 0.0E0_nag_wp
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: tol
      Integer                          :: i, ifail, info, j, lda, n, rank
      Character (1)                    :: uplo
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: a(:,:), work(:)
      Integer, Allocatable             :: piv(:)
      Character (1)                    :: clabs(1), rlabs(1)
!     .. Executable Statements ..
      Write (nout,*) 'F07KDF Example Program Results'
!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) n, uplo
      lda = n
      Allocate (a(lda,n),piv(n),work(2*n))

!     Read A from data file
      If (uplo=='U') Then
        Read (nin,*)(a(i,i:n),i=1,n)
      Else If (uplo=='L') Then
        Read (nin,*)(a(i,1:i),i=1,n)
      End If
      tol = -1.0_nag_wp

!     Factorize A
!     The NAG name equivalent of dpstrf is f07kdf
      Call dpstrf(uplo,n,a,lda,piv,rank,tol,work,info)

!     Zero out columns rank+1 to n
      If (uplo=='U') Then
        Do j = rank + 1, n
          a(rank+1:j,j) = zero
        End Do
      Else If (uplo=='L') Then
        Do j = rank + 1, n
          a(j:n,j) = zero
        End Do
      End If

!     Print rank
      Write (nout,*)
      Write (nout,'(1X,A15,I3)') 'Computed rank: ', rank

!     Print factor
      Write (nout,*)
      Flush (nout)
      ifail = 0
      Call x04caf(uplo,'Nonunit',n,n,a,lda,'Factor',ifail)

!     Print pivot indices
      Write (nout,*)
      Write (nout,*) 'PIV'
      Flush (nout)

      ifail = 0
      Call x04ebf('General','Non-unit',1,n,piv,1,'I11',' ','No',rlabs,'No',    &
        clabs,80,1,ifail)

    End Program f07kdfe


f07krfe.f90

    Program f07krfe

!     F07KRF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: nag_wp, x04dbf, x04ebf, zpstrf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Complex (Kind=nag_wp), Parameter :: zero = (0.0E0_nag_wp,0.0E0_nag_wp)
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: tol
      Integer                          :: i, ifail, info, j, lda, n, rank
      Character (1)                    :: uplo
!     .. Local Arrays ..
      Complex (Kind=nag_wp), Allocatable :: a(:,:)
      Real (Kind=nag_wp), Allocatable  :: work(:)
      Integer, Allocatable             :: piv(:)
      Character (1)                    :: clabs(1), rlabs(1)
!     .. Executable Statements ..
      Write (nout,*) 'F07KRF Example Program Results'
!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) n, uplo
      lda = n
      Allocate (a(lda,n),piv(n),work(2*n))

!     Read A from data file
      If (uplo=='U') Then
        Read (nin,*)(a(i,i:n),i=1,n)
      Else If (uplo=='L') Then
        Read (nin,*)(a(i,1:i),i=1,n)
      End If
      tol = -1.0_nag_wp

!     Factorize A
!     The NAG name equivalent of zpstrf is f07krf
      Call zpstrf(uplo,n,a,lda,piv,rank,tol,work,info)

!     Zero out columns rank+1 to n
      If (uplo=='U') Then
        Do j = rank + 1, n
          a(rank+1:j,j) = zero
        End Do
      Else If (uplo=='L') Then
        Do j = rank + 1, n
          a(j:n,j) = zero
        End Do
      End If

!     Print rank
      Write (nout,*)
      Write (nout,'(1X,A15,I3)') 'Computed rank: ', rank

!     Print factor
      Write (nout,*)
      Flush (nout)
      ifail = 0
      Call x04dbf(uplo,'Nonunit',n,n,a,lda,'Bracketed','F5.2','Factor',        &
        'Integer',rlabs,'Integer',clabs,80,0,ifail)

!     Print pivot indices
      Write (nout,*)
      Write (nout,*) 'PIV'
      Flush (nout)
      ifail = 0
      Call x04ebf('General','Non-unit',1,n,piv,1,'I14',' ','No',rlabs,'No',    &
        clabs,80,1,ifail)

    End Program f07krfe


f07mafe.f90

    Program f07mafe

!     F07MAF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: dsysv, nag_wp, x04caf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nb = 64, nin = 5, nout = 6
!     .. Local Scalars ..
      Integer                          :: i, ifail, info, lda, lwork, n
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: a(:,:), b(:), work(:)
      Integer, Allocatable             :: ipiv(:)
!     .. Executable Statements ..
      Write (nout,*) 'F07MAF Example Program Results'
      Write (nout,*)
!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) n
      lda = n
      lwork = nb*n
      Allocate (a(lda,n),b(n),work(lwork),ipiv(n))

!     Read the upper triangular part of the matrix A from data file

      Read (nin,*)(a(i,i:n),i=1,n)

!     Read b from data file

      Read (nin,*) b(1:n)

!     Solve the equations Ax = b for x
!     The NAG name equivalent of dsysv is f07maf
      Call dsysv('Upper',n,1,a,lda,ipiv,b,n,work,lwork,info)

      If (info==0) Then

!       Print solution

        Write (nout,*) 'Solution'
        Write (nout,99999) b(1:n)

!       Print details of factorization

        Write (nout,*)
        Flush (nout)

!       ifail: behaviour on error exit
!              =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
        ifail = 0
        Call x04caf('Upper','Non-unit diagonal',n,n,a,lda,                     &
          'Details of the factorization',ifail)

!       Print pivot indices

        Write (nout,*)
        Write (nout,*) 'Pivot indices'
        Write (nout,99998) ipiv(1:n)

      Else
        Write (nout,99997) 'The diagonal block ', info, ' of D is zero'
      End If

99999 Format ((3X,7F11.4))
99998 Format (1X,7I11)
99997 Format (1X,A,I3,A)
    End Program f07mafe


f07mbfe.f90

    Program f07mbfe

!     F07MBF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: dsysvx, nag_wp, x04caf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nb = 64, nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: rcond
      Integer                          :: i, ifail, info, lda, ldaf, ldb, ldx, &
                                          lwork, n, nrhs
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: a(:,:), af(:,:), b(:,:), berr(:),    &
                                          ferr(:), work(:), x(:,:)
      Integer, Allocatable             :: ipiv(:), iwork(:)
!     .. Executable Statements ..
      Write (nout,*) 'F07MBF Example Program Results'
      Write (nout,*)
      Flush (nout)
!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) n, nrhs
      lda = n
      ldaf = n
      ldb = n
      ldx = n
      lwork = nb*n
      Allocate (a(lda,n),af(ldaf,n),b(ldb,nrhs),berr(nrhs),ferr(nrhs),         &
        work(lwork),x(ldx,nrhs),ipiv(n),iwork(n))

!     Read the upper triangular part of A from data file

      Read (nin,*)(a(i,i:n),i=1,n)

!     Read B from data file

      Read (nin,*)(b(i,1:nrhs),i=1,n)

!     Solve the equations AX = B for X
!     The NAG name equivalent of dsysvx is f07mbf
      Call dsysvx('Not factored','Upper',n,nrhs,a,lda,af,ldaf,ipiv,b,ldb,x,    &
        ldx,rcond,ferr,berr,work,lwork,iwork,info)

      If ((info==0) .Or. (info==n+1)) Then

!       Print solution, error bounds and condition number

!       ifail: behaviour on error exit
!              =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
        ifail = 0
        Call x04caf('General',' ',n,nrhs,x,ldx,'Solution(s)',ifail)

        Write (nout,*)
        Write (nout,*) 'Backward errors (machine-dependent)'
        Write (nout,99999) berr(1:nrhs)
        Write (nout,*)
        Write (nout,*) 'Estimated forward error bounds (machine-dependent)'
        Write (nout,99999) ferr(1:nrhs)
        Write (nout,*)
        Write (nout,*) 'Estimate of reciprocal condition number'
        Write (nout,99999) rcond
        Write (nout,*)

        If (info==n+1) Then
          Write (nout,*)
          Write (nout,*) 'The matrix A is singular to working precision'
        End If
      Else
        Write (nout,99998) 'The diagonal block ', info, ' of D is zero'
      End If

99999 Format ((3X,1P,7E11.1))
99998 Format (1X,A,I3,A)
    End Program f07mbfe


f07mdfe.f90

    Program f07mdfe

!     F07MDF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: dsytrf, nag_wp, x04caf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Integer                          :: i, ifail, info, lda, lwork, n
      Character (1)                    :: uplo
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: a(:,:), work(:)
      Integer, Allocatable             :: ipiv(:)
!     .. Executable Statements ..
      Write (nout,*) 'F07MDF Example Program Results'
!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) n
      lda = n
      lwork = 64*n
      Allocate (a(lda,n),work(lwork),ipiv(n))

!     Read A from data file

      Read (nin,*) uplo
      If (uplo=='U') Then
        Read (nin,*)(a(i,i:n),i=1,n)
      Else If (uplo=='L') Then
        Read (nin,*)(a(i,1:i),i=1,n)
      End If

!     Factorize A
!     The NAG name equivalent of dsytrf is f07mdf
      Call dsytrf(uplo,n,a,lda,ipiv,work,lwork,info)

      Write (nout,*)
      Flush (nout)

!     Print details of factorization

!     ifail: behaviour on error exit
!             =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
      ifail = 0
      Call x04caf(uplo,'Nonunit',n,n,a,lda,'Details of factorization',ifail)

!     Print pivot indices

      Write (nout,*)
      Write (nout,*) 'IPIV'
      Write (nout,99999) ipiv(1:n)

      If (info/=0) Then
        Write (nout,*) 'The factor D is singular'
      End If

99999 Format ((3X,7I11))
    End Program f07mdfe


f07mefe.f90

    Program f07mefe

!     F07MEF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: dsytrf, dsytrs, nag_wp, x04caf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Integer                          :: i, ifail, info, lda, ldb, lwork, n,  &
                                          nrhs
      Character (1)                    :: uplo
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: a(:,:), b(:,:), work(:)
      Integer, Allocatable             :: ipiv(:)
!     .. Executable Statements ..
      Write (nout,*) 'F07MEF Example Program Results'
!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) n, nrhs
      lda = n
      ldb = n
      lwork = 64*n
      Allocate (a(lda,n),b(ldb,nrhs),work(lwork),ipiv(n))

!     Read A and B from data file

      Read (nin,*) uplo
      If (uplo=='U') Then
        Read (nin,*)(a(i,i:n),i=1,n)
      Else If (uplo=='L') Then
        Read (nin,*)(a(i,1:i),i=1,n)
      End If
      Read (nin,*)(b(i,1:nrhs),i=1,n)

!     Factorize A
!     The NAG name equivalent of dsytrf is f07mdf
      Call dsytrf(uplo,n,a,lda,ipiv,work,lwork,info)

      Write (nout,*)
      Flush (nout)
      If (info==0) Then

!       Compute solution
!       The NAG name equivalent of dsytrs is f07mef
        Call dsytrs(uplo,n,nrhs,a,lda,ipiv,b,ldb,info)

!       Print solution

!       ifail: behaviour on error exit
!              =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
        ifail = 0
        Call x04caf('General',' ',n,nrhs,b,ldb,'Solution(s)',ifail)

      Else
        Write (nout,*) 'The factor D is singular'
      End If

    End Program f07mefe


f07mgfe.f90

    Program f07mgfe

!     F07MGF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: dlansy => f06rcf, dsycon, dsytrf, nag_wp, x02ajf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: anorm, rcond
      Integer                          :: i, info, lda, lwork, n
      Character (1)                    :: uplo
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: a(:,:), work(:)
      Integer, Allocatable             :: ipiv(:), iwork(:)
!     .. Executable Statements ..
      Write (nout,*) 'F07MGF Example Program Results'
!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) n
      lda = n
      lwork = 64*n
      Allocate (a(lda,n),work(lwork),ipiv(n),iwork(n))

!     Read A from data file

      Read (nin,*) uplo
      If (uplo=='U') Then
        Read (nin,*)(a(i,i:n),i=1,n)
      Else If (uplo=='L') Then
        Read (nin,*)(a(i,1:i),i=1,n)
      End If

!     Compute norm of A
!     f06rcf is the NAG name equivalent of the LAPACK auxiliary dlansy
      anorm = dlansy('1-norm',uplo,n,a,lda,work)

!     Factorize A
!     The NAG name equivalent of dsytrf is f07mdf
      Call dsytrf(uplo,n,a,lda,ipiv,work,lwork,info)

      Write (nout,*)
      If (info==0) Then

!       Estimate condition number
!       The NAG name equivalent of dsycon is f07mgf
        Call dsycon(uplo,n,a,lda,ipiv,anorm,rcond,work,iwork,info)

        If (rcond>=x02ajf()) Then
          Write (nout,99999) 'Estimate of condition number =',                 &
            1.0_nag_wp/rcond
        Else
          Write (nout,*) 'A is singular to working precision'
        End If
      Else
        Write (nout,*) 'The factor D is singular'
      End If

99999 Format (1X,A,1P,E10.2)
    End Program f07mgfe


f07mhfe.f90

    Program f07mhfe

!     F07MHF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: dsyrfs, dsytrf, dsytrs, nag_wp, x04caf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Integer                          :: i, ifail, info, lda, ldaf, ldb, ldx, &
                                          lwork, n, nrhs
      Character (1)                    :: uplo
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: a(:,:), af(:,:), b(:,:), berr(:),    &
                                          ferr(:), work(:), x(:,:)
      Integer, Allocatable             :: ipiv(:), iwork(:)
!     .. Executable Statements ..
      Write (nout,*) 'F07MHF Example Program Results'
!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) n, nrhs
      lda = n
      ldaf = n
      ldb = n
      ldx = n
      lwork = 64*n
      Allocate (a(lda,n),af(ldaf,n),b(ldb,nrhs),berr(nrhs),ferr(nrhs),         &
        work(lwork),x(ldx,n),ipiv(n),iwork(n))

!     Read A and B from data file, and copy A to AF and B to X

      Read (nin,*) uplo
      If (uplo=='U') Then
        Do i = 1, n
          Read (nin,*) a(i,i:n)
          af(i,i:n) = a(i,i:n)
        End Do
      Else If (uplo=='L') Then
        Do i = 1, n
          Read (nin,*) a(i,1:i)
          af(i,1:i) = a(i,1:i)
        End Do
      End If
      Read (nin,*)(b(i,1:nrhs),i=1,n)

      x(1:n,1:nrhs) = b(1:n,1:nrhs)

!     Factorize A in the array AF
!     The NAG name equivalent of dsytrf is f07mdf
      Call dsytrf(uplo,n,af,ldaf,ipiv,work,lwork,info)

      Write (nout,*)
      Flush (nout)
      If (info==0) Then

!       Compute solution in the array X
!       The NAG name equivalent of dsytrs is f07mef
        Call dsytrs(uplo,n,nrhs,af,ldaf,ipiv,x,ldx,info)

!       Improve solution, and compute backward errors and
!       estimated bounds on the forward errors
!       The NAG name equivalent of dsyrfs is f07mhf
        Call dsyrfs(uplo,n,nrhs,a,lda,af,ldaf,ipiv,b,ldb,x,ldx,ferr,berr,work, &
          iwork,info)

!       Print solution

!       ifail: behaviour on error exit
!              =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
        ifail = 0
        Call x04caf('General',' ',n,nrhs,x,ldx,'Solution(s)',ifail)

        Write (nout,*)
        Write (nout,*) 'Backward errors (machine-dependent)'
        Write (nout,99999) berr(1:nrhs)
        Write (nout,*) 'Estimated forward error bounds (machine-dependent)'
        Write (nout,99999) ferr(1:nrhs)
      Else
        Write (nout,*) 'The factor D is singular'
      End If

99999 Format ((3X,1P,7E11.1))
    End Program f07mhfe


f07mjfe.f90

    Program f07mjfe

!     F07MJF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: dsytrf, dsytri, nag_wp, x04caf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Integer                          :: i, ifail, info, lda, lwork, n
      Character (1)                    :: uplo
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: a(:,:), work(:)
      Integer, Allocatable             :: ipiv(:)
!     .. Executable Statements ..
      Write (nout,*) 'F07MJF Example Program Results'
!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) n
      lda = n
      lwork = 64*n
      Allocate (a(lda,n),work(lwork),ipiv(n))

!     Read A from data file

      Read (nin,*) uplo
      If (uplo=='U') Then
        Read (nin,*)(a(i,i:n),i=1,n)
      Else If (uplo=='L') Then
        Read (nin,*)(a(i,1:i),i=1,n)
      End If

!     Factorize A
!     The NAG name equivalent of dsytrf is f07mdf
      Call dsytrf(uplo,n,a,lda,ipiv,work,lwork,info)

      Write (nout,*)
      Flush (nout)
      If (info==0) Then

!       Compute inverse of A
!       The NAG name equivalent of dsytri is f07mjf
        Call dsytri(uplo,n,a,lda,ipiv,work,info)

!       Print inverse

!       ifail: behaviour on error exit
!              =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
        ifail = 0
        Call x04caf(uplo,'Nonunit',n,n,a,lda,'Inverse',ifail)

      Else
        Write (nout,*) 'The factor D is singular'
      End If

    End Program f07mjfe


f07mnfe.f90

    Program f07mnfe

!     F07MNF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: nag_wp, x04dbf, zhesv
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nb = 64, nin = 5, nout = 6
!     .. Local Scalars ..
      Integer                          :: i, ifail, info, lda, lwork, n
!     .. Local Arrays ..
      Complex (Kind=nag_wp), Allocatable :: a(:,:), b(:), work(:)
      Integer, Allocatable             :: ipiv(:)
      Character (1)                    :: clabs(1), rlabs(1)
!     .. Executable Statements ..
      Write (nout,*) 'F07MNF Example Program Results'
      Write (nout,*)
!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) n
      lda = n
      lwork = nb*n
      Allocate (a(lda,n),b(n),work(lwork),ipiv(n))

!     Read the upper triangular part of the matrix A from data file

      Read (nin,*)(a(i,i:n),i=1,n)

!     Read b from data file

      Read (nin,*) b(1:n)

!     Solve the equations Ax = b for x
!     The NAG name equivalent of zhesv is f06mnf
      Call zhesv('Upper',n,1,a,lda,ipiv,b,n,work,lwork,info)

      If (info==0) Then

!       Print solution

        Write (nout,*) 'Solution'
        Write (nout,99999) b(1:n)

!       Print details of factorization

        Write (nout,*)
        Flush (nout)

!       ifail: behaviour on error exit
!              =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
        ifail = 0
        Call x04dbf('Upper','Non-unit diagonal',n,n,a,lda,'Bracketed','F7.4',  &
          'Details of the factorization','Integer',rlabs,'Integer',clabs,80,0, &
          ifail)

!       Print pivot indices

        Write (nout,*)
        Write (nout,*) 'Pivot indices'
        Write (nout,99998) ipiv(1:n)

      Else
        Write (nout,99997) 'The diagonal block ', info, ' of D is zero'
      End If

99999 Format ((3X,4(' (',F7.4,',',F7.4,')',:)))
99998 Format (1X,7I11)
99997 Format (1X,A,I3,A)
    End Program f07mnfe


f07mpfe.f90

    Program f07mpfe

!     F07MPF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: nag_wp, x04dbf, zhesvx
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nb = 64, nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: rcond
      Integer                          :: i, ifail, info, lda, ldaf, ldb, ldx, &
                                          lwork, n, nrhs
!     .. Local Arrays ..
      Complex (Kind=nag_wp), Allocatable :: a(:,:), af(:,:), b(:,:), work(:),  &
                                          x(:,:)
      Real (Kind=nag_wp), Allocatable  :: berr(:), ferr(:), rwork(:)
      Integer, Allocatable             :: ipiv(:)
      Character (1)                    :: clabs(1), rlabs(1)
!     .. Executable Statements ..
      Write (nout,*) 'F07MPF Example Program Results'
      Write (nout,*)
      Flush (nout)
!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) n, nrhs
      lda = n
      ldaf = n
      ldb = n
      ldx = n
      lwork = nb*n
      Allocate (a(lda,n),af(ldaf,n),b(ldb,nrhs),work(lwork),x(ldx,nrhs),       &
        berr(nrhs),ferr(nrhs),rwork(n),ipiv(n))

!     Read the upper triangular part of A from data file

      Read (nin,*)(a(i,i:n),i=1,n)

!     Read B from data file

      Read (nin,*)(b(i,1:nrhs),i=1,n)

!     Solve the equations AX = B for X
!     The NAG name equivalent of zhesvx is f07mpf
      Call zhesvx('Not factored','Upper',n,nrhs,a,lda,af,ldaf,ipiv,b,ldb,x,    &
        ldx,rcond,ferr,berr,work,lwork,rwork,info)

      If ((info==0) .Or. (info==n+1)) Then

!       Print solution, error bounds and condition number

!       ifail: behaviour on error exit
!              =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
        ifail = 0
        Call x04dbf('General',' ',n,nrhs,x,ldx,'Bracketed','F7.4',             &
          'Solution(s)','Integer',rlabs,'Integer',clabs,80,0,ifail)

        Write (nout,*)
        Write (nout,*) 'Backward errors (machine-dependent)'
        Write (nout,99999) berr(1:nrhs)
        Write (nout,*)
        Write (nout,*) 'Estimated forward error bounds (machine-dependent)'
        Write (nout,99999) ferr(1:nrhs)
        Write (nout,*)
        Write (nout,*) 'Estimate of reciprocal condition number'
        Write (nout,99999) rcond
        Write (nout,*)

        If (info==n+1) Then
          Write (nout,*)
          Write (nout,*) 'The matrix A is singular to working precision'
        End If
      Else
        Write (nout,99998) 'The diagonal block ', info, ' of D is zero'
      End If

99999 Format ((3X,1P,7E11.1))
99998 Format (1X,A,I3,A)
    End Program f07mpfe


f07mrfe.f90

    Program f07mrfe

!     F07MRF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: nag_wp, x04dbf, zhetrf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Integer                          :: i, ifail, info, lda, lwork, n
      Character (1)                    :: uplo
!     .. Local Arrays ..
      Complex (Kind=nag_wp), Allocatable :: a(:,:), work(:)
      Integer, Allocatable             :: ipiv(:)
      Character (1)                    :: clabs(1), rlabs(1)
!     .. Executable Statements ..
      Write (nout,*) 'F07MRF Example Program Results'
!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) n
      lda = n
      lwork = 64*n
      Allocate (a(lda,n),work(lwork),ipiv(n))

!     Read A from data file

      Read (nin,*) uplo
      If (uplo=='U') Then
        Read (nin,*)(a(i,i:n),i=1,n)
      Else If (uplo=='L') Then
        Read (nin,*)(a(i,1:i),i=1,n)
      End If

!     Factorize A
!     The NAG name equivalent of zhetrf is f07mrf
      Call zhetrf(uplo,n,a,lda,ipiv,work,lwork,info)

      Write (nout,*)
      Flush (nout)

!     Print details of factorization

!     ifail: behaviour on error exit
!             =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
      ifail = 0
      Call x04dbf(uplo,'Nonunit',n,n,a,lda,'Bracketed','F7.4',                 &
        'Details of factorization','Integer',rlabs,'Integer',clabs,80,0,ifail)

!     Print pivot indices

      Write (nout,*)
      Write (nout,*) 'IPIV'
      Write (nout,99999) ipiv(1:n)

      If (info/=0) Then
        Write (nout,*) 'The factor D is singular'
      End If

99999 Format ((1X,I12,3I18))
    End Program f07mrfe


f07msfe.f90

    Program f07msfe

!     F07MSF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: nag_wp, x04dbf, zhetrf, zhetrs
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Integer                          :: i, ifail, info, lda, ldb, lwork, n,  &
                                          nrhs
      Character (1)                    :: uplo
!     .. Local Arrays ..
      Complex (Kind=nag_wp), Allocatable :: a(:,:), b(:,:), work(:)
      Integer, Allocatable             :: ipiv(:)
      Character (1)                    :: clabs(1), rlabs(1)
!     .. Executable Statements ..
      Write (nout,*) 'F07MSF Example Program Results'
!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) n, nrhs
      lda = n
      ldb = n
      lwork = 64*n
      Allocate (a(lda,n),b(ldb,nrhs),work(lwork),ipiv(n))

!     Read A and B from data file

      Read (nin,*) uplo
      If (uplo=='U') Then
        Read (nin,*)(a(i,i:n),i=1,n)
      Else If (uplo=='L') Then
        Read (nin,*)(a(i,1:i),i=1,n)
      End If
      Read (nin,*)(b(i,1:nrhs),i=1,n)

!     Factorize A
!     The NAG name equivalent of zhetrf is f07mrf
      Call zhetrf(uplo,n,a,lda,ipiv,work,lwork,info)

      Write (nout,*)
      Flush (nout)
      If (info==0) Then

!       Compute solution
!       The NAG name equivalent of zhetrs is f07msf
        Call zhetrs(uplo,n,nrhs,a,lda,ipiv,b,ldb,info)

!       Print solution

!       ifail: behaviour on error exit
!              =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
        ifail = 0
        Call x04dbf('General',' ',n,nrhs,b,ldb,'Bracketed','F7.4',             &
          'Solution(s)','Integer',rlabs,'Integer',clabs,80,0,ifail)

      Else
        Write (nout,*) 'The factor D is singular'
      End If

    End Program f07msfe


f07mufe.f90

    Program f07mufe

!     F07MUF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: nag_wp, x02ajf, zhecon, zhetrf, zlanhe => f06ucf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: anorm, rcond
      Integer                          :: i, info, lda, lwork, n
      Character (1)                    :: uplo
!     .. Local Arrays ..
      Complex (Kind=nag_wp), Allocatable :: a(:,:), work(:)
      Real (Kind=nag_wp), Allocatable  :: rwork(:)
      Integer, Allocatable             :: ipiv(:)
!     .. Executable Statements ..
      Write (nout,*) 'F07MUF Example Program Results'
!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) n
      lda = n
      lwork = 64*n
      Allocate (a(lda,n),work(lwork),rwork(n),ipiv(n))

!     Read A from data file

      Read (nin,*) uplo
      If (uplo=='U') Then
        Read (nin,*)(a(i,i:n),i=1,n)
      Else If (uplo=='L') Then
        Read (nin,*)(a(i,1:i),i=1,n)
      End If

!     Compute norm of A
!     f06ucf is the NAG name equivalent of the LAPACK auxiliary zlanhe
      anorm = zlanhe('1-norm',uplo,n,a,lda,rwork)

!     Factorize A
!     The NAG name equivalent of zhetrf is f07mrf
      Call zhetrf(uplo,n,a,lda,ipiv,work,lwork,info)

      Write (nout,*)
      If (info==0) Then

!       Estimate condition number
!       The NAG name equivalent of zhecon is f07muf
        Call zhecon(uplo,n,a,lda,ipiv,anorm,rcond,work,info)

        If (rcond>=x02ajf()) Then
          Write (nout,99999) 'Estimate of condition number =',                 &
            1.0_nag_wp/rcond
        Else
          Write (nout,*) 'A is singular to working precision'
        End If
      Else
        Write (nout,*) 'The factor D is singular'
      End If

99999 Format (1X,A,1P,E10.2)
    End Program f07mufe


f07mvfe.f90

    Program f07mvfe

!     F07MVF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: f06tff, nag_wp, x04dbf, zherfs, zhetrf, zhetrs
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Integer                          :: i, ifail, info, lda, ldaf, ldb, ldx, &
                                          lwork, n, nrhs
      Character (1)                    :: uplo
!     .. Local Arrays ..
      Complex (Kind=nag_wp), Allocatable :: a(:,:), af(:,:), b(:,:), work(:),  &
                                          x(:,:)
      Real (Kind=nag_wp), Allocatable  :: berr(:), ferr(:), rwork(:)
      Integer, Allocatable             :: ipiv(:)
      Character (1)                    :: clabs(1), rlabs(1)
!     .. Executable Statements ..
      Write (nout,*) 'F07MVF Example Program Results'
!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) n, nrhs
      lda = n
      ldaf = n
      ldb = n
      ldx = n
      lwork = 64*n
      Allocate (a(lda,n),af(ldaf,n),b(ldb,nrhs),work(lwork),x(ldx,n),          &
        berr(nrhs),ferr(nrhs),rwork(n),ipiv(n))

!     Read A and B from data file, and copy A to AF and B to X

      Read (nin,*) uplo
      If (uplo=='U') Then
        Read (nin,*)(a(i,i:n),i=1,n)
      Else If (uplo=='L') Then
        Read (nin,*)(a(i,1:i),i=1,n)
      End If
      Read (nin,*)(b(i,1:nrhs),i=1,n)

      Call f06tff(uplo,n,n,a,lda,af,ldaf)
      x(1:n,1:nrhs) = b(1:n,1:nrhs)

!     Factorize A in the array AF
!     The NAG name equivalent of zhetrf is f07mrf
      Call zhetrf(uplo,n,af,ldaf,ipiv,work,lwork,info)

      Write (nout,*)
      Flush (nout)
      If (info==0) Then

!       Compute solution in the array X
!       The NAG name equivalent of zhetrs is f07msf
        Call zhetrs(uplo,n,nrhs,af,ldaf,ipiv,x,ldx,info)

!       Improve solution, and compute backward errors and
!       estimated bounds on the forward errors

!       The NAG name equivalent of zherfs is f07mvf
        Call zherfs(uplo,n,nrhs,a,lda,af,ldaf,ipiv,b,ldb,x,ldx,ferr,berr,work, &
          rwork,info)

!       Print solution

!       ifail: behaviour on error exit
!              =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
        ifail = 0
        Call x04dbf('General',' ',n,nrhs,x,ldx,'Bracketed','F7.4',             &
          'Solution(s)','Integer',rlabs,'Integer',clabs,80,0,ifail)

        Write (nout,*)
        Write (nout,*) 'Backward errors (machine-dependent)'
        Write (nout,99999) berr(1:nrhs)
        Write (nout,*) 'Estimated forward error bounds (machine-dependent)'
        Write (nout,99999) ferr(1:nrhs)
      Else
        Write (nout,*) 'The factor D is singular'
      End If

99999 Format ((5X,1P,4(E11.1,7X)))
    End Program f07mvfe


f07mwfe.f90

    Program f07mwfe

!     F07MWF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: nag_wp, x04dbf, zhetrf, zhetri
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Integer                          :: i, ifail, info, lda, lwork, n
      Character (1)                    :: uplo
!     .. Local Arrays ..
      Complex (Kind=nag_wp), Allocatable :: a(:,:), work(:)
      Integer, Allocatable             :: ipiv(:)
      Character (1)                    :: clabs(1), rlabs(1)
!     .. Executable Statements ..
      Write (nout,*) 'F07MWF Example Program Results'
!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) n
      lda = n
      lwork = 64*n
      Allocate (a(lda,n),work(lwork),ipiv(n))

!     Read A from data file

      Read (nin,*) uplo
      If (uplo=='U') Then
        Read (nin,*)(a(i,i:n),i=1,n)
      Else If (uplo=='L') Then
        Read (nin,*)(a(i,1:i),i=1,n)
      End If

!     Factorize A
!     The NAG name equivalent of zhetrf is f07mrf
      Call zhetrf(uplo,n,a,lda,ipiv,work,lwork,info)

      Write (nout,*)
      Flush (nout)
      If (info==0) Then

!       Compute inverse of A
!       The NAG name equivalent of zhetri is f07mwf
        Call zhetri(uplo,n,a,lda,ipiv,work,info)

!       Print inverse

!       ifail: behaviour on error exit
!              =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
        ifail = 0
        Call x04dbf(uplo,'Nonunit',n,n,a,lda,'Bracketed','F7.4','Inverse',     &
          'Integer',rlabs,'Integer',clabs,80,0,ifail)

      Else
        Write (nout,*) 'The factor D is singular'
      End If

    End Program f07mwfe


f07nnfe.f90

    Program f07nnfe

!     F07NNF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: nag_wp, x04dbf, zsysv
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nb = 64, nin = 5, nout = 6
!     .. Local Scalars ..
      Integer                          :: i, ifail, info, lda, lwork, n
!     .. Local Arrays ..
      Complex (Kind=nag_wp), Allocatable :: a(:,:), b(:), work(:)
      Integer, Allocatable             :: ipiv(:)
      Character (1)                    :: clabs(1), rlabs(1)
!     .. Executable Statements ..
      Write (nout,*) 'F07NNF Example Program Results'
      Write (nout,*)
!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) n
      lda = n
      lwork = nb*n
      Allocate (a(lda,n),b(n),work(lwork),ipiv(n))

!     Read the upper triangular part of the matrix A from data file

      Read (nin,*)(a(i,i:n),i=1,n)

!     Read b from data file

      Read (nin,*) b(1:n)

!     Solve the equations Ax = b for x

!     The NAG name equivalent of zsysv is f07nnf
      Call zsysv('Upper',n,1,a,lda,ipiv,b,n,work,lwork,info)

      If (info==0) Then

!       Print solution

        Write (nout,*) 'Solution'
        Write (nout,99999) b(1:n)

!       Print details of factorization

        Write (nout,*)
        Flush (nout)

!       ifail: behaviour on error exit
!              =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
        ifail = 0
        Call x04dbf('Upper','Non-unit diagonal',n,n,a,lda,'Bracketed','F7.4',  &
          'Details of the factorization','Integer',rlabs,'Integer',clabs,80,0, &
          ifail)

!       Print pivot indices

        Write (nout,*)
        Write (nout,*) 'Pivot indices'
        Write (nout,99998) ipiv(1:n)

      Else
        Write (nout,99997) 'The diagonal block ', info, ' of D is zero'
      End If

99999 Format ((4X,4('(',F7.4,',',F7.4,') ')))
99998 Format (1X,7I11)
99997 Format (1X,A,I3,A)
    End Program f07nnfe


f07npfe.f90

    Program f07npfe

!     F07NPF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: nag_wp, x04dbf, zsysvx
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nb = 64, nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: rcond
      Integer                          :: i, ifail, info, lda, ldaf, ldb, ldx, &
                                          lwork, n, nrhs
!     .. Local Arrays ..
      Complex (Kind=nag_wp), Allocatable :: a(:,:), af(:,:), b(:,:), work(:),  &
                                          x(:,:)
      Real (Kind=nag_wp), Allocatable  :: berr(:), ferr(:), rwork(:)
      Integer, Allocatable             :: ipiv(:)
      Character (1)                    :: clabs(1), rlabs(1)
!     .. Executable Statements ..
      Write (nout,*) 'F07NPF Example Program Results'
      Write (nout,*)
      Flush (nout)
!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) n, nrhs
      lda = n
      ldaf = n
      ldb = n
      ldx = n
      lwork = nb*n
      Allocate (a(lda,n),af(ldaf,n),b(ldb,nrhs),work(lwork),x(ldx,nrhs),       &
        berr(nrhs),ferr(nrhs),rwork(n),ipiv(n))

!     Read the upper triangular part of A from data file

      Read (nin,*)(a(i,i:n),i=1,n)

!     Read B from data file

      Read (nin,*)(b(i,1:nrhs),i=1,n)

!     Solve the equations AX = B for X
!     The NAG name equivalent of zsysvx is f07npf
      Call zsysvx('Not factored','Upper',n,nrhs,a,lda,af,ldaf,ipiv,b,ldb,x,    &
        ldx,rcond,ferr,berr,work,lwork,rwork,info)

      If ((info==0) .Or. (info==n+1)) Then

!       Print solution, error bounds and condition number

!       ifail: behaviour on error exit
!              =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
        ifail = 0
        Call x04dbf('General',' ',n,nrhs,x,ldx,'Bracketed','F7.4',             &
          'Solution(s)','Integer',rlabs,'Integer',clabs,80,0,ifail)

        Write (nout,*)
        Write (nout,*) 'Backward errors (machine-dependent)'
        Write (nout,99999) berr(1:nrhs)
        Write (nout,*)
        Write (nout,*) 'Estimated forward error bounds (machine-dependent)'
        Write (nout,99999) ferr(1:nrhs)
        Write (nout,*)
        Write (nout,*) 'Estimate of reciprocal condition number'
        Write (nout,99999) rcond
        Write (nout,*)

        If (info==n+1) Then
          Write (nout,*)
          Write (nout,*) 'The matrix A is singular to working precision'
        End If
      Else
        Write (nout,99998) 'The diagonal block ', info, ' of D is zero'
      End If

99999 Format ((3X,1P,7E11.1))
99998 Format (1X,A,I3,A)
    End Program f07npfe


f07nrfe.f90

    Program f07nrfe

!     F07NRF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: nag_wp, x04dbf, zsytrf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Integer                          :: i, ifail, info, lda, lwork, n
      Character (1)                    :: uplo
!     .. Local Arrays ..
      Complex (Kind=nag_wp), Allocatable :: a(:,:), work(:)
      Integer, Allocatable             :: ipiv(:)
      Character (1)                    :: clabs(1), rlabs(1)
!     .. Executable Statements ..
      Write (nout,*) 'F07NRF Example Program Results'
!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) n
      lda = n
      lwork = 64*n
      Allocate (a(lda,n),work(lwork),ipiv(n))

!     Read A from data file

      Read (nin,*) uplo
      If (uplo=='U') Then
        Read (nin,*)(a(i,i:n),i=1,n)
      Else If (uplo=='L') Then
        Read (nin,*)(a(i,1:i),i=1,n)
      End If

!     Factorize A
!     The NAG name equivalent of zsytrf is f07nrf
      Call zsytrf(uplo,n,a,lda,ipiv,work,lwork,info)

      Write (nout,*)
      Flush (nout)

!     Print details of factorization

!     ifail: behaviour on error exit
!            =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
      ifail = 0
      Call x04dbf(uplo,'Nonunit',n,n,a,lda,'Bracketed','F7.4',                 &
        'Details of factorization','Integer',rlabs,'Integer',clabs,80,0,ifail)

!     Print pivot indices

      Write (nout,*)
      Write (nout,*) 'IPIV'
      Write (nout,99999) ipiv(1:n)

      If (info/=0) Then
        Write (nout,*) 'The factor D is singular'
      End If

99999 Format ((1X,I12,3I18))
    End Program f07nrfe


f07nsfe.f90

    Program f07nsfe

!     F07NSF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: nag_wp, x04dbf, zsytrf, zsytrs
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Integer                          :: i, ifail, info, lda, ldb, lwork, n,  &
                                          nrhs
      Character (1)                    :: uplo
!     .. Local Arrays ..
      Complex (Kind=nag_wp), Allocatable :: a(:,:), b(:,:), work(:)
      Integer, Allocatable             :: ipiv(:)
      Character (1)                    :: clabs(1), rlabs(1)
!     .. Executable Statements ..
      Write (nout,*) 'F07NSF Example Program Results'
!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) n, nrhs
      lda = n
      ldb = n
      lwork = 64*n
      Allocate (a(lda,n),b(ldb,nrhs),work(lwork),ipiv(n))

!     Read A and B from data file

      Read (nin,*) uplo
      If (uplo=='U') Then
        Read (nin,*)(a(i,i:n),i=1,n)
      Else If (uplo=='L') Then
        Read (nin,*)(a(i,1:i),i=1,n)
      End If
      Read (nin,*)(b(i,1:nrhs),i=1,n)

!     Factorize A
!     The NAG name equivalent of zsytrf is f07nrf
      Call zsytrf(uplo,n,a,lda,ipiv,work,lwork,info)

      Write (nout,*)
      Flush (nout)
      If (info==0) Then

!       Compute solution
!       The NAG name equivalent of zsytrs is f07nsf
        Call zsytrs(uplo,n,nrhs,a,lda,ipiv,b,ldb,info)

!       Print solution

!       ifail: behaviour on error exit
!              =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
        ifail = 0
        Call x04dbf('General',' ',n,nrhs,b,ldb,'Bracketed','F7.4',             &
          'Solution(s)','Integer',rlabs,'Integer',clabs,80,0,ifail)

      Else
        Write (nout,*) 'The factor D is singular'
      End If

    End Program f07nsfe


f07nufe.f90

    Program f07nufe

!     F07NUF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: nag_wp, x02ajf, zlansy => f06uff, zsycon, zsytrf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: anorm, rcond
      Integer                          :: i, info, lda, lwork, n
      Character (1)                    :: uplo
!     .. Local Arrays ..
      Complex (Kind=nag_wp), Allocatable :: a(:,:), work(:)
      Real (Kind=nag_wp), Allocatable  :: rwork(:)
      Integer, Allocatable             :: ipiv(:)
!     .. Executable Statements ..
      Write (nout,*) 'F07NUF Example Program Results'
!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) n
      lda = n
      lwork = 64*n
      Allocate (a(lda,n),work(lwork),rwork(n),ipiv(n))

!     Read A from data file

      Read (nin,*) uplo
      If (uplo=='U') Then
        Read (nin,*)(a(i,i:n),i=1,n)
      Else If (uplo=='L') Then
        Read (nin,*)(a(i,1:i),i=1,n)
      End If

!     Compute norm of A
!     f06uff is the NAG name equivalent of the LAPACK auxiliary zlansy
      anorm = zlansy('1-norm',uplo,n,a,lda,rwork)

!     Factorize A
!     The NAG name equivalent of zsytrf is f07nrf
      Call zsytrf(uplo,n,a,lda,ipiv,work,lwork,info)

      Write (nout,*)
      If (info==0) Then

!       Estimate condition number
!       The NAG name equivalent of zsycon is f07nuf
        Call zsycon(uplo,n,a,lda,ipiv,anorm,rcond,work,info)

        If (rcond>=x02ajf()) Then
          Write (nout,99999) 'Estimate of condition number =',                 &
            1.0_nag_wp/rcond
        Else
          Write (nout,*) 'A is singular to working precision'
        End If
      Else
        Write (nout,*) 'The factor D is singular'
      End If

99999 Format (1X,A,1P,E10.2)
    End Program f07nufe


f07nvfe.f90

    Program f07nvfe

!     F07NVF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: f06tff, nag_wp, x04dbf, zsyrfs, zsytrf, zsytrs
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Integer                          :: i, ifail, info, lda, ldaf, ldb, ldx, &
                                          lwork, n, nrhs
      Character (1)                    :: uplo
!     .. Local Arrays ..
      Complex (Kind=nag_wp), Allocatable :: a(:,:), af(:,:), b(:,:), work(:),  &
                                          x(:,:)
      Real (Kind=nag_wp), Allocatable  :: berr(:), ferr(:), rwork(:)
      Integer, Allocatable             :: ipiv(:)
      Character (1)                    :: clabs(1), rlabs(1)
!     .. Executable Statements ..
      Write (nout,*) 'F07NVF Example Program Results'
!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) n, nrhs
      lda = n
      ldaf = n
      ldb = n
      ldx = n
      lwork = 64*n
      Allocate (a(lda,n),af(ldaf,n),b(ldb,nrhs),work(lwork),x(ldx,n),          &
        berr(nrhs),ferr(nrhs),rwork(n),ipiv(n))

!     Read A and B from data file, and copy A to AF and B to X

      Read (nin,*) uplo
      If (uplo=='U') Then
        Read (nin,*)(a(i,i:n),i=1,n)
      Else If (uplo=='L') Then
        Read (nin,*)(a(i,1:i),i=1,n)
      End If
      Read (nin,*)(b(i,1:nrhs),i=1,n)
      Call f06tff(uplo,n,n,a,lda,af,ldaf)
      x(1:n,1:nrhs) = b(1:n,1:nrhs)

!     Factorize A in the array AF
!     The NAG name equivalent of zsytrf is f07nrf
      Call zsytrf(uplo,n,af,ldaf,ipiv,work,lwork,info)

      Write (nout,*)
      Flush (nout)
      If (info==0) Then

!       Compute solution in the array X
!       The NAG name equivalent of zsytrs is f07nsf
        Call zsytrs(uplo,n,nrhs,af,ldaf,ipiv,x,ldx,info)

!       Improve solution, and compute backward errors and
!       estimated bounds on the forward errors

!       The NAG name equivalent of zsyrfs is f07nvf
        Call zsyrfs(uplo,n,nrhs,a,lda,af,ldaf,ipiv,b,ldb,x,ldx,ferr,berr,work, &
          rwork,info)

!       Print solution

!       ifail: behaviour on error exit
!              =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
        ifail = 0
        Call x04dbf('General',' ',n,nrhs,x,ldx,'Bracketed','F7.4',             &
          'Solution(s)','Integer',rlabs,'Integer',clabs,80,0,ifail)

        Write (nout,*)
        Write (nout,*) 'Backward errors (machine-dependent)'
        Write (nout,99999) berr(1:nrhs)
        Write (nout,*) 'Estimated forward error bounds (machine-dependent)'
        Write (nout,99999) ferr(1:nrhs)
      Else
        Write (nout,*) 'The factor D is singular'
      End If

99999 Format ((5X,1P,4(E11.1,7X)))
    End Program f07nvfe


f07nwfe.f90

    Program f07nwfe

!     F07NWF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: nag_wp, x04dbf, zsytrf, zsytri
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Integer                          :: i, ifail, info, lda, lwork, n
      Character (1)                    :: uplo
!     .. Local Arrays ..
      Complex (Kind=nag_wp), Allocatable :: a(:,:), work(:)
      Integer, Allocatable             :: ipiv(:)
      Character (1)                    :: clabs(1), rlabs(1)
!     .. Executable Statements ..
      Write (nout,*) 'F07NWF Example Program Results'
!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) n
      lda = n
      lwork = 64*n
      Allocate (a(lda,n),work(lwork),ipiv(n))

!     Read A from data file

      Read (nin,*) uplo
      If (uplo=='U') Then
        Read (nin,*)(a(i,i:n),i=1,n)
      Else If (uplo=='L') Then
        Read (nin,*)(a(i,1:i),i=1,n)
      End If

!     Factorize A
!     The NAG name equivalent of zsytrf is f07nrf
      Call zsytrf(uplo,n,a,lda,ipiv,work,lwork,info)

      Write (nout,*)
      Flush (nout)
      If (info==0) Then

!       Compute inverse of A
!       The NAG name equivalent of zsytri is f07nwf
        Call zsytri(uplo,n,a,lda,ipiv,work,info)

!       Print inverse

!       ifail: behaviour on error exit
!              =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
        ifail = 0
        Call x04dbf(uplo,'Nonunit',n,n,a,lda,'Bracketed','F7.4','Inverse',     &
          'Integer',rlabs,'Integer',clabs,80,0,ifail)

      Else
        Write (nout,*) 'The factor D is singular'
      End If

    End Program f07nwfe


f07pafe.f90

    Program f07pafe

!     F07PAF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: dspsv, nag_wp, x04ccf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
      Character (1), Parameter         :: uplo = 'U'
!     .. Local Scalars ..
      Integer                          :: i, ifail, info, j, n
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: ap(:), b(:)
      Integer, Allocatable             :: ipiv(:)
!     .. Executable Statements ..
      Write (nout,*) 'F07PAF Example Program Results'
      Write (nout,*)
!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) n

      Allocate (ap((n*(n+1))/2),b(n),ipiv(n))

!     Read the upper or lower triangular part of the matrix A from
!     data file

      If (uplo=='U') Then
        Read (nin,*)((ap(i+(j*(j-1))/2),j=i,n),i=1,n)
      Else If (uplo=='L') Then
        Read (nin,*)((ap(i+((2*n-j)*(j-1))/2),j=1,i),i=1,n)
      End If

!     Read b from data file

      Read (nin,*) b(1:n)

!     Solve the equations Ax = b for x
!     The NAG name equivalent of dspsv is f07paf
      Call dspsv(uplo,n,1,ap,ipiv,b,n,info)

      If (info==0) Then

!       Print solution

        Write (nout,*) 'Solution'
        Write (nout,99999) b(1:n)

!       Print details of factorization

        Write (nout,*)
        Flush (nout)

!       ifail: behaviour on error exit
!              =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
        ifail = 0
        Call x04ccf(uplo,'Non-unit diagonal',n,ap,                             &
          'Details of the factorization',ifail)

!       Print pivot indices

        Write (nout,*)
        Write (nout,*) 'Pivot indices'
        Write (nout,99998) ipiv(1:n)

      Else
        Write (nout,99997) 'The diagonal block ', info, ' of D is zero'
      End If

99999 Format ((3X,7F11.4))
99998 Format (1X,7I11)
99997 Format (1X,A,I3,A)
    End Program f07pafe


f07pbfe.f90

    Program f07pbfe

!     F07PBF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: dspsvx, nag_wp, x04caf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
      Character (1), Parameter         :: uplo = 'U'
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: rcond
      Integer                          :: i, ifail, info, j, ldb, ldx, n, nrhs
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: afp(:), ap(:), b(:,:), berr(:),      &
                                          ferr(:), work(:), x(:,:)
      Integer, Allocatable             :: ipiv(:), iwork(:)
!     .. Executable Statements ..
      Write (nout,*) 'F07PBF Example Program Results'
      Write (nout,*)
      Flush (nout)
!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) n, nrhs
      ldb = n
      ldx = n
      Allocate (afp((n*(n+1))/2),ap((n*(n+1))/2),b(ldb,nrhs),berr(nrhs),ferr(  &
        nrhs),work(3*n),x(ldx,nrhs),ipiv(n),iwork(n))

!     Read the upper or lower triangular part of the matrix A from
!     data file

      If (uplo=='U') Then
        Read (nin,*)((ap(i+(j*(j-1))/2),j=i,n),i=1,n)
      Else If (uplo=='L') Then
        Read (nin,*)((ap(i+((2*n-j)*(j-1))/2),j=1,i),i=1,n)
      End If

!     Read B from data file

      Read (nin,*)(b(i,1:nrhs),i=1,n)

!     Solve the equations AX = B for X
!     The NAG name equivalent of dspsvx is f07pbf
      Call dspsvx('Not factored',uplo,n,nrhs,ap,afp,ipiv,b,ldb,x,ldx,rcond,    &
        ferr,berr,work,iwork,info)

      If ((info==0) .Or. (info==n+1)) Then

!       Print solution, error bounds and condition number

!       ifail: behaviour on error exit
!              =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
        ifail = 0
        Call x04caf('General',' ',n,nrhs,x,ldx,'Solution(s)',ifail)

        Write (nout,*)
        Write (nout,*) 'Backward errors (machine-dependent)'
        Write (nout,99999) berr(1:nrhs)
        Write (nout,*)
        Write (nout,*) 'Estimated forward error bounds (machine-dependent)'
        Write (nout,99999) ferr(1:nrhs)
        Write (nout,*)
        Write (nout,*) 'Estimate of reciprocal condition number'
        Write (nout,99999) rcond
        Write (nout,*)

        If (info==n+1) Then
          Write (nout,*)
          Write (nout,*) 'The matrix A is singular to working precision'
        End If
      Else
        Write (nout,99998) 'The diagonal block ', info, ' of D is zero'
      End If

99999 Format ((3X,1P,7E11.1))
99998 Format (1X,A,I3,A)
    End Program f07pbfe


f07pdfe.f90

    Program f07pdfe

!     F07PDF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: dsptrf, nag_wp, x04ccf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Integer                          :: i, ifail, info, j, n
      Character (1)                    :: uplo
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: ap(:)
      Integer, Allocatable             :: ipiv(:)
!     .. Executable Statements ..
      Write (nout,*) 'F07PDF Example Program Results'
!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) n

      Allocate (ap(n*(n+1)/2),ipiv(n))

!     Read A from data file

      Read (nin,*) uplo
      If (uplo=='U') Then
        Read (nin,*)((ap(i+j*(j-1)/2),j=i,n),i=1,n)
      Else If (uplo=='L') Then
        Read (nin,*)((ap(i+(2*n-j)*(j-1)/2),j=1,i),i=1,n)
      End If

!     Factorize A
!     The NAG name equivalent of dsptrf is f07pdf
      Call dsptrf(uplo,n,ap,ipiv,info)

      Write (nout,*)
      Flush (nout)

!     Print details of factorization

!     ifail: behaviour on error exit
!            =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
      ifail = 0
      Call x04ccf(uplo,'Nonunit',n,ap,'Details of factorization',ifail)

!     Print pivot indices

      Write (nout,*)
      Write (nout,*) 'IPIV'
      Write (nout,99999) ipiv(1:n)

      If (info/=0) Then
        Write (nout,*) 'The factor D is singular'
      End If

99999 Format ((3X,7I11))
    End Program f07pdfe


f07pefe.f90

    Program f07pefe

!     F07PEF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: dsptrf, dsptrs, nag_wp, x04caf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Integer                          :: i, ifail, info, j, ldb, n, nrhs
      Character (1)                    :: uplo
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: ap(:), b(:,:)
      Integer, Allocatable             :: ipiv(:)
!     .. Executable Statements ..
      Write (nout,*) 'F07PEF Example Program Results'
!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) n, nrhs
      ldb = n
      Allocate (ap(n*(n+1)/2),b(ldb,nrhs),ipiv(n))

!     Read A and B from data file

      Read (nin,*) uplo
      If (uplo=='U') Then
        Read (nin,*)((ap(i+j*(j-1)/2),j=i,n),i=1,n)
      Else If (uplo=='L') Then
        Read (nin,*)((ap(i+(2*n-j)*(j-1)/2),j=1,i),i=1,n)
      End If
      Read (nin,*)(b(i,1:nrhs),i=1,n)

!     Factorize A
!     The NAG name equivalent of dsptrf is f07pdf
      Call dsptrf(uplo,n,ap,ipiv,info)

      Write (nout,*)
      Flush (nout)
      If (info==0) Then

!       Compute solution
!       The NAG name equivalent of dsptrs is f07pef
        Call dsptrs(uplo,n,nrhs,ap,ipiv,b,ldb,info)

!       Print solution

!       ifail: behaviour on error exit
!              =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
        ifail = 0
        Call x04caf('General',' ',n,nrhs,b,ldb,'Solution(s)',ifail)

      Else
        Write (nout,*) 'The factor D is singular'
      End If

    End Program f07pefe


f07pgfe.f90

    Program f07pgfe

!     F07PGF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: dlansp => f06rdf, dspcon, dsptrf, nag_wp, x02ajf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: anorm, rcond
      Integer                          :: i, info, j, n
      Character (1)                    :: uplo
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: ap(:), work(:)
      Integer, Allocatable             :: ipiv(:), iwork(:)
!     .. Executable Statements ..
      Write (nout,*) 'F07PGF Example Program Results'
!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) n

      Allocate (ap(n*(n+1)/2),work(2*n),ipiv(n),iwork(n))

!     Read A from data file

      Read (nin,*) uplo
      If (uplo=='U') Then
        Read (nin,*)((ap(i+j*(j-1)/2),j=i,n),i=1,n)
      Else If (uplo=='L') Then
        Read (nin,*)((ap(i+(2*n-j)*(j-1)/2),j=1,i),i=1,n)
      End If

!     Compute norm of A
!     f06rdf is the NAG name equivalent of the LAPACK auxiliary dlansp
      anorm = dlansp('1-norm',uplo,n,ap,work)

!     Factorize A
!     The NAG name equivalent of dsptrf is f07pdf
      Call dsptrf(uplo,n,ap,ipiv,info)

      Write (nout,*)
      If (info==0) Then

!       Estimate condition number
!       The NAG name equivalent of dspcon is f07pgf
        Call dspcon(uplo,n,ap,ipiv,anorm,rcond,work,iwork,info)

        If (rcond>=x02ajf()) Then
          Write (nout,99999) 'Estimate of condition number =',                 &
            1.0_nag_wp/rcond
        Else
          Write (nout,*) 'A is singular to working precision'
        End If
      Else
        Write (nout,*) 'The factor D is singular'
      End If

99999 Format (1X,A,1P,E10.2)
    End Program f07pgfe


f07phfe.f90

    Program f07phfe

!     F07PHF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: dsprfs, dsptrf, dsptrs, nag_wp, x04caf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Integer                          :: i, ifail, info, j, ldb, ldx, len, n, &
                                          nrhs
      Character (1)                    :: uplo
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: afp(:), ap(:), b(:,:), berr(:),      &
                                          ferr(:), work(:), x(:,:)
      Integer, Allocatable             :: ipiv(:), iwork(:)
!     .. Executable Statements ..
      Write (nout,*) 'F07PHF Example Program Results'
!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) n, nrhs
      ldb = n
      ldx = n
      len = n*(n+1)/2
      Allocate (afp(len),ap(len),b(ldb,nrhs),berr(nrhs),ferr(nrhs),work(3*n),  &
        x(ldx,n),ipiv(n),iwork(n))

!     Read A and B from data file, and copy A to AFP and B to X

      Read (nin,*) uplo
      If (uplo=='U') Then
        Read (nin,*)((ap(i+j*(j-1)/2),j=i,n),i=1,n)
      Else If (uplo=='L') Then
        Read (nin,*)((ap(i+(2*n-j)*(j-1)/2),j=1,i),i=1,n)
      End If
      Read (nin,*)(b(i,1:nrhs),i=1,n)

      afp(1:len) = ap(1:len)
      x(1:n,1:nrhs) = b(1:n,1:nrhs)

!     Factorize A in the array AFP
!     The NAG name equivalent of dsptrf is f07pdf
      Call dsptrf(uplo,n,afp,ipiv,info)

      Write (nout,*)
      Flush (nout)
      If (info==0) Then

!       Compute solution in the array X
!       The NAG name equivalent of dsptrs is f07pef
        Call dsptrs(uplo,n,nrhs,afp,ipiv,x,ldx,info)

!       Improve solution, and compute backward errors and
!       estimated bounds on the forward errors

!       The NAG name equivalent of dsprfs is f07phf
        Call dsprfs(uplo,n,nrhs,ap,afp,ipiv,b,ldb,x,ldx,ferr,berr,work,iwork,  &
          info)

!       Print solution

!       ifail: behaviour on error exit
!              =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
        ifail = 0
        Call x04caf('General',' ',n,nrhs,x,ldx,'Solution(s)',ifail)

        Write (nout,*)
        Write (nout,*) 'Backward errors (machine-dependent)'
        Write (nout,99999) berr(1:nrhs)
        Write (nout,*) 'Estimated forward error bounds (machine-dependent)'
        Write (nout,99999) ferr(1:nrhs)
      Else
        Write (nout,*) 'The factor D is singular'
      End If

99999 Format ((3X,1P,7E11.1))
    End Program f07phfe


f07pjfe.f90

    Program f07pjfe

!     F07PJF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: dsptrf, dsptri, nag_wp, x04ccf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Integer                          :: i, ifail, info, j, n
      Character (1)                    :: uplo
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: ap(:), work(:)
      Integer, Allocatable             :: ipiv(:)
!     .. Executable Statements ..
      Write (nout,*) 'F07PJF Example Program Results'
!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) n

      Allocate (ap(n*(n+1)/2),work(n),ipiv(n))

!     Read A from data file

      Read (nin,*) uplo
      If (uplo=='U') Then
        Read (nin,*)((ap(i+j*(j-1)/2),j=i,n),i=1,n)
      Else If (uplo=='L') Then
        Read (nin,*)((ap(i+(2*n-j)*(j-1)/2),j=1,i),i=1,n)
      End If

!     Factorize A
!     The NAG name equivalent of dsptrf is f07pdf
      Call dsptrf(uplo,n,ap,ipiv,info)

      Write (nout,*)
      Flush (nout)
      If (info==0) Then

!       Compute inverse of A
!       The NAG name equivalent of dsptri is f07pjf
        Call dsptri(uplo,n,ap,ipiv,work,info)

!       Print inverse

!       ifail: behaviour on error exit
!              =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
        ifail = 0
        Call x04ccf(uplo,'Nonunit',n,ap,'Inverse',ifail)

      Else
        Write (nout,*) 'The factor D is singular'
      End If

    End Program f07pjfe


f07pnfe.f90

    Program f07pnfe

!     F07PNF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: nag_wp, x04ddf, zhpsv
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
      Character (1), Parameter         :: uplo = 'U'
!     .. Local Scalars ..
      Integer                          :: i, ifail, info, j, n
!     .. Local Arrays ..
      Complex (Kind=nag_wp), Allocatable :: ap(:), b(:)
      Integer, Allocatable             :: ipiv(:)
      Character (1)                    :: clabs(1), rlabs(1)
!     .. Executable Statements ..
      Write (nout,*) 'F07PNF Example Program Results'
      Write (nout,*)
!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) n

      Allocate (ap((n*(n+1))/2),b(n),ipiv(n))

!     Read the upper or lower triangular part of the matrix A from
!     data file

      If (uplo=='U') Then
        Read (nin,*)((ap(i+(j*(j-1))/2),j=i,n),i=1,n)
      Else If (uplo=='L') Then
        Read (nin,*)((ap(i+((2*n-j)*(j-1))/2),j=1,i),i=1,n)
      End If

!     Read b from data file

      Read (nin,*) b(1:n)

!     Solve the equations Ax = b for x
!     The NAG name equivalent of zhpsv is f07pnf
      Call zhpsv(uplo,n,1,ap,ipiv,b,n,info)

      If (info==0) Then

!       Print solution

        Write (nout,*) 'Solution'
        Write (nout,99999) b(1:n)

!       Print details of factorization

        Write (nout,*)
        Flush (nout)

!       ifail: behaviour on error exit
!              =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
        ifail = 0
        Call x04ddf(uplo,'Non-unit diagonal',n,ap,'Bracketed','F7.4',          &
          'Details of factorization','Integer',rlabs,'Integer',clabs,80,0,     &
          ifail)

!       Print pivot indices

        Write (nout,*)
        Write (nout,*) 'Pivot indices'
        Write (nout,99998) ipiv(1:n)

      Else
        Write (nout,99997) 'The diagonal block ', info, ' of D is zero'
      End If

99999 Format ((3X,4(' (',F7.4,',',F7.4,')',:)))
99998 Format (1X,7I11)
99997 Format (1X,A,I3,A)
    End Program f07pnfe


f07ppfe.f90

    Program f07ppfe

!     F07PPF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: nag_wp, x04dbf, zhpsvx
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
      Character (1), Parameter         :: uplo = 'U'
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: rcond
      Integer                          :: i, ifail, info, j, ldb, ldx, n, nrhs
!     .. Local Arrays ..
      Complex (Kind=nag_wp), Allocatable :: afp(:), ap(:), b(:,:), work(:),    &
                                          x(:,:)
      Real (Kind=nag_wp), Allocatable  :: berr(:), ferr(:), rwork(:)
      Integer, Allocatable             :: ipiv(:)
      Character (1)                    :: clabs(1), rlabs(1)
!     .. Executable Statements ..
      Write (nout,*) 'F07PPF Example Program Results'
      Write (nout,*)
      Flush (nout)
!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) n, nrhs
      ldb = n
      ldx = n
      Allocate (afp((n*(n+1))/2),ap((n*(n+1))/2),b(ldb,nrhs),work(2*n),x(ldx,  &
        nrhs),berr(nrhs),ferr(nrhs),rwork(n),ipiv(n))

!     Read the upper or lower triangular part of the matrix A from
!     data file

      If (uplo=='U') Then
        Read (nin,*)((ap(i+(j*(j-1))/2),j=i,n),i=1,n)
      Else If (uplo=='L') Then
        Read (nin,*)((ap(i+((2*n-j)*(j-1))/2),j=1,i),i=1,n)
      End If

!     Read B from data file

      Read (nin,*)(b(i,1:nrhs),i=1,n)

!     Solve the equations AX = B for X
!     The NAG name equivalent of zhpsvx is f07ppf
      Call zhpsvx('Not factored',uplo,n,nrhs,ap,afp,ipiv,b,ldb,x,ldx,rcond,    &
        ferr,berr,work,rwork,info)

      If ((info==0) .Or. (info==n+1)) Then

!       Print solution, error bounds and condition number

!       ifail: behaviour on error exit
!              =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
        ifail = 0
        Call x04dbf('General',' ',n,nrhs,x,ldx,'Bracketed','F7.4',             &
          'Solution(s)','Integer',rlabs,'Integer',clabs,80,0,ifail)

        Write (nout,*)
        Write (nout,*) 'Backward errors (machine-dependent)'
        Write (nout,99999) berr(1:nrhs)
        Write (nout,*)
        Write (nout,*) 'Estimated forward error bounds (machine-dependent)'
        Write (nout,99999) ferr(1:nrhs)
        Write (nout,*)
        Write (nout,*) 'Estimate of reciprocal condition number'
        Write (nout,99999) rcond
        Write (nout,*)

        If (info==n+1) Then
          Write (nout,*)
          Write (nout,*) 'The matrix A is singular to working precision'
        End If
      Else
        Write (nout,99998) 'The diagonal block ', info, ' of D is zero'
      End If

99999 Format ((3X,1P,7E11.1))
99998 Format (1X,A,I3,A)
    End Program f07ppfe


f07prfe.f90

    Program f07prfe

!     F07PRF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: nag_wp, x04ddf, zhptrf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Integer                          :: i, ifail, info, j, n
      Character (1)                    :: uplo
!     .. Local Arrays ..
      Complex (Kind=nag_wp), Allocatable :: ap(:)
      Integer, Allocatable             :: ipiv(:)
      Character (1)                    :: clabs(1), rlabs(1)
!     .. Executable Statements ..
      Write (nout,*) 'F07PRF Example Program Results'
!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) n

      Allocate (ap(n*(n+1)/2),ipiv(n))

!     Read A from data file

      Read (nin,*) uplo
      If (uplo=='U') Then
        Read (nin,*)((ap(i+j*(j-1)/2),j=i,n),i=1,n)
      Else If (uplo=='L') Then
        Read (nin,*)((ap(i+(2*n-j)*(j-1)/2),j=1,i),i=1,n)
      End If

!     Factorize A
!     The NAG name equivalent of zhptrf is f07prf
      Call zhptrf(uplo,n,ap,ipiv,info)

      Write (nout,*)
      Flush (nout)

!     Print details of factorization

!     ifail: behaviour on error exit
!            =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
      ifail = 0
      Call x04ddf(uplo,'Nonunit',n,ap,'Bracketed','F7.4',                      &
        'Details of factorization','Integer',rlabs,'Integer',clabs,80,0,ifail)

!     Print pivot indices

      Write (nout,*)
      Write (nout,*) 'IPIV'
      Write (nout,99999) ipiv(1:n)

      If (info/=0) Then
        Write (nout,*) 'The factor D is singular'
      End If

99999 Format ((1X,I12,3I18))
    End Program f07prfe


f07psfe.f90

    Program f07psfe

!     F07PSF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: nag_wp, x04dbf, zhptrf, zhptrs
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Integer                          :: i, ifail, info, j, ldb, n, nrhs
      Character (1)                    :: uplo
!     .. Local Arrays ..
      Complex (Kind=nag_wp), Allocatable :: ap(:), b(:,:)
      Integer, Allocatable             :: ipiv(:)
      Character (1)                    :: clabs(1), rlabs(1)
!     .. Executable Statements ..
      Write (nout,*) 'F07PSF Example Program Results'
!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) n, nrhs
      ldb = n
      Allocate (ap(n*(n+1)/2),b(ldb,nrhs),ipiv(n))

!     Read A and B from data file

      Read (nin,*) uplo
      If (uplo=='U') Then
        Read (nin,*)((ap(i+j*(j-1)/2),j=i,n),i=1,n)
      Else If (uplo=='L') Then
        Read (nin,*)((ap(i+(2*n-j)*(j-1)/2),j=1,i),i=1,n)
      End If
      Read (nin,*)(b(i,1:nrhs),i=1,n)

!     Factorize A
!     The NAG name equivalent of zhptrf is f07prf
      Call zhptrf(uplo,n,ap,ipiv,info)

      Write (nout,*)
      Flush (nout)
      If (info==0) Then

!       Compute solution
!       The NAG name equivalent of zhptrs is f07psf
        Call zhptrs(uplo,n,nrhs,ap,ipiv,b,ldb,info)

!       Print solution

!       ifail: behaviour on error exit
!              =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
        ifail = 0
        Call x04dbf('General',' ',n,nrhs,b,ldb,'Bracketed','F7.4',             &
          'Solution(s)','Integer',rlabs,'Integer',clabs,80,0,ifail)

      Else
        Write (nout,*) 'The factor D is singular'
      End If

    End Program f07psfe


f07pufe.f90

    Program f07pufe

!     F07PUF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: nag_wp, x02ajf, zhpcon, zhptrf, zlanhp => f06udf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: anorm, rcond
      Integer                          :: i, info, j, n
      Character (1)                    :: uplo
!     .. Local Arrays ..
      Complex (Kind=nag_wp), Allocatable :: ap(:), work(:)
      Real (Kind=nag_wp), Allocatable  :: rwork(:)
      Integer, Allocatable             :: ipiv(:)
!     .. Executable Statements ..
      Write (nout,*) 'F07PUF Example Program Results'
!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) n

      Allocate (ap(n*(n+1)/2),work(2*n),rwork(n),ipiv(n))

!     Read A from data file

      Read (nin,*) uplo
      If (uplo=='U') Then
        Read (nin,*)((ap(i+j*(j-1)/2),j=i,n),i=1,n)
      Else If (uplo=='L') Then
        Read (nin,*)((ap(i+(2*n-j)*(j-1)/2),j=1,i),i=1,n)
      End If

!     Compute norm of A
!     f06udf is the NAG name equivalent of the LAPACK auxiliary zlanhp
      anorm = zlanhp('1-norm',uplo,n,ap,rwork)

!     Factorize A
!     The NAG name equivalent of zhptrf is f07prf
      Call zhptrf(uplo,n,ap,ipiv,info)

      Write (nout,*)
      If (info==0) Then

!       Estimate condition number
!       The NAG name equivalent of zhpcon is f07puf
        Call zhpcon(uplo,n,ap,ipiv,anorm,rcond,work,info)

        If (rcond>=x02ajf()) Then
          Write (nout,99999) 'Estimate of condition number =',                 &
            1.0_nag_wp/rcond
        Else
          Write (nout,*) 'A is singular to working precision'
        End If
      Else
        Write (nout,*) 'The factor D is singular'
      End If

99999 Format (1X,A,1P,E10.2)
    End Program f07pufe


f07pvfe.f90

    Program f07pvfe

!     F07PVF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: nag_wp, x04dbf, zhprfs, zhptrf, zhptrs
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Integer                          :: aplen, i, ifail, info, j, ldb, ldx,  &
                                          n, nrhs
      Character (1)                    :: uplo
!     .. Local Arrays ..
      Complex (Kind=nag_wp), Allocatable :: afp(:), ap(:), b(:,:), work(:),    &
                                          x(:,:)
      Real (Kind=nag_wp), Allocatable  :: berr(:), ferr(:), rwork(:)
      Integer, Allocatable             :: ipiv(:)
      Character (1)                    :: clabs(1), rlabs(1)
!     .. Executable Statements ..
      Write (nout,*) 'F07PVF Example Program Results'
!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) n, nrhs
      ldb = n
      ldx = n
      aplen = n*(n+1)/2
      Allocate (afp(aplen),ap(aplen),b(ldb,nrhs),work(2*n),x(ldx,n),           &
        berr(nrhs),ferr(nrhs),rwork(n),ipiv(n))

!     Read A and B from data file, and copy A to AFP and B to X

      Read (nin,*) uplo
      If (uplo=='U') Then
        Read (nin,*)((ap(i+j*(j-1)/2),j=i,n),i=1,n)
      Else If (uplo=='L') Then
        Read (nin,*)((ap(i+(2*n-j)*(j-1)/2),j=1,i),i=1,n)
      End If
      Read (nin,*)(b(i,1:nrhs),i=1,n)

      afp(1:aplen) = ap(1:aplen)
      x(1:n,1:nrhs) = b(1:n,1:nrhs)

!     Factorize A in the array AFP
!     The NAG name equivalent of zhptrf is f07prf
      Call zhptrf(uplo,n,afp,ipiv,info)

      Write (nout,*)
      Flush (nout)
      If (info==0) Then

!       Compute solution in the array X
!       The NAG name equivalent of zhptrs is f07psf
        Call zhptrs(uplo,n,nrhs,afp,ipiv,x,ldx,info)

!       Improve solution, and compute backward errors and
!       estimated bounds on the forward errors

!       The NAG name equivalent of zhprfs is f07puf
        Call zhprfs(uplo,n,nrhs,ap,afp,ipiv,b,ldb,x,ldx,ferr,berr,work,rwork,  &
          info)

!       Print solution

!       ifail: behaviour on error exit
!              =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
        ifail = 0
        Call x04dbf('General',' ',n,nrhs,x,ldx,'Bracketed','F7.4',             &
          'Solution(s)','Integer',rlabs,'Integer',clabs,80,0,ifail)

        Write (nout,*)
        Write (nout,*) 'Backward errors (machine-dependent)'
        Write (nout,99999) berr(1:nrhs)
        Write (nout,*) 'Estimated forward error bounds (machine-dependent)'
        Write (nout,99999) ferr(1:nrhs)
      Else
        Write (nout,*) 'The factor D is singular'
      End If

99999 Format ((5X,1P,4(E11.1,7X)))
    End Program f07pvfe


f07pwfe.f90

    Program f07pwfe

!     F07PWF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: nag_wp, x04ddf, zhptrf, zhptri
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Integer                          :: i, ifail, info, j, n
      Character (1)                    :: uplo
!     .. Local Arrays ..
      Complex (Kind=nag_wp), Allocatable :: ap(:), work(:)
      Integer, Allocatable             :: ipiv(:)
      Character (1)                    :: clabs(1), rlabs(1)
!     .. Executable Statements ..
      Write (nout,*) 'F07PWF Example Program Results'
!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) n

      Allocate (ap(n*(n+1)/2),work(n),ipiv(n))

!     Read A from data file

      Read (nin,*) uplo
      If (uplo=='U') Then
        Read (nin,*)((ap(i+j*(j-1)/2),j=i,n),i=1,n)
      Else If (uplo=='L') Then
        Read (nin,*)((ap(i+(2*n-j)*(j-1)/2),j=1,i),i=1,n)
      End If

!     Factorize A
!     The NAG name equivalent of zhptrf is f07prf
      Call zhptrf(uplo,n,ap,ipiv,info)

      Write (nout,*)
      Flush (nout)
      If (info==0) Then

!       Compute inverse of A
!       The NAG name equivalent of zhptri is f07pwf
        Call zhptri(uplo,n,ap,ipiv,work,info)

!       Print inverse

!       ifail: behaviour on error exit
!              =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
        ifail = 0
        Call x04ddf(uplo,'Nonunit',n,ap,'Bracketed','F7.4','Inverse',          &
          'Integer',rlabs,'Integer',clabs,80,0,ifail)

      Else
        Write (nout,*) 'The factor D is singular'
      End If

    End Program f07pwfe


f07qnfe.f90

    Program f07qnfe

!     F07QNF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: nag_wp, x04ddf, zspsv
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
      Character (1), Parameter         :: uplo = 'U'
!     .. Local Scalars ..
      Integer                          :: i, ifail, info, j, n
!     .. Local Arrays ..
      Complex (Kind=nag_wp), Allocatable :: ap(:), b(:)
      Integer, Allocatable             :: ipiv(:)
      Character (1)                    :: clabs(1), rlabs(1)
!     .. Executable Statements ..
      Write (nout,*) 'F07QNF Example Program Results'
      Write (nout,*)
!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) n

      Allocate (ap((n*(n+1))/2),b(n),ipiv(n))

!     Read the upper or lower triangular part of the matrix A from
!     data file

      If (uplo=='U') Then
        Read (nin,*)((ap(i+(j*(j-1))/2),j=i,n),i=1,n)
      Else If (uplo=='L') Then
        Read (nin,*)((ap(i+((2*n-j)*(j-1))/2),j=1,i),i=1,n)
      End If

!     Read b from data file

      Read (nin,*) b(1:n)

!     Solve the equations Ax = b for x
!     The NAG name equivalent of zspsv is f07qnf
      Call zspsv(uplo,n,1,ap,ipiv,b,n,info)

      If (info==0) Then

!       Print solution

        Write (nout,*) 'Solution'
        Write (nout,99999) b(1:n)

!       Print details of factorization

        Write (nout,*)
        Flush (nout)

!       ifail: behaviour on error exit
!              =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
        ifail = 0
        Call x04ddf(uplo,'Non-unit diagonal',n,ap,'Bracketed','F7.4',          &
          'Details of factorization','Integer',rlabs,'Integer',clabs,80,0,     &
          ifail)

!       Print pivot indices

        Write (nout,*)
        Write (nout,*) 'Pivot indices'
        Write (nout,99998) ipiv(1:n)

      Else
        Write (nout,99997) 'The diagonal block ', info, ' of D is zero'
      End If

99999 Format ((3X,4(' (',F7.4,',',F7.4,')',:)))
99998 Format (1X,7I11)
99997 Format (1X,A,I3,A)
    End Program f07qnfe


f07qpfe.f90

    Program f07qpfe

!     F07QPF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: nag_wp, x04dbf, zspsvx
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
      Character (1), Parameter         :: uplo = 'U'
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: rcond
      Integer                          :: i, ifail, info, j, ldb, ldx, n, nrhs
!     .. Local Arrays ..
      Complex (Kind=nag_wp), Allocatable :: afp(:), ap(:), b(:,:), work(:),    &
                                          x(:,:)
      Real (Kind=nag_wp), Allocatable  :: berr(:), ferr(:), rwork(:)
      Integer, Allocatable             :: ipiv(:)
      Character (1)                    :: clabs(1), rlabs(1)
!     .. Executable Statements ..
      Write (nout,*) 'F07QPF Example Program Results'
      Write (nout,*)
      Flush (nout)
!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) n, nrhs
      ldb = n
      ldx = n
      Allocate (afp((n*(n+1))/2),ap((n*(n+1))/2),b(ldb,nrhs),work(2*n),x(ldx,  &
        nrhs),berr(nrhs),ferr(nrhs),rwork(n),ipiv(n))

!     Read the upper or lower triangular part of the matrix A from
!     data file

      If (uplo=='U') Then
        Read (nin,*)((ap(i+(j*(j-1))/2),j=i,n),i=1,n)
      Else If (uplo=='L') Then
        Read (nin,*)((ap(i+((2*n-j)*(j-1))/2),j=1,i),i=1,n)
      End If

!     Read B from data file

      Read (nin,*)(b(i,1:nrhs),i=1,n)

!     Solve the equations AX = B for X
!     The NAG name equivalent of zspsvx is f06qpf
      Call zspsvx('Not factored',uplo,n,nrhs,ap,afp,ipiv,b,ldb,x,ldx,rcond,    &
        ferr,berr,work,rwork,info)

      If ((info==0) .Or. (info==n+1)) Then

!       Print solution, error bounds and condition number

!       ifail: behaviour on error exit
!              =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
        ifail = 0
        Call x04dbf('General',' ',n,nrhs,x,ldx,'Bracketed','F7.4',             &
          'Solution(s)','Integer',rlabs,'Integer',clabs,80,0,ifail)

        Write (nout,*)
        Write (nout,*) 'Backward errors (machine-dependent)'
        Write (nout,99999) berr(1:nrhs)
        Write (nout,*)
        Write (nout,*) 'Estimated forward error bounds (machine-dependent)'
        Write (nout,99999) ferr(1:nrhs)
        Write (nout,*)
        Write (nout,*) 'Estimate of reciprocal condition number'
        Write (nout,99999) rcond
        Write (nout,*)

        If (info==n+1) Then
          Write (nout,*)
          Write (nout,*) 'The matrix A is singular to working precision'
        End If
      Else
        Write (nout,99998) 'The diagonal block ', info, ' of D is zero'
      End If

99999 Format ((3X,1P,7E11.1))
99998 Format (1X,A,I3,A)
    End Program f07qpfe


f07qrfe.f90

    Program f07qrfe

!     F07QRF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: nag_wp, x04ddf, zsptrf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Integer                          :: i, ifail, info, j, n
      Character (1)                    :: uplo
!     .. Local Arrays ..
      Complex (Kind=nag_wp), Allocatable :: ap(:)
      Integer, Allocatable             :: ipiv(:)
      Character (1)                    :: clabs(1), rlabs(1)
!     .. Executable Statements ..
      Write (nout,*) 'F07QRF Example Program Results'
!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) n

      Allocate (ap(n*(n+1)/2),ipiv(n))

!     Read A from data file

      Read (nin,*) uplo
      If (uplo=='U') Then
        Read (nin,*)((ap(i+j*(j-1)/2),j=i,n),i=1,n)
      Else If (uplo=='L') Then
        Read (nin,*)((ap(i+(2*n-j)*(j-1)/2),j=1,i),i=1,n)
      End If

!     Factorize A
!     The NAG name equivalent of zsptrf is f07qrf
      Call zsptrf(uplo,n,ap,ipiv,info)

      Write (nout,*)
      Flush (nout)

!     Print details of factorization

!     ifail: behaviour on error exit
!            =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
      ifail = 0
      Call x04ddf(uplo,'Nonunit',n,ap,'Bracketed','F7.4',                      &
        'Details of factorization','Integer',rlabs,'Integer',clabs,80,0,ifail)

!     Print pivot indices

      Write (nout,*)
      Write (nout,*) 'IPIV'
      Write (nout,99999) ipiv(1:n)

      If (info/=0) Then
        Write (nout,*) 'The factor D is singular'
      End If

99999 Format ((1X,I12,3I18))
    End Program f07qrfe


f07qsfe.f90

    Program f07qsfe

!     F07QSF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: nag_wp, x04dbf, zsptrf, zsptrs
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Integer                          :: i, ifail, info, j, ldb, n, nrhs
      Character (1)                    :: uplo
!     .. Local Arrays ..
      Complex (Kind=nag_wp), Allocatable :: ap(:), b(:,:)
      Integer, Allocatable             :: ipiv(:)
      Character (1)                    :: clabs(1), rlabs(1)
!     .. Executable Statements ..
      Write (nout,*) 'F07QSF Example Program Results'
!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) n, nrhs
      ldb = n
      Allocate (ap(n*(n+1)/2),b(ldb,nrhs),ipiv(n))

!     Read A and B from data file

      Read (nin,*) uplo
      If (uplo=='U') Then
        Read (nin,*)((ap(i+j*(j-1)/2),j=i,n),i=1,n)
      Else If (uplo=='L') Then
        Read (nin,*)((ap(i+(2*n-j)*(j-1)/2),j=1,i),i=1,n)
      End If
      Read (nin,*)(b(i,1:nrhs),i=1,n)

!     Factorize A
!     The NAG name equivalent of zsptrf is f07qrf
      Call zsptrf(uplo,n,ap,ipiv,info)

      Write (nout,*)
      Flush (nout)
      If (info==0) Then

!       Compute solution
!       The NAG name equivalent of zsptrs is f07qsf
        Call zsptrs(uplo,n,nrhs,ap,ipiv,b,ldb,info)

!       Print solution

!       ifail: behaviour on error exit
!              =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
        ifail = 0
        Call x04dbf('General',' ',n,nrhs,b,ldb,'Bracketed','F7.4',             &
          'Solution(s)','Integer',rlabs,'Integer',clabs,80,0,ifail)

      Else
        Write (nout,*) 'The factor D is singular'
      End If

    End Program f07qsfe


f07qufe.f90

    Program f07qufe

!     F07QUF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: nag_wp, x02ajf, zlansp => f06ugf, zspcon, zsptrf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: anorm, rcond
      Integer                          :: i, info, j, n
      Character (1)                    :: uplo
!     .. Local Arrays ..
      Complex (Kind=nag_wp), Allocatable :: ap(:), work(:)
      Real (Kind=nag_wp), Allocatable  :: rwork(:)
      Integer, Allocatable             :: ipiv(:)
!     .. Executable Statements ..
      Write (nout,*) 'F07QUF Example Program Results'
!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) n

      Allocate (ap(n*(n+1)/2),work(2*n),rwork(n),ipiv(n))

!     Read A from data file

      Read (nin,*) uplo
      If (uplo=='U') Then
        Read (nin,*)((ap(i+j*(j-1)/2),j=i,n),i=1,n)
      Else If (uplo=='L') Then
        Read (nin,*)((ap(i+(2*n-j)*(j-1)/2),j=1,i),i=1,n)
      End If

!     Compute norm of A
!     f06ugf is the NAG name equivalent of the LAPACK auxiliary zlansp
      anorm = zlansp('1-norm',uplo,n,ap,rwork)

!     Factorize A
!     The NAG name equivalent of zsptrf is f07qrf
      Call zsptrf(uplo,n,ap,ipiv,info)

      Write (nout,*)
      If (info==0) Then

!       Estimate condition number
!       The NAG name equivalent of zspcon is f07quf
        Call zspcon(uplo,n,ap,ipiv,anorm,rcond,work,info)

        If (rcond>=x02ajf()) Then
          Write (nout,99999) 'Estimate of condition number =',                 &
            1.0E0_nag_wp/rcond
        Else
          Write (nout,*) 'A is singular to working precision'
        End If
      Else
        Write (nout,*) 'The factor D is singular'
      End If

99999 Format (1X,A,1P,E10.2)
    End Program f07qufe


f07qvfe.f90

    Program f07qvfe

!     F07QVF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: nag_wp, x04dbf, zsprfs, zsptrf, zsptrs
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Integer                          :: aplen, i, ifail, info, j, ldb, ldx,  &
                                          n, nrhs
      Character (1)                    :: uplo
!     .. Local Arrays ..
      Complex (Kind=nag_wp), Allocatable :: afp(:), ap(:), b(:,:), work(:),    &
                                          x(:,:)
      Real (Kind=nag_wp), Allocatable  :: berr(:), ferr(:), rwork(:)
      Integer, Allocatable             :: ipiv(:)
      Character (1)                    :: clabs(1), rlabs(1)
!     .. Executable Statements ..
      Write (nout,*) 'F07QVF Example Program Results'
!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) n, nrhs
      ldb = n
      ldx = n
      aplen = n*(n+1)/2
      Allocate (afp(aplen),ap(aplen),b(ldb,nrhs),work(2*n),x(ldx,n),           &
        berr(nrhs),ferr(nrhs),rwork(n),ipiv(n))

!     Read A and B from data file, and copy A to AFP and B to X

      Read (nin,*) uplo
      If (uplo=='U') Then
        Read (nin,*)((ap(i+j*(j-1)/2),j=i,n),i=1,n)
      Else If (uplo=='L') Then
        Read (nin,*)((ap(i+(2*n-j)*(j-1)/2),j=1,i),i=1,n)
      End If
      Read (nin,*)(b(i,1:nrhs),i=1,n)

      afp(1:aplen) = ap(1:aplen)
      x(1:n,1:nrhs) = b(1:n,1:nrhs)

!     Factorize A in the array AFP
!     The NAG name equivalent of zsptrf is f07qrf
      Call zsptrf(uplo,n,afp,ipiv,info)

      Write (nout,*)
      Flush (nout)
      If (info==0) Then

!       Compute solution in the array X
!       The NAG name equivalent of zsptrs is f07qsf
        Call zsptrs(uplo,n,nrhs,afp,ipiv,x,ldx,info)

!       Improve solution, and compute backward errors and
!       estimated bounds on the forward errors

!       The NAG name equivalent of zsprfs is f07qvf
        Call zsprfs(uplo,n,nrhs,ap,afp,ipiv,b,ldb,x,ldx,ferr,berr,work,rwork,  &
          info)

!       Print solution

!       ifail: behaviour on error exit
!              =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
        ifail = 0
        Call x04dbf('General',' ',n,nrhs,x,ldx,'Bracketed','F7.4',             &
          'Solution(s)','Integer',rlabs,'Integer',clabs,80,0,ifail)

        Write (nout,*)
        Write (nout,*) 'Backward errors (machine-dependent)'
        Write (nout,99999) berr(1:nrhs)
        Write (nout,*) 'Estimated forward error bounds (machine-dependent)'
        Write (nout,99999) ferr(1:nrhs)
      Else
        Write (nout,*) 'The factor D is singular'
      End If

99999 Format ((5X,1P,4(E11.1,7X)))
    End Program f07qvfe


f07qwfe.f90

    Program f07qwfe

!     F07QWF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: nag_wp, x04ddf, zsptrf, zsptri
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Integer                          :: i, ifail, info, j, n
      Character (1)                    :: uplo
!     .. Local Arrays ..
      Complex (Kind=nag_wp), Allocatable :: ap(:), work(:)
      Integer, Allocatable             :: ipiv(:)
      Character (1)                    :: clabs(1), rlabs(1)
!     .. Executable Statements ..
      Write (nout,*) 'F07QWF Example Program Results'
!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) n

      Allocate (ap(n*(n+1)/2),work(n),ipiv(n))

!     Read A from data file

      Read (nin,*) uplo
      If (uplo=='U') Then
        Read (nin,*)((ap(i+j*(j-1)/2),j=i,n),i=1,n)
      Else If (uplo=='L') Then
        Read (nin,*)((ap(i+(2*n-j)*(j-1)/2),j=1,i),i=1,n)
      End If

!     Factorize A
!     The NAG name equivalent of zsptrf is f07qrf
      Call zsptrf(uplo,n,ap,ipiv,info)

      Write (nout,*)
      Flush (nout)
      If (info==0) Then

!       Compute inverse of A
!       The NAG name equivalent of zsptri is f07qwf
        Call zsptri(uplo,n,ap,ipiv,work,info)

!       Print inverse

!       ifail: behaviour on error exit
!              =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
        ifail = 0
        Call x04ddf(uplo,'Nonunit',n,ap,'Bracketed','F7.4','Inverse',          &
          'Integer',rlabs,'Integer',clabs,80,0,ifail)

      Else
        Write (nout,*) 'The factor D is singular'
      End If

    End Program f07qwfe


f07tefe.f90

    Program f07tefe

!     F07TEF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: dtrtrs, nag_wp, x04caf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
      Character (1), Parameter         :: diag = 'N', trans = 'N'
!     .. Local Scalars ..
      Integer                          :: i, ifail, info, lda, ldb, n, nrhs
      Character (1)                    :: uplo
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: a(:,:), b(:,:)
!     .. Executable Statements ..
      Write (nout,*) 'F07TEF Example Program Results'
!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) n, nrhs
      lda = n
      ldb = n
      Allocate (a(lda,n),b(ldb,nrhs))

!     Read A and B from data file

      Read (nin,*) uplo
      If (uplo=='U') Then
        Read (nin,*)(a(i,i:n),i=1,n)
      Else If (uplo=='L') Then
        Read (nin,*)(a(i,1:i),i=1,n)
      End If
      Read (nin,*)(b(i,1:nrhs),i=1,n)

!     Compute solution

!     The NAG name equivalent of dtrtrs is f07tef
      Call dtrtrs(uplo,trans,diag,n,nrhs,a,lda,b,ldb,info)

!     Print solution

      Write (nout,*)
      Flush (nout)
      If (info==0) Then

!       ifail: behaviour on error exit
!              =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
        ifail = 0
        Call x04caf('General',' ',n,nrhs,b,ldb,'Solution(s)',ifail)

      Else
        Write (nout,*) 'A is singular'
      End If

    End Program f07tefe


f07tgfe.f90

    Program f07tgfe

!     F07TGF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: dtrcon, nag_wp, x02ajf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
      Character (1), Parameter         :: diag = 'N', norm = '1'
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: rcond
      Integer                          :: i, info, lda, n
      Character (1)                    :: uplo
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: a(:,:), work(:)
      Integer, Allocatable             :: iwork(:)
!     .. Executable Statements ..
      Write (nout,*) 'F07TGF Example Program Results'
!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) n
      lda = n
      Allocate (a(lda,n),work(3*n),iwork(n))

!     Read A from data file

      Read (nin,*) uplo
      If (uplo=='U') Then
        Read (nin,*)(a(i,i:n),i=1,n)
      Else If (uplo=='L') Then
        Read (nin,*)(a(i,1:i),i=1,n)
      End If

!     Estimate condition number
!     The NAG name equivalent of dtrcon is f07tgf
      Call dtrcon(norm,uplo,diag,n,a,lda,rcond,work,iwork,info)

      Write (nout,*)
      If (rcond>=x02ajf()) Then
        Write (nout,99999) 'Estimate of condition number =',                   &
          1.0E0_nag_wp/rcond
      Else
        Write (nout,*) 'A is singular to working precision'
      End If

99999 Format (1X,A,1P,E10.2)
    End Program f07tgfe


f07thfe.f90

    Program f07thfe

!     F07THF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: dtrrfs, dtrtrs, nag_wp, x04caf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
      Character (1), Parameter         :: diag = 'N', trans = 'N'
!     .. Local Scalars ..
      Integer                          :: i, ifail, info, lda, ldb, ldx, n,    &
                                          nrhs
      Character (1)                    :: uplo
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: a(:,:), b(:,:), berr(:), ferr(:),    &
                                          work(:), x(:,:)
      Integer, Allocatable             :: iwork(:)
!     .. Executable Statements ..
      Write (nout,*) 'F07THF Example Program Results'
!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) n, nrhs
      lda = n
      ldb = n
      ldx = n
      Allocate (a(lda,n),b(ldb,nrhs),berr(nrhs),ferr(nrhs),work(3*n),x(ldx,n), &
        iwork(n))

!     Read A and B from data file, and copy B to X

      Read (nin,*) uplo
      If (uplo=='U') Then
        Read (nin,*)(a(i,i:n),i=1,n)
      Else If (uplo=='L') Then
        Read (nin,*)(a(i,1:i),i=1,n)
      End If
      Read (nin,*)(b(i,1:nrhs),i=1,n)

      x(1:n,1:nrhs) = b(1:n,1:nrhs)

!     Compute solution in the array X
!     The NAG name equivalent of dtrtrs is f07tef
      Call dtrtrs(uplo,trans,diag,n,nrhs,a,lda,x,ldx,info)

!     Compute backward errors and estimated bounds on the
!     forward errors

!     The NAG name equivalent of dtrrfs is f07thf
      Call dtrrfs(uplo,trans,diag,n,nrhs,a,lda,b,ldb,x,ldx,ferr,berr,work,     &
        iwork,info)

!     Print solution

      Write (nout,*)
      Flush (nout)

!     ifail: behaviour on error exit
!             =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
      ifail = 0
      Call x04caf('General',' ',n,nrhs,x,ldx,'Solution(s)',ifail)

      Write (nout,*)
      Write (nout,*) 'Backward errors (machine-dependent)'
      Write (nout,99999) berr(1:nrhs)
      Write (nout,*) 'Estimated forward error bounds (machine-dependent)'
      Write (nout,99999) ferr(1:nrhs)

99999 Format ((3X,1P,7E11.1))
    End Program f07thfe


f07tjfe.f90

    Program f07tjfe

!     F07TJF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: dtrtri, nag_wp, x04caf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
      Character (1), Parameter         :: diag = 'N'
!     .. Local Scalars ..
      Integer                          :: i, ifail, info, lda, n
      Character (1)                    :: uplo
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: a(:,:)
!     .. Executable Statements ..
      Write (nout,*) 'F07TJF Example Program Results'
!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) n
      lda = n
      Allocate (a(lda,n))

!     Read A from data file

      Read (nin,*) uplo
      If (uplo=='U') Then
        Read (nin,*)(a(i,i:n),i=1,n)
      Else If (uplo=='L') Then
        Read (nin,*)(a(i,1:i),i=1,n)
      End If

!     Compute inverse of A
!     The NAG name equivalent of dtrtri is f07tjf
      Call dtrtri(uplo,diag,n,a,lda,info)

!     Print inverse

      Write (nout,*)
      Flush (nout)

!     ifail: behaviour on error exit
!             =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
      ifail = 0
      Call x04caf(uplo,diag,n,n,a,lda,'Inverse',ifail)

    End Program f07tjfe


f07tsfe.f90

    Program f07tsfe

!     F07TSF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: nag_wp, x04dbf, ztrtrs
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
      Character (1), Parameter         :: diag = 'N', trans = 'N'
!     .. Local Scalars ..
      Integer                          :: i, ifail, info, lda, ldb, n, nrhs
      Character (1)                    :: uplo
!     .. Local Arrays ..
      Complex (Kind=nag_wp), Allocatable :: a(:,:), b(:,:)
      Character (1)                    :: clabs(1), rlabs(1)
!     .. Executable Statements ..
      Write (nout,*) 'F07TSF Example Program Results'
!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) n, nrhs
      lda = n
      ldb = n
      Allocate (a(lda,n),b(ldb,nrhs))

!     Read A and B from data file

      Read (nin,*) uplo
      If (uplo=='U') Then
        Read (nin,*)(a(i,i:n),i=1,n)
      Else If (uplo=='L') Then
        Read (nin,*)(a(i,1:i),i=1,n)
      End If
      Read (nin,*)(b(i,1:nrhs),i=1,n)

!     Compute solution
!     The NAG name equivalent of ztrtrs is f07tsf
      Call ztrtrs(uplo,trans,diag,n,nrhs,a,lda,b,ldb,info)

!     Print solution

      Write (nout,*)
      Flush (nout)
      If (info==0) Then

!       ifail: behaviour on error exit
!              =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
        ifail = 0
        Call x04dbf('General',' ',n,nrhs,b,ldb,'Bracketed','F7.4',             &
          'Solution(s)','Integer',rlabs,'Integer',clabs,80,0,ifail)

      Else
        Write (nout,*) 'A is singular'
      End If

    End Program f07tsfe


f07tufe.f90

    Program f07tufe

!     F07TUF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: nag_wp, x02ajf, ztrcon
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
      Character (1), Parameter         :: diag = 'N', norm = '1'
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: rcond
      Integer                          :: i, info, lda, n
      Character (1)                    :: uplo
!     .. Local Arrays ..
      Complex (Kind=nag_wp), Allocatable :: a(:,:), work(:)
      Real (Kind=nag_wp), Allocatable  :: rwork(:)
!     .. Executable Statements ..
      Write (nout,*) 'F07TUF Example Program Results'
!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) n
      lda = n
      Allocate (a(lda,n),work(2*n),rwork(n))

!     Read A from data file

      Read (nin,*) uplo
      If (uplo=='U') Then
        Read (nin,*)(a(i,i:n),i=1,n)
      Else If (uplo=='L') Then
        Read (nin,*)(a(i,1:i),i=1,n)
      End If

!     Estimate condition number
!     The NAG name equivalent of ztrcon is f07tuf
      Call ztrcon(norm,uplo,diag,n,a,lda,rcond,work,rwork,info)

      Write (nout,*)
      If (rcond>=x02ajf()) Then
        Write (nout,99999) 'Estimate of condition number =', 1.0_nag_wp/rcond
      Else
        Write (nout,*) 'A is singular to working precision'
      End If

99999 Format (1X,A,1P,E10.2)
    End Program f07tufe


f07tvfe.f90

    Program f07tvfe

!     F07TVF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: nag_wp, x04dbf, ztrrfs, ztrtrs
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
      Character (1), Parameter         :: diag = 'N', trans = 'N'
!     .. Local Scalars ..
      Integer                          :: i, ifail, info, lda, ldb, ldx, n,    &
                                          nrhs
      Character (1)                    :: uplo
!     .. Local Arrays ..
      Complex (Kind=nag_wp), Allocatable :: a(:,:), b(:,:), work(:), x(:,:)
      Real (Kind=nag_wp), Allocatable  :: berr(:), ferr(:), rwork(:)
      Character (1)                    :: clabs(1), rlabs(1)
!     .. Executable Statements ..
      Write (nout,*) 'F07TVF Example Program Results'
!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) n, nrhs
      lda = n
      ldb = n
      ldx = n
      Allocate (a(lda,n),b(ldb,nrhs),work(2*n),x(ldx,n),berr(nrhs),ferr(nrhs), &
        rwork(n))

!     Read A and B from data file, and copy B to X

      Read (nin,*) uplo
      If (uplo=='U') Then
        Read (nin,*)(a(i,i:n),i=1,n)
      Else If (uplo=='L') Then
        Read (nin,*)(a(i,1:i),i=1,n)
      End If
      Read (nin,*)(b(i,1:nrhs),i=1,n)
      x(1:n,1:nrhs) = b(1:n,1:nrhs)

!     Compute solution in the array X
!     The NAG name equivalent of ztrtrs is f07tsf
      Call ztrtrs(uplo,trans,diag,n,nrhs,a,lda,x,ldx,info)

!     Compute backward errors and estimated bounds on the
!     forward errors

!     The NAG name equivalent of ztrrfs is f07tvf
      Call ztrrfs(uplo,trans,diag,n,nrhs,a,lda,b,ldb,x,ldx,ferr,berr,work,     &
        rwork,info)

!     Print solution

      Write (nout,*)
      Flush (nout)

!     ifail: behaviour on error exit
!             =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
      ifail = 0
      Call x04dbf('General',' ',n,nrhs,x,ldx,'Bracketed','F7.4','Solution(s)', &
        'Integer',rlabs,'Integer',clabs,80,0,ifail)

      Write (nout,*)
      Write (nout,*) 'Backward errors (machine-dependent)'
      Write (nout,99999) berr(1:nrhs)
      Write (nout,*) 'Estimated forward error bounds (machine-dependent)'
      Write (nout,99999) ferr(1:nrhs)

99999 Format ((5X,1P,4(E11.1,7X)))
    End Program f07tvfe


f07twfe.f90

    Program f07twfe

!     F07TWF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: nag_wp, x04dbf, ztrtri
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
      Character (1), Parameter         :: diag = 'N'
!     .. Local Scalars ..
      Integer                          :: i, ifail, info, lda, n
      Character (1)                    :: uplo
!     .. Local Arrays ..
      Complex (Kind=nag_wp), Allocatable :: a(:,:)
      Character (1)                    :: clabs(1), rlabs(1)
!     .. Executable Statements ..
      Write (nout,*) 'F07TWF Example Program Results'
!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) n
      lda = n
      Allocate (a(lda,n))

!     Read A from data file

      Read (nin,*) uplo
      If (uplo=='U') Then
        Read (nin,*)(a(i,i:n),i=1,n)
      Else If (uplo=='L') Then
        Read (nin,*)(a(i,1:i),i=1,n)
      End If

!     Compute inverse of A
!     The NAG name equivalent of ztrtri is f07twf
      Call ztrtri(uplo,diag,n,a,lda,info)

!     Print inverse

      Write (nout,*)
      Flush (nout)

!     ifail: behaviour on error exit
!             =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
      ifail = 0
      Call x04dbf(uplo,diag,n,n,a,lda,'Bracketed','F7.4','Inverse','Integer',  &
        rlabs,'Integer',clabs,80,0,ifail)

    End Program f07twfe


f07uefe.f90

    Program f07uefe

!     F07UEF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: dtptrs, nag_wp, x04caf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
      Character (1), Parameter         :: diag = 'N', trans = 'N'
!     .. Local Scalars ..
      Integer                          :: i, ifail, info, j, ldb, n, nrhs
      Character (1)                    :: uplo
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: ap(:), b(:,:)
!     .. Executable Statements ..
      Write (nout,*) 'F07UEF Example Program Results'
!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) n, nrhs
      ldb = n
      Allocate (ap(n*(n+1)/2),b(ldb,nrhs))

!     Read A and B from data file

      Read (nin,*) uplo
      If (uplo=='U') Then
        Read (nin,*)((ap(i+j*(j-1)/2),j=i,n),i=1,n)
      Else If (uplo=='L') Then
        Read (nin,*)((ap(i+(2*n-j)*(j-1)/2),j=1,i),i=1,n)
      End If
      Read (nin,*)(b(i,1:nrhs),i=1,n)

!     Compute solution
!     The NAG name equivalent of dtptrs is f07uef
      Call dtptrs(uplo,trans,diag,n,nrhs,ap,b,ldb,info)

!     Print solution

      Write (nout,*)
      Flush (nout)
      If (info==0) Then

!       ifail: behaviour on error exit
!              =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
        ifail = 0
        Call x04caf('General',' ',n,nrhs,b,ldb,'Solution(s)',ifail)

      Else
        Write (nout,*) 'A is singular'
      End If

    End Program f07uefe


f07ugfe.f90

    Program f07ugfe

!     F07UGF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: dtpcon, nag_wp, x02ajf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
      Character (1), Parameter         :: diag = 'N', norm = '1'
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: rcond
      Integer                          :: i, info, j, n
      Character (1)                    :: uplo
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: ap(:), work(:)
      Integer, Allocatable             :: iwork(:)
!     .. Executable Statements ..
      Write (nout,*) 'F07UGF Example Program Results'
!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) n

      Allocate (ap(n*(n+1)/2),work(3*n),iwork(n))

!     Read A from data file

      Read (nin,*) uplo
      If (uplo=='U') Then
        Read (nin,*)((ap(i+j*(j-1)/2),j=i,n),i=1,n)
      Else If (uplo=='L') Then
        Read (nin,*)((ap(i+(2*n-j)*(j-1)/2),j=1,i),i=1,n)
      End If

!     Estimate condition number
!     The NAG name equivalent of dtpcon is f07ugf
      Call dtpcon(norm,uplo,diag,n,ap,rcond,work,iwork,info)

      Write (nout,*)
      If (rcond>=x02ajf()) Then
        Write (nout,99999) 'Estimate of condition number =',                   &
          1.0E0_nag_wp/rcond
      Else
        Write (nout,*) 'A is singular to working precision'
      End If

99999 Format (1X,A,1P,E10.2)
    End Program f07ugfe


f07uhfe.f90

    Program f07uhfe

!     F07UHF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: dtprfs, dtptrs, nag_wp, x04caf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
      Character (1), Parameter         :: diag = 'N', trans = 'N'
!     .. Local Scalars ..
      Integer                          :: i, ifail, info, j, ldb, ldx, n, nrhs
      Character (1)                    :: uplo
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: ap(:), b(:,:), berr(:), ferr(:),     &
                                          work(:), x(:,:)
      Integer, Allocatable             :: iwork(:)
!     .. Executable Statements ..
      Write (nout,*) 'F07UHF Example Program Results'
!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) n, nrhs
      ldb = n
      ldx = n
      Allocate (ap(n*(n+1)/2),b(ldb,nrhs),berr(nrhs),ferr(nrhs),work(3*n),x(   &
        ldx,n),iwork(n))

!     Read A and B from data file, and copy B to X

      Read (nin,*) uplo
      If (uplo=='U') Then
        Read (nin,*)((ap(i+j*(j-1)/2),j=i,n),i=1,n)
      Else If (uplo=='L') Then
        Read (nin,*)((ap(i+(2*n-j)*(j-1)/2),j=1,i),i=1,n)
      End If
      Read (nin,*)(b(i,1:nrhs),i=1,n)

      x(1:n,1:nrhs) = b(1:n,1:nrhs)

!     Compute solution in the array X
!     The NAG name equivalent of dtptrs is f07uef
      Call dtptrs(uplo,trans,diag,n,nrhs,ap,x,ldx,info)

!     Compute backward errors and estimated bounds on the
!     forward errors

!     The NAG name equivalent of dtprfs is f07uhf
      Call dtprfs(uplo,trans,diag,n,nrhs,ap,b,ldb,x,ldx,ferr,berr,work,iwork,  &
        info)

!     Print solution

      Write (nout,*)
      Flush (nout)

!     ifail: behaviour on error exit
!             =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
      ifail = 0
      Call x04caf('General',' ',n,nrhs,x,ldx,'Solution(s)',ifail)

      Write (nout,*)
      Write (nout,*) 'Backward errors (machine-dependent)'
      Write (nout,99999) berr(1:nrhs)
      Write (nout,*) 'Estimated forward error bounds (machine-dependent)'
      Write (nout,99999) ferr(1:nrhs)

99999 Format ((3X,1P,7E11.1))
    End Program f07uhfe


f07ujfe.f90

    Program f07ujfe

!     F07UJF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: dtptri, nag_wp, x04ccf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
      Character (1), Parameter         :: diag = 'N'
!     .. Local Scalars ..
      Integer                          :: i, ifail, info, j, n
      Character (1)                    :: uplo
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: ap(:)
!     .. Executable Statements ..
      Write (nout,*) 'F07UJF Example Program Results'
!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) n

      Allocate (ap(n*(n+1)/2))

!     Read A from data file

      Read (nin,*) uplo
      If (uplo=='U') Then
        Read (nin,*)((ap(i+j*(j-1)/2),j=i,n),i=1,n)
      Else If (uplo=='L') Then
        Read (nin,*)((ap(i+(2*n-j)*(j-1)/2),j=1,i),i=1,n)
      End If

!     Compute inverse of A
!     The NAG name equivalent of dtptri is f07ujf
      Call dtptri(uplo,diag,n,ap,info)

!     Print inverse

      Write (nout,*)
      Flush (nout)

!     ifail: behaviour on error exit
!             =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
      ifail = 0
      Call x04ccf(uplo,diag,n,ap,'Inverse',ifail)

    End Program f07ujfe


f07usfe.f90

    Program f07usfe

!     F07USF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: nag_wp, x04dbf, ztptrs
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
      Character (1), Parameter         :: diag = 'N', trans = 'N'
!     .. Local Scalars ..
      Integer                          :: i, ifail, info, j, ldb, n, nrhs
      Character (1)                    :: uplo
!     .. Local Arrays ..
      Complex (Kind=nag_wp), Allocatable :: ap(:), b(:,:)
      Character (1)                    :: clabs(1), rlabs(1)
!     .. Executable Statements ..
      Write (nout,*) 'F07USF Example Program Results'
!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) n, nrhs
      ldb = n
      Allocate (ap(n*(n+1)/2),b(ldb,nrhs))

!     Read A and B from data file

      Read (nin,*) uplo
      If (uplo=='U') Then
        Read (nin,*)((ap(i+j*(j-1)/2),j=i,n),i=1,n)
      Else If (uplo=='L') Then
        Read (nin,*)((ap(i+(2*n-j)*(j-1)/2),j=1,i),i=1,n)
      End If
      Read (nin,*)(b(i,1:nrhs),i=1,n)

!     Compute solution
!     The NAG name equivalent of ztptrs is f07usf
      Call ztptrs(uplo,trans,diag,n,nrhs,ap,b,ldb,info)

!     Print solution

      Write (nout,*)
      Flush (nout)
      If (info==0) Then

!       ifail: behaviour on error exit
!              =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
        ifail = 0
        Call x04dbf('General',' ',n,nrhs,b,ldb,'Bracketed','F7.4',             &
          'Solution(s)','Integer',rlabs,'Integer',clabs,80,0,ifail)

      Else
        Write (nout,*) 'A is singular'
      End If

    End Program f07usfe


f07uufe.f90

    Program f07uufe

!     F07UUF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: nag_wp, x02ajf, ztpcon
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
      Character (1), Parameter         :: diag = 'N', norm = '1'
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: rcond
      Integer                          :: i, info, j, n
      Character (1)                    :: uplo
!     .. Local Arrays ..
      Complex (Kind=nag_wp), Allocatable :: ap(:), work(:)
      Real (Kind=nag_wp), Allocatable  :: rwork(:)
!     .. Executable Statements ..
      Write (nout,*) 'F07UUF Example Program Results'
!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) n

      Allocate (ap(n*(n+1)/2),work(2*n),rwork(n))

!     Read A from data file

      Read (nin,*) uplo
      If (uplo=='U') Then
        Read (nin,*)((ap(i+j*(j-1)/2),j=i,n),i=1,n)
      Else If (uplo=='L') Then
        Read (nin,*)((ap(i+(2*n-j)*(j-1)/2),j=1,i),i=1,n)
      End If

!     Estimate condition number
!     The NAG name equivalent of ztpcon is f07uuf
      Call ztpcon(norm,uplo,diag,n,ap,rcond,work,rwork,info)

      Write (nout,*)
      If (rcond>=x02ajf()) Then
        Write (nout,99999) 'Estimate of condition number =',                   &
          1.0E0_nag_wp/rcond
      Else
        Write (nout,*) 'A is singular to working precision'
      End If

99999 Format (1X,A,1P,E10.2)
    End Program f07uufe


f07uvfe.f90

    Program f07uvfe

!     F07UVF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: nag_wp, x04dbf, ztprfs, ztptrs
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
      Character (1), Parameter         :: diag = 'N', trans = 'N'
!     .. Local Scalars ..
      Integer                          :: i, ifail, info, j, ldb, ldx, n, nrhs
      Character (1)                    :: uplo
!     .. Local Arrays ..
      Complex (Kind=nag_wp), Allocatable :: ap(:), b(:,:), work(:), x(:,:)
      Real (Kind=nag_wp), Allocatable  :: berr(:), ferr(:), rwork(:)
      Character (1)                    :: clabs(1), rlabs(1)
!     .. Executable Statements ..
      Write (nout,*) 'F07UVF Example Program Results'
!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) n, nrhs
      ldb = n
      ldx = n
      Allocate (ap(n*(n+1)/2),b(ldb,nrhs),work(2*n),x(ldx,n),berr(nrhs),ferr(  &
        nrhs),rwork(n))

!     Read A and B from data file, and copy B to X

      Read (nin,*) uplo
      If (uplo=='U') Then
        Read (nin,*)((ap(i+j*(j-1)/2),j=i,n),i=1,n)
      Else If (uplo=='L') Then
        Read (nin,*)((ap(i+(2*n-j)*(j-1)/2),j=1,i),i=1,n)
      End If
      Read (nin,*)(b(i,1:nrhs),i=1,n)
      x(1:n,1:nrhs) = b(1:n,1:nrhs)

!     Compute solution in the array X
!     The NAG name equivalent of ztptrs is f07usf
      Call ztptrs(uplo,trans,diag,n,nrhs,ap,x,ldx,info)

!     Compute backward errors and estimated bounds on the
!     forward errors

!     The NAG name equivalent of ztprfs is f07uvf
      Call ztprfs(uplo,trans,diag,n,nrhs,ap,b,ldb,x,ldx,ferr,berr,work,rwork,  &
        info)

!     Print solution

      Write (nout,*)
      Flush (nout)

!     ifail: behaviour on error exit
!             =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
      ifail = 0
      Call x04dbf('General',' ',n,nrhs,x,ldx,'Bracketed','F7.4','Solution(s)', &
        'Integer',rlabs,'Integer',clabs,80,0,ifail)

      Write (nout,*)
      Write (nout,*) 'Backward errors (machine-dependent)'
      Write (nout,99999) berr(1:nrhs)
      Write (nout,*) 'Estimated forward error bounds (machine-dependent)'
      Write (nout,99999) ferr(1:nrhs)

99999 Format ((5X,1P,4(E11.1,7X)))
    End Program f07uvfe


f07uwfe.f90

    Program f07uwfe

!     F07UWF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: nag_wp, x04ddf, ztptri
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
      Character (1), Parameter         :: diag = 'N'
!     .. Local Scalars ..
      Integer                          :: i, ifail, info, j, n
      Character (1)                    :: uplo
!     .. Local Arrays ..
      Complex (Kind=nag_wp), Allocatable :: ap(:)
      Character (1)                    :: clabs(1), rlabs(1)
!     .. Executable Statements ..
      Write (nout,*) 'F07UWF Example Program Results'
!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) n

      Allocate (ap(n*(n+1)/2))

!     Read A from data file

      Read (nin,*) uplo
      If (uplo=='U') Then
        Read (nin,*)((ap(i+j*(j-1)/2),j=i,n),i=1,n)
      Else If (uplo=='L') Then
        Read (nin,*)((ap(i+(2*n-j)*(j-1)/2),j=1,i),i=1,n)
      End If

!     Compute inverse of A
!     The NAG name equivalent of ztptri is f07uwf
      Call ztptri(uplo,diag,n,ap,info)

!     Print inverse

      Write (nout,*)
      Flush (nout)

!     ifail: behaviour on error exit
!             =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
      ifail = 0
      Call x04ddf(uplo,diag,n,ap,'Bracketed','F7.4','Inverse','Integer',rlabs, &
        'Integer',clabs,80,0,ifail)

    End Program f07uwfe


f07vefe.f90

    Program f07vefe

!     F07VEF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: dtbtrs, nag_wp, x04caf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
      Character (1), Parameter         :: diag = 'N', trans = 'N'
!     .. Local Scalars ..
      Integer                          :: i, ifail, info, j, kd, ldab, ldb, n, &
                                          nrhs
      Character (1)                    :: uplo
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: ab(:,:), b(:,:)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: max, min
!     .. Executable Statements ..
      Write (nout,*) 'F07VEF Example Program Results'
!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) n, kd, nrhs
      ldab = kd + 1
      ldb = n
      Allocate (ab(ldab,n),b(ldb,nrhs))

!     Read A and B from data file

      Read (nin,*) uplo
      If (uplo=='U') Then
        Do i = 1, n
          Read (nin,*)(ab(kd+1+i-j,j),j=i,min(n,i+kd))
        End Do
      Else If (uplo=='L') Then
        Do i = 1, n
          Read (nin,*)(ab(1+i-j,j),j=max(1,i-kd),i)
        End Do
      End If
      Read (nin,*)(b(i,1:nrhs),i=1,n)

!     Compute solution
!     The NAG name equivalent of dtbtrs is f07vef
      Call dtbtrs(uplo,trans,diag,n,kd,nrhs,ab,ldab,b,ldb,info)

!     Print solution

      Write (nout,*)
      Flush (nout)
      If (info==0) Then

!       ifail: behaviour on error exit
!              =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
        ifail = 0
        Call x04caf('General',' ',n,nrhs,b,ldb,'Solution(s)',ifail)

      Else
        Write (nout,*) 'A is singular'
      End If

    End Program f07vefe


f07vgfe.f90

    Program f07vgfe

!     F07VGF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: dtbcon, nag_wp, x02ajf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
      Character (1), Parameter         :: diag = 'N', norm = '1'
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: rcond
      Integer                          :: i, info, j, kd, ldab, n
      Character (1)                    :: uplo
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: ab(:,:), work(:)
      Integer, Allocatable             :: iwork(:)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: max, min
!     .. Executable Statements ..
      Write (nout,*) 'F07VGF Example Program Results'
!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) n, kd
      ldab = kd + 1
      Allocate (ab(ldab,n),work(3*n),iwork(n))

!     Read A from data file

      Read (nin,*) uplo
      If (uplo=='U') Then
        Do i = 1, n
          Read (nin,*)(ab(kd+1+i-j,j),j=i,min(n,i+kd))
        End Do
      Else If (uplo=='L') Then
        Do i = 1, n
          Read (nin,*)(ab(1+i-j,j),j=max(1,i-kd),i)
        End Do
      End If

!     Estimate condition number
!     The NAG name equivalent of dtbcon is f07vgf
      Call dtbcon(norm,uplo,diag,n,kd,ab,ldab,rcond,work,iwork,info)

      Write (nout,*)
      If (rcond>=x02ajf()) Then
        Write (nout,99999) 'Estimate of condition number =',                   &
          1.0E0_nag_wp/rcond
      Else
        Write (nout,*) 'A is singular to working precision'
      End If

99999 Format (1X,A,1P,E10.2)
    End Program f07vgfe


f07vhfe.f90

    Program f07vhfe

!     F07VHF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: dtbrfs, dtbtrs, nag_wp, x04caf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
      Character (1), Parameter         :: diag = 'N', trans = 'N'
!     .. Local Scalars ..
      Integer                          :: i, ifail, info, j, kd, ldab, ldb,    &
                                          ldx, n, nrhs
      Character (1)                    :: uplo
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: ab(:,:), b(:,:), berr(:), ferr(:),   &
                                          work(:), x(:,:)
      Integer, Allocatable             :: iwork(:)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: max, min
!     .. Executable Statements ..
      Write (nout,*) 'F07VHF Example Program Results'
!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) n, kd, nrhs
      ldab = kd + 1
      ldb = n
      ldx = n
      Allocate (ab(ldab,n),b(ldb,nrhs),berr(nrhs),ferr(nrhs),work(3*n),        &
        x(ldx,n),iwork(n))

!     Read A and B from data file, and copy B to X

      Read (nin,*) uplo
      If (uplo=='U') Then
        Do i = 1, n
          Read (nin,*)(ab(kd+1+i-j,j),j=i,min(n,i+kd))
        End Do
      Else If (uplo=='L') Then
        Do i = 1, n
          Read (nin,*)(ab(1+i-j,j),j=max(1,i-kd),i)
        End Do
      End If
      Read (nin,*)(b(i,1:nrhs),i=1,n)

      x(1:n,1:nrhs) = b(1:n,1:nrhs)

!     Compute solution in the array X
!     The NAG name equivalent of dtbtrs is f07vef
      Call dtbtrs(uplo,trans,diag,n,kd,nrhs,ab,ldab,x,ldx,info)

!     Compute backward errors and estimated bounds on the
!     forward errors

!     The NAG name equivalent of dtbrfs is f07vhf
      Call dtbrfs(uplo,trans,diag,n,kd,nrhs,ab,ldab,b,ldb,x,ldx,ferr,berr,     &
        work,iwork,info)

!     Print solution

      Write (nout,*)
      Flush (nout)

!     ifail: behaviour on error exit
!             =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
      ifail = 0
      Call x04caf('General',' ',n,nrhs,x,ldx,'Solution(s)',ifail)

      Write (nout,*)
      Write (nout,*) 'Backward errors (machine-dependent)'
      Write (nout,99999) berr(1:nrhs)
      Write (nout,*) 'Estimated forward error bounds (machine-dependent)'
      Write (nout,99999) ferr(1:nrhs)

99999 Format ((3X,1P,7E11.1))
    End Program f07vhfe


f07vsfe.f90

    Program f07vsfe

!     F07VSF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: nag_wp, x04dbf, ztbtrs
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
      Character (1), Parameter         :: diag = 'N', trans = 'N'
!     .. Local Scalars ..
      Integer                          :: i, ifail, info, j, kd, ldab, ldb, n, &
                                          nrhs
      Character (1)                    :: uplo
!     .. Local Arrays ..
      Complex (Kind=nag_wp), Allocatable :: ab(:,:), b(:,:)
      Character (1)                    :: clabs(1), rlabs(1)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: max, min
!     .. Executable Statements ..
      Write (nout,*) 'F07VSF Example Program Results'
!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) n, kd, nrhs
      ldab = kd + 1
      ldb = n
      Allocate (ab(ldab,n),b(ldb,nrhs))

!     Read A and B from data file

      Read (nin,*) uplo
      If (uplo=='U') Then
        Do i = 1, n
          Read (nin,*)(ab(kd+1+i-j,j),j=i,min(n,i+kd))
        End Do
      Else If (uplo=='L') Then
        Do i = 1, n
          Read (nin,*)(ab(1+i-j,j),j=max(1,i-kd),i)
        End Do
      End If
      Read (nin,*)(b(i,1:nrhs),i=1,n)

!     Compute solution
!     The NAG name equivalent of ztbtrs is f07vsf
      Call ztbtrs(uplo,trans,diag,n,kd,nrhs,ab,ldab,b,ldb,info)

!     Print solution

      Write (nout,*)
      Flush (nout)
      If (info==0) Then

!       ifail: behaviour on error exit
!              =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
        ifail = 0
        Call x04dbf('General',' ',n,nrhs,b,ldb,'Bracketed','F7.4',             &
          'Solution(s)','Integer',rlabs,'Integer',clabs,80,0,ifail)

      Else
        Write (nout,*) 'A is singular'
      End If

    End Program f07vsfe


f07vufe.f90

    Program f07vufe

!     F07VUF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: nag_wp, x02ajf, ztbcon
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
      Character (1), Parameter         :: diag = 'N', norm = '1'
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: rcond
      Integer                          :: i, info, j, kd, ldab, n
      Character (1)                    :: uplo
!     .. Local Arrays ..
      Complex (Kind=nag_wp), Allocatable :: ab(:,:), work(:)
      Real (Kind=nag_wp), Allocatable  :: rwork(:)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: max, min
!     .. Executable Statements ..
      Write (nout,*) 'F07VUF Example Program Results'
!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) n, kd
      ldab = kd + 1
      Allocate (ab(ldab,n),work(2*n),rwork(n))

!     Read A from data file

      Read (nin,*) uplo
      If (uplo=='U') Then
        Do i = 1, n
          Read (nin,*)(ab(kd+1+i-j,j),j=i,min(n,i+kd))
        End Do
      Else If (uplo=='L') Then
        Do i = 1, n
          Read (nin,*)(ab(1+i-j,j),j=max(1,i-kd),i)
        End Do
      End If

!     Estimate condition number
!     The NAG name equivalent of ztbcon is f07vuf
      Call ztbcon(norm,uplo,diag,n,kd,ab,ldab,rcond,work,rwork,info)

      Write (nout,*)
      If (rcond>=x02ajf()) Then
        Write (nout,99999) 'Estimate of condition number =',                   &
          1.0E0_nag_wp/rcond
      Else
        Write (nout,*) 'A is singular to working precision'
      End If

99999 Format (1X,A,1P,E10.2)
    End Program f07vufe


f07vvfe.f90

    Program f07vvfe

!     F07VVF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: nag_wp, x04dbf, ztbrfs, ztbtrs
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
      Character (1), Parameter         :: diag = 'N', trans = 'N'
!     .. Local Scalars ..
      Integer                          :: i, ifail, info, j, kd, ldab, ldb,    &
                                          ldx, n, nrhs
      Character (1)                    :: uplo
!     .. Local Arrays ..
      Complex (Kind=nag_wp), Allocatable :: ab(:,:), b(:,:), work(:), x(:,:)
      Real (Kind=nag_wp), Allocatable  :: berr(:), ferr(:), rwork(:)
      Character (1)                    :: clabs(1), rlabs(1)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: max, min
!     .. Executable Statements ..
      Write (nout,*) 'F07VVF Example Program Results'
!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) n, kd, nrhs
      ldab = kd + 1
      ldb = n
      ldx = n
      Allocate (ab(ldab,n),b(ldb,nrhs),work(2*n),x(ldx,n),berr(nrhs),          &
        ferr(nrhs),rwork(n))

!     Read A and B from data file, and copy B to X

      Read (nin,*) uplo
      If (uplo=='U') Then
        Do i = 1, n
          Read (nin,*)(ab(kd+1+i-j,j),j=i,min(n,i+kd))
        End Do
      Else If (uplo=='L') Then
        Do i = 1, n
          Read (nin,*)(ab(1+i-j,j),j=max(1,i-kd),i)
        End Do
      End If
      Read (nin,*)(b(i,1:nrhs),i=1,n)
      x(1:n,1:nrhs) = b(1:n,1:nrhs)

!     Compute solution in the array X
!     The NAG name equivalent of ztbtrs is f07vsf
      Call ztbtrs(uplo,trans,diag,n,kd,nrhs,ab,ldab,x,ldx,info)

!     Compute backward errors and estimated bounds on the
!     forward errors

!     The NAG name equivalent of ztbrfs is f07vvf
      Call ztbrfs(uplo,trans,diag,n,kd,nrhs,ab,ldab,b,ldb,x,ldx,ferr,berr,     &
        work,rwork,info)

!     Print solution

      Write (nout,*)
      Flush (nout)

!     ifail: behaviour on error exit
!             =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
      ifail = 0
      Call x04dbf('General',' ',n,nrhs,x,ldx,'Bracketed','F7.4','Solution(s)', &
        'Integer',rlabs,'Integer',clabs,80,0,ifail)

      Write (nout,*)
      Write (nout,*) 'Backward errors (machine-dependent)'
      Write (nout,99999) berr(1:nrhs)
      Write (nout,*) 'Estimated forward error bounds (machine-dependent)'
      Write (nout,99999) ferr(1:nrhs)

99999 Format ((5X,1P,4(E11.1,7X)))
    End Program f07vvfe


f07wdfe.f90

    Program f07wdfe

!     F07WDF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: dpftrf, dtfttr, nag_wp, x04caf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Integer                          :: i, ifail, info, k, lar1, lda, lenar, &
                                          n, q
      Character (1)                    :: transr, uplo
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: a(:,:), ar(:)
!     .. Executable Statements ..
      Write (nout,*) 'F07WDF Example Program Results'
!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) n, uplo, transr

      lenar = n*(n+1)/2
      lda = n
      Allocate (ar(lenar),a(lda,n))

!     Setup notional dimensions of RFP matrix AR
      k = n/2
      q = n - k
      If (transr=='N' .Or. transr=='n') Then
        lar1 = 2*k + 1
      Else
        lar1 = q
      End If

!     Read an RFP matrix into array AR
      Do i = 1, lar1
        Read (nin,*) ar(i:lenar:lar1)
      End Do

!     Factorize A
!     The NAG name equivalent of dpftrf is f07wdf
      Call dpftrf(transr,uplo,n,ar,info)

      Write (nout,*)
      Flush (nout)
      If (info==0) Then

!       Convert factor to full array form, and print it
!       The NAG name equivalent of dtfttr is f01vgf
        Call dtfttr(transr,uplo,n,ar,a,lda,info)
        ifail = 0
        Call x04caf(uplo,'Nonunit',n,n,a,lda,'Factor',ifail)

      Else
        Write (nout,*) 'A is not positive definite'
      End If

    End Program f07wdfe


f07wefe.f90

    Program f07wefe

!     F07WEF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: dpftrf, dpftrs, nag_wp, x04caf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Integer                          :: i, ifail, info, k, lar1, ldb, lenar, &
                                          n, nrhs, q
      Character (1)                    :: transr, uplo
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: ar(:), b(:,:)
!     .. Executable Statements ..
      Write (nout,*) 'F07WEF Example Program Results'
!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) n, nrhs, uplo, transr

      lenar = n*(n+1)/2
      ldb = n
      Allocate (ar(lenar),b(ldb,nrhs))

!     Setup notional dimensions of RFP matrix AR
      k = n/2
      q = n - k
      If (transr=='N' .Or. transr=='n') Then
        lar1 = 2*k + 1
      Else
        lar1 = q
      End If

!     Read an RFP matrix into array AR
      Do i = 1, lar1
        Read (nin,*) ar(i:lenar:lar1)
      End Do

!     Read RHS matrix B
      Do i = 1, n
        Read (nin,*) b(i,1:nrhs)
      End Do

!     Factorize A
!     The NAG name equivalent of dpftrf is f07wdf
      Call dpftrf(transr,uplo,n,ar,info)

      Write (nout,*)
      Flush (nout)
      If (info==0) Then

!       Compute solution
!       The NAG name equivalent of dpftrs is f07wef
        Call dpftrs(transr,uplo,n,nrhs,ar,b,ldb,info)

!       Print solution
        ifail = 0
        Call x04caf('General',' ',n,nrhs,b,ldb,'Solution(s)',ifail)

      Else
        Write (nout,*) 'A is not positive definite'
      End If

    End Program f07wefe


f07wjfe.f90

    Program f07wjfe

!     F07WJF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: dpftrf, dpftri, dtfttr, nag_wp, x04caf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Integer                          :: i, ifail, info, k, lar1, lda, lenar, &
                                          n, q
      Character (1)                    :: transr, uplo
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: a(:,:), ar(:)
!     .. Executable Statements ..
      Write (nout,*) 'F07WJF Example Program Results'
!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) n, uplo, transr

      lenar = n*(n+1)/2
      lda = n
      Allocate (ar(lenar),a(lda,n))

!     Setup notional dimensions of RFP matrix AR
      k = n/2
      q = n - k
      If (transr=='N' .Or. transr=='n') Then
        lar1 = 2*k + 1
      Else
        lar1 = q
      End If

!     Read an RFP matrix into array AR
      Do i = 1, lar1
        Read (nin,*) ar(i:lenar:lar1)
      End Do

!     Factorize A
!     The NAG name equivalent of dpftrf is f07wdf
      Call dpftrf(transr,uplo,n,ar,info)

      Write (nout,*)
      Flush (nout)
      If (info==0) Then

!       Compute inverse of A
!       The NAG name equivalent of dpftri is f07wjf
        Call dpftri(transr,uplo,n,ar,info)

!       Convert inverse to full array form, and print it
!       The NAG name equivalent of dtfttr is f01vgf
        Call dtfttr(transr,uplo,n,ar,a,lda,info)
        ifail = 0
        Call x04caf(uplo,'Nonunit',n,n,a,lda,'Inverse',ifail)

      Else
        Write (nout,*) 'A is not positive definite'
      End If

    End Program f07wjfe


f07wkfe.f90

    Program f07wkfe

!     F07WKF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: dtftri, dtfttr, nag_wp, x04caf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Integer                          :: i, ifail, info, k, lar1, lda, lenar, &
                                          n, q
      Character (1)                    :: diag, transr, uplo
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: a(:,:), ar(:)
!     .. Executable Statements ..
      Write (nout,*) 'F07WKF Example Program Results'
!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) n, uplo, transr, diag

      lenar = n*(n+1)/2
      lda = n
      Allocate (ar(lenar),a(lda,n))

!     Setup notional dimensions of RFP matrix AR
      k = n/2
      q = n - k
      If (transr=='N' .Or. transr=='n') Then
        lar1 = 2*k + 1
      Else
        lar1 = q
      End If

!     Read an RFP matrix into array AR
      Do i = 1, lar1
        Read (nin,*) ar(i:lenar:lar1)
      End Do

!     Compute inverse of A
!     The NAG name equivalent of dtftri is f07wkf
      Call dtftri(transr,uplo,diag,n,ar,info)

      Write (nout,*)
      Flush (nout)
      If (info==0) Then

!       Convert inverse to full array form, and print it
!       The NAG name equivalent of dtfttr is f01vgf
        Call dtfttr(transr,uplo,n,ar,a,lda,info)
        ifail = 0
        Call x04caf(uplo,'Nonunit',n,n,a,lda,'Inverse',ifail)
      Else
        Write (nout,*) 'A is singular'
      End If

    End Program f07wkfe


f07wrfe.f90

    Program f07wrfe

!     F07WRF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: nag_wp, x04dbf, zpftrf, ztfttr
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Integer                          :: i, ifail, info, k, lar1, lda, lenar, &
                                          n, q
      Character (1)                    :: transr, uplo
!     .. Local Arrays ..
      Complex (Kind=nag_wp), Allocatable :: a(:,:), ar(:)
      Character (1)                    :: clabs(1), rlabs(1)
!     .. Executable Statements ..
      Write (nout,*) 'F07WRF Example Program Results'
!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) n, uplo, transr

      lenar = n*(n+1)/2
      lda = n
      Allocate (ar(lenar),a(lda,n))

!     Setup notional dimensions of RFP matrix AR
      k = n/2
      q = n - k
      If (transr=='N' .Or. transr=='n') Then
        lar1 = 2*k + 1
      Else
        lar1 = q
      End If

!     Read an RFP matrix into array AR
      Do i = 1, lar1
        Read (nin,*) ar(i:lenar:lar1)
      End Do

!     Factorize A
!     The NAG name equivalent of zpftrf is f07wrf
      Call zpftrf(transr,uplo,n,ar,info)

      Write (nout,*)
      Flush (nout)
      If (info==0) Then

!       Convert and print factor
!       The NAG name equivalent of ztfttr is f01vhf
        Call ztfttr(transr,uplo,n,ar,a,lda,info)
        ifail = 0
        Call x04dbf(uplo,'Nonunit',n,n,a,lda,'Bracketed','F7.4','Factor',      &
          'Integer',rlabs,'Integer',clabs,80,0,ifail)

      Else
        Write (nout,*) 'A is not positive definite'
      End If

    End Program f07wrfe


f07wsfe.f90

    Program f07wsfe

!     F07WSF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: nag_wp, x04dbf, zpftrf, zpftrs
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Integer                          :: i, ifail, info, k, lar1, ldb, lenar, &
                                          n, nrhs, q
      Character (1)                    :: transr, uplo
!     .. Local Arrays ..
      Complex (Kind=nag_wp), Allocatable :: ar(:), b(:,:)
      Character (1)                    :: clabs(1), rlabs(1)
!     .. Executable Statements ..
      Write (nout,*) 'F07WSF Example Program Results'
!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) n, nrhs, uplo, transr

      lenar = n*(n+1)/2
      ldb = n
      Allocate (ar(lenar),b(ldb,nrhs))

!     Setup notional dimensions of RFP matrix AR
      k = n/2
      q = n - k
      If (transr=='N' .Or. transr=='n') Then
        lar1 = 2*k + 1
      Else
        lar1 = q
      End If

!     Read an RFP matrix into array AR
      Do i = 1, lar1
        Read (nin,*) ar(i:lenar:lar1)
      End Do

!     Read RHS matrix B
      Do i = 1, n
        Read (nin,*) b(i,1:nrhs)
      End Do

!     Factorize A
!     The NAG name equivalent of zpftrf is f07wrf
      Call zpftrf(transr,uplo,n,ar,info)

      Write (nout,*)
      Flush (nout)
      If (info==0) Then

!       Compute solution
!       The NAG name equivalent of zpftrs is f07wsf
        Call zpftrs(transr,uplo,n,nrhs,ar,b,ldb,info)

!       Print solution
        ifail = 0
        Call x04dbf('General',' ',n,nrhs,b,ldb,'Bracketed','F7.4',             &
          'Solution(s)','Integer',rlabs,'Integer',clabs,80,0,ifail)

      Else
        Write (nout,*) 'A is not positive definite'
      End If

    End Program f07wsfe


f07wwfe.f90

    Program f07wwfe

!     F07WWF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: nag_wp, x04dbf, zpftrf, zpftri, ztfttr
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Integer                          :: i, ifail, info, k, lar1, lda, lenar, &
                                          n, q
      Character (1)                    :: transr, uplo
!     .. Local Arrays ..
      Complex (Kind=nag_wp), Allocatable :: a(:,:), ar(:)
      Character (1)                    :: clabs(1), rlabs(1)
!     .. Executable Statements ..
      Write (nout,*) 'F07WWF Example Program Results'
!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) n, uplo, transr

      lenar = n*(n+1)/2
      lda = n
      Allocate (ar(lenar),a(lda,n))

!     Setup notional dimensions of RFP matrix AR
      k = n/2
      q = n - k
      If (transr=='N' .Or. transr=='n') Then
        lar1 = 2*k + 1
      Else
        lar1 = q
      End If

!     Read an RFP matrix into array AR
      Do i = 1, lar1
        Read (nin,*) ar(i:lenar:lar1)
      End Do

!     Factorize A
!     The NAG name equivalent of zpftrf is f07wrf
      Call zpftrf(transr,uplo,n,ar,info)

      Write (nout,*)
      Flush (nout)
      If (info==0) Then

!       Compute inverse of A
!       The NAG name equivalent of zpftri is f07wwf
        Call zpftri(transr,uplo,n,ar,info)

!       Convert and print inverse
!       The NAG name equivalent of ztfttr is f01vhf
        Call ztfttr(transr,uplo,n,ar,a,lda,info)
        ifail = 0
        Call x04dbf(uplo,'Nonunit',n,n,a,lda,'Bracketed','F7.4','Inverse',     &
          'Integer',rlabs,'Integer',clabs,80,0,ifail)

      Else
        Write (nout,*) 'A is not positive definite'
      End If

    End Program f07wwfe


f07wxfe.f90

    Program f07wxfe

!     F07WXF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: nag_wp, x04dbf, ztftri, ztfttr
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Integer                          :: i, ifail, info, k, lar1, lda, lenar, &
                                          n, q
      Character (1)                    :: diag, transr, uplo
!     .. Local Arrays ..
      Complex (Kind=nag_wp), Allocatable :: a(:,:), ar(:)
      Character (1)                    :: clabs(1), rlabs(1)
!     .. Executable Statements ..
      Write (nout,*) 'F07WXF Example Program Results'
!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) n, uplo, transr, diag

      lenar = n*(n+1)/2
      lda = n
      Allocate (ar(1:lenar),a(lda,n))

!     Setup notional dimensions of RFP matrix AR
      k = n/2
      q = n - k
      If (transr=='N' .Or. transr=='n') Then
        lar1 = 2*k + 1
      Else
        lar1 = q
      End If

!     Read an RFP matrix into array AR
      Do i = 1, lar1
        Read (nin,*) ar(i:lenar:lar1)
      End Do

!     Compute inverse of A
!     The NAG name equivalent of ztftri is f07wxf
      Call ztftri(transr,uplo,diag,n,ar,info)

      Write (nout,*)
      Flush (nout)
      If (info==0) Then

!       Convert and print inverse
!       The NAG name equivalent of ztfttr is f01vhf
        Call ztfttr(transr,uplo,n,ar,a,lda,info)
        ifail = 0

        Call x04dbf(uplo,'Nonunit',n,n,a,lda,'Bracketed','F7.4','Inverse',     &
          'Integer',rlabs,'Integer',clabs,80,0,ifail)
      Else
        Write (nout,*) 'A is singular'
      End If

    End Program f07wxfe


f08aafe.f90

    Program f08aafe

!     F08AAF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: dgels, dnrm2, nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nb = 64, nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: rnorm
      Integer                          :: i, info, lda, ldb, lwork, m, n, nrhs
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: a(:,:), b(:), work(:)
!     .. Executable Statements ..
      Write (nout,*) 'F08AAF Example Program Results'
      Write (nout,*)
!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) m, n
      lda = m
      lwork = n + nb*m
      Allocate (a(lda,n),b(m),work(lwork))

!     Read A and B from data file

      Read (nin,*)(a(i,1:n),i=1,m)
      Read (nin,*) b(1:m)

!     Solve the least squares problem min( norm2(b - Ax) ) for x

      nrhs = 1
      ldb = m

!     The NAG name equivalent of dgels is f08aaf
      Call dgels('No transpose',m,n,nrhs,a,lda,b,ldb,work,lwork,info)

!     Print solution

      Write (nout,*) 'Least squares solution'
      Write (nout,99999) b(1:n)

!     Compute and print estimate of the square root of the residual
!     sum of squares

!     The NAG name equivalent of dnrm2 is f06ejf
      rnorm = dnrm2(m-n,b(n+1),1)
      Write (nout,*)
      Write (nout,*) 'Square root of the residual sum of squares'
      Write (nout,99998) rnorm

99999 Format (1X,7F11.4)
99998 Format (3X,1P,E11.2)
    End Program f08aafe


f08abfe.f90

    Program f08abfe

!     F08ABF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: dgemqrt, dgeqrt, dnrm2, dtrtrs, nag_wp, x04caf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nbmax = 64, nin = 5, nout = 6
!     .. Local Scalars ..
      Integer                          :: i, ifail, info, j, lda, ldb, ldt,    &
                                          lwork, m, n, nb, nrhs
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: a(:,:), b(:,:), rnorm(:), t(:,:),    &
                                          work(:)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: max, min
!     .. Executable Statements ..
      Write (nout,*) 'F08ABF Example Program Results'
      Write (nout,*)
      Flush (nout)
!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) m, n, nrhs
      lda = m
      ldb = m
      nb = min(m,n,nbmax)
      ldt = nb
      lwork = nb*max(n,m)
      Allocate (a(lda,n),b(ldb,nrhs),rnorm(nrhs),t(ldt,min(m,n)),work(lwork))

!     Read A and B from data file

      Read (nin,*)(a(i,1:n),i=1,m)
      Read (nin,*)(b(i,1:nrhs),i=1,m)

!     Compute the QR factorization of A
!     The NAG name equivalent of dgeqrt is f08abf
      Call dgeqrt(m,n,nb,a,lda,t,ldt,work,info)

!     Compute C = (C1) = (Q**T)*B, storing the result in B
!                 (C2)
!     The NAG name equivalent of dgemqrt is f08acf
      Call dgemqrt('Left','Transpose',m,nrhs,n,nb,a,lda,t,ldt,b,ldb,work,info)

!     Compute least squares solutions by back-substitution in
!     R*X = C1
!     The NAG name equivalent of dtrtrs is f07tef
      Call dtrtrs('Upper','No transpose','Non-Unit',n,nrhs,a,lda,b,ldb,info)

      If (info>0) Then
        Write (nout,*) 'The upper triangular factor, R, of A is singular, '
        Write (nout,*) 'the least squares solution could not be computed'
      Else

!       Print least squares solutions

!       ifail: behaviour on error exit
!              =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
        ifail = 0
        Call x04caf('General',' ',n,nrhs,b,ldb,'Least squares solution(s)',    &
          ifail)

!       Compute and print estimates of the square roots of the residual
!       sums of squares

!       The NAG name equivalent of dnrm2 is f06ejf
        Do j = 1, nrhs
          rnorm(j) = dnrm2(m-n,b(n+1,j),1)
        End Do

        Write (nout,*)
        Write (nout,*) 'Square root(s) of the residual sum(s) of squares'
        Write (nout,99999) rnorm(1:nrhs)
      End If

99999 Format (5X,1P,7E11.2)
    End Program f08abfe


f08aefe.f90

    Program f08aefe

!     F08AEF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: dgeqrf, dnrm2, dormqr, dtrtrs, nag_wp, x04caf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nb = 64, nin = 5, nout = 6
!     .. Local Scalars ..
      Integer                          :: i, ifail, info, j, lda, ldb, lwork,  &
                                          m, n, nrhs
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: a(:,:), b(:,:), rnorm(:), tau(:),    &
                                          work(:)
!     .. Executable Statements ..
      Write (nout,*) 'F08AEF Example Program Results'
      Write (nout,*)
      Flush (nout)
!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) m, n, nrhs
      lda = m
      ldb = m
      lwork = nb*n
      Allocate (a(lda,n),b(ldb,nrhs),rnorm(nrhs),tau(n),work(lwork))

!     Read A and B from data file

      Read (nin,*)(a(i,1:n),i=1,m)
      Read (nin,*)(b(i,1:nrhs),i=1,m)

!     Compute the QR factorization of A
!     The NAG name equivalent of dgeqrf is f08aef
      Call dgeqrf(m,n,a,lda,tau,work,lwork,info)

!     Compute C = (C1) = (Q**T)*B, storing the result in B
!                 (C2)
!     The NAG name equivalent of dormqr is f08agf
      Call dormqr('Left','Transpose',m,nrhs,n,a,lda,tau,b,ldb,work,lwork,info)

!     Compute least squares solutions by back-substitution in
!     R*X = C1
!     The NAG name equivalent of dtrtrs is f07tef
      Call dtrtrs('Upper','No transpose','Non-Unit',n,nrhs,a,lda,b,ldb,info)

      If (info>0) Then
        Write (nout,*) 'The upper triangular factor, R, of A is singular, '
        Write (nout,*) 'the least squares solution could not be computed'
      Else

!       Print least squares solutions

!       ifail: behaviour on error exit
!              =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
        ifail = 0
        Call x04caf('General',' ',n,nrhs,b,ldb,'Least squares solution(s)',    &
          ifail)

!       Compute and print estimates of the square roots of the residual
!       sums of squares

!       The NAG name equivalent of dnrm2 is f06ejf
        Do j = 1, nrhs
          rnorm(j) = dnrm2(m-n,b(n+1,j),1)
        End Do

        Write (nout,*)
        Write (nout,*) 'Square root(s) of the residual sum(s) of squares'
        Write (nout,99999) rnorm(1:nrhs)
      End If

99999 Format (5X,1P,7E11.2)
    End Program f08aefe


f08affe.f90

    Program f08affe

!     F08AFF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: dgeqrf, dorgqr, nag_wp, x04caf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Integer                          :: i, ifail, info, lda, lwork, m, n
      Character (30)                   :: title
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: a(:,:), tau(:), work(:)
!     .. Executable Statements ..
      Write (nout,*) 'F08AFF Example Program Results'
!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) m, n
      lda = m
      lwork = 64*n
      Allocate (a(lda,n),tau(n),work(lwork))

!     Read A from data file

      Read (nin,*)(a(i,1:n),i=1,m)

!     Compute the QR factorization of A
!     The NAG name equivalent of dgeqrf is f08aef
      Call dgeqrf(m,n,a,lda,tau,work,lwork,info)

!     Form the leading N columns of Q explicitly
!     The NAG name equivalent of dorgqr is f08aff
      Call dorgqr(m,n,n,a,lda,tau,work,lwork,info)

!     Print the leading N columns of Q only

      Write (nout,*)
      Write (title,99999) n
      Flush (nout)

!     ifail: behaviour on error exit
!             =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
      ifail = 0
      Call x04caf('General',' ',m,n,a,lda,title,ifail)

99999 Format ('The leading ',I2,' columns of Q')
    End Program f08affe


f08ahfe.f90

    Program f08ahfe

!     F08AHF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: dgelqf, dormlq, dtrsm, nag_wp, x04caf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Real (Kind=nag_wp), Parameter    :: one = 1.0E0_nag_wp
      Real (Kind=nag_wp), Parameter    :: zero = 0.0E0_nag_wp
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Integer                          :: i, ifail, info, lda, ldb, lwork, m,  &
                                          n, nrhs
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: a(:,:), b(:,:), tau(:), work(:)
!     .. Executable Statements ..
      Write (nout,*) 'F08AHF Example Program Results'
!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) m, n, nrhs
      lda = m
      ldb = n
      lwork = 64*n
      Allocate (a(lda,n),b(ldb,nrhs),tau(n),work(lwork))

!     Read A and B from data file

      Read (nin,*)(a(i,1:n),i=1,m)
      Read (nin,*)(b(i,1:nrhs),i=1,m)

!     Compute the LQ factorization of A
!     The NAG name equivalent of dgelqf is f08ahf
      Call dgelqf(m,n,a,lda,tau,work,lwork,info)

!     Solve L*Y = B, storing the result in B
!     The NAG name equivalent of dtrsm is f06yjf
      Call dtrsm('Left','Lower','No transpose','Non-Unit',m,nrhs,one,a,lda,b,  &
        ldb)

!     Set rows (M+1) to N of B to zero

      If (m<n) Then
        b(m+1:n,1:nrhs) = zero
      End If

!     Compute minimum-norm solution X = (Q**T)*B in B
!     The NAG name equivalent of dormlq is f08akf
      Call dormlq('Left','Transpose',n,nrhs,m,a,lda,tau,b,ldb,work,lwork,info)

!     Print minimum-norm solution(s)

      Write (nout,*)
      Flush (nout)

!     ifail: behaviour on error exit
!             =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
      ifail = 0
      Call x04caf('General',' ',n,nrhs,b,ldb,'Minimum-norm solution(s)',ifail)

    End Program f08ahfe


f08ajfe.f90

    Program f08ajfe

!     F08AJF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: dgelqf, dorglq, nag_wp, x04caf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Integer                          :: i, ifail, info, lda, lwork, m, n
      Character (30)                   :: title
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: a(:,:), tau(:), work(:)
!     .. Executable Statements ..
      Write (nout,*) 'F08AJF Example Program Results'
!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) m, n
      lda = m
      lwork = 64*m
      Allocate (a(lda,n),tau(n),work(lwork))

!     Read A from data file

      Read (nin,*)(a(i,1:n),i=1,m)

!     Compute the LQ factorization of A
!     The NAG name equivalent of dgelqf is f08ahf
      Call dgelqf(m,n,a,lda,tau,work,lwork,info)

!     Form the leading M rows of Q explicitly
!     The NAG name equivalent of dorglq is f08ajf
      Call dorglq(m,n,m,a,lda,tau,work,lwork,info)

!     Print the leading M rows of Q only

      Write (nout,*)
      Write (title,99999) m
      Flush (nout)

!     ifail: behaviour on error exit
!             =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
      ifail = 0
      Call x04caf('General',' ',m,n,a,lda,title,ifail)

99999 Format ('The leading ',I2,' rows of Q')
    End Program f08ajfe


f08anfe.f90

    Program f08anfe

!     F08ANF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: dznrm2, nag_wp, zgels
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nb = 64, nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: rnorm
      Integer                          :: i, info, lda, lwork, m, n
!     .. Local Arrays ..
      Complex (Kind=nag_wp), Allocatable :: a(:,:), b(:), work(:)
!     .. Executable Statements ..
      Write (nout,*) 'F08ANF Example Program Results'
      Write (nout,*)
!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) m, n
      lda = m
      lwork = n + nb*m
      Allocate (a(lda,n),b(m),work(lwork))

!     Read A and B from data file

      Read (nin,*)(a(i,1:n),i=1,m)
      Read (nin,*) b(1:m)

!     Solve the least squares problem min( norm2(b - Ax) ) for x
!     The NAG name equivalent of zgels is f08anf
      Call zgels('No transpose',m,n,1,a,lda,b,m,work,lwork,info)

!     Print solution

      Write (nout,*) 'Least squares solution'
      Write (nout,99999) b(1:n)

!     Compute and print estimate of the square root of the residual
!     sum of squares

!     The NAG name equivalent of dznrm2 is f06jjf
      rnorm = dznrm2(m-n,b(n+1),1)
      Write (nout,*)
      Write (nout,*) 'Square root of the residual sum of squares'
      Write (nout,99998) rnorm

99999 Format (4(' (',F7.4,',',F7.4,')',:))
99998 Format (1X,1P,E10.2)
    End Program f08anfe


f08apfe.f90

    Program f08apfe

!     F08APF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: dznrm2, nag_wp, x04dbf, zgemqrt, zgeqrt, ztrtrs
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nbmax = 64, nin = 5, nout = 6
!     .. Local Scalars ..
      Integer                          :: i, ifail, info, j, lda, ldb, ldt,    &
                                          lwork, m, n, nb, nrhs
!     .. Local Arrays ..
      Complex (Kind=nag_wp), Allocatable :: a(:,:), b(:,:), t(:,:), work(:)
      Real (Kind=nag_wp), Allocatable  :: rnorm(:)
      Character (1)                    :: clabs(1), rlabs(1)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: max, min
!     .. Executable Statements ..
      Write (nout,*) 'F08APF Example Program Results'
      Write (nout,*)
      Flush (nout)
!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) m, n, nrhs
      lda = m
      ldb = m
      nb = min(m,n,nbmax)
      ldt = nb
      lwork = nb*max(m,n)
      Allocate (a(lda,n),b(ldb,nrhs),t(ldt,min(m,n)),work(lwork),rnorm(nrhs))

!     Read A and B from data file

      Read (nin,*)(a(i,1:n),i=1,m)
      Read (nin,*)(b(i,1:nrhs),i=1,m)

!     Compute the QR factorization of A
!     The NAG name equivalent of zgeqrf is f08apf
      Call zgeqrt(m,n,nb,a,lda,t,ldt,work,info)

!     Compute C = (C1) = (Q**H)*B, storing the result in B
!                  (C2)
!     The NAG name equivalent of zgemqrt is f08aqf
      Call zgemqrt('Left','Conjugate transpose',m,nrhs,n,nb,a,lda,t,ldt,b,ldb, &
        work,info)

!     Compute least squares solutions by back-substitution in
!     R*X = C1
!     The NAG name equivalent of ztrtrs is f07tsf
      Call ztrtrs('Upper','No transpose','Non-Unit',n,nrhs,a,lda,b,ldb,info)

      If (info>0) Then
        Write (nout,*) 'The upper triangular factor, R, of A is singular, '
        Write (nout,*) 'the least squares solution could not be computed'
      Else

!       Print least squares solutions

!       ifail: behaviour on error exit
!              =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
        ifail = 0
        Call x04dbf('General',' ',n,nrhs,b,ldb,'Bracketed','F7.4',             &
          'Least squares solution(s)','Integer',rlabs,'Integer',clabs,80,0,    &
          ifail)

!       Compute and print estimates of the square roots of the residual
!       sums of squares
!       The NAG name equivalent of dznrm2 is f06jjf
        Do j = 1, nrhs
          rnorm(j) = dznrm2(m-n,b(n+1,j),1)
        End Do

        Write (nout,*)
        Write (nout,*) 'Square root(s) of the residual sum(s) of squares'
        Write (nout,99999) rnorm(1:nrhs)
      End If

99999 Format (3X,1P,7E11.2)
    End Program f08apfe


f08asfe.f90

    Program f08asfe

!     F08ASF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: dznrm2, nag_wp, x04dbf, zgeqrf, ztrtrs, zunmqr
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nb = 64, nin = 5, nout = 6
!     .. Local Scalars ..
      Integer                          :: i, ifail, info, j, lda, ldb, lwork,  &
                                          m, n, nrhs
!     .. Local Arrays ..
      Complex (Kind=nag_wp), Allocatable :: a(:,:), b(:,:), tau(:), work(:)
      Real (Kind=nag_wp), Allocatable  :: rnorm(:)
      Character (1)                    :: clabs(1), rlabs(1)
!     .. Executable Statements ..
      Write (nout,*) 'F08ASF Example Program Results'
      Write (nout,*)
      Flush (nout)
!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) m, n, nrhs
      lda = m
      ldb = m
      lwork = nb*n
      Allocate (a(lda,n),b(ldb,nrhs),tau(n),work(lwork),rnorm(nrhs))

!     Read A and B from data file

      Read (nin,*)(a(i,1:n),i=1,m)
      Read (nin,*)(b(i,1:nrhs),i=1,m)

!     Compute the QR factorization of A
!     The NAG name equivalent of zgeqrf is f08asf
      Call zgeqrf(m,n,a,lda,tau,work,lwork,info)

!     Compute C = (C1) = (Q**H)*B, storing the result in B
!                  (C2)
!     The NAG name equivalent of zunmqr is f08auf
      Call zunmqr('Left','Conjugate transpose',m,nrhs,n,a,lda,tau,b,ldb,work,  &
        lwork,info)

!     Compute least squares solutions by back-substitution in
!     R*X = C1
!     The NAG name equivalent of ztrtrs is f07tsf
      Call ztrtrs('Upper','No transpose','Non-Unit',n,nrhs,a,lda,b,ldb,info)

      If (info>0) Then
        Write (nout,*) 'The upper triangular factor, R, of A is singular, '
        Write (nout,*) 'the least squares solution could not be computed'
      Else

!       Print least squares solutions

!       ifail: behaviour on error exit
!              =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
        ifail = 0
        Call x04dbf('General',' ',n,nrhs,b,ldb,'Bracketed','F7.4',             &
          'Least squares solution(s)','Integer',rlabs,'Integer',clabs,80,0,    &
          ifail)

!       Compute and print estimates of the square roots of the residual
!       sums of squares
!       The NAG name equivalent of dznrm2 is f06jjf
        Do j = 1, nrhs
          rnorm(j) = dznrm2(m-n,b(n+1,j),1)
        End Do

        Write (nout,*)
        Write (nout,*) 'Square root(s) of the residual sum(s) of squares'
        Write (nout,99999) rnorm(1:nrhs)
      End If

99999 Format (3X,1P,7E11.2)
    End Program f08asfe


f08atfe.f90

    Program f08atfe

!     F08ATF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: nag_wp, x04dbf, zgeqrf, zungqr
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Integer                          :: i, ifail, info, lda, lwork, m, n
      Character (30)                   :: title
!     .. Local Arrays ..
      Complex (Kind=nag_wp), Allocatable :: a(:,:), tau(:), work(:)
      Character (1)                    :: clabs(1), rlabs(1)
!     .. Executable Statements ..
      Write (nout,*) 'F08ATF Example Program Results'
!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) m, n
      lda = m
      lwork = 64*n
      Allocate (a(lda,n),tau(n),work(lwork))

!     Read A from data file

      Read (nin,*)(a(i,1:n),i=1,m)

!     Compute the QR factorization of A
!     The NAG name equivalent of zgeqrf is f08asf
      Call zgeqrf(m,n,a,lda,tau,work,lwork,info)

!     Form the leading N columns of Q explicitly
!     The NAG name equivalent of zungqr is f08atf
      Call zungqr(m,n,n,a,lda,tau,work,lwork,info)

!     Print the leading N columns of Q only

      Write (nout,*)
      Write (title,99999) n
      Flush (nout)

!     ifail: behaviour on error exit
!             =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
      ifail = 0
      Call x04dbf('General',' ',m,n,a,lda,'Bracketed','F7.4',title,'Integer',  &
        rlabs,'Integer',clabs,80,0,ifail)

99999 Format ('The leading ',I2,' columns of Q')
    End Program f08atfe


f08avfe.f90

    Program f08avfe

!     F08AVF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: nag_wp, x04dbf, zgelqf, ztrsm, zunmlq
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Complex (Kind=nag_wp), Parameter :: one = (1.0_nag_wp,0.0_nag_wp)
      Complex (Kind=nag_wp), Parameter :: zero = (0.0_nag_wp,0.0_nag_wp)
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Integer                          :: i, ifail, info, lda, ldb, lwork, m,  &
                                          n, nrhs
!     .. Local Arrays ..
      Complex (Kind=nag_wp), Allocatable :: a(:,:), b(:,:), tau(:), work(:)
      Character (1)                    :: clabs(1), rlabs(1)
!     .. Executable Statements ..
      Write (nout,*) 'F08AVF Example Program Results'
!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) m, n, nrhs
      lda = m
      ldb = n
      lwork = 64*n
      Allocate (a(lda,n),b(ldb,nrhs),tau(n),work(lwork))

!     Read A and B from data file

      Read (nin,*)(a(i,1:n),i=1,m)
      Read (nin,*)(b(i,1:nrhs),i=1,m)

!     Compute the LQ factorization of A
!     The NAG name equivalent of zgelqf is f08avf
      Call zgelqf(m,n,a,lda,tau,work,lwork,info)

!     Solve L*Y = B, storing the result in B
!     The NAG name equivalent of ztrsm is f06zjf
      Call ztrsm('Left','Lower','No transpose','Non-Unit',m,nrhs,one,a,lda,b,  &
        ldb)

!     Set rows (M+1) to N of B to zero

      If (m<n) Then
        b(m+1:n,1:nrhs) = zero
      End If

!     Compute minimum-norm solution X = (Q**H)*B in B
!     The NAG name equivalent of zunmlq is f08axf
      Call zunmlq('Left','Conjugate transpose',n,nrhs,m,a,lda,tau,b,ldb,work,  &
        lwork,info)

!     Print minimum-norm solution(s)

      Write (nout,*)
      Flush (nout)

!     ifail: behaviour on error exit
!             =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
      ifail = 0
      Call x04dbf('General',' ',n,nrhs,b,ldb,'Bracketed','F7.4',               &
        'Minimum-norm solution(s)','Integer',rlabs,'Integer',clabs,80,0,ifail)

    End Program f08avfe


f08awfe.f90

    Program f08awfe

!     F08AWF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: nag_wp, x04dbf, zgelqf, zunglq
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Integer                          :: i, ifail, info, lda, lwork, m, n
      Character (30)                   :: title
!     .. Local Arrays ..
      Complex (Kind=nag_wp), Allocatable :: a(:,:), tau(:), work(:)
      Character (1)                    :: clabs(1), rlabs(1)
!     .. Executable Statements ..
      Write (nout,*) 'F08AWF Example Program Results'
!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) m, n
      lda = m
      lwork = 64*m
      Allocate (a(lda,n),tau(n),work(lwork))

!     Read A from data file

      Read (nin,*)(a(i,1:n),i=1,m)

!     Compute the LQ factorization of A
!     The NAG name equivalent of zgelqf is f08avf
      Call zgelqf(m,n,a,lda,tau,work,lwork,info)

!     Form the leading M rows of Q explicitly
!     The NAG name equivalent of zunglq is f08awf
      Call zunglq(m,n,m,a,lda,tau,work,lwork,info)

!     Print the leading M rows of Q only

      Write (nout,*)
      Write (title,99999) m
      Flush (nout)

!     ifail: behaviour on error exit
!             =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
      ifail = 0
      Call x04dbf('General',' ',m,n,a,lda,'Bracketed','F7.4',title,'Integer',  &
        rlabs,'Integer',clabs,80,0,ifail)

99999 Format ('The leading ',I2,' rows of Q')
    End Program f08awfe


f08bafe.f90

    Program f08bafe

!     F08BAF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: dgelsy, nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nb = 64, nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: rcond
      Integer                          :: i, info, lda, lwork, m, n, rank
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: a(:,:), b(:), work(:)
      Integer, Allocatable             :: jpvt(:)
!     .. Executable Statements ..
      Write (nout,*) 'F08BAF Example Program Results'
      Write (nout,*)
!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) m, n
      lda = m
      lwork = 3*n + nb*(n+1)
      Allocate (a(lda,n),b(m),work(lwork),jpvt(n))

!     Read A and B from data file

      Read (nin,*)(a(i,1:n),i=1,m)
      Read (nin,*) b(1:m)

!     Initialize JPVT to be zero so that all columns are free

      jpvt(1:n) = 0

!     Choose RCOND to reflect the relative accuracy of the input data

      rcond = 0.01_nag_wp

!     Solve the least squares problem min( norm2(b - Ax) ) for the x
!     of minimum norm.

!     The NAG name equivalent of dgelsy is f08baf
      Call dgelsy(m,n,1,a,lda,b,m,jpvt,rcond,rank,work,lwork,info)

!     Print solution

      Write (nout,*) 'Least squares solution'
      Write (nout,99999) b(1:n)

!     Print the effective rank of A

      Write (nout,*)
      Write (nout,*) 'Tolerance used to estimate the rank of A'
      Write (nout,99998) rcond
      Write (nout,*) 'Estimated rank of A'
      Write (nout,99997) rank

99999 Format (1X,7F11.4)
99998 Format (3X,1P,E11.2)
99997 Format (1X,I6)
    End Program f08bafe


f08bbfe.f90

    Program f08bbfe

!     F08BBF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: dgemqrt, dgeqrt, dnrm2, dtpmqrt, dtpqrt, dtrtrs,  &
                             nag_wp, x04caf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nbmax = 64, nin = 5, nout = 6
!     .. Local Scalars ..
      Integer                          :: i, ifail, info, j, lda, ldb, ldt,    &
                                          lwork, m, n, nb, nrhs
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: a(:,:), b(:,:), c(:,:), rnorm(:),    &
                                          t(:,:), work(:)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: max, min
!     .. Executable Statements ..
      Write (nout,*) 'F08BBF Example Program Results'
      Write (nout,*)
      Flush (nout)
!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) m, n, nrhs
      lda = m
      ldb = m
      nb = min(m,n,nbmax)
      ldt = nb
      lwork = nb*max(n,m)
      Allocate (a(lda,n),b(ldb,nrhs),c(ldb,nrhs),rnorm(nrhs),t(ldt,min(m,      &
        n)),work(lwork))

!     Read A and B from data file

      Read (nin,*)(a(i,1:n),i=1,m)
      Read (nin,*)(b(i,1:nrhs),i=1,m)

      c(1:m,1:nrhs) = b(1:m,1:nrhs)
!     Compute the QR factorization of first n rows of A
!     The NAG name equivalent of dgeqrt is f08abf
      Call dgeqrt(n,n,nb,a,lda,t,ldt,work,info)

!     Compute C = (C1) = (Q**T)*B, storing the result in C
!                  (C2)
!     The NAG name equivalent of dgemqrt is f08acf
      Call dgemqrt('Left','Transpose',n,nrhs,n,nb,a,lda,t,ldt,c,ldb,work,info)

      b(1:n,1:nrhs) = c(1:n,1:nrhs)
!     Compute least squares solutions for first n rows by back-substitution in
!     R*X = C1
!     The NAG name equivalent of dtrtrs is f07tef
      Call dtrtrs('Upper','No transpose','Non-Unit',n,nrhs,a,lda,c,ldb,info)

      If (info>0) Then
        Write (nout,*) 'The upper triangular factor, R, of A is singular, '
        Write (nout,*) 'the least squares solution could not be computed'
      Else

!       Print solution using first n rows

!       ifail: behaviour on error exit
!              =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
        ifail = 0
        Call x04caf('General',' ',n,nrhs,c,ldb,'solution(s) for n rows',ifail)

      End If

!     Now add the remaining rows and perform QR update
!     The NAG name equivalent of dtpqrt is f08bbf
      Call dtpqrt(m-n,n,0,nb,a,lda,a(n+1,1),lda,t,ldt,work,info)

!     Apply orthogonal transformations to C
!     The NAG name equivalent of dtpmqrt is f08bcf
      Call dtpmqrt('Left','Transpose',m-n,nrhs,n,0,nb,a(n+1,1),lda,t,ldt,b,    &
        ldb,b(5,1),ldb,work,info)
!     Compute least squares solutions for first n rows by bac-substitution in
!     R*X = C1
!     The NAG name equivalent of dtrtrs is f07tef
      Call dtrtrs('Upper','No transpose','Non-Unit',n,nrhs,a,lda,b,ldb,info)

      If (info>0) Then
        Write (nout,*) 'The upper triangular factor, R, of A is singular, '
        Write (nout,*) 'the least squares solution could not be computed'
      Else

!       Print least squares solutions
        Write (nout,*)
        ifail = 0
        Call x04caf('G',' ',n,nrhs,b,ldb,                                      &
          'Least squares solution(s) for all rows',ifail)

!       Compute and print estimates of the square roots of the residual
!       sums of squares

!       The NAG name equivalent of dnrm2 is f06ejf
        Do j = 1, nrhs
          rnorm(j) = dnrm2(m-n,b(n+1,j),1)
        End Do

        Write (nout,*)
        Write (nout,*) 'Square root(s) of the residual sum(s) of squares'
        Write (nout,99999) rnorm(1:nrhs)
      End If

99999 Format (5X,1P,7E11.2)
    End Program f08bbfe


f08befe.f90

    Program f08befe

!     F08BEF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: dgeqpf, dormqr, dtrsv, nag_wp, x04caf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Real (Kind=nag_wp), Parameter    :: zero = 0.0E0_nag_wp
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: tol
      Integer                          :: i, ifail, info, k, lda, ldb, ldx,    &
                                          lwork, m, n, nrhs
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: a(:,:), b(:,:), tau(:), work(:),     &
                                          x(:,:)
      Integer, Allocatable             :: jpvt(:)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: abs
!     .. Executable Statements ..
      Write (nout,*) 'F08BEF Example Program Results'
!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) m, n, nrhs
      lda = m
      ldb = m
      ldx = m
      lwork = 64*n
      Allocate (a(lda,n),b(ldb,nrhs),tau(n),work(lwork),x(ldx,nrhs),jpvt(n))

!     Read A and B from data file

      Read (nin,*)(a(i,1:n),i=1,m)
      Read (nin,*)(b(i,1:nrhs),i=1,m)

!     Initialize JPVT to be zero so that all columns are free

      jpvt(1:n) = 0

!     Compute the QR factorization of A

!     The NAG name equivalent of dgeqpf is f08bef
      Call dgeqpf(m,n,a,lda,jpvt,tau,work,info)

!     Choose TOL to reflect the relative accuracy of the input data

      tol = 0.01E0_nag_wp

!     Determine which columns of R to use

loop: Do k = 1, n
        If (abs(a(k,k))<=tol*abs(a(1,1))) Then
          Exit loop
        End If
      End Do loop

!     Compute C = (Q**T)*B, storing the result in B

      k = k - 1

!     The NAG name equivalent of dormqr is f08agf
      Call dormqr('Left','Transpose',m,nrhs,n,a,lda,tau,b,ldb,work,lwork,info)

!     Compute least squares solution by back-substitution in R*B = C
      Do i = 1, nrhs

!       The NAG name equivalent of dtrsv is f06pjf
        Call dtrsv('Upper','No transpose','Non-Unit',k,a,lda,b(1,i),1)

!       Set the unused elements of the I-th solution vector to zero

        b(k+1:n,i) = zero

      End Do

!     Unscramble the least squares solution stored in B

      Do i = 1, n
        x(jpvt(i),1:nrhs) = b(i,1:nrhs)
      End Do

!     Print least squares solution

      Write (nout,*)
      Flush (nout)

!     ifail: behaviour on error exit
!             =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
      ifail = 0
      Call x04caf('General',' ',n,nrhs,x,ldx,'Least squares solution',ifail)

    End Program f08befe


f08bffe.f90

    Program f08bffe

!     F08BFF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: dgeqp3, dnrm2, dormqr, dtrsm, nag_wp, x04caf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Real (Kind=nag_wp), Parameter    :: one = 1.0E0_nag_wp
      Real (Kind=nag_wp), Parameter    :: zero = 0.0E0_nag_wp
      Integer, Parameter               :: inc1 = 1, nb = 64, nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: tol
      Integer                          :: i, ifail, info, j, k, lda, ldb,      &
                                          lwork, m, n, nrhs
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: a(:,:), b(:,:), rnorm(:), tau(:),    &
                                          work(:)
      Integer, Allocatable             :: jpvt(:)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: abs
!     .. Executable Statements ..
      Write (nout,*) 'F08BFF Example Program Results'
      Write (nout,*)
!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) m, n, nrhs
      lda = m
      ldb = m
      lwork = 2*n + (n+1)*nb
      Allocate (a(lda,n),b(ldb,nrhs),rnorm(n),tau(n),work(lwork),jpvt(n))

!     Read A and B from data file

      Read (nin,*)(a(i,1:n),i=1,m)
      Read (nin,*)(b(i,1:nrhs),i=1,m)

!     Initialize JPVT to be zero so that all columns are free

      jpvt(1:n) = 0

!     Compute the QR factorization of A
!     The NAG name equivalent of dgeqp3 is f08bff
      Call dgeqp3(m,n,a,lda,jpvt,tau,work,lwork,info)

!     Compute C = (C1) = (Q**T)*B, storing the result in B
!                  (C2)
!     The NAG name equivalent of dormqr is f08agf
      Call dormqr('Left','Transpose',m,nrhs,n,a,lda,tau,b,ldb,work,lwork,info)

!     Choose TOL to reflect the relative accuracy of the input data

      tol = 0.01_nag_wp

!     Determine and print the rank, K, of R relative to TOL

loop: Do k = 1, n
        If (abs(a(k,k))<=tol*abs(a(1,1))) Then
          Exit loop
        End If
      End Do loop
      k = k - 1

      Write (nout,*) 'Tolerance used to estimate the rank of A'
      Write (nout,99999) tol
      Write (nout,*) 'Estimated rank of A'
      Write (nout,99998) k
      Write (nout,*)
      Flush (nout)

!     Compute least squares solutions by back-substitution in
!     R(1:K,1:K)*Y = C1, storing the result in B

      Call dtrsm('Left','Upper','No transpose','Non-Unit',k,nrhs,one,a,lda,b,  &
        ldb)

!     Compute estimates of the square roots of the residual sums of
!     squares (2-norm of each of the columns of C2)

!     The NAG name equivalent of dnrm2 is f06ejf
      Do j = 1, nrhs
        rnorm(j) = dnrm2(m-k,b(k+1,j),inc1)
      End Do

!     Set the remaining elements of the solutions to zero (to give
!     the basic solutions)

      b(k+1:n,1:nrhs) = zero

!     Permute the least squares solutions stored in B to give X = P*Y

      Do j = 1, nrhs
        work(jpvt(1:n)) = b(1:n,j)
        b(1:n,j) = work(1:n)
      End Do

!     Print least squares solutions

!     ifail: behaviour on error exit
!             =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
      ifail = 0
      Call x04caf('General',' ',n,nrhs,b,ldb,'Least squares solution(s)',      &
        ifail)

!     Print the square roots of the residual sums of squares

      Write (nout,*)
      Write (nout,*) 'Square root(s) of the residual sum(s) of squares'
      Write (nout,99999) rnorm(1:nrhs)

99999 Format (5X,1P,6E11.2)
99998 Format (1X,I8)
    End Program f08bffe


f08bhfe.f90

    Program f08bhfe

!     F08BHF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: dgeqp3, dnrm2, dormqr, dormrz, dtrsm, dtzrzf,     &
                             nag_wp, x04caf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Real (Kind=nag_wp), Parameter    :: one = 1.0E0_nag_wp
      Real (Kind=nag_wp), Parameter    :: zero = 0.0E0_nag_wp
      Integer, Parameter               :: inc1 = 1, nb = 64, nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: tol
      Integer                          :: i, ifail, info, j, k, lda, ldb,      &
                                          lwork, m, n, nrhs
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: a(:,:), b(:,:), rnorm(:), tau(:),    &
                                          work(:)
      Integer, Allocatable             :: jpvt(:)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: abs
!     .. Executable Statements ..
      Write (nout,*) 'F08BHF Example Program Results'
      Write (nout,*)
!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) m, n, nrhs
      lda = m
      ldb = m
      lwork = 2*n + (n+1)*nb
      Allocate (a(lda,n),b(ldb,nrhs),rnorm(n),tau(n),work(lwork),jpvt(n))

!     Read A and B from data file

      Read (nin,*)(a(i,1:n),i=1,m)
      Read (nin,*)(b(i,1:nrhs),i=1,m)

!     Initialize JPVT to be zero so that all columns are free

      jpvt(1:n) = 0

!     Compute the QR factorization of A with column pivoting as
!     A = Q*(R11 R12)*(P**T)
!            ( 0  R22)

!     The NAG name equivalent of dgeqp3 is f08bff
      Call dgeqp3(m,n,a,lda,jpvt,tau,work,lwork,info)

!     Compute C = (C1) = (Q**T)*B, storing the result in B
!                  (C2)
!     The NAG name equivalent of dormqr is f08agf
      Call dormqr('Left','Transpose',m,nrhs,n,a,lda,tau,b,ldb,work,lwork,info)

!     Choose TOL to reflect the relative accuracy of the input data

      tol = 0.01_nag_wp

!     Determine and print the rank, K, of R relative to TOL

loop: Do k = 1, n
        If (abs(a(k,k))<=tol*abs(a(1,1))) Then
          Exit loop
        End If
      End Do loop
      k = k - 1

      Write (nout,*) 'Tolerance used to estimate the rank of A'
      Write (nout,99999) tol
      Write (nout,*) 'Estimated rank of A'
      Write (nout,99998) k
      Write (nout,*)
      Flush (nout)

!     Compute the RZ factorization of the K by K part of R as
!     (R11 R12) = (T 0)*Z
!     The NAG name equivalent of dtzrzf is f08bhf
      Call dtzrzf(k,n,a,lda,tau,work,lwork,info)

!     Compute least squares solutions of triangular problems by
!     back-substitution in T*Y1 = C1, storing the result in B
!     The NAG name equivalent of dtrsm is f06yjf
      Call dtrsm('Left','Upper','No transpose','Non-Unit',k,nrhs,one,a,lda,b,  &
        ldb)

!     Compute estimates of the square roots of the residual sums of
!     squares (2-norm of each of the columns of C2)
!     The NAG name equivalent of dnrm2 is f06ejf
      Do j = 1, nrhs
        rnorm(j) = dnrm2(m-k,b(k+1,j),inc1)
      End Do

!     Set the remaining elements of the solutions to zero (to give
!     the minimum-norm solutions), Y2 = 0

      b(k+1:n,1:nrhs) = zero

!     Form W = (Z**T)*Y

!     The NAG name equivalent of dormrz is f08bkf
      Call dormrz('Left','Transpose',n,nrhs,k,n-k,a,lda,tau,b,ldb,work,lwork,  &
        info)

!     Permute the least squares solutions stored in B to give X = P*W

      Do j = 1, nrhs
        work(jpvt(1:n)) = b(1:n,j)
        b(1:n,j) = work(1:n)
      End Do

!     Print least squares solutions

!     ifail: behaviour on error exit
!             =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
      ifail = 0
      Call x04caf('General',' ',n,nrhs,b,ldb,'Least squares solution(s)',      &
        ifail)

!     Print the square roots of the residual sums of squares

      Write (nout,*)
      Write (nout,*) 'Square root(s) of the residual sum(s) of squares'
      Write (nout,99999) rnorm(1:nrhs)

99999 Format (5X,1P,6E11.2)
99998 Format (1X,I8)
    End Program f08bhfe


f08bnfe.f90

    Program f08bnfe

!     F08BNF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: nag_wp, zgelsy
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nb = 64, nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: rcond
      Integer                          :: i, info, lda, lwork, m, n, rank
!     .. Local Arrays ..
      Complex (Kind=nag_wp), Allocatable :: a(:,:), b(:), work(:)
      Real (Kind=nag_wp), Allocatable  :: rwork(:)
      Integer, Allocatable             :: jpvt(:)
!     .. Executable Statements ..
      Write (nout,*) 'F08BNF Example Program Results'
      Write (nout,*)
!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) m, n
      lda = m
      lwork = nb*(n+1)
      Allocate (a(lda,n),b(m),work(lwork),rwork(2*n),jpvt(n))

!     Read A and B from data file

      Read (nin,*)(a(i,1:n),i=1,m)
      Read (nin,*) b(1:m)

!     Initialize JPVT to be zero so that all columns are free

      jpvt(1:n) = 0

!     Choose RCOND to reflect the relative accuracy of the input data

      rcond = 0.01_nag_wp

!     Solve the least squares problem min( norm2(b - Ax) ) for the x
!     of minimum norm.

!     The NAG name equivalent of zgelsy is f08bnf
      Call zgelsy(m,n,1,a,lda,b,m,jpvt,rcond,rank,work,lwork,rwork,info)

!     Print solution

      Write (nout,*) 'Least squares solution'
      Write (nout,99999) b(1:n)

!     Print the effective rank of A

      Write (nout,*)
      Write (nout,*) 'Tolerance used to estimate the rank of A'
      Write (nout,99998) rcond
      Write (nout,*) 'Estimated rank of A'
      Write (nout,99997) rank

99999 Format (4(' (',F7.4,',',F7.4,')',:))
99998 Format (1X,1P,E10.2)
99997 Format (1X,I6)
    End Program f08bnfe


f08bpfe.f90

    Program f08bpfe

!     F08BPF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: dznrm2, nag_wp, x04dbf, zgemqrt, zgeqrt, ztpmqrt, &
                             ztpqrt, ztrtrs
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nbmax = 64, nin = 5, nout = 6
!     .. Local Scalars ..
      Integer                          :: i, ifail, info, j, lda, ldb, ldt,    &
                                          lwork, m, n, nb, nrhs
!     .. Local Arrays ..
      Complex (Kind=nag_wp), Allocatable :: a(:,:), b(:,:), c(:,:), t(:,:),    &
                                          work(:)
      Real (Kind=nag_wp), Allocatable  :: rnorm(:)
      Character (1)                    :: clabs(1), rlabs(1)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: max, min
!     .. Executable Statements ..
      Write (nout,*) 'F08BPF Example Program Results'
      Write (nout,*)
      Flush (nout)
!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) m, n, nrhs
      lda = m
      ldb = m
      nb = min(m,n,nbmax)
      ldt = nb
      lwork = nb*max(n,m)
      Allocate (a(lda,n),b(ldb,nrhs),c(ldb,nrhs),rnorm(nrhs),t(ldt,min(m,      &
        n)),work(lwork))

!     Read A and B from data file

      Read (nin,*)(a(i,1:n),i=1,m)
      Read (nin,*)(b(i,1:nrhs),i=1,m)

      c(1:m,1:nrhs) = b(1:m,1:nrhs)
!     Compute the QR factorization of first n rows of A
!     The NAG name equivalent of zgeqrt is f08apf
      Call zgeqrt(n,n,nb,a,lda,t,ldt,work,info)

!     Compute C = (C1) = (Q**H)*B, storing the result in C
!                 (C2)
!     The NAG name equivalent of zgemqrt is f08aqf
      Call zgemqrt('Left','Conjugate Transpose',n,nrhs,n,nb,a,lda,t,ldt,c,ldb, &
        work,info)

      b(1:n,1:nrhs) = c(1:n,1:nrhs)
!     Compute least squares solutions for first n rows by back-substitution in
!     R*X = C1
!     The NAG name equivalent of ztrtrs is f07tsf
      Call ztrtrs('Upper','No transpose','Non-Unit',n,nrhs,a,lda,c,ldb,info)

      If (info>0) Then
        Write (nout,*) 'The upper triangular factor, R, of A is singular, '
        Write (nout,*) 'the least squares solution could not be computed'
      Else

!       Print solution using first n rows

!       ifail: behaviour on error exit
!              =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
        ifail = 0
        Call x04dbf('General',' ',n,nrhs,c,ldb,'Bracketed','F7.4',             &
          'solution(s) for n rows','Integer',rlabs,'Integer',clabs,80,0,ifail)

      End If

!     Now add the remaining rows and perform QR update
!     The NAG name equivalent of ztpqrt is f08bpf
      Call ztpqrt(m-n,n,0,nb,a,lda,a(n+1,1),lda,t,ldt,work,info)

!     Apply orthogonal transformations to C
!     The NAG name equivalent of ztpmqrt is f08bqf
      Call ztpmqrt('Left','Conjugate Transpose',m-n,nrhs,n,0,nb,a(n+1,1),lda,  &
        t,ldt,b,ldb,b(5,1),ldb,work,info)
!     Compute least squares solutions for first n rows by back-substitution in
!     R*X = C1
!     The NAG name equivalent of ztrtrs is f07tsf
      Call ztrtrs('Upper','No transpose','Non-Unit',n,nrhs,a,lda,b,ldb,info)

      If (info>0) Then
        Write (nout,*) 'The upper triangular factor, R, of A is singular, '
        Write (nout,*) 'the least squares solution could not be computed'
      Else

!       Print least squares solutions
        Write (nout,*)
        ifail = 0
        Call x04dbf('G',' ',n,nrhs,b,ldb,'Bracketed','F7.4',                   &
          'Least squares solution(s) for all rows','Integer',rlabs,'Integer',  &
          clabs,80,0,ifail)

!       Compute and print estimates of the square roots of the residual
!       sums of squares

!       The NAG name equivalent of dznrm2 is f06jjf
        Do j = 1, nrhs
          rnorm(j) = dznrm2(m-n,b(n+1,j),1)
        End Do

        Write (nout,*)
        Write (nout,*) 'Square root(s) of the residual sum(s) of squares'
        Write (nout,99999) rnorm(1:nrhs)
      End If

99999 Format (5X,1P,7E11.2)
    End Program f08bpfe


f08bsfe.f90

    Program f08bsfe

!     F08BSF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: nag_wp, x04dbf, zgeqpf, ztrsv, zunmqr
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Complex (Kind=nag_wp), Parameter :: zero = (0.0E0_nag_wp,0.0E0_nag_wp)
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: tol
      Integer                          :: i, ifail, info, k, lda, ldb, ldx,    &
                                          lwork, m, n, nrhs
!     .. Local Arrays ..
      Complex (Kind=nag_wp), Allocatable :: a(:,:), b(:,:), tau(:), work(:),   &
                                          x(:,:)
      Real (Kind=nag_wp), Allocatable  :: rwork(:)
      Integer, Allocatable             :: jpvt(:)
      Character (1)                    :: clabs(1), rlabs(1)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: abs
!     .. Executable Statements ..
      Write (nout,*) 'F08BSF Example Program Results'
!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) m, n, nrhs
      lda = m
      ldb = m
      ldx = m
      lwork = 64*n
      Allocate (a(lda,n),b(ldb,nrhs),tau(n),work(lwork),x(ldx,nrhs),           &
        rwork(2*n),jpvt(n))

!     Read A and B from data file

      Read (nin,*)(a(i,1:n),i=1,m)
      Read (nin,*)(b(i,1:nrhs),i=1,m)

!     Initialize JPVT to be zero so that all columns are free

      jpvt(1:n) = 0

!     Compute the QR factorization of A
!     The NAG name equivalent of zgeqpf is f08bsf
      Call zgeqpf(m,n,a,lda,jpvt,tau,work,rwork,info)

!     Choose TOL to reflect the relative accuracy of the input data

      tol = 0.01_nag_wp

!     Determine which columns of R to use

loop: Do k = 1, n
        If (abs(a(k,k))<=tol*abs(a(1,1))) Then
          Exit loop
        End If
      End Do loop

!     Compute C = (Q**H)*B, storing the result in B

      k = k - 1

!     The NAG name equivalent of zunmqr is f08auf
      Call zunmqr('Left','Conjugate Transpose',m,nrhs,k,a,lda,tau,b,ldb,work,  &
        lwork,info)

!     Compute least squares solution by back-substitution in R*B = C

      Do i = 1, nrhs

!       The NAG name equivalent of ztrsv is f06sjf
        Call ztrsv('Upper','No transpose','Non-Unit',k,a,lda,b(1,i),1)

!       Set the unused elements of the I-th solution vector to zero

        b(k+1:n,i) = zero

      End Do

!     Unscramble the least squares solution stored in B

      Do i = 1, n
        x(jpvt(i),1:nrhs) = b(i,1:nrhs)
      End Do

!     Print least squares solution

      Write (nout,*)
      Flush (nout)

!     ifail: behaviour on error exit
!             =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
      ifail = 0
      Call x04dbf('General',' ',n,nrhs,x,ldx,'Bracketed','F7.4',               &
        'Least squares solution','Integer',rlabs,'Integer',clabs,80,0,ifail)

    End Program f08bsfe


f08btfe.f90

    Program f08btfe

!     F08BTF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: dznrm2, nag_wp, x04dbf, zgeqp3, ztrsm, zunmqr
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Complex (Kind=nag_wp), Parameter :: one = (1.0E0_nag_wp,0.0E0_nag_wp)
      Complex (Kind=nag_wp), Parameter :: zero = (0.0E0_nag_wp,0.0E0_nag_wp)
      Integer, Parameter               :: inc1 = 1, nb = 64, nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: tol
      Integer                          :: i, ifail, info, j, k, lda, ldb,      &
                                          lwork, m, n, nrhs
!     .. Local Arrays ..
      Complex (Kind=nag_wp), Allocatable :: a(:,:), b(:,:), tau(:), work(:)
      Real (Kind=nag_wp), Allocatable  :: rnorm(:), rwork(:)
      Integer, Allocatable             :: jpvt(:)
      Character (1)                    :: clabs(1), rlabs(1)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: abs
!     .. Executable Statements ..
      Write (nout,*) 'F08BTF Example Program Results'
      Write (nout,*)
!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) m, n, nrhs
      lda = m
      ldb = m
      lwork = (n+1)*nb
      Allocate (a(lda,n),b(ldb,nrhs),tau(n),work(lwork),rnorm(nrhs),           &
        rwork(2*n),jpvt(n))

!     Read A and B from data file

      Read (nin,*)(a(i,1:n),i=1,m)
      Read (nin,*)(b(i,1:nrhs),i=1,m)

!     Initialize JPVT to be zero so that all columns are free

      jpvt(1:n) = 0

!     Compute the QR factorization of A

!     The NAG name equivalent of zgeqp3 is f08btf
      Call zgeqp3(m,n,a,lda,jpvt,tau,work,lwork,rwork,info)

!     Compute C = (C1) = (Q**H)*B, storing the result in B
!                  (C2)

!     The NAG name equivalent of zunmqr is f08auf
      Call zunmqr('Left','Conjugate Transpose',m,nrhs,n,a,lda,tau,b,ldb,work,  &
        lwork,info)

!     Choose TOL to reflect the relative accuracy of the input data

      tol = 0.01_nag_wp

!     Determine and print the rank, K, of R relative to TOL

loop: Do k = 1, n
        If (abs(a(k,k))<=tol*abs(a(1,1))) Then
          Exit loop
        End If
      End Do loop
      k = k - 1

      Write (nout,*) 'Tolerance used to estimate the rank of A'
      Write (nout,99999) tol
      Write (nout,*) 'Estimated rank of A'
      Write (nout,99998) k
      Write (nout,*)
      Flush (nout)

!     Compute least squares solutions by back-substitution in
!     R(1:K,1:K)*Y = C1, storing the result in B

!     The NAG name equivalent of ztrsm is f06zjf
      Call ztrsm('Left','Upper','No transpose','Non-Unit',k,nrhs,one,a,lda,b,  &
        ldb)

!     Compute estimates of the square roots of the residual sums of
!     squares (2-norm of each of the columns of C2)

!     The NAG name equivalent of dznrm2 is f06jjf
      Do j = 1, nrhs
        rnorm(j) = dznrm2(m-k,b(k+1,j),inc1)
      End Do

!     Set the remaining elements of the solutions to zero (to give
!     the basic solutions)

      b(k+1:n,1:nrhs) = zero

!     Permute the least squares solutions stored in B to give X = P*Y

      Do j = 1, nrhs
        work(jpvt(1:n)) = b(1:n,j)
        b(1:n,j) = work(1:n)
      End Do

!     Print least squares solutions

!     ifail: behaviour on error exit
!             =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
      ifail = 0
      Call x04dbf('General',' ',n,nrhs,b,ldb,'Bracketed','F7.4',               &
        'Least squares solution(s)','Integer',rlabs,'Integer',clabs,80,0,      &
        ifail)

!     Print the square roots of the residual sums of squares

      Write (nout,*)
      Write (nout,*) 'Square root(s) of the residual sum(s) of squares'
      Write (nout,99999) rnorm(1:nrhs)

99999 Format (3X,1P,7E11.2)
99998 Format (1X,I8)
    End Program f08btfe


f08bvfe.f90

    Program f08bvfe

!     F08BVF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: dznrm2, nag_wp, x04dbf, zgeqp3, ztrsm, ztzrzf,    &
                             zunmqr, zunmrz
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Complex (Kind=nag_wp), Parameter :: one = (1.0_nag_wp,0.0_nag_wp)
      Complex (Kind=nag_wp), Parameter :: zero = (0.0_nag_wp,0.0_nag_wp)
      Integer, Parameter               :: inc1 = 1, nb = 64, nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: tol
      Integer                          :: i, ifail, info, j, k, lda, ldb,      &
                                          lwork, m, n, nrhs
!     .. Local Arrays ..
      Complex (Kind=nag_wp), Allocatable :: a(:,:), b(:,:), tau(:), work(:)
      Real (Kind=nag_wp), Allocatable  :: rnorm(:), rwork(:)
      Integer, Allocatable             :: jpvt(:)
      Character (1)                    :: clabs(1), rlabs(1)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: abs
!     .. Executable Statements ..
      Write (nout,*) 'F08BVF Example Program Results'
      Write (nout,*)
!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) m, n, nrhs
      lda = m
      ldb = m
      lwork = (n+1)*nb
      Allocate (a(lda,n),b(ldb,nrhs),tau(n),work(lwork),rnorm(n),rwork(2*n),   &
        jpvt(n))

!     Read A and B from data file

      Read (nin,*)(a(i,1:n),i=1,m)
      Read (nin,*)(b(i,1:nrhs),i=1,m)

!     Initialize JPVT to be zero so that all columns are free

      jpvt(1:n) = 0

!     Compute the QR factorization of A with column pivoting as
!     A = Q*(R11 R12)*(P**T)
!            ( 0  R22)
!     The NAG name equivalent of zgeqp3 is f08btf
      Call zgeqp3(m,n,a,lda,jpvt,tau,work,lwork,rwork,info)

!     Compute C = (C1) = (Q**H)*B, storing the result in B
!                  (C2)
!     The NAG name equivalent of zunmqr is f08auf
      Call zunmqr('Left','Conjugate transpose',m,nrhs,n,a,lda,tau,b,ldb,work,  &
        lwork,info)

!     Choose TOL to reflect the relative accuracy of the input data

      tol = 0.01_nag_wp

!     Determine and print the rank, K, of R relative to TOL

loop: Do k = 1, n
        If (abs(a(k,k))<=tol*abs(a(1,1))) Then
          Exit loop
        End If
      End Do loop
      k = k - 1

      Write (nout,*) 'Tolerance used to estimate the rank of A'
      Write (nout,99999) tol
      Write (nout,*) 'Estimated rank of A'
      Write (nout,99998) k
      Write (nout,*)
      Flush (nout)

!     Compute the RZ factorization of the K by K part of R as
!     (R1 R2) = (T 0)*Z
!     The NAG name equivalent of ztzrzf is f08bvf
      Call ztzrzf(k,n,a,lda,tau,work,lwork,info)

!     Compute least squares solutions of triangular problems by
!     back substitution in T*Y1 = C1, storing the result in B
!     The NAG name equivalent of ztrsm is f06zjf
      Call ztrsm('Left','Upper','No transpose','Non-Unit',k,nrhs,one,a,lda,b,  &
        ldb)

!     Compute estimates of the square roots of the residual sums of
!     squares (2-norm of each of the columns of C2)

!     The NAG name equivalent of dznrm2 is f06jjf
      Do j = 1, nrhs
        rnorm(j) = dznrm2(m-k,b(k+1,j),inc1)
      End Do

!     Set the remaining elements of the solutions to zero (to give
!     the minimum-norm solutions), Y2 = 0

      b(k+1:n,1:nrhs) = zero

!     Form W = (Z**H)*Y
!     The NAG name equivalent of zunmrz is f08bxf
      Call zunmrz('Left','Conjugate transpose',n,nrhs,k,n-k,a,lda,tau,b,ldb,   &
        work,lwork,info)

!     Permute the least squares solutions stored in B to give X = P*W

      Do j = 1, nrhs
        Do i = 1, n
          work(jpvt(i)) = b(i,j)
        End Do
        b(1:n,j) = work(1:n)
      End Do

!     Print least squares solutions

!     ifail: behaviour on error exit
!             =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
      ifail = 0
      Call x04dbf('General',' ',n,nrhs,b,ldb,'Bracketed','F7.4',               &
        'Least squares solution(s)','Integer',rlabs,'Integer',clabs,80,0,      &
        ifail)

!     Print the square roots of the residual sums of squares

      Write (nout,*)
      Write (nout,*) 'Square root(s) of the residual sum(s) of squares'
      Write (nout,99999) rnorm(1:nrhs)

99999 Format (3X,1P,7E11.2)
99998 Format (1X,I6)
    End Program f08bvfe


f08cefe.f90

    Program f08cefe

!     F08CEF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: dgeqlf, dnrm2, dormql, dtrtrs, nag_wp, x04caf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nb = 64, nin = 5, nout = 6
!     .. Local Scalars ..
      Integer                          :: i, ifail, info, j, lda, ldb, lwork,  &
                                          m, n, nrhs
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: a(:,:), b(:,:), rnorm(:), tau(:),    &
                                          work(:)
!     .. Executable Statements ..
      Write (nout,*) 'F08CEF Example Program Results'
      Write (nout,*)
      Flush (nout)
!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) m, n, nrhs
      lda = m
      ldb = m
      lwork = nb*n
      Allocate (a(lda,n),b(ldb,nrhs),rnorm(nrhs),tau(n),work(lwork))

!     Read A and B from data file

      Read (nin,*)(a(i,1:n),i=1,m)
      Read (nin,*)(b(i,1:nrhs),i=1,m)

!     Compute the QL factorization of A
!     The NAG name equivalent of dgeqlf is f08cef
      Call dgeqlf(m,n,a,lda,tau,work,lwork,info)

!     Compute C = (C1) = (Q**T)*B, storing the result in B
!                  (C2)
!     The NAG name equivalent of dormql is f08cgf
      Call dormql('Left','Transpose',m,nrhs,n,a,lda,tau,b,ldb,work,lwork,info)

!     Compute least squares solutions by back-substitution in
!     L*X = C2
!     The NAG name equivalent of dtrtrs is f07tef
      Call dtrtrs('Lower','No transpose','Non-Unit',n,nrhs,a(m-n+1,1),lda,     &
        b(m-n+1,1),ldb,info)

      If (info>0) Then
        Write (nout,*) 'The lower triangular factor, L, of A is singular, '
        Write (nout,*) 'the least squares solution could not be computed'
      Else

!       Print least squares solution(s)

!       ifail: behaviour on error exit
!              =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
        ifail = 0
        Call x04caf('General',' ',n,nrhs,b(m-n+1,1),ldb,                       &
          'Least squares solution(s)',ifail)

!       Compute and print estimates of the square roots of the residual
!       sums of squares

!       The NAG name equivalent of dnrm2 is f06ejf
        Do j = 1, nrhs
          rnorm(j) = dnrm2(m-n,b(1,j),1)
        End Do

        Write (nout,*)
        Write (nout,*) 'Square root(s) of the residual sum(s) of squares'
        Write (nout,99999) rnorm(1:nrhs)
      End If

99999 Format (5X,1P,7E11.2)
    End Program f08cefe


f08cffe.f90

    Program f08cffe

!     F08CFF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: dgeqlf, dorgql, nag_wp, x04caf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nb = 64, nin = 5, nout = 6
!     .. Local Scalars ..
      Integer                          :: i, ifail, info, lda, lwork, m, n
      Character (30)                   :: title
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: a(:,:), tau(:), work(:)
!     .. Executable Statements ..
      Write (nout,*) 'F08CFF Example Program Results'
      Write (nout,*)
!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) m, n
      lda = m
      lwork = nb*n
      Allocate (a(lda,n),tau(n),work(lwork))

!     Read A from data file

      Read (nin,*)(a(i,1:n),i=1,m)

!     Compute the QL factorization of A

!     The NAG name equivalent of dgeqlf is f08cef
      Call dgeqlf(m,n,a,lda,tau,work,lwork,info)

!     Form the leading N columns of Q explicitly

!     The NAG name equivalent of dorgql is f08cff
      Call dorgql(m,n,n,a,lda,tau,work,lwork,info)

!     Form the heading for X04CAF

      Write (title,99999) n
      Flush (nout)

!     Print the leading N columns of Q

!     ifail: behaviour on error exit
!             =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
      ifail = 0
      Call x04caf('General',' ',m,n,a,lda,title,ifail)

99999 Format ('The leading ',I4,' columns of Q')
    End Program f08cffe


f08chfe.f90

    Program f08chfe

!     F08CHF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: dgerqf, dormrq, dtrtrs, nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Real (Kind=nag_wp), Parameter    :: zero = 0.0E0_nag_wp
      Integer, Parameter               :: nb = 64, nin = 5, nout = 6
!     .. Local Scalars ..
      Integer                          :: i, info, lda, lwork, m, n
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: a(:,:), b(:), tau(:), work(:), x(:)
!     .. Executable Statements ..
      Write (nout,*) 'F08CHF Example Program Results'
      Write (nout,*)
!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) m, n
      lda = m
      lwork = nb*m
      Allocate (a(lda,n),b(m),tau(m),work(lwork),x(n))

!     Read the matrix A and the vector b from data file

      Read (nin,*)(a(i,1:n),i=1,m)
      Read (nin,*) b(1:m)

!     Compute the RQ factorization of A
!     The NAG name equivalent of dgerqf is f08chf
      Call dgerqf(m,n,a,lda,tau,work,lwork,info)

!     Copy the m element vector b into elements x(n-m+1), ..., x(n) of x

      x(n-m+1:n) = b(1:m)

!     Solve R*y2 = b, storing the result in x2
!     The NAG name equivalent of dtrtrs is f07tef
      Call dtrtrs('Upper','No transpose','Non-Unit',m,1,a(1,n-m+1),lda,        &
        x(n-m+1),m,info)

      If (info>0) Then
        Write (nout,*) 'The upper triangular factor, R, of A is singular, '
        Write (nout,*) 'the least squares solution could not be computed'
      Else

        x(1:n-m) = zero

!       Compute the minimum-norm solution x = (Q**T)*y
!       The NAG name equivalent of dormrq is f08ckf
        Call dormrq('Left','Transpose',n,1,m,a,lda,tau,x,n,work,lwork,info)

!       Print minimum-norm solution

        Write (nout,*) 'Minimum-norm solution'
        Write (nout,99999) x(1:n)

      End If

99999 Format (1X,8F9.4)
    End Program f08chfe


f08cjfe.f90

    Program f08cjfe

!     F08CJF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: dgerqf, dorgrq, nag_wp, x04caf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nb = 64, nin = 5, nout = 6
!     .. Local Scalars ..
      Integer                          :: i, ifail, info, lda, lwork, m, n
      Character (26)                   :: title
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: a(:,:), tau(:), work(:)
!     .. Executable Statements ..
      Write (nout,*) 'F08CJF Example Program Results'
      Write (nout,*)
!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) m, n
      lda = m
      lwork = nb*m
      Allocate (a(lda,n),tau(n),work(lwork))

!     Read A from data file

      Read (nin,*)(a(i,1:n),i=1,m)

!     Compute the RQ factorization of A
!     The NAG name equivalent of dgerqf is f08chf
      Call dgerqf(m,n,a,lda,tau,work,lwork,info)

!     Form the leading M rows of Q explicitly
!     The NAG name equivalent of dorgrq is f08cjf
      Call dorgrq(m,n,m,a,lda,tau,work,lwork,info)

!     Form the heading for X04CAF

      Write (title,99999) m
      Flush (nout)

!     Print the leading M rows of Q

!     ifail: behaviour on error exit
!             =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
      ifail = 0
      Call x04caf('General',' ',m,n,a,lda,title,ifail)

99999 Format ('The leading ',I4,' rows of Q')
    End Program f08cjfe


f08csfe.f90

    Program f08csfe

!     F08CSF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: dznrm2, nag_wp, x04dbf, zgeqlf, ztrtrs, zunmql
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nb = 64, nin = 5, nout = 6
!     .. Local Scalars ..
      Integer                          :: i, ifail, info, j, lda, ldb, lwork,  &
                                          m, n, nrhs
!     .. Local Arrays ..
      Complex (Kind=nag_wp), Allocatable :: a(:,:), b(:,:), tau(:), work(:)
      Real (Kind=nag_wp), Allocatable  :: rnorm(:)
      Character (1)                    :: clabs(1), rlabs(1)
!     .. Executable Statements ..
      Write (nout,*) 'F08CSF Example Program Results'
      Write (nout,*)
      Flush (nout)
!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) m, n, nrhs
      lda = m
      ldb = m
      lwork = nb*n
      Allocate (a(lda,n),b(ldb,nrhs),tau(n),work(lwork),rnorm(nrhs))

!     Read A and B from data file

      Read (nin,*)(a(i,1:n),i=1,m)
      Read (nin,*)(b(i,1:nrhs),i=1,m)

!     Compute the QL factorization of A
!     The NAG name equivalent of zgeqlf is f08csf
      Call zgeqlf(m,n,a,lda,tau,work,lwork,info)

!     Compute C = (C1) = (Q**H)*B, storing the result in B
!                  (C2)
!     The NAG name equivalent of zunmql is f08cuf
      Call zunmql('Left','Conjugate Transpose',m,nrhs,n,a,lda,tau,b,ldb,work,  &
        lwork,info)

!     Compute least squares solutions by back-substitution in
!     L*X = C2
!     The NAG name equivalent of ztrtrs is f07tsf
      Call ztrtrs('Lower','No transpose','Non-Unit',n,nrhs,a(m-n+1,1),lda,     &
        b(m-n+1,1),ldb,info)

      If (info>0) Then
        Write (nout,*) 'The lower triangular factor, L, of A is singular, '
        Write (nout,*) 'the least squares solution could not be computed'
      Else

!       Print least squares solution(s)

!       ifail: behaviour on error exit
!              =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
        ifail = 0
        Call x04dbf('General',' ',n,nrhs,b(m-n+1,1),ldb,'Bracketed','F7.4',    &
          'Least squares solution(s)','Integer',rlabs,'Integer',clabs,80,0,    &
          ifail)

!       Compute and print estimates of the square roots of the residual
!       sums of squares
!       The NAG name equivalent of dznrm2 is f06jjf
        Do j = 1, nrhs
          rnorm(j) = dznrm2(m-n,b(1,j),1)
        End Do

        Write (nout,*)
        Write (nout,*) 'Square root(s) of the residual sum(s) of squares'
        Write (nout,99999) rnorm(1:nrhs)
      End If

99999 Format (3X,1P,7E11.2)
    End Program f08csfe


f08ctfe.f90

    Program f08ctfe

!     F08CTF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: nag_wp, x04dbf, zgeqlf, zungql
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nb = 64, nin = 5, nout = 6
!     .. Local Scalars ..
      Integer                          :: i, ifail, info, lda, lwork, m, n
      Character (30)                   :: title
!     .. Local Arrays ..
      Complex (Kind=nag_wp), Allocatable :: a(:,:), tau(:), work(:)
      Character (1)                    :: clabs(1), rlabs(1)
!     .. Executable Statements ..
      Write (nout,*) 'F08CTF Example Program Results'
      Write (nout,*)
!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) m, n
      lda = m
      lwork = nb*n
      Allocate (a(lda,n),tau(n),work(lwork))

!     Read A from data file

      Read (nin,*)(a(i,1:n),i=1,m)

!     Compute the QL factorization of A
!     The NAG name equivalent of zgeqlf is f08csf
      Call zgeqlf(m,n,a,lda,tau,work,lwork,info)

!     Form the leading N columns of Q explicitly
!     The NAG name equivalent of zungql is f08ctf
      Call zungql(m,n,n,a,lda,tau,work,lwork,info)

!     Form the heading for X04DBF

      Write (title,99999) n
      Flush (nout)

!     Print the leading N columns of Q

!     ifail: behaviour on error exit
!             =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
      ifail = 0
      Call x04dbf('General',' ',m,n,a,lda,'Bracketed','F7.4',title,'Integer',  &
        rlabs,'Integer',clabs,80,0,ifail)

99999 Format ('The leading ',I4,' columns of Q')
    End Program f08ctfe


f08cvfe.f90

    Program f08cvfe

!     F08CVF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: nag_wp, zgerqf, ztrtrs, zunmrq
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Complex (Kind=nag_wp), Parameter :: zero = (0.0_nag_wp,0.0_nag_wp)
      Integer, Parameter               :: nb = 64, nin = 5, nout = 6
!     .. Local Scalars ..
      Integer                          :: i, info, lda, lwork, m, n
!     .. Local Arrays ..
      Complex (Kind=nag_wp), Allocatable :: a(:,:), b(:), tau(:), work(:),     &
                                          x(:)
!     .. Executable Statements ..
      Write (nout,*) 'F08CVF Example Program Results'
      Write (nout,*)
!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) m, n
      lda = m
      lwork = nb*m
      Allocate (a(lda,n),b(m),tau(m),work(lwork),x(n))

!     Read the matrix A and the vector b from data file

      Read (nin,*)(a(i,1:n),i=1,m)
      Read (nin,*) b(1:m)

!     Compute the RQ factorization of A
!     The NAG name equivalent of zgerqf is f08cvf
      Call zgerqf(m,n,a,lda,tau,work,lwork,info)

!     Copy the m-element vector b into elements x(n-m+1), ..., x(n) of x

      x(n-m+1:n) = b(1:m)

!     Solve R*y2 = b, storing the result in x2
!     The NAG name equivalent of ztrtrs is f07tsf
      Call ztrtrs('Upper','No transpose','Non-Unit',m,1,a(1,n-m+1),lda,        &
        x(n-m+1),m,info)

      If (info>0) Then
        Write (nout,*) 'The upper triangular factor, R, of A is singular, '
        Write (nout,*) 'the least squares solution could not be computed'
      Else

!       Set y1 to zero (stored in x(1:n-m))

        x(1:n-m) = zero

!       Compute minimum-norm solution x = (Q**H)*y
!       The NAG name equivalent of zunmrq is f08cxf
        Call zunmrq('Left','Conjugate transpose',n,1,m,a,lda,tau,x,n,work,     &
          lwork,info)

!       Print minimum-norm solution

        Write (nout,*) 'Minimum-norm solution'
        Write (nout,99999) x(1:n)
      End If

99999 Format (4(' (',F8.4,',',F8.4,')',:))
    End Program f08cvfe


f08cwfe.f90

    Program f08cwfe

!     F08CWF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: nag_wp, x04dbf, zgerqf, zungrq
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nb = 64, nin = 5, nout = 6
!     .. Local Scalars ..
      Integer                          :: i, ifail, info, lda, lwork, m, n
      Character (26)                   :: title
!     .. Local Arrays ..
      Complex (Kind=nag_wp), Allocatable :: a(:,:), tau(:), work(:)
      Character (1)                    :: clabs(1), rlabs(1)
!     .. Executable Statements ..
      Write (nout,*) 'F08CWF Example Program Results'
      Write (nout,*)
!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) m, n
      lda = m
      lwork = nb*m
      Allocate (a(lda,n),tau(n),work(lwork))

!     Read A from data file

      Read (nin,*)(a(i,1:n),i=1,m)

!     Compute the RQ factorization of A
!     The NAG name equivalent of zgerqf is f08cvf
      Call zgerqf(m,n,a,lda,tau,work,lwork,info)

!     Form the leading M rows of Q explicitly
!     The NAG name equivalent of zungrq is f08cwf
      Call zungrq(m,n,m,a,lda,tau,work,lwork,info)

!     Form the heading for X04DBF

      Write (title,99999) m
      Flush (nout)

!     Print the leading M rows of Q

!     ifail: behaviour on error exit
!             =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
      ifail = 0
      Call x04dbf('General',' ',m,n,a,lda,'Bracketed','F7.4',title,'Integer',  &
        rlabs,'Integer',clabs,80,0,ifail)

99999 Format ('The leading ',I4,' rows of Q')
    End Program f08cwfe


f08fafe.f90

    Program f08fafe

!     F08FAF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: blas_damax_val, ddisna, dsyev, nag_wp, x02ajf,    &
                             x04caf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Real (Kind=nag_wp), Parameter    :: zero = 0.0_nag_wp
      Integer, Parameter               :: nb = 64, nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: eerrbd, eps, r
      Integer                          :: i, ifail, info, k, lda, lwork, n
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: a(:,:), rcondz(:), w(:), work(:),    &
                                          zerrbd(:)
      Real (Kind=nag_wp)               :: dummy(1)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: abs, max, nint
!     .. Executable Statements ..
      Write (nout,*) 'F08FAF Example Program Results'
      Write (nout,*)
!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) n
      lda = n
      Allocate (a(lda,n),rcondz(n),w(n),zerrbd(n))

!     Use routine workspace query to get optimal workspace.
!     The NAG name equivalent of dsyev is f08faf
      lwork = -1
      Call dsyev('Vectors','Upper',n,a,lda,w,dummy,lwork,info)

!     Make sure that there is enough workspace for block size nb.
      lwork = max((nb+2)*n,nint(dummy(1)))
      Allocate (work(lwork))

!     Read the upper triangular part of the matrix A from data file

      Read (nin,*)(a(i,i:n),i=1,n)

!     Solve the symmetric eigenvalue problem
!     The NAG name equivalent of dsyev is f08faf
      Call dsyev('Vectors','Upper',n,a,lda,w,work,lwork,info)

      If (info==0) Then

!       Print solution

        Write (nout,*) 'Eigenvalues'
        Write (nout,99999) w(1:n)
        Flush (nout)

!       Normalize the eigenvectors: largest element positive
        Do i = 1, n
          Call blas_damax_val(n,a(1,i),1,k,r)
          If (a(k,i)<zero) Then
            a(1:n,i) = -a(1:n,i)
          End If
        End Do

!       ifail: behaviour on error exit
!              =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
        ifail = 0
        Call x04caf('General',' ',n,n,a,lda,'Eigenvectors',ifail)

!       Get the machine precision, EPS and compute the approximate
!       error bound for the computed eigenvalues.  Note that for
!       the 2-norm, max( abs(W(i)) ) = norm(A), and since the
!       eigenvalues are returned in ascending order
!       max( abs(W(i)) ) = max( abs(W(1)), abs(W(n)))

        eps = x02ajf()
        eerrbd = eps*max(abs(w(1)),abs(w(n)))

!       Call DDISNA (F08FLF) to estimate reciprocal condition
!       numbers for the eigenvectors
        Call ddisna('Eigenvectors',n,n,w,rcondz,info)

!       Compute the error estimates for the eigenvectors

        Do i = 1, n
          zerrbd(i) = eerrbd/rcondz(i)
        End Do

!       Print the approximate error bounds for the eigenvalues
!       and vectors

        Write (nout,*)
        Write (nout,*) 'Error estimate for the eigenvalues'
        Write (nout,99998) eerrbd
        Write (nout,*)
        Write (nout,*) 'Error estimates for the eigenvectors'
        Write (nout,99998) zerrbd(1:n)
      Else
        Write (nout,99997) 'Failure in DSYEV. INFO =', info
      End If

99999 Format (3X,(8F8.4))
99998 Format (4X,1P,6E11.1)
99997 Format (1X,A,I4)
    End Program f08fafe


f08fbfe.f90

    Program f08fbfe

!     F08FBF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: dsyevx, nag_wp, x04caf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Real (Kind=nag_wp), Parameter    :: zero = 0.0E+0_nag_wp
      Integer, Parameter               :: nb = 64, nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: abstol, vl, vu
      Integer                          :: i, ifail, il, info, iu, lda, ldz,    &
                                          lwork, m, n
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: a(:,:), w(:), work(:), z(:,:)
      Real (Kind=nag_wp)               :: dummy(1)
      Integer, Allocatable             :: iwork(:), jfail(:)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: max, nint
!     .. Executable Statements ..
      Write (nout,*) 'F08FBF Example Program Results'
      Write (nout,*)
!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) n
      lda = n
      ldz = n
      m = n
      Allocate (a(lda,n),w(n),z(ldz,m),iwork(5*n),jfail(n))

!     Read the lower and upper bounds of the interval to be searched.
      Read (nin,*) vl, vu

!     Use routine workspace query to get optimal workspace.
!     The NAG name equivalent of dsyevx is f08fbf
      lwork = -1
      Call dsyevx('Vectors','Values in range','Upper',n,a,lda,vl,vu,il,iu,     &
        abstol,m,w,z,ldz,dummy,lwork,iwork,jfail,info)

!     Make sure that there is enough workspace for block size nb.
      lwork = max((nb+3)*n,nint(dummy(1)))
      Allocate (work(lwork))

!     Read the upper triangular part of the matrix A.

      Read (nin,*)(a(i,i:n),i=1,n)

!     Set the absolute error tolerance for eigenvalues.  With ABSTOL
!     set to zero, the default value is used instead

      abstol = zero

!     Solve the symmetric eigenvalue problem
!     The NAG name equivalent of dsyevx is f08fbf
      Call dsyevx('Vectors','Values in range','Upper',n,a,lda,vl,vu,il,iu,     &
        abstol,m,w,z,ldz,work,lwork,iwork,jfail,info)

      If (info>=0) Then

!       Print solution

        Write (nout,99999) 'Number of eigenvalues found =', m
        Write (nout,*)
        Write (nout,*) 'Eigenvalues'
        Write (nout,99998) w(1:m)
        Flush (nout)

!       ifail: behaviour on error exit
!              =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
        ifail = 0
        Call x04caf('General',' ',n,m,z,ldz,'Selected eigenvectors',ifail)

        If (info>0) Then
          Write (nout,99999) 'INFO eigenvectors failed to converge, INFO =',   &
            info
          Write (nout,*) 'Indices of eigenvectors that did not converge'
          Write (nout,99997) jfail(1:m)
        End If
      Else
        Write (nout,99999) 'Failure in DSYEVX. INFO =', info
      End If

99999 Format (1X,A,I5)
99998 Format (3X,(8F8.4))
99997 Format (3X,(8I8))
    End Program f08fbfe


f08fcfe.f90

    Program f08fcfe

!     F08FCF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: blas_damax_val, dsyevd, nag_wp, x04caf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Real (Kind=nag_wp), Parameter    :: zero = 0.0_nag_wp
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: r
      Integer                          :: i, ifail, info, k, lda, liwork,      &
                                          lwork, n
      Character (1)                    :: job, uplo
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: a(:,:), w(:), work(:)
      Integer, Allocatable             :: iwork(:)
!     .. Executable Statements ..
      Write (nout,*) 'F08FCF Example Program Results'
!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) n
      lda = n
      liwork = 5*n + 3
      lwork = 2*n*n + 6*n + 1
      Allocate (a(lda,n),w(n),work(lwork),iwork(liwork))

!     Read A from data file

      Read (nin,*) uplo
      If (uplo=='U') Then
        Read (nin,*)(a(i,i:n),i=1,n)
      Else If (uplo=='L') Then
        Read (nin,*)(a(i,1:i),i=1,n)
      End If

      Read (nin,*) job

!     Calculate all the eigenvalues and eigenvectors of A
!     The NAG name equivalent of dsyevd is f08fcf
      Call dsyevd(job,uplo,n,a,lda,w,work,lwork,iwork,liwork,info)

      Write (nout,*)
      If (info>0) Then
        Write (nout,*) 'Failure to converge.'
      Else

!       Print eigenvalues and eigenvectors

        Write (nout,*) 'Eigenvalues'
        Write (nout,99999) w(1:n)
        Write (nout,*)
        Flush (nout)

!       Normalize the eigenvectors: largest element positive
        Do i = 1, n
          Call blas_damax_val(n,a(1,i),1,k,r)
          If (a(k,i)<zero) Then
            a(1:n,i) = -a(1:n,i)
          End If
        End Do

!       ifail: behaviour on error exit
!              =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
        ifail = 0
        Call x04caf('General',' ',n,n,a,lda,'Eigenvectors',ifail)

      End If

99999 Format (3X,(8F8.4))
    End Program f08fcfe


f08fdfe.f90

    Program f08fdfe

!     F08FDF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: dsyevr, nag_wp, x04caf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Real (Kind=nag_wp), Parameter    :: zero = 0.0E+0_nag_wp
      Integer, Parameter               :: nb = 64, nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: abstol, vl, vu
      Integer                          :: i, ifail, il, info, iu, lda, ldz,    &
                                          liwork, lwork, m, n
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: a(:,:), w(:), work(:), z(:,:)
      Real (Kind=nag_wp)               :: dummy(1)
      Integer                          :: idum(1)
      Integer, Allocatable             :: isuppz(:), iwork(:)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: max, nint
!     .. Executable Statements ..
      Write (nout,*) 'F08FDF Example Program Results'
      Write (nout,*)
!     Skip heading in data file and read N and the lower and upper
!     indices of the smallest and largest eigenvalues to be found
      Read (nin,*)
      Read (nin,*) n, il, iu
      lda = n
      ldz = n
      m = n
      Allocate (a(lda,n),w(n),z(ldz,m),isuppz(2*m))

!     Use routine workspace query to get optimal workspace.
      lwork = -1
      liwork = -1
!     The NAG name equivalent of dsyevr is f08fdf
      Call dsyevr('Vectors','I','Upper',n,a,lda,vl,vu,il,iu,abstol,m,w,z,ldz,  &
        isuppz,dummy,lwork,idum,liwork,info)

!     Make sure that there is enough workspace for block size nb.
      lwork = max((nb+6)*n,nint(dummy(1)))
      liwork = max(10*n,idum(1))
      Allocate (work(lwork),iwork(liwork))

!     Read the upper triangular part of the matrix A from data file

      Read (nin,*)(a(i,i:n),i=1,n)

!     Set the absolute error tolerance for eigenvalues.  With ABSTOL
!     set to zero, the default value is used instead

      abstol = zero

!     Solve the symmetric eigenvalue problem
!     The NAG name equivalent of dsyevr is f08fdf
      Call dsyevr('Vectors','I','Upper',n,a,lda,vl,vu,il,iu,abstol,m,w,z,ldz,  &
        isuppz,work,lwork,iwork,liwork,info)

      If (info==0) Then

!       Print solution

        Write (nout,*) 'Selected eigenvalues'
        Write (nout,99999) w(1:m)
        Flush (nout)

!       ifail: behaviour on error exit
!              =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
        ifail = 0
        Call x04caf('General',' ',n,m,z,ldz,'Selected eigenvectors',ifail)

      Else
        Write (nout,99998) 'Failure in DSYEVR. INFO =', info
      End If

99999 Format (3X,(8F8.4))
99998 Format (1X,A,I5)
    End Program f08fdfe


f08fefe.f90

    Program f08fefe

!     F08FEF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: dsytrd, nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Integer                          :: i, info, lda, lwork, n
      Character (1)                    :: uplo
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: a(:,:), d(:), e(:), tau(:), work(:)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: abs
!     .. Executable Statements ..
      Write (nout,*) 'F08FEF Example Program Results'
!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) n
      lda = n
      lwork = 64*n
      Allocate (a(lda,n),d(n),e(n-1),tau(n-1),work(lwork))

!     Read A from data file and copy A into C to store as a full matrix

      Read (nin,*) uplo
      If (uplo=='U') Then
        Read (nin,*)(a(i,i:n),i=1,n)
      Else If (uplo=='L') Then
        Read (nin,*)(a(i,1:i),i=1,n)
      End If

!     Reduce A to tridiagonal form
!     The NAG name equivalent of dsytrd is f08fef.
      Call dsytrd(uplo,n,a,lda,d,e,tau,work,lwork,info)

      If (info==0) Then
!       Print the diagonal and off-diagonal of tridiagonal T.
!       The absolute value of E is printed since this can vary by a change of
!       sign (corresponding to multiplying through a column of Q by -1).

        Write (nout,*)
        Write (nout,*)                                                         &
          'Diagonal and off-diagonal elements of tridiagonal form'
        Write (nout,*)
        Write (nout,99999) 'i', 'D', 'E'
        Do i = 1, n - 1
          Write (nout,99998) i, d(i), abs(e(i))
        End Do
        Write (nout,99998) n, d(n)

      Else
        Write (nout,99997) info
      End If

99999 Format (5X,A,9X,A,12X,A)
99998 Format (1X,I5,2(1X,F12.5))
99997 Format (1X,'** DSYTRD/F08FEF retuned with INFO = ',I10)

    End Program f08fefe


f08fffe.f90

    Program f08fffe

!     F08FFF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: blas_damax_val, dorgtr, dsteqr, dsytrd, f06qff,   &
                             nag_wp, x04caf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Real (Kind=nag_wp), Parameter    :: zero = 0.0_nag_wp
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: r
      Integer                          :: i, ifail, info, k, lda, ldz, lwork,  &
                                          n
      Character (1)                    :: uplo
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: a(:,:), d(:), e(:), tau(:), work(:), &
                                          z(:,:)
!     .. Executable Statements ..
      Write (nout,*) 'F08FFF Example Program Results'
!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) n
      lda = n
      ldz = n
      lwork = 64*n
      Allocate (a(lda,n),d(n),e(n),tau(n),work(lwork),z(ldz,n))

!     Read A from data file

      Read (nin,*) uplo
      If (uplo=='U') Then
        Read (nin,*)(a(i,i:n),i=1,n)
      Else If (uplo=='L') Then
        Read (nin,*)(a(i,1:i),i=1,n)
      End If

!     Reduce A to tridiagonal form T = (Q**T)*A*Q
!     The NAG name equivalent of dsytrd is f08fef
      Call dsytrd(uplo,n,a,lda,d,e,tau,work,lwork,info)

!     Copy A into Z
      Call f06qff(uplo,n,n,a,lda,z,ldz)

!     Form Q explicitly, storing the result in Z
!     The NAG name equivalent of dorgtr is f08fff
      Call dorgtr(uplo,n,z,ldz,tau,work,lwork,info)

!     Calculate all the eigenvalues and eigenvectors of A
!     The NAG name equivalent of dsteqr is f08jef
      Call dsteqr('V',n,d,e,z,ldz,work,info)

      Write (nout,*)
      If (info>0) Then
        Write (nout,*) 'Failure to converge.'
      Else

!       Print eigenvalues and eigenvectors

        Write (nout,*) 'Eigenvalues'
        Write (nout,99999) d(1:n)
        Write (nout,*)
        Flush (nout)

!       Normalize the eigenvectors: largest element positive
        Do i = 1, n
          Call blas_damax_val(n,z(1,i),1,k,r)
          If (z(k,i)<zero) Then
            z(1:n,i) = -z(1:n,i)
          End If
        End Do

!       ifail: behaviour on error exit
!              =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
        ifail = 0
        Call x04caf('General',' ',n,n,z,ldz,'Eigenvectors',ifail)

      End If

99999 Format (3X,(8F8.4))
    End Program f08fffe


f08fgfe.f90

    Program f08fgfe

!     F08FGF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: dormtr, dstebz, dstein, dsytrd, nag_wp, x04caf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Real (Kind=nag_wp), Parameter    :: zero = 0.0E0_nag_wp
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: vl, vu
      Integer                          :: i, ifail, info, lda, ldc, lwork, m,  &
                                          n, nsplit
      Character (1)                    :: uplo
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: a(:,:), c(:,:), d(:), e(:), tau(:),  &
                                          w(:), work(:)
      Integer, Allocatable             :: iblock(:), ifailv(:), isplit(:),     &
                                          iwork(:)
!     .. Executable Statements ..
      Write (nout,*) 'F08FGF Example Program Results'
!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) n
      lda = n
      ldc = n
      lwork = 64*n
      Allocate (a(lda,n),c(ldc,n),d(n),e(n),tau(n),w(n),work(lwork),iblock(n), &
        ifailv(n),isplit(n),iwork(3*n))

!     Read A from data file

      Read (nin,*) uplo
      If (uplo=='U') Then
        Read (nin,*)(a(i,i:n),i=1,n)
      Else If (uplo=='L') Then
        Read (nin,*)(a(i,1:i),i=1,n)
      End If

!     Reduce A to tridiagonal form T = (Q**T)*A*Q
      Call dsytrd(uplo,n,a,lda,d,e,tau,work,lwork,info)

!     Calculate the two smallest eigenvalues of T (same as A)

!     The NAG name equivalent of dstebz is f08jjf
      Call dstebz('I','B',n,vl,vu,1,2,zero,d,e,m,nsplit,w,iblock,isplit,work,  &
        iwork,info)

      Write (nout,*)
      If (info>0) Then
        Write (nout,*) 'Failure to converge.'
      Else
        Write (nout,*) 'Eigenvalues'
        Write (nout,99999) w(1:m)

!       Calculate the eigenvectors of T, storing the result in C
!       The NAG name equivalent of dstein is f08jkf
        Call dstein(n,d,e,m,w,iblock,isplit,c,ldc,work,iwork,ifailv,info)

        If (info>0) Then
          Write (nout,*) 'Failure to converge.'
        Else

!         Calculate the eigenvectors of A = Q * (eigenvectors of T)
!         The NAG name equivalent of dormtr is f08fgf
          Call dormtr('Left',uplo,'No transpose',n,m,a,lda,tau,c,ldc,work,     &
            lwork,info)

!         Print eigenvectors

          Write (nout,*)
          Flush (nout)

!         ifail: behaviour on error exit
!                =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
          ifail = 0
          Call x04caf('General',' ',n,m,c,ldc,'Eigenvectors',ifail)

        End If
      End If

99999 Format (3X,(9F8.4))
    End Program f08fgfe


f08fnfe.f90

    Program f08fnfe

!     F08FNF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: ddisna, nag_wp, x02ajf, x04daf, zheev, zscal
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nb = 64, nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: eerrbd, eps
      Integer                          :: i, ifail, info, k, lda, lwork, n
!     .. Local Arrays ..
      Complex (Kind=nag_wp), Allocatable :: a(:,:), work(:)
      Complex (Kind=nag_wp)            :: dummy(1)
      Real (Kind=nag_wp), Allocatable  :: rcondz(:), rwork(:), w(:), zerrbd(:)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: abs, cmplx, conjg, max, maxloc,      &
                                          nint, real
!     .. Executable Statements ..
      Write (nout,*) 'F08FNF Example Program Results'
      Write (nout,*)
!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) n
      lda = n
      Allocate (a(lda,n),rcondz(n),rwork(3*n-2),w(n),zerrbd(n))

!     Use routine workspace query to get optimal workspace.
!     The NAG name equivalent of zheev is f08fnf
      lwork = -1
      Call zheev('Vectors','Upper',n,a,lda,w,dummy,lwork,rwork,info)

!     Make sure that there is enough workspace for block size nb.
      lwork = max((nb+1)*n,nint(real(dummy(1))))
      Allocate (work(lwork))

!     Read the upper triangular part of the matrix A from data file

      Read (nin,*)(a(i,i:n),i=1,n)

!     Solve the Hermitian eigenvalue problem
!     The NAG name equivalent of zheev is f08fnf
      Call zheev('Vectors','Upper',n,a,lda,w,work,lwork,rwork,info)

      If (info==0) Then

!       Print solution

        Write (nout,*) 'Eigenvalues'
        Write (nout,99999) w(1:n)

        Write (nout,*)
        Flush (nout)

!       Normalize the eigenvectors so that the element of largest absolute
!       value is real.
        Do i = 1, n
          rwork(1:n) = abs(a(1:n,i))
          k = maxloc(rwork(1:n),1)
          Call zscal(n,conjg(a(k,i))/cmplx(abs(a(k,i)),kind=nag_wp),a(1,i),1)
        End Do

!       ifail: behaviour on error exit
!              =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
        ifail = 0
        Call x04daf('General',' ',n,n,a,lda,'Eigenvectors',ifail)

!       Get the machine precision, EPS and compute the approximate
!       error bound for the computed eigenvalues.  Note that for
!       the 2-norm, max( abs(W(i)) ) = norm(A), and since the
!       eigenvalues are returned in descending order
!       max( abs(W(i)) ) = max( abs(W(1)), abs(W(n)))

        eps = x02ajf()
        eerrbd = eps*max(abs(w(1)),abs(w(n)))

!       Call DDISNA (F08FLF) to estimate reciprocal condition
!       numbers for the eigenvectors
        Call ddisna('Eigenvectors',n,n,w,rcondz,info)

!       Compute the error estimates for the eigenvectors

        Do i = 1, n
          zerrbd(i) = eerrbd/rcondz(i)
        End Do

!       Print the approximate error bounds for the eigenvalues
!       and vectors

        Write (nout,*)
        Write (nout,*) 'Error estimate for the eigenvalues'
        Write (nout,99998) eerrbd
        Write (nout,*)
        Write (nout,*) 'Error estimates for the eigenvectors'
        Write (nout,99998) zerrbd(1:n)
      Else
        Write (nout,99997) 'Failure in ZHEEV. INFO =', info
      End If

99999 Format (3X,(8F8.4))
99998 Format (4X,1P,6E11.1)
99997 Format (1X,A,I4)
    End Program f08fnfe


f08fpfe.f90

    Program f08fpfe

!     F08FPF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: nag_wp, x04daf, zheevx, zscal
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Real (Kind=nag_wp), Parameter    :: zero = 0.0E+0_nag_wp
      Integer, Parameter               :: nb = 64, nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: abstol, vl, vu
      Integer                          :: i, ifail, il, info, iu, k, lda, ldz, &
                                          lwork, m, n
!     .. Local Arrays ..
      Complex (Kind=nag_wp), Allocatable :: a(:,:), work(:), z(:,:)
      Complex (Kind=nag_wp)            :: dummy(1)
      Real (Kind=nag_wp), Allocatable  :: rwork(:), w(:)
      Integer, Allocatable             :: iwork(:), jfail(:)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: abs, cmplx, conjg, max, maxloc,      &
                                          nint, real
!     .. Executable Statements ..
      Write (nout,*) 'F08FPF Example Program Results'
      Write (nout,*)
!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) n
      lda = n
      ldz = n
      m = n
      Allocate (a(lda,n),z(ldz,m),rwork(7*n),w(n),iwork(5*n),jfail(n))

!     Read the lower and upper bounds of the interval to be searched.
      Read (nin,*) vl, vu

!     Use routine workspace query to get optimal workspace.
      lwork = -1
!     The NAG name equivalent of zheevx is f08fpf
      Call zheevx('Vectors','Values in range','Upper',n,a,lda,vl,vu,il,iu,     &
        abstol,m,w,z,ldz,dummy,lwork,rwork,iwork,jfail,info)

!     Make sure that there is enough workspace for block size nb.
      lwork = max((nb+1)*n,nint(real(dummy(1))))
      Allocate (work(lwork))

!     Read the upper triangular part of the matrix A.

      Read (nin,*)(a(i,i:n),i=1,n)

!     Set the absolute error tolerance for eigenvalues.  With ABSTOL
!     set to zero, the default value is used instead

      abstol = zero

!     Solve the Hermitian eigenvalue problem

!     The NAG name equivalent of zheevx is f08fpf
      Call zheevx('Vectors','Values in range','Upper',n,a,lda,vl,vu,il,iu,     &
        abstol,m,w,z,ldz,work,lwork,rwork,iwork,jfail,info)

      If (info>=0) Then

!       Print solution

        Write (nout,99999) 'Number of eigenvalues found =', m
        Write (nout,*)
        Write (nout,*) 'Eigenvalues'
        Write (nout,99998) w(1:m)
        Flush (nout)

!       Normalize the eigenvectors so that the element of largest absolute
!       value is real.
        Do i = 1, m
          rwork(1:n) = abs(z(1:n,i))
          k = maxloc(rwork(1:n),1)
          Call zscal(n,conjg(z(k,i))/cmplx(abs(z(k,i)),kind=nag_wp),z(1,i),1)
        End Do

!       ifail: behaviour on error exit
!              =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
        ifail = 0
        Call x04daf('General',' ',n,m,z,ldz,'Selected eigenvectors',ifail)

        If (info>0) Then
          Write (nout,99999) 'INFO eigenvectors failed to converge, INFO =',   &
            info
          Write (nout,*) 'Indices of eigenvectors that did not converge'
          Write (nout,99997) jfail(1:m)
        End If
      Else
        Write (nout,99999) 'Failure in ZHEEVX. INFO =', info
      End If

99999 Format (1X,A,I5)
99998 Format (3X,(8F8.4))
99997 Format (3X,(8I8))
    End Program f08fpfe


f08fqfe.f90

    Program f08fqfe

!     F08FQF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: nag_wp, x04daf, zheevd, zscal
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Integer                          :: i, ifail, info, k, lda, liwork,      &
                                          lrwork, lwork, n
      Character (1)                    :: job, uplo
!     .. Local Arrays ..
      Complex (Kind=nag_wp), Allocatable :: a(:,:), work(:)
      Real (Kind=nag_wp), Allocatable  :: rwork(:), w(:)
      Integer, Allocatable             :: iwork(:)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: abs, cmplx, conjg, maxloc
!     .. Executable Statements ..
      Write (nout,*) 'F08FQF Example Program Results'
!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) n
      lda = n
      liwork = 5*n + 3
      lrwork = 2*n*n + 5*n + 1
      lwork = n*(n+2)
      Allocate (a(lda,n),work(lwork),rwork(lrwork),w(n),iwork(liwork))
      Read (nin,*) uplo

!     Read A from data file

      If (uplo=='U') Then
        Read (nin,*)(a(i,i:n),i=1,n)
      Else If (uplo=='L') Then
        Read (nin,*)(a(i,1:i),i=1,n)
      End If

      Read (nin,*) job

!     Calculate all the eigenvalues and eigenvectors of A
!     The NAG name equivalent of zheevd is f08fqf
      Call zheevd(job,uplo,n,a,lda,w,work,lwork,rwork,lrwork,iwork,liwork,     &
        info)

      Write (nout,*)
      If (info>0) Then
        Write (nout,*) 'Failure to converge.'
      Else

!       Print eigenvalues and eigenvectors

        Write (nout,*) 'Eigenvalues'
        Do i = 1, n
          Write (nout,99999) i, w(i)
        End Do
        Write (nout,*)
        Flush (nout)

!       Normalize the eigenvectors so that the element of largest absolute
!       value is real.
        Do i = 1, n
          rwork(1:n) = abs(a(1:n,i))
          k = maxloc(rwork(1:n),1)
          Call zscal(n,conjg(a(k,i))/cmplx(abs(a(k,i)),kind=nag_wp),a(1,i),1)
        End Do

!       ifail: behaviour on error exit
!              =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
        ifail = 0
        Call x04daf('General',' ',n,n,a,lda,'Eigenvectors',ifail)

      End If

99999 Format (3X,I5,5X,2F8.4)
    End Program f08fqfe


f08frfe.f90

    Program f08frfe

!     F08FRF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: nag_wp, x04daf, zheevr, zscal
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Real (Kind=nag_wp), Parameter    :: zero = 0.0E+0_nag_wp
      Integer, Parameter               :: nb = 64, nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: abstol, vl, vu
      Integer                          :: i, ifail, il, info, iu, k, lda, ldz, &
                                          liwork, lrwork, lwork, m, n
!     .. Local Arrays ..
      Complex (Kind=nag_wp), Allocatable :: a(:,:), work(:), z(:,:)
      Complex (Kind=nag_wp)            :: dummy(1)
      Real (Kind=nag_wp)               :: rdum(1)
      Real (Kind=nag_wp), Allocatable  :: rwork(:), w(:)
      Integer                          :: idum(1)
      Integer, Allocatable             :: isuppz(:), iwork(:)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: abs, cmplx, conjg, max, maxloc,      &
                                          nint, real
!     .. Executable Statements ..
      Write (nout,*) 'F08FRF Example Program Results'
      Write (nout,*)
!     Skip heading in data file and read N and the lower and upper
!     indices of the smallest and largest eigenvalues to be found
      Read (nin,*)
      Read (nin,*) n, il, iu
      lda = n
      ldz = n
      m = n
      Allocate (a(lda,n),z(ldz,m),w(n),isuppz(2*m))

!     Use routine workspace query to get optimal workspace.
      lwork = -1
      liwork = -1
      lrwork = -1
!     The NAG name equivalent of zheevr is f08frf
      Call zheevr('Vectors','I','Upper',n,a,lda,vl,vu,il,iu,abstol,m,w,z,ldz,  &
        isuppz,dummy,lwork,rdum,lrwork,idum,liwork,info)

!     Make sure that there is enough workspace for block size nb.
      lwork = max((nb+1)*n,nint(real(dummy(1))))
      lrwork = max(24*n,nint(rdum(1)))
      liwork = max(10*n,idum(1))
      Allocate (work(lwork),rwork(lrwork),iwork(liwork))

!     Read the upper triangular part of the matrix A from data file

      Read (nin,*)(a(i,i:n),i=1,n)

!     Set the absolute error tolerance for eigenvalues.  With ABSTOL
!     set to zero, the default value is used instead

      abstol = zero

!     Solve the symmetric eigenvalue problem

!     The NAG name equivalent of zheevr is f08frf
      Call zheevr('Vectors','I','Upper',n,a,lda,vl,vu,il,iu,abstol,m,w,z,ldz,  &
        isuppz,work,lwork,rwork,lrwork,iwork,liwork,info)

      If (info==0) Then

!       Print solution

        Write (nout,*) 'Selected eigenvalues'
        Write (nout,99999) w(1:m)
        Flush (nout)

!       Normalize the eigenvectors so that the element of largest absolute
!       value is real.
        Do i = 1, m
          rwork(1:n) = abs(z(1:n,i))
          k = maxloc(rwork(1:n),1)
          Call zscal(n,conjg(z(k,i))/cmplx(abs(z(k,i)),kind=nag_wp),z(1,i),1)
        End Do

!       ifail: behaviour on error exit
!              =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
        ifail = 0
        Call x04daf('General',' ',n,m,z,ldz,'Selected eigenvectors',ifail)
      Else
        Write (nout,99998) 'Failure in ZHEEVR. INFO =', info
      End If

99999 Format (3X,(8F8.4))
99998 Format (1X,A,I5)
    End Program f08frfe


f08fsfe.f90

    Program f08fsfe

!     F08FSF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: nag_wp, zhetrd
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Integer                          :: i, info, lda, lwork, n
      Character (1)                    :: uplo
!     .. Local Arrays ..
      Complex (Kind=nag_wp), Allocatable :: a(:,:), tau(:), work(:)
      Real (Kind=nag_wp), Allocatable  :: d(:), e(:)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: abs
!     .. Executable Statements ..
      Write (nout,*) 'F08FSF Example Program Results'
!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) n
      lda = n
      lwork = 64*n
      Allocate (a(lda,n),tau(n-1),work(lwork),d(n),e(n-1))

!     Read A from data file and copy A into C

      Read (nin,*) uplo
      If (uplo=='U') Then
        Read (nin,*)(a(i,i:n),i=1,n)
      Else If (uplo=='L') Then
        Read (nin,*)(a(i,1:i),i=1,n)
      End If

!     Reduce A to tridiagonal form
!     The NAG name equivalent of zhetrd is f08fsf
      Call zhetrd(uplo,n,a,lda,d,e,tau,work,lwork,info)

      If (info==0) Then
!       Print the diagonal and off-diagonal of tridiagonal T.
!       The absolute value of E is printed since this can vary by a change of
!       sign (corresponding to multiplying through a column of Q by -1).

        Write (nout,*)
        Write (nout,*)                                                         &
          'Diagonal and off-diagonal elements of tridiagonal form'
        Write (nout,*)
        Write (nout,99999) 'i', 'D', 'E'
        Do i = 1, n - 1
          Write (nout,99998) i, d(i), abs(e(i))
        End Do
        Write (nout,99998) n, d(n)

      Else
        Write (nout,99997) info
      End If

99999 Format (5X,A,9X,A,12X,A)
99998 Format (1X,I5,2(1X,F12.5))
99997 Format (1X,'** ZHETRD/F08FSF retuned with INFO = ',I10)

    End Program f08fsfe


f08ftfe.f90

    Program f08ftfe

!     F08FTF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: f06tff, nag_wp, x04dbf, zhetrd, zscal, zsteqr,    &
                             zungtr
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Integer                          :: i, ifail, info, k, lda, ldz, lwork,  &
                                          n
      Character (1)                    :: uplo
!     .. Local Arrays ..
      Complex (Kind=nag_wp), Allocatable :: a(:,:), tau(:), work(:), z(:,:)
      Real (Kind=nag_wp), Allocatable  :: d(:), e(:), rwork(:)
      Character (1)                    :: clabs(1), rlabs(1)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: abs, cmplx, conjg, maxloc
!     .. Executable Statements ..
      Write (nout,*) 'F08FTF Example Program Results'
!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) n
      lda = n
      ldz = n
      lwork = 64*n
      Allocate (a(lda,n),tau(n),work(lwork),z(ldz,n),d(n),e(n),rwork(2*n-2))

!     Read A from data file

      Read (nin,*) uplo
      If (uplo=='U') Then
        Read (nin,*)(a(i,i:n),i=1,n)
      Else If (uplo=='L') Then
        Read (nin,*)(a(i,1:i),i=1,n)
      End If

!     Reduce A to tridiagonal form T = (Q**H)*A*Q

!     The NAG name equivalent of zhetrd is f08fsf
      Call zhetrd(uplo,n,a,lda,d,e,tau,work,lwork,info)

!     Copy A into Z
      Call f06tff(uplo,n,n,a,lda,z,ldz)

!     Form Q explicitly, storing the result in Z
!     The NAG name equivalent of zungtr is f08ftf
      Call zungtr(uplo,n,z,ldz,tau,work,lwork,info)

!     Calculate all the eigenvalues and eigenvectors of A
!     The NAG name equivalent of zsteqr is f08jsf
      Call zsteqr('V',n,d,e,z,ldz,rwork,info)

      Write (nout,*)
      If (info>0) Then
        Write (nout,*) 'Failure to converge.'
      Else

!       Print eigenvalues and eigenvectors

        Write (nout,*) 'Eigenvalues'
        Write (nout,99999) d(1:n)
        Write (nout,*)
        Flush (nout)

!       Normalize the eigenvectors so that the element of largest absolute
!       value is real.
        Do i = 1, n
          rwork(1:n) = abs(z(1:n,i))
          k = maxloc(rwork(1:n),1)
          Call zscal(n,conjg(z(k,i))/cmplx(abs(z(k,i)),kind=nag_wp),z(1,i),1)
        End Do

!       ifail: behaviour on error exit
!              =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
        ifail = 0
        Call x04dbf('General',' ',n,n,z,ldz,'Bracketed','F7.4','Eigenvectors', &
          'Integer',rlabs,'Integer',clabs,80,0,ifail)

      End If

99999 Format (8X,4(F7.4,11X,:))
    End Program f08ftfe


f08fufe.f90

    Program f08fufe

!     F08FUF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: dstebz, nag_wp, x04dbf, zhetrd, zscal, zstein,    &
                             zunmtr
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Real (Kind=nag_wp), Parameter    :: zero = 0.0E0_nag_wp
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: vl, vu
      Integer                          :: i, ifail, info, k, lda, ldc, lwork,  &
                                          m, n, nsplit
      Character (1)                    :: uplo
!     .. Local Arrays ..
      Complex (Kind=nag_wp), Allocatable :: a(:,:), c(:,:), tau(:), work(:)
      Real (Kind=nag_wp), Allocatable  :: d(:), e(:), rwork(:), w(:)
      Integer, Allocatable             :: iblock(:), ifailv(:), isplit(:),     &
                                          iwork(:)
      Character (1)                    :: clabs(1), rlabs(1)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: abs, cmplx, conjg, maxloc
!     .. Executable Statements ..
      Write (nout,*) 'F08FUF Example Program Results'
!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) n
      lda = n
      ldc = n
      lwork = 64*n
      Allocate (a(lda,n),c(ldc,n),tau(n),work(lwork),d(n),e(n),rwork(5*n),     &
        w(n),iblock(n),ifailv(n),isplit(n),iwork(3*n))

!     Read A from data file

      Read (nin,*) uplo
      If (uplo=='U') Then
        Read (nin,*)(a(i,i:n),i=1,n)
      Else If (uplo=='L') Then
        Read (nin,*)(a(i,1:i),i=1,n)
      End If

!     Reduce A to tridiagonal form T = (Q**H)*A*Q
!     The NAG name equivalent of zhetrd is f08fsf
      Call zhetrd(uplo,n,a,lda,d,e,tau,work,lwork,info)

!     Calculate the two smallest eigenvalues of T (same as A)

!     The NAG name equivalent of dstebz is f08jjf
      Call dstebz('I','B',n,vl,vu,1,2,zero,d,e,m,nsplit,w,iblock,isplit,rwork, &
        iwork,info)

      Write (nout,*)
      If (info>0) Then
        Write (nout,*) 'Failure to converge.'
      Else
        Write (nout,*) 'Eigenvalues'
        Write (nout,99999) w(1:m)

!       Calculate the eigenvectors of T, storing the result in C
!       The NAG name equivalent of zstein is f08jxf
        Call zstein(n,d,e,m,w,iblock,isplit,c,ldc,rwork,iwork,ifailv,info)

        If (info>0) Then
          Write (nout,*) 'Failure to converge.'
        Else

!         Calculate the eigenvectors of A = Q * (eigenvectors of T)
!         The NAG name equivalent of zunmtr is f08fuf
          Call zunmtr('Left',uplo,'No transpose',n,m,a,lda,tau,c,ldc,work,     &
            lwork,info)

!         Print eigenvectors
          Write (nout,*)
          Flush (nout)

!         Normalize the eigenvectors so that the element of largest absolute
!         value is real.
          Do i = 1, m
            rwork(1:n) = abs(c(1:n,i))
            k = maxloc(rwork(1:n),1)
            Call zscal(n,conjg(c(k,i))/cmplx(abs(c(k,i)),kind=nag_wp),c(1,i),1 &
              )
          End Do

!         ifail: behaviour on error exit
!                =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
          ifail = 0
          Call x04dbf('General',' ',n,m,c,ldc,'Bracketed','F7.4',              &
            'Eigenvectors','Integer',rlabs,'Integer',clabs,80,0,ifail)

        End If
      End If

99999 Format (8X,4(F7.4,11X,:))
    End Program f08fufe


f08gafe.f90

    Program f08gafe

!     F08GAF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: dspev, nag_wp, x02ajf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
      Character (1), Parameter         :: uplo = 'U'
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: eerrbd, eps
      Integer                          :: i, info, j, n
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: ap(:), w(:), work(:)
      Real (Kind=nag_wp)               :: dummy(1,1)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: abs, max
!     .. Executable Statements ..
      Write (nout,*) 'F08GAF Example Program Results'
      Write (nout,*)
!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) n

      Allocate (ap((n*(n+1))/2),w(n),work(3*n))

!     Read the upper or lower triangular part of the matrix A from
!     data file

      If (uplo=='U') Then
        Read (nin,*)((ap(i+(j*(j-1))/2),j=i,n),i=1,n)
      Else If (uplo=='L') Then
        Read (nin,*)((ap(i+((2*n-j)*(j-1))/2),j=1,i),i=1,n)
      End If

!     Solve the symmetric eigenvalue problem
!     The NAG name equivalent of dspev is f08gaf
      Call dspev('No vectors',uplo,n,ap,w,dummy,1,work,info)

      If (info==0) Then

!       Print solution

        Write (nout,*) 'Eigenvalues'
        Write (nout,99999) w(1:n)

!       Get the machine precision, EPS and compute the approximate
!       error bound for the computed eigenvalues.  Note that for
!       the 2-norm, max( abs(W(i)) ) = norm(A), and since the
!       eigenvalues are returned in ascending order
!       max( abs(W(i)) ) = max( abs(W(1)), abs(W(n)))

        eps = x02ajf()
        eerrbd = eps*max(abs(w(1)),abs(w(n)))

!       Print the approximate error bound for the eigenvalues

        Write (nout,*)
        Write (nout,*) 'Error estimate for the eigenvalues'
        Write (nout,99998) eerrbd
      Else
        Write (nout,99997) 'Failure in DSPEV. INFO =', info
      End If

99999 Format (3X,(8F8.4))
99998 Format (4X,1P,6E11.1)
99997 Format (1X,A,I4)
    End Program f08gafe


f08gbfe.f90

    Program f08gbfe

!     F08GBF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: blas_damax_val, dspevx, nag_wp, x04caf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Real (Kind=nag_wp), Parameter    :: zero = 0.0E+0_nag_wp
      Integer, Parameter               :: nin = 5, nout = 6
      Character (1), Parameter         :: uplo = 'U'
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: abstol, r, vl, vu
      Integer                          :: i, ifail, il, info, iu, j, k, ldz,   &
                                          m, n
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: ap(:), w(:), work(:), z(:,:)
      Integer, Allocatable             :: iwork(:), jfail(:)
!     .. Executable Statements ..
      Write (nout,*) 'F08GBF Example Program Results'
      Write (nout,*)
!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) n
      ldz = n
      m = n
      Allocate (ap((n*(n+1))/2),w(n),work(8*n),z(ldz,m),iwork(5*n),jfail(n))

!     Read the lower and upper bounds of the interval to be searched,
!     and read the upper or lower triangular part of the matrix A
!     from data file

      Read (nin,*) vl, vu
      If (uplo=='U') Then
        Read (nin,*)((ap(i+(j*(j-1))/2),j=i,n),i=1,n)
      Else If (uplo=='L') Then
        Read (nin,*)((ap(i+((2*n-j)*(j-1))/2),j=1,i),i=1,n)
      End If

!     Set the absolute error tolerance for eigenvalues.  With ABSTOL
!     set to zero, the default value is used instead

      abstol = zero

!     Solve the symmetric eigenvalue problem
!     The NAG name equivalent of dspevx is f08gbf
      Call dspevx('Vectors','Values in range',uplo,n,ap,vl,vu,il,iu,abstol,m,  &
        w,z,ldz,work,iwork,jfail,info)

      If (info>=0) Then

!       Print solution

        Write (nout,99999) 'Number of eigenvalues found =', m
        Write (nout,*)
        Write (nout,*) 'Eigenvalues'
        Write (nout,99998) w(1:m)
        Flush (nout)

!       Normalize the eigenvectors: largest element positive
        Do i = 1, m
          Call blas_damax_val(n,z(1,i),1,k,r)
          If (z(k,i)<zero) Then
            z(1:n,i) = -z(1:n,i)
          End If
        End Do

!       ifail: behaviour on error exit
!              =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
        ifail = 0
        Call x04caf('General',' ',n,m,z,ldz,'Selected eigenvectors',ifail)

        If (info>0) Then
          Write (nout,99999) 'INFO eigenvectors failed to converge, INFO =',   &
            info
          Write (nout,*) 'Indices of eigenvectors that did not converge'
          Write (nout,99997) jfail(1:m)
        End If
      Else
        Write (nout,99999) 'Failure in DSPEVX. INFO =', info
      End If

99999 Format (1X,A,I5)
99998 Format (3X,(8F8.4))
99997 Format (3X,(8I8))
    End Program f08gbfe


f08gcfe.f90

    Program f08gcfe

!     F08GCF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: blas_damax_val, dspevd, nag_wp, x04caf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Real (Kind=nag_wp), Parameter    :: zero = 0.0E0_nag_wp
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: r
      Integer                          :: i, ifail, info, j, k, ldz, liwork,   &
                                          lwork, n
      Character (1)                    :: job, uplo
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: ap(:), w(:), work(:), z(:,:)
      Integer, Allocatable             :: iwork(:)
!     .. Executable Statements ..
      Write (nout,*) 'F08GCF Example Program Results'
!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) n
      ldz = n
      liwork = 5*n + 3
      lwork = n*n + 6*n + 1
      Allocate (ap(n*(n+1)/2),w(n),work(lwork),z(ldz,n),iwork(liwork))

!     Read A from data file

      Read (nin,*) uplo
      If (uplo=='U') Then
        Read (nin,*)((ap(i+j*(j-1)/2),j=i,n),i=1,n)
      Else If (uplo=='L') Then
        Read (nin,*)((ap(i+(2*n-j)*(j-1)/2),j=1,i),i=1,n)
      End If

      Read (nin,*) job

!     Calculate all the eigenvalues and eigenvectors of A
!     The NAG name equivalent of dspevd is f08gcf
      Call dspevd(job,uplo,n,ap,w,z,ldz,work,lwork,iwork,liwork,info)

      Write (nout,*)
      If (info>0) Then
        Write (nout,*) 'Failure to converge.'
      Else

!       Print eigenvalues and eigenvectors

        Write (nout,*) 'Eigenvalues'
        Write (nout,99999) w(1:n)
        Write (nout,*)
        Flush (nout)

!       Normalize the eigenvectors: largest element positive
        Do i = 1, n
          Call blas_damax_val(n,z(1,i),1,k,r)
          If (z(k,i)<zero) Then
            z(1:n,i) = -z(1:n,i)
          End If
        End Do

!       ifail: behaviour on error exit
!              =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
        ifail = 0
        Call x04caf('General',' ',n,n,z,ldz,'Eigenvectors',ifail)

      End If

99999 Format (3X,(8F8.4))
    End Program f08gcfe


f08gefe.f90

    Program f08gefe

!     F08GEF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: dsptrd, nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Integer                          :: i, info, j, n
      Character (1)                    :: uplo
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: ap(:), d(:), e(:), tau(:)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: abs
!     .. Executable Statements ..
      Write (nout,*) 'F08GEF Example Program Results'
!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) n

      Allocate (ap(n*(n+1)/2),d(n),e(n-1),tau(n-1))

!     Read A from data file and copy A into AW

      Read (nin,*) uplo
      If (uplo=='U') Then
        Read (nin,*)((ap(i+j*(j-1)/2),j=i,n),i=1,n)
      Else If (uplo=='L') Then
        Read (nin,*)((ap(i+(2*n-j)*(j-1)/2),j=1,i),i=1,n)
      End If

!     Reduce A to tridiagonal form
!     The NAG name equivalent of dsptrd is f08gef
      Call dsptrd(uplo,n,ap,d,e,tau,info)

      If (info==0) Then
!       Print the diagonal and off-diagonal of tridiagonal T.
!       The absolute value of E is printed since this can vary by a change of
!       sign (corresponding to multiplying through a column of Q by -1).

        Write (nout,*)
        Write (nout,*)                                                         &
          'Diagonal and off-diagonal elements of tridiagonal form'
        Write (nout,*)
        Write (nout,99999) 'i', 'D', 'E'
        Do i = 1, n - 1
          Write (nout,99998) i, d(i), abs(e(i))
        End Do
        Write (nout,99998) n, d(n)

      Else
        Write (nout,99997) info
      End If

99999 Format (5X,A,9X,A,12X,A)
99998 Format (1X,I5,2(1X,F12.5))
99997 Format (1X,'** DSPTRD/F08GEF retuned with INFO = ',I10)

    End Program f08gefe


f08gffe.f90

    Program f08gffe

!     F08GFF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: blas_damax_val, dopgtr, dsptrd, dsteqr, nag_wp,   &
                             x04caf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Real (Kind=nag_wp), Parameter    :: zero = 0.0E0_nag_wp
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: r
      Integer                          :: i, ifail, info, j, k, ldq, n
      Character (1)                    :: uplo
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: ap(:), d(:), e(:), q(:,:), tau(:),   &
                                          work(:)
!     .. Executable Statements ..
      Write (nout,*) 'F08GFF Example Program Results'
!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) n
      ldq = n
      Allocate (ap(n*(n+1)/2),d(n),e(n),q(ldq,n),tau(n),work(2*n-2))

!     Read A from data file

      Read (nin,*) uplo
      If (uplo=='U') Then
        Read (nin,*)((ap(i+j*(j-1)/2),j=i,n),i=1,n)
      Else If (uplo=='L') Then
        Read (nin,*)((ap(i+(2*n-j)*(j-1)/2),j=1,i),i=1,n)
      End If

!     Reduce A to tridiagonal form T = (Q**T)*A*Q
!     The NAG name equivalent of dsptrd is f08gef
      Call dsptrd(uplo,n,ap,d,e,tau,info)

!     Form Q explicitly, storing the result in Q
!     The NAG name equivalent of dopgtr is f08gff
      Call dopgtr(uplo,n,ap,tau,q,ldq,work,info)

!     Calculate all the eigenvalues and eigenvectors of A
!     The NAG name equivalent of dsteqr is f08jef
      Call dsteqr('V',n,d,e,q,ldq,work,info)

      Write (nout,*)
      If (info>0) Then
        Write (nout,*) 'Failure to converge.'
      Else

!       Print eigenvalues and eigenvectors

        Write (nout,*) 'Eigenvalues'
        Write (nout,99999) d(1:n)
        Write (nout,*)
        Flush (nout)

!       Normalize the eigenvectors: largest element positive
        Do i = 1, n
          Call blas_damax_val(n,q(1,i),1,k,r)
          If (q(k,i)<zero) Then
            q(1:n,i) = -q(1:n,i)
          End If
        End Do

!       ifail: behaviour on error exit
!              =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
        ifail = 0
        Call x04caf('General',' ',n,n,q,ldq,'Eigenvectors',ifail)

      End If

99999 Format (3X,(8F8.4))
    End Program f08gffe


f08ggfe.f90

    Program f08ggfe

!     F08GGF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: blas_damax_val, dopmtr, dsptrd, dstebz, dstein,   &
                             nag_wp, x04caf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Real (Kind=nag_wp), Parameter    :: zero = 0.0E0_nag_wp
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: r, vl, vu
      Integer                          :: i, ifail, info, j, k, ldc, m, n,     &
                                          nsplit
      Character (1)                    :: uplo
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: ap(:), c(:,:), d(:), e(:), tau(:),   &
                                          w(:), work(:)
      Integer, Allocatable             :: iblock(:), ifailv(:), isplit(:),     &
                                          iwork(:)
!     .. Executable Statements ..
      Write (nout,*) 'F08GGF Example Program Results'
!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) n
      ldc = n
      Allocate (ap(n*(n+1)/2),c(ldc,n),d(n),e(n),tau(n),w(n),work(5*n),iblock( &
        n),ifailv(n),isplit(n),iwork(3*n))

!     Read A from data file

      Read (nin,*) uplo
      If (uplo=='U') Then
        Read (nin,*)((ap(i+j*(j-1)/2),j=i,n),i=1,n)
      Else If (uplo=='L') Then
        Read (nin,*)((ap(i+(2*n-j)*(j-1)/2),j=1,i),i=1,n)
      End If

!     Reduce A to tridiagonal form T = (Q**T)*A*Q
!     The NAG name equivalent of dsptrd is f08gef
      Call dsptrd(uplo,n,ap,d,e,tau,info)

!     Calculate the two smallest eigenvalues of T (same as A)
!     The NAG name equivalent of dstebz is f08jjf
      Call dstebz('I','B',n,vl,vu,1,2,zero,d,e,m,nsplit,w,iblock,isplit,work,  &
        iwork,info)

      Write (nout,*)
      If (info>0) Then
        Write (nout,*) 'Failure to converge.'
      Else
        Write (nout,*) 'Eigenvalues'
        Write (nout,99999) w(1:m)

!       Calculate the eigenvectors of T, storing the result in C
!       The NAG name equivalent of dstein is f08jkf
        Call dstein(n,d,e,m,w,iblock,isplit,c,ldc,work,iwork,ifailv,info)

        If (info>0) Then
          Write (nout,*) 'Failure to converge.'
        Else

!         Calculate the eigenvectors of A = Q * (eigenvectors of T)
!         The NAG name equivalent of dopmtr is f08ggf
          Call dopmtr('Left',uplo,'No transpose',n,m,ap,tau,c,ldc,work,info)

!         Print eigenvectors
          Write (nout,*)
          Flush (nout)

!         Normalize the eigenvectors
          Do i = 1, m
            Call blas_damax_val(n,c(1,i),1,k,r)
            If (c(k,i)<zero) Then
              c(1:n,i) = -c(1:n,i)
            End If
          End Do

!         ifail: behaviour on error exit
!                =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
          ifail = 0
          Call x04caf('General',' ',n,m,c,ldc,'Eigenvectors',ifail)

        End If
      End If

99999 Format (3X,(9F8.4))
    End Program f08ggfe


f08gnfe.f90

    Program f08gnfe

!     F08GNF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: nag_wp, x02ajf, zhpev
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
      Character (1), Parameter         :: uplo = 'U'
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: eerrbd, eps
      Integer                          :: i, info, j, n
!     .. Local Arrays ..
      Complex (Kind=nag_wp), Allocatable :: ap(:), work(:)
      Complex (Kind=nag_wp)            :: dummy(1,1)
      Real (Kind=nag_wp), Allocatable  :: rwork(:), w(:)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: abs, max
!     .. Executable Statements ..
      Write (nout,*) 'F08GNF Example Program Results'
      Write (nout,*)
!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) n

      Allocate (ap((n*(n+1))/2),work(2*n-1),rwork(3*n-2),w(n))

!     Read the upper or lower triangular part of the matrix A from
!     data file

      If (uplo=='U') Then
        Read (nin,*)((ap(i+(j*(j-1))/2),j=i,n),i=1,n)
      Else If (uplo=='L') Then
        Read (nin,*)((ap(i+((2*n-j)*(j-1))/2),j=1,i),i=1,n)
      End If

!     Solve the Hermitian eigenvalue problem

!     The NAG name equivalent of zhpev is f08gnf
      Call zhpev('No vectors',uplo,n,ap,w,dummy,1,work,rwork,info)

      If (info==0) Then

!       Print solution

        Write (nout,*) 'Eigenvalues'
        Write (nout,99999) w(1:n)

!       Get the machine precision, EPS and compute the approximate
!       error bound for the computed eigenvalues.  Note that for
!       the 2-norm, max( abs(W(i)) ) = norm(A), and since the
!       eigenvalues are returned in ascending order
!       max( abs(W(i)) ) = max( abs(W(1)), abs(W(n)))

        eps = x02ajf()
        eerrbd = eps*max(abs(w(1)),abs(w(n)))

!       Print the approximate error bound for the eigenvalues

        Write (nout,*)
        Write (nout,*) 'Error estimate for the eigenvalues'
        Write (nout,99998) eerrbd
      Else
        Write (nout,99997) 'Failure in ZHPEV. INFO =', info
      End If

99999 Format (3X,(8F8.4))
99998 Format (4X,1P,6E11.1)
99997 Format (1X,A,I4)
    End Program f08gnfe


f08gpfe.f90

    Program f08gpfe

!     F08GPF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: dznrm2, nag_wp, x04daf, zhpevx
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Real (Kind=nag_wp), Parameter    :: zero = 0.0E+0_nag_wp
      Integer, Parameter               :: nin = 5, nout = 6
      Character (1), Parameter         :: uplo = 'U'
!     .. Local Scalars ..
      Complex (Kind=nag_wp)            :: scal
      Real (Kind=nag_wp)               :: abstol, vl, vu
      Integer                          :: i, ifail, il, info, iu, j, k, ldz,   &
                                          m, n
!     .. Local Arrays ..
      Complex (Kind=nag_wp), Allocatable :: ap(:), work(:), z(:,:)
      Real (Kind=nag_wp), Allocatable  :: rwork(:), w(:)
      Integer, Allocatable             :: iwork(:), jfail(:)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: abs, conjg, maxloc
!     .. Executable Statements ..
      Write (nout,*) 'F08GPF Example Program Results'
      Write (nout,*)
!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) n
      ldz = n
      m = n
      Allocate (ap((n*(n+1))/2),work(2*n),z(ldz,m),rwork(7*n),w(n),iwork(5*n), &
        jfail(n))

!     Read the lower and upper bounds of the interval to be searched,
!     and read the upper or lower triangular part of the matrix A
!     from data file

      Read (nin,*) vl, vu
      If (uplo=='U') Then
        Read (nin,*)((ap(i+(j*(j-1))/2),j=i,n),i=1,n)
      Else If (uplo=='L') Then
        Read (nin,*)((ap(i+((2*n-j)*(j-1))/2),j=1,i),i=1,n)
      End If

!     Set the absolute error tolerance for eigenvalues.  With ABSTOL
!     set to zero, the default value is used instead

      abstol = zero

!     Solve the Hermitian eigenvalue problem

!     The NAG name equivalent of zhpevx is f08gpf
      Call zhpevx('Vectors','Values in range',uplo,n,ap,vl,vu,il,iu,abstol,m,  &
        w,z,ldz,work,rwork,iwork,jfail,info)

      If (info>=0) Then

!       Print solution

        Write (nout,99999) 'Number of eigenvalues found =', m
        Write (nout,*)
        Write (nout,*) 'Eigenvalues'
        Write (nout,99998) w(1:m)
        Flush (nout)

!       Normalize the eigenvectors, largest element real
        Do i = 1, m
          rwork(1:n) = abs(z(1:n,i))
          k = maxloc(rwork(1:n),1)
          scal = conjg(z(k,i))/abs(z(k,i))/dznrm2(n,z(1,i),1)
          z(1:n,i) = z(1:n,i)*scal
        End Do

!       ifail: behaviour on error exit
!              =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
        ifail = 0
        Call x04daf('General',' ',n,m,z,ldz,'Selected eigenvectors',ifail)

        If (info>0) Then
          Write (nout,99999) 'INFO eigenvectors failed to converge, INFO =',   &
            info
          Write (nout,*) 'Indices of eigenvectors that did not converge'
          Write (nout,99997) jfail(1:m)
        End If
      Else
        Write (nout,99999) 'Failure in ZHPEVX. INFO =', info
      End If

99999 Format (1X,A,I5)
99998 Format (3X,(8F8.4))
99997 Format (3X,(8I8))
    End Program f08gpfe


f08gqfe.f90

    Program f08gqfe

!     F08GQF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: dznrm2, nag_wp, x04daf, zhpevd
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Complex (Kind=nag_wp)            :: scal
      Integer                          :: i, ifail, info, j, k, ldz, liwork,   &
                                          lrwork, lwork, n
      Character (1)                    :: job, uplo
!     .. Local Arrays ..
      Complex (Kind=nag_wp), Allocatable :: ap(:), work(:), z(:,:)
      Real (Kind=nag_wp), Allocatable  :: rwork(:), w(:)
      Integer, Allocatable             :: iwork(:)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: abs, conjg, maxloc
!     .. Executable Statements ..
      Write (nout,*) 'F08GQF Example Program Results'
!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) n
      ldz = n
      liwork = 5*n + 3
      lrwork = 2*n*n + 5*n + 1
      lwork = 2*n
      Allocate (ap(n*(n+1)/2),work(lwork),z(ldz,n),rwork(lrwork),w(n),iwork(   &
        liwork))
      Read (nin,*) uplo

!     Read A from data file

      If (uplo=='U') Then
        Read (nin,*)((ap(i+j*(j-1)/2),j=i,n),i=1,n)
      Else If (uplo=='L') Then
        Read (nin,*)((ap(i+(2*n-j)*(j-1)/2),j=1,i),i=1,n)
      End If

      Read (nin,*) job

!     Calculate all the eigenvalues and eigenvectors of A

!     The NAG name equivalent of zhpevd is f08gqf
      Call zhpevd(job,uplo,n,ap,w,z,ldz,work,lwork,rwork,lrwork,iwork,liwork,  &
        info)

      Write (nout,*)
      If (info>0) Then
        Write (nout,*) 'Failure to converge.'
      Else

!       Print eigenvalues and eigenvectors

        Write (nout,*) 'Eigenvalues'
        Do i = 1, n
          Write (nout,99999) i, w(i)
        End Do
        Write (nout,*)
        Flush (nout)

!       Normalize the eigenvectors, largest element real
        Do i = 1, n
          rwork(1:n) = abs(z(1:n,i))
          k = maxloc(rwork(1:n),1)
          scal = conjg(z(k,i))/abs(z(k,i))/dznrm2(n,z(1,i),1)
          z(1:n,i) = z(1:n,i)*scal
        End Do

!       ifail: behaviour on error exit
!              =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
        ifail = 0
        Call x04daf('General',' ',n,n,z,ldz,'Eigenvectors',ifail)

      End If

99999 Format (3X,I5,5X,2F8.4)
    End Program f08gqfe


f08gsfe.f90

    Program f08gsfe

!     F08GSF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: nag_wp, zhptrd
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Integer                          :: i, info, j, n
      Character (1)                    :: uplo
!     .. Local Arrays ..
      Complex (Kind=nag_wp), Allocatable :: ap(:), tau(:)
      Real (Kind=nag_wp), Allocatable  :: d(:), e(:)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: abs
!     .. Executable Statements ..
      Write (nout,*) 'F08GSF Example Program Results'
!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) n

      Allocate (ap(n*(n+1)/2),tau(n-1),d(n),e(n-1))

!     Read A from data file and copy a into AW

      Read (nin,*) uplo
      If (uplo=='U') Then
        Read (nin,*)((ap(i+j*(j-1)/2),j=i,n),i=1,n)
      Else If (uplo=='L') Then
        Read (nin,*)((ap(i+(2*n-j)*(j-1)/2),j=1,i),i=1,n)
      End If

!     Reduce A to tridiagonal form
!     The NAG name equivalent of zhptrd is f08gsf
      Call zhptrd(uplo,n,ap,d,e,tau,info)

      If (info==0) Then
!       Print the diagonal and off-diagonal of tridiagonal T.
!       The absolute value of E is printed since this can vary by a change of
!       sign (corresponding to multiplying through a column of Q by -1).

        Write (nout,*)
        Write (nout,*)                                                         &
          'Diagonal and off-diagonal elements of tridiagonal form'
        Write (nout,*)
        Write (nout,99999) 'i', 'D', 'E'
        Do i = 1, n - 1
          Write (nout,99998) i, d(i), abs(e(i))
        End Do
        Write (nout,99998) n, d(n)

      Else
        Write (nout,99997) info
      End If

99999 Format (5X,A,9X,A,12X,A)
99998 Format (1X,I5,2(1X,F12.5))
99997 Format (1X,'** ZHPTRD/F08GSF retuned with INFO = ',I10)

    End Program f08gsfe


f08gtfe.f90

    Program f08gtfe

!     F08GTF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: dznrm2, nag_wp, x04dbf, zhptrd, zsteqr, zupgtr
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Complex (Kind=nag_wp)            :: scal
      Integer                          :: i, ifail, info, j, k, ldq, n
      Character (1)                    :: uplo
!     .. Local Arrays ..
      Complex (Kind=nag_wp), Allocatable :: ap(:), q(:,:), tau(:), work(:)
      Real (Kind=nag_wp), Allocatable  :: d(:), e(:), rwork(:)
      Character (1)                    :: clabs(1), rlabs(1)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: abs, conjg, maxloc
!     .. Executable Statements ..
      Write (nout,*) 'F08GTF Example Program Results'
!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) n
      ldq = n
      Allocate (ap(n*(n+1)/2),q(ldq,n),tau(n),work(n-1),d(n),e(n),rwork(2*n-2) &
        )

!     Read A from data file

      Read (nin,*) uplo
      If (uplo=='U') Then
        Read (nin,*)((ap(i+j*(j-1)/2),j=i,n),i=1,n)
      Else If (uplo=='L') Then
        Read (nin,*)((ap(i+(2*n-j)*(j-1)/2),j=1,i),i=1,n)
      End If

!     Reduce A to tridiagonal form T = (Q**H)*A*Q
!     The NAG name equivalent of zhptrd is f08gsf
      Call zhptrd(uplo,n,ap,d,e,tau,info)

!     Form Q explicitly, storing the result in Q
!     The NAG name equivalent of zupgtr is f08gtf
      Call zupgtr(uplo,n,ap,tau,q,ldq,work,info)

!     Calculate all the eigenvalues and eigenvectors of A
!     The NAG name equivalent of zsteqr is f08jsf
      Call zsteqr('V',n,d,e,q,ldq,rwork,info)

      Write (nout,*)
      If (info>0) Then
        Write (nout,*) 'Failure to converge.'
      Else

!       Print eigenvalues and eigenvectors

        Write (nout,*) 'Eigenvalues'
        Write (nout,99999) d(1:n)
        Write (nout,*)
        Flush (nout)

!       Normalize the eigenvectors, largest element real
        Do i = 1, n
          rwork(1:n) = abs(q(1:n,i))
          k = maxloc(rwork(1:n),1)
          scal = conjg(q(k,i))/abs(q(k,i))/dznrm2(n,q(1,i),1)
          q(1:n,i) = q(1:n,i)*scal
        End Do

!       ifail: behaviour on error exit
!              =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
        ifail = 0
        Call x04dbf('General',' ',n,n,q,ldq,'Bracketed','F7.4','Eigenvectors', &
          'Integer',rlabs,'Integer',clabs,80,0,ifail)

      End If

99999 Format (8X,4(F7.4,11X,:))
    End Program f08gtfe


f08gufe.f90

    Program f08gufe

!     F08GUF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: dstebz, dznrm2, nag_wp, x04dbf, zhptrd, zstein,   &
                             zupmtr
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Real (Kind=nag_wp), Parameter    :: zero = 0.0E0_nag_wp
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Complex (Kind=nag_wp)            :: scal
      Real (Kind=nag_wp)               :: vl, vu
      Integer                          :: i, ifail, info, j, k, ldc, m, n,     &
                                          nsplit
      Character (1)                    :: uplo
!     .. Local Arrays ..
      Complex (Kind=nag_wp), Allocatable :: ap(:), c(:,:), tau(:), work(:)
      Real (Kind=nag_wp), Allocatable  :: d(:), e(:), rwork(:), w(:)
      Integer, Allocatable             :: iblock(:), ifailv(:), isplit(:),     &
                                          iwork(:)
      Character (1)                    :: clabs(1), rlabs(1)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: abs, conjg, maxloc
!     .. Executable Statements ..
      Write (nout,*) 'F08GUF Example Program Results'
!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) n
      ldc = n
      Allocate (ap(n*(n+1)/2),c(ldc,n),tau(n),work(n),d(n),e(n),rwork(5*n),w(n &
        ),iblock(n),ifailv(n),isplit(n),iwork(3*n))

!     Read A from data file

      Read (nin,*) uplo
      If (uplo=='U') Then
        Read (nin,*)((ap(i+j*(j-1)/2),j=i,n),i=1,n)
      Else If (uplo=='L') Then
        Read (nin,*)((ap(i+(2*n-j)*(j-1)/2),j=1,i),i=1,n)
      End If

!     Reduce A to tridiagonal form T = (Q**H)*A*Q
!     The NAG name equivalent of zhptrd is f08gsf
      Call zhptrd(uplo,n,ap,d,e,tau,info)

!     Calculate the two smallest eigenvalues of T (same as A)

!     The NAG name equivalent of dstebz is f08jjf
      Call dstebz('I','B',n,vl,vu,1,2,zero,d,e,m,nsplit,w,iblock,isplit,rwork, &
        iwork,info)

      Write (nout,*)
      If (info>0) Then
        Write (nout,*) 'Failure to converge.'
      Else
        Write (nout,*) 'Eigenvalues'
        Write (nout,99999) w(1:m)

!       Calculate the eigenvectors of T, storing the result in C
!       The NAG name equivalent of zstein is f08jxf
        Call zstein(n,d,e,m,w,iblock,isplit,c,ldc,rwork,iwork,ifailv,info)

        If (info>0) Then
          Write (nout,*) 'Failure to converge.'
        Else

!         Calculate the eigenvectors of A = Q * (eigenvectors of T)
!         The NAG name equivalent of zupmtr is f08guf
          Call zupmtr('Left',uplo,'No transpose',n,m,ap,tau,c,ldc,work,info)

!         Print eigenvectors

          Write (nout,*)
          Flush (nout)

!         Normalize the eigenvectors, largest element real
          Do i = 1, m
            rwork(1:n) = abs(c(1:n,i))
            k = maxloc(rwork(1:n),1)
            scal = conjg(c(k,i))/abs(c(k,i))/dznrm2(n,c(1,i),1)
            c(1:n,i) = c(1:n,i)*scal
          End Do

!         ifail: behaviour on error exit
!                =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
          ifail = 0
          Call x04dbf('General',' ',n,m,c,ldc,'Bracketed','F7.4',              &
            'Eigenvectors','Integer',rlabs,'Integer',clabs,80,0,ifail)

        End If
      End If

99999 Format (8X,4(F7.4,11X,:))
    End Program f08gufe


f08hafe.f90

    Program f08hafe

!     F08HAF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: ddisna, dsbev, nag_wp, x02ajf, x04caf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
      Character (1), Parameter         :: uplo = 'U'
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: eerrbd, eps
      Integer                          :: i, ifail, info, j, kd, ldab, ldz, n
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: ab(:,:), rcondz(:), w(:), work(:),   &
                                          z(:,:), zerrbd(:)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: abs, max, min
!     .. Executable Statements ..
      Write (nout,*) 'F08HAF Example Program Results'
      Write (nout,*)
!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) n, kd
      ldab = kd + 1
      ldz = n
      Allocate (ab(ldab,n),rcondz(n),w(n),work(3*n-2),z(ldz,n),zerrbd(n))

!     Read the upper or lower triangular part of the symmetric band
!     matrix A from data file

      If (uplo=='U') Then
        Read (nin,*)((ab(kd+1+i-j,j),j=i,min(n,i+kd)),i=1,n)
      Else If (uplo=='L') Then
        Read (nin,*)((ab(1+i-j,j),j=max(1,i-kd),i),i=1,n)
      End If

!     Solve the band symmetric eigenvalue problem

!     The NAG name equivalent of dsbev is f08haf
      Call dsbev('Vectors',uplo,n,kd,ab,ldab,w,z,ldz,work,info)

      If (info==0) Then

!       Print solution

        Write (nout,*) 'Eigenvalues'
        Write (nout,99999) w(1:n)
        Flush (nout)

!       Standardize the eigenvectors so that first elements are non-negative.
        Do i = 1, n
          If (z(1,i)<0.0_nag_wp) Then
            z(1:n,i) = -z(1:n,i)
          End If
        End Do

!       ifail: behaviour on error exit
!              =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
        ifail = 0
        Call x04caf('General',' ',n,n,z,ldz,'Eigenvectors',ifail)

!       Get the machine precision, EPS and compute the approximate
!       error bound for the computed eigenvalues.  Note that for
!       the 2-norm, max( abs(W(i)) ) = norm(A), and since the
!       eigenvalues are returned in ascending order
!       max( abs(W(i)) ) = max( abs(W(1)), abs(W(n)))

        eps = x02ajf()
        eerrbd = eps*max(abs(w(1)),abs(w(n)))

!       Call DDISNA (F08FLF) to estimate reciprocal condition
!       numbers for the eigenvectors
        Call ddisna('Eigenvectors',n,n,w,rcondz,info)

!       Compute the error estimates for the eigenvectors

        Do i = 1, n
          zerrbd(i) = eerrbd/rcondz(i)
        End Do

!       Print the approximate error bounds for the eigenvalues
!       and vectors

        Write (nout,*)
        Write (nout,*) 'Error estimate for the eigenvalues'
        Write (nout,99998) eerrbd
        Write (nout,*)
        Write (nout,*) 'Error estimates for the eigenvectors'
        Write (nout,99998) zerrbd(1:n)
      Else
        Write (nout,99997) 'Failure in DSBEV. INFO =', info
      End If

99999 Format (3X,(8F8.4))
99998 Format (4X,1P,6E11.1)
99997 Format (1X,A,I4)
    End Program f08hafe


f08hbfe.f90

    Program f08hbfe

!     F08HBF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: dsbevx, nag_wp, x04caf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Real (Kind=nag_wp), Parameter    :: zero = 0.0E+0_nag_wp
      Integer, Parameter               :: nin = 5, nout = 6
      Character (1), Parameter         :: uplo = 'U'
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: abstol, vl, vu
      Integer                          :: i, ifail, il, info, iu, j, kd, ldab, &
                                          ldq, ldz, m, n
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: ab(:,:), q(:,:), w(:), work(:),      &
                                          z(:,:)
      Integer, Allocatable             :: iwork(:), jfail(:)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: max, min
!     .. Executable Statements ..
      Write (nout,*) 'F08HBF Example Program Results'
      Write (nout,*)
!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) n, kd
      ldab = kd + 1
      ldq = n
      ldz = n
      m = n
      Allocate (ab(ldab,n),q(ldq,n),w(n),work(7*n),z(ldz,m),iwork(5*n),        &
        jfail(n))

!     Read the lower and upper bounds of the interval to be searched,
!     and read the upper or lower triangular part of the matrix A
!     from data file

      Read (nin,*) vl, vu
      If (uplo=='U') Then
        Read (nin,*)((ab(kd+1+i-j,j),j=i,min(n,i+kd)),i=1,n)
      Else If (uplo=='L') Then
        Read (nin,*)((ab(1+i-j,j),j=max(1,i-kd),i),i=1,n)
      End If

!     Set the absolute error tolerance for eigenvalues.  With ABSTOL
!     set to zero, the default value is used instead

      abstol = zero

!     Solve the band symmetric eigenvalue problem
!     The NAG name equivalent of dsbevx is f08hbf
      Call dsbevx('Vectors','Values in range',uplo,n,kd,ab,ldab,q,ldq,vl,vu,   &
        il,iu,abstol,m,w,z,ldz,work,iwork,jfail,info)

      If (info>=0) Then

!       Print solution

        Write (nout,99999) 'Number of eigenvalues found =', m
        Write (nout,*)
        Write (nout,*) 'Eigenvalues'
        Write (nout,99998) w(1:m)
        Flush (nout)

!       ifail: behaviour on error exit
!              =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
        ifail = 0
        Call x04caf('General',' ',n,m,z,ldz,'Selected eigenvectors',ifail)

        If (info>0) Then
          Write (nout,99999) 'INFO eigenvectors failed to converge, INFO =',   &
            info
          Write (nout,*) 'Indices of eigenvectors that did not converge'
          Write (nout,99997) jfail(1:m)
        End If
      Else
        Write (nout,99999) 'Failure in DSBEVX. INFO =', info
      End If

99999 Format (1X,A,I5)
99998 Format (3X,(8F8.4))
99997 Format (3X,(8I8))
    End Program f08hbfe


f08hcfe.f90

    Program f08hcfe

!     F08HCF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: dsbevd, nag_wp, x04caf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Integer                          :: i, ifail, info, j, kd, ldab, ldz,    &
                                          liwork, lwork, n
      Character (1)                    :: job, uplo
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: ab(:,:), w(:), work(:), z(:,:)
      Integer, Allocatable             :: iwork(:)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: max, min
!     .. Executable Statements ..
      Write (nout,*) 'F08HCF Example Program Results'
!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) n, kd
      ldab = kd + 1
      ldz = n
      liwork = 5*n + 3
      lwork = 2*n*n + 5*n + 1
      Allocate (ab(ldab,n),w(n),work(lwork),z(ldz,n),iwork(liwork))

!     Read A from data file

      Read (nin,*) uplo
      If (uplo=='U') Then
        Do i = 1, n
          Read (nin,*)(ab(kd+1+i-j,j),j=i,min(n,i+kd))
        End Do
      Else If (uplo=='L') Then
        Do i = 1, n
          Read (nin,*)(ab(1+i-j,j),j=max(1,i-kd),i)
        End Do
      End If

      Read (nin,*) job

!     Calculate all the eigenvalues and eigenvectors of A
!     The NAG name equivalent of dsbevd is f08hcf
      Call dsbevd(job,uplo,n,kd,ab,ldab,w,z,ldz,work,lwork,iwork,liwork,info)

      Write (nout,*)
      If (info>0) Then
        Write (nout,*) 'Failure to converge.'
      Else

!       Print eigenvalues and eigenvectors

        Write (nout,*) 'Eigenvalues'
        Write (nout,99999) w(1:n)
        Write (nout,*)
        Flush (nout)

!       Standardize the eigenvectors so that first elements are non-negative.
        Do i = 1, n
          If (z(1,i)<0.0_nag_wp) Then
            z(1:n,i) = -z(1:n,i)
          End If
        End Do

!       ifail: behaviour on error exit
!              =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
        ifail = 0
        Call x04caf('General',' ',n,n,z,ldz,'Eigenvectors',ifail)

      End If

99999 Format (3X,(8F8.4))
    End Program f08hcfe


f08hefe.f90

    Program f08hefe

!     F08HEF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: dsbtrd, dsteqr, nag_wp, x04caf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Integer                          :: i, ifail, info, j, kd, ldab, ldq, n
      Character (1)                    :: uplo
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: ab(:,:), d(:), e(:), q(:,:), work(:)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: max, min
!     .. Executable Statements ..
      Write (nout,*) 'F08HEF Example Program Results'
!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) n, kd
      ldab = kd + 1
      ldq = n
      Allocate (ab(ldab,n),d(n),e(n-1),q(ldq,n),work(2*n-2))

!     Read A from data file

      Read (nin,*) uplo
      If (uplo=='U') Then
        Do i = 1, n
          Read (nin,*)(ab(kd+1+i-j,j),j=i,min(n,i+kd))
        End Do
      Else If (uplo=='L') Then
        Do i = 1, n
          Read (nin,*)(ab(1+i-j,j),j=max(1,i-kd),i)
        End Do
      End If

!     Reduce A to tridiagonal form T = (Q**T)*A*Q (and form Q)
!     The NAG name equivalent of dsbtrd is f08hef
      Call dsbtrd('V',uplo,n,kd,ab,ldab,d,e,q,ldq,work,info)

!     Calculate all the eigenvalues and eigenvectors of A
!     The NAG name equivalent of dsteqr is f08jef
      Call dsteqr('V',n,d,e,q,ldq,work,info)

      Write (nout,*)
      If (info>0) Then
        Write (nout,*) 'Failure to converge.'
      Else

!       Print eigenvalues and eigenvectors

        Write (nout,*) 'Eigenvalues'
        Write (nout,99999) d(1:n)
        Write (nout,*)
        Flush (nout)

!       Standardize the eigenvectors so that first elements are non-negative.
        Do i = 1, n
          If (q(1,i)<0.0_nag_wp) Then
            q(1:n,i) = -q(1:n,i)
          End If
        End Do

!       ifail: behaviour on error exit
!              =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
        ifail = 0
        Call x04caf('General',' ',n,n,q,ldq,'Eigenvectors',ifail)

      End If

99999 Format (3X,(8F8.4))
    End Program f08hefe


f08hnfe.f90

    Program f08hnfe

!     F08HNF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: ddisna, dznrm2, nag_wp, x02ajf, x04daf, zhbev
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
      Character (1), Parameter         :: uplo = 'U'
!     .. Local Scalars ..
      Complex (Kind=nag_wp)            :: scal
      Real (Kind=nag_wp)               :: eerrbd, eps
      Integer                          :: i, ifail, info, j, k, kd, ldab, ldz, &
                                          n
!     .. Local Arrays ..
      Complex (Kind=nag_wp), Allocatable :: ab(:,:), work(:), z(:,:)
      Real (Kind=nag_wp), Allocatable  :: rcondz(:), rwork(:), w(:), zerrbd(:)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: abs, conjg, max, maxloc, min
!     .. Executable Statements ..
      Write (nout,*) 'F08HNF Example Program Results'
      Write (nout,*)
!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) n, kd
      ldab = kd + 1
      ldz = n
      Allocate (ab(ldab,n),work(n),z(ldz,n),rcondz(n),rwork(3*n-2),w(n),       &
        zerrbd(n))

!     Read the upper or lower triangular part of the symmetric band
!     matrix A from data file

      If (uplo=='U') Then
        Read (nin,*)((ab(kd+1+i-j,j),j=i,min(n,i+kd)),i=1,n)
      Else If (uplo=='L') Then
        Read (nin,*)((ab(1+i-j,j),j=max(1,i-kd),i),i=1,n)
      End If

!     Solve the band Hermitian eigenvalue problem
!     The NAG name equivalent of zhbev is f08hnf
      Call zhbev('Vectors',uplo,n,kd,ab,ldab,w,z,ldz,work,rwork,info)

      If (info==0) Then

!       Print solution

        Write (nout,*) 'Eigenvalues'
        Write (nout,99999) w(1:n)
        Flush (nout)

!       Normalize the eigenvectors, largest element real
        Do i = 1, n
          rwork(1:n) = abs(z(1:n,i))
          k = maxloc(rwork(1:n),1)
          scal = conjg(z(k,i))/abs(z(k,i))/dznrm2(n,z(1,i),1)
          z(1:n,i) = z(1:n,i)*scal
        End Do

!       ifail: behaviour on error exit
!              =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
        ifail = 0
        Call x04daf('General',' ',n,n,z,ldz,'Eigenvectors',ifail)

!       Get the machine precision, EPS and compute the approximate
!       error bound for the computed eigenvalues.  Note that for
!       the 2-norm, max( abs(W(i)) ) = norm(A), and since the
!       eigenvalues are returned in ascending order
!       max( abs(W(i)) ) = max( abs(W(1)), abs(W(n)))

        eps = x02ajf()
        eerrbd = eps*max(abs(w(1)),abs(w(n)))

!       Call DDISNA (F08FLF) to estimate reciprocal condition
!       numbers for the eigenvectors
        Call ddisna('Eigenvectors',n,n,w,rcondz,info)

!       Compute the error estimates for the eigenvectors

        Do i = 1, n
          zerrbd(i) = eerrbd/rcondz(i)
        End Do

!       Print the approximate error bounds for the eigenvalues
!       and vectors

        Write (nout,*)
        Write (nout,*) 'Error estimate for the eigenvalues'
        Write (nout,99998) eerrbd
        Write (nout,*)
        Write (nout,*) 'Error estimates for the eigenvectors'
        Write (nout,99998) zerrbd(1:n)
      Else
        Write (nout,99997) 'Failure in ZHBEV. INFO =', info
      End If

99999 Format (3X,(8F8.4))
99998 Format (4X,1P,6E11.1)
99997 Format (1X,A,I4)
    End Program f08hnfe


f08hpfe.f90

    Program f08hpfe

!     F08HPF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: nag_wp, x04daf, zhbevx
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Real (Kind=nag_wp), Parameter    :: zero = 0.0E+0_nag_wp
      Integer, Parameter               :: nin = 5, nout = 6
      Character (1), Parameter         :: uplo = 'U'
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: abstol, vl, vu
      Integer                          :: i, ifail, il, info, iu, j, kd, ldab, &
                                          ldq, ldz, m, n
!     .. Local Arrays ..
      Complex (Kind=nag_wp), Allocatable :: ab(:,:), q(:,:), work(:), z(:,:)
      Real (Kind=nag_wp), Allocatable  :: rwork(:), w(:)
      Integer, Allocatable             :: iwork(:), jfail(:)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: max, min
!     .. Executable Statements ..
      Write (nout,*) 'F08HPF Example Program Results'
      Write (nout,*)
!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) n, kd
      ldab = kd + 1
      ldq = n
      ldz = n
      m = n
      Allocate (ab(ldab,n),q(ldq,n),work(n),z(ldz,m),rwork(7*n),w(n),          &
        iwork(5*n),jfail(n))

!     Read the lower and upper bounds of the interval to be searched,
!     and read the upper or lower triangular part of the matrix A
!     from data file

      Read (nin,*) vl, vu
      If (uplo=='U') Then
        Read (nin,*)((ab(kd+1+i-j,j),j=i,min(n,i+kd)),i=1,n)
      Else If (uplo=='L') Then
        Read (nin,*)((ab(1+i-j,j),j=max(1,i-kd),i),i=1,n)
      End If

!     Set the absolute error tolerance for eigenvalues.  With ABSTOL
!     set to zero, the default value is used instead

      abstol = zero

!     Solve the band symmetric eigenvalue problem
!     The NAG name equivalent of zhbevx is f08hpf
      Call zhbevx('Vectors','Values in range',uplo,n,kd,ab,ldab,q,ldq,vl,vu,   &
        il,iu,abstol,m,w,z,ldz,work,rwork,iwork,jfail,info)

      If (info>=0) Then

!       Print solution

        Write (nout,99999) 'Number of eigenvalues found =', m
        Write (nout,*)
        Write (nout,*) 'Eigenvalues'
        Write (nout,99998) w(1:m)
        Flush (nout)

!       ifail: behaviour on error exit
!              =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
        ifail = 0
        Call x04daf('General',' ',n,m,z,ldz,'Selected eigenvectors',ifail)

        If (info>0) Then
          Write (nout,99999) 'INFO eigenvectors failed to converge, INFO =',   &
            info
          Write (nout,*) 'Indices of eigenvectors that did not converge'
          Write (nout,99997) jfail(1:m)
        End If
      Else
        Write (nout,99999) 'Failure in ZHBEVX. INFO =', info
      End If

99999 Format (1X,A,I5)
99998 Format (3X,(8F8.4))
99997 Format (3X,(8I8))
    End Program f08hpfe


f08hqfe.f90

    Program f08hqfe

!     F08HQF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: dznrm2, nag_wp, x04daf, zhbevd
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Complex (Kind=nag_wp)            :: scal
      Integer                          :: i, ifail, info, j, k, kd, ldab, ldz, &
                                          liwork, lrwork, lwork, n
      Character (1)                    :: job, uplo
!     .. Local Arrays ..
      Complex (Kind=nag_wp), Allocatable :: ab(:,:), work(:), z(:,:)
      Real (Kind=nag_wp), Allocatable  :: rwork(:), w(:)
      Integer, Allocatable             :: iwork(:)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: abs, conjg, max, maxloc, min
!     .. Executable Statements ..
      Write (nout,*) 'F08HQF Example Program Results'
!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) n, kd
      ldab = n
      ldz = n
      liwork = 5*n + 3
      lrwork = 2*n*n + 5*n + 1
      lwork = 2*n*n
      Allocate (ab(ldab,n),work(lwork),z(ldz,n),rwork(lrwork),w(n),            &
        iwork(liwork))

!     Read A from data file

      Read (nin,*) uplo
      If (uplo=='U') Then
        Do i = 1, n
          Read (nin,*)(ab(kd+1+i-j,j),j=i,min(n,i+kd))
        End Do
      Else If (uplo=='L') Then
        Do i = 1, n
          Read (nin,*)(ab(1+i-j,j),j=max(1,i-kd),i)
        End Do
      End If

      Read (nin,*) job

!     Calculate all the eigenvalues and eigenvectors of A
!     The NAG name equivalent of zhbevd is f08hqf
      Call zhbevd(job,uplo,n,kd,ab,ldab,w,z,ldz,work,lwork,rwork,lrwork,iwork, &
        liwork,info)

      Write (nout,*)
      If (info>0) Then
        Write (nout,*) 'Failure to converge.'
      Else

!       Print eigenvalues and eigenvectors

        Write (nout,*) 'Eigenvalues'
        Do i = 1, n
          Write (nout,99999) i, w(i)
        End Do
        Write (nout,*)
        Flush (nout)

!       Normalize the eigenvectors, largest element real
        Do i = 1, n
          rwork(1:n) = abs(z(1:n,i))
          k = maxloc(rwork(1:n),1)
          scal = conjg(z(k,i))/abs(z(k,i))/dznrm2(n,z(1,i),1)
          z(1:n,i) = z(1:n,i)*scal
        End Do

!       ifail: behaviour on error exit
!              =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
        ifail = 0
        Call x04daf('General',' ',n,n,z,ldz,'Eigenvectors',ifail)

      End If

99999 Format (3X,I5,5X,2F8.4)
    End Program f08hqfe


f08hsfe.f90

    Program f08hsfe

!     F08HSF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: dznrm2, nag_wp, x04dbf, zhbtrd, zsteqr
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Complex (Kind=nag_wp)            :: scal
      Integer                          :: i, ifail, info, j, k, kd, ldab, ldq, &
                                          n
      Character (1)                    :: uplo
!     .. Local Arrays ..
      Complex (Kind=nag_wp), Allocatable :: ab(:,:), q(:,:), work(:)
      Real (Kind=nag_wp), Allocatable  :: d(:), e(:), rwork(:)
      Character (1)                    :: clabs(1), rlabs(1)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: abs, conjg, max, maxloc, min
!     .. Executable Statements ..
      Write (nout,*) 'F08HSF Example Program Results'
!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) n, kd
      ldab = kd + 1
      ldq = n
      Allocate (ab(ldab,n),q(ldq,n),work(n),d(n),e(n-1),rwork(2*n-2))

!     Read A from data file

      Read (nin,*) uplo
      If (uplo=='U') Then
        Do i = 1, n
          Read (nin,*)(ab(kd+1+i-j,j),j=i,min(n,i+kd))
        End Do
      Else If (uplo=='L') Then
        Do i = 1, n
          Read (nin,*)(ab(1+i-j,j),j=max(1,i-kd),i)
        End Do
      End If

!     Reduce A to tridiagonal form T = (Q**H)*A*Q (and form Q)
!     The NAG name equivalent of zhbtrd is f08hsf
      Call zhbtrd('V',uplo,n,kd,ab,ldab,d,e,q,ldq,work,info)

!     Calculate all the eigenvalues and eigenvectors of A
!     The NAG name equivalent of zsteqr is f08jsf
      Call zsteqr('V',n,d,e,q,ldq,rwork,info)

      Write (nout,*)
      If (info>0) Then
        Write (nout,*) 'Failure to converge.'
      Else

!       Print eigenvalues and eigenvectors

        Write (nout,*) 'Eigenvalues'
        Write (nout,99999) d(1:n)
        Write (nout,*)
        Flush (nout)

!       Normalize the eigenvectors, largest element real
        Do i = 1, n
          rwork(1:n) = abs(q(1:n,i))
          k = maxloc(rwork(1:n),1)
          scal = conjg(q(k,i))/abs(q(k,i))/dznrm2(n,q(1,i),1)
          q(1:n,i) = q(1:n,i)*scal
        End Do

!       ifail: behaviour on error exit
!              =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
        ifail = 0
        Call x04dbf('General',' ',n,n,q,ldq,'Bracketed','F7.4','Eigenvectors', &
          'Integer',rlabs,'Integer',clabs,80,0,ifail)

      End If

99999 Format (8X,4(F7.4,11X,:))
    End Program f08hsfe


f08jafe.f90

    Program f08jafe

!     F08JAF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: ddisna, dstev, nag_wp, x02ajf, x04caf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: eerrbd, eps
      Integer                          :: i, ifail, info, ldz, n
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: d(:), e(:), rcondz(:), work(:),      &
                                          z(:,:), zerrbd(:)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: abs, max
!     .. Executable Statements ..
      Write (nout,*) 'F08JAF Example Program Results'
      Write (nout,*)
!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) n
      ldz = n
      Allocate (d(n),e(n-1),rcondz(n),work(2*n-2),z(ldz,n),zerrbd(n))

!     Read the diagonal and off-diagonal elements of the matrix A
!     from data file

      Read (nin,*) d(1:n)
      Read (nin,*) e(1:n-1)

!     Solve the symmetric tridiagonal eigenvalue problem
!     The NAG name equivalent of dstev is f08jaf
      Call dstev('Vectors',n,d,e,z,ldz,work,info)

      If (info==0) Then

!       Print solution

        Write (nout,*) 'Eigenvalues'
        Write (nout,99999) d(1:n)
        Flush (nout)

!       Standardize the eigenvectors so that first elements are non-negative.
        Do i = 1, n
          If (z(1,i)<0.0_nag_wp) Then
            z(1:n,i) = -z(1:n,i)
          End If
        End Do

!       ifail: behaviour on error exit
!              =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
        ifail = 0
        Call x04caf('General',' ',n,n,z,ldz,'Eigenvectors',ifail)

!       Get the machine precision, EPS and compute the approximate
!       error bound for the computed eigenvalues.  Note that for
!       the 2-norm, max( abs(D(i)) ) = norm(A), and since the
!       eigenvalues are returned in ascending order
!       max( abs(D(i)) ) = max( abs(D(1)), abs(D(n)))

        eps = x02ajf()
        eerrbd = eps*max(abs(d(1)),abs(d(n)))

!       Call DDISNA (F08FLF) to estimate reciprocal condition
!       numbers for the eigenvectors
        Call ddisna('Eigenvectors',n,n,d,rcondz,info)

!       Compute the error estimates for the eigenvectors

        Do i = 1, n
          zerrbd(i) = eerrbd/rcondz(i)
        End Do

!       Print the approximate error bounds for the eigenvalues
!       and vectors

        Write (nout,*)
        Write (nout,*) 'Error estimate for the eigenvalues'
        Write (nout,99998) eerrbd
        Write (nout,*)
        Write (nout,*) 'Error estimates for the eigenvectors'
        Write (nout,99998) zerrbd(1:n)
      Else
        Write (nout,99997) 'Failure in DSTEV. INFO =', info
      End If

99999 Format (3X,(8F8.4))
99998 Format (4X,1P,6E11.1)
99997 Format (1X,A,I4)
    End Program f08jafe


f08jbfe.f90

    Program f08jbfe

!     F08JBF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: dstevx, nag_wp, x02amf, x04caf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: abstol, vl, vu
      Integer                          :: ifail, il, info, iu, ldz, m, n
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: d(:), e(:), w(:), work(:), z(:,:)
      Integer, Allocatable             :: iwork(:), jfail(:)
!     .. Executable Statements ..
      Write (nout,*) 'F08JBF Example Program Results'
      Write (nout,*)
!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) n
      ldz = n
      m = n
      Allocate (d(n),e(n),w(n),work(5*n),z(ldz,m),iwork(5*n),jfail(n))

!     Read the lower and upper bounds of the interval to be searched,
!     and read the diagonal and off-diagonal elements of the matrix
!     A from data file

      Read (nin,*) vl, vu
      Read (nin,*) d(1:n)
      Read (nin,*) e(1:n-1)

!     Set the absolute error tolerance for eigenvalues.  With ABSTOL
!     set to zero, the default value would be used instead

      abstol = 2.0E0_nag_wp*x02amf()

!     Solve the symmetric eigenvalue problem
!     The NAG name equivalent of dstevx is f08jbf
      Call dstevx('Vectors','Values in range',n,d,e,vl,vu,il,iu,abstol,m,w,z,  &
        ldz,work,iwork,jfail,info)

      If (info>=0) Then

!       Print solution

        Write (nout,99999) 'Number of eigenvalues found =', m
        Write (nout,*)
        Write (nout,*) 'Eigenvalues'
        Write (nout,99998) w(1:m)
        Flush (nout)

!       ifail: behaviour on error exit
!              =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
        ifail = 0
        Call x04caf('General',' ',n,m,z,ldz,'Selected eigenvectors',ifail)

        If (info>0) Then
          Write (nout,99999) 'INFO eigenvectors failed to converge, INFO =',   &
            info
          Write (nout,*) 'Indices of eigenvectors that did not converge'
          Write (nout,99997) jfail(1:m)
        End If
      Else
        Write (nout,99999) 'Failure in DSTEVX. INFO =', info
      End If

99999 Format (1X,A,I5)
99998 Format (3X,(8F8.4))
99997 Format (3X,(8I8))
    End Program f08jbfe


f08jcfe.f90

    Program f08jcfe

!     F08JCF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: dnrm2, dstevd, nag_wp, x04caf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: norm
      Integer                          :: i, ifail, info, ldz, liwork, lwork,  &
                                          n
      Character (1)                    :: job
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: d(:), e(:), work(:), z(:,:)
      Integer, Allocatable             :: iwork(:)
!     .. Executable Statements ..
      Write (nout,*) 'F08JCF Example Program Results'
!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) n
      ldz = n
      liwork = 5*n + 3
      lwork = n*n + 4*n + 1
      Allocate (d(n),e(n-1),work(lwork),z(ldz,n),iwork(liwork))

!     Read T from data file

      Read (nin,*) d(1:n)
      Read (nin,*) e(1:n-1)

      Read (nin,*) job

!     Calculate all the eigenvalues and eigenvectors of T
!     The NAG name equivalent of dstevd is f08jcf
      Call dstevd(job,n,d,e,z,ldz,work,lwork,iwork,liwork,info)

      Write (nout,*)
      If (info>0) Then
        Write (nout,*) 'Failure to converge.'
      Else

!       Print eigenvalues and eigenvectors

        Write (nout,*) 'Eigenvalues'
        Write (nout,99999) d(1:n)
        Write (nout,*)
        Flush (nout)

!       Normalize the eigenvectors
        Do i = 1, n
!         The NAG name equivalent of dnrm2 is f06ejf
          norm = dnrm2(n,z(1,i),1)
          If (z(1,i)<0.0_nag_wp) Then
            norm = -norm
          End If
          z(1:n,i) = z(1:n,i)/norm
        End Do

!       ifail: behaviour on error exit
!              =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
        ifail = 0
        Call x04caf('General',' ',n,n,z,ldz,'Eigenvectors',ifail)

      End If

99999 Format (3X,(8F8.4))
    End Program f08jcfe


f08jdfe.f90

    Program f08jdfe

!     F08JDF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: dstevr, nag_wp, x04caf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Real (Kind=nag_wp), Parameter    :: zero = 0.0_nag_wp
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: abstol, vl, vu
      Integer                          :: ifail, il, info, iu, ldz, liwork,    &
                                          lwork, m, n
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: d(:), e(:), w(:), work(:), z(:,:)
      Real (Kind=nag_wp)               :: rdum(1)
      Integer                          :: idum(1)
      Integer, Allocatable             :: isuppz(:), iwork(:)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: max, nint
!     .. Executable Statements ..
      Write (nout,*) 'F08JDF Example Program Results'
      Write (nout,*)
!     Skip heading in data file and read N and the lower and upper
!     indices of the eigenvalues to be found
      Read (nin,*)
      Read (nin,*) n, il, iu
      ldz = n
      m = n
      Allocate (d(n),e(n-1),w(n),z(ldz,m),isuppz(2*n))

!     Use routine workspace query to get optimal workspace.
      lwork = -1
      liwork = -1
!     The NAG name equivalent of dstevr is f08jdf
      Call dstevr('Vectors','Indices',n,d,e,vl,vu,il,iu,abstol,m,w,z,ldz,      &
        isuppz,rdum,lwork,idum,liwork,info)

!     Make sure that there is enough workspace for block size nb.
      lwork = max(20*n,nint(rdum(1)))
      liwork = max(10*n,idum(1))
      Allocate (work(lwork),iwork(liwork))

!     Read the diagonal and off-diagonal elements of the matrix A
!     from data file

      Read (nin,*) d(1:n)
      Read (nin,*) e(1:n-1)

!     Set the absolute error tolerance for eigenvalues.  With ABSTOL
!     set to zero, the default value is used instead

      abstol = zero

!     Solve the symmetric tridiagonal eigenvalue problem
!     The NAG name equivalent of dstevr is f08jdf
      Call dstevr('Vectors','Indices',n,d,e,vl,vu,il,iu,abstol,m,w,z,ldz,      &
        isuppz,work,lwork,iwork,liwork,info)

      If (info==0) Then

!       Print solution

        Write (nout,*) 'Selected eigenvalues'
        Write (nout,99999) w(1:m)
        Flush (nout)

!       ifail: behaviour on error exit
!              =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
        ifail = 0
        Call x04caf('General',' ',n,m,z,ldz,'Selected eigenvectors',ifail)

      Else
        Write (nout,99998) 'Failure in DSTEVR. INFO =', info
      End If

99999 Format (3X,(8F8.4))
99998 Format (1X,A,I5)
    End Program f08jdfe


f08jefe.f90

    Program f08jefe

!     F08JEF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: dsteqr, nag_wp, x04caf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Integer                          :: i, ifail, info, ldz, n
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: d(:), e(:), work(:), z(:,:)
!     .. Executable Statements ..
      Write (nout,*) 'F08JEF Example Program Results'
!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) n
      ldz = n
      Allocate (d(n),e(n-1),work(2*n-2),z(ldz,n))

!     Read T from data file

      Read (nin,*) d(1:n)
      Read (nin,*) e(1:n-1)

!     Calculate all the eigenvalues and eigenvectors of T
!     The NAG name equivalent of dsteqr is f08jef
      Call dsteqr('I',n,d,e,z,ldz,work,info)

      Write (nout,*)
      If (info>0) Then
        Write (nout,*) 'Failure to converge.'
      Else

!       Print eigenvalues and eigenvectors

        Write (nout,*) 'Eigenvalues'
        Write (nout,99999) d(1:n)
        Write (nout,*)
        Flush (nout)

!       Standardize the eigenvectors so that first elements are non-negative.
        Do i = 1, n
          If (z(1,i)<0.0_nag_wp) Then
            z(1:n,i) = -z(1:n,i)
          End If
        End Do

!       ifail: behaviour on error exit
!              =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
        ifail = 0
        Call x04caf('General',' ',n,n,z,ldz,'Eigenvectors',ifail)

      End If

99999 Format (3X,(8F8.4))
    End Program f08jefe


f08jffe.f90

    Program f08jffe

!     F08JFF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: dsterf, nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Integer                          :: info, n
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: d(:), e(:)
!     .. Executable Statements ..
      Write (nout,*) 'F08JFF Example Program Results'
!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) n

      Allocate (d(n),e(n-1))

!     Read T from data file

      Read (nin,*) d(1:n)
      Read (nin,*) e(1:n-1)

!     Calculate the eigenvalues of T
!     The NAG name equivalent of dsterf is f08jff
      Call dsterf(n,d,e,info)

      Write (nout,*)
      If (info>0) Then
        Write (nout,*) 'Failure to converge.'
      Else
        Write (nout,*) 'Eigenvalues'
        Write (nout,99999) d(1:n)
      End If

99999 Format (3X,(9F8.4))
    End Program f08jffe


f08jgfe.f90

    Program f08jgfe

!     F08JGF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: blas_damax_val, dpteqr, nag_wp, x04caf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Real (Kind=nag_wp), Parameter    :: zero = 0.0_nag_wp
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: r
      Integer                          :: i, ifail, info, k, ldz, n
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: d(:), e(:), work(:), z(:,:)
!     .. Executable Statements ..
      Write (nout,*) 'F08JGF Example Program Results'
!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) n
      ldz = n
      Allocate (d(n),e(n-1),work(4*n),z(ldz,n))

!     Read T from data file

      Read (nin,*) d(1:n)
      Read (nin,*) e(1:n-1)

!     Calculate all the eigenvalues and eigenvectors of T
!     The NAG name equivalent of dpteqr is f08jgf
      Call dpteqr('I',n,d,e,z,ldz,work,info)

      Write (nout,*)
      If (info>0 .And. info<=n) Then
        Write (nout,*) 'T is not positive definite.'
      Else If (info>n) Then
        Write (nout,*) 'Failure to converge.'
      Else

!       Print eigenvalues and eigenvectors

        Write (nout,*) 'Eigenvalues'
        Write (nout,99999) d(1:n)
        Write (nout,*)
        Flush (nout)

!       Normalize the eigenvectors, largest positive
        Do i = 1, n
          Call blas_damax_val(n,z(1,i),1,k,r)
          If (z(k,i)<zero) Then
            z(1:n,i) = -z(1:n,i)
          End If
        End Do

!       ifail: behaviour on error exit
!              =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
        ifail = 0
        Call x04caf('General',' ',n,n,z,ldz,'Eigenvectors',ifail)

      End If

99999 Format (3X,(8F8.4))
    End Program f08jgfe


f08jhfe.f90

    Program f08jhfe

!     F08JHF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: dsbtrd, dstedc, nag_wp, x04caf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
      Character (1), Parameter         :: uplo = 'U'
!     .. Local Scalars ..
      Integer                          :: i, ifail, info, j, kd, ldab, ldz,    &
                                          lgn, liwork, lwork, n
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: ab(:,:), d(:), e(:), work(:), z(:,:)
      Real (Kind=nag_wp)               :: rdum(1)
      Integer                          :: idum(1)
      Integer, Allocatable             :: iwork(:)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: ceiling, log, max, min, nint, real
!     .. Executable Statements ..
      Write (nout,*) 'F08JHF Example Program Results'
      Write (nout,*)
!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) n, kd
      ldab = kd + 1
      ldz = n
      lgn = ceiling(log(real(n,kind=nag_wp))/log(2.0E0_nag_wp))
      Allocate (ab(ldab,n),d(n),e(n-1),z(ldz,n))

!     Use routine workspace query to get optimal workspace.
      lwork = -1
      liwork = -1
!     The NAG name equivalent of dstedc is f08jhf
      Call dstedc('V',n,d,e,z,ldz,rdum,lwork,idum,liwork,info)

!     Make sure that there is enough workspace.
      lwork = max(1+3*n+2*n*lgn+4*n*n,nint(rdum(1)))
      liwork = max(6+6*n+5*n*lgn,idum(1))
      Allocate (work(lwork),iwork(liwork))

!     Read the upper or lower triangular part of the band matrix A
!     from data file

      If (uplo=='U') Then
        Do i = 1, n
          Read (nin,*)(ab(kd+1+i-j,j),j=i,min(n,i+kd))
        End Do
      Else If (uplo=='L') Then
        Do i = 1, n
          Read (nin,*)(ab(1+i-j,j),j=max(1,i-kd),i)
        End Do
      End If

!     Reduce A to tridiagonal form T = (Z**T)*A*Z, and form Z
!     The NAG name equivalent of dsbtrd is f08hef
      Call dsbtrd('V',uplo,n,kd,ab,ldab,d,e,z,ldz,work,info)

!     Calculate all the eigenvalues and eigenvectors of A,
!     from T and Z
!     The NAG name equivalent of dstedc is f08jhf
      Call dstedc('V',n,d,e,z,ldz,work,lwork,iwork,liwork,info)

      If (info==0) Then

!       Print eigenvalues and eigenvectors

        Write (nout,*) 'Eigenvalues'
        Write (nout,99999) d(1:n)

        Write (nout,*)
        Flush (nout)

!       Standardize the eigenvectors so that first elements are non-negative.
        Do i = 1, n
          If (z(1,i)<0.0_nag_wp) Then
            z(1:n,i) = -z(1:n,i)
          End If
        End Do

!       ifail: behaviour on error exit
!               =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
        ifail = 0
        Call x04caf('General',' ',n,n,z,ldz,'Eigenvectors',ifail)

      Else
        Write (nout,99998) 'Failure in DSTEDC. INFO = ', info
      End If

99999 Format ((3X,8F8.4))
99998 Format (1X,A,I10)
    End Program f08jhfe


f08jlfe.f90

    Program f08jlfe

!     F08JLF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: dstegr, nag_wp, x04caf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Real (Kind=nag_wp), Parameter    :: vl = 0.0E0_nag_wp
      Real (Kind=nag_wp), Parameter    :: vu = 0.0E0_nag_wp
      Integer, Parameter               :: il = 0, iu = 0, nin = 5, nout = 6
      Character (1), Parameter         :: range = 'A'
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: abstol
      Integer                          :: i, ifail, info, ldz, liwork, lwork,  &
                                          m, n
      Character (1)                    :: jobz
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: d(:), e(:), w(:), work(:), z(:,:)
      Integer, Allocatable             :: isuppz(:), iwork(:)
!     .. Executable Statements ..
      Write (nout,*) 'F08JLF Example Program Results'
      Write (nout,*)
!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) n
      ldz = n
      liwork = 10*n
      lwork = 18*n
      Allocate (d(n),e(n),w(n),work(lwork),z(ldz,n),isuppz(2*n),iwork(liwork))

!     Read the symmetric tridiagonal matrix T from data file, first
!     the diagonal elements, then the off diagonal elements and then
!     JOBV ('N' - eigenvalues only, 'V' - vectors as well)

      Read (nin,*) d(1:n)
      Read (nin,*) e(1:n-1)
      Read (nin,*) jobz

!     Calculate all the eigenvalues of T. Set ABSTOL to zero so that
!     the default value is used.

      abstol = 0.0E0_nag_wp
!     The NAG name equivalent of dstegr is f08jlf
      Call dstegr(jobz,range,n,d,e,vl,vu,il,iu,abstol,m,w,z,ldz,isuppz,work,   &
        lwork,iwork,liwork,info)

      If (info==0) Then

!       Print eigenvalues and eigenvectors

        Write (nout,*) 'Eigenvalues'
        Write (nout,99999) w(1:m)

        Write (nout,*)
        Flush (nout)

!       Standardize the eigenvectors so that first elements are non-negative.
        Do i = 1, m
          If (z(1,i)<0.0_nag_wp) Then
            z(1:n,i) = -z(1:n,i)
          End If
        End Do

!       ifail: behaviour on error exit
!              =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
        ifail = 0
        Call x04caf('General',' ',n,m,z,ldz,'Eigenvectors',ifail)

      Else
        Write (nout,99998) 'Failure to compute an eigenvalue, INFO = ', info
      End If

99999 Format ((3X,8F8.4))
99998 Format (1X,A,I10)
    End Program f08jlfe


f08jufe.f90

    Program f08jufe

!     F08JUF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: dznrm2, f06tff, nag_wp, x04dbf, zhetrd, zpteqr,   &
                             zungtr
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Complex (Kind=nag_wp)            :: scal
      Integer                          :: i, ifail, info, k, lda, ldz, lwork,  &
                                          n
      Character (1)                    :: uplo
!     .. Local Arrays ..
      Complex (Kind=nag_wp), Allocatable :: a(:,:), tau(:), work(:), z(:,:)
      Real (Kind=nag_wp), Allocatable  :: d(:), e(:), rwork(:)
      Character (1)                    :: clabs(1), rlabs(1)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: abs, conjg, maxloc
!     .. Executable Statements ..
      Write (nout,*) 'F08JUF Example Program Results'
!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) n
      lda = n
      ldz = n
      lwork = 64*n
      Allocate (a(lda,n),tau(n),work(lwork),z(ldz,n),d(n),e(n),rwork(4*n))

!     Read A from data file

      Read (nin,*) uplo
      If (uplo=='U') Then
        Read (nin,*)(a(i,i:n),i=1,n)
      Else If (uplo=='L') Then
        Read (nin,*)(a(i,1:i),i=1,n)
      End If

!     Reduce A to tridiagonal form T = (Q**H)*A*Q

!     The NAG name equivalent of zhetrd is f08fsf
      Call zhetrd(uplo,n,a,lda,d,e,tau,work,lwork,info)

!     Copy A into Z

      Call f06tff(uplo,n,n,a,lda,z,ldz)

!     Form Q explicitly, storing the result in Z

!     The NAG name equivalent of zungtr is f08ftf
      Call zungtr(uplo,n,z,ldz,tau,work,lwork,info)

!     Calculate all the eigenvalues and eigenvectors of A

!     The NAG name equivalent of zpteqr is f08juf
      Call zpteqr('V',n,d,e,z,ldz,rwork,info)

      Write (nout,*)
      If (info>0) Then
        Write (nout,*) 'Failure to converge.'
      Else

!       Print eigenvalues and eigenvectors

        Write (nout,*) 'Eigenvalues'
        Write (nout,99999) d(1:n)
        Write (nout,*)
        Flush (nout)

!       Normalize the eigenvectors, largest element real
        Do i = 1, n
          rwork(1:n) = abs(z(1:n,i))
          k = maxloc(rwork(1:n),1)
          scal = conjg(z(k,i))/abs(z(k,i))/dznrm2(n,z(1,i),1)
          z(1:n,i) = z(1:n,i)*scal
        End Do

!       ifail: behaviour on error exit
!              =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
        ifail = 0
        Call x04dbf('General',' ',n,n,z,ldz,'Bracketed','F7.4','Eigenvectors', &
          'Integer',rlabs,'Integer',clabs,80,0,ifail)

      End If

99999 Format (8X,4(F7.4,11X,:))
    End Program f08jufe


f08jvfe.f90

    Program f08jvfe

!     F08JVF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: dznrm2, nag_wp, x04dbf, zhbtrd, zstedc
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
      Character (1), Parameter         :: uplo = 'U'
!     .. Local Scalars ..
      Complex (Kind=nag_wp)            :: scal
      Integer                          :: i, ifail, info, j, k, kd, ldab, ldz, &
                                          lgn, liwork, lrwork, lwork, n
!     .. Local Arrays ..
      Complex (Kind=nag_wp), Allocatable :: ab(:,:), work(:), z(:,:)
      Complex (Kind=nag_wp)            :: cdum(1)
      Real (Kind=nag_wp), Allocatable  :: d(:), e(:), rwork(:)
      Real (Kind=nag_wp)               :: rdum(1)
      Integer                          :: idum(1)
      Integer, Allocatable             :: iwork(:)
      Character (1)                    :: clabs(1), rlabs(1)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: abs, ceiling, conjg, log, max,       &
                                          maxloc, min, nint, real
!     .. Executable Statements ..
      Write (nout,*) 'F08JVF Example Program Results'
      Write (nout,*)
!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) n, kd
      ldab = kd + 1
      ldz = n
      lgn = ceiling(log(real(n,kind=nag_wp))/log(2.0_nag_wp))
      Allocate (ab(ldab,n),z(ldz,n),d(n),e(n-1))

!     Use routine workspace query to get optimal workspace.
      lwork = -1
      lrwork = -1
      liwork = -1
!     The NAG name equivalent of zstedc is f08jvf
      Call zstedc('V',n,d,e,z,ldz,cdum,lwork,rdum,lrwork,idum,liwork,info)

!     Make sure that there is enough workspace.
      lwork = max(n*n,nint(real(cdum(1))))
      lrwork = max(1+3*n+2*n*lgn+4*n*n,nint(rdum(1)))
      liwork = max(6+6*n+5*n*lgn,idum(1))
      Allocate (work(lwork),rwork(lrwork),iwork(liwork))

!     Read the upper or lower triangular part of the band matrix A
!     from data file

      If (uplo=='U') Then
        Do i = 1, n
          Read (nin,*)(ab(kd+1+i-j,j),j=i,min(n,i+kd))
        End Do
      Else If (uplo=='L') Then
        Do i = 1, n
          Read (nin,*)(ab(1+i-j,j),j=max(1,i-kd),i)
        End Do
      End If

!     Reduce A to tridiagonal form T = (Z**T)*A*Z, and form Z

!     The NAG name equivalent of zhbtrd is f08hsf
      Call zhbtrd('V',uplo,n,kd,ab,ldab,d,e,z,ldz,work,info)

!     Calculate all the eigenvalues and eigenvectors of A,
!     from T and Z

!     The NAG name equivalent of zstedc is f08jvf
      Call zstedc('V',n,d,e,z,ldz,work,lwork,rwork,lrwork,iwork,liwork,info)

      If (info==0) Then

!       Print eigenvalues and eigenvectors

        Write (nout,*) 'Eigenvalues'
        Write (nout,99999) d(1:n)

        Write (nout,*)
        Flush (nout)

!       Normalize the eigenvectors, largest element real
        Do i = 1, n
          rwork(1:n) = abs(z(1:n,i))
          k = maxloc(rwork(1:n),1)
          scal = conjg(z(k,i))/abs(z(k,i))/dznrm2(n,z(1,i),1)
          z(1:n,i) = z(1:n,i)*scal
        End Do

!       ifail: behaviour on error exit
!              =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
        ifail = 0
        Call x04dbf('General',' ',n,n,z,ldz,'Bracketed','F7.4','Eigenvectors', &
          'Integer',rlabs,'Integer',clabs,80,0,ifail)

      Else
        Write (nout,99998) 'Failure in ZSTEDC. INFO = ', info
      End If

99999 Format (4X,F8.4,3(10X,F8.4))
99998 Format (1X,A,I10)
    End Program f08jvfe


f08jyfe.f90

    Program f08jyfe

!     F08JYF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: nag_wp, x04daf, zstegr
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Real (Kind=nag_wp), Parameter    :: vl = 0.0E0_nag_wp
      Real (Kind=nag_wp), Parameter    :: vu = 0.0E0_nag_wp
      Integer, Parameter               :: il = 0, iu = 0, nin = 5, nout = 6
      Character (1), Parameter         :: range = 'A'
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: abstol
      Integer                          :: i, ifail, info, ldz, liwork, lwork,  &
                                          m, n
      Character (1)                    :: jobz
!     .. Local Arrays ..
      Complex (Kind=nag_wp), Allocatable :: z(:,:)
      Real (Kind=nag_wp), Allocatable  :: d(:), e(:), w(:), work(:)
      Integer, Allocatable             :: isuppz(:), iwork(:)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: real
!     .. Executable Statements ..
      Write (nout,*) 'F08JYF Example Program Results'
      Write (nout,*)
!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) n
      ldz = n
      liwork = 10*n
      lwork = 18*n
      Allocate (z(ldz,n),d(n),e(n),w(n),work(lwork),isuppz(2*n),iwork(liwork))

!     Read the symmetric tridiagonal matrix T from data file, first
!     the diagonal elements, then the off diagonal elements and then
!     JOBV ('N' - eigenvalues only, 'V' - vectors as well)

      Read (nin,*) d(1:n)
      Read (nin,*) e(1:n-1)
      Read (nin,*) jobz

!     Calculate all the eigenvalues of T. Set ABSTOL to zero so that
!     the default value is used.

      abstol = 0.0E0_nag_wp
!     The NAG name equivalent of zstegr is f08jyf
      Call zstegr(jobz,range,n,d,e,vl,vu,il,iu,abstol,m,w,z,ldz,isuppz,work,   &
        lwork,iwork,liwork,info)

      If (info==0) Then

!       Print eigenvalues and eigenvectors

        Write (nout,*) 'Eigenvalues'
        Write (nout,99999) w(1:m)

        Write (nout,*)
        Flush (nout)

!       Standardize the eigenvectors so that first elements are non-negative.
        Do i = 1, m
          If (real(z(1,i))<0.0_nag_wp) Then
            z(1:n,i) = -z(1:n,i)
          End If
        End Do

!       ifail: behaviour on error exit
!              =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
        ifail = 0
        Call x04daf('General',' ',n,m,z,ldz,'Eigenvectors',ifail)

      Else
        Write (nout,99998) 'Failure to compute an eigenvalue, INFO = ', info
      End If

99999 Format ((3X,8F8.4))
99998 Format (1X,A,I10)
    End Program f08jyfe


f08kafe.f90

    Program f08kafe

!     F08KAF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: dgelss, dnrm2, nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nb = 64, nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: rcond, rnorm
      Integer                          :: i, info, lda, lwork, m, n, rank
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: a(:,:), b(:), s(:), work(:)
!     .. Executable Statements ..
      Write (nout,*) 'F08KAF Example Program Results'
      Write (nout,*)
!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) m, n
      lda = m
      lwork = 3*n + nb*(m+n)
      Allocate (a(lda,n),b(m),s(n),work(lwork))

!     Read A and B from data file

      Read (nin,*)(a(i,1:n),i=1,m)
      Read (nin,*) b(1:m)

!     Choose RCOND to reflect the relative accuracy of the input data

      rcond = 0.01_nag_wp

!     Solve the least squares problem min( norm2(b - Ax) ) for the x
!     of minimum norm.

!     The NAG name equivalent of dgelss is f08kaf
      Call dgelss(m,n,1,a,lda,b,m,s,rcond,rank,work,lwork,info)

      If (info==0) Then

!       Print solution

        Write (nout,*) 'Least squares solution'
        Write (nout,99999) b(1:n)

!       Print the effective rank of A

        Write (nout,*)
        Write (nout,*) 'Tolerance used to estimate the rank of A'
        Write (nout,99998) rcond
        Write (nout,*) 'Estimated rank of A'
        Write (nout,99997) rank

!       Print singular values of A

        Write (nout,*)
        Write (nout,*) 'Singular values of A'
        Write (nout,99999) s(1:n)

!       Compute and print estimate of the square root of the
!       residual sum of squares

        If (rank==n) Then
!         The NAG name equivalent of dnrm2 is f06ejf
          rnorm = dnrm2(m-n,b(n+1),1)
          Write (nout,*)
          Write (nout,*) 'Square root of the residual sum of squares'
          Write (nout,99998) rnorm
        End If
      Else
        Write (nout,*) 'The SVD algorithm failed to converge'
      End If

99999 Format (1X,7F11.4)
99998 Format (3X,1P,E11.2)
99997 Format (1X,I6)
    End Program f08kafe


f08kbfe.f90

    Program f08kbfe

!     F08KBF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: dgesvd, nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nb = 64, nin = 5, nout = 6,          &
                                          prerr = 0
!     .. Local Scalars ..
      Integer                          :: i, info, lda, ldu, ldvt, lwork, m, n
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: a(:,:), a_copy(:,:), b(:), s(:),     &
                                          u(:,:), vt(:,:), work(:)
      Real (Kind=nag_wp)               :: dummy(1,1)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: max, min, nint
!     .. Executable Statements ..
      Write (nout,*) 'F08KBF Example Program Results'
      Write (nout,*)
!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) m, n
      lda = m
      ldu = m
      ldvt = n
      Allocate (a(lda,n),a_copy(m,n),s(n),vt(ldvt,n),u(ldu,m),b(m))

!     Read the m by n matrix A from data file
      Read (nin,*)(a(i,1:n),i=1,m)

!     Read the right hand side of the linear system
      Read (nin,*) b(1:m)

      a_copy(1:m,1:n) = a(1:m,1:n)

!     Use routine workspace query to get optimal workspace.
      lwork = -1
!     The NAG name equivalent of dgesvd is f08kbf
      Call dgesvd('A','S',m,n,a,lda,s,u,ldu,vt,ldvt,dummy,lwork,info)

!     Make sure that there is enough workspace for block size nb.
      lwork = max(m+4*n+nb*(m+n),nint(dummy(1,1)))
      Allocate (work(lwork))

!     Compute the singular values and left and right singular vectors
!     of A.

!     The NAG name equivalent of dgesvd is f08kbf
      Call dgesvd('A','S',m,n,a,lda,s,u,ldu,vt,ldvt,work,lwork,info)

      If (info/=0) Then
        Write (nout,99999) 'Failure in DGESVD. INFO =', info
99999   Format (1X,A,I4)
        Go To 100
      End If

!     Print the significant singular values of A

      Write (nout,*) 'Singular values of A:'
      Write (nout,99998) s(1:min(m,n))
99998 Format (1X,4(3X,F11.4))

      If (prerr>0) Then
        Call compute_error_bounds(m,n,s)
      End If

      If (m>n) Then
!       Compute V*Inv(S)*U^T * b to get least squares solution.
        Call compute_least_squares(m,n,a_copy,m,u,ldu,vt,ldvt,s,b)
      End If

100   Continue

    Contains
      Subroutine compute_least_squares(m,n,a,lda,u,ldu,vt,ldvt,s,b)

!       .. Use Statements ..
        Use nag_library, Only: dgemv, dnrm2
!       .. Implicit None Statement ..
        Implicit None
!       .. Scalar Arguments ..
        Integer, Intent (In)           :: lda, ldu, ldvt, m, n
!       .. Array Arguments ..
        Real (Kind=nag_wp), Intent (In) :: a(lda,n), s(n), u(ldu,m),           &
                                          vt(ldvt,n)
        Real (Kind=nag_wp), Intent (Inout) :: b(m)
!       .. Local Scalars ..
        Real (Kind=nag_wp)             :: alpha, beta, norm
!       .. Local Arrays ..
        Real (Kind=nag_wp), Allocatable :: x(:), y(:)
!       .. Intrinsic Procedures ..
        Intrinsic                      :: allocated
!       .. Executable Statements ..
        Allocate (x(n),y(n))

!       Compute V*Inv(S)*U^T * b to get least squares solution.

!       y = U^T b
!       The NAG name equivalent of dgemv is f06paf
        alpha = 1._nag_wp
        beta = 0._nag_wp
        Call dgemv('T',m,n,alpha,u,ldu,b,1,beta,y,1)

        y(1:n) = y(1:n)/s(1:n)

!       x = V y
        Call dgemv('T',n,n,alpha,vt,ldvt,y,1,beta,x,1)

        Write (nout,*)
        Write (nout,*) 'Least squares solution:'
        Write (nout,99999) x(1:n)

!       Find norm of residual ||b-Ax||.
        alpha = -1._nag_wp
        beta = 1._nag_wp
        Call dgemv('N',m,n,alpha,a,lda,x,1,beta,b,1)

        norm = dnrm2(m,b,1)

        Write (nout,*)
        Write (nout,*) 'Norm of Residual:'
        Write (nout,99999) norm

        If (allocated(x)) Then
          Deallocate (x)
        End If
        If (allocated(y)) Then
          Deallocate (y)
        End If

99999   Format (1X,4(3X,F11.4))

      End Subroutine compute_least_squares

      Subroutine compute_error_bounds(m,n,s)

!       Error estimates for singular values and vectors is computed
!       and printed here.

!       .. Use Statements ..
        Use nag_library, Only: ddisna, nag_wp, x02ajf
!       .. Implicit None Statement ..
        Implicit None
!       .. Scalar Arguments ..
        Integer, Intent (In)           :: m, n
!       .. Array Arguments ..
        Real (Kind=nag_wp), Intent (In) :: s(n)
!       .. Local Scalars ..
        Real (Kind=nag_wp)             :: eps, serrbd
        Integer                        :: i, info
!       .. Local Arrays ..
        Real (Kind=nag_wp), Allocatable :: rcondu(:), rcondv(:), uerrbd(:),    &
                                          verrbd(:)
!       .. Executable Statements ..
        Allocate (rcondu(n),rcondv(n),uerrbd(n),verrbd(n))

!       Get the machine precision, EPS and compute the approximate
!       error bound for the computed singular values.  Note that for
!       the 2-norm, S(1) = norm(A)

        eps = x02ajf()
        serrbd = eps*s(1)

!       Call DDISNA (F08FLF) to estimate reciprocal condition
!       numbers for the singular vectors

        Call ddisna('Left',m,n,s,rcondu,info)
        Call ddisna('Right',m,n,s,rcondv,info)

!       Compute the error estimates for the singular vectors

        Do i = 1, n
          uerrbd(i) = serrbd/rcondu(i)
          verrbd(i) = serrbd/rcondv(i)
        End Do

!       Print the approximate error bounds for the singular values
!       and vectors

        Write (nout,*)
        Write (nout,*) 'Error estimate for the singular values'
        Write (nout,99999) serrbd
        Write (nout,*)
        Write (nout,*) 'Error estimates for the left singular vectors'
        Write (nout,99999) uerrbd(1:n)
        Write (nout,*)
        Write (nout,*) 'Error estimates for the right singular vectors'
        Write (nout,99999) verrbd(1:n)

99999   Format (4X,1P,6E11.1)

      End Subroutine compute_error_bounds

    End Program f08kbfe


f08kcfe.f90

    Program f08kcfe

!     F08KCF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: dgelsd, nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: rcond
      Integer                          :: i, info, lda, liwork, lwork, m, n,   &
                                          rank
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: a(:,:), b(:), s(:), work(:)
      Real (Kind=nag_wp)               :: lw(1)
      Integer, Allocatable             :: iwork(:)
      Integer                          :: liw(1)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: nint
!     .. Executable Statements ..
      Write (nout,*) 'F08KCF Example Program Results'
      Write (nout,*)
!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) m, n
      lda = m
      Allocate (a(lda,n),b(n),s(m))

!     Read A and B from data file

      Read (nin,*)(a(i,1:n),i=1,m)
      Read (nin,*) b(1:m)

!     Choose RCOND to reflect the relative accuracy of the input
!     data

      rcond = 0.01_nag_wp

!     Call f08kcf/dgelsd in workspace query mode.
      lwork = -1
!     The NAG name equivalent of dgelsd is f08kcf
      Call dgelsd(m,n,1,a,lda,b,n,s,rcond,rank,lw,lwork,liw,info)
      lwork = nint(lw(1))
      liwork = liw(1)
      Allocate (work(lwork),iwork(liwork))

!     Now Solve the least squares problem min( norm2(b - Ax) ) for the
!     x of minimum norm.
      Call dgelsd(m,n,1,a,lda,b,n,s,rcond,rank,work,lwork,iwork,info)

      If (info==0) Then

!       Print solution

        Write (nout,*) 'Least squares solution'
        Write (nout,99999) b(1:n)

!       Print the effective rank of A

        Write (nout,*)
        Write (nout,*) 'Tolerance used to estimate the rank of A'
        Write (nout,99998) rcond
        Write (nout,*) 'Estimated rank of A'
        Write (nout,99997) rank

!       Print singular values of A

        Write (nout,*)
        Write (nout,*) 'Singular values of A'
        Write (nout,99999) s(1:m)
      Else
        Write (nout,*) 'The SVD algorithm failed to converge'
      End If

99999 Format (1X,7F11.4)
99998 Format (3X,1P,E11.2)
99997 Format (1X,I6)
    End Program f08kcfe


f08kdfe.f90

    Program f08kdfe

!     F08KDF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: ddisna, dgesdd, nag_wp, x02ajf, x04caf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nb = 64, nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: eps, serrbd
      Integer                          :: i, ifail, info, lda, ldu, lwork, m,  &
                                          n
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: a(:,:), rcondu(:), rcondv(:), s(:),  &
                                          u(:,:), uerrbd(:), verrbd(:),        &
                                          work(:)
      Real (Kind=nag_wp)               :: dummy(1,1)
      Integer, Allocatable             :: iwork(:)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: max, min, nint
!     .. Executable Statements ..
      Write (nout,*) 'F08KDF Example Program Results'
      Write (nout,*)
!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) m, n
      lda = m
      ldu = m
      Allocate (a(lda,n),rcondu(m),rcondv(m),s(m),u(ldu,m),uerrbd(m),          &
        verrbd(m),iwork(8*min(m,n)))

!     Use routine workspace query to get optimal workspace.
      lwork = -1
!     The NAG name equivalent of dgesdd is f08kdf
      Call dgesdd('Overwrite A by tranpose(V)',m,n,a,lda,s,u,ldu,dummy,1,      &
        dummy,lwork,iwork,info)

!     Make sure that there is enough workspace for block size nb.
      lwork = max((5*m+9)*m+n+nb*(m+n),nint(dummy(1,1)))
      Allocate (work(lwork))

!     Read the m by n matrix A from data file

      Read (nin,*)(a(i,1:n),i=1,m)

!     Compute the singular values and left and right singular vectors
!     of A (A = U*S*(V**T), m.le.n)

!     The NAG name equivalent of dgesdd is f08kdf
      Call dgesdd('Overwrite A by tranpose(V)',m,n,a,lda,s,u,ldu,dummy,1,work, &
        lwork,iwork,info)

      If (info==0) Then

!       Print solution

        Write (nout,*) 'Singular values'
        Write (nout,99999) s(1:m)
        Flush (nout)

!       Normalize so that u(1,j)>=0
        Do i = 1, m
          If (u(1,i)<0.0_nag_wp) Then
            u(1:m,i) = -u(1:m,i)
            a(i,1:n) = -a(i,1:n)
          End If
        End Do
!       ifail: behaviour on error exit
!              =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
        ifail = 0
        Call x04caf('General',' ',m,m,u,ldu,'Left singular vectors',ifail)

        Write (nout,*)
        Flush (nout)

        Call x04caf('General',' ',m,n,a,lda,'Right singular vectors by row '// &
          '(first m rows of V**T)',ifail)

!       Get the machine precision, EPS and compute the approximate
!       error bound for the computed singular values.  Note that for
!       the 2-norm, S(1) = norm(A)

        eps = x02ajf()
        serrbd = eps*s(1)

!       Call DDISNA (F08FLF) to estimate reciprocal condition
!       numbers for the singular vectors

        Call ddisna('Left',m,n,s,rcondu,info)
        Call ddisna('Right',m,n,s,rcondv,info)

!       Compute the error estimates for the singular vectors

        Do i = 1, m
          uerrbd(i) = serrbd/rcondu(i)
          verrbd(i) = serrbd/rcondv(i)
        End Do

!       Print the approximate error bounds for the singular values
!       and vectors

        Write (nout,*)
        Write (nout,*) 'Error estimate for the singular values'
        Write (nout,99998) serrbd
        Write (nout,*)
        Write (nout,*) 'Error estimates for the left singular vectors'
        Write (nout,99998) uerrbd(1:m)
        Write (nout,*)
        Write (nout,*) 'Error estimates for the right singular vectors'
        Write (nout,99998) verrbd(1:m)
      Else
        Write (nout,99997) 'Failure in DGESDD. INFO =', info
      End If

99999 Format (3X,(8F8.4))
99998 Format (4X,1P,6E11.1)
99997 Format (1X,A,I4)
    End Program f08kdfe


f08kefe.f90

    Program f08kefe

!     F08KEF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: dgebrd, nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Integer                          :: i, info, lda, lwork, m, n
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: a(:,:), d(:), e(:), taup(:),         &
                                          tauq(:), work(:)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: min
!     .. Executable Statements ..
      Write (nout,*) 'F08KEF Example Program Results'
!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) m, n
      lda = m
      lwork = 64*(m+n)
      Allocate (a(lda,n),d(n),e(n-1),taup(n),tauq(n),work(lwork))

!     Read A from data file

      Read (nin,*)(a(i,1:n),i=1,m)

!     Reduce A to bidiagonal form

!     The NAG name equivalent of dgebrd is f08kef
      Call dgebrd(m,n,a,lda,d,e,tauq,taup,work,lwork,info)

!     Print bidiagonal form

      Write (nout,*)
      Write (nout,*) 'Diagonal'
      Write (nout,99999) d(1:min(m,n))
      If (m>=n) Then
        Write (nout,*) 'Superdiagonal'
      Else
        Write (nout,*) 'Subdiagonal'
      End If
      Write (nout,99999) e(1:min(m,n)-1)

99999 Format (1X,8F9.4)
    End Program f08kefe


f08kffe.f90

    Program f08kffe

!     F08KFF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: dbdsqr, dgebrd, dorgbr, f06qff, nag_wp, x04caf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Integer                          :: i, ic, ifail, info, lda, ldc, ldu,   &
                                          ldvt, lwork, m, n
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: a(:,:), c(:,:), d(:), e(:), taup(:), &
                                          tauq(:), u(:,:), vt(:,:), work(:)
!     .. Executable Statements ..
      Write (nout,*) 'F08KFF Example Program Results'
!     Skip heading in data file
      Read (nin,*)
      Do ic = 1, 2
        Read (nin,*) m, n
        lda = m
        ldc = n
        ldu = m
        ldvt = n
        lwork = 64*(m+n)
        Allocate (a(lda,n),c(ldc,n),d(n),e(n-1),taup(n),tauq(n),u(ldu,n),      &
          vt(ldvt,n),work(lwork))

!       Read A from data file

        Read (nin,*)(a(i,1:n),i=1,m)

!       Reduce A to bidiagonal form
!       The NAG name equivalent of dgebrd is f08kef
        Call dgebrd(m,n,a,lda,d,e,tauq,taup,work,lwork,info)

        If (m>=n) Then

!         Copy A to VT and U

          Call f06qff('Upper',n,n,a,lda,vt,ldvt)
          Call f06qff('Lower',m,n,a,lda,u,ldu)

!         Form P**T explicitly, storing the result in VT
!         The NAG name equivalent of dorgbr is f08kff
          Call dorgbr('P',n,n,m,vt,ldvt,taup,work,lwork,info)

!         Form Q explicitly, storing the result in U
!         The NAG name equivalent of dorgbr is f08kff
          Call dorgbr('Q',m,n,n,u,ldu,tauq,work,lwork,info)

!         Compute the SVD of A
!         The NAG name equivalent of dbdsqr is f08mef
          Call dbdsqr('Upper',n,n,m,0,d,e,vt,ldvt,u,ldu,c,ldc,work,info)

!         Print singular values, left & right singular vectors

          Write (nout,*)
          Write (nout,*) 'Example 1: singular values'
          Write (nout,99999) d(1:n)
          Write (nout,*)
          Flush (nout)

!         ifail: behaviour on error exit
!                =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
          ifail = 0
          Call x04caf('General',' ',n,n,vt,ldvt,                               &
            'Example 1: right singular vectors, by row',ifail)

          Write (nout,*)
          Flush (nout)

          Call x04caf('General',' ',m,n,u,ldu,                                 &
            'Example 1: left singular vectors, by column',ifail)

        Else

!         Copy A to VT and U

          Call f06qff('Upper',m,n,a,lda,vt,ldvt)
          Call f06qff('Lower',m,m,a,lda,u,ldu)

!         Form P**T explicitly, storing the result in VT
!         The NAG name equivalent of dorgbr is f08kff
          Call dorgbr('P',m,n,m,vt,ldvt,taup,work,lwork,info)

!         Form Q explicitly, storing the result in U
!         The NAG name equivalent of dorgbr is f08kff
          Call dorgbr('Q',m,m,n,u,ldu,tauq,work,lwork,info)

!         Compute the SVD of A
!         The NAG name equivalent of dbdsqr is f08mef
          Call dbdsqr('Lower',m,n,m,0,d,e,vt,ldvt,u,ldu,c,ldc,work,info)

!         Print singular values, left & right singular vectors

          Write (nout,*)
          Write (nout,*) 'Example 2: singular values'
          Write (nout,99999) d(1:m)
          Write (nout,*)
          Flush (nout)

          ifail = 0
          Call x04caf('General',' ',m,n,vt,ldvt,                               &
            'Example 2: right singular vectors, by row',ifail)

          Write (nout,*)
          Flush (nout)

          Call x04caf('General',' ',m,m,u,ldu,                                 &
            'Example 2: left singular vectors, by column',ifail)

        End If
        Deallocate (a,c,d,e,taup,tauq,u,vt,work)
      End Do

99999 Format (3X,(8F8.4))
    End Program f08kffe


f08kgfe.f90

    Program f08kgfe

!     F08KGF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: dgebrd, dgelqf, dgeqrf, dorglq, dorgqr, dormbr,   &
                             f06qff, f06qhf, nag_wp, x04caf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Real (Kind=nag_wp), Parameter    :: zero = 0.0E0_nag_wp
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Integer                          :: i, ic, ifail, info, lda, ldpt, ldu,  &
                                          lwork, m, n
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: a(:,:), d(:), e(:), pt(:,:), tau(:), &
                                          taup(:), tauq(:), u(:,:), work(:)
!     .. Executable Statements ..
      Write (nout,*) 'F08KGF Example Program Results'
!     Skip heading in data file
      Read (nin,*)
      Do ic = 1, 2
        Read (nin,*) m, n
        lda = m
        ldpt = n
        ldu = m
        lwork = 64*(m+n)
        Allocate (a(lda,n),d(n),e(n-1),pt(ldpt,n),tau(n),taup(n),tauq(n),      &
          u(ldu,n),work(lwork))

!       Read A from data file

        Read (nin,*)(a(i,1:n),i=1,m)

        If (m>=n) Then

!         Compute the QR factorization of A
!         The NAG name equivalent of dgeqrf is f08aef
          Call dgeqrf(m,n,a,lda,tau,work,lwork,info)

!         Copy A to U
          Call f06qff('Lower',m,n,a,lda,u,ldu)

!         Form Q explicitly, storing the result in U
!         The NAG name equivalent of dorgqr is f08aff
          Call dorgqr(m,n,n,u,ldu,tau,work,lwork,info)

!         Copy R to PT (used as workspace)
          Call f06qff('Upper',n,n,a,lda,pt,ldpt)

!         Set the strictly lower triangular part of R to zero
          Call f06qhf('Lower',n-1,n-1,zero,zero,pt(2,1),ldpt)

!         Bidiagonalize R
!         The NAG name equivalent of dgebrd is f08kef
          Call dgebrd(n,n,pt,ldpt,d,e,tauq,taup,work,lwork,info)

!         Update Q, storing the result in U
!         The NAG name equivalent of dormbr is f08kgf
          Call dormbr('Q','Right','No transpose',m,n,n,pt,ldpt,tauq,u,ldu,     &
            work,lwork,info)

!         Print bidiagonal form and matrix Q

          Write (nout,*)
          Write (nout,*) 'Example 1: bidiagonal matrix B'
          Write (nout,*) 'Diagonal'
          Write (nout,99999) d(1:n)
          Write (nout,*) 'Superdiagonal'
          Write (nout,99999) e(1:n-1)
          Write (nout,*)
          Flush (nout)

!         ifail: behaviour on error exit
!                =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
          ifail = 0
          Call x04caf('General',' ',m,n,u,ldu,'Example 1: matrix Q',ifail)

        Else

!         Compute the LQ factorization of A
!         The NAG name equivalent of dgelqf is f08ahf
          Call dgelqf(m,n,a,lda,tau,work,lwork,info)

!         Copy A to PT
          Call f06qff('Upper',m,n,a,lda,pt,ldpt)

!         Form Q explicitly, storing the result in PT
!         The NAG name equivalent of dorglq is f08ajf
          Call dorglq(n,n,m,pt,ldpt,tau,work,lwork,info)

!         Copy L to U (used as workspace)
          Call f06qff('Lower',m,m,a,lda,u,ldu)

!         Set the strictly upper triangular part of L to zero
          Call f06qhf('Upper',m-1,m-1,zero,zero,u(1,2),ldu)

!         Bidiagonalize L
!         The NAG name equivalent of dgebrd is f08kef
          Call dgebrd(m,m,u,ldu,d,e,tauq,taup,work,lwork,info)

!         Update P**T, storing the result in PT
!         The NAG name equivalent of dormbr is f08kgf
          Call dormbr('P','Left','Transpose',m,n,m,u,ldu,taup,pt,ldpt,work,    &
            lwork,info)

!         Print bidiagonal form and matrix P**T

          Write (nout,*)
          Write (nout,*) 'Example 2: bidiagonal matrix B'
          Write (nout,*) 'Diagonal'
          Write (nout,99999) d(1:m)
          Write (nout,*) 'Superdiagonal'
          Write (nout,99999) e(1:m-1)
          Write (nout,*)
          Flush (nout)

          ifail = 0
          Call x04caf('General',' ',m,n,pt,ldpt,'Example 2: matrix P**T',      &
            ifail)

        End If
        Deallocate (a,d,e,pt,tau,taup,tauq,u,work)
      End Do

99999 Format (3X,(8F8.4))
    End Program f08kgfe


f08khfe.f90

    Program f08khfe

!     F08KHF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: ddisna, dgejsv, nag_wp, x02ajf, x04caf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nb = 64, nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: eps, serrbd
      Integer                          :: i, ifail, info, j, lda, ldu, ldv,    &
                                          lwork, m, n
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: a(:,:), rcondu(:), rcondv(:), s(:),  &
                                          u(:,:), v(:,:), work(:)
      Integer, Allocatable             :: iwork(:)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: abs, max
!     .. Executable Statements ..
      Write (nout,*) 'F08KHF Example Program Results'
      Write (nout,*)
      Flush (nout)
!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) m, n
      lda = m
      ldu = m
      ldv = n
      lwork = max(3*n+n*n+m,3*n+n*n+n*nb,7)
      Allocate (a(lda,n),rcondu(m),rcondv(m),s(n),u(ldu,n),v(ldv,n),           &
        work(lwork),iwork(m+3*n))

!     Read the m by n matrix A from data file
      Read (nin,*)((a(i,j),j=1,n),i=1,m)

!     Compute the singular values and left and right singular vectors
!     of A (A = U*S*V^T, m.ge.n)
!     The NAG name equivalent of dgejsv is f08khf
      Call dgejsv('E','U','V','R','N','N',m,n,a,lda,s,u,ldu,v,ldv,work,lwork,  &
        iwork,info)

      If (info==0) Then

!       Compute the approximate error bound for the computed singular values
!       using the 2-norm, s(1) = norm(A), and machine precision, eps.
        eps = x02ajf()
        serrbd = eps*s(1)

!       Print solution
        If (abs(work(1)-work(2))<2.0_nag_wp*eps) Then
!         No scaling required
          Write (nout,'(1X,A)') 'Singular values'
          Write (nout,99999)(s(j),j=1,n)
        Else
          Write (nout,'(/1X,A)') 'Scaled singular values'
          Write (nout,99999)(s(j),j=1,n)
          Write (nout,'(/1X,A)') 'For true singular values, multiply by a/b,'
          Write (nout,99996) ' where a = ', work(1), ' and b = ', work(2)
        End If

!       ifail: behaviour on error exit
!              =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
        Write (nout,*)
        Flush (nout)
        ifail = 0
        Call x04caf('General',' ',m,n,u,ldu,'Left singular vectors',ifail)

        Write (nout,*)
        Flush (nout)
        ifail = 0
        Call x04caf('General',' ',n,n,v,ldv,'Right singular vectors',ifail)

!       Call DDISNA (F08FLF) to estimate reciprocal condition numbers for
!       the singular vectors.

        Call ddisna('Left',m,n,s,rcondu,info)
        Call ddisna('Right',m,n,s,rcondv,info)

!       Print the approximate error bounds for the singular values
!       and vectors.
        Write (nout,*)
        Write (nout,'(/1X,A)')                                                 &
          'Estimate of the condition number of column equilibrated A'
        Write (nout,99998) work(3)
        Write (nout,'(/1X,A)') 'Error estimate for the singular values'
        Write (nout,99998) serrbd
        Write (nout,'(/1X,A)') 'Error estimates for left singular vectors'
        Write (nout,99998)(serrbd/rcondu(i),i=1,n)
        Write (nout,'(/1X,A)') 'Error estimates for right singular vectors'
        Write (nout,99998)(serrbd/rcondv(i),i=1,n)
      Else
        Write (nout,99997) 'Failure in DGEJSV. INFO =', info
      End If

99999 Format (3X,8F8.4)
99998 Format (4X,1P,6E11.1)
99997 Format (1X,A,I4)
99996 Format (1X,2(A,1P,E13.5))
    End Program f08khfe


f08kjfe.f90

    Program f08kjfe

!     F08KJF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: ddisna, dgesvj, nag_wp, x02ajf, x04caf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: eps, serrbd
      Integer                          :: i, ifail, info, j, lda, ldv, lwork,  &
                                          m, n
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: a(:,:), rcondu(:), rcondv(:), s(:),  &
                                          v(:,:), work(:)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: abs
!     .. Executable Statements ..
      Write (nout,*) 'F08KJF Example Program Results'
      Write (nout,*)
      Flush (nout)
!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) m, n
      lda = m
      ldv = n
      lwork = n + m
      Allocate (a(lda,n),rcondu(m),rcondv(m),s(n),v(ldv,n),work(lwork))

!     Read the m by n matrix A from data file

      Read (nin,*)((a(i,j),j=1,n),i=1,m)

!     Compute the singular values and left and right singular vectors
!     of A (A = U*S*V, m.ge.n)

!     The NAG name equivalent of dgesvj is f08kjf
      Call dgesvj('G','U','V',m,n,a,lda,s,0,v,ldv,work,lwork,info)

      If (info==0) Then

!       Compute the approximate error bound for the computed singular values
!       using the 2-norm, s(1) = norm(A), and machine precision, eps.
        eps = x02ajf()
        serrbd = eps*s(1)

!       Print solution
        Write (nout,*) 'Singular values'
        Write (nout,99999)(s(j),j=1,n)

        If (abs(work(1)-1.0_nag_wp)>eps) Then
          Write (nout,99996) 'Values need scaling by factor = ', work(1)
        End If
        Flush (nout)

!       ifail: behaviour on error exit
!              =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
        ifail = 0
        Call x04caf('General',' ',m,n,a,lda,'Left singular vectors',ifail)

        Write (nout,*)
        Flush (nout)

        ifail = 0
        Call x04caf('General',' ',n,n,v,ldv,'Right singular vectors',ifail)

!       Call DDISNA (F08FLF) to estimate reciprocal condition
!       numbers for the singular vectors
        Call ddisna('Left',m,n,s,rcondu,info)
        Call ddisna('Right',m,n,s,rcondv,info)

!       Print the approximate error bounds for the singular values
!       and vectors
        Write (nout,'(/1X,A)') 'Error estimate for the singular values'
        Write (nout,99998) serrbd
        Write (nout,'(/1X,A)') 'Error estimates for left singular vectors'
        Write (nout,99998)(serrbd/rcondu(i),i=1,n)
        Write (nout,'(/1X,A)') 'Error estimates for right singular vectors'
        Write (nout,99998)(serrbd/rcondv(i),i=1,n)
      Else
        Write (nout,99997) 'Failure in DGESVJ. INFO =', info
      End If

99999 Format (3X,(8F8.4))
99998 Format (4X,1P,6E11.1)
99997 Format (1X,A,I4)
99996 Format (/,1X,A,1P,E13.5)
    End Program f08kjfe


f08kmfe.f90

    Program f08kmfe

!     F08KMF Example Program Text

!     Mark 26.1 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: dgesvdx, nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: vl, vu
      Integer                          :: i, il, info, iu, lda, ldu, ldvt,     &
                                          lwork, m, n, ns
      Character (1)                    :: range
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: a(:,:), a_copy(:,:), b(:), s(:),     &
                                          u(:,:), vt(:,:), work(:)
      Real (Kind=nag_wp)               :: dummy(1,1)
      Integer, Allocatable             :: iwork(:)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: nint
!     .. Executable Statements ..
      Write (nout,*) 'F08KMF Example Program Results'
      Write (nout,*)
!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) m, n
      lda = m
      ldu = m
      ldvt = n
      Allocate (a(lda,n),a_copy(m,n),s(n),vt(ldvt,n),u(ldu,m),b(m),            &
        iwork(12*m))

!     Read the m by n matrix A from data file
      Read (nin,*)(a(i,1:n),i=1,m)

!     Read the right hand side of the linear system
      Read (nin,*) b(1:m)

!     Read range for selected singular values
      Read (nin,*) range

      If (range=='I' .Or. range=='i') Then
        Read (nin,*) il, iu
      Else If (range=='V' .Or. range=='v') Then
        Read (nin,*) vl, vu
      End If

      a_copy(1:m,1:n) = a(1:m,1:n)

!     Use routine workspace query to get optimal workspace.
      lwork = -1
!     The NAG name equivalent of dgesvd is f08kmf
      Call dgesvdx('V','V',range,m,n,a,lda,vl,vu,il,iu,ns,s,u,ldu,vt,ldvt,     &
        dummy,lwork,iwork,info)

!     Make sure that there is enough workspace for block size nb.
      lwork = nint(dummy(1,1))
      Allocate (work(lwork))

!     Compute the singular values and left and right singular vectors
!     of A.

!     The NAG name equivalent of dgesvd is f08kmf
      Call dgesvdx('V','V',range,m,n,a,lda,vl,vu,il,iu,ns,s,u,ldu,vt,ldvt,     &
        work,lwork,iwork,info)

      If (info/=0) Then
        Write (nout,99999) 'Failure in DGESVDX. INFO =', info
99999   Format (1X,A,I4)
        Go To 100
      End If

!     Print the selected singular values of A

      Write (nout,*) 'Singular values of A:'
      Write (nout,99998) s(1:ns)
99998 Format (1X,4(3X,F11.4))

      Call compute_error_bounds(m,ns,s)

      If (m>n .And. ns==n) Then
!       Compute V*Inv(S)*U^T * b to get least squares solution.
        Call compute_least_squares(m,n,a_copy,m,u,ldu,vt,ldvt,s,b)
      End If

100   Continue

    Contains
      Subroutine compute_least_squares(m,n,a,lda,u,ldu,vt,ldvt,s,b)

!       .. Use Statements ..
        Use nag_library, Only: dgemv, dnrm2
!       .. Implicit None Statement ..
        Implicit None
!       .. Scalar Arguments ..
        Integer, Intent (In)           :: lda, ldu, ldvt, m, n
!       .. Array Arguments ..
        Real (Kind=nag_wp), Intent (In) :: a(lda,n), s(n), u(ldu,m),           &
                                          vt(ldvt,n)
        Real (Kind=nag_wp), Intent (Inout) :: b(m)
!       .. Local Scalars ..
        Real (Kind=nag_wp)             :: alpha, beta, norm
!       .. Local Arrays ..
        Real (Kind=nag_wp), Allocatable :: x(:), y(:)
!       .. Intrinsic Procedures ..
        Intrinsic                      :: allocated
!       .. Executable Statements ..
        Allocate (x(n),y(n))

!       Compute V*Inv(S)*U^T * b to get least squares solution.

!       y = U^T b
!       The NAG name equivalent of dgemv is f06paf
        alpha = 1._nag_wp
        beta = 0._nag_wp
        Call dgemv('T',m,n,alpha,u,ldu,b,1,beta,y,1)

        y(1:n) = y(1:n)/s(1:n)

!       x = V y
        Call dgemv('T',n,n,alpha,vt,ldvt,y,1,beta,x,1)

        Write (nout,*)
        Write (nout,*) 'Least squares solution:'
        Write (nout,99999) x(1:n)

!       Find norm of residual ||b-Ax||.
        alpha = -1._nag_wp
        beta = 1._nag_wp
        Call dgemv('N',m,n,alpha,a,lda,x,1,beta,b,1)

        norm = dnrm2(m,b,1)

        Write (nout,*)
        Write (nout,*) 'Norm of Residual:'
        Write (nout,99999) norm

        If (allocated(x)) Then
          Deallocate (x)
        End If
        If (allocated(y)) Then
          Deallocate (y)
        End If

99999   Format (1X,4(3X,F11.4))

      End Subroutine compute_least_squares

      Subroutine compute_error_bounds(m,n,s)

!       Error estimates for singular values and vectors is computed
!       and printed here.

!       .. Use Statements ..
        Use nag_library, Only: ddisna, nag_wp, x02ajf
!       .. Implicit None Statement ..
        Implicit None
!       .. Scalar Arguments ..
        Integer, Intent (In)           :: m, n
!       .. Array Arguments ..
        Real (Kind=nag_wp), Intent (In) :: s(n)
!       .. Local Scalars ..
        Real (Kind=nag_wp)             :: eps, serrbd
        Integer                        :: i, info
!       .. Local Arrays ..
        Real (Kind=nag_wp), Allocatable :: rcondu(:), rcondv(:), uerrbd(:),    &
                                          verrbd(:)
!       .. Executable Statements ..
        Allocate (rcondu(n),rcondv(n),uerrbd(n),verrbd(n))

!       Get the machine precision, EPS and compute the approximate
!       error bound for the computed singular values.  Note that for
!       the 2-norm, S(1) = norm(A)

        eps = x02ajf()
        serrbd = eps*s(1)

!       Call DDISNA (F08FLF) to estimate reciprocal condition
!       numbers for the singular vectors

        Call ddisna('Left',m,n,s,rcondu,info)
        Call ddisna('Right',m,n,s,rcondv,info)

!       Compute the error estimates for the singular vectors

        Do i = 1, n
          uerrbd(i) = serrbd/rcondu(i)
          verrbd(i) = serrbd/rcondv(i)
        End Do

!       Print the approximate error bounds for the singular values
!       and vectors

        Write (nout,*)
        Write (nout,*) 'Estimates given as multiples of machine precision'
        Write (nout,*) 'Error estimate for the singular values'
        Write (nout,99999) nint(serrbd/x02ajf())
        Write (nout,*)
        Write (nout,*) 'Error estimates for the left singular vectors'
        Write (nout,99999) nint(uerrbd(1:n)/x02ajf())
        Write (nout,*)
        Write (nout,*) 'Error estimates for the right singular vectors'
        Write (nout,99999) nint(verrbd(1:n)/x02ajf())

99999   Format (4X,6I11)

      End Subroutine compute_error_bounds

    End Program f08kmfe


f08knfe.f90

    Program f08knfe

!     F08KNF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: dznrm2, nag_wp, zgelss
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nb = 64, nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: rcond, rnorm
      Integer                          :: i, info, lda, lwork, m, n, rank
!     .. Local Arrays ..
      Complex (Kind=nag_wp), Allocatable :: a(:,:), b(:), work(:)
      Real (Kind=nag_wp), Allocatable  :: rwork(:), s(:)
!     .. Executable Statements ..
      Write (nout,*) 'F08KNF Example Program Results'
      Write (nout,*)
!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) m, n
      lda = m
      lwork = 2*n + nb*(m+n)
      Allocate (a(lda,n),b(m),work(lwork),rwork(5*n),s(n))

!     Read A and B from data file

      Read (nin,*)(a(i,1:n),i=1,m)
      Read (nin,*) b(1:m)

!     Choose RCOND to reflect the relative accuracy of the input data

      rcond = 0.01E0_nag_wp

!     Solve the least squares problem min( norm2(b - Ax) ) for the x
!     of minimum norm.

!     The NAG name equivalent of zgelss is f08knf
      Call zgelss(m,n,1,a,lda,b,m,s,rcond,rank,work,lwork,rwork,info)

      If (info==0) Then

!       Print solution

        Write (nout,*) 'Least squares solution'
        Write (nout,99999) b(1:n)

!       Print the effective rank of A

        Write (nout,*)
        Write (nout,*) 'Tolerance used to estimate the rank of A'
        Write (nout,99998) rcond
        Write (nout,*) 'Estimated rank of A'
        Write (nout,99997) rank

!       Print singular values of A

        Write (nout,*)
        Write (nout,*) 'Singular values of A'
        Write (nout,99996) s(1:n)

!       Compute and print estimate of the square root of the
!       residual sum of squares

        If (rank==n) Then
!         The NAG name equivalent of dznrm2 is f06jjf
          rnorm = dznrm2(m-n,b(n+1),1)
          Write (nout,*)
          Write (nout,*) 'Square root of the residual sum of squares'
          Write (nout,99998) rnorm
        End If
      Else
        Write (nout,*) 'The SVD algorithm failed to converge'
      End If

99999 Format (4(' (',F7.4,',',F7.4,')',:))
99998 Format (3X,1P,E11.2)
99997 Format (1X,I6)
99996 Format (1X,7F11.4)
    End Program f08knfe


f08kpfe.f90

    Program f08kpfe

!     F08KPF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: nag_wp, zgesvd
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nb = 64, nin = 5, nout = 6,          &
                                          prerr = 0
!     .. Local Scalars ..
      Integer                          :: i, info, lda, ldu, ldvt, lwork, m, n
!     .. Local Arrays ..
      Complex (Kind=nag_wp), Allocatable :: a(:,:), a_copy(:,:), b(:), u(:,:), &
                                          vt(:,:), work(:)
      Complex (Kind=nag_wp)            :: dummy(1,1)
      Real (Kind=nag_wp), Allocatable  :: rwork(:), s(:)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: max, min, nint, real
!     .. Executable Statements ..
      Write (nout,*) 'F08KPF Example Program Results'
      Write (nout,*)
!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) m, n
      lda = m
      ldu = m
      ldvt = n
      Allocate (a(lda,n),a_copy(m,n),s(n),u(ldu,m),vt(ldvt,n),b(m),rwork(5*n))

!     Read the m by n matrix A from data file
      Read (nin,*)(a(i,1:n),i=1,m)

!     Read the right hand side of the linear system
      Read (nin,*) b(1:m)

      a_copy(1:m,1:n) = a(1:m,1:n)

!     Use routine workspace query to get optimal workspace.
      lwork = -1
!     The NAG name equivalent of dgesvd is f08kpf
      Call zgesvd('A','S',m,n,a,lda,s,u,ldu,vt,ldvt,dummy,lwork,rwork,info)

!     Make sure that there is enough workspace for block size nb.
      lwork = max(m+3*n+nb*(m+n),nint(real(dummy(1,1))))
      Allocate (work(lwork))

!     Compute the singular values and left and right singular vectors
!     of A.

!     The NAG name equivalent of dgesvd is f08kpf
      Call zgesvd('A','S',m,n,a,lda,s,u,ldu,vt,ldvt,work,lwork,rwork,info)

      If (info/=0) Then
        Write (nout,99999) 'Failure in F08KPF/ZGESVD. INFO =', info
99999   Format (1X,A,I4)
        Go To 100
      End If

!     Print the significant singular values of A

      Write (nout,*) 'Singular values of A:'
      Write (nout,99998) s(1:min(m,n))
99998 Format (1X,4(3X,F11.4))

      If (prerr>0) Then
        Call compute_error_bounds(m,n,s)
      End If

      If (m>n) Then
!       Compute V*Inv(S)*U^T * b to get least squares solution.
        Call compute_least_squares(m,n,a_copy,m,u,ldu,vt,ldvt,s,b)
      End If

100   Continue

    Contains
      Subroutine compute_least_squares(m,n,a,lda,u,ldu,vt,ldvt,s,b)

!       .. Use Statements ..
        Use nag_library, Only: dznrm2, zgemv
!       .. Implicit None Statement ..
        Implicit None
!       .. Scalar Arguments ..
        Integer, Intent (In)           :: lda, ldu, ldvt, m, n
!       .. Array Arguments ..
        Complex (Kind=nag_wp), Intent (In) :: a(lda,n), u(ldu,m), vt(ldvt,n)
        Complex (Kind=nag_wp), Intent (Inout) :: b(m)
        Real (Kind=nag_wp), Intent (In) :: s(n)
!       .. Local Scalars ..
        Complex (Kind=nag_wp)          :: alpha, beta
        Real (Kind=nag_wp)             :: norm
!       .. Local Arrays ..
        Complex (Kind=nag_wp), Allocatable :: x(:), y(:)
!       .. Intrinsic Procedures ..
        Intrinsic                      :: allocated, cmplx
!       .. Executable Statements ..
        Allocate (x(n),y(n))

!       Compute V*Inv(S)*U^H * b to get least squares solution.

!       y = U^T b
!       The NAG name equivalent of zgemv is f06saf
        alpha = cmplx(1.0_nag_wp,0.0_nag_wp,kind=nag_wp)
        beta = cmplx(0.0_nag_wp,0.0_nag_wp,kind=nag_wp)
        Call zgemv('C',m,n,alpha,u,ldu,b,1,beta,y,1)

        y(1:n) = y(1:n)/s(1:n)

!       x = V y
        Call zgemv('C',n,n,alpha,vt,ldvt,y,1,beta,x,1)

        Write (nout,*)
        Write (nout,*) 'Least squares solution:'
        Write (nout,99999) x(1:n)

!       Find norm of residual ||b-Ax||.
        alpha = cmplx(-1.0_nag_wp,0.0_nag_wp,kind=nag_wp)
        beta = cmplx(1._nag_wp,0.0_nag_wp,kind=nag_wp)
        Call zgemv('N',m,n,alpha,a,lda,x,1,beta,b,1)

        norm = dznrm2(m,b,1)

        Write (nout,*)
        Write (nout,*) 'Norm of Residual:'
        Write (nout,99998) norm

        If (allocated(x)) Then
          Deallocate (x)
        End If
        If (allocated(y)) Then
          Deallocate (y)
        End If

99999   Format (4X,'(',F8.4,',',F8.4,')')
99998   Format (4X,F11.4)

      End Subroutine compute_least_squares

      Subroutine compute_error_bounds(m,n,s)

!       Error estimates for singular values and vectors is computed
!       and printed here.

!       .. Use Statements ..
        Use nag_library, Only: ddisna, nag_wp, x02ajf
!       .. Implicit None Statement ..
        Implicit None
!       .. Scalar Arguments ..
        Integer, Intent (In)           :: m, n
!       .. Array Arguments ..
        Real (Kind=nag_wp), Intent (In) :: s(n)
!       .. Local Scalars ..
        Real (Kind=nag_wp)             :: eps, serrbd
        Integer                        :: i, info
!       .. Local Arrays ..
        Real (Kind=nag_wp), Allocatable :: rcondu(:), rcondv(:), uerrbd(:),    &
                                          verrbd(:)
!       .. Executable Statements ..
        Allocate (rcondu(n),rcondv(n),uerrbd(n),verrbd(n))

!       Get the machine precision, EPS and compute the approximate
!       error bound for the computed singular values.  Note that for
!       the 2-norm, S(1) = norm(A)

        eps = x02ajf()
        serrbd = eps*s(1)

!       Call DDISNA (F08FLF) to estimate reciprocal condition
!       numbers for the singular vectors

        Call ddisna('Left',m,n,s,rcondu,info)
        Call ddisna('Right',m,n,s,rcondv,info)

!       Compute the error estimates for the singular vectors

        Do i = 1, n
          uerrbd(i) = serrbd/rcondu(i)
          verrbd(i) = serrbd/rcondv(i)
        End Do

!       Print the approximate error bounds for the singular values
!       and vectors

        Write (nout,*)
        Write (nout,*) 'Error estimate for the singular values'
        Write (nout,99999) serrbd
        Write (nout,*)
        Write (nout,*) 'Error estimates for the left singular vectors'
        Write (nout,99999) uerrbd(1:n)
        Write (nout,*)
        Write (nout,*) 'Error estimates for the right singular vectors'
        Write (nout,99999) verrbd(1:n)

99999   Format (4X,1P,6E11.1)

      End Subroutine compute_error_bounds

    End Program f08kpfe


f08kqfe.f90

    Program f08kqfe

!     F08KQF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: nag_wp, zgelsd
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: rcond
      Integer                          :: i, info, lda, liwork, lrwork, lwork, &
                                          m, n, rank
!     .. Local Arrays ..
      Complex (Kind=nag_wp), Allocatable :: a(:,:), b(:), work(:)
      Complex (Kind=nag_wp)            :: lw(1)
      Real (Kind=nag_wp)               :: lrw(1)
      Real (Kind=nag_wp), Allocatable  :: rwork(:), s(:)
      Integer, Allocatable             :: iwork(:)
      Integer                          :: liw(1)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: nint, real
!     .. Executable Statements ..
      Write (nout,*) 'F08KQF Example Program Results'
      Write (nout,*)
!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) m, n
      lda = m
      Allocate (a(lda,n),b(n),s(m))

!     Read A and B from data file

      Read (nin,*)(a(i,1:n),i=1,m)
      Read (nin,*) b(1:m)

!     Choose RCOND to reflect the relative accuracy of the input
!     data

      rcond = 0.01E0_nag_wp

!     Call f08kqf/zgelsd in workspace query mode.
      lwork = -1
      Call zgelsd(m,n,1,a,lda,b,n,s,rcond,rank,lw,lwork,lrw,liw,info)
      lwork = nint(real(lw(1)))
      lrwork = nint(lrw(1))
      liwork = liw(1)
      Allocate (work(lwork),rwork(lrwork),iwork(liwork))

!     Solve the least squares problem min( norm2(b - Ax) ) for the
!     x of minimum norm.

!     The NAG name equivalent of zgelsd is f08kqf
      Call zgelsd(m,n,1,a,lda,b,n,s,rcond,rank,work,lwork,rwork,iwork,info)

      If (info==0) Then

!       Print solution

        Write (nout,*) 'Least squares solution'
        Write (nout,99999) b(1:n)

!       Print the effective rank of A

        Write (nout,*)
        Write (nout,*) 'Tolerance used to estimate the rank of A'
        Write (nout,99998) rcond
        Write (nout,*) 'Estimated rank of A'
        Write (nout,99997) rank

!       Print singular values of A

        Write (nout,*)
        Write (nout,*) 'Singular values of A'
        Write (nout,99996) s(1:m)
      Else If (info>0) Then
        Write (nout,*) 'The SVD algorithm failed to converge'
      End If

99999 Format (4(' (',F7.4,',',F7.4,')',:))
99998 Format (3X,1P,E11.2)
99997 Format (1X,I6)
99996 Format (1X,7F11.4)
    End Program f08kqfe


f08krfe.f90

    Program f08krfe

!     F08KRF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: nag_wp, zgesdd
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nb = 64, nin = 5, nout = 6,          &
                                          prerr = 0
!     .. Local Scalars ..
      Integer                          :: i, info, lda, ldu, ldvt, lwork, m, n
!     .. Local Arrays ..
      Complex (Kind=nag_wp), Allocatable :: a(:,:), a_copy(:,:), b(:), u(:,:), &
                                          vt(:,:), work(:)
      Complex (Kind=nag_wp)            :: dummy(1,1)
      Real (Kind=nag_wp), Allocatable  :: rwork(:), s(:)
      Integer, Allocatable             :: iwork(:)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: max, min, nint, real
!     .. Executable Statements ..
      Write (nout,*) 'F08KRF Example Program Results'
      Write (nout,*)
!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) m, n
      lda = m
      ldu = m
      ldvt = n
      Allocate (a(lda,n),a_copy(m,n),s(m),u(ldu,m),vt(ldvt,n),b(m),rwork((5*m+ &
        7)*n),iwork(8*m))

!     Read the m by n matrix A from data file
      Read (nin,*)(a(i,1:n),i=1,m)

!     Read the right hand side of the linear system
      Read (nin,*) b(1:m)

      a_copy(1:m,1:n) = a(1:m,1:n)

!     Use routine workspace query to get optimal workspace.
      lwork = -1
!     The NAG name equivalent of dgesdd is f08krf
      Call zgesdd('A',m,n,a,lda,s,u,ldu,vt,ldvt,dummy,lwork,rwork,iwork,info)

!     Make sure that there is enough workspace for block size nb.
      lwork = max((2*m+2)*m+2*n+nb*(m+n),nint(real(dummy(1,1))))
      Allocate (work(lwork))

!     Compute the singular values and left and right singular vectors
!     of A.

!     The NAG name equivalent of dgesdd is f08krf
      Call zgesdd('A',m,n,a,lda,s,u,ldu,vt,ldvt,work,lwork,rwork,iwork,info)

      If (info/=0) Then
        Write (nout,99999) 'Failure in F08KRF/ZGESDD. INFO =', info
99999   Format (1X,A,I4)
        Go To 100
      End If

!     Print the significant singular values of A

      Write (nout,*) 'Singular values of A:'
      Write (nout,99998) s(1:min(m,n))
99998 Format (1X,4(3X,F11.4))

      If (prerr>0) Then
        Call compute_error_bounds(m,n,s)
      End If

      If (m<n) Then
!       Compute V*Inv(S)*U^T * b to get minimum norm solution.
        Call compute_minimum_norm(m,n,a_copy,m,u,ldu,vt,ldvt,s,b)
      End If

100   Continue

    Contains
      Subroutine compute_minimum_norm(m,n,a,lda,u,ldu,vt,ldvt,s,b)

!       .. Use Statements ..
        Use nag_library, Only: dznrm2, zgemv
!       .. Implicit None Statement ..
        Implicit None
!       .. Scalar Arguments ..
        Integer, Intent (In)           :: lda, ldu, ldvt, m, n
!       .. Array Arguments ..
        Complex (Kind=nag_wp), Intent (In) :: a(lda,n), u(ldu,m), vt(ldvt,n)
        Complex (Kind=nag_wp), Intent (Inout) :: b(m)
        Real (Kind=nag_wp), Intent (In) :: s(m)
!       .. Local Scalars ..
        Complex (Kind=nag_wp)          :: alpha, beta
        Real (Kind=nag_wp)             :: norm
!       .. Local Arrays ..
        Complex (Kind=nag_wp), Allocatable :: x(:), y(:)
!       .. Intrinsic Procedures ..
        Intrinsic                      :: allocated, cmplx
!       .. Executable Statements ..
        Allocate (x(n),y(m))

!       Compute V*Inv(S)*U^H * b to get least squares solution.

!       y = U^H b
!       The NAG name equivalent of zgemv is f06saf
        alpha = cmplx(1.0_nag_wp,0.0_nag_wp,kind=nag_wp)
        beta = cmplx(0.0_nag_wp,0.0_nag_wp,kind=nag_wp)
        Call zgemv('C',m,m,alpha,u,ldu,b,1,beta,y,1)

        y(1:m) = y(1:m)/s(1:m)

!       x = V y
        Call zgemv('C',m,n,alpha,vt,ldvt,y,1,beta,x,1)

        Write (nout,*)
        Write (nout,*) 'Minimum norm solution:'
        Write (nout,99999) x(1:n)

        norm = dznrm2(n,x,1)

        Write (nout,*)
        Write (nout,*) 'Norm of Solution:'
        Write (nout,99998) norm

!       Find norm of residual ||b-Ax||, should be zero.
        alpha = cmplx(-1.0_nag_wp,0.0_nag_wp,kind=nag_wp)
        beta = cmplx(1._nag_wp,0.0_nag_wp,kind=nag_wp)
        Call zgemv('N',m,n,alpha,a,lda,x,1,beta,b,1)

        norm = dznrm2(m,b,1)

        Write (nout,*)
        Write (nout,*) 'Norm of Residual:'
        Write (nout,99998) norm

        If (allocated(x)) Then
          Deallocate (x)
        End If
        If (allocated(y)) Then
          Deallocate (y)
        End If

99999   Format (4X,'(',F8.4,',',F8.4,')')
99998   Format (4X,F11.4)

      End Subroutine compute_minimum_norm

      Subroutine compute_error_bounds(m,n,s)

!       Error estimates for singular values and vectors is computed
!       and printed here.

!       .. Use Statements ..
        Use nag_library, Only: ddisna, nag_wp, x02ajf
!       .. Implicit None Statement ..
        Implicit None
!       .. Scalar Arguments ..
        Integer, Intent (In)           :: m, n
!       .. Array Arguments ..
        Real (Kind=nag_wp), Intent (In) :: s(m)
!       .. Local Scalars ..
        Real (Kind=nag_wp)             :: eps, serrbd
        Integer                        :: i, info
!       .. Local Arrays ..
        Real (Kind=nag_wp), Allocatable :: rcondu(:), rcondv(:), uerrbd(:),    &
                                          verrbd(:)
!       .. Executable Statements ..
        Allocate (rcondu(n),rcondv(n),uerrbd(n),verrbd(n))

!       Get the machine precision, EPS and compute the approximate
!       error bound for the computed singular values.  Note that for
!       the 2-norm, S(1) = norm(A)

        eps = x02ajf()
        serrbd = eps*s(1)

!       Call DDISNA (F08FLF) to estimate reciprocal condition
!       numbers for the singular vectors

        Call ddisna('Left',m,n,s,rcondu,info)
        Call ddisna('Right',m,n,s,rcondv,info)

!       Compute the error estimates for the singular vectors

        Do i = 1, n
          uerrbd(i) = serrbd/rcondu(i)
          verrbd(i) = serrbd/rcondv(i)
        End Do

!       Print the approximate error bounds for the singular values
!       and vectors

        Write (nout,*)
        Write (nout,*) 'Error estimate for the singular values'
        Write (nout,99999) serrbd
        Write (nout,*)
        Write (nout,*) 'Error estimates for the left singular vectors'
        Write (nout,99999) uerrbd(1:n)
        Write (nout,*)
        Write (nout,*) 'Error estimates for the right singular vectors'
        Write (nout,99999) verrbd(1:n)

99999   Format (4X,1P,6E11.1)

      End Subroutine compute_error_bounds

    End Program f08krfe


f08ksfe.f90

    Program f08ksfe

!     F08KSF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: nag_wp, zgebrd
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Integer                          :: i, info, lda, lwork, m, n
!     .. Local Arrays ..
      Complex (Kind=nag_wp), Allocatable :: a(:,:), taup(:), tauq(:), work(:)
      Real (Kind=nag_wp), Allocatable  :: d(:), e(:)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: min
!     .. Executable Statements ..
      Write (nout,*) 'F08KSF Example Program Results'
!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) m, n
      lda = m
      lwork = 64*(m+n)
      Allocate (a(lda,n),taup(n),tauq(n),work(lwork),d(n),e(n-1))

!     Read A from data file

      Read (nin,*)(a(i,1:n),i=1,m)

!     Reduce A to bidiagonal form

!     The NAG name equivalent of zgebrd is f08ksf
      Call zgebrd(m,n,a,lda,d,e,tauq,taup,work,lwork,info)

!     Print bidiagonal form

      Write (nout,*)
      Write (nout,*) 'Diagonal'
      Write (nout,99999) d(1:min(m,n))
      If (m>=n) Then
        Write (nout,*) 'Superdiagonal'
      Else
        Write (nout,*) 'Subdiagonal'
      End If
      Write (nout,99999) e(1:min(m,n)-1)

99999 Format (1X,8F9.4)
    End Program f08ksfe


f08ktfe.f90

    Program f08ktfe

!     F08KTF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: f06tff, nag_wp, x04dbf, zbdsqr, zgebrd, zungbr
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Integer                          :: i, ic, ifail, info, lda, ldc, ldu,   &
                                          ldvt, lwork, m, n
!     .. Local Arrays ..
      Complex (Kind=nag_wp), Allocatable :: a(:,:), c(:,:), taup(:), tauq(:),  &
                                          u(:,:), vt(:,:), work(:)
      Real (Kind=nag_wp), Allocatable  :: d(:), e(:), rwork(:)
      Character (1)                    :: clabs(1), rlabs(1)
!     .. Executable Statements ..
      Write (nout,*) 'F08KTF Example Program Results'
!     Skip heading in data file
      Read (nin,*)
      Do ic = 1, 2
        Read (nin,*) m, n
        lda = m
        ldc = n
        ldu = m
        ldvt = n
        lwork = 64*(m+n)
        Allocate (a(lda,n),c(ldc,n),taup(n),tauq(n),u(ldu,n),vt(ldvt,n),       &
          work(lwork),d(n),e(n-1),rwork(4*n-4))

!       Read A from data file
        Read (nin,*)(a(i,1:n),i=1,m)

!       Reduce A to bidiagonal form
!       The NAG name equivalent of zgebrd is f08ksf
        Call zgebrd(m,n,a,lda,d,e,tauq,taup,work,lwork,info)

        If (m>=n) Then

!         Copy A to VT and U
          Call f06tff('Upper',n,n,a,lda,vt,ldvt)
          Call f06tff('Lower',m,n,a,lda,u,ldu)

!         Form P**H explicitly, storing the result in VT
!         The NAG name equivalent of zungbr is f08ktf
          Call zungbr('P',n,n,m,vt,ldvt,taup,work,lwork,info)

!         Form Q explicitly, storing the result in U
          Call zungbr('Q',m,n,n,u,ldu,tauq,work,lwork,info)

!         Compute the SVD of A
!         The NAG name equivalent of zbdsqr is f08msf
          Call zbdsqr('Upper',n,n,m,0,d,e,vt,ldvt,u,ldu,c,ldc,rwork,info)

!         Print singular values, left & right singular vectors

          Write (nout,*)
          Write (nout,*) 'Example 1: singular values'
          Write (nout,99999) d(1:n)
          Write (nout,*)
          Flush (nout)

!         ifail: behaviour on error exit
!                =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
          ifail = 0
          Call x04dbf('General',' ',n,n,vt,ldvt,'Bracketed','F7.4',            &
            'Example 1: right singular vectors, by row','Integer',rlabs,       &
            'Integer',clabs,80,0,ifail)

          Write (nout,*)
          Flush (nout)

          Call x04dbf('General',' ',m,n,u,ldu,'Bracketed','F7.4',              &
            'Example 1: left singular vectors, by column','Integer',rlabs,     &
            'Integer',clabs,80,0,ifail)

        Else

!         Copy A to VT and U
          Call f06tff('Upper',m,n,a,lda,vt,ldvt)
          Call f06tff('Lower',m,m,a,lda,u,ldu)

!         Form P**H explicitly, storing the result in VT
!         The NAG name equivalent of zungbr is f08ktf
          Call zungbr('P',m,n,m,vt,ldvt,taup,work,lwork,info)

!         Form Q explicitly, storing the result in U
          Call zungbr('Q',m,m,n,u,ldu,tauq,work,lwork,info)

!         Compute the SVD of A
!         The NAG name equivalent of zbdsqr is f08msf
          Call zbdsqr('Lower',m,n,m,0,d,e,vt,ldvt,u,ldu,c,ldc,rwork,info)

!         Print singular values, left & right singular vectors

          Write (nout,*)
          Write (nout,*) 'Example 2: singular values'
          Write (nout,99999) d(1:m)
          Write (nout,*)
          Flush (nout)

          ifail = 0
          Call x04dbf('General',' ',m,n,vt,ldvt,'Bracketed','F7.4',            &
            'Example 2: right singular vectors, by row','Integer',rlabs,       &
            'Integer',clabs,80,0,ifail)

          Write (nout,*)
          Flush (nout)

          Call x04dbf('General',' ',m,m,u,ldu,'Bracketed','F7.4',              &
            'Example 2: left singular vectors, by column','Integer',rlabs,     &
            'Integer',clabs,80,0,ifail)

        End If
        Deallocate (a,c,taup,tauq,u,vt,work,d,e,rwork)
      End Do

99999 Format (8X,4(F7.4,11X,:))
    End Program f08ktfe


f08kufe.f90

    Program f08kufe

!     F08KUF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: f06tff, f06thf, nag_wp, x04dbf, zgebrd, zgelqf,   &
                             zgeqrf, zunglq, zungqr, zunmbr
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Complex (Kind=nag_wp), Parameter :: zero = (0.0E0_nag_wp,0.0E0_nag_wp)
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Integer                          :: i, ic, ifail, info, lda, ldph, ldu,  &
                                          lwork, m, n
!     .. Local Arrays ..
      Complex (Kind=nag_wp), Allocatable :: a(:,:), ph(:,:), tau(:), taup(:),  &
                                          tauq(:), u(:,:), work(:)
      Real (Kind=nag_wp), Allocatable  :: d(:), e(:)
      Character (1)                    :: clabs(1), rlabs(1)
!     .. Executable Statements ..
      Write (nout,*) 'F08KUF Example Program Results'
!     Skip heading in data file
      Read (nin,*)
      Do ic = 1, 2
        Read (nin,*) m, n
        lda = m
        ldph = n
        ldu = m
        lwork = 64*(m+n)
        Allocate (a(lda,n),ph(ldph,n),tau(n),taup(n),tauq(n),u(ldu,n),         &
          work(lwork),d(n),e(n-1))

!       Read A from data file

        Read (nin,*)(a(i,1:n),i=1,m)

        If (m>=n) Then

!         Compute the QR factorization of A
!         The NAG name equivalent of zgeqrf is f08asf
          Call zgeqrf(m,n,a,lda,tau,work,lwork,info)

!         Copy A to U
          Call f06tff('Lower',m,n,a,lda,u,ldu)

!         Form Q explicitly, storing the result in U
!         The NAG name equivalent of zungqr is f08atf
          Call zungqr(m,n,n,u,ldu,tau,work,lwork,info)

!         Copy R to PH (used as workspace)
          Call f06tff('Upper',n,n,a,lda,ph,ldph)

!         Set the strictly lower triangular part of R to zero
          Call f06thf('Lower',n-1,n-1,zero,zero,ph(2,1),ldph)

!         Bidiagonalize R
!         The NAG name equivalent of zgebrd is f08ksf
          Call zgebrd(n,n,ph,ldph,d,e,tauq,taup,work,lwork,info)

!         Update Q, storing the result in U
!         The NAG name equivalent of zunmbr is f08kuf
          Call zunmbr('Q','Right','No transpose',m,n,n,ph,ldph,tauq,u,ldu,     &
            work,lwork,info)

!         Print bidiagonal form and matrix Q

          Write (nout,*)
          Write (nout,*) 'Example 1: bidiagonal matrix B'
          Write (nout,*) 'Diagonal'
          Write (nout,99999) d(1:n)
          Write (nout,*) 'Superdiagonal'
          Write (nout,99999) e(1:n-1)
          Write (nout,*)
          Flush (nout)

!         ifail: behaviour on error exit
!                =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
          ifail = 0
          Call x04dbf('General',' ',m,n,u,ldu,'Bracketed','F7.4',              &
            'Example 1: matrix Q','Integer',rlabs,'Integer',clabs,80,0,ifail)

        Else

!         Compute the LQ factorization of A
!         The NAG name equivalent of zgelqf is f08avf
          Call zgelqf(m,n,a,lda,tau,work,lwork,info)

!         Copy A to PH
          Call f06tff('Upper',m,n,a,lda,ph,ldph)

!         Form Q explicitly, storing the result in PH
!         The NAG name equivalent of zunglq is f08awf
          Call zunglq(n,n,m,ph,ldph,tau,work,lwork,info)

!         Copy L to U (used as workspace)
          Call f06tff('Lower',m,m,a,lda,u,ldu)

!         Set the strictly upper triangular part of L to zero
          Call f06thf('Upper',m-1,m-1,zero,zero,u(1,2),ldu)

!         Bidiagonalize L
!         The NAG name equivalent of zgebrd is f08ksf
          Call zgebrd(m,m,u,ldu,d,e,tauq,taup,work,lwork,info)

!         Update P**H, storing the result in PH
!         The NAG name equivalent of zunmbr is f08kuf
          Call zunmbr('P','Left','Conjugate transpose',m,n,m,u,ldu,taup,ph,    &
            ldph,work,lwork,info)

!         Print bidiagonal form and matrix P**H

          Write (nout,*)
          Write (nout,*) 'Example 2: bidiagonal matrix B'
          Write (nout,*) 'Diagonal'
          Write (nout,99999) d(1:m)
          Write (nout,*) 'Superdiagonal'
          Write (nout,99999) e(1:m-1)
          Write (nout,*)
          Flush (nout)

          ifail = 0
          Call x04dbf('General',' ',m,n,ph,ldph,'Bracketed','F7.4',            &
            'Example 2: matrix P**H','Integer',rlabs,'Integer',clabs,80,0,     &
            ifail)

        End If
        Deallocate (a,ph,tau,taup,tauq,u,work,d,e)
      End Do

99999 Format (3X,(8F8.4))
    End Program f08kufe


f08kvfe.f90

    Program f08kvfe

!     F08KVF Example Program Text

!     Mark 26.1 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: ddisna, nag_wp, x02ajf, x04daf, zgejsv
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: eps, serrbd
      Integer                          :: i, ifail, info, j, lda, ldu, ldv,    &
                                          lrwork, lwork, m, n
!     .. Local Arrays ..
      Complex (Kind=nag_wp), Allocatable :: a(:,:), cwork(:), u(:,:), v(:,:)
      Real (Kind=nag_wp), Allocatable  :: rcondu(:), rcondv(:), rwork(:),      &
                                          sva(:)
      Integer, Allocatable             :: iwork(:)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: abs, nint
!     .. Executable Statements ..
      Write (nout,*) 'F08KVF Example Program Results'
      Write (nout,*)
      Flush (nout)
!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) m, n
      lda = m
      ldu = m
      ldv = n
      lwork = 5*n + n*n + 1000
      lrwork = n + 2*m + 7
      Allocate (a(lda,n),rcondu(m),rcondv(m),sva(n),u(ldu,n),v(ldv,n),         &
        cwork(lwork),rwork(lrwork),iwork(m+3*n+3))

!     Read the m by n matrix A from data file
      Read (nin,*)((a(i,j),j=1,n),i=1,m)

!     Compute the singular values and left and right singular vectors
!     of A (A = U*S*V^T, m.ge.n)
!     The NAG name equivalent of zgejsv is f08kvf
      Call zgejsv('E','U','V','R','N','N',m,n,a,lda,sva,u,ldu,v,ldv,cwork,     &
        lwork,rwork,lrwork,iwork,info)

      If (info==0) Then

!       Compute the approximate error bound for the computed singular values
!       using the 2-norm, s(1) = norm(A), and machine precision, eps.
        eps = x02ajf()
        serrbd = eps*sva(1)

!       Print solution
        If (abs(rwork(1)-rwork(2))<2.0_nag_wp*eps) Then
!         No scaling required
          Write (nout,'(1X,A)') 'Singular values'
          Write (nout,99999)(sva(j),j=1,n)
        Else
          Write (nout,'(/1X,A)') 'Scaled singular values'
          Write (nout,99999)(sva(j),j=1,n)
          Write (nout,'(/1X,A)') 'For true singular values, multiply by a/b,'
          Write (nout,99995) ' where a = ', rwork(1), ' and b = ', rwork(2)
        End If

!       ifail: behaviour on error exit
!              =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
        Write (nout,*)
        Flush (nout)
        ifail = 0
        Call x04daf('General',' ',m,n,u,ldu,'Left singular vectors',ifail)

        Write (nout,*)
        Flush (nout)
        ifail = 0
        Call x04daf('General',' ',n,n,v,ldv,'Right singular vectors',ifail)

!       Call DDISNA (F08FLF) to estimate reciprocal condition numbers for
!       the singular vectors.

        Call ddisna('Left',m,n,sva,rcondu,info)
        Call ddisna('Right',m,n,sva,rcondv,info)

!       Print the approximate error bounds for the singular values
!       and vectors.
        Write (nout,*)
        Write (nout,'(/1X,A)')                                                 &
          'Estimate of the condition number of column equilibrated A'
        Write (nout,99998) rwork(3)
        Write (nout,'(/1X,A)')                                                 &
          'Error estimates (as multiples of machine precision):'
        Write (nout,'(/1X,A)') '  for the singular values'
        Write (nout,99997) nint(serrbd/x02ajf())
        Write (nout,'(/1X,A)') '  for left singular vectors'
        Write (nout,99997)(nint(serrbd/rcondu(i)/x02ajf()),i=1,n)
        Write (nout,'(/1X,A)') '  for right singular vectors'
        Write (nout,99997)(nint(serrbd/rcondv(i)/x02ajf()),i=1,n)
      Else
        Write (nout,99996) 'Failure in ZGEJSV. INFO =', info
      End If

99999 Format (3X,8F8.4)
99998 Format (4X,1P,E11.2)
99997 Format (4X,6I4)
99996 Format (1X,A,I4)
99995 Format (1X,2(A,1P,E13.5))
    End Program f08kvfe


f08kwfe.f90

    Program f08kwfe

!     F08KWF Example Program Text

!     Mark 26.1 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: ddisna, nag_wp, x02ajf, x04daf, zgesvj
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: eps, serrbd
      Integer                          :: i, ifail, info, j, lda, ldv, lrwork, &
                                          lwork, m, n
!     .. Local Arrays ..
      Complex (Kind=nag_wp), Allocatable :: a(:,:), cwork(:), v(:,:)
      Real (Kind=nag_wp), Allocatable  :: rcondu(:), rcondv(:), rwork(:),      &
                                          sva(:)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: abs, max, nint
!     .. Executable Statements ..
      Write (nout,*) 'F08KWF Example Program Results'
      Write (nout,*)
      Flush (nout)
!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) m, n
      lda = m
      ldv = n
      lwork = n + m
      lrwork = max(6,n)
      Allocate (a(lda,n),rcondu(m),rcondv(m),sva(n),v(ldv,n),cwork(lwork),     &
        rwork(lrwork))

!     Read the m by n matrix A from data file

      Read (nin,*)((a(i,j),j=1,n),i=1,m)

!     Compute the singular values and left and right singular vectors
!     of A (A = U*S*V, m.ge.n)

!     The NAG name equivalent of zgesvj is f08kwf
      Call zgesvj('G','U','V',m,n,a,lda,sva,0,v,ldv,cwork,lwork,rwork,lrwork,  &
        info)
      If (info==0) Then

!       Compute the approximate error bound for the computed singular values
!       using the 2-norm, s(1) = norm(A), and machine precision, eps.
        eps = x02ajf()
        serrbd = eps*sva(1)

!       Print solution
        Write (nout,*) 'Singular values'
        Write (nout,99999)(sva(j),j=1,n)

        If (abs(rwork(1)-1.0_nag_wp)>eps) Then
          Write (nout,99996) 'Values need scaling by factor = ', rwork(1)
        End If
        Write (nout,*)
        Flush (nout)

!       ifail: behaviour on error exit
!              =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
        ifail = 0
        Call x04daf('General',' ',m,n,a,lda,'Left singular vectors',ifail)

        Write (nout,*)
        Flush (nout)

        ifail = 0
        Call x04daf('General',' ',n,n,v,ldv,'Right singular vectors',ifail)

!       Call DDISNA (F08FLF) to estimate reciprocal condition
!       numbers for the singular vectors
        Call ddisna('Left',m,n,sva,rcondu,info)
        Call ddisna('Right',m,n,sva,rcondv,info)

!       Print the approximate error bounds for the singular values
!       and vectors
        Write (nout,'(/1X,A)')                                                 &
          'Error estimates (as multiples of machine precision):'
        Write (nout,'(/1X,A)') '  for the singular values'
        Write (nout,99998) nint(serrbd/x02ajf())
        Write (nout,'(/1X,A)') '  for left singular vectors'
        Write (nout,99998)(nint(serrbd/rcondu(i)/x02ajf()),i=1,n)
        Write (nout,'(/1X,A)') '  for right singular vectors'
        Write (nout,99998)(nint(serrbd/rcondv(i)/x02ajf()),i=1,n)
      Else
        Write (nout,99997) 'Failure in ZGESVJ. INFO =', info
      End If

99999 Format (3X,(8F8.4))
99998 Format (4X,6I4)
99997 Format (1X,A,I4)
99996 Format (/,1X,A,1P,E13.5)
    End Program f08kwfe


f08kzfe.f90

    Program f08kzfe

!     F08KZF Example Program Text

!     Mark 26.1 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: nag_wp, zgesvdx
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: vl, vu
      Integer                          :: i, il, info, iu, lda, ldu, ldvt,     &
                                          liwork, lrwork, lwork, m, n, ns
      Character (1)                    :: range
!     .. Local Arrays ..
      Complex (Kind=nag_wp), Allocatable :: a(:,:), u(:,:), vt(:,:), work(:)
      Real (Kind=nag_wp), Allocatable  :: rwork(:), s(:)
      Integer, Allocatable             :: iwork(:)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: nint
!     .. Executable Statements ..
      Write (nout,*) 'F08KZF Example Program Results'
      Write (nout,*)
!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) m, n
      lda = m
      ldu = m
      ldvt = n
      lwork = 2*n**2 + 4*n
      lrwork = 2*n*2 + 34*n
      liwork = 12*n
      Allocate (a(lda,n),s(n),vt(ldvt,n),u(ldu,m),iwork(liwork),work(lwork),   &
        rwork(lrwork))

!     Read the m by n matrix A from data file
      Read (nin,*)(a(i,1:n),i=1,m)

!     Read range for selected singular values
      Read (nin,*) range

      If (range=='I' .Or. range=='i') Then
        Read (nin,*) il, iu
      Else If (range=='V' .Or. range=='v') Then
        Read (nin,*) vl, vu
      End If

!     Compute the singular values and left and right singular vectors
!     of A.

!     The NAG name equivalent of zgesvd is f08kzf
      Call zgesvdx('V','V',range,m,n,a,lda,vl,vu,il,iu,ns,s,u,ldu,vt,ldvt,     &
        work,lwork,rwork,iwork,info)

      If (info/=0) Then
        Write (nout,99999) 'Failure in ZGESVDX. INFO =', info
99999   Format (1X,A,I4)
        Go To 100
      End If

!     Print the selected singular values of A

      Write (nout,*) 'Singular values of A:'
      Write (nout,99998) s(1:ns)
99998 Format (1X,4(3X,F11.4))

      Call compute_error_bounds(m,ns,s)

100   Continue

    Contains
      Subroutine compute_error_bounds(m,n,s)

!       Error estimates for singular values and vectors is computed
!       and printed here.

!       .. Use Statements ..
        Use nag_library, Only: ddisna, nag_wp, x02ajf
!       .. Implicit None Statement ..
        Implicit None
!       .. Scalar Arguments ..
        Integer, Intent (In)           :: m, n
!       .. Array Arguments ..
        Real (Kind=nag_wp), Intent (In) :: s(n)
!       .. Local Scalars ..
        Real (Kind=nag_wp)             :: eps, serrbd
        Integer                        :: i, info
!       .. Local Arrays ..
        Real (Kind=nag_wp), Allocatable :: rcondu(:), rcondv(:), uerrbd(:),    &
                                          verrbd(:)
!       .. Executable Statements ..
        Allocate (rcondu(n),rcondv(n),uerrbd(n),verrbd(n))

!       Get the machine precision, EPS and compute the approximate
!       error bound for the computed singular values.  Note that for
!       the 2-norm, S(1) = norm(A)

        eps = x02ajf()
        serrbd = eps*s(1)

!       Call DDISNA (F08FLF) to estimate reciprocal condition
!       numbers for the singular vectors

        Call ddisna('Left',m,n,s,rcondu,info)
        Call ddisna('Right',m,n,s,rcondv,info)

!       Compute the error estimates for the singular vectors

        Do i = 1, n
          uerrbd(i) = serrbd/rcondu(i)
          verrbd(i) = serrbd/rcondv(i)
        End Do

!       Print the approximate error bounds for the singular values
!       and vectors

        Write (nout,*)
        Write (nout,*) 'Error estimates (as multiples of machine precision):'
        Write (nout,*) '  for the singular values'
        Write (nout,99999) nint(serrbd/x02ajf())
        Write (nout,*)
        Write (nout,*) '  for the left singular vectors'
        Write (nout,99999) nint(uerrbd(1:n)/x02ajf())
        Write (nout,*)
        Write (nout,*) '  for the right singular vectors'
        Write (nout,99999) nint(verrbd(1:n)/x02ajf())

99999   Format (4X,6I11)

      End Subroutine compute_error_bounds

    End Program f08kzfe


f08lefe.f90

    Program f08lefe

!     F08LEF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: dgbbrd, nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
      Character (1), Parameter         :: vect = 'B'
!     .. Local Scalars ..
      Integer                          :: i, info, j, kl, ku, ldab, ldb, ldc,  &
                                          ldpt, ldq, m, n, ncc
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: ab(:,:), b(:,:), c(:,:), d(:), e(:), &
                                          pt(:,:), q(:,:), work(:)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: abs, max, min
!     .. Executable Statements ..
      Write (nout,*) 'F08LEF Example Program Results'
!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) m, n, kl, ku, ncc
      ldab = kl + ku + 1
      ldb = m
      ldc = m
      ldpt = n
      ldq = m
      Allocate (ab(ldab,n),b(ldb,n),c(m,ncc),d(n),e(n-1),pt(ldpt,n),q(ldq,m),  &
        work(2*m+2*n))

!     Read A from data file

      Read (nin,*)((ab(ku+1+i-j,j),j=max(i-kl,1),min(i+ku,n)),i=1,m)

!     Reduce A to upper bidiagonal form
!     The NAG name equivalent of dgbbrd is f08lef
      Call dgbbrd(vect,m,n,ncc,kl,ku,ab,ldab,d,e,q,ldq,pt,ldpt,c,ldc,work,     &
        info)

!     Print the absolute values of bidiagonal vectors d and e.
!     Any of these can differ by a sign change by combinations of sign
!     changes in columns of Q and P (rows of PT).
      Write (nout,*)
      Write (nout,*) 'Diagonal D:'
      Write (nout,99999) abs(d(1:n))
      Write (nout,*)
      Write (nout,*) 'Off-diagonal E:'
      Write (nout,99999) abs(e(1:n-1))
99999 Format (1X,4(3X,F11.4))

    End Program f08lefe


f08lsfe.f90

    Program f08lsfe

!     F08LSF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: nag_wp, zgbbrd
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
      Character (1), Parameter         :: vect = 'N'
!     .. Local Scalars ..
      Integer                          :: i, info, j, kl, ku, ldab, ldc, ldpt, &
                                          ldq, m, n, ncc
!     .. Local Arrays ..
      Complex (Kind=nag_wp), Allocatable :: ab(:,:), c(:,:), pt(:,:), q(:,:),  &
                                          work(:)
      Real (Kind=nag_wp), Allocatable  :: d(:), e(:), rwork(:)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: max, min
!     .. Executable Statements ..
      Write (nout,*) 'F08LSF Example Program Results'
!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) m, n, kl, ku, ncc
      ldab = kl + ku + 1
      ldc = m
      ldpt = n
      ldq = m
      Allocate (ab(ldab,n),c(m,ncc),pt(ldpt,n),q(ldq,m),work(m+n),d(n),e(n-1), &
        rwork(m+n))

!     Read A from data file

      Read (nin,*)((ab(ku+1+i-j,j),j=max(i-kl,1),min(i+ku,n)),i=1,m)

!     Reduce A to upper bidiagonal form

!     The NAG name equivalent of zgbbrd is f08lsf
      Call zgbbrd(vect,m,n,ncc,kl,ku,ab,ldab,d,e,q,ldq,pt,ldpt,c,ldc,work,     &
        rwork,info)

!     Print bidiagonal form

      Write (nout,*)
      Write (nout,*) 'Diagonal'
      Write (nout,99999) d(1:min(m,n))
      Write (nout,*) 'Superdiagonal'
      Write (nout,99999) e(1:min(m,n)-1)

99999 Format (1X,8F9.4)
    End Program f08lsfe


f08mbfe.f90

    Program f08mbfe

!     F08MBF Example Program Text

!     Mark 26.1 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: dbdsvdx, nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: vl, vu
      Integer                          :: il, info, iu, ldz, n, ns
      Character (1)                    :: range
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: d(:), e(:), s(:), work(:), z(:,:)
      Integer, Allocatable             :: iwork(:)
!     .. Executable Statements ..
      Write (nout,*) 'F08MBF Example Program Results'
      Write (nout,*)
      Flush (nout)
!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) n
      ldz = 2*n
      Allocate (d(n),e(n-1),s(n),z(ldz,n+1),work(14*n),iwork(12*n))

!     Read the bidiagonal matrix B from data file, first
!     the diagonal elements, and then the off diagonal elements

      Read (nin,*) d(1:n)
      Read (nin,*) e(1:n-1)

!     Read range for selected singular values
      Read (nin,*) range

      If (range=='I' .Or. range=='i') Then
        Read (nin,*) il, iu
      Else If (range=='V' .Or. range=='v') Then
        Read (nin,*) vl, vu
      End If

!     Calculate the singular values and singular vectors of B.

!     The NAG name equivalent of dbdsvdx is f08mbf
      Call dbdsvdx('Upper','V',range,n,d,e,vl,vu,il,iu,ns,s,z,ldz,work,iwork,  &
        info)

      If (info==0) Then
!       Print the singular values of B.

        If (range=='I' .Or. range=='i') Then
          Write (nout,99999) ns, il, iu
        Else If (range=='V' .Or. range=='v') Then
          Write (nout,99998) ns, vl, vu
        End If
        Write (nout,99997) s(1:ns)
      Else
        Write (nout,99996) '** F08MBF/DBDSVDX failed with INFO = ', info
      End If

99999 Format (1X,I2,1X,'singular values of B in the index range [',I2,',',I2,  &
        ']:')
99998 Format (1X,I2,1X,'singular values of B in the range [',F7.3,',',F7.3,    &
        ']:')
99997 Format (1X,4(3X,F11.4))
99996 Format (1X,A,I10)
    End Program f08mbfe


f08mdfe.f90

    Program f08mdfe

!     F08MDF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: dbdsdc, nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Integer                          :: info, ldb, ldu, ldvt, n
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: b(:,:), d(:), e(:), u(:,:), vt(:,:), &
                                          work(:)
      Real (Kind=nag_wp)               :: q(1)
      Integer                          :: iq(1)
      Integer, Allocatable             :: iwork(:)
!     .. Executable Statements ..
      Write (nout,*) 'F08MDF Example Program Results'
      Write (nout,*)
      Flush (nout)
!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) n
      ldb = n
      ldu = n
      ldvt = n
      Allocate (b(ldb,n),d(n),e(n-1),u(ldu,n),vt(ldvt,n),work(n*(3*n+          &
        4)),iwork(8*n))

!     Read the bidiagonal matrix B from data file, first
!     the diagonal elements, and then the off diagonal elements

      Read (nin,*) d(1:n)
      Read (nin,*) e(1:n-1)

!     Calculate the singular values and left and right singular
!     vectors of B.

!     The NAG name equivalent of dbdsdc is f08mdf
      Call dbdsdc('Upper','I',n,d,e,u,ldu,vt,ldvt,q,iq,work,iwork,info)

      If (info==0) Then
!       Print the singular values of B.

        Write (nout,*) 'Singular values of B:'
        Write (nout,99999) d(1:n)
      Else
        Write (nout,99998) '** F08MDF/DBDSDC failed with INFO = ', info
      End If

99999 Format (1X,4(3X,F11.4))
99998 Format (1X,A,I10)
    End Program f08mdfe


f08mefe.f90

    Program f08mefe

!     F08MEF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: dbdsqr, f06qhf, nag_wp, x04caf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Real (Kind=nag_wp), Parameter    :: one = 1.0_nag_wp
      Real (Kind=nag_wp), Parameter    :: zero = 0.0_nag_wp
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Integer                          :: ifail, info, ldc, ldu, ldvt, n
      Character (1)                    :: uplo
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: c(:,:), d(:), e(:), u(:,:), vt(:,:), &
                                          work(:)
!     .. Executable Statements ..
      Write (nout,*) 'F08MEF Example Program Results'
!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) n
      ldc = 1
      ldu = n
      ldvt = n
      Allocate (c(ldc,1),d(n),e(n-1),u(ldu,n),vt(ldvt,n),work(4*n))

!     Read B from data file

      Read (nin,*) d(1:n)
      Read (nin,*) e(1:n-1)

      Read (nin,*) uplo

!     Initialize U and VT to be the unit matrix
      Call f06qhf('General',n,n,zero,one,u,ldu)
      Call f06qhf('General',n,n,zero,one,vt,ldvt)

!     Calculate the SVD of B
!     The NAG name equivalent of dbdsqr is f08mef
      Call dbdsqr(uplo,n,n,n,0,d,e,vt,ldvt,u,ldu,c,ldc,work,info)

      Write (nout,*)
      If (info>0) Then
        Write (nout,*) 'Failure to converge.'
      Else

!       Print singular values, left & right singular vectors

        Write (nout,*) 'Singular values'
        Write (nout,99999) d(1:n)
        Write (nout,*)
        Flush (nout)

!       ifail: behaviour on error exit
!              =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
        ifail = 0
        Call x04caf('General',' ',n,n,vt,ldvt,'Right singular vectors, by row' &
          ,ifail)

        Write (nout,*)
        Flush (nout)

        ifail = 0
        Call x04caf('General',' ',n,n,u,ldu,'Left singular vectors, by column' &
          ,ifail)

      End If

99999 Format (3X,(8F8.4))
    End Program f08mefe


f08nafe.f90

    Program f08nafe

!     F08NAF Example Program Text
!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: dgeev, nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Real (Kind=nag_wp), Parameter    :: zero = 0.0_nag_wp
      Integer, Parameter               :: nb = 64, nin = 5, nout = 6
!     .. Local Scalars ..
      Complex (Kind=nag_wp)            :: eig
      Real (Kind=nag_wp)               :: alpha, beta, scale
      Integer                          :: i, info, j, k, lda, ldvr, lwork, n
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: a(:,:), vr(:,:), wi(:), work(:),     &
                                          wr(:)
      Real (Kind=nag_wp)               :: dummy(1,1)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: cmplx, max, maxloc, nint, sqrt
!     .. Executable Statements ..
      Write (nout,*) 'F08NAF Example Program Results'
!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) n
      lda = n
      ldvr = n
      Allocate (a(lda,n),vr(ldvr,n),wi(n),wr(n))

!     Use routine workspace query to get optimal workspace.
      lwork = -1
!     The NAG name equivalent of dgeev is f08naf
      Call dgeev('No left vectors','Vectors (right)',n,a,lda,wr,wi,dummy,1,vr, &
        ldvr,dummy,lwork,info)

!     Make sure that there is enough workspace for block size nb.
      lwork = max((nb+2)*n,nint(dummy(1,1)))
      Allocate (work(lwork))

!     Read the matrix A from data file

      Read (nin,*)(a(i,1:n),i=1,n)

!     Compute the eigenvalues and right eigenvectors of A

!     The NAG name equivalent of dgeev is f08naf
      Call dgeev('No left vectors','Vectors (right)',n,a,lda,wr,wi,dummy,1,vr, &
        ldvr,work,lwork,info)

      If (info==0) Then

!       Print solution

        Do j = 1, n
          Write (nout,*)
          If (wi(j)==zero) Then
            Write (nout,99999) 'Eigenvalue(', j, ') = ', wr(j)
          Else
            eig = cmplx(wr(j),wi(j),kind=nag_wp)
            Write (nout,99998) 'Eigenvalue(', j, ') = ', eig
          End If
          Write (nout,*)
          Write (nout,99997) 'Eigenvector(', j, ')'
          If (wi(j)==zero) Then
!           Scale by making largest element positive
            k = maxloc(vr(1:n,j),1)
            If (vr(k,j)<zero) Then
              vr(1:n,j) = -vr(1:n,j)
            End If
            Write (nout,99996) vr(1:n,j)
          Else If (wi(j)>0.0E0_nag_wp) Then
!           Scale by making largest element real and positive
            work(1:n) = vr(1:n,j)**2 + vr(1:n,j+1)**2
            k = maxloc(work(1:n),1)
            scale = sqrt(work(k))
            work(1:n) = vr(1:n,j)
            alpha = vr(k,j)/scale
            beta = vr(k,j+1)/scale
            vr(1:n,j) = alpha*work(1:n) + beta*vr(1:n,j+1)
            vr(1:n,j+1) = alpha*vr(1:n,j+1) - beta*work(1:n)
            Write (nout,99995)(vr(i,j),vr(i,j+1),i=1,n)
          Else
            Write (nout,99995)(vr(i,j-1),-vr(i,j),i=1,n)
          End If
        End Do
      Else
        Write (nout,*)
        Write (nout,99994) 'Failure in DGEEV.  INFO = ', info
      End If

99999 Format (1X,A,I2,A,1P,E11.4)
99998 Format (1X,A,I2,A,'(',1P,E11.4,',',1P,E11.4,')')
99997 Format (1X,A,I2,A)
99996 Format (1X,1P,E11.4)
99995 Format (1X,'(',1P,E11.4,',',1P,E11.4,')')
99994 Format (1X,A,I4)
    End Program f08nafe


f08nbfe.f90

    Program f08nbfe

!     F08NBF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: dgeevx, nag_wp, x02ajf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nb = 64, nin = 5, nout = 6
!     .. Local Scalars ..
      Complex (Kind=nag_wp)            :: eig
      Real (Kind=nag_wp)               :: abnrm, eps, tol
      Integer                          :: i, ihi, ilo, info, j, k, lda, ldvl,  &
                                          ldvr, lwork, n
      Logical                          :: pair
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: a(:,:), rconde(:), rcondv(:),        &
                                          scale(:), vl(:,:), vr(:,:), wi(:),   &
                                          work(:), wr(:)
      Real (Kind=nag_wp)               :: dummy(1)
      Integer, Allocatable             :: iwork(:)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: cmplx, max, maxloc, nint
!     .. Executable Statements ..
      Write (nout,*) 'F08NBF Example Program Results'
!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) n
      lda = n
      ldvl = n
      ldvr = n
      lwork = (2+nb)*n
      Allocate (a(lda,n),rconde(n),rcondv(n),scale(n),vl(ldvl,n),vr(ldvr,n),   &
        wi(n),wr(n),iwork(2*n-2))

!     Use routine workspace query to get optimal workspace.
      lwork = -1
!     The NAG name equivalent of dgeevx is f08nbf
      Call dgeevx('Balance','Vectors (left)','Vectors (right)',                &
        'Both reciprocal condition numbers',n,a,lda,wr,wi,vl,ldvl,vr,ldvr,ilo, &
        ihi,scale,abnrm,rconde,rcondv,dummy,lwork,iwork,info)

!     Make sure that there is enough workspace for block size nb.
      lwork = max((nb+2)*n,nint(dummy(1)))
      Allocate (work(lwork))

!     Read the matrix A from data file

      Read (nin,*)(a(i,1:n),i=1,n)

!     Solve the eigenvalue problem
!     The NAG name equivalent of dgeevx is f08nbf
      Call dgeevx('Balance','Vectors (left)','Vectors (right)',                &
        'Both reciprocal condition numbers',n,a,lda,wr,wi,vl,ldvl,vr,ldvr,ilo, &
        ihi,scale,abnrm,rconde,rcondv,work,lwork,iwork,info)

      If (info==0) Then

!       Compute the machine precision
        eps = x02ajf()
        tol = eps*abnrm
        pair = .False.

!       Print the eigenvalues and vectors, and associated condition
!       number and bounds

        Write (nout,*)
        Write (nout,*) 'Eigenvalues'
        Write (nout,*)
        Write (nout,*) '         Eigenvalue           rcond    error'

        Do j = 1, n

!         Print information on j-th eigenvalue

          If (wi(j)==0.0_nag_wp) Then
            If (rconde(j)>0.0_nag_wp) Then
              If (tol/rconde(j)<10.0_nag_wp*eps) Then
                Write (nout,99999) j, wr(j), rconde(j), '-'
              Else
                Write (nout,99998) j, wr(j), rconde(j), tol/rconde(j)
              End If
            Else
              Write (nout,99998) j, wr(j), rconde(j), 'Inf'
            End If
          Else
            If (rconde(j)>0.0_nag_wp) Then
              If (tol/rconde(j)<10.0_nag_wp*eps) Then
                Write (nout,99997) j, wr(j), wi(j), rconde(j), '-'
              Else
                Write (nout,99996) j, wr(j), wi(j), rconde(j), tol/rconde(j)
              End If
            Else
              Write (nout,99997) j, wr(j), wi(j), rconde(j), 'Inf'
            End If
          End If
        End Do

        Write (nout,*)
        Write (nout,*) 'Eigenvectors'
        Write (nout,*)
        Write (nout,*) '         Eigenvector          rcond    error'

        Do j = 1, n

!         Print information on j-th eigenvector
          Write (nout,*)

          If (wi(j)==0.0E0_nag_wp) Then
!           Make real eigenvectors have positive first entry
            If (vr(1,j)<0.0_nag_wp) Then
              vr(1:n,j) = -vr(1:n,j)
            End If
            If (rcondv(j)>0.0_nag_wp) Then
              If (tol/rcondv(j)<10.0_nag_wp*eps) Then
                Write (nout,99999) j, vr(1,j), rcondv(j), '-'
              Else
                Write (nout,99998) j, vr(1,j), rcondv(j), tol/rcondv(j)
              End If
            Else
              Write (nout,99998) j, vr(1,j), rcondv(j), 'Inf'
            End If
            Write (nout,99995) vr(2:n,j)
          Else
            If (pair) Then
              eig = cmplx(vr(1,j-1),-vr(1,j),kind=nag_wp)
            Else
!             Make largest eigenvector element have positive first entry
              work(1:n) = vr(1:n,j)**2 + vr(1:n,j+1)**2
              k = maxloc(work(1:n),1)
              If (vr(k,j)<0.0_nag_wp) Then
                vr(1:n,j) = -vr(1:n,j)
              End If
              eig = cmplx(vr(1,j),vr(1,j+1),kind=nag_wp)
            End If
            If (rcondv(j)>0.0_nag_wp) Then
              If (tol/rcondv(j)<10.0_nag_wp*eps) Then
                Write (nout,99997) j, eig, rcondv(j), '-'
              Else
                Write (nout,99996) j, eig, rcondv(j), tol/rcondv(j)
              End If
            Else
              Write (nout,99997) j, eig, rcondv(j), 'Inf'
            End If
            If (pair) Then
              Write (nout,99994)(vr(i,j-1),-vr(i,j),i=2,n)
            Else
              Write (nout,99994)(vr(i,j),vr(i,j+1),i=2,n)
            End If
            pair = .Not. pair
          End If
        End Do
        Write (nout,*)
        Write (nout,*) 'Errors below 10*machine precision are not displayed'
      Else
        Write (nout,*)
        Write (nout,99993) 'Failure in DGEEVX.  INFO = ', info
      End If

99999 Format (1X,I2,2X,1P,E11.4,14X,0P,F7.4,4X,A)
99998 Format (1X,I2,2X,1P,E11.4,11X,0P,F7.4,1X,1P,E8.1)
99997 Format (1X,I2,1X,'(',1P,E11.4,',',E11.4,')',1X,0P,F7.4,4X,A)
99996 Format (1X,I2,1X,'(',1P,E11.4,',',E11.4,')',1X,0P,F7.4,1X,1P,E8.1)
99995 Format (1X,4X,1P,E11.4)
99994 Format (1X,3X,'(',1P,E11.4,',',E11.4,')')
99993 Format (1X,A,I4)
    End Program f08nbfe


f08nefe.f90

    Program f08nefe

!     F08NEF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: dgehrd, nag_wp, x04caf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Real (Kind=nag_wp), Parameter    :: zero = 0.0E0_nag_wp
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Integer                          :: i, ifail, info, lda, lwork, n
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: a(:,:), tau(:), work(:)
!     .. Executable Statements ..
      Write (nout,*) 'F08NEF Example Program Results'
!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) n
      lda = n
      lwork = 64*n
      Allocate (a(lda,n),tau(n-1),work(lwork))

!     Read A from data file

      Read (nin,*)(a(i,1:n),i=1,n)

!     Reduce A to upper Hessenberg form

!     The NAG name equivalent of dgehrd is f08nef
      Call dgehrd(n,1,n,a,lda,tau,work,lwork,info)

!     Set the elements below the first subdiagonal to zero

      Do i = 1, n - 2
        a(i+2:n,i) = zero
      End Do

!     Print upper Hessenberg form

      Write (nout,*)
      Flush (nout)

!     ifail: behaviour on error exit
!             =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
      ifail = 0
      Call x04caf('General',' ',n,n,a,lda,'Upper Hessenberg form',ifail)

    End Program f08nefe


f08nffe.f90

    Program f08nffe

!     F08NFF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: dgehrd, dgemm, dhseqr, dlange => f06raf, dorghr,  &
                             nag_wp, x02ajf, x04caf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: alpha, beta, norm
      Integer                          :: i, ifail, info, lda, ldc, ldd, ldz,  &
                                          lwork, n
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: a(:,:), c(:,:), d(:,:), tau(:),      &
                                          wi(:), work(:), wr(:), z(:,:)
!     .. Executable Statements ..
      Write (nout,*) 'F08NFF Example Program Results'
!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) n
      lda = n
      ldz = n
      ldc = n
      ldd = n
      lwork = 64*(n-1)
      Allocate (a(lda,n),c(ldc,n),d(ldd,n),tau(n),wi(n),work(lwork),wr(n),     &
        z(ldz,n))

!     Read A from data file
      Read (nin,*)(a(i,1:n),i=1,n)

!     Copy A into D.
      d(1:n,1:n) = a(1:n,1:n)

      Write (nout,*)
      Flush (nout)

!     Print Matrix A
!     ifail: behaviour on error exit
!             =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
      ifail = 0
      Call x04caf('General',' ',n,n,a,lda,'Matrix A',ifail)

      Write (nout,*)
      Flush (nout)

!     Reduce A to upper Hessenberg form H = (Q**T)*A*Q
!     The NAG name equivalent of dgehrd is f08nef
      Call dgehrd(n,1,n,a,lda,tau,work,lwork,info)

!     Copy A into Z
      z(1:n,1:n) = a(1:n,1:n)

!     Form Q explicitly, storing the result in Z
!     The NAG name equivalent of dorghr is f08nff
      Call dorghr(n,1,n,z,ldz,tau,work,lwork,info)

!     Calculate the Schur factorization of H = Y*T*(Y**T) and form
!     Q*Y explicitly, storing the result in Z

!     Note that A = Z*T*(Z**T), where Z = Q*Y
!     The NAG name equivalent of dhseqr is f08pef
      Call dhseqr('Schur form','Vectors',n,1,n,a,lda,wr,wi,z,ldz,work,lwork,   &
        info)

!     Compute A - Z*T*Z^T from the factorization of A and store in matrix D.
!     The NAG name equivalent of dgemm is f06yaf.
      alpha = 1.0_nag_wp
      beta = 0.0_nag_wp
      Call dgemm('N','N',n,n,n,alpha,z,ldz,a,lda,beta,c,ldc)
      alpha = -1.0_nag_wp
      beta = 1.0_nag_wp
      Call dgemm('N','T',n,n,n,alpha,c,ldc,z,ldz,beta,d,ldd)

!     Find norm of difference matrix D and warn if it is too large;
!     f06raf is the NAG name equivalent of the LAPACK auxiliary dlange
      norm = dlange('O',ldd,n,d,ldd,work)
      If (norm>x02ajf()**0.8_nag_wp) Then
        Write (nout,*) 'Norm of A-(Z*T*Z^T) is much greater than 0.'
        Write (nout,*) 'Schur factorization has failed.'
      Else
!       Print eigenvalues.
        Write (nout,*) 'Eigenvalues'
        Write (nout,99999)(' (',wr(i),',',wi(i),')',i=1,n)
      End If

99999 Format (1X,A,F8.4,A,F8.4,A)

    End Program f08nffe


f08ngfe.f90

    Program f08ngfe

!     F08NGF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: blas_damax_val, dgehrd, dhsein, dhseqr, dormhr,   &
                             nag_wp, x04caf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Real (Kind=nag_wp), Parameter    :: zero = 0.0_nag_wp
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Complex (Kind=nag_wp)            :: eig, eig1
      Real (Kind=nag_wp)               :: r, thresh
      Integer                          :: i, ifail, info, j, k, l, lda, ldc,   &
                                          ldh, ldvl, ldz, lwork, m, n
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: a(:,:), c(:,:), h(:,:), tau(:),      &
                                          vl(:,:), wi(:), work(:), wr(:),      &
                                          z(:,:)
      Integer, Allocatable             :: ifaill(:), ifailr(:)
      Logical, Allocatable             :: select(:)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: aimag, cmplx, conjg, maxloc, real,   &
                                          sqrt, sum
!     .. Executable Statements ..
      Write (nout,*) 'F08NGF Example Program Results'
!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) n
      ldz = 1
      lda = n
      ldc = n
      ldh = n
      ldvl = n
      lwork = 64*n
      Allocate (a(lda,n),c(ldc,n),h(ldh,n),tau(n),vl(ldvl,n),wi(n),            &
        work(lwork),wr(n),z(ldz,1),ifaill(n),ifailr(n),select(n))

!     Read A from data file

      Read (nin,*)(a(i,1:n),i=1,n)

      Read (nin,*) thresh

!     Reduce A to upper Hessenberg form H = (Q**T)*A*Q
!     The NAG name equivalent of dgehrd is f08nef
      Call dgehrd(n,1,n,a,lda,tau,work,lwork,info)

!     Copy A to H
      h(1:n,1:n) = a(1:n,1:n)

!     Calculate the eigenvalues of H (same as A)
!     The NAG name equivalent of dhseqr is f08pef
      Call dhseqr('Eigenvalues','No vectors',n,1,n,h,ldh,wr,wi,z,ldz,work,     &
        lwork,info)

      Write (nout,*)
      If (info>0) Then
        Write (nout,*) 'Failure to converge.'
      Else
        Write (nout,*) 'Eigenvalues'
        Write (nout,99999)(' (',wr(i),',',wi(i),')',i=1,n)

        Do i = 1, n
          select(i) = wr(i) < thresh
        End Do

!       Calculate the eigenvectors of H (as specified by SELECT),
!       storing the result in C
!       The NAG name equivalent of dhsein is f08pkf
        Call dhsein('Right','QR','No initial vectors',select,n,a,lda,wr,wi,vl, &
          ldvl,c,ldc,n,m,work,ifaill,ifailr,info)

!       Calculate the eigenvectors of A = Q * (eigenvectors of H)
!       The NAG name equivalent of dormhr is f08ngf
        Call dormhr('Left','No transpose',n,m,1,n,a,lda,tau,c,ldc,work,lwork,  &
          info)

!       Print eigenvectors

        Write (nout,*)
        Flush (nout)

!       Normalize selected eigenvectors
        j = 0
        k = 1
        Do While (k<=n)
          If (select(k)) Then
            j = j + 1
            If (wi(k)==0.0_nag_wp) Then
!             Normalize real eigenvector by making largest positive
              Do i = 1, n
                Call blas_damax_val(n,c(1,j),1,l,r)
                If (c(l,j)<zero) Then
                  c(1:n,j) = -c(1:n,j)
                End If
              End Do
            Else
!             Normalize complex eigenvectors making largest element real
              work(1:n) = c(1:n,j)**2 + c(1:n,j+1)**2
              l = maxloc(work(1:n),1)
              eig1 = cmplx(c(l,j),c(l,j+1),kind=nag_wp)
              eig1 = conjg(eig1)/sqrt(work(l)*sum(work(1:n)))
              Do i = 1, n
                eig = cmplx(c(i,j),c(i,j+1),kind=nag_wp)
                eig = eig*eig1
                c(i,j) = real(eig)
                c(i,j+1) = aimag(eig)
              End Do
              c(l,j+1) = 0.0_nag_wp
              j = j + 1
              k = k + 1
            End If
          End If
          k = k + 1
        End Do

!       ifail: behaviour on error exit
!              =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
        ifail = 0
        Call x04caf('General',' ',n,m,c,ldc,'Contents of array C',ifail)

      End If

99999 Format (1X,A,F8.4,A,F8.4,A)
    End Program f08ngfe


f08nhfe.f90

    Program f08nhfe

!     F08NHF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: blas_damax_val, dgebak, dgebal, dgehrd, dhseqr,   &
                             dnrm2, dorghr, dtrevc, nag_wp, x04caf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Real (Kind=nag_wp), Parameter    :: zero = 0.0_nag_wp
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: r
      Integer                          :: i, ifail, ihi, ilo, info, k, lda,    &
                                          ldh, ldvl, ldvr, lwork, m, n
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: a(:,:), h(:,:), scale(:), tau(:),    &
                                          vl(:,:), vr(:,:), wi(:), work(:),    &
                                          wr(:)
      Logical                          :: select(1)
!     .. Executable Statements ..
      Write (nout,*) 'F08NHF Example Program Results'
!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) n
      ldvl = 1
      lda = n
      ldh = n
      ldvr = n
      lwork = 64*n
      Allocate (a(lda,n),h(ldh,n),scale(n),tau(n),vl(ldvl,1),vr(ldvr,n),wi(n), &
        work(lwork),wr(n))

!     Read A from data file
      Read (nin,*)(a(i,1:n),i=1,n)

!     Balance A
!     The NAG name equivalent of dgebal is f08nhf
      Call dgebal('Both',n,a,lda,ilo,ihi,scale,info)

!     Reduce A to upper Hessenberg form H = (Q**T)*A*Q
!     The NAG name equivalent of dgehrd is f08nef
      Call dgehrd(n,ilo,ihi,a,lda,tau,work,lwork,info)

!     Copy A to H and VR
      h(1:n,1:n) = a(1:n,1:n)
      vr(1:n,1:n) = a(1:n,1:n)

!     Form Q explicitly, storing the result in VR
!     The NAG name equivalent of dorghr is f08nff
      Call dorghr(n,1,n,vr,ldvr,tau,work,lwork,info)

!     Calculate the eigenvalues and Schur factorization of A
!     The NAG name equivalent of dhseqr is f08pef
      Call dhseqr('Schur form','Vectors',n,ilo,ihi,h,ldh,wr,wi,vr,ldvr,work,   &
        lwork,info)

      Write (nout,*)
      If (info>0) Then
        Write (nout,*) 'Failure to converge.'
      Else
        Write (nout,*) 'Eigenvalues'
        Write (nout,99999)(' (',wr(i),',',wi(i),')',i=1,n)

!       Calculate the eigenvectors of A, storing the result in VR

!       The NAG name equivalent of dtrevc is f08qkf
        Call dtrevc('Right','Backtransform',select,n,h,ldh,vl,ldvl,vr,ldvr,n,  &
          m,work,info)

!       The NAG name equivalent of dgebak is f08njf
        Call dgebak('Both','Right',n,ilo,ihi,scale,m,vr,ldvr,info)

!       Print eigenvectors

        Write (nout,*)
        Flush (nout)

!       Normalize the eigenvectors, largest positive
        Do i = 1, m
          Call blas_damax_val(n,vr(1,i),1,k,r)
          If (vr(k,i)<zero) Then
            vr(1:n,i) = -vr(1:n,i)
          End If
          r = dnrm2(n,vr(1,i),1)
          vr(1:n,i) = vr(1:n,i)/r
        End Do

!       ifail: behaviour on error exit
!              =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
        ifail = 0
        Call x04caf('General',' ',n,m,vr,ldvr,'Contents of array VR',ifail)

      End If

99999 Format (1X,A,F8.4,A,F8.4,A)
    End Program f08nhfe


f08nnfe.f90

    Program f08nnfe

!     F08NNF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: nag_wp, x04daf, zgeev
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nb = 64, nin = 5, nout = 6
!     .. Local Scalars ..
      Integer                          :: i, ifail, info, lda, ldvr, lwork, n
!     .. Local Arrays ..
      Complex (Kind=nag_wp), Allocatable :: a(:,:), vr(:,:), w(:), work(:)
      Complex (Kind=nag_wp)            :: dummy(1,1)
      Real (Kind=nag_wp), Allocatable  :: rwork(:)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: max, nint, real
!     .. Executable Statements ..
      Write (nout,*) 'F08NNF Example Program Results'
      Write (nout,*)
!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) n
      lda = n
      ldvr = n
      Allocate (a(lda,n),vr(ldvr,n),w(n),rwork(2*n))

!     Use routine workspace query to get optimal workspace.
      lwork = -1
!     The NAG name equivalent of zgeev is f08nnf
      Call zgeev('No left vectors','Vectors (right)',n,a,lda,w,dummy,1,vr,     &
        ldvr,dummy,lwork,rwork,info)

!     Make sure that there is enough workspace for block size nb.
      lwork = max((nb+1)*n,nint(real(dummy(1,1))))
      Allocate (work(lwork))

!     Read the matrix A from data file

      Read (nin,*)(a(i,1:n),i=1,n)

!     Compute the eigenvalues and right eigenvectors of A

!     The NAG name equivalent of zgeev is f08nnf
      Call zgeev('No left vectors','Vectors (right)',n,a,lda,w,dummy,1,vr,     &
        ldvr,work,lwork,rwork,info)

      If (info==0) Then

!       Print solution

        Write (nout,*) 'Eigenvalues'
        Write (nout,99999) w(1:n)

        Write (nout,*)
        Flush (nout)

!       ifail: behaviour on error exit
!              =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
        ifail = 0
        Call x04daf('General',' ',n,n,vr,ldvr,'Eigenvectors',ifail)

      Else
        Write (nout,*)
        Write (nout,99998) 'Failure in ZGEEV.  INFO = ', info
      End If

99999 Format ((3X,4(' (',F7.4,',',F7.4,')',:)))
99998 Format (1X,A,I4)
    End Program f08nnfe


f08npfe.f90

    Program f08npfe

!     F08NPF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: nag_wp, x02ajf, zgeevx
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nb = 64, nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: abnrm, eps, tol
      Integer                          :: i, ihi, ilo, info, j, lda, ldvl,     &
                                          ldvr, lwork, n
!     .. Local Arrays ..
      Complex (Kind=nag_wp), Allocatable :: a(:,:), vl(:,:), vr(:,:), w(:),    &
                                          work(:)
      Complex (Kind=nag_wp)            :: dummy(1)
      Real (Kind=nag_wp), Allocatable  :: rconde(:), rcondv(:), rwork(:),      &
                                          scale(:)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: max, nint, real
!     .. Executable Statements ..
      Write (nout,*) 'F08NPF Example Program Results'
!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) n
      lda = n
      ldvl = n
      ldvr = n
      Allocate (a(lda,n),vl(ldvl,n),vr(ldvr,n),w(n),rconde(n),rcondv(n),       &
        rwork(2*n),scale(n))

!     Use routine workspace query to get optimal workspace.
      lwork = -1
!     The NAG name equivalent of zgeevx is f08npf
      Call zgeevx('Balance','Vectors (left)','Vectors (right)',                &
        'Both reciprocal condition numbers',n,a,lda,w,vl,ldvl,vr,ldvr,ilo,ihi, &
        scale,abnrm,rconde,rcondv,dummy,lwork,rwork,info)

!     Make sure that there is enough workspace for block size nb.
      lwork = max((nb+1)*n,nint(real(dummy(1))))
      Allocate (work(lwork))

!     Read the matrix A from data file

      Read (nin,*)(a(i,1:n),i=1,n)

!     Solve the eigenvalue problem

!     The NAG name equivalent of zgeevx is f08npf
      Call zgeevx('Balance','Vectors (left)','Vectors (right)',                &
        'Both reciprocal condition numbers',n,a,lda,w,vl,ldvl,vr,ldvr,ilo,ihi, &
        scale,abnrm,rconde,rcondv,work,lwork,rwork,info)

      If (info==0) Then

!       Compute the machine precision

        eps = x02ajf()
        tol = eps*abnrm

!       Print the eigenvalues and vectors, and associated condition
!       number and bounds

        Write (nout,*)
        Write (nout,*) 'Eigenvalues'
        Write (nout,*)
        Write (nout,*) '         Eigenvalue           rcond    error'

        Do j = 1, n

!         Print information on j-th eigenvalue

          If (rconde(j)>0.0_nag_wp) Then
            If (tol/rconde(j)<10.0_nag_wp*eps) Then
              Write (nout,99999) j, w(j), rconde(j), '-'
            Else
              Write (nout,99998) j, w(j), rconde(j), tol/rconde(j)
            End If
          Else
            Write (nout,99999) j, w(j), rconde(j), 'Inf'
          End If

        End Do

        Write (nout,*)
        Write (nout,*) 'Eigenvectors'
        Write (nout,*)
        Write (nout,*) '         Eigenvector          rcond    error'

        Do j = 1, n

!         Print information on j-th eigenvector

          Write (nout,*)

!         Make first real part component be positive
          If (real(vr(1,j))<0.0_nag_wp) Then
            vr(1:n,j) = -vr(1:n,j)
          End If
          If (rcondv(j)>0.0_nag_wp) Then
            If (tol/rcondv(j)<10.0_nag_wp*eps) Then
              Write (nout,99999) j, vr(1,j), rcondv(j), '-'
            Else
              Write (nout,99998) j, vr(1,j), rcondv(j), tol/rcondv(j)
            End If
          Else
            Write (nout,99999) j, vr(1,j), rcondv(j), 'Inf'
          End If

          Write (nout,99997) vr(2:n,j)

        End Do
        Write (nout,*)
        Write (nout,*) 'Errors below 10*machine precision are not displayed'
      Else
        Write (nout,*)
        Write (nout,99996) 'Failure in ZGEEVX. INFO =', info
      End If

99999 Format (1X,I2,1X,'(',1P,E11.4,',',E11.4,')',1X,0P,F7.4,4X,A)
99998 Format (1X,I2,1X,'(',1P,E11.4,',',E11.4,')',1X,0P,F7.4,1X,1P,E8.1)
99997 Format (1X,3X,'(',1P,E11.4,',',E11.4,')')
99996 Format (1X,A,I4)

    End Program f08npfe


f08nsfe.f90

    Program f08nsfe

!     F08NSF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: nag_wp, x04dbf, zgehrd
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Complex (Kind=nag_wp), Parameter :: zero = (0.0E0_nag_wp,0.0E0_nag_wp)
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Integer                          :: i, ifail, info, lda, lwork, n
!     .. Local Arrays ..
      Complex (Kind=nag_wp), Allocatable :: a(:,:), tau(:), work(:)
      Character (1)                    :: clabs(1), rlabs(1)
!     .. Executable Statements ..
      Write (nout,*) 'F08NSF Example Program Results'
!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) n
      lda = n
      lwork = 64*n
      Allocate (a(lda,n),tau(n-1),work(lwork))

!     Read A from data file

      Read (nin,*)(a(i,1:n),i=1,n)

!     Reduce A to upper Hessenberg form

!     The NAG name equivalent of zgehrd is f08nsf
      Call zgehrd(n,1,n,a,lda,tau,work,lwork,info)

!     Set the elements below the first subdiagonal to zero

      Do i = 1, n - 2
        a(i+2:n,i) = zero
      End Do

!     Print upper Hessenberg form

      Write (nout,*)
      Flush (nout)

!     ifail: behaviour on error exit
!             =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
      ifail = 0
      Call x04dbf('General',' ',n,n,a,lda,'Bracketed','F7.4',                  &
        'Upper Hessenberg form','Integer',rlabs,'Integer',clabs,80,0,ifail)

    End Program f08nsfe


f08ntfe.f90

    Program f08ntfe

!     F08NTF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: nag_wp, x02ajf, x04dbf, zgehrd, zgemm, zhseqr,    &
                             zlange => f06uaf, zunghr
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Complex (Kind=nag_wp)            :: alpha, beta
      Real (Kind=nag_wp)               :: norm
      Integer                          :: i, ifail, info, lda, ldc, ldd, ldz,  &
                                          lwork, n
!     .. Local Arrays ..
      Complex (Kind=nag_wp), Allocatable :: a(:,:), c(:,:), d(:,:), tau(:),    &
                                          w(:), work(:), z(:,:)
      Real (Kind=nag_wp), Allocatable  :: rwork(:)
      Character (1)                    :: clabs(1), rlabs(1)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: cmplx
!     .. Executable Statements ..
      Write (nout,*) 'F08NTF Example Program Results'
      Write (nout,*)
      Flush (nout)
!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) n
      lda = n
      ldc = n
      ldd = n
      ldz = n
      lwork = 64*(n-1)
      Allocate (a(lda,n),c(ldc,n),d(ldd,n),rwork(lda),tau(n),w(n),work(lwork), &
        z(ldz,n))

!     Read A from data file
      Read (nin,*)(a(i,1:n),i=1,n)

!     Store A in D
      d(1:ldd,1:n) = a(1:lda,1:n)

!     Print matrix A
!     ifail: behaviour on error exit
!            =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
      ifail = 0
      Call x04dbf('General',' ',n,n,a,lda,'Bracketed','F7.4','Matrix A',       &
        'Integer',rlabs,'Integer',clabs,80,0,ifail)
      Write (nout,*)
      Flush (nout)

!     Reduce A to upper Hessenberg form H = (Q**H)*A*Q

!     The NAG name equivalent of zgehrd is f08nsf
      Call zgehrd(n,1,n,a,lda,tau,work,lwork,info)

!     Copy A into Z
      z(1:n,1:n) = a(1:n,1:n)

!     Form Q explicitly, storing the result in Z
!     The NAG name equivalent of zunghr is f08ntf
      Call zunghr(n,1,n,z,ldz,tau,work,lwork,info)

!     Calculate the Schur factorization of H = Y*T*(Y**H) and form
!     Q*Y explicitly, storing the result in Z

!     Note that A = Z*T*(Z**H), where Z = Q*Y

!     The NAG name equivalent of zhseqr is f08psf
      Call zhseqr('Schur form','Vectors',n,1,n,a,lda,w,z,ldz,work,lwork,info)

!     Compute A - Z*T*Z^H from Schur factorization of A, and store in matrix D
!     The NAG name equivalent of zgemm is f06zaf
      alpha = cmplx(1,kind=nag_wp)
      beta = cmplx(0,kind=nag_wp)
      Call zgemm('N','N',n,n,n,alpha,z,ldz,a,lda,beta,c,ldc)
      alpha = cmplx(-1,kind=nag_wp)
      beta = cmplx(1,kind=nag_wp)
      Call zgemm('N','C',n,n,n,alpha,c,ldc,z,ldz,beta,d,ldd)

!     Find norm of matrix D and print warning if it is too large
!     f06uaf is the NAG name equivalent of the LAPACK auxiliary zlange
      norm = zlange('O',ldd,n,d,ldd,rwork)
      If (norm>x02ajf()**0.5_nag_wp) Then
        Write (nout,*) 'Norm of A-(Z*T*Z^H) is much greater than 0.'
        Write (nout,*) 'Schur factorization has failed.'
      Else
!       Print eigenvalues.
        Write (nout,*) 'Eigenvalues'
        Write (nout,99999)(w(i),i=1,n)
      End If

99999 Format ((3X,4(' (',F7.4,',',F7.4,')',:)))

    End Program f08ntfe


f08nufe.f90

    Program f08nufe

!     F08NUF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: dznrm2, nag_wp, x04dbf, zgehrd, zhsein, zhseqr,   &
                             zunmhr
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Complex (Kind=nag_wp)            :: scal
      Real (Kind=nag_wp)               :: thresh
      Integer                          :: i, ifail, info, k, lda, ldc, ldh,    &
                                          ldvl, ldz, lwork, m, n
!     .. Local Arrays ..
      Complex (Kind=nag_wp), Allocatable :: a(:,:), c(:,:), h(:,:), tau(:),    &
                                          vl(:,:), w(:), work(:), z(:,:)
      Real (Kind=nag_wp), Allocatable  :: rwork(:)
      Integer, Allocatable             :: ifaill(:), ifailr(:)
      Logical, Allocatable             :: select(:)
      Character (1)                    :: clabs(1), rlabs(1)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: abs, aimag, conjg, maxloc, real
!     .. Executable Statements ..
      Write (nout,*) 'F08NUF Example Program Results'
      Flush (nout)
!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) n
      ldz = 1
      lda = n
      ldc = n
      ldh = n
      ldvl = n
      lwork = 64*n
      Allocate (a(lda,n),c(ldc,n),h(ldh,n),tau(n),vl(ldvl,n),w(n),work(lwork), &
        z(ldz,1),rwork(n),ifaill(n),ifailr(n),select(n))

!     Read A from data file
      Read (nin,*)(a(i,1:n),i=1,n)

      Read (nin,*) thresh

!     Reduce A to upper Hessenberg form H = (Q**H)*A*Q
!     The NAG name equivalent of zgehrd is f08nsf
      Call zgehrd(n,1,n,a,lda,tau,work,lwork,info)

!     Copy A to H
      h(1:n,1:n) = a(1:n,1:n)

!     Calculate the eigenvalues of H (same as A)
!     The NAG name equivalent of zhseqr is f08psf
      Call zhseqr('Eigenvalues','No vectors',n,1,n,h,ldh,w,z,ldz,work,lwork,   &
        info)

      Write (nout,*)
      If (info>0) Then
        Write (nout,*) 'Failure to converge.'
      Else
        Write (nout,*) 'Eigenvalues'
        Write (nout,99999)(' (',real(w(i)),',',aimag(w(i)),')',i=1,n)
        Flush (nout)

        Do i = 1, n
          select(i) = real(w(i)) < thresh
        End Do

!       Calculate the eigenvectors of H (as specified by SELECT),
!       storing the result in C
!       The NAG name equivalent of zhsein is f08pxf
        Call zhsein('Right','QR','No initial vectors',select,n,a,lda,w,vl,     &
          ldvl,c,ldc,n,m,work,rwork,ifaill,ifailr,info)

!       Calculate the eigenvectors of A = Q * (eigenvectors of H)
!       The NAG name equivalent of zunmhr is f08nuf
        Call zunmhr('Left','No transpose',n,m,1,n,a,lda,tau,c,ldc,work,lwork,  &
          info)

!       Print eigenvectors

        Write (nout,*)
        Flush (nout)

!       Normalize the eigenvectors, largest element real
        Do i = 1, m
          rwork(1:n) = abs(c(1:n,i))
          k = maxloc(rwork(1:n),1)
          scal = conjg(c(k,i))/abs(c(k,i))/dznrm2(n,c(1,i),1)
          c(1:n,i) = c(1:n,i)*scal
        End Do

!       ifail: behaviour on error exit
!              =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
        ifail = 0
        Call x04dbf('General',' ',n,m,c,ldc,'Bracketed','F7.4',                &
          'Contents of array C','Integer',rlabs,'Integer',clabs,80,0,ifail)

      End If

99999 Format ((3X,4(A,F7.4,A,F7.4,A,:)))
    End Program f08nufe


f08nvfe.f90

    Program f08nvfe

!     F08NVF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: dznrm2, m01daf, m01edf, nag_wp, x04dbf, zgebak,   &
                             zgebal, zgehrd, zhseqr, ztrevc, zunghr
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Complex (Kind=nag_wp)            :: scal
      Integer                          :: i, ifail, ihi, ilo, info, k, lda,    &
                                          ldh, ldvl, ldvr, lwork, m, n
!     .. Local Arrays ..
      Complex (Kind=nag_wp), Allocatable :: a(:,:), h(:,:), tau(:), vl(:,:),   &
                                          vr(:,:), vr_row(:), w(:), work(:)
      Real (Kind=nag_wp), Allocatable  :: rwork(:), scale(:)
      Integer, Allocatable             :: irank(:)
      Logical                          :: select(1)
      Character (1)                    :: clabs(1), rlabs(1)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: abs, aimag, conjg, maxloc, real
!     .. Executable Statements ..
      Write (nout,*) 'F08NVF Example Program Results'
      Flush (nout)
!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) n
      ldvl = 1
      lda = n
      ldh = n
      ldvr = n
      lwork = 64*n
      Allocate (a(lda,n),h(ldh,n),tau(n),vl(ldvl,1),vr(ldvr,n),w(n),           &
        work(lwork),rwork(n),scale(n),irank(n))

!     Read A from data file
      Read (nin,*)(a(i,1:n),i=1,n)

!     Balance A
!     The NAG name equivalent of zgebal is f08nvf
      Call zgebal('Both',n,a,lda,ilo,ihi,scale,info)

!     Reduce A to upper Hessenberg form H = (Q**H)*A*Q
!     The NAG name equivalent of zgehrd is f08nsf
      Call zgehrd(n,ilo,ihi,a,lda,tau,work,lwork,info)

!     Copy A to H and VR
      h(1:n,1:n) = a(1:n,1:n)
      vr(1:n,1:n) = a(1:n,1:n)

!     Form Q explicitly, storing the result in VR
!     The NAG name equivalent of zunghr is f08ntf
      Call zunghr(n,1,n,vr,ldvr,tau,work,lwork,info)

!     Calculate the eigenvalues and Schur factorization of A
!     The NAG name equivalent of zhseqr is f08psf
      Call zhseqr('Schur form','Vectors',n,ilo,ihi,h,ldh,w,vr,ldvr,work,lwork, &
        info)

      Write (nout,*)
      If (info>0) Then
        Write (nout,*) 'Failure to converge.'
      Else
!       Sort eigenvalues into descending absolute value
        rwork(1:n) = abs(w(1:n))
!       ifail: behaviour on error exit
!              =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
        ifail = 0
        Call m01daf(rwork,1,n,'Descending',irank,ifail)
!       ifail: behaviour on error exit
!              =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
        ifail = 0
        Call m01edf(w,1,n,irank,ifail)

        Write (nout,*) 'Eigenvalues'
        Write (nout,99999)(' (',real(w(i)),',',aimag(w(i)),')',i=1,n)
        Flush (nout)

!       Calculate the eigenvectors of A, storing the result in VR
!       The NAG name equivalent of ztrevc is f08qxf
        Call ztrevc('Right','Backtransform',select,n,h,ldh,vl,ldvl,vr,ldvr,n,  &
          m,work,rwork,info)

!       The NAG name equivalent of zgebak is f08nwf
        Call zgebak('Both','Right',n,ilo,ihi,scale,m,vr,ldvr,info)

!       Reorder eigenvectors using irank
        Allocate (vr_row(n))
        Do i = 1, n
          vr_row(1:n) = vr(i,1:n)
!         ifail: behaviour on error exit
!                =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
          ifail = 0
          Call m01edf(vr_row,1,n,irank,ifail)
          vr(i,1:n) = vr_row(1:n)
        End Do
        Deallocate (vr_row)

!       Print eigenvectors

        Write (nout,*)
        Flush (nout)

!       Normalize the eigenvectors, largest element real
        Do i = 1, m
          rwork(1:n) = abs(vr(1:n,i))
          k = maxloc(rwork(1:n),1)
          scal = conjg(vr(k,i))/abs(vr(k,i))/dznrm2(n,vr(1,i),1)
          vr(1:n,i) = vr(1:n,i)*scal
        End Do

!       ifail: behaviour on error exit
!              =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
        ifail = 0
        Call x04dbf('General',' ',n,m,vr,ldvr,'Bracketed','F7.4',              &
          'Contents of array VR','Integer',rlabs,'Integer',clabs,80,0,ifail)

      End If

99999 Format ((3X,4(A,F7.4,A,F7.4,A,:)))
    End Program f08nvfe


f08pafe.f90

!   F08PAF Example Program Text
!   Mark 26 Release. NAG Copyright 2016.

    Module f08pafe_mod

!     F08PAF Example Program Module:
!            Parameters and User-defined Routines

!     .. Use Statements ..
      Use nag_library, Only: nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Accessibility Statements ..
      Private
      Public                           :: select
!     .. Parameters ..
      Integer, Parameter, Public       :: nb = 64, nin = 5, nout = 6
    Contains
      Function select(wr,wi)

!       Logical function select for use with DGEES (F08PAF)
!       Returns the value .TRUE. if the eigenvalue is real and positive

!       .. Function Return Value ..
        Logical                        :: select
!       .. Scalar Arguments ..
        Real (Kind=nag_wp), Intent (In) :: wi, wr
!       .. Executable Statements ..
        select = (wr>0._nag_wp .And. wi==0._nag_wp)
        Return
      End Function select
    End Module f08pafe_mod
    Program f08pafe

!     F08PAF Example Main Program

!     .. Use Statements ..
      Use nag_library, Only: dgees, dgemm, dlange => f06raf, nag_wp, x02ajf,   &
                             x04caf
      Use f08pafe_mod, Only: nb, nin, nout, select
!     .. Implicit None Statement ..
      Implicit None
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: alpha, beta, norm
      Integer                          :: i, ifail, info, lda, ldc, ldd, ldvs, &
                                          lwork, n, sdim
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: a(:,:), c(:,:), d(:,:), vs(:,:),     &
                                          wi(:), work(:), wr(:)
      Real (Kind=nag_wp)               :: dummy(1), rwork(1)
      Logical, Allocatable             :: bwork(:)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: max, nint
!     .. Executable Statements ..
      Write (nout,*) 'F08PAF Example Program Results'
      Write (nout,*)
      Flush (nout)
!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) n
      lda = n
      ldc = n
      ldd = n
      ldvs = n
      Allocate (a(lda,n),c(ldc,n),d(ldd,n),vs(ldvs,n),wi(n),wr(n),bwork(n))

!     Use routine workspace query to get optimal workspace.
      lwork = -1
!     The NAG name equivalent of dgees is f08paf
      Call dgees('Vectors (Schur)','Sort',select,n,a,lda,sdim,wr,wi,vs,ldvs,   &
        dummy,lwork,bwork,info)

!     Make sure that there is enough workspace for block size nb.
      lwork = max((nb+2)*n,nint(dummy(1)))
      Allocate (work(lwork))

!     Read in the matrix A
      Read (nin,*)(a(i,1:n),i=1,n)

!     Copy A into D
      d(1:n,1:n) = a(1:n,1:n)

!     Print matrix A
!     ifail: behaviour on error exit
!            =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
      ifail = 0
      Call x04caf('General',' ',n,n,a,lda,'Matrix A',ifail)

      Write (nout,*)
      Flush (nout)

!     Find the Schur factorization of A
!     The NAG name equivalent of dgees is f08paf
      Call dgees('Vectors (Schur)','Sort',select,n,a,lda,sdim,wr,wi,vs,ldvs,   &
        work,lwork,bwork,info)

      If (info==0 .Or. info==(n+2)) Then

!       Compute A - Z*T*Z^T from the factorization of A and store in matrix D
!       The NAG name equivalent of dgemm is f06yaf
        alpha = 1.0_nag_wp
        beta = 0.0_nag_wp
        Call dgemm('N','N',n,n,n,alpha,vs,ldvs,a,lda,beta,c,ldc)
        alpha = -1.0_nag_wp
        beta = 1.0_nag_wp
        Call dgemm('N','T',n,n,n,alpha,c,ldc,vs,ldvs,beta,d,ldd)

!       Find norm of matrix D and print warning if it is too large
!       f06raf is the NAG name equivalent of the LAPACK auxiliary dlange
        norm = dlange('O',ldd,n,d,ldd,rwork)
        If (norm>x02ajf()**0.8_nag_wp) Then
          Write (nout,*) 'Norm of A-(Z*T*Z^T) is much greater than 0.'
          Write (nout,*) 'Schur factorization has failed.'
        Else

!         Print solution
          Write (nout,99999)                                                   &
            'Number of eigenvalues for which SELECT is true = ', sdim,         &
            '(dimension of invariant subspace)'

          Write (nout,*)
!         Print eigenvalues.
          Write (nout,*) 'Selected eigenvalues'
          Write (nout,99997)(' (',wr(i),',',wi(i),')',i=1,sdim)
          Write (nout,*)

          If (info==(n+2)) Then
            Write (nout,99996) '***Note that rounding errors mean ',           &
              'that leading eigenvalues in the Schur form',                    &
              'no longer satisfy SELECT = .TRUE.'
            Write (nout,*)
          End If

        End If

      Else
        Write (nout,99998) 'Failure in DGEES. INFO = ', info
      End If

99999 Format (1X,A,I4,/,1X,A)
99998 Format (1X,A,I4)
99997 Format (1X,A,F8.4,A,F8.4,A)
99996 Format (1X,2A,/,1X,A)
    End Program f08pafe


f08pbfe.f90

!   F08PBF Example Program Text
!   Mark 26 Release. NAG Copyright 2016.

    Module f08pbfe_mod

!     F08PBF Example Program Module:
!            Parameters and User-defined Routines

!     .. Use Statements ..
      Use nag_library, Only: nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Accessibility Statements ..
      Private
      Public                           :: select
!     .. Parameters ..
      Integer, Parameter, Public       :: nb = 64, nin = 5, nout = 6
      Logical, Parameter, Public       :: check_fac = .True.,                  &
                                          print_cond = .False.
    Contains
      Function select(wr,wi)

!       Logical function select for use with DGEESX (F08PBF)
!       Returns the value .TRUE. if the eigenvalue is real and positive

!       .. Function Return Value ..
        Logical                        :: select
!       .. Scalar Arguments ..
        Real (Kind=nag_wp), Intent (In) :: wi, wr
!       .. Executable Statements ..
        select = (wr>0._nag_wp .And. wi==0._nag_wp)
        Return
      End Function select
    End Module f08pbfe_mod
    Program f08pbfe

!     F08PBF Example Main Program

!     .. Use Statements ..
      Use nag_library, Only: dgeesx, dgemm, dlange => f06raf, nag_wp, x02ajf,  &
                             x04caf
      Use f08pbfe_mod, Only: check_fac, nb, nin, nout, print_cond, select
!     .. Implicit None Statement ..
      Implicit None
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: alpha, anorm, beta, eps, norm,       &
                                          rconde, rcondv, tol
      Integer                          :: i, ifail, info, lda, ldc, ldd, ldvs, &
                                          liwork, lwork, n, sdim
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: a(:,:), c(:,:), d(:,:), vs(:,:),     &
                                          wi(:), work(:), wr(:)
      Real (Kind=nag_wp)               :: dummy(1)
      Integer                          :: idum(1)
      Integer, Allocatable             :: iwork(:)
      Logical, Allocatable             :: bwork(:)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: max, nint
!     .. Executable Statements ..
      Write (nout,*) 'F08PBF Example Program Results'
      Write (nout,*)
      Flush (nout)
!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) n
      lda = n
      ldc = n
      ldd = n
      ldvs = n
      Allocate (a(lda,n),c(ldc,n),d(ldd,n),vs(ldvs,n),wi(n),wr(n),bwork(n))

!     Use routine workspace query to get optimal workspace.
      lwork = -1
      liwork = -1
!     The NAG name equivalent of dgeesx is f08pbf
      Call dgeesx('Vectors (Schur)','Sort',select,                             &
        'Both reciprocal condition numbers',n,a,lda,sdim,wr,wi,vs,ldvs,rconde, &
        rcondv,dummy,lwork,idum,liwork,bwork,info)

!     Make sure that there is enough workspace for block size nb.
      liwork = max((n*n)/4,idum(1))
      lwork = max(n*(nb+2+n/2),nint(dummy(1)))
      Allocate (work(lwork),iwork(liwork))

!     Read in the matrix A
      Read (nin,*)(a(i,1:n),i=1,n)

!     Copy A into D
      d(1:n,1:n) = a(1:n,1:n)

!     Print matrix A
!     ifail: behaviour on error exit
!            =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
      ifail = 0
      Call x04caf('General',' ',n,n,a,lda,'Matrix A',ifail)

      Write (nout,*)
      Flush (nout)

!     Find the Frobenius norm of A
!     The NAG name equivalent of the LAPACK auxiliary dlange is f06raf
      anorm = dlange('Frobenius',n,n,a,lda,work)

!     Find the Schur factorization of A
!     The NAG name equivalent of dgeesx is f08pbf
      Call dgeesx('Vectors (Schur)','Sort',select,                             &
        'Both reciprocal condition numbers',n,a,lda,sdim,wr,wi,vs,ldvs,rconde, &
        rcondv,work,lwork,iwork,liwork,bwork,info)

      If (info/=0 .And. info/=(n+2)) Then
        Write (nout,99993) 'Failure in DGEESX. INFO =', info
        Go To 100
      End If

      If (check_fac) Then
!       Compute A - Z*T*Z^T from the factorization of A and store in matrix D
!       The NAG name equivalent of dgemm is f06yaf
        alpha = 1.0_nag_wp
        beta = 0.0_nag_wp
        Call dgemm('N','N',n,n,n,alpha,vs,ldvs,a,lda,beta,c,ldc)
        alpha = -1.0_nag_wp
        beta = 1.0_nag_wp
        Call dgemm('N','T',n,n,n,alpha,c,ldc,vs,ldvs,beta,d,ldd)

!       Find norm of matrix D and print warning if it is too large
!       f06raf is the NAG name equivalent of the LAPACK auxiliary dlange
        norm = dlange('O',ldd,n,d,ldd,work)
        If (norm>x02ajf()**0.8_nag_wp) Then
          Write (nout,*) 'Norm of A-(Z*T*Z^T) is much greater than 0.'
          Write (nout,*) 'Schur factorization has failed.'
          Go To 100
        End If
      End If

!     Print solution
      Write (nout,99999) 'Number of eigenvalues for which SELECT is true = ',  &
        sdim, '(dimension of invariant subspace)'

      Write (nout,*)
!     Print eigenvalues.
      Write (nout,*) 'Selected eigenvalues'
      Write (nout,99998)(' (',wr(i),',',wi(i),')',i=1,sdim)
      Write (nout,*)

      If (info==(n+2)) Then
        Write (nout,99997) '***Note that rounding errors mean ',               &
          'that leading eigenvalues in the Schur form',                        &
          'no longer satisfy SELECT = .TRUE.'
        Write (nout,*)
      End If
      Flush (nout)

      If (print_cond) Then
!       Print out the reciprocal condition numbers
        Write (nout,99996) 'Reciprocal of projection norm onto the invariant', &
          'subspace for the selected eigenvalues', 'RCONDE = ', rconde
        Write (nout,*)
        Write (nout,99995)                                                     &
          'Reciprocal condition number for the invariant subspace',            &
          'RCONDV = ', rcondv

!       Compute the machine precision
        eps = x02ajf()
        tol = eps*anorm

!       Print out the approximate asymptotic error bound on the
!       average absolute error of the selected eigenvalues given by
!       eps*norm(A)/RCONDE
        Write (nout,*)
        Write (nout,99994) 'Approximate asymptotic error bound for selected ', &
          'eigenvalues   = ', tol/rconde

!       Print out an approximate asymptotic bound on the maximum
!       angular error in the computed invariant subspace given by
!       eps*norm(A)/RCONDV
        Write (nout,99994)                                                     &
          'Approximate asymptotic error bound for the invariant ',             &
          'subspace = ', tol/rcondv
      End If
100   Continue

99999 Format (1X,A,I4,/,1X,A)
99998 Format (1X,A,F8.4,A,F8.4,A)
99997 Format (1X,2A,/,1X,A)
99996 Format (1X,A,/,1X,A,/,1X,A,1P,E8.1)
99995 Format (1X,A,/,1X,A,1P,E8.1)
99994 Format (1X,2A,1P,E8.1)
99993 Format (1X,A,I4)
    End Program f08pbfe


f08pefe.f90

    Program f08pefe

!     F08PEF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: dgemm, dhseqr, dlange => f06raf, nag_wp, x02ajf,  &
                             x04caf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: alpha, beta, norm
      Integer                          :: i, ifail, info, ldc, ldd, ldh, ldz,  &
                                          lwork, n
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: c(:,:), d(:,:), h(:,:), wi(:),       &
                                          work(:), wr(:), z(:,:)
!     .. Executable Statements ..
      Write (nout,*) 'F08PEF Example Program Results'
      Flush (nout)

!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) n
      ldc = n
      ldd = n
      ldh = n
      ldz = n
      lwork = n
      Allocate (c(ldc,n),d(ldd,n),h(ldh,n),wi(n),work(lwork),wr(n),z(ldz,n))

!     Read H from data file
      Read (nin,*)(h(i,1:n),i=1,n)

!     Copy H into D
      d(1:n,1:n) = h(1:n,1:n)

!     Print Matrix H
!     ifail: behaviour on error exit
!            =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
      ifail = 0
      Call x04caf('General',' ',n,n,h,ldh,'Matrix H',ifail)

!     Calculate the eigenvalues and Schur factorization of H

!     The NAG name equivalent of dhseqr is f08pef
      Call dhseqr('Schur form','Initialize Z',n,1,n,h,ldh,wr,wi,z,ldz,work,    &
        lwork,info)

      Write (nout,*)
      If (info>0) Then
        Write (nout,*) 'Failure to converge.'
      Else

!       Compute H - Z*T*Z^T from the factorization of A and store in matrix D
!       The NAG name equivalent of dgemm is f06yaf
        alpha = 1.0_nag_wp
        beta = 0.0_nag_wp
        Call dgemm('N','N',n,n,n,alpha,z,ldz,h,ldh,beta,c,ldc)
        alpha = -1.0_nag_wp
        beta = 1.0_nag_wp
        Call dgemm('N','T',n,n,n,alpha,c,ldc,z,ldz,beta,d,ldd)

!       Find norm of matrix D and print warning if it is too large
!       f06raf is the NAG name equivalent of the LAPACK auxiliary dlange
        norm = dlange('O',ldd,n,d,ldd,work)
        If (norm>x02ajf()**0.8_nag_wp) Then
          Write (nout,*) 'Norm of H-(Z*T*Z^T) is much greater than 0.'
          Write (nout,*) 'Schur factorization has failed.'
        Else
!         Print eigenvalues
          Write (nout,*) 'Eigenvalues'
          Write (nout,99999)(' (',wr(i),',',wi(i),')',i=1,n)
        End If
      End If

99999 Format (1X,A,F8.4,A,F8.4,A)
    End Program f08pefe


f08pnfe.f90

    Program f08pnfe

!     F08PNF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: f08pnz, nag_wp, x02ajf, x04dbf, zgees, zgemm,     &
                             zlange => f06uaf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nb = 64, nin = 5, nout = 6
!     .. Local Scalars ..
      Complex (Kind=nag_wp)            :: alpha, beta
      Real (Kind=nag_wp)               :: norm
      Integer                          :: i, ifail, info, lda, ldc, ldd, ldvs, &
                                          lwork, n, sdim
!     .. Local Arrays ..
      Complex (Kind=nag_wp), Allocatable :: a(:,:), c(:,:), d(:,:), vs(:,:),   &
                                          w(:), work(:)
      Complex (Kind=nag_wp)            :: wdum(1)
      Real (Kind=nag_wp), Allocatable  :: rwork(:)
      Logical                          :: dummy(1)
      Character (1)                    :: clabs(1), rlabs(1)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: cmplx, max, nint, real
!     .. Executable Statements ..
      Write (nout,*) 'F08PNF Example Program Results'
      Write (nout,*)
      Flush (nout)
!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) n
      lda = n
      ldc = n
      ldd = n
      ldvs = n
      Allocate (a(lda,n),vs(ldvs,n),c(ldc,n),d(ldd,n),w(n),rwork(n))

!     Use routine workspace query to get optimal workspace.
      lwork = -1
!     The NAG name equivalent of zgees is f08pnf
      Call zgees('Vectors (Schur)','No sort',f08pnz,n,a,lda,sdim,w,vs,ldvs,    &
        wdum,lwork,rwork,dummy,info)

!     Make sure that there is enough workspace for block size nb.
      lwork = max((nb+1)*n,nint(real(wdum(1))))
      Allocate (work(lwork))

!     Read in the matrix A
      Read (nin,*)(a(i,1:n),i=1,n)

!     Copy A into D
      d(1:n,1:n) = a(1:n,1:n)

!     Print matrix A
!     ifail: behaviour on error exit
!            =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
      ifail = 0
      Call x04dbf('General',' ',n,n,a,lda,'Bracketed','F7.4','Matrix A',       &
        'Integer',rlabs,'Integer',clabs,80,0,ifail)

      Write (nout,*)
      Flush (nout)

!     Find the Schur factorization of A
!     The NAG name equivalent of zgees is f08pnf
      Call zgees('Vectors (Schur)','No sort',f08pnz,n,a,lda,sdim,w,vs,ldvs,    &
        work,lwork,rwork,dummy,info)

      If (info>0) Then
        Write (nout,99999) 'Failure in ZGEES. INFO =', info
      Else

!       Compute A - Z*T*Z^H from the factorization of A and store in matrix D
!       The NAG name equivalent of zgemm is f06zaf
        alpha = cmplx(1,kind=nag_wp)
        beta = cmplx(0,kind=nag_wp)
        Call zgemm('N','N',n,n,n,alpha,vs,ldvs,a,lda,beta,c,ldc)
        alpha = cmplx(-1,kind=nag_wp)
        beta = cmplx(1,kind=nag_wp)
        Call zgemm('N','C',n,n,n,alpha,c,ldc,vs,ldvs,beta,d,ldd)

!       Find norm of matrix D and print warning if it is too large
!       f06uaf is the NAG name equivalent of the LAPACK auxiliary zlange
        norm = zlange('O',ldd,n,d,ldd,rwork)
        If (norm>x02ajf()**0.5_nag_wp) Then
          Write (nout,*) 'Norm of A-(Z*T*Z^H) is much greater than 0.'
          Write (nout,*) 'Schur factorization has failed.'
        Else
!         Print eigenvalues.
          Write (nout,*) 'Eigenvalues'
          Write (nout,99998)(i,w(i),i=1,n)
        End If
      End If

99999 Format (1X,A,I4)
99998 Format (1X,I4,2X,' (',F7.4,',',F7.4,')',:)
    End Program f08pnfe


f08ppfe.f90

!   F08PPF Example Program Text
!   Mark 26 Release. NAG Copyright 2016.

    Module f08ppfe_mod

!     F08PPF Example Program Module:
!            Parameters and User-defined Routines

!     .. Use Statements ..
      Use nag_library, Only: nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Accessibility Statements ..
      Private
      Public                           :: select
!     .. Parameters ..
      Integer, Parameter, Public       :: nb = 64, nin = 5, nout = 6
      Logical, Parameter, Public       :: check_fac = .True.,                  &
                                          print_cond = .False.
    Contains
      Function select(w)

!       Logical function select for use with ZGEESX (F08PPF)
!       Returns the value .TRUE. if the real part of the eigenvalue
!       w is positive.

!       .. Function Return Value ..
        Logical                        :: select
!       .. Scalar Arguments ..
        Complex (Kind=nag_wp), Intent (In) :: w
!       .. Intrinsic Procedures ..
        Intrinsic                      :: real
!       .. Executable Statements ..
        select = (real(w)>0._nag_wp)
        Return
      End Function select
    End Module f08ppfe_mod
    Program f08ppfe

!     F08PPF Example Main Program

!     .. Use Statements ..
      Use nag_library, Only: nag_wp, x02ajf, x04dbf, zgeesx, zgemm,            &
                             zlange => f06uaf
      Use f08ppfe_mod, Only: check_fac, nb, nin, nout, print_cond, select
!     .. Implicit None Statement ..
      Implicit None
!     .. Local Scalars ..
      Complex (Kind=nag_wp)            :: alpha, beta
      Real (Kind=nag_wp)               :: anorm, eps, norm, rconde, rcondv,    &
                                          tol
      Integer                          :: i, ifail, info, lda, ldc, ldd, ldvs, &
                                          lwork, n, sdim
!     .. Local Arrays ..
      Complex (Kind=nag_wp), Allocatable :: a(:,:), c(:,:), d(:,:), vs(:,:),   &
                                          w(:), work(:)
      Complex (Kind=nag_wp)            :: dummy(1)
      Real (Kind=nag_wp), Allocatable  :: rwork(:)
      Logical, Allocatable             :: bwork(:)
      Character (1)                    :: clabs(1), rlabs(1)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: cmplx, max, nint, real
!     .. Executable Statements ..
      Write (nout,*) 'F08PPF Example Program Results'
      Write (nout,*)
      Flush (nout)
!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) n
      lda = n
      ldc = n
      ldd = n
      ldvs = n
      Allocate (a(lda,n),c(ldc,n),d(ldd,n),vs(ldvs,n),w(n),rwork(n),bwork(n))

!     Use routine workspace query to get optimal workspace.
      lwork = -1
!     The NAG name equivalent of zgeesx is f08ppf
      Call zgeesx('Vectors (Schur)','Sort',select,                             &
        'Both reciprocal condition numbers',n,a,lda,sdim,w,vs,ldvs,rconde,     &
        rcondv,dummy,lwork,rwork,bwork,info)

!     Make sure that there is enough workspace for block size nb.
      lwork = max(n*(nb+1+n/2),nint(real(dummy(1))))
      Allocate (work(lwork))

!     Read in the matrix A
      Read (nin,*)(a(i,1:n),i=1,n)

!     Copy A into D
      d(1:n,1:n) = a(1:n,1:n)

!     Print matrix A
!     ifail: behaviour on error exit
!            =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
      ifail = 0
      Call x04dbf('General',' ',n,n,a,lda,'Bracketed','F7.4','Matrix A',       &
        'Integer',rlabs,'Integer',clabs,80,0,ifail)

      Write (nout,*)
      Flush (nout)

!     Find the Frobenius norm of A
!     The NAG name equivalent of the LAPACK auxiliary zlange is f06uaf
      anorm = zlange('Frobenius',n,n,a,lda,rwork)

!     Find the Schur factorization of A
!     The NAG name equivalent of zgeesx is f08ppf
      Call zgeesx('Vectors (Schur)','Sort',select,                             &
        'Both reciprocal condition numbers',n,a,lda,sdim,w,vs,ldvs,rconde,     &
        rcondv,work,lwork,rwork,bwork,info)

      If (info/=0 .And. info/=(n+2)) Then
        Write (nout,99993) 'Failure in ZGEESX. INFO =', info
        Go To 100
      End If

      If (check_fac) Then
!       Compute A - Z*T*Z^H from the factorization of A and store in matrix D
!       The NAG name equivalent of zgemm is f06zaf
        alpha = cmplx(1,kind=nag_wp)
        beta = cmplx(0,kind=nag_wp)
        Call zgemm('N','N',n,n,n,alpha,vs,ldvs,a,lda,beta,c,ldc)
        alpha = cmplx(-1,kind=nag_wp)
        beta = cmplx(1,kind=nag_wp)
        Call zgemm('N','C',n,n,n,alpha,c,ldc,vs,ldvs,beta,d,ldd)

!       Find norm of matrix D and print warning if it is too large
!       f06uaf is the NAG name equivalent of the LAPACK auxiliary zlange
        norm = zlange('O',ldd,n,d,ldd,rwork)
        If (norm>x02ajf()**0.5_nag_wp) Then
          Write (nout,*) 'Norm of A-(Z*T*Z^H) is much greater than 0.'
          Write (nout,*) 'Schur factorization has failed.'
          Go To 100
        End If
      End If

!     Print solution
      Write (nout,99999) 'Number of eigenvalues for which SELECT is true = ',  &
        sdim, '(dimension of invariant subspace)'

      Write (nout,*)
!     Print eigenvalues.
      Write (nout,*) 'Selected eigenvalues'
      Write (nout,99998)(i,w(i),i=1,sdim)
      Write (nout,*)

      If (info==(n+2)) Then
        Write (nout,99997) '***Note that rounding errors mean ',               &
          'that leading eigenvalues in the Schur form',                        &
          'no longer satisfy SELECT = .TRUE.'
        Write (nout,*)
      End If
      Flush (nout)

      If (print_cond) Then
!       Print out the reciprocal condition numbers
        Write (nout,99996) 'Reciprocal of projection norm onto the invariant', &
          'subspace for the selected eigenvalues', 'RCONDE = ', rconde
        Write (nout,*)
        Write (nout,99995)                                                     &
          'Reciprocal condition number for the invariant subspace',            &
          'RCONDV = ', rcondv

!       Compute the machine precision
        eps = x02ajf()
        tol = eps*anorm

!       Print out the approximate asymptotic error bound on the
!       average absolute error of the selected eigenvalues given by
!       eps*norm(A)/RCONDE
        Write (nout,*)
        Write (nout,99994) 'Approximate asymptotic error bound for selected ', &
          'eigenvalues   = ', tol/rconde

!       Print out an approximate asymptotic bound on the maximum
!       angular error in the computed invariant subspace given by
!       eps*norm(A)/RCONDV
        Write (nout,99994)                                                     &
          'Approximate asymptotic error bound for the invariant ',             &
          'subspace = ', tol/rcondv
      End If
100   Continue

99999 Format (1X,A,I4,/,1X,A)
99998 Format (1X,I4,2X,' (',F7.4,',',F7.4,')',:)
99997 Format (1X,2A,/,1X,A)
99996 Format (1X,A,/,1X,A,/,1X,A,1P,E8.1)
99995 Format (1X,A,/,1X,A,1P,E8.1)
99994 Format (1X,2A,1P,E8.1)
99993 Format (1X,A,I4)
    End Program f08ppfe


f08psfe.f90

    Program f08psfe

!     F08PSF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: nag_wp, x02ajf, x04dbf, zgemm, zhseqr,            &
                             zlange => f06uaf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Complex (Kind=nag_wp)            :: alpha, beta
      Real (Kind=nag_wp)               :: norm
      Integer                          :: i, ifail, info, ldc, ldd, ldh, ldz,  &
                                          lwork, n
!     .. Local Arrays ..
      Complex (Kind=nag_wp), Allocatable :: c(:,:), d(:,:), h(:,:), w(:),      &
                                          work(:), z(:,:)
      Real (Kind=nag_wp)               :: rwork(1)
      Character (1)                    :: clabs(1), rlabs(1)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: cmplx
!     .. Executable Statements ..
      Write (nout,*) 'F08PSF Example Program Results'
      Write (nout,*)
      Flush (nout)
!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) n
      ldc = n
      ldd = n
      ldh = n
      ldz = n
      lwork = n
      Allocate (c(ldc,n),d(ldd,n),h(ldh,n),w(n),work(lwork),z(ldz,n))

!     Read H from data file

      Read (nin,*)(h(i,1:n),i=1,n)

!     Store H in D
      d(1:ldd,1:n) = h(1:ldh,1:n)

!     Print matrix H
!     ifail: behaviour on error exit
!            =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
      ifail = 0
      Call x04dbf('General',' ',n,n,h,ldh,'Bracketed','F7.4','Matrix H',       &
        'Integer',rlabs,'Integer',clabs,80,0,ifail)

!     Calculate the eigenvalues and Schur factorization of H

!     The NAG name equivalent of zhseqr is f08psf
      Call zhseqr('Schur form','Initialize Z',n,1,n,h,ldh,w,z,ldz,work,lwork,  &
        info)

      Write (nout,*)
      If (info>0) Then
        Write (nout,*) 'Failure to converge.'
      Else

!       Compute A - Z*T*Z^H from Schur factorization of A, and store in matrix
!       D
!       The NAG name equivalent of zgemm is f06zaf
        alpha = cmplx(1,kind=nag_wp)
        beta = cmplx(0,kind=nag_wp)
        Call zgemm('N','N',n,n,n,alpha,z,ldz,h,ldh,beta,c,ldc)
        alpha = cmplx(-1,kind=nag_wp)
        beta = cmplx(1,kind=nag_wp)
        Call zgemm('N','C',n,n,n,alpha,c,ldc,z,ldz,beta,d,ldd)

!       Find norm of matrix D and print warning if it is too large
!       f06uaf is the NAG name equivalent of the LAPACK auxiliary zlange
        norm = zlange('O',ldd,n,d,ldd,rwork)

        If (norm>x02ajf()**0.5_nag_wp) Then
          Write (nout,*) 'Norm of A-(Z*T*Z^H) is much greater than 0.'
          Write (nout,*) 'Schur factorization has failed.'
        Else
!         Print eigenvalues
          Write (nout,*) 'Eigenvalues'
          Write (nout,99999)(w(i),i=1,n)
        End If

      End If

99999 Format ((3X,4(' (',F7.4,',',F7.4,')',:)))
    End Program f08psfe


f08qffe.f90

    Program f08qffe

!     F08QFF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: dtrexc, nag_wp, x04caf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Integer                          :: i, ifail, ifst, ilst, info, ldq,     &
                                          ldt, n
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: q(:,:), t(:,:), work(:)
!     .. Executable Statements ..
      Write (nout,*) 'F08QFF Example Program Results'
      Write (nout,*)
      Flush (nout)
!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) n
      ldq = 1
      ldt = n
      Allocate (q(ldq,1),t(ldt,n),work(n))

!     Read T from data file

      Read (nin,*)(t(i,1:n),i=1,n)

!     Read the row indices

      Read (nin,*) ifst, ilst

!     Reorder the Schur factor T

!     The NAG name equivalent of dtrexc is f08qff
      Call dtrexc('No update',n,t,ldt,q,ldq,ifst,ilst,work,info)
      If (info>0) Then
        Write (nout,99999) info, ilst
        Write (nout,*)
        Flush (nout)
      End If

!     Print reordered Schur factor

!     ifail: behaviour on error exit
!             =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
      ifail = 0
      Call x04caf('General',' ',n,n,t,ldt,'Reordered Schur form',ifail)

99999 Format (' Reordering could not be completed. INFO = ',I3,' ILST = ',I5)
    End Program f08qffe


f08qgfe.f90

    Program f08qgfe

!     F08QGF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: dgemm, dlange => f06raf, dtrsen, nag_wp, x02ajf,  &
                             x04caf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: alpha, beta, norm, s, sep
      Integer                          :: i, ifail, info, lda, ldc, ldq, ldt,  &
                                          liwork, lwork, m, n
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: a(:,:), c(:,:), q(:,:), t(:,:),      &
                                          wi(:), work(:), wr(:)
      Integer, Allocatable             :: iwork(:)
      Logical, Allocatable             :: select(:)
!     .. Executable Statements ..
      Write (nout,*) 'F08QGF Example Program Results'
      Write (nout,*)
      Flush (nout)
!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) n
      lda = n
      ldc = n
      ldq = n
      ldt = n
      liwork = (n*n)/4
      lwork = (n*n)/2
      Allocate (a(lda,n),c(ldc,n),q(ldq,n),t(ldt,n),wi(n),work(lwork),wr(n),   &
        iwork(liwork),select(n))

!     Read T, Q and the logical array SELECT from data file

      Read (nin,*)(t(i,1:n),i=1,n)
      Read (nin,*)(q(i,1:n),i=1,n)

      Read (nin,*) select(1:n)

!     Compute Q * T * Q**T to find  A
!     The NAG name equivalent of dgemm is f06yaf
      alpha = 1._nag_wp
      beta = 0._nag_wp
      Call dgemm('N','N',n,n,n,alpha,q,ldq,t,ldt,beta,c,ldc)
      Call dgemm('N','T',n,n,n,alpha,c,ldc,q,ldq,beta,a,lda)

!     Print Matrix A, as computed from Q * T * Q**T
!     ifail: behaviour on error exit
!            =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
      ifail = 0
      Call x04caf('General',' ',n,n,a,lda,'Matrix A computed from Q*T*Q^T',    &
        ifail)

      Write (nout,*)
      Flush (nout)

!     Reorder the Schur factor T and update the matrix Q to obtain TT and QT

!     The NAG name equivalent of dtrsen is f08qgf
      Call dtrsen('Both','Vectors',select,n,t,ldt,q,ldq,wr,wi,m,s,sep,work,    &
        lwork,iwork,liwork,info)

!     Compute (Q * T * Q^T) - (QT * TT * QT^T) and store in A,
!     i.e. the difference between reconstructed A using Schur and reordered
!          Schur decompositions.
      alpha = 1._nag_wp
      beta = 0._nag_wp
      Call dgemm('N','N',n,n,n,alpha,q,ldq,t,ldt,beta,c,ldc)
      alpha = -1._nag_wp
      beta = 1._nag_wp
      Call dgemm('N','T',n,n,n,alpha,c,ldc,q,ldq,beta,a,lda)

!     Find norm of difference matrix and print warning if it is too large
!     f06raf is the NAG name equivalent of the LAPACK auxiliary dlange
      norm = dlange('O',lda,n,a,lda,work)
      If (norm>x02ajf()**0.8_nag_wp) Then
        Write (nout,*) 'Norm of A - (QT * TT * QT^T) is much greater than 0.'
        Write (nout,*) 'Schur factorization has failed.'
      Else
!       Print Result
        Write (nout,99999) 'Condition number estimate',                        &
          ' of the selected cluster of eigenvalues = ', 1.0_nag_wp/s
        Write (nout,*)
        Write (nout,99999) 'Condition number estimate of the spec',            &
          'ified invariant subspace    = ', 1.0_nag_wp/sep
      End If

99999 Format (1X,A,A,1P,E10.2)
    End Program f08qgfe


f08qhfe.f90

    Program f08qhfe

!     F08QHF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: dtrsyl, nag_wp, x04caf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: scale
      Integer                          :: i, ifail, info, lda, ldb, ldc, m, n, &
                                          sign
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: a(:,:), b(:,:), c(:,:)
!     .. Executable Statements ..
      Write (nout,*) 'F08QHF Example Program Results'
      Write (nout,*)
      Flush (nout)
!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) m, n
      lda = m
      ldb = n
      ldc = m
      sign = 1
      Allocate (a(lda,m),b(ldb,n),c(ldc,n))

!     Read A, B and C from data file

      Read (nin,*)(a(i,1:m),i=1,m)
      Read (nin,*)(b(i,1:n),i=1,n)
      Read (nin,*)(c(i,1:n),i=1,m)

!     Solve the Sylvester equation A*X + X*B = C for X
!     The NAG name equivalent of dtrsyl is f08qhf
      Call dtrsyl('No transpose','No transpose',sign,m,n,a,lda,b,ldb,c,ldc,    &
        scale,info)
      If (info==1) Then
        Write (nout,99999)
        Write (nout,*)
      End If

      Flush (nout)

!     Print X
!     ifail: behaviour on error exit
!             =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
      ifail = 0
      Call x04caf('General',' ',m,n,c,ldc,'Solution Matrix',ifail)

99999 Format (/,' A and B have common or very close eigenvalues.',/,' Pe',     &
        'rturbed values were used to solve the equations')
    End Program f08qhfe


f08qlfe.f90

    Program f08qlfe

!     F08QLF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: dlange => f06raf, dtrevc, dtrsna, nag_wp, x02ajf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: eps, tnorm
      Integer                          :: i, info, ldt, ldvl, ldvr, ldwork, m, &
                                          n
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: s(:), sep(:), t(:,:), vl(:,:),       &
                                          vr(:,:), work(:,:)
      Integer, Allocatable             :: iwork(:)
      Logical                          :: select(1)
!     .. Executable Statements ..
      Write (nout,*) 'F08QLF Example Program Results'
      Write (nout,*)
!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) n
      ldt = n
      ldvl = n
      ldvr = n
      ldwork = n
      Allocate (s(n),sep(n),t(ldt,n),vl(ldvl,n),vr(ldvr,n),work(ldwork,n+6),   &
        iwork(2*n-1))

!     Read T from data file

      Read (nin,*)(t(i,1:n),i=1,n)

!     Calculate the left and right eigenvectors of T

!     The NAG name equivalent of dtrevc is f08qkf
      Call dtrevc('Both','All',select,n,t,ldt,vl,ldvl,vr,ldvr,n,m,work,info)

!     Estimate condition numbers for all the eigenvalues and right
!     eigenvectors of T

!     The NAG name equivalent of dtrsna is f08qlf
      Call dtrsna('Both','All',select,n,t,ldt,vl,ldvl,vr,ldvr,s,sep,n,m,work,  &
        ldwork,iwork,info)

!     Print condition numbers of eigenvalues and right eigenvectors

      Write (nout,*) 'S'
      Write (nout,99999) s(1:m)
      Write (nout,*)
      Write (nout,*) 'SEP'
      Write (nout,99999) sep(1:m)

!     Calculate approximate error estimates (using the 1-norm)

      eps = x02ajf()
!     f06raf is the NAG name equivalent of the LAPACK auxiliary dlange
      tnorm = dlange('1-norm',n,n,t,ldt,work)
      Write (nout,*)
      Write (nout,*) 'Approximate error estimates for eigenvalues ',           &
        'of T (machine-dependent)'
      Write (nout,99999)(eps*tnorm/s(i),i=1,m)
      Write (nout,*)
      Write (nout,*) 'Approximate error estimates for right ',                 &
        'eigenvectors of T (machine-dependent)'
      Write (nout,99999)(eps*tnorm/sep(i),i=1,m)

99999 Format ((3X,1P,7E11.1))
    End Program f08qlfe


f08qtfe.f90

    Program f08qtfe

!     F08QTF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: nag_wp, x04dbf, ztrexc
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Integer                          :: i, ifail, ifst, ilst, info, ldq,     &
                                          ldt, n
!     .. Local Arrays ..
      Complex (Kind=nag_wp), Allocatable :: q(:,:), t(:,:)
      Character (1)                    :: clabs(1), rlabs(1)
!     .. Executable Statements ..
      Write (nout,*) 'F08QTF Example Program Results'
      Write (nout,*)
      Flush (nout)
!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) n
      ldq = 1
      ldt = n
      Allocate (q(ldq,1),t(ldt,n))

!     Read T from data file

      Read (nin,*)(t(i,1:n),i=1,n)

!     Read the row indices

      Read (nin,*) ifst, ilst

!     Reorder the Schur factor T

!     The NAG name equivalent of ztrexc is f08qtf
      Call ztrexc('No update',n,t,ldt,q,ldq,ifst,ilst,info)
      If (info/=0) Then
        Write (nout,99999) info, ilst
        Write (nout,*)
        Flush (nout)
      End If

!     Print reordered Schur form

!     ifail: behaviour on error exit
!             =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
      ifail = 0
      Call x04dbf('General',' ',n,n,t,ldt,'Bracketed','F7.4',                  &
        'Reordered Schur form','Integer',rlabs,'Integer',clabs,80,0,ifail)

99999 Format (' Reordering could not be completed. INFO = ',I3,' ILST = ',I5)
    End Program f08qtfe


f08qufe.f90

    Program f08qufe

!     F08QUF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: nag_wp, x02ajf, x04dbf, zgemm, zlange => f06uaf,  &
                             ztrsen
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Complex (Kind=nag_wp)            :: alpha, beta
      Real (Kind=nag_wp)               :: norm, s, sep
      Integer                          :: i, ifail, info, lda, ldc, ldq, ldt,  &
                                          lwork, m, n
!     .. Local Arrays ..
      Complex (Kind=nag_wp), Allocatable :: a(:,:), c(:,:), q(:,:), t(:,:),    &
                                          w(:), work(:)
      Real (Kind=nag_wp)               :: rwork(1)
      Logical, Allocatable             :: select(:)
      Character (1)                    :: clabs(1), rlabs(1)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: cmplx
!     .. Executable Statements ..
      Write (nout,*) 'F08QUF Example Program Results'
      Write (nout,*)
      Flush (nout)
!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) n
      ldc = n
      lda = n
      ldq = n
      ldt = n
      lwork = (n*n)/2
      Allocate (a(lda,n),c(ldc,n),q(ldq,n),t(ldt,n),w(n),work(lwork),          &
        select(n))

!     Read T, Q and the logical array SELECT from data file

      Read (nin,*)(t(i,1:n),i=1,n)
      Read (nin,*)
      Read (nin,*)(q(i,1:n),i=1,n)
      Read (nin,*)
      Read (nin,*) select(1:n)

!     Compute Q * T * Q**T to find  A
!     The NAG name equivalent of zgemm is f06zaf
      alpha = cmplx(1,kind=nag_wp)
      beta = cmplx(0,kind=nag_wp)
      Call zgemm('N','N',n,n,n,alpha,q,ldq,t,ldt,beta,c,ldc)
      Call zgemm('N','C',n,n,n,alpha,c,ldc,q,ldq,beta,a,lda)

!     Print Matrix A, as computed from Q * T * Q**T
!     ifail: behaviour on error exit
!            =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
      ifail = 0
      Call x04dbf('General',' ',n,n,a,lda,'Bracketed','F7.4',                  &
        'Matrix A created from Q*T*Q^T','Integer',rlabs,'Integer',clabs,80,0,  &
        ifail)

      Write (nout,*)
      Flush (nout)

!     Reorder the Schur factor T and update the matrix Q to obtain TT and QT

!     The NAG name equivalent of ztrsen is f08quf
      Call ztrsen('Both','Vectors',select,n,t,ldt,q,ldq,w,m,s,sep,work,lwork,  &
        info)

!     Compute (Q * T * Q^H) - (QT * TT * QT^H) and store in A,
!     i.e. the difference between reconstructed A using Schur and reordered
!          Schur decompositions.
      alpha = cmplx(1,kind=nag_wp)
      beta = cmplx(0,kind=nag_wp)
      Call zgemm('N','N',n,n,n,alpha,q,ldq,t,ldt,beta,c,ldc)
      alpha = cmplx(-1,kind=nag_wp)
      beta = cmplx(1,kind=nag_wp)
      Call zgemm('N','C',n,n,n,alpha,c,ldc,q,ldq,beta,a,lda)

!     Find norm of difference matrix and print warning if it is too large
!     f06uaf is the NAG name equivalent of the LAPACK auxiliary zlange
      norm = zlange('O',lda,n,a,lda,rwork)
      If (norm>x02ajf()**0.5_nag_wp) Then
        Write (nout,*) 'Norm of A - (QT * TT * QT^H) is much greater than 0.'
        Write (nout,*) 'Schur factorization has failed.'
      Else
!       Print condition estimates
        Write (nout,99999) 'Condition number estimate',                        &
          ' of the selected cluster of eigenvalues = ', 1.0_nag_wp/s
        Write (nout,*)
        Write (nout,99999) 'Condition number estimate of the specified ',      &
          'invariant subspace    = ', 1.0_nag_wp/sep
      End If

99999 Format (1X,A,A,1P,E10.2)
    End Program f08qufe


f08qvfe.f90

    Program f08qvfe

!     F08QVF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: nag_wp, x04dbf, ztrsyl
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: scale
      Integer                          :: i, ifail, info, lda, ldb, ldc, m, n
!     .. Local Arrays ..
      Complex (Kind=nag_wp), Allocatable :: a(:,:), b(:,:), c(:,:)
      Character (1)                    :: clabs(1), rlabs(1)
!     .. Executable Statements ..
      Write (nout,*) 'F08QVF Example Program Results'
      Write (nout,*)
      Flush (nout)
!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) m, n
      lda = m
      ldb = n
      ldc = m
      Allocate (a(lda,m),b(ldb,n),c(ldc,n))

!     Read A, B and C from data file

      Read (nin,*)(a(i,1:m),i=1,m)
      Read (nin,*)(b(i,1:n),i=1,n)
      Read (nin,*)(c(i,1:n),i=1,m)

!     Solve the Sylvester equation A*X + X*B = C for X
!     The NAG name equivalent of ztrsyl is f08qvf
      Call ztrsyl('No transpose','No transpose',1,m,n,a,lda,b,ldb,c,ldc,scale, &
        info)
      If (info>=1) Then
        Write (nout,99999)
        Write (nout,*)
        Flush (nout)
      End If

!     Print X
!     ifail: behaviour on error exit
!             =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
      ifail = 0
      Call x04dbf('General',' ',m,n,c,ldc,'Bracketed','F8.4',                  &
        'Solution Matrix','I',rlabs,'I',clabs,80,0,ifail)

99999 Format (/,' A and B have common or very close eigenvalues.',/,' Pe',     &
        'rturbed values were used to solve the equations')
    End Program f08qvfe


f08qyfe.f90

    Program f08qyfe

!     F08QYF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: f06uaf, nag_wp, x02ajf, ztrevc, ztrsna
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: eps, tnorm
      Integer                          :: i, info, ldt, ldvl, ldvr, ldwork, m, &
                                          n
!     .. Local Arrays ..
      Complex (Kind=nag_wp), Allocatable :: t(:,:), vl(:,:), vr(:,:),          &
                                          work(:,:)
      Real (Kind=nag_wp), Allocatable  :: rwork(:), s(:), sep(:)
      Logical                          :: select(1)
!     .. Executable Statements ..
      Write (nout,*) 'F08QYF Example Program Results'
      Write (nout,*)
!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) n
      ldt = n
      ldvl = n
      ldvr = n
      ldwork = n
      Allocate (t(ldt,n),vl(ldvl,n),vr(ldvr,n),work(ldwork,n+1),rwork(n),s(n), &
        sep(n))

!     Read T from data file

      Read (nin,*)(t(i,1:n),i=1,n)

!     Calculate the left and right eigenvectors of T

!     The NAG name equivalent of ztrevc is f08qxf
      Call ztrevc('Both','All',select,n,t,ldt,vl,ldvl,vr,ldvr,n,m,work,rwork,  &
        info)

!     Estimate condition numbers for all the eigenvalues and right
!     eigenvectors of T

!     The NAG name equivalent of ztrsna is f08qyf
      Call ztrsna('Both','All',select,n,t,ldt,vl,ldvl,vr,ldvr,s,sep,n,m,work,  &
        ldwork,rwork,info)

!     Print condition numbers of eigenvalues and right eigenvectors

      Write (nout,*) 'S'
      Write (nout,99999) s(1:m)
      Write (nout,*)
      Write (nout,*) 'SEP'
      Write (nout,99999) sep(1:m)

!     Calculate approximate error estimates (using the 1-norm)

      eps = x02ajf()
      tnorm = f06uaf('1-norm',n,n,t,ldt,rwork)
      Write (nout,*)
      Write (nout,*) 'Approximate error estimates for eigenvalues ',           &
        'of T (machine-dependent)'
      Write (nout,99999)(eps*tnorm/s(i),i=1,m)
      Write (nout,*)
      Write (nout,*) 'Approximate error estimates for right ',                 &
        'eigenvectors of T (machine-dependent)'
      Write (nout,99999)(eps*tnorm/sep(i),i=1,m)

99999 Format ((3X,1P,7E11.1))
    End Program f08qyfe


f08rafe.f90

    Program f08rafe

!     F08RAF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: dgemm, dorcsd, nag_wp, x04caf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Real (Kind=nag_wp), Parameter    :: one = 1.0_nag_wp
      Real (Kind=nag_wp), Parameter    :: zero = 0.0_nag_wp
      Integer, Parameter               :: nin = 5, nout = 6, recombine = 1,    &
                                          reprint = 0
!     .. Local Scalars ..
      Integer                          :: i, ifail, info, info2, j, ldu, ldu1, &
                                          ldu2, ldv, ldv1t, ldv2t, ldx, ldx11, &
                                          ldx12, ldx21, ldx22, lwork, m, n11,  &
                                          n12, n21, n22, p, q, r
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: theta(:), u(:,:), u1(:,:), u2(:,:),  &
                                          v(:,:), v1t(:,:), v2t(:,:), w(:,:),  &
                                          work(:), x(:,:), x11(:,:), x12(:,:), &
                                          x21(:,:), x22(:,:)
      Real (Kind=nag_wp)               :: wdum(1)
      Integer, Allocatable             :: iwork(:)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: cos, min, nint, sin
!     .. Executable Statements ..
      Write (nout,*) 'F08RAF Example Program Results'
      Write (nout,*)
      Flush (nout)
!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) m, p, q

      r = min(min(p,q),min(m-p,m-q))

      ldx = m
      ldx11 = p
      ldx12 = p
      ldx21 = m - p
      ldx22 = m - p
      ldu = m
      ldu1 = p
      ldu2 = m - p
      ldv = m
      ldv1t = q
      ldv2t = m - q
      Allocate (x(ldx,m),u(ldu,m),v(ldv,m),theta(r),iwork(m),w(ldx,m))
      Allocate (x11(ldx11,q),x12(ldx12,m-q),x21(ldx21,q),x22(ldx22,m-q))
      Allocate (u1(ldu1,p),u2(ldu2,m-p),v1t(ldv1t,q),v2t(ldv2t,m-q))

!     Read and print orthogonal X from data file
!     (as, say, generated by a generalized singular value decomposition).

      Read (nin,*)(x(i,1:m),i=1,m)

!     Print general matrix using simple matrix printing routine x04caf.
!     ifail: behaviour on error exit
!            =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
      ifail = 0
      Call x04caf('G','N',m,m,x,ldx,'    Orthogonal matrix X',ifail)
      Write (nout,*)

!     Compute the complete CS factorization of X:
!        X11 is stored in X(1:p,   1:q), X12 is stored in X(1:p,   q+1:m)
!        X21 is stored in X(p+1:m, 1:q), X22 is stored in X(p+1:m, q+1:m)
!        U1  is stored in U(1:p,   1:p), U2  is stored in U(p+1:m, p+1:m)
!        V1  is stored in V(1:q,   1:q), V2  is stored in V(q+1:m, q+1:m)
      x11(1:p,1:q) = x(1:p,1:q)
      x12(1:p,1:m-q) = x(1:p,q+1:m)
      x21(1:m-p,1:q) = x(p+1:m,1:q)
      x22(1:m-p,1:m-q) = x(p+1:m,q+1:m)

!     Workspace query first to get length of work array for complete CS
!     factorization routine dorcsd/f08raf.
      lwork = -1
      Call dorcsd('Yes U1','Yes U2','Yes V1T','Yes V2T','Column','Default',m,  &
        p,q,x,ldx,x(1,q+1),ldx,x(p+1,1),ldx,x(p+1,q+1),ldx,theta,u,ldu,        &
        u(p+1,p+1),ldu,v,ldv,v(q+1,q+1),ldv,wdum,lwork,iwork,info)
      lwork = nint(wdum(1))
      Allocate (work(lwork))
!     Initialize all of  u, v to zero.
      u(1:m,1:m) = zero
      v(1:m,1:m) = zero

!     This is how you might pass partitions as sub-matrices
      Call dorcsd('Yes U1','Yes U2','Yes V1T','Yes V2T','Column','Default',m,  &
        p,q,x,ldx,x(1,q+1),ldx,x(p+1,1),ldx,x(p+1,q+1),ldx,theta,u,ldu,        &
        u(p+1,p+1),ldu,v,ldv,v(q+1,q+1),ldv,work,lwork,iwork,info)
      If (info/=0) Then
        Write (nout,99999) 'Failure in DORCSD/F08RAF. info =', info
        Go To 100
      End If
!     Print Theta, U1, U2, V1T, V2T using matrix printing routine x04caf.
      Write (nout,99998) 'Components of CS factorization of X:'
      ifail = 0
      Call x04caf('G','N',r,1,theta,r,'    Theta',ifail)
      Write (nout,*)
!     By changes of sign the first r elements of the first row of U1 can be
!     made positive.
      Do i = 1, r
        If (u(1,i)<0.0_nag_wp) Then
          u(1:p,i) = -u(1:p,i)
          u(p+1:m,p+i) = -u(p+1:m,p+i)
          v(i,1:q) = -v(i,1:q)
          v(q+i,q+1:m) = -v(q+i,q+1:m)
        End If
      End Do
      ifail = 0
      Call x04caf('G','N',p,p,u,ldu,'    U1',ifail)
      Write (nout,*)
      ifail = 0
      Call x04caf('G','N',m-p,m-p,u(p+1,p+1),ldu,'    U2',ifail)
      Write (nout,*)
      ifail = 0
      Call x04caf('G','N',q,q,v,ldv,'    V1T',ifail)
      Write (nout,*)
      ifail = 0
      Call x04caf('G','N',m-q,m-q,v(q+1,q+1),ldv,'    V2T',ifail)
      Write (nout,*)

!     And this is how you might pass partitions as separate matrices.
      Call dorcsd('Yes U1','Yes U2','Yes V1T','Yes V2T','Column','Default',m,  &
        p,q,x11,ldx11,x12,ldx12,x21,ldx21,x22,ldx22,theta,u1,ldu1,u2,ldu2,v1t, &
        ldv1t,v2t,ldv2t,work,lwork,iwork,info2)
      If (info2/=0) Then
        Write (nout,99999) 'Failure in DORCSD/F08RAF. info =', info
        Go To 100
      End If

!     Print Theta, U1, U2, V1T, V2T using matrix printing routine x04caf.
      If (reprint/=0) Then
!       By changes of sign the first r elements of the first row of U1 can be
!       made positive.
        Do i = 1, r
          If (u1(1,i)<0.0_nag_wp) Then
            u1(1:p,i) = -u1(1:p,i)
            u2(1:m-p,i) = -u2(1:m-p,i)
            v1t(i,1:q) = -v1t(i,1:q)
            v2t(i,1:m-q) = -v2t(i,1:m-q)
          End If
        End Do
        Write (nout,99998) 'Components of CS factorization of X:'
        ifail = 0
        Call x04caf('G','N',r,1,theta,r,'    Theta',ifail)
        Write (nout,*)
        ifail = 0
        Call x04caf('G','N',p,p,u1,ldu1,'    U1',ifail)
        Write (nout,*)
        ifail = 0
        Call x04caf('G','N',m-p,m-p,u2,ldu2,'    U2',ifail)
        Write (nout,*)
        ifail = 0
        Call x04caf('G','N',q,q,v1t,ldv1t,'    V1T',ifail)
        Write (nout,*)
        ifail = 0
        Call x04caf('G','N',m-q,m-q,v2t,ldv2t,'    V2T',ifail)
        Write (nout,*)
      End If
      If (recombine/=0) Then
!       Recombining should return the original matrix
!       Assemble Sigma_p into X
        x(1:m,1:m) = zero
        n11 = min(p,q) - r
        n12 = min(p,m-q) - r
        n21 = min(m-p,q) - r
        n22 = min(m-p,m-1) - r
!       Top Half
        Do j = 1, n11
          x(j,j) = one
        End Do
        Do j = 1, r
          x(j+n11,j+n11) = cos(theta(j))
          x(j+n11,j+n11+r+n21+n22) = -sin(theta(j))
        End Do
        Do j = 1, n12
          x(j+n11+r,j+n11+r+n21+n22+r) = -one
        End Do
!       Bottom half
        Do j = 1, n22
          x(p+j,q+j) = one
        End Do
        Do j = 1, r
          x(p+n22+j,j+n11) = sin(theta(j))
          x(p+n22+j,j+r+n21+n22) = cos(theta(j))
        End Do
        Do j = 1, n21
          x(p+n22+r+j,n11+r+j) = one
        End Do
!       multiply U * Sigma_p into w
        Call dgemm('n','n',m,m,m,one,u,ldu,x,ldx,zero,w,ldx)
!       form U * Sigma_p * V^T into u
        Call dgemm('n','n',m,m,m,one,w,ldx,v,ldv,zero,u,ldu)

        ifail = 0
        Call x04caf('G','N',m,m,u,ldu,                                         &
          '    Recombined matrix X = U * Sigma_p * V^T',ifail)
      End If

100   Continue

99999 Format (1X,A,I4)
99998 Format (1X,A,/)
    End Program f08rafe


f08rnfe.f90

    Program f08rnfe

!     F08RNF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: nag_wp, x04caf, x04dbf, zgemm, zuncsd
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Complex (Kind=nag_wp), Parameter :: one = (1.0_nag_wp,0.0_nag_wp)
      Complex (Kind=nag_wp), Parameter :: zero = (0.0_nag_wp,0.0_nag_wp)
      Integer, Parameter               :: nin = 5, nout = 6, recombine = 1,    &
                                          reprint = 1
!     .. Local Scalars ..
      Integer                          :: i, ifail, info, info2, j, ldu, ldu1, &
                                          ldu2, ldv, ldv1t, ldv2t, ldx, ldx11, &
                                          ldx12, ldx21, ldx22, lrwork, lwork,  &
                                          m, n11, n12, n21, n22, p, q, r
!     .. Local Arrays ..
      Complex (Kind=nag_wp), Allocatable :: u(:,:), u1(:,:), u2(:,:), v(:,:),  &
                                          v1t(:,:), v2t(:,:), w(:,:), work(:), &
                                          x(:,:), x11(:,:), x12(:,:),          &
                                          x21(:,:), x22(:,:)
      Complex (Kind=nag_wp)            :: wdum(1)
      Real (Kind=nag_wp)               :: rwdum(1)
      Real (Kind=nag_wp), Allocatable  :: rwork(:), theta(:)
      Integer, Allocatable             :: iwork(:)
      Character (1)                    :: clabs(1), rlabs(1)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: cmplx, cos, min, nint, real, sin
!     .. Executable Statements ..
      Write (nout,*) 'F08RNF Example Program Results'
      Write (nout,*)
      Flush (nout)
!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) m, p, q

      r = min(min(p,q),min(m-p,m-q))

      ldx = m
      ldx11 = p
      ldx12 = p
      ldx21 = m - p
      ldx22 = m - p
      ldu = m
      ldu1 = p
      ldu2 = m - p
      ldv = m
      ldv1t = q
      ldv2t = m - q
      Allocate (x(ldx,m),u(ldu,m),v(ldv,m),theta(r),iwork(m),w(ldx,m))
      Allocate (x11(ldx11,q),x12(ldx12,m-q),x21(ldx21,q),x22(ldx22,m-q))
      Allocate (u1(ldu1,p),u2(ldu2,m-p),v1t(ldv1t,q),v2t(ldv2t,m-q))

!     Read (by column) and print unitary X from data file
!      (as, say, generated by a generalized singular value decomposition).

      Do i = 1, m
        Read (nin,*) x(1:m,i)
      End Do

!     Print general complex matrix using matrix printing routine x04dbf.
!     ifail: behaviour on error exit
!            =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
      ifail = 0
      Call x04dbf('General','N',m,m,x,ldx,'Bracketed','F7.4',                  &
        '    Unitary matrix X','Integer',rlabs,'Integer',clabs,80,0,ifail)
      Write (nout,*)

!     Compute the complete CS factorization of X:
!        X11 is stored in X(1:p,   1:q), X12 is stored in X(1:p,   q+1:m)
!        X21 is stored in X(p+1:m, 1:q), X22 is stored in X(p+1:m, q+1:m)
!        U1  is stored in U(1:p,   1:p), U2  is stored in U(p+1:m, p+1:m)
!        V1  is stored in V(1:q,   1:q), V2  is stored in V(q+1:m, q+1:m)
      x11(1:p,1:q) = x(1:p,1:q)
      x12(1:p,1:m-q) = x(1:p,q+1:m)
      x21(1:m-p,1:q) = x(p+1:m,1:q)
      x22(1:m-p,1:m-q) = x(p+1:m,q+1:m)

!     Workspace query first to get length of work array for complete CS
!     factorization routine zuncsd/f08rnf.
      lwork = -1
      lrwork = -1
      Call zuncsd('Yes U1','Yes U2','Yes V1T','Yes V2T','Column','Default',m,  &
        p,q,x,ldx,x(1,q+1),ldx,x(p+1,1),ldx,x(p+1,q+1),ldx,theta,u,ldu,        &
        u(p+1,p+1),ldu,v,ldv,v(q+1,q+1),ldv,wdum,lwork,rwdum,lrwork,iwork,     &
        info)
      lwork = nint(real(wdum(1)))
      lrwork = nint(rwdum(1))
      Allocate (work(lwork),rwork(lrwork))
!     Initialize all of  u, v to zero.
      u(1:m,1:m) = zero
      v(1:m,1:m) = zero

!     This is how you might pass partitions as sub-matrices
      Call zuncsd('Yes U1','Yes U2','Yes V1T','Yes V2T','Column','Default',m,  &
        p,q,x,ldx,x(1,q+1),ldx,x(p+1,1),ldx,x(p+1,q+1),ldx,theta,u,ldu,        &
        u(p+1,p+1),ldu,v,ldv,v(q+1,q+1),ldv,work,lwork,rwork,lrwork,iwork,     &
        info)
      If (info/=0) Then
        Write (nout,99999) 'Failure in ZUNCSD/F08RNF. info =', info
        Go To 100
      End If

!     Print Theta using real matrix printing routine x04caf
!     Note: U1, U2, V1T, V2T not printed since these may differ by a sign
!     change in columns of U1, U2 and corresponding rows of V1T, V2T.
      Write (nout,99998) 'Theta Component of CS factorization of X:'
      ifail = 0
      Call x04caf('G','N',r,1,theta,r,'    Theta',ifail)
      Write (nout,*)

!     And this is how you might pass partitions as separate matrices.
      Call zuncsd('Yes U1','Yes U2','Yes V1T','Yes V2T','Column','Default',m,  &
        p,q,x11,ldx11,x12,ldx12,x21,ldx21,x22,ldx22,theta,u1,ldu1,u2,ldu2,v1t, &
        ldv1t,v2t,ldv2t,work,lwork,rwork,lrwork,iwork,info2)
      If (info/=0) Then
        Write (nout,99999) 'Failure in ZUNCSD/F08RNF. info =', info
        Go To 100
      End If

!     Reprint Theta using matrix printing routine x04caf.
      If (reprint/=0) Then
        Write (nout,99998) 'Components of CS factorization of X:'
        ifail = 0
        Call x04caf('G','N',r,1,theta,r,'    Theta',ifail)
        Write (nout,*)
      End If

      If (recombine/=0) Then
!       Recombining should return the original matrix
!       Assemble Sigma_p into X
        x(1:m,1:m) = zero
        n11 = min(p,q) - r
        n12 = min(p,m-q) - r
        n21 = min(m-p,q) - r
        n22 = min(m-p,m-q) - r
!       Top Half
        Do j = 1, n11
          x(j,j) = one
        End Do
        Do j = 1, r
          x(j+n11,j+n11) = cmplx(cos(theta(j)),0.0_nag_wp,kind=nag_wp)
          x(j+n11,j+n11+r+n21+n22) = cmplx(-sin(theta(j)),0.0_nag_wp,          &
            kind=nag_wp)
        End Do
        Do j = 1, n12
          x(j+n11+r,j+n11+r+n21+n22+r) = -one
        End Do
!       Bottom half
        Do j = 1, n22
          x(p+j,q+j) = one
        End Do
        Do j = 1, r
          x(p+n22+j,j+n11) = cmplx(sin(theta(j)),0.0_nag_wp,kind=nag_wp)
          x(p+n22+j,j+r+n21+n22) = cmplx(cos(theta(j)),0.0_nag_wp,kind=nag_wp)
        End Do
        Do j = 1, n21
          x(p+n22+r+j,n11+r+j) = one
        End Do
!       multiply U * Sigma_p into w
        Call zgemm('n','n',m,m,m,one,u,ldu,x,ldx,zero,w,ldx)
!       form U * Sigma_p * V^T into u
        Call zgemm('n','n',m,m,m,one,w,ldx,v,ldv,zero,u,ldu)

!       Print recombined matrix using complex matrix printing routine x04dbf.
        Write (nout,*)
        ifail = 0
        Call x04dbf('General','N',m,m,u,ldu,'Bracketed','F7.4',                &
          '    Recombined matrix X = U * Sigma_p * V^H','Integer',rlabs,       &
          'Integer',clabs,80,0,ifail)
      End If
100   Continue

99999 Format (1X,A,I4)
99998 Format (/,1X,A,/)
    End Program f08rnfe


f08safe.f90

    Program f08safe

!     F08SAF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: blas_damax_val, ddisna, dsygv, dtrcon, f06rcf,    &
                             nag_wp, x02ajf, x04caf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Real (Kind=nag_wp), Parameter    :: zero = 0.0_nag_wp
      Integer, Parameter               :: nb = 64, nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: anorm, bnorm, eps, r, rcond, rcondb, &
                                          t1, t2, t3
      Integer                          :: i, ifail, info, k, lda, ldb, lwork,  &
                                          n
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: a(:,:), b(:,:), eerbnd(:),           &
                                          rcondz(:), w(:), work(:), zerbnd(:)
      Real (Kind=nag_wp)               :: dummy(1)
      Integer, Allocatable             :: iwork(:)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: abs, max, nint
!     .. Executable Statements ..
      Write (nout,*) 'F08SAF Example Program Results'
      Write (nout,*)
!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) n
      lda = n
      ldb = n
      Allocate (a(lda,n),b(ldb,n),eerbnd(n),rcondz(n),w(n),zerbnd(n),iwork(n))

!     Use routine workspace query to get optimal workspace.
      lwork = -1
!     The NAG name equivalent of dsygv is f08saf
      Call dsygv(1,'Vectors','Upper',n,a,lda,b,ldb,w,dummy,lwork,info)

!     Make sure that there is enough workspace for block size nb.
      lwork = max((nb+2)*n,nint(dummy(1)))
      Allocate (work(lwork))

!     Read the upper triangular parts of the matrices A and B

      Read (nin,*)(a(i,i:n),i=1,n)
      Read (nin,*)(b(i,i:n),i=1,n)

!     Compute the one-norms of the symmetric matrices A and B

      anorm = f06rcf('One norm','Upper',n,a,lda,work)
      bnorm = f06rcf('One norm','Upper',n,b,ldb,work)

!     Solve the generalized symmetric eigenvalue problem
!     A*x = lambda*B*x (ITYPE = 1)

!     The NAG name equivalent of dsygv is f08saf
      Call dsygv(1,'Vectors','Upper',n,a,lda,b,ldb,w,work,lwork,info)

      If (info==0) Then

!       Print solution

        Write (nout,*) 'Eigenvalues'
        Write (nout,99999) w(1:n)

        Write (nout,*)
        Flush (nout)

!       Normalize the eigenvectors, largest positive
        Do i = 1, n
          Call blas_damax_val(n,a(1,i),1,k,r)
          If (a(k,i)<zero) Then
            a(1:n,i) = -a(1:n,i)
          End If
        End Do

!       ifail: behaviour on error exit
!              =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
        ifail = 0
        Call x04caf('General',' ',n,n,a,lda,'Eigenvectors',ifail)

!       Call DTRCON (F07TGF) to estimate the reciprocal condition
!       number of the Cholesky factor of B.  Note that:
!       cond(B) = 1/rcond**2

!       The NAG name equivalent of dtrcon is f07tgf
        Call dtrcon('One norm','Upper','Non-unit',n,b,ldb,rcond,work,iwork,    &
          info)

!       Print the reciprocal condition number of B

        rcondb = rcond**2
        Write (nout,*)
        Write (nout,*) 'Estimate of reciprocal condition number for B'
        Write (nout,99998) rcondb
        Flush (nout)

!       Get the machine precision, eps, and if rcondb is not less
!       than eps**2, compute error estimates for the eigenvalues and
!       eigenvectors

        eps = x02ajf()
        If (rcond>=eps) Then

!         Call DDISNA (F08FLF) to estimate reciprocal condition
!         numbers for the eigenvectors of (A - lambda*B)

          Call ddisna('Eigenvectors',n,n,w,rcondz,info)

!         Compute the error estimates for the eigenvalues and
!         eigenvectors

          t1 = eps/rcondb
          t2 = anorm/bnorm
          t3 = t2/rcond
          Do i = 1, n
            eerbnd(i) = t1*(t2+abs(w(i)))
            zerbnd(i) = t1*(t3+abs(w(i)))/rcondz(i)
          End Do

!         Print the approximate error bounds for the eigenvalues
!         and vectors

          Write (nout,*)
          Write (nout,*) 'Error estimates for the eigenvalues'
          Write (nout,99998) eerbnd(1:n)
          Write (nout,*)
          Write (nout,*) 'Error estimates for the eigenvectors'
          Write (nout,99998) zerbnd(1:n)
        Else
          Write (nout,*)
          Write (nout,*) 'B is very ill-conditioned, error ',                  &
            'estimates have not been computed'
        End If
      Else If (info>n .And. info<=2*n) Then
        i = info - n
        Write (nout,99997) 'The leading minor of order ', i,                   &
          ' of B is not positive definite'
      Else
        Write (nout,99996) 'Failure in DSYGV. INFO =', info
      End If

99999 Format (3X,(6F11.4))
99998 Format (4X,1P,6E11.1)
99997 Format (1X,A,I4,A)
99996 Format (1X,A,I4)
    End Program f08safe


f08sbfe.f90

    Program f08sbfe

!     F08SBF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: blas_damax_val, dsygvx, nag_wp, x04caf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Real (Kind=nag_wp), Parameter    :: zero = 0.0_nag_wp
      Integer, Parameter               :: nb = 64, nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: abstol, r, vl, vu
      Integer                          :: i, ifail, il, info, iu, k, lda, ldb, &
                                          ldz, lwork, m, n
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: a(:,:), b(:,:), w(:), work(:),       &
                                          z(:,:)
      Real (Kind=nag_wp)               :: dummy(1)
      Integer, Allocatable             :: iwork(:), jfail(:)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: max, nint
!     .. Executable Statements ..
      Write (nout,*) 'F08SBF Example Program Results'
      Write (nout,*)
!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) n
      lda = n
      ldb = n
      ldz = n
      m = n
      Allocate (a(lda,n),b(ldb,n),w(n),z(ldz,m),iwork(5*n),jfail(n))

!     Read the lower and upper bounds of the interval to be searched.
      Read (nin,*) vl, vu

!     Use routine workspace query to get optimal workspace.
      lwork = -1
!     The NAG name equivalent of dsygvx is f08sbf
      Call dsygvx(1,'Vectors','Values in range','Upper',n,a,lda,b,ldb,vl,vu,   &
        il,iu,abstol,m,w,z,ldz,dummy,lwork,iwork,jfail,info)

!     Make sure that there is enough workspace for block size nb.
      lwork = max((nb+3)*n,nint(dummy(1)))
      Allocate (work(lwork))

!     Read the upper triangular parts of the matrices A and B

      Read (nin,*)(a(i,i:n),i=1,n)
      Read (nin,*)(b(i,i:n),i=1,n)

!     Set the absolute error tolerance for eigenvalues.  With ABSTOL
!     set to zero, the default value is used instead

      abstol = zero

!     Solve the generalized symmetric eigenvalue problem
!     A*x = lambda*B*x (ITYPE = 1)

!     The NAG name equivalent of dsygvx is f08sbf
      Call dsygvx(1,'Vectors','Values in range','Upper',n,a,lda,b,ldb,vl,vu,   &
        il,iu,abstol,m,w,z,ldz,work,lwork,iwork,jfail,info)

      If (info>=0 .And. info<=n) Then

!       Print solution

        Write (nout,99999) 'Number of eigenvalues found =', m
        Write (nout,*)
        Write (nout,*) 'Eigenvalues'
        Write (nout,99998) w(1:m)
        Flush (nout)

!       Normalize the eigenvectors, largest positive
        Do i = 1, m
          Call blas_damax_val(n,z(1,i),1,k,r)
          If (z(k,i)<zero) Then
            z(1:n,i) = -z(1:n,i)
          End If
        End Do

!       ifail: behaviour on error exit
!              =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
        ifail = 0
        Call x04caf('General',' ',n,m,z,ldz,'Selected eigenvectors',ifail)

        If (info>0) Then
          Write (nout,99999) 'INFO eigenvectors failed to converge, INFO =',   &
            info
          Write (nout,*) 'Indices of eigenvectors that did not converge'
          Write (nout,99997) jfail(1:m)
        End If
      Else If (info>n .And. info<=2*n) Then
        i = info - n
        Write (nout,99996) 'The leading minor of order ', i,                   &
          ' of B is not positive definite'
      Else
        Write (nout,99999) 'Failure in DSYGVX. INFO =', info
      End If

99999 Format (1X,A,I5)
99998 Format (3X,(8F8.4))
99997 Format (3X,(8I8))
99996 Format (1X,A,I4,A)
    End Program f08sbfe


f08scfe.f90

    Program f08scfe

!     F08SCF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: blas_damax_val, ddisna, dsygvd, dtrcon, f06rcf,   &
                             nag_wp, x02ajf, x04caf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Real (Kind=nag_wp), Parameter    :: one = 1.0E+0_nag_wp
      Real (Kind=nag_wp), Parameter    :: zero = 0.0_nag_wp
      Integer, Parameter               :: nb = 64, nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: anorm, bnorm, eps, r, rcond, rcondb, &
                                          t1, t2, t3
      Integer                          :: i, ifail, info, k, lda, ldb, liwork, &
                                          lwork, n
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: a(:,:), b(:,:), eerbnd(:),           &
                                          rcondz(:), w(:), work(:), zerbnd(:)
      Real (Kind=nag_wp)               :: dummy(1)
      Integer                          :: idum(1)
      Integer, Allocatable             :: iwork(:)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: abs, max, nint
!     .. Executable Statements ..
      Write (nout,*) 'F08SCF Example Program Results'
      Write (nout,*)
!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) n
      lda = n
      ldb = n
      Allocate (a(lda,n),b(ldb,n),eerbnd(n),rcondz(n),w(n),zerbnd(n))

!     Use routine workspace query to get optimal workspace.
      lwork = -1
      liwork = -1
!     The NAG name equivalent of dsygvd is f08scf
      Call dsygvd(2,'Vectors','Upper',n,a,lda,b,ldb,w,dummy,lwork,idum,liwork, &
        info)

!     Make sure that there is enough workspace for block size nb.
      lwork = max(1+(nb+6+2*n)*n,nint(dummy(1)))
      liwork = max(3+5*n,idum(1))
      Allocate (work(lwork),iwork(liwork))

!     Read the upper triangular parts of the matrices A and B

      Read (nin,*)(a(i,i:n),i=1,n)
      Read (nin,*)(b(i,i:n),i=1,n)

!     Compute the one-norms of the symmetric matrices A and B

      anorm = f06rcf('One norm','Upper',n,a,lda,work)
      bnorm = f06rcf('One norm','Upper',n,b,ldb,work)

!     Solve the generalized symmetric eigenvalue problem
!     A*B*x = lambda*x (ITYPE = 2)

!     The NAG name equivalent of dsygvd is f08scf
      Call dsygvd(2,'Vectors','Upper',n,a,lda,b,ldb,w,work,lwork,iwork,liwork, &
        info)

      If (info==0) Then

!       Print solution

        Write (nout,*) 'Eigenvalues'
        Write (nout,99999) w(1:n)
        Flush (nout)

!       Normalize the eigenvectors, largest positive
        Do i = 1, n
          Call blas_damax_val(n,a(1,i),1,k,r)
          If (a(k,i)<zero) Then
            a(1:n,i) = -a(1:n,i)
          End If
        End Do

!       ifail: behaviour on error exit
!              =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
        ifail = 0
        Call x04caf('General',' ',n,n,a,lda,'Eigenvectors',ifail)

!       Call DTRCON (F07TGF) to estimate the reciprocal condition
!       number of the Cholesky factor of B.  Note that:
!       cond(B) = 1/RCOND**2

!       The NAG name equivalent of dtrcon is f07tgf
        Call dtrcon('One norm','Upper','Non-unit',n,b,ldb,rcond,work,iwork,    &
          info)

!       Print the reciprocal condition number of B

        rcondb = rcond**2
        Write (nout,*)
        Write (nout,*) 'Estimate of reciprocal condition number for B'
        Write (nout,99998) rcondb
        Flush (nout)

!       Get the machine precision, EPS, and if RCONDB is not less
!       than EPS**2, compute error estimates for the eigenvalues and
!       eigenvectors

        eps = x02ajf()
        If (rcond>=eps) Then

!         Call DDISNA (F08FLF) to estimate reciprocal condition
!         numbers for the eigenvectors of (A*B - lambda*I)

          Call ddisna('Eigenvectors',n,n,w,rcondz,info)

!         Compute the error estimates for the eigenvalues and
!         eigenvectors

          t1 = one/rcond
          t2 = eps*t1
          t3 = anorm*bnorm
          Do i = 1, n
            eerbnd(i) = eps*(t3+abs(w(i))/rcondb)
            zerbnd(i) = t2*(t3/rcondz(i)+t1)
          End Do

!         Print the approximate error bounds for the eigenvalues
!         and vectors

          Write (nout,*)
          Write (nout,*) 'Error estimates for the eigenvalues'
          Write (nout,99998) eerbnd(1:n)
          Write (nout,*)
          Write (nout,*) 'Error estimates for the eigenvectors'
          Write (nout,99998) zerbnd(1:n)
        Else
          Write (nout,*)
          Write (nout,*) 'B is very ill-conditioned, error ',                  &
            'estimates have not been computed'
        End If
      Else If (info>n .And. info<=2*n) Then
        i = info - n
        Write (nout,99997) 'The leading minor of order ', i,                   &
          ' of B is not positive definite'
      Else
        Write (nout,99996) 'Failure in DSYGVD. INFO =', info
      End If

99999 Format (3X,(6F11.4))
99998 Format (4X,1P,6E11.1)
99997 Format (1X,A,I4,A)
99996 Format (1X,A,I4)
    End Program f08scfe


f08sefe.f90

    Program f08sefe

!     F08SEF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: dpotrf, dsterf, dsygst, dsytrd, nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Integer                          :: i, info, lda, ldb, lwork, n
      Character (1)                    :: uplo
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: a(:,:), b(:,:), d(:), e(:), tau(:),  &
                                          work(:)
!     .. Executable Statements ..
      Write (nout,*) 'F08SEF Example Program Results'
!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) n
      lda = n
      ldb = n
      lwork = 64*n
      Allocate (a(lda,n),b(ldb,n),d(n),e(n-1),tau(n),work(lwork))

!     Read A and B from data file

      Read (nin,*) uplo
      If (uplo=='U') Then
        Read (nin,*)(a(i,i:n),i=1,n)
        Read (nin,*)(b(i,i:n),i=1,n)
      Else If (uplo=='L') Then
        Read (nin,*)(a(i,1:i),i=1,n)
        Read (nin,*)(b(i,1:i),i=1,n)
      End If

!     Compute the Cholesky factorization of B
!     The NAG name equivalent of dpotrf is f07fdf
      Call dpotrf(uplo,n,b,ldb,info)

      Write (nout,*)
      If (info>0) Then
        Write (nout,*) 'B is not positive definite.'
      Else

!       Reduce the problem to standard form C*y = lambda*y, storing
!       the result in A
!       The NAG name equivalent of dsygst is f08sef
        Call dsygst(1,uplo,n,a,lda,b,ldb,info)

!       Reduce C to tridiagonal form T = (Q**T)*C*Q
!       The NAG name equivalent of dsytrd is f08fef
        Call dsytrd(uplo,n,a,lda,d,e,tau,work,lwork,info)

!       Calculate the eigenvalues of T (same as C)
!       The NAG name equivalent of dsterf is f08jff
        Call dsterf(n,d,e,info)

        If (info>0) Then
          Write (nout,*) 'Failure to converge.'
        Else

!         Print eigenvalues

          Write (nout,*) 'Eigenvalues'
          Write (nout,99999) d(1:n)
        End If
      End If

99999 Format (3X,(9F8.4))
    End Program f08sefe


f08snfe.f90

    Program f08snfe

!     F08SNF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: ddisna, f06ucf, nag_wp, x02ajf, x04daf, zhegv,    &
                             ztrcon
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nb = 64, nin = 5, nout = 6
!     .. Local Scalars ..
      Complex (Kind=nag_wp)            :: scal
      Real (Kind=nag_wp)               :: anorm, bnorm, eps, rcond, rcondb,    &
                                          t1, t2, t3
      Integer                          :: i, ifail, info, k, lda, ldb, lwork,  &
                                          n
!     .. Local Arrays ..
      Complex (Kind=nag_wp), Allocatable :: a(:,:), b(:,:), work(:)
      Complex (Kind=nag_wp)            :: dummy(1)
      Real (Kind=nag_wp), Allocatable  :: eerbnd(:), rcondz(:), rwork(:),      &
                                          w(:), zerbnd(:)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: abs, conjg, max, maxloc, nint, real
!     .. Executable Statements ..
      Write (nout,*) 'F08SNF Example Program Results'
      Write (nout,*)
!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) n
      lda = n
      ldb = n
      Allocate (a(lda,n),b(ldb,n),eerbnd(n),rcondz(n),rwork(3*n-2),w(n),       &
        zerbnd(n))

!     Use routine workspace query to get optimal workspace.
      lwork = -1
!     The NAG name equivalent of zhegv is f08snf
      Call zhegv(1,'Vectors','Upper',n,a,lda,b,ldb,w,dummy,lwork,rwork,info)

!     Make sure that there is enough workspace for block size nb.
      lwork = max((nb+1)*n,nint(real(dummy(1))))
      Allocate (work(lwork))

!     Read the upper triangular parts of the matrices A and B

      Read (nin,*)(a(i,i:n),i=1,n)
      Read (nin,*)(b(i,i:n),i=1,n)

!     Compute the one-norms of the symmetric matrices A and B

      anorm = f06ucf('One norm','Upper',n,a,lda,rwork)
      bnorm = f06ucf('One norm','Upper',n,b,ldb,rwork)

!     Solve the generalized Hermitian eigenvalue problem
!     A*x = lambda*B*x (itype = 1)

!     The NAG name equivalent of zhegv is f08snf
      Call zhegv(1,'Vectors','Upper',n,a,lda,b,ldb,w,work,lwork,rwork,info)

      If (info==0) Then

!       Print solution

        Write (nout,*) 'Eigenvalues'
        Write (nout,99999) w(1:n)
        Flush (nout)

!       Normalize the eigenvectors, largest element real
!       (normalization w.r.t B unaffected: Z^HBZ = I).
        Do i = 1, n
          rwork(1:n) = abs(a(1:n,i))
          k = maxloc(rwork(1:n),1)
          scal = conjg(a(k,i))/abs(a(k,i))
          a(1:n,i) = a(1:n,i)*scal
        End Do

!       ifail: behaviour on error exit
!              =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
        ifail = 0
        Call x04daf('General',' ',n,n,a,lda,'Eigenvectors',ifail)

!       Call ZTRCON (F07TUF) to estimate the reciprocal condition
!       number of the Cholesky factor of B.  Note that:
!       cond(B) = 1/rcond**2
        Call ztrcon('One norm','Upper','Non-unit',n,b,ldb,rcond,work,rwork,    &
          info)

!       Print the reciprocal condition number of B

        rcondb = rcond**2
        Write (nout,*)
        Write (nout,*) 'Estimate of reciprocal condition number for B'
        Write (nout,99998) rcondb
        Flush (nout)

!       Get the machine precision, eps, and if rcondb is not less
!       than eps**2, compute error estimates for the eigenvalues and
!       eigenvectors

        eps = x02ajf()
        If (rcond>=eps) Then

!         Call DDISNA (F08FLF) to estimate reciprocal condition
!         numbers for the eigenvectors of (A - lambda*B)

          Call ddisna('Eigenvectors',n,n,w,rcondz,info)

!         Compute the error estimates for the eigenvalues and
!         eigenvectors

          t1 = eps/rcondb
          t2 = anorm/bnorm
          t3 = t2/rcond
          Do i = 1, n
            eerbnd(i) = t1*(t2+abs(w(i)))
            zerbnd(i) = t1*(t3+abs(w(i)))/rcondz(i)
          End Do

!         Print the approximate error bounds for the eigenvalues
!         and vectors

          Write (nout,*)
          Write (nout,*) 'Error estimates for the eigenvalues'
          Write (nout,99998) eerbnd(1:n)
          Write (nout,*)
          Write (nout,*) 'Error estimates for the eigenvectors'
          Write (nout,99998) zerbnd(1:n)
        Else
          Write (nout,*)
          Write (nout,*) 'B is very ill-conditioned, error ',                  &
            'estimates have not been computed'
        End If
      Else If (info>n) Then
        i = info - n
        Write (nout,99997) 'The leading minor of order ', i,                   &
          ' of B is not positive definite'
      Else
        Write (nout,99996) 'Failure in ZHEGV. INFO =', info
      End If

99999 Format (3X,(6F11.4))
99998 Format (4X,1P,6E11.1)
99997 Format (1X,A,I4,A)
99996 Format (1X,A,I4)
    End Program f08snfe


f08spfe.f90

    Program f08spfe

!     F08SPF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: nag_wp, x04daf, zhegvx
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Real (Kind=nag_wp), Parameter    :: zero = 0.0E+0_nag_wp
      Integer, Parameter               :: nb = 64, nin = 5, nout = 6
!     .. Local Scalars ..
      Complex (Kind=nag_wp)            :: scal
      Real (Kind=nag_wp)               :: abstol, vl, vu
      Integer                          :: i, ifail, il, info, iu, k, lda, ldb, &
                                          ldz, lwork, m, n
!     .. Local Arrays ..
      Complex (Kind=nag_wp), Allocatable :: a(:,:), b(:,:), work(:), z(:,:)
      Complex (Kind=nag_wp)            :: dummy(1)
      Real (Kind=nag_wp), Allocatable  :: rwork(:), w(:)
      Integer, Allocatable             :: iwork(:), jfail(:)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: abs, conjg, max, maxloc, nint, real
!     .. Executable Statements ..
      Write (nout,*) 'F08SPF Example Program Results'
      Write (nout,*)
!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) n
      lda = n
      ldb = n
      ldz = n
      m = n
      Allocate (a(lda,n),b(ldb,n),z(ldz,m),rwork(7*n),w(n),iwork(5*n),         &
        jfail(n))

!     Read the lower and upper bounds of the interval to be searched.
      Read (nin,*) vl, vu

!     Use routine workspace query to get optimal workspace.
      lwork = -1
!     The NAG name equivalent of zhegvx is f08spf
      Call zhegvx(1,'Vectors','Values in range','Upper',n,a,lda,b,ldb,vl,vu,   &
        il,iu,abstol,m,w,z,ldz,dummy,lwork,rwork,iwork,jfail,info)

!     Make sure that there is enough workspace for block size nb.
      lwork = max((nb+1)*n,nint(real(dummy(1))))
      Allocate (work(lwork))

!     Read the upper triangular parts of the matrices A and B

      Read (nin,*)(a(i,i:n),i=1,n)
      Read (nin,*)(b(i,i:n),i=1,n)

!     Set the absolute error tolerance for eigenvalues.  With abstol
!     set to zero, the default value is used instead

      abstol = zero

!     Solve the generalized Hermitian eigenvalue problem
!     A*x = lambda*B*x (itype = 1)

!     The NAG name equivalent of zhegvx is f08spf
      Call zhegvx(1,'Vectors','Values in range','Upper',n,a,lda,b,ldb,vl,vu,   &
        il,iu,abstol,m,w,z,ldz,work,lwork,rwork,iwork,jfail,info)

      If (info>=0 .And. info<=n) Then

!       Print solution

        Write (nout,99999) 'Number of eigenvalues found =', m
        Write (nout,*)
        Write (nout,*) 'Eigenvalues'
        Write (nout,99998) w(1:m)
        Flush (nout)

!       Normalize the eigenvectors, largest element real
        Do i = 1, m
          rwork(1:n) = abs(z(1:n,i))
          k = maxloc(rwork(1:n),1)
          scal = conjg(z(k,i))/abs(z(k,i))
          z(1:n,i) = z(1:n,i)*scal
        End Do

!       ifail: behaviour on error exit
!              =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
        ifail = 0
        Call x04daf('General',' ',n,m,z,ldz,'Selected eigenvectors',ifail)

        If (info>0) Then
          Write (nout,99999) 'INFO eigenvectors failed to converge, INFO =',   &
            info
          Write (nout,*) 'Indices of eigenvectors that did not converge'
          Write (nout,99997) jfail(1:m)
        End If
      Else If (info>n .And. info<=2*n) Then
        i = info - n
        Write (nout,99996) 'The leading minor of order ', i,                   &
          ' of B is not positive definite'
      Else
        Write (nout,99999) 'Failure in ZHEGVX. INFO =', info
      End If

99999 Format (1X,A,I5)
99998 Format (3X,(8F8.4))
99997 Format (3X,(8I8))
99996 Format (1X,A,I4,A)
    End Program f08spfe


f08sqfe.f90

    Program f08sqfe

!     F08SQF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: ddisna, nag_wp, x02ajf, x04daf, zhegvd,           &
                             zlanhe => f06ucf, ztrcon
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Real (Kind=nag_wp), Parameter    :: one = 1.0E+0_nag_wp
      Integer, Parameter               :: nb = 64, nin = 5, nout = 6
!     .. Local Scalars ..
      Complex (Kind=nag_wp)            :: scal
      Real (Kind=nag_wp)               :: anorm, bnorm, eps, rcond, rcondb,    &
                                          t1, t2
      Integer                          :: i, ifail, info, k, lda, ldb, liwork, &
                                          lrwork, lwork, n
!     .. Local Arrays ..
      Complex (Kind=nag_wp), Allocatable :: a(:,:), b(:,:), work(:)
      Complex (Kind=nag_wp)            :: cdum(1)
      Real (Kind=nag_wp), Allocatable  :: eerbnd(:), rcondz(:), rwork(:),      &
                                          w(:), zerbnd(:)
      Real (Kind=nag_wp)               :: rdum(1)
      Integer                          :: idum(1)
      Integer, Allocatable             :: iwork(:)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: abs, conjg, max, maxloc, nint, real
!     .. Executable Statements ..
      Write (nout,*) 'F08SQF Example Program Results'
      Write (nout,*)
!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) n
      lda = n
      ldb = n
      Allocate (a(lda,n),b(ldb,n),eerbnd(n),rcondz(n),w(n),zerbnd(n))

!     Use routine workspace query to get optimal workspace.
      lwork = -1
      liwork = -1
      lrwork = -1
!     The NAG name equivalent of zhegvd is f08sqf
      Call zhegvd(2,'Vectors','Upper',n,a,lda,b,ldb,w,cdum,lwork,rdum,lrwork,  &
        idum,liwork,info)

!     Make sure that there is enough workspace for block size nb.
      lwork = max((nb+2+n)*n,nint(real(cdum(1))))
      lrwork = max(1+(5+2*n)*n,nint(rdum(1)))
      liwork = max(3+5*n,idum(1))
      Allocate (work(lwork),rwork(lrwork),iwork(liwork))

!     Read the upper triangular parts of the matrices A and B

      Read (nin,*)(a(i,i:n),i=1,n)
      Read (nin,*)(b(i,i:n),i=1,n)

!     Compute the one-norms of the symmetric matrices A and B

!     f06ucf is the NAG name equivalent of the LAPACK auxiliary zlanhe
      anorm = zlanhe('One norm','Upper',n,a,lda,rwork)
      bnorm = zlanhe('One norm','Upper',n,b,ldb,rwork)

!     Solve the generalized Hermitian eigenvalue problem
!     A*B*x = lambda*x (itype = 2)
!     The NAG name equivalent of zhegvd is f08sqf
      Call zhegvd(2,'Vectors','Upper',n,a,lda,b,ldb,w,work,lwork,rwork,lrwork, &
        iwork,liwork,info)

      If (info==0) Then

!       Print solution

        Write (nout,*) 'Eigenvalues'
        Write (nout,99999) w(1:n)
        Flush (nout)

!       Normalize the eigenvectors, largest element real
        Do i = 1, n
          rwork(1:n) = abs(a(1:n,i))
          k = maxloc(rwork(1:n),1)
          scal = conjg(a(k,i))/abs(a(k,i))
          a(1:n,i) = a(1:n,i)*scal
        End Do

!       ifail: behaviour on error exit
!              =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
        ifail = 0
        Call x04daf('General',' ',n,n,a,lda,'Eigenvectors',ifail)

!       Call ZTRCON (F07TUF) to estimate the reciprocal condition
!       number of the Cholesky factor of B.  Note that:
!       cond(B) = 1/rcond**2
        Call ztrcon('One norm','Upper','Non-unit',n,b,ldb,rcond,work,rwork,    &
          info)

!       Print the reciprocal condition number of B

        rcondb = rcond**2
        Write (nout,*)
        Write (nout,*) 'Estimate of reciprocal condition number for B'
        Write (nout,99998) rcondb
        Flush (nout)

!       Get the machine precision, eps, and if rcondb is not less
!       than eps**2, compute error estimates for the eigenvalues and
!       eigenvectors

        eps = x02ajf()
        If (rcond>=eps) Then

!         Call DDISNA (F08FLF) to estimate reciprocal condition
!         numbers for the eigenvectors of (A*B - lambda*I)

          Call ddisna('Eigenvectors',n,n,w,rcondz,info)

!         Compute the error estimates for the eigenvalues and
!         eigenvectors

          t1 = one/rcond
          t2 = anorm*bnorm
          Do i = 1, n
            eerbnd(i) = (t2+abs(w(i))/rcondb)
            zerbnd(i) = t1*(t2/rcondz(i)+t1)
          End Do

!         Print the approximate error bounds for the eigenvalues
!         and vectors

          Write (nout,*)
          Write (nout,*) 'Error estimates (relative to machine precision)'
          Write (nout,*) 'for the eigenvalues:'
          Write (nout,99998) eerbnd(1:n)
          Write (nout,*)
          Write (nout,*) 'for the eigenvectors:'
          Write (nout,99998) zerbnd(1:n)
        Else
          Write (nout,*)
          Write (nout,*) 'B is very ill-conditioned, error ',                  &
            'estimates have not been computed'
        End If
      Else If (info>n) Then
        i = info - n
        Write (nout,99997) 'The leading minor of order ', i,                   &
          ' of B is not positive definite'
      Else
        Write (nout,99996) 'Failure in ZHEGVD. INFO =', info
      End If

99999 Format (3X,(6F11.4))
99998 Format (4X,1P,6E11.1)
99997 Format (1X,A,I4,A)
99996 Format (1X,A,I4)
    End Program f08sqfe


f08ssfe.f90

    Program f08ssfe

!     F08SSF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: dsterf, nag_wp, zhegst, zhetrd, zpotrf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Integer                          :: i, info, lda, ldb, lwork, n
      Character (1)                    :: uplo
!     .. Local Arrays ..
      Complex (Kind=nag_wp), Allocatable :: a(:,:), b(:,:), tau(:), work(:)
      Real (Kind=nag_wp), Allocatable  :: d(:), e(:)
!     .. Executable Statements ..
      Write (nout,*) 'F08SSF Example Program Results'
!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) n
      lda = n
      ldb = n
      lwork = 64*n
      Allocate (a(lda,n),b(ldb,n),tau(n),work(lwork),d(n),e(n-1))

!     Read A and B from data file

      Read (nin,*) uplo
      If (uplo=='U') Then
        Read (nin,*)(a(i,i:n),i=1,n)
        Read (nin,*)(b(i,i:n),i=1,n)
      Else If (uplo=='L') Then
        Read (nin,*)(a(i,1:i),i=1,n)
        Read (nin,*)(b(i,1:i),i=1,n)
      End If

!     Compute the Cholesky factorization of B
!     The NAG name equivalent of zpotrf is f07frf
      Call zpotrf(uplo,n,b,ldb,info)

      Write (nout,*)
      If (info>0) Then
        Write (nout,*) 'B is not positive definite.'
      Else

!       Reduce the problem to standard form C*y = lambda*y, storing
!       the result in A
!       The NAG name equivalent of zhegst is f08ssf
        Call zhegst(1,uplo,n,a,lda,b,ldb,info)

!       Reduce C to tridiagonal form T = (Q**H)*C*Q
!       The NAG name equivalent of zhetrd is f08fsf
        Call zhetrd(uplo,n,a,lda,d,e,tau,work,lwork,info)

!       Calculate the eigenvalues of T (same as C)
!       The NAG name equivalent of dsterf is f08jff
        Call dsterf(n,d,e,info)

        If (info>0) Then
          Write (nout,*) 'Failure to converge.'
        Else

!         Print eigenvalues

          Write (nout,*) 'Eigenvalues'
          Write (nout,99999) d(1:n)
        End If
      End If

99999 Format (3X,(9F8.4))
    End Program f08ssfe


f08tafe.f90

    Program f08tafe

!     F08TAF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: dspgv, dtpcon, f06rdf, nag_wp, x02ajf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
      Character (1), Parameter         :: uplo = 'U'
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: anorm, bnorm, eps, rcond, rcondb,    &
                                          t1, t2
      Integer                          :: i, info, j, n
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: ap(:), bp(:), eerbnd(:), w(:),       &
                                          work(:)
      Real (Kind=nag_wp)               :: dummy(1,1)
      Integer, Allocatable             :: iwork(:)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: abs
!     .. Executable Statements ..
      Write (nout,*) 'F08TAF Example Program Results'
      Write (nout,*)
!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) n

      Allocate (ap((n*(n+1))/2),bp((n*(n+1))/2),eerbnd(n),w(n),work(3*n),iwork &
        (n))

!     Read the upper or lower triangular parts of the matrices A and
!     B from data file

      If (uplo=='U') Then
        Read (nin,*)((ap(i+(j*(j-1))/2),j=i,n),i=1,n)
        Read (nin,*)((bp(i+(j*(j-1))/2),j=i,n),i=1,n)
      Else If (uplo=='L') Then
        Read (nin,*)((ap(i+((2*n-j)*(j-1))/2),j=1,i),i=1,n)
        Read (nin,*)((bp(i+((2*n-j)*(j-1))/2),j=1,i),i=1,n)
      End If

!     Compute the one-norms of the symmetric matrices A and B

      anorm = f06rdf('One norm',uplo,n,ap,work)
      bnorm = f06rdf('One norm',uplo,n,bp,work)

!     Solve the generalized symmetric eigenvalue problem
!     A*x = lambda*B*x (itype = 1)

!     The NAG name equivalent of dspgv is f08taf
      Call dspgv(1,'No vectors',uplo,n,ap,bp,w,dummy,1,work,info)

      If (info==0) Then

!       Print solution

        Write (nout,*) 'Eigenvalues'
        Write (nout,99999) w(1:n)

!       Call DTPCON (F07UGF) to estimate the reciprocal condition
!       number of the Cholesky factor of B.  Note that:
!       cond(B) = 1/rcond**2

        Call dtpcon('One norm',uplo,'Non-unit',n,bp,rcond,work,iwork,info)

!       Print the reciprocal condition number of B

        rcondb = rcond**2
        Write (nout,*)
        Write (nout,*) 'Estimate of reciprocal condition number for B'
        Write (nout,99998) rcondb

!       Get the machine precision, eps, and if rcondb is not less
!       than eps**2, compute error estimates for the eigenvalues

        eps = x02ajf()
        If (rcond>=eps) Then
          t1 = eps/rcondb
          t2 = anorm/bnorm
          Do i = 1, n
            eerbnd(i) = t1*(t2+abs(w(i)))
          End Do

!         Print the approximate error bounds for the eigenvalues

          Write (nout,*)
          Write (nout,*) 'Error estimates for the eigenvalues'
          Write (nout,99998) eerbnd(1:n)
        Else
          Write (nout,*)
          Write (nout,*) 'B is very ill-conditioned, error ',                  &
            'estimates have not been computed'
        End If
      Else If (info>n .And. info<=2*n) Then
        i = info - n
        Write (nout,99997) 'The leading minor of order ', i,                   &
          ' of B is not positive definite'
      Else
        Write (nout,99996) 'Failure in DSPGV. INFO =', info
      End If

99999 Format (3X,(6F11.4))
99998 Format (4X,1P,6E11.1)
99997 Format (1X,A,I4,A)
99996 Format (1X,A,I4)
    End Program f08tafe


f08tbfe.f90

    Program f08tbfe

!     F08TBF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: blas_damax_val, dspgvx, nag_wp, x04caf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Real (Kind=nag_wp), Parameter    :: zero = 0.0E+0_nag_wp
      Integer, Parameter               :: nin = 5, nout = 6
      Character (1), Parameter         :: uplo = 'U'
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: abstol, r, vl, vu
      Integer                          :: i, ifail, il, info, iu, j, k, ldz,   &
                                          m, n
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: ap(:), bp(:), w(:), work(:), z(:,:)
      Integer, Allocatable             :: iwork(:), jfail(:)
!     .. Executable Statements ..
      Write (nout,*) 'F08TBF Example Program Results'
      Write (nout,*)
!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) n
      ldz = n
      m = n
      Allocate (ap((n*(n+1))/2),bp((n*(n+1))/2),w(n),work(8*n),z(ldz,m),iwork( &
        5*n),jfail(n))

!     Read the lower and upper bounds of the interval to be searched,
!     and read the upper or lower triangular parts of the matrices A
!     and B from data file

      Read (nin,*) vl, vu
      If (uplo=='U') Then
        Read (nin,*)((ap(i+(j*(j-1))/2),j=i,n),i=1,n)
        Read (nin,*)((bp(i+(j*(j-1))/2),j=i,n),i=1,n)
      Else If (uplo=='L') Then
        Read (nin,*)((ap(i+((2*n-j)*(j-1))/2),j=1,i),i=1,n)
        Read (nin,*)((bp(i+((2*n-j)*(j-1))/2),j=1,i),i=1,n)
      End If

!     Set the absolute error tolerance for eigenvalues. With abstol
!     set to zero, the default value is used instead

      abstol = zero

!     Solve the generalized symmetric eigenvalue problem
!     A*x = lambda*B*x (itype = 1)

!     The NAG name equivalent of dspgvx is f08tbf
      Call dspgvx(1,'Vectors','Values in range',uplo,n,ap,bp,vl,vu,il,iu,      &
        abstol,m,w,z,ldz,work,iwork,jfail,info)

      If (info>=0 .And. info<=n) Then

!       Print solution

        Write (nout,99999) 'Number of eigenvalues found =', m
        Write (nout,*)
        Write (nout,*) 'Eigenvalues'
        Write (nout,99998) w(1:m)
        Flush (nout)

!       Normalize the eigenvectors, largest positive
        Do i = 1, m
          Call blas_damax_val(n,z(1,i),1,k,r)
          If (z(k,i)<zero) Then
            z(1:n,i) = -z(1:n,i)
          End If
        End Do

!       ifail: behaviour on error exit
!              =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
        ifail = 0
        Call x04caf('General',' ',n,m,z,ldz,'Selected eigenvectors',ifail)

        If (info>0) Then
          Write (nout,99999) 'INFO eigenvectors failed to converge, INFO =',   &
            info
          Write (nout,*) 'Indices of eigenvectors that did not converge'
          Write (nout,99997) jfail(1:m)
        End If
      Else If (info>n .And. info<=2*n) Then
        i = info - n
        Write (nout,99996) 'The leading minor of order ', i,                   &
          ' of B is not positive definite'
      Else
        Write (nout,99999) 'Failure in DSPGVX. INFO =', info
      End If

99999 Format (1X,A,I5)
99998 Format (3X,(8F8.4))
99997 Format (3X,(8I8))
99996 Format (1X,A,I4,A)
    End Program f08tbfe


f08tcfe.f90

    Program f08tcfe

!     F08TCF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: dspgvd, dtpcon, f06rdf, nag_wp, x02ajf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
      Character (1), Parameter         :: uplo = 'U'
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: anorm, bnorm, eps, rcond, rcondb, t1
      Integer                          :: aplen, i, info, j, liwork, lwork, n
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: ap(:), bp(:), eerbnd(:), w(:),       &
                                          work(:)
      Real (Kind=nag_wp)               :: dummy(1,1)
      Integer                          :: idum(1)
      Integer, Allocatable             :: iwork(:)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: abs, max, nint
!     .. Executable Statements ..
      Write (nout,*) 'F08TCF Example Program Results'
      Write (nout,*)
!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) n
      aplen = (n*(n+1))/2
      Allocate (ap(aplen),bp(aplen),eerbnd(n),w(n))

!     Use routine workspace query to get optimal workspace.
      lwork = -1
      liwork = -1
!     The NAG name equivalent of dspgvd is f08tcf
      Call dspgvd(2,'No vectors',uplo,n,ap,bp,w,dummy,n,dummy,lwork,idum,      &
        liwork,info)

!     Make sure that there is at least minimum workspace.
      lwork = max(3*n,nint(dummy(1,1)))
      liwork = max(n,idum(1))
      Allocate (work(lwork),iwork(liwork))

!     Read the upper or lower triangular parts of the matrices A and
!     B from data file

      If (uplo=='U') Then
        Read (nin,*)((ap(i+(j*(j-1))/2),j=i,n),i=1,n)
        Read (nin,*)((bp(i+(j*(j-1))/2),j=i,n),i=1,n)
      Else If (uplo=='L') Then
        Read (nin,*)((ap(i+((2*n-j)*(j-1))/2),j=1,i),i=1,n)
        Read (nin,*)((bp(i+((2*n-j)*(j-1))/2),j=1,i),i=1,n)
      End If

!     Compute the one-norms of the symmetric matrices A and B

      anorm = f06rdf('One norm',uplo,n,ap,work)
      bnorm = f06rdf('One norm',uplo,n,bp,work)

!     Solve the generalized symmetric eigenvalue problem
!     A*B*x = lambda*x (itype = 2)

!     In the following call the 9th argument is set to n rather
!     than 1 to avoid an incorrect error message in some vendor
!     versions of LAPACK.
!     The NAG name equivalent of dspgvd is f08tcf
      Call dspgvd(2,'No vectors',uplo,n,ap,bp,w,dummy,n,work,lwork,iwork,      &
        liwork,info)

      If (info==0) Then

!       Print solution

        Write (nout,*) 'Eigenvalues'
        Write (nout,99999) w(1:n)

!       Call DTPCON (F07UGF) to estimate the reciprocal condition
!       number of the Cholesky factor of B.  Note that:
!       cond(B) = 1/rcond**2.  DTPCON requires WORK and IWORK to be
!       of length at least 3*n and n respectively

        Call dtpcon('One norm',uplo,'Non-unit',n,bp,rcond,work,iwork,info)

!       Print the reciprocal condition number of B

        rcondb = rcond**2
        Write (nout,*)
        Write (nout,*) 'Estimate of reciprocal condition number for B'
        Write (nout,99998) rcondb

!       Get the machine precision, eps, and if rcondb is not less
!       than eps**2, compute error estimates for the eigenvalues

        eps = x02ajf()
        If (rcond>=eps) Then
          t1 = anorm*bnorm
          Do i = 1, n
            eerbnd(i) = eps*(t1+abs(w(i))/rcondb)
          End Do

!         Print the approximate error bounds for the eigenvalues

          Write (nout,*)
          Write (nout,*) 'Error estimates for the eigenvalues'
          Write (nout,99998) eerbnd(1:n)
        Else
          Write (nout,*)
          Write (nout,*) 'B is very ill-conditioned, error ',                  &
            'estimates have not been computed'
        End If
      Else If (info>n .And. info<=2*n) Then
        i = info - n
        Write (nout,99997) 'The leading minor of order ', i,                   &
          ' of B is not positive definite'
      Else
        Write (nout,99996) 'Failure in DSPGVD. INFO =', info
      End If

99999 Format (3X,(6F11.4))
99998 Format (4X,1P,6E11.1)
99997 Format (1X,A,I4,A)
99996 Format (1X,A,I4)
    End Program f08tcfe


f08tefe.f90

    Program f08tefe

!     F08TEF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: dpptrf, dspgst, dsptrd, dsterf, nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Integer                          :: i, info, j, n
      Character (1)                    :: uplo
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: ap(:), bp(:), d(:), e(:), tau(:)
!     .. Executable Statements ..
      Write (nout,*) 'F08TEF Example Program Results'
!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) n

      Allocate (ap(n*(n+1)/2),bp(n*(n+1)/2),d(n),e(n-1),tau(n))

!     Read A and B from data file

      Read (nin,*) uplo
      If (uplo=='U') Then
        Read (nin,*)((ap(i+j*(j-1)/2),j=i,n),i=1,n)
        Read (nin,*)((bp(i+j*(j-1)/2),j=i,n),i=1,n)
      Else If (uplo=='L') Then
        Read (nin,*)((ap(i+(2*n-j)*(j-1)/2),j=1,i),i=1,n)
        Read (nin,*)((bp(i+(2*n-j)*(j-1)/2),j=1,i),i=1,n)
      End If

!     Compute the Cholesky factorization of B
!     The NAG name equivalent of dpptrf is f07gdf
      Call dpptrf(uplo,n,bp,info)

      Write (nout,*)
      If (info>0) Then
        Write (nout,*) 'B is not positive definite.'
      Else

!       Reduce the problem to standard form C*y = lambda*y, storing
!       the result in A
!       The NAG name equivalent of dspgst is f08tef
        Call dspgst(1,uplo,n,ap,bp,info)

!       Reduce C to tridiagonal form T = (Q**T)*C*Q
!       The NAG name equivalent of dsptrd is f08gef
        Call dsptrd(uplo,n,ap,d,e,tau,info)

!       Calculate the eigenvalues of T (same as C)
!       The NAG name equivalent of dsterf is f08jff
        Call dsterf(n,d,e,info)

        If (info>0) Then
          Write (nout,*) 'Failure to converge.'
        Else

!         Print eigenvalues

          Write (nout,*) 'Eigenvalues'
          Write (nout,99999) d(1:n)
        End If
      End If

99999 Format (3X,(9F8.4))
    End Program f08tefe


f08tnfe.f90

    Program f08tnfe

!     F08TNF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: f06udf, nag_wp, x02ajf, zhpgv, ztpcon
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
      Character (1), Parameter         :: uplo = 'U'
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: anorm, bnorm, eps, rcond, rcondb,    &
                                          t1, t2
      Integer                          :: i, info, j, n
!     .. Local Arrays ..
      Complex (Kind=nag_wp), Allocatable :: ap(:), bp(:), work(:)
      Complex (Kind=nag_wp)            :: dummy(1,1)
      Real (Kind=nag_wp), Allocatable  :: eerbnd(:), rwork(:), w(:)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: abs
!     .. Executable Statements ..
      Write (nout,*) 'F08TNF Example Program Results'
      Write (nout,*)
!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) n

      Allocate (ap((n*(n+1))/2),bp((n*(n+1))/2),work(2*n),eerbnd(n),rwork(3*n- &
        2),w(n))

!     Read the upper or lower triangular parts of the matrices A and
!     B from data file

      If (uplo=='U') Then
        Read (nin,*)((ap(i+(j*(j-1))/2),j=i,n),i=1,n)
        Read (nin,*)((bp(i+(j*(j-1))/2),j=i,n),i=1,n)
      Else If (uplo=='L') Then
        Read (nin,*)((ap(i+((2*n-j)*(j-1))/2),j=1,i),i=1,n)
        Read (nin,*)((bp(i+((2*n-j)*(j-1))/2),j=1,i),i=1,n)
      End If

!     Compute the one-norms of the symmetric matrices A and B

      anorm = f06udf('One norm',uplo,n,ap,rwork)
      bnorm = f06udf('One norm',uplo,n,bp,rwork)

!     Solve the generalized symmetric eigenvalue problem
!     A*x = lambda*B*x (ITYPE = 1)

!     The NAG name equivalent of zhpgv is f08tnf
      Call zhpgv(1,'No vectors',uplo,n,ap,bp,w,dummy,1,work,rwork,info)

      If (info==0) Then

!       Print solution

        Write (nout,*) 'Eigenvalues'
        Write (nout,99999) w(1:n)

!       Call ZTPCON (F07UUF) to estimate the reciprocal condition
!       number of the Cholesky factor of B.  Note that:
!       cond(B) = 1/RCOND**2

        Call ztpcon('One norm',uplo,'Non-unit',n,bp,rcond,work,rwork,info)

!       Print the reciprocal condition number of B

        rcondb = rcond**2
        Write (nout,*)
        Write (nout,*) 'Estimate of reciprocal condition number for B'
        Write (nout,99998) rcondb

!       Get the machine precision, EPS, and if RCONDB is not less
!       than EPS**2, compute error estimates for the eigenvalues

        eps = x02ajf()
        If (rcond>=eps) Then
          t1 = eps/rcondb
          t2 = anorm/bnorm
          Do i = 1, n
            eerbnd(i) = t1*(t2+abs(w(i)))
          End Do

!         Print the approximate error bounds for the eigenvalues

          Write (nout,*)
          Write (nout,*) 'Error estimates for the eigenvalues'
          Write (nout,99998) eerbnd(1:n)
        Else
          Write (nout,*)
          Write (nout,*) 'B is very ill-conditioned, error ',                  &
            'estimates have not been computed'
        End If
      Else If (info>n .And. info<=2*n) Then
        i = info - n
        Write (nout,99997) 'The leading minor of order ', i,                   &
          ' of B is not positive definite'
      Else
        Write (nout,99996) 'Failure in ZHPGV. INFO =', info
      End If

99999 Format (3X,(6F11.4))
99998 Format (4X,1P,6E11.1)
99997 Format (1X,A,I4,A)
99996 Format (1X,A,I4)
    End Program f08tnfe


f08tpfe.f90

    Program f08tpfe

!     F08TPF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: nag_wp, x04daf, zhpgvx
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Real (Kind=nag_wp), Parameter    :: zero = 0.0E+0_nag_wp
      Integer, Parameter               :: nin = 5, nout = 6
      Character (1), Parameter         :: uplo = 'U'
!     .. Local Scalars ..
      Complex (Kind=nag_wp)            :: scal
      Real (Kind=nag_wp)               :: abstol, vl, vu
      Integer                          :: i, ifail, il, info, iu, j, k, ldz,   &
                                          m, n
!     .. Local Arrays ..
      Complex (Kind=nag_wp), Allocatable :: ap(:), bp(:), work(:), z(:,:)
      Real (Kind=nag_wp), Allocatable  :: rwork(:), w(:)
      Integer, Allocatable             :: iwork(:), jfail(:)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: abs, conjg, maxloc
!     .. Executable Statements ..
      Write (nout,*) 'F08TPF Example Program Results'
      Write (nout,*)
!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) n
      ldz = n
      m = n
      Allocate (ap((n*(n+1))/2),bp((n*(n+1))/2),work(2*n),z(ldz,m),rwork(7*n), &
        w(n),iwork(5*n),jfail(n))

!     Read the lower and upper bounds of the interval to be searched,
!     and read the upper or lower triangular parts of the matrices A
!     and B from data file

      Read (nin,*) vl, vu
      If (uplo=='U') Then
        Read (nin,*)((ap(i+(j*(j-1))/2),j=i,n),i=1,n)
        Read (nin,*)((bp(i+(j*(j-1))/2),j=i,n),i=1,n)
      Else If (uplo=='L') Then
        Read (nin,*)((ap(i+((2*n-j)*(j-1))/2),j=1,i),i=1,n)
        Read (nin,*)((bp(i+((2*n-j)*(j-1))/2),j=1,i),i=1,n)
      End If

!     Set the absolute error tolerance for eigenvalues. With abstol
!     set to zero, the default value is used instead

      abstol = zero

!     Solve the generalized Hermitian eigenvalue problem
!     A*x = lambda*B*x (itype = 1)

!     The NAG name equivalent of zhpgvx is f08tpf
      Call zhpgvx(1,'Vectors','Values in range',uplo,n,ap,bp,vl,vu,il,iu,      &
        abstol,m,w,z,ldz,work,rwork,iwork,jfail,info)

      If (info>=0 .And. info<=n) Then

!       Print solution

        Write (nout,99999) 'Number of eigenvalues found =', m
        Write (nout,*)
        Write (nout,*) 'Eigenvalues'
        Write (nout,99998) w(1:m)
        Flush (nout)

!       Normalize the eigenvectors, largest element real
        Do i = 1, m
          rwork(1:n) = abs(z(1:n,i))
          k = maxloc(rwork(1:n),1)
          scal = conjg(z(k,i))/abs(z(k,i))
          z(1:n,i) = z(1:n,i)*scal
        End Do

!       ifail: behaviour on error exit
!              =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
        ifail = 0
        Call x04daf('General',' ',n,m,z,ldz,'Selected eigenvectors',ifail)

        If (info>0) Then
          Write (nout,99999) 'INFO eigenvectors failed to converge, INFO =',   &
            info
          Write (nout,*) 'Indices of eigenvectors that did not converge'
          Write (nout,99997) jfail(1:m)
        End If
      Else If (info>n .And. info<=2*n) Then
        i = info - n
        Write (nout,99996) 'The leading minor of order ', i,                   &
          ' of B is not positive definite'
      Else
        Write (nout,99999) 'Failure in ZHPGVX. INFO =', info
      End If

99999 Format (1X,A,I5)
99998 Format (3X,(8F8.4))
99997 Format (3X,(8I8))
99996 Format (1X,A,I4,A)
    End Program f08tpfe


f08tqfe.f90

    Program f08tqfe

!     F08TQF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: f06udf, nag_wp, x02ajf, zhpgvd, ztpcon
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
      Character (1), Parameter         :: uplo = 'U'
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: anorm, bnorm, eps, rcond, rcondb, t1
      Integer                          :: aplen, i, info, j, liwork, lrwork,   &
                                          lwork, n
!     .. Local Arrays ..
      Complex (Kind=nag_wp), Allocatable :: ap(:), bp(:), work(:)
      Complex (Kind=nag_wp)            :: dummy(1,1)
      Real (Kind=nag_wp), Allocatable  :: eerbnd(:), rwork(:), w(:)
      Real (Kind=nag_wp)               :: rdum(1)
      Integer                          :: idum(1)
      Integer, Allocatable             :: iwork(:)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: abs, max, nint, real
!     .. Executable Statements ..
      Write (nout,*) 'F08TQF Example Program Results'
      Write (nout,*)
!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) n
      aplen = (n*(n+1))/2
      Allocate (ap(aplen),bp(aplen),eerbnd(n),w(n))

!     Use routine workspace query to get optimal workspace.
      lwork = -1
      liwork = -1
      lrwork = -1
!     The NAG name equivalent of zhpgvd is f08tqf
      Call zhpgvd(2,'No vectors',uplo,n,ap,bp,w,dummy,1,dummy,lwork,rdum,      &
        lrwork,idum,liwork,info)

!     Make sure that there is at least the minimum workspace
      lwork = max(2*n,nint(real(dummy(1,1))))
      lrwork = max(n,nint(rdum(1)))
      liwork = max(1,idum(1))
      Allocate (work(lwork),rwork(lrwork),iwork(liwork))

!     Read the upper or lower triangular parts of the matrices A and
!     B from data file

      If (uplo=='U') Then
        Read (nin,*)((ap(i+(j*(j-1))/2),j=i,n),i=1,n)
        Read (nin,*)((bp(i+(j*(j-1))/2),j=i,n),i=1,n)
      Else If (uplo=='L') Then
        Read (nin,*)((ap(i+((2*n-j)*(j-1))/2),j=1,i),i=1,n)
        Read (nin,*)((bp(i+((2*n-j)*(j-1))/2),j=1,i),i=1,n)
      End If

!     Compute the one-norms of the symmetric matrices A and B

      anorm = f06udf('One norm',uplo,n,ap,rwork)
      bnorm = f06udf('One norm',uplo,n,bp,rwork)

!     Solve the generalized symmetric eigenvalue problem
!     A*B*x = lambda*x (itype = 2)

!     The NAG name equivalent of zhpgvd is f08tqf
      Call zhpgvd(2,'No vectors',uplo,n,ap,bp,w,dummy,1,work,lwork,rwork,      &
        lrwork,iwork,liwork,info)

      If (info==0) Then

!       Print solution

        Write (nout,*) 'Eigenvalues'
        Write (nout,99999) w(1:n)

!       Call ZTPCON (F07UUF) to estimate the reciprocal condition
!       number of the Cholesky factor of B.  Note that:
!       cond(B) = 1/rcond**2.  ZTPCON requires WORK and RWORK to be
!       of length at least 2*n and n respectively

        Call ztpcon('One norm',uplo,'Non-unit',n,bp,rcond,work,rwork,info)

!       Print the reciprocal condition number of B

        rcondb = rcond**2
        Write (nout,*)
        Write (nout,*) 'Estimate of reciprocal condition number for B'
        Write (nout,99998) rcondb

!       Get the machine precision, eps, and if rcondb is not less
!       than eps**2, compute error estimates for the eigenvalues

        eps = x02ajf()
        If (rcond>=eps) Then
          t1 = anorm*bnorm
          Do i = 1, n
            eerbnd(i) = t1 + abs(w(i))/rcondb
          End Do

!         Print the approximate error bounds for the eigenvalues

          Write (nout,*)
          Write (nout,*) 'Error estimates (relative to machine precision)'
          Write (nout,*) 'for the eigenvalues:'
          Write (nout,99998) eerbnd(1:n)
        Else
          Write (nout,*)
          Write (nout,*) 'B is very ill-conditioned, error ',                  &
            'estimates have not been computed'
        End If
      Else If (info>n .And. info<=2*n) Then
        i = info - n
        Write (nout,99997) 'The leading minor of order ', i,                   &
          ' of B is not positive definite'
      Else
        Write (nout,99996) 'Failure in ZHPGVD. INFO =', info
      End If

99999 Format (3X,(6F11.4))
99998 Format (4X,1P,6E11.1)
99997 Format (1X,A,I4,A)
99996 Format (1X,A,I4)
    End Program f08tqfe


f08tsfe.f90

    Program f08tsfe

!     F08TSF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: dsterf, nag_wp, zhpgst, zhptrd, zpptrf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Integer                          :: i, info, j, n
      Character (1)                    :: uplo
!     .. Local Arrays ..
      Complex (Kind=nag_wp), Allocatable :: ap(:), bp(:), tau(:)
      Real (Kind=nag_wp), Allocatable  :: d(:), e(:)
!     .. Executable Statements ..
      Write (nout,*) 'F08TSF Example Program Results'
!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) n

      Allocate (ap(n*(n+1)/2),bp(n*(n+1)/2),tau(n),d(n),e(n-1))

!     Read A and B from data file

      Read (nin,*) uplo
      If (uplo=='U') Then
        Read (nin,*)((ap(i+j*(j-1)/2),j=i,n),i=1,n)
        Read (nin,*)((bp(i+j*(j-1)/2),j=i,n),i=1,n)
      Else If (uplo=='L') Then
        Read (nin,*)((ap(i+(2*n-j)*(j-1)/2),j=1,i),i=1,n)
        Read (nin,*)((bp(i+(2*n-j)*(j-1)/2),j=1,i),i=1,n)
      End If

!     Compute the Cholesky factorization of B
!     The NAG name equivalent of zpptrf is f07grf
      Call zpptrf(uplo,n,bp,info)

      Write (nout,*)
      If (info>0) Then
        Write (nout,*) 'B is not positive definite.'
      Else

!       Reduce the problem to standard form C*y = lambda*y, storing
!       the result in A
!       The NAG name equivalent of zhpgst is f08tsf
        Call zhpgst(1,uplo,n,ap,bp,info)

!       Reduce C to tridiagonal form T = (Q**H)*C*Q
!       The NAG name equivalent of zhptrd is f08gsf
        Call zhptrd(uplo,n,ap,d,e,tau,info)

!       Calculate the eigenvalues of T (same as C)
!       The NAG name equivalent of dsterf is f08jff
        Call dsterf(n,d,e,info)

        If (info>0) Then
          Write (nout,*) 'Failure to converge.'
        Else

!         Print eigenvalues

          Write (nout,*) 'Eigenvalues'
          Write (nout,99999) d(1:n)
        End If
      End If

99999 Format (3X,(9F8.4))
    End Program f08tsfe


f08uafe.f90

    Program f08uafe

!     F08UAF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: dsbgv, nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
      Character (1), Parameter         :: uplo = 'U'
!     .. Local Scalars ..
      Integer                          :: i, info, j, ka, kb, ldab, ldbb, n
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: ab(:,:), bb(:,:), w(:), work(:)
      Real (Kind=nag_wp)               :: dummy(1,1)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: max, min
!     .. Executable Statements ..
      Write (nout,*) 'F08UAF Example Program Results'
      Write (nout,*)
!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) n, ka, kb
      ldab = ka + 1
      ldbb = kb + 1
      Allocate (ab(ldab,n),bb(ldbb,n),w(n),work(3*n))

!     Read the upper or lower triangular parts of the matrices A and
!     B from data file

      If (uplo=='U') Then
        Read (nin,*)((ab(ka+1+i-j,j),j=i,min(n,i+ka)),i=1,n)
        Read (nin,*)((bb(kb+1+i-j,j),j=i,min(n,i+kb)),i=1,n)
      Else If (uplo=='L') Then
        Read (nin,*)((ab(1+i-j,j),j=max(1,i-ka),i),i=1,n)
        Read (nin,*)((bb(1+i-j,j),j=max(1,i-kb),i),i=1,n)
      End If

!     Solve the generalized symmetric band eigenvalue problem
!     A*x = lambda*B*x

!     The NAG name equivalent of dsbgv is f08uaf
      Call dsbgv('No vectors',uplo,n,ka,kb,ab,ldab,bb,ldbb,w,dummy,1,work,     &
        info)

      If (info==0) Then

!       Print solution

        Write (nout,*) 'Eigenvalues'
        Write (nout,99999) w(1:n)
      Else If (info>n .And. info<=2*n) Then
        i = info - n
        Write (nout,99998) 'The leading minor of order ', i,                   &
          ' of B is not positive definite'
      Else
        Write (nout,99997) 'Failure in DSBGV. INFO =', info
      End If

99999 Format (3X,(6F11.4))
99998 Format (1X,A,I4,A)
99997 Format (1X,A,I4)
    End Program f08uafe


f08ubfe.f90

    Program f08ubfe

!     F08UBF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: dsbgvx, nag_wp, x04caf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Real (Kind=nag_wp), Parameter    :: zero = 0.0E+0_nag_wp
      Integer, Parameter               :: nin = 5, nout = 6
      Character (1), Parameter         :: uplo = 'U'
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: abstol, vl, vu
      Integer                          :: i, ifail, il, info, iu, j, ka, kb,   &
                                          ldab, ldbb, ldq, ldz, m, n
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: ab(:,:), bb(:,:), q(:,:), w(:),      &
                                          work(:), z(:,:)
      Integer, Allocatable             :: iwork(:), jfail(:)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: max, min
!     .. Executable Statements ..
      Write (nout,*) 'F08UBF Example Program Results'
      Write (nout,*)
!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) n, ka, kb
      ldab = ka + 1
      ldbb = kb + 1
      ldq = n
      ldz = n
      m = n
      Allocate (ab(ldab,n),bb(ldbb,n),q(ldq,n),w(n),work(7*n),z(ldz,m),        &
        iwork(5*n),jfail(n))

!     Read the lower and upper bounds of the interval to be searched,
!     and read the upper or lower triangular parts of the matrices A
!     and B from data file

      Read (nin,*) vl, vu
      If (uplo=='U') Then
        Read (nin,*)((ab(ka+1+i-j,j),j=i,min(n,i+ka)),i=1,n)
        Read (nin,*)((bb(kb+1+i-j,j),j=i,min(n,i+kb)),i=1,n)
      Else If (uplo=='L') Then
        Read (nin,*)((ab(1+i-j,j),j=max(1,i-ka),i),i=1,n)
        Read (nin,*)((bb(1+i-j,j),j=max(1,i-kb),i),i=1,n)
      End If

!     Set the absolute error tolerance for eigenvalues. With abstol
!     set to zero, the default value is used instead

      abstol = zero

!     Solve the generalized symmetric eigenvalue problem
!     A*x = lambda*B*x

!     The NAG name equivalent of dsbgvx is f08ubf
      Call dsbgvx('Vectors','Values in range',uplo,n,ka,kb,ab,ldab,bb,ldbb,q,  &
        ldq,vl,vu,il,iu,abstol,m,w,z,ldz,work,iwork,jfail,info)

      If (info>=0 .And. info<=n) Then

!       Print solution

        Write (nout,99999) 'Number of eigenvalues found =', m
        Write (nout,*)
        Write (nout,*) 'Eigenvalues'
        Write (nout,99998) w(1:m)
        Flush (nout)

!       ifail: behaviour on error exit
!              =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
        ifail = 0
        Call x04caf('General',' ',n,m,z,ldz,'Selected eigenvectors',ifail)

        If (info>0) Then
          Write (nout,99999) 'INFO eigenvectors failed to converge, INFO =',   &
            info
          Write (nout,*) 'Indices of eigenvectors that did not converge'
          Write (nout,99997) jfail(1:m)
        End If
      Else If (info>n .And. info<=2*n) Then
        i = info - n
        Write (nout,99996) 'The leading minor of order ', i,                   &
          ' of B is not positive definite'
        Write (nout,99999) 'Failure in DSBGVX. INFO =', info
      End If

99999 Format (1X,A,I5)
99998 Format (3X,(8F8.4))
99997 Format (3X,(8I8))
99996 Format (1X,A,I4,A)
    End Program f08ubfe


f08ucfe.f90

    Program f08ucfe

!     F08UCF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: dsbgvd, nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
      Character (1), Parameter         :: uplo = 'U'
!     .. Local Scalars ..
      Integer                          :: i, info, j, ka, kb, ldab, ldbb,      &
                                          liwork, lwork, n
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: ab(:,:), bb(:,:), w(:), work(:)
      Real (Kind=nag_wp)               :: dummy(1,1)
      Integer, Allocatable             :: iwork(:)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: max, min
!     .. Executable Statements ..
      Write (nout,*) 'F08UCF Example Program Results'
      Write (nout,*)
!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) n, ka, kb
      ldab = ka + 1
      ldbb = kb + 1
      liwork = 1
      lwork = 3*n
      Allocate (ab(ldab,n),bb(ldbb,n),w(n),work(lwork),iwork(liwork))

!     Read the upper or lower triangular parts of the matrices A and
!     B from data file

      If (uplo=='U') Then
        Read (nin,*)((ab(ka+1+i-j,j),j=i,min(n,i+ka)),i=1,n)
        Read (nin,*)((bb(kb+1+i-j,j),j=i,min(n,i+kb)),i=1,n)
      Else If (uplo=='L') Then
        Read (nin,*)((ab(1+i-j,j),j=max(1,i-ka),i),i=1,n)
        Read (nin,*)((bb(1+i-j,j),j=max(1,i-kb),i),i=1,n)
      End If

!     Solve the generalized symmetric band eigenvalue problem
!     A*x = lambda*B*x

!     The NAG name equivalent of dsbgvd is f08ucf
      Call dsbgvd('No vectors',uplo,n,ka,kb,ab,ldab,bb,ldbb,w,dummy,1,work,    &
        lwork,iwork,liwork,info)

      If (info==0) Then

!       Print solution

        Write (nout,*) 'Eigenvalues'
        Write (nout,99999) w(1:n)
      Else If (info>n .And. info<=2*n) Then
        i = info - n
        Write (nout,99998) 'The leading minor of order ', i,                   &
          ' of B is not positive definite'
      Else
        Write (nout,99997) 'Failure in DSBGVD. INFO =', info
      End If

99999 Format (3X,(6F11.4))
99998 Format (1X,A,I4,A)
99997 Format (1X,A,I4)
    End Program f08ucfe


f08uefe.f90

    Program f08uefe

!     F08UEF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: dpbstf, dsbgst, dsbtrd, dsterf, nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Integer                          :: i, info, j, ka, kb, ldab, ldbb, ldx, &
                                          n
      Character (1)                    :: uplo
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: ab(:,:), bb(:,:), d(:), e(:),        &
                                          work(:), x(:,:)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: max, min
!     .. Executable Statements ..
      Write (nout,*) 'F08UEF Example Program Results'
!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) n, ka, kb
      ldab = ka + 1
      ldbb = kb + 1
      ldx = n
      Allocate (ab(ldab,n),bb(ldbb,n),d(n),e(n-1),work(2*n),x(ldx,n))

!     Read A and B from data file

      Read (nin,*) uplo
      If (uplo=='U') Then
        Do i = 1, n
          Read (nin,*)(ab(ka+1+i-j,j),j=i,min(n,i+ka))
        End Do
        Do i = 1, n
          Read (nin,*)(bb(kb+1+i-j,j),j=i,min(n,i+kb))
        End Do
      Else If (uplo=='L') Then
        Do i = 1, n
          Read (nin,*)(ab(1+i-j,j),j=max(1,i-ka),i)
        End Do
        Do i = 1, n
          Read (nin,*)(bb(1+i-j,j),j=max(1,i-kb),i)
        End Do
      End If

!     Compute the split Cholesky factorization of B
!     The NAG name equivalent of dpbstf is f08uff
      Call dpbstf(uplo,n,kb,bb,ldbb,info)

      Write (nout,*)
      If (info>0) Then
        Write (nout,*) 'B is not positive definite.'
      Else

!       Reduce the problem to standard form C*y = lambda*y, storing
!       the result in A
!       The NAG name equivalent of dsbgst is f08uef
        Call dsbgst('N',uplo,n,ka,kb,ab,ldab,bb,ldbb,x,ldx,work,info)

!       Reduce C to tridiagonal form T = (Q**T)*C*Q
!       The NAG name equivalent of dsbtrd is f08hef
        Call dsbtrd('N',uplo,n,ka,ab,ldab,d,e,x,ldx,work,info)

!       Calculate the eigenvalues of T (same as C)
!       The NAG name equivalent of dsterf is f08jff
        Call dsterf(n,d,e,info)

        If (info>0) Then
          Write (nout,*) 'Failure to converge.'
        Else

!         Print eigenvalues

          Write (nout,*) 'Eigenvalues'
          Write (nout,99999) d(1:n)
        End If
      End If

99999 Format (3X,(8F8.4))
    End Program f08uefe


f08unfe.f90

    Program f08unfe

!     F08UNF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: nag_wp, zhbgv
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
      Character (1), Parameter         :: uplo = 'U'
!     .. Local Scalars ..
      Integer                          :: i, info, j, ka, kb, ldab, ldbb, n
!     .. Local Arrays ..
      Complex (Kind=nag_wp), Allocatable :: ab(:,:), bb(:,:), work(:)
      Complex (Kind=nag_wp)            :: dummy(1,1)
      Real (Kind=nag_wp), Allocatable  :: rwork(:), w(:)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: max, min
!     .. Executable Statements ..
      Write (nout,*) 'F08UNF Example Program Results'
      Write (nout,*)
!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) n, ka, kb
      ldab = ka + 1
      ldbb = kb + 1
      Allocate (ab(ldab,n),bb(ldbb,n),work(n),rwork(3*n),w(n))

!     Read the upper or lower triangular parts of the matrices A and
!     B from data file

      If (uplo=='U') Then
        Read (nin,*)((ab(ka+1+i-j,j),j=i,min(n,i+ka)),i=1,n)
        Read (nin,*)((bb(kb+1+i-j,j),j=i,min(n,i+kb)),i=1,n)
      Else If (uplo=='L') Then
        Read (nin,*)((ab(1+i-j,j),j=max(1,i-ka),i),i=1,n)
        Read (nin,*)((bb(1+i-j,j),j=max(1,i-kb),i),i=1,n)
      End If

!     Solve the generalized Hermitian band eigenvalue problem
!     A*x = lambda*B*x

!     The NAG name equivalent of zhbgv is f08unf
      Call zhbgv('No vectors',uplo,n,ka,kb,ab,ldab,bb,ldbb,w,dummy,1,work,     &
        rwork,info)

      If (info==0) Then

!       Print solution

        Write (nout,*) 'Eigenvalues'
        Write (nout,99999) w(1:n)
      Else If (info>n .And. info<=2*n) Then
        i = info - n
        Write (nout,99998) 'The leading minor of order ', i,                   &
          ' of B is not positive definite'
      Else
        Write (nout,99997) 'Failure in ZHBGV. INFO =', info
      End If

99999 Format (3X,(6F11.4))
99998 Format (1X,A,I4,A)
99997 Format (1X,A,I4)
    End Program f08unfe


f08upfe.f90

    Program f08upfe

!     F08UPF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: nag_wp, x04daf, zhbgvx
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Real (Kind=nag_wp), Parameter    :: zero = 0.0E+0_nag_wp
      Integer, Parameter               :: nin = 5, nout = 6
      Character (1), Parameter         :: uplo = 'U'
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: abstol, vl, vu
      Integer                          :: i, ifail, il, info, iu, j, ka, kb,   &
                                          ldab, ldbb, ldq, ldz, m, n
!     .. Local Arrays ..
      Complex (Kind=nag_wp), Allocatable :: ab(:,:), bb(:,:), q(:,:), work(:), &
                                          z(:,:)
      Real (Kind=nag_wp), Allocatable  :: rwork(:), w(:)
      Integer, Allocatable             :: iwork(:), jfail(:)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: max, min
!     .. Executable Statements ..
      Write (nout,*) 'F08UPF Example Program Results'
      Write (nout,*)
!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) n, ka, kb
      ldab = ka + 1
      ldbb = kb + 1
      ldq = n
      ldz = n
      m = n
      Allocate (ab(ldab,n),bb(ldbb,n),q(ldq,n),work(n),z(ldz,m),rwork(7*n),    &
        w(n),iwork(5*n),jfail(n))

!     Read the lower and upper bounds of the interval to be searched,
!     and read the upper or lower triangular parts of the matrices A
!     and B from data file

      Read (nin,*) vl, vu
      If (uplo=='U') Then
        Read (nin,*)((ab(ka+1+i-j,j),j=i,min(n,i+ka)),i=1,n)
        Read (nin,*)((bb(kb+1+i-j,j),j=i,min(n,i+kb)),i=1,n)
      Else If (uplo=='L') Then
        Read (nin,*)((ab(1+i-j,j),j=max(1,i-ka),i),i=1,n)
        Read (nin,*)((bb(1+i-j,j),j=max(1,i-kb),i),i=1,n)
      End If

!     Set the absolute error tolerance for eigenvalues. With abstol
!     set to zero, the default value is used instead

      abstol = zero

!     Solve the generalized symmetric eigenvalue problem
!     A*x = lambda*B*x

!     The NAG name equivalent of zhbgvx is f08upf
      Call zhbgvx('Vectors','Values in range',uplo,n,ka,kb,ab,ldab,bb,ldbb,q,  &
        ldq,vl,vu,il,iu,abstol,m,w,z,ldz,work,rwork,iwork,jfail,info)

      If (info>=0 .And. info<=n) Then

!       Print solution

        Write (nout,99999) 'Number of eigenvalues found =', m
        Write (nout,*)
        Write (nout,*) 'Eigenvalues'
        Write (nout,99998) w(1:m)
        Flush (nout)

!       ifail: behaviour on error exit
!              =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
        ifail = 0
        Call x04daf('General',' ',n,m,z,ldz,'Selected eigenvectors',ifail)

        If (info>0) Then
          Write (nout,99999) 'INFO eigenvectors failed to converge, INFO =',   &
            info
          Write (nout,*) 'Indices of eigenvectors that did not converge'
          Write (nout,99997) jfail(1:m)
        End If
      Else If (info>n .And. info<=2*n) Then
        i = info - n
        Write (nout,99996) 'The leading minor of order ', i,                   &
          ' of B is not positive definite'
      Else
        Write (nout,99999) 'Failure in ZHBGVX. INFO =', info
      End If

99999 Format (1X,A,I5)
99998 Format (3X,(8F8.4))
99997 Format (3X,(8I8))
99996 Format (1X,A,I4,A)
    End Program f08upfe


f08uqfe.f90

    Program f08uqfe

!     F08UQF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: nag_wp, zhbgvd
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
      Character (1), Parameter         :: uplo = 'U'
!     .. Local Scalars ..
      Integer                          :: i, info, j, ka, kb, ldab, ldbb,      &
                                          liwork, lrwork, lwork, n
!     .. Local Arrays ..
      Complex (Kind=nag_wp), Allocatable :: ab(:,:), bb(:,:), work(:)
      Complex (Kind=nag_wp)            :: dummy(1,1)
      Real (Kind=nag_wp), Allocatable  :: rwork(:), w(:)
      Integer, Allocatable             :: iwork(:)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: max, min
!     .. Executable Statements ..
      Write (nout,*) 'F08UQF Example Program Results'
      Write (nout,*)
!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) n, ka, kb
      ldab = ka + 1
      ldbb = kb + 1
      lrwork = n
      lwork = n
      liwork = 1
      Allocate (ab(ldab,n),bb(ldbb,n),work(lwork),rwork(lrwork),w(n),          &
        iwork(liwork))

!     Read the upper or lower triangular parts of the matrices A and
!     B from data file

      If (uplo=='U') Then
        Read (nin,*)((ab(ka+1+i-j,j),j=i,min(n,i+ka)),i=1,n)
        Read (nin,*)((bb(kb+1+i-j,j),j=i,min(n,i+kb)),i=1,n)
      Else If (uplo=='L') Then
        Read (nin,*)((ab(1+i-j,j),j=max(1,i-ka),i),i=1,n)
        Read (nin,*)((bb(1+i-j,j),j=max(1,i-kb),i),i=1,n)
      End If

!     Solve the generalized Hermitian band eigenvalue problem
!     A*x = lambda*B*x

!     The NAG name equivalent of zhbgvd is f08uqf
      Call zhbgvd('No vectors',uplo,n,ka,kb,ab,ldab,bb,ldbb,w,dummy,1,work,    &
        lwork,rwork,lrwork,iwork,liwork,info)

      If (info==0) Then

!       Print solution

        Write (nout,*) 'Eigenvalues'
        Write (nout,99999) w(1:n)
      Else If (info>n .And. info<=2*n) Then
        i = info - n
        Write (nout,99998) 'The leading minor of order ', i,                   &
          ' of B is not positive definite'
      Else
        Write (nout,99997) 'Failure in ZHBGVD. INFO =', info
      End If

99999 Format (3X,(6F11.4))
99998 Format (1X,A,I4,A)
99997 Format (1X,A,I4)
    End Program f08uqfe


f08usfe.f90

    Program f08usfe

!     F08USF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: dsterf, nag_wp, zhbgst, zhbtrd, zpbstf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Integer                          :: i, info, j, ka, kb, ldab, ldbb, ldx, &
                                          n
      Character (1)                    :: uplo
!     .. Local Arrays ..
      Complex (Kind=nag_wp), Allocatable :: ab(:,:), bb(:,:), work(:), x(:,:)
      Real (Kind=nag_wp), Allocatable  :: d(:), e(:), rwork(:)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: max, min
!     .. Executable Statements ..
      Write (nout,*) 'F08USF Example Program Results'
!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) n, ka, kb
      ldab = ka + 1
      ldbb = kb + 1
      ldx = n
      Allocate (ab(ldab,n),bb(ldbb,n),work(n),x(ldx,n),d(n),e(n-1),rwork(n))

!     Read A and B from data file

      Read (nin,*) uplo
      If (uplo=='U') Then
        Do i = 1, n
          Read (nin,*)(ab(ka+1+i-j,j),j=i,min(n,i+ka))
        End Do
        Do i = 1, n
          Read (nin,*)(bb(kb+1+i-j,j),j=i,min(n,i+kb))
        End Do
      Else If (uplo=='L') Then
        Do i = 1, n
          Read (nin,*)(ab(1+i-j,j),j=max(1,i-ka),i)
        End Do
        Do i = 1, n
          Read (nin,*)(bb(1+i-j,j),j=max(1,i-kb),i)
        End Do
      End If

!     Compute the split Cholesky factorization of B
!     The NAG name equivalent of zpbstf is f08utf
      Call zpbstf(uplo,n,kb,bb,ldbb,info)

      Write (nout,*)
      If (info>0) Then
        Write (nout,*) 'B is not positive definite.'
      Else

!       Reduce the problem to standard form C*y = lambda*y, storing
!       the result in A
!       The NAG name equivalent of zhbgst is f08usf
        Call zhbgst('N',uplo,n,ka,kb,ab,ldab,bb,ldbb,x,ldx,work,rwork,info)

!       Reduce C to tridiagonal form T = (Q**H)*C*Q
!       The NAG name equivalent of zhbtrd is f08hsf
        Call zhbtrd('N',uplo,n,ka,ab,ldab,d,e,x,ldx,work,info)

!       Calculate the eigenvalues of T (same as C)
!       The NAG name equivalent of dsterf is f08jff
        Call dsterf(n,d,e,info)

        If (info>0) Then
          Write (nout,*) 'Failure to converge.'
        Else

!         Print eigenvalues

          Write (nout,*) 'Eigenvalues'
          Write (nout,99999) d(1:n)
        End If
      End If

99999 Format (3X,(8F8.4))
    End Program f08usfe


f08vafe.f90

    Program f08vafe

!     F08VAF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: dggsvd, dtrcon, nag_wp, x02ajf, x04cbf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: eps, rcond, serrbd
      Integer                          :: i, ifail, info, irank, j, k, l, lda, &
                                          ldb, ldq, ldu, ldv, m, n, p
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: a(:,:), alpha(:), b(:,:), beta(:),   &
                                          q(:,:), u(:,:), v(:,:), work(:)
      Integer, Allocatable             :: iwork(:)
      Character (1)                    :: clabs(1), rlabs(1)
!     .. Executable Statements ..
      Write (nout,*) 'F08VAF Example Program Results'
      Write (nout,*)
      Flush (nout)
!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) m, n, p
      lda = m
      ldb = p
      ldq = n
      ldu = m
      ldv = p
      Allocate (a(lda,n),alpha(n),b(ldb,n),beta(n),q(ldq,n),u(ldu,m),v(ldv,p), &
        work(m+3*n),iwork(n))

!     Read the m by n matrix A and p by n matrix B from data file

      Read (nin,*)(a(i,1:n),i=1,m)
      Read (nin,*)(b(i,1:n),i=1,p)

!     Compute the generalized singular value decomposition of (A, B)
!     (A = U*D1*(0 R)*(Q**T), B = V*D2*(0 R)*(Q**T), m>=n)
!     The NAG name equivalent of dggsvd is f08vaf
      Call dggsvd('U','V','Q',m,n,p,k,l,a,lda,b,ldb,alpha,beta,u,ldu,v,ldv,q,  &
        ldq,work,iwork,info)

      If (info==0) Then

!       Print solution

        irank = k + l
        Write (nout,*) 'Number of infinite generalized singular values (K)'
        Write (nout,99999) k
        Write (nout,*) 'Number of finite generalized singular values (L)'
        Write (nout,99999) l
        Write (nout,*) 'Numerical rank of (A**T B**T)**T (K+L)'
        Write (nout,99999) irank
        Write (nout,*)
        Write (nout,*) 'Finite generalized singular values'
        Write (nout,99998)(alpha(j)/beta(j),j=k+1,irank)

        Write (nout,*)
        Flush (nout)

!       ifail: behaviour on error exit
!              =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
        ifail = 0
        Call x04cbf('General',' ',m,m,u,ldu,'1P,E12.4','Orthogonal matrix U',  &
          'Integer',rlabs,'Integer',clabs,80,0,ifail)

        Write (nout,*)
        Flush (nout)

        Call x04cbf('General',' ',p,p,v,ldv,'1P,E12.4','Orthogonal matrix V',  &
          'Integer',rlabs,'Integer',clabs,80,0,ifail)

        Write (nout,*)
        Flush (nout)

        Call x04cbf('General',' ',n,n,q,ldq,'1P,E12.4','Orthogonal matrix Q',  &
          'Integer',rlabs,'Integer',clabs,80,0,ifail)

        Write (nout,*)
        Flush (nout)

        Call x04cbf('Upper triangular','Non-unit',irank,irank,a(1,n-irank+1),  &
          lda,'1P,E12.4','Nonsingular upper triangular matrix R','Integer',    &
          rlabs,'Integer',clabs,80,0,ifail)

!       Call DTRCON (F07TGF) to estimate the reciprocal condition
!       number of R

        Call dtrcon('Infinity-norm','Upper','Non-unit',irank,a(1,n-irank+1),   &
          lda,rcond,work,iwork,info)

        Write (nout,*)
        Write (nout,*) 'Estimate of reciprocal condition number for R'
        Write (nout,99997) rcond
        Write (nout,*)

!       So long as irank = n, get the machine precision, eps, and
!       compute the approximate error bound for the computed
!       generalized singular values

        If (irank==n) Then
          eps = x02ajf()
          serrbd = eps/rcond
          Write (nout,*) 'Error estimate for the generalized singular values'
          Write (nout,99997) serrbd
        Else
          Write (nout,*) '(A**T B**T)**T is not of full rank'
        End If
      Else
        Write (nout,99996) 'Failure in DGGSVD. INFO =', info
      End If

99999 Format (1X,I5)
99998 Format (3X,8(1P,E12.4))
99997 Format (1X,1P,E11.1)
99996 Format (1X,A,I4)
    End Program f08vafe


f08vcfe.f90

    Program f08vcfe

!     F08VCF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: dggsvd3, dtrcon, nag_wp, x02ajf, x04cbf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: eps, rcond, serrbd
      Integer                          :: i, ifail, info, irank, j, k, l, lda, &
                                          ldb, ldq, ldu, ldv, lwork, m, n, p
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: a(:,:), alpha(:), b(:,:), beta(:),   &
                                          q(:,:), u(:,:), v(:,:), work(:)
      Real (Kind=nag_wp)               :: wdum(1)
      Integer, Allocatable             :: iwork(:)
      Character (1)                    :: clabs(1), rlabs(1)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: nint
!     .. Executable Statements ..
      Write (nout,*) 'F08VCF Example Program Results'
      Write (nout,*)
      Flush (nout)
!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) m, n, p
      lda = m
      ldb = p
      ldq = n
      ldu = m
      ldv = p
      Allocate (a(lda,n),alpha(n),b(ldb,n),beta(n),q(ldq,n),u(ldu,m),v(ldv,p), &
        iwork(n))

!     Perform workspace query to get optimal size of work
!     The NAG name equivalent of dggsvd3 is f08vcf
      lwork = -1
      Call dggsvd3('U','V','Q',m,n,p,k,l,a,lda,b,ldb,alpha,beta,u,ldu,v,ldv,q, &
        ldq,wdum,lwork,iwork,info)
      lwork = nint(wdum(1))
      Allocate (work(lwork))

!     Read the m by n matrix A and p by n matrix B from data file

      Read (nin,*)(a(i,1:n),i=1,m)
      Read (nin,*)(b(i,1:n),i=1,p)

!     Compute the generalized singular value decomposition of (A, B)
!     (A = U*D1*(0 R)*(Q**T), B = V*D2*(0 R)*(Q**T), m>=n)
!     The NAG name equivalent of dggsvd3 is f08vcf
      Call dggsvd3('U','V','Q',m,n,p,k,l,a,lda,b,ldb,alpha,beta,u,ldu,v,ldv,q, &
        ldq,work,lwork,iwork,info)

      If (info==0) Then

!       Print solution

        irank = k + l
        Write (nout,*) 'Number of infinite generalized singular values (K)'
        Write (nout,99999) k
        Write (nout,*) 'Number of finite generalized singular values (L)'
        Write (nout,99999) l
        Write (nout,*) 'Numerical rank of (A**T B**T)**T (K+L)'
        Write (nout,99999) irank
        Write (nout,*)
        Write (nout,*) 'Finite generalized singular values'
        Write (nout,99998)(alpha(j)/beta(j),j=k+1,irank)

        Write (nout,*)
        Flush (nout)

!       ifail: behaviour on error exit
!              =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
        ifail = 0
        Call x04cbf('General',' ',m,m,u,ldu,'1P,E12.4','Orthogonal matrix U',  &
          'Integer',rlabs,'Integer',clabs,80,0,ifail)

        Write (nout,*)
        Flush (nout)

        Call x04cbf('General',' ',p,p,v,ldv,'1P,E12.4','Orthogonal matrix V',  &
          'Integer',rlabs,'Integer',clabs,80,0,ifail)

        Write (nout,*)
        Flush (nout)

        Call x04cbf('General',' ',n,n,q,ldq,'1P,E12.4','Orthogonal matrix Q',  &
          'Integer',rlabs,'Integer',clabs,80,0,ifail)

        Write (nout,*)
        Flush (nout)

        Call x04cbf('Upper triangular','Non-unit',irank,irank,a(1,n-irank+1),  &
          lda,'1P,E12.4','Nonsingular upper triangular matrix R','Integer',    &
          rlabs,'Integer',clabs,80,0,ifail)

!       Call DTRCON (F07TGF) to estimate the reciprocal condition
!       number of R

        Call dtrcon('Infinity-norm','Upper','Non-unit',irank,a(1,n-irank+1),   &
          lda,rcond,work,iwork,info)

        Write (nout,*)
        Write (nout,*) 'Estimate of reciprocal condition number for R'
        Write (nout,99997) rcond
        Write (nout,*)

!       So long as irank = n, get the machine precision, eps, and
!       compute the approximate error bound for the computed
!       generalized singular values

        If (irank==n) Then
          eps = x02ajf()
          serrbd = eps/rcond
          Write (nout,*) 'Error estimate for the generalized singular values'
          Write (nout,99997) serrbd
        Else
          Write (nout,*) '(A**T B**T)**T is not of full rank'
        End If
      Else
        Write (nout,99996) 'Failure in DGGSVD3. INFO =', info
      End If

99999 Format (1X,I5)
99998 Format (3X,8(1P,E12.4))
99997 Format (1X,1P,E11.1)
99996 Format (1X,A,I4)
    End Program f08vcfe


f08vefe.f90

    Program f08vefe

!     F08VEF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: dggsvp, f06raf, nag_wp, x02ajf, x04cbf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: eps, tola, tolb
      Integer                          :: i, ifail, info, irank, k, l, lda,    &
                                          ldb, ldq, ldu, ldv, m, n, p
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: a(:,:), b(:,:), q(:,:), tau(:),      &
                                          u(:,:), v(:,:), work(:)
      Integer, Allocatable             :: iwork(:)
      Character (1)                    :: clabs(1), rlabs(1)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: max, real
!     .. Executable Statements ..
      Write (nout,*) 'F08VEF Example Program Results'
      Write (nout,*)
      Flush (nout)

!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) m, n, p
      lda = m
      ldb = p
      ldq = n
      ldu = m
      ldv = p
      Allocate (a(lda,n),b(ldb,n),q(ldq,n),tau(n),u(ldu,m),v(ldv,p),           &
        work(m+3*n+p),iwork(n))

!     Read the m by n matrix A and p by n matrix B from data file

      Read (nin,*)(a(i,1:n),i=1,m)
      Read (nin,*)(b(i,1:n),i=1,p)

!     Compute tola and tolb as
!         tola = max(m,n)*norm(A)*macheps
!         tolb = max(p,n)*norm(B)*macheps

      eps = x02ajf()
      tola = real(max(m,n),kind=nag_wp)*f06raf('One-norm',m,n,a,lda,work)*eps
      tolb = real(max(p,n),kind=nag_wp)*f06raf('One-norm',p,n,b,ldb,work)*eps

!     Compute the factorization of (A, B)
!         (A = U*S*(Q**T), B = V*T*(Q**T))

!     The NAG name equivalent of dggsvp is f08vef
      Call dggsvp('U','V','Q',m,p,n,a,lda,b,ldb,tola,tolb,k,l,u,ldu,v,ldv,q,   &
        ldq,iwork,tau,work,info)

!     Print solution

      irank = k + l
      Write (nout,*) 'Numerical rank of (A**T B**T)**T (K+L)'
      Write (nout,99999) irank

      Write (nout,*)
      Flush (nout)
      If (m>=irank) Then

!       ifail: behaviour on error exit
!              =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
        ifail = 0
        Call x04cbf('Upper','Non-unit',irank,irank,a(1,n-irank+1),lda,         &
          '1P,E12.4','Upper triangular matrix S','Integer',rlabs,'Integer',    &
          clabs,80,0,ifail)

      Else

        ifail = 0
        Call x04cbf('Upper','Non-unit',m,irank,a(1,n-irank+1),lda,'1P,E12.4',  &
          'Upper trapezoidal matrix S','Integer',rlabs,'Integer',clabs,80,0,   &
          ifail)

      End If
      Write (nout,*)
      Flush (nout)

      ifail = 0
      Call x04cbf('Upper','Non-unit',l,l,b(1,n-l+1),ldb,'1P,E12.4',            &
        'Upper triangular matrix T','Integer',rlabs,'Integer',clabs,80,0,      &
        ifail)

      Write (nout,*)
      Flush (nout)

      ifail = 0
      Call x04cbf('General',' ',m,m,u,ldu,'1P,E12.4','Orthogonal matrix U',    &
        'Integer',rlabs,'Integer',clabs,80,0,ifail)

      Write (nout,*)
      Flush (nout)

      ifail = 0
      Call x04cbf('General',' ',p,p,v,ldv,'1P,E12.4','Orthogonal matrix V',    &
        'Integer',rlabs,'Integer',clabs,80,0,ifail)

      Write (nout,*)
      Flush (nout)

      ifail = 0
      Call x04cbf('General',' ',n,n,q,ldq,'1P,E12.4','Orthogonal matrix Q',    &
        'Integer',rlabs,'Integer',clabs,80,0,ifail)

99999 Format (1X,I5)
    End Program f08vefe


f08vgfe.f90

    Program f08vgfe

!     F08VGF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: dggsvp3, f06raf, f08yef, nag_wp, x02ajf, x04cbf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: eps, tola, tolb
      Integer                          :: i, ifail, info, irank, j, k, l, lda, &
                                          ldb, ldq, ldu, ldv, lwork, m, n,     &
                                          ncycle, p
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: a(:,:), alpha(:), b(:,:), beta(:),   &
                                          q(:,:), tau(:), u(:,:), v(:,:),      &
                                          work(:)
      Real (Kind=nag_wp)               :: wdum(1)
      Integer, Allocatable             :: iwork(:)
      Character (1)                    :: clabs(1), rlabs(1)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: max, nint, real
!     .. Executable Statements ..
      Write (nout,*) 'F08VGF Example Program Results'
      Write (nout,*)
      Flush (nout)

!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) m, n, p
      lda = m
      ldb = p
      ldq = n
      ldu = m
      ldv = p
      Allocate (a(lda,n),alpha(n),b(ldb,n),beta(n),q(ldq,n),tau(n),u(ldu,m),   &
        v(ldv,p),iwork(n))

!     Perform workspace query to get optimal size of work
!     The NAG name equivalent of dggsvp3 is f08vgf
      lwork = -1
      Call dggsvp3('U','V','Q',m,p,n,a,lda,b,ldb,tola,tolb,k,l,u,ldu,v,ldv,q,  &
        ldq,iwork,tau,wdum,lwork,info)
      lwork = nint(wdum(1))
      Allocate (work(lwork))

!     Read the m by n matrix A and p by n matrix B from data file

      Read (nin,*)(a(i,1:n),i=1,m)
      Read (nin,*)(b(i,1:n),i=1,p)

!     Compute tola and tolb as
!         tola = max(m,n)*norm(A)*macheps
!         tolb = max(p,n)*norm(B)*macheps

      eps = x02ajf()
      tola = real(max(m,n),kind=nag_wp)*f06raf('One-norm',m,n,a,lda,work)*eps
      tolb = real(max(p,n),kind=nag_wp)*f06raf('One-norm',p,n,b,ldb,work)*eps

!     Compute the factorization of (A, B)
!         (A = U*S*(Q**T), B = V*T*(Q**T))

!     The NAG name equivalent of dggsvp3 is f08vgf
      Call dggsvp3('U','V','Q',m,p,n,a,lda,b,ldb,tola,tolb,k,l,u,ldu,v,ldv,q,  &
        ldq,iwork,tau,work,lwork,info)

!     Given the factors above find the generalized SVD of (A, B)

!     The NAG name equivalent of dtgdja is f08yef
      Call f08yef('U','V','Q',m,p,n,k,l,a,lda,b,ldb,tola,tolb,alpha,beta,u,    &
        ldu,v,ldv,q,ldq,work,ncycle,info)

!     Print solution

      irank = k + l
      Write (nout,*) 'Number of infinite generalized singular values (k)'
      Write (nout,99999) k
      Write (nout,*) 'Number of finite generalized singular values (l)'
      Write (nout,99999) l
      Write (nout,*) 'Effective Numerical rank of (A; B) (k+l)'
      Write (nout,99999) irank
      Write (nout,*)
      Write (nout,*) 'Finite generalized singular values'
      Write (nout,99998)(alpha(j)/beta(j),j=k+1,irank)

      Write (nout,*)
      Flush (nout)

      Call x04cbf('General',' ',m,m,u,ldu,'1P,E12.4','Orthogonal matrix U',    &
        'Integer',rlabs,'Integer',clabs,80,0,ifail)

      Write (nout,*)
      Flush (nout)

      Call x04cbf('General',' ',p,p,v,ldv,'1P,E12.4','Orthogonal matrix V',    &
        'Integer',rlabs,'Integer',clabs,80,0,ifail)

      Write (nout,*)
      Flush (nout)

      Call x04cbf('General',' ',n,n,q,ldq,'1P,E12.4','Orthogonal matrix Q',    &
        'Integer',rlabs,'Integer',clabs,80,0,ifail)

      Write (nout,*)
      Flush (nout)

      Call x04cbf('Upper triangular','Non-unit',irank,irank,a(1,n-irank+1),    &
        lda,'1P,E12.4','Nonsingular upper triangular matrix R','Integer',      &
        rlabs,'Integer',clabs,80,0,ifail)

      Write (nout,*)
      Write (nout,*) 'Number of cycles of the Kogbetliantz method'
      Write (nout,99999) ncycle

99999 Format (1X,I5)
99998 Format (3X,8(1P,E12.4))
    End Program f08vgfe


f08vnfe.f90

    Program f08vnfe

!     F08VNF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: nag_wp, x02ajf, x04dbf, zggsvd, ztrcon
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: eps, rcond, serrbd
      Integer                          :: i, ifail, info, irank, j, k, l, lda, &
                                          ldb, ldq, ldu, ldv, m, n, p
!     .. Local Arrays ..
      Complex (Kind=nag_wp), Allocatable :: a(:,:), b(:,:), q(:,:), u(:,:),    &
                                          v(:,:), work(:)
      Real (Kind=nag_wp), Allocatable  :: alpha(:), beta(:), rwork(:)
      Integer, Allocatable             :: iwork(:)
      Character (1)                    :: clabs(1), rlabs(1)
!     .. Executable Statements ..
      Write (nout,*) 'F08VNF Example Program Results'
      Write (nout,*)
      Flush (nout)
!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) m, n, p
      lda = m
      ldb = p
      ldq = n
      ldu = m
      ldv = p
      Allocate (a(lda,n),b(ldb,n),q(ldq,n),u(ldu,m),v(ldv,p),work(m+3*n),      &
        alpha(n),beta(n),rwork(2*n),iwork(n))

!     Read the m by n matrix A and p by n matrix B from data file

      Read (nin,*)(a(i,1:n),i=1,m)
      Read (nin,*)(b(i,1:n),i=1,p)

!     Compute the generalized singular value decomposition of (A, B)
!     (A = U*D1*(0 R)*(Q**H), B = V*D2*(0 R)*(Q**H), m.ge.n)
!     The NAG name equivalent of zggsvd is f08vnf
      Call zggsvd('U','V','Q',m,n,p,k,l,a,lda,b,ldb,alpha,beta,u,ldu,v,ldv,q,  &
        ldq,work,rwork,iwork,info)

      If (info==0) Then

!       Print solution

        irank = k + l
        Write (nout,*) 'Number of infinite generalized singular values (K)'
        Write (nout,99999) k
        Write (nout,*) 'Number of finite generalized singular values (L)'
        Write (nout,99999) l
        Write (nout,*) 'Numerical rank of (A**H B**H)**H (K+L)'
        Write (nout,99999) irank
        Write (nout,*)
        Write (nout,*) 'Finite generalized singular values'
        Write (nout,99998)(alpha(j)/beta(j),j=k+1,irank)

        Write (nout,*)
        Flush (nout)

!       ifail: behaviour on error exit
!              =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
        ifail = 0
        Call x04dbf('General',' ',m,m,u,ldu,'Bracketed','1P,E12.4',            &
          'Unitary matrix U','Integer',rlabs,'Integer',clabs,80,0,ifail)

        Write (nout,*)
        Flush (nout)

        Call x04dbf('General',' ',p,p,v,ldv,'Bracketed','1P,E12.4',            &
          'Unitary matrix V','Integer',rlabs,'Integer',clabs,80,0,ifail)

        Write (nout,*)
        Flush (nout)

        Call x04dbf('General',' ',n,n,q,ldq,'Bracketed','1P,E12.4',            &
          'Unitary matrix Q','Integer',rlabs,'Integer',clabs,80,0,ifail)

        Write (nout,*)
        Flush (nout)

        Call x04dbf('Upper triangular','Non-unit',irank,irank,a(1,n-irank+1),  &
          lda,'Bracketed','1P,E12.4','Nonsingular upper triangular matrix R',  &
          'Integer',rlabs,'Integer',clabs,80,0,ifail)

!       Call ZTRCON (F07TUF) to estimate the reciprocal condition
!       number of R

        Call ztrcon('Infinity-norm','Upper','Non-unit',irank,a(1,n-irank+1),   &
          lda,rcond,work,rwork,info)

        Write (nout,*)
        Write (nout,*) 'Estimate of reciprocal condition number for R'
        Write (nout,99997) rcond
        Write (nout,*)

!       So long as irank = n, get the machine precision, eps, and
!       compute the approximate error bound for the computed
!       generalized singular values

        If (irank==n) Then
          eps = x02ajf()
          serrbd = eps/rcond
          Write (nout,*) 'Error estimate for the generalized singular values'
          Write (nout,99997) serrbd
        Else
          Write (nout,*) '(A**H B**H)**H is not of full rank'
        End If
      Else
        Write (nout,99996) 'Failure in ZGGSVD. INFO =', info
      End If

99999 Format (1X,I5)
99998 Format (4X,8(1P,E13.4))
99997 Format (3X,1P,E11.1)
99996 Format (1X,A,I4)
    End Program f08vnfe


f08vqfe.f90

    Program f08vqfe

!     F08VQF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: nag_wp, x02ajf, x04dbf, zggsvd3, ztrcon
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: eps, rcond, serrbd
      Integer                          :: i, ifail, info, irank, j, k, l, lda, &
                                          ldb, ldq, ldu, ldv, lwork, m, n, p
!     .. Local Arrays ..
      Complex (Kind=nag_wp), Allocatable :: a(:,:), b(:,:), q(:,:), u(:,:),    &
                                          v(:,:), work(:)
      Complex (Kind=nag_wp)            :: wdum(1)
      Real (Kind=nag_wp), Allocatable  :: alpha(:), beta(:), rwork(:)
      Integer, Allocatable             :: iwork(:)
      Character (1)                    :: clabs(1), rlabs(1)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: nint, real
!     .. Executable Statements ..
      Write (nout,*) 'F08VQF Example Program Results'
      Write (nout,*)
      Flush (nout)
!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) m, n, p
      lda = m
      ldb = p
      ldq = n
      ldu = m
      ldv = p
      Allocate (a(lda,n),b(ldb,n),q(ldq,n),u(ldu,m),v(ldv,p),alpha(n),beta(n), &
        rwork(2*n),iwork(n))

!     Perform workspace query to get optimal size of work
!     The NAG name equivalent of zggsvd3 is f08vqf
      lwork = -1
      Call zggsvd3('U','V','Q',m,n,p,k,l,a,lda,b,ldb,alpha,beta,u,ldu,v,ldv,q, &
        ldq,wdum,lwork,rwork,iwork,info)
      lwork = nint(real(wdum(1)))
      Allocate (work(lwork))

!     Read the m by n matrix A and p by n matrix B from data file

      Read (nin,*)(a(i,1:n),i=1,m)
      Read (nin,*)(b(i,1:n),i=1,p)

!     Compute the generalized singular value decomposition of (A, B)
!     (A = U*D1*(0 R)*(Q**H), B = V*D2*(0 R)*(Q**H), m.ge.n)
!     The NAG name equivalent of zggsvd3 is f08vqf
      Call zggsvd3('U','V','Q',m,n,p,k,l,a,lda,b,ldb,alpha,beta,u,ldu,v,ldv,q, &
        ldq,work,lwork,rwork,iwork,info)

      If (info==0) Then

!       Print solution

        irank = k + l
        Write (nout,*) 'Number of infinite generalized singular values (K)'
        Write (nout,99999) k
        Write (nout,*) 'Number of finite generalized singular values (L)'
        Write (nout,99999) l
        Write (nout,*) 'Numerical rank of (A**T B**T)**T (K+L)'
        Write (nout,99999) irank
        Write (nout,*)
        Write (nout,*) 'Finite generalized singular values'
        Write (nout,99998)(alpha(j)/beta(j),j=k+1,irank)

        Write (nout,*)
        Flush (nout)

!       ifail: behaviour on error exit
!              =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
        ifail = 0
        Call x04dbf('General',' ',m,m,u,ldu,'Bracketed','1P,E12.4',            &
          'Unitary matrix U','Integer',rlabs,'Integer',clabs,80,0,ifail)

        Write (nout,*)
        Flush (nout)

        Call x04dbf('General',' ',p,p,v,ldv,'Bracketed','1P,E12.4',            &
          'Unitary matrix V','Integer',rlabs,'Integer',clabs,80,0,ifail)

        Write (nout,*)
        Flush (nout)

        Call x04dbf('General',' ',n,n,q,ldq,'Bracketed','1P,E12.4',            &
          'Unitary matrix Q','Integer',rlabs,'Integer',clabs,80,0,ifail)

        Write (nout,*)
        Flush (nout)

        Call x04dbf('Upper triangular','Non-unit',irank,irank,a(1,n-irank+1),  &
          lda,'Bracketed','1P,E12.4','Nonsingular upper triangular matrix R',  &
          'Integer',rlabs,'Integer',clabs,80,0,ifail)

!       Call ZTRCON (F07TUF) to estimate the reciprocal condition
!       number of R

        Call ztrcon('Infinity-norm','Upper','Non-unit',irank,a(1,n-irank+1),   &
          lda,rcond,work,rwork,info)

        Write (nout,*)
        Write (nout,*) 'Estimate of reciprocal condition number for R'
        Write (nout,99997) rcond
        Write (nout,*)

!       So long as irank = n, get the machine precision, eps, and
!       compute the approximate error bound for the computed
!       generalized singular values

        If (irank==n) Then
          eps = x02ajf()
          serrbd = eps/rcond
          Write (nout,*) 'Error estimate for the generalized singular values'
          Write (nout,99997) serrbd
        Else
          Write (nout,*) '(A**T B**T)**T is not of full rank'
        End If
      Else
        Write (nout,99996) 'Failure in ZGGSVD3. INFO =', info
      End If

99999 Format (1X,I5)
99998 Format (4X,8(1P,E13.4))
99997 Format (3X,1P,E11.1)
99996 Format (1X,A,I4)
    End Program f08vqfe


f08vsfe.f90

    Program f08vsfe

!     F08VSF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: f06uaf, nag_wp, x02ajf, x04dbf, zggsvp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: eps, tola, tolb
      Integer                          :: i, ifail, info, irank, k, l, lda,    &
                                          ldb, ldq, ldu, ldv, m, n, p
!     .. Local Arrays ..
      Complex (Kind=nag_wp), Allocatable :: a(:,:), b(:,:), q(:,:), tau(:),    &
                                          u(:,:), v(:,:), work(:)
      Real (Kind=nag_wp), Allocatable  :: rwork(:)
      Integer, Allocatable             :: iwork(:)
      Character (1)                    :: clabs(1), rlabs(1)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: max, real
!     .. Executable Statements ..
      Write (nout,*) 'F08VSF Example Program Results'
      Write (nout,*)
      Flush (nout)
!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) m, n, p
      lda = m
      ldb = p
      ldq = n
      ldu = m
      ldv = p
      Allocate (a(lda,n),b(ldb,n),q(ldq,n),tau(n),u(ldu,m),v(ldv,p),           &
        work(m+3*n+p),rwork(2*n),iwork(n))

!     Read the m by n matrix A and p by n matrix B from data file

      Read (nin,*)(a(i,1:n),i=1,m)
      Read (nin,*)(b(i,1:n),i=1,p)

!     Compute tola and tolb as
!         tola = max(m,n)*norm(A)*macheps
!         tolb = max(p,n)*norm(B)*macheps

      eps = x02ajf()
      tola = real(max(m,n),kind=nag_wp)*f06uaf('One-norm',m,n,a,lda,rwork)*eps
      tolb = real(max(p,n),kind=nag_wp)*f06uaf('One-norm',p,n,b,ldb,rwork)*eps

!     Compute the factorization of (A, B)
!         (A = U*S*(Q**H), B = V*T*(Q**H))

!     The NAG name equivalent of zggsvp is f08vsf
      Call zggsvp('U','V','Q',m,p,n,a,lda,b,ldb,tola,tolb,k,l,u,ldu,v,ldv,q,   &
        ldq,iwork,rwork,tau,work,info)

!     Print solution

      irank = k + l
      Write (nout,*) 'Numerical rank of (A**T B**T)**T (K+L)'
      Write (nout,99999) irank

      Write (nout,*)
      Flush (nout)
      If (m>=irank) Then

!       ifail: behaviour on error exit
!              =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
        ifail = 0
        Call x04dbf('Upper','Non-unit',irank,irank,a(1,n-irank+1),lda,         &
          'Bracketed','1P,E12.4','Upper triangular matrix S','Integer',rlabs,  &
          'Integer',clabs,80,0,ifail)

      Else

        ifail = 0
        Call x04dbf('Upper','Non-unit',m,irank,a(1,n-irank+1),lda,'Bracketed', &
          '1P,E12.4','Upper trapezoidal matrix S','Integer',rlabs,'Integer',   &
          clabs,80,0,ifail)

      End If
      Write (nout,*)
      Flush (nout)

      ifail = 0
      Call x04dbf('Upper','Non-unit',l,l,b(1,n-l+1),ldb,'Bracketed',           &
        '1P,E12.4','Upper triangular matrix T','Integer',rlabs,'Integer',      &
        clabs,80,0,ifail)

      Write (nout,*)
      Flush (nout)

      ifail = 0
      Call x04dbf('General',' ',m,m,u,ldu,'Bracketed','1P,E12.4',              &
        'Unitary matrix U','Integer',rlabs,'Integer',clabs,80,0,ifail)

      Write (nout,*)
      Flush (nout)

      ifail = 0
      Call x04dbf('General',' ',p,p,v,ldv,'Bracketed','1P,E12.4',              &
        'Unitary matrix V','Integer',rlabs,'Integer',clabs,80,0,ifail)

      Write (nout,*)
      Flush (nout)

      ifail = 0
      Call x04dbf('General',' ',n,n,q,ldq,'Bracketed','1P,E12.4',              &
        'Unitary matrix Q','Integer',rlabs,'Integer',clabs,80,0,ifail)

99999 Format (1X,I5)
    End Program f08vsfe


f08vufe.f90

    Program f08vufe

!     F08VUF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: f06uaf, nag_wp, x02ajf, x04dbf, zggsvp3, ztgsja
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: eps, tola, tolb
      Integer                          :: i, ifail, info, irank, j, k, l, lda, &
                                          ldb, ldq, ldu, ldv, lwork, m, n,     &
                                          ncycle, p
!     .. Local Arrays ..
      Complex (Kind=nag_wp), Allocatable :: a(:,:), b(:,:), q(:,:), tau(:),    &
                                          u(:,:), v(:,:), work(:)
      Complex (Kind=nag_wp)            :: wdum(1)
      Real (Kind=nag_wp), Allocatable  :: alpha(:), beta(:), rwork(:)
      Integer, Allocatable             :: iwork(:)
      Character (1)                    :: clabs(1), rlabs(1)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: max, nint, real
!     .. Executable Statements ..
      Write (nout,*) 'F08VUF Example Program Results'
      Write (nout,*)
      Flush (nout)
!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) m, n, p
      lda = m
      ldb = p
      ldq = n
      ldu = m
      ldv = p
      Allocate (a(lda,n),alpha(n),b(ldb,n),beta(n),q(ldq,n),tau(n),u(ldu,m),   &
        v(ldv,p),rwork(2*n),iwork(n))

!     Perform workspace query to get optimal size of work
!     The NAG name equivalent of zggsvp3 is f08vuf
      lwork = -1
      Call zggsvp3('U','V','Q',m,p,n,a,lda,b,ldb,tola,tolb,k,l,u,ldu,v,ldv,q,  &
        ldq,iwork,rwork,tau,wdum,lwork,info)
      lwork = nint(real(wdum(1)))
      Allocate (work(lwork))

!     Read the m by n matrix A and p by n matrix B from data file

      Read (nin,*)(a(i,1:n),i=1,m)
      Read (nin,*)(b(i,1:n),i=1,p)

!     Compute tola and tolb as
!         tola = max(m,n)*norm(A)*macheps
!         tolb = max(p,n)*norm(B)*macheps

      eps = x02ajf()
      tola = real(max(m,n),kind=nag_wp)*f06uaf('One-norm',m,n,a,lda,rwork)*eps
      tolb = real(max(p,n),kind=nag_wp)*f06uaf('One-norm',p,n,b,ldb,rwork)*eps

!     Compute the factorization of (A, B)
!         (A = U*S*(Q**H), B = V*T*(Q**H))

!     The NAG name equivalent of zggsvp3 is f08vuf
      Call zggsvp3('U','V','Q',m,p,n,a,lda,b,ldb,tola,tolb,k,l,u,ldu,v,ldv,q,  &
        ldq,iwork,rwork,tau,work,lwork,info)

!     Compute the generalized singular value decomposition of (A, B)
!         (A = U*D1*(0 R)*(Q**H), B = V*D2*(0 R)*(Q**H))

      Deallocate (work)
      Allocate (work(2*n))

!     The NAG name equivalent of ztgsja is f08ysf
      Call ztgsja('U','V','Q',m,p,n,k,l,a,lda,b,ldb,tola,tolb,alpha,beta,u,    &
        ldu,v,ldv,q,ldq,work,ncycle,info)

!     Print solution

      irank = k + l
      Write (nout,*) 'Number of infinite generalized singular values (k)'
      Write (nout,99999) k
      Write (nout,*) 'Number of finite generalized singular values (l)'
      Write (nout,99999) l
      Write (nout,*) 'Effective Numerical rank of (A; B) (k+l)'
      Write (nout,99999) irank
      Write (nout,*)
      Write (nout,*) 'Finite generalized singular values'
      Write (nout,99998)(alpha(j)/beta(j),j=k+1,irank)
      Write (nout,*)
      Flush (nout)

!     ifail: behaviour on error exit
!            =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
      ifail = 0
      Call x04dbf('General',' ',m,m,u,ldu,'Bracketed','1P,E12.4',              &
        'Unitary matrix U','Integer',rlabs,'Integer',clabs,80,0,ifail)

      Write (nout,*)
      Flush (nout)

      Call x04dbf('General',' ',p,p,v,ldv,'Bracketed','1P,E12.4',              &
        'Unitary matrix V','Integer',rlabs,'Integer',clabs,80,0,ifail)

      Write (nout,*)
      Flush (nout)

      Call x04dbf('General',' ',n,n,q,ldq,'Bracketed','1P,E12.4',              &
        'Unitary matrix Q','Integer',rlabs,'Integer',clabs,80,0,ifail)

      Write (nout,*)
      Flush (nout)

      Call x04dbf('Upper triangular','Non-unit',irank,irank,a(1,n-irank+1),    &
        lda,'Bracketed','1P,E12.4','Nonsingular upper triangular matrix R',    &
        'Integer',rlabs,'Integer',clabs,80,0,ifail)

      Write (nout,*)
      Write (nout,*) 'Number of cycles of the Kogbetliantz method'
      Write (nout,99999) ncycle

99999 Format (1X,I5)
99998 Format (3X,8(1P,E12.4))
    End Program f08vufe


f08wafe.f90

    Program f08wafe

!     F08WAF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: dggev, m01def, m01eaf, nag_wp, x02ajf, x02amf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Real (Kind=nag_wp), Parameter    :: zero = 0.0_nag_wp
      Integer, Parameter               :: nb = 64, nin = 5, nout = 6
!     .. Local Scalars ..
      Complex (Kind=nag_wp)            :: eig
      Real (Kind=nag_wp)               :: scal_i, scal_r, small
      Integer                          :: i, ifail, info, j, k, lda, ldb,      &
                                          ldvr, lwork, n
      Logical                          :: pair
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: a(:,:), alphai(:), alphar(:),        &
                                          b(:,:), beta(:), vr(:,:), vr_row(:), &
                                          work(:)
      Real (Kind=nag_wp)               :: dummy(1,1)
      Integer, Allocatable             :: irank(:)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: abs, all, cmplx, max, maxloc, nint,  &
                                          sqrt
!     .. Executable Statements ..
      Write (nout,*) 'F08WAF Example Program Results'
!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) n
      lda = n
      ldb = n
      ldvr = n
      Allocate (a(lda,n),alphai(n),alphar(n),b(ldb,n),beta(n),vr(ldvr,n),      &
        irank(n))

!     Use routine workspace query to get optimal workspace.
      lwork = -1
!     The NAG name equivalent of dggev is f08waf
      Call dggev('No left vectors','Vectors (right)',n,a,lda,b,ldb,alphar,     &
        alphai,beta,dummy,1,vr,ldvr,dummy,lwork,info)

!     Make sure that there is enough workspace for block size nb.
      lwork = max((nb+7)*n,nint(dummy(1,1)))
      Allocate (work(lwork))

!     Read in the matrices A and B

      Read (nin,*)(a(i,1:n),i=1,n)
      Read (nin,*)(b(i,1:n),i=1,n)

!     Solve the generalized eigenvalue problem

!     The NAG name equivalent of dggev is f08waf
      Call dggev('No left vectors','Vectors (right)',n,a,lda,b,ldb,alphar,     &
        alphai,beta,dummy,1,vr,ldvr,work,lwork,info)

      If (info>0) Then
        Write (nout,*)
        Write (nout,99999) 'Failure in DGGEV. INFO =', info
      Else
!       If beta(:) > eps, Order eigenvalues by ascending real parts
!       and then by ascending imaginary parts
        If (all(abs(beta(1:n))>x02ajf())) Then
          work(1:n) = alphar(1:n)/beta(1:n)
          work(n+1:2*n) = alphai(1:n)/beta(1:n)
          ifail = 0
          Call m01def(work,n,1,n,1,2,'Ascending',irank,ifail)
          Call m01eaf(alphar,1,n,irank,ifail)
          Call m01eaf(alphai,1,n,irank,ifail)
          Call m01eaf(beta,1,n,irank,ifail)
!         Order the eigenvectors in the same way
          Allocate (vr_row(n))
          Do j = 1, n
            vr_row(1:n) = vr(j,1:n)
            Call m01eaf(vr_row,1,n,irank,ifail)
            vr(j,1:n) = vr_row(1:n)
          End Do
          Deallocate (vr_row)
        End If
        small = x02amf()
        pair = .False.
        Do j = 1, n
          Write (nout,*)
          If ((abs(alphar(j))+abs(alphai(j)))*small>=abs(beta(j))) Then
            Write (nout,99998) 'Eigenvalue(', j, ')',                          &
              ' is numerically infinite or undetermined', 'ALPHAR(', j,        &
              ') = ', alphar(j), ', ALPHAI(', j, ') = ', alphai(j), ', BETA(', &
              j, ') = ', beta(j)
          Else
            If (alphai(j)==zero) Then
              Write (nout,99997) 'Eigenvalue(', j, ') = ', alphar(j)/beta(j)
            Else
              eig = cmplx(alphar(j),alphai(j),kind=nag_wp)/                    &
                cmplx(beta(j),kind=nag_wp)
              Write (nout,99996) 'Eigenvalue(', j, ') = ', eig
            End If
          End If
          Write (nout,*)
          Write (nout,99995) 'Eigenvector(', j, ')'
          If (alphai(j)==zero) Then
!           Let largest element be positive
            work(1:n) = abs(vr(1:n,j))
            k = maxloc(work(1:n),1)
            If (vr(k,j)<zero) Then
              vr(1:n,j) = -vr(1:n,j)
            End If
            Write (nout,99994)(vr(i,j),i=1,n)
          Else
            If (pair) Then
              Write (nout,99993)(vr(i,j-1),-vr(i,j),i=1,n)
            Else
!             Let largest element be real (and positive).
              work(1:n) = vr(1:n,j)**2 + vr(1:n,j+1)**2
              k = maxloc(work(1:n),1)
              scal_r = vr(k,j)/sqrt(work(k))
              scal_i = -vr(k,j+1)/sqrt(work(k))
              work(1:n) = vr(1:n,j)
              vr(1:n,j) = scal_r*work(1:n) - scal_i*vr(1:n,j+1)
              vr(1:n,j+1) = scal_r*vr(1:n,j+1) + scal_i*work(1:n)
              Write (nout,99993)(vr(i,j),vr(i,j+1),i=1,n)
            End If
            pair = .Not. pair
          End If
        End Do

      End If

99999 Format (1X,A,I4)
99998 Format (1X,A,I2,2A,/,1X,2(A,I2,A,1P,F11.3,3X),A,I2,A,1P,F11.3)
99997 Format (1X,A,I2,A,1P,F11.3)
99996 Format (1X,A,I2,A,'(',1P,F11.3,',',1P,F11.3,')')
99995 Format (1X,A,I2,A)
99994 Format (1X,1P,F11.5)
99993 Format (1X,'(',1P,F11.5,',',1P,F11.5,')')
    End Program f08wafe


f08wbfe.f90

    Program f08wbfe

!     F08WBF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: dggevx, dnrm2, m01daf, m01eaf, nag_wp, x02ajf,    &
                             x02amf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nb = 64, nin = 5, nout = 6
!     .. Local Scalars ..
      Complex (Kind=nag_wp)            :: eig
      Real (Kind=nag_wp)               :: abnrm, bbnrm, eps, jswap, rcnd,      &
                                          scal_i, scal_r, small
      Integer                          :: i, ifail, ihi, ilo, info, j, k, lda, &
                                          ldb, ldvr, lwork, n
      Logical                          :: pair
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: a(:,:), alphai(:), alphar(:),        &
                                          b(:,:), beta(:), lscale(:),          &
                                          rconde(:), rcondv(:), rscale(:),     &
                                          vr(:,:), vr_row(:), work(:)
      Real (Kind=nag_wp)               :: dummy(1,1)
      Integer, Allocatable             :: iwork(:)
      Logical, Allocatable             :: bwork(:)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: abs, all, cmplx, max, maxloc, nint,  &
                                          sqrt, sum
!     .. Executable Statements ..
      Write (nout,*) 'F08WBF Example Program Results'
!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) n
      lda = n
      ldb = n
      ldvr = n
      Allocate (a(lda,n),alphai(n),alphar(n),b(ldb,n),beta(n),lscale(n),       &
        rconde(n),rcondv(n),rscale(n),vr(ldvr,n),iwork(n+6),bwork(n))

!     Use routine workspace query to get optimal workspace.
      lwork = -1
!     The NAG name equivalent of dggevx is f08wbf
      Call dggevx('Balance','No vectors (left)','Vectors (right)',             &
        'Both reciprocal condition numbers',n,a,lda,b,ldb,alphar,alphai,beta,  &
        dummy,1,vr,ldvr,ilo,ihi,lscale,rscale,abnrm,bbnrm,rconde,rcondv,dummy, &
        lwork,iwork,bwork,info)

!     Make sure that there is enough workspace for block size nb.
      lwork = max((nb+2*n)*n,nint(dummy(1,1)))
      Allocate (work(lwork))

!     Read in the matrices A and B

      Read (nin,*)(a(i,1:n),i=1,n)
      Read (nin,*)(b(i,1:n),i=1,n)

!     Solve the generalized eigenvalue problem

!     The NAG name equivalent of dggevx is f08wbf
      Call dggevx('Balance','No vectors (left)','Vectors (right)',             &
        'Both reciprocal condition numbers',n,a,lda,b,ldb,alphar,alphai,beta,  &
        dummy,1,vr,ldvr,ilo,ihi,lscale,rscale,abnrm,bbnrm,rconde,rcondv,work,  &
        lwork,iwork,bwork,info)

      If (info>0) Then
        Write (nout,*)
        Write (nout,99999) 'Failure in DGGEVX. INFO =', info
      Else

!       Compute the machine precision and the safe range parameter
!       small

        eps = x02ajf()
        small = x02amf()

!       If beta(:) > eps, Order eigenvalues by ascending real parts
        If (all(abs(beta(1:n))>eps)) Then
          work(1:n) = alphar(1:n)/beta(1:n)
          ifail = 0
          Call m01daf(work,1,n,'Ascending',iwork,ifail)
          Call m01eaf(alphar,1,n,iwork,ifail)
          Call m01eaf(alphai,1,n,iwork,ifail)
          Call m01eaf(beta,1,n,iwork,ifail)
!         Order the eigenvectors in the same way
          Allocate (vr_row(n))
          Do j = 1, n
            vr_row(1:n) = vr(j,1:n)
            Call m01eaf(vr_row,1,n,iwork,ifail)
            vr(j,1:n) = vr_row(1:n)
          End Do
          Deallocate (vr_row)
        End If

!       Print out eigenvalues and vectors and associated condition
!       number and bounds

        pair = .False.
        Do j = 1, n

!         Print out information on the j-th eigenvalue

          Write (nout,*)
          If ((abs(alphar(j))+abs(alphai(j)))*small>=abs(beta(j))) Then
            Write (nout,99998) 'Eigenvalue(', j, ')',                          &
              ' is numerically infinite or undetermined', 'ALPHAR(', j,        &
              ') = ', alphar(j), ', ALPHAI(', j, ') = ', alphai(j), ', BETA(', &
              j, ') = ', beta(j)
          Else
            If (.Not. pair) Then
              jswap = 1.0_nag_wp
              If (alphai(j)>0.0_nag_wp) Then
                jswap = -jswap
              End If
            End If
            If (alphai(j)==0.0E0_nag_wp) Then
              Write (nout,99997) 'Eigenvalue(', j, ') = ', alphar(j)/beta(j)
            Else
              eig = cmplx(alphar(j),jswap*alphai(j),kind=nag_wp)/              &
                cmplx(beta(j),kind=nag_wp)
              Write (nout,99996) 'Eigenvalue(', j, ') = ', eig
            End If
          End If
          rcnd = rconde(j)
          Write (nout,*)
          Write (nout,99995) '  Reciprocal condition number = ', rcnd

!         Print out information on the j-th eigenvector

          Write (nout,*)
          Write (nout,99994) 'Eigenvector(', j, ')'
          If (alphai(j)==0.0E0_nag_wp) Then
!           Let largest element be positive
            work(1:n) = abs(vr(1:n,j))
            k = maxloc(work(1:n),1)
            If (vr(k,j)<0.0_nag_wp) Then
              vr(1:n,j) = -vr(1:n,j)/dnrm2(n,vr(1,j),1)
            End If
            Write (nout,99993)(vr(i,j),i=1,n)
          Else
            If (pair) Then
              Write (nout,99992)(vr(i,j-1),-jswap*vr(i,j),i=1,n)
            Else
!             Let largest element be real (and positive).
              work(1:n) = vr(1:n,j)**2 + vr(1:n,j+1)**2
              k = maxloc(work(1:n),1)
              scal_r = vr(k,j)/sqrt(work(k))/sqrt(sum(work(1:n)))
              scal_i = -vr(k,j+1)/sqrt(work(k))/sqrt(sum(work(1:n)))
              work(1:n) = vr(1:n,j)
              vr(1:n,j) = scal_r*work(1:n) - scal_i*vr(1:n,j+1)
              vr(1:n,j+1) = scal_r*vr(1:n,j+1) + scal_i*work(1:n)
              vr(k,j+1) = 0.0_nag_wp
              Write (nout,99992)(vr(i,j),jswap*vr(i,j+1),i=1,n)
            End If
            pair = .Not. pair
          End If
          rcnd = rcondv(j)
          Write (nout,*)
          Write (nout,99995) '  Reciprocal condition number = ', rcnd
        End Do

      End If

99999 Format (1X,A,I4)
99998 Format (/,1X,A,I2,2A,/,1X,2(A,I2,A,F11.5),A,I2,A,F11.5)
99997 Format (/,1X,A,I2,A,F11.5)
99996 Format (/,1X,A,I2,A,'(',F11.5,',',F11.5,')')
99995 Format (1X,A,1P,E8.1)
99994 Format (1X,A,I2,A)
99993 Format (1X,F11.5)
99992 Format (1X,'(',F11.5,',',F11.5,')')
    End Program f08wbfe


f08wcfe.f90

    Program f08wcfe

!     F08WCF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: dggev3, m01def, m01edf, nag_wp, x02ajf, x04caf,   &
                             x04daf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Real (Kind=nag_wp), Parameter    :: zero = 0.0_nag_wp
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Complex (Kind=nag_wp)            :: scal
      Integer                          :: i, ifail, info, j, k, lda, ldb,      &
                                          ldvr, lwork, n
!     .. Local Arrays ..
      Complex (Kind=nag_wp), Allocatable :: eigval(:), eigvec(:,:)
      Real (Kind=nag_wp), Allocatable  :: a(:,:), alphai(:), alphar(:),        &
                                          b(:,:), beta(:), vr(:,:), work(:)
      Real (Kind=nag_wp)               :: dummy(1,1)
      Integer, Allocatable             :: irank(:)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: abs, all, cmplx, conjg, maxloc, nint
!     .. Executable Statements ..
      Write (nout,*) 'F08WCF Example Program Results'
!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) n
      lda = n
      ldb = n
      ldvr = n
      Allocate (a(lda,n),alphai(n),alphar(n),b(ldb,n),beta(n),vr(ldvr,n),      &
        eigvec(n,n),eigval(n),irank(n))

!     Use routine workspace query to get optimal workspace.
      lwork = -1
!     The NAG name equivalent of dggev3 is f08wcf
      Call dggev3('No left vectors','Vectors (right)',n,a,lda,b,ldb,alphar,    &
        alphai,beta,dummy,1,vr,ldvr,dummy,lwork,info)

      lwork = nint(dummy(1,1))
      Allocate (work(lwork))

!     Read in the matrices A and B

      Read (nin,*)(a(i,1:n),i=1,n)
      Read (nin,*)(b(i,1:n),i=1,n)

!     Solve the generalized eigenvalue problem

!     The NAG name equivalent of dggev3 is f08wcf
      Call dggev3('No left vectors','Vectors (right)',n,a,lda,b,ldb,alphar,    &
        alphai,beta,dummy,1,vr,ldvr,work,lwork,info)
      If (info>0) Then
        Write (nout,*)
        Write (nout,99999) 'Failure in DGGEV3. INFO =', info
        Go To 100
      End If

!     Re-normalize the eigenvectors, largest absolute element real
      j = 0
      Do i = 1, n
        If (alphai(i)==zero) Then
          eigvec(1:n,i) = cmplx(vr(1:n,i),zero,kind=nag_wp)
        Else If (j==0) Then
          eigvec(1:n,i) = cmplx(vr(1:n,i),vr(1:n,i+1),kind=nag_wp)
          j = 1
        Else
          eigvec(1:n,i) = cmplx(vr(1:n,i-1),-vr(1:n,i),kind=nag_wp)
          j = 0
        End If
        work(1:n) = abs(eigvec(1:n,i))
        k = maxloc(work(1:n),1)
        scal = conjg(eigvec(k,i))/abs(eigvec(k,i))
        eigvec(1:n,i) = eigvec(1:n,i)*scal
      End Do

!     If eigenvalues are finite, order by descending absolute values
      If (all(abs(beta(1:n))>x02ajf())) Then
!       add small amount to alphai to distinguish conjugates
        alphai(1:n) = alphai(1:n) + x02ajf()*10.0_nag_wp
        eigval(1:n) = cmplx(alphar(1:n),alphai(1:n),kind=nag_wp)
        eigval(1:n) = eigval(1:n)/beta(1:n)
        work(1:n) = abs(eigval(1:n))
        ifail = 0
        Call m01def(work,n,1,n,1,1,'Descending',irank,ifail)
        Call m01edf(eigval,1,n,irank,ifail)

!       Print ordered eigenvalues
        ifail = 0
        Call x04daf('Gen',' ',1,n,eigval,1,'Eigenvalues:',ifail)

!       Order the eigenvectors in the same way and print
        Do j = 1, n
          eigval(1:n) = eigvec(j,1:n)
          Call m01edf(eigval,1,n,irank,ifail)
          eigvec(j,1:n) = eigval(1:n)
        End Do

        Write (nout,*)
        ifail = 0
        Call x04daf('Gen',' ',n,n,eigvec,n,'Right Eigenvectors (columns):',    &
          ifail)
      Else
        Write (nout,*) 'Some of the eigenvalues are infinite'
        Write (nout,*)
        ifail = 0
        Call x04caf('Gen',' ',1,n,alphar,1,'Alpha (real):',ifail)
        Call x04caf('Gen',' ',1,n,alphai,1,'Alpha (imag):',ifail)
        Call x04caf('Gen',' ',1,n,beta,1,'Beta:',ifail)
      End If
100   Continue

99999 Format (1X,A,I4)
    End Program f08wcfe


f08wnfe.f90

    Program f08wnfe

!     F08WNF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: m01daf, m01edf, nag_wp, x02ajf, x04daf, zggev
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Real (Kind=nag_wp), Parameter    :: one = 1.0_nag_wp
      Real (Kind=nag_wp), Parameter    :: zero = 0.0_nag_wp
      Integer, Parameter               :: nb = 64, nin = 5, nout = 6
      Complex (Kind=nag_wp), Parameter :: cone = (one,zero)
!     .. Local Scalars ..
      Complex (Kind=nag_wp)            :: scal
      Integer                          :: i, ifail, info, j, k, lda, ldb,      &
                                          ldvr, lwork, n
!     .. Local Arrays ..
      Complex (Kind=nag_wp), Allocatable :: a(:,:), alpha(:), b(:,:), beta(:), &
                                          vr(:,:), work(:)
      Complex (Kind=nag_wp)            :: dummy(1,1)
      Real (Kind=nag_wp), Allocatable  :: rwork(:)
      Integer, Allocatable             :: irank(:)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: abs, all, max, maxloc, nint, real
!     .. Executable Statements ..
      Write (nout,*) 'F08WNF Example Program Results'
!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) n
      lda = n
      ldb = n
      ldvr = n
      Allocate (a(lda,n),alpha(n),b(ldb,n),beta(n),vr(ldvr,n),rwork(8*n))

!     Use routine workspace query to get optimal workspace.
      lwork = -1
!     The NAG name equivalent of zggev is f08wnf
      Call zggev('No left vectors','Vectors (right)',n,a,lda,b,ldb,alpha,beta, &
        dummy,1,vr,ldvr,dummy,lwork,rwork,info)

!     Make sure that there is enough workspace for block size nb.
      lwork = max((nb+1)*n,nint(real(dummy(1,1))))
      Allocate (work(lwork))

!     Read in the matrices A and B

      Read (nin,*)(a(i,1:n),i=1,n)
      Read (nin,*)(b(i,1:n),i=1,n)

!     Solve the generalized eigenvalue problem

!     The NAG name equivalent of zggev is f08wnf
      Call zggev('No left vectors','Vectors (right)',n,a,lda,b,ldb,alpha,beta, &
        dummy,1,vr,ldvr,work,lwork,rwork,info)

      If (info>0) Then
        Write (nout,*)
        Write (nout,99999) 'Failure in ZGGEV. INFO =', info
      Else
!       Re-normalize the eigenvectors, largest absolute element real (=1)
        Do i = 1, n
          rwork(1:n) = abs(vr(1:n,i))
          k = maxloc(rwork(1:n),1)
          scal = cone/vr(k,i)
          vr(1:n,i) = vr(1:n,i)*scal
          vr(k,i) = cone
        End Do

        Write (nout,*)
        If (all(abs(beta(1:n))>x02ajf())) Then
!         Reorder eigenvalues by descending absolute value and print
          alpha(1:n) = alpha(1:n)/beta(1:n)
          rwork(1:n) = abs(alpha(1:n))
          Allocate (irank(n))
          ifail = 0
          Call m01daf(rwork,1,n,'Descending',irank,ifail)
          Call m01edf(alpha,1,n,irank,ifail)
          ifail = 0
          Call x04daf('Gen',' ',1,n,alpha,1,'Eigenvalues:',ifail)

!         Reorder eigenvectors accordingly
          Do j = 1, n
            beta(1:n) = vr(j,1:n)
            Call m01edf(beta,1,n,irank,ifail)
            vr(j,1:n) = beta(1:n)
          End Do
        Else
          Write (nout,*)                                                       &
            'Some of the eigenvalues are infinite or undetermined'
          Write (nout,*)
          ifail = 0
          Call x04daf('Gen',' ',1,n,alpha,1,'Alpha:',ifail)
          Call x04daf('Gen',' ',1,n,beta,1,'Beta:',ifail)
        End If
        Write (nout,*)
        ifail = 0
        Call x04daf('Gen',' ',n,n,vr,ldvr,'Eigenvectors (columns):',ifail)
      End If

99999 Format (1X,A,I4)
    End Program f08wnfe


f08wpfe.f90

    Program f08wpfe

!     F08WPF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: f06bnf, nag_wp, x02ajf, x02amf, zggevx
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nb = 64, nin = 5, nout = 6
!     .. Local Scalars ..
      Complex (Kind=nag_wp)            :: eig, scal
      Real (Kind=nag_wp)               :: abnorm, abnrm, bbnrm, eps, small,    &
                                          tol
      Integer                          :: i, ihi, ilo, info, j, k, lda, ldb,   &
                                          ldvr, lwork, n
!     .. Local Arrays ..
      Complex (Kind=nag_wp), Allocatable :: a(:,:), alpha(:), b(:,:), beta(:), &
                                          vr(:,:), work(:)
      Complex (Kind=nag_wp)            :: dummy(1,1)
      Real (Kind=nag_wp), Allocatable  :: lscale(:), rconde(:), rcondv(:),     &
                                          rscale(:), rwork(:)
      Integer, Allocatable             :: iwork(:)
      Logical, Allocatable             :: bwork(:)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: abs, max, maxloc, nint, real
!     .. Executable Statements ..
      Write (nout,*) 'F08WPF Example Program Results'
!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) n
      lda = n
      ldb = n
      ldvr = n
      Allocate (a(lda,n),alpha(n),b(ldb,n),beta(n),vr(ldvr,n),lscale(n),       &
        rconde(n),rcondv(n),rscale(n),rwork(6*n),iwork(n+2),bwork(n))

!     Use routine workspace query to get optimal workspace.
      lwork = -1
!     The NAG name equivalent of zggevx is f08wpf
      Call zggevx('Balance','No vectors (left)','Vectors (right)',             &
        'Both reciprocal condition numbers',n,a,lda,b,ldb,alpha,beta,dummy,1,  &
        vr,ldvr,ilo,ihi,lscale,rscale,abnrm,bbnrm,rconde,rcondv,dummy,lwork,   &
        rwork,iwork,bwork,info)

!     Make sure that there is enough workspace for block size nb.
      lwork = max((nb+2*n)*n,nint(real(dummy(1,1))))
      Allocate (work(lwork))

!     Read in the matrices A and B

      Read (nin,*)(a(i,1:n),i=1,n)
      Read (nin,*)(b(i,1:n),i=1,n)

!     Solve the generalized eigenvalue problem

!     The NAG name equivalent of zggevx is f08wpf
      Call zggevx('Balance','No vectors (left)','Vectors (right)',             &
        'Both reciprocal condition numbers',n,a,lda,b,ldb,alpha,beta,dummy,1,  &
        vr,ldvr,ilo,ihi,lscale,rscale,abnrm,bbnrm,rconde,rcondv,work,lwork,    &
        rwork,iwork,bwork,info)

      If (info>0) Then
        Write (nout,*)
        Write (nout,99999) 'Failure in ZGGEVX. INFO =', info
      Else

!       Compute the machine precision, the safe range parameter
!       SMALL and sqrt(ABNRM**2+BBNRM**2)

        eps = x02ajf()
        small = x02amf()
        abnorm = f06bnf(abnrm,bbnrm)
        tol = eps*abnorm

!       Print out eigenvalues and vectors and associated condition
!       number and bounds

        Write (nout,*)
        Write (nout,*) 'Eigenvalues'
        Write (nout,*)
        Write (nout,*) '         Eigenvalue           rcond    error'

        Do j = 1, n

!         Print out information on the j-th eigenvalue

          If ((abs(alpha(j)))*small>=abs(beta(j))) Then
            If (rconde(j)>0.0_nag_wp) Then
              If (tol/rconde(j)<100.0_nag_wp*eps) Then
                Write (nout,99995) j, rconde(j), '-'
              Else
                Write (nout,99994) j, rconde(j), tol/rconde(j)
              End If
            Else
              Write (nout,99995) j, rconde(j), 'Inf'
            End If
          Else
            eig = alpha(j)/beta(j)
            If (rconde(j)>0.0_nag_wp) Then
              If (tol/rconde(j)<100.0_nag_wp*eps) Then
                Write (nout,99998) j, eig, rconde(j), '-'
              Else
                Write (nout,99997) j, eig, rconde(j), tol/rconde(j)
              End If
            Else
              Write (nout,99998) j, eig, rconde(j), 'Inf'
            End If
          End If

        End Do

        Write (nout,*)
        Write (nout,*) 'Eigenvectors'
        Write (nout,*)
        Write (nout,*) '         Eigenvector          rcond    error'

        Do j = 1, n

!         Print information on j-th eigenvector
          Write (nout,*)

!         Re-normalize eigenvector, largest absolute element real (=1)
          rwork(1:n) = abs(vr(1:n,j))
          k = maxloc(rwork(1:n),1)
          scal = (1.0_nag_wp,0.0_nag_wp)/vr(k,j)
          vr(1:n,j) = vr(1:n,j)*scal

          If (rcondv(j)>0.0_nag_wp) Then
            If (tol/rcondv(j)<100.0_nag_wp*eps) Then
              Write (nout,99998) j, vr(1,j), rcondv(j), '-'
            Else
              Write (nout,99997) j, vr(1,j), rcondv(j), tol/rcondv(j)
            End If
          Else
            Write (nout,99998) j, vr(1,j), rcondv(j), 'Inf'
          End If

          Write (nout,99996) vr(2:n,j)

        End Do

        Write (nout,*)
        Write (nout,*) 'Errors below 100*machine precision are not displayed'
      End If

99999 Format (1X,A,I4)
99998 Format (1X,I2,1X,'(',1P,E11.4,',',E11.4,')',1X,0P,F7.4,4X,A)
99997 Format (1X,I2,1X,'(',1P,E11.4,',',E11.4,')',1X,0P,F7.4,1X,1P,E8.1)
99996 Format (1X,3X,'(',1P,E11.4,',',E11.4,')')
99995 Format (1X,I2,1X,'  Infinite or undetermined',1X,0P,F7.4,4X,A)
99994 Format (1X,I2,1X,'  Infinite or undetermined',1X,0P,F7.4,1X,1P,E8.1)

    End Program f08wpfe


f08wqfe.f90

    Program f08wqfe

!     F08WQF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: nag_wp, x02ajf, x04daf, zggev3
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Complex (Kind=nag_wp)            :: scal
      Integer                          :: i, ifail, info, k, lda, ldb, ldvr,   &
                                          lwork, n
!     .. Local Arrays ..
      Complex (Kind=nag_wp), Allocatable :: a(:,:), alpha(:), b(:,:), beta(:), &
                                          vr(:,:), work(:)
      Complex (Kind=nag_wp)            :: dummy(1,1)
      Real (Kind=nag_wp), Allocatable  :: rwork(:)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: abs, all, conjg, maxloc, nint, real
!     .. Executable Statements ..
      Write (nout,*) 'F08WQF Example Program Results'
      Write (nout,*)
!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) n
      lda = n
      ldb = n
      ldvr = n
      Allocate (a(lda,n),alpha(n),b(ldb,n),beta(n),vr(ldvr,n),rwork(8*n))

!     Use routine workspace query to get optimal workspace.
      lwork = -1
!     The NAG name equivalent of zggev3 is f08wqf
      Call zggev3('No left vectors','Vectors (right)',n,a,lda,b,ldb,alpha,     &
        beta,dummy,1,vr,ldvr,dummy,lwork,rwork,info)

      lwork = nint(real(dummy(1,1)))
      Allocate (work(lwork))

!     Read in the matrices A and B

      Read (nin,*)(a(i,1:n),i=1,n)
      Read (nin,*)(b(i,1:n),i=1,n)

!     Solve the generalized eigenvalue problem

!     The NAG name equivalent of zggev3 is f08wqf
      Call zggev3('No left vectors','Vectors (right)',n,a,lda,b,ldb,alpha,     &
        beta,dummy,1,vr,ldvr,work,lwork,rwork,info)

      If (info>0) Then
        Write (nout,*)
        Write (nout,99999) 'Failure in ZGGEV3. INFO =', info
      Else If (all(abs(beta(1:n))>x02ajf())) Then
!       Re-normalize the eigenvectors, largest absolute element real
        Do i = 1, n
          rwork(1:n) = abs(vr(1:n,i))
          k = maxloc(rwork(1:n),1)
          scal = conjg(vr(k,i))/rwork(k)
          vr(1:n,i) = vr(1:n,i)*scal
        End Do
        alpha(1:n) = alpha(1:n)/beta(1:n)
        ifail = 0
        Call x04daf('Gen',' ',1,n,alpha,1,'Eigenvalues:',ifail)
        Write (nout,*)
        Call x04daf('Gen',' ',n,n,vr,ldvr,'Right Eigenvectors (columns):',     &
          ifail)
      Else
        Write (nout,*) 'Some of the eigenvalues are infinite.'
        Write (nout,*)
        ifail = 0
        Call x04daf('Gen',' ',1,n,alpha,1,'Alpha',ifail)
        Call x04daf('Gen',' ',1,n,beta,1,'Beta',ifail)
      End If

99999 Format (1X,A,I4)
    End Program f08wqfe


f08xafe.f90

!   F08XAF Example Program Text
!   Mark 26 Release. NAG Copyright 2016.

    Module f08xafe_mod

!     F08XAF Example Program Module:
!            Parameters and User-defined Routines

!     .. Use Statements ..
      Use nag_library, Only: nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Accessibility Statements ..
      Private
      Public                           :: selctg
!     .. Parameters ..
      Integer, Parameter, Public       :: nb = 64, nin = 5, nout = 6
    Contains
      Function selctg(ar,ai,b)

!       Logical function selctg for use with DGGES (F08XAF)
!       Returns the value .TRUE. if the eigenvalue is real and positive

!       .. Function Return Value ..
        Logical                        :: selctg
!       .. Scalar Arguments ..
        Real (Kind=nag_wp), Intent (In) :: ai, ar, b
!       .. Executable Statements ..
        selctg = (ar>0._nag_wp .And. ai==0._nag_wp .And. b/=0._nag_wp)
        Return
      End Function selctg
    End Module f08xafe_mod
    Program f08xafe

!     F08XAF Example Main Program

!     .. Use Statements ..
      Use nag_library, Only: dgemm, dgges, dlange => f06raf, nag_wp, x02ajf,   &
                             x04caf
      Use f08xafe_mod, Only: nb, nin, nout, selctg
!     .. Implicit None Statement ..
      Implicit None
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: alph, bet, normd, norme
      Integer                          :: i, ifail, info, lda, ldb, ldc, ldd,  &
                                          lde, ldvsl, ldvsr, lwork, n, sdim
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: a(:,:), alphai(:), alphar(:),        &
                                          b(:,:), beta(:), c(:,:), d(:,:),     &
                                          e(:,:), vsl(:,:), vsr(:,:), work(:)
      Real (Kind=nag_wp)               :: dummy(1)
      Logical, Allocatable             :: bwork(:)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: max, nint
!     .. Executable Statements ..
      Write (nout,*) 'F08XAF Example Program Results'
      Write (nout,*)
      Flush (nout)
!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) n
      lda = n
      ldb = n
      ldc = n
      ldd = n
      lde = n
      ldvsl = n
      ldvsr = n
      Allocate (a(lda,n),alphai(n),alphar(n),b(ldb,n),beta(n),vsl(ldvsl,n),    &
        vsr(ldvsr,n),bwork(n),c(ldc,n),d(ldd,n),e(lde,n))

!     Use routine workspace query to get optimal workspace.
      lwork = -1
!     The NAG name equivalent of dgges is f08xaf
      Call dgges('Vectors (left)','Vectors (right)','Sort',selctg,n,a,lda,b,   &
        ldb,sdim,alphar,alphai,beta,vsl,ldvsl,vsr,ldvsr,dummy,lwork,bwork,     &
        info)

!     Make sure that there is enough workspace for block size nb.
      lwork = max(8*n+16+n*nb,nint(dummy(1)))
      Allocate (work(lwork))

!     Read in the matrices A and B
      Read (nin,*)(a(i,1:n),i=1,n)
      Read (nin,*)(b(i,1:n),i=1,n)

!     Copy A and B into D and E respectively
      d(1:n,1:n) = a(1:n,1:n)
      e(1:n,1:n) = b(1:n,1:n)

!     Print matrices A and B
!     ifail: behaviour on error exit
!            =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
      ifail = 0
      Call x04caf('General',' ',n,n,a,lda,'Matrix A',ifail)
      Write (nout,*)
      Flush (nout)

      ifail = 0
      Call x04caf('General',' ',n,n,b,ldb,'Matrix B',ifail)
      Write (nout,*)
      Flush (nout)

!     Find the generalized Schur form
!     The NAG name equivalent of dgges is f08xaf
      Call dgges('Vectors (left)','Vectors (right)','Sort',selctg,n,a,lda,b,   &
        ldb,sdim,alphar,alphai,beta,vsl,ldvsl,vsr,ldvsr,work,lwork,bwork,info)

      If (info==0 .Or. info==(n+2)) Then

!       Compute A - Q*S*Z^T from the factorization of (A,B) and store in
!       matrix D
!       The NAG name equivalent of dgemm is f06yaf
        alph = 1.0_nag_wp
        bet = 0.0_nag_wp
        Call dgemm('N','N',n,n,n,alph,vsl,ldvsl,a,lda,bet,c,ldc)
        alph = -1.0_nag_wp
        bet = 1.0_nag_wp
        Call dgemm('N','T',n,n,n,alph,c,ldc,vsr,ldvsr,bet,d,ldd)

!       Compute B - Q*T*Z^T from the factorization of (A,B) and store in
!       matrix E
        alph = 1.0_nag_wp
        bet = 0.0_nag_wp
        Call dgemm('N','N',n,n,n,alph,vsl,ldvsl,b,ldb,bet,c,ldc)
        alph = -1.0_nag_wp
        bet = 1.0_nag_wp
        Call dgemm('N','T',n,n,n,alph,c,ldc,vsr,ldvsr,bet,e,lde)

!       Find norms of matrices D and E and warn if either is too large
!       f06raf is the NAG name equivalent of the LAPACK auxiliary dlange
        normd = dlange('O',ldd,n,d,ldd,work)
        norme = dlange('O',lde,n,e,lde,work)
        If (normd>x02ajf()**0.8_nag_wp .Or. norme>x02ajf()**0.8_nag_wp) Then
          Write (nout,*)                                                       &
            'Norm of A-(Q*S*Z^T) or norm of B-(Q*T*Z^T) is much greater than 0.'
          Write (nout,*) 'Schur factorization has failed.'
        Else

!         Print solution
          Write (nout,99999)                                                   &
            'Number of eigenvalues for which SELCTG is true = ', sdim,         &
            '(dimension of deflating subspaces)'

          Write (nout,*)
!         Print generalized eigenvalues
          Write (nout,*) 'Selected generalized eigenvalues'

          Do i = 1, sdim
            If (beta(i)/=0.0_nag_wp) Then
              Write (nout,99997) i, '(', alphar(i)/beta(i), ',',               &
                alphai(i)/beta(i), ')'
            Else
              Write (nout,99996) i
            End If
          End Do
          Write (nout,*)

          If (info==(n+2)) Then
            Write (nout,99995) '***Note that rounding errors mean ',           &
              'that leading eigenvalues in the generalized',                   &
              'Schur form no longer satisfy SELCTG = .TRUE.'
            Write (nout,*)
          End If

        End If

      Else
        Write (nout,99998) 'Failure in DGGES. INFO =', info
      End If

99999 Format (1X,A,I4,/,1X,A)
99998 Format (1X,A,I4)
99997 Format (1X,I4,5X,A,F7.3,A,F7.3,A)
99996 Format (1X,I4,'Eigenvalue is infinite')
99995 Format (1X,2A,/,1X,A)
    End Program f08xafe


f08xbfe.f90

!   F08XBF Example Program Text
!   Mark 26 Release. NAG Copyright 2016.

    Module f08xbfe_mod

!     F08XBF Example Program Module:
!            Parameters and User-defined Routines

!     .. Use Statements ..
      Use nag_library, Only: nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Accessibility Statements ..
      Private
      Public                           :: selctg
!     .. Parameters ..
      Integer, Parameter, Public       :: nb = 64, nin = 5, nout = 6
    Contains
      Function selctg(ar,ai,b)

!       Logical function selctg for use with DGGESX (F08XBF)
!       Returns the value .TRUE. if the eigenvalue is real and positive

!       .. Function Return Value ..
        Logical                        :: selctg
!       .. Scalar Arguments ..
        Real (Kind=nag_wp), Intent (In) :: ai, ar, b
!       .. Executable Statements ..
        selctg = (ar>0._nag_wp .And. ai==0._nag_wp .And. b/=0._nag_wp)
        Return
      End Function selctg
    End Module f08xbfe_mod
    Program f08xbfe

!     F08XBF Example Main Program

!     .. Use Statements ..
      Use nag_library, Only: dgemm, dggesx, dlange => f06raf, f06bnf, nag_wp,  &
                             x02ajf, x04caf
      Use f08xbfe_mod, Only: nb, nin, nout, selctg
!     .. Implicit None Statement ..
      Implicit None
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: abnorm, alph, anorm, bet, bnorm,     &
                                          eps, normd, norme, tol
      Integer                          :: i, ifail, info, lda, ldb, ldc, ldd,  &
                                          lde, ldvsl, ldvsr, liwork, lwork, n, &
                                          sdim
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: a(:,:), alphai(:), alphar(:),        &
                                          b(:,:), beta(:), c(:,:), d(:,:),     &
                                          e(:,:), vsl(:,:), vsr(:,:), work(:)
      Real (Kind=nag_wp)               :: rconde(2), rcondv(2), rdum(1)
      Integer                          :: idum(1)
      Integer, Allocatable             :: iwork(:)
      Logical, Allocatable             :: bwork(:)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: max, nint
!     .. Executable Statements ..
      Write (nout,*) 'F08XBF Example Program Results'
      Write (nout,*)
      Flush (nout)
!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) n
      lda = n
      ldb = n
      ldc = n
      ldd = n
      lde = n
      ldvsl = n
      ldvsr = n
      Allocate (a(lda,n),alphai(n),alphar(n),b(ldb,n),beta(n),vsl(ldvsl,n),    &
        vsr(ldvsr,n),bwork(n),c(ldc,n),d(ldd,n),e(lde,n))

!     Use routine workspace query to get optimal workspace.
      lwork = -1
      liwork = -1
!     The NAG name equivalent of dggesx is f08xbf
      Call dggesx('Vectors (left)','Vectors (right)','Sort',selctg,            &
        'Both reciprocal condition numbers',n,a,lda,b,ldb,sdim,alphar,alphai,  &
        beta,vsl,ldvsl,vsr,ldvsr,rconde,rcondv,rdum,lwork,idum,liwork,bwork,   &
        info)

!     Make sure that there is enough workspace for block size nb.
      lwork = max(8*(n+1)+16+n*nb+n*n/2,nint(rdum(1)))
      liwork = max(n+6,idum(1))
      Allocate (work(lwork),iwork(liwork))

!     Read in the matrices A and B
      Read (nin,*)(a(i,1:n),i=1,n)
      Read (nin,*)(b(i,1:n),i=1,n)

!     Copy A and B into D and E respectively
      d(1:n,1:n) = a(1:n,1:n)
      e(1:n,1:n) = b(1:n,1:n)

!     Print matrices A and B
!     ifail: behaviour on error exit
!            =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
      ifail = 0
      Call x04caf('General',' ',n,n,a,lda,'Matrix A',ifail)
      Write (nout,*)
      Flush (nout)

      ifail = 0
      Call x04caf('General',' ',n,n,b,ldb,'Matrix B',ifail)
      Write (nout,*)
      Flush (nout)

!     Find the Frobenius norms of A and B
!     The NAG name equivalent of the LAPACK auxiliary dlange is f06raf
      anorm = dlange('Frobenius',n,n,a,lda,work)
      bnorm = dlange('Frobenius',n,n,b,ldb,work)

!     Find the generalized Schur form
!     The NAG name equivalent of dggesx is f08xbf
      Call dggesx('Vectors (left)','Vectors (right)','Sort',selctg,            &
        'Both reciprocal condition numbers',n,a,lda,b,ldb,sdim,alphar,alphai,  &
        beta,vsl,ldvsl,vsr,ldvsr,rconde,rcondv,work,lwork,iwork,liwork,bwork,  &
        info)

      If (info==0 .Or. info==(n+2)) Then

!       Compute A - Q*S*Z^T from the factorization of (A,B) and store in
!       matrix D
!       The NAG name equivalent of dgemm is f06yaf
        alph = 1.0_nag_wp
        bet = 0.0_nag_wp
        Call dgemm('N','N',n,n,n,alph,vsl,ldvsl,a,lda,bet,c,ldc)
        alph = -1.0_nag_wp
        bet = 1.0_nag_wp
        Call dgemm('N','T',n,n,n,alph,c,ldc,vsr,ldvsr,bet,d,ldd)

!       Compute B - Q*T*Z^T from the factorization of (A,B) and store in
!       matrix E
        alph = 1.0_nag_wp
        bet = 0.0_nag_wp
        Call dgemm('N','N',n,n,n,alph,vsl,ldvsl,b,ldb,bet,c,ldc)
        alph = -1.0_nag_wp
        bet = 1.0_nag_wp
        Call dgemm('N','T',n,n,n,alph,c,ldc,vsr,ldvsr,bet,e,lde)

!       Find norms of matrices D and E and warn if either is too large
        normd = dlange('O',ldd,n,d,ldd,work)
        norme = dlange('O',lde,n,e,lde,work)
        If (normd>x02ajf()**0.8_nag_wp .Or. norme>x02ajf()**0.8_nag_wp) Then
          Write (nout,*)                                                       &
            'Norm of A-(Q*S*Z^T) or norm of B-(Q*T*Z^T) is much greater than 0.'
          Write (nout,*) 'Schur factorization has failed.'
        Else

!         Print solution
          Write (nout,99999)                                                   &
            'Number of eigenvalues for which SELCTG is true = ', sdim,         &
            '(dimension of deflating subspaces)'

          Write (nout,*)
!         Print generalized eigenvalues
          Write (nout,*) 'Selected generalized eigenvalues'

          Do i = 1, sdim
            If (beta(i)/=0.0_nag_wp) Then
              Write (nout,99998) i, '(', alphar(i)/beta(i), ',',               &
                alphai(i)/beta(i), ')'
            Else
              Write (nout,99997) i
            End If
          End Do

          If (info==(n+2)) Then
            Write (nout,99996) '***Note that rounding errors mean ',           &
              'that leading eigenvalues in the generalized',                   &
              'Schur form no longer satisfy SELCTG = .TRUE.'
            Write (nout,*)
          End If
          Flush (nout)

!         Print out the reciprocal condition numbers
          Write (nout,*)
          Write (nout,99995)                                                   &
            'Reciprocals of left and right projection norms onto',             &
            'the deflating subspaces for the selected eigenvalues',            &
            'RCONDE(1) = ', rconde(1), ', RCONDE(2) = ', rconde(2)
          Write (nout,*)
          Write (nout,99995)                                                   &
            'Reciprocal condition numbers for the left and right',             &
            'deflating subspaces', 'RCONDV(1) = ', rcondv(1),                  &
            ', RCONDV(2) = ', rcondv(2)
          Flush (nout)

!         Compute the machine precision and sqrt(anorm**2+bnorm**2)
          eps = x02ajf()
          abnorm = f06bnf(anorm,bnorm)
          tol = eps*abnorm

!         Print out the approximate asymptotic error bound on the
!         average absolute error of the selected eigenvalues given by
!         eps*norm((A, B))/PL,   where PL = RCONDE(1)
          Write (nout,*)
          Write (nout,99994)                                                   &
            'Approximate asymptotic error bound for selected ',                &
            'eigenvalues    = ', tol/rconde(1)

!         Print out an approximate asymptotic bound on the maximum
!         angular error in the computed deflating subspaces given by
!         eps*norm((A, B))/DIF(2),   where DIF(2) = RCONDV(2)
          Write (nout,99994)                                                   &
            'Approximate asymptotic error bound for the deflating ',           &
            'subspaces = ', tol/rcondv(2)

        End If

      Else
        Write (nout,99999) 'Failure in DGGESX. INFO =', info
      End If

99999 Format (1X,A,I4,/,1X,A)
99998 Format (1X,I4,5X,A,F7.3,A,F7.3,A)
99997 Format (1X,I4,'Eigenvalue is infinite')
99996 Format (1X,2A,/,1X,A)
99995 Format (1X,A,/,1X,A,/,1X,2(A,1P,E8.1))
99994 Format (1X,2A,1P,E8.1)
    End Program f08xbfe


f08xcfe.f90

!   F08XCF Example Program Text
!   Mark 26 Release. NAG Copyright 2016.

    Module f08xcfe_mod

!     F08XCF Example Program Module:
!            Parameters and User-defined Routines

!     .. Use Statements ..
      Use nag_library, Only: nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Accessibility Statements ..
      Private
      Public                           :: selctg
!     .. Parameters ..
      Integer, Parameter, Public       :: nb = 64, nin = 5, nout = 6
    Contains
      Function selctg(ar,ai,b)

!       Logical function selctg for use with DGGES3 (F08XCF)
!       Returns the value .TRUE. if the eigenvalue is real and positive

!       .. Function Return Value ..
        Logical                        :: selctg
!       .. Scalar Arguments ..
        Real (Kind=nag_wp), Intent (In) :: ai, ar, b
!       .. Executable Statements ..
        selctg = (ar>0._nag_wp .And. ai==0._nag_wp .And. b/=0._nag_wp)
        Return
      End Function selctg
    End Module f08xcfe_mod
    Program f08xcfe

!     F08XCF Example Main Program

!     .. Use Statements ..
      Use nag_library, Only: dgemm, dgges3, dlange => f06raf, nag_wp, x02ajf,  &
                             x04caf
      Use f08xcfe_mod, Only: nb, nin, nout, selctg
!     .. Implicit None Statement ..
      Implicit None
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: alph, bet, normd, norme
      Integer                          :: i, ifail, info, lda, ldb, ldc, ldd,  &
                                          lde, ldvsl, ldvsr, lwork, n, sdim
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: a(:,:), alphai(:), alphar(:),        &
                                          b(:,:), beta(:), c(:,:), d(:,:),     &
                                          e(:,:), vsl(:,:), vsr(:,:), work(:)
      Real (Kind=nag_wp)               :: dummy(1)
      Logical, Allocatable             :: bwork(:)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: max, nint
!     .. Executable Statements ..
      Write (nout,*) 'F08XCF Example Program Results'
      Write (nout,*)
      Flush (nout)
!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) n
      lda = n
      ldb = n
      ldc = n
      ldd = n
      lde = n
      ldvsl = n
      ldvsr = n
      Allocate (a(lda,n),alphai(n),alphar(n),b(ldb,n),beta(n),vsl(ldvsl,n),    &
        vsr(ldvsr,n),bwork(n),c(ldc,n),d(ldd,n),e(lde,n))

!     Use routine workspace query to get optimal workspace.
      lwork = -1
!     The NAG name equivalent of dgges3 is f08xcf
      Call dgges3('Vectors (left)','Vectors (right)','Sort',selctg,n,a,lda,b,  &
        ldb,sdim,alphar,alphai,beta,vsl,ldvsl,vsr,ldvsr,dummy,lwork,bwork,     &
        info)

!     Make sure that there is enough workspace for block size nb.
      lwork = max(8*n+16+n*nb,nint(dummy(1)))
      Allocate (work(lwork))

!     Read in the matrices A and B
      Read (nin,*)(a(i,1:n),i=1,n)
      Read (nin,*)(b(i,1:n),i=1,n)

!     Copy A and B into D and E respectively
      d(1:n,1:n) = a(1:n,1:n)
      e(1:n,1:n) = b(1:n,1:n)

!     Print matrices A and B
!     ifail: behaviour on error exit
!            =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
      ifail = 0
      Call x04caf('General',' ',n,n,a,lda,'Matrix A',ifail)
      Write (nout,*)
      Flush (nout)

      ifail = 0
      Call x04caf('General',' ',n,n,b,ldb,'Matrix B',ifail)
      Write (nout,*)
      Flush (nout)

!     Find the generalized Schur form
!     The NAG name equivalent of dgges3 is f08xcf
      Call dgges3('Vectors (left)','Vectors (right)','Sort',selctg,n,a,lda,b,  &
        ldb,sdim,alphar,alphai,beta,vsl,ldvsl,vsr,ldvsr,work,lwork,bwork,info)

      If (info==0 .Or. info==(n+2)) Then

!       Compute A - Q*S*Z^T from the factorization of (A,B) and store in
!       matrix D
!       The NAG name equivalent of dgemm is f06yaf
        alph = 1.0_nag_wp
        bet = 0.0_nag_wp
        Call dgemm('N','N',n,n,n,alph,vsl,ldvsl,a,lda,bet,c,ldc)
        alph = -1.0_nag_wp
        bet = 1.0_nag_wp
        Call dgemm('N','T',n,n,n,alph,c,ldc,vsr,ldvsr,bet,d,ldd)

!       Compute B - Q*T*Z^T from the factorization of (A,B) and store in
!       matrix E
        alph = 1.0_nag_wp
        bet = 0.0_nag_wp
        Call dgemm('N','N',n,n,n,alph,vsl,ldvsl,b,ldb,bet,c,ldc)
        alph = -1.0_nag_wp
        bet = 1.0_nag_wp
        Call dgemm('N','T',n,n,n,alph,c,ldc,vsr,ldvsr,bet,e,lde)

!       Find norms of matrices D and E and warn if either is too large
!       f06raf is the NAG name equivalent of the LAPACK auxiliary dlange
        normd = dlange('O',ldd,n,d,ldd,work)
        norme = dlange('O',lde,n,e,lde,work)
        If (normd>x02ajf()**0.8_nag_wp .Or. norme>x02ajf()**0.8_nag_wp) Then
          Write (nout,*)                                                       &
            'Norm of A-(Q*S*Z^T) or norm of B-(Q*T*Z^T) is much greater than 0.'
          Write (nout,*) 'Schur factorization has failed.'
        Else

!         Print solution
          Write (nout,99999)                                                   &
            'Number of eigenvalues for which SELCTG is true = ', sdim,         &
            '(dimension of deflating subspaces)'

          Write (nout,*)
!         Print generalized eigenvalues
          Write (nout,*) 'Selected generalized eigenvalues'

          Do i = 1, sdim
            If (beta(i)/=0.0_nag_wp) Then
              Write (nout,99997) i, '(', alphar(i)/beta(i), ',',               &
                alphai(i)/beta(i), ')'
            Else
              Write (nout,99996) i
            End If
          End Do
          Write (nout,*)

          If (info==(n+2)) Then
            Write (nout,99995) '***Note that rounding errors mean ',           &
              'that leading eigenvalues in the generalized',                   &
              'Schur form no longer satisfy SELCTG = .TRUE.'
            Write (nout,*)
          End If

        End If

      Else
        Write (nout,99998) 'Failure in DGGES3. INFO =', info
      End If

99999 Format (1X,A,I4,/,1X,A)
99998 Format (1X,A,I4)
99997 Format (1X,I4,5X,A,F7.3,A,F7.3,A)
99996 Format (1X,I4,'Eigenvalue is infinite')
99995 Format (1X,2A,/,1X,A)
    End Program f08xcfe


f08xefe.f90

    Program f08xefe

!     F08XEF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: dgeqrf, dggbal, dgghd3, dhgeqz, dormqr, nag_wp,   &
                             x04caf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Integer                          :: i, ifail, ihi, ilo, info, irows,     &
                                          jwork, lda, ldb, ldq, ldz, lwork, n
      Character (1)                    :: compq, compz, job
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: a(:,:), alphai(:), alphar(:),        &
                                          b(:,:), beta(:), lscale(:), q(:,:),  &
                                          rscale(:), tau(:), work(:), z(:,:)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: nint
!     .. Executable Statements ..
      Write (nout,*) 'F08XEF Example Program Results'
      Flush (nout)

!     Skip heading in data file

      Read (nin,*)
      Read (nin,*) n
      ldq = 1
      ldz = 1
      lda = n
      ldb = n
      lwork = 6*n
      Allocate (alphai(n),alphar(n),beta(n),a(lda,n),lscale(n),q(ldq,ldq),     &
        rscale(n),b(ldb,n),tau(n),work(lwork),z(ldz,ldz))

!     READ matrix A from data file
      Read (nin,*)(a(i,1:n),i=1,n)

!     READ matrix B from data file
      Read (nin,*)(b(i,1:n),i=1,n)

!     Balance matrix pair (A,B)
      job = 'B'

!     The NAG name equivalent of dggbal is f08whf
      Call dggbal(job,n,a,lda,b,ldb,ilo,ihi,lscale,rscale,work,info)

!     Matrix A after balancing

!     ifail: behaviour on error exit
!             =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
      ifail = 0
      Call x04caf('General',' ',n,n,a,lda,'Matrix A after balancing',ifail)

      Write (nout,*)
      Flush (nout)

!     Matrix B after balancing

      ifail = 0
      Call x04caf('General',' ',n,n,b,ldb,'Matrix B after balancing',ifail)

      Write (nout,*)
      Flush (nout)

!     Reduce B to triangular form using QR
      irows = ihi + 1 - ilo

!     The NAG name equivalent of dgeqrf is f08aef
      Call dgeqrf(irows,irows,b(ilo,ilo),ldb,tau,work,lwork,info)

!     Apply the orthogonal transformation to matrix A
!     The NAG name equivalent of dormqr is f08agf
      Call dormqr('L','T',irows,irows,irows,b(ilo,ilo),ldb,tau,a(ilo,ilo),lda, &
        work,lwork,info)

!     Compute the generalized Hessenberg form of (A,B) -> (H,T)
      compq = 'N'
      compz = 'N'

!     The NAG name equivalent of dgghd3 is f08wff
      Call dgghd3(compq,compz,irows,1,irows,a(ilo,ilo),lda,b(ilo,ilo),ldb,q,   &
        ldq,z,ldz,work,lwork,info)

!     Matrix A (H) in generalized Hessenberg form.

      ifail = 0
      Call x04caf('General',' ',n,n,a,lda,'Matrix A in Hessenberg form',ifail)

      Write (nout,*)
      Flush (nout)

!     Matrix B (T) in generalized Hessenberg form.

      ifail = 0
      Call x04caf('General',' ',n,n,b,ldb,'Matrix B is triangular',ifail)

!     Routine DHGEQZ
!     Workspace query: jwork = -1

      jwork = -1
      job = 'E'

!     The NAG name equivalent of dhgeqz is f08xef
      Call dhgeqz(job,compq,compz,n,ilo,ihi,a,lda,b,ldb,alphar,alphai,beta,q,  &
        ldq,z,ldz,work,jwork,info)

      Write (nout,*)
      Write (nout,99999) nint(work(1))
      Write (nout,99998) lwork
      Write (nout,*)

!     Compute the generalized Schur form
!     if the workspace lwork is adequate

      If (nint(work(1))<=lwork) Then

!       The NAG name equivalent of dhgeqz is f08xef
        Call dhgeqz(job,compq,compz,n,ilo,ihi,a,lda,b,ldb,alphar,alphai,beta,  &
          q,ldq,z,ldz,work,lwork,info)

!       Print the generalized eigenvalues

        Write (nout,99997)

        Do i = 1, n
          If (beta(i)/=0.0E0_nag_wp) Then
            Write (nout,99996) i, '(', alphar(i)/beta(i), ',',                 &
              alphai(i)/beta(i), ')'
          Else
            Write (nout,99994) i
          End If
        End Do
      Else
        Write (nout,99995)
      End If

99999 Format (1X,'Minimal required LWORK = ',I6)
99998 Format (1X,'Actual value of  LWORK = ',I6)
99997 Format (1X,'Generalized eigenvalues')
99996 Format (1X,I4,5X,A,F7.3,A,F7.3,A)
99995 Format (1X,'Insufficient workspace allocated for call to F08XEF/DHGEQZ')
99994 Format (1X,I4,'Eigenvalue is infinite')
    End Program f08xefe


f08xnfe.f90

    Program f08xnfe

!     F08XNF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: f08xnz, m01daf, m01edf, nag_wp, x02ajf, x04dbf,   &
                             zgemm, zgges, zlange => f06uaf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nb = 64, nin = 5, nout = 6
      Logical, Parameter               :: chkfac = .False., prmat = .False.
!     .. Local Scalars ..
      Complex (Kind=nag_wp)            :: alph, bet
      Real (Kind=nag_wp)               :: normd, norme
      Integer                          :: i, ifail, info, lda, ldb, ldc, ldd,  &
                                          lde, ldvsl, ldvsr, lwork, n, sdim
      Logical                          :: factor
!     .. Local Arrays ..
      Complex (Kind=nag_wp), Allocatable :: a(:,:), alpha(:), b(:,:), beta(:), &
                                          c(:,:), d(:,:), e(:,:), vsl(:,:),    &
                                          vsr(:,:), work(:)
      Complex (Kind=nag_wp)            :: wdum(1)
      Real (Kind=nag_wp), Allocatable  :: rwork(:)
      Integer, Allocatable             :: irank(:)
      Logical, Allocatable             :: bwork(:)
      Character (1)                    :: clabs(1), rlabs(1)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: abs, all, cmplx, max, nint, real
!     .. Executable Statements ..
      Write (nout,*) 'F08XNF Example Program Results'
      Write (nout,*)
      Flush (nout)
!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) n
      lda = n
      ldb = n
      ldc = n
      ldd = n
      lde = n
      ldvsl = n
      ldvsr = n
      Allocate (a(lda,n),alpha(n),b(ldb,n),beta(n),c(ldc,n),d(ldd,n),e(lde,n), &
        vsl(ldvsl,n),vsr(ldvsr,n),rwork(8*n),bwork(n),irank(n))

!     Use routine workspace query to get optimal workspace.
      lwork = -1
!     The NAG name equivalent of zgges is f08xnf
      Call zgges('Vectors (left)','Vectors (right)','No sort',f08xnz,n,a,lda,  &
        b,ldb,sdim,alpha,beta,vsl,ldvsl,vsr,ldvsr,wdum,lwork,rwork,bwork,info)

!     Make sure that there is enough workspace for block size nb.
      lwork = max((nb+1)*n,nint(real(wdum(1))))
      Allocate (work(lwork))

!     Read in the matrices A and B
      Read (nin,*)(a(i,1:n),i=1,n)
      Read (nin,*)(b(i,1:n),i=1,n)

!     Copy A and B into D and E respectively
      d(1:n,1:n) = a(1:n,1:n)
      e(1:n,1:n) = b(1:n,1:n)

      If (prmat) Then
!       Print matrices A and B
!       ifail: behaviour on error exit
!              =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
        ifail = 0
        Call x04dbf('General',' ',n,n,a,lda,'Bracketed','F8.4','Matrix A',     &
          'Integer',rlabs,'Integer',clabs,80,0,ifail)
        Write (nout,*)
        Flush (nout)

        ifail = 0
        Call x04dbf('General',' ',n,n,b,ldb,'Bracketed','F8.4','Matrix B',     &
          'Integer',rlabs,'Integer',clabs,80,0,ifail)
        Write (nout,*)
        Flush (nout)
      End If

      factor = .True.
!     Find the generalized Schur form
!     The NAG name equivalent of zgges is f08xnf
      Call zgges('Vectors (left)','Vectors (right)','No sort',f08xnz,n,a,lda,  &
        b,ldb,sdim,alpha,beta,vsl,ldvsl,vsr,ldvsr,work,lwork,rwork,bwork,info)

      If (info>0) Then
        Write (nout,99999) 'Failure in ZGGES. INFO =', info
        factor = .False.
      Else If (chkfac) Then

!       Compute A - Q*S*Z^H from the factorization of (A,B) and store in
!       matrix D
!       The NAG name equivalent of zgemm is f06zaf
        alph = cmplx(1,kind=nag_wp)
        bet = cmplx(0,kind=nag_wp)
        Call zgemm('N','N',n,n,n,alph,vsl,ldvsl,a,lda,bet,c,ldc)
        alph = cmplx(-1,kind=nag_wp)
        bet = cmplx(1,kind=nag_wp)
        Call zgemm('N','C',n,n,n,alph,c,ldc,vsr,ldvsr,bet,d,ldd)

!       Compute B - Q*T*Z^H from the factorization of (A,B) and store in
!       matrix E
        alph = cmplx(1,kind=nag_wp)
        bet = cmplx(0,kind=nag_wp)
        Call zgemm('N','N',n,n,n,alph,vsl,ldvsl,b,ldb,bet,c,ldc)
        alph = cmplx(-1,kind=nag_wp)
        bet = cmplx(1,kind=nag_wp)
        Call zgemm('N','C',n,n,n,alph,c,ldc,vsr,ldvsr,bet,e,lde)

!       Find norms of matrices D and E and warn if either is too large
!       f06uaf is the NAG name equivalent of the LAPACK auxiliary zlange
        normd = zlange('O',ldd,n,d,ldd,rwork)
        norme = zlange('O',lde,n,e,lde,rwork)
        If (normd>x02ajf()**0.75_nag_wp) Then
          Write (nout,*) 'Norm of A-(Q*S*Z^H) is much greater than 0.'
          factor = .False.
        End If
        If (norme>x02ajf()**0.75_nag_wp) Then
          Write (nout,*) 'Norm of B-(Q*T*Z^H) is much greater than 0.'
          factor = .False.
        End If
      End If
      If (factor) Then
!       Sort and print generalized eigenvalues if none are infinite
        If (all(real(beta(1:n))>0.0_nag_wp)) Then
          work(1:n) = alpha(1:n)/beta(1:n)
          rwork(1:n) = abs(work(1:n))

!         Rank eigenvalues
          ifail = 0
          Call m01daf(rwork,1,n,'Descending',irank,ifail)

!         Sort eigenvalues in work(1:n)
          Call m01edf(work,1,n,irank,ifail)
          Write (nout,*) 'Generalized Eigenvalues'
          Do i = 1, n
            Write (nout,99998) i, work(i)
          End Do
        End If
      Else
        Write (nout,*) 'Schur factorization has failed.'
      End If

99999 Format (1X,A,I4)
99998 Format (1X,I2,3X,'(',F6.2,',',F6.2,')')
    End Program f08xnfe


f08xpfe.f90

!   F08XPF Example Program Text
!   Mark 26 Release. NAG Copyright 2016.

    Module f08xpfe_mod

!     F08XPF Example Program Module:
!            Parameters and User-defined Routines

!     .. Use Statements ..
      Use nag_library, Only: nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Accessibility Statements ..
      Private
      Public                           :: selctg
!     .. Parameters ..
      Integer, Parameter, Public       :: nb = 64, nin = 5, nout = 6
      Logical, Parameter, Public       :: chkfac = .False., prcond = .False.,  &
                                          prmat = .False.
    Contains
      Function selctg(a,b)

!       Logical function selctg for use with ZGGESX (F08XPF)
!       Returns the value .TRUE. if the absolute value of the eigenvalue
!       a/b < 6.0

!       .. Function Return Value ..
        Logical                        :: selctg
!       .. Scalar Arguments ..
        Complex (Kind=nag_wp), Intent (In) :: a, b
!       .. Intrinsic Procedures ..
        Intrinsic                      :: abs
!       .. Executable Statements ..
        selctg = (abs(a)<6.0_nag_wp*abs(b))
        Return
      End Function selctg
    End Module f08xpfe_mod
    Program f08xpfe

!     F08XPF Example Main Program

!     .. Use Statements ..
      Use nag_library, Only: f06bnf, m01daf, m01edf, nag_wp, x02ajf, x04dbf,   &
                             zgemm, zggesx, zlange => f06uaf
      Use f08xpfe_mod, Only: chkfac, nb, nin, nout, prcond, prmat, selctg
!     .. Implicit None Statement ..
      Implicit None
!     .. Local Scalars ..
      Complex (Kind=nag_wp)            :: alph, bet
      Real (Kind=nag_wp)               :: abnorm, anorm, bnorm, eps, normd,    &
                                          norme, tol
      Integer                          :: i, ifail, info, lda, ldb, ldc, ldd,  &
                                          lde, ldvsl, ldvsr, liwork, lwork, n, &
                                          sdim
      Logical                          :: factor
!     .. Local Arrays ..
      Complex (Kind=nag_wp), Allocatable :: a(:,:), alpha(:), b(:,:), beta(:), &
                                          c(:,:), d(:,:), e(:,:), vsl(:,:),    &
                                          vsr(:,:), work(:)
      Complex (Kind=nag_wp)            :: dummy(1)
      Real (Kind=nag_wp)               :: rconde(2), rcondv(2)
      Real (Kind=nag_wp), Allocatable  :: rwork(:)
      Integer                          :: idum(1)
      Integer, Allocatable             :: iwork(:)
      Logical, Allocatable             :: bwork(:)
      Character (1)                    :: clabs(1), rlabs(1)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: abs, cmplx, max, nint, real
!     .. Executable Statements ..
      Write (nout,*) 'F08XPF Example Program Results'
      Write (nout,*)
      Flush (nout)
!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) n
      lda = n
      ldb = n
      ldc = n
      ldd = n
      lde = n
      ldvsl = n
      ldvsr = n
      Allocate (a(lda,n),alpha(n),b(ldb,n),beta(n),c(ldc,n),d(ldd,n),e(lde,n), &
        vsl(ldvsl,n),vsr(ldvsr,n),rwork(8*n),bwork(n))

!     Use routine workspace query to get optimal workspace.
      lwork = -1
      liwork = -1
!     The NAG name equivalent of zggesx is f08xpf
      Call zggesx('Vectors (left)','Vectors (right)','Sort',selctg,            &
        'Both reciprocal condition numbers',n,a,lda,b,ldb,sdim,alpha,beta,vsl, &
        ldvsl,vsr,ldvsr,rconde,rcondv,dummy,lwork,rwork,idum,liwork,bwork,     &
        info)

!     Make sure that there is enough workspace for block size nb.
      lwork = max(n*nb+n*n/2,nint(real(dummy(1))))
      liwork = max(n+2,idum(1))
      Allocate (work(lwork),iwork(liwork))

!     Read in the matrices A and B
      Read (nin,*)(a(i,1:n),i=1,n)
      Read (nin,*)(b(i,1:n),i=1,n)

      If (chkfac) Then
!       Copy A and B into D and E respectively
        d(1:n,1:n) = a(1:n,1:n)
        e(1:n,1:n) = b(1:n,1:n)
      End If

!     Find the Frobenius norms of A and B
!     The NAG name equivalent of the LAPACK auxiliary zlange is f06uaf
      anorm = zlange('Frobenius',n,n,a,lda,rwork)
      bnorm = zlange('Frobenius',n,n,b,ldb,rwork)

      If (prmat) Then
!       Print matrices A and B
!       ifail: behaviour on error exit
!              =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
        ifail = 0
        Call x04dbf('General',' ',n,n,a,lda,'Bracketed','F8.4','Matrix A',     &
          'Integer',rlabs,'Integer',clabs,80,0,ifail)
        Write (nout,*)
        Flush (nout)

        ifail = 0
        Call x04dbf('General',' ',n,n,b,ldb,'Bracketed','F8.4','Matrix B',     &
          'Integer',rlabs,'Integer',clabs,80,0,ifail)
        Write (nout,*)
        Flush (nout)
      End If

      factor = .True.
!     Find the generalized Schur form
!     The NAG name equivalent of zggesx is f08xpf
      Call zggesx('Vectors (left)','Vectors (right)','Sort',selctg,            &
        'Both reciprocal condition numbers',n,a,lda,b,ldb,sdim,alpha,beta,vsl, &
        ldvsl,vsr,ldvsr,rconde,rcondv,work,lwork,rwork,iwork,liwork,bwork,     &
        info)

      If (info/=0 .And. info/=(n+2)) Then
        Write (nout,99999) 'Failure in ZGGESX. INFO =', info
        factor = .False.
      Else If (chkfac) Then
!       Compute A - Q*S*Z^H from the factorization of (A,B) and store in
!       matrix D
!       The NAG name equivalent of zgemm is f06zaf
        alph = cmplx(1,kind=nag_wp)
        bet = cmplx(0,kind=nag_wp)
        Call zgemm('N','N',n,n,n,alph,vsl,ldvsl,a,lda,bet,c,ldc)
        alph = cmplx(-1,kind=nag_wp)
        bet = cmplx(1,kind=nag_wp)
        Call zgemm('N','C',n,n,n,alph,c,ldc,vsr,ldvsr,bet,d,ldd)

!       Compute B - Q*T*Z^H from the factorization of (A,B) and store in
!       matrix E
        alph = cmplx(1,kind=nag_wp)
        bet = cmplx(0,kind=nag_wp)
        Call zgemm('N','N',n,n,n,alph,vsl,ldvsl,b,ldb,bet,c,ldc)
        alph = cmplx(-1,kind=nag_wp)
        bet = cmplx(1,kind=nag_wp)
        Call zgemm('N','C',n,n,n,alph,c,ldc,vsr,ldvsr,bet,e,lde)

!       Find norms of matrices D and E and warn if either is too large
        normd = zlange('O',ldd,n,d,ldd,rwork)
        If (normd>x02ajf()**0.75_nag_wp) Then
          Write (nout,*) 'Norm of A-(Q*S*Z^T) is much greater than 0.'
          factor = .False.
          Write (nout,*) 'Schur factorization has failed.'
        End If
        norme = zlange('O',lde,n,e,lde,rwork)
        If (norme>x02ajf()**0.75_nag_wp) Then
          Write (nout,*) 'Norm of B-(Q*T*Z^T) is much greater than 0.'
          factor = .False.
        End If
      End If

      If (factor) Then
!       Print eigenvalue details
        Write (nout,99999) 'Number of eigenvalues for which SELCTG is true = ' &
          , sdim, '(dimension of deflating subspaces)'

        Write (nout,*)
!       Print selected (finite) generalized eigenvalues
        Write (nout,*) 'Selected generalized eigenvalues'

!       Store absolute values of eigenvalues for ranking
        work(1:n) = alpha(1:n)/beta(1:n)
        rwork(1:n) = abs(work(1:n))

!       Rank eigenvalues
        ifail = 0
        Call m01daf(rwork,1,sdim,'Descending',iwork,ifail)

!       Sort eigenvalues in work(1:n)
        Call m01edf(work,1,sdim,iwork,ifail)
        Do i = 1, sdim
          Write (nout,99998) i, work(i)
        End Do

        If (info==(n+2)) Then
          Write (nout,99997) '*** Note that rounding errors mean ',            &
            'that leading eigenvalues in the',                                 &
            'generalized Schur form no longer satisfy SELCTG = .TRUE.'
          Write (nout,*)
        End If
        Flush (nout)

        If (prcond) Then
!         Compute the machine precision and sqrt(anorm**2+bnorm**2)
          eps = x02ajf()
          abnorm = f06bnf(anorm,bnorm)
          tol = eps*abnorm

!         Print out the reciprocal condition numbers and error bound for
!         selected eigenvalues
          Write (nout,*)
          Write (nout,99996)                                                   &
            'Reciprocal condition numbers for the average of the',             &
            'selected eigenvalues and their asymptotic error bound',           &
            'rcond-left = ', rconde(1), ', rcond-right = ', rconde(2),         &
            ', error = ', tol/rconde(1)

          Write (nout,*)
          Write (nout,99996)                                                   &
            'Reciprocal condition numbers for the deflating subspaces',        &
            'and their approximate asymptotic error bound', 'rcond-left = ',   &
            rcondv(1), ', rcond-right = ', rcondv(2), ', error = ',            &
            tol/rcondv(2)
        End If

      Else
        Write (nout,*) 'Schur factorization has failed.'
      End If

99999 Format (1X,A,I4,/,1X,A)
99998 Format (1X,I2,1X,'(',F6.2,',',F6.2,')')
99997 Format (1X,2A,/,1X,A)
99996 Format (1X,A,/,1X,A,/,1X,3(A,1P,E8.1))
    End Program f08xpfe


f08xqfe.f90

    Program f08xqfe

!     F08XQF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: f08xnz, nag_wp, x02ajf, x04dbf, zgemm, zgges3,    &
                             zlange => f06uaf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nb = 64, nin = 5, nout = 6
!     .. Local Scalars ..
      Complex (Kind=nag_wp)            :: alph, bet
      Real (Kind=nag_wp)               :: normd, norme
      Integer                          :: i, ifail, info, lda, ldb, ldc, ldd,  &
                                          lde, ldvsl, ldvsr, lwork, n, sdim
!     .. Local Arrays ..
      Complex (Kind=nag_wp), Allocatable :: a(:,:), alpha(:), b(:,:), beta(:), &
                                          c(:,:), d(:,:), e(:,:), vsl(:,:),    &
                                          vsr(:,:), work(:)
      Complex (Kind=nag_wp)            :: wdum(1)
      Real (Kind=nag_wp), Allocatable  :: rwork(:)
      Logical, Allocatable             :: bwork(:)
      Character (1)                    :: clabs(1), rlabs(1)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: cmplx, max, nint, real
!     .. Executable Statements ..
      Write (nout,*) 'F08XQF Example Program Results'
      Write (nout,*)
      Flush (nout)
!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) n
      lda = n
      ldb = n
      ldc = n
      ldd = n
      lde = n
      ldvsl = n
      ldvsr = n
      Allocate (a(lda,n),alpha(n),b(ldb,n),beta(n),c(ldc,n),d(ldd,n),e(lde,n), &
        vsl(ldvsl,n),vsr(ldvsr,n),rwork(8*n),bwork(n))

!     Use routine workspace query to get optimal workspace.
      lwork = -1
!     The NAG name equivalent of zgges3 is f08xqf
      Call zgges3('Vectors (left)','Vectors (right)','No sort',f08xnz,n,a,lda, &
        b,ldb,sdim,alpha,beta,vsl,ldvsl,vsr,ldvsr,wdum,lwork,rwork,bwork,info)

!     Make sure that there is enough workspace for block size nb.
      lwork = max((nb+1)*n,nint(real(wdum(1))))
      Allocate (work(lwork))

!     Read in the matrices A and B
      Read (nin,*)(a(i,1:n),i=1,n)
      Read (nin,*)(b(i,1:n),i=1,n)

!     Copy A and B into D and E respectively
      d(1:n,1:n) = a(1:n,1:n)
      e(1:n,1:n) = b(1:n,1:n)

!     Print matrices A and B
!     ifail: behaviour on error exit
!            =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
      ifail = 0
      Call x04dbf('General',' ',n,n,a,lda,'Bracketed','F8.4','Matrix A',       &
        'Integer',rlabs,'Integer',clabs,80,0,ifail)
      Write (nout,*)
      Flush (nout)

      ifail = 0
      Call x04dbf('General',' ',n,n,b,ldb,'Bracketed','F8.4','Matrix B',       &
        'Integer',rlabs,'Integer',clabs,80,0,ifail)
      Write (nout,*)
      Flush (nout)

!     Find the generalized Schur form
!     The NAG name equivalent of zgges3 is f08xqf
      Call zgges3('Vectors (left)','Vectors (right)','No sort',f08xnz,n,a,lda, &
        b,ldb,sdim,alpha,beta,vsl,ldvsl,vsr,ldvsr,work,lwork,rwork,bwork,info)

      If (info>0) Then
        Write (nout,99999) 'Failure in ZGGES3. INFO =', info
      Else

!       Compute A - Q*S*Z^H from the factorization of (A,B) and store in
!       matrix D
!       The NAG name equivalent of zgemm is f06zaf
        alph = cmplx(1,kind=nag_wp)
        bet = cmplx(0,kind=nag_wp)
        Call zgemm('N','N',n,n,n,alph,vsl,ldvsl,a,lda,bet,c,ldc)
        alph = cmplx(-1,kind=nag_wp)
        bet = cmplx(1,kind=nag_wp)
        Call zgemm('N','C',n,n,n,alph,c,ldc,vsr,ldvsr,bet,d,ldd)

!       Compute B - Q*T*Z^H from the factorization of (A,B) and store in
!       matrix E
        alph = cmplx(1,kind=nag_wp)
        bet = cmplx(0,kind=nag_wp)
        Call zgemm('N','N',n,n,n,alph,vsl,ldvsl,b,ldb,bet,c,ldc)
        alph = cmplx(-1,kind=nag_wp)
        bet = cmplx(1,kind=nag_wp)
        Call zgemm('N','C',n,n,n,alph,c,ldc,vsr,ldvsr,bet,e,lde)

!       Find norms of matrices D and E and warn if either is too large
!       f06uaf is the NAG name equivalent of the LAPACK auxiliary zlange
        normd = zlange('O',ldd,n,d,ldd,rwork)
        norme = zlange('O',lde,n,e,lde,rwork)
        If (normd>x02ajf()**0.75_nag_wp .Or. norme>x02ajf()**0.75_nag_wp) Then
          Write (nout,*)                                                       &
            'Norm of A-(Q*S*Z^H) or norm of B-(Q*T*Z^H) is much greater than 0.'
          Write (nout,*) 'Schur factorization has failed.'
        Else
!         Print generalized eigenvalues
          Write (nout,*) 'Generalized Eigenvalues'

          Do i = 1, n
            If (beta(i)/=0.0_nag_wp) Then
              Write (nout,99998) i, alpha(i)/beta(i)
            Else
              Write (nout,99997) i
            End If
          End Do
        End If
      End If

99999 Format (1X,A,I4)
99998 Format (1X,I2,1X,'(',1P,E11.4,',',E11.4,')')
99997 Format (1X,I4,'Eigenvalue is infinite')
    End Program f08xqfe


f08xsfe.f90

    Program f08xsfe

!     F08XSF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: m01daf, m01edf, nag_wp, x04dbf, zgeqrf, zggbal,   &
                             zgghd3, zhgeqz, zunmqr
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Integer                          :: i, ifail, ihi, ilo, info, irows,     &
                                          jwork, lda, ldb, ldq, ldz, lwork, n, &
                                          ni
      Character (1)                    :: compq, compz, job
!     .. Local Arrays ..
      Complex (Kind=nag_wp), Allocatable :: a(:,:), alpha(:), b(:,:), beta(:), &
                                          e(:), q(:,:), tau(:), work(:),       &
                                          z(:,:)
      Real (Kind=nag_wp), Allocatable  :: emod(:), lscale(:), rscale(:),       &
                                          rwork(:)
      Integer, Allocatable             :: irank(:)
      Character (1)                    :: clabs(1), rlabs(1)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: abs, aimag, nint, real
!     .. Executable Statements ..
      Write (nout,*) 'F08XSF Example Program Results'
      Flush (nout)

!     Skip heading in data file

      Read (nin,*)
      Read (nin,*) n
      ldq = 1
      ldz = 1
      lda = n
      ldb = n
      lwork = 6*n
      Allocate (a(lda,n),alpha(n),b(ldb,n),beta(n),q(ldq,ldq),tau(n),          &
        work(lwork),z(ldz,ldz),lscale(n),rscale(n),rwork(6*n))

!     READ matrix A from data file
      Read (nin,*)(a(i,1:n),i=1,n)

!     READ matrix B from data file
      Read (nin,*)(b(i,1:n),i=1,n)

!     Balance matrix pair (A,B)
      job = 'B'
      Call zggbal(job,n,a,lda,b,ldb,ilo,ihi,lscale,rscale,rwork,info)

!     Matrix A after balancing

!     ifail: behaviour on error exit
!             =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
      ifail = 0
      Call x04dbf('General',' ',n,n,a,lda,'Bracketed','F7.4',                  &
        'Matrix A after balancing','Integer',rlabs,'Integer',clabs,80,0,ifail)

      Write (nout,*)
      Flush (nout)

!     Matrix B after balancing

      ifail = 0
      Call x04dbf('General',' ',n,n,b,ldb,'Bracketed','F7.4',                  &
        'Matrix B after balancing','Integer',rlabs,'Integer',clabs,80,0,ifail)

      Write (nout,*)
      Flush (nout)

!     Reduce B to triangular form using QR
      irows = ihi + 1 - ilo

!     The NAG name equivalent of zgeqrf is f08asf
      Call zgeqrf(irows,irows,b(ilo,ilo),ldb,tau,work,lwork,info)

!     Apply the orthogonal transformation to A
!     The NAG name equivalent of zunmqr is f08auf
      Call zunmqr('L','C',irows,irows,irows,b(ilo,ilo),ldb,tau,a(ilo,ilo),lda, &
        work,lwork,info)

!     Compute the generalized Hessenberg form of (A,B) -> (H,T)
      compq = 'N'
      compz = 'N'

!     The NAG name equivalent of zgghd3 is f08wuf
      Call zgghd3(compq,compz,irows,1,irows,a(ilo,ilo),lda,b(ilo,ilo),ldb,q,   &
        ldq,z,ldz,work,lwork,info)

!     Matrix A (H) in generalized Hessenberg form
      ifail = 0
      Call x04dbf('General',' ',n,n,a,lda,'Bracketed','F7.3',                  &
        'Matrix A in Hessenberg form','Integer',rlabs,'Integer',clabs,80,0,    &
        ifail)

      Write (nout,*)
      Flush (nout)

!     Matrix B (T) in generalized Hessenberg form
      ifail = 0
      Call x04dbf('General',' ',n,n,b,ldb,'Bracketed','F7.3',                  &
        'Matrix B is triangular','Integer',rlabs,'Integer',clabs,80,0,ifail)

!     Routine ZHGEQZ
!     Workspace query: jwork = -1

      jwork = -1
      job = 'E'
!     The NAG name equivalent of zhgeqz is f08xsf
      Call zhgeqz(job,compq,compz,n,ilo,ihi,a,lda,b,ldb,alpha,beta,q,ldq,z,    &
        ldz,work,jwork,rwork,info)
      Write (nout,*)
      Write (nout,99999) nint(real(work(1)))
      Write (nout,99998) lwork
      Write (nout,*)
      Write (nout,99997)
      Write (nout,*)
      Flush (nout)

!     Compute the generalized Schur form
!     if the workspace lwork is adequate

      If (nint(real(work(1)))<=lwork) Then

!       The NAG name equivalent of zhgeqz is f08xsf
        Call zhgeqz(job,compq,compz,n,ilo,ihi,a,lda,b,ldb,alpha,beta,q,ldq,z,  &
          ldz,work,lwork,rwork,info)

!       Print the generalized eigenvalues in descending size order
!       Note: the actual values of beta are real and non-negative

!       Calculate the moduli of the finite eigenvalues.
        Allocate (e(n),emod(n),irank(n))
        ni = 0
        Do i = 1, n
          If (real(beta(i))/=0.0_nag_wp) Then
            ni = ni + 1
            e(ni) = alpha(i)/beta(i)
            emod(ni) = abs(e(ni))
          Else
            Write (nout,99996) i
          End If
        End Do

!       Rearrange the finite eigenvalues in descending order of modulus.
        ifail = 0
        Call m01daf(emod,1,ni,'Descending',irank,ifail)
        ifail = 0
        Call m01edf(e,1,ni,irank,ifail)

        Write (nout,99995)(i,'(',real(e(i)),',',aimag(e(i)),')',i=1,ni)
      Else
        Write (nout,99994)
      End If

99999 Format (1X,'Minimal required LWORK = ',I6)
99998 Format (1X,'Actual value of  LWORK = ',I6)
99997 Format (1X,'Generalized eigenvalues')
99996 Format (1X,I4,5X,'Infinite eigenvalue')
99995 Format (1X,I4,5X,A,F7.3,A,F7.3,A)
99994 Format (1X,'Insufficient workspace allocated for call to F08XSF/ZHGEQZ')
    End Program f08xsfe


f08yefe.f90

    Program f08yefe

!     F08YEF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: dggsvp, dtgsja, f06raf, nag_wp, x02ajf, x04cbf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: eps, tola, tolb
      Integer                          :: i, ifail, info, irank, j, k, l, lda, &
                                          ldb, ldq, ldu, ldv, m, n, ncycle, p
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: a(:,:), alpha(:), b(:,:), beta(:),   &
                                          q(:,:), tau(:), u(:,:), v(:,:),      &
                                          work(:)
      Integer, Allocatable             :: iwork(:)
      Character (1)                    :: clabs(1), rlabs(1)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: max, real
!     .. Executable Statements ..
      Write (nout,*) 'F08YEF Example Program Results'
      Write (nout,*)
      Flush (nout)
!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) m, n, p
      lda = m
      ldb = p
      ldq = n
      ldu = m
      ldv = p
      Allocate (a(lda,n),alpha(n),b(ldb,n),beta(n),q(ldq,n),tau(n),u(ldu,m),   &
        v(ldv,p),work(m+3*n+p),iwork(n))

!     Read the m by n matrix A and p by n matrix B from data file

      Read (nin,*)(a(i,1:n),i=1,m)
      Read (nin,*)(b(i,1:n),i=1,p)

!     Compute tola and tolb as
!         tola = max(m,n)*norm(A)*macheps
!         tolb = max(p,n)*norm(B)*macheps

      eps = x02ajf()
      tola = real(max(m,n),kind=nag_wp)*f06raf('One-norm',m,n,a,lda,work)*eps
      tolb = real(max(p,n),kind=nag_wp)*f06raf('One-norm',p,n,b,ldb,work)*eps

!     Compute the factorization of (A, B)
!         (A = U1*S*(Q1**T), B = V1*T*(Q1**T))
!     The NAG name equivalent of dggsvp is f08vef
      Call dggsvp('U','V','Q',m,p,n,a,lda,b,ldb,tola,tolb,k,l,u,ldu,v,ldv,q,   &
        ldq,iwork,tau,work,info)

!     Compute the generalized singular value decomposition of (A, B)
!         (A = U*D1*(0 R)*(Q**T), B = V*D2*(0 R)*(Q**T))
!     The NAG name equivalent of dtgsja is f08yef
      Call dtgsja('U','V','Q',m,p,n,k,l,a,lda,b,ldb,tola,tolb,alpha,beta,u,    &
        ldu,v,ldv,q,ldq,work,ncycle,info)

      If (info==0) Then

!       Print solution

        irank = k + l
        Write (nout,*) 'Number of infinite generalized singular values (K)'
        Write (nout,99999) k
        Write (nout,*) 'Number of finite generalized singular values (L)'
        Write (nout,99999) l
        Write (nout,*) ' Effective Numerical rank of (A**T B**T)**T (K+L)'
        Write (nout,99999) irank
        Write (nout,*)
        Write (nout,*) 'Finite generalized singular values'
        Write (nout,99998)(alpha(j)/beta(j),j=k+1,irank)

        Write (nout,*)
        Flush (nout)

!       ifail: behaviour on error exit
!              =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
        ifail = 0
        Call x04cbf('General',' ',m,m,u,ldu,'1P,E12.4','Orthogonal matrix U',  &
          'Integer',rlabs,'Integer',clabs,80,0,ifail)

        Write (nout,*)
        Flush (nout)

        Call x04cbf('General',' ',p,p,v,ldv,'1P,E12.4','Orthogonal matrix V',  &
          'Integer',rlabs,'Integer',clabs,80,0,ifail)

        Write (nout,*)
        Flush (nout)

        Call x04cbf('General',' ',n,n,q,ldq,'1P,E12.4','Orthogonal matrix Q',  &
          'Integer',rlabs,'Integer',clabs,80,0,ifail)

        Write (nout,*)
        Flush (nout)

        Call x04cbf('Upper triangular','Non-unit',irank,irank,a(1,n-irank+1),  &
          lda,'1P,E12.4','Nonsingular upper triangular matrix R','Integer',    &
          rlabs,'Integer',clabs,80,0,ifail)

        Write (nout,*)
        Write (nout,*) 'Number of cycles of the Kogbetliantz method'
        Write (nout,99999) ncycle
      Else
        Write (nout,99997) 'Failure in DTGSJA. INFO =', info
      End If

99999 Format (1X,I5)
99998 Format (3X,8(1P,E12.4))
99997 Format (1X,A,I4)
    End Program f08yefe


f08yffe.f90

    Program f08yffe

!     F08YFF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: dtgexc, nag_wp, x04caf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
      Logical, Parameter               :: wantq = .False., wantz = .False.
!     .. Local Scalars ..
      Integer                          :: i, ifail, ifst, ilst, info, lda,     &
                                          ldb, ldq, ldz, lwork, n
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: a(:,:), b(:,:), q(:,:), work(:),     &
                                          z(:,:)
!     .. Executable Statements ..
      Write (nout,*) 'F08YFF Example Program Results'
      Write (nout,*)
      Flush (nout)
!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) n
      ldq = 1
      ldz = 1
      lda = n
      ldb = n
      lwork = 4*n + 16
      Allocate (a(lda,n),b(ldb,n),q(ldq,1),work(lwork),z(ldz,1))

!     Read A and B from data file

      Read (nin,*)(a(i,1:n),i=1,n)
      Read (nin,*)(b(i,1:n),i=1,n)

!     Read the row indices

      Read (nin,*) ifst, ilst

!     Reorder A and B

!     The NAG name equivalent of dtgexc is f08yff
      Call dtgexc(wantq,wantz,n,a,lda,b,ldb,q,ldq,z,ldz,ifst,ilst,work,lwork,  &
        info)

      If (info/=0) Then
        Write (nout,99999) info, ilst
        Write (nout,*)
        Flush (nout)
      End If

!     The resulting reordered Schur matrices can differ by +- signs by
!     multiplying rows and columns of Q and Z by -1. We will normalize here by
!     making the diagonals and last column of B positive.
      Call normalize(a,b)

!     Print reordered generalized Schur form

!     ifail: behaviour on error exit
!             =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
      ifail = 0
      Call x04caf('General',' ',n,n,a,lda,'Reordered Schur matrix A',ifail)

      Write (nout,*)
      Flush (nout)

      ifail = 0
      Call x04caf('General',' ',n,n,b,ldb,'Reordered Schur matrix B',ifail)

99999 Format (' Reordering could not be completed. INFO = ',I3,' ILST = ',I5)

    Contains
      Subroutine normalize(a,b)

!       .. Array Arguments ..
        Real (Kind=nag_wp), Intent (Inout) :: a(lda,n), b(ldb,n)
!       .. Local Scalars ..
        Integer                        :: i, j
!       .. Intrinsic Procedures ..
        Intrinsic                      :: max
!       .. Executable Statements ..

!       Last column of B positive
        Do i = 1, n
          j = max(1,i-1)
          If (b(i,n)<0.0_nag_wp) Then
            a(i,j:n) = -a(i,j:n)
            b(i,i:n) = -b(i,i:n)
          End If
        End Do

!       Diagonals of B positive
        Do i = 1, n - 1
          If (b(i,i)<0.0_nag_wp) Then
            a(1:i+1,i) = -a(1:i+1,i)
            b(1:i,i) = -b(1:i,i)
          End If
        End Do
      End Subroutine normalize
    End Program f08yffe


f08ygfe.f90

    Program f08ygfe

!     F08YGF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: dtgsen, nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: pl, pr
      Integer                          :: i, ijob, info, lda, ldb, ldc, ldq,   &
                                          ldz, liwork, lwork, m, n
      Logical                          :: wantq, wantz
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: a(:,:), alphai(:), alphar(:),        &
                                          b(:,:), beta(:), c(:,:), q(:,:),     &
                                          work(:), z(:,:)
      Real (Kind=nag_wp)               :: dif(2)
      Integer, Allocatable             :: iwork(:)
      Logical, Allocatable             :: select(:)
!     .. Executable Statements ..
      Write (nout,*) 'F08YGF Example Program Results'
      Write (nout,*)
      Flush (nout)
!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) n
      lda = n
      ldb = n
      ldc = n
      ldq = n
      ldz = n
      liwork = (n*n)/2 + 6
      lwork = n*(n+4) + 16
      Allocate (a(lda,n),alphai(n),alphar(n),b(ldb,n),beta(n),c(ldc,n),        &
        q(ldq,n),work(lwork),z(ldz,n),iwork(liwork),select(n))

!     Read A, B, Q, Z and the logical array SELECT from data file

      Read (nin,*)(a(i,1:n),i=1,n)
      Read (nin,*)(b(i,1:n),i=1,n)
      Read (nin,*)(q(i,1:n),i=1,n)
      Read (nin,*)(z(i,1:n),i=1,n)

      Read (nin,*) select(1:n)

!     Set ijob, wantq and wantz
      ijob = 4
      wantq = .True.
      wantz = .True.

!     Reorder the Schur factors A and B and update the matrices
!     Q and Z

!     The NAG name equivalent of dtgsen is f08ygf
      Call dtgsen(ijob,wantq,wantz,select,n,a,lda,b,ldb,alphar,alphai,beta,q,  &
        ldq,z,ldz,m,pl,pr,dif,work,lwork,iwork,liwork,info)

      If (info>0) Then
        Write (nout,99999) info
        Write (nout,*)
        Flush (nout)
      End If

!     Print Results
      Write (nout,99996) 'Number of selected eigenvalues  = ', m
      Write (nout,*)
      Write (nout,*) 'Selected Generalized Eigenvalues'
      Write (nout,*)
      Write (nout,99997)(i,alphar(i)/beta(i),alphai(i)/beta(i),i=1,m)

      Write (nout,*)
      Write (nout,99998) 'Norm estimate of projection onto',                   &
        ' left  eigenspace for selected cluster', 1.0_nag_wp/pl
      Write (nout,*)
      Write (nout,99998) 'Norm estimate of projection onto',                   &
        ' right eigenspace for selected cluster', 1.0_nag_wp/pr
      Write (nout,*)
      Write (nout,99998) 'F-norm based upper bound on', ' Difu', dif(1)
      Write (nout,*)
      Write (nout,99998) 'F-norm based upper bound on', ' Difl', dif(2)

99999 Format (' Reordering could not be completed. INFO = ',I3)
99998 Format (1X,2A,/,1X,1P,E10.2)
99997 Format (1X,I2,1X,'(',1P,E11.4,',',E11.4,')')
99996 Format (1X,A,I4)
    End Program f08ygfe


f08yhfe.f90

    Program f08yhfe

!     F08YHF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: dtgsyl, nag_wp, x04caf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: dif, scale
      Integer                          :: i, ifail, ijob, info, lda, ldb, ldc, &
                                          ldd, lde, ldf, lwork, m, n
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: a(:,:), b(:,:), c(:,:), d(:,:),      &
                                          e(:,:), f(:,:), work(:)
      Integer, Allocatable             :: iwork(:)
!     .. Executable Statements ..
      Write (nout,*) 'F08YHF Example Program Results'
      Write (nout,*)
      Flush (nout)
!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) m, n
      lda = m
      ldb = n
      ldc = m
      ldd = m
      lde = n
      ldf = m
      lwork = 1
      Allocate (a(lda,m),b(ldb,n),c(ldc,n),d(ldd,m),e(lde,n),f(ldf,n),         &
        work(lwork),iwork(m+n+6))

!     Read A, B, D, E, C and F from data file

      Read (nin,*)(a(i,1:m),i=1,m)
      Read (nin,*)(b(i,1:n),i=1,n)
      Read (nin,*)(d(i,1:m),i=1,m)
      Read (nin,*)(e(i,1:n),i=1,n)
      Read (nin,*)(c(i,1:n),i=1,m)
      Read (nin,*)(f(i,1:n),i=1,m)

!     Solve the Sylvester equations
!         A*R - L*B = scale*C and D*R - L*E = scale*F
!     for R and L.
      ijob = 0

!     The NAG name equivalent of dtgsyl is f08yhf
      Call dtgsyl('No transpose',ijob,m,n,a,lda,b,ldb,c,ldc,d,ldd,e,lde,f,ldf, &
        scale,dif,work,lwork,iwork,info)

      If (info>=1) Then
        Write (nout,99999)
        Write (nout,*)
        Flush (nout)
      End If

!     Print the solution matrices R and L

!     ifail: behaviour on error exit
!             =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
      ifail = 0
      Call x04caf('General',' ',m,n,c,ldc,'Solution matrix R',ifail)

      Write (nout,*)
      Flush (nout)

      ifail = 0
      Call x04caf('General',' ',m,n,f,ldf,'Solution matrix L',ifail)

      Write (nout,*)
      Write (nout,99998) 'SCALE = ', scale

99999 Format (/,' (A,D) and (B,E) have common or very close eigenval','ues.',  &
        /,' Perturbed values were used to solve the equations')
99998 Format (1X,A,1P,E10.2)
    End Program f08yhfe


f08ykfe.f90

!   F08YKF Example Program Text
!   Mark 26 Release. NAG Copyright 2016.

    Module f08ykfe_mod

!     F08YKF Example Program Module:
!            Parameters and User-defined Routines

!     .. Use Statements ..
      Use nag_library, Only: nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Accessibility Statements ..
      Private
      Public                           :: normalize
!     .. Parameters ..
      Real (Kind=nag_wp), Parameter, Public :: one = 1.0_nag_wp
      Real (Kind=nag_wp), Parameter, Public :: zero = 0.0_nag_wp
      Integer, Parameter, Public       :: nin = 5, nout = 6
    Contains
      Subroutine normalize(n,alphai,v,ldv)

!       .. Use Statements ..
        Use nag_library, Only: dnrm2
!       .. Implicit None Statement ..
        Implicit None
!       .. Scalar Arguments ..
        Integer, Intent (In)           :: ldv, n
!       .. Array Arguments ..
        Real (Kind=nag_wp), Intent (In) :: alphai(n)
        Real (Kind=nag_wp), Intent (Inout) :: v(ldv,*)
!       .. Local Scalars ..
        Real (Kind=nag_wp)             :: a, b, r, r1, r2, v1, v2
        Integer                        :: i, j, k
!       .. Intrinsic Procedures ..
        Intrinsic                      :: sqrt
!       .. Executable Statements ..

        Do j = 1, n

          If (alphai(j)>=0.0_nag_wp) Then
            If (alphai(j)==0.0_nag_wp) Then
!             Real eigenvalue
!             The 2-norm of Q is calculated using dnrm2 (f06ejf).
              r = dnrm2(n,v(1,j),1)
              v(1:n,j) = v(1:n,j)/r
            Else
!             Complex eigenvalue (positive imaginary part)
!             Make largest element real and positive
              r1 = dnrm2(n,v(1,j),1)
              r2 = dnrm2(n,v(1,j+1),1)
              r1 = sqrt(r1**2+r2**2)
              r2 = -1.0_nag_wp
              Do i = 1, n
                r = v(i,j)**2 + v(i,j+1)**2
                If (r>r2) Then
                  r2 = r
                  k = i
                End If
              End Do
              r = r1*sqrt(r2)
              a = v(k,j)/r
              b = v(k,j+1)/r
              Do i = 1, n
                v1 = v(i,j)
                v2 = v(i,j+1)
                v(i,j) = v1*a + v2*b
                v(i,j+1) = v2*a - v1*b
              End Do
            End If
          End If
        End Do
      End Subroutine normalize
    End Module f08ykfe_mod
    Program f08ykfe

!     F08YKF Example Main Program

!     .. Use Statements ..
      Use nag_library, Only: dgeqrf, dggbak, dggbal, dgghrd, dhgeqz, dorgqr,   &
                             dormqr, dtgevc, f06qff, f06qhf, nag_wp, x04cbf
      Use f08ykfe_mod, Only: nin, normalize, nout, one, zero
!     .. Implicit None Statement ..
      Implicit None
!     .. Local Scalars ..
      Integer                          :: i, icols, ifail, ihi, ilo, info,     &
                                          irows, jwork, lda, ldb, ldvl, ldvr,  &
                                          lwork, m, n
      Logical                          :: ileft, iright
      Character (1)                    :: compq, compz, howmny, job, side
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: a(:,:), alphai(:), alphar(:),        &
                                          b(:,:), beta(:), lscale(:),          &
                                          rscale(:), tau(:), vl(:,:), vr(:,:), &
                                          work(:)
      Logical, Allocatable             :: select(:)
      Character (0)                    :: clabs(1), rlabs(1)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: nint
!     .. Executable Statements ..
      Write (nout,*) 'F08YKF Example Program Results'
      Flush (nout)

!     ileft  is TRUE if left  eigenvectors are required
!     iright is TRUE if right eigenvectors are required

      ileft = .True.
      iright = .True.

!     Skip heading in data file

      Read (nin,*)
      Read (nin,*) n
      lda = n
      ldb = n
      ldvl = n
      ldvr = n
      lwork = 6*n
      Allocate (a(lda,n),alphai(n),alphar(n),b(ldb,n),beta(n),lscale(n),       &
        rscale(n),tau(n),vl(ldvl,ldvl),vr(ldvr,ldvr),work(lwork),select(n))

!     READ matrix A from data file
      Read (nin,*)(a(i,1:n),i=1,n)

!     READ matrix B from data file
      Read (nin,*)(b(i,1:n),i=1,n)

!     Balance matrix pair (A,B)
      job = 'B'
!     The NAG name equivalent of dggbal is f08whf
      Call dggbal(job,n,a,lda,b,ldb,ilo,ihi,lscale,rscale,work,info)

!     Matrix A after balancing
!     ifail: behaviour on error exit
!             =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
      ifail = 0
      Call x04cbf('General',' ',n,n,a,lda,'F8.4','Matrix A after balancing',   &
        'I',rlabs,'I',clabs,80,0,ifail)
      Write (nout,*)
      Flush (nout)

!     Matrix B after balancing
      ifail = 0
      Call x04cbf('General',' ',n,n,b,ldb,'F8.4','Matrix B after balancing',   &
        'I',rlabs,'I',clabs,80,0,ifail)
      Write (nout,*)
      Flush (nout)

!     Reduce B to triangular form using QR
      irows = ihi + 1 - ilo
      icols = n + 1 - ilo
!     The NAG name equivalent of dgeqrf is f08aef
      Call dgeqrf(irows,icols,b(ilo,ilo),ldb,tau,work,lwork,info)

!     Apply the orthogonal transformation to matrix A
!     The NAG name equivalent of dormqr is f08agf
      Call dormqr('L','T',irows,icols,irows,b(ilo,ilo),ldb,tau,a(ilo,ilo),lda, &
        work,lwork,info)

!     Initialize VL (if left eigenvectors are required)
      If (ileft) Then

        Call f06qhf('General',n,n,zero,one,vl,ldvl)
        Call f06qff('Lower',irows-1,irows-1,b(ilo+1,ilo),ldb,vl(ilo+1,ilo),    &
          ldvl)

!       The NAG name equivalent of dorgqr is f08aff
        Call dorgqr(irows,irows,irows,vl(ilo,ilo),ldvl,tau,work,lwork,info)
      End If

!     Initialize VR (if right eigenvectors are required)
      If (iright) Then
        Call f06qhf('General',n,n,zero,one,vr,ldvr)
      End If

!     Compute the generalized Hessenberg form of (A,B)
      compq = 'V'
      compz = 'V'
!     The NAG name equivalent of dgghrd is f08wef
      Call dgghrd(compq,compz,n,ilo,ihi,a,lda,b,ldb,vl,ldvl,vr,ldvr,info)

!     Matrix A in generalized Hessenberg form
      ifail = 0
      Call x04cbf('General',' ',n,n,a,lda,'F8.4','Matrix A in Hessenberg form' &
        ,'I',rlabs,'I',clabs,80,0,ifail)
      Write (nout,*)
      Flush (nout)

!     Matrix B in generalized Hessenberg form
      ifail = 0
      Call x04cbf('General',' ',n,n,b,ldb,'F8.4','Matrix B in Hessenberg form' &
        ,'I',rlabs,'I',clabs,80,0,ifail)

!     Routine DHGEQZ
!     Workspace query: jwork = -1

      jwork = -1
      job = 'S'

!     The NAG name equivalent of dhgeqz is f08xef
      Call dhgeqz(job,compq,compz,n,ilo,ihi,a,lda,b,ldb,alphar,alphai,beta,vl, &
        ldvl,vr,ldvr,work,jwork,info)

      Write (nout,*)
      Write (nout,99999) nint(work(1))
      Write (nout,99998) lwork
      Write (nout,*)
      Write (nout,99997)
      Write (nout,99996)

!     Compute the generalized Schur form
!     if the workspace lwork is adequate
!     The Schur form also gives parameters
!     required to compute generalized eigenvalues

      If (nint(work(1))<=lwork) Then

!       The NAG name equivalent of dhgeqz is f08xef
        Call dhgeqz(job,compq,compz,n,ilo,ihi,a,lda,b,ldb,alphar,alphai,beta,  &
          vl,ldvl,vr,ldvr,work,lwork,info)

!       Print the generalized eigenvalues

        Do i = 1, n
          If (beta(i)/=0.0E0_nag_wp) Then
            Write (nout,99995) i, '(', alphar(i)/beta(i), ',',                 &
              alphai(i)/beta(i), ')'
          Else
            Write (nout,99996) i
          End If
        End Do
        Write (nout,*)
        Flush (nout)

!       Compute left and right generalized eigenvectors
!       of the balanced matrix

        howmny = 'B'
        If (ileft .And. iright) Then
          side = 'B'
        Else If (ileft) Then
          side = 'L'
        Else If (iright) Then
          side = 'R'
        End If

!       The NAG name equivalent of dtgevc is f08ykf
        Call dtgevc(side,howmny,select,n,a,lda,b,ldb,vl,ldvl,vr,ldvr,n,m,work, &
          info)

        If (iright) Then

!         Compute right eigenvectors of the original matrix

          job = 'B'
          side = 'R'

!         The NAG name equivalent of dggbak is f08wjf
          Call dggbak(job,side,n,ilo,ihi,lscale,rscale,n,vr,ldvr,info)

          Call normalize(n,alphai,vr,ldvr)
!         Print the right eigenvectors

          ifail = 0
          Call x04cbf('General',' ',n,n,vr,ldvr,'F8.4','Right eigenvectors',   &
            'I',rlabs,'I',clabs,80,0,ifail)

          Write (nout,*)
          Flush (nout)
        End If

!       Compute left eigenvectors of the original matrix

        If (ileft) Then
          job = 'B'
          side = 'L'

!         The NAG name equivalent of dggbak is f08wjf
          Call dggbak(job,side,n,ilo,ihi,lscale,rscale,n,vl,ldvl,info)

          Call normalize(n,alphai,vl,ldvl)
!         Print the left eigenvectors

          ifail = 0
          Call x04cbf('General',' ',n,n,vl,ldvl,'F8.4','Left eigenvectors',    &
            'I',rlabs,'I',clabs,80,0,ifail)

        End If
      Else
        Write (nout,99994)
      End If

99999 Format (1X,'Minimal required LWORK = ',I6)
99998 Format (1X,'Actual value of  LWORK = ',I6)
99997 Format (1X,'Generalized eigenvalues')
99996 Format (1X,I4,5X,'Infinite eigenvalue')
99995 Format (1X,I4,5X,A,F7.3,A,F7.3,A)
99994 Format (1X,'Insufficient workspace for array WORK',/,' in F08XEF/',      &
        'DHGEQZ')
    End Program f08ykfe


f08ylfe.f90

    Program f08ylfe

!     F08YLF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: dtgevc, dtgsna, f06bnf, f06raf, nag_wp, x02ajf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: eps, snorm, stnrm, tnorm
      Integer                          :: i, info, lda, ldb, ldvl, ldvr,       &
                                          lwork, m, n
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: a(:,:), b(:,:), dif(:), s(:),        &
                                          vl(:,:), vr(:,:), work(:)
      Integer, Allocatable             :: iwork(:)
      Logical                          :: select(1)
!     .. Executable Statements ..
      Write (nout,*) 'F08YLF Example Program Results'
      Write (nout,*)
!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) n
      lda = n
      ldb = n
      ldvl = n
      ldvr = n
      lwork = 2*n*(n+2) + 16
      Allocate (a(lda,n),b(ldb,n),dif(n),s(n),vl(ldvl,n),vr(ldvr,n),           &
        work(lwork),iwork(n+6))

!     Read A and B from data file

      Read (nin,*)(a(i,1:n),i=1,n)
      Read (nin,*)(b(i,1:n),i=1,n)

!     Calculate the left and right generalized eigenvectors of the
!     pair (A,B). Note that DTGEVC requires WORK to be of dimension
!     at least 6*n.

!     The NAG name equivalent of dtgevc is f08ykf
      Call dtgevc('Both','All',select,n,a,lda,b,ldb,vl,ldvl,vr,ldvr,n,m,work,  &
        info)

      If (info>0) Then
        Write (nout,99999) info, info + 1
      Else

!       Estimate condition numbers for all the generalized eigenvalues
!       and right eigenvectors of the pair (A,B)

!       The NAG name equivalent of dtgsna is f08ylf
        Call dtgsna('Both','All',select,n,a,lda,b,ldb,vl,ldvl,vr,ldvr,s,dif,n, &
          m,work,lwork,iwork,info)

!       Print condition numbers of eigenvalues and right eigenvectors

        Write (nout,*) 'S'
        Write (nout,99998) s(1:m)
        Write (nout,*)
        Write (nout,*) 'DIF'
        Write (nout,99998) dif(1:m)

!       Calculate approximate error estimates

!       Compute the 1-norms of A and B and then compute
!       SQRT(snorm**2 + tnorm**2)

        eps = x02ajf()
        snorm = f06raf('1-norm',n,n,a,lda,work)
        tnorm = f06raf('1-norm',n,n,b,ldb,work)
        stnrm = f06bnf(snorm,tnorm)
        Write (nout,*)
        Write (nout,*) 'Approximate error estimates for eigenvalues of (A,B)'
        Write (nout,99998)(eps*stnrm/s(i),i=1,m)
        Write (nout,*)
        Write (nout,*) 'Approximate error estimates for right ',               &
          'eigenvectors of (A,B)'
        Write (nout,99998)(eps*stnrm/dif(i),i=1,m)
      End If

99999 Format (' The 2-by-2 block (',I5,':',I5,') does not have a co',          &
        'mplex eigenvalue')
99998 Format ((3X,1P,7E11.1))
    End Program f08ylfe


f08ysfe.f90

    Program f08ysfe

!     F08YSF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: f06uaf, nag_wp, x02ajf, x04dbf, zggsvp, ztgsja
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: eps, tola, tolb
      Integer                          :: i, ifail, info, irank, j, k, l, lda, &
                                          ldb, ldq, ldu, ldv, m, n, ncycle, p
!     .. Local Arrays ..
      Complex (Kind=nag_wp), Allocatable :: a(:,:), b(:,:), q(:,:), tau(:),    &
                                          u(:,:), v(:,:), work(:)
      Real (Kind=nag_wp), Allocatable  :: alpha(:), beta(:), rwork(:)
      Integer, Allocatable             :: iwork(:)
      Character (1)                    :: clabs(1), rlabs(1)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: max, real
!     .. Executable Statements ..
      Write (nout,*) 'F08YSF Example Program Results'
      Write (nout,*)
      Flush (nout)

!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) m, n, p
      lda = m
      ldb = p
      ldq = n
      ldu = m
      ldv = p
      Allocate (a(lda,n),b(ldb,n),q(ldq,n),tau(n),u(ldu,m),v(ldv,p),           &
        work(m+3*n+p),alpha(n),beta(n),rwork(2*n),iwork(n))

!     Read the m by n matrix A and p by n matrix B from data file

      Read (nin,*)(a(i,1:n),i=1,m)
      Read (nin,*)(b(i,1:n),i=1,p)

!     Compute tola and tolb as
!         tola = max(m,n)*norm(A)*macheps
!         tolb = max(p,n)*norm(B)*macheps

      eps = x02ajf()
      tola = real(max(m,n),kind=nag_wp)*f06uaf('One-norm',m,n,a,lda,rwork)*eps
      tolb = real(max(p,n),kind=nag_wp)*f06uaf('One-norm',p,n,b,ldb,rwork)*eps

!     Compute the factorization of (A, B)
!         (A = U1*S*(Q1**H), B = V1*T*(Q1**H))

!     The NAG name equivalent of zggsvp is f08vsf
      Call zggsvp('U','V','Q',m,p,n,a,lda,b,ldb,tola,tolb,k,l,u,ldu,v,ldv,q,   &
        ldq,iwork,rwork,tau,work,info)

!     Compute the generalized singular value decomposition of (A, B)
!         (A = U*D1*(0 R)*(Q**H), B = V*D2*(0 R)*(Q**H))

!     The NAG name equivalent of ztgsja is f08ysf
      Call ztgsja('U','V','Q',m,p,n,k,l,a,lda,b,ldb,tola,tolb,alpha,beta,u,    &
        ldu,v,ldv,q,ldq,work,ncycle,info)

      If (info==0) Then

!       Print solution

        irank = k + l
        Write (nout,*) 'Number of infinite generalized singular values (K)'
        Write (nout,99999) k
        Write (nout,*) 'Number of finite generalized singular values (L)'
        Write (nout,99999) l
        Write (nout,*) ' Effective Numerical rank of (A**T B**T)**T (K+L)'
        Write (nout,99999) irank
        Write (nout,*)
        Write (nout,*) 'Finite generalized singular values'
        Write (nout,99998)(alpha(j)/beta(j),j=k+1,irank)
        Write (nout,*)
        Flush (nout)

!       ifail: behaviour on error exit
!              =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
        ifail = 0
        Call x04dbf('General',' ',m,m,u,ldu,'Bracketed','1P,E12.4',            &
          'Unitary matrix U','Integer',rlabs,'Integer',clabs,80,0,ifail)

        Write (nout,*)
        Flush (nout)

        Call x04dbf('General',' ',p,p,v,ldv,'Bracketed','1P,E12.4',            &
          'Unitary matrix V','Integer',rlabs,'Integer',clabs,80,0,ifail)

        Write (nout,*)
        Flush (nout)

        Call x04dbf('General',' ',n,n,q,ldq,'Bracketed','1P,E12.4',            &
          'Unitary matrix Q','Integer',rlabs,'Integer',clabs,80,0,ifail)

        Write (nout,*)
        Flush (nout)

        Call x04dbf('Upper triangular','Non-unit',irank,irank,a(1,n-irank+1),  &
          lda,'Bracketed','1P,E12.4','Nonsingular upper triangular matrix R',  &
          'Integer',rlabs,'Integer',clabs,80,0,ifail)

        Write (nout,*)
        Write (nout,*) 'Number of cycles of the Kogbetliantz method'
        Write (nout,99999) ncycle
      Else
        Write (nout,99997) 'Failure in ZTGSJA. INFO =', info
      End If

99999 Format (1X,I5)
99998 Format (3X,8(1P,E12.4))
99997 Format (1X,A,I4)
    End Program f08ysfe


f08ytfe.f90

    Program f08ytfe

!     F08YTF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: nag_wp, x04dbf, ztgexc
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
      Logical, Parameter               :: wantq = .False., wantz = .False.
!     .. Local Scalars ..
      Integer                          :: i, ifail, ifst, ilst, info, lda,     &
                                          ldb, ldq, ldz, n
!     .. Local Arrays ..
      Complex (Kind=nag_wp), Allocatable :: a(:,:), b(:,:), q(:,:), z(:,:)
      Character (1)                    :: clabs(1), rlabs(1)
!     .. Executable Statements ..
      Write (nout,*) 'F08YTF Example Program Results'
      Write (nout,*)
      Flush (nout)
!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) n
      ldq = 1
      ldz = 1
      lda = n
      ldb = n
      Allocate (a(lda,n),b(ldb,n),q(ldq,1),z(ldz,1))

!     Read A and B from data file

      Read (nin,*)(a(i,1:n),i=1,n)
      Read (nin,*)(b(i,1:n),i=1,n)

!     Read the row indices

      Read (nin,*) ifst, ilst

!     Reorder the A and B

!     The NAG name equivalent of ztgexc is f08ytf
      Call ztgexc(wantq,wantz,n,a,lda,b,ldb,q,ldq,z,ldz,ifst,ilst,info)

      If (info/=0) Then
        Write (nout,99999) info, ilst
        Write (nout,*)
        Flush (nout)
      End If

!     Print reordered generalized Schur form

!     ifail: behaviour on error exit
!             =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
      ifail = 0
      Call x04dbf('General',' ',n,n,a,lda,'Bracketed','F7.4',                  &
        'Reordered Schur matrix A','Integer',rlabs,'Integer',clabs,80,0,ifail)

      Write (nout,*)
      Flush (nout)

      ifail = 0
      Call x04dbf('General',' ',n,n,b,ldb,'Bracketed','F7.4',                  &
        'Reordered Schur matrix B','Integer',rlabs,'Integer',clabs,80,0,ifail)

99999 Format (' Reordering could not be completed. INFO = ',I3,' ILST = ',I5)
    End Program f08ytfe


f08yufe.f90

    Program f08yufe

!     F08YUF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: nag_wp, x04dbf, ztgsen
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: pl, pr
      Integer                          :: i, ifail, ijob, info, lda, ldb, ldq, &
                                          ldz, liwork, lwork, m, n
      Logical                          :: wantq, wantz
!     .. Local Arrays ..
      Complex (Kind=nag_wp), Allocatable :: a(:,:), alpha(:), b(:,:), beta(:), &
                                          q(:,:), work(:), z(:,:)
      Real (Kind=nag_wp)               :: dif(2)
      Integer, Allocatable             :: iwork(:)
      Logical, Allocatable             :: select(:)
      Character (1)                    :: clabs(1), rlabs(1)
!     .. Executable Statements ..
      Write (nout,*) 'F08YUF Example Program Results'
      Write (nout,*)
      Flush (nout)
!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) n
      lda = n
      ldb = n
      ldq = n
      ldz = n
      liwork = (n*n)/2 + 2
      lwork = n*n
      Allocate (a(lda,n),alpha(n),b(ldb,n),beta(n),q(ldq,n),work(lwork),       &
        z(ldz,n),iwork(liwork),select(n))

!     Read A, B, Q, Z and the logical array SELECT from data file

      Read (nin,*)(a(i,1:n),i=1,n)
      Read (nin,*)(b(i,1:n),i=1,n)
      Read (nin,*)(q(i,1:n),i=1,n)
      Read (nin,*)(z(i,1:n),i=1,n)

      Read (nin,*) select(1:n)

!     Set ijob, wantq and wantz
      ijob = 4
      wantq = .True.
      wantz = .True.

!     Reorder the Schur factors A and B and update the matrices
!     Q and Z

!     The NAG name equivalent of ztgsen is f08yuf
      Call ztgsen(ijob,wantq,wantz,select,n,a,lda,b,ldb,alpha,beta,q,ldq,z,    &
        ldz,m,pl,pr,dif,work,lwork,iwork,liwork,info)

      If (info/=0) Then
        Write (nout,99999) info
        Write (nout,*)
        Flush (nout)
      End If

!     Print reordered generalized Schur form

!     ifail: behaviour on error exit
!             =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
      ifail = 0
      Call x04dbf('General',' ',n,n,a,lda,'Bracketed','F7.4',                  &
        'Reordered Schur matrix A','Integer',rlabs,'Integer',clabs,80,0,ifail)

      Write (nout,*)
      Flush (nout)

      ifail = 0
      Call x04dbf('General',' ',n,n,b,ldb,'Bracketed','F7.4',                  &
        'Reordered Schur matrix B','Integer',rlabs,'Integer',clabs,80,0,ifail)

!     Print deflating subspaces

      Write (nout,*)
      Flush (nout)

      ifail = 0
      Call x04dbf('General',' ',n,m,q,ldq,'Bracketed','F7.4',                  &
        'Basis of left deflating invariant subspace','Integer',rlabs,          &
        'Integer',clabs,80,0,ifail)

      Write (nout,*)
      Flush (nout)

      ifail = 0
      Call x04dbf('General',' ',n,m,z,ldz,'Bracketed','F7.4',                  &
        'Basis of right deflating invariant subspace','Integer',rlabs,         &
        'Integer',clabs,80,0,ifail)

!     Print norm estimates and F-norm upper bounds

      Write (nout,*)
      Write (nout,99998) 'Norm estimate of projection onto',                   &
        ' left  eigenspace for selected cluster', 1.0E0_nag_wp/pl
      Write (nout,*)
      Write (nout,99998) 'Norm estimate of projection onto',                   &
        ' right eigenspace for selected cluster', 1.0E0_nag_wp/pr
      Write (nout,*)
      Write (nout,99998) 'F-norm based upper bound on', ' Difu', dif(1)
      Write (nout,*)
      Write (nout,99998) 'F-norm based upper bound on', ' Difl', dif(2)

99999 Format (' Reordering could not be completed. INFO = ',I3)
99998 Format (1X,2A,/,1X,1P,E10.2)
    End Program f08yufe


f08yvfe.f90

    Program f08yvfe

!     F08YVF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: nag_wp, x04dbf, ztgsyl
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: dif, scale
      Integer                          :: i, ifail, ijob, info, lda, ldb, ldc, &
                                          ldd, lde, ldf, lwork, m, n
!     .. Local Arrays ..
      Complex (Kind=nag_wp), Allocatable :: a(:,:), b(:,:), c(:,:), d(:,:),    &
                                          e(:,:), f(:,:), work(:)
      Integer, Allocatable             :: iwork(:)
      Character (1)                    :: clabs(1), rlabs(1)
!     .. Executable Statements ..
      Write (nout,*) 'F08YVF Example Program Results'
      Write (nout,*)
      Flush (nout)
!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) m, n
      lda = m
      ldb = n
      ldc = m
      ldd = m
      lde = n
      ldf = m
      lwork = 1
      Allocate (a(lda,m),b(ldb,n),c(ldc,n),d(ldd,m),e(lde,n),f(ldf,n),         &
        work(lwork),iwork(m+n+2))

!     Read A, B, D, E, C and F from data file

      Read (nin,*)(a(i,1:m),i=1,m)
      Read (nin,*)(b(i,1:n),i=1,n)
      Read (nin,*)(d(i,1:m),i=1,m)
      Read (nin,*)(e(i,1:n),i=1,n)
      Read (nin,*)(c(i,1:n),i=1,m)
      Read (nin,*)(f(i,1:n),i=1,m)

!     Solve the Sylvester equations
!         A*R - L*B = scale*C and D*R - L*E = scale*F
!     for R and L.

      ijob = 0

!     The NAG name equivalent of ztgsyl is f08yvf
      Call ztgsyl('No transpose',ijob,m,n,a,lda,b,ldb,c,ldc,d,ldd,e,lde,f,ldf, &
        scale,dif,work,lwork,iwork,info)

      If (info>=1) Then
        Write (nout,99999)
        Write (nout,*)
        Flush (nout)
      End If

!     Print the solution matrices R and L

!     ifail: behaviour on error exit
!             =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
      ifail = 0
      Call x04dbf('General',' ',m,n,c,ldc,'Bracketed','F7.4',                  &
        'Solution matrix R','Integer',rlabs,'Integer',clabs,80,0,ifail)

      Write (nout,*)
      Flush (nout)

      ifail = 0
      Call x04dbf('General',' ',m,n,f,ldf,'Bracketed','F7.4',                  &
        'Solution matrix L','Integer',rlabs,'Integer',clabs,80,0,ifail)

      Write (nout,*)
      Write (nout,99998) 'SCALE = ', scale

99999 Format (/,' (A,D) and (B,E) have common or very close eigenval','ues.',  &
        /,' Perturbed values were used to solve the equations')
99998 Format (1X,A,1P,E10.2)
    End Program f08yvfe


f08yxfe.f90

    Program f08yxfe

!     F08YXF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: dznrm2, f06tff, f06thf, m01daf, m01edf, nag_wp,   &
                             x04dbf, zgeqrf, zggbak, zggbal, zgghrd, zhgeqz,   &
                             ztgevc, zungqr, zunmqr
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Complex (Kind=nag_wp), Parameter :: cone = (1.0E0_nag_wp,0.0E0_nag_wp)
      Complex (Kind=nag_wp), Parameter :: czero = (0.0E0_nag_wp,0.0E0_nag_wp)
      Integer, Parameter               :: nin = 5, nout = 6
      Logical, Parameter               :: prbal = .False., prhess = .False.
!     .. Local Scalars ..
      Complex (Kind=nag_wp)            :: scal
      Integer                          :: i, icols, ifail, ihi, ilo, info,     &
                                          irows, j, jwork, k, lda, ldb, ldvl,  &
                                          ldvr, lwork, m, n
      Logical                          :: ileft, iright
      Character (1)                    :: compq, compz, howmny, job, side
!     .. Local Arrays ..
      Complex (Kind=nag_wp), Allocatable :: a(:,:), alpha(:), b(:,:), beta(:), &
                                          tau(:), v(:,:), vl(:,:), vr(:,:),    &
                                          work(:), zwork(:)
      Real (Kind=nag_wp), Allocatable  :: lscale(:), rscale(:), rwork(:)
      Integer, Allocatable             :: irank(:)
      Logical, Allocatable             :: select(:)
      Character (1)                    :: clabs(1), rlabs(1)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: abs, aimag, all, cmplx, conjg,       &
                                          maxloc, nint, real
!     .. Executable Statements ..
      Write (nout,*) 'F08YXF Example Program Results'
      Flush (nout)

!     ileft  is TRUE if left  eigenvectors are required
!     iright is TRUE if right eigenvectors are required

      ileft = .True.
      iright = .True.

!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) n
      lda = n
      ldb = n
      ldvl = n
      ldvr = n
      lwork = 6*n
      Allocate (a(lda,n),alpha(n),b(ldb,n),beta(n),tau(n),vl(ldvl,ldvl),       &
        vr(ldvr,ldvr),work(lwork),lscale(n),rscale(n),rwork(6*n),select(n),    &
        irank(n),v(n,n))

!     READ matrix A from data file
      Read (nin,*)(a(i,1:n),i=1,n)

!     READ matrix B from data file
      Read (nin,*)(b(i,1:n),i=1,n)

!     Balance matrix pair (A,B)
      job = 'B'
!     The NAG name equivalent of zggbal is f08wvf
      Call zggbal(job,n,a,lda,b,ldb,ilo,ihi,lscale,rscale,rwork,info)

      If (prbal) Then
!       Matrix A after balancing
!       ifail: behaviour on error exit
!               =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
        ifail = 0
        Call x04dbf('General',' ',n,n,a,lda,'Bracketed','F7.4',                &
          'Matrix A after balancing','Integer',rlabs,'Integer',clabs,80,0,     &
          ifail)
        Write (nout,*)
        Flush (nout)

!       Matrix B after balancing
        ifail = 0
        Call x04dbf('General',' ',n,n,b,ldb,'Bracketed','F7.4',                &
          'Matrix B after balancing','Integer',rlabs,'Integer',clabs,80,0,     &
          ifail)
        Write (nout,*)
        Flush (nout)
      End If

!     Reduce B to triangular form using QR
      irows = ihi + 1 - ilo
      icols = n + 1 - ilo
!     The NAG name equivalent of zgeqrf is f08asf
      Call zgeqrf(irows,icols,b(ilo,ilo),ldb,tau,work,lwork,info)

!     Apply the orthogonal transformation to A
!     The NAG name equivalent of zunmqr is f08auf
      Call zunmqr('L','C',irows,icols,irows,b(ilo,ilo),ldb,tau,a(ilo,ilo),lda, &
        work,lwork,info)

!     Initialize VL (for left eigenvectors)
      If (ileft) Then

        Call f06thf('General',n,n,czero,cone,vl,ldvl)
        Call f06tff('Lower',irows-1,irows-1,b(ilo+1,ilo),ldb,vl(ilo+1,ilo),    &
          ldvl)
!       The NAG name equivalent of zungqr is f08atf
        Call zungqr(irows,irows,irows,vl(ilo,ilo),ldvl,tau,work,lwork,info)

      End If

!     Initialize VR for right eigenvectors
      If (iright) Then
        Call f06thf('General',n,n,czero,cone,vr,ldvr)
      End If

!     Compute the generalized Hessenberg form of (A,B)
      compq = 'V'
      compz = 'V'
!     The NAG name equivalent of zgghrd is f08wsf
      Call zgghrd(compq,compz,n,ilo,ihi,a,lda,b,ldb,vl,ldvl,vr,ldvr,info)

      If (prhess) Then
!       Matrix A in generalized Hessenberg form
        ifail = 0
        Call x04dbf('General',' ',n,n,a,lda,'Bracketed','F7.3',                &
          'Matrix A in Hessenberg form','Integer',rlabs,'Integer',clabs,80,0,  &
          ifail)
        Write (nout,*)
        Flush (nout)

!       Matrix B in generalized Hessenberg form
        ifail = 0
        Call x04dbf('General',' ',n,n,b,ldb,'Bracketed','F7.3',                &
          'Matrix B in Hessenberg form','Integer',rlabs,'Integer',clabs,80,0,  &
          ifail)
        Write (nout,*)
        Flush (nout)
      End If

!     Routine ZHGEQZ
!     Workspace query: jwork = -1
      jwork = -1
      job = 'S'
!     The NAG name equivalent of zhgeqz is f08xsf
      Call zhgeqz(job,compq,compz,n,ilo,ihi,a,lda,b,ldb,alpha,beta,vl,ldvl,vr, &
        ldvr,work,jwork,rwork,info)

      lwork = nint(real(work(1)))
      Allocate (zwork(lwork))

!     Compute the generalized Schur form
!     The NAG name equivalent of zhgeqz is f08xsf
      Call zhgeqz(job,compq,compz,n,ilo,ihi,a,lda,b,ldb,alpha,beta,vl,ldvl,vr, &
        ldvr,zwork,lwork,rwork,info)

!     Sort and print generalized eigenvalues if none are infinite.
      If (all(real(beta(1:n))>0.0_nag_wp)) Then
!       Store absolute values of eigenvalues for ranking
        work(1:n) = alpha(1:n)/beta(1:n)
        rwork(1:n) = abs(work(1:n))

!       Rank eigenvalues
        ifail = 0
        Call m01daf(rwork,1,n,'Descending',irank,ifail)

!       Sort eigenvalues in work(1:n)
        Call m01edf(work,1,n,irank,ifail)

        Write (nout,99999)
        Do i = 1, n
          Write (nout,99998) i, '(', real(work(i)), ',', aimag(work(i)), ')'
        End Do
        Write (nout,*)
        Flush (nout)
      Else
        irank(1:n) = (/(i,i=1,n)/)
      End If

!     Compute left and right generalized eigenvectors
!     of the balanced matrix
      howmny = 'B'
      If (ileft .And. iright) Then
        side = 'B'
      Else If (ileft) Then
        side = 'L'
      Else If (iright) Then
        side = 'R'
      End If

!     The NAG name equivalent of ztgevc is f08yxf
      Call ztgevc(side,howmny,select,n,a,lda,b,ldb,vl,ldvl,vr,ldvr,n,m,work,   &
        rwork,info)

!     Compute right eigenvectors of the original matrix

      If (iright) Then
        job = 'B'
        side = 'R'

!       The NAG name equivalent of zggbak is f08wwf
        Call zggbak(job,side,n,ilo,ihi,lscale,rscale,n,vr,ldvr,info)

!       Normalize the right eigenvectors
        Do i = 1, n
          j = irank(i)
          rwork(1:n) = abs(vr(1:n,i))
          k = maxloc(rwork(1:n),1)
          scal = conjg(vr(k,i))/abs(vr(k,i))/dznrm2(n,vr(1,i),1)
          v(1:n,j) = vr(1:n,i)*scal
          v(k,j) = cmplx(real(v(k,j)),kind=nag_wp)
        End Do

!       Print the right eigenvectors

        ifail = 0
        Call x04dbf('General',' ',n,n,v,n,'Bracketed','F7.4',                  &
          'Right eigenvectors','Integer',rlabs,'Integer',clabs,80,0,ifail)

        Write (nout,*)
        Flush (nout)

      End If

!     Compute left eigenvectors of the original matrix

      If (ileft) Then
        job = 'B'
        side = 'L'

!       The NAG name equivalent of zggbak is f08wwf
        Call zggbak(job,side,n,ilo,ihi,lscale,rscale,n,vl,ldvl,info)

!       Normalize the left eigenvectors
        Do i = 1, n
          j = irank(i)
          rwork(1:n) = abs(vl(1:n,i))
          k = maxloc(rwork(1:n),1)
          scal = conjg(vl(k,i))/abs(vl(k,i))/dznrm2(n,vl(1,i),1)
          v(1:n,j) = vl(1:n,i)*scal
          v(k,j) = cmplx(real(v(k,j)),kind=nag_wp)
        End Do

!       Print the left eigenvectors

        ifail = 0
        Call x04dbf('General',' ',n,n,v,n,'Bracketed','F7.4',                  &
          'Left eigenvectors','Integer',rlabs,'Integer',clabs,80,0,ifail)

      End If

99999 Format (1X,/,1X,'Generalized eigenvalues')
99998 Format (1X,I4,5X,A,F7.3,A,F7.3,A)
    End Program f08yxfe


f08yyfe.f90

    Program f08yyfe

!     F08YYF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: f06bnf, f06uaf, nag_wp, x02ajf, ztgevc, ztgsna
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: eps, snorm, stnrm, tnorm
      Integer                          :: i, info, lda, ldb, ldvl, ldvr,       &
                                          lwork, m, n
!     .. Local Arrays ..
      Complex (Kind=nag_wp), Allocatable :: a(:,:), b(:,:), vl(:,:), vr(:,:),  &
                                          work(:)
      Real (Kind=nag_wp), Allocatable  :: dif(:), rwork(:), s(:)
      Integer, Allocatable             :: iwork(:)
      Logical                          :: select(1)
!     .. Executable Statements ..
      Write (nout,*) 'F08YYF Example Program Results'
      Write (nout,*)
!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) n
      lda = n
      ldb = n
      ldvl = n
      ldvr = n
      lwork = 2*n*n
      Allocate (a(lda,n),b(ldb,n),vl(ldvl,n),vr(ldvr,n),work(lwork),dif(n),    &
        rwork(2*n),s(n),iwork(n+2))

!     Read A and B from data file

      Read (nin,*)(a(i,1:n),i=1,n)
      Read (nin,*)(b(i,1:n),i=1,n)

!     Calculate the left and right generalized eigenvectors of the
!     pair (A,B).

!     The NAG name equivalent of ztgevc is f08yxf
      Call ztgevc('Both','All',select,n,a,lda,b,ldb,vl,ldvl,vr,ldvr,n,m,work,  &
        rwork,info)

!     Estimate condition numbers for all the generalized eigenvalues
!     and right eigenvectors of the pair (A,B)

!     The NAG name equivalent of ztgsna is f08yyf
      Call ztgsna('Both','All',select,n,a,lda,b,ldb,vl,ldvl,vr,ldvr,s,dif,n,m, &
        work,lwork,iwork,info)

!     Print condition numbers of eigenvalues and right eigenvectors

      Write (nout,*) 'S'
      Write (nout,99999) s(1:m)
      Write (nout,*)
      Write (nout,*) 'DIF'
      Write (nout,99999) dif(1:m)

!     Calculate approximate error estimates

!     Compute the 1-norms of A and B and then compute
!     SQRT(snorm**2 + tnorm**2)

      eps = x02ajf()
      snorm = f06uaf('1-norm',n,n,a,lda,rwork)
      tnorm = f06uaf('1-norm',n,n,b,ldb,rwork)
      stnrm = f06bnf(snorm,tnorm)
      Write (nout,*)
      Write (nout,*) 'Approximate error estimates for eigenvalues of (A,B)'
      Write (nout,99999)(eps*stnrm/s(i),i=1,m)
      Write (nout,*)
      Write (nout,*)                                                           &
        'Approximate error estimates for right eigenvectors of (A,B)'
      Write (nout,99999)(eps*stnrm/dif(i),i=1,m)

99999 Format ((3X,1P,7E11.1))
    End Program f08yyfe


f08zafe.f90

    Program f08zafe

!     F08ZAF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: dgglse, dnrm2, nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nb = 64, nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: rnorm
      Integer                          :: i, info, lda, ldb, lwork, m, n, p
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: a(:,:), b(:,:), c(:), d(:), work(:), &
                                          x(:)
!     .. Executable Statements ..
      Write (nout,*) 'F08ZAF Example Program Results'
      Write (nout,*)
!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) m, n, p
      lda = m
      ldb = p
      lwork = p + n + nb*(m+n)
      Allocate (a(lda,n),b(ldb,n),c(m),d(p),work(lwork),x(n))

!     Read A, B, C and D from data file

      Read (nin,*)(a(i,1:n),i=1,m)
      Read (nin,*)(b(i,1:n),i=1,p)
      Read (nin,*) c(1:m)
      Read (nin,*) d(1:p)

!     Solve the equality-constrained least squares problem

!     minimize ||c - A*x|| (in the 2-norm) subject to B*x = D

!     The NAG name equivalent of dgglse is f08zaf
      Call dgglse(m,n,p,a,lda,b,ldb,c,d,x,work,lwork,info)

!     Print least squares solution

      Write (nout,*) 'Constrained least squares solution'
      Write (nout,99999) x(1:n)

!     Compute the square root of the residual sum of squares

!     The NAG name equivalent of dnrm2 is f06ejf
      rnorm = dnrm2(m-n+p,c(n-p+1),1)
      Write (nout,*)
      Write (nout,*) 'Square root of the residual sum of squares'
      Write (nout,99998) rnorm

99999 Format (1X,7F11.4)
99998 Format (3X,1P,E11.2)
    End Program f08zafe


f08zbfe.f90

    Program f08zbfe

!     F08ZBF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: dggglm, dnrm2, nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nb = 64, nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: rnorm
      Integer                          :: i, info, lda, ldb, lwork, m, n, p
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: a(:,:), b(:,:), d(:), work(:), x(:), &
                                          y(:)
!     .. Executable Statements ..
      Write (nout,*) 'F08ZBF Example Program Results'
      Write (nout,*)
!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) m, n, p
      lda = m
      ldb = m
      lwork = n + m + nb*(m+p)
      Allocate (a(lda,n),b(ldb,p),d(m),work(lwork),x(n),y(p))

!     Read A, B and D from data file

      Read (nin,*)(a(i,1:n),i=1,m)
      Read (nin,*)(b(i,1:p),i=1,m)
      Read (nin,*) d(1:m)

!     Solve the weighted least squares problem

!     minimize ||inv(B)*(d - A*x)|| (in the 2-norm)

!     The NAG name equivalent of dggglm is f08zbf
      Call dggglm(m,n,p,a,lda,b,ldb,d,x,y,work,lwork,info)

!     Print least squares solution, x

      Write (nout,*) 'Weighted least squares solution'
      Write (nout,99999) x(1:n)

!     Print residual vector y = inv(B)*(d - A*x)

      Write (nout,*)
      Write (nout,*) 'Residual vector'
      Write (nout,99998) y(1:p)

!     Compute and print the square root of the residual sum of
!     squares

!     The NAG name equivalent of dnrm2 is f06ejf
      rnorm = dnrm2(p,y,1)

      Write (nout,*)
      Write (nout,*) 'Square root of the residual sum of squares'
      Write (nout,99998) rnorm

99999 Format (1X,7F11.4)
99998 Format (3X,1P,7E11.2)
    End Program f08zbfe


f08zefe.f90

    Program f08zefe

!     F08ZEF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: dgemv, dggqrf, dnrm2, dormqr, dormrq, dtrtrs,     &
                             nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Real (Kind=nag_wp), Parameter    :: one = 1.0E0_nag_wp
      Real (Kind=nag_wp), Parameter    :: zero = 0.0E0_nag_wp
      Integer, Parameter               :: nb = 64, nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: rnorm
      Integer                          :: i, info, lda, ldb, lwork, m, n, p
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: a(:,:), b(:,:), d(:), taua(:),       &
                                          taub(:), work(:), y(:)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: max, min
!     .. Executable Statements ..
      Write (nout,*) 'F08ZEF Example Program Results'
      Write (nout,*)
!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) n, m, p
      lda = n
      ldb = n
      lwork = nb*(m+p)
      Allocate (a(lda,m),b(ldb,p),d(n),taua(m),taub(m+p),work(lwork),y(p))

!     Read A, B and D from data file
      Read (nin,*)(a(i,1:m),i=1,n)
      Read (nin,*)(b(i,1:p),i=1,n)
      Read (nin,*) d(1:n)

!     Compute the generalized QR factorization of (A,B) as
!     A = Q*(R),   B = Q*(T11 T12)*Z
!            (0)          ( 0  T22)
!     The NAG name equivalent of dggqrf is f08zef
      Call dggqrf(n,m,p,a,lda,taua,b,ldb,taub,work,lwork,info)

!     Compute c = (c1) = (Q**T)*d, storing the result in D
!                  (c2)
!     The NAG name equivalent of dormqr is f08agf
      Call dormqr('Left','Transpose',n,1,m,a,lda,taua,d,n,work,lwork,info)

!     Putting Z*y = w = (w1), set w1 = 0, storing the result in Y1
!                        (w2)
      y(1:m+p-n) = zero

      If (n>m) Then

!       Copy c2 into Y2
        y(m+p-n+1:p) = d(m+1:n)

!       Solve T22*w2 = c2 for w2, storing result in Y2
!       The NAG name equivalent of dtrtrs is f07tef
        Call dtrtrs('Upper','No transpose','Non-unit',n-m,1,b(m+1,m+p-n+1),    &
          ldb,y(m+p-n+1),n-m,info)

        If (info>0) Then
          Write (nout,*)                                                       &
            'The upper triangular factor, T22, of B is singular, '
          Write (nout,*) 'the least squares solution could not be computed'
          Go To 100
        End If

!       Compute estimate of the square root of the residual sum of squares
!       norm(y) = norm(w2)

!       The NAG name equivalent of dnrm2 is f06ejf
        rnorm = dnrm2(n-m,y(m+p-n+1),1)

!       Form c1 - T12*w2 in D
!       The NAG name equivalent of dgemv is f06paf
        Call dgemv('No transpose',m,n-m,-one,b(1,m+p-n+1),ldb,y(m+p-n+1),1,    &
          one,d,1)
      End If

!     Solve R*x = c1 - T12*w2 for x
!     The NAG name equivalent of dtrtrs is f07tef
      Call dtrtrs('Upper','No transpose','Non-unit',m,1,a,lda,d,m,info)

      If (info>0) Then
        Write (nout,*) 'The upper triangular factor, R, of A is singular, '
        Write (nout,*) 'the least squares solution could not be computed'
      Else

!       Compute y = (Z**T)*w
!       The NAG name equivalent of dormrq is f08ckf
        Call dormrq('Left','Transpose',p,1,min(n,p),b(max(1,                   &
          n-p+1),1),ldb,taub,y,p,work,lwork,info)

!       Print least squares solution x

        Write (nout,*) 'Generalized least squares solution'
        Write (nout,99999) d(1:m)

!       Print residual vector y

        Write (nout,*)
        Write (nout,*) 'Residual vector'
        Write (nout,99998) y(1:p)

!       Print estimate of the square root of the residual sum of squares

        Write (nout,*)
        Write (nout,*) 'Square root of the residual sum of squares'
        Write (nout,99998) rnorm
      End If
100   Continue

99999 Format (1X,7F11.4)
99998 Format (3X,1P,7E11.2)
    End Program f08zefe


f08zffe.f90

    Program f08zffe

!     F08ZFF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: dgemv, dggrqf, dnrm2, dormqr, dormrq, dtrmv,      &
                             dtrtrs, nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Real (Kind=nag_wp), Parameter    :: one = 1.0E0_nag_wp
      Integer, Parameter               :: nb = 64, nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: rnorm
      Integer                          :: i, info, lda, ldb, lwork, m, n, p
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: a(:,:), b(:,:), c(:), d(:), taua(:), &
                                          taub(:), work(:), x(:)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: min
!     .. Executable Statements ..
      Write (nout,*) 'F08ZFF Example Program Results'
      Write (nout,*)
!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) m, n, p
      lda = m
      ldb = p
      lwork = nb*(p+n)
      Allocate (a(lda,n),b(ldb,n),c(m),d(p),taua(n),taub(n),work(lwork),x(n))

!     Read B, A, C and D from data file
      Read (nin,*)(a(i,1:n),i=1,m)
      Read (nin,*)(b(i,1:n),i=1,p)
      Read (nin,*) c(1:m)
      Read (nin,*) d(1:p)

!     Compute the generalized RQ factorization of (B,A) as
!     B = (0 T12)*Q,   A = Z*(R11 R12)*Q, where T12, R11
!                            ( 0  R22)
!     are upper triangular
!     The NAG name equivalent of dggrqf is f08zff
      Call dggrqf(p,m,n,b,ldb,taub,a,lda,taua,work,lwork,info)

!     Set Qx = y. The problem then reduces to:
!                 minimize (Ry - Z^Tc) subject to Ty = d
!     Update c = Z^T*c -> minimize (Ry-c)
!     The NAG name equivalent of dormqr is f08agf
      Call dormqr('Left','Transpose',m,1,min(m,n),a,lda,taua,c,m,work,lwork,   &
        info)

!     Putting y = (y1), solve T12*w = d for w, storing result in d
!                 (w )
!     The NAG name equivalent of dtrtrs is f07tef
      Call dtrtrs('Upper','No transpose','Non-unit',p,1,b(1,n-p+1),ldb,d,p,    &
        info)

      If (info>0) Then
        Write (nout,*) 'The upper triangular factor of B is singular, '
        Write (nout,*) 'the least squares solution could not be computed'
        Go To 100
      End If

!     From first n-p rows of (Ry-c) we have: R11*y1 + R12*w = c(1:n-p) = c1
!     Form c1 = c1 - R12*w = R11*y1
!     The NAG name equivalent of dgemv is f06raf
      Call dgemv('No transpose',n-p,p,-one,a(1,n-p+1),lda,d,1,one,c,1)

!     Solve R11*y1 = c1 for y1, storing result in c(1:n-p)
!     The NAG name equivalent of dtrtrs is f07tef
      Call dtrtrs('Upper','No transpose','Non-unit',n-p,1,a,lda,c,n-p,info)

      If (info>0) Then
        Write (nout,*) 'The upper triangular factor of A is singular, '
        Write (nout,*) 'the least squares solution could not be computed'
        Go To 100
      End If

!     Copy y into X (first y1, then w)
      x(1:n-p) = c(1:n-p)
      x(n-p+1:n) = d(1:p)

!     Compute x = (Q**T)*y
!     The NAG name equivalent of dormrq is f08ckf
      Call dormrq('Left','Transpose',n,1,p,b,ldb,taub,x,n,work,lwork,info)

!     The least squares solution is in x, the remainder here is to compute
!     the residual, which equals c2 - R22*w.

!     Upper triangular part of R22 first
!     The NAG name equivalent of dtrmv is f06pff
      Call dtrmv('Upper','No transpose','Non-unit',min(m,n)-n+p,               &
        a(n-p+1,n-p+1),lda,d,1)
      Do i = 1, min(m,n) - n + p
        c(n-p+i) = c(n-p+i) - d(i)
      End Do

      If (m<n) Then

!       Additional rectangular part of R22
!       The NAG name equivalent of dgemv is f06paf
        Call dgemv('No transpose',m-n+p,n-m,-one,a(n-p+1,m+1),lda,d(m-n+p+1),  &
          1,one,c(n-p+1),1)
      End If

!     Compute norm of residual sum of squares.
      rnorm = dnrm2(m-(n-p),c(n-p+1),1)

!     Print least squares solution x
      Write (nout,*) 'Constrained least squares solution'
      Write (nout,99999) x(1:n)

!     Print estimate of the square root of the residual sum of squares
      Write (nout,*)
      Write (nout,*) 'Square root of the residual sum of squares'
      Write (nout,99998) rnorm

100   Continue

99999 Format (1X,7F11.4)
99998 Format (3X,1P,E11.2)
    End Program f08zffe


f08znfe.f90

    Program f08znfe

!     F08ZNF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: dznrm2, nag_wp, zgglse
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nb = 64, nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: rnorm
      Integer                          :: i, info, lda, ldb, lwork, m, n, p
!     .. Local Arrays ..
      Complex (Kind=nag_wp), Allocatable :: a(:,:), b(:,:), c(:), d(:),        &
                                          work(:), x(:)
!     .. Executable Statements ..
      Write (nout,*) 'F08ZNF Example Program Results'
      Write (nout,*)
!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) m, n, p
      lda = m
      ldb = p
      lwork = p + n + nb*(m+n)
      Allocate (a(lda,n),b(ldb,n),c(m),d(p),work(lwork),x(n))

!     Read A, B, C and D from data file

      Read (nin,*)(a(i,1:n),i=1,m)
      Read (nin,*)(b(i,1:n),i=1,p)
      Read (nin,*) c(1:m)
      Read (nin,*) d(1:p)

!     Solve the equality-constrained least squares problem

!     minimize ||c - A*x|| (in the 2-norm) subject to B*x = D

!     The NAG name equivalent of zgglse is f08znf
      Call zgglse(m,n,p,a,lda,b,ldb,c,d,x,work,lwork,info)

!     Print least squares solution

      Write (nout,*) 'Constrained least squares solution'
      Write (nout,99999) x(1:n)

!     Compute the square root of the residual sum of squares

!     The NAG name equivalent of dznrm2 is f06jjf
      rnorm = dznrm2(m-n+p,c(n-p+1),1)
      Write (nout,*)
      Write (nout,*) 'Square root of the residual sum of squares'
      Write (nout,99998) rnorm

99999 Format (4(' (',F7.4,',',F7.4,')',:))
99998 Format (1X,1P,E10.2)
    End Program f08znfe


f08zpfe.f90

    Program f08zpfe

!     F08ZPF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: dznrm2, nag_wp, zggglm
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nb = 64, nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: rnorm
      Integer                          :: i, info, lda, ldb, lwork, m, n, p
!     .. Local Arrays ..
      Complex (Kind=nag_wp), Allocatable :: a(:,:), b(:,:), d(:), work(:),     &
                                          x(:), y(:)
!     .. Executable Statements ..
      Write (nout,*) 'F08ZPF Example Program Results'
      Write (nout,*)
!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) m, n, p
      lda = m
      ldb = m
      lwork = n + m + nb*(m+p)
      Allocate (a(lda,n),b(ldb,p),d(m),work(lwork),x(n),y(p))

!     Read A, B and D from data file

      Read (nin,*)(a(i,1:n),i=1,m)
      Read (nin,*)(b(i,1:p),i=1,m)
      Read (nin,*) d(1:m)

!     Solve the weighted least squares problem

!     minimize ||inv(B)*(d - A*x)|| (in the 2-norm)

!     The NAG name equivalent of zggglm is f08zpf
      Call zggglm(m,n,p,a,lda,b,ldb,d,x,y,work,lwork,info)

!     Print least squares solution

      Write (nout,*) 'Weighted least squares solution'
      Write (nout,99999) x(1:n)

!     Print residual vector y = inv(B)*(d - A*x)

      Write (nout,*)
      Write (nout,*) 'Residual vector'
      Write (nout,99998) y(1:p)

!     Compute and print the square root of the residual sum of squares
!     The NAG name equivalent of dznrm2 is f06jjf
      rnorm = dznrm2(p,y,1)

      Write (nout,*)
      Write (nout,*) 'Square root of the residual sum of squares'
      Write (nout,99997) rnorm

99999 Format (3(' (',F9.4,',',F9.4,')',:))
99998 Format (3(' (',1P,E9.2,',',1P,E9.2,')',:))
99997 Format (1X,1P,E10.2)
    End Program f08zpfe


f08zsfe.f90

    Program f08zsfe

!     F08ZSF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: dznrm2, nag_wp, zgemv, zggqrf, ztrtrs, zunmqr,    &
                             zunmrq
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Complex (Kind=nag_wp), Parameter :: one = (1.0E0_nag_wp,0.0E0_nag_wp)
      Complex (Kind=nag_wp), Parameter :: zero = (0.0E0_nag_wp,0.0E0_nag_wp)
      Integer, Parameter               :: nb = 64, nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: rnorm
      Integer                          :: i, info, lda, ldb, lwork, m, n, p
!     .. Local Arrays ..
      Complex (Kind=nag_wp), Allocatable :: a(:,:), b(:,:), d(:), taua(:),     &
                                          taub(:), work(:), y(:)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: max, min
!     .. Executable Statements ..
      Write (nout,*) 'F08ZSF Example Program Results'
      Write (nout,*)
!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) n, m, p
      lda = n
      ldb = n
      lwork = nb*(m+p)
      Allocate (a(lda,m),b(ldb,p),d(n),taua(m),taub(m+p),work(lwork),y(p))

!     Read A, B and D from data file
      Read (nin,*)(a(i,1:m),i=1,n)
      Read (nin,*)(b(i,1:p),i=1,n)
      Read (nin,*) d(1:n)

!     Compute the generalized QR factorization of (A,B) as
!     A = Q*(R),   B = Q*(T11 T12)*Z
!            (0)          ( 0  T22)
!     The NAG name equivalent of zggqrf is f08zsf
      Call zggqrf(n,m,p,a,lda,taua,b,ldb,taub,work,lwork,info)

!     Compute c = (c1) = (Q**H)*d, storing the result in D
!                  (c2)
!     The NAG name equivalent of zunmqr is f08auf
      Call zunmqr('Left','Conjugate transpose',n,1,m,a,lda,taua,d,n,work,      &
        lwork,info)

!     Putting Z*y = w = (w1), set w1 = 0, storing the result in Y1
!                        (w2)
      y(1:m+p-n) = zero

      If (n>m) Then

!       Copy c2 into Y2

        y(m+p-n+1:p) = d(m+1:n)

!       Solve T22*w2 = c2 for w2, storing result in Y2

!       The NAG name equivalent of ztrtrs is f07tsf
        Call ztrtrs('Upper','No transpose','Non-unit',n-m,1,b(m+1,m+p-n+1),    &
          ldb,y(m+p-n+1),n-m,info)

        If (info>0) Then
          Write (nout,*)                                                       &
            'The upper triangular factor, T22, of B is singular, '
          Write (nout,*) 'the least squares solution could not be computed'
          Go To 100
        End If

!       Compute estimate of the square root of the residual sum of
!       squares norm(y) = norm(w2)
!       The NAG name equivalent of dznrm2 is f06jjf
        rnorm = dznrm2(n-m,y(m+p-n+1),1)

!       Form c1 - T12*w2 in D
!       The NAG name equivalent of zgemv is f06saf
        Call zgemv('No transpose',m,n-m,-one,b(1,m+p-n+1),ldb,y(m+p-n+1),1,    &
          one,d,1)
      End If

!     Solve R*x = c1 - T12*w2 for x
!     The NAG name equivalent of ztrtrs is f07tsf
      Call ztrtrs('Upper','No transpose','Non-unit',m,1,a,lda,d,m,info)

      If (info>0) Then
        Write (nout,*) 'The upper triangular factor, R, of A is singular, '
        Write (nout,*) 'the least squares solution could not be computed'
      Else

!       Compute y = (Z**H)*w
!       The NAG name equivalent of zunmrq is f08cxf
        Call zunmrq('Left','Conjugate transpose',p,1,min(n,p),b(max(1,         &
          n-p+1),1),ldb,taub,y,p,work,lwork,info)

!       Print least squares solution x
        Write (nout,*) 'Generalized least squares solution'
        Write (nout,99999) d(1:m)

!       Print residual vector y
        Write (nout,*)
        Write (nout,*) 'Residual vector'
        Write (nout,99998) y(1:p)

!       Print estimate of the square root of the residual sum of
!       squares
        Write (nout,*)
        Write (nout,*) 'Square root of the residual sum of squares'
        Write (nout,99997) rnorm
      End If
100   Continue

99999 Format (3(' (',F9.4,',',F9.4,')',:))
99998 Format (3(' (',1P,E9.2,',',1P,E9.2,')',:))
99997 Format (1X,1P,E10.2)
    End Program f08zsfe


f08ztfe.f90

    Program f08ztfe

!     F08ZTF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: dznrm2, nag_wp, zgemv, zggrqf, ztrmv, ztrtrs,     &
                             zunmqr, zunmrq
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Complex (Kind=nag_wp), Parameter :: one = (1.0E0_nag_wp,0.0E0_nag_wp)
      Integer, Parameter               :: nb = 64, nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: rnorm
      Integer                          :: i, info, lda, ldb, lwork, m, n, p
!     .. Local Arrays ..
      Complex (Kind=nag_wp), Allocatable :: a(:,:), b(:,:), c(:), d(:),        &
                                          taua(:), taub(:), work(:), x(:)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: min
!     .. Executable Statements ..
      Write (nout,*) 'F08ZTF Example Program Results'
      Write (nout,*)
!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) m, n, p
      lda = m
      ldb = p
      lwork = nb*(p+n)
      Allocate (a(lda,n),b(ldb,n),c(m),d(p),taua(n),taub(n),work(lwork),x(n))

!     Read A, B, C and D from data file

      Read (nin,*)(a(i,1:n),i=1,m)
      Read (nin,*)(b(i,1:n),i=1,p)
      Read (nin,*) c(1:m)
      Read (nin,*) d(1:p)

!     Compute the generalized RQ factorization of (B,A) as
!     B = (0 T12)*Q,   A = Z*(R11 R12)*Q, where T12 and R11
!                            ( 0  R22)
!     are upper triangular
!     The NAG name equivalent of zggrqf is f08ztf
      Call zggrqf(p,m,n,b,ldb,taub,a,lda,taua,work,lwork,info)

!     Set Qx = y. The problem then reduces to:
!                 minimize (Ry - Z^Hc) subject to Ty = d
!     Update c = Z^H*c -> minimize (Ry-c)
!     The NAG name equivalent of zunmqr is f08auf
      Call zunmqr('Left','Conjugate transpose',m,1,min(m,n),a,lda,taua,c,m,    &
        work,lwork,info)

!     Putting y = (y1), solve T12*w = d for w, storing result in d
!                 (w )
!     The NAG name equivalent of ztrtrs is f07tsf
      Call ztrtrs('Upper','No transpose','Non-unit',p,1,b(1,n-p+1),ldb,d,p,    &
        info)

      If (info>0) Then
        Write (nout,*) 'The upper triangular factor of B is singular, '
        Write (nout,*) 'the least squares solution could not be computed'
        Go To 100
      End If

!     From first n-p rows of (Ry-c) we have
!     R11*y1 + R12*w = c(1:n-p) = c1
!     Form c1 = c1 - R12*w = R11*y1

!     The NAG name equivalent of zgemv is f06saf
      Call zgemv('No transpose',n-p,p,-one,a(1,n-p+1),lda,d,1,one,c,1)

!     Solve R11*y1 = c1 for y1, storing result in c(1:n-p)
!     The NAG name equivalent of ztrtrs is f07tsf
      Call ztrtrs('Upper','No transpose','Non-unit',n-p,1,a,lda,c,n-p,info)

      If (info>0) Then
        Write (nout,*) 'The upper triangular factor of A is singular, '
        Write (nout,*) 'the least squares solution could not be computed'
        Go To 100
      End If

!     Copy y into x (first y1, then w)
      x(1:n-p) = c(1:n-p)
      x(n-p+1:n) = d(1:p)

!     Compute x = (Q**H)*y
!     The NAG name equivalent of zunmrq is f08cxf
      Call zunmrq('Left','Conjugate transpose',n,1,p,b,ldb,taub,x,n,work,      &
        lwork,info)

!     The least squares solution is in x, the remainder here is to compute
!     the residual, which equals c2 - R22*w.

!     Upper triangular part of R22 first
!     The NAG name equivalent of ztrmv is f06sff
      Call ztrmv('Upper','No transpose','Non-unit',min(m,n)-n+p,               &
        a(n-p+1,n-p+1),lda,d,1)
      Do i = 1, min(m,n) - n + p
        c(n-p+i) = c(n-p+i) - d(i)
      End Do

      If (m<n) Then

!       Additional rectangular part of R22
!       The NAG name equivalent of zgemv is f06saf
        Call zgemv('No transpose',m-n+p,n-m,-one,a(n-p+1,m+1),lda,d(m-n+p+1),  &
          1,one,c(n-p+1),1)

      End If

!     Compute norm of residual sum of squares.
!     The NAG name equivalent of dznrm2 is f06jjf
      rnorm = dznrm2(m-(n-p),c(n-p+1),1)

!     Print least squares solution x
      Write (nout,*) 'Constrained least squares solution'
      Write (nout,99999) x(1:n)

!     Print estimate of the square root of the residual sum of
!     squares
      Write (nout,*)
      Write (nout,*) 'Square root of the residual sum of squares'
      Write (nout,99998) rnorm

100   Continue

99999 Format (4(' (',F7.4,',',F7.4,')',:))
99998 Format (1X,1P,E10.2)
    End Program f08ztfe


f11bdfe.f90

    Program f11bdfe

!     F11BDF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: f11bdf, f11bef, f11bff, f11daf, f11dbf, f11xaf,   &
                             nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: anorm, dtol, sigmax, stplhs, stprhs, &
                                          tol
      Integer                          :: i, ifail, ifail1, irevcm, iterm,     &
                                          itn, la, lfill, liwork, lwork,       &
                                          lwreq, m, maxitn, monit, n, nnz,     &
                                          nnzc, npivm
      Character (8)                    :: method
      Character (1)                    :: milu, norm, precon, pstrat, weight
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: a(:), b(:), wgt(:), work(:), x(:)
      Integer, Allocatable             :: icol(:), idiag(:), ipivp(:),         &
                                          ipivq(:), irow(:), istr(:), iwork(:)
!     .. Executable Statements ..
      Write (nout,*) 'F11BDF Example Program Results'

!     Skip heading in data file

      Read (nin,*)
      Read (nin,*) n
      Read (nin,*) nnz
      la = 3*nnz
      liwork = 7*n + 2
      lwork = 200
      Allocate (a(la),b(n),wgt(n),work(lwork),x(n),icol(la),idiag(n),ipivp(n), &
        ipivq(n),irow(la),istr(n+1),iwork(liwork))

!     Read or initialize the parameters for the iterative solver

      Read (nin,*) method
      Read (nin,*) precon, norm, weight, iterm
      Read (nin,*) m, tol, maxitn
      Read (nin,*) monit
      anorm = 0.0E0_nag_wp
      sigmax = 0.0E0_nag_wp

!     Read the parameters for the preconditioner

      Read (nin,*) lfill, dtol
      Read (nin,*) milu, pstrat

!     Read the nonzero elements of the matrix A

      Do i = 1, nnz
        Read (nin,*) a(i), irow(i), icol(i)
      End Do

!     Read right-hand side vector b and initial approximate solution

      Read (nin,*) b(1:n)
      Read (nin,*) x(1:n)

!     Calculate incomplete LU factorization

      milu = 'N'

!     ifail: behaviour on error exit
!             =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
      ifail = 0
      Call f11daf(n,nnz,a,la,irow,icol,lfill,dtol,pstrat,milu,ipivp,ipivq,     &
        istr,idiag,nnzc,npivm,iwork,liwork,ifail)

!     Call F11BDF to initialize the solver

      ifail = 0
      Call f11bdf(method,precon,norm,weight,iterm,n,m,tol,maxitn,anorm,sigmax, &
        monit,lwreq,work,lwork,ifail)

!     Call repeatedly F11BEF to solve the equations
!     Note that the arrays B and X are overwritten

!     On final exit, X will contain the solution and B the
!     residual vector

      irevcm = 0
      lwreq = lwork

      ifail = 1
loop: Do
        Call f11bef(irevcm,x,b,wgt,work,lwreq,ifail)

        If (irevcm/=4) Then
          ifail1 = -1
          Select Case (irevcm)
          Case (-1)

            Call f11xaf('Transpose',n,nnz,a,irow,icol,'No checking',x,b,       &
              ifail1)

          Case (1)

            Call f11xaf('No transpose',n,nnz,a,irow,icol,'No checking',x,b,    &
              ifail1)

          Case (2)

            Call f11dbf('No transpose',n,a,la,irow,icol,ipivp,ipivq,istr,      &
              idiag,'No checking',x,b,ifail1)

          Case (3)

            ifail1 = 0
            Call f11bff(itn,stplhs,stprhs,anorm,sigmax,work,lwreq,ifail1)

            Write (nout,99999) itn, stplhs
            Write (nout,99998)
            Write (nout,99997)(x(i),b(i),i=1,n)
          End Select
          If (ifail1/=0) Then
            irevcm = 6
          End If
        Else If (ifail/=0) Then
          Write (nout,99993) ifail
          Go To 100
        Else
          Exit loop
        End If
      End Do loop

!     Obtain information about the computation

      ifail1 = 0
      Call f11bff(itn,stplhs,stprhs,anorm,sigmax,work,lwreq,ifail1)

!     Print the output data

      Write (nout,99996)
      Write (nout,99995) 'Number of iterations for convergence:    ', itn
      Write (nout,99994) 'Residual norm:                           ', stplhs
      Write (nout,99994) 'Right-hand side of termination criterion:', stprhs
      Write (nout,99994) '1-norm of matrix A:                      ', anorm

!     Output x

      Write (nout,99998)
      Write (nout,99997)(x(i),b(i),i=1,n)
100   Continue

99999 Format (/,1X,'Monitoring at iteration no.',I4,/,1X,1P,'residual no',     &
        'rm: ',E14.4)
99998 Format (/,2X,'  Solution vector',2X,' Residual vector')
99997 Format (1X,1P,E16.4,1X,E16.4)
99996 Format (/,1X,'Final Results')
99995 Format (1X,A,I4)
99994 Format (1X,A,1P,E14.4)
99993 Format (1X,/,1X,' ** F11BEF returned with IFAIL = ',I5)
    End Program f11bdfe


f11brfe.f90

    Program f11brfe

!     F11BRF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: f11brf, f11bsf, f11btf, f11dnf, f11dpf, f11xnf,   &
                             nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: anorm, dtol, sigmax, stplhs, stprhs, &
                                          tol
      Integer                          :: i, ifail, ifail1, irevcm, iterm,     &
                                          itn, la, lfill, liwork, lwork,       &
                                          lwreq, m, maxitn, monit, n, nnz,     &
                                          nnzc, npivm
      Character (8)                    :: method
      Character (1)                    :: milu, norm, precon, pstrat, weight
!     .. Local Arrays ..
      Complex (Kind=nag_wp), Allocatable :: a(:), b(:), work(:), x(:)
      Real (Kind=nag_wp), Allocatable  :: wgt(:)
      Integer, Allocatable             :: icol(:), idiag(:), ipivp(:),         &
                                          ipivq(:), irow(:), istr(:), iwork(:)
!     .. Executable Statements ..
      Write (nout,*) 'F11BRF Example Program Results'

!     Skip heading in data file

      Read (nin,*)
      Read (nin,*) n
      Read (nin,*) nnz
      la = 2*nnz
      liwork = 7*n + 2
      lwork = 200
      Allocate (a(la),b(n),work(lwork),x(n),wgt(n),icol(la),idiag(n),ipivp(n), &
        ipivq(n),irow(la),istr(n+1),iwork(liwork))

!     Read or initialize the parameters for the iterative solver

      Read (nin,*) method
      Read (nin,*) precon, norm, weight, iterm
      Read (nin,*) m, tol, maxitn
      Read (nin,*) monit
      anorm = 0.0E0_nag_wp
      sigmax = 0.0E0_nag_wp

!     Read the parameters for the preconditioner

      Read (nin,*) lfill, dtol
      Read (nin,*) milu, pstrat

!     Read the nonzero elements of the matrix A

      Do i = 1, nnz
        Read (nin,*) a(i), irow(i), icol(i)
      End Do

!     Read right-hand side vector b and initial approximate
!     solution x

      Read (nin,*) b(1:n)
      Read (nin,*) x(1:n)

!     Calculate incomplete LU factorization

!     ifail: behaviour on error exit
!             =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
      ifail = 0
      Call f11dnf(n,nnz,a,la,irow,icol,lfill,dtol,pstrat,milu,ipivp,ipivq,     &
        istr,idiag,nnzc,npivm,iwork,liwork,ifail)

!     Call F11BRF to initialize the solver

      ifail = 0
      Call f11brf(method,precon,norm,weight,iterm,n,m,tol,maxitn,anorm,sigmax, &
        monit,lwreq,work,lwork,ifail)

!     Call repeatedly F11BSF to solve the equations
!     Note that the arrays B and X are overwritten

!     On final exit, X will contain the solution and B the residual
!     vector

      irevcm = 0
      lwreq = lwork

      ifail = 1
loop: Do
        Call f11bsf(irevcm,x,b,wgt,work,lwreq,ifail)

        If (irevcm/=4) Then
          ifail1 = -1
          Select Case (irevcm)
          Case (-1)

            Call f11xnf('Transpose',n,nnz,a,irow,icol,'No checking',x,b,       &
              ifail1)

          Case (1)

            Call f11xnf('No transpose',n,nnz,a,irow,icol,'No checking',x,b,    &
              ifail1)

          Case (2)

            Call f11dpf('No transpose',n,a,la,irow,icol,ipivp,ipivq,istr,      &
              idiag,'No checking',x,b,ifail1)

          Case (3)

            ifail1 = 0
            Call f11btf(itn,stplhs,stprhs,anorm,sigmax,work,lwreq,ifail1)

            Write (nout,99999) itn, stplhs
            Write (nout,99998)
            Write (nout,99996) x(1:n)
            Write (nout,99997)
            Write (nout,99996) b(1:n)

          End Select
          If (ifail1/=0) Then
            irevcm = 6
          End If
        Else If (ifail/=0) Then
          Write (nout,99992) ifail
          Go To 100
        Else
          Exit loop
        End If
      End Do loop

!     Obtain information about the computation

      ifail1 = 0
      Call f11btf(itn,stplhs,stprhs,anorm,sigmax,work,lwreq,ifail1)

!     Print the output data

      Write (nout,99995)
      Write (nout,99994) 'Number of iterations for convergence:    ', itn
      Write (nout,99993) 'Residual norm:                           ', stplhs
      Write (nout,99993) 'Right-hand side of termination criterion:', stprhs
      Write (nout,99993) '1-norm of matrix A:                      ', anorm

!     Output x

      Write (nout,99998)
      Write (nout,99996) x(1:n)
      Write (nout,99997)
      Write (nout,99996) b(1:n)
100   Continue

99999 Format (/,1X,'Monitoring at iteration no.',I4,/,1X,1P,'residual no',     &
        'rm: ',E14.4)
99998 Format (/,2X,'  Solution vector')
99997 Format (/,2X,'  Residual vector')
99996 Format (1X,'(',1P,E16.4,',',1P,E16.4,')')
99995 Format (/,1X,'Final Results')
99994 Format (1X,A,I4)
99993 Format (1X,A,1P,E14.4)
99992 Format (1X,/,1X,' ** F11BSF returned with IFAIL = ',I5)
    End Program f11brfe


f11dafe.f90

    Program f11dafe

!     F11DAF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: f11daf, nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: dtol
      Integer                          :: i, ifail, la, lfill, liwork, n, nnz, &
                                          nnzc, npivm
      Character (1)                    :: milu, pstrat
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: a(:)
      Integer, Allocatable             :: icol(:), idiag(:), ipivp(:),         &
                                          ipivq(:), irow(:), istr(:), iwork(:)
!     .. Executable Statements ..
      Write (nout,*) 'F11DAF Example Program Results'
      Write (nout,*)

!     Skip heading in data file

      Read (nin,*)

!     Read algorithmic parameters

      Read (nin,*) n
      Read (nin,*) nnz

      la = 2*nnz
      liwork = 7*n + 2

      Allocate (a(la),icol(la),idiag(n),ipivp(n),ipivq(n),irow(la),istr(n+1),  &
        iwork(liwork))
      Read (nin,*) lfill, dtol
      Read (nin,*) pstrat
      Read (nin,*) milu

!     Read the matrix A

      Do i = 1, nnz
        Read (nin,*) a(i), irow(i), icol(i)
      End Do

!     Calculate incomplete LU factorization

!     ifail: behaviour on error exit
!             =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
      ifail = 0
      Call f11daf(n,nnz,a,la,irow,icol,lfill,dtol,pstrat,milu,ipivp,ipivq,     &
        istr,idiag,nnzc,npivm,iwork,liwork,ifail)

!     Output original matrix

      Write (nout,*) ' Original Matrix'
      Write (nout,'(A,I4)') ' N     =', n
      Write (nout,'(A,I4)') ' NNZ   =', nnz
      Do i = 1, nnz
        Write (nout,'(I8,E16.4,2I8)') i, a(i), irow(i), icol(i)
      End Do
      Write (nout,*)

!     Output details of the factorization

      Write (nout,*) ' Factorization'
      Write (nout,'(A,I4)') ' N     =', n
      Write (nout,'(A,I4)') ' NNZ   =', nnzc
      Write (nout,'(A,I4)') ' NPIVM =', npivm
      Do i = nnz + 1, nnz + nnzc
        Write (nout,'(I8,E16.4,2I8)') i, a(i), irow(i), icol(i)
      End Do
      Write (nout,*)

      Write (nout,*) '        I       IPIVP(I)  IPIVQ(I)'
      Do i = 1, n
        Write (nout,'(3I10)') i, ipivp(i), ipivq(i)
      End Do

    End Program f11dafe


f11dbfe.f90

    Program f11dbfe

!     F11DBF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: f11daf, f11dbf, nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: dtol
      Integer                          :: i, ifail, la, lfill, liwork, n, nnz, &
                                          nnzc, npivm
      Character (1)                    :: check, milu, pstrat, trans
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: a(:), x(:), y(:)
      Integer, Allocatable             :: icol(:), idiag(:), ipivp(:),         &
                                          ipivq(:), irow(:), istr(:), iwork(:)
!     .. Executable Statements ..
      Write (nout,*) 'F11DBF Example Program Results'
      Write (nout,*)

!     Skip heading in data file

      Read (nin,*)

!     Read order of matrix and number of nonzero entries

      Read (nin,*) n
      Read (nin,*) nnz
      la = 2*nnz
      liwork = 7*n + 2
      Allocate (a(la),x(n),y(n),icol(la),idiag(n),ipivp(n),ipivq(n),irow(la),  &
        istr(n+1),iwork(liwork))

!     Read the matrix A

      Do i = 1, nnz
        Read (nin,*) a(i), irow(i), icol(i)
      End Do

!     Read the vector y

      Read (nin,*) y(1:n)

!     Calculate LU factorization

      lfill = -1
      dtol = 0.E0_nag_wp
      pstrat = 'C'
      milu = 'N'

!     ifail: behaviour on error exit
!             =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
      ifail = 0
      Call f11daf(n,nnz,a,la,irow,icol,lfill,dtol,pstrat,milu,ipivp,ipivq,     &
        istr,idiag,nnzc,npivm,iwork,liwork,ifail)

!     Check value of npivm

      If (npivm>0) Then

        Write (nout,*) 'Factorization is not complete'

      Else

!       Solve P L D U x = y

        trans = 'N'
        check = 'C'

        ifail = 0
        Call f11dbf(trans,n,a,la,irow,icol,ipivp,ipivq,istr,idiag,check,y,x,   &
          ifail)

!       Output results

        Write (nout,*) ' Solution of linear system'
        Write (nout,'(E16.4)') x(1:n)

      End If

    End Program f11dbfe


f11dcfe.f90

    Program f11dcfe

!     F11DCF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: f11daf, f11dcf, nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: dtol, rnorm, tol
      Integer                          :: i, ifail, itn, la, lfill, liwork,    &
                                          lwork, m, maxitn, n, nnz, nnzc,      &
                                          npivm
      Character (8)                    :: method
      Character (1)                    :: milu, pstrat
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: a(:), b(:), work(:), x(:)
      Integer, Allocatable             :: icol(:), idiag(:), ipivp(:),         &
                                          ipivq(:), irow(:), istr(:), iwork(:)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: max
!     .. Executable Statements ..
      Write (nout,*) 'F11DCF Example Program Results'
      Write (nout,*)
!     Skip heading in data file
      Read (nin,*)

!     Read algorithmic parameters

      Read (nin,*) n, m
      Read (nin,*) nnz
      la = 3*nnz
      liwork = 7*n + 2
      lwork = max(4*n+m*(m+n+5)+101,8*n+100,2*n*(m+3)+m*(m+2)+100,11*n+100)
      Allocate (a(la),b(n),work(lwork),x(n),icol(la),idiag(n),ipivp(n),        &
        ipivq(n),irow(la),istr(n+1),iwork(liwork))
      Read (nin,*) method
      Read (nin,*) lfill, dtol
      Read (nin,*) pstrat
      Read (nin,*) milu
      Read (nin,*) tol, maxitn

!     Read the matrix A

      Do i = 1, nnz
        Read (nin,*) a(i), irow(i), icol(i)
      End Do

!     Read right-hand side vector b and initial approximate solution x

      Read (nin,*) b(1:n)
      Read (nin,*) x(1:n)

!     Calculate incomplete LU factorization

!     ifail: behaviour on error exit
!             =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
      ifail = 0
      Call f11daf(n,nnz,a,la,irow,icol,lfill,dtol,pstrat,milu,ipivp,ipivq,     &
        istr,idiag,nnzc,npivm,iwork,liwork,ifail)

!     Solve Ax = b using F11DCF

      ifail = 0
      Call f11dcf(method,n,nnz,a,la,irow,icol,ipivp,ipivq,istr,idiag,b,m,tol,  &
        maxitn,x,rnorm,itn,work,lwork,ifail)

      Write (nout,99999) itn
      If (rnorm<tol) Then
        Write (nout,99996) tol
      Else
        Write (nout,99998) rnorm
      End If
      Write (nout,*)

!     Output solution, x

      Write (nout,*) '       Solution'
      Write (nout,99997) x(1:n)

99999 Format (1X,' Converged in',I4,' iterations')
99998 Format (1X,' Final residual norm =',1P,E15.2)
99997 Format (1X,1P,E16.3)
99996 Format (1X,' Final residual norm < tolerance (',1P,E10.3,')')
    End Program f11dcfe


f11ddfe.f90

    Program f11ddfe

!     F11DDF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: f11bdf, f11bef, f11bff, f11ddf, f11xaf, nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: anorm, omega, sigmax, stplhs,        &
                                          stprhs, tol
      Integer                          :: i, ifail, irevcm, iterm, itn, la,    &
                                          liwork, lwneed, lwork, m, maxitn,    &
                                          monit, n, nnz
      Character (1)                    :: ckddf, ckxaf, norm, precon, trans,   &
                                          weight
      Character (8)                    :: method
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: a(:), b(:), rdiag(:), wgt(:),        &
                                          work(:), x(:)
      Integer, Allocatable             :: icol(:), irow(:), iwork(:)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: max
!     .. Executable Statements ..
      Write (nout,*) 'F11DDF Example Program Results'
      Write (nout,*)
!     Skip heading in data file
      Read (nin,*)

!     Read algorithmic parameters
      Read (nin,*) n, m
      Read (nin,*) nnz
      la = 3*nnz
      lwork = max(n*(m+3)+m*(m+5)+101,7*n+100,(2*n+m)*(m+2)+n+100,10*n+100)
      liwork = 2*n + 1
      Allocate (a(la),b(n),rdiag(n),wgt(n),work(lwork),x(n),icol(la),irow(la), &
        iwork(liwork))
      Read (nin,*) method
      Read (nin,*) precon, norm, iterm
      Read (nin,*) tol, maxitn
      Read (nin,*) anorm, sigmax
      Read (nin,*) omega

!     Read the matrix A

      Do i = 1, nnz
        Read (nin,*) a(i), irow(i), icol(i)
      End Do

!     Read right-hand side vector b and initial approximate solution x

      Read (nin,*) b(1:n)
      Read (nin,*) x(1:n)

!     Call F11BDF to initialize solver

      weight = 'N'
      monit = 0

!     ifail: behaviour on error exit
!             =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
      ifail = 0
      Call f11bdf(method,precon,norm,weight,iterm,n,m,tol,maxitn,anorm,sigmax, &
        monit,lwneed,work,lwork,ifail)

!     Calculate reciprocal diagonal matrix elements if necessary

      If (precon=='P' .Or. precon=='p') Then

        iwork(1:n) = 0

        Do i = 1, nnz
          If (irow(i)==icol(i)) Then
            iwork(irow(i)) = iwork(irow(i)) + 1
            If (a(i)/=0.E0_nag_wp) Then
              rdiag(irow(i)) = 1.E0_nag_wp/a(i)
            Else
              Write (nout,*) 'Matrix has a zero diagonal element'
              Go To 100
            End If
          End If
        End Do

        Do i = 1, n
          If (iwork(i)==0) Then
            Write (nout,*) 'Matrix has a missing diagonal element'
            Go To 100
          End If
          If (iwork(i)>=2) Then
            Write (nout,*) 'Matrix has a multiple diagonal element'
            Go To 100
          End If
        End Do

      End If

!     Call F11BEF to solve the linear system

      irevcm = 0
      ckxaf = 'C'
      ckddf = 'C'

loop: Do
        ifail = 0
        Call f11bef(irevcm,x,b,wgt,work,lwork,ifail)

        Select Case (irevcm)
        Case (1)
!         Compute matrix-vector product
          trans = 'N'

          Call f11xaf(trans,n,nnz,a,irow,icol,ckxaf,x,b,ifail)

          ckxaf = 'N'
        Case (-1)
!         Compute transposed matrix-vector product
          trans = 'T'

          Call f11xaf(trans,n,nnz,a,irow,icol,ckxaf,x,b,ifail)

          ckxaf = 'N'
        Case (2)

!         SSOR preconditioning
          trans = 'N'

          Call f11ddf(trans,n,nnz,a,irow,icol,rdiag,omega,ckddf,x,b,iwork,     &
            ifail)

          ckddf = 'N'
        Case (4)
!         Termination

          ifail = 0
          Call f11bff(itn,stplhs,stprhs,anorm,sigmax,work,lwork,ifail)

          Write (nout,'(A,I10,A)') ' Converged in', itn, ' iterations'
          Write (nout,'(A,1P,E16.3)') ' Matrix norm =', anorm
          Write (nout,'(A,1P,E16.3)') ' Final residual norm =', stplhs
          Write (nout,*)

!         Output x
          Write (nout,*) '           X'
          Write (nout,'(1X,1P,E16.4)') x(1:n)
          Exit loop
        Case Default
          Exit loop
        End Select
      End Do loop

100   Continue

    End Program f11ddfe


f11defe.f90

    Program f11defe

!     F11DEF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: f11def, nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: omega, rnorm, tol
      Integer                          :: i, ifail, itn, l, lwork, m, maxitn,  &
                                          n, nnz
      Character (8)                    :: method
      Character (1)                    :: precon
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: a(:), b(:), work(:), x(:)
      Integer, Allocatable             :: icol(:), irow(:), iwork(:)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: max
!     .. Executable Statements ..
      Write (nout,*) 'F11DEF Example Program Results'
      Write (nout,*)
!     Skip heading in data file
      Read (nin,*)

!     Read algorithmic parameters
      Read (nin,*) n, m
      Read (nin,*) nnz
      Read (nin,*) method, precon
      l = n
      If (precon=='N' .Or. precon=='n') Then
        l = 0
      End If
      lwork = max(4*n+m*(m+n+5)+l+101,8*n+l+100,2*n*(m+3)+m*(m+2)+l+100,       &
        11*n+l+100)

      Allocate (a(nnz),b(n),work(lwork),x(n),icol(nnz),irow(nnz),iwork(2*n+1))
      Read (nin,*) omega
      Read (nin,*) tol, maxitn

!     Read the matrix A

      Do i = 1, nnz
        Read (nin,*) a(i), irow(i), icol(i)
      End Do

!     Read right-hand side vector b and initial approximate solution x

      Read (nin,*) b(1:n)
      Read (nin,*) x(1:n)

!     Solve Ax = b using F11DEF

!     ifail: behaviour on error exit
!             =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
      ifail = 0
      Call f11def(method,precon,n,nnz,a,irow,icol,omega,b,m,tol,maxitn,x,      &
        rnorm,itn,work,lwork,iwork,ifail)

      Write (nout,'(A,I10,A)') ' Converged in', itn, ' iterations'
      Write (nout,'(A,1P,E16.3)') ' Final residual norm =', rnorm
      Write (nout,*)

!     Output x

      Write (nout,*) '           X'
      Write (nout,'(1X,1P,E16.4)') x(1:n)

    End Program f11defe


f11dffe.f90

!   F11DFF Example Program Text
!   Mark 26 Release. NAG Copyright 2016.

    Program f11dffe

!     .. Use Statements ..
      Use nag_library, Only: f11dff, nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: dtolg
      Integer                          :: i, ifail, k, la, lfillg, lindb,      &
                                          liwork, mb, n, nb, nnz, nnzc, nover
      Character (1)                    :: milug, pstrag
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: a(:), b(:), dtol(:)
      Integer, Allocatable             :: icol(:), idiag(:), indb(:),          &
                                          ipivp(:), ipivq(:), irow(:),         &
                                          istb(:), istr(:), iwork(:),          &
                                          lfill(:), npivm(:)
      Character (1), Allocatable       :: milu(:), pstrat(:)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: maxval, minval
!     .. Executable Statements ..
      Continue

!     Print example header
      Write (nout,*) 'F11DFF Example Program Results'
      Write (nout,*)

!     Skip heading in data file
      Read (nin,*)

!     Get the matrix order and number of nonzero entries.
      Read (nin,*) n
      Read (nin,*) nnz

!     Allocate arrays with lengths based on n and nnz.
      liwork = 9*n + 3
      Allocate (b(n),iwork(liwork))

      la = 20*nnz
      Allocate (a(la),irow(la),icol(la))

      lindb = 3*n
      Allocate (idiag(lindb),indb(lindb),ipivp(lindb),ipivq(lindb),            &
        istr(lindb+1))

!     Read the matrix A
      Read (nin,*)(a(i),irow(i),icol(i),i=1,nnz)

!     Read algorithmic parameters
      Read (nin,*) lfillg, dtolg
      Read (nin,*) pstrag
      Read (nin,*) milug
      Read (nin,*) nb, nover

!     Allocate arrays with length based on number of blocks.
      Allocate (dtol(nb),istb(nb+1),lfill(nb),npivm(nb),milu(nb),pstrat(nb))

!     Define diagonal block indices.
!     In this example use blocks of MB consecutive rows and initialize
!     assuming no overlap.
      mb = (n+nb-1)/nb
      Do k = 1, nb
        istb(k) = (k-1)*mb + 1
      End Do
      istb(nb+1) = n + 1
      Do i = 1, n
        indb(i) = i
      End Do

!     Modify INDB and ISTB to account for overlap.
      Call f11dffe_overlap(n,nnz,la,irow,icol,nb,istb,indb,lindb,nover,iwork)
      If (iwork(1)==-999) Then
        Write (nout,*) '** LINDB too small, LINDB = ', lindb, '.'
        Go To 100
      End If

!     Output matrix and blocking details
      Write (nout,*) ' Original Matrix'
      Write (nout,99997) ' N     =', n
      Write (nout,99997) ' NNZ   =', nnz
      Write (nout,99997) ' NB    =', nb
      Do k = 1, nb
        Write (nout,99993) ' Block ', k, ': order = ', istb(k+1) - istb(k),    &
          ', start row = ', minval(indb(istb(k):istb(k+1)-1))
      End Do

!     Set algorithmic parameters for each block from global values
      lfill(1:nb) = lfillg
      dtol(1:nb) = dtolg
      pstrat(1:nb) = pstrag
      milu(1:nb) = milug

!     Calculate factorization
      ifail = 1
      Call f11dff(n,nnz,a,la,irow,icol,nb,istb,indb,lindb,lfill,dtol,pstrat,   &
        milu,ipivp,ipivq,istr,idiag,nnzc,npivm,iwork,liwork,ifail)
      If (ifail/=0) Then
        Write (nout,99995) ifail
        Go To 100
      End If

!     Output details of the factorization
      Write (nout,99996) ' Factorization'
      Write (nout,99997) '  NNZC  =', nnzc

      Write (nout,99996) ' Elements of factorization'
      Write (nout,99996) '        I   J        C(I,J)     Index'
      Do k = 1, nb
        Write (nout,99994) ' C_', k, ' --------------------------------'
!       Elements of the k-th block
        Do i = istr(istb(k)), istr(istb(k+1)) - 1
          Write (nout,99992) irow(i), icol(i), a(i), i
        End Do
      End Do

      Write (nout,99996) ' Details of factorized blocks'
      If (maxval(npivm(1:nb))>0) Then
!       Including pivoting details.
        Write (nout,99996)                                                     &
          '  K   I      ISTR(I)  IDIAG(I)   INDB(I)  IPIVP(I)  IPIVQ(I)'
        Do k = 1, nb
          i = istb(k)
          Write (nout,99999) k, i, istr(i), idiag(i), indb(i), ipivp(i),       &
            ipivq(i)
          Do i = istb(k) + 1, istb(k+1) - 1
            Write (nout,99998) i, istr(i), idiag(i), indb(i), ipivp(i),        &
              ipivq(i)
          End Do
          Write (nout,*)                                                       &
            ' -----------------------------------------------------'
        End Do
      Else
!       No pivoting on any block.
        Write (nout,99996) '  K   I      ISTR(I)  IDIAG(I)   INDB(I)'
        Do k = 1, nb
          i = istb(k)
          Write (nout,99999) k, i, istr(i), idiag(i), indb(i)
          Do i = istb(k) + 1, istb(k+1) - 1
            Write (nout,99998) i, istr(i), idiag(i), indb(i)
          End Do
          Write (nout,*) ' ------------------------------------'
        End Do
      End If

100   Continue

99999 Format (1X,I3,1X,I3,5(I10))
99998 Format (1X,I7,5(I10))
99997 Format (1X,A,I4)
99996 Format (1X,/,1X,A)
99995 Format (1X,/,1X,' ** F11DFF returned with IFAIL = ',I5)
99994 Format (1X,A3,I1,A)
99993 Format (1X,A,I3,A,I3,A,I3)
99992 Format (6X,2I4,E16.5,I8)

    Contains

      Subroutine f11dffe_overlap(n,nnz,la,irow,icol,nb,istb,indb,lindb,nover,  &
        iwork)

!       Purpose
!       =======
!       This routine takes a set of row indices INDB defining the diagonal
!       blocks to be used in F11DFF to define a block Jacobi or additive
!       Schwarz preconditioner, and expands them to allow for NOVER levels of
!       overlap.
!       The pointer array ISTB is also updated accordingly, so that the
!       returned values of ISTB and INDB can be passed to F11DFF to define
!       overlapping diagonal blocks.
!       ----------------------------------------------------------------------

!       .. Implicit None Statement ..
        Implicit None
!       .. Scalar Arguments ..
        Integer, Intent (In)           :: la, lindb, n, nb, nnz, nover
!       .. Array Arguments ..
        Integer, Intent (In)           :: icol(la), irow(la)
        Integer, Intent (Inout)        :: indb(lindb), istb(nb+1)
        Integer, Intent (Out)          :: iwork(3*n+1)
!       .. Local Scalars ..
        Integer                        :: i, ik, ind, iover, k, l, n21, nadd,  &
                                          row
!       .. Executable Statements ..
        Continue

!       Find the number of nonzero elements in each row of the matrix A, and
!       and start address of each row. Store the start addresses in
!       IWORK(N+1,...,2*N+1).

        iwork(1:n) = 0
        Do k = 1, nnz
          iwork(irow(k)) = iwork(irow(k)) + 1
        End Do
        iwork(n+1) = 1
        Do i = 1, n
          iwork(n+i+1) = iwork(n+i) + iwork(i)
        End Do

!       Loop over blocks.
blocks: Do k = 1, nb

!         Initialize marker array.
          iwork(1:n) = 0

!         Mark the rows already in block K in the workspace array.
          Do l = istb(k), istb(k+1) - 1
            iwork(indb(l)) = 1
          End Do

!         Loop over levels of overlap.
          Do iover = 1, nover

!           Initialize counter of new row indices to be added.
            ind = 0

!           Loop over the rows currently in the diagonal block.
            Do l = istb(k), istb(k+1) - 1
              row = indb(l)

!             Loop over nonzero elements in row ROW.
              Do i = iwork(n+row), iwork(n+row+1) - 1

!               If the column index of the nonzero element is not in the
!               existing set for this block, store it to be added later, and
!               mark it in the marker array.
                If (iwork(icol(i))==0) Then
                  iwork(icol(i)) = 1
                  ind = ind + 1
                  iwork(2*n+1+ind) = icol(i)
                End If
              End Do
            End Do

!           Shift the indices in INDB and add the new entries for block K.
!           Change ISTB accordingly.
            nadd = ind
            If (istb(nb+1)+nadd-1>lindb) Then
              iwork(1) = -999
              Exit blocks
            End If

            Do i = istb(nb+1) - 1, istb(k+1), -1
              indb(i+nadd) = indb(i)
            End Do
            n21 = 2*n + 1
            ik = istb(k+1) - 1
            indb(ik+1:ik+nadd) = iwork(n21+1:n21+nadd)
            istb(k+1:nb+1) = istb(k+1:nb+1) + nadd
          End Do
        End Do blocks

        Return

      End Subroutine f11dffe_overlap
    End Program f11dffe


f11dgfe.f90

!   F11DGF Example Program Text
!   Mark 26 Release. NAG Copyright 2016.

    Program f11dgfe

!     .. Use Statements ..
      Use nag_library, Only: f11dff, f11dgf, nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: dtolg, rnorm, tol
      Integer                          :: i, ifail, itn, k, la, lfillg, lindb, &
                                          liwork, lwork, m, maxitn, mb, n, nb, &
                                          nnz, nnzc, nover
      Character (8)                    :: method
      Character (1)                    :: milug, pstrag
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: a(:), b(:), dtol(:), work(:), x(:)
      Integer, Allocatable             :: icol(:), idiag(:), indb(:),          &
                                          ipivp(:), ipivq(:), irow(:),         &
                                          istb(:), istr(:), iwork(:),          &
                                          lfill(:), npivm(:)
      Character (1), Allocatable       :: milu(:), pstrat(:)
!     .. Executable Statements ..
      Continue

!     Print example header
      Write (nout,*) 'F11DGF Example Program Results'
      Write (nout,*)

!     Skip heading in data file
      Read (nin,*)

!     Get the square matrix size
      Read (nin,*) n

!     Allocate arrays with lengths based on mesh.
      liwork = 9*n + 3
      Allocate (b(n),x(n),iwork(liwork))

!     Get the number of non zero (nnz) matrix entries
      Read (nin,*) nnz
      la = 20*nnz
      Allocate (a(la),irow(la),icol(la))

      lindb = 3*n
      Allocate (idiag(lindb),indb(lindb),ipivp(lindb),ipivq(lindb),            &
        istr(lindb+1))

!     Read in matrix A
      Read (nin,*)(a(i),irow(i),icol(i),i=1,nnz)

!     Read in RHS
      Read (nin,*) b(1:n)

!     Read algorithmic parameters
      Read (nin,*) method
      Read (nin,*) lfillg, dtolg
      Read (nin,*) pstrag
      Read (nin,*) milug
      Read (nin,*) m, tol, maxitn
      Read (nin,*) nb, nover

!     Allocate arrays with length based on number of blocks.
      Allocate (dtol(nb),istb(nb+1),lfill(nb),npivm(nb),milu(nb),pstrat(nb))

!     Set up initial approximate solution x
      x(1:n) = 0.0_nag_wp

!     Define diagonal block indices.
!     In this example use blocks of MB consecutive rows and initialize
!     assuming no overlap.
      mb = (n+nb-1)/nb
      Do k = 1, nb
        istb(k) = (k-1)*mb + 1
      End Do
      istb(nb+1) = n + 1
      Do i = 1, n
        indb(i) = i
      End Do

!     Modify INDB and ISTB to account for overlap.
      Call f11dgfe_overlap(n,nnz,la,irow,icol,nb,istb,indb,lindb,nover,iwork)
      If (iwork(1)==-999) Then
        Write (nout,*) '** LINDB too small, LINDB = ', lindb, '.'
        Go To 100
      End If

!     Set algorithmic parameters for each block from global values
      lfill(1:nb) = lfillg
      dtol(1:nb) = dtolg
      pstrat(1:nb) = pstrag
      milu(1:nb) = milug

!     Set size of real workspace
      lwork = 2*n*m + 8*n + m*(m+2) + 100
      Allocate (work(lwork))

!     Calculate factorization
      ifail = 0
      Call f11dff(n,nnz,a,la,irow,icol,nb,istb,indb,lindb,lfill,dtol,pstrat,   &
        milu,ipivp,ipivq,istr,idiag,nnzc,npivm,iwork,liwork,ifail)

!     Solve Ax = b using F11DGF
      ifail = 0
      Call f11dgf(method,n,nnz,a,la,irow,icol,nb,istb,indb,lindb,ipivp,ipivq,  &
        istr,idiag,b,m,tol,maxitn,x,rnorm,itn,work,lwork,ifail)

      Write (nout,99999) itn
      Write (nout,99998) rnorm
      Write (nout,*)

!     Output x
      Write (nout,*) ' Solution vector  X'
      Write (nout,*) ' ------------------'
      Write (nout,99997) x(1:n)

100   Continue

99999 Format (' Converged in',I10,' iterations')
99998 Format (' Final residual norm =',1P,D16.3)
99997 Format (F8.4)

    Contains

      Subroutine f11dgfe_overlap(n,nnz,la,irow,icol,nb,istb,indb,lindb,nover,  &
        iwork)

!       Purpose
!       =======
!       This routine takes a set of row indices INDB defining the diagonal
!       blocks to be used in F11DFF to define a block Jacobi or additive
!       Schwarz preconditioner, and expands them to allow for NOVER levels of
!       overlap.
!       The pointer array ISTB is also updated accordingly, so that the
!       returned values of ISTB and INDB can be passed to F11DFF to define
!       overlapping diagonal blocks.
!       ----------------------------------------------------------------------

!       .. Implicit None Statement ..
        Implicit None
!       .. Scalar Arguments ..
        Integer, Intent (In)           :: la, lindb, n, nb, nnz, nover
!       .. Array Arguments ..
        Integer, Intent (In)           :: icol(la), irow(la)
        Integer, Intent (Inout)        :: indb(lindb), istb(nb+1)
        Integer, Intent (Out)          :: iwork(3*n+1)
!       .. Local Scalars ..
        Integer                        :: i, ind, iover, k, l, m, nadd, row
!       .. Executable Statements ..
        Continue

!       Find the number of nonzero elements in each row of the matrix A, and
!       the start address of each row. Store the start addresses in
!       IWORK(N+1,...,2*N+1).
        iwork(1:n) = 0
        Do k = 1, nnz
          iwork(irow(k)) = iwork(irow(k)) + 1
        End Do
        iwork(n+1) = 1
        Do i = 1, n
          iwork(n+i+1) = iwork(n+i) + iwork(i)
        End Do

!       Loop over blocks.
blocks: Do k = 1, nb

!         Initialize marker array.
          iwork(1:n) = 0

!         Mark the rows already in block K in the workspace array.
          Do l = istb(k), istb(k+1) - 1
            iwork(indb(l)) = 1
          End Do

!         Loop over levels of overlap.
          Do iover = 1, nover

!           Initialize counter of new row indices to be added.
            ind = 0

!           Loop over the rows currently in the diagonal block.
            Do l = istb(k), istb(k+1) - 1
              row = indb(l)

!             Loop over nonzero elements in row ROW.
              Do i = iwork(n+row), iwork(n+row+1) - 1

!               If the column index of the nonzero element is not in the
!               existing set for this block, store it to be added later, and
!               mark it in the marker array.
                If (iwork(icol(i))==0) Then
                  iwork(icol(i)) = 1
                  ind = ind + 1
                  iwork(2*n+1+ind) = icol(i)
                End If
              End Do
            End Do

!           Shift the indices in INDB and add the new entries for block K.
!           Change ISTB accordingly.
            nadd = ind
            If (istb(nb+1)+nadd-1>lindb) Then
              iwork(1) = -999
              Exit blocks
            End If

            Do i = istb(nb+1) - 1, istb(k+1), -1
              indb(i+nadd) = indb(i)
            End Do

            Do i = 1, nadd
              l = istb(k+1) + i - 1
              indb(l) = iwork(2*n+1+i)
            End Do

            Do m = k + 1, nb + 1
              istb(m) = istb(m) + nadd
            End Do
          End Do
        End Do blocks

        Return

      End Subroutine f11dgfe_overlap
    End Program f11dgfe


f11dkfe.f90

    Program f11dkfe

!     F11DKF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: f11bdf, f11bef, f11bff, f11dkf, f11xaf, nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: anorm, sigmax, stplhs, stprhs, tol
      Integer                          :: i, ifail, ifail1, irevcm, iterm,     &
                                          itn, lwork, lwreq, m, maxitn, monit, &
                                          n, niter, nnz
      Character (1)                    :: init, norm, precon, weight
      Character (8)                    :: method
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: a(:), b(:), diag(:), wgt(:),         &
                                          work(:), x(:)
      Integer, Allocatable             :: icol(:), irow(:)
!     .. Executable Statements ..
      Write (nout,*) 'F11DKF Example Program Results'

!     Skip heading in data file

      Read (nin,*)
      Read (nin,*) n
      Read (nin,*) nnz
      lwork = 200
      Allocate (a(nnz),b(n),diag(n),wgt(n),work(lwork),x(n),icol(nnz),         &
        irow(nnz))

!     Read or initialize the parameters for the iterative solver

      Read (nin,*) method
      Read (nin,*) precon, norm, weight, iterm
      Read (nin,*) m, tol, maxitn
      Read (nin,*) monit
      anorm = 0.0E0_nag_wp
      sigmax = 0.0E0_nag_wp

!     Read the parameters for the preconditioner

      Read (nin,*) niter

!     Read the nonzero elements of the matrix A

      Do i = 1, nnz
        Read (nin,*) a(i), irow(i), icol(i)
      End Do

!     Read right-hand side vector b and initial approximate solution

      Read (nin,*) b(1:n)
      Read (nin,*) x(1:n)

!     Call F11BDF to initialize the solver

!       ifail: behaviour on error exit
!                =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
      ifail = 0
      Call f11bdf(method,precon,norm,weight,iterm,n,m,tol,maxitn,anorm,sigmax, &
        monit,lwreq,work,lwork,ifail)

!     Call repeatedly F11BEF to solve the equations
!     Note that the arrays B and X are overwritten

!     On final exit, X will contain the solution and B the residual
!     vector

      irevcm = 0
      init = 'I'

      ifail = 1
loop: Do
        Call f11bef(irevcm,x,b,wgt,work,lwreq,ifail)

        If (irevcm/=4) Then
          ifail1 = -1
          Select Case (irevcm)
          Case (-1)

            Call f11xaf('Transpose',n,nnz,a,irow,icol,'No checking',x,b,       &
              ifail1)

          Case (1)

            Call f11xaf('No transpose',n,nnz,a,irow,icol,'No checking',x,b,    &
              ifail1)

          Case (2)

            Call f11dkf('Non symmetric','N',init,niter,n,nnz,a,irow,icol,      &
              'Check',x,b,diag,work(lwreq+1),ifail1)

            init = 'N'
          Case (3)

            ifail1 = 0
            Call f11bff(itn,stplhs,stprhs,anorm,sigmax,work,lwreq,ifail1)

            Write (nout,99999) itn, stplhs
          End Select
          If (ifail1/=0) Then
            irevcm = 6
          End If
        Else If (ifail/=0) Then
          Write (nout,99993) ifail
          Go To 100
        Else
          Exit loop
        End If
      End Do loop

!     Obtain information about the computation

      ifail1 = 0
      Call f11bff(itn,stplhs,stprhs,anorm,sigmax,work,lwreq,ifail1)

!     Print the output data
      Write (nout,99996)
      Write (nout,99995) 'Number of iterations for convergence:    ', itn
      Write (nout,99994) 'Residual norm:                           ', stplhs
      Write (nout,99994) 'Right-hand side of termination criterion:', stprhs
      Write (nout,99994) '1-norm of matrix A:                      ', anorm

!     Output x

      Write (nout,99998)
      Write (nout,99997)(x(i),b(i),i=1,n)
100   Continue

99999 Format (/,1X,'Monitoring at iteration no.',I4,/,1X,1P,'residual no',     &
        'rm: ',E14.4)
99998 Format (/,2X,'  Solution vector',2X,' Residual vector')
99997 Format (1X,1P,E16.4,1X,E16.4)
99996 Format (/,1X,'Final Results')
99995 Format (1X,A,I4)
99994 Format (1X,A,1P,E14.4)
99993 Format (1X,/,1X,' ** F11BEF returned with IFAIL = ',I5)
    End Program f11dkfe


f11dnfe.f90

    Program f11dnfe

!     F11DNF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: f11dnf, nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: dtol
      Integer                          :: i, ifail, la, lfill, liwork, n, nnz, &
                                          nnzc, npivm
      Character (1)                    :: milu, pstrat
!     .. Local Arrays ..
      Complex (Kind=nag_wp), Allocatable :: a(:)
      Integer, Allocatable             :: icol(:), idiag(:), ipivp(:),         &
                                          ipivq(:), irow(:), istr(:), iwork(:)
!     .. Executable Statements ..
      Write (nout,*) 'F11DNF Example Program Results'
      Write (nout,*)
!     Skip heading in data file
      Read (nin,*)

!     Read algorithmic parameters

      Read (nin,*) n
      Read (nin,*) nnz
      la = 2*nnz
      liwork = 7*n + 2
      Allocate (a(la),icol(la),idiag(n),ipivp(n),ipivq(n),irow(la),istr(n+1),  &
        iwork(liwork))
      Read (nin,*) lfill, dtol
      Read (nin,*) pstrat
      Read (nin,*) milu

!     Read the matrix A

      Do i = 1, nnz
        Read (nin,*) a(i), irow(i), icol(i)
      End Do

!     Calculate incomplete LU factorization

!     ifail: behaviour on error exit
!             =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
      ifail = 0
      Call f11dnf(n,nnz,a,la,irow,icol,lfill,dtol,pstrat,milu,ipivp,ipivq,     &
        istr,idiag,nnzc,npivm,iwork,liwork,ifail)

!     Output original matrix

      Write (nout,*) ' Original Matrix'
      Write (nout,'(A,I4)') ' N     =', n
      Write (nout,'(A,I4)') ' NNZ   =', nnz
      Do i = 1, nnz
        Write (nout,99999) i, a(i), irow(i), icol(i)
      End Do
      Write (nout,*)

!     Output details of the factorization

      Write (nout,*) ' Factorization'
      Write (nout,'(A,I4)') ' N     =', n
      Write (nout,'(A,I4)') ' NNZ   =', nnzc
      Write (nout,'(A,I4)') ' NPIVM =', npivm
      Do i = nnz + 1, nnz + nnzc
        Write (nout,99999) i, a(i), irow(i), icol(i)
      End Do
      Write (nout,*)

      Write (nout,*) '        I       IPIVP(I)  IPIVQ(I)'
      Do i = 1, n
        Write (nout,'(3I10)') i, ipivp(i), ipivq(i)
      End Do

99999 Format (1X,I8,5X,'(',E16.4,',',E16.4,')',2I8)
    End Program f11dnfe


f11dpfe.f90

    Program f11dpfe

!     F11DPF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: f11dnf, f11dpf, nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: dtol
      Integer                          :: i, ifail, la, lfill, liwork, n, nnz, &
                                          nnzc, npivm
      Character (1)                    :: check, milu, pstrat, trans
!     .. Local Arrays ..
      Complex (Kind=nag_wp), Allocatable :: a(:), x(:), y(:)
      Integer, Allocatable             :: icol(:), idiag(:), ipivp(:),         &
                                          ipivq(:), irow(:), istr(:), iwork(:)
!     .. Executable Statements ..
      Write (nout,*) 'F11DPF Example Program Results'
      Write (nout,*)
!     Skip heading in data file
      Read (nin,*)

!     Read order of matrix and number of nonzero entries

      Read (nin,*) n
      Read (nin,*) nnz
      la = 3*nnz
      liwork = 7*n + 2
      Allocate (a(la),x(n),y(n),icol(la),idiag(n),ipivp(n),ipivq(n),irow(la),  &
        istr(n+1),iwork(liwork))

!     Read the matrix A

      Do i = 1, nnz
        Read (nin,*) a(i), irow(i), icol(i)
      End Do

!     Read the vector y

      Read (nin,*) y(1:n)

!     Calculate LU factorization

      lfill = -1
      dtol = 0.0E0_nag_wp
      pstrat = 'C'
      milu = 'N'

!     ifail: behaviour on error exit
!             =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
      ifail = 0
      Call f11dnf(n,nnz,a,la,irow,icol,lfill,dtol,pstrat,milu,ipivp,ipivq,     &
        istr,idiag,nnzc,npivm,iwork,liwork,ifail)

!     Check value of NPIVM

      If (npivm>0) Then

        Write (nout,*) 'Factorization is not complete'

      Else

!       Solve P L D U x = y

        trans = 'N'
        check = 'C'

        ifail = 0
        Call f11dpf(trans,n,a,la,irow,icol,ipivp,ipivq,istr,idiag,check,y,x,   &
          ifail)

!       Output results

        Write (nout,*) 'Solution of linear system'
        Write (nout,99999) x(1:n)
      End If

99999 Format (1X,'(',E16.4,',',E16.4,')')
    End Program f11dpfe


f11dqfe.f90

    Program f11dqfe

!     F11DQF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: f11dnf, f11dqf, nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: dtol, rnorm, tol
      Integer                          :: i, ifail, itn, la, lfill, liwork,    &
                                          lwork, m, maxitn, n, nnz, nnzc,      &
                                          npivm
      Character (8)                    :: method
      Character (1)                    :: milu, pstrat
!     .. Local Arrays ..
      Complex (Kind=nag_wp), Allocatable :: a(:), b(:), work(:), x(:)
      Integer, Allocatable             :: icol(:), idiag(:), ipivp(:),         &
                                          ipivq(:), irow(:), istr(:), iwork(:)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: max
!     .. Executable Statements ..
      Write (nout,*) 'F11DQF Example Program Results'
      Write (nout,*)
!     Skip heading in data file
      Read (nin,*)

!     Read algorithmic parameters

      Read (nin,*) n, m
      Read (nin,*) nnz
      la = 2*nnz
      liwork = 7*n + 2
      lwork = max(4*n+m*(m+n+5)+121,8*n+120,2*n*(m+3)+m*(m+2)+120,11*n+120)

      Allocate (a(la),b(n),work(lwork),x(n),icol(la),idiag(n),ipivp(n),        &
        ipivq(n),irow(la),istr(n+1),iwork(liwork))
      Read (nin,*) method
      Read (nin,*) lfill, dtol
      Read (nin,*) pstrat
      Read (nin,*) milu
      Read (nin,*) tol, maxitn

!     Read the matrix A

      Do i = 1, nnz
        Read (nin,*) a(i), irow(i), icol(i)
      End Do

!     Read rhs vector b and initial approximate solution x

      Read (nin,*) b(1:n)
      Read (nin,*) x(1:n)

!     Calculate incomplete LU factorization

!     ifail: behaviour on error exit
!             =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
      ifail = 0
      Call f11dnf(n,nnz,a,la,irow,icol,lfill,dtol,pstrat,milu,ipivp,ipivq,     &
        istr,idiag,nnzc,npivm,iwork,liwork,ifail)

!     Solve Ax = b using F11DQF

      ifail = 0
      Call f11dqf(method,n,nnz,a,la,irow,icol,ipivp,ipivq,istr,idiag,b,m,tol,  &
        maxitn,x,rnorm,itn,work,lwork,ifail)

      Write (nout,99999) itn
      Write (nout,99998) rnorm
      Write (nout,*)

!     Output x

      Write (nout,*) '                   X'
      Write (nout,99997) x(1:n)

99999 Format (1X,'Converged in',I10,' iterations')
99998 Format (1X,'Final residual norm =',1P,E16.3)
99997 Format (1X,'(',1P,E16.4,',',1P,E16.4,')')
    End Program f11dqfe


f11drfe.f90

    Program f11drfe

!     F11DRF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: f11brf, f11bsf, f11btf, f11drf, f11xnf, nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: anorm, omega, sigmax, stplhs,        &
                                          stprhs, tol
      Integer                          :: i, ifail, ifail1, irevcm, iterm,     &
                                          itn, liwork, lwneed, lwork, m,       &
                                          maxitn, monit, n, nnz
      Character (1)                    :: ckdrf, ckxnf, norm, precon, trans,   &
                                          weight
      Character (8)                    :: method
!     .. Local Arrays ..
      Complex (Kind=nag_wp), Allocatable :: a(:), b(:), rdiag(:), work(:),     &
                                          x(:)
      Real (Kind=nag_wp), Allocatable  :: wgt(:)
      Integer, Allocatable             :: icol(:), irow(:), iwork(:)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: max
!     .. Executable Statements ..
      Write (nout,*) 'F11DRF Example Program Results'
      Write (nout,*)
!     Skip heading in data file
      Read (nin,*)

!     Read algorithmic parameters

      Read (nin,*) n, m
      Read (nin,*) nnz
      lwork = max(121+n*(3+m)+m*(m+5),120+7*n,120+(2*n+m)*(m+2)+2*n,120+10*n)
      liwork = 2*n + 1
      Allocate (a(nnz),b(n),rdiag(n),work(lwork),x(n),wgt(n),icol(nnz),        &
        irow(nnz),iwork(liwork))
      Read (nin,*) method
      Read (nin,*) precon, norm, iterm
      Read (nin,*) tol, maxitn
      Read (nin,*) anorm, sigmax
      Read (nin,*) omega

!     Read the matrix A

      Do i = 1, nnz
        Read (nin,*) a(i), irow(i), icol(i)
      End Do

!     Read rhs vector b and initial approximate solution x

      Read (nin,*) b(1:n)
      Read (nin,*) x(1:n)

!     Call F11BRF to initialize solver

      weight = 'N'
      monit = 0

!     ifail: behaviour on error exit
!             =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
      ifail = 0
      Call f11brf(method,precon,norm,weight,iterm,n,m,tol,maxitn,anorm,sigmax, &
        monit,lwneed,work,lwork,ifail)

!     Calculate reciprocal diagonal matrix elements if necessary

      If (precon=='P' .Or. precon=='p') Then

        iwork(1:n) = 0

        Do i = 1, nnz
          If (irow(i)==icol(i)) Then
            iwork(irow(i)) = iwork(irow(i)) + 1
            If (a(i)/=(0.0E0_nag_wp,0.0E0_nag_wp)) Then
              rdiag(irow(i)) = (1.0E0_nag_wp,0.0E0_nag_wp)/a(i)
            Else
              Write (nout,*) 'Matrix has a zero diagonal element'
              Go To 100
            End If
          End If
        End Do

        Do i = 1, n
          If (iwork(i)==0) Then
            Write (nout,*) 'Matrix has a missing diagonal element'
            Go To 100
          End If
          If (iwork(i)>=2) Then
            Write (nout,*) 'Matrix has a multiple diagonal element'
            Go To 100
          End If
        End Do

      End If

!     Call F11BSF to solve the linear system

      irevcm = 0
      ckxnf = 'C'
      ckdrf = 'C'

      ifail = 1
loop: Do
        Call f11bsf(irevcm,x,b,wgt,work,lwork,ifail)

        If (irevcm/=4) Then
          ifail1 = 1
          Select Case (irevcm)
          Case (1)
!           Compute matrix-vector product
            trans = 'N'

            Call f11xnf(trans,n,nnz,a,irow,icol,ckxnf,x,b,ifail1)

            ckxnf = 'N'
          Case (-1)
!           Compute conjugate transposed matrix-vector product
            trans = 'T'

            Call f11xnf(trans,n,nnz,a,irow,icol,ckxnf,x,b,ifail1)

            ckxnf = 'N'
          Case (2)
!           SSOR preconditioning
            trans = 'N'

            Call f11drf(trans,n,nnz,a,irow,icol,rdiag,omega,ckdrf,x,b,iwork,   &
              ifail1)

            ckdrf = 'N'
          End Select
          If (ifail1/=0) Then
            irevcm = 6
          End If
        Else If (ifail==0) Then
!         Termination

          ifail = 0
          Call f11btf(itn,stplhs,stprhs,anorm,sigmax,work,lwork,ifail)

          Write (nout,99996) itn
          Write (nout,99997) 'Matrix norm =', anorm
          Write (nout,99997) 'Final residual norm =', stplhs
          Write (nout,*)

!         Output x
          Write (nout,*) '                   X'
          Write (nout,99998) x(1:n)

          Exit loop
        Else
          Write (nout,99999) ifail
          Exit loop
        End If
      End Do loop
100   Continue

99999 Format (1X,/,1X,' ** F11BSF returned with IFAIL = ',I5)
99998 Format (1X,'(',1P,E16.4,',',1P,E16.4,')')
99997 Format (1X,A,1P,E16.3)
99996 Format (1X,'Converged in',I10,' iterations')
    End Program f11drfe


f11dsfe.f90

    Program f11dsfe

!     F11DSF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: f11dsf, nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: omega, rnorm, tol
      Integer                          :: i, ifail, itn, l, lwork, m, maxitn,  &
                                          n, nnz
      Character (8)                    :: method
      Character (1)                    :: precon
!     .. Local Arrays ..
      Complex (Kind=nag_wp), Allocatable :: a(:), b(:), work(:), x(:)
      Integer, Allocatable             :: icol(:), irow(:), iwork(:)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: max
!     .. Executable Statements ..
      Write (nout,*) 'F11DSF Example Program Results'
      Write (nout,*)
!     Skip heading in data file
      Read (nin,*)

!     Read algorithmic parameters

      Read (nin,*) n
      Read (nin,*) nnz
      Read (nin,*) method, precon
      Read (nin,*) omega
      Read (nin,*) m, tol, maxitn
      l = n
      If (precon=='N' .Or. precon=='n') Then
        l = 0
      End If
      lwork = max(4*n+m*(m+n+5)+l+121,8*n+l+120,2*n*(m+3)+m*(m+2)+l+120,       &
        11*n+l+120)

      Allocate (a(nnz),b(n),work(lwork),x(n),icol(nnz),irow(nnz),iwork(2*n+1))

!     Read the matrix A

      Do i = 1, nnz
        Read (nin,*) a(i), irow(i), icol(i)
      End Do

!     Read rhs vector b and initial approximate solution x

      Read (nin,*) b(1:n)
      Read (nin,*) x(1:n)

!     Solve Ax = b using F11DSF

!     ifail: behaviour on error exit
!             =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
      ifail = 0
      Call f11dsf(method,precon,n,nnz,a,irow,icol,omega,b,m,tol,maxitn,x,      &
        rnorm,itn,work,lwork,iwork,ifail)

      Write (nout,99999) itn
      Write (nout,99998) rnorm
      Write (nout,*)

!     Output x

      Write (nout,*) '                   X'
      Write (nout,99997) x(1:n)

99999 Format (1X,'Converged in',I10,' iterations')
99998 Format (1X,'Final residual norm =',1P,E16.3)
99997 Format (1X,'(',1P,E16.4,',',1P,E16.4,')')
    End Program f11dsfe


f11dtfe.f90

!   F11DTF Example Program Text
!   Mark 26 Release. NAG Copyright 2016.

    Program f11dtfe

!     .. Use Statements ..
      Use nag_library, Only: f11dtf, nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: dtolg
      Integer                          :: i, ifail, k, la, lfillg, lindb,      &
                                          liwork, mb, n, nb, nnz, nnzc, nover
      Character (1)                    :: milug, pstrag
!     .. Local Arrays ..
      Complex (Kind=nag_wp), Allocatable :: a(:), b(:)
      Real (Kind=nag_wp), Allocatable  :: dtol(:)
      Integer, Allocatable             :: icol(:), idiag(:), indb(:),          &
                                          ipivp(:), ipivq(:), irow(:),         &
                                          istb(:), istr(:), iwork(:),          &
                                          lfill(:), npivm(:)
      Character (1), Allocatable       :: milu(:), pstrat(:)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: maxval, minval
!     .. Executable Statements ..
      Continue

!     Print example header
      Write (nout,*) 'F11DTF Example Program Results'
      Write (nout,*)

!     Skip heading in data file
      Read (nin,*)

!     Get the square matrix size
      Read (nin,*) n

!     Allocate arrays with lengths based on mesh.
      liwork = 9*n + 3
      Allocate (b(n),iwork(liwork))

!     Get the number of non zero (nnz) matrix entries
      Read (nin,*) nnz
      la = 20*nnz
      Allocate (a(la),irow(la),icol(la))

      lindb = 3*n
      Allocate (idiag(lindb),indb(lindb),ipivp(lindb),ipivq(lindb),            &
        istr(lindb+1))

!     Read the matrix A
      Read (nin,*)(a(i),irow(i),icol(i),i=1,nnz)

!     Read algorithmic parameters
      Read (nin,*) lfillg, dtolg
      Read (nin,*) pstrag
      Read (nin,*) milug
      Read (nin,*) nb, nover

!     Allocate arrays with length based on number of blocks.
      Allocate (dtol(nb),istb(nb+1),lfill(nb),npivm(nb),milu(nb),pstrat(nb))

!     Define diagonal block indices.
!     In this example use blocks of MB consecutive rows and initialize
!     assuming no overlap.
      mb = (n+nb-1)/nb
      Do k = 1, nb
        istb(k) = (k-1)*mb + 1
      End Do
      istb(nb+1) = n + 1
      Do i = 1, n
        indb(i) = i
      End Do

!     Modify INDB and ISTB to account for overlap.
      Call f11dtfe_overlap(n,nnz,la,irow,icol,nb,istb,indb,lindb,nover,iwork)
      If (iwork(1)==-999) Then
        Write (nout,*) '** LINDB too small, LINDB = ', lindb, '.'
        Go To 100
      End If

!     Output matrix and blocking details
      Write (nout,*) ' Original Matrix'
      Write (nout,99998) ' N     =', n
      Write (nout,99998) ' NNZ   =', nnz
      Write (nout,99998) ' NB    =', nb
      Do k = 1, nb
        Write (nout,99994) ' Block ', k, ': order = ', istb(k+1) - istb(k),    &
          ', start row = ', minval(indb(istb(k):istb(k+1)-1))
      End Do

!     Set algorithmic parameters for each block from global values
      lfill(1:nb) = lfillg
      dtol(1:nb) = dtolg
      pstrat(1:nb) = pstrag
      milu(1:nb) = milug

!     Calculate factorization
      ifail = 0
      Call f11dtf(n,nnz,a,la,irow,icol,nb,istb,indb,lindb,lfill,dtol,pstrat,   &
        milu,ipivp,ipivq,istr,idiag,nnzc,npivm,iwork,liwork,ifail)

!     Output details of the factorization
      Write (nout,99997) ' Factorization'
      Write (nout,99998) '  NNZC  =', nnzc

      Write (nout,99997) ' Elements of factorization'
      Write (nout,99997)                                                       &
        '      I   J              C(I,J)                Index'
      Do k = 1, nb
        Write (nout,99995) ' C_', k,                                           &
          ' -----------------------------------------------'
!       Elements of the k-th block
        Do i = istr(istb(k)), istr(istb(k+1)) - 1
          Write (nout,99993) irow(i), icol(i), a(i), i
        End Do
      End Do

      Write (nout,99997) ' Details of factorized blocks'
      If (maxval(npivm(1:nb))>0) Then
!       Including pivoting details.
        Write (nout,99997)                                                     &
          '  K   I      ISTR(I)  IDIAG(I)   INDB(I)  IPIVP(I)  IPIVQ(I)'
        Do k = 1, nb
          i = istb(k)
          Write (nout,99996) k, i, istr(i), idiag(i), indb(i), ipivp(i),       &
            ipivq(i)
          Do i = istb(k) + 1, istb(k+1) - 1
            Write (nout,99999) i, istr(i), idiag(i), indb(i), ipivp(i),        &
              ipivq(i)
          End Do
          Write (nout,*)                                                       &
            ' -----------------------------------------------------'
        End Do
      Else
!       No pivoting on any block.
        Write (nout,99997) '  K   I      ISTR(I)  IDIAG(I)   INDB(I)'
        Do k = 1, nb
          i = istb(k)
          Write (nout,99996) k, i, istr(i), idiag(i), indb(i)
          Do i = istb(k) + 1, istb(k+1) - 1
            Write (nout,99999) i, istr(i), idiag(i), indb(i)
          End Do
          Write (nout,*) ' ------------------------------------'
        End Do
      End If

100   Continue

99999 Format (1X,I7,5(I10))
99998 Format (1X,A,I4)
99997 Format (1X,/,1X,A)
99996 Format (1X,I3,1X,I3,5(I10))
99995 Format (1X,A3,I1,A)
99994 Format (1X,A,I3,A,I3,A,I3)
99993 Format (4X,2I4,4X,'(',E13.5,',',E13.5,')',I8)

    Contains
      Subroutine f11dtfe_overlap(n,nnz,la,irow,icol,nb,istb,indb,lindb,nover,  &
        iwork)

!       Purpose
!       =======
!       This routine takes a set of row indices INDB defining the diagonal
!       blocks to be used in F11DTF to define a block Jacobi or additive
!       Schwarz preconditioner, and expands them to allow for NOVER levels of
!       overlap.
!       The pointer array ISTB is also updated accordingly, so that the
!       returned values of ISTB and INDB can be passed to F11DTF to define
!       overlapping diagonal blocks.
!       ----------------------------------------------------------------------

!       .. Implicit None Statement ..
        Implicit None
!       .. Scalar Arguments ..
        Integer, Intent (In)           :: la, lindb, n, nb, nnz, nover
!       .. Array Arguments ..
        Integer, Intent (In)           :: icol(la), irow(la)
        Integer, Intent (Inout)        :: indb(lindb), istb(nb+1)
        Integer, Intent (Out)          :: iwork(3*n+1)
!       .. Local Scalars ..
        Integer                        :: i, ik, ind, iover, k, l, n21, nadd,  &
                                          row
!       .. Executable Statements ..
        Continue

!       Find the number of nonzero elements in each row of the matrix A, and
!       and start address of each row. Store the start addresses in
!       IWORK(N+1,...,2*N+1).

        iwork(1:n) = 0
        Do k = 1, nnz
          iwork(irow(k)) = iwork(irow(k)) + 1
        End Do
        iwork(n+1) = 1
        Do i = 1, n
          iwork(n+i+1) = iwork(n+i) + iwork(i)
        End Do

!       Loop over blocks.
blocks: Do k = 1, nb

!         Initialize marker array.
          iwork(1:n) = 0

!         Mark the rows already in block K in the workspace array.
          Do l = istb(k), istb(k+1) - 1
            iwork(indb(l)) = 1
          End Do

!         Loop over levels of overlap.
          Do iover = 1, nover

!           Initialize counter of new row indices to be added.
            ind = 0

!           Loop over the rows currently in the diagonal block.
            Do l = istb(k), istb(k+1) - 1
              row = indb(l)

!             Loop over nonzero elements in row ROW.
              Do i = iwork(n+row), iwork(n+row+1) - 1

!               If the column index of the nonzero element is not in the
!               existing set for this block, store it to be added later, and
!               mark it in the marker array.
                If (iwork(icol(i))==0) Then
                  iwork(icol(i)) = 1
                  ind = ind + 1
                  iwork(2*n+1+ind) = icol(i)
                End If
              End Do
            End Do

!           Shift the indices in INDB and add the new entries for block K.
!           Change ISTB accordingly.
            nadd = ind
            If (istb(nb+1)+nadd-1>lindb) Then
              iwork(1) = -999
              Exit blocks
            End If

            Do i = istb(nb+1) - 1, istb(k+1), -1
              indb(i+nadd) = indb(i)
            End Do
            n21 = 2*n + 1
            ik = istb(k+1) - 1
            indb(ik+1:ik+nadd) = iwork(n21+1:n21+nadd)
            istb(k+1:nb+1) = istb(k+1:nb+1) + nadd
          End Do
        End Do blocks

        Return

      End Subroutine f11dtfe_overlap
    End Program f11dtfe


f11dufe.f90

!   F11DUF Example Program Text
!   Mark 26 Release. NAG Copyright 2016.

    Program f11dufe

!     .. Use Statements ..
      Use nag_library, Only: f11dtf, f11duf, nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: dtolg, rnorm, tol
      Integer                          :: i, ifail, itn, k, la, lfillg, lindb, &
                                          liwork, lwork, m, maxitn, mb, n, nb, &
                                          nnz, nnzc, nover
      Character (8)                    :: method
      Character (1)                    :: milug, pstrag
!     .. Local Arrays ..
      Complex (Kind=nag_wp), Allocatable :: a(:), b(:), work(:), x(:)
      Real (Kind=nag_wp), Allocatable  :: dtol(:)
      Integer, Allocatable             :: icol(:), idiag(:), indb(:),          &
                                          ipivp(:), ipivq(:), irow(:),         &
                                          istb(:), istr(:), iwork(:),          &
                                          lfill(:), npivm(:)
      Character (1), Allocatable       :: milu(:), pstrat(:)
!     .. Executable Statements ..
      Continue

!     Print example header
      Write (nout,*) 'F11DUF Example Program Results'
      Write (nout,*)

!     Skip heading in data file
      Read (nin,*)

!     Get the square matrix size
      Read (nin,*) n

!     Allocate arrays with lengths based on mesh.
      liwork = 9*n + 3
      Allocate (b(n),x(n),iwork(liwork))

!     Get the number of non zero (nnz) matrix entries
      Read (nin,*) nnz
      la = 20*nnz
      Allocate (a(la),irow(la),icol(la))

      lindb = 3*n
      Allocate (idiag(lindb),indb(lindb),ipivp(lindb),ipivq(lindb),            &
        istr(lindb+1))

!     Read in matrix A
      Read (nin,*)(a(i),irow(i),icol(i),i=1,nnz)

!     Read in RHS
      Read (nin,*) b(1:n)

!     Read algorithmic parameters
      Read (nin,*) method
      Read (nin,*) lfillg, dtolg
      Read (nin,*) pstrag
      Read (nin,*) milug
      Read (nin,*) m, tol, maxitn
      Read (nin,*) nb, nover

!     Allocate arrays with length based on number of blocks.
      Allocate (dtol(nb),istb(nb+1),lfill(nb),npivm(nb),milu(nb),pstrat(nb))

!     Set up initial approximate solution x
      x(1:n) = (0.0_nag_wp,0.0_nag_wp)

!     Define diagonal block indices.
!     In this example use blocks of MB consecutive rows and initialize
!     assuming no overlap.
      mb = (n+nb-1)/nb
      Do k = 1, nb
        istb(k) = (k-1)*mb + 1
      End Do
      istb(nb+1) = n + 1
      Do i = 1, n
        indb(i) = i
      End Do

!     Modify INDB and ISTB to account for overlap.
      Call f11dufe_overlap(n,nnz,la,irow,icol,nb,istb,indb,lindb,nover,iwork)
      If (iwork(1)==-999) Then
        Write (nout,*) '** LINDB too small, LINDB = ', lindb, '.'
        Go To 100
      End If

!     Set algorithmic parameters for each block from global values
      lfill(1:nb) = lfillg
      dtol(1:nb) = dtolg
      pstrat(1:nb) = pstrag
      milu(1:nb) = milug

!     Set size of real workspace
      lwork = 6*n + m*(m+n+5) + 121
      Allocate (work(lwork))

!     Calculate factorization
      ifail = 0
      Call f11dtf(n,nnz,a,la,irow,icol,nb,istb,indb,lindb,lfill,dtol,pstrat,   &
        milu,ipivp,ipivq,istr,idiag,nnzc,npivm,iwork,liwork,ifail)

!     Solve Ax = b using F11DUF
      ifail = 0
      Call f11duf(method,n,nnz,a,la,irow,icol,nb,istb,indb,lindb,ipivp,ipivq,  &
        istr,idiag,b,m,tol,maxitn,x,rnorm,itn,work,lwork,ifail)

      Write (nout,99999) itn
      Write (nout,99998) rnorm
      Write (nout,*)

!     Output x
      Write (nout,*) 'Solution vector   X'
      Write (nout,*) '-------------------'
      Write (nout,99997) x(1:n)

100   Continue

99999 Format (1X,' Converged in',I10,' iterations')
99998 Format (1X,' Final residual norm =',1P,D16.3)
99997 Format (1X,'(',F8.4,',',F8.4,')')

    Contains
      Subroutine f11dufe_overlap(n,nnz,la,irow,icol,nb,istb,indb,lindb,nover,  &
        iwork)

!       Purpose
!       =======
!       This routine takes a set of row indices INDB defining the diagonal
!       blocks to be used in F11DTF to define a block Jacobi or additive
!       Schwarz preconditioner, and expands them to allow for NOVER levels of
!       overlap.
!       The pointer array ISTB is also updated accordingly, so that the
!       returned values of ISTB and INDB can be passed to F11DTF to define
!       overlapping diagonal blocks.
!       ----------------------------------------------------------------------

!       .. Implicit None Statement ..
        Implicit None
!       .. Scalar Arguments ..
        Integer, Intent (In)           :: la, lindb, n, nb, nnz, nover
!       .. Array Arguments ..
        Integer, Intent (In)           :: icol(la), irow(la)
        Integer, Intent (Inout)        :: indb(lindb), istb(nb+1)
        Integer, Intent (Out)          :: iwork(3*n+1)
!       .. Local Scalars ..
        Integer                        :: i, ik, ind, iover, k, l, n21, nadd,  &
                                          row
!       .. Executable Statements ..
        Continue

!       Find the number of nonzero elements in each row of the matrix A, and
!       and start address of each row. Store the start addresses in
!       IWORK(N+1,...,2*N+1).

        iwork(1:n) = 0
        Do k = 1, nnz
          iwork(irow(k)) = iwork(irow(k)) + 1
        End Do
        iwork(n+1) = 1
        Do i = 1, n
          iwork(n+i+1) = iwork(n+i) + iwork(i)
        End Do

!       Loop over blocks.
blocks: Do k = 1, nb

!         Initialize marker array.
          iwork(1:n) = 0

!         Mark the rows already in block K in the workspace array.
          Do l = istb(k), istb(k+1) - 1
            iwork(indb(l)) = 1
          End Do

!         Loop over levels of overlap.
          Do iover = 1, nover

!           Initialize counter of new row indices to be added.
            ind = 0

!           Loop over the rows currently in the diagonal block.
            Do l = istb(k), istb(k+1) - 1
              row = indb(l)

!             Loop over nonzero elements in row ROW.
              Do i = iwork(n+row), iwork(n+row+1) - 1

!               If the column index of the nonzero element is not in the
!               existing set for this block, store it to be added later, and
!               mark it in the marker array.
                If (iwork(icol(i))==0) Then
                  iwork(icol(i)) = 1
                  ind = ind + 1
                  iwork(2*n+1+ind) = icol(i)
                End If
              End Do
            End Do

!           Shift the indices in INDB and add the new entries for block K.
!           Change ISTB accordingly.
            nadd = ind
            If (istb(nb+1)+nadd-1>lindb) Then
              iwork(1) = -999
              Exit blocks
            End If

            Do i = istb(nb+1) - 1, istb(k+1), -1
              indb(i+nadd) = indb(i)
            End Do
            n21 = 2*n + 1
            ik = istb(k+1) - 1
            indb(ik+1:ik+nadd) = iwork(n21+1:n21+nadd)
            istb(k+1:nb+1) = istb(k+1:nb+1) + nadd
          End Do
        End Do blocks

        Return

      End Subroutine f11dufe_overlap
    End Program f11dufe


f11dxfe.f90

    Program f11dxfe

!     F11DXF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: f11brf, f11bsf, f11btf, f11dxf, f11xnf, nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: anorm, sigmax, stplhs, stprhs, tol
      Integer                          :: i, ifail, ifail1, irevcm, iterm,     &
                                          itn, lwork, lwreq, m, maxitn, monit, &
                                          n, niter, nnz
      Logical                          :: verbose
      Character (1)                    :: init, norm, precon, weight
      Character (8)                    :: method
!     .. Local Arrays ..
      Complex (Kind=nag_wp), Allocatable :: a(:), b(:), diag(:), work(:), x(:)
      Real (Kind=nag_wp), Allocatable  :: wgt(:)
      Integer, Allocatable             :: icol(:), irow(:)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: log, nint
!     .. Executable Statements ..
      Write (nout,*) 'F11DXF Example Program Results'

!     Skip heading in data file

      Read (nin,*)
      Read (nin,*) n
      Read (nin,*) nnz
      lwork = 300
      Allocate (a(nnz),b(n),diag(n),work(lwork),x(n),wgt(n),icol(nnz),         &
        irow(nnz))

!     Read or initialize the parameters for the iterative solver

      Read (nin,*) method
      Read (nin,*) precon, norm, weight, iterm
      Read (nin,*) m, tol, maxitn
      Read (nin,*) monit
      anorm = 0.0E0_nag_wp
      sigmax = 0.0E0_nag_wp

!     Read the parameters for the preconditioner

      Read (nin,*) niter

!     Read the nonzero elements of the matrix A

      Do i = 1, nnz
        Read (nin,*) a(i), irow(i), icol(i)
      End Do

!     Read right-hand side vector b and initial approximate solution

      Read (nin,*) b(1:n)
      Read (nin,*) x(1:n)

!     Call F11BDF to initialize the solver

!     ifail: behaviour on error exit
!             =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
      ifail = 0
      Call f11brf(method,precon,norm,weight,iterm,n,m,tol,maxitn,anorm,sigmax, &
        monit,lwreq,work,lwork,ifail)

!     Call repeatedly F11BSF to solve the equations
!     Note that the arrays B and X are overwritten

!     On final exit, X will contain the solution and B the residual
!     vector

      irevcm = 0
      init = 'I'

      ifail = 0
loop: Do
        Call f11bsf(irevcm,x,b,wgt,work,lwreq,ifail)

        If (irevcm/=4) Then
          ifail1 = -1
          If (irevcm==-1) Then
            Call f11xnf('Transpose',n,nnz,a,irow,icol,'No checking',x,b,       &
              ifail1)
          Else If (irevcm==1) Then
            Call f11xnf('No transpose',n,nnz,a,irow,icol,'No checking',x,b,    &
              ifail1)
          Else If (irevcm==2) Then
            Call f11dxf('Non Hermitian','N',init,niter,n,nnz,a,irow,icol,      &
              'Check',x,b,diag,work(lwreq+1),ifail1)
            init = 'N'
          Else If (irevcm==3) Then
            Call f11btf(itn,stplhs,stprhs,anorm,sigmax,work,lwreq,ifail1)
            If (ifail1==0) Then
              If (itn<=3) Then
                Write (nout,99999) itn
                Write (nout,99998) nint(log(stplhs)/log(10.0_nag_wp))
              End If
            End If
          End If
          If (ifail1/=0) Then
            irevcm = 6
          End If
        Else
          Exit loop
        End If
      End Do loop

!     Obtain information about the computation

      ifail1 = 0
      Call f11btf(itn,stplhs,stprhs,anorm,sigmax,work,lwreq,ifail1)

!     Print the output data

      Write (nout,99997)
      verbose = .False.
      If (verbose) Then
        Write (nout,99996) 'Number of iterations for convergence:    ', itn
        Write (nout,99995) 'Residual norm:                           ', stplhs
        Write (nout,99995) 'Right-hand side of termination criterion:', stprhs
        Write (nout,99995) '1-norm of matrix A:                      ', anorm
      End If

!     Output x

      Write (nout,99994)
      Write (nout,99993) x(1:n)

99999 Format (/,1X,'Monitoring at iteration number',I4)
99998 Format (1X,'  order of residual norm:',I4)
99997 Format (/,1X,'Final Results')
99996 Format (1X,A,I5)
99995 Format (1X,A,1P,E11.1)
99994 Format (/,2X,'  Solution vector')
99993 Format (1X,'(',F8.3,',',F8.3,')')
    End Program f11dxfe


f11gdfe.f90

    Program f11gdfe

!     F11GDF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: f11gdf, f11gef, f11gff, f11jaf, f11jbf, f11xef,   &
                             nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: anorm, dscale, dtol, sigerr, sigmax, &
                                          sigtol, stplhs, stprhs, tol
      Integer                          :: i, ifail, ifail1, irevcm, iterm,     &
                                          itn, its, la, lfill, liwork, lwork,  &
                                          lwreq, maxitn, maxits, monit, n,     &
                                          nnz, nnzc, npivm
      Character (6)                    :: method
      Character (1)                    :: mic, norm, precon, pstrat, sigcmp,   &
                                          weight
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: a(:), b(:), wgt(:), work(:), x(:)
      Integer, Allocatable             :: icol(:), ipiv(:), irow(:), istr(:),  &
                                          iwork(:)
!     .. Executable Statements ..
      Write (nout,*) 'F11GDF Example Program Results'

!     Skip heading in data file

      Read (nin,*)
      Read (nin,*) n
      Read (nin,*) nnz
      la = 2*nnz
      liwork = 2*la + 7*n + 1
      lwork = 120

      Allocate (a(la),b(n),wgt(n),work(lwork),x(n),icol(la),ipiv(n),irow(la),  &
        istr(n+1),iwork(liwork))

!     Read or initialize the parameters for the iterative solver

      Read (nin,*) method
      Read (nin,*) precon, sigcmp, norm, weight, iterm
      Read (nin,*) tol, maxitn
      Read (nin,*) monit
      anorm = 0.0E0_nag_wp
      sigmax = 0.0E0_nag_wp
      sigtol = 1.0E-2_nag_wp
      maxits = n

!     Read the parameters for the preconditioner

      Read (nin,*) lfill, dtol
      Read (nin,*) mic, dscale
      Read (nin,*) pstrat

!     Read the nonzero elements of the matrix A

      Do i = 1, nnz
        Read (nin,*) a(i), irow(i), icol(i)
      End Do

!     Read right-hand side vector b and initial approximate solution x

      Read (nin,*) b(1:n)
      Read (nin,*) x(1:n)

      If (method=='CG') Then
        Write (nout,99999)
      Else If (method=='SYMMLQ') Then
        Write (nout,99998)
      Else If (method=='MINRES') Then
        Write (nout,99997)
      End If

!     Calculate incomplete Cholesky factorization

!     ifail: behaviour on error exit
!             =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
      ifail = 0
      Call f11jaf(n,nnz,a,la,irow,icol,lfill,dtol,mic,dscale,pstrat,ipiv,istr, &
        nnzc,npivm,iwork,liwork,ifail)

!     Call F11GDF to initialize the solver

      Do
        ifail = 0
        Call f11gdf(method,precon,sigcmp,norm,weight,iterm,n,tol,maxitn,anorm, &
          sigmax,sigtol,maxits,monit,lwreq,work,lwork,ifail)
        If (lwork>=lwreq) Then
          Exit
        Else
          Deallocate (work)
          lwork = lwreq
          Allocate (work(lwork))
        End If
      End Do

!     Call repeatedly F11GEF to solve the equations
!     Note that the arrays B and X are overwritten

!     On final exit, X will contain the solution and B the residual
!     vector

      irevcm = 0
      ifail = 1
loop: Do
        Call f11gef(irevcm,x,b,wgt,work,lwork,ifail)

        If (irevcm/=4) Then
          ifail1 = -1
          Select Case (irevcm)
          Case (1)

            Call f11xef(n,nnz,a,irow,icol,'No checking',x,b,ifail1)

          Case (2)

            Call f11jbf(n,a,la,irow,icol,ipiv,istr,'No checking',x,b,ifail1)

          Case (3)

            ifail1 = 0
            Call f11gff(itn,stplhs,stprhs,anorm,sigmax,its,sigerr,work,lwork,  &
              ifail1)

            Write (nout,99996) itn, stplhs
            Write (nout,99995)
            Write (nout,99994)(x(i),b(i),i=1,n)
          End Select
          If (ifail1/=0) Then
            irevcm = 6
          End If
        Else If (ifail/=0) Then
          Write (nout,99990) ifail
          Go To 100
        Else
          Exit loop
        End If
      End Do loop

!     Obtain information about the computation

      ifail1 = 0
      Call f11gff(itn,stplhs,stprhs,anorm,sigmax,its,sigerr,work,lwork,ifail1)

!     Print the output data

      Write (nout,99993)
      Write (nout,99992) 'Number of iterations for convergence:    ', itn
      Write (nout,99991) 'Residual norm:                           ', stplhs
      Write (nout,99991) 'Right-hand side of termination criterion:', stprhs
      Write (nout,99991) '1-norm of matrix A:                      ', anorm
      Write (nout,99991) 'Largest singular value of A_bar:         ', sigmax

!     Output x

      Write (nout,99995)
      Write (nout,99994)(x(i),b(i),i=1,n)
100   Continue

99999 Format (/,1X,'Solve a system of linear equations using the conjug',      &
        'ate gradient method')
99998 Format (/,1X,'Solve a system of linear equations using the Lanczo',      &
        's method (SYMMLQ)')
99997 Format (/,1X,'Solve a system of linear equations using the minimu',      &
        'm residual method (MINRES)')
99996 Format (/,1X,'Monitoring at iteration no.',I4,/,1X,1P,'residual no',     &
        'rm: ',E14.4)
99995 Format (2X,'Solution vector',2X,'Residual vector')
99994 Format (1X,1P,E16.4,1X,E16.4)
99993 Format (/,1X,'Final Results')
99992 Format (1X,A,I4)
99991 Format (1X,A,1P,E14.4)
99990 Format (1X,/,1X,' ** F11GEF returned with IFAIL = ',I5)
    End Program f11gdfe


f11grfe.f90

    Program f11grfe

!     F11GRF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: f11grf, f11gsf, f11gtf, f11jnf, f11jpf, f11xsf,   &
                             nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: anorm, dscale, dtol, sigerr, sigmax, &
                                          sigtol, stplhs, stprhs, tol
      Integer                          :: i, ifail, ifail1, irevcm, iterm,     &
                                          itn, its, la, lfill, liwork, lwork,  &
                                          lwreq, maxitn, maxits, monit, n,     &
                                          nnz, nnzc, npivm
      Character (6)                    :: method
      Character (1)                    :: mic, norm, precon, pstrat, sigcmp,   &
                                          weight
!     .. Local Arrays ..
      Complex (Kind=nag_wp), Allocatable :: a(:), b(:), work(:), x(:)
      Real (Kind=nag_wp), Allocatable  :: wgt(:)
      Integer, Allocatable             :: icol(:), ipiv(:), irow(:), istr(:),  &
                                          iwork(:)
!     .. Executable Statements ..
      Write (nout,*) 'F11GRF Example Program Results'

!     Skip heading in data file

      Read (nin,*)
      Read (nin,*) n
      Read (nin,*) nnz
      la = 2*nnz
      liwork = 2*la + 7*n + 1
      lwork = 200

      Allocate (a(la),b(n),work(lwork),x(n),wgt(n),icol(la),ipiv(n),irow(la),  &
        istr(n+1),iwork(liwork))

!     Read or initialize the parameters for the iterative solver

      Read (nin,*) method
      Read (nin,*) precon, sigcmp, norm, weight, iterm
      Read (nin,*) tol, maxitn
      Read (nin,*) monit
      anorm = 0.0E0_nag_wp
      sigmax = 0.0E0_nag_wp
      sigtol = 1.0E-2_nag_wp
      maxits = n

!     Read the parameters for the preconditioner

      Read (nin,*) lfill, dtol
      Read (nin,*) mic, dscale
      Read (nin,*) pstrat

!     Read the nonzero elements of the matrix A

      Do i = 1, nnz
        Read (nin,*) a(i), irow(i), icol(i)
      End Do

!     Read right-hand side vector b and initial approximate solution x

      Read (nin,*) b(1:n)
      Read (nin,*) x(1:n)

!     Calculate incomplete Cholesky factorization

!     ifail: behaviour on error exit
!             =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
      ifail = 0
      Call f11jnf(n,nnz,a,la,irow,icol,lfill,dtol,mic,dscale,pstrat,ipiv,istr, &
        nnzc,npivm,iwork,liwork,ifail)

!     Call F11GRF to initialize the solver

      ifail = 0
      Call f11grf(method,precon,sigcmp,norm,weight,iterm,n,tol,maxitn,anorm,   &
        sigmax,sigtol,maxits,monit,lwreq,work,lwork,ifail)

!     Call repeatedly F11GSF to solve the equations
!     Note that the arrays B and X are overwritten

!     On final exit, X will contain the solution and B the residual
!     vector

      irevcm = 0
      lwreq = lwork

      ifail = 1
loop: Do
        Call f11gsf(irevcm,x,b,wgt,work,lwreq,ifail)

        If (irevcm/=4) Then
          ifail1 = -1
          Select Case (irevcm)
          Case (1)

            Call f11xsf(n,nnz,a,irow,icol,'No checking',x,b,ifail1)

          Case (2)

            Call f11jpf(n,a,la,irow,icol,ipiv,istr,'No checking',x,b,ifail1)

          Case (3)

            ifail1 = 0
            Call f11gtf(itn,stplhs,stprhs,anorm,sigmax,its,sigerr,work,lwreq,  &
              ifail1)

            Write (nout,99999) itn, stplhs
            Write (nout,99998)
            Write (nout,99997)(x(i),b(i),i=1,n)
          End Select
          If (ifail1/=0) Then
            irevcm = 6
          End If
        Else If (ifail/=0) Then
          Write (nout,99993) ifail
          Go To 100
        Else
          Exit loop
        End If
      End Do loop

!     Obtain information about the computation

      ifail1 = 0
      Call f11gtf(itn,stplhs,stprhs,anorm,sigmax,its,sigerr,work,lwreq,ifail1)

!     Print the output data

      Write (nout,99996)
      Write (nout,99995) 'Number of iterations for convergence:    ', itn
      Write (nout,99994) 'Residual norm:                           ', stplhs
      Write (nout,99994) 'Right-hand side of termination criterion:', stprhs
      Write (nout,99994) '1-norm of matrix A:                      ', anorm
      Write (nout,99994) 'Largest singular value of A_bar:         ', sigmax

!     Output x

      Write (nout,99998)
      Write (nout,99997)(x(i),b(i),i=1,n)
100   Continue

99999 Format (/,1X,'Monitoring at iteration no.',I4,/,1X,1P,'residual no',     &
        'rm: ',E14.4)
99998 Format (6X,'Solution vector',12X,'Residual vector')
99997 Format (1X,1P,'(',E11.4,',',E11.4,')',2X,'(',E11.4,',',E11.4,')')
99996 Format (/,1X,'Final Results')
99995 Format (1X,A,I4)
99994 Format (1X,A,1P,E14.4)
99993 Format (1X,/,1X,' ** F11GSF returned with IFAIL = ',I5)
    End Program f11grfe


f11jafe.f90

    Program f11jafe

!     F11JAF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: f11jaf, nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: dscale, dtol
      Integer                          :: i, ifail, la, lfill, liwork, n, nnz, &
                                          nnzc, npivm
      Character (1)                    :: mic, pstrat
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: a(:)
      Integer, Allocatable             :: icol(:), ipiv(:), irow(:), istr(:),  &
                                          iwork(:)
!     .. Executable Statements ..
      Write (nout,*) 'F11JAF Example Program Results'
!     Skip heading in data file
      Read (nin,*)

!     Read algorithmic parameters

      Read (nin,*) n
      Read (nin,*) nnz
      la = 2*nnz
      liwork = 2*la + 7*n + 1
      Allocate (a(la),icol(la),ipiv(n),irow(la),istr(n+1),iwork(liwork))
      Read (nin,*) lfill, dtol
      Read (nin,*) mic, dscale
      Read (nin,*) pstrat

!     Read the matrix A

      Do i = 1, nnz
        Read (nin,*) a(i), irow(i), icol(i)
      End Do

!     Calculate incomplete Cholesky factorization

!     ifail: behaviour on error exit
!             =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
      ifail = 0
      Call f11jaf(n,nnz,a,la,irow,icol,lfill,dtol,mic,dscale,pstrat,ipiv,istr, &
        nnzc,npivm,iwork,liwork,ifail)

!     Output original matrix

      Write (nout,*) ' Original Matrix'
      Write (nout,99997) 'N     =', n
      Write (nout,99997) 'NNZ   =', nnz
      Do i = 1, nnz
        Write (nout,99999) i, a(i), irow(i), icol(i)
      End Do
      Write (nout,*)

!     Output details of the factorization

      Write (nout,*) ' Factorization'
      Write (nout,99997) 'N     =', n
      Write (nout,99997) 'NNZ   =', nnzc
      Write (nout,99997) 'NPIVM =', npivm
      Do i = nnz + 1, nnz + nnzc
        Write (nout,99999) i, a(i), irow(i), icol(i)
      End Do
      Write (nout,*)

      Write (nout,*) '      I     IPIV(I)'
      Do i = 1, n
        Write (nout,99998) i, ipiv(i)
      End Do

99999 Format (1X,I8,E16.4,2I8)
99998 Format (1X,2I8)
99997 Format (1X,A,I16)
    End Program f11jafe


f11jbfe.f90

    Program f11jbfe

!     F11JBF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: f11jaf, f11jbf, nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: dscale, dtol
      Integer                          :: i, ifail, la, lfill, liwork, n, nnz, &
                                          nnzc, npivm
      Character (1)                    :: check, mic, pstrat
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: a(:), x(:), y(:)
      Integer, Allocatable             :: icol(:), ipiv(:), irow(:), istr(:),  &
                                          iwork(:), perm_fwd(:), perm_inv(:)
!     .. Executable Statements ..
      Write (nout,*) 'F11JBF Example Program Results'
!     Skip heading in data file
      Read (nin,*)

!     Read order of matrix and number of nonzero entries

      Read (nin,*) n
      Read (nin,*) nnz

      la = 3*nnz
      liwork = 2*la + 7*n + 1

      Allocate (a(la),x(n),y(n),icol(la),ipiv(n),irow(la),istr(n+1),           &
        iwork(liwork),perm_fwd(n),perm_inv(n))

!     Read the matrix A

      Do i = 1, nnz
        Read (nin,*) a(i), irow(i), icol(i)
      End Do

!     Read the vector y

      Read (nin,*) y(1:n)

!     Calculate Cholesky factorization

      lfill = -1
      dtol = 0.0E0_nag_wp
      mic = 'N'
      dscale = 0.0E0_nag_wp
      pstrat = 'M'

!     ifail: behaviour on error exit
!             =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
      ifail = 0
      Call f11jaf(n,nnz,a,la,irow,icol,lfill,dtol,mic,dscale,pstrat,ipiv,istr, &
        nnzc,npivm,iwork,liwork,ifail)

!     Check the output value of NPIVM
      If (npivm/=0) Then
        Write (nout,99998) 'Factorization is not complete', npivm
      Else
!       Solve P L D L^T P^T x = y
        check = 'C'
        ifail = 0
        Call f11jbf(n,a,la,irow,icol,ipiv,istr,check,y,x,ifail)
!       Output results
        Write (nout,*) ' Solution of linear system'
        Write (nout,99999) x(1:n)
      End If

!     Compute reverse Cuthill-McKee permutation for bandwidth reduction
      Call do_rcm(irow,icol,a,y,istr,perm_fwd,perm_inv,iwork)

      ifail = 0
      Call f11jaf(n,nnz,a,la,irow,icol,lfill,dtol,mic,dscale,pstrat,ipiv,istr, &
        nnzc,npivm,iwork,liwork,ifail)

!     Check the output value of NPIVM
      If (npivm/=0) Then
        Write (nout,99998) 'Factorization is not complete', npivm
      Else
!       Solve P L D L^T P^T x = y
        ifail = 0
        Call f11jbf(n,a,la,irow,icol,ipiv,istr,check,y,x,ifail)
!       Output results
        Write (nout,*) ' Solution of linear system with Reverse Cuthill-McKee'
        Write (nout,99999)(x(perm_inv(i)),i=1,n)
      End If

99999 Format (1X,E16.4)
99998 Format (1X,A,I20)
    Contains
      Subroutine do_rcm(irow,icol,a,y,istr,perm_fwd,perm_inv,iwork)

!       .. Use Statements ..
        Use nag_library, Only: f11yef, f11zaf, f11zbf
!       .. Parameters ..
        Logical, Parameter             :: lopts(5) = (/.False.,.False.,.True., &
                                          .True.,.True./)
!       .. Array Arguments ..
        Real (Kind=nag_wp), Intent (Inout) :: a(la), y(n)
        Integer, Intent (Inout)        :: icol(la), irow(la), istr(n+1),       &
                                          iwork(*)
        Integer, Intent (Out)          :: perm_fwd(n), perm_inv(n)
!       .. Local Scalars ..
        Integer                        :: i, ifail, j, nnz_cs, nnz_scs
!       .. Local Arrays ..
        Real (Kind=nag_wp), Allocatable :: rwork(:)
        Integer                        :: info(4), mask(1)
!       .. Intrinsic Procedures ..
        Intrinsic                      :: size
!       .. Executable Statements ..

!       SCS to CS, must add the upper triangle entries.
        j = nnz + 1
        Do i = 1, nnz
          If (irow(i)>icol(i)) Then
!           strictly lower triangle, add the transposed
            a(j) = a(i)
            irow(j) = icol(i)
            icol(j) = irow(i)
            j = j + 1
          End If
        End Do
        nnz_cs = j - 1

!       Reorder, CS to CCS, icolzp in istr
        ifail = 0
        Call f11zaf(n,nnz_cs,a,icol,irow,'F','F',istr,iwork,ifail)

!       Calculate reverse Cuthill-McKee
        ifail = 0
        Call f11yef(n,nnz_cs,istr,irow,lopts,mask,perm_fwd,info,ifail)

!       compute inverse perm, in perm_inv(1:n)
        Do i = 1, n
          perm_inv(perm_fwd(i)) = i
        End Do

!       Apply permutation on column/row indices
        icol(1:nnz_cs) = perm_inv(icol(1:nnz_cs))
        irow(1:nnz_cs) = perm_inv(irow(1:nnz_cs))

!       restrict to lower triangle, SCS format
!       copying entries upwards
        j = 1
        Do i = 1, nnz_cs
          If (irow(i)>=icol(i)) Then
!           non-upper triangle, bubble up
            a(j) = a(i)
            icol(j) = icol(i)
            irow(j) = irow(i)
            j = j + 1
          End If
        End Do
        nnz_scs = j - 1

!       sort
        ifail = 0
        Call f11zbf(n,nnz_scs,a,irow,icol,'S','K',istr,iwork,ifail)

!       permute rhs vector
        Allocate (rwork(size(perm_fwd)))
        rwork(:) = y(perm_fwd(:))
        y(:) = rwork(:)
        Deallocate (rwork)
      End Subroutine do_rcm
    End Program f11jbfe


f11jcfe.f90

    Program f11jcfe

!     F11JCF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: f11jaf, f11jcf, nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: dscale, dtol, rnorm, tol
      Integer                          :: i, ifail, itn, la, lfill, liwork,    &
                                          lwork, maxitn, n, nnz, nnzc, npivm
      Character (6)                    :: method
      Character (1)                    :: mic, pstrat
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: a(:), b(:), work(:), x(:)
      Integer, Allocatable             :: icol(:), ipiv(:), irow(:), istr(:),  &
                                          iwork(:)
!     .. Executable Statements ..
      Write (nout,*) 'F11JCF Example Program Results'
!     Skip heading in data file
      Read (nin,*)

!     Read algorithmic parameters

      Read (nin,*) n
      Read (nin,*) nnz
      la = 3*nnz
      liwork = 2*la + 7*n + 1
      lwork = 6*n + 120
      Allocate (a(la),b(n),work(lwork),x(n),icol(la),ipiv(n),irow(la),         &
        istr(n+1),iwork(liwork))
      Read (nin,*) method
      Read (nin,*) lfill, dtol
      Read (nin,*) mic, dscale
      Read (nin,*) pstrat
      Read (nin,*) tol, maxitn

!     Read the matrix A

      Do i = 1, nnz
        Read (nin,*) a(i), irow(i), icol(i)
      End Do

!     Read right-hand side vector b and initial approximate solution x

      Read (nin,*) b(1:n)
      Read (nin,*) x(1:n)

!     Calculate incomplete Cholesky factorization

!     ifail: behaviour on error exit
!             =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
      ifail = 0
      Call f11jaf(n,nnz,a,la,irow,icol,lfill,dtol,mic,dscale,pstrat,ipiv,istr, &
        nnzc,npivm,iwork,liwork,ifail)

!     Solve Ax = b using F11JCF

      ifail = 0
      Call f11jcf(method,n,nnz,a,la,irow,icol,ipiv,istr,b,tol,maxitn,x,rnorm,  &
        itn,work,lwork,ifail)

      Write (nout,99999) 'Converged in', itn, ' iterations'
      Write (nout,99998) 'Final residual norm =', rnorm

!     Output x

      Write (nout,99997) x(1:n)

99999 Format (1X,A,I10,A)
99998 Format (1X,A,1P,E16.3)
99997 Format (1X,1P,E16.4)
    End Program f11jcfe


f11jdfe.f90

    Program f11jdfe

!     F11JDF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: f11gdf, f11gef, f11gff, f11jdf, f11xef, nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: anorm, omega, sigerr, sigmax,        &
                                          sigtol, stplhs, stprhs, tol
      Integer                          :: i, ifail, ifail1, irevcm, iterm,     &
                                          itn, its, liwork, lwneed, lwork,     &
                                          maxitn, maxits, monit, n, nnz
      Character (1)                    :: ckjdf, ckxef, norm, precon, sigcmp,  &
                                          weight
      Character (6)                    :: method
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: a(:), b(:), rdiag(:), wgt(:),        &
                                          work(:), x(:)
      Integer, Allocatable             :: icol(:), irow(:), iwork(:)
!     .. Executable Statements ..
      Write (nout,*) 'F11JDF Example Program Results'
!     Skip heading in data file
      Read (nin,*)

!     Read algorithmic parameters

      Read (nin,*) n
      Read (nin,*) nnz
      liwork = n + 1
      lwork = 6*n + 120

      Allocate (a(nnz),b(n),rdiag(n),wgt(n),work(lwork),x(n),icol(nnz),        &
        irow(nnz),iwork(liwork))
      Read (nin,*) method
      Read (nin,*) precon, sigcmp, norm, iterm
      Read (nin,*) tol, maxitn
      Read (nin,*) anorm, sigmax
      Read (nin,*) sigtol, maxits
      Read (nin,*) omega

!     Read the matrix A

      Do i = 1, nnz
        Read (nin,*) a(i), irow(i), icol(i)
      End Do

!     Read right-hand side vector b and initial approximate solution x

      Read (nin,*) b(1:n)
      Read (nin,*) x(1:n)

!     Call F11GDF to initialize solver

      weight = 'N'
      monit = 0

!     ifail: behaviour on error exit
!             =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
      ifail = 0
      Call f11gdf(method,precon,sigcmp,norm,weight,iterm,n,tol,maxitn,anorm,   &
        sigmax,sigtol,maxits,monit,lwneed,work,lwork,ifail)

!     Calculate reciprocal diagonal matrix elements.

      iwork(1:n) = 0

      Do i = 1, nnz
        If (irow(i)==icol(i)) Then
          iwork(irow(i)) = iwork(irow(i)) + 1
          If (a(i)/=0.0E0_nag_wp) Then
            rdiag(irow(i)) = 1.0E0_nag_wp/a(i)
          Else
            Write (nout,*) 'Matrix has a zero diagonal element'
            Go To 100
          End If
        End If
      End Do

      Do i = 1, n
        If (iwork(i)==0) Then
          Write (nout,*) 'Matrix has a missing diagonal element'
          Go To 100
        End If
        If (iwork(i)>=2) Then
          Write (nout,*) 'Matrix has a multiple diagonal element'
          Go To 100
        End If
      End Do

!     Call F11GEF to solve the linear system

      irevcm = 0
      ckxef = 'C'
      ckjdf = 'C'

      ifail = 1
loop: Do
        Call f11gef(irevcm,x,b,wgt,work,lwork,ifail)

        If (irevcm/=4) Then
          ifail1 = -1
          Select Case (irevcm)
          Case (1)
!           Compute matrix vector product

            Call f11xef(n,nnz,a,irow,icol,ckxef,x,b,ifail1)

            ckxef = 'N'
          Case (2)
!           SSOR preconditioning

            Call f11jdf(n,nnz,a,irow,icol,rdiag,omega,ckjdf,x,b,iwork,ifail1)

            ckjdf = 'N'
          End Select
          If (ifail1/=0) Then
            irevcm = 6
          End If
        Else If (ifail/=0) Then
          Write (nout,99996) ifail
          Go To 100
        Else
          Exit loop
        End If
      End Do loop

!     Termination

      Call f11gff(itn,stplhs,stprhs,anorm,sigmax,its,sigerr,work,lwork,ifail)

      Write (nout,99999) 'Converged in', itn, ' iterations'
      Write (nout,99998) 'Final residual norm =', stplhs

!     Output x

      Write (nout,99997) x(1:n)

100   Continue

99999 Format (1X,A,I10,A)
99998 Format (1X,A,1P,E16.3)
99997 Format (1X,1P,E16.4)
99996 Format (1X,/,1X,' ** F11GEF returned with IFAIL = ',I5)
    End Program f11jdfe


f11jefe.f90

    Program f11jefe

!     F11JEF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: f11jef, nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: omega, rnorm, tol
      Integer                          :: i, ifail, itn, lwork, maxitn, n, nnz
      Character (6)                    :: method
      Character (1)                    :: precon
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: a(:), b(:), work(:), x(:)
      Integer, Allocatable             :: icol(:), irow(:), iwork(:)
!     .. Executable Statements ..
      Write (nout,*) 'F11JEF Example Program Results'
!     Skip heading in data file
      Read (nin,*)

!     Read algorithmic parameters

      Read (nin,*) n
      Read (nin,*) nnz
      lwork = 7*n + 120
      Allocate (a(nnz),b(n),work(lwork),x(n),icol(nnz),irow(nnz),iwork(n+1))
      Read (nin,*) method, precon
      Read (nin,*) omega
      Read (nin,*) tol, maxitn

!     Read the matrix A

      Do i = 1, nnz
        Read (nin,*) a(i), irow(i), icol(i)
      End Do

!     Read right-hand side vector b and initial approximate solution x

      Read (nin,*) b(1:n)
      Read (nin,*) x(1:n)

!     Solve Ax = b using F11JEF

!     ifail: behaviour on error exit
!             =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
      ifail = 0
      Call f11jef(method,precon,n,nnz,a,irow,icol,omega,b,tol,maxitn,x,rnorm,  &
        itn,work,lwork,iwork,ifail)

      Write (nout,99999) 'Converged in', itn, ' iterations'
      Write (nout,99998) 'Final residual norm =', rnorm

!     Output x

      Write (nout,99997) x(1:n)

99999 Format (1X,A,I10,A)
99998 Format (1X,A,1P,E16.3)
99997 Format (1X,1P,E16.4)
    End Program f11jefe


f11jnfe.f90

    Program f11jnfe

!     F11JNF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: f11jnf, nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: dscale, dtol
      Integer                          :: i, ifail, la, lfill, liwork, n, nnz, &
                                          nnzc, npivm
      Character (1)                    :: mic, pstrat
!     .. Local Arrays ..
      Complex (Kind=nag_wp), Allocatable :: a(:)
      Integer, Allocatable             :: icol(:), ipiv(:), irow(:), istr(:),  &
                                          iwork(:)
!     .. Executable Statements ..
      Write (nout,*) 'F11JNF Example Program Results'
!     Skip heading in data file
      Read (nin,*)

!     Read algorithmic parameters

      Read (nin,*) n
      Read (nin,*) nnz
      la = 3*nnz
      liwork = 2*la + 7*n + 1
      Allocate (a(la),icol(la),ipiv(n),irow(la),istr(n+1),iwork(liwork))
      Read (nin,*) lfill, dtol
      Read (nin,*) mic, dscale
      Read (nin,*) pstrat

!     Read the matrix A

      Do i = 1, nnz
        Read (nin,*) a(i), irow(i), icol(i)
      End Do

!     Calculate incomplete Cholesky factorization

!     ifail: behaviour on error exit
!             =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
      ifail = 0
      Call f11jnf(n,nnz,a,la,irow,icol,lfill,dtol,mic,dscale,pstrat,ipiv,istr, &
        nnzc,npivm,iwork,liwork,ifail)

!     Output original matrix

      Write (nout,*) ' Original Matrix'
      Write (nout,99997) 'N     =', n
      Write (nout,99997) 'NNZ   =', nnz
      Do i = 1, nnz
        Write (nout,99999) i, a(i), irow(i), icol(i)
      End Do
      Write (nout,*)

!     Output details of the factorization

      Write (nout,*) ' Factorization'
      Write (nout,99997) 'N     =', n
      Write (nout,99997) 'NNZ   =', nnzc
      Write (nout,99997) 'NPIVM =', npivm
      Do i = nnz + 1, nnz + nnzc
        Write (nout,99999) i, a(i), irow(i), icol(i)
      End Do
      Write (nout,*)

      Write (nout,*) '      I     IPIV(I)'
      Do i = 1, n
        Write (nout,99998) i, ipiv(i)
      End Do

99999 Format (I8,5X,'(',E16.4,',',E16.4,')',2I8)
99998 Format (1X,2I8)
99997 Format (1X,A,I16)
    End Program f11jnfe


f11jpfe.f90

    Program f11jpfe

!     F11JPF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: f11jnf, f11jpf, nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: dscale, dtol
      Integer                          :: i, ifail, la, lfill, liwork, n, nnz, &
                                          nnzc, npivm
      Character (1)                    :: check, mic, pstrat
!     .. Local Arrays ..
      Complex (Kind=nag_wp), Allocatable :: a(:), x(:), y(:)
      Integer, Allocatable             :: icol(:), ipiv(:), irow(:), istr(:),  &
                                          iwork(:)
!     .. Executable Statements ..
      Write (nout,*) 'F11JPF Example Program Results'
!     Skip heading in data file
      Read (nin,*)

!     Read order of matrix and number of nonzero entries

      Read (nin,*) n
      Read (nin,*) nnz
      la = 3*nnz
      liwork = 2*la + 7*n + 1
      Allocate (a(la),x(n),y(n),icol(la),ipiv(n),irow(la),istr(n+1),           &
        iwork(liwork))

!     Read the matrix A

      Do i = 1, nnz
        Read (nin,*) a(i), irow(i), icol(i)
      End Do

!     Read the vector y

      Read (nin,*) y(1:n)

!     Calculate Cholesky factorization

      lfill = -1
      dtol = 0.0E0_nag_wp
      mic = 'N'
      dscale = 0.0E0_nag_wp
      pstrat = 'M'

!     ifail: behaviour on error exit
!             =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
      ifail = 0
      Call f11jnf(n,nnz,a,la,irow,icol,lfill,dtol,mic,dscale,pstrat,ipiv,istr, &
        nnzc,npivm,iwork,liwork,ifail)

!     Check the output value of NPIVM

      If (npivm/=0) Then

        Write (nout,*) 'Factorization is not complete'

      Else

!       Solve P L D L^H P^T x = y

        check = 'C'

        ifail = 0
        Call f11jpf(n,a,la,irow,icol,ipiv,istr,check,y,x,ifail)

!       Output results

        Write (nout,*) 'Solution of linear system'
        Write (nout,99999) x(1:n)
      End If

99999 Format (1X,'(',E16.4,',',E16.4,')')
    End Program f11jpfe


f11jqfe.f90

    Program f11jqfe

!     F11JQF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: f11jnf, f11jqf, nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: dscale, dtol, rnorm, tol
      Integer                          :: i, ifail, itn, la, lfill, liwork,    &
                                          lwork, maxitn, n, nnz, nnzc, npivm
      Character (6)                    :: method
      Character (1)                    :: mic, pstrat
!     .. Local Arrays ..
      Complex (Kind=nag_wp), Allocatable :: a(:), b(:), work(:), x(:)
      Integer, Allocatable             :: icol(:), ipiv(:), irow(:), istr(:),  &
                                          iwork(:)
!     .. Executable Statements ..
      Write (nout,*) 'F11JQF Example Program Results'
!     Skip heading in data file
      Read (nin,*)

!     Read algorithmic parameters

      Read (nin,*) n
      Read (nin,*) nnz
      la = 3*nnz
      liwork = 2*la + 7*n + 1
      lwork = 7*n + 120
      Allocate (a(la),b(n),work(lwork),x(n),icol(la),ipiv(n),irow(la),         &
        istr(n+1),iwork(liwork))
      Read (nin,*) method
      Read (nin,*) lfill, dtol
      Read (nin,*) mic, dscale
      Read (nin,*) pstrat
      Read (nin,*) tol, maxitn

!     Read the matrix A

      Do i = 1, nnz
        Read (nin,*) a(i), irow(i), icol(i)
      End Do

!     Read rhs vector b and initial approximate solution x

      Read (nin,*) b(1:n)
      Read (nin,*) x(1:n)

!     Calculate incomplete Cholesky factorization

!     ifail: behaviour on error exit
!             =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
      ifail = 0
      Call f11jnf(n,nnz,a,la,irow,icol,lfill,dtol,mic,dscale,pstrat,ipiv,istr, &
        nnzc,npivm,iwork,liwork,ifail)

!     Solve Ax = b using F11JQF

      Call f11jqf(method,n,nnz,a,la,irow,icol,ipiv,istr,b,tol,maxitn,x,rnorm,  &
        itn,work,lwork,ifail)

      Write (nout,99999) 'Converged in', itn, ' iterations'
      Write (nout,99998) 'Final residual norm =', rnorm

!     Output x

      Write (nout,99997) x(1:n)

99999 Format (1X,A,I10,A)
99998 Format (1X,A,1P,E16.3)
99997 Format (1X,'(',E16.4,',',E16.4,')')
    End Program f11jqfe


f11jrfe.f90

    Program f11jrfe

!     F11JRF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: f11jrf, nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: omega
      Integer                          :: i, ifail, n, nnz
      Character (1)                    :: check
!     .. Local Arrays ..
      Complex (Kind=nag_wp), Allocatable :: a(:), x(:), y(:)
      Real (Kind=nag_wp), Allocatable  :: rdiag(:)
      Integer, Allocatable             :: icol(:), irow(:), iwork(:)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: real
!     .. Executable Statements ..
      Write (nout,*) 'F11JRF Example Program Results'
!     Skip heading in data file
      Read (nin,*)

!     Read algorithmic parameters

      Read (nin,*) n
      Read (nin,*) nnz

      Allocate (a(nnz),x(n),y(n),rdiag(n),icol(nnz),irow(nnz),iwork(n+1))
      Read (nin,*) check
      Read (nin,*) omega

!     Read the matrix A

      Do i = 1, nnz
        Read (nin,*) a(i), irow(i), icol(i)
      End Do

!     Read rhs vector y

      Read (nin,*) y(1:n)

!     Fill in the diagonal part

      Do i = 1, nnz
        If (irow(i)==icol(i)) Then
          rdiag(irow(i)) = 1.E0_nag_wp/real(a(i))
        End If
      End Do

!     Solve Mx = b using F11JRF

!     ifail: behaviour on error exit
!             =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
      ifail = 0
      Call f11jrf(n,nnz,a,irow,icol,rdiag,omega,check,y,x,iwork,ifail)

!     Output x

      Write (nout,99999) x(1:n)

99999 Format (1X,'(',E16.4,',',E16.4,')')
    End Program f11jrfe


f11jsfe.f90

    Program f11jsfe

!     F11JSF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: f11jsf, nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: omega, rnorm, tol
      Integer                          :: i, ifail, itn, lwork, maxitn, n, nnz
      Character (6)                    :: method
      Character (1)                    :: precon
!     .. Local Arrays ..
      Complex (Kind=nag_wp), Allocatable :: a(:), b(:), work(:), x(:)
      Real (Kind=nag_wp), Allocatable  :: rdiag(:)
      Integer, Allocatable             :: icol(:), irow(:), iwork(:)
!     .. Executable Statements ..
      Write (nout,*) 'F11JSF Example Program Results'
!     Skip heading in data file
      Read (nin,*)

!     Read algorithmic parameters

      Read (nin,*) n
      Read (nin,*) nnz
      lwork = 7*n + 120
      Allocate (a(nnz),b(n),work(lwork),x(n),rdiag(n),icol(nnz),irow(nnz),     &
        iwork(n+1))
      Read (nin,*) method, precon
      Read (nin,*) omega
      Read (nin,*) tol, maxitn

!     Read the matrix A

      Do i = 1, nnz
        Read (nin,*) a(i), irow(i), icol(i)
      End Do

!     Read rhs vector b and initial approximate solution x

      Read (nin,*) b(1:n)
      Read (nin,*) x(1:n)

!     Solve Ax = b using F11JSF

!     ifail: behaviour on error exit
!             =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
      ifail = 0
      Call f11jsf(method,precon,n,nnz,a,irow,icol,omega,b,tol,maxitn,x,rnorm,  &
        itn,rdiag,work,lwork,iwork,ifail)

      Write (nout,99999) 'Converged in', itn, ' iterations'
      Write (nout,99998) 'Final residual norm =', rnorm

!     Output x

      Write (nout,99997) x(1:n)

99999 Format (1X,A,I10,A)
99998 Format (1X,A,1P,E16.3)
99997 Format (1X,'(',E16.4,',',E16.4,')')
    End Program f11jsfe


f11mdfe.f90

    Program f11mdfe

!     F11MDF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: f11mdf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Integer                          :: ifail, n, nnz
      Character (1)                    :: spec
!     .. Local Arrays ..
      Integer, Allocatable             :: icolzp(:), iprm(:), irowix(:)
!     .. Executable Statements ..
      Write (nout,*) 'F11MDF Example Program Results'
!     Skip heading in data file
      Read (nin,*)

!     Read order of matrix

      Read (nin,*) n

      Allocate (icolzp(n+1),iprm(7*n))

!     Read the matrix

      Read (nin,*) icolzp(1:n+1)
      nnz = icolzp(n+1) - 1

      Allocate (irowix(nnz))

      Read (nin,*) irowix(1:nnz)

!     Calculate COLAMD permutation

      spec = 'M'

!     ifail: behaviour on error exit
!             =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
      ifail = 0
      Call f11mdf(spec,n,icolzp,irowix,iprm,ifail)

!     Output results

      Write (nout,*)
      Write (nout,*) 'COLAMD Permutation'
      Write (nout,'(10I6)') iprm(1:n)

!     Calculate user permutation

      spec = 'U'
      iprm(1) = 4
      iprm(2) = 3
      iprm(3) = 2
      iprm(4) = 1
      iprm(5) = 0

      ifail = 0
      Call f11mdf(spec,n,icolzp,irowix,iprm,ifail)

!     Output results

      Write (nout,*)
      Write (nout,*) 'User Permutation'
      Write (nout,'(10I6)') iprm(1:n)

!     Calculate natural permutation

      spec = 'N'

      ifail = 0
      Call f11mdf(spec,n,icolzp,irowix,iprm,ifail)

!     Output results

      Write (nout,*)
      Write (nout,*) 'Natural Permutation'
      Write (nout,'(10I6)') iprm(1:n)

    End Program f11mdfe


f11mefe.f90

    Program f11mefe

!     F11MEF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: f11mdf, f11mef, nag_wp, x04cbf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Real (Kind=nag_wp), Parameter    :: one = 1.E0_nag_wp
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: flop, thresh
      Integer                          :: i, ifail, n, nnz, nnzl, nnzu, nzlmx, &
                                          nzlumx, nzumx
      Character (1)                    :: spec
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: a(:), lval(:), uval(:)
      Integer, Allocatable             :: icolzp(:), il(:), iprm(:),           &
                                          irowix(:), iu(:)
      Character (1)                    :: clabs(1), rlabs(1)
!     .. Executable Statements ..
      Write (nout,*) 'F11MEF Example Program Results'
      Flush (nout)
!     Skip heading in data file
      Read (nin,*)

!     Read order of matrix

      Read (nin,*) n

      Allocate (icolzp(n+1),iprm(7*n))

!     Read the matrix A

      Read (nin,*) icolzp(1:n+1)
      nnz = icolzp(n+1) - 1

      Allocate (a(nnz),lval(8*nnz),uval(8*nnz),il(7*n+8*nnz+4),irowix(nnz),    &
        iu(2*n+8*nnz+1))

      Do i = 1, nnz
        Read (nin,*) a(i), irowix(i)
      End Do

!     Calculate COLAMD permutation

      spec = 'M'

!     ifail: behaviour on error exit
!             =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
      ifail = 0
      Call f11mdf(spec,n,icolzp,irowix,iprm,ifail)

!     Factorise

      thresh = one
      ifail = 0
      nzlmx = 8*nnz
      nzlumx = 8*nnz
      nzumx = 8*nnz
      Call f11mef(n,irowix,a,iprm,thresh,nzlmx,nzlumx,nzumx,il,lval,iu,uval,   &
        nnzl,nnzu,flop,ifail)

!     Output results

      Write (nout,99999)
      Write (nout,99998) nnzl + nnzu - n
      Flush (nout)

      Call x04cbf('G','X',1,10,lval,1,'F7.2','Factor elements in LVAL','N',    &
        rlabs,'N',clabs,80,0,ifail)
      Call x04cbf('G','X',1,4,uval,1,'F7.2','Factor elements in UVAL','N',     &
        rlabs,'N',clabs,80,0,ifail)

99999 Format (1X,/,1X,'Number of nonzeros in factors (excluding unit',         &
        ' diagonal)')
99998 Format (1X,I8)
    End Program f11mefe


f11mffe.f90

    Program f11mffe

!     F11MFF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: f11mdf, f11mef, f11mff, nag_wp, x04caf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Real (Kind=nag_wp), Parameter    :: one = 1.E0_nag_wp
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: flop, thresh
      Integer                          :: i, ifail, j, ldb, n, nnz, nnzl,      &
                                          nnzu, nrhs, nzlmx, nzlumx, nzumx
      Character (1)                    :: spec, trans
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: a(:), b(:,:), lval(:), uval(:)
      Integer, Allocatable             :: icolzp(:), il(:), iprm(:),           &
                                          irowix(:), iu(:)
!     .. Executable Statements ..
      Write (nout,*) 'F11MFF Example Program Results'
      Flush (nout)
!     Skip heading in data file
      Read (nin,*)

!     Read order of matrix and number of right hand sides

      Read (nin,*) n, nrhs
      ldb = n

      Allocate (b(ldb,nrhs),icolzp(n+1),iprm(7*n))

!     Read the matrix A

      Read (nin,*) icolzp(1:n+1)

      nnz = icolzp(n+1) - 1

      Allocate (a(nnz),lval(8*nnz),uval(8*nnz),il(7*n+8*nnz+4),irowix(nnz),    &
        iu(2*n+8*nnz+1))

      Do i = 1, nnz
        Read (nin,*) a(i), irowix(i)
      End Do

!     Read the right hand sides

      Do j = 1, nrhs
        Read (nin,*) b(1:n,j)
      End Do

!     Calculate COLAMD permutation

      spec = 'M'

!     ifail: behaviour on error exit
!             =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
      ifail = 0
      Call f11mdf(spec,n,icolzp,irowix,iprm,ifail)

!     Factorise

      thresh = one
      ifail = 0
      nzlmx = 8*nnz
      nzlumx = 8*nnz
      nzumx = 8*nnz

      Call f11mef(n,irowix,a,iprm,thresh,nzlmx,nzlumx,nzumx,il,lval,iu,uval,   &
        nnzl,nnzu,flop,ifail)

!     Solve

      trans = 'N'

      ifail = 0
      Call f11mff(trans,n,iprm,il,lval,iu,uval,nrhs,b,ldb,ifail)

!     Output results
      Write (nout,*)
      Flush (nout)

      Call x04caf('G',' ',n,nrhs,b,ldb,'Solutions',ifail)

    End Program f11mffe


f11mgfe.f90

    Program f11mgfe

!     F11MGF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: f11mdf, f11mef, f11mgf, f11mlf, nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Real (Kind=nag_wp), Parameter    :: one = 1.E0_nag_wp
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: anorm, flop, rcond, thresh
      Integer                          :: i, ifail, n, nnz, nnzl, nnzu, nzlmx, &
                                          nzlumx, nzumx
      Character (1)                    :: norm, spec
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: a(:), lval(:), uval(:)
      Integer, Allocatable             :: icolzp(:), il(:), iprm(:),           &
                                          irowix(:), iu(:)
!     .. Executable Statements ..
      Write (nout,*) 'F11MGF Example Program Results'
!     Skip heading in data file
      Read (nin,*)

!     Read order of matrix

      Read (nin,*) n

      Allocate (icolzp(n+1),iprm(7*n))

!     Read the matrix A

      Read (nin,*) icolzp(1:n+1)
      nnz = icolzp(n+1) - 1

      Allocate (a(nnz),lval(8*nnz),uval(8*nnz),il(7*n+8*nnz+4),irowix(nnz),    &
        iu(2*n+8*nnz+1))

      Do i = 1, nnz
        Read (nin,*) a(i), irowix(i)
      End Do

!     Calculate COLAMD permutation

      spec = 'M'

!     ifail: behaviour on error exit
!             =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
      ifail = 0
      Call f11mdf(spec,n,icolzp,irowix,iprm,ifail)

!     Factorise

      thresh = one
      ifail = 0
      nzlmx = 8*nnz
      nzlumx = 8*nnz
      nzumx = 8*nnz

      Call f11mef(n,irowix,a,iprm,thresh,nzlmx,nzlumx,nzumx,il,lval,iu,uval,   &
        nnzl,nnzu,flop,ifail)

!     Calculate norm

      norm = '1'

      ifail = 0
      Call f11mlf(norm,anorm,n,icolzp,irowix,a,ifail)

!     Calculate condition number

      ifail = 0
      Call f11mgf(norm,n,il,lval,iu,uval,anorm,rcond,ifail)

!     Output result

      Write (nout,*)
      Write (nout,*) 'Norm  ,Condition number'
      Write (nout,'(F7.3,A1,F7.3)') anorm, ',', 1.0E0_nag_wp/rcond

    End Program f11mgfe


f11mhfe.f90

    Program f11mhfe

!     F11MHF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: f11mdf, f11mef, f11mff, f11mhf, nag_wp, x04caf,   &
                             x04cbf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Real (Kind=nag_wp), Parameter    :: one = 1.E0_nag_wp
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: flop, thresh
      Integer                          :: i, ifail, j, ldb, ldx, n, nnz, nnzl, &
                                          nnzu, nrhs, nzlmx, nzlumx, nzumx
      Character (1)                    :: spec, trans
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: a(:), b(:,:), berr(:), ferr(:),      &
                                          lval(:), uval(:), x(:,:)
      Integer, Allocatable             :: icolzp(:), il(:), iprm(:),           &
                                          irowix(:), iu(:)
      Character (1)                    :: clabs(1), rlabs(1)
!     .. Executable Statements ..
      Write (nout,*) 'F11MHF Example Program Results'
      Flush (nout)
!     Skip heading in data file
      Read (nin,*)

!     Read order of matrix and number of right hand sides

      Read (nin,*) n, nrhs
      ldb = n
      ldx = n

      Allocate (b(ldb,nrhs),berr(nrhs),ferr(nrhs),x(ldx,nrhs),icolzp(n+1),     &
        iprm(7*n))

!     Read the matrix A

      Read (nin,*) icolzp(1:n+1)
      nnz = icolzp(n+1) - 1

      Allocate (a(nnz),lval(8*nnz),uval(8*nnz),il(7*n+8*nnz+4),irowix(nnz),    &
        iu(2*n+8*nnz+1))

      Do i = 1, nnz
        Read (nin,*) a(i), irowix(i)
      End Do

!     Read the right hand sides

      Do j = 1, nrhs
        Read (nin,*) x(1:n,j)
        b(1:n,j) = x(1:n,j)
      End Do

!     Calculate COLAMD permutation

      spec = 'M'

!     ifail: behaviour on error exit
!             =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
      ifail = 0
      Call f11mdf(spec,n,icolzp,irowix,iprm,ifail)

!     Factorise

      thresh = one
      ifail = 0
      nzlmx = 8*nnz
      nzlumx = 8*nnz
      nzumx = 8*nnz

      Call f11mef(n,irowix,a,iprm,thresh,nzlmx,nzlumx,nzumx,il,lval,iu,uval,   &
        nnzl,nnzu,flop,ifail)

!     Compute solution in array X

      trans = 'N'

      ifail = 0
      Call f11mff(trans,n,iprm,il,lval,iu,uval,nrhs,x,ldx,ifail)

!     Improve solution, and compute backward errors and estimated
!     bounds on the forward errors

      Call f11mhf(trans,n,icolzp,irowix,a,iprm,il,lval,iu,uval,nrhs,b,ldb,x,   &
        ldx,ferr,berr,ifail)

!     Print solution

      Write (nout,*)
      Flush (nout)

      Call x04caf('G',' ',n,nrhs,x,ldx,'Solutions',ifail)
      Call x04cbf('G','X',nrhs,1,ferr,nrhs,'1PE8.1','Estimated Forward Error', &
        'N',rlabs,'N',clabs,80,0,ifail)
      Call x04cbf('G','X',nrhs,1,berr,nrhs,'1PE8.1','Backward Error','N',      &
        rlabs,'N',clabs,80,0,ifail)

    End Program f11mhfe


f11mkfe.f90

    Program f11mkfe

!     F11MKF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: f11mkf, nag_wp, x04caf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Real (Kind=nag_wp), Parameter    :: alpha = 1.E0_nag_wp
      Real (Kind=nag_wp), Parameter    :: beta = 0.E0_nag_wp
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Integer                          :: i, ifail, j, ldb, ldc, m, n, nnz
      Character (1)                    :: trans
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: a(:), b(:,:), c(:,:)
      Integer, Allocatable             :: icolzp(:), irowix(:)
!     .. Executable Statements ..
      Write (nout,*) 'F11MKF Example Program Results'
!     Skip heading in data file
      Read (nin,*)

!     Read order of matrix

      Read (nin,*) n, m
      ldb = n
      ldc = n

      Allocate (b(ldb,m),c(ldc,m),icolzp(n+1))

!     Read the matrix A

      Read (nin,*) icolzp(1:n+1)
      nnz = icolzp(n+1) - 1

      Allocate (a(nnz),irowix(nnz))

      Do i = 1, nnz
        Read (nin,*) a(i), irowix(i)
      End Do

!     Read the matrix B

      Do j = 1, m
        Read (nin,*) b(1:n,j)
      End Do

!     Calculate matrix-matrix product

      trans = 'N'

!     ifail: behaviour on error exit
!             =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
      ifail = 0
      Call f11mkf(trans,n,m,alpha,icolzp,irowix,a,b,ldb,beta,c,ldc,ifail)

!     Output results
      Write (nout,*)
      Flush (nout)

      Call x04caf('G',' ',n,m,c,ldc,'Matrix-matrix product',ifail)

!     Calculate transposed matrix-matrix product
      trans = 'T'

      ifail = 0
      Call f11mkf(trans,n,m,alpha,icolzp,irowix,a,b,ldb,beta,c,ldc,ifail)

!     Output results
      Write (nout,*)
      Flush (nout)

      Call x04caf('G',' ',n,m,c,ldc,'Transposed matrix-matrix product',ifail)

    End Program f11mkfe


f11mlfe.f90

    Program f11mlfe

!     F11MLF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: f11mlf, nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: anorm
      Integer                          :: i, ifail, n, nnz
      Character (1)                    :: norm
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: a(:)
      Integer, Allocatable             :: icolzp(:), irowix(:)
!     .. Executable Statements ..
      Write (nout,*) 'F11MLF Example Program Results'
!     Skip heading in data file
      Read (nin,*)

!     Read order of matrix and number of right hand sides

      Read (nin,*) n

      Allocate (icolzp(n+1))

!     Read the matrix A

      Read (nin,*) icolzp(1:n+1)
      nnz = icolzp(n+1) - 1

      Allocate (a(nnz),irowix(nnz))

      Do i = 1, nnz
        Read (nin,*) a(i), irowix(i)
      End Do

!     Calculate 1-norm

      norm = '1'

!     ifail: behaviour on error exit
!             =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
      ifail = 0
      Call f11mlf(norm,anorm,n,icolzp,irowix,a,ifail)

!     Output norm

      Write (nout,*)
      Write (nout,*) 'One-norm'
      Write (nout,'(F7.3)') anorm

!     Calculate M-norm

      norm = 'M'

      ifail = 0
      Call f11mlf(norm,anorm,n,icolzp,irowix,a,ifail)

!     Output norm

      Write (nout,*)
      Write (nout,*) 'Max'
      Write (nout,'(F7.3)') anorm

!     Calculate I-norm

      norm = 'I'

      ifail = 0
      Call f11mlf(norm,anorm,n,icolzp,irowix,a,ifail)

!     Output norm

      Write (nout,*)
      Write (nout,*) 'Infinity-norm'
      Write (nout,'(F7.3)') anorm

    End Program f11mlfe


f11mmfe.f90

    Program f11mmfe

!     F11MMF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: f11mdf, f11mef, f11mmf, nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Real (Kind=nag_wp), Parameter    :: one = 1.E0_nag_wp
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: flop, rpg, thresh
      Integer                          :: i, ifail, n, nnz, nnzl, nnzu, nzlmx, &
                                          nzlumx, nzumx
      Character (1)                    :: spec
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: a(:), lval(:), uval(:)
      Integer, Allocatable             :: icolzp(:), il(:), iprm(:),           &
                                          irowix(:), iu(:)
!     .. Executable Statements ..
      Write (nout,*) 'F11MMF Example Program Results'
!     Skip heading in data file
      Read (nin,*)

!     Read order of matrix

      Read (nin,*) n

      Allocate (icolzp(n+1),iprm(7*n))

!     Read the matrix A

      Read (nin,*) icolzp(1:n+1)
      nnz = icolzp(n+1) - 1

      Allocate (a(nnz),lval(8*nnz),uval(8*nnz),il(7*n+8*nnz+4),irowix(nnz),    &
        iu(2*n+8*nnz+1))

      Do i = 1, nnz
        Read (nin,*) a(i), irowix(i)
      End Do

!     Calculate COLAMD permutation

      spec = 'M'

!     ifail: behaviour on error exit
!             =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
      ifail = 0
      Call f11mdf(spec,n,icolzp,irowix,iprm,ifail)

!     Factorise

      thresh = one
      ifail = 0
      nzlmx = 8*nnz
      nzlumx = 8*nnz
      nzumx = 8*nnz

      Call f11mef(n,irowix,a,iprm,thresh,nzlmx,nzlumx,nzumx,il,lval,iu,uval,   &
        nnzl,nnzu,flop,ifail)

!     Calculate reciprocal pivot growth

      ifail = 0
      Call f11mmf(n,icolzp,a,iprm,il,lval,iu,uval,rpg,ifail)

!     Output result

      Write (nout,*)
      Write (nout,*) 'Reciprocal pivot growth'
      Write (nout,'(F7.3)') rpg

    End Program f11mmfe


f11xafe.f90

    Program f11xafe

!     F11XAF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: f11xaf, nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Integer                          :: i, ifail, n, nnz
      Character (1)                    :: check, trans
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: a(:), x(:), y(:)
      Integer, Allocatable             :: icol(:), irow(:)
!     .. Executable Statements ..
      Write (nout,*) 'F11XAF Example Program Results'
!     Skip heading in data file
      Read (nin,*)

!     Read order of matrix and number of nonzero entries

      Read (nin,*) n
      Read (nin,*) nnz

      Allocate (a(nnz),x(n),y(n),icol(nnz),irow(nnz))

!     Read the matrix A

      Do i = 1, nnz
        Read (nin,*) a(i), irow(i), icol(i)
      End Do

!     Read the vector x

      Read (nin,*) x(1:n)

!     Calculate matrix-vector product

      trans = 'N'
      check = 'C'

!     ifail: behaviour on error exit
!             =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
      ifail = 0
      Call f11xaf(trans,n,nnz,a,irow,icol,check,x,y,ifail)

!     Output results

      Write (nout,*)
      Write (nout,*) ' Matrix-vector product'
      Write (nout,'(E16.4)') y(1:n)

!     Calculate transposed matrix-vector product

      trans = 'T'
      check = 'N'

      ifail = 0
      Call f11xaf(trans,n,nnz,a,irow,icol,check,x,y,ifail)

!     Output results

      Write (nout,*)
      Write (nout,*) ' Transposed matrix-vector product'
      Write (nout,'(E16.4)') y(1:n)

    End Program f11xafe


f11xefe.f90

    Program f11xefe

!     F11XEF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: f11xef, nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Integer                          :: i, ifail, n, nnz
      Character (1)                    :: check
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: a(:), x(:), y(:)
      Integer, Allocatable             :: icol(:), irow(:)
!     .. Executable Statements ..
      Write (nout,*) 'F11XEF Example Program Results'
!     Skip heading in data file
      Read (nin,*)

!     Read order of matrix and number of nonzero entries

      Read (nin,*) n
      Read (nin,*) nnz

      Allocate (a(nnz),x(n),y(n),icol(nnz),irow(nnz))

!     Read the matrix A

      Do i = 1, nnz
        Read (nin,*) a(i), irow(i), icol(i)
      End Do

!     Read the vector x

      Read (nin,*) x(1:n)

!     Calculate matrix-vector product

      check = 'C'

!     ifail: behaviour on error exit
!             =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
      ifail = 0
      Call f11xef(n,nnz,a,irow,icol,check,x,y,ifail)

!     Output results

      Write (nout,*) ' Matrix-vector product'
      Write (nout,99999) y(1:n)

99999 Format (1X,E16.4)
    End Program f11xefe


f11xnfe.f90

    Program f11xnfe

!     F11XNF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: f11xnf, nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Integer                          :: i, ifail, n, nnz
      Character (1)                    :: check, trans
!     .. Local Arrays ..
      Complex (Kind=nag_wp), Allocatable :: a(:), x(:), y(:)
      Integer, Allocatable             :: icol(:), irow(:)
!     .. Executable Statements ..
      Write (nout,*) 'F11XNF Example Program Results'
!     Skip heading in data file
      Read (nin,*)

!     Read order of matrix and number of nonzero entries

      Read (nin,*) n
      Read (nin,*) nnz

      Allocate (a(nnz),x(n),y(n),icol(nnz),irow(nnz))

!     Read the matrix A

      Do i = 1, nnz
        Read (nin,*) a(i), irow(i), icol(i)
      End Do

!     Read the vector x

      Read (nin,*) x(1:n)

!     Calculate matrix-vector product

      trans = 'N'
      check = 'C'

!     ifail: behaviour on error exit
!             =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
      ifail = 0
      Call f11xnf(trans,n,nnz,a,irow,icol,check,x,y,ifail)

!     Output results

      Write (nout,*)
      Write (nout,*) ' Matrix-vector product'
      Write (nout,'(1X,''('',E16.4,'','',E16.4,'')'')') y(1:n)

!     Calculate conjugate transposed matrix-vector product

      trans = 'T'
      check = 'N'

      ifail = 0
      Call f11xnf(trans,n,nnz,a,irow,icol,check,x,y,ifail)

!     Output results

      Write (nout,*)
      Write (nout,*) ' Conjugate transposed matrix-vector product'
      Write (nout,'(1X,''('',E16.4,'','',E16.4,'')'')') y(1:n)

    End Program f11xnfe


f11xsfe.f90

    Program f11xsfe

!     F11XSF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: f11xsf, nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Integer                          :: i, ifail, n, nnz
      Character (1)                    :: check
!     .. Local Arrays ..
      Complex (Kind=nag_wp), Allocatable :: a(:), x(:), y(:)
      Integer, Allocatable             :: icol(:), irow(:)
!     .. Executable Statements ..
      Write (nout,*) 'F11XSF Example Program Results'
!     Skip heading in data file
      Read (nin,*)

!     Read order of matrix and number of nonzero entries

      Read (nin,*) n
      Read (nin,*) nnz

      Allocate (a(nnz),x(n),y(n),icol(nnz),irow(nnz))

!     Read the matrix A

      Do i = 1, nnz
        Read (nin,*) a(i), irow(i), icol(i)
      End Do

!     Read the vector x

      Read (nin,*) x(1:n)

!     Calculate matrix-vector product

      check = 'C'

!     ifail: behaviour on error exit
!             =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
      ifail = 0
      Call f11xsf(n,nnz,a,irow,icol,check,x,y,ifail)

!     Output results

      Write (nout,*) ' Matrix-vector product'
      Write (nout,99999) y(1:n)

99999 Format (1X,'(',E16.4,',',E16.4,')')
    End Program f11xsfe


f11yefe.f90

    Program f11yefe

!     F11YEF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: f11yef, nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
      Logical, Parameter               :: plotdata = .False.
!     .. Local Scalars ..
      Integer                          :: ifail, n, nnz
      Logical                          :: bw_after, bw_before, check_sym,      &
                                          do_cm, use_mask
!     .. Local Arrays ..
      Integer, Allocatable             :: icolzp(:), irowix(:), mask(:),       &
                                          perm(:)
      Integer                          :: info(4)
      Logical                          :: lopts(5)
!     .. Executable Statements ..
      Write (nout,*) 'F11YEF Example Program Results'

!     Skip heading in data file

      Read (nin,*)

!     Size of the matrix
      Read (nin,*) n

!     Number of nonzero elements
      Read (nin,*) nnz

      Allocate (icolzp(n+1),irowix(nnz),mask(n),perm(n))

!     Read in data
      Read (nin,*) irowix(1:nnz)
      Read (nin,*) icolzp(1:n+1)

!     Set options
      use_mask = .False.
      do_cm = .False.
      check_sym = .True.
      bw_before = .True.
      bw_after = .True.
      lopts(1:5) = (/use_mask,do_cm,check_sym,bw_before,bw_after/)

!     ifail: behaviour on error exit
!     =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
      ifail = 0
      Call f11yef(n,nnz,icolzp,irowix,lopts,mask,perm,info,ifail)

!     Print results
      Write (nout,'(A)') 'Permutation (perm):'
      Write (nout,99999) perm(1:n)

      Write (nout,*)
      Write (nout,'(A)') 'Statistics:'
      Write (nout,'(A,I6)') '  Before:  Bandwidth = ', info(1)
      Write (nout,'(A,I6)') '  Before:  Profile   = ', info(2)
      Write (nout,'(A,I6)') '  After :  Bandwidth = ', info(3)
      Write (nout,'(A,I6)') '  After :  Profile   = ', info(4)

!     Print matrix entries and permuted entries in form suitable for printing
      If (plotdata) Then
        Call plot(n,nnz)
      End If

99999 Format (6(4X,I3))

    Contains
      Subroutine uncompress(n,nnz,icolzp,icol)

!       .. Implicit None Statement ..
        Implicit None
!       .. Scalar Arguments ..
        Integer, Intent (In)           :: n, nnz
!       .. Array Arguments ..
        Integer, Intent (Out)          :: icol(nnz)
        Integer, Intent (In)           :: icolzp(n+1)
!       .. Local Scalars ..
        Integer                        :: col_beg, col_end, i
!       .. Executable Statements ..
        Do i = 1, n
          col_end = icolzp(i+1) - 1
          col_beg = icolzp(i)
          If (col_end>=col_beg) Then
            icol(col_beg:col_end) = i
          End If
        End Do
        Return
      End Subroutine uncompress
      Subroutine plot(n,nnz)
!       Put data, suitable for plotting matrix structure, in data file

!       .. Use Statements ..
        Use nag_library, Only: f11zaf
!       .. Implicit None Statement ..
        Implicit None
!       .. Scalar Arguments ..
        Integer, Intent (In)           :: n, nnz
!       .. Local Scalars ..
        Integer                        :: i, ifail, nnz2
!       .. Local Arrays ..
        Real (Kind=nag_wp), Allocatable :: a(:)
        Integer, Allocatable           :: icolix(:), ipcolix(:), iperm(:),     &
                                          iprowix(:), istr(:), iwork(:)
!       .. Executable Statements ..

        Allocate (icolix(nnz),ipcolix(nnz),iprowix(nnz))
        Allocate (iperm(n),a(nnz),istr(n+1),iwork(n))

!       Decompress icolzp to full set of column indices and invert perm
        Call uncompress(n,nnz,icolzp,icolix)
        Do i = 1, n
          iperm(perm(i)) = i
        End Do

!       Give some nice values, encoding original position
        Do i = 1, nnz
          a(i) = icolix(i)*.01_nag_wp + 1.0_nag_wp*irowix(i)
        End Do

!       Original matrix structure
        Write (*,'(I8,4X,I8,4X,F8.2)')(irowix(i),icolix(i),a(i),i=1,nnz)
        Write (*,'(/)')

!       Permute
        Do i = 1, nnz
          a(i) = icolix(i)*.01_nag_wp + 1.0_nag_wp*irowix(i)
          ipcolix(i) = iperm(icolix(i))
          iprowix(i) = iperm(irowix(i))
        End Do

!       Reorder (in exit: istr contains new CCS icolzp)
        nnz2 = nnz
        ifail = 0
        Call f11zaf(n,nnz2,a,ipcolix,iprowix,'F','K',istr,iwork,ifail)

!       Permuted matrix structure
        Write (*,'(I8,4X,I8,4X,F8.2)')(iprowix(i),ipcolix(i),a(i),i=1,nnz2)
        Deallocate (icolix,ipcolix,iprowix,iperm,a,istr,iwork)

        Return

      End Subroutine plot
    End Program f11yefe


f11zafe.f90

    Program f11zafe

!     F11ZAF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: f11mlf, f11zaf, nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: anorm
      Integer                          :: i, ifail, n, nnz
      Character (1)                    :: dup, norm, zer
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: a(:)
      Integer, Allocatable             :: icol(:), irow(:), istr(:), iwork(:)
!     .. Executable Statements ..
      Write (nout,*) 'F11ZAF Example Program Results'
      Write (nout,*)
!     Skip heading in data file
      Read (nin,*)

!     Read order of matrix and number of nonzero entries

      Read (nin,*) n
      Read (nin,*) nnz

      Allocate (a(nnz),icol(nnz),irow(nnz),istr(n+1),iwork(n))

!     Read and output the original nonzero elements

      Do i = 1, nnz
        Read (nin,*) a(i), irow(i), icol(i)
      End Do
      Write (nout,*) 'Original elements'
      Write (nout,99999) nnz
      Write (nout,99997)
      Do i = 1, nnz
        Write (nout,99998) i, a(i), irow(i), icol(i)
      End Do

!     Reorder, sum duplicates and remove zeros

      dup = 'S'
      zer = 'R'

!     ifail: behaviour on error exit
!             =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
      ifail = 0
      Call f11zaf(n,nnz,a,irow,icol,dup,zer,istr,iwork,ifail)

!     Output results

      Write (nout,*) 'Reordered elements, along rows first'
      Write (nout,99999) nnz
      Do i = 1, nnz
        Write (nout,99998) i, a(i), irow(i), icol(i)
      End Do

!     Reorder down columns, fail on duplicates or zeros.
!     Creates CCS storage format as side-effect

      dup = 'F'
      zer = 'F'
      ifail = 0

      Call f11zaf(n,nnz,a,icol,irow,dup,zer,istr,iwork,ifail)

!     Output results

      Write (nout,*) 'Reordered elements, along columns first'
      Write (nout,99999) nnz
      Do i = 1, nnz
        Write (nout,99998) i, a(i), irow(i), icol(i)
      End Do
      Write (nout,99996)
      Do i = 1, n + 1
        Write (nout,99995) i, istr(i)
      End Do

!     Calculate 1-norm in Compressed Column Storage format

      norm = '1'
      Call f11mlf(norm,anorm,n,istr,irow,a,ifail)

!     Output norm

      Write (nout,99994) anorm

99999 Format (1X,'NNZ = ',I4)
99998 Format (1X,I8,1P,E16.4,2I8)
99997 Format (24X,'A',4X,'IROW',4X,'ICOL')
99996 Format (13X,'ISTR')
99995 Format (1X,2I8)
99994 Format (1X,'One norm ',1P,E16.4)
    End Program f11zafe


f11zbfe.f90

    Program f11zbfe

!     F11ZBF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: f11zbf, nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Integer                          :: i, ifail, n, nnz
      Character (1)                    :: dup, zer
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: a(:)
      Integer, Allocatable             :: icol(:), irow(:), istr(:), iwork(:)
!     .. Executable Statements ..
      Write (nout,*) 'F11ZBF Example Program Results'
!     Skip heading in data file
      Read (nin,*)

!     Read order of matrix and number of nonzero entries

      Read (nin,*) n
      Read (nin,*) nnz

      Allocate (a(nnz),icol(nnz),irow(nnz),istr(n+1),iwork(n))

!     Read and output the original nonzero elements

      Do i = 1, nnz
        Read (nin,*) a(i), irow(i), icol(i)
      End Do
      Write (nout,*) 'Original elements'
      Write (nout,99997) 'NNZ = ', nnz
      Do i = 1, nnz
        Write (nout,99998) i, a(i), irow(i), icol(i)
      End Do

!     Reorder, sum duplicates and remove zeros

      dup = 'S'
      zer = 'R'

!     ifail: behaviour on error exit
!             =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
      ifail = 0
      Call f11zbf(n,nnz,a,irow,icol,dup,zer,istr,iwork,ifail)

!     Output results

      Write (nout,*) 'Reordered elements'
      Write (nout,99999) 'NNZ = ', nnz
      Do i = 1, nnz
        Write (nout,99998) i, a(i), irow(i), icol(i)
      End Do

99999 Format (1X,A,I4)
99998 Format (1X,I8,E16.4,2I8)
99997 Format (1X,A,I16)
    End Program f11zbfe


f11znfe.f90

    Program f11znfe

!     F11ZNF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: f11znf, nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Integer                          :: i, ifail, n, nnz
      Character (1)                    :: dup, zer
!     .. Local Arrays ..
      Complex (Kind=nag_wp), Allocatable :: a(:)
      Integer, Allocatable             :: icol(:), irow(:), istr(:), iwork(:)
!     .. Executable Statements ..
      Write (nout,*) 'F11ZNF Example Program Results'
      Write (nout,*)
!     Skip heading in data file
      Read (nin,*)

!     Read order of matrix and number of nonzero entries

      Read (nin,*) n
      Read (nin,*) nnz

      Allocate (a(nnz),icol(nnz),irow(nnz),istr(n+1),iwork(n))

!     Read and output the original nonzero elements

      Do i = 1, nnz
        Read (nin,*) a(i), irow(i), icol(i)
      End Do
      Write (nout,*) 'Original elements'
      Write (nout,99999) ' NNZ = ', nnz
      Do i = 1, nnz
        Write (nout,99998) i, a(i), irow(i), icol(i)
      End Do

!     Reorder, sum duplicates and remove zeros

      dup = 'S'
      zer = 'R'

!     ifail: behaviour on error exit
!             =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
      ifail = 0
      Call f11znf(n,nnz,a,irow,icol,dup,zer,istr,iwork,ifail)

!     Output results

      Write (nout,*) 'Reordered elements'
      Write (nout,99999) ' NNZ = ', nnz
      Do i = 1, nnz
        Write (nout,99998) i, a(i), irow(i), icol(i)
      End Do

99999 Format (1X,A,I4)
99998 Format (1X,I8,5X,'(',E16.4,',',E16.4,')',2I8)
    End Program f11znfe


f11zpfe.f90

    Program f11zpfe

!     F11ZPF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: f11zpf, nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Integer                          :: i, ifail, n, nnz
      Character (1)                    :: dup, zer
!     .. Local Arrays ..
      Complex (Kind=nag_wp), Allocatable :: a(:)
      Integer, Allocatable             :: icol(:), irow(:), istr(:), iwork(:)
!     .. Executable Statements ..
      Write (nout,*) 'F11ZPF Example Program Results'
!     Skip heading in data file
      Read (nin,*)

!     Read order of matrix and number of nonzero entries

      Read (nin,*) n
      Read (nin,*) nnz

      Allocate (a(nnz),icol(nnz),irow(nnz),istr(n+1),iwork(n))

!     Read and output the original nonzero elements

      Do i = 1, nnz
        Read (nin,*) a(i), irow(i), icol(i)
      End Do
      Write (nout,*) 'Original elements'
      Write (nout,99997) 'NNZ = ', nnz
      Do i = 1, nnz
        Write (nout,99998) i, a(i), irow(i), icol(i)
      End Do

!     Reorder, sum duplicates and remove zeros

      dup = 'S'
      zer = 'R'

!     ifail: behaviour on error exit
!             =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
      ifail = 0
      Call f11zpf(n,nnz,a,irow,icol,dup,zer,istr,iwork,ifail)

!     Output results

      Write (nout,*) 'Reordered elements'
      Write (nout,99999) 'NNZ = ', nnz
      Do i = 1, nnz
        Write (nout,99998) i, a(i), irow(i), icol(i)
      End Do

99999 Format (1X,A,I4)
99998 Format (I8,5X,'(',E16.4,',',E16.4,')',2I8)
99997 Format (1X,A,I16)
    End Program f11zpfe


f12aafe.f90

!   F12AAF Example Program Text
!   Mark 26 Release. NAG Copyright 2016.

    Module f12aafe_mod

!     F12AAF Example Program Module:
!            Parameters and User-defined Routines

!     .. Use Statements ..
      Use nag_library, Only: nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Accessibility Statements ..
      Private
      Public                           :: av
!     .. Parameters ..
      Integer, Parameter, Public       :: imon = 0, ipoint = 0, nin = 5,       &
                                          nout = 6
    Contains
      Subroutine tv(nx,x,y)
!       Compute the matrix vector multiplication y<---T*x where T is a nx
!       by nx tridiagonal matrix with constant diagonals (DD, DL and DU).

!       .. Parameters ..
        Real (Kind=nag_wp), Parameter  :: half = 0.5_nag_wp
        Real (Kind=nag_wp), Parameter  :: rho = 100.0_nag_wp
!       .. Scalar Arguments ..
        Integer, Intent (In)           :: nx
!       .. Array Arguments ..
        Real (Kind=nag_wp), Intent (In) :: x(nx)
        Real (Kind=nag_wp), Intent (Out) :: y(nx)
!       .. Local Scalars ..
        Real (Kind=nag_wp)             :: dd, dl, du, nx1, nx2
        Integer                        :: j
!       .. Intrinsic Procedures ..
        Intrinsic                      :: real
!       .. Executable Statements ..
        nx1 = real(nx+1,kind=nag_wp)
        nx2 = nx1*nx1
        dd = 4.0_nag_wp*nx2
        dl = -nx2 - half*rho*nx1
        du = -nx2 + half*rho*nx1
        y(1) = dd*x(1) + du*x(2)
        Do j = 2, nx - 1
          y(j) = dl*x(j-1) + dd*x(j) + du*x(j+1)
        End Do
        y(nx) = dl*x(nx-1) + dd*x(nx)
        Return
      End Subroutine tv
      Subroutine av(nx,v,w)

!       .. Use Statements ..
        Use nag_library, Only: daxpy
!       .. Scalar Arguments ..
        Integer, Intent (In)           :: nx
!       .. Array Arguments ..
        Real (Kind=nag_wp), Intent (In) :: v(nx*nx)
        Real (Kind=nag_wp), Intent (Out) :: w(nx*nx)
!       .. Local Scalars ..
        Real (Kind=nag_wp)             :: nx2
        Integer                        :: j, lo
!       .. Intrinsic Procedures ..
        Intrinsic                      :: real
!       .. Executable Statements ..
        nx2 = -real((nx+1)*(nx+1),kind=nag_wp)
        Call tv(nx,v(1),w(1))
!       The NAG name equivalent of daxpy is f06ecf
        Call daxpy(nx,nx2,v(nx+1),1,w(1),1)
        Do j = 2, nx - 1
          lo = (j-1)*nx
          Call tv(nx,v(lo+1),w(lo+1))
          Call daxpy(nx,nx2,v(lo-nx+1),1,w(lo+1),1)
          Call daxpy(nx,nx2,v(lo+nx+1),1,w(lo+1),1)
        End Do
        lo = (nx-1)*nx
        Call tv(nx,v(lo+1),w(lo+1))
        Call daxpy(nx,nx2,v(lo-nx+1),1,w(lo+1),1)
        Return
      End Subroutine av
    End Module f12aafe_mod
    Program f12aafe

!     F12AAF Example Main Program

!     .. Use Statements ..
      Use nag_library, Only: dnrm2, f12aaf, f12abf, f12acf, f12adf, f12aef,    &
                             nag_wp
      Use f12aafe_mod, Only: av, imon, ipoint, nin, nout
!     .. Implicit None Statement ..
      Implicit None
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: sigmai, sigmar
      Integer                          :: i, ifail, ifail1, irevcm, lcomm,     &
                                          ldv, licomm, n, nconv, ncv, nev,     &
                                          niter, nshift, nx
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: ax(:), comm(:), d(:,:), mx(:),       &
                                          resid(:), v(:,:), x(:)
      Integer, Allocatable             :: icomm(:)
!     .. Executable Statements ..
      Write (nout,*) 'F12AAF Example Program Results'
      Write (nout,*)
!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) nx, nev, ncv
      n = nx*nx
      ldv = n
      lcomm = 3*n + 3*ncv*ncv + 6*ncv + 60
      licomm = 140
      Allocate (ax(n),comm(lcomm),d(ncv,3),mx(n),resid(n),v(ldv,ncv),x(n),     &
        icomm(licomm))

!     ifail: behaviour on error exit
!             =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
      ifail = 0
      Call f12aaf(n,nev,ncv,icomm,licomm,comm,lcomm,ifail)

!     Set the region of the spectrum that is required.
      ifail = 0
      Call f12adf('SMALLEST MAG',icomm,comm,ifail)

      If (ipoint/=0) Then

!       Use pointers to workspace in calculating matrix vector products
!       rather than interfacing through the array X.
        ifail = 0
        Call f12adf('POINTERS=YES',icomm,comm,ifail)

      End If

      irevcm = 0
      ifail = -1
loop: Do
        Call f12abf(irevcm,resid,v,ldv,x,mx,nshift,comm,icomm,ifail)

        If (irevcm/=5) Then
          If (irevcm==-1 .Or. irevcm==1) Then
!           Perform matrix vector multiplication y <--- Op*x
            If (ipoint==0) Then

              Call av(nx,x,ax)
              x(1:n) = ax(1:n)

            Else

              Call av(nx,comm(icomm(1)),comm(icomm(2)))

            End If
          Else If (irevcm==4 .And. imon/=0) Then

!           Set IMON=1 to output monitoring information.
            Call f12aef(niter,nconv,d,d(1,2),d(1,3),icomm,comm)

!           The NAG name equivalent of dnrm2 is f06ejf
            Write (6,99999) niter, nconv, dnrm2(nev,d(1,3),1)
          End If
        Else
          Exit loop
        End If
      End Do loop

      If (ifail==0) Then

!       Post-Process using F12ACF to compute eigenvalues and
!       (by default) the corresponding eigenvectors.
        ifail1 = 0
        Call f12acf(nconv,d,d(1,2),v,ldv,sigmar,sigmai,resid,v,ldv,comm,icomm, &
          ifail1)

        Write (nout,99998) nconv
        Do i = 1, nconv
          Write (nout,99997) i, d(i,1), d(i,2)
        End Do
      End If

99999 Format (1X,'Iteration',1X,I3,', No. converged =',1X,I3,', norm o',       &
        'f estimates =',E16.8)
99998 Format (1X,/,' The ',I4,' Ritz values of smallest magnitude are:',/)
99997 Format (1X,I8,5X,'( ',F12.4,' , ',F12.4,' )')
    End Program f12aafe


f12abfe.f90

    Program f12abfe

!     F12ABF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: dgttrf, dgttrs, dnrm2, f12aaf, f12abf, f12acf,    &
                             f12adf, f12aef, nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Real (Kind=nag_wp), Parameter    :: one = 1.0_nag_wp
      Real (Kind=nag_wp), Parameter    :: two = 2.0_nag_wp
      Integer, Parameter               :: imon = 0, nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: h, rho, s, s1, s2, s3, sigmai,       &
                                          sigmar
      Integer                          :: i, ifail, ifail1, info, irevcm,      &
                                          lcomm, ldv, licomm, n, nconv, ncv,   &
                                          nev, niter, nshift, nx
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: comm(:), d(:,:), dd(:), dl(:),       &
                                          du(:), du2(:), mx(:), resid(:),      &
                                          v(:,:), x(:)
      Integer, Allocatable             :: icomm(:), ipiv(:)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: real
!     .. Executable Statements ..
      Write (nout,*) 'F12ABF Example Program Results'
      Write (nout,*)
!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) nx, nev, ncv, rho, sigmar, sigmai
      n = nx*nx
      ldv = n
      licomm = 140
      lcomm = 3*n + 3*ncv*ncv + 6*ncv + 60
      Allocate (comm(lcomm),d(ncv,3),dd(n),dl(n),du(n),du2(n),mx(n),resid(n),  &
        v(ldv,ncv),x(n),icomm(licomm),ipiv(n))

!     ifail: behaviour on error exit
!             =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
      ifail = 0
      Call f12aaf(n,nev,ncv,icomm,licomm,comm,lcomm,ifail)

!     Set the mode.
      ifail = 0
      Call f12adf('SHIFTED INVERSE REAL',icomm,comm,ifail)

!     Construct C = A - SIGMA*I, and factorize using DGTTRF/F07CDF.
      h = one/real(n+1,kind=nag_wp)
      s = rho*h/two
      s1 = -one - s
      s2 = two - sigmar
      s3 = -one + s
      dl(1:n-1) = s1
      dd(1:n-1) = s2
      du(1:n-1) = s3
      dd(n) = s2

!     The NAG name equivalent of dgttrf is f07cdf
      Call dgttrf(n,dl,dd,du,du2,ipiv,info)

      irevcm = 0
      ifail = -1
loop: Do
        Call f12abf(irevcm,resid,v,ldv,x,mx,nshift,comm,icomm,ifail)

        If (irevcm/=5) Then
          If (irevcm==-1 .Or. irevcm==1) Then
!           Perform  x <--- OP*x = inv[A-SIGMA*I]*x.
!           The NAG name equivalent of dgttrs is f07cef
            Call dgttrs('N',n,1,dl,dd,du,du2,ipiv,x,n,info)
          Else If (irevcm==4 .And. imon/=0) Then
!           Output monitoring information
            Call f12aef(niter,nconv,d,d(1,2),d(1,3),icomm,comm)
!           The NAG name equivalent of dnrm2 is f06ejf
            Write (6,99999) niter, nconv, dnrm2(nev,d(1,3),1)
          End If
        Else
          Exit loop
        End If
      End Do loop
      If (ifail==0) Then
!       Post-Process using F12ACF to compute eigenvalues/vectors.
        ifail1 = 0
        Call f12acf(nconv,d,d(1,2),v,ldv,sigmar,sigmai,resid,v,ldv,comm,icomm, &
          ifail1)
!       Print computed eigenvalues.
        Write (nout,99998) nconv
        Do i = 1, nconv
          Write (nout,99997) i, d(i,1), d(i,2)
        End Do
      End If

99999 Format (1X,'Iteration',1X,I3,', No. converged =',1X,I3,', norm o',       &
        'f estimates =',E16.8)
99998 Format (1X,/,' The ',I4,' Ritz values of closest to unity are:',/)
99997 Format (1X,I8,5X,'( ',F12.4,' , ',F12.4,' )')
    End Program f12abfe


f12acfe.f90

!   F12ACF Example Program Text
!   Mark 26 Release. NAG Copyright 2016.

    Module f12acfe_mod

!     F12ACF Example Program Module:
!            Parameters and User-defined Routines

!     .. Use Statements ..
      Use nag_library, Only: nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Accessibility Statements ..
      Private
      Public                           :: av, mv
!     .. Parameters ..
      Real (Kind=nag_wp), Parameter, Public :: one = 1.0_nag_wp
      Integer, Parameter, Public       :: imon = 0, nin = 5, nout = 6
    Contains
      Subroutine av(nx,rho,v,w)

!       .. Parameters ..
        Real (Kind=nag_wp), Parameter  :: two = 2.0_nag_wp
!       .. Scalar Arguments ..
        Real (Kind=nag_wp), Intent (In) :: rho
        Integer, Intent (In)           :: nx
!       .. Array Arguments ..
        Real (Kind=nag_wp), Intent (In) :: v(nx*nx)
        Real (Kind=nag_wp), Intent (Out) :: w(nx*nx)
!       .. Local Scalars ..
        Real (Kind=nag_wp)             :: dd, dl, du, h, s
        Integer                        :: j, n
!       .. Intrinsic Procedures ..
        Intrinsic                      :: real
!       .. Executable Statements ..
        n = nx*nx
        h = one/real(n+1,kind=nag_wp)
        s = rho/two
        dd = two/h
        dl = -one/h - s
        du = -one/h + s
        w(1) = dd*v(1) + du*v(2)
        Do j = 2, n - 1
          w(j) = dl*v(j-1) + dd*v(j) + du*v(j+1)
        End Do
        w(n) = dl*v(n-1) + dd*v(n)
        Return
      End Subroutine av

      Subroutine mv(nx,v,w)

!       .. Use Statements ..
        Use nag_library, Only: dscal
!       .. Parameters ..
        Real (Kind=nag_wp), Parameter  :: four = 4.0_nag_wp
!       .. Scalar Arguments ..
        Integer, Intent (In)           :: nx
!       .. Array Arguments ..
        Real (Kind=nag_wp), Intent (In) :: v(nx*nx)
        Real (Kind=nag_wp), Intent (Out) :: w(nx*nx)
!       .. Local Scalars ..
        Real (Kind=nag_wp)             :: h
        Integer                        :: j, n
!       .. Intrinsic Procedures ..
        Intrinsic                      :: real
!       .. Executable Statements ..
        n = nx*nx
        w(1) = four*v(1) + one*v(2)
        Do j = 2, n - 1
          w(j) = one*v(j-1) + four*v(j) + one*v(j+1)
        End Do
        w(n) = one*v(n-1) + four*v(n)
        h = one/real(n+1,kind=nag_wp)
!       The NAG name equivalent of dscal is f06edf
        Call dscal(n,h,w,1)
        Return
      End Subroutine mv
    End Module f12acfe_mod

    Program f12acfe

!     F12ACF Example Main Program

!     .. Use Statements ..
      Use nag_library, Only: dnrm2, dpttrf, dpttrs, f12aaf, f12abf, f12acf,    &
                             f12adf, f12aef, nag_wp
      Use f12acfe_mod, Only: av, imon, mv, nin, nout, one
!     .. Implicit None Statement ..
      Implicit None
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: h, rho, sigmai, sigmar
      Integer                          :: ifail, ifail1, info, irevcm, j,      &
                                          lcomm, ldv, licomm, n, nconv, ncv,   &
                                          nev, niter, nshift, nx
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: comm(:), d(:,:), md(:), me(:),       &
                                          mx(:), resid(:), v(:,:), x(:)
      Integer, Allocatable             :: icomm(:)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: real
!     .. Executable Statements ..
      Write (nout,*) 'F12ACF Example Program Results'
      Write (nout,*)
!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) nx, nev, ncv, rho
      n = nx*nx
      ldv = n
      licomm = 140
      lcomm = 3*n + 3*ncv*ncv + 6*ncv + 60
      Allocate (comm(lcomm),d(ncv,3),md(n),me(n-1),mx(n),resid(n),v(ldv,ncv),  &
        x(n),icomm(licomm))

!     ifail: behaviour on error exit
!             =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
      ifail = 0
      Call f12aaf(n,nev,ncv,icomm,licomm,comm,lcomm,ifail)

!     Set the mode.
      ifail = 0
      Call f12adf('REGULAR INVERSE',icomm,comm,ifail)
!     Set problem type.
      Call f12adf('GENERALIZED',icomm,comm,ifail)
!     Use pointers to Workspace in calculating matrix vector
!     products rather than interfacing through the array X
      Call f12adf('POINTERS=YES',icomm,comm,ifail)

!     Construct M, and factorize using DPTTRF/F07JDF.
      h = one/real(n+1,kind=nag_wp)
      md(1:n-1) = 4.0_nag_wp*h
      me(1:n-1) = h
      md(n) = 4.0_nag_wp*h

!     The NAG name equivalent of dpttrf is f07jdf
      Call dpttrf(n,md,me,info)

      irevcm = 0

      ifail = -1
loop: Do
        Call f12abf(irevcm,resid,v,ldv,x,mx,nshift,comm,icomm,ifail)

        If (irevcm/=5) Then
          Select Case (irevcm)
          Case (-1,1)
!           Perform  y <--- OP*x = inv[M]*A*x using DPTTRS/F07JEF.
            Call av(nx,rho,comm(icomm(1)),comm(icomm(2)))
!           The NAG name equivalent of dpttrs is f07jef
            Call dpttrs(n,1,md,me,comm(icomm(2)),n,info)
          Case (2)
!           Perform  y <--- M*x.
            Call mv(nx,comm(icomm(1)),comm(icomm(2)))
          Case (4)
            If (imon/=0) Then
!             Output monitoring information if required.
              Call f12aef(niter,nconv,d,d(1,2),d(1,3),icomm,comm)
!             The NAG name equivalent of dnrm2 is f06ejf
              Write (6,99999) niter, nconv, dnrm2(nev,d(1,3),1)
            End If
          End Select
        Else
          Exit loop
        End If
      End Do loop
      If (ifail==0) Then
!       Post-Process using F12ACF to compute eigenvalues/vectors.
        ifail1 = 0
        Call f12acf(nconv,d,d(1,2),v,ldv,sigmar,sigmai,resid,v,ldv,comm,icomm, &
          ifail1)
!       Print computed eigenvalues.
        Write (nout,99998) nconv
        Do j = 1, nconv
          Write (nout,99997) j, d(j,1), d(j,2)
        End Do
      End If

99999 Format (1X,'Iteration',1X,I3,', No. converged =',1X,I3,', norm o',       &
        'f estimates =',E16.8)
99998 Format (1X,/,' The ',I4,' generalized Ritz values of largest ',          &
        'magnitude are:',/)
99997 Format (1X,I8,5X,'( ',F12.4,' , ',F12.4,' )')
    End Program f12acfe


f12adfe.f90

!   F12ADF Example Program Text
!   Mark 26 Release. NAG Copyright 2016.

    Module f12adfe_mod

!     F12ADF Example Program Module:
!            Parameters and User-defined Routines

!     .. Use Statements ..
      Use nag_library, Only: nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Accessibility Statements ..
      Private
      Public                           :: mv
!     .. Parameters ..
      Real (Kind=nag_wp), Parameter, Public :: four = 4.0_nag_wp
      Real (Kind=nag_wp), Parameter, Public :: one = 1.0_nag_wp
      Real (Kind=nag_wp), Parameter, Public :: six = 6.0_nag_wp
      Real (Kind=nag_wp), Parameter, Public :: two = 2.0_nag_wp
      Integer, Parameter, Public       :: imon = 0, nin = 5, nout = 6
    Contains
      Subroutine mv(n,v)
!       Compute the in-place matrix vector multiplication X<---M*X,
!       where M is mass matrix formed by using piecewise linear elements
!       on [0,1].

!       .. Use Statements ..
        Use nag_library, Only: dscal
!       .. Scalar Arguments ..
        Integer, Intent (In)           :: n
!       .. Array Arguments ..
        Real (Kind=nag_wp), Intent (Inout) :: v(n)
!       .. Local Scalars ..
        Real (Kind=nag_wp)             :: h, vm1, vv
        Integer                        :: j
!       .. Intrinsic Procedures ..
        Intrinsic                      :: real
!       .. Executable Statements ..
        vm1 = v(1)
        v(1) = (four*v(1)+v(2))/six
        Do j = 2, n - 1
          vv = v(j)
          v(j) = (vm1+four*vv+v(j+1))/six
          vm1 = vv
        End Do
        v(n) = (vm1+four*v(n))/six

        h = one/real(n+1,kind=nag_wp)
!       The NAG name equivalent of dscal is f06edf
        Call dscal(n,h,v,1)
        Return
      End Subroutine mv
    End Module f12adfe_mod

    Program f12adfe

!     F12ADF Example Main Program

!     .. Use Statements ..
      Use nag_library, Only: dgttrf, dgttrs, dnrm2, f12aaf, f12abf, f12acf,    &
                             f12adf, f12aef, nag_wp
      Use f12adfe_mod, Only: four, imon, mv, nin, nout, one, six, two
!     .. Implicit None Statement ..
      Implicit None
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: h, rho, s, s1, s2, s3, sigmai,       &
                                          sigmar
      Integer                          :: ifail, ifail1, info, irevcm, j,      &
                                          lcomm, ldv, licomm, n, nconv, ncv,   &
                                          nev, niter, nshift, nx
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: comm(:), d(:,:), dd(:), dl(:),       &
                                          du(:), du2(:), mx(:), resid(:),      &
                                          v(:,:), x(:)
      Integer, Allocatable             :: icomm(:), ipiv(:)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: real
!     .. Executable Statements ..
      Write (nout,*) 'F12ADF Example Program Results'
      Write (nout,*)
!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) nx, nev, ncv, rho, sigmar, sigmai
      n = nx*nx
      ldv = n
      licomm = 140
      lcomm = 3*n + 3*ncv*ncv + 6*ncv + 60
      Allocate (comm(lcomm),d(ncv,3),dd(n),dl(n),du(n),du2(n),mx(n),resid(n),  &
        v(ldv,ncv),x(n),icomm(licomm),ipiv(n))

!     ifail: behaviour on error exit
!             =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
      ifail = 0
      Call f12aaf(n,nev,ncv,icomm,licomm,comm,lcomm,ifail)

!     Set the mode.
      Call f12adf('SHIFTED REAL',icomm,comm,ifail)
!     Set problem type
      ifail = 0
      Call f12adf('GENERALIZED',icomm,comm,ifail)
!     Construct C = A - SIGMA*I, and factor C using DGTTRF/F07CDF.
      h = one/real(n+1,kind=nag_wp)
      s = rho/two
      s1 = -one/h - s - sigmar*h/six
      s2 = two/h - four*sigmar*h/six
      s3 = -one/h + s - sigmar*h/six
      dl(1:n-1) = s1
      dd(1:n-1) = s2
      du(1:n-1) = s3
      dd(n) = s2

!     The NAG name equivalent of dgttrf is f07cdf
      Call dgttrf(n,dl,dd,du,du2,ipiv,info)

      irevcm = 0

      ifail = -1
loop: Do
        Call f12abf(irevcm,resid,v,ldv,x,mx,nshift,comm,icomm,ifail)

        If (irevcm/=5) Then
          Select Case (irevcm)
          Case (-1)
!           Perform  x <--- OP*x = inv[A-SIGMA*M]*M*x.
            Call mv(n,x)
!           The NAG name equivalent of dgttrs is f07cef
            Call dgttrs('N',n,1,dl,dd,du,du2,ipiv,x,n,info)
          Case (1)
!           Perform  x <--- OP*x = inv[A-SIGMA*M]*M*x.
            Call dgttrs('N',n,1,dl,dd,du,du2,ipiv,mx,n,info)
            x(1:n) = mx(1:n)
          Case (2)
!           Perform  y <--- M*x
            Call mv(n,x)
          Case (4)
            If (imon/=0) Then
!             Output monitoring information
              Call f12aef(niter,nconv,d,d(1,2),d(1,3),icomm,comm)
!             The NAG name equivalent of dnrm2 is f06ejf
              Write (6,99999) niter, nconv, dnrm2(nev,d(1,3),1)
            End If
          End Select
        Else
          Exit loop
        End If
      End Do loop
      If (ifail==0) Then
!       Post-Process using F12ACF to compute eigenvalues/vectors.
        ifail1 = 0
        Call f12acf(nconv,d,d(1,2),v,ldv,sigmar,sigmai,resid,v,ldv,comm,icomm, &
          ifail1)
!       Print computed eigenvalues.
        Write (nout,99998) nconv
        Do j = 1, nconv
          Write (nout,99997) j, d(j,1), d(j,2)
        End Do
      End If

99999 Format (1X,'Iteration',1X,I3,', No. converged =',1X,I3,', norm o',       &
        'f estimates =',E16.8)
99998 Format (1X,/,' The ',I4,' generalized Ritz values closest to ',          &
        'unity are:',/)
99997 Format (1X,I8,5X,'( ',F12.4,' , ',F12.4,' )')
    End Program f12adfe


f12aefe.f90

!   F12AEF Example Program Text
!   Mark 26 Release. NAG Copyright 2016.

    Module f12aefe_mod

!     F12AEF Example Program Module:
!            Parameters and User-defined Routines

!     .. Use Statements ..
      Use nag_library, Only: nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Accessibility Statements ..
      Private
      Public                           :: av, mv
!     .. Parameters ..
      Real (Kind=nag_wp), Parameter, Public :: four = 4.0_nag_wp
      Real (Kind=nag_wp), Parameter, Public :: three = 3.0_nag_wp
      Real (Kind=nag_wp), Parameter, Public :: two = 2.0_nag_wp
      Real (Kind=nag_wp), Parameter, Public :: zero = 0.0_nag_wp
      Integer, Parameter, Public       :: nin = 5, nout = 6
    Contains
      Subroutine mv(n,v)
!       Compute the in-place matrix vector multiplication X<---M*X,
!       where M is mass matrix formed by using piecewise linear elements
!       on [0,1].

!       .. Scalar Arguments ..
        Integer, Intent (In)           :: n
!       .. Array Arguments ..
        Real (Kind=nag_wp), Intent (Inout) :: v(n)
!       .. Local Scalars ..
        Real (Kind=nag_wp)             :: vm1, vv
        Integer                        :: j
!       .. Executable Statements ..
        vm1 = v(1)
        v(1) = four*v(1) + v(2)
        Do j = 2, n - 1
          vv = v(j)
          v(j) = vm1 + four*vv + v(j+1)
          vm1 = vv
        End Do
        v(n) = vm1 + four*v(n)
        Return
      End Subroutine mv

      Subroutine av(n,v,w)

!       .. Scalar Arguments ..
        Integer, Intent (In)           :: n
!       .. Array Arguments ..
        Real (Kind=nag_wp), Intent (In) :: v(n)
        Real (Kind=nag_wp), Intent (Out) :: w(n)
!       .. Local Scalars ..
        Integer                        :: j
!       .. Executable Statements ..
        w(1) = two*v(1) + three*v(2)
        Do j = 2, n - 1
          w(j) = -two*v(j-1) + two*v(j) + three*v(j+1)
        End Do
        w(n) = -two*v(n-1) + two*v(n)
        Return
      End Subroutine av
    End Module f12aefe_mod

    Program f12aefe

!     F12AEF Example Main Program

!     .. Use Statements ..
      Use nag_library, Only: ddot, dnrm2, f06bnf, f12aaf, f12abf, f12acf,      &
                             f12adf, f12aef, nag_wp, zgttrf, zgttrs
      Use f12aefe_mod, Only: av, four, mv, nin, nout, three, two, zero
!     .. Implicit None Statement ..
      Implicit None
!     .. Local Scalars ..
      Complex (Kind=nag_wp)            :: c1, c2, c3, csig
      Real (Kind=nag_wp)               :: deni, denr, nev_nrm, numi, numr,     &
                                          sigmai, sigmar
      Integer                          :: ifail, ifail1, info, irevcm, j,      &
                                          lcomm, ldv, licomm, n, nconv, ncv,   &
                                          nev, niter, nshift
      Logical                          :: first
!     .. Local Arrays ..
      Complex (Kind=nag_wp), Allocatable :: cdd(:), cdl(:), cdu(:), cdu2(:),   &
                                          ctemp(:)
      Real (Kind=nag_wp), Allocatable  :: ax(:), comm(:), d(:,:), mx(:),       &
                                          resid(:), v(:,:), x(:)
      Integer, Allocatable             :: icomm(:), ipiv(:)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: cmplx, real
!     .. Executable Statements ..
      Write (nout,*) 'F12AEF Example Program Results'
      Write (nout,*)
!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) n, nev, ncv, sigmar, sigmai
      ldv = n
      licomm = 140
      lcomm = 3*n + 3*ncv*ncv + 6*ncv + 60

      Allocate (cdd(n),cdl(n),cdu(n),cdu2(n),ctemp(n),ax(n),comm(lcomm),       &
        d(ncv,3),mx(n),resid(n),v(ldv,ncv),x(n),icomm(licomm),ipiv(n))

!     ifail: behaviour on error exit
!             =0 for hard exit, =1 for quiet-soft, =-1 for noisy-soft
      ifail = 0
      Call f12aaf(n,nev,ncv,icomm,licomm,comm,lcomm,ifail)

!     Set the mode.
      ifail = 0
      Call f12adf('SHIFTED REAL',icomm,comm,ifail)

!     Set problem type
      Call f12adf('GENERALIZED',icomm,comm,ifail)

!     Solve A*x = lambda*B*x in shift-invert mode.
!     The shift, sigma, is a complex number (sigmar, sigmai).
!     OP = Real_Part{inv[A-(SIGMAR,SIGMAI)*M]*M and  B = M.
      csig = cmplx(sigmar,sigmai,kind=nag_wp)
      c1 = cmplx(-two,kind=nag_wp) - csig
      c2 = cmplx(two,kind=nag_wp) - cmplx(four,kind=nag_wp)*csig
      c3 = cmplx(three,kind=nag_wp) - csig

      cdl(1:n-1) = c1
      cdd(1:n-1) = c2
      cdu(1:n-1) = c3
      cdd(n) = c2

!     The NAG name equivalent of zgttrf is f07crf
      Call zgttrf(n,cdl,cdd,cdu,cdu2,ipiv,info)

      irevcm = 0
      ifail = -1
loop: Do
        Call f12abf(irevcm,resid,v,ldv,x,mx,nshift,comm,icomm,ifail)

        If (irevcm/=5) Then
          Select Case (irevcm)
          Case (-1)
!           Perform  x <--- OP*x = inv[A-SIGMA*M]*M*x
            Call mv(n,x)
            ctemp(1:n) = cmplx(x(1:n),kind=nag_wp)
!           The NAG name equivalent of zgttrs is f07csf
            Call zgttrs('N',n,1,cdl,cdd,cdu,cdu2,ipiv,ctemp,n,info)
            x(1:n) = real(ctemp(1:n))
          Case (1)
!           Perform  x <--- OP*x = inv[A-SIGMA*M]*M*x,
!           M*X stored in MX.
            ctemp(1:n) = cmplx(mx(1:n),kind=nag_wp)
!           The NAG name equivalent of zgttrs is f07csf
            Call zgttrs('N',n,1,cdl,cdd,cdu,cdu2,ipiv,ctemp,n,info)
            x(1:n) = real(ctemp(1:n))
          Case (2)
!           Perform  y <--- M*x
            Call mv(n,x)
          Case (4)
!           Output monitoring information
            Call f12aef(niter,nconv,d,d(1,2),d(1,3),icomm,comm)
!           The NAG name equivalent of dnrm2 is f06ejf
            nev_nrm = dnrm2(nev,d(1,3),1)
            Write (6,99999) niter, nconv, nev_nrm
          End Select
        Else
          Exit loop
        End If
      End Do loop
      If (ifail==0) Then

!       Post-Process using F12ACF to compute eigenvalues/vectors.
        ifail1 = 0
        Call f12acf(nconv,d,d(1,2),v,ldv,sigmar,sigmai,resid,v,ldv,comm,icomm, &
          ifail1)

        first = .True.
        Do j = 1, nconv
!         Use Rayleigh Quotient to recover eigenvalues of the original
!         problem.
!         The NAG name equivalent of ddot is f06eaf
          If (d(j,2)==zero) Then
!           Ritz value is real. x = v(:,j); eig = x'Ax/x'Mx.
            Call av(n,v(1,j),ax)
            numr = ddot(n,v(1,j),1,ax,1)
            mx(1:n) = v(1:n,j)
            Call mv(n,mx)
            denr = ddot(n,v(1,j),1,mx,1)
            d(j,1) = numr/denr
          Else If (first) Then
!           Ritz value is complex: x = v(:,j) - i v(:,j+1).

!           Compute x'(Ax):
!              first (xr,xi)'*(A xr)
            Call av(n,v(1,j),ax)
            numr = ddot(n,v(1,j),1,ax,1)
            numi = ddot(n,v(1,j+1),1,ax,1)
!           then add (xi,-xr)'*(A xi)
            Call av(n,v(1,j+1),ax)
            numr = numr + ddot(n,v(1,j+1),1,ax,1)
            numi = -numi + ddot(n,v(1,j),1,ax,1)

!           Compute x'(Mx) as above using mv in, place of av.
            mx(1:n) = v(1:n,j)
            Call mv(n,mx)
            denr = ddot(n,v(1,j),1,mx,1)
            deni = ddot(n,v(1,j+1),1,mx,1)
            mx(1:n) = v(1:n,j+1)
            Call mv(n,mx)
            denr = denr + ddot(n,v(1,j+1),1,mx,1)
            deni = -deni + ddot(n,v(1,j),1,mx,1)

!           Rayleigh quotient,  d=x'(Ax)/x'(Mx), (complex division).
            d(j,1) = (numr*denr+numi*deni)/f06bnf(denr,deni)
            d(j,2) = (numi*denr-numr*deni)/f06bnf(denr,deni)
            first = .False.
          Else
!           Second of complex conjugate pair.
            d(j,1) = d(j-1,1)
            d(j,2) = -d(j-1,2)
            first = .True.
          End If
        End Do
!       Print computed eigenvalues.
        Write (nout,99998) nconv, sigmar, sigmai
        Write (nout,99997)(j,d(j,1:2),j=1,nconv)
      End If

99999 Format (1X,'Iteration',1X,I3,', No. converged =',1X,I3,', norm o',       &
        'f estimates =',E12.4)
99998 Format (1X,/,' The ',I4,' generalized Ritz values closest to (',F8.4,    &
        ', ',F8.4,') are:',/)
99997 Format (1X,I8,5X,'(',F7.4,',',F7.4,')')
    End Program f12aefe


f12agfe.f90

    Program f12agfe

!     F12AGF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: dgbmv, dnrm2, f06bnf, f12adf, f12aff, f12agf,     &
                             nag_wp, x04abf, x04caf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Real (Kind=nag_wp), Parameter    :: one = 1.0_nag_wp
      Real (Kind=nag_wp), Parameter    :: zero = 0.0_nag_wp
      Integer, Parameter               :: iset = 1, nin = 5, nout = 6
      Logical, Parameter               :: printr = .False.
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: h, rho, sigmai, sigmar
      Integer                          :: i, idiag, ifail, isub, isup, j, kl,  &
                                          ku, lcomm, ldab, ldmb, ldv, licomm,  &
                                          lo, n, ncol, nconv, ncv, nev, nx,    &
                                          outchn
      Logical                          :: first
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: ab(:,:), ax(:), comm(:), di(:),      &
                                          dr(:), d_print(:,:), mb(:,:), mx(:), &
                                          resid(:), v(:,:)
      Integer, Allocatable             :: icomm(:)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: abs, int, max, real
!     .. Executable Statements ..
      Write (nout,*) 'F12AGF Example Program Results'
      Write (nout,*)
      Flush (nout)

!     Skip heading in data file
      Read (nin,*)

      Read (nin,*) nx, nev, ncv, sigmar, sigmai
      n = nx*nx

!     Initialize communication arrays.
!     Query the required sizes of the communication arrays.

      licomm = -1
      lcomm = -1
      Allocate (icomm(max(1,licomm)),comm(max(1,lcomm)))

      ifail = 0
      Call f12aff(n,nev,ncv,icomm,licomm,comm,lcomm,ifail)

      licomm = icomm(1)
      lcomm = int(comm(1))
      Deallocate (icomm,comm)
      Allocate (icomm(max(1,licomm)),comm(max(1,lcomm)))

      ifail = 0
      Call f12aff(n,nev,ncv,icomm,licomm,comm,lcomm,ifail)

!     Set the mode.

      ifail = 0
      Call f12adf('SHIFTED IMAGINARY',icomm,comm,ifail)

!     Set problem type

      ifail = 0
      Call f12adf('GENERALIZED',icomm,comm,ifail)

!     Construct the matrix A in banded form and store in AB.
!     KU, KL are number of superdiagonals and subdiagonals within
!     the band of matrices A and M.

      kl = nx
      ku = nx
      ldab = 2*kl + ku + 1
      ldmb = 2*kl + ku + 1
      Allocate (ab(ldab,n),mb(ldmb,n))

!     Zero out AB and MB.

      ab(1:ldab,1:n) = 0.0_nag_wp
      mb(1:ldmb,1:n) = 0.0_nag_wp

!     Main diagonal of A.

      idiag = kl + ku + 1
      ab(idiag,1:n) = 4.0_nag_wp
      mb(idiag,1:n) = 4.0_nag_wp

!     First subdiagonal and superdiagonal of A.

      isup = kl + ku
      isub = kl + ku + 2
      rho = 100.0_nag_wp
      h = one/real(nx+1,kind=nag_wp)

      Do i = 1, nx
        lo = (i-1)*nx

        Do j = lo + 1, lo + nx - 1
          ab(isub,j+1) = -one + 0.5_nag_wp*h*rho
          ab(isup,j) = -one - 0.5_nag_wp*h*rho
        End Do

      End Do

      mb(isub,2:n) = one
      mb(isup,1:n-1) = one

!     KL-th subdiagonal and KU-th superdiagonal.

      isup = kl + 1
      isub = 2*kl + ku + 1

      Do i = 1, nx - 1
        lo = (i-1)*nx

        Do j = lo + 1, lo + nx
          ab(isup,nx+j) = -one
          ab(isub,j) = -one
        End Do

      End Do

!     Find eigenvalues closest in value to SIGMA and corresponding
!     eigenvectors.

      ldv = n
      Allocate (dr(nev+1),di(nev+1),v(ldv,ncv),resid(n))

      ifail = -1
      Call f12agf(kl,ku,ab,ldab,mb,ldmb,sigmar,sigmai,nconv,dr,di,v,ldv,resid, &
        v,ldv,comm,icomm,ifail)

      If (ifail/=0) Then
        Go To 100
      End If

!     Compute the residual norm  ||A*x - lambda*x||.

      first = .True.
      Allocate (ax(n),mx(n),d_print(nconv,3))
      d_print(1:nconv,1) = dr(1:nconv)
      d_print(1:nconv,2) = di(1:nconv)

      Do j = 1, nconv

        If (di(j)==zero) Then

!         The NAG name equivalent of dgbmv is f06pbf
          Call dgbmv('N',n,n,kl,ku,one,ab(kl+1,1),ldab,v(1,j),1,zero,ax,1)

          Call dgbmv('N',n,n,kl,ku,one,mb(kl+1,1),ldmb,v(1,j),1,zero,mx,1)

          ax(1:n) = -dr(j)*mx(1:n) + ax(1:n)
          d_print(j,3) = dnrm2(n,ax,1)/abs(dr(j))
        Else If (first) Then

          Call dgbmv('N',n,n,kl,ku,one,ab(kl+1,1),ldab,v(1,j),1,zero,ax,1)

          Call dgbmv('N',n,n,kl,ku,one,mb(kl+1,1),ldmb,v(1,j),1,zero,mx,1)

          ax(1:n) = -dr(j)*mx(1:n) + ax(1:n)

          Call dgbmv('N',n,n,kl,ku,one,mb(kl+1,1),ldmb,v(1,j+1),1,zero,mx,1)

          ax(1:n) = di(j)*mx(1:n) + ax(1:n)
          d_print(j,3) = dnrm2(n,ax,1)

          Call dgbmv('N',n,n,kl,ku,one,ab(kl+1,1),ldab,v(1,j+1),1,zero,ax,1)

          Call dgbmv('N',n,n,kl,ku,one,mb(kl+1,1),ldmb,v(1,j+1),1,zero,mx,1)

          ax(1:n) = -dr(j)*mx(1:n) + ax(1:n)

          Call dgbmv('N',n,n,kl,ku,one,mb(kl+1,1),ldmb,v(1,j),1,zero,mx,1)

          ax(1:n) = -di(j)*mx(1:n) + ax(1:n)
!         The NAG name equivalent of dnrm2 is f06ejf
          d_print(j,3) = f06bnf(d_print(j,3),dnrm2(n,ax,1))
          d_print(j,3) = d_print(j,3)/f06bnf(dr(j),di(j))
          d_print(j+1,3) = d_print(j,3)
          first = .False.
        Else
          first = .True.
        End If

      End Do

      Write (nout,*)
      Flush (nout)

      outchn = nout
      Call x04abf(iset,outchn)

      If (printr) Then
!       Print residual associated with each Ritz value.
        ncol = 3
      Else
        ncol = 2
      End If
      ifail = 0
      Call x04caf('G','N',nconv,ncol,d_print,nconv,                            &
        ' Ritz values closest to sigma',ifail)

100   Continue
    End Program f12agfe


f12anfe.f90

!   F12ANF Example Program Text
!   Mark 26 Release. NAG Copyright 2016.

    Module f12anfe_mod

!     F12ANF Example Program Module:
!            Parameters and User-defined Routines

!     .. Use Statements ..
      Use nag_library, Only: nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Accessibility Statements ..
      Private
      Public                           :: av
!     .. Parameters ..
      Integer, Parameter, Public       :: imon = 0, ipoint = 0, licomm = 140,  &
                                          nin = 5, nout = 6
    Contains
      Subroutine tv(nx,x,y)
!       Compute the matrix vector multiplication y<---T*x where T is a nx
!       by nx tridiagonal matrix.

!       .. Parameters ..
        Complex (Kind=nag_wp), Parameter :: four = (4.0_nag_wp,0.0_nag_wp)
        Complex (Kind=nag_wp), Parameter :: half = (0.5_nag_wp,0.0_nag_wp)
        Complex (Kind=nag_wp), Parameter :: rho = (100.0_nag_wp,0.0_nag_wp)
!       .. Scalar Arguments ..
        Integer, Intent (In)           :: nx
!       .. Array Arguments ..
        Complex (Kind=nag_wp), Intent (In) :: x(nx)
        Complex (Kind=nag_wp), Intent (Out) :: y(nx)
!       .. Local Scalars ..
        Complex (Kind=nag_wp)          :: dd, dl, du, h, h2
        Integer                        :: j
!       .. Intrinsic Procedures ..
        Intrinsic                      :: cmplx
!       .. Executable Statements ..
        h = cmplx(nx+1,kind=nag_wp)
        h2 = h*h
        dd = four*h2
        dl = -h2 - half*rho*h
        du = -h2 + half*rho*h

        y(1) = dd*x(1) + du*x(2)
        Do j = 2, nx - 1
          y(j) = dl*x(j-1) + dd*x(j) + du*x(j+1)
        End Do
        y(nx) = dl*x(nx-1) + dd*x(nx)
        Return
      End Subroutine tv
      Subroutine av(nx,v,w)

!       .. Use Statements ..
        Use nag_library, Only: zaxpy
!       .. Scalar Arguments ..
        Integer, Intent (In)           :: nx
!       .. Array Arguments ..
        Complex (Kind=nag_wp), Intent (In) :: v(nx*nx)
        Complex (Kind=nag_wp), Intent (Out) :: w(nx*nx)
!       .. Local Scalars ..
        Complex (Kind=nag_wp)          :: h2
        Integer                        :: j, lo
!       .. Intrinsic Procedures ..
        Intrinsic                      :: cmplx
!       .. Executable Statements ..
        h2 = cmplx(-(nx+1)*(nx+1),kind=nag_wp)

        Call tv(nx,v(1),w(1))
!       The NAG name equivalent of zaxpy is f06gcf
        Call zaxpy(nx,h2,v(nx+1),1,w(1),1)

        Do j = 2, nx - 1
          lo = (j-1)*nx
          Call tv(nx,v(lo+1),w(lo+1))
          Call zaxpy(nx,h2,v(lo-nx+1),1,w(lo+1),1)
          Call zaxpy(nx,h2,v(lo+nx+1),1,w(lo+1),1)
        End Do

        lo = (nx-1)*nx
        Call tv(nx,v(lo+1),w(lo+1))
        Call zaxpy(nx,h2,v(lo-nx+1),1,w(lo+1),1)

        Return
      End Subroutine av
    End Module f12anfe_mod
    Program f12anfe

!     F12ANF Example Main Program

!     .. Use Statements ..
      Use nag_library, Only: dznrm2, f12anf, f12apf, f12aqf, f12arf, f12asf,   &
                             nag_wp
      Use f12anfe_mod, Only: av, imon, ipoint, licomm, nin, nout
!     .. Implicit None Statement ..
      Implicit None
!     .. Local Scalars ..
      Complex (Kind=nag_wp)            :: sigma
      Integer                          :: i, ifail, ifail1, irevcm, lcomm,     &
                                          ldv, n, nconv, ncv, nev, niter,      &
                                          nshift, nx
!     .. Local Arrays ..
      Complex (Kind=nag_wp), Allocatable :: ax(:), comm(:), d(:,:), mx(:),     &
                                          resid(:), v(:,:), x(:)
      Integer                          :: icomm(licomm)
!     .. Executable Statements ..
      Write (nout,*) 'F12ANF Example Program Results'
      Write (nout,*)
!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) nx, nev, ncv

      n = nx*nx
      ldv = n
      lcomm = 3*n + 3*ncv*ncv + 5*ncv + 60
      Allocate (ax(n),comm(lcomm),d(ncv,2),mx(n),resid(n),v(n,ncv),x(n))

      ifail = 0
      Call f12anf(n,nev,ncv,icomm,licomm,comm,lcomm,ifail)

      If (ipoint/=0) Then
!       Use pointers to Workspace in calculating matrix vector
!       products rather than interfacing through the array X.
        ifail = 0
        Call f12arf('POINTERS=YES',icomm,comm,ifail)
      End If

      irevcm = 0
      ifail = -1

revcm: Do
        Call f12apf(irevcm,resid,v,ldv,x,mx,nshift,comm,icomm,ifail)
        If (irevcm==5) Then
          Exit revcm
        Else If (irevcm==-1 .Or. irevcm==1) Then
!         Perform matrix vector multiplication y <--- Op*x.
          If (ipoint==0) Then
            Call av(nx,x,ax)
            x(1:n) = ax(1:n)
          Else
            Call av(nx,comm(icomm(1)),comm(icomm(2)))
          End If
        Else If (irevcm==4 .And. imon/=0) Then
!         Output monitoring information.
          Call f12asf(niter,nconv,d,d(1,2),icomm,comm)
!         The NAG name equivalent of dznrm2 is f06jjf
          Write (6,99999) niter, nconv, dznrm2(nev,d(1,2),1)
        End If
      End Do revcm

      If (ifail==0) Then
!       Post-Process using F12AQF to compute eigenvalues/vectors.
        ifail1 = 0
        Call f12aqf(nconv,d,v,ldv,sigma,resid,v,ldv,comm,icomm,ifail1)

        Write (nout,99998) nconv
        Write (nout,99997)(i,d(i,1),i=1,nconv)
      End If

99999 Format (1X,'Iteration',1X,I3,', No. converged =',1X,I3,', norm o',       &
        'f estimates =',E16.8)
99998 Format (1X,/,' The ',I4,' Ritz values of largest magnitude are:',/)
99997 Format (1X,I8,5X,'( ',F12.4,' , ',F12.4,' )')
    End Program f12anfe


f12apfe.f90

    Program f12apfe

!     F12APF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: dznrm2, f12anf, f12apf, f12aqf, f12arf, f12asf,   &
                             nag_wp, zgttrf, zgttrs
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Complex (Kind=nag_wp), Parameter :: one = (1.0_nag_wp,0.0_nag_wp)
      Complex (Kind=nag_wp), Parameter :: two = (2.0_nag_wp,0.0_nag_wp)
      Integer, Parameter               :: imon = 0, nerr = 6, nin = 5,         &
                                          nout = 6
!     .. Local Scalars ..
      Complex (Kind=nag_wp)            :: h, h2, rho, s, s1, s2, s3, sigma
      Integer                          :: ifail, info, irevcm, j, lcomm, ldv,  &
                                          licomm, n, nconv, ncv, nev, niter,   &
                                          nshift, nx
!     .. Local Arrays ..
      Complex (Kind=nag_wp), Allocatable :: comm(:), d(:,:), dd(:), dl(:),     &
                                          du(:), du2(:), mx(:), resid(:),      &
                                          v(:,:), x(:)
      Integer, Allocatable             :: icomm(:), ipiv(:)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: cmplx, int, max
!     .. Executable Statements ..
      Write (nout,*) 'F12APF Example Program Results'
      Write (nout,*)

!     Skip heading in data file
      Read (nin,*)

      Read (nin,*) nx, nev, ncv
      n = nx*nx

!     Initialize communication arrays.
!     Query the required sizes of the communication arrays.

      licomm = -1
      lcomm = -1
      Allocate (icomm(max(1,licomm)),comm(max(1,lcomm)))

      ifail = 0
      Call f12anf(n,nev,ncv,icomm,licomm,comm,lcomm,ifail)

      licomm = icomm(1)
      lcomm = int(comm(1))
      Deallocate (icomm,comm)
      Allocate (icomm(max(1,licomm)),comm(max(1,lcomm)))

      ifail = 0
      Call f12anf(n,nev,ncv,icomm,licomm,comm,lcomm,ifail)

!     Set the mode.

      ifail = 0
      Call f12arf('SHIFTED INVERSE',icomm,comm,ifail)

      sigma = cmplx(0,kind=nag_wp)
      rho = (10.0_nag_wp,0.0_nag_wp)
      h = one/cmplx(n+1,kind=nag_wp)
      h2 = h*h
      s = rho/two

      s1 = -one/h2 - s/h
      s2 = two/h2 - sigma
      s3 = -one/h2 + s/h

      Allocate (dl(n-1),dd(n),du(n-1),du2(n-2),ipiv(n))
      dl(1:n-1) = s1
      dd(1:n-1) = s2
      du(1:n-1) = s3
      dd(n) = s2

!     The NAG name equivalent of zgttrf is f07crf
      Call zgttrf(n,dl,dd,du,du2,ipiv,info)

      If (info/=0) Then
        Write (nerr,99999) info
        Go To 110
      End If

      ldv = n
      Allocate (resid(n),v(ldv,ncv),x(n),mx(n),d(ncv,2))

      irevcm = 0
      ifail = -1

100   Continue

      Call f12apf(irevcm,resid,v,ldv,x,mx,nshift,comm,icomm,ifail)

      If (irevcm/=5) Then

        If (irevcm==-1 .Or. irevcm==1) Then

!         Perform  x <--- OP*x = inv[A-SIGMA*I]*x

!         The NAG name equivalent of zgttrs is f07csf
          Call zgttrs('N',n,1,dl,dd,du,du2,ipiv,x,n,info)

          If (info/=0) Then
            Write (nerr,99998) info
            Go To 110
          End If

        Else If (irevcm==4 .And. imon/=0) Then

!         Output monitoring information

          Call f12asf(niter,nconv,d,d(1,2),icomm,comm)

!         The NAG name equivalent of dznrm2 is f06jjf
          Write (6,99997) niter, nconv, dznrm2(nev,d(1,2),1)
        End If

        Go To 100

      End If

      If (ifail==0) Then

!       Post-Process using F12AQF to compute eigenvalues/vectors.

        ifail = 0
        Call f12aqf(nconv,d,v,ldv,sigma,resid,v,ldv,comm,icomm,ifail)

        Write (nout,99996) nconv

        Do j = 1, nconv
          Write (nout,99995) j, d(j,1)
        End Do

      End If

110   Continue

99999 Format (1X,'** Error status returned by ZGTTRF, INFO =',I12)
99998 Format (1X,'** Error status returned by ZGTTRS, INFO =',I12)
99997 Format (1X,'Iteration',1X,I3,', No. converged =',1X,I3,', norm o',       &
        'f estimates =',E16.8)
99996 Format (1X,/,' The ',I4,' Ritz values of smallest magnitude are:',/)
99995 Format (1X,I8,5X,'( ',F12.4,' , ',F12.4,' )')
    End Program f12apfe


f12aqfe.f90

!   F12AQF Example Program Text
!   Mark 26 Release. NAG Copyright 2016.

    Module f12aqfe_mod

!     F12AQF Example Program Module:
!            Parameters and User-defined Routines

!     .. Use Statements ..
      Use nag_library, Only: nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Accessibility Statements ..
      Private
      Public                           :: av, mv
!     .. Parameters ..
      Complex (Kind=nag_wp), Parameter, Public :: four = (4.0_nag_wp,          &
                                          0.0_nag_wp)
      Complex (Kind=nag_wp), Parameter, Public :: one = (1.0E+0_nag_wp,        &
                                          0.0E+0_nag_wp)
      Complex (Kind=nag_wp), Parameter :: two = (2.0_nag_wp,0.0_nag_wp)
      Integer, Parameter, Public       :: imon = 0, licomm = 140, nerr = 6,    &
                                          nin = 5, nout = 6
    Contains
      Subroutine av(nx,v,w)

!       .. Parameters ..
        Complex (Kind=nag_wp), Parameter :: rho = (10.0_nag_wp,0.0_nag_wp)
!       .. Scalar Arguments ..
        Integer, Intent (In)           :: nx
!       .. Array Arguments ..
        Complex (Kind=nag_wp), Intent (In) :: v(nx*nx)
        Complex (Kind=nag_wp), Intent (Out) :: w(nx*nx)
!       .. Local Scalars ..
        Complex (Kind=nag_wp)          :: dd, dl, du, h, s
        Integer                        :: j, n
!       .. Intrinsic Procedures ..
        Intrinsic                      :: cmplx
!       .. Executable Statements ..
        n = nx*nx
        h = one/cmplx(n+1,kind=nag_wp)
        s = rho/two
        dd = two/h
        dl = -one/h - s
        du = -one/h + s
        w(1) = dd*v(1) + du*v(2)
        Do j = 2, n - 1
          w(j) = dl*v(j-1) + dd*v(j) + du*v(j+1)
        End Do
        w(n) = dl*v(n-1) + dd*v(n)
        Return
      End Subroutine av

      Subroutine mv(nx,v,w)

!       .. Use Statements ..
        Use nag_library, Only: zscal
!       .. Scalar Arguments ..
        Integer, Intent (In)           :: nx
!       .. Array Arguments ..
        Complex (Kind=nag_wp), Intent (In) :: v(nx*nx)
        Complex (Kind=nag_wp), Intent (Out) :: w(nx*nx)
!       .. Local Scalars ..
        Complex (Kind=nag_wp)          :: h
        Integer                        :: j, n
!       .. Intrinsic Procedures ..
        Intrinsic                      :: cmplx
!       .. Executable Statements ..
        n = nx*nx
        w(1) = four*v(1) + one*v(2)
        Do j = 2, n - 1
          w(j) = one*v(j-1) + four*v(j) + one*v(j+1)
        End Do
        w(n) = one*v(n-1) + four*v(n)
        h = one/cmplx(n+1,kind=nag_wp)
!       The NAG name equivalent of zscal is f06gdf
        Call zscal(n,h,w,1)
        Return
      End Subroutine mv
    End Module f12aqfe_mod
    Program f12aqfe

!     F12AQF Example Main Program

!     .. Use Statements ..
      Use nag_library, Only: dznrm2, f12anf, f12apf, f12aqf, f12arf, f12asf,   &
                             nag_wp, zgttrf, zgttrs
      Use f12aqfe_mod, Only: av, four, imon, licomm, mv, nerr, nin, nout, one
!     .. Implicit None Statement ..
      Implicit None
!     .. Local Scalars ..
      Complex (Kind=nag_wp)            :: h, sigma
      Integer                          :: ifail, ifail1, info, irevcm, j,      &
                                          lcomm, ldv, n, nconv, ncv, nev,      &
                                          niter, nshift, nx
!     .. Local Arrays ..
      Complex (Kind=nag_wp), Allocatable :: comm(:), d(:,:), dd(:), dl(:),     &
                                          du(:), du2(:), mx(:), resid(:),      &
                                          v(:,:), x(:)
      Integer                          :: icomm(licomm)
      Integer, Allocatable             :: ipiv(:)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: cmplx
!     .. Executable Statements ..
      Write (nout,*) 'F12AQF Example Program Results'
      Write (nout,*)
!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) nx, nev, ncv

      n = nx*nx
      lcomm = 3*n + 3*ncv*ncv + 5*ncv + 60
      ldv = n
      Allocate (comm(lcomm),d(ncv,2),dd(n),dl(n),du(n),du2(n),mx(n),resid(n),  &
        v(ldv,ncv),x(n),ipiv(n))

      ifail = 0
      Call f12anf(n,nev,ncv,icomm,licomm,comm,lcomm,ifail)

!     Set the mode.
      ifail = 0
      Call f12arf('REGULAR INVERSE',icomm,comm,ifail)
!     Set problem type.
      Call f12arf('GENERALIZED',icomm,comm,ifail)
!     Use pointers to Workspace rather than interfacing through the array X.
      Call f12arf('POINTERS=YES',icomm,comm,ifail)
      h = one/cmplx(n+1,kind=nag_wp)

      dl(1:n-1) = h
      dd(1:n-1) = four*h
      du(1:n-1) = h
      dd(n) = four*h

!     The NAG name equivalent of zgttrf is f07crf
      Call zgttrf(n,dl,dd,du,du2,ipiv,info)
      If (info/=0) Then
        Write (nerr,99999) info
        Go To 100
      End If

      irevcm = 0
      ifail = -1
revcm: Do
        Call f12apf(irevcm,resid,v,ldv,x,mx,nshift,comm,icomm,ifail)
        If (irevcm==5) Then
          Exit revcm
        Else If (irevcm==-1 .Or. irevcm==1) Then
!         Perform  y <--- OP*x = inv[M]*A*x      |
          Call av(nx,comm(icomm(1)),comm(icomm(2)))
!         The NAG name equivalent of zgttrs is f07csf
          Call zgttrs('N',n,1,dl,dd,du,du2,ipiv,comm(icomm(2)),n,info)
          If (info/=0) Then
            Write (nerr,99998) info
            Exit revcm
          End If
        Else If (irevcm==2) Then
!         Perform  y <--- M*x
          Call mv(nx,comm(icomm(1)),comm(icomm(2)))
        Else If (irevcm==4 .And. imon/=0) Then
!         Output monitoring information
          Call f12asf(niter,nconv,d,d(1,2),icomm,comm)
!         The NAG name equivalent of dznrm2 is f06jjf
          Write (6,99997) niter, nconv, dznrm2(nev,d(1,2),1)
        End If
      End Do revcm

      If (ifail==0 .And. info==0) Then
!       Post-Process using F12AQF to compute eigenvalues/vectors.
        ifail1 = 0
        Call f12aqf(nconv,d,v,ldv,sigma,resid,v,ldv,comm,icomm,ifail1)
        Write (nout,99996) nconv
        Write (nout,99995)(j,d(j,1),j=1,nconv)
      End If
100   Continue

99999 Format (1X,'** Error status returned by ZGTTRF, INFO =',I12)
99998 Format (1X,'** Error status returned by ZGTTRS, INFO =',I12)
99997 Format (1X,'Iteration',1X,I3,', No. converged =',1X,I3,', norm o',       &
        'f estimates =',E16.8)
99996 Format (1X,/,' The ',I4,' Ritz values of largest magnitude are:',/)
99995 Format (1X,I8,5X,'( ',F12.4,' , ',F12.4,' )')
    End Program f12aqfe


f12arfe.f90

!   F12ARF Example Program Text
!   Mark 26 Release. NAG Copyright 2016.

    Module f12arfe_mod

!     F12ARF Example Program Module:
!            Parameters and User-defined Routines

!     .. Use Statements ..
      Use nag_library, Only: nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Accessibility Statements ..
      Private
      Public                           :: mv
!     .. Parameters ..
      Complex (Kind=nag_wp), Parameter, Public :: four = (4.0_nag_wp,          &
                                          0.0_nag_wp)
      Complex (Kind=nag_wp), Parameter, Public :: one = (1.0_nag_wp,0.0_nag_wp &
                                          )
      Complex (Kind=nag_wp), Parameter, Public :: six = (6.0_nag_wp,0.0_nag_wp &
                                          )
      Complex (Kind=nag_wp), Parameter, Public :: two = (2.0_nag_wp,0.0_nag_wp &
                                          )
      Integer, Parameter, Public       :: imon = 0, licomm = 140, nerr = 6,    &
                                          nin = 5, nout = 6
    Contains
      Subroutine mv(nx,v,w)
!       Compute the out-of--place matrix vector multiplication Y<---M*X,
!       where M is mass matrix formed by using piecewise linear elements
!       on [0,1].

!       .. Use Statements ..
        Use nag_library, Only: zscal
!       .. Scalar Arguments ..
        Integer, Intent (In)           :: nx
!       .. Array Arguments ..
        Complex (Kind=nag_wp), Intent (In) :: v(nx*nx)
        Complex (Kind=nag_wp), Intent (Out) :: w(nx*nx)
!       .. Local Scalars ..
        Complex (Kind=nag_wp)          :: h
        Integer                        :: j, n
!       .. Intrinsic Procedures ..
        Intrinsic                      :: cmplx
!       .. Executable Statements ..
        n = nx*nx
        w(1) = (four*v(1)+v(2))/six
        Do j = 2, n - 1
          w(j) = (v(j-1)+four*v(j)+v(j+1))/six
        End Do
        w(n) = (v(n-1)+four*v(n))/six

        h = one/cmplx(n+1,kind=nag_wp)
!       The NAG name equivalent of zscal is f06gdf
        Call zscal(n,h,w,1)
        Return
      End Subroutine mv
    End Module f12arfe_mod
    Program f12arfe

!     F12ARF Example Main Program

!     .. Use Statements ..
      Use nag_library, Only: dznrm2, f12anf, f12apf, f12aqf, f12arf, f12asf,   &
                             nag_wp, zgttrf, zgttrs
      Use f12arfe_mod, Only: four, imon, licomm, mv, nerr, nin, nout, one,     &
                             six, two
!     .. Implicit None Statement ..
      Implicit None
!     .. Local Scalars ..
      Complex (Kind=nag_wp)            :: h, rho, s, s1, s2, s3, sigma
      Integer                          :: ifail, ifail1, info, irevcm, j,      &
                                          lcomm, ldv, n, nconv, ncv, nev,      &
                                          niter, nshift, nx
!     .. Local Arrays ..
      Complex (Kind=nag_wp), Allocatable :: ax(:), comm(:), d(:,:), dd(:),     &
                                          dl(:), du(:), du2(:), mx(:),         &
                                          resid(:), v(:,:), x(:)
      Integer                          :: icomm(licomm)
      Integer, Allocatable             :: ipiv(:)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: cmplx
!     .. Executable Statements ..
      Write (nout,*) 'F12ARF Example Program Results'
      Write (nout,*)
!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) nx, nev, ncv

      n = nx*nx
      lcomm = 3*n + 3*ncv*ncv + 5*ncv + 60
      ldv = n
      Allocate (comm(lcomm),ax(n),d(ncv,2),dd(n),dl(n),du(n),du2(n),mx(n),     &
        resid(n),v(ldv,ncv),x(n),ipiv(n))

      ifail = 0
      Call f12anf(n,nev,ncv,icomm,licomm,comm,lcomm,ifail)

!     Set the mode.
      ifail = 0
      Call f12arf('SHIFTED INVERSE',icomm,comm,ifail)
!     Set problem type.
      Call f12arf('GENERALIZED',icomm,comm,ifail)
      sigma = (500.0_nag_wp,0.0_nag_wp)
      rho = (10.0_nag_wp,0.0_nag_wp)
      h = one/cmplx(n+1,kind=nag_wp)
      s = rho/two
      s1 = -one/h - s - sigma*h/six
      s2 = two/h - four*sigma*h/six
      s3 = -one/h + s - sigma*h/six

      dl(1:n-1) = s1
      dd(1:n-1) = s2
      du(1:n-1) = s3
      dd(n) = s2

!     The NAG name equivalent of zgttrf is f07crf
      Call zgttrf(n,dl,dd,du,du2,ipiv,info)
      If (info/=0) Then
        Write (nerr,99999) info
        Go To 100
      End If

      irevcm = 0
      ifail = -1
revcm: Do
        Call f12apf(irevcm,resid,v,ldv,x,mx,nshift,comm,icomm,ifail)
        If (irevcm==5) Then
          Exit revcm
        Else If (irevcm==-1) Then
!         Perform  x <--- OP*x = inv[A-SIGMA*M]*M*x
          Call mv(nx,x,ax)
          x(1:n) = ax(1:n)
!         The NAG name equivalent of zgttrs is f07csf
          Call zgttrs('N',n,1,dl,dd,du,du2,ipiv,x,n,info)
          If (info/=0) Then
            Write (nerr,99998) info
            Exit revcm
          End If
        Else If (irevcm==1) Then
!         Perform  x <--- OP*x = inv[A-SIGMA*M]*M*x,
!         MX stored in COMM from location IPNTR(3)
!         The NAG name equivalent of zgttrs is f07csf
          Call zgttrs('N',n,1,dl,dd,du,du2,ipiv,mx,n,info)
          x(1:n) = mx(1:n)
          If (info/=0) Then
            Write (nerr,99998) info
            Exit revcm
          End If
        Else If (irevcm==2) Then
!         Perform  y <--- M*x
          Call mv(nx,x,ax)
          x(1:n) = ax(1:n)
        Else If (irevcm==4 .And. imon/=0) Then
!         Output monitoring information
          Call f12asf(niter,nconv,d,d(1,2),icomm,comm)
!         The NAG name equivalent of dznrm2 is f06jjf
          Write (6,99997) niter, nconv, dznrm2(nev,d(1,2),1)
        End If
      End Do revcm

      If (ifail==0 .And. info==0) Then
!       Post-Process using F12AQF to compute eigenvalues/vectors.
        ifail1 = 0
        Call f12aqf(nconv,d,v,ldv,sigma,resid,v,ldv,comm,icomm,ifail1)
        Write (nout,99996) nconv, sigma
        Write (nout,99995)(j,d(j,1),j=1,nconv)
      End If
100   Continue

99999 Format (1X,'** Error status returned by ZGTTRF, INFO =',I12)
99998 Format (1X,'** Error status returned by ZGTTRS, INFO =',I12)
99997 Format (1X,'Iteration',1X,I3,', No. converged =',1X,I3,', norm o',       &
        'f estimates =',E16.8)
99996 Format (1X,/,' The ',I4,' generalized Ritz values closest to (',F7.3,    &
        ',',F7.3,') are:',/)
99995 Format (1X,I8,5X,'( ',F10.4,' , ',F10.4,' )')
    End Program f12arfe


f12asfe.f90

!   F12ASF Example Program Text
!   Mark 26 Release. NAG Copyright 2016.

    Module f12asfe_mod

!     F12ASF Example Program Module:
!            Parameters and User-defined Routines

!     .. Use Statements ..
      Use nag_library, Only: nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Accessibility Statements ..
      Private
      Public                           :: mv
!     .. Parameters ..
      Complex (Kind=nag_wp), Parameter, Public :: four = (4.0_nag_wp,          &
                                          0.0_nag_wp)
      Complex (Kind=nag_wp), Parameter, Public :: one = (1.0_nag_wp,0.0_nag_wp &
                                          )
      Complex (Kind=nag_wp), Parameter, Public :: six = (6.0_nag_wp,0.0_nag_wp &
                                          )
      Complex (Kind=nag_wp), Parameter, Public :: two = (2.0_nag_wp,0.0_nag_wp &
                                          )
      Integer, Parameter, Public       :: imon = 1, licomm = 140, nerr = 6,    &
                                          nin = 5, nout = 6
    Contains
      Subroutine mv(nx,v,w)
!       Compute the out-of--place matrix vector multiplication Y<---M*X,
!       where M is mass matrix formed by using piecewise linear elements
!       on [0,1].

!       .. Use Statements ..
        Use nag_library, Only: zscal
!       .. Scalar Arguments ..
        Integer, Intent (In)           :: nx
!       .. Array Arguments ..
        Complex (Kind=nag_wp), Intent (In) :: v(nx*nx)
        Complex (Kind=nag_wp), Intent (Out) :: w(nx*nx)
!       .. Local Scalars ..
        Complex (Kind=nag_wp)          :: h
        Integer                        :: j, n
!       .. Intrinsic Procedures ..
        Intrinsic                      :: cmplx
!       .. Executable Statements ..
        n = nx*nx
        w(1) = (four*v(1)+v(2))/six
        Do j = 2, n - 1
          w(j) = (v(j-1)+four*v(j)+v(j+1))/six
        End Do
        w(n) = (v(n-1)+four*v(n))/six

        h = one/cmplx(n+1,kind=nag_wp)
!       The NAG name equivalent of zscal is f06gdf
        Call zscal(n,h,w,1)
        Return
      End Subroutine mv
    End Module f12asfe_mod

    Program f12asfe

!     F12ASF Example Main Program

!     .. Use Statements ..
      Use nag_library, Only: dznrm2, f12anf, f12apf, f12aqf, f12arf, f12asf,   &
                             nag_wp, zgttrf, zgttrs
      Use f12asfe_mod, Only: four, imon, licomm, mv, nerr, nin, nout, one,     &
                             six, two
!     .. Implicit None Statement ..
      Implicit None
!     .. Local Scalars ..
      Complex (Kind=nag_wp)            :: h, rho, s, s1, s2, s3, sigma
      Real (Kind=nag_wp)               :: nev_nrm
      Integer                          :: ifail, ifail1, info, irevcm, j,      &
                                          lcomm, ldv, n, nconv, ncv, nev,      &
                                          niter, nshift, nx
!     .. Local Arrays ..
      Complex (Kind=nag_wp), Allocatable :: ax(:), comm(:), d(:,:), dd(:),     &
                                          dl(:), du(:), du2(:), mx(:),         &
                                          resid(:), v(:,:), x(:)
      Integer                          :: icomm(licomm)
      Integer, Allocatable             :: ipiv(:)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: cmplx
!     .. Executable Statements ..
      Write (nout,*) 'F12ASF Example Program Results'
      Write (nout,*)
!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) nx, nev, ncv

      n = nx*nx
      lcomm = 3*n + 3*ncv*ncv + 5*ncv + 60
      ldv = n
      Allocate (ax(n),comm(lcomm),d(ncv,2),dd(n),dl(n),du(n),du2(n),mx(n),     &
        resid(n),v(ldv,ncv),x(n),ipiv(n))

      ifail = 0
      Call f12anf(n,nev,ncv,icomm,licomm,comm,lcomm,ifail)

!     Set the mode.
      ifail = 0
      Call f12arf('SHIFTED INVERSE',icomm,comm,ifail)
!     Set problem type.
      Call f12arf('GENERALIZED',icomm,comm,ifail)
      sigma = (5000.0_nag_wp,0.0_nag_wp)
      rho = (10.0_nag_wp,0.0_nag_wp)
      h = one/cmplx(n+1,kind=nag_wp)
      s = rho/two
      s1 = -one/h - s - sigma*h/six
      s2 = two/h - four*sigma*h/six
      s3 = -one/h + s - sigma*h/six

      dl(1:n-1) = s1
      dd(1:n-1) = s2
      du(1:n-1) = s3
      dd(n) = s2

!     The NAG name equivalent of zgttrf is f07crf
      Call zgttrf(n,dl,dd,du,du2,ipiv,info)
      If (info/=0) Then
        Write (nerr,99999) info
        Go To 100
      End If

      irevcm = 0
      ifail = -1
revcm: Do
        Call f12apf(irevcm,resid,v,ldv,x,mx,nshift,comm,icomm,ifail)
        If (irevcm==5) Then
          Exit revcm
        Else If (irevcm==-1) Then
!         Perform  x <--- OP*x = inv[A-SIGMA*M]*M*x
          Call mv(nx,x,ax)
          x(1:n) = ax(1:n)
!         The NAG name equivalent of zgttrs is f07csf
          Call zgttrs('N',n,1,dl,dd,du,du2,ipiv,x,n,info)
          If (info/=0) Then
            Write (nerr,99998) info
            Exit revcm
          End If
        Else If (irevcm==1) Then
!         Perform  x <--- OP*x = inv[A-SIGMA*M]*M*x,
!         MX stored in COMM from location IPNTR(3)
!         The NAG name equivalent of zgttrs is f07csf
          Call zgttrs('N',n,1,dl,dd,du,du2,ipiv,mx,n,info)
          x(1:n) = mx(1:n)
          If (info/=0) Then
            Write (nerr,99998) info
            Exit revcm
          End If
        Else If (irevcm==2) Then
!         Perform  y <--- M*x
          Call mv(nx,x,ax)
          x(1:n) = ax(1:n)
        Else If (irevcm==4 .And. imon/=0) Then
!         Output monitoring information
          Call f12asf(niter,nconv,d,d(1,2),icomm,comm)
!         The NAG name equivalent of dznrm2 is f06jjf
          nev_nrm = dznrm2(nev,d(1,2),1)
          Write (6,99997) niter, nconv, nev_nrm
        End If
      End Do revcm

      If (ifail==0 .And. info==0) Then
!       Post-Process using F12AQF to compute eigenvalues/vectors.
        ifail1 = 0
        Call f12aqf(nconv,d,v,ldv,sigma,resid,v,ldv,comm,icomm,ifail1)
        Write (nout,99996) nconv, sigma
        Write (nout,99995)(j,d(j,1),j=1,nconv)
      End If
100   Continue

99999 Format (1X,'** Error status returned by ZGTTRF, INFO =',I12)
99998 Format (1X,'** Error status returned by ZGTTRS, INFO =',I12)
99997 Format (1X,'Iteration',1X,I3,', No. converged =',1X,I3,', norm o',       &
        'f estimates =',E12.4)
99996 Format (1X,/,' The ',I4,' generalized Ritz values closest to (',F8.3,    &
        ',',F8.3,') are:',/)
99995 Format (1X,I8,5X,'( ',F10.4,' , ',F10.4,' )')
    End Program f12asfe


f12aufe.f90

    Program f12aufe

!     F12AUF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: dznrm2, f12arf, f12atf, f12auf, nag_wp, x04abf,   &
                             x04caf, zaxpy, zgbmv
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Complex (Kind=nag_wp), Parameter :: one = (1.0_nag_wp,0.0_nag_wp)
      Complex (Kind=nag_wp), Parameter :: zero = (0.0_nag_wp,0.0_nag_wp)
      Integer, Parameter               :: iset = 1, nin = 5, nout = 6
      Logical, Parameter               :: printr = .False.
!     .. Local Scalars ..
      Complex (Kind=nag_wp)            :: ch, sigma
      Real (Kind=nag_wp)               :: h, rho
      Integer                          :: i, idiag, ifail, isub, isup, j, kl,  &
                                          ku, lcomm, ldab, ldmb, ldv, licomm,  &
                                          lo, n, ncol, nconv, ncv, nev, nx,    &
                                          outchn
!     .. Local Arrays ..
      Complex (Kind=nag_wp), Allocatable :: ab(:,:), ax(:), comm(:), d(:),     &
                                          mb(:,:), mx(:), resid(:), v(:,:)
      Real (Kind=nag_wp), Allocatable  :: d_print(:,:)
      Integer, Allocatable             :: icomm(:)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: abs, aimag, cmplx, int, max, real
!     .. Executable Statements ..
      Write (nout,*) 'F12AUF Example Program Results'
      Write (nout,*)
      Flush (nout)

!     Skip heading in data file
      Read (nin,*)

      Read (nin,*) nx, nev, ncv
      Read (nin,*) sigma
      n = nx*nx

!     Initialize communication arrays.
!     Query the required sizes of the communication arrays.

      licomm = -1
      lcomm = -1
      Allocate (icomm(max(1,licomm)),comm(max(1,lcomm)))

      ifail = 0
      Call f12atf(n,nev,ncv,icomm,licomm,comm,lcomm,ifail)

      licomm = icomm(1)
      lcomm = int(comm(1))
      Deallocate (icomm,comm)
      Allocate (icomm(max(1,licomm)),comm(max(1,lcomm)))

      ifail = 0
      Call f12atf(n,nev,ncv,icomm,licomm,comm,lcomm,ifail)

!     Set the mode.

      ifail = 0
      Call f12arf('SHIFTED INVERSE',icomm,comm,ifail)

!     Set problem type

      ifail = 0
      Call f12arf('GENERALIZED',icomm,comm,ifail)

!     Construct the matrix A in banded form and store in AB.
!     KU, KL are number of superdiagonals and subdiagonals within
!     the band of matrices A and M.

      kl = nx
      ku = nx
      ldab = 2*kl + ku + 1
      ldmb = 2*kl + ku + 1
      Allocate (ab(ldab,n),mb(ldmb,n))

!     Zero out AB and MB.

      ab(1:ldab,1:n) = zero
      mb(1:ldmb,1:n) = zero

!     Main diagonal of A.

      idiag = kl + ku + 1
      ab(idiag,1:n) = cmplx(4.0_nag_wp,0.0_nag_wp,kind=nag_wp)
      mb(idiag,1:n) = ab(idiag,1)

!     First subdiagonal and superdiagonal of A.

      isup = kl + ku
      isub = kl + ku + 2
      rho = 100.0_nag_wp
      h = 1._nag_wp/real(nx+1,kind=nag_wp)
      ch = cmplx(0.5_nag_wp*h*rho,0.0_nag_wp,kind=nag_wp)

      Do i = 1, nx
        lo = (i-1)*nx

        Do j = lo + 1, lo + nx - 1
          ab(isub,j+1) = -one + ch
          ab(isup,j) = -one - ch
        End Do

      End Do

      mb(isub,2:n) = one
      mb(isup,1:n-1) = one

!     KL-th subdiagonal and KU-th superdiagonal.

      isup = kl + 1
      isub = 2*kl + ku + 1

      Do i = 1, nx - 1
        lo = (i-1)*nx

        Do j = lo + 1, lo + nx
          ab(isup,nx+j) = -one
          ab(isub,j) = -one
        End Do

      End Do

!     Find eigenvalues closest in value to SIGMA and corresponding
!     eigenvectors.

      ldv = n
      Allocate (d(nev),v(ldv,ncv),resid(n))

      ifail = -1
      Call f12auf(kl,ku,ab,ldab,mb,ldmb,sigma,nconv,d,v,ldv,resid,v,ldv,comm,  &
        icomm,ifail)

      If (ifail/=0) Then
        Go To 100
      End If

!     Compute the residual norm  ||A*x - lambda*x||.

      Allocate (ax(n),mx(n),d_print(nconv,3))
      d_print(1:nconv,1) = real(d(1:nconv))
      d_print(1:nconv,2) = aimag(d(1:nconv))

      Do j = 1, nconv

!       The NAG name equivalent of zgbmv is f06sbf
        Call zgbmv('N',n,n,kl,ku,one,ab(kl+1,1),ldab,v(1,j),1,zero,ax,1)

        Call zgbmv('N',n,n,kl,ku,one,mb(kl+1,1),ldmb,v(1,j),1,zero,mx,1)

        Call zaxpy(n,-d(j),mx,1,ax,1)
        d_print(j,3) = dznrm2(n,ax,1)/abs(d(j))

      End Do

      Write (nout,*)
      Flush (nout)

      outchn = nout
      Call x04abf(iset,outchn)

      If (printr) Then
!       Print residual associated with each Ritz value.
        ncol = 3
      Else
        ncol = 2
      End If
      ifail = 0
      Call x04caf('G','N',nconv,ncol,d_print,nconv,                            &
        ' Ritz values closest to sigma',ifail)

100   Continue
    End Program f12aufe


f12fafe.f90

!   F12FAF Example Program Text
!   Mark 26 Release. NAG Copyright 2016.

    Module f12fafe_mod

!     F12FAF Example Program Module:
!            Parameters and User-defined Routines

!     .. Use Statements ..
      Use nag_library, Only: nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Accessibility Statements ..
      Private
      Public                           :: av
!     .. Parameters ..
      Real (Kind=nag_wp), Parameter    :: one = 1.0_nag_wp
      Integer, Parameter, Public       :: imon = 0, ipoint = 0, licomm = 140,  &
                                          nin = 5, nout = 6
    Contains
      Subroutine tv(nx,x,y)
!       Compute the matrix vector multiplication y<---T*x where T is a nx
!       by nx tridiagonal matrix.

!       .. Scalar Arguments ..
        Integer, Intent (In)           :: nx
!       .. Array Arguments ..
        Real (Kind=nag_wp), Intent (In) :: x(nx)
        Real (Kind=nag_wp), Intent (Out) :: y(nx)
!       .. Local Scalars ..
        Real (Kind=nag_wp)             :: dd, dl, du
        Integer                        :: j
!       .. Executable Statements ..
        dd = 4.0_nag_wp
        dl = -one
        du = -one
        y(1) = dd*x(1) + du*x(2)
        Do j = 2, nx - 1
          y(j) = dl*x(j-1) + dd*x(j) + du*x(j+1)
        End Do
        y(nx) = dl*x(nx-1) + dd*x(nx)
        Return
      End Subroutine tv
      Subroutine av(nx,v,w)

!       .. Use Statements ..
        Use nag_library, Only: daxpy, dscal
!       .. Scalar Arguments ..
        Integer, Intent (In)           :: nx
!       .. Array Arguments ..
        Real (Kind=nag_wp), Intent (In) :: v(nx*nx)
        Real (Kind=nag_wp), Intent (Out) :: w(nx*nx)
!       .. Local Scalars ..
        Real (Kind=nag_wp)             :: h2
        Integer                        :: j, lo, n
!       .. Intrinsic Procedures ..
        Intrinsic                      :: real
!       .. Executable Statements ..
        h2 = one/real((nx+1)*(nx+1),kind=nag_wp)
        Call tv(nx,v(1),w(1))
!       The NAG name equivalent of daxpy is f06ecf
        Call daxpy(nx,-one,v(nx+1),1,w(1),1)
        Do j = 2, nx - 1
          lo = (j-1)*nx
          Call tv(nx,v(lo+1),w(lo+1))
          Call daxpy(nx,-one,v(lo-nx+1),1,w(lo+1),1)
          Call daxpy(nx,-one,v(lo+nx+1),1,w(lo+1),1)
        End Do
        lo = (nx-1)*nx
        Call tv(nx,v(lo+1),w(lo+1))
        Call daxpy(nx,-one,v(lo-nx+1),1,w(lo+1),1)
        n = nx*nx
!       The NAG name equivalent of dscal is f06edf
        Call dscal(n,one/h2,w,1)
        Return
      End Subroutine av
    End Module f12fafe_mod
    Program f12fafe

!     F12FAF Example Main Program

!     .. Use Statements ..
      Use nag_library, Only: dnrm2, f12faf, f12fbf, f12fcf, f12fdf, f12fef,    &
                             nag_wp
      Use f12fafe_mod, Only: av, imon, ipoint, licomm, nin, nout
!     .. Implicit None Statement ..
      Implicit None
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: sigma
      Integer                          :: ifail, irevcm, j, lcomm, ldv, n,     &
                                          nconv, ncv, nev, niter, nshift, nx
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: ax(:), comm(:), d(:,:), mx(:),       &
                                          resid(:), v(:,:), x(:)
      Integer                          :: icomm(licomm)
!     .. Executable Statements ..
      Write (nout,*) 'F12FAF Example Program Results'
      Write (nout,*)
!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) nx, nev, ncv

      n = nx*nx
      ldv = n
      lcomm = 3*n + ncv*ncv + 8*ncv + 60
      Allocate (ax(n),comm(lcomm),d(ncv,2),mx(n),resid(n),v(ldv,ncv),x(n))

      ifail = 0
      Call f12faf(n,nev,ncv,icomm,licomm,comm,lcomm,ifail)

      ifail = 0
      Call f12fdf('SMALLEST MAGNITUDE',icomm,comm,ifail)
!     Increase the iteration limit if required.
      Call f12fdf('ITERATION LIMIT=500',icomm,comm,ifail)
      If (ipoint==1) Then
!       Use pointers to Workspace in calculating matrix vector
!       products rather than interfacing through the array X.
        Call f12fdf('POINTERS=YES',icomm,comm,ifail)
      End If

      irevcm = 0
      ifail = -1
revcm: Do
        Call f12fbf(irevcm,resid,v,ldv,x,mx,nshift,comm,icomm,ifail)
        If (irevcm==5) Then
          Exit revcm
        Else If (irevcm==-1 .Or. irevcm==1) Then
!         Perform matrix vector multiplication y <--- Op*x
          If (ipoint==0) Then
            Call av(nx,x,ax)
            x(1:n) = ax(1:n)
          Else
            Call av(nx,comm(icomm(1)),comm(icomm(2)))
          End If
        Else If (irevcm==4 .And. imon/=0) Then
!         Output monitoring information
          Call f12fef(niter,nconv,d,d(1,2),icomm,comm)
!         The NAG name equivalent of dnrm2 is f06ejf
          Write (6,99999) niter, nconv, dnrm2(nev,d(1,2),1)
        End If
      End Do revcm

      If (ifail==0) Then
!       Post-Process using F12FCF to compute eigenvalue/vectors.
        ifail = 0
        Call f12fcf(nconv,d,v,ldv,sigma,resid,v,ldv,comm,icomm,ifail)
        Write (nout,99998) nconv
        Write (nout,99997)(j,d(j,1),j=1,nconv)
      End If

99999 Format (1X,'Iteration',1X,I3,', No. converged =',1X,I3,', norm o',       &
        'f estimates =',E16.8)
99998 Format (1X,/,' The ',I4,' Ritz values of smallest magnitude are:',/)
99997 Format (1X,I8,5X,F12.4)
    End Program f12fafe


f12fbfe.f90

!   F12FBF Example Program Text
!   Mark 26 Release. NAG Copyright 2016.

    Module f12fbfe_mod

!     F12FBF Example Program Module:
!            Parameters and User-defined Routines

!     .. Use Statements ..
      Use nag_library, Only: nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Accessibility Statements ..
      Private
      Public                           :: atv, av
!     .. Parameters ..
      Real (Kind=nag_wp), Parameter, Public :: one = 1.0_nag_wp
      Real (Kind=nag_wp), Parameter, Public :: two = 2.0_nag_wp
      Real (Kind=nag_wp), Parameter, Public :: zero = 0.0_nag_wp
      Integer, Parameter, Public       :: imon = 0, licomm = 140, nin = 5,     &
                                          nout = 6
    Contains
      Subroutine av(m,n,x,w)

!       Computes  w <- A*x.

!       .. Scalar Arguments ..
        Integer, Intent (In)           :: m, n
!       .. Array Arguments ..
        Real (Kind=nag_wp), Intent (Out) :: w(m)
        Real (Kind=nag_wp), Intent (In) :: x(n)
!       .. Local Scalars ..
        Real (Kind=nag_wp)             :: h, k, s, t
        Integer                        :: i, j
!       .. Intrinsic Procedures ..
        Intrinsic                      :: real
!       .. Executable Statements ..
        h = one/real(m+1,kind=nag_wp)
        k = one/real(n+1,kind=nag_wp)
        w(1:m) = zero
        t = zero

        Do j = 1, n
          t = t + k
          s = zero
          Do i = 1, j
            s = s + h
            w(i) = w(i) + k*s*(t-one)*x(j)
          End Do
          Do i = j + 1, m
            s = s + h
            w(i) = w(i) + k*t*(s-one)*x(j)
          End Do
        End Do

        Return
      End Subroutine av

      Subroutine atv(m,n,w,y)

!       Computes  y <- A'*w.

!       .. Scalar Arguments ..
        Integer, Intent (In)           :: m, n
!       .. Array Arguments ..
        Real (Kind=nag_wp), Intent (In) :: w(m)
        Real (Kind=nag_wp), Intent (Out) :: y(n)
!       .. Local Scalars ..
        Real (Kind=nag_wp)             :: h, k, s, t
        Integer                        :: i, j
!       .. Intrinsic Procedures ..
        Intrinsic                      :: real
!       .. Executable Statements ..
        h = one/real(m+1,kind=nag_wp)
        k = one/real(n+1,kind=nag_wp)
        y(1:n) = zero
        t = zero

        Do j = 1, n
          t = t + k
          s = zero
          Do i = 1, j
            s = s + h
            y(j) = y(j) + k*s*(t-one)*w(i)
          End Do
          Do i = j + 1, m
            s = s + h
            y(j) = y(j) + k*t*(s-one)*w(i)
          End Do
        End Do

        Return
      End Subroutine atv
    End Module f12fbfe_mod
    Program f12fbfe

!     F12FBF Example Main Program

!     .. Use Statements ..
      Use f12fbfe_mod, Only: nout
!     .. Implicit None Statement ..
      Implicit None
!     .. Executable Statements ..
      Write (nout,*) 'F12FBF Example Program Results'

      Call ex1

      Call ex2

    Contains
      Subroutine ex1

!       .. Use Statements ..
        Use nag_library, Only: dgttrf, dgttrs, dnrm2, f12faf, f12fbf, f12fcf,  &
                               f12fdf, f12fef, nag_wp
        Use f12fbfe_mod, Only: imon, licomm, nin, one, two, zero
!       .. Local Scalars ..
        Real (Kind=nag_wp)             :: h2, sigma
        Integer                        :: ifail, info, irevcm, j, lcomm, ldv,  &
                                          n, nconv, ncv, nev, niter, nshift
!       .. Local Arrays ..
        Real (Kind=nag_wp), Allocatable :: ad(:), adl(:), adu(:), adu2(:),     &
                                          comm(:), d(:,:), mx(:), resid(:),    &
                                          v(:,:), x(:)
        Integer                        :: icomm(licomm)
        Integer, Allocatable           :: ipiv(:)
!       .. Intrinsic Procedures ..
        Intrinsic                      :: real
!       .. Executable Statements ..
        Write (nout,*)
        Write (nout,*) 'F12FBF Example 1'
        Write (nout,*)
        Flush (nout)
!       Skip heading in data file
        Read (nin,*)
        Read (nin,*)
        Read (nin,*) n, nev, ncv

        ldv = n
        lcomm = 3*n + ncv*ncv + 8*ncv + 60
        Allocate (ad(n),adl(n),adu(n),adu2(n),comm(lcomm),d(ncv,2),mx(n),      &
          resid(n),v(ldv,ncv),x(n),ipiv(n))

        ifail = 0
        Call f12faf(n,nev,ncv,icomm,licomm,comm,lcomm,ifail)

!       Set the region of the spectrum that is required.
        Call f12fdf('LARGEST MAGNITUDE',icomm,comm,ifail)
!       Use the Shifted Inverse mode.
        Call f12fdf('SHIFTED INVERSE',icomm,comm,ifail)

        h2 = one/real((n+1)*(n+1),kind=nag_wp)
        sigma = zero
        ad(1:n) = two/h2 - sigma
        adl(1:n) = -one/h2
        adu(1:n) = adl(1:n)
!       The NAG name equivalent of dgttrf is f07cdf
        Call dgttrf(n,adl,ad,adu,adu2,ipiv,info)

        irevcm = 0
        ifail = -1
revcm:  Do
          Call f12fbf(irevcm,resid,v,ldv,x,mx,nshift,comm,icomm,ifail)
          If (irevcm==5) Then
            Exit revcm
          Else If (irevcm==-1 .Or. irevcm==1) Then
!           Perform matrix vector multiplication
!           y <--- inv[A-sigma*I]*x
!           The NAG name equivalent of dgttrs is f07cef
            Call dgttrs('N',n,1,adl,ad,adu,adu2,ipiv,x,n,info)
          Else If (irevcm==4 .And. imon/=0) Then
!           Output monitoring information
            Call f12fef(niter,nconv,d,d(1,2),icomm,comm)
!           The NAG name equivalent of dnrm2 is f06ejf
            Write (6,99999) niter, nconv, dnrm2(nev,d(1,2),1)
            Flush (nout)
          End If
        End Do revcm

        If (ifail==0) Then
!         Post-Process using F12FCF to compute eigenvalues/vectors.
          Call f12fcf(nconv,d,v,ldv,sigma,resid,v,ldv,comm,icomm,ifail)
          Write (nout,99998) nconv, sigma
          Write (nout,99997)(j,d(j,1),j=1,nconv)
        End If

        Deallocate (ad,adl,adu,adu2,comm,d,mx,resid,v,x,ipiv)

        Return

99999   Format (1X,'Iteration',1X,I3,', No. converged =',1X,I3,', norm o',     &
          'f estimates =',E16.8)
99998   Format (1X,/,' The ',I4,' Ritz values of closest to ',F8.4,' are:',/)
99997   Format (1X,I8,5X,F12.4)
      End Subroutine ex1
      Subroutine ex2

!       .. Use Statements ..
        Use nag_library, Only: daxpy, dnrm2, dscal, f12faf, f12fbf, f12fcf,    &
                               nag_wp, x04caf
        Use f12fbfe_mod, Only: atv, av, licomm, nin, one
!       .. Local Scalars ..
        Real (Kind=nag_wp)             :: sigma, temp
        Integer                        :: ifail, ifail1, irevcm, j, lcomm,     &
                                          ldu, ldv, m, n, nconv, ncv, nev,     &
                                          nshift
!       .. Local Arrays ..
        Real (Kind=nag_wp), Allocatable :: ax(:), comm(:), d(:,:), mx(:),      &
                                          resid(:), u(:,:), v(:,:), x(:)
        Integer                        :: icomm(licomm)
!       .. Intrinsic Procedures ..
        Intrinsic                      :: sqrt
!       .. Executable Statements ..
        Write (nout,*)
        Write (nout,*) 'F12FBF Example 2'
        Write (nout,*)
        Flush (nout)
!       Skip heading in data file
        Read (nin,*)
        Read (nin,*) m, n, nev, ncv

        ldu = m
        ldv = n
        lcomm = 3*n + ncv*ncv + 8*ncv + 60
        Allocate (ax(m),comm(lcomm),d(ncv,2),mx(m),resid(n),u(ldu,nev),        &
          v(ldv,ncv),x(m))

!       Initialize for problem.
        ifail = 0
        Call f12faf(n,nev,ncv,icomm,licomm,comm,lcomm,ifail)

!       Main reverse communication loop.
        irevcm = 0
        ifail = -1
revcm:  Do
          Call f12fbf(irevcm,resid,v,ldv,x,mx,nshift,comm,icomm,ifail)
          If (irevcm==5) Then
            Exit revcm
          Else If (irevcm==-1 .Or. irevcm==1) Then
!           Perform the operation X <- A'AX
            Call av(m,n,x,ax)
            Call atv(m,n,ax,x)
          End If
        End Do revcm

        If (ifail==0) Then
!         Post-Process using F12FCF.
!         Computed singular values may be extracted.
!         Singular vectors may also be computed now if desired.
          ifail1 = 0
          Call f12fcf(nconv,d,v,ldv,sigma,resid,v,ldv,comm,icomm,ifail1)

!         Singular values (squared) are returned in the first column
!         of D and the corresponding right singular vectors are
!         returned in the first NEV columns of V.

          Do j = 1, nconv
            d(j,1) = sqrt(d(j,1))

!           Compute the left singular vectors from the formula
!           u = Av/sigma/norm(Av).

            Call av(m,n,v(1,j),ax)
            u(1:m,j) = ax(1:m)
!           The NAG name equivalent of dnrm2 is f06ejf
            temp = one/dnrm2(m,u(1,j),1)
!           The NAG name equivalent of dscal is f06edf
            Call dscal(m,temp,u(1,j),1)

!           Compute the residual norm ||A*v - sigma*u|| for the nconv
!           accurately computed singular values and vectors.
!           Store the result in 2nd column of array D.

!           The NAG name equivalent of daxpy is f06ecf
            Call daxpy(m,-d(j,1),u(1,j),1,ax,1)
            d(j,2) = dnrm2(m,ax,1)

          End Do

!         Print computed residuals

          Call x04caf('G','N',nconv,2,d,ncv,                                   &
            ' Singular values and direct residuals',ifail1)
        End If

        Deallocate (ax,comm,d,mx,resid,u,v,x)

        Return

      End Subroutine ex2
    End Program f12fbfe


f12fcfe.f90

!   F12FCF Example Program Text
!   Mark 26 Release. NAG Copyright 2016.

    Module f12fcfe_mod

!     F12FCF Example Program Module:
!            Parameters and User-defined Routines

!     .. Use Statements ..
      Use nag_library, Only: nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Accessibility Statements ..
      Private
      Public                           :: av, mv
!     .. Parameters ..
      Real (Kind=nag_wp), Parameter, Public :: four = 4.0_nag_wp
      Real (Kind=nag_wp), Parameter, Public :: one = 1.0_nag_wp
      Real (Kind=nag_wp), Parameter, Public :: six = 6.0_nag_wp
      Real (Kind=nag_wp), Parameter, Public :: zero = 0.0_nag_wp
      Real (Kind=nag_wp), Parameter    :: two = 2.0_nag_wp
      Integer, Parameter, Public       :: imon = 0, licomm = 140, nin = 5,     &
                                          nout = 6
    Contains
      Subroutine mv(n,v,w)

!       .. Use Statements ..
        Use nag_library, Only: dscal
!       .. Scalar Arguments ..
        Integer, Intent (In)           :: n
!       .. Array Arguments ..
        Real (Kind=nag_wp), Intent (In) :: v(n)
        Real (Kind=nag_wp), Intent (Out) :: w(n)
!       .. Local Scalars ..
        Real (Kind=nag_wp)             :: h
        Integer                        :: j
!       .. Intrinsic Procedures ..
        Intrinsic                      :: real
!       .. Executable Statements ..
        h = one/(real(n+1,kind=nag_wp)*six)
        w(1) = four*v(1) + v(2)
        Do j = 2, n - 1
          w(j) = v(j-1) + four*v(j) + v(j+1)
        End Do
        j = n
        w(j) = v(j-1) + four*v(j)
!       The NAG name equivalent of dscal is f06edf
        Call dscal(n,h,w,1)
        Return
      End Subroutine mv

      Subroutine av(n,v,w)

!       .. Use Statements ..
        Use nag_library, Only: dscal
!       .. Scalar Arguments ..
        Integer, Intent (In)           :: n
!       .. Array Arguments ..
        Real (Kind=nag_wp), Intent (In) :: v(n)
        Real (Kind=nag_wp), Intent (Out) :: w(n)
!       .. Local Scalars ..
        Real (Kind=nag_wp)             :: h
        Integer                        :: j
!       .. Intrinsic Procedures ..
        Intrinsic                      :: real
!       .. Executable Statements ..
        h = one/real(n+1,kind=nag_wp)
        w(1) = two*v(1) - v(2)
        Do j = 2, n - 1
          w(j) = -v(j-1) + two*v(j) - v(j+1)
        End Do
        j = n
        w(j) = -v(j-1) + two*v(j)
!       The NAG name equivalent of dscal is f06edf
        Call dscal(n,one/h,w,1)
        Return
      End Subroutine av
    End Module f12fcfe_mod
    Program f12fcfe

!     F12FCF Example Main Program

!     .. Use Statements ..
      Use nag_library, Only: dgttrf, dgttrs, dnrm2, f12faf, f12fbf, f12fcf,    &
                             f12fdf, f12fef, nag_wp
      Use f12fcfe_mod, Only: av, four, imon, licomm, mv, nin, nout, one, six,  &
                             zero
!     .. Implicit None Statement ..
      Implicit None
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: h, r1, r2, sigma
      Integer                          :: ifail, info, irevcm, j, lcomm, ldv,  &
                                          n, nconv, ncv, nev, niter, nshift
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: ad(:), adl(:), adu(:), adu2(:),      &
                                          comm(:), d(:,:), mx(:), resid(:),    &
                                          v(:,:), x(:)
      Integer                          :: icomm(licomm)
      Integer, Allocatable             :: ipiv(:)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: real
!     .. Executable Statements ..
      Write (nout,*) 'F12FCF Example Program Results'
      Write (nout,*)
!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) n, nev, ncv

      lcomm = 3*n + ncv*ncv + 8*ncv + 60
      ldv = n
      Allocate (ad(n),adl(n),adu(n),adu2(n),comm(lcomm),d(ncv,2),mx(n),        &
        resid(n),v(ldv,ncv),x(n),ipiv(n))

      ifail = 0
      Call f12faf(n,nev,ncv,icomm,licomm,comm,lcomm,ifail)

!     We are solving a generalized problem
      ifail = 0
      Call f12fdf('GENERALIZED',icomm,comm,ifail)

      h = one/real(n+1,kind=nag_wp)
      r1 = (four/six)*h
      r2 = (one/six)*h
      ad(1:n) = r1
      adl(1:n) = r2
      adu(1:n) = adl(1:n)
!     The NAG name equivalent of dgttrf is f07cdf
      Call dgttrf(n,adl,ad,adu,adu2,ipiv,info)

      irevcm = 0
      ifail = -1
revcm: Do
        Call f12fbf(irevcm,resid,v,ldv,x,mx,nshift,comm,icomm,ifail)
        If (irevcm==5) Then
          Exit revcm
        Else If (irevcm==-1 .Or. irevcm==1) Then
!         Perform  X <--- OP*x = inv[M]*A*x.
          Call av(n,x,mx)
          x(1:n) = mx(1:n)
!         The NAG name equivalent of dgttrs is f07cef
          Call dgttrs('N',n,1,adl,ad,adu,adu2,ipiv,x,n,info)
        Else If (irevcm==2) Then
!         Perform  MX <--- M*x.
          Call mv(n,x,mx)
        Else If (irevcm==4 .And. imon/=0) Then
!         Output monitoring information
          Call f12fef(niter,nconv,d,d(1,2),icomm,comm)
!         The NAG name equivalent of dnrm2 is f06ejf
          Write (6,99999) niter, nconv, dnrm2(nev,d(1,2),1)
        End If
      End Do revcm

      If (ifail==0) Then
!       Post-Process using F12FCF to compute eigenvalues/vectors.
        sigma = zero
        ifail = 0
        Call f12fcf(nconv,d,v,ldv,sigma,resid,v,ldv,comm,icomm,ifail)
        Write (nout,99998) nconv
        Write (nout,99997)(j,d(j,1),j=1,nconv)
      End If

99999 Format (1X,'Iteration',1X,I3,', No. converged =',1X,I3,', norm o',       &
        'f estimates =',E16.8)
99998 Format (1X,/,' The ',I4,' generalized Ritz values of largest magn',      &
        'itude are:',/)
99997 Format (1X,I8,5X,F9.1)
    End Program f12fcfe


f12fdfe.f90

!   F12FDF Example Program Text
!   Mark 26 Release. NAG Copyright 2016.

    Module f12fdfe_mod

!     F12FDF Example Program Module:
!            Parameters and User-defined Routines

!     .. Use Statements ..
      Use nag_library, Only: nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Accessibility Statements ..
      Private
      Public                           :: mv
!     .. Parameters ..
      Real (Kind=nag_wp), Parameter, Public :: four = 4.0_nag_wp
      Real (Kind=nag_wp), Parameter, Public :: one = 1.0_nag_wp
      Real (Kind=nag_wp), Parameter, Public :: six = 6.0_nag_wp
      Real (Kind=nag_wp), Parameter, Public :: two = 2.0_nag_wp
      Real (Kind=nag_wp), Parameter, Public :: zero = 0.0_nag_wp
      Integer, Parameter, Public       :: imon = 0, ipoint = 1, licomm = 140,  &
                                          nin = 5, nout = 6
    Contains
      Subroutine mv(n,v,w)

!       .. Use Statements ..
        Use nag_library, Only: dscal
!       .. Scalar Arguments ..
        Integer, Intent (In)           :: n
!       .. Array Arguments ..
        Real (Kind=nag_wp), Intent (In) :: v(n)
        Real (Kind=nag_wp), Intent (Out) :: w(n)
!       .. Local Scalars ..
        Real (Kind=nag_wp)             :: h
        Integer                        :: j
!       .. Intrinsic Procedures ..
        Intrinsic                      :: real
!       .. Executable Statements ..
        h = one/(real(n+1,kind=nag_wp)*six)
        w(1) = four*v(1) + v(2)
        Do j = 2, n - 1
          w(j) = v(j-1) + four*v(j) + v(j+1)
        End Do
        j = n
        w(j) = v(j-1) + four*v(j)
!       The NAG name equivalent of dscal is f06edf
        Call dscal(n,h,w,1)
        Return
      End Subroutine mv
    End Module f12fdfe_mod
    Program f12fdfe

!     F12FDF Example Main Program

!     .. Use Statements ..
      Use nag_library, Only: dcopy, dgttrf, dgttrs, dnrm2, f12faf, f12fbf,     &
                             f12fcf, f12fdf, f12fef, nag_wp
      Use f12fdfe_mod, Only: four, imon, ipoint, licomm, mv, nin, nout, one,   &
                             six, two, zero
!     .. Implicit None Statement ..
      Implicit None
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: h, r1, r2, sigma
      Integer                          :: ifail, info, irevcm, j, lcomm, ldv,  &
                                          n, nconv, ncv, nev, niter, nshift
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: ad(:), adl(:), adu(:), adu2(:),      &
                                          comm(:), d(:,:), mx(:), resid(:),    &
                                          v(:,:), x(:)
      Integer                          :: icomm(licomm)
      Integer, Allocatable             :: ipiv(:)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: real
!     .. Executable Statements ..
      Write (nout,*) 'F12FDF Example Program Results'
      Write (nout,*)
!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) n, nev, ncv

      lcomm = 3*n + ncv*ncv + 8*ncv + 60
      ldv = n
      Allocate (ad(n),adl(n),adu(n),adu2(n),comm(lcomm),d(ncv,2),mx(n),        &
        resid(n),v(ldv,ncv),x(n),ipiv(n))

      ifail = 0
      Call f12faf(n,nev,ncv,icomm,licomm,comm,lcomm,ifail)

!     We are solving a generalized problem
      ifail = 0
      Call f12fdf('GENERALIZED',icomm,comm,ifail)
!     Indicate that we are using the shift and invert mode.
      Call f12fdf('SHIFTED INVERSE',icomm,comm,ifail)
      If (ipoint==1) Then
!       Use pointers to Workspace in calculating matrix vector
!       products rather than interfacing through the array X
        Call f12fdf('POINTERS=YES',icomm,comm,ifail)
      End If

      h = one/real(n+1,kind=nag_wp)
      r1 = (four/six)*h
      r2 = (one/six)*h
      sigma = zero
      ad(1:n) = two/h - sigma*r1
      adl(1:n) = -one/h - sigma*r2
      adu(1:n) = adl(1:n)
!     The NAG name equivalent of dgttrf is f07cdf
      Call dgttrf(n,adl,ad,adu,adu2,ipiv,info)

      irevcm = 0
      ifail = -1
revcm: Do
        Call f12fbf(irevcm,resid,v,ldv,x,mx,nshift,comm,icomm,ifail)
        If (irevcm==5) Then
          Exit revcm
        Else If (irevcm==-1) Then
!         Perform  y <--- OP*x = inv[A-SIGMA*M]*M*x
!         The NAG name equivalent of dgttrs is f07cef
          If (ipoint==0) Then
            Call mv(n,x,mx)
            x(1:n) = mx(1:n)
            Call dgttrs('N',n,1,adl,ad,adu,adu2,ipiv,x,n,info)
          Else
            Call mv(n,comm(icomm(1)),comm(icomm(2)))
            Call dgttrs('N',n,1,adl,ad,adu,adu2,ipiv,comm(icomm(2)),n,info)
          End If
        Else If (irevcm==1) Then
!         Perform y <-- OP*x = inv[A-sigma*M]*M*x
!         The NAG name equivalent of dgttrs is f07cef.
!         M*x has been saved in COMM(ICOMM(3)) or MX.
          If (ipoint==0) Then
            x(1:n) = mx(1:n)
            Call dgttrs('N',n,1,adl,ad,adu,adu2,ipiv,x,n,info)
          Else
!           The NAG name equivalent of dcopy is f06eff
            Call dcopy(n,comm(icomm(3)),1,comm(icomm(2)),1)
            Call dgttrs('N',n,1,adl,ad,adu,adu2,ipiv,comm(icomm(2)),n,info)
          End If
        Else If (irevcm==2) Then
!         Perform  y <--- M*x.
          If (ipoint==0) Then
            Call mv(n,x,mx)
          Else
            Call mv(n,comm(icomm(1)),comm(icomm(2)))
          End If
        Else If (irevcm==4 .And. imon/=0) Then
!         Output monitoring information
          Call f12fef(niter,nconv,d,d(1,2),icomm,comm)
!         The NAG name equivalent of dnrm2 is f06ejf
          Write (6,99999) niter, nconv, dnrm2(nev,d(1,2),1)
        End If
      End Do revcm

      If (ifail==0) Then
!       Post-Process using F12FCF to compute eigenvalues/values.
        ifail = 0
        Call f12fcf(nconv,d,v,ldv,sigma,resid,v,ldv,comm,icomm,ifail)
        Write (nout,99998) nconv, sigma
        Write (nout,99997)(j,d(j,1),j=1,nconv)
      End If

99999 Format (1X,'Iteration',1X,I3,', No. converged =',1X,I3,', norm o',       &
        'f estimates =',E16.8)
99998 Format (1X,/,' The ',I4,' Ritz values of closest to ',F8.4,' are:',/)
99997 Format (1X,I8,5X,F12.4)
    End Program f12fdfe


f12fefe.f90

!   F12FEF Example Program Text
!   Mark 26 Release. NAG Copyright 2016.

    Module f12fefe_mod

!     F12FEF Example Program Module:
!            Parameters and User-defined Routines

!     .. Use Statements ..
      Use nag_library, Only: nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Accessibility Statements ..
      Private
      Public                           :: av
!     .. Parameters ..
      Real (Kind=nag_wp), Parameter, Public :: four = 4.0_nag_wp
      Real (Kind=nag_wp), Parameter, Public :: one = 1.0_nag_wp
      Real (Kind=nag_wp), Parameter, Public :: six = 6.0_nag_wp
      Real (Kind=nag_wp), Parameter, Public :: two = 2.0_nag_wp
      Integer, Parameter, Public       :: imon = 1, ipoint = 0, licomm = 140,  &
                                          nin = 5, nout = 6
    Contains
      Subroutine av(n,v,w)

!       .. Use Statements ..
        Use nag_library, Only: dscal
!       .. Scalar Arguments ..
        Integer, Intent (In)           :: n
!       .. Array Arguments ..
        Real (Kind=nag_wp), Intent (In) :: v(n)
        Real (Kind=nag_wp), Intent (Out) :: w(n)
!       .. Local Scalars ..
        Real (Kind=nag_wp)             :: h
        Integer                        :: j
!       .. Intrinsic Procedures ..
        Intrinsic                      :: real
!       .. Executable Statements ..
        h = one/real(n+1,kind=nag_wp)
        w(1) = two*v(1) - v(2)
        Do j = 2, n - 1
          w(j) = -v(j-1) + two*v(j) - v(j+1)
        End Do
        j = n
        w(j) = -v(j-1) + two*v(j)
!       The NAG name equivalent of dscal is f06edf
        Call dscal(n,one/h,w,1)
        Return
      End Subroutine av
    End Module f12fefe_mod
    Program f12fefe

!     F12FEF Example Main Program

!     .. Use Statements ..
      Use nag_library, Only: dcopy, dgttrf, dgttrs, dnrm2, f12faf, f12fbf,     &
                             f12fcf, f12fdf, f12fef, nag_wp
      Use f12fefe_mod, Only: av, four, imon, ipoint, licomm, nin, nout, one,   &
                             six, two
!     .. Implicit None Statement ..
      Implicit None
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: h, r1, r2, sigma
      Integer                          :: ifail, info, irevcm, j, lcomm, ldv,  &
                                          n, nconv, ncv, nev, niter, nshift
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: ad(:), adl(:), adu(:), adu2(:),      &
                                          comm(:), d(:,:), mx(:), resid(:),    &
                                          v(:,:), x(:)
      Integer                          :: icomm(licomm)
      Integer, Allocatable             :: ipiv(:)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: real
!     .. Executable Statements ..
      Write (nout,*) 'F12FEF Example Program Results'
      Write (nout,*)
!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) n, nev, ncv

      lcomm = 3*n + ncv*ncv + 8*ncv + 60
      ldv = n
      Allocate (ad(n),adl(n),adu(n),adu2(n),comm(lcomm),d(ncv,2),mx(n),        &
        resid(n),v(ldv,ncv),x(n),ipiv(n))

      ifail = 0
      Call f12faf(n,nev,ncv,icomm,licomm,comm,lcomm,ifail)

!     We are solving a generalized problem
      ifail = 0
      Call f12fdf('GENERALIZED',icomm,comm,ifail)
!     Indicate that we are using the buckling mode.
      Call f12fdf('BUCKLING',icomm,comm,ifail)
      If (ipoint==1) Then
        Call f12fdf('POINTERS=YES',icomm,comm,ifail)
      End If

      h = one/real(n+1,kind=nag_wp)
      r1 = (four/six)*h
      r2 = (one/six)*h
      sigma = one
      ad(1:n) = two/h - sigma*r1
      adl(1:n) = -one/h - sigma*r2
      adu(1:n) = adl(1:n)

!     The NAG name equivalent of dgttrf is f07cdf
      Call dgttrf(n,adl,ad,adu,adu2,ipiv,info)

      irevcm = 0
      ifail = -1
revcm: Do
        Call f12fbf(irevcm,resid,v,ldv,x,mx,nshift,comm,icomm,ifail)
        If (irevcm==5) Then
          Exit revcm
        Else If (irevcm==-1) Then
!         Perform  y <--- OP*x = inv[K-SIGMA*KG]*K*x
!         The NAG name equivalent of dgttrs is f07cef
          If (ipoint==0) Then
            Call av(n,x,mx)
            x(1:n) = mx(1:n)
            Call dgttrs('N',n,1,adl,ad,adu,adu2,ipiv,x,n,info)
          Else
            Call av(n,comm(icomm(1)),comm(icomm(2)))
            Call dgttrs('N',n,1,adl,ad,adu,adu2,ipiv,comm(icomm(2)),n,info)
          End If
        Else If (irevcm==1) Then
!         Perform y <-- OP*x = inv[K-sigma*KG]*K*x.
!         The NAG name equivalent of dgttrs is f07cef
          If (ipoint==0) Then
            x(1:n) = mx(1:n)
            Call dgttrs('N',n,1,adl,ad,adu,adu2,ipiv,x,n,info)
          Else
!           The NAG name equivalent of dcopy is f06eff
            Call dcopy(n,comm(icomm(3)),1,comm(icomm(2)),1)
            Call dgttrs('N',n,1,adl,ad,adu,adu2,ipiv,comm(icomm(2)),n,info)
          End If
        Else If (irevcm==2) Then
!         Perform  y <--- M*x.
          If (ipoint==0) Then
            Call av(n,x,mx)
          Else
            Call av(n,comm(icomm(1)),comm(icomm(2)))
          End If
        Else If (irevcm==4 .And. imon/=0) Then
!         Output monitoring information
          Call f12fef(niter,nconv,d,d(1,2),icomm,comm)
!         The NAG name equivalent of dnrm2 is f06ejf
          Write (6,99999) niter, nconv, dnrm2(nev,d(1,2),1)
        End If
      End Do revcm

      If (ifail==0) Then
!       Post-Process using F12FCF to compute eigenvalues/vectors.
        Call f12fcf(nconv,d,v,ldv,sigma,resid,v,ldv,comm,icomm,ifail)
        Write (nout,99998) nconv, sigma
        Write (nout,99997)(j,d(j,1),j=1,nconv)
      End If

99999 Format (1X,'Iteration',1X,I3,', No. converged =',1X,I3,', norm o',       &
        'f estimates =',E16.8)
99998 Format (1X,/,' The ',I4,' generalized Ritz values closest to ',F8.4,     &
        ' are:',/)
99997 Format (1X,I8,5X,F12.4)
    End Program f12fefe


f12fgfe.f90

    Program f12fgfe

!     F12FGF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: daxpy, dgbmv, dnrm2, f12fff, f12fgf, nag_wp,      &
                             x04abf, x04caf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Real (Kind=nag_wp), Parameter    :: one = 1.0_nag_wp
      Real (Kind=nag_wp), Parameter    :: zero = 0.0_nag_wp
      Integer, Parameter               :: inc1 = 1, iset = 1, nin = 5,         &
                                          nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: h2, sigma
      Integer                          :: i, idiag, ifail, isub, isup, j, kl,  &
                                          ku, lcomm, ldab, ldmb, ldv, licomm,  &
                                          lo, n, nconv, ncv, nev, nx, outchn
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: ab(:,:), ax(:), comm(:), d(:),       &
                                          d_print(:,:), mb(:,:), resid(:),     &
                                          v(:,:)
      Integer, Allocatable             :: icomm(:)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: abs, int, max, real
!     .. Executable Statements ..
      Write (nout,*) 'F12FGF Example Program Results'
      Write (nout,*)

!     Skip heading in data file
      Read (nin,*)

      Read (nin,*) nx, nev, ncv
      n = nx*nx

!     Initialize communication arrays.
!     Query the required sizes of the communication arrays.

      licomm = -1
      lcomm = -1
      Allocate (icomm(max(1,licomm)),comm(max(1,lcomm)))

      ifail = 0
      Call f12fff(n,nev,ncv,icomm,licomm,comm,lcomm,ifail)

      licomm = icomm(1)
      lcomm = int(comm(1))
      Deallocate (icomm,comm)
      Allocate (icomm(max(1,licomm)),comm(max(1,lcomm)))

      ifail = 0
      Call f12fff(n,nev,ncv,icomm,licomm,comm,lcomm,ifail)

!     Construct the matrix A in banded form and store in AB.
!     KU, KL are number of superdiagonals and subdiagonals within
!     the band of matrices A and M.

      kl = nx
      ku = nx
      ldab = 2*kl + ku + 1
      Allocate (ab(ldab,n))

!     Zero out AB.

      ab(1:ldab,1:n) = 0.0_nag_wp

!     Main diagonal of A.

      h2 = one/real((nx+1)*(nx+1),kind=nag_wp)
      idiag = kl + ku + 1
      ab(idiag,1:n) = 4.0_nag_wp/h2

!     First subdiagonal and superdiagonal of A.

      isup = kl + ku
      isub = kl + ku + 2

      Do i = 1, nx
        lo = (i-1)*nx

        Do j = lo + 1, lo + nx - 1
          ab(isup,j+1) = -one/h2
          ab(isub,j) = -one/h2
        End Do

      End Do

!     KL-th subdiagonal and KU-th superdiagonal.

      isup = kl + 1
      isub = 2*kl + ku + 1

      Do i = 1, nx - 1
        lo = (i-1)*nx

        Do j = lo + 1, lo + nx
          ab(isup,nx+j) = -one/h2
          ab(isub,j) = -one/h2
        End Do

      End Do

!     Find eigenvalues of largest magnitude and the corresponding
!     eigenvectors.

      ldmb = 2*kl + ku + 1
      ldv = n
      Allocate (mb(ldmb,n),d(ncv),v(ldv,ncv+1),resid(n))

      ifail = -1
      Call f12fgf(kl,ku,ab,ldab,mb,ldmb,sigma,nconv,d,v,ldv,resid,v,ldv,comm,  &
        icomm,ifail)

      If (ifail/=0) Then
        Go To 100
      End If

!     Compute the residual norm  ||A*x - lambda*x||.

      Allocate (d_print(nconv,2),ax(n))
      d_print(1:nconv,1) = d(1:nconv)

      Do j = 1, nconv

!       The NAG name equivalent of dgbmv is f06pbf
        Call dgbmv('N',n,n,kl,ku,one,ab(kl+1,1),ldab,v(1,j),inc1,zero,ax,inc1)

!       The NAG name equivalent of daxpy is f06ecf
        Call daxpy(n,-d_print(j,1),v(1,j),inc1,ax,inc1)

!       The NAG name equivalent of dnrm2 is f06ejf
        d_print(j,2) = dnrm2(n,ax,1)
      End Do

      d_print(1:nconv,2) = d_print(1:nconv,2)/abs(d_print(1:nconv,1))

      Write (nout,*)
      Flush (nout)

      outchn = nout
      Call x04abf(iset,outchn)

      ifail = 0
      Call x04caf('G','N',nconv,2,d_print,nconv,' Ritz values and residuals',  &
        ifail)

100   Continue
    End Program f12fgfe


f16dlfe.f90

    Program f16dlfe

!     F16DLF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: f16dlf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Integer                          :: i, incx, ix, n, sumval
!     .. Local Arrays ..
      Integer, Allocatable             :: x(:)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: abs
!     .. Executable Statements ..
      Write (nout,*) 'F16DLF Example Program Results'

!     Skip heading in data file
      Read (nin,*)

      Read (nin,*) n, incx
      Allocate (x(1+(n-1)*abs(incx)))

!     Read the vector x and store forwards or backwards
!     as determined by incx.
      If (incx>0) Then
        ix = 1
      Else
        ix = 1 - (n-1)*incx
      End If

      Do i = 1, n
        Read (nin,*) x(ix)
        ix = ix + incx
      End Do

!     Sum the elements of x

      sumval = f16dlf(n,x,incx)

      Write (nout,*)
      Write (nout,99999) sumval

99999 Format (1X,'Sum of elements of x is',I5)
    End Program f16dlfe


f16dnfe.f90

    Program f16dnfe

!     F16DNF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: f16dnf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Integer                          :: i, incx, j, jx, k, n
!     .. Local Arrays ..
      Integer, Allocatable             :: x(:)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: abs
!     .. Executable Statements ..
      Write (nout,*) 'F16DNF Example Program Results'

!     Skip heading in data file
      Read (nin,*)

      Read (nin,*) n, incx
      Allocate (x(1+(n-1)*abs(incx)))

!     Read the vector x and store forwards or backwards
!     as determined by incx.
      If (incx>0) Then
        jx = 1
      Else
        jx = 1 - (n-1)*incx
      End If

      Do j = 1, n
        Read (nin,*) x(jx)
        jx = jx + incx
      End Do

!     Find k = argmax(x) and i = max(x).

      Call f16dnf(n,x,incx,k,i)

      Write (nout,*)
      Write (nout,99999) k
      Write (nout,99998) i

99999 Format (1X,'Index of largest component of x is',I3)
99998 Format (1X,'Largest component of x is',I12)
    End Program f16dnfe


f16dpfe.f90

    Program f16dpfe

!     F16DPF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: f16dpf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Integer                          :: i, incx, j, jx, k, n
!     .. Local Arrays ..
      Integer, Allocatable             :: x(:)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: abs
!     .. Executable Statements ..
      Write (nout,*) 'F16DPF Example Program Results'

!     Skip heading in data file
      Read (nin,*)

      Read (nin,*) n, incx
      Allocate (x(1+(n-1)*abs(incx)))

!     Read the vector x and store forwards or backwards
!     as determined by incx.
      If (incx>0) Then
        jx = 1
      Else
        jx = 1 - (n-1)*incx
      End If

      Do j = 1, n
        Read (nin,*) x(jx)
        jx = jx + incx
      End Do

!     Find k = argmin(x) and i = min(x).

      Call f16dpf(n,x,incx,k,i)

      Write (nout,*)
      Write (nout,99999) k
      Write (nout,99998) i

99999 Format (1X,'Index of smallest component of x is',I3)
99998 Format (1X,'Smallest component of x is',I12)
    End Program f16dpfe


f16dqfe.f90

    Program f16dqfe

!     F16DQF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: f16dqf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Integer                          :: i, incx, j, jx, k, n
!     .. Local Arrays ..
      Integer, Allocatable             :: x(:)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: abs
!     .. Executable Statements ..
      Write (nout,*) 'F16DQF Example Program Results'

!     Skip heading in data file
      Read (nin,*)

      Read (nin,*) n, incx
      Allocate (x(1+(n-1)*abs(incx)))

!     Read the vector x and store forwards or backwards
!     as determined by incx.
      If (incx>0) Then
        jx = 1
      Else
        jx = 1 - (n-1)*incx
      End If

      Do j = 1, n
        Read (nin,*) x(jx)
        jx = jx + incx
      End Do

!     Find k = argmax(abs(x)) and i = max(abs(x)).

      Call f16dqf(n,x,incx,k,i)

      Write (nout,*)
      Write (nout,99999) k
      Write (nout,99998) i

99999 Format (1X,'Index of absolutely largest component of x is',I3)
99998 Format (1X,'Absolutely largest component of x is',I12)
    End Program f16dqfe


f16drfe.f90

    Program f16drfe

!     F16DRF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: f16drf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Integer                          :: i, incx, j, jx, k, n
!     .. Local Arrays ..
      Integer, Allocatable             :: x(:)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: abs
!     .. Executable Statements ..
      Write (nout,*) 'F16DRF Example Program Results'

!     Skip heading in data file
      Read (nin,*)

      Read (nin,*) n, incx
      Allocate (x(1+(n-1)*abs(incx)))

!     Read the vector x and store forwards or backwards
!     as determined by incx.
      If (incx>0) Then
        jx = 1
      Else
        jx = 1 - (n-1)*incx
      End If

      Do j = 1, n
        Read (nin,*) x(jx)
        jx = jx + incx
      End Do

!     Find k = argmin(abs(x)) and i = min(abs(x)).

      Call f16drf(n,x,incx,k,i)

      Write (nout,*)
      Write (nout,99999) k
      Write (nout,99998) i

99999 Format (1X,'Index of absolutely smallest component of x is',I3)
99998 Format (1X,'Absolutely smallest component of x is',I12)
    End Program f16drfe


f16eafe.f90

    Program f16eafe

!     F16EAF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: blas_ddot, nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: alpha, beta, r
      Integer                          :: conj, i, incx, incy, ix, iy, j, n
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: x(:), y(:)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: abs
!     .. Executable Statements ..
      Write (nout,*) 'F16EAF Example Program Results'
      Write (nout,*)

!     Skip heading in data file.
      Read (nin,*)

!     Accumulate two dot products, set beta=zero initially.
      beta = 0.0_nag_wp

      Do j = 1, 2
!       Read data for dot product.
        Read (nin,*) n
        Read (nin,*) incx, incy
        Allocate (x(1+(n-1)*abs(incx)),y(1+(n-1)*abs(incy)))

        Read (nin,*) alpha

!       Read the vectors x and y and store forwards or backwards
!       as determined by incx (resp. incy).
        If (incx>0) Then
          ix = 1
        Else
          ix = 1 - (n-1)*incx
        End If

        Do i = 1, n
          Read (nin,*) x(ix)
          ix = ix + incx
        End Do

        If (incy>0) Then
          iy = 1
        Else
          iy = 1 - (n-1)*incy
        End If

        Do i = 1, n
          Read (nin,*) y(iy)
          iy = iy + incy
        End Do

!       Compute r = beta*r + alpha*(x^T*y).
!       The NAG name equivalent of blas_ddot is f16eaf.
        Call blas_ddot(conj,n,alpha,x,incx,beta,y,incy,r)

!       Reset beta for accumulation and deallocate x, y.
        beta = 1.0_nag_wp
        Deallocate (x,y)
      End Do

      Write (nout,99999) r

99999 Format (1X,'Accumulated dot product, r = ',F9.4)
    End Program f16eafe


f16ecfe.f90

    Program f16ecfe

!     F16ECF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: blas_daxpby, nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: alpha, beta
      Integer                          :: i, incx, incy, ix, iy, n
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: x(:), y(:)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: abs
!     .. Executable Statements ..
      Write (nout,*) 'F16ECF Example Program Results'

!     Skip heading in data file
      Read (nin,*)

      Read (nin,*) n
      Read (nin,*) incx, incy
      Allocate (x(1+(n-1)*abs(incx)),y(1+(n-1)*abs(incy)))

      Read (nin,*) alpha, beta

!     Read the vectors x and y and store forwards or backwards
!     as determined by incx (resp. incy).
      If (incx>0) Then
        ix = 1
      Else
        ix = 1 - (n-1)*incx
      End If

      Do i = 1, n
        Read (nin,*) x(ix)
        ix = ix + incx
      End Do

      If (incy>0) Then
        iy = 1
      Else
        iy = 1 - (n-1)*incy
      End If

      Do i = 1, n
        Read (nin,*) y(iy)
        iy = iy + incy
      End Do

!     Compute y = alpha*x + beta*y

      Call blas_daxpby(n,alpha,x,incx,beta,y,incy)

!     Display the vector y forwards or backwards
!     as determined by incy.
      Write (nout,*)
      Write (nout,99999)
      If (incy>0) Then
        Write (nout,99998) y(1:1+(n-1)*incy:incy)
      Else
        Write (nout,99998) y(1-(n-1)*incy:1:incy)
      End If

99999 Format (1X,'Result of scaled vector addition is')
99998 Format (1X,'y =',5F9.4)
    End Program f16ecfe


f16ehfe.f90

    Program f16ehfe

!     F16EHF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: blas_dwaxpby, nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: alpha, beta
      Integer                          :: i, incw, incx, incy, ix, iy, n
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: w(:), x(:), y(:)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: abs
!     .. Executable Statements ..
      Write (nout,*) 'F16EHF Example Program Results'

!     Skip heading in data file
      Read (nin,*)

      Read (nin,*) n
      Read (nin,*) incx, incy, incw
      Allocate (w(1+(n-1)*abs(incw)),x(1+(n-1)*abs(incx)),y(1+(n-              &
        1)*abs(incy)))

      Read (nin,*) alpha, beta

!     Read the vectors x and y and store forwards or backwards
!     as determined by incx (resp. incy).
      If (incx>0) Then
        ix = 1
      Else
        ix = 1 - (n-1)*incx
      End If

      Do i = 1, n
        Read (nin,*) x(ix)
        ix = ix + incx
      End Do

      If (incy>0) Then
        iy = 1
      Else
        iy = 1 - (n-1)*incy
      End If

      Do i = 1, n
        Read (nin,*) y(iy)
        iy = iy + incy
      End Do

!     Compute w = alpha*x + beta*y

      Call blas_dwaxpby(n,alpha,x,incx,beta,y,incy,w,incw)

!     Display the vector w forwards or backwards
!     as determined by incw.
      Write (nout,*)
      Write (nout,99999)
      If (incw>0) Then
        Write (nout,99998) w(1:1+(n-1)*incw:incw)
      Else
        Write (nout,99998) w(1-(n-1)*incw:1:incw)
      End If

99999 Format (1X,'Result of scaled vector addition is')
99998 Format (1X,'w =',5F9.4)
    End Program f16ehfe


f16elfe.f90

    Program f16elfe

!     F16ELF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: blas_dsum, nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: sumval
      Integer                          :: i, incx, ix, n
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: x(:)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: abs
!     .. Executable Statements ..
      Write (nout,*) 'F16ELF Example Program Results'

!     Skip heading in data file
      Read (nin,*)

      Read (nin,*) n, incx
      Allocate (x(1+(n-1)*abs(incx)))

!     Read the vector x and store forwards or backwards
!     as determined by incx.
      If (incx>0) Then
        ix = 1
      Else
        ix = 1 - (n-1)*incx
      End If

      Do i = 1, n
        Read (nin,*) x(ix)
        ix = ix + incx
      End Do

!     Sum the elements of x

      sumval = blas_dsum(n,x,incx)

      Write (nout,*)
      Write (nout,99999) sumval

99999 Format (1X,'Sum of elements of x is',F9.5)
    End Program f16elfe


f16gcfe.f90

    Program f16gcfe

!     F16GCF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: blas_zaxpby, nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Complex (Kind=nag_wp)            :: alpha, beta
      Integer                          :: i, incx, incy, ix, iy, n
!     .. Local Arrays ..
      Complex (Kind=nag_wp), Allocatable :: x(:), y(:)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: abs
!     .. Executable Statements ..
      Write (nout,*) 'F16GCF Example Program Results'

!     Skip heading in data file
      Read (nin,*)

      Read (nin,*) n
      Read (nin,*) incx, incy

      Allocate (x(1+(n-1)*abs(incx)),y(1+(n-1)*abs(incy)))

      Read (nin,*) alpha, beta

!     Read the vectors x and y and store forwards or backwards
!     as determined by incx (resp. incy).
      If (incx>0) Then
        ix = 1
      Else
        ix = 1 - (n-1)*incx
      End If

      Do i = 1, n
        Read (nin,*) x(ix)
        ix = ix + incx
      End Do

      If (incy>0) Then
        iy = 1
      Else
        iy = 1 - (n-1)*incy
      End If

      Do i = 1, n
        Read (nin,*) y(iy)
        iy = iy + incy
      End Do

!     Compute y = alpha*x + beta*y

      Call blas_zaxpby(n,alpha,x,incx,beta,y,incy)

!     Display the vector y forwards or backwards
!     as determined by incy.
      Write (nout,*)
      Write (nout,99999)
      If (incy>0) Then
        Write (nout,99998) y(1:1+(n-1)*incy:incy)
      Else
        Write (nout,99998) y(1-(n-1)*incy:1:incy)
      End If

99999 Format (1X,'Result of scaled vector addition is')
99998 Format (1X,'y = ( ',2('(',F9.4,',',F9.4,'), '),'(',F9.4,',',F9.4,') )')
    End Program f16gcfe


f16ghfe.f90

    Program f16ghfe

!     F16GHF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: blas_zwaxpby, nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Complex (Kind=nag_wp)            :: alpha, beta
      Integer                          :: i, incw, incx, incy, ix, iy, n
!     .. Local Arrays ..
      Complex (Kind=nag_wp), Allocatable :: w(:), x(:), y(:)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: abs
!     .. Executable Statements ..
      Write (nout,*) 'F16GHF Example Program Results'

!     Skip heading in data file
      Read (nin,*)

      Read (nin,*) n
      Read (nin,*) incx, incy, incw
      Allocate (w(1+(n-1)*abs(incw)),x(1+(n-1)*abs(incx)),y(1+(n-              &
        1)*abs(incy)))

      Read (nin,*) alpha, beta

!     Read the vectors x and y and store forwards or backwards
!     as determined by incx (resp. incy).
      If (incx>0) Then
        ix = 1
      Else
        ix = 1 - (n-1)*incx
      End If

      Do i = 1, n
        Read (nin,*) x(ix)
        ix = ix + incx
      End Do

      If (incy>0) Then
        iy = 1
      Else
        iy = 1 - (n-1)*incy
      End If

      Do i = 1, n
        Read (nin,*) y(iy)
        iy = iy + incy
      End Do

!     Compute w = alpha*x + beta*y

      Call blas_zwaxpby(n,alpha,x,incx,beta,y,incy,w,incw)

!     Display the vector w forwards or backwards
!     as determined by incw.
      Write (nout,*)
      Write (nout,99999)
      If (incw>0) Then
        Write (nout,99998) w(1:1+(n-1)*incw:incw)
      Else
        Write (nout,99998) w(1-(n-1)*incw:1:incw)
      End If

99999 Format (1X,'Result of scaled vector addition is')
99998 Format (1X,'w = ( ',2('(',F9.4,',',F9.4,'), '),'(',F9.4,',',F9.4,') )')
    End Program f16ghfe


f16glfe.f90

    Program f16glfe

!     F16GLF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: blas_zsum, nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Complex (Kind=nag_wp)            :: sumval
      Integer                          :: i, incx, ix, n
!     .. Local Arrays ..
      Complex (Kind=nag_wp), Allocatable :: x(:)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: abs
!     .. Executable Statements ..
      Write (nout,*) 'F16GLF Example Program Results'

!     Skip heading in data file
      Read (nin,*)

      Read (nin,*) n, incx
      Allocate (x(1+(n-1)*abs(incx)))

!     Read the vector x and store forwards or backwards
!     as determined by incx.
      If (incx>0) Then
        ix = 1
      Else
        ix = 1 - (n-1)*incx
      End If

      Do i = 1, n
        Read (nin,*) x(ix)
        ix = ix + incx
      End Do

!     Sum the elements of x

      sumval = blas_zsum(n,x,incx)

      Write (nout,*)
      Write (nout,99999) sumval

99999 Format (1X,'Sum of elements of x is (',F9.5,',',F9.5,')')
    End Program f16glfe


f16jnfe.f90

    Program f16jnfe

!     F16JNF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: blas_dmax_val, nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: r
      Integer                          :: i, incx, ix, k, n
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: x(:)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: abs
!     .. Executable Statements ..
      Write (nout,*) 'F16JNF Example Program Results'

!     Skip heading in data file
      Read (nin,*)

      Read (nin,*) n, incx
      Allocate (x(1+(n-1)*abs(incx)))

!     Read the vector x and store forwards or backwards
!     as determined by incx.
      If (incx>0) Then
        ix = 1
      Else
        ix = 1 - (n-1)*incx
      End If

      Do i = 1, n
        Read (nin,*) x(ix)
        ix = ix + incx
      End Do

!     Find k = argmax(x) and r = max(x).

      Call blas_dmax_val(n,x,incx,k,r)

      Write (nout,*)
      Write (nout,99999) k
      Write (nout,99998) r

99999 Format (1X,'Index of largest component of x is',I3)
99998 Format (1X,'Largest component of x is',F12.5)
    End Program f16jnfe


f16jpfe.f90

    Program f16jpfe

!     F16JPF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: blas_dmin_val, nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: r
      Integer                          :: i, incx, ix, k, n
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: x(:)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: abs
!     .. Executable Statements ..
      Write (nout,*) 'F16JPF Example Program Results'

!     Skip heading in data file
      Read (nin,*)

      Read (nin,*) n, incx
      Allocate (x(1+(n-1)*abs(incx)))

!     Read the vector x and store forwards or backwards
!     as determined by incx.
      If (incx>0) Then
        ix = 1
      Else
        ix = 1 - (n-1)*incx
      End If

      Do i = 1, n
        Read (nin,*) x(ix)
        ix = ix + incx
      End Do

!     Find k = argmin(x) and r = min(x).

      Call blas_dmin_val(n,x,incx,k,r)

      Write (nout,*)
      Write (nout,99999) k
      Write (nout,99998) r

99999 Format (1X,'Index of smallest component of x is',I3)
99998 Format (1X,'Smallest component of x is',F12.5)
    End Program f16jpfe


f16jqfe.f90

    Program f16jqfe

!     F16JQF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: blas_damax_val, nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: r
      Integer                          :: i, incx, ix, k, n
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: x(:)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: abs
!     .. Executable Statements ..
      Write (nout,*) 'F16JQF Example Program Results'

!     Skip heading in data file
      Read (nin,*)

      Read (nin,*) n, incx
      Allocate (x(1+(n-1)*abs(incx)))

!     Read the vector x and store forwards or backwards
!     as determined by incx.
      If (incx>0) Then
        ix = 1
      Else
        ix = 1 - (n-1)*incx
      End If

      Do i = 1, n
        Read (nin,*) x(ix)
        ix = ix + incx
      End Do

!     Find k = argmax(abs(x)) and r = max(abs(x)).

      Call blas_damax_val(n,x,incx,k,r)

      Write (nout,*)
      Write (nout,99999) k
      Write (nout,99998) r

99999 Format (1X,'Index of absolutely largest component of x is',I3)
99998 Format (1X,'Absolutely largest component of x is',F12.5)
    End Program f16jqfe


f16jrfe.f90

    Program f16jrfe

!     F16JRF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: blas_damin_val, nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: r
      Integer                          :: i, incx, ix, k, n
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: x(:)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: abs
!     .. Executable Statements ..
      Write (nout,*) 'F16JRF Example Program Results'

!     Skip heading in data file
      Read (nin,*)

      Read (nin,*) n, incx
      Allocate (x(1+(n-1)*abs(incx)))

!     Read the vector x and store forwards or backwards
!     as determined by incx.
      If (incx>0) Then
        ix = 1
      Else
        ix = 1 - (n-1)*incx
      End If

      Do i = 1, n
        Read (nin,*) x(ix)
        ix = ix + incx
      End Do

!     Find k = argmin(abs(x)) and r = min(abs(x)).

      Call blas_damin_val(n,x,incx,k,r)

      Write (nout,*)
      Write (nout,99999) k
      Write (nout,99998) r

99999 Format (1X,'Index of absolutely smallest component of x is',I3)
99998 Format (1X,'Absolutely smallest component of x is',F12.5)
    End Program f16jrfe


f16jsfe.f90

    Program f16jsfe

!     F16JSF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: blas_zamax_val, nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: r
      Integer                          :: i, incx, ix, k, n
!     .. Local Arrays ..
      Complex (Kind=nag_wp), Allocatable :: x(:)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: abs
!     .. Executable Statements ..
      Write (nout,*) 'F16JSF Example Program Results'

!     Skip heading in data file
      Read (nin,*)

      Read (nin,*) n, incx
      Allocate (x(1+(n-1)*abs(incx)))

!     Read the vector x and store forwards or backwards
!     as determined by incx.
      If (incx>0) Then
        ix = 1
      Else
        ix = 1 - (n-1)*incx
      End If

      Do i = 1, n
        Read (nin,*) x(ix)
        ix = ix + incx
      End Do

!     Find k = argmax(abs(Re(x))+abs(Im(x))) and
!          r = max(abs(Re(x))+abs(Im(x))).

      Call blas_zamax_val(n,x,incx,k,r)

      Write (nout,*)
      Write (nout,99999) k
      Write (nout,99998) r

99999 Format (1X,'Index of absolutely largest component of x is',I3)
99998 Format (1X,'Absolutely largest component of x is',F12.5)
    End Program f16jsfe


f16jtfe.f90

    Program f16jtfe

!     F16JTF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: blas_zamin_val, nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: r
      Integer                          :: i, incx, ix, k, n
!     .. Local Arrays ..
      Complex (Kind=nag_wp), Allocatable :: x(:)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: abs
!     .. Executable Statements ..
      Write (nout,*) 'F16JTF Example Program Results'

!     Skip heading in data file
      Read (nin,*)

      Read (nin,*) n, incx
      Allocate (x(1+(n-1)*abs(incx)))

!     Read the vector x and store forwards or backwards
!     as determined by incx.
      If (incx>0) Then
        ix = 1
      Else
        ix = 1 - (n-1)*incx
      End If

      Do i = 1, n
        Read (nin,*) x(ix)
        ix = ix + incx
      End Do

!     Find k = argmin(abs(Re(x))+abs(Im(x))) and
!          r = min(abs(Re(x))+abs(Im(x))).

      Call blas_zamin_val(n,x,incx,k,r)

      Write (nout,*)
      Write (nout,99999) k
      Write (nout,99998) r

99999 Format (1X,'Index of absolutely smallest component of x is',I3)
99998 Format (1X,'Absolutely smallest component of x is',F12.5)
    End Program f16jtfe


f16rbfe.f90

    Program f16rbfe

!     F16RBF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: f01zcf, f16rbf, nag_frobenius_norm, nag_inf_norm, &
                             nag_max_norm, nag_one_norm, nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: r_fro, r_inf, r_max, r_one
      Integer                          :: i, ifail, j, kl, ku, lda, ldab, m, n
      Character (1)                    :: job
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: a(:,:), ab(:,:)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: max, min
!     .. Executable Statements ..
      Write (nout,*) 'F16RBF Example Program Results'

!     Skip heading in data file
      Read (nin,*)

      Read (nin,*) m, n, kl, ku
      lda = m
      ldab = kl + ku + 1
      Allocate (a(lda,n),ab(ldab,n))

!     Read A from data file into rectangular storage

      Do i = 1, m
        Read (nin,*)(a(i,j),j=max(1,i-kl),min(n,i+ku))
      End Do

!     Convert A to packed storage

      job = 'P'

      ifail = 0
      Call f01zcf(job,m,n,kl,ku,a,lda,ab,ldab,ifail)

      Write (nout,*)
      Write (nout,99999) 'Norms of banded matrix AB:'
      Write (nout,*)

      r_one = f16rbf(nag_one_norm,m,n,kl,ku,ab,ldab)
      Write (nout,99998) 'One norm           = ', r_one

      r_inf = f16rbf(nag_inf_norm,m,n,kl,ku,ab,ldab)
      Write (nout,99998) 'Infinity norm      = ', r_inf

      r_fro = f16rbf(nag_frobenius_norm,m,n,kl,ku,ab,ldab)
      Write (nout,99998) 'Frobenius norm     = ', r_fro

      r_max = f16rbf(nag_max_norm,m,n,kl,ku,ab,ldab)
      Write (nout,99998) 'Maximum norm       = ', r_max

99999 Format (1X,A)
99998 Format (1X,A,F9.4)
    End Program f16rbfe


f16ubfe.f90

    Program f16ubfe

!     F16UBF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: f01zdf, f16ubf, nag_frobenius_norm, nag_inf_norm, &
                             nag_max_norm, nag_one_norm, nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: r_fro, r_inf, r_max, r_one
      Integer                          :: i, ifail, j, kl, ku, lda, ldab, m, n
      Character (1)                    :: job
!     .. Local Arrays ..
      Complex (Kind=nag_wp), Allocatable :: a(:,:), ab(:,:)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: max, min
!     .. Executable Statements ..
      Write (nout,*) 'F16UBF Example Program Results'

!     Skip heading in data file
      Read (nin,*)

      Read (nin,*) m, n, kl, ku
      lda = m
      ldab = kl + ku + 1
      Allocate (a(lda,n),ab(ldab,n))

!     Read A from data file into rectangular storage

      Do i = 1, m
        Read (nin,*)(a(i,j),j=max(1,i-kl),min(n,i+ku))
      End Do

!     Convert A to packed storage

      job = 'P'

      ifail = 0
      Call f01zdf(job,m,n,kl,ku,a,lda,ab,ldab,ifail)

      Write (nout,*)
      Write (nout,99999) 'Norms of banded matrix AB:'
      Write (nout,*)

      r_one = f16ubf(nag_one_norm,m,n,kl,ku,ab,ldab)
      Write (nout,99998) 'One norm           = ', r_one

      r_inf = f16ubf(nag_inf_norm,m,n,kl,ku,ab,ldab)
      Write (nout,99998) 'Infinity norm      = ', r_inf

      r_fro = f16ubf(nag_frobenius_norm,m,n,kl,ku,ab,ldab)
      Write (nout,99998) 'Frobenius norm     = ', r_fro

      r_max = f16ubf(nag_max_norm,m,n,kl,ku,ab,ldab)
      Write (nout,99998) 'Maximum norm       = ', r_max

99999 Format (1X,A)
99998 Format (1X,A,F9.4)
    End Program f16ubfe


g01abfe.f90

    Program g01abfe

!     G01ABF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: g01abf, nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Integer                          :: i, ifail, iwt, n
!     .. Local Arrays ..
      Real (Kind=nag_wp)               :: res(13)
      Real (Kind=nag_wp), Allocatable  :: wt(:), wtin(:), x1(:), x2(:)
!     .. Executable Statements ..
      Write (nout,*) 'G01ABF Example Program Results'
      Write (nout,*)

!     Skip heading in data file
      Read (nin,*)

!     Read in the problem size
      Read (nin,*) n, iwt

      Allocate (wt(n),wtin(n),x1(n),x2(n))

!     Read in data
      Read (nin,*)(x1(i),x2(i),i=1,n)
      If (iwt==1) Then
        Read (nin,*) wtin(1:n)
        wt(1:n) = wtin(1:n)
      End If

!     Display data
      Write (nout,99999) 'Number of cases', n
      Write (nout,*) 'Data as input -'
      Write (nout,*)                                                           &
        '         Var  1     Var  2     Var  1     Var  2     Var  1     Var  2'

      Write (nout,99995)(x1(i),x2(i),i=1,n)
      If (iwt==1) Then
        Write (nout,*) 'Weights as input -'
        Write (nout,99994) wtin(1:n)
      End If
      Write (nout,*)

!     Calculate summary statistics
      ifail = -1
      Call g01abf(n,x1,x2,iwt,wt,res,ifail)
      If (ifail/=0) Then
        If (ifail/=2) Then
          Go To 100
        End If
      End If

!     Display results
      Write (nout,99999) 'No. of valid cases', iwt
      Write (nout,99993) 'Variable 1', 'Variable 2'
      Write (nout,99998) 'Mean    ', res(1), res(2)
      Write (nout,99997) 'Corr SSP', res(5), res(6), res(7)
      Write (nout,99998) 'Minimum ', res(9), res(11)
      Write (nout,99998) 'Maximum ', res(10), res(12)
      Write (nout,99998) 'Sum of weights         ', res(13)
      If (ifail==0) Then
        Write (nout,99998) 'Std devn', res(3), res(4)
        Write (nout,99996) 'Correln ', res(8)
      Else
        Write (nout,*) 'Std devn and Correln not defined'
      End If

100   Continue

99999 Format (1X,A,I5)
99998 Format (1X,A,F15.1,F30.1)
99997 Format (1X,A,3E15.5)
99996 Format (1X,A,F30.4)
99995 Format (5X,6F11.1)
99994 Format (13X,F9.3)
99993 Format (13X,A,20X,A)
    End Program g01abfe


g01adfe.f90

    Program g01adfe

!     G01ADF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: g01adf, nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: s2, s3, s4, xmean
      Integer                          :: i, ifail, k, kmin1, n
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: x(:)
      Integer, Allocatable             :: ifreq(:)
!     .. Executable Statements ..
      Write (nout,*) 'G01ADF Example Program Results'
      Write (nout,*)

!     Skip heading in data file
      Read (nin,*)

!     Read in the problem size
      Read (nin,*) kmin1
      k = kmin1 + 1

      Allocate (ifreq(k),x(k))

!     Read in data
      Read (nin,*)(x(i),ifreq(i),i=1,kmin1), x(k)

!     Calculate summary statistics
      ifail = 0
      Call g01adf(k,x,ifreq,xmean,s2,s3,s4,n,ifail)

!     Display results
      Write (nout,99999) 'Number of classes ', kmin1
      Write (nout,*)
      Write (nout,*) '          Class          Frequency'
      Write (nout,*)
      Write (nout,99998)(x(i),x(i+1),ifreq(i),i=1,kmin1)
      Write (nout,*)
      Write (nout,99997) ' Mean ', xmean
      Write (nout,99996) ' Std devn', s2
      Write (nout,99996) ' Skewness', s3
      Write (nout,99996) ' Kurtosis', s4
      Write (nout,99995) ' Number of cases', n

99999 Format (1X,A,I4)
99998 Format (1X,2F10.2,I12)
99997 Format (1X,A,F16.4)
99996 Format (1X,A,F13.4)
99995 Format (1X,A,I8)
    End Program g01adfe


g01aefe.f90

    Program g01aefe

!     G01AEF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: g01aef, nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: xmax, xmin
      Integer                          :: iclass, ifail, j, k, n
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: cb(:), x(:)
      Integer, Allocatable             :: ifreq(:)
!     .. Executable Statements ..
      Write (nout,*) 'G01AEF Example Program Results'
      Write (nout,*)

!     Skip heading in data file
      Read (nin,*)

!     Read in the problem size
      Read (nin,*) n, iclass, k

      Allocate (x(n),cb(k),ifreq(k))

!     Read in data
      Read (nin,*) x(1:n)

      Write (nout,99997) 'Number of cases', n
      Write (nout,99997) 'Number of classes', k

!     Get the class boundaries
      If (iclass/=1) Then
        Write (nout,*) 'Routine-supplied class boundaries'
      Else
        Read (nin,*) cb(1:(k-1))
        Write (nout,*) 'User-supplied class boundaries'
      End If
      Write (nout,*)

!     Construct the frequency table
      ifail = 0
      Call g01aef(n,k,x,iclass,cb,ifreq,xmin,xmax,ifail)

!     Display results
      Write (nout,*) '*** Frequency  distribution ***'
      Write (nout,*)
      Write (nout,*) '       Class            Frequency'
      Write (nout,*)
      Write (nout,99999) '   Up to    ', cb(1), ifreq(1)
      k = k - 1
      If (k>1) Then
        Write (nout,99998)(cb(j-1),' to ',cb(j),ifreq(j),j=2,k)
      End If
      Write (nout,99996) cb(k), '    and over  ', ifreq(k+1)
      Write (nout,*)
      Write (nout,99995) 'Total frequency = ', n
      Write (nout,99994) 'Minimum = ', xmin
      Write (nout,99994) 'Maximum = ', xmax

99999 Format (1X,A,F8.2,I11)
99998 Format (1X,F8.2,A,F8.2,I11)
99997 Format (1X,A,I4)
99996 Format (1X,F8.2,A,I9)
99995 Format (1X,A,I6)
99994 Format (1X,A,F9.2)
    End Program g01aefe


g01affe.f90

    Program g01affe

!     G01AFF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: g01aff, nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: chis
      Integer                          :: ifail, im, in, j, k, ldnob, ldpred,  &
                                          m, m1, m2, n, n1, n2, ndf, npos, num
!     .. Local Arrays ..
      Real (Kind=nag_wp)               :: p(21)
      Real (Kind=nag_wp), Allocatable  :: pred(:,:)
      Integer, Allocatable             :: nobs(:,:)
!     .. Executable Statements ..
      Write (nout,*) 'G01AFF Example Program Results'
      Write (nout,*)

!     Skip heading in data file
      Read (nin,*)

!     Read in the problem size (where N and M are the number of
!     rows and columns in the two way table NOBS)
      Read (nin,*) im, in, num

!     M and N as supplied to G01AFF must be 1 more than the number
!     of rows and columns of data in NOBS
      m = im + 1
      n = in + 1

      ldnob = m
      ldpred = m
      Allocate (nobs(ldnob,n),pred(ldpred,n))

!     Read in data
      Read (nin,*)(nobs(j,1:in),j=1,im)

      Write (nout,*) 'Data as input -'
      Write (nout,99992) 'Number of rows', im
      Write (nout,99992) 'Number of columns', in
      Write (nout,99992) 'NUM =', num,                                         &
        ' (NUM = 1 means table reduced in size if necessary)'

!     Perform the analysis
      ifail = 0
      Call g01aff(ldnob,ldpred,m,n,nobs,num,pred,chis,p,npos,ndf,m1,n1,ifail)

!     Display results
      If (num==0) Then
        m2 = m - 1
        n2 = n - 1
        If (m1/=m2) Then
          Write (nout,99992) 'No. of rows reduced from ', m2, ' to ', m1
        End If
        If (n1/=n2) Then
          Write (nout,99992) 'No. of cols reduced from ', n2, ' to ', n1
        End If
        Write (nout,*)
        Write (nout,*) 'Table of observed and expected frequencies'
        Write (nout,*)
        Write (nout,*) '              Column'
        Write (nout,99991)(k,k=1,n1)
        Write (nout,*) 'Row'
        Do j = 1, m1
          Write (nout,99999) j, nobs(j,1:n1)
          Write (nout,99998) pred(j,1:n1)
          Write (nout,99994) 'Row total = ', nobs(j,n)
        End Do
        Write (nout,*)
        Write (nout,*) 'Column'
        Write (nout,99993) 'totals', nobs(m,1:n1)
        Write (nout,99994) 'Grand total = ', nobs(m,n)
        Write (nout,*)
        Write (nout,99997) 'Chi-squared = ', chis, '   D.F. = ', ndf
      Else
        Write (nout,*) 'Fisher''s exact test for 2*2 table'
        Write (nout,*)
        Write (nout,*) 'Table of observed frequencies'
        Write (nout,*)
        Write (nout,*) '          Column'
        Write (nout,*) '          1    2'
        Write (nout,*) 'Row'
        Do j = 1, 2
          Write (nout,99999) j, nobs(j,1:2)
          Write (nout,99994) 'Row total = ', nobs(j,n)
        End Do
        Write (nout,*)
        Write (nout,*) 'Column'
        Write (nout,99993) 'totals', nobs(m,1:2)
        Write (nout,99994) 'Grand total = ', nobs(m,n)
        Write (nout,*)
        Write (nout,99996) 'This table corresponds to element ', npos,         &
          ' in vector P below'
        Write (nout,*)
        Write (nout,*) 'Vector P'
        Write (nout,*)
        Write (nout,*) ' I   P(I)'
        Write (nout,99995)(j,p(j),j=1,num)
      End If

99999 Format (1X,I2,4X,10I6)
99998 Format (8X,12F6.0)
99997 Format (1X,A,F10.3,A,I3)
99996 Format (1X,A,I4,A)
99995 Format (1X,I2,F9.4)
99994 Format (49X,A,I7)
99993 Format (1X,A,10I6)
99992 Format (1X,A,I3,A,I3)
99991 Format (7X,10I6)
    End Program g01affe


g01agfe.f90

    Program g01agfe

!     G01AGF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: g01agf, nag_wp, x04abf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: iset = 1, nin = 5, nout = 6
!     .. Local Scalars ..
      Integer                          :: i, ifail, nobs, nstepx, nstepy,      &
                                          outchn
      Character (80)                   :: title
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: x(:), y(:)
      Integer, Allocatable             :: isort(:)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: len_trim
!     .. Executable Statements ..
      Write (nout,*) 'G01AGF Example Program Results'
      Write (nout,*)

!     Skip heading in data file
      Read (nin,*)

!     Read in the problem size
      Read (nin,*) nobs, nstepx, nstepy

      Allocate (x(nobs),y(nobs),isort(nobs))

!     Read in data
      Read (nin,*)(x(i),y(i),i=1,nobs)

!     Read in the title
      Read (nin,99999) title

!     Set advisory channel
      outchn = nout
      Call x04abf(iset,outchn)

!     Display title
      Write (nout,*) title(1:len_trim(title))
      Write (nout,*)
      Flush (nout)

!     Produce the plot
      ifail = 0
      Call g01agf(x,y,nobs,isort,nstepx,nstepy,ifail)

99999 Format (A80)
    End Program g01agfe


g01ahfe.f90

    Program g01ahfe

!     G01AHF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: g01ahf, nag_wp, x04abf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: iset = 1, nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: xbar, xstd
      Integer                          :: ifail, istand, lwork, nobs, nstepx,  &
                                          nstepy, outchn
      Character (80)                   :: title
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: work(:), x(:), xsort(:)
      Integer, Allocatable             :: iwork(:)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: len_trim
!     .. Executable Statements ..
      Write (nout,*) 'G01AHF Example Program Results'
      Write (nout,*)

!     Skip heading in data file
      Read (nin,*)

!     Read in the problem size
      Read (nin,*) nobs, nstepx, nstepy, istand

      lwork = 5*nobs/2
      Allocate (iwork(nobs),xsort(nobs),x(nobs),work(lwork))

!     Read in data
      Read (nin,*) x(1:nobs)

!     Read in the title
      Read (nin,99997) title

!     Set advisory channel
      outchn = nout
      Call x04abf(iset,outchn)

!     Display data to be plotted
      Write (nout,*) 'Data values to be plotted'
      Write (nout,99998) x(1:nobs)
      Write (nout,*)
      Write (nout,*)

!     Display title
      Write (nout,*)
      Write (nout,*) title(1:len_trim(title))
      Write (nout,*)
      Flush (nout)

!     Produce the plot
      ifail = 0
      Call g01ahf(x,nobs,nstepx,nstepy,istand,iwork,work,lwork,xsort,xbar,     &
        xstd,ifail)

!     Display additional results
      Write (nout,*)
      Write (nout,99999) 'Mean of data values = ', xbar
      Write (nout,99999) 'Standard deviation  = ', xstd
      Write (nout,*)
      Write (nout,*) 'Sorted standardised data values'
      Write (nout,99998) xsort(1:nobs)

99999 Format (1X,A,F5.2)
99998 Format (5X,5F7.2)
99997 Format (A80)
    End Program g01ahfe


g01ajfe.f90

    Program g01ajfe

!     G01AJF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: g01ajf, nag_wp, x04abf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: iset = 1, nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: xmax, xmin, xstep
      Integer                          :: ifail, ispace, itype, multy, n, n1,  &
                                          nstepx, nstepy, outchn
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: x(:)
!     .. Executable Statements ..
      Write (nout,*) 'G01AJF Example Program Results'
      Write (nout,*)
      Flush (nout)

!     Skip heading in data file
      Read (nin,*)

!     Read in the problem size
      Read (nin,*) n, nstepx, nstepy

      Allocate (x(n))

!     Read in data
      Read (nin,*) x(1:n)

!     Set advisory channel
      outchn = nout
      Call x04abf(iset,outchn)

!     Display histogram
      itype = 0

!     Indent 10 spaces
      ispace = 10

!     Display all the data
      xmin = 0.0E0_nag_wp
      xmax = 0.0E0_nag_wp

!     Produce the plot
      ifail = 0
      Call g01ajf(x,n,nstepx,nstepy,itype,ispace,xmin,xmax,xstep,n1,multy,     &
        ifail)

      Write (nout,*)
      Write (nout,*)
      Write (nout,*)
      Flush (nout)

!     Display cumulative histogram
      itype = 1

!     Don't indent
      ispace = 0

!     Display only data between -10 and 5
      xmin = -10.0E0_nag_wp
      xmax = 5.0E0_nag_wp

!     Produce the plot
      ifail = 0
      Call g01ajf(x,n,nstepx,nstepy,itype,ispace,xmin,xmax,xstep,n1,multy,     &
        ifail)

    End Program g01ajfe


g01alfe.f90

    Program g01alfe

!     G01ALF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: g01alf, nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Integer                          :: ifail, n
!     .. Local Arrays ..
      Real (Kind=nag_wp)               :: res(5)
      Real (Kind=nag_wp), Allocatable  :: x(:)
      Integer, Allocatable             :: iwrk(:)
!     .. Executable Statements ..
      Write (nout,*) 'G01ALF Example Program Results'
      Write (nout,*)

!     Skip heading in data file
      Read (nin,*)

!     Read in the problem size
      Read (nin,*) n

      Allocate (x(n),iwrk(n))

!     Read in data
      Read (nin,*) x(1:n)

!     Calculate summary statistics
      ifail = 0
      Call g01alf(n,x,iwrk,res,ifail)

!     Display results
      Write (nout,99999) 'Maximum                   ', res(5)
      Write (nout,99999) 'Upper Hinge (75% quantile)', res(4)
      Write (nout,99999) 'Median      (50% quantile)', res(3)
      Write (nout,99999) 'Lower Hinge (25% quantile)', res(2)
      Write (nout,99999) 'Minimum                   ', res(1)

99999 Format (1X,A,F16.4)
    End Program g01alfe


g01amfe.f90

    Program g01amfe

!     G01AMF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: g01amf, nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Integer                          :: i, ifail, n, nq
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: q(:), qv(:), rv(:)
!     .. Executable Statements ..
      Write (nout,*) 'G01AMF Example Program Results'
      Write (nout,*)

!     Skip heading in data file
      Read (nin,*)

!     Read in the problem size
      Read (nin,*) n, nq

      Allocate (q(nq),qv(nq),rv(n))

!     Read in data
      Read (nin,*) rv(1:n)

!     Read in the required quantiles
      Read (nin,*) q(1:nq)

!     Display data
      Write (nout,*) 'Data Values:'
      Write (nout,99998) rv(1:n)
      Write (nout,*)

!     Calculate the quantiles
      ifail = 0
      Call g01amf(n,rv,nq,q,qv,ifail)

!     Display results
      Write (nout,*) 'Quantile     Result'
      Write (nout,*)
      Write (nout,99999)(q(i),qv(i),i=1,nq)

99999 Format (1X,F7.2,4X,F7.2)
99998 Format (1X,20F7.2)
    End Program g01amfe


g01anfe.f90

    Program g01anfe

!     G01ANF Example Program Text
!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: g01anf, nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: eps
      Integer                          :: i, ifail, ind, licomm, lrcomm, n,    &
                                          nb, np, nq, nrv, onb
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: q(:), qv(:), rcomm(:), rv(:)
      Integer, Allocatable             :: icomm(:)
!     .. Executable Statements ..
      Write (nout,*) 'G01ANF Example Program Results'
      Write (nout,*)

!     Skip heading in data file
      Read (nin,*)

!     Read in stream size and approximation factor
      Read (nin,*) n, eps

!     Read in number of elements in the output vector qv
      Read (nin,*) nq
      Allocate (qv(nq),q(nq))

!     Read in vector q
      Read (nin,*) q(1:nq)

!     Dummy allocation for the communication arrays
      lrcomm = 1
      licomm = 2
      nb = 1
      Allocate (rv(nb),rcomm(lrcomm),icomm(licomm))

!     Call NAG routine for the first time to obtain lrcomm and licomm
      ind = 0
      ifail = 0
      Call g01anf(ind,n,rv,nb,eps,np,q,qv,nq,rcomm,lrcomm,icomm,licomm,ifail)

!     Reallocate the communication arrays to the required size
      lrcomm = icomm(1)
      licomm = icomm(2)
      Deallocate (rcomm,icomm)
      Allocate (rcomm(lrcomm),icomm(licomm))

!     Read in number of vectors with dataset blocks
      Read (nin,*) nrv

      onb = 0
d_lp: Do i = 1, nrv
!       Read in number of elements in the first/next vector rv
        Read (nin,*) nb

        If (onb/=nb) Then
!         Reallocate RV if required
          Deallocate (rv)
          Allocate (rv(nb))
        End If
        onb = nb

!       Read in vector rv
        Read (nin,*) rv(1:nb)

!       Repeat calls to NAG routine for every dataset block rv
!       until n observations have been passed
        ifail = 1
        Call g01anf(ind,n,rv,nb,eps,np,q,qv,nq,rcomm,lrcomm,icomm,licomm,      &
          ifail)
        If (ifail/=0) Then
!         This routine is most likely to be used to process large datasets,
!         certain parameter checks will only be done once all the data has
!         been processed. Calling the routine with a hard failure (IFAIL=0)
!         would cause any processing to be lost as the program terminates.
!         It is likely that a soft failure would be more appropriate. This
!         would allow any issues with the input parameters to be resolved
!         without losing any processing already carried out.

!         In this small example we are just calling the routine again with
!         a hard failure so that the error messages are displayed.
          ifail = 0
          Call g01anf(ind,n,rv,nb,eps,np,q,qv,nq,rcomm,lrcomm,icomm,licomm,    &
            ifail)
        End If
        If (ind==4) Then
          Exit d_lp
        End If
      End Do d_lp

!     Call NAG routine again to calculate quantiles specified in vector q
      ind = 3
      ifail = 0
      Call g01anf(ind,n,rv,nb,eps,np,q,qv,nq,rcomm,lrcomm,icomm,licomm,ifail)

!     Print the results
      Write (nout,*) 'Input data:'
      Write (nout,99999) n, ' observations'
      Write (nout,99998) 'eps = ', eps
      Write (nout,*)
      Write (nout,*) 'Quantile     Result'
      Write (nout,99997)(q(i),qv(i),i=1,nq)

99999 Format (1X,I2,A)
99998 Format (1X,A,F5.2)
99997 Format (1X,F7.2,4X,F7.2)
    End Program g01anfe


g01apfe.f90

    Program g01apfe

!     G01APF Example Program Text
!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: g01apf, nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: eps
      Integer                          :: i, ifail, ind, licomm, lrcomm,       &
                                          ltcomm, n, nb, np, nq
      Logical                          :: repeat
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: q(:), qv(:), rcomm(:), rv(:),        &
                                          trcomm(:)
      Integer, Allocatable             :: icomm(:), ticomm(:)
!     .. Executable Statements ..
      Write (nout,*) 'G01APF Example Program Results'
      Write (nout,*)

!     Skip heading in data file
      Read (nin,*)

!     Read in approximation factor
      Read (nin,*) eps

!     Read in number of elements in the output vector qv
      Read (nin,*) nq
      Allocate (qv(nq),q(nq))

!     Read in vector q
      Read (nin,*) q(1:nq)

      lrcomm = 100
      licomm = 400
      nb = 20
      Allocate (rcomm(lrcomm),icomm(licomm),rv(nb))

      ind = 0
      repeat = .True.
      n = 0

m_lp: Do While (repeat)

        If (ind==0 .Or. ind==1) Then
d_lp:     Do i = 1, nb
            Read (nin,*,Iostat=ifail) rv(i)
            If (ifail/=0) Then
              Exit d_lp
            End If
          End Do d_lp

          If (i==1) Then
            Exit m_lp
          Else If (i-1<nb) Then
            nb = i - 1
            repeat = .False.
          End If
          n = n + nb
        End If

!       Call the routine
        ifail = 1
        Call g01apf(ind,rv,nb,eps,np,q,qv,nq,rcomm,lrcomm,icomm,licomm,ifail)
        If (ifail/=0) Then
!         This routine is most likely to be used to process large datasets,
!         certain parameter checks will only be done once all the data has
!         been processed. Calling the routine with a hard failure (IFAIL=0)
!         would cause any processing to be lost as the program terminates.
!         It is likely that a soft failure would be more appropriate. This
!         would allow any issues with the input parameters to be resolved
!         without losing any processing already carried out.

!         In this small example we are just calling the routine again with
!         a hard failure so that the error messages are displayed.
          ifail = 0
          Call g01apf(ind,rv,nb,eps,np,q,qv,nq,rcomm,lrcomm,icomm,licomm,      &
            ifail)
        End If

!       If ind=2, the communication arrays are too small.
!       Allocate more memory, copy the content back to the communication
!       arrays and call the routine again with the same rv
        If (ind==2) Then
          If (lrcomm<icomm(1)) Then
            ltcomm = lrcomm
            lrcomm = icomm(1)
            Allocate (trcomm(ltcomm))
            trcomm(1:ltcomm) = rcomm(1:ltcomm)
            Deallocate (rcomm)
            Allocate (rcomm(lrcomm))
            rcomm(1:ltcomm) = trcomm(1:ltcomm)
            Deallocate (trcomm)
          End If
          If (licomm<icomm(2)) Then
            ltcomm = licomm
            licomm = icomm(2)
            Allocate (ticomm(ltcomm))
            ticomm(1:ltcomm) = icomm(1:ltcomm)
            Deallocate (icomm)
            Allocate (icomm(licomm))
            icomm(1:ltcomm) = ticomm(1:ltcomm)
            Deallocate (ticomm)
          End If
        End If
      End Do m_lp

!     Call NAG again with ind=3 to calculate quantiles specified in vector q
      ind = 3
      ifail = 0
      Call g01apf(ind,rv,nb,eps,np,q,qv,nq,rcomm,lrcomm,icomm,licomm,ifail)

!     Print the results
      Write (nout,*) 'Input data:'
      Write (nout,99999) n, ' observations'
      Write (nout,99998) 'eps = ', eps
      Write (nout,*)
      Write (nout,*) 'Quantile     Result'
      Write (nout,99997)(q(i),qv(i),i=1,nq)

99999 Format (1X,I2,A)
99998 Format (1X,A,F5.2)
99997 Format (1X,F7.2,4X,F7.2)
    End Program g01apfe


g01arfe.f90

    Program g01arfe

!     G01ARF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: g01arf, nag_wp, x04abf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: iset = 1, nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: unit, unit1, unit2
      Integer                          :: i, ifail, ldplot, lines, n, nstepx,  &
                                          nstepy, outchn
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: sorty(:), y(:)
      Integer, Allocatable             :: iwork(:)
      Character (1), Allocatable       :: plot(:,:)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: max
!     .. Executable Statements ..
      Write (nout,*) 'G01ARF Example Program Results'
      Write (nout,*)
      Flush (nout)

!     Skip heading in data file
      Read (nin,*)

!     Read in the problem size
      Read (nin,*) n, unit, nstepx, nstepy

!     Make sure there is more than the minimum number of lines available
!     for the plot
      ldplot = max(100,nstepy)

      Allocate (y(n),iwork(n),sorty(n),plot(ldplot,nstepx))

!     Read in data
      Read (nin,*) y(1:n)

!     Set advisory channel
      outchn = nout
      Call x04abf(iset,outchn)

!     Produce and display the plot
      unit1 = unit
      ifail = 0
      Call g01arf('Fences','Print',n,y,nstepx,nstepy,unit1,plot,ldplot,lines,  &
        sorty,iwork,ifail)

      Write (nout,*)
      Flush (nout)

!     Produce the plot, without printing it
      unit2 = unit
      ifail = 0
      Call g01arf('Extremes','Noprint',n,y,nstepx,nstepy,unit2,plot,ldplot,    &
        lines,sorty,iwork,ifail)

!     Display the plot
      Do i = 1, lines
        Write (nout,99999) plot(i,1:nstepx)
      End Do

99999 Format (1X,132A)
    End Program g01arfe


g01asfe.f90

    Program g01asfe

!     G01ASF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: g01asf, nag_wp, x04abf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: iset = 1, nin = 5, nout = 6
!     .. Local Scalars ..
      Integer                          :: ifail, j, ldplot, ldx, m, nstepx,    &
                                          nstepy, outchn
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: work(:), x(:,:)
      Integer, Allocatable             :: iwork(:), n(:)
      Character (1), Allocatable       :: plot(:,:)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: maxval
!     .. Executable Statements ..
      Write (nout,*) 'G01ASF Example Program Results'
      Write (nout,*)
      Flush (nout)

!     Skip heading in data file
      Read (nin,*)

!     Read in the problem size
      Read (nin,*) m, nstepx, nstepy

      ldplot = nstepy
      Allocate (n(m))

!     Read in number of observations in each batch
      Read (nin,*) n(1:m)

      ldx = maxval(n(1:m))
      Allocate (iwork(ldx),x(ldx,m),work(5*m),plot(ldplot,nstepx))

!     Read in data
      Read (nin,*)(x(1:n(j),j),j=1,m)

!     Set advisory channel
      outchn = nout
      Call x04abf(iset,outchn)

!     Produce the plot
      ifail = 0
      Call g01asf('Print',m,n,x,ldx,nstepx,nstepy,plot,ldplot,work,iwork,      &
        ifail)

    End Program g01asfe


g01atfe.f90

    Program g01atfe
!     G01ATF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: g01atf, nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: xkurt, xmax, xmean, xmin, xsd, xskew
      Integer                          :: b, i, ierr, ifail, iwt, nb, pn
!     .. Local Arrays ..
      Real (Kind=nag_wp)               :: rcomm(20)
      Real (Kind=nag_wp), Allocatable  :: wt(:), x(:)
!     .. Executable Statements ..
      Write (nout,*) 'G01ATF Example Program Results'
      Write (nout,*)

!     Skip heading in data file
      Read (nin,*)

!     Initialize the number of valid observations processed so far
      pn = 0

!     Loop over each block of data
      b = 0
      Do
!       Read in the number of observations in this block and the weight flag
        Read (nin,*,Iostat=ierr) nb, iwt
        If (ierr/=0) Then
          Exit
        End If

!       Keep a running total of the number of blocks of data
        b = b + 1

!       Allocate X to the required size
        Allocate (x(nb))

!       Read in the data for this block
        If (iwt==0) Then
          Allocate (wt(0))
          Read (nin,*) x(1:nb)
        Else
          Allocate (wt(nb))
          Read (nin,*)(x(i),wt(i),i=1,nb)
        End If

!       IFAIL = 53, 71 or 72 are warnings and return valid information in some
!       fields, so we don't want to terminate on any nonzero IFAIL. Therefore
!       we set the flag for a quiet exit
        ifail = 1

!       Update the summaries for this block of data
        Call g01atf(nb,x,iwt,wt,pn,xmean,xsd,xskew,xkurt,xmin,xmax,rcomm,      &
          ifail)
        If (ifail/=0 .And. ifail/=71 .And. ifail/=72 .And. ifail/=53) Then
          Write (nout,*) 'G01ATF failed with IFAIL = ', ifail
          Exit
        End If

        Deallocate (x,wt)
      End Do

      If (ifail==0 .Or. ifail==71 .Or. ifail==72 .Or. ifail==53) Then
!       Display the results
        Write (nout,99999) 'Data supplied in ', b, ' blocks'
        If (ifail==53) Then
          Write (nout,*)                                                       &
            'No valid observations supplied. All weights are zero.'
        Else
          Write (nout,99997) pn, 'valid observations'
          Write (nout,99998) 'Mean          ', xmean
          If (ifail==72) Then
            Write (nout,*)                                                     &
              '  Unable to calculate the standard deviation, skewness or ',    &
              'kurtosis'
          Else
            Write (nout,99998) 'Std devn      ', xsd
            If (ifail==71) Then
              Write (nout,*) '  Unable to calculate the skewness or kurtosis'
            Else
              Write (nout,99998) 'Skewness      ', xskew
              Write (nout,99998) 'Kurtosis      ', xkurt
            End If
          End If
          Write (nout,99998) 'Minimum       ', xmin
          Write (nout,99998) 'Maximum       ', xmax
        End If
      End If

99999 Format (1X,A,I0,A)
99998 Format (1X,A,F13.2)
99997 Format (1X,I0,1X,A)
    End Program g01atfe


g01aufe.f90

    Program g01aufe
!     G01AUF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: g01atf, g01auf, nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: xkurt, xmax, xmean, xmin, xsd, xskew
      Integer                          :: b, i, ifail, iwt, j, nb, pn
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: mrcomm(:,:), wt(:), x(:)
      Real (Kind=nag_wp)               :: rcomm(20)
!     .. Executable Statements ..
      Write (nout,*) 'G01AUF Example Program Results'
      Write (nout,*)

!     Skip heading in data file
      Read (nin,*)

!     Read in the number of block of data we have
      Read (nin,*) b

      Allocate (mrcomm(20,b))

!     Loop over each block of data
      Do i = 1, b
!       Read in the number of observations in this block and the weight flag
        Read (nin,*) nb, iwt

!       Allocate X to the required size
        Allocate (x(nb))

!       Read in the data for this block
        If (iwt==0) Then
          Allocate (wt(0))
          Read (nin,*) x(1:nb)
        Else
          Allocate (wt(nb))
          Read (nin,*)(x(j),wt(j),j=1,nb)
        End If

!       IFAIL = 53, 71 or 72 are warnings and so we don't want to terminate
!       on any nonzero IFAIL. Therefore we set the flag for a quiet exit
        ifail = 1

!       Summarise this block of data
        pn = 0
        Call g01atf(nb,x,iwt,wt,pn,xmean,xsd,xskew,xkurt,xmin,xmax,            &
          mrcomm(1:20,i),ifail)
        If (ifail/=0 .And. ifail/=71 .And. ifail/=72 .And. ifail/=53) Then
          Write (nout,*) 'G01ATF failed with IFAIL = ', ifail
          Exit
        End If

!       Display the results for this block
        Write (nout,99999) 'Summary for block ', i
        If (ifail==53) Then
          Write (nout,*)                                                       &
            'No valid observations supplied. All weights are zero.'
        Else
          Write (nout,99997) pn, 'valid observations'
          Write (nout,99998) '  Mean           ', xmean
          If (ifail==72) Then
            Write (nout,*)                                                     &
              '  Unable to calculate the standard deviation, skewness or ',    &
              'kurtosis'
          Else
            Write (nout,99998) '  Std devn       ', xsd
            If (ifail==71) Then
              Write (nout,*) '  Unable to calculate the skewness or kurtosis'
            Else
              Write (nout,99998) '  Skewness       ', xskew
              Write (nout,99998) '  Kurtosis       ', xkurt
            End If
          End If
          Write (nout,99998) '  Minimum        ', xmin
          Write (nout,99998) '  Maximum        ', xmax
        End If
        Write (nout,*)

        Deallocate (x,wt)
      End Do

      If (ifail==0 .Or. ifail==71 .Or. ifail==72 .Or. ifail==53) Then
!       Combine the summaries across all the blocks
        Call g01auf(b,mrcomm,pn,xmean,xsd,xskew,xkurt,xmin,xmax,rcomm,ifail)

!       Display the combined results
        Write (nout,99999) 'Summary for the combined data'
        If (ifail==53) Then
          Write (nout,*)                                                       &
            'No valid observations supplied. All weights are zero.'
        Else
          Write (nout,99997) pn, 'valid observations'
          Write (nout,99998) '  Mean           ', xmean
          If (ifail==72) Then
            Write (nout,*)                                                     &
              '  Unable to calculate the standard deviation, skewness and ',   &
              'kurtosis'
          Else
            Write (nout,99998) '  Std devn       ', xsd
            If (ifail==71) Then
              Write (nout,*) '  Unable to calculate the skewness and kurtosis'
            Else
              Write (nout,99998) '  Skewness       ', xskew
              Write (nout,99998) '  Kurtosis       ', xkurt
            End If
          End If
          Write (nout,99998) '  Minimum        ', xmin
          Write (nout,99998) '  Maximum        ', xmax
        End If
      End If

99999 Format (1X,A,I0,A)
99998 Format (1X,A,F13.2)
99997 Format (1X,I0,1X,A)
    End Program g01aufe


g01bjfe.f90

    Program g01bjfe

!     G01BJF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: g01bjf, nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: p, peqk, pgtk, plek
      Integer                          :: ifail, k, n
!     .. Executable Statements ..
      Write (nout,*) 'G01BJF Example Program Results'
      Write (nout,*)

!     Skip heading in data file
      Read (nin,*)

!     Display titles
      Write (nout,*) '   N     P      K     PLEK      PGTK      PEQK'
      Write (nout,*)

!     Loop over all data
d_lp: Do
        Read (nin,*,Iostat=ifail) n, p, k
        If (ifail/=0) Then
!         All data processed
          Exit d_lp
        End If

!       Calculate probability
        ifail = 0
        Call g01bjf(n,p,k,plek,pgtk,peqk,ifail)

!       Display results
        Write (nout,99999) n, p, k, plek, pgtk, peqk
      End Do d_lp

99999 Format (1X,I4,F8.3,I5,3F10.5)
    End Program g01bjfe


g01bkfe.f90

    Program g01bkfe

!     G01BKF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: g01bkf, nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: peqk, pgtk, plek, rlamda
      Integer                          :: ifail, k
!     .. Executable Statements ..
      Write (nout,*) 'G01BKF Example Program Results'
      Write (nout,*)

!     Skip heading in data file
      Read (nin,*)

!     Display titles
      Write (nout,*) '    RLAMDA     K     PLEK      PGTK      PEQK'
      Write (nout,*)

!     Loop over all data
d_lp: Do
        Read (nin,*,Iostat=ifail) rlamda, k
        If (ifail/=0) Then
!         All data processed
          Exit d_lp
        End If

!       Calculate probability
        ifail = 0
        Call g01bkf(rlamda,k,plek,pgtk,peqk,ifail)

!       Display results
        Write (nout,99999) rlamda, k, plek, pgtk, peqk
      End Do d_lp

99999 Format (1X,F10.3,I6,3F10.5)
    End Program g01bkfe


g01blfe.f90

    Program g01blfe

!     G01BLF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: g01blf, nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: peqk, pgtk, plek
      Integer                          :: ifail, k, l, m, n
!     .. Executable Statements ..
      Write (nout,*) 'G01BLF Example Program Results'
      Write (nout,*)

!     Skip heading in data file
      Read (nin,*)

!     Display titles
      Write (nout,*) '   N   L   M   K     PLEK      PGTK      PEQK'
      Write (nout,*)

!     Loop over all dta
d_lp: Do
        Read (nin,*,Iostat=ifail) n, l, m, k
        If (ifail/=0) Then
!         All data processed
          Exit d_lp
        End If

!       Calculate probability
        ifail = 0
        Call g01blf(n,l,m,k,plek,pgtk,peqk,ifail)

!       Display results
        Write (nout,99999) n, l, m, k, plek, pgtk, peqk
      End Do d_lp

99999 Format (1X,4I4,3F10.5)
    End Program g01blfe


g01dafe.f90

    Program g01dafe

!     G01DAF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: g01daf, nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: errest, etol
      Integer                          :: ifail, iw, n
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: pp(:), work(:)
!     .. Executable Statements ..
      Write (nout,*) 'G01DAF Example Program Results'
      Write (nout,*)

!     Set the problem size
      n = 15
      etol = 0.001E0_nag_wp

      iw = 3*n/2
      Allocate (pp(n),work(iw))

!     Compute the normal scores
      ifail = 0
      Call g01daf(n,pp,etol,errest,work,iw,ifail)

!     Display results
      Write (nout,99999) 'Set size = ', n
      Write (nout,99998) 'Error tolerance (input) = ', etol
      Write (nout,99998) 'Error estimate (output) = ', errest
      Write (nout,*) 'Normal scores'
      Write (nout,99997) pp(1:n)

99999 Format (1X,A,I2)
99998 Format (1X,A,E13.3)
99997 Format (10X,5F10.3)
    End Program g01dafe


g01dbfe.f90

    Program g01dbfe

!     G01DBF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: g01dbf, nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nout = 6
!     .. Local Scalars ..
      Integer                          :: ifail, n
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: pp(:)
!     .. Executable Statements ..
      Write (nout,*) 'G01DBF Example Program Results'
      Write (nout,*)

!     Set the problem size
      n = 10

      Allocate (pp(n))

!     Calculate the normal scores
      ifail = 0
      Call g01dbf(n,pp,ifail)

!     Display results
      Write (nout,99999) 'Sample size = ', n
      Write (nout,*) 'Normal scores'
      Write (nout,99998) pp(1:n)

99999 Format (1X,A,I2)
99998 Format (10X,5F12.4)
    End Program g01dbfe


g01dcfe.f90

    Program g01dcfe

!     G01DCF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: g01daf, g01dcf, nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: errest, etol, exp1, exp2, sumssq
      Integer                          :: i, ifail, iw, j, k, lvec, n
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: pp(:), vec(:), work(:)
!     .. Executable Statements ..
      Write (nout,*) 'G01DCF Example Program Results'
      Write (nout,*)

!     Set the problem size
      n = 6
      etol = 0.0001E0_nag_wp

      lvec = n*(n+1)/2
      iw = 3*n/2
      Allocate (pp(n),work(iw),vec(lvec))

!     Compute normal scores
      ifail = 0
      Call g01daf(n,pp,etol,errest,work,iw,ifail)

      exp1 = pp(n)
      exp2 = pp(n-1)
      sumssq = 0.0E0_nag_wp
      Do i = 1, n
        sumssq = sumssq + pp(i)*pp(i)
      End Do

!     Compute approximate variance-covariance matrix
      ifail = 0
      Call g01dcf(n,exp1,exp2,sumssq,vec,ifail)

!     Display results
      Write (nout,99999) 'Sample size = ', n
      Write (nout,*) 'Variance-covariance matrix'
      k = 1
      Do j = 1, n
        Write (nout,99998) vec(k:(k+j-1))
        k = k + j
      End Do

99999 Format (1X,A,I2)
99998 Format (1X,6F8.4)
    End Program g01dcfe


g01ddfe.f90

    Program g01ddfe

!     G01DDF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: g01ddf, m01caf, nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: pw, w
      Integer                          :: ifail, j, n, pn
      Logical                          :: calwts
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: a(:), x(:)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: allocated
!     .. Executable Statements ..
      Write (nout,*) 'G01DDF Example Program Results'
      Write (nout,*)

!     Skip heading in data file
      Read (nin,*)

      pn = 0
      j = 0
d_lp: Do
!       Read in the problem size
        Read (nin,*,Iostat=ifail) n
        If (ifail/=0) Then
          Exit d_lp
        End If

        If (pn/=n) Then
          If (allocated(x)) Then
            Deallocate (x)
            Deallocate (a)
          End If
          Allocate (a(n),x(n))

!         Need to re-calculate the weights
          calwts = .True.
        Else
!         Use the previously calculated weights
          calwts = .False.
        End If
        pn = n

!       Read in data
        Read (nin,*) x(1:n)

!       Sort the data
        ifail = 0
        Call m01caf(x,1,n,'A',ifail)

!       Calculate the test statistic
        ifail = 0
        Call g01ddf(x,n,calwts,a,w,pw,ifail)

        j = j + 1

!       Display results
        Write (nout,99999) 'For sample number ', j,                            &
          ', value of W statistic = ', w
        Write (nout,99998) '                     Significance level is ', pw
        Write (nout,*)
      End Do d_lp

99999 Format (1X,A,I1,A,F7.4)
99998 Format (1X,A,F8.4)
    End Program g01ddfe


g01dhfe.f90

    Program g01dhfe

!     G01DHF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: g01dhf, nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Integer                          :: ifail, n
      Character (20)                   :: scores, ties
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: r(:), x(:)
      Integer, Allocatable             :: iwrk(:)
!     .. Executable Statements ..
      Write (nout,*) 'G01DHF Example Program Results'
      Write (nout,*)

!     Skip heading in data file
      Read (nin,*)

!     Read in the problem size
      Read (nin,*) scores, ties, n

      Allocate (r(n),x(n),iwrk(n))

!     Read in data
      Read (nin,*) x(1:n)

!     Compute ranks
      ifail = 0
      Call g01dhf(scores,ties,n,x,r,iwrk,ifail)

!     Display results
      Write (nout,*) 'Scores: ', scores
      Write (nout,*) 'Ties  : ', ties
      Write (nout,*)
      Write (nout,99999) r(1:n)

99999 Format (1X,F10.4)
    End Program g01dhfe


g01eafe.f90

    Program g01eafe

!     G01EAF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: g01eaf, nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: prob, x
      Integer                          :: ifail
      Character (1)                    :: tail
!     .. Executable Statements ..
      Write (nout,*) 'G01EAF Example Program Results'
      Write (nout,*)

!     Skip heading in data file
      Read (nin,*)

!     Display title
      Write (nout,*) ' TAIL    X      Probability'
      Write (nout,*)

d_lp: Do
        Read (nin,*,Iostat=ifail) tail, x
        If (ifail/=0) Then
          Exit d_lp
        End If

!       Calculate probability
        ifail = 0
        prob = g01eaf(tail,x,ifail)

!       Display results
        Write (nout,99999) tail, x, prob
      End Do d_lp

99999 Format (3X,A1,4X,F5.2,6X,F7.4)
    End Program g01eafe


g01ebfe.f90

    Program g01ebfe

!     G01EBF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: g01ebf, nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: df, prob, t
      Integer                          :: ifail
      Character (1)                    :: tail
!     .. Executable Statements ..
      Write (nout,*) 'G01EBF Example Program Results'
      Write (nout,*)

!     Skip heading in data file
      Read (nin,*)

!     Display titles
      Write (nout,*) ' TAIL     T       DF      Probability'
      Write (nout,*)

d_lp: Do
        Read (nin,*,Iostat=ifail) tail, t, df
        If (ifail/=0) Then
          Exit d_lp
        End If

!       Calculate probability
        ifail = 0
        prob = g01ebf(tail,t,df,ifail)

!       Display results
        Write (nout,99999) tail, t, df, prob
      End Do d_lp

99999 Format (3X,A1,4X,F6.3,F8.1,7X,F7.4)
    End Program g01ebfe


g01ecfe.f90

    Program g01ecfe

!     G01ECF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: g01ecf, nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: df, prob, x
      Integer                          :: ifail
      Character (1)                    :: tail
!     .. Executable Statements ..
      Write (nout,*) 'G01ECF Example Program Results'
      Write (nout,*)

!     Skip heading in data file
      Read (nin,*)

!     Display titles
      Write (nout,*) ' TAIL     X       DF      Probability'
      Write (nout,*)

d_lp: Do
        Read (nin,*,Iostat=ifail) tail, x, df
        If (ifail/=0) Then
          Exit d_lp
        End If

!       Calculate probability
        ifail = -1
        prob = g01ecf(tail,x,df,ifail)
        If (ifail/=0) Then
          If (ifail/=4) Then
            Exit d_lp
          End If
        End If

!       Display results
        Write (nout,99999) tail, x, df, prob
      End Do d_lp

99999 Format (3X,A1,4X,F6.3,F8.1,7X,F7.4)
    End Program g01ecfe


g01edfe.f90

    Program g01edfe

!     G01EDF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: g01edf, nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: df1, df2, f, prob
      Integer                          :: ifail
      Character (1)                    :: tail
!     .. Executable Statements ..
      Write (nout,*) 'G01EDF Example Program Results'
      Write (nout,*)

!     Skip heading in data file
      Read (nin,*)

!     Display titles
      Write (nout,*) ' TAIL      F      DF1     DF2     Probability'
      Write (nout,*)

d_lp: Do
        Read (nin,*,Iostat=ifail) tail, f, df1, df2
        If (ifail/=0) Then
          Exit d_lp
        End If

!       Calculate probability
        ifail = -1
        prob = g01edf(tail,f,df1,df2,ifail)
        If (ifail/=0) Then
          If (ifail/=4) Then
            Exit d_lp
          End If
        End If

!       Display results
        Write (nout,99999) tail, f, df1, df2, prob
      End Do d_lp

99999 Format (3X,A1,4X,F6.3,2F8.2,7X,F7.4)
    End Program g01edfe


g01eefe.f90

    Program g01eefe

!     G01EEF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: g01eef, nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: a, b, p, pdf, q, tol, x
      Integer                          :: ifail
!     .. Executable Statements ..
      Write (nout,*) 'G01EEF Example Program Results'
      Write (nout,*)

!     Skip heading in data file
      Read (nin,*)

!     Display titles
      Write (nout,*) '    X        A        B        P        Q       PDF'
      Write (nout,*)

d_lp: Do
        Read (nin,*,Iostat=ifail) x, a, b
        If (ifail/=0) Then
          Exit d_lp
        End If

!       Calculate probability
!       NB: parameter tol is no longer referenced
        ifail = -1
        Call g01eef(x,a,b,tol,p,q,pdf,ifail)
        If (ifail/=0) Then
          If (ifail/=3 .And. ifail/=4) Then
            Exit d_lp
          End If
        End If

!       Display results
        Write (nout,99999) x, a, b, p, q, pdf
      End Do d_lp

99999 Format (1X,6(F7.4,2X),A,I1)
    End Program g01eefe


g01effe.f90

    Program g01effe

!     G01EFF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: g01eff, nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: a, b, g, p
      Integer                          :: ifail
      Character (1)                    :: tail
!     .. Executable Statements ..
      Write (nout,*) 'G01EFF Example Program Results'
      Write (nout,*)

!     Skip heading in data file
      Read (nin,*)

!     Display titles
      Write (nout,*) ' TAIL        G            A        B      Probability'
      Write (nout,*)

d_lp: Do
        Read (nin,*,Iostat=ifail) tail, g, a, b
        If (ifail/=0) Then
          Exit d_lp
        End If

!       Calculate probability
        ifail = 0
        p = g01eff(tail,g,a,b,ifail)

!       Display results
        Write (nout,99999) tail, g, a, b, p
      End Do d_lp

99999 Format (3X,A1,4X,F9.2,F13.2,F9.2,7X,F7.4)
    End Program g01effe


g01emfe.f90

    Program g01emfe

!     G01EMF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: g01emf, nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: q, v, valp
      Integer                          :: ifail, ir
!     .. Executable Statements ..
      Write (nout,*) 'G01EMF Example Program Results '
      Write (nout,*)

!     Skip heading in data file
      Read (nin,*)

!     Display titles
      Write (nout,*) '  Q       V    IR    Prob     '
      Write (nout,*)

d_lp: Do
        Read (nin,*,Iostat=ifail) q, v, ir
        If (ifail/=0) Then
          Exit d_lp
        End If

!       Calculate probability
        ifail = 0
        valp = g01emf(q,v,ir,ifail)

!       Display data
        Write (nout,99999) q, v, ir, valp
      End Do d_lp

99999 Format (1X,F7.4,2X,F4.1,1X,I3,1X,F10.4)
    End Program g01emfe


g01epfe.f90

    Program g01epfe

!     G01EPF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: g01epf, nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: d, pdl, pdu
      Integer                          :: ifail, ip, n
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: work(:)
!     .. Executable Statements ..
      Write (nout,*) 'G01EPF Example Program Results '
      Write (nout,*)

!     Skip heading in data file
      Read (nin,*)

!     Read in the problem size
      Read (nin,*) n, ip, d

      Allocate (work(n))

!     Calculate the probability
      ifail = 0
      Call g01epf(n,ip,d,pdl,pdu,work,ifail)

!     Display results
      Write (nout,99999) ' Durbin-Watson statistic ', d
      Write (nout,*)
      Write (nout,99998) ' Probability for the lower bound = ', pdl
      Write (nout,99998) ' Probability for the upper bound = ', pdu

99999 Format (1X,A,F10.4)
99998 Format (1X,A,F10.4)
    End Program g01epfe


g01erfe.f90

    Program g01erfe

!     G01ERF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: g01erf, nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: p, t, vk
      Integer                          :: ifail
!     .. Executable Statements ..
      Write (nout,*) 'G01ERF Example Program Results'
      Write (nout,*)

!     Skip heading in data file
      Read (nin,*)

!     Display titles
      Write (nout,*) '      T          VK     Probability'
      Write (nout,*)

d_lp: Do
        Read (nin,*,Iostat=ifail) t, vk
        If (ifail/=0) Then
          Exit d_lp
        End If

!       Calculate probability
        ifail = 0
        p = g01erf(t,vk,ifail)

!       Display the results
        Write (nout,99999) t, vk, p
      End Do d_lp

99999 Format (F10.4,2X,F10.4,2X,F10.4)
    End Program g01erfe


g01etfe.f90

    Program g01etfe

!     G01ETF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: a00acf, g01etf, nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: x, y
      Integer                          :: ifail
!     .. Executable Statements ..
      Write (nout,*) 'G01ETF Example Program Results'
      Write (nout,*)

!     Check for valid licence prior to calling G01ETF
      If (.Not. a00acf()) Then
        Write (nout,*) ' ** A valid licence key was not found'

      Else
!       Skip heading in data file
        Read (nin,*)

!       Display titles
        Write (nout,*) '  X          Y'
        Write (nout,*)

d_lp:   Do
          Read (nin,*,Iostat=ifail) x
          If (ifail/=0) Then
            Exit d_lp
          End If

!         Compute the value of the Landau distribution function
          y = g01etf(x)

!         Display the results
          Write (nout,99999) x, y
        End Do d_lp
      End If

99999 Format (1X,F4.1,3X,1P,E12.4)
    End Program g01etfe


g01eufe.f90

    Program g01eufe

!     G01EUF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: g01euf, g01zuf, nag_wp, x02alf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: mode = 1, nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: beta2, c1, c2, rkappa, x, xl, xu, y
      Integer                          :: ifail
!     .. Local Arrays ..
      Real (Kind=nag_wp)               :: rcomm(322)
!     .. Executable Statements ..
      Write (nout,*) 'G01EUF Example Program Results'
      Write (nout,*)

!     Skip heading in data file
      Read (nin,*)

!     Display titles
      Write (nout,99998) 'X', 'RKAPPA', 'BETA2', 'Y', 'IFAIL'
      Write (nout,*)

      c1 = -x02alf()
      c2 = -x02alf()
d_lp: Do
        Read (nin,*,Iostat=ifail) x, rkappa, beta2
        If (ifail/=0) Then
          Exit d_lp
        End If

        If ((rkappa/=c1) .Or. (beta2/=c2)) Then
!         If RKAPPA or BETA2 have changed, initialize array RCOMM
          ifail = 0
          Call g01zuf(rkappa,beta2,mode,xl,xu,rcomm,ifail)
        End If

!       Compute the value of the Vavilov distribution function
        ifail = 0
        y = g01euf(x,rcomm,ifail)

!       Display results
        Write (nout,99999) x, rkappa, beta2, y, ifail
        c1 = rkappa
        c2 = beta2
      End Do d_lp

99999 Format (1X,F4.1,5X,F4.1,5X,F4.1,3X,1P,E12.4,I6)
99998 Format (1X,A2,5X,A6,4X,A5,8X,A1,8X,A5)
    End Program g01eufe


g01eyfe.f90

    Program g01eyfe

!     G01EYF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: g01eyf, nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: d, prob
      Integer                          :: ifail, n
!     .. Executable Statements ..
      Write (nout,*) 'G01EYF Example Program Results'
      Write (nout,*)

!     Skip heading in data file
      Read (nin,*)

!     Display titles
      Write (nout,*) '    D       N    One-sided probability'
      Write (nout,*)

d_lp: Do
        Read (nin,*,Iostat=ifail) n, d
        If (ifail/=0) Then
          Exit d_lp
        End If

!       Calculate probability
        ifail = 0
        prob = g01eyf(n,d,ifail)

!       Display results
        Write (nout,99999) d, n, prob
      End Do d_lp

99999 Format (1X,F7.4,2X,I4,10X,F7.4)
    End Program g01eyfe


g01ezfe.f90

    Program g01ezfe

!     G01EZF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: g01ezf, nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: d, prob
      Integer                          :: ifail, n1, n2
!     .. Executable Statements ..
      Write (nout,*) 'G01EZF Example Program Results'
      Write (nout,*)

!     Skip heading in data file
      Read (nin,*)

!     Display titles
      Write (nout,*) '    D      N1    N2    Two-sided probability'
      Write (nout,*)

d_lp: Do
        Read (nin,*,Iostat=ifail) n1, n2, d
        If (ifail/=0) Then
          Exit d_lp
        End If

!       Calculate probability
        ifail = -1
        prob = g01ezf(n1,n2,d,ifail)
        If (ifail/=0) Then
          If (ifail/=3) Then
            Exit d_lp
          End If
        End If

!       Display results
        Write (nout,99999) d, n1, n2, prob
      End Do d_lp

99999 Format (1X,F7.4,2X,I4,2X,I4,10X,F7.4)
    End Program g01ezfe


g01fafe.f90

    Program g01fafe

!     G01FAF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: g01faf, nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: dev, p
      Integer                          :: ifail
      Character (1)                    :: tail
!     .. Executable Statements ..
      Write (nout,*) 'G01FAF Example Program Results'
      Write (nout,*)

!     Skip heading in data file
      Read (nin,*)

!     Display titles
      Write (nout,*) ' Tail    Probability     Deviate '
      Write (nout,*)

d_lp: Do
        Read (nin,*,Iostat=ifail) tail, p
        If (ifail/=0) Then
          Exit d_lp
        End If

!       Calculate the deviate (inverse CDF)
        ifail = 0
        dev = g01faf(tail,p,ifail)

!       Display results
        Write (nout,99999) tail, p, dev
      End Do d_lp

99999 Format (3X,A1,8X,F6.3,8X,F7.4)
    End Program g01fafe


g01fbfe.f90

    Program g01fbfe

!     G01FBF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: g01fbf, nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: df, p, x
      Integer                          :: ifail
      Character (1)                    :: tail
!     .. Executable Statements ..
      Write (nout,*) 'G01FBF Example Program Results'
      Write (nout,*)

!     Skip heading in data file
      Read (nin,*)

!     Display titles
      Write (nout,*) '     P      DF    TAIL      X'
      Write (nout,*)

d_lp: Do
        Read (nin,*,Iostat=ifail) p, df, tail
        If (ifail/=0) Then
          Exit d_lp
        End If

!       Calculate deviates (inverse CDF)
        ifail = -1
        x = g01fbf(tail,p,df,ifail)
        If (ifail/=0) Then
          If (ifail/=4 .And. ifail/=5) Then
            Exit d_lp
          End If
        End If

!       Display results
        Write (nout,99999) p, df, tail, x
      End Do d_lp

99999 Format (1X,2F8.3,3X,A1,3X,F8.3,A,I1)
    End Program g01fbfe


g01fcfe.f90

    Program g01fcfe

!     G01FCF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: g01fcf, nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: df, p, x
      Integer                          :: ifail
!     .. Executable Statements ..
      Write (nout,*) 'G01FCF Example Program Results'
      Write (nout,*)

!     Skip heading in data file
      Read (nin,*)

!     Display titles
      Write (nout,*) '     P       DF      X'
      Write (nout,*)

d_lp: Do
        Read (nin,*,Iostat=ifail) p, df
        If (ifail/=0) Then
          Exit d_lp
        End If

!       Calculate deviates (inverse CDF)
        ifail = -1
        x = g01fcf(p,df,ifail)
        If (ifail/=0) Then
          If (ifail/=4 .And. ifail/=5) Then
            Exit d_lp
          End If
        End If

!       Display results
        Write (nout,99999) p, df, x
      End Do d_lp

99999 Format (1X,3F8.3,A,I1)
    End Program g01fcfe


g01fdfe.f90

    Program g01fdfe

!     G01FDF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: g01fdf, nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: df1, df2, f, p
      Integer                          :: ifail
!     .. Executable Statements ..
      Write (nout,*) 'G01FDF Example Program Results'
      Write (nout,*)

!     Skip heading in data file
      Read (nin,*)

!     Display titles
      Write (nout,*) '     P      DF1     DF2      F'
      Write (nout,*)

d_lp: Do
        Read (nin,*,Iostat=ifail) p, df1, df2
        If (ifail/=0) Then
          Exit d_lp
        End If

!       Calculate deviates (inverse CDF)
        ifail = -1
        f = g01fdf(p,df1,df2,ifail)
        If (ifail/=0) Then
          If (ifail/=3 .And. ifail/=4) Then
            Exit d_lp
          End If
        End If

!       Display results
        Write (nout,99999) p, df1, df2, f
      End Do d_lp

99999 Format (1X,4F8.3,A,I1)
    End Program g01fdfe


g01fefe.f90

    Program g01fefe

!     G01FEF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: g01fef, nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: a, b, p, tol, x
      Integer                          :: ifail
!     .. Executable Statements ..
      Write (nout,*) 'G01FEF Example Program Results'
      Write (nout,*)

!     Skip heading in data file
      Read (nin,*)

!     Display titles
      Write (nout,*) ' Probability     A         B     Deviate'
      Write (nout,*)

!     Use default tolerance
      tol = 0.0E0_nag_wp

d_lp: Do
        Read (nin,*,Iostat=ifail) p, a, b
        If (ifail/=0) Then
          Exit d_lp
        End If

!       Calculate deviates (inverse CDF)
        ifail = -1
        x = g01fef(p,a,b,tol,ifail)
        If (ifail/=0) Then
          If (ifail/=3 .And. ifail/=4) Then
            Exit d_lp
          End If
        End If

!       Display results
        Write (nout,99999) p, a, b, x
      End Do d_lp

99999 Format (1X,F9.4,2F10.3,F10.4,A,I1)
    End Program g01fefe


g01fffe.f90

    Program g01fffe

!     G01FFF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: g01fff, nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: a, b, p, tol, x
      Integer                          :: ifail
!     .. Executable Statements ..
      Write (nout,*) 'G01FFF Example Program Results'
      Write (nout,*)

!     Skip heading in data file
      Read (nin,*)

!     Display titles
      Write (nout,*) '   P       A       B           X'
      Write (nout,*)

!     Use default tolerance
      tol = 0.0E0_nag_wp

d_lp: Do
        Read (nin,*,Iostat=ifail) p, a, b
        If (ifail/=0) Then
          Exit d_lp
        End If

!       Calculate deviates (inverse CDF)
        ifail = -1
        x = g01fff(p,a,b,tol,ifail)
        If (ifail/=0) Then
          If (ifail/=4 .And. ifail/=5) Then
            Exit d_lp
          End If
        End If

!       Display results
        Write (nout,99999) p, a, b, x
      End Do d_lp

99999 Format (1X,3F8.3,F10.3,A,I1)
    End Program g01fffe


g01fmfe.f90

    Program g01fmfe

!     G01FMF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: g01fmf, nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: p, v, valq
      Integer                          :: ifail, ir
!     .. Executable Statements ..
      Write (nout,*) 'G01FMF Example Program Results'
      Write (nout,*)

!     Skip heading in data file
      Read (nin,*)

!     Display titles
      Write (nout,*) '  P     V    IR    Quantile '
      Write (nout,*)

d_lp: Do
        Read (nin,*,Iostat=ifail) p, v, ir
        If (ifail/=0) Then
          Exit d_lp
        End If

!       Compute deviate
        ifail = -1
        valq = g01fmf(p,v,ir,ifail)
        If (ifail/=0) Then
          If (ifail/=3) Then
            Exit d_lp
          End If
        End If

!       Display results
        Write (nout,99999) p, v, ir, valq
      End Do d_lp

99999 Format (1X,F5.2,2X,F4.1,1X,I3,1X,F10.4)
    End Program g01fmfe


g01ftfe.f90

    Program g01ftfe

!     G01FTF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: g01ftf, nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: x, y
      Integer                          :: ifail
!     .. Executable Statements ..
      Write (nout,*) 'G01FTF Example Program Results'
      Write (nout,*)

!     Skip heading in data file
      Read (nin,*)

!     Display titles
      Write (nout,*) '  X          Y        IFAIL'
      Write (nout,*)

d_lp: Do
        Read (nin,*,Iostat=ifail) x
        If (ifail/=0) Then
          Exit d_lp
        End If

!       Compute the value of the inverse of the Landau distribution function
        ifail = 0
        y = g01ftf(x,ifail)

!       Display results
        Write (nout,99999) x, y, ifail
      End Do d_lp

99999 Format (1X,F4.1,3X,1P,E12.4,I6)
    End Program g01ftfe


g01gbfe.f90

    Program g01gbfe

!     G01GBF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: g01gbf, nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: delta, df, prob, t, tol
      Integer                          :: ifail, maxit
!     .. Executable Statements ..
      Write (nout,*) 'G01GBF Example Program Results'
      Write (nout,*)

!     Skip heading in data file
      Read (nin,*)

!     Display titles
      Write (nout,*) '     T       DF    DELTA    PROB'
      Write (nout,*)

!     Use default tolerance and suggested number of iterations
      tol = 0.0E0_nag_wp
      maxit = 100

d_lp: Do
        Read (nin,*,Iostat=ifail) t, df, delta
        If (ifail/=0) Then
          Exit d_lp
        End If

!       Calculate probability
        ifail = 0
        prob = g01gbf(t,df,delta,tol,maxit,ifail)

!       Display results
        Write (nout,99999) t, df, delta, prob
      End Do d_lp

99999 Format (1X,3F8.3,F8.4)
    End Program g01gbfe


g01gcfe.f90

    Program g01gcfe

!     G01GCF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: g01gcf, nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: df, prob, rlamda, tol, x
      Integer                          :: ifail, maxit
!     .. Executable Statements ..
      Write (nout,*) 'G01GCF Example Program Results'
      Write (nout,*)

!     Skip heading in data file
      Read (nin,*)

!     Display titles
      Write (nout,*) '     X       DF   RLAMDA   PROB'
      Write (nout,*)

!     Use default tolerance and suggested number of iterations
      tol = 0.0E0_nag_wp
      maxit = 100

d_lp: Do
        Read (nin,*,Iostat=ifail) x, df, rlamda
        If (ifail/=0) Then
          Exit d_lp
        End If

!       Calculate probability
        ifail = 0
        prob = g01gcf(x,df,rlamda,tol,maxit,ifail)

!       Display results
        Write (nout,99999) x, df, rlamda, prob
      End Do d_lp

99999 Format (1X,3F8.3,F8.4,A,I1)
    End Program g01gcfe


g01gdfe.f90

    Program g01gdfe

!     G01GDF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: g01gdf, nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: df1, df2, f, prob, rlamda, tol
      Integer                          :: ifail, maxit
!     .. Executable Statements ..
      Write (nout,*) 'G01GDF Example Program Results'
      Write (nout,*)

!     Skip heading in data file
      Read (nin,*)

!     Display titles
      Write (nout,*) '     F      DF1     DF2   RLAMDA   PROB'
      Write (nout,*)

!     Use default tolerance and suggested number of iterations
      tol = 0.0E0_nag_wp
      maxit = 100

d_lp: Do
        Read (nin,*,Iostat=ifail) f, df1, df2, rlamda
        If (ifail/=0) Then
          Exit d_lp
        End If

!       Calculate probability
        ifail = -1
        prob = g01gdf(f,df1,df2,rlamda,tol,maxit,ifail)
        If (ifail/=0) Then
          If (ifail<3) Then
            Exit d_lp
          End If
        End If

!       Display results
        Write (nout,99999) f, df1, df2, rlamda, prob
      End Do d_lp

99999 Format (1X,4F8.3,F8.4,A,I1)
    End Program g01gdfe


g01gefe.f90

    Program g01gefe

!     G01GEF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: g01gef, nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: a, b, prob, rlamda, tol, x
      Integer                          :: ifail, maxit
!     .. Executable Statements ..
      Write (nout,*) 'G01GEF Example Program Results'
      Write (nout,*)

!     Skip heading in data file
      Read (nin,*)

!     Display titles
      Write (nout,*) '     X       A       B    RLAMDA   PROB'
      Write (nout,*)

!     Use default tolerance
      tol = 0.0E0_nag_wp
      maxit = 100

d_lp: Do
        Read (nin,*,Iostat=ifail) x, a, b, rlamda
        If (ifail/=0) Then
          Exit d_lp
        End If

!       Calculate probability
        ifail = -1
        prob = g01gef(x,a,b,rlamda,tol,maxit,ifail)
        If (ifail/=0) Then
          If (ifail<3) Then
            Exit d_lp
          End If
        End If

!       Display results
        Write (nout,99999) x, a, b, rlamda, prob
      End Do d_lp

99999 Format (1X,4F8.3,F8.4,A,I1)
    End Program g01gefe


g01hafe.f90

    Program g01hafe

!     G01HAF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: g01haf, nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: prob, rho, x, y
      Integer                          :: ifail
!     .. Executable Statements ..
      Write (nout,*) 'G01HAF Example Program Results'
      Write (nout,*)

!     Skip heading in data file
      Read (nin,*)

!     Display titles
      Write (nout,*) '     X       Y      RHO    PROB'
      Write (nout,*)

d_lp: Do
        Read (nin,*,Iostat=ifail) x, y, rho
        If (ifail/=0) Then
          Exit d_lp
        End If

!       Calculate probability
        ifail = 0
        prob = g01haf(x,y,rho,ifail)

!       Display results
        Write (nout,99999) x, y, rho, prob
      End Do d_lp

99999 Format (1X,3F8.3,F8.4)
    End Program g01hafe


g01hbfe.f90

    Program g01hbfe

!     G01HBF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: g01hbf, nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: prob, tol
      Integer                          :: i, ifail, ldsig, lwk, n
      Character (1)                    :: tail
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: a(:), b(:), sig(:,:), wk(:), xmu(:)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: max
!     .. Executable Statements ..
      Write (nout,*) 'G01HBF Example Program Results'
      Write (nout,*)

!     Skip heading in data file
      Read (nin,*)

!     Read in the problem size
      Read (nin,*) n, tol, tail

!     Use more workspace, unless N is very large
!     as LWK also defines the number of sub-intervals
      lwk = max(2000,4*n)

      ldsig = n
      Allocate (a(n),b(n),xmu(n),sig(ldsig,n),wk(lwk))

!     Read in the means
      Read (nin,*) xmu(1:n)

!     Read in the variance covariance matrix
      Read (nin,*)(sig(i,1:n),i=1,n)

!     Read in bounds
      If (tail=='C' .Or. tail=='c' .Or. tail=='U' .Or. tail=='u') Then
        Read (nin,*) a(1:n)
      End If
      If (tail=='C' .Or. tail=='c' .Or. tail=='L' .Or. tail=='l') Then
        Read (nin,*) b(1:n)
      End If

!     Calculate probability
      ifail = -1
      prob = g01hbf(tail,n,a,b,xmu,sig,ldsig,tol,wk,lwk,ifail)
      If (ifail/=0) Then
        If (ifail<=3) Then
          Go To 100
        End If
      End If

!     Display results
      Write (nout,99999) 'Multivariate Normal probability =', prob

100   Continue

99999 Format (1X,A,F7.4)
    End Program g01hbfe


g01hcfe.f90

    Program g01hcfe

!     G01HCF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: g01hcf, nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: prob, rho
      Integer                          :: df, ierr, ifail
      Character (1)                    :: tail
!     .. Local Arrays ..
      Real (Kind=nag_wp)               :: a(2), b(2)
!     .. Executable Statements ..
      Write (nout,*) 'G01HCF Example Program Results'
      Write (nout,*)

!     Skip heading in data file
      Read (nin,*)

!     Display titles
      Write (nout,*)                                                           &
        ' A(1)         B(1)       A(2)        B(2)        DF  RHO     TAIL P'
      Write (nout,*)

d_lp: Do
        ierr = 0
        a(1:2) = 0.0_nag_wp
        b(1:2) = 0.0_nag_wp

        Read (nin,Fmt='(a1)',Advance='no',Iostat=ierr) tail

!       Read parameter values
        Select Case (tail)
        Case ('l','L')
          Read (nin,*,Iostat=ierr) df, rho, b(1), b(2)
        Case ('c','C')
          Read (nin,*,Iostat=ierr) df, rho, a(1), b(1), a(2), b(2)
        Case ('u','U')
          Read (nin,*,Iostat=ierr) df, rho, a(1), a(2)
        Case Default
          Write (nout,*) 'Invalid problem specification in data file'
          Exit d_lp
        End Select

        If (ierr/=0) Then
          Exit d_lp
        End If

!       Calculate probability
        ifail = 0
        prob = g01hcf(tail,a,b,df,rho,ifail)

!       Display results
        Select Case (tail)
        Case ('l','L')
          Write (nout,99999,Advance='no') '-Inf', b(1), '-Inf', b(2)
        Case ('u','U')
          Write (nout,99998,Advance='no') a(1), 'Inf', a(2), 'Inf'
        Case ('c','C')
          Write (nout,99997,Advance='no') a(1), b(1), a(2), b(2)
        End Select

        Write (nout,99996) df, rho, tail, prob
      End Do d_lp

99999 Format (1X,2(A4,8X,E11.4,1X))
99998 Format (1X,2(E11.4,2X,A3,8X))
99997 Format (1X,4(E11.4,1X))
99996 Format (I3,1X,F7.4,2X,A1,2X,F8.4)
    End Program g01hcfe


g01hdfe.f90

    Program g01hdfe

!      G01HDF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: g01hdf, nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: epsabs, epsrel, errest, nu, prob
      Integer                          :: fmax, i, ifail, iscov, ldrc, n,      &
                                          nsampl, numsub
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: a(:), b(:), delta(:), rc(:,:)
      Character (1), Allocatable       :: tail(:)
!     .. Executable Statements ..
      Write (nout,*) 'G01HDF Example Program Results'
      Write (nout,*)

!     Skip heading in data file
      Read (nin,*)

      Read (nin,*) n, iscov

      ldrc = n

      numsub = 200
      nsampl = 8
      fmax = 25000
      epsabs = 0.0E0_nag_wp
      epsrel = 1.0E-3_nag_wp

      Allocate (tail(n),a(n),b(n),delta(n),rc(ldrc,n))

d_lp: Do
        ifail = 0

        Read (nin,*,Iostat=ifail)
        If (ifail==0) Then
          Read (nin,*,Iostat=ifail) nu
          If (ifail/=0) Then
            Exit d_lp
          End If
        Else
          Exit d_lp
        End If
        Read (nin,*) tail(1:n)
        Read (nin,*) a(1:n)
        Read (nin,*) b(1:n)
        Read (nin,*) delta(1:n)
        Read (nin,*)(rc(i,1:n),i=1,n)

!       Calculate probability
        ifail = 0
        prob = g01hdf(n,tail,a,b,nu,delta,iscov,rc,ldrc,epsabs,epsrel,numsub,  &
          nsampl,fmax,errest,ifail)

        Write (nout,99999) 'Probability:   ', prob
        Write (nout,99998) 'Error estimate:', errest
        Write (nout,*)
      End Do d_lp

99999 Format (2X,A24,E24.8)
99998 Format (2X,A24,E24.2)
    End Program g01hdfe


g01jcfe.f90

    Program g01jcfe

!     G01JCF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: g01jcf, nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: c, p, pdf, tol
      Integer                          :: i, ifail, lwrk, maxit, n, pn
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: a(:), rlamda(:), wrk(:)
      Integer, Allocatable             :: mult(:)
!     .. Executable Statements ..
      Write (nout,*) 'G01JCF Example Program Results'
      Write (nout,*)

!     Skip heading in data file
      Read (nin,*)

!     Display titles
      Write (nout,*) '        A     MULT  RLAMDA'
      Write (nout,*)

!     Use default tolerance
      tol = 0.0E0_nag_wp
      maxit = 500

!     Dummy allocation for the arrays
      Allocate (a(1),rlamda(1),mult(1),wrk(1))

      pn = 0
d_lp: Do
        Read (nin,*,Iostat=ifail) n, c
        If (ifail/=0) Then
          Exit d_lp
        End If

!       Reallocate arrays if required
        If (pn/=n) Then
          Deallocate (a,rlamda,mult,wrk)
          lwrk = n + 2*maxit
          Allocate (a(n),rlamda(n),mult(n),wrk(lwrk))
        End If
        pn = n

!       Read in weights, degrees of freedom and distribution parameter
        Read (nin,*) a(1:n)
        Read (nin,*) mult(1:n)
        Read (nin,*) rlamda(1:n)

!       Calculate probability
        ifail = -1
        Call g01jcf(a,mult,rlamda,n,c,p,pdf,tol,maxit,wrk,ifail)
        If (ifail/=0) Then
          If (ifail<4) Then
            Exit d_lp
          End If
        End If

!       Display results
        Write (nout,99999)(a(i),mult(i),rlamda(i),i=1,n)
        Write (nout,99998) 'C = ', c, '    PROB =', p
      End Do d_lp

99999 Format (1X,F10.2,I6,F9.2)
99998 Format (1X,A,F6.2,A,F7.4)
    End Program g01jcfe


g01jdfe.f90

    Program g01jdfe

!     G01JDF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: g01jdf, nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: c, d, prob
      Integer                          :: ifail, n
      Character (1)                    :: method
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: rlam(:), work(:)
!     .. Executable Statements ..
      Write (nout,*) 'G01JDF Example Program Results'
      Write (nout,*)

!     Skip heading in data file
      Read (nin,*)

!     Read in the problem size
      Read (nin,*) n, method, d, c

      Allocate (rlam(n),work(n+1))

!     Read in data
      Read (nin,*) rlam(1:n)

!     Calculate probability
      ifail = 0
      Call g01jdf(method,n,rlam,d,c,prob,work,ifail)

!     Display results
      Write (nout,99999) ' Values of lambda ', rlam(1:n)
      Write (nout,99999) ' Value of D       ', d
      Write (nout,99999) ' value of C       ', c
      Write (nout,*)
      Write (nout,99998) ' Probability = ', prob

99999 Format (1X,A,10F6.2)
99998 Format (1X,A,F10.4)
    End Program g01jdfe


g01kafe.f90

    Program g01kafe

!     G01KAF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: g01kaf, nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: f, x, xmean, xstd
      Integer                          :: ifail
!     .. Executable Statements ..
      Write (nout,*) 'G01KAF Example Program Results'
      Write (nout,*)

!     Skip heading in data file
      Read (nin,*)

!     Display titles
      Write (nout,*) '   X             MEAN          STANDARD      RESULT '
      Write (nout,*) '                               DEVIATION'
      Write (nout,*)

d_lp: Do
        Read (nin,*,Iostat=ifail) x, xmean, xstd
        If (ifail/=0) Then
          Exit d_lp
        End If

        ifail = 0
        f = g01kaf(x,xmean,xstd,ifail)

!       Display results
        Write (nout,99999) x, xmean, xstd, f
      End Do d_lp

99999 Format (1X,1P,4(1X,E13.5))
    End Program g01kafe


g01kffe.f90

    Program g01kffe

!     G01KFF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: g01kff, nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: a, b, f, x
      Integer                          :: ifail
!     .. Executable Statements ..
      Write (nout,*) 'G01KFF Example Program Results'
      Write (nout,*)

!     Skip heading in data file
      Read (nin,*)

!     Display titles
      Write (nout,*) '      X            A            B          RESULT'
      Write (nout,*)

d_lp: Do
        Read (nin,*,Iostat=ifail) x, a, b
        If (ifail/=0) Then
          Exit d_lp
        End If

        ifail = 0
        f = g01kff(x,a,b,ifail)

!       Display results
        Write (nout,99999) x, a, b, f
      End Do d_lp

99999 Format (1X,1P,4(1X,E12.4))
    End Program g01kffe


g01kkfe.f90

    Program g01kkfe
!     G01KKF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: g01kkf, nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Integer                          :: i, ifail, ilog, la, lb, lout, lx
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: a(:), b(:), pdf(:), x(:)
      Integer, Allocatable             :: ivalid(:)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: max, mod, repeat
!     .. Executable Statements ..
      Write (nout,*) 'G01KKF Example Program Results'
      Write (nout,*)

!     Skip heading in data file
      Read (nin,*)

!     Read in flag indicating whether logs are required
      Read (nin,*) ilog

!     Read in the input vectors
      Read (nin,*) lx
      Allocate (x(lx))
      Read (nin,*) x(1:lx)

      Read (nin,*) la
      Allocate (a(la))
      Read (nin,*) a(1:la)

      Read (nin,*) lb
      Allocate (b(lb))
      Read (nin,*) b(1:lb)

!     Allocate memory for output
      lout = max(lx,la,lb)
      Allocate (pdf(lout),ivalid(lout))

!     Calculate the PDF
      ifail = -1
      Call g01kkf(ilog,lx,x,la,a,lb,b,pdf,ivalid,ifail)

      If (ifail==0 .Or. ifail==1) Then
!       Display titles
        Write (nout,*) '    X         A         B         PDF      IVALID'
        Write (nout,*) repeat('-',50)

!       Display results
        Do i = 1, lout
          Write (nout,99999) x(mod(i-1,lx)+1), a(mod(i-1,la)+1),               &
            b(mod(i-1,lb)+1), pdf(i), ivalid(i)
        End Do
      End If

99999 Format (1X,3(F6.2,4X),E10.3,4X,I3)
    End Program g01kkfe


g01kqfe.f90

    Program g01kqfe
!     G01KQF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: g01kqf, nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Integer                          :: i, ifail, ilog, lout, lx, lxmu,      &
                                          lxstd
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: pdf(:), x(:), xmu(:), xstd(:)
      Integer, Allocatable             :: ivalid(:)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: max, mod, repeat
!     .. Executable Statements ..
      Write (nout,*) 'G01KQF Example Program Results'
      Write (nout,*)

!     Skip heading in data file
      Read (nin,*)

!     Read in flag indicating whether logs are required
      Read (nin,*) ilog

!     Read in the input vectors
      Read (nin,*) lx
      Allocate (x(lx))
      Read (nin,*) x(1:lx)

      Read (nin,*) lxmu
      Allocate (xmu(lxmu))
      Read (nin,*) xmu(1:lxmu)

      Read (nin,*) lxstd
      Allocate (xstd(lxstd))
      Read (nin,*) xstd(1:lxstd)

!     Allocate memory for output
      lout = max(lx,lxmu,lxstd)
      Allocate (pdf(lout),ivalid(lout))

!     Calculate the PDF
      ifail = -1
      Call g01kqf(ilog,lx,x,lxmu,xmu,lxstd,xstd,pdf,ivalid,ifail)

      If (ifail==0 .Or. ifail==1) Then
!       Display titles
        Write (nout,*) '    X        XMU      XSTD        PDF      IVALID'
        Write (nout,*) repeat('-',50)

!       Display results
        Do i = 1, lout
          Write (nout,99999) x(mod(i-1,lx)+1), xmu(mod(i-1,lxmu)+1),           &
            xstd(mod(i-1,lxstd)+1), pdf(i), ivalid(i)
        End Do
      End If

99999 Format (1X,3(F6.2,4X),E10.3,4X,I3)
    End Program g01kqfe


g01lbfe.f90

    Program g01lbfe

!     G01LBF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: g01lbf, nag_wp, x04caf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Integer                          :: i, ifail, ilog, iuld, k, ldsig, ldx, &
                                          n, rank
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: pdf(:), sig(:,:), x(:,:), xmu(:)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: repeat
!     .. Executable Statements ..
      Write (nout,*) 'G01LBF Example Program Results'
      Write (nout,*)
      Flush (nout)

!     Skip heading in data file
      Read (nin,*)

!     Read in the problem size and how the covariance matrix is stored
!     and whether the log PDF is required
      Read (nin,*) k, n, iuld, ilog

!     Allocate arrays
      ldx = n
      Allocate (x(ldx,k),xmu(n),pdf(k))

!     Read in and echo the vector of means
      Read (nin,*) xmu(1:n)
      Write (nout,*) 'Vector of Means: '
      Write (nout,99999) xmu(1:n)
      Write (nout,*)

!     Read in and echo the covariance matrix
      If (iuld==3) Then
!       Covariance matrix is diagonal
        ldsig = 1
        Allocate (sig(ldsig,n))
        Read (nin,*) sig(1,1:n)

        Write (nout,*) 'Diagonal Elements of Covariance Matrix: '
        Write (nout,99999) sig(1,1:n)

      Else
!       Read in an upper or lower triangular matrix
        ldsig = n
        Allocate (sig(ldsig,n))
        If (iuld==1 .Or. iuld==4) Then
!         Lower triangular matrix
          Read (nin,*)(sig(i,1:i),i=1,n)

          If (iuld==1) Then
            Call x04caf('Lower','Nonunit',n,n,sig,ldsig,'Covariance Matrix:',  &
              ifail)
          Else
            Call x04caf('Lower','Nonunit',n,n,sig,ldsig,                       &
              'Lower Triangular Cholesky Factor of Covariance Matrix:',ifail)
          End If
        Else
!         Upper triangular matrix
          Read (nin,*)(sig(i,i:n),i=1,n)

          If (iuld==2) Then
            Call x04caf('Upper','Nonunit',n,n,sig,ldsig,'Covariance Matrix:',  &
              ifail)
          Else
            Call x04caf('Upper','Nonunit',n,n,sig,ldsig,                       &
              'Upper Triangular Cholesky Factor of Covariance Matrix:',ifail)
          End If
        End If
      End If

!     Read in the points at which to evaluate the PDF
      Read (nin,*)(x(1:n,i),i=1,k)

!     Evaluate the PDF
      ifail = 0
      Call g01lbf(ilog,k,n,x,ldx,xmu,iuld,sig,ldsig,pdf,rank,ifail)

!     Display results
      Write (nout,*)
      Write (nout,*) 'Rank of the covariance matrix: ', rank
      Write (nout,*)
      If (ilog==1) Then
        Write (nout,*) '     log(PDF)                  X'
      Else
        Write (nout,*) '       PDF                     X'
      End If
      Write (nout,*) '  ', repeat('-',48)
      Do i = 1, k
        Write (nout,99998) pdf(i), x(1:n,i)
      End Do

99999 Format (1X,100(F8.4,1X))
99998 Format (1X,1P,E13.4,0P,10(1X,F8.4))
    End Program g01lbfe


g01mbfe.f90

    Program g01mbfe

!     G01MBF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: a00acf, g01mbf, nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: rm, x, xmu, xsig, z
      Integer                          :: ifail
!     .. Executable Statements ..
      Write (nout,*) 'G01MBF Example Program Results '
      Write (nout,*)

!     Check for valid licence prior to calling G01MBF
      If (.Not. a00acf()) Then
        Write (nout,*) ' ** A valid licence key was not found'

      Else
!       Skip heading in data file
        Read (nin,*)

!       Display titles
        Write (nout,*) ' Mean     Sigma    X        Reciprocal'
        Write (nout,*) '                            Mills Ratio'
        Write (nout,*)

d_lp:   Do
          Read (nin,*,Iostat=ifail) x, xmu, xsig
          If (ifail/=0) Then
            Exit d_lp
          End If

          z = (x-xmu)/xsig
          rm = g01mbf(z)/xsig

!         Display results
          Write (nout,99999) xmu, xsig, x, rm
        End Do d_lp
      End If

99999 Format (1X,4(F7.4,2X))
    End Program g01mbfe


g01mtfe.f90

    Program g01mtfe

!     G01MTF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: a00acf, g01mtf, nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: x, y
      Integer                          :: ifail
!     .. Executable Statements ..
      Write (nout,*) 'G01MTF Example Program Results'
      Write (nout,*)

!     Check for valid licence prior to calling G01MTF
      If (.Not. a00acf()) Then
        Write (nout,*) ' ** A valid licence key was not found'

      Else
!       Skip heading in data file
        Read (nin,*)

!       Display titles
        Write (nout,*) '  X          Y'
        Write (nout,*)

d_lp:   Do
          Read (nin,*,Iostat=ifail) x
          If (ifail/=0) Then
            Exit d_lp
          End If

!         Compute the value of the Landau density function
          y = g01mtf(x)

!         Display results
          Write (nout,99999) x, y
        End Do d_lp
      End If

99999 Format (1X,F4.1,3X,1P,E12.4)
    End Program g01mtfe


g01mufe.f90

    Program g01mufe

!     G01MUF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: g01muf, g01zuf, nag_wp, x02alf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: mode = 0, nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: beta2, c1, c2, rkappa, x, xl, xu, y
      Integer                          :: ifail
!     .. Local Arrays ..
      Real (Kind=nag_wp)               :: rcomm(322)
!     .. Executable Statements ..
      Write (nout,*) 'G01MUF Example Program Results'
      Write (nout,*)

!     Skip heading in data file
      Read (nin,*)
      c1 = -x02alf()
      c2 = -x02alf()

!     Display titles
      Write (nout,*) '  X     RKAPPA    BETA2        Y        IFAIL'
      Write (nout,*)

d_lp: Do
        Read (nin,*,Iostat=ifail) x, rkappa, beta2
        If (ifail/=0) Then
          Exit d_lp
        End If

        If ((rkappa/=c1) .Or. (beta2/=c2)) Then
!         Initialize the RCOMM array if RKAPPA or BETA2 has changed
          ifail = 0
          Call g01zuf(rkappa,beta2,mode,xl,xu,rcomm,ifail)
        End If

!       Compute the value of the Vavilov density function
        ifail = 0
        y = g01muf(x,rcomm,ifail)

!       Display results
        Write (nout,99999) x, rkappa, beta2, y, ifail
        c1 = rkappa
        c2 = beta2
      End Do d_lp

99999 Format (1X,F4.1,5X,F4.1,5X,F4.1,3X,1P,E12.4,I6)
    End Program g01mufe


g01nafe.f90

    Program g01nafe

!     G01NAF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: g01naf, nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: beta, con
      Integer                          :: i, ifail, j, l, lda, ldsig, lwk, n
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: a(:,:), emu(:), rkum(:), rmom(:),    &
                                          sigma(:,:), wk(:)
!     .. Executable Statements ..
      Write (nout,*) 'G01NAF Example Program Results'
      Write (nout,*)

!     Skip heading in data file
      Read (nin,*)

!     Read in the problem size
      Read (nin,*) beta, con
      Read (nin,*) n, l

      ldsig = n
      lda = n
      lwk = 3*n*(n+1)/2 + n
      Allocate (a(lda,n),emu(n),sigma(ldsig,n),rkum(l),rmom(l),wk(lwk))

!     Compute A, EMU, and SIGMA for simple autoregression
      Do i = 1, n
        Do j = i, n
          a(j,i) = 0.0E0_nag_wp
        End Do
      End Do
      Do i = 1, n - 1
        a(i+1,i) = 0.5E0_nag_wp
      End Do
      emu(1) = con*beta
      Do i = 1, n - 1
        emu(i+1) = beta*emu(i)
      End Do
      sigma(1,1) = 1.0E0_nag_wp
      Do i = 2, n
        sigma(i,i) = beta*beta*sigma(i-1,i-1) + 1.0E0_nag_wp
      End Do
      Do i = 1, n
        Do j = i + 1, n
          sigma(j,i) = beta*sigma(j-1,i)
        End Do
      End Do

!     Compute cumulants
      ifail = 0
      Call g01naf('M','M',n,a,lda,emu,sigma,ldsig,l,rkum,rmom,wk,ifail)

!     Display results
      Write (nout,99999) ' N = ', n, ' BETA = ', beta, ' CON = ', con
      Write (nout,*)
      Write (nout,*) '    Cumulants       Moments'
      Write (nout,*)
      Write (nout,99998)(i,rkum(i),rmom(i),i=1,l)

99999 Format (A,I3,2(A,F6.3))
99998 Format (I3,E12.4,4X,E12.4)
    End Program g01nafe


g01nbfe.f90

    Program g01nbfe

!     G01NBF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: g01nbf, nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: abserr, beta, eps, y0
      Integer                          :: i, ifail, j, l1, l2, lda, ldb, ldc,  &
                                          ldsig, lmax, lwk, n
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: a(:,:), b(:,:), c(:,:), ela(:),      &
                                          emu(:), rmom(:), sigma(:,:), wk(:)
!     .. Executable Statements ..
      Write (nout,*) 'G01NBF Example Program Results'
      Write (nout,*)

!     Skip heading in data file
      Read (nin,*)

!     Read in the problem size
      Read (nin,*) beta, y0
      Read (nin,*) n, l1, l2

      lda = n
      ldb = n
      ldc = n
      ldsig = n
      lwk = 3*n*n + (8+l2)*n
      Allocate (a(lda,n),b(ldb,n),c(ldc,n),ela(n),emu(n),sigma(ldsig,n),       &
        wk(lwk),rmom(l2-l1+1))

!     Compute A, EMU, and SIGMA for simple autoregression
      Do i = 1, n
        Do j = i, n
          a(j,i) = 0.0E0_nag_wp
          b(j,i) = 0.0E0_nag_wp
        End Do
      End Do
      Do i = 1, n - 1
        a(i+1,i) = 0.5E0_nag_wp
        b(i,i) = 1.0E0_nag_wp
      End Do
      emu(1) = y0*beta
      Do i = 1, n - 1
        emu(i+1) = beta*emu(i)
      End Do
      sigma(1,1) = 1.0E0_nag_wp
      Do i = 2, n
        sigma(i,i) = beta*beta*sigma(i-1,i-1) + 1.0E0_nag_wp
      End Do
      Do i = 1, n
        Do j = i + 1, n
          sigma(j,i) = beta*sigma(j-1,i)
        End Do
      End Do

!     Use default accuracy
      eps = 0.0E0_nag_wp

!     Compute moments
      ifail = -1
      Call g01nbf('Ratio','Mean',n,a,lda,b,ldb,c,ldc,ela,emu,sigma,ldsig,l1,   &
        l2,lmax,rmom,abserr,eps,wk,ifail)
      If (ifail/=0) Then
        If (ifail<6) Then
          Go To 100
        End If
      End If

!     Display results
      Write (nout,99999) ' N = ', n, ' BETA = ', beta, ' Y0 = ', y0
      Write (nout,*)
      Write (nout,*) '      Moments'
      Write (nout,*)
      j = 0
      Do i = l1, lmax
        j = j + 1
        Write (nout,99998) i, rmom(j)
      End Do

100   Continue

99999 Format (A,I3,2(A,F6.3))
99998 Format (I3,E12.3)
    End Program g01nbfe


g01ptfe.f90

    Program g01ptfe

!     G01PTF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: a00acf, g01ptf, nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: x, y
      Integer                          :: ifail
!     .. Executable Statements ..
      Write (nout,*) 'G01PTF Example Program Results'
      Write (nout,*)

!     Check for valid licence prior to calling G01PTF
      If (.Not. a00acf()) Then
        Write (nout,*) ' ** A valid licence key was not found'

      Else
!       Skip heading in data file
        Read (nin,*)

!       Display title
        Write (nout,*) '  X          Y'
        Write (nout,*)

d_lp:   Do
          Read (nin,*,Iostat=ifail) x
          If (ifail/=0) Then
            Exit d_lp
          End If

!         Compute the value of the 1st moment of the Landau density function
          y = g01ptf(x)

!         Display results
          Write (nout,99999) x, y
        End Do d_lp
      End If

99999 Format (1X,F4.1,3X,1P,E12.4)
    End Program g01ptfe


g01qtfe.f90

    Program g01qtfe

!     G01QTF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: a00acf, g01qtf, nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: x, y
      Integer                          :: ifail
!     .. Executable Statements ..
      Write (nout,*) 'G01QTF Example Program Results'
      Write (nout,*)

!     Check for valid licence prior to calling G01QTF
      If (.Not. a00acf()) Then
        Write (nout,*) ' ** A valid licence key was not found'

      Else
!       Skip heading in data file
        Read (nin,*)

!       Display title
        Write (nout,*) '  X          Y'
        Write (nout,*)

d_lp:   Do
          Read (nin,*,Iostat=ifail) x
          If (ifail/=0) Then
            Exit d_lp
          End If

!         Compute the value of the 2nd moment of the Landau density function
          y = g01qtf(x)

!         Display results
          Write (nout,99999) x, y
        End Do d_lp
      End If

99999 Format (1X,F4.1,3X,1P,E12.4)
    End Program g01qtfe


g01rtfe.f90

    Program g01rtfe

!     G01RTF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: a00acf, g01rtf, nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: x, y
      Integer                          :: ifail
!     .. Executable Statements ..
      Write (nout,*) 'G01RTF Example Program Results'
      Write (nout,*)

!     Check for valid licence prior to calling G01RTF
      If (.Not. a00acf()) Then
        Write (nout,*) ' ** A valid licence key was not found'

      Else
!       Skip heading in data file
        Read (nin,*)

!       Display title
        Write (nout,*) '  X          Y'
        Write (nout,*)

d_lp:   Do
          Read (nin,*,Iostat=ifail) x
          If (ifail/=0) Then
            Exit d_lp
          End If

!         Compute the value of the derivative of the Landau density function
          y = g01rtf(x)

!         Display results
          Write (nout,99999) x, y
        End Do d_lp
      End If

99999 Format (1X,F4.1,3X,1P,E12.4)
    End Program g01rtfe


g01safe.f90

    Program g01safe
!     G01SAF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: g01saf, nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Integer                          :: i, ifail, lout, ltail, lx, lxmu,     &
                                          lxstd
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: p(:), x(:), xmu(:), xstd(:)
      Integer, Allocatable             :: ivalid(:)
      Character (1), Allocatable       :: tail(:)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: max, mod, repeat
!     .. Executable Statements ..
      Write (nout,*) 'G01SAF Example Program Results'
      Write (nout,*)

!     Skip heading in data file
      Read (nin,*)

!     Read in the input vectors
      Read (nin,*) ltail
      Allocate (tail(ltail))
      Read (nin,*) tail(1:ltail)

      Read (nin,*) lx
      Allocate (x(lx))
      Read (nin,*) x(1:lx)

      Read (nin,*) lxmu
      Allocate (xmu(lxmu))
      Read (nin,*) xmu(1:lxmu)

      Read (nin,*) lxstd
      Allocate (xstd(lxstd))
      Read (nin,*) xstd(1:lxstd)

!     Allocate memory for output
      lout = max(ltail,lx,lxmu,lxstd)
      Allocate (p(lout),ivalid(lout))

!     Calculate probability
      ifail = -1
      Call g01saf(ltail,tail,lx,x,lxmu,xmu,lxstd,xstd,p,ivalid,ifail)

      If (ifail==0 .Or. ifail==1) Then
!       Display title
        Write (nout,*)                                                         &
          '   TAIL      X        XMU      XSTD       P     IVALID'
        Write (nout,*) repeat('-',56)

!       Display results
        Do i = 1, lout
          Write (nout,99999) tail(mod(i-1,ltail)+1), x(mod(i-1,lx)+1),         &
            xmu(mod(i-1,lxmu)+1), xstd(mod(i-1,lxstd)+1), p(i), ivalid(i)
        End Do
      End If

99999 Format (5X,A1,3(4X,F6.2),4X,F6.3,4X,I3)
    End Program g01safe


g01sbfe.f90

    Program g01sbfe
!     G01SBF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: g01sbf, nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Integer                          :: i, ifail, ldf, lout, lt, ltail
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: df(:), p(:), t(:)
      Integer, Allocatable             :: ivalid(:)
      Character (1), Allocatable       :: tail(:)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: max, mod, repeat
!     .. Executable Statements ..
      Write (nout,*) 'G01SBF Example Program Results'
      Write (nout,*)

!     Skip heading in data file
      Read (nin,*)

!     Read in the input vectors
      Read (nin,*) ltail
      Allocate (tail(ltail))
      Read (nin,*) tail(1:ltail)

      Read (nin,*) lt
      Allocate (t(lt))
      Read (nin,*) t(1:lt)

      Read (nin,*) ldf
      Allocate (df(ldf))
      Read (nin,*) df(1:ldf)

!     Allocate memory for output
      lout = max(lt,ldf,ltail)
      Allocate (p(lout),ivalid(lout))

!     Calculate probability
      ifail = -1
      Call g01sbf(ltail,tail,lt,t,ldf,df,p,ivalid,ifail)

      If (ifail==0 .Or. ifail==1) Then
!       Display titles
        Write (nout,*) '   TAIL      T        DF        P      IVALID'
        Write (nout,*) repeat('-',47)

!       Display results
        Do i = 1, lout
          Write (nout,99999) tail(mod(i-1,ltail)+1), t(mod(i-1,lt)+1),         &
            df(mod(i-1,ldf)+1), p(i), ivalid(i)
        End Do
      End If

99999 Format (5X,A1,2(4X,F6.2),4X,F6.3,4X,I3)
    End Program g01sbfe


g01scfe.f90

    Program g01scfe
!     G01SCF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: g01scf, nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Integer                          :: i, ifail, ldf, lout, ltail, lx
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: df(:), p(:), x(:)
      Integer, Allocatable             :: ivalid(:)
      Character (1), Allocatable       :: tail(:)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: max, mod, repeat
!     .. Executable Statements ..
      Write (nout,*) 'G01SCF Example Program Results'
      Write (nout,*)

!     Skip heading in data file
      Read (nin,*)

!     Read in the input vectors
      Read (nin,*) ltail
      Allocate (tail(ltail))
      Read (nin,*) tail(1:ltail)

      Read (nin,*) lx
      Allocate (x(lx))
      Read (nin,*) x(1:lx)

      Read (nin,*) ldf
      Allocate (df(ldf))
      Read (nin,*) df(1:ldf)

!     Allocate memory for output
      lout = max(ltail,lx,ldf)
      Allocate (p(lout),ivalid(lout))

!     Calculate probability
      ifail = -1
      Call g01scf(ltail,tail,lx,x,ldf,df,p,ivalid,ifail)

      If (ifail==0 .Or. ifail==1) Then
!       Display titles
        Write (nout,*) '   TAIL     X        DF        P      IVALID'
        Write (nout,*) repeat('-',45)

!       Display results
        Do i = 1, lout
          Write (nout,99999) tail(mod(i-1,ltail)+1), x(mod(i-1,lx)+1),         &
            df(mod(i-1,ldf)+1), p(i), ivalid(i)
        End Do
      End If

99999 Format (5X,A1,2(4X,F6.2),4X,F6.3,4X,I3)
    End Program g01scfe


g01sdfe.f90

    Program g01sdfe
!     G01SDF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: g01sdf, nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Integer                          :: i, ifail, ldf1, ldf2, lf, lout,      &
                                          ltail
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: df1(:), df2(:), f(:), p(:)
      Integer, Allocatable             :: ivalid(:)
      Character (1), Allocatable       :: tail(:)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: max, mod, repeat
!     .. Executable Statements ..
      Write (nout,*) 'G01SDF Example Program Results'
      Write (nout,*)

!     Skip heading in data file
      Read (nin,*)

!     Read in the input vectors
      Read (nin,*) ltail
      Allocate (tail(ltail))
      Read (nin,*) tail(1:ltail)

      Read (nin,*) lf
      Allocate (f(lf))
      Read (nin,*) f(1:lf)

      Read (nin,*) ldf1
      Allocate (df1(ldf1))
      Read (nin,*) df1(1:ldf1)

      Read (nin,*) ldf2
      Allocate (df2(ldf2))
      Read (nin,*) df2(1:ldf2)

!     Allocate memory for output
      lout = max(lf,ldf1,ldf2,ltail)
      Allocate (p(lout),ivalid(lout))

!     Calculate probability
      ifail = -1
      Call g01sdf(ltail,tail,lf,f,ldf1,df1,ldf2,df2,p,ivalid,ifail)

      If (ifail==0 .Or. ifail==1) Then
!       Display titles
        Write (nout,*)                                                         &
          '   TAIL      F        DF1       DF2       P      IVALID'
        Write (nout,*) repeat('-',56)

!       Display results
        Do i = 1, lout
          Write (nout,99999) tail(mod(i-1,ltail)+1), f(mod(i-1,lf)+1),         &
            df1(mod(i-1,ldf1)+1), df2(mod(i-1,ldf2)+1), p(i), ivalid(i)
        End Do
      End If

99999 Format (5X,A1,3(4X,F6.2),4X,F6.3,4X,I3)
    End Program g01sdfe


g01sefe.f90

    Program g01sefe
!     G01SEF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: g01sef, nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Integer                          :: i, ifail, la, lb, lbeta, lout, ltail
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: a(:), b(:), beta(:), p(:)
      Integer, Allocatable             :: ivalid(:)
      Character (1), Allocatable       :: tail(:)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: max, mod, repeat
!     .. Executable Statements ..
      Write (nout,*) 'G01SEF Example Program Results'
      Write (nout,*)

!     Skip heading in data file
      Read (nin,*)

!     Read in the input vectors
      Read (nin,*) ltail
      Allocate (tail(ltail))
      Read (nin,*) tail(1:ltail)

      Read (nin,*) lbeta
      Allocate (beta(lbeta))
      Read (nin,*) beta(1:lbeta)

      Read (nin,*) la
      Allocate (a(la))
      Read (nin,*) a(1:la)

      Read (nin,*) lb
      Allocate (b(lb))
      Read (nin,*) b(1:lb)

!     Allocate memory for output
      lout = max(ltail,lbeta,la,lb)
      Allocate (p(lout),ivalid(lout))

!     Calculate probability
      ifail = -1
      Call g01sef(ltail,tail,lbeta,beta,la,a,lb,b,p,ivalid,ifail)

      If (ifail==0 .Or. ifail==1) Then
!       Display titles
        Write (nout,*)                                                         &
          '  TAIL    BETA        A         B        P      IVALID'
        Write (nout,*) repeat('-',56)

!       Display results
        Do i = 1, lout
          Write (nout,99999) tail(mod(i-1,ltail)+1), beta(mod(i-1,lbeta)+1),   &
            a(mod(i-1,la)+1), b(mod(i-1,lb)+1), p(i), ivalid(i)
        End Do
      End If

99999 Format (5X,A1,3(4X,F6.2),4X,F6.3,4X,I3)
    End Program g01sefe


g01sffe.f90

    Program g01sffe
!     G01SFF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: g01sff, nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Integer                          :: i, ifail, la, lb, lg, lout, ltail
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: a(:), b(:), g(:), p(:)
      Integer, Allocatable             :: ivalid(:)
      Character (1), Allocatable       :: tail(:)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: max, mod, repeat
!     .. Executable Statements ..
      Write (nout,*) 'G01SFF Example Program Results'
      Write (nout,*)
!     Skip heading in data file
      Read (nin,*)

!     Read in the input vectors
      Read (nin,*) ltail
      Allocate (tail(ltail))
      Read (nin,*) tail(1:ltail)

      Read (nin,*) lg
      Allocate (g(lg))
      Read (nin,*) g(1:lg)

      Read (nin,*) la
      Allocate (a(la))
      Read (nin,*) a(1:la)

      Read (nin,*) lb
      Allocate (b(lb))
      Read (nin,*) b(1:lb)

!     Allocate memory for output
      lout = max(ltail,lg,la,lb)
      Allocate (p(lout),ivalid(lout))

!     Calculate probability
      ifail = -1
      Call g01sff(ltail,tail,lg,g,la,a,lb,b,p,ivalid,ifail)

      If (ifail==0 .Or. ifail==1) Then
!       Display titles
        Write (nout,*)                                                         &
          '  TAIL      G         A         B         P     IVALID'
        Write (nout,*) repeat('-',57)

!       Display results
        Do i = 1, lout
          Write (nout,99999) tail(mod(i-1,ltail)+1), g(mod(i-1,lg)+1),         &
            a(mod(i-1,la)+1), b(mod(i-1,lb)+1), p(i), ivalid(i)
        End Do
      End If

99999 Format (5X,A1,3(4X,F6.2),4X,F6.3,4X,I3)
    End Program g01sffe


g01sjfe.f90

    Program g01sjfe
!     G01SJF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: g01sjf, nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Integer                          :: i, ifail, lk, ln, lout, lp
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: p(:), peqk(:), pgtk(:), plek(:)
      Integer, Allocatable             :: ivalid(:), k(:), n(:)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: max, mod, repeat
!     .. Executable Statements ..
      Write (nout,*) 'G01SJF Example Program Results'
      Write (nout,*)

!     Skip heading in data file
      Read (nin,*)

!     Read in the input vectors
      Read (nin,*) ln
      Allocate (n(ln))
      Read (nin,*) n(1:ln)

      Read (nin,*) lp
      Allocate (p(lp))
      Read (nin,*) p(1:lp)

      Read (nin,*) lk
      Allocate (k(lk))
      Read (nin,*) k(1:lk)

!     Allocate memory for output
      lout = max(ln,lp,lk)
      Allocate (peqk(lout),pgtk(lout),plek(lout),ivalid(lout))

!     Calculate probability
      ifail = -1
      Call g01sjf(ln,n,lp,p,lk,k,plek,pgtk,peqk,ivalid,ifail)

      If (ifail==0 .Or. ifail==1) Then
!       Display titles
        Write (nout,*)                                                         &
          '    N         P         K       PLEK      PGTK      PEQK    IVALID'
        Write (nout,*) repeat('-',68)

!       Display results
        Do i = 1, lout
          Write (nout,99999) n(mod(i-1,ln)+1), p(mod(i-1,lp)+1),               &
            k(mod(i-1,lk)+1), plek(i), pgtk(i), peqk(i), ivalid(i)
        End Do
      End If

99999 Format (1X,I6,4X,F6.2,4X,I6,3(4X,F6.3),4X,I3)
    End Program g01sjfe


g01skfe.f90

    Program g01skfe
!     G01SKF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: g01skf, nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Integer                          :: i, ifail, lk, ll, lout
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: l(:), peqk(:), pgtk(:), plek(:)
      Integer, Allocatable             :: ivalid(:), k(:)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: max, mod, repeat
!     .. Executable Statements ..
      Write (nout,*) 'G01SKF Example Program Results'
      Write (nout,*)

!     Skip heading in data file
      Read (nin,*)

!     Read in the input vectors
      Read (nin,*) ll
      Allocate (l(ll))
      Read (nin,*) l(1:ll)

      Read (nin,*) lk
      Allocate (k(lk))
      Read (nin,*) k(1:lk)

!     Allocate memory for output
      lout = max(ll,lk)
      Allocate (peqk(lout),pgtk(lout),plek(lout),ivalid(lout))

!     Calculate probability
      ifail = -1
      Call g01skf(ll,l,lk,k,plek,pgtk,peqk,ivalid,ifail)

      If (ifail==0 .Or. ifail==1) Then
!       Display titles
        Write (nout,*)                                                         &
          '    L         K       PLEK      PGTK      PEQK    IVALID'
        Write (nout,*) repeat('-',58)

!       Display results
        Do i = 1, lout
          Write (nout,99999) l(mod(i-1,ll)+1), k(mod(i-1,lk)+1), plek(i),      &
            pgtk(i), peqk(i), ivalid(i)
        End Do
      End If

99999 Format (1X,F6.2,4X,I6,3(4X,F6.3),4X,I3)
    End Program g01skfe


g01slfe.f90

    Program g01slfe
!     G01SLF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: g01slf, nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Integer                          :: i, ifail, lk, ll, lm, ln, lout
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: peqk(:), pgtk(:), plek(:)
      Integer, Allocatable             :: ivalid(:), k(:), l(:), m(:), n(:)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: max, mod, repeat
!     .. Executable Statements ..
      Write (nout,*) 'G01SLF Example Program Results'
      Write (nout,*)

!     Skip heading in data file
      Read (nin,*)

!     Read in the input vectors
      Read (nin,*) ln
      Allocate (n(ln))
      Read (nin,*) n(1:ln)

      Read (nin,*) ll
      Allocate (l(ll))
      Read (nin,*) l(1:ll)

      Read (nin,*) lm
      Allocate (m(lm))
      Read (nin,*) m(1:lm)

      Read (nin,*) lk
      Allocate (k(lk))
      Read (nin,*) k(1:lk)

!     Allocate memory for output
      lout = max(ln,ll,lm,lk)
      Allocate (pgtk(lout),plek(lout),peqk(lout),ivalid(lout))

!     Calculate probability
      ifail = -1
      Call g01slf(ln,n,ll,l,lm,m,lk,k,plek,pgtk,peqk,ivalid,ifail)

      If (ifail==0 .Or. ifail==1) Then
!       Display titles
        Write (nout,*)                                                         &
          '    N         L         M         K       PLEK      PGTK      ',    &
          'PEQK    IVALID'
        Write (nout,*) repeat('-',78)

!       Display results
        Do i = 1, lout
          Write (nout,99999) n(mod(i-1,ln)+1), l(mod(i-1,ll)+1),               &
            m(mod(i-1,lm)+1), k(mod(i-1,lk)+1), plek(i), pgtk(i), peqk(i),     &
            ivalid(i)
        End Do
      End If

99999 Format (1X,4(I6,4X),3(F6.3,4X),I3)
    End Program g01slfe


g01tafe.f90

    Program g01tafe
!     G01TAF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: g01taf, nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Integer                          :: i, ifail, lout, lp, ltail, lxmu,     &
                                          lxstd
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: p(:), x(:), xmu(:), xstd(:)
      Integer, Allocatable             :: ivalid(:)
      Character (1), Allocatable       :: tail(:)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: max, mod, repeat
!     .. Executable Statements ..
      Write (nout,*) 'G01TAF Example Program Results'
      Write (nout,*)

!     Skip heading in data file
      Read (nin,*)

!     Read in the input vectors
      Read (nin,*) ltail
      Allocate (tail(ltail))
      Read (nin,*) tail(1:ltail)

      Read (nin,*) lp
      Allocate (p(lp))
      Read (nin,*) p(1:lp)

      Read (nin,*) lxmu
      Allocate (xmu(lxmu))
      Read (nin,*) xmu(1:lxmu)

      Read (nin,*) lxstd
      Allocate (xstd(lxstd))
      Read (nin,*) xstd(1:lxstd)

!     Allocate memory for output
      lout = max(lp,ltail,lxmu,lxstd)
      Allocate (x(lout),ivalid(lout))

!     Calculate the deviate (inverse CDF)
      ifail = -1
      Call g01taf(ltail,tail,lp,p,lxmu,xmu,lxstd,xstd,x,ivalid,ifail)

      If (ifail==0 .Or. ifail==1) Then
!       Display titles
        Write (nout,*)
        Write (nout,*)                                                         &
          '   TAIL      P        XMU      XSTD       X     IVALID'
        Write (nout,*) repeat('-',56)

!       Display results
        Do i = 1, lout
          Write (nout,99999) tail(mod(i-1,ltail)+1), p(mod(i-1,lp)+1),         &
            xmu(mod(i-1,lxmu)+1), xstd(mod(i-1,lxstd)+1), x(i), ivalid(i)
        End Do
      End If

99999 Format (5X,A1,4X,F6.3,2(4X,F6.3),3X,F7.3,4X,I3)
    End Program g01tafe


g01tbfe.f90

    Program g01tbfe
!     G01TBF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: g01tbf, nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Integer                          :: i, ifail, ldf, lout, lp, ltail
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: df(:), p(:), t(:)
      Integer, Allocatable             :: ivalid(:)
      Character (1), Allocatable       :: tail(:)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: max, mod, repeat
!     .. Executable Statements ..
      Write (nout,*) 'G01TBF Example Program Results'
      Write (nout,*)

!     Skip heading in data file
      Read (nin,*)

!     Read in the input vectors
      Read (nin,*) ltail
      Allocate (tail(ltail))
      Read (nin,*) tail(1:ltail)

      Read (nin,*) lp
      Allocate (p(lp))
      Read (nin,*) p(1:lp)

      Read (nin,*) ldf
      Allocate (df(ldf))
      Read (nin,*) df(1:ldf)

!     Allocate memory for output
      lout = max(lp,ldf,ltail)
      Allocate (ivalid(lout),t(lout))

!     Calculate deviates (inverse CDF)
      ifail = -1
      Call g01tbf(ltail,tail,lp,p,ldf,df,t,ivalid,ifail)

      If (ifail==0 .Or. ifail==1) Then
!       Display titles
        Write (nout,*) '   TAIL      P        DF        T      IVALID'
        Write (nout,*) repeat('-',47)

!       Display results
        Do i = 1, lout
          Write (nout,99999) tail(mod(i-1,ltail)+1), p(mod(i-1,lp)+1),         &
            df(mod(i-1,ldf)+1), t(i), ivalid(i)
        End Do
      End If

99999 Format (5X,A1,4X,F6.3,4X,F6.2,3X,F7.3,4X,I3)
    End Program g01tbfe


g01tcfe.f90

    Program g01tcfe
!     G01TCF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: g01tcf, nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Integer                          :: i, ifail, ldf, lout, lp, ltail
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: df(:), p(:), x(:)
      Integer, Allocatable             :: ivalid(:)
      Character (1), Allocatable       :: tail(:)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: max, mod, repeat
!     .. Executable Statements ..
      Write (nout,*) 'G01TCF Example Program Results'
      Write (nout,*)

!     Skip heading in data file
      Read (nin,*)

!     Read in the input vectors
      Read (nin,*) ltail
      Allocate (tail(ltail))
      Read (nin,*) tail(1:ltail)

      Read (nin,*) lp
      Allocate (p(lp))
      Read (nin,*) p(1:lp)

      Read (nin,*) ldf
      Allocate (df(ldf))
      Read (nin,*) df(1:ldf)

!     Allocate memory for output
      lout = max(ltail,lp,ldf)
      Allocate (x(lout),ivalid(lout))

!     Calculate deviates (inverse CDF)
      ifail = -1
      Call g01tcf(ltail,tail,lp,p,ldf,df,x,ivalid,ifail)

      If (ifail==0 .Or. ifail==1) Then
!       Display titles
        Write (nout,*) '   TAIL      P        DF        X      IVALID'
        Write (nout,*) repeat('-',48)

!       Display results
        Do i = 1, lout
          Write (nout,99999) tail(mod(i-1,ltail)+1), p(mod(i-1,lp)+1),         &
            df(mod(i-1,ldf)+1), x(i), ivalid(i)
        End Do
      End If

99999 Format (5X,A1,4X,F6.3,4X,F6.2,3X,F7.3,4X,I3)
    End Program g01tcfe


g01tdfe.f90

    Program g01tdfe
!     G01TDF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: g01tdf, nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Integer                          :: i, ifail, ldf1, ldf2, lout, lp,      &
                                          ltail
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: df1(:), df2(:), f(:), p(:)
      Integer, Allocatable             :: ivalid(:)
      Character (1), Allocatable       :: tail(:)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: max, mod, repeat
!     .. Executable Statements ..
      Write (nout,*) 'G01TDF Example Program Results'
      Write (nout,*)

!     Skip heading in data file
      Read (nin,*)

!     Read in the input vectors
      Read (nin,*) ltail
      Allocate (tail(ltail))
      Read (nin,*) tail(1:ltail)

      Read (nin,*) lp
      Allocate (p(lp))
      Read (nin,*) p(1:lp)

      Read (nin,*) ldf1
      Allocate (df1(ldf1))
      Read (nin,*) df1(1:ldf1)

      Read (nin,*) ldf2
      Allocate (df2(ldf2))
      Read (nin,*) df2(1:ldf2)

!     Allocate memory for output
      lout = max(ltail,lp,ldf1,ldf2)
      Allocate (f(lout),ivalid(lout))

!     Calculate deviates (inverse CDF)
      ifail = -1
      Call g01tdf(ltail,tail,lp,p,ldf1,df1,ldf2,df2,f,ivalid,ifail)

      If (ifail==0 .Or. ifail==1) Then
!       Display titles
        Write (nout,*)                                                         &
          '   TAIL      P        DF1       DF2       F      IVALID'
        Write (nout,*) repeat('-',57)

!       Display results
        Do i = 1, lout
          Write (nout,99999) tail(mod(i-1,ltail)+1), p(mod(i-1,lp)+1),         &
            df1(mod(i-1,ldf1)+1), df2(mod(i-1,ldf2)+1), f(i), ivalid(i)
        End Do
      End If

99999 Format (5X,A1,4X,F6.3,2(4X,F6.2),3X,F7.3,4X,I3)
    End Program g01tdfe


g01tefe.f90

    Program g01tefe
!     G01TEF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: g01tef, nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: tol
      Integer                          :: i, ifail, la, lb, lout, lp, ltail
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: a(:), b(:), beta(:), p(:)
      Integer, Allocatable             :: ivalid(:)
      Character (1), Allocatable       :: tail(:)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: max, mod, repeat
!     .. Executable Statements ..
      Write (nout,*) 'G01TEF Example Program Results'
      Write (nout,*)

!     Skip heading in data file
      Read (nin,*)

!     Read in the tolerance
      Read (nin,*) tol

!     Read in the input vectors
      Read (nin,*) ltail
      Allocate (tail(ltail))
      Read (nin,*) tail(1:ltail)

      Read (nin,*) lp
      Allocate (p(lp))
      Read (nin,*) p(1:lp)

      Read (nin,*) la
      Allocate (a(la))
      Read (nin,*) a(1:la)

      Read (nin,*) lb
      Allocate (b(lb))
      Read (nin,*) b(1:lb)

!     Allocate memory for output
      lout = max(ltail,la,lb,lp)
      Allocate (beta(lout),ivalid(lout))

!     Calculate deviates (inverse CDF)
      ifail = -1
      Call g01tef(ltail,tail,lp,p,la,a,lb,b,tol,beta,ivalid,ifail)

      If (ifail==0 .Or. ifail==1) Then
!       Display titles
        Write (nout,*)                                                         &
          '   TAIL      P        A         B        BETA   IVALID'
        Write (nout,*) repeat('-',55)

!       Display results
        Do i = 1, lout
          Write (nout,99999) tail(mod(i-1,ltail)+1), p(mod(i-1,lp)+1),         &
            a(mod(i-1,la)+1), b(mod(i-1,lb)+1), beta(i), ivalid(i)
        End Do
      End If

99999 Format (5X,A1,4X,F6.3,2(4X,F6.2),3X,F7.3,4X,I3)
    End Program g01tefe


g01tffe.f90

    Program g01tffe
!     G01TFF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: g01tff, nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: tol
      Integer                          :: i, ifail, la, lb, lout, lp, ltail
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: a(:), b(:), g(:), p(:)
      Integer, Allocatable             :: ivalid(:)
      Character (1), Allocatable       :: tail(:)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: max, mod, repeat
!     .. Executable Statements ..
      Write (nout,*) 'G01TFF Example Program Results'
      Write (nout,*)

!     Skip heading in data file
      Read (nin,*)

!     Read in the tolerance
      Read (nin,*) tol

!     Read in the input vectors
      Read (nin,*) ltail
      Allocate (tail(ltail))
      Read (nin,*) tail(1:ltail)

      Read (nin,*) lp
      Allocate (p(lp))
      Read (nin,*) p(1:lp)

      Read (nin,*) la
      Allocate (a(la))
      Read (nin,*) a(1:la)

      Read (nin,*) lb
      Allocate (b(lb))
      Read (nin,*) b(1:lb)

!     Allocate memory for output
      lout = max(ltail,lp,la,lb)
      Allocate (g(lout),ivalid(lout))

!     Calculate deviates (inverse CDF)
      ifail = -1
      Call g01tff(ltail,tail,lp,p,la,a,lb,b,tol,g,ivalid,ifail)

      If (ifail==0 .Or. ifail==1) Then
!       Display titles
        Write (nout,*) '   TAIL    P         A         B         G     IVALID'
        Write (nout,*) repeat('-',55)

!       Display results
        Do i = 1, lout
          Write (nout,99999) tail(mod(i-1,ltail)+1), p(mod(i-1,lp)+1),         &
            a(mod(i-1,la)+1), b(mod(i-1,lb)+1), g(i), ivalid(i)
        End Do
      End If

99999 Format (5X,A,4X,F6.3,2(4X,F6.2),3X,F7.3,4X,I3)
    End Program g01tffe


g01wafe.f90

    Program g01wafe

!     G01WAF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: g01waf, nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Integer                          :: i, ierr, ifail, iwt, lrcomm, lrsd,   &
                                          m, nb, nsummaries, offset, pn
      Logical                          :: want_sd
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: rcomm(:), rmean(:), rsd(:), wt(:),   &
                                          x(:)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: allocated, max, min
!     .. Executable Statements ..
      Write (nout,*) 'G01WAF Example Program Results'
      Write (nout,*)

!     Skip heading in data file
      Read (nin,*)

!     Read in the problem type
      Read (nin,*) iwt, m

!     Read in a flag indicating whether we want the standard deviations
      Read (nin,*) want_sd

!     Initial handling of weights
      Select Case (iwt)
      Case (1)
!       Weights will be read in with the data
      Case (2)
!       Each observation in the rolling window has its own weight
        Allocate (wt(m))
        Read (nin,*) wt(1:m)
      Case Default
!       No weights need supplying
        Allocate (wt(0))
      End Select

      lrcomm = 2*m + 20
      Allocate (rcomm(lrcomm))

!     Print some titles
      If (want_sd) Then
        Write (nout,99997) '                              Standard'
        Write (nout,99997) ' Interval         Mean        Deviation'
        Write (nout,99997) '---------------------------------------'
      Else
        Write (nout,99997) ' Interval         Mean  '
        Write (nout,99997) '------------------------'
      End If

!     Loop over each block of data
      pn = 0
blk_lp: Do
!       Read in the number of observations in this block
        Read (nin,*,Iostat=ierr) nb
        If (ierr/=0) Then
          Exit blk_lp
        End If
!       Reallocate X to the required size
        If (allocated(x)) Then
          Deallocate (x)
        End If
        Allocate (x(nb))

!       Read in the data for this block
        Read (nin,*) x(1:nb)

        If (iwt==1) Then
!         User supplied weights are present

!         Reallocate WT to the required size
          If (allocated(wt)) Then
            Deallocate (wt)
          End If
          Allocate (wt(nb))

!         Read in the weights for this block
          Read (nin,*) wt(1:nb)
        End If

!       Calculate the number of summaries we can produce
        nsummaries = max(0,nb+min(0,pn-m+1))
        If (want_sd) Then
          lrsd = nsummaries
        Else
          lrsd = 0
        End If

!       Reallocate the output arrays
        If (allocated(rmean)) Then
          Deallocate (rmean)
        End If
        Allocate (rmean(nsummaries))

        If (allocated(rsd)) Then
          Deallocate (rsd)
        End If
        Allocate (rsd(lrsd))

!       Calculate summary statistics for this block of data
        ifail = 0
        Call g01waf(m,nb,x,iwt,wt,pn,rmean,rsd,lrsd,rcomm,lrcomm,ifail)

!       Number of results printed so far
        offset = max(0,pn-nb-m+1)

!       Display the results for this block of data
        If (want_sd) Then
          Do i = 1, nsummaries
            Write (nout,99998) '[', i + offset, ',', i + m - 1 + offset, ']',  &
              rmean(i), rsd(i)
          End Do
        Else
          Do i = 1, nsummaries
            Write (nout,99998) '[', i + offset, ',', i + m - 1 + offset, ']',  &
              rmean(i)
          End Do
        End If
      End Do blk_lp

      Write (nout,*)
      Write (nout,99999) 'Total number of observations : ', pn
      Write (nout,99999) 'Length of window             : ', m

99999 Format (1X,A,I5)
99998 Format (1X,A,2(I3,A),2(4X,F10.1))
99997 Format (1X,A)
    End Program g01wafe


g02aafe.f90

    Program g02aafe

!     G02AAF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: g02aaf, nag_wp, x04caf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: errtol, nrmgrd
      Integer                          :: feval, i, ifail, iter, ldg, ldx,     &
                                          maxit, maxits, n
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: g(:,:), x(:,:)
!     .. Executable Statements ..
      Write (nout,*) 'G02AAF Example Program Results'
      Write (nout,*)
      Flush (nout)

!     Skip heading in data file
      Read (nin,*)

!     Read in the problem size
      Read (nin,*) n

      ldg = n
      ldx = n
      Allocate (g(ldg,n),x(ldx,n))

!     Read in the matrix G
      Read (nin,*)(g(i,1:n),i=1,n)

!     Use the defaults for ERRTOL, MAXITS and MAXIT
      errtol = 0.0E0_nag_wp
      maxits = 0
      maxit = 0

!     Calculate nearest correlation matrix
      ifail = 0
      Call g02aaf(g,ldg,n,errtol,maxits,maxit,x,ldx,iter,feval,nrmgrd,ifail)

!     Display results
      ifail = 0
      Call x04caf('General',' ',n,n,x,ldx,'Nearest Correlation Matrix',ifail)
      Write (nout,*)
      Write (nout,99999) ' Number of Newton steps taken:', iter
      Write (nout,99998) ' Number of function evaluations:', feval

99999 Format (1X,A,I11)
99998 Format (1X,A,I9)
    End Program g02aafe


g02abfe.f90

    Program g02abfe

!     G02ABF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: dsyev, g02abf, nag_wp, x04caf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: alpha, errtol, nrmgrd
      Integer                          :: feval, i, ifail, iter, ldg, ldx,     &
                                          lwork, maxit, maxits, n
      Character (1)                    :: opt
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: eig(:), g(:,:), w(:), work(:),       &
                                          x(:,:)
!     .. Executable Statements ..
      Write (nout,*) 'G02ABF Example Program Results'
      Write (nout,*)
      Flush (nout)

!     Skip heading in data file
      Read (nin,*)

!     Read in the problem size, opt and alpha
      Read (nin,*) n, opt, alpha

      ldg = n
      ldx = n
      lwork = 66*n
      Allocate (g(ldg,n),w(n),x(ldx,n),eig(n),work(lwork))

!     Read in the matrix G
      Read (nin,*)(g(i,1:n),i=1,n)

!     Read in the vector W
      Read (nin,*) w(1:n)

!     Use the defaults for ERRTOL, MAXITS and MAXIT
      errtol = 0.0E0_nag_wp
      maxits = 0
      maxit = 0

!     Calculate nearest correlation matrix
      ifail = 0

      Call g02abf(g,ldg,n,opt,alpha,w,errtol,maxits,maxit,x,ldx,iter,feval,    &
        nrmgrd,ifail)

!     Display results
      ifail = 0
      Call x04caf('General',' ',n,n,x,ldx,'Nearest Correlation Matrix X',      &
        ifail)
      Write (nout,*)
      Write (nout,99999) 'Number of Newton steps taken:', iter
      Write (nout,99998) 'Number of function evaluations:', feval

      Write (nout,*)
      Write (nout,99997) 'ALPHA: ', alpha

      ifail = 0
!     The NAG name equivalent of dsyev is f08faf
      Call dsyev('N','U',n,x,ldx,eig,work,lwork,ifail)
      Write (nout,*)
      Flush (nout)
      Call x04caf('General',' ',1,n,eig,1,'Eigenvalues of X',ifail)

99999 Format (1X,A,I11)
99998 Format (1X,A,I9)
99997 Format (1X,A,F37.3)

    End Program g02abfe


g02aefe.f90

    Program g02aefe

!     G02AEF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: dgemm, g02aef, nag_wp, x04caf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Real (Kind=nag_wp), Parameter    :: one = 1.0_nag_wp
      Real (Kind=nag_wp), Parameter    :: zero = 0.0_nag_wp
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: errtol, nrmpgd
      Integer                          :: feval, i, ifail, iter, k, lda, ldg,  &
                                          ldx, maxit, n
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: a(:,:), g(:,:), x(:,:)
!     .. Executable Statements ..
      Write (nout,*) 'G02AEF Example Program Results'
      Write (nout,*)
      Flush (nout)

!     Skip heading in data file
      Read (nin,*)

!     Read in the problem size
      Read (nin,*) n

      lda = n
      ldg = n
      ldx = n
      Allocate (a(lda,n),g(ldg,n),x(ldx,n))

!     Read in the matrix G
      Read (nin,*)(g(i,1:n),i=1,n)

!     Use the defaults for ERRTOL and MAXIT
      errtol = zero
      maxit = 0

!     Set k value
      k = 2

!     Calculate the nearest factor loading matrix
      ifail = 0

      Call g02aef(g,ldg,n,k,errtol,maxit,x,ldx,iter,feval,nrmpgd,ifail)

!     Display results
      ifail = 0
      Call x04caf('General',' ',n,k,x,ldx,'Factor Loading Matrix X',ifail)
      Write (nout,*)
      Write (nout,99999) 'Number of steps taken:', iter
      Write (nout,99998) 'Number of function evaluations:', feval

!     Generate Nearest k factor correlation matrix
!     The NAG name equivalent of dgemm is f06yaf
      Call dgemm('N','T',n,n,k,one,x,n,x,n,zero,a,n)
      Do i = 1, n
        a(i,i) = one
      End Do
      Write (nout,*)
      Flush (nout)
      ifail = 0
      Call x04caf('General',' ',n,n,a,lda,'Nearest Correlation Matrix',ifail)

99999 Format (1X,A,I11)
99998 Format (1X,A,I9)

    End Program g02aefe


g02ajfe.f90

    Program g02ajfe

!     G02AJF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: dsyev, g02ajf, nag_wp, x04caf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: alpha, errtol, norm
      Integer                          :: i, ifail, iter, ldg, ldh, ldx,       &
                                          lwork, maxit, n
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: eig(:), g(:,:), h(:,:), work(:),     &
                                          x(:,:)
!     .. Executable Statements ..
      Write (nout,*) 'G02AJF Example Program Results'
      Write (nout,*)
      Flush (nout)

!     Skip heading in data file
      Read (nin,*)

!     Read in the problem size and alpha
      Read (nin,*) n, alpha

      ldg = n
      ldh = n
      ldx = n
      lwork = 66*n
      Allocate (g(ldg,n),h(ldh,n),x(ldx,n),eig(n),work(lwork))

!     Read in the matrix G
      Read (nin,*)(g(i,1:n),i=1,n)

!     Read in the matrix H
      Read (nin,*)(h(i,1:n),i=1,n)

!     Use the defaults for ERRTOL and MAXIT
      errtol = 0.0E0_nag_wp
      maxit = 0

!     Calculate nearest correlation matrix
      ifail = 0

      Call g02ajf(g,ldg,n,alpha,h,ldh,errtol,maxit,x,ldx,iter,norm,ifail)

!     Display results
      ifail = 0
      Call x04caf('General',' ',n,n,h,ldh,'Returned H Matrix',ifail)
      Write (nout,*)

      ifail = 0
      Call x04caf('General',' ',n,n,x,ldx,'Nearest Correlation Matrix X',      &
        ifail)
      Write (nout,*)

      Write (nout,99999) 'Number of iterations:', iter
      Write (nout,*)
      Write (nout,99998) 'Norm value:', norm
      Write (nout,*)
      Write (nout,99997) 'ALPHA: ', alpha

      ifail = 0
!     The NAG name equivalent of dsyev is f08faf
      Call dsyev('N','U',n,x,ldx,eig,work,lwork,ifail)
      Write (nout,*)
      Flush (nout)
      Call x04caf('General',' ',1,n,eig,1,'Eigenvalues of X',ifail)

99999 Format (1X,A,I11)
99998 Format (1X,A,F26.4)
99997 Format (1X,A,F30.4)

    End Program g02ajfe


g02anfe.f90

    Program g02anfe

!     G02ANF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: g02anf, nag_wp, x04caf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: alpha, eigmin, eigtol, errtol, norm
      Integer                          :: i, ifail, iter, k, ldg, ldx, n
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: g(:,:), x(:,:)
!     .. Executable Statements ..
      Write (nout,*) 'G02ANF Example Program Results'
      Write (nout,*)
      Flush (nout)

!     Skip heading in data file
      Read (nin,*)

!     Read in the problem sizes
      Read (nin,*) n, k

      ldg = n
      ldx = n
      Allocate (g(ldg,n),x(ldx,n))

!     Read in the matrix G
      Read (nin,*)(g(i,1:n),i=1,n)

!     Use the defaults for EIGTOL and ERRTOL
      eigtol = -1.E0_nag_wp
      errtol = -1.E0_nag_wp

!     Calculate nearest correlation matrix
      ifail = 0

      Call g02anf(g,ldg,n,k,errtol,eigtol,x,ldx,alpha,iter,eigmin,norm,ifail)

      ifail = 0
!     Display the symmetrised input matrix
      Call x04caf('General',' ',n,n,g,ldg,'Symmetrised Input Matrix G',ifail)
      Write (nout,*)

!     Display results
      ifail = 0
      Call x04caf('General',' ',n,n,x,ldx,                                     &
        'Nearest Perturbed Correlation Matrix X',ifail)
      Write (nout,*)
      Write (nout,99999) 'K:                         ', k
      Write (nout,*)
      Write (nout,99999) 'Number of iterations taken:', iter
      Write (nout,*)
      Write (nout,99998) 'ALPHA:                   ', alpha
      Write (nout,*)
      Write (nout,99998) 'Norm value:              ', norm
      Write (nout,*)
      Write (nout,99998) 'Smallest eigenvalue of A:', eigmin

99999 Format (1X,A,I9)
99998 Format (1X,A,F16.4)

    End Program g02anfe


g02apfe.f90

    Program g02apfe

!     G02APF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: dsyev, g02apf, nag_wp, x04caf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: alpha, eigmin, eigtol, errtol, norm, &
                                          theta
      Integer                          :: i, ifail, iter, ldg, ldh, ldx,       &
                                          lwork, n
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: eig(:), g(:,:), h(:,:), work(:),     &
                                          x(:,:)
!     .. Executable Statements ..
      Write (nout,*) 'G02APF Example Program Results'
      Write (nout,*)
      Flush (nout)

!     Skip heading in data file
      Read (nin,*)

!     Read in the problem size and theta
      Read (nin,*) n, theta

      ldg = n
      ldh = n
      ldx = n
      lwork = 66*n
      Allocate (g(ldg,n),h(ldh,n),x(ldx,n),eig(n),work(lwork))

!     Read in the matrix G
      Read (nin,*)(g(i,1:n),i=1,n)

!     Read in the matrix H
      Read (nin,*)(h(i,1:n),i=1,n)

!     Use the defaults for EIGTOL and ERRTOL
      eigtol = -1.E0_nag_wp
      errtol = -1.E0_nag_wp

!     Calculate nearest correlation matrix using target matrix
      ifail = 0

      Call g02apf(g,ldg,n,theta,h,ldh,errtol,eigtol,x,ldx,alpha,iter,eigmin,   &
        norm,ifail)

      ifail = 0
!     Display the symmetrised input matrix
      Call x04caf('General',' ',n,n,g,ldg,'Symmetrised Input Matrix G',ifail)
      Write (nout,*)

!     Display results
      ifail = 0
      Call x04caf('General',' ',n,n,x,ldx,'Nearest Correlation Matrix X',      &
        ifail)
      Write (nout,*)
      Write (nout,99999) 'Number of iterations taken:', iter
      Write (nout,*)
      Write (nout,99998) 'ALPHA:                        ', alpha
      Write (nout,*)
      Write (nout,99998) 'Norm value:                   ', norm
      Write (nout,*)
      Write (nout,99998) 'THETA:                        ', theta
      Write (nout,*)
      Write (nout,99998) 'Smallest eigenvalue of target:', eigmin

      ifail = 0
!     Compute the eigenvalues of X
      Call dsyev('N','U',n,x,ldx,eig,work,lwork,ifail)
      Write (nout,*)
      Flush (nout)
      Call x04caf('General',' ',1,n,eig,1,'Eigenvalues of X',ifail)

99999 Format (1X,A,I9)
99998 Format (1X,A,F11.4)

    End Program g02apfe


g02bafe.f90

    Program g02bafe

!     G02BAF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: g02baf, nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Integer                          :: i, ifail, ldr, ldssp, ldx, m, n
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: r(:,:), ssp(:,:), std(:), x(:,:),    &
                                          xbar(:)
!     .. Executable Statements ..
      Write (nout,*) 'G02BAF Example Program Results'
      Write (nout,*)

!     Skip heading in data file
      Read (nin,*)

!     Read in the problem size
      Read (nin,*) n, m

      ldr = m
      ldssp = m
      ldx = n
      Allocate (x(ldx,m),r(ldr,m),ssp(ldssp,m),std(m),xbar(m))

!     Read in data
      Read (nin,*)(x(i,1:m),i=1,n)

!     Display data
      Write (nout,99999) 'Number of variables (columns) = ', m
      Write (nout,99999) 'Number of cases     (rows)    = ', n
      Write (nout,*)
      Write (nout,*) 'Data matrix is:-'
      Write (nout,*)
      Write (nout,99998)(i,i=1,m)
      Write (nout,99997)(i,x(i,1:m),i=1,n)
      Write (nout,*)

!     Compute summary statistics
      ifail = 0
      Call g02baf(n,m,x,ldx,xbar,std,ssp,ldssp,r,ldr,ifail)

!     Display results
      Write (nout,*) 'Variable   Mean    St. dev.'
      Write (nout,99996)(i,xbar(i),std(i),i=1,m)
      Write (nout,*)
      Write (nout,*) 'Sums of squares and cross-products of deviations'
      Write (nout,99998)(i,i=1,m)
      Write (nout,99997)(i,ssp(i,1:m),i=1,m)
      Write (nout,*)
      Write (nout,*) 'Correlation coefficients'
      Write (nout,99998)(i,i=1,m)
      Write (nout,99997)(i,r(i,1:m),i=1,m)

99999 Format (1X,A,I0)
99998 Format (1X,6I12)
99997 Format (1X,I3,3F12.4)
99996 Format (1X,I5,2F11.4)
    End Program g02bafe


g02bbfe.f90

    Program g02bbfe

!     G02BBF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: g02bbf, nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Integer                          :: i, ifail, ldr, ldssp, ldx, m, n,     &
                                          ncases
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: r(:,:), ssp(:,:), std(:), x(:,:),    &
                                          xbar(:), xmiss(:)
      Integer, Allocatable             :: miss(:)
!     .. Executable Statements ..
      Write (nout,*) 'G02BBF Example Program Results'
      Write (nout,*)

!     Skip heading in data file
      Read (nin,*)

!     Read in the problem size
      Read (nin,*) n, m

      ldr = m
      ldssp = m
      ldx = n
      Allocate (x(ldx,m),r(ldr,m),ssp(ldssp,m),std(m),xbar(m),xmiss(m),        &
        miss(m))

!     Read in data
      Read (nin,*)(x(i,1:m),i=1,n)

!     Read in missing value flags
      Read (nin,*) miss(1:m)
      Read (nin,*) xmiss(1:m)

!     Display data
      Write (nout,99999) 'Number of variables (columns) =', m
      Write (nout,99999) 'Number of cases     (rows)    =', n
      Write (nout,*)
      Write (nout,*) 'Data matrix is:-'
      Write (nout,*)
      Write (nout,99998)(i,i=1,m)
      Write (nout,99997)(i,x(i,1:m),i=1,n)
      Write (nout,*)

!     Calculate summary statistics
      ifail = 0
      Call g02bbf(n,m,x,ldx,miss,xmiss,xbar,std,ssp,ldssp,r,ldr,ncases,ifail)

!     Display results
      Write (nout,*) 'Variable   Mean    St. dev.'
      Write (nout,99996)(i,xbar(i),std(i),i=1,m)
      Write (nout,*)
      Write (nout,*) 'Sums of squares and cross-products of deviations'
      Write (nout,99998)(i,i=1,m)
      Write (nout,99997)(i,ssp(i,1:m),i=1,m)
      Write (nout,*)
      Write (nout,*) 'Correlation coefficients'
      Write (nout,99998)(i,i=1,m)
      Write (nout,99997)(i,r(i,1:m),i=1,m)
      Write (nout,*)
      Write (nout,99999) 'Number of cases actually used: ', ncases

99999 Format (1X,A,I5)
99998 Format (1X,6I12)
99997 Format (1X,I3,3F12.4)
99996 Format (1X,I5,2F11.4)
    End Program g02bbfe


g02bcfe.f90

    Program g02bcfe

!     G02BCF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: g02bcf, nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Integer                          :: i, ifail, ldcnt, ldr, ldssp, ldx, m, &
                                          n, ncases
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: cnt(:,:), r(:,:), ssp(:,:), std(:),  &
                                          x(:,:), xbar(:), xmiss(:)
      Integer, Allocatable             :: miss(:)
!     .. Executable Statements ..
      Write (nout,*) 'G02BCF Example Program Results'
      Write (nout,*)

!     Skip heading in data file
      Read (nin,*)

!     Read in the problem size
      Read (nin,*) n, m

      ldcnt = m
      ldr = m
      ldssp = m
      ldx = n
      Allocate (cnt(ldcnt,m),r(ldr,m),ssp(ldssp,m),std(m),x(ldx,m),xbar(m),    &
        xmiss(m),miss(m))

!     Read in data
      Read (nin,*)(x(i,1:m),i=1,n)

!     Read in missing value flags
      Read (nin,*) miss(1:m)
      Read (nin,*) xmiss(1:m)

!     Display data
      Write (nout,99999) 'Number of variables (columns) =', m
      Write (nout,99999) 'Number of cases     (rows)    =', n
      Write (nout,*)
      Write (nout,*) 'Data matrix is:-'
      Write (nout,*)
      Write (nout,99998)(i,i=1,m)
      Write (nout,99997)(i,x(i,1:m),i=1,n)
      Write (nout,*)

!     Calculate summary statistics
      ifail = 0
      Call g02bcf(n,m,x,ldx,miss,xmiss,xbar,std,ssp,ldssp,r,ldr,ncases,cnt,    &
        ldcnt,ifail)

!     Display results
      Write (nout,*) 'Variable   Mean    St. dev.'
      Write (nout,99996)(i,xbar(i),std(i),i=1,m)
      Write (nout,*)
      Write (nout,*) 'Sums of squares and cross-products of deviations'
      Write (nout,99998)(i,i=1,m)
      Write (nout,99997)(i,ssp(i,1:m),i=1,m)
      Write (nout,*)
      Write (nout,*) 'Correlation coefficients'
      Write (nout,99998)(i,i=1,m)
      Write (nout,99997)(i,r(i,1:m),i=1,m)
      Write (nout,*)
      Write (nout,99999)                                                       &
        'Minimum number of cases used for any pair of variables: ', ncases
      Write (nout,*)
      Write (nout,*) 'Numbers used for each pair are:'
      Write (nout,99998)(i,i=1,m)
      Write (nout,99997)(i,cnt(i,1:m),i=1,m)

99999 Format (1X,A,I2)
99998 Format (1X,6I12)
99997 Format (1X,I3,3F12.4)
99996 Format (1X,I5,2F11.4)
    End Program g02bcfe


g02bdfe.f90

    Program g02bdfe

!     G02BDF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: g02bdf, nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Integer                          :: i, ifail, ldrz, ldsspz, ldx, m, n
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: rz(:,:), sspz(:,:), std(:), x(:,:),  &
                                          xbar(:)
!     .. Executable Statements ..
      Write (nout,*) 'G02BDF Example Program Results'
      Write (nout,*)

!     Skip heading in data file
      Read (nin,*)

!     Read in the problem size
      Read (nin,*) n, m

      ldrz = m
      ldsspz = m
      ldx = n
      Allocate (rz(ldrz,m),sspz(ldsspz,m),std(m),x(ldx,m),xbar(m))

!     Read in data
      Read (nin,*)(x(i,1:m),i=1,n)

!     Display data
      Write (nout,99999) 'Number of variables (columns) =', m
      Write (nout,99999) 'Number of cases     (rows)    =', n
      Write (nout,*)
      Write (nout,*) 'Data matrix is:-'
      Write (nout,*)
      Write (nout,99998)(i,i=1,m)
      Write (nout,99997)(i,x(i,1:m),i=1,n)
      Write (nout,*)

!     Compute summary statistics
      ifail = 0
      Call g02bdf(n,m,x,ldx,xbar,std,sspz,ldsspz,rz,ldrz,ifail)

!     Display results
      Write (nout,*) 'Variable   Mean    St. dev.'
      Write (nout,99996)(i,xbar(i),std(i),i=1,m)
      Write (nout,*)
      Write (nout,*) 'Sums of squares and cross-products about' // ' zero'
      Write (nout,99998)(i,i=1,m)
      Write (nout,99997)(i,sspz(i,1:m),i=1,m)
      Write (nout,*)
      Write (nout,*) 'Correlation-like coefficients'
      Write (nout,99998)(i,i=1,m)
      Write (nout,99997)(i,rz(i,1:m),i=1,m)

99999 Format (1X,A,I5)
99998 Format (1X,6I12)
99997 Format (1X,I3,3F12.4)
99996 Format (1X,I5,2F11.4)
    End Program g02bdfe


g02befe.f90

    Program g02befe

!     G02BEF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: g02bef, nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Integer                          :: i, ifail, ldrz, ldsspz, ldx, m, n,   &
                                          ncases
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: rz(:,:), sspz(:,:), std(:), x(:,:),  &
                                          xbar(:), xmiss(:)
      Integer, Allocatable             :: miss(:)
!     .. Executable Statements ..
      Write (nout,*) 'G02BEF Example Program Results'
      Write (nout,*)

!     Skip heading in data file
      Read (nin,*)

!     Read in the problem size
      Read (nin,*) n, m

      ldrz = m
      ldsspz = m
      ldx = n
      Allocate (rz(ldrz,m),sspz(ldsspz,m),std(m),x(ldx,m),xbar(m),xmiss(m),    &
        miss(m))

!     Read in data
      Read (nin,*)(x(i,1:m),i=1,n)

!     Read in missing value flags
      Read (nin,*) miss(1:m)
      Read (nin,*) xmiss(1:m)

!     Display data
      Write (nout,99999) 'Number of variables (columns) =', m
      Write (nout,99999) 'Number of cases     (rows)    =', n
      Write (nout,*)
      Write (nout,*) 'Data matrix is:-'
      Write (nout,*)
      Write (nout,99998)(i,i=1,m)
      Write (nout,99997)(i,x(i,1:m),i=1,n)
      Write (nout,*)

!     Calculate summary statistics
      ifail = 0
      Call g02bef(n,m,x,ldx,miss,xmiss,xbar,std,sspz,ldsspz,rz,ldrz,ncases,    &
        ifail)

!     Display results
      Write (nout,*) 'Variable   Mean    St. dev.'
      Write (nout,99996)(i,xbar(i),std(i),i=1,m)
      Write (nout,*)
      Write (nout,*) 'Sums of squares and cross-products about' // ' zero'
      Write (nout,99998)(i,i=1,m)
      Write (nout,99997)(i,sspz(i,1:m),i=1,m)
      Write (nout,*)
      Write (nout,*) 'Correlation-like coefficients'
      Write (nout,99998)(i,i=1,m)
      Write (nout,99997)(i,rz(i,1:m),i=1,m)
      Write (nout,*)
      Write (nout,99999) 'Number of cases actually used: ', ncases

99999 Format (1X,A,I5)
99998 Format (1X,6I12)
99997 Format (1X,I3,3F12.4)
99996 Format (1X,I5,2F11.4)
    End Program g02befe


g02bffe.f90

    Program g02bffe

!     G02BFF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: g02bff, nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Integer                          :: i, ifail, ldcnt, ldrz, ldsspz, ldx,  &
                                          m, n, ncases
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: cnt(:,:), rz(:,:), sspz(:,:),        &
                                          std(:), x(:,:), xbar(:), xmiss(:)
      Integer, Allocatable             :: miss(:)
!     .. Executable Statements ..
      Write (nout,*) 'G02BFF Example Program Results'
      Write (nout,*)

!     Skip heading in data file
      Read (nin,*)

!     Read in the problem size
      Read (nin,*) n, m

      ldcnt = m
      ldrz = m
      ldsspz = m
      ldx = n
      Allocate (cnt(ldcnt,m),rz(ldrz,m),sspz(ldsspz,m),std(m),x(ldx,m),        &
        xbar(m),xmiss(m),miss(m))

!     Read in data
      Read (nin,*)(x(i,1:m),i=1,n)

!     Read in missing value flags
      Read (nin,*) miss(1:m)
      Read (nin,*) xmiss(1:m)

!     Display data
      Write (nout,99999) 'Number of variables (columns) =', m
      Write (nout,99999) 'Number of cases     (rows)    =', n
      Write (nout,*)
      Write (nout,*) 'Data matrix is:-'
      Write (nout,*)
      Write (nout,99998)(i,i=1,m)
      Write (nout,99997)(i,x(i,1:m),i=1,n)
      Write (nout,*)

!     Calculate summary statistics
      ifail = 0
      Call g02bff(n,m,x,ldx,miss,xmiss,xbar,std,sspz,ldsspz,rz,ldrz,ncases,    &
        cnt,ldcnt,ifail)

!     Display results
      Write (nout,*) 'Variable   Mean    St. dev.'
      Write (nout,99996)(i,xbar(i),std(i),i=1,m)
      Write (nout,*)
      Write (nout,*) 'Sums of squares and cross-products about' // ' zero'
      Write (nout,99998)(i,i=1,m)
      Write (nout,99997)(i,sspz(i,1:m),i=1,m)
      Write (nout,*)
      Write (nout,*) 'Correlation-like coefficients'
      Write (nout,99998)(i,i=1,m)
      Write (nout,99997)(i,rz(i,1:m),i=1,m)
      Write (nout,*)
      Write (nout,99999)                                                       &
        'Minimum number of cases used for any pair of variables: ', ncases
      Write (nout,*)
      Write (nout,*) 'Numbers used for each pair are:'
      Write (nout,99998)(i,i=1,m)
      Write (nout,99997)(i,cnt(i,1:m),i=1,m)

99999 Format (1X,A,I5)
99998 Format (1X,6I12)
99997 Format (1X,I3,3F12.4)
99996 Format (1X,I5,2F11.4)
    End Program g02bffe


g02bgfe.f90

    Program g02bgfe

!     G02BGF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: g02bgf, nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Integer                          :: i, ifail, ldr, ldssp, ldx, m, n,     &
                                          nvars
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: r(:,:), ssp(:,:), std(:), x(:,:),    &
                                          xbar(:)
      Integer, Allocatable             :: kvar(:)
!     .. Executable Statements ..
      Write (nout,*) 'G02BGF Example Program Results'
      Write (nout,*)

!     Skip heading in data file
      Read (nin,*)

!     Read in the problem size
      Read (nin,*) n, m, nvars

      ldr = nvars
      ldssp = nvars
      ldx = n
      Allocate (r(ldr,nvars),ssp(ldssp,nvars),std(nvars),x(ldx,m),xbar(nvars), &
        kvar(nvars))

!     Read in data
      Read (nin,*)(x(i,1:m),i=1,n)

!     Read in column IDs
      Read (nin,*) kvar(1:nvars)

!     Display data
      Write (nout,99999) 'Number of variables (columns) =', m
      Write (nout,99999) 'Number of cases     (rows)    =', n
      Write (nout,*)
      Write (nout,*) 'Data matrix is:-'
      Write (nout,*)
      Write (nout,99998)(i,i=1,m)
      Write (nout,99997)(i,x(i,1:m),i=1,n)
      Write (nout,*)

!     Calculate summary statistics
      ifail = 0
      Call g02bgf(n,m,x,ldx,nvars,kvar,xbar,std,ssp,ldssp,r,ldr,ifail)

!     Display results
      Write (nout,*) 'Variable   Mean    St. dev.'
      Write (nout,99995)(kvar(i),xbar(i),std(i),i=1,nvars)
      Write (nout,*)
      Write (nout,*) 'Sums of squares and cross-products of deviations'
      Write (nout,99998) kvar(1:nvars)
      Write (nout,99996)(kvar(i),ssp(i,1:nvars),i=1,nvars)
      Write (nout,*)
      Write (nout,*) 'Correlation coefficients'
      Write (nout,99998) kvar(1:nvars)
      Write (nout,99996)(kvar(i),r(i,1:nvars),i=1,nvars)

99999 Format (1X,A,I5)
99998 Format (1X,6I12)
99997 Format (1X,I3,4F12.4)
99996 Format (1X,I3,3F12.4)
99995 Format (1X,I5,2F11.4)
    End Program g02bgfe


g02bhfe.f90

    Program g02bhfe

!     G02BHF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: g02bhf, nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Integer                          :: i, ifail, ldr, ldssp, ldx, m,        &
                                          mistyp, n, ncases, nvars
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: r(:,:), ssp(:,:), std(:), x(:,:),    &
                                          xbar(:), xmiss(:)
      Integer, Allocatable             :: kvar(:), miss(:)
!     .. Executable Statements ..
      Write (nout,*) 'G02BHF Example Program Results'
      Write (nout,*)

!     Skip heading in data file
      Read (nin,*)

!     Read in the problem size
      Read (nin,*) n, m, nvars, mistyp

      ldr = nvars
      ldssp = nvars
      ldx = n
      Allocate (r(ldr,nvars),ssp(ldssp,nvars),std(nvars),x(ldx,m),xbar(nvars), &
        xmiss(m),kvar(nvars),miss(m))

!     Read in data
      Read (nin,*)(x(i,1:m),i=1,n)

!     Read in missing value flags
      Read (nin,*) miss(1:m)
      Read (nin,*) xmiss(1:m)

!     Read in column IDs
      Read (nin,*) kvar(1:nvars)

!     Display data
      Write (nout,99999) 'Number of variables (columns) =', m
      Write (nout,99999) 'Number of cases     (rows)    =', n
      Write (nout,*)
      Write (nout,*) 'Data matrix is:-'
      Write (nout,99998)(i,i=1,m)
      Write (nout,99997)(i,x(i,1:m),i=1,n)
      Write (nout,*)

!     Calculate summary statistics
      ifail = 0
      Call g02bhf(n,m,x,ldx,miss,xmiss,mistyp,nvars,kvar,xbar,std,ssp,ldssp,r, &
        ldr,ncases,ifail)

!     Display results
      Write (nout,*) 'Variable   Mean    St. dev.'
      Write (nout,99995)(kvar(i),xbar(i),std(i),i=1,nvars)
      Write (nout,*)
      Write (nout,*) 'Sums of squares and cross-products of deviations'
      Write (nout,99998) kvar(1:nvars)
      Write (nout,99996)(kvar(i),ssp(i,1:nvars),i=1,nvars)
      Write (nout,*)
      Write (nout,*) 'Correlation coefficients'
      Write (nout,99998) kvar(1:nvars)
      Write (nout,99996)(kvar(i),r(i,1:nvars),i=1,nvars)
      Write (nout,*)
      Write (nout,99999) 'Number of cases actually used:', ncases

99999 Format (1X,A,I5)
99998 Format (1X,4I12)
99997 Format (1X,I3,4F12.4)
99996 Format (1X,I3,3F12.4)
99995 Format (1X,I5,2F11.4)
    End Program g02bhfe


g02bjfe.f90

    Program g02bjfe

!     G02BJF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: g02bjf, nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Integer                          :: i, ifail, ldcnt, ldr, ldssp, ldx, m, &
                                          n, ncases, nvars
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: cnt(:,:), r(:,:), ssp(:,:), std(:),  &
                                          x(:,:), xbar(:), xmiss(:)
      Integer, Allocatable             :: kvar(:), miss(:)
!     .. Executable Statements ..
      Write (nout,*) 'G02BJF Example Program Results'
      Write (nout,*)

!     Skip heading in data file
      Read (nin,*)

!     Read in the problem size
      Read (nin,*) n, m, nvars

      ldcnt = nvars
      ldr = nvars
      ldssp = nvars
      ldx = n
      Allocate (cnt(ldcnt,nvars),r(ldr,nvars),ssp(ldssp,nvars),std(nvars),     &
        x(ldx,m),xbar(nvars),xmiss(m),kvar(nvars),miss(m))

!     Read in data
      Read (nin,*)(x(i,1:m),i=1,n)

!     Read in missing value flags
      Read (nin,*) miss(1:m)
      Read (nin,*) xmiss(1:m)

!     Read in column IDs
      Read (nin,*) kvar(1:nvars)

!     Display data
      Write (nout,99999) 'Number of variables (columns) =', m
      Write (nout,99999) 'Number of cases     (rows)    =', n
      Write (nout,*)
      Write (nout,*) 'Data matrix is:-'
      Write (nout,99998)(i,i=1,m)
      Write (nout,99997)(i,x(i,1:m),i=1,n)
      Write (nout,*)

!     Calculate summary statistics
      ifail = 0
      Call g02bjf(n,m,x,ldx,miss,xmiss,nvars,kvar,xbar,std,ssp,ldssp,r,ldr,    &
        ncases,cnt,ldcnt,ifail)

!     Display results
      Write (nout,*) 'Variable   Mean    St. dev.'
      Write (nout,99995)(kvar(i),xbar(i),std(i),i=1,nvars)
      Write (nout,*)
      Write (nout,*) 'Sums of squares and cross-products of deviations'
      Write (nout,99998) kvar(1:nvars)
      Write (nout,99996)(kvar(i),ssp(i,1:nvars),i=1,nvars)
      Write (nout,*)
      Write (nout,*) 'Correlation coefficients'
      Write (nout,99998) kvar(1:nvars)
      Write (nout,99996)(kvar(i),r(i,1:nvars),i=1,nvars)
      Write (nout,*)
      Write (nout,99999)                                                       &
        'Minimum number of cases used for any pair of variables:', ncases
      Write (nout,*)
      Write (nout,*) 'Numbers used for each pair are:'
      Write (nout,99998) kvar(1:nvars)
      Write (nout,99996)(kvar(i),cnt(i,1:nvars),i=1,nvars)

99999 Format (1X,A,I5)
99998 Format (1X,4I12)
99997 Format (1X,I3,4F12.4)
99996 Format (1X,I3,3F12.4)
99995 Format (1X,I5,2F11.4)
    End Program g02bjfe


g02bkfe.f90

    Program g02bkfe

!     G02BKF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: g02bkf, nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Integer                          :: i, ifail, ldrz, ldsspz, ldx, m, n,   &
                                          nvars
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: rz(:,:), sspz(:,:), std(:), x(:,:),  &
                                          xbar(:)
      Integer, Allocatable             :: kvar(:)
!     .. Executable Statements ..
      Write (nout,*) 'G02BKF Example Program Results'
      Write (nout,*)

!     Skip heading in data file
      Read (nin,*)

!     Read in the problem size
      Read (nin,*) n, m, nvars

      ldrz = nvars
      ldsspz = nvars
      ldx = n
      Allocate (rz(ldrz,nvars),sspz(ldsspz,nvars),std(nvars),x(ldx,m),         &
        xbar(nvars),kvar(nvars))

!     Read in data
      Read (nin,*)(x(i,1:m),i=1,n)

!     Read in column IDs
      Read (nin,*) kvar(1:nvars)

!     Display data
      Write (nout,99999) 'Number of variables (columns) =', m
      Write (nout,99999) 'Number of cases     (rows)    =', n
      Write (nout,*)
      Write (nout,*) 'Data matrix is:-'
      Write (nout,*)
      Write (nout,99998)(i,i=1,m)
      Write (nout,99997)(i,x(i,1:m),i=1,n)
      Write (nout,*)

!     Calculate summary statistics
      ifail = 0
      Call g02bkf(n,m,x,ldx,nvars,kvar,xbar,std,sspz,ldsspz,rz,ldrz,ifail)

!     Display results
      Write (nout,*) 'Variable   Mean    St. dev.'
      Write (nout,99995)(kvar(i),xbar(i),std(i),i=1,nvars)
      Write (nout,*)
      Write (nout,*) 'Sums of squares and cross-products about' // ' zero'
      Write (nout,99998) kvar(1:nvars)
      Write (nout,99996)(kvar(i),sspz(i,1:nvars),i=1,nvars)
      Write (nout,*)
      Write (nout,*) 'Correlation-like coefficients'
      Write (nout,99998) kvar(1:nvars)
      Write (nout,99996)(kvar(i),rz(i,1:nvars),i=1,nvars)

99999 Format (1X,A,I5)
99998 Format (1X,4I12)
99997 Format (1X,I3,4F12.4)
99996 Format (1X,I3,3F12.4)
99995 Format (1X,I5,2F11.4)
    End Program g02bkfe


g02blfe.f90

    Program g02blfe

!     G02BLF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: g02blf, nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Integer                          :: i, ifail, ldrz, ldsspz, ldx, m,      &
                                          mistyp, n, ncases, nvars
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: rz(:,:), sspz(:,:), std(:), x(:,:),  &
                                          xbar(:), xmiss(:)
      Integer, Allocatable             :: kvar(:), miss(:)
!     .. Executable Statements ..
      Write (nout,*) 'G02BLF Example Program Results'
      Write (nout,*)

!     Skip heading in data file
      Read (nin,*)

!     Read in the problem size
      Read (nin,*) n, m, nvars, mistyp

      ldrz = nvars
      ldsspz = nvars
      ldx = n
      Allocate (rz(ldrz,nvars),sspz(ldsspz,nvars),std(nvars),x(ldx,m),         &
        xbar(nvars),xmiss(m),kvar(nvars),miss(m))

!     Read in data
      Read (nin,*)(x(i,1:m),i=1,n)

!     Read in missing value flags
      Read (nin,*) miss(1:m)
      Read (nin,*) xmiss(1:m)

!     Read in column IDs
      Read (nin,*) kvar(1:nvars)

!     Display data
      Write (nout,99999) 'Number of variables (columns) =', m
      Write (nout,99999) 'Number of cases     (rows)    =', n
      Write (nout,*)
      Write (nout,*) 'Data matrix is:-'
      Write (nout,*)
      Write (nout,99998)(i,i=1,m)
      Write (nout,99997)(i,x(i,1:m),i=1,n)
      Write (nout,*)

!     Calculate summary statistics
      ifail = 0
      Call g02blf(n,m,x,ldx,miss,xmiss,mistyp,nvars,kvar,xbar,std,sspz,ldsspz, &
        rz,ldrz,ncases,ifail)

!     Display results
      Write (nout,*) 'Variable   Mean    St. dev.'
      Write (nout,99995)(kvar(i),xbar(i),std(i),i=1,nvars)
      Write (nout,*)
      Write (nout,*) 'Sums of squares and cross-products about' // ' zero'
      Write (nout,99998) kvar(1:nvars)
      Write (nout,99996)(kvar(i),sspz(i,1:nvars),i=1,nvars)
      Write (nout,*)
      Write (nout,*) 'Correlation-like coefficients'
      Write (nout,99998) kvar(1:nvars)
      Write (nout,99996)(kvar(i),rz(i,1:nvars),i=1,nvars)
      Write (nout,*)
      Write (nout,99999) 'Number of cases actually used:', ncases

99999 Format (1X,A,I5)
99998 Format (1X,4I12)
99997 Format (1X,I3,4F12.4)
99996 Format (1X,I3,3F12.4)
99995 Format (1X,I5,2F11.4)
    End Program g02blfe


g02bmfe.f90

    Program g02bmfe

!     G02BMF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: g02bmf, nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Integer                          :: i, ifail, ldcnt, ldrz, ldsspz, ldx,  &
                                          m, n, ncases, nvars
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: cnt(:,:), rz(:,:), sspz(:,:),        &
                                          std(:), x(:,:), xbar(:), xmiss(:)
      Integer, Allocatable             :: kvar(:), miss(:)
!     .. Executable Statements ..
      Write (nout,*) 'G02BMF Example Program Results'
      Write (nout,*)

!     Skip heading in data file
      Read (nin,*)

!     Read in the problem size
      Read (nin,*) n, m, nvars

      ldcnt = nvars
      ldrz = nvars
      ldsspz = nvars
      ldx = n
      Allocate (cnt(ldcnt,nvars),rz(ldrz,nvars),sspz(ldsspz,nvars),std(nvars), &
        x(ldx,m),xbar(nvars),xmiss(m),kvar(nvars),miss(m))

!     Read in data
      Read (nin,*)(x(i,1:m),i=1,n)

!     Read in missing value flags
      Read (nin,*) miss(1:m)
      Read (nin,*) xmiss(1:m)

!     Read in column IDs
      Read (nin,*) kvar(1:nvars)

!     Display data
      Write (nout,99999) 'Number of variables (columns) =', m
      Write (nout,99999) 'Number of cases     (rows)    =', n
      Write (nout,*)
      Write (nout,*) 'Data matrix is:-'
      Write (nout,*)
      Write (nout,99998)(i,i=1,m)
      Write (nout,99997)(i,x(i,1:m),i=1,n)
      Write (nout,*)

!     Calculate summary statistics
      ifail = 0
      Call g02bmf(n,m,x,ldx,miss,xmiss,nvars,kvar,xbar,std,sspz,ldsspz,rz,     &
        ldrz,ncases,cnt,ldcnt,ifail)

!     Display results
      Write (nout,*) 'Variable   Mean    St. dev.'
      Write (nout,99995)(kvar(i),xbar(i),std(i),i=1,nvars)
      Write (nout,*)
      Write (nout,*) 'Sums of squares and cross-products about' // ' zero'
      Write (nout,99998) kvar(1:nvars)
      Write (nout,99996)(kvar(i),sspz(i,1:nvars),i=1,nvars)
      Write (nout,*)
      Write (nout,*) 'Correlation-like coefficients'
      Write (nout,99998) kvar(1:nvars)
      Write (nout,99996)(kvar(i),rz(i,1:nvars),i=1,nvars)
      Write (nout,*)
      Write (nout,99999)                                                       &
        'Minimum number of cases used for any pair of variables:', ncases
      Write (nout,*)
      Write (nout,*) 'Numbers used for each pair are:'
      Write (nout,99998) kvar(1:nvars)
      Write (nout,99996)(kvar(i),cnt(i,1:nvars),i=1,nvars)

99999 Format (1X,A,I5)
99998 Format (1X,4I12)
99997 Format (1X,I3,4F12.4)
99996 Format (1X,I3,3F12.4)
99995 Format (1X,I5,2F11.4)
    End Program g02bmfe


g02bnfe.f90

    Program g02bnfe

!     G02BNF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: g02bnf, nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Integer                          :: i, ifail, itype, ldrr, ldx, m, n
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: rr(:,:), work1(:), work2(:), x(:,:)
      Integer, Allocatable             :: kworka(:), kworkb(:)
!     .. Executable Statements ..
      Write (nout,*) 'G02BNF Example Program Results'
      Write (nout,*)

!     Skip heading in data file
      Read (nin,*)

!     Read in the problem size
      Read (nin,*) n, m, itype

      ldrr = m
      ldx = n
      Allocate (rr(ldrr,m),work1(m),work2(m),x(ldx,m),kworka(n),kworkb(n))

!     Read in data
      Read (nin,*)(x(i,1:m),i=1,n)

!     Display data
      Write (nout,99999) 'Number of variables (columns) =', m
      Write (nout,99999) 'Number of cases     (rows)    =', n
      Write (nout,*)
      Write (nout,*) 'Data matrix is:-'
      Write (nout,*)
      Write (nout,99998)(i,i=1,m)
      Write (nout,99997)(i,x(i,1:m),i=1,n)
      Write (nout,*)

!     Calculate correlation coefficients
      ifail = 0
      Call g02bnf(n,m,x,ldx,itype,rr,ldrr,kworka,kworkb,work1,work2,ifail)

!     Display results
      Write (nout,*) 'Matrix of ranks:-'
      Write (nout,99998)(i,i=1,m)
      Write (nout,99997)(i,x(i,1:m),i=1,n)
      Write (nout,*)
      Write (nout,*) 'Matrix of rank correlation coefficients:'
      Write (nout,*) 'Upper triangle -- Spearman''s'
      Write (nout,*) 'Lower triangle -- Kendall''s tau'
      Write (nout,*)
      Write (nout,99998)(i,i=1,m)
      Write (nout,99997)(i,rr(i,1:m),i=1,m)

99999 Format (1X,A,I5)
99998 Format (1X,3I12)
99997 Format (1X,I3,3F12.4)
    End Program g02bnfe


g02bpfe.f90

    Program g02bpfe

!     G02BPF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: g02bpf, nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Integer                          :: i, ifail, itype, ldrr, ldx, m, n,    &
                                          ncases
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: rr(:,:), work1(:), work2(:), x(:,:), &
                                          xmiss(:)
      Integer, Allocatable             :: incase(:), kworka(:), kworkb(:),     &
                                          kworkc(:), miss(:)
!     .. Executable Statements ..
      Write (nout,*) 'G02BPF Example Program Results'
      Write (nout,*)

!     Skip heading in data file
      Read (nin,*)

!     Read in the problem size
      Read (nin,*) n, m, itype

      ldrr = m
      ldx = n
      Allocate (rr(ldrr,m),work1(m),work2(m),x(ldx,m),xmiss(m),incase(n),      &
        kworka(n),kworkb(n),kworkc(n),miss(m))

!     Read in data
      Read (nin,*)(x(i,1:m),i=1,n)

!     Read in missing value flags
      Read (nin,*) miss(1:m)
      Read (nin,*) xmiss(1:m)

!     Display data
      Write (nout,99999) 'Number of variables (columns) =', m
      Write (nout,99999) 'Number of cases     (rows)    =', n
      Write (nout,*)
      Write (nout,*) 'Data matrix is:-'
      Write (nout,*)
      Write (nout,99998)(i,i=1,m)
      Write (nout,99997)(i,x(i,1:m),i=1,n)
      Write (nout,*)

!     Calculate correlation coefficients
      ifail = 0
      Call g02bpf(n,m,x,ldx,miss,xmiss,itype,rr,ldrr,ncases,incase,kworka,     &
        kworkb,kworkc,work1,work2,ifail)

!     Display results
      Write (nout,*) 'Matrix of ranks:-'
      Write (nout,*)
      Write (nout,*)                                                           &
        '(1 in the column headed In/Out indicates the case was included,'
      Write (nout,*)                                                           &
        ' 0 in the column headed In/Out indicates the case was omitted.)'
      Write (nout,*)
      Write (nout,99996) 'Case   In/Out', (i,i=1,m)
      Write (nout,99995)(i,incase(i),x(i,1:m),i=1,n)
      Write (nout,*)
      Write (nout,*) 'Matrix of rank correlation coefficients:'
      Write (nout,*) 'Upper triangle -- Spearman''s'
      Write (nout,*) 'Lower triangle -- Kendall''s tau'
      Write (nout,*)
      Write (nout,99998)(i,i=1,m)
      Write (nout,99997)(i,rr(i,1:m),i=1,m)
      Write (nout,*)
      Write (nout,99999) 'Number of cases actually used:', ncases

99999 Format (1X,A,I5)
99998 Format (1X,3I12)
99997 Format (1X,I3,3F12.4)
99996 Format (1X,A,I6,2I12)
99995 Format (1X,I3,I7,3F12.4)
    End Program g02bpfe


g02bqfe.f90

    Program g02bqfe

!     G02BQF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: g02bqf, nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Integer                          :: i, ifail, itype, ldrr, ldx, m, n
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: rr(:,:), work1(:), work2(:), x(:,:)
      Integer, Allocatable             :: kworka(:), kworkb(:)
!     .. Executable Statements ..
      Write (nout,*) 'G02BQF Example Program Results'
      Write (nout,*)

!     Skip heading in data file
      Read (nin,*)

!     Read in the problem size
      Read (nin,*) n, m, itype

      ldrr = m
      ldx = n
      Allocate (rr(ldrr,m),work1(n),work2(n),x(ldx,m),kworka(n),kworkb(n))

!     Read in data
      Read (nin,*)(x(i,1:m),i=1,n)

!     Display data
      Write (nout,99999) 'Number of variables (columns) =', m
      Write (nout,99999) 'Number of cases     (rows)    =', n
      Write (nout,*)
      Write (nout,*) 'Data matrix is:-'
      Write (nout,*)
      Write (nout,99998)(i,i=1,m)
      Write (nout,99997)(i,x(i,1:m),i=1,n)
      Write (nout,*)

!     Calculate correlation coefficients
      ifail = 0
      Call g02bqf(n,m,x,ldx,itype,rr,ldrr,kworka,kworkb,work1,work2,ifail)

!     Display results
      Write (nout,*) 'Matrix of rank correlation coefficients:'
      Write (nout,*) 'Upper triangle -- Spearman''s'
      Write (nout,*) 'Lower triangle -- Kendall''s tau'
      Write (nout,*)
      Write (nout,99998)(i,i=1,m)
      Write (nout,99997)(i,rr(i,1:m),i=1,m)

99999 Format (1X,A,I5)
99998 Format (1X,3I12)
99997 Format (1X,I3,3F12.4)
    End Program g02bqfe


g02brfe.f90

    Program g02brfe

!     G02BRF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: g02brf, nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Integer                          :: i, ifail, itype, ldrr, ldx, m, n,    &
                                          ncases
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: rr(:,:), work1(:), work2(:), x(:,:), &
                                          xmiss(:)
      Integer, Allocatable             :: incase(:), kworka(:), kworkb(:),     &
                                          kworkc(:), miss(:)
!     .. Executable Statements ..
      Write (nout,*) 'G02BRF Example Program Results'
      Write (nout,*)

!     Skip heading in data file
      Read (nin,*)

!     Read in the problem size
      Read (nin,*) n, m, itype

      ldrr = m
      ldx = n
      Allocate (rr(ldrr,m),work1(n),work2(n),x(ldx,m),xmiss(m),incase(n),      &
        kworka(n),kworkb(n),kworkc(n),miss(m))

!     Read in data
      Read (nin,*)(x(i,1:m),i=1,n)

!     Read in missing value flags
      Read (nin,*) miss(1:m)
      Read (nin,*) xmiss(1:m)

!     Display data
      Write (nout,99999) 'Number of variables (columns) =', m
      Write (nout,99999) 'Number of cases     (rows)    =', n
      Write (nout,*)
      Write (nout,*) 'Data matrix is:-'
      Write (nout,*)
      Write (nout,99998)(i,i=1,m)
      Write (nout,99997)(i,x(i,1:m),i=1,n)
      Write (nout,*)

!     Calculate correlation coefficients
      ifail = 0
      Call g02brf(n,m,x,ldx,miss,xmiss,itype,rr,ldrr,ncases,incase,kworka,     &
        kworkb,kworkc,work1,work2,ifail)

!     Display results
      Write (nout,*) 'Matrix of rank correlation coefficients:'
      Write (nout,*) 'Upper triangle -- Spearman''s'
      Write (nout,*) 'Lower triangle -- Kendall''s tau'
      Write (nout,*)
      Write (nout,99998)(i,i=1,m)
      Write (nout,99997)(i,rr(i,1:m),i=1,m)
      Write (nout,*)
      Write (nout,99999) 'Number of cases actually used:', ncases

99999 Format (1X,A,I5)
99998 Format (1X,3I12)
99997 Format (1X,I3,3F12.4)
    End Program g02brfe


g02bsfe.f90

    Program g02bsfe

!     G02BSF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: g02bsf, nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Integer                          :: i, ifail, itype, ldcnt, ldrr, ldx,   &
                                          m, n, ncases
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: cnt(:,:), rr(:,:), work1(:),         &
                                          work2(:), x(:,:), xmiss(:)
      Integer, Allocatable             :: kworka(:), kworkb(:), kworkc(:),     &
                                          kworkd(:), miss(:)
!     .. Executable Statements ..
      Write (nout,*) 'G02BSF Example Program Results'
      Write (nout,*)

!     Skip heading in data file
      Read (nin,*)

!     Read in the problem size
      Read (nin,*) n, m, itype

      ldcnt = m
      ldrr = m
      ldx = n
      Allocate (cnt(ldcnt,m),rr(ldrr,m),work1(n),work2(n),x(ldx,m),xmiss(m),   &
        kworka(n),kworkb(n),kworkc(n),kworkd(n),miss(m))

!     Read in data
      Read (nin,*)(x(i,1:m),i=1,n)

!     Read in missing value flags
      Read (nin,*) miss(1:m)
      Read (nin,*) xmiss(1:m)

!     Display data
      Write (nout,99999) 'Number of variables (columns) =', m
      Write (nout,99999) 'Number of cases     (rows)    =', n
      Write (nout,*)
      Write (nout,*) 'Data matrix is:-'
      Write (nout,*)
      Write (nout,99998)(i,i=1,m)
      Write (nout,99997)(i,x(i,1:m),i=1,n)
      Write (nout,*)

!     Calculate correlation coefficients
      ifail = 0
      Call g02bsf(n,m,x,ldx,miss,xmiss,itype,rr,ldrr,ncases,cnt,ldcnt,kworka,  &
        kworkb,kworkc,kworkd,work1,work2,ifail)

!     Display results
      Write (nout,*) 'Matrix of rank correlation coefficients:'
      Write (nout,*) 'Upper triangle -- Spearman''s'
      Write (nout,*) 'Lower triangle -- Kendall''s tau'
      Write (nout,*)
      Write (nout,99998)(i,i=1,m)
      Write (nout,99997)(i,rr(i,1:m),i=1,m)
      Write (nout,*)
      Write (nout,99999)                                                       &
        'Minimum number of cases used for any pair of variables:', ncases
      Write (nout,*)
      Write (nout,*) 'Numbers used for each pair are:'
      Write (nout,99998)(i,i=1,m)
      Write (nout,99997)(i,cnt(i,1:m),i=1,m)

99999 Format (1X,A,I5)
99998 Format (1X,3I12)
99997 Format (1X,I3,3F12.4)
    End Program g02bsfe


g02btfe.f90

    Program g02btfe

!     G02BTF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: g02btf, nag_wp, x04ccf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Real (Kind=nag_wp), Parameter    :: one = 1.0_nag_wp
      Real (Kind=nag_wp), Parameter    :: zero = 0.0_nag_wp
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: alpha, sw, wt
      Integer                          :: i, ifail, incx, lc, m, n, nprint
      Character (1)                    :: mean
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: c(:), v(:), x(:), xbar(:)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: mod
!     .. Executable Statements ..
      Write (nout,*) 'G02BTF Example Program Results'
      Write (nout,*)

!     Skip heading in data file
      Read (nin,*)

!     Read in problem size
      Read (nin,*) mean, m, n, nprint

      lc = (m*m+m)/2
      Allocate (x(m),xbar(m),c(lc),v(lc))

!     Elements of X are stored consecutively
      incx = 1

!     Loop over each observation individually, updating the sums of squares
!     and cross-product matrix at each iteration
      sw = zero
      i = 0
data_lp: Do
        Read (nin,*,Iostat=ifail) wt, x(1:m)
        If (ifail/=0) Then
!         Finished processing all the data
          Exit data_lp
        End If

        i = i + 1

!       Update the sums of squares and cross-products matrix
        ifail = 0
        Call g02btf(mean,m,wt,x,incx,sw,xbar,c,ifail)

!       Display the results, either at the end or every NPRINT iterations
        If (mod(i,nprint)==0 .Or. i==n) Then
          Write (nout,*) '---------------------------------------------'
          Write (nout,99999) 'Observation: ', i, '      Weight = ', wt
          Write (nout,*) '---------------------------------------------'
          Write (nout,*)
          Write (nout,*) 'Means'
          Write (nout,99998) xbar(1:m)
          Write (nout,*)
          Flush (nout)
          ifail = 0
          Call x04ccf('Upper','Non-unit',m,c,                                  &
            'Sums of squares and cross-products',ifail)

!         Convert the sums of squares and cross-products to a variance matrix
          If (sw>one) Then
            alpha = one/(sw-one)
            v(1:lc) = alpha*c(1:lc)
            Write (nout,*)
            Flush (nout)
            ifail = 0
            Call x04ccf('Upper','Non-unit',m,v,'Variance matrix',ifail)
          End If
          Write (nout,*)
        End If
      End Do data_lp

99999 Format (1X,A,I4,A,F13.4)
99998 Format (1X,4F14.4)
    End Program g02btfe


g02bufe.f90

    Program g02bufe

!     G02BUF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: dscal, g02buf, nag_wp, x04ccf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Real (Kind=nag_wp), Parameter    :: one = 1.0_nag_wp
      Integer, Parameter               :: inc1 = 1, nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: alpha, sw
      Integer                          :: i, ifail, lc, ldx, lwt, m, n
      Character (1)                    :: mean, weight
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: c(:), wmean(:), wt(:), x(:,:)
!     .. Executable Statements ..
      Write (nout,*) 'G02BUF Example Program Results'
      Write (nout,*)
      Flush (nout)

!     Skip heading in data file
      Read (nin,*)

!     Read in problem size
      Read (nin,*) mean, weight, m, n

      If (weight=='W' .Or. weight=='w') Then
        lwt = n
      Else
        lwt = 0
      End If
      ldx = n
      lc = (m*m+m)/2
      Allocate (wt(lwt),x(ldx,m),wmean(m),c(lc))

!     Read in data
      If (lwt>0) Then
        Read (nin,*) wt(1:n)
      End If
      Read (nin,*)(x(i,1:m),i=1,n)

!     Calculate sums of squares and cross-products matrix
      ifail = 0
      Call g02buf(mean,weight,n,m,x,ldx,wt,sw,wmean,c,ifail)

!     Display results
      Write (nout,*) 'Means'
      Write (nout,99999) wmean(1:m)
      Write (nout,*)
      Write (nout,*) 'Weights'
      Write (nout,99999) wt(1:n)
      Write (nout,*)
      Flush (nout)
      ifail = 0
      Call x04ccf('Upper','Non-unit',m,c,'Sums of squares and cross-products', &
        ifail)

!     Convert the sums of squares and cross-products to a variance matrix
      If (sw>one) Then
        alpha = one/(sw-one)
!       The NAG name equivalent of dscal is f06edf
        Call dscal(lc,alpha,c,inc1)
        Write (nout,*)
        Flush (nout)
        ifail = 0
        Call x04ccf('Upper','Non-unit',m,c,'Variance matrix',ifail)
      End If

99999 Format (1X,6F14.4)
    End Program g02bufe


g02bwfe.f90

    Program g02bwfe

!     G02BWF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: g02buf, g02bwf, nag_wp, x04ccf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: sw
      Integer                          :: i, ifail, ldx, lr, lwt, m, n
      Logical                          :: zero_var
      Character (1)                    :: mean, weight
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: r(:), wmean(:), wt(:), x(:,:)
!     .. Executable Statements ..
      Write (nout,*) 'G02BWF Example Program Results'
      Write (nout,*)
      Flush (nout)

!     Skip heading in data file
      Read (nin,*)

!     Read in the problem size
      Read (nin,*) mean, weight, m, n

      If (weight=='W' .Or. weight=='w') Then
        lwt = n
      Else
        lwt = 0
      End If
      ldx = n
      lr = (m*m+m)/2
      Allocate (r(lr),wmean(m),wt(lwt),x(ldx,m))

!     Read in data
      Read (nin,*) wt(1:n)
      Read (nin,*)(x(i,1:m),i=1,n)

!     Calculate the sums of squares and cross-products matrix
      ifail = 0
      Call g02buf(mean,weight,n,m,x,ldx,wt,sw,wmean,r,ifail)

!     Calculate the correlation matrix
      ifail = -1
      Call g02bwf(m,r,ifail)
      If (ifail/=0) Then
        If (ifail==2) Then
          zero_var = .True.
        Else
          Go To 100
        End If
      Else
        zero_var = .False.
      End If

!     Display the results
      ifail = 0
      Call x04ccf('Upper','Non-unit',m,r,'Correlation matrix',ifail)
      If (zero_var) Then
        Write (nout,*) ' NOTE: some variances are zero'
      End If

100   Continue

    End Program g02bwfe


g02bxfe.f90

    Program g02bxfe

!     G02BXF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: g02bxf, nag_wp, x04caf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Integer                          :: i, ifail, ldv, ldx, lwt, m, n
      Logical                          :: zero_var
      Character (1)                    :: weight
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: r(:,:), std(:), v(:,:), wt(:),       &
                                          x(:,:), xbar(:)
!     .. Executable Statements ..
      Write (nout,*) 'G02BXF Example Program Results'
      Write (nout,*)

!     Skip heading in data file
      Read (nin,*)

!     Read in problem size
      Read (nin,*) weight, n, m
      If (weight=='W' .Or. weight=='w') Then
        lwt = n
      Else
        lwt = 0
      End If
      ldx = n
      ldv = m
      Allocate (x(ldx,m),wt(lwt),xbar(m),std(m),v(ldv,m),r(ldv,m))

!     Read in data
      If (lwt>0) Then
        Read (nin,*)(x(i,1:m),wt(i),i=1,n)
      Else
        Read (nin,*)(x(i,1:m),i=1,n)
      End If

!     Calculate summary statistics
      ifail = -1
      Call g02bxf(weight,n,m,x,ldx,wt,xbar,std,v,ldv,r,ifail)
      If (ifail/=0) Then
        If (ifail==5) Then
          zero_var = .True.
        Else
          Go To 100
        End If
      Else
        zero_var = .False.
      End If

!     Display results
      Write (nout,*) '     Means'
      Write (nout,*)
      Write (nout,99999)(xbar(i),i=1,m)
      Write (nout,*)
      Write (nout,*) '     Standard deviations'
      Write (nout,*)
      Write (nout,99999)(std(i),i=1,m)
      Write (nout,*)
      Flush (nout)
      ifail = 0
      Call x04caf('Upper','Non-unit',m,m,r,ldv,'     Correlation matrix',      &
        ifail)
      If (zero_var) Then
        Write (nout,*) ' NOTE: some variances are zero'
      End If

100   Continue

99999 Format (1X,10F13.4)
    End Program g02bxfe


g02byfe.f90

    Program g02byfe

!     G02BYF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: g02bxf, g02byf, nag_wp, x04caf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Integer                          :: i, ifail, ldp, ldr, ldx, lwt, m, n,  &
                                          nx, ny
      Character (1)                    :: weight
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: p(:,:), r(:,:), std(:), v(:,:),      &
                                          wk(:), wt(:), x(:,:), xbar(:)
      Integer, Allocatable             :: isz(:)
!     .. Executable Statements ..
      Write (nout,*) 'G02BYF Example Program Results'
      Write (nout,*)
      Flush (nout)

!     Skip heading in data file
      Read (nin,*)

!     Read in the problem size
      Read (nin,*) weight, n, m

      If (weight=='W' .Or. weight=='w') Then
        lwt = n
      Else
        lwt = 0
      End If
      ldp = m
      ldr = m
      ldx = n
      Allocate (p(ldp,m),v(ldr,m),std(m),wk(m*m),wt(lwt),x(ldx,m),xbar(m),     &
        isz(m),r(ldr,m))

!     Read in data
      Read (nin,*)(x(i,1:m),i=1,n)

!     Read in number of variables and variable flags for partial correlation
!     coefficients.
      Read (nin,*) ny, nx
      Read (nin,*) isz(1:m)

!     Calculate correlation matrix
      ifail = 0
      Call g02bxf(weight,n,m,x,ldx,wt,xbar,std,v,ldr,r,ifail)

!     Calculate partial correlation matrix
      ifail = 0
      Call g02byf(m,ny,nx,isz,r,ldr,p,ldp,wk,ifail)

!     Display results
      ifail = 0
      Call x04caf('Upper','Non-unit',m,m,r,ldr,'Correlation matrix',ifail)
      Write (nout,*)
      Flush (nout)
      ifail = 0
      Call x04caf('Upper','Unit',ny,ny,p,ldp,'Partial Correlation matrix',     &
        ifail)

    End Program g02byfe


g02bzfe.f90

    Program g02bzfe
!     G02BZF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: dscal, g02buf, g02bzf, nag_wp, x04ccf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: alpha, xsw, ysw
      Integer                          :: b, i, ierr, ifail, lc, ldx, m, n
      Character (1)                    :: mean, weight
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: wt(:), x(:,:), xc(:), xmean(:),      &
                                          yc(:), ymean(:)
!     .. Executable Statements ..
      Write (nout,*) 'G02BZF Example Program Results'
      Write (nout,*)
      Flush (nout)

!     Skip heading in data file
      Read (nin,*)

!     Read in the problem defining variables
      Read (nin,*) mean, m

!     Allocate memory for output arrays
      lc = (m*m+m)/2
      Allocate (xmean(m),ymean(m),xc(lc),yc(lc))

!     Loop over each block of data
      b = 0
      Do
!       Read in the number of observations in this block and the weight flag
        Read (nin,*,Iostat=ierr) n, weight
        If (ierr/=0) Then
          Exit
        End If

!       Keep a running total of the number of blocks of data
        b = b + 1

!       Allocate arrays to hold data and read the current block of data in
        ldx = n
        Allocate (x(ldx,m))
        If (weight=='W' .Or. weight=='w') Then
!         Weighted
          Allocate (wt(n))
          Do i = 1, n
            Read (nin,*) x(i,1:m), wt(i)
          End Do
        Else
!         Unweighted
          Allocate (wt(0))
          Do i = 1, n
            Read (nin,*) x(i,1:m)
          End Do
        End If

!       Summarise this block of data
        If (b==1) Then
!         This is the first block of data, so summarise the data into XMEAN
!         and XC
          ifail = 0
          Call g02buf(mean,weight,n,m,x,ldx,wt,xsw,xmean,xc,ifail)

        Else
!         This is not the first block of data, so summarise the data into
!         YMEAN and YC
          ifail = 0
          Call g02buf(mean,weight,n,m,x,ldx,wt,ysw,ymean,yc,ifail)

!         Update the running summaries
          ifail = 0
          Call g02bzf(mean,m,xsw,xmean,xc,ysw,ymean,yc,ifail)
        End If

        Deallocate (x,wt)
      End Do

!     Display results
      Write (nout,*) 'Means'
      Write (nout,99999) xmean(1:m)

      Write (nout,*)
      ifail = 0
      Call x04ccf('Upper','Non-unit',m,xc,'Sums of squares and cross-products' &
        ,ifail)

      If (xsw>1.0_nag_wp .And. (mean=='M' .Or. mean=='m')) Then
!       Use DSCAL (F06EDF) to scale the sums of squares and cross-products
!       matrix XC, and so convert it to a covariance matrix
        alpha = 1.0_nag_wp/(xsw-1.0_nag_wp)
        Call dscal(lc,alpha,xc,1)

        Write (nout,*)
        ifail = 0
        Call x04ccf('Upper','Non-unit',m,xc,'Covariance matrix',ifail)
      End If

99999 Format (1X,6F14.4)
    End Program g02bzfe


g02cafe.f90

    Program g02cafe

!     G02CAF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: g02caf, nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Integer                          :: i, ifail, n
!     .. Local Arrays ..
      Real (Kind=nag_wp)               :: reslt(20)
      Real (Kind=nag_wp), Allocatable  :: x(:), y(:)
!     .. Executable Statements ..
      Write (nout,*) 'G02CAF Example Program Results'
      Write (nout,*)

!     Skip heading in data file
      Read (nin,*)

!     Read in the problem size
      Read (nin,*) n

      Allocate (x(n),y(n))

!     Read in data
      Read (nin,*)(x(i),y(i),i=1,n)

!     Display data
      Write (nout,*) ' Case     Independent     Dependent'
      Write (nout,*) 'number     variable       variable'
      Write (nout,*)
      Write (nout,99999)(i,x(i),y(i),i=1,n)
      Write (nout,*)

!     Fit linear regression model
      ifail = 0
      Call g02caf(n,x,y,reslt,ifail)

!     Display results
      Write (nout,99998) 'Mean of independent variable               = ',      &
        reslt(1)
      Write (nout,99998) 'Mean of   dependent variable               = ',      &
        reslt(2)
      Write (nout,99998) 'Standard deviation of independent variable = ',      &
        reslt(3)
      Write (nout,99998) 'Standard deviation of   dependent variable = ',      &
        reslt(4)
      Write (nout,99998) 'Correlation coefficient                    = ',      &
        reslt(5)
      Write (nout,*)
      Write (nout,99998) 'Regression coefficient                     = ',      &
        reslt(6)
      Write (nout,99998) 'Standard error of coefficient              = ',      &
        reslt(8)
      Write (nout,99998) 't-value for coefficient                    = ',      &
        reslt(10)
      Write (nout,*)
      Write (nout,99998) 'Regression constant                        = ',      &
        reslt(7)
      Write (nout,99998) 'Standard error of constant                 = ',      &
        reslt(9)
      Write (nout,99998) 't-value for constant                       = ',      &
        reslt(11)
      Write (nout,*)
      Write (nout,*) 'Analysis of regression table :-'
      Write (nout,*)
      Write (nout,*)                                                           &
        '      Source        Sum of squares  D.F.    Mean square     F-value'
      Write (nout,*)
      Write (nout,99997) 'Due to regression', reslt(12:15)
      Write (nout,99997) 'About  regression', reslt(16:18)
      Write (nout,99997) 'Total            ', reslt(19:20)

99999 Format (1X,I4,2F15.4)
99998 Format (1X,A,F8.4)
99997 Format (1X,A,F14.3,F8.0,2F14.3)
    End Program g02cafe


g02cbfe.f90

    Program g02cbfe

!     G02CBF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: g02cbf, nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Integer                          :: i, ifail, n
!     .. Local Arrays ..
      Real (Kind=nag_wp)               :: reslt(20)
      Real (Kind=nag_wp), Allocatable  :: x(:), y(:)
!     .. Executable Statements ..
      Write (nout,*) 'G02CBF Example Program Results'
      Write (nout,*)

!     Skip heading in data file
      Read (nin,*)

!     Read in problem size
      Read (nin,*) n

      Allocate (x(n),y(n))

!     Read in data
      Read (nin,*)(x(i),y(i),i=1,n)

!     Display data
      Write (nout,*) ' Case     Independent     Dependent'
      Write (nout,*) 'number     variable       variable'
      Write (nout,*)
      Write (nout,99999)(i,x(i),y(i),i=1,n)
      Write (nout,*)

!     Fit linear regression model
      ifail = 0
      Call g02cbf(n,x,y,reslt,ifail)

!     Display results
      Write (nout,99998) 'Mean of independent variable               = ',      &
        reslt(1)
      Write (nout,99998) 'Mean of   dependent variable               = ',      &
        reslt(2)
      Write (nout,99998) 'Standard deviation of independent variable = ',      &
        reslt(3)
      Write (nout,99998) 'Standard deviation of   dependent variable = ',      &
        reslt(4)
      Write (nout,99998) 'Correlation coefficient                    = ',      &
        reslt(5)
      Write (nout,*)
      Write (nout,99998) 'Regression coefficient                     = ',      &
        reslt(6)
      Write (nout,99998) 'Standard error of coefficient              = ',      &
        reslt(8)
      Write (nout,99998) 't-value for coefficient                    = ',      &
        reslt(10)
      Write (nout,*)
      Write (nout,*) 'Analysis of regression table :-'
      Write (nout,*)
      Write (nout,*)                                                           &
        '      Source        Sum of squares  D.F.    Mean square     F-value'
      Write (nout,*)
      Write (nout,99997) 'Due to regression', reslt(12:15)
      Write (nout,99997) 'About  regression', reslt(16:18)
      Write (nout,99997) 'Total            ', reslt(19:20)

99999 Format (1X,I4,2F15.4)
99998 Format (1X,A,F8.4)
99997 Format (1X,A,F14.4,F8.0,2F14.4)
    End Program g02cbfe


g02ccfe.f90

    Program g02ccfe

!     G02CCF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: g02ccf, nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: xmiss, ymiss
      Integer                          :: i, ifail, n
!     .. Local Arrays ..
      Real (Kind=nag_wp)               :: reslt(21)
      Real (Kind=nag_wp), Allocatable  :: x(:), y(:)
!     .. Executable Statements ..
      Write (nout,*) 'G02CCF Example Program Results'
      Write (nout,*)

!     Skip heading in data file
      Read (nin,*)

!     Read in problem size
      Read (nin,*) n

      Allocate (x(n),y(n))

!     Read in data
      Read (nin,*)(x(i),y(i),i=1,n)

!     Read in missing value flags
      Read (nin,*) xmiss, ymiss

!     Display data
      Write (nout,*) ' Case     Independent     Dependent'
      Write (nout,*) 'number     variable       variable'
      Write (nout,*)
      Write (nout,99999)(i,x(i),y(i),i=1,n)
      Write (nout,*)

!     Fit linear regression model
      ifail = 0
      Call g02ccf(n,x,y,xmiss,ymiss,reslt,ifail)

      Write (nout,99998) 'Mean of independent variable               = ',      &
        reslt(1)
      Write (nout,99998) 'Mean of   dependent variable               = ',      &
        reslt(2)
      Write (nout,99998) 'Standard deviation of independent variable = ',      &
        reslt(3)
      Write (nout,99998) 'Standard deviation of   dependent variable = ',      &
        reslt(4)
      Write (nout,99998) 'Correlation coefficient                    = ',      &
        reslt(5)
      Write (nout,*)
      Write (nout,99998) 'Regression coefficient                     = ',      &
        reslt(6)
      Write (nout,99998) 'Standard error of coefficient              = ',      &
        reslt(8)
      Write (nout,99998) 't-value for coefficient                    = ',      &
        reslt(10)
      Write (nout,*)
      Write (nout,99998) 'Regression constant                        = ',      &
        reslt(7)
      Write (nout,99998) 'Standard error of constant                 = ',      &
        reslt(9)
      Write (nout,99998) 't-value for constant                       = ',      &
        reslt(11)
      Write (nout,*)
      Write (nout,*) 'Analysis of regression table :-'
      Write (nout,*)
      Write (nout,*)                                                           &
        '      Source        Sum of squares  D.F.    Mean square     F-value'
      Write (nout,*)
      Write (nout,99997) 'Due to regression', reslt(12:15)
      Write (nout,99997) 'About  regression', reslt(16:18)
      Write (nout,99997) 'Total            ', reslt(19:20)
      Write (nout,*)
      Write (nout,99996) 'Number of cases used = ', reslt(21)

99999 Format (1X,I4,2F15.4)
99998 Format (1X,A,F8.4)
99997 Format (1X,A,F14.4,F8.0,2F14.4)
99996 Format (1X,A,F3.0)
    End Program g02ccfe


g02cdfe.f90

    Program g02cdfe

!     G02CDF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: g02cdf, nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: xmiss, ymiss
      Integer                          :: i, ifail, n
!     .. Local Arrays ..
      Real (Kind=nag_wp)               :: reslt(21)
      Real (Kind=nag_wp), Allocatable  :: x(:), y(:)
!     .. Executable Statements ..
      Write (nout,*) 'G02CDF Example Program Results'
      Write (nout,*)

!     Skip heading in data file
      Read (nin,*)

!     Read in problem size
      Read (nin,*) n

      Allocate (x(n),y(n))

!     Read in data
      Read (nin,*)(x(i),y(i),i=1,n)

!     Read in missing value flags
      Read (nin,*) xmiss, ymiss

!     Display data
      Write (nout,*) ' Case     Independent     Dependent'
      Write (nout,*) 'number     variable       variable'
      Write (nout,*)
      Write (nout,99999)(i,x(i),y(i),i=1,n)
      Write (nout,*)

!     Fit linear regression model
      ifail = 0
      Call g02cdf(n,x,y,xmiss,ymiss,reslt,ifail)

!     Display results
      Write (nout,99998) 'Mean of independent variable               = ',      &
        reslt(1)
      Write (nout,99998) 'Mean of   dependent variable               = ',      &
        reslt(2)
      Write (nout,99998) 'Standard deviation of independent variable = ',      &
        reslt(3)
      Write (nout,99998) 'Standard deviation of   dependent variable = ',      &
        reslt(4)
      Write (nout,99998) 'Correlation coefficient                    = ',      &
        reslt(5)
      Write (nout,*)
      Write (nout,99998) 'Regression coefficient                     = ',      &
        reslt(6)
      Write (nout,99998) 'Standard error of coefficient              = ',      &
        reslt(8)
      Write (nout,99998) 't-value for coefficient                    = ',      &
        reslt(10)
      Write (nout,*)
      Write (nout,*) 'Analysis of regression table :-'
      Write (nout,*)
      Write (nout,*)                                                           &
        '      Source        Sum of squares  D.F.    Mean square     F-value'
      Write (nout,*)
      Write (nout,99997) 'Due to regression', reslt(12:15)
      Write (nout,99997) 'About  regression', reslt(16:18)
      Write (nout,99997) 'Total            ', reslt(19:20)
      Write (nout,*)
      Write (nout,99996) 'Number of cases used = ', reslt(21)

99999 Format (1X,I4,2F15.4)
99998 Format (1X,A,F8.4)
99997 Format (1X,A,F14.4,F8.0,2F14.4)
99996 Format (1X,A,F3.0)
    End Program g02cdfe


g02cefe.f90

    Program g02cefe

!     G02CEF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: g02cef, nag_wp, x04caf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Integer                          :: i, ifail, ldr, ldr2, ldssp, ldssp2,  &
                                          m, n
      Character (80)                   :: fmt
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: r(:,:), r2(:,:), ssp(:,:),           &
                                          ssp2(:,:), std(:), std2(:), xbar(:), &
                                          xbar2(:)
      Integer, Allocatable             :: korder(:)
!     .. Executable Statements ..
      Write (nout,*) 'G02CEF Example Program Results'
      Write (nout,*)

!     Skip heading in data file
      Read (nin,*)

!     Read in the problem size
      Read (nin,*) n, m

      ldr = n
      ldr2 = m
      ldssp = n
      ldssp2 = m
      Allocate (r(ldr,n),r2(ldr2,m),ssp(ldssp,n),ssp2(ldssp2,m),std(n),        &
        std2(m),xbar(n),xbar2(m),korder(m))

!     Read in the data
      Read (nin,*) xbar(1:n)
      Read (nin,*) std(1:n)
      Read (nin,*)(ssp(i,1:n),i=1,n)
      Read (nin,*)(r(i,1:n),i=1,n)

!     Read in the reordering vector
      Read (nin,*) korder(1:m)

!     Format for displaying vectors
      Write (fmt,99999) '(1x,a,', n, '(1x,f10.4))'

!     Display data
      Write (nout,fmt) 'Original vector XBAR :   ', xbar(1:n)
      Write (nout,*)
      Write (nout,fmt) 'Original vector STD  :   ', std(1:n)
      Write (nout,*)
      Flush (nout)
      ifail = 0
      Call x04caf('General',' ',n,n,ssp,ldssp,'Original matrix SSP  :',ifail)
      Write (nout,*)
      Flush (nout)
      ifail = 0
      Call x04caf('General',' ',n,n,r,ldr,'Original matrix R    :',ifail)
      Write (nout,*)

!     Calculate summaries on reduced number of variables
      ifail = 0
      Call g02cef(n,xbar,std,ssp,ldssp,r,ldr,m,korder,xbar2,std2,ssp2,ldssp2,  &
        r2,ldr2,ifail)

!     Display results
      Write (nout,fmt) 'New vector XBAR2 :   ', xbar2(1:m)
      Write (nout,*)
      Write (nout,fmt) 'New vector STD2  :   ', std2(1:m)
      Write (nout,*)
      Flush (nout)
      ifail = 0
      Call x04caf('General',' ',m,m,ssp2,ldssp2,'New matrix SSP2  :',ifail)
      Write (nout,*)
      Flush (nout)
      ifail = 0
      Call x04caf('General',' ',m,m,r2,ldr2,'New matrix R2    :',ifail)

99999 Format (A,I0,A)
    End Program g02cefe


g02cffe.f90

    Program g02cffe

!     G02CFF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: g02cff, nag_wp, x04caf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Integer                          :: i, ifail, ldr, ldssp, n
      Character (80)                   :: fmt
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: r(:,:), ssp(:,:), std(:), xbar(:)
      Integer, Allocatable             :: korder(:), kwork(:)
!     .. Executable Statements ..
      Write (nout,*) 'G02CFF Example Program Results'
      Write (nout,*)

!     Skip heading in data file
      Read (nin,*)

!     Read in the problem size
      Read (nin,*) n

      ldr = n
      ldssp = n
      Allocate (r(ldr,n),ssp(ldssp,n),std(n),xbar(n),korder(n),kwork(n))

!     Read in data
      Read (nin,*) xbar(1:n)
      Read (nin,*) std(1:n)
      Read (nin,*)(ssp(i,1:n),i=1,n)
      Read (nin,*)(r(i,1:n),i=1,n)

!     Read in the reordering vector
      Read (nin,*) korder(1:n)

!     Format for displaying vectors
      Write (fmt,99999) '(1x,A,', n, '(1X,F10.4))'

!     Display data
      Write (nout,fmt) 'Original vector XBAR :   ', xbar(1:n)
      Write (nout,*)
      Write (nout,fmt) 'Original vector STD  :   ', std(1:n)
      Write (nout,*)
      Flush (nout)
      ifail = 0
      Call x04caf('General',' ',n,n,ssp,ldssp,'Original matrix SSP  :',ifail)
      Write (nout,*)
      Flush (nout)
      ifail = 0
      Call x04caf('General',' ',n,n,r,ldr,'Original matrix R    :',ifail)
      Write (nout,*)

!     Reorder the results
      ifail = 0
      Call g02cff(n,korder,xbar,std,ssp,ldssp,r,ldr,kwork,ifail)

!     Display results
      Write (nout,fmt) 'New vector XBAR :   ', xbar(1:n)
      Write (nout,*)
      Write (nout,fmt) 'New vector STD  :   ', std(1:n)
      Write (nout,*)
      Flush (nout)
      ifail = 0
      Call x04caf('General',' ',n,n,ssp,ldssp,'New matrix SSP  :',ifail)
      Write (nout,*)
      Flush (nout)
      ifail = 0
      Call x04caf('General',' ',n,n,r,ldr,'New matrix R    :',ifail)

99999 Format (A,I0,A)
    End Program g02cffe


g02cgfe.f90

    Program g02cgfe

!     G02CGF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: g02cgf, nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Integer                          :: i, ifail, k, k1, ldc, ldcoef, ldr,   &
                                          ldrinv, ldssp, ldwkz, n
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: c(:,:), coef(:,:), r(:,:),           &
                                          rinv(:,:), ssp(:,:), wkz(:,:),       &
                                          xbar(:)
      Real (Kind=nag_wp)               :: con(3), reslt(13)
!     .. Executable Statements ..
      Write (nout,*) 'G02CGF Example Program Results'
      Write (nout,*)

!     Skip heading in data file
      Read (nin,*)

!     Read in problem size
      Read (nin,*) n, k
      k1 = k + 1
      ldr = k1
      ldssp = k1
      ldc = k
      ldcoef = k
      ldrinv = k
      ldwkz = k
      Allocate (c(ldc,k),coef(ldcoef,3),r(ldr,k1),rinv(ldrinv,k),              &
        ssp(ldssp,k1),wkz(ldwkz,k),xbar(k1))

!     Read in data
      Read (nin,*) xbar(1:k1)
      Read (nin,*)(ssp(i,1:k1),i=1,k1)
      Read (nin,*)(r(i,1:k1),i=1,k1)

!     Display data
      Write (nout,*) 'Means:'
      Write (nout,99999)(i,xbar(i),i=1,k1)
      Write (nout,*)
      Write (nout,*) 'Sums of squares and cross-products about means:'
      Write (nout,99998)(i,i=1,k1)
      Write (nout,99997)(i,ssp(i,1:k1),i=1,k1)
      Write (nout,*)
      Write (nout,*) 'Correlation coefficients:'
      Write (nout,99998)(i,i=1,k1)
      Write (nout,99997)(i,r(i,1:k1),i=1,k1)
      Write (nout,*)

!     Fit multiple linear regression model
      ifail = 0
      Call g02cgf(n,k1,k,xbar,ssp,ldssp,r,ldr,reslt,coef,ldcoef,con,rinv,      &
        ldrinv,c,ldc,wkz,ldwkz,ifail)

!     Display results
      Write (nout,*) 'Vble     Coef       Std err      t-value'
      Write (nout,99996)(i,coef(i,1:3),i=1,k)
      Write (nout,*)
      Write (nout,99995) 'Const', con(1:3)
      Write (nout,*)
      Write (nout,*) 'Analysis of regression table :-'
      Write (nout,*)
      Write (nout,*)                                                           &
        '      Source        Sum of squares  D.F.    Mean square     F-value'
      Write (nout,*)
      Write (nout,99994) 'Due to regression', reslt(1:4)
      Write (nout,99994) 'About  regression', reslt(5:7)
      Write (nout,99994) 'Total            ', reslt(8:9)
      Write (nout,*)
      Write (nout,99993) 'Standard error of estimate =', reslt(10)
      Write (nout,99993) 'Multiple correlation (R)   =', reslt(11)
      Write (nout,99993) 'Determination (R squared)  =', reslt(12)
      Write (nout,99993) 'Corrected R squared        =', reslt(13)
      Write (nout,*)
      Write (nout,*) 'Inverse of correlation matrix of independent variables:'
      Write (nout,99992)(i,i=1,k)
      Write (nout,99991)(i,rinv(i,1:k),i=1,k)
      Write (nout,*)
      Write (nout,*) 'Modified inverse matrix:'
      Write (nout,99992)(i,i=1,k)
      Write (nout,99991)(i,c(i,1:k),i=1,k)

99999 Format (1X,I4,F10.4)
99998 Format (1X,3I10)
99997 Format (1X,I4,3F10.4)
99996 Format (1X,I3,3F12.4)
99995 Format (1X,A,F11.4,2F13.4)
99994 Format (1X,A,F14.4,F8.0,2F14.4)
99993 Format (1X,A,F8.4)
99992 Format (1X,2I10)
99991 Format (1X,I4,2F10.4)
    End Program g02cgfe


g02chfe.f90

    Program g02chfe

!     G02CHF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: g02chf, nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Integer                          :: i, ifail, k, k1, ldcoef, ldcz, ldrz, &
                                          ldrznv, ldsspz, ldwkz, n
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: coef(:,:), cz(:,:), rz(:,:),         &
                                          rznv(:,:), sspz(:,:), wkz(:,:)
      Real (Kind=nag_wp)               :: reslt(13)
!     .. Executable Statements ..
      Write (nout,*) 'G02CHF Example Program Results'
      Write (nout,*)

!     Skip heading in data file
      Read (nin,*)

!     Read in the problem size
      Read (nin,*) n, k
      k1 = k + 1
      ldcoef = k
      ldcz = k
      ldrz = k1
      ldrznv = k
      ldsspz = k1
      ldwkz = k
      Allocate (coef(ldcoef,3),cz(ldcz,k),rz(ldrz,k1),rznv(ldrznv,k),          &
        sspz(ldsspz,k1),wkz(ldwkz,k))

!     Read in data
      Read (nin,*)(sspz(i,1:k1),i=1,k1)
      Read (nin,*)(rz(i,1:k1),i=1,k1)

!     Display data
      Write (nout,*) 'Sums of squares and cross-products about zero:'
      Write (nout,99999)(i,i=1,k1)
      Write (nout,99998)(i,sspz(i,1:k1),i=1,k1)
      Write (nout,*)
      Write (nout,*) 'Correlation-like coefficients:'
      Write (nout,99999)(i,i=1,k1)
      Write (nout,99998)(i,rz(i,1:k1),i=1,k1)
      Write (nout,*)

!     Fit multiple linear regression model
      ifail = 0
      Call g02chf(n,k1,k,sspz,ldsspz,rz,ldrz,reslt,coef,ldcoef,rznv,ldrznv,cz, &
        ldcz,wkz,ldwkz,ifail)

!     Display results
      Write (nout,*) 'Vble     Coef       Std err      t-value'
      Write (nout,99997)(i,coef(i,1:3),i=1,k)
      Write (nout,*)
      Write (nout,*) 'Analysis of regression table :-'
      Write (nout,*)
      Write (nout,*)                                                           &
        '      Source        Sum of squares  D.F.    Mean square     F-value'
      Write (nout,*)
      Write (nout,99996) 'Due to regression', reslt(1:4)
      Write (nout,99996) 'About  regression', reslt(5:7)
      Write (nout,99996) 'Total            ', reslt(8:9)
      Write (nout,*)
      Write (nout,99995) 'Standard error of estimate =', reslt(10)
      Write (nout,99995) 'Multiple correlation (R)   =', reslt(11)
      Write (nout,99995) 'Determination (R squared)  =', reslt(12)
      Write (nout,99995) 'Corrected R squared        =', reslt(13)
      Write (nout,*)
      Write (nout,*) 'Inverse of correlation matrix of independent variables:'
      Write (nout,99994)(i,i=1,k)
      Write (nout,99993)(i,rznv(i,1:k),i=1,k)
      Write (nout,*)
      Write (nout,*) 'Modified inverse matrix:'
      Write (nout,99994)(i,i=1,k)
      Write (nout,99993)(i,cz(i,1:k),i=1,k)

99999 Format (1X,3I10)
99998 Format (1X,I4,3F10.4)
99997 Format (1X,I3,3F12.4)
99996 Format (1X,A,F14.4,F8.0,2F14.4)
99995 Format (1X,A,F8.4)
99994 Format (1X,2I10)
99993 Format (1X,I4,2F10.4)
    End Program g02chfe


g02dafe.f90

    Program g02dafe

!     G02DAF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: g02buf, g02daf, nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: aic, arsq, en, mult, rsq, rss, sw,   &
                                          tol
      Integer                          :: i, idf, ifail, ip, irank, ldq, ldx,  &
                                          lwt, m, n
      Logical                          :: svd
      Character (1)                    :: mean, weight
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: b(:), cov(:), h(:), p(:), q(:,:),    &
                                          res(:), se(:), wk(:), wt(:), x(:,:), &
                                          y(:)
      Real (Kind=nag_wp)               :: c(1), wmean(1)
      Integer, Allocatable             :: isx(:)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: count, log, real
!     .. Executable Statements ..
      Write (nout,*) 'G02DAF Example Program Results'
      Write (nout,*)

!     Skip heading in data file
      Read (nin,*)

!     Read in the problem size
      Read (nin,*) n, m, weight, mean

      If (weight=='W' .Or. weight=='w') Then
        lwt = n
      Else
        lwt = 0
      End If
      ldx = n
      Allocate (x(ldx,m),y(n),wt(lwt),isx(m))

!     Read in data
      If (lwt>0) Then
        Read (nin,*)(x(i,1:m),y(i),wt(i),i=1,n)
      Else
        Read (nin,*)(x(i,1:m),y(i),i=1,n)
      End If

!     Read in variable inclusion flags
      Read (nin,*) isx(1:m)

!     Calculate IP
      ip = count(isx(1:m)>0)
      If (mean=='M' .Or. mean=='m') Then
        ip = ip + 1
      End If

      ldq = n
      Allocate (b(ip),cov((ip*ip+ip)/2),h(n),p(ip*(ip+                         &
        2)),q(ldq,ip+1),res(n),se(ip),wk(ip*ip+5*(ip-1)))

!     Use suggested value for tolerance
      tol = 0.000001E0_nag_wp

!     Fit general linear regression model
      ifail = -1
      Call g02daf(mean,weight,n,x,ldx,m,isx,ip,y,wt,rss,idf,b,se,cov,res,h,q,  &
        ldq,svd,irank,p,tol,wk,ifail)
      If (ifail/=0) Then
        If (ifail/=5) Then
          Go To 100
        End If
      End If

!     Calculate (weighted) total sums of squares, adjusted for mean if
!     required
!     If in G02DAF, an intercept is added to the regression by including a
!     column of 1's in X, rather than by using the MEAN argument then
!     MEAN = 'M' should be used in this call to G02BUF.
      ifail = 0
      Call g02buf(mean,weight,n,1,y,n,wt,sw,wmean,c,ifail)

!     Get effective number of observations (=N if there are no zero weights)
      en = real(idf+irank,kind=nag_wp)

!     Calculate R-squared, corrected R-squared and AIC
      rsq = 1.0_nag_wp - rss/c(1)
      If (mean=='M' .Or. mean=='m') Then
        mult = (en-1.0E0_nag_wp)/(en-real(irank,kind=nag_wp))
      Else
        mult = en/(en-real(irank,kind=nag_wp))
      End If
      arsq = 1.0_nag_wp - mult*(1.0_nag_wp-rsq)
      aic = en*log(rss/en) + 2.0_nag_wp*real(irank,kind=nag_wp)

!     Display results
      If (svd) Then
        Write (nout,99999) 'Model not of full rank, rank = ', irank
        Write (nout,*)
      End If
      Write (nout,99998) 'Residual sum of squares = ', rss
      Write (nout,99999) 'Degrees of freedom      = ', idf
      Write (nout,99998) 'R-squared               = ', rsq
      Write (nout,99998) 'Adjusted R-squared      = ', arsq
      Write (nout,99998) 'AIC                     = ', aic
      Write (nout,*)
      Write (nout,*) 'Variable   Parameter estimate   Standard error'
      Write (nout,*)
      If (ifail==0) Then
        Write (nout,99997)(i,b(i),se(i),i=1,ip)
      Else
        Write (nout,99996)(i,b(i),i=1,ip)
      End If
      Write (nout,*)
      Write (nout,*) '   Obs          Residuals              H'
      Write (nout,*)
      Write (nout,99997)(i,res(i),h(i),i=1,n)

100   Continue

99999 Format (1X,A,I4)
99998 Format (1X,A,E12.4)
99997 Format (1X,I6,2E20.4)
99996 Format (1X,I6,E20.4)
    End Program g02dafe


g02dcfe.f90

    Program g02dcfe

!     G02DCF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: g02daf, g02dcf, g02ddf, nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: rss, tol, wt, y
      Integer                          :: i, idf, ifail, ip, irank, ix, ldq,   &
                                          ldxm, lwt, m, n
      Logical                          :: svd
      Character (1)                    :: mean, update, weight
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: b(:), cov(:), h(:), p(:), q(:,:),    &
                                          res(:), se(:), wk(:), wtm(:), x(:),  &
                                          xm(:,:), ym(:)
      Integer, Allocatable             :: isx(:)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: count
!     .. Executable Statements ..
      Write (nout,*) 'G02DCF Example Program Results'
      Write (nout,*)

!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) n, m, weight, mean

      If (weight=='W' .Or. weight=='w') Then
        lwt = n
      Else
        lwt = 0
      End If
      ldxm = n
      Allocate (xm(ldxm,m),ym(n),wtm(lwt),isx(m),x(m))

!     Read in data
      If (lwt>0) Then
        Read (nin,*)(xm(i,1:m),ym(i),wtm(i),i=1,n)
      Else
        Read (nin,*)(xm(i,1:m),ym(i),i=1,n)
      End If

!     Read in variable inclusion flags
      Read (nin,*) isx(1:m)

!     Calculate IP
      ip = count(isx>0)
      If (mean=='M' .Or. mean=='m') Then
        ip = ip + 1
      End If

      ldq = n
      Allocate (b(ip),cov((ip*ip+ip)/2),h(n),p(ip*(ip+                         &
        2)),q(ldq,ip+1),res(n),se(ip),wk(ip*ip+5*(ip-1)))

!     Use suggested value for tolerance
      tol = 0.000001E0_nag_wp

!     Fit initial model using G02DAF
      ifail = 0
      Call g02daf(mean,weight,n,xm,ldxm,m,isx,ip,ym,wtm,rss,idf,b,se,cov,res,  &
        h,q,ldq,svd,irank,p,tol,wk,ifail)

!     Display results from initial model fit
      Write (nout,*) 'Results from initial model fit using G02DAF'
      If (svd) Then
        Write (nout,*)
        Write (nout,*) 'Model not of full rank'
      End If
      Write (nout,99999) 'Residual sum of squares = ', rss
      Write (nout,99998) 'Degrees of freedom = ', idf
      Write (nout,*)
      Write (nout,*) 'Variable   Parameter estimate   ', 'Standard error'
      Write (nout,*)
      Write (nout,99997)(i,b(i),se(i),i=1,ip)

!     Updating data is held in X consecutively
      ix = 1

!     Add or delete observations supplied in the data file
u_lp: Do
        Read (nin,*,Iostat=ifail) update
        If (ifail/=0) Then
          Exit u_lp
        End If

        If (lwt>0) Then
          Read (nin,*) x(1:m), y, wt
        Else
          Read (nin,*) x(1:m), y
        End If

!       Update the regression
        ifail = 0
        Call g02dcf(update,mean,weight,m,isx,q,ldq,ip,x,ix,y,wt,rss,wk,ifail)

!       Display titles and update observation count
        Write (nout,*)
        Select Case (update)
        Case ('a','A')
          Write (nout,*) 'Results from adding an observation using G02DCF'
          n = n + 1
        Case ('d','D')
          Write (nout,*) 'Results from dropping an observation using G02DCF'
          n = n - 1
        Case Default
          Write (nout,*) 'Unknown update flag read in from data file'
          Go To 100
        End Select

!       Recalculate the parameter estimates etc
        ifail = 0
        Call g02ddf(n,ip,q,ldq,rss,idf,b,se,cov,svd,irank,p,tol,wk,ifail)

!       Display updated results
        Write (nout,99999) 'Residual sum of squares = ', rss
        Write (nout,99998) 'Degrees of freedom = ', idf
        Write (nout,*)
        Write (nout,*) 'Variable   Parameter estimate   ', 'Standard error'
        Write (nout,*)
        Write (nout,99997)(i,b(i),se(i),i=1,ip)
      End Do u_lp

100   Continue

99999 Format (1X,A,E12.4)
99998 Format (1X,A,I4)
99997 Format (1X,I6,2E20.4)
    End Program g02dcfe


g02ddfe.f90

    Program g02ddfe

!     G02DDF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: g02ddf, g02def, nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: rss, tol
      Integer                          :: i, idf, ifail, ip, irank, ldq, lwt,  &
                                          m, n
      Logical                          :: svd
      Character (1)                    :: weight
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: b(:), cov(:), p(:), q(:,:), se(:),   &
                                          wk(:), wt(:), x(:,:)
!     .. Executable Statements ..
      Write (nout,*) 'G02DDF Example Program Results'
      Write (nout,*)

!     Skip heading in data file
      Read (nin,*)

!     Read in the problem size
      Read (nin,*) n, m, weight

      If (weight=='W' .Or. weight=='w') Then
        lwt = n
      Else
        lwt = 0
      End If
      ldq = n
      Allocate (b(m),cov(m*(m+1)/2),p(m*(m+2)),q(ldq,m+1),se(m),wk(m*m+5*m),wt &
        (n),x(n,m))

!     Read in data
      If (lwt>0) Then
        Read (nin,*)(x(i,1:m),q(i,1),wt(i),i=1,n)
      Else
        Read (nin,*)(x(i,1:m),q(i,1),i=1,n)
      End If

!     Use suggested value for tolerance
      tol = 0.000001E0_nag_wp

!     Fit general linear regression model, adding each variable in turn
      ip = 0
      Do i = 1, m
        ifail = -1
        Call g02def(weight,n,ip,q,ldq,p,wt,x(1,i),rss,tol,ifail)
        If (ifail==0) Then
          ip = ip + 1
        Else If (ifail==3) Then
          Write (nout,99996) ' * Variable ', ip,                               &
            ' is linear combination of previous columns'
          Write (nout,99996) '   so it has not been added'
        Else
          Go To 100
        End If
      End Do

!     Get G02DDF to calculate RSS
      rss = 0.0E0_nag_wp

!     Calculate parameter estimates, RSS etc
      ifail = 0
      Call g02ddf(n,ip,q,ldq,rss,idf,b,se,cov,svd,irank,p,tol,wk,ifail)

!     Display results
      If (svd) Then
        Write (nout,*) 'Model not of full rank'
        Write (nout,*)
      End If
      Write (nout,99999) 'Residual sum of squares = ', rss
      Write (nout,99998) 'Degrees of freedom = ', idf
      Write (nout,*)
      Write (nout,*) 'Variable   Parameter estimate   Standard error'
      Write (nout,*)
      Write (nout,99997)(i,b(i),se(i),i=1,ip)

100   Continue

99999 Format (1X,A,E12.4)
99998 Format (1X,A,I4)
99997 Format (1X,I6,2E20.4)
99996 Format (1X,A,I0,A)
    End Program g02ddfe


g02defe.f90

    Program g02defe

!     G02DEF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: g02ddf, g02def, nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: rss, rsst, tol
      Integer                          :: i, idf, ifail, ip, irank, ldq, lwt,  &
                                          m, n
      Logical                          :: svd
      Character (1)                    :: weight
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: b(:), cov(:), p(:), q(:,:), se(:),   &
                                          wk(:), wt(:), x(:)
!     .. Executable Statements ..
      Write (nout,*) 'G02DEF Example Program Results'
      Write (nout,*)

!     Skip heading in data file
      Read (nin,*)

!     Read in the problem size
      Read (nin,*) n, m, weight

      If (weight=='W' .Or. weight=='w') Then
        lwt = n
      Else
        lwt = 0
      End If
      ldq = n
      Allocate (b(m),cov(m*(m+1)/2),p(m*(m+2)),q(ldq,m+1),se(m),wk(m*m+5*m),wt &
        (n),x(n))

!     Read in the dependent variable, Y, and store in first column of Q
      Read (nin,*) q(1:n,1)

!     Read in weights
      If (lwt>0) Then
        Read (nin,*) wt(1:n)
      End If

!     Use suggested value for tolerance
      tol = 0.000001E0_nag_wp

!     Loop over each of the supplied variables
      ip = 0
u_lp: Do
        Read (nin,*,Iostat=ifail) x(1:n)
        If (ifail/=0) Then
          Exit u_lp
        End If

!       Add the new variable to the model
        ifail = -1
        Call g02def(weight,n,ip,q,ldq,p,wt,x,rss,tol,ifail)
        If (ifail/=0) Then
          If (ifail==3) Then
            Write (nout,99999) ' * Variable ', ip,                             &
              ' is linear combination of previous columns'
            Write (nout,*) '   so it has not been added'
            Write (nout,*)
            Cycle u_lp
          Else
            Go To 100
          End If
        End If

        ip = ip + 1
        Write (nout,99999) 'Variable ', ip, ' added'

!       Get G02DDF to recalculate RSS
        rsst = 0.0E0_nag_wp

!       Calculate the parameter estimates
        ifail = 0
        Call g02ddf(n,ip,q,ldq,rsst,idf,b,se,cov,svd,irank,p,tol,wk,ifail)

        If (svd) Then
          Write (nout,*) 'Model not of full rank'
          Write (nout,*)
        End If
        Write (nout,99998) 'Residual sum of squares = ', rsst
        Write (nout,99999) 'Degrees of freedom = ', idf
        Write (nout,*)
        Write (nout,*) 'Variable   Parameter estimate   Standard error'
        Write (nout,*)
        Write (nout,99997)(i,b(i),se(i),i=1,ip)
        Write (nout,*)
      End Do u_lp

100   Continue

99999 Format (1X,A,I0,A)
99998 Format (1X,A,E13.4)
99997 Format (1X,I6,2E20.4)
    End Program g02defe


g02dffe.f90

    Program g02dffe

!     G02DFF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: g02daf, g02ddf, g02dff, nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: rss, tol
      Integer                          :: i, idf, ifail, indx, ip, irank, ldq, &
                                          ldx, lwk, lwt, m, n
      Logical                          :: svd
      Character (1)                    :: mean, weight
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: b(:), cov(:), h(:), p(:), q(:,:),    &
                                          res(:), se(:), wk(:), wt(:), x(:,:), &
                                          y(:)
      Integer, Allocatable             :: isx(:)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: max
!     .. Executable Statements ..
      Write (nout,*) 'G02DFF Example Program Results'
      Write (nout,*)

!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) n, m, weight, mean

      If (weight=='W' .Or. weight=='w') Then
        lwt = n
      Else
        lwt = 0
      End If
      ldx = n
      Allocate (x(ldx,m),isx(m),y(n),wt(lwt))

!     Read in data
      If (lwt>0) Then
        Read (nin,*)(x(i,1:m),y(i),wt(i),i=1,n)
      Else
        Read (nin,*)(x(i,1:m),y(i),i=1,n)
      End If

!     Include all variables in the model
      isx(1:m) = 1
      ip = m
      If (mean=='M' .Or. mean=='m') Then
        ip = ip + 1
      End If

      lwk = max(5*(ip-1)+ip*ip,2*ip)
      ldq = n
      Allocate (b(ip),se(ip),cov(ip*(ip+1)/2),res(n),h(n),q(ldq,ip+1),p(2*ip+  &
        ip*ip),wk(lwk))

!     Use suggested value for tolerance
      tol = 0.000001E0_nag_wp

!     Fit general linear regression model
      ifail = 0
      Call g02daf(mean,weight,n,x,ldx,m,isx,ip,y,wt,rss,idf,b,se,cov,res,h,q,  &
        ldq,svd,irank,p,tol,wk,ifail)

!     Display results from G02DAF
      Write (nout,*) 'Results from full model'
      If (svd) Then
        Write (nout,*) 'Model not of full rank'
        Write (nout,*)
      End If
      Write (nout,99999) 'Residual sum of squares = ', rss
      Write (nout,99998) 'Degrees of freedom = ', idf
      Write (nout,*)

!     Loop over list of variables to drop
u_lp: Do
        Read (nin,*,Iostat=ifail) indx
        If (ifail/=0) Then
          Exit u_lp
        End If

        If (ip<=0) Then
          Write (nout,*) 'No terms left in model'
          Exit u_lp
        End If

!       Drop variable INDX from the model
        ifail = 0
        Call g02dff(ip,q,ldq,indx,rss,wk,ifail)

        ip = ip - 1
        Write (nout,99998) 'Variable', indx, ' dropped'

!       Calculate parameter estimates etc
        ifail = 0
        Call g02ddf(n,ip,q,ldq,rss,idf,b,se,cov,svd,irank,p,tol,wk,ifail)

!       Display the results for model with variable INDX dropped
        Write (nout,99999) 'Residual sum of squares = ', rss
        Write (nout,99998) 'Degrees of freedom = ', idf
        Write (nout,*)
        Write (nout,*) 'Parameter estimate   Standard error'
        Write (nout,*)
        Write (nout,99997)(b(i),se(i),i=1,ip)
      End Do u_lp

99999 Format (1X,A,E13.4)
99998 Format (1X,A,I4,A)
99997 Format (1X,E15.4,E20.4)
    End Program g02dffe


g02dgfe.f90

    Program g02dgfe

!     G02DGF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: g02daf, g02dgf, nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: rss, tol
      Integer                          :: i, idf, ifail, ip, irank, ldq, ldx,  &
                                          lwk, lwt, m, n
      Logical                          :: svd
      Character (1)                    :: mean, weight
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: b(:), cov(:), h(:), oy(:), p(:),     &
                                          q(:,:), res(:), se(:), wk(:), wt(:), &
                                          x(:,:), y(:)
      Integer, Allocatable             :: isx(:)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: count
!     .. Executable Statements ..
      Write (nout,*) 'G02DGF Example Program Results'
      Write (nout,*)

!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) n, m, weight, mean

      If (weight=='W' .Or. weight=='w') Then
        lwt = n
      Else
        lwt = 0
      End If
      ldx = n
      Allocate (x(ldx,m),isx(m),oy(n),y(n),wt(lwt))

!     Read in data
      If (lwt>0) Then
        Read (nin,*)(x(i,1:m),oy(i),wt(i),i=1,n)
      Else
        Read (nin,*)(x(i,1:m),oy(i),i=1,n)
      End If

!     Read in variable inclusion flags
      Read (nin,*) isx(1:m)

!     Calculate IP
      ip = count(isx(1:m)>0)
      If (mean=='M' .Or. mean=='m') Then
        ip = ip + 1
      End If

      lwk = 5*(ip-1) + ip*ip
      ldq = n
      Allocate (b(ip),se(ip),cov(ip*(ip+1)/2),res(n),h(n),q(ldq,ip+1),p(2*ip+  &
        ip*ip),wk(lwk))

!     Use suggested value for tolerance
      tol = 0.000001E0_nag_wp

!     Fit general linear regression model to first dependent variable
      ifail = 0
      Call g02daf(mean,weight,n,x,ldx,m,isx,ip,oy,wt,rss,idf,b,se,cov,res,h,q, &
        ldq,svd,irank,p,tol,wk,ifail)

!     Display results for model fit to original dependent variable
      Write (nout,*) 'Results for original y-variable using G02DAF'
      Write (nout,*)
      If (svd) Then
        Write (nout,*) 'Model not of full rank'
        Write (nout,*)
      End If
      Write (nout,99999) 'Residual sum of squares = ', rss
      Write (nout,99998) 'Degrees of freedom = ', idf
      Write (nout,*)
      Write (nout,*) 'Variable   Parameter estimate   Standard error'
      Write (nout,*)
      Write (nout,99997)(i,b(i),se(i),i=1,ip)
      Write (nout,*)

!     Read in the new dependent variable
      Read (nin,*) y(1:n)

!     Fit same model to different dependent variable
      ifail = 0
      Call g02dgf(weight,n,wt,rss,ip,irank,cov,q,ldq,svd,p,y,b,se,res,wk,      &
        ifail)

!     Display results for model fit to new dependent variable
      Write (nout,*) 'Results for second y-variable using G02DGF'
      Write (nout,*)
      Write (nout,99999) 'Residual sum of squares = ', rss
      Write (nout,99998) 'Degrees of freedom = ', idf
      Write (nout,*)
      Write (nout,*) 'Variable   Parameter estimate   ', 'Standard error'
      Write (nout,*)
      Write (nout,99997)(i,b(i),se(i),i=1,ip)

99999 Format (1X,A,E12.4)
99998 Format (1X,A,I4)
99997 Format (1X,I6,2E20.4)
    End Program g02dgfe


g02dkfe.f90

    Program g02dkfe

!     G02DKF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: g02daf, g02dkf, nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: rss, tol
      Integer                          :: i, iconst, idf, ifail, ip, irank,    &
                                          ldc, ldq, ldx, lwk, lwt, m, n, tlwk
      Logical                          :: svd
      Character (1)                    :: mean, weight
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: b(:), c(:,:), cov(:), h(:), p(:),    &
                                          q(:,:), res(:), se(:), wk(:), wt(:), &
                                          x(:,:), y(:)
      Integer, Allocatable             :: isx(:)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: count
!     .. Executable Statements ..
      Write (nout,*) 'G02DKF Example Program Results'
      Write (nout,*)

!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) n, m, weight, mean

!     Read in data
      If (weight=='W' .Or. weight=='w') Then
        lwt = n
      Else
        lwt = 0
      End If
      ldx = n
      Allocate (x(ldx,m),isx(m),y(n),wt(lwt))

      If (lwt>0) Then
        Read (nin,*)(x(i,1:m),y(i),wt(i),i=1,n)
      Else
        Read (nin,*)(x(i,1:m),y(i),i=1,n)
      End If

!     Read in variable inclusion flags
      Read (nin,*) isx(1:m)

!     Calculate IP
      ip = count(isx>0)
      If (mean=='M' .Or. mean=='m') Then
        ip = ip + 1
      End If

      lwk = 5*(ip-1) + ip*ip
      ldq = n
      ldc = ip
      Allocate (b(ip),se(ip),cov(ip*(ip+1)/2),res(n),h(n),q(ldq,ip+1),p(2*ip+  &
        ip*ip),wk(lwk),c(ldc,ip))

!     Use suggested value for tolerance
      tol = 0.000001E0_nag_wp

!     Fit general linear regression model
      ifail = 0
      Call g02daf(mean,weight,n,x,ldx,m,isx,ip,y,wt,rss,idf,b,se,cov,res,h,q,  &
        ldq,svd,irank,p,tol,wk,ifail)

!     Display the initial estimates
      Write (nout,*) 'Estimates from G02DAF'
      Write (nout,*)
      Write (nout,99999) 'Residual sum of squares = ', rss
      Write (nout,99998) 'Degrees of freedom = ', idf
      Write (nout,*)
      Write (nout,*) 'Variable    Parameter estimate   Standard error'
      Write (nout,*)
      Write (nout,99997)(i,b(i),se(i),i=1,ip)

!     Read in constraints
      iconst = ip - irank
      Read (nin,*)(c(i,1:iconst),i=1,ip)

      tlwk = 2*ip*ip + ip*iconst + 2*iconst*iconst + 4*iconst
      If (tlwk>lwk) Then
!       Reallocate workspace
        Deallocate (wk)
        Allocate (wk(tlwk))
      End If

!     Re-estimate the parameters given the constraints
      ifail = 0
      Call g02dkf(ip,iconst,p,c,ldc,b,rss,idf,se,cov,wk,ifail)

!     Display the results
      Write (nout,*)
      Write (nout,*) 'Estimates from G02DKF using constraints'
      Write (nout,*)
      Write (nout,*) 'Variable    Parameter estimate   Standard error'
      Write (nout,*)
      Write (nout,99997)(i,b(i),se(i),i=1,ip)

99999 Format (1X,A,E13.3)
99998 Format (1X,A,I4)
99997 Format (1X,I6,2E20.3)
    End Program g02dkfe


g02dnfe.f90

    Program g02dnfe

!     G02DNF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: g02daf, g02dnf, nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: rss, sestat, stat, t, tol
      Integer                          :: i, idf, ifail, ip, irank, ldq, ldx,  &
                                          lwk, lwt, m, n
      Logical                          :: est, svd
      Character (1)                    :: mean, weight
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: b(:), cov(:), f(:), h(:), p(:),      &
                                          q(:,:), res(:), se(:), wk(:), wt(:), &
                                          x(:,:), y(:)
      Integer, Allocatable             :: isx(:)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: count, max
!     .. Executable Statements ..
      Write (nout,*) 'G02DNF Example Program Results'
      Write (nout,*)

!     Skip heading in data file
      Read (nin,*)

!     Read in the problem size
      Read (nin,*) n, m, weight, mean

      If (weight=='W' .Or. weight=='w') Then
        lwt = n
      Else
        lwt = 0
      End If
      ldx = n
      Allocate (x(ldx,m),isx(m),y(n),wt(lwt))

      If (lwt>0) Then
        Read (nin,*)(x(i,1:m),y(i),wt(i),i=1,n)
      Else
        Read (nin,*)(x(i,1:m),y(i),i=1,n)
      End If

!     Read in variable inclusion flags
      Read (nin,*) isx(1:m)

!     Calculate IP
      ip = count(isx(1:m)>0)
      If (mean=='M' .Or. mean=='m') Then
        ip = ip + 1
      End If

      lwk = max(5*(ip-1)+ip*ip,ip)
      ldq = n
      Allocate (b(ip),se(ip),cov(ip*(ip+1)/2),res(n),h(n),q(ldq,ip+1),p(2*ip+  &
        ip*ip),wk(lwk),f(ip))

!     Use suggested value for tolerance
      tol = 0.000001E0_nag_wp

!     Fit general linear regression model
      ifail = 0
      Call g02daf(mean,weight,n,x,ldx,m,isx,ip,y,wt,rss,idf,b,se,cov,res,h,q,  &
        ldq,svd,irank,p,tol,wk,ifail)

!     Display initial parameter estimates
      Write (nout,*) 'Estimates from G02DAF'
      Write (nout,*)
      Write (nout,99999) 'Residual sum of squares = ', rss
      Write (nout,99998) 'Degrees of freedom = ', idf
      Write (nout,*)
      Write (nout,*) 'Variable   Parameter estimate   Standard error'
      Write (nout,*)
      Write (nout,99997)(i,b(i),se(i),i=1,ip)
      Write (nout,*)

      i = 0
estfn_lp: Do
        Read (nin,*,Iostat=ifail) f(1:ip)
        If (ifail/=0) Then
          Exit estfn_lp
        End If

        i = i + 1

!       Compute the estimable function
        ifail = -1
        Call g02dnf(ip,irank,b,cov,p,f,est,stat,sestat,t,tol,wk,ifail)
        If (ifail/=0) Then
          If (ifail/=2) Then
            Go To 100
          End If
        End If

!       Display results
        Write (nout,99996) 'Function ', i
        Write (nout,*)
        Write (nout,99995) f(1:ip)
        Write (nout,*)
        If (est) Then
          Write (nout,99994) 'STAT = ', stat, ' SE = ', sestat, ' T = ', t
        Else
          Write (nout,*) 'Function not estimable'
        End If
        Write (nout,*)
      End Do estfn_lp

100   Continue

99999 Format (1X,A,E12.4)
99998 Format (1X,A,I4)
99997 Format (1X,I6,2E20.4)
99996 Format (1X,A,I4)
99995 Format (1X,5F8.2)
99994 Format (1X,A,F10.4,A,F10.4,A,F10.4)
    End Program g02dnfe


g02eafe.f90

    Program g02eafe

!     G02EAF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: g02eaf, nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6, vnlen = 3
!     .. Local Scalars ..
      Integer                          :: i, ifail, k, ldmodl, ldx, lwt, m, n, &
                                          nmod
      Character (1)                    :: mean, weight
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: rss(:), wk(:), wt(:), x(:,:), y(:)
      Integer, Allocatable             :: isx(:), mrank(:), nterms(:)
      Character (vnlen), Allocatable   :: modl(:,:), vname(:)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: count, max
!     .. Executable Statements ..
      Write (nout,*) 'G02EAF Example Program Results'
      Write (nout,*)

!     Skip heading in data file
      Read (nin,*)

!     Read in the problem size
      Read (nin,*) n, m, mean, weight

      If (weight=='W' .Or. weight=='w') Then
        lwt = n
      Else
        lwt = 0
      End If
      ldx = n
      Allocate (x(ldx,m),vname(m),isx(m),y(n),wt(lwt))

!     Read in data
      If (lwt>0) Then
        Read (nin,*)(x(i,1:m),y(i),wt(i),i=1,n)
      Else
        Read (nin,*)(x(i,1:m),y(i),i=1,n)
      End If

!     Read in variable inclusion flags
      Read (nin,*) isx(1:m)

!     Read in first VNLEN characters of the variable names
      Read (nin,*) vname(1:m)

!     Calculate the number of free variables
      k = count(isx(1:m)==1)

      ldmodl = max(m,2**k)
      Allocate (modl(ldmodl,m),rss(ldmodl),nterms(ldmodl),mrank(ldmodl),wk(n*( &
        m+1)))

!     Calculate residual sums of squares for all possible models
      ifail = 0
      Call g02eaf(mean,weight,n,m,x,ldx,vname,isx,y,wt,nmod,modl,ldmodl,rss,   &
        nterms,mrank,wk,ifail)

!     Display results
      Write (nout,*) 'Number of     RSS    RANK  MODL'
      Write (nout,*) 'parameters'
      Do i = 1, nmod
        Write (nout,99999) nterms(i), rss(i), mrank(i), modl(i,1:nterms(i))
      End Do

99999 Format (1X,I8,F11.4,I4,3X,5(1X,A))
    End Program g02eafe


g02ecfe.f90

    Program g02ecfe

!     G02ECF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: g02eaf, g02ecf, nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6, vnlen = 3
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: sigsq, tss
      Integer                          :: i, ifail, k, ldmodl, ldx, lwt, m, n, &
                                          nmod
      Character (1)                    :: mean, weight
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: cp(:), rsq(:), rss(:), wk(:), wt(:), &
                                          x(:,:), y(:)
      Integer, Allocatable             :: isx(:), mrank(:), nterms(:)
      Character (vnlen), Allocatable   :: modl(:,:), vname(:)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: count, max, real
!     .. Executable Statements ..
      Write (nout,*) 'G02ECF Example Program Results'
      Write (nout,*)

!     Skip heading in data file
      Read (nin,*)

!     Read in the problem size
      Read (nin,*) n, m, mean, weight

      If (weight=='W' .Or. weight=='w') Then
        lwt = n
      Else
        lwt = 0
      End If
      ldx = n
      Allocate (x(ldx,m),wt(lwt),y(n),isx(m),vname(m))

!     Read in data
      If (lwt>0) Then
        Read (nin,*)(x(i,1:m),y(i),wt(i),i=1,n)
      Else
        Read (nin,*)(x(i,1:m),y(i),i=1,n)
      End If

!     Read in variable inclusion flags
      Read (nin,*) isx(1:m)

!     Read in first VNLEN characters of the variable names
      Read (nin,*) vname(1:m)

!     Calculate the number of free variables
      k = count(isx(1:m)==1)

      ldmodl = max(m,2**k)
      Allocate (modl(ldmodl,m),rss(ldmodl),nterms(ldmodl),mrank(ldmodl),wk(n*( &
        m+1)))

!     Calculate residual sums of squares
      ifail = 0
      Call g02eaf(mean,weight,n,m,x,ldx,vname,isx,y,wt,nmod,modl,ldmodl,rss,   &
        nterms,mrank,wk,ifail)

!     Extract total sums of squares
      tss = rss(1)

!     Calculate best estimate of true variance from full model
      sigsq = rss(nmod)/real(n-nterms(nmod)-1,kind=nag_wp)

      Allocate (rsq(nmod),cp(nmod))

!     Calculate R-squared and Mallows Cp
      ifail = 0
      Call g02ecf('M',n,sigsq,tss,nmod,nterms,rss,rsq,cp,ifail)

!     Display results
      Write (nout,*) 'Number of     CP      RSQ         MODEL'
      Write (nout,*) 'parameters'
      Write (nout,*)
      Do i = 1, nmod
        Write (nout,99999) nterms(i), cp(i), rsq(i), modl(i,1:nterms(i))
      End Do

99999 Format (1X,I7,F11.2,F8.4,1X,5(1X,A))
    End Program g02ecfe


g02eefe.f90

    Program g02eefe

!     G02EEF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: g02eef, nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6, vnlen = 3
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: chrss, f, fin, rss
      Integer                          :: i, idf, ifail, ifr, istep, ldq, ldx, &
                                          lwt, m, maxip, n, nterm
      Logical                          :: addvar
      Character (1)                    :: mean, weight
      Character (3)                    :: newvar
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: exss(:), p(:), q(:,:), wk(:), wt(:), &
                                          x(:,:), y(:)
      Integer, Allocatable             :: isx(:)
      Character (vnlen), Allocatable   :: free(:), model(:), vname(:)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: count
!     .. Executable Statements ..
      Write (nout,*) 'G02EEF Example Program Results'
      Write (nout,*)

!     Skip heading in data file
      Read (nin,*)

!     Read in the problem size and various control parameters
      Read (nin,*) n, m, mean, weight, fin

      If (weight=='W' .Or. weight=='w') Then
        lwt = n
      Else
        lwt = 0
      End If
      ldx = n
      Allocate (x(ldx,m),y(n),wt(lwt),isx(m),vname(m))

!     Read in data
      If (lwt>0) Then
        Read (nin,*)(x(i,1:m),y(i),wt(i),i=1,n)
      Else
        Read (nin,*)(x(i,1:m),y(i),i=1,n)
      End If

!     Read in variable inclusion flags
      Read (nin,*) isx(1:m)

!     Read in first VNLEN characters of the variable names
      Read (nin,*) vname(1:m)

!     Calculate the maximum number of parameters in the model
      maxip = count(isx(1:m)>0)
      If (mean=='M' .Or. mean=='m') Then
        maxip = maxip + 1
      End If

      ldq = n
      Allocate (model(maxip),free(maxip),exss(maxip),q(ldq,maxip+2),           &
        p(maxip+1),wk(2*maxip))

!     Loop over each variable, attempting to add each in turn
      istep = 0
      Do i = 1, m
!       Fit the linear regression model
        ifail = 0
        Call g02eef(istep,mean,weight,n,m,x,ldx,vname,isx,maxip,y,wt,fin,      &
          addvar,newvar,chrss,f,model,nterm,rss,idf,ifr,free,exss,q,ldq,p,wk,  &
          ifail)

!       Display the results at each step
        Write (nout,99999) 'Step ', istep
        If (.Not. addvar) Then
          Write (nout,99998) 'No further variables added maximum F =', f
          Write (nout,99993) 'Free variables:  ', free(1:ifr)
          Write (nout,*)                                                       &
            'Change in residual sums of squares for free variables:'
          Write (nout,99992) '                 ', exss(1:ifr)
          Go To 100
        Else
          Write (nout,99997) 'Added variable is ', newvar
          Write (nout,99996) 'Change in residual sum of squares =', chrss
          Write (nout,99998) 'F Statistic = ', f
          Write (nout,*)
          Write (nout,99995) 'Variables in model:', model(1:nterm)
          Write (nout,*)
          Write (nout,99994) 'Residual sum of squares = ', rss
          Write (nout,99999) 'Degrees of freedom = ', idf
          Write (nout,*)
          If (ifr==0) Then
            Write (nout,*) 'No free variables remaining'
            Go To 100
          End If
          Write (nout,99993) 'Free variables:  ', free(1:ifr)
          Write (nout,*)                                                       &
            'Change in residual sums of squares for free variables:'
          Write (nout,99992) '                 ', exss(1:ifr)
          Write (nout,*)
        End If
      End Do

100   Continue

99999 Format (1X,A,I2)
99998 Format (1X,A,F7.2)
99997 Format (1X,2A)
99996 Format (1X,A,E13.4)
99995 Format (1X,A,6(1X,A))
99994 Format (1X,A,E13.4)
99993 Format (1X,A,6(6X,A))
99992 Format (1X,A,6(F9.4))
    End Program g02eefe


g02effe.f90

    Program g02effe

!     G02EFF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: g02buf, g02eff, g02efh, nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: fin, fout, rms, rsq, sw, tau
      Integer                          :: df, i, ifail, ldz, liuser, lruser,   &
                                          m, m1, monlev, n
      Character (1)                    :: mean, weight
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: b(:), c(:), ruser(:), se(:),         &
                                          wmean(:), z(:,:)
      Real (Kind=nag_wp)               :: wt(1)
      Integer, Allocatable             :: isx(:), iuser(:)
!     .. Executable Statements ..
      Write (nout,*) 'G02EFF Example Program Results'
      Write (nout,*)
      Flush (nout)

!     Skip heading in data file
      Read (nin,*)

!     Read in the problem size and various control parameters
      Read (nin,*) n, m, fin, fout, tau, monlev

!     Not using the user supplied arrays RUSER and IUSER
      liuser = 0
      lruser = 0

      m1 = m + 1
      ldz = n
      Allocate (wmean(m1),c(m1*(m+2)/2),isx(m),b(m1),se(m1),iuser(liuser),     &
        ruser(lruser),z(ldz,m1))

!     Read in augmented design matrix Z = (X | Y)
      Read (nin,*)(z(i,1:m1),i=1,n)

!     Read in variable inclusion flags
      Read (nin,*) isx(1:m)

!     No weights in this example
      weight = 'U'

!     Compute upper-triangular sums of squares and cross-products of deviations
!     from the mean for the augmented matrix
      mean = 'M'
      ifail = 0
      Call g02buf(mean,weight,n,m1,z,ldz,wt,sw,wmean,c,ifail)

!     Perform stepwise selection of variables.
      ifail = 0
      Call g02eff(m,n,wmean,c,sw,isx,fin,fout,tau,b,se,rsq,rms,df,monlev,      &
        g02efh,iuser,ruser,ifail)

!     Display results
      Write (nout,*)
      Write (nout,99999) 'Fitted Model Summary'
      Write (nout,99999) 'Term              Estimate   Standard Error'
      Write (nout,99998) 'Intercept:', b(1), se(1)
      Do i = 1, m
        If (isx(i)==1 .Or. isx(i)==2) Then
          Write (nout,99997) 'Variable:', i, b(i+1), se(i+1)
        End If
      End Do
      Write (nout,*)
      Write (nout,99996) 'RMS:', rms

99999 Format (1X,A)
99998 Format (1X,A,4X,1P,E12.3,5X,E12.3)
99997 Format (1X,A,1X,I3,1X,1P,E12.3,5X,E12.3)
99996 Format (1X,A,1X,1P,E12.3)
    End Program g02effe


g02fafe.f90

    Program g02fafe

!     G02FAF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: g02faf, nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: rms
      Integer                          :: i, ifail, ip, ldsres, n, nres
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: h(:), res(:), sres(:,:)
!     .. Executable Statements ..
      Write (nout,*) 'G02FAF Example Program Results'
      Write (nout,*)

!     Skip heading in data file
      Read (nin,*)

!     Read in the problem size
      Read (nin,*) n, ip, nres, rms

      ldsres = nres
      Allocate (res(nres),h(nres),sres(ldsres,4))

!     Read in the data
      Read (nin,*)(res(i),h(i),i=1,nres)

!     Calculate standardised residuals
      ifail = 0
      Call g02faf(n,ip,nres,res,h,rms,sres,ldsres,ifail)

!     Display results
      Write (nout,*) '        Internally    Internally'
      Write (nout,*)                                                           &
        'Obs.   standardized  standardized   Cook''s D   Atkinson''s T'
      Write (nout,*) '         residuals     residuals'
      Write (nout,*)
      Write (nout,99999)(i,sres(i,1:4),i=1,nres)

99999 Format (1X,I2,4F13.3)
    End Program g02fafe


g02fcfe.f90

    Program g02fcfe

!     G02FCF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: g02fcf, nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: d, pdl, pdu
      Integer                          :: i, ifail, ip, n
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: res(:), work(:)
!     .. Executable Statements ..
      Write (nout,*) 'G02FCF Example Program Results'
      Write (nout,*)

!     Skip heading in data file
      Read (nin,*)

!     Read in the problem size
      Read (nin,*) n, ip

      Allocate (res(n),work(n))

!     Read in the data
      Read (nin,*)(res(i),i=1,n)

!     Calculate the statistic
      ifail = 0
      Call g02fcf(n,ip,res,d,pdl,pdu,work,ifail)

!     Display the results
      Write (nout,99999) ' Durbin-Watson statistic ', d
      Write (nout,*)
      Write (nout,99998) ' Lower and upper bound ', pdl, pdu

99999 Format (1X,A,F10.4)
99998 Format (1X,A,2F10.4)
    End Program g02fcfe


g02gafe.f90

    Program g02gafe

!     G02GAF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: g02gaf, nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: a, eps, rss, s, tol
      Integer                          :: i, idf, ifail, ip, iprint, irank,    &
                                          ldv, ldx, lwt, m, maxit, n
      Character (1)                    :: link, mean, offset, weight
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: b(:), cov(:), se(:), v(:,:), wk(:),  &
                                          wt(:), x(:,:), y(:)
      Integer, Allocatable             :: isx(:)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: count
!     .. Executable Statements ..
      Write (nout,*) 'G02GAF Example Program Results'
      Write (nout,*)

!     Skip heading in data file
      Read (nin,*)

!     Read in the problem size
      Read (nin,*) link, mean, offset, weight, n, m, s

      If (weight=='W' .Or. weight=='w') Then
        lwt = n
      Else
        lwt = 0
      End If
      ldx = n
      Allocate (x(ldx,m),isx(m),y(n),wt(lwt))

!     Read in the data
      If (lwt>0) Then
        Read (nin,*)(x(i,1:m),y(i),wt(i),i=1,n)
      Else
        Read (nin,*)(x(i,1:m),y(i),i=1,n)
      End If

!     Read in variable inclusion flags
      Read (nin,*) isx(1:m)

!     Calculate IP
      ip = count(isx(1:m)>0)
      If (mean=='M' .Or. mean=='m') Then
        ip = ip + 1
      End If

!     Read in power for exponential link
      If (link=='E' .Or. link=='e') Then
        Read (nin,*) a
      End If

      ldv = n
      Allocate (b(ip),se(ip),cov(ip*(ip+1)/2),v(ldv,ip+7),wk((ip*ip+3*ip+      &
        22)/2))

!     Read in the offset
      If (offset=='Y' .Or. offset=='y') Then
        Read (nin,*) v(1:n,7)
      End If

!     Read in control parameters
      Read (nin,*) iprint, eps, tol, maxit

!     Fit the generalized linear model with Normal errors
      ifail = -1
      Call g02gaf(link,mean,offset,weight,n,x,ldx,m,isx,ip,y,wt,s,a,rss,idf,b, &
        irank,se,cov,v,ldv,tol,maxit,iprint,eps,wk,ifail)
      If (ifail/=0) Then
        If (ifail<6) Then
          Go To 100
        End If
      End If

!     Display results
      Write (nout,99999) 'Residual sum of squares     = ', rss
      Write (nout,99998) ' Residual degrees of freedom = ', idf
      Write (nout,*)
      Write (nout,*) '      Estimate    Standard error'
      Write (nout,*)
      Write (nout,99997)(b(i),se(i),i=1,ip)
      Write (nout,*)
      Write (nout,*) '     Y        FV     Residual       H'
      Write (nout,*)
      Write (nout,99996)(y(i),v(i,2),v(i,5),v(i,6),i=1,n)

100   Continue

99999 Format (1X,A,E12.4)
99998 Format (1X,A,I2)
99997 Format (1X,2F14.4)
99996 Format (1X,F7.1,F10.2,F12.4,F10.3)
    End Program g02gafe


g02gbfe.f90

    Program g02gbfe

!     G02GBF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: g02gbf, nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: dev, eps, tol
      Integer                          :: i, idf, ifail, ip, iprint, irank,    &
                                          ldv, ldx, lwk, lwt, m, maxit, n
      Character (1)                    :: link, mean, offset, weight
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: b(:), cov(:), se(:), t(:), v(:,:),   &
                                          wk(:), wt(:), x(:,:), y(:)
      Integer, Allocatable             :: isx(:)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: count
!     .. Executable Statements ..
      Write (nout,*) 'G02GBF Example Program Results'
      Write (nout,*)

!     Skip heading in data file
      Read (nin,*)

!     Read in the problem size
      Read (nin,*) link, mean, offset, weight, n, m

      If (weight=='W' .Or. weight=='w') Then
        lwt = n
      Else
        lwt = 0
      End If
      ldx = n
      Allocate (x(ldx,m),y(n),t(n),wt(lwt),isx(m))

!     Read in data
      If (lwt>0) Then
        Read (nin,*)(x(i,1:m),y(i),t(i),wt(i),i=1,n)
      Else
        Read (nin,*)(x(i,1:m),y(i),t(i),i=1,n)
      End If

!     Read in variable inclusion flags
      Read (nin,*) isx(1:m)

!     Calculate IP
      ip = count(isx(1:m)>0)
      If (mean=='M' .Or. mean=='m') Then
        ip = ip + 1
      End If

      ldv = n
      lwk = (ip*ip+3*ip+22)/2
      Allocate (b(ip),se(ip),cov(ip*(ip+1)/2),v(ldv,ip+7),wk(lwk))

!     Read in the offset
      If (offset=='Y' .Or. offset=='y') Then
        Read (nin,*) v(1:n,7)
      End If

!     Read in the control parameters
      Read (nin,*) iprint, eps, tol, maxit

!     Fit generalized linear model with Binomial errors
      ifail = -1
      Call g02gbf(link,mean,offset,weight,n,x,ldx,m,isx,ip,y,t,wt,dev,idf,b,   &
        irank,se,cov,v,ldv,tol,maxit,iprint,eps,wk,ifail)
      If (ifail/=0) Then
        If (ifail<7) Then
          Go To 100
        End If
      End If

!     Display results
      Write (nout,99999) 'Deviance = ', dev
      Write (nout,99998) 'Degrees of freedom = ', idf
      Write (nout,*)
      Write (nout,*) '       Estimate     Standard error'
      Write (nout,*)
      Write (nout,99997)(b(i),se(i),i=1,ip)
      Write (nout,*)
      Write (nout,*) '       N          Y        FV      Residual      H'
      Write (nout,*)
      Write (nout,99996)(t(i),y(i),v(i,2),v(i,5),v(i,6),i=1,n)

100   Continue

99999 Format (1X,A,E12.4)
99998 Format (1X,A,I0)
99997 Format (1X,2F14.4)
99996 Format (1X,2F10.1,F10.2,F12.4,F10.3)
    End Program g02gbfe


g02gcfe.f90

    Program g02gcfe

!     G02GCF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: g02gcf, nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: a, dev, eps, tol
      Integer                          :: i, idf, ifail, ip, iprint, irank,    &
                                          ldv, ldx, lwk, lwt, m, maxit, n
      Character (1)                    :: link, mean, offset, weight
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: b(:), cov(:), se(:), v(:,:), wk(:),  &
                                          wt(:), x(:,:), y(:)
      Integer, Allocatable             :: isx(:)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: count
!     .. Executable Statements ..
      Write (nout,*) 'G02GCF Example Program Results'
      Write (nout,*)

!     Skip heading in data file
      Read (nin,*)

!     Read in the problem size
      Read (nin,*) link, mean, offset, weight, n, m

      If (weight=='W' .Or. weight=='w') Then
        lwt = n
      Else
        lwt = 0
      End If
      ldx = n
      Allocate (x(ldx,m),y(n),wt(lwt),isx(m))

!     Read in data
      If (lwt>0) Then
        Read (nin,*)(x(i,1:m),y(i),wt(i),i=1,n)
      Else
        Read (nin,*)(x(i,1:m),y(i),i=1,n)
      End If

!     Read in variable inclusion flags
      Read (nin,*) isx(1:m)

!     Calculate IP
      ip = count(isx(1:m)>0)
      If (mean=='M' .Or. mean=='m') Then
        ip = ip + 1
      End If

!     Read in power for exponential link
      If (link=='E' .Or. link=='e') Then
        Read (nin,*) a
      End If

      ldv = n
      lwk = (ip*ip+3*ip+22)/2
      Allocate (b(ip),se(ip),cov(ip*(ip+1)/2),v(ldv,ip+7),wk(lwk))

!     Read in the offset
      If (offset=='Y' .Or. offset=='y') Then
        Read (nin,*) v(1:n,7)
      End If

!     Read in control parameters
      Read (nin,*) iprint, eps, tol, maxit

!     Fit generalized linear model with Poisson errors
      ifail = -1
      Call g02gcf(link,mean,offset,weight,n,x,ldx,m,isx,ip,y,wt,a,dev,idf,b,   &
        irank,se,cov,v,ldv,tol,maxit,iprint,eps,wk,ifail)
      If (ifail/=0) Then
        If (ifail<7) Then
          Go To 100
        End If
      End If

!     Display results
      Write (nout,99999) 'Deviance = ', dev
      Write (nout,99998) 'Degrees of freedom = ', idf
      Write (nout,*)
      Write (nout,*) '      Estimate     Standard error'
      Write (nout,*)
      Write (nout,99997)(b(i),se(i),i=1,ip)
      Write (nout,*)
      Write (nout,*) '    Y        FV      Residual       H'
      Write (nout,*)
      Write (nout,99996)(y(i),v(i,2),v(i,5),v(i,6),i=1,n)

100   Continue

99999 Format (1X,A,E12.4)
99998 Format (1X,A,I0)
99997 Format (1X,2F14.4)
99996 Format (1X,F7.1,F10.2,F12.4,F10.3)
    End Program g02gcfe


g02gdfe.f90

    Program g02gdfe

!     G02GDF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: g02gdf, nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: a, dev, eps, s, tol
      Integer                          :: i, idf, ifail, ip, iprint, irank,    &
                                          ldv, ldx, lwk, lwt, m, maxit, n
      Character (1)                    :: link, mean, offset, weight
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: b(:), cov(:), se(:), v(:,:), wk(:),  &
                                          wt(:), x(:,:), y(:)
      Integer, Allocatable             :: isx(:)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: count
!     .. Executable Statements ..
      Write (nout,*) 'G02GDF Example Program Results'
      Write (nout,*)

!     Skip heading in data file
      Read (nin,*)

!     Read in the problem size
      Read (nin,*) link, mean, offset, weight, n, m, s

      If (weight=='W' .Or. weight=='w') Then
        lwt = n
      Else
        lwt = 0
      End If
      ldx = n
      Allocate (x(ldx,m),y(n),wt(lwt),isx(m))

!     Read in data
      If (lwt>0) Then
        Read (nin,*)(x(i,1:m),y(i),wt(i),i=1,n)
      Else
        Read (nin,*)(x(i,1:m),y(i),i=1,n)
      End If

!     Read in variable inclusion flags
      Read (nin,*) isx(1:m)

!     Calculate IP
      ip = count(isx(1:m)>0)
      If (mean=='M' .Or. mean=='m') Then
        ip = ip + 1
      End If

!     Read in power for exponential link
      If (link=='E' .Or. link=='e') Then
        Read (nin,*) a
      End If

      ldv = n
      lwk = (ip*ip+3*ip+22)/2
      Allocate (b(ip),se(ip),cov(ip*(ip+1)/2),v(ldv,ip+7),wk(lwk))

!     Read in the offset
      If (offset=='Y' .Or. offset=='y') Then
        Read (nin,*) v(1:n,7)
      End If

!     Read in control parameters
      Read (nin,*) iprint, eps, tol, maxit

!     Fit generalized linear model with Gamma errors
      ifail = -1
      Call g02gdf(link,mean,offset,weight,n,x,ldx,m,isx,ip,y,wt,s,a,dev,idf,b, &
        irank,se,cov,v,ldv,tol,maxit,iprint,eps,wk,ifail)
      If (ifail/=0) Then
        If (ifail<7) Then
          Go To 100
        End If
      End If

!     Display results
      Write (nout,99999) 'Deviance = ', dev
      Write (nout,99998) 'Degrees of freedom = ', idf
      Write (nout,*)
      Write (nout,*) '     Estimate     Standard error'
      Write (nout,*)
      Write (nout,99997)(b(i),se(i),i=1,ip)
      Write (nout,*)
      Write (nout,*) '     Y        FV     Residual        H'
      Write (nout,*)
      Write (nout,99996)(y(i),v(i,2),v(i,5),v(i,6),i=1,n)

100   Continue

99999 Format (1X,A,E12.4)
99998 Format (1X,A,I0)
99997 Format (1X,2F14.4)
99996 Format (1X,F7.1,F10.2,F12.4,F10.3)
    End Program g02gdfe


g02gkfe.f90

    Program g02gkfe

!     G02GKF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: g02gcf, g02gkf, nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: a, dev, eps, tol
      Integer                          :: i, iconst, idf, ifail, ip, iprint,   &
                                          irank, ldc, ldv, ldx, lwk, lwt, m,   &
                                          maxit, n
      Character (1)                    :: link, mean, offset, weight
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: b(:), c(:,:), cov(:), se(:), v(:,:), &
                                          wk(:), wt(:), x(:,:), y(:)
      Integer, Allocatable             :: isx(:)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: count
!     .. Executable Statements ..
      Write (nout,*) 'G02GKF Example Program Results'
      Write (nout,*)

!     Skip heading in data file
      Read (nin,*)

!     Read in the problem size
      Read (nin,*) link, mean, offset, weight, n, m

      If (weight=='W' .Or. weight=='w') Then
        lwt = n
      Else
        lwt = 0
      End If
      ldx = n
      Allocate (x(ldx,m),y(n),wt(lwt),isx(m))

!     Read in data
      If (lwt>0) Then
        Read (nin,*)(x(i,1:m),y(i),wt(i),i=1,n)
      Else
        Read (nin,*)(x(i,1:m),y(i),i=1,n)
      End If

!     Read in variable inclusion flags
      Read (nin,*) isx(1:m)

!     Calculate IP
      ip = count(isx(1:m)>0)
      If (mean=='M' .Or. mean=='m') Then
        ip = ip + 1
      End If

!     Read in power for exponential link
      If (link=='E' .Or. link=='e') Then
        Read (nin,*) a
      End If

      ldv = n
      lwk = (ip*ip+3*ip+22)/2
      Allocate (b(ip),se(ip),cov(ip*(ip+1)/2),v(ldv,ip+7),wk(lwk))

!     Read in the offset
      If (offset=='Y' .Or. offset=='y') Then
        Read (nin,*) v(1:n,7)
      End If

!     Read in control parameters
      Read (nin,*) iprint, eps, tol, maxit

!     Fit generalized linear model with Poisson errors
      ifail = -1
      Call g02gcf(link,mean,offset,weight,n,x,ldx,m,isx,ip,y,wt,a,dev,idf,b,   &
        irank,se,cov,v,ldv,tol,maxit,iprint,eps,wk,ifail)
      If (ifail/=0) Then
        If (ifail<7) Then
          Go To 100
        End If
      End If

!     Display initial results
      Write (nout,99999) 'Deviance = ', dev
      Write (nout,99998) 'Degrees of freedom = ', idf
      Write (nout,*)

!     Calculate the number of constraints required
      iconst = ip - irank

!     Going to reallocate workspace, so deallocate it
      Deallocate (wk)
      lwk = 2*ip*ip + ip*iconst + 2*iconst*iconst + 4*iconst

      ldc = ip
      Allocate (c(ldc,iconst),wk(lwk))

!     Read in constraints
      Read (nin,*,Iostat=ifail)(c(i,1:iconst),i=1,ip)
      If (ifail/=0) Then
        Write (nout,99996)                                                     &
          ' ** Insufficient constraints supplied, was expecting ', iconst
        Go To 100
      End If

!     Re-estimate the model given the constraints
      ifail = 0
      Call g02gkf(ip,iconst,v,ldv,c,ldc,b,1.0E0_nag_wp,se,cov,wk,ifail)

!     Display the constrained parameter estimates
      Write (nout,*) '      Estimate     Standard error'
      Write (nout,*)
      Write (nout,99997)(b(i),se(i),i=1,ip)

100   Continue

99999 Format (1X,A,E12.4)
99998 Format (1X,A,I2)
99997 Format (1X,2F14.4)
99996 Format (1X,A,I5)
    End Program g02gkfe


g02gnfe.f90

    Program g02gnfe

!     G02GNF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: g02gcf, g02gnf, nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: a, dev, eps, sestat, stat, tol, z
      Integer                          :: i, idf, ifail, ip, iprint, irank,    &
                                          ldv, ldx, lwk, lwt, m, maxit, n
      Logical                          :: est
      Character (1)                    :: link, mean, offset, weight
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: b(:), cov(:), f(:), se(:), v(:,:),   &
                                          wk(:), wt(:), x(:,:), y(:)
      Integer, Allocatable             :: isx(:)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: count, max
!     .. Executable Statements ..
      Write (nout,*) 'G02GNF Example Program Results'
      Write (nout,*)

!     Skip heading in data file
      Read (nin,*)

!     Read in the problem size
      Read (nin,*) link, mean, offset, weight, n, m

      If (weight=='W' .Or. weight=='w') Then
        lwt = n
      Else
        lwt = 0
      End If
      ldx = n
      Allocate (x(ldx,m),y(n),wt(lwt),isx(m))

!     Read in data
      If (lwt>0) Then
        Read (nin,*)(x(i,1:m),y(i),wt(i),i=1,n)
      Else
        Read (nin,*)(x(i,1:m),y(i),i=1,n)
      End If

!     Read in variable inclusion flags
      Read (nin,*) isx(1:m)

!     Calculate IP
      ip = count(isx(1:m)>0)
      If (mean=='M' .Or. mean=='m') Then
        ip = ip + 1
      End If

!     Read in power for exponential link
      If (link=='E' .Or. link=='e') Then
        Read (nin,*) a
      End If

      ldv = n
      lwk = max((ip*ip+3*ip+22)/2,ip)
      Allocate (b(ip),se(ip),cov(ip*(ip+1)/2),v(ldv,ip+7),wk(lwk),f(ip))

!     Read in the offset
      If (offset=='Y' .Or. offset=='y') Then
        Read (nin,*) v(1:n,7)
      End If

!     Read in control parameters
      Read (nin,*) iprint, eps, tol, maxit

!     Fit generalized linear model with Poisson errors
      ifail = -1
      Call g02gcf('L','M','N','U',n,x,ldx,m,isx,ip,y,wt,a,dev,idf,b,irank,se,  &
        cov,v,ldv,tol,maxit,iprint,eps,wk,ifail)
      If (ifail/=0) Then
        If (ifail<7) Then
          Go To 100
        End If
      End If

!     Display initial results
      Write (nout,99999) 'Deviance = ', dev
      Write (nout,99998) 'Degrees of freedom = ', idf
      Write (nout,*)
      Write (nout,*) '      Estimate     Standard error'
      Write (nout,*)
      Write (nout,99997)(b(i),se(i),i=1,ip)

!     Estimate the estimable functions
      i = 0
fun_lp: Do
!       Read in the function
        Read (nin,*,Iostat=ifail) f(1:ip)
        If (ifail/=0) Then
          Exit fun_lp
        End If

        i = i + 1

!       Estimate it
        ifail = -1
        Call g02gnf(ip,irank,b,cov,v,ldv,f,est,stat,sestat,z,tol,wk,ifail)
        If (ifail/=0) Then
          If (ifail/=2) Then
            Go To 100
          End If
        End If

!       Display results
        Write (nout,*)
        Write (nout,99996) 'Function ', i
        Write (nout,99995) f(1:ip)
        Write (nout,*)
        If (est) Then
          Write (nout,99994) 'STAT = ', stat, ' SE = ', sestat, ' Z = ', z
        Else
          Write (nout,*) 'Function not estimable'
        End If
      End Do fun_lp

100   Continue

99999 Format (1X,A,E12.4)
99998 Format (1X,A,I2)
99997 Format (1X,2F14.4)
99996 Format (1X,A,I4)
99995 Format (1X,5F8.2)
99994 Format (1X,A,F10.4,A,F10.4,A,F10.4)
    End Program g02gnfe


g02gpfe.f90

    Program g02gpfe

!     G02GPF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: g02gaf, g02gpf, nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: a, eps, rss, s, tol
      Integer                          :: i, idf, ifail, ip, iprint, irank,    &
                                          ldv, ldx, loff, lt, lwk, lwt, m,     &
                                          maxit, n, tldx
      Logical                          :: vfobs
      Character (1)                    :: errfn, link, mean, offset, weight
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: b(:), cov(:), eta(:), off(:),        &
                                          pred(:), se(:), seeta(:), sepred(:), &
                                          t(:), twt(:), tx(:,:), ty(:),        &
                                          v(:,:), wk(:), wt(:), x(:,:), y(:)
      Integer, Allocatable             :: isx(:)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: count
!     .. Executable Statements ..
      Write (nout,*) 'G02GPF Example Program Results'
      Write (nout,*)

!     Skip headings in data file
      Read (nin,*)
      Read (nin,*)

!     Read in training data for model that will be used for prediction
      Read (nin,*) link, mean, offset, weight, n, m, s

      If (weight=='W' .Or. weight=='w') Then
        lwt = n
      Else
        lwt = 0
      End If
      tldx = n
      Allocate (tx(tldx,m),ty(n),twt(lwt),isx(m))

!     Read in data
      If (lwt>0) Then
        Read (nin,*)(tx(i,1:m),ty(i),twt(i),i=1,n)
      Else
        Read (nin,*)(tx(i,1:m),ty(i),i=1,n)
      End If

!     Read in variable inclusion flags
      Read (nin,*) isx(1:m)

!     Calculate IP
      ip = count(isx(1:m)>0)
      If (mean=='M' .Or. mean=='m') Then
        ip = ip + 1
      End If

!     Read in power for exponential link
      If (link=='E' .Or. link=='e') Then
        Read (nin,*) a
      End If

      ldv = n
      lwk = (ip*ip+3*ip+22)/2
      Allocate (b(ip),se(ip),cov(ip*(ip+1)/2),v(ldv,ip+7),wk(lwk))

!     Read in the offset
      If (offset=='Y' .Or. offset=='y') Then
        Read (nin,*) v(1:n,7)
      End If

!     Read in control parameters
      Read (nin,*) iprint, eps, tol, maxit

!     Call routine to fit generalized linear model, with Normal errors,
!     to training data
      ifail = -1
      Call g02gaf(link,mean,offset,weight,n,tx,tldx,m,isx,ip,ty,twt,s,a,rss,   &
        idf,b,irank,se,cov,v,ldv,tol,maxit,iprint,eps,wk,ifail)
      If (ifail/=0) Then
        If (ifail<6) Then
          Go To 100
        End If
      End If

!     Display parameter estimates for training data
      Write (nout,99999) 'Residual sum of squares = ', rss
      Write (nout,99998) 'Degrees of freedom      = ', idf
      Write (nout,*)
      Write (nout,*) '      Estimate     Standard error'
      Write (nout,*)
      Write (nout,99997)(b(i),se(i),i=1,ip)

!     Skip second lot of headings in data file
      Read (nin,*)

!     Read in size of prediction data
      Read (nin,*) n, vfobs, offset, weight

!     Used G02GAF to fit training model, so error structure is normal is
!     do not require T array
      errfn = 'N'
      lt = 0

      ldx = n
      If (weight=='W' .Or. weight=='w') Then
        lwt = n
      Else
        lwt = 0
      End If
      If (offset=='Y' .Or. offset=='y') Then
        loff = n
      Else
        loff = 0
      End If
      Allocate (x(ldx,m),y(n),wt(lwt),off(loff),eta(n),seeta(n),pred(n),       &
        sepred(n),t(lt))

!     Read in predication data
      If (lwt>0) Then
        Read (nin,*)(x(i,1:m),wt(i),i=1,n)
      Else
        Read (nin,*)(x(i,1:m),i=1,n)
      End If

!     Read in offset for the prediction data
      If (offset=='Y' .Or. offset=='y') Then
        Read (nin,*) off(1:n)
      End If

!     Call prediction routine
      ifail = -1
      Call g02gpf(errfn,link,mean,offset,weight,n,x,ldx,m,isx,ip,t,off,wt,s,a, &
        b,cov,vfobs,eta,seeta,pred,sepred,ifail)
      If (ifail/=0) Then
        Write (nout,99995) ifail
        If (ifail/=22) Then
          Go To 100
        End If
      End If

!     Display predicted values
      Write (nout,*)
      Write (nout,*) '  I      ETA         SE(ETA)      Predicted  ',          &
        ' SE(Predicted)'
      Write (nout,*)
      Write (nout,99996)(i,eta(i),seeta(i),pred(i),sepred(i),i=1,n)

100   Continue

99999 Format (1X,A,E12.4)
99998 Format (1X,A,I0)
99997 Format (1X,2F14.4)
99996 Format (1X,I3,')',F10.5,3F14.5)
99995 Format (1X,A,I5)
    End Program g02gpfe


g02hafe.f90

    Program g02hafe

!     G02HAF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: g02haf, nag_wp, x04abf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: iset = 1, nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: cpsi, cucv, dchi, h1, h2, h3, sigma, &
                                          tol
      Integer                          :: i, ifail, indc, indw, ipsi, isigma,  &
                                          ldc, ldx, lwork, m, maxit, n, nadv,  &
                                          nitmon
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: c(:,:), rs(:), theta(:), wgt(:),     &
                                          work(:), x(:,:), y(:)
!     .. Executable Statements ..
      Write (nout,*) 'G02HAF Example Program Results'
      Write (nout,*)

!     Skip heading in data file
      Read (nin,*)

!     Read in the problem size
      Read (nin,*) n, m

      ldx = n
      ldc = m
      lwork = 4*n + m*(n+m)
      Allocate (x(ldx,m),y(n),theta(m),c(ldc,m),work(lwork),rs(n),wgt(n))

!     Read in data
      Read (nin,*)(x(i,1:m),y(i),i=1,n)

!     Read in control parameters
      Read (nin,*) indw, ipsi, isigma, nitmon, maxit, tol

!     Read in appropriate weight function parameters
      If (indw/=0) Then
        Read (nin,*) cucv, indc
      End If
      If (ipsi>0) Then
        If (ipsi==1) Then
          Read (nin,*) cpsi
        Else If (ipsi==2) Then
          Read (nin,*) h1, h2, h3
        End If
        If (isigma>0) Then
          Read (nin,*) dchi
        End If
      End If

!     Set the advisory channel to NOUT for monitoring information
      If (nitmon/=0) Then
        nadv = nout
        Call x04abf(iset,nadv)
      End If

!     Read in initial values
      Read (nin,*) sigma
      Read (nin,*) theta(1:m)

!     Perform M-estimate regression
      ifail = -1
      Call g02haf(indw,ipsi,isigma,indc,n,m,x,ldx,y,cpsi,h1,h2,h3,cucv,dchi,   &
        theta,sigma,c,ldc,rs,wgt,tol,maxit,nitmon,work,ifail)
      If (ifail/=0) Then
        If (ifail<7) Then
          Go To 100
        Else
          Write (nout,*)                                                       &
            '       Some of the following reslts may be unreliable'
        End If
      End If

!     Display results
      Write (nout,99999) 'Sigma = ', sigma
      Write (nout,*)
      Write (nout,*) '       THETA      Standard'
      Write (nout,*) '                   errors'
      Write (nout,99998)(theta(i),c(i,i),i=1,m)
      Write (nout,*)
      Write (nout,*) '     Weights     Residuals'
      Write (nout,99998)(wgt(i),rs(i),i=1,n)

100   Continue

99999 Format (1X,A,F10.4)
99998 Format (1X,F12.4,F13.4)
    End Program g02hafe


g02hbfe.f90

!   G02HBF Example Program Text
!   Mark 26 Release. NAG Copyright 2016.

    Module g02hbfe_mod

!     G02HBF Example Program Module:
!            Parameters and User-defined Routines

!     .. Use Statements ..
      Use nag_library, Only: nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Accessibility Statements ..
      Private
      Public                           :: ucv
!     .. Parameters ..
      Real (Kind=nag_wp), Parameter, Public :: one = 1.0_nag_wp
      Real (Kind=nag_wp), Parameter    :: two = 2.0_nag_wp
      Real (Kind=nag_wp), Parameter    :: zero = 0.0_nag_wp
      Integer, Parameter, Public       :: iset = 1, nin = 5, nout = 6
    Contains
      Function ucv(t)
!       UCV function for Krasker-Welsch weights

!       .. Use Statements ..
        Use nag_library, Only: s15abf, x01aaf, x02akf
!       .. Function Return Value ..
        Real (Kind=nag_wp)             :: ucv
!       .. Parameters ..
        Real (Kind=nag_wp), Parameter  :: ucvc = 2.5_nag_wp
!       .. Scalar Arguments ..
        Real (Kind=nag_wp), Intent (In) :: t
!       .. Local Scalars ..
        Real (Kind=nag_wp)             :: pc, pd, q, q2
        Integer                        :: ifail
!       .. Intrinsic Procedures ..
        Intrinsic                      :: exp, log, sqrt
!       .. Executable Statements ..
        ucv = one
        If (t/=zero) Then
          q = ucvc/t
          q2 = q*q
          ifail = 0
          pc = s15abf(q,ifail)
          If (q2<-log(x02akf())) Then
            pd = exp(-q2/two)/sqrt(x01aaf(zero)*two)
          Else
            pd = zero
          End If
          ucv = (two*pc-one)*(one-q2) + q2 - two*q*pd
        End If
        Return
      End Function ucv
    End Module g02hbfe_mod
    Program g02hbfe

!     G02HBF Example Main Program

!     .. Use Statements ..
      Use nag_library, Only: g02hbf, nag_wp, x04abf, x04ccf
      Use g02hbfe_mod, Only: iset, nin, nout, one, ucv
!     .. Implicit None Statement ..
      Implicit None
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: bd, bl, tol
      Integer                          :: i, ifail, la, ldx, m, maxit, n,      &
                                          nadv, nit, nitmon
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: a(:), wk(:), x(:,:), z(:)
!     .. Executable Statements ..
      Write (nout,*) 'G02HBF Example Program Results'
      Write (nout,*)
      Flush (nout)

!     Skip heading in data file
      Read (nin,*)

!     Read in the problem size
      Read (nin,*) n, m

      ldx = n
      la = (m+1)*m/2
      Allocate (x(ldx,m),a(la),wk(la),z(n))

!     Read in data
      Read (nin,*)(x(i,1:m),i=1,n)

!     Read in initial value of A
      Read (nin,*) a(1:la)

!     Read in control parameters
      Read (nin,*) nitmon, bl, bd, maxit, tol

!     Set the advisory channel to NOUT for monitoring information
      If (nitmon/=0) Then
        nadv = nout
        Call x04abf(iset,nadv)
      End If

!     Calculate A
      ifail = 0
      Call g02hbf(ucv,n,m,x,ldx,a,z,bl,bd,tol,maxit,nitmon,nit,wk,ifail)

!     Display results
      Write (nout,99999) 'G02HBF required ', nit, ' iterations to converge'
      Write (nout,*)
      Flush (nout)
      ifail = 0
      Call x04ccf('Lower','Non-Unit',m,a,'Matrix A',ifail)
      Write (nout,*)
      Write (nout,*) 'Vector Z'
      Write (nout,99998)(z(i),i=1,n)
      Write (nout,*)
      Write (nout,*) 'Vector of Krasker-Welsch weights'
      Write (nout,99998)(one/z(i),i=1,n)

99999 Format (1X,A,I0,A)
99998 Format (1X,F9.4)
    End Program g02hbfe


g02hdfe.f90

!   G02HDF Example Program Text
!   Mark 26 Release. NAG Copyright 2016.

    Module g02hdfe_mod

!     G02HDF Example Program Module:
!            Parameters and User-defined Routines

!     .. Use Statements ..
      Use nag_library, Only: nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Accessibility Statements ..
      Private
      Public                           :: betcal, chi, psi
!     .. Parameters ..
      Real (Kind=nag_wp), Parameter    :: dchi = 1.5_nag_wp
      Real (Kind=nag_wp), Parameter    :: one = 1.0_nag_wp
      Real (Kind=nag_wp), Parameter    :: two = 2.0_nag_wp
      Real (Kind=nag_wp), Parameter    :: zero = 0.0_nag_wp
      Integer, Parameter, Public       :: iset = 1, nin = 5, nout = 6
    Contains
      Function psi(t)

!       .. Function Return Value ..
        Real (Kind=nag_wp)             :: psi
!       .. Parameters ..
        Real (Kind=nag_wp), Parameter  :: c = 1.5_nag_wp
!       .. Scalar Arguments ..
        Real (Kind=nag_wp), Intent (In) :: t
!       .. Intrinsic Procedures ..
        Intrinsic                      :: abs
!       .. Executable Statements ..
        If (t<=-c) Then
          psi = -c
        Else If (abs(t)<c) Then
          psi = t
        Else
          psi = c
        End If
        Return
      End Function psi

      Function chi(t)

!       .. Function Return Value ..
        Real (Kind=nag_wp)             :: chi
!       .. Scalar Arguments ..
        Real (Kind=nag_wp), Intent (In) :: t
!       .. Local Scalars ..
        Real (Kind=nag_wp)             :: ps
!       .. Intrinsic Procedures ..
        Intrinsic                      :: abs
!       .. Executable Statements ..
        ps = dchi
        If (abs(t)<dchi) Then
          ps = t
        End If
        chi = ps*ps/two
        Return
      End Function chi

      Subroutine betcal(n,wgt,beta)
!       Calculate BETA for Schweppe type regression

!       .. Use Statements ..
        Use nag_library, Only: s15abf, x01aaf, x02akf
!       .. Scalar Arguments ..
        Real (Kind=nag_wp), Intent (Out) :: beta
        Integer, Intent (In)           :: n
!       .. Array Arguments ..
        Real (Kind=nag_wp), Intent (In) :: wgt(n)
!       .. Local Scalars ..
        Real (Kind=nag_wp)             :: amaxex, anormc, b, d2, dc, dw, dw2,  &
                                          pc, w2
        Integer                        :: i, ifail
!       .. Intrinsic Procedures ..
        Intrinsic                      :: exp, log, real, sqrt
!       .. Executable Statements ..
        amaxex = -log(x02akf())
        anormc = sqrt(x01aaf(zero)*two)
        d2 = dchi*dchi
        beta = zero
        Do i = 1, n
          w2 = wgt(i)*wgt(i)
          dw = wgt(i)*dchi
          ifail = 0
          pc = s15abf(dw,ifail)
          dw2 = dw*dw
          dc = zero
          If (dw2<amaxex) Then
            dc = exp(-dw2/two)/anormc
          End If
          b = (-dw*dc+pc-0.5_nag_wp)/w2 + (one-pc)*d2
          beta = b*w2/real(n,kind=nag_wp) + beta
        End Do
        Return
      End Subroutine betcal
    End Module g02hdfe_mod
    Program g02hdfe
!     G02HDF Example Main Program

!     .. Use Statements ..
      Use nag_library, Only: g02hdf, nag_wp, x04abf
      Use g02hdfe_mod, Only: betcal, chi, iset, nin, nout, psi
!     .. Implicit None Statement ..
      Implicit None
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: beta, eps, psip0, sigma, tol
      Integer                          :: i, ifail, indw, isigma, k, ldx, m,   &
                                          maxit, n, nadv, nit, nitmon
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: rs(:), theta(:), wgt(:), wk(:),      &
                                          x(:,:), y(:)
!     .. Executable Statements ..
      Write (nout,*) 'G02HDF Example Program Results'
      Write (nout,*)

!     Skip heading in data file
      Read (nin,*)

!     Read in the problem size
      Read (nin,*) n, m

      ldx = n
      Allocate (x(ldx,m),y(n),wgt(n),theta(m),rs(n),wk((m+4)*n))

!     Read in data
      Read (nin,*)(x(i,2:m),y(i),wgt(i),i=1,n)

!     Set first column of X to 1 for the constant term
      x(1:n,1) = 1.0E0_nag_wp

!     Set BETA
      Call betcal(n,wgt,beta)

!     Read in value for PSI(0)
      Read (nin,*) psip0

!     Read in control parameters
      Read (nin,*) indw, isigma, nitmon, maxit, tol, eps

!     Set the advisory channel to NOUT for monitoring information
      If (nitmon/=0) Then
        nadv = nout
        Call x04abf(iset,nadv)
      End If

!     Read in initial values
      Read (nin,*) sigma
      Read (nin,*) theta(1:m)

!     Perform bounded influence regression
      ifail = -1
      Call g02hdf(chi,psi,psip0,beta,indw,isigma,n,m,x,ldx,y,wgt,theta,k,      &
        sigma,rs,tol,eps,maxit,nitmon,nit,wk,ifail)
      If (ifail==7) Then
        Write (nout,*) 'Some of the following results may be unreliable'
      Else If (ifail/=0) Then
        Go To 100
      End If

!     Display results
      Write (nout,99999) 'G02HDF required ', nit, ' iterations to converge'
      Write (nout,99999) '                   K = ', k
      Write (nout,99998) '               Sigma = ', sigma
      Write (nout,*) '    THETA'
      Write (nout,99997)(theta(i),i=1,m)
      Write (nout,*)
      Write (nout,*) '  Weights  Residuals'
      Write (nout,99996)(wgt(i),rs(i),i=1,n)

100   Continue

99999 Format (1X,A,I0,A)
99998 Format (1X,A,F9.4)
99997 Format (1X,F9.4)
99996 Format (1X,2F9.4)
    End Program g02hdfe


g02hffe.f90

!   G02HFF Example Program Text
!   Mark 26 Release. NAG Copyright 2016.

    Module g02hffe_mod

!     G02HFF Example Program Module:
!            Parameters and User-defined Routines

!     .. Use Statements ..
      Use nag_library, Only: nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Accessibility Statements ..
      Private
      Public                           :: psi, psp
!     .. Parameters ..
      Real (Kind=nag_wp), Parameter    :: tc = 1.5_nag_wp
      Integer, Parameter, Public       :: nin = 5, nout = 6
    Contains
      Function psi(t)

!       .. Function Return Value ..
        Real (Kind=nag_wp)             :: psi
!       .. Scalar Arguments ..
        Real (Kind=nag_wp), Intent (In) :: t
!       .. Intrinsic Procedures ..
        Intrinsic                      :: abs
!       .. Executable Statements ..
        If (t<=-tc) Then
          psi = -tc
        Else If (abs(t)<tc) Then
          psi = t
        Else
          psi = tc
        End If
        Return
      End Function psi

      Function psp(t)

!       .. Function Return Value ..
        Real (Kind=nag_wp)             :: psp
!       .. Scalar Arguments ..
        Real (Kind=nag_wp), Intent (In) :: t
!       .. Intrinsic Procedures ..
        Intrinsic                      :: abs
!       .. Executable Statements ..
        psp = 0.0_nag_wp
        If (abs(t)<tc) Then
          psp = 1.0_nag_wp
        End If
        Return
      End Function psp
    End Module g02hffe_mod
    Program g02hffe

!     G02HFF Example Main Program

!     .. Use Statements ..
      Use nag_library, Only: g02hff, nag_wp, x04cbf
      Use g02hffe_mod, Only: nin, nout, psi, psp
!     .. Implicit None Statement ..
      Implicit None
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: sigma
      Integer                          :: i, ifail, indc, indw, ldc, ldx, m, n
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: c(:,:), rs(:), wgt(:), wk(:), x(:,:)
      Character (0)                    :: clabs(1), rlabs(1)
!     .. Executable Statements ..
      Write (nout,*) 'G02HFF Example Program Results'
      Write (nout,*)
      Flush (nout)

!     Skip heading in data file
      Read (nin,*)

!     Read in the problem size
      Read (nin,*) n, m

      ldx = n
      ldc = m
      Allocate (x(ldx,m),wgt(n),rs(n),wk(m*(n+m+1)+2*n),c(ldc,m))

!     Read in the data
      Read (nin,*)(x(i,1:m),i=1,n)

!     Read in SIGMA
      Read (nin,*) sigma

!     Read in weights and residuals
      Read (nin,*)(wgt(i),rs(i),i=1,n)

!     Read in control parameters
      Read (nin,*) indw, indc

!     Estimate variance-covariance matrix
      ifail = 0
      Call g02hff(psi,psp,indw,indc,sigma,n,m,x,ldx,rs,wgt,c,ldc,wk,ifail)

!     Display results
      ifail = 0
      Call x04cbf('General',' ',m,m,c,ldc,'F8.4','Covariance matrix','I',      &
        rlabs,'I',clabs,80,0,ifail)

    End Program g02hffe


g02hkfe.f90

    Program g02hkfe

!     G02HKF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: g02hkf, nag_wp, x04abf, x04ccf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: iset = 1, nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: eps, tol
      Integer                          :: i, ifail, j, ldx, m, maxit, n, nadv, &
                                          nit, nitmon
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: cov(:), theta(:), wk(:), x(:,:)
!     .. Executable Statements ..
      Write (nout,*) 'G02HKF Example Program Results'
      Write (nout,*)

!     Skip heading in data file
      Read (nin,*)

!     Read in the problem size and control parameters
      Read (nin,*) n, m

      ldx = n
      Allocate (x(ldx,m),cov(m*(m+1)/2),theta(m),wk(n+m*(m+5)/2))

!     Read in data
      Read (nin,*)(x(i,1:m),i=1,n)

!     Read in the control parameters
      Read (nin,*) nitmon, maxit, tol, eps

!     Set the advisory channel to NOUT for monitoring information
      If (nitmon/=0) Then
        nadv = nout
        Call x04abf(iset,nadv)
      End If

!     Compute robust estimate of variance / covariance matrix
      ifail = 0
      Call g02hkf(n,m,x,ldx,eps,cov,theta,maxit,nitmon,tol,nit,wk,ifail)

!     Display results
      Write (nout,99999) 'G02HKF required ', nit, ' iterations to converge'
      Write (nout,*)
      Flush (nout)
      ifail = 0
      Call x04ccf('Upper','Non-Unit',m,cov,'Covariance matrix',ifail)
      Write (nout,*)
      Write (nout,*) 'THETA'
      Write (nout,99998)(theta(j),j=1,m)

99999 Format (1X,A,I0,A)
99998 Format (1X,F10.3)
    End Program g02hkfe


g02hlfe.f90

!   G02HLF Example Program Text
!   Mark 26 Release. NAG Copyright 2016.

    Module g02hlfe_mod

!     G02HLF Example Program Module:
!            Parameters and User-defined Routines

!     .. Use Statements ..
      Use nag_library, Only: nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Accessibility Statements ..
      Private
      Public                           :: ucv
!     .. Parameters ..
      Integer, Parameter, Public       :: iset = 1, nin = 5, nout = 6
    Contains
      Subroutine ucv(t,ruser,u,ud,w,wd)

!       u function and derivative

!       .. Scalar Arguments ..
        Real (Kind=nag_wp), Intent (In) :: t
        Real (Kind=nag_wp), Intent (Out) :: u, ud, w, wd
!       .. Array Arguments ..
        Real (Kind=nag_wp), Intent (Inout) :: ruser(*)
!       .. Local Scalars ..
        Real (Kind=nag_wp)             :: cu, cw, t2
!       .. Executable Statements ..
        cu = ruser(1)
        u = 1.0_nag_wp
        ud = 0.0_nag_wp
        If (t/=0.0_nag_wp) Then
          t2 = t*t
          If (t2>cu) Then
            u = cu/t2
            ud = -2.0_nag_wp*u/t
          End If
        End If
!       w function and derivative
        cw = ruser(2)
        If (t>cw) Then
          w = cw/t
          wd = -w/t
        Else
          w = 1.0_nag_wp
          wd = 0.0_nag_wp
        End If
      End Subroutine ucv
    End Module g02hlfe_mod
    Program g02hlfe

!     G02HLF Example Main Program

!     .. Use Statements ..
      Use nag_library, Only: g02hlf, nag_wp, x04abf, x04ccf
      Use g02hlfe_mod, Only: iset, nin, nout, ucv
!     .. Implicit None Statement ..
      Implicit None
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: bd, bl, tol
      Integer                          :: i, ifail, indm, la, lcov, ldx,       &
                                          lruser, m, maxit, n, nadv, nit,      &
                                          nitmon
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: a(:), cov(:), ruser(:), theta(:),    &
                                          wk(:), wt(:), x(:,:)
!     .. Executable Statements ..
      Write (nout,*) 'G02HLF Example Program Results'
      Write (nout,*)

!     Skip heading in data file
      Read (nin,*)

!     Read in the problem size
      Read (nin,*) n, m

      ldx = n
      lruser = 2
      la = (m+1)*m/2
      lcov = la
      Allocate (x(ldx,m),ruser(lruser),cov(lcov),a(la),wt(n),theta(m),wk(2*m))

!     Read in the data
      Read (nin,*)(x(i,1:m),i=1,n)

!     Read in the initial value of A
      Read (nin,*) a(1:la)

!     Read in the initial value of THETA
      Read (nin,*) theta(1:m)

!     Read in the values of the parameters of the ucv functions
      Read (nin,*) ruser(1:lruser)

!     Read in the control parameters
      Read (nin,*) indm, nitmon, bl, bd, maxit, tol

!     Set the advisory channel to NOUT for monitoring information
      If (nitmon/=0) Then
        nadv = nout
        Call x04abf(iset,nadv)
      End If

!     Compute robust estimate of variance / covariance matrix
      ifail = 0
      Call g02hlf(ucv,ruser,indm,n,m,x,ldx,cov,a,wt,theta,bl,bd,maxit,nitmon,  &
        tol,nit,wk,ifail)

!     Display results
      Write (nout,99999) 'G02HLF required ', nit, ' iterations to converge'
      Write (nout,*)
      Flush (nout)
      ifail = 0
      Call x04ccf('Upper','Non-Unit',m,cov,'Robust covariance matrix',ifail)
      Write (nout,*)
      Write (nout,*) 'Robust estimates of THETA'
      Write (nout,99998) theta(1:m)

99999 Format (1X,A,I0,A)
99998 Format (1X,F10.3)
    End Program g02hlfe


g02hmfe.f90

!   G02HMF Example Program Text
!   Mark 26 Release. NAG Copyright 2016.

    Module g02hmfe_mod

!     G02HMF Example Program Module:
!            Parameters and User-defined Routines

!     .. Use Statements ..
      Use nag_library, Only: nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Accessibility Statements ..
      Private
      Public                           :: ucv
!     .. Parameters ..
      Integer, Parameter, Public       :: iset = 1, nin = 5, nout = 6
    Contains
      Subroutine ucv(t,ruser,u,w)

!       u function

!       .. Scalar Arguments ..
        Real (Kind=nag_wp), Intent (In) :: t
        Real (Kind=nag_wp), Intent (Out) :: u, w
!       .. Array Arguments ..
        Real (Kind=nag_wp), Intent (Inout) :: ruser(*)
!       .. Local Scalars ..
        Real (Kind=nag_wp)             :: cu, cw, t2
!       .. Executable Statements ..
        cu = ruser(1)
        u = 1.0_nag_wp
        If (t/=0.0_nag_wp) Then
          t2 = t*t
          If (t2>cu) Then
            u = cu/t2
          End If
        End If
!       w function
        cw = ruser(2)
        If (t>cw) Then
          w = cw/t
        Else
          w = 1.0_nag_wp
        End If
      End Subroutine ucv
    End Module g02hmfe_mod
    Program g02hmfe

!     G02HMF Example Main Program

!     .. Use Statements ..
      Use nag_library, Only: g02hmf, nag_wp, x04abf, x04ccf
      Use g02hmfe_mod, Only: iset, nin, nout, ucv
!     .. Implicit None Statement ..
      Implicit None
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: bd, bl, tol
      Integer                          :: i, ifail, indm, la, lcov, ldx,       &
                                          lruser, m, maxit, n, nadv, nit,      &
                                          nitmon
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: a(:), cov(:), ruser(:), theta(:),    &
                                          wk(:), wt(:), x(:,:)
!     .. Executable Statements ..
      Write (nout,*) 'G02HMF Example Program Results'
      Write (nout,*)

!     Skip heading in data file
      Read (nin,*)

!     Read in the problem size
      Read (nin,*) n, m

      ldx = n
      lruser = 2
      la = ((m+1)*m)/2
      lcov = la
      Allocate (x(ldx,m),ruser(lruser),cov(lcov),a(la),wt(n),theta(m),wk(2*m))

!     Read in data
      Read (nin,*)(x(i,1:m),i=1,n)

!     Read in the initial value of A
      Read (nin,*) a(1:la)

!     Read in the initial value of THETA
      Read (nin,*) theta(1:m)

!     Read in the values of the parameters of the ucv functions
      Read (nin,*) ruser(1:lruser)

!     Read in the control parameters
      Read (nin,*) indm, nitmon, bl, bd, maxit, tol

!     Set the advisory channel to NOUT for monitoring information
      If (nitmon/=0) Then
        nadv = nout
        Call x04abf(iset,nadv)
      End If

!     Compute robust estimate of variance / covariance matrix
      ifail = 0
      Call g02hmf(ucv,ruser,indm,n,m,x,ldx,cov,a,wt,theta,bl,bd,maxit,nitmon,  &
        tol,nit,wk,ifail)

!     Display results
      Write (nout,99999) 'G02HMF required ', nit, ' iterations to converge'
      Write (nout,*)
      Flush (nout)
      ifail = 0
      Call x04ccf('Upper','Non-Unit',m,cov,'Robust covariance matrix',ifail)
      Write (nout,*)
      Write (nout,*) 'Robust estimates of THETA'
      Write (nout,99998) theta(1:m)

99999 Format (1X,A,I0,A)
99998 Format (1X,F10.3)
    End Program g02hmfe


g02jafe.f90

    Program g02jafe

!     G02JAF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: g02jaf, nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: reml, tol
      Integer                          :: cwid, df, fint, i, ifail, j, k, l,   &
                                          lb, lddat, maxit, n, ncol, nff, nfv, &
                                          nrf, nrv, nvpr, rint, svid, warn,    &
                                          yvid
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: b(:), dat(:,:), gamma(:), se(:)
      Integer, Allocatable             :: fvid(:), levels(:), rvid(:), vpr(:)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: max
!     .. Executable Statements ..
      Write (nout,*) 'G02JAF Example Program Results'
      Write (nout,*)

!     Skip heading in data file
      Read (nin,*)

!     Read in the problem size
      Read (nin,*) n, ncol, nfv, nrv, nvpr

      Allocate (levels(ncol),fvid(nfv),rvid(nrv))

!     Read in number of levels for each variable
      Read (nin,*) levels(1:ncol)

!     Read in model information
      Read (nin,*) yvid, fvid(1:nfv), rvid(1:nrv), svid, cwid, fint, rint

!     If no subject specified, then ignore RINT
      If (svid==0) Then
        rint = 0
      End If

!     Calculate LB
      lb = rint
      Do i = 1, nrv
        lb = lb + levels(rvid(i))
      End Do
      If (svid/=0) Then
        lb = lb*levels(svid)
      End If
      lb = lb + fint
      Do i = 1, nfv
        lb = lb + max(levels(fvid(i))-1,1)
      End Do

      lddat = n
      Allocate (vpr(nrv),dat(lddat,ncol),gamma(nvpr+2),b(lb),se(lb))

!     Read in the variance component flag
      Read (nin,*) vpr(1:nrv)

!     Read in the Data matrix
      Read (nin,*)(dat(i,1:ncol),i=1,n)

!     Read in the initial values for GAMMA
      Read (nin,*) gamma(1:(nvpr+rint))

!     Read in the maximum number of iterations
      Read (nin,*) maxit

!     Use default value for tolerance
      tol = 0.0E0_nag_wp

!     Fit the linear mixed effects regression model
      ifail = 0
      Call g02jaf(n,ncol,lddat,dat,levels,yvid,cwid,nfv,fvid,fint,nrv,rvid,    &
        nvpr,vpr,rint,svid,gamma,nff,nrf,df,reml,lb,b,se,maxit,tol,warn,ifail)

!     Display results
      If (warn/=0) Then
        Write (nout,*) 'Warning: At least one variance component was ',        &
          'estimated to be negative and then reset to zero'
        Write (nout,*)
      End If
      Write (nout,*) 'Fixed effects (Estimate and Standard Deviation)'
      Write (nout,*)
      k = 1
      If (fint==1) Then
        Write (nout,99999) 'Intercept             ', b(k), se(k)
        k = k + 1
      End If
      Do i = 1, nfv
        Do j = 1, levels(fvid(i))
          If (levels(fvid(i))==1 .Or. j/=1) Then
            Write (nout,99995) 'Variable', i, ' Level', j, b(k), se(k)
            k = k + 1
          End If
        End Do
      End Do

      Write (nout,*)
      Write (nout,*) 'Random Effects (Estimate and Standard', ' Deviation)'
      Write (nout,*)
      If (svid==0) Then
        Do i = 1, nrv
          Do j = 1, levels(rvid(i))
            Write (nout,99995) 'Variable', i, ' Level', j, b(k), se(k)
            k = k + 1
          End Do
        End Do
      Else
        Do l = 1, levels(svid)
          If (rint==1) Then
            Write (nout,99998) 'Intercept for Subject Level', l, '         ',  &
              b(k), se(k)
            k = k + 1
          End If
          Do i = 1, nrv
            Do j = 1, levels(rvid(i))
              Write (nout,99997) 'Subject Level', l, ' Variable', i, ' Level', &
                j, b(k), se(k)
              k = k + 1
            End Do
          End Do
        End Do
      End If

      Write (nout,*)
      Write (nout,*) ' Variance Components'
      Write (nout,99996)(i,gamma(i),i=1,nvpr+rint)

      Write (nout,*)
      Write (nout,99994) 'SIGMA^2     = ', gamma(nvpr+rint+1)
      Write (nout,99994) '-2LOG LIKE  = ', reml
      Write (nout,99993) 'DF          = ', df

99999 Format (1X,A,2F10.4)
99998 Format (1X,A,I4,A,2F10.4)
99997 Format (1X,3(A,I4),2F10.4)
99996 Format (1X,I4,F10.4)
99995 Format (1X,2(A,I4),2F10.4)
99994 Format (1X,A,F10.4)
99993 Format (1X,A,I16)
    End Program g02jafe


g02jbfe.f90

    Program g02jbfe

!     G02JBF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: g02jbf, nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: reml, tol
      Integer                          :: cwid, df, fint, i, ifail, j, k, l,   &
                                          lb, lddat, maxit, n, ncol, nff, nfv, &
                                          nrf, nrv, nvpr, rint, svid, warn,    &
                                          yvid
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: b(:), dat(:,:), gamma(:), se(:)
      Integer, Allocatable             :: fvid(:), levels(:), rvid(:), vpr(:)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: max
!     .. Executable Statements ..
      Write (nout,*) 'G02JBF Example Program Results'
      Write (nout,*)

!     Skip heading in data file
      Read (nin,*)

!     Read in the problem size
      Read (nin,*) n, ncol, nfv, nrv, nvpr

      Allocate (levels(ncol),fvid(nfv),rvid(nrv))

!     Read in number of levels for each variable
      Read (nin,*) levels(1:ncol)

!     Read in model information
      Read (nin,*) yvid, fvid(1:nfv), rvid(1:nrv), svid, cwid, fint, rint

!     If no subject specified, then ignore RINT
      If (svid==0) Then
        rint = 0
      End If

!     Calculate LB
      lb = rint
      Do i = 1, nrv
        lb = lb + levels(rvid(i))
      End Do
      If (svid/=0) Then
        lb = lb*levels(svid)
      End If
      lb = lb + fint
      Do i = 1, nfv
        lb = lb + max(levels(fvid(i))-1,1)
      End Do

      lddat = n
      Allocate (vpr(nrv),dat(lddat,ncol),gamma(nvpr+2),b(lb),se(lb))

!     Read in the variance component flag
      Read (nin,*) vpr(1:nrv)

!     Read in the Data matrix
      Read (nin,*)(dat(i,1:ncol),i=1,n)

!     Read in the initial values for GAMMA
      Read (nin,*) gamma(1:(nvpr+rint))

!     Read in the maximum number of iterations
      Read (nin,*) maxit

!     Use default value for tolerance
      tol = 0.0E0_nag_wp

!     Fit the linear mixed effects regression model
      ifail = 0
      Call g02jbf(n,ncol,lddat,dat,levels,yvid,cwid,nfv,fvid,fint,nrv,rvid,    &
        nvpr,vpr,rint,svid,gamma,nff,nrf,df,reml,lb,b,se,maxit,tol,warn,ifail)

!     Display results
      If (warn/=0) Then
        Write (nout,*) 'Warning: At least one variance component was ',        &
          'estimated to be negative and then reset to zero'
        Write (nout,*)
      End If
      Write (nout,*) 'Fixed effects (Estimate and Standard Deviation)'
      Write (nout,*)
      k = 1
      If (fint==1) Then
        Write (nout,99999) 'Intercept             ', b(k), se(k)
        k = k + 1
      End If
      Do i = 1, nfv
        Do j = 1, levels(fvid(i))
          If (levels(fvid(i))==1 .Or. j/=1) Then
            Write (nout,99995) 'Variable', i, ' Level', j, b(k), se(k)
            k = k + 1
          End If
        End Do
      End Do

      Write (nout,*)
      Write (nout,*) 'Random Effects (Estimate and Standard', ' Deviation)'
      Write (nout,*)
      If (svid==0) Then
        Do i = 1, nrv
          Do j = 1, levels(rvid(i))
            Write (nout,99995) 'Variable', i, ' Level', j, b(k), se(k)
            k = k + 1
          End Do
        End Do
      Else
        Do l = 1, levels(svid)
          If (rint==1) Then
            Write (nout,99998) 'Intercept for Subject Level', l, '         ',  &
              b(k), se(k)
            k = k + 1
          End If
          Do i = 1, nrv
            Do j = 1, levels(rvid(i))
              Write (nout,99997) 'Subject Level', l, ' Variable', i, ' Level', &
                j, b(k), se(k)
              k = k + 1
            End Do
          End Do
        End Do
      End If

      Write (nout,*)
      Write (nout,*) ' Variance Components'
      Write (nout,99996)(i,gamma(i),i=1,nvpr+rint)

      Write (nout,*)
      Write (nout,99994) 'SIGMA^2     = ', gamma(nvpr+rint+1)
      Write (nout,99994) '-2LOG LIKE  = ', reml
      Write (nout,99993) 'DF          = ', df

99999 Format (1X,A,2F10.4)
99998 Format (1X,A,I4,A,2F10.4)
99997 Format (1X,3(A,I4),2F10.4)
99996 Format (1X,I4,F10.4)
99995 Format (1X,2(A,I4),2F10.4)
99994 Format (1X,A,F10.4)
99993 Format (1X,A,I16)
    End Program g02jbfe


g02jdfe.f90

!   G02JDF Example Program Text
!   Mark 26 Release. NAG Copyright 2016.

    Module g02jdfe_mod

!     G02JDF Example Program Module:
!            Parameters and User-defined Routines

!     .. Use Statements ..
      Use nag_library, Only: nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Accessibility Statements ..
      Private
      Public                           :: print_results
!     .. Parameters ..
      Integer, Parameter, Public       :: nin = 5, nout = 6
    Contains
      Subroutine print_results(n,nff,nlsv,nrf,fixed,lfixed,nrndm,rndm,ldrndm,  &
        nvpr,vpr,lvpr,gamma,effn,rnkx,ncov,lnlike,lb,id,ldid,b,se)

!       .. Scalar Arguments ..
        Real (Kind=nag_wp), Intent (In) :: lnlike
        Integer, Intent (In)           :: effn, lb, ldid, ldrndm, lfixed,      &
                                          lvpr, n, ncov, nff, nlsv, nrf,       &
                                          nrndm, nvpr, rnkx
!       .. Array Arguments ..
        Real (Kind=nag_wp), Intent (In) :: b(lb), gamma(nvpr+1), se(lb)
        Integer, Intent (In)           :: fixed(lfixed), id(ldid,lb),          &
                                          rndm(ldrndm,nrndm), vpr(lvpr)
!       .. Local Scalars ..
        Integer                        :: aid, i, k, l, ns, nv, p, pb, tb,     &
                                          tdid, vid
        Character (120)                :: pfmt, tfmt
!       .. Executable Statements ..
!       Display the output
        Write (nout,*) 'Number of observations (N)                    = ', n
        Write (nout,*) 'Number of random factors (NRF)                = ', nrf
        Write (nout,*) 'Number of fixed factors (NFF)                 = ', nff
        Write (nout,*) 'Number of subject levels (NLSV)               = ',     &
          nlsv
        Write (nout,*) 'Rank of X (RNKX)                              = ',     &
          rnkx
        Write (nout,*) 'Effective N (EFFN)                            = ',     &
          effn
        Write (nout,*) 'Number of nonzero variance components (NCOV) = ', ncov

        Write (nout,99990) 'Parameter Estimates'
        tdid = nff + nrf*nlsv

        If (nrf>0) Then
          Write (nout,*)
          Write (nout,99990) 'Random Effects'
        End If
        pb = -999
        pfmt = ' '
        Do k = 1, nrf*nlsv
          tb = id(1,k)
          If (tb/=-999) Then
            vid = id(2,k)
            nv = rndm(1,tb)
            ns = rndm(3+nv,tb)
            Write (tfmt,*)(id(3+l,k),l=1,ns)
            If (pb/=tb .Or. tfmt/=pfmt) Then
              If (k/=1) Then
                Write (nout,*)
              End If
              Write (nout,99991) ' Subject: ', ('Variable ',rndm(3+nv+l,tb),   &
                ' (Level ',id(3+l,k),')',l=1,ns)
            End If
            If (vid==0) Then
!             Intercept
              Write (nout,99994) b(k), se(k)
            Else
!             VID'th variable specified in RNDM
              aid = rndm(2+vid,tb)
              If (id(3,k)==0) Then
                Write (nout,99992) aid, b(k), se(k)
              Else
                Write (nout,99993) aid, id(3,k), b(k), se(k)
              End If
            End If
            pfmt = tfmt
          End If
          pb = tb
        End Do

        If (nff>0) Then
          Write (nout,*)
          Write (nout,99990) 'Fixed Effects'
        End If
        Do k = nrf*nlsv + 1, tdid
          If (vid/=-999) Then
            vid = id(2,k)
            If (vid==0) Then
!             Intercept
              Write (nout,99997) b(k), se(k)
            Else
!             VID'th variable specified in FIXED
              aid = fixed(2+vid)
              If (id(3,k)==0) Then
                Write (nout,99995) aid, b(k), se(k)
              Else
                Write (nout,99996) aid, id(3,k), b(k), se(k)
              End If
            End If
          End If
        End Do

        Write (nout,*)
        Write (nout,*) 'Variance Components'
        Write (nout,*) ' Estimate      Parameter        Subject'
        Do k = 1, nvpr
          Write (nout,99999,Advance='NO') gamma(k)
          p = 0
          Do tb = 1, nrndm
            nv = rndm(1,tb)
            ns = rndm(3+nv,tb)
            If (rndm(2,tb)==1) Then
              p = p + 1
              If (vpr(p)==k) Then
                Write (nout,99988,Advance='NO')(rndm(3+nv+l,tb),l=1,ns)
              End If
            End If
            Do i = 1, nv
              p = p + 1
              If (vpr(p)==k) Then
                Write (nout,99989,Advance='NO') rndm(2+i,tb),                  &
                  (rndm(3+nv+l,tb),l=1,ns)
              End If
            End Do
          End Do
          Write (nout,*)
        End Do
        Write (nout,*)
        Write (nout,99998) 'SIGMA**2         = ', gamma(nvpr+1)
        Write (nout,99998) '-2LOG LIKELIHOOD = ', lnlike

        Return
99999   Format (1X,F10.5,5X)
99998   Format (1X,A,F15.5)
99997   Format (3X,'Intercept',20X,F10.4,1X,F10.4)
99996   Format (3X,'Variable ',I2,' (Level ',I2,')',7X,F10.4,1X,F10.4)
99995   Format (3X,'Variable ',I2,18X,F10.4,1X,F10.4)
99994   Format (5X,'Intercept',18X,F10.4,1X,F10.4)
99993   Format (5X,'Variable ',I2,' (Level ',I2,')',5X,F10.4,1X,F10.4)
99992   Format (5X,'Variable ',I2,16X,F10.4,1X,F10.4)
99991   Format (1X,A,4(A,I2,A,I2,A,1X))
99990   Format (1X,A)
99989   Format (1X,'Variable',1X,I2,5X,'Variables',1X,100(I2,1X))
99988   Format (1X,'Intercept',7X,'Variables',1X,100(I2,1X))
      End Subroutine print_results
    End Module g02jdfe_mod
    Program g02jdfe

!     G02JDF Example Main Program

!     .. Use Statements ..
      Use nag_library, Only: g02jcf, g02jdf, nag_wp
      Use g02jdfe_mod, Only: nin, nout, print_results
!     .. Implicit None Statement ..
      Implicit None
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: lnlike
      Integer                          :: effn, i, ifail, j, lb, ldcxx, ldcxz, &
                                          ldczz, lddat, ldid, ldrndm, lfixed,  &
                                          licomm, liopt, lrcomm, lropt, lvpr,  &
                                          lwt, n, ncol, ncov, nff, nl, nlsv,   &
                                          nrf, nrndm, nv, nvpr, nzz, rnkx
      Character (1)                    :: weight
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: b(:), cxx(:,:), cxz(:,:), czz(:,:),  &
                                          dat(:,:), gamma(:), rcomm(:),        &
                                          ropt(:), se(:), wt(:), y(:)
      Integer, Allocatable             :: fixed(:), icomm(:), id(:,:),         &
                                          iopt(:), levels(:), rndm(:,:),       &
                                          vpr(:)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: max
!     .. Executable Statements ..
      Write (nout,*) 'G02JDF Example Program Results'
      Write (nout,*)

!     Skip the heading in data file
      Read (nin,*)

!     Read in the problem size
      Read (nin,*) weight, n, ncol, nrndm, nvpr

!     Set LFIXED and LDRNDM to maximum value they could
!     be for this dataset
      lfixed = ncol + 2
      ldrndm = 3 + 2*ncol

      If (weight=='W' .Or. weight=='w') Then
        lwt = n
      Else
        lwt = 0
      End If
      lddat = n
      Allocate (dat(lddat,ncol),levels(ncol),y(n),wt(lwt),fixed(lfixed),       &
        rndm(ldrndm,nrndm))

!     Read in the number of levels associated with each of the
!     independent variables
      Read (nin,*) levels(1:ncol)

!     Read in the fixed part of the model
      Read (nin,*)

!     Number of variables
      Read (nin,*) fixed(1)
      nv = fixed(1)

!     Intercept
      Read (nin,*) fixed(2)

!     Variable IDs
      If (nv>0) Then
        Read (nin,*) fixed(3:(nv+2))
      End If

!     Read in the random part of the model
      lvpr = 0
      Do j = 1, nrndm
!       Skip header
        Read (nin,*)

!       Number of variables and intercept
        Read (nin,*) rndm(1,j)
        Read (nin,*) rndm(2,j)
        nv = rndm(1,j)

!       Variable IDs
        If (nv>0) Then
          Read (nin,*)(rndm(i,j),i=3,nv+2)
        End If

!       Number of subject variables
        Read (nin,*) rndm(nv+3,j)
        nl = rndm(nv+3,j)

!       Subject variable IDs
        If (nl>0) Then
          Read (nin,*)(rndm(i,j),i=nv+4,nv+nl+3)
        End If
        lvpr = lvpr + rndm(2,j) + nv
      End Do

!     Read in the dependent and independent data
      If (lwt>0) Then
        Read (nin,*)(y(i),dat(i,1:ncol),wt(i),i=1,n)
      Else
        Read (nin,*)(y(i),dat(i,1:ncol),i=1,n)
      End If

      licomm = 2
      lrcomm = 0
      Allocate (icomm(licomm),rcomm(lrcomm))

!     Call the initialization routine once to get LRCOMM and LICOMM
      ifail = 0
      Call g02jcf(weight,n,ncol,dat,lddat,levels,y,wt,fixed,lfixed,nrndm,rndm, &
        ldrndm,nff,nlsv,nrf,rcomm,lrcomm,icomm,licomm,ifail)

!     Reallocate ICOMM and RCOMM
      licomm = icomm(1)
      lrcomm = icomm(2)
      Deallocate (icomm,rcomm)
      Allocate (icomm(licomm),rcomm(lrcomm))

!     Pre-process the data
      ifail = 0
      Call g02jcf(weight,n,ncol,dat,lddat,levels,y,wt,fixed,lfixed,nrndm,rndm, &
        ldrndm,nff,nlsv,nrf,rcomm,lrcomm,icomm,licomm,ifail)

!     Use the default options
      liopt = 0
      lropt = 0

!     Calculate LDID
      ldid = 0
      Do i = 1, nrndm
        nv = rndm(1,i)
        ldid = max(rndm(3+nv,i),ldid)
      End Do
      ldid = ldid + 3

      lb = nff + nrf*nlsv
      nzz = nrf*nlsv
      ldczz = nzz
      ldcxx = nff
      ldcxz = nff
      Allocate (vpr(lvpr),gamma(nvpr+1),id(ldid,lb),b(lb),se(lb),              &
        czz(ldczz,nzz),cxx(ldcxx,nff),cxz(ldcxz,nzz),iopt(liopt),ropt(lropt))

!     Read in VPR
      Read (nin,*) vpr(1:lvpr)

!     Read in GAMMA
      Read (nin,*) gamma(1:nvpr)

!     Perform the analysis
      ifail = -1
      Call g02jdf(lvpr,vpr,nvpr,gamma,effn,rnkx,ncov,lnlike,lb,id,ldid,b,se,   &
        czz,ldczz,cxx,ldcxx,cxz,ldcxz,rcomm,icomm,iopt,liopt,ropt,lropt,ifail)
      If (ifail/=0 .And. ifail<100) Then
        Go To 100
      End If

!     Display results
      Call print_results(n,nff,nlsv,nrf,fixed,lfixed,nrndm,rndm,ldrndm,nvpr,   &
        vpr,lvpr,gamma,effn,rnkx,ncov,lnlike,lb,id,ldid,b,se)

100   Continue

    End Program g02jdfe


g02jefe.f90

!   G02JEF Example Program Text
!   Mark 26 Release. NAG Copyright 2016.

    Module g02jefe_mod

!     G02JEF Example Program Module:
!            Parameters and User-defined Routines

!     .. Use Statements ..
      Use nag_library, Only: nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Accessibility Statements ..
      Private
      Public                           :: print_results
!     .. Parameters ..
      Integer, Parameter, Public       :: nin = 5, nout = 6
    Contains
      Subroutine print_results(n,nff,nlsv,nrf,fixed,lfixed,nrndm,rndm,ldrndm,  &
        nvpr,vpr,lvpr,gamma,effn,rnkx,ncov,lnlike,lb,id,ldid,b,se)

!       .. Scalar Arguments ..
        Real (Kind=nag_wp), Intent (In) :: lnlike
        Integer, Intent (In)           :: effn, lb, ldid, ldrndm, lfixed,      &
                                          lvpr, n, ncov, nff, nlsv, nrf,       &
                                          nrndm, nvpr, rnkx
!       .. Array Arguments ..
        Real (Kind=nag_wp), Intent (In) :: b(lb), gamma(nvpr+1), se(lb)
        Integer, Intent (In)           :: fixed(lfixed), id(ldid,lb),          &
                                          rndm(ldrndm,nrndm), vpr(lvpr)
!       .. Local Scalars ..
        Integer                        :: aid, i, k, l, ns, nv, p, pb, tb,     &
                                          tdid, vid
        Character (120)                :: pfmt, tfmt
!       .. Executable Statements ..
!       Display the output
        Write (nout,*) 'Number of observations (N)                    = ', n
        Write (nout,*) 'Number of random factors (NRF)                = ', nrf
        Write (nout,*) 'Number of fixed factors (NFF)                 = ', nff
        Write (nout,*) 'Number of subject levels (NLSV)               = ',     &
          nlsv
        Write (nout,*) 'Rank of X (RNKX)                              = ',     &
          rnkx
        Write (nout,*) 'Effective N (EFFN)                            = ',     &
          effn
        Write (nout,*) 'Number of nonzero variance components (NCOV) = ', ncov

        Write (nout,99990) 'Parameter Estimates'
        tdid = nff + nrf*nlsv

        If (nrf>0) Then
          Write (nout,*)
          Write (nout,99990) 'Random Effects'
        End If
        pb = -999
        pfmt = ' '
        Do k = 1, nrf*nlsv
          tb = id(1,k)
          If (tb/=-999) Then
            vid = id(2,k)
            nv = rndm(1,tb)
            ns = rndm(3+nv,tb)
            Write (tfmt,*)(id(3+l,k),l=1,ns)
            If (pb/=tb .Or. tfmt/=pfmt) Then
              If (k/=1) Then
                Write (nout,*)
              End If
              Write (nout,99991) ' Subject: ', ('Variable ',rndm(3+nv+l,tb),   &
                ' (Level ',id(3+l,k),')',l=1,ns)
            End If
            If (vid==0) Then
!             Intercept
              Write (nout,99994) b(k), se(k)
            Else
!             VID'th variable specified in RNDM
              aid = rndm(2+vid,tb)
              If (id(3,k)==0) Then
                Write (nout,99992) aid, b(k), se(k)
              Else
                Write (nout,99993) aid, id(3,k), b(k), se(k)
              End If
            End If
            pfmt = tfmt
          End If
          pb = tb
        End Do

        If (nff>0) Then
          Write (nout,*)
          Write (nout,99990) 'Fixed Effects'
        End If
        Do k = nrf*nlsv + 1, tdid
          If (vid/=-999) Then
            vid = id(2,k)
            If (vid==0) Then
!             Intercept
              Write (nout,99997) b(k), se(k)
            Else
!             VID'th variable specified in FIXED
              aid = fixed(2+vid)
              If (id(3,k)==0) Then
                Write (nout,99995) aid, b(k), se(k)
              Else
                Write (nout,99996) aid, id(3,k), b(k), se(k)
              End If
            End If
          End If
        End Do

        Write (nout,*)
        Write (nout,*) 'Variance Components'
        Write (nout,*) ' Estimate      Parameter        Subject'
        Do k = 1, nvpr
          Write (nout,99999,Advance='NO') gamma(k)
          p = 0
          Do tb = 1, nrndm
            nv = rndm(1,tb)
            ns = rndm(3+nv,tb)
            If (rndm(2,tb)==1) Then
              p = p + 1
              If (vpr(p)==k) Then
                Write (nout,99988,Advance='NO')(rndm(3+nv+l,tb),l=1,ns)
              End If
            End If
            Do i = 1, nv
              p = p + 1
              If (vpr(p)==k) Then
                Write (nout,99989,Advance='NO') rndm(2+i,tb),                  &
                  (rndm(3+nv+l,tb),l=1,ns)
              End If
            End Do
          End Do
          Write (nout,*)
        End Do
        Write (nout,*)
        Write (nout,99998) 'SIGMA**2         = ', gamma(nvpr+1)
        Write (nout,99998) '-2LOG LIKELIHOOD = ', lnlike

        Return
99999   Format (1X,F10.5,5X)
99998   Format (1X,A,F15.5)
99997   Format (3X,'Intercept',20X,F10.4,1X,F10.4)
99996   Format (3X,'Variable ',I2,' (Level ',I2,')',7X,F10.4,1X,F10.4)
99995   Format (3X,'Variable ',I2,18X,F10.4,1X,F10.4)
99994   Format (5X,'Intercept',18X,F10.4,1X,F10.4)
99993   Format (5X,'Variable ',I2,' (Level ',I2,')',5X,F10.4,1X,F10.4)
99992   Format (5X,'Variable ',I2,16X,F10.4,1X,F10.4)
99991   Format (1X,A,4(A,I2,A,I2,A,1X))
99990   Format (1X,A)
99989   Format (1X,'Variable',1X,I2,5X,'Variables',1X,100(I2,1X))
99988   Format (1X,'Intercept',7X,'Variables',1X,100(I2,1X))
      End Subroutine print_results
    End Module g02jefe_mod
    Program g02jefe

!     G02JEF Example Main Program

!     .. Use Statements ..
      Use nag_library, Only: g02jcf, g02jef, nag_wp
      Use g02jefe_mod, Only: nin, nout, print_results
!     .. Implicit None Statement ..
      Implicit None
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: lnlike
      Integer                          :: effn, i, ifail, j, lb, ldcxx, ldcxz, &
                                          ldczz, lddat, ldid, ldrndm, lfixed,  &
                                          licomm, liopt, lrcomm, lropt, lvpr,  &
                                          lwt, n, ncol, ncov, nff, nl, nlsv,   &
                                          nrf, nrndm, nv, nvpr, nzz, rnkx
      Character (1)                    :: weight
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: b(:), cxx(:,:), cxz(:,:), czz(:,:),  &
                                          dat(:,:), gamma(:), rcomm(:),        &
                                          ropt(:), se(:), wt(:), y(:)
      Integer, Allocatable             :: fixed(:), icomm(:), id(:,:),         &
                                          iopt(:), levels(:), rndm(:,:),       &
                                          vpr(:)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: max
!     .. Executable Statements ..
      Write (nout,*) 'G02JEF Example Program Results'
      Write (nout,*)

!     Skip the heading in data file
      Read (nin,*)

!     Read in the problem size
      Read (nin,*) weight, n, ncol, nrndm, nvpr

!     Set LFIXED and LDRNDM to maximum value they could
!     be for this dataset
      lfixed = ncol + 2
      ldrndm = 3 + 2*ncol

      If (weight=='W' .Or. weight=='w') Then
        lwt = n
      Else
        lwt = 0
      End If
      lddat = n
      Allocate (dat(lddat,ncol),levels(ncol),y(n),wt(lwt),fixed(lfixed),       &
        rndm(ldrndm,nrndm))

!     Read in the number of levels associated with each of the
!     independent variables
      Read (nin,*) levels(1:ncol)

!     Read in the fixed part of the model
      Read (nin,*)

!     Number of variables
      Read (nin,*) fixed(1)
      nv = fixed(1)

!     Intercept
      Read (nin,*) fixed(2)

!     Variable IDs
      If (nv>0) Then
        Read (nin,*) fixed(3:(nv+2))
      End If

!     Read in the random part of the model
      lvpr = 0
      Do j = 1, nrndm
!       Skip header
        Read (nin,*)

!       Number of variables
        Read (nin,*) rndm(1,j)
        nv = rndm(1,j)

!       Intercept
        Read (nin,*) rndm(2,j)

!       Variable IDs
        If (nv>0) Then
          Read (nin,*)(rndm(i,j),i=3,nv+2)
        End If

!       Number of subject variables
        Read (nin,*) rndm(nv+3,j)
        nl = rndm(nv+3,j)

!       Subject variable IDs
        If (nl>0) Then
          Read (nin,*)(rndm(i,j),i=nv+4,nv+nl+3)
        End If
        lvpr = lvpr + rndm(2,j) + nv
      End Do

!     Read in the dependent and independent data
      If (lwt>0) Then
        Read (nin,*)(y(i),dat(i,1:ncol),wt(i),i=1,n)
      Else
        Read (nin,*)(y(i),dat(i,1:ncol),i=1,n)
      End If

      licomm = 2
      lrcomm = 0
      Allocate (icomm(licomm),rcomm(lrcomm))

!     Call the initialization routine once to get LRCOMM and LICOMM
      ifail = 0
      Call g02jcf(weight,n,ncol,dat,lddat,levels,y,wt,fixed,lfixed,nrndm,rndm, &
        ldrndm,nff,nlsv,nrf,rcomm,lrcomm,icomm,licomm,ifail)

!     Reallocate ICOMM and RCOMM
      licomm = icomm(1)
      lrcomm = icomm(2)
      Deallocate (icomm,rcomm)
      Allocate (icomm(licomm),rcomm(lrcomm))

!     Pre-process the data
      ifail = 0
      Call g02jcf(weight,n,ncol,dat,lddat,levels,y,wt,fixed,lfixed,nrndm,rndm, &
        ldrndm,nff,nlsv,nrf,rcomm,lrcomm,icomm,licomm,ifail)

!     Use the default options
      liopt = 0
      lropt = 0

!     Calculate LDID
      ldid = 0
      Do i = 1, nrndm
        nv = rndm(1,i)
        ldid = max(rndm(3+nv,i),ldid)
      End Do
      ldid = ldid + 3

      lb = nff + nrf*nlsv
      nzz = nrf*nlsv
      ldczz = nzz
      ldcxx = nff
      ldcxz = nff
      Allocate (vpr(lvpr),gamma(nvpr+1),id(ldid,lb),b(lb),se(lb),              &
        czz(ldczz,nzz),cxx(ldcxx,nff),cxz(ldcxz,nzz),iopt(liopt),ropt(lropt))

!     Read in VPR
      Read (nin,*) vpr(1:lvpr)

!     Read in GAMMA
      Read (nin,*) gamma(1:nvpr)

!     Perform the analysis
      ifail = -1
      Call g02jef(lvpr,vpr,nvpr,gamma,effn,rnkx,ncov,lnlike,lb,id,ldid,b,se,   &
        czz,ldczz,cxx,ldcxx,cxz,ldcxz,rcomm,icomm,iopt,liopt,ropt,lropt,ifail)
      If (ifail/=0) Then
        If (ifail<100) Then
          Go To 100
        End If
      End If

!     Display results
      Call print_results(n,nff,nlsv,nrf,fixed,lfixed,nrndm,rndm,ldrndm,nvpr,   &
        vpr,lvpr,gamma,effn,rnkx,ncov,lnlike,lb,id,ldid,b,se)

100   Continue

    End Program g02jefe


g02kafe.f90

    Program g02kafe

!     G02KAF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: g02kaf, nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: h, nep, rss, tau, tol
      Integer                          :: df, i, ifail, ip, ldx, m, n, niter,  &
                                          opt, optloo, orig
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: b(:), res(:), vif(:), x(:,:), y(:)
      Real (Kind=nag_wp)               :: perr(5)
      Integer, Allocatable             :: isx(:)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: count
!     .. Executable Statements ..
      Write (nout,*) 'G02KAF Example Program Results'
      Write (nout,*)

!     Skip heading in data file
      Read (nin,*)

!     Read in the problem size
      Read (nin,*) n, m, h, opt, tol, niter, orig, optloo, tau

      ldx = n
      Allocate (x(ldx,m),y(n),isx(m))

!     Read in data
      Read (nin,*)(x(i,1:m),y(i),i=1,n)

!     Read in variable inclusion flags
      Read (nin,*) isx(1:m)

!     Calculate IP
      ip = count(isx(1:m)==1)

      Allocate (b(ip+1),vif(ip),res(n))

!     Fit ridge regression model
      ifail = -1
      Call g02kaf(n,m,x,ldx,isx,ip,tau,y,h,opt,niter,tol,nep,orig,b,vif,res,   &
        rss,df,optloo,perr,ifail)
      If (ifail/=0) Then
        If (ifail/=-1) Then
          Go To 100
        End If
      End If

!     Display results
      Write (nout,99999) 'Value of ridge parameter:', h
      Write (nout,*)
      Write (nout,99998) 'Sum of squares of residuals:', rss
      Write (nout,99997) 'Degrees of freedom: ', df
      Write (nout,99999) 'Number of effective parameters:', nep
      Write (nout,*)
      Write (nout,*) 'Parameter estimates'
      Write (nout,99995)(i,b(i),i=1,ip+1)
      Write (nout,*)
      Write (nout,99996) 'Number of iterations:', niter
      Write (nout,*)
      If (opt==1) Then
        Write (nout,*) 'Ridge parameter minimises GCV'
      Else If (opt==2) Then
        Write (nout,*) 'Ridge parameter minimises UEV'
      Else If (opt==3) Then
        Write (nout,*) 'Ridge parameter minimises FPE'
      Else If (opt==4) Then
        Write (nout,*) 'Ridge parameter minimises BIC'
      End If
      Write (nout,*)
      Write (nout,*) 'Estimated prediction errors:'
      Write (nout,99999) 'GCV    =', perr(1)
      Write (nout,99999) 'UEV    =', perr(2)
      Write (nout,99999) 'FPE    =', perr(3)
      Write (nout,99999) 'BIC    =', perr(4)
      If (optloo==2) Then
        Write (nout,99999) 'LOO CV =', perr(5)
      End If
      Write (nout,*)
      Write (nout,*) 'Residuals'
      Write (nout,99995)(i,res(i),i=1,n)
      Write (nout,*)
      Write (nout,*) 'Variance inflation factors'
      Write (nout,99995)(i,vif(i),i=1,ip)

100   Continue

99999 Format (1X,A,1X,F10.4)
99998 Format (1X,A,E11.4)
99997 Format (1X,A,1X,I5)
99996 Format (1X,A,I16)
99995 Format (1X,I4,1X,F11.4)
    End Program g02kafe


g02kbfe.f90

    Program g02kbfe

!     G02KBF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: g02kbf, nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Integer                          :: i, ifail, ip, ldb, ldpe, ldvf, ldx,  &
                                          lh, lpec, m, n, pl, tdb, tdpe, tdvf, &
                                          wantb, wantvf
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: b(:,:), h(:), nep(:), pe(:,:),       &
                                          vf(:,:), x(:,:), y(:)
      Integer, Allocatable             :: isx(:)
      Character (1), Allocatable       :: pec(:)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: count, min
!     .. Executable Statements ..
      Write (nout,*) 'G02KBF Example Program Results'
      Write (nout,*)

!     Skip heading in data file
      Read (nin,*)

!     Read in the problem size
      Read (nin,*) n, m, lh, lpec, wantb, wantvf

      ldx = n
      Allocate (x(ldx,m),isx(m),y(n),h(lh),pec(lpec))

!     Read in data
      If (lpec>0) Then
        Read (nin,*) pec(1:lpec)
      End If
      Read (nin,*)(x(i,1:m),y(i),i=1,n)

!     Read in variable inclusion flags
      Read (nin,*) isx(1:m)

!     Read in the ridge coefficients
      Read (nin,*) h(1:lh)

!     Calculate IP
      ip = count(isx(1:m)==1)

      If (wantb/=0) Then
        ldb = ip + 1
        tdb = lh
      Else
        ldb = 0
        tdb = 0
      End If
      If (wantvf/=0) Then
        ldvf = ip
        tdvf = lh
      Else
        ldvf = 0
        tdvf = 0
      End If
      If (lpec>0) Then
        ldpe = lpec
        tdpe = lh
      Else
        ldpe = 0
        tdpe = 0
      End If
      Allocate (nep(lh),b(ldb,tdb),vf(ldvf,tdvf),pe(ldpe,tdpe))

!     Fit ridge regression
      ifail = 0
      Call g02kbf(n,m,x,ldx,isx,ip,y,lh,h,nep,wantb,b,ldb,wantvf,vf,ldvf,lpec, &
        pec,pe,ldpe,ifail)

!     Display results
      Write (nout,99994) 'Number of parameters used = ', ip + 1
      Write (nout,*) 'Effective number of parameters (NEP):'
      Write (nout,*) '   Ridge   '
      Write (nout,*) '   Coeff.  ', 'NEP'
      Write (nout,99993)(h(i),nep(i),i=1,lh)

!     Parameter estimates
      If (wantb/=0) Then
        Write (nout,*)
        If (wantb==1) Then
          Write (nout,*) 'Parameter Estimates (Original scalings)'
        Else
          Write (nout,*) 'Parameter Estimates (Standarised)'
        End If
        pl = min(ip,4)
        Write (nout,*) '  Ridge  '
        Write (nout,99997) '   Coeff.  ', ' Intercept ', (i,i=1,pl)
        If (pl<ip-1) Then
          Write (nout,99996)(i,i=pl+1,ip-1)
        End If
        pl = min(ip+1,5)
        Do i = 1, lh
          Write (nout,99999) h(i), b(1:pl,i)
          If (pl<ip) Then
            Write (nout,99998) b((pl+1):ip,i)
          End If
        End Do
      End If

!     Variance inflation factors
      If (wantvf/=0) Then
        Write (nout,*)
        Write (nout,*) 'Variance Inflation Factors'
        pl = min(ip,5)
        Write (nout,*) '  Ridge  '
        Write (nout,99995) '  Coeff.  ', (i,i=1,pl)
        If (pl<ip) Then
          Write (nout,99996)(i,i=pl+1,ip)
        End If
        Do i = 1, lh
          Write (nout,99999) h(i), vf(1:pl,i)
          If (pl<ip) Then
            Write (nout,99998) vf((pl+1):ip,i)
          End If
        End Do
      End If

!     Prediction error criterion
      If (lpec>0) Then
        Write (nout,*)
        Write (nout,*) 'Prediction error criterion'
        pl = min(lpec,5)
        Write (nout,*) '  Ridge  '
        Write (nout,99995) '  Coeff.  ', (i,i=1,pl)
        If (pl<lpec) Then
          Write (nout,99996)(i,i=pl+1,lpec)
        End If
        Do i = 1, lh
          Write (nout,99999) h(i), pe(1:pl,i)
          If (pl<ip) Then
            Write (nout,99998) pe((pl+1):ip,i)
          End If
        End Do
        Write (nout,*)
        Write (nout,*) 'Key:'
        Do i = 1, lpec
          Select Case (pec(i))
          Case ('L')
            Write (nout,99992) i, 'Leave one out cross-validation'
          Case ('G')
            Write (nout,99992) i, 'Generalized cross-validation'
          Case ('U')
            Write (nout,99992) i, 'Unbiased estimate of variance'
          Case ('F')
            Write (nout,99992) i, 'Final prediction error'
          Case ('B')
            Write (nout,99992) i, 'Bayesian information criterion'
          End Select
        End Do
      End If

99999 Format (1X,F10.4,5F10.4)
99998 Format (1X,10X,5F10.4)
99997 Format (1X,A,A,4I10)
99996 Format (10X,5I10)
99995 Format (1X,A,5I10)
99994 Format (1X,A,I10)
99993 Format (1X,F10.4,F10.4)
99992 Format (1X,1X,I5,1X,A)
    End Program g02kbfe


g02lafe.f90

    Program g02lafe

!     G02LAF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: g02laf, nag_wp, x04caf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Integer                          :: i, ifail, ip, iscale, j, ldc, ldp,   &
                                          ldt, ldu, ldw, ldx, ldxres, ldy,     &
                                          ldycv, ldyres, maxfac, mx, my, n
      Character (80)                   :: fmt
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: c(:,:), p(:,:), t(:,:), u(:,:),      &
                                          w(:,:), x(:,:), xbar(:), xcv(:),     &
                                          xres(:,:), xstd(:), y(:,:), ybar(:), &
                                          ycv(:,:), yres(:,:), ystd(:)
      Integer, Allocatable             :: isx(:)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: count
!     .. Executable Statements ..
      Write (nout,*) 'G02LAF Example Program Results'
      Write (nout,*)
      Flush (nout)

!     Skip heading in data file
      Read (nin,*)

!     Read in the problem size
      Read (nin,*) n, mx, my, iscale, maxfac

      ldx = n
      ldy = n
      Allocate (x(ldx,mx),isx(mx),y(ldy,my))

!     Read in data
      Read (nin,*)(x(i,1:mx),y(i,1:my),i=1,n)

!     Read in variable inclusion flags
      Read (nin,*)(isx(j),j=1,mx)

!     Calculate IP
      ip = count(isx(1:mx)==1)

      ldxres = n
      ldyres = n
      ldw = ip
      ldp = ip
      ldt = n
      ldc = my
      ldu = n
      ldycv = maxfac
      Allocate (xbar(ip),ybar(my),xstd(ip),ystd(my),xres(ldxres,ip),           &
        yres(ldyres,my),w(ldw,maxfac),p(ldp,maxfac),t(ldt,maxfac),             &
        c(ldc,maxfac),u(ldu,maxfac),xcv(maxfac),ycv(ldycv,my))

!     Fit a PLS model
      ifail = 0
      Call g02laf(n,mx,x,ldx,isx,ip,my,y,ldy,xbar,ybar,iscale,xstd,ystd,       &
        maxfac,xres,ldxres,yres,ldyres,w,ldw,p,ldp,t,ldt,c,ldc,u,ldu,xcv,ycv,  &
        ldycv,ifail)

!     Display results
      ifail = 0
      Call x04caf('General',' ',ip,maxfac,p,ldp,'x-loadings, P',ifail)
      Write (nout,*)
      Flush (nout)
      ifail = 0
      Call x04caf('General',' ',n,maxfac,t,ldt,'x-scores, T',ifail)
      Write (nout,*)
      Flush (nout)
      ifail = 0
      Call x04caf('General',' ',my,maxfac,c,ldc,'y-loadings, C',ifail)
      Write (nout,*)
      Flush (nout)
      ifail = 0
      Call x04caf('General',' ',n,maxfac,u,ldu,'y-scores, U',ifail)
      Write (nout,*)
      Write (nout,*) 'Explained Variance'
      Write (nout,*) ' Model effects   Dependent variable(s)'
      Write (fmt,99999) '(', my + 1, '(F12.6,3X))'
      Write (nout,fmt)(xcv(i),ycv(i,1:my),i=1,maxfac)

99999 Format (A,I0,A)
    End Program g02lafe


g02lbfe.f90

    Program g02lbfe

!     G02LBF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: g02lbf, nag_wp, x04caf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: tau
      Integer                          :: i, ifail, ip, iscale, ldc, ldp, ldt, &
                                          ldu, ldw, ldx, ldxres, ldy, ldycv,   &
                                          ldyres, maxfac, maxit, mx, my, n
      Character (80)                   :: fmt
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: c(:,:), p(:,:), t(:,:), u(:,:),      &
                                          w(:,:), x(:,:), xbar(:), xcv(:),     &
                                          xres(:,:), xstd(:), y(:,:), ybar(:), &
                                          ycv(:,:), yres(:,:), ystd(:)
      Integer, Allocatable             :: isx(:)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: count
!     .. Executable Statements ..
      Write (nout,*) 'G02LBF Example Program Results'
      Write (nout,*)
      Flush (nout)

!     Skip heading in data file
      Read (nin,*)

!     Read in the problem size
      Read (nin,*) n, mx, my, iscale, maxfac

      ldx = n
      ldy = n
      Allocate (x(ldx,mx),isx(mx),y(ldy,my))

!     Read in data
      Read (nin,*)(x(i,1:mx),y(i,1:my),i=1,n)

!     Read in variable inclusion flags
      Read (nin,*) isx(1:mx)

!     Calculate IP
      ip = count(isx(1:mx)==1)

      ldxres = n
      ldyres = n
      ldt = n
      ldc = my
      ldu = n
      ldycv = maxfac
      ldw = ip
      ldp = ip
      Allocate (xbar(ip),ybar(my),xstd(ip),ystd(my),xres(ldxres,ip),           &
        yres(ldyres,ip),w(ldw,maxfac),p(ldp,maxfac),t(ldt,maxfac),             &
        c(ldc,maxfac),u(ldu,maxfac),xcv(maxfac),ycv(ldycv,my))

!     Use suggested values for control parameters
      maxit = 200
      tau = 1.0E-4_nag_wp

!     Fit a PLS model
      ifail = 0
      Call g02lbf(n,mx,x,ldx,isx,ip,my,y,ldy,xbar,ybar,iscale,xstd,ystd,       &
        maxfac,maxit,tau,xres,ldxres,yres,ldyres,w,ldw,p,ldp,t,ldt,c,ldc,u,    &
        ldu,xcv,ycv,ldycv,ifail)

!     Display results
      ifail = 0
      Call x04caf('General',' ',ip,maxfac,p,ldp,'x-loadings, P',ifail)
      Write (nout,*)
      Flush (nout)
      ifail = 0
      Call x04caf('General',' ',n,maxfac,t,ldt,'x-scores, T',ifail)
      Write (nout,*)
      Flush (nout)
      ifail = 0
      Call x04caf('General',' ',my,maxfac,c,ldc,'y-loadings, C',ifail)
      Write (nout,*)
      Flush (nout)
      ifail = 0
      Call x04caf('General',' ',n,maxfac,u,ldu,'y-scores, U',ifail)
      Write (nout,*)
      Write (nout,*) 'Explained Variance'
      Write (nout,*) ' Model effects   Dependent variable(s)'
      Write (fmt,99999) '(', my + 1, '(F12.6,3X))'
      Write (nout,fmt)(xcv(i),ycv(i,1:my),i=1,maxfac)

99999 Format (A,I0,A)
    End Program g02lbfe


g02lcfe.f90

    Program g02lcfe

!     G02LCF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: g02lcf, nag_wp, x04caf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: rcond
      Integer                          :: i, ifail, ip, iscale, ldb, ldc,      &
                                          ldob, ldp, ldvip, ldw, ldycv,        &
                                          maxfac, my, nfact, orig, vipopt
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: b(:,:), c(:,:), ob(:,:), p(:,:),     &
                                          vip(:,:), w(:,:), xbar(:), xstd(:),  &
                                          ybar(:), ycv(:,:), ystd(:)
!     .. Executable Statements ..
      Write (nout,*) 'G02LCF Example Program Results'
      Write (nout,*)
      Flush (nout)

!     Skip heading in data file
      Read (nin,*)

!     Read problem size
      Read (nin,*) ip, my, maxfac, nfact, orig, iscale, vipopt

      ldp = ip
      ldc = my
      ldw = ip
      ldb = ip
      If (orig==1) Then
        ldob = ip + 1
      Else
        ldob = 1
      End If
      If (vipopt/=0) Then
        ldycv = nfact
        ldvip = ip
      Else
        ldycv = 0
        ldvip = 0
      End If
      Allocate (p(ldp,maxfac),c(ldc,maxfac),w(ldw,maxfac),b(ldb,my),xbar(ip),  &
        ybar(my),xstd(ip),ystd(my),ob(ldob,my),ycv(ldycv,my),                  &
        vip(ldvip,vipopt))

!     Read in data
      Read (nin,*)(p(i,1:maxfac),i=1,ip)
      Read (nin,*)(c(i,1:maxfac),i=1,my)
      Read (nin,*)(w(i,1:maxfac),i=1,ip)
      If (vipopt/=0) Then
        Read (nin,*)(ycv(i,1:my),i=1,nfact)
      End If

!     Read means and scalings
      If (orig==1) Then
        Read (nin,*) xbar(1:ip)
        Read (nin,*) ybar(1:my)
        If (iscale/=-1) Then
          Read (nin,*) xstd(1:ip)
          Read (nin,*) ystd(1:my)
        End If
      End If

!     Calculate predictions
      rcond = -1.0E0_nag_wp
      ifail = 0
      Call g02lcf(ip,my,maxfac,nfact,p,ldp,c,ldc,w,ldw,rcond,b,ldb,orig,xbar,  &
        ybar,iscale,xstd,ystd,ob,ldob,vipopt,ycv,ldycv,vip,ldvip,ifail)

!     Display results
      ifail = 0
      Call x04caf('General',' ',ip,my,b,ldb,'B',ifail)
      If (orig==1) Then
        Write (nout,*)
        Flush (nout)
        ifail = 0
        Call x04caf('General',' ',ip+1,my,ob,ldob,'OB',ifail)
      End If
      If (vipopt/=0) Then
        Write (nout,*)
        Flush (nout)
        ifail = 0
        Call x04caf('General',' ',ip,vipopt,vip,ldvip,'VIP',ifail)
      End If

    End Program g02lcfe


g02ldfe.f90

    Program g02ldfe

!     G02LDF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: g02ldf, nag_wp, x04caf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Integer                          :: i, ifail, ip, iscale, ldb, ldyhat,   &
                                          ldz, my, mz, n, orig
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: b(:,:), xbar(:), xstd(:), ybar(:),   &
                                          yhat(:,:), ystd(:), z(:,:)
      Integer, Allocatable             :: isz(:)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: sum
!     .. Executable Statements ..
      Write (nout,*) 'G02LDF Example Program Results'
      Write (nout,*)
      Flush (nout)

!     Skip heading in data file
      Read (nin,*)

!     Read in problem size
      Read (nin,*) my, orig, iscale, n, mz

      ldyhat = n
      ldz = n
      Allocate (ybar(my),ystd(my),isz(mz),z(ldz,mz),yhat(ldyhat,my))

!     Read prediction x-data
      Read (nin,*)(z(i,1:mz),i=1,n)

!     Read in elements of ISZ
      Read (nin,*) isz(1:mz)

!     Calculate IP
      ip = sum(isz(1:mz))

      ldb = ip
      If (orig==1) Then
        ldb = ldb + 1
      End If
      Allocate (xbar(ip),xstd(ip),b(ldb,my))

!     Read parameter estimates
      Read (nin,*)(b(i,1:my),i=1,ldb)

!     Read means
      If (orig==-1) Then
        Read (nin,*) xbar(1:ip)
        Read (nin,*) ybar(1:my)

        If (iscale/=-1) Then
!         Read scalings
          Read (nin,*) xstd(1:ip)
          Read (nin,*) ystd(1:my)
        End If
      End If

!     Calculate predictions
      ifail = 0
      Call g02ldf(ip,my,orig,xbar,ybar,iscale,xstd,ystd,b,ldb,n,mz,isz,z,ldz,  &
        yhat,ldyhat,ifail)

!     Display results
      ifail = 0
      Call x04caf('General',' ',n,my,yhat,ldyhat,'YHAT',ifail)

    End Program g02ldfe


g02mafe.f90

    Program g02mafe

!     G02MAF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: g02maf, nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Integer                          :: i, ifail, ip, k, ldb, ldd, lisx,     &
                                          lropt, m, mnstep, mtype, n, nstep,   &
                                          pred, prey
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: b(:,:), d(:,:), fitsum(:,:),         &
                                          ropt(:), y(:)
      Integer, Allocatable             :: isx(:)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: count, floor, max, repeat
!     .. Executable Statements ..
      Write (nout,*) 'G02MAF Example Program Results'
      Write (nout,*)

!     Skip heading in data file
      Read (nin,*)

!     Read in the problem size
      Read (nin,*) n, m

!     Read in the model specification
      Read (nin,*) mtype, pred, prey, mnstep, lisx

!     Read in variable inclusion flags (if specified) and calculate IP
      Allocate (isx(lisx))
      If (lisx==m) Then
        Read (nin,*) isx(1:lisx)
        ip = count(isx(1:m)==1)
      Else
        ip = m
      End If

!     Optional arguments (using defaults)
      lropt = 0
      Allocate (ropt(lropt))

!     Read in the data
      ldd = n
      Allocate (y(n),d(ldd,m))
      Read (nin,*)(d(i,1:m),y(i),i=1,n)

!     Allocate output arrays
      ldb = ip
      Allocate (b(ldb,mnstep+2),fitsum(6,mnstep+1))

!     Call the model fitting routine
      ifail = -1
      Call g02maf(mtype,pred,prey,n,m,d,ldd,isx,lisx,y,mnstep,ip,nstep,b,ldb,  &
        fitsum,ropt,lropt,ifail)
      If (ifail/=0) Then
        If (ifail/=112 .And. ifail/=161 .And. ifail/=162 .And. ifail/=163)     &
          Then
!         IFAIL = 112, 161, 162 and 163 are warnings, so no need to terminate
!         if they occur
          Go To 100
        End If
      End If

!     Display the parameter estimates
      Write (nout,*) ' Step ', repeat(' ',max((ip-2),0)*5),                    &
        ' Parameter Estimate'
      Write (nout,*) repeat('-',5+ip*10)
      Do k = 1, nstep
        Write (nout,99998) k, b(1:ip,k)
      End Do
      Write (nout,*)
      Write (nout,99999) 'alpha: ', fitsum(1,nstep+1)
      Write (nout,*)
      Write (nout,*)                                                           &
        ' Step     Sum      RSS       df       Cp       Ck     Step Size'
      Write (nout,*) repeat('-',64)
      Do k = 1, nstep
        Write (nout,99997) k, fitsum(1:2,k), floor(fitsum(3,k)+0.5_nag_wp),    &
          fitsum(4:6,k)
      End Do
      Write (nout,*)
      Write (nout,99999) 'sigma^2: ', fitsum(5,nstep+1)

100   Continue
99999 Format (1X,A,F9.3)
99998 Format (2X,I3,10(1X,F9.3))
99997 Format (2X,I3,2(1X,F9.3),1X,I6,1X,3(1X,F9.3))
    End Program g02mafe


g02mbfe.f90

    Program g02mbfe

!     G02MBF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: g02buf, g02mbf, nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: sw
      Integer                          :: i, ifail, intcpt, ip, k, ldb, lddtd, &
                                          lisx, lropt, m, mnstep, mtype, n,    &
                                          nstep, pm, pm2, pred
      Character (10)                   :: mean
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: b(:,:), dtd(:,:), dy(:,:),           &
                                          fitsum(:,:), ropt(:), wmean(:)
      Real (Kind=nag_wp)               :: wt(1)
      Integer, Allocatable             :: isx(:)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: count, floor, max, repeat
!     .. Executable Statements ..

!     .. Executable Statements ..
      Write (nout,*) 'G02MBF Example Program Results'
      Write (nout,*)

!     Skip heading in data file
      Read (nin,*)

!     Read in the problem size
      Read (nin,*) n, m

!     Read in the model specification
      Read (nin,*) mtype, pred, intcpt, mnstep, lisx

!     Read in variable inclusion flags (if specified) and calculate IP
      Allocate (isx(lisx))
      If (lisx==m) Then
        Read (nin,*) isx(1:lisx)
        ip = count(isx(1:m)==1)
      Else
        ip = m
      End If

!     Optional arguments (using defaults)
      lropt = 0
      Allocate (ropt(lropt))

!     Read in the augmented matrix [D y] and calculate cross-product matrices
!     (NB: Datasets with a large number of observations can be split into
!     blocks with the resulting cross-product matrices being combined
!     using G02BZF)
      Allocate (dy(n,m+1))
      Read (nin,*)(dy(i,1:m),dy(i,m+1),i=1,n)

      pm = m*(m+1)/2
      pm2 = (m+1)*(m+2)/2

!     We are calculating the cross-product matrix using G02BUF
!     which returns it in packed storage
      lddtd = 1

!     Calculate the cross-product matrices
      Allocate (wmean(m+1),dtd(1,pm2))
      If (intcpt==1) Then
        mean = 'Mean'
      Else
        mean = 'Zero'
      End If
      ifail = 0
      Call g02buf(mean,'UnWeighted',n,m+1,dy,n,wt,sw,wmean,dtd(1,:),ifail)
!     The first PM elements of DTD(1,:) contain the cross-products of D
!     elements DTD(1,PM+1:PM2-1) contains cross-product of D with y and
!     DTD(1,PM2) contains cross-product of y with itself

!     Allocate output arrays
      ldb = ip
      Allocate (b(ldb,mnstep+1),fitsum(6,mnstep+1))

!     Call the model fitting routine
      ifail = -1
      Call g02mbf(mtype,pred,intcpt,n,m,dtd,lddtd,isx,lisx,dtd(1,pm+1:pm2-1),  &
        dtd(1,pm2),mnstep,ip,nstep,b,ldb,fitsum,ropt,lropt,ifail)
      If (ifail/=0) Then
        If (ifail/=112 .And. ifail/=161 .And. ifail/=162 .And. ifail/=163)     &
          Then
!         IFAIL = 112, 161, 162 and 163 are warnings, so no need to terminate
!         if they occur
          Go To 100
        End If
      End If

!     Display the parameter estimates
      Write (nout,*) ' Step ', repeat(' ',max((ip-2),0)*5),                    &
        ' Parameter Estimate'
      Write (nout,*) repeat('-',5+ip*10)
      Do k = 1, nstep
        Write (nout,99998) k, b(1:ip,k)
      End Do
      Write (nout,*)
      Write (nout,99999) 'alpha: ', wmean(m+1)
      Write (nout,*)
      Write (nout,*)                                                           &
        ' Step     Sum      RSS       df       Cp       Ck     Step Size'
      Write (nout,*) repeat('-',64)
      Do k = 1, nstep
        Write (nout,99997) k, fitsum(1:2,k), floor(fitsum(3,k)+0.5_nag_wp),    &
          fitsum(4:6,k)
      End Do
      Write (nout,*)
      Write (nout,99999) 'sigma^2: ', fitsum(5,nstep+1)

100   Continue
99999 Format (1X,A,F9.3)
99998 Format (2X,I3,10(1X,F9.3))
99997 Format (2X,I3,2(1X,F9.3),1X,I6,1X,3(1X,F9.3))
    End Program g02mbfe


g02mcfe.f90

    Program g02mcfe

!     G02MCF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: g02maf, g02mcf, nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Integer                          :: i, ifail, ip, k, ktype, ldb, ldd,    &
                                          ldnb, lisx, lnk, lropt, m, mnstep,   &
                                          mtype, n, nstep, pred, prey
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: b(:,:), d(:,:), fitsum(:,:),         &
                                          nb(:,:), nk(:), ropt(:), y(:)
      Integer, Allocatable             :: isx(:)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: max, repeat
!     .. Executable Statements ..
      Write (nout,*) 'G02MCF Example Program Results'
      Write (nout,*)

!     Skip heading in data file
      Read (nin,*)

!     Read in the problem size
      Read (nin,*) n, m

!     Read in the model specification
      Read (nin,*) mtype, pred, prey, mnstep

!     Use all of the variables
      lisx = 0
      Allocate (isx(lisx))

!     Optional arguments (using defaults)
      lropt = 0
      Allocate (ropt(lropt))

!     Read in the data
      ldd = n
      Allocate (y(n),d(ldd,m))
      Read (nin,*)(d(i,1:m),y(i),i=1,n)

!     Allocate output arrays
      ldb = m
      Allocate (b(ldb,mnstep+2),fitsum(6,mnstep+1))

!     Call the model fitting routine
      ifail = -1
      Call g02maf(mtype,pred,prey,n,m,d,ldd,isx,lisx,y,mnstep,ip,nstep,b,ldb,  &
        fitsum,ropt,lropt,ifail)
      If (ifail/=0) Then
        If (ifail/=112 .And. ifail/=161 .And. ifail/=162 .And. ifail/=163)     &
          Then
!         IFAIL = 112, 161, 162 and 163 are warnings, so no need to terminate
!         if they occur
          Go To 100
        End If
      End If

!     Read in the number of additional parameter estimates required and the
!     way they will be specified
      Read (nin,*) ktype, lnk
      ldnb = ip
      Allocate (nk(lnk),nb(ip,lnk))

!     Read in the target values
      Read (nin,*) nk(1:lnk)

!     Calculate the additional parameter estimates
      ifail = 0
      Call g02mcf(nstep,ip,b,ldb,fitsum,ktype,nk,lnk,nb,ldnb,ifail)

      Write (nout,*) 'Parameter Estimates from G02MAF'
      Write (nout,*) ' Step ', repeat(' ',max((ip-2),0)*5),                    &
        ' Parameter Estimate'
      Write (nout,*) repeat('-',5+ip*10)
      Do k = 1, nstep
        Write (nout,99999) k, b(1:ip,k)
      End Do
      Write (nout,*)

      Write (nout,*) 'Additional Parameter Estimates from G02MCF'
      Write (nout,*) '  NK  ', repeat(' ',max((ip-2),0)*5),                    &
        ' Parameter Estimate'
      Write (nout,*) repeat('-',5+ip*10)
      Do k = 1, lnk
        Write (nout,99998) nk(k), nb(1:ip,k)
      End Do

100   Continue
99999 Format (2X,I3,10(1X,F9.3))
99998 Format (1X,F4.1,10(1X,F9.3))
    End Program g02mcfe


g02qffe.f90

    Program g02qffe

!     G02QFF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: g02qff, nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: df
      Integer                          :: i, ifail, j, l, m, n, ntau
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: b(:,:), bl(:,:), bu(:,:), tau(:),    &
                                          x(:,:), y(:)
      Integer, Allocatable             :: info(:)
!     .. Executable Statements ..
      Write (nout,*) 'G02QFF Example Program Results'
      Write (nout,*)

!     Skip heading in data file
      Read (nin,*)

!     Read in the problem size
      Read (nin,*) n, m, ntau

!     Read in the data
      Allocate (y(n),tau(ntau),x(n,m))
      Read (nin,*)(x(i,1:m),y(i),i=1,n)

!     Read in the quantiles required
      Read (nin,*) tau(1:ntau)

!     Allocate memory for output arrays
      Allocate (b(m,ntau),info(ntau),bl(m,ntau),bu(m,ntau))

!     Call the model fitting routine
      ifail = -1
      Call g02qff(n,m,x,y,ntau,tau,df,b,bl,bu,info,ifail)
      If (ifail/=0) Then
        If (ifail==111) Then
          Write (nout,*) 'Additional error information (INFO): ', info(1:ntau)
        Else
          Go To 100
        End If
      End If

!     Display the parameter estimates
      Do l = 1, ntau
        Write (nout,99999) 'Quantile: ', tau(l)
        Write (nout,*)
        Write (nout,*) '        Lower   Parameter   Upper'
        Write (nout,*) '        Limit   Estimate    Limit'
        Do j = 1, m
          Write (nout,99998) j, bl(j,l), b(j,l), bu(j,l)
        End Do
        Write (nout,*)
        Write (nout,*)
      End Do

100   Continue

99999 Format (1X,A,F6.3)
99998 Format (1X,I3,3(3X,F7.3))
    End Program g02qffe


g02qgfe.f90

    Program g02qgfe

!     G02QGF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: g02qgf, g02zkf, g02zlf, g05kff, nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: lseed = 1, nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: df, rvalue
      Integer                          :: genid, i, ifail, ip, ivalue, j, l,   &
                                          ldbl, lddat, ldres, liopts, lopts,   &
                                          lstate, lwt, m, n, ntau, optype,     &
                                          sorder, subid, tdch
      Character (1)                    :: c1, weight
      Character (30)                   :: cvalue, semeth
      Character (100)                  :: optstr
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: b(:,:), bl(:,:), bu(:,:), ch(:,:,:), &
                                          dat(:,:), opts(:), res(:,:), tau(:), &
                                          wt(:), y(:)
      Integer, Allocatable             :: info(:), iopts(:), isx(:), state(:)
      Integer                          :: seed(lseed)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: count, len_trim, min
!     .. Executable Statements ..
      Write (nout,*) 'G02QGF Example Program Results'
      Write (nout,*)
      Flush (nout)

!     Skip heading in data file
      Read (nin,*)

!     Read in the problem size
      Read (nin,*) sorder, c1, weight, n, m, ntau

!     Read in the data
      If (weight=='W' .Or. weight=='w') Then
        lwt = n
      Else
        lwt = 0
      End If
      Allocate (wt(lwt),isx(m),y(n),tau(ntau))

      If (sorder==1) Then
!       DAT(N,M)
        lddat = n
        Allocate (dat(lddat,m))
        If (lwt==0) Then
          Read (nin,*)(dat(i,1:m),y(i),i=1,n)
        Else
          Read (nin,*)(dat(i,1:m),y(i),wt(i),i=1,n)
        End If
      Else
!       DAT(M,N)
        lddat = m
        Allocate (dat(lddat,n))
        If (lwt==0) Then
          Read (nin,*)(dat(1:m,i),y(i),i=1,n)
        Else
          Read (nin,*)(dat(1:m,i),y(i),wt(i),i=1,n)
        End If
      End If

!     Read in variable inclusion flags
      Read (nin,*) isx(1:m)

!     Calculate IP
      ip = count(isx(1:m)==1)
      If (c1=='Y' .Or. c1=='y') Then
        ip = ip + 1
      End If

!     Read in the quantiles required
      Read (nin,*) tau(1:ntau)

      liopts = 100
      lopts = 100
      Allocate (iopts(liopts),opts(lopts))

!     Initialize the optional argument array
      ifail = 0
      Call g02zkf('INITIALIZE = G02QGF',iopts,liopts,opts,lopts,ifail)

c_lp: Do
!       Read in any optional arguments. Reads in to the end of
!       the input data, or until a blank line is reached
        ifail = 1
        Read (nin,99994,Iostat=ifail) optstr
        If (ifail/=0) Then
          Exit c_lp
        Else If (len_trim(optstr)==0) Then
          Exit c_lp
        End If

!       Set the supplied option
        ifail = 0
        Call g02zkf(optstr,iopts,liopts,opts,lopts,ifail)
      End Do c_lp

!     Assume that no intervals or output matrices are required
!     unless the optional argument state differently
      ldbl = 0
      tdch = 0
      ldres = 0
      lstate = 0

!     Query the optional arguments to see what output is required
      ifail = 0
      Call g02zlf('INTERVAL METHOD',ivalue,rvalue,cvalue,optype,iopts,opts,    &
        ifail)
      semeth = cvalue
      If (semeth/='NONE') Then
!       Require the intervals to be output
        ldbl = ip

        If (semeth=='BOOTSTRAP XY') Then
!         Need to find the length of the state array for the random
!         number generator

!         Read in the generator ID and a seed
          Read (nin,*) genid, subid, seed(1)

!         Query the length of the state array
          Allocate (state(lstate))
          ifail = 0
          Call g05kff(genid,subid,seed,lseed,state,lstate,ifail)

!         Deallocate STATE so that it can reallocated later
          Deallocate (state)
        End If

        ifail = 0
        Call g02zlf('MATRIX RETURNED',ivalue,rvalue,cvalue,optype,iopts,opts,  &
          ifail)
        If (cvalue=='COVARIANCE') Then
          tdch = ntau
        Else If (cvalue=='H INVERSE') Then
          If (semeth=='BOOTSTRAP XY' .Or. semeth=='IID') Then
!           NB: If we are using bootstrap or IID errors then any request for
!           H INVERSE is ignored
            tdch = 0
          Else
            tdch = ntau + 1
          End If
        End If

        ifail = 0
        Call g02zlf('RETURN RESIDUALS',ivalue,rvalue,cvalue,optype,iopts,opts, &
          ifail)
        If (cvalue=='YES') Then
          ldres = n
        End If
      End If

!     Allocate memory for output arrays
      Allocate (b(ip,ntau),info(ntau),bl(ldbl,ntau),bu(ldbl,ntau),             &
        ch(ldbl,ldbl,tdch),state(lstate),res(ldres,ntau))

      If (lstate>0) Then
!       Doing bootstrap, so initialize the RNG
        ifail = 0
        Call g05kff(genid,subid,seed,lseed,state,lstate,ifail)
      End If

!     Call the model fitting routine
      ifail = -1
      Call g02qgf(sorder,c1,weight,n,m,dat,lddat,isx,ip,y,wt,ntau,tau,df,b,bl, &
        bu,ch,res,iopts,opts,state,info,ifail)
      If (ifail/=0) Then
        If (ifail==231) Then
          Write (nout,*) 'Additional error information (INFO): ', info(1:ntau)
        Else
          Go To 100
        End If
      End If

!     Display the parameter estimates
      Do l = 1, ntau
        Write (nout,99999) 'Quantile: ', tau(l)
        Write (nout,*)
        If (ldbl>0) Then
          Write (nout,*) '        Lower   Parameter   Upper'
          Write (nout,*) '        Limit   Estimate    Limit'
        Else
          Write (nout,*) '      Parameter'
          Write (nout,*) '      Estimate'
        End If
        Do j = 1, ip
          If (ldbl>0) Then
            Write (nout,99998) j, bl(j,l), b(j,l), bu(j,l)
          Else
            Write (nout,99998) j, b(j,l)
          End If
        End Do
        Write (nout,*)
        If (tdch==ntau) Then
          Write (nout,*) 'Covariance matrix'
          Do i = 1, ip
            Write (nout,99997) ch(1:i,i,l)
          End Do
          Write (nout,*)
        Else If (tdch==ntau+1) Then
          Write (nout,*) 'J'
          Do i = 1, ip
            Write (nout,99997) ch(1:i,i,1)
          End Do
          Write (nout,*)
          Write (nout,*) 'H inverse'
          Do i = 1, ip
            Write (nout,99997) ch(1:i,i,l+1)
          End Do
          Write (nout,*)
        End If
        Write (nout,*)
      End Do

      If (ldres>0) Then
        Write (nout,*) 'First 10 Residuals'
        Write (nout,*) '                              Quantile'
        Write (nout,99995) 'Obs.', tau(1:ntau)
        Do i = 1, min(n,10)
          Write (nout,99996) i, res(i,1:ntau)
        End Do
      Else
        Write (nout,*) 'Residuals not returned'
      End If
      Write (nout,*)

100   Continue

99999 Format (1X,A,F6.3)
99998 Format (1X,I3,3(3X,F7.3))
99997 Format (1X,10(E10.3,3X))
99996 Format (2X,I3,10(1X,F10.5))
99995 Format (1X,A,10(3X,F6.3,2X))
99994 Format (A100)
    End Program g02qgfe


g03aafe.f90

    Program g03aafe

!     G03AAF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: g03aaf, nag_wp, x04caf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Integer                          :: i, ifail, lde, ldp, ldv, ldx, lwt,   &
                                          m, n, nvar
      Logical                          :: verbose
      Character (1)                    :: matrix, std, weight
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: e(:,:), p(:,:), s(:), v(:,:), wk(:), &
                                          wt(:), x(:,:)
      Integer, Allocatable             :: isx(:)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: count
!     .. Executable Statements ..
      Write (nout,*) 'G03AAF Example Program Results'
      Write (nout,*)

!     Skip heading in data file
      Read (nin,*)

!     Read in the problem size
      Read (nin,*) matrix, std, weight, n, m

      If (weight=='W' .Or. weight=='w') Then
        lwt = n
      Else
        lwt = 0
      End If
      ldx = n
      Allocate (x(ldx,m),wt(lwt),isx(m),s(m))

!     Read in data
      If (lwt>0) Then
        Read (nin,*)(x(i,1:m),wt(i),i=1,n)
      Else
        Read (nin,*)(x(i,1:m),i=1,n)
      End If

!     Read in variable inclusion flags
      Read (nin,*) isx(1:m)

!     Read in standardizations
      If (matrix=='S' .Or. matrix=='s') Then
        Read (nin,*) s(1:m)
      End If

!     Calculate NVAR
      nvar = count(isx(1:m)==1)

      lde = nvar
      ldp = nvar
      ldv = n
      Allocate (e(lde,6),p(ldp,nvar),v(ldv,nvar),wk(1))

!     Perform PCA
      ifail = 0
      Call g03aaf(matrix,std,weight,n,m,x,ldx,isx,s,wt,nvar,e,lde,p,ldp,v,ldv, &
        wk,ifail)

!     Display results
      Write (nout,*)                                                           &
        'Eigenvalues  Percentage  Cumulative     Chisq      DF     Sig'
      Write (nout,*) '              variation   variation'
      Write (nout,*)
      Write (nout,99999)(e(i,1:6),i=1,nvar)

!     Set verbose to .True. to see principal component loadings and scores
      verbose = .False.
      If (verbose) Then
        Write (nout,*)
        Flush (nout)
        ifail = 0
        Call x04caf('General',' ',nvar,nvar,p,ldp,                             &
          'Principal component loadings',ifail)
        Write (nout,*)
        Flush (nout)
        ifail = 0
        Call x04caf('General',' ',n,nvar,v,ldv,'Principal component scores',   &
          ifail)
      End If

99999 Format (1X,F11.4,2F12.4,F10.4,F8.1,F8.4)
    End Program g03aafe


g03acfe.f90

    Program g03acfe

!     G03ACF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: g03acf, nag_wp, x04caf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: tol
      Integer                          :: i, ifail, irankx, iwk, ldcvm, ldcvx, &
                                          lde, ldx, lwt, m, n, ncv, ng, nx
      Character (1)                    :: weight
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: cvm(:,:), cvx(:,:), e(:,:), wk(:),   &
                                          wt(:), x(:,:)
      Integer, Allocatable             :: ing(:), isx(:), nig(:)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: max, min
!     .. Executable Statements ..
      Write (nout,*) 'G03ACF Example Program Results'
      Write (nout,*)

!     Skip heading in data file
      Read (nin,*)

!     Read in the problem size
      Read (nin,*) n, m, nx, ng, weight

      Select Case (weight)
      Case ('W','w','V','v')
        lwt = n
      Case Default
        lwt = 0
      End Select
      ldx = n
      ldcvm = ng
      lde = min(nx,ng-1)
      ldcvx = nx
      If (nx>=ng-1) Then
        iwk = n*nx + max(5*(nx-1)+(nx+1)*nx,n) + 1
      Else
        iwk = n*nx + max(5*(nx-1)+(ng-1)*nx,n) + 1
      End If
      Allocate (x(ldx,m),isx(m),ing(n),wt(lwt),nig(ng),cvm(ldcvm,nx),e(lde,6), &
        cvx(ldcvx,nx),wk(iwk))

!     Read in data
      If (lwt>0) Then
        Read (nin,*)(x(i,1:m),wt(i),ing(i),i=1,n)
      Else
        Read (nin,*)(x(i,1:m),ing(i),i=1,n)
      End If

!     Read in variable inclusion flags
      Read (nin,*) isx(1:m)

!     Use default tolerance
      tol = 0.0E0_nag_wp

!     Perform canonical variate analysis
      ifail = 0
      Call g03acf(weight,n,m,x,ldx,isx,nx,ing,ng,wt,nig,cvm,ldcvm,e,lde,ncv,   &
        cvx,ldcvx,tol,irankx,wk,iwk,ifail)

!     Display results
      Write (nout,99999) 'Rank of X = ', irankx
      Write (nout,*)
      Write (nout,*)                                                           &
        'Canonical    Eigenvalues Percentage     CHISQ      DF     SIG'
      Write (nout,*) 'Correlations              Variation'
      Write (nout,99998)(e(i,1:6),i=1,ncv)
      Write (nout,*)
      Flush (nout)
      ifail = 0
      Call x04caf('General',' ',nx,ncv,cvx,ldcvx,                              &
        'Canonical Coefficients for X',ifail)
      Write (nout,*)
      Flush (nout)
      ifail = 0
      Call x04caf('General',' ',ng,ncv,cvm,ldcvm,'Canonical variate means',    &
        ifail)

99999 Format (1X,A,I0)
99998 Format (1X,2F12.4,F11.4,F10.4,F8.1,F8.4)
    End Program g03acfe


g03adfe.f90

    Program g03adfe

!     G03ADF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: g03adf, nag_wp, x04caf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: tol
      Integer                          :: i, ifail, iwk, ldcvx, ldcvy, lde,    &
                                          ldz, lwt, m, mcv, n, ncv, nx, ny
      Character (1)                    :: weight
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: cvx(:,:), cvy(:,:), e(:,:), wk(:),   &
                                          wt(:), z(:,:)
      Integer, Allocatable             :: isz(:)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: max
!     .. Executable Statements ..
      Write (nout,*) 'G03ADF Example Program Results'
      Write (nout,*)

!     Skip heading in data file
      Read (nin,*)

!     Read in problem size
      Read (nin,*) n, m, nx, ny, weight

      If (weight=='W' .Or. weight=='w') Then
        lwt = n
      Else
        lwt = 0
      End If
      If (nx>=ny) Then
        iwk = n*nx + nx*ny + max(5*(nx-1)+nx*nx,n*ny) + 1
        lde = ny
        mcv = ny
      Else
        iwk = n*ny + nx*ny + max(5*(ny-1)+ny*ny,n*nx) + 1
        lde = nx
        mcv = nx
      End If
      ldz = n
      ldcvx = nx
      ldcvy = ny
      Allocate (z(ldz,m),isz(m),wt(lwt),e(lde,6),cvx(ldcvx,mcv),               &
        cvy(ldcvy,mcv),wk(iwk))

!     Read in data
      If (lwt>0) Then
        Read (nin,*)(z(i,1:m),wt(i),i=1,n)
      Else
        Read (nin,*)(z(i,1:m),i=1,n)
      End If

!     Read in variable inclusion flags
      Read (nin,*) isz(1:m)

!     Use default tolerance
      tol = 0.0E0_nag_wp

!     Perform canonical correlation analysis
      ifail = 0
      Call g03adf(weight,n,m,z,ldz,isz,nx,ny,wt,e,lde,ncv,cvx,ldcvx,mcv,cvy,   &
        ldcvy,tol,wk,iwk,ifail)

!     Display results
      Write (nout,99999) 'Rank of X = ', nx, ' Rank of Y = ', ny
      Write (nout,*)
      Write (nout,*)                                                           &
        'Canonical    Eigenvalues Percentage     Chisq      DF     Sig'
      Write (nout,*) 'correlations              variation'
      Write (nout,99998)(e(i,1:6),i=1,ncv)
      Write (nout,*)
      Flush (nout)
      ifail = 0
      Call x04caf('General',' ',nx,ncv,cvx,ldcvx,                              &
        'Canonical Coefficients for X',ifail)
      Write (nout,*)
      Flush (nout)
      ifail = 0
      Call x04caf('General',' ',ny,ncv,cvy,ldcvy,                              &
        'Canonical Coefficients for Y',ifail)

99999 Format (1X,A,I0,A,I0)
99998 Format (1X,2F12.4,F11.4,F10.4,F8.1,F8.4)
    End Program g03adfe


g03bafe.f90

    Program g03bafe

!     G03BAF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: g03baf, nag_wp, x04caf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: acc, g
      Integer                          :: i, ifail, iter, k, ldfl, ldr, lwk,   &
                                          maxit, nvar
      Character (1)                    :: stand
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: fl(:,:), flr(:,:), r(:,:), wk(:)
!     .. Executable Statements ..
      Write (nout,*) 'G03BAF Example Program Results'
      Write (nout,*)
      Flush (nout)

!     Skip heading in data file
      Read (nin,*)

!     Read in the problem size
      Read (nin,*) nvar, k, g, stand, acc, maxit

      ldfl = nvar
      ldr = k
      lwk = 2*nvar + k*k + 5*(k-1)
      Allocate (fl(ldfl,k),flr(ldfl,k),r(ldr,k),wk(lwk))

!     Read in loadings
      Read (nin,*)(fl(i,1:k),i=1,nvar)

!     Compute rotations
      ifail = 0
      Call g03baf(stand,g,nvar,k,fl,ldfl,flr,r,ldr,acc,maxit,iter,wk,ifail)

!     Display results
      ifail = 0
      Call x04caf('General',' ',nvar,k,flr,ldfl,'Rotated factor loadings',     &
        ifail)
      Write (nout,*)
      Flush (nout)
      ifail = 0
      Call x04caf('General',' ',k,k,r,ldr,'Rotated matrix',ifail)

    End Program g03bafe


g03bcfe.f90

    Program g03bcfe

!     G03BCF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: g03bcf, nag_wp, x04caf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: alpha, rss
      Integer                          :: i, ifail, ldr, ldx, ldy, lwk, m, n
      Character (1)                    :: pscale, stand
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: r(:,:), res(:), wk(:), x(:,:),       &
                                          y(:,:), yhat(:,:)
!     .. Executable Statements ..
      Write (nout,*) 'G03BCF Example Program Results'
      Write (nout,*)
      Flush (nout)

!     Skip heading in data file
      Read (nin,*)

!     Read in problem size
      Read (nin,*) n, m, stand, pscale

      ldx = n
      ldy = n
      ldr = m
      lwk = m*m + 7*m
      Allocate (x(ldx,m),y(ldy,m),yhat(ldy,m),r(ldr,m),res(n),wk(lwk))

!     Read in data
      Read (nin,*)(x(i,1:m),i=1,n)
      Read (nin,*)(y(i,1:m),i=1,n)

!     Calculate rotations
      ifail = 0
      Call g03bcf(stand,pscale,n,m,x,ldx,y,ldy,yhat,r,ldr,alpha,rss,res,wk,    &
        ifail)

!     Display results
      ifail = 0
      Call x04caf('General',' ',m,m,r,ldr,'Rotation Matrix',ifail)
      If (pscale=='S' .Or. pscale=='s') Then
        Write (nout,*)
        Write (nout,99999) ' Scale factor = ', alpha
      End If
      Write (nout,*)
      Flush (nout)
      ifail = 0
      Call x04caf('General',' ',n,m,y,ldy,'Target Matrix',ifail)
      Write (nout,*)
      Flush (nout)
      ifail = 0
      Call x04caf('General',' ',n,m,yhat,ldy,'Fitted Matrix',ifail)
      Write (nout,*)
      Write (nout,99999) 'RSS = ', rss

99999 Format (1X,A,F10.3)
    End Program g03bcfe


g03bdfe.f90

    Program g03bdfe

!     G03BDF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: g03baf, g03bdf, nag_wp, x04caf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: acc, g, power
      Integer                          :: i, ifail, iter, ldfp, ldfs, ldphi,   &
                                          ldr, ldro, ldx, lwk, m, maxit, n
      Character (1)                    :: stand
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: fp(:,:), fs(:,:), phi(:,:), r(:,:),  &
                                          ro(:,:), wk(:), x(:,:)
!     .. Executable Statements ..
      Write (nout,*) 'G03BDF Example Program Results'
      Write (nout,*)
      Flush (nout)

!     Skip heading in data file
      Read (nin,*)

!     Read in problem size
      Read (nin,*) n, m, g, stand, acc, maxit, power

      ldx = n
      ldro = m
      ldfp = n
      ldfs = n
      ldr = m
      ldphi = m
      lwk = 2*n + m*m + 5*(m-1)
      Allocate (fp(ldx,m),x(ldx,m),ro(ldro,m),wk(lwk),phi(ldphi,m),fs(ldfs,m), &
        r(ldr,m))

!     Read loadings matrix
      Read (nin,*)(fp(i,1:m),i=1,n)

!     Calculate orthogonal rotation
      ifail = 0
      Call g03baf(stand,g,n,m,fp,ldx,x,ro,ldro,acc,maxit,iter,wk,ifail)

!     Calculate ProMax rotation
      ifail = 0
      Call g03bdf(stand,n,m,x,ldx,ro,ldro,power,fp,ldfp,r,ldr,phi,ldphi,fs,    &
        ldfs,ifail)

!     Display results
      ifail = 0
      Call x04caf('General',' ',n,m,fp,ldfp,'Factor pattern',ifail)
      Write (nout,*)
      Flush (nout)
      ifail = 0
      Call x04caf('General',' ',m,m,r,ldr,'ProMax rotation',ifail)
      Write (nout,*)
      Flush (nout)
      ifail = 0
      Call x04caf('General',' ',m,m,phi,ldphi,'Inter-factor correlations',     &
        ifail)
      Write (nout,*)
      Flush (nout)
      ifail = 0
      Call x04caf('General',' ',n,m,fs,ldfs,'Factor structure',ifail)

    End Program g03bdfe


g03cafe.f90

    Program g03cafe

!     G03CAF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: g03caf, nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Integer                          :: i, ifail, l, ldfl, ldx, liwk, lres,  &
                                          lwk, lwt, m, n, nfac, nvar
      Character (1)                    :: matrix, weight
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: com(:), e(:), fl(:,:), psi(:),       &
                                          res(:), wk(:), wt(:), x(:,:)
      Real (Kind=nag_wp)               :: stat(4)
      Integer                          :: iop(5)
      Integer, Allocatable             :: isx(:), iwk(:)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: max
!     .. Executable Statements ..
      Write (nout,*) 'G03CAF Example Program Results'
      Write (nout,*)

!     Skip headings in data file
      Read (nin,*)

!     Read in the problem size
      Read (nin,*) matrix, weight, n, m, nvar, nfac

      lwk = (5*nvar*nvar+33*nvar-4)/2
      If (matrix=='C' .Or. matrix=='c') Then
        lwt = 0
        ldx = m
      Else
        If (weight=='W' .Or. weight=='w') Then
          lwt = n
        Else
          lwt = 0
        End If
        ldx = n
        lwk = max(lwk,n*nvar+7*nvar+nvar*(nvar-1)/2)
      End If
      ldfl = nvar
      lres = nvar*(nvar-1)/2
      liwk = 4*nvar + 2
      Allocate (x(ldx,m),isx(m),wt(lwt),e(nvar),com(nvar),psi(nvar),res(lres), &
        fl(ldfl,nfac),iwk(liwk),wk(lwk))

!     Read in the data
      If (lwt>0) Then
        Read (nin,*)(x(i,1:m),wt(i),i=1,ldx)
      Else
        Read (nin,*)(x(i,1:m),i=1,ldx)
      End If

!     Read in variable inclusion flags
      Read (nin,*) isx(1:m)

!     Read in options
      Read (nin,*) iop(1:5)

!     Fit factor analysis model
      ifail = -1
      Call g03caf(matrix,weight,n,m,x,ldx,nvar,isx,nfac,wt,e,stat,com,psi,res, &
        fl,ldfl,iop,iwk,wk,lwk,ifail)
      If (ifail/=0) Then
        If (ifail<=4) Then
          Go To 100
        End If
      End If

!     Display results
      Write (nout,*) ' Eigenvalues'
      Write (nout,*)
      Write (nout,99998) e(1:nvar)
      Write (nout,*)
      Write (nout,99997) '     Test Statistic = ', stat(2)
      Write (nout,99997) '                 df = ', stat(3)
      Write (nout,99997) ' Significance level = ', stat(4)
      Write (nout,*)
      Write (nout,*) ' Residuals'
      Write (nout,*)
      l = 1
      Do i = 1, nvar - 1
        Write (nout,99999) res(l:(l+i-1))
        l = l + i
      End Do
      Write (nout,*)
      Write (nout,*) ' Loadings, Communalities and PSI'
      Write (nout,*)
      Do i = 1, nvar
        Write (nout,99999) fl(i,1:nfac), com(i), psi(i)
      End Do

100   Continue

99999 Format (2X,9F8.3)
99998 Format (2X,6E12.4)
99997 Format (A,F6.3)
    End Program g03cafe


g03ccfe.f90

    Program g03ccfe

!     G03CCF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: g03caf, g03ccf, nag_wp, x04caf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Integer                          :: i, ifail, ldfl, ldfs, ldr, ldx,      &
                                          liwk, lres, lwk, lwt, m, n, nfac,    &
                                          nvar, tdr
      Character (80)                   :: fmt
      Character (1)                    :: matrix, method, rotate, weight
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: com(:), e(:), fl(:,:), fs(:,:),      &
                                          psi(:), r(:,:), res(:), wk(:),       &
                                          wt(:), x(:,:)
      Real (Kind=nag_wp)               :: stat(4)
      Integer                          :: iop(5)
      Integer, Allocatable             :: isx(:), iwk(:)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: count, max
!     .. Executable Statements ..
      Write (nout,*) 'G03CCF Example Program Results'
      Write (nout,*)
      Flush (nout)

!     Skip headings in data file
      Read (nin,*)

!     Read in the problem size
      Read (nin,*) matrix, weight, n, m, nfac

      If (matrix=='C' .Or. matrix=='c') Then
        lwt = 0
        ldx = m
      Else
        If (weight=='W' .Or. weight=='w') Then
          lwt = n
        Else
          lwt = 0
        End If
        ldx = n
      End If
      Allocate (x(ldx,m),isx(m),wt(lwt))

!     Read in the data
      If (lwt>0) Then
        Read (nin,*)(x(i,1:m),wt(i),i=1,ldx)
      Else
        Read (nin,*)(x(i,1:m),i=1,ldx)
      End If

!     Read in variable inclusion flags
      Read (nin,*) isx(1:m)

!     Calculate NVAR
      nvar = count(isx(1:m)==1)

!     Do not apply a rotation
      rotate = 'U'
      tdr = 1
      ldr = 1

      lres = nvar*(nvar-1)/2
      liwk = 4*nvar + 2
      lwk = 5*nvar*nvar + 33*nvar - 4/2
      If (matrix/='C' .And. matrix/='c') Then
        lwk = max(lwk,n*nvar+7*nvar+nvar*(nvar-1)/2)
      End If
      lwk = max(lwk,nvar)
      ldfs = nvar
      ldfl = nvar
      Allocate (e(nvar),com(nvar),psi(nvar),res(lres),fl(ldfl,nfac),wk(lwk),   &
        iwk(liwk),fs(ldfs,nfac),r(ldr,tdr))

!     Read in options
      Read (nin,*) iop(1:5)

!     Fit factor analysis model
      ifail = -1
      Call g03caf(matrix,weight,n,m,x,ldx,nvar,isx,nfac,wt,e,stat,com,psi,res, &
        fl,ldfl,iop,iwk,wk,lwk,ifail)
      If (ifail/=0) Then
        If (ifail<=4) Then
          Go To 100
        End If
      End If

!     Display results
      Write (nout,*) ' Loadings, Communalities and PSI'
      Write (nout,*)
      Write (fmt,99999) '(', nfac + 2, '(1X,F8.3))'
      Write (nout,fmt)(fl(i,1:nfac),com(i),psi(i),i=1,nvar)

!     Read in details of how to compute factor scores
      Read (nin,*) method

!     Compute factor scores
      ifail = 0
      Call g03ccf(method,rotate,nvar,nfac,fl,ldfl,psi,e,r,ldr,fs,ldfs,wk,      &
        ifail)

!     Display factor score coefficients
      Write (nout,*)
      Flush (nout)
      ifail = 0
      Call x04caf('General',' ',nvar,nfac,fs,ldfs,'Factor score coefficients', &
        ifail)

100   Continue

99999 Format (A,I0,A)
    End Program g03ccfe


g03dafe.f90

    Program g03dafe

!     G03DAF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: g03daf, nag_wp, x04caf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: df, sig, stat
      Integer                          :: i, ifail, ldgmn, ldx, lgc, lwk, lwt, &
                                          m, n, ng, nvar
      Character (1)                    :: weight
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: det(:), gc(:), gmn(:,:), wk(:),      &
                                          wt(:), x(:,:)
      Integer, Allocatable             :: ing(:), isx(:), iwk(:), nig(:)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: count
!     .. Executable Statements ..
      Write (nout,*) 'G03DAF Example Program Results'
      Write (nout,*)
      Flush (nout)

!     Skip headings in data file
      Read (nin,*)

!     Read in the problem size
      Read (nin,*) n, m, ng, weight

      If (weight=='W' .Or. weight=='w') Then
        lwt = n
      Else
        lwt = 0
      End If
      ldx = n
      Allocate (x(ldx,m),ing(n),wt(lwt),isx(m))

!     Read in data
      If (lwt>0) Then
        Read (nin,*)(x(i,1:m),ing(i),wt(i),i=1,n)
      Else
        Read (nin,*)(x(i,1:m),ing(i),i=1,n)
      End If

!     Read in variable inclusion flags
      Read (nin,*) isx(1:m)

!     Calculate NVAR
      nvar = count(isx(1:m)==1)

      ldgmn = ng
      lgc = (ng+1)*nvar*(nvar+1)/2
      lwk = n*(nvar+1)
      Allocate (nig(ng),gmn(ldgmn,nvar),det(ng),gc(lgc),wk(lwk),iwk(ng))

!     Compute test statistic
      ifail = 0
      Call g03daf(weight,n,m,x,ldx,isx,nvar,ing,ng,wt,nig,gmn,ldgmn,det,gc,    &
        stat,df,sig,wk,iwk,ifail)

!     Display results
      ifail = 0
      Call x04caf('General',' ',ng,nvar,gmn,ldgmn,'Group means',ifail)
      Write (nout,*)
      Write (nout,*) ' LOG of determinants'
      Write (nout,*)
      Write (nout,99999) det(1:ng)
      Write (nout,*)
      Write (nout,99998) ' STAT = ', stat
      Write (nout,99998) '   DF = ', df
      Write (nout,99998) '  SIG = ', sig

99999 Format (1X,3F10.4)
99998 Format (1X,A,F7.4)
    End Program g03dafe


g03dbfe.f90

    Program g03dbfe

!     G03DBF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: g03daf, g03dbf, nag_wp, x04caf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: df, sig, stat
      Integer                          :: i, ifail, ldd, ldgmn, ldox, ldx,     &
                                          lgc, lwk, lwt, m, n, ng, nobs, nvar
      Character (1)                    :: equal, mode, weight
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: d(:,:), det(:), gc(:), gmn(:,:),     &
                                          ox(:,:), wk(:), wt(:), x(:,:)
      Integer, Allocatable             :: ing(:), isx(:), iwk(:), nig(:)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: count, max
!     .. Executable Statements ..
      Write (nout,*) 'G03DBF Example Program Results'
      Write (nout,*)
      Flush (nout)

!     Skip headings in data file
      Read (nin,*)

!     Read in the problem size
      Read (nin,*) n, m, ng, weight

      If (weight=='W' .Or. weight=='w') Then
        lwt = n
      Else
        lwt = 0
      End If
      ldox = n
      Allocate (ox(ldox,m),ing(n),wt(lwt),isx(m))

!     Read in original data
      If (lwt>0) Then
        Read (nin,*)(ox(i,1:m),ing(i),wt(i),i=1,n)
      Else
        Read (nin,*)(ox(i,1:m),ing(i),i=1,n)
      End If

!     Read in variable inclusion flags
      Read (nin,*) isx(1:m)

!     Calculate NVAR
      nvar = count(isx(1:m)==1)

      ldgmn = ng
      lgc = (ng+1)*nvar*(nvar+1)/2
      lwk = max(n*(nvar+1),2*nvar)
      Allocate (nig(ng),gmn(ldgmn,nvar),det(ng),gc(lgc),wk(lwk),iwk(ng))

!     Compute covariance matrix
      ifail = 0
      Call g03daf(weight,n,m,ox,ldox,isx,nvar,ing,ng,wt,nig,gmn,ldgmn,det,gc,  &
        stat,df,sig,wk,iwk,ifail)

!     Read in size data from which to compute distances
      Read (nin,*) mode, equal

      If (mode=='S' .Or. mode=='s') Then
        Read (nin,*) nobs
        ldd = nobs
      Else
        nobs = 0
        ldd = ng
      End If

      ldx = nobs
      Allocate (x(ldx,m),d(ldd,ng))

!     Read in data from which to compute distances
      If (nobs>0) Then
        Read (nin,*)(x(i,1:m),i=1,nobs)
      End If

!     Compute distances
      ifail = 0
      Call g03dbf(equal,mode,nvar,ng,gmn,ldgmn,gc,nobs,m,isx,x,ldx,d,ldd,wk,   &
        ifail)

!     Display results
      ifail = 0
      Call x04caf('General',' ',nobs,ng,d,ldd,'Distances',ifail)

    End Program g03dbfe


g03dcfe.f90

    Program g03dcfe

!     G03DCF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: g03daf, g03dcf, nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: df, sig, stat
      Integer                          :: i, ifail, ldgmn, ldox, ldp, ldx,     &
                                          lgc, lwk, lwt, m, n, ng, nobs, nvar, &
                                          tdati
      Logical                          :: atiq
      Character (1)                    :: equal, priors, typ, weight
      Character (80)                   :: fmt
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: ati(:,:), det(:), gc(:), gmn(:,:),   &
                                          ox(:,:), p(:,:), prior(:), wk(:),    &
                                          wt(:), x(:,:)
      Integer, Allocatable             :: iag(:), ing(:), isx(:), iwk(:),      &
                                          nig(:)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: count, max
!     .. Executable Statements ..
      Write (nout,*) 'G03DCF Example Program Results'
      Write (nout,*)

!     Skip headings in data file
      Read (nin,*)

!     Read in the problem size
      Read (nin,*) n, m, ng, weight

      If (weight=='W' .Or. weight=='w') Then
        lwt = n
      Else
        lwt = 0
      End If
      ldox = n
      Allocate (ox(ldox,m),ing(n),wt(lwt),isx(m))

!     Read in data
      If (lwt>0) Then
        Read (nin,*)(ox(i,1:m),ing(i),wt(i),i=1,n)
      Else
        Read (nin,*)(ox(i,1:m),ing(i),i=1,n)
      End If

!     Read in variable inclusion flags
      Read (nin,*) isx(1:m)

!     Calculate NVAR
      nvar = count(isx(1:m)==1)

      lwk = max(n*(nvar+1),2*nvar)
      ldgmn = ng
      lgc = (ng+1)*nvar*(nvar+1)/2
      Allocate (nig(ng),gmn(ldgmn,nvar),det(ng),gc(lgc),wk(lwk),iwk(ng))

!     Compute covariance matrix
      ifail = 0
      Call g03daf(weight,n,m,ox,ldox,isx,nvar,ing,ng,wt,nig,gmn,ldgmn,det,gc,  &
        stat,df,sig,wk,iwk,ifail)

!     Read in parameters controlling grouping
      Read (nin,*) typ, equal, priors, nobs, atiq

      If (atiq) Then
        tdati = ng
      Else
        tdati = 1
      End If
      ldx = nobs
      ldp = nobs
      Allocate (x(ldx,m),prior(ng),p(ldp,ng),iag(nobs),ati(ldp,tdati))

!     Read in data to group
      Read (nin,*)(x(i,1:m),i=1,nobs)

!     Read in priors
      If (priors=='I' .Or. priors=='i') Then
        Read (nin,*) prior(1:ng)
      End If

!     Allocate observations to groups
      ifail = 0
      Call g03dcf(typ,equal,priors,nvar,ng,nig,gmn,ldgmn,gc,det,nobs,m,isx,x,  &
        ldx,prior,p,ldp,iag,atiq,ati,wk,ifail)

!     Display results
      If (atiq) Then
        Write (fmt,99999) '(2(I6,5X,', ng, 'F6.3))'
        Write (nout,*) '   Obs       Posterior        Allocated',              &
          '     Atypicality'
        Write (nout,*) '             probabilities    to group      index'
        Write (nout,*)
        Write (nout,fmt)(i,p(i,1:ng),iag(i),ati(i,1:ng),i=1,nobs)
      Else
        Write (fmt,99999) '(I6,5X,', ng, 'F6.3,I6))'
        Write (nout,*) '   Obs       Posterior        Allocated'
        Write (nout,*) '             probabilities    to group '
        Write (nout,*)
        Write (nout,fmt)(i,p(i,1:ng),iag(i),i=1,nobs)
      End If

99999 Format (A,I0,A)
    End Program g03dcfe


g03eafe.f90

    Program g03eafe

!     G03EAF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: g03eaf, nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Integer                          :: i, ifail, ld, ldx, lj, m, n, uj
      Character (1)                    :: dist, scal, update
      Character (80)                   :: fmt
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: d(:), s(:), x(:,:)
      Integer, Allocatable             :: isx(:)
!     .. Executable Statements ..
      Write (nout,*) 'G03EAF Example Program Results'
      Write (nout,*)

!     Skip heading in data file
      Read (nin,*)

!     Read in the problem size
      Read (nin,*) n, m

!     Read in information on the type of distance matrix to use
      Read (nin,*) update, dist, scal

      ldx = n
      ld = n*(n-1)/2
      Allocate (x(ldx,m),isx(m),s(m),d(ld))

!     Read in the data used to construct distance matrix
      Read (nin,*)(x(i,1:m),i=1,n)

!     Read in variable inclusion flags
      Read (nin,*) isx(1:m)

!     Read in scaling
      If (scal=='G' .Or. scal=='g') Then
        Read (nin,*) s(1:m)
      End If

!     Compute the distance matrix
      ifail = 0
      Call g03eaf(update,dist,scal,n,m,x,ldx,isx,s,d,ifail)

!     Display results
      Write (nout,*) ' Distance Matrix'
      Write (nout,*)
      Write (fmt,99999) '(3X,', n - 1, 'I8)'
      Write (nout,fmt)(i,i=1,n-1)
      Write (nout,*)
      Write (fmt,99999) '(1X,I2,2X,', n - 1, '(3X,F5.2))'
      Do i = 2, n
        lj = (i-1)*(i-2)/2 + 1
        uj = i*(i-1)/2
        Write (nout,fmt) i, d(lj:uj)
      End Do

99999 Format (A,I0,A)
    End Program g03eafe


g03ecfe.f90

    Program g03ecfe

!     G03ECF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: g03eaf, g03ecf, nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6, rnlen = 3
!     .. Local Scalars ..
      Integer                          :: i, ifail, ld, ldx, liwk, m, method,  &
                                          n, n1
      Character (1)                    :: dist, scal, update
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: cd(:), d(:), dord(:), s(:), x(:,:)
      Integer, Allocatable             :: ilc(:), iord(:), isx(:), iuc(:),     &
                                          iwk(:)
      Character (rnlen), Allocatable   :: row_name(:)
!     .. Executable Statements ..
      Write (nout,*) 'G03ECF Example Program Results'
      Write (nout,*)

!     Skip heading in data file
      Read (nin,*)

!     Read in the problem size
      Read (nin,*) n, m

!     Read in information on the type of distance matrix to use
      Read (nin,*) update, dist, scal

      ldx = n
      ld = n*(n-1)/2
      n1 = n - 1
      liwk = 2*n
      Allocate (x(ldx,m),isx(m),s(m),d(ld),ilc(n1),iuc(n1),cd(n1),iord(n),     &
        dord(n),iwk(liwk),row_name(n))

!     Read in the data used to construct distance matrix
      Read (nin,*)(x(i,1:m),i=1,n)

!     Read in variable inclusion flags
      Read (nin,*) isx(1:m)

!     Read in scaling
      If (scal=='G' .Or. scal=='g') Then
        Read (nin,*) s(1:m)
      End If

!     Compute the distance matrix
      ifail = 0
      Call g03eaf(update,dist,scal,n,m,x,ldx,isx,s,d,ifail)

!     Read in information on the clustering method to use
      Read (nin,*) method

!     Read in first RNLEN characters of row names. Used to make example
!     output easier to read
      Read (nin,*) row_name(1:n)

!     Perform clustering
      ifail = 0
      Call g03ecf(method,n,d,ilc,iuc,cd,iord,dord,iwk,ifail)

!     Display results
      Write (nout,*) '  Distance   Clusters Joined'
      Write (nout,*)
      Write (nout,99999)(cd(i),row_name(ilc(i)),row_name(iuc(i)),i=1,n1)

99999 Format (F10.3,5X,2A)
    End Program g03ecfe


g03effe.f90

    Program g03effe

!     G03EFF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: g03eff, nag_wp, x04caf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Integer                          :: i, ifail, k, ldc, ldx, lwt, m,       &
                                          maxit, n, nvar
      Character (1)                    :: weight
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: cmeans(:,:), css(:), csw(:), wk(:),  &
                                          wt(:), x(:,:)
      Integer, Allocatable             :: inc(:), isx(:), iwk(:), nic(:)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: count
!     .. Executable Statements ..
      Write (nout,*) 'G03EFF Example Program Results'
      Write (nout,*)

!     Skip heading in the data file
      Read (nin,*)

!     Read in the problem size and control parameters
      Read (nin,*) weight, n, m, k, maxit

      If (weight=='W' .Or. weight=='w') Then
        lwt = n
      Else
        lwt = 0
      End If
      ldx = n
      Allocate (x(ldx,m),wt(n),isx(m))

!     Read in data
      If (lwt>0) Then
        Read (nin,*)(x(i,1:m),wt(i),i=1,n)
      Else
        Read (nin,*)(x(i,1:m),i=1,n)
      End If

!     Read in variable inclusion flags
      Read (nin,*) isx(1:m)

!     Calculate NVAR
      nvar = count(isx(1:m)==1)

      ldc = k
      Allocate (cmeans(ldc,nvar),inc(n),nic(k),css(k),csw(k),iwk(n+3*k),       &
        wk(n+2*k))

!     Read in the initial cluster centres
      Read (nin,*)(cmeans(i,1:nvar),i=1,k)

!     Perform k means clustering
      ifail = 0
      Call g03eff(weight,n,m,x,ldx,isx,nvar,k,cmeans,ldc,wt,inc,nic,css,csw,   &
        maxit,iwk,wk,ifail)

!     Display results
      Write (nout,*) ' The cluster each point belongs to'
      Write (nout,99999) inc(1:n)
      Write (nout,*)
      Write (nout,*) ' The number of points in each cluster'
      Write (nout,99999) nic(1:k)
      Write (nout,*)
      Write (nout,*) ' The within-cluster sum of weights of each cluster'
      Write (nout,99998) csw(1:k)
      Write (nout,*)
      Write (nout,*) ' The within-cluster sum of squares of each cluster'
      Write (nout,99997) css(1:k)
      Write (nout,*)
      Flush (nout)
      ifail = 0
      Call x04caf('General',' ',k,nvar,cmeans,ldc,'The final cluster centres', &
        ifail)

99999 Format (1X,10I6)
99998 Format (1X,5F9.2)
99997 Format (1X,5F13.4)
    End Program g03effe


g03ehfe.f90

    Program g03ehfe

!     G03EHF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: g03eaf, g03ecf, g03ehf, nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: llen = 50, nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: dmin, dstep
      Integer                          :: ellen, i, ifail, ld, ldx, lenc,      &
                                          liwk, m, method, n, n1, nsym, olenc
      Character (1)                    :: dist, orient, scal, update
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: cd(:), d(:), dord(:), s(:), x(:,:)
      Integer, Allocatable             :: ilc(:), iord(:), isx(:), iuc(:),     &
                                          iwk(:)
      Character (llen), Allocatable    :: c(:)
!     .. Executable Statements ..
      Write (nout,*) 'G03EHF Example Program Results'
      Write (nout,*)

!     Skip heading in data file
      Read (nin,*)

!     Read in the problem size
      Read (nin,*) n, m

!     Read in information on the type of distance matrix to use
      Read (nin,*) update, dist, scal

      ldx = n
      ld = n*(n-1)/2
      n1 = n - 1
      liwk = 2*n
      Allocate (x(ldx,m),isx(m),s(m),d(ld),ilc(n1),iuc(n1),cd(n1),iord(n),     &
        dord(n),iwk(liwk),c(1))

!     Read in the data used to construct distance matrix
      Read (nin,*)(x(i,1:m),i=1,n)

!     Read in variable inclusion flags
      Read (nin,*) isx(1:m)

!     Read in scaling
      If (scal=='G' .Or. scal=='g') Then
        Read (nin,*) s(1:m)
      End If

!     Compute the distance matrix
      ifail = 0
      Call g03eaf(update,dist,scal,n,m,x,ldx,isx,s,d,ifail)

!     Read in information on the clustering method to use
      Read (nin,*) method

!     Perform clustering
      ifail = 0
      Call g03ecf(method,n,d,ilc,iuc,cd,iord,dord,iwk,ifail)

!     Produce some example dendrogram
      olenc = 0
d_lp: Do
        Read (nin,*,Iostat=ifail) orient, dmin, dstep, nsym
        If (ifail/=0) Then
          Go To 100
        End If

!       Display the dendrogram
        Select Case (orient)
        Case ('N')
          Write (nout,*) 'Dendrogram, Orientation North'
          lenc = nsym
          ellen = n
        Case ('E')
          Write (nout,*) 'Dendrogram, Orientation East'
          lenc = n
          ellen = nsym
        Case ('S')
          Write (nout,*) 'Dendrogram, Orientation South'
          lenc = nsym
          ellen = n
        Case ('W')
          Write (nout,*) 'Dendrogram, Orientation West'
          lenc = n
          ellen = nsym
        End Select

!       Check that each element in the character array is sufficiently large
        If (llen<ellen) Then
          Write (nout,*)                                                       &
            'Each element of character array C needs to be at least ', ellen
          Write (nout,*) 'elements long, current length is ', llen
          Go To 100
        End If

        If (olenc<lenc) Then
!         Reallocate matrix
          Deallocate (c)
          Allocate (c(lenc))
        End If

!       Generate character array holding the dendrogram
        ifail = 0
        Call g03ehf(orient,n,dord,dmin,dstep,nsym,c,lenc,ifail)

        Write (nout,99999) c(1:lenc)
        Write (nout,*)
      End Do d_lp

100   Continue

99999 Format (1X,A)
    End Program g03ehfe


g03ejfe.f90

    Program g03ejfe

!     G03EJF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: g03eaf, g03ecf, g03ejf, nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6, rnlen = 3
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: dlevel
      Integer                          :: i, ifail, k, ld, ldx, liwk, m,       &
                                          method, n, n1
      Character (1)                    :: dist, scal, update
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: cd(:), d(:), dord(:), s(:), x(:,:)
      Integer, Allocatable             :: ic(:), ilc(:), iord(:), isx(:),      &
                                          iuc(:), iwk(:)
      Character (rnlen), Allocatable   :: row_name(:)
!     .. Executable Statements ..
      Write (nout,*) 'G03EJF Example Program Results'
      Write (nout,*)

!     Skip heading in data file
      Read (nin,*)

!     Read in the problem size
      Read (nin,*) n, m

!     Read in information on the type of distance matrix to use
      Read (nin,*) update, dist, scal

      ldx = n
      ld = n*(n-1)/2
      n1 = n - 1
      liwk = 2*n
      Allocate (x(ldx,m),isx(m),s(m),d(ld),ilc(n1),iuc(n1),cd(n1),iord(n),     &
        dord(n),iwk(liwk),ic(n),row_name(n))

!     Read in the data used to construct distance matrix
      Read (nin,*)(x(i,1:m),i=1,n)

!     Read in variable inclusion flags
      Read (nin,*) isx(1:m)

!     Read in scaling
      If (scal=='G' .Or. scal=='g') Then
        Read (nin,*) s(1:m)
      End If

!     Compute the distance matrix
      ifail = 0
      Call g03eaf(update,dist,scal,n,m,x,ldx,isx,s,d,ifail)

!     Read in information on the clustering method to use
      Read (nin,*) method

!     Read in first RNLEN characters of row names. Used to make example
!     output easier to read
      Read (nin,*) row_name(1:n)

!     Perform clustering
      ifail = 0
      Call g03ecf(method,n,d,ilc,iuc,cd,iord,dord,iwk,ifail)

!     Display full clustering information
      Write (nout,*) '  Distance   Clusters Joined'
      Write (nout,*)
      Do i = 1, n - 1
        Write (nout,99999) cd(i), row_name(ilc(i)), row_name(iuc(i))
      End Do
      Write (nout,*)

!     Read in number of clusters required (K) and
!     distance (DLEVEL). If K > 0 then DLEVEL is
!     ignored (i.e. attempt to find K clusters,
!     irrespective of distance), else all clusters at
!     level DLEVEL are used
      Read (nin,*) k, dlevel

!     Compute cluster indicator
      ifail = 0
      Call g03ejf(n,cd,iord,dord,k,dlevel,ic,ifail)

!     Display the indicators
      Write (nout,99998) ' Allocation to ', k, ' clusters'
      Write (nout,99996) ' Clusters found at distance ', dlevel
      Write (nout,*)
      Write (nout,*) ' Object  Cluster'
      Write (nout,*)
      Write (nout,99997)(row_name(i),ic(i),i=1,n)

99999 Format (1X,F10.3,5X,2A)
99998 Format (1X,A,I0,A)
99997 Format (6X,A,5X,I2)
99996 Format (1X,A,F0.3)
    End Program g03ejfe


g03fafe.f90

    Program g03fafe

!     G03FAF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: g03faf, nag_wp, x04caf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Integer                          :: ifail, ld, ldx, liwk, lwk, n, ndim
      Character (1)                    :: roots
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: d(:), eval(:), wk(:), x(:,:)
      Integer, Allocatable             :: iwk(:)
!     .. Executable Statements ..
      Write (nout,*) 'G03FAF Example Program Results'
      Write (nout,*)

!     Skip heading in data file
      Read (nin,*)

!     Read in the problem size
      Read (nin,*) n, ndim, roots

      ld = n*(n-1)/2
      ldx = n
      lwk = n*(n+17)/2 - 1
      liwk = 5*n
      Allocate (d(ld),x(ldx,ndim),eval(n),wk(lwk),iwk(liwk))

!     Read in the lower triangular part of the distance matrix
      Read (nin,*) d(1:ld)

!     Perform principal co-ordinate analysis
      ifail = 0
      Call g03faf(roots,n,d,ndim,x,ldx,eval,wk,iwk,ifail)

!     Display results
      Write (nout,*) ' Scaled Eigenvalues'
      Write (nout,*)
      If (roots=='L' .Or. roots=='l') Then
        Write (nout,99999) eval(1:ndim)
      Else
        Write (nout,99999) eval(1:n)
      End If
      Write (nout,*)
      Flush (nout)
      ifail = 0
      Call x04caf('General',' ',n,ndim,x,ldx,'Co-ordinates',ifail)

99999 Format (8F10.4)
    End Program g03fafe


g03fcfe.f90

    Program g03fcfe

!     G03FCF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: g03faf, g03fcf, nag_wp, x04caf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: stress
      Integer                          :: ifail, iopt, iter, ld, ldfit, ldx,   &
                                          liwk, lwk, n, ndim
      Character (1)                    :: roots, typ
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: d(:), dfit(:), eval(:), wk(:),       &
                                          x(:,:)
      Integer, Allocatable             :: iwk(:)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: max
!     .. Executable Statements ..
      Write (nout,*) 'G03FCF Example Program Results'
      Write (nout,*)

!     Skip heading in data file
      Read (nin,*)

!     Read in the problem size
      Read (nin,*) n, ndim, roots, typ

      ld = n*(n-1)/2
      ldx = n
      lwk = max(n*(n+17)/2-1,15*n*ndim)
      liwk = max(5*n,n*(n-1)/2+n*ndim+5)
      ldfit = 2*n*(n-1)
      Allocate (d(ld),x(ldx,ndim),eval(n),wk(lwk),iwk(liwk),dfit(ldfit))

!     Read in the lower triangular part of the distance matrix
      Read (nin,*) d(1:ld)

!     Perform principal co-ordinate analysis
      ifail = 0
      Call g03faf(roots,n,d,ndim,x,ldx,eval,wk,iwk,ifail)

!     Use default values for number of iterations and options
      iter = 0
      iopt = 0

!     Perform multi-dimensional scaling
      ifail = 0
      Call g03fcf(typ,n,ndim,d,x,ldx,stress,dfit,iter,iopt,wk,iwk,ifail)

!     Display the results
      Write (nout,99999) 'STRESS = ', stress
      Write (nout,*)
      Flush (nout)
      ifail = 0
      Call x04caf('General',' ',n,ndim,x,ldx,'Co-ordinates',ifail)

99999 Format (10X,A,E13.4)
    End Program g03fcfe


g03gafe.f90

    Program g03gafe

!     G03GAF Example Program Text
!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: g03gaf, nag_wp, x04caf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: loglik, tol
      Integer                          :: i, ifail, ldprob, lds, ldx, m, n,    &
                                          ng, niter, nvar, popt, riter, sds,   &
                                          sopt
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: f(:,:), g(:,:), prob(:,:), s(:,:,:), &
                                          w(:), x(:,:)
      Integer, Allocatable             :: isx(:)
!     .. Executable Statements ..
      Write (nout,*) 'G03GAF Example Program Results'
      Write (nout,*)
      Flush (nout)

!     Skip heading in data file
      Read (nin,*)

!     Problem size
      Read (nin,*) n, m, nvar

!     Number of groups
      Read (nin,*) ng

!     Scaling option
      Read (nin,*) sopt

!     Initial probabilities option
      Read (nin,*) popt

!     Maximum number of iterations
      Read (nin,*) niter

!     Leading dimensions
      ldx = n
      ldprob = n

      Select Case (sopt)
      Case (1)
        Allocate (s(nvar,nvar,ng))
        lds = nvar
        sds = nvar
      Case (2)
        Allocate (s(nvar,nvar,1))
        lds = nvar
        sds = nvar
      Case (3)
        Allocate (s(nvar,ng,1))
        lds = nvar
        sds = ng
      Case (4)
        Allocate (s(nvar,1,1))
        lds = nvar
        sds = 1
      Case Default
        Allocate (s(1,1,1))
        lds = 1
        sds = 1
      End Select

      Allocate (x(ldx,m),prob(ldprob,ng),g(nvar,ng),w(ng),isx(m),f(n,ng))

!     Data matrix X
      Read (nin,*)(x(i,1:m),i=1,n)

!     Included variables
      If (nvar/=m) Then
        Read (nin,*) isx(1:m)
      End If

!     Optionally read initial probabilities of group membership
      If (popt==2) Then
        Read (nin,*)(prob(i,1:ng),i=1,n)
      End If

      tol = 0.0E0_nag_wp
      riter = 5

      ifail = 0
      Call g03gaf(n,m,x,ldx,isx,nvar,ng,popt,prob,ldprob,niter,riter,w,g,sopt, &
        s,lds,sds,f,tol,loglik,ifail)

!     Results
      Write (nout,*)
      ifail = 0
      Call x04caf('g','n',1,ng,w,1,'Mixing proportions',ifail)

      Write (nout,*)
      ifail = 0
      Call x04caf('g','n',nvar,ng,g,nvar,'Group means',ifail)

      Write (nout,*)
      Select Case (sopt)
      Case (1)
        Do i = 1, ng
          ifail = 0
          Call x04caf('g','n',nvar,nvar,s(1,1,i),lds,                          &
            'Variance-covariance matrix',ifail)
        End Do
      Case (2)
        ifail = 0
        Call x04caf('g','n',nvar,nvar,s,lds,                                   &
          'Pooled Variance-covariance matrix',ifail)
      Case (3)
        ifail = 0
        Call x04caf('g','n',nvar,ng,s,lds,'Groupwise Variance',ifail)
      Case (4)
        ifail = 0
        Call x04caf('g','n',nvar,1,s,lds,'Pooled Variance',ifail)
      Case (5)
        ifail = 0
        Call x04caf('g','n',1,1,s,lds,'Overall Variance',ifail)
      End Select

      Write (nout,*)
      ifail = 0
      Call x04caf('g','n',n,ng,f,n,'Densities',ifail)

      Write (nout,*)
      ifail = 0
      Call x04caf('g','n',n,ng,prob,n,'Membership probabilities',ifail)

      Write (nout,*)
      Write (nout,'(1X,A,1X,I16)') 'No. iterations:', niter

      Write (nout,'(1X,A,1X,F16.4)') 'Log-likelihood:', loglik

      Deallocate (x,prob,g,s,w,isx,f)
    End Program g03gafe


g03zafe.f90

    Program g03zafe

!     G03ZAF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: g03zaf, nag_wp, x04caf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Integer                          :: i, ifail, ldx, ldz, m, n, nvar
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: e(:), s(:), x(:,:), z(:,:)
      Integer, Allocatable             :: isx(:)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: count
!     .. Executable Statements ..
      Write (nout,*) 'G03ZAF Example Program Results'
      Write (nout,*)
      Flush (nout)

!     Skip headings in data file
      Read (nin,*)

!     Read in the problem size
      Read (nin,*) n, m

      ldx = n
      Allocate (x(ldx,m),isx(m),e(m),s(m))

!     Read in data
      Read (nin,*)(x(i,1:m),i=1,n)

!     Read in variable inclusion flags
      Read (nin,*) isx(1:m)

!     Read in shift and scaling
      Read (nin,*) e(1:m)
      Read (nin,*) s(1:m)

!     Calculate NVAR
      nvar = count(isx(1:m)/=0)

      ldz = n
      Allocate (z(ldz,nvar))

!     Standardize data
      ifail = 0
      Call g03zaf(n,m,x,ldx,nvar,isx,s,e,z,ldz,ifail)

!     Display results
      ifail = 0
      Call x04caf('General',' ',n,nvar,z,ldz,'Standardized Values',ifail)

    End Program g03zafe


g04agfe.f90

    Program g04agfe

!     G04AGF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: g04agf, nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: gm
      Integer                          :: i, ifail, ii, j, k, l, li, n, nhi,   &
                                          nij, nlo, nsub
!     .. Local Arrays ..
      Real (Kind=nag_wp)               :: f(2), fp(2), ss(4)
      Real (Kind=nag_wp), Allocatable  :: gbar(:), sgbar(:), y(:)
      Integer                          :: idf(4)
      Integer, Allocatable             :: lsub(:), ngp(:), nobs(:)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: sum
!     .. Executable Statements ..
      Write (nout,*) 'G04AGF Example Program Results'
      Write (nout,*)

!     Skip heading in data file
      Read (nin,*)

!     Read in number of groups
      Read (nin,*) k

      Allocate (lsub(k),ngp(k),gbar(k))

!     Read in number of subgroups
      Read (nin,*) lsub(1:k)

!     Total number of subgroups
      l = sum(lsub(1:k))

      Allocate (nobs(l),sgbar(l))

!     Read in the number of observations
      Read (nin,*) nobs(1:l)

!     Total number of observations
      n = sum(nobs(1:l))

      Allocate (y(n))

!     Read in the data
      Read (nin,*) y(1:n)

!     Display data
      Write (nout,*) 'Data values'
      Write (nout,*)
      Write (nout,*) ' Group  Subgroup  Observations'
      nsub = 0
      nlo = 1
      Do i = 1, k
        li = lsub(i)
        Do j = 1, li
          nsub = nsub + 1
          nij = nobs(nsub)
          nhi = nlo + nij - 1
          Write (nout,99999) i, j, y(nlo:nhi)
          nlo = nlo + nij
        End Do
      End Do

!     Perform ANOVA
      ifail = 0
      Call g04agf(y,n,k,lsub,nobs,l,ngp,gbar,sgbar,gm,ss,idf,f,fp,ifail)

!     Display results
      Write (nout,*)
      Write (nout,*) 'Subgroup means'
      Write (nout,*)
      Write (nout,*) '   Group  Subgroup  Mean'
      ii = 0
      Do i = 1, k
        li = lsub(i)
        Do j = 1, li
          ii = ii + 1
          Write (nout,99998) i, j, sgbar(ii)
        End Do
      End Do
      Write (nout,*)
      Write (nout,99997) '    Group 1 mean =', gbar(1), '   (', ngp(1),        &
        ' observations)'
      Write (nout,99997) '    Group 2 mean =', gbar(2), '   (', ngp(2),        &
        ' observations)'
      Write (nout,99997) '    Grand mean   =', gm, '   (', n, ' observations)'
      Write (nout,*)
      Write (nout,*) 'Analysis of variance table'
      Write (nout,*)
      Write (nout,*) '   Source                SS    DF  F ratio  Sig'
      Write (nout,*)
      Write (nout,99996) 'Between groups        ', ss(1), idf(1), f(1), fp(1)
      Write (nout,99996) 'Bet sbgps within gps  ', ss(2), idf(2), f(2), fp(2)
      Write (nout,99996) 'Residual              ', ss(3), idf(3)
      Write (nout,*)
      Write (nout,99996) 'Total                 ', ss(4), idf(4)

99999 Format (1X,I5,I9,4X,10F4.1)
99998 Format (1X,I6,I8,F10.2)
99997 Format (1X,A,F5.2,A,I2,A)
99996 Format (1X,A,F6.3,I5,F7.2,F8.3)
    End Program g04agfe


g04bbfe.f90

    Program g04bbfe

!     G04BBF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: g04bbf, nag_wp, x04caf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: ldtabl = 4, nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: gmean, tol
      Integer                          :: iblock, ifail, irdf, ldc, lit, n, nt
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: bmean(:), c(:,:), ef(:), r(:),       &
                                          tmean(:), wk(:), y(:)
      Real (Kind=nag_wp)               :: tabl(ldtabl,5)
      Integer, Allocatable             :: irep(:), it(:)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: abs
!     .. Executable Statements ..
      Write (nout,*) 'G04BBF Example Program Results'
      Write (nout,*)

!     Skip heading in data file
      Read (nin,*)

!     Read in the problem size
      Read (nin,*) n, nt, iblock

      ldc = nt
      If (nt>1) Then
        lit = n
      Else
        lit = 1
      End If
      Allocate (y(n),bmean(abs(iblock)),tmean(nt),irep(nt),c(ldc,nt),r(n),     &
        ef(nt),wk(3*nt),it(lit))

!     Read in the data and plot information
      Read (nin,*) y(1:n)
      If (nt>1) Then
        Read (nin,*) it(1:n)
      End If

!     Use default tolerance
      tol = 0.0E0_nag_wp

!     Use standard degrees of freedom
      irdf = 0

!     Calculate the ANOVA table
      ifail = 0
      Call g04bbf(n,y,iblock,nt,it,gmean,bmean,tmean,tabl,ldtabl,c,ldc,irep,r, &
        ef,tol,irdf,wk,ifail)

!     Display results
      Write (nout,*) ' ANOVA table'
      Write (nout,*)
      Write (nout,*) '  Source        df         SS          MS          F',   &
        '        Prob'
      Write (nout,*)
      Write (nout,99998) ' Blocks      ', tabl(1,1:5)
      Write (nout,99998) ' Treatments  ', tabl(2,1:5)
      Write (nout,99998) ' Residual    ', tabl(3,1:3)
      Write (nout,99998) ' Total       ', tabl(4,1:2)
      Write (nout,*)
      Write (nout,*) ' Efficiency Factors'
      Write (nout,*)
      Write (nout,99999) ef(1:nt)
      Write (nout,*)
      Write (nout,99997) '  Grand Mean', gmean
      Write (nout,*)
      Write (nout,*) ' Treatment Means'
      Write (nout,*)
      Write (nout,99999) tmean(1:nt)
      Write (nout,*)
      Flush (nout)
      ifail = 0
      Call x04caf('Lower','B',nt,nt,c,ldc,                                     &
        'Standard errors of differences between means',ifail)

99999 Format (8F10.2)
99998 Format (A,3X,F3.0,2X,3(F10.2,2X),F9.4)
99997 Format (A,F10.2)
    End Program g04bbfe


g04bcfe.f90

    Program g04bcfe

!     G04BCF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: g04bcf, nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: ldtabl = 6, nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: gmean, tol
      Integer                          :: ifail, irdf, ldc, lit, n, ncol,      &
                                          nrep, nrow, nt
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: c(:,:), cmean(:), ef(:), r(:),       &
                                          rmean(:), rpmean(:), tmean(:),       &
                                          wk(:), y(:)
      Real (Kind=nag_wp)               :: tabl(ldtabl,5)
      Integer, Allocatable             :: irep(:), it(:)
!     .. Executable Statements ..
      Write (nout,*) 'G04BCF Example Program Results'
      Write (nout,*)

!     Skip heading in data file
      Read (nin,*)

!     Read in the problem size
      Read (nin,*) nrep, nrow, ncol, nt

      n = nrep*nrow*ncol
      If (nt>1) Then
        lit = n
      Else
        lit = 1
      End If
      ldc = nt
      Allocate (irep(nt),y(n),tmean(nt),it(lit),c(ldc,nt),rpmean(nrep),        &
        rmean(nrep*nrow),cmean(nrep*ncol),r(n),ef(nt),wk(3*nt))

!     Read in the data
      Read (nin,*) y(1:n)
      If (nt>1) Then
        Read (nin,*) it(1:n)
      End If

!     Use default tolerance
      tol = 0.0E0_nag_wp

!     Use standard degrees of freedom
      irdf = 0

!     Calculate the ANOVA table
      ifail = 0
      Call g04bcf(nrep,nrow,ncol,y,nt,it,gmean,tmean,tabl,ldtabl,c,ldc,irep,   &
        rpmean,rmean,cmean,r,ef,tol,irdf,wk,ifail)

!     Display results
      Write (nout,*) ' ANOVA TABLE'
      Write (nout,*)
      If (nrep>1) Then
        Write (nout,99998) ' Reps        ', tabl(1,1:5)
      End If
      Write (nout,99998) ' Rows        ', tabl(2,1:5)
      Write (nout,99998) ' Columns     ', tabl(3,1:5)
      If (nt>1) Then
        Write (nout,99998) ' Treatments  ', tabl(4,1:5)
      End If
      Write (nout,99998) ' Residual    ', tabl(5,1:3)
      Write (nout,99998) ' Total       ', tabl(6,1:2)
      If (nt>1) Then
        Write (nout,*)
        Write (nout,*) ' Treatment means'
        Write (nout,*)
        Write (nout,99999) tmean(1:nt)
        Write (nout,*)
        Write (nout,99997) ' S.E. of difference (orthogonal design) = ',       &
          c(2,1)
      End If

99999 Format (10F10.4)
99998 Format (A,F3.0,2X,3(F10.4,2X),F8.4)
99997 Format (A,F10.4)
    End Program g04bcfe


g04cafe.f90

    Program g04cafe

!     G04CAF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: g04caf, nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Integer                          :: i, ifail, inter, irdf, itotal, k, l, &
                                          maxt, mterm, n, nblock, nfac, ntreat
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: bmean(:), e(:), r(:), semean(:),     &
                                          table(:,:), tmean(:), y(:)
      Integer, Allocatable             :: imean(:), iwk(:), lfac(:)
!     .. Executable Statements ..
      Write (nout,*) 'G04CAF Example Program Results'
      Write (nout,*)

!     Skip heading in data file
      Read (nin,*)

!     Read in problem size
      Read (nin,*) n, nblock, nfac, inter

      Allocate (lfac(nfac),iwk(n+3*nfac),y(n),bmean(nblock+1),r(n))

!     Read in the number of levels for each factor
      Read (nin,*) lfac(1:nfac)

!     Read in the observations
      Read (nin,*) y(1:n)

!     Use standard degrees of freedom
      irdf = 0

!     Using call to G04CAF to calculate required values for MAXT and MTERM ...

!     Setting MAXT to zero ensures it is too small and hence the routine
!     will calculate its correct size, IMEAN needs to be at least 1 element
!     long so set MTERM to 1.
      maxt = 0
      mterm = 1

!     Dummy allocation
      Allocate (tmean(maxt),e(maxt),table(mterm,5),semean(mterm),imean(mterm))

!     Call the routine initially to get MTERM and MAXT
      ifail = 1
      Call g04caf(n,y,nfac,lfac,nblock,inter,irdf,mterm,table,itotal,tmean,    &
        maxt,e,imean,semean,bmean,r,iwk,ifail)
      If (ifail/=0 .And. ifail/=2) Then
        Write (nout,99996) ' ** G04CAF exited with IFAIL = ', ifail
        Go To 100
      End If

!     Allocate remaining output arrays
      mterm = itotal
      maxt = imean(1)
      Deallocate (tmean,e,table,semean,imean)
      Allocate (tmean(maxt),e(maxt),table(mterm,5),semean(mterm),imean(mterm))

!     Calculate the ANOVA table
      ifail = 0
      Call g04caf(n,y,nfac,lfac,nblock,inter,irdf,mterm,table,itotal,tmean,    &
        maxt,e,imean,semean,bmean,r,iwk,ifail)

!     Display results
      Write (nout,*) ' ANOVA table'
      Write (nout,*)
      Write (nout,*) '  Source      df         SS          MS          F',     &
        '        Prob'
      Write (nout,*)
      k = 0
      If (nblock>1) Then
        k = k + 1
        Write (nout,99998) ' Blocks    ', table(1,1:5)
      End If
      ntreat = itotal - 2 - k
      Do i = 1, ntreat
        Write (nout,99997) ' Effect  ', i, table(k+i,1:5)
      End Do
      Write (nout,99998) ' Residual  ', table(itotal-1,1:3)
      Write (nout,99998) ' Total     ', table(itotal,1:2)
      Write (nout,*)
      Write (nout,*) ' Treatment Means and Standard Errors'
      Write (nout,*)
      k = 1
      Do i = 1, ntreat
        l = imean(i)
        Write (nout,99996) ' Effect ', i
        Write (nout,*)
        Write (nout,99999) tmean(k:l)
        Write (nout,*)
        Write (nout,99995) ' SE of difference in means  = ', semean(i)
        Write (nout,*)
        k = l + 1
      End Do

100   Continue

99999 Format (8F10.2)
99998 Format (A,3X,F3.0,2X,2(F10.0,2X),F10.3,2X,F9.4)
99997 Format (A,I2,3X,F3.0,2X,2(F10.0,2X),F10.3,2X,F9.4)
99996 Format (A,I5)
99995 Format (A,F10.2)
    End Program g04cafe


g04dafe.f90

    Program g04dafe

!     G04DAF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: g04bbf, g04daf, nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: gmean, rdf, rms, tol
      Integer                          :: i, iblock, ifail, irdf, ldc, ldct,   &
                                          ldtabl, lit, n, nc, nt
      Logical                          :: usetx
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: bmean(:), c(:,:), ct(:,:), ef(:),    &
                                          est(:), r(:), tabl(:,:), tmean(:),   &
                                          tx(:), wk(:), y(:)
      Integer, Allocatable             :: irep(:), it(:)
      Character (11), Allocatable      :: names(:)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: abs
!     .. Executable Statements ..
      Write (nout,*) 'G04DAF Example Program Results'
      Write (nout,*)

!     Skip heading in data file
      Read (nin,*)

!     Read in problem size for G04BBF
      Read (nin,*) n, nt, iblock

      ldc = nt
      If (nt>1) Then
        lit = n
      Else
        lit = 1
      End If
      Allocate (y(n),bmean(abs(iblock)),tmean(nt),irep(nt),c(ldc,nt),r(n),     &
        ef(nt),wk(3*nt),it(lit))

!     Read in the data and plot information for G04BBF
      Read (nin,*) y(1:n)
      If (nt>1) Then
        Read (nin,*) it(1:n)
      End If

!     Don't use TX when calling G04DAF
      usetx = .False.

!     Read in the number of contrasts
      Read (nin,*) nc

!     Using first 4 rows of TABL in G04BBF next NC rows in  G04DAF
      ldtabl = nc + 4

      ldct = nt
      Allocate (ct(ldct,nc),est(nc),tabl(ldtabl,5),tx(nt),names(nc))

!     Read in the contrasts and their names
      Do i = 1, nc
        Read (nin,*) ct(1:nt,i)
        Read (nin,99999) names(i)
      End Do

!     Use default tolerance
      tol = 0.0E0_nag_wp

!     Use standard degrees of freedom
      irdf = 0

!     Calculate the ANOVA table
      ifail = 0
      Call g04bbf(n,y,iblock,nt,it,gmean,bmean,tmean,tabl,ldtabl,c,ldc,irep,r, &
        ef,tol,irdf,wk,ifail)

!     Display results from G04BBF
      Write (nout,*) ' ANOVA table'
      Write (nout,*)
      Write (nout,*) '  Source        df         SS          MS          F',   &
        '        Prob'
      Write (nout,*)
      If (iblock>1) Then
        Write (nout,99998) ' Blocks    ', tabl(1,1:5)
      End If
      Write (nout,99998) ' Treatments', tabl(2,1:5)
      Write (nout,99998) ' Residual  ', tabl(3,1:3)
      Write (nout,99998) ' Total     ', tabl(4,1:2)
      Write (nout,*)

!     Extract the residual mean square and degrees of freedom from ANOVA
!     table
      rms = tabl(3,3)
      rdf = tabl(3,1)

!     Compute sums of squares for contrast
      ifail = -1
      Call g04daf(nt,tmean,irep,rms,rdf,nc,ct,ldct,est,tabl(5,1),ldtabl,tol,   &
        usetx,tx,ifail)
      If (ifail/=0) Then
        If (ifail/=2) Then
          Go To 100
        End If
      End If

!     Display results from G04DAF
      Write (nout,*) ' Orthogonal Contrasts'
      Write (nout,*)
      Write (nout,99998)(names(i),tabl(i+4,1:5),i=1,nc)

100   Continue

99999 Format (A)
99998 Format (A,3X,F3.0,2X,F10.1,2X,F10.1,2X,F10.3,2X,F9.4)
    End Program g04dafe


g04dbfe.f90

    Program g04dbfe

!     G04DBF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: g04bbf, g04dbf, nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: clevel, gmean, rdf, tol
      Integer                          :: i, iblock, ifail, ij, irdf, j, ldc,  &
                                          lit, n, nt
      Character (1)                    :: typ
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: bmean(:), c(:,:), cil(:), ciu(:),    &
                                          ef(:), r(:), tmean(:), wk(:), y(:)
      Real (Kind=nag_wp)               :: table(4,5)
      Integer, Allocatable             :: irep(:), isig(:), it(:)
      Character (1)                    :: star(2)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: abs
!     .. Executable Statements ..
      Write (nout,*) 'G04DBF Example Program Results'
      Write (nout,*)

!     Skip heading in data file
      Read (nin,*)

!     Read in the problem size
      Read (nin,*) n, nt, iblock

      ldc = nt
      If (nt>1) Then
        lit = n
      Else
        lit = 1
      End If
      Allocate (y(n),bmean(abs(iblock)),tmean(nt),irep(nt),c(ldc,nt),r(n),     &
        ef(nt),wk(3*nt),it(lit),cil(nt*(nt-1)/2),ciu(nt*(nt-1)/2),isig(nt*(nt- &
        1)/2))

!     Read in the data and plot information
      Read (nin,*) y(1:n)
      If (nt>1) Then
        Read (nin,*) it(1:n)
      End If

!     Read in the type of level for the CIs
      Read (nin,*) typ, clevel

!     Use default tolerance
      tol = 0.0E0_nag_wp

!     Use standard degrees of freedom
      irdf = 0

!     Calculate the ANOVA table
      ifail = 0
      Call g04bbf(n,y,iblock,nt,it,gmean,bmean,tmean,table,4,c,ldc,irep,r,ef,  &
        tol,irdf,wk,ifail)

!     Display results from G04BBF
      Write (nout,*) ' ANOVA table'
      Write (nout,*)
      Write (nout,*) '  Source        df         SS          MS          F',   &
        '        Prob'
      Write (nout,*)
      If (iblock>1) Then
        Write (nout,99998) ' Blocks    ', table(1,1:5)
      End If
      Write (nout,99998) ' Treatments', table(2,1:5)
      Write (nout,99998) ' Residual  ', table(3,1:3)
      Write (nout,99998) ' Total     ', table(4,1:2)
      Write (nout,*)
      Write (nout,*) ' Treatment means'
      Write (nout,*)
      Write (nout,99999) tmean(1:nt)
      Write (nout,*)

!     Extract the residual degrees of freedom
      rdf = table(3,1)

!     Calculate simultaneous CIs
      ifail = 0
      Call g04dbf(typ,nt,tmean,rdf,c,ldc,clevel,cil,ciu,isig,ifail)

!     Display results from G04DBF
      Write (nout,*) ' Simultaneous Confidence Intervals'
      Write (nout,*)
      star(2) = '*'
      star(1) = ' '
      ij = 0
      Do i = 1, nt
        Do j = 1, i - 1
          ij = ij + 1
          Write (nout,99997) i, j, cil(ij), ciu(ij), star(isig(ij)+1)
        End Do
      End Do

99999 Format (10F8.3)
99998 Format (A,3X,F3.0,2X,2(F10.1,2X),F10.3,2X,F9.4)
99997 Format (2X,2I2,3X,2(F10.3,3X),A)
    End Program g04dbfe


g04eafe.f90

    Program g04eafe

!     G04EAF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: g02daf, g04eaf, nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: rss, tol
      Integer                          :: i, idf, ifail, ip, irank, j, ldq,    &
                                          ldx, levels, lv, lwt, m, n, tdx
      Logical                          :: svd
      Character (1)                    :: mean, typ, weight
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: b(:), cov(:), h(:), p(:), q(:,:),    &
                                          rep(:), res(:), se(:), v(:), wk(:),  &
                                          wt(:), x(:,:), y(:)
      Integer, Allocatable             :: ifact(:), isx(:)
!     .. Executable Statements ..
      Write (nout,*) 'G04EAF Example Program Results'
      Write (nout,*)

!     Skip heading in data file
      Read (nin,*)

!     Read in problem information
      Read (nin,*) n, levels, typ, weight, mean

      If (typ=='P' .Or. typ=='p') Then
        lv = levels
      Else
        lv = 1
      End If
      If (typ=='C' .Or. typ=='c') Then
        tdx = levels
      Else
        tdx = levels - 1
      End If
      If (weight=='w' .Or. weight=='W') Then
        lwt = n
      Else
        lwt = 1
      End If
      ldx = n
      Allocate (x(ldx,tdx),ifact(n),v(lv),rep(levels),y(n),wt(lwt))

!     Read in data
      If (weight=='W' .Or. weight=='w') Then
        Read (nin,*)(ifact(i),y(i),wt(i),i=1,n)
      Else
        Read (nin,*)(ifact(i),y(i),i=1,n)
      End If
      If (typ=='P' .Or. typ=='p') Then
        Read (nin,*) v(1:levels)
      End If

!     Calculate dummy variables
      ifail = 0
      Call g04eaf(typ,n,levels,ifact,x,ldx,v,rep,ifail)

      If (typ=='C' .Or. typ=='c') Then
        m = levels
      Else
        m = levels - 1
      End If
      ip = m
      If (mean=='M' .Or. mean=='m') Then
        ip = ip + 1
      End If

      ldq = n
      Allocate (isx(m),b(ip),se(ip),cov(ip*(ip+1)/2),res(n),h(n),q(ldq,ip+1),p &
        (2*ip+ip*ip),wk(5*(ip-1)+ip*ip))

!     Use all the variables in the regression
      isx(1:m) = 1

!     Use the suggested value for tolerance
      tol = 0.00001E0_nag_wp

!     Fit linear regression model
      ifail = 0
      Call g02daf(mean,weight,n,x,ldx,m,isx,ip,y,wt,rss,idf,b,se,cov,res,h,q,  &
        ldq,svd,irank,p,tol,wk,ifail)

!     Display the results of the regression
      If (svd) Then
        Write (nout,99999) 'Model not of full rank, rank = ', irank
        Write (nout,*)
      End If
      Write (nout,99998) 'Residual sum of squares = ', rss
      Write (nout,99999) 'Degrees of freedom = ', idf
      Write (nout,*)
      Write (nout,*) 'Variable   Parameter estimate   Standard error'
      Write (nout,*)
      Write (nout,99997)(j,b(j),se(j),j=1,ip)

99999 Format (1X,A,I4)
99998 Format (1X,A,E12.4)
99997 Format (1X,I6,2E20.4)
    End Program g04eafe


g05kffe.f90

    Program g05kffe

!     G05KFF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: g05kff, g05saf, nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: lseed = 1, nin = 5, nout = 6
!     .. Local Scalars ..
      Integer                          :: genid, ifail, lstate, n, subid
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: x(:)
      Integer                          :: seed(lseed)
      Integer, Allocatable             :: state(:)
!     .. Executable Statements ..
      Write (nout,*) 'G05KFF Example Program Results'
      Write (nout,*)

!     Skip heading in data file
      Read (nin,*)

!     Read in the base generator information and seed
      Read (nin,*) genid, subid, seed(1)

!     Initial call to initializer to get size of STATE array
      lstate = 0
      Allocate (state(lstate))
      ifail = 0
      Call g05kff(genid,subid,seed,lseed,state,lstate,ifail)

!     Reallocate STATE
      Deallocate (state)
      Allocate (state(lstate))

!     Initialize the generator to a repeatable sequence
      ifail = 0
      Call g05kff(genid,subid,seed,lseed,state,lstate,ifail)

!     Read in sample size
      Read (nin,*) n

      Allocate (x(n))

!     Generate the variates
      ifail = 0
      Call g05saf(n,state,x,ifail)

!     Display the variates
      Write (nout,99999) x(1:n)

99999 Format (1X,F10.4)
    End Program g05kffe


g05kgfe.f90

    Program g05kgfe

!     G05KGF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: g05kgf, g05tlf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nout = 6
!     .. Local Scalars ..
      Integer                          :: genid, ifail, lstate, n, subid
!     .. Local Arrays ..
      Integer, Allocatable             :: state(:), x1(:), x2(:)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: any
!     .. Executable Statements ..
      Write (nout,*) 'G05KGF Example Program Results'
      Write (nout,*)

!     Choose the base generator
      genid = 3
      subid = 1

!     Initial call to initializer to get size of STATE array
      lstate = 0
      Allocate (state(lstate))
      ifail = 0
      Call g05kgf(genid,subid,state,lstate,ifail)

!     Reallocate STATE
      Deallocate (state)
      Allocate (state(lstate))

!     Initialize the generator to a non-repeatable sequence
      ifail = 0
      Call g05kgf(genid,subid,state,lstate,ifail)

!     Using samples of size 500
      n = 500
      Allocate (x1(n),x2(n))

!     Generate a sample of values from a discrete uniform distribution
      Call g05tlf(n,-100,100,state,x1,ifail)

!     Re-initialize the generator to another non-repeatable sequence
!     NB: In practice, in order to preserve its statistical properties,
!     you should only initialize the RNG generators once
      ifail = 0
      Call g05kgf(genid,subid,state,lstate,ifail)

!     Generate a second sample of values from the same distribution
      Call g05tlf(n,-100,100,state,x2,ifail)

!     Check that the two samples are different
      If (any(x1/=x2)) Then
        Write (nout,*) 'The two samples differ, as expected'
      Else
        Write (nout,*) 'The two samples are the same'
        Write (nout,*) 'whilst this is possible, it is unlikely'
      End If

    End Program g05kgfe


g05khfe.f90

    Program g05khfe

!     G05KHF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: g05kff, g05khf, g05saf, nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: lseed = 1, nin = 5, nout = 6
!     .. Local Scalars ..
      Integer                          :: genid, i, ifail, lstate, n, nv,      &
                                          subid
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: x(:,:)
      Integer                          :: seed(lseed)
      Integer, Allocatable             :: state(:,:)
!     .. Executable Statements ..
      Write (nout,*) 'G05KHF Example Program Results'
      Write (nout,*)

!     Skip heading in data file
      Read (nin,*)

!     Read in the base generator information and seed
      Read (nin,*) genid, subid, seed(1)

!     Read in number of streams and sample size for each stream
      Read (nin,*) n, nv

!     Initial call to initializer to get size of STATE array
      lstate = 0
      Allocate (state(lstate,1))
      ifail = 0
      Call g05kff(genid,subid,seed,lseed,state,lstate,ifail)

!     Reallocate STATE
      Deallocate (state)
      Allocate (state(lstate,n))

      Allocate (x(nv,n))

!     Prepare N streams
      Do i = 1, n
!       Initialize each stream to a repeatable sequence
        ifail = 0
        Call g05kff(genid,subid,seed,lseed,state(1,i),lstate,ifail)

!       Prepare the I'th out of N streams
        ifail = 0
        Call g05khf(n,i,state(1,i),ifail)
      End Do

!     Generate a NV variates, from a uniform distribution, from each stream
      Do i = 1, n
        ifail = 0
        Call g05saf(nv,state(1,i),x(1,i),ifail)
      End Do

!     Display results
      Do i = 1, n
        Write (nout,99998) 'Stream ', i
        Write (nout,99999) x(1:nv,i)
        Write (nout,*)
      End Do

99999 Format (1X,F10.4)
99998 Format (1X,A,I16)
    End Program g05khfe


g05kjfe.f90

    Program g05kjfe

!     G05KJF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: g05kff, g05kjf, g05saf, nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: lseed = 1, nin = 5, nout = 6
!     .. Local Scalars ..
      Integer                          :: genid, ifail, lstate, n, nv, subid
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: x(:)
      Integer                          :: seed(lseed)
      Integer, Allocatable             :: state(:)
!     .. Executable Statements ..
      Write (nout,*) 'G05KJF Example Program Results'
      Write (nout,*)

!     Skip heading in data file
      Read (nin,*)

!     Read in the base generator information and seed
      Read (nin,*) genid, subid, seed(1)

!     Query G05KFF to get the require length of STATE array
      lstate = 0
      Allocate (state(lstate))
      ifail = 0
      Call g05kff(genid,subid,seed,lseed,state,lstate,ifail)

!     Reallocate STATE
      Deallocate (state)
      Allocate (state(lstate))

!     Initialize the generator to a repeatable sequence
      ifail = 0
      Call g05kff(genid,subid,seed,lseed,state,lstate,ifail)

!     Read in the skip ahead and sample size
      Read (nin,*) n, nv

      Allocate (x(nv))

!     Advance the sequence N places
      ifail = 0
      Call g05kjf(n,state,ifail)

!     Generate a NV variates from a uniform distribution
      ifail = 0
      Call g05saf(nv,state,x,ifail)

!     Display the variates
      Write (nout,99999) x(1:nv)

99999 Format (1X,F10.4)
    End Program g05kjfe


g05kkfe.f90

    Program g05kkfe

!     G05KKF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: g05kff, g05kkf, g05saf, nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: lseed = 1, nin = 5, nout = 6
!     .. Local Scalars ..
      Integer                          :: genid, ifail, lstate, n, nv, subid
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: x(:)
      Integer                          :: seed(lseed)
      Integer, Allocatable             :: state(:)
!     .. Executable Statements ..
      Write (nout,*) 'G05KKF Example Program Results'
      Write (nout,*)

!     Skip heading in data file
      Read (nin,*)

!     Read in the base generator information and seed
      Read (nin,*) genid, subid, seed(1)

!     Query G05KFF to get the require length of STATE array
      lstate = 0
      Allocate (state(lstate))
      ifail = 0
      Call g05kff(genid,subid,seed,lseed,state,lstate,ifail)

!     Reallocate STATE
      Deallocate (state)
      Allocate (state(lstate))

!     Initialize the generator to a repeatable sequence
      ifail = 0
      Call g05kff(genid,subid,seed,lseed,state,lstate,ifail)

!     Read in the skip ahead and sample size
      Read (nin,*) n, nv

      Allocate (x(nv))

!     Advance the sequence 2**N places
      ifail = 0
      Call g05kkf(n,state,ifail)

!     Generate a NV variates from a uniform distribution
      ifail = 0
      Call g05saf(nv,state,x,ifail)

!     Display the variates
      Write (nout,99999) x(1:nv)

99999 Format (1X,F10.4)
    End Program g05kkfe


g05ncfe.f90

    Program g05ncfe

!     G05NCF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: g05kff, g05ncf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: lseed = 1, nin = 5, nout = 6
!     .. Local Scalars ..
      Integer                          :: genid, i, ifail, j, lstate, n,       &
                                          nperm, subid
!     .. Local Arrays ..
      Integer, Allocatable             :: indx(:), state(:)
      Integer                          :: seed(lseed)
!     .. Executable Statements ..
      Write (nout,*) 'G05NCF Example Program Results'
      Write (nout,*)

!     Skip heading in data file
      Read (nin,*)

!     Read in the base generator information and seed
      Read (nin,*) genid, subid, seed(1)

!     Initial call to initializer to get size of STATE array
      lstate = 0
      Allocate (state(lstate))
      ifail = 0
      Call g05kff(genid,subid,seed,lseed,state,lstate,ifail)

!     Reallocate STATE
      Deallocate (state)
      Allocate (state(lstate))

!     Initialize the generator to a repeatable sequence
      ifail = 0
      Call g05kff(genid,subid,seed,lseed,state,lstate,ifail)

!     Read in sample size and number of permutations
      Read (nin,*) n, nperm

      Allocate (indx(n))

      Write (nout,99998) nperm, ' Permutations of first ', n, ' integers'
      Write (nout,*)

!     Permutate NPERM times
      Do j = 1, nperm
!       Set up the index vector
        Do i = 1, n
          indx(i) = i
        End Do

!       Call the permutation routine
        ifail = 0
        Call g05ncf(indx,n,state,ifail)

!       Display the results
        Write (nout,99999) indx(1:n)
      End Do

99999 Format (1X,8I3)
99998 Format (1X,I0,A,I0,A)
    End Program g05ncfe


g05ndfe.f90

    Program g05ndfe

!     G05NDF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: g05kff, g05ndf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: lseed = 1, nin = 5, nout = 6
!     .. Local Scalars ..
      Integer                          :: genid, i, ifail, lstate, m, n, pm,   &
                                          subid
!     .. Local Arrays ..
      Integer, Allocatable             :: ipop(:), isampl(:), state(:)
      Integer                          :: seed(lseed)
!     .. Executable Statements ..
      Write (nout,*) 'G05NDF Example Program Results'
      Write (nout,*)

!     Skip heading in data file
      Read (nin,*)

!     Read in the base generator information and seed
      Read (nin,*) genid, subid, seed(1)

!     Initial call to initializer to get size of STATE array
      lstate = 0
      Allocate (state(lstate))
      ifail = 0
      Call g05kff(genid,subid,seed,lseed,state,lstate,ifail)

!     Reallocate STATE
      Deallocate (state)
      Allocate (state(lstate))

!     Initialize the generator to a repeatable sequence
      ifail = 0
      Call g05kff(genid,subid,seed,lseed,state,lstate,ifail)

!     Read in sample size
      Read (nin,*) n

      Allocate (ipop(n))

!     Display title
      Write (nout,99999) ' Samples from the first ', n, ' integers'
      Write (nout,*)
      Write (nout,*) ' Sample size     Values'

!     Initialize the population
      Do i = 1, n
        ipop(i) = i
      End Do

!     Dummy allocation
      Allocate (isampl(1))

!     Loop over different sample sizes
      pm = 0
d_lp: Do
        Read (nin,*,Iostat=ifail) m
        If (ifail/=0) Then
          Exit d_lp
        End If

!       Reallocate ISAMPL
        If (pm/=m) Then
          Deallocate (isampl)
          Allocate (isampl(m))
          pm = m
        End If

!       Generate sample
        ifail = 0
        Call g05ndf(ipop,n,isampl,m,state,ifail)

!       Display the results
        Write (nout,99998) m, isampl(1:m)
      End Do d_lp

99999 Format (1X,A,I0,A)
99998 Format (1X,I6,9X,8(1X,I3))
    End Program g05ndfe


g05nefe.f90

    Program g05nefe

!     G05NEF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: g05kff, g05nef, nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: lseed = 1, nin = 5, nout = 6
!     .. Local Scalars ..
      Integer                          :: genid, i, ifail, lipop, lstate, m,   &
                                          n, subid
      Character (1)                    :: order, pop
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: wt(:)
      Integer, Allocatable             :: ipop(:), isampl(:), state(:)
      Integer                          :: seed(lseed)
!     .. Executable Statements ..
      Write (nout,*) 'G05NEF Example Program Results'
      Write (nout,*)

!     Skip heading in data file
      Read (nin,*)

!     Read in the base generator information and seed
      Read (nin,*) genid, subid, seed(1)

!     Initial call to initializer to get size of STATE array
      lstate = 0
      Allocate (state(lstate))
      ifail = 0
      Call g05kff(genid,subid,seed,lseed,state,lstate,ifail)

!     Reallocate STATE
      Deallocate (state)
      Allocate (state(lstate))

!     Initialize the generator to a repeatable sequence
      ifail = 0
      Call g05kff(genid,subid,seed,lseed,state,lstate,ifail)

!     Read in population size, sample size and order
      Read (nin,*) n, m, pop
      Read (nin,*) order

      Select Case (pop)
      Case ('S','s')
        lipop = n
      Case Default
        lipop = 0
      End Select

      Allocate (ipop(lipop),wt(n),isampl(m))

      If (lipop==n) Then
!       Read in the population and weights
        Do i = 1, n
          Read (nin,*) ipop(i), wt(i)
        End Do
      Else
!       Read in just the weights
        Do i = 1, n
          Read (nin,*) wt(i)
        End Do
      End If

!     Generate the sample without replacement, unequal weights
      Call g05nef(order,wt,pop,ipop,n,isampl,m,state,ifail)

!     Display the results
      Write (nout,99999)(isampl(i),i=1,m)

99999 Format (10(1X,I4))
    End Program g05nefe


g05pdfe.f90

    Program g05pdfe

!     G05PDF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: g05kff, g05pdf, nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: lseed = 1, nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: gamma
      Integer                          :: df, genid, i, ifail, ip, iq, lr,     &
                                          lstate, ltheta, nreal, num, rn,      &
                                          subid
      Logical                          :: fcall
      Character (1)                    :: dist
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: et(:), ht(:), r(:), theta(:)
      Integer                          :: seed(lseed)
      Integer, Allocatable             :: state(:)
!     .. Executable Statements ..
      Write (nout,*) 'G05PDF Example Program Results'
      Write (nout,*)

!     Skip heading in data file
      Read (nin,*)

!     Read in the base generator information and seed
      Read (nin,*) genid, subid, seed(1)

!     Initial call to initializer to get size of STATE array
      lstate = 0
      Allocate (state(lstate))
      ifail = 0
      Call g05kff(genid,subid,seed,lseed,state,lstate,ifail)

!     Reallocate STATE
      Deallocate (state)
      Allocate (state(lstate))

!     Initialize the generator to a repeatable sequence
      ifail = 0
      Call g05kff(genid,subid,seed,lseed,state,lstate,ifail)

!     Read in sample size and number of realizations
      Read (nin,*) num, nreal

!     Read in number of coefficients
      Read (nin,*) ip, iq

      lr = 2*(ip+iq+2)
      ltheta = ip + iq + 1
      Allocate (theta(ip+iq+1),ht(num),et(num),r(lr))

!     Read in error distribution
      Read (nin,*) dist

!     Read in degrees of freedom if required
      If (dist=='T' .Or. dist=='t') Then
        Read (nin,*) df
      End If

!     Read in rest of series parameters
      Read (nin,*) theta(1:ltheta)
      Read (nin,*) gamma

!     Set FCALL for first realization
      fcall = .True.

!     Generate NREAL realizations
      Do rn = 1, nreal

        ifail = 0
        Call g05pdf(dist,num,ip,iq,theta,gamma,df,ht,et,fcall,r,lr,state,      &
          ifail)

!       Display the results
        Write (nout,99998) ' Realization Number ', rn
        Write (nout,*) '   I            HT(I)            ET(I)'
        Write (nout,*) '  --------------------------------------'
        Write (nout,99999)(i,ht(i),et(i),i=1,num)
        Write (nout,*)

!       Set FCALL flag for any further realizations
        fcall = .False.
      End Do

99999 Format (1X,I5,1X,F16.4,1X,F16.4)
99998 Format (1X,A,I0)
    End Program g05pdfe


g05pefe.f90

    Program g05pefe

!     G05PEF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: g05kff, g05pef, nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: lseed = 1, nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: gamma
      Integer                          :: df, genid, i, ifail, ip, iq, lr,     &
                                          lstate, ltheta, nreal, num, rn,      &
                                          subid
      Logical                          :: fcall
      Character (1)                    :: dist
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: et(:), ht(:), r(:), theta(:)
      Integer                          :: seed(lseed)
      Integer, Allocatable             :: state(:)
!     .. Executable Statements ..
      Write (nout,*) 'G05PEF Example Program Results'
      Write (nout,*)

!     Skip heading in data file
      Read (nin,*)

!     Read in the base generator information and seed
      Read (nin,*) genid, subid, seed(1)

!     Initial call to initializer to get size of STATE array
      lstate = 0
      Allocate (state(lstate))
      ifail = 0
      Call g05kff(genid,subid,seed,lseed,state,lstate,ifail)

!     Reallocate STATE
      Deallocate (state)
      Allocate (state(lstate))

!     Initialize the generator to a repeatable sequence
      ifail = 0
      Call g05kff(genid,subid,seed,lseed,state,lstate,ifail)

!     Read in sample size and number of realizations
      Read (nin,*) num, nreal

!     Read in number of coefficients
      Read (nin,*) ip, iq

      lr = 2*(ip+iq+2)
      ltheta = iq + ip + 1
      Allocate (theta(ltheta),ht(num),et(num),r(lr))

!     Read in error distribution
      Read (nin,*) dist

!     Read in degrees of freedom if required
      If (dist=='T' .Or. dist=='t') Then
        Read (nin,*) df
      End If

!     Read in rest of series parameters
      Read (nin,*) theta(1:ltheta)
      Read (nin,*) gamma

!     Set FCALL for first realization
      fcall = .True.

!     Generate NREAL realizations
      Do rn = 1, nreal

        ifail = 0
        Call g05pef(dist,num,ip,iq,theta,gamma,df,ht,et,fcall,r,lr,state,      &
          ifail)

!       Display the results
        Write (nout,99998) 'Realization Number ', rn
        Write (nout,*) '   I            HT(I)            ET(I)'
        Write (nout,*) '  --------------------------------------'
        Write (nout,99999)(i,ht(i),et(i),i=1,num)
        Write (nout,*)

!       Set FCALL flag for any further realizations
        fcall = .False.
      End Do

99999 Format (1X,I5,1X,F16.4,1X,F16.4)
99998 Format (1X,A,I0)
    End Program g05pefe


g05pffe.f90

    Program g05pffe

!     G05PFF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: g05kff, g05pff, nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: lseed = 1, nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: gamma
      Integer                          :: df, genid, i, ifail, ip, iq, lr,     &
                                          lstate, ltheta, nreal, num, rn,      &
                                          subid
      Logical                          :: fcall
      Character (1)                    :: dist
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: et(:), ht(:), r(:), theta(:)
      Integer                          :: seed(lseed)
      Integer, Allocatable             :: state(:)
!     .. Executable Statements ..
      Write (nout,*) 'G05PFF Example Program Results'
      Write (nout,*)

!     Skip heading in data file
      Read (nin,*)

!     Read in the base generator information and seed
      Read (nin,*) genid, subid, seed(1)

!     Initial call to initializer to get size of STATE array
      lstate = 0
      Allocate (state(lstate))
      ifail = 0
      Call g05kff(genid,subid,seed,lseed,state,lstate,ifail)

!     Reallocate STATE
      Deallocate (state)
      Allocate (state(lstate))

!     Initialize the generator to a repeatable sequence
      ifail = 0
      Call g05kff(genid,subid,seed,lseed,state,lstate,ifail)

!     Read in sample size and number of realizations
      Read (nin,*) num, nreal

!     Read in number of coefficients
      Read (nin,*) ip, iq

      lr = 2*(ip+iq+2)
      ltheta = ip + iq + 1
      Allocate (theta(ltheta),ht(num),et(num),r(lr))

!     Read in error distribution
      Read (nin,*) dist

!     Read in degrees of freedom if required
      If (dist=='T' .Or. dist=='t') Then
        Read (nin,*) df
      End If

!     Read in rest of series parameters
      Read (nin,*) theta(1:ltheta)
      Read (nin,*) gamma

!     Set FCALL for first realization
      fcall = .True.

!     Generate NREAL realizations
      Do rn = 1, nreal

        ifail = 0
        Call g05pff(dist,num,ip,iq,theta,gamma,df,ht,et,fcall,r,lr,state,      &
          ifail)

!       Display the results
        Write (nout,99998) 'Realization Number ', rn
        Write (nout,*) '   I            HT(I)            ET(I)'
        Write (nout,*) '  --------------------------------------'
        Write (nout,99999)(i,ht(i),et(i),i=1,num)
        Write (nout,*)

!       Set FCALL flag for any further realizations
        fcall = .False.
      End Do

99999 Format (1X,I5,1X,F16.4,1X,F16.4)
99998 Format (1X,A,I0)
    End Program g05pffe


g05pgfe.f90

    Program g05pgfe

!     G05PGF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: g05kff, g05pgf, nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: lseed = 1, nin = 5, nout = 6
!     .. Local Scalars ..
      Integer                          :: df, genid, i, ifail, ip, iq, lr,     &
                                          lstate, ltheta, nreal, num, rn,      &
                                          subid
      Logical                          :: fcall
      Character (1)                    :: dist
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: et(:), ht(:), r(:), theta(:)
      Integer                          :: seed(lseed)
      Integer, Allocatable             :: state(:)
!     .. Executable Statements ..
      Write (nout,*) 'G05PGF Example Program Results'
      Write (nout,*)

!     Skip heading in data file
      Read (nin,*)

!     Read in the base generator information and seed
      Read (nin,*) genid, subid, seed(1)

!     Initial call to initializer to get size of STATE array
      lstate = 0
      Allocate (state(lstate))
      ifail = 0
      Call g05kff(genid,subid,seed,lseed,state,lstate,ifail)

!     Reallocate STATE
      Deallocate (state)
      Allocate (state(lstate))

!     Initialize the generator to a repeatable sequence
      ifail = 0
      Call g05kff(genid,subid,seed,lseed,state,lstate,ifail)

!     Read in sample size and number of realizations
      Read (nin,*) num, nreal

!     Read in number of coefficients
      Read (nin,*) ip, iq

      lr = 2*(ip+2*iq+2)
      ltheta = 2*iq + ip + 1
      Allocate (theta(ltheta),ht(num),et(num),r(lr))

!     Read in error distribution
      Read (nin,*) dist

!     Read in degrees of freedom if required
      If (dist=='T' .Or. dist=='t') Then
        Read (nin,*) df
      End If

!     Read in rest of series parameters
      Read (nin,*) theta(1:ltheta)

!     Set FCALL for first realization
      fcall = .True.

!     Generate NREAL realizations
      Do rn = 1, nreal

        ifail = 0
        Call g05pgf(dist,num,ip,iq,theta,df,ht,et,fcall,r,lr,state,ifail)

!       Display the results
        Write (nout,99998) 'Realization Number ', rn
        Write (nout,*) '   I            HT(I)            ET(I)'
        Write (nout,*) '  --------------------------------------'
        Write (nout,99999)(i,ht(i),et(i),i=1,num)
        Write (nout,*)

!       Set FCALL flag for any further realizations
        fcall = .False.
      End Do

99999 Format (1X,I5,1X,F16.4,1X,F16.4)
99998 Format (1X,A,I0)
    End Program g05pgfe


g05phfe.f90

    Program g05phfe

!     G05PHF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: g05kff, g05phf, nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: lseed = 1, nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: avar, var, xmean
      Integer                          :: genid, ifail, ip, iq, lr, lstate,    &
                                          mode, n, subid
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: phi(:), r(:), theta(:), x(:)
      Integer                          :: seed(lseed)
      Integer, Allocatable             :: state(:)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: max
!     .. Executable Statements ..
      Write (nout,*) 'G05PHF Example Program Results'
      Write (nout,*)

!     Skip heading in data file
      Read (nin,*)

!     Read in the base generator information and seed
      Read (nin,*) genid, subid, seed(1)

!     Initial call to initializer to get size of STATE array
      lstate = 0
      Allocate (state(lstate))
      ifail = 0
      Call g05kff(genid,subid,seed,lseed,state,lstate,ifail)

!     Reallocate STATE
      Deallocate (state)
      Allocate (state(lstate))

!     Initialize the generator to a repeatable sequence
      ifail = 0
      Call g05kff(genid,subid,seed,lseed,state,lstate,ifail)

!     Read in sample size
      Read (nin,*) n

!     Read in number of coefficients
      Read (nin,*) ip, iq

      lr = ip + iq + 6 + max(ip,iq+1)
      Allocate (phi(ip),theta(iq),x(n),r(lr))

!     Read in mean
      Read (nin,*) xmean

!     Read in autoregressive coefficients
      If (ip>0) Then
        Read (nin,*) phi(1:ip)
      End If

!     Read in moving average coefficients
      If (iq>0) Then
        Read (nin,*) theta(1:iq)
      End If

!     Read in variance
      Read (nin,*) avar

!     Using a single call to G05PHF, so set up reference vector
!     and generate values in one go
      mode = 2

      ifail = 0
      Call g05phf(mode,n,xmean,ip,phi,iq,theta,avar,r,lr,state,var,x,ifail)

!     Display the variates
      Write (nout,99999) x(1:n)

99999 Format (1X,F12.4)
    End Program g05phfe


g05pjfe.f90

    Program g05pjfe

!     G05PJF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: g05kff, g05pjf, nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: lseed = 1, nin = 5, nout = 6
!     .. Local Scalars ..
      Integer                          :: genid, i, ifail, ii, ip, iq, j, k,   &
                                          k2, l, ldvar, ldx, lphi, lr, lstate, &
                                          ltheta, mode, n, nreal, rn, subid
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: phi(:), r(:), theta(:), var(:,:),    &
                                          x(:,:), xmean(:)
      Integer                          :: seed(lseed)
      Integer, Allocatable             :: state(:)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: max
!     .. Executable Statements ..
      Write (nout,*) 'G05PJF Example Program Results'
      Write (nout,*)

!     Skip heading in data file
      Read (nin,*)

!     Read in the base generator information and seed
      Read (nin,*) genid, subid, seed(1)

!     Initial call to initializer to get size of STATE array
      lstate = 0
      Allocate (state(lstate))
      ifail = 0
      Call g05kff(genid,subid,seed,lseed,state,lstate,ifail)

!     Reallocate STATE
      Deallocate (state)
      Allocate (state(lstate))

!     Initialize the generator to a repeatable sequence
      ifail = 0
      Call g05kff(genid,subid,seed,lseed,state,lstate,ifail)

!     Read in the sample size and number of realizations
      Read (nin,*) n, nreal

!     Read in the number of coefficients
      Read (nin,*) k, ip, iq

      k2 = k**2
      rn = max(ip,iq)
      l = k*(k+1)/2
      If (ip>0) Then
        l = l + (ip-1)*k2
      End If
      If (k>=6) Then
        lr = (5*rn**2+1)*k2 + (4*rn+3) + 4
      Else
        lr = ((ip+iq)**2+1)*k2 + (4*(ip+iq)+3)*k + max(k*rn*(k*rn+2),k2*(ip+iq &
          )**2+l*(l+3)+k2*(iq+1)) + 4
      End If
      lphi = ip*k*k
      ltheta = iq*k*k
      ldvar = k
      ldx = k
      Allocate (phi(lphi),theta(ltheta),var(ldvar,k),r(lr),x(ldx,n),xmean(k))

!     Read in the AR parameters
      Do l = 1, ip
        Do i = 1, k
          ii = (l-1)*k*k + i
          Read (nin,*)(phi(ii+k*(j-1)),j=1,k)
        End Do
      End Do

!     Read in the MA parameters
      Do l = 1, iq
        Do i = 1, k
          ii = (l-1)*k*k + i
          Read (nin,*)(theta(ii+k*(j-1)),j=1,k)
        End Do
      End Do

!     Read in the means
      Read (nin,*) xmean(1:k)

!     Read in the variance / covariance matrix
      Read (nin,*)(var(i,1:i),i=1,k)

!     For the first realization we need to set up the reference vector
!     as well as generate the series
      mode = 2

!     Generate NREAL realizations
d_lp: Do rn = 1, nreal

        ifail = 0
        Call g05pjf(mode,n,k,xmean,ip,phi,iq,theta,var,ldvar,r,lr,state,x,ldx, &
          ifail)

!       Display the results
        Write (nout,99999) ' Realization Number ', rn
        Do i = 1, k
          Write (nout,*)
          Write (nout,99999) '  Series number ', i
          Write (nout,*) '  -------------'
          Write (nout,*)
          Write (nout,99998) x(i,1:n)
        End Do
        Write (nout,*)

!       For subsequent realizations we use previous reference vector
        mode = 3

      End Do d_lp

99999 Format (1X,A,I0)
99998 Format (8(2X,F8.3))
    End Program g05pjfe


g05pmfe.f90

    Program g05pmfe

!     G05PMF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: g01amf, g01faf, g05kff, g05pmf, g13amf, nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: lseed = 1, nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: ad, alpha, dv, tmp, var, z
      Integer                          :: en, genid, i, ifail, itype, k, le,   &
                                          linit, lparam, lr, lstate, mode, n,  &
                                          nf, nsim, p, smode, subid
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: blim(:,:), bsim(:,:), e(:), fse(:),  &
                                          fv(:), glim(:,:), gsim(:,:),         &
                                          init(:), param(:), r(:), res(:),     &
                                          tsim1(:), tsim2(:), y(:), yhat(:)
      Real (Kind=nag_wp)               :: q(2)
      Integer                          :: seed(lseed)
      Integer, Allocatable             :: state(:)
!     .. Executable Statements ..
      Write (nout,*) 'G05PMF Example Program Results'
      Write (nout,*)

!     Skip heading in data file
      Read (nin,*)

!     Read in the base generator information and seed
      Read (nin,*) genid, subid, seed(1)

!     Initial call to initializer to get size of STATE array
      lstate = 0
      Allocate (state(lstate))
      ifail = 0
      Call g05kff(genid,subid,seed,lseed,state,lstate,ifail)

!     Reallocate STATE
      Deallocate (state)
      Allocate (state(lstate))

!     Initialize the generator to a repeatable sequence
      ifail = 0
      Call g05kff(genid,subid,seed,lseed,state,lstate,ifail)

!     Read in the initial arguments and check array sizes
      Read (nin,*) mode, itype, n, nf, nsim, alpha

      Select Case (itype)
      Case (1)
        lparam = 1
        p = 0
        linit = 1
      Case (2)
        lparam = 2
        p = 0
        linit = 2
      Case (3)
        lparam = 3
        p = 0
        linit = 2
      Case Default
        lparam = 4

!       Read in seasonal order
        Read (nin,*) p

        linit = p + 2
      End Select
      lr = 13 + p
!     Not using the E array for the bootstrap
      le = 0
      Allocate (param(lparam),init(linit),r(lr),e(le),fv(nf),fse(nf),yhat(n),  &
        res(n),blim(2,nf),glim(2,nf),tsim1(nf),tsim2(nf),gsim(nsim,nf),        &
        bsim(nsim,nf),y(n))

!     Read in series to be smoothed
      Read (nin,*) y(1:n)

!     Read in parameters
      Read (nin,*) param(1:lparam)

!     Read in the MODE dependent arguments (skipping headings)
      Select Case (mode)
      Case (0)
!       User supplied initial values
        Read (nin,*) init(1:linit)
      Case (1)
!       Continuing from a previously saved R
        Read (nin,*) r(1:(p+13))
      Case (2)
!       Initial values calculated from first K observations
        Read (nin,*) k
      End Select

!     Fit a smoothing model (parameter R in G05PMF and STATE in G13AMF
!     are in the same format)
      ifail = 0
      Call g13amf(mode,itype,p,param,n,y,k,init,nf,fv,fse,yhat,res,dv,ad,r,    &
        ifail)

!     Simulate forecast values from the model, and don't update R
      smode = 2
      var = dv*dv

!     Simulate NSIM forecasts
      Do i = 1, nsim
!       Not using E array for Gaussian errors
        en = 0

!       Simulations assuming Gaussian errors
        ifail = 0
        Call g05pmf(smode,nf,itype,p,param,init,var,r,state,e,en,tsim1,ifail)

!       For bootstrapping error, we are using RES from call to G13AMF as the
!       errors, and length of RES is N
        en = n

!       Bootstrapping errors
        ifail = 0
        Call g05pmf(smode,nf,itype,p,param,init,0.0E0_nag_wp,r,state,res,en,   &
          tsim2,ifail)

!       Copy and transpose the simulated values
        gsim(i,1:nf) = tsim1(1:nf)
        bsim(i,1:nf) = tsim2(1:nf)
      End Do

!     Calculate CI based on the quantiles for each simulated forecast
      q(1) = alpha/2.0E0_nag_wp
      q(2) = 1.0E0_nag_wp - q(1)
      Do i = 1, nf
        ifail = 0
        Call g01amf(nsim,gsim(1,i),2,q,glim(1,i),ifail)
        ifail = 0
        Call g01amf(nsim,bsim(1,i),2,q,blim(1,i),ifail)
      End Do

!     Display the forecast values and associated prediction intervals
      Write (nout,*) 'Initial values used:'
      Write (nout,99998) init(1:linit)
      Write (nout,*)
      Write (nout,99999) 'Mean Deviation     = ', dv
      Write (nout,99999) 'Absolute Deviation = ', ad
      Write (nout,*)
      Write (nout,*) '         Observed      1-Step'
      Write (nout,*) ' Period   Values      Forecast      Residual'
      Write (nout,*)
      Write (nout,99997)(i,y(i),yhat(i),res(i),i=1,n)
      Write (nout,*)
      Write (nout,*) '                                     ' //                &
        '      Simulated CI         Simulated CI'
      Write (nout,*) 'Obs.  Forecast      Estimated CI   ' //                  &
        '     (Gaussian Errors)    (Bootstrap Errors)'
      z = g01faf('L',q(2),ifail)
      Do i = 1, nf
        tmp = z*fse(i)
        Write (nout,99996) n + i, fv(i), fv(i) - tmp, fv(i) + tmp, glim(1,i),  &
          glim(2,i), blim(1,i), blim(2,i)
      End Do
      Write (nout,99995) 100.0E0_nag_wp*(1.0E0_nag_wp-alpha),                  &
        '% CIs were produced'

99999 Format (A,E12.4)
99998 Format (F12.3)
99997 Format (I4,1X,F12.3,1X,F12.3,1X,F12.3)
99996 Format (I3,7(1X,F10.3))
99995 Format (1X,F5.1,A)
    End Program g05pmfe


g05pvfe.f90

    Program g05pvfe

!     G05PVF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: g02gbf, g02gpf, g05kff, g05pvf, nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: lseed = 1, nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: a, dev, eps, s, tol
      Integer                          :: fn, fold, fp, genid, i, idf, ifail,  &
                                          ip, iprint, irank, k, ldv, ldx,      &
                                          lstate, lwk, m, maxit, max_nv, n,    &
                                          nn, np, nt, nv, obs_val, pred_val,   &
                                          sordx, subid, tn, tp, uset, usey
      Logical                          :: vfobs
      Character (1)                    :: errfn, link, mean, offset, weight
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: b(:), cov(:), eta(:), pred(:),       &
                                          se(:), seeta(:), sepred(:), t(:),    &
                                          v(:,:), wk(:), x(:,:), y(:)
      Real (Kind=nag_wp)               :: off(1), wt(1)
      Integer, Allocatable             :: isx(:), state(:)
      Integer                          :: seed(lseed)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: ceiling, count, int, real
!     .. Executable Statements ..
      Write (nout,*) 'G05PVF Example Program Results'
      Write (nout,*)

!     Skip heading in data file
      Read (nin,*)

!     Set variables required by the regression (G02GBF) ...

!     Read in the type of link function, whether a mean is required
!     and the problem size
      Read (nin,*) link, mean, n, m

!     Set storage order for G05PVF (pick the one required by G02GBF and
!     G02GPF)
      sordx = 1

      ldx = n
      Allocate (x(ldx,m),y(n),t(n),isx(m))

!     This example is not using an offset or weights
      offset = 'N'
      weight = 'U'

!     Read in data
      Read (nin,*)(x(i,1:m),y(i),t(i),i=1,n)

!     Read in variable inclusion flags
      Read (nin,*) isx(1:m)

!     Read in control parameters for the regression
      Read (nin,*) iprint, eps, tol, maxit

!     Calculate IP
      ip = count(isx(1:m)>0)
      If (mean=='M' .Or. mean=='m') Then
        ip = ip + 1
      End If
!     ... End of setting variables required by the regression

!     Set variables required by data sampling routine (G05PVF) ...

!     Read in the base generator information and seed
      Read (nin,*) genid, subid, seed(1:lseed)

!     Will always have a Y and T variable
      usey = 1
      uset = 1

!     Query the required size of the STATE array
      lstate = 0
      Allocate (state(lstate))
      ifail = 0
      Call g05kff(genid,subid,seed,lseed,state,lstate,ifail)

!     Reallocate STATE
      Deallocate (state)
      Allocate (state(lstate))

!     Initialize the generator to a repeatable sequence
      ifail = 0
      Call g05kff(genid,subid,seed,lseed,state,lstate,ifail)

!     Read in the number of folds
      Read (nin,*) k

!     ... End of setting variables required by data sampling routine

!     Set variables required by prediction routine (G02GPF) ...

!     Regression is performed using G02GBF so error structure is binomial
      errfn = 'B'

!     This example does not use the predicted standard errors, so
!     it doesn't matter what VFOBS is set to
      vfobs = .False.
!     ... End of setting variables required by prediction routine

!     This is the maximum size for a validation dataset
      max_nv = ceiling(real(n,kind=nag_wp)/real(k,kind=nag_wp))

!     Allocate arrays
      ldv = n
      lwk = (ip*ip+3*ip+22)/2
      Allocate (b(ip),se(ip),cov(ip*(ip+1)/2),v(ldv,ip+7),wk(lwk))
      Allocate (eta(max_nv),seeta(max_nv),pred(max_nv),sepred(max_nv))

!     Initialize counts
      tp = 0
      tn = 0
      fp = 0
      fn = 0

!     Loop over each fold
      Do fold = 1, k
!       Split the data into training and validation datasets
        ifail = -1
        Call g05pvf(k,fold,n,m,sordx,x,ldx,usey,y,uset,t,nt,state,ifail)
        If (ifail/=0 .And. ifail/=61) Then
          Go To 100
        End If

!       Calculate the size of the validation dataset
        nv = n - nt

!       Call routine to fit generalized linear model, with Binomial errors
!       to training data
        ifail = -1
        Call g02gbf(link,mean,offset,weight,nt,x,ldx,m,isx,ip,y,t,wt,dev,idf,  &
          b,irank,se,cov,v,ldv,tol,maxit,iprint,eps,wk,ifail)
        If (ifail/=0) Then
          If (ifail<6) Then
            Go To 100
          End If
        End If

!       Predict the response for the observations in the validation dataset
        ifail = 0
        Call g02gpf(errfn,link,mean,offset,weight,nv,x(nt+1,1),ldx,m,isx,ip,   &
          t(nt+1),off,wt,s,a,b,cov,vfobs,eta,seeta,pred,sepred,ifail)

!       Count the true/false positives/negatives
        Do i = 1, nv
          obs_val = int(y(nt+i))

          If (pred(i)>=0.5_nag_wp) Then
            pred_val = 1
          Else
            pred_val = 0
          End If

          Select Case (obs_val)
          Case (0)
!           Negative
            Select Case (pred_val)
            Case (0)
!             True negative
              tn = tn + 1
            Case (1)
!             False positive
              fp = fp + 1
            End Select
          Case (1)
!           Positive
            Select Case (pred_val)
            Case (0)
!             False negative
              fn = fn + 1
            Case (1)
!             True positive
              tp = tp + 1
            End Select
          End Select
        End Do
      End Do

!     Display results
      np = tp + fn
      nn = fp + tn

      Write (*,99998) '                      Observed'
      Write (*,99998) '            --------------------------'
      Write (*,99998) 'Predicted | Negative  Positive   Total'
      Write (*,99998) '--------------------------------------'
      Write (*,99997) 'Negative  |', tn, fn, tn + fn
      Write (*,99997) 'Positive  |', fp, tp, fp + tp
      Write (*,99997) 'Total     |', nn, np, nn + np
      Write (*,*)

      If (np/=0) Then
        Write (nout,99999) 'True Positive Rate (Sensitivity):',                &
          real(tp,kind=nag_wp)/real(np,kind=nag_wp)
      Else
        Write (nout,99998)                                                     &
          'True Positive Rate (Sensitivity): No positives in data'
      End If
      If (nn/=0) Then
        Write (nout,99999) 'True Negative Rate (Specificity):',                &
          real(tn,kind=nag_wp)/real(nn,kind=nag_wp)
      Else
        Write (nout,99998)                                                     &
          'True Negative Rate (Specificity): No negatives in data'
      End If

100   Continue
99999 Format (1X,A,F5.2)
99998 Format (1X,A)
99997 Format (1X,A,1X,I5,5X,I5,5X,I5)
    End Program g05pvfe


g05pwfe.f90

    Program g05pwfe

!     G05PWF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: g02gbf, g02gpf, g05kff, g05pwf, nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: lseed = 1, nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: a, dev, eps, s, tol
      Integer                          :: fn, fp, genid, i, idf, ifail, ip,    &
                                          iprint, irank, ldv, ldx, lstate,     &
                                          lwk, m, maxit, n, nn, np, nsamp, nt, &
                                          nv, obs_val, pred_val, samp, sordx,  &
                                          subid, tn, tp, uset, usey
      Logical                          :: vfobs
      Character (1)                    :: errfn, link, mean, offset, weight
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: b(:), cov(:), eta(:), pred(:),       &
                                          se(:), seeta(:), sepred(:), t(:),    &
                                          v(:,:), wk(:), x(:,:), y(:)
      Real (Kind=nag_wp)               :: off(1), wt(1)
      Integer, Allocatable             :: isx(:), state(:)
      Integer                          :: seed(lseed)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: count, int, real
!     .. Executable Statements ..
      Write (nout,*) 'G05PWF Example Program Results'
      Write (nout,*)

!     Skip heading in data file
      Read (nin,*)

!     Set variables required by the regression (G02GBF) ...

!     Read in the type of link function, whether a mean is required
!     and the problem size
      Read (nin,*) link, mean, n, m

!     Set storage order for G05PWF (pick the one required by G02GBF and
!     G02GPF)
      sordx = 1

      ldx = n
      Allocate (x(ldx,m),y(n),t(n),isx(m))

!     This example is not using an offset or weights
      offset = 'N'
      weight = 'U'

!     Read in data
      Read (nin,*)(x(i,1:m),y(i),t(i),i=1,n)

!     Read in variable inclusion flags
      Read (nin,*) isx(1:m)

!     Read in control parameters for the regression
      Read (nin,*) iprint, eps, tol, maxit

!     Calculate IP
      ip = count(isx(1:m)>0)
      If (mean=='M' .Or. mean=='m') Then
        ip = ip + 1
      End If
!     ... End of setting variables required by the regression

!     Set variables required by data sampling routine (G05PWF) ...

!     Read in the base generator information and seed
      Read (nin,*) genid, subid, seed(1:lseed)

!     Will always have a Y and T variable
      usey = 1
      uset = 1

!     Query the required size of the STATE array
      lstate = 0
      Allocate (state(lstate))
      ifail = 0
      Call g05kff(genid,subid,seed,lseed,state,lstate,ifail)

!     Reallocate STATE
      Deallocate (state)
      Allocate (state(lstate))

!     Initialize the generator to a repeatable sequence
      ifail = 0
      Call g05kff(genid,subid,seed,lseed,state,lstate,ifail)

!     Read in the size of the training set required
      Read (nin,*) nt

!     Read in the number of sub-samples we will use */
      Read (nin,*) nsamp
!     ... End of setting variables required by data sampling routine

!     Set variables required by prediction routine (G02GPF) ...

!     Regression is performed using G02GBF so error structure is binomial
      errfn = 'B'

!     This example does not use the predicted standard errors, so
!     it doesn't matter what VFOBS is set to
      vfobs = .False.
!     ... End of setting variables required by prediction routine

!     Calculate the size of the validation dataset
      nv = n - nt

!     Allocate arrays
      ldv = n
      lwk = (ip*ip+3*ip+22)/2
      Allocate (b(ip),se(ip),cov(ip*(ip+1)/2),v(ldv,ip+7),wk(lwk))
      Allocate (eta(nv),seeta(nv),pred(nv),sepred(nv))

!     Initialize counts
      tp = 0
      tn = 0
      fp = 0
      fn = 0

!     Loop over each sample
      Do samp = 1, nsamp
!       Split the data into training and validation datasets
        ifail = 0
        Call g05pwf(nt,n,m,sordx,x,ldx,usey,y,uset,t,state,ifail)

!       Call routine to fit generalized linear model, with Binomial errors
!       to training data
        ifail = -1
        Call g02gbf(link,mean,offset,weight,nt,x,ldx,m,isx,ip,y,t,wt,dev,idf,  &
          b,irank,se,cov,v,ldv,tol,maxit,iprint,eps,wk,ifail)
        If (ifail/=0) Then
          If (ifail<6) Then
            Go To 100
          End If
        End If

!       Predict the response for the observations in the validation dataset
        ifail = 0
        Call g02gpf(errfn,link,mean,offset,weight,nv,x(nt+1,1),ldx,m,isx,ip,   &
          t(nt+1),off,wt,s,a,b,cov,vfobs,eta,seeta,pred,sepred,ifail)

!       Count the true/false positives/negatives
        Do i = 1, nv
          obs_val = int(y(nt+i))

          If (pred(i)>=0.5_nag_wp) Then
            pred_val = 1
          Else
            pred_val = 0
          End If

          Select Case (obs_val)
          Case (0)
!           Negative
            Select Case (pred_val)
            Case (0)
!             True negative
              tn = tn + 1
            Case (1)
!             False positive
              fp = fp + 1
            End Select
          Case (1)
!           Positive
            Select Case (pred_val)
            Case (0)
!             False negative
              fn = fn + 1
            Case (1)
!             True positive
              tp = tp + 1
            End Select
          End Select
        End Do
      End Do

!     Display results
      np = tp + fn
      nn = fp + tn

      Write (*,99998) '                      Observed'
      Write (*,99998) '            --------------------------'
      Write (*,99998) 'Predicted | Negative  Positive   Total'
      Write (*,99998) '--------------------------------------'
      Write (*,99997) 'Negative  |', tn, fn, tn + fn
      Write (*,99997) 'Positive  |', fp, tp, fp + tp
      Write (*,99997) 'Total     |', nn, np, nn + np
      Write (*,*)

      If (np/=0) Then
        Write (nout,99999) 'True Positive Rate (Sensitivity):',                &
          real(tp,kind=nag_wp)/real(np,kind=nag_wp)
      Else
        Write (nout,99998)                                                     &
          'True Positive Rate (Sensitivity): No positives in data'
      End If
      If (nn/=0) Then
        Write (nout,99999) 'True Negative Rate (Specificity):',                &
          real(tn,kind=nag_wp)/real(nn,kind=nag_wp)
      Else
        Write (nout,99998)                                                     &
          'True Negative Rate (Specificity): No negatives in data'
      End If

100   Continue
99999 Format (1X,A,F5.2)
99998 Format (1X,A)
99997 Format (1X,A,1X,I5,5X,I5,5X,I5)
    End Program g05pwfe


g05pxfe.f90

    Program g05pxfe

!     G05PXF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: g05kff, g05pxf, nag_wp, x04caf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: lseed = 1, nin = 5, nout = 6
!     .. Local Scalars ..
      Integer                          :: genid, i, ifail, lda, lstate, m, n,  &
                                          subid
      Character (1)                    :: init, side
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: a(:,:)
      Integer                          :: seed(lseed)
      Integer, Allocatable             :: state(:)
!     .. Executable Statements ..
      Write (nout,*) 'G05PXF Example Program Results'
      Write (nout,*)
      Flush (nout)

!     Skip heading in data file
      Read (nin,*)

!     Read in the base generator information and seed
      Read (nin,*) genid, subid, seed(1)

!     Initial call to initializer to get size of STATE array
      lstate = 0
      Allocate (state(lstate))
      ifail = 0
      Call g05kff(genid,subid,seed,lseed,state,lstate,ifail)

!     Reallocate STATE
      Deallocate (state)
      Allocate (state(lstate))

!     Initialize the generator to a repeatable sequence
      ifail = 0
      Call g05kff(genid,subid,seed,lseed,state,lstate,ifail)

!     Read in the problem size
      Read (nin,*) n, m

!     Read in control parameters
      Read (nin,*) side, init

      lda = m
      Allocate (a(lda,n))

!     Read in A if required
      If (init=='N' .Or. init=='n') Then
        Read (nin,*)(a(i,1:n),i=1,m)
      End If

!     Generate the random orthogonal matrix
      ifail = 0
      Call g05pxf(side,init,m,n,state,a,lda,ifail)

!     Display the results
      ifail = 0
      Call x04caf('General',' ',m,n,a,lda,'Random Matrix',ifail)

    End Program g05pxfe


g05pyfe.f90

    Program g05pyfe

!     G05PYF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: g05kff, g05pyf, nag_wp, x04caf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: lseed = 1, nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: eps
      Integer                          :: genid, ifail, ldc, lstate, n, subid
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: c(:,:), d(:)
      Integer                          :: seed(lseed)
      Integer, Allocatable             :: state(:)
!     .. Executable Statements ..
      Write (nout,*) 'G05PYF Example Program Results'
      Write (nout,*)
      Flush (nout)

!     Skip heading in data file
      Read (nin,*)

!     Read in the base generator information and seed
      Read (nin,*) genid, subid, seed(1)

!     Initial call to initializer to get size of STATE array
      lstate = 0
      Allocate (state(lstate))
      ifail = 0
      Call g05kff(genid,subid,seed,lseed,state,lstate,ifail)

!     Reallocate STATE
      Deallocate (state)
      Allocate (state(lstate))

!     Initialize the generator to a repeatable sequence
      ifail = 0
      Call g05kff(genid,subid,seed,lseed,state,lstate,ifail)

!     Read in the problem size and tolerance
      Read (nin,*) n, eps

      ldc = n
      Allocate (c(ldc,n),d(n))

!     Read in the eigenvalues
      Read (nin,*) d(1:n)

!     Generate the correlation matrix
      ifail = 0
      Call g05pyf(n,d,eps,state,c,ldc,ifail)

!     Display the results
      ifail = 0
      Call x04caf('General',' ',n,n,c,ldc,'Correlation Matrix',ifail)

    End Program g05pyfe


g05pzfe.f90

    Program g05pzfe

!     G05PZF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: g05kff, g05pzf, nag_wp, x04eaf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: lseed = 1, nin = 5, nout = 6
!     .. Local Scalars ..
      Integer                          :: genid, ifail, ldx, lr, lstate, mode, &
                                          ncol, nrow, subid
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: r(:)
      Integer                          :: seed(lseed)
      Integer, Allocatable             :: state(:), totc(:), totr(:), x(:,:)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: sum
!     .. Executable Statements ..
      Write (nout,*) 'G05PZF Example Program Results'
      Write (nout,*)
      Flush (nout)

!     Skip heading in data file
      Read (nin,*)

!     Read in the base generator information and seed
      Read (nin,*) genid, subid, seed(1)

!     Initial call to initializer to get size of STATE array
      lstate = 0
      Allocate (state(lstate))
      ifail = 0
      Call g05kff(genid,subid,seed,lseed,state,lstate,ifail)

!     Reallocate STATE
      Deallocate (state)
      Allocate (state(lstate))

!     Initialize the generator to a repeatable sequence
      ifail = 0
      Call g05kff(genid,subid,seed,lseed,state,lstate,ifail)

!     Read in the problem size
      Read (nin,*) nrow, ncol

      ldx = nrow
      Allocate (totr(nrow),totc(ncol),x(ldx,ncol))

!     Read in row and column totals
      Read (nin,*) totr(1:nrow)
      Read (nin,*) totc(1:ncol)

      lr = sum(totr(1:nrow)) + 5
      Allocate (r(lr))

!     Using a single call to G05PZF, so set up reference vector
!     and generate values in one go
      mode = 2

!     Generate the random table
      ifail = 0
      Call g05pzf(mode,nrow,ncol,totr,totc,r,lr,state,x,ldx,ifail)

!     Display the results
      ifail = 0
      Call x04eaf('General',' ',nrow,ncol,x,ldx,'Random Table',ifail)
      Write (nout,*)
      Write (nout,Fmt=99999) 'Supplied row totals:', totr(1:nrow)
      Write (nout,Fmt=99999) 'Supplied column totals:', totc(1:ncol)
99999 Format (1X,A,/,(2X,4I10))
    End Program g05pzfe


g05rcfe.f90

    Program g05rcfe

!     G05RCF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: g05kff, g05rcf, nag_wp, x04caf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: lseed = 1, nin = 5, nout = 6
!     .. Local Scalars ..
      Integer                          :: df, genid, i, ifail, ldc, ldx, lr,   &
                                          lstate, m, mode, n, subid
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: c(:,:), r(:), x(:,:)
      Integer                          :: seed(lseed)
      Integer, Allocatable             :: state(:)
!     .. Executable Statements ..
      Write (nout,*) 'G05RCF Example Program Results'
      Write (nout,*)
      Flush (nout)

!     Skip heading in data file
      Read (nin,*)

!     Read in the base generator information and seed
      Read (nin,*) genid, subid, seed(1)

!     Initial call to initializer to get size of STATE array
      lstate = 0
      Allocate (state(lstate))
      ifail = 0
      Call g05kff(genid,subid,seed,lseed,state,lstate,ifail)

!     Reallocate STATE
      Deallocate (state)
      Allocate (state(lstate))

!     Initialize the generator to a repeatable sequence
      ifail = 0
      Call g05kff(genid,subid,seed,lseed,state,lstate,ifail)

!     Read in sample size and number of dimensions
      Read (nin,*) n, m

      ldc = m
      ldx = n
      lr = m*(m+1) + 2
      Allocate (c(ldc,m),x(ldx,m),r(lr))

!     Read in degrees of freedom
      Read (nin,*) df

!     Read in upper triangle portion of the covariance matrix
      Do i = 1, m
        Read (nin,*) c(i,i:m)
      End Do

!     Using a single call to G05RCF, so set up reference vector
!     and generate values in one go
      mode = 2

!     Generate variates
      ifail = 0
      Call g05rcf(mode,n,df,m,c,ldc,r,lr,state,x,ldx,ifail)

!     Display the variates
      ifail = 0
      Call x04caf('General',' ',n,m,x,ldx,'Variates',ifail)

    End Program g05rcfe


g05rdfe.f90

    Program g05rdfe

!     G05RDF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: g05kff, g05rdf, nag_wp, x04caf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: lseed = 1, nin = 5, nout = 6
!     .. Local Scalars ..
      Integer                          :: genid, i, ifail, ldc, ldx, lr,       &
                                          lstate, m, mode, n, subid
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: c(:,:), r(:), x(:,:)
      Integer                          :: seed(lseed)
      Integer, Allocatable             :: state(:)
!     .. Executable Statements ..
      Write (nout,*) 'G05RDF Example Program Results'
      Write (nout,*)
      Flush (nout)

!     Skip heading in data file
      Read (nin,*)

!     Read in the base generator information and seed
      Read (nin,*) genid, subid, seed(1)

!     Initial call to initializer to get size of STATE array
      lstate = 0
      Allocate (state(lstate))
      ifail = 0
      Call g05kff(genid,subid,seed,lseed,state,lstate,ifail)

!     Reallocate STATE
      Deallocate (state)
      Allocate (state(lstate))

!     Initialize the generator to a repeatable sequence
      ifail = 0
      Call g05kff(genid,subid,seed,lseed,state,lstate,ifail)

!     Read in sample size and number of dimensions
      Read (nin,*) n, m

      ldc = m
      ldx = n
      lr = m*(m+1) + 1
      Allocate (c(ldc,m),x(ldx,m),r(lr))

!     Read in upper triangle portion of the covariance matrix
      Do i = 1, m
        Read (nin,*) c(i,i:m)
      End Do

!     Using a single call to G05RDF, so set up reference vector
!     and generate values in one go
      mode = 2

!     Generate variates
      ifail = 0
      Call g05rdf(mode,n,m,c,ldc,r,lr,state,x,ldx,ifail)

!     Display variates
      ifail = 0
      Call x04caf('General',' ',n,m,x,ldx,'Variates',ifail)

    End Program g05rdfe


g05refe.f90

    Program g05refe

!     G05REF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: g05kff, g05ref, nag_wp, x04caf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: lseed = 1, nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: theta
      Integer                          :: genid, ifail, ldx, lstate, n, sdx,   &
                                          sorder, subid
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: x(:,:)
      Integer                          :: seed(lseed)
      Integer, Allocatable             :: state(:)
!     .. Executable Statements ..
      Write (nout,*) 'G05REF Example Program Results'
      Write (nout,*)
      Flush (nout)

!     Skip heading in data file
      Read (nin,*)

!     Read in the base generator information and seed
      Read (nin,*) genid, subid, seed(1)

!     Initial call to initializer to get size of STATE array
      lstate = 0
      Allocate (state(lstate))
      ifail = 0
      Call g05kff(genid,subid,seed,lseed,state,lstate,ifail)

!     Reallocate STATE
      Deallocate (state)
      Allocate (state(lstate))

!     Initialize the generator to a repeatable sequence
      ifail = 0
      Call g05kff(genid,subid,seed,lseed,state,lstate,ifail)

!     Read in sample size and order
      Read (nin,*) n, sorder

      If (sorder==1) Then
!       X(N,2)
        ldx = n
        sdx = 2
      Else
!       X(2,N)
        ldx = 2
        sdx = n
      End If
      Allocate (x(ldx,sdx))

!     Read in parameter
      Read (nin,*) theta

!     Generate variates
      ifail = 0
      Call g05ref(n,theta,sorder,state,x,ldx,sdx,ifail)

!     Display the variates
      If (sorder==1) Then
!       X(N,2)
        ifail = 0
        Call x04caf('General',' ',n,2,x,ldx,                                   &
          'Uniform variates with copula joint distribution',ifail)
      Else
!       X(2,N)
        ifail = 0
        Call x04caf('General',' ',2,n,x,ldx,                                   &
          'Uniform variates with copula joint distribution',ifail)
      End If

    End Program g05refe


g05rffe.f90

    Program g05rffe

!     G05RFF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: g05kff, g05rff, nag_wp, x04caf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: lseed = 1, nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: theta
      Integer                          :: genid, ifail, ldx, lstate, n, sdx,   &
                                          sorder, subid
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: x(:,:)
      Integer                          :: seed(lseed)
      Integer, Allocatable             :: state(:)
!     .. Executable Statements ..
      Write (nout,*) 'G05RFF Example Program Results'
      Write (nout,*)
      Flush (nout)

!     Skip heading in data file
      Read (nin,*)

!     Read in the base generator information and seed
      Read (nin,*) genid, subid, seed(1)

!     Initial call to initializer to get size of STATE array
      lstate = 0
      Allocate (state(lstate))
      ifail = 0
      Call g05kff(genid,subid,seed,lseed,state,lstate,ifail)

!     Reallocate STATE
      Deallocate (state)
      Allocate (state(lstate))

!     Initialize the generator to a repeatable sequence
      ifail = 0
      Call g05kff(genid,subid,seed,lseed,state,lstate,ifail)

!     Read in sample size and order
      Read (nin,*) n, sorder

      If (sorder==1) Then
!       X(N,2)
        ldx = n
        sdx = 2
      Else
!       X(2,N)
        ldx = 2
        sdx = n
      End If
      Allocate (x(ldx,sdx))

!     Read in parameter
      Read (nin,*) theta

!     Generate variates
      ifail = 0
      Call g05rff(n,theta,sorder,state,x,ldx,sdx,ifail)

!     Display the variates
      If (sorder==1) Then
!       X(N,2)
        ifail = 0
        Call x04caf('General',' ',n,2,x,ldx,                                   &
          'Uniform variates with copula joint distribution',ifail)
      Else
!       X(2,N)
        ifail = 0
        Call x04caf('General',' ',2,n,x,ldx,                                   &
          'Uniform variates with copula joint distribution',ifail)
      End If

    End Program g05rffe


g05rgfe.f90

    Program g05rgfe

!     G05RGF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: g05kff, g05rgf, nag_wp, x04caf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: lseed = 1, nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: theta
      Integer                          :: genid, ifail, ldx, lstate, n, sdx,   &
                                          sorder, subid
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: x(:,:)
      Integer                          :: seed(lseed)
      Integer, Allocatable             :: state(:)
!     .. Executable Statements ..
      Write (nout,*) 'G05RGF Example Program Results'
      Write (nout,*)
      Flush (nout)

!     Skip heading in data file
      Read (nin,*)

!     Read in the base generator information and seed
      Read (nin,*) genid, subid, seed(1)

!     Initial call to initializer to get size of STATE array
      lstate = 0
      Allocate (state(lstate))
      ifail = 0
      Call g05kff(genid,subid,seed,lseed,state,lstate,ifail)

!     Reallocate STATE
      Deallocate (state)
      Allocate (state(lstate))

!     Initialize the generator to a repeatable sequence
      ifail = 0
      Call g05kff(genid,subid,seed,lseed,state,lstate,ifail)

!     Read in sample size and order
      Read (nin,*) n, sorder

      If (sorder==1) Then
!       X(N,2)
        ldx = n
        sdx = 2
      Else
!       X(2,N)
        ldx = 2
        sdx = n
      End If
      Allocate (x(ldx,sdx))

!     Read in parameter
      Read (nin,*) theta

!     Generate variates
      ifail = 0
      Call g05rgf(n,theta,sorder,state,x,ldx,sdx,ifail)

!     Display the variates
      If (sorder==1) Then
!       X(N,2)
        ifail = 0
        Call x04caf('General',' ',n,2,x,ldx,                                   &
          'Uniform variates with copula joint distribution',ifail)
      Else
!       X(2,N)
        ifail = 0
        Call x04caf('General',' ',2,n,x,ldx,                                   &
          'Uniform variates with copula joint distribution',ifail)
      End If

    End Program g05rgfe


g05rhfe.f90

    Program g05rhfe

!     G05RHF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: g05kff, g05rhf, nag_wp, x04caf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: lseed = 1, nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: theta
      Integer                          :: genid, ifail, ldx, lstate, m, n,     &
                                          sdx, sorder, subid
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: x(:,:)
      Integer                          :: seed(lseed)
      Integer, Allocatable             :: state(:)
!     .. Executable Statements ..
      Write (nout,*) 'G05RHF Example Program Results'
      Write (nout,*)
      Flush (nout)

!     Skip heading in data file
      Read (nin,*)

!     Read in the base generator information and seed
      Read (nin,*) genid, subid, seed(1)

!     Initial call to initializer to get size of STATE array
      lstate = 0
      Allocate (state(lstate))
      ifail = 0
      Call g05kff(genid,subid,seed,lseed,state,lstate,ifail)

!     Reallocate STATE
      Deallocate (state)
      Allocate (state(lstate))

!     Initialize the generator to a repeatable sequence
      ifail = 0
      Call g05kff(genid,subid,seed,lseed,state,lstate,ifail)

!     Read in sample size, number of dimensions and order
      Read (nin,*) n, m, sorder

      If (sorder==1) Then
!       X(N,M)
        ldx = n
        sdx = m
      Else
!       X(M,N)
        ldx = m
        sdx = n
      End If
      Allocate (x(ldx,sdx))

!     Read in parameter
      Read (nin,*) theta

!     Generate variates
      ifail = 0
      Call g05rhf(n,m,theta,sorder,state,x,ldx,sdx,ifail)

!     Display the variates
      If (sorder==1) Then
!       X(N,M)
        ifail = 0
        Call x04caf('General',' ',n,m,x,ldx,                                   &
          'Uniform variates with copula joint distribution',ifail)
      Else
!       X(M,N)
        ifail = 0
        Call x04caf('General',' ',m,n,x,ldx,                                   &
          'Uniform variates with copula joint distribution',ifail)
      End If

    End Program g05rhfe


g05rjfe.f90

    Program g05rjfe

!     G05RJF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: g05kff, g05rjf, nag_wp, x04caf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: lseed = 1, nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: theta
      Integer                          :: genid, ifail, ldx, lstate, m, n,     &
                                          sdx, sorder, subid
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: x(:,:)
      Integer                          :: seed(lseed)
      Integer, Allocatable             :: state(:)
!     .. Executable Statements ..
      Write (nout,*) 'G05RJF Example Program Results'
      Write (nout,*)
      Flush (nout)

!     Skip heading in data file
      Read (nin,*)

!     Read in the base generator information and seed
      Read (nin,*) genid, subid, seed(1)

!     Initial call to initializer to get size of STATE array
      lstate = 0
      Allocate (state(lstate))
      ifail = 0
      Call g05kff(genid,subid,seed,lseed,state,lstate,ifail)

!     Reallocate STATE
      Deallocate (state)
      Allocate (state(lstate))

!     Initialize the generator to a repeatable sequence
      ifail = 0
      Call g05kff(genid,subid,seed,lseed,state,lstate,ifail)

!     Read in sample size, number of dimensions and order
      Read (nin,*) n, m, sorder

      If (sorder==1) Then
!       X(N,M)
        ldx = n
        sdx = m
      Else
!       X(M,N)
        ldx = m
        sdx = n
      End If
      Allocate (x(ldx,sdx))

!     Read in parameter
      Read (nin,*) theta

!     Generate variates
      ifail = 0
      Call g05rjf(n,m,theta,sorder,state,x,ldx,sdx,ifail)

!     Display the variates
      If (sorder==1) Then
!       X(N,M)
        ifail = 0
        Call x04caf('General',' ',n,m,x,ldx,                                   &
          'Uniform variates with copula joint distribution',ifail)
      Else
!       X(M,N)
        ifail = 0
        Call x04caf('General',' ',m,n,x,ldx,                                   &
          'Uniform variates with copula joint distribution',ifail)
      End If

    End Program g05rjfe


g05rkfe.f90

    Program g05rkfe

!     G05RKF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: g05kff, g05rkf, nag_wp, x04caf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: lseed = 1, nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: theta
      Integer                          :: genid, ifail, ldx, lstate, m, n,     &
                                          sdx, sorder, subid
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: x(:,:)
      Integer                          :: seed(lseed)
      Integer, Allocatable             :: state(:)
!     .. Executable Statements ..
      Write (nout,*) 'G05RKF Example Program Results'
      Write (nout,*)
      Flush (nout)

!     Skip heading in data file
      Read (nin,*)

!     Read in the base generator information and seed
      Read (nin,*) genid, subid, seed(1)

!     Initial call to initializer to get size of STATE array
      lstate = 0
      Allocate (state(lstate))
      ifail = 0
      Call g05kff(genid,subid,seed,lseed,state,lstate,ifail)

!     Reallocate STATE
      Deallocate (state)
      Allocate (state(lstate))

!     Initialize the generator to a repeatable sequence
      ifail = 0
      Call g05kff(genid,subid,seed,lseed,state,lstate,ifail)

!     Read in sample size, number of dimensions and order
      Read (nin,*) n, m, sorder

      If (sorder==1) Then
!       X(N,M)
        ldx = n
        sdx = m
      Else
!       X(M,N)
        ldx = m
        sdx = n
      End If
      Allocate (x(ldx,sdx))

!     Read in parameter
      Read (nin,*) theta

!     Generate variates
      ifail = 0
      Call g05rkf(n,m,theta,sorder,state,x,ldx,sdx,ifail)

!     Display the variates
      If (sorder==1) Then
!       X(N,M)
        ifail = 0
        Call x04caf('General',' ',n,m,x,ldx,                                   &
          'Uniform variates with copula joint distribution',ifail)
      Else
!       X(M,N)
        ifail = 0
        Call x04caf('General',' ',m,n,x,ldx,                                   &
          'Uniform variates with copula joint distribution',ifail)
      End If

    End Program g05rkfe


g05ryfe.f90

    Program g05ryfe

!     G05RYF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: g05kff, g05ryf, nag_wp, x04caf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: lseed = 1, nin = 5, nout = 6
!     .. Local Scalars ..
      Integer                          :: df, genid, i, ifail, ldc, ldx, lr,   &
                                          lstate, m, mode, n, subid
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: c(:,:), r(:), x(:,:), xmu(:)
      Integer                          :: seed(lseed)
      Integer, Allocatable             :: state(:)
!     .. Executable Statements ..
      Write (nout,*) 'G05RYF Example Program Results'
      Write (nout,*)
      Flush (nout)

!     Skip heading in data file
      Read (nin,*)

!     Read in the base generator information and seed
      Read (nin,*) genid, subid, seed(1)

!     Initial call to initializer to get size of STATE array
      lstate = 0
      Allocate (state(lstate))
      ifail = 0
      Call g05kff(genid,subid,seed,lseed,state,lstate,ifail)

!     Reallocate STATE
      Deallocate (state)
      Allocate (state(lstate))

!     Initialize the generator to a repeatable sequence
      ifail = 0
      Call g05kff(genid,subid,seed,lseed,state,lstate,ifail)

!     Read in sample size and number of dimensions
      Read (nin,*) n, m

      ldc = m
      ldx = n
      lr = m*(m+1) + 2
      Allocate (x(ldx,m),c(ldc,m),r(lr),xmu(m))

!     Read in degrees of freedom
      Read (nin,*) df

!     Read in vector of means
      Read (nin,*) xmu(1:m)

!     Read in upper triangle portion of the covariance matrix
      Do i = 1, m
        Read (nin,*) c(i,i:m)
      End Do

!     Using a single call to G05RYF, so set up reference vector
!     and generate values in one go
      mode = 2

!     Generate variates
      ifail = 0
      Call g05ryf(mode,n,df,m,xmu,c,ldc,r,lr,state,x,ldx,ifail)

!     Display the variates
      ifail = 0
      Call x04caf('General',' ',n,m,x,ldx,'Variates',ifail)

    End Program g05ryfe


g05rzfe.f90

    Program g05rzfe

!     G05RZF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: g05kff, g05rzf, nag_wp, x04caf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: lseed = 1, nin = 5, nout = 6
!     .. Local Scalars ..
      Integer                          :: genid, i, ifail, ldc, ldx, lr,       &
                                          lstate, m, mode, n, subid
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: c(:,:), r(:), x(:,:), xmu(:)
      Integer                          :: seed(lseed)
      Integer, Allocatable             :: state(:)
!     .. Executable Statements ..
      Write (nout,*) 'G05RZF Example Program Results'
      Write (nout,*)
      Flush (nout)

!     Skip heading in data file
      Read (nin,*)

!     Read in the base generator information and seed
      Read (nin,*) genid, subid, seed(1)

!     Initial call to initializer to get size of STATE array
      lstate = 0
      Allocate (state(lstate))
      ifail = 0
      Call g05kff(genid,subid,seed,lseed,state,lstate,ifail)

!     Reallocate STATE
      Deallocate (state)
      Allocate (state(lstate))

!     Initialize the generator to a repeatable sequence
      ifail = 0
      Call g05kff(genid,subid,seed,lseed,state,lstate,ifail)

!     Read in sample size and number of dimensions
      Read (nin,*) n, m

      ldc = m
      ldx = n
      lr = m*(m+1) + 1
      Allocate (x(ldx,m),c(ldc,m),r(lr),xmu(m))

!     Read in vector of means
      Read (nin,*) xmu(1:m)

!     Read in upper triangle portion of the covariance matrix
      Do i = 1, m
        Read (nin,*) c(i,i:m)
      End Do

!     Using a single call to G05RZF, so set up reference vector
!     and generate values in one go
      mode = 2

!     Generate variates
      ifail = 0
      Call g05rzf(mode,n,m,xmu,c,ldc,r,lr,state,x,ldx,ifail)

!     Display the variates
      ifail = 0
      Call x04caf('General',' ',n,m,x,ldx,'Variates',ifail)

    End Program g05rzfe


g05safe.f90

    Program g05safe

!     G05SAF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: g05kff, g05saf, nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: lseed = 1, nin = 5, nout = 6
!     .. Local Scalars ..
      Integer                          :: genid, ifail, lstate, n, subid
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: x(:)
      Integer                          :: seed(lseed)
      Integer, Allocatable             :: state(:)
!     .. Executable Statements ..
      Write (nout,*) 'G05SAF Example Program Results'
      Write (nout,*)

!     Skip heading in data file
      Read (nin,*)

!     Read in the base generator information and seed
      Read (nin,*) genid, subid, seed(1)

!     Initial call to initializer to get size of STATE array
      lstate = 0
      Allocate (state(lstate))
      ifail = 0
      Call g05kff(genid,subid,seed,lseed,state,lstate,ifail)

!     Reallocate STATE
      Deallocate (state)
      Allocate (state(lstate))

!     Initialize the generator to a repeatable sequence
      ifail = 0
      Call g05kff(genid,subid,seed,lseed,state,lstate,ifail)

!     Read in sample size
      Read (nin,*) n

      Allocate (x(n))

!     Generate the variates
      ifail = 0
      Call g05saf(n,state,x,ifail)

!     Display the variates
      Write (nout,99999) x(1:n)

99999 Format (1X,F10.4)
    End Program g05safe


g05sbfe.f90

    Program g05sbfe

!     G05SBF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: g05kff, g05sbf, nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: lseed = 1, nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: a, b
      Integer                          :: genid, ifail, lstate, n, subid
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: x(:)
      Integer                          :: seed(lseed)
      Integer, Allocatable             :: state(:)
!     .. Executable Statements ..
      Write (nout,*) 'G05SBF Example Program Results'
      Write (nout,*)

!     Skip heading in data file
      Read (nin,*)

!     Read in the base generator information and seed
      Read (nin,*) genid, subid, seed(1)

!     Initial call to initializer to get size of STATE array
      lstate = 0
      Allocate (state(lstate))
      ifail = 0
      Call g05kff(genid,subid,seed,lseed,state,lstate,ifail)

!     Reallocate STATE
      Deallocate (state)
      Allocate (state(lstate))

!     Initialize the generator to a repeatable sequence
      ifail = 0
      Call g05kff(genid,subid,seed,lseed,state,lstate,ifail)

!     Read in sample size
      Read (nin,*) n

      Allocate (x(n))

!     Read in the distribution parameters
      Read (nin,*) a, b

!     Generate the variates
      ifail = 0
      Call g05sbf(n,a,b,state,x,ifail)

!     Display the variates
      Write (nout,99999) x(1:n)

99999 Format (1X,F10.4)
    End Program g05sbfe


g05scfe.f90

    Program g05scfe

!     G05SCF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: g05kff, g05scf, nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: lseed = 1, nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: semiqr, xmed
      Integer                          :: genid, ifail, lstate, n, subid
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: x(:)
      Integer                          :: seed(lseed)
      Integer, Allocatable             :: state(:)
!     .. Executable Statements ..
      Write (nout,*) 'G05SCF Example Program Results'
      Write (nout,*)

!     Skip heading in data file
      Read (nin,*)

!     Read in the base generator information and seed
      Read (nin,*) genid, subid, seed(1)

!     Initial call to initializer to get size of STATE array
      lstate = 0
      Allocate (state(lstate))
      ifail = 0
      Call g05kff(genid,subid,seed,lseed,state,lstate,ifail)

!     Reallocate STATE
      Deallocate (state)
      Allocate (state(lstate))

!     Initialize the generator to a repeatable sequence
      ifail = 0
      Call g05kff(genid,subid,seed,lseed,state,lstate,ifail)

!     Read in sample size
      Read (nin,*) n

      Allocate (x(n))

!     Read in the distribution parameters
      Read (nin,*) xmed, semiqr

!     Generate the variates
      ifail = 0
      Call g05scf(n,xmed,semiqr,state,x,ifail)

!     Display the variates
      Write (nout,99999) x(1:n)

99999 Format (1X,F10.4)
    End Program g05scfe


g05sdfe.f90

    Program g05sdfe

!     G05SDF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: g05kff, g05sdf, nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: lseed = 1, nin = 5, nout = 6
!     .. Local Scalars ..
      Integer                          :: df, genid, ifail, lstate, n, subid
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: x(:)
      Integer                          :: seed(lseed)
      Integer, Allocatable             :: state(:)
!     .. Executable Statements ..
      Write (nout,*) 'G05SDF Example Program Results'
      Write (nout,*)

!     Skip heading in data file
      Read (nin,*)

!     Read in the base generator information and seed
      Read (nin,*) genid, subid, seed(1)

!     Initial call to initializer to get size of STATE array
      lstate = 0
      Allocate (state(lstate))
      ifail = 0
      Call g05kff(genid,subid,seed,lseed,state,lstate,ifail)

!     Reallocate STATE
      Deallocate (state)
      Allocate (state(lstate))

!     Initialize the generator to a repeatable sequence
      ifail = 0
      Call g05kff(genid,subid,seed,lseed,state,lstate,ifail)

!     Read in sample size
      Read (nin,*) n

      Allocate (x(n))

!     Read in the distribution parameter
      Read (nin,*) df

!     Generate the variates
      ifail = 0
      Call g05sdf(n,df,state,x,ifail)

!     Display the variates
      Write (nout,99999) x(1:n)

99999 Format (1X,F10.4)
    End Program g05sdfe


g05sefe.f90

    Program g05sefe

!     G05SEF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: g05kff, g05sef, nag_wp, x04caf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: lseed = 1, nin = 5, nout = 6
!     .. Local Scalars ..
      Integer                          :: genid, ifail, ldx, lstate, m, n,     &
                                          subid
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: a(:), x(:,:)
      Integer                          :: seed(lseed)
      Integer, Allocatable             :: state(:)
!     .. Executable Statements ..
      Write (nout,*) 'G05SEF Example Program Results'
      Write (nout,*)
      Flush (nout)

!     Skip heading in data file
      Read (nin,*)

!     Read in the base generator information and seed
      Read (nin,*) genid, subid, seed(1)

!     Initial call to initializer to get size of STATE array
      lstate = 0
      Allocate (state(lstate))
      ifail = 0
      Call g05kff(genid,subid,seed,lseed,state,lstate,ifail)

!     Reallocate STATE
      Deallocate (state)
      Allocate (state(lstate))

!     Initialize the generator to a repeatable sequence
      ifail = 0
      Call g05kff(genid,subid,seed,lseed,state,lstate,ifail)

!     Read in sample size and number of dimensions
      Read (nin,*) n, m

      ldx = n
      Allocate (x(ldx,m),a(m))

!     Read in the distribution parameters
      Read (nin,*) a(1:m)

!     Generate the variates
      ifail = 0
      Call g05sef(n,m,a,state,x,ldx,ifail)

!     Display the variates
      ifail = 0
      Call x04caf('General',' ',n,m,x,ldx,' ',ifail)

    End Program g05sefe


g05sffe.f90

    Program g05sffe

!     G05SFF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: g05kff, g05sff, nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: lseed = 1, nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: a
      Integer                          :: genid, ifail, lstate, n, subid
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: x(:)
      Integer                          :: seed(lseed)
      Integer, Allocatable             :: state(:)
!     .. Executable Statements ..
      Write (nout,*) 'G05SFF Example Program Results'
      Write (nout,*)

!     Skip heading in data file
      Read (nin,*)

!     Read in the base generator information and seed
      Read (nin,*) genid, subid, seed(1)

!     Initial call to initializer to get size of STATE array
      lstate = 0
      Allocate (state(lstate))
      ifail = 0
      Call g05kff(genid,subid,seed,lseed,state,lstate,ifail)

!     Reallocate STATE
      Deallocate (state)
      Allocate (state(lstate))

!     Initialize the generator to a repeatable sequence
      ifail = 0
      Call g05kff(genid,subid,seed,lseed,state,lstate,ifail)

!     Read in sample size
      Read (nin,*) n

      Allocate (x(n))

!     Read in the distribution parameter
      Read (nin,*) a

!     Generate the variates
      ifail = 0
      Call g05sff(n,a,state,x,ifail)

!     Display the variates
      Write (nout,99999) x(1:n)

99999 Format (1X,F10.4)
    End Program g05sffe


g05sgfe.f90

    Program g05sgfe

!     G05SGF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: g05kff, g05sgf, nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: lseed = 1, nin = 5, nout = 6
!     .. Local Scalars ..
      Integer                          :: genid, ifail, lstate, n, nmix, subid
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: a(:), wgt(:), x(:)
      Integer                          :: seed(lseed)
      Integer, Allocatable             :: state(:)
!     .. Executable Statements ..
      Write (nout,*) 'G05SGF Example Program Results'
      Write (nout,*)

!     Skip heading in data file
      Read (nin,*)

!     Read in the base generator information and seed
      Read (nin,*) genid, subid, seed(1)

!     Initial call to initializer to get size of STATE array
      lstate = 0
      Allocate (state(lstate))
      ifail = 0
      Call g05kff(genid,subid,seed,lseed,state,lstate,ifail)

!     Reallocate STATE
      Deallocate (state)
      Allocate (state(lstate))

!     Initialize the generator to a repeatable sequence
      ifail = 0
      Call g05kff(genid,subid,seed,lseed,state,lstate,ifail)

!     Read in sample size and number of mixtures
      Read (nin,*) n, nmix

      Allocate (x(n),a(nmix),wgt(nmix))

!     Read in the distribution parameters
      Read (nin,*) a(1:nmix)
      Read (nin,*) wgt(1:nmix)

!     Generate the variates
      ifail = 0
      Call g05sgf(n,nmix,a,wgt,state,x,ifail)

!     Display the variates
      Write (nout,99999) x(1:n)

99999 Format (1X,F10.4)
    End Program g05sgfe


g05shfe.f90

    Program g05shfe

!     G05SHF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: g05kff, g05shf, nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: lseed = 1, nin = 5, nout = 6
!     .. Local Scalars ..
      Integer                          :: df1, df2, genid, ifail, lstate, n,   &
                                          subid
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: x(:)
      Integer                          :: seed(lseed)
      Integer, Allocatable             :: state(:)
!     .. Executable Statements ..
      Write (nout,*) 'G05SHF Example Program Results'
      Write (nout,*)

!     Skip heading in data file
      Read (nin,*)

!     Read in the base generator information and seed
      Read (nin,*) genid, subid, seed(1)

!     Initial call to initializer to get size of STATE array
      lstate = 0
      Allocate (state(lstate))
      ifail = 0
      Call g05kff(genid,subid,seed,lseed,state,lstate,ifail)

!     Reallocate STATE
      Deallocate (state)
      Allocate (state(lstate))

!     Initialize the generator to a repeatable sequence
      ifail = 0
      Call g05kff(genid,subid,seed,lseed,state,lstate,ifail)

!     Read in sample size
      Read (nin,*) n

      Allocate (x(n))

!     Read in the distribution parameters
      Read (nin,*) df1, df2

!     Generate the variates
      ifail = 0
      Call g05shf(n,df1,df2,state,x,ifail)

!     Display the variates
      Write (nout,99999) x(1:n)

99999 Format (1X,F10.4)
    End Program g05shfe


g05sjfe.f90

    Program g05sjfe

!     G05SJF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: g05kff, g05sjf, nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: lseed = 1, nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: a, b
      Integer                          :: genid, ifail, lstate, n, subid
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: x(:)
      Integer                          :: seed(lseed)
      Integer, Allocatable             :: state(:)
!     .. Executable Statements ..
      Write (nout,*) 'G05SJF Example Program Results'
      Write (nout,*)

!     Skip heading in data file
      Read (nin,*)

!     Read in the base generator information and seed
      Read (nin,*) genid, subid, seed(1)

!     Initial call to initializer to get size of STATE array
      lstate = 0
      Allocate (state(lstate))
      ifail = 0
      Call g05kff(genid,subid,seed,lseed,state,lstate,ifail)

!     Reallocate STATE
      Deallocate (state)
      Allocate (state(lstate))

!     Initialize the generator to a repeatable sequence
      ifail = 0
      Call g05kff(genid,subid,seed,lseed,state,lstate,ifail)

!     Read in sample size
      Read (nin,*) n

      Allocate (x(n))

!     Read in the distribution parameters
      Read (nin,*) a, b

!     Generate the variates
      ifail = 0
      Call g05sjf(n,a,b,state,x,ifail)

!     Display the variates
      Write (nout,99999) x(1:n)

99999 Format (1X,F10.4)
    End Program g05sjfe


g05skfe.f90

    Program g05skfe

!     G05SKF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: g05kff, g05skf, nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: lseed = 1, nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: var, xmu
      Integer                          :: genid, ifail, lstate, n, subid
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: x(:)
      Integer                          :: seed(lseed)
      Integer, Allocatable             :: state(:)
!     .. Executable Statements ..
      Write (nout,*) 'G05SKF Example Program Results'
      Write (nout,*)

!     Skip heading in data file
      Read (nin,*)

!     Read in the base generator information and seed
      Read (nin,*) genid, subid, seed(1)

!     Initial call to initializer to get size of STATE array
      lstate = 0
      Allocate (state(lstate))
      ifail = 0
      Call g05kff(genid,subid,seed,lseed,state,lstate,ifail)

!     Reallocate STATE
      Deallocate (state)
      Allocate (state(lstate))

!     Initialize the generator to a repeatable sequence
      ifail = 0
      Call g05kff(genid,subid,seed,lseed,state,lstate,ifail)

!     Read in sample size
      Read (nin,*) n

      Allocate (x(n))

!     Read in the distribution parameters
      Read (nin,*) xmu, var

!     Generate the variates
      ifail = 0
      Call g05skf(n,xmu,var,state,x,ifail)

!     Display the variates
      Write (nout,99999) x(1:n)

99999 Format (1X,F10.4)
    End Program g05skfe


g05slfe.f90

    Program g05slfe

!     G05SLF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: g05kff, g05slf, nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: lseed = 1, nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: a, b
      Integer                          :: genid, ifail, lstate, n, subid
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: x(:)
      Integer                          :: seed(lseed)
      Integer, Allocatable             :: state(:)
!     .. Executable Statements ..
      Write (nout,*) 'G05SLF Example Program Results'
      Write (nout,*)

!     Skip heading in data file
      Read (nin,*)

!     Read in the base generator information and seed
      Read (nin,*) genid, subid, seed(1)

!     Initial call to initializer to get size of STATE array
      lstate = 0
      Allocate (state(lstate))
      ifail = 0
      Call g05kff(genid,subid,seed,lseed,state,lstate,ifail)

!     Reallocate STATE
      Deallocate (state)
      Allocate (state(lstate))

!     Initialize the generator to a repeatable sequence
      ifail = 0
      Call g05kff(genid,subid,seed,lseed,state,lstate,ifail)

!     Read in sample size
      Read (nin,*) n

      Allocate (x(n))

!     Read in the distribution parameters
      Read (nin,*) a, b

!     Generate the variates
      ifail = 0
      Call g05slf(n,a,b,state,x,ifail)

!     Display the variates
      Write (nout,99999) x(1:n)

99999 Format (1X,F10.4)
    End Program g05slfe


g05smfe.f90

    Program g05smfe

!     G05SMF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: g05kff, g05smf, nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: lseed = 1, nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: var, xmu
      Integer                          :: genid, ifail, lstate, n, subid
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: x(:)
      Integer                          :: seed(lseed)
      Integer, Allocatable             :: state(:)
!     .. Executable Statements ..
      Write (nout,*) 'G05SMF Example Program Results'
      Write (nout,*)

!     Skip heading in data file
      Read (nin,*)

!     Read in the base generator information and seed
      Read (nin,*) genid, subid, seed(1)

!     Initial call to initializer to get size of STATE array
      lstate = 0
      Allocate (state(lstate))
      ifail = 0
      Call g05kff(genid,subid,seed,lseed,state,lstate,ifail)

!     Reallocate STATE
      Deallocate (state)
      Allocate (state(lstate))

!     Initialize the generator to a repeatable sequence
      ifail = 0
      Call g05kff(genid,subid,seed,lseed,state,lstate,ifail)

!     Read in sample size
      Read (nin,*) n

      Allocate (x(n))

!     Read in the distribution parameters
      Read (nin,*) xmu, var

!     Generate the variates
      ifail = 0
      Call g05smf(n,xmu,var,state,x,ifail)

!     Display the variates
      Write (nout,99999) x(1:n)

99999 Format (1X,F10.4)
    End Program g05smfe


g05snfe.f90

    Program g05snfe

!     G05SNF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: g05kff, g05snf, nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: lseed = 1, nin = 5, nout = 6
!     .. Local Scalars ..
      Integer                          :: df, genid, ifail, lstate, n, subid
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: x(:)
      Integer                          :: seed(lseed)
      Integer, Allocatable             :: state(:)
!     .. Executable Statements ..
      Write (nout,*) 'G05SNF Example Program Results'
      Write (nout,*)

!     Skip heading in data file
      Read (nin,*)

!     Read in the base generator information and seed
      Read (nin,*) genid, subid, seed(1)

!     Initial call to initializer to get size of STATE array
      lstate = 0
      Allocate (state(lstate))
      ifail = 0
      Call g05kff(genid,subid,seed,lseed,state,lstate,ifail)

!     Reallocate STATE
      Deallocate (state)
      Allocate (state(lstate))

!     Initialize the generator to a repeatable sequence
      ifail = 0
      Call g05kff(genid,subid,seed,lseed,state,lstate,ifail)

!     Read in sample size
      Read (nin,*) n

      Allocate (x(n))

!     Read in the distribution parameters
      Read (nin,*) df

!     Generate the variates
      ifail = 0
      Call g05snf(n,df,state,x,ifail)

!     Display the variates
      Write (nout,99999) x(1:n)

99999 Format (1X,F10.4)
    End Program g05snfe


g05spfe.f90

    Program g05spfe

!     G05SPF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: g05kff, g05spf, nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: lseed = 1, nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: xmax, xmed, xmin
      Integer                          :: genid, ifail, lstate, n, subid
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: x(:)
      Integer                          :: seed(lseed)
      Integer, Allocatable             :: state(:)
!     .. Executable Statements ..
      Write (nout,*) 'G05SPF Example Program Results'
      Write (nout,*)

!     Skip heading in data file
      Read (nin,*)

!     Read in the base generator information and seed
      Read (nin,*) genid, subid, seed(1)

!     Initial call to initializer to get size of STATE array
      lstate = 0
      Allocate (state(lstate))
      ifail = 0
      Call g05kff(genid,subid,seed,lseed,state,lstate,ifail)

!     Reallocate STATE
      Deallocate (state)
      Allocate (state(lstate))

!     Initialize the generator to a repeatable sequence
      ifail = 0
      Call g05kff(genid,subid,seed,lseed,state,lstate,ifail)

!     Read in sample size
      Read (nin,*) n

      Allocate (x(n))

!     Read in the distribution parameters
      Read (nin,*) xmin, xmed, xmax

!     Generate the variates
      ifail = 0
      Call g05spf(n,xmin,xmed,xmax,state,x,ifail)

!     Display the variates
      Write (nout,99999) x(1:n)

99999 Format (1X,F10.4)
    End Program g05spfe


g05sqfe.f90

    Program g05sqfe

!     G05SQF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: g05kff, g05sqf, nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: lseed = 1, nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: a, b
      Integer                          :: genid, ifail, lstate, n, subid
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: x(:)
      Integer                          :: seed(lseed)
      Integer, Allocatable             :: state(:)
!     .. Executable Statements ..
      Write (nout,*) 'G05SQF Example Program Results'
      Write (nout,*)

!     Skip heading in data file
      Read (nin,*)

!     Read in the base generator information and seed
      Read (nin,*) genid, subid, seed(1)

!     Initial call to initializer to get size of STATE array
      lstate = 0
      Allocate (state(lstate))
      ifail = 0
      Call g05kff(genid,subid,seed,lseed,state,lstate,ifail)

!     Reallocate STATE
      Deallocate (state)
      Allocate (state(lstate))

!     Initialize the generator to a repeatable sequence
      ifail = 0
      Call g05kff(genid,subid,seed,lseed,state,lstate,ifail)

!     Read in sample size
      Read (nin,*) n

      Allocate (x(n))

!     Read in the distribution parameters
      Read (nin,*) a, b

!     Generate the variates
      ifail = 0
      Call g05sqf(n,a,b,state,x,ifail)

!     Display the variates
      Write (nout,99999) x(1:n)

99999 Format (1X,F10.4)
    End Program g05sqfe


g05srfe.f90

    Program g05srfe

!     G05SRF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: g05kff, g05srf, nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: lseed = 1, nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: vk
      Integer                          :: genid, ifail, lstate, n, subid
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: x(:)
      Integer                          :: seed(lseed)
      Integer, Allocatable             :: state(:)
!     .. Executable Statements ..
      Write (nout,*) 'G05SRF Example Program Results'
      Write (nout,*)

!     Skip heading in data file
      Read (nin,*)

!     Read in the base generator information and seed
      Read (nin,*) genid, subid, seed(1)

!     Initial call to initializer to get size of STATE array
      lstate = 0
      Allocate (state(lstate))
      ifail = 0
      Call g05kff(genid,subid,seed,lseed,state,lstate,ifail)

!     Reallocate STATE
      Deallocate (state)
      Allocate (state(lstate))

!     Initialize the generator to a repeatable sequence
      ifail = 0
      Call g05kff(genid,subid,seed,lseed,state,lstate,ifail)

!     Read in sample size
      Read (nin,*) n

      Allocate (x(n))

!     Read in the distribution parameters
      Read (nin,*) vk

!     Generate the variates
      ifail = 0
      Call g05srf(n,vk,state,x,ifail)

!     Display the variates
      Write (nout,99999) x(1:n)

99999 Format (1X,F10.4)
    End Program g05srfe


g05ssfe.f90

    Program g05ssfe

!     G05SSF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: g05kff, g05ssf, nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: lseed = 1, nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: a, b
      Integer                          :: genid, ifail, lstate, n, subid
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: x(:)
      Integer                          :: seed(lseed)
      Integer, Allocatable             :: state(:)
!     .. Executable Statements ..
      Write (nout,*) 'G05SSF Example Program Results'
      Write (nout,*)

!     Skip heading in data file
      Read (nin,*)

!     Read in the base generator information and seed
      Read (nin,*) genid, subid, seed(1)

!     Initial call to initializer to get size of STATE array
      lstate = 0
      Allocate (state(lstate))
      ifail = 0
      Call g05kff(genid,subid,seed,lseed,state,lstate,ifail)

!     Reallocate STATE
      Deallocate (state)
      Allocate (state(lstate))

!     Initialize the generator to a repeatable sequence
      ifail = 0
      Call g05kff(genid,subid,seed,lseed,state,lstate,ifail)

!     Read in sample size
      Read (nin,*) n

      Allocate (x(n))

!     Read in the distribution parameters
      Read (nin,*) a, b

!     Generate the variates
      ifail = 0
      Call g05ssf(n,a,b,state,x,ifail)

!     Display the variates
      Write (nout,99999) x(1:n)

99999 Format (1X,F10.4)
    End Program g05ssfe


g05tafe.f90

    Program g05tafe

!     G05TAF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: g05kff, g05taf, nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: lseed = 1, maxlr = 5000, nin = 5,    &
                                          nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: p
      Integer                          :: genid, ifail, lr, lstate, m, mode,   &
                                          n, subid
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: r(:)
      Integer                          :: seed(lseed)
      Integer, Allocatable             :: state(:), x(:)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: int, real, sqrt
!     .. Executable Statements ..
      Write (nout,*) 'G05TAF Example Program Results'
      Write (nout,*)

!     Skip heading in data file
      Read (nin,*)

!     Read in the base generator information and seed
      Read (nin,*) genid, subid, seed(1)

!     Initial call to initializer to get size of STATE array
      lstate = 0
      Allocate (state(lstate))
      ifail = 0
      Call g05kff(genid,subid,seed,lseed,state,lstate,ifail)

!     Reallocate STATE
      Deallocate (state)
      Allocate (state(lstate))

!     Initialize the generator to a repeatable sequence
      ifail = 0
      Call g05kff(genid,subid,seed,lseed,state,lstate,ifail)

!     Read in sample size and mode
      Read (nin,*) n

!     Read in the distribution parameters
      Read (nin,*) p, m

!     Use suggested value for LR
      lr = int(2.2E1_nag_wp+2.0E1_nag_wp*sqrt(real(m,                          &
        kind=nag_wp)*p*(1.0E0_nag_wp-p)))

!     If R is a reasonable size use MODE = 2
!     else do not reference R and use MODE = 3
      If (lr<maxlr) Then
        mode = 2
      Else
        mode = 3
        lr = 0
      End If

      Allocate (x(n),r(lr))

!     Generate the variates
      ifail = 0
      Call g05taf(mode,n,m,p,r,lr,state,x,ifail)

!     Display the variates
      Write (nout,99999) x(1:n)

99999 Format (1X,I12)
    End Program g05tafe


g05tbfe.f90

    Program g05tbfe

!     G05TBF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: g05kff, g05tbf, nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: lseed = 1, nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: p
      Integer                          :: genid, ifail, lstate, n, subid
!     .. Local Arrays ..
      Integer                          :: seed(lseed)
      Integer, Allocatable             :: state(:)
      Logical, Allocatable             :: x(:)
!     .. Executable Statements ..
      Write (nout,*) 'G05TBF Example Program Results'
      Write (nout,*)

!     Skip heading in data file
      Read (nin,*)

!     Read in the base generator information and seed
      Read (nin,*) genid, subid, seed(1)

!     Initial call to initializer to get size of STATE array
      lstate = 0
      Allocate (state(lstate))
      ifail = 0
      Call g05kff(genid,subid,seed,lseed,state,lstate,ifail)

!     Reallocate STATE
      Deallocate (state)
      Allocate (state(lstate))

!     Initialize the generator to a repeatable sequence
      ifail = 0
      Call g05kff(genid,subid,seed,lseed,state,lstate,ifail)

!     Read in sample size
      Read (nin,*) n

!     Read in the distribution parameters
      Read (nin,*) p

      Allocate (x(n))

!     Generate the variates
      ifail = 0
      Call g05tbf(n,p,state,x,ifail)

!     Display the variates
      Write (nout,99999) x(1:n)

99999 Format (1X,L1)
    End Program g05tbfe


g05tcfe.f90

    Program g05tcfe

!     G05TCF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: g05kff, g05tcf, nag_wp, x02amf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: lseed = 1, maxlr = 5000, nin = 5,    &
                                          nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: p
      Integer                          :: genid, ifail, lr, lstate, mode, n,   &
                                          subid
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: r(:)
      Integer                          :: seed(lseed)
      Integer, Allocatable             :: state(:), x(:)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: int
!     .. Executable Statements ..
      Write (nout,*) 'G05TCF Example Program Results'
      Write (nout,*)

!     Skip heading in data file
      Read (nin,*)

!     Read in the base generator information and seed
      Read (nin,*) genid, subid, seed(1)

!     Initial call to initializer to get size of STATE array
      lstate = 0
      Allocate (state(lstate))
      ifail = 0
      Call g05kff(genid,subid,seed,lseed,state,lstate,ifail)

!     Reallocate STATE
      Deallocate (state)
      Allocate (state(lstate))

!     Initialize the generator to a repeatable sequence
      ifail = 0
      Call g05kff(genid,subid,seed,lseed,state,lstate,ifail)

!     Read in sample size
      Read (nin,*) n

!     Read in the distribution parameters
      Read (nin,*) p

!     Use suggested value for LR
      If (p<x02amf()) Then
!       P is too close to 0.0 to calculate LR, so
!       set to MAXLR, which means we will use MODE = 3
        lr = maxlr
      Else
        lr = int(8.0E0_nag_wp+4.2E1_nag_wp/p)
      End If

!     If R is a reasonable size use MODE = 2
!     else do not reference R and use MODE = 3
      If (lr<maxlr) Then
        mode = 2
      Else
        mode = 3
        lr = 0
      End If

      Allocate (x(n),r(lr))

!     Generate the variates
      ifail = 0
      Call g05tcf(mode,n,p,r,lr,state,x,ifail)

!     Display the variates
      Write (nout,99999) x(1:n)

99999 Format (1X,I12)
    End Program g05tcfe


g05tdfe.f90

    Program g05tdfe

!     G05TDF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: g05kff, g05tdf, nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: lseed = 1, nin = 5, nout = 6
!     .. Local Scalars ..
      Integer                          :: genid, ifail, ip1, itype, lr,        &
                                          lstate, mode, n, np, subid
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: p(:), r(:)
      Integer                          :: seed(lseed)
      Integer, Allocatable             :: state(:), x(:)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: ceiling, real
!     .. Executable Statements ..
      Write (nout,*) 'G05TDF Example Program Results'
      Write (nout,*)

!     Skip heading in data file
      Read (nin,*)

!     Read in the base generator information and seed
      Read (nin,*) genid, subid, seed(1)

!     Initial call to initializer to get size of STATE array
      lstate = 0
      Allocate (state(lstate))
      ifail = 0
      Call g05kff(genid,subid,seed,lseed,state,lstate,ifail)

!     Reallocate STATE
      Deallocate (state)
      Allocate (state(lstate))

!     Initialize the generator to a repeatable sequence
      ifail = 0
      Call g05kff(genid,subid,seed,lseed,state,lstate,ifail)

!     Read in sample size
      Read (nin,*) n

!     Read in the distribution parameters
      Read (nin,*) np, ip1, itype

!     Use suggested value for LR
      lr = 10 + ceiling(1.4E0_nag_wp*real(np,kind=nag_wp))

!     Generate and set up reference vector in one go
      mode = 2

      Allocate (p(np),x(n),r(lr))

!     Read in probabilities
      Read (nin,*) p(1:np)

!     Generate the variates
      ifail = 0
      Call g05tdf(mode,n,p,np,ip1,itype,r,lr,state,x,ifail)

!     Display the variates
      Write (nout,99999) x(1:n)

99999 Format (1X,I12)
    End Program g05tdfe


g05tefe.f90

    Program g05tefe

!     G05TEF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: g05kff, g05tef, nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: lseed = 1, maxlr = 5000, nin = 5,    &
                                          nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: anp, tmp
      Integer                          :: genid, ifail, lr, lstate, m, mode,   &
                                          n, np, ns, subid
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: r(:)
      Integer                          :: seed(lseed)
      Integer, Allocatable             :: state(:), x(:)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: int, real, sqrt
!     .. Executable Statements ..
      Write (nout,*) 'G05TEF Example Program Results'
      Write (nout,*)

!     Skip heading in data file
      Read (nin,*)

!     Read in the base generator information and seed
      Read (nin,*) genid, subid, seed(1)

!     Initial call to initializer to get size of STATE array
      lstate = 0
      Allocate (state(lstate))
      ifail = 0
      Call g05kff(genid,subid,seed,lseed,state,lstate,ifail)

!     Reallocate STATE
      Deallocate (state)
      Allocate (state(lstate))

!     Initialize the generator to a repeatable sequence
      ifail = 0
      Call g05kff(genid,subid,seed,lseed,state,lstate,ifail)

!     Read in sample size
      Read (nin,*) n

!     Read in the distribution parameters
      Read (nin,*) ns, m, np

!     Use suggested value for LR
      anp = real(np,kind=nag_wp)
      tmp = (real(np-m,kind=nag_wp)/anp)*(real(np-ns,kind=nag_wp)/anp)*        &
        (real(m*ns,kind=nag_wp)/real(np,kind=nag_wp))
      lr = 28 + 20*int(sqrt(tmp))

!     If R is a reasonable size use MODE = 2
!     else do not reference R and use MODE = 3
      If (lr<maxlr) Then
        mode = 2
      Else
        mode = 3
        lr = 0
      End If

      Allocate (x(n),r(lr))

!     Generate the variates
      ifail = -1
      Call g05tef(mode,n,ns,np,m,r,lr,state,x,ifail)

!     Display the variates
      Write (nout,99999) x(1:n)

99999 Format (1X,I12)
    End Program g05tefe


g05tffe.f90

    Program g05tffe

!     G05TFF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: g05kff, g05tff, nag_wp, x02amf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: lseed = 1, maxlr = 5000, nin = 5,    &
                                          nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: a
      Integer                          :: genid, ifail, lr, lstate, mode, n,   &
                                          subid
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: r(:)
      Integer                          :: seed(lseed)
      Integer, Allocatable             :: state(:), x(:)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: int
!     .. Executable Statements ..
      Write (nout,*) 'G05TFF Example Program Results'
      Write (nout,*)

!     Skip heading in data file
      Read (nin,*)

!     Read in the base generator information and seed
      Read (nin,*) genid, subid, seed(1)

!     Initial call to initializer to get size of STATE array
      lstate = 0
      Allocate (state(lstate))
      ifail = 0
      Call g05kff(genid,subid,seed,lseed,state,lstate,ifail)

!     Reallocate STATE
      Deallocate (state)
      Allocate (state(lstate))

!     Initialize the generator to a repeatable sequence
      ifail = 0
      Call g05kff(genid,subid,seed,lseed,state,lstate,ifail)

!     Read in sample size
      Read (nin,*) n

!     Read in the distribution parameters
      Read (nin,*) a

!     Use suggested value for LR
      If (1.0E0_nag_wp-a<x02amf()) Then
!       A is too close to 1.0 to calculate LR, so
!       set to MAXLR, which means we will use MODE = 3
        lr = maxlr
      Else
        lr = int(1.8E1_nag_wp+4.0E1_nag_wp/(1.0E0_nag_wp-a))
      End If

      lr = maxlr
!     If R is a reasonable size use MODE = 2
!     else do not reference R and use MODE = 3
      If (lr<maxlr) Then
        mode = 2
      Else
        mode = 3
        lr = 0
      End If

      Allocate (x(n),r(lr))

!     Generate the variates
      ifail = 0
      Call g05tff(mode,n,a,r,lr,state,x,ifail)

!     Display the variates
      Write (nout,99999) x(1:n)

99999 Format (1X,I12)
    End Program g05tffe


g05tgfe.f90

    Program g05tgfe

!     G05TGF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: g05kff, g05tgf, nag_wp, x04eaf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: lseed = 1, maxlr = 5000, nin = 5,    &
                                          nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: pmax
      Integer                          :: genid, ifail, k, ldx, lr, lstate, m, &
                                          mode, n, subid
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: p(:), r(:)
      Integer                          :: seed(lseed)
      Integer, Allocatable             :: state(:), x(:,:)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: int, maxval, real, sqrt
!     .. Executable Statements ..
      Write (nout,*) 'G05TGF Example Program Results'
      Write (nout,*)
      Flush (nout)

!     Skip heading in data file
      Read (nin,*)

!     Read in the base generator information and seed
      Read (nin,*) genid, subid, seed(1)

!     Initial call to initializer to get size of STATE array
      lstate = 0
      Allocate (state(lstate))
      ifail = 0
      Call g05kff(genid,subid,seed,lseed,state,lstate,ifail)

!     Reallocate STATE
      Deallocate (state)
      Allocate (state(lstate))

!     Initialize the generator to a repeatable sequence
      ifail = 0
      Call g05kff(genid,subid,seed,lseed,state,lstate,ifail)

!     Read in sample size
      Read (nin,*) n

!     Read in the distribution parameters
      Read (nin,*) m, k

      ldx = n
      Allocate (x(ldx,k),p(k))

!     Read in probabilities
      Read (nin,*) p(1:k)

!     Use suggested value for LR
      pmax = maxval(p(1:k))
      lr = int(3.0E1_nag_wp+2.0E1_nag_wp*sqrt(real(m,                          &
        kind=nag_wp)*pmax*(1.0E0_nag_wp-pmax)))

!     If R is a reasonable size use MODE = 2
!     else do not reference R and use MODE = 3
      If (lr<maxlr) Then
        mode = 2
      Else
        mode = 3
        lr = 0
      End If

      Allocate (r(lr))

!     Generate the variates
      ifail = 0
      Call g05tgf(mode,n,m,k,p,r,lr,state,x,ldx,ifail)

!     Display the variates
      ifail = 0
      Call x04eaf('General',' ',n,k,x,ldx,' ',ifail)

    End Program g05tgfe


g05thfe.f90

    Program g05thfe

!     G05THF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: g05kff, g05thf, nag_wp, x02amf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: lseed = 1, maxlr = 5000, nin = 5,    &
                                          nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: p
      Integer                          :: genid, ifail, lr, lstate, m, mode,   &
                                          n, subid
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: r(:)
      Integer                          :: seed(lseed)
      Integer, Allocatable             :: state(:), x(:)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: int, real, sqrt
!     .. Executable Statements ..
      Write (nout,*) 'G05THF Example Program Results'
      Write (nout,*)

!     Skip heading in data file
      Read (nin,*)

!     Read in the base generator information and seed
      Read (nin,*) genid, subid, seed(1)

!     Initial call to initializer to get size of STATE array
      lstate = 0
      Allocate (state(lstate))
      ifail = 0
      Call g05kff(genid,subid,seed,lseed,state,lstate,ifail)

!     Reallocate STATE
      Deallocate (state)
      Allocate (state(lstate))

!     Initialize the generator to a repeatable sequence
      ifail = 0
      Call g05kff(genid,subid,seed,lseed,state,lstate,ifail)

!     Read in sample size
      Read (nin,*) n

!     Read in the distribution parameters
      Read (nin,*) p, m

!     Use suggested value for LR
      If (1.0E0_nag_wp-p<x02amf()) Then
!       P is too close to 1.0 to calculate LR, so
!       set to MAXLR, which means we will use MODE = 3
        lr = maxlr
      Else
        lr = int(2.8E1_nag_wp+(2.0E1_nag_wp*sqrt(real(m,kind=nag_wp)*          &
          p)+3.0E1_nag_wp*p)/(1.0E0_nag_wp-p))
      End If

!     If R is a reasonable size use MODE = 2
!     else do not reference R and use MODE = 3
      If (lr<maxlr) Then
        mode = 2
      Else
        mode = 3
        lr = 0
      End If

      Allocate (x(n),r(lr))

!     Generate the variates
      ifail = 0
      Call g05thf(mode,n,m,p,r,lr,state,x,ifail)

!     Display the variates
      Write (nout,99999) x(1:n)

99999 Format (1X,I12)
    End Program g05thfe


g05tjfe.f90

    Program g05tjfe

!     G05TJF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: g05kff, g05tjf, nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: lseed = 1, maxlr = 5000, nin = 5,    &
                                          nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: lambda
      Integer                          :: genid, ifail, lr, lstate, mode, n,   &
                                          subid
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: r(:)
      Integer                          :: seed(lseed)
      Integer, Allocatable             :: state(:), x(:)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: int, sqrt
!     .. Executable Statements ..
      Write (nout,*) 'G05TJF Example Program Results'
      Write (nout,*)

!     Skip heading in data file
      Read (nin,*)

!     Read in the base generator information and seed
      Read (nin,*) genid, subid, seed(1)

!     Initial call to initializer to get size of STATE array
      lstate = 0
      Allocate (state(lstate))
      ifail = 0
      Call g05kff(genid,subid,seed,lseed,state,lstate,ifail)

!     Reallocate STATE
      Deallocate (state)
      Allocate (state(lstate))

!     Initialize the generator to a repeatable sequence
      ifail = 0
      Call g05kff(genid,subid,seed,lseed,state,lstate,ifail)

!     Read in sample size
      Read (nin,*) n

!     Read in the distribution parameters
      Read (nin,*) lambda

!     Use suggested value for LR
      lr = int(3.0E1_nag_wp+2.0E1_nag_wp*sqrt(lambda)+lambda)

!     If R is a reasonable size use MODE = 2
!     else do not reference R and use MODE = 3
      If (lr<maxlr) Then
        mode = 2
      Else
        mode = 3
        lr = 0
      End If

      Allocate (x(n),r(lr))

!     Generate the variates
      ifail = 0
      Call g05tjf(mode,n,lambda,r,lr,state,x,ifail)

!     Display the variates
      Write (nout,99999) x(1:n)

99999 Format (1X,I12)
    End Program g05tjfe


g05tkfe.f90

    Program g05tkfe

!     G05TKF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: g05kff, g05tkf, nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: lseed = 1, nin = 5, nout = 6
!     .. Local Scalars ..
      Integer                          :: genid, i, ifail, lstate, m, n, subid
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: lambda(:)
      Integer                          :: seed(lseed)
      Integer, Allocatable             :: state(:), x(:)
!     .. Executable Statements ..
      Write (nout,*) 'G05TKF Example Program Results'
      Write (nout,*)

!     Skip heading in data file
      Read (nin,*)

!     Read in the base generator information and seed
      Read (nin,*) genid, subid, seed(1)

!     Initial call to initializer to get size of STATE array
      lstate = 0
      Allocate (state(lstate))
      ifail = 0
      Call g05kff(genid,subid,seed,lseed,state,lstate,ifail)

!     Reallocate STATE
      Deallocate (state)
      Allocate (state(lstate))

!     Initialize the generator to a repeatable sequence
      ifail = 0
      Call g05kff(genid,subid,seed,lseed,state,lstate,ifail)

!     Read in sample size
      Read (nin,*) n

!     Read in the distribution parameters
      Read (nin,*) m

      Allocate (x(n),lambda(m))

!     Read in rest of distribution parameters
      Read (nin,*) lambda(1:m)

!     Generate N sets of the M variates
      Do i = 1, n
        ifail = 0
        Call g05tkf(m,lambda,state,x,ifail)

!       Display the variates
        Write (nout,99999) i, x(1:m)
      End Do

99999 Format (1X,6(1X,I12))
    End Program g05tkfe


g05tlfe.f90

    Program g05tlfe

!     G05TLF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: g05kff, g05tlf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: lseed = 1, nin = 5, nout = 6
!     .. Local Scalars ..
      Integer                          :: a, b, genid, ifail, lstate, n, subid
!     .. Local Arrays ..
      Integer                          :: seed(lseed)
      Integer, Allocatable             :: state(:), x(:)
!     .. Executable Statements ..
      Write (nout,*) 'G05TLF Example Program Results'
      Write (nout,*)

!     Skip heading in data file
      Read (nin,*)

!     Read in the base generator information and seed
      Read (nin,*) genid, subid, seed(1)

!     Initial call to initializer to get size of STATE array
      lstate = 0
      Allocate (state(lstate))
      ifail = 0
      Call g05kff(genid,subid,seed,lseed,state,lstate,ifail)

!     Reallocate STATE
      Deallocate (state)
      Allocate (state(lstate))

!     Initialize the generator to a repeatable sequence
      ifail = 0
      Call g05kff(genid,subid,seed,lseed,state,lstate,ifail)

!     Read in sample size
      Read (nin,*) n

!     Read in the distribution parameters
      Read (nin,*) a, b

      Allocate (x(n))

!     Generate the variates
      ifail = 0
      Call g05tlf(n,a,b,state,x,ifail)

!     Display the variates
      Write (nout,99999) x(1:n)

99999 Format (1X,I12)
    End Program g05tlfe


g05xafe.f90

    Program g05xafe

!     G05XAF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: g05xaf, g05xbf, g05xef, nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: t0, tend
      Integer                          :: a, bgord, d, ifail, ldb, ldc, ldz,   &
                                          nmove, npaths, ntimes, rcord
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: b(:,:), c(:,:), intime(:), rcomm(:), &
                                          start(:), term(:), times(:), z(:,:)
      Integer, Allocatable             :: move(:)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: size
!     .. Executable Statements ..
!     Get information required to set up the bridge
      Call get_bridge_init_data(bgord,t0,tend,ntimes,intime,nmove,move)

!     Make the bridge construction bgord
      Allocate (times(ntimes))
      ifail = 0
      Call g05xef(bgord,t0,tend,ntimes,intime,nmove,move,times,ifail)

!     Initialize the Brownian bridge generator
      Allocate (rcomm(12*(ntimes+1)))
      ifail = 0
      Call g05xaf(t0,tend,times,ntimes,rcomm,ifail)

!     Get additional information required by the bridge generator
      Call get_bridge_gen_data(npaths,rcord,d,start,a,term,c)

!     Generate the Z values
      Call get_z(rcord,npaths,d,a,ntimes,z,b)

!     Leading dimensions for the various input arrays
      ldz = size(z,1)
      ldc = size(c,1)
      ldb = size(b,1)

!     Call the Brownian bridge generator routine
      ifail = 0
      Call g05xbf(npaths,rcord,d,start,a,term,z,ldz,c,ldc,b,ldb,rcomm,ifail)

!     Display the results
      Call display_results(rcord,ntimes,d,b)

    Contains
      Subroutine get_bridge_init_data(bgord,t0,tend,ntimes,intime,nmove,move)

!       .. Scalar Arguments ..
        Real (Kind=nag_wp), Intent (Out) :: t0, tend
        Integer, Intent (Out)          :: bgord, nmove, ntimes
!       .. Array Arguments ..
        Real (Kind=nag_wp), Allocatable, Intent (Out) :: intime(:)
        Integer, Allocatable, Intent (Out) :: move(:)
!       .. Local Scalars ..
        Integer                        :: i
!       .. Intrinsic Procedures ..
        Intrinsic                      :: real
!       .. Executable Statements ..
!       Set the basic parameters for a Wiener process
        ntimes = 10
        t0 = 0.0_nag_wp
        Allocate (intime(ntimes))

!       We want to generate the Wiener process at these time points
        Do i = 1, ntimes
          intime(i) = t0 + real(i,kind=nag_wp)
        End Do
        tend = t0 + real(ntimes+1,kind=nag_wp)

        nmove = 0
        Allocate (move(nmove))
        bgord = 3
      End Subroutine get_bridge_init_data

      Subroutine get_bridge_gen_data(npaths,rcord,d,start,a,term,c)

!       .. Use Statements ..
        Use nag_library, Only: dpotrf
!       .. Scalar Arguments ..
        Integer, Intent (Out)          :: a, d, npaths, rcord
!       .. Array Arguments ..
        Real (Kind=nag_wp), Allocatable, Intent (Out) :: c(:,:), start(:),     &
                                          term(:)
!       .. Local Scalars ..
        Integer                        :: info
!       .. Executable Statements ..
!       Set the basic parameters for a free Wiener process
        npaths = 2
        rcord = 1
        d = 3
        a = 0

        Allocate (start(d),term(d),c(d,d))

        start(1:d) = 0.0_nag_wp
!       As A = 0, TERM need not be initialized

!       We want the following covariance matrix
        c(:,1) = (/6.0_nag_wp,1.0_nag_wp,-0.2_nag_wp/)
        c(:,2) = (/1.0_nag_wp,5.0_nag_wp,0.3_nag_wp/)
        c(:,3) = (/-0.2_nag_wp,0.3_nag_wp,4.0_nag_wp/)

!       G05XBF works with the Cholesky factorization of the covariance matrix
!       C so perform the decomposition
        Call dpotrf('Lower',d,c,d,info)
        If (info/=0) Then
          Write (nout,*)                                                       &
            'Specified covariance matrix is not positive definite: info=',     &
            info
          Stop
        End If
      End Subroutine get_bridge_gen_data

      Subroutine get_z(rcord,npaths,d,a,ntimes,z,b)

!       .. Use Statements ..
        Use nag_library, Only: g05skf
!       .. Scalar Arguments ..
        Integer, Intent (In)           :: a, d, npaths, ntimes, rcord
!       .. Array Arguments ..
        Real (Kind=nag_wp), Allocatable, Intent (Out) :: b(:,:), z(:,:)
!       .. Local Scalars ..
        Integer                        :: idim, ifail
!       .. Local Arrays ..
        Integer                        :: seed(1)
        Integer, Allocatable           :: state(:)
!       .. Executable Statements ..
        idim = d*(ntimes+1-a)

!       Allocate Z
        If (rcord==1) Then
          Allocate (z(idim,npaths))
          Allocate (b(d*(ntimes+1),npaths))
        Else
          Allocate (z(npaths,idim))
          Allocate (b(npaths,d*(ntimes+1)))
        End If

!       We now need to generate the input pseudorandom points
!       First initialize the base pseudorandom number generator
        seed(1) = 1023401
        Call initialize_prng(6,0,seed,size(seed),state)

!       Generate the pseudorandom points from N(0,1)
        ifail = 0
        Call g05skf(idim*npaths,0.0_nag_wp,1.0_nag_wp,state,z,ifail)
      End Subroutine get_z

      Subroutine initialize_prng(genid,subid,seed,lseed,state)

!       .. Use Statements ..
        Use nag_library, Only: g05kff
!       .. Scalar Arguments ..
        Integer, Intent (In)           :: genid, lseed, subid
!       .. Array Arguments ..
        Integer, Intent (In)           :: seed(lseed)
        Integer, Allocatable, Intent (Out) :: state(:)
!       .. Local Scalars ..
        Integer                        :: ifail, lstate
!       .. Executable Statements ..

!       Initial call to initializer to get size of STATE array
        lstate = 0
        Allocate (state(lstate))
        ifail = 0
        Call g05kff(genid,subid,seed,lseed,state,lstate,ifail)

!       Reallocate STATE
        Deallocate (state)
        Allocate (state(lstate))

!       Initialize the generator to a repeatable sequence
        ifail = 0
        Call g05kff(genid,subid,seed,lseed,state,lstate,ifail)
      End Subroutine initialize_prng

      Subroutine display_results(rcord,ntimes,d,b)

!       .. Scalar Arguments ..
        Integer, Intent (In)           :: d, ntimes, rcord
!       .. Array Arguments ..
        Real (Kind=nag_wp), Intent (In) :: b(:,:)
!       .. Local Scalars ..
        Integer                        :: i, j, k
!       .. Executable Statements ..
        Write (nout,*) 'G05XAF Example Program Results'
        Write (nout,*)

        Do i = 1, npaths
          Write (nout,99999) 'Weiner Path ', i, ', ', ntimes + 1,              &
            ' time steps, ', d, ' dimensions'
          Write (nout,99997)(j,j=1,d)
          k = 1
          Do j = 1, ntimes + 1
            If (rcord==1) Then
              Write (nout,99998) j, b(k:k+d-1,i)
            Else
              Write (nout,99998) j, b(i,k:k+d-1)
            End If
            k = k + d
          End Do
          Write (nout,*)
        End Do
99999   Format (1X,A,I0,A,I0,A,I0,A)
99998   Format (1X,I2,1X,20(1X,F10.4))
99997   Format (1X,3X,20(9X,I2))
      End Subroutine display_results
    End Program g05xafe


g05xbfe.f90

    Program g05xbfe

!     G05XBF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: g05xaf, g05xbf, g05xef, nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: t0, tend
      Integer                          :: a, bgord, d, ifail, ldb, ldc, ldz,   &
                                          nmove, npaths, ntimes, rcord
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: b(:,:), c(:,:), intime(:), rcomm(:), &
                                          start(:), term(:), times(:), z(:,:)
      Integer, Allocatable             :: move(:)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: size
!     .. Executable Statements ..
!     Get information required to set up the bridge
      Call get_bridge_init_data(bgord,t0,tend,ntimes,intime,nmove,move)

!     Make the bridge construction bgord
      Allocate (times(ntimes))
      ifail = 0
      Call g05xef(bgord,t0,tend,ntimes,intime,nmove,move,times,ifail)

!     Initialize the Brownian bridge generator
      Allocate (rcomm(12*(ntimes+1)))
      ifail = 0
      Call g05xaf(t0,tend,times,ntimes,rcomm,ifail)

!     Get additional information required by the bridge generator
      Call get_bridge_gen_data(npaths,rcord,d,start,a,term,c)

!     Generate the Z values and allocate B
      Call get_z(rcord,npaths,d,a,ntimes,z,b)

!     Leading dimensions for the various input arrays
      ldz = size(z,1)
      ldc = size(c,1)
      ldb = size(b,1)

!     Call the Brownian bridge generator routine
      ifail = 0
      Call g05xbf(npaths,rcord,d,start,a,term,z,ldz,c,ldc,b,ldb,rcomm,ifail)

!     Display the results
      Call display_results(rcord,ntimes,d,b)

    Contains
      Subroutine get_bridge_init_data(bgord,t0,tend,ntimes,intime,nmove,move)

!       .. Scalar Arguments ..
        Real (Kind=nag_wp), Intent (Out) :: t0, tend
        Integer, Intent (Out)          :: bgord, nmove, ntimes
!       .. Array Arguments ..
        Real (Kind=nag_wp), Allocatable, Intent (Out) :: intime(:)
        Integer, Allocatable, Intent (Out) :: move(:)
!       .. Local Scalars ..
        Integer                        :: i
!       .. Intrinsic Procedures ..
        Intrinsic                      :: real
!       .. Executable Statements ..
!       Set the basic parameters for a Wiener process
        ntimes = 10
        t0 = 0.0_nag_wp
        Allocate (intime(ntimes))

!       We want to generate the Wiener process at these time points
        Do i = 1, ntimes
          intime(i) = t0 + real(i,kind=nag_wp)
        End Do
        tend = t0 + real(ntimes+1,kind=nag_wp)

        nmove = 0
        Allocate (move(nmove))
        bgord = 3
      End Subroutine get_bridge_init_data

      Subroutine get_bridge_gen_data(npaths,rcord,d,start,a,term,c)

!       .. Use Statements ..
        Use nag_library, Only: dpotrf
!       .. Scalar Arguments ..
        Integer, Intent (Out)          :: a, d, npaths, rcord
!       .. Array Arguments ..
        Real (Kind=nag_wp), Allocatable, Intent (Out) :: c(:,:), start(:),     &
                                          term(:)
!       .. Local Scalars ..
        Integer                        :: info
!       .. Executable Statements ..
!       Set the basic parameters for a non-free Wiener process
        npaths = 2
        rcord = 2
        d = 3
        a = 1

        Allocate (start(d),term(d),c(d,d))

        start(1:d) = 0.0_nag_wp
        term(1:d) = (/1.0_nag_wp,0.5_nag_wp,0.0_nag_wp/)

!       We want the following covariance matrix
        c(:,1) = (/6.0_nag_wp,1.0_nag_wp,-0.2_nag_wp/)
        c(:,2) = (/1.0_nag_wp,5.0_nag_wp,0.3_nag_wp/)
        c(:,3) = (/-0.2_nag_wp,0.3_nag_wp,4.0_nag_wp/)

!       G05XBF works with the Cholesky factorization of the covariance matrix
!       C so perform the decomposition
        Call dpotrf('Lower',d,c,d,info)
        If (info/=0) Then
          Write (nout,*)                                                       &
            'Specified covariance matrix is not positive definite: info=',     &
            info
          Stop
        End If
      End Subroutine get_bridge_gen_data

      Subroutine get_z(rcord,npaths,d,a,ntimes,z,b)

!       .. Use Statements ..
        Use nag_library, Only: g05yjf
!       .. Scalar Arguments ..
        Integer, Intent (In)           :: a, d, npaths, ntimes, rcord
!       .. Array Arguments ..
        Real (Kind=nag_wp), Allocatable, Intent (Out) :: b(:,:), z(:,:)
!       .. Local Scalars ..
        Integer                        :: idim, ifail
!       .. Local Arrays ..
        Real (Kind=nag_wp), Allocatable :: std(:), tz(:,:), xmean(:)
        Integer, Allocatable           :: iref(:), state(:)
        Integer                        :: seed(1)
!       .. Intrinsic Procedures ..
        Intrinsic                      :: transpose
!       .. Executable Statements ..
        idim = d*(ntimes+1-a)

!       Allocate Z
        If (rcord==1) Then
          Allocate (z(idim,npaths))
          Allocate (b(d*(ntimes+1),npaths))
        Else
          Allocate (z(npaths,idim))
          Allocate (b(npaths,d*(ntimes+1)))
        End If

!       We now need to generate the input quasi-random points
!       First initialize the base pseudorandom number generator
        seed(1) = 1023401
        Call initialize_prng(6,0,seed,size(seed),state)

!       Scrambled quasi-random sequences preserve the good discrepancy
!       properties of quasi-random sequences while counteracting the bias
!       some applications experience when using quasi-random sequences.
!       Initialize the scrambled quasi-random generator.
        Call initialize_scrambled_qrng(1,2,idim,state,iref)

!       Generate the quasi-random points from N(0,1)
        Allocate (xmean(idim),std(idim))
        xmean(1:idim) = 0.0_nag_wp
        std(1:idim) = 1.0_nag_wp
        If (rcord==1) Then
          Allocate (tz(npaths,idim))
          ifail = 0
          Call g05yjf(xmean,std,npaths,tz,iref,ifail)
          z(:,:) = transpose(tz)
        Else
          ifail = 0
          Call g05yjf(xmean,std,npaths,z,iref,ifail)
        End If
      End Subroutine get_z

      Subroutine initialize_prng(genid,subid,seed,lseed,state)

!       .. Use Statements ..
        Use nag_library, Only: g05kff
!       .. Scalar Arguments ..
        Integer, Intent (In)           :: genid, lseed, subid
!       .. Array Arguments ..
        Integer, Intent (In)           :: seed(lseed)
        Integer, Allocatable, Intent (Out) :: state(:)
!       .. Local Scalars ..
        Integer                        :: ifail, lstate
!       .. Executable Statements ..

!       Initial call to initializer to get size of STATE array
        lstate = 0
        Allocate (state(lstate))
        ifail = 0
        Call g05kff(genid,subid,seed,lseed,state,lstate,ifail)

!       Reallocate STATE
        Deallocate (state)
        Allocate (state(lstate))

!       Initialize the generator to a repeatable sequence
        ifail = 0
        Call g05kff(genid,subid,seed,lseed,state,lstate,ifail)
      End Subroutine initialize_prng

      Subroutine initialize_scrambled_qrng(genid,stype,idim,state,iref)

!       .. Use Statements ..
        Use nag_library, Only: g05ynf
!       .. Scalar Arguments ..
        Integer, Intent (In)           :: genid, idim, stype
!       .. Array Arguments ..
        Integer, Allocatable, Intent (Out) :: iref(:)
        Integer, Intent (Inout)        :: state(*)
!       .. Local Scalars ..
        Integer                        :: ifail, iskip, liref, nsdigits
!       .. Executable Statements ..
        liref = 32*idim + 7
        iskip = 0
        nsdigits = 32
        Allocate (iref(liref))
        ifail = 0
        Call g05ynf(genid,stype,idim,iref,liref,iskip,nsdigits,state,ifail)
      End Subroutine initialize_scrambled_qrng

      Subroutine display_results(rcord,ntimes,d,b)

!       .. Scalar Arguments ..
        Integer, Intent (In)           :: d, ntimes, rcord
!       .. Array Arguments ..
        Real (Kind=nag_wp), Intent (In) :: b(:,:)
!       .. Local Scalars ..
        Integer                        :: i, j, k
!       .. Executable Statements ..
        Write (nout,*) 'G05XBF Example Program Results'
        Write (nout,*)

        Do i = 1, npaths
          Write (nout,99999) 'Weiner Path ', i, ', ', ntimes + 1,              &
            ' time steps, ', d, ' dimensions'
          Write (nout,99997)(j,j=1,d)
          k = 1
          Do j = 1, ntimes + 1
            If (rcord==1) Then
              Write (nout,99998) j, b(k:k+d-1,i)
            Else
              Write (nout,99998) j, b(i,k:k+d-1)
            End If
            k = k + d
          End Do
          Write (nout,*)
        End Do
99999   Format (1X,A,I0,A,I0,A,I0,A)
99998   Format (1X,I2,1X,20(1X,F10.4))
99997   Format (1X,3X,20(9X,I2))
      End Subroutine display_results
    End Program g05xbfe


g05xcfe.f90

    Program g05xcfe

!     G05XCF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: g05xaf, g05xbf, g05xcf, g05xdf, g05xef, nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: t0, tend
      Integer                          :: a, bgord, d, ifail, ldb, ldc, ldz,   &
                                          nmove, npaths, ntimes, rcord
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: bb(:,:), bd(:,:), c(:,:), diff(:),   &
                                          intime(:), rcommb(:), rcommd(:),     &
                                          start(:), term(:), times(:),         &
                                          zb(:,:), zd(:,:)
      Integer, Allocatable             :: move(:)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: size
!     .. Executable Statements ..
!     Get information required to set up the bridge
      Call get_bridge_init_data(bgord,t0,tend,ntimes,intime,nmove,move)

!     Make the bridge construction bgord
      Allocate (times(ntimes))
      ifail = 0
      Call g05xef(bgord,t0,tend,ntimes,intime,nmove,move,times,ifail)

!     Initialize the Brownian bridge generator
      Allocate (rcommb(12*(ntimes+1)),rcommd(12*(ntimes+1)))
      ifail = 0
      Call g05xaf(t0,tend,times,ntimes,rcommb,ifail)
      ifail = 0
      Call g05xcf(t0,tend,times,ntimes,rcommd,ifail)

!     Get additional information required by the bridge generator
      Call get_bridge_gen_data(npaths,rcord,d,start,a,term,c)
      Allocate (diff(d))
      diff(:) = term(:) - start(:)

      Call allocate_arrays(rcord,npaths,d,a,ntimes,zb,bb,zd,bd)

!     Generate the Z values
      Call get_z(rcord,npaths,d*(ntimes+1-a),zb)
      zd(:,:) = zb(:,:)

!     Leading dimensions for the various input arrays
      ldz = size(zb,1)
      ldc = size(c,1)
      ldb = size(bb,1)

!     Call the Brownian bridge generator routine
      ifail = 0
      Call g05xbf(npaths,rcord,d,start,a,term,zb,ldz,c,ldc,bb,ldb,rcommb,      &
        ifail)
      ifail = 0
      Call g05xdf(npaths,rcord,d,a,diff,zd,ldz,c,ldc,bd,ldb,rcommd,ifail)

!     Display the results
      Call display_results(rcord,t0,tend,ntimes,intime,d,start,bb,bd)

    Contains
      Subroutine get_bridge_init_data(bgord,t0,tend,ntimes,intime,nmove,move)

!       .. Scalar Arguments ..
        Real (Kind=nag_wp), Intent (Out) :: t0, tend
        Integer, Intent (Out)          :: bgord, nmove, ntimes
!       .. Array Arguments ..
        Real (Kind=nag_wp), Allocatable, Intent (Out) :: intime(:)
        Integer, Allocatable, Intent (Out) :: move(:)
!       .. Local Scalars ..
        Integer                        :: i
!       .. Intrinsic Procedures ..
        Intrinsic                      :: real
!       .. Executable Statements ..
!       Set the basic parameters for a Wiener process
        ntimes = 10
        t0 = 0.0_nag_wp
        Allocate (intime(ntimes))

!       We want to generate the Wiener process at these time points
        Do i = 1, ntimes
          intime(i) = t0 + real(i,kind=nag_wp)
        End Do
        tend = t0 + real(ntimes+1,kind=nag_wp)

        nmove = 0
        Allocate (move(nmove))
        bgord = 3
      End Subroutine get_bridge_init_data

      Subroutine get_bridge_gen_data(npaths,rcord,d,start,a,term,c)

!       .. Use Statements ..
        Use nag_library, Only: dpotrf
!       .. Scalar Arguments ..
        Integer, Intent (Out)          :: a, d, npaths, rcord
!       .. Array Arguments ..
        Real (Kind=nag_wp), Allocatable, Intent (Out) :: c(:,:), start(:),     &
                                          term(:)
!       .. Local Scalars ..
        Integer                        :: info
!       .. Executable Statements ..
!       Set the basic parameters for a free Wiener process
        npaths = 2
        rcord = 2
        d = 2
        a = 0

        Allocate (start(d),term(d),c(d,d))

        start(1:d) = (/0.0_nag_wp,2.0_nag_wp/)
        term(1:d) = (/1.0_nag_wp,0.0_nag_wp/)

!       We want the following covariance matrix
        c(:,1) = (/6.0_nag_wp,-1.0_nag_wp/)
        c(:,2) = (/-1.0_nag_wp,5.0_nag_wp/)

!       G05XBF works with the Cholesky factorization of the covariance matrix
!       C so perform the decomposition
        Call dpotrf('Lower',d,c,d,info)
        If (info/=0) Then
          Write (nout,*)                                                       &
            'Specified covariance matrix is not positive definite: info=',     &
            info
          Stop
        End If
      End Subroutine get_bridge_gen_data

      Subroutine allocate_arrays(rcord,npaths,d,a,ntimes,zb,bb,zd,bd)

!       .. Scalar Arguments ..
        Integer, Intent (In)           :: a, d, npaths, ntimes, rcord
!       .. Array Arguments ..
        Real (Kind=nag_wp), Allocatable, Intent (Out) :: bb(:,:), bd(:,:),     &
                                          zb(:,:), zd(:,:)
!       .. Local Scalars ..
        Integer                        :: idim
!       .. Executable Statements ..
        idim = d*(ntimes+1-a)

        If (rcord==1) Then
          Allocate (zb(idim,npaths),zd(idim,npaths))
          Allocate (bb(d*(ntimes+1),npaths),bd(d*(ntimes+1),npaths))
        Else
          Allocate (zb(npaths,idim),zd(npaths,idim))
          Allocate (bb(npaths,d*(ntimes+1)),bd(npaths,d*(ntimes+1)))
        End If

      End Subroutine allocate_arrays

      Subroutine get_z(rcord,npaths,idim,z)

!       .. Use Statements ..
        Use nag_library, Only: g05skf
!       .. Scalar Arguments ..
        Integer, Intent (In)           :: idim, npaths, rcord
!       .. Array Arguments ..
        Real (Kind=nag_wp), Intent (Out) :: z(npaths*idim)
!       .. Local Scalars ..
        Integer                        :: ifail
!       .. Local Arrays ..
        Real (Kind=nag_wp), Allocatable :: ztmp(:,:), ztmp2(:,:)
        Integer                        :: seed(1)
        Integer, Allocatable           :: state(:)
!       .. Intrinsic Procedures ..
        Intrinsic                      :: reshape, transpose
!       .. Executable Statements ..
!       We now need to generate the input pseudorandom points
!       First initialize the base pseudorandom number generator
        seed(1) = 1023401
        Call initialize_prng(6,0,seed,size(seed),state)

!       Generate the pseudorandom points from N(0,1)
        ifail = 0
        Call g05skf(idim*npaths,0.0_nag_wp,1.0_nag_wp,state,z,ifail)
        If (rcord==1) Then
          Allocate (ztmp(npaths,idim),ztmp2(idim,npaths))
          ztmp(1:npaths,1:idim) = reshape(z,(/npaths,idim/))
          ztmp2(1:idim,1:npaths) = transpose(ztmp)
          z(1:npaths*idim) = reshape(ztmp2,(/npaths*idim/))
        End If
      End Subroutine get_z

      Subroutine initialize_prng(genid,subid,seed,lseed,state)

!       .. Use Statements ..
        Use nag_library, Only: g05kff
!       .. Scalar Arguments ..
        Integer, Intent (In)           :: genid, lseed, subid
!       .. Array Arguments ..
        Integer, Intent (In)           :: seed(lseed)
        Integer, Allocatable, Intent (Out) :: state(:)
!       .. Local Scalars ..
        Integer                        :: ifail, lstate
!       .. Executable Statements ..
!       Initial call to initializer to get size of STATE array
        lstate = 0
        Allocate (state(lstate))
        ifail = 0
        Call g05kff(genid,subid,seed,lseed,state,lstate,ifail)

!       Reallocate STATE
        Deallocate (state)
        Allocate (state(lstate))

!       Initialize the generator to a repeatable sequence
        ifail = 0
        Call g05kff(genid,subid,seed,lseed,state,lstate,ifail)
      End Subroutine initialize_prng

      Subroutine display_results(rcord,t0,tend,ntimes,intime,d,start,bb,bd)

!       .. Scalar Arguments ..
        Real (Kind=nag_wp), Intent (In) :: t0, tend
        Integer, Intent (In)           :: d, ntimes, rcord
!       .. Array Arguments ..
        Real (Kind=nag_wp), Intent (In) :: bb(:,:), bd(:,:), intime(:),        &
                                          start(:)
!       .. Local Scalars ..
        Integer                        :: i, n
!       .. Local Arrays ..
        Real (Kind=nag_wp), Allocatable :: cum(:), unscaled(:)
!       .. Executable Statements ..
        Allocate (cum(d),unscaled(d))
        Write (nout,*) 'G05XCF Example Program Results'
        Write (nout,*)

        Do n = 1, npaths
          Write (nout,99999) 'Weiner Path ', n, ', ', ntimes + 1,              &
            ' time steps, ', d, ' dimensions'
          Write (nout,'(A)')                                                   &
            '      Output of G05XBF    Output of G05XDF      Sum of G05XDF'

          cum(:) = start(:)
          If (rcord==1) Then
            unscaled(:) = bd(1:d,n)*(intime(1)-t0)
            cum(:) = cum(:) + unscaled(:)
            Write (nout,99998) 1, bb(1:d,n), bd(1:d,n), cum(1:d)
          Else
            unscaled(:) = bd(n,1:d)*(intime(1)-t0)
            cum(:) = cum(:) + unscaled(:)
            Write (nout,99998) 1, bb(n,1:d), bd(n,1:d), cum(1:d)
          End If
          Do i = 2, ntimes
            If (rcord==1) Then
              unscaled(:) = bd(1+(i-1)*d:i*d,n)*(intime(i)-intime(i-1))
              cum(:) = cum(:) + unscaled(:)
              Write (nout,99998) i, bb(1+(i-1)*d:i*d,n), bd(1+(i-1)*d:i*d,n),  &
                cum(1:d)
            Else
              unscaled(:) = bd(n,1+(i-1)*d:i*d)*(intime(i)-intime(i-1))
              cum(:) = cum(:) + unscaled(:)
              Write (nout,99998) i, bb(n,1+(i-1)*d:i*d), bd(n,1+(i-1)*d:i*d),  &
                cum(1:d)
            End If
          End Do
          i = ntimes + 1
          If (rcord==1) Then
            unscaled(:) = bd(1+(i-1)*d:i*d,n)*(tend-intime(i-1))
            cum(:) = cum(:) + unscaled(:)
            Write (nout,99998) i, bb(1+(i-1)*d:i*d,n), bd(1+(i-1)*d:i*d,n),    &
              cum(1:d)
          Else
            unscaled(:) = bd(n,1+(i-1)*d:i*d)*(tend-intime(i-1))
            cum(:) = cum(:) + unscaled(:)
            Write (nout,99998) i, bb(n,1+(i-1)*d:i*d), bd(n,1+(i-1)*d:i*d),    &
              cum(1:d)
          End If

          Write (nout,*)
        End Do

99999   Format (1X,A,I0,A,I0,A,I0,A)
99998   Format (1X,I2,1X,2(1X,F8.4),2X,2(1X,F8.4),2X,2(1X,F8.4))
      End Subroutine display_results
    End Program g05xcfe


g05xdfe.f90

    Program g05xdfe

!     G05XDF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: g05xcf, g05xdf, g05xef, nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: a = 0, d = 1, nout = 6, rcord = 2
      Real (Kind=nag_wp), Parameter    :: c(d) = (/1.0_nag_wp/)
      Real (Kind=nag_wp), Parameter    :: diff(d) = (/0.0_nag_wp/)
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: r, s0, sigma, t0, tend
      Integer                          :: bgord, i, ifail, ldb, ldz, nmove,    &
                                          npaths, ntimesteps, p
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: analytic(:), b(:,:), rcomm(:),       &
                                          st(:,:), t(:), times(:), z(:,:)
      Integer, Allocatable             :: move(:)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: exp, real, size, sqrt
!     .. Executable Statements ..
      ifail = 0

!     We wish to solve the stochastic differential equation (SDE)
!       dSt = r*St*dt + sigma*St*dXt
!     where X is a one dimensional Wiener process.
!     This means we have
!         A = 0
!         D = 1
!         C = 1
!     We now set the other parameters of the SDE and the Euler-Maruyama scheme

!     Initial value of the process
      s0 = 1.0_nag_wp
      r = 0.05_nag_wp
      sigma = 0.12_nag_wp
!     Number of paths to simulate
      npaths = 3
!     The time interval [t0,T] on which to solve the SDE
      t0 = 0.0_nag_wp
      tend = 1.0_nag_wp
!     The time steps in the discretization of [t0,T]
      ntimesteps = 20
      Allocate (t(ntimesteps))
      Do i = 1, ntimesteps
        t(i) = t0 + i*(tend-t0)/real(ntimesteps+1,kind=nag_wp)
      End Do

!     Make the bridge construction order
      nmove = 0
      Allocate (times(ntimesteps),move(nmove))
      bgord = 3
      Call g05xef(bgord,t0,tend,ntimesteps,t,nmove,move,times,ifail)

!     Generate the input Z values and allocate memory for b
      Call get_z(rcord,npaths,d,a,ntimesteps,z,b)
!     Leading dimensions for the various input arrays
      ldz = size(z,1)
      ldb = size(b,1)

!     Initialize the generator
      Allocate (rcomm(12*(ntimesteps+1)))
      Call g05xcf(t0,tend,times,ntimesteps,rcomm,ifail)

!     Get the scaled increments of the Wiener process
      Call g05xdf(npaths,rcord,d,a,diff,z,ldz,c,d,b,ldb,rcomm,ifail)

!     Do the Euler-Maruyama time stepping
      Allocate (st(npaths,ntimesteps+1),analytic(npaths))

!     Do first time step
      st(:,1) = s0 + (t(1)-t0)*(r*s0+sigma*s0*b(:,1))
      Do i = 2, ntimesteps
        Do p = 1, npaths
          st(p,i) = st(p,i-1) + (t(i)-t(i-1))*(r*st(p,i-1)+sigma*st(p,i-1)*b(p &
            ,i))
        End Do
      End Do
!     Do last time step
      st(:,i) = st(:,i-1) + (tend-t(i-1))*(r*st(:,i-1)+sigma*st(:,i-1)*b(:,i))

!     Compute the analytic solution:
!        ST = S0*exp( (r-sigma**2/2)T + sigma WT )

      analytic(:) = s0*exp((r-0.5_nag_wp*sigma*sigma)*tend+sigma*sqrt(tend-t0) &
        *z(:,1))

!     Display the results
      Call display_results(ntimesteps,npaths,st,analytic)

    Contains

      Subroutine get_z(rcord,npaths,d,a,ntimes,z,b)

!       .. Use Statements ..
        Use nag_library, Only: g05yjf
!       .. Scalar Arguments ..
        Integer, Intent (In)           :: a, d, npaths, ntimes, rcord
!       .. Array Arguments ..
        Real (Kind=nag_wp), Allocatable, Intent (Out) :: b(:,:), z(:,:)
!       .. Local Scalars ..
        Integer                        :: idim, ifail
!       .. Local Arrays ..
        Real (Kind=nag_wp), Allocatable :: std(:), tz(:,:), xmean(:)
        Integer, Allocatable           :: iref(:), state(:)
        Integer                        :: seed(1)
!       .. Intrinsic Procedures ..
        Intrinsic                      :: transpose
!       .. Executable Statements ..
        idim = d*(ntimes+1-a)

!       Allocate Z
        If (rcord==1) Then
          Allocate (z(idim,npaths))
          Allocate (b(d*(ntimes+1),npaths))
        Else
          Allocate (z(npaths,idim))
          Allocate (b(npaths,d*(ntimes+1)))
        End If

!       We now need to generate the input quasi-random points
!       First initialize the base pseudorandom number generator
        seed(1) = 1023401
        Call initialize_prng(6,0,seed,size(seed),state)

!       Scrambled quasi-random sequences preserve the good discrepancy
!       properties of quasi-random sequences while counteracting the bias
!       some applications experience when using quasi-random sequences.
!       Initialize the scrambled quasi-random generator.
        Call initialize_scrambled_qrng(1,2,idim,state,iref)

!       Generate the quasi-random points from N(0,1)
        Allocate (xmean(idim),std(idim))
        xmean(1:idim) = 0.0_nag_wp
        std(1:idim) = 1.0_nag_wp
        If (rcord==1) Then
          Allocate (tz(npaths,idim))
          ifail = 0
          Call g05yjf(xmean,std,npaths,tz,iref,ifail)
          z(:,:) = transpose(tz)
        Else
          ifail = 0
          Call g05yjf(xmean,std,npaths,z,iref,ifail)
        End If
      End Subroutine get_z

      Subroutine initialize_prng(genid,subid,seed,lseed,state)

!       .. Use Statements ..
        Use nag_library, Only: g05kff
!       .. Scalar Arguments ..
        Integer, Intent (In)           :: genid, lseed, subid
!       .. Array Arguments ..
        Integer, Intent (In)           :: seed(lseed)
        Integer, Allocatable, Intent (Out) :: state(:)
!       .. Local Scalars ..
        Integer                        :: ifail, lstate
!       .. Executable Statements ..

!       Initial call to initializer to get size of STATE array
        lstate = 0
        Allocate (state(lstate))
        ifail = 0
        Call g05kff(genid,subid,seed,lseed,state,lstate,ifail)

!       Reallocate STATE
        Deallocate (state)
        Allocate (state(lstate))

!       Initialize the generator to a repeatable sequence
        ifail = 0
        Call g05kff(genid,subid,seed,lseed,state,lstate,ifail)
      End Subroutine initialize_prng

      Subroutine initialize_scrambled_qrng(genid,stype,idim,state,iref)

!       .. Use Statements ..
        Use nag_library, Only: g05ynf
!       .. Scalar Arguments ..
        Integer, Intent (In)           :: genid, idim, stype
!       .. Array Arguments ..
        Integer, Allocatable, Intent (Out) :: iref(:)
        Integer, Intent (Inout)        :: state(*)
!       .. Local Scalars ..
        Integer                        :: ifail, iskip, liref, nsdigits
!       .. Executable Statements ..
        liref = 32*idim + 7
        iskip = 0
        nsdigits = 32
        Allocate (iref(liref))
        ifail = 0
        Call g05ynf(genid,stype,idim,iref,liref,iskip,nsdigits,state,ifail)
      End Subroutine initialize_scrambled_qrng

      Subroutine display_results(ntimesteps,npaths,st,analytic)

!       .. Scalar Arguments ..
        Integer, Intent (In)           :: npaths, ntimesteps
!       .. Array Arguments ..
        Real (Kind=nag_wp), Intent (In) :: analytic(:), st(:,:)
!       .. Local Scalars ..
        Integer                        :: i, p
!       .. Executable Statements ..
        Write (nout,*) 'G05XDF Example Program Results'
        Write (nout,*)

        Write (nout,*) 'Euler-Maruyama solution for Geometric Brownian motion'

        Write (nout,99999)('Path',p,p=1,npaths)
        Do i = 1, ntimesteps + 1
          Write (nout,99998) i, st(:,i)
        End Do
        Write (nout,*)

        Write (nout,'(A)') 'Analytic solution at final time step'
        Write (nout,99999)('Path',p,p=1,npaths)
        Write (nout,'(4X,20(1X,F10.4))') analytic(:)

99999   Format (4X,20(5X,A,I2))
99998   Format (1X,I2,1X,20(1X,F10.4))
      End Subroutine display_results
    End Program g05xdfe


g05xefe.f90

    Program g05xefe

!     G05XEF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: g05xaf, g05xbf, g05xef, nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: t0, tend
      Integer                          :: a, bgord, d, ifail, ldb, ldc, ldz,   &
                                          nmove, npaths, ntimes, rcord
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: b(:,:), c(:,:), intime(:), rcomm(:), &
                                          start(:), term(:), times(:), z(:,:)
      Integer, Allocatable             :: move(:)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: size
!     .. Executable Statements ..
!     Get information required to set up the bridge
      Call get_bridge_init_data(bgord,t0,tend,ntimes,intime,nmove,move)

!     Make the bridge construction bgord
      Allocate (times(ntimes))
      ifail = 0
      Call g05xef(bgord,t0,tend,ntimes,intime,nmove,move,times,ifail)

!     Initialize the Brownian bridge generator
      Allocate (rcomm(12*(ntimes+1)))
      ifail = 0
      Call g05xaf(t0,tend,times,ntimes,rcomm,ifail)

!     Get additional information required by the bridge generator
      Call get_bridge_gen_data(npaths,rcord,d,start,a,term,c)

!     Generate the Z values
      Call get_z(rcord,npaths,d,a,ntimes,z,b)

!     Leading dimensions for the various input arrays
      ldz = size(z,1)
      ldc = size(c,1)
      ldb = size(b,1)

!     Call the Brownian bridge generator routine
      ifail = 0
      Call g05xbf(npaths,rcord,d,start,a,term,z,ldz,c,ldc,b,ldb,rcomm,ifail)

!     Display the results
      Call display_results(rcord,ntimes,d,b)

    Contains
      Subroutine get_bridge_init_data(bgord,t0,tend,ntimes,intime,nmove,move)

!       .. Scalar Arguments ..
        Real (Kind=nag_wp), Intent (Out) :: t0, tend
        Integer, Intent (Out)          :: bgord, nmove, ntimes
!       .. Array Arguments ..
        Real (Kind=nag_wp), Allocatable, Intent (Out) :: intime(:)
        Integer, Allocatable, Intent (Out) :: move(:)
!       .. Local Scalars ..
        Integer                        :: i
!       .. Intrinsic Procedures ..
        Intrinsic                      :: real
!       .. Executable Statements ..
!       Set the basic parameters for a Wiener process
        ntimes = 10
        t0 = 0.0_nag_wp
        Allocate (intime(ntimes))

!       We want to generate the Wiener process at these time points
        Do i = 1, ntimes
          intime(i) = t0 + 1.71_nag_wp*real(i,kind=nag_wp)
        End Do
        tend = t0 + 1.71_nag_wp*real(ntimes+1,kind=nag_wp)

!       We suppose the following 3 times are very important and should be
!       constructed first. Note: these are indices into INTIME
        nmove = 3
        Allocate (move(nmove))
        move(1:nmove) = (/3,5,4/)
        bgord = 3
      End Subroutine get_bridge_init_data

      Subroutine get_bridge_gen_data(npaths,rcord,d,start,a,term,c)

!       .. Use Statements ..
        Use nag_library, Only: dpotrf
!       .. Scalar Arguments ..
        Integer, Intent (Out)          :: a, d, npaths, rcord
!       .. Array Arguments ..
        Real (Kind=nag_wp), Allocatable, Intent (Out) :: c(:,:), start(:),     &
                                          term(:)
!       .. Local Scalars ..
        Integer                        :: info
!       .. Executable Statements ..
!       Set the basic parameters for a free Wiener process
        npaths = 2
        rcord = 2
        d = 3
        a = 0

        Allocate (start(d),term(d),c(d,d))

        start(1:d) = 0.0_nag_wp
!       As A = 0, TERM need not be initialized

!       We want the following covariance matrix
        c(:,1) = (/6.0_nag_wp,1.0_nag_wp,-0.2_nag_wp/)
        c(:,2) = (/1.0_nag_wp,5.0_nag_wp,0.3_nag_wp/)
        c(:,3) = (/-0.2_nag_wp,0.3_nag_wp,4.0_nag_wp/)

!       G05XBF works with the Cholesky factorization of the covariance matrix
!       C so perform the decomposition
        Call dpotrf('Lower',d,c,d,info)
        If (info/=0) Then
          Write (nout,*)                                                       &
            'Specified covariance matrix is not positive definite: info=',     &
            info
          Stop
        End If
      End Subroutine get_bridge_gen_data

      Subroutine get_z(rcord,npaths,d,a,ntimes,z,b)

!       .. Use Statements ..
        Use nag_library, Only: g05yjf
!       .. Scalar Arguments ..
        Integer, Intent (In)           :: a, d, npaths, ntimes, rcord
!       .. Array Arguments ..
        Real (Kind=nag_wp), Allocatable, Intent (Out) :: b(:,:), z(:,:)
!       .. Local Scalars ..
        Integer                        :: idim, ifail
!       .. Local Arrays ..
        Real (Kind=nag_wp), Allocatable :: std(:), tz(:,:), xmean(:)
        Integer, Allocatable           :: iref(:), state(:)
        Integer                        :: seed(1)
!       .. Intrinsic Procedures ..
        Intrinsic                      :: transpose
!       .. Executable Statements ..
        idim = d*(ntimes+1-a)

!       Allocate Z
        If (rcord==1) Then
          Allocate (z(idim,npaths))
          Allocate (b(d*(ntimes+1),npaths))
        Else
          Allocate (z(npaths,idim))
          Allocate (b(npaths,d*(ntimes+1)))
        End If

!       We now need to generate the input quasi-random points
!       First initialize the base pseudorandom number generator
        seed(1) = 1023401
        Call initialize_prng(6,0,seed,size(seed),state)

!       Scrambled quasi-random sequences preserve the good discrepancy
!       properties of quasi-random sequences while counteracting the bias
!       some applications experience when using quasi-random sequences.
!       Initialize the scrambled quasi-random generator.
        Call initialize_scrambled_qrng(1,2,idim,state,iref)

!       Generate the quasi-random points from N(0,1)
        Allocate (xmean(idim),std(idim))
        xmean(1:idim) = 0.0_nag_wp
        std(1:idim) = 1.0_nag_wp
        If (rcord==1) Then
          Allocate (tz(npaths,idim))
          ifail = 0
          Call g05yjf(xmean,std,npaths,tz,iref,ifail)
          z(:,:) = transpose(tz)
        Else
          ifail = 0
          Call g05yjf(xmean,std,npaths,z,iref,ifail)
        End If
      End Subroutine get_z

      Subroutine initialize_prng(genid,subid,seed,lseed,state)

!       .. Use Statements ..
        Use nag_library, Only: g05kff
!       .. Scalar Arguments ..
        Integer, Intent (In)           :: genid, lseed, subid
!       .. Array Arguments ..
        Integer, Intent (In)           :: seed(lseed)
        Integer, Allocatable, Intent (Out) :: state(:)
!       .. Local Scalars ..
        Integer                        :: ifail, lstate
!       .. Executable Statements ..

!       Initial call to initializer to get size of STATE array
        lstate = 0
        Allocate (state(lstate))
        ifail = 0
        Call g05kff(genid,subid,seed,lseed,state,lstate,ifail)

!       Reallocate STATE
        Deallocate (state)
        Allocate (state(lstate))

!       Initialize the generator to a repeatable sequence
        ifail = 0
        Call g05kff(genid,subid,seed,lseed,state,lstate,ifail)
      End Subroutine initialize_prng

      Subroutine initialize_scrambled_qrng(genid,stype,idim,state,iref)

!       .. Use Statements ..
        Use nag_library, Only: g05ynf
!       .. Scalar Arguments ..
        Integer, Intent (In)           :: genid, idim, stype
!       .. Array Arguments ..
        Integer, Allocatable, Intent (Out) :: iref(:)
        Integer, Intent (Inout)        :: state(*)
!       .. Local Scalars ..
        Integer                        :: ifail, iskip, liref, nsdigits
!       .. Executable Statements ..
        liref = 32*idim + 7
        iskip = 0
        nsdigits = 32
        Allocate (iref(liref))
        ifail = 0
        Call g05ynf(genid,stype,idim,iref,liref,iskip,nsdigits,state,ifail)
      End Subroutine initialize_scrambled_qrng

      Subroutine display_results(rcord,ntimes,d,b)

!       .. Scalar Arguments ..
        Integer, Intent (In)           :: d, ntimes, rcord
!       .. Array Arguments ..
        Real (Kind=nag_wp), Intent (In) :: b(:,:)
!       .. Local Scalars ..
        Integer                        :: i, j, k
!       .. Executable Statements ..
        Write (nout,*) 'G05XEF Example Program Results'
        Write (nout,*)

        Do i = 1, npaths
          Write (nout,99999) 'Weiner Path ', i, ', ', ntimes + 1,              &
            ' time steps, ', d, ' dimensions'
          Write (nout,99997)(j,j=1,d)
          k = 1
          Do j = 1, ntimes + 1
            If (rcord==1) Then
              Write (nout,99998) j, b(k:k+d-1,i)
            Else
              Write (nout,99998) j, b(i,k:k+d-1)
            End If
            k = k + d
          End Do
          Write (nout,*)
        End Do
99999   Format (1X,A,I0,A,I0,A,I0,A)
99998   Format (1X,I2,1X,20(1X,F10.4))
99997   Format (1X,3X,20(9X,I2))
      End Subroutine display_results
    End Program g05xefe


g05yjfe.f90

    Program g05yjfe

!     G05YJF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: g05yjf, g05ylf, nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Integer                          :: genid, i, idim, ifail, iskip,        &
                                          ldquas, liref, n
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: quas(:,:), std(:), xmean(:)
      Integer, Allocatable             :: iref(:)
!     .. Executable Statements ..
      Write (nout,*) 'G05YJF Example Program Results'
      Write (nout,*)

!     Skip heading in data file
      Read (nin,*)

!     Read in the generator to use
      Read (nin,*) genid

!     Read in problem size
      Read (nin,*) n, idim, iskip

      If (genid==4) Then
        liref = 407
      Else
        liref = 32*idim + 7
      End If
      ldquas = n
      Allocate (quas(ldquas,idim),iref(liref),xmean(idim),std(idim))

!     Read in the parameters for the distribution
      Read (nin,*) xmean(1:idim)
      Read (nin,*) std(1:idim)

!     Initialize the generator
      ifail = 0
      Call g05ylf(genid,idim,iref,liref,iskip,ifail)

!     Generate N values for the normal distribution
      ifail = 0
      Call g05yjf(xmean,std,n,quas,iref,ifail)

!     Display results
      Write (nout,99999)(quas(i,1:idim),i=1,n)

99999 Format (1X,4F10.4)
    End Program g05yjfe


g05ykfe.f90

    Program g05ykfe

!     G05YKF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: g05ykf, g05ylf, nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Integer                          :: genid, i, idim, ifail, iskip,        &
                                          ldquas, liref, n
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: quas(:,:), std(:), xmean(:)
      Integer, Allocatable             :: iref(:)
!     .. Executable Statements ..
      Write (nout,*) 'G05YKF Example Program Results'
      Write (nout,*)

!     Skip heading in data file
      Read (nin,*)

!     Read in the generator to use
      Read (nin,*) genid

!     Read in problem size
      Read (nin,*) n, idim, iskip

      If (genid==4) Then
        liref = 407
      Else
        liref = 32*idim + 7
      End If
      ldquas = n
      Allocate (quas(ldquas,idim),iref(liref),xmean(idim),std(idim))

!     Read in the parameters for the distribution
      Read (nin,*) xmean(1:idim)
      Read (nin,*) std(1:idim)

!     Initialize the generator
      ifail = 0
      Call g05ylf(genid,idim,iref,liref,iskip,ifail)

!     Generate N values for the normal distribution
      ifail = 0
      Call g05ykf(xmean,std,n,quas,iref,ifail)

!     Display results
      Write (nout,99999)(quas(i,1:idim),i=1,n)

99999 Format (1X,4F10.4)
    End Program g05ykfe


g05ymfe.f90

!   G05YMF Example Program Text
!   Mark 26 Release. NAG Copyright 2016.

    Module g05ymfe_mod

!     G05YMF Example Program Module:
!            Parameters and User-defined Routines

!     .. Use Statements ..
      Use nag_library, Only: nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Accessibility Statements ..
      Private
      Public                           :: ifun
!     .. Parameters ..
      Integer, Parameter, Public       :: nin = 5, nout = 6
    Contains
      Function ifun(x,lx)
!       Function being integrated, in this example
!       ABS(4.0 X - 2)

!       .. Function Return Value ..
        Real (Kind=nag_wp)             :: ifun
!       .. Scalar Arguments ..
        Integer, Intent (In)           :: lx
!       .. Array Arguments ..
        Real (Kind=nag_wp), Intent (In) :: x(lx)
!       .. Local Scalars ..
        Integer                        :: d
!       .. Intrinsic Procedures ..
        Intrinsic                      :: abs
!       .. Executable Statements ..
        ifun = 1.0E0_nag_wp
        Do d = 1, lx
          ifun = ifun*abs(4.0E0_nag_wp*x(d)-2.0E0_nag_wp)
        End Do
      End Function ifun
    End Module g05ymfe_mod
    Program g05ymfe

!     G05YMF Example Main Program

!     .. Use Statements ..
      Use nag_library, Only: g05ylf, g05ymf, nag_wp, x04caf
      Use g05ymfe_mod, Only: ifun, nin, nout
!     .. Implicit None Statement ..
      Implicit None
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: sum, vsbl
      Integer                          :: dn, genid, i, idim, ifail, iskip,    &
                                          ldquas, liref, n, rcord
      Character (80)                   :: title
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: quas(:,:)
      Integer, Allocatable             :: iref(:)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: real
!     .. Executable Statements ..
      Write (nout,*) 'G05YMF Example Program Results'
      Write (nout,*)

!     Skip heading in data file
      Read (nin,*)

!     Fix the RCORD = 1, so QUAS(IDIM,N). As we
!     are accessing each dimension in turn for a given variate
!     when evaluating the function, this is more efficient
      rcord = 1

!     Read in the generator to use
      Read (nin,*) genid

!     Read in the problem size
      Read (nin,*) n, idim, iskip

      If (genid==4) Then
        liref = 407
      Else
        liref = 32*idim + 7
      End If
      ldquas = idim
      Allocate (quas(ldquas,n),iref(liref))

!     Initialize the generator
      ifail = 0
      Call g05ylf(genid,idim,iref,liref,iskip,ifail)

!     Generate N quasi-random variates
      ifail = 0
      Call g05ymf(n,rcord,quas,ldquas,iref,ifail)

!     Evaluate the function, and sum
      sum = 0.0E0_nag_wp
      Do i = 1, n
        sum = sum + ifun(quas(1:idim,i),idim)
      End Do

!     Convert sum to mean value
      vsbl = sum/real(n,kind=nag_wp)
      Write (nout,*)
      Write (nout,99999) 'Value of integral = ', vsbl

!     Read in number of variates to display
      Read (nin,*) dn

!     Display the first DN variates
      Write (nout,*)
      Write (title,99998) 'First ', dn, ' variates for all ', idim,            &
        ' dimensions'
      Flush (nout)
      ifail = 0
      Call x04caf('General',' ',idim,dn,quas,ldquas,title,ifail)

99999 Format (1X,A,F8.4)
99998 Format (A,I0,A,I0,A)
    End Program g05ymfe


g05ynfe.f90

!   G05YNF Example Program Text
!   Mark 26 Release. NAG Copyright 2016.

    Module g05ynfe_mod

!     G05YNF Example Program Module:
!            Parameters and User-defined Routines

!     .. Use Statements ..
      Use nag_library, Only: nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Accessibility Statements ..
      Private
      Public                           :: ifun
!     .. Parameters ..
      Integer, Parameter, Public       :: lseed = 1, nin = 5, nout = 6
    Contains
      Function ifun(x,lx)
!       Function being integrated, in this case
!       ABS(4.0 X - 2)

!       .. Function Return Value ..
        Real (Kind=nag_wp)             :: ifun
!       .. Scalar Arguments ..
        Integer, Intent (In)           :: lx
!       .. Array Arguments ..
        Real (Kind=nag_wp), Intent (In) :: x(lx)
!       .. Local Scalars ..
        Integer                        :: d
!       .. Intrinsic Procedures ..
        Intrinsic                      :: abs
!       .. Executable Statements ..
        ifun = 1.0E0_nag_wp
        Do d = 1, lx
          ifun = ifun*abs(4.0E0_nag_wp*x(d)-2.0E0_nag_wp)
        End Do
      End Function ifun
    End Module g05ynfe_mod
    Program g05ynfe

!     G05YNF Example Main Program

!     .. Use Statements ..
      Use nag_library, Only: g05kff, g05ymf, g05ynf, nag_wp, x04caf
      Use g05ynfe_mod, Only: ifun, lseed, nin, nout
!     .. Implicit None Statement ..
      Implicit None
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: sum, vsbl
      Integer                          :: dn, genid, i, idim, ifail, iskip,    &
                                          ldquas, liref, lstate, n, nsdigi,    &
                                          pgenid, psubid, rcord, stype
      Character (80)                   :: title
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: quas(:,:)
      Integer, Allocatable             :: iref(:), state(:)
      Integer                          :: seed(lseed)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: real
!     .. Executable Statements ..
      Write (nout,*) 'G05YNF Example Program Results'
      Write (nout,*)

!     Skip heading in data file
      Read (nin,*)

!     Read in the base generator information and seed
      Read (nin,*) pgenid, psubid, seed(1)

!     Initial call to initializer to get size of STATE array
      lstate = 0
      Allocate (state(lstate))
      ifail = 0
      Call g05kff(pgenid,psubid,seed,lseed,state,lstate,ifail)

!     Reallocate STATE
      Deallocate (state)
      Allocate (state(lstate))

!     Initialize the generator to a repeatable sequence
      ifail = 0
      Call g05kff(pgenid,psubid,seed,lseed,state,lstate,ifail)

!     Fix the RCORD = 1, so QUAS(IDIM,N). As we
!     are accessing each dimension in turn for a given variate
!     when evaluating the function, this is more efficient
      rcord = 1

!     Read in quasi-random generator and scrambling to use
      Read (nin,*) genid, stype, nsdigi

!     Read in problem size
      Read (nin,*) n, idim, iskip

      If (genid==4) Then
        liref = 407
      Else
        liref = 32*idim + 7
      End If
      ldquas = idim
      Allocate (quas(ldquas,n),iref(liref))

!     Call the initializer for the quasi-random sequence
      ifail = 0
      Call g05ynf(genid,stype,idim,iref,liref,iskip,nsdigi,state,ifail)

!     Generate N quasi-random variates
      ifail = 0
      Call g05ymf(n,rcord,quas,ldquas,iref,ifail)

!     Evaluate the function, and sum
      sum = 0.0E0_nag_wp
      Do i = 1, n
        sum = sum + ifun(quas(1:idim,i),idim)
      End Do

!     Convert sum to mean value
      vsbl = sum/real(n,kind=nag_wp)
      Write (nout,99999)
      Write (nout,99999) 'Value of integral = ', vsbl

!     Read in number of variates to display
      Read (nin,*) dn

!     Display the first DN variates
      Write (nout,*)
      Write (title,99998) 'First ', dn, ' variates for all ', idim,            &
        ' dimensions'
      Flush (nout)
      ifail = 0
      Call x04caf('General',' ',idim,dn,quas,ldquas,title,ifail)

99999 Format (1X,A,F8.4)
99998 Format (A,I0,A,I0,A)
    End Program g05ynfe


g05zmfe.f90

!   G05ZMF Example Program Text

!   Mark 26 Release. NAG Copyright 2016.

    Module g05zmfe_mod

!     G05ZMF Example Program Module:
!            Parameters and User-defined Routines

!     .. Use Statements ..
      Use nag_library, Only: nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Accessibility Statements ..
      Private
      Public                           :: cov1
    Contains
      Subroutine cov1(t,gamma,iuser,ruser)

!       .. Implicit None Statement ..
        Implicit None
!       .. Scalar Arguments ..
        Real (Kind=nag_wp), Intent (Out) :: gamma
        Real (Kind=nag_wp), Intent (In) :: t
!       .. Array Arguments ..
        Real (Kind=nag_wp), Intent (Inout) :: ruser(*)
        Integer, Intent (Inout)        :: iuser(*)
!       .. Local Scalars ..
        Real (Kind=nag_wp)             :: dummy, l, nu
!       .. Intrinsic Procedures ..
        Intrinsic                      :: abs, exp
!       .. Executable Statements ..
!       Correlation length in ruser(1)
        l = ruser(1)
!       Exponent in ruser(2)
        nu = ruser(2)

        If (t==0.0_nag_wp) Then
          gamma = 1.0_nag_wp
        Else
          dummy = (abs(t)/l)**nu
          gamma = exp(-dummy)
        End If

        Return

      End Subroutine cov1
    End Module g05zmfe_mod

    Program g05zmfe

!     G05ZMF Example Main Program

!     .. Use Statements ..
      Use nag_library, Only: g05zmf, nag_wp
      Use g05zmfe_mod, Only: cov1
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: l, nu, rho, var, xmax, xmin
      Integer                          :: approx, icorr, icount, ifail, m,     &
                                          maxm, ns, pad
!     .. Local Arrays ..
      Real (Kind=nag_wp)               :: eig(3), ruser(2)
      Real (Kind=nag_wp), Allocatable  :: lam(:), xx(:)
      Integer                          :: iuser(0)
!     .. Executable Statements ..
      Write (nout,*) 'G05ZMF Example Program Results'
      Write (nout,*)

!     Get problem specifications from data file
      Call read_input_data(l,nu,var,xmin,xmax,ns,maxm,icorr,pad)

!     Put covariance parameters in communication array
      ruser(1) = l
      ruser(2) = nu

      Allocate (lam(maxm),xx(ns))

!     Get square roots of the eigenvalues of the embedding matrix
      ifail = 0
      Call g05zmf(ns,xmin,xmax,maxm,var,cov1,pad,icorr,lam,xx,m,approx,rho,    &
        icount,eig,iuser,ruser,ifail)

!     Output results
      Call display_results(approx,m,rho,eig,icount,lam)

    Contains
      Subroutine read_input_data(l,nu,var,xmin,xmax,ns,maxm,icorr,pad)

!       .. Implicit None Statement ..
        Implicit None
!       .. Scalar Arguments ..
        Real (Kind=nag_wp), Intent (Out) :: l, nu, var, xmax, xmin
        Integer, Intent (Out)          :: icorr, maxm, ns, pad
!       .. Executable Statements ..
!       Skip heading in data file
        Read (nin,*)

!       Read in l and nu for cov1 function
        Read (nin,*) l, nu

!       Read in variance of random field
        Read (nin,*) var

!       Read in domain endpoints
        Read (nin,*) xmin, xmax

!       Read in number of sample points
        Read (nin,*) ns

!       Read in maximum size of embedding matrix
        Read (nin,*) maxm

!       Read in choice of scaling in case of approximation
        Read (nin,*) icorr

!       Read in choice of padding
        Read (nin,*) pad

        Return

      End Subroutine read_input_data

      Subroutine display_results(approx,m,rho,eig,icount,lam)

!       .. Implicit None Statement ..
        Implicit None
!       .. Scalar Arguments ..
        Real (Kind=nag_wp), Intent (In) :: rho
        Integer, Intent (In)           :: approx, icount, m
!       .. Array Arguments ..
        Real (Kind=nag_wp), Intent (In) :: eig(3), lam(m)
!       .. Executable Statements ..
!       Display size of embedding matrix
        Write (nout,*)
        Write (nout,99999) 'Size of embedding matrix = ', m

!       Display approximation information if approximation used
        Write (nout,*)
        If (approx==1) Then
          Write (nout,*) 'Approximation required'
          Write (nout,*)
          Write (nout,99998) 'RHO = ', rho
          Write (nout,99997) 'EIG = ', eig(1:3)
          Write (nout,99999) 'ICOUNT = ', icount
        Else
          Write (nout,*) 'Approximation not required'
        End If

!       Display square roots of the eigenvalues of the embedding matrix
        Write (nout,*)
        Write (nout,*) 'Square roots of eigenvalues of embedding matrix:'
        Write (nout,*)
        Write (nout,99996) lam(1:m)

        Return

99999   Format (1X,A,I7)
99998   Format (1X,A,F10.5)
99997   Format (1X,A,3(F10.5,1X))
99996   Format (1X,4F10.5)

      End Subroutine display_results

    End Program g05zmfe


g05znfe.f90

!   G05ZNF Example Program Text

!   Mark 26 Release. NAG Copyright 2016.

    Program g05znfe

!     G05ZNF Example Main Program

!     .. Use Statements ..
      Use nag_library, Only: g05znf, nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6, npmax = 4
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: rho, var, xmax, xmin
      Integer                          :: approx, icorr, icount, icov1, ifail, &
                                          m, maxm, np, ns, pad
!     .. Local Arrays ..
      Real (Kind=nag_wp)               :: eig(3), params(npmax)
      Real (Kind=nag_wp), Allocatable  :: lam(:), xx(:)
!     .. Executable Statements ..
      Write (nout,*) 'G05ZNF Example Program Results'
      Write (nout,*)

!     Get problem specifications from data file
      Call read_input_data(icov1,np,params,var,xmin,xmax,ns,maxm,icorr,pad)

      Allocate (lam(maxm),xx(ns))

!     Get square roots of the eigenvalues of the embedding matrix
      ifail = 0
      Call g05znf(ns,xmin,xmax,maxm,var,icov1,np,params,pad,icorr,lam,xx,m,    &
        approx,rho,icount,eig,ifail)

!     Output results
      Call display_results(approx,m,rho,eig,icount,lam)

    Contains
      Subroutine read_input_data(icov1,np,params,var,xmin,xmax,ns,maxm,icorr,  &
        pad)

!       .. Implicit None Statement ..
        Implicit None
!       .. Scalar Arguments ..
        Real (Kind=nag_wp), Intent (Out) :: var, xmax, xmin
        Integer, Intent (Out)          :: icorr, icov1, maxm, np, ns, pad
!       .. Array Arguments ..
        Real (Kind=nag_wp), Intent (Out) :: params(npmax)
!       .. Executable Statements ..
!       Skip heading in data file
        Read (nin,*)

!       Read in covariance function number
        Read (nin,*) icov1

!       Read in number of parameters
        Read (nin,*) np

!       Read in parameters
        If (np>0) Then
          Read (nin,*) params(1:np)
        End If

!       Read in variance of random field
        Read (nin,*) var

!       Read in domain endpoints
        Read (nin,*) xmin, xmax

!       Read in number of sample points
        Read (nin,*) ns

!       Read in maximum size of embedding matrix
        Read (nin,*) maxm

!       Read in choice of scaling in case of approximation
        Read (nin,*) icorr

!       Read in choice of padding
        Read (nin,*) pad

        Return

      End Subroutine read_input_data

      Subroutine display_results(approx,m,rho,eig,icount,lam)

!       .. Implicit None Statement ..
        Implicit None
!       .. Scalar Arguments ..
        Real (Kind=nag_wp), Intent (In) :: rho
        Integer, Intent (In)           :: approx, icount, m
!       .. Array Arguments ..
        Real (Kind=nag_wp), Intent (In) :: eig(3), lam(m)
!       .. Executable Statements ..
!       Display size of embedding matrix
        Write (nout,*)
        Write (nout,99999) 'Size of embedding matrix = ', m

!       Display approximation information if approximation used
        Write (nout,*)
        If (approx==1) Then
          Write (nout,*) 'Approximation required'
          Write (nout,*)
          Write (nout,99998) 'RHO = ', rho
          Write (nout,99997) 'EIG = ', eig(1:3)
          Write (nout,99999) 'ICOUNT = ', icount
        Else
          Write (nout,*) 'Approximation not required'
        End If

!       Display square roots of the eigenvalues of the embedding matrix
        Write (nout,*)
        Write (nout,*) 'Square roots of eigenvalues of embedding matrix:'
        Write (nout,*)
        Write (nout,99996) lam(1:m)

        Return

99999   Format (1X,A,I7)
99998   Format (1X,A,F10.5)
99997   Format (1X,A,3(F10.5,1X))
99996   Format (1X,4F10.5)

      End Subroutine display_results

    End Program g05znfe


g05zpfe.f90

!   G05ZPF Example Program Text

!   Mark 26 Release. NAG Copyright 2016.

    Program g05zpfe

!     G05ZPF Example Main Program

!     .. Use Statements ..
      Use nag_library, Only: g05znf, g05zpf, nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: lenst = 17, nin = 5, nout = 6,       &
                                          npmax = 4
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: rho, var, xmax, xmin
      Integer                          :: approx, icorr, icount, icov1, ifail, &
                                          m, maxm, np, ns, pad, s
!     .. Local Arrays ..
      Real (Kind=nag_wp)               :: eig(3), params(npmax)
      Real (Kind=nag_wp), Allocatable  :: lam(:), xx(:), z(:,:)
      Integer                          :: state(lenst)
!     .. Executable Statements ..
      Write (nout,*) 'G05ZPF Example Program Results'
      Write (nout,*)
      Flush (nout)

!     Get problem specifications from data file
      Call read_input_data(icov1,np,params,var,xmin,xmax,ns,maxm,icorr,pad,s)

      Allocate (lam(maxm),xx(ns))

!     Get square roots of the eigenvalues of the embedding matrix
      ifail = 0
      Call g05znf(ns,xmin,xmax,maxm,var,icov1,np,params,pad,icorr,lam,xx,m,    &
        approx,rho,icount,eig,ifail)

      Call display_embedding_results(approx,m,rho,eig,icount)

!     Initialize state array
      Call initialize_state(state)

      Allocate (z(ns,s))

!     Compute s random field realizations.
      Call g05zpf(ns,s,m,lam,rho,state,z,ifail)

      Call display_realizations(ns,s,xx,z)

    Contains
      Subroutine read_input_data(icov1,np,params,var,xmin,xmax,ns,maxm,icorr,  &
        pad,s)

!       .. Implicit None Statement ..
        Implicit None
!       .. Scalar Arguments ..
        Real (Kind=nag_wp), Intent (Out) :: var, xmax, xmin
        Integer, Intent (Out)          :: icorr, icov1, maxm, np, ns, pad, s
!       .. Array Arguments ..
        Real (Kind=nag_wp), Intent (Out) :: params(npmax)
!       .. Executable Statements ..
!       Skip heading in data file
        Read (nin,*)

!       Read in covariance function number
        Read (nin,*) icov1

!       Read in number of parameters
        Read (nin,*) np

!       Read in parameters
        If (np>0) Then
          Read (nin,*) params(1:np)
        End If

!       Read in variance of random field
        Read (nin,*) var

!       Read in domain endpoints
        Read (nin,*) xmin, xmax

!       Read in number of sample points
        Read (nin,*) ns

!       Read in maximum size of embedding matrix
        Read (nin,*) maxm

!       Read in choice of scaling in case of approximation
        Read (nin,*) icorr

!       Read in choice of padding
        Read (nin,*) pad

!       Read in number of realization samples to be generated
        Read (nin,*) s

        Return

      End Subroutine read_input_data

      Subroutine display_embedding_results(approx,m,rho,eig,icount)

!       .. Implicit None Statement ..
        Implicit None
!       .. Scalar Arguments ..
        Real (Kind=nag_wp), Intent (In) :: rho
        Integer, Intent (In)           :: approx, icount, m
!       .. Array Arguments ..
        Real (Kind=nag_wp), Intent (In) :: eig(3)
!       .. Executable Statements ..
!       Display size of embedding matrix
        Write (nout,*)
        Write (nout,99999) 'Size of embedding matrix = ', m

!       Display approximation information if approximation used
        Write (nout,*)
        If (approx==1) Then
          Write (nout,*) 'Approximation required'
          Write (nout,*)
          Write (nout,99998) 'RHO = ', rho
          Write (nout,99997) 'EIG = ', eig(1:3)
          Write (nout,99999) 'ICOUNT = ', icount
        Else
          Write (nout,*) 'Approximation not required'
        End If

        Return

99999   Format (1X,A,I7)
99998   Format (1X,A,F10.5)
99997   Format (1X,A,3(F10.5,1X))

      End Subroutine display_embedding_results

      Subroutine initialize_state(state)

!       .. Use Statements ..
        Use nag_library, Only: g05kff
!       .. Implicit None Statement ..
        Implicit None
!       .. Parameters ..
        Integer, Parameter             :: genid = 1, inseed = 14965,           &
                                          lseed = 1, subid = 1
!       .. Array Arguments ..
        Integer, Intent (Out)          :: state(lenst)
!       .. Local Scalars ..
        Integer                        :: ifail, lstate
!       .. Local Arrays ..
        Integer                        :: seed(lseed)
!       .. Executable Statements ..
!       Initialize the generator to a repeatable sequence
        lstate = lenst
        seed(1) = inseed
        ifail = 0
        Call g05kff(genid,subid,seed,lseed,state,lstate,ifail)

      End Subroutine initialize_state

      Subroutine display_realizations(ns,s,xx,z)

!       .. Use Statements ..
        Use nag_library, Only: x04cbf
!       .. Implicit None Statement ..
        Implicit None
!       .. Parameters ..
        Integer, Parameter             :: indent = 0, ncols = 80
        Character (1), Parameter       :: charlab = 'C', intlab = 'I',         &
                                          matrix = 'G', unit = 'n'
        Character (5), Parameter       :: form = 'F10.5'
!       .. Scalar Arguments ..
        Integer, Intent (In)           :: ns, s
!       .. Array Arguments ..
        Real (Kind=nag_wp), Intent (In) :: xx(ns), z(ns,s)
!       .. Local Scalars ..
        Integer                        :: i, ifail
        Character (26)                 :: title
!       .. Local Arrays ..
        Character (1)                  :: clabs(0)
        Character (10), Allocatable    :: rlabs(:)
!       .. Executable Statements ..
        Allocate (rlabs(ns))

!       Set row labels to grid points (column label is realization number).
        Do i = 1, ns
          Write (rlabs(i),99999) xx(i)
        End Do

!       Display random field results
        title = 'Random field realizations:'
        Write (nout,*)
        ifail = 0
        Call x04cbf(matrix,unit,ns,s,z,ns,form,title,charlab,rlabs,intlab,     &
          clabs,ncols,indent,ifail)

99999   Format (F10.5)

      End Subroutine display_realizations

    End Program g05zpfe


g05zqfe.f90

!   G05ZQF Example Program Text

!   Mark 26 Release. NAG Copyright 2016.

    Module g05zqfe_mod

!     G05ZQF Example Program Module:
!            Parameters and User-defined Routines

!     .. Use Statements ..
      Use nag_library, Only: nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Accessibility Statements ..
      Private
      Public                           :: cov2
!     .. Parameters ..
      Integer, Parameter, Public       :: even = 1
    Contains
      Subroutine cov2(t1,t2,gamma,iuser,ruser)

!       .. Implicit None Statement ..
        Implicit None
!       .. Scalar Arguments ..
        Real (Kind=nag_wp), Intent (Out) :: gamma
        Real (Kind=nag_wp), Intent (In) :: t1, t2
!       .. Array Arguments ..
        Real (Kind=nag_wp), Intent (Inout) :: ruser(*)
        Integer, Intent (Inout)        :: iuser(*)
!       .. Local Scalars ..
        Real (Kind=nag_wp)             :: l1, l2, nu, rnorm, tl1, tl2
        Integer                        :: norm
!       .. Intrinsic Procedures ..
        Intrinsic                      :: abs, exp, sqrt
!       .. Executable Statements ..
!       Covariance parameters stored in ruser array.
        norm = iuser(1)
        l1 = ruser(1)
        l2 = ruser(2)
        nu = ruser(3)

        tl1 = abs(t1)/l1
        tl2 = abs(t2)/l2
        If (norm==1) Then
          rnorm = tl1 + tl2
        Else If (norm==2) Then
          rnorm = sqrt(tl1**2+tl2**2)
        End If

        gamma = exp(-(rnorm**nu))

        Return

      End Subroutine cov2
    End Module g05zqfe_mod

    Program g05zqfe

!     G05ZQF Example Main Program

!     .. Use Statements ..
      Use nag_library, Only: g05zqf, nag_wp
      Use g05zqfe_mod, Only: cov2, even
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: l1, l2, nu, rho, var, xmax, xmin,    &
                                          ymax, ymin
      Integer                          :: approx, icorr, icount, ifail, norm,  &
                                          pad
!     .. Local Arrays ..
      Real (Kind=nag_wp)               :: eig(3), ruser(3)
      Real (Kind=nag_wp), Allocatable  :: lam(:), xx(:), yy(:)
      Integer                          :: iuser(1), m(2), maxm(2), ns(2)
!     .. Executable Statements ..
      Write (nout,*) 'G05ZQF Example Program Results'
      Write (nout,*)

!     Get problem specifications from data file
      Call read_input_data(norm,l1,l2,nu,var,xmin,xmax,ymin,ymax,ns,maxm,      &
        icorr,pad)

!     Put covariance parameters in communication arrays
      iuser(1) = norm
      ruser(1) = l1
      ruser(2) = l2
      ruser(3) = nu

      Allocate (lam(maxm(1)*maxm(2)),xx(ns(1)),yy(ns(2)))

!     Get square roots of the eigenvalues of the embedding matrix
      ifail = 0
      Call g05zqf(ns,xmin,xmax,ymin,ymax,maxm,var,cov2,even,pad,icorr,lam,xx,  &
        yy,m,approx,rho,icount,eig,iuser,ruser,ifail)

!     Output results
      Call display_results(approx,m,rho,eig,icount,lam)

    Contains
      Subroutine read_input_data(norm,l1,l2,nu,var,xmin,xmax,ymin,ymax,ns,     &
        maxm,icorr,pad)

!       .. Implicit None Statement ..
        Implicit None
!       .. Scalar Arguments ..
        Real (Kind=nag_wp), Intent (Out) :: l1, l2, nu, var, xmax, xmin, ymax, &
                                          ymin
        Integer, Intent (Out)          :: icorr, norm, pad
!       .. Array Arguments ..
        Integer, Intent (Out)          :: maxm(2), ns(2)
!       .. Executable Statements ..
!       Skip heading in data file
        Read (nin,*)

!       Read in norm, l1, l2 and nu for cov2 function
        Read (nin,*) norm, l1, l2, nu

!       Read in variance of random field
        Read (nin,*) var

!       Read in domain endpoints
        Read (nin,*) xmin, xmax
        Read (nin,*) ymin, ymax

!       Read in number of sample points in each direction
        Read (nin,*) ns(1), ns(2)

!       Read in maximum size of embedding matrix
        Read (nin,*) maxm(1), maxm(2)

!       Read in choice of scaling in case of approximation
        Read (nin,*) icorr

!       Read in choice of padding
        Read (nin,*) pad

        Return

      End Subroutine read_input_data

      Subroutine display_results(approx,m,rho,eig,icount,lam)

!       .. Implicit None Statement ..
        Implicit None
!       .. Scalar Arguments ..
        Real (Kind=nag_wp), Intent (In) :: rho
        Integer, Intent (In)           :: approx, icount
!       .. Array Arguments ..
        Real (Kind=nag_wp), Intent (In) :: eig(3)
        Integer, Intent (In)           :: m(2)
        Real (Kind=nag_wp), Intent (In) :: lam(m(1),m(2))
!       .. Local Scalars ..
        Integer                        :: i
!       .. Executable Statements ..
!       Display size of embedding matrix
        Write (nout,*)
        Write (nout,99999) 'Size of embedding matrix = ', m(1)*m(2)

!       Display approximation information if approximation used
        Write (nout,*)
        If (approx==1) Then
          Write (nout,*) 'Approximation required'
          Write (nout,*)
          Write (nout,99998) 'RHO = ', rho
          Write (nout,99997) 'EIG = ', eig(1:3)
          Write (nout,99999) 'ICOUNT = ', icount
        Else
          Write (nout,*) 'Approximation not required'
        End If

!       Display square roots of the eigenvalues of the embedding matrix
        Write (nout,*)
        Write (nout,*) 'Square roots of eigenvalues of embedding matrix:'
        Write (nout,*)
        Do i = 1, m(1)
          Write (nout,99996) lam(i,1:m(2))
        End Do

        Return

99999   Format (1X,A,I7)
99998   Format (1X,A,F10.5)
99997   Format (1X,A,3(F10.5,1X))
99996   Format (1X,8F8.4)

      End Subroutine display_results

    End Program g05zqfe


g05zrfe.f90

!   G05ZRF Example Program Text

!   Mark 26 Release. NAG Copyright 2016.

    Program g05zrfe

!     G05ZRF Example Main Program

!     .. Use Statements ..
      Use nag_library, Only: g05zrf, nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6, npmax = 4
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: rho, var, xmax, xmin, ymax, ymin
      Integer                          :: approx, icorr, icount, icov2, ifail, &
                                          norm, np, pad
!     .. Local Arrays ..
      Real (Kind=nag_wp)               :: eig(3), params(npmax)
      Real (Kind=nag_wp), Allocatable  :: lam(:), xx(:), yy(:)
      Integer                          :: m(2), maxm(2), ns(2)
!     .. Executable Statements ..
      Write (nout,*) 'G05ZRF Example Program Results'
      Write (nout,*)

!     Get problem specifications from data file
      Call read_input_data(icov2,np,params,norm,var,xmin,xmax,ymin,ymax,ns,    &
        maxm,icorr,pad)

      Allocate (lam(maxm(1)*maxm(2)),xx(ns(1)),yy(ns(2)))

!     Get square roots of the eigenvalues of the embedding matrix
      ifail = 0
      Call g05zrf(ns,xmin,xmax,ymin,ymax,maxm,var,icov2,norm,np,params,pad,    &
        icorr,lam,xx,yy,m,approx,rho,icount,eig,ifail)

!     Output results
      Call display_results(approx,m,rho,eig,icount,lam)

    Contains
      Subroutine read_input_data(icov2,np,params,norm,var,xmin,xmax,ymin,ymax, &
        ns,maxm,icorr,pad)

!       .. Implicit None Statement ..
        Implicit None
!       .. Scalar Arguments ..
        Real (Kind=nag_wp), Intent (Out) :: var, xmax, xmin, ymax, ymin
        Integer, Intent (Out)          :: icorr, icov2, norm, np, pad
!       .. Array Arguments ..
        Real (Kind=nag_wp), Intent (Out) :: params(npmax)
        Integer, Intent (Out)          :: maxm(2), ns(2)
!       .. Executable Statements ..
!       Skip heading in data file
        Read (nin,*)

!       Read in covariance function number
        Read (nin,*) icov2

!       Read in number of parameters
        Read (nin,*) np

!       Read in parameters
        If (np>0) Then
          Read (nin,*) params(1:np)
        End If

!       Read in choice of norm to use
        Read (nin,*) norm

!       Read in variance of random field
        Read (nin,*) var

!       Read in domain endpoints
        Read (nin,*) xmin, xmax
        Read (nin,*) ymin, ymax

!       Read in number of sample points
        Read (nin,*) ns(1:2)

!       Read in maximum size of embedding matrix
        Read (nin,*) maxm(1:2)

!       Read in choice of scaling in case of approximation
        Read (nin,*) icorr

!       Read in choice of padding
        Read (nin,*) pad

        Return

      End Subroutine read_input_data

      Subroutine display_results(approx,m,rho,eig,icount,lam)

!       .. Implicit None Statement ..
        Implicit None
!       .. Scalar Arguments ..
        Real (Kind=nag_wp), Intent (In) :: rho
        Integer, Intent (In)           :: approx, icount
!       .. Array Arguments ..
        Real (Kind=nag_wp), Intent (In) :: eig(3)
        Integer, Intent (In)           :: m(2)
        Real (Kind=nag_wp), Intent (In) :: lam(m(1),m(2))
!       .. Local Scalars ..
        Integer                        :: i
!       .. Executable Statements ..
!       Display size of embedding matrix
        Write (nout,*)
        Write (nout,99999) 'Size of embedding matrix = ', m(1)*m(2)

!       Display approximation information if approximation used
        Write (nout,*)
        If (approx==1) Then
          Write (nout,*) 'Approximation required'
          Write (nout,*)
          Write (nout,99998) 'RHO = ', rho
          Write (nout,99997) 'EIG = ', eig(1:3)
          Write (nout,99999) 'ICOUNT = ', icount
        Else
          Write (nout,*) 'Approximation not required'
        End If

!       Display square roots of the eigenvalues of the embedding matrix
        Write (nout,*)
        Write (nout,*) 'Square roots of eigenvalues of embedding matrix:'
        Write (nout,*)
        Do i = 1, m(1)
          Write (nout,99996) lam(i,1:m(2))
        End Do

        Return

99999   Format (1X,A,I7)
99998   Format (1X,A,F10.5)
99997   Format (1X,A,3(F10.5,1X))
99996   Format (1X,8F8.4)

      End Subroutine display_results

    End Program g05zrfe


g05zsfe.f90

!   G05ZSF Example Program Text

!   Mark 26 Release. NAG Copyright 2016.

    Program g05zsfe

!     G05ZSF Example Main Program

!     .. Use Statements ..
      Use nag_library, Only: g05zrf, g05zsf, nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: lenst = 17, nin = 5, nout = 6,       &
                                          npmax = 4
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: rho, var, xmax, xmin, ymax, ymin
      Integer                          :: approx, icorr, icount, icov2, ifail, &
                                          norm, np, pad, s
!     .. Local Arrays ..
      Real (Kind=nag_wp)               :: eig(3), params(npmax)
      Real (Kind=nag_wp), Allocatable  :: lam(:), xx(:), yy(:), z(:,:)
      Integer                          :: m(2), maxm(2), ns(2), state(lenst)
!     .. Executable Statements ..
      Write (nout,*) 'G05ZSF Example Program Results'
      Write (nout,*)
      Flush (nout)

!     Get problem specifications from data file
      Call read_input_data(icov2,np,params,norm,var,xmin,xmax,ymin,ymax,ns,    &
        maxm,icorr,pad,s)

      Allocate (lam(maxm(1)*maxm(2)),xx(ns(1)),yy(ns(2)))

!     Get square roots of the eigenvalues of the embedding matrix
      ifail = 0
      Call g05zrf(ns,xmin,xmax,ymin,ymax,maxm,var,icov2,norm,np,params,pad,    &
        icorr,lam,xx,yy,m,approx,rho,icount,eig,ifail)

      Call display_embedding_results(approx,m,rho,eig,icount)

!     Initialize state array
      Call initialize_state(state)

      Allocate (z(ns(1)*ns(2),s))

!     Compute s random field realizations
      ifail = 0
      Call g05zsf(ns,s,m,lam,rho,state,z,ifail)

      Call display_realizations(ns,s,xx,yy,z)

    Contains
      Subroutine read_input_data(icov2,np,params,norm,var,xmin,xmax,ymin,ymax, &
        ns,maxm,icorr,pad,s)

!       .. Implicit None Statement ..
        Implicit None
!       .. Scalar Arguments ..
        Real (Kind=nag_wp), Intent (Out) :: var, xmax, xmin, ymax, ymin
        Integer, Intent (Out)          :: icorr, icov2, norm, np, pad, s
!       .. Array Arguments ..
        Real (Kind=nag_wp), Intent (Out) :: params(npmax)
        Integer, Intent (Out)          :: maxm(2), ns(2)
!       .. Executable Statements ..
!       Skip heading in data file
        Read (nin,*)

!       Read in covariance function number
        Read (nin,*) icov2

!       Read in number of parameters
        Read (nin,*) np

!       Read in parameters
        If (np>0) Then
          Read (nin,*) params(1:np)
        End If

!       Read in choice of norm to use
        Read (nin,*) norm

!       Read in variance of random field
        Read (nin,*) var

!       Read in domain endpoints
        Read (nin,*) xmin, xmax
        Read (nin,*) ymin, ymax

!       Read in number of sample points
        Read (nin,*) ns(1:2)

!       Read in maximum size of embedding matrix
        Read (nin,*) maxm(1:2)

!       Read in choice of scaling in case of approximation
        Read (nin,*) icorr

!       Read in choice of padding
        Read (nin,*) pad

!       Read in number of realization samples to be generated
        Read (nin,*) s

        Return

      End Subroutine read_input_data

      Subroutine display_embedding_results(approx,m,rho,eig,icount)

!       .. Implicit None Statement ..
        Implicit None
!       .. Scalar Arguments ..
        Real (Kind=nag_wp), Intent (In) :: rho
        Integer, Intent (In)           :: approx, icount
!       .. Array Arguments ..
        Real (Kind=nag_wp), Intent (In) :: eig(3)
        Integer, Intent (In)           :: m(2)
!       .. Executable Statements ..
!       Display size of embedding matrix
        Write (nout,*)
        Write (nout,99999) 'Size of embedding matrix = ', m(1)*m(2)

!       Display approximation information if approximation used
        Write (nout,*)
        If (approx==1) Then
          Write (nout,*) 'Approximation required'
          Write (nout,*)
          Write (nout,99998) 'RHO = ', rho
          Write (nout,99997) 'EIG = ', eig(1:3)
          Write (nout,99999) 'ICOUNT = ', icount
        Else
          Write (nout,*) 'Approximation not required'
        End If

        Return

99999   Format (1X,A,I7)
99998   Format (1X,A,F10.5)
99997   Format (1X,A,3(F10.5,1X))

      End Subroutine display_embedding_results

      Subroutine initialize_state(state)

!       .. Use Statements ..
        Use nag_library, Only: g05kff
!       .. Implicit None Statement ..
        Implicit None
!       .. Parameters ..
        Integer, Parameter             :: genid = 1, inseed = 14965,           &
                                          lseed = 1, subid = 1
!       .. Array Arguments ..
        Integer, Intent (Out)          :: state(lenst)
!       .. Local Scalars ..
        Integer                        :: ifail, lstate
!       .. Local Arrays ..
        Integer                        :: seed(lseed)
!       .. Executable Statements ..
!       Initialize the generator to a repeatable sequence
        lstate = lenst
        seed(1) = inseed
        ifail = 0
        Call g05kff(genid,subid,seed,lseed,state,lstate,ifail)

      End Subroutine initialize_state

      Subroutine display_realizations(ns,s,xx,yy,z)

!       .. Use Statements ..
        Use nag_library, Only: x04cbf
!       .. Implicit None Statement ..
        Implicit None
!       .. Parameters ..
        Integer, Parameter             :: indent = 0, ncols = 80
        Character (1), Parameter       :: charlab = 'C', intlab = 'I',         &
                                          matrix = 'G', unit = 'n'
        Character (5), Parameter       :: form = 'F10.5'
!       .. Scalar Arguments ..
        Integer, Intent (In)           :: s
!       .. Array Arguments ..
        Integer, Intent (In)           :: ns(2)
        Real (Kind=nag_wp), Intent (In) :: xx(ns(1)), yy(ns(2)),               &
                                          z(ns(1)*ns(2),s)
!       .. Local Scalars ..
        Integer                        :: i, ifail, j, nn
        Character (61)                 :: title
!       .. Local Arrays ..
        Character (1)                  :: clabs(0)
        Character (12), Allocatable    :: rlabs(:)
!       .. Executable Statements ..
        nn = ns(1)*ns(2)
        Allocate (rlabs(nn))

!       Set row labels to grid points (column label is realization number).
        Do j = 1, ns(2)
          Do i = 1, ns(1)
            If (i==1) Then
              Write (rlabs((j-1)*ns(1)+i),99999) xx(i), yy(j)
            Else
              Write (rlabs((j-1)*ns(1)+i),99998) xx(i)
            End If
          End Do
        End Do

!       Display random field results
        title = 'Random field realizations (x,y coordinates first):'
        Write (nout,*)
        ifail = 0
        Call x04cbf(matrix,unit,nn,s,z,nn,form,title,charlab,rlabs,intlab,     &
          clabs,ncols,indent,ifail)

99999   Format (2F6.1)
99998   Format (F6.1,5X,'.')

      End Subroutine display_realizations

    End Program g05zsfe


g05ztfe.f90

!   G05ZTF Example Program Text

!   Mark 26 Release. NAG Copyright 2016.

    Program g05ztfe

!     G05ZTF Example Main Program

!     .. Use Statements ..
      Use nag_library, Only: g05znf, g05ztf, nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: lenst = 17, nin = 5, nout = 6,       &
                                          npmax = 4
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: h, rho, var, xmax, xmin
      Integer                          :: approx, icorr, icount, icov1, ifail, &
                                          m, maxm, np, ns, pad, s
!     .. Local Arrays ..
      Real (Kind=nag_wp)               :: eig(3), params(npmax)
      Real (Kind=nag_wp), Allocatable  :: lam(:), xx(:), yy(:), z(:,:)
      Integer                          :: state(lenst)
!     .. Executable Statements ..
      Write (nout,*) 'G05ZTF Example Program Results'
      Write (nout,*)
      Flush (nout)

!     Set fixed problem specifications for simulating fractional Brownian
!     motion.
      icov1 = 14
      np = 2
      xmin = 0.0_nag_wp
      var = 1.0_nag_wp

!     Get other problem specifications from data file
      Call read_input_data(params,xmax,ns,maxm,icorr,pad,s)

      Allocate (lam(maxm),xx(ns))

!     Get square roots of the eigenvalues of the embedding matrix
      ifail = 0
      Call g05znf(ns,xmin,xmax,maxm,var,icov1,np,params,pad,icorr,lam,xx,m,    &
        approx,rho,icount,eig,ifail)

      Call display_embedding_results(approx,m,rho,eig,icount)

!     Initialize state array
      Call initialize_state(state)

      Allocate (yy(ns+1),z(ns+1,s))

!     Computes fractional Brownian motion realizations.
      h = params(1)
      ifail = 0
      Call g05ztf(ns,s,m,xmax,h,lam,rho,state,z,yy,ifail)

      Call display_realizations(ns,s,yy,z)

    Contains
      Subroutine read_input_data(params,xmax,ns,maxm,icorr,pad,s)

!       .. Implicit None Statement ..
        Implicit None
!       .. Scalar Arguments ..
        Real (Kind=nag_wp), Intent (Out) :: xmax
        Integer, Intent (Out)          :: icorr, maxm, ns, pad, s
!       .. Array Arguments ..
        Real (Kind=nag_wp), Intent (Out) :: params(npmax)
!       .. Intrinsic Procedures ..
        Intrinsic                      :: real
!       .. Executable Statements ..
!       Skip heading in data file
        Read (nin,*)

!       Read in the Hurst parameter, H
        Read (nin,*) params(1)

!       Read in domain endpoint
        Read (nin,*) xmax

!       Read in number of sample points
        Read (nin,*) ns

        params(2) = xmax/(real(ns,kind=nag_wp))

!       Read in maximum size of embedding matrix
        Read (nin,*) maxm

!       Read in choice of scaling in case of approximation
        Read (nin,*) icorr

!       Read in choice of padding
        Read (nin,*) pad

!       Read in number of realization samples to be generated
        Read (nin,*) s

        Return

      End Subroutine read_input_data

      Subroutine display_embedding_results(approx,m,rho,eig,icount)

!       .. Implicit None Statement ..
        Implicit None
!       .. Scalar Arguments ..
        Real (Kind=nag_wp), Intent (In) :: rho
        Integer, Intent (In)           :: approx, icount, m
!       .. Array Arguments ..
        Real (Kind=nag_wp), Intent (In) :: eig(3)
!       .. Executable Statements ..
!       Display size of embedding matrix
        Write (nout,*)
        Write (nout,99999) 'Size of embedding matrix = ', m

!       Display approximation information if approximation used
        Write (nout,*)
        If (approx==1) Then
          Write (nout,*) 'Approximation required'
          Write (nout,*)
          Write (nout,99998) 'RHO = ', rho
          Write (nout,99997) 'EIG = ', eig(1:3)
          Write (nout,99999) 'ICOUNT = ', icount
        Else
          Write (nout,*) 'Approximation not required'
        End If

        Return

99999   Format (1X,A,I7)
99998   Format (1X,A,F10.5)
99997   Format (1X,A,3(F10.5,1X))

      End Subroutine display_embedding_results

      Subroutine initialize_state(state)

!       .. Use Statements ..
        Use nag_library, Only: g05kff
!       .. Implicit None Statement ..
        Implicit None
!       .. Parameters ..
        Integer, Parameter             :: genid = 1, inseed = 14965,           &
                                          lseed = 1, subid = 1
!       .. Array Arguments ..
        Integer, Intent (Out)          :: state(lenst)
!       .. Local Scalars ..
        Integer                        :: ifail, lstate
!       .. Local Arrays ..
        Integer                        :: seed(lseed)
!       .. Executable Statements ..
!       Initialize the generator to a repeatable sequence
        lstate = lenst
        seed(1) = inseed
        ifail = 0
        Call g05kff(genid,subid,seed,lseed,state,lstate,ifail)

      End Subroutine initialize_state

      Subroutine display_realizations(ns,s,yy,z)

!       .. Use Statements ..
        Use nag_library, Only: x04cbf
!       .. Implicit None Statement ..
        Implicit None
!       .. Parameters ..
        Integer, Parameter             :: indent = 0, ncols = 80
        Character (1), Parameter       :: charlab = 'C', intlab = 'I',         &
                                          matrix = 'G', unit = 'n'
        Character (5), Parameter       :: form = 'F10.5'
!       .. Scalar Arguments ..
        Integer, Intent (In)           :: ns, s
!       .. Array Arguments ..
        Real (Kind=nag_wp), Intent (In) :: yy(ns+1), z(ns+1,s)
!       .. Local Scalars ..
        Integer                        :: i, ifail
        Character (61)                 :: title
!       .. Local Arrays ..
        Character (1)                  :: clabs(0)
        Character (6), Allocatable     :: rlabs(:)
!       .. Executable Statements ..
        Allocate (rlabs(ns+1))

!       Set row labels to mesh points (column label is realization number).
        Do i = 1, ns + 1
          Write (rlabs(i),99999) yy(i)
        End Do

!       Display random field results
        title =                                                                &
          'Fractional Brownian motion realizations (x coordinate first):'
        Write (nout,*)
        ifail = 0
        Call x04cbf(matrix,unit,ns+1,s,z,ns+1,form,title,charlab,rlabs,intlab, &
          clabs,ncols,indent,ifail)

99999   Format (F6.1)

      End Subroutine display_realizations

    End Program g05ztfe


g07aafe.f90

    Program g07aafe

!     G07AAF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: g07aaf, nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: clevel, phat, pl, pu
      Integer                          :: ifail, k, n
!     .. Intrinsic Procedures ..
      Intrinsic                        :: real
!     .. Executable Statements ..
      Write (nout,*) 'G07AAF Example Program Results'
      Write (nout,*)

!     Skip heading in data file
      Read (nin,*)

!     Display titles
      Write (nout,*) ' Probability    Confidence Interval '
      Write (nout,*)

d_lp: Do
        Read (nin,*,Iostat=ifail) n, k, clevel
        If (ifail/=0) Then
          Exit d_lp
        End If

!       Calculate probability
        phat = real(k,kind=nag_wp)/real(n,kind=nag_wp)

!       Compute probability
        ifail = 0
        Call g07aaf(n,k,clevel,pl,pu,ifail)

!       Display results
        Write (nout,99999) phat, '(', pl, ' ,', pu, ' )'
      End Do d_lp

99999 Format (1X,F10.4,6X,A,F7.4,A,F7.4,A)
    End Program g07aafe


g07abfe.f90

    Program g07abfe

!     G07ABF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: g07abf, nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: clevel, sum, tl, tu, xmean
      Integer                          :: ifail, ifreq, n, num
!     .. Intrinsic Procedures ..
      Intrinsic                        :: real
!     .. Executable Statements ..
      Write (nout,*) 'G07ABF Example Program Results'
      Write (nout,*)

!     Skip heading in data file
      Read (nin,*)

!     Read in counts and frequencies
      sum = 0.0E0_nag_wp
      n = 0
d_lp: Do
        Read (nin,*,Iostat=ifail) num, ifreq
        If (ifail/=0) Then
          Exit d_lp
        End If

!       Calculate sum
        sum = sum + real(num,kind=nag_wp)*real(ifreq,kind=nag_wp)
        n = n + ifreq
      End Do d_lp

!     Estimate Poisson parameter
      xmean = sum/real(n,kind=nag_wp)
      Write (nout,99999) 'The point estimate of the Poisson parameter =',      &
        xmean
      Write (nout,*)

!     Calculate 95% confidence interval
      clevel = 0.95E0_nag_wp
      ifail = 0
      Call g07abf(n,xmean,clevel,tl,tu,ifail)

!     Display CI
      Write (nout,*) '95 percent Confidence Interval for the estimate'
      Write (nout,99998) '(', tl, ' ,', tu, ' )'
      Write (nout,*)

!     Calculate 99% confidence interval
      clevel = 0.99E0_nag_wp
      ifail = 0
      Call g07abf(n,xmean,clevel,tl,tu,ifail)

!     Display CI
      Write (nout,*) '99 percent Confidence Interval for the estimate'
      Write (nout,99998) '(', tl, ' ,', tu, ' )'

99999 Format (1X,A,F7.4)
99998 Format (6X,A,F7.4,A,F7.4,A)
    End Program g07abfe


g07bbfe.f90

    Program g07bbfe

!     G07BBF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: g07bbf, nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: corr, dev, sexmu, sexsig, tol, xmu,  &
                                          xsig
      Integer                          :: i, ifail, maxit, n, nit
      Character (1)                    :: method
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: wk(:), x(:), xc(:)
      Integer, Allocatable             :: ic(:)
      Integer                          :: nobs(4)
!     .. Executable Statements ..
      Write (nout,*) 'G07BBF Example Program Results'
      Write (nout,*)

!     Skip heading in data file
      Read (nin,*)

!     Read in problem size and control parameters
      Read (nin,*) n, method, xmu, xsig, tol, maxit

      Allocate (x(n),xc(n),ic(n),wk(2*n))

!     Read in data
      Read (nin,*)(x(i),xc(i),ic(i),i=1,n)

!     Calculate estimates
      ifail = 0
      Call g07bbf(method,n,x,xc,ic,xmu,xsig,tol,maxit,sexmu,sexsig,corr,dev,   &
        nobs,nit,wk,ifail)

!     Display results
      Write (nout,99999) ' Mean = ', xmu
      Write (nout,99999) ' Standard deviation = ', xsig
      Write (nout,99999) ' Standard error of mean = ', sexmu
      Write (nout,99999) ' Standard error of sigma = ', sexsig
      Write (nout,99999) ' Correlation coefficient = ', corr
      Write (nout,99998) ' Number of right censored observations = ', nobs(1)
      Write (nout,99998) ' Number of left censored observations = ', nobs(2)
      Write (nout,99998) ' Number of interval censored observations = ',       &
        nobs(3)
      Write (nout,99998) ' Number of exactly specified observations = ',       &
        nobs(4)
      Write (nout,99998) ' Number of iterations = ', nit
      Write (nout,99999) ' Log-likelihood = ', dev

99999 Format (1X,A,F8.4)
99998 Format (1X,A,I2)
    End Program g07bbfe


g07befe.f90

    Program g07befe

!     G07BEF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: g07bef, nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: beta, corr, dev, gamma, sebeta,      &
                                          segam, tol
      Integer                          :: ifail, lic, maxit, n, nit
      Character (1)                    :: cens
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: wk(:), x(:)
      Integer, Allocatable             :: ic(:)
!     .. Executable Statements ..
      Write (nout,*) 'G07BEF Example Program Results'
      Write (nout,*)

!     Skip heading in data file
      Read (nin,*)

!     Read in the problem size and control parameters
      Read (nin,*) cens, n, tol, maxit

      If (cens=='N' .Or. cens=='n') Then
        lic = 0
      Else
        lic = n
      End If
      Allocate (x(n),ic(lic),wk(n))

!     Read in data
      Read (nin,*) x(1:n)

!     Read in censor flag if required
      If (lic>0) Then
        Read (nin,*) ic(1:n)
      End If

!     Read in initial estimate of GAMMA
      Read (nin,*) gamma

!     Calculate estimates
      ifail = 0
      Call g07bef(cens,n,x,ic,beta,gamma,tol,maxit,sebeta,segam,corr,dev,nit,  &
        wk,ifail)

!     Display results
      Write (nout,99999) ' BETA  = ', beta, ' Standard error = ', sebeta
      Write (nout,99999) ' GAMMA = ', gamma, ' Standard error = ', segam

99999 Format (1X,2(A,F10.4))
    End Program g07befe


g07bffe.f90

    Program g07bffe

!     G07BFF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: g07bff, nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: beta, ll, xi
      Integer                          :: ifail, n, optopt
!     .. Local Arrays ..
      Real (Kind=nag_wp)               :: asvc(4), obsvc(4)
      Real (Kind=nag_wp), Allocatable  :: y(:)
!     .. Executable Statements ..
      Write (nout,*) 'G07BFF Example Program Results'
      Write (nout,*)

!     Skip header
      Read (nin,*)

!     Read in problem size and control parameters
      Read (nin,*) n, optopt

      Allocate (y(n))

!     Read in data
      Read (nin,*) y(1:n)

!     Calculate the GPD parameter estimates
      ifail = 1
      Call g07bff(n,y,optopt,xi,beta,asvc,obsvc,ll,ifail)
      If (ifail/=0) Then
        If (ifail/=6 .And. ifail/=7 .And. ifail/=8) Then
          Write (*,99997) '** G07BFF returned with IFAIL = ', ifail
          Go To 100
        End If
      End If

!     Display parameter estimates
      Write (nout,*) 'Parameter estimates'
      Write (nout,Fmt=99998) 'xi            ', xi
      Write (nout,Fmt=99998) 'beta          ', beta
      Write (nout,*)

!     Display parameter distribution
      If (optopt>0) Then
        If (ifail==7 .Or. ifail==8) Then
          Write (nout,Fmt=99999) 'Invalid observed distribution'
        Else
          Write (nout,*) 'Observed distribution'
          Write (nout,Fmt=99998) 'Var(xi)         ', obsvc(1)
          Write (nout,Fmt=99998) 'Var(beta)       ', obsvc(4)
          Write (nout,Fmt=99998) 'Covar(xi,beta)  ', obsvc(2)
          Write (nout,Fmt=99998) 'Final log-likelihood:', ll
        End If
        Write (nout,*)

      Else
        If (ifail==6 .Or. ifail==7) Then
          Write (nout,Fmt=99999) 'Invalid asymptotic distribution'
        Else
          Write (nout,*) 'Asymptotic distribution'
          Write (nout,Fmt=99998) 'Var(xi)         ', asvc(1)
          Write (nout,Fmt=99998) 'Var(beta)       ', asvc(4)
          Write (nout,Fmt=99998) 'Covar(xi,beta)  ', asvc(2)
        End If
      End If

100   Continue

99999 Format (1X,A)
99998 Format (1X,A,1X,E14.6)
99997 Format (1X,A,I0)
    End Program g07bffe


g07cafe.f90

    Program g07cafe

!     G07CAF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: g07caf, nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: clevel, df, dl, du, prob, t, xmean,  &
                                          xstd, ymean, ystd
      Integer                          :: ifail, nx, ny
      Character (1)                    :: equal, tail
!     .. Executable Statements ..
      Write (nout,*) 'G07CAF Example Program Results'
      Write (nout,*)

!     Skip heading in data file
      Read (nin,*)

!     Read in the sample sizes, means and standard deviations
      Read (nin,*) nx, xmean, xstd
      Read (nin,*) ny, ymean, ystd

!     Display data
      Write (nout,*) 'Sample X'
      Write (nout,99996) '  Sample size        = ', nx
      Write (nout,99995) '  Mean               =', xmean
      Write (nout,99995) '  Standard deviation =', xstd
      Write (nout,*)
      Write (nout,*) 'Sample Y'
      Write (nout,99996) '  Sample size        = ', ny
      Write (nout,99995) '  Mean               =', ymean
      Write (nout,99995) '  Standard deviation =', ystd

d_lp: Do

!       Read in the type of statistic and CI required
        Read (nin,*,Iostat=ifail) clevel, tail, equal
        If (ifail/=0) Then
          Exit d_lp
        End If

!       Calculate statistic
        ifail = 0
        Call g07caf(tail,equal,nx,ny,xmean,ymean,xstd,ystd,clevel,t,df,prob,   &
          dl,du,ifail)

!       Display results
        Write (nout,*)
        If (equal=='E' .Or. equal=='e') Then
          Write (nout,*) 'Assuming population variances are equal.'
        Else
          Write (nout,*) 'No assumptions about population variances.'
        End If
        Write (nout,*)
        Write (nout,99999) 't test statistic         =  ', t
        Write (nout,99998) 'Degrees of freedom       = ', df
        Write (nout,99997) 'Significance level       =    ', prob
        Write (nout,*)
        Write (nout,99999) 'Difference in means'
        Write (nout,99999) '  Value                  = ', xmean - ymean
        Write (nout,99999) '  Lower confidence limit = ', dl
        Write (nout,99999) '  Upper confidence limit = ', du
        Write (nout,99999) '  Confidence level       = ', clevel
      End Do d_lp

99999 Format (1X,A,F10.4)
99998 Format (1X,A,F8.1)
99997 Format (1X,A,F8.4)
99996 Format (1X,A,I5)
99995 Format (1X,A,E11.4)
    End Program g07cafe


g07dafe.f90

    Program g07dafe

!     G07DAF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: g07daf, nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: xmd, xme, xsd
      Integer                          :: ifail, n
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: x(:), y(:)
!     .. Executable Statements ..
      Write (nout,*) 'G07DAF Example Program Results'
      Write (nout,*)

!     Skip heading in data file
      Read (nin,*)

!     Read in problem size
      Read (nin,*) n

      Allocate (x(n),y(n))

!     Read in data
      Read (nin,*) x(1:n)

!     Calculate robust summaries
      ifail = 0
      Call g07daf(n,x,y,xme,xmd,xsd,ifail)

!     Display results
      Write (nout,*) 'Original Data'
      Write (nout,99999) x(1:n)
      Write (nout,*)
      Write (nout,*) 'Sorted Data'
      Write (nout,99999) y(1:n)
      Write (nout,*)
      Write (nout,99998) 'Median                             = ', xme
      Write (nout,99998) 'Median absolute deviation          = ', xmd
      Write (nout,99998) 'Robust estimate standard deviation = ', xsd

99999 Format (1X,11F7.3)
99998 Format (1X,A,F6.3)
    End Program g07dafe


g07dbfe.f90

    Program g07dbfe

!     G07DBF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: g07dbf, nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: c, dchi, h1, h2, h3, sigma, sigsav,  &
                                          thesav, theta, tol
      Integer                          :: ifail, ipsi, isigma, maxit, n, nit
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: rs(:), wrk(:), x(:)
!     .. Executable Statements ..
      Write (nout,*) 'G07DBF Example Program Results'
      Write (nout,*)

!     Skip heading in data file
      Read (nin,*)

!     Read in the problem size
      Read (nin,*) n

      Allocate (x(n),rs(n),wrk(n))

!     Read in data
      Read (nin,*) x(1:n)

!     Read in details of algorithm to use
      Read (nin,*) ipsi, dchi, maxit
      If (ipsi==2) Then
        Read (nin,*) h1, h2, h3
      End If

!     Display titles
      Write (nout,*) '          Input parameters     Output parameters'
      Write (nout,*) 'ISIGMA   SIGMA   THETA   TOL    SIGMA  THETA'

d_lp: Do
        Read (nin,*,Iostat=ifail) isigma, sigma, theta, tol
        If (ifail/=0) Then
          Exit d_lp
        End If

!       Save the input parameters for later display
        sigsav = sigma
        thesav = theta

!       Compute M-estimates
        ifail = 0
        Call g07dbf(isigma,n,x,ipsi,c,h1,h2,h3,dchi,theta,sigma,maxit,tol,rs,  &
          nit,wrk,ifail)

!       Display results
        Write (nout,99999) isigma, sigsav, thesav, tol, sigma, theta
      End Do d_lp

99999 Format (1X,I3,3X,2F8.4,F7.4,F9.4,F8.4,I4)
    End Program g07dbfe


g07dcfe.f90

!   G07DCF Example Program Text
!   Mark 26 Release. NAG Copyright 2016.

    Module g07dcfe_mod

!     G07DCF Example Program Module:
!            Parameters and User-defined Routines

!     .. Use Statements ..
      Use nag_library, Only: nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Accessibility Statements ..
      Private
      Public                           :: hampels_psi, hubers_chi
!     .. Parameters ..
      Real (Kind=nag_wp), Parameter    :: dchi = 1.5_nag_wp
      Real (Kind=nag_wp), Parameter    :: h1 = 1.5_nag_wp
      Real (Kind=nag_wp), Parameter    :: h2 = 3.0_nag_wp
      Real (Kind=nag_wp), Parameter    :: h3 = 4.5_nag_wp
      Real (Kind=nag_wp), Parameter    :: zero = 0.0_nag_wp
      Integer, Parameter, Public       :: nin = 5, nout = 6
    Contains
      Function hampels_psi(t)
!       Hampel's Piecewise Linear Function.

!       .. Function Return Value ..
        Real (Kind=nag_wp)             :: hampels_psi
!       .. Scalar Arguments ..
        Real (Kind=nag_wp), Intent (In) :: t
!       .. Local Scalars ..
        Real (Kind=nag_wp)             :: abst
!       .. Intrinsic Procedures ..
        Intrinsic                      :: abs, min
!       .. Executable Statements ..
        abst = abs(t)
        If (abst<h3) Then
          If (abst<=h2) Then
            hampels_psi = min(h1,abst)
          Else
            hampels_psi = h1*(h3-abst)/(h3-h2)
          End If
          If (t<zero) Then
            hampels_psi = -hampels_psi
          End If
        Else
          hampels_psi = zero
        End If
        Return
      End Function hampels_psi
      Function hubers_chi(t)
!       Huber's CHI function.

!       .. Function Return Value ..
        Real (Kind=nag_wp)             :: hubers_chi
!       .. Scalar Arguments ..
        Real (Kind=nag_wp), Intent (In) :: t
!       .. Local Scalars ..
        Real (Kind=nag_wp)             :: abst, ps
!       .. Intrinsic Procedures ..
        Intrinsic                      :: abs, min
!       .. Executable Statements ..
        abst = abs(t)
        ps = min(dchi,abst)
        hubers_chi = ps*ps/2.0E0_nag_wp
        Return
      End Function hubers_chi
    End Module g07dcfe_mod
    Program g07dcfe

!     G07DCF Example Main Program

!     .. Use Statements ..
      Use nag_library, Only: g07dcf, nag_wp
      Use g07dcfe_mod, Only: hampels_psi, hubers_chi, nin, nout
!     .. Implicit None Statement ..
      Implicit None
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: beta, sigma, sigsav, thesav, theta,  &
                                          tol
      Integer                          :: ifail, isigma, maxit, n, nit
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: rs(:), wrk(:), x(:)
!     .. Executable Statements ..
      Write (nout,*) 'G07DCF Example Program Results'
      Write (nout,*)

!     Skip heading in data file
      Read (nin,*)

!     Read in the problem size and control parameters
      Read (nin,*) n, beta, maxit

      Allocate (x(n),wrk(n),rs(n))

!     Read in data
      Read (nin,*) x(1:n)

!     Display titles
      Write (nout,*) '          Input parameters     Output parameters'
      Write (nout,*) 'ISIGMA   SIGMA   THETA   TOL    SIGMA  THETA'

d_lp: Do
        Read (nin,*,Iostat=ifail) isigma, sigma, theta, tol
        If (ifail/=0) Then
          Exit d_lp
        End If

!       Save input parameters
        sigsav = sigma
        thesav = theta

!       Compute M-estimates
        ifail = 0
        Call g07dcf(hubers_chi,hampels_psi,isigma,n,x,beta,theta,sigma,maxit,  &
          tol,rs,nit,wrk,ifail)

!       Display results
        Write (nout,99999) isigma, sigsav, thesav, tol, sigma, theta
      End Do d_lp

99999 Format (1X,I3,3X,2F8.4,F7.4,1X,2F8.4)
    End Program g07dcfe


g07ddfe.f90

    Program g07ddfe

!     G07DDF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: g07ddf, nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: alpha, propn, tmean, tvar, wmean,    &
                                          wvar
      Integer                          :: ifail, k, n
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: sx(:), x(:)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: real
!     .. Executable Statements ..
      Write (nout,*) 'G07DDF Example Program Results'
      Write (nout,*)

!     Skip heading in data file
      Read (nin,*)

!     Read in the problem size
      Read (nin,*) n, alpha

      Allocate (x(n),sx(n))

!     Read in data
      Read (nin,*) x(1:n)

!     Trim data
      ifail = 0
      Call g07ddf(n,x,alpha,tmean,wmean,tvar,wvar,k,sx,ifail)

!     Calculate proportion of data cut
      propn = real(k,kind=nag_wp)/real(n,kind=nag_wp)
      propn = 100.0E0_nag_wp - 200.0E0_nag_wp*propn

!     Display results
      Write (nout,99999) 'Statistics from middle ', propn, '% of data'
      Write (nout,*)
      Write (nout,99998) '               Trimmed-mean = ', tmean
      Write (nout,99998) '   Variance of Trimmed-mean = ', tvar
      Write (nout,*)
      Write (nout,99998) '            Winsorized-mean = ', wmean
      Write (nout,99998) 'Variance of Winsorized-mean = ', wvar

99999 Format (1X,A,F6.2,A)
99998 Format (1X,A,F11.4)
    End Program g07ddfe


g07eafe.f90

    Program g07eafe

!     G07EAF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: g07eaf, nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: clevel, estcl, theta, thetal,        &
                                          thetau, wlower, wupper
      Integer                          :: ifail, n
      Character (1)                    :: method
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: wrk(:), x(:)
      Integer, Allocatable             :: iwrk(:)
!     .. Executable Statements ..
      Write (nout,*) 'G07EAF Example Program Results'
      Write (nout,*)

!     Skip heading in data file
      Read (nin,*)

!     Read in problem size and CI level
      Read (nin,*) method, n, clevel

      Allocate (x(n),wrk(4*n),iwrk(3*n))

!     Read in data
      Read (nin,*) x(1:n)

!     Calculate statistics
      ifail = 0
      Call g07eaf(method,n,x,clevel,theta,thetal,thetau,estcl,wlower,wupper,   &
        wrk,iwrk,ifail)

!     Display results
      Write (nout,*) ' Location estimator     Confidence Interval '
      Write (nout,*)
      Write (nout,99999) theta, '(', thetal, ' ,', thetau, ' )'
      Write (nout,*)
      Write (nout,*) ' Corresponding Wilcoxon statistics'
      Write (nout,*)
      Write (nout,99998) 'Lower : ', wlower
      Write (nout,99998) 'Upper : ', wupper

99999 Format (3X,F10.4,12X,A,F7.4,A,F7.4,A)
99998 Format (1X,A,F8.2)
    End Program g07eafe


g07ebfe.f90

    Program g07ebfe

!     G07EBF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: g07ebf, nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: clevel, estcl, theta, thetal,        &
                                          thetau, ulower, uupper
      Integer                          :: ifail, m, n
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: wrk(:), x(:), y(:)
      Integer, Allocatable             :: iwrk(:)
!     .. Executable Statements ..
      Write (nout,*) 'G07EBF Example Program Results'
      Write (nout,*)

!     Skip Heading in data file
      Read (nin,*)

!     Read in problem size and confidence level
      Read (nin,*) n, m, clevel

      Allocate (x(n),y(m),iwrk(3*n),wrk(3*(m+n)))

!     Read in first sample
      Read (nin,*)
      Read (nin,*) x(1:n)

!     Read in second sample
      Read (nin,*)
      Read (nin,*) y(1:m)

!     Calculate statistics
      ifail = 0
      Call g07ebf('Approx',n,x,m,y,clevel,theta,thetal,thetau,estcl,ulower,    &
        uupper,wrk,iwrk,ifail)

!     Display results
      Write (nout,*) ' Location estimator     Confidence Interval '
      Write (nout,*)
      Write (nout,99999) theta, '(', thetal, ' ,', thetau, ' )'
      Write (nout,*)
      Write (nout,*) ' Corresponding Mann-Whitney U statistics'
      Write (nout,*)
      Write (nout,99998) 'Lower : ', ulower
      Write (nout,99998) 'Upper : ', uupper

99999 Format (3X,F10.4,12X,A,F7.4,A,F7.4,A)
99998 Format (1X,A,F8.2)
    End Program g07ebfe


g07gafe.f90

    Program g07gafe

!     G07GAF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: g07gaf, nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: mean, var
      Integer                          :: i, ifail, ldiff, n, niout, p
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: diff(:), llamb(:), y(:)
      Integer, Allocatable             :: iout(:)
!     .. Executable Statements ..
      Write (nout,*) 'G07GAF Example Program Results'
      Write (nout,*)

!     Skip heading in data file
      Read (nin,*)

!     Read in the problem size
      Read (nin,*) n, p, ldiff

      Allocate (y(n),iout(n),diff(ldiff),llamb(ldiff))

!     Read in data
      Read (nin,*) y(1:n)

!     Let routine calculate mean and variance
      mean = 0.0E0_nag_wp
      var = 0.0E0_nag_wp

!     Get a list of potential outliers
      ifail = 0
      Call g07gaf(n,p,y,mean,var,iout,niout,ldiff,diff,llamb,ifail)

!     Display results
      Write (nout,*) 'Number of potential outliers:', niout
      If (ldiff>0) Then
        Write (nout,*) '  No.  Index    Value       Diff    ln(lambda^2)'
      Else
        Write (nout,*) '  No.  Index    Value'
      End If
      Do i = 1, niout
        If (i>ldiff) Then
          Write (nout,99999) i, iout(i), y(iout(i))
        Else
          Write (nout,99998) i, iout(i), y(iout(i)), diff(i), llamb(i)
        End If
      End Do

99999 Format (1X,I4,2X,I4,1X,F10.2)
99998 Format (1X,I4,2X,I4,3(1X,F10.2))
    End Program g07gafe


g07gbfe.f90

    Program g07gbfe

!     G07GBF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: g07gbf, nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: e, lx, ux, var1, var2, x
      Integer                          :: ifail, n
      Logical                          :: outlier
!     .. Executable Statements ..
      Write (nout,*) 'G07GBF Example Program Results'
      Write (nout,*)

!     Skip heading in data file
      Read (nin,*)

d_lp: Do
!       Read in the sample size, variances and value to test
        Read (nin,*,Iostat=ifail) n, e, var1, var2
        If (ifail/=0) Then
          Exit d_lp
        End If

!       Check whether E is a potential outlier
        ifail = 0
        outlier = g07gbf(n,e,var1,var2,x,lx,ux,ifail)

!       Display results
        Write (nout,99999) 'Sample size                              :', n
        Write (nout,99998) 'Largest absolute residual (E)            :', e
        Write (nout,99998) 'Variance for whole sample                :', var1
        Write (nout,99998) 'Variance excluding E                     :', var2
        Write (nout,99998) 'Estimate for cutoff (X)                  :', x
        Write (nout,99998) 'Lower limit for cutoff (LX)              :', lx
        Write (nout,99998) 'Upper limit for cutoff (UX)              :', ux
        If (outlier) Then
          Write (nout,*) 'E is a potential outlier'
        Else
          Write (nout,*) 'E does not appear to be an outlier'
        End If
        Write (nout,*)
      End Do d_lp

99999 Format (1X,A,1X,I10)
99998 Format (1X,A,1X,F10.3)
    End Program g07gbfe


g08aafe.f90

    Program g08aafe

!     G08AAF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: g08aaf, nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: p
      Integer                          :: ifail, isgn, n, n1
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: x(:), y(:)
!     .. Executable Statements ..
      Write (nout,*) 'G08AAF Example Program Results'
      Write (nout,*)

!     Skip heading in data file
      Read (nin,*)

!     Read in problem size
      Read (nin,*) n

      Allocate (x(n),y(n))

!     Read in data
      Read (nin,*) x(1:n)
      Read (nin,*) y(1:n)

!     Display title
      Write (nout,*) 'Sign test'
      Write (nout,*)

!     Display input data
      Write (nout,*) 'Data values'
      Write (nout,*)
      Write (nout,99999) x(1:n)
      Write (nout,99999) y(1:n)

!     Perform the sign test
      ifail = 0
      Call g08aaf(x,y,n,isgn,n1,p,ifail)

!     Display results
      Write (nout,*)
      Write (nout,99998) 'Test statistic   ', isgn
      Write (nout,99998) 'Observations     ', n1
      Write (nout,99997) 'Lower tail prob.', p

99999 Format (4X,20F3.0)
99998 Format (1X,A,I5)
99997 Format (1X,A,F6.3)
    End Program g08aafe


g08acfe.f90

    Program g08acfe

!     G08ACF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: g08acf, nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: p
      Integer                          :: i1, i2, ifail, n, n1
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: w(:), x(:)
!     .. Executable Statements ..
      Write (nout,*) 'G08ACF Example Program Results'
      Write (nout,*)

!     Skip heading in data file
      Read (nin,*)

!     Read in problem size
      Read (nin,*) n, n1

      Allocate (x(n),w(n))

!     Read in data
      Read (nin,*) x(1:n)

!     Display title
      Write (nout,*) 'Median test'
      Write (nout,*)

!     Output data
      Write (nout,*) 'Data values'
      Write (nout,*)
      Write (nout,99999) '    Group 1  ', x(1:n1)
      Write (nout,*)
      Write (nout,99999) '    Group 2  ', x((n1+1):n)

!     Perform median test
      ifail = 0
      Call g08acf(x,n,n1,w,i1,i2,p,ifail)

!     Display results
      Write (nout,*)
      Write (nout,99998) i1, ' scores below median in group 1'
      Write (nout,99998) i2, ' scores below median in group 2'
      Write (nout,*)
      Write (nout,99997) '     Significance  ', p

99999 Format (1X,A,8F4.0,/,(14X,8F4.0))
99998 Format (1X,I6,A)
99997 Format (1X,A,F8.5)
    End Program g08acfe


g08aefe.f90

    Program g08aefe

!     G08AEF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: g08aef, nag_wp, x04caf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: fr, p
      Integer                          :: i, ifail, k, ldx, n
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: w1(:), w2(:), x(:,:)
!     .. Executable Statements ..
      Write (nout,*) 'G08AEF Example Program Results'
      Write (nout,*)

!     Skip heading in data file
      Read (nin,*)

!     Read in the problem size
      Read (nin,*) k, n

      ldx = k
      Allocate (x(ldx,n),w1(k),w2(k))

!     Read in data
      Read (nin,*)(x(i,1:n),i=1,k)

!     Display title
      Write (nout,*) 'Friedman test'
      Write (nout,*)
      Flush (nout)

!     Display input data
      ifail = 0
      Call x04caf('General',' ',k,n,x,ldx,'Data values',ifail)

!     Perform ANOVA
      ifail = 0
      Call g08aef(x,ldx,k,n,w1,w2,fr,p,ifail)

!     Display results
      Write (nout,*)
      Write (nout,99999) 'Test statistic       ', fr
      Write (nout,99998) 'Degrees of freedom   ', k - 1
      Write (nout,99999) 'Significance         ', p

99999 Format (1X,A,F6.3)
99998 Format (1X,A,I6)
    End Program g08aefe


g08affe.f90

    Program g08affe

!     G08AFF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: g08aff, nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: h, p
      Integer                          :: i, ifail, k, lx, nhi, nlo
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: w(:), x(:)
      Integer, Allocatable             :: l(:)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: sum
!     .. Executable Statements ..
      Write (nout,*) 'G08AFF Example Program Results'
      Write (nout,*)

!     Skip heading in data file
      Read (nin,*)

!     Read in problem size
      Read (nin,*) k

      Allocate (l(k))

!     Read in number of observations in each sample
      Read (nin,*) l(1:k)

!     Calculate total number of observations
      lx = sum(l(1:k))

      Allocate (x(lx),w(lx))

!     Read in data
      Read (nin,*) x(1:lx)

!     Display title
      Write (nout,*) 'Kruskal-Wallis test'
      Write (nout,*)

!     Display input data
      Write (nout,*) 'Data values'
      Write (nout,*)
      Write (nout,*) '  Group    Observations'
      nlo = 1
      Do i = 1, k
        nhi = nlo + l(i) - 1
        Write (nout,99999) i, x(nlo:nhi)
        nlo = nlo + l(i)
      End Do

!     Perform ANOVA
      ifail = 0
      Call g08aff(x,lx,l,k,w,h,p,ifail)

!     Display results
      Write (nout,*)
      Write (nout,99998) 'Test statistic       ', h
      Write (nout,99997) 'Degrees of freedom   ', k - 1
      Write (nout,99998) 'Significance         ', p

99999 Format (1X,I5,5X,10F4.0)
99998 Format (1X,A,F9.3)
99997 Format (1X,A,I9)
    End Program g08affe


g08agfe.f90

    Program g08agfe

!     G08AGF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: g08agf, nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: p, w, wnor, xme
      Integer                          :: ifail, n, n1
      Character (1)                    :: tail, zer
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: wrk(:), x(:), y(:), z(:)
!     .. Executable Statements ..
      Write (nout,*) 'G08AGF Example Program Results'
      Write (nout,*)

!     Skip heading in data file
      Read (nin,*)

!     Read in the problem size, median test value and details of
!     test to perform
      Read (nin,*) n, xme, tail, zer

      Allocate (x(n),y(n),z(n),wrk(3*n))

!     Read in data
      Read (nin,*) x(1:n)
      Read (nin,*) y(1:n)

!     Display title
      Write (nout,*) 'Wilcoxon one sample signed ranks test'
      Write (nout,*)

!     Display input data
      Write (nout,*) 'Data values'
      Write (nout,99999) x(1:n)
      Write (nout,99999) y(1:n)

!     Calculate difference
      z(1:n) = x(1:n) - y(1:n)

!     Perform test
      ifail = 0
      Call g08agf(n,z,xme,tail,zer,w,wnor,p,n1,wrk,ifail)

!     Display results
      Write (nout,*)
      Write (nout,99998) 'Test statistic            = ', w
      Write (nout,99998) 'Normalized test statistic = ', wnor
      Write (nout,99997) 'Degrees of freedom        = ', n1
      Write (nout,99998) 'Two tail probability      = ', p

99999 Format (4X,8F5.1)
99998 Format (1X,A,F8.4)
99997 Format (1X,A,I8)
    End Program g08agfe


g08ahfe.f90

    Program g08ahfe

!     G08AHF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: g08ahf, g08ajf, g08akf, nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: p, pexact, u, unor
      Integer                          :: ifail, liwrk, lwrk, lwrk1, lwrk2,    &
                                          lwrk3, mn, n1, n2, nsum
      Logical                          :: ties
      Character (1)                    :: tail
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: ranks(:), wrk(:), x(:), y(:)
      Integer, Allocatable             :: iwrk(:)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: int, max, min
!     .. Executable Statements ..
      Write (nout,*) 'G08AHF Example Program Results'
      Write (nout,*)

!     Skip heading in data file
      Read (nin,*)

!     Read in problem size
      Read (nin,*) n1, n2, tail

!     Calculate sizes of various workspaces
      nsum = n1 + n2
      mn = min(n1,n2)

!     Workspace for G08AHF
      lwrk1 = nsum

!     Workspace for G08AJF
      lwrk2 = int(n1*n2/2) + 1

!     Workspace for G08AKF
      lwrk3 = mn + mn*(mn+1)*nsum - mn*(mn+1)*(2*mn+1)/3 + 1
      liwrk = 2*nsum + 2

      lwrk = max(lwrk1,lwrk2,lwrk3)
      Allocate (x(n1),y(n2),ranks(nsum),wrk(lwrk),iwrk(liwrk))

!     Read in data
      Read (nin,*) x(1:n1)
      Read (nin,*) y(1:n2)

!     Display title
      Write (nout,*) 'Mann-Whitney U test'
      Write (nout,*)

!     Display input data
      Write (nout,99999) 'Sample size of group 1 = ', n1
      Write (nout,99999) 'Sample size of group 2 = ', n2
      Write (nout,*)
      Write (nout,*) 'Data values'
      Write (nout,*)
      Write (nout,99998) '    Group 1  ', x(1:n1)
      Write (nout,*)
      Write (nout,99998) '    Group 2  ', y(1:n2)

!     Perform test
      ifail = 0
      Call g08ahf(n1,x,n2,y,tail,u,unor,p,ties,ranks,wrk,ifail)

!     Calculate exact probabilities
      If (.Not. ties) Then
        ifail = 0
        Call g08ajf(n1,n2,tail,u,pexact,wrk,lwrk,ifail)

      Else
        ifail = 0
        Call g08akf(n1,n2,tail,ranks,u,pexact,wrk,lwrk,iwrk,ifail)
      End If

!     Display results
      Write (nout,*)
      Write (nout,99997) 'Test statistic           = ', u
      Write (nout,99997) 'Normal Statistic         = ', unor
      Write (nout,99997) 'Approx. tail probability = ', p
      Write (nout,*)
      If (ties) Then
        Write (nout,*) 'There are ties in the pooled sample'
      Else
        Write (nout,*) 'There are no ties in the pooled sample'
      End If
      Write (nout,*)
      Write (nout,99997) 'Exact tail probability   = ', pexact

99999 Format (1X,A,I5)
99998 Format (1X,A,8F5.1,2(/,14X,8F5.1))
99997 Format (1X,A,F10.4)
    End Program g08ahfe


g08ajfe.f90

    Program g08ajfe

!     G08AJF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: g08ahf, g08ajf, nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: p, pexact, u, unor
      Integer                          :: ifail, lwrk, lwrk1, lwrk2, n1, n2,   &
                                          nsum
      Logical                          :: ties
      Character (1)                    :: tail
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: ranks(:), wrk(:), x(:), y(:)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: int, max
!     .. Executable Statements ..
      Write (nout,*) 'G08AJF Example Program Results'
      Write (nout,*)

!     Skip heading in data file
      Read (nin,*)

!     Read in problem size
      Read (nin,*) n1, n2, tail

!     Calculate sizes of various workspaces
      nsum = n1 + n2

!     Workspace for G08AHF
      lwrk1 = nsum

!     Workspace for G08AJF
      lwrk2 = int(n1*n2/2) + 1

      lwrk = max(lwrk1,lwrk2)
      Allocate (x(n1),y(n2),ranks(nsum),wrk(lwrk))

!     Read in data
      Read (nin,*) x(1:n1)
      Read (nin,*) y(1:n2)

!     Display title
      Write (nout,*) 'Mann-Whitney U test'
      Write (nout,*)

!     Display input data
      Write (nout,99999) 'Sample size of group 1 = ', n1
      Write (nout,99999) 'Sample size of group 2 = ', n2
      Write (nout,*)
      Write (nout,*) 'Data values'
      Write (nout,*)
      Write (nout,99998) '    Group 1  ', x(1:n1)
      Write (nout,*)
      Write (nout,99998) '    Group 2  ', y(1:n2)

!     Perform test
      ifail = 0
      Call g08ahf(n1,x,n2,y,tail,u,unor,p,ties,ranks,wrk,ifail)

!     Calculate exact probabilities
      If (.Not. ties) Then
        ifail = 0
        Call g08ajf(n1,n2,tail,u,pexact,wrk,lwrk,ifail)
      End If

!     Display results
      Write (nout,*)
      Write (nout,99997) 'Test statistic     = ', u
      Write (nout,99997) 'Normal statistic   = ', unor
      Write (nout,99997) 'Tail probability   = ', p
      Write (nout,*)
      If (.Not. ties) Then
        Write (nout,99997) 'Exact tail probability = ', pexact
      Else
        Write (nout,*)                                                         &
          'There are ties in the pooled sample so G08AJF was not called.'
      End If

99999 Format (1X,A,I5)
99998 Format (1X,A,8F5.1,2(/,14X,8F5.1))
99997 Format (1X,A,F10.4)
    End Program g08ajfe


g08akfe.f90

    Program g08akfe

!     G08AKF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: g08ahf, g08akf, nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: p, pexact, u, unor
      Integer                          :: ifail, liwrk, lwrk, lwrk1, lwrk2,    &
                                          mn, n1, n2, nsum
      Logical                          :: ties
      Character (1)                    :: tail
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: ranks(:), wrk(:), x(:), y(:)
      Integer, Allocatable             :: iwrk(:)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: max, min
!     .. Executable Statements ..
      Write (nout,*) 'G08AKF Example Program Results'
      Write (nout,*)

!     Skip heading in data file
      Read (nin,*)

!     Read in problem size
      Read (nin,*) n1, n2, tail

!     Calculate sizes of various workspaces
      nsum = n1 + n2
      mn = min(n1,n2)

!     Workspace for G08AHF
      lwrk1 = nsum

!     Workspace for G08AKF
      lwrk2 = mn + mn*(mn+1)*nsum - mn*(mn+1)*(2*mn+1)/3 + 1
      liwrk = 2*nsum + 2

      lwrk = max(lwrk1,lwrk2)
      Allocate (x(n1),y(n2),ranks(nsum),wrk(lwrk),iwrk(liwrk))

!     Read in data
      Read (nin,*) x(1:n1)
      Read (nin,*) y(1:n2)

!     Display title
      Write (nout,*) 'Mann-Whitney U test'
      Write (nout,*)

!     Display input data
      Write (nout,99999) 'Sample size of group 1 = ', n1
      Write (nout,99999) 'Sample size of group 2 = ', n2
      Write (nout,*)
      Write (nout,*) 'Data values'
      Write (nout,*)
      Write (nout,99998) '    Group 1  ', x(1:n1)
      Write (nout,*)
      Write (nout,99998) '    Group 2  ', y(1:n2)

!     Perform test
      ifail = 0
      Call g08ahf(n1,x,n2,y,tail,u,unor,p,ties,ranks,wrk,ifail)

!     Calculate exact probabilities
      If (ties) Then
        ifail = 0
        Call g08akf(n1,n2,tail,ranks,u,pexact,wrk,lwrk,iwrk,ifail)
      End If

!     Display results
      Write (nout,*)
      Write (nout,99997) 'Test statistic     = ', u
      Write (nout,99997) 'Normal statistic   = ', unor
      Write (nout,99997) 'Tail probability   = ', p
      Write (nout,*)
      If (ties) Then
        Write (nout,*)
        Write (nout,*) 'Ranks'
        Write (nout,*)
        Write (nout,99998) '    Group 1  ', ranks(1:n1)
        Write (nout,*)
        Write (nout,99998) '    Group 2  ', ranks((n1+1):nsum)
        Write (nout,*)
        Write (nout,*)
        Write (nout,99997) 'Exact tail probability = ', pexact
      Else
        Write (nout,*)                                                         &
          'There are no ties in the pooled sample so G08AKF was not called.'
      End If

99999 Format (1X,A,I5)
99998 Format (1X,A,8F5.1,2(/,14X,8F5.1))
99997 Format (1X,A,F10.4)
    End Program g08akfe


g08alfe.f90

    Program g08alfe

!     G08ALF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: g08alf, nag_wp, x04caf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: df, prob, q
      Integer                          :: i, ifail, k, ldx, n
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: x(:,:)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: real
!     .. Executable Statements ..
      Write (nout,*) 'G08ALF Example Program Results'
      Write (nout,*)

!     Skip heading in data file
      Read (nin,*)

!     Read in the problem size
      Read (nin,*) n, k

      ldx = n
      Allocate (x(ldx,k))

!     Read in the data
      Read (nin,*)(x(i,1:k),i=1,n)

!     Display title
      Write (nout,*) 'Cochrans Q test'
      Write (nout,*)
      Flush (nout)

!     Display the input data
      ifail = 0
      Call x04caf('General',' ',n,k,x,ldx,'Data matrix',ifail)

!     Perform test
      ifail = 0
      Call g08alf(n,k,x,ldx,q,prob,ifail)

!     Display results
      df = real(k-1,kind=nag_wp)
      Write (nout,*)
      Write (nout,99999) 'Cochrans Q test statistic = ', q
      Write (nout,99998) 'Degrees of freedom = ', df
      Write (nout,99999) 'Upper-tail probability = ', prob

99999 Format (1X,A,F12.4)
99998 Format (1X,A,F6.1)
    End Program g08alfe


g08bafe.f90

    Program g08bafe

!     G08BAF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: g08baf, nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: pv, pw, v, w
      Integer                          :: ifail, itest, n, n1
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: r(:), x(:)
!     .. Executable Statements ..
      Write (nout,*) 'G08BAF Example Program Results'
      Write (nout,*)

!     Skip heading in data file
      Read (nin,*)

!     Read in problem size and type of test
      Read (nin,*) n, n1, itest

      Allocate (x(n),r(n))

!     Read in data
      Read (nin,*) x(1:n)

!     Display title
      Write (nout,*) 'Mood''s test and David''s test'
      Write (nout,*)

!     Display input data
      Write (nout,*) 'Data values'
      Write (nout,*)
      Write (nout,*) 'Group 1  '
      Write (nout,99999) x(1:n1)
      Write (nout,*)
      Write (nout,*) 'Group 2  '
      Write (nout,99999) x((n1+1):n)

!     Perform test
      ifail = 0
      Call g08baf(x,n,n1,r,itest,w,v,pw,pv,ifail)

!     Display results
      Write (nout,*)
      Write (nout,99998) '    Mood''s measure  = ', w, '   Significance = ',   &
        pw
      Write (nout,99998) '    David''s measure = ', v, '   Significance = ',   &
        pv

99999 Format (1X,8F4.0)
99998 Format (1X,A,F8.3,A,F8.4)
    End Program g08bafe


g08cbfe.f90

    Program g08cbfe

!     G08CBF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: g08cbf, nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: d, p, z
      Integer                          :: ifail, n, npar, ntype
      Character (2)                    :: dist
      Character (1)                    :: estima
!     .. Local Arrays ..
      Real (Kind=nag_wp)               :: par(2)
      Real (Kind=nag_wp), Allocatable  :: sx(:), x(:)
!     .. Executable Statements ..
      Write (nout,*) 'G08CBF Example Program Results'
      Write (nout,*)

!     Skip heading in data file
      Read (nin,*)

!     Read in problem size and the statistic to calculate
      Read (nin,*) n, ntype

      Allocate (x(n),sx(n))

!     Read in data
      Read (nin,*) x(1:n)

!     Read in information on the distribution to test against
      Read (nin,*) dist, estima

      Select Case (dist)
      Case ('P','p','E','e')
        npar = 1
      Case Default
        npar = 2
      End Select

!     Read in the distribution parameters if required
!     otherwise they are estimated from the data by G08CBF
!     and PAR need not be set
      If (estima=='S' .Or. estima=='s') Then
        Read (nin,*) par(1:npar)
      Else If (dist=='B' .Or. dist=='b' .Or. dist=='NB' .Or. dist=='nb') Then
!       Read in M for the binomial distribution
        Read (nin,*) par(1)
      End If

!     Perform K-S test
      ifail = 0
      Call g08cbf(n,x,dist,par,estima,ntype,d,z,p,sx,ifail)

!     Display results
      Write (nout,*) 'K-S Test'
      Write (nout,*) 'Distribution: ', dist
      Write (nout,99999) 'Parameters  : ', par(1:npar)
      Write (nout,*)
      Write (nout,99999) 'Test statistic D = ', d
      Write (nout,99999) 'Z statistic      = ', z
      Write (nout,99999) 'Tail probability = ', p

99999 Format (1X,A,2F8.4)
    End Program g08cbfe


g08ccfe.f90

!   G08CCF Example Program Text
!   Mark 26 Release. NAG Copyright 2016.

    Module g08ccfe_mod

!     G08CCF Example Program Module:
!            Parameters and User-defined Routines

!     .. Use Statements ..
      Use nag_library, Only: nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Accessibility Statements ..
      Private
      Public                           :: user_cdf
!     .. Parameters ..
      Real (Kind=nag_wp), Parameter    :: std = 0.5_nag_wp
      Real (Kind=nag_wp), Parameter    :: xmean = 0.75_nag_wp
      Integer, Parameter, Public       :: nin = 5, nout = 6
    Contains
      Function user_cdf(x)
!       Cumulative distribution function for the user supplied distribution.
!       In this example, the distribution is the normal distribution, with
!       mean = 0.75 and standard deviation = 0.5

!       .. Use Statements ..
        Use nag_library, Only: s15abf
!       .. Function Return Value ..
        Real (Kind=nag_wp)             :: user_cdf
!       .. Scalar Arguments ..
        Real (Kind=nag_wp), Intent (In) :: x
!       .. Local Scalars ..
        Real (Kind=nag_wp)             :: z
        Integer                        :: ifail
!       .. Executable Statements ..
        z = (x-xmean)/std
        ifail = -1
        user_cdf = s15abf(z,ifail)
        Return
      End Function user_cdf
    End Module g08ccfe_mod
    Program g08ccfe

!     G08CCF Example Main Program

!     .. Use Statements ..
      Use nag_library, Only: g08ccf, nag_wp
      Use g08ccfe_mod, Only: nin, nout, user_cdf
!     .. Implicit None Statement ..
      Implicit None
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: d, p, z
      Integer                          :: ifail, n, ntype
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: sx(:), x(:)
!     .. Executable Statements ..
      Write (nout,*) 'G08CCF Example Program Results'
      Write (nout,*)

!     Skip heading in data file
      Read (nin,*)

!     Read in problem type and required statistic
      Read (nin,*) n, ntype

      Allocate (x(n),sx(n))

!     Read in data
      Read (nin,*) x(1:n)

!     Perform K-S test for user specified distribution
      ifail = 0
      Call g08ccf(n,x,user_cdf,ntype,d,z,p,sx,ifail)

!     Display results
      Write (nout,*) 'Test against normal distribution with mean = 0.75'
      Write (nout,*) 'and standard deviation = 0.5.'
      Write (nout,*)
      Write (nout,99999) 'Test statistic D = ', d
      Write (nout,99999) 'Z statistic      = ', z
      Write (nout,99999) 'Tail probability = ', p

99999 Format (1X,A,F8.4)
    End Program g08ccfe


g08cdfe.f90

    Program g08cdfe

!     G08CDF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: g08cdf, nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: d, p, z
      Integer                          :: ifail, n1, n2, ntype
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: sx(:), sy(:), x(:), y(:)
!     .. Executable Statements ..
      Write (nout,*) 'G08CDF Example Program Results'
      Write (nout,*)

!     Skip heading in data file
      Read (nin,*)

!     Read in the problem size and statistic type
      Read (nin,*) n1, n2, ntype

      Allocate (x(n1),y(n2),sx(n1),sy(n2))

!     Read in data
      Read (nin,*) x(1:n1)
      Read (nin,*) y(1:n2)

!     Perform test
      ifail = 0
      Call g08cdf(n1,x,n2,y,ntype,d,z,p,sx,sy,ifail)

!     Display results
      Write (nout,99999) 'Test statistic D = ', d
      Write (nout,99999) 'Z statistic      = ', z
      Write (nout,99999) 'Tail probability = ', p

99999 Format (1X,A,F8.4)
    End Program g08cdfe


g08cgfe.f90

    Program g08cgfe

!     G08CGF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: g01aef, g08cgf, nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: chisq, p, xmax, xmin
      Integer                          :: iclass, ifail, n, nclass, ndf, npar, &
                                          npest
      Character (1)                    :: dist
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: cb(:), chisqi(:), eval(:), prob(:),  &
                                          x(:)
      Real (Kind=nag_wp)               :: par(2)
      Integer, Allocatable             :: ifreq(:)
!     .. Executable Statements ..
      Write (nout,*) 'G08CGF Example Program Results'
      Write (nout,*)

!     Skip heading in data file
      Read (nin,*)

!     Read in problem size
      Read (nin,*) n

!     Read in class information
      Read (nin,*) nclass, iclass

      Allocate (x(n),cb(nclass),ifreq(nclass),prob(nclass),eval(nclass),       &
        chisqi(nclass))

!     Read in data
      Read (nin,*) x(1:n)

!     Read in the class boundaries, if supplied
      If (iclass==1) Then
        Read (nin,*) cb(1:(nclass-1))
      End If

!     Read in information on the distribution to test against
      Read (nin,*) dist, npest

      Select Case (dist)
      Case ('A','a')
        npar = 0
      Case ('E','e','C','c')
        npar = 1
      Case Default
        npar = 2
      End Select

!     Read in the distribution parameters or probabilities
      If (npar==0) Then
        Read (nin,*) prob(1:nclass)
      Else
        Read (nin,*) par(1:npar)
      End If

!     Produce frequency table for data
      ifail = 0
      Call g01aef(n,nclass,x,iclass,cb,ifreq,xmin,xmax,ifail)

!     Perform chi-squared test
      ifail = -1
      Call g08cgf(nclass,ifreq,cb,dist,par,npest,prob,chisq,p,ndf,eval,chisqi, &
        ifail)
      If (ifail/=0) Then
        If (ifail<=9) Then
          Go To 100
        End If
      End If

!     Display results
      Write (nout,99999) 'Chi-squared test statistic   = ', chisq
      Write (nout,99998) 'Degrees of freedom.          = ', ndf
      Write (nout,99999) 'Significance level           = ', p
      Write (nout,*)
      Write (nout,*) 'The contributions to the test statistic are :-'
      Write (nout,99997) chisqi(1:nclass)

100   Continue

99999 Format (1X,A,F10.4)
99998 Format (1X,A,I5)
99997 Format (1X,F10.4)
    End Program g08cgfe


g08chfe.f90

    Program g08chfe

!     G08CHF Example Program Text
!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: g05kff, g05sff, g08chf, nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: genid = 1, lseed = 1, mstate = 17,   &
                                          nin = 5, nout = 6, subid = -1
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: a2, aa2, beta, nupper, p, sa2, sbeta
      Integer                          :: i, ifail, j, k, lstate, n, nsim,     &
                                          n_pseudo
      Logical                          :: issort
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: x(:), xsim(:), y(:)
      Integer                          :: seed(lseed), state(17)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: exp, real, sum
!     .. Executable Statements ..
      Write (nout,*) 'G08CHF Example Program Results'
      Write (nout,*)

!     Skip heading in data file
      Read (nin,*)

!     Read number of observations
      Read (nin,*) n

!     Memory allocation
      Allocate (x(n),y(n))

!     Read observations
      Read (nin,*)(x(i),i=1,n)

!     Maximum likelihood estimate of mean
      beta = sum(x(1:n))/real(n,kind=nag_wp)

!     PIT, using exponential CDF with mean beta
      Do i = 1, n
        y(i) = 1.0E0_nag_wp - exp(-x(i)/beta)
      End Do

!     Let g08chf sort the (approximately) uniform variates
      issort = .False.

!     Calculate A-squared
      ifail = 0
      a2 = g08chf(n,issort,y,ifail)
      aa2 = (1.0E0_nag_wp+0.6E0_nag_wp/real(n,kind=nag_wp))*a2

!     Number of simulations
      nsim = 888

!     Generate exponential variates using a repeatable seed
      Allocate (xsim(n*nsim))
      seed(1) = 206033
      lstate = mstate
      ifail = 0
      Call g05kff(genid,subid,seed,lseed,state,lstate,ifail)
      n_pseudo = n*nsim
      ifail = 0
      Call g05sff(n_pseudo,beta,state,xsim,ifail)

!     Simulations loop
      nupper = 0.0E0_nag_wp
      Do j = 1, nsim
        k = (j-1)*n
!       Maximum likelihood estimate of mean
        sbeta = sum(xsim(k+1:k+n))/real(n,kind=nag_wp)
!       PIT
        Do i = 1, n
          y(i) = 1.0E0_nag_wp - exp(-xsim(k+i)/sbeta)
        End Do
!       Calculate A-squared
        ifail = 0
        sa2 = g08chf(n,issort,y,ifail)
        If (sa2>aa2) Then
          nupper = nupper + 1.0E0_nag_wp
        End If
      End Do

!     Simulated upper tail probability value
      p = nupper/real(nsim+1,kind=nag_wp)

!     Results
      Write (nout,'(1X,A,E11.4)')                                              &
        'H0: data from exponential distribution with mean', beta
      Write (nout,'(1X,A,1X,F8.4)') 'Test statistic, A-squared: ', a2
      Write (nout,'(1X,A,1X,F8.4)') 'Upper tail probability:    ', p

    End Program g08chfe


g08cjfe.f90

    Program g08cjfe

!     G08CJF Example Program Text
!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: g08cjf, nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: a2, mu, p
      Integer                          :: i, ifail, n
      Logical                          :: issort
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: x(:), y(:)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: exp
!     .. Executable Statements ..
      Write (nout,*) 'G08CJF Example Program Results'
      Write (nout,*)

!     Skip heading in data file
      Read (nin,*)

!     Read number of observations and parameter value
      Read (nin,*) n, mu

!     Memory allocation
      Allocate (x(n),y(n))

!     Read observations
      Read (nin,*)(x(i),i=1,n)

!     PIT
      Do i = 1, n
        y(i) = 1.0E0_nag_wp - exp(-x(i)/mu)
      End Do

!     Let g08cjf sort the uniform variates
      issort = .False.

!     Calculate A-squared and probability
      ifail = 0
      Call g08cjf(n,issort,y,a2,p,ifail)

!     Results
      Write (nout,'(1X,A,E11.4)')                                              &
        'H0: data from exponential distribution with mean', mu
      Write (nout,'(1X,A,1X,F8.4)') 'Test statistic, A-squared: ', a2
      Write (nout,'(1X,A,1X,F8.4)') 'Upper tail probability:    ', p

    End Program g08cjfe


g08ckfe.f90

    Program g08ckfe

!     G08CKF Example Program Text
!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: g08ckf, nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: a2, aa2, p, ybar, yvar
      Integer                          :: i, ifail, n
      Logical                          :: issort
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: y(:)
!     .. Executable Statements ..
      Write (nout,*) 'G08CKF Example Program Results'
      Write (nout,*)

!     Skip heading in data file
      Read (nin,*)

!     Read number of observations
      Read (nin,*) n

!     Memory allocation
      Allocate (y(n))

!     Read observations
      Read (nin,*)(y(i),i=1,n)

!     Let g08ckf sort the data
      issort = .False.

!     Calculate A-squared and probability
      ifail = 0
      Call g08ckf(n,issort,y,ybar,yvar,a2,aa2,p,ifail)

!     Results
      Write (nout,'(1X,A,E11.4,1X,A,E11.4)')                                   &
        'H0: data from Normal distribution with mean', ybar, 'and variance',   &
        yvar
      Write (nout,'(1X,A,1X,F8.4)') 'Test statistic, A-squared: ', a2
      Write (nout,'(1X,A,1X,F8.4)') 'Adjusted A-squared:        ', aa2
      Write (nout,'(1X,A,1X,F8.4)') 'Upper tail probability:    ', p

    End Program g08ckfe


g08clfe.f90

    Program g08clfe

!     G08CLF Example Program Text
!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: g08clf, nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: a2, aa2, p, ybar
      Integer                          :: i, ifail, n
      Logical                          :: issort
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: y(:)
!     .. Executable Statements ..
      Write (nout,*) 'G08CLF Example Program Results'
      Write (nout,*)

!     Skip heading in data file
      Read (nin,*)

!     Read number of observations
      Read (nin,*) n

!     Memory allocation
      Allocate (y(n))

!     Read observations
      Read (nin,*)(y(i),i=1,n)

!     Let g08clf sort the data
      issort = .False.

!     Calculate A-squared and probability
      ifail = 0
      Call g08clf(n,issort,y,ybar,a2,aa2,p,ifail)

!     Results
      Write (nout,'(1X,A,E11.4)')                                              &
        'H0: data from exponential distribution with mean', ybar
      Write (nout,'(1X,A,1X,F8.4)') 'Test statistic, A-squared: ', a2
      Write (nout,'(1X,A,1X,F8.4)') 'Adjusted A-squared:        ', aa2
      Write (nout,'(1X,A,1X,F8.4)') 'Upper tail probability:    ', p

    End Program g08clfe


g08dafe.f90

    Program g08dafe

!     G08DAF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: g08daf, nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: p, w
      Integer                          :: i, ifail, k, ldx, n
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: rnk(:,:), x(:,:)
!     .. Executable Statements ..
      Write (nout,*) 'G08DAF Example Program Results'
      Write (nout,*)

!     Skip heading in data file
      Read (nin,*)

!     Read in the problem size
      Read (nin,*) k, n

      ldx = k
      Allocate (x(ldx,n),rnk(ldx,n))

!     Read in data
      Read (nin,*)(x(i,1:n),i=1,k)

!     Display title
      Write (nout,*) 'Kendall''s coefficient of concordance'
      Write (nout,*)

!     Display data
      Write (nout,*) 'Data values'
      Write (nout,*)
      Write (nout,99999)('Comparison ',i,' scores  ',x(i,1:n),i=1,k)

      ifail = 0
      Call g08daf(x,ldx,k,n,rnk,w,p,ifail)

!     Display results
      Write (nout,*)
      Write (nout,99998) 'Kendall''s coefficient =', w
      Write (nout,99998) '          Significance =', p

99999 Format (1X,A,I1,A,10F5.1)
99998 Format (1X,A,F8.3)
    End Program g08dafe


g08eafe.f90

    Program g08eafe

!     G08EAF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: g08eaf, nag_wp, x04caf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: chi, df, prob
      Integer                          :: i, ifail, ldcov, lwrk, m, maxr, n,   &
                                          nruns, nsamp, pn
      Character (1)                    :: cl
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: cov(:,:), ex(:), wrk(:), x(:)
      Integer, Allocatable             :: ncount(:)
!     .. Executable Statements ..
      Write (nout,*) 'G08EAF Example Program Results'
      Write (nout,*)

!     Skip main heading in data file
      Read (nin,*)

!     Read in number of samples
      Read (nin,*) nsamp, m, maxr

      ldcov = maxr
      lwrk = maxr*(maxr+5)/2 + 1
      Allocate (ncount(maxr),cov(ldcov,maxr),ex(maxr),wrk(lwrk),x(1))

      If (nsamp==1) Then
        cl = 'S'
      Else
        cl = 'F'
      End If

      pn = 0
      Do i = 1, nsamp
!       Skip run heading in data file
        Read (nin,*)

!       Read in sample size
        Read (nin,*) n

        If (n>pn) Then
!         Reallocate X if required
          Deallocate (x)
          Allocate (x(n))
          pn = n
        End If

!       Read in the sample
        Read (nin,*) x(1:n)

!       Process the sample
        ifail = -1
        Call g08eaf(cl,n,x,m,maxr,nruns,ncount,ex,cov,ldcov,chi,df,prob,wrk,   &
          lwrk,ifail)
        If (ifail/=0 .And. ifail/=10) Then
          Go To 100
        End If

!       Adjust CL for intermediate calls
        If (i<nsamp-1) Then
          cl = 'I'
        Else
          cl = 'L'
        End If

      End Do

!     Display results
      Write (nout,99999) 'Total number of runs found = ', nruns
      If (ifail==10) Then
        Write (nout,*)                                                         &
          ' ** Note : the number of runs requested were not found.'
      End If
      Write (nout,*)
      Write (nout,*) '                             Count'
      Write (nout,*)                                                           &
        '          1        2        3        4        5       >5'
      Write (nout,99998) ncount(1:maxr)
      Write (nout,*)
      Write (nout,*) '                             Expect'
      Write (nout,*)                                                           &
        '          1        2        3        4        5       >5'
      Write (nout,99997) ex(1:maxr)
      Write (nout,*)
      Flush (nout)
      ifail = 0
      Call x04caf('General',' ',maxr,maxr,cov,ldcov,'Covariance matrix',ifail)
      Write (nout,*)
      Write (nout,99996) 'Chisq = ', chi
      Write (nout,99995) 'DF    = ', df
      Write (nout,99996) 'Prob  = ', prob

100   Continue

99999 Format (1X,A,I10)
99998 Format (3X,6I9)
99997 Format (3X,6F9.1)
99996 Format (1X,A,F10.4)
99995 Format (1X,A,F7.1)
    End Program g08eafe


g08ebfe.f90

    Program g08ebfe

!     G08EBF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: g08ebf, nag_wp, x04eaf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: chi, df, ex, prob
      Integer                          :: i, ifail, lag, ldc, lwrk, msize, n,  &
                                          nsamp, pn
      Logical                          :: bapp
      Character (1)                    :: cl
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: wrk(:), x(:)
      Integer, Allocatable             :: ncount(:,:)
!     .. Executable Statements ..
      Write (nout,*) 'G08EBF Example Program Results'
      Write (nout,*)
      Flush (nout)

!     Skip main heading in data file
      Read (nin,*)

!     Read in number of samples
      Read (nin,*) nsamp, msize, lag

      ldc = msize
      lwrk = 2*lag
      Allocate (ncount(ldc,msize),wrk(lwrk),x(1))

      If (nsamp==1) Then
        cl = 'S'
      Else
        cl = 'F'
      End If

      pn = 0
      bapp = .False.
      Do i = 1, nsamp
!       Skip run heading in data file
        Read (nin,*)

!       Read in sample size
        Read (nin,*) n

        If (n>pn) Then
!         Reallocate X if required
          Deallocate (x)
          Allocate (x(n))
          pn = n
        End If

!       Read in the sample
        Read (nin,*) x(1:n)

!       Process the sample
        ifail = -1
        Call g08ebf(cl,n,x,msize,lag,ncount,ldc,ex,chi,df,prob,wrk,ifail)
        If (ifail==8) Then
          bapp = .True.
        Else If (ifail/=0) Then
          Go To 100
        End If

!       Adjust CL for intermediate calls
        If (i<nsamp-1) Then
          cl = 'I'
        Else
          cl = 'L'
        End If

      End Do

!     Display results
      ifail = 0
      Call x04eaf('General',' ',msize,msize,ncount,ldc,'Count matrix',ifail)
      Write (nout,*)
      Write (nout,99999) 'Expected value = ', ex
      Write (nout,99998) 'CHISQ          = ', chi
      Write (nout,99999) 'DF             = ', df
      Write (nout,99998) 'Probability    = ', prob
      If (bapp) Then
        Write (nout,*)                                                         &
          ' ** Note : EX <= 5.0, the chi square approximation may not be ',    &
          'very good.'
      End If

100   Continue

99999 Format (1X,A,F8.2)
99998 Format (1X,A,F10.4)
    End Program g08ebfe


g08ecfe.f90

    Program g08ecfe

!     G08ECF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: g08ecf, nag_wp, x04eaf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: chi, df, ex, prob
      Integer                          :: i, ifail, ldc, msize, n, nsamp, pn
      Logical                          :: bapp
      Character (1)                    :: cl
      Character (80)                   :: title
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: x(:)
      Integer, Allocatable             :: ncount(:,:,:)
!     .. Executable Statements ..
      Write (nout,*) 'G08ECF Example Program Results'
      Write (nout,*)

!     Skip main heading in data file
      Read (nin,*)

!     Read in number of samples
      Read (nin,*) nsamp, msize

      ldc = msize
      Allocate (ncount(ldc,ldc,msize),x(1))

      If (nsamp==1) Then
        cl = 'S'
      Else
        cl = 'F'
      End If

      pn = 0
      bapp = .False.
      Do i = 1, nsamp
!       Skip run heading in data file
        Read (nin,*)

!       Read in sample size
        Read (nin,*) n

        If (n>pn) Then
!         Reallocate X if required
          Deallocate (x)
          Allocate (x(n))
          pn = n
        End If

!       Read in the sample
        Read (nin,*) x(1:n)

!       Process the sample
        ifail = -1
        Call g08ecf(cl,n,x,msize,ncount,ldc,ex,chi,df,prob,ifail)
        If (ifail==7) Then
          bapp = .True.
        Else If (ifail/=0) Then
          Go To 100
        End If

!       Adjust CL for intermediate calls
        If (i<nsamp-1) Then
          cl = 'I'
        Else
          cl = 'L'
        End If

      End Do

!     Display results
      Write (nout,*) 'Count matrix'
      Do i = 1, msize
        Write (nout,*)
        Write (title,99999) 'I = ', i
        Flush (nout)
        ifail = 0
        Call x04eaf('General',' ',msize,msize,ncount(1,1,i),ldc,title,ifail)
      End Do
      Write (nout,*)
      Write (nout,99998) 'Expected value = ', ex
      Write (nout,99997) 'CHISQ          = ', chi
      Write (nout,99998) 'DF             = ', df
      Write (nout,99997) 'Prob           = ', prob
      If (bapp) Then
        Write (nout,*) ' ** Note : expected value <= 5.0'
        Write (nout,*)                                                         &
          '    the chi square approximation may not be very good.'
      End If

100   Continue

99999 Format (1X,A,I2)
99998 Format (1X,A,F8.2)
99997 Format (1X,A,F10.4)
    End Program g08ecfe


g08edfe.f90

    Program g08edfe

!     G08EDF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: g08edf, nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: chi, df, prob, rlo, rup, totlen
      Integer                          :: i, ifail, m, maxg, n, ngaps, nsamp,  &
                                          pn
      Character (1)                    :: cl
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: ex(:), x(:)
      Integer, Allocatable             :: ncount(:)
!     .. Executable Statements ..
      Write (nout,*) 'G08EDF Example Program Results'
      Write (nout,*)

!     Skip main heading in data file
      Read (nin,*)

!     Read in number of samples and control parameters
      Read (nin,*) nsamp, m, maxg
      Read (nin,*) rlo, rup, totlen

      Allocate (ncount(maxg),ex(maxg),x(1))

      If (nsamp==1) Then
        cl = 'S'
      Else
        cl = 'F'
      End If

      pn = 0
      Do i = 1, nsamp
!       Skip run heading in data file
        Read (nin,*)

!       Read in sample size
        Read (nin,*) n

        If (n>pn) Then
!         Reallocate X if required
          Deallocate (x)
          Allocate (x(n))
          pn = n
        End If

!       Read in the sample
        Read (nin,*) x(1:n)

!       Process the sample
        ifail = -1
        Call g08edf(cl,n,x,m,maxg,rlo,rup,totlen,ngaps,ncount,ex,chi,df,prob,  &
          ifail)
        If (ifail/=0 .And. ifail<8) Then
          Go To 100
        End If

!       Adjust CL for intermediate calls
        If (i<nsamp-1) Then
          cl = 'I'
        Else
          cl = 'L'
        End If

      End Do

!     Display results
      Write (nout,99999) 'Total number of gaps found = ', ngaps
      If (ifail==8) Then
        Write (nout,*)                                                         &
          ' ** Note : the number of gaps requested were not found.'
      End If
      Write (nout,*)
      Write (nout,*) 'Count'
      Write (nout,*)                                                           &
        '      0      1      2      3      4      5      6      7      8',     &
        '     >9'
      Write (nout,99998) ncount(1:maxg)
      Write (nout,*)
      Write (nout,*) 'Expect'
      Write (nout,*)                                                           &
        '      0      1      2      3      4      5      6      7      8',     &
        '     >9'
      Write (nout,99997) ex(1:maxg)
      Write (nout,*)
      Write (nout,99996) 'Chisq = ', chi
      Write (nout,99995) 'DF    = ', df
      Write (nout,99996) 'Prob  = ', prob
      If (ifail==9) Then
        Write (nout,*) ' ** Note : expected value <= 5.0'
        Write (nout,*)                                                         &
          '    the chi square approximation may not be very good.'
      End If

100   Continue

99999 Format (1X,A,I10)
99998 Format (1X,10I7)
99997 Format (1X,10F7.1)
99996 Format (1X,A,F10.4)
99995 Format (1X,A,F7.1)
    End Program g08edfe


g08rafe.f90

    Program g08rafe

!     G08RAF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: g08raf, nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: tol
      Integer                          :: i, idist, ifail, ip, j, ldprvr, ldx, &
                                          lparest, lvapvec, lwork, nmax, ns,   &
                                          nsum
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: eta(:), parest(:), prvr(:,:),        &
                                          vapvec(:), work(:), x(:,:), y(:),    &
                                          zin(:)
      Integer, Allocatable             :: irank(:), iwa(:), nv(:)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: maxval, sum
!     .. Executable Statements ..
      Write (nout,*) 'G08RAF Example Program Results'
      Write (nout,*)

!     Skip heading in data file
      Read (nin,*)

!     Read number of samples, number of parameters to be fitted,
!     error distribution parameter and tolerance criterion for ties.
      Read (nin,*) ns, ip, idist, tol

      Allocate (nv(ns))

!     Read the number of observations in each sample.
      Read (nin,*) nv(1:ns)

!     Calculate NSUM, NMAX and various array lengths
      nsum = sum(nv(1:ns))
      nmax = maxval(nv(1:ns))
      ldx = nsum
      ldprvr = ip + 1
      lvapvec = nmax*(nmax+1)/2
      lparest = 4*ip + 1
      lwork = nmax*(ip+1)
      Allocate (y(nsum),x(ldx,ip),prvr(ldprvr,ip),irank(nmax),zin(nmax),       &
        eta(nmax),vapvec(lvapvec),parest(lparest),work(lwork),iwa(nmax))

!     Read in observations and design matrices for each sample.
      Read (nin,*)(y(i),x(i,1:ip),i=1,nsum)

!     Display input information
      Write (nout,99999) 'Number of samples =', ns
      Write (nout,99999) 'Number of parameters fitted =', ip
      Write (nout,99999) 'Distribution =', idist
      Write (nout,99998) 'Tolerance for ties =', tol

      ifail = 0
      Call g08raf(ns,nv,nsum,y,ip,x,ldx,idist,nmax,tol,prvr,ldprvr,irank,zin,  &
        eta,vapvec,parest,work,lwork,iwa,ifail)

!     Display results
      Write (nout,*)
      Write (nout,*) 'Score statistic'
      Write (nout,99997) parest(1:ip)
      Write (nout,*)
      Write (nout,*) 'Covariance matrix of score statistic'
      Do j = 1, ip
        Write (nout,99997) prvr(1:j,j)
      End Do
      Write (nout,*)
      Write (nout,*) 'Parameter estimates'
      Write (nout,99997) parest((ip+1):(2*ip))
      Write (nout,*)
      Write (nout,*) 'Covariance matrix of parameter estimates'
      Do i = 1, ip
        Write (nout,99997) prvr(i+1,1:i)
      End Do
      Write (nout,*)
      Write (nout,99996) 'Chi-squared statistic =', parest(2*ip+1), ' with',   &
        ip, ' d.f.'
      Write (nout,*)
      Write (nout,*) 'Standard errors of estimates and'
      Write (nout,*) 'approximate z-statistics'
      Write (nout,99995)(parest(2*ip+1+i),parest(3*ip+1+i),i=1,ip)

99999 Format (1X,A,I2)
99998 Format (1X,A,F8.5)
99997 Format (1X,2F9.3)
99996 Format (1X,A,F9.3,A,I2,A)
99995 Format (1X,F9.3,F14.3)
    End Program g08rafe


g08rbfe.f90

    Program g08rbfe

!     G08RBF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: g08rbf, nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: gamma, tol
      Integer                          :: i, ifail, ip, j, ldprvr, ldx, liwa,  &
                                          lparest, lvapvec, lwork, nmax, ns,   &
                                          nsum
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: eta(:), parest(:), prvr(:,:),        &
                                          vapvec(:), work(:), x(:,:), y(:),    &
                                          zin(:)
      Integer, Allocatable             :: icen(:), irank(:), iwa(:), nv(:)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: maxval, sum
!     .. Executable Statements ..
      Write (nout,*) 'G08RBF Example Program Results'
      Write (nout,*)

!     Skip heading in data file
      Read (nin,*)

!     Read number of samples, number of parameters to be fitted,
!     distribution power parameter and tolerance criterion for ties.
      Read (nin,*) ns, ip, gamma, tol

      Allocate (nv(ns))

!     Read the number of observations in each sample
      Read (nin,*) nv(1:ns)

!     Calculate NSUM, NMAX and various array lengths
      nsum = sum(nv(1:ns))
      nmax = maxval(nv(1:ns))
      ldx = nsum
      ldprvr = ip + 1
      lvapvec = nmax*(nmax+1)/2
      lparest = 4*ip + 1
      lwork = nmax*(ip+1)
      liwa = 4*nmax

      Allocate (y(nsum),x(ldx,ip),icen(nsum),prvr(ldprvr,ip),irank(nmax),      &
        zin(nmax),eta(nmax),vapvec(lvapvec),parest(lparest),work(lwork),       &
        iwa(liwa))

!     Read in observations, design matrix and censoring variable
      Read (nin,*)(y(i),x(i,1:ip),icen(i),i=1,nsum)

!     Display input information
      Write (nout,99999) 'Number of samples =', ns
      Write (nout,99999) 'Number of parameters fitted =', ip
      Write (nout,99998) 'Distribution power parameter =', gamma
      Write (nout,99998) 'Tolerance for ties =', tol

      ifail = 0
      Call g08rbf(ns,nv,nsum,y,ip,x,ldx,icen,gamma,nmax,tol,prvr,ldprvr,irank, &
        zin,eta,vapvec,parest,work,lwork,iwa,ifail)

!     Display results
      Write (nout,*)
      Write (nout,*) 'Score statistic'
      Write (nout,99997) parest(1:ip)
      Write (nout,*)
      Write (nout,*) 'Covariance matrix of score statistic'
      Do j = 1, ip
        Write (nout,99997) prvr(1:j,j)
      End Do
      Write (nout,*)
      Write (nout,*) 'Parameter estimates'
      Write (nout,99997) parest((ip+1):(2*ip))
      Write (nout,*)
      Write (nout,*) 'Covariance matrix of parameter estimates'
      Do i = 1, ip
        Write (nout,99997) prvr(i+1,1:i)
      End Do
      Write (nout,*)
      Write (nout,99996) 'Chi-squared statistic =', parest(2*ip+1), ' with',   &
        ip, ' d.f.'
      Write (nout,*)
      Write (nout,*) 'Standard errors of estimates and'
      Write (nout,*) 'approximate z-statistics'
      Write (nout,99995)(parest(2*ip+1+i),parest(3*ip+1+i),i=1,ip)

99999 Format (1X,A,I2)
99998 Format (1X,A,F10.5)
99997 Format (1X,F9.3)
99996 Format (1X,A,F9.3,A,I2,A)
99995 Format (1X,F9.3,F14.3)
    End Program g08rbfe


g10abfe.f90

    Program g10abfe

!     G10ABF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: g10abf, g10zaf, nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Integer                          :: i, ifail, j, lcomm, ldc, lwt, n,     &
                                          nord, nrho
      Character (1)                    :: mode, weight
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: c(:,:), comm(:), df(:), h(:),        &
                                          res(:), rho(:), rss(:), wt(:),       &
                                          wwt(:), x(:), xord(:), y(:),         &
                                          yhat(:,:), yord(:)
      Integer, Allocatable             :: iwrk(:)
!     .. Executable Statements ..
      Write (nout,*) ' G10ABF Example Program Results'
      Write (nout,*)

!     Skip heading in data file
      Read (nin,*)

!     Read in problem size and control parameters
      Read (nin,*) n, weight, nrho

      If (weight=='W' .Or. weight=='w') Then
        lwt = n
      Else
        lwt = 0
      End If
      lcomm = 9*n + 14
      ldc = n - 1
      Allocate (x(n),y(n),wt(lwt),xord(n),yord(n),wwt(n),yhat(n,nrho),         &
        c(ldc,3),res(n),h(n),comm(lcomm),iwrk(n),rho(nrho),rss(nrho),df(nrho))

!     Read in the smoothing parameters
      Read (nin,*) rho(1:nrho)

!     Read in data
      If (lwt>0) Then
        Read (nin,*)(x(i),y(i),wt(i),i=1,n)
      Else
        Read (nin,*)(x(i),y(i),i=1,n)
      End If

!     Reorder data into increasing X and remove tied observations, weighting
!     accordingly
      ifail = 0
      Call g10zaf(weight,n,x,y,wt,nord,xord,yord,wwt,rss(1),iwrk,ifail)

!     Fit cubic spline the first time
!     NB: These are weighted as G10ZAF creates weights
      ifail = 0
      mode = 'P'
      Call g10abf(mode,'W',nord,xord,yord,wwt,rho(1),yhat(1,1),c,ldc,rss(1),   &
        df(1),res,h,comm,ifail)

!     Fit cubic spline the remaining NRHO - 1 times
      mode = 'Q'
      Do i = 2, nrho
        ifail = 0
        Call g10abf(mode,'W',nord,xord,yord,wwt,rho(i),yhat(1,i),c,ldc,rss(i), &
          df(i),res,h,comm,ifail)
      End Do

!     Display results
      Write (nout,99999) 'Smoothing coefficient (rho) = ', rho(1:nrho)
      Write (nout,99998) 'Residual sum of squares     = ', rss(1:nrho)
      Write (nout,99998) 'Degrees of freedom          = ', df(1:nrho)
      Write (nout,*)
      Write (nout,*) '    X       Y                            Fitted Values'
      Do i = 1, nord
        Write (nout,99997) xord(i), yord(i), (yhat(i,j),j=1,nrho)
      End Do

99999 Format (1X,A,10(2X,F8.2))
99998 Format (1X,A,10(F10.3))
99997 Format (1X,2F8.4,14X,10(2X,F8.4))
    End Program g10abfe


g10acfe.f90

    Program g10acfe

!     G10ACF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: g10acf, g10zaf, nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: crit, df, rho, rss, tol, u
      Integer                          :: i, ifail, ldc, lwk, lwt, maxcal, n,  &
                                          nord
      Character (1)                    :: method, weight
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: c(:,:), h(:), res(:), wk(:), wt(:),  &
                                          wwt(:), x(:), xord(:), y(:),         &
                                          yhat(:), yord(:)
      Integer, Allocatable             :: iwrk(:)
!     .. Executable Statements ..
      Write (nout,*) 'G10ACF Example Program Results'
      Write (nout,*)

!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) method, weight, n

      If (weight=='W' .Or. weight=='w') Then
        lwt = n
      Else
        lwt = 0
      End If
      ldc = n - 1
      lwk = 7*(n+2)
      Allocate (x(n),y(n),wt(lwt),xord(n),yord(n),wwt(n),yhat(n),c(ldc,3),     &
        res(n),h(n),wk(lwk),iwrk(n))

!     Read in data
      If (lwt>0) Then
        Read (nin,*)(x(i),y(i),wt(i),i=1,n)
      Else
        Read (nin,*)(x(i),y(i),i=1,n)
      End If

!     Read in control parameters
      Read (nin,*) u, tol, maxcal, crit

!     Sort data, removing ties and weighting accordingly
      ifail = 0
      Call g10zaf(weight,n,x,y,wt,nord,xord,yord,wwt,rss,iwrk,ifail)

!     Fit cubic spline
      ifail = 0
      Call g10acf(method,'W',nord,xord,yord,wwt,yhat,c,ldc,rss,df,res,h,crit,  &
        rho,u,tol,maxcal,wk,ifail)

!     Display results
      Write (nout,99999) 'Residual sum of squares = ', rss
      Write (nout,99999) 'Degrees of freedom = ', df
      Write (nout,99999) 'RHO = ', rho
      Write (nout,*)
      Write (nout,*) '     Input data                Output results'
      Write (nout,*) '   I    X       Y            YHAT      H'
      Write (nout,99998)(i,xord(i),yord(i),yhat(i),h(i),i=1,nord)

99999 Format (1X,A,F10.2)
99998 Format (I4,2F8.3,6X,2F8.3)
    End Program g10acfe


g10bafe.f90

    Program g10bafe

!     G10BAF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: g10baf, nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: shi, slo, window
      Integer                          :: i, ifail, n, ns
      Logical                          :: usefft
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: fft(:), smooth(:), t(:), x(:)
      Integer, Allocatable             :: iwrk(:)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: min
!     .. Executable Statements ..
      Write (nout,*) 'G10BAF Example Program Results'
      Write (nout,*)
      Flush (nout)

!     Skip heading in data file
      Read (nin,*)

!     Read in density estimation information
      Read (nin,*) window, slo, shi, ns

!     Read in the size of the dataset
      Read (nin,*) n

      Allocate (smooth(ns),t(ns),fft(ns),x(n),iwrk(ns))

!     Read in data
      Read (nin,*) x(1:n)

!     Perform kernel density estimation
      usefft = .False.
      ifail = 0
      Call g10baf(n,x,window,slo,shi,ns,smooth,t,usefft,fft,ifail)

!     Display the results
      Write (nout,99998) 'Window Width Used = ', window
      Write (nout,99997) 'Interval = (', slo, ',', shi, ')'
      Write (nout,*)
      Write (nout,99999) 'First ', min(20,ns), ' output values:'
      Write (nout,*)
      Write (nout,*) '      Time        Density'
      Write (nout,*) '      Point       Estimate'
      Write (nout,*) ' ---------------------------'
      Do i = 1, min(20,ns)
        Write (nout,99996) t(i), smooth(i)
      End Do

99999 Format (A,I0,A)
99998 Format (A,E11.4)
99997 Format (A,E11.4,A,E11.4,A)
99996 Format (1X,E13.4,1X,E13.4)
    End Program g10bafe


g10bbfe.f90

    Program g10bbfe
!     G10BBF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: g10bbf, nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: shi, slo, window
      Integer                          :: fcall, i, ifail, n, ns, wtype
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: rcomm(:), smooth(:), t(:), x(:)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: min
!     .. Executable Statements ..
      Write (nout,*) 'G10BBF Example Program Results'
      Write (nout,*)

!     Skip heading in data file
      Read (nin,*)

!     Read in density estimation information
      Read (nin,*) wtype, window, slo, shi, ns

!     Read in the size of the dataset
      Read (nin,*) n

      Allocate (smooth(ns),t(ns),rcomm(ns+20),x(n))

!     Only calling the routine once
      fcall = 1

!     Read in data
      Read (nin,*) x(1:n)

!     Perform kernel density estimation
      ifail = 0
      Call g10bbf(n,x,wtype,window,slo,shi,ns,smooth,t,fcall,rcomm,ifail)

!     Display the results
      Write (nout,99998) 'Window Width Used = ', window
      Write (nout,99997) 'Interval = (', slo, ',', shi, ')'
      Write (nout,*)
      Write (nout,99999) 'First ', min(20,ns), ' output values:'
      Write (nout,*)
      Write (nout,*) '      Time        Density'
      Write (nout,*) '      Point       Estimate'
      Write (nout,*) ' ---------------------------'
      Do i = 1, min(20,ns)
        Write (nout,99996) t(i), smooth(i)
      End Do

99999 Format (A,I0,A)
99998 Format (A,E11.4)
99997 Format (A,E11.4,A,E11.4,A)
99996 Format (1X,E13.4,1X,E13.4)
    End Program g10bbfe


g10cafe.f90

    Program g10cafe

!     G10CAF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: g10caf, nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Integer                          :: i, ifail, itype, n
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: rough0(:), rough1(:), smooth0(:),    &
                                          smooth1(:), y(:)
!     .. Executable Statements ..
      Write (nout,*) ' G10CAF Example Program Results'
      Write (nout,*)

!     Skip heading in data file
      Read (nin,*)

!     Read in the problem size
      Read (nin,*) n

      Allocate (y(n),rough0(n),smooth0(n),rough1(n),smooth1(n))

!     Read in data
      Read (nin,*) y(1:n)

!     Smooth sequence using 3RSSH,twice
      itype = 1
      ifail = 0
      Call g10caf(itype,n,y,smooth1,rough1,ifail)

!     Smooth sequence using 4253H,twice
      itype = 0
      ifail = 0
      Call g10caf(itype,n,y,smooth0,rough0,ifail)

!     Display results
      Write (nout,*)                                                           &
        '                      Using 3RSSH,twice         Using 4253H,twice'
      Write (nout,*)                                                           &
        ' Index     Data      Smooth        Rough       Smooth       Rough'
      Write (nout,99999)(i,y(i),smooth1(i),rough1(i),smooth0(i),rough0(i),i=1, &
        n)

99999 Format (1X,I4,F11.1,2F13.4,2F13.1)
    End Program g10cafe


g10zafe.f90

    Program g10zafe

!     G10ZAF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: g10zaf, nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: rss
      Integer                          :: i, ifail, lwt, n, nord
      Character (1)                    :: weight
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: wt(:), wtord(:), x(:), xord(:),      &
                                          y(:), yord(:)
      Integer, Allocatable             :: iwrk(:)
!     .. Executable Statements ..
      Write (nout,*) 'G10ZAF Example Program Results'
      Write (nout,*)

!     Skip heading in data file
      Read (nin,*)

!     Read in the problem size
      Read (nin,*) weight, n

      If (weight=='W' .Or. weight=='w') Then
        lwt = n
      Else
        lwt = 0
      End If
      Allocate (x(n),y(n),iwrk(n),wt(lwt),xord(n),yord(n),wtord(n))

!     Read in data
      If (lwt>0) Then
        Read (nin,*)(x(i),y(i),wt(i),i=1,n)
      Else
        Read (nin,*)(x(i),y(i),i=1,n)
      End If

!     Reorder data
      ifail = 0
      Call g10zaf(weight,n,x,y,wt,nord,xord,yord,wtord,rss,iwrk,ifail)

!     Display results
      Write (nout,99999) 'Number of distinct observations = ', nord
      Write (nout,99998) 'Residual sum of squares         = ', rss
      Write (nout,*)
      Write (nout,*) '             X                 Y                 WT'
      Write (nout,99997)(xord(i),yord(i),wtord(i),i=1,nord)

99999 Format (1X,A,I6)
99998 Format (1X,A,F13.5)
99997 Format (5X,F13.5,5X,F13.5,5X,F13.5)
    End Program g10zafe


g11aafe.f90

    Program g11aafe

!     G11AAF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: g11aaf, nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: chi, df, g, prob
      Integer                          :: i, ifail, ldnobs, ncol, nrow
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: chist(:,:), expt(:,:)
      Integer, Allocatable             :: nobs(:,:)
!     .. Executable Statements ..
      Write (nout,*) ' G11AAF Example Program Results'
      Write (nout,*)

!     Skip heading in data file
      Read (nin,*)

!     Read in the problem size
      Read (nin,*) nrow, ncol

      ldnobs = nrow
      Allocate (nobs(ldnobs,ncol),expt(ldnobs,ncol),chist(ldnobs,ncol))

!     Read in data
      Read (nin,*)(nobs(i,1:ncol),i=1,nrow)

!     Perform chi-squared test
      ifail = -1
      Call g11aaf(nrow,ncol,nobs,ldnobs,expt,chist,prob,chi,g,df,ifail)
      If (ifail/=0) Then
        If (ifail/=3) Then
          Go To 100
        End If
      End If

!     Display results
      Write (nout,99999) ' Probability =', prob
      Write (nout,99998) ' Pearson Chi-square statistic = ', chi
      Write (nout,99998) ' Likelihood ratio test statistic = ', g
      Write (nout,99997) ' Degrees of freedom = ', df

100   Continue

99999 Format (A,F7.4)
99998 Format (A,F8.3)
99997 Format (A,F4.0)
    End Program g11aafe


g11bafe.f90

    Program g11bafe

!     G11BAF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: g11baf, nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Integer                          :: i, ifail, j, k, lauxt, ldf, lwt,     &
                                          maxt, n, ncells, ncol, ndim, nfac,   &
                                          nrow
      Character (1)                    :: stat, weight
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: auxt(:), table(:), wt(:), y(:)
      Integer, Allocatable             :: icount(:), idim(:), ifac(:,:),       &
                                          isf(:), iwk(:), lfac(:)
!     .. Executable Statements ..
      Write (nout,*) 'G11BAF Example Program Results'
      Write (nout,*)

!     Skip heading in data file
      Read (nin,*)

!     Read in the problem size
      Read (nin,*) stat, weight, n, nfac

      If (weight=='W' .Or. weight=='w' .Or. weight=='V' .Or. weight=='v') Then
        lwt = n
      Else
        lwt = 0
      End If
      ldf = n
      Allocate (isf(nfac),lfac(nfac),ifac(ldf,nfac),y(n),wt(lwt),idim(nfac),   &
        iwk(2*nfac))

!     Read in data
      If (lwt>0) Then
        Read (nin,*)(ifac(i,1:nfac),y(i),wt(i),i=1,n)
      Else
        Read (nin,*)(ifac(i,1:nfac),y(i),i=1,n)
      End If
      Read (nin,*) lfac(1:nfac)
      Read (nin,*) isf(1:nfac)

!     Calculate MAXT
      maxt = 1
      Do i = 1, nfac
        If (isf(i)>0) Then
          maxt = maxt*lfac(i)
        End If
      End Do

      Select Case (stat)
      Case ('A','a')
        lauxt = maxt
      Case ('V','v')
        lauxt = 2*maxt
      Case Default
        lauxt = 0
      End Select

      Allocate (table(maxt),icount(maxt),auxt(lauxt))

!     Compute table
      ifail = 0
      Call g11baf(stat,'I',weight,n,nfac,isf,lfac,ifac,ldf,y,wt,table,maxt,    &
        ncells,ndim,idim,icount,auxt,iwk,ifail)

!     Display results
      Write (nout,*) ' TABLE'
      Write (nout,*)
      ncol = idim(ndim)
      nrow = ncells/ncol
      k = 1
      Do i = 1, nrow
        Write (nout,99999)(table(j),'(',icount(j),')',j=k,k+ncol-1)
        k = k + ncol
      End Do

99999 Format (1X,6(F8.2,A,I2,A))
    End Program g11bafe


g11bbfe.f90

    Program g11bbfe

!     G11BBF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: g11bbf, nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: percnt
      Integer                          :: i, ifail, j, k, ldf, liwk, lwk, lwt, &
                                          maxt, n, ncells, ncol, ndim, nfac,   &
                                          nrow
      Character (1)                    :: typ, weight
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: table(:), wk(:), wt(:), y(:)
      Integer, Allocatable             :: icount(:), idim(:), ifac(:,:),       &
                                          isf(:), iwk(:), lfac(:)
!     .. Executable Statements ..
      Write (nout,*) 'G11BBF Example Program Results'
      Write (nout,*)

!     Skip heading in data file
      Read (nin,*)

!     Read in the problem size
      Read (nin,*) typ, weight, n, nfac, percnt

      If (weight=='W' .Or. weight=='w') Then
        lwt = n
      Else
        lwt = 0
      End If
      liwk = 2*nfac + n
      lwk = 2*n
      ldf = n
      Allocate (isf(nfac),lfac(nfac),ifac(ldf,nfac),idim(nfac),iwk(liwk),y(n), &
        wt(lwt),wk(lwk))

!     Read in data
      If (lwt>0) Then
        Read (nin,*)(ifac(i,1:nfac),y(i),wt(i),i=1,n)
      Else
        Read (nin,*)(ifac(i,1:nfac),y(i),i=1,n)
      End If
      Read (nin,*) lfac(1:nfac)
      Read (nin,*) isf(1:nfac)

!     Calculate the size of TABLE
      maxt = 1
      Do i = 1, nfac
        If (isf(i)>0) Then
          maxt = maxt*lfac(i)
        End If
      End Do

      Allocate (table(maxt),icount(maxt))

!     Compute classification table
      ifail = 0
      Call g11bbf(typ,weight,n,nfac,isf,lfac,ifac,ldf,percnt,y,wt,table,maxt,  &
        ncells,ndim,idim,icount,iwk,wk,ifail)

!     Display results
      Write (nout,99999) ' TABLE for ', percnt, 'th percentile'
      Write (nout,*)
      ncol = idim(ndim)
      nrow = ncells/ncol
      k = 1
      Do i = 1, nrow
        Write (nout,99998)(table(j),'(',icount(j),')',j=k,k+ncol-1)
        k = k + ncol
      End Do

99999 Format (A,F4.0,A)
99998 Format (1X,6(F8.2,A,I2,A))
    End Program g11bbfe


g11bcfe.f90

    Program g11bcfe

!     G11BCF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: g11bcf, nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Integer                          :: i, ifail, k, lauxt, maxst, mcells,   &
                                          mdim, ncells, ncol, ndim, nrow
      Character (1)                    :: stat
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: auxt(:), stable(:), table(:), wk(:)
      Integer, Allocatable             :: idim(:), isdim(:), iwk(:), mlevel(:)
!     .. Executable Statements ..
      Write (nout,*) 'G11BCF Example Program Results'
      Write (nout,*)

!     Skip heading in data file
      Read (nin,*)

!     Read in the problem size
      Read (nin,*) stat, ncells, ndim

      Allocate (table(ncells),idim(ndim),isdim(ndim))

!     Read in data
      Read (nin,*) table(1:ncells)
      Read (nin,*) idim(1:ndim)
      Read (nin,*) isdim(1:ndim)

!     Calculate MAXST
      maxst = 1
      Do i = 1, ndim
        If (isdim(i)>0) Then
          maxst = maxst*idim(i)
        End If
      End Do

      If (stat=='V' .Or. stat=='v') Then
        lauxt = maxst
      Else
        lauxt = 0
      End If
      Allocate (stable(maxst),mlevel(ndim),auxt(lauxt),iwk(3*ndim),wk(ncells))

!     Compute marginal table
      ifail = 0
      Call g11bcf(stat,table,ncells,ndim,idim,isdim,stable,maxst,mcells,mdim,  &
        mlevel,auxt,iwk,wk,ifail)

!     Display results
      Write (nout,*) ' Marginal Table'
      Write (nout,*)
      ncol = mlevel(mdim)
      nrow = mcells/ncol
      k = 1
      Do i = 1, nrow
        Write (nout,99999) stable(k:(k+ncol-1))
        k = k + ncol
      End Do

99999 Format (10F8.2)
    End Program g11bcfe


g11cafe.f90

    Program g11cafe

!     G11CAF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: g11caf, nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: dev, tol
      Integer                          :: cm, i, ifail, ip, iprint, ldz, lwk,  &
                                          m, maxit, n, n0, ns
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: b(:), cov(:), sc(:), se(:), wk(:),   &
                                          z(:,:)
      Integer, Allocatable             :: cnt(:), ic(:), isi(:), isz(:),       &
                                          nca(:), nct(:)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: count, maxval, sum
!     .. Executable Statements ..
      Write (nout,*) 'G11CAF Example Program Results'
      Write (nout,*)

!     Skip heading in data file
      Read (nin,*)

!     Read in problem size and control parameters
      Read (nin,*) n, m, ns, maxit, iprint, tol

      ldz = n
      Allocate (z(ldz,m),isz(m),ic(n),isi(n),nca(ns),nct(ns),cnt(ns))

!     Read in data
      Read (nin,*)(isi(i),ic(i),z(i,1:m),i=1,n)

!     Read in variable inclusion flags
      Read (nin,*) isz(1:m)

!     Calculate IP
      ip = count(isz(1:m)>0)

!     Calculate number of observations in the model and maximum number of
!     observations in any stratum
      cnt(1:ns) = 0
      Do i = 1, n
        If (isi(i)>0 .And. isi(i)<=ns) Then
          cnt(isi(i)) = cnt(isi(i)) + 1
        End If
      End Do
      cm = maxval(cnt(1:ns))
      n0 = sum(cnt(1:ns))

      lwk = ip*n0 + (cm+1)*(ip+1)*(ip+2)/2 + cm
      Allocate (b(ip),se(ip),sc(ip),cov(ip*(ip+1)/2),wk(lwk))

!     Read in initial estimate for B
      Read (nin,*) b(1:ip)

!     Calculate parameter estimates
      ifail = 0
      Call g11caf(n,m,ns,z,ldz,isz,ip,ic,isi,dev,b,se,sc,cov,nca,nct,tol,      &
        maxit,iprint,wk,lwk,ifail)

!     Display results
      Write (nout,99999) ' Deviance = ', dev
      Write (nout,*)
      Write (nout,*) ' Strata     No. Cases   No. Controls'
      Write (nout,*)
      Write (nout,99998)(i,nca(i),nct(i),i=1,ns)
      Write (nout,*)
      Write (nout,*) ' Parameter      Estimate', '       Standard Error'
      Write (nout,*)
      Write (nout,99997)(i,b(i),se(i),i=1,ip)

99999 Format (A,E13.4)
99998 Format (3X,I3,10X,I2,10X,I2)
99997 Format (I6,10X,F8.4,10X,F8.4)
    End Program g11cafe


g11safe.f90

    Program g11safe

!     G11SAF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: g11saf, nag_wp, x04abf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: iset = 1, nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: cgetol, chi, rlogl, siglev
      Integer                          :: i, idf, ifail, ip, ip2, iprint,      &
                                          ishow, ldcm, ldexpp, ldx, lw, maxit, &
                                          n, nadv, niter, ns
      Logical                          :: chisqr, gprob
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: a(:), alpha(:), c(:), cm(:,:),       &
                                          exf(:), expp(:,:), g(:), obs(:,:),   &
                                          pigam(:), w(:), xl(:), y(:)
      Integer, Allocatable             :: iob(:), irl(:)
      Logical, Allocatable             :: x(:,:)
!     .. Executable Statements ..
      Write (nout,*) 'G11SAF Example Program Results'
      Write (nout,*)
      Flush (nout)

!     Skip heading in data file
      Read (nin,*)

!     Read in problem size
      Read (nin,*) ip, n, ns

!     Read in control parameters
      Read (nin,*) gprob, iprint, cgetol, maxit, chisqr, ishow

!     Set the advisory channel to NOUT for monitoring information
      If (iprint>0 .Or. ishow/=0) Then
        nadv = nout
        Call x04abf(iset,nadv)
      End If

      ip2 = 2*ip
      ldx = ns
      ldcm = ip2
      ldexpp = ip
      lw = 4*ip*(ip+16)
      Allocate (x(ldx,ip),irl(ns),a(ip),c(ip),alpha(ip),pigam(ip),             &
        cm(ldcm,ip2),g(ip2),expp(ldexpp,ip),obs(ldexpp,ip),exf(ns),y(ns),      &
        xl(ns),iob(ns),w(lw))

!     Read in data
      Read (nin,*)(irl(i),x(i,1:ip),i=1,ns)

!     Read in initial values
      Read (nin,*) a(1:ip)
      Read (nin,*) c(1:ip)

!     Fit a latent variable model
      ifail = 0
      Call g11saf(ip,n,gprob,ns,x,ldx,irl,a,c,iprint,cgetol,maxit,chisqr,      &
        ishow,niter,alpha,pigam,cm,ldcm,g,expp,ldexpp,obs,exf,y,xl,iob,rlogl,  &
        chi,idf,siglev,w,lw,ifail)

    End Program g11safe


g11sbfe.f90

    Program g11sbfe

!     G11SBF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: g11sbf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Integer                          :: i, ifail, ip, ldx, n, ns
!     .. Local Arrays ..
      Integer, Allocatable             :: irl(:)
      Logical, Allocatable             :: x(:,:)
!     .. Executable Statements ..
      Write (nout,*) 'G11SBF Example Program Results'
      Write (nout,*)

!     Skip heading in data file
      Read (nin,*)
      Read (nin,*) n, ip

      ldx = n
      Allocate (x(ldx,ip),irl(n))

!     Read in data
      Read (nin,*)(x(i,1:ip),i=1,n)

      ifail = 0
      Call g11sbf(ip,n,ns,x,ldx,irl,ifail)

!     Display results
      Write (nout,*) 'Frequency     Score pattern'
      Write (nout,*)
      Do i = 1, ns
        Write (nout,99999) irl(i), x(i,1:ip)
      End Do

99999 Format (1X,I5,12X,5(L2))
    End Program g11sbfe


g12aafe.f90

    Program g12aafe

!     G12AAF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: g12aaf, nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Integer                          :: i, ifail, lifreq, n, nd
      Character (1)                    :: freq
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: p(:), psig(:), t(:), tp(:)
      Integer, Allocatable             :: ic(:), ifreq(:), iwk(:)
!     .. Executable Statements ..
      Write (nout,*) 'G12AAF Example Program Results'
      Write (nout,*)

!     Skip heading in data file
      Read (nin,*)

!     Read in the problem size
      Read (nin,*) n, freq

      If (freq=='F' .Or. freq=='f') Then
        lifreq = n
      Else
        lifreq = 0
      End If
      Allocate (p(n),psig(n),t(n),tp(n),ic(n),ifreq(lifreq),iwk(n))

!     Read in the data
      If (lifreq==0) Then
        Read (nin,*)(t(i),ic(i),i=1,n)
      Else
        Read (nin,*)(t(i),ic(i),ifreq(i),i=1,n)
      End If

!     Calculate Kaplan-Meier statistic
      ifail = 0
      Call g12aaf(n,t,ic,freq,ifreq,nd,tp,p,psig,iwk,ifail)

!     Display the results
      Write (nout,*) '  Time   Survival    Standard'
      Write (nout,*) '        probability  deviation'
      Write (nout,*)
      Write (nout,99999)(tp(i),p(i),psig(i),i=1,nd)

99999 Format (1X,F6.1,F10.3,2X,F10.3)
    End Program g12aafe


g12abfe.f90

    Program g12abfe

!     G12ABF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: g12abf, nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: p, ts
      Integer                          :: df, i, ifail, ldn, lfreq, lwt, n,    &
                                          nd, ngrp
      Character (1)                    :: freq, weight
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: expt(:), obsd(:), t(:), wt(:)
      Integer, Allocatable             :: di(:), grp(:), ic(:), ifreq(:),      &
                                          ni(:)
!     .. Executable Statements ..
      Write (nout,*) 'G12ABF Example Program Results'
      Write (nout,*)

!     Skip heading in data file
      Read (nin,*)

!     Read in the problem size
      Read (nin,*) n, ngrp, freq, weight

      If (freq=='F' .Or. freq=='f') Then
        lfreq = n
      Else
        lfreq = 0
      End If
      If (weight=='W' .Or. weight=='w') Then
        lwt = n
      Else
        lwt = 0
      End If
      ldn = n
      Allocate (t(n),ic(n),grp(n),ifreq(lfreq),obsd(ngrp),expt(ngrp),di(ldn),  &
        ni(ldn),wt(lwt))

!     Read in data
      If (lfreq==0) Then
        Read (nin,*)(t(i),ic(i),grp(i),i=1,n)
      Else
        Read (nin,*)(t(i),ic(i),grp(i),ifreq(i),i=1,n)
      End If

!     Calculate the statistic
      ifail = 0
      Call g12abf(n,t,ic,grp,ngrp,freq,ifreq,weight,wt,ts,df,p,obsd,expt,nd,   &
        di,ni,ldn,ifail)

!     Display results
      Write (nout,99999) 'Observed', 'Expected'
      Write (nout,99998)('Group',i,obsd(i),expt(i),i=1,ngrp)
      Write (nout,*)
      Write (nout,99996) 'No. Unique Failure Times = ', nd
      Write (nout,*)
      Write (nout,99997) 'Test Statistic           = ', ts
      Write (nout,99996) 'Degrees of Freedom       = ', df
      Write (nout,99997) 'p-value                  = ', p

99999 Format (11X,A,2X,A)
99998 Format (1X,A,1X,I1,1X,F8.2,2X,F8.2)
99997 Format (1X,A,1X,F8.4)
99996 Format (1X,A,1X,I3)
    End Program g12abfe


g12bafe.f90

    Program g12bafe

!     G12BAF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: g02gcf, g12baf, nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: dev, tol
      Integer                          :: i, idf, ifail, ip, ip1, iprint,      &
                                          irank, ldv, ldz, lisi, lomega, m,    &
                                          maxit, n, nd, ndmax, ns
      Character (1)                    :: offset
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: b(:), cov(:), omega(:), res(:),      &
                                          sc(:), se(:), sur(:,:), t(:), tp(:), &
                                          v(:,:), wk(:), y(:), z(:,:)
      Integer, Allocatable             :: ic(:), isi(:), isz(:), iwk(:)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: count, eoshift, log, max, real
!     .. Executable Statements ..
      Write (nout,*) 'G12BAF Example Program Results'
      Write (nout,*)

!     Skip heading in data file
      Read (nin,*)

!     Read in problem size
      Read (nin,*) n, m, ns, maxit, iprint, offset

      If (offset=='Y' .Or. offset=='y') Then
        lomega = n
      Else
        lomega = 0
      End If
      If (ns>0) Then
        lisi = n
      Else
        lisi = 0
      End If
      ldz = n
      ndmax = n
      ldv = n
      Allocate (z(ldz,m),isz(m),t(n),ic(n),omega(lomega),isi(lisi),res(n),     &
        tp(ndmax),sur(ndmax,max(ns,1)),iwk(2*n),y(n))

!     Read in the data
      If (ns>0) Then
        If (lomega==0) Then
          Read (nin,*)(t(i),z(i,1:m),ic(i),isi(i),i=1,n)
        Else
          Read (nin,*)(t(i),z(i,1:m),ic(i),isi(i),omega(i),i=1,n)
        End If
      Else
        If (lomega==0) Then
          Read (nin,*)(t(i),z(i,1:m),ic(i),i=1,n)
        Else
          Read (nin,*)(t(i),z(i,1:m),ic(i),omega(i),i=1,n)
        End If
      End If

!     Read in the variable indication
      Read (nin,*) isz(1:m)

!     Calculate number of parameters in the model
      ip = count(isz(1:m)>0)

!     We are fitting a mean in the exponential model, so arrays used by G02GCF
!     need to be based on IP + 1
      ip1 = ip + 1
      Allocate (b(ip1),se(ip1),sc(ip),cov(ip1*(ip1+1)/2),wk(ip1*(ip1+          &
        9)/2+n),v(ldv,ip1+7))

!     Specify tolerance to use
      tol = 5.0E-5_nag_wp

!     Get initial estimates by fitting an exponential model
      Do i = 1, n
        y(i) = 1.0E0_nag_wp - real(ic(i),kind=nag_wp)
        v(i,7) = log(t(i))
      End Do

!     Fit exponential model
      ifail = -1
      Call g02gcf('L','M','Y','U',n,z,ldz,m,isz,ip1,y,res,0.0E0_nag_wp,dev,    &
        idf,b,irank,se,cov,v,ldv,tol,maxit,0,0.0E0_nag_wp,wk,ifail)
      If (ifail/=0) Then
        If (ifail<5) Then
          Go To 100
        End If
      End If

!     Check exponential model was of full rank
      If (irank/=ip1) Then
        Write (nout,*) ' WARNING: covariates not of full rank'
      End If

!     Move all parameter estimates down one so as to drop the parameter
!     estimate for the mean.
      b(1:ip1) = eoshift(b(1:ip1),1)

!     Fit Cox proportional hazards model
      ifail = -1
      Call g12baf('No-offset',n,m,ns,z,ldz,isz,ip,t,ic,omega,isi,dev,b,se,sc,  &
        cov,res,nd,tp,sur,ndmax,tol,maxit,iprint,wk,iwk,ifail)
      If (ifail/=0) Then
        If (ifail<5) Then
          Go To 100
        End If
      End If

!     Display results
      Write (nout,*) ' Parameter      Estimate', '       Standard Error'
      Write (nout,*)
      Write (nout,99999)(i,b(i),se(i),i=1,ip)
      Write (nout,*)
      Write (nout,99998) ' Deviance = ', dev
      Write (nout,*)
      Write (nout,*) '    Time     Survivor Function'
      Write (nout,*)
      ns = max(ns,1)
      Write (nout,99997)(tp(i),sur(i,1:ns),i=1,nd)

100   Continue

99999 Format (I6,10X,F8.4,10X,F8.4)
99998 Format (A,E13.4)
99997 Format (F10.0,5X,F8.4)
    End Program g12bafe


g12zafe.f90

    Program g12zafe

!     G12ZAF Example Program Text.

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: g11caf, g12zaf, nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: dev, tol
      Integer                          :: cm, i, ifail, ip, iprint, ldz, lisi, &
                                          lwk, m, maxit, mxn, n, nd, ns, num,  &
                                          nxs
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: b(:), cov(:), sc(:), se(:), t(:),    &
                                          tp(:), wk(:), x(:,:), z(:,:)
      Integer, Allocatable             :: cnt(:), ic(:), id(:), irs(:),        &
                                          isi(:), isz(:), ixs(:), nca(:),      &
                                          nct(:)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: count, maxval
!     .. Executable Statements ..
      Write (nout,*) 'G12ZAF Example Program Results'
      Write (nout,*)

!     Skip heading in data file
      Read (nin,*)

!     Read in problem size
      Read (nin,*) n, m, ns, maxit, iprint

      If (ns>0) Then
        lisi = n
      Else
        lisi = 0
      End If

      ldz = n
      Allocate (z(ldz,m),isz(m),t(n),ic(n),isi(lisi),tp(n),irs(n))

!     Read in the data
      If (ns>0) Then
        Read (nin,*)(t(i),z(i,1:m),ic(i),isi(i),i=1,n)
      Else
        Read (nin,*)(t(i),z(i,1:m),ic(i),i=1,n)
      End If

!     Read in the variable indicator
      Read (nin,*) isz(1:m)

!     Calculate number of parameters in the model
      ip = count(isz(1:m)>0)

!     Call the routine once to calculate size of MXN ...

!     Dummy allocation
      mxn = 0
      Allocate (x(mxn,ip),id(mxn),ixs(mxn))

!     Call G12ZAF to calculate MXN
      ifail = 1
      Call g12zaf(n,m,ns,z,ldz,isz,ip,t,ic,isi,num,ixs,nxs,x,mxn,id,nd,tp,irs, &
        ifail)
      If (ifail/=0 .And. ifail/=3) Then
        Go To 100
      End If

!     Required size for MXN is returned in NUM, so reallocate memory
      mxn = num
      Deallocate (x,id,ixs)
      Allocate (x(mxn,ip),id(mxn),ixs(mxn))

!     Create risk set
      ifail = 0
      Call g12zaf(n,m,ns,z,ldz,isz,ip,t,ic,isi,num,ixs,nxs,x,mxn,id,nd,tp,irs, &
        ifail)

      Allocate (cnt(nxs),b(ip),se(ip),sc(ip),nca(nxs),nct(nxs),cov(ip*(ip+     &
        1)/2))

!     Set tolerance
      tol = 1.0E-5_nag_wp

!     Read in initial parameter estimates
      Read (nin,*) b(1:ip)

!     Count the number of observations in each stratum
      cnt(1:nxs) = 0
      Do i = 1, num
        cnt(ixs(i)) = cnt(ixs(i)) + 1
      End Do
      cm = maxval(cnt(1:nxs))

      lwk = ip*num + (cm+1)*(ip+1)*(ip+2)/2 + cm
      Allocate (wk(lwk))

!     Get parameter estimates from conditional logistic analysis
      ifail = 0
      Call g11caf(num,ip,nxs,x,mxn,isz,ip,id,ixs,dev,b,se,sc,cov,nca,nct,tol,  &
        maxit,iprint,wk,lwk,ifail)

!     Display results
      Write (nout,*) ' Parameter      Estimate', '       Standard Error'
      Write (nout,*)
      Write (nout,99999)(i,b(i),se(i),i=1,ip)

100   Continue

99999 Format (I6,10X,F8.4,10X,F8.4)
    End Program g12zafe


g13aafe.f90

    Program g13aafe

!     G13AAF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: g13aaf, nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Integer                          :: ifail, nd, nds, ns, nx, nxd
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: x(:), xd(:)
!     .. Executable Statements ..
      Write (nout,*) 'G13AAF Example Program Results'
      Write (nout,*)

!     Skip heading in data file
      Read (nin,*)

!     Read in the problem size
      Read (nin,*) nx, nd, nds, ns

      Allocate (x(nx),xd(nx))

!     Read in data
      Read (nin,*) x(1:nx)

!     Perform differencing
      ifail = 0
      Call g13aaf(x,nx,nd,nds,ns,xd,nxd,ifail)

!     Display results
      Write (nout,99999) 'Non-seasonal differencing of order ', nd,            &
        ' and seasonal differencing'
      Write (nout,99999) 'of order ', nds, ' with seasonality ', ns,           &
        ' are applied'
      Write (nout,*)
      Write (nout,99998) 'The output array holds ', nx,                        &
        ' values, of which the first ', nxd, ' are differenced values'
      Write (nout,*)
      Write (nout,99997) xd(1:nx)

99999 Format (1X,A,I1,A,I1,A)
99998 Format (1X,A,I2,A,I2,A)
99997 Format (1X,5F9.1)
    End Program g13aafe


g13abfe.f90

    Program g13abfe

!     G13ABF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: g13abf, nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: stat, xm, xv
      Integer                          :: i, ifail, nk, nx
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: r(:), x(:)
!     .. Executable Statements ..
      Write (nout,*) 'G13ABF Example Program Results'
      Write (nout,*)

!     Skip heading in data file
      Read (nin,*)

!     Read in the problem size
      Read (nin,*) nx, nk

      Allocate (x(nx),r(nk))

!     Read in data
      Read (nin,*) x(1:nx)

!     Compute autocorrelation
      ifail = 0
      Call g13abf(x,nx,nk,xm,xv,r,stat,ifail)

!     Display results
      Write (nout,99999) 'The first ', nk, ' coefficients are required'
      Write (nout,99998) 'The input array has sample mean ', xm
      Write (nout,99998) 'The input array has sample variance ', xv
      Write (nout,*) 'The sample autocorrelation coefficients are'
      Write (nout,*)
      Write (nout,*) '   Lag    Coeff      Lag    Coeff'
      Write (nout,99997)(i,r(i),i=1,nk)
      Write (nout,*)
      Write (nout,99998) 'The value of STAT is ', stat

99999 Format (1X,A,I2,A)
99998 Format (1X,A,F12.4)
99997 Format (1X,I6,F10.4,I8,F10.4)
    End Program g13abfe


g13acfe.f90

    Program g13acfe

!     G13ACF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: g13acf, nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Integer                          :: i, ifail, nk, nl, nvl
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: ar(:), p(:), r(:), v(:)
!     .. Executable Statements ..
      Write (nout,*) 'G13ACF Example Program Results'
      Write (nout,*)

!     Skip heading in data file
      Read (nin,*)

!     Read in the problem size
      Read (nin,*) nk, nl

      Allocate (ar(nl),p(nl),r(nk),v(nl))

!     Read in data
      Read (nin,*)(r(i),i=1,nk)

!     Calculate partial ACF
      ifail = -1
      Call g13acf(r,nk,nl,p,v,ar,nvl,ifail)
      If (ifail/=0) Then
        If (ifail==3) Then
          Write (nout,99999) '   Only', nvl, 'valid sets were generated'
          Write (nout,*)
        Else
          Go To 100
        End If
      End If

!     Display results
      Write (nout,*) 'Lag  Partial    Predictor error  Autoregressive'
      Write (nout,*) '     autocorrn  variance ratio' // '   parameter'
      Write (nout,*)
      Write (nout,99998)(i,p(i),v(i),ar(i),i=1,nvl)

100   Continue

99999 Format (1X,A,I2,A)
99998 Format (1X,I2,F9.3,F16.3,F14.3)
    End Program g13acfe


g13adfe.f90

    Program g13adfe

!     G13ADF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: g13adf, nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: rv, xv
      Integer                          :: ifail, nk, npar, nwa, pp, qp
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: par(:), r(:), wa(:)
      Integer                          :: isf(4), mr(7)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: max
!     .. Executable Statements ..
      Write (nout,*) 'G13ADF Example Program Results'
      Write (nout,*)

!     Skip heading in data file
      Read (nin,*)

!     Read in problem size and variance
      Read (nin,*) nk
      Read (nin,*) xv

      Allocate (r(nk))

!     Read in data
      Read (nin,*) r(1:nk)

!     Read in the orders
      Read (nin,*) mr(1:7)

!     Calculate NPAR
      npar = mr(1) + mr(3) + mr(4) + mr(6)

      pp = max(mr(1),mr(4))
      qp = max(mr(3),mr(6))
      nwa = max(pp**2+pp,4*(qp+1))
      Allocate (par(npar),wa(nwa))

!     Calculate preliminary estimates
      ifail = -1
      Call g13adf(mr,r,nk,xv,npar,wa,nwa,par,rv,isf,ifail)
      If (ifail/=0) Then
        If (ifail<7) Then
          Go To 100
        End If
      End If

!     Display results
      Write (nout,99999) 'Parameter estimation success/failure indicator',     &
        isf(1:4)
      Write (nout,*)
      Write (nout,99998) 'ARIMA model parameter values ', par(1:npar)
      Write (nout,*)
      Write (nout,99998) 'Residual variance', rv

100   Continue

99999 Format (1X,A,4I4)
99998 Format (1X,A,5F10.5)
    End Program g13adfe


g13aefe.f90

!   G13AEF Example Program Text
!   Mark 26 Release. NAG Copyright 2016.

    Module g13aefe_mod

!     G13AEF Example Program Module:
!            Parameters and User-defined Routines

!     .. Use Statements ..
      Use nag_library, Only: nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Accessibility Statements ..
      Private
      Public                           :: piv
!     .. Parameters ..
      Integer, Parameter, Public       :: nin = 5, nout = 6
    Contains
      Subroutine piv(mr,par,npar,c,kfc,icount,s,g,h,ldh,igh,itc,zsp)

!       .. Parameters ..
        Integer, Parameter             :: param_inds(4) = (/1,3,4,6/)
!       .. Scalar Arguments ..
        Real (Kind=nag_wp), Intent (In) :: c, s
        Integer, Intent (In)           :: igh, itc, kfc, ldh, npar
!       .. Array Arguments ..
        Real (Kind=nag_wp), Intent (In) :: g(igh), h(ldh,igh), par(npar),      &
                                          zsp(4)
        Integer, Intent (In)           :: icount(6), mr(7)
!       .. Local Scalars ..
        Integer                        :: i, param, start_ind
!       .. Executable Statements ..
        Write (nout,*)

        If (itc==0) Then
          Write (nout,*) 'Begin monitoring output'
          Write (nout,99999) 'Degrees of freedom: ', icount(5)
        End If

        Write (nout,99999) 'Iteration: ', itc

param_loop: Do i = 1, 4
          param = mr(param_inds(i))
          If (param<=0) Then
            Cycle param_loop
          End If
          Select Case (param_inds(i))
          Case (1)
            Write (nout,*) 'Autoregressive parameters:'
            start_ind = 1
          Case (3)
            Write (nout,*) 'Moving-average parameters:'
          Case (4)
            Write (nout,*) 'Seasonal autoregressive parameters:'
          Case (6)
            Write (nout,*) 'Seasonal moving-average parameters:'
          End Select
          Write (nout,99998) par(start_ind:start_ind+param-1)
          start_ind = start_ind + param
        End Do param_loop

        If (kfc==1) Then
          Write (nout,*) 'Constant term:'
          Write (nout,99998) c
        End If

        Write (nout,*) 'Residual sum of squares:'
        Write (nout,99998) s

        Write (nout,*)                                                         &
          'Parameters (alpha, beta, delta, gamma) controlling the search ',    &
          'procedure:'
        Write (nout,99998) zsp

        Return
99999   Format (1X,A,I3)
99998   Format (1X,E13.4)
      End Subroutine piv
    End Module g13aefe_mod
    Program g13aefe

!     G13AEF Example Main Program

!     .. Use Statements ..
      Use nag_library, Only: g13aef, nag_wp, x04caf
      Use g13aefe_mod, Only: nin, nout, piv
!     .. Implicit None Statement ..
      Implicit None
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: c, s
      Integer                          :: iex, ifail, igh, ist, itc, iwa, kfc, &
                                          kpiv, kzsp, ldh, ndf, nex, ngh, nit, &
                                          npar, nst, nx
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: al(:), ex(:), exr(:), g(:), h(:,:),  &
                                          hc(:,:), par(:), sd(:), st(:),       &
                                          wa(:), x(:)
      Real (Kind=nag_wp)               :: zsp(4)
      Integer                          :: icount(6), isf(4), mr(7)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: max
!     .. Executable Statements ..
      Write (nout,*) 'G13AEF Example Program Results'
      Write (nout,*)

!     Skip heading in data file
      Read (nin,*)

!     Read in the problem size etc
      Read (nin,*) nx, kfc, c

!     Read in the orders
      Read (nin,*) mr(1:7)

!     Calculate NPAR and various array lengths
      npar = mr(1) + mr(3) + mr(4) + mr(6)
      iex = mr(3) + (mr(6)*mr(7)) + nx
      igh = mr(3) + (mr(6)*mr(7)) + npar + kfc
      ist = (mr(4)*mr(7)) + mr(2) + (mr(5)*mr(7)) + mr(3) +                    &
        max(mr(1),(mr(6)*mr(7)))
      iwa = ((nx+1+mr(1)+(mr(4)*mr(7))+mr(3)+(mr(6)*mr(7)))*8) + (9*npar)

      ldh = igh + 1
      Allocate (x(nx),par(npar),ex(iex),exr(iex),al(iex),g(igh),sd(igh),       &
        h(ldh,igh),st(ist),wa(iwa),hc(ldh,igh))

!     Read in data
      Read (nin,*) x(1:nx)

!     Read in initial values
      Read (nin,*) par(1:npar)

!     Read in control parameters
      Read (nin,*) kpiv, nit, kzsp
      If (kzsp==1) Then
        Read (nin,*) zsp(1:4)
      End If

!     Fit ARIMA model
      ifail = -1
      Call g13aef(mr,par,npar,c,kfc,x,nx,icount,ex,exr,al,iex,s,g,igh,sd,h,    &
        ldh,st,ist,nst,piv,kpiv,nit,itc,zsp,kzsp,isf,wa,iwa,hc,ifail)
      If (ifail/=0) Then
        If (ifail<7) Then
          Go To 100
        End If
      End If

!     Display results
      nex = icount(4)
      ndf = icount(5)
      ngh = icount(6)
      If (ifail==0) Then
        Write (nout,99998) 'Convergence was achieved after', itc, ' cycles'
      Else
        Write (nout,99998) 'Iterative process ran for', itc, ' cycles'
      End If
      Write (nout,*)
      Write (nout,*)                                                           &
        'Final values of the PAR parameters and the constant are as follows'
      Write (nout,99997) par(1:npar), c
      Write (nout,*)
      Write (nout,99996) 'Residual sum of squares is', s, '  with', ndf,       &
        ' degrees of freedom'
      Write (nout,*)
      Write (nout,*) 'The final values of ZSP were'
      Write (nout,99995) zsp(1:4)
      Write (nout,*)
      Write (nout,99999) 'The number of parameters estimated was', ngh
      Write (nout,*) '( backward forecasts, PAR and C, in that order )'
      Write (nout,*)
      Write (nout,*) 'The corresponding G array holds'
      Write (nout,99994) g(1:ngh)
      If ((ifail==0 .Or. ifail==9) .And. itc>0) Then
        Write (nout,*)
        Write (nout,*) 'The corresponding SD array holds'
        Write (nout,99994) sd(1:ngh)
        Write (nout,*)
        Flush (nout)
        ifail = 0
        Call x04caf('General',' ',ngh,ngh,h,ldh,'Corresponding H matrix',      &
          ifail)
        Write (nout,*)                                                         &
          'Holds second derivatives in the upper half (including the main ',   &
          'diagonal)'
        Write (nout,*) 'and correlation coefficients in the lower triangle'
      End If
      Write (nout,*)
      Write (nout,99993) 'EX, EXR, and AL each hold', nex,                     &
        ' values made up of', icount(1), ' back forecast(s),'
      Write (nout,99992) icount(2), ' differenced values, and'
      Write (nout,99992) icount(3), ' element(s) of reconstituted information'
      Write (nout,*)
      Write (nout,*) '  EX'
      Write (nout,99991) ex(1:nex)
      If (ifail==0 .Or. ifail==9) Then
        Write (nout,*)
        Write (nout,*) '  EXR'
        Write (nout,99991) exr(1:nex)
      End If
      If (ifail==0) Then
        Write (nout,*)
        Write (nout,*) '  AL'
        Write (nout,99991) al(1:nex)
      End If
      If (ifail==0 .Or. ifail==9) Then
        Write (nout,*)
        Write (nout,99998) 'The state set consists of', nst, ' values'
        Write (nout,99991) st(1:nst)
      End If

100   Continue

99999 Format (1X,A,I5)
99998 Format (1X,A,I3,A)
99997 Format (1X,4F10.4)
99996 Format (1X,A,F10.3,A,I4,A)
99995 Format (1X,4E15.4)
99994 Format (1X,10F9.4)
99993 Format (1X,A,I5,A,I5,A)
99992 Format (1X,I5,A)
99991 Format (1X,5F11.4)
    End Program g13aefe


g13affe.f90

    Program g13affe

!     G13AFF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: g13aff, nag_wp, x04abf, x04caf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: c, s
      Integer                          :: ifail, ipd, iqd, ires, itc, kfc,     &
                                          kpiv, ldcm, nadv, ndf, nit, npar,    &
                                          nppc, nres, nst, nx
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: cm(:,:), par(:), res(:), sd(:),      &
                                          st(:), x(:)
      Integer                          :: isf(4), mr(7)
!     .. Executable Statements ..
      Write (nout,*) 'G13AFF Example Program Results'
      Write (nout,*)

!     Skip heading in data file
      Read (nin,*)

!     Read in the problem size etc
      Read (nin,*) nx, kfc, c

!     Read in the orders
      Read (nin,*) mr(1:7)

!     Calculate NPAR and various array lengths
      npar = mr(1) + mr(3) + mr(4) + mr(6)
      nppc = npar + kfc
      iqd = mr(6)*mr(7) + mr(3)
      ipd = mr(4)*mr(7) + mr(1)
      ires = 15*iqd + 11*nx + 13*nppc + 8*ipd + 12 + 2*(iqd+nppc)**2

      ldcm = nppc
      Allocate (x(nx),par(npar),sd(nppc),cm(ldcm,nppc),st(nx),res(ires))

!     Read in data
      Read (nin,*) x(1:nx)

!     Read in initial values
      Read (nin,*) par(1:npar)

!     Read in control parameters
      Read (nin,*) kpiv, nit

!     Set the advisory channel to NOUT for monitoring information
      If (kpiv/=0) Then
        nadv = nout
        Call x04abf(1,nadv)
      End If

!     Fit ARIMA model
      ifail = -1
      Call g13aff(mr,par,npar,c,kfc,x,nx,s,ndf,sd,nppc,cm,ldcm,st,nst,kpiv,    &
        nit,itc,isf,res,ires,nres,ifail)
      If (ifail/=0) Then
        If (ifail<7) Then
          Go To 100
        End If
      End If

!     Display results
      If (ifail==0) Then
        Write (nout,99999) 'Convergence was achieved after', itc, ' cycles'
      Else
        Write (nout,99999) 'Iterative process ran for', itc, ' cycles'
      End If
      Write (nout,*)
      Write (nout,*)                                                           &
        'Final values of the PAR parameters and the constant are as follows'
      Write (nout,99996) par(1:npar), c
      Write (nout,*)
      Write (nout,99995) 'Residual sum of squares is', s, '  with', ndf,       &
        ' degrees of freedom'
      If ((ifail==0 .Or. ifail==9) .And. itc>0) Then
        Write (nout,*)
        Write (nout,*) 'The corresponding SD array holds'
        Write (nout,99994) sd(1:nppc)
        Write (nout,*)
        Flush (nout)
        ifail = 0
        Call x04caf('General',' ',nppc,nppc,cm,ldcm,                           &
          'The correlation matrix is as follows',ifail)
      End If
      If (ifail==0 .Or. ifail==9) Then
        Write (nout,*)
        Write (nout,99999) 'The residuals consist of', nres, ' values'
        Write (nout,99998) res(1:nres)
        Write (nout,*)
        Write (nout,99997) 'The state set consists of', nst, ' values'
        Write (nout,99993) st(1:nst)
      End If

100   Continue

99999 Format (1X,A,I4,A)
99998 Format (1X,5F10.4)
99997 Format (1X,A,I3,A)
99996 Format (1X,4F10.4)
99995 Format (1X,A,F10.3,A,I4,A)
99994 Format (1X,10F9.4)
99993 Format (1X,6F11.3)
    End Program g13affe


g13agfe.f90

    Program g13agfe

!     G13AGF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: g13agf, nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: c
      Integer                          :: ifail, npar, nst, nuv, nwa
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: anexr(:), anx(:), par(:), st(:),     &
                                          wa(:)
      Integer                          :: mr(7)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: max
!     .. Executable Statements ..
      Write (nout,*) 'G13AGF Example Program Results'
      Write (nout,*)

!     Skip heading in data file
      Read (nin,*)

!     Read in the problem size etc
      Read (nin,*) nuv, c

!     Read in the orders
      Read (nin,*) mr(1:7)

!     Calculate NPAR and various array lengths
      npar = mr(1) + mr(3) + mr(4) + mr(6)
      nst = mr(4)*mr(7) + mr(5)*mr(7) + mr(2) + mr(3) + max(mr(1),mr(6)*mr(7))
      nwa = 4*npar + 3*nst

      Allocate (st(nst),anx(nuv),anexr(nuv),wa(nwa),par(npar))

!     Read in parameter estimates
      Read (nin,*) par(1:npar)

!     Read in state set from G13AEF, G13AFF or previous call to G13AGF
      Read (nin,*) st(1:nst)

!     Read in new observations to update state set
      Read (nin,*) anx(1:nuv)

!     Update state set
      ifail = 0
      Call g13agf(st,nst,mr,par,npar,c,anx,nuv,anexr,wa,nwa,ifail)

!     Display results
      Write (nout,*) 'The updated state set array now holds the values'
      Write (nout,99999) st(1:nst)
      Write (nout,*)
      Write (nout,99998) 'The residuals corresponding to the', nuv
      Write (nout,*) 'values used to update the system are'
      Write (nout,99999) anexr(1:nuv)

99999 Format (1X,8F8.4)
99998 Format (1X,A,I3,A)
    End Program g13agfe


g13ahfe.f90

    Program g13ahfe

!     G13AHF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: g13ahf, nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: c, rms
      Integer                          :: ifail, nfv, npar, nst, nwa
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: fsd(:), fva(:), par(:), st(:), wa(:)
      Integer                          :: mr(7)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: max
!     .. Executable Statements ..
      Write (nout,*) 'G13AHF Example Program Results'
      Write (nout,*)

!     Skip heading in data file
      Read (nin,*)

!     Read in problem size etc
      Read (nin,*) nfv, c

!     Read in the orders
      Read (nin,*) mr(1:7)

!     Calculate NPAR and various array lengths
      npar = mr(1) + mr(3) + mr(4) + mr(6)
      nst = mr(4)*mr(7) + mr(5)*mr(7) + mr(2) + mr(3) + max(mr(1),mr(6)*mr(7))
      nwa = 4*npar + 3*nst

      Allocate (fsd(nfv),fva(nfv),par(npar),st(nst),wa(nwa))

!     Read in parameter estimates
      Read (nin,*) par(1:npar)

!     Read in state set from G13AEF, G13AFF or G13AGF
      Read (nin,*) st(1:nst)

!     Read in residual variance
      Read (nin,*) rms

!     Produce forecasts
      ifail = 0
      Call g13ahf(st,nst,mr,par,npar,c,rms,nfv,fva,fsd,wa,nwa,ifail)

      Write (nout,99998) 'The required', nfv,                                  &
        ' forecast values are as follows'
      Write (nout,99999) fva(1:nfv)
      Write (nout,*)
      Write (nout,*)                                                           &
        'The standard deviations corresponding to the forecasts are'
      Write (nout,99999) fsd(1:nfv)

99999 Format (1X,8F8.4)
99998 Format (1X,A,I3,A)
    End Program g13ahfe


g13ajfe.f90

    Program g13ajfe

!     G13AJF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: g13ajf, nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: c, rms
      Integer                          :: i, ifail, ifv, ist, iw, kfc, nfv,    &
                                          npar, nst, nx, pp, qp
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: fsd(:), fva(:), par(:), st(:), w(:), &
                                          x(:)
      Integer                          :: isf(4), mr(7)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: max
!     .. Executable Statements ..
      Write (nout,*) 'G13AJF Example Program Results'
      Write (nout,*)

!     Skip heading in data file
      Read (nin,*)

!     Read in problem size etc
      Read (nin,*) nx, nfv, kfc, c

!     Read in the orders
      Read (nin,*) mr(1:7)

!     Calculate NPAR and various array lengths
      npar = mr(1) + mr(3) + mr(4) + mr(6)
      ist = mr(4) + mr(7) + mr(2) + mr(5) + mr(3) + max(mr(1),mr(6)*mr(7))
      ifv = max(1,nfv)
      qp = mr(6)*mr(7) + mr(3)
      pp = mr(4)*mr(7) + mr(1)
      iw = 6*nx + 5*npar + qp*(qp+11) + 3*pp + 7
      Allocate (par(npar),x(nx),st(ist),fva(ifv),fsd(ifv),w(iw))

!     Read in data
      Read (nin,*) x(1:nx)

!     Read in parameter estimates
      Read (nin,*) par(1:npar)

      ifail = 0
      Call g13ajf(mr,par,npar,c,kfc,x,nx,rms,st,ist,nst,nfv,fva,fsd,ifv,isf,w, &
        iw,ifail)

!     Display results
      Write (nout,99999) 'The residual mean square is ', rms
      Write (nout,*)
      Write (nout,99998) 'The state set consists of ', nst, ' values'
      Write (nout,99997) st(1:nst)
      Write (nout,*)
      Write (nout,99996) 'The ', nfv,                                          &
        ' forecast values and standard errors are -'
      Write (nout,99995)(fva(i),fsd(i),i=1,nfv)

99999 Format (1X,A,F9.2)
99998 Format (1X,A,I1,A)
99997 Format (1X,4F11.4)
99996 Format (1X,A,I2,A)
99995 Format (10X,2F10.2)
    End Program g13ajfe


g13amfe.f90

    Program g13amfe

!     G13AMF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: g13amf, nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: ad, dv
      Integer                          :: i, ifail, itype, ival, k, mode, n,   &
                                          nf, p
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: fse(:), fv(:), init(:), param(:),    &
                                          r(:), res(:), y(:), yhat(:)
!     .. Executable Statements ..
      Write (nout,*) 'G13AMF Example Program Results'
      Write (nout,*)

!     Skip headings in data file
      Read (nin,*)

!     Read in the initial arguments and check array sizes
      Read (nin,*) mode, itype, n, nf

      Allocate (y(n),fv(nf),fse(nf),yhat(n),res(n))

!     Read in data
      Read (nin,*) y(1:n)

!     Read in the ITYPE dependent arguments (skipping headings)
      Select Case (itype)
      Case (1)
!       Single exponential smoothing
        Allocate (param(1))
        Read (nin,*) param(1)
        p = 0
        ival = 1

      Case (2)
!       Brown double exponential smoothing
        Allocate (param(2))
        Read (nin,*) param(1), param(2)
        p = 0
        ival = 2

      Case (3)
!       Linear Holt smoothing
        Allocate (param(3))
        Read (nin,*) param(1), param(2), param(3)
        p = 0
        ival = 2

      Case Default
!       Additive or multiplicative Holt-Winter smoothing
        Allocate (param(4))
        Read (nin,*) param(1), param(2), param(3), param(4), p
        ival = p + 2
      End Select

      Allocate (init(ival),r(p+13))

!     Read in the MODE dependent arguments (skipping headings)
      Select Case (mode)
      Case (0)
!       User supplied initial values
        Read (nin,*) init(1:ival)
      Case (1)
!       Continuing from a previously saved R
        Read (nin,*) r(1:(p+13))
      Case (2)
!       Initial values calculated from first K observations
        Read (nin,*) k
      End Select

!     Call the library routine
      ifail = 0
      Call g13amf(mode,itype,p,param,n,y,k,init,nf,fv,fse,yhat,res,dv,ad,r,    &
        ifail)

!     Display output
      Write (nout,*) 'Initial values used:'
      Write (nout,99997)(i,init(i),i=1,ival)
      Write (nout,*)
      Write (nout,99999) 'Mean Deviation     = ', dv
      Write (nout,99999) 'Absolute Deviation = ', ad
      Write (nout,*)
      Write (nout,*) '         Observed      1-Step'
      Write (nout,*) ' Period   Values      Forecast      Residual'
      Write (nout,*)
      Write (nout,99998)(i,y(i),yhat(i),res(i),i=1,n)
      Write (nout,*)
      Write (nout,*) '         Forecast     Standard'
      Write (nout,*) ' Period   Values       Errors'
      Write (nout,*)
      Write (nout,99996)(n+i,fv(i),fse(i),i=1,nf)

99999 Format (A,E12.4)
99998 Format (I4,1X,F12.3,1X,F12.3,1X,F12.3)
99997 Format (I4,1X,F12.3)
99996 Format (I4,1X,F12.3,1X,F12.3)
    End Program g13amfe


g13asfe.f90

    Program g13asfe

!     G13ASF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: g13aff, g13asf, nag_wp, x04abf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: iset = 1, nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: c, chi, s, siglev
      Integer                          :: idf, ifail, ires, ishow, itc, kfc,   &
                                          kpiv, ldcm, ldrcm, liw, lwork, m, n, &
                                          nadv, ndf, nit, npar, nppc, nst, nx, &
                                          pp, qp
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: cm(:,:), par(:), r(:), rcm(:,:),     &
                                          sd(:), st(:), v(:), work(:), x(:)
      Integer                          :: isf(4), mr(7)
      Integer, Allocatable             :: iw(:)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: max
!     .. Executable Statements ..
      Write (nout,*) 'G13ASF Example Program Results'
      Write (nout,*)
      Flush (nout)

!     Skip heading in data file
      Read (nin,*)

!     Read in problem size
      Read (nin,*) nx, kfc, c

!     Read in the orders
      Read (nin,*) mr(1:7)

!     Calculate NPAR and various array sizes
      npar = mr(1) + mr(3) + mr(4) + mr(6)
      nppc = npar + kfc
      ldcm = nppc
      pp = mr(1) + mr(4)*mr(7)
      qp = mr(3) + mr(6)*mr(7)
      ires = 15*qp + 11*nx + 13*nppc + 8*pp + 12 + 2*(qp+nppc)**2

      Allocate (par(npar),x(nx),sd(nppc),cm(ldcm,nppc),st(nx),v(ires))

!     Read in data
      Read (nin,*) x(1:nx)

!     Read in initial values
      Read (nin,*) par(1:npar)

!     Read in control parameters
      Read (nin,*) kpiv, nit

!     Set the advisory channel to NOUT for monitoring information
      If (kpiv/=0) Then
        nadv = nout
        Call x04abf(iset,nadv)
      End If

!     Fit ARIMA model
      ifail = -1
      Call g13aff(mr,par,npar,c,kfc,x,nx,s,ndf,sd,nppc,cm,ldcm,st,nst,kpiv,    &
        nit,itc,isf,v,ires,n,ifail)
      If (ifail/=0) Then
        If (ifail/=9) Then
          Go To 100
        End If
      End If

!     Read in parameters for G13ASF
      Read (nin,*) m, ishow

      ldrcm = m
      liw = max(mr(1),mr(3),mr(4),mr(6))
      lwork = npar*(n+npar+1) + liw*max(mr(7),1) + m
      Allocate (r(m),rcm(ldrcm,m),iw(liw),work(lwork))

!     Set the advisory channel to NOUT for monitoring information
!     if it has not been set previously
      If (ishow/=0 .And. kpiv==0) Then
        nadv = nout
        Call x04abf(iset,nadv)
      End If

!     Perform diagnostic checks
      ifail = 0
      Call g13asf(n,v,mr,m,par,npar,ishow,r,rcm,ldrcm,chi,idf,siglev,iw,liw,   &
        work,lwork,ifail)

100   Continue

    End Program g13asfe


g13aufe.f90

    Program g13aufe

!     G13AUF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: g13auf, nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Integer                          :: i, ifail, m, n, ngrps
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: mean(:), y(:), z(:)
!     .. Executable Statements ..
      Write (nout,*) 'G13AUF Example Program Results'
      Write (nout,*)

!     Skip heading in data file
      Read (nin,*)

!     Read in the problem size
      Read (nin,*) n, m

      ngrps = n/m

      Allocate (z(n),y(ngrps),mean(ngrps))

!     Read in data
      Read (nin,*) z(1:n)

!     Calculate summary statistics
      ifail = 0
      Call g13auf(n,z,m,ngrps,'RANGE',y,mean,ifail)

!     Display title
      Write (*,*) '     Mean      Range'
      Write (*,*) '   -------------------'
      Do i = 1, ngrps
        Write (nout,99999) mean(i), y(i)
      End Do

99999 Format (2(1X,F10.3))
    End Program g13aufe


g13awfe.f90

    Program g13awfe
!     G13AWF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: g01ewf, g13awf, nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: pvalue, ts
      Integer                          :: ifail, method, n, nsamp, p, type
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: y(:)
      Integer                          :: state(1)
!     .. Executable Statements ..

!     .. Executable Statements ..
      Write (nout,*) 'G13AWF Example Program Results'
      Write (nout,*)

!     Skip heading in data file
      Read (nin,*)

!     Read in the problem size, test type, order of the AR process
      Read (nin,*) n, type, p

!     Allocate memory
      Allocate (y(n))

!     Read in the time series
      Read (nin,*) y(1:n)

!     Calculate the Dickey-Fuller test statistic
      ifail = 0
      ts = g13awf(type,p,n,y,ifail)

!     Get the associated p-value using the look-up method
      method = 1
      ifail = -1
      pvalue = g01ewf(method,type,n,ts,nsamp,state,ifail)

      If (ifail==0 .Or. ifail==201) Then
!       Display the results
        Write (nout,'(A,F6.3)') 'Dickey-Fuller test statistic     = ', ts
        Write (nout,'(A,F6.3)') 'associated p-value               = ', pvalue
      End If

    End Program g13awfe


g13bafe.f90

    Program g13bafe

!     G13BAF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: g13ajf, g13baf, nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: cx, cy, rms
      Integer                          :: i, idd, ifail, ifv, ii, ij, ipar,    &
                                          iqxd, ist, iw, nb, nmr, npar, nparx, &
                                          nst, nwa, nx, ny, pp, qp, sy
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: b(:), fsd(:), fva(:), par(:),        &
                                          parx(:), st(:), w(:), wa(:), x(:),   &
                                          y(:)
      Integer                          :: isf(4), mrx(7)
      Integer, Allocatable             :: mr(:)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: max, min, mod
!     .. Executable Statements ..
      Write (nout,*) 'G13BAF Example Program Results'
      Write (nout,*)

!     Skip heading in data file
      Read (nin,*)

!     Read in the problem size
      Read (nin,*) nx

!     Read univariate ARIMA for series
      Read (nin,*) mrx(1:7)
      Read (nin,*) cx

!     Calculate number of backforecasts required
      iqxd = mrx(3) + mrx(6)*mrx(7)
      If (iqxd/=0) Then
        nmr = 14
      Else
        nmr = 7
      End If

!     Back forecasts will be stored in first IQXD elements
!     of Y, the series will be stored in last NX elements of
!     Y, so calculate start point for the series
      sy = iqxd + 1

!     Calculate length of series with back forecasts
      ny = nx + iqxd

      Allocate (y(ny),mr(nmr))

!     Read in the series into the end of Y
      Read (nin,*) y(sy:ny)

!     Get back forecasts if required
      If (iqxd/=0) Then

!       Calculate number of parameters in ARIMA model
        nparx = mrx(1) + mrx(3) + mrx(4) + mrx(6)

        ist = mrx(4) + mrx(7) + mrx(2) + mrx(5) + mrx(3) +                     &
          max(mrx(1),mrx(6)*mrx(7))
        ifv = max(1,iqxd)
        qp = mrx(6)*mrx(7) + mrx(3)
        pp = mrx(4)*mrx(7) + mrx(1)
        iw = 6*nx + 5*nparx + qp*(qp+11) + 3*pp + 7
        Allocate (parx(nparx),x(nx),st(ist),fva(ifv),fsd(ifv),w(iw))

!       Read in initial values
        Read (nin,*) parx(1:nparx)

!       Reverse series
        x(nx:1:-1) = y(sy:ny)

!       Possible sign reversal for ARIMA constant
        idd = mrx(2) + mrx(5)
        If (mod(idd,2)/=0) Then
          cx = -cx
        End If

!       Calculate back forecasts
        ifail = 0
        Call g13ajf(mrx,parx,nparx,cx,1,x,nx,rms,st,ist,nst,iqxd,fva,fsd,ifv,  &
          isf,w,iw,ifail)

!       Move back forecasts into Y, in reverse order
        y(1:iqxd) = fva(iqxd:1:-1)

!       Reverse sign for ARIMA constant back again
        If (mod(idd,2)/=0) Then
          cx = -cx
        End If
      End If

!     Read model by which to filter series
      Read (nin,*) mr(1:7)

!     Calculate NPAR
      ipar = mr(1) + mr(3) + mr(4) + mr(6)
      npar = ipar + nparx

      Allocate (par(npar))

!     Read in initial parameter values
      Read (nin,*) par(1:ipar)

      If (iqxd/=0) Then
!       Move ARIMA series into MR
        mr(8:14) = mrx(1:7)

!       Move parameters of ARIMA for Y into PAR
        par((ipar+1):(ipar+nparx)) = parx(1:nparx)
      End If

!     Move constant
      cy = cx

!     Set parameters for call to filter routine G13BAF
      If (nmr==14) Then
        nwa = mr(3) + mr(6)*mr(7) + mr(8) + mr(9) + (mr(11)+mr(12))*mr(14)
        nwa = nwa*(nwa+2)
        nb = ny + max(mr(3)+mr(6)*mr(7),mr(1)+mr(2)+(mr(4)+mr(5))*mr(7))
      Else
        nwa = 1
        nb = ny
      End If
      Allocate (wa(nwa),b(nb))

!     Filter series by call to G13BAF
      ifail = 0
      Call g13baf(y,ny,mr,nmr,par,npar,cy,wa,nwa,b,nb,ifail)

!     Display results
      If (iqxd/=0) Then
        Write (nout,*) '                 Original        Filtered'
        Write (nout,*) 'Backforecasts    y-series         series'
        ij = -iqxd
        Do i = 1, iqxd
          Write (nout,99999) ij, y(i), b(i)
          ij = ij + 1
        End Do
        Write (nout,*)
      End If
      Write (nout,*)                                                           &
        '       Filtered        Filtered        Filtered        Filtered'
      Write (nout,*)                                                           &
        '        series          series          series          series'
      Do i = iqxd + 1, ny, 4
        Write (nout,99998)(ii-iqxd,b(ii),ii=i,min(ny,i+3))
      End Do

99999 Format (1X,I8,F17.4,F15.4)
99998 Format (1X,I5,F9.4,I7,F9.4,I7,F9.4,I7,F9.4)
    End Program g13bafe


g13bbfe.f90

    Program g13bbfe

!     G13BBF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: g13ajf, g13bbf, nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: cx, cy, rms
      Integer                          :: i, idd, ifail, ifv, ii, ij, ipar,    &
                                          iqxd, ist, iw, iwa, nb, nmr, npar,   &
                                          nparx, nst, nx, ny, pp, qp, sy
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: b(:), fsd(:), fva(:), par(:),        &
                                          parx(:), st(:), w(:), wa(:), x(:),   &
                                          y(:)
      Integer                          :: isf(4), mrx(7)
      Integer, Allocatable             :: mr(:)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: max, min, mod
!     .. Executable Statements ..
      Write (nout,*) 'G13BBF Example Program Results'
      Write (nout,*)

!     Skip heading in data file
      Read (nin,*)

!     Read in problem size
      Read (nin,*) nx

!     Read univariate ARIMA for series
      Read (nin,*) mrx(1:7)
      Read (nin,*) cx

!     Calculate number of backforecasts required
      iqxd = mrx(3) + mrx(6)*mrx(7)
      If (iqxd/=0) Then
        nmr = 10
      Else
        nmr = 3
      End If

!     Back forecasts will be stored in first IQXD elements
!     of Y, the series will be stored in last NX elements of
!     Y, so calculate start point for the series
      sy = iqxd + 1

!     Calculate length of series with back forecasts
      ny = nx + iqxd

      Allocate (y(ny),mr(nmr))

!     Read in series
      Read (nin,*) y(sy:ny)

!     Get back forecasts if required
      If (iqxd/=0) Then

!       Calculate number of parameters in ARIMA model
        nparx = mrx(1) + mrx(3) + mrx(4) + mrx(6)

        ist = mrx(4) + mrx(7) + mrx(2) + mrx(5) + mrx(3) +                     &
          max(mrx(1),mrx(6)*mrx(7))
        ifv = max(1,iqxd)
        qp = mrx(6)*mrx(7) + mrx(3)
        pp = mrx(4)*mrx(7) + mrx(1)
        iw = 6*nx + 5*nparx + qp*(qp+11) + 3*pp + 7
        Allocate (parx(nparx),x(nx),st(ist),fva(ifv),fsd(ifv),w(iw))

!       Read in initial values
        Read (nin,*) parx(1:nparx)

!       Reverse series
        x(nx:1:-1) = y(sy:ny)

!       Possible sign reversal for ARIMA constant
        idd = mrx(2) + mrx(5)
        If (mod(idd,2)/=0) Then
          cx = -cx
        End If

!       Calculate back forecasts
        ifail = 0
        Call g13ajf(mrx,parx,nparx,cx,0,x,nx,rms,st,ist,nst,iqxd,fva,fsd,ifv,  &
          isf,w,iw,ifail)

!       Move back forecasts into Y, in reverse order
        y(1:iqxd) = fva(iqxd:1:-1)

!       Reverse sign for ARIMA constant back again
        If (mod(idd,2)/=0) Then
          cx = -cx
        End If
      End If

!     Read model by which to filter series
      Read (nin,*) mr(1:3)

!     Calculate NPAR
      ipar = mr(2) + mr(3) + 1
      npar = ipar + nparx

      Allocate (par(npar))

!     Read in initial parameter values
      Read (nin,*) par(1:ipar)

      If (iqxd/=0) Then
!       Move ARIMA for series into MR
        mr(4:10) = mrx(1:7)

!       Move parameters of ARIMA for Y into PAR
        par((ipar+1):(ipar+nparx)) = parx(1:nparx)
      End If

!     Move constant
      cy = cx

!     Set parameters for call to filter routine G13BBF
      If (nmr==10) Then
        iwa = mr(3) + mr(4) + mr(5) + (mr(7)+mr(8))*mr(10)
        iwa = npar + iwa*(iwa+2)
        nb = ny + max(mr(1)+mr(2),mr(3))
      Else
        iwa = mr(1) + npar
        nb = ny
      End If

      Allocate (wa(iwa),b(nb))

!     Filter series by call to G13BBF
      ifail = 0
      Call g13bbf(y,ny,mr,nmr,par,npar,cy,wa,iwa,b,nb,ifail)

!     Display results
      If (iqxd/=0) Then
        Write (nout,*) '                  Original        Filtered'
        Write (nout,*) ' Backforecasts    y-series         series'
        ij = -iqxd
        Do i = 1, iqxd
          Write (nout,99999) ij, y(i), b(i)
          ij = ij + 1
        End Do
        Write (nout,*)
      End If
      Write (nout,*)                                                           &
        '        Filtered        Filtered        Filtered        Filtered'
      Write (nout,*)                                                           &
        '         series          series          series          series'
      Do i = iqxd + 1, ny, 4
        Write (nout,99998)(ii-iqxd,b(ii),ii=i,min(ny,i+3))
      End Do

99999 Format (1X,I8,F17.1,F16.1)
99998 Format (1X,I5,F10.1,I6,F10.1,I6,F10.1,I6,F10.1)
    End Program g13bbfe


g13bcfe.f90

    Program g13bcfe

!     G13BCF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: g13bcf, nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: r0xy, r0yx, statxy, statyx, sxy, syx
      Integer                          :: i, ifail, nl, nxy
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: rxy(:), ryx(:), x(:), y(:)
!     .. Executable Statements ..
      Write (nout,*) 'G13BCF Example Program Results'
      Write (nout,*)

!     Skip heading in data file
      Read (nin,*)

!     Read series length and number of lags
      Read (nin,*) nxy, nl

      Allocate (x(nxy),y(nxy),rxy(nl),ryx(nl))

!     Read series
      Read (nin,*) x(1:nxy)
      Read (nin,*) y(1:nxy)

!     Call routine to calculate cross correlations between X and Y
      ifail = 0
      Call g13bcf(x,y,nxy,nl,sxy,r0xy,rxy,statxy,ifail)

!     Call routine to calculate cross correlations between Y and X
      ifail = 0
      Call g13bcf(y,x,nxy,nl,syx,r0yx,ryx,statyx,ifail)

!     Display results
      Write (nout,*) '                           Between        Between'
      Write (nout,*) '                           X and Y        Y and X'
      Write (nout,*)
      Write (nout,99999) 'Standard deviation ratio', sxy, syx
      Write (nout,*)
      Write (nout,*) 'Cross correlation at lag'
      Write (nout,99999) '                       0', r0xy, r0yx
      Write (nout,99998)(i,rxy(i),ryx(i),i=1,nl)
      Write (nout,*)
      Write (nout,99997) 'Test statistic          ', statxy, statyx

99999 Format (1X,A,F10.4,F15.4)
99998 Format (21X,I4,F10.4,F15.4)
99997 Format (1X,A,F10.4,F15.4)
    End Program g13bcfe


g13bdfe.f90

    Program g13bdfe

!     G13BDF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: g13bdf, nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: r0, s
      Integer                          :: ifail, iwa, nl, nwds
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: r(:), wa(:), wds(:)
      Integer                          :: isf(2), nna(3)
!     .. Executable Statements ..
      Write (nout,*) 'G13BDF Example Program Results'
      Write (nout,*)

!     Skip heading in data file
      Read (nin,*)

!     Read in problem size and cross-correlation at lag 0
      Read (nin,*) nl, r0

      Allocate (r(nl))

!     Read in rest of cross-correlations
      Read (nin,*) r(1:nl)

!     Read in transfer function model orders
      Read (nin,*) nna(1:3)

!     Read in standard deviation ratio
      Read (nin,*) s

      nwds = nna(2) + nna(3) + 1
      iwa = nna(3)*(nna(3)+1)
      Allocate (wa(iwa),wds(nwds))

!     Calculate parameter estimates
      ifail = 0
      Call g13bdf(r0,r,nl,nna,s,nwds,wa,iwa,wds,isf,ifail)

!     Display results
      Write (nout,99999) 'Success/failure indicator', isf(1), isf(2)
      Write (nout,*)
      Write (nout,99999) 'Transfer function model B, Q, P =', nna(1:3)
      Write (nout,*)
      Write (nout,*) 'Parameter initial estimates'
      Write (nout,99998) wds(1:nwds)

99999 Format (1X,A,3I4)
99998 Format (1X,4F10.4)
    End Program g13bdfe


g13befe.f90

    Program g13befe

!     G13BEF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: g13bef, nag_wp, x04abf, x04caf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: iset = 1, nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: d, s
      Integer                          :: dp, i, ifail, imwa, inc, isttf, itc, &
                                          iwa, kef, kfc, kpriv, kzef, kzsp,    &
                                          ldcm, ldxxy, mx, nadv, ncd, nce,     &
                                          ncf, ncg, ndf, ndv, nis, nit, npara, &
                                          nser, nsttf, nxxy, qp, qx, smx
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: cm(:,:), para(:), res(:), sd(:),     &
                                          sttf(:), wa(:), xxy(:,:)
      Real (Kind=nag_wp)               :: zsp(4)
      Integer                          :: mr(7)
      Integer, Allocatable             :: mt(:,:), mwa(:)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: max, sum
!     .. Executable Statements ..
      Write (nout,*) 'G13BEF Example Program Results'
      Write (nout,*)

!     Skip heading in data file
      Read (nin,*)

!     Read in problem size
      Read (nin,*) kzef, kfc, nxxy, nser, kef, nit, kzsp, kpriv
      If (kzsp/=0) Then
        Read (nin,*) zsp
      End If

!     Number of input series
      nis = nser - 1

!     Set the advisory channel to NOUT for monitoring information
      If (kpriv/=0) Then
        nadv = nout
        Call x04abf(iset,nadv)
      End If

      Allocate (mt(4,nser))

!     Read in orders
      Read (nin,*) mr(1:7)

!     Read in transfer function
      Do i = 1, nis
        Read (nin,*) mt(1:4,i)
      End Do

!     Calculate NPARA and various other quantities required
!     for calculate array sizes
      npara = 0
      ncg = 0
      qx = 0
      smx = 0
      ncf = nser
      inc = 1
      Do i = 1, nis
        npara = npara + mt(2,i) + mt(3,i)
        If (mt(4,i)>1) Then
          ncg = ncg + sum(mt(1:3,i))
          If (mt(4,i)==3) Then
            mx = max(mt(1,i)+mt(2,i),mt(3,i))
            qx = max(qx,mx)
            smx = smx + mx
          End If
        Else If (mt(4,i)==1 .And. kef==3) Then
          If (mt(3,i)>0) Then
            ncf = ncf + 1
          End If
          inc = inc + 1
        End If
      End Do
      npara = npara + mr(1) + mr(3) + mr(4) + mr(6) + nser

!     Calculate size of arrays
      isttf = mr(4)*mr(7) + mr(2) + mr(5)*mr(7) + mr(3) +                      &
        max(mr(1),mr(6)*mr(7)) + ncg
      ldxxy = nxxy
      ldcm = npara
      qp = mr(3) + mr(6)*mr(7)
      dp = mr(2) + mr(5)*mr(7)
      If (mr(3)>0 .And. kef>1) Then
        inc = inc + 1
      End If
      If (kfc>0 .And. kef==3) Then
        inc = inc + 1
      End If
      qx = qp
      ncd = npara + kfc + smx
      If (mr(1)>0) Then
        ncf = ncf + inc
      End If
      If (mr(3)>0) Then
        ncf = ncf + inc
      End If
      If (mr(4)>0) Then
        ncf = ncf + inc
      End If
      If (mr(6)>0) Then
        ncf = ncf + inc
      End If
      If (qx>0) Then
        ncf = ncf + 1
      End If
      If (kfc>0) Then
        ncf = ncf + 1
      End If
      ncd = ncd + qx
      nce = nxxy + dp + 6*qx
      iwa = 2*ncd**2 + nce*(ncf+4)
      iwa = 2*iwa
      imwa = 16*nser + 7*ncd + 3*npara + 3*kfc + 27

      Allocate (xxy(ldxxy,nser),para(npara),sd(npara),cm(ldcm,npara),          &
        res(nxxy),sttf(isttf),wa(iwa),mwa(imwa))

!     Read in rest of data
      Read (nin,*) para(1:npara)
      Read (nin,*)(xxy(i,1:nser),i=1,nxxy)

      ifail = -1
      Call g13bef(mr,nser,mt,para,npara,kfc,nxxy,xxy,ldxxy,kef,nit,kzsp,zsp,   &
        itc,sd,cm,ldcm,s,d,ndf,kzef,res,sttf,isttf,nsttf,wa,iwa,mwa,imwa,      &
        kpriv,ifail)
      If (ifail/=0) Then
        If (ifail/=8 .And. ifail/=9) Then
          Go To 100
        End If
      End If

!     Display results
      Write (nout,99999) 'The number of iterations carried out is', itc
      Write (nout,*)
      If (ifail/=8 .And. ifail/=9) Then
        Write (nout,*)                                                         &
          'Final values of the parameters and their standard deviations'
        Write (nout,*)
        Write (nout,*) '   I            PARA(I)                 SD'
        Write (nout,*)
        Write (nout,99998)(i,para(i),sd(i),i=1,npara)
        Write (nout,*)
        Flush (nout)
        ifail = 0
        Call x04caf('General',' ',npara,npara,cm,ldcm,                         &
          'The correlation matrix is',ifail)
      End If
      Write (nout,*)
      Write (nout,*) 'The residuals and the z and n values are'
      Write (nout,*)
      Write (nout,*) '   I         RES(I)          z(t)           n(t)'
      Write (nout,*)
      ndv = nxxy - mr(2) - mr(5)*mr(7)
      Do i = 1, nxxy
        If (i<=ndv) Then
          Write (nout,99997) i, res(i), xxy(i,1:nser)
        Else
          Write (nout,99996) i, xxy(i,1:nser)
        End If
      End Do
      If (mr(2)/=0 .Or. mr(5)/=0) Then
        Write (nout,*)
        Write (nout,*)                                                         &
          '** Note that the residuals relate to differenced values **'
      End If
      Write (nout,*)
      Write (nout,99995) 'The state set consists of', nsttf, ' values'
      Write (nout,*)
      Write (nout,99994) sttf(1:nsttf)
      Write (nout,*)
      Write (nout,99999) 'The number of degrees of freedom is', ndf

100   Continue

99999 Format (1X,A,I4)
99998 Format (1X,I4,2F20.6)
99997 Format (1X,I4,3F15.3)
99996 Format (1X,I4,F30.3,F15.3)
99995 Format (1X,A,I4,A)
99994 Format (1X,6F10.4)
    End Program g13befe


g13bgfe.f90

    Program g13bgfe

!     G13BGF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: g13bgf, nag_wp, x04caf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Integer                          :: i, ifail, iwa, kzef, ldxxyn, ncc,    &
                                          nis, nnv, npara, nser, nsttf
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: para(:), res(:), sttf(:), wa(:),     &
                                          xxyn(:,:)
      Integer                          :: mr(7)
      Integer, Allocatable             :: mt(:,:)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: max
!     .. Executable Statements ..
      Write (nout,*) 'G13BGF Example Program Results'
      Write (nout,*)

!     Skip heading in data file
      Read (nin,*)

!     Read in the problem size
      Read (nin,*) nsttf, nser, nnv, kzef

!     Number of input series
      nis = nser - 1

!     Read in orders
      Read (nin,*) mr(1:7)

      ldxxyn = nnv
      Allocate (mt(4,nser))

!     Read in transfer function
      Do i = 1, nis
        Read (nin,*) mt(1:4,i)
      End Do

!     Calculate NPARA
      npara = 0
      Do i = 1, nis
        npara = npara + mt(2,i) + mt(3,i)
      End Do
      npara = npara + mr(1) + mr(3) + mr(4) + mr(6) + nser

      ldxxyn = nnv
      ncc = 4*(mr(1)+mr(3)+mr(4)+mr(6))
      iwa = nnv + 2*nsttf + max(nnv,nsttf) + max(nnv,ncc)
      Allocate (sttf(nsttf),xxyn(ldxxyn,nser),res(nnv),para(npara),wa(iwa))

!     Read in state set
      Read (nin,*) sttf(1:nsttf)

!     Read in parameters
      Read (nin,*) para(1:npara)

!     Read in new observations
      Read (nin,*)(xxyn(i,1:nser),i=1,nnv)

      ifail = 0
      Call g13bgf(sttf,nsttf,mr,nser,mt,para,npara,nnv,xxyn,ldxxyn,kzef,res,   &
        wa,iwa,ifail)

!     Display results
      Write (nout,*) 'The updated state set'
      Write (nout,99999) sttf(1:nsttf)
      Write (nout,*)
      Write (nout,*) 'The residuals (after differencing)'
      Write (nout,99998)(i,res(i),i=1,nnv)
      Write (nout,*)
      Flush (nout)
      ifail = 0
      Call x04caf('General',' ',nnv,nser,xxyn,ldxxyn,                          &
        'The values of z(t) and n(t)',ifail)
      Write (nout,99997) 'The first ', nis,                                    &
        ' columns hold the z(t) and the last column the n(t)'

99999 Format (1X,6F10.4)
99998 Format (1X,I4,F10.4)
99997 Format (1X,A,I0,A)
    End Program g13bgfe


g13bhfe.f90

    Program g13bhfe

!     G13BHF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: g13bhf, nag_wp, x04caf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Integer                          :: i, ifail, iwa, kzef, ldparx, ldxxyn, &
                                          ncf, ncg, nch, nci, ncj, nck, ncl,   &
                                          ncm, nfv, nis, npara, nparax, nser,  &
                                          nsttf
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: fsd(:), fva(:), para(:), parx(:,:),  &
                                          rmsxy(:), sttf(:), wa(:), xxyn(:,:)
      Integer                          :: mr(7)
      Integer, Allocatable             :: mrx(:,:), mt(:,:)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: max
!     .. Executable Statements ..
      Write (nout,*) 'G13BHF Example Program Results'
      Write (nout,*)

!     Skip heading in data file
      Read (nin,*)

!     Read in problem size
      Read (nin,*) nsttf, nser, nfv, kzef

!     Number of input series
      nis = nser - 1

!     Read in the orders
      Read (nin,*)(mr(i),i=1,7)

      Allocate (mt(4,nser))

!     Read in transfer function
      Do i = 1, nis
        Read (nin,*) mt(1:4,i)
      End Do

!     Calculate NPARA
      npara = 0
      Do i = 1, nis
        npara = npara + mt(2,i) + mt(3,i)
      End Do
      npara = npara + mr(1) + mr(3) + mr(4) + mr(6) + nser

      ldxxyn = nfv
      ldparx = npara
      Allocate (para(npara),sttf(nsttf),xxyn(ldxxyn,nser),mrx(7,nser),         &
        parx(ldparx,nser),rmsxy(nser),fva(nfv),fsd(nfv))

!     Read in rest of data
      Read (nin,*) sttf(1:nsttf)
      Read (nin,*) para(1:npara)
      Read (nin,*)(xxyn(i,1:nis),i=1,nfv)
      ncf = mr(1) + mr(3) + mr(4) + mr(6)
      Do i = 1, nis
        Read (nin,*) mrx(1:7,i)
        nparax = mrx(1,i) + mrx(3,i) + mrx(4,i) + mrx(6,i)
        ncf = max(ncf,nparax)
        Read (nin,*) parx(1:nparax,i)
      End Do
      Read (nin,*) rmsxy(1:nser)

!     Calculate size of workspace array
      ncg = 0
      nch = 0
      nci = 0
      Do i = 1, nis
        If (mt(4,i)>1) Then
          ncg = max(ncg,mrx(1,i))
          nch = max(nch,mt(1,i)+mrx(3,i))
          nci = max(nci,mt(1,i)+mrx(3,i)+mrx(1,i))
        End If
        ncf = max(ncf,mrx(1,i)+mrx(3,i)+mrx(4,i)+mrx(6,i))
      End Do
      ncj = nci + 1
      nck = nfv + max(ncg,nch)
      ncl = max(nsttf,ncf,ncj,nck)
      ncm = max(nsttf+4*ncf,ncl)
      iwa = ncm + 3*ncl + nfv
      Allocate (wa(iwa))

!     Produce forecasts
      ifail = 0
      Call g13bhf(sttf,nsttf,mr,nser,mt,para,npara,nfv,xxyn,ldxxyn,mrx,parx,   &
        ldparx,rmsxy,kzef,fva,fsd,wa,iwa,ifail)

!     Display results
      Write (nout,*) 'The forecast values and their standard errors'
      Write (nout,*)
      Write (nout,*) '   I     FVA       FSD'
      Write (nout,*)
      Write (nout,99999)(i,fva(i),fsd(i),i=1,nfv)
      Write (nout,*)
      Flush (nout)
      ifail = 0
      Call x04caf('General',' ',nfv,nser,xxyn,ldxxyn,                          &
        'The values of z(t) and n(t)',ifail)
      Write (nout,99998) 'The first ', nis,                                    &
        ' columns hold the z(t) and the last column the n(t)'

99999 Format (1X,I4,2F10.4)
99998 Format (1X,A,I0,A)
    End Program g13bhfe


g13bjfe.f90

    Program g13bjfe

!     G13BJF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: g13bjf, nag_wp, x04caf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Integer                          :: dp, i, ifail, imwa, isttf, iwa, kfc, &
                                          kzef, ldparx, ldxxy, mx, n, ncf,     &
                                          ncg, nch, nci, nev, nfv, nis, npara, &
                                          nparx, nser, nsttf, qp, qx, smx
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: fsd(:), fva(:), para(:), parx(:,:),  &
                                          rmsxy(:), sttf(:), wa(:), xxy(:,:)
      Integer                          :: mr(7)
      Integer, Allocatable             :: mrx(:,:), mt(:,:), mwa(:)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: max, sum
!     .. Executable Statements ..
      Write (nout,*) 'G13BJF Example Program Results'
      Write (nout,*)

!     Skip heading in data file
      Read (nin,*)

!     Read in problem size
      Read (nin,*) kfc, nev, nfv, nser, kzef

!     Number of input series
      nis = nser - 1

      Allocate (mt(4,nser))

!     Read in the orders for the output noise
      Read (nin,*) mr(1:7)

!     Read in transfer function
      Do i = 1, nis
        Read (nin,*) mt(1:4,i)
      End Do

!     Calculate NPARA
      npara = 0
      Do i = 1, nis
        npara = npara + mt(2,i) + mt(3,i)
      End Do
      npara = npara + mr(1) + mr(3) + mr(4) + mr(6) + nser

!     Calculate array sizes
      n = nev + nfv
      ldxxy = n
      ncf = 0
      Do i = 1, nis
        If (mt(4,i)>1) Then
          ncf = sum(mt(1:3,i))
        End If
      End Do
      isttf = mr(4)*mr(7) + mr(2) + mr(5)*mr(7) + mr(3) +                      &
        max(mr(1),mr(6)*mr(7)) + ncf
      qp = mr(3) + mr(6)*mr(7)
      dp = mr(2) + mr(5)*mr(7)
      smx = 0
      qx = qp
      nci = nser
      Do i = 1, nis
        If (mt(4,i)==3) Then
          mx = max(mt(1,i)+mt(2,i),mt(3,i))
          nci = nci + 1
        Else
          mx = 0
        End If
        If (mt(3,i)>0) Then
          nci = nci + 1
        End If
        smx = smx + mx
        qx = max(qx,mx)
      End Do
      ncg = npara + qx + smx
      nch = dp + 6*qx + nev
      If (qx>0) Then
        nci = nci + 1
      End If
      If (mr(1)>0) Then
        nci = nci + 1
      End If
      If (mr(3)>0) Then
        nci = nci + 1
      End If
      If (mr(4)>0) Then
        nci = nci + 1
      End If
      If (mr(6)>0) Then
        nci = nci + 1
      End If
      iwa = 2*(ncg**2) + nch*(nci+4)
      imwa = 16*nser + 7*ncg + 3*npara + 27
      Allocate (para(npara),xxy(ldxxy,nser),rmsxy(nser),mrx(7,nser),fva(nfv),  &
        fsd(nfv),sttf(isttf),wa(iwa),mwa(imwa))

!     Read in multi-input model parameters
      Read (nin,*) para(1:npara)

!     Read in the observed values for the input and output series
      Read (nin,*)(xxy(i,1:nser),i=1,nev)

!     Read in the future values for the input series
      Read (nin,*)(xxy(nev+i,1:nis),i=1,nfv)

      If (nis>=1) Then
!       Read in residual variance of input series
        Read (nin,*) rmsxy(1:nis)

!       Read in orders for input series ARIMA where available
!       (i.e. where residual variance is not zero)
        ldparx = 0
        Do i = 1, nis
          If (rmsxy(i)/=0.0E0_nag_wp) Then
            Read (nin,*) mrx(1:7,i)
            nparx = mrx(1,i) + mrx(3,i) + mrx(4,i) + mrx(6,i)
            ldparx = max(ldparx,nparx)
          Else
            mrx(1:7,i) = 0
          End If
        End Do
      Else
!       No input series
        ldparx = 1
      End If

      Allocate (parx(ldparx,nser))

!     Read in parameters for each input series ARIMA
      If (nis>0) Then
        Do i = 1, nis
          If (rmsxy(i)/=0.0E0_nag_wp) Then
            nparx = mrx(1,i) + mrx(3,i) + mrx(4,i) + mrx(6,i)
            If (nparx>0) Then
              Read (nin,*) parx(1:nparx,i)
            End If
          End If
        End Do
      End If

      ifail = 0
      Call g13bjf(mr,nser,mt,para,npara,kfc,nev,nfv,xxy,ldxxy,kzef,rmsxy,mrx,  &
        parx,ldparx,fva,fsd,sttf,isttf,nsttf,wa,iwa,mwa,imwa,ifail)

!     Display results
      Write (nout,99999) 'After processing', nev, ' sets of observations'
      Write (nout,99998) nsttf, ' values of the state set are derived'
      Write (nout,*)
      Write (nout,99997) sttf(1:nsttf)
      Write (nout,*)
      Write (nout,*) 'The residual mean square for the output'
      Write (nout,99996) 'series is also derived and its value is',            &
        rmsxy(nser)
      Write (nout,*)
      Write (nout,*) 'The forecast values and their standard errors are'
      Write (nout,*)
      Write (nout,*) '   I       FVA       FSD'
      Write (nout,*)
      Write (nout,99995)(i,fva(i),fsd(i),i=1,nfv)
      Write (nout,*)
      Flush (nout)
      ifail = 0
      Call x04caf('General',' ',n,nser,xxy,ldxxy,                              &
        'The values of z(t) and n(t) are',ifail)
      Write (nout,99994) 'The first ', nis,                                    &
        ' columns hold the z(t) and the last column the n(t)'

99999 Format (1X,A,I3,A)
99998 Format (1X,I3,A)
99997 Format (1X,6F10.4)
99996 Format (1X,A,F10.4)
99995 Format (1X,I4,F10.3,F10.4)
99994 Format (1X,A,I0,A)
    End Program g13bjfe


g13cafe.f90

    Program g13cafe

!     G13CAF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: g13caf, nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: px
      Integer                          :: i, ic, ifail, iw, kc, l, lg, lxg,    &
                                          mtx, mw, nc, ng, nx, nxg
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: c(:), xg(:)
      Real (Kind=nag_wp)               :: stats(4)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: max
!     .. Executable Statements ..
      Write (nout,*) 'G13CAF Example Program Results'
      Write (nout,*)

!     Skip heading in data file
      Read (nin,*)

!     Read in the problem size
      Read (nin,*) nx, nc

!     Read in smoothing parameters
      Read (nin,*) mtx, ic, px, iw, mw, l, lg
      If (ic==0) Then
        Read (nin,*) kc
      End If

      If (ic==0) Then
        nxg = max(kc,l)
      Else
        nxg = l
      End If
      lxg = max(nxg,nx)
      Allocate (xg(lxg),c(nc))

!     Read in the data
      Read (nin,*) xg(1:nx)

!     Calculate smoothed spectrum
      ifail = -1
      Call g13caf(nx,mtx,px,iw,mw,ic,nc,c,kc,l,lg,nxg,xg,ng,stats,ifail)
      If (ifail/=0) Then
        If (ifail<4) Then
          Go To 100
        End If
      End If

!     Display results
      Write (nout,*) 'Covariances'
      Write (nout,99999) c(1:nc)
      Write (nout,*)
      Write (nout,99998) 'Degrees of freedom =', stats(1),                     &
        '      Bandwidth =', stats(4)
      Write (nout,*)
      Write (nout,99997) '95 percent confidence limits -     Lower =',         &
        stats(2), '  Upper =', stats(3)
      Write (nout,*)
      Write (nout,*)                                                           &
        '      Spectrum       Spectrum      Spectrum       Spectrum'
      Write (nout,*)                                                           &
        '      estimate       estimate      estimate       estimate'
      Write (nout,99996)(i,xg(i),i=1,ng)

100   Continue

99999 Format (1X,6F11.4)
99998 Format (1X,A,F4.1,A,F7.4)
99997 Format (1X,A,F7.4,A,F7.4)
99996 Format (1X,I4,F10.4,I5,F10.4,I5,F10.4,I5,F10.4)
    End Program g13cafe


g13cbfe.f90

    Program g13cbfe

!     G13CBF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: g13cbf, nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: pw, px
      Integer                          :: i, ifail, kc, l, lg, lxg, mtx, mw,   &
                                          ng, nx
!     .. Local Arrays ..
      Real (Kind=nag_wp)               :: stats(4)
      Real (Kind=nag_wp), Allocatable  :: xg(:)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: max
!     .. Executable Statements ..
      Write (nout,*) 'G13CBF Example Program Results'
      Write (nout,*)

!     Skip heading in data file
      Read (nin,*)

!     Read in the problem size
      Read (nin,*) nx

!     Read in smoothing parameters
      Read (nin,*) mtx, px, mw, l, kc, lg
      If (mw/=nx) Then
        Read (nin,*) pw
      End If

      lxg = max(kc,nx)
      Allocate (xg(lxg))

!     Read in series
      Read (nin,*) xg(1:nx)

!     Calculate smooth spectrum
      ifail = -1
      Call g13cbf(nx,mtx,px,mw,pw,l,kc,lg,xg,ng,stats,ifail)
      If (ifail/=0) Then
        If (ifail<4) Then
          Go To 100
        End If
      End If

!     Display results
      If (mw==nx) Then
        Write (nout,*) 'No smoothing'
      Else
        Write (nout,99999) 'Frequency width of smoothing window = 1/', mw
      End If
      Write (nout,99998) 'Degrees of freedom =', stats(1),                     &
        '      Bandwidth =', stats(4)
      Write (nout,*)
      Write (nout,99997) '95 percent confidence limits -   Lower = ',          &
        stats(2), '  Upper = ', stats(3)
      Write (nout,*)
      Write (nout,*)                                                           &
        '      Spectrum       Spectrum       Spectrum       Spectrum'
      Write (nout,*)                                                           &
        '      estimate       estimate       estimate       estimate'
      Write (nout,99996)(i,xg(i),i=1,ng)
      Write (nout,*)

100   Continue

99999 Format (1X,A,I0)
99998 Format (1X,A,F4.1,A,F7.4)
99997 Format (1X,A,F7.4,A,F7.4)
99996 Format (1X,I4,F10.4,I5,F10.4,I5,F10.4,I5,F10.4)
    End Program g13cbfe


g13ccfe.f90

    Program g13ccfe

!     G13CCF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: g13ccf, nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: pxy
      Integer                          :: i, ic, ifail, ii, ish, iw, kc, l,    &
                                          lxg, lyg, mtxy, mw, nc, ng, nxy,     &
                                          nxyg
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: cxy(:), cyx(:), xg(:), yg(:)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: max, min
!     .. Executable Statements ..
      Write (nout,*) 'G13CCF Example Program Results'
      Write (nout,*)

!     Skip heading in data file
      Read (nin,*)

!     Read in the problem size
      Read (nin,*) nxy, nc, ic

!     Read in control parameters
      Read (nin,*) mtxy, pxy
      Read (nin,*) iw, mw
      Read (nin,*) ish, kc, l

      If (ic==0) Then
        nxyg = max(kc,l)
      Else
        nxyg = l
      End If
      lxg = max(nxyg,nxy)
      lyg = max(nxyg,nxy)
      Allocate (xg(lxg),yg(lyg),cxy(nc),cyx(nc))

      If (ic==0) Then
        Read (nin,*)(xg(i),i=1,nxy)
        Read (nin,*)(yg(i),i=1,nxy)
      Else
        Read (nin,*)(cxy(i),i=1,nc)
        Read (nin,*)(cyx(i),i=1,nc)
      End If

      ifail = 0
      Call g13ccf(nxy,mtxy,pxy,iw,mw,ish,ic,nc,cxy,cyx,kc,l,nxyg,xg,yg,ng,     &
        ifail)

!     Display results
      Write (nout,*) '                  Returned cross covariances'
      Write (nout,*)
      Write (nout,*)                                                           &
        'Lag     XY       YX   Lag     XY       YX   Lag     XY       YX'
      Do i = 1, nc, 3
        Write (nout,99999)(ii-1,cxy(ii),cyx(ii),ii=i,min(i+2,nc))
      End Do
      Write (nout,*)
      Write (nout,*) '                      Returned sample spectrum'
      Write (nout,*)
      Write (nout,*)                                                           &
        '       Real  Imaginary       Real  Imaginary       Real  Imaginary'
      Write (nout,*)                                                           &
        'Lag    part     part  Lag    part     part  Lag    part     part'
      Do i = 1, ng, 3
        Write (nout,99999)(ii-1,xg(ii),yg(ii),ii=i,min(i+2,ng))
      End Do

99999 Format (1X,I3,2F9.4,I4,2F9.4,I4,2F9.4)
    End Program g13ccfe


g13cdfe.f90

    Program g13cdfe

!     G13CDF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: g13cdf, nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: pw, pxy
      Integer                          :: ifail, ish, j, kc, l, m, mtxy, mw,   &
                                          ng, nxy
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: xg(:), yg(:)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: ceiling, log, real
!     .. Executable Statements ..
      Write (nout,*) 'G13CDF Example Program Results'
      Write (nout,*)

!     Skip heading in data file
      Read (nin,*)

!     Read in the problem size
      Read (nin,*) nxy, l

!     Read in control parameters
      Read (nin,*) mtxy, pxy, pw, mw, ish

!     Get a value for KC
      m = ceiling(log(2.0E0_nag_wp*real(nxy,kind=nag_wp)/real(l,               &
        kind=nag_wp))/log(2.0E0_nag_wp))
      kc = (2**m)*l
      Allocate (xg(kc),yg(kc))

!     Read in data
      Read (nin,*) xg(1:nxy)
      Read (nin,*) yg(1:nxy)

      ifail = 0
      Call g13cdf(nxy,mtxy,pxy,mw,ish,pw,l,kc,xg,yg,ng,ifail)

!     Display results
      Write (nout,*) '                      Returned sample spectrum'
      Write (nout,*)
      Write (nout,*)                                                           &
        '      Real  Imaginary       Real  Imaginary       Real  Imaginary'
      Write (nout,*)                                                           &
        '      part     part         part     part         part     part'
      Write (nout,99999)(j,xg(j),yg(j),j=1,ng)

99999 Format (1X,I3,F8.4,F9.4,I5,F8.4,F9.4,I5,F8.4,F9.4)
    End Program g13cdfe


g13cefe.f90

    Program g13cefe

!     G13CEF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: g13cef, nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: t
      Integer                          :: i, ifail, j, ng
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: ca(:), calw(:), caup(:), sc(:),      &
                                          sclw(:), scup(:), xg(:), xyig(:),    &
                                          xyrg(:), yg(:)
      Real (Kind=nag_wp)               :: stats(4)
!     .. Executable Statements ..
      Write (nout,*) 'G13CEF Example Program Results'
      Write (nout,*)

!     Skip heading in data file
      Read (nin,*)

!     Read in the problem size
      Read (nin,*) ng

!     Read in statistics
      Read (nin,*) stats(1:4)

      Allocate (xg(ng),yg(ng),xyrg(ng),xyig(ng),ca(ng),calw(ng),caup(ng),      &
        sc(ng),sclw(ng),scup(ng))

!     Read in data
      Read (nin,*)(xg(i),yg(i),xyrg(i),xyig(i),i=1,ng)

!     Calculate cross-amplitude spectrum
      ifail = -1
      Call g13cef(xg,yg,xyrg,xyig,ng,stats,ca,calw,caup,t,sc,sclw,scup,ifail)
      If (ifail/=0) Then
        If (ifail<2) Then
          Go To 100
        End If
      End If

!     Display results
      Write (nout,*) '      Cross amplitude spectrum'
      Write (nout,*)
      Write (nout,*) '                    Lower     Upper'
      Write (nout,*) '          Value     bound     bound'
      Write (nout,99999)(j-1,ca(j),calw(j),caup(j),j=1,ng)
      Write (nout,*)
      Write (nout,99998) 'Squared coherency test statistic =', t
      Write (nout,*)
      Write (nout,*) '         Squared coherency'
      Write (nout,*)
      Write (nout,*) '                    Lower     Upper'
      Write (nout,*) '          Value     bound     bound'
      Write (nout,99999)(j-1,sc(j),sclw(j),scup(j),j=1,ng)

100   Continue

99999 Format (1X,I5,3F10.4)
99998 Format (1X,A,F12.4)
    End Program g13cefe


g13cffe.f90

    Program g13cffe

!     G13CFF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: g13cff, nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Integer                          :: i, ifail, j, ng
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: gn(:), gnlw(:), gnup(:), ph(:),      &
                                          phlw(:), phup(:), xg(:), xyig(:),    &
                                          xyrg(:), yg(:)
      Real (Kind=nag_wp)               :: stats(4)
!     .. Executable Statements ..
      Write (nout,*) 'G13CFF Example Program Results'
      Write (nout,*)

!     Skip heading in data file
      Read (nin,*)

!     Read in problem size
      Read (nin,*) ng

      Allocate (xg(ng),yg(ng),xyrg(ng),xyig(ng),gn(ng),gnlw(ng),gnup(ng),      &
        ph(ng),phlw(ng),phup(ng))

!     Read in statistics
      Read (nin,*) stats(1:4)

!     Read in data
      Read (nin,*)(xg(i),yg(i),xyrg(i),xyig(i),i=1,ng)

!     Calculate gain and phase
      ifail = -1
      Call g13cff(xg,yg,xyrg,xyig,ng,stats,gn,gnlw,gnup,ph,phlw,phup,ifail)
      If (ifail/=0) Then
        If (ifail<2) Then
          Go To 100
        End If
      End If

!     Display results
      Write (nout,*) '              The gain'
      Write (nout,*)
      Write (nout,*) '                    Lower     Upper'
      Write (nout,*) '          Value     bound     bound'
      Write (nout,99999)(j-1,gn(j),gnlw(j),gnup(j),j=1,ng)
      Write (nout,*)
      Write (nout,*) '             The phase'
      Write (nout,*)
      Write (nout,*) '                    Lower     Upper'
      Write (nout,*) '          Value     bound     bound'
      Write (nout,99999)(j-1,ph(j),phlw(j),phup(j),j=1,ng)

100   Continue

99999 Format (1X,I5,3F10.4)
    End Program g13cffe


g13cgfe.f90

    Program g13cgfe

!     G13CGF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: g13cgf, nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: erlw, erup, rfse
      Integer                          :: i, ifail, j, l, n, ng
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: er(:), rf(:), xg(:), xyig(:),        &
                                          xyrg(:), yg(:)
      Real (Kind=nag_wp)               :: stats(4)
!     .. Executable Statements ..
      Write (nout,*) 'G13CGF Example Program Results'
      Write (nout,*)

!     Skip heading in data file
      Read (nin,*)

!     Read in the problem size
      Read (nin,*) ng, l, n

      Allocate (xg(ng),yg(ng),xyrg(ng),xyig(ng),er(ng),rf(l))

!     Read in the statistics
      Read (nin,*)(stats(i),i=1,4)

!     Read in data
      Read (nin,*)(xg(i),yg(i),xyrg(i),xyig(i),i=1,ng)

!     Calculate noise spectrum
      ifail = -1
      Call g13cgf(xg,yg,xyrg,xyig,ng,stats,l,n,er,erlw,erup,rf,rfse,ifail)
      If (ifail/=0) Then
        If (ifail<2) Then
          Go To 100
        End If
      End If

!     Display results
      Write (nout,*) '           Noise spectrum'
      Write (nout,99999)(j-1,er(j),j=1,ng)
      Write (nout,*)
      Write (nout,*) 'Noise spectrum bounds multiplying factors'
      Write (nout,99998) 'Lower =', erlw, '     Upper =', erup
      Write (nout,*)
      Write (nout,*) 'Impulse response function'
      Write (nout,*)
      Write (nout,99999)(j-1,rf(j),j=1,l)
      Write (nout,*)
      Write (nout,99998) 'Impulse response function standard error =', rfse

100   Continue

99999 Format (1X,I5,F16.4)
99998 Format (1X,A,F10.4,A,F10.4)
    End Program g13cgfe


g13dbfe.f90

    Program g13dbfe

!     G13DBF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: g13dbf, nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: v0
      Integer                          :: i, ifail, iwa, k, ldc0, nk, nl, ns,  &
                                          nvp
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: c(:,:,:), c0(:,:), d(:,:,:),         &
                                          db(:,:), p(:), v(:), w(:,:,:),       &
                                          wa(:), wb(:,:,:)
!     .. Executable Statements ..
      Write (nout,*) 'G13DBF Example Program Results'
      Write (nout,*)

!     Skip heading in data file
      Read (nin,*)

!     Read series length, and numbers of lags
      Read (nin,*) ns, nl, nk

      ldc0 = ns
      iwa = (2*ns+1)*ns
      Allocate (c0(ldc0,ns),c(ldc0,ldc0,nl),p(nk),v(nk),d(ldc0,ldc0,nk),       &
        w(ldc0,ldc0,nk),wb(ldc0,ldc0,nk),wa(iwa),db(ldc0,ns))

!     Read autocovariances
      Read (nin,*)(c0(i,1:ns),i=1,ns)
      Read (nin,*)((c(i,1:ns,k),i=1,ns),k=1,nl)

!     Calculate multivariate partial autocorrelation function
      ifail = -1
      Call g13dbf(c0,c,ldc0,ns,nl,nk,p,v0,v,d,db,w,wb,nvp,wa,iwa,ifail)
      If (ifail/=0) Then
        If (ifail/=3) Then
          Go To 100
        End If
      End If

!     Display results
      Write (nout,99999) 'Number of valid parameters =', nvp
      Write (nout,*)
      Write (nout,*) 'Multivariate partial autocorrelations'
      Write (nout,99998) p(1:nk)
      Write (nout,*)
      Write (nout,*) 'Zero lag predictor error variance determinant'
      Write (nout,*) 'followed by error variance ratios'
      Write (nout,99998) v0, v(1:nk)
      Write (nout,*)
      Write (nout,*) 'Prediction error variances'
      Do k = 1, nk
        Write (nout,*)
        Write (nout,99997) 'Lag =', k
        Do i = 1, ns
          Write (nout,99998) d(i,1:ns,k)
        End Do
      End Do
      Write (nout,*)
      Write (nout,*) 'Last backward prediction error variances'
      Write (nout,*)
      Write (nout,99997) 'Lag =', nvp
      Do i = 1, ns
        Write (nout,99998) db(i,1:ns)
      End Do
      Write (nout,*)
      Write (nout,*) 'Prediction coefficients'
      Do k = 1, nk
        Write (nout,*)
        Write (nout,99997) 'Lag =', k
        Do i = 1, ns
          Write (nout,99998) w(i,1:ns,k)
        End Do
      End Do
      Write (nout,*)
      Write (nout,*) 'Backward prediction coefficients'
      Do k = 1, nk
        Write (nout,*)
        Write (nout,99997) 'Lag =', k
        Do i = 1, ns
          Write (nout,99998) wb(i,1:ns,k)
        End Do
      End Do

100   Continue

99999 Format (1X,A,I10)
99998 Format (1X,5F12.5)
99997 Format (1X,A,I5)
    End Program g13dbfe


g13ddfe.f90

    Program g13ddfe

!     G13DDF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: g13ddf, nag_wp, x04abf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: iset = 1, nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: cgetol, rlogl
      Integer                          :: i, ifail, ip, iprint, iq, ishow, k,  &
                                          kmax, ldcm, maxcal, n, nadv, niter,  &
                                          npar
      Logical                          :: exact, mean
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: cm(:,:), g(:), par(:), qq(:,:),      &
                                          v(:,:), w(:,:)
      Logical, Allocatable             :: parhld(:)
!     .. Executable Statements ..
      Write (nout,*) 'G13DDF Example Program Results'
      Write (nout,*)
      Flush (nout)

!     Skip heading in data file
      Read (nin,*)

!     Read in problem size
      Read (nin,*) k, ip, iq, n, mean

!     Calculate NPAR
      npar = (ip+iq)*k*k
      If (mean) Then
        npar = npar + k
      End If

      ldcm = npar
      kmax = k
      Allocate (par(npar),qq(kmax,k),w(kmax,n),v(kmax,n),g(npar),              &
        cm(ldcm,npar),parhld(npar))

!     Read in series
      Read (nin,*)(w(i,1:n),i=1,k)

!     Read in control parameters
      Read (nin,*) iprint, cgetol, maxcal, ishow

!     Read in exact likelihood flag
      Read (nin,*) exact

!     Read in initial parameter estimates and free parameter flags
      Read (nin,*) par(1:npar)
      Read (nin,*) parhld(1:npar)

!     Read in initial values for covariance matrix QQ
      Read (nin,*)(qq(i,1:i),i=1,k)

!     Set the advisory channel to NOUT for monitoring information
      If (iprint>=0 .Or. ishow/=0) Then
        nadv = nout
        Call x04abf(iset,nadv)
      End If

!     Fit a VARMA model
      ifail = 0
      Call g13ddf(k,n,ip,iq,mean,par,npar,qq,kmax,w,parhld,exact,iprint,       &
        cgetol,maxcal,ishow,niter,rlogl,v,g,cm,ldcm,ifail)

    End Program g13ddfe


g13djfe.f90

!   G13DJF Example Program Text
!   Mark 26 Release. NAG Copyright 2016.

    Module g13djfe_mod

!     G13DJF Example Program Module:
!            Parameters and User-defined Routines

!     .. Use Statements ..
      Use nag_library, Only: nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Accessibility Statements ..
      Private
      Public                           :: fprint
!     .. Parameters ..
      Integer, Parameter, Public       :: iset = 1, nin = 5, nout = 6
    Contains
      Subroutine fprint(k,nm,lmax,predz,sefz,ldsefz,nout)

!       .. Scalar Arguments ..
        Integer, Intent (In)           :: k, ldsefz, lmax, nm, nout
!       .. Array Arguments ..
        Real (Kind=nag_wp), Intent (In) :: predz(ldsefz,lmax),                 &
                                          sefz(ldsefz,lmax)
!       .. Local Scalars ..
        Integer                        :: i, i2, j, l, l2, loop
!       .. Intrinsic Procedures ..
        Intrinsic                      :: min, mod
!       .. Executable Statements ..
        Write (nout,*) ' FORECAST SUMMARY TABLE'
        Write (nout,*) ' ----------------------'
        Write (nout,*)
        Write (nout,99999) ' Forecast origin is set at t = ', nm
        Write (nout,*)
        loop = lmax/5
        If (mod(lmax,5)/=0) Then
          loop = loop + 1
        End If

        Do j = 1, loop
          i2 = (j-1)*5
          l2 = min(i2+5,lmax)
          Write (nout,99998) 'Lead Time ', (i,i=i2+1,l2)
          Write (nout,*)
          i = 1
          Write (nout,99997) 'Series ', i, ' : Forecast    ',                  &
            (predz(1,l),l=i2+1,l2)
          Write (nout,99996) ' : Standard Error ', (sefz(1,l),l=i2+1,l2)
          Do i = 2, k
            Write (nout,99997) 'Series ', i, ' : Forecast    ',                &
              (predz(i,l),l=i2+1,l2)
            Write (nout,99996) ' : Standard Error ', (sefz(i,l),l=i2+1,l2)
          End Do
          Write (nout,*)
        End Do
        Return

99999   Format (1X,A,I4)
99998   Format (1X,A,12X,5I10)
99997   Format (1X,A,I2,A,5F10.2)
99996   Format (10X,A,4(F7.2,3X),F7.2)
      End Subroutine fprint
    End Module g13djfe_mod
    Program g13djfe

!     G13DJF Example Main Program

!     .. Use Statements ..
      Use nag_library, Only: g13ddf, g13djf, g13dlf, nag_wp, x04abf
      Use g13djfe_mod, Only: fprint, iset, nin, nout
!     .. Implicit None Statement ..
      Implicit None
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: cgetol, rlogl
      Integer                          :: d, i, ifail, ip, iprint, iq, ishow,  &
                                          k, kmax, ldcm, liwork, lmax, lpar,   &
                                          lref, lwork, maxcal, n, nadv, nd,    &
                                          niter, r, tddelta
      Logical                          :: exact, meanl
      Character (1)                    :: mean
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: cm(:,:), delta(:,:), g(:), par(:),   &
                                          predz(:,:), qq(:,:), ref(:),         &
                                          sefz(:,:), v(:,:), w(:,:), work(:),  &
                                          workl(:), z(:,:)
      Integer, Allocatable             :: id(:), iwork(:)
      Logical, Allocatable             :: parhld(:)
      Character (1), Allocatable       :: tr(:)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: max, maxval
!     .. Executable Statements ..
      Write (nout,*) 'G13DJF Example Program Results'
      Write (nout,*)

!     Skip heading in data file
      Read (nin,*)

!     Read in the problem size
      Read (nin,*) k, n

      Allocate (tr(k),id(k))

!     Read in differencing
      Read (nin,*) id(1:k)

      d = maxval(id(1:k))
      tddelta = max(d,1)
      nd = n - d
      kmax = k
      Allocate (delta(kmax,tddelta),w(kmax,nd),workl(k*n),z(kmax,n))

!     Read in series and the transformation flag
      Read (nin,*)(z(i,1:n),i=1,k)
      Read (nin,*) tr(1:k)

!     If required, read in delta
      If (d>0) Then
        Read (nin,*)(delta(i,1:id(i)),i=1,k)
      End If

!     Difference and / or transform series
      ifail = 0
      Call g13dlf(k,n,z,kmax,tr,id,delta,w,nd,workl,ifail)

!     Read in information on the VARMA
      Read (nin,*) ip, iq, mean, lmax

!     Calculate number of parameters for the VARMA
      lpar = (ip+iq)*k*k
      meanl = .False.
      If (mean=='M' .Or. mean=='m') Then
        lpar = lpar + k
        meanl = .True.
      End If

!     Read in control parameters
      Read (nin,*) iprint, cgetol, maxcal, ishow

!     Read in exact likelihood flag
      Read (nin,*) exact

      ldcm = lpar
      kmax = k
      Allocate (par(lpar),qq(kmax,k),v(kmax,nd),g(lpar),cm(ldcm,lpar),         &
        parhld(lpar))

!     Read in initial parameter estimates and free parameter flags
      Read (nin,*) par(1:lpar)
      Read (nin,*) parhld(1:lpar)

!     Read in initial values for covariance matrix Q
      Read (nin,*)(qq(i,1:i),i=1,k)

!     Set the advisory channel to NOUT for monitoring information
      If (iprint>=0 .Or. ishow/=0) Then
        nadv = nout
        Call x04abf(iset,nadv)
      End If

!     Fit a VARMA model
      ifail = -1
      Call g13ddf(k,nd,ip,iq,meanl,par,lpar,qq,kmax,w,parhld,exact,iprint,     &
        cgetol,maxcal,ishow,niter,rlogl,v,g,cm,ldcm,ifail)
      If (ifail/=0) Then
        If (ifail<4) Then
          Go To 100
        End If
      End If

      lref = (lmax-1)*k*k + 2*k*lmax + k
      r = max(ip,iq)
      lwork = max(k*r*(k*r+2),(ip+d+2)*k**2+(n+lmax)*k)
      liwork = k*max(ip,iq)
      Allocate (predz(kmax,lmax),sefz(kmax,lmax),ref(lref),work(lwork),        &
        iwork(liwork))

!     Perform forecast
      ifail = 0
      Call g13djf(k,n,z,kmax,tr,id,delta,ip,iq,mean,par,lpar,qq,v,lmax,predz,  &
        sefz,ref,lref,work,lwork,iwork,liwork,ifail)

!     Display results
      Call fprint(k,n,lmax,predz,sefz,kmax,nout)

100   Continue

    End Program g13djfe


g13dkfe.f90

!   G13DKF Example Program Text
!   Mark 26 Release. NAG Copyright 2016.

    Module g13dkfe_mod

!     G13DKF Example Program Module:
!            Parameters and User-defined Routines

!     .. Use Statements ..
      Use nag_library, Only: nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Accessibility Statements ..
      Private
      Public                           :: fprint
!     .. Parameters ..
      Integer, Parameter, Public       :: iset = 1, nin = 5, nout = 6
    Contains
      Subroutine fprint(k,nm,lmax,predz,sefz,ldsefz,nout)

!       .. Scalar Arguments ..
        Integer, Intent (In)           :: k, ldsefz, lmax, nm, nout
!       .. Array Arguments ..
        Real (Kind=nag_wp), Intent (In) :: predz(ldsefz,lmax),                 &
                                          sefz(ldsefz,lmax)
!       .. Local Scalars ..
        Integer                        :: i, i2, j, l, l2, loop
!       .. Intrinsic Procedures ..
        Intrinsic                      :: min, mod
!       .. Executable Statements ..
        Write (nout,*)
        Write (nout,*) ' FORECAST SUMMARY TABLE'
        Write (nout,*) ' ----------------------'
        Write (nout,*)
        Write (nout,99999) ' Forecast origin is set at t = ', nm
        Write (nout,*)
        loop = lmax/5
        If (mod(lmax,5)/=0) Then
          loop = loop + 1
        End If
        Do j = 1, loop
          i2 = (j-1)*5
          l2 = min(i2+5,lmax)
          Write (nout,99998) 'Lead Time ', (i,i=i2+1,l2)
          Write (nout,*)
          i = 1
          Write (nout,99997) 'Series ', i, ' : Forecast    ',                  &
            (predz(1,l),l=i2+1,l2)
          Write (nout,99996) ' : Standard Error ', (sefz(1,l),l=i2+1,l2)
          Do i = 2, k
            Write (nout,99997) 'Series ', i, ' : Forecast    ',                &
              (predz(i,l),l=i2+1,l2)
            Write (nout,99996) ' : Standard Error ', (sefz(i,l),l=i2+1,l2)
          End Do
          Write (nout,*)
        End Do

        Return

99999   Format (1X,A,I4)
99998   Format (1X,A,12X,5I10)
99997   Format (1X,A,I2,A,5F10.2)
99996   Format (10X,A,4(F7.2,3X),F7.2)
      End Subroutine fprint
    End Module g13dkfe_mod
    Program g13dkfe

!     G13DKF Example Main Program

!     .. Use Statements ..
      Use nag_library, Only: g13ddf, g13djf, g13dkf, g13dlf, nag_wp, x04abf
      Use g13dkfe_mod, Only: fprint, iset, nin, nout
!     .. Implicit None Statement ..
      Implicit None
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: cgetol, rlogl
      Integer                          :: d, i, ifail, ip, iprint, iq, ishow,  &
                                          k, kmax, ldcm, liwork, lmax, lpar,   &
                                          lref, lwork, m, maxcal, mlast, n,    &
                                          nadv, nd, niter, r, tddelta, tdv
      Logical                          :: exact, meanl
      Character (1)                    :: mean
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: cm(:,:), delta(:,:), g(:), par(:),   &
                                          predz(:,:), qq(:,:), ref(:),         &
                                          sefz(:,:), v(:,:), w(:,:), work(:),  &
                                          workl(:), z(:,:)
      Integer, Allocatable             :: id(:), iwork(:)
      Logical, Allocatable             :: parhld(:)
      Character (1), Allocatable       :: tr(:)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: max, maxval
!     .. Executable Statements ..
      Write (nout,*) 'G13DKF Example Program Results'
      Write (nout,*)

!     Skip heading in data file
      Read (nin,*)

!     Read in the problem size
      Read (nin,*) k, n

      Allocate (id(k))

!     Read in differencing
      Read (nin,*) id(1:k)

      d = maxval(id(1:k))
      tddelta = max(d,1)
      nd = n - d
      kmax = k
      Allocate (z(kmax,n),tr(k),delta(kmax,tddelta),w(kmax,nd),workl(k*n))

!     Read in series and the transformation flag
      Read (nin,*)(z(i,1:n),i=1,k)
      Read (nin,*) tr(1:k)

!     If required, read in delta
      If (d>0) Then
        Read (nin,*)(delta(i,1:id(i)),i=1,k)
      End If

!     Difference and / or transform series
      ifail = 0
      Call g13dlf(k,n,z,kmax,tr,id,delta,w,nd,workl,ifail)

!     Read in information on the VARMA
      Read (nin,*) ip, iq, mean, lmax

!     Calculate number of parameters for the VARMA
      lpar = (ip+iq)*k*k
      If (mean=='M' .Or. mean=='m') Then
        lpar = lpar + k
        meanl = .True.
      Else
        meanl = .False.
      End If

!     Read in control parameters
      Read (nin,*) iprint, cgetol, maxcal, ishow

!     Read in exact likelihood flag
      Read (nin,*) exact

      ldcm = lpar
      tdv = nd
      Allocate (par(lpar),parhld(lpar),qq(kmax,k),v(kmax,tdv),g(lpar),         &
        cm(ldcm,lpar))

!     Read in initial parameter estimates and free parameter flags
      Read (nin,*) par(1:lpar)
      Read (nin,*) parhld(1:lpar)

!     Read in initial values for covariance matrix Q
      Read (nin,*)(qq(i,1:i),i=1,k)

!     Set the advisory channel to NOUT for monitoring information
      If (iprint>=0 .Or. ishow/=0) Then
        nadv = nout
        Call x04abf(iset,nadv)
      End If

!     Fit a VARMA model
      ifail = -1
      Call g13ddf(k,nd,ip,iq,meanl,par,lpar,qq,kmax,w,parhld,exact,iprint,     &
        cgetol,maxcal,ishow,niter,rlogl,v,g,cm,ldcm,ifail)
      If (ifail/=0) Then
        If (ifail<4) Then
          Go To 100
        End If
      End If

      lref = (lmax-1)*k*k + 2*k*lmax + k
      r = max(ip,iq)
      lwork = max(k*r*(k*r+2),(ip+d+2)*k**2+(n+lmax)*k)
      liwork = k*max(ip,iq)
      Allocate (predz(kmax,lmax),sefz(kmax,lmax),ref(lref),work(lwork),        &
        iwork(liwork))

!     Forecast from VARMA
      ifail = 0
      Call g13djf(k,n,z,kmax,tr,id,delta,ip,iq,mean,par,lpar,qq,v,lmax,predz,  &
        sefz,ref,lref,work,lwork,iwork,liwork,ifail)

!     Display results
      Call fprint(k,n,lmax,predz,sefz,kmax,nout)

!     Update forecasts
      mlast = 0
d_lp: Do
        Read (nin,*,Iostat=ifail) m
        If (ifail/=0) Then
          Exit d_lp
        End If
        Read (nin,*,Iostat=ifail)(z(1:k,i),i=1,m)
        If (ifail/=0) Then
          Exit d_lp
        End If

!       Reallocate V if required
        If (tdv<m) Then
          Deallocate (v)
          Allocate (v(kmax,m))
        End If

!       Reallocate WORK if required
        If (lwork<k*m) Then
          Deallocate (work)
          Allocate (work(lwork))
        End If

!       Update forecast
        ifail = 0
        Call g13dkf(k,lmax,m,mlast,z,kmax,ref,lref,v,predz,sefz,work,ifail)

        Call fprint(k,n+mlast,lmax,predz,sefz,kmax,nout)
      End Do d_lp

100   Continue

    End Program g13dkfe


g13dlfe.f90

    Program g13dlfe

!     G13DLF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: g13dlf, nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Integer                          :: d, i, ifail, k, kmax, n, nd, tddelta
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: delta(:,:), w(:,:), work(:), z(:,:)
      Integer, Allocatable             :: id(:)
      Character (1), Allocatable       :: tr(:)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: max, maxval
!     .. Executable Statements ..
      Write (nout,*) 'G13DLF Example Program Results'
      Write (nout,*)

!     Skip heading in data file
      Read (nin,*)

!     Read in problem size
      Read (nin,*) k, n

      Allocate (id(k))

!     Read in differencing
      Read (nin,*) id(1:k)

      d = maxval(id(1:k))
      tddelta = max(d,1)
      nd = n - d
      kmax = k
      Allocate (z(kmax,n),tr(k),delta(kmax,tddelta),w(kmax,nd),work(k*n))

!     Read in series and the transformation flag
      Read (nin,*)(z(i,1:n),i=1,k)
      Read (nin,*) tr(1:k)

!     If required, read in delta
      If (d>0) Then
        Read (nin,*)(delta(i,1:id(i)),i=1,k)
      End If

!     Difference and / or transform series
      ifail = 0
      Call g13dlf(k,n,z,kmax,tr,id,delta,w,nd,work,ifail)

!     Display results
      Write (nout,*) ' Transformed/Differenced series'
      Write (nout,*) ' ------------------------------'
      Do i = 1, k
        Write (nout,*)
        Write (nout,99999) ' Series ', i
        Write (nout,*) ' -----------'
        Write (nout,*)
        Write (nout,99998) ' Number of differenced values = ', nd
        Write (nout,*)
        Write (nout,99997) w(i,1:nd)
      End Do

99999 Format (1X,A,I2)
99998 Format (1X,A,I6)
99997 Format (1X,8F9.3)
    End Program g13dlfe


g13dmfe.f90

!   G13DMF Example Program Text
!   Mark 26 Release. NAG Copyright 2016.

    Module g13dmfe_mod

!     G13DMF Example Program Module:
!            Parameters and User-defined Routines

!     .. Use Statements ..
      Use nag_library, Only: nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Accessibility Statements ..
      Private
      Public                           :: cprint
!     .. Parameters ..
      Integer, Parameter, Public       :: nin = 5, nout = 6
    Contains
      Subroutine cprint(k,n,ldr,m,wmean,r0,r,nout)

!       .. Use Statements ..
        Use nag_library, Only: x04cbf
!       .. Scalar Arguments ..
        Integer, Intent (In)           :: k, ldr, m, n, nout
!       .. Array Arguments ..
        Real (Kind=nag_wp), Intent (In) :: r(ldr,ldr,m), r0(ldr,k), wmean(k)
!       .. Local Scalars ..
        Real (Kind=nag_wp)             :: c1, c2, c3, c5, c6, c7, inv_sqrt_n,  &
                                          sum
        Integer                        :: i, i2, ifail, j, l, ll
!       .. Local Arrays ..
        Character (1)                  :: clabs(1), rlabs(1)
        Character (79)                 :: rec(7)
!       .. Intrinsic Procedures ..
        Intrinsic                      :: real, sqrt
!       .. Executable Statements ..
!       Print the correlation matrices and indicator symbols.

        inv_sqrt_n = 1.0E0_nag_wp/sqrt(real(n,kind=nag_wp))
        Write (nout,*)
        Write (nout,*) ' THE MEANS'
        Write (nout,*) ' ---------'
        Write (nout,99999) wmean(1:k)
        Write (nout,*)
        Write (nout,*) ' CROSS-CORRELATION MATRICES'
        Write (nout,*) ' --------------------------'
        Write (nout,99998) ' Lag = ', 0
        Flush (nout)
        ifail = 0
        Call x04cbf('G','N',k,k,r0,ldr,'F9.3',' ','N',rlabs,'N',clabs,80,5,    &
          ifail)
        Do l = 1, m
          Write (nout,99998) ' Lag = ', l
          Flush (nout)
          ifail = 0
          Call x04cbf('G','N',k,k,r(1,1,l),ldr,'F9.3',' ','N',rlabs,'N',clabs, &
            80,5,ifail)
        End Do

!       Print indicator symbols to indicate significant elements.
        Write (nout,99997) ' Standard error = 1 / SQRT(N) =', inv_sqrt_n
        Write (nout,*)
        Write (nout,*) ' TABLES OF INDICATOR SYMBOLS'
        Write (nout,*) ' ---------------------------'
        Write (nout,99998) ' For Lags 1 to ', m

!       Set up annotation for the plots.
        Write (rec(1),99996) '              0.005  :'
        Write (rec(2),99996) '        +     0.01   :'
        Write (rec(3),99996) '              0.05   :'
        Write (rec(4)(1:23),99996) '   Sig. Level        :'
        Write (rec(4)(24:),99996) '- - - - - - - - - -  Lags'
        Write (rec(5),99996) '              0.05   :'
        Write (rec(6),99996) '        -     0.01   :'
        Write (rec(7),99996) '              0.005  :'

!       Set up the critical values
        c1 = 3.29E0_nag_wp*inv_sqrt_n
        c2 = 2.58E0_nag_wp*inv_sqrt_n
        c3 = 1.96E0_nag_wp*inv_sqrt_n
        c5 = -c3
        c6 = -c2
        c7 = -c1

        Do i = 1, k
          Do j = 1, k
            Write (nout,*)
            If (i==j) Then
              Write (nout,99995) ' Auto-correlation function for', ' series ', &
                i
            Else
              Write (nout,99994) ' Cross-correlation function for',            &
                ' series ', i, ' and series', j
            End If
            Do l = 1, m
              ll = 23 + 2*l
              sum = r(i,j,l)

!             Clear the last plot with blanks
              Do i2 = 1, 7
                If (i2/=4) Then
                  rec(i2)(ll:ll) = ' '
                End If
              End Do

!             Check for significance
              If (sum>c1) Then
                rec(1)(ll:ll) = '*'
              End If
              If (sum>c2) Then
                rec(2)(ll:ll) = '*'
              End If
              If (sum>c3) Then
                rec(3)(ll:ll) = '*'
              End If
              If (sum<c5) Then
                rec(5)(ll:ll) = '*'
              End If
              If (sum<c6) Then
                rec(6)(ll:ll) = '*'
              End If
              If (sum<c7) Then
                rec(7)(ll:ll) = '*'
              End If
            End Do

!           Print
            Write (nout,99996)(rec(i2),i2=1,7)
          End Do
        End Do
        Return

99999   Format (/,1X,2(2X,F9.3))
99998   Format (/,1X,A,I2)
99997   Format (/,1X,A,F6.3,A)
99996   Format (1X,A)
99995   Format (/,/,1X,A,A,I2,/)
99994   Format (/,/,1X,A,A,I2,A,I2,/)
      End Subroutine cprint
    End Module g13dmfe_mod
    Program g13dmfe

!     G13DMF Example Main Program

!     .. Use Statements ..
      Use nag_library, Only: g13dmf, nag_wp
      Use g13dmfe_mod, Only: cprint, nin, nout
!     .. Implicit None Statement ..
      Implicit None
!     .. Local Scalars ..
      Integer                          :: i, ifail, k, kmax, m, n
      Character (1)                    :: matrix
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: r(:,:,:), r0(:,:), w(:,:), wmean(:)
!     .. Executable Statements ..
      Write (nout,*) 'G13DMF Example Program Results'
      Write (nout,*)

!     Skip heading in data file
      Read (nin,*)

!     Read in the problem size
      Read (nin,*) k, n, m, matrix

      kmax = k
      Allocate (w(kmax,n),r0(kmax,k),wmean(k),r(kmax,kmax,m))

!     Read in series
      Do i = 1, k
        Read (nin,*) w(i,1:n)
      End Do

!     Calculate sample cross-correlation matrices
      ifail = 0
      Call g13dmf(matrix,k,n,m,w,kmax,wmean,r0,r,ifail)

!     Display results
      Call cprint(k,n,kmax,m,wmean,r0,r,nout)

    End Program g13dmfe


g13dnfe.f90

!   G13DNF Example Program Text
!   Mark 26 Release. NAG Copyright 2016.

    Module g13dnfe_mod

!     G13DNF Example Program Module:
!            Parameters and User-defined Routines

!     .. Use Statements ..
      Use nag_library, Only: nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Accessibility Statements ..
      Private
      Public                           :: zprint
!     .. Parameters ..
      Integer, Parameter, Public       :: nin = 5, nout = 6
    Contains
      Subroutine zprint(k,n,m,ldpar,parlag,x,pvalue,nout)

!       .. Use Statements ..
        Use nag_library, Only: x04cbf
!       .. Scalar Arguments ..
        Integer, Intent (In)           :: k, ldpar, m, n, nout
!       .. Array Arguments ..
        Real (Kind=nag_wp), Intent (In) :: parlag(ldpar,ldpar,m), pvalue(m),   &
                                          x(m)
!       .. Local Scalars ..
        Real (Kind=nag_wp)             :: c1, c2, c3, c5, c6, c7, inv_sqrt_n,  &
                                          sum
        Integer                        :: i, i2, ifail, j, l, ll
!       .. Local Arrays ..
        Character (1)                  :: clabs(1), rlabs(1)
        Character (79)                 :: rec(7)
!       .. Intrinsic Procedures ..
        Intrinsic                      :: real, sqrt
!       .. Executable Statements ..
!       Print the partial lag correlation matrices.

        inv_sqrt_n = 1.0E0_nag_wp/sqrt(real(n,kind=nag_wp))
        Write (nout,*)
        Write (nout,*) ' PARTIAL LAG CORRELATION MATRICES'
        Write (nout,*) ' --------------------------------'
        Do l = 1, m
          Write (nout,99999) ' Lag = ', l
          Flush (nout)
          ifail = 0
          Call x04cbf('G','N',k,k,parlag(1,1,l),ldpar,'F9.3',' ','N',rlabs,    &
            'N',clabs,80,5,ifail)
        End Do
        Write (nout,99998) ' Standard error = 1 / SQRT(N) =', inv_sqrt_n

!       Print indicator symbols to indicate significant elements.
        Write (nout,*)
        Write (nout,*) ' TABLES OF INDICATOR SYMBOLS'
        Write (nout,*) ' ---------------------------'
        Write (nout,99999) ' For Lags 1 to ', m

!       Set up annotation for the plots.
        Write (rec(1),99997) '              0.005  :'
        Write (rec(2),99997) '        +     0.01   :'
        Write (rec(3),99997) '              0.05   :'
        Write (rec(4)(1:23),99997) '   Sig. Level        :'
        Write (rec(4)(24:),99997) '- - - - - - - - - -  Lags'
        Write (rec(5),99997) '              0.05   :'
        Write (rec(6),99997) '        -     0.01   :'
        Write (rec(7),99997) '              0.005  :'

!       Set up the critical values
        c1 = 3.29E0_nag_wp*inv_sqrt_n
        c2 = 2.58E0_nag_wp*inv_sqrt_n
        c3 = 1.96E0_nag_wp*inv_sqrt_n
        c5 = -c3
        c6 = -c2
        c7 = -c1

        Do i = 1, k
          Do j = 1, k
            Write (nout,*)
            If (i==j) Then
              Write (nout,99996) ' Auto-correlation function for', ' series ', &
                i
            Else
              Write (nout,99995) ' Cross-correlation function for',            &
                ' series ', i, ' and series', j
            End If
            Do l = 1, m
              ll = 23 + 2*l
              sum = parlag(i,j,l)

!             Clear the last plot with blanks
              Do i2 = 1, 7
                If (i2/=4) Then
                  rec(i2)(ll:ll) = ' '
                End If
              End Do

!             Check for significance
              If (sum>c1) Then
                rec(1)(ll:ll) = '*'
              End If
              If (sum>c2) Then
                rec(2)(ll:ll) = '*'
              End If
              If (sum>c3) Then
                rec(3)(ll:ll) = '*'
              End If
              If (sum<c5) Then
                rec(5)(ll:ll) = '*'
              End If
              If (sum<c6) Then
                rec(6)(ll:ll) = '*'
              End If
              If (sum<c7) Then
                rec(7)(ll:ll) = '*'
              End If
            End Do

!           Print
            Write (nout,99997)(rec(i2),i2=1,7)
          End Do
        End Do

!       Print the chi-square statistics and p-values.
        Write (nout,*)
        Write (nout,*)
        Write (nout,*) ' Lag     Chi-square statistic     P-value'
        Write (nout,*) ' ---     --------------------     -------'
        Write (nout,*)
        Write (nout,99994)(l,x(l),pvalue(l),l=1,m)

        Return

99999   Format (/,1X,A,I2)
99998   Format (/,1X,A,F6.3,A)
99997   Format (1X,A)
99996   Format (/,/,1X,A,A,I2,/)
99995   Format (/,/,1X,A,A,I2,A,I2,/)
99994   Format (1X,I4,10X,F8.3,11X,F8.4)
      End Subroutine zprint
    End Module g13dnfe_mod
    Program g13dnfe

!     G13DNF Example Main Program

!     .. Use Statements ..
      Use nag_library, Only: g13dmf, g13dnf, nag_wp
      Use g13dnfe_mod, Only: nin, nout, zprint
!     .. Implicit None Statement ..
      Implicit None
!     .. Local Scalars ..
      Integer                          :: i, ifail, k, kmax, lwork, m, maxlag, &
                                          n
      Character (1)                    :: matrix
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: parlag(:,:,:), pvalue(:), r(:,:,:),  &
                                          r0(:,:), w(:,:), wmean(:), work(:),  &
                                          x(:)
!     .. Executable Statements ..
      Write (nout,*) 'G13DNF Example Program Results'
      Write (nout,*)

!     Skip heading in data file
      Read (nin,*)

!     Read in the problem size
      Read (nin,*) k, n, m, matrix

      kmax = k
      lwork = (5*m+6)*k**2 + k
      Allocate (w(kmax,n),wmean(k),r0(kmax,k),r(kmax,kmax,m),                  &
        parlag(kmax,kmax,m),x(m),pvalue(m),work(lwork))

!     Read in series
      Read (nin,*)(w(i,1:n),i=1,k)

!     Calculate cross correlations
      ifail = 0
      Call g13dmf(matrix,k,n,m,w,kmax,wmean,r0,r,ifail)

!     Calculate sample partial lag correlation matrices
      ifail = 0
      Call g13dnf(k,n,m,kmax,r0,r,maxlag,parlag,x,pvalue,work,lwork,ifail)

!     Display results
      Call zprint(k,n,m,kmax,parlag,x,pvalue,nout)

    End Program g13dnfe


g13dpfe.f90

!   G13DPF Example Program Text
!   Mark 26 Release. NAG Copyright 2016.

    Module g13dpfe_mod

!     G13DPF Example Program Module:
!            Parameters and User-defined Routines

!     .. Use Statements ..
      Use nag_library, Only: nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Accessibility Statements ..
      Private
      Public                           :: zprint
!     .. Parameters ..
      Integer, Parameter, Public       :: nin = 5, nout = 6
    Contains
      Subroutine zprint(k,m,ldpar,maxlag,parlag,se,qq,x,pvalue,nout,ifail)

!       .. Scalar Arguments ..
        Integer, Intent (In)           :: ifail, k, ldpar, m, maxlag, nout
!       .. Array Arguments ..
        Real (Kind=nag_wp), Intent (In) :: parlag(ldpar,ldpar,m), pvalue(m),   &
                                          qq(ldpar,ldpar,m),                   &
                                          se(ldpar,ldpar,m), x(m)
!       .. Local Scalars ..
        Real (Kind=nag_wp)             :: sum
        Integer                        :: i, i2, j, l
!       .. Local Arrays ..
        Character (6)                  :: st(6)
!       .. Executable Statements ..
!       Display titles
        If (k>1) Then
          Write (nout,99999)
        Else If (k==1) Then
          Write (nout,99998)
        End If

        Do l = 1, maxlag
          Do j = 1, k
            sum = parlag(1,j,l)
            st(j) = '.'
            If (sum>1.96E0_nag_wp*se(1,j,l)) Then
              st(j) = '+'
            End If
            If (sum<-1.96E0_nag_wp*se(1,j,l)) Then
              st(j) = '-'
            End If
          End Do
          If (k==1) Then
            Write (nout,99997) l, (parlag(1,j,l),j=1,k), (st(i2),i2=1,k),      &
              qq(1,1,l), x(l), pvalue(l)
            Write (nout,99996)(se(1,j,l),j=1,k)
          Else If (k==2) Then
            Write (nout,99995) l, (parlag(1,j,l),j=1,k), (st(i2),i2=1,k),      &
              qq(1,1,l), x(l), pvalue(l)
            Write (nout,99994)(se(1,j,l),j=1,k)
          Else If (k==3) Then
            Write (nout,99993) l, (parlag(1,j,l),j=1,k), (st(i2),i2=1,k),      &
              qq(1,1,l), x(l), pvalue(l)
            Write (nout,99992)(se(1,j,l),j=1,k)
          Else If (k==4) Then
            Write (nout,99991) l
            Write (nout,99986)(parlag(1,j,l),j=1,k), (st(i2),i2=1,k),          &
              qq(1,1,l), x(l), pvalue(l)
            Write (nout,99990)(se(1,j,l),j=1,k)
          End If

          Do i = 2, k

            Do j = 1, k
              sum = parlag(i,j,l)
              st(j) = '.'
              If (sum>1.96E0_nag_wp*se(i,j,l)) Then
                st(j) = '+'
              End If
              If (sum<-1.96E0_nag_wp*se(i,j,l)) Then
                st(j) = '-'
              End If
            End Do
            If (k==2) Then
              Write (nout,99989)(parlag(i,j,l),j=1,k), (st(i2),i2=1,k),        &
                qq(i,i,l)
              Write (nout,99994)(se(i,j,l),j=1,k)
            Else If (k==3) Then
              Write (nout,99988)(parlag(i,j,l),j=1,k), (st(i2),i2=1,k),        &
                qq(i,i,l)
              Write (nout,99992)(se(i,j,l),j=1,k)
            Else If (k==4) Then
              Write (nout,99987)(parlag(i,j,l),j=1,k), (st(i2),i2=1,k),        &
                qq(i,i,l)
              Write (nout,99990)(se(i,j,l),j=1,k)
            End If

          End Do
        End Do

        If (ifail==2) Then
          Write (nout,99985) 'Recursive equations broke down at ', maxlag + 1
        End If

        Return

99999   Format (' Partial Autoregression Matrices',4X,'Indicator',2X,          &
          'Residual',3X,'Chi-Square',2X,'Pvalue',/,37X,'Symbols',3X,           &
          'Variances',3X,'Statistic',/,' -------------------------------',4X,  &
          '---------',2X,'---------',2X,'-----------',1X,'------')
99998   Format (' Partial Autoregression Function',4X,'Indicator',2X,          &
          'Residual',3X,'Chi-Square',2X,'Pvalue',/,37X,'Symbols',3X,           &
          'Variances',3X,'Statistic',/,' -------------------------------',4X,  &
          '---------',2X,'---------',2X,'-----------',1X,'------')
99997   Format (/,' Lag',I3,1X,':',F7.3,22X,A1,F14.3,3X,F10.3,F9.3)
99996   Format (9X,'(',F6.3,')')
99995   Format (/,' Lag',I3,1X,':',2F8.3,14X,2A1,F13.3,3X,F10.3,F9.3)
99994   Format (10X,'(',F6.3,')(',F6.3,')')
99993   Format (/,' Lag',I3,1X,':',3F8.3,6X,3A1,F12.3,3X,F10.3,F9.3)
99992   Format (10X,'(',F6.3,')(',F6.3,')(',F6.3,')')
99991   Format (/,' Lag',I3)
99990   Format (2X,'(',F6.3,')(',F6.3,')(',F6.3,')(',F6.3,')')
99989   Format (9X,2F8.3,14X,2A1,F13.3)
99988   Format (9X,3F8.3,6X,3A1,F12.3)
99987   Format (1X,4F8.3,5X,4A1,F12.3)
99986   Format (1X,4F8.3,5X,4A1,F12.3,3X,F10.3,F9.3)
99985   Format (1X,A,I0)
      End Subroutine zprint
    End Module g13dpfe_mod
    Program g13dpfe

!     G13DPF Example Main Program

!     .. Use Statements ..
      Use nag_library, Only: g13dpf, nag_wp
      Use g13dpfe_mod, Only: nin, nout, zprint
!     .. Implicit None Statement ..
      Implicit None
!     .. Local Scalars ..
      Integer                          :: i, ifail, k, kmax, l, lwork, m,      &
                                          maxlag, mk, n
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: loglhd(:), parlag(:,:,:), pvalue(:), &
                                          qq(:,:,:), se(:,:,:), work(:), x(:), &
                                          z(:,:)
      Integer, Allocatable             :: iwork(:)
!     .. Executable Statements ..
      Write (nout,*) 'G13DPF Example Program Results'
      Write (nout,*)

!     Skip heading in data file
      Read (nin,*)

!     Read in the problem size
      Read (nin,*) k, n, m

      kmax = k
      mk = m*k
      l = mk + 1
      lwork = (k+1)*k + l*(4+k)*2*l**2
      Allocate (z(kmax,n),parlag(kmax,kmax,m),se(kmax,kmax,m),x(m),pvalue(m),  &
        loglhd(m),work(lwork),qq(kmax,kmax,m),iwork(mk))

!     Read in series
      Do i = 1, k
        Read (nin,*) z(i,1:n)
      End Do

!     Calculate sample partial autoregression matrices
      ifail = -1
      Call g13dpf(k,n,z,kmax,m,maxlag,parlag,se,qq,x,pvalue,loglhd,work,lwork, &
        iwork,ifail)
      If (ifail/=0) Then
        If (ifail/=2) Then
          Go To 100
        End If
      End If

!     Display results
      Call zprint(k,m,kmax,maxlag,parlag,se,qq,x,pvalue,nout,ifail)

100   Continue

    End Program g13dpfe


g13dsfe.f90

    Program g13dsfe

!     G13DSF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: g13ddf, g13dsf, nag_wp, x04abf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: iset = 1, nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: cgetol, chi, rlogl, siglev
      Integer                          :: dishow, i, idf, ifail, ip, iprint,   &
                                          iq, ishow, k, k2, kmax, ldcm, ldrcm, &
                                          liw, lpar, lwork, m, maxcal, mk2, n, &
                                          nadv, niter, npar
      Logical                          :: exact, mean
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: cm(:,:), g(:), par(:), qq(:,:),      &
                                          r(:,:,:), r0(:,:), rcm(:,:), v(:,:), &
                                          w(:,:), work(:)
      Integer, Allocatable             :: iw(:)
      Logical, Allocatable             :: parhld(:)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: max
!     .. Executable Statements ..
      Write (nout,*) 'G13DSF Example Program Results'
      Write (nout,*)
      Flush (nout)

!     Skip heading in data file
      Read (nin,*)

!     Read in the problem size
      Read (nin,*) k, ip, iq, n, mean, m

!     Calculate number of parameters for the VARMA
      k2 = k*k
      lpar = (ip+iq)*k2
      npar = lpar
      If (mean) Then
        lpar = lpar + k
      End If

      kmax = k
      ldcm = lpar
      mk2 = m*k2
      ldrcm = mk2
      liw = k*max(ip,iq)
      lwork = k*(n+kmax+2) + mk2*(npar+mk2+1) + 3*k2
      Allocate (par(lpar),parhld(lpar),qq(kmax,k),w(kmax,n),v(kmax,n),g(lpar), &
        cm(ldcm,lpar),r0(kmax,k),rcm(ldrcm,mk2),iw(liw),work(lwork),           &
        r(kmax,kmax,mk2))

!     Read in series
      Read (nin,*)(w(i,1:n),i=1,k)

!     Read in control parameters
      Read (nin,*) iprint, cgetol, maxcal, dishow

!     Read in exact likelihood flag
      Read (nin,*) exact

!     Read in initial parameter estimates and free parameter flags
      Read (nin,*) par(1:lpar)
      Read (nin,*) parhld(1:lpar)

!     Read in initial values for covariance matrix Q
      Read (nin,*)(qq(i,1:i),i=1,k)

!     Read in the ISHOW flag for G13DSF
      Read (nin,*) ishow

!     Set the advisory channel to NOUT for monitoring information
      If (iprint>=0 .Or. dishow/=0 .Or. ishow/=0) Then
        nadv = nout
        Call x04abf(iset,nadv)
      End If

!     Fit VARMA model
      ifail = -1
      Call g13ddf(k,n,ip,iq,mean,par,lpar,qq,kmax,w,parhld,exact,iprint,       &
        cgetol,maxcal,dishow,niter,rlogl,v,g,cm,ldcm,ifail)
      If (ifail/=0) Then
        If (ifail<4) Then
          Go To 100
        End If
      End If

!     Titles
      Write (nout,*)
      Write (nout,*) 'Output from G13DSF'
      Write (nout,*)
      Flush (nout)

!     Calculate and display diagnostics
      ifail = 0
      Call g13dsf(k,n,v,kmax,ip,iq,m,par,parhld,qq,ishow,r0,r,rcm,ldrcm,chi,   &
        idf,siglev,iw,liw,work,lwork,ifail)

100   Continue

    End Program g13dsfe


g13dxfe.f90

    Program g13dxfe

!     G13DXF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: g13dxf, nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Integer                          :: i, ifail, ip, k, kip, npar
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: par(:), ri(:), rmod(:), rr(:),       &
                                          work(:)
      Integer, Allocatable             :: iwork(:)
!     .. Executable Statements ..
      Write (nout,*) 'G13DXF Example Program Results'
      Write (nout,*)

!     Skip heading in data file
      Read (nin,*)

!     Read in problem size
      Read (nin,*) k, ip

      kip = k*ip
      npar = k*kip
      Allocate (par(npar),rr(kip),ri(kip),rmod(kip),work(ip*npar),iwork(kip))

!     Read the AR (or MA) parameters
      Read (nin,*) par(1:npar)

!     Calculate zeros
      ifail = 0
      Call g13dxf(k,ip,par,rr,ri,rmod,work,iwork,ifail)

!     Display results
      Write (nout,*) '        Eigenvalues       Moduli'
      Write (nout,*) '        -----------       ------'
      Do i = 1, k*ip
        If (ri(i)>=0.0E0_nag_wp) Then
          Write (nout,99999) rr(i), ri(i), rmod(i)
        Else
          Write (nout,99998) rr(i), -ri(i), rmod(i)
        End If
      End Do

99999 Format (' ',F10.3,'  + ',F6.3,' i  ',F8.3)
99998 Format (' ',F10.3,'  - ',F6.3,' i  ',F8.3)
    End Program g13dxfe


g13eafe.f90

    Program g13eafe

!     G13EAF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: daxpy, ddot, dgemv, dpotrf, dtrmv, dtrsv, g13eaf, &
                             nag_wp, x04caf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Real (Kind=nag_wp), Parameter    :: one = 1.0_nag_wp
      Real (Kind=nag_wp), Parameter    :: zero = 0.0_nag_wp
      Integer, Parameter               :: inc1 = 1, nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: dev, tol
      Integer                          :: i, ifail, info, istep, l, ldm, ldq,  &
                                          lds, lwk, m, n, ncall, tdq
      Logical                          :: full, is_const, read_matrix, stq
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: a(:,:), ax(:), b(:,:), c(:,:),       &
                                          h(:,:), k(:,:), p(:,:), q(:,:),      &
                                          r(:,:), s(:,:), wk(:), x(:), y(:),   &
                                          ymean(:)
      Integer, Allocatable             :: iwk(:)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: log
!     .. Executable Statements ..
      Write (nout,*) 'G13EAF Example Program Results'
      Write (nout,*)

!     Skip heading in data file
      Read (nin,*)

!     Read in the problem size
      Read (nin,*) n, m, l, stq, is_const

      lds = n
      If (.Not. stq) Then
        ldq = l
        tdq = l
      Else
        ldq = 1
        tdq = 1
      End If
      ldm = m
      lwk = (n+m)*(n+m+l)
      Allocate (a(lds,n),b(lds,l),q(ldq,tdq),c(ldm,n),r(ldm,m),s(lds,n),       &
        k(lds,m),h(ldm,m),iwk(m),wk(lwk),x(n),ymean(m),y(m),ax(n),p(lds,n))

!     Read in the state covariance matrix, S
      Read (nin,*)(s(i,1:n),i=1,n)

!     Read in flag indicating whether S is the full matrix, or its
!     Cholesky decomposition
      Read (nin,*) full

!     If required (full), perform the Cholesky decomposition on S
      If (full) Then
!       The NAG name equivalent of dpotrf is f07fdf
        Call dpotrf('L',n,s,lds,info)
        If (info>0) Then
          Write (nout,*) ' S not positive definite'
          Go To 100
        End If
      End If

!     Read in initial state vector
      Read (nin,*) x(1:n)

!     Read in mean of the series
      Read (nin,*) ymean(1:m)

!     Read in control parameter
      Read (nin,*) ncall, tol

!     Display titles
      Write (nout,*) '         Residuals'
      Write (nout,*)

!     Initialize variables
      dev = zero
      read_matrix = .True.

!     Loop through data
      Do istep = 1, ncall
!       Read in the various matrices. If the series is constant
!       then this only happens at the first call
        If (read_matrix) Then

!         Read in transition matrix, A
          Read (nin,*)(a(i,1:n),i=1,n)
!         Read in noise coefficient matrix, B
          Read (nin,*)(b(i,1:l),i=1,n)
!         Read in measurement coefficient matrix, C
          Read (nin,*)(c(i,1:n),i=1,m)

!         Read in measurement noise covariance matrix, R
          Read (nin,*)(r(i,1:m),i=1,m)
!         Read in flag indicating whether R is the full matrix, or its
!         Cholesky decomposition
          Read (nin,*) full
!         If required (full), perform the Cholesky decomposition on R
          If (full) Then
!           The NAG name equivalent of dpotrf is f07fdf
            Call dpotrf('L',m,r,ldm,info)
            If (info>0) Then
              Write (nout,*) ' R not positive definite'
              Go To 100
            End If
          End If

!         Read in state noise matrix Q, if not assume to be identity matrix
          If (.Not. stq) Then
            Read (nin,*)(q(i,1:l),i=1,l)
!           Read in flag indicating whether Q is the full matrix, or its
!           Cholesky decomposition
            Read (nin,*) full
!           Perform Cholesky factorization on Q, if full matrix is supplied
            If (full) Then
!             The NAG name equivalent of dpotrf is f07fdf
              Call dpotrf('L',l,q,ldq,info)
              If (info>0) Then
                Write (nout,*) ' Q not positive definite'
                Go To 100
              End If
            End If
          End If

!         If series is constant set flag to false
          read_matrix = .Not. is_const
        End If

!       Read in observed values
        Read (nin,*) y(1:m)

!       Call G13EAF
        ifail = 0
        Call g13eaf(n,m,l,a,lds,b,stq,q,ldq,c,ldm,r,s,k,h,tol,iwk,wk,ifail)

!       Subtract the mean y:= y-ymean
!       The NAG name equivalent of daxpy is f06ecf
        Call daxpy(m,-one,ymean,inc1,y,inc1)

!       Perform time and measurement update x <= Ax + K(y-Cx)
!       The NAG name equivalent of dgemv is f06paf
        Call dgemv('N',m,n,-one,c,ldm,x,inc1,one,y,1)
        Call dgemv('N',n,n,one,a,lds,x,inc1,zero,ax,1)
        Call dgemv('N',n,m,one,k,lds,y,inc1,one,ax,1)
        x(1:n) = ax(1:n)

!       Display the residuals
        Write (nout,99999) y(1:m)

!       Update log-likelihood.
!       The NAG name equivalent of dtrsv is f06pjf
        Call dtrsv('L','N','N',m,h,ldm,y,1)
!       The NAG name equivalent of ddot is f06eaf
        dev = dev + ddot(m,y,1,y,1)
        Do i = 1, m
          dev = dev + 2.0_nag_wp*log(h(i,i))
        End Do
      End Do

!     Compute P from S
!     The NAG name equivalent of dtrmv is f06pff
      Do i = 1, n
        p(1:i,i) = s(i,1:i)
        Call dtrmv('L','N','N',i,s,lds,p(1,i),inc1)
        p(i,1:i-1) = p(1:i-1,i)
      End Do

!     Display final results
      Write (nout,*)
      Write (nout,*) ' Final X(I+1:I) '
      Write (nout,*)
      Write (nout,99999) x(1:n)
      Write (nout,*)
      Flush (nout)
      ifail = 0
      Call x04caf('Lower','Non-Diag',n,n,p,lds,'Final Value of P',ifail)
      Write (nout,*)
      Write (nout,99998) ' Deviance = ', dev

100   Continue

99999 Format (6F12.4)
99998 Format (A,E13.4)
    End Program g13eafe


g13ebfe.f90

    Program g13ebfe

!     G13EBF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: ddot, dgemv, dpotrf, dsyrk, dtrsv, g13ebf,        &
                             nag_wp, x04caf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Real (Kind=nag_wp), Parameter    :: one = 1.0_nag_wp
      Real (Kind=nag_wp), Parameter    :: zero = 0.0_nag_wp
      Integer, Parameter               :: inc1 = 1, nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: dev, tol
      Integer                          :: i, ifail, info, istep, l, ldm, ldq,  &
                                          lds, lwk, m, n, ncall, tdq
      Logical                          :: full, stq
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: a(:,:), ax(:), b(:,:), c(:,:),       &
                                          h(:,:), k(:,:), p(:,:), q(:,:),      &
                                          r(:,:), s(:,:), u(:,:), us(:,:),     &
                                          wk(:), x(:), y(:)
      Integer, Allocatable             :: iwk(:)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: log
!     .. Executable Statements ..
      Write (nout,*) 'G13EBF Example Program Results'
      Write (nout,*)

!     Skip heading in data file
      Read (nin,*)

!     Read in problem size
      Read (nin,*) n, m, l, stq

      lds = n
      If (.Not. stq) Then
        ldq = l
        tdq = l
      Else
        ldq = 1
        tdq = 1
      End If
      ldm = m
      lwk = (n+m)*(n+m+l)
      Allocate (a(lds,n),b(lds,l),q(ldq,tdq),c(ldm,n),r(ldm,m),s(lds,n),       &
        k(lds,m),h(ldm,m),u(lds,n),iwk(m),wk(lwk),ax(n),y(m),x(n),p(lds,n),    &
        us(lds,n))

!     Read in the state covariance matrix, S
      Read (nin,*)(s(i,1:n),i=1,n)
!     Read in flag indicating whether S is the full matrix, or its
!     Cholesky decomposition.
      Read (nin,*) full
!     If required, perform Cholesky decomposition on S
      If (full) Then
!       The NAG name equivalent of dpotrf is f07fdf
        Call dpotrf('L',n,s,lds,info)
        If (info>0) Then
          Write (nout,*) ' S not positive definite'
          Go To 100
        End If
      End If

!     Read in initial state vector
      Read (nin,*) ax(1:n)
!     Read in transition matrix, A
      Read (nin,*)(a(i,1:n),i=1,n)
!     Read in noise coefficient matrix, B
      Read (nin,*)(b(i,1:l),i=1,n)
!     Read in measurement coefficient matrix, C
      Read (nin,*)(c(i,1:n),i=1,m)

!     Read in measurement noise covariance matrix, R
      Read (nin,*)(r(i,1:m),i=1,m)
!     Read in flag indicating whether R is the full matrix, or its Cholesky
!     decomposition
      Read (nin,*) full
!     If required, perform Cholesky decomposition on R
      If (full) Then
!       The NAG name equivalent of dpotrf is f07fdf
        Call dpotrf('L',m,r,ldm,info)
        If (info>0) Then
          Write (nout,*) ' R not positive definite'
          Go To 100
        End If
      End If

!     Read in state noise matrix Q, if not assume to be identity matrix
      If (.Not. stq) Then
        Read (nin,*)(q(i,1:l),i=1,l)
!       Read in flag indicating whether Q is the full matrix, or
!       its Cholesky decomposition
        Read (nin,*) full
!       Perform Cholesky factorization on Q, if full matrix is supplied
        If (full) Then
!         The NAG name equivalent of dpotrf is f07fdf
          Call dpotrf('L',l,q,ldq,info)
          If (info>0) Then
            Write (nout,*) ' Q not positive definite'
            Go To 100
          End If
        End If
      End If

!     Read in control parameters
      Read (nin,*) ncall, tol

!     Display titles
      Write (nout,*) '         Residuals'
      Write (nout,*)

!     Loop through data
      dev = 0.0E0_nag_wp
      Do istep = 1, ncall

!       Read in observed values
        Read (nin,*) y(1:m)

        If (istep==1) Then
!         Make first call to G13EBF
          ifail = 0
          Call g13ebf('T',n,m,l,a,lds,b,stq,q,ldq,c,ldm,r,s,k,h,u,tol,iwk,wk,  &
            ifail)

!         The NAG name equivalent of dgemv is f06paf
          Call dgemv('N',n,n,one,u,lds,ax,inc1,zero,x,inc1)

        Else
!         Make remaining calls to G13EBF
          ifail = 0
          Call g13ebf('H',n,m,l,a,lds,b,stq,q,ldq,c,ldm,r,s,k,h,u,tol,iwk,wk,  &
            ifail)
        End If

!       Perform time and measurement update x <= Ax + K(y-Cx)
!       The NAG name equivalent of dgemv is f06paf
        Call dgemv('N',m,n,-one,c,ldm,x,inc1,one,y,inc1)
        Call dgemv('N',n,n,one,a,lds,x,inc1,zero,ax,inc1)
        Call dgemv('N',n,m,one,k,lds,y,inc1,one,ax,inc1)
        x(1:n) = ax(1:n)

!       Display the residuals
        Write (nout,99999) y(1:m)

!       Update log-likelihood
!       The NAG name equivalent of dtrsv is f06pjf
        Call dtrsv('L','N','N',m,h,ldm,y,inc1)
!       The NAG name equivalent of ddot is f06eaf
        dev = dev + ddot(m,y,1,y,1)
        Do i = 1, m
          dev = dev + 2.0_nag_wp*log(h(i,i))
        End Do
      End Do

!     Calculate back-transformed x <- U^T x
!     The NAG name equivalent of dgemv is f06paf
      Call dgemv('T',n,n,one,u,lds,ax,inc1,zero,x,inc1)

!     Compute back-transformed P from S
      Do i = 1, n
        Call dgemv('T',n-i+1,n,one,u(i,1),lds,s(i,i),inc1,zero,us(1,i),inc1)
      End Do
!     The NAG name equivalent of dsyrk is f06ypf
      Call dsyrk('L','N',n,n,one,us,lds,zero,p,lds)

!     Display final results
      Write (nout,*)
      Write (nout,*) ' Final X(I+1:I) '
      Write (nout,99999) x(1:n)
      Write (nout,*)
      Flush (nout)
      ifail = 0
      Call x04caf('Lower','N',n,n,p,lds,'Final Value of P',ifail)
      Write (nout,99998) ' Deviance = ', dev

100   Continue

99999 Format (6F12.4)
99998 Format (A,E13.4)
    End Program g13ebfe


g13ejfe.f90

!   G13EJF Example Program Text
!   Mark 26 Release. NAG Copyright 2016.

    Module g13ejfe_mod

!     G13EJF Example Program Module:
!     User-defined Routines

!     .. Use Statements ..
      Use nag_library, Only: nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Accessibility Statements ..
      Private
      Public                           :: f, h, read_problem_data
!     .. Parameters ..
      Integer, Parameter, Public       :: mx = 3, my = 2, nin = 5, nout = 6
!     .. Derived Type Definitions ..
      Type, Public                     :: g13ej_problem_data
        Real (Kind=nag_wp)             :: delta, a, r, d
        Real (Kind=nag_wp)             :: phi_rt, phi_lt
      End Type g13ej_problem_data
    Contains
      Subroutine f(n,xt,fxt,dat)

!       .. Scalar Arguments ..
        Type (g13ej_problem_data), Intent (In) :: dat
        Integer, Intent (In)           :: n
!       .. Array Arguments ..
        Real (Kind=nag_wp), Intent (Out) :: fxt(:,:)
        Real (Kind=nag_wp), Intent (In) :: xt(:,:)
!       .. Local Scalars ..
        Real (Kind=nag_wp)             :: t1, t3
        Integer                        :: i
!       .. Intrinsic Procedures ..
        Intrinsic                      :: cos, sin
!       .. Executable Statements ..
        Continue

        t1 = 0.5_nag_wp*dat%r*(dat%phi_rt+dat%phi_lt)
        t3 = (dat%r/dat%d)*(dat%phi_rt-dat%phi_lt)

        Do i = 1, n
          fxt(1,i) = xt(1,i) + cos(xt(3,i))*t1
          fxt(2,i) = xt(2,i) + sin(xt(3,i))*t1
          fxt(3,i) = xt(3,i) + t3
        End Do

        Return
      End Subroutine f
      Subroutine h(n,yt,hyt,dat)

!       .. Use Statements ..
        Use nag_library, Only: x01aaf
!       .. Scalar Arguments ..
        Type (g13ej_problem_data), Intent (In) :: dat
        Integer, Intent (In)           :: n
!       .. Array Arguments ..
        Real (Kind=nag_wp), Intent (Out) :: hyt(:,:)
        Real (Kind=nag_wp), Intent (In) :: yt(:,:)
!       .. Local Scalars ..
        Real (Kind=nag_wp)             :: tmp
        Integer                        :: i
!       .. Intrinsic Procedures ..
        Intrinsic                      :: cos, sin
!       .. Executable Statements ..
        Continue

        Do i = 1, n
          hyt(1,i) = dat%delta - yt(1,i)*cos(dat%a) - yt(2,i)*sin(dat%a)
          hyt(2,i) = yt(3,i) - dat%a

!         Make sure that the theta is in the same range as the observed
!         data, which in this case is [0, 2*pi)
          If (hyt(2,i)<0.0_nag_wp) Then
            hyt(2,i) = hyt(2,i) + 2*x01aaf(tmp)
          End If
        End Do

        Return
      End Subroutine h
      Subroutine read_problem_data(t,dat,read_ok)
!       Read in any data specific to the F and H subroutines

!       .. Scalar Arguments ..
        Type (g13ej_problem_data), Intent (Inout) :: dat
        Integer, Intent (In)           :: t
        Logical, Intent (Out)          :: read_ok
!       .. Local Scalars ..
        Integer                        :: tt
!       .. Executable Statements ..
        Continue

        If (t==0) Then
!         Read in the data that is constant across all time points
          Read (nin,*) dat%r, dat%d, dat%delta, dat%a
          read_ok = .True.
        Else
!         Read in data for time point t
          Read (nin,*) tt, dat%phi_rt, dat%phi_lt
          If (tt/=t) Then
!           Sanity check
            Write (nout,99999) 'Expected to read in data for time point ', t
            Write (nout,99999) 'Data that was read in was for time point ', tt
99999       Format (A,E22.15)
            read_ok = .False.
          Else
            read_ok = .True.
          End If
        End If
      End Subroutine read_problem_data
    End Module g13ejfe_mod

    Program g13ejfe

!     .. Use Statements ..
      Use nag_library, Only: g13ejf, nag_wp
      Use g13ejfe_mod, Only: f, g13ej_problem_data, h, mx, my, nin, nout,      &
                             read_problem_data
!     .. Implicit None Statement ..
      Implicit None
!     .. Local Scalars ..
      Type (g13ej_problem_data)        :: dat
      Integer                          :: i, ifail, irevcm, ldfxt, ldlx, ldly, &
                                          ldst, ldxt, licomm, lrcomm, lropt,   &
                                          n, ntime, t
      Logical                          :: read_ok
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: fxt(:,:), lx(:,:), ly(:,:),          &
                                          rcomm(:), ropt(:), st(:,:), x(:),    &
                                          xt(:,:), y(:)
      Integer, Allocatable             :: icomm(:)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: abs, max, repeat
!     .. Executable Statements ..
      Write (nout,*) 'G13EJF Example Program Results'
      Write (nout,*)

!     Skip heading in data file
      Read (nin,*)

!     Using default optional arguments
      lropt = 0
      Allocate (ropt(lropt))

!     Allocate arrays
      n = 2*mx + 1
      If (lropt>=1) Then
        If (abs(ropt(1)-2.0_nag_wp)<=0.0_nag_wp) Then
          n = n + 2*mx
        End If
      End If
      ldlx = mx
      ldly = my
      ldst = mx
      ldxt = mx
      ldfxt = max(mx,my)
      licomm = 30
      lrcomm = 30 + my + mx*my + 2*max(mx,my)
      Allocate (lx(ldlx,mx),ly(ldly,my),x(mx),st(ldst,mx),xt(ldxt,max(my,      &
        n)),fxt(ldfxt,n+max(mx,my)),icomm(licomm),rcomm(lrcomm),y(my))

!     Read in the Cholesky factorization of the covariance matrix for the
!     process noise
      Do i = 1, mx
        Read (nin,*) lx(i,1:i)
      End Do

!     Read in the Cholesky factorization of the covariance matrix for the
!     observation noise
      Do i = 1, my
        Read (nin,*) ly(i,1:i)
      End Do

!     Read in the initial state vector
      Read (nin,*) x(1:mx)

!     Read in the Cholesky factorization of the initial state covariance
!     matrix
      Do i = 1, mx
        Read (nin,*) st(i,1:i)
      End Do

!     Read in the number of time points to run the system for
      Read (nin,*) ntime

!     Read in any problem specific data that is constant
      Call read_problem_data(0,dat,read_ok)
      If (.Not. read_ok) Then
        Go To 100
      End If

!     Title for first set of output
      Write (nout,*) ' Time   ', repeat(' ',(11*mx-16)/2), 'Estimate of State'
      Write (nout,*) repeat('-',7+11*mx)

!     Loop over each time point
      irevcm = 0
      Do t = 1, ntime

!       Read in any problem specific data that is time dependent
        Call read_problem_data(t,dat,read_ok)
        If (.Not. read_ok) Then
          Go To 100
        End If

!       Read in the observed data for time t
        Read (nin,*) y(1:my)

!       Call Unscented Kalman Filter routine
ukf_lp: Do
          ifail = 0
          Call g13ejf(irevcm,mx,my,y,lx,ldlx,ly,ldly,x,st,ldst,n,xt,ldxt,fxt,  &
            ldfxt,ropt,lropt,icomm,licomm,rcomm,lrcomm,ifail)
          Select Case (irevcm)
          Case (1)
!           Evaluate F(X)
            Call f(n,xt,fxt,dat)

          Case (2)
!           Evaluate H(X)
            Call h(n,xt,fxt,dat)

          Case Default
!           IREVCM = 3, finished
            Exit ukf_lp
          End Select
        End Do ukf_lp

!       Display the some of the current state estimate
        Write (nout,99999) t, x(1:mx)
      End Do

      Write (nout,*)
      Write (nout,*) 'Estimate of Cholesky Factorization of the State'
      Write (nout,*) 'Covariance Matrix at the Last Time Point'
      Do i = 1, mx
        Write (nout,99998) st(i,1:i)
      End Do

100   Continue

99999 Format (1X,I3,4X,10(1X,F10.3))
99998 Format (10(1X,E10.3))
    End Program g13ejfe


g13ekfe.f90

!   G13EKF Example Program Text
!   Mark 26 Release. NAG Copyright 2016.

    Module g13ekfe_mod

!     G13EKF Example Program Module:
!     User-defined Routines

!     .. Use Statements ..
      Use nag_library, Only: nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Accessibility Statements ..
      Private
      Public                           :: f, h, read_problem_data
!     .. Parameters ..
      Integer, Parameter, Public       :: mx = 3, my = 2, nin = 5, nout = 6
    Contains
      Subroutine f(mx,n,xt,fxt,iuser,ruser,info)

!       .. Scalar Arguments ..
        Integer, Intent (Inout)        :: info
        Integer, Intent (In)           :: mx, n
!       .. Array Arguments ..
        Real (Kind=nag_wp), Intent (Out) :: fxt(mx,n)
        Real (Kind=nag_wp), Intent (Inout) :: ruser(*)
        Real (Kind=nag_wp), Intent (In) :: xt(mx,n)
        Integer, Intent (Inout)        :: iuser(*)
!       .. Local Scalars ..
        Real (Kind=nag_wp)             :: d, phi_lt, phi_rt, r, t1, t3
        Integer                        :: i
!       .. Intrinsic Procedures ..
        Intrinsic                      :: cos, sin
!       .. Executable Statements ..
        Continue

        r = ruser(3)
        d = ruser(4)
        phi_rt = ruser(5)
        phi_lt = ruser(6)

        t1 = 0.5_nag_wp*r*(phi_rt+phi_lt)
        t3 = (r/d)*(phi_rt-phi_lt)

        Do i = 1, n
          fxt(1,i) = xt(1,i) + cos(xt(3,i))*t1
          fxt(2,i) = xt(2,i) + sin(xt(3,i))*t1
          fxt(3,i) = xt(3,i) + t3
        End Do

!       Set info nonzero to terminate execution for any reason.
        info = 0

        Return
      End Subroutine f
      Subroutine h(mx,my,n,yt,hyt,iuser,ruser,info)

!       .. Use Statements ..
        Use nag_library, Only: x01aaf
!       .. Scalar Arguments ..
        Integer, Intent (Inout)        :: info
        Integer, Intent (In)           :: mx, my, n
!       .. Array Arguments ..
        Real (Kind=nag_wp), Intent (Out) :: hyt(my,n)
        Real (Kind=nag_wp), Intent (Inout) :: ruser(*)
        Real (Kind=nag_wp), Intent (In) :: yt(mx,n)
        Integer, Intent (Inout)        :: iuser(*)
!       .. Local Scalars ..
        Real (Kind=nag_wp)             :: a, delta, tmp
        Integer                        :: i
!       .. Intrinsic Procedures ..
        Intrinsic                      :: cos, sin
!       .. Executable Statements ..
        Continue

        delta = ruser(1)
        a = ruser(2)

        Do i = 1, n
          hyt(1,i) = delta - yt(1,i)*cos(a) - yt(2,i)*sin(a)
          hyt(2,i) = yt(3,i) - a

!         Make sure that the theta is in the same range as the observed
!         data, which in this case is [0, 2*pi)
          If (hyt(2,i)<0.0_nag_wp) Then
            hyt(2,i) = hyt(2,i) + 2*x01aaf(tmp)
          End If
        End Do

!       Set info nonzero to terminate execution for any reason.
        info = 0

        Return
      End Subroutine h
      Subroutine read_problem_data(t,iuser,ruser,read_ok)
!       Read in any data specific to the F and H subroutines

!       .. Scalar Arguments ..
        Integer, Intent (In)           :: t
        Logical, Intent (Out)          :: read_ok
!       .. Array Arguments ..
        Real (Kind=nag_wp), Allocatable, Intent (Inout) :: ruser(:)
        Integer, Allocatable, Intent (Inout) :: iuser(:)
!       .. Local Scalars ..
        Real (Kind=nag_wp)             :: a, d, delta, phi_lt, phi_rt, r
        Integer                        :: tt
!       .. Executable Statements ..
        Continue

        If (t==0) Then
!         Allocate the arrays to hold the data
          Allocate (ruser(6),iuser(0))

!         Read in the data that is constant across all time points
          Read (nin,*) r, d, delta, a

!         Store the data in RUSER
          ruser(1) = delta
          ruser(2) = a
          ruser(3) = r
          ruser(4) = d

          read_ok = .True.
        Else
!         Read in data for time point t
          Read (nin,*) tt, phi_rt, phi_lt
          If (tt/=t) Then
!           Sanity check
            Write (nout,99999) 'Expected to read in data for time point ', t
            Write (nout,99999) 'Data that was read in was for time point ', tt
99999       Format (A,E22.15)
            read_ok = .False.
          Else
            read_ok = .True.
          End If

!         Store the data in RUSER
          ruser(5) = phi_rt
          ruser(6) = phi_lt

        End If
      End Subroutine read_problem_data
    End Module g13ekfe_mod

    Program g13ekfe

!     .. Use Statements ..
      Use nag_library, Only: g13ekf, nag_wp
      Use g13ekfe_mod, Only: f, h, mx, my, nin, nout, read_problem_data
!     .. Implicit None Statement ..
      Implicit None
!     .. Local Scalars ..
      Integer                          :: i, ifail, ntime, t
      Logical                          :: read_ok
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: lx(:,:), ly(:,:), ruser(:), st(:,:), &
                                          x(:), y(:)
      Integer, Allocatable             :: iuser(:)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: repeat
!     .. Executable Statements ..
      Write (nout,*) 'G13EKF Example Program Results'
      Write (nout,*)

!     Skip heading in data file
      Read (nin,*)

!     Allocate arrays
      Allocate (lx(mx,mx),ly(my,my),x(mx),st(mx,mx),y(my))

!     Read in the Cholesky factorization of the covariance matrix for the
!     process noise
      Do i = 1, mx
        Read (nin,*) lx(i,1:i)
      End Do

!     Read in the Cholesky factorization of the covariance matrix for the
!     observation noise
      Do i = 1, my
        Read (nin,*) ly(i,1:i)
      End Do

!     Read in the initial state vector
      Read (nin,*) x(1:mx)

!     Read in the Cholesky factorization of the initial state covariance
!     matrix
      Do i = 1, mx
        Read (nin,*) st(i,1:i)
      End Do

!     Read in the number of time points to run the system for
      Read (nin,*) ntime

!     Read in any problem specific data that is constant
      Call read_problem_data(0,iuser,ruser,read_ok)
      If (.Not. read_ok) Then
        Go To 100
      End If

!     Title for first set of output
      Write (nout,*) ' Time   ', repeat(' ',(11*mx-16)/2), 'Estimate of State'
      Write (nout,*) repeat('-',7+11*mx)

!     Loop over each time point
      Do t = 1, ntime

!       Read in any problem specific data that is time dependent
        Call read_problem_data(t,iuser,ruser,read_ok)
        If (.Not. read_ok) Then
          Go To 100
        End If

!       Read in the observed data for time t
        Read (nin,*) y(1:my)

!       Call Unscented Kalman Filter routine
        ifail = 0
        Call g13ekf(mx,my,y,lx,ly,f,h,x,st,iuser,ruser,ifail)

!       Display the some of the current state estimate
        Write (nout,99999) t, x(1:mx)
      End Do

      Write (nout,*)
      Write (nout,*) 'Estimate of Cholesky Factorization of the State'
      Write (nout,*) 'Covariance Matrix at the Last Time Point'
      Do i = 1, mx
        Write (nout,99998) st(i,1:i)
      End Do

100   Continue

99999 Format (1X,I3,4X,10(1X,F10.3))
99998 Format (10(1X,E10.3))
    End Program g13ekfe


g13fafe.f90

    Program g13fafe

!     G13FAF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: g13faf, g13fbf, nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: gamma, hp, lgf, tol
      Integer                          :: i, ifail, ip, iq, isym, l, ldcovr,   &
                                          ldx, lwork, maxit, mn, npar, nreg,   &
                                          nt, num, pgamma
      Logical                          :: tdist
      Character (1)                    :: dist
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: covr(:,:), et(:), fht(:), ht(:),     &
                                          sc(:), se(:), theta(:), work(:),     &
                                          x(:,:), yt(:)
      Logical                          :: copts(2)
!     .. Executable Statements ..
      Write (nout,*) 'G13FAF Example Program Results'
      Write (nout,*)

!     Skip heading in data file
      Read (nin,*)

!     Read in the problem size
      Read (nin,*) num, mn, nreg

      ldx = num
      Allocate (yt(num),x(ldx,nreg))

!     Read in the series
      Read (nin,*) yt(1:num)

!     Read in the exogenous variables
      If (nreg>0) Then
        Read (nin,*,Iostat=ifail)(x(i,1:nreg),i=1,num)
      End If

!     Read in details of the model to fit
      Read (nin,*) dist, ip, iq, isym

!     Read in control parameters
      Read (nin,*) copts(1:2), maxit, tol

!     Calculate NPAR
      npar = 1 + iq + ip + isym + mn + nreg
      If (dist=='T' .Or. dist=='t') Then
        npar = npar + 1
        tdist = .True.
      Else
        tdist = .False.
      End If

      ldcovr = npar
      lwork = (nreg+3)*num + npar + 403
      Allocate (theta(npar),se(npar),sc(npar),covr(ldcovr,npar),et(num),       &
        ht(num),work(lwork))

!     Read in initial values
!     alpha_0
      Read (nin,*) theta(1)
      l = 2
!     alpha_i
      If (iq>0) Then
        Read (nin,*) theta(l:(l+iq-1))
        l = l + iq
      End If
!     beta_i
      If (ip>0) Then
        Read (nin,*) theta(l:(l+ip-1))
        l = l + ip
      End If
!     gamma
      If (isym==1) Then
        Read (nin,*) theta(l)
        pgamma = l
        l = l + 1
      End If
!     degrees of freedom
      If (tdist) Then
        Read (nin,*) theta(l)
        l = l + 1
      End If
!     mean
      If (mn==1) Then
        Read (nin,*) theta(l)
        l = l + 1
      End If
!     Regression parameters and pre-observed conditional variance
      If (.Not. copts(2)) Then
        Read (nin,*) theta(l:(l+nreg-1))
        Read (nin,*) hp
      End If

!     Fit the GARCH model
      ifail = -1
      Call g13faf(dist,yt,x,ldx,num,ip,iq,nreg,mn,isym,npar,theta,se,sc,covr,  &
        ldcovr,hp,et,ht,lgf,copts,maxit,tol,work,lwork,ifail)
      If (ifail/=0) Then
        If (ifail/=5 .And. ifail/=6) Then
          Go To 100
        End If
      End If

!     Read in forecast horizon
      Read (nin,*) nt

      Allocate (fht(nt))

!     Extract the estimate of the asymmetry parameter from theta
      If (isym==1) Then
        gamma = theta(pgamma)
      Else
        gamma = 0.0E0_nag_wp
      End If

!     Calculate the volatility forecast
      ifail = 0
      Call g13fbf(num,nt,ip,iq,theta,gamma,fht,ht,et,ifail)

!     Output the results
      Write (nout,*) '               Parameter        Standard'
      Write (nout,*) '               estimates         errors'
!     Output the coefficient alpha_0
      Write (nout,99999) 'Alpha', 0, theta(1), se(1)
      l = 2
!     Output the coefficients alpha_i
      If (iq>0) Then
        Write (nout,99999)('Alpha',i-1,theta(i),se(i),i=l,l+iq-1)
        l = l + iq
      End If
      Write (nout,*)
!     Output the coefficients beta_j
      If (ip>0) Then
        Write (nout,99999)(' Beta',i-l+1,theta(i),se(i),i=l,l+ip-1)
        l = l + ip
        Write (nout,*)
      End If
!     Output the estimated asymmetry parameter, gamma
      If (isym==1) Then
        Write (nout,99998) ' Gamma', theta(l), se(l)
        Write (nout,*)
        l = l + 1
      End If
!     Output the estimated degrees of freedom, df
      If (dist=='T') Then
        Write (nout,99998) '    DF', theta(l), se(l)
        Write (nout,*)
        l = l + 1
      End If
!     Output the estimated mean term, b_0
      If (mn==1) Then
        Write (nout,99999) '    B', 0, theta(l), se(l)
        l = l + 1
      End If
!     Output the estimated linear regression coefficients, b_i
      If (nreg>0) Then
        Write (nout,99999)('    B',i-l+1,theta(i),se(i),i=l,l+nreg-1)
      End If
      Write (nout,*)

!     Display the volatility forecast
      Write (nout,99997) 'Volatility forecast = ', fht(nt)
      Write (nout,*)

100   Continue

99999 Format (1X,A,I0,1X,2F16.2)
99998 Format (1X,A,1X,2F16.2)
99997 Format (1X,A,F12.2)
    End Program g13fafe


g13fcfe.f90

    Program g13fcfe

!     G13FCF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: g13fcf, g13fdf, nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: gamma, hp, lgf, tol
      Integer                          :: i, ifail, ip, iq, l, ldcovr, ldx,    &
                                          lwork, maxit, mn, npar, nreg, nt,    &
                                          num, pgamma
      Logical                          :: tdist
      Character (1)                    :: dist
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: covr(:,:), et(:), fht(:), ht(:),     &
                                          sc(:), se(:), theta(:), work(:),     &
                                          x(:,:), yt(:)
      Logical                          :: copts(2)
!     .. Executable Statements ..
      Write (nout,*) 'G13FCF Example Program Results'
      Write (nout,*)

!     Skip heading in data file
      Read (nin,*)

!     Read in the problem size
      Read (nin,*) num, mn, nreg

      ldx = num
      Allocate (yt(num),x(ldx,nreg))

!     Read in the series
      Read (nin,*) yt(1:num)

!     Read in the exogenous variables
      If (nreg>0) Then
        Read (nin,*)(x(i,1:nreg),i=1,num)
      End If

!     Read in details of the model to fit
      Read (nin,*) dist, ip, iq

!     Read in control parameters
      Read (nin,*) copts(1:2), maxit, tol

!     Calculate NPAR
      npar = 2 + iq + ip + mn + nreg
      If (dist=='T' .Or. dist=='t') Then
        npar = npar + 1
        tdist = .True.
      Else
        tdist = .False.
      End If

      ldcovr = npar
      lwork = (nreg+3)*num + npar + 403
      Allocate (theta(npar),se(npar),sc(npar),covr(ldcovr,npar),et(num),       &
        ht(num),work(lwork))

!     Read in initial values
!     alpha_0
      Read (nin,*) theta(1)
      l = 2
!     alpha_i
      If (iq>0) Then
        Read (nin,*) theta(l:(l+iq-1))
        l = l + iq
      End If
!     beta_i
      If (ip>0) Then
        Read (nin,*) theta(l:(l+ip-1))
        l = l + ip
      End If
!     gamma
      Read (nin,*) theta(l)
      pgamma = l
      l = l + 1
!     degrees of freedom
      If (tdist) Then
        Read (nin,*) theta(l)
        l = l + 1
      End If
!     mean
      If (mn==1) Then
        Read (nin,*) theta(l)
        l = l + 1
      End If
!     Regression parameters and pre-observed conditional variance
      If (.Not. copts(2)) Then
        Read (nin,*) theta(l:(l+nreg-1))
        Read (nin,*) hp
      End If

!     Fit the GARCH model
      ifail = -1
      Call g13fcf(dist,yt,x,ldx,num,ip,iq,nreg,mn,npar,theta,se,sc,covr,       &
        ldcovr,hp,et,ht,lgf,copts,maxit,tol,work,lwork,ifail)
      If (ifail/=0) Then
        If (ifail/=5 .And. ifail/=6) Then
          Go To 100
        End If
      End If

!     Read in forecast horizon
      Read (nin,*) nt

      Allocate (fht(nt))

!     Extract the estimate of the asymmetry parameter from theta
      gamma = theta(pgamma)

!     Calculate the volatility forecast
      ifail = 0
      Call g13fdf(num,nt,ip,iq,theta,gamma,fht,ht,et,ifail)

!     Output the results
      Write (nout,*) '               Parameter        Standard'
      Write (nout,*) '               estimates         errors'
!     Output the coefficient alpha_0
      Write (nout,99999) 'Alpha', 0, theta(1), se(1)
      l = 2
!     Output the coefficients alpha_i
      If (iq>0) Then
        Write (nout,99999)('Alpha',i-1,theta(i),se(i),i=l,l+iq-1)
        l = l + iq
      End If
      Write (nout,*)
!     Output the coefficients beta_j
      If (ip>0) Then
        Write (nout,99999)(' Beta',i-l+1,theta(i),se(i),i=l,l+ip-1)
        l = l + ip
        Write (nout,*)
      End If
!     Output the estimated asymmetry parameter, gamma
      Write (nout,99998) ' Gamma', theta(l), se(l)
      Write (nout,*)
      l = l + 1
!     Output the estimated degrees of freedom, df
      If (dist=='T') Then
        Write (nout,99998) '    DF', theta(l), se(l)
        Write (nout,*)
        l = l + 1
      End If
!     Output the estimated mean term, b_0
      If (mn==1) Then
        Write (nout,99999) '    B', 0, theta(l), se(l)
        l = l + 1
      End If
!     Output the estimated linear regression coefficients, b_i
      If (nreg>0) Then
        Write (nout,99999)('    B',i-l+1,theta(i),se(i),i=l,l+nreg-1)
      End If
      Write (nout,*)

!     Display the volatility forecast
      Write (nout,*)
      Write (nout,99997) 'Volatility forecast = ', fht(nt)
      Write (nout,*)

100   Continue

99999 Format (1X,A,I0,1X,2F16.2)
99998 Format (1X,A,1X,2F16.2)
99997 Format (1X,A,F12.2)
    End Program g13fcfe


g13fefe.f90

    Program g13fefe

!     G13FEF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: g13fef, g13fff, nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: gamma, hp, lgf, tol
      Integer                          :: i, ifail, ip, iq, l, ldcovr, ldx,    &
                                          lwork, maxit, mn, npar, nreg, nt,    &
                                          num, pgamma
      Logical                          :: tdist
      Character (1)                    :: dist
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: covr(:,:), et(:), fht(:), ht(:),     &
                                          sc(:), se(:), theta(:), work(:),     &
                                          x(:,:), yt(:)
      Logical                          :: copts(2)
!     .. Executable Statements ..
      Write (nout,*) 'G13FEF Example Program Results'
      Write (nout,*)

!     Skip heading in data file
      Read (nin,*)

!     Read in the problem size
      Read (nin,*) num, mn, nreg

      ldx = num
      Allocate (yt(num),x(ldx,nreg))

!     Read in the series
      Read (nin,*) yt(1:num)

!     Read in the exogenous variables
      If (nreg>0) Then
        Read (nin,*)(x(i,1:nreg),i=1,num)
      End If

!     Read in details of the model to fit
      Read (nin,*) dist, ip, iq

!     Read in control parameters
      Read (nin,*) copts(1:2), maxit, tol

!     Calculate NPAR
      npar = 2 + iq + ip + mn + nreg
      If (dist=='T' .Or. dist=='t') Then
        npar = npar + 1
        tdist = .True.
      Else
        tdist = .False.
      End If

      ldcovr = npar
      lwork = (nreg+3)*num + npar + 403
      Allocate (theta(npar),se(npar),sc(npar),covr(ldcovr,npar),et(num),       &
        ht(num),work(lwork))

!     Read in initial values
!     alpha_0
      Read (nin,*) theta(1)
      l = 2
!     alpha_i
      If (iq>0) Then
        Read (nin,*) theta(l:(l+iq-1))
        l = l + iq
      End If
!     beta_i
      If (ip>0) Then
        Read (nin,*) theta(l:(l+ip-1))
        l = l + ip
      End If
!     gamma
      Read (nin,*) theta(l)
      pgamma = l
      l = l + 1
!     degrees of freedom
      If (tdist) Then
        Read (nin,*) theta(l)
        l = l + 1
      End If
!     mean
      If (mn==1) Then
        Read (nin,*) theta(l)
        l = l + 1
      End If
!     Regression parameters and pre-observed conditional variance
      If (.Not. copts(2)) Then
        Read (nin,*) theta(l:(l+nreg-1))
        Read (nin,*) hp
      End If

!     Fit the GARCH model
      ifail = -1
      Call g13fef(dist,yt,x,ldx,num,ip,iq,nreg,mn,npar,theta,se,sc,covr,       &
        ldcovr,hp,et,ht,lgf,copts,maxit,tol,work,lwork,ifail)
      If (ifail/=0) Then
        If (ifail/=5 .And. ifail/=6) Then
          Go To 100
        End If
      End If

!     Read in forecast horizon
      Read (nin,*) nt

      Allocate (fht(nt))

!     Extract the estimate of the asymmetry parameter from theta
      gamma = theta(pgamma)

!     Calculate the volatility forecast
      ifail = 0
      Call g13fff(num,nt,ip,iq,theta,gamma,fht,ht,et,ifail)

!     Output the results
      Write (nout,*) '               Parameter        Standard'
      Write (nout,*) '               estimates         errors '
!     Output the coefficient alpha_0
      Write (nout,99999) 'Alpha', 0, theta(1), se(1)
      l = 2
!     Output the coefficients alpha_i
      If (iq>0) Then
        Write (nout,99999)('Alpha',i-1,theta(i),se(i),i=l,l+iq-1)
        l = l + iq
      End If
      Write (nout,*)
!     Output the coefficients beta_j
      If (ip>0) Then
        Write (nout,99999)(' Beta',i-l+1,theta(i),se(i),i=l,l+ip-1)
        l = l + ip
        Write (nout,*)
      End If
!     Output the estimated asymmetry parameter, gamma
      Write (nout,99998) ' Gamma', theta(l), se(l)
      Write (nout,*)
      l = l + 1
!     Output the estimated degrees of freedom, df
      If (dist=='T') Then
        Write (nout,99998) '    DF', theta(l), se(l)
        Write (nout,*)
        l = l + 1
      End If
!     Output the estimated mean term, b_0
      If (mn==1) Then
        Write (nout,99999) '    B', 0, theta(l), se(l)
        l = l + 1
      End If
!     Output the estimated linear regression coefficients, b_i
      If (nreg>0) Then
        Write (nout,99999)('    B',i-l+1,theta(i),se(i),i=l,l+nreg-1)
      End If
      Write (nout,*)

!     Display the volatility forecast
      Write (nout,*)
      Write (nout,99997) 'Volatility forecast = ', fht(nt)
      Write (nout,*)

100   Continue

99999 Format (1X,A,I0,1X,2F16.2)
99998 Format (1X,A,1X,2F16.2)
99997 Format (1X,A,F12.2)
    End Program g13fefe


g13fgfe.f90

    Program g13fgfe

!     G13FGF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: g13fgf, g13fhf, nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: hp, lgf, tol
      Integer                          :: i, ifail, ip, iq, l, ldcovr, ldx,    &
                                          lwork, maxit, mn, npar, nreg, nt,    &
                                          num
      Logical                          :: copts, tdist
      Character (1)                    :: dist
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: covr(:,:), et(:), fht(:), ht(:),     &
                                          sc(:), se(:), theta(:), work(:),     &
                                          x(:,:), yt(:)
!     .. Executable Statements ..
      Write (nout,*) 'G13FGF Example Program Results'
      Write (nout,*)

!     Skip heading in data file
      Read (nin,*)

!     Read in the problem size
      Read (nin,*) num, mn, nreg

      ldx = num
      Allocate (yt(num),x(ldx,nreg))

!     Read in the series
      Read (nin,*) yt(1:num)

!     Read in the exogenous variables
      If (nreg>0) Then
        Read (nin,*)(x(i,1:nreg),i=1,num)
      End If

!     Read in details of the model to fit
      Read (nin,*) dist, ip, iq

!     Read in control parameters
      Read (nin,*) copts, maxit, tol

!     Calculate NPAR
      npar = 1 + 2*iq + ip + mn + nreg
      If (dist=='T' .Or. dist=='t') Then
        npar = npar + 1
        tdist = .True.
      Else
        tdist = .False.
      End If

      ldcovr = npar
      lwork = (nreg+3)*num + npar + 403
      Allocate (theta(npar),se(npar),sc(npar),covr(ldcovr,npar),et(num),       &
        ht(num),work(lwork))

!     Read in initial values
!     alpha_0
      Read (nin,*) theta(1)
      l = 2
!     alpha_i and psi_i
      If (iq>0) Then
        Read (nin,*) theta(l:(l+iq-1))
        l = l + iq
        Read (nin,*) theta(l:(l+iq-1))
        l = l + iq
      End If
!     beta_i
      If (ip>0) Then
        Read (nin,*) theta(l:(l+ip-1))
        l = l + ip
      End If
!     degrees of freedom
      If (tdist) Then
        Read (nin,*) theta(l)
        l = l + 1
      End If
!     mean
      If (mn==1) Then
        Read (nin,*) theta(l)
        l = l + 1
      End If
!     Regression parameters and pre-observed conditional variance
      If (.Not. copts) Then
        Read (nin,*) theta(l:(l+nreg-1))
        Read (nin,*) hp
      End If

!     Fit the GARCH model
      ifail = -1
      Call g13fgf(dist,yt,x,ldx,num,ip,iq,nreg,mn,npar,theta,se,sc,covr,       &
        ldcovr,hp,et,ht,lgf,copts,maxit,tol,work,lwork,ifail)
      If (ifail/=0) Then
        If (ifail/=5 .And. ifail/=6) Then
          Go To 100
        End If
      End If

!     Read in forecast horizon
      Read (nin,*) nt

      Allocate (fht(nt))

!     Calculate the volatility forecast
      ifail = 0
      Call g13fhf(num,nt,ip,iq,theta,fht,ht,et,ifail)

!     Output the results
      Write (nout,*) '               Parameter        Standard'
      Write (nout,*) '               estimates         errors'
!     Output the coefficient alpha_0
      Write (nout,99999) 'Alpha', 0, theta(1), se(1)
      l = 2
!     Output the coefficients alpha_i and psi_i
      If (iq>0) Then
        Write (nout,99999)('Alpha',i-1,theta(i),se(i),i=l,l+iq-1)
        l = l + iq
        Write (nout,99999)('  Psi',i-l+1,theta(i),se(i),i=l,l+iq-1)
        l = l + iq
      End If
      Write (nout,*)
!     Output the coefficients beta_j
      If (ip>0) Then
        Write (nout,99999)(' Beta',i-l+1,theta(i),se(i),i=l,l+ip-1)
        l = l + ip
        Write (nout,*)
      End If
!     Output the estimated degrees of freedom, df
      If (dist=='T') Then
        Write (nout,99998) '    DF', theta(l), se(l)
        l = l + 1
        Write (nout,*)
      End If
!     Output the estimated mean term, b_0
      If (mn==1) Then
        Write (nout,99999) '    B', 0, theta(l), se(l)
        l = l + 1
      End If
!     Output the estimated linear regression coefficients, b_i
      If (nreg>0) Then
        Write (nout,99999)('    B',i-l+1,theta(i),se(i),i=l,l+nreg-1)
      End If

!     Display the volatility forecast
      Write (nout,*)
      Write (nout,99997) 'Volatility forecast = ', fht(nt)
      Write (nout,*)

100   Continue
99999 Format (1X,A,I0,1X,2F16.2)
99998 Format (1X,A,1X,2F16.2)
99997 Format (1X,A,F12.2)
    End Program g13fgfe


g13mefe.f90

    Program g13mefe
!     G13MEF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: g13mef, nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: tau
      Integer                          :: i, ierr, ifail, lrcomm, m, nb, pn
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: iema(:), rcomm(:), sinit(:), t(:)
      Integer                          :: inter(2)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: repeat
!     .. Executable Statements ..
      Write (nout,*) 'G13MEF Example Program Results'
      Write (nout,*)

!     Skip heading in data file
      Read (nin,*)

!     Read in the number of iterations required
      Read (nin,*) m

!     Read in the interpolation method to use and the decay parameter
      Read (nin,*) inter(1:2), tau

!     Read in the initial values
      Allocate (sinit(m+2))
      Read (nin,*) sinit(1:m+2)

!     Print some titles
      Write (nout,99996) 'Iterated'
      Write (nout,99997) 'Time', 'EMA'
      Write (nout,99998) repeat('-',32)

      lrcomm = 20 + m
      Allocate (rcomm(lrcomm))

!     Loop over each block of data
      pn = 0
      Do
!       Read in the number of observations in this block
        Read (nin,*,Iostat=ierr) nb
        If (ierr/=0) Then
          Exit
        End If

!       Allocate IEMA and T to the required size
        Allocate (iema(nb),t(nb))

!       Read in the data for this block
        Do i = 1, nb
          Read (nin,*) t(i), iema(i)
        End Do

!       Update the iterated EMA for this block of data
!       G13MEF overwrites the input data with the iterated EMA
        ifail = 0
        Call g13mef(nb,iema,t,tau,m,sinit,inter,pn,rcomm,lrcomm,ifail)

!       Display the results for this block of data
        Write (nout,99999)(pn-nb+i,t(i),iema(i),i=1,nb)
        Write (nout,*)

        Deallocate (t,iema)
      End Do

99999 Format (1X,I3,4X,F10.1,4X,F10.3)
99998 Format (1X,A)
99997 Format (14X,A,10X,A)
99996 Format (25X,A)
    End Program g13mefe


g13mffe.f90

    Program g13mffe
!     G13MFF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: g13mff, nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: p, tau
      Integer                          :: ftype, i, ierr, ifail, ldiema,       &
                                          lrcomm, m1, m2, miema, nb, pn,       &
                                          sdiema, sorder
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: iema(:,:), rcomm(:), sinit(:), t(:), &
                                          x(:), z(:)
      Integer                          :: inter(2)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: repeat
!     .. Executable Statements ..
      Write (nout,*) 'G13MFF Example Program Results'
      Write (nout,*)

!     Skip heading in data file
      Read (nin,*)

!     Read in the required order for the output matrix
      Read (nin,*) sorder

!     Read in the problem size
      Read (nin,*) m1, m2

!     Read in the transformation function, its parameter, the interpolation
!     method to use and the decay parameter tau
      Read (nin,*) ftype, p, inter(1:2), tau

!     Read in the initial values
      Allocate (sinit(m2+2))
      Read (nin,*) sinit(1:m2+2)

      miema = m2 - m1 + 1

!     Print some titles
      Write (nout,99997) repeat(' ',5*miema), 'Iteration'
      Write (nout,99996) 'Time', (i,i=m1,m2)
      Write (nout,99998) repeat('-',22+10*miema)

      lrcomm = m2 + 20
      Allocate (rcomm(lrcomm))

!     Loop over each block of data
      pn = 0
      Do
!       Read in the number of observations in this block
        Read (nin,*,Iostat=ierr) nb
        If (ierr/=0) Then
          Exit
        End If

!       Allocate Z and T to the required size
        Allocate (z(nb),t(nb))

!       Read in the data for this block
        If (ftype/=3) Then
          Allocate (x(0))
          Do i = 1, nb
            Read (nin,*) t(i), z(i)
          End Do
        Else
          Allocate (x(nb))
          Do i = 1, nb
            Read (nin,*) t(i), z(i), x(i)
          End Do
        End If

        If (sorder==1) Then
          ldiema = nb
          sdiema = miema
        Else
          ldiema = miema
          sdiema = nb
        End If
        Allocate (iema(ldiema,sdiema))

!       Update the iterated EMA for this block of data
        ifail = 0
        Call g13mff(sorder,nb,z,iema,ldiema,t,tau,m1,m2,sinit,inter,ftype,p,x, &
          pn,rcomm,lrcomm,ifail)

!       Display the results for this block of data
        If (sorder==1) Then
!         IEMA(NB,M2-M1+1)
          Do i = 1, nb
            Write (nout,99999) pn - nb + i, t(i), iema(i,1:miema)
          End Do
        Else
!         IEMA(NB,M2-M1+1)
          Do i = 1, nb
            Write (nout,99999) pn - nb + i, t(i), iema(1:miema,i)
          End Do
        End If
        Write (nout,*)

        Deallocate (z,t,x,iema)
      End Do

99999 Format (1X,I3,4X,F10.1,4X,20(2X,F8.3))
99998 Format (1X,A)
99997 Format (20X,A,A)
99996 Format (14X,A,10X,20(I2,8X))
    End Program g13mffe


g13mgfe.f90

    Program g13mgfe
!     G13MGF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: g13mgf, nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: p, tau
      Integer                          :: ftype, i, ierr, ifail, lrcomm,       &
                                          lsinit, m1, m2, nb, pn
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: ma(:), rcomm(:), sinit(:), t(:),     &
                                          wma(:)
      Integer                          :: inter(2)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: repeat
!     .. Executable Statements ..
      Write (nout,*) 'G13MGF Example Program Results'
      Write (nout,*)

!     Skip heading in data file
      Read (nin,*)

!     Read in the number of iterations required
      Read (nin,*) m1, m2

!     Read in the transformation function, its parameter, the interpolation
!     method to use and the decay parameter tau
      Read (nin,*) ftype, p, inter(1:2), tau

!     Read in the initial values
      If (ftype==3 .Or. ftype==5) Then
        lsinit = 2*m2 + 3
      Else
        lsinit = m2 + 2
      End If
      Allocate (sinit(lsinit))
      Read (nin,*) sinit(1:lsinit)

!     Print some titles
      Write (nout,99997) 'Time', 'MA'
      Write (nout,99998) repeat('-',32)

      lrcomm = 20 + 2*m2
      Allocate (rcomm(lrcomm))

!     Loop over each block of data
      pn = 0
      Do
!       Read in the number of observations in this block
        Read (nin,*,Iostat=ierr) nb
        If (ierr/=0) Then
          Exit
        End If

!       Allocate MA, T and WMA to the required size
        Allocate (ma(nb),t(nb),wma(nb))

!       Read in the data for this block
        Do i = 1, nb
          Read (nin,*) t(i), ma(i)
        End Do

!       Update the moving average operator for this block of data
!       G13MGF overwrites the input data
        ifail = 0
        Call g13mgf(nb,ma,t,tau,m1,m2,sinit,inter,ftype,p,pn,wma,rcomm,lrcomm, &
          ifail)

!       Display the results for this block of data
        Write (nout,99999)(pn-nb+i,t(i),ma(i),i=1,nb)
        Write (nout,*)

        Deallocate (t,ma,wma)
      End Do

99999 Format (1X,I3,4X,F10.1,4X,F10.3)
99998 Format (1X,A)
99997 Format (14X,A,10X,A)
    End Program g13mgfe


g13nafe.f90

    Program g13nafe
!     G13NAF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: g13naf, nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: beta
      Integer                          :: ctype, i, ifail, iparam, minss, n,   &
                                          ntau
!     .. Local Arrays ..
      Real (Kind=nag_wp)               :: param(1)
      Real (Kind=nag_wp), Allocatable  :: sparam(:), y(:)
      Integer, Allocatable             :: tau(:)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: repeat
!     .. Executable Statements ..
      Continue
      Write (nout,*) 'G13NAF Example Program Results'
      Write (nout,*)

!     Skip heading in data file
      Read (nin,*)

!     Read in the problem size
      Read (nin,*) n

!     Allocate memory to hold the input series
      Allocate (y(n))

!     Read in the input series
      Read (nin,*) y(1:n)

!     Read in the type of change point, penalty and minimum segment size
      Read (nin,*) ctype, iparam, beta, minss

!     Read in the distribution parameter (if required)
      If (iparam==1) Then
        Read (nin,*) param(1)
      End If

!     Allocate output arrays
      Allocate (tau(n),sparam(2*n+2))

!     Call routine to detect change points
      ifail = -1
      Call g13naf(ctype,n,y,beta,minss,iparam,param,ntau,tau,sparam,ifail)

      If (ifail==0 .Or. ifail==200 .Or. ifail==201) Then
!       Display the results
        If (ctype==5 .Or. ctype==6) Then
!         Exponential or Poisson distribution
          Write (nout,99999) ' -- Change Points --      Distribution'
          Write (nout,99999) '  Number     Position      Parameter'
          Write (nout,99999) repeat('=',38)
          Do i = 1, ntau
            Write (nout,99998) i, tau(i), sparam(i)
          End Do
        Else
!         Normal or Gamma distribution
          Write (nout,99999)                                                   &
            ' -- Change Points --         --- Distribution ---'
          Write (nout,99999) ' Number     Position              Parameters'
          Write (nout,99999) repeat('=',50)
          Do i = 1, ntau
            Write (nout,99997) i, tau(i), sparam(2*i-1), sparam(2*i)
          End Do
        End If
        If (ifail==200 .Or. ifail==201) Then
          Write (nout,99999)                                                   &
            'Some truncation occurred internally to avoid overflow'
        End If
      End If

99999 Format (1X,A)
99998 Format (1X,I4,7X,I6,4X,F12.2)
99997 Format (1X,I4,7X,I6,2(4X,F12.2))
    End Program g13nafe


g13nbfe.f90

!   G13NBF Example Program Text
!   Mark 26 Release. NAG Copyright 2016.

    Module g13nbfe_mod

!     G13NBF Example Program Module:
!            Parameters and User-defined Routines

!     .. Use Statements ..
      Use nag_library, Only: nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Accessibility Statements ..
      Private
      Public                           :: costfn, get_data
    Contains
      Subroutine costfn(ts,nr,r,c,y,iuser,ruser,info)
!       Cost function, C. This cost function is based on the likelihood of
!       the gamma distribution

!       .. Scalar Arguments ..
        Integer, Intent (Inout)        :: info
        Integer, Intent (In)           :: nr, ts
!       .. Array Arguments ..
        Real (Kind=nag_wp), Intent (Out) :: c(nr)
        Real (Kind=nag_wp), Intent (Inout) :: ruser(*), y(0:*)
        Integer, Intent (Inout)        :: iuser(*)
        Integer, Intent (In)           :: r(nr)
!       .. Local Scalars ..
        Real (Kind=nag_wp)             :: dn, shape, si
        Integer                        :: i
!       .. Intrinsic Procedures ..
        Intrinsic                      :: log, real
!       .. Executable Statements ..
        Continue

!       RUSER(1) holds the shape parameter (a) for the gamma distribution
        shape = ruser(1)

!       Test which way around TS and R are (only needs to be done once)
        If (ts<r(1)) Then
          Do i = 1, nr
            si = y(r(i)) - y(ts)
            dn = real(r(i)-ts,kind=nag_wp)
            c(i) = 2.0_nag_wp*dn*shape*(log(si)-log(dn*shape))
          End Do

        Else
          Do i = 1, nr
            si = y(ts) - y(r(i))
            dn = real(ts-r(i),kind=nag_wp)
            c(i) = 2.0_nag_wp*dn*shape*(log(si)-log(dn*shape))
          End Do
        End If

!       Set info nonzero to terminate execution for any reason
        info = 0
      End Subroutine costfn

      Subroutine get_data(nin,n,k,y,iuser,ruser)
!       Read in data that is specific to the cost function

!       .. Scalar Arguments ..
        Real (Kind=nag_wp), Intent (Out) :: k
        Integer, Intent (In)           :: n, nin
!       .. Array Arguments ..
        Real (Kind=nag_wp), Allocatable, Intent (Out) :: ruser(:), y(:)
        Integer, Allocatable, Intent (Out) :: iuser(:)
!       .. Local Scalars ..
        Real (Kind=nag_wp)             :: shape
        Integer                        :: i
!       .. Executable Statements ..
        Continue

!       Read in the series of interest
!       NB: we are starting Y allocation at 0 as we manipulate
!       the data in Y in a moment
        Allocate (y(0:n))
        Read (nin,*) y(1:n)

!       Read in the shape parameter for the Gamma distribution
        Read (nin,*) shape

!       Store the shape parameter in RUSER. IUSER is not used
        Allocate (ruser(1),iuser(0))
        ruser(1) = shape

!       The cost function is a function of the sum of Y, so for
!       efficiency we will calculate the cumulative sum
!       It should be noted that this may introduce some rounding issues
!       with very extreme data
        y(0) = 0.0_nag_wp
        Do i = 1, n
          y(i) = y(i-1) + y(i)
        End Do

!       The value of K is defined by the cost function being used
!       in this example a value of 0.0 is the required value
        k = 0.0_nag_wp

        Return
      End Subroutine get_data
    End Module g13nbfe_mod

    Program g13nbfe

!     .. Use Statements ..
      Use nag_library, Only: g13nbf, nag_wp
      Use g13nbfe_mod, Only: costfn, get_data
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: beta, k
      Integer                          :: i, ifail, minss, n, ntau
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: ruser(:), y(:)
      Integer, Allocatable             :: iuser(:), tau(:)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: repeat
!     .. Executable Statements ..
      Continue
      Write (nout,*) 'G13NBF Example Program Results'
      Write (nout,*)

!     Skip heading in data file
      Read (nin,*)

!     Read in the problem size, penalty and minimum segment size
      Read (nin,*) n, beta, minss

!     Read in the rest of the data, that (may be) dependent on the cost
!     function
      Call get_data(nin,n,k,y,iuser,ruser)

!     Allocate output arrays
      Allocate (tau(n))

!     Call routine to detect change points
      ifail = 0
      Call g13nbf(n,beta,minss,k,costfn,ntau,tau,y,iuser,ruser,ifail)

!     Display the results
      Write (nout,99999) ' -- Change Points --'
      Write (nout,99999) ' Number     Position'
      Write (nout,99999) repeat('=',21)
      Do i = 1, ntau
        Write (nout,99998) i, tau(i)
      End Do

99999 Format (1X,A)
99998 Format (1X,I4,7X,I6)
    End Program g13nbfe


g13ndfe.f90

    Program g13ndfe
!     G13NDF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: g13ndf, nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: beta
      Integer                          :: ctype, i, ifail, iparam, mdepth,     &
                                          minss, n, ntau
!     .. Local Arrays ..
      Real (Kind=nag_wp)               :: param(1)
      Real (Kind=nag_wp), Allocatable  :: sparam(:), y(:)
      Integer, Allocatable             :: tau(:)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: repeat
!     .. Executable Statements ..
      Continue
      Write (nout,*) 'G13NDF Example Program Results'
      Write (nout,*)

!     Skip heading in data file
      Read (nin,*)

!     Read in the problem size
      Read (nin,*) n

!     Allocate memory to hold the input series
      Allocate (y(n))

!     Read in the input series
      Read (nin,*) y(1:n)

!     Read in the type of change point, penalty, minimum segment size
!     and maximum depth
      Read (nin,*) ctype, iparam, beta, minss, mdepth

!     Read in the distribution parameter (if required)
      If (iparam==1) Then
        Read (nin,*) param(1)
      End If

!     Allocate output arrays
      Allocate (tau(n),sparam(2*n+2))

!     Call routine to detect change points
      ifail = -1
      Call g13ndf(ctype,n,y,beta,minss,iparam,param,mdepth,ntau,tau,sparam,    &
        ifail)

      If (ifail==0 .Or. ifail==200 .Or. ifail==201) Then
!       Display the results
        If (ctype==5 .Or. ctype==6) Then
!         Exponential or Poisson distribution
          Write (nout,99999) ' -- Change Points --      Distribution'
          Write (nout,99999) '  Number     Position      Parameter'
          Write (nout,99999) repeat('=',38)
          Do i = 1, ntau
            Write (nout,99998) i, tau(i), sparam(i)
          End Do
        Else
!         Normal or Gamma distribution
          Write (nout,99999)                                                   &
            ' -- Change Points --         --- Distribution ---'
          Write (nout,99999) ' Number     Position              Parameters'
          Write (nout,99999) repeat('=',50)
          Do i = 1, ntau
            Write (nout,99997) i, tau(i), sparam(2*i-1), sparam(2*i)
          End Do
        End If
        If (ifail==200 .Or. ifail==201) Then
          Write (nout,99999)                                                   &
            'Some truncation occurred internally to avoid overflow'
        End If
      End If

99999 Format (1X,A)
99998 Format (1X,I4,7X,I6,4X,F12.2)
99997 Format (1X,I4,7X,I6,2(4X,F12.2))
    End Program g13ndfe


g13nefe.f90

!   G13NEF Example Program Text
!   Mark 26 Release. NAG Copyright 2016.
    Module g13nefe_mod

!     G13NEF Example Program Module:
!            Parameters and User-defined Routines

!     .. Use Statements ..
      Use nag_library, Only: nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Accessibility Statements ..
      Private
      Public                           :: chgpfn, get_data
    Contains
      Subroutine chgpfn(side,u,w,minss,v,cost,y,iuser,ruser,info)
!       Routine to calculate a proposed change point and associated cost
!       The cost is based on the likelihood of the gamma distribution

!       .. Use Statements ..
        Use nag_library, Only: x07caf, x07cbf
!       .. Scalar Arguments ..
        Integer, Intent (Inout)        :: info
        Integer, Intent (In)           :: minss, side, u, w
        Integer, Intent (Out)          :: v
!       .. Array Arguments ..
        Real (Kind=nag_wp), Intent (Out) :: cost(3)
        Real (Kind=nag_wp), Intent (Inout) :: ruser(0:*), y(*)
        Integer, Intent (Inout)        :: iuser(*)
!       .. Local Scalars ..
        Real (Kind=nag_wp)             :: dn, shape, this_cost, tmp, ys
        Integer                        :: floc, i, li, lloc
!       .. Local Arrays ..
        Integer                        :: cexmode(3), texmode(3)
!       .. Intrinsic Procedures ..
        Intrinsic                      :: log
!       .. Executable Statements ..
        Continue

!       The gamma cost function used below can result in log(0) being taken
!       (if there is a segment of zeros in Y), this leads to a cost of -Inf
!       (which is correct), but we need to make sure that the compiler
!       doesn't stop at the creation of the -Inf

!       Save the current IEEE exception mode
        Call x07caf(cexmode)

!       Set the IEEE exception mode to not trap division by zero
        texmode(:) = cexmode(:)
        texmode(2) = 0
        Call x07cbf(texmode)

!       Extract shape from RUSER
        shape = ruser(0)

!       Calculate the first and last positions for potential change
!       points, conditional on the fact that each sub-segment must be
!       at least MINSS wide
        floc = u + minss - 1
        lloc = w - minss

!       In order to calculate the cost of having a change point at I, we
!       need to calculate C(Y(FLOC:I)) and C(Y(I+1:LLOC)), where C(.) is
!       the cost function (based on the gamma distribution in this example).
!       Rather than calculate these values at each call to CHGPFN we store
!       the values for later use

!       If SIDE = 1 (i.e. we are working with a left hand sub-segment),
!       we already have C(Y(FLOC:I)) for this value of FLOC, so only need
!       to calculate C(Y(I+1:LLOC)), similarly when SIDE = 2 we only need
!       to calculate C(Y(FLOC:I))
!       When SIDE = -1, we need the cost of the full segment, which we do
!       in a forwards manner (calculating C(Y(FLOC:I)) in the process), so
!       when SIDE = 0 we only need to calculate C(Y(I:1:LLOC))

!       Get the intermediate costs
        ys = 0.0_nag_wp
        dn = 0.0_nag_wp
        If (side==0 .Or. side==1) Then
!         RUSER(2*I) = C(Y(I+1:W))
          Do i = w, floc + 1, -1
            dn = dn + 1.0_nag_wp
            tmp = dn*shape
            ys = ys + y(i)
            ruser(2*i-2) = 2.0_nag_wp*tmp*(log(ys)-log(tmp))
          End Do

        Else
!         RUSER(2*I-1) = C(Y(U:I))
          If (side==-1) Then
            li = w
          Else
            li = lloc
          End If
          Do i = u, li
            dn = dn + 1.0_nag_wp
            tmp = dn*shape
            ys = ys + y(i)
            ruser(2*i-1) = 2.0_nag_wp*tmp*(log(ys)-log(tmp))
          End Do
        End If

        If (side>=0) Then
!         Need to find a potential change point
          v = 0
          cost(1) = 0.0_nag_wp

!         Loop over all possible change point locations
          Do i = floc, lloc
            this_cost = ruser(2*i-1) + ruser(2*i)

            If (this_cost<cost(1) .Or. v==0) Then
!             Update the proposed change point location
              v = i
              cost(1) = this_cost
              cost(2) = ruser(2*i-1)
              cost(3) = ruser(2*i)
            End If
          End Do
        Else
!         Need to calculate the cost for the full segment
          cost(1) = ruser(2*w-1)
!         No need to populate the rest of COST or V
        End If

!       Reset the IEEE exception mode back to what it was
        Call x07cbf(cexmode)

!       Set info nonzero to terminate execution for any reason
        info = 0
      End Subroutine chgpfn

      Subroutine get_data(nin,n,y,iuser,ruser)
!       Read in data that is specific to the cost function

!       .. Scalar Arguments ..
        Integer, Intent (In)           :: n, nin
!       .. Array Arguments ..
        Real (Kind=nag_wp), Allocatable, Intent (Out) :: ruser(:), y(:)
        Integer, Allocatable, Intent (Out) :: iuser(:)
!       .. Local Scalars ..
        Real (Kind=nag_wp)             :: shape
!       .. Executable Statements ..
        Continue

!       Read in the series of interest
        Allocate (y(1:n))
        Read (nin,*) y(1:n)

!       Read in the shape parameter for the Gamma distribution
        Read (nin,*) shape

!       We are going to use RUSER for two purposes, firstly to store the shape
!       parameter, and we also need an additional 2*N elements of workspace
!       we reference from 0 to make the coding easier later

!       IUSER is not going to be used
        Allocate (iuser(0),ruser(0:2*n))

!       Store the shape parameter in the 0th element of RUSER
        ruser(0) = shape

!       We will be populating the other elements of RUSER in the first
!       call to CHGPFN

        Return
      End Subroutine get_data
    End Module g13nefe_mod

    Program g13nefe

!     .. Use Statements ..
      Use nag_library, Only: g13nef, nag_wp
      Use g13nefe_mod, Only: chgpfn, get_data
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: beta
      Integer                          :: i, ifail, mdepth, minss, n, ntau
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: ruser(:), y(:)
      Integer, Allocatable             :: iuser(:), tau(:)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: repeat
!     .. Executable Statements ..
      Continue
      Write (nout,*) 'G13NEF Example Program Results'
      Write (nout,*)

!     Skip heading in data file
      Read (nin,*)

!     Read in the problem size, penalty, minimum segment size and
!     maximum depth
      Read (nin,*) n, beta, minss, mdepth

!     Read in the rest of the data, that (may be) dependent on the cost
!     function
      Call get_data(nin,n,y,iuser,ruser)

!     Allocate output arrays
      Allocate (tau(n))

!     Call routine to detect change points
      ifail = 0
      Call g13nef(n,beta,minss,mdepth,chgpfn,ntau,tau,y,iuser,ruser,ifail)

!     Display the results
      Write (nout,99999) ' -- Change Points --'
      Write (nout,99999) ' Number     Position'
      Write (nout,99999) repeat('=',21)
      Do i = 1, ntau
        Write (nout,99998) i, tau(i)
      End Do

99999 Format (1X,A)
99998 Format (1X,I4,7X,I6)
    End Program g13nefe


h02bbfe.f90

    Program h02bbfe

!     H02BBF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: h02bbf, nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: bigbnd, objmip, tolfes, toliv
      Integer                          :: i, ifail, intfst, itmax, j, lda,     &
                                          liwork, lrwork, m, maxdpt, maxnod,   &
                                          msglvl, n
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: a(:,:), bl(:), bu(:), cvec(:),       &
                                          rwork(:), x(:)
      Integer, Allocatable             :: intvar(:), iwork(:)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: min
!     .. Executable Statements ..
      Write (nout,*) 'H02BBF Example Program Results'
      Flush (nout)

!     Skip heading in data file
      Read (nin,*)

      Read (nin,*) n, m
      lda = m
      Allocate (a(lda,n),bl(m+n),bu(m+n),cvec(n),x(n),intvar(n))

      Read (nin,*) itmax, msglvl
      Read (nin,*) maxnod
      Read (nin,*) intfst, maxdpt
      Read (nin,*) tolfes, toliv
      Read (nin,*)(cvec(i),i=1,n)
      Read (nin,*)((a(i,j),j=1,n),i=1,m)
      Read (nin,*) bigbnd
      Read (nin,*)(bl(i),i=1,n+m)
      Read (nin,*)(bu(i),i=1,n+m)
      Read (nin,*)(intvar(i),i=1,n)
      Read (nin,*)(x(i),i=1,n)

      liwork = (25+n+m)*maxdpt + 5*n + m + 4
      lrwork = maxdpt*(n+1) + 2*min(n,m+1)**2 + 14*n + 12*m
      Allocate (iwork(liwork),rwork(lrwork))

!     Solve the IP problem

      ifail = 0
      Call h02bbf(itmax,msglvl,n,m,a,lda,bl,bu,intvar,cvec,maxnod,intfst,      &
        maxdpt,toliv,tolfes,bigbnd,x,objmip,iwork,liwork,rwork,lrwork,ifail)

    End Program h02bbfe


h02bffe.f90

    Program h02bffe

!     H02BFF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: h02bff, nag_wp, x04acf, x04baf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Real (Kind=nag_wp), Parameter    :: xbl_default = 0.0E0_nag_wp
      Real (Kind=nag_wp), Parameter    :: xbu_default = 1.0E+20_nag_wp
      Integer, Parameter               :: maxm = 50, maxn = 50, msglvl = 1,    &
                                          nindat = 7, nout = 6
      Integer, Parameter               :: maxdpt = 3*maxn/2
      Integer, Parameter               :: liwork = (25+maxn+maxm)*maxdpt + 2*  &
                                          maxm + 7*maxn + 4
      Integer, Parameter               :: lrwork = maxdpt*(maxn+1) + 2*maxn**2 &
                                          + maxm*maxn + 19*maxn + 15*maxm
      Character (*), Parameter         :: fname = 'h02bffe.opt'
      Character (3), Parameter         :: optim = 'MIN'
!     .. Local Scalars ..
      Integer                          :: ifail, infile, m, mode, n
      Character (80)                   :: rec
!     .. Local Arrays ..
      Real (Kind=nag_wp)               :: rwork(lrwork), x(maxn)
      Integer                          :: iwork(liwork)
      Character (8)                    :: crname(maxn+maxm)
!     .. Executable Statements ..
      Write (rec,99999) 'H02BFF Example Program Results'
      Call x04baf(nout,rec)

!     Open the data file for reading

      mode = 0

      ifail = 0
      Call x04acf(nindat,fname,mode,ifail)

!     Solve the problem

      infile = nindat

      ifail = 0
      Call h02bff(infile,maxn,maxm,optim,xbl_default,xbu_default,maxdpt,       &
        msglvl,n,m,x,crname,iwork,liwork,rwork,lrwork,ifail)

99999 Format (1X,A)
    End Program h02bffe


h02bufe.f90

    Program h02bufe

!     H02BUF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: e04mff, e04mhf, h02buf, h02bvf, nag_wp, x04acf,   &
                             x04baf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Real (Kind=nag_wp), Parameter    :: xbl_default = 0.0E0_nag_wp
      Real (Kind=nag_wp), Parameter    :: xbu_default = 1.0E+20_nag_wp
      Integer, Parameter               :: maxm = 50, maxn = 50, nindat = 7,    &
                                          nout = 6
      Integer, Parameter               :: lda = maxm
      Integer, Parameter               :: liwork = 2*maxn + 3
      Integer, Parameter               :: lwork = 2*(maxm+1)**2 + 7*maxn + 5*  &
                                          maxm
      Character (*), Parameter         :: fname = 'h02bufe.opt'
      Character (8), Parameter         :: kblank = '        '
      Character (3), Parameter         :: optim = 'MIN'
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: objval
      Integer                          :: ifail, infile, iter, m, mode, n
      Logical                          :: mpslst
      Character (8)                    :: nmbnd, nmobj, nmprob, nmrhs, nmrng
      Character (80)                   :: rec
!     .. Local Arrays ..
      Real (Kind=nag_wp)               :: a(maxm,maxn), ax(maxm),              &
                                          bl(maxn+maxm), bu(maxn+maxm),        &
                                          clamda(maxn+maxm), cvec(maxn),       &
                                          work(lwork), x(maxn)
      Integer                          :: intvar(maxn), istate(maxn+maxm),     &
                                          iwork(liwork)
      Character (8)                    :: crname(maxn+maxm)
!     .. Executable Statements ..
      Write (rec,99999) 'H02BUF Example Program Results'
      Call x04baf(nout,rec)

!     Open the data file for reading

      mode = 0

      ifail = 0
      Call x04acf(nindat,fname,mode,ifail)

!     Initialize parameters

      infile = nindat
      nmprob = kblank
      nmobj = kblank
      nmrhs = kblank
      nmrng = kblank
      nmbnd = kblank
      mpslst = .False.

!     Convert the MPSX data file for use by E04MFF

      ifail = 0
      Call h02buf(infile,maxn,maxm,optim,xbl_default,xbu_default,nmobj,nmrhs,  &
        nmrng,nmbnd,mpslst,n,m,a,bl,bu,cvec,x,intvar,crname,nmprob,istate,     &
        ifail)

!     Solve the problem

      Call e04mhf('Print Level = 5')

      ifail = -1
      Call e04mff(n,m,a,lda,bl,bu,cvec,istate,x,iter,objval,ax,clamda,iwork,   &
        liwork,work,lwork,ifail)

      Select Case (ifail)
      Case (0,1,3)

!       Print solution (using MPSX names)

        ifail = 0
        Call h02bvf(n,m,a,lda,bl,bu,x,clamda,istate,crname,ifail)

      End Select

99999 Format (1X,A)
    End Program h02bufe


h02bzfe.f90

!   H02BZF Example Program Text
!   Mark 26 Release. NAG Copyright 2016.

    Module h02bzfe_mod

!     H02BZF Example Program Module:
!            Parameters and User-defined Routines

!     .. Use Statements ..
      Use nag_library, Only: nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Accessibility Statements ..
      Private
      Public                           :: outsol
!     .. Parameters ..
      Integer, Parameter, Public       :: nin = 5, nout = 6
    Contains
      Subroutine outsol(n,m,a,lda,bl,bu,x,istate,clamda,bigbnd,names,nout)

!       .. Use Statements ..
        Use nag_library, Only: ddot
!       .. Parameters ..
        Character (2), Parameter       :: lstate(-2:4) = (/'  ','  ','FR','LL' &
                                          ,'UL','EQ','TF'/)
!       .. Scalar Arguments ..
        Real (Kind=nag_wp), Intent (In) :: bigbnd
        Integer, Intent (In)           :: lda, m, n, nout
!       .. Array Arguments ..
        Real (Kind=nag_wp), Intent (In) :: a(lda,*), bl(n+m), bu(n+m),         &
                                          clamda(n+m), x(n)
        Integer, Intent (In)           :: istate(n+m)
        Character (8), Intent (In)     :: names(n+m)
!       .. Local Scalars ..
        Real (Kind=nag_wp)             :: b1, b2, res, res2, v, wlam
        Integer                        :: is, j, k
        Character (80)                 :: rec
!       .. Intrinsic Procedures ..
        Intrinsic                      :: abs
!       .. Executable Statements ..
        Write (nout,99999)

        Do j = 1, n + m
          b1 = bl(j)
          b2 = bu(j)
          wlam = clamda(j)
          is = istate(j)

          If (j<=n) Then

!           The variables  x.

            k = j
            v = x(j)
          Else

!           The linear constraints  A*x.

            If (j==n+1) Then
              Write (nout,99998)
            End If

            k = j - n
!           The NAG name equivalent of ddot is f06eaf
            v = ddot(n,a(k,1),lda,x,1)
          End If

!         Print a line for the j-th variable or constraint.

          res = v - b1
          res2 = b2 - v

          If (abs(res)>abs(res2)) Then
            res = res2
          End If

          Write (rec,99997) names(j), lstate(is), v, b1, b2, wlam, res

          If (b1<=-bigbnd) Then
            rec(29:42) = '    None     '
          End If

          If (b2>=bigbnd) Then
            rec(43:56) = '    None     '
          End If

          Write (nout,'(A)') rec
        End Do

        Return

99999   Format (/,/,1X,'Varbl',3X,'State',5X,'Value',5X,'Lower Bound',3X,      &
          'Upper Bound',4X,'Lagr Mult',3X,'Residual',/)
99998   Format (/,/,1X,'L Con',3X,'State',5X,'Value',5X,'Lower Bound',3X,      &
          'Upper Bound',4X,'Lagr Mult',3X,'Residual',/)
99997   Format (1X,A8,2X,A2,1X,1P,3G14.4,1P,G12.4,1P,G12.4)
      End Subroutine outsol
    End Module h02bzfe_mod
    Program h02bzfe

!     H02BZF Example Main Program

!     .. Use Statements ..
      Use nag_library, Only: h02bbf, h02bzf, nag_wp
      Use h02bzfe_mod, Only: nin, nout, outsol
!     .. Implicit None Statement ..
      Implicit None
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: bigbnd, inival, objmip, tolfes,      &
                                          toliv
      Integer                          :: i, ifail, intfst, itmax, j, lda,     &
                                          liwork, lrwork, m, maxdpt, maxnod,   &
                                          msglvl, n
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: a(:,:), bl(:), bu(:), clamda(:),     &
                                          cvec(:), rwork(:), x(:)
      Integer, Allocatable             :: intvar(:), istate(:), iwork(:)
      Character (8), Allocatable       :: names(:)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: min
!     .. Executable Statements ..
      Write (nout,*) 'H02BZF Example Program Results'

!     Skip heading in data file
      Read (nin,*)

      Read (nin,*) n, m
      lda = m
      Allocate (a(lda,n),bl(n+m),bu(n+m),clamda(n+m),cvec(n),x(n),intvar(n),   &
        istate(n+m),names(n+m))

      Read (nin,*) itmax, msglvl
      Read (nin,*) maxnod
      Read (nin,*) intfst, maxdpt
      Read (nin,*) tolfes, toliv
      Read (nin,*) cvec(1:n)
      Read (nin,*)(names(j),a(1:m,j),j=1,n)
      Read (nin,*) bigbnd
      Read (nin,*) bl(1:n)
      Read (nin,*)(names(n+i),bl(n+i),i=1,m)
      Read (nin,*) bu(1:n+m)
      Read (nin,*) intvar(1:n)
      Read (nin,*) x(1:n)

      liwork = (25+n+m)*maxdpt + 5*n + m + 4
      lrwork = maxdpt*(n+1) + 2*min(n,m+1)**2 + 14*n + 12*m
      Allocate (iwork(liwork),rwork(lrwork))

!     Solve the IP problem using H02BBF

      ifail = -1
      Call h02bbf(itmax,msglvl,n,m,a,lda,bl,bu,intvar,cvec,maxnod,intfst,      &
        maxdpt,toliv,tolfes,bigbnd,x,objmip,iwork,liwork,rwork,lrwork,ifail)

      Select Case (ifail)
      Case (0,7,9)
        Write (nout,99999) 'IP objective value = ', objmip

!       Get information about the solution

        ifail = 0
        Call h02bzf(n,m,bl,bu,clamda,istate,iwork,liwork,rwork,lrwork,ifail)

!       Print the solution

        Call outsol(n,m,a,lda,bl,bu,x,istate,clamda,bigbnd,names,nout)

!       Increase the energy requirements and solve the modified IP
!       problem using the current IP solution as the starting point

        inival = bl(n+1)
        Read (nin,*) bl(n+1)
        Write (nout,99998) 'Increase the energy requirements from', inival,    &
          'to', bl(n+1)

        ifail = -1
        Call h02bbf(itmax,msglvl,n,m,a,lda,bl,bu,intvar,cvec,maxnod,intfst,    &
          maxdpt,toliv,tolfes,bigbnd,x,objmip,iwork,liwork,rwork,lrwork,ifail)

        Select Case (ifail)
        Case (0,7,9)
          Write (nout,99999) 'IP objective value = ', objmip

!         Get information about the solution

          ifail = 0
          Call h02bzf(n,m,bl,bu,clamda,istate,iwork,liwork,rwork,lrwork,ifail)

!         Print the solution

          Call outsol(n,m,a,lda,bl,bu,x,istate,clamda,bigbnd,names,nout)

        End Select

      End Select

99999 Format (/,/,1X,A,1P,G16.4)
99998 Format (/,/,1X,A,1X,1P,G11.4,2X,A,1X,1P,G11.4)
    End Program h02bzfe


h02cbfe.f90

    Program h02cbfe

!     H02CBF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: e04nfu, h02cbf, h02cbu, h02cdf, nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: lintvr = 1, mdepth = 30, nin = 5,    &
                                          nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: obj
      Integer                          :: i, ifail, j, lda, ldh, liwrk, lwrk,  &
                                          n, nclin, strtgy
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: a(:,:), ax(:), bl(:), bu(:),         &
                                          clamda(:), cvec(:), h(:,:), wrk(:),  &
                                          xs(:)
      Integer, Allocatable             :: intvar(:), istate(:), iwrk(:)
!     .. Executable Statements ..
      Write (nout,*) 'H02CBF Example Program Results'

!     Skip heading in data file
      Read (nin,*)

      Read (nin,*) n, nclin
      lda = nclin
      ldh = n
      liwrk = 2*n + 3 + 2*mdepth

!     LWRK for default problem-type QP2

      If (nclin==0) Then
        lwrk = n**2 + 9*n + 4*mdepth
      Else
        lwrk = 2*n**2 + 9*n + 5*nclin + 4*mdepth
      End If

      Allocate (a(lda,n),ax(nclin),bl(n+nclin),bu(n+nclin),clamda(n+nclin),    &
        cvec(n),h(ldh,n),xs(n),intvar(lintvr),istate(n+nclin),iwrk(liwrk),     &
        wrk(lwrk))

      Read (nin,*)(cvec(i),i=1,n)
      Read (nin,*)((a(i,j),j=1,n),i=1,nclin)
      Read (nin,*)(bl(i),i=1,n+nclin)
      Read (nin,*)(bu(i),i=1,n+nclin)
      Read (nin,*)(xs(i),i=1,n)
      Read (nin,*)((h(i,j),j=1,n),i=1,n)

      strtgy = 2
      intvar(1) = 4

      Call h02cdf('Nolist')

      Call h02cdf('Print Level = 0')

!     Solve the problem

      ifail = 0
      Call h02cbf(n,nclin,a,lda,bl,bu,cvec,h,ldh,e04nfu,intvar,lintvr,mdepth,  &
        istate,xs,obj,ax,clamda,strtgy,iwrk,liwrk,wrk,lwrk,h02cbu,ifail)

!     Print out the best integer solution found

      Write (nout,99999) obj, (i,xs(i),i=1,n)

99999 Format (' Optimal Integer Value is = ',E20.8,/,' Components are ',       &
        7(/,' X(',I3,') = ',F15.8))
    End Program h02cbfe


h02ccfe.f90

    Program h02ccfe

!     H02CCF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: e04nfu, h02cbf, h02cbu, h02ccf, h02cdf, nag_wp,   &
                             x04abf, x04acf, x04baf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: iset = 1, lintvr = 1, mdepth = 30,   &
                                          nin = 5, ninopt = 7, nout = 6
      Character (*), Parameter         :: fname = 'h02ccfe.opt'
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: obj
      Integer                          :: i, ifail, inform, j, lda, ldh,       &
                                          liwork, lwork, mode, n, nclin,       &
                                          outchn, strtgy
      Character (80)                   :: rec
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: a(:,:), ax(:), bl(:), bu(:),         &
                                          clamda(:), cvec(:), h(:,:), work(:), &
                                          x(:)
      Integer, Allocatable             :: intvar(:), istate(:), iwork(:)
!     .. Executable Statements ..
      Write (rec,99996) 'H02CCF Example Program Results'
      Call x04baf(nout,rec)

!     Skip heading in data file
      Read (nin,*)

      Read (nin,*) n, nclin
      lda = nclin
      ldh = n

      liwork = 2*n + 3 + 2*mdepth

!     LWRK for default problem-type QP2

      If (nclin==0) Then
        lwork = n**2 + 9*n + 4*mdepth
      Else
        lwork = 2*n**2 + 9*n + 5*nclin + 4*mdepth
      End If

      Allocate (a(lda,n),ax(nclin),bl(n+nclin),bu(n+nclin),clamda(n+nclin),    &
        cvec(n),h(ldh,n),x(n+nclin),intvar(lintvr),istate(n+nclin),            &
        iwork(liwork),work(lwork))

      Read (nin,*)(cvec(i),i=1,n)
      Read (nin,*)((a(i,j),j=1,n),i=1,nclin)
      Read (nin,*)(bl(i),i=1,n+nclin)
      Read (nin,*)(bu(i),i=1,n+nclin)
      Read (nin,*)(x(i),i=1,n)
      Read (nin,*)((h(i,j),j=1,n),i=1,n)

!     Set four options using H02CDF

      Call h02cdf(' Print Level = 1 ')

      Call h02cdf(' Check Frequency = 10 ')

      Call h02cdf(' Crash Tolerance = 0.05 ')

      Call h02cdf(' Infinite Bound Size = 1.0D+25 ')

!     Set the unit number for advisory messages to OUTCHN

      outchn = nout

      Call x04abf(iset,outchn)

!     Open the options file for reading

      mode = 0

      ifail = 0
      Call x04acf(ninopt,fname,mode,ifail)

!     Read the options file for the remaining options

      Call h02ccf(ninopt,inform)

      If (inform/=0) Then
        Write (rec,99997) 'H02CCF terminated with INFORM = ', inform
        Call x04baf(nout,rec)
        Go To 100
      End If

      strtgy = 2
      intvar(1) = 4

      Call h02cdf('Nolist')

      Call h02cdf('Print Level = 0')

!     Solve the problem

      ifail = 0
      Call h02cbf(n,nclin,a,lda,bl,bu,cvec,h,ldh,e04nfu,intvar,lintvr,mdepth,  &
        istate,x,obj,ax,clamda,strtgy,iwork,liwork,work,lwork,h02cbu,ifail)

!     Print out the best integer solution found

      Write (rec,'()')
      Call x04baf(nout,rec)
      Write (rec,'()')
      Call x04baf(nout,rec)
      Write (rec,99999) obj
      Call x04baf(nout,rec)
      Call x04baf(nout,' Components are ')

      Do i = 1, n
        Write (rec,99998) i, x(i)
        Call x04baf(nout,rec)
      End Do

100   Continue

99999 Format (1X,'Optimal Integer Value is = ',E20.8)
99998 Format (1X,'X(',I3,') = ',F15.8)
99997 Format (A,I5)
99996 Format (1X,A)
    End Program h02ccfe


h02cefe.f90

!   H02CEF Example Program Text
!   Mark 26 Release. NAG Copyright 2016.

    Module h02cefe_mod

!     H02CEF Example Program Module:
!            Parameters and User-defined Routines

!     .. Use Statements ..
      Use nag_library, Only: nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Accessibility Statements ..
      Private
      Public                           :: monit, qphx
!     .. Parameters ..
      Real (Kind=nag_wp), Parameter    :: cutoff = -1847510.0_nag_wp
      Integer, Parameter, Public       :: lintvr = 10, mdepth = 2000, nin = 5, &
                                          nout = 6
    Contains
      Subroutine qphx(nstate,ncolh,x,hx)

!       Routine to compute H*x. (In this version of QPHX, the Hessian
!       matrix H is not referenced explicitly.)

!       .. Scalar Arguments ..
        Integer, Intent (In)           :: ncolh, nstate
!       .. Array Arguments ..
        Real (Kind=nag_wp), Intent (Out) :: hx(ncolh)
        Real (Kind=nag_wp), Intent (In) :: x(ncolh)
!       .. Executable Statements ..
        If (nstate==1) Then
!         This is the first call.
!         Take any special action here if desired.
          Continue
        Else If (nstate>=2) Then
!         This is the last call.
          Continue
        End If
        hx(1:ncolh) = 2._nag_wp*x(1:ncolh)
        hx(3) = hx(3) + 2._nag_wp*x(4)
        hx(4) = hx(4) + 2._nag_wp*x(3)
        hx(6) = hx(6) + 2._nag_wp*x(7)
        hx(7) = hx(7) + 2._nag_wp*x(6)
        Return
      End Subroutine qphx
      Subroutine monit(intfnd,nodes,depth,obj,x,bstval,bstsol,bl,bu,n,halt,    &
        count)

!       .. Scalar Arguments ..
        Real (Kind=nag_wp), Intent (Inout) :: bstval
        Real (Kind=nag_wp), Intent (In) :: obj
        Integer, Intent (Inout)        :: count
        Integer, Intent (In)           :: depth, intfnd, n, nodes
        Logical, Intent (Inout)        :: halt
!       .. Array Arguments ..
        Real (Kind=nag_wp), Intent (In) :: bl(n), bstsol(n), bu(n), x(n)
!       .. Executable Statements ..
        If (intfnd==0) Then
          bstval = cutoff
        Else If (intfnd>count) Then
          Write (nout,*) 'New integer solution found'
          Write (nout,99999) '  Nodes solved so far: ', nodes
          Write (nout,99999) '  Reached depth: ', depth
          Write (nout,99998) '  Solution value at current node: ', obj
          Write (nout,*) '  Solution vector at current node:'
          Write (nout,99997) x(1:n)
          Write (nout,99998) '  Current best function value: ', bstval
          Write (nout,*) '  Current best solution:'
          Write (nout,99997) bstsol(1:n)
          Write (nout,*) '  Current lower bounds:'
          Write (nout,99997) bl(1:n)
          Write (nout,*) '  Current upper bounds:'
          Write (nout,99997) bu(1:n)
        End If
        count = intfnd
!       Set halt .True. to terminate execution for any reason.
        halt = .False.
        Return
99999   Format (1X,A,I20)
99998   Format (1X,A,E13.5)
99997   Format (1X,2X,E13.5)
      End Subroutine monit
    End Module h02cefe_mod
    Program h02cefe

!     H02CEF Example Main Program

!     .. Use Statements ..
      Use nag_library, Only: h02cef, h02cgf, nag_wp
      Use h02cefe_mod, Only: lintvr, mdepth, monit, nin, nout, qphx
!     .. Implicit None Statement ..
      Implicit None
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: obj
      Integer                          :: i, icol, ifail, iobj, jcol, leniz,   &
                                          lenz, m, miniz, minz, n, ncolh,      &
                                          nname, nnz, ns, strtgy
      Character (1)                    :: start
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: a(:), bl(:), bu(:), clamda(:),       &
                                          xs(:), z(:)
      Integer, Allocatable             :: ha(:), intvar(:), istate(:), iz(:),  &
                                          ka(:)
      Character (8), Allocatable       :: crname(:)
      Character (8)                    :: names(5)
!     .. Executable Statements ..
      Write (nout,*) 'H02CEF Example Program Results'

!     Skip heading in data file.
      Read (nin,*)

      Read (nin,*) n, m
      Read (nin,*) nnz, iobj, ncolh, start, nname
      Allocate (a(nnz),bl(n+m),bu(n+m),clamda(n+m),xs(n+m),ha(nnz),            &
        intvar(lintvr),istate(n+m),ka(n+1),crname(nname))

      Read (nin,*) names(1:5)
      Read (nin,*) crname(1:nname)

!     Read the matrix A from data file. Set up KA.

      jcol = 1
      ka(jcol) = 1

      Do i = 1, nnz

!       Element ( HA( I ), ICOL ) is stored in A( I ).

        Read (nin,*) a(i), ha(i), icol

        If (icol==jcol+1) Then

!         Index in A of the start of the ICOL-th column equals I.

          ka(icol) = i
          jcol = icol
        Else If (icol>jcol+1) Then

!         Index in A of the start of the ICOL-th column equals I,
!         but columns JCOL+1,JCOL+2,...,ICOL-1 are empty. Set the
!         corresponding elements of KA to I.

          ka((jcol+1):(icol-1)) = i
          ka(icol) = i
          jcol = icol
        End If

      End Do

      ka(n+1) = nnz + 1

      Read (nin,*) bl(1:n+m)
      Read (nin,*) bu(1:n+m)
      Read (nin,*) istate(1:n)
      Read (nin,*) xs(1:n)

      strtgy = 3
      intvar(1:7) = (/2,3,4,5,6,7,-1/)

      Call h02cgf('NoList')

      Call h02cgf('Print Level = 0')

!     Solve the QP problem.
!     First call is a workspace query

      leniz = 1
      lenz = 1
      Allocate (iz(leniz),z(lenz))

      ifail = 1
      Call h02cef(n,m,nnz,iobj,ncolh,qphx,a,ha,ka,bl,bu,start,names,nname,     &
        crname,ns,xs,intvar,lintvr,mdepth,istate,miniz,minz,obj,clamda,strtgy, &
        iz,leniz,z,lenz,monit,ifail)

      If (ifail/=14) Then
        Write (nout,99998) ifail
      Else
        Deallocate (iz,z)

        leniz = miniz
        lenz = minz
        Allocate (iz(leniz),z(lenz))

        ifail = 0
        Call h02cef(n,m,nnz,iobj,ncolh,qphx,a,ha,ka,bl,bu,start,names,nname,   &
          crname,ns,xs,intvar,lintvr,mdepth,istate,miniz,minz,obj,clamda,      &
          strtgy,iz,leniz,z,lenz,monit,ifail)

!       Print out the best integer solution found

        Write (nout,99999) obj, (i,xs(i),i=1,n)
      End If

99999 Format (' Optimal Integer Value is = ',E20.8,/,' Components are ',/,     &
        (' X(',I3,') = ',F10.2))
99998 Format (1X,'** Workspace query in H02CEF exited with IFAIL = ',I0)
    End Program h02cefe


h02cffe.f90

!   H02CFF Example Program Text
!   Mark 26 Release. NAG Copyright 2016.

    Module h02cffe_mod

!     H02CFF Example Program Module:
!            Parameters and User-defined Routines

!     .. Use Statements ..
      Use nag_library, Only: nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Accessibility Statements ..
      Private
      Public                           :: monit, qphx
!     .. Parameters ..
      Real (Kind=nag_wp), Parameter    :: cutoff = -1840000.0_nag_wp
      Integer, Parameter, Public       :: iset = 1, lintvr = 10,               &
                                          mdepth = 2000, nin = 5, ninopt = 7,  &
                                          nout = 6
    Contains
      Subroutine qphx(nstate,ncolh,x,hx)

!       Routine to compute H*x. (In this version of QPHX, the Hessian
!       matrix H is not referenced explicitly.)

!       .. Scalar Arguments ..
        Integer, Intent (In)           :: ncolh, nstate
!       .. Array Arguments ..
        Real (Kind=nag_wp), Intent (Out) :: hx(ncolh)
        Real (Kind=nag_wp), Intent (In) :: x(ncolh)
!       .. Executable Statements ..
        hx(1) = 2.0_nag_wp*x(1)
        hx(2) = 2.0_nag_wp*x(2)
        hx(3) = 2.0_nag_wp*(x(3)+x(4))
        hx(4) = hx(3)
        hx(5) = 2.0_nag_wp*x(5)
        hx(6) = 2.0_nag_wp*(x(6)+x(7))
        hx(7) = hx(6)

        Return

      End Subroutine qphx
      Subroutine monit(intfnd,nodes,depth,obj,x,bstval,bstsol,bl,bu,n,halt,    &
        count)

!       .. Scalar Arguments ..
        Real (Kind=nag_wp), Intent (Inout) :: bstval
        Real (Kind=nag_wp), Intent (In) :: obj
        Integer, Intent (Inout)        :: count
        Integer, Intent (In)           :: depth, intfnd, n, nodes
        Logical, Intent (Inout)        :: halt
!       .. Array Arguments ..
        Real (Kind=nag_wp), Intent (In) :: bl(n), bstsol(n), bu(n), x(n)
!       .. Executable Statements ..
        If (intfnd==0) Then
          bstval = cutoff
        End If

        Return

      End Subroutine monit
    End Module h02cffe_mod
    Program h02cffe

!     H02CFF Example Main Program

!     .. Use Statements ..
      Use nag_library, Only: h02cef, h02cff, h02cgf, nag_wp, x04abf, x04acf,   &
                             x04baf
      Use h02cffe_mod, Only: iset, lintvr, mdepth, monit, nin, ninopt, nout,   &
                             qphx
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Character (*), Parameter         :: fname = 'h02cffe.opt'
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: obj
      Integer                          :: i, icol, ifail, inform, iobj, jcol,  &
                                          leniz, lenz, m, miniz, minz, mode,   &
                                          n, ncolh, nname, nnz, ns, outchn,    &
                                          strtgy
      Character (200)                  :: rec
      Character (1)                    :: start
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: a(:), bl(:), bu(:), clamda(:),       &
                                          xs(:), z(:)
      Integer, Allocatable             :: ha(:), intvar(:), istate(:), iz(:),  &
                                          ka(:)
      Character (8), Allocatable       :: crname(:)
      Character (8)                    :: names(5)
!     .. Executable Statements ..
      Write (rec,99996) 'H02CFF Example Program Results'
      Call x04baf(nout,rec)

!     Skip heading in data file.
      Read (nin,*)

      Read (nin,*) n, m
      Read (nin,*) nnz, iobj, ncolh, start, nname
      Allocate (a(nnz),bl(n+m),bu(n+m),clamda(n+m),xs(n+m),ha(nnz),            &
        intvar(lintvr),istate(n+m),ka(n+1),crname(nname))

      Read (nin,*) names(1:5)
      Read (nin,*) crname(1:nname)

!     Read the matrix A from data file. Set up KA.

      jcol = 1
      ka(jcol) = 1

      Do i = 1, nnz

!       Element ( HA( I ), ICOL ) is stored in A( I ).

        Read (nin,*) a(i), ha(i), icol

        If (icol==jcol+1) Then

!         Index in A of the start of the ICOL-th column equals I.

          ka(icol) = i
          jcol = icol
        Else If (icol>jcol+1) Then

!         Index in A of the start of the ICOL-th column equals I,
!         but columns JCOL+1,JCOL+2,...,ICOL-1 are empty. Set the
!         corresponding elements of KA to I.

          ka((jcol+1):(icol-1)) = i
          ka(icol) = i
          jcol = icol
        End If

      End Do

      ka(n+1) = nnz + 1

      Read (nin,*) bl(1:n+m)
      Read (nin,*) bu(1:n+m)
      Read (nin,*) istate(1:n)
      Read (nin,*) xs(1:n)

!     Set three options using H02CGF.

      Call h02cgf(' Check Frequency = 10 ')

      Call h02cgf(' Feasibility Tolerance = 0.00001 ')

      Call h02cgf(' Infinite Bound Size = 1.0D+25 ')

!     Set the unit number for advisory messages to OUTCHN.

      outchn = nout

      Call x04abf(iset,outchn)

!     Open the options file for reading

      mode = 0

      ifail = 0
      Call x04acf(ninopt,fname,mode,ifail)

!     Read the options file for the remaining options.

      Call h02cff(ninopt,inform)

      If (inform/=0) Then
        Write (rec,99997) 'H02CFF terminated with INFORM = ', inform
        Call x04baf(nout,rec)
        Go To 100
      End If

      strtgy = 3
      intvar(1:7) = (/2,3,4,5,6,7,-1/)

      Call h02cgf('NoList')

      Call h02cgf('Print Level = 0')

!     Solve the QP problem.
!     First call is a workspace query

      leniz = 1
      lenz = 1
      Allocate (iz(leniz),z(lenz))

      ifail = 1
      Call h02cef(n,m,nnz,iobj,ncolh,qphx,a,ha,ka,bl,bu,start,names,nname,     &
        crname,ns,xs,intvar,lintvr,mdepth,istate,miniz,minz,obj,clamda,strtgy, &
        iz,leniz,z,lenz,monit,ifail)

      If (ifail/=14) Then
        Write (rec,99995) ifail
        Call x04baf(nout,rec)
      Else
        Deallocate (iz,z)

        leniz = miniz
        lenz = minz
        Allocate (iz(leniz),z(lenz))

        ifail = 0
        Call h02cef(n,m,nnz,iobj,ncolh,qphx,a,ha,ka,bl,bu,start,names,nname,   &
          crname,ns,xs,intvar,lintvr,mdepth,istate,miniz,minz,obj,clamda,      &
          strtgy,iz,leniz,z,lenz,monit,ifail)

!       Print out the best integer solution found

        Write (rec,99999) obj
        Call x04baf(nout,rec)
        Call x04baf(nout,' Components are')

        Do i = 1, n
          Write (rec,99998) i, xs(i)
          Call x04baf(nout,rec)
        End Do

      End If

100   Continue

99999 Format (1X,'Optimal Integer Value is = ',E20.8)
99998 Format (1X,'X(',I3,') = ',F10.2)
99997 Format (A,I5)
99996 Format (1X,A)
99995 Format (1X,'** Workspace query in H02CEF exited with IFAIL = ',I0)
    End Program h02cffe


h02dafe.f90

!   H02DAF Example Program Text
!   Mark 26 Release. NAG Copyright 2016.

    Module h02dafe_mod

!     .. Use Statements ..
      Use nag_library, Only: nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Accessibility Statements ..
      Private
      Public                           :: confun, objfun
    Contains
      Subroutine objfun(mode,n,varcon,x,objmip,objgrd,nstate,iuser,ruser)

!       .. Scalar Arguments ..
        Real (Kind=nag_wp), Intent (Out) :: objmip
        Integer, Intent (Inout)        :: mode
        Integer, Intent (In)           :: n, nstate
!       .. Array Arguments ..
        Real (Kind=nag_wp), Intent (Inout) :: objgrd(n), ruser(*)
        Real (Kind=nag_wp), Intent (In) :: x(n)
        Integer, Intent (Inout)        :: iuser(*)
        Integer, Intent (In)           :: varcon(*)
!       .. Executable Statements ..
        Continue

        If (mode==0) Then
!         Objective value
          objmip = x(1)*(4.0_nag_wp*x(1)+3.0_nag_wp*x(2)-x(3)) +               &
            x(2)*(3.0_nag_wp*x(1)+6.0_nag_wp*x(2)+x(3)) +                      &
            x(3)*(x(2)-x(1)+10.0_nag_wp*x(3))
        Else
!         Objective gradients for continuous variables
          objgrd(1) = 8.0_nag_wp*x(1) + 6.0_nag_wp*x(2) - 2.0_nag_wp*x(3)
          objgrd(2) = 6.0_nag_wp*x(1) + 12.0_nag_wp*x(2) + 2.0_nag_wp*x(3)
          objgrd(3) = 2.0_nag_wp*(x(2)-x(1)) + 20.0_nag_wp*x(3)
          objgrd(4) = 0.0_nag_wp
        End If
        Return
      End Subroutine objfun

      Subroutine confun(mode,ncnln,n,varcon,x,c,cjac,nstate,iuser,ruser)

!       .. Parameters ..
        Real (Kind=nag_wp), Parameter  :: eight = 8.0_nag_wp
        Real (Kind=nag_wp), Parameter  :: nine = 9.0_nag_wp
        Real (Kind=nag_wp), Parameter  :: seven = 7.0_nag_wp
        Real (Kind=nag_wp), Parameter  :: twelve = 12.0_nag_wp
        Real (Kind=nag_wp), Parameter  :: zero = 0.0_nag_wp
!       .. Scalar Arguments ..
        Integer, Intent (Inout)        :: mode
        Integer, Intent (In)           :: n, ncnln, nstate
!       .. Array Arguments ..
        Real (Kind=nag_wp), Intent (Out) :: c(ncnln)
        Real (Kind=nag_wp), Intent (Inout) :: cjac(ncnln,n), ruser(*)
        Real (Kind=nag_wp), Intent (In) :: x(n)
        Integer, Intent (Inout)        :: iuser(*)
        Integer, Intent (In)           :: varcon(*)
!       .. Local Scalars ..
        Real (Kind=nag_wp)             :: rho
        Integer                        :: p
!       .. Intrinsic Procedures ..
        Intrinsic                      :: real
!       .. Executable Statements ..
        Continue

        If (mode==0) Then
!         Constraints
          p = iuser(1)
          rho = ruser(1)

!         Mean return rho:
          c(1) = eight*x(1) + nine*x(2) + twelve*x(3) + seven*x(4) - rho
!         Maximum of p assets in portfolio:
          c(2) = real(p,kind=nag_wp) - x(5) - x(6) - x(7) - x(8)
        Else
!         Jacobian
          cjac(1,1:4) = (/eight,nine,twelve,seven/)
!          c(2) does not include continuous variables which requires
!          that their derivatives are zero
          cjac(2,1:4) = zero
        End If

        Return
      End Subroutine confun
    End Module h02dafe_mod

    Program h02dafe

!     .. Use Statements ..
      Use nag_library, Only: h02daf, h02zkf, h02zlf, nag_wp, x04caf
      Use h02dafe_mod, Only: confun, objfun
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Real (Kind=nag_wp), Parameter    :: bigish = 1.0E3_nag_wp
      Real (Kind=nag_wp), Parameter    :: one = 1.0_nag_wp
      Real (Kind=nag_wp), Parameter    :: zero = 0.0_nag_wp
      Integer, Parameter               :: nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: acc, accqp, objmip
      Integer                          :: ifail, ivalue, lda, liopts, lopts,   &
                                          maxit, n, nclin, ncnln, optype
      Character (40)                   :: cvalue
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: a(:,:), ax(:), bl(:), bu(:), c(:),   &
                                          cjac(:,:), d(:), objgrd(:), x(:)
      Real (Kind=nag_wp)               :: opts(100), ruser(1)
      Integer                          :: iopts(200), iuser(1)
      Integer, Allocatable             :: varcon(:)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: size
!     .. Executable Statements ..
      Write (nout,*) 'H02DAF Example Program Results'
      Write (nout,*)

      n = 8
      nclin = 5
      ncnln = 2

      lda = nclin
      Allocate (a(lda,n),d(nclin),ax(nclin),bl(n),bu(n),varcon(n+nclin+ncnln), &
        x(n),c(ncnln),cjac(ncnln,n),objgrd(n))

!     Set variable types: continuous then binary
      varcon(1:4) = 0
      varcon(5:8) = 1

!     Set continuous variable bounds
      bl(1:4) = zero
      bu(1:4) = bigish

!     Bounds for binary variables need not be provided
      bl(5:8) = zero
      bu(5:8) = one

!     Set linear constraint, equality first
      varcon(n+1) = 3
      varcon(n+2:n+nclin) = 4

!     Set Ax=d then Ax>=d
      a(1:nclin,1:n) = zero
      a(1,1:4) = one
      a(2,(/1,5/)) = (/-one,one/)
      a(3,(/2,6/)) = (/-one,one/)
      a(4,(/3,7/)) = (/-one,one/)
      a(5,(/4,8/)) = (/-one,one/)
      d(1) = one
      d(2:5) = zero

!     Set constraints supplied by CONFUN, equality first
      varcon(n+nclin+1) = 3
      varcon(n+nclin+2) = 4

      liopts = size(iopts)
      lopts = size(opts)

!     Initialize communication arrays
      ifail = 0
      Call h02zkf('Initialize = H02DAF',iopts,liopts,opts,lopts,ifail)

!     Optimization parameters
      maxit = 500
      acc = 1.0E-6_nag_wp

!     Initial estimate (binary variables need not be given)
      x(1:4) = one
      x(5:8) = zero

!     Portfolio parameters p and rho
      iuser(1) = 3
      ruser(1) = 10.0_nag_wp

      ifail = 0
      Call h02daf(n,nclin,ncnln,a,lda,d,ax,bl,bu,varcon,x,confun,c,cjac,       &
        objfun,objgrd,maxit,acc,objmip,iopts,opts,iuser,ruser,ifail)

!     Results
      If (ifail==0) Then
        Call x04caf('G','N',n,1,x,n,'Final estimate:',ifail)

!       Query the accuracy of the mixed integer QP solver
        ifail = -1
        Call h02zlf('QP Accuracy',ivalue,accqp,cvalue,optype,iopts,opts,ifail)
        If (ifail==0) Then

          Write (nout,'(/1x,a,1x,g12.4)')                                      &
            'Requested accuracy of QP subproblems', accqp
        End If
        Write (nout,'(1x,a,1x,g12.4)') 'Optimised value:', objmip
      Else
        Write (nout,'(/1x,a,i4/)') 'h02daf returns ifail = ', ifail
      End If
    End Program h02dafe


h03abfe.f90

    Program h03abfe

!     H03ABF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: h03abf, nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: z
      Integer                          :: i, ifail, j, ldkost, m, ma, maxit,   &
                                          mb, numit
!     .. Local Arrays ..
      Integer, Allocatable             :: k11(:), k12(:), k15(:), k6(:),       &
                                          k7(:), k8(:), k9(:), kost(:,:)
!     .. Executable Statements ..
      Write (nout,*) 'H03ABF Example Program Results'

!     Skip heading in data file
      Read (nin,*)

      Read (nin,*) ma, mb
      m = ma + mb
      ldkost = ma
      Allocate (kost(ldkost,mb),k15(m),k7(m),k9(m),k6(m),k8(m),k11(m),k12(m))

      Read (nin,*)(k15(i),i=1,m)

      Do i = 1, ma
        Read (nin,*)(kost(i,j),j=1,mb)
      End Do

      maxit = 200

      ifail = 0
      Call h03abf(kost,ldkost,ma,mb,m,k15,maxit,k7,k9,numit,k6,k8,k11,k12,z,   &
        ifail)

      Write (nout,*)
      Write (nout,99999) 'Total cost = ', z
      Write (nout,*)
      Write (nout,*) 'Goods from  to'
      Write (nout,*)
      Write (nout,99998)(k11(i),k6(i),k8(i),i=1,m-1)

99999 Format (1X,A,F5.1)
99998 Format (1X,I3,I6,I5)
    End Program h03abfe


h03adfe.f90

    Program h03adfe

!     H03ADF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: f11zaf, h03adf, nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
      Character (1), Parameter         :: dup = 'F', zero = 'R'
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: splen
      Integer                          :: ifail, j, lenc, n, ne, nnz, ns
      Logical                          :: direct
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: d(:), work(:)
      Integer, Allocatable             :: icol(:), irow(:), iwork(:), path(:)
!     .. Executable Statements ..
      Write (nout,*) 'H03ADF Example Program Results'

!     Skip heading in data file
      Read (nin,*)

      Read (nin,*) n, ns, ne, nnz, direct
      Allocate (d(nnz),work(2*n),icol(nnz),irow(nnz),iwork(3*n+1),path(n))

      Read (nin,*)(d(j),irow(j),icol(j),j=1,nnz)

!     Reorder the elements of D into the form required by H03ADF.

      ifail = 0
      Call f11zaf(n,nnz,d,irow,icol,dup,zero,iwork,iwork(n+2),ifail)

!     Find the shortest path between vertices NS and NE.

      ifail = 0
      Call h03adf(n,ns,ne,direct,nnz,d,irow,icol,splen,path,iwork,work,ifail)

!     Print details of shortest path.

      lenc = n

loop: Do j = 0, n - 1

        If (path(j+1)==0) Then
          lenc = j
          Exit loop
        End If

      End Do loop

      Write (nout,99999) 'Shortest path = ', (path(j),j=1,lenc)
      Write (nout,99998) 'Length of shortest path = ', splen

99999 Format (/,1X,A,10(I2,:,'  to '))
99998 Format (/,1X,A,G16.6)
    End Program h03adfe


h03bbfe.f90

    Program h03bbfe

!     H03BBF Example Program Text
!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: g05kff, h03bbf, nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: lseed = 4, nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: bound, cost, targc
      Integer                          :: genid, i, i2, ib, ifail, j, l,       &
                                          lstate, nb, nc, subid, tmode
!     .. Local Arrays ..
      Real (Kind=nag_wp)               :: alg_stats(6)
      Real (Kind=nag_wp), Allocatable  :: dm(:,:)
      Integer, Allocatable             :: path(:), state(:)
      Integer                          :: seed(lseed)
      Character (20), Allocatable      :: cities(:)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: len_trim, max, min, repeat, trim
!     .. Executable Statements ..

      Write (nout,*) 'H03BBF Example Program Results'
      Write (nout,*)

!     Skip heading in data file
      Read (nin,*)

!     Number of cities
      Read (nin,*) nc

!     Allocate distance matrix and path
      Allocate (path(nc),dm(nc,nc))
!     Read distance matrix 10 columns at a time
      nb = (nc+8)/10
      Do ib = 1, nb
        Read (nin,*)
        Read (nin,*)
        i2 = min(10*ib,nc-1)
        Do i = 1, i2
          Read (nin,*)(dm(i,j),j=max(i+1,10*ib-8),i2+1)
        End Do
      End Do

      Allocate (cities(nc))
      Do i = 1, nc
        Read (nin,*) cities(i)
      End Do

!     Calculate a lower bound internally and try to find lowest cost path.
      bound = -1.0_nag_wp
      targc = -1.0_nag_wp

!     Initialize the random number state array.
!     Use the query mechanism to find the required lstate.
      genid = 2
      subid = 53
      seed(:) = (/304950,889934,209094,23423990/)
      lstate = 0
      Allocate (state(lstate))
      ifail = 0
      Call g05kff(genid,subid,seed,lseed,state,lstate,ifail)
      Deallocate (state)
      Allocate (state(lstate))
      ifail = 0
      Call g05kff(genid,subid,seed,lseed,state,lstate,ifail)

!     Find low cost return path through all cities
      ifail = 0
      Call h03bbf(nc,dm,bound,targc,path,cost,tmode,alg_stats,state,ifail)

      Write (nout,99999) 'Initial search end cost', alg_stats(3)
      Write (nout,99999) 'Search best cost       ', alg_stats(4)
      Write (nout,99999) 'Initial temperature    ', alg_stats(5)
      Write (nout,99999) 'Lower bound            ', alg_stats(6)
      Write (nout,99998) 'Termination mode       ', tmode
      Write (nout,*)
      Write (nout,99999) 'Final cost             ', cost

      Write (nout,*)
      Write (nout,*) 'Final Path:'
      Write (nout,99997) trim(cities(path(1))), trim(cities(path(2)))
      l = len_trim(cities(path(1)))
      Write (nout,99997)(repeat(' ',l),trim(cities(path(i+1))),i=2,nc-1)
      Write (nout,99997) repeat(' ',l), trim(cities(path(1)))
99999 Format (1X,A,':',F12.2)
99998 Format (1X,A,':',I12)
99997 Format (1X,A,' --> ',A)
    End Program h03bbfe


h05aafe.f90

!   H05AAF Example Program Text

!   Mark 26 Release. NAG Copyright 2016.
    Module h05aafe_mod

!     .. Use Statements ..
      Use nag_library, Only: nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Accessibility Statements ..
      Private
      Public                           :: calc_subset_score, free_subset_score
!     .. Parameters ..
      Integer, Parameter, Public       :: nin = 5, nout = 6
!     .. Derived Type Definitions ..
      Type, Public                     :: calc_subset_data
        Integer                        :: n, ldq, ldx
        Real (Kind=nag_wp)             :: tol
        Real (Kind=nag_wp), Allocatable :: x(:,:), y(:), b(:), cov(:), h(:),   &
                                          p(:), q(:,:), res(:), se(:), wk(:),  &
                                          wt(:)
        Integer, Allocatable           :: isx(:)
        Character (1)                  :: mean, weight
      End Type calc_subset_data
    Contains
      Subroutine calc_subset_score(m,drop,lz,z,la,a,bscore,cs)
!       Calculate the score associated with a particular set of feature
!       subsets.

!       M,DROP,LZ,Z,LA,A and BSCORE are all as described in the documentation
!       of H05AAF.

!       CS - Variable of type CALC_SUBSET_DATA that holds any additional data
!            required by this routine

!       This particular example finds the set, of a given size, of explanatory
!       variables that best fit a response variable when a linear regression
!       model is used. Therefore the feature set is the set of all the
!       explanatory variables and the best set of features is defined as set
!       of explanatory variables that gives the smallest residual sums of
!       squares.
!       See the documentation for G02DAF for details on linear regression
!       models.

!       .. Use Statements ..
        Use nag_library, Only: g02daf
!       .. Scalar Arguments ..
        Type (calc_subset_data), Intent (Inout) :: cs
        Integer, Intent (In)           :: drop, la, lz, m
!       .. Array Arguments ..
        Real (Kind=nag_wp), Intent (Out) :: bscore(:)
        Integer, Intent (In)           :: a(:), z(:)
!       .. Local Scalars ..
        Real (Kind=nag_wp)             :: rss
        Integer                        :: i, idf, ifail, inv_drop, ip, irank
        Logical                        :: svd
        Character (200)                :: line
!       .. Intrinsic Procedures ..
        Intrinsic                      :: abs, allocated, count, max
!       .. Executable Statements ..
        Continue

!       Allocate various arrays and read in the data if this is the first time
!       this routine has been called
        If (.Not. allocated(cs%x)) Then
!         Read in the number of observations for the data used in the linear
!         regression skipping any headings or blank lines
          Do
            Read (nin,*,Iostat=ifail) line
            If (ifail/=0) Then
              Exit
            End If
            Read (line,*,Iostat=ifail) cs%n
            If (ifail==0) Then
              Exit
            End If
          End Do

!         Read in the control parameters for the linear regression
          Read (nin,*) cs%tol

!         Read in the data
          cs%ldx = cs%n
          Allocate (cs%x(cs%ldx,m),cs%y(cs%n))
          Read (nin,*)(cs%x(i,1:m),cs%y(i),i=1,cs%n)

!         No intercept term and no weights
          cs%mean = 'Z'
          cs%weight = 'U'

!         Allocate memory required by the regression routine
          cs%ldq = cs%n
          Allocate (cs%b(m),cs%cov((m*m+m)/2),cs%h(cs%n),cs%p(m*(m+            &
            2)),cs%q(cs%ldq,m+1),cs%res(cs%n),cs%se(m),cs%wk(m*m+5*(m-         &
            1)),cs%wt(1),cs%isx(m))
        End If

!       Set up the initial feature set.
!       If DROP = 0, this is the Null set (i.e. no features).
!       If DROP = 1 then this is the full set (i.e. all features)
        cs%isx(1:m) = drop

!       Add (if DROP = 0) or remove (if DROP = 1) the all the features
!       specified in Z
        inv_drop = abs(drop-1)
        Do i = 1, lz
          cs%isx(z(i)) = inv_drop
        End Do

        Do i = 1, max(la,1)
          If (la>0) Then
            If (i>1) Then
!             Reset the feature altered at the last iteration
              cs%isx(a(i-1)) = drop
            End If

!           Add or drop the I'th feature in A
            cs%isx(a(i)) = inv_drop
          End If

          ip = count(cs%isx(1:m)==1)

!         Fit the regression model
          ifail = 0
          Call g02daf(cs%mean,cs%weight,cs%n,cs%x,cs%ldx,m,cs%isx,ip,cs%y,     &
            cs%wt,rss,idf,cs%b,cs%se,cs%cov,cs%res,cs%h,cs%q,cs%ldq,svd,irank, &
            cs%p,cs%tol,cs%wk,ifail)

!         Return the score (the residual sums of squares)
          bscore(i) = rss
        End Do
      End Subroutine calc_subset_score
      Subroutine free_subset_score(cs)

!       .. Scalar Arguments ..
        Type (calc_subset_data), Intent (Inout) :: cs
!       .. Intrinsic Procedures ..
        Intrinsic                      :: allocated
!       .. Executable Statements ..
        If (allocated(cs%x)) Then
          Deallocate (cs%x)
        End If
        If (allocated(cs%y)) Then
          Deallocate (cs%y)
        End If
        If (allocated(cs%b)) Then
          Deallocate (cs%b)
        End If
        If (allocated(cs%cov)) Then
          Deallocate (cs%cov)
        End If
        If (allocated(cs%h)) Then
          Deallocate (cs%h)
        End If
        If (allocated(cs%p)) Then
          Deallocate (cs%p)
        End If
        If (allocated(cs%q)) Then
          Deallocate (cs%q)
        End If
        If (allocated(cs%res)) Then
          Deallocate (cs%res)
        End If
        If (allocated(cs%se)) Then
          Deallocate (cs%se)
        End If
        If (allocated(cs%wk)) Then
          Deallocate (cs%wk)
        End If
        If (allocated(cs%wt)) Then
          Deallocate (cs%wt)
        End If
        If (allocated(cs%isx)) Then
          Deallocate (cs%isx)
        End If
      End Subroutine free_subset_score
    End Module h05aafe_mod

    Program h05aafe

!     .. Use Statements ..
      Use nag_library, Only: h05aaf, nag_wp
      Use h05aafe_mod, Only: calc_subset_data, calc_subset_score,              &
                             free_subset_score, nin, nout
!     .. Implicit None Statement ..
      Implicit None
!     .. Local Scalars ..
      Type (calc_subset_data)          :: cs
      Real (Kind=nag_wp)               :: gamma
      Integer                          :: cnt, drop, i, ifail, ip, irevcm, j,  &
                                          la, licomm, lrcomm, lz, m, mincnt,   &
                                          mincr, mip, nbest
!     .. Local Arrays ..
      Real (Kind=nag_wp)               :: acc(2)
      Real (Kind=nag_wp), Allocatable  :: bscore(:), rcomm(:)
      Integer, Allocatable             :: a(:), bz(:,:), ibz(:), icomm(:),     &
                                          z(:)
      Logical, Allocatable             :: mask(:)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: max, pack
!     .. Executable Statements ..
      Write (nout,*) 'H05AAF Example Program Results'
      Write (nout,*)

!     Skip headings in data file
      Read (nin,*)
      Read (nin,*)

!     Read in the problem size
      Read (nin,*) m, ip, nbest

!     Read in the control parameters for the subset selection
      Read (nin,*) mincr, mincnt, gamma, acc(1:2)

!     Allocate memory required by the subset selection routine
      mip = m - ip
      Allocate (z(mip),a(max(nbest,m)),bz(mip,nbest),bscore(max(nbest,m)))

!     Allocate dummy communication arrays, as we will query the required size
      licomm = 2
      lrcomm = 0
      Allocate (icomm(licomm),rcomm(lrcomm))

!     Query the required length for the communication arrays
      irevcm = 0
      ifail = 1
      Call h05aaf(irevcm,mincr,m,ip,nbest,drop,lz,z,la,a,bscore,bz,mincnt,     &
        gamma,acc,icomm,licomm,rcomm,lrcomm,ifail)

!     Extract the required sizes from the communication array
      licomm = icomm(1)
      lrcomm = icomm(2)

!     Reallocate communication arrays to the correct size
      Deallocate (icomm,rcomm)
      Allocate (icomm(licomm),rcomm(lrcomm))

!     Initialize reverse communication control flag
      irevcm = 0

!     Call the reverse communication best subset routine in a loop.
!     The loop should terminate when IRECVM = 0 on exit
      cnt = 0
rev_lp: Do
        ifail = -1
        Call h05aaf(irevcm,mincr,m,ip,nbest,drop,lz,z,la,a,bscore,bz,mincnt,   &
          gamma,acc,icomm,licomm,rcomm,lrcomm,ifail)
        If (irevcm==0) Then
          If (ifail==0 .Or. ifail==53) Then
!           No error, or a warning was issued
            Exit rev_lp
          Else
!           An error occurred
            Go To 100
          End If
        End If

!       Calculate and return the score for the required models and keep track
!       of the number of subsets evaluated
        cnt = cnt + max(1,la)
        Call calc_subset_score(m,drop,lz,z,la,a,bscore,cs)

      End Do rev_lp

      Call free_subset_score(cs)

!     Titles
      Write (nout,99999) '    Score        Feature Subset'
      Write (nout,99999) '    -----        --------------'

!     Display the best subsets and corresponding scores. H05AAF returns a list
!     of features excluded from the best subsets, so this is inverted to give
!     the set of features included in each subset
      Allocate (ibz(m),mask(m))
      ibz(1:m) = (/(i,i=1,m)/)
      Do i = 1, la
        mask(1:m) = .True.
        Do j = 1, mip
          mask(bz(j,i)) = .False.
        End Do
        Write (nout,99998) bscore(i), pack(ibz,mask)
      End Do

      Write (nout,*)
      If (ifail==53) Then
        Write (nout,99997) nbest,                                              &
          ' subsets of the requested size do not exist, only ', la,            &
          ' are displayed.'
      End If
      Write (nout,99996) cnt, ' subsets evaluated in total'

100   Continue

99999 Format (1X,A)
99998 Format (1X,E12.5,100(1X,I5))
99997 Format (1X,I0,A,I0,A)
99996 Format (1X,I0,A)

    End Program h05aafe


h05abfe.f90

!   H05ABF Example Program Text

!   Mark 26 Release. NAG Copyright 2016.
    Module h05abfe_mod

!     .. Use Statements ..
      Use nag_library, Only: nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Accessibility Statements ..
      Private
      Public                           :: f, prepare_user_arrays
!     .. Parameters ..
      Integer, Parameter, Public       :: nin = 5, nout = 6
    Contains
      Subroutine f(m,drop,lz,z,la,a,score,iuser,ruser,info)
!       Score calculating function required by H05ABF

!       M,DROP,LZ,Z,LA,A,SCORE IUSER and RUSER are all as described in the
!       documentation of H05ABF.

!       This particular example finds the set, of a given size, of explanatory
!       variables that best fit a response variable when a linear regression
!       model is used. Therefore the feature set is the set of all the
!       explanatory variables and the best set of features is defined as set
!       of explanatory variables that gives the smallest residual sums of
!       squares.
!       See the documentation for G02DAF for details on linear regression
!       models.

!       .. Use Statements ..
        Use nag_library, Only: g02daf
!       .. Scalar Arguments ..
        Integer, Intent (In)           :: drop, la, lz, m
        Integer, Intent (Inout)        :: info
!       .. Array Arguments ..
        Real (Kind=nag_wp), Intent (Inout) :: ruser(*)
        Real (Kind=nag_wp), Intent (Out) :: score(max(la,1))
        Integer, Intent (In)           :: a(la), z(lz)
        Integer, Intent (Inout)        :: iuser(*)
!       .. Local Scalars ..
        Real (Kind=nag_wp)             :: rss, tol
        Integer                        :: ex, ey, i, idf, ifail, inv_drop, ip, &
                                          irank, ldq, ldx, n, sx, sy
        Logical                        :: svd
        Character (1)                  :: mean, weight
!       .. Local Arrays ..
        Real (Kind=nag_wp), Allocatable :: b(:), cov(:), h(:), p(:), q(:,:),   &
                                          res(:), se(:), wk(:), wt(:)
        Integer, Allocatable           :: isx(:)
!       .. Intrinsic Procedures ..
        Intrinsic                      :: abs, count, max
!       .. Executable Statements ..
        Continue
        info = 0

        n = iuser(1)
        ldq = n
        ldx = n

!       No intercept term and no weights
        mean = 'Z'
        weight = 'U'

!       Allocate various arrays required by G02DAF
        Allocate (b(m),cov((m*m+m)/2),h(n),p(m*(m+2)),q(ldq,m+1),res(n),se(m), &
          wk(m*m+5*(m-1)),wt(1),isx(m))

!       Set up the initial feature set. If DROP = 0, this is the Null set
!       (i.e. no features). If DROP = 1 then this is the full set (i.e. all
!       features)
        isx(1:m) = drop

!       Add (if DROP = 0) or remove (if DROP = 1) the all the features
!       specified in Z
        inv_drop = abs(drop-1)
        Do i = 1, lz
          isx(z(i)) = inv_drop
        End Do

!       Get the start and end of X and Y in RUSER
        sx = iuser(4)
        ex = sx + m*n - 1
        sy = iuser(3)
        ey = sy + n - 1

!       Extract some parameters from RUSER
        tol = ruser(iuser(2))

        Do i = 1, max(la,1)
          If (la>0) Then
            If (i>1) Then
!             Reset the feature altered at the last iteration
              isx(a(i-1)) = drop
            End If

!           Add or drop the I'th feature in A
            isx(a(i)) = inv_drop
          End If

          ip = count(isx(1:m)==1)

!         Fit the regression model
          ifail = 0
          Call g02daf(mean,weight,n,ruser(sx:ex),ldx,m,isx,ip,ruser(sy:ey),wt, &
            rss,idf,b,se,cov,res,h,q,ldq,svd,irank,p,tol,wk,ifail)

!         Return the score (the residual sums of squares)
          score(i) = rss
        End Do

!       Keep track of the number of subsets evaluated
        iuser(5) = iuser(5) + max(1,la)
      End Subroutine f

      Subroutine prepare_user_arrays(m,iuser,ruser)
!       Populate the user arrays

!       M is the maximum number of features (as per H05ABF)

!       In this example RUSER holds the data required for the linear
!       regression (the matrix of explanatory variables, X, the vector of
!       response values, Y, and the tolerance, TOL) and IUSER holds number
!       of observations and the location of the various elements in RUSER

!       .. Scalar Arguments ..
        Integer, Intent (In)           :: m
!       .. Array Arguments ..
        Real (Kind=nag_wp), Allocatable, Intent (Out) :: ruser(:)
        Integer, Allocatable, Intent (Out) :: iuser(:)
!       .. Local Scalars ..
        Integer                        :: i, ierr, j, liuser, lruser, n, p1,   &
                                          p2
        Character (200)                :: line
!       .. Executable Statements ..
        Continue

!       Read in the number of observations for the data used in the linear
!       regression skipping any headings or blank lines
        Do
          Read (nin,*,Iostat=ierr) line
          If (ierr/=0) Then
            Exit
          End If
          Read (line,*,Iostat=ierr) n
          If (ierr==0) Then
            Exit
          End If
        End Do

!       Allocate space for the user arrays
        liuser = 5
        lruser = n + n*m + 1
        Allocate (ruser(lruser),iuser(liuser))

!       Number of observations
        iuser(1) = n
!       Location of TOL in RUSER
        iuser(2) = 1
!       Start of Y in RUSER
        iuser(3) = 2
!       Start of X in RUSER
        iuser(4) = iuser(3) + n
!       Keep track of the number of subsets evaluated
        iuser(5) = 0

!       Read in the tolerance for the regression
        Read (nin,*) ruser(iuser(2))

!       Read in the data
        p1 = iuser(3)
        p2 = iuser(4)
        Do i = 0, n - 1
          Read (nin,*)(ruser(p2+i+j*n),j=0,m-1), ruser(p1+i)
        End Do
      End Subroutine prepare_user_arrays
    End Module h05abfe_mod

    Program h05abfe

!     .. Use Statements ..
      Use nag_library, Only: h05abf, nag_wp
      Use h05abfe_mod, Only: f, nin, nout, prepare_user_arrays
!     .. Implicit None Statement ..
      Implicit None
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: gamma
      Integer                          :: i, ifail, ip, j, la, m, mincnt,      &
                                          mincr, mip, nbest
!     .. Local Arrays ..
      Real (Kind=nag_wp)               :: acc(2)
      Real (Kind=nag_wp), Allocatable  :: bscore(:), ruser(:)
      Integer, Allocatable             :: a(:), bz(:,:), ibz(:), iuser(:),     &
                                          z(:)
      Logical, Allocatable             :: mask(:)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: max, pack
!     .. Executable Statements ..
      Write (nout,*) 'H05ABF Example Program Results'
      Write (nout,*)

!     Skip headings in data file
      Read (nin,*)
      Read (nin,*)

!     Read in the problem size
      Read (nin,*) m, ip, nbest

!     Read in the control parameters for the subset selection
      Read (nin,*) mincr, mincnt, gamma, acc(1:2)

!     Allocate memory required by the subset selection routine
      mip = m - ip
      Allocate (z(mip),a(max(nbest,m)),bz(mip,nbest),bscore(max(nbest,m)))

!     Prepare the user workspace arrays IUSER and RUSER
      Call prepare_user_arrays(m,iuser,ruser)

!     Call the forward communication best subset routine
      ifail = -1
      Call h05abf(mincr,m,ip,nbest,la,bscore,bz,f,mincnt,gamma,acc,iuser,      &
        ruser,ifail)
      If (ifail/=0 .And. ifail/=42) Then
!       An error occurred
        Go To 100
      End If

!     Titles
      Write (nout,99999) '    Score        Feature Subset'
      Write (nout,99999) '    -----        --------------'

!     Display the best subsets and corresponding scores. H05AAF returns a list
!     of features excluded from the best subsets, so this is inverted to give
!     the set of features included in each subset
      Allocate (ibz(m),mask(m))
      ibz(1:m) = (/(i,i=1,m)/)
      Do i = 1, la
        mask(1:m) = .True.
        Do j = 1, mip
          mask(bz(j,i)) = .False.
        End Do
        Write (nout,99998) bscore(i), pack(ibz,mask)
      End Do

      Write (nout,*)
      If (ifail==42) Then
        Write (nout,99997) nbest,                                              &
          ' subsets of the requested size do not exist, only ', la,            &
          ' are displayed.'
      End If
      Write (nout,99996) iuser(5), ' subsets evaluated in total'

100   Continue

99999 Format (1X,A)
99998 Format (1X,E12.5,100(1X,I5))
99997 Format (1X,I0,A,I0,A)
99996 Format (1X,I0,A)

    End Program h05abfe


m01cafe.f90

    Program m01cafe

!     M01CAF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: m01caf, nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Integer                          :: i, ifail, m1, m2
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: rv(:)
!     .. Executable Statements ..
      Write (nout,*) 'M01CAF Example Program Results'

!     Skip heading in data file
      Read (nin,*)

      Read (nin,*) m2
      Allocate (rv(m2))

      m1 = 1

      Read (nin,*)(rv(i),i=m1,m2)

      ifail = 0
      Call m01caf(rv,m1,m2,'Ascending',ifail)

      Write (nout,*)
      Write (nout,*) 'Sorted numbers'
      Write (nout,*)
      Write (nout,99999)(rv(i),i=m1,m2)

99999 Format (1X,10F7.1)
    End Program m01cafe


m01cbfe.f90

    Program m01cbfe

!     M01CBF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: m01cbf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Integer                          :: i, ifail, m1, m2
!     .. Local Arrays ..
      Integer, Allocatable             :: iv(:)
!     .. Executable Statements ..
      Write (nout,*) 'M01CBF Example Program Results'

!     Skip heading in data file
      Read (nin,*)

      Read (nin,*) m2
      Allocate (iv(m2))

      m1 = 1

      Read (nin,*)(iv(i),i=m1,m2)

      ifail = 0
      Call m01cbf(iv,m1,m2,'Descending',ifail)

      Write (nout,*)
      Write (nout,*) 'Sorted numbers'
      Write (nout,*)
      Write (nout,99999)(iv(i),i=m1,m2)

99999 Format (1X,10I7)
    End Program m01cbfe


m01ccfe.f90

    Program m01ccfe

!     M01CCF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: m01ccf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Integer                          :: i, ifail, l1, l2, m1, m2
!     .. Local Arrays ..
      Character (12), Allocatable      :: ch(:)
!     .. Executable Statements ..
      Write (nout,*) 'M01CCF Example Program Results'

!     Skip heading in data file
      Read (nin,*)

      Read (nin,*) m2
      Allocate (ch(m2))

      m1 = 1

      Do i = m1, m2
        Read (nin,'(A)') ch(i)
      End Do

      l1 = 7
      l2 = 12

      ifail = 0
      Call m01ccf(ch,m1,m2,l1,l2,'Reverse ASCII',ifail)

      Write (nout,*)
      Write (nout,99999) 'Records sorted on columns ', l1, '  to ', l2
      Write (nout,*)
      Write (nout,99998)(ch(i),i=m1,m2)

99999 Format (1X,A,I2,A,I2)
99998 Format (1X,A)
    End Program m01ccfe


m01dafe.f90

    Program m01dafe

!     M01DAF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: m01daf, nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Integer                          :: i, ifail, m1, m2
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: rv(:)
      Integer, Allocatable             :: irank(:)
!     .. Executable Statements ..
      Write (nout,*) 'M01DAF Example Program Results'

!     Skip heading in data file
      Read (nin,*)

      Read (nin,*) m2
      Allocate (rv(m2),irank(m2))

      m1 = 1

      Read (nin,*)(rv(i),i=m1,m2)

      ifail = 0
      Call m01daf(rv,m1,m2,'Ascending',irank,ifail)

      Write (nout,*)
      Write (nout,*) '   Data   Ranks'
      Write (nout,*)

      Do i = m1, m2
        Write (nout,99999) rv(i), irank(i)
      End Do

99999 Format (1X,F7.1,I7)
    End Program m01dafe


m01dbfe.f90

    Program m01dbfe

!     M01DBF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: m01dbf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Integer                          :: i, ifail, m1, m2
!     .. Local Arrays ..
      Integer, Allocatable             :: irank(:), iv(:)
!     .. Executable Statements ..
      Write (nout,*) 'M01DBF Example Program Results'

!     Skip heading in data file
      Read (nin,*)

      Read (nin,*) m2
      Allocate (irank(m2),iv(m2))

      m1 = 1

      Read (nin,*)(iv(i),i=m1,m2)

      ifail = 0
      Call m01dbf(iv,m1,m2,'Descending',irank,ifail)

      Write (nout,*)
      Write (nout,*) '   Data   Ranks'
      Write (nout,*)

      Do i = m1, m2
        Write (nout,99999) iv(i), irank(i)
      End Do

99999 Format (1X,2I7)
    End Program m01dbfe


m01dcfe.f90

    Program m01dcfe

!     M01DCF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: m01dcf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Integer                          :: i, ifail, l1, l2, m1, m2
!     .. Local Arrays ..
      Integer, Allocatable             :: irank(:)
      Character (12), Allocatable      :: ch(:)
!     .. Executable Statements ..
      Write (nout,*) 'M01DCF Example Program Results'

!     Skip heading in data file
      Read (nin,*)

      Read (nin,*) m2
      Allocate (ch(m2),irank(m2))

      m1 = 1

      Do i = m1, m2
        Read (nin,'(A)') ch(i)
      End Do

      l1 = 7
      l2 = 12

      ifail = 0
      Call m01dcf(ch,m1,m2,l1,l2,'Reverse ASCII',irank,ifail)

      Write (nout,*)
      Write (nout,99999) 'Records ranked on columns ', l1, '  to ', l2
      Write (nout,*)
      Write (nout,*) 'Data            Ranks'
      Write (nout,*)
      Write (nout,99998)(ch(i),irank(i),i=m1,m2)

99999 Format (1X,A,I2,A,I2)
99998 Format (1X,A,I7)
    End Program m01dcfe


m01defe.f90

    Program m01defe

!     M01DEF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: m01def, nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Integer                          :: i, ifail, j, ldm, m1, m2, n1, n2
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: rm(:,:)
      Integer, Allocatable             :: irank(:)
!     .. Executable Statements ..
      Write (nout,*) 'M01DEF Example Program Results'

!     Skip heading in data file
      Read (nin,*)

      Read (nin,*) m2, n2
      ldm = m2
      Allocate (rm(ldm,n2),irank(m2))

      m1 = 1
      n1 = 1

      Do i = m1, m2
        Read (nin,*)(rm(i,j),j=n1,n2)
      End Do

      ifail = 0
      Call m01def(rm,ldm,m1,m2,n1,n2,'Ascending',irank,ifail)

      Write (nout,*)
      Write (nout,*) 'Data                        Ranks'
      Write (nout,*)

      Do i = m1, m2
        Write (nout,99999)(rm(i,j),j=n1,n2), irank(i)
      End Do

99999 Format (1X,3F7.1,I11)
    End Program m01defe


m01dffe.f90

    Program m01dffe

!     M01DFF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: m01dff
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Integer                          :: i, ifail, j, ldm, m1, m2, n1, n2
!     .. Local Arrays ..
      Integer, Allocatable             :: im(:,:), irank(:)
!     .. Executable Statements ..
      Write (nout,*) 'M01DFF Example Program Results'

!     Skip heading in data file
      Read (nin,*)

      Read (nin,*) m2, n2
      ldm = m2
      Allocate (im(ldm,n2),irank(m2))

      m1 = 1
      n1 = 1

      Do i = m1, m2
        Read (nin,*)(im(i,j),j=n1,n2)
      End Do

      ifail = 0
      Call m01dff(im,ldm,m1,m2,n1,n2,'Descending',irank,ifail)

      Write (nout,*)
      Write (nout,*) 'Data                        Ranks'
      Write (nout,*)

      Do i = m1, m2
        Write (nout,99999)(im(i,j),j=n1,n2), irank(i)
      End Do

99999 Format (1X,3I7,I11)
    End Program m01dffe


m01djfe.f90

    Program m01djfe

!     M01DJF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: m01djf, nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Integer                          :: i, ifail, j, ldm, m1, m2, n1, n2
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: rm(:,:)
      Integer, Allocatable             :: irank(:)
!     .. Executable Statements ..
      Write (nout,*) 'M01DJF Example Program Results'

!     Skip heading in data file
      Read (nin,*)

      Read (nin,*) m2, n2
      ldm = m2
      Allocate (rm(ldm,n2),irank(n2))

      m1 = 1
      n1 = 1

      Do i = m1, m2
        Read (nin,*)(rm(i,j),j=n1,n2)
      End Do

      ifail = 0
      Call m01djf(rm,ldm,m1,m2,n1,n2,'Ascending',irank,ifail)

      Write (nout,*)
      Write (nout,*) 'Data'
      Write (nout,*)

      Do i = m1, m2
        Write (nout,99999)(rm(i,j),j=n1,n2)
      End Do

      Write (nout,*)
      Write (nout,*) 'Ranks'
      Write (nout,*)
      Write (nout,99998)(irank(i),i=n1,n2)

99999 Format (1X,12F6.1)
99998 Format (1X,12I6)
    End Program m01djfe


m01dkfe.f90

    Program m01dkfe

!     M01DKF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: m01dkf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Integer                          :: i, ifail, j, ldm, m1, m2, n1, n2
!     .. Local Arrays ..
      Integer, Allocatable             :: im(:,:), irank(:)
!     .. Executable Statements ..
      Write (nout,*) 'M01DKF Example Program Results'

!     Skip heading in data file
      Read (nin,*)

      Read (nin,*) m2, n2
      ldm = m2
      Allocate (im(ldm,n2),irank(n2))

      m1 = 1
      n1 = 1

      Do i = m1, m2
        Read (nin,*)(im(i,j),j=n1,n2)
      End Do

      ifail = 0
      Call m01dkf(im,ldm,m1,m2,n1,n2,'Descending',irank,ifail)

      Write (nout,*)
      Write (nout,*) 'Data'
      Write (nout,*)

      Do i = m1, m2
        Write (nout,99999)(im(i,j),j=n1,n2)
      End Do

      Write (nout,*)
      Write (nout,*) 'Ranks'
      Write (nout,*)
      Write (nout,99999)(irank(i),i=n1,n2)

99999 Format (1X,12I6)
    End Program m01dkfe


m01dzfe.f90

!   M01DZF Example Program Text
!   Mark 26 Release. NAG Copyright 2016.

    Module m01dzfe_mod

!     M01DZF Example Program Module:
!            Parameters and User-defined Routines

!     .. Use Statements ..
      Use nag_library, Only: nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Accessibility Statements ..
      Private
      Public                           :: compar
!     .. Parameters ..
      Integer, Parameter, Public       :: nin = 5, nout = 6
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable, Public, Save :: rv(:)
      Integer, Allocatable, Public, Save :: iv(:)
    Contains
      Function compar(i,j)

!       .. Function Return Value ..
        Logical                        :: compar
!       .. Scalar Arguments ..
        Integer, Intent (In)           :: i, j
!       .. Executable Statements ..
        If (iv(i)/=iv(j)) Then
          compar = iv(i) > iv(j)
        Else

          If (iv(i)<0) Then
            compar = rv(i) < rv(j)
          Else If (iv(i)>0) Then
            compar = rv(i) > rv(j)
          Else
            compar = i < j
          End If

        End If

        Return

      End Function compar
    End Module m01dzfe_mod
    Program m01dzfe

!     M01DZF Example Main Program

!     .. Use Statements ..
      Use nag_library, Only: m01dzf, m01zaf
      Use m01dzfe_mod, Only: compar, iv, nin, nout, rv
!     .. Implicit None Statement ..
      Implicit None
!     .. Local Scalars ..
      Integer                          :: i, ifail, m1, m2
!     .. Local Arrays ..
      Integer, Allocatable             :: irank(:)
!     .. Executable Statements ..
      Write (nout,*) 'M01DZF Example Program Results'

!     Skip heading in data file
      Read (nin,*)

      Read (nin,*) m2
      Allocate (iv(m2),rv(m2),irank(m2))

      m1 = 1

      Read (nin,*)(iv(i),rv(i),i=m1,m2)

      ifail = 0
      Call m01dzf(compar,m1,m2,irank,ifail)

      ifail = 0
      Call m01zaf(irank,m1,m2,ifail)

      Write (nout,*)
      Write (nout,*) '   Data in sorted order'
      Write (nout,*)

      Write (nout,99999)(iv(irank(i)),rv(irank(i)),i=m1,m2)

      Deallocate (iv,rv)

99999 Format (1X,I7,F7.1)
    End Program m01dzfe


m01eafe.f90

    Program m01eafe

!     M01EAF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: m01daf, m01eaf, nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Integer                          :: i, ifail, j, k, m1, m2, n
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: rm(:,:)
      Integer, Allocatable             :: irank(:)
!     .. Executable Statements ..
      Write (nout,*) 'M01EAF Example Program Results'

!     Skip heading in data file
      Read (nin,*)

      Read (nin,*) m2, n, k

      If (k<1 .Or. k>n) Then
        Go To 100
      End If

      Allocate (rm(m2,n),irank(m2))

      m1 = 1

      Do i = m1, m2
        Read (nin,*)(rm(i,j),j=1,n)
      End Do

      ifail = 0
      Call m01daf(rm(1,k),m1,m2,'Ascending',irank,ifail)

      Do j = 1, n

        ifail = 0
        Call m01eaf(rm(m1,j),m1,m2,irank,ifail)

      End Do

      Write (nout,*)
      Write (nout,99999) 'Matrix sorted on column', k
      Write (nout,*)

      Do i = m1, m2
        Write (nout,99998)(rm(i,j),j=1,n)
      End Do

100   Continue

99999 Format (1X,A,I3)
99998 Format (1X,3F7.1)
    End Program m01eafe


m01ebfe.f90

    Program m01ebfe

!     M01EBF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: m01dbf, m01ebf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Integer                          :: i, ifail, j, k, m1, m2, n
!     .. Local Arrays ..
      Integer, Allocatable             :: im(:,:), irank(:)
!     .. Executable Statements ..
      Write (nout,*) 'M01EBF Example Program Results'

!     Skip heading in data file
      Read (nin,*)

      Read (nin,*) m2, n, k

      If (k<1 .Or. k>n) Then
        Go To 100
      End If

      Allocate (im(m2,n),irank(m2))

      m1 = 1

      Do i = m1, m2
        Read (nin,*)(im(i,j),j=1,n)
      End Do

      ifail = 0
      Call m01dbf(im(m1,k),m1,m2,'Ascending',irank,ifail)

      Do j = 1, n

        ifail = 0
        Call m01ebf(im(m1,j),m1,m2,irank,ifail)

      End Do

      Write (nout,*)
      Write (nout,99999) 'Matrix sorted on column', k
      Write (nout,*)

      Do i = m1, m2
        Write (nout,99998)(im(i,j),j=1,n)
      End Do

100   Continue

99999 Format (1X,A,I3)
99998 Format (1X,3I7)
    End Program m01ebfe


m01ecfe.f90

    Program m01ecfe

!     M01ECF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: m01dbf, m01ecf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Integer                          :: i, ifail, m1, m2
!     .. Local Arrays ..
      Integer, Allocatable             :: ifreq(:), irank(:)
      Character (6), Allocatable       :: ch(:)
!     .. Executable Statements ..
      Write (nout,*) 'M01ECF Example Program Results'

!     Skip heading in data file
      Read (nin,*)

      Read (nin,*) m2
      Allocate (ifreq(m2),irank(m2),ch(m2))

      m1 = 1

      Do i = m1, m2
        Read (nin,99999,End=100) ch(i), ifreq(i)
      End Do

      ifail = 0
      Call m01dbf(ifreq,m1,m2,'Descending',irank,ifail)

      ifail = 0
      Call m01ecf(ch,m1,m2,irank,ifail)

      Write (nout,*)
      Write (nout,*) 'Names in order of frequency'
      Write (nout,*)
      Write (nout,99998)(ch(i),i=m1,m2)

100   Continue

99999 Format (A6,I6)
99998 Format (1X,A)
    End Program m01ecfe


m01edfe.f90

    Program m01edfe

!     M01EDF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: m01daf, m01edf, nag_wp, x04daf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Integer                          :: i, ifail, j, k, m1, m2, n
      Character (30)                   :: string
!     .. Local Arrays ..
      Complex (Kind=nag_wp), Allocatable :: cm(:,:)
      Real (Kind=nag_wp), Allocatable  :: cmod(:)
      Integer, Allocatable             :: irank(:)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: abs
!     .. Executable Statements ..
      Write (nout,*) 'M01EDF Example Program Results'
      Flush (nout)

!     Skip heading in data file
      Read (nin,*)

      Read (nin,*) m2, n, k

      If (k<1 .Or. k>n) Then
        Go To 100
      End If

      Allocate (cm(m2,n),cmod(m2),irank(m2))

      m1 = 1

      Do i = m1, m2
        Read (nin,*)(cm(i,j),j=1,n)
      End Do

!     Calculate the moduli of the elements in the K-th column.

      Do i = m1, m2
        cmod(i) = abs(cm(i,k))
      End Do

!     Rearrange the rows so that the elements in the K-th column
!     are in ascending order of modulus.

      ifail = 0
      Call m01daf(cmod,m1,m2,'Ascending',irank,ifail)

!     Rearrange each column into the order specified by IRANK.

      Do j = 1, n

        ifail = 0
        Call m01edf(cm(m1,j),m1,m2,irank,ifail)

      End Do

!     Print the results.

      Write (nout,*)
      Write (string,99999) 'Matrix sorted on column', k
      Flush (nout)

      ifail = 0
      Call x04daf('General',' ',m2-m1+1,n,cm(m1,1),m2,string,ifail)

100   Continue

99999 Format (1X,A,I3)
    End Program m01edfe


m01nafe.f90

    Program m01nafe

!     M01NAF Example Program Text
!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: m01naf, nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: item
      Integer                          :: i, ifail, index, ioerr, m1, m2
      Logical                          :: first
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: rv(:)
!     .. Executable Statements ..
      Write (nout,*) 'M01NAF Example Program Results'

!     Skip heading in data file
      Read (nin,*)

      Read (nin,*) m2
      Allocate (rv(m2))

      m1 = 1

      Read (nin,*)(rv(i),i=m1,m2)

      first = .True.

data: Do
        Read (nin,*,Iostat=ioerr) item

        If (ioerr<0) Then
          Exit data
        End If

        ifail = 0
        index = m01naf(first,rv,m1,m2,item,ifail)

        If (first) Then
          Write (nout,*)
          Write (nout,*) 'Reference Vector is:'
          Write (nout,99999)(rv(i),i=m1,m2)
          first = .False.
        End If

        Write (nout,*)
        Write (nout,99998) item, index
      End Do data

99999 Format (1X,8F7.1)
99998 Format (1X,'Search for item ',F7.1,' returned index: ',I4)
    End Program m01nafe


m01nbfe.f90

    Program m01nbfe

!     M01NBF Example Program Text
!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: m01nbf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Integer                          :: i, ifail, index, ioerr, item, m1, m2
      Logical                          :: first
!     .. Local Arrays ..
      Integer, Allocatable             :: iv(:)
!     .. Executable Statements ..
      Write (nout,*) 'M01NBF Example Program Results'

!     Skip heading in data file
      Read (nin,*)

      Read (nin,*) m2
      Allocate (iv(m2))

      m1 = 1

      Read (nin,*)(iv(i),i=m1,m2)

      first = .True.

data: Do
        Read (nin,*,Iostat=ioerr) item

        If (ioerr<0) Then
          Exit data
        End If

        ifail = 0
        index = m01nbf(first,iv,m1,m2,item,ifail)

        If (first) Then
          Write (nout,*)
          Write (nout,*) 'Reference Vector is:'
          Write (nout,99999)(iv(i),i=m1,m2)
          first = .False.
        End If

        Write (nout,*)
        Write (nout,99998) item, index
      End Do data

99999 Format (1X,8I5)
99998 Format (1X,'Search for item ',I5,' returned index: ',I4)
    End Program m01nbfe


m01ncfe.f90

    Program m01ncfe

!     M01NCF Example Program Text
!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: m01ncf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Integer                          :: i, ifail, index, ioerr, m1, m2
      Logical                          :: first
      Character (6)                    :: item
!     .. Local Arrays ..
      Character (6), Allocatable       :: ch(:)
!     .. Executable Statements ..
      Write (nout,*) 'M01NCF Example Program Results'

!     Skip heading in data file
      Read (nin,*)

      Read (nin,*) m2
      Allocate (ch(m2))

      m1 = 1

      Read (nin,*)(ch(i),i=m1,m2)

      first = .True.

data: Do
        Read (nin,'(A)',Iostat=ioerr) item

        If (ioerr<0) Then
          Exit data
        End If

        ifail = 0
        index = m01ncf(first,ch,m1,m2,item,ifail)

        If (first) Then
          Write (nout,*)
          Write (nout,*) 'Reference Vector is:'
          Write (nout,99999)(ch(i),i=m1,m2)
          first = .False.
        End If

        Write (nout,*)
        Write (nout,99998) item, index
      End Do data

99999 Format (10(1X,A))
99998 Format (1X,'Search for item ',A,' returned index: ',I4)
    End Program m01ncfe


m01zafe.f90

    Program m01zafe

!     M01ZAF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: m01def, m01zaf, nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Integer                          :: i, ifail, j, ldm, m1, m2, n1, n2
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: rm(:,:)
      Integer, Allocatable             :: iperm(:)
!     .. Executable Statements ..
      Write (nout,*) 'M01ZAF Example Program Results'

!     Skip heading in data file
      Read (nin,*)

      Read (nin,*) m2, n2
      ldm = m2
      Allocate (rm(ldm,n2),iperm(m2))

      m1 = 1
      n1 = 1

      Do i = m1, m2
        Read (nin,*)(rm(i,j),j=n1,n2)
      End Do

      ifail = 0
      Call m01def(rm,ldm,m1,m2,n1,n2,'Ascending',iperm,ifail)

      ifail = 0
      Call m01zaf(iperm,m1,m2,ifail)

      Write (nout,*)
      Write (nout,*) 'Matrix sorted by rows'
      Write (nout,*)

      Do i = m1, m2
        Write (nout,99999)(rm(iperm(i),j),j=n1,n2)
      End Do

99999 Format (1X,3F7.1)
    End Program m01zafe


m01zbfe.f90

    Program m01zbfe

!     M01ZBF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: m01eaf, m01zbf, nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Integer                          :: i, ifail, m1, m2
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: rv(:)
      Integer, Allocatable             :: iperm(:)
!     .. Executable Statements ..
      Write (nout,*) 'M01ZBF Example Program Results'

!     Skip heading in data file
      Read (nin,*)

      Read (nin,*) m2
      Allocate (rv(m2),iperm(m2))

      m1 = 1

      Read (nin,*)(rv(i),i=m1,m2)
      Read (nin,*)(iperm(i),i=m1,m2)

      ifail = 0
      Call m01zbf(iperm,m1,m2,ifail)

      ifail = 0
      Call m01eaf(rv,m1,m2,iperm,ifail)

      Write (nout,*)
      Write (nout,*) 'Numbers in rank order'
      Write (nout,*)
      Write (nout,99999)(rv(i),i=m1,m2)

99999 Format (1X,10F7.1)
    End Program m01zbfe


m01zcfe.f90

    Program m01zcfe

!     M01ZCF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: m01djf, m01zcf, nag_wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: t
      Integer                          :: i, ifail, ii, j, k, l, ldm, m1, m2,  &
                                          n1, n2
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: rm(:,:)
      Integer, Allocatable             :: icycl(:), iperm(:)
!     .. Executable Statements ..
      Write (nout,*) 'M01ZCF Example Program Results'

!     Skip heading in data file
      Read (nin,*)

      Read (nin,*) m2, n2, l

      If (l<1 .Or. l>m2) Then
        Go To 100
      End If

      ldm = m2
      Allocate (rm(ldm,n2),icycl(n2),iperm(n2))

      m1 = 1
      n1 = 1

      Do i = m1, m2
        Read (nin,*)(rm(i,j),j=n1,n2)
      End Do

      ifail = 0
      Call m01djf(rm,ldm,l,l,n1,n2,'Ascending',iperm,ifail)

      ifail = 0
      Call m01zcf(iperm,n1,n2,icycl,ifail)

      Do k = n1, n2
        i = icycl(k)

        If (i<0) Then
          j = -i
        Else

!         Swap columns I and J

          Do ii = m1, m2
            t = rm(ii,j)
            rm(ii,j) = rm(ii,i)
            rm(ii,i) = t
          End Do

        End If

      End Do

      Write (nout,*)
      Write (nout,99999) 'Matrix sorted on row', l
      Write (nout,*)

      Do i = m1, m2
        Write (nout,99998)(rm(i,j),j=n1,n2)
      End Do

100   Continue

99999 Format (1X,A,I3)
99998 Format (1X,12F6.1)
    End Program m01zcfe


s01bafe.f90

    Program s01bafe

!     S01BAF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: nag_wp, s01baf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: x, y
      Integer                          :: ifail, ioerr
!     .. Executable Statements ..
      Write (nout,*) 'S01BAF Example Program Results'

!     Skip heading in data file
      Read (nin,*)

      Write (nout,*)
      Write (nout,*) '       X           Y'

data: Do
        Read (nin,*,Iostat=ioerr) x

        If (ioerr<0) Then
          Exit data
        End If

        ifail = -1
        y = s01baf(x,ifail)

        If (ifail<0) Then
          Exit data
        End If

        Write (nout,99999) x, y
      End Do data

99999 Format (1X,1P,2E12.4)
    End Program s01bafe


s01eafe.f90

    Program s01eafe

!     S01EAF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: nag_wp, s01eaf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Complex (Kind=nag_wp)            :: w, z
      Integer                          :: ifail, ioerr
!     .. Executable Statements ..
      Write (nout,*) 'S01EAF Example Program Results'
      Write (nout,*)

!     Skip heading in data file
      Read (nin,*)

      Write (nout,*) '              Z                              exp(Z)'

data: Do

        Read (nin,*,Iostat=ioerr) z

        If (ioerr<0) Then
          Exit data
        End If

        ifail = -1
        w = s01eaf(z,ifail)

        If (ifail<0) Then
          Exit data
        End If

        Write (nout,99999) z, w
      End Do data

99999 Format (1X,'(',F12.4,',',F12.4,')      (',F12.4,',',F12.4,')')
    End Program s01eafe


s07aafe.f90

    Program s07aafe

!     S07AAF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: nag_wp, s07aaf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: x, y
      Integer                          :: ifail, ioerr
!     .. Executable Statements ..
      Write (nout,*) 'S07AAF Example Program Results'

!     Skip heading in data file
      Read (nin,*)

      Write (nout,*)
      Write (nout,*) '     X           Y'
      Write (nout,*)

data: Do
        Read (nin,*,Iostat=ioerr) x

        If (ioerr<0) Then
          Exit data
        End If

        ifail = -1
        y = s07aaf(x,ifail)

        If (ifail<0) Then
          Exit data
        End If

        Write (nout,99999) x, y
      End Do data

99999 Format (1X,1P,2E12.3)
    End Program s07aafe


s09aafe.f90

    Program s09aafe

!     S09AAF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: nag_wp, s09aaf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: x, y
      Integer                          :: ifail, ioerr
!     .. Executable Statements ..
      Write (nout,*) 'S09AAF Example Program Results'

!     Skip heading in data file
      Read (nin,*)

      Write (nout,*)
      Write (nout,*) '     X           Y'
      Write (nout,*)

data: Do
        Read (nin,*,Iostat=ioerr) x

        If (ioerr<0) Then
          Exit data
        End If

        ifail = -1
        y = s09aaf(x,ifail)

        If (ifail<0) Then
          Exit data
        End If

        Write (nout,99999) x, y
      End Do data

99999 Format (1X,1P,2E12.3)
    End Program s09aafe


s09abfe.f90

    Program s09abfe

!     S09ABF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: nag_wp, s09abf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: x, y
      Integer                          :: ifail, ioerr
!     .. Executable Statements ..
      Write (nout,*) 'S09ABF Example Program Results'

!     Skip heading in data file
      Read (nin,*)

      Write (nout,*)
      Write (nout,*) '     X           Y'
      Write (nout,*)

data: Do
        Read (nin,*,Iostat=ioerr) x

        If (ioerr<0) Then
          Exit data
        End If

        ifail = -1
        y = s09abf(x,ifail)

        If (ifail<0) Then
          Exit data
        End If

        Write (nout,99999) x, y
      End Do data

99999 Format (1X,1P,2E12.3)
    End Program s09abfe


s10aafe.f90

    Program s10aafe

!     S10AAF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: nag_wp, s10aaf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: x, y
      Integer                          :: ifail, ioerr
!     .. Executable Statements ..
      Write (nout,*) 'S10AAF Example Program Results'

!     Skip heading in data file
      Read (nin,*)

      Write (nout,*)
      Write (nout,*) '     X           Y'
      Write (nout,*)

data: Do
        Read (nin,*,Iostat=ioerr) x

        If (ioerr<0) Then
          Exit data
        End If

        ifail = 0
        y = s10aaf(x,ifail)

        Write (nout,99999) x, y
      End Do data

99999 Format (1X,1P,2E12.3)
    End Program s10aafe


s10abfe.f90

    Program s10abfe

!     S10ABF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: nag_wp, s10abf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: x, y
      Integer                          :: ifail, ioerr
!     .. Executable Statements ..
      Write (nout,*) 'S10ABF Example Program Results'

!     Skip heading in data file
      Read (nin,*)

      Write (nout,*)
      Write (nout,*) '     X           Y'
      Write (nout,*)

data: Do
        Read (nin,*,Iostat=ioerr) x

        If (ioerr<0) Then
          Exit data
        End If

        ifail = -1
        y = s10abf(x,ifail)

        If (ifail<0) Then
          Exit data
        End If

        Write (nout,99999) x, y
      End Do data

99999 Format (1X,1P,2E12.3)
    End Program s10abfe


s10acfe.f90

    Program s10acfe

!     S10ACF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: nag_wp, s10acf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: x, y
      Integer                          :: ifail, ioerr
!     .. Executable Statements ..
      Write (nout,*) 'S10ACF Example Program Results'

!     Skip heading in data file
      Read (nin,*)

      Write (nout,*)
      Write (nout,*) '     X           Y'
      Write (nout,*)

data: Do
        Read (nin,*,Iostat=ioerr) x

        If (ioerr<0) Then
          Exit data
        End If

        ifail = -1
        y = s10acf(x,ifail)

        If (ifail<0) Then
          Exit data
        End If

        Write (nout,99999) x, y
      End Do data

99999 Format (1X,1P,2E12.3)
    End Program s10acfe


s11aafe.f90

    Program s11aafe

!     S11AAF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: nag_wp, s11aaf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: x, y
      Integer                          :: ifail, ioerr
!     .. Executable Statements ..
      Write (nout,*) 'S11AAF Example Program Results'

!     Skip heading in data file
      Read (nin,*)

      Write (nout,*)
      Write (nout,*) '     X           Y'
      Write (nout,*)

data: Do
        Read (nin,*,Iostat=ioerr) x

        If (ioerr<0) Then
          Exit data
        End If

        ifail = -1
        y = s11aaf(x,ifail)

        If (ifail<0) Then
          Exit data
        End If

        Write (nout,99999) x, y
      End Do data

99999 Format (1X,1P,2E12.3)
    End Program s11aafe


s11abfe.f90

    Program s11abfe

!     S11ABF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: nag_wp, s11abf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: x, y
      Integer                          :: ifail, ioerr
!     .. Executable Statements ..
      Write (nout,*) 'S11ABF Example Program Results'

!     Skip heading in data file
      Read (nin,*)

      Write (nout,*)
      Write (nout,*) '     X           Y'
      Write (nout,*)

data: Do
        Read (nin,*,Iostat=ioerr) x

        If (ioerr<0) Then
          Exit data
        End If

        ifail = 0
        y = s11abf(x,ifail)

        Write (nout,99999) x, y
      End Do data

99999 Format (1X,1P,2E12.3)
    End Program s11abfe


s11acfe.f90

    Program s11acfe

!     S11ACF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: nag_wp, s11acf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: x, y
      Integer                          :: ifail, ioerr
!     .. Executable Statements ..
      Write (nout,*) 'S11ACF Example Program Results'

!     Skip heading in data file
      Read (nin,*)

      Write (nout,*)
      Write (nout,*) '     X            Y'
      Write (nout,*)

data: Do
        Read (nin,*,Iostat=ioerr) x

        If (ioerr<0) Then
          Exit data
        End If

        ifail = -1
        y = s11acf(x,ifail)

        If (ifail<0) Then
          Exit data
        End If

        Write (nout,99999) x, y
      End Do data

99999 Format (1X,1P,2E12.3)
    End Program s11acfe


s13aafe.f90

    Program s13aafe

!     S13AAF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: nag_wp, s13aaf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: x, y
      Integer                          :: ifail, ioerr
!     .. Executable Statements ..
      Write (nout,*) 'S13AAF Example Program Results'

!     Skip heading in data file
      Read (nin,*)

      Write (nout,*)
      Write (nout,*) '     X           Y'
      Write (nout,*)

data: Do
        Read (nin,*,Iostat=ioerr) x

        If (ioerr<0) Then
          Exit data
        End If

        ifail = -1
        y = s13aaf(x,ifail)

        If (ifail<0) Then
          Exit data
        End If

        Write (nout,99999) x, y
      End Do data

99999 Format (1X,1P,2E12.3)
    End Program s13aafe


s13acfe.f90

    Program s13acfe

!     S13ACF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: nag_wp, s13acf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: x, y
      Integer                          :: ifail, ioerr
!     .. Executable Statements ..
      Write (nout,*) 'S13ACF Example Program Results'

!     Skip heading in data file
      Read (nin,*)

      Write (nout,*)
      Write (nout,*) '     X           Y'
      Write (nout,*)

data: Do
        Read (nin,*,Iostat=ioerr) x

        If (ioerr<0) Then
          Exit data
        End If

        ifail = -1
        y = s13acf(x,ifail)

        If (ifail<0) Then
          Exit data
        End If

        Write (nout,99999) x, y
      End Do data

99999 Format (1X,1P,2E12.3)
    End Program s13acfe


s13adfe.f90

    Program s13adfe

!     S13ADF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: nag_wp, s13adf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: x, y
      Integer                          :: ifail, ioerr
!     .. Executable Statements ..
      Write (nout,*) 'S13ADF Example Program Results'

!     Skip heading in data file
      Read (nin,*)

      Write (nout,*)
      Write (nout,*) '     X           Y'
      Write (nout,*)

data: Do
        Read (nin,*,Iostat=ioerr) x

        If (ioerr<0) Then
          Exit data
        End If

        ifail = -1
        y = s13adf(x,ifail)

        If (ifail<0) Then
          Exit data
        End If

        Write (nout,99999) x, y
      End Do data

99999 Format (1X,1P,2E12.3)
    End Program s13adfe


s14aafe.f90

    Program s14aafe

!     S14AAF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: nag_wp, s14aaf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: x, y
      Integer                          :: ifail, ioerr
!     .. Executable Statements ..
      Write (nout,*) 'S14AAF Example Program Results'

!     Skip heading in data file
      Read (nin,*)

      Write (nout,*)
      Write (nout,*) '     X           Y'
      Write (nout,*)

data: Do
        Read (nin,*,Iostat=ioerr) x

        If (ioerr<0) Then
          Exit data
        End If

        ifail = -1
        y = s14aaf(x,ifail)

        If (ifail<0) Then
          Exit data
        End If

        Write (nout,99999) x, y
      End Do data

99999 Format (1X,1P,2E12.3)
    End Program s14aafe


s14abfe.f90

    Program s14abfe

!     S14ABF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: nag_wp, s14abf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: x, y
      Integer                          :: ifail, ioerr
!     .. Executable Statements ..
      Write (nout,*) 'S14ABF Example Program Results'

!     Skip heading in data file
      Read (nin,*)

      Write (nout,*)
      Write (nout,*) '     X           Y'
      Write (nout,*)

data: Do
        Read (nin,*,Iostat=ioerr) x

        If (ioerr<0) Then
          Exit data
        End If

        ifail = -1
        y = s14abf(x,ifail)

        If (ifail<0) Then
          Exit data
        End If

        Write (nout,99999) x, y
      End Do data

99999 Format (1X,1P,2E12.3)
    End Program s14abfe


s14acfe.f90

    Program s14acfe

!     S14ACF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: nag_wp, s14acf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: f, x
      Integer                          :: ifail, ioerr
!     .. Executable Statements ..
      Write (nout,*) 'S14ACF Example Program Results'

!     Skip heading in data file
      Read (nin,*)

      Write (nout,*)
      Write (nout,*) '       X        psi(X)-log(X)'
      Write (nout,*)

data: Do
        Read (nin,*,Iostat=ioerr) x

        If (ioerr<0) Then
          Exit data
        End If

        ifail = -1
        f = s14acf(x,ifail)

        If (ifail<0) Then
          Exit data
        End If

        Write (nout,99999) x, f
      End Do data

99999 Format (1X,F12.4,F15.4)
    End Program s14acfe


s14adfe.f90

    Program s14adfe

!     S14ADF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: nag_wp, s14adf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: m = 4, nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: x
      Integer                          :: i, ifail, ioerr, n
!     .. Local Arrays ..
      Real (Kind=nag_wp)               :: ans(m)
!     .. Executable Statements ..
      Write (nout,*) 'S14ADF Example Program Results'

!     Skip heading in data file
      Read (nin,*)

      Write (nout,*)
      Write (nout,*) '      X           ANS(1)        ANS(2)        ',         &
        'ANS(3)        ANS(4)'
      Write (nout,*)

      n = 0

data: Do
        Read (nin,*,Iostat=ioerr) x

        If (ioerr<0) Then
          Exit data
        End If

        ifail = 0
        Call s14adf(x,n,m,ans,ifail)

        Write (nout,99999) x, (ans(i),i=1,m)
      End Do data

99999 Format (1X,1P,5(E12.4,2X))
    End Program s14adfe


s14aefe.f90

    Program s14aefe

!     S14AEF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: nag_wp, s14aef
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: x, y
      Integer                          :: ifail, ioerr, k
!     .. Executable Statements ..
      Write (nout,*) 'S14AEF Example Program Results'

!     Skip heading in data file
      Read (nin,*)

      Write (nout,*)
      Write (nout,*) '   X     K    (d^K/dx^K)psi(X)'
      Write (nout,*)

data: Do
        Read (nin,*,Iostat=ioerr) x, k

        If (ioerr<0) Then
          Exit data
        End If

        ifail = -1
        y = s14aef(x,k,ifail)

        If (ifail<0) Then
          Exit data
        End If

        Write (nout,99999) x, k, y
      End Do data

99999 Format (1X,F5.1,I5,5X,1P,E12.4)
    End Program s14aefe


s14affe.f90

    Program s14affe

!     S14AFF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: nag_wp, s14aff
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Complex (Kind=nag_wp)            :: y, z
      Integer                          :: ifail, ioerr, k
!     .. Executable Statements ..
      Write (nout,*) 'S14AFF Example Program Results'

!     Skip heading in data file
      Read (nin,*)

      Write (nout,*)
      Write (nout,*) '       Z           K         (d^K/dz^K)psi(Z)'
      Write (nout,*)

data: Do
        Read (nin,*,Iostat=ioerr) z, k

        If (ioerr<0) Then
          Exit data
        End If

        ifail = -1
        y = s14aff(z,k,ifail)

        If (ifail<0) Then
          Exit data
        End If

        Write (nout,99999) z, k, y
      End Do data

99999 Format (1X,'(',F5.1,',',F5.1,' )',I6,'   (',1P,E12.4,',',E12.4,' )')
    End Program s14affe


s14agfe.f90

    Program s14agfe

!     S14AGF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: nag_wp, s14agf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Complex (Kind=nag_wp)            :: y, z
      Integer                          :: ifail, ioerr
!     .. Executable Statements ..
      Write (nout,*) 'S14AGF Example Program Results'

!     Skip heading in data file
      Read (nin,*)

      Write (nout,*)
      Write (nout,*) '       Z                 ln(Gamma(Z))'
      Write (nout,*)

data: Do
        Read (nin,*,Iostat=ioerr) z

        If (ioerr<0) Then
          Exit data
        End If

        ifail = -1
        y = s14agf(z,ifail)

        If (ifail<0) Then
          Exit data
        End If

        Write (nout,99999) z, y
      End Do data

99999 Format (1X,'(',F5.1,',',F5.1,' )   (',1P,E12.4,',',E12.4,' )')
    End Program s14agfe


s14ahfe.f90

    Program s14ahfe

!     S14AHF Example Program Text
!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: nag_wp, s14ahf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: x, y
      Integer                          :: ifail, ioerr
!     .. Executable Statements ..
      Write (nout,*) 'S14AHF Example Program Results'

!     Skip heading in data file
      Read (nin,*)

      Write (nout,*)
      Write (nout,*) '     X           Y'
      Write (nout,*)

data: Do
        Read (nin,*,Iostat=ioerr) x

        If (ioerr<0) Then
          Exit data
        End If

        ifail = -1
        y = s14ahf(x,ifail)

        If (ifail<0) Then
          Exit data
        End If

        Write (nout,99999) x, y
      End Do data

99999 Format (1X,1P,2E12.3)
    End Program s14ahfe


s14bafe.f90

    Program s14bafe

!     S14BAF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: nag_wp, s14baf, x02ajf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: a, p, q, tol, x
      Integer                          :: ifail, ioerr
!     .. Executable Statements ..
      Write (nout,*) 'S14BAF Example Program Results'

!     Skip heading in data file
      Read (nin,*)

      Write (nout,*)
      Write (nout,*) '         A           X           P           Q'

      tol = x02ajf()

data: Do
        Read (nin,*,Iostat=ioerr) a, x

        If (ioerr<0) Then
          Exit data
        End If

        ifail = 0
        Call s14baf(a,x,tol,p,q,ifail)

        Write (nout,99999) a, x, p, q
      End Do data

99999 Format (1X,4F12.4)
    End Program s14bafe


s14cbfe.f90

    Program s14cbfe

!     S14CBF Example Program Text
!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: nag_wp, s14cbf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: a, b, lb
      Integer                          :: i, ifail
!     .. Executable Statements ..
      Write (nout,*) 'S14CBF Example Program Results'
      Write (nout,*)
      Write (nout,*) ' A    B        ln(beta(A,B))'
      Write (nout,*)

!     Skip heading in data file
      Read (nin,*)

      Do
        Read (nin,*,Iostat=i) a, b
        If (i/=0) Then
          Exit
        End If

        ifail = -1
        lb = s14cbf(a,b,ifail)

        If (ifail==0) Then
          Write (nout,99999) a, b, lb
        End If
      End Do

99999 Format (2F5.2,1P,E17.4)
    End Program s14cbfe


s14ccfe.f90

    Program s14ccfe

!     S14CCF Example Program Text
!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: nag_wp, s14ccf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: a, b, w, w1, x
      Integer                          :: i, ifail
!     .. Executable Statements ..
      Write (nout,*) 'S14CCF Example Program Results'
      Write (nout,*)
      Write (nout,*)                                                           &
        '  A     B     X           Ix(A,B)                1-Ix(A,B)'
      Write (nout,*)

!     Skip heading in data file
      Read (nin,*)

      Do
        Read (nin,*,Iostat=i) a, b, x
        If (i/=0) Then
          Exit
        End If

        ifail = -1
        Call s14ccf(a,b,x,w,w1,ifail)

        If (ifail==0) Then
          Write (nout,99999) a, b, x, w, w1
        End If
      End Do

99999 Format (3F6.2,1P,E17.4,7X,E17.4)
    End Program s14ccfe


s15abfe.f90

    Program s15abfe

!     S15ABF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: nag_wp, s15abf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: x, y
      Integer                          :: ifail, ioerr
!     .. Executable Statements ..
      Write (nout,*) 'S15ABF Example Program Results'

!     Skip heading in data file
      Read (nin,*)

      Write (nout,*)
      Write (nout,*) '     X           Y'
      Write (nout,*)

data: Do
        Read (nin,*,Iostat=ioerr) x

        If (ioerr<0) Then
          Exit data
        End If

        ifail = 0
        y = s15abf(x,ifail)

        Write (nout,99999) x, y
      End Do data

99999 Format (1X,1P,2E12.3)
    End Program s15abfe


s15acfe.f90

    Program s15acfe

!     S15ACF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: nag_wp, s15acf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: x, y
      Integer                          :: ifail, ioerr
!     .. Executable Statements ..
      Write (nout,*) 'S15ACF Example Program Results'

!     Skip heading in data file
      Read (nin,*)

      Write (nout,*)
      Write (nout,*) '     X           Y'
      Write (nout,*)

data: Do
        Read (nin,*,Iostat=ioerr) x

        If (ioerr<0) Then
          Exit data
        End If

        ifail = 0
        y = s15acf(x,ifail)

        Write (nout,99999) x, y
      End Do data

99999 Format (1X,1P,2E12.3)
    End Program s15acfe


s15adfe.f90

    Program s15adfe

!     S15ADF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: nag_wp, s15adf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: x, y
      Integer                          :: ifail, ioerr
!     .. Executable Statements ..
      Write (nout,*) 'S15ADF Example Program Results'

!     Skip heading in data file
      Read (nin,*)

      Write (nout,*)
      Write (nout,*) '     X           Y'
      Write (nout,*)

data: Do
        Read (nin,*,Iostat=ioerr) x

        If (ioerr<0) Then
          Exit data
        End If

        ifail = 0
        y = s15adf(x,ifail)

        Write (nout,99999) x, y
      End Do data

99999 Format (1X,1P,2E12.3)
    End Program s15adfe


s15aefe.f90

    Program s15aefe

!     S15AEF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: nag_wp, s15aef
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: x, y
      Integer                          :: ifail, ioerr
!     .. Executable Statements ..
      Write (nout,*) 'S15AEF Example Program Results'

!     Skip heading in data file
      Read (nin,*)

      Write (nout,*)
      Write (nout,*) '     X           Y'
      Write (nout,*)

data: Do
        Read (nin,*,Iostat=ioerr) x

        If (ioerr<0) Then
          Exit data
        End If

        ifail = 0
        y = s15aef(x,ifail)

        Write (nout,99999) x, y
      End Do data

99999 Format (1X,1P,2E12.3)
    End Program s15aefe


s15affe.f90

    Program s15affe

!     S15AFF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: nag_wp, s15aff
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: x, y
      Integer                          :: ifail, ioerr
!     .. Executable Statements ..
      Write (nout,*) 'S15AFF Example Program Results'

!     Skip heading in data file
      Read (nin,*)

      Write (nout,*)
      Write (nout,*) '     X           Y'
      Write (nout,*)

data: Do
        Read (nin,*,Iostat=ioerr) x

        If (ioerr<0) Then
          Exit data
        End If

        ifail = 0
        y = s15aff(x,ifail)

        Write (nout,99999) x, y
      End Do data

99999 Format (1X,1P,2E12.3)
    End Program s15affe


s15agfe.f90

    Program s15agfe

!     S15AGF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: nag_wp, s15agf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: x, y
      Integer                          :: ifail, ioerr
!     .. Executable Statements ..
      Write (nout,*) 'S15AGF Example Program Results'

!     Skip heading in data file
      Read (nin,*)

      Write (nout,*)
      Write (nout,*) '       X          erfcx(X)'
      Write (nout,*)

data: Do
        Read (nin,*,Iostat=ioerr) x

        If (ioerr<0) Then
          Exit data
        End If

        ifail = -1
        y = s15agf(x,ifail)

        If (ifail<0) Then
          Exit data
        End If

        Write (nout,99999) x, y
      End Do data

99999 Format (1X,1P,2(1X,E13.5))
    End Program s15agfe


s15ddfe.f90

    Program s15ddfe

!     S15DDF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: nag_wp, s15ddf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Complex (Kind=nag_wp)            :: w, z
      Integer                          :: ifail, ioerr
!     .. Executable Statements ..
      Write (nout,*) 'S15DDF Example Program Results'

!     Skip heading in data file
      Read (nin,*)

      Write (nout,*)
      Write (nout,*) '              Z                                W'

data: Do
        Read (nin,*,Iostat=ioerr) z

        If (ioerr<0) Then
          Exit data
        End If

        ifail = -1
        w = s15ddf(z,ifail)

        If (ifail<0) Then
          Exit data
        End If

        Write (nout,99999) z, w
      End Do data

99999 Format (1X,'(',F12.4,',',F12.4,')      (',F12.4,',',F12.4,')')
    End Program s15ddfe


s17acfe.f90

    Program s17acfe

!     S17ACF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: nag_wp, s17acf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: x, y
      Integer                          :: ifail, ioerr
!     .. Executable Statements ..
      Write (nout,*) 'S17ACF Example Program Results'

!     Skip heading in data file
      Read (nin,*)

      Write (nout,*)
      Write (nout,*) '     X           Y'
      Write (nout,*)

data: Do
        Read (nin,*,Iostat=ioerr) x

        If (ioerr<0) Then
          Exit data
        End If

        ifail = -1
        y = s17acf(x,ifail)

        If (ifail<0) Then
          Exit data
        End If

        Write (nout,99999) x, y
      End Do data

99999 Format (1X,1P,2E12.3)
    End Program s17acfe


s17adfe.f90

    Program s17adfe

!     S17ADF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: nag_wp, s17adf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: x, y
      Integer                          :: ifail, ioerr
!     .. Executable Statements ..
      Write (nout,*) 'S17ADF Example Program Results'

!     Skip heading in data file
      Read (nin,*)

      Write (nout,*)
      Write (nout,*) '     X           Y'
      Write (nout,*)

data: Do
        Read (nin,*,Iostat=ioerr) x

        If (ioerr<0) Then
          Exit data
        End If

        ifail = -1
        y = s17adf(x,ifail)

        If (ifail<0) Then
          Exit data
        End If

        Write (nout,99999) x, y
      End Do data

99999 Format (1X,1P,2E12.3)
    End Program s17adfe


s17aefe.f90

    Program s17aefe

!     S17AEF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: nag_wp, s17aef
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: x, y
      Integer                          :: ifail, ioerr
!     .. Executable Statements ..
      Write (nout,*) 'S17AEF Example Program Results'

!     Skip heading in data file
      Read (nin,*)

      Write (nout,*)
      Write (nout,*) '     X           Y'
      Write (nout,*)

data: Do
        Read (nin,*,Iostat=ioerr) x

        If (ioerr<0) Then
          Exit data
        End If

        ifail = -1
        y = s17aef(x,ifail)

        If (ifail<0) Then
          Exit data
        End If

        Write (nout,99999) x, y
      End Do data

99999 Format (1X,1P,2E12.3)
    End Program s17aefe


s17affe.f90

    Program s17affe

!     S17AFF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: nag_wp, s17aff
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: x, y
      Integer                          :: ifail, ioerr
!     .. Executable Statements ..
      Write (nout,*) 'S17AFF Example Program Results'

!     Skip heading in data file
      Read (nin,*)

      Write (nout,*)
      Write (nout,*) '     X           Y'
      Write (nout,*)

data: Do
        Read (nin,*,Iostat=ioerr) x

        If (ioerr<0) Then
          Exit data
        End If

        ifail = -1
        y = s17aff(x,ifail)

        If (ifail<0) Then
          Exit data
        End If

        Write (nout,99999) x, y
      End Do data

99999 Format (1X,1P,2E12.3)
    End Program s17affe


s17agfe.f90

    Program s17agfe

!     S17AGF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: nag_wp, s17agf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: x, y
      Integer                          :: ifail, ioerr
!     .. Executable Statements ..
      Write (nout,*) 'S17AGF Example Program Results'

!     Skip heading in data file
      Read (nin,*)

      Write (nout,*)
      Write (nout,*) '     X           Y'
      Write (nout,*)

data: Do
        Read (nin,*,Iostat=ioerr) x

        If (ioerr<0) Then
          Exit data
        End If

        ifail = -1
        y = s17agf(x,ifail)

        If (ifail<0) Then
          Exit data
        End If

        Write (nout,99999) x, y
      End Do data

99999 Format (1X,1P,2E12.3)
    End Program s17agfe


s17ahfe.f90

    Program s17ahfe

!     S17AHF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: nag_wp, s17ahf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: x, y
      Integer                          :: ifail, ioerr
!     .. Executable Statements ..
      Write (nout,*) 'S17AHF Example Program Results'

!     Skip heading in data file
      Read (nin,*)

      Write (nout,*)
      Write (nout,*) '     X           Y'
      Write (nout,*)

data: Do
        Read (nin,*,Iostat=ioerr) x

        If (ioerr<0) Then
          Exit data
        End If

        ifail = -1
        y = s17ahf(x,ifail)

        If (ifail<0) Then
          Exit data
        End If

        Write (nout,99999) x, y
      End Do data

99999 Format (1X,1P,2E12.3)
    End Program s17ahfe


s17ajfe.f90

    Program s17ajfe

!     S17AJF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: nag_wp, s17ajf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: x, y
      Integer                          :: ifail, ioerr
!     .. Executable Statements ..
      Write (nout,*) 'S17AJF Example Program Results'

!     Skip heading in data file
      Read (nin,*)

      Write (nout,*)
      Write (nout,*) '     X           Y'
      Write (nout,*)

data: Do
        Read (nin,*,Iostat=ioerr) x

        If (ioerr<0) Then
          Exit data
        End If

        ifail = -1
        y = s17ajf(x,ifail)

        If (ifail<0) Then
          Exit data
        End If

        Write (nout,99999) x, y
      End Do data

99999 Format (1X,1P,2E12.3)
    End Program s17ajfe


s17akfe.f90

    Program s17akfe

!     S17AKF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: nag_wp, s17akf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: x, y
      Integer                          :: ifail, ioerr
!     .. Executable Statements ..
      Write (nout,*) 'S17AKF Example Program Results'

!     Skip heading in data file
      Read (nin,*)

      Write (nout,*)
      Write (nout,*) '     X           Y'
      Write (nout,*)

data: Do
        Read (nin,*,Iostat=ioerr) x

        If (ioerr<0) Then
          Exit data
        End If

        ifail = -1
        y = s17akf(x,ifail)

        If (ifail<0) Then
          Exit data
        End If

        Write (nout,99999) x, y
      End Do data

99999 Format (1X,1P,2E12.3)
    End Program s17akfe


s17alfe.f90

    Program s17alfe

!     S17ALF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: nag_wp, s17alf, x02ajf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: a, rel
      Integer                          :: i, ifail, mode, n
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: x(:)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: sqrt
!     .. Executable Statements ..
      Write (nout,*) 'S17ALF Example Program Results'

!     Skip heading in data file
      Read (nin,*)

      rel = sqrt(x02ajf())
      Read (nin,*) a, n, mode
      Allocate (x(n))

      ifail = 0
      Call s17alf(a,n,mode,rel,x,ifail)

      Write (nout,*)
      Write (nout,*) '   A   N   MODE        REL'
      Write (nout,*) '                 (machine-dependent)'
      Write (nout,*)
      Write (nout,99999) a, n, mode, rel
      Write (nout,*)

      Select Case (mode)
      Case (1)
        Write (nout,*) 'Leading N positive zeros of J'
      Case (2)
        Write (nout,*) 'Leading N positive zeros of Y'
      Case (3)

        If (a==0.0E0_nag_wp) Then
          Write (nout,*) 'Leading N non-negative zeros of J'''
        Else
          Write (nout,*) 'Leading N positive zeros of J'''
        End If

      Case (4)
        Write (nout,*) 'Leading N positive zeros of Y'''
      End Select

      Write (nout,*)
      Write (nout,*) 'X ='
      Write (nout,99998)(x(i),i=1,n)
      Write (nout,*)

99999 Format (1X,F4.1,I4,I7,4X,1P,E9.1)
99998 Format (1P,(E12.4))
    End Program s17alfe


s17aqfe.f90

    Program s17aqfe

!     S17AQF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: nag_wp, s17aqf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Integer                          :: i, ifail, n
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: f(:), x(:)
      Integer, Allocatable             :: ivalid(:)
!     .. Executable Statements ..
      Write (nout,*) 'S17AQF Example Program Results'

!     Skip heading in data file
      Read (nin,*)

      Write (nout,*)
      Write (nout,*) '     X           F          IVALID'
      Write (nout,*)

      Read (nin,*) n

      Allocate (x(n),f(n),ivalid(n))

      Read (nin,*) x(1:n)

      ifail = 0
      Call s17aqf(n,x,f,ivalid,ifail)

      Do i = 1, n
        Write (nout,99999) x(i), f(i), ivalid(i)
      End Do

99999 Format (1X,1P,2E12.3,I5)
    End Program s17aqfe


s17arfe.f90

    Program s17arfe

!     S17ARF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: nag_wp, s17arf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Integer                          :: i, ifail, n
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: f(:), x(:)
      Integer, Allocatable             :: ivalid(:)
!     .. Executable Statements ..
      Write (nout,*) 'S17ARF Example Program Results'

!     Skip heading in data file
      Read (nin,*)

      Write (nout,*)
      Write (nout,*) '     X           F          IVALID'
      Write (nout,*)

      Read (nin,*) n

      Allocate (x(n),f(n),ivalid(n))

      Read (nin,*) x(1:n)

      ifail = 0
      Call s17arf(n,x,f,ivalid,ifail)

      Do i = 1, n
        Write (nout,99999) x(i), f(i), ivalid(i)
      End Do

99999 Format (1X,1P,2E12.3,I5)
    End Program s17arfe


s17asfe.f90

    Program s17asfe

!     S17ASF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: nag_wp, s17asf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Integer                          :: i, ifail, n
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: f(:), x(:)
      Integer, Allocatable             :: ivalid(:)
!     .. Executable Statements ..
      Write (nout,*) 'S17ASF Example Program Results'

!     Skip heading in data file
      Read (nin,*)

      Write (nout,*)
      Write (nout,*) '     X           F          IVALID'
      Write (nout,*)

      Read (nin,*) n

      Allocate (x(n),f(n),ivalid(n))

      Read (nin,*) x(1:n)

      ifail = 0
      Call s17asf(n,x,f,ivalid,ifail)

      Do i = 1, n
        Write (nout,99999) x(i), f(i), ivalid(i)
      End Do

99999 Format (1X,1P,2E12.3,I5)
    End Program s17asfe


s17atfe.f90

    Program s17atfe

!     S17ATF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: nag_wp, s17atf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Integer                          :: i, ifail, n
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: f(:), x(:)
      Integer, Allocatable             :: ivalid(:)
!     .. Executable Statements ..
      Write (nout,*) 'S17ATF Example Program Results'

!     Skip heading in data file
      Read (nin,*)

      Write (nout,*)
      Write (nout,*) '     X           F          IVALID'
      Write (nout,*)

      Read (nin,*) n

      Allocate (x(n),f(n),ivalid(n))

      Read (nin,*) x(1:n)

      ifail = 0
      Call s17atf(n,x,f,ivalid,ifail)

      Do i = 1, n
        Write (nout,99999) x(i), f(i), ivalid(i)
      End Do

99999 Format (1X,1P,2E12.3,I5)
    End Program s17atfe


s17aufe.f90

    Program s17aufe

!     S17AUF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: nag_wp, s17auf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Integer                          :: i, ifail, n
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: f(:), x(:)
      Integer, Allocatable             :: ivalid(:)
!     .. Executable Statements ..
      Write (nout,*) 'S17AUF Example Program Results'

!     Skip heading in data file
      Read (nin,*)

      Write (nout,*)
      Write (nout,*) '     X           F          IVALID'
      Write (nout,*)

      Read (nin,*) n

      Allocate (x(n),f(n),ivalid(n))

      Read (nin,*) x(1:n)

      ifail = 0
      Call s17auf(n,x,f,ivalid,ifail)

      Do i = 1, n
        Write (nout,99999) x(i), f(i), ivalid(i)
      End Do

99999 Format (1X,1P,2E12.3,I5)
    End Program s17aufe


s17avfe.f90

    Program s17avfe

!     S17AVF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: nag_wp, s17avf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Integer                          :: i, ifail, n
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: f(:), x(:)
      Integer, Allocatable             :: ivalid(:)
!     .. Executable Statements ..
      Write (nout,*) 'S17AVF Example Program Results'

!     Skip heading in data file
      Read (nin,*)

      Write (nout,*)
      Write (nout,*) '     X           F          IVALID'
      Write (nout,*)

      Read (nin,*) n

      Allocate (x(n),f(n),ivalid(n))

      Read (nin,*) x(1:n)

      ifail = 0
      Call s17avf(n,x,f,ivalid,ifail)

      Do i = 1, n
        Write (nout,99999) x(i), f(i), ivalid(i)
      End Do

99999 Format (1X,1P,2E12.3,I5)
    End Program s17avfe


s17awfe.f90

    Program s17awfe

!     S17AWF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: nag_wp, s17awf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Integer                          :: i, ifail, n
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: f(:), x(:)
      Integer, Allocatable             :: ivalid(:)
!     .. Executable Statements ..
      Write (nout,*) 'S17AWF Example Program Results'

!     Skip heading in data file
      Read (nin,*)

      Write (nout,*)
      Write (nout,*) '     X           F          IVALID'
      Write (nout,*)

      Read (nin,*) n

      Allocate (x(n),f(n),ivalid(n))

      Read (nin,*) x(1:n)

      ifail = 0
      Call s17awf(n,x,f,ivalid,ifail)

      Do i = 1, n
        Write (nout,99999) x(i), f(i), ivalid(i)
      End Do

99999 Format (1X,1P,2E12.3,I5)
    End Program s17awfe


s17axfe.f90

    Program s17axfe

!     S17AXF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: nag_wp, s17axf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Integer                          :: i, ifail, n
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: f(:), x(:)
      Integer, Allocatable             :: ivalid(:)
!     .. Executable Statements ..
      Write (nout,*) 'S17AXF Example Program Results'

!     Skip heading in data file
      Read (nin,*)

      Write (nout,*)
      Write (nout,*) '     X           F          IVALID'
      Write (nout,*)

      Read (nin,*) n

      Allocate (x(n),f(n),ivalid(n))

      Read (nin,*) x(1:n)

      ifail = 0
      Call s17axf(n,x,f,ivalid,ifail)

      Do i = 1, n
        Write (nout,99999) x(i), f(i), ivalid(i)
      End Do

99999 Format (1X,1P,2E12.3,I5)
    End Program s17axfe


s17dcfe.f90

    Program s17dcfe

!     S17DCF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: nag_wp, s17dcf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: n = 2, nin = 5, nout = 6
!     .. Local Scalars ..
      Complex (Kind=nag_wp)            :: z
      Real (Kind=nag_wp)               :: fnu
      Integer                          :: ifail, ioerr, nz
      Character (1)                    :: scal
!     .. Local Arrays ..
      Complex (Kind=nag_wp)            :: cwrk(n), cy(n)
!     .. Executable Statements ..
      Write (nout,*) 'S17DCF Example Program Results'

!     Skip heading in data file
      Read (nin,*)

      Write (nout,*)
      Write (nout,99999) 'Calling with N =', n
      Write (nout,*)
      Write (nout,*)                                                           &
        '   FNU            Z        SCAL       CY(1)              CY(2)',      &
        '        NZ'
      Write (nout,*)

data: Do
        Read (nin,*,Iostat=ioerr) fnu, z, scal

        If (ioerr<0) Then
          Exit data
        End If

        ifail = 0
        Call s17dcf(fnu,z,n,scal,cy,nz,cwrk,ifail)

        Write (nout,99998) fnu, z, scal, cy(1), cy(2), nz
      End Do data

99999 Format (1X,A,I2)
99998 Format (1X,F7.4,'  (',F7.3,',',F7.3,')   ',A,2('  (',F7.3,',',F7.3,')'), &
        I4)
    End Program s17dcfe


s17defe.f90

    Program s17defe

!     S17DEF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: nag_wp, s17def
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: n = 2, nin = 5, nout = 6
!     .. Local Scalars ..
      Complex (Kind=nag_wp)            :: z
      Real (Kind=nag_wp)               :: fnu
      Integer                          :: ifail, ioerr, nz
      Character (1)                    :: scal
!     .. Local Arrays ..
      Complex (Kind=nag_wp)            :: cy(n)
!     .. Executable Statements ..
      Write (nout,*) 'S17DEF Example Program Results'

!     Skip heading in data file
      Read (nin,*)

      Write (nout,*)
      Write (nout,99999) 'Calling with N =', n
      Write (nout,*)
      Write (nout,*)                                                           &
        '   FNU            Z        SCAL       CY(1)              CY(2)',      &
        '     NZ'
      Write (nout,*)

data: Do
        Read (nin,*,Iostat=ioerr) fnu, z, scal

        If (ioerr<0) Then
          Exit data
        End If

        ifail = 0
        Call s17def(fnu,z,n,scal,cy,nz,ifail)

        Write (nout,99998) fnu, z, scal, cy(1), cy(2), nz
      End Do data

99999 Format (1X,A,I2)
99998 Format (1X,F7.4,'  (',F7.3,',',F7.3,')   ',A,2('  (',F7.3,',',F7.3,')'), &
        I4)
    End Program s17defe


s17dgfe.f90

    Program s17dgfe

!     S17DGF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: nag_wp, s17dgf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Complex (Kind=nag_wp)            :: ai, z
      Integer                          :: ifail, ioerr, nz
      Character (1)                    :: deriv, scal
!     .. Executable Statements ..
      Write (nout,*) 'S17DGF Example Program Results'

!     Skip heading in data file
      Read (nin,*)

      Write (nout,*)
      Write (nout,*) 'DERIV           Z         SCAL           AI          NZ'
      Write (nout,*)

data: Do
        Read (nin,*,Iostat=ioerr) deriv, z, scal

        If (ioerr<0) Then
          Exit data
        End If

        ifail = 0
        Call s17dgf(deriv,z,scal,ai,nz,ifail)

        Write (nout,99999) deriv, z, scal, ai, nz
      End Do data

99999 Format (3X,A,'   (',F8.4,',',F8.4,')   ',A,'   (',F8.4,',',F8.4,')',I4)
    End Program s17dgfe


s17dhfe.f90

    Program s17dhfe

!     S17DHF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: nag_wp, s17dhf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Complex (Kind=nag_wp)            :: bi, z
      Integer                          :: ifail, ioerr
      Character (1)                    :: deriv, scal
!     .. Executable Statements ..
      Write (nout,*) 'S17DHF Example Program Results'

!     Skip heading in data file
      Read (nin,*)

      Write (nout,*)
      Write (nout,*) 'DERIV           Z         SCAL           BI'
      Write (nout,*)

data: Do
        Read (nin,*,Iostat=ioerr) deriv, z, scal

        If (ioerr<0) Then
          Exit data
        End If

        ifail = 0
        Call s17dhf(deriv,z,scal,bi,ifail)

        Write (nout,99999) deriv, z, scal, bi
      End Do data

99999 Format (3X,A,'   (',F8.4,',',F8.4,')   ',A,'   (',F8.4,',',F8.4,')')
    End Program s17dhfe


s17dlfe.f90

    Program s17dlfe

!     S17DLF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: nag_wp, s17dlf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: n = 2, nin = 5, nout = 6
!     .. Local Scalars ..
      Complex (Kind=nag_wp)            :: z
      Real (Kind=nag_wp)               :: fnu
      Integer                          :: ifail, ioerr, m, nz
      Character (1)                    :: scal
!     .. Local Arrays ..
      Complex (Kind=nag_wp)            :: cy(n)
!     .. Executable Statements ..
      Write (nout,*) 'S17DLF Example Program Results'

!     Skip heading in data file
      Read (nin,*)

      Write (nout,*)
      Write (nout,99999) 'Calling with N =', n
      Write (nout,*)
      Write (nout,*) 'M    FNU            Z       SCAL       CY(1) ' //        &
        '             CY(2)        NZ'
      Write (nout,*)

data: Do
        Read (nin,*,Iostat=ioerr) m, fnu, z, scal

        If (ioerr<0) Then
          Exit data
        End If

        ifail = 0
        Call s17dlf(m,fnu,z,n,scal,cy,nz,ifail)

        Write (nout,99998) m, fnu, z, scal, cy(1), cy(2), nz
      End Do data

99999 Format (1X,A,I2)
99998 Format (1X,I1,1X,F7.4,'  (',F7.3,',',F7.3,')  ',A,                       &
        2('  (',F7.3,',',F7.3,')'),I4)
    End Program s17dlfe


s18acfe.f90

    Program s18acfe

!     S18ACF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: nag_wp, s18acf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: x, y
      Integer                          :: ifail, ioerr
!     .. Executable Statements ..
      Write (nout,*) 'S18ACF Example Program Results'

!     Skip heading in data file
      Read (nin,*)

      Write (nout,*)
      Write (nout,*) '     X           Y'
      Write (nout,*)

data: Do
        Read (nin,*,Iostat=ioerr) x

        If (ioerr<0) Then
          Exit data
        End If

        ifail = -1
        y = s18acf(x,ifail)

        If (ifail<0) Then
          Exit data
        End If

        Write (nout,99999) x, y
      End Do data

99999 Format (1X,1P,2E12.3)
    End Program s18acfe


s18adfe.f90

    Program s18adfe

!     S18ADF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: nag_wp, s18adf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: x, y
      Integer                          :: ifail, ioerr
!     .. Executable Statements ..
      Write (nout,*) 'S18ADF Example Program Results'

!     Skip heading in data file
      Read (nin,*)

      Write (nout,*)
      Write (nout,*) '     X           Y'
      Write (nout,*)

data: Do
        Read (nin,*,Iostat=ioerr) x

        If (ioerr<0) Then
          Exit data
        End If

        ifail = -1
        y = s18adf(x,ifail)

        If (ifail<0) Then
          Exit data
        End If

        Write (nout,99999) x, y
      End Do data

99999 Format (1X,1P,2E12.3)
    End Program s18adfe


s18aefe.f90

    Program s18aefe

!     S18AEF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: nag_wp, s18aef
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: x, y
      Integer                          :: ifail, ioerr
!     .. Executable Statements ..
      Write (nout,*) 'S18AEF Example Program Results'

!     Skip heading in data file
      Read (nin,*)

      Write (nout,*)
      Write (nout,*) '     X           Y'
      Write (nout,*)

data: Do
        Read (nin,*,Iostat=ioerr) x

        If (ioerr<0) Then
          Exit data
        End If

        ifail = -1
        y = s18aef(x,ifail)

        If (ifail<0) Then
          Exit data
        End If

        Write (nout,99999) x, y
      End Do data

99999 Format (1X,1P,2E12.3)
    End Program s18aefe


s18affe.f90

    Program s18affe

!     S18AFF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: nag_wp, s18aff
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: x, y
      Integer                          :: ifail, ioerr
!     .. Executable Statements ..
      Write (nout,*) 'S18AFF Example Program Results'

!     Skip heading in data file
      Read (nin,*)

      Write (nout,*)
      Write (nout,*) '     X           Y'
      Write (nout,*)

data: Do
        Read (nin,*,Iostat=ioerr) x

        If (ioerr<0) Then
          Exit data
        End If

        ifail = -1
        y = s18aff(x,ifail)

        If (ifail<0) Then
          Exit data
        End If

        Write (nout,99999) x, y
      End Do data

99999 Format (1X,1P,2E12.3)
    End Program s18affe


s18aqfe.f90

    Program s18aqfe

!     S18AQF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: nag_wp, s18aqf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Integer                          :: i, ifail, n
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: f(:), x(:)
      Integer, Allocatable             :: ivalid(:)
!     .. Executable Statements ..
      Write (nout,*) 'S18AQF Example Program Results'

!     Skip heading in data file
      Read (nin,*)

      Write (nout,*)
      Write (nout,*) '     X           F          IVALID'
      Write (nout,*)

      Read (nin,*) n

      Allocate (x(n),f(n),ivalid(n))

      Read (nin,*) x(1:n)

      ifail = 0
      Call s18aqf(n,x,f,ivalid,ifail)

      Do i = 1, n
        Write (nout,99999) x(i), f(i), ivalid(i)
      End Do

99999 Format (1X,1P,2E12.3,I5)
    End Program s18aqfe


s18arfe.f90

    Program s18arfe

!     S18ARF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: nag_wp, s18arf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Integer                          :: i, ifail, n
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: f(:), x(:)
      Integer, Allocatable             :: ivalid(:)
!     .. Executable Statements ..
      Write (nout,*) 'S18ARF Example Program Results'

!     Skip heading in data file
      Read (nin,*)

      Write (nout,*)
      Write (nout,*) '     X           F          IVALID'
      Write (nout,*)

      Read (nin,*) n

      Allocate (x(n),f(n),ivalid(n))

      Read (nin,*) x(1:n)

      ifail = 0
      Call s18arf(n,x,f,ivalid,ifail)

      Do i = 1, n
        Write (nout,99999) x(i), f(i), ivalid(i)
      End Do

99999 Format (1X,1P,2E12.3,I5)
    End Program s18arfe


s18asfe.f90

    Program s18asfe

!     S18ASF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: nag_wp, s18asf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Integer                          :: i, ifail, n
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: f(:), x(:)
      Integer, Allocatable             :: ivalid(:)
!     .. Executable Statements ..
      Write (nout,*) 'S18ASF Example Program Results'

!     Skip heading in data file
      Read (nin,*)

      Write (nout,*)
      Write (nout,*) '     X           F          IVALID'
      Write (nout,*)

      Read (nin,*) n

      Allocate (x(n),f(n),ivalid(n))

      Read (nin,*) x(1:n)

      ifail = 0
      Call s18asf(n,x,f,ivalid,ifail)

      Do i = 1, n
        Write (nout,99999) x(i), f(i), ivalid(i)
      End Do

99999 Format (1X,1P,2E12.3,I5)
    End Program s18asfe


s18atfe.f90

    Program s18atfe

!     S18ATF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: nag_wp, s18atf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Integer                          :: i, ifail, n
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: f(:), x(:)
      Integer, Allocatable             :: ivalid(:)
!     .. Executable Statements ..
      Write (nout,*) 'S18ATF Example Program Results'

!     Skip heading in data file
      Read (nin,*)

      Write (nout,*)
      Write (nout,*) '     X           F          IVALID'
      Write (nout,*)

      Read (nin,*) n

      Allocate (x(n),f(n),ivalid(n))

      Read (nin,*) x(1:n)

      ifail = 0
      Call s18atf(n,x,f,ivalid,ifail)

      Do i = 1, n
        Write (nout,99999) x(i), f(i), ivalid(i)
      End Do

99999 Format (1X,1P,2E12.3,I5)
    End Program s18atfe


s18ccfe.f90

    Program s18ccfe

!     S18CCF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: nag_wp, s18ccf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: x, y
      Integer                          :: ifail, ioerr
!     .. Executable Statements ..
      Write (nout,*) 'S18CCF Example Program Results'

!     Skip heading in data file
      Read (nin,*)

      Write (nout,*)
      Write (nout,*) '     X           Y'
      Write (nout,*)

data: Do
        Read (nin,*,Iostat=ioerr) x

        If (ioerr<0) Then
          Exit data
        End If

        ifail = -1
        y = s18ccf(x,ifail)

        If (ifail<0) Then
          Exit data
        End If

        Write (nout,99999) x, y
      End Do data

99999 Format (1X,1P,2E12.3)
    End Program s18ccfe


s18cdfe.f90

    Program s18cdfe

!     S18CDF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: nag_wp, s18cdf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: x, y
      Integer                          :: ifail, ioerr
!     .. Executable Statements ..
      Write (nout,*) 'S18CDF Example Program Results'

!     Skip heading in data file
      Read (nin,*)

      Write (nout,*)
      Write (nout,*) '     X           Y'
      Write (nout,*)

data: Do
        Read (nin,*,Iostat=ioerr) x

        If (ioerr<0) Then
          Exit data
        End If

        ifail = -1
        y = s18cdf(x,ifail)

        If (ifail<0) Then
          Exit data
        End If

        Write (nout,99999) x, y
      End Do data

99999 Format (1X,1P,2E12.3)
    End Program s18cdfe


s18cefe.f90

    Program s18cefe

!     S18CEF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: nag_wp, s18cef
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: x, y
      Integer                          :: ifail, ioerr
!     .. Executable Statements ..
      Write (nout,*) 'S18CEF Example Program Results'

!     Skip heading in data file
      Read (nin,*)

      Write (nout,*)
      Write (nout,*) '     X           Y'
      Write (nout,*)

data: Do
        Read (nin,*,Iostat=ioerr) x

        If (ioerr<0) Then
          Exit data
        End If

        ifail = 0
        y = s18cef(x,ifail)

        Write (nout,99999) x, y
      End Do data

99999 Format (1X,1P,2E12.3)
    End Program s18cefe


s18cffe.f90

    Program s18cffe

!     S18CFF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: nag_wp, s18cff
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: x, y
      Integer                          :: ifail, ioerr
!     .. Executable Statements ..
      Write (nout,*) 'S18CFF Example Program Results'

!     Skip heading in data file
      Read (nin,*)

      Write (nout,*)
      Write (nout,*) '     X           Y'
      Write (nout,*)

data: Do
        Read (nin,*,Iostat=ioerr) x

        If (ioerr<0) Then
          Exit data
        End If

        ifail = 0
        y = s18cff(x,ifail)

        Write (nout,99999) x, y
      End Do data

99999 Format (1X,1P,2E12.3)
    End Program s18cffe


s18cqfe.f90

    Program s18cqfe

!     S18CQF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: nag_wp, s18cqf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Integer                          :: i, ifail, n
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: f(:), x(:)
      Integer, Allocatable             :: ivalid(:)
!     .. Executable Statements ..
      Write (nout,*) 'S18CQF Example Program Results'

!     Skip heading in data file
      Read (nin,*)

      Write (nout,*)
      Write (nout,*) '     X           F          IVALID'
      Write (nout,*)

      Read (nin,*) n

      Allocate (x(n),f(n),ivalid(n))

      Read (nin,*) x(1:n)

      ifail = 0
      Call s18cqf(n,x,f,ivalid,ifail)

      Do i = 1, n
        Write (nout,99999) x(i), f(i), ivalid(i)
      End Do

99999 Format (1X,1P,2E12.3,I5)
    End Program s18cqfe


s18crfe.f90

    Program s18crfe

!     S18CRF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: nag_wp, s18crf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Integer                          :: i, ifail, n
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: f(:), x(:)
      Integer, Allocatable             :: ivalid(:)
!     .. Executable Statements ..
      Write (nout,*) 'S18CRF Example Program Results'

!     Skip heading in data file
      Read (nin,*)

      Write (nout,*)
      Write (nout,*) '     X           F          IVALID'
      Write (nout,*)

      Read (nin,*) n

      Allocate (x(n),f(n),ivalid(n))

      Read (nin,*) x(1:n)

      ifail = 0
      Call s18crf(n,x,f,ivalid,ifail)

      Do i = 1, n
        Write (nout,99999) x(i), f(i), ivalid(i)
      End Do

99999 Format (1X,1P,2E12.3,I5)
    End Program s18crfe


s18csfe.f90

    Program s18csfe

!     S18CSF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: nag_wp, s18csf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Integer                          :: i, ifail, n
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: f(:), x(:)
!     .. Executable Statements ..
      Write (nout,*) 'S18CSF Example Program Results'

!     Skip heading in data file
      Read (nin,*)

      Write (nout,*)
      Write (nout,*) '     X           F'
      Write (nout,*)

      Read (nin,*) n

      Allocate (x(n),f(n))

      Read (nin,*) x(1:n)

      ifail = 0
      Call s18csf(n,x,f,ifail)

      Do i = 1, n
        Write (nout,99999) x(i), f(i)
      End Do

99999 Format (1X,1P,2E12.3,I5)
    End Program s18csfe


s18ctfe.f90

    Program s18ctfe

!     S18CTF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: nag_wp, s18ctf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Integer                          :: i, ifail, n
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: f(:), x(:)
!     .. Executable Statements ..
      Write (nout,*) 'S18CTF Example Program Results'

!     Skip heading in data file
      Read (nin,*)

      Write (nout,*)
      Write (nout,*) '     X           F'
      Write (nout,*)

      Read (nin,*) n

      Allocate (x(n),f(n))

      Read (nin,*) x(1:n)

      ifail = 0
      Call s18ctf(n,x,f,ifail)

      Do i = 1, n
        Write (nout,99999) x(i), f(i)
      End Do

99999 Format (1X,1P,2E12.3,I5)
    End Program s18ctfe


s18dcfe.f90

    Program s18dcfe

!     S18DCF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: nag_wp, s18dcf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: n = 2, nin = 5, nout = 6
!     .. Local Scalars ..
      Complex (Kind=nag_wp)            :: z
      Real (Kind=nag_wp)               :: fnu
      Integer                          :: ifail, ioerr, nz
      Character (1)                    :: scal
!     .. Local Arrays ..
      Complex (Kind=nag_wp)            :: cy(n)
!     .. Executable Statements ..
      Write (nout,*) 'S18DCF Example Program Results'

!     Skip heading in data file
      Read (nin,*)

      Write (nout,*)
      Write (nout,99999) 'Calling with N =', n
      Write (nout,*)
      Write (nout,*)                                                           &
        '   FNU            Z        SCAL       CY(1)              CY(2)',      &
        '        NZ'
      Write (nout,*)

data: Do
        Read (nin,*,Iostat=ioerr) fnu, z, scal

        If (ioerr<0) Then
          Exit data
        End If

        ifail = 0
        Call s18dcf(fnu,z,n,scal,cy,nz,ifail)

        Write (nout,99998) fnu, z, scal, cy(1), cy(2), nz
      End Do data

99999 Format (1X,A,I2)
99998 Format (1X,F7.4,'  (',F7.3,',',F7.3,')   ',A,2('  (',F7.3,',',F7.3,')'), &
        I4)
    End Program s18dcfe


s18defe.f90

    Program s18defe

!     S18DEF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: nag_wp, s18def
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: n = 2, nin = 5, nout = 6
!     .. Local Scalars ..
      Complex (Kind=nag_wp)            :: z
      Real (Kind=nag_wp)               :: fnu
      Integer                          :: ifail, ioerr, nz
      Character (1)                    :: scal
!     .. Local Arrays ..
      Complex (Kind=nag_wp)            :: cy(n)
!     .. Executable Statements ..
      Write (nout,*) 'S18DEF Example Program Results'

!     Skip heading in data file
      Read (nin,*)

      Write (nout,*)
      Write (nout,99999) 'Calling with N =', n
      Write (nout,*)
      Write (nout,*)                                                           &
        '   FNU            Z        SCAL       CY(1)              CY(2)',      &
        '        NZ'
      Write (nout,*)

data: Do
        Read (nin,*,Iostat=ioerr) fnu, z, scal

        If (ioerr<0) Then
          Exit data
        End If

        ifail = 0
        Call s18def(fnu,z,n,scal,cy,nz,ifail)

        Write (nout,99998) fnu, z, scal, cy(1), cy(2), nz
      End Do data

99999 Format (1X,A,I2)
99998 Format (1X,F7.4,'  (',F7.3,',',F7.3,')   ',A,2('  (',F7.3,',',F7.3,')'), &
        I4)
    End Program s18defe


s18gkfe.f90

    Program s18gkfe

!     S18GKF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: nag_wp, s18gkf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Complex (Kind=nag_wp)            :: z
      Real (Kind=nag_wp)               :: a, alpha
      Integer                          :: i, ifail, nl
!     .. Local Arrays ..
      Complex (Kind=nag_wp), Allocatable :: b(:)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: abs, real, sign
!     .. Executable Statements ..
      Write (nout,*) 'S18GKF Example Program Results'

!     Skip heading in data file
      Read (nin,*)

      Read (nin,*) z, a, nl
      Allocate (b(abs(nl)+1))

      ifail = 0
      Call s18gkf(z,a,nl,b,ifail)

      Write (nout,*)
      Write (nout,*) '      Z           A     NL'
      Write (nout,*)
      Write (nout,99999) z, a, nl

      Write (nout,*)
      Write (nout,*) ' Requested values of J_alpha(Z)'
      Write (nout,*)
      Write (nout,*) '     alpha              J_alpha(Z)'

      alpha = a

      Do i = 1, abs(nl) + 1
        Write (nout,99998) alpha, b(i)
        alpha = alpha + sign(1.0E0_nag_wp,real(nl,kind=nag_wp))
      End Do

99999 Format (1X,'( ',F4.1,', ',F4.1,' )',2X,F4.1,I6)
99998 Format (1X,1P,E12.4,3X,'(',E12.4,',',E12.4,' )')
    End Program s18gkfe


s19aafe.f90

    Program s19aafe

!     S19AAF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: nag_wp, s19aaf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: x, y
      Integer                          :: ifail, ioerr
!     .. Executable Statements ..
      Write (nout,*) 'S19AAF Example Program Results'

!     Skip heading in data file
      Read (nin,*)

      Write (nout,*)
      Write (nout,*) '     X           Y'
      Write (nout,*)

data: Do
        Read (nin,*,Iostat=ioerr) x

        If (ioerr<0) Then
          Exit data
        End If

        ifail = -1
        y = s19aaf(x,ifail)

        If (ifail<0) Then
          Exit data
        End If

        Write (nout,99999) x, y
      End Do data

99999 Format (1X,1P,2E12.3)
    End Program s19aafe


s19abfe.f90

    Program s19abfe

!     S19ABF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: nag_wp, s19abf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: x, y
      Integer                          :: ifail, ioerr
!     .. Executable Statements ..
      Write (nout,*) 'S19ABF Example Program Results'

!     Skip heading in data file
      Read (nin,*)

      Write (nout,*)
      Write (nout,*) '     X           Y'
      Write (nout,*)

data: Do
        Read (nin,*,Iostat=ioerr) x

        If (ioerr<0) Then
          Exit data
        End If

        ifail = -1
        y = s19abf(x,ifail)

        If (ifail<0) Then
          Exit data
        End If

        Write (nout,99999) x, y
      End Do data

99999 Format (1X,1P,2E12.3)
    End Program s19abfe


s19acfe.f90

    Program s19acfe

!     S19ACF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: nag_wp, s19acf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: x, y
      Integer                          :: ifail, ioerr
!     .. Executable Statements ..
      Write (nout,*) 'S19ACF Example Program Results'

!     Skip heading in data file
      Read (nin,*)

      Write (nout,*)
      Write (nout,*) '     X           Y'
      Write (nout,*)

data: Do
        Read (nin,*,Iostat=ioerr) x

        If (ioerr<0) Then
          Exit data
        End If

        ifail = -1
        y = s19acf(x,ifail)

        If (ifail<0) Then
          Exit data
        End If

        Write (nout,99999) x, y
      End Do data

99999 Format (1X,1P,2E12.3)
    End Program s19acfe


s19adfe.f90

    Program s19adfe

!     S19ADF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: nag_wp, s19adf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: x, y
      Integer                          :: ifail, ioerr
!     .. Executable Statements ..
      Write (nout,*) 'S19ADF Example Program Results'

!     Skip heading in data file
      Read (nin,*)

      Write (nout,*)
      Write (nout,*) '     X           Y'
      Write (nout,*)

data: Do
        Read (nin,*,Iostat=ioerr) x

        If (ioerr<0) Then
          Exit data
        End If

        ifail = -1
        y = s19adf(x,ifail)

        If (ifail<0) Then
          Exit data
        End If

        Write (nout,99999) x, y
      End Do data

99999 Format (1X,1P,2E12.3)
    End Program s19adfe


s19anfe.f90

    Program s19anfe

!     S19ANF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: nag_wp, s19anf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Integer                          :: i, ifail, n
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: f(:), x(:)
      Integer, Allocatable             :: ivalid(:)
!     .. Executable Statements ..
      Write (nout,*) 'S19ANF Example Program Results'

!     Skip heading in data file
      Read (nin,*)

      Write (nout,*)
      Write (nout,*) '     X           F          IVALID'
      Write (nout,*)

      Read (nin,*) n

      Allocate (x(n),f(n),ivalid(n))

      Read (nin,*) x(1:n)

      ifail = 0
      Call s19anf(n,x,f,ivalid,ifail)

      Do i = 1, n
        Write (nout,99999) x(i), f(i), ivalid(i)
      End Do

99999 Format (1X,1P,2E12.3,I5)
    End Program s19anfe


s19apfe.f90

    Program s19apfe

!     S19APF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: nag_wp, s19apf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Integer                          :: i, ifail, n
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: f(:), x(:)
      Integer, Allocatable             :: ivalid(:)
!     .. Executable Statements ..
      Write (nout,*) 'S19APF Example Program Results'

!     Skip heading in data file
      Read (nin,*)

      Write (nout,*)
      Write (nout,*) '     X           F          IVALID'
      Write (nout,*)

      Read (nin,*) n

      Allocate (x(n),f(n),ivalid(n))

      Read (nin,*) x(1:n)

      ifail = 0
      Call s19apf(n,x,f,ivalid,ifail)

      Do i = 1, n
        Write (nout,99999) x(i), f(i), ivalid(i)
      End Do

99999 Format (1X,1P,2E12.3,I5)
    End Program s19apfe


s19aqfe.f90

    Program s19aqfe

!     S19AQF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: nag_wp, s19aqf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Integer                          :: i, ifail, n
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: f(:), x(:)
      Integer, Allocatable             :: ivalid(:)
!     .. Executable Statements ..
      Write (nout,*) 'S19AQF Example Program Results'

!     Skip heading in data file
      Read (nin,*)

      Write (nout,*)
      Write (nout,*) '     X           F          IVALID'
      Write (nout,*)

      Read (nin,*) n

      Allocate (x(n),f(n),ivalid(n))

      Read (nin,*) x(1:n)

      ifail = 0
      Call s19aqf(n,x,f,ivalid,ifail)

      Do i = 1, n
        Write (nout,99999) x(i), f(i), ivalid(i)
      End Do

99999 Format (1X,1P,2E12.3,I5)
    End Program s19aqfe


s19arfe.f90

    Program s19arfe

!     S19ARF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: nag_wp, s19arf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Integer                          :: i, ifail, n
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: f(:), x(:)
      Integer, Allocatable             :: ivalid(:)
!     .. Executable Statements ..
      Write (nout,*) 'S19ARF Example Program Results'

!     Skip heading in data file
      Read (nin,*)

      Write (nout,*)
      Write (nout,*) '     X           F          IVALID'
      Write (nout,*)

      Read (nin,*) n

      Allocate (x(n),f(n),ivalid(n))

      Read (nin,*) x(1:n)

      ifail = 0
      Call s19arf(n,x,f,ivalid,ifail)

      Do i = 1, n
        Write (nout,99999) x(i), f(i), ivalid(i)
      End Do

99999 Format (1X,1P,2E12.3,I5)
    End Program s19arfe


s20acfe.f90

    Program s20acfe

!     S20ACF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: nag_wp, s20acf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: x, y
      Integer                          :: ifail, ioerr
!     .. Executable Statements ..
      Write (nout,*) 'S20ACF Example Program Results'

!     Skip heading in data file
      Read (nin,*)

      Write (nout,*)
      Write (nout,*) '     X          Y'
      Write (nout,*)

data: Do
        Read (nin,*,Iostat=ioerr) x

        If (ioerr<0) Then
          Exit data
        End If

        ifail = 0
        y = s20acf(x,ifail)

        Write (nout,99999) x, y
      End Do data

99999 Format (1X,1P,2E12.3)
    End Program s20acfe


s20adfe.f90

    Program s20adfe

!     S20ADF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: nag_wp, s20adf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: x, y
      Integer                          :: ifail, ioerr
!     .. Executable Statements ..
      Write (nout,*) 'S20ADF Example Program Results'

!     Skip heading in data file
      Read (nin,*)

      Write (nout,*)
      Write (nout,*) '     X           Y'
      Write (nout,*)

data: Do
        Read (nin,*,Iostat=ioerr) x

        If (ioerr<0) Then
          Exit data
        End If

        ifail = 0
        y = s20adf(x,ifail)

        Write (nout,99999) x, y
      End Do data

99999 Format (1X,1P,2E12.3)
    End Program s20adfe


s20aqfe.f90

    Program s20aqfe

!     S20AQF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: nag_wp, s20aqf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Integer                          :: i, ifail, n
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: f(:), x(:)
!     .. Executable Statements ..
      Write (nout,*) 'S20AQF Example Program Results'

!     Skip heading in data file
      Read (nin,*)

      Write (nout,*)
      Write (nout,*) '     X           F'
      Write (nout,*)

      Read (nin,*) n

      Allocate (x(n),f(n))

      Read (nin,*) x(1:n)

      ifail = 0
      Call s20aqf(n,x,f,ifail)

      Do i = 1, n
        Write (nout,99999) x(i), f(i)
      End Do

99999 Format (1X,1P,2E12.3)
    End Program s20aqfe


s20arfe.f90

    Program s20arfe

!     S20ARF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: nag_wp, s20arf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Integer                          :: i, ifail, n
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: f(:), x(:)
!     .. Executable Statements ..
      Write (nout,*) 'S20ARF Example Program Results'

!     Skip heading in data file
      Read (nin,*)

      Write (nout,*)
      Write (nout,*) '     X           F'
      Write (nout,*)

      Read (nin,*) n

      Allocate (x(n),f(n))

      Read (nin,*) x(1:n)

      ifail = 0
      Call s20arf(n,x,f,ifail)

      Do i = 1, n
        Write (nout,99999) x(i), f(i)
      End Do

99999 Format (1X,1P,2E12.3)
    End Program s20arfe


s21bafe.f90

    Program s21bafe

!     S21BAF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: nag_wp, s21baf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: rc, x, y
      Integer                          :: ifail, ix
!     .. Intrinsic Procedures ..
      Intrinsic                        :: real
!     .. Executable Statements ..
      Write (nout,*) 'S21BAF Example Program Results'

      Write (nout,*)
      Write (nout,*) '    X      Y        S21BAF'
      Write (nout,*)

data: Do ix = 1, 3
        x = real(ix,kind=nag_wp)*0.5E0_nag_wp
        y = 1.0E0_nag_wp

        ifail = -1
        rc = s21baf(x,y,ifail)

        If (ifail<0) Then
          Exit data
        End If

        Write (nout,99999) x, y, rc
      End Do data

99999 Format (1X,2F7.2,F12.4)
    End Program s21bafe


s21bbfe.f90

    Program s21bbfe

!     S21BBF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: nag_wp, s21bbf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: rf, x, y, z
      Integer                          :: ifail, ix
!     .. Intrinsic Procedures ..
      Intrinsic                        :: real
!     .. Executable Statements ..
      Write (nout,*) 'S21BBF Example Program Results'

      Write (nout,*)
      Write (nout,*) '    X      Y      Z        S21BBF'
      Write (nout,*)

data: Do ix = 1, 3
        x = real(ix,kind=nag_wp)*0.5E0_nag_wp
        y = real(ix+1,kind=nag_wp)*0.5E0_nag_wp
        z = real(ix+2,kind=nag_wp)*0.5E0_nag_wp

        ifail = -1
        rf = s21bbf(x,y,z,ifail)

        If (ifail<0) Then
          Exit data
        End If

        Write (nout,99999) x, y, z, rf
      End Do data

99999 Format (1X,3F7.2,F12.4)
    End Program s21bbfe


s21bcfe.f90

    Program s21bcfe

!     S21BCF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: nag_wp, s21bcf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: rd, x, y, z
      Integer                          :: ifail, ix, iy
!     .. Intrinsic Procedures ..
      Intrinsic                        :: real
!     .. Executable Statements ..
      Write (nout,*) 'S21BCF Example Program Results'

      Write (nout,*)
      Write (nout,*) '    X      Y      Z        S21BCF'
      Write (nout,*)

data: Do ix = 1, 3
        x = real(ix,kind=nag_wp)*0.5E0_nag_wp

        Do iy = ix, 3
          y = real(iy,kind=nag_wp)*0.5E0_nag_wp
          z = 1.0E0_nag_wp

          ifail = -1
          rd = s21bcf(x,y,z,ifail)

          If (ifail<0) Then
            Exit data
          End If

          Write (nout,99999) x, y, z, rd
        End Do

      End Do data

99999 Format (1X,3F7.2,F12.4)
    End Program s21bcfe


s21bdfe.f90

    Program s21bdfe

!     S21BDF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: nag_wp, s21bdf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: r, rj, x, y, z
      Integer                          :: ifail, ix, iy, iz
!     .. Intrinsic Procedures ..
      Intrinsic                        :: real
!     .. Executable Statements ..
      Write (nout,*) 'S21BDF Example Program Results'

      Write (nout,*)
      Write (nout,*) '    X      Y      Z      R        S21BDF'
      Write (nout,*)

data: Do ix = 1, 3
        x = real(ix,kind=nag_wp)*0.5E0_nag_wp

        Do iy = ix, 3
          y = real(iy,kind=nag_wp)*0.5E0_nag_wp

          Do iz = iy, 3
            z = real(iz,kind=nag_wp)*0.5E0_nag_wp
            r = 2.0E0_nag_wp

            ifail = -1
            rj = s21bdf(x,y,z,r,ifail)

            If (ifail<0) Then
              Exit data
            End If

            Write (nout,99999) x, y, z, r, rj
          End Do

        End Do

      End Do data

99999 Format (1X,4F7.2,F12.4)
    End Program s21bdfe


s21befe.f90

    Program s21befe

!     S21BEF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: nag_wp, s21bef, x01aaf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: dm, f, phi, pi
      Integer                          :: ifail, ix
!     .. Intrinsic Procedures ..
      Intrinsic                        :: real
!     .. Executable Statements ..
      Write (nout,*) 'S21BEF Example Program Results'

      Write (nout,*)
      Write (nout,*) '    PHI    DM      S21BEF'
      Write (nout,*)

      pi = x01aaf(pi)

data: Do ix = 1, 3
        phi = real(ix,kind=nag_wp)*pi/6.0E0_nag_wp
        dm = real(ix,kind=nag_wp)*0.25E0_nag_wp

        ifail = -1
        f = s21bef(phi,dm,ifail)

        If (ifail<0) Then
          Exit data
        End If

        Write (nout,99999) phi, dm, f
      End Do data

99999 Format (1X,2F7.2,F12.4)
    End Program s21befe


s21bffe.f90

    Program s21bffe

!     S21BFF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: nag_wp, s21bff, x01aaf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: dm, f, phi, pi
      Integer                          :: ifail, ix
!     .. Intrinsic Procedures ..
      Intrinsic                        :: real
!     .. Executable Statements ..
      Write (nout,*) 'S21BFF Example Program Results'

      Write (nout,*)
      Write (nout,*) '    PHI    DM      S21BFF'
      Write (nout,*)

      pi = x01aaf(pi)

data: Do ix = 1, 3
        phi = real(ix,kind=nag_wp)*pi/6.0E0_nag_wp
        dm = real(ix,kind=nag_wp)*0.25E0_nag_wp

        ifail = -1
        f = s21bff(phi,dm,ifail)

        If (ifail<0) Then
          Exit data
        End If

        Write (nout,99999) phi, dm, f
      End Do data

99999 Format (1X,2F7.2,F12.4)
    End Program s21bffe


s21bgfe.f90

    Program s21bgfe

!     S21BGF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: nag_wp, s21bgf, x01aaf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: dm, dn, f, phi, pi
      Integer                          :: ifail, ix
!     .. Intrinsic Procedures ..
      Intrinsic                        :: real
!     .. Executable Statements ..
      Write (nout,*) 'S21BGF Example Program Results'

      Write (nout,*)
      Write (nout,*) '    DN     PHI    DM      S21BGF'
      Write (nout,*)

      pi = x01aaf(pi)

data: Do ix = 1, 3
        phi = real(ix,kind=nag_wp)*pi/6.0E0_nag_wp
        dm = real(ix,kind=nag_wp)*0.25E0_nag_wp
        dn = ((-1.0E0_nag_wp)**(ix+1))*real(ix,kind=nag_wp)*0.1E0_nag_wp

        ifail = -1
        f = s21bgf(dn,phi,dm,ifail)

        If (ifail<0) Then
          Exit data
        End If

        Write (nout,99999) dn, phi, dm, f
      End Do data

99999 Format (1X,3F7.2,F12.4)
    End Program s21bgfe


s21bhfe.f90

    Program s21bhfe

!     S21BHF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: nag_wp, s21bhf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: dm, f
      Integer                          :: ifail, ix
!     .. Intrinsic Procedures ..
      Intrinsic                        :: real
!     .. Executable Statements ..
      Write (nout,*) 'S21BHF Example Program Results'

      Write (nout,*)
      Write (nout,*) '    DM       S21BHF'
      Write (nout,*)

data: Do ix = 1, 3
        dm = real(ix,kind=nag_wp)*0.25E0_nag_wp

        ifail = -1
        f = s21bhf(dm,ifail)

        If (ifail<0) Then
          Exit data
        End If

        Write (nout,99999) dm, f
      End Do data

99999 Format (1X,F7.2,F12.4)
    End Program s21bhfe


s21bjfe.f90

    Program s21bjfe

!     S21BJF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: nag_wp, s21bjf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: dm, f
      Integer                          :: ifail, ix
!     .. Intrinsic Procedures ..
      Intrinsic                        :: real
!     .. Executable Statements ..
      Write (nout,*) 'S21BJF Example Program Results'

      Write (nout,*)
      Write (nout,*) '    DM       S21BJF'
      Write (nout,*)

data: Do ix = 1, 3
        dm = real(ix,kind=nag_wp)*0.25E0_nag_wp

        ifail = -1
        f = s21bjf(dm,ifail)

        If (ifail<0) Then
          Exit data
        End If

        Write (nout,99999) dm, f
      End Do data

99999 Format (1X,F7.2,F12.4)
    End Program s21bjfe


s21cafe.f90

    Program s21cafe

!     S21CAF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: nag_wp, s21caf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: cn, dn, m, sn, u
      Integer                          :: ifail, ioerr
!     .. Executable Statements ..
      Write (nout,*) 'S21CAF Example Program Results'

!     Skip heading in data file
      Read (nin,*)

      Write (nout,*)
      Write (nout,*)                                                           &
        '          U            M           SN           CN           DN'

data: Do
        Read (nin,*,Iostat=ioerr) u, m

        If (ioerr<0) Then
          Exit data
        End If

        ifail = 0
        Call s21caf(u,m,sn,cn,dn,ifail)

        Write (nout,99999) u, m, sn, cn, dn
      End Do data

99999 Format (3X,5E13.4)
    End Program s21cafe


s21cbfe.f90

    Program s21cbfe

!     S21CBF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: nag_wp, s21cbf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Complex (Kind=nag_wp)            :: cn, dn, sn, z
      Real (Kind=nag_wp)               :: ak2
      Integer                          :: ifail
!     .. Executable Statements ..
      Write (nout,*) 'S21CBF Example Program Results'

!     Skip heading in data file
      Read (nin,*)

      Write (nout,*)

      Read (nin,*) z, ak2

      ifail = 0
      Call s21cbf(z,ak2,sn,cn,dn,ifail)

      Write (nout,*) '          Z                    AK2'
      Write (nout,99999) z, ak2
      Write (nout,*)
      Write (nout,*) '         SN                     CN',                     &
        '                     DN'
      Write (nout,99998) sn, cn, dn

99999 Format (1X,'(',F8.4,',',F8.4,')',5X,F10.2)
99998 Format (3(' (',F8.4,',',F8.4,')',3X))
    End Program s21cbfe


s21ccfe.f90

    Program s21ccfe

!     S21CCF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: nag_wp, s21ccf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: q, x, y
      Integer                          :: ifail, k
!     .. Executable Statements ..
      Write (nout,*) 'S21CCF Example Program Results'

!     Skip heading in data file
      Read (nin,*)

      Write (nout,*)
      Write (nout,*) ' K    X     Q         Y'
      Write (nout,*)

      Read (nin,*) k, x, q

      ifail = -1
      y = s21ccf(k,x,q,ifail)

      If (ifail>=0) Then
        Write (nout,99999) k, x, q, y
      End If

99999 Format (1X,I2,2X,F4.1,2X,F4.1,2X,1P,E12.4)
    End Program s21ccfe


s21dafe.f90

    Program s21dafe

!     S21DAF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: nag_wp, s21daf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Complex (Kind=nag_wp)            :: y, z
      Real (Kind=nag_wp)               :: a, akp, b
      Integer                          :: ifail
!     .. Executable Statements ..
      Write (nout,*) 'S21DAF Example Program Results'

!     Skip heading in data file
      Read (nin,*)

      Write (nout,*)
      Write (nout,*) '     Z          AKP     A', '      B                 Y'
      Write (nout,*)

      Read (nin,*) z, akp, a, b

      ifail = -1
      y = s21daf(z,akp,a,b,ifail)

      If (ifail>=0) Then
        Write (nout,99999) z, akp, a, b, y
      End If

99999 Format (1X,'(',F4.1,',',F4.1,' )',3F7.1,3X,'(',1P,E12.4,',',E12.4,' )')
    End Program s21dafe


s22aafe.f90

    Program s22aafe

!     S22AAF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: nag_wp, s22aaf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nlmax = 100, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: x
      Integer                          :: ifail, m, mode, n, nl
!     .. Local Arrays ..
      Real (Kind=nag_wp)               :: p(0:nlmax)
!     .. Executable Statements ..
      Write (nout,*) 'S22AAF Example Program Results'

!     Skip heading in data file
      Read (nin,*)

      Read (nin,*) mode, x, m, nl

      Write (nout,*)

      ifail = 0
      Call s22aaf(mode,x,m,nl,p,ifail)

      Write (nout,*) 'MODE      X      M    NL'
      Write (nout,*)
      Write (nout,99999) mode, x, m, nl
      Write (nout,*)

      Select Case (mode)
      Case (1)

        If (m==0) Then
          Write (nout,*) 'Unnormalized Legendre function values'
        Else
          Write (nout,*) 'Unnormalized associated Legendre function values'
        End If

      Case (2)

        If (m==0) Then
          Write (nout,*) 'Normalized Legendre function values'
        Else
          Write (nout,*) 'Normalized associated Legendre function values'
        End If

      End Select

      Write (nout,*) ' n      P(n)'

      Do n = 0, nl
        Write (nout,99998) n, p(n)
      End Do

99999 Format (1X,I3,4X,F5.1,2I6)
99998 Format (1X,I2,1X,1P,E12.4)
    End Program s22aafe


s22bafe.f90

    Program s22bafe

!     S22BAF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: nag_wp, s22baf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: a, b, m, x
      Integer                          :: ifail, kx
!     .. Intrinsic Procedures ..
      Intrinsic                        :: real
!     .. Executable Statements ..
      Write (nout,*) 'S22BAF Example Program Results'

      a = 13.6E0_nag_wp
      b = 14.2E0_nag_wp

      Write (nout,99999) 'a    ', 'b    '
      Write (nout,99998)
      Write (nout,99997) a, b
      Write (nout,99998)
      Write (nout,99994) 'x    ', 'M(a,b,x)  ', 'IFAIL    '
      Write (nout,99995)

      Do kx = -5, 5
        x = real(kx,kind=nag_wp) + 0.5E0_nag_wp
        ifail = -1
        Call s22baf(a,b,x,m,ifail)
        Write (nout,99996) x, m, ifail
      End Do

99999 Format (/,2(1X,A14))
99998 Format (2('+--------------'),'+')
99997 Format (2(1X,F13.2,1X))
99996 Format (1X,F10.2,'    ',1X,E13.5,1X,I9)
99995 Format (3('+--------------'),'+')
99994 Format (/,3(1X,A14))
    End Program s22bafe


s22bbfe.f90

    Program s22bbfe

!     S22BBF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: nag_wp, s22bbf, x02bhf, x02blf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: ai, ar, bi, br, delta, frm, scale, x
      Integer                          :: ifail, k, scm
!     .. Local Arrays ..
      Real (Kind=nag_wp)               :: frmv(2)
      Integer                          :: scmv(2)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: real
!     .. Executable Statements ..
      Write (nout,*) 'S22BBF Example Program Results'

      ai = -10.0_nag_wp
      bi = 30.0_nag_wp
      delta = 1.0E-4_nag_wp
      ar = delta
      br = -delta
      x = 25.0_nag_wp

      Write (nout,99999) 'a', 'b', 'x', 'frm', 'scm', 'M(a,b,x)'

      Do k = 1, 2
        If (k==2) Then
          ar = -ar
          br = -br
        End If

        ifail = -1
        Call s22bbf(ai,ar,bi,br,x,frm,scm,ifail)
        If (ifail==2 .Or. ifail>3) Then
!         Either the result has overflowed, no accuracy may be assumed,
!          or an input error has been detected.
          Write (nout,99996) ai + ar, bi + br, x, 'FAILED'
          Go To 100
        Else If (scm<x02blf()) Then
          scale = frm*real(x02bhf(),kind=nag_wp)**scm
          Write (nout,99998) ai + ar, bi + br, x, frm, scm, scale
        Else
          Write (nout,99997) ai + ar, bi + br, x, frm, scm,                    &
            'Not representable'
        End If
        frmv(k) = frm
        scmv(k) = scm
      End Do

!     Calculate the product M1*M2
      frm = frmv(1)*frmv(2)
      scm = scmv(1) + scmv(2)
      Write (nout,*)
      If (scm<x02blf()) Then
        scale = frm*real(x02bhf(),kind=nag_wp)**scm
        Write (nout,99995) 'Solution product', frm, scm, scale
      Else
        Write (nout,99994) 'Solution product', frm, scm, 'Not representable'
      End If

!     Calculate the ratio M1/M2
      If (frmv(2)/=0.0_nag_wp) Then
        frm = frmv(1)/frmv(2)
        scm = scmv(1) - scmv(2)
        Write (nout,*)
        If (scm<x02blf()) Then
          scale = frm*real(x02bhf(),kind=nag_wp)**scm
          Write (nout,99995) 'Solution ratio  ', frm, scm, scale
        Else
          Write (nout,99994) 'Solution ratio  ', frm, scm, 'Not representable'
        End If
      End If

100   Continue

99999 Format (/,1X,3(A10,1X),A12,1X,A6,1X,A12)
99998 Format (1X,3(F10.4,1X),Es12.4,1X,I6,1X,Es12.4)
99997 Format (1X,3(F10.4,1X),Es12.4,1X,I6,1X,A17)
99996 Format (1X,3(F10.4,1X),20X,A17)
99995 Format (1X,A16,17X,Es12.4,1X,I6,1X,Es12.4)
99994 Format (1X,A16,17X,Es12.4,1X,I6,1X,A17)
    End Program s22bbfe


s22befe.f90

    Program s22befe

!     S22BEF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: nag_wp, s22bef
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: a, b, c, f, x
      Integer                          :: ifail, kx
!     .. Intrinsic Procedures ..
      Intrinsic                        :: real
!     .. Executable Statements ..
      Write (nout,*) 'S22BEF Example Program Results'

      a = 1.2E0_nag_wp
      b = -2.6E0_nag_wp
      c = 3.5E0_nag_wp

      Write (nout,*)
      Write (nout,99999)
      Write (nout,99998)
      Write (nout,99997) a, b, c
      Write (nout,*)
      Write (nout,99996)
      Write (nout,99995)

      Do kx = 1, 21
        x = -4.0E0_nag_wp + real(kx-1,kind=nag_wp)*0.25E0_nag_wp
        ifail = 1
        f = s22bef(a,b,c,x,ifail)
        Select Case (ifail)
        Case (0,1,2,3)
          Write (nout,99994) x, f
        Case (4,5,6)
          If (f>=0.0E0_nag_wp) Then
            Write (nout,99993) x, '+Infinity'
          Else
            Write (nout,99993) x, '-Infinity'
          End If
        Case (9)
          Write (nout,99993) x, 'NaN'
        Case Default
          Write (nout,*) 'Illegal parameter: ifail = ', ifail
          Go To 100
        End Select
      End Do

100   Continue

99999 Format (12X,'a',14X,'b',14X,'c')
99998 Format (3('+--------------'),'+')
99997 Format (3(4X,F10.2,1X))
99996 Format (12X,'x',4X,'2F1(a,b;c;x)')
99995 Format (2('+--------------'),'+')
99994 Format (4X,F10.2,5X,F10.4)
99993 Format (4X,F10.2,3X,A13)
    End Program s22befe


s22bffe.f90

    Program s22bffe

!     S22BFF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: nag_wp, s22bff, x02bhf, x02blf, x07caf, x07cbf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: adr, ani, bdr, bni, cdr, cni, delta, &
                                          frf, scale, x
      Integer                          :: ifail, k, scf
      Logical                          :: finite_solutions
!     .. Local Arrays ..
      Real (Kind=nag_wp)               :: frfv(2)
      Integer                          :: exmode(3), scfv(2)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: real
!     .. Executable Statements ..
      Write (nout,*) 'S22BFF Example Program Results'

!     Get current exception mode
      Call x07caf(exmode)
!     Disable exceptions
      Call x07cbf((/0,0,0/))

      finite_solutions = .True.

      ani = -10.0_nag_wp
      bni = 2.0_nag_wp
      cni = -5.0E0_nag_wp
      delta = 1.0E-4_nag_wp
      adr = delta
      bdr = -delta
      cdr = delta
      x = 0.45_nag_wp

      Write (nout,99999) 'a', 'b', 'c', 'x', 'frf', 'scf', ' 2F1(a,b;c;x)'

      Do k = 1, 2

        ifail = 1
        Call s22bff(ani,adr,bni,bdr,cni,cdr,x,frf,scf,ifail)
        Select Case (ifail)
        Case (0,1,2,3)
!         A finite result has been returned.
          If (scf<x02blf()) Then
            scale = frf*2.0E0_nag_wp**scf
            Write (nout,99998) ani + adr, bni + bdr, cni + cdr, x, frf, scf,   &
              scale
          Else
            Write (nout,99997) ani + adr, bni + bdr, cni + cdr, x, frf, scf,   &
              'Not representable'
          End If
        Case (4)
!         The result is analytically infinite.
          finite_solutions = .False.
          If (frf>=0.0E0_nag_wp) Then
            Write (nout,99993) ani + adr, bni + bdr, cni + cdr, x, 'Inf', scf, &
              'Inf'
          Else
            Write (nout,99993) ani + adr, bni + bdr, cni + cdr, x, '-Inf',     &
              scf, '-Inf'
          End If
        Case (5,6)
!         The final result has overflowed.
          finite_solutions = .False.
          If (frf>=0.0E0_nag_wp) Then
            Write (nout,99992) ani + adr, bni + bdr, cni + cdr, x, frf,        &
              'IMAX', '>2**IMAX'
          Else
            Write (nout,99992) ani + adr, bni + bdr, cni + cdr, x, frf,        &
              'IMAX', '<-2**IMAX'
          End If
        Case (9)
!         An internal calculation resulted in a non-finite, non-infinite
!         result.
          finite_solutions = .False.
          Write (nout,99993) ani + adr, bni + bdr, cni + cdr, x, 'NaN', scf,   &
            'NaN'
        Case Default
!         An input error has been detected.
          Write (nout,99996) ani + adr, bni + bdr, cni + cdr, x, 'FAILED'
          Go To 100
        End Select

        frfv(k) = frf
        scfv(k) = scf

        adr = -adr
        bdr = -bdr
        cdr = -cdr

      End Do

      If (finite_solutions) Then
!       Calculate the product M1*M2
        frf = frfv(1)*frfv(2)
        scf = scfv(1) + scfv(2)
        Write (nout,*)
        If (scf<x02blf()) Then
          scale = frf*real(x02bhf(),kind=nag_wp)**scf
          Write (nout,99995) 'Solution product', frf, scf, scale
        Else
          Write (nout,99994) 'Solution product', frf, scf, 'Not representable'
        End If

!       Calculate the ratio M1/M2
        If (frfv(2)/=0.0_nag_wp) Then
          frf = frfv(1)/frfv(2)
          scf = scfv(1) - scfv(2)
          Write (nout,*)
          If (scf<x02blf()) Then
            scale = frf*real(x02bhf(),kind=nag_wp)**scf
            Write (nout,99995) 'Solution ratio  ', frf, scf, scale
          Else
            Write (nout,99994) 'Solution ratio  ', frf, scf,                   &
              'Not representable'
          End If
        End If
      End If

100   Continue
!     Restore exception mode.
      Call x07cbf(exmode)

99999 Format (/,1X,4(A10,1X),A13,1X,A6,1X,A13)
99998 Format (1X,4(F10.4,1X),Es13.5,1X,I6,1X,Es13.5)
99997 Format (1X,4(F10.4,1X),Es13.5,1X,I6,1X,A17)
99996 Format (1X,4(F10.4,1X),20X,A17)
99995 Format (1X,A16,17X,Es13.5,1X,I6,1X,Es13.5)
99994 Format (1X,A16,17X,Es13.5,1X,I6,1X,A17)
99993 Format (1X,4(F10.4,1X),A13,1X,I6,1X,A13)
99992 Format (1X,4(F10.4,1X),Es13.5,1X,A6,1X,A13)

    End Program s22bffe


s30aafe.f90

    Program s30aafe

!     S30AAF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: nag_wp, s30aaf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: q, r, s, sigma
      Integer                          :: i, ifail, j, ldp, m, n
      Character (1)                    :: calput
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: p(:,:), t(:), x(:)
!     .. Executable Statements ..
      Write (nout,*) 'S30AAF Example Program Results'

!     Skip heading in data file
      Read (nin,*)

      Read (nin,*) calput
      Read (nin,*) s, sigma, r, q
      Read (nin,*) m, n

      ldp = m
      Allocate (p(ldp,n),t(n),x(m))

      Read (nin,*)(x(i),i=1,m)
      Read (nin,*)(t(i),i=1,n)

      ifail = 0
      Call s30aaf(calput,m,n,x,s,t,sigma,r,q,p,ldp,ifail)

      Write (nout,*)
      Write (nout,*) 'Black-Scholes-Merton formula'

      Select Case (calput)
      Case ('C','c')
        Write (nout,*) 'European Call :'
      Case ('P','p')
        Write (nout,*) 'European Put :'
      End Select

      Write (nout,99998) '  Spot       = ', s
      Write (nout,99998) '  Volatility = ', sigma
      Write (nout,99998) '  Rate       = ', r
      Write (nout,99998) '  Dividend   = ', q

      Write (nout,*)
      Write (nout,*) '   Strike    Expiry    Option Price'

      Do i = 1, m

        Do j = 1, n
          Write (nout,99999) x(i), t(j), p(i,j)
        End Do

      End Do

99999 Format (1X,2(F9.4,1X),6X,F9.4)
99998 Format (A,1X,F8.4)
    End Program s30aafe


s30abfe.f90

    Program s30abfe

!     S30ABF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: nag_wp, s30abf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: q, r, s, sigma
      Integer                          :: i, ifail, j, ldp, m, n
      Character (1)                    :: calput
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: charm(:,:), colour(:,:), crho(:,:),  &
                                          delta(:,:), gamma(:,:), p(:,:),      &
                                          rho(:,:), speed(:,:), t(:),          &
                                          theta(:,:), vanna(:,:), vega(:,:),   &
                                          vomma(:,:), x(:), zomma(:,:)
!     .. Executable Statements ..
      Write (nout,*) 'S30ABF Example Program Results'

!     Skip heading in data file.
      Read (nin,*)

      Read (nin,*) calput
      Read (nin,*) s, sigma, r, q
      Read (nin,*) m, n

      ldp = m
      Allocate (charm(ldp,n),colour(ldp,n),crho(ldp,n),delta(ldp,n),           &
        gamma(ldp,n),p(ldp,n),rho(ldp,n),speed(ldp,n),t(n),theta(ldp,n),       &
        vanna(ldp,n),vega(ldp,n),vomma(ldp,n),x(m),zomma(ldp,n))

      Read (nin,*)(x(i),i=1,m)
      Read (nin,*)(t(i),i=1,n)

      ifail = 0
      Call s30abf(calput,m,n,x,s,t,sigma,r,q,p,ldp,delta,gamma,vega,theta,rho, &
        crho,vanna,charm,speed,colour,zomma,vomma,ifail)

      Write (nout,*)

      Select Case (calput)
      Case ('C','c')
        Write (nout,*) 'European Call :'
      Case ('P','p')
        Write (nout,*) 'European Put :'
      End Select

      Write (nout,99997) '  Spot       = ', s
      Write (nout,99997) '  Volatility = ', sigma
      Write (nout,99997) '  Rate       = ', r
      Write (nout,99997) '  Dividend   = ', q

      Write (nout,*)

      Do j = 1, n
        Write (nout,*)
        Write (nout,99999) t(j)
        Write (nout,*) '  Strike    Price    Delta    Gamma     Vega    ' //   &
          'Theta      Rho     CRho'

        Do i = 1, m
          Write (nout,99998) x(i), p(i,j), delta(i,j), gamma(i,j), vega(i,j),  &
            theta(i,j), rho(i,j), crho(i,j)
        End Do

        Write (nout,*) '  Strike    Price    Vanna    Charm    Speed   ' //    &
          'Colour    Zomma    Vomma'

        Do i = 1, m
          Write (nout,99998) x(i), p(i,j), vanna(i,j), charm(i,j), speed(i,j), &
            colour(i,j), zomma(i,j), vomma(i,j)
        End Do

      End Do

99999 Format (1X,'Time to Expiry : ',1X,F8.4)
99998 Format (1X,8(F8.4,1X))
99997 Format (A,1X,F8.4)
    End Program s30abfe


s30bafe.f90

    Program s30bafe

!     S30BAF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: nag_wp, s30baf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: q, r, s, sigma
      Integer                          :: i, ifail, j, ldp, m, n
      Character (1)                    :: calput
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: p(:,:), sm(:), t(:)
!     .. Executable Statements ..
      Write (nout,*) 'S30BAF Example Program Results'

!     Skip heading in data file
      Read (nin,*)

      Read (nin,*) calput
      Read (nin,*) s, sigma, r, q
      Read (nin,*) m, n

      ldp = m
      Allocate (p(ldp,n),sm(m),t(n))

      Read (nin,*)(sm(i),i=1,m)
      Read (nin,*)(t(i),i=1,n)

      ifail = 0
      Call s30baf(calput,m,n,sm,s,t,sigma,r,q,p,ldp,ifail)

      Write (nout,*)
      Write (nout,*) 'Floating-strike Lookback'

      Select Case (calput)
      Case ('C','c')
        Write (nout,*) 'European Call :'
      Case ('P','p')
        Write (nout,*) 'European Put :'
      End Select

      Write (nout,99998) '  Spot       = ', s
      Write (nout,99998) '  Volatility = ', sigma
      Write (nout,99998) '  Rate       = ', r
      Write (nout,99998) '  Dividend   = ', q

      Write (nout,*)
      Write (nout,*) '   Strike    Expiry    Option Price'

      Do i = 1, m

        Do j = 1, n
          Write (nout,99999) sm(i), t(j), p(i,j)
        End Do

      End Do

99999 Format (1X,2(F9.4,1X),6X,F9.4)
99998 Format (A,1X,F8.4)
    End Program s30bafe


s30bbfe.f90

    Program s30bbfe

!     S30BBF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: nag_wp, s30bbf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: q, r, s, sigma
      Integer                          :: i, ifail, j, ldp, m, n
      Character (1)                    :: calput
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: charm(:,:), colour(:,:), crho(:,:),  &
                                          delta(:,:), gamma(:,:), p(:,:),      &
                                          rho(:,:), sm(:), speed(:,:), t(:),   &
                                          theta(:,:), vanna(:,:), vega(:,:),   &
                                          vomma(:,:), zomma(:,:)
!     .. Executable Statements ..
      Write (nout,*) 'S30BBF Example Program Results'

!     Skip heading in data file
      Read (nin,*)

      Read (nin,*) calput
      Read (nin,*) s, sigma, r, q
      Read (nin,*) m, n

      ldp = m
      Allocate (charm(ldp,n),colour(ldp,n),crho(ldp,n),delta(ldp,n),           &
        gamma(ldp,n),p(ldp,n),rho(ldp,n),sm(m),speed(ldp,n),t(n),theta(ldp,n), &
        vanna(ldp,n),vega(ldp,n),vomma(ldp,n),zomma(ldp,n))

      Read (nin,*)(sm(i),i=1,m)
      Read (nin,*)(t(i),i=1,n)

      ifail = 0
      Call s30bbf(calput,m,n,sm,s,t,sigma,r,q,p,ldp,delta,gamma,vega,theta,    &
        rho,crho,vanna,charm,speed,colour,zomma,vomma,ifail)

      Write (nout,*)
      Write (nout,*) 'Floating-Strike Lookback'

      Select Case (calput)
      Case ('C','c')
        Write (nout,*) 'European Call :'
      Case ('P','p')
        Write (nout,*) 'European Put :'
      End Select

      Write (nout,99997) '  Spot       = ', s
      Write (nout,99997) '  Volatility = ', sigma
      Write (nout,99997) '  Rate       = ', r
      Write (nout,99997) '  Dividend   = ', q

      Write (nout,*)

      Do j = 1, n
        Write (nout,*)
        Write (nout,99999) t(j)
        Write (nout,*) 'S-Max/Min     Price     Delta     Gamma' //            &
          '      Vega      Theta      Rho      CRho'

        Do i = 1, m
          Write (nout,99998) sm(i), p(i,j), delta(i,j), gamma(i,j), vega(i,j), &
            theta(i,j), rho(i,j), crho(i,j)
        End Do

        Write (nout,*) 'S-Max/Min     Price     Vanna     Charm' //            &
          '     Speed     Colour    Zomma     Vomma'

        Do i = 1, m
          Write (nout,99998) sm(i), p(i,j), vanna(i,j), charm(i,j),            &
            speed(i,j), colour(i,j), zomma(i,j), vomma(i,j)
        End Do

      End Do

99999 Format (1X,'Time to Expiry : ',1X,F8.4)
99998 Format (8(1X,F9.4))
99997 Format (A,1X,F8.4)
    End Program s30bbfe


s30cafe.f90

    Program s30cafe

!     S30CAF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: nag_wp, s30caf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: k, q, r, s, sigma
      Integer                          :: i, ifail, j, ldp, m, n
      Character (1)                    :: calput
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: p(:,:), t(:), x(:)
!     .. Executable Statements ..
      Write (nout,*) 'S30CAF Example Program Results'

!     Skip heading in data file
      Read (nin,*)

      Read (nin,*) calput
      Read (nin,*) s, k, sigma, r, q
      Read (nin,*) m, n

      ldp = m
      Allocate (p(ldp,n),t(n),x(m))

      Read (nin,*)(x(i),i=1,m)
      Read (nin,*)(t(i),i=1,n)

      ifail = 0
      Call s30caf(calput,m,n,x,s,k,t,sigma,r,q,p,ldp,ifail)

      Write (nout,*)
      Write (nout,*) 'Binary (Digital): Cash-or-Nothing'

      Select Case (calput)
      Case ('C','c')
        Write (nout,*) 'European Call :'
      Case ('P','p')
        Write (nout,*) 'European Put :'
      End Select

      Write (nout,99998) '  Spot       = ', s
      Write (nout,99998) '  Payout     = ', k
      Write (nout,99998) '  Volatility = ', sigma
      Write (nout,99998) '  Rate       = ', r
      Write (nout,99998) '  Dividend   = ', q

      Write (nout,*)
      Write (nout,*) '  Strike     Expiry    Option Price'

      Do i = 1, m

        Do j = 1, n
          Write (nout,99999) x(i), t(j), p(i,j)
        End Do

      End Do

99999 Format (1X,2(F9.4,1X),6X,F9.4)
99998 Format (A,1X,F8.4)
    End Program s30cafe


s30cbfe.f90

    Program s30cbfe

!     S30CBF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: nag_wp, s30cbf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: k, q, r, s, sigma
      Integer                          :: i, ifail, j, ldp, m, n
      Character (1)                    :: calput
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: charm(:,:), colour(:,:), crho(:,:),  &
                                          delta(:,:), gamma(:,:), p(:,:),      &
                                          rho(:,:), speed(:,:), t(:),          &
                                          theta(:,:), vanna(:,:), vega(:,:),   &
                                          vomma(:,:), x(:), zomma(:,:)
!     .. Executable Statements ..
      Write (nout,*) 'S30CBF Example Program Results'

!     Skip heading in data file
      Read (nin,*)

      Read (nin,*) calput
      Read (nin,*) s, k, sigma, r, q
      Read (nin,*) m, n

      ldp = m
      Allocate (charm(ldp,n),colour(ldp,n),crho(ldp,n),delta(ldp,n),           &
        gamma(ldp,n),p(ldp,n),rho(ldp,n),speed(ldp,n),t(n),theta(ldp,n),       &
        vanna(ldp,n),vega(ldp,n),vomma(ldp,n),x(m),zomma(ldp,n))

      Read (nin,*)(x(i),i=1,m)
      Read (nin,*)(t(i),i=1,n)

      ifail = 0
      Call s30cbf(calput,m,n,x,s,k,t,sigma,r,q,p,ldp,delta,gamma,vega,theta,   &
        rho,crho,vanna,charm,speed,colour,zomma,vomma,ifail)

      Write (nout,*)
      Write (nout,*) 'Binary (Digital): Cash-or-Nothing'

      Select Case (calput)
      Case ('C','c')
        Write (nout,*) 'European Call :'
      Case ('P','p')
        Write (nout,*) 'European Put :'
      End Select

      Write (nout,99997) '  Spot       = ', s
      Write (nout,99997) '  Payout     = ', k
      Write (nout,99997) '  Volatility = ', sigma
      Write (nout,99997) '  Rate       = ', r
      Write (nout,99997) '  Dividend   = ', q

      Write (nout,*)

      Do j = 1, n
        Write (nout,*)
        Write (nout,99999) t(j)
        Write (nout,*) '  Strike    Price    Delta    Gamma     Vega    Theta' &
          // '     Rho      CRho'

        Do i = 1, m
          Write (nout,99998) x(i), p(i,j), delta(i,j), gamma(i,j), vega(i,j),  &
            theta(i,j), rho(i,j), crho(i,j)
        End Do

        Write (nout,*)                                                         &
          '  Strike    Price    Vanna    Charm    Speed   Colour    Zomma' //  &
          '    Vomma'

        Do i = 1, m
          Write (nout,99998) x(i), p(i,j), vanna(i,j), charm(i,j), speed(i,j), &
            colour(i,j), zomma(i,j), vomma(i,j)
        End Do

      End Do

99999 Format (1X,'Time to Expiry : ',1X,F8.4)
99998 Format (1X,8(F8.4,1X))
99997 Format (A,1X,F8.4)
    End Program s30cbfe


s30ccfe.f90

    Program s30ccfe

!     S30CCF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: nag_wp, s30ccf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: q, r, s, sigma
      Integer                          :: i, ifail, j, ldp, m, n
      Character (1)                    :: calput
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: p(:,:), t(:), x(:)
!     .. Executable Statements ..
      Write (nout,*) 'S30CCF Example Program Results'

!     Skip heading in data file
      Read (nin,*)

      Read (nin,*) calput
      Read (nin,*) s, sigma, r, q
      Read (nin,*) m, n

      ldp = m
      Allocate (p(ldp,n),t(n),x(m))

      Read (nin,*)(x(i),i=1,m)
      Read (nin,*)(t(i),i=1,n)

      ifail = 0
      Call s30ccf(calput,m,n,x,s,t,sigma,r,q,p,ldp,ifail)

      Write (nout,*)
      Write (nout,*) 'Binary (Digital): Asset-or-Nothing'

      Select Case (calput)
      Case ('C','c')
        Write (nout,*) 'European Call :'
      Case ('P','p')
        Write (nout,*) 'European Put :'
      End Select

      Write (nout,99998) '  Spot       = ', s
      Write (nout,99998) '  Volatility = ', sigma
      Write (nout,99998) '  Rate       = ', r
      Write (nout,99998) '  Dividend   = ', q

      Write (nout,*)
      Write (nout,*) '   Strike    Expiry    Option Price'

      Do i = 1, m

        Do j = 1, n
          Write (nout,99999) x(i), t(j), p(i,j)
        End Do

      End Do

99999 Format (1X,2(F9.4,1X),6X,F9.4)
99998 Format (A,1X,F8.4)
    End Program s30ccfe


s30cdfe.f90

    Program s30cdfe

!     S30CDF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: nag_wp, s30cdf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: q, r, s, sigma
      Integer                          :: i, ifail, j, ldp, m, n
      Character (1)                    :: calput
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: charm(:,:), colour(:,:), crho(:,:),  &
                                          delta(:,:), gamma(:,:), p(:,:),      &
                                          rho(:,:), rhoq(:,:), speed(:,:),     &
                                          t(:), theta(:,:), vanna(:,:),        &
                                          vega(:,:), vomma(:,:), x(:),         &
                                          zomma(:,:)
!     .. Executable Statements ..
      Write (nout,*) 'S30CDF Example Program Results'

!     Skip heading in data file
      Read (nin,*)

      Read (nin,*) calput
      Read (nin,*) s, sigma, r, q
      Read (nin,*) m, n

      ldp = m
      Allocate (charm(ldp,n),colour(ldp,n),crho(ldp,n),delta(ldp,n),           &
        gamma(ldp,n),p(ldp,n),rho(ldp,n),rhoq(ldp,n),speed(ldp,n),t(n),        &
        theta(ldp,n),vanna(ldp,n),vega(ldp,n),vomma(ldp,n),x(m),zomma(ldp,n))

      Read (nin,*)(x(i),i=1,m)
      Read (nin,*)(t(i),i=1,n)

      ifail = 0
      Call s30cdf(calput,m,n,x,s,t,sigma,r,q,p,ldp,delta,gamma,vega,theta,rho, &
        rhoq,vanna,charm,speed,colour,zomma,vomma,ifail)

      Write (nout,*)
      Write (nout,*) 'Binary (Digital): Asset-or-Nothing'

      Select Case (calput)
      Case ('C','c')
        Write (nout,*) 'European Call :'
      Case ('P','p')
        Write (nout,*) 'European Put :'
      End Select

      Write (nout,99997) '  Spot       = ', s
      Write (nout,99997) '  Volatility = ', sigma
      Write (nout,99997) '  Rate       = ', r
      Write (nout,99997) '  Dividend   = ', q

      Write (nout,*)

      Do j = 1, n
        Write (nout,*)
        Write (nout,99999) t(j)
        Write (nout,*) '   Strike     Price     Delta     Gamma      Vega' //  &
          '     Theta       Rho      CRho'

        Do i = 1, m
          Write (nout,99998) x(i), p(i,j), delta(i,j), gamma(i,j), vega(i,j),  &
            theta(i,j), rho(i,j), rhoq(i,j)
        End Do

        Write (nout,*) '   Strike     Price     Vanna     Charm     Speed' //  &
          '    Colour     Zomma     Vomma'

        Do i = 1, m
          Write (nout,99998) x(i), p(i,j), vanna(i,j), charm(i,j), speed(i,j), &
            colour(i,j), zomma(i,j), vomma(i,j)
        End Do

      End Do

99999 Format (1X,'Time to Expiry : ',1X,F8.4)
99998 Format (8(1X,F9.4))
99997 Format (A,1X,F8.4)
    End Program s30cdfe


s30fafe.f90

    Program s30fafe

!     S30FAF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: nag_wp, s30faf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: h, k, q, r, s, sigma
      Integer                          :: i, ifail, j, ldp, m, n
      Character (1)                    :: calput
      Character (2)                    :: type
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: p(:,:), t(:), x(:)
!     .. Executable Statements ..
      Write (nout,*) 'S30FAF Example Program Results'

!     Skip heading in data file
      Read (nin,*)

      Read (nin,*) calput, type
      Read (nin,*) s, h, k, sigma, r, q
      Read (nin,*) m, n

      ldp = m
      Allocate (p(ldp,n),t(n),x(m))

      Read (nin,*)(x(i),i=1,m)
      Read (nin,*)(t(i),i=1,n)

      ifail = 0
      Call s30faf(calput,type,m,n,x,s,h,k,t,sigma,r,q,p,ldp,ifail)

      Write (nout,*)
      Write (nout,*) 'Standard Barrier Option'

      Select Case (calput)
      Case ('C','c')
        Write (nout,*) 'Call :'
      Case ('P','p')
        Write (nout,*) 'Put :'
      End Select

      Select Case (type)
      Case ('DI','di','Di','dI')
        Write (nout,*) 'Down-and-In'
      Case ('DO','do','Do','dO')
        Write (nout,*) 'Down-and-Out'
      Case ('UI','ui','Ui','uI')
        Write (nout,*) 'Up-and-In'
      Case ('UO','uo','Uo','uO')
        Write (nout,*) 'Up-and-Out'
      End Select

      Write (nout,99998) '  Spot       = ', s
      Write (nout,99998) '  Barrier    = ', h
      Write (nout,99998) '  Rebate     = ', k
      Write (nout,99998) '  Volatility = ', sigma
      Write (nout,99998) '  Rate       = ', r
      Write (nout,99998) '  Dividend   = ', q

      Write (nout,*)
      Write (nout,*) '   Strike    Expiry    Option Price'

      Do i = 1, m

        Do j = 1, n
          Write (nout,99999) x(i), t(j), p(i,j)
        End Do

      End Do

99999 Format (1X,2(F9.4,1X),6X,F9.4)
99998 Format (A,1X,F8.4)
    End Program s30fafe


s30jafe.f90

    Program s30jafe

!     S30JAF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: nag_wp, s30jaf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: jvol, lambda, r, s, sigma
      Integer                          :: i, ifail, j, ldp, m, n
      Character (1)                    :: calput
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: p(:,:), t(:), x(:)
!     .. Executable Statements ..
      Write (nout,*) 'S30JAF Example Program Results'

!     Skip heading in data file
      Read (nin,*)

      Read (nin,*) calput
      Read (nin,*) lambda
      Read (nin,*) s, sigma, r, jvol
      Read (nin,*) m, n

      ldp = m
      Allocate (p(ldp,n),t(n),x(m))

      Read (nin,*)(x(i),i=1,m)
      Read (nin,*)(t(i),i=1,n)

      ifail = 0
      Call s30jaf(calput,m,n,x,s,t,sigma,r,lambda,jvol,p,ldp,ifail)

      Write (nout,*)
      Write (nout,*) 'Merton Jump-Diffusion Model'

      Select Case (calput)
      Case ('C','c')
        Write (nout,*) 'European Call :'
      Case ('P','p')
        Write (nout,*) 'European Put :'
      End Select

      Write (nout,99998) '  Spot       = ', s
      Write (nout,99998) '  Volatility = ', sigma
      Write (nout,99998) '  Rate       = ', r
      Write (nout,99998) '  Jumps      = ', lambda
      Write (nout,99998) '  Jump vol   = ', jvol

      Write (nout,*)
      Write (nout,*) '   Strike    Expiry    Option Price'

      Do i = 1, m

        Do j = 1, n
          Write (nout,99999) x(i), t(j), p(i,j)
        End Do

      End Do

99999 Format (1X,2(F9.4,1X),6X,F9.4)
99998 Format (A,1X,F8.4)
    End Program s30jafe


s30jbfe.f90

    Program s30jbfe

!     S30JBF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: nag_wp, s30jbf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: jvol, lambda, r, s, sigma
      Integer                          :: i, ifail, j, ldp, m, n
      Character (1)                    :: calput
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: charm(:,:), colour(:,:), crho(:,:),  &
                                          delta(:,:), gamma(:,:), p(:,:),      &
                                          rho(:,:), speed(:,:), t(:),          &
                                          theta(:,:), vanna(:,:), vega(:,:),   &
                                          vomma(:,:), x(:), zomma(:,:)
!     .. Executable Statements ..
      Write (nout,*) 'S30JBF Example Program Results'

!     Skip heading in data file
      Read (nin,*)

      Read (nin,*) calput
      Read (nin,*) lambda
      Read (nin,*) s, sigma, r, jvol
      Read (nin,*) m, n

      ldp = m
      Allocate (charm(ldp,n),colour(ldp,n),crho(ldp,n),delta(ldp,n),           &
        gamma(ldp,n),p(ldp,n),rho(ldp,n),speed(ldp,n),t(n),theta(ldp,n),       &
        vanna(ldp,n),vega(ldp,n),vomma(ldp,n),x(m),zomma(ldp,n))

      Read (nin,*)(x(i),i=1,m)
      Read (nin,*)(t(i),i=1,n)

      ifail = 0

      Call s30jbf(calput,m,n,x,s,t,sigma,r,lambda,jvol,p,ldp,delta,gamma,vega, &
        theta,rho,vanna,charm,speed,colour,zomma,vomma,ifail)

      Write (nout,*)
      Write (nout,*) 'Merton Jump-Diffusion Model'

      Select Case (calput)
      Case ('C','c')
        Write (nout,*) 'European Call :'
      Case ('P','p')
        Write (nout,*) 'European Put :'
      End Select

      Write (nout,99996) '  Spot       = ', s
      Write (nout,99996) '  Volatility = ', sigma
      Write (nout,99996) '  Rate       = ', r
      Write (nout,99996) '  Jumps      = ', lambda
      Write (nout,99996) '  Jump vol   = ', jvol

      Write (nout,*)

      Do j = 1, n
        Write (nout,*)
        Write (nout,99999) t(j)
        Write (nout,*) '  Strike    Price    Delta    Gamma     Vega    Theta' &
          // '      Rho'

        Do i = 1, m
          Write (nout,99998) x(i), p(i,j), delta(i,j), gamma(i,j), vega(i,j),  &
            theta(i,j), rho(i,j)
        End Do

        Write (nout,*)                                                         &
          '  Strike    Price    Vanna    Charm    Speed   Colour    Zomma' //  &
          '    Vomma'

        Do i = 1, m
          Write (nout,99997) x(i), p(i,j), vanna(i,j), charm(i,j), speed(i,j), &
            colour(i,j), zomma(i,j), vomma(i,j)
        End Do

      End Do

99999 Format (1X,'Time to Expiry : ',1X,F8.4)
99998 Format (1X,7(F8.4,1X))
99997 Format (1X,8(F8.4,1X))
99996 Format (A,1X,F8.4)
    End Program s30jbfe


s30nafe.f90

    Program s30nafe

!     S30NAF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: nag_wp, s30naf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: corr, eta, grisk, kappa, q, r, s,    &
                                          sigmav, var0
      Integer                          :: i, ifail, j, ldp, m, n
      Character (1)                    :: calput
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: p(:,:), t(:), x(:)
!     .. Executable Statements ..
      Write (nout,*) 'S30NAF Example Program Results'

!     Skip heading in data file
      Read (nin,*)

      Read (nin,*) calput
      Read (nin,*) s, r, q
      Read (nin,*) kappa, eta, var0, sigmav, corr, grisk
      Read (nin,*) m, n

      ldp = m
      Allocate (p(ldp,n),t(n),x(m))

      Read (nin,*)(x(i),i=1,m)
      Read (nin,*)(t(i),i=1,n)

      ifail = 0
      Call s30naf(calput,m,n,x,s,t,sigmav,kappa,corr,var0,eta,grisk,r,q,p,ldp, &
        ifail)

      Write (nout,*)
      Write (nout,*) 'Heston''s Stochastic volatility Model'

      Select Case (calput)
      Case ('C','c')
        Write (nout,*) 'European Call :'
      Case ('P','p')
        Write (nout,*) 'European Put :'
      End Select

      Write (nout,99998) '  Spot                   = ', s
      Write (nout,99998) '  Volatility of vol      = ', sigmav
      Write (nout,99998) '  Mean reversion         = ', kappa
      Write (nout,99998) '  Correlation            = ', corr
      Write (nout,99998) '  Variance               = ', var0
      Write (nout,99998) '  Mean of variance       = ', eta
      Write (nout,99998) '  Risk aversion          = ', grisk
      Write (nout,99998) '  Rate                   = ', r
      Write (nout,99998) '  Dividend               = ', q

      Write (nout,*)
      Write (nout,*) '   Strike    Expiry    Option Price'

      Do i = 1, m

        Do j = 1, n
          Write (nout,99999) x(i), t(j), p(i,j)
        End Do

      End Do

99999 Format (1X,2(F9.4,1X),6X,F9.4)
99998 Format (A,1X,F8.4)
    End Program s30nafe


s30nbfe.f90

    Program s30nbfe

!     S30NBF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: nag_wp, s30nbf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: corr, eta, grisk, kappa, q, r, s,    &
                                          sigmav, var0
      Integer                          :: i, ifail, j, ldp, m, n
      Character (1)                    :: calput
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: charm(:,:), delta(:,:), gamma(:,:),  &
                                          p(:,:), rho(:,:), speed(:,:), t(:),  &
                                          theta(:,:), vanna(:,:), vega(:,:),   &
                                          vomma(:,:), x(:), zomma(:,:)
!     .. Executable Statements ..
      Write (nout,*) 'S30NBF Example Program Results'

!     Skip heading in data file
      Read (nin,*)

      Read (nin,*) calput
      Read (nin,*) s, r, q
      Read (nin,*) kappa, eta, var0, sigmav, corr, grisk
      Read (nin,*) m, n

      ldp = m
      Allocate (charm(ldp,n),delta(ldp,n),gamma(ldp,n),p(ldp,n),rho(ldp,n),    &
        speed(ldp,n),t(n),theta(ldp,n),vanna(ldp,n),vega(ldp,n),vomma(ldp,n),  &
        x(m),zomma(ldp,n))

      Read (nin,*)(x(i),i=1,m)
      Read (nin,*)(t(i),i=1,n)

      ifail = 0
      Call s30nbf(calput,m,n,x,s,t,sigmav,kappa,corr,var0,eta,grisk,r,q,p,ldp, &
        delta,gamma,vega,theta,rho,vanna,charm,speed,zomma,vomma,ifail)

      Write (nout,*)
      Write (nout,*) 'Heston''s Stochastic volatility Model'

      Select Case (calput)
      Case ('C','c')
        Write (nout,*) 'European Call :'
      Case ('P','p')
        Write (nout,*) 'European Put :'
      End Select

      Write (nout,99997) '  Spot                   = ', s
      Write (nout,99997) '  Volatility of vol      = ', sigmav
      Write (nout,99997) '  Mean reversion         = ', kappa
      Write (nout,99997) '  Correlation            = ', corr
      Write (nout,99997) '  Variance               = ', var0
      Write (nout,99997) '  Mean of variance       = ', eta
      Write (nout,99997) '  Risk aversion          = ', grisk
      Write (nout,99997) '  Rate                   = ', r
      Write (nout,99997) '  Dividend               = ', q

      Write (nout,*)

      Do j = 1, n
        Write (nout,*)
        Write (nout,99999) t(j)
        Write (nout,*)                                                         &
          '  Strike       Price      Delta      Gamma      Vega       ' //     &
          'Theta      Rho'

        Do i = 1, m
          Write (nout,99998) x(i), p(i,j), delta(i,j), gamma(i,j), vega(i,j),  &
            theta(i,j), rho(i,j)
        End Do

        Write (nout,*)                                                         &
          '  Strike       Price      Vanna      Charm      Speed      ' //     &
          'Zomma      Vomma'

        Do i = 1, m
          Write (nout,99998) x(i), p(i,j), vanna(i,j), charm(i,j), speed(i,j), &
            zomma(i,j), vomma(i,j)
        End Do

      End Do

99999 Format (1X,'Time to Expiry : ',1X,F8.4)
99998 Format (1X,7(F10.4,1X))
99997 Format (A,1X,F10.4)
    End Program s30nbfe


s30ncfe.f90

    Program s30ncfe

!      S30NCF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: s30ncf
      Use nag_precisions, Only: wp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=wp)                   :: disc, fwd, t, var0
      Integer                          :: i, ifail, m, numts
      Character (1)                    :: calput
!     .. Local Arrays ..
      Real (Kind=wp), Allocatable      :: alpha(:), corr(:), lambda(:), p(:),  &
                                          sigmat(:), ts(:), x(:)
!     .. Executable Statements ..
      Write (nout,*) 'S30NCF Example Program Results'

!     Skip heading in data file

      Read (nin,*)

      Read (nin,*) calput
      Read (nin,*) m, numts

      Allocate (p(m),ts(numts),x(m),alpha(numts),corr(numts),lambda(numts),    &
        sigmat(numts))

      Read (nin,*) fwd, disc, var0
      Read (nin,*) x(1:m)
      Read (nin,*) ts(1:numts)
      Read (nin,*) t
      Read (nin,*) alpha(1:numts)
      Read (nin,*) corr(1:numts)
      Read (nin,*) lambda(1:numts)
      Read (nin,*) sigmat(1:numts)

      ifail = 0
      Call s30ncf(calput,m,numts,x,fwd,disc,ts,t,alpha,lambda,corr,sigmat,     &
        var0,p,ifail)

      If (ifail/=0) Then
        Go To 100
      End If

      Write (nout,*)
      Write (nout,*)                                                           &
        'Heston''s Stochastic volatility Model with Term Structure'

      Select Case (calput)
      Case ('C','c')
        Write (nout,*) 'European Call :'
      Case ('P','p')
        Write (nout,*) 'European Put :'
      End Select

      Write (nout,99998) '  Forward                = ', fwd
      Write (nout,99998) '  Discount Factor        = ', disc
      Write (nout,99998) '  Variance               = ', var0

      Write (nout,*) '   ts        alpha     lambda    corr      sigmat'
      Do i = 1, numts
        Write (nout,99997) ts(i), alpha(i), lambda(i), corr(i), sigmat(i)
      End Do

      Write (nout,*)
      Write (nout,*) '   Strike    Expiry       Option Price'

      Do i = 1, m
        Write (nout,99999) x(i), t, p(i)
      End Do

100   Continue

99999 Format (1X,2(F9.4,1X),3X,F9.4)
99998 Format (A,1X,F8.4)
99997 Format (1X,5(F9.4,1X))
    End Program s30ncfe


s30qcfe.f90

    Program s30qcfe

!     S30QCF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: nag_wp, s30qcf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: q, r, s, sigma
      Integer                          :: i, ifail, j, ldp, m, n
      Character (1)                    :: calput
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: p(:,:), t(:), x(:)
!     .. Executable Statements ..
      Write (nout,*) 'S30QCF Example Program Results'

!     Skip heading in data file
      Read (nin,*)

      Read (nin,*) calput
      Read (nin,*) s, sigma, r, q
      Read (nin,*) m, n

      ldp = m
      Allocate (p(ldp,n),t(n),x(m))

      Read (nin,*)(x(i),i=1,m)
      Read (nin,*)(t(i),i=1,n)

      ifail = 0
      Call s30qcf(calput,m,n,x,s,t,sigma,r,q,p,ldp,ifail)

      Write (nout,*)

      Select Case (calput)
      Case ('C','c')
        Write (nout,*) 'American Call :'
      Case ('P','p')
        Write (nout,*) 'American Put :'
      End Select

      Write (nout,99998) '  Spot       = ', s
      Write (nout,99998) '  Volatility = ', sigma
      Write (nout,99998) '  Rate       = ', r
      Write (nout,99998) '  Dividend   = ', q

      Write (nout,*)
      Write (nout,*) '   Strike    Expiry    Option Price'

      Do i = 1, m

        Do j = 1, n
          Write (nout,99999) x(i), t(j), p(i,j)
        End Do

      End Do

99999 Format (1X,2(F9.4,1X),6X,F9.4)
99998 Format (A,1X,F8.4)
    End Program s30qcfe


s30safe.f90

    Program s30safe

!     S30SAF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: nag_wp, s30saf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: b, r, s, sigma
      Integer                          :: i, ifail, j, ldp, m, n
      Character (1)                    :: calput
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: p(:,:), t(:), x(:)
!     .. Executable Statements ..
      Write (nout,*) 'S30SAF Example Program Results'

!     Skip heading in data file
      Read (nin,*)

      Read (nin,*) calput
      Read (nin,*) s, sigma, r, b
      Read (nin,*) m, n

      ldp = m
      Allocate (p(ldp,n),t(n),x(m))

      Read (nin,*)(x(i),i=1,m)
      Read (nin,*)(t(i),i=1,n)

      ifail = 0
      Call s30saf(calput,m,n,x,s,t,sigma,r,b,p,ldp,ifail)

      Write (nout,*)
      Write (nout,*) 'Asian Option: Geometric Continuous Average-Rate'

      Select Case (calput)
      Case ('C','c')
        Write (nout,*) 'Asian Call :'
      Case ('P','p')
        Write (nout,*) 'Asian Put :'
      End Select

      Write (nout,99998) '  Spot          = ', s
      Write (nout,99998) '  Volatility    = ', sigma
      Write (nout,99998) '  Rate          = ', r
      Write (nout,99998) '  Cost of carry = ', b

      Write (nout,*)
      Write (nout,*) '   Strike    Expiry    Option Price'

      Do i = 1, m

        Do j = 1, n
          Write (nout,99999) x(i), t(j), p(i,j)
        End Do

      End Do

99999 Format (1X,2(F9.4,1X),6X,F9.4)
99998 Format (A,1X,F8.4)
    End Program s30safe


s30sbfe.f90

    Program s30sbfe

!     S30SBF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: nag_wp, s30sbf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: b, r, s, sigma
      Integer                          :: i, ifail, j, ldp, m, n
      Character (1)                    :: calput
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: charm(:,:), colour(:,:), crho(:,:),  &
                                          delta(:,:), gamma(:,:), p(:,:),      &
                                          rho(:,:), speed(:,:), t(:),          &
                                          theta(:,:), vanna(:,:), vega(:,:),   &
                                          vomma(:,:), x(:), zomma(:,:)
!     .. Executable Statements ..
      Write (nout,*) 'S30SBF Example Program Results'

!     Skip heading in data file
      Read (nin,*)

      Read (nin,*) calput
      Read (nin,*) s, sigma, r, b
      Read (nin,*) m, n

      ldp = m
      Allocate (charm(ldp,n),colour(ldp,n),crho(ldp,n),delta(ldp,n),           &
        gamma(ldp,n),p(ldp,n),rho(ldp,n),speed(ldp,n),t(n),theta(ldp,n),       &
        vanna(ldp,n),vega(ldp,n),vomma(ldp,n),x(m),zomma(ldp,n))

      Read (nin,*)(x(i),i=1,m)
      Read (nin,*)(t(i),i=1,n)

      ifail = 0
      Call s30sbf(calput,m,n,x,s,t,sigma,r,b,p,ldp,delta,gamma,vega,theta,rho, &
        crho,vanna,charm,speed,colour,zomma,vomma,ifail)

      Write (nout,*)
      Write (nout,*) 'Asian Option: Geometric Continuous Average-Rate'

      Select Case (calput)
      Case ('C','c')
        Write (nout,*) 'Asian Call :'
      Case ('P','p')
        Write (nout,*) 'Asian Put :'
      End Select

      Write (nout,99997) '  Spot          = ', s
      Write (nout,99997) '  Volatility    = ', sigma
      Write (nout,99997) '  Rate          = ', r
      Write (nout,99997) '  Cost of carry = ', b

      Write (nout,*)

      Do j = 1, n
        Write (nout,*)
        Write (nout,99999) t(j)
        Write (nout,*)                                                         &
          '  Strike    Price    Delta    Gamma     Vega     Theta     Rho' //  &
          '     CRho'

        Do i = 1, m
          Write (nout,99998) x(i), p(i,j), delta(i,j), gamma(i,j), vega(i,j),  &
            theta(i,j), rho(i,j), crho(i,j)
        End Do

        Write (nout,*)                                                         &
          '  Strike    Price    Vanna    Charm    Speed    Colour   Zomma' //  &
          '    Vomma'

        Do i = 1, m
          Write (nout,99998) x(i), p(i,j), vanna(i,j), charm(i,j), speed(i,j), &
            colour(i,j), zomma(i,j), vomma(i,j)
        End Do

      End Do

99999 Format (1X,'Time to Expiry : ',1X,F8.4)
99998 Format (1X,8(F8.4,1X))
99997 Format (A,1X,F8.4)
    End Program s30sbfe


x02ajfe.f90

    Program x02ajfe

!     X02AJF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: nag_wp, x02ahf, x02ajf, x02akf, x02alf, x02amf,   &
                             x02anf, x02bbf, x02bef, x02bhf, x02bjf, x02bkf,   &
                             x02blf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: largest_arg, largest_pos, machpr,    &
                                          safe_complex, safe_real,             &
                                          smallest_pos
      Integer                          :: largest_pos_int, model_b,            &
                                          model_emax, model_emin, model_p,     &
                                          prec
!     .. Executable Statements ..
      Write (nout,*) 'X02AJF Example Program Results'
      Write (nout,*)
      Write (nout,*) '(results are machine-dependent)'
      Write (nout,*)
      Write (nout,*) 'The basic parameters of the model'
      Write (nout,*)
      model_b = x02bhf()
      Write (nout,99999) ' X02BHF = ', model_b, '  (the model parameter B)'
      model_p = x02bjf()
      Write (nout,99999) ' X02BJF = ', model_p, '  (the model parameter P)'
      model_emin = x02bkf()
      Write (nout,99999) ' X02BKF = ', model_emin,                             &
        '  (the model parameter EMIN)'
      model_emax = x02blf()
      Write (nout,99999) ' X02BLF = ', model_emax,                             &
        '  (the model parameter EMAX)'
      Write (nout,*)
      Write (nout,*) 'Derived parameters of floating-point arithmetic'
      Write (nout,*)
      machpr = x02ajf()
      Write (nout,99998) ' X02AJF = ', machpr, '  (the machine precision)'
      smallest_pos = x02akf()
      Write (nout,99998) ' X02AKF = ', smallest_pos,                           &
        '  (the smallest positive model number)'
      largest_pos = x02alf()
      Write (nout,99998) ' X02ALF = ', largest_pos,                            &
        '  (the largest positive model number)'
      safe_real = x02amf()
      Write (nout,99998) ' X02AMF = ', safe_real,                              &
        '  (the real safe range parameter)'
      safe_complex = x02anf()
      Write (nout,99998) ' X02ANF = ', safe_complex,                           &
        '  (the complex safe range parameter)'
      Write (nout,*)
      Write (nout,*)                                                           &
        'Parameters of other aspects of the computing environment'
      Write (nout,*)
      largest_arg = x02ahf(0.0E0_nag_wp)
      Write (nout,99996) ' X02AHF = ', largest_arg,                            &
        '  (largest argument for SIN and COS)'
      largest_pos_int = x02bbf(0.0E0_nag_wp)
      Write (nout,99997) ' X02BBF = ', largest_pos_int,                        &
        '  (largest positive integer)'
      prec = x02bef(0.0E0_nag_wp)
      Write (nout,99997) ' X02BEF = ', prec, '  (precision in decimal digits)'

99999 Format (1X,A,I7,1X,A)
99998 Format (1X,A,1P,E26.18e3,1X,A)
99997 Format (1X,A,I20,1X,A)
99996 Format (1X,A,1P,E20.8e3,1X,A)
    End Program x02ajfe


x03aafe.f90

    Program x03aafe

!     X03AAF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: nag_wp, x03aaf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: n = 3, nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: c1, c2, d1, d2
      Integer                          :: i, ifail, isizea, isizeb, istepa,    &
                                          istepb, j
      Logical                          :: sw
!     .. Local Arrays ..
      Real (Kind=nag_wp)               :: a(n,n), b(n)
!     .. Executable Statements ..
      Write (nout,*) 'X03AAF Example Program Results'

!     Skip heading in data file
      Read (nin,*)

      Read (nin,*)((a(i,j),j=1,n),i=1,n), (b(i),i=1,n)
      c1 = 1.0E0_nag_wp
      c2 = 0.0E0_nag_wp
      isizea = n
      isizeb = n
      istepa = 1
      istepb = 1
      sw = .True.

      ifail = 0
      Call x03aaf(a(1,2),isizea,b,isizeb,n,istepa,istepb,c1,c2,d1,d2,sw,ifail)

      Write (nout,*)
      Write (nout,99999) 'D1 = ', d1, ' D2 = ', d2

99999 Format (1X,A,F4.1,A,F4.1)
    End Program x03aafe


x03abfe.f90

    Program x03abfe

!     X03ABF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: nag_wp, x03abf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: n = 3, nin = 5, nout = 6
!     .. Local Scalars ..
      Complex (Kind=nag_wp)            :: cx, dx
      Integer                          :: i, ifail, isizea, isizeb, istepa,    &
                                          istepb, j
      Logical                          :: sw
!     .. Local Arrays ..
      Complex (Kind=nag_wp)            :: a(n,n), b(n)
!     .. Executable Statements ..
      Write (nout,*) 'X03ABF Example Program Results'

!     Skip heading in data file
      Read (nin,*)

      Read (nin,*)((a(i,j),j=1,n),i=1,n), (b(i),i=1,n)
      cx = (1.0E0_nag_wp,1.0E0_nag_wp)
      isizea = n
      isizeb = n
      istepa = 1
      istepb = 1
      sw = .True.

      ifail = 0
      Call x03abf(a(1,2),isizea,b,isizeb,n,istepa,istepb,cx,dx,sw,ifail)

      Write (nout,*)
      Write (nout,99999) 'Result = ', dx

99999 Format (1X,A,'(',F3.0,',',F3.0,')')
    End Program x03abfe


x04aafe.f90

!   X04AAF Example Program Text
!   Mark 26 Release. NAG Copyright 2016.

    Module x04aafe_mod

!     X04AAF Example Program Module:
!            Parameters and User-defined Routines

!     .. Implicit None Statement ..
      Implicit None
!     .. Accessibility Statements ..
      Private
      Public                           :: dummy
!     .. Parameters ..
      Integer, Parameter, Public       :: nout = 6
    Contains
      Subroutine dummy

!       .. Use Statements ..
        Use nag_library, Only: x04aaf
!       .. Local Scalars ..
        Integer                        :: nerr
!       .. Executable Statements ..
        Call x04aaf(0,nerr)

        Write (nerr,*)
        Write (nerr,*) 'This is a dummy error message'

        Return

      End Subroutine dummy
    End Module x04aafe_mod
    Program x04aafe

!     X04AAF Example Main Program

!     .. Use Statements ..
      Use nag_library, Only: x04aaf
      Use x04aafe_mod, Only: dummy, nout
!     .. Implicit None Statement ..
      Implicit None
!     .. Local Scalars ..
      Integer                          :: outchn
!     .. Executable Statements ..
      Write (nout,*) 'X04AAF Example Program Results'

      outchn = nout

      Call x04aaf(1,outchn)

      Call dummy

    End Program x04aafe


x04abfe.f90

!   X04ABF Example Program Text
!   Mark 26 Release. NAG Copyright 2016.

    Module x04abfe_mod

!     X04ABF Example Program Module:
!            Parameters and User-defined Routines

!     .. Implicit None Statement ..
      Implicit None
!     .. Accessibility Statements ..
      Private
      Public                           :: dummy
!     .. Parameters ..
      Integer, Parameter               :: iget = 0
      Integer, Parameter, Public       :: iset = 1, nout = 6
    Contains
      Subroutine dummy

!       .. Use Statements ..
        Use nag_library, Only: x04abf
!       .. Local Scalars ..
        Integer                        :: nadv
!       .. Executable Statements ..
        Call x04abf(iget,nadv)

        Write (nadv,*)
        Write (nadv,*) 'This is a dummy advisory message'

        Return

      End Subroutine dummy
    End Module x04abfe_mod
    Program x04abfe

!     X04ABF Example Main Program

!     .. Use Statements ..
      Use nag_library, Only: x04abf
      Use x04abfe_mod, Only: dummy, iset, nout
!     .. Implicit None Statement ..
      Implicit None
!     .. Local Scalars ..
      Integer                          :: outchn
!     .. Executable Statements ..
      Write (nout,*) 'X04ABF Example Program Results'

      outchn = nout

      Call x04abf(iset,outchn)

      Call dummy

    End Program x04abfe


x04acfe.f90

    Program x04acfe

!     X04ACF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: x04acf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: iounit = 4, nout = 6
      Character (*), Parameter         :: file = 'x04acfe_success.res'
!     .. Local Scalars ..
      Integer                          :: ifail, mode
!     .. Executable Statements ..
      Write (nout,*) 'X04ACF Example Program Results'

!     Test successful open for write

      mode = 1

      ifail = 0
      Call x04acf(iounit,file,mode,ifail)

      Write (nout,99999)
      Write (iounit,99999)

99999 Format (' OK file successfully opened for writing')
    End Program x04acfe


x04adfe.f90

    Program x04adfe

!     X04ADF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: x04acf, x04adf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: iounit = 4, nout = 6
      Character (*), Parameter         :: fname = 'x04adfe_success.res'
!     .. Local Scalars ..
      Integer                          :: ifail
!     .. Executable Statements ..
      Write (nout,*) 'X04ADF Example Program Results'

!     Test successful open and close for write

      ifail = 0
      Call x04acf(iounit,fname,1,ifail)

      Write (nout,99999)
      Write (iounit,99999)

      ifail = 0
      Call x04adf(iounit,ifail)

      Write (nout,99998)

!     Test successful open and close for read

      ifail = 0
      Call x04acf(iounit,fname,0,ifail)

      Write (nout,99997)

      ifail = 0
      Call x04adf(iounit,ifail)

      Write (nout,99998)

99999 Format (' OK file successfully opened for writing')
99998 Format (' OK file successfully closed')
99997 Format (' OK file successfully opened for reading')
    End Program x04adfe


x04bafe.f90

    Program x04bafe

!     X04BAF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: x04baf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nout = 6
!     .. Local Scalars ..
      Character (40)                   :: rec
!     .. Executable Statements ..
      Write (nout,*) 'X04BAF Example Program Results'

      Write (nout,*)
      Write (rec,99999) 'This record was output by X04BAF'
      Flush (nout)

      Call x04baf(nout,rec)

99999 Format (1X,A)
    End Program x04bafe


x04bbfe.f90

    Program x04bbfe

!     X04BBF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: nag_wp, x04bbf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: x
      Integer                          :: i, ifail
      Character (40)                   :: recin
!     .. Executable Statements ..
      Write (nout,*) 'X04BBF Example Program Results'

!     Skip heading in data file
      Call x04bbf(nin,recin,ifail)

      Write (nout,*)

!     Read in values of I and X, then write them.

      Call x04bbf(nin,recin,ifail)

      Read (recin,99999) i, x

      Write (nout,99998) i, x

99999 Format (I3,F7.3)
99998 Format (1X,I5,F11.3)
    End Program x04bbfe


x04cafe.f90

    Program x04cafe

!     X04CAF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: nag_wp, x04caf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nmax = 5, nout = 6
      Integer, Parameter               :: lda = nmax
!     .. Local Scalars ..
      Integer                          :: i, ifail, j
!     .. Local Arrays ..
      Real (Kind=nag_wp)               :: a(lda,nmax)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: real
!     .. Executable Statements ..
      Write (nout,*) 'X04CAF Example Program Results'

      Write (nout,*)
      Flush (nout)

!     Generate an array of data

      Do j = 1, nmax

        Do i = 1, lda
          a(i,j) = real(10*i+j,kind=nag_wp)
        End Do

      End Do

!     Print 3 by nmax rectangular matrix

      ifail = 0
      Call x04caf('General',' ',3,nmax,a,lda,'Example 1:',ifail)

      Write (nout,*)
      Flush (nout)

!     Print nmax by nmax lower triangular matrix

      ifail = 0
      Call x04caf('Lower','Non-unit',nmax,nmax,a,lda,'Example 2:',ifail)

    End Program x04cafe


x04cbfe.f90

    Program x04cbfe

!     X04CBF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: nag_wp, x04cbf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nmax = 5, nout = 6
      Integer, Parameter               :: lda = nmax
      Character (7), Parameter         :: clabs(nmax) = (/'Un     ','Deux   ', &
                                          'Trois  ','Quatre ','Cinq   '/)
      Character (7), Parameter         :: rlabs(nmax) = (/'Uno    ','Due    ', &
                                          'Tre    ','Quattro','Cinque '/)
!     .. Local Scalars ..
      Integer                          :: i, ifail, indent, j, ncols
!     .. Local Arrays ..
      Real (Kind=nag_wp)               :: a(lda,nmax)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: real
!     .. Executable Statements ..
      Write (nout,*) 'X04CBF Example Program Results'

      Write (nout,*)
      Flush (nout)

!     Generate an array of data

      Do j = 1, nmax

        Do i = 1, lda
          a(i,j) = real(10*i+j,kind=nag_wp)
        End Do

      End Do

      ncols = 80
      indent = 0

!     Print 3 by nmax rectangular matrix with default format and integer
!     row and column labels

      ifail = 0
      Call x04cbf('General',' ',3,nmax,a,lda,' ','Example 1:','Integer',rlabs, &
        'Integer',clabs,ncols,indent,ifail)

      Write (nout,*)
      Flush (nout)

!     Print nmax by nmax upper triangular matrix with user-supplied format
!     and row and column labels

      ifail = 0
      Call x04cbf('Upper','Non-unit',nmax,nmax,a,lda,'F8.2','Example 2:',      &
        'Character',rlabs,'Character',clabs,ncols,indent,ifail)

      Write (nout,*)
      Flush (nout)

!     Print 3 by nmax lower triangular matrix in MATLAB format
!     Row and column labelling is ignored

      ifail = 0
      Call x04cbf('Lower','Non-unit',3,nmax,a,lda,'MATLABF8.2','A',' ',rlabs,  &
        ' ',clabs,ncols,indent,ifail)

    End Program x04cbfe


x04ccfe.f90

    Program x04ccfe

!     X04CCF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: dtrttp, nag_wp, x04ccf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: n = 5, nout = 6
!     .. Local Scalars ..
      Integer                          :: i, ifail, info, j, lda
      Character (1)                    :: uplo
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: a(:,:), ap(:)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: real
!     .. Executable Statements ..
      Write (nout,*) 'X04CCF Example Program Results'

      Write (nout,*)
      Flush (nout)

!     Generate a full-format symmetric array of data

      lda = n
      Allocate (a(lda,n))

      Do j = 1, n

        Do i = 1, j
          a(i,j) = real(10*i+j,kind=nag_wp)
          a(j,i) = a(i,j)
        End Do

      End Do

!     Print order (n-1) lower triangular matrix

!     Convert a to packed storage.

      Allocate (ap(n*(n+1)/2))

!     The lower triangle.

      uplo = 'L'

!     The NAG name equivalent of dtrttp is f01vaf
      Call dtrttp(uplo,n-1,a,lda,ap,info)

      If (info/=0) Then
        Write (nout,99999) 'Failure in DTRTTP. INFO =', info
        Go To 100
      End If

      ifail = 0
      Call x04ccf('Lower','Unit',n-1,ap,'Example 1:',ifail)

      Write (nout,*)
      Flush (nout)

!     Print order n upper triangular matrix

!     Convert the upper triangle of a to packed storage.

      uplo = 'U'

!     The NAG name equivalent of dtrttp is f01vaf
      Call dtrttp(uplo,n,a,lda,ap,info)

      If (info/=0) Then
        Write (nout,99999) 'Failure in DTRTTP. INFO =', info
        Go To 100
      End If

      ifail = 0
      Call x04ccf('Upper','Non-unit',n,ap,'Example 2:',ifail)

100   Continue

99999 Format (1X,A,I4)
    End Program x04ccfe


x04cdfe.f90

    Program x04cdfe

!     X04CDF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: dtrttp, nag_wp, x04cdf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: n = 5, nout = 6
      Character (7), Parameter         :: clabs(n) = (/'Un     ','Deux   ',    &
                                          'Trois  ','Quatre ','Cinq   '/)
      Character (7), Parameter         :: rlabs(n) = (/'Uno    ','Due    ',    &
                                          'Tre    ','Quattro','Cinque '/)
!     .. Local Scalars ..
      Integer                          :: i, ifail, indent, info, j, lda,      &
                                          ncols
      Character (1)                    :: uplo
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: a(:,:), ap(:)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: real
!     .. Executable Statements ..
      Write (nout,*) 'X04CDF Example Program Results'

      Write (nout,*)
      Flush (nout)

!     Generate a full-format symmetric array of data

      lda = n
      Allocate (a(lda,n))

      Do j = 1, n

        Do i = 1, j
          a(i,j) = real(10*i+j,kind=nag_wp)
          a(j,i) = a(i,j)
        End Do

      End Do

      ncols = 80
      indent = 0

!     Print order (n-1) lower triangular matrix with default format and
!     integer row and column labels

!     Convert a to packed storage.

      Allocate (ap(n*(n+1)/2))

!     The lower triangle.

      uplo = 'L'

!     The NAG name equivalent of dtrttp is f01vaf
      Call dtrttp(uplo,n-1,a,lda,ap,info)

      If (info/=0) Then
        Write (nout,99999) 'Failure in DTRTTP. INFO =', info
        Go To 100
      End If

      ifail = 0
      Call x04cdf('Lower','Non-unit',n-1,ap,' ','Example 1:','Integer',rlabs,  &
        'Integer',clabs,ncols,indent,ifail)

      Write (nout,*)
      Flush (nout)

!     Print order n upper triangular matrix with user-supplied format
!     and row and column labels

!     Convert the upper triangle of a to packed storage.

      uplo = 'U'

!     The NAG name equivalent of dtrttp is f01vaf
      Call dtrttp(uplo,n,a,lda,ap,info)

      If (info/=0) Then
        Write (nout,99999) 'Failure in DTRTTP. INFO =', info
        Go To 100
      End If

      ifail = 0
      Call x04cdf('Upper','Unit',n,ap,'F8.2','Example 2:','Character',rlabs,   &
        'Character',clabs,ncols,indent,ifail)

      Write (nout,*)
      Flush (nout)

!     Print order n upper triangular matrix in MATLAB format
!     Row and column labelling is ignored

      ifail = 0
      Call x04cdf('Upper','Non-unit',n,ap,'MATLABF8.2','A',' ',rlabs,' ',      &
        clabs,ncols,indent,ifail)

100   Continue

99999 Format (1X,A,I4)
    End Program x04cdfe


x04cefe.f90

    Program x04cefe

!     X04CEF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: f01zcf, nag_wp, x04cef
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nout = 6
!     .. Local Scalars ..
      Integer                          :: i, ifail, j, kl, ku, lda, ldab, m, n
      Character (1)                    :: job
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: a(:,:), ab(:,:)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: max, min, real
!     .. Executable Statements ..
      Write (nout,*) 'X04CEF Example Program Results'

      Write (nout,*)
      Flush (nout)

!     Generate a square array of data.

      m = 5
      n = m
      kl = 1
      ku = 1

      lda = m
      Allocate (a(lda,n))

      Do j = 1, n

        Do i = max(1,j-ku), min(m,j+kl)
          a(i,j) = real(10*i+j,kind=nag_wp)
        End Do

      End Do

!     Convert to packed storage.

      ldab = kl + ku + 1
      Allocate (ab(ldab,n))

      job = 'P'

      ifail = 0
      Call f01zcf(job,m,n,kl,ku,a,lda,ab,ldab,ifail)

!     Print m by n band matrix with kl subdiagonals and ku superdiagonals.

      ifail = 0
      Call x04cef(m,n,kl,ku,ab,ldab,'Band Matrix:',ifail)

    End Program x04cefe


x04cffe.f90

    Program x04cffe

!     X04CFF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: f01zcf, nag_wp, x04cff
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: n = 5, nout = 6
      Character (7), Parameter         :: clabs(n) = (/'Un     ','Deux   ',    &
                                          'Trois  ','Quatre ','Cinq   '/)
      Character (7), Parameter         :: rlabs(n) = (/'Uno    ','Due    ',    &
                                          'Tre    ','Quattro','Cinque '/)
!     .. Local Scalars ..
      Integer                          :: i, ifail, indent, j, kl, ku, ku_a,   &
                                          lda, ldab, m, ncols
      Character (1)                    :: job
!     .. Local Arrays ..
      Real (Kind=nag_wp), Allocatable  :: a(:,:), ab(:,:)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: max, min, real
!     .. Executable Statements ..
      Write (nout,*) 'X04CFF Example Program Results'

      Write (nout,*)
      Flush (nout)

!     Generate a square array of data.

      m = n
      kl = 1
      ku_a = 2

      lda = m
      Allocate (a(lda,n))

      Do j = 1, n

        Do i = max(1,j-ku_a), min(m,j+kl)
          a(i,j) = real(10*i+j,kind=nag_wp)
        End Do

      End Do

!     Convert a to packed storage, ignoring the second superdiagonal.

      ldab = kl + ku_a + 1
      Allocate (ab(ldab,n))

      ku = 1

      job = 'P'

      ifail = 0
      Call f01zcf(job,m,n,kl,ku,a,lda,ab,ldab,ifail)

      ncols = 80
      indent = 0

!     Print m by n band matrix with kl subdiagonals, 1 superdiagonal,
!     default format and integer row and column labels

      ifail = 0
      Call x04cff(m,n,kl,ku,ab,ldab,' ','Example 1:','Integer',rlabs,          &
        'Integer',clabs,ncols,indent,ifail)

      Write (nout,*)
      Flush (nout)

!     Convert the whole matrix a to packed storage.

      ku = ku_a

      job = 'P'

      ifail = 0
      Call f01zcf(job,m,n,kl,ku,a,lda,ab,ldab,ifail)

!     Print m by n band matrix with kl subdiagonals, ku superdiagonals,
!     user-supplied format and row and column labels

      ifail = 0
      Call x04cff(m,n,kl,ku,ab,ldab,'F8.2','Example 2:','Character',rlabs,     &
        'Character',clabs,ncols,indent,ifail)

      Write (nout,*)
      Flush (nout)

!     Print m by n band matrix with kl subdiagonals, ku superdiagonals,
!     in MATLAB format
!     Row and column labelling is ignored

      ifail = 0
      Call x04cff(m,n,kl,ku,ab,ldab,'MATLABF8.2','A',' ',rlabs,' ',clabs,      &
        ncols,indent,ifail)

    End Program x04cffe


x04dafe.f90

    Program x04dafe

!     X04DAF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: nag_wp, x04daf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nmax = 4, nout = 6
      Integer, Parameter               :: lda = nmax
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: aa
      Integer                          :: i, ifail, j
!     .. Local Arrays ..
      Complex (Kind=nag_wp)            :: a(lda,nmax)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: cmplx, real
!     .. Executable Statements ..
      Write (nout,*) 'X04DAF Example Program Results'

      Write (nout,*)
      Flush (nout)

!     Generate an array of data

      Do j = 1, nmax

        Do i = 1, lda
          aa = real(10*i+j,kind=nag_wp)
          a(i,j) = cmplx(aa,-aa,kind=nag_wp)
        End Do

      End Do

!     Print nmax by (nmax-1) rectangular matrix

      ifail = 0
      Call x04daf('General',' ',nmax,nmax-1,a,lda,'Example 1:',ifail)

      Write (nout,*)
      Flush (nout)

!     Print nmax by nmax lower triangular matrix

      ifail = 0
      Call x04daf('Lower','Non-unit',nmax,nmax,a,lda,'Example 2:',ifail)

    End Program x04dafe


x04dbfe.f90

    Program x04dbfe

!     X04DBF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: nag_wp, x04dbf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nmax = 4, nout = 6
      Integer, Parameter               :: lda = nmax
      Character (7), Parameter         :: clabs(nmax) = (/'Un     ','Deux   ', &
                                          'Trois  ','Quatre '/)
      Character (7), Parameter         :: rlabs(nmax) = (/'Uno    ','Due    ', &
                                          'Tre    ','Quattro'/)
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: aa
      Integer                          :: i, ifail, indent, j, ncols
!     .. Local Arrays ..
      Complex (Kind=nag_wp)            :: a(lda,nmax)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: cmplx, real
!     .. Executable Statements ..
      Write (nout,*) 'X04DBF Example Program Results'

      Write (nout,*)
      Flush (nout)

!     Generate an array of data

      Do j = 1, nmax

        Do i = 1, lda
          aa = real(10*i+j,kind=nag_wp)
          a(i,j) = cmplx(aa,-aa,kind=nag_wp)
        End Do

      End Do

      ncols = 80
      indent = 0

!     Print (nmax-1) by nmax rectangular matrix with default format and
!     integer row and column labels, and bracketed complex elements

      ifail = 0
      Call x04dbf('General',' ',nmax-1,nmax,a,lda,'Bracketed',' ',             &
        'Example 1:','Integer',rlabs,'Integer',clabs,ncols,indent,ifail)

      Write (nout,*)
      Flush (nout)

!     Print nmax by nmax upper triangular matrix with user-supplied format
!     and row and column labels, and complex elements with real part
!     above imaginary part

      ifail = 0
      Call x04dbf('Upper','Non-unit',nmax,nmax,a,lda,'Above','F8.2',           &
        'Example 2:','Character',rlabs,'Character',clabs,ncols,indent,ifail)

      Write (nout,*)
      Flush (nout)

!     Print (nmax-1) by nmax lower triangular matrix in MATLAB format
!     Row and column labelling and USEFRM are ignored

      ifail = 0
      Call x04dbf('Lower','Unit',nmax-1,nmax,a,lda,' ','MATLABF8.2','A',' ',   &
        rlabs,' ',clabs,ncols,indent,ifail)

    End Program x04dbfe


x04dcfe.f90

    Program x04dcfe

!     X04DCF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: nag_wp, x04dcf, ztrttp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: n = 4, nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: aa
      Integer                          :: i, ifail, info, j, lda
      Character (1)                    :: uplo
!     .. Local Arrays ..
      Complex (Kind=nag_wp), Allocatable :: a(:,:), ap(:)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: cmplx, real
!     .. Executable Statements ..
      Write (nout,*) 'X04DCF Example Program Results'

      Write (nout,*)
      Flush (nout)

!     Generate a full-format symmetric array of data

      lda = n
      Allocate (a(lda,n))

      Do j = 1, n

        Do i = 1, j
          aa = real(10*i+j,kind=nag_wp)
          a(i,j) = cmplx(aa,-aa,kind=nag_wp)
          a(j,i) = a(i,j)
        End Do

      End Do

!     Print order (n-1) lower triangular matrix

!     Convert a to packed storage.

      Allocate (ap(n*(n+1)/2))

!     The lower triangle.

      uplo = 'L'

!     The NAG name equivalent of ztrttp is f01vbf
      Call ztrttp(uplo,n-1,a,lda,ap,info)

      If (info/=0) Then
        Write (nout,99999) 'Failure in ZTRTTP. INFO =', info
        Go To 100
      End If

      ifail = 0
      Call x04dcf('Lower','Unit',n-1,ap,'Example 1:',ifail)

      Write (nout,*)
      Flush (nout)

!     Print order n upper triangular matrix

!     Convert the upper triangle of a to packed storage.

      uplo = 'U'

!     The NAG name equivalent of ztrttp is f01vbf
      Call ztrttp(uplo,n,a,lda,ap,info)

      If (info/=0) Then
        Write (nout,99999) 'Failure in ZTRTTP. INFO =', info
        Go To 100
      End If

      ifail = 0
      Call x04dcf('Upper','Non-unit',n,ap,'Example 2:',ifail)

100   Continue

99999 Format (1X,A,I4)
    End Program x04dcfe


x04ddfe.f90

    Program x04ddfe

!     X04DDF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: nag_wp, x04ddf, ztrttp
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: n = 4, nout = 6
      Character (7), Parameter         :: clabs(n) = (/'Un     ','Deux   ',    &
                                          'Trois  ','Quatre '/)
      Character (7), Parameter         :: rlabs(n) = (/'Uno    ','Due    ',    &
                                          'Tre    ','Quattro'/)
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: aa
      Integer                          :: i, ifail, indent, info, j, lda,      &
                                          ncols
      Character (19)                   :: form
      Character (1)                    :: uplo
!     .. Local Arrays ..
      Complex (Kind=nag_wp), Allocatable :: a(:,:), ap(:)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: cmplx, real
!     .. Executable Statements ..
      Write (nout,*) 'X04DDF Example Program Results'

      Write (nout,*)
      Flush (nout)

!     Generate a full-format symmetric array of data

      lda = n
      Allocate (a(lda,n))

      Do j = 1, n

        Do i = 1, j
          aa = real(10*i+j,kind=nag_wp)
          a(i,j) = cmplx(aa,-aa,kind=nag_wp)
          a(j,i) = a(i,j)
        End Do

      End Do

      ncols = 80
      indent = 0

!     Print order n lower triangular matrix with default format and
!     integer row and column labels, and bracketed complex elements

!     Convert a to packed storage.

      Allocate (ap(n*(n+1)/2))

!     The lower triangle.

      uplo = 'L'

!     The NAG name equivalent of ztrttp is f01vbf
      Call ztrttp(uplo,n,a,lda,ap,info)

      If (info/=0) Then
        Write (nout,99999) 'Failure in ZTRTTP. INFO =', info
        Go To 100
      End If

      form = ' '

      ifail = 0
      Call x04ddf('Lower','Non-unit',n,ap,'Bracketed',form,'Example 1:',       &
        'Integer',rlabs,'Integer',clabs,ncols,indent,ifail)

      Write (nout,*)
      Flush (nout)

!     Print order n upper triangular matrix with user-supplied format
!     and row and column labels, using the supplied format directly

!     Convert the upper triangle of a to packed storage.

      uplo = 'U'

!     The NAG name equivalent of ztrttp is f01vbf
      Call ztrttp(uplo,n,a,lda,ap,info)

      If (info/=0) Then
        Write (nout,99999) 'Failure in ZTRTTP. INFO =', info
        Go To 100
      End If

      form = 'SS,F7.1,SP,F6.1,''i'''

      ifail = 0
      Call x04ddf('Upper','Unit',n,ap,'Direct',form,'Example 2:','Character',  &
        rlabs,'Character',clabs,ncols,indent,ifail)

      Write (nout,*)
      Flush (nout)

!     Print order n upper triangular matrix in MATLAB format
!     Row and column labelling and USEFRM are ignored

      form = 'MATLABF8.2'

      ifail = 0
      Call x04ddf('Upper','Non-unit',n,ap,' ',form,'A',' ',rlabs,' ',clabs,    &
        ncols,indent,ifail)

100   Continue

99999 Format (1X,A,I4)
    End Program x04ddfe


x04defe.f90

    Program x04defe

!     X04DEF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: f01zdf, nag_wp, x04def
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: aa
      Integer                          :: i, ifail, j, kl, ku, lda, ldab, m, n
      Character (1)                    :: job
!     .. Local Arrays ..
      Complex (Kind=nag_wp), Allocatable :: a(:,:), ab(:,:)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: cmplx, max, min, real
!     .. Executable Statements ..
      Write (nout,*) 'X04DEF Example Program Results'

      Write (nout,*)
      Flush (nout)

!     Generate a square array of data.

      m = 5
      n = m
      kl = 1
      ku = 1

      lda = m
      Allocate (a(lda,n))

      Do j = 1, n

        Do i = max(1,j-ku), min(m,j+kl)
          aa = real(10*i+j,kind=nag_wp)
          a(i,j) = cmplx(aa,-aa,kind=nag_wp)
        End Do

      End Do

!     Convert to packed storage.

      ldab = kl + ku + 1
      Allocate (ab(ldab,n))

      job = 'P'

      ifail = 0
      Call f01zdf(job,m,n,kl,ku,a,lda,ab,ldab,ifail)

!     Print m by n band matrix with kl subdiagonals and ku superdiagonals.

      ifail = 0
      Call x04def(m,n,kl,ku,ab,ldab,'Band Matrix:',ifail)

    End Program x04defe


x04dffe.f90

    Program x04dffe

!     X04DFF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: f01zdf, nag_wp, x04dff
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: n = 5, nout = 6
      Character (7), Parameter         :: clabs(n) = (/'Un     ','Deux   ',    &
                                          'Trois  ','Quatre ','Cinq   '/)
      Character (7), Parameter         :: rlabs(n) = (/'Uno    ','Due    ',    &
                                          'Tre    ','Quattro','Cinque '/)
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: aa
      Integer                          :: i, ifail, indent, j, kl, ku, ku_a,   &
                                          lda, ldab, m, ncols
      Character (19)                   :: form
      Character (1)                    :: job
!     .. Local Arrays ..
      Complex (Kind=nag_wp), Allocatable :: a(:,:), ab(:,:)
!     .. Intrinsic Procedures ..
      Intrinsic                        :: cmplx, max, min, real
!     .. Executable Statements ..
      Write (nout,*) 'X04DFF Example Program Results'

      Write (nout,*)
      Flush (nout)

!     Generate a square array of data.

      m = n
      kl = 1
      ku_a = 2

      lda = m
      Allocate (a(lda,n))

      Do j = 1, n

        Do i = max(1,j-ku_a), min(m,j+kl)
          aa = real(10*i+j,kind=nag_wp)
          a(i,j) = cmplx(aa,-aa,kind=nag_wp)
        End Do

      End Do

!     Convert a to packed storage, ignoring the second superdiagonal.

      ldab = kl + ku_a + 1
      Allocate (ab(ldab,n))

      ku = 1

      job = 'P'

      ifail = 0
      Call f01zdf(job,m,n,kl,ku,a,lda,ab,ldab,ifail)

      ncols = 80
      indent = 0

!     Print m by n band matrix with kl subdiagonals, 1 superdiagonal,
!     default format, bracketed complex numbers, and integer row and
!     column labels

      form = ' '

      ifail = 0
      Call x04dff(m,n,kl,1,ab,ldab,'Bracketed',form,'Example 1:','Integer',    &
        rlabs,'Integer',clabs,ncols,indent,ifail)

      Write (nout,*)
      Flush (nout)

!     Convert the whole matrix a to packed storage.

      ku = ku_a

      job = 'P'

      ifail = 0
      Call f01zdf(job,m,n,kl,ku,a,lda,ab,ldab,ifail)

!     Print (m-1) by (n-1) band matrix with kl subdiagonals,
!     ku superdiagonals, user-supplied format and row and column labels.

      form = 'SS,F7.1,SP,F6.1,''i'''

      ifail = 0
      Call x04dff(m-1,n-1,kl,ku,ab,ldab,'Direct',form,'Example 2:',            &
        'Character',rlabs,'Character',clabs,ncols,indent,ifail)

      Write (nout,*)
      Flush (nout)

!     Print (m-1) by (n-1) band matrix with kl subdiagonals,
!     ku superdiagonals, in MATLAB format.
!     Row and column labelling and USEFRM are ignored.

      form = 'MATLABF7.1'

      ifail = 0
      Call x04dff(m-1,n-1,kl,ku,ab,ldab,' ',form,'A',' ',rlabs,' ',clabs,      &
        ncols,indent,ifail)

    End Program x04dffe


x04eafe.f90

    Program x04eafe

!     X04EAF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: x04eaf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nmax = 5, nout = 6
      Integer, Parameter               :: lda = nmax
!     .. Local Scalars ..
      Integer                          :: i, ifail, j
!     .. Local Arrays ..
      Integer                          :: a(lda,nmax)
!     .. Executable Statements ..
      Write (nout,*) 'X04EAF Example Program Results'

      Write (nout,*)
      Flush (nout)

!     Generate an array of data

      Do j = 1, nmax

        Do i = 1, lda
          a(i,j) = 10*i + j
        End Do

      End Do

!     Print 3 by nmax rectangular matrix

      ifail = 0
      Call x04eaf('General',' ',3,nmax,a,lda,'Example 1:',ifail)

      Write (nout,*)
      Flush (nout)

!     Print nmax by nmax lower triangular matrix

      ifail = 0
      Call x04eaf('Lower','Non-unit',nmax,nmax,a,lda,'Example 2:',ifail)

    End Program x04eafe


x04ebfe.f90

    Program x04ebfe

!     X04EBF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: x04ebf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nmax = 5, nout = 6
      Integer, Parameter               :: lda = nmax
      Character (7), Parameter         :: clabs(nmax) = (/'Un     ','Deux   ', &
                                          'Trois  ','Quatre ','Cinq   '/)
      Character (7), Parameter         :: rlabs(nmax) = (/'Uno    ','Due    ', &
                                          'Tre    ','Quattro','Cinque '/)
!     .. Local Scalars ..
      Integer                          :: i, ifail, indent, j, ncols
!     .. Local Arrays ..
      Integer                          :: a(lda,nmax)
!     .. Executable Statements ..
      Write (nout,*) 'X04EBF Example Program Results'

      Write (nout,*)
      Flush (nout)

!     Generate an array of data

      Do j = 1, nmax

        Do i = 1, lda
          a(i,j) = 10*i + j
        End Do

      End Do

      ncols = 80
      indent = 0

!     Print 3 by nmax rectangular matrix with default format and integer
!     row and column labels

      ifail = 0
      Call x04ebf('General',' ',3,nmax,a,lda,' ','Example 1:','Integer',rlabs, &
        'Integer',clabs,ncols,indent,ifail)

      Write (nout,*)
      Flush (nout)

!     Print nmax by nmax upper triangular matrix with user-supplied format
!     and row and column labels

      ifail = 0
      Call x04ebf('Upper','Non-unit',nmax,nmax,a,lda,'I8','Example 2:',        &
        'Character',rlabs,'Character',clabs,ncols,indent,ifail)

      Write (nout,*)
      Flush (nout)

!     Print 4 by nmax lower triangular matrix in MATLAB format
!     Row and column labelling is ignored

      ifail = 0
      Call x04ebf('Lower','Non-unit',4,nmax,a,lda,'MATLABI8','A',' ',rlabs,    &
        ' ',clabs,ncols,indent,ifail)

    End Program x04ebfe


x05aafe.f90

    Program x05aafe

!     X05AAF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: x04acf, x04adf, x04baf, x05aaf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: iounit = 53, nout = 6
      Character (*), Parameter         :: fname = 'x05aafe_output.txt'
!     .. Local Scalars ..
      Integer                          :: ifail
      Character (80)                   :: rec
!     .. Local Arrays ..
      Integer                          :: itime(7)
!     .. Executable Statements ..
      Write (nout,*) 'X05AAF Example Program Results'

!     Associate fname with iounit and open the unit for writing:
      ifail = 0
      Call x04acf(iounit,fname,1,ifail)

!     Get the time array:
      Call x05aaf(itime)

!     Stamp the output file:
      Call x04baf(iounit,                                                      &
        'File created by NAG x05aaf example program, time stamp:')
      Write (rec,99999) itime
      Call x04baf(iounit,rec)

!     Close the output file:
      ifail = 0
      Call x04adf(iounit,ifail)

      Write (nout,*) 'File created and stamped successfully.'

99999 Format (I4.4,2I2.2,'-',3(I2.2,':'),I3.3)
    End Program x05aafe


x05abfe.f90

    Program x05abfe

!     X05ABF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: x05abf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Character (30)                   :: ctime
!     .. Local Arrays ..
      Integer                          :: itime(7)
!     .. Executable Statements ..
      Write (nout,*) 'X05ABF Example Program Results'

!     Skip heading in data file
      Read (nin,*)

      Read (nin,*) itime

      ctime = x05abf(itime)

      Write (nout,99999) ctime

99999 Format (1X,A)
    End Program x05abfe


x05acfe.f90

    Program x05acfe

!     X05ACF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: x05acf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nin = 5, nout = 6
!     .. Local Scalars ..
      Integer                          :: k
      Character (50)                   :: ctime1, ctime2
!     .. Executable Statements ..
      Write (nout,*) 'X05ACF Example Program Results'

!     Skip heading in data file
      Read (nin,*)

      Read (nin,*) ctime1, ctime2

      k = x05acf(ctime1,ctime2)

      Write (nout,99999) ctime1

      Select Case (k)
      Case (:-1)
        Write (nout,99999) 'is earlier than'
      Case (0)
        Write (nout,99999) 'is equivalent to'
      Case (1:)
        Write (nout,99999) 'is later than'
      End Select

      Write (nout,99999) ctime2

99999 Format (1X,A)
    End Program x05acfe


x05bafe.f90

    Program x05bafe

!     X05BAF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: nag_wp, x05baf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Real (Kind=nag_wp), Parameter    :: timeout_s = 100._nag_wp
      Integer, Parameter               :: nout = 6
      Integer, Parameter               :: nterms = 10**7
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: h, start
      Integer                          :: n
!     .. Intrinsic Procedures ..
      Intrinsic                        :: real
!     .. Executable Statements ..
      Write (nout,*) 'X05BAF Example Program Results'

      start = x05baf()

!     Do a non-trivial amount of intermediate work.

      h = 0._nag_wp
      n = 1

loop: Do
        h = h + 1.0_nag_wp/real(nterms-n+1,kind=nag_wp)

        If (x05baf()-start>timeout_s) Then
          Write (nout,*) 'Computation timed out.'
          Exit loop
        End If

        If (n==nterms) Then
          Exit loop
        End If

        n = n + 1
      End Do loop

      Write (nout,99999) 'Computed ', n,                                       &
        ' terms of the harmonic series within the allotted time limit.'
99999 Format (1X,A,I8,A)
      Write (nout,99998) 'Value of partial sum is', h, '.'
99998 Format (1X,A,E13.5,A)
    End Program x05bafe


x06aafe.f90

    Program x06aafe

!     X06AAF Example Program Text

!     Mark 26 Release. NAG Copyright 2015.

!     .. Use Statements ..
      Use nag_library, Only: x06aaf, x06abf, x06acf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nout = 6
!     .. Local Scalars ..
      Integer                          :: ifail, num, num_max, num_set
!     .. Executable Statements ..
      Write (nout,*) 'X06AAF Example Program Results'
      Write (nout,*)

      ifail = 0
      num_set = 5

!     Set the OpenMP Internal Control Variable (ICV) controlling the number
!     of threads
      Call x06aaf(num_set,ifail)

!     Retrieve the value of the ICV, and display it
      num_max = x06acf()
      Write (nout,99999) 'Value of ICV controlling the number of threads:',    &
        num_max
      Write (nout,*)

!     Display the number of threads in the current team
      num = x06abf()
      Write (nout,99999) 'Number of threads outside the parallel region: ',    &
        num
      Write (nout,*)

!     Spawn an OpenMP parallel region and have the master thread display
!     the number of threads in the current team

      !$Omp Parallel Private (num), Default (None)

        num = x06abf()

        !$Omp Master
          Write (nout,99999) 'Number of threads inside the parallel region: ', &
            num
          Write (nout,*)
        !$Omp End Master

      !$Omp End Parallel

99999 Format (1X,A,I5)

    End Program x06aafe


x06adfe.f90

    Program x06adfe

!     X06ADF Example Program Text

!     Mark 26 Release. NAG Copyright 2015.

!     .. Use Statements ..
      Use nag_library, Only: x06abf, x06adf, x06aff
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nout = 6
!     .. Local Scalars ..
      Integer                          :: in_para, me, num_got, num_req
!     .. Executable Statements ..
      Write (nout,*) 'X06ADF Example Program Results'
      Write (nout,*)

!     Get the thread number with a call to X06ADF and display it
      me = x06adf()
      Write (nout,99999) 'Thread number:            ', me
      Write (nout,*)

!     Call x06aff to check whether we are in an active parallel region
      in_para = x06aff()
      Write (nout,99999) 'In active parallel region:', in_para
      Write (nout,*)

!     Spawn an OpenMP parallel region, have the master thread display
!     the number of threads and check whether we are in an active
!     parallel region

      num_req = 5

      !$Omp Parallel Num_threads (num_req), Private (in_para,me,num_got),      &
      !$Omp   Default (None)

        me = x06adf()
        num_got = x06abf()
        in_para = x06aff()

        If (me==0) Then
          Write (nout,99999) 'Number of threads:        ', num_got
          Write (nout,*)
          Write (nout,99999) 'In active parallel region:', in_para
          Write (nout,*)
        End If

      !$Omp End Parallel

99999 Format (1X,A,I11)

    End Program x06adfe


x06agfe.f90

    Program x06agfe

!     X06AGF Example Program Text

!     Mark 26 Release. NAG Copyright 2015.

!     .. Use Statements ..
      Use nag_library, Only: x06aaf, x06agf, x06ahf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nout = 6
!     .. Local Scalars ..
      Integer                          :: ifail, nesting, nesting_set,         &
                                          num_inner, num_outer, total
!     .. Executable Statements ..
      Write (nout,*) 'X06AGF Example Program Results'
      Write (nout,*)

!     Enable the nesting of OpenMP parallel regions
      nesting_set = 1
      Call x06agf(nesting_set)

      ifail = 0
      num_inner = 3
      num_outer = 5

!     Set the number of OpenMP threads for an outer parallel region
      Call x06aaf(num_outer,ifail)

!     Spawn an OpenMP parallel region and have the master thread check whether
!     nesting of parallel regions has been enabled.

      total = 0

      !$Omp Parallel Shared (num_inner,total), Private (ifail,nesting),        &
      !$Omp   Default (None)

        nesting = x06ahf()

        !$Omp Master
          Write (nout,99999) 'Nesting enabled:', nesting
          Write (nout,*)
        !$Omp End Master

        ifail = 0
!       Set the number of OpenMP threads for an inner parallel region
        Call x06aaf(num_inner,ifail)

!       Spawn a nested parallel region
        !$Omp Parallel Shared (total), Default (None)

!         Add up the total number of threads in all teams
          !$Omp Atomic
            total = total + 1

        !$Omp End Parallel

      !$Omp End Parallel

      Write (nout,99999) 'Total number of threads requested:',                 &
        num_outer*num_inner
      Write (nout,99999) 'Total number of threads from sum: ', total
      Write (nout,*)

99999 Format (1X,A,I5)

    End Program x06agfe


x07aafe.f90

    Program x07aafe

!     X07AAF Example Program Text

!     Mark 26 Release. NAG Copyright 2016.

!     .. Use Statements ..
      Use nag_library, Only: nag_wp, x02alf, x07aaf, x07abf, x07baf, x07bbf,   &
                             x07caf, x07cbf
!     .. Implicit None Statement ..
      Implicit None
!     .. Parameters ..
      Integer, Parameter               :: nout = 6
!     .. Local Scalars ..
      Real (Kind=nag_wp)               :: huge, neginf, qnan, x, y, zero
!     .. Local Arrays ..
      Integer                          :: exmode(3), newexmode(3)
!     .. Executable Statements ..
      Write (nout,*) 'X07AAF Example Program Results'
      Write (nout,*)

!     Turn exception halting mode off for the three common exceptions
!     overflow, division-by-zero, and invalid operation
      Write (nout,*) 'Turn exception halting off ...'
      exmode = (/0,0,0/)
      Call x07cbf(exmode)

!     Check that exception halting mode for the three common exceptions
!     was really turned off
      Call x07caf(newexmode)
      Write (nout,99999) 'Exception halting mode is now: ', newexmode

!     Look at some ordinary numbers
      x = 1.0_nag_wp
      Call diagnose('one',x)
      x = -2.0_nag_wp
      Call diagnose('-two',x)
      zero = 0.0_nag_wp
      Call diagnose('zero',zero)

!     Generate an infinity and a NaN and look at their properties
      Call x07baf(-1,neginf)
      Call diagnose('-Infinity',neginf)
      Call x07bbf(1,qnan)
      Call diagnose('Quiet NaN',qnan)

!     Do some operations which purposely raise exceptions
      huge = x02alf()
      Write (nout,*)
      Write (nout,*) 'Try to cause overflow - no trap should occur:'
      x = huge
      y = x*x
      If (y>huge) Then
        Write (nout,99998) 'y = huge() * huge() > huge() '
      Else
        Write (nout,99998) 'y = huge() * huge() = ', y
      End If

      Write (nout,*)
      Write (nout,*) 'Try to cause NaN - no trap should occur:'
      y = zero/zero
      If (x07abf(y)) Then
        Write (nout,99998) 'y = 0.0 / 0.0 = NaN'
      Else
        Write (nout,99998) 'y = 0.0 / 0.0 = ', y
      End If

      Write (nout,*)
      Write (nout,*) 'Try to cause division by zero - no trap should occur:'
      x = 1.0_nag_wp
      y = x/zero
      If (y>huge) Then
        Write (nout,99998) 'y = 1.0 / 0.0 > huge()'
      Else
        Write (nout,99998) 'y = 1.0 / 0.0 = ', y
      End If

99999 Format (1X,A,3I3)
99998 Format (1X,A,1P,E12.4)

    Contains

      Subroutine diagnose(c,x)

!       .. Implicit None Statement ..
        Implicit None
!       .. Scalar Arguments ..
        Real (Kind=nag_wp), Intent (In) :: x
        Character (*), Intent (In)     :: c
!       .. Executable Statements ..
        Write (nout,*)
        If (c=='-Infinity') Then
          Write (nout,99999) c
        Else
          Write (nout,99998) c, x
        End If

        If (x07aaf(x)) Then
          Write (nout,*) '"' // c // '" is finite'
        Else
          Write (nout,*) '"' // c // '" is not finite'
        End If
        If (x07abf(x)) Then
          Write (nout,*) '"' // c // '" is NaN'
        Else
          Write (nout,*) '"' // c // '" is not NaN'
        End If

        If (x<0.0_nag_wp) Then
          Write (nout,*) '"' // c // '" compares less than zero.'
        Else
          Write (nout,*) '"' // c // '" does not compare less than zero.'
        End If
        If (x==0.0_nag_wp) Then
          Write (nout,*) '"' // c // '" compares equal to zero.'
        Else
          Write (nout,*) '"' // c // '" does not compare equal to zero.'
        End If
        If (x>0.0_nag_wp) Then
          Write (nout,*) '"' // c // '" compares greater than zero.'
        Else
          Write (nout,*) '"' // c // '" does not compare greater than zero.'
        End If

        Return

99999   Format (1X,'Diagnosis of value "',A,'"')
99998   Format (1X,'Diagnosis of value "',A,'" which prints as ',1P,E12.4)

      End Subroutine diagnose

    End Program x07aafe


A00AAF : NAG Library, Mark 26

A00 Chapter Contents
A00 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

A00AAF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

A00AAF prints information about the version of the NAG Library in use.

2 Specification

SUBROUTINE A00AAF ( )

3 Description

The NAG Library is available for use on a number of different computer systems. For each distinct system an implementation of the library is prepared. This includes tested compiled libraries and any necessary system-specific support material. A00AAF may be called to print the implementation details and Mark (i.e., maintenance level) of the NAG Library implementation that is being used.

4 References

None.

5 Arguments

None.

6 Error Indicators and Warnings

None.

7 Accuracy

Not applicable.

8 Parallelism and Performance

Not applicable.

9 Further Comments

None.

10 Example

This example makes a call of A00AAF sending output to the current advisory message unit.

10.1 Program Text

Program Text (a00aafe.f90)

10.2 Program Data

None.

10.3 Program Results

Program Results (a00aafe.r)

A00 Chapter Contents
A00 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


A00ACF : NAG Library, Mark 26

A00 Chapter Contents
A00 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

A00ACF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

A00ACF provides a convenient means of checking the availability of a valid licence key on licence-managed implementations before starting computations that will use NAG Library routines. In particular, the use of this function is highly recommended in programs that call NAG Library routines within multithreaded sections (e.g., OpenMP parallel regions). The function need only be called once, before the start of the first multithreaded section.

2 Specification

FUNCTION A00ACF ( )
LOGICAL A00ACF

3 Description

A00ACF returns the logical value .TRUE. if a valid licence is found, otherwise .FALSE. is returned.
On non licence-managed implementations, .TRUE. is always returned.

4 References

None.

5 Arguments

None.

6 Error Indicators and Warnings

None.

7 Accuracy

Not applicable.

8 Parallelism and Performance

Not applicable.

9 Further Comments

None.

10 Example

This example prints an appropriate message depending upon the value returned by A00ACF.

10.1 Program Text

Program Text (a00acfe.f90)

10.2 Program Data

None.

10.3 Program Results

Program Results (a00acfe.r)

A00 Chapter Contents
A00 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


A00ADF : NAG Library, Mark 26

A00 Chapter Contents
A00 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

A00ADF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

A00ADF provides information about the version of the NAG Library in use.

2 Specification

SUBROUTINE A00ADF ( IMPL, PREC, PCODE, MKMAJ, MKMIN, HDWARE, OPSYS, FCOMP, VEND, LICVAL)
INTEGER | MKMAJ, MKMIN
LOGICAL | LICVAL
CHARACTER(*) | IMPL, PREC, PCODE, HDWARE, OPSYS, FCOMP, VEND

3 Description

The NAG Library is available for use on a number of different computer systems. For each distinct system an implementation of the library is prepared and this implementation is given a unique code. The specifics that define the implementation are: the working precision, the major and minor marks of the NAG Library, the target hardware and operating system, the compiler used, and the vendor library (if any) that is also required to be linked. A00ADF may be called to return, in separate arguments, these specific details of the NAG Library implementation that is being used; it also returns whether a valid licence has been found for this implementation. This differs from A00AAF which simply outputs the collected information in a readable form directly to the current advisory message unit (see X04ABF).

4 References

None.

5 Arguments

1:   IMPL – CHARACTER(*)Output
Note: it is recommended that IMPL be at least 57 characters in length.
On exit: the implementation title which usually lists the target platform, operating system and compiler.
2:   PREC – CHARACTER(*)Output
Note: it is recommended that PREC be at least 57 characters in length.
On exit: the working or basic precision of the implementation. Some routines may perform operations in reduced precision or additional precision, but the great majority will perform all operations in basic precision. See Section 4.4 in How to Use the NAG Library and its Documentation for definitions of these precisions.
3:   PCODE – CHARACTER(*)Output
Note: it is recommended that PCODE be at least 20 characters in length.
On exit: the product code for the NAG Library implementation that is being used. The code has a discernible structure, but it is not necessary to know the details of this structure. The product code can be used to differentiate between individual product licence codes.
4:   MKMAJ – INTEGEROutput
On exit: the major mark of the NAG Library implementation that is being used.
5:   MKMIN – INTEGEROutput
On exit: the minor mark of the NAG Library implementation that is being used.
6:   HDWARE – CHARACTER(*)Output
Note: it is recommended that HDWARE be at least 64 characters in length.
On exit: the target hardware for the NAG Library implementation that is being used.
7:   OPSYS – CHARACTER(*)Output
Note: it is recommended that OPSYS be at least 64 characters in length.
On exit: the target operating system for the NAG Library implementation that is being used.
8:   FCOMP – CHARACTER(*)Output
Note: it is recommended that FCOMP be at least 64 characters in length.
On exit: the compiler used to build the NAG Library implementation that is being used.
9:   VEND – CHARACTER(*)Output
Note: it is recommended that VEND be at least 64 characters in length.
On exit: the subsidiary library, if any, that must be linked with the NAG Library implementation that is being used. If the implementation does not require a subsidiary library then the string
 '(self-contained)'
will be returned in VEND.
10:   LICVAL – LOGICALOutput
On exit: specifies whether or not a valid licence has been found for the NAG Library implementation that is being used.

6 Error Indicators and Warnings

None.

7 Accuracy

Not applicable.

8 Parallelism and Performance

Not applicable.

9 Further Comments

None.

10 Example

This example makes a call of A00ADF, collects information on the NAG Library implementation that is being used and prints it out in a form that is similar to the output obtained by a call to A00AAF. Additionally the time is also printed in a readable form. The output from running this example program provides information that is very useful when contacting NAG with a support query.

10.1 Program Text

Program Text (a00adfe.f90)

10.2 Program Data

None.

10.3 Program Results

Program Results (a00adfe.r)

A00 Chapter Contents
A00 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


A00 Chapter Contents : NAG Library Manual, Mark 26

A00 Chapter Introduction
NAG Library Manual

NAG Library Chapter Contents

A00 – Library Identification

A00 Chapter Introduction – a description of the Chapter and an overview of the algorithms available

Routine Name | Mark of Introduction | Purpose
A00AAF Example Text | 18 | nagf_info_impl_details Library identification, details of implementation and mark
A00ACF Example Text | 21 | nagf_info_licence Check availability of a valid licence key
A00ADF Example Text | 22 | nagf_info_impl_details_separate Library identification, details of implementation, major and minor marks
A00 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


A00 Chapter Introduction : NAG Library, Mark 26

A00 Chapter Contents
NAG Library Manual

NAG Library Chapter Introduction

A00 – Library Identification

▸▿ Contents

1 Scope of the Chapter
2 Background to the Problems
3 Recommendations on Choice and Use of Available Routines
4 Functionality Index
5 Auxiliary Routines Associated with Library Routine Arguments
6 Routines Withdrawn or Scheduled for Withdrawal

1 Scope of the Chapter

The routines in this chapter provide information about the NAG Library.
Information about the precise implementation of the NAG Library in use will be needed when communicating with the NAG Technical Support Service (see Support from NAG).

2 Background to the Problems

None.

3 Recommendations on Choice and Use of Available Routines

A00AAF enables you to determine the precise Mark and maintenance level of the NAG Library which is being used, and also details of the implementation.
A00ACF enables you to check if a valid key is available for the library licence management system.
A00ADF is similar to A00AAF but returns different aspects of an implementation, such as the product code and Mark in separate strings and integers.

4 Functionality Index

Check availability of a valid licence key A00ACF
Library identification,
print details of implementation and mark A00AAF
separated details of implementation, and major and minor mark A00ADF

5 Auxiliary Routines Associated with Library Routine Arguments

None.

6 Routines Withdrawn or Scheduled for Withdrawal

None.
A00 Chapter Contents
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


A02AAF : NAG Library, Mark 26

A02 Chapter Contents
A02 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

A02AAF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

A02AAF evaluates the square root of the complex number x=xr,xi.

2 Specification

SUBROUTINE A02AAF ( XR, XI, YR, YI)
REAL (KIND=nag_wp) XR, XI, YR, YI

3 Description

The method of evaluating y=x depends on the value of xr.
For xr≥0,
yr=xr+xr 2+xi 2 2,  yi=xi 2 yr .
For xr<0,
yi=sign xi×xr+xr 2+xi 2 2 ,  yr=xi 2 yi .
Overflow is avoided when squaring xi and xr by calling A02ABF to evaluate xr 2+xi 2.

4 References

Wilkinson J H and Reinsch C (1971) Handbook for Automatic Computation II, Linear Algebra Springer–Verlag

5 Arguments

1:   XR – REAL (KIND=nag_wp)Input
2:   XI – REAL (KIND=nag_wp)Input
On entry: xr and xi, the real and imaginary parts of x, respectively.
3:   YR – REAL (KIND=nag_wp)Output
4:   YI – REAL (KIND=nag_wp)Output
On exit: yr and yi, the real and imaginary parts of y, respectively.

6 Error Indicators and Warnings

None.

7 Accuracy

The result should be correct to machine precision.

8 Parallelism and Performance

A02AAF is not threaded in any implementation.

9 Further Comments

The time taken by A02AAF is negligible.

10 Example

This example finds the square root of -1.7+2.6 i.

10.1 Program Text

Program Text (a02aafe.f90)

10.2 Program Data

Program Data (a02aafe.d)

10.3 Program Results

Program Results (a02aafe.r)

A02 Chapter Contents
A02 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


A02ABF : NAG Library, Mark 26

A02 Chapter Contents
A02 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

A02ABF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

A02ABF returns the value of the modulus of the complex number x=xr,xi.

2 Specification

FUNCTION A02ABF ( XR, XI)
REAL (KIND=nag_wp) A02ABF
REAL (KIND=nag_wp) XR, XI

3 Description

The function evaluates xr 2+xi 2 by using a⁢1+ ba 2 where a is the larger of xr and xi, and b is the smaller of xr and xi. This ensures against unnecessary overflow and loss of accuracy when calculating xr 2+xi 2.

4 References

Wilkinson J H and Reinsch C (1971) Handbook for Automatic Computation II, Linear Algebra Springer–Verlag

5 Arguments

1:   XR – REAL (KIND=nag_wp)Input
2:   XI – REAL (KIND=nag_wp)Input
On entry: xr and xi, the real and imaginary parts of x, respectively.

6 Error Indicators and Warnings

None.

7 Accuracy

The result should be correct to machine precision.

8 Parallelism and Performance

A02ABF is not threaded in any implementation.

9 Further Comments

None.

10 Example

This example finds the modulus of -1.7+2.6 i.

10.1 Program Text

Program Text (a02abfe.f90)

10.2 Program Data

Program Data (a02abfe.d)

10.3 Program Results

Program Results (a02abfe.r)

A02 Chapter Contents
A02 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


A02ACF : NAG Library, Mark 26

A02 Chapter Contents
A02 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

A02ACF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

A02ACF divides one complex number, x=xr,xi, by a second complex number, y=yr,yi, returning the result in z=zr,zi.

2 Specification

SUBROUTINE A02ACF ( XR, XI, YR, YI, ZR, ZI)
REAL (KIND=nag_wp) XR, XI, YR, YI, ZR, ZI

3 Description

The result z is calculated using Smith's algorithm with scaling, from Li et al. (2002), which ensures that no unnecessary overflow or underflow occurs at intermediate stages of the computation.

4 References

Li X S, Demmel J W, Bailey D H, Henry G, Hida Y, Iskandar J, Kahan W, Kapur A, Martin M C, Tung T and Yoo D J (2002) Design, implementation and testing of extended and mixed precision BLAS ACM Trans. Math. Soft. 28(2) 152–205

5 Arguments

1:   XR – REAL (KIND=nag_wp)Input
2:   XI – REAL (KIND=nag_wp)Input
On entry: xr and xi, the real and imaginary parts of x, respectively.
3:   YR – REAL (KIND=nag_wp)Input
4:   YI – REAL (KIND=nag_wp)Input
On entry: yr and yi, the real and imaginary parts of y, respectively.
5:   ZR – REAL (KIND=nag_wp)Output
6:   ZI – REAL (KIND=nag_wp)Output
On exit: zr and zi, the real and imaginary parts of z, respectively.

6 Error Indicators and Warnings

None.

7 Accuracy

The result should be correct to machine precision.

8 Parallelism and Performance

A02ACF is not threaded in any implementation.

9 Further Comments

The time taken by A02ACF is negligible.
This routine must not be called with YR=0.0 and YI=0.0.

10 Example

This example finds the value of -1.7+2.6 i/-3.1-0.9 i.

10.1 Program Text

Program Text (a02acfe.f90)

10.2 Program Data

Program Data (a02acfe.d)

10.3 Program Results

Program Results (a02acfe.r)

A02 Chapter Contents
A02 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


A02 Chapter Contents : NAG Library Manual, Mark 26

A02 Chapter Introduction
NAG Library Manual

NAG Library Chapter Contents

A02 – Complex Arithmetic

A02 Chapter Introduction – a description of the Chapter and an overview of the algorithms available

Routine Name | Mark of Introduction | Purpose
A02AAF Example Text Example Data | 2 | nagf_complex_sqrt Square root of complex number
A02ABF Example Text Example Data | 2 | nagf_complex_abs Modulus of complex number
A02ACF Example Text Example Data | 2 | nagf_complex_divide Quotient of two complex numbers
A02 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


A02 Chapter Introduction : NAG Library, Mark 26

A02 Chapter Contents
NAG Library Manual

NAG Library Chapter Introduction

A02 – Complex Arithmetic

▸▿ Contents

1 Scope of the Chapter
2 Background to the Problems
3 Recommendations on Choice and Use of Available Routines
4 Functionality Index
5 Auxiliary Routines Associated with Library Routine Arguments
6 Routines Withdrawn or Scheduled for Withdrawal

1 Scope of the Chapter

This chapter provides facilities for arithmetic operations involving complex numbers.

2 Background to the Problems

Of the several representations used for complex numbers, perhaps the most common is a+ib, where a and b are real numbers, and i represents the imaginary number -1. The number a is the real part, and ib the imaginary part.
For the basic arithmetic operations of addition, subtraction and multiplication, the inclusion of routines was not considered worthwhile. Their coding would be short and no special techniques need be used.
In complex number operations of a more complicated nature, special precautions may have to be taken to avoid unnecessary overflow and underflow at intermediate stages of the computation. This has led to the inclusion of routines in this chapter.

3 Recommendations on Choice and Use of Available Routines

The routines were originally written for use by NAG Library routines which compute eigensystems of real and complex matrices (see Chapter F02). They may, however, be of general use to programmers using complex numbers.
Fortran programmers may prefer to use the COMPLEX facilities in that language rather than carrying the real and imaginary parts of the numbers in different variables.

4 Functionality Index

Complex numbers,
division A02ACF
modulus A02ABF
square root A02AAF

5 Auxiliary Routines Associated with Library Routine Arguments

None.

6 Routines Withdrawn or Scheduled for Withdrawal

None.
A02 Chapter Contents
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


C02AFF : NAG Library, Mark 26

C02 Chapter Contents
C02 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

C02AFF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

C02AFF finds all the roots of a complex polynomial equation, using a variant of Laguerre's method.

2 Specification

SUBROUTINE C02AFF ( A, N, SCAL, Z, W, IFAIL)
INTEGER | N, IFAIL
REAL (KIND=nag_wp) | A(2,N+1), Z(2,N), W(4*(N+1))
LOGICAL | SCAL

3 Description

C02AFF attempts to find all the roots of the nth degree complex polynomial equation
P z = a 0 zn + a 1 z n-1 + a 2 z n-2 + ⋯ + a n-1 z + an = 0 .
The roots are located using a modified form of Laguerre's method, originally proposed by Smith (1967).
The method of Laguerre (see Wilkinson (1965)) can be described by the iterative scheme
L zk = z k+1 - zk = -n P zk P′ zk ± H zk ,
where H zk=n-1n-1 P′zk 2-nP zk P′′zk and z 0 is specified.
The sign in the denominator is chosen so that the modulus of the Laguerre step at zk, viz. L zk, is as small as possible. The method can be shown to be cubically convergent for isolated roots (real or complex) and linearly convergent for multiple roots.
The routine generates a sequence of iterates z 1,z 2,z 3,…, such that P z k+1<P zk and ensures that z k+1+L z k+1 ‘roughly’ lies inside a circular region of radius F about zk known to contain a zero of P z; that is, L z k+1≤F, where F denotes the Fejér bound (see Marden (1966)) at the point zk. Following Smith (1967), F is taken to be min B,1.445 nR , where B is an upper bound for the magnitude of the smallest zero given by
B = 1.0001 × min n L zk ,r 1, an / a 0 1/n ,
r 1 is the zero X of smaller magnitude of the quadratic equation
P′′ zk 2 n n-1 X 2 + P′ zk n X + 12 P zk = 0
and the Cauchy lower bound R for the smallest zero is computed (using Newton's Method) as the positive root of the polynomial equation
a 0 zn + a 1 z n-1 + a 2 z n-2 +⋯+ a n-1 z - an = 0 .
Starting from the origin, successive iterates are generated according to the rule z k+1 = zk + L zk , for k=1 , 2 , 3 ,…, and L zk is ‘adjusted’ so that P z k+1 < P zk and L z k+1 ≤ F . The iterative procedure terminates if P z k+1 is smaller in absolute value than the bound on the rounding error in P z k+1 and the current iterate zp = z k+1 is taken to be a zero of P z. The deflated polynomial P~ z = P z / z-zp of degree n-1 is then formed, and the above procedure is repeated on the deflated polynomial until n<3, whereupon the remaining roots are obtained via the ‘standard’ closed formulae for a linear (n=1) or quadratic (n=2) equation.
Note that C02AHF, C02AMF and C02ANF can be used to obtain the roots of a quadratic, cubic (n=3) and quartic (n=4) polynomial, respectively.

4 References

Marden M (1966) Geometry of polynomials Mathematical Surveys 3 American Mathematical Society, Providence, RI
Smith B T (1967) ZERPOL: a zero finding algorithm for polynomials using Laguerre's method Technical Report Department of Computer Science, University of Toronto, Canada
Thompson K W (1991) Error analysis for polynomial solvers Fortran Journal (Volume 3) 3 10–13
Wilkinson J H (1965) The Algebraic Eigenvalue Problem Oxford University Press, Oxford

5 Arguments

1:   A 2 N+1 – REAL (KIND=nag_wp) arrayInput
On entry: if A is declared with bounds 2,0:N, then A 1 i and A 2 i must contain the real and imaginary parts of ai (i.e., the coefficient of z n-i), for i=0,1,…,n.
Constraint: A 10 ≠ 0.0 or A 20 ≠ 0.0 .
2:   N – INTEGERInput
On entry: n, the degree of the polynomial.
Constraint: N≥1.
3:   SCAL – LOGICALInput
On entry: indicates whether or not the polynomial is to be scaled. See Section 9 for advice on when it may be preferable to set SCAL=.FALSE. and for a description of the scaling strategy.
Suggested value: SCAL=.TRUE..
4:   Z 2 N – REAL (KIND=nag_wp) arrayOutput
On exit: the real and imaginary parts of the roots are stored in Z 1 i and Z 2 i respectively, for i=1,2,…,n.
5:   W 4×N+1 – REAL (KIND=nag_wp) arrayWorkspace
6:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, | A 10=0.0 and A 20=0.0,
or | N<1.
IFAIL=2
The iterative procedure has failed to converge. This error is very unlikely to occur. If it does, please contact NAG, as some basic assumption for the arithmetic has been violated. See also Section 9.
IFAIL=3
Either overflow or underflow prevents the evaluation of P z near some of its zeros. This error is very unlikely to occur. If it does, please contact NAG. See also Section 9.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

All roots are evaluated as accurately as possible, but because of the inherent nature of the problem complete accuracy cannot be guaranteed. See also Section 10.

8 Parallelism and Performance

C02AFF is not threaded in any implementation.

9 Further Comments

If SCAL=.TRUE., then a scaling factor for the coefficients is chosen as a power of the base b of the machine so that the largest coefficient in magnitude approaches thresh=b emax-p. You should note that no scaling is performed if the largest coefficient in magnitude exceeds thresh, even if SCAL=.TRUE.. (b, emax and p are defined in Chapter X02.)
However, with SCAL=.TRUE., overflow may be encountered when the input coefficients a 0,a 1,a 2,…,an vary widely in magnitude, particularly on those machines for which b 4 p overflows. In such cases, SCAL should be set to .FALSE. and the coefficients scaled so that the largest coefficient in magnitude does not exceed b emax-2 p .
Even so, the scaling strategy used by C02AFF is sometimes insufficient to avoid overflow and/or underflow conditions. In such cases, you are recommended to scale the independent variable z so that the disparity between the largest and smallest coefficient in magnitude is reduced. That is, use the routine to locate the zeros of the polynomial dP cz for some suitable values of c and d. For example, if the original polynomial was P z=2-100 i+2100z 20, then choosing c=2-10 and d=2100, for instance, would yield the scaled polynomial i+z 20, which is well-behaved relative to overflow and underflow and has zeros which are 210 times those of P z.
If the routine fails with IFAIL=2 or 3, then the real and imaginary parts of any roots obtained before the failure occurred are stored in Z in the reverse order in which they were found. Let nR denote the number of roots found before the failure occurred. Then Z 1 n and Z 2 n contain the real and imaginary parts of the first root found, Z 1 n-1 and Z 2 n-1 contain the real and imaginary parts of the second root found, … , Z 1 n- nR+1 and Z 2 n- nR+1 contain the real and imaginary parts of the nR th root found. After the failure has occurred, the remaining 2× n-nR elements of Z contain a large negative number (equal to -1 / X02AMF×2 ).

10 Example

For this routine two examples are presented. There is a single example program for C02AFF, with a main program and the code to solve the two example problems given in the subroutines EX1 and EX2.
Example 1 (EX1)
This example finds the roots of the polynomial
a 0 z 5 + a 1 z 4 + a 2 z 3 + a 3 z 2 + a 4 z+a 5 = 0 ,
where a 0=5.0+6.0 i , a 1=30.0+20.0 i , a 2=- 0.2+6.0 i , a 3=50.0+100000.0 i , a 4=- 2.0-40.0 i and a 5=10.0+1.0 i .
Example 2 (EX2)
This example solves the same problem as subroutine EX1, but in addition attempts to estimate the accuracy of the computed roots using a perturbation analysis. Further details can be found in Thompson (1991).

10.1 Program Text

Program Text (c02affe.f90)

10.2 Program Data

Program Data (c02affe.d)

10.3 Program Results

Program Results (c02affe.r)

C02 Chapter Contents
C02 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


C02AGF : NAG Library, Mark 26

C02 Chapter Contents
C02 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

C02AGF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

C02AGF finds all the roots of a real polynomial equation, using a variant of Laguerre's method.

2 Specification

SUBROUTINE C02AGF ( A, N, SCAL, Z, W, IFAIL)
INTEGER | N, IFAIL
REAL (KIND=nag_wp) | A(N+1), Z(2,N), W(2*(N+1))
LOGICAL | SCAL

3 Description

C02AGF attempts to find all the roots of the nth degree real polynomial equation
P z = a 0 zn + a 1 z n-1 + a 2 z n-2 + ⋯ + a n-1 z + an = 0 .
The roots are located using a modified form of Laguerre's method, originally proposed by Smith (1967).
The method of Laguerre (see Wilkinson (1965)) can be described by the iterative scheme
L zk = z k+1 - zk = -n P zk P′ zk ± H zk ,
where H zk=n-1n-1 P′zk 2-nP zk P′′zk and z 0 is specified.
The sign in the denominator is chosen so that the modulus of the Laguerre step at zk, viz. L zk, is as small as possible. The method can be shown to be cubically convergent for isolated roots (real or complex) and linearly convergent for multiple roots.
The routine generates a sequence of iterates z 1,z 2,z 3,…, such that P z k+1<P zk and ensures that z k+1+L z k+1 ‘roughly’ lies inside a circular region of radius F about zk known to contain a zero of P z; that is, L z k+1≤F, where F denotes the Fejér bound (see Marden (1966)) at the point zk. Following Smith (1967), F is taken to be min B,1.445 nR , where B is an upper bound for the magnitude of the smallest zero given by
B = 1.0001 × min n L zk ,r 1, an / a 0 1/n ,
r 1 is the zero X of smaller magnitude of the quadratic equation
P′′ zk 2 n n-1 X 2 + P′ zk n X + 12 P zk = 0
and the Cauchy lower bound R for the smallest zero is computed (using Newton's Method) as the positive root of the polynomial equation
a 0 zn + a 1 z n-1 + a 2 z n-2 +⋯+ a n-1 z - an = 0 .
Starting from the origin, successive iterates are generated according to the rule z k+1 = zk + L zk , for k=1 , 2 , 3 ,…, and L zk is ‘adjusted’ so that P z k+1 < P zk and L z k+1 ≤ F . The iterative procedure terminates if P z k+1 is smaller in absolute value than the bound on the rounding error in P z k+1 and the current iterate zp = z k+1 is taken to be a zero of P z (as is its conjugate z-p if zp is complex). The deflated polynomial P~ z = P z / z-zp of degree n-1 if zp is real ( P~ z = P z / z-zp z-z-p of degree n-2 if zp is complex) is then formed, and the above procedure is repeated on the deflated polynomial until n<3, whereupon the remaining roots are obtained via the ‘standard’ closed formulae for a linear (n=1) or quadratic (n=2) equation.
Note that C02AJF, C02AKF and C02ALF can be used to obtain the roots of a quadratic, cubic (n=3) and quartic (n=4) polynomial, respectively.

4 References

Marden M (1966) Geometry of polynomials Mathematical Surveys 3 American Mathematical Society, Providence, RI
Smith B T (1967) ZERPOL: a zero finding algorithm for polynomials using Laguerre's method Technical Report Department of Computer Science, University of Toronto, Canada
Thompson K W (1991) Error analysis for polynomial solvers Fortran Journal (Volume 3) 3 10–13
Wilkinson J H (1965) The Algebraic Eigenvalue Problem Oxford University Press, Oxford

5 Arguments

1:   A N+1 – REAL (KIND=nag_wp) arrayInput
On entry: if A is declared with bounds 0:N, then A i must contain ai (i.e., the coefficient of z n-i ) , for i=0,1,…,n.
Constraint: A 0 ≠ 0.0 .
2:   N – INTEGERInput
On entry: n, the degree of the polynomial.
Constraint: N≥1.
3:   SCAL – LOGICALInput
On entry: indicates whether or not the polynomial is to be scaled. See Section 9 for advice on when it may be preferable to set SCAL=.FALSE. and for a description of the scaling strategy.
Suggested value: SCAL=.TRUE..
4:   Z 2 N – REAL (KIND=nag_wp) arrayOutput
On exit: the real and imaginary parts of the roots are stored in Z 1 i and Z 2 i respectively, for i=1,2,…,n. Complex conjugate pairs of roots are stored in consecutive pairs of elements of Z; that is, Z 1 i+1 = Z 1 i and Z 2 i+1 = -Z 2 i .
5:   W 2×N+1 – REAL (KIND=nag_wp) arrayWorkspace
6:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, | A 0=0.0,
or | N<1.
IFAIL=2
The iterative procedure has failed to converge. This error is very unlikely to occur. If it does, please contact NAG, as some basic assumption for the arithmetic has been violated. See also Section 9.
IFAIL=3
Either overflow or underflow prevents the evaluation of P z near some of its zeros. This error is very unlikely to occur. If it does, please contact NAG. See also Section 9.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

All roots are evaluated as accurately as possible, but because of the inherent nature of the problem complete accuracy cannot be guaranteed. See also Section 10.

8 Parallelism and Performance

C02AGF is not threaded in any implementation.

9 Further Comments

If SCAL=.TRUE., then a scaling factor for the coefficients is chosen as a power of the base b of the machine so that the largest coefficient in magnitude approaches thresh=b emax-p. You should note that no scaling is performed if the largest coefficient in magnitude exceeds thresh, even if SCAL=.TRUE.. (b, emax and p are defined in Chapter X02.)
However, with SCAL=.TRUE., overflow may be encountered when the input coefficients a 0,a 1,a 2,…,an vary widely in magnitude, particularly on those machines for which b 4 p overflows. In such cases, SCAL should be set to .FALSE. and the coefficients scaled so that the largest coefficient in magnitude does not exceed b emax-2 p .
Even so, the scaling strategy used by C02AGF is sometimes insufficient to avoid overflow and/or underflow conditions. In such cases, you are recommended to scale the independent variable z so that the disparity between the largest and smallest coefficient in magnitude is reduced. That is, use the routine to locate the zeros of the polynomial dP cz for some suitable values of c and d. For example, if the original polynomial was P z=2-100+2100z 20, then choosing c=2-10 and d=2100, for instance, would yield the scaled polynomial 1+z 20, which is well-behaved relative to overflow and underflow and has zeros which are 210 times those of P z.
If the routine fails with IFAIL=2 or 3, then the real and imaginary parts of any roots obtained before the failure occurred are stored in Z in the reverse order in which they were found. Let nR denote the number of roots found before the failure occurred. Then Z 1 n and Z 2 n contain the real and imaginary parts of the first root found, Z 1 n-1 and Z 2 n-1 contain the real and imaginary parts of the second root found, … , Z 1 n- nR+1 and Z 2 n- nR+1 contain the real and imaginary parts of the nR th root found. After the failure has occurred, the remaining 2× n-nR elements of Z contain a large negative number (equal to -1 / X02AMF×2 ).

10 Example

For this routine two examples are presented. There is a single example program for C02AGF, with a main program and the code to solve the two example problems given in the subroutines EX1 and EX2.
Example 1 (EX1)
This example finds the roots of the fifth degree polynomial
z 5 + 2⁢z 4 + 3⁢z 3 + 4⁢z 2 + 5 z + 6=0 .
Example 2 (EX2)
This example solves the same problem as subroutine EX1, but in addition attempts to estimate the accuracy of the computed roots using a perturbation analysis. Further details can be found in Thompson (1991).

10.1 Program Text

Program Text (c02agfe.f90)

10.2 Program Data

Program Data (c02agfe.d)

10.3 Program Results

Program Results (c02agfe.r)

C02 Chapter Contents
C02 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


C02AHF : NAG Library, Mark 26

C02 Chapter Contents
C02 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

C02AHF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

C02AHF determines the roots of a quadratic equation with complex coefficients.

2 Specification

SUBROUTINE C02AHF ( AR, AI, BR, BI, CR, CI, ZSM, ZLG, IFAIL)
INTEGER | IFAIL
REAL (KIND=nag_wp) | AR, AI, BR, BI, CR, CI, ZSM(2), ZLG(2)

3 Description

C02AHF attempts to find the roots of the quadratic equation a z 2+bz+c=0 (where a, b and c are complex coefficients), by carefully evaluating the ‘standard’ closed formula
z=-b±b 2-4 ac 2 a .
It is based on the routine CQDRTC from Smith (1967).
Note: it is not necessary to scale the coefficients prior to calling the routine.

4 References

Smith B T (1967) ZERPOL: a zero finding algorithm for polynomials using Laguerre's method Technical Report Department of Computer Science, University of Toronto, Canada

5 Arguments

1:   AR – REAL (KIND=nag_wp)Input
2:   AI – REAL (KIND=nag_wp)Input
On entry: AR and AI must contain the real and imaginary parts respectively of a, the coefficient of z 2.
3:   BR – REAL (KIND=nag_wp)Input
4:   BI – REAL (KIND=nag_wp)Input
On entry: BR and BI must contain the real and imaginary parts respectively of b, the coefficient of z.
5:   CR – REAL (KIND=nag_wp)Input
6:   CI – REAL (KIND=nag_wp)Input
On entry: CR and CI must contain the real and imaginary parts respectively of c, the constant coefficient.
7:   ZSM 2 – REAL (KIND=nag_wp) arrayOutput
On exit: the real and imaginary parts of the smallest root in magnitude are stored in ZSM 1 and ZSM 2 respectively.
8:   ZLG 2 – REAL (KIND=nag_wp) arrayOutput
On exit: the real and imaginary parts of the largest root in magnitude are stored in ZLG 1 and ZLG 2 respectively.
9:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, AR,AI=0,0. In this case, ZSM 1 and ZSM 2 contain the real and imaginary parts respectively of the root -c/b.
IFAIL=2
On entry, AR,AI=0,0 and BR,BI=0,0. In this case, ZSM 1 contains the largest machine representable number (see X02ALF) and ZSM 2 contains zero.
IFAIL=3
On entry, AR,AI=0,0 and the root -c/b overflows. In this case, ZSM 1 contains the largest machine representable number (see X02ALF) and ZSM 2 contains zero.
IFAIL=4
On entry, CR,CI=0,0 and the root -b/a overflows. In this case, both ZSM 1 and ZSM 2 contain zero.
IFAIL=5
On entry, b~ is so large that b~ 2 is indistinguishable from b~ 2 - 4 a~ c~ and the root -b / a overflows, where b~ = max BR,BI , a~ = max AR,AI and c~ = max CR,CI . In this case, ZSM 1 and ZSM 2 contain the real and imaginary parts respectively of the root -c / b .
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.
If IFAIL>0 on exit, then ZLG 1 contains the largest machine representable number (see X02ALF) and ZLG 2 contains zero.

7 Accuracy

If IFAIL=0 on exit, then the computed roots should be accurate to within a small multiple of the machine precision except when underflow (or overflow) occurs, in which case the true roots are within a small multiple of the underflow (or overflow) threshold of the machine.

8 Parallelism and Performance

C02AHF is not threaded in any implementation.

9 Further Comments

None.

10 Example

This example finds the roots of the quadratic equation z 2-3.0-1.0 i z+8.0+1.0 i=0.

10.1 Program Text

Program Text (c02ahfe.f90)

10.2 Program Data

Program Data (c02ahfe.d)

10.3 Program Results

Program Results (c02ahfe.r)

C02 Chapter Contents
C02 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


C02AJF : NAG Library, Mark 26

C02 Chapter Contents
C02 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

C02AJF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

C02AJF determines the roots of a quadratic equation with real coefficients.

2 Specification

SUBROUTINE C02AJF ( A, B, C, ZSM, ZLG, IFAIL)
INTEGER | IFAIL
REAL (KIND=nag_wp) | A, B, C, ZSM(2), ZLG(2)

3 Description

C02AJF attempts to find the roots of the quadratic equation a z 2+bz+c=0 (where a, b and c are real coefficients), by carefully evaluating the ‘standard’ closed formula
z=-b±b 2-4 ac 2 a .
It is based on the routine QDRTC from Smith (1967).
Note: it is not necessary to scale the coefficients prior to calling the routine.

4 References

Smith B T (1967) ZERPOL: a zero finding algorithm for polynomials using Laguerre's method Technical Report Department of Computer Science, University of Toronto, Canada

5 Arguments

1:   A – REAL (KIND=nag_wp)Input
On entry: must contain a, the coefficient of z 2.
2:   B – REAL (KIND=nag_wp)Input
On entry: must contain b, the coefficient of z.
3:   C – REAL (KIND=nag_wp)Input
On entry: must contain c, the constant coefficient.
4:   ZSM 2 – REAL (KIND=nag_wp) arrayOutput
On exit: the real and imaginary parts of the smallest root in magnitude are stored in ZSM 1 and ZSM 2 respectively.
5:   ZLG 2 – REAL (KIND=nag_wp) arrayOutput
On exit: the real and imaginary parts of the largest root in magnitude are stored in ZLG 1 and ZLG 2 respectively.
6:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, A=0.0. In this case, ZSM 1 contains the root -c/b and ZSM 2 contains zero.
IFAIL=2
On entry, A=0.0 and B=0.0. In this case, ZSM 1 contains the largest machine representable number (see X02ALF) and ZSM 2 contains zero.
IFAIL=3
On entry, A=0.0 and the root -c/b overflows. In this case, ZSM 1 contains the largest machine representable number (see X02ALF) and ZSM 2 contains zero.
IFAIL=4
On entry, C=0.0 and the root -b/a overflows. In this case, both ZSM 1 and ZSM 2 contain zero.
IFAIL=5
On entry, b is so large that b 2 is indistinguishable from b 2-4 ac and the root -b/a overflows. In this case, ZSM 1 contains the root -c/b and ZSM 2 contains zero.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.
If IFAIL>0 on exit, then ZLG 1 contains the largest machine representable number (see X02ALF) and ZLG 2 contains zero.

7 Accuracy

If IFAIL=0 on exit, then the computed roots should be accurate to within a small multiple of the machine precision except when underflow (or overflow) occurs, in which case the true roots are within a small multiple of the underflow (or overflow) threshold of the machine.

8 Parallelism and Performance

C02AJF is not threaded in any implementation.

9 Further Comments

None.

10 Example

This example finds the roots of the quadratic equation z 2+3 z-10=0.

10.1 Program Text

Program Text (c02ajfe.f90)

10.2 Program Data

Program Data (c02ajfe.d)

10.3 Program Results

Program Results (c02ajfe.r)

C02 Chapter Contents
C02 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


C02AKF : NAG Library, Mark 26

C02 Chapter Contents
C02 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

C02AKF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

C02AKF determines the roots of a cubic equation with real coefficients.

2 Specification

SUBROUTINE C02AKF ( U, R, S, T, ZEROR, ZEROI, ERREST, IFAIL)
INTEGER | IFAIL
REAL (KIND=nag_wp) | U, R, S, T, ZEROR(3), ZEROI(3), ERREST(3)

3 Description

C02AKF attempts to find the roots of the cubic equation
u z 3+r z 2+sz+t=0,
where u, r, s and t are real coefficients with u≠0. The roots are located by finding the eigenvalues of the associated 3 by 3 (upper Hessenberg) companion matrix H given by
H= 0 0 -t/u 1 0 -s/u 0 1 -r/u .
The eigenvalues are obtained by a call to F08PEF (DHSEQR). Further details can be found in Section 9.
To obtain the roots of a quartic equation, C02ALF can be used.

4 References

Golub G H and Van Loan C F (1996) Matrix Computations (3rd Edition) Johns Hopkins University Press, Baltimore

5 Arguments

1:   U – REAL (KIND=nag_wp)Input
On entry: u, the coefficient of z 3.
Constraint: U≠0.0.
2:   R – REAL (KIND=nag_wp)Input
On entry: r, the coefficient of z 2.
3:   S – REAL (KIND=nag_wp)Input
On entry: s, the coefficient of z.
4:   T – REAL (KIND=nag_wp)Input
On entry: t, the constant coefficient.
5:   ZEROR 3 – REAL (KIND=nag_wp) arrayOutput
6:   ZEROI 3 – REAL (KIND=nag_wp) arrayOutput
On exit: ZEROR i and ZEROI i contain the real and imaginary parts, respectively, of the ith root.
7:   ERREST 3 – REAL (KIND=nag_wp) arrayOutput
On exit: ERREST i contains an approximate error estimate for the ith root.
8:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, U=0.0.
IFAIL=2
The companion matrix H cannot be formed without overflow.
IFAIL=3
The iterative procedure used to determine the eigenvalues has failed to converge.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

If IFAIL=0 on exit, then the ith computed root should have approximately log 10 ERREST i correct significant digits.

8 Parallelism and Performance

C02AKF is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
C02AKF makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The method used by the routine consists of the following steps, which are performed by routines from LAPACK in Chapter F08.
(a) | Form matrix H.
(b) | Apply a diagonal similarity transformation to H (to give H′).
(c) | Calculate the eigenvalues and Schur factorization of H′.
(d) | Calculate the left and right eigenvectors of H′.
(e) | Estimate reciprocal condition numbers for all the eigenvalues of H′.
(f) | Calculate approximate error estimates for all the eigenvalues of H′ (using the 1-norm).

10 Example

This example finds the roots of the cubic equation
z 3+3⁢z 2+9 z-13=0.

10.1 Program Text

Program Text (c02akfe.f90)

10.2 Program Data

Program Data (c02akfe.d)

10.3 Program Results

Program Results (c02akfe.r)

C02 Chapter Contents
C02 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


C02ALF : NAG Library, Mark 26

C02 Chapter Contents
C02 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

C02ALF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

C02ALF determines the roots of a quartic equation with real coefficients.

2 Specification

SUBROUTINE C02ALF ( E, A, B, C, D, ZEROR, ZEROI, ERREST, IFAIL)
INTEGER | IFAIL
REAL (KIND=nag_wp) | E, A, B, C, D, ZEROR(4), ZEROI(4), ERREST(4)

3 Description

C02ALF attempts to find the roots of the quartic equation
e z 4+a z 3+b z 2+cz+d=0,
where e, a, b, c and d are real coefficients with e≠0. The roots are located by finding the eigenvalues of the associated 4 by 4 (upper Hessenberg) companion matrix H given by
H= 0 0 0 -d/e 1 0 0 -c/e 0 1 0 -b/e 0 0 1 -a/e .
The eigenvalues are obtained by a call to F08PEF (DHSEQR). Further details can be found in Section 9.
To obtain the roots of a cubic equation, C02AKF can be used.

4 References

Golub G H and Van Loan C F (1996) Matrix Computations (3rd Edition) Johns Hopkins University Press, Baltimore

5 Arguments

1:   E – REAL (KIND=nag_wp)Input
On entry: e, the coefficient of z 4.
Constraint: E≠0.0.
2:   A – REAL (KIND=nag_wp)Input
On entry: a, the coefficient of z 3.
3:   B – REAL (KIND=nag_wp)Input
On entry: b, the coefficient of z 2.
4:   C – REAL (KIND=nag_wp)Input
On entry: c, the coefficient of z.
5:   D – REAL (KIND=nag_wp)Input
On entry: d, the constant coefficient.
6:   ZEROR 4 – REAL (KIND=nag_wp) arrayOutput
7:   ZEROI 4 – REAL (KIND=nag_wp) arrayOutput
On exit: ZEROR i and ZEROI i contain the real and imaginary parts, respectively, of the ith root.
8:   ERREST 4 – REAL (KIND=nag_wp) arrayOutput
On exit: ERREST i contains an approximate error estimate for the ith root.
9:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, E=0.0.
IFAIL=2
The companion matrix H cannot be formed without overflow.
IFAIL=3
The iterative procedure used to determine the eigenvalues has failed to converge.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

If IFAIL=0 on exit, then the ith computed root should have approximately log 10 ERREST i correct significant digits.

8 Parallelism and Performance

C02ALF is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
C02ALF makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The method used by the routine consists of the following steps, which are performed by routines from LAPACK in Chapter F08.
(a) | Form matrix H.
(b) | Apply a diagonal similarity transformation to H (to give H′).
(c) | Calculate the eigenvalues and Schur factorization of H′.
(d) | Calculate the left and right eigenvectors of H′.
(e) | Estimate reciprocal condition numbers for all the eigenvalues of H′.
(f) | Calculate approximate error estimates for all the eigenvalues of H′ (using the 1-norm).

10 Example

This example finds the roots of the quartic equation
z 4+2⁢z 3+6⁢z 2-8 z-40=0.

10.1 Program Text

Program Text (c02alfe.f90)

10.2 Program Data

Program Data (c02alfe.d)

10.3 Program Results

Program Results (c02alfe.r)

C02 Chapter Contents
C02 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


C02AMF : NAG Library, Mark 26

C02 Chapter Contents
C02 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

C02AMF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

C02AMF determines the roots of a cubic equation with complex coefficients.

2 Specification

SUBROUTINE C02AMF ( U, R, S, T, ZEROR, ZEROI, ERREST, IFAIL)
INTEGER | IFAIL
REAL (KIND=nag_wp) | ZEROR(3), ZEROI(3), ERREST(3)
COMPLEX (KIND=nag_wp) | U, R, S, T

3 Description

C02AMF attempts to find the roots of the cubic equation
u z 3+r z 2+sz+t=0,
where u, r, s and t are complex coefficients with u≠0. The roots are located by finding the eigenvalues of the associated 3 by 3 (upper Hessenberg) companion matrix H given by
H= 0 0 -t/u 1 0 -s/u 0 1 -r/u .
The eigenvalues are obtained by a call to F08PSF (ZHSEQR). Further details can be found in Section 9.
To obtain the roots of a quadratic equation, C02AHF can be used.

4 References

Golub G H and Van Loan C F (1996) Matrix Computations (3rd Edition) Johns Hopkins University Press, Baltimore

5 Arguments

1:   U – COMPLEX (KIND=nag_wp)Input
On entry: u, the coefficient of z 3.
Constraint: U≠0.0,0.0.
2:   R – COMPLEX (KIND=nag_wp)Input
On entry: r, the coefficient of z 2.
3:   S – COMPLEX (KIND=nag_wp)Input
On entry: s, the coefficient of z.
4:   T – COMPLEX (KIND=nag_wp)Input
On entry: t, the constant coefficient.
5:   ZEROR 3 – REAL (KIND=nag_wp) arrayOutput
6:   ZEROI 3 – REAL (KIND=nag_wp) arrayOutput
On exit: ZEROR i and ZEROI i contain the real and imaginary parts, respectively, of the ith root.
7:   ERREST 3 – REAL (KIND=nag_wp) arrayOutput
On exit: ERREST i contains an approximate error estimate for the ith root.
8:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, U=0.0,0.0.
IFAIL=2
The companion matrix H cannot be formed without overflow.
IFAIL=3
The iterative procedure used to determine the eigenvalues has failed to converge.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

If IFAIL=0 on exit, then the ith computed root should have approximately log 10 ERREST i correct significant digits.

8 Parallelism and Performance

C02AMF is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
C02AMF makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The method used by the routine consists of the following steps, which are performed by routines from LAPACK in Chapter F08.
(a) | Form matrix H.
(b) | Apply a diagonal similarity transformation to H (to give H′).
(c) | Calculate the eigenvalues and Schur factorization of H′.
(d) | Calculate the left and right eigenvectors of H′.
(e) | Estimate reciprocal condition numbers for all the eigenvalues of H′.
(f) | Calculate approximate error estimates for all the eigenvalues of H′ (using the 1-norm).

10 Example

This example finds the roots of the cubic equation
z 3-2-3 i z 2+5+14 i z-40+5 i=0.

10.1 Program Text

Program Text (c02amfe.f90)

10.2 Program Data

Program Data (c02amfe.d)

10.3 Program Results

Program Results (c02amfe.r)

C02 Chapter Contents
C02 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


C02ANF : NAG Library, Mark 26

C02 Chapter Contents
C02 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

C02ANF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

C02ANF determines the roots of a quartic equation with complex coefficients.

2 Specification

SUBROUTINE C02ANF ( E, A, B, C, D, ZEROR, ZEROI, ERREST, IFAIL)
INTEGER | IFAIL
REAL (KIND=nag_wp) | ZEROR(4), ZEROI(4), ERREST(4)
COMPLEX (KIND=nag_wp) | E, A, B, C, D

3 Description

C02ANF attempts to find the roots of the quartic equation
e z 4+a z 3+b z 2+cz+d=0,
where e, a, b, c and d are complex coefficients with e≠0. The roots are located by finding the eigenvalues of the associated 4 by 4 (upper Hessenberg) companion matrix H given by
H= 0 0 0 -d/e 1 0 0 -c/e 0 1 0 -b/e 0 0 1 -a/e .
The eigenvalues are obtained by a call to F08PSF (ZHSEQR). Further details can be found in Section 9.
To obtain the roots of a cubic equation, C02AMF can be used.

4 References

Golub G H and Van Loan C F (1996) Matrix Computations (3rd Edition) Johns Hopkins University Press, Baltimore

5 Arguments

1:   E – COMPLEX (KIND=nag_wp)Input
On entry: e, the coefficient of z 4.
Constraint: E≠0.0,0.0.
2:   A – COMPLEX (KIND=nag_wp)Input
On entry: a, the coefficient of z 3.
3:   B – COMPLEX (KIND=nag_wp)Input
On entry: b, the coefficient of z 2.
4:   C – COMPLEX (KIND=nag_wp)Input
On entry: c, the coefficient of z.
5:   D – COMPLEX (KIND=nag_wp)Input
On entry: d, the constant coefficient.
6:   ZEROR 4 – REAL (KIND=nag_wp) arrayOutput
7:   ZEROI 4 – REAL (KIND=nag_wp) arrayOutput
On exit: ZEROR i and ZEROI i contain the real and imaginary parts, respectively, of the ith root.
8:   ERREST 4 – REAL (KIND=nag_wp) arrayOutput
On exit: ERREST i contains an approximate error estimate for the ith root.
9:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, E=0.0,0.0.
IFAIL=2
The companion matrix H cannot be formed without overflow.
IFAIL=3
The iterative procedure used to determine the eigenvalues has failed to converge.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

If IFAIL=0 on exit, then the ith computed root should have approximately log 10 ERREST i correct significant digits.

8 Parallelism and Performance

C02ANF is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
C02ANF makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The method used by the routine consists of the following steps, which are performed by routines from LAPACK in Chapter F08.
(a) | Form matrix H.
(b) | Apply a diagonal similarity transformation to H (to give H′).
(c) | Calculate the eigenvalues and Schur factorization of H′.
(d) | Calculate the left and right eigenvectors of H′.
(e) | Estimate reciprocal condition numbers for all the eigenvalues of H′.
(f) | Calculate approximate error estimates for all the eigenvalues of H′ (using the 1-norm).

10 Example

This example finds the roots of the quartic equation
z 4+16 i z 2-8-8 i z-65=0.

10.1 Program Text

Program Text (c02anfe.f90)

10.2 Program Data

Program Data (c02anfe.d)

10.3 Program Results

Program Results (c02anfe.r)

C02 Chapter Contents
C02 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


C02 Chapter Contents : NAG Library Manual, Mark 26

C02 Chapter Introduction
NAG Library Manual

NAG Library Chapter Contents

C02 – Zeros of Polynomials

C02 Chapter Introduction – a description of the Chapter and an overview of the algorithms available

Routine Name | Mark of Introduction | Purpose
C02AFF Example Text Example Data | 14 | nagf_zeros_poly_complex All zeros of complex polynomial, modified Laguerre's method
C02AGF Example Text Example Data | 13 | nagf_zeros_poly_real All zeros of real polynomial, modified Laguerre's method
C02AHF Example Text Example Data | 14 | nagf_zeros_quadratic_complex All zeros of complex quadratic equation
C02AJF Example Text Example Data | 14 | nagf_zeros_quadratic_real All zeros of real quadratic equation
C02AKF Example Text Example Data | 20 | nagf_zeros_cubic_real All zeros of real cubic equation
C02ALF Example Text Example Data | 20 | nagf_zeros_quartic_real All zeros of real quartic equation
C02AMF Example Text Example Data | 20 | nagf_zeros_cubic_complex All zeros of complex cubic equation
C02ANF Example Text Example Data | 20 | nagf_zeros_quartic_complex All zeros of complex quartic equation
C02 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


C02 Chapter Introduction : NAG Library, Mark 26

C02 Chapter Contents
NAG Library Manual

NAG Library Chapter Introduction

C02 – Zeros of Polynomials

▸▿ Contents

1 Scope of the Chapter
2 Background to the Problems
3 Recommendations on Choice and Use of Available Routines
4 Auxiliary Routines Associated with Library Routine Arguments
5 Routines Withdrawn or Scheduled for Withdrawal
6 References

1 Scope of the Chapter

This chapter is concerned with computing the zeros of a polynomial with real or complex coefficients.

2 Background to the Problems

Let f z be a polynomial of degree n with complex coefficients ai:
f z≡a 0 zn+a 1 z n-1+a 2 z n-2+⋯+a n-1 z+an,  a 0≠0.
A complex number z 1 is called a zero of f z (or equivalently a root of the equation f z=0), if
f z 1=0.
If z 1 is a zero, then f z can be divided by a factor z-z 1:
f z=z-z 1 f 1 z (1)
where f 1 z is a polynomial of degree n-1. By the Fundamental Theorem of Algebra, a polynomial f z always has a zero, and so the process of dividing out factors z-zi can be continued until we have a complete factorization of f z:
f z≡a 0 z-z 1z-z 2…z-zn.
Here the complex numbers z 1,z 2,…,zn are the zeros of f z; they may not all be distinct, so it is sometimes more convenient to write
f z≡a 0 z-z 1 m 1z-z 2 m 2…z-zk mk,  k≤n,
with distinct zeros z 1,z 2,…,zk and multiplicities mi≥1. If mi=1, zi is called a simple or isolated zero; if mi>1, zi is called a multiple or repeated zero; a multiple zero is also a zero of the derivative of f z.
If the coefficients of f z are all real, then the zeros of f z are either real or else occur as pairs of conjugate complex numbers x+iy and x-iy. A pair of complex conjugate zeros are the zeros of a quadratic factor of f z, z 2+rz+s, with real coefficients r and s.
Mathematicians are accustomed to thinking of polynomials as pleasantly simple functions to work with. However, the problem of numerically computing the zeros of an arbitrary polynomial is far from simple. A great variety of algorithms have been proposed, of which a number have been widely used in practice; for a fairly comprehensive survey, see Householder (1970). All general algorithms are iterative. Most converge to one zero at a time; the corresponding factor can then be divided out as in equation (1) above – this process is called deflation or, loosely, dividing out the zero – and the algorithm can be applied again to the polynomial f 1 z. A pair of complex conjugate zeros can be divided out together – this corresponds to dividing f z by a quadratic factor.
Whatever the theoretical basis of the algorithm, a number of practical problems arise; for a thorough discussion of some of them see Peters and Wilkinson (1971) and Chapter 2 of Wilkinson (1963). The most elementary point is that, even if z 1 is mathematically an exact zero of f z, because of the fundamental limitations of computer arithmetic the computed value of f z 1 will not necessarily be exactly 0.0. In practice there is usually a small region of values of z about the exact zero at which the computed value of f z becomes swamped by rounding errors. Moreover, in many algorithms this inaccuracy in the computed value of f z results in a similar inaccuracy in the computed step from one iterate to the next. This limits the precision with which any zero can be computed. Deflation is another potential cause of trouble, since, in the notation of equation (1), the computed coefficients of f 1 z will not be completely accurate, especially if z 1 is not an exact zero of f z; so the zeros of the computed f 1 z will deviate from the zeros of f z.
A zero is called ill-conditioned if it is sensitive to small changes in the coefficients of the polynomial. An ill-conditioned zero is likewise sensitive to the computational inaccuracies just mentioned. Conversely a zero is called well-conditioned if it is comparatively insensitive to such perturbations. Roughly speaking a zero which is well separated from other zeros is well-conditioned, while zeros which are close together are ill-conditioned, but in talking about ‘closeness’ the decisive factor is not the absolute distance between neighbouring zeros but their ratio: if the ratio is close to one the zeros are ill-conditioned. In particular, multiple zeros are ill-conditioned. A multiple zero is usually split into a cluster of zeros by perturbations in the polynomial or computational inaccuracies.

3 Recommendations on Choice and Use of Available Routines

All zeros of cubic,
complex coefficients C02AMF
real coefficients C02AKF
All zeros of polynomial,
complex coefficients,
modified Laguerre's method C02AFF
real coefficients,
modified Laguerre's method C02AGF
All zeros of quadratic,
complex coefficients C02AHF
real coefficients C02AJF
All zeros of quartic,
complex coefficients C02ANF
real coefficients C02ALF

4 Auxiliary Routines Associated with Library Routine Arguments

None.

5 Routines Withdrawn or Scheduled for Withdrawal

None.

6 References

Householder A S (1970) The Numerical Treatment of a Single Nonlinear Equation McGraw–Hill
Peters G and Wilkinson J H (1971) Practical problems arising in the solution of polynomial equations J. Inst. Maths. Applics. 8 16–35
Thompson K W (1991) Error analysis for polynomial solvers Fortran Journal (Volume 3) 3 10–13
Wilkinson J H (1963) Rounding Errors in Algebraic Processes HMSO
C02 Chapter Contents
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


C05AUF : NAG Library, Mark 26

C05 Chapter Contents
C05 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

C05AUF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

C05AUF locates a simple zero of a continuous function from a given starting value. It uses a binary search to locate an interval containing a zero of the function, then Brent's method, which is a combination of nonlinear interpolation, linear extrapolation and bisection, to locate the zero precisely.

2 Specification

SUBROUTINE C05AUF ( X, H, EPS, ETA, F, A, B, IUSER, RUSER, IFAIL)
INTEGER | IUSER(*), IFAIL
REAL (KIND=nag_wp) | X, H, EPS, ETA, F, A, B, RUSER(*)
EXTERNAL | F

3 Description

C05AUF attempts to locate an interval a,b containing a simple zero of the function f x by a binary search starting from the initial point x=X and using repeated calls to C05AVF. If this search succeeds, then the zero is determined to a user-specified accuracy by a call to C05AYF. The specifications of routines C05AVF and C05AYF should be consulted for details of the methods used.
The approximation x to the zero α is determined so that at least one of the following criteria is satisfied:
(i) | x-α ≤ EPS ,
(ii) | f x≤ETA .

4 References

Brent R P (1973) Algorithms for Minimization Without Derivatives Prentice–Hall

5 Arguments

1:   X – REAL (KIND=nag_wp)Input/Output
On entry: an initial approximation to the zero.
On exit: if IFAIL=0 or 4, X is the final approximation to the zero.
If IFAIL=3, X is likely to be a pole of f x.
Otherwise, X contains no useful information.
2:   H – REAL (KIND=nag_wp)Input
On entry: a step length for use in the binary search for an interval containing the zero. The maximum interval searched is X-256.0×H,X+256.0×H .
Constraint: H must be sufficiently large that X+H≠X on the computer.
3:   EPS – REAL (KIND=nag_wp)Input
On entry: the termination tolerance on x (see Section 3).
Constraint: EPS>0.0 .
4:   ETA – REAL (KIND=nag_wp)Input
On entry: a value such that if f x≤ETA , x is accepted as the zero. ETA may be specified as 0.0 (see Section 7).
5:   F – REAL (KIND=nag_wp) FUNCTION, supplied by the user.External Procedure
F must evaluate the function f whose zero is to be determined.
The specification of F is:
FUNCTION F ( X, IUSER, RUSER)
REAL (KIND=nag_wp) F
INTEGER | IUSER(*)
REAL (KIND=nag_wp) | X, RUSER(*)
1:   X – REAL (KIND=nag_wp)Input
On entry: the point at which the function must be evaluated.
2:   IUSER* – INTEGER arrayUser Workspace
3:   RUSER* – REAL (KIND=nag_wp) arrayUser Workspace
F is called with the arguments IUSER and RUSER as supplied to C05AUF. You are free to use the arrays IUSER and RUSER to supply information to F as an alternative to using COMMON global variables.
F must either be a module subprogram USEd by, or declared as EXTERNAL in, the (sub)program from which C05AUF is called. Arguments denoted as Input must not be changed by this procedure.
6:   A – REAL (KIND=nag_wp)Output
7:   B – REAL (KIND=nag_wp)Output
On exit: the lower and upper bounds respectively of the interval resulting from the binary search. If the zero is determined exactly such that f x=0.0 or is determined so that f x≤ETA at any stage in the calculation, then on exit A=B=x .
8:   IUSER* – INTEGER arrayUser Workspace
9:   RUSER* – REAL (KIND=nag_wp) arrayUser Workspace
IUSER and RUSER are not used by C05AUF, but are passed directly to F and may be used to pass information to this routine as an alternative to using COMMON global variables.
10:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, EPS=value.
Constraint: EPS>0.0.
On entry, X=value and H=value.
Constraint: X+H≠X (to machine accuracy).
IFAIL=2
An interval containing the zero could not be found. Increasing H and calling C05AUF again will increase the range searched for the zero. Decreasing H and calling C05AUF again will refine the mesh used in the search for the zero.
IFAIL=3
Solution may be a pole rather than a zero.
IFAIL=4
The tolerance EPS has been set too small for the problem being solved. However, the value X returned is a good approximation to the zero. EPS=value.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

The levels of accuracy depend on the values of EPS and ETA. If full machine accuracy is required, they may be set very small, resulting in an exit with IFAIL=4, although this may involve many more iterations than a lesser accuracy. You are recommended to set ETA=0.0 and to use EPS to control the accuracy, unless you have considerable knowledge of the size of f x for values of x near the zero.

8 Parallelism and Performance

C05AUF is not threaded in any implementation.

9 Further Comments

The time taken by C05AUF depends primarily on the time spent evaluating F (see Section 5). The accuracy of the initial approximation X and the value of H will have a somewhat unpredictable effect on the timing.
If it is important to determine an interval of relative length less than 2×EPS containing the zero, or if F is expensive to evaluate and the number of calls to F is to be restricted, then use of C05AVF followed by C05AZF is recommended. Use of this combination is also recommended when the structure of the problem to be solved does not permit a simple F to be written: the reverse communication facilities of these routines are more flexible than the direct communication of F required by C05AUF.
If the iteration terminates with successful exit and A=B=X there is no guarantee that the value returned in X corresponds to a simple zero and you should check whether it does.
One way to check this is to compute the derivative of f at the point X, preferably analytically, or, if this is not possible, numerically, perhaps by using a central difference estimate. If f′X=0.0 , then X must correspond to a multiple zero of f rather than a simple zero.

10 Example

This example calculates an approximation to the zero of x-e-x using a tolerance of EPS=1.0E−5 starting from X=1.0 and using an initial search step H=0.1 .

10.1 Program Text

Program Text (c05aufe.f90)

10.2 Program Data

None.

10.3 Program Results

Program Results (c05aufe.r)

C05 Chapter Contents
C05 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


C05AVF : NAG Library, Mark 26

C05 Chapter Contents
C05 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

C05AVF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

C05AVF attempts to locate an interval containing a simple zero of a continuous function using a binary search. It uses reverse communication for evaluating the function.

2 Specification

SUBROUTINE C05AVF ( X, FX, H, BOUNDL, BOUNDU, Y, C, IND, IFAIL)
INTEGER | IND, IFAIL
REAL (KIND=nag_wp) | X, FX, H, BOUNDL, BOUNDU, Y, C(11)

3 Description

You must supply an initial point X and a step H. C05AVF attempts to locate a short interval X,Y ⊂ BOUNDL,BOUNDU containing a simple zero of f x .
(On exit we may have X>Y ; X is determined as the first point encountered in a binary search where the sign of f x differs from the sign of f x at the initial input point X.) The routine attempts to locate a zero of f x using H, 0.1×H , 0.01×H and 0.001×H in turn as its basic step before quitting with an error exit if unsuccessful.
C05AVF returns to the calling program for each evaluation of f x . On each return you should set FX=f X and call C05AVF again.

4 References

None.

5 Arguments

Note: this routine uses reverse communication. Its use involves an initial entry, intermediate exits and re-entries, and a final exit, as indicated by the argument IND. Between intermediate exits and re-entries, all arguments other than FX must remain unchanged.
1:   X – REAL (KIND=nag_wp)Input/Output
On initial entry: the best available approximation to the zero.
Constraint: X must lie in the closed interval BOUNDL,BOUNDU (see below).
On intermediate exit: contains the point at which f must be evaluated before re-entry to the routine.
On final exit: contains one end of an interval containing the zero, the other end being in Y, unless an error has occurred. If IFAIL=4, X and Y are the end points of the largest interval searched. If a zero is located exactly, its value is returned in X (and in Y).
2:   FX – REAL (KIND=nag_wp)Input
On initial entry: if IND=1, FX need not be set.
If IND=-1, FX must contain f X for the initial value of X.
On intermediate re-entry: must contain f X for the current value of X.
3:   H – REAL (KIND=nag_wp)Input/Output
On initial entry: a basic step size which is used in the binary search for an interval containing a zero. The basic step sizes H,0.1×H , 0.01×H and 0.001×H are used in turn when searching for the zero.
Constraint: either X+H or X-H must lie inside the closed interval BOUNDL,BOUNDU .
H must be sufficiently large that X+H≠X on the computer.
On final exit: is undefined.
4:   BOUNDL – REAL (KIND=nag_wp)Input
5:   BOUNDU – REAL (KIND=nag_wp)Input
On initial entry: BOUNDL and BOUNDU must contain respectively lower and upper bounds for the interval of search for the zero.
Constraint: BOUNDL<BOUNDU .
6:   Y – REAL (KIND=nag_wp)Input/Output
On initial entry: need not be set.
On final exit: contains the closest point found to the final value of X, such that f X × f Y≤0.0 . If a value X is found such that f X=0 , then Y=X . On final exit with IFAIL=4, X and Y are the end points of the largest interval searched.
7:   C 11 – REAL (KIND=nag_wp) arrayCommunication Array
On initial entry: need not be set.
On final exit: if IFAIL=0 or 4, C 1 contains f Y .
8:   IND – INTEGERInput/Output
On initial entry: must be set to 1 or -1 .
IND=1
FX need not be set.
IND=-1
FX must contain f X .
On intermediate exit: contains 2 or 3. The calling program must evaluate f at X, storing the result in FX, and re-enter C05AVF with all other arguments unchanged.
On final exit: contains 0.
Constraint: on entry IND=-1, 1, 2 or 3.
9:   IFAIL – INTEGERInput/Output
On initial entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, because for this routine the values of the output arguments may be useful even if IFAIL≠0 on exit, the recommended value is -1. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On final exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, | BOUNDU≤BOUNDL ,
or | X ∉ BOUNDL,BOUNDU ,
or | both X+H and X-H ∉ BOUNDL,BOUNDU .
IFAIL=2
On initial entry, H is too small to be used to perturb the initial value of X in the search.
IFAIL=3
The argument IND is incorrectly set on initial or intermediate entry.
IFAIL=4
C05AVF has been unable to determine an interval containing a simple zero starting from the initial value of X and using the step H. If you have prior knowledge that a simple zero lies in the interval BOUNDL,BOUNDU , you should vary X and H in an attempt to find it. (See also Section 9.)
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

C05AVF is not intended to be used to obtain accurate approximations to the zero of f x but rather to locate an interval containing a zero. This interval can then be used as input to an accurate rootfinder such as C05AYF or C05AZF. The size of the interval determined depends somewhat unpredictably on the choice of X and H. The closer X is to the root and the smaller the initial value of H, then, in general, the smaller (more accurate) the interval determined; however, the accuracy of this statement depends to some extent on the behaviour of f x near x=X and on the size of H.

8 Parallelism and Performance

C05AVF is not threaded in any implementation.

9 Further Comments

For most problems, the time taken on each call to C05AVF will be negligible compared with the time spent evaluating f x between calls to C05AVF. However, the initial value of X and H will clearly affect the timing. The closer X is to the root, and the larger the initial value of H then the less time taken. (However taking a large H can affect the accuracy and reliability of the routine, see below.)
You are expected to choose BOUNDL and BOUNDU as physically (or mathematically) realistic limits on the interval of search. For example, it may be known, from physical arguments, that no zero of f x of interest will lie outside BOUNDL,BOUNDU . Alternatively, f x may be more expensive to evaluate for some values of X than for others and such expensive evaluations can sometimes be avoided by careful choice of BOUNDL and BOUNDU.
The choice of BOUNDL and BOUNDU affects the search only in that these values provide physical limitations on the search values and that the search is terminated if it seems, from the available information about f x , that the zero lies outside BOUNDL,BOUNDU . In this case (IFAIL=4 on exit), only one of f BOUNDL and f BOUNDU may have been evaluated and a zero close to the other end of the interval could be missed. The actual interval searched is returned in the arguments X and Y and you can call C05AVF again to search the remainder of the original interval.
Though C05AVF is intended primarily for determining an interval containing a zero of f x , it may be used to shorten a known interval. This could be useful if, for example, a large interval containing the zero is known and it is also known that the root lies close to one end of the interval; by setting X to this end of the interval and H small, a short interval will usually be determined. However, it is worth noting that once any interval containing a zero has been determined, a call to C05AZF will usually be the most efficient way to calculate an interval of specified length containing the zero. To assist in this determination, the information in FX and in X, Y and C 1 on successful exit from C05AVF is in the correct form for a call to routine C05AZF with IND=-1 .
If the calculation terminates because f X=0.0 , then on return Y is set to X. (In fact, Y=X on return only in this case.) In this case, there is no guarantee that the value in X corresponds to a simple zero and you should check whether it does.
One way to check this is to compute the derivative of f at the point X, preferably analytically, or, if this is not possible, numerically, perhaps by using a central difference estimate. If f′X=0.0 , then X must correspond to a multiple zero of f rather than a simple zero.

10 Example

This example finds a sub-interval of 0.0,4.0 containing a simple zero of x 2 - 3 x+2 . The zero nearest to 3.0 is required and so we set X=3.0 initially.

10.1 Program Text

Program Text (c05avfe.f90)

10.2 Program Data

None.

10.3 Program Results

Program Results (c05avfe.r)

C05 Chapter Contents
C05 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


C05AWF : NAG Library, Mark 26

C05 Chapter Contents
C05 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

C05AWF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

C05AWF attempts to locate a zero of a continuous function using a continuation method based on a secant iteration.

2 Specification

SUBROUTINE C05AWF ( X, EPS, ETA, F, NFMAX, IUSER, RUSER, IFAIL)
INTEGER | NFMAX, IUSER(*), IFAIL
REAL (KIND=nag_wp) | X, EPS, ETA, F, RUSER(*)
EXTERNAL | F

3 Description

C05AWF attempts to obtain an approximation to a simple zero α of the function f x given an initial approximation x to α. The zero is found by a call to C05AXF whose specification should be consulted for details of the method used.
The approximation x to the zero α is determined so that at least one of the following criteria is satisfied:
(i) | x-α∼EPS ,
(ii) | f x<ETA .

4 References

None.

5 Arguments

1:   X – REAL (KIND=nag_wp)Input/Output
On entry: an initial approximation to the zero.
On exit: the final approximation to the zero, unless IFAIL=1, 2 or 5, in which case it contains no useful information.
2:   EPS – REAL (KIND=nag_wp)Input
On entry: an absolute tolerance to control the accuracy to which the zero is determined. In general, the smaller the value of EPS the more accurate X will be as an approximation to α. Indeed, for very small positive values of EPS, it is likely that the final approximation will satisfy X-α<EPS . You are advised to call the routine with more than one value for EPS to check the accuracy obtained.
Constraint: EPS>0.0 .
3:   ETA – REAL (KIND=nag_wp)Input
On entry: a value such that if f x<ETA , x is accepted as the zero. ETA may be specified as 0.0 (see Section 7).
4:   F – REAL (KIND=nag_wp) FUNCTION, supplied by the user.External Procedure
F must evaluate the function f whose zero is to be determined.
The specification of F is:
FUNCTION F ( X, IUSER, RUSER)
REAL (KIND=nag_wp) F
INTEGER | IUSER(*)
REAL (KIND=nag_wp) | X, RUSER(*)
1:   X – REAL (KIND=nag_wp)Input
On entry: the point at which the function must be evaluated.
2:   IUSER* – INTEGER arrayUser Workspace
3:   RUSER* – REAL (KIND=nag_wp) arrayUser Workspace
F is called with the arguments IUSER and RUSER as supplied to C05AWF. You are free to use the arrays IUSER and RUSER to supply information to F as an alternative to using COMMON global variables.
F must either be a module subprogram USEd by, or declared as EXTERNAL in, the (sub)program from which C05AWF is called. Arguments denoted as Input must not be changed by this procedure.
5:   NFMAX – INTEGERInput
On entry: the maximum permitted number of calls to F from C05AWF. If F is inexpensive to evaluate, NFMAX should be given a large value (say >1000 ).
Constraint: NFMAX>0 .
6:   IUSER* – INTEGER arrayUser Workspace
7:   RUSER* – REAL (KIND=nag_wp) arrayUser Workspace
IUSER and RUSER are not used by C05AWF, but are passed directly to F and may be used to pass information to this routine as an alternative to using COMMON global variables.
8:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, EPS=value.
Constraint: EPS>0.0.
On entry, NFMAX=value.
Constraint: NFMAX>0.
IFAIL=2
Internal scale factor invalid for this problem. Consider using C05AXF instead and setting SCAL.
IFAIL=3
Either F has no zero near X or too much accuracy has been requested. Check the coding of F or increase EPS.
IFAIL=4
More than NFMAX calls have been made to F.
NFMAX may be too small for the problem (because X is too far away from the zero), or F has no zero near X, or too much accuracy has been requested in calculating the zero. Increase NFMAX, check the coding of F or increase EPS.
IFAIL=5
A serious error occurred in an internal call to an auxiliary routine.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

The levels of accuracy depend on the values of EPS and ETA. If full machine accuracy is required, they may be set very small, resulting in an exit with IFAIL=3 or 4, although this may involve many more iterations than a lesser accuracy. You are recommended to set ETA=0.0 and to use EPS to control the accuracy, unless you have considerable knowledge of the size of f x for values of x near the zero.

8 Parallelism and Performance

C05AWF is not threaded in any implementation.

9 Further Comments

The time taken by C05AWF depends primarily on the time spent evaluating the function f (see Section 5) and on how close the initial value of X is to the zero.
If a more flexible way of specifying the function f is required or if you wish to have closer control of the calculation, then the reverse communication routine C05AXF is recommended instead of C05AWF.

10 Example

This example calculates the zero of f x = e-x - x from a starting value X=1.0 . Two calculations are made with EPS=1.0E−3 and 1.0E−4 for comparison purposes, with ETA=0.0 in both cases.

10.1 Program Text

Program Text (c05awfe.f90)

10.2 Program Data

None.

10.3 Program Results

Program Results (c05awfe.r)

C05 Chapter Contents
C05 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


C05AXF : NAG Library, Mark 26

C05 Chapter Contents
C05 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

C05AXF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

C05AXF attempts to locate a zero of a continuous function using a continuation method based on a secant iteration. It uses reverse communication for evaluating the function.

2 Specification

SUBROUTINE C05AXF ( X, FX, TOL, IR, SCAL, C, IND, IFAIL)
INTEGER | IR, IND, IFAIL
REAL (KIND=nag_wp) | X, FX, TOL, SCAL, C(26)

3 Description

C05AXF uses a modified version of an algorithm given in Swift and Lindfield (1978) to compute a zero α of a continuous function f x . The algorithm used is based on a continuation method in which a sequence of problems
f x-θr f x 0,  r=0,1,…,m
are solved, where 1 = θ 0 > θ 1 > ⋯ > θm = 0 (the value of m is determined as the algorithm proceeds) and where x 0 is your initial estimate for the zero of f x . For each θr the current problem is solved by a robust secant iteration using the solution from earlier problems to compute an initial estimate.
You must supply an error tolerance TOL. TOL is used directly to control the accuracy of solution of the final problem ( θm=0 ) in the continuation method, and TOL is used to control the accuracy in the intermediate problems ( θ 1 , θ 2 , … , θ m-1 ).

4 References

Swift A and Lindfield G R (1978) Comparison of a continuation method for the numerical solution of a single nonlinear equation Comput. J. 21 359–362

5 Arguments

Note: this routine uses reverse communication. Its use involves an initial entry, intermediate exits and re-entries, and a final exit, as indicated by the argument IND. Between intermediate exits and re-entries, all arguments other than FX must remain unchanged.
1:   X – REAL (KIND=nag_wp)Input/Output
On initial entry: an initial approximation to the zero.
On intermediate exit: the point at which f must be evaluated before re-entry to the routine.
On final exit: the final approximation to the zero.
2:   FX – REAL (KIND=nag_wp)Input
On initial entry: if IND=1, FX need not be set.
If IND=-1, FX must contain f X for the initial value of X.
On intermediate re-entry: must contain f X for the current value of X.
3:   TOL – REAL (KIND=nag_wp)Input
On initial entry: a value that controls the accuracy to which the zero is determined. TOL is used in determining the convergence of the secant iteration used at each stage of the continuation process. It is used directly when solving the last problem ( θm=0 in Section 3), and TOL is used for the problem defined by θr , r<m . Convergence to the accuracy specified by TOL is not guaranteed, and so you are recommended to find the zero using at least two values for TOL to check the accuracy obtained.
Constraint: TOL>0.0 .
4:   IR – INTEGERInput
On initial entry: indicates the type of error test required, as follows. Solving the problem defined by θr , 1≤r≤m , involves computing a sequence of secant iterates xr 0,xr 1,… . This sequence will be considered to have converged only if:
for IR=0,
xr i+1 -xr i ≤eps×max 1.0,xr i ,
for IR=1,
xr i+1 -xr i ≤eps,
for IR=2,
xr i+1 -xr i ≤eps×xr i ,
for some i>1 ; here eps is either TOL or TOL as discussed above. Note that there are other subsidiary conditions (not given here) which must also be satisfied before the secant iteration is considered to have converged.
Constraint: IR=0, 1 or 2.
5:   SCAL – REAL (KIND=nag_wp)Input
On initial entry: a factor for use in determining a significant approximation to the derivative of f x at x=x 0 , the initial value. A number of difference approximations to f′x 0 are calculated using
f′x 0∼f x 0+h-f x 0/h
where h<SCAL and h has the same sign as SCAL. A significance (cancellation) check is made on each difference approximation and the approximation is rejected if insignificant.
Suggested value: ε, where ε is the machine precision returned by X02AJF.
Constraint: SCAL must be sufficiently large that X+SCAL≠X on the computer.
6:   C 26 – REAL (KIND=nag_wp) arrayCommunication Array
( C 5 contains the current θr , this value may be useful in the event of an error exit.)
7:   IND – INTEGERInput/Output
On initial entry: must be set to 1 or -1 .
IND=1
FX need not be set.
IND=-1
FX must contain f X .
On intermediate exit: contains 2, 3 or 4. The calling program must evaluate f at X, storing the result in FX, and re-enter C05AXF with all other arguments unchanged.
On final exit: contains 0.
Constraint: on entry IND=-1, 1, 2, 3 or 4.
8:   IFAIL – INTEGERInput/Output
On initial entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, because for this routine the values of the output arguments may be useful even if IFAIL≠0 on exit, the recommended value is -1. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On final exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, | TOL≤0.0 ,
or | IR≠0, 1 or 2.
IFAIL=2
The argument IND is incorrectly set on initial or intermediate entry.
IFAIL=3
SCAL is too small, or significant derivatives of f cannot be computed (this can happen when f is almost constant and nonzero, for any value of SCAL).
IFAIL=4
The current problem in the continuation sequence cannot be solved, see C 5 for the value of θr . The most likely explanation is that the current problem has no solution, either because the original problem had no solution or because the continuation path passes through a set of insoluble problems. This latter reason for failure should occur rarely, and not at all if the initial approximation to the zero is sufficiently close. Other possible explanations are that TOL is too small and hence the accuracy requirement is too stringent, or that TOL is too large and the initial approximation too poor, leading to successively worse intermediate solutions.
IFAIL=5
Continuation away from the initial point is not possible. This error exit will usually occur if the problem has not been properly posed or the error requirement is extremely stringent.
IFAIL=6
The final problem (with θm=0 ) cannot be solved. It is likely that too much accuracy has been requested, or that the zero is at α=0 and IR=2 .
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

The accuracy of the approximation to the zero depends on TOL and IR. In general decreasing TOL will give more accurate results. Care must be exercised when using the relative error criterion ( IR=2 ).
If the zero is at X=0 , or if the initial value of X and the zero bracket the point X=0 , it is likely that an error exit with IFAIL=4, 5 or 6 will occur.
It is possible to request too much or too little accuracy. Since it is not possible to achieve more than machine accuracy, a value of TOL≪machine precision should not be input and may lead to an error exit with IFAIL=4, 5 or 6. For the reasons discussed under IFAIL=4 in Section 6, TOL should not be taken too large, say no larger than TOL=1.0E−3 .

8 Parallelism and Performance

C05AXF is not threaded in any implementation.

9 Further Comments

For most problems, the time taken on each call to C05AXF will be negligible compared with the time spent evaluating f x between calls to C05AXF. However, the initial value of X and the choice of TOL will clearly affect the timing. The closer that X is to the root, the less evaluations of f required. The effect of the choice of TOL will not be large, in general, unless TOL is very small, in which case the timing will increase.

10 Example

This example calculates a zero of x - e-x with initial approximation x 0=1.0 , and TOL=1.0E−3 and 1.0E−4 .

10.1 Program Text

Program Text (c05axfe.f90)

10.2 Program Data

None.

10.3 Program Results

Program Results (c05axfe.r)

C05 Chapter Contents
C05 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


C05AYF : NAG Library, Mark 26

C05 Chapter Contents
C05 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

C05AYF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

C05AYF locates a simple zero of a continuous function in a given interval using Brent's method, which is a combination of nonlinear interpolation, linear extrapolation and bisection.

2 Specification

SUBROUTINE C05AYF ( A, B, EPS, ETA, F, X, IUSER, RUSER, IFAIL)
INTEGER | IUSER(*), IFAIL
REAL (KIND=nag_wp) | A, B, EPS, ETA, F, X, RUSER(*)
EXTERNAL | F

3 Description

C05AYF attempts to obtain an approximation to a simple zero of the function f x given an initial interval a,b such that f a × f b ≤ 0 . The same core algorithm is used by C05AZF whose specification should be consulted for details of the method used.
The approximation x to the zero α is determined so that at least one of the following criteria is satisfied:
(i) | x-α ≤ EPS ,
(ii) | f x≤ETA .

4 References

Brent R P (1973) Algorithms for Minimization Without Derivatives Prentice–Hall

5 Arguments

1:   A – REAL (KIND=nag_wp)Input
On entry: a, the lower bound of the interval.
2:   B – REAL (KIND=nag_wp)Input
On entry: b, the upper bound of the interval.
Constraint: B≠A .
3:   EPS – REAL (KIND=nag_wp)Input
On entry: the termination tolerance on x (see Section 3).
Constraint: EPS>0.0 .
4:   ETA – REAL (KIND=nag_wp)Input
On entry: a value such that if f x≤ETA , x is accepted as the zero. ETA may be specified as 0.0 (see Section 7).
5:   F – REAL (KIND=nag_wp) FUNCTION, supplied by the user.External Procedure
F must evaluate the function f whose zero is to be determined.
The specification of F is:
FUNCTION F ( X, IUSER, RUSER)
REAL (KIND=nag_wp) F
INTEGER | IUSER(*)
REAL (KIND=nag_wp) | X, RUSER(*)
1:   X – REAL (KIND=nag_wp)Input
On entry: the point at which the function must be evaluated.
2:   IUSER* – INTEGER arrayUser Workspace
3:   RUSER* – REAL (KIND=nag_wp) arrayUser Workspace
F is called with the arguments IUSER and RUSER as supplied to C05AYF. You are free to use the arrays IUSER and RUSER to supply information to F as an alternative to using COMMON global variables.
F must either be a module subprogram USEd by, or declared as EXTERNAL in, the (sub)program from which C05AYF is called. Arguments denoted as Input must not be changed by this procedure.
6:   X – REAL (KIND=nag_wp)Output
On exit: if IFAIL=0 or 2, X is the final approximation to the zero. If IFAIL=3, X is likely to be a pole of f x. Otherwise, X contains no useful information.
7:   IUSER* – INTEGER arrayUser Workspace
8:   RUSER* – REAL (KIND=nag_wp) arrayUser Workspace
IUSER and RUSER are not used by C05AYF, but are passed directly to F and may be used to pass information to this routine as an alternative to using COMMON global variables.
9:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, A=value and B=value.
Constraint: A≠B.
On entry, EPS=value.
Constraint: EPS>0.0.
On entry, F A and F B have the same sign with neither equalling 0.0: F A=value and F B=value.
IFAIL=2
No further improvement in the solution is possible. EPS is too small: EPS=value . The final value of X returned is an accurate approximation to the zero.
IFAIL=3
The function values in the interval A,B might contain a pole rather than a zero. Reducing EPS may help in distinguishing between a pole and a zero.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

The levels of accuracy depend on the values of EPS and ETA. If full machine accuracy is required, they may be set very small, resulting in an exit with IFAIL=2, although this may involve many more iterations than a lesser accuracy. You are recommended to set ETA=0.0 and to use EPS to control the accuracy, unless you have considerable knowledge of the size of f x for values of x near the zero.

8 Parallelism and Performance

C05AYF is not threaded in any implementation.

9 Further Comments

The time taken by C05AYF depends primarily on the time spent evaluating F (see Section 5).
If it is important to determine an interval of relative length less than 2×EPS containing the zero, or if F is expensive to evaluate and the number of calls to F is to be restricted, then use of C05AZF is recommended. Use of C05AZF is also recommended when the structure of the problem to be solved does not permit a simple F to be written: the reverse communication facilities of C05AZF are more flexible than the direct communication of F required by C05AYF.

10 Example

This example calculates an approximation to the zero of e-x - x within the interval 0,1 using a tolerance of EPS=1.0E−5.

10.1 Program Text

Program Text (c05ayfe.f90)

10.2 Program Data

None.

10.3 Program Results

Program Results (c05ayfe.r)

C05 Chapter Contents
C05 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


C05AZF : NAG Library, Mark 26

C05 Chapter Contents
C05 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

C05AZF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

C05AZF locates a simple zero of a continuous function in a given interval by using Brent's method, which is a combination of nonlinear interpolation, linear extrapolation and bisection. It uses reverse communication for evaluating the function.

2 Specification

SUBROUTINE C05AZF ( X, Y, FX, TOLX, IR, C, IND, IFAIL)
INTEGER | IR, IND, IFAIL
REAL (KIND=nag_wp) | X, Y, FX, TOLX, C(17)

3 Description

You must supply X and Y to define an initial interval a,b containing a simple zero of the function f x (the choice of X and Y must be such that f X × f Y ≤ 0.0 ). The routine combines the methods of bisection, nonlinear interpolation and linear extrapolation (see Dahlquist and Björck (1974)), to find a sequence of sub-intervals of the initial interval such that the final interval X,Y contains the zero and X-Y is less than some tolerance specified by TOLX and IR (see Section 5). In fact, since the intermediate intervals X,Y are determined only so that f X × f Y ≤ 0.0 , it is possible that the final interval may contain a discontinuity or a pole of f (violating the requirement that f be continuous). C05AZF checks if the sign change is likely to correspond to a pole of f and gives an error return in this case.
A feature of the algorithm used by this routine is that unlike some other methods it guarantees convergence within about log 2 b-a / δ 2 function evaluations, where δ is related to the argument TOLX. See Brent (1973) for more details.
C05AZF returns to the calling program for each evaluation of f x . On each return you should set FX = f X and call C05AZF again.
The routine is a modified version of procedure ‘zeroin’ given by Brent (1973).

4 References

Brent R P (1973) Algorithms for Minimization Without Derivatives Prentice–Hall
Bus J C P and Dekker T J (1975) Two efficient algorithms with guaranteed convergence for finding a zero of a function ACM Trans. Math. Software 1 330–345
Dahlquist G and Björck Å (1974) Numerical Methods Prentice–Hall

5 Arguments

Note: this routine uses reverse communication. Its use involves an initial entry, intermediate exits and re-entries, and a final exit, as indicated by the argument IND. Between intermediate exits and re-entries, all arguments other than FX must remain unchanged.
1:   X – REAL (KIND=nag_wp)Input/Output
2:   Y – REAL (KIND=nag_wp)Input/Output
On initial entry: X and Y must define an initial interval a,b containing the zero, such that f X × f Y≤0.0 . It is not necessary that X<Y .
On intermediate exit: X contains the point at which f must be evaluated before re-entry to the routine.
On final exit: X and Y define a smaller interval containing the zero, such that f X×f Y≤0.0 , and X-Y satisfies the accuracy specified by TOLX and IR, unless an error has occurred. If IFAIL=4, X and Y generally contain very good approximations to a pole; if IFAIL=5, X and Y generally contain very good approximations to the zero (see Section 6). If a point X is found such that f X=0.0 , then on final exit X=Y (in this case there is no guarantee that X is a simple zero). In all cases, the value returned in X is the better approximation to the zero.
3:   FX – REAL (KIND=nag_wp)Input
On initial entry: if IND=1, FX need not be set.
If IND=-1, FX must contain f X for the initial value of X.
On intermediate re-entry: must contain f X for the current value of X.
4:   TOLX – REAL (KIND=nag_wp)Input
On initial entry: the accuracy to which the zero is required. The type of error test is specified by IR.
Constraint: TOLX>0.0 .
5:   IR – INTEGERInput
On initial entry: indicates the type of error test.
IR=0
The test is: X-Y≤2.0×TOLX×max 1.0,X .
IR=1
The test is: X-Y≤2.0×TOLX .
IR=2
The test is: X-Y≤2.0×TOLX×X .
Suggested value: IR=0.
Constraint: IR=0, 1 or 2.
6:   C 17 – REAL (KIND=nag_wp) arrayInput/Output
On initial entry: if IND=1 , no elements of C need be set.
If IND=-1 , C 1 must contain f Y , other elements of C need not be set.
On final exit: is undefined.
7:   IND – INTEGERInput/Output
On initial entry: must be set to 1 or -1 .
IND=1
FX and C 1 need not be set.
IND=-1
FX and C 1 must contain f X and f Y respectively.
On intermediate exit: contains 2, 3 or 4. The calling program must evaluate f at X, storing the result in FX, and re-enter C05AZF with all other arguments unchanged.
On final exit: contains 0.
Constraint: on entry IND=-1, 1, 2, 3 or 4.
8:   IFAIL – INTEGERInput/Output
On initial entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, because for this routine the values of the output arguments may be useful even if IFAIL≠0 on exit, the recommended value is -1. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On final exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, f X and f Y have the same sign with neither equalling 0.0 .
IFAIL=2
On entry, IND≠-1, 1, 2, 3 or 4.
IFAIL=3
On entry, | TOLX≤0.0,
or | IR≠0, 1 or 2.
IFAIL=4
An interval X,Y has been determined satisfying the error tolerance specified by TOLX and IR and such that f X × f Y ≤ 0 . However, from observation of the values of f during the calculation of X,Y , it seems that the interval X,Y contains a pole rather than a zero. Note that this error exit is not completely reliable: the error exit may be taken in extreme cases when X,Y contains a zero, or the error exit may not be taken when X,Y contains a pole. Both these cases occur most frequently when TOLX is large.
IFAIL=5
The tolerance TOLX is too small for the problem being solved. This indicator is only set when the interval containing the zero has been reduced to one of relative length at most 2 ε, where ε is the machine precision, but the exit condition specified by IR is not satisfied. It is unsafe to continue reducing the interval beyond this point, but the final values of X and Y returned are accurate approximations to the zero.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

The accuracy of the final value X as an approximation of the zero is determined by TOLX and IR (see Section 5). A relative accuracy criterion ( IR=2 ) should not be used when the initial values X and Y are of different orders of magnitude. In this case a change of origin of the independent variable may be appropriate. For example, if the initial interval X,Y is transformed linearly to the interval 1,2 , then the zero can be determined to a precise number of figures using an absolute ( IR=1 ) or relative ( IR=2 ) error test and the effect of the transformation back to the original interval can also be determined. Except for the accuracy check, such a transformation has no effect on the calculation of the zero.

8 Parallelism and Performance

C05AZF is not threaded in any implementation.

9 Further Comments

For most problems, the time taken on each call to C05AZF will be negligible compared with the time spent evaluating f x between calls to C05AZF.
If the calculation terminates because f X=0.0 , then on return Y is set to X. (In fact, Y=X on return only in this case and, possibly, when IFAIL=5.) There is no guarantee that the value returned in X corresponds to a simple root and you should check whether it does. One way to check this is to compute the derivative of f at the point X, preferably analytically, or, if this is not possible, numerically, perhaps by using a central difference estimate. If f′X=0.0 , then X must correspond to a multiple zero of f rather than a simple zero.

10 Example

This example calculates a zero of e-x - x with an initial interval 0,1 , TOLX=1.0E−5 and a mixed error test.

10.1 Program Text

Program Text (c05azfe.f90)

10.2 Program Data

None.

10.3 Program Results

Program Results (c05azfe.r)

C05 Chapter Contents
C05 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


C05BAF : NAG Library, Mark 26

C05 Chapter Contents
C05 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

C05BAF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

C05BAF returns the real values of Lambert's W function W x, via the routine name.

2 Specification

FUNCTION C05BAF ( X, BRANCH, OFFSET, IFAIL)
REAL (KIND=nag_wp) C05BAF
INTEGER | BRANCH, IFAIL
REAL (KIND=nag_wp) | X
LOGICAL | OFFSET

3 Description

C05BAF calculates an approximate value for the real branches of Lambert's W function (sometimes known as the ‘product log’ or ‘Omega’ function), which is the inverse function of
f w = w ew   for   w∈C .
The function f is many-to-one, and so, except at 0, W is multivalued. C05BAF restricts W and its argument x to be real, resulting in a function defined for x≥-exp-1 and which is double valued on the interval -exp-1,0. This double-valued function is split into two real-valued branches according to the sign of W x+1. We denote by W 0 the branch satisfying W 0 x≥-1 for all real x, and by W-1 the branch satisfying W-1 x≤-1 for all real x. You may select your branch of interest using the argument BRANCH.
The precise method used to approximate W is described fully in Barry et al. (1995). For x close to -exp-1 greater accuracy comes from evaluating W-exp-1+Δx rather than W x: by setting OFFSET=.TRUE. on entry you inform C05BAF that you are providing Δx, not x, in X.

4 References

Barry D J, Culligan–Hensley P J, and Barry S J (1995) Real values of the W-function ACM Trans. Math. Software 21(2) 161–171

5 Arguments

1:   X – REAL (KIND=nag_wp)Input
On entry: if OFFSET=.TRUE., X is the offset Δx from -exp-1 of the intended argument to W; that is, W β is computed, where β=-exp-1+Δx.
If OFFSET=.FALSE., X is the argument x of the function; that is, W β is computed, where β=x.
Constraints:
  • if BRANCH=0, -exp-1≤β;
  • if BRANCH=-1, -exp-1≤β<0.0.
2:   BRANCH – INTEGERInput
On entry: the real branch required.
BRANCH=0
The branch W 0 is selected.
BRANCH=-1
The branch W-1 is selected.
Constraint: BRANCH=0 or -1.
3:   OFFSET – LOGICALInput
On entry: controls whether or not X is being specified as an offset from -exp-1.
4:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, because for this routine the values of the output arguments may be useful even if IFAIL≠0 on exit, the recommended value is -1. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Note: C05BAF may return useful information for one or more of the following detected errors or warnings.
Errors or warnings detected by the routine:
IFAIL=1
On entry, BRANCH=value.
Constraint: BRANCH=0 or -1.
On entry, BRANCH=-1, OFFSET=.FALSE. and X=value.
Constraint: if BRANCH=-1 and OFFSET=.FALSE. then X<0.0.
On entry, BRANCH=-1, OFFSET=.TRUE. and X=value.
Constraint: if BRANCH=-1 and OFFSET=.TRUE. then X<exp-1.0.
On entry, OFFSET=.FALSE. and X=value.
Constraint: if OFFSET=.FALSE. then X≥-exp-1.0.
On entry, OFFSET=.TRUE. and X=value.
Constraint: if OFFSET=.TRUE. then X≥0.0.
IFAIL=2
For the given offset X, W is negligibly different from -1: X=value.
X is close to -exp-1. Enter X as an offset to -exp-1 for greater accuracy: X=value.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

For a high percentage of legal X on input, C05BAF is accurate to the number of decimal digits of precision on the host machine (see X02BEF). An extra digit may be lost on some implementations and for a small proportion of such X. This depends on the accuracy of the base-10 logarithm on your system.

8 Parallelism and Performance

C05BAF is not threaded in any implementation.

9 Further Comments

None.

10 Example

This example reads from a file the values of the required branch, whether or not the arguments to W are to be considered as offsets to -exp-1, and the arguments X themselves. It then evaluates the function for these sets of input data X and prints the results.

10.1 Program Text

Program Text (c05bafe.f90)

10.2 Program Data

Program Data (c05bafe.d)

10.3 Program Results

Program Results (c05bafe.r)

C05 Chapter Contents
C05 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


C05 Chapter Contents : NAG Library Manual, Mark 26

C05 Chapter Introduction
NAG Library Manual

NAG Library Chapter Contents

C05 – Roots of One or More Transcendental Equations

C05 Chapter Introduction – a description of the Chapter and an overview of the algorithms available

Routine Name | Mark of Introduction | Purpose
C05AUF Example Text | 23 | nagf_roots_contfn_brent_interval Zero of continuous function, Brent algorithm, from a given starting value, binary search for interval
C05AVF Example Text | 8 | nagf_roots_contfn_interval_rcomm Binary search for interval containing zero of continuous function (reverse communication)
C05AWF Example Text | 23 | nagf_roots_contfn_cntin Zero of continuous function, continuation method, from a given starting value
C05AXF Example Text | 8 | nagf_roots_contfn_cntin_rcomm Zero of continuous function, continuation method, from a given starting value (reverse communication)
C05AYF Example Text | 23 | nagf_roots_contfn_brent Zero of continuous function in a given interval, Brent algorithm
C05AZF Example Text | 7 | nagf_roots_contfn_brent_rcomm Zero of continuous function in a given interval, Brent algorithm (reverse communication)
C05BAF Example Text Example Data | 22 | nagf_roots_lambertw_real Real values of Lambert's W function, W x
C05BBF Example Text Example Data | 23 | nagf_roots_lambertw_complex Values of Lambert's W function, W z
C05QBF Example Text | 23 | nagf_roots_sys_func_easy Solution of a system of nonlinear equations using function values only (easy-to-use)
C05QCF Example Text | 23 | nagf_roots_sys_func_expert Solution of a system of nonlinear equations using function values only (comprehensive)
C05QDF Example Text | 23 | nagf_roots_sys_func_rcomm Solution of a system of nonlinear equations using function values only (reverse communication)
C05QSF Example Text | 23 | nagf_roots_sparsys_func_expert Solution of a sparse system of nonlinear equations using function values only (easy-to-use)
C05RBF Example Text | 23 | nagf_roots_sys_deriv_easy Solution of a system of nonlinear equations using first derivatives (easy-to-use)
C05RCF Example Text | 23 | nagf_roots_sys_deriv_expert Solution of a system of nonlinear equations using first derivatives (comprehensive)
C05RDF Example Text | 23 | nagf_roots_sys_deriv_rcomm Solution of a system of nonlinear equations using first derivatives (reverse communication)
C05ZDF Example Text | 23 | nagf_roots_sys_deriv_check Check user's routine for calculating first derivatives of a set of nonlinear functions of several variables
C05 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


C05 Chapter Introduction : NAG Library, Mark 26

C05 Chapter Contents
NAG Library Manual

NAG Library Chapter Introduction

C05 – Roots of One or More Transcendental Equations

▸▿ Contents

1 Scope of the Chapter
▸▿ 2 Background to the Problems
2.1 A Single Equation
2.2 Systems of Equations
▸▿ 3 Recommendations on Choice and Use of Available Routines
3.1 Zeros of Functions of One Variable
3.2 Solution of Sets of Nonlinear Equations
3.3 Values of Lambert's W function
4 Decision Trees
5 Functionality Index
6 Auxiliary Routines Associated with Library Routine Arguments
7 Routines Withdrawn or Scheduled for Withdrawal
8 References

1 Scope of the Chapter

This chapter is concerned with the calculation of zeros of continuous functions of one or more variables. The majority of problems considered are for real-valued functions of real variables, in which case complex equations must be expressed in terms of the equivalent larger system of real equations.

2 Background to the Problems

The chapter divides naturally into two parts.

2.1 A Single Equation

The first deals with the real zeros of a real function of a single variable f x .
There are three routines with simple calling sequences. The first assumes that you can determine an initial interval a,b within which the desired zero lies, (that is, where f a×f b<0 ), and outside which all other zeros lie. The routine then systematically subdivides the interval to produce a final interval containing the zero. This final interval has a length bounded by your specified error requirements; the end of the interval where the function has smallest magnitude is returned as the zero. This routine is guaranteed to converge to a simple zero of the function. (Here we define a simple zero as a zero corresponding to a sign-change of the function; none of the available routines are capable of making any finer distinction.) However, as with the other routines described below, a non-simple zero might be determined and it is left to you to check for this. The algorithm used is due to Brent (1973).
The two other routines are both designed for the case where you are unable to specify an interval containing the simple zero. One starts from an initial point and performs a search for an interval containing a simple zero. If such an interval is computed then the method described above is used next to determine the zero accurately. The other method uses a ‘continuation’ method based on a secant iteration. A sequence of subproblems is solved; the first of these is trivial and the last is the actual problem of finding a zero of f x . The intermediate problems employ the solutions of earlier problems to provide initial guesses for the secant iterations used to calculate their solutions.
Three other routines are also supplied. They employ reverse communication and use the same core algorithms as the routines described above.
Finally, two routines are provided to return values of Lambert's W function (sometimes known as the ‘product log’ or ‘Omega’ function), which is the inverse function of
f w=w ew  for  w∈C;
that is, if Lambert's W function W x=a for x,a∈C, then a is a zero of the function F w=w ew-x. One routine uses the iterative method described in Barry et al. (1995) to return values from the real branches of W (restricting x,a∈R). The second routine enforces no such restriction, and uses the approach described in Corless et al. (1996).

2.2 Systems of Equations

The routines in the second part of this chapter are designed to solve a set of nonlinear equations in n unknowns
fi x = 0 ,   i= 1,2,…,n ,   x= x 1,x 2,…,xn T , (1)
where T stands for transpose.
It is assumed that the functions are continuous and differentiable so that the matrix of first partial derivatives of the functions, the Jacobian matrix J ij x= ∂fi ∂xj evaluated at the point x, exists, though it may not be possible to calculate it directly.
The functions fi must be independent, otherwise there will be an infinity of solutions and the methods will fail. However, even when the functions are independent the solutions may not be unique. Since the methods are iterative, an initial guess at the solution has to be supplied, and the solution located will usually be the one closest to this initial guess.

3 Recommendations on Choice and Use of Available Routines

3.1 Zeros of Functions of One Variable

The routines can be divided into two classes. There are three routines (C05AVF, C05AXF and C05AZF) all written in reverse communication form and three (C05AUF, C05AWF and C05AYF) written in direct communication form (see Section 3.3.3 in How to Use the NAG Library and its Documentation for a description of the difference between these two conventions). The direct communication routines are designed for inexperienced users and, in particular, for solving problems where the function f x whose zero is to be calculated, can be coded as a user-supplied (sub)program. These routines find the zero by using the same core algorithms as the reverse communication routines. Experienced users are recommended to use the reverse communication routines directly as they permit you more control of the calculation. Indeed, if the zero-finding process is embedded in a much larger program then the reverse communication routines should always be used.
The recommendation as to which routine should be used depends mainly on whether you can supply an interval a,b containing the zero; that is, where f a×f b<0 . If the interval can be supplied, then C05AYF (or, in reverse communication, C05AZF) should be used, in general. This recommendation should be qualified in the case when the only interval which can be supplied is very long relative to your error requirements and you can also supply a good approximation to the zero. In this case C05AWF (or, in reverse communication, C05AXF) may prove more efficient (though these latter routines will not provide the error bound available from C05AZF).
If an interval containing the zero cannot be supplied then you must choose between C05AUF (or, in reverse communication, C05AVF followed by C05AZF) and C05AWF (or, in reverse communication, C05AXF). C05AUF first determines an interval containing the zero, and then proceeds as in C05AYF; it is particularly recommended when you do not have a good initial approximation to the zero. If a good initial approximation to the zero is available then C05AWF is to be preferred. Since neither of these latter routines has guaranteed convergence to the zero, you are recommended to experiment with both in case of difficulty.

3.2 Solution of Sets of Nonlinear Equations

The solution of a set of nonlinear equations
fi x 1,x 2,…,xn=0,  i=1,2,…,n (2)
can be regarded as a special case of the problem of finding a minimum of a sum of squares
s x = ∑ i = 1 m f i x 1 , x 2 ,…, x n 2 ,   m ≥ n . (3)
So the routines in Chapter E04 are relevant as well as the special nonlinear equations routines.
The routines for solving a set of nonlinear equations can also be divided into classes. There are five routines (C05QBF, C05QCF, C05QSF, C05RBF and C05RCF) all written in direct communication form and two (C05QDF and C05RDF) written in reverse communication form. The direct communication routines are designed for inexperienced users and, in particular, these routines require the fi (and possibly their derivatives) to be calculated in user-supplied subroutines. These should be set up carefully so the Library routines can work as efficiently as possible. Experienced users are recommended to use the reverse communication routines as they permit you more control of the calculation. Indeed, if the zero-finding process is embedded in a much larger program then the reverse communication routines should always be used.
The main decision you have to make is whether to supply the derivatives ∂fi ∂xj . It is advisable to do so if possible, since the results obtained by algorithms which use derivatives are generally more reliable than those obtained by algorithms which do not use derivatives.
C05RBF, C05RCF and C05RDF require you to provide the derivatives, whilst C05QBF, C05QCF, C05QDF and C05QSF do not. C05QBF, C05QSF and C05RBF are easy-to-use routines; greater flexibility may be obtained using C05QCF and C05RCF (or, in reverse communication, C05QDF and C05RDF), but these have longer argument lists.
C05QSF is an easy-to-use routine specially adapted for sparse problems, that is, problems where each function depends on a small subset of the n variables so that the Jacobian matrix has many zeros. It employs sparse linear algebra methods and consequently is expected to take significantly less time to complete than the other routines, especially if n is large.
C05ZDF is provided for use in conjunction with C05RBF, C05RCF and C05RDF to check the user-supplied derivatives for consistency with the functions themselves. You are strongly advised to make use of this routine whenever C05RBF, C05RCF or C05RDF is used.
Firstly, the calculation of the functions and their derivatives should be ordered so that cancellation errors are avoided. This is particularly important in a routine that uses these quantities to build up estimates of higher derivatives.
Secondly, scaling of the variables has a considerable effect on the efficiency of a routine. The problem should be designed so that the elements of x are of similar magnitude. The same comment applies to the functions, i.e., all the fi should be of comparable size.
The accuracy is usually determined by the accuracy arguments of the routines, but the following points may be useful.
(i) | Greater accuracy in the solution may be requested by choosing smaller input values for the accuracy arguments. However, if unreasonable accuracy is demanded, rounding errors may become important and cause a failure.
(ii) | Some idea of the accuracies of the xi may be obtained by monitoring the progress of the routine to see how many figures remain unchanged during the last few iterations.
(iii) An approximation to the error in the solution x is given by e where e is the solution to the set of linear equations
J x e=-f x
where f x = f 1 x,f 2 x,…,fn x T .
Note that the QR decomposition of J is available from C05QCF and C05RCF (or, in reverse communication, C05QDF and C05RDF) so that
Re=-QT f
and QT f is also provided by these routines.
(iv) If the functions fi x are changed by small amounts ε i , for i=1,2,…,n, then the corresponding change in the solution x is given approximately by σ, where σ is the solution of the set of linear equations
J x σ = -ε .
Thus one can estimate the sensitivity of x to any uncertainties in the specification of fi x , for i=1,2,…,n. As noted above, the sophisticated routines C05QCF and C05RCF (or, in reverse communication, C05QDF and C05RDF) provide the QR decomposition of J.

3.3 Values of Lambert's W function

If you require purely-real values of W, these will be evaluated marginally more efficiently by C05BAF than C05BBF owing to the differing iterative procedures used by each routine.

4 Decision Trees

Tree 1: Functions of One Variable

Is reverse communication required? |  |  | Is there available an interval a,b containing a simple zero, and no others? |  |  | C05AZF
 |  | yes |  |  | yes
 | no |  |  | no |
 |  |  | Is a good approximation to the zero available? |  |  | C05AXF
 |  |  |  |  | yes
 |  |  |  | no |
 |  |  | C05AVF followed by C05AZF
Do you wish to compute the values of Lambert's W function? |  |  | do you require values from only the real branches? |  |  | C05BAF
 |  | yes |  |  | yes
 | no |  |  | no |
 |  |  | C05BBF
Is there available an interval a,b containing a simple zero, and no others? |  |  | C05AYF
 |  | yes
 | no |
Is a good approximation to the zero available? |  |  | C05AWF
 |  | yes
 | no |
C05AUF

Tree 2: Functions of several variables

Is the Jacobian matrix sparse? |  |  | C05QSF
 |  | yes
 | no |
Is reverse communication required? |  |  | Is the Jacobian matrix available? |  |  | C05RDF and C05ZDF
 |  | yes |  |  | yes
 | no |  |  | no |
 |  |  | C05QDF
Is the Jacobian matrix available? |  |  | Is flexibility required? |  |  | C05RCF and C05ZDF
 |  | yes |  |  | yes
 | no |  |  | no |
 |  |  | C05RBF and C05ZDF
Is flexibility required? |  |  | C05QCF
 |  | yes
 | no |
C05QBF

5 Functionality Index

Lambert's W function,
complex values C05BBF
real values C05BAF
Zeros of functions of one variable,
direct communication,
binary search followed by Brent algorithm C05AUF
Brent algorithm C05AYF
continuation method C05AWF
reverse communication,
binary search C05AVF
Brent algorithm C05AZF
continuation method C05AXF
Zeros of functions of several variables,
checking routine,
checks user-supplied Jacobian C05ZDF
direct communication,
easy-to-use,
derivatives required C05RBF
no derivatives required C05QBF
no derivatives required, sparse C05QSF
sophisticated,
derivatives required C05RCF
no derivatives required C05QCF
reverse communication,
sophisticated,
derivatives required C05RDF
no derivatives required C05QDF

6 Auxiliary Routines Associated with Library Routine Arguments

None.

7 Routines Withdrawn or Scheduled for Withdrawal

The following lists all those routines that have been withdrawn since Mark 19 of the Library or are scheduled for withdrawal at one of the next two marks.
Withdrawn Routine | Mark of Withdrawal | Replacement Routine(s)
C05ADF | 25 | C05AYF
C05AGF | 25 | C05AUF
C05AJF | 25 | C05AWF
C05NBF | 25 | C05QBF
C05NCF | 25 | C05QCF
C05NDF | 25 | C05QDF
C05PBF/C05PBA | 25 | C05RBF
C05PCF/C05PCA | 25 | C05RCF
C05PDF/C05PDA | 25 | C05RDF
C05ZAF | 25 | C05ZDF

8 References

Barry D J, Culligan–Hensley P J, and Barry S J (1995) Real values of the W-function ACM Trans. Math. Software 21(2) 161–171
Brent R P (1973) Algorithms for Minimization Without Derivatives Prentice–Hall
Corless R M, Gonnet G H, Hare D E G, Jeffrey D J and Knuth D E (1996) On the Lambert W function Advances in Comp. Math. 3 329–359
Gill P E and Murray W (1976) Algorithms for the solution of the nonlinear least squares problem Report NAC 71 National Physical Laboratory
Moré J J, Garbow B S and Hillstrom K E (1980) User guide for MINPACK-1 Technical Report ANL-80-74 Argonne National Laboratory
Ortega J M and Rheinboldt W C (1970) Iterative Solution of Nonlinear Equations in Several Variables Academic Press
Rabinowitz P (1970) Numerical Methods for Nonlinear Algebraic Equations Gordon and Breach
C05 Chapter Contents
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


C05QBF : NAG Library, Mark 26

C05 Chapter Contents
C05 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

C05QBF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

C05QBF is an easy-to-use routine that finds a solution of a system of nonlinear equations by a modification of the Powell hybrid method.

2 Specification

SUBROUTINE C05QBF ( FCN, N, X, FVEC, XTOL, IUSER, RUSER, IFAIL)
INTEGER | N, IUSER(*), IFAIL
REAL (KIND=nag_wp) | X(N), FVEC(N), XTOL, RUSER(*)
EXTERNAL | FCN

3 Description

The system of equations is defined as:
fi x 1,x 2,…,xn = 0 ,   ​ i= 1, 2, …, n .
C05QBF is based on the MINPACK routine HYBRD1 (see Moré et al. (1980)). It chooses the correction at each step as a convex combination of the Newton and scaled gradient directions. The Jacobian is updated by the rank-1 method of Broyden. At the starting point, the Jacobian is approximated by forward differences, but these are not used again until the rank-1 method fails to produce satisfactory progress. For more details see Powell (1970).

4 References

Moré J J, Garbow B S and Hillstrom K E (1980) User guide for MINPACK-1 Technical Report ANL-80-74 Argonne National Laboratory
Powell M J D (1970) A hybrid method for nonlinear algebraic equations Numerical Methods for Nonlinear Algebraic Equations (ed P Rabinowitz) Gordon and Breach

5 Arguments

1:   FCN – SUBROUTINE, supplied by the user.External Procedure
FCN must return the values of the functions fi at a point x.
The specification of FCN is:
SUBROUTINE FCN ( N, X, FVEC, IUSER, RUSER, IFLAG)
INTEGER | N, IUSER(*), IFLAG
REAL (KIND=nag_wp) | X(N), FVEC(N), RUSER(*)
1:   N – INTEGERInput
On entry: n, the number of equations.
2:   X N – REAL (KIND=nag_wp) arrayInput
On entry: the components of the point x at which the functions must be evaluated.
3:   FVEC N – REAL (KIND=nag_wp) arrayOutput
On exit: the function values fi x (unless IFLAG is set to a negative value by FCN).
4:   IUSER* – INTEGER arrayUser Workspace
5:   RUSER* – REAL (KIND=nag_wp) arrayUser Workspace
FCN is called with the arguments IUSER and RUSER as supplied to C05QBF. You are free to use the arrays IUSER and RUSER to supply information to FCN as an alternative to using COMMON global variables.
6:   IFLAG – INTEGERInput/Output
On entry: IFLAG>0 .
On exit: in general, IFLAG should not be reset by FCN. If, however, you wish to terminate execution (perhaps because some illegal point X has been reached), then IFLAG should be set to a negative integer.
FCN must either be a module subprogram USEd by, or declared as EXTERNAL in, the (sub)program from which C05QBF is called. Arguments denoted as Input must not be changed by this procedure.
2:   N – INTEGERInput
On entry: n, the number of equations.
Constraint: N>0 .
3:   X N – REAL (KIND=nag_wp) arrayInput/Output
On entry: an initial guess at the solution vector.
On exit: the final estimate of the solution vector.
4:   FVEC N – REAL (KIND=nag_wp) arrayOutput
On exit: the function values at the final point returned in X.
5:   XTOL – REAL (KIND=nag_wp)Input
On entry: the accuracy in X to which the solution is required.
Suggested value: ε, where ε is the machine precision returned by X02AJF.
Constraint: XTOL≥0.0 .
6:   IUSER* – INTEGER arrayUser Workspace
7:   RUSER* – REAL (KIND=nag_wp) arrayUser Workspace
IUSER and RUSER are not used by C05QBF, but are passed directly to FCN and may be used to pass information to this routine as an alternative to using COMMON global variables.
8:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=2
There have been at least 200 × N+1 calls to FCN. Consider restarting the calculation from the point held in X.
IFAIL=3
No further improvement in the solution is possible. XTOL is too small: XTOL=value.
IFAIL=4
The iteration is not making good progress. This failure exit may indicate that the system does not have a zero, or that the solution is very close to the origin (see Section 7). Otherwise, rerunning C05QBF from a different starting point may avoid the region of difficulty.
IFAIL=5
IFLAG was set negative in FCN. IFLAG=value.
IFAIL=11
On entry, N=value.
Constraint: N>0.
IFAIL=12
On entry, XTOL=value.
Constraint: XTOL≥0.0.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

If x^ is the true solution, C05QBF tries to ensure that
x-x^ 2 ≤ XTOL × x^ 2 .
If this condition is satisfied with XTOL = 10-k , then the larger components of x have k significant decimal digits. There is a danger that the smaller components of x may have large relative errors, but the fast rate of convergence of C05QBF usually obviates this possibility.
If XTOL is less than machine precision and the above test is satisfied with the machine precision in place of XTOL, then the routine exits with IFAIL=3.
Note: this convergence test is based purely on relative error, and may not indicate convergence if the solution is very close to the origin.
The convergence test assumes that the functions are reasonably well behaved. If this condition is not satisfied, then C05QBF may incorrectly indicate convergence. The validity of the answer can be checked, for example, by rerunning C05QBF with a lower value for XTOL.

8 Parallelism and Performance

C05QBF is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
C05QBF makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

Local workspace arrays of fixed lengths are allocated internally by C05QBF. The total size of these arrays amounts to n×3×n+13/2 real elements.
The time required by C05QBF to solve a given problem depends on n, the behaviour of the functions, the accuracy requested and the starting point. The number of arithmetic operations executed by C05QBF to process each evaluation of the functions is approximately 11.5×n 2. The timing of C05QBF is strongly influenced by the time spent evaluating the functions.
Ideally the problem should be scaled so that, at the solution, the function values are of comparable magnitude.

10 Example

This example determines the values x 1 , … , x 9 which satisfy the tridiagonal equations:
3-2 x 1 x 1-2 x 2 = -1, -x i-1+3-2 xi xi-2 x i+1 = -1,  i=2,3,…,8 -x 8+3-2 x 9 x 9 = -1.

10.1 Program Text

Program Text (c05qbfe.f90)

10.2 Program Data

None.

10.3 Program Results

Program Results (c05qbfe.r)

C05 Chapter Contents
C05 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


C05QCF : NAG Library, Mark 26

C05 Chapter Contents
C05 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

C05QCF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

C05QCF is a comprehensive routine that finds a solution of a system of nonlinear equations by a modification of the Powell hybrid method.

2 Specification

SUBROUTINE C05QCF ( FCN, N, X, FVEC, XTOL, MAXFEV, ML, MU, EPSFCN, MODE, DIAG, FACTOR, NPRINT, NFEV, FJAC, R, QTF, IUSER, RUSER, IFAIL)
INTEGER | N, MAXFEV, ML, MU, MODE, NPRINT, NFEV, IUSER(*), IFAIL
REAL (KIND=nag_wp) | X(N), FVEC(N), XTOL, EPSFCN, DIAG(N), FACTOR, FJAC(N,N), R(N*(N+1)/2), QTF(N), RUSER(*)
EXTERNAL | FCN

3 Description

The system of equations is defined as:
fi x 1,x 2,…,xn = 0 ,   ​ i= 1, 2, …, n .
C05QCF is based on the MINPACK routine HYBRD (see Moré et al. (1980)). It chooses the correction at each step as a convex combination of the Newton and scaled gradient directions. The Jacobian is updated by the rank-1 method of Broyden. At the starting point, the Jacobian is approximated by forward differences, but these are not used again until the rank-1 method fails to produce satisfactory progress. For more details see Powell (1970).

4 References

Moré J J, Garbow B S and Hillstrom K E (1980) User guide for MINPACK-1 Technical Report ANL-80-74 Argonne National Laboratory
Powell M J D (1970) A hybrid method for nonlinear algebraic equations Numerical Methods for Nonlinear Algebraic Equations (ed P Rabinowitz) Gordon and Breach

5 Arguments

1:   FCN – SUBROUTINE, supplied by the user.External Procedure
FCN must return the values of the functions fi at a point x, unless IFLAG=0 on entry to C05QCF.
The specification of FCN is:
SUBROUTINE FCN ( N, X, FVEC, IUSER, RUSER, IFLAG)
INTEGER | N, IUSER(*), IFLAG
REAL (KIND=nag_wp) | X(N), FVEC(N), RUSER(*)
1:   N – INTEGERInput
On entry: n, the number of equations.
2:   X N – REAL (KIND=nag_wp) arrayInput
On entry: the components of the point x at which the functions must be evaluated.
3:   FVEC N – REAL (KIND=nag_wp) arrayInput/Output
On entry: if IFLAG=0 , FVEC contains the function values fi x and must not be changed.
On exit: if IFLAG>0 on entry, FVEC must contain the function values fi x (unless IFLAG is set to a negative value by FCN).
4:   IUSER* – INTEGER arrayUser Workspace
5:   RUSER* – REAL (KIND=nag_wp) arrayUser Workspace
FCN is called with the arguments IUSER and RUSER as supplied to C05QCF. You are free to use the arrays IUSER and RUSER to supply information to FCN as an alternative to using COMMON global variables.
6:   IFLAG – INTEGERInput/Output
On entry: IFLAG≥0 .
IFLAG=0
X and FVEC are available for printing (see NPRINT).
IFLAG>0
FVEC must be updated.
On exit: in general, IFLAG should not be reset by FCN. If, however, you wish to terminate execution (perhaps because some illegal point X has been reached), then IFLAG should be set to a negative integer.
FCN must either be a module subprogram USEd by, or declared as EXTERNAL in, the (sub)program from which C05QCF is called. Arguments denoted as Input must not be changed by this procedure.
2:   N – INTEGERInput
On entry: n, the number of equations.
Constraint: N>0 .
3:   X N – REAL (KIND=nag_wp) arrayInput/Output
On entry: an initial guess at the solution vector.
On exit: the final estimate of the solution vector.
4:   FVEC N – REAL (KIND=nag_wp) arrayOutput
On exit: the function values at the final point returned in X.
5:   XTOL – REAL (KIND=nag_wp)Input
On entry: the accuracy in X to which the solution is required.
Suggested value: ε, where ε is the machine precision returned by X02AJF.
Constraint: XTOL≥0.0 .
6:   MAXFEV – INTEGERInput
On entry: the maximum number of calls to FCN with IFLAG≠0 . C05QCF will exit with IFAIL=2, if, at the end of an iteration, the number of calls to FCN exceeds MAXFEV.
Suggested value: MAXFEV=200×N+1 .
Constraint: MAXFEV>0 .
7:   ML – INTEGERInput
On entry: the number of subdiagonals within the band of the Jacobian matrix. (If the Jacobian is not banded, or you are unsure, set ML=N-1 .)
Constraint: ML≥0 .
8:   MU – INTEGERInput
On entry: the number of superdiagonals within the band of the Jacobian matrix. (If the Jacobian is not banded, or you are unsure, set MU=N-1 .)
Constraint: MU≥0 .
9:   EPSFCN – REAL (KIND=nag_wp)Input
On entry: a rough estimate of the largest relative error in the functions. It is used in determining a suitable step for a forward difference approximation to the Jacobian. If EPSFCN is less than machine precision (returned by X02AJF) then machine precision is used. Consequently a value of 0.0 will often be suitable.
Suggested value: EPSFCN=0.0 .
10:   MODE – INTEGERInput
On entry: indicates whether or not you have provided scaling factors in DIAG.
If MODE=2 the scaling must have been specified in DIAG.
Otherwise, if MODE=1, the variables will be scaled internally.
Constraint: MODE=1 or 2.
11:   DIAG N – REAL (KIND=nag_wp) arrayInput/Output
On entry: if MODE=2, DIAG must contain multiplicative scale factors for the variables.
If MODE=1, DIAG need not be set.
Constraint: if MODE=2, DIAG i>0.0 , for i=1,2,…,n.
On exit: the scale factors actually used (computed internally if MODE=1).
12:   FACTOR – REAL (KIND=nag_wp)Input
On entry: a quantity to be used in determining the initial step bound. In most cases, FACTOR should lie between 0.1 and 100.0. (The step bound is FACTOR×DIAG×X 2 if this is nonzero; otherwise the bound is FACTOR.)
Suggested value: FACTOR=100.0 .
Constraint: FACTOR>0.0 .
13:   NPRINT – INTEGERInput
On entry: indicates whether (and how often) special calls to FCN, with IFLAG set to 0, are to be made for printing purposes.
NPRINT≤0
No calls are made.
NPRINT>0
FCN is called at the beginning of the first iteration, every NPRINT iterations thereafter and immediately before the return from C05QCF.
14:   NFEV – INTEGEROutput
On exit: the number of calls made to FCN with IFLAG>0.
15:   FJAC NN – REAL (KIND=nag_wp) arrayOutput
On exit: the orthogonal matrix Q produced by the QR factorization of the final approximate Jacobian.
16:   R N×N+1/2 – REAL (KIND=nag_wp) arrayOutput
On exit: the upper triangular matrix R produced by the QR factorization of the final approximate Jacobian, stored row-wise.
17:   QTF N – REAL (KIND=nag_wp) arrayOutput
On exit: the vector QT f .
18:   IUSER* – INTEGER arrayUser Workspace
19:   RUSER* – REAL (KIND=nag_wp) arrayUser Workspace
IUSER and RUSER are not used by C05QCF, but are passed directly to FCN and may be used to pass information to this routine as an alternative to using COMMON global variables.
20:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=2
There have been at least MAXFEV calls to FCN: MAXFEV=value. Consider restarting the calculation from the final point held in X.
IFAIL=3
No further improvement in the solution is possible. XTOL is too small: XTOL=value.
IFAIL=4
The iteration is not making good progress, as measured by the improvement from the last value Jacobian evaluations.
IFAIL=5
The iteration is not making good progress, as measured by the improvement from the last value iterations.
IFAIL=6
IFLAG was set negative in FCN. IFLAG=value.
IFAIL=11
On entry, N=value.
Constraint: N>0.
IFAIL=12
On entry, XTOL=value.
Constraint: XTOL≥0.0.
IFAIL=13
On entry, MODE=value.
Constraint: MODE=1 or 2.
IFAIL=14
On entry, FACTOR=value.
Constraint: FACTOR>0.0.
IFAIL=15
On entry, MODE=2 and DIAG contained a non-positive element.
IFAIL=16
On entry, ML=value.
Constraint: ML≥0.
IFAIL=17
On entry, MU=value.
Constraint: MU≥0.
IFAIL=18
On entry, MAXFEV=value.
Constraint: MAXFEV>0.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.
A value of IFAIL=4 or 5 may indicate that the system does not have a zero, or that the solution is very close to the origin (see Section 7). Otherwise, rerunning C05QCF from a different starting point may avoid the region of difficulty.

7 Accuracy

If x^ is the true solution and D denotes the diagonal matrix whose entries are defined by the array DIAG, then C05QCF tries to ensure that
D x-x^ 2 ≤ XTOL × D x^ 2 .
If this condition is satisfied with XTOL = 10-k , then the larger components of Dx have k significant decimal digits. There is a danger that the smaller components of Dx may have large relative errors, but the fast rate of convergence of C05QCF usually obviates this possibility.
If XTOL is less than machine precision and the above test is satisfied with the machine precision in place of XTOL, then the routine exits with IFAIL=3.
Note: this convergence test is based purely on relative error, and may not indicate convergence if the solution is very close to the origin.
The convergence test assumes that the functions are reasonably well behaved. If this condition is not satisfied, then C05QCF may incorrectly indicate convergence. The validity of the answer can be checked, for example, by rerunning C05QCF with a lower value for XTOL.

8 Parallelism and Performance

C05QCF is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
C05QCF makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

Local workspace arrays of fixed lengths are allocated internally by C05QCF. The total size of these arrays amounts to 4×n real elements.
The time required by C05QCF to solve a given problem depends on n, the behaviour of the functions, the accuracy requested and the starting point. The number of arithmetic operations executed by C05QCF to process each evaluation of the functions is approximately 11.5×n 2 . The timing of C05QCF is strongly influenced by the time spent evaluating the functions.
Ideally the problem should be scaled so that, at the solution, the function values are of comparable magnitude.
The number of function evaluations required to evaluate the Jacobian may be reduced if you can specify ML and MU accurately.

10 Example

This example determines the values x 1 , … , x 9 which satisfy the tridiagonal equations:
3-2 x 1 x 1-2 x 2 = -1, -x i-1+3-2 xi xi-2 x i+1 = -1,  i=2,3,…,8 -x 8+3-2 x 9 x 9 = -1.

10.1 Program Text

Program Text (c05qcfe.f90)

10.2 Program Data

None.

10.3 Program Results

Program Results (c05qcfe.r)

C05 Chapter Contents
C05 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


C05QDF : NAG Library, Mark 26

C05 Chapter Contents
C05 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

C05QDF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

C05QDF is a comprehensive reverse communication routine that finds a solution of a system of nonlinear equations by a modification of the Powell hybrid method.

2 Specification

SUBROUTINE C05QDF ( IREVCM, N, X, FVEC, XTOL, ML, MU, EPSFCN, MODE, DIAG, FACTOR, FJAC, R, QTF, IWSAV, RWSAV, IFAIL)
INTEGER | IREVCM, N, ML, MU, MODE, IWSAV(17), IFAIL
REAL (KIND=nag_wp) | X(N), FVEC(N), XTOL, EPSFCN, DIAG(N), FACTOR, FJAC(N,N), R(N*(N+1)/2), QTF(N), RWSAV(4*N+10)

3 Description

The system of equations is defined as:
fi x 1,x 2,…,xn = 0 ,   i= 1, 2, …, n .
C05QDF is based on the MINPACK routine HYBRD (see Moré et al. (1980)). It chooses the correction at each step as a convex combination of the Newton and scaled gradient directions. The Jacobian is updated by the rank-1 method of Broyden. At the starting point, the Jacobian is approximated by forward differences, but these are not used again until the rank-1 method fails to produce satisfactory progress. For more details see Powell (1970).

4 References

Moré J J, Garbow B S and Hillstrom K E (1980) User guide for MINPACK-1 Technical Report ANL-80-74 Argonne National Laboratory
Powell M J D (1970) A hybrid method for nonlinear algebraic equations Numerical Methods for Nonlinear Algebraic Equations (ed P Rabinowitz) Gordon and Breach

5 Arguments

Note: this routine uses reverse communication. Its use involves an initial entry, intermediate exits and re-entries, and a final exit, as indicated by the argument IREVCM. Between intermediate exits and re-entries, all arguments other than FVEC must remain unchanged.
1:   IREVCM – INTEGERInput/Output
On initial entry: must have the value 0.
On intermediate exit: specifies what action you must take before re-entering C05QDF with IREVCM unchanged. The value of IREVCM should be interpreted as follows:
IREVCM=1
Indicates the start of a new iteration. No action is required by you, but X and FVEC are available for printing.
IREVCM=2
Indicates that before re-entry to C05QDF, FVEC must contain the function values fi x .
On final exit: IREVCM=0 , and the algorithm has terminated.
Constraint: IREVCM=0, 1 or 2.
2:   N – INTEGERInput
On entry: n, the number of equations.
Constraint: N>0 .
3:   X N – REAL (KIND=nag_wp) arrayInput/Output
On initial entry: an initial guess at the solution vector.
On intermediate exit: contains the current point.
On final exit: the final estimate of the solution vector.
4:   FVEC N – REAL (KIND=nag_wp) arrayInput/Output
On initial entry: need not be set.
On intermediate re-entry: if IREVCM=1 , FVEC must not be changed.
If IREVCM=2 , FVEC must be set to the values of the functions computed at the current point X.
On final exit: the function values at the final point, X.
5:   XTOL – REAL (KIND=nag_wp)Input
On initial entry: the accuracy in X to which the solution is required.
Suggested value: ε, where ε is the machine precision returned by X02AJF.
Constraint: XTOL≥0.0 .
6:   ML – INTEGERInput
On initial entry: the number of subdiagonals within the band of the Jacobian matrix. (If the Jacobian is not banded, or you are unsure, set ML=N-1 .)
Constraint: ML≥0 .
7:   MU – INTEGERInput
On initial entry: the number of superdiagonals within the band of the Jacobian matrix. (If the Jacobian is not banded, or you are unsure, set MU=N-1 .)
Constraint: MU≥0 .
8:   EPSFCN – REAL (KIND=nag_wp)Input
On initial entry: the order of the largest relative error in the functions. It is used in determining a suitable step for a forward difference approximation to the Jacobian. If EPSFCN is less than machine precision (returned by X02AJF) then machine precision is used. Consequently a value of 0.0 will often be suitable.
Suggested value: EPSFCN=0.0 .
9:   MODE – INTEGERInput
On initial entry: indicates whether or not you have provided scaling factors in DIAG.
If MODE=2 the scaling must have been supplied in DIAG.
Otherwise, if MODE=1, the variables will be scaled internally.
Constraint: MODE=1 or 2.
10:   DIAG N – REAL (KIND=nag_wp) arrayInput/Output
On entry: if MODE=2, DIAG must contain multiplicative scale factors for the variables.
If MODE=1, DIAG need not be set.
Constraint: if MODE=2, DIAG i>0.0 , for i=1,2,…,n.
On exit: the scale factors actually used (computed internally if MODE=1).
11:   FACTOR – REAL (KIND=nag_wp)Input
On initial entry: a quantity to be used in determining the initial step bound. In most cases, FACTOR should lie between 0.1 and 100.0. (The step bound is FACTOR×DIAG×X 2 if this is nonzero; otherwise the bound is FACTOR.)
Suggested value: FACTOR=100.0 .
Constraint: FACTOR>0.0 .
12:   FJAC NN – REAL (KIND=nag_wp) arrayInput/Output
On initial entry: need not be set.
On intermediate exit: must not be changed.
On final exit: the orthogonal matrix Q produced by the QR factorization of the final approximate Jacobian.
13:   R N×N+1/2 – REAL (KIND=nag_wp) arrayInput/Output
On initial entry: need not be set.
On intermediate exit: must not be changed.
On final exit: the upper triangular matrix R produced by the QR factorization of the final approximate Jacobian, stored row-wise.
14:   QTF N – REAL (KIND=nag_wp) arrayInput/Output
On initial entry: need not be set.
On intermediate exit: must not be changed.
On final exit: the vector QT f .
15:   IWSAV 17 – INTEGER arrayCommunication Array
16:   RWSAV 4×N+10 – REAL (KIND=nag_wp) arrayCommunication Array
The arrays IWSAV and RWSAV must not be altered between calls to C05QDF.
17:   IFAIL – INTEGERInput/Output
On initial entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, because for this routine the values of the output arguments may be useful even if IFAIL≠0 on exit, the recommended value is -1. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On final exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=2
On entry, IREVCM=value.
Constraint: IREVCM=0, 1 or 2.
IFAIL=3
No further improvement in the solution is possible. XTOL is too small: XTOL=value.
IFAIL=4
The iteration is not making good progress, as measured by the improvement from the last value Jacobian evaluations.
IFAIL=5
The iteration is not making good progress, as measured by the improvement from the last value iterations.
IFAIL=11
On entry, N=value.
Constraint: N>0.
IFAIL=12
On entry, XTOL=value.
Constraint: XTOL≥0.0.
IFAIL=13
On entry, MODE=value.
Constraint: MODE=1 or 2.
IFAIL=14
On entry, FACTOR=value.
Constraint: FACTOR>0.0.
IFAIL=15
On entry, MODE=2 and DIAG contained a non-positive element.
IFAIL=16
On entry, ML=value.
Constraint: ML≥0.
IFAIL=17
On entry, MU=value.
Constraint: MU≥0.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.
A value of IFAIL=4 or 5 may indicate that the system does not have a zero, or that the solution is very close to the origin (see Section 7). Otherwise, rerunning C05QDF from a different starting point may avoid the region of difficulty.

7 Accuracy

If x^ is the true solution and D denotes the diagonal matrix whose entries are defined by the array DIAG, then C05QDF tries to ensure that
D x-x^ 2 ≤ XTOL × D x^ 2 .
If this condition is satisfied with XTOL = 10-k , then the larger components of Dx have k significant decimal digits. There is a danger that the smaller components of Dx may have large relative errors, but the fast rate of convergence of C05QDF usually obviates this possibility.
If XTOL is less than machine precision and the above test is satisfied with the machine precision in place of XTOL, then the routine exits with IFAIL=3.
Note: this convergence test is based purely on relative error, and may not indicate convergence if the solution is very close to the origin.
The convergence test assumes that the functions are reasonably well behaved. If this condition is not satisfied, then C05QDF may incorrectly indicate convergence. The validity of the answer can be checked, for example, by rerunning C05QDF with a lower value for XTOL.

8 Parallelism and Performance

C05QDF is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
C05QDF makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The time required by C05QDF to solve a given problem depends on n, the behaviour of the functions, the accuracy requested and the starting point. The number of arithmetic operations executed by C05QDF to process the evaluation of functions in the main program in each exit is approximately 11.5×n 2. The timing of C05QDF is strongly influenced by the time spent evaluating the functions.
Ideally the problem should be scaled so that, at the solution, the function values are of comparable magnitude.
The number of function evaluations required to evaluate the Jacobian may be reduced if you can specify ML and MU accurately.

10 Example

This example determines the values x 1 , … , x 9 which satisfy the tridiagonal equations:
3-2 x 1 x 1-2 x 2 = -1, -x i-1+3-2 xi xi-2 x i+1 = -1,  i=2,3,…,8 -x 8+3-2 x 9 x 9 = -1.

10.1 Program Text

Program Text (c05qdfe.f90)

10.2 Program Data

None.

10.3 Program Results

Program Results (c05qdfe.r)

C05 Chapter Contents
C05 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


C05QSF : NAG Library, Mark 26

C05 Chapter Contents
C05 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

C05QSF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

C05QSF is an easy-to-use routine that finds a solution of a sparse system of nonlinear equations by a modification of the Powell hybrid method.

2 Specification

SUBROUTINE C05QSF ( FCN, N, X, FVEC, XTOL, INIT, RCOMM, LRCOMM, ICOMM, LICOMM, IUSER, RUSER, IFAIL)
INTEGER | N, LRCOMM, ICOMM(LICOMM), LICOMM, IUSER(*), IFAIL
REAL (KIND=nag_wp) | X(N), FVEC(N), XTOL, RCOMM(LRCOMM), RUSER(*)
LOGICAL | INIT
EXTERNAL | FCN

3 Description

The system of equations is defined as:
fi x 1,x 2,…,xn = 0 ,   ​ i= 1, 2, …, n .
C05QSF is based on the MINPACK routine HYBRD1 (see Moré et al. (1980)). It chooses the correction at each step as a convex combination of the Newton and scaled gradient directions. The Jacobian is updated by the sparse rank-1 method of Schubert (see Schubert (1970)). At the starting point, the sparsity pattern is determined and the Jacobian is approximated by forward differences, but these are not used again until the rank-1 method fails to produce satisfactory progress. Then, the sparsity structure is used to recompute an approximation to the Jacobian by forward differences with the least number of function evaluations. The subroutine you supply must be able to compute only the requested subset of the function values. The sparse Jacobian linear system is solved at each iteration with F11MEF computing the Newton step. For more details see Powell (1970) and Broyden (1965).

4 References

Broyden C G (1965) A class of methods for solving nonlinear simultaneous equations Mathematics of Computation 19(92) 577–593
Moré J J, Garbow B S and Hillstrom K E (1980) User guide for MINPACK-1 Technical Report ANL-80-74 Argonne National Laboratory
Powell M J D (1970) A hybrid method for nonlinear algebraic equations Numerical Methods for Nonlinear Algebraic Equations (ed P Rabinowitz) Gordon and Breach
Schubert L K (1970) Modification of a quasi-Newton method for nonlinear equations with a sparse Jacobian Mathematics of Computation 24(109) 27–30

5 Arguments

1:   FCN – SUBROUTINE, supplied by the user.External Procedure
FCN must return the values of the functions fi at a point x.
The specification of FCN is:
SUBROUTINE FCN ( N, LINDF, INDF, X, FVEC, IUSER, RUSER, IFLAG)
INTEGER | N, LINDF, INDF(LINDF), IUSER(*), IFLAG
REAL (KIND=nag_wp) | X(N), FVEC(N), RUSER(*)
1:   N – INTEGERInput
On entry: n, the number of equations.
2:   LINDF – INTEGERInput
On entry: LINDF specifies the number of indices i for which values of fi x must be computed.
3:   INDF LINDF – INTEGER arrayInput
On entry: INDF specifies the indices i for which values of fi x must be computed. The indices are specified in strictly ascending order.
4:   X N – REAL (KIND=nag_wp) arrayInput
On entry: the components of the point x at which the functions must be evaluated. X i contains the coordinate xi.
5:   FVEC N – REAL (KIND=nag_wp) arrayOutput
On exit: FVEC i must contain the function values fi x, for all indices i in INDF.
6:   IUSER* – INTEGER arrayUser Workspace
7:   RUSER* – REAL (KIND=nag_wp) arrayUser Workspace
FCN is called with the arguments IUSER and RUSER as supplied to C05QSF. You are free to use the arrays IUSER and RUSER to supply information to FCN as an alternative to using COMMON global variables.
8:   IFLAG – INTEGERInput/Output
On entry: IFLAG>0 .
On exit: in general, IFLAG should not be reset by FCN. If, however, you wish to terminate execution (perhaps because some illegal point X has been reached), then IFLAG should be set to a negative integer.
FCN must either be a module subprogram USEd by, or declared as EXTERNAL in, the (sub)program from which C05QSF is called. Arguments denoted as Input must not be changed by this procedure.
2:   N – INTEGERInput
On entry: n, the number of equations.
Constraint: N>0 .
3:   X N – REAL (KIND=nag_wp) arrayInput/Output
On entry: an initial guess at the solution vector. X i must contain the coordinate xi.
On exit: the final estimate of the solution vector.
4:   FVEC N – REAL (KIND=nag_wp) arrayOutput
On exit: the function values at the final point returned in X. FVEC i contains the function values fi.
5:   XTOL – REAL (KIND=nag_wp)Input
On entry: the accuracy in X to which the solution is required.
Suggested value: ε, where ε is the machine precision returned by X02AJF.
Constraint: XTOL≥0.0 .
6:   INIT – LOGICALInput
On entry: INIT must be set to .TRUE. to indicate that this is the first time C05QSF is called for this specific problem. C05QSF then computes the dense Jacobian and detects and stores its sparsity pattern (in RCOMM and ICOMM) before proceeding with the iterations. This is noticeably time consuming when N is large. If not enough storage has been provided for RCOMM or ICOMM, C05QSF will fail. On exit with IFAIL=0, 2, 3 or 4, ICOMM 1 contains nnz, the number of nonzero entries found in the Jacobian. On subsequent calls, INIT can be set to .FALSE. if the problem has a Jacobian of the same sparsity pattern. In that case, the computation time required for the detection of the sparsity pattern will be smaller.
7:   RCOMM LRCOMM – REAL (KIND=nag_wp) arrayCommunication Array
RCOMM must not be altered between successive calls to C05QSF.
8:   LRCOMM – INTEGERInput
On entry: the dimension of the array RCOMM as declared in the (sub)program from which C05QSF is called.
Constraint: LRCOMM≥12+nnz where nnz is the number of nonzero entries in the Jacobian, as computed by C05QSF.
9:   ICOMM LICOMM – INTEGER arrayCommunication Array
If IFAIL=0, 2, 3 or 4 on exit, ICOMM 1 contains nnz where nnz is the number of nonzero entries in the Jacobian.
ICOMM must not be altered between successive calls to C05QSF.
10:   LICOMM – INTEGERInput
On entry: the dimension of the array ICOMM as declared in the (sub)program from which C05QSF is called.
Constraint: LICOMM≥8×N+19+nnz where nnz is the number of nonzero entries in the Jacobian, as computed by C05QSF.
11:   IUSER* – INTEGER arrayUser Workspace
12:   RUSER* – REAL (KIND=nag_wp) arrayUser Workspace
IUSER and RUSER are not used by C05QSF, but are passed directly to FCN and may be used to pass information to this routine as an alternative to using COMMON global variables.
13:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=2
There have been at least 200 × N+1 calls to FCN. Consider setting INIT=.FALSE. and restarting the calculation from the point held in X.
IFAIL=3
No further improvement in the solution is possible. XTOL is too small: XTOL=value.
IFAIL=4
The iteration is not making good progress. This failure exit may indicate that the system does not have a zero, or that the solution is very close to the origin (see Section 7). Otherwise, rerunning C05QSF from a different starting point may avoid the region of difficulty. The condition number of the Jacobian is value.
IFAIL=5
IFLAG was set negative in FCN. IFLAG=value.
IFAIL=6
On entry, LRCOMM=value.
Constraint: LRCOMM≥value.
IFAIL=7
On entry, LICOMM=value.
Constraint: LICOMM≥value.
IFAIL=9
An internal error has occurred. Code =value.
IFAIL=11
On entry, N=value.
Constraint: N>0.
IFAIL=12
On entry, XTOL=value.
Constraint: XTOL≥0.0.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

If x^ is the true solution, C05QSF tries to ensure that
x-x^ 2 ≤ XTOL × x^ 2 .
If this condition is satisfied with XTOL = 10-k , then the larger components of x have k significant decimal digits. There is a danger that the smaller components of x may have large relative errors, but the fast rate of convergence of C05QSF usually obviates this possibility.
If XTOL is less than machine precision and the above test is satisfied with the machine precision in place of XTOL, then the routine exits with IFAIL=3.
Note: this convergence test is based purely on relative error, and may not indicate convergence if the solution is very close to the origin.
The convergence test assumes that the functions are reasonably well behaved. If this condition is not satisfied, then C05QSF may incorrectly indicate convergence. The validity of the answer can be checked, for example, by rerunning C05QSF with a lower value for XTOL.

8 Parallelism and Performance

C05QSF is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
C05QSF makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

Local workspace arrays of fixed lengths are allocated internally by C05QSF. The total size of these arrays amounts to 8×n+2×q real elements and 10×n+2×q+5 integer elements where the integer q is bounded by 8×nnz and n 2 and depends on the sparsity pattern of the Jacobian.
The time required by C05QSF to solve a given problem depends on n, the behaviour of the functions, the accuracy requested and the starting point. The number of arithmetic operations executed by C05QSF to process each evaluation of the functions depends on the number of nonzero entries in the Jacobian. The timing of C05QSF is strongly influenced by the time spent evaluating the functions.
When INIT is .TRUE., the dense Jacobian is first evaluated and that will take time proportional to n 2.
Ideally the problem should be scaled so that, at the solution, the function values are of comparable magnitude.

10 Example

This example determines the values x 1 , … , x 9 which satisfy the tridiagonal equations:
3-2 x 1 x 1-2 x 2 = -1, -x i-1+3-2 xi xi-2 x i+1 = -1,  i=2,3,…,8 -x 8+3-2 x 9 x 9 = -1.
It then perturbs the equations by a small amount and solves the new system.

10.1 Program Text

Program Text (c05qsfe.f90)

10.2 Program Data

None.

10.3 Program Results

Program Results (c05qsfe.r)

C05 Chapter Contents
C05 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


C05RBF : NAG Library, Mark 26

C05 Chapter Contents
C05 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

C05RBF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

C05RBF is an easy-to-use routine that finds a solution of a system of nonlinear equations by a modification of the Powell hybrid method. You must provide the Jacobian.

2 Specification

SUBROUTINE C05RBF ( FCN, N, X, FVEC, FJAC, XTOL, IUSER, RUSER, IFAIL)
INTEGER | N, IUSER(*), IFAIL
REAL (KIND=nag_wp) | X(N), FVEC(N), FJAC(N,N), XTOL, RUSER(*)
EXTERNAL | FCN

3 Description

The system of equations is defined as:
fi x 1,x 2,…,xn = 0 ,   i= 1, 2, …, n .
C05RBF is based on the MINPACK routine HYBRJ1 (see Moré et al. (1980)). It chooses the correction at each step as a convex combination of the Newton and scaled gradient directions. The Jacobian is updated by the rank-1 method of Broyden. At the starting point, the Jacobian is requested, but it is not asked for again until the rank-1 method fails to produce satisfactory progress. For more details see Powell (1970).

4 References

Moré J J, Garbow B S and Hillstrom K E (1980) User guide for MINPACK-1 Technical Report ANL-80-74 Argonne National Laboratory
Powell M J D (1970) A hybrid method for nonlinear algebraic equations Numerical Methods for Nonlinear Algebraic Equations (ed P Rabinowitz) Gordon and Breach

5 Arguments

1:   FCN – SUBROUTINE, supplied by the user.External Procedure
Depending upon the value of IFLAG, FCN must either return the values of the functions fi at a point x or return the Jacobian at x.
The specification of FCN is:
SUBROUTINE FCN ( N, X, FVEC, FJAC, IUSER, RUSER, IFLAG)
INTEGER | N, IUSER(*), IFLAG
REAL (KIND=nag_wp) | X(N), FVEC(N), FJAC(N,N), RUSER(*)
1:   N – INTEGERInput
On entry: n, the number of equations.
2:   X N – REAL (KIND=nag_wp) arrayInput
On entry: the components of the point x at which the functions or the Jacobian must be evaluated.
3:   FVEC N – REAL (KIND=nag_wp) arrayInput/Output
On entry: if IFLAG=2 , FVEC contains the function values fi x and must not be changed.
On exit: if IFLAG=1 on entry, FVEC must contain the function values fi x (unless IFLAG is set to a negative value by FCN).
4:   FJAC NN – REAL (KIND=nag_wp) arrayInput/Output
On entry: if IFLAG=1 , FJAC contains the value of ∂fi ∂xj at the point x, for i=1,2,…,n and j=1,2,…,n, and must not be changed.
On exit: if IFLAG=2 on entry, FJAC ij must contain the value of ∂fi ∂xj at the point x, for i=1,2,…,n and j=1,2,…,n, (unless IFLAG is set to a negative value by FCN).
5:   IUSER* – INTEGER arrayUser Workspace
6:   RUSER* – REAL (KIND=nag_wp) arrayUser Workspace
FCN is called with the arguments IUSER and RUSER as supplied to C05RBF. You are free to use the arrays IUSER and RUSER to supply information to FCN as an alternative to using COMMON global variables.
7:   IFLAG – INTEGERInput/Output
On entry: IFLAG=1 or 2.
IFLAG=1
FVEC is to be updated.
IFLAG=2
FJAC is to be updated.
On exit: in general, IFLAG should not be reset by FCN. If, however, you wish to terminate execution (perhaps because some illegal point X has been reached), then IFLAG should be set to a negative integer.
FCN must either be a module subprogram USEd by, or declared as EXTERNAL in, the (sub)program from which C05RBF is called. Arguments denoted as Input must not be changed by this procedure.
2:   N – INTEGERInput
On entry: n, the number of equations.
Constraint: N>0 .
3:   X N – REAL (KIND=nag_wp) arrayInput/Output
On entry: an initial guess at the solution vector.
On exit: the final estimate of the solution vector.
4:   FVEC N – REAL (KIND=nag_wp) arrayOutput
On exit: the function values at the final point returned in X.
5:   FJAC NN – REAL (KIND=nag_wp) arrayOutput
On exit: the orthogonal matrix Q produced by the QR factorization of the final approximate Jacobian.
6:   XTOL – REAL (KIND=nag_wp)Input
On entry: the accuracy in X to which the solution is required.
Suggested value: ε, where ε is the machine precision returned by X02AJF.
Constraint: XTOL≥0.0 .
7:   IUSER* – INTEGER arrayUser Workspace
8:   RUSER* – REAL (KIND=nag_wp) arrayUser Workspace
IUSER and RUSER are not used by C05RBF, but are passed directly to FCN and may be used to pass information to this routine as an alternative to using COMMON global variables.
9:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=2
There have been at least 100 × N+1 calls to FCN. Consider restarting the calculation from the point held in X.
IFAIL=3
No further improvement in the solution is possible. XTOL is too small: XTOL=value.
IFAIL=4
The iteration is not making good progress. This failure exit may indicate that the system does not have a zero, or that the solution is very close to the origin (see Section 7). Otherwise, rerunning C05RBF from a different starting point may avoid the region of difficulty.
IFAIL=5
IFLAG was set negative in FCN. IFLAG=value.
IFAIL=11
On entry, N=value.
Constraint: N>0.
IFAIL=12
On entry, XTOL=value.
Constraint: XTOL≥0.0.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

If x^ is the true solution, C05RBF tries to ensure that
x-x^ 2 ≤ XTOL × x^ 2 .
If this condition is satisfied with XTOL = 10-k , then the larger components of x have k significant decimal digits. There is a danger that the smaller components of x may have large relative errors, but the fast rate of convergence of C05RBF usually obviates this possibility.
If XTOL is less than machine precision and the above test is satisfied with the machine precision in place of XTOL, then the routine exits with IFAIL=3.
Note: this convergence test is based purely on relative error, and may not indicate convergence if the solution is very close to the origin.
The convergence test assumes that the functions and the Jacobian are coded consistently and that the functions are reasonably well behaved. If these conditions are not satisfied, then C05RBF may incorrectly indicate convergence. The coding of the Jacobian can be checked using C05ZDF. If the Jacobian is coded correctly, then the validity of the answer can be checked by rerunning C05RBF with a lower value for XTOL.

8 Parallelism and Performance

C05RBF is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
C05RBF makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

Local workspace arrays of fixed lengths are allocated internally by C05RBF. The total size of these arrays amounts to n×n+13/2 real elements.
The time required by C05RBF to solve a given problem depends on n, the behaviour of the functions, the accuracy requested and the starting point. The number of arithmetic operations executed by C05RBF is approximately 11.5×n 2 to process each evaluation of the functions and approximately 1.3×n 3 to process each evaluation of the Jacobian. The timing of C05RBF is strongly influenced by the time spent evaluating the functions.
Ideally the problem should be scaled so that, at the solution, the function values are of comparable magnitude.

10 Example

This example determines the values x 1 , … , x 9 which satisfy the tridiagonal equations:
3-2 x 1 x 1-2 x 2 = -1, -x i-1+3-2 xi xi-2 x i+1 = -1,  i=2,3,…,8 -x 8+3-2 x 9 x 9 = -1.

10.1 Program Text

Program Text (c05rbfe.f90)

10.2 Program Data

None.

10.3 Program Results

Program Results (c05rbfe.r)

C05 Chapter Contents
C05 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


C05RCF : NAG Library, Mark 26

C05 Chapter Contents
C05 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

C05RCF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

C05RCF is a comprehensive routine that finds a solution of a system of nonlinear equations by a modification of the Powell hybrid method. You must provide the Jacobian.

2 Specification

SUBROUTINE C05RCF ( FCN, N, X, FVEC, FJAC, XTOL, MAXFEV, MODE, DIAG, FACTOR, NPRINT, NFEV, NJEV, R, QTF, IUSER, RUSER, IFAIL)
INTEGER | N, MAXFEV, MODE, NPRINT, NFEV, NJEV, IUSER(*), IFAIL
REAL (KIND=nag_wp) | X(N), FVEC(N), FJAC(N,N), XTOL, DIAG(N), FACTOR, R(N*(N+1)/2), QTF(N), RUSER(*)
EXTERNAL | FCN

3 Description

The system of equations is defined as:
fi x 1,x 2,…,xn = 0 ,   ​ i= 1, 2, …, n .
C05RCF is based on the MINPACK routine HYBRJ (see Moré et al. (1980)). It chooses the correction at each step as a convex combination of the Newton and scaled gradient directions. The Jacobian is updated by the rank-1 method of Broyden. At the starting point, the Jacobian is requested, but it is not asked for again until the rank-1 method fails to produce satisfactory progress. For more details see Powell (1970).

4 References

Moré J J, Garbow B S and Hillstrom K E (1980) User guide for MINPACK-1 Technical Report ANL-80-74 Argonne National Laboratory
Powell M J D (1970) A hybrid method for nonlinear algebraic equations Numerical Methods for Nonlinear Algebraic Equations (ed P Rabinowitz) Gordon and Breach

5 Arguments

1:   FCN – SUBROUTINE, supplied by the user.External Procedure
Depending upon the value of IFLAG, FCN must either return the values of the functions fi at a point x or return the Jacobian at x.
The specification of FCN is:
SUBROUTINE FCN ( N, X, FVEC, FJAC, IUSER, RUSER, IFLAG)
INTEGER | N, IUSER(*), IFLAG
REAL (KIND=nag_wp) | X(N), FVEC(N), FJAC(N,N), RUSER(*)
1:   N – INTEGERInput
On entry: n, the number of equations.
2:   X N – REAL (KIND=nag_wp) arrayInput
On entry: the components of the point x at which the functions or the Jacobian must be evaluated.
3:   FVEC N – REAL (KIND=nag_wp) arrayInput/Output
On entry: if IFLAG=0 or 2, FVEC contains the function values fi x and must not be changed.
On exit: if IFLAG=1 on entry, FVEC must contain the function values fi x (unless IFLAG is set to a negative value by FCN).
4:   FJAC NN – REAL (KIND=nag_wp) arrayInput/Output
On entry: if IFLAG=0, FJAC ij contains the value of ∂fi ∂xj at the point x, for i=1,2,…,n and j=1,2,…,n. When IFLAG=0 or 1, FJAC must not be changed.
On exit: if IFLAG=2 on entry, FJAC ij must contain the value of ∂fi ∂xj at the point x, for i=1,2,…,n and j=1,2,…,n, (unless IFLAG is set to a negative value by FCN).
5:   IUSER* – INTEGER arrayUser Workspace
6:   RUSER* – REAL (KIND=nag_wp) arrayUser Workspace
FCN is called with the arguments IUSER and RUSER as supplied to C05RCF. You are free to use the arrays IUSER and RUSER to supply information to FCN as an alternative to using COMMON global variables.
7:   IFLAG – INTEGERInput/Output
On entry: IFLAG=0, 1 or 2.
IFLAG=0
X, FVEC and FJAC are available for printing (see NPRINT).
IFLAG=1
FVEC is to be updated.
IFLAG=2
FJAC is to be updated.
On exit: in general, IFLAG should not be reset by FCN. If, however, you wish to terminate execution (perhaps because some illegal point X has been reached), then IFLAG should be set to a negative integer value.
FCN must either be a module subprogram USEd by, or declared as EXTERNAL in, the (sub)program from which C05RCF is called. Arguments denoted as Input must not be changed by this procedure.
2:   N – INTEGERInput
On entry: n, the number of equations.
Constraint: N>0 .
3:   X N – REAL (KIND=nag_wp) arrayInput/Output
On entry: an initial guess at the solution vector.
On exit: the final estimate of the solution vector.
4:   FVEC N – REAL (KIND=nag_wp) arrayOutput
On exit: the function values at the final point returned in X.
5:   FJAC NN – REAL (KIND=nag_wp) arrayOutput
On exit: the orthogonal matrix Q produced by the QR factorization of the final approximate Jacobian.
6:   XTOL – REAL (KIND=nag_wp)Input
On entry: the accuracy in X to which the solution is required.
Suggested value: ε, where ε is the machine precision returned by X02AJF.
Constraint: XTOL≥0.0 .
7:   MAXFEV – INTEGERInput
On entry: the maximum number of calls to FCN with IFLAG≠0 . C05RCF will exit with IFAIL=2, if, at the end of an iteration, the number of calls to FCN exceeds MAXFEV.
Suggested value: MAXFEV=100×N+1 .
Constraint: MAXFEV>0 .
8:   MODE – INTEGERInput
On entry: indicates whether or not you have provided scaling factors in DIAG.
If MODE=2 the scaling must have been specified in DIAG.
Otherwise, if MODE=1, the variables will be scaled internally.
Constraint: MODE=1 or 2.
9:   DIAG N – REAL (KIND=nag_wp) arrayInput/Output
On entry: if MODE=2, DIAG must contain multiplicative scale factors for the variables.
If MODE=1, DIAG need not be set.
Constraint: if MODE=2, DIAG i>0.0 , for i=1,2,…,n.
On exit: the scale factors actually used (computed internally if MODE=1).
10:   FACTOR – REAL (KIND=nag_wp)Input
On entry: a quantity to be used in determining the initial step bound. In most cases, FACTOR should lie between 0.1 and 100.0. (The step bound is FACTOR×DIAG×X 2 if this is nonzero; otherwise the bound is FACTOR.)
Suggested value: FACTOR=100.0 .
Constraint: FACTOR>0.0 .
11:   NPRINT – INTEGERInput
On entry: indicates whether (and how often) special calls to FCN, with IFLAG set to 0, are to be made for printing purposes.
NPRINT≤0
No calls are made.
NPRINT>0
FCN is called at the beginning of the first iteration, every NPRINT iterations thereafter and immediately before the return from C05RCF.
12:   NFEV – INTEGEROutput
On exit: the number of calls made to FCN to evaluate the functions.
13:   NJEV – INTEGEROutput
On exit: the number of calls made to FCN to evaluate the Jacobian.
14:   R N×N+1/2 – REAL (KIND=nag_wp) arrayOutput
On exit: the upper triangular matrix R produced by the QR factorization of the final approximate Jacobian, stored row-wise.
15:   QTF N – REAL (KIND=nag_wp) arrayOutput
On exit: the vector QT f .
16:   IUSER* – INTEGER arrayUser Workspace
17:   RUSER* – REAL (KIND=nag_wp) arrayUser Workspace
IUSER and RUSER are not used by C05RCF, but are passed directly to FCN and may be used to pass information to this routine as an alternative to using COMMON global variables.
18:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=2
There have been at least MAXFEV calls to FCN: MAXFEV=value. Consider restarting the calculation from the final point held in X.
IFAIL=3
No further improvement in the solution is possible. XTOL is too small: XTOL=value.
IFAIL=4
The iteration is not making good progress, as measured by the improvement from the last value Jacobian evaluations. This failure exit may indicate that the system does not have a zero, or that the solution is very close to the origin (see Section 7). Otherwise, rerunning C05RCF from a different starting point may avoid the region of difficulty.
IFAIL=5
The iteration is not making good progress, as measured by the improvement from the last value iterations. This failure exit may indicate that the system does not have a zero, or that the solution is very close to the origin (see Section 7). Otherwise, rerunning C05RCF from a different starting point may avoid the region of difficulty.
IFAIL=6
IFLAG was set negative in FCN. IFLAG=value.
IFAIL=11
On entry, N=value.
Constraint: N>0.
IFAIL=12
On entry, XTOL=value.
Constraint: XTOL≥0.0.
IFAIL=13
On entry, MODE=value.
Constraint: MODE=1 or 2.
IFAIL=14
On entry, FACTOR=value.
Constraint: FACTOR>0.0.
IFAIL=15
On entry, MODE=2 and DIAG contained a non-positive element.
IFAIL=18
On entry, MAXFEV=value.
Constraint: MAXFEV>0.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

If x^ is the true solution and D denotes the diagonal matrix whose entries are defined by the array DIAG, then C05RCF tries to ensure that
D x-x^ 2 ≤ XTOL × D x^ 2 .
If this condition is satisfied with XTOL = 10-k , then the larger components of Dx have k significant decimal digits. There is a danger that the smaller components of Dx may have large relative errors, but the fast rate of convergence of C05RCF usually obviates this possibility.
If XTOL is less than machine precision and the above test is satisfied with the machine precision in place of XTOL, then the routine exits with IFAIL=3.
Note: this convergence test is based purely on relative error, and may not indicate convergence if the solution is very close to the origin.
The convergence test assumes that the functions and the Jacobian are coded consistently and that the functions are reasonably well behaved. If these conditions are not satisfied, then C05RCF may incorrectly indicate convergence. The coding of the Jacobian can be checked using C05ZDF. If the Jacobian is coded correctly, then the validity of the answer can be checked by rerunning C05RCF with a lower value for XTOL.

8 Parallelism and Performance

C05RCF is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
C05RCF makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

Local workspace arrays of fixed lengths are allocated internally by C05RCF. The total size of these arrays amounts to 4×n real elements.
The time required by C05RCF to solve a given problem depends on n, the behaviour of the functions, the accuracy requested and the starting point. The number of arithmetic operations executed by C05RCF is approximately 11.5×n 2 to process each evaluation of the functions and approximately 1.3×n 3 to process each evaluation of the Jacobian. The timing of C05RCF is strongly influenced by the time spent evaluating the functions.
Ideally the problem should be scaled so that, at the solution, the function values are of comparable magnitude.

10 Example

This example determines the values x 1 , … , x 9 which satisfy the tridiagonal equations:
3-2 x 1 x 1-2 x 2 = -1, -x i-1+3-2 xi xi-2 x i+1 = -1,  i=2,3,…,8 -x 8+3-2 x 9 x 9 = -1.

10.1 Program Text

Program Text (c05rcfe.f90)

10.2 Program Data

None.

10.3 Program Results

Program Results (c05rcfe.r)

C05 Chapter Contents
C05 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


C05RDF : NAG Library, Mark 26

C05 Chapter Contents
C05 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

C05RDF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

C05RDF is a comprehensive reverse communication routine that finds a solution of a system of nonlinear equations by a modification of the Powell hybrid method. You must provide the Jacobian.

2 Specification

SUBROUTINE C05RDF ( IREVCM, N, X, FVEC, FJAC, XTOL, MODE, DIAG, FACTOR, R, QTF, IWSAV, RWSAV, IFAIL)
INTEGER | IREVCM, N, MODE, IWSAV(17), IFAIL
REAL (KIND=nag_wp) | X(N), FVEC(N), FJAC(N,N), XTOL, DIAG(N), FACTOR, R(N*(N+1)/2), QTF(N), RWSAV(4*N+10)

3 Description

The system of equations is defined as:
fi x 1,x 2,…,xn = 0 ,   i= 1, 2, …, n .
C05RDF is based on the MINPACK routine HYBRJ (see Moré et al. (1980)). It chooses the correction at each step as a convex combination of the Newton and scaled gradient directions. The Jacobian is updated by the rank-1 method of Broyden. For more details see Powell (1970).

4 References

Moré J J, Garbow B S and Hillstrom K E (1980) User guide for MINPACK-1 Technical Report ANL-80-74 Argonne National Laboratory
Powell M J D (1970) A hybrid method for nonlinear algebraic equations Numerical Methods for Nonlinear Algebraic Equations (ed P Rabinowitz) Gordon and Breach

5 Arguments

Note: this routine uses reverse communication. Its use involves an initial entry, intermediate exits and re-entries, and a final exit, as indicated by the argument IREVCM. Between intermediate exits and re-entries, all arguments other than FVEC and FJAC must remain unchanged.
1:   IREVCM – INTEGERInput/Output
On initial entry: must have the value 0.
On intermediate exit: specifies what action you must take before re-entering C05RDF with IREVCM unchanged. The value of IREVCM should be interpreted as follows:
IREVCM=1
Indicates the start of a new iteration. No action is required by you, but X and FVEC are available for printing.
IREVCM=2
Indicates that before re-entry to C05RDF, FVEC must contain the function values fi x .
IREVCM=3
Indicates that before re-entry to C05RDF, FJAC ij must contain the value of ∂fi ∂xj at the point x, for i=1,2,…,n and j=1,2,…,n.
On final exit: IREVCM=0 , and the algorithm has terminated.
Constraint: IREVCM=0, 1, 2 or 3.
2:   N – INTEGERInput
On entry: n, the number of equations.
Constraint: N>0 .
3:   X N – REAL (KIND=nag_wp) arrayInput/Output
On initial entry: an initial guess at the solution vector.
On intermediate exit: contains the current point.
On final exit: the final estimate of the solution vector.
4:   FVEC N – REAL (KIND=nag_wp) arrayInput/Output
On initial entry: need not be set.
On intermediate re-entry: if IREVCM≠2 , FVEC must not be changed.
If IREVCM=2 , FVEC must be set to the values of the functions computed at the current point X.
On final exit: the function values at the final point, X.
5:   FJAC NN – REAL (KIND=nag_wp) arrayInput/Output
On initial entry: need not be set.
On intermediate re-entry: if IREVCM≠3 , FJAC must not be changed.
If IREVCM=3 , FJAC ij must contain the value of ∂fi ∂xj at the point x, for i=1,2,…,n and j=1,2,…,n.
On final exit: the orthogonal matrix Q produced by the QR factorization of the final approximate Jacobian.
6:   XTOL – REAL (KIND=nag_wp)Input
On initial entry: the accuracy in X to which the solution is required.
Suggested value: ε, where ε is the machine precision returned by X02AJF.
Constraint: XTOL≥0.0 .
7:   MODE – INTEGERInput
On initial entry: indicates whether or not you have provided scaling factors in DIAG.
If MODE=2 the scaling must have been supplied in DIAG.
Otherwise, if MODE=1, the variables will be scaled internally.
Constraint: MODE=1 or 2.
8:   DIAG N – REAL (KIND=nag_wp) arrayInput/Output
On initial entry: if MODE=2, DIAG must contain multiplicative scale factors for the variables.
If MODE=1, DIAG need not be set.
Constraint: if MODE=2, DIAG i>0.0 , for i=1,2,…,n.
On intermediate exit: DIAG must not be changed.
On final exit: the scale factors actually used (computed internally if MODE=1).
9:   FACTOR – REAL (KIND=nag_wp)Input
On initial entry: a quantity to be used in determining the initial step bound. In most cases, FACTOR should lie between 0.1 and 100.0. (The step bound is FACTOR×DIAG×X 2 if this is nonzero; otherwise the bound is FACTOR.)
Suggested value: FACTOR=100.0 .
Constraint: FACTOR>0.0 .
10:   R N×N+1/2 – REAL (KIND=nag_wp) arrayInput/Output
On initial entry: need not be set.
On intermediate exit: must not be changed.
On final exit: the upper triangular matrix R produced by the QR factorization of the final approximate Jacobian, stored row-wise.
11:   QTF N – REAL (KIND=nag_wp) arrayInput/Output
On initial entry: need not be set.
On intermediate exit: must not be changed.
On final exit: the vector QT f .
12:   IWSAV 17 – INTEGER arrayCommunication Array
13:   RWSAV 4×N+10 – REAL (KIND=nag_wp) arrayCommunication Array
The arrays IWSAV and RWSAV must not be altered between calls to C05RDF.
14:   IFAIL – INTEGERInput/Output
On initial entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, because for this routine the values of the output arguments may be useful even if IFAIL≠0 on exit, the recommended value is -1. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On final exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=2
On entry, IREVCM=value.
Constraint: IREVCM=0, 1, 2 or 3.
IFAIL=3
No further improvement in the solution is possible. XTOL is too small: XTOL=value.
IFAIL=4
The iteration is not making good progress, as measured by the improvement from the last value Jacobian evaluations. This failure exit may indicate that the system does not have a zero, or that the solution is very close to the origin (see Section 7). Otherwise, rerunning C05RDF from a different starting point may avoid the region of difficulty.
IFAIL=5
The iteration is not making good progress, as measured by the improvement from the last value iterations. This failure exit may indicate that the system does not have a zero, or that the solution is very close to the origin (see Section 7). Otherwise, rerunning C05RDF from a different starting point may avoid the region of difficulty.
IFAIL=11
On entry, N=value.
Constraint: N>0.
IFAIL=12
On entry, XTOL=value.
Constraint: XTOL≥0.0.
IFAIL=13
On entry, MODE=value.
Constraint: MODE=1 or 2.
IFAIL=14
On entry, FACTOR=value.
Constraint: FACTOR>0.0.
IFAIL=15
On entry, MODE=2 and DIAG contained a non-positive element.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

If x^ is the true solution and D denotes the diagonal matrix whose entries are defined by the array DIAG, then C05RDF tries to ensure that
D x-x^ 2 ≤ XTOL × D x^ 2 .
If this condition is satisfied with XTOL = 10-k , then the larger components of Dx have k significant decimal digits. There is a danger that the smaller components of Dx may have large relative errors, but the fast rate of convergence of C05RDF usually obviates this possibility.
If XTOL is less than machine precision and the above test is satisfied with the machine precision in place of XTOL, then the routine exits with IFAIL=3.
Note: this convergence test is based purely on relative error, and may not indicate convergence if the solution is very close to the origin.
The convergence test assumes that the functions and the Jacobian are coded consistently and that the functions are reasonably well behaved. If these conditions are not satisfied, then C05RDF may incorrectly indicate convergence. The coding of the Jacobian can be checked using C05ZDF. If the Jacobian is coded correctly, then the validity of the answer can be checked by rerunning C05RDF with a lower value for XTOL.

8 Parallelism and Performance

C05RDF is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
C05RDF makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The time required by C05RDF to solve a given problem depends on n, the behaviour of the functions, the accuracy requested and the starting point. The number of arithmetic operations executed by C05RDF is approximately 11.5×n 2 to process each evaluation of the functions and approximately 1.3×n 3 to process each evaluation of the Jacobian. The timing of C05RDF is strongly influenced by the time spent evaluating the functions.
Ideally the problem should be scaled so that, at the solution, the function values are of comparable magnitude.

10 Example

This example determines the values x 1 , … , x 9 which satisfy the tridiagonal equations:
3-2 x 1 x 1-2 x 2 = -1, -x i-1+3-2 xi xi-2 x i+1 = -1,  i=2,3,…,8 -x 8+3-2 x 9 x 9 = -1.

10.1 Program Text

Program Text (c05rdfe.f90)

10.2 Program Data

None.

10.3 Program Results

Program Results (c05rdfe.r)

C05 Chapter Contents
C05 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


C05ZDF : NAG Library, Mark 26

C05 Chapter Contents
C05 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

C05ZDF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

C05ZDF checks the user-supplied gradients of a set of nonlinear functions in several variables, for consistency with the functions themselves. The routine must be called twice.

2 Specification

SUBROUTINE C05ZDF ( MODE, M, N, X, FVEC, FJAC, XP, FVECP, ERR, IFAIL)
INTEGER | MODE, M, N, IFAIL
REAL (KIND=nag_wp) | X(N), FVEC(M), FJAC(M,N), XP(N), FVECP(M), ERR(M)

3 Description

C05ZDF is based on the MINPACK routine CHKDER (see Moré et al. (1980)). It checks the ith gradient for consistency with the ith function by computing a forward-difference approximation along a suitably chosen direction and comparing this approximation with the user-supplied gradient along the same direction. The principal characteristic of C05ZDF is its invariance under changes in scale of the variables or functions.

4 References

Moré J J, Garbow B S and Hillstrom K E (1980) User guide for MINPACK-1 Technical Report ANL-80-74 Argonne National Laboratory

5 Arguments

1:   MODE – INTEGERInput
On entry: the value 1 on the first call and the value 2 on the second call of C05ZDF.
Constraint: MODE=1 or 2.
2:   M – INTEGERInput
On entry: m, the number of functions.
Constraint: M≥1.
3:   N – INTEGERInput
On entry: n, the number of variables. For use with C05RBF, C05RCF and C05RDF, M=N.
Constraint: N≥1.
4:   X N – REAL (KIND=nag_wp) arrayInput
On entry: the components of a point x, at which the consistency check is to be made. (See Section 7.)
5:   FVEC M – REAL (KIND=nag_wp) arrayInput
On entry: if MODE=2, FVEC must contain the value of the functions evaluated at x. If MODE=1, FVEC is not referenced.
6:   FJAC MN – REAL (KIND=nag_wp) arrayInput
On entry: if MODE=2, FJAC must contain the value of ∂fi ∂xj at the point x, for i=1,2,…,m and j=1,2,…,n. If MODE=1, FJAC is not referenced.
7:   XP N – REAL (KIND=nag_wp) arrayOutput
On exit: if MODE=1, XP is set to a point neighbouring X. If MODE=2, XP is undefined.
8:   FVECP M – REAL (KIND=nag_wp) arrayInput
On entry: if MODE=2, FVECP must contain the value of the functions evaluated at XP (as output by a preceding call to C05ZDF with MODE=1). If MODE=1, FVECP is not referenced.
9:   ERR M – REAL (KIND=nag_wp) arrayOutput
On exit: if MODE=2, ERR contains measures of correctness of the respective gradients. If MODE=1, ERR is undefined. If there is no loss of significance (see Section 7), then if ERR i is 1.0 the ith user-supplied gradient ∂fi ∂xj , for j=1,2,…,n is correct, whilst if ERR i is 0.0 the ith gradient is incorrect. For values of ERR i between 0.0 and 1.0 the categorisation is less certain. In general, a value of ERR i>0.5 indicates that the ith gradient is probably correct.
10:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, MODE=value.
Constraint: MODE=1 or 2.
IFAIL=2
On entry, M=value.
Constraint: M≥1.
IFAIL=3
On entry, N=value.
Constraint: N≥1.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

C05ZDF does not perform reliably if cancellation or rounding errors cause a severe loss of significance in the evaluation of a function. Therefore, none of the components of x should be unusually small (in particular, zero) or any other value which may cause loss of significance. The relative differences between corresponding elements of FVECP and FVEC should be at least two orders of magnitude greater than the machine precision returned by X02AJF.

8 Parallelism and Performance

C05ZDF is not threaded in any implementation.

9 Further Comments

The time required by C05ZDF increases with M and N.

10 Example

This example checks the Jacobian matrix for a problem with 15 functions of 3 variables (sometimes referred to as the Bard problem).

10.1 Program Text

Program Text (c05zdfe.f90)

10.2 Program Data

None.

10.3 Program Results

Program Results (c05zdfe.r)

C05 Chapter Contents
C05 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


C06BAF : NAG Library, Mark 26

C06 Chapter Contents
C06 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

C06BAF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
▸▿ 9 Further Comments
9.1 Timing
9.2 Choice of LWORK
9.3 Convergence
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

C06BAF accelerates the convergence of a given convergent sequence to its limit.

2 Specification

SUBROUTINE C06BAF ( SEQN, NCALL, RESULT, ABSERR, WORK, LWORK, IFAIL)
INTEGER | NCALL, LWORK, IFAIL
REAL (KIND=nag_wp) | SEQN, RESULT, ABSERR, WORK(LWORK)

3 Description

C06BAF performs Shanks' transformation on a given sequence of real values by means of the Epsilon algorithm of Wynn (1956). A (possibly unreliable) estimate of the absolute error is also given.
The routine must be called repetitively, once for each new term in the sequence.

4 References

Shanks D (1955) Nonlinear transformations of divergent and slowly convergent sequences J. Math. Phys. 34 1–42
Wynn P (1956) On a device for computing the em Sn transformation Math. Tables Aids Comput. 10 91–96

5 Arguments

1:   SEQN – REAL (KIND=nag_wp)Input
On entry: the next term of the sequence to be considered.
2:   NCALL – INTEGERInput/Output
On entry: on the first call NCALL must be set to 0. Thereafter NCALL must not be changed between calls.
On exit: the number of terms in the sequence that have been considered.
3:   RESULT – REAL (KIND=nag_wp)Output
On exit: the estimate of the limit of the sequence. For the first two calls, RESULT=SEQN.
4:   ABSERR – REAL (KIND=nag_wp)Output
On exit: an estimate of the absolute error in RESULT. For the first three calls, ABSERR is set to a large machine-dependent constant.
5:   WORK LWORK – REAL (KIND=nag_wp) arrayCommunication Array
Used as workspace, but must not be changed between calls.
6:   LWORK – INTEGERInput
On entry: the dimension of the array WORK as declared in the (sub)program from which C06BAF is called.
Suggested value: (maximum number of terms in the sequence)+6. See Section 9.2.
Constraint: LWORK≥7.
7:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, NCALL<0.
IFAIL=2
On entry, LWORK<7.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

The accuracy of the absolute error estimate ABSERR varies considerably with the type of sequence to which the routine is applied. In general it is better when applied to oscillating sequences than to monotonic sequences where it may be a severe underestimate.

8 Parallelism and Performance

C06BAF is not threaded in any implementation.

9 Further Comments

9.1 Timing

The time taken is approximately proportional to the final value of NCALL.

9.2 Choice of LWORK

For long sequences, a ‘window’ of the last n values can be used instead of all the terms of the sequence. Tests on a variety of problems indicate that a suitable value is n=50 ; this implies a value for LWORK of 56. You are advised to experiment with other values for your own specific problems.

9.3 Convergence

C06BAF will induce convergence in some divergent sequences. See Shanks (1955) for more details.

10 Example

This example attempts to sum the infinite series
∑ n=1 ∞ -1 n+1 n 2 = π 2 12
by considering the sequence of partial sums
∑ n= 1 1 , ∑ n= 1 2 , ∑ n= 1 3 , … , ∑ n= 1 10

10.1 Program Text

Program Text (c06bafe.f90)

10.2 Program Data

None.

10.3 Program Results

Program Results (c06bafe.r)

GnuplotProduced by GNUPLOT 4.6 patchlevel 3 0.75 0.8 0.85 0.9 0.95 1 1 2 3 4 5 6 7 8 9 10 1e−08 1e−07 1e−06 1e−05 0.0001 0.001 0.01 0.1 1 Result abs(Error) Number of Terms in Sequence Example Program Estimate Sum of Infinite Series by Sequence of Partial Sums result actual error estimated error gnuplot_plot_1 gnuplot_plot_2 gnuplot_plot_3
C06 Chapter Contents
C06 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


C06 Chapter Contents : NAG Library Manual, Mark 26

C06 Chapter Introduction
NAG Library Manual

NAG Library Chapter Contents

C06 – Summation of Series

C06 Chapter Introduction – a description of the Chapter and an overview of the algorithms available

Routine Name | Mark of Introduction | Purpose
C06BAF Example Text Example Plot | 10 | nagf_sum_accelerate Acceleration of convergence of sequence, Shanks' transformation and epsilon algorithm
C06DCF Example Text Example Data | 23 | nagf_sum_chebyshev Sum of a Chebyshev series at a set of points
C06FAF Example Text Example Data | 8 | nagf_sum_fft_real_1d_rfmt Single one-dimensional real discrete Fourier transform, extra workspace for greater speed
C06FBF Example Text Example Data | 8 | nagf_sum_fft_hermitian_1d_rfmt Single one-dimensional Hermitian discrete Fourier transform, extra workspace for greater speed
C06FCF Example Text Example Data | 8 | nagf_sum_fft_complex_1d_sep Single one-dimensional complex discrete Fourier transform, extra workspace for greater speed
C06FFF Example Text Example Data | 11 | nagf_sum_fft_complex_multid_1d_sep One-dimensional complex discrete Fourier transform of multidimensional data
C06FJF Example Text Example Data | 11 | nagf_sum_fft_complex_multid_sep Multidimensional complex discrete Fourier transform of multidimensional data
C06FKF Example Text Example Data | 11 | nagf_sum_convcorr_real Circular convolution or correlation of two real vectors, no restrictions on n
C06FPF Example Text Example Data | 12 | nagf_sum_withdraw_fft_real_1d_multi_rfmt Multiple one-dimensional real discrete Fourier transforms Note: this routine is scheduled for withdrawal at Mark 28, see Advice on Replacement Calls for Withdrawn/Superseded Routines for further information.
C06FQF Example Text Example Data | 12 | nagf_sum_withdraw_fft_hermitian_1d_multi_rfmt Multiple one-dimensional Hermitian discrete Fourier transforms Note: this routine is scheduled for withdrawal at Mark 28, see Advice on Replacement Calls for Withdrawn/Superseded Routines for further information.
C06FXF Example Text Example Data | 17 | nagf_sum_fft_complex_3d_sep Three-dimensional complex discrete Fourier transform
C06LAF Example Text Example Data Example Plot | 12 | nagf_sum_invlaplace_crump Inverse Laplace transform, Crump's method
C06LBF Example Text Example Data Example Plot | 14 | nagf_sum_invlaplace_weeks Inverse Laplace transform, modified Weeks' method
C06LCF | 14 | nagf_sum_invlaplace_weeks_eval Evaluate inverse Laplace transform as computed by C06LBF
C06PAF Example Text Example Data | 19 | nagf_sum_fft_realherm_1d Single one-dimensional real and Hermitian complex discrete Fourier transform, using complex storage format for Hermitian sequences
C06PCF Example Text Example Data | 19 | nagf_sum_fft_complex_1d Single one-dimensional complex discrete Fourier transform, complex data type
C06PFF Example Text Example Data | 19 | nagf_sum_fft_complex_multid_1d One-dimensional complex discrete Fourier transform of multidimensional data (using complex data type)
C06PJF Example Text Example Data | 19 | nagf_sum_fft_complex_multid Multidimensional complex discrete Fourier transform of multidimensional data (using complex data type)
C06PKF Example Text Example Data | 19 | nagf_sum_convcorr_complex Circular convolution or correlation of two complex vectors
C06PPF Example Text Example Data | 19 | nagf_sum_fft_realherm_1d_multi_row Multiple one-dimensional real and Hermitian complex discrete Fourier transforms, using row ordered complex storage format for Hermitian sequences
C06PQF Example Text Example Data | 19 | nagf_sum_fft_realherm_1d_multi_col Multiple one-dimensional real and Hermitian complex discrete Fourier transforms, using column ordered complex storage format for Hermitian sequences
C06PRF Example Text Example Data | 19 | nagf_sum_fft_complex_1d_multi_row Multiple one-dimensional complex discrete Fourier transforms using complex data type
C06PSF Example Text Example Data | 19 | nagf_sum_fft_complex_1d_multi_col Multiple one-dimensional complex discrete Fourier transforms, complex data type
C06PUF Example Text Example Data | 19 | nagf_sum_fft_complex_2d Two-dimensional complex discrete Fourier transform, complex data type
C06PVF Example Text Example Data | 24 | nagf_sum_fft_real_2d Two-dimensional real-to-complex discrete Fourier transform
C06PWF | 24 | nagf_sum_fft_hermitian_2d Two-dimensional complex-to-real discrete Fourier transform
C06PXF Example Text Example Data | 19 | nagf_sum_fft_complex_3d Three-dimensional complex discrete Fourier transform, complex data type
C06PYF Example Text Example Data | 24 | nagf_sum_fft_real_3d Three-dimensional real-to-complex discrete Fourier transform
C06PZF | 24 | nagf_sum_fft_hermitian_3d Three-dimensional complex-to-real discrete Fourier transform
C06RAF Example Text Example Data | 19 | nagf_sum_fft_real_sine_simple Discrete sine transform (easy-to-use)
C06RBF Example Text Example Data | 19 | nagf_sum_fft_real_cosine_simple Discrete cosine transform (easy-to-use)
C06RCF Example Text Example Data | 19 | nagf_sum_fft_real_qtrsine_simple Discrete quarter-wave sine transform (easy-to-use)
C06RDF Example Text Example Data | 19 | nagf_sum_fft_real_qtrcosine_simple Discrete quarter-wave cosine transform (easy-to-use)
C06REF Example Text Example Data | 25 | nagf_sum_fft_sine Multiple discrete sine transforms, simple
C06RFF Example Text Example Data | 25 | nagf_sum_fft_cosine Multiple discrete cosine transforms, simple
C06RGF Example Text Example Data | 25 | nagf_sum_fft_qtrsine Multiple discrete quarter-wave sine transforms, simple
C06RHF Example Text Example Data | 25 | nagf_sum_fft_qtrcosine Multiple discrete quarter-wave cosine transforms, simple
C06 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


C06DCF : NAG Library, Mark 26

C06 Chapter Contents
C06 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

C06DCF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

C06DCF evaluates a polynomial from its Chebyshev series representation at a set of points.

2 Specification

SUBROUTINE C06DCF ( X, LX, XMIN, XMAX, C, N, S, RES, IFAIL)
INTEGER | LX, N, S, IFAIL
REAL (KIND=nag_wp) | X(LX), XMIN, XMAX, C(N), RES(LX)

3 Description

C06DCF evaluates, at each point in a given set X, the sum of a Chebyshev series of one of three forms according to the value of the parameter S:
S=1: | 0.5 c 1+ ∑ j=2 n cj T j-1 x-
S=2: | 0.5 c 1+ ∑ j=2 n cj T 2 j-2 x-
S=3: | ∑ j=1 n cj T 2 j-1 x-
where x- lies in the range -1.0≤x-≤1.0. Here Tr x is the Chebyshev polynomial of order r in x-, defined by cos ry where cos⁡y=x-.
It is assumed that the independent variable x- in the interval -1.0,+1.0 was obtained from your original variable x∈X, a set of real numbers in the interval xmin,xmax, by the linear transformation
x- = 2 x-xmax+xmin xmax-xmin .
The method used is based upon a three-term recurrence relation; for details see Clenshaw (1962).
The coefficients cj are normally generated by other routines, for example they may be those returned by the interpolation routine E01AEF (in vector A), by a least squares fitting routine in Chapter E02, or as the solution of a boundary value problem by D02JAF, D02JBF or D02UEF.

4 References

Clenshaw C W (1962) Chebyshev Series for Mathematical Functions Mathematical tables HMSO

5 Arguments

1:   X LX – REAL (KIND=nag_wp) arrayInput
On entry: x∈X, the set of arguments of the series.
Constraint: XMIN≤X i≤XMAX, for i=1,2,…,LX.
2:   LX – INTEGERInput
On entry: the number of evaluation points in X.
Constraint: LX≥1.
3:   XMIN – REAL (KIND=nag_wp)Input
4:   XMAX – REAL (KIND=nag_wp)Input
On entry: the lower and upper end points respectively of the interval xmin,xmax. The Chebyshev series representation is in terms of the normalized variable x-, where
x- = 2 x-xmax+xmin xmax-xmin .
Constraint: XMIN<XMAX.
5:   C N – REAL (KIND=nag_wp) arrayInput
On entry: C j must contain the coefficient cj of the Chebyshev series, for j=1,2,…,n.
6:   N – INTEGERInput
On entry: n, the number of terms in the series.
Constraint: N≥1.
7:   S – INTEGERInput
On entry: determines the series (see Section 3).
S=1
The series is general.
S=2
The series is even.
S=3
The series is odd.
Constraint: S=1, 2 or 3.
8:   RES LX – REAL (KIND=nag_wp) arrayOutput
On exit: the Chebyshev series evaluated at the set of points X.
9:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, LX=value.
Constraint: LX≥1.
IFAIL=2
On entry, N=value.
Constraint: N≥1.
IFAIL=3
On entry, S=value.
Constraint: S=1, 2 or 3.
IFAIL=4
On entry, XMAX=value and XMIN=value.
Constraint: XMIN<XMAX.
IFAIL=5
On entry, element X value=value, XMIN=value and XMAX=value.
Constraint: XMIN≤X i≤XMAX, for all i.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

There may be a loss of significant figures due to cancellation between terms. However, provided that n is not too large, C06DCF yields results which differ little from the best attainable for the available machine precision.

8 Parallelism and Performance

C06DCF is not threaded in any implementation.

9 Further Comments

The time taken increases with n.
C06DCF has been prepared in the present form to complement a number of integral equation solving routines which use Chebyshev series methods, e.g., D05AAF and D05ABF.

10 Example

This example evaluates
0.5+ T 1 x+ 0.5 T 2 x+ 0.25 T 3 x
at the points X=0.5,1.0,-0.2.

10.1 Program Text

Program Text (c06dcfe.f90)

10.2 Program Data

Program Data (c06dcfe.d)

10.3 Program Results

Program Results (c06dcfe.r)

C06 Chapter Contents
C06 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


C06FAF : NAG Library, Mark 26

C06 Chapter Contents
C06 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

C06FAF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

C06FAF calculates the discrete Fourier transform of a sequence of n real data values (using a work array for extra speed).

2 Specification

SUBROUTINE C06FAF ( X, N, WORK, IFAIL)
INTEGER | N, IFAIL
REAL (KIND=nag_wp) | X(N), WORK(N)

3 Description

Given a sequence of n real data values xj, for j=0,1,…,n-1, C06FAF calculates their discrete Fourier transform defined by
z^k = 1 n ∑ j=0 n-1 xj × exp -i 2 πjk n ,   k= 0, 1, …, n-1 .
(Note the scale factor of 1 n in this definition.) The transformed values z^k are complex, but they form a Hermitian sequence (i.e., z^ n-k is the complex conjugate of z^k ), so they are completely determined by n real numbers (see also the C06 Chapter Introduction).
To compute the inverse discrete Fourier transform defined by
w^k = 1 n ∑ j=0 n-1 xj × exp +i 2 πjk n ,
this routine should be followed by forming the complex conjugates of the z^k ; that is, x k=-x k, for k=n/2+2,…,n.
C06FAF uses the fast Fourier transform (FFT) algorithm (see Brigham (1974)). There are some restrictions on the value of n (see Section 5).

4 References

Brigham E O (1974) The Fast Fourier Transform Prentice–Hall

5 Arguments

1:   X N – REAL (KIND=nag_wp) arrayInput/Output
On entry: if X is declared with bounds 0:N-1 in the subroutine from which C06FAF is called, then X j must contain xj, for j=0,1,…,n-1.
On exit: the discrete Fourier transform stored in Hermitian form. If the components of the transform z^k are written as ak + i bk, and if X is declared with bounds 0:N-1 in the subroutine from which C06FAF is called, then for 0 ≤ k ≤ n/2, ak is contained in X k, and for 1 ≤ k ≤ n-1 / 2 , bk is contained in X n-k. (See also Section 2.1.2 in the C06 Chapter Introduction and Section 10.)
2:   N – INTEGERInput
On entry: n, the number of data values. The largest prime factor of N must not exceed 19, and the total number of prime factors of N, counting repetitions, must not exceed 20.
Constraint: N>1.
3:   WORK N – REAL (KIND=nag_wp) arrayWorkspace
4:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
At least one of the prime factors of N is greater than 19.
IFAIL=2
N has more than 20 prime factors.
IFAIL=3
On entry, N≤1.
IFAIL=4
An unexpected error has occurred in an internal call. Check all subroutine calls and array dimensions. Seek expert help.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

Some indication of accuracy can be obtained by performing a subsequent inverse transform and comparing the results with the original sequence (in exact arithmetic they would be identical).

8 Parallelism and Performance

C06FAF is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
C06FAF makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The time taken is approximately proportional to n × log n, but also depends on the factorization of n. C06FAF is faster if the only prime factors of n are 2, 3 or 5; and fastest of all if n is a power of 2.

10 Example

This example reads in a sequence of real data values and prints their discrete Fourier transform (as computed by C06FAF), after expanding it from Hermitian form into a full complex sequence. It then performs an inverse transform using C06FBF and conjugation, and prints the sequence so obtained alongside the original data values.

10.1 Program Text

Program Text (c06fafe.f90)

10.2 Program Data

Program Data (c06fafe.d)

10.3 Program Results

Program Results (c06fafe.r)

C06 Chapter Contents
C06 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


C06FBF : NAG Library, Mark 26

C06 Chapter Contents
C06 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

C06FBF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

C06FBF calculates the discrete Fourier transform of a Hermitian sequence of n complex data values (using a work array for extra speed).

2 Specification

SUBROUTINE C06FBF ( X, N, WORK, IFAIL)
INTEGER | N, IFAIL
REAL (KIND=nag_wp) | X(N), WORK(N)

3 Description

Given a Hermitian sequence of n complex data values zj (i.e., a sequence such that z 0 is real and z n-j is the complex conjugate of zj , for j=1,2,…,n-1), C06FBF calculates their discrete Fourier transform defined by
x^k = 1 n ∑ j=0 n-1 zj × exp -i 2 πjk n ,   k= 0, 1, …, n-1 .
(Note the scale factor of 1 n in this definition.) The transformed values x^k are purely real (see also the C06 Chapter Introduction).
To compute the inverse discrete Fourier transform defined by
y^k = 1 n ∑ j=0 n-1 zj × exp +i 2 πjk n ,
this routine should be preceded by forming the complex conjugates of the z^k ; that is, x k=-x k, for k=n/2+2,…,n.
C06FBF uses the fast Fourier transform (FFT) algorithm (see Brigham (1974)). There are some restrictions on the value of n (see Section 5).

4 References

Brigham E O (1974) The Fast Fourier Transform Prentice–Hall

5 Arguments

1:   X N – REAL (KIND=nag_wp) arrayInput/Output
On entry: the sequence to be transformed stored in Hermitian form. If the data values zj are written as xj + i yj, and if X is declared with bounds 0:N-1 in the subroutine from which C06FBF is called, then for 0 ≤ j ≤ n/2, xj is contained in X j, and for 1 ≤ j ≤ n-1 / 2 , yj is contained in X n-j. (See also Section 2.1.2 in the C06 Chapter Introduction and Section 10.)
On exit: the components of the discrete Fourier transform x^k. If X is declared with bounds 0:N-1 in the subroutine from which C06FBF is called, then x^k is stored in X k, for k=0,1,…,n-1.
2:   N – INTEGERInput
On entry: n, the number of data values. The largest prime factor of N must not exceed 19, and the total number of prime factors of N, counting repetitions, must not exceed 20.
Constraint: N>1.
3:   WORK N – REAL (KIND=nag_wp) arrayWorkspace
4:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
At least one of the prime factors of N is greater than 19.
IFAIL=2
N has more than 20 prime factors.
IFAIL=3
On entry, N≤1.
IFAIL=4
An unexpected error has occurred in an internal call. Check all subroutine calls and array dimensions. Seek expert help.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

Some indication of accuracy can be obtained by performing a subsequent inverse transform and comparing the results with the original sequence (in exact arithmetic they would be identical).

8 Parallelism and Performance

C06FBF is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
C06FBF makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The time taken is approximately proportional to n × log n, but also depends on the factorization of n. C06FBF is faster if the only prime factors of n are 2, 3 or 5; and fastest of all if n is a power of 2.

10 Example

This example reads in a sequence of real data values which is assumed to be a Hermitian sequence of complex data values stored in Hermitian form. The input sequence is expanded into a full complex sequence and printed alongside the original sequence. The discrete Fourier transform (as computed by C06FBF) is printed out. It then performs an inverse transform using C06FAF and conjugation, and prints the sequence so obtained alongside the original data values.

10.1 Program Text

Program Text (c06fbfe.f90)

10.2 Program Data

Program Data (c06fbfe.d)

10.3 Program Results

Program Results (c06fbfe.r)

C06 Chapter Contents
C06 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


C06FCF : NAG Library, Mark 26

C06 Chapter Contents
C06 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

C06FCF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

C06FCF calculates the discrete Fourier transform of a sequence of n complex data values (using a work array for extra speed).

2 Specification

SUBROUTINE C06FCF ( X, Y, N, WORK, IFAIL)
INTEGER | N, IFAIL
REAL (KIND=nag_wp) | X(N), Y(N), WORK(N)

3 Description

Given a sequence of n complex data values zj , for j=0,1,…,n-1, C06FCF calculates their discrete Fourier transform defined by
z^k = ak + i bk = 1 n ∑ j=0 n-1 zj × exp -i 2 πjk n ,   k= 0, 1, …, n-1 .
(Note the scale factor of 1 n in this definition.)
To compute the inverse discrete Fourier transform defined by
w^k = 1 n ∑ j=0 n-1 zj × exp +i 2 πjk n ,
this routine should be preceded and followed by the complex conjugation of the data values and the transform (by negating the imaginary parts stored in y).
C06FCF uses the fast Fourier transform (FFT) algorithm (see Brigham (1974)). There are some restrictions on the value of n (see Section 5).

4 References

Brigham E O (1974) The Fast Fourier Transform Prentice–Hall

5 Arguments

1:   X N – REAL (KIND=nag_wp) arrayInput/Output
On entry: if X is declared with bounds 0:N-1 in the subroutine from which C06FCF is called, then X j must contain xj, the real part of zj, for j=0,1,…,n-1.
On exit: the real parts ak of the components of the discrete Fourier transform. If X is declared with bounds 0:N-1 in the subroutine from which C06FCF is called, then for 0 ≤ k ≤ n-1, ak is contained in X k.
2:   Y N – REAL (KIND=nag_wp) arrayInput/Output
On entry: if Y is declared with bounds 0:N-1 in the subroutine from which C06FCF is called, then Y j must contain yj, the imaginary part of zj, for j=0,1,…,n-1.
On exit: the imaginary parts bk of the components of the discrete Fourier transform. If Y is declared with bounds 0:N-1 in the subroutine from which C06FCF is called, then for 0≤k≤n-1, bk is contained in Y k.
3:   N – INTEGERInput
On entry: n, the number of data values. The largest prime factor of N must not exceed 19, and the total number of prime factors of N, counting repetitions, must not exceed 20.
Constraint: N>1.
4:   WORK N – REAL (KIND=nag_wp) arrayWorkspace
5:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
At least one of the prime factors of N is greater than 19.
IFAIL=2
N has more than 20 prime factors.
IFAIL=3
On entry, N≤1.
IFAIL=4
An unexpected error has occurred in an internal call. Check all subroutine calls and array dimensions. Seek expert help.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

Some indication of accuracy can be obtained by performing a subsequent inverse transform and comparing the results with the original sequence (in exact arithmetic they would be identical).

8 Parallelism and Performance

C06FCF is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
C06FCF makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The time taken is approximately proportional to n × log n, but also depends on the factorization of n. C06FCF is faster if the only prime factors of n are 2, 3 or 5; and fastest of all if n is a power of 2.

10 Example

This example reads in a sequence of complex data values and prints their discrete Fourier transform (as computed by C06FCF). It then performs an inverse transform using C06FCF, and prints the sequence so obtained alongside the original data values.

10.1 Program Text

Program Text (c06fcfe.f90)

10.2 Program Data

Program Data (c06fcfe.d)

10.3 Program Results

Program Results (c06fcfe.r)

C06 Chapter Contents
C06 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


C06FFF : NAG Library, Mark 26

C06 Chapter Contents
C06 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

C06FFF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

C06FFF computes the discrete Fourier transform of one variable in a multivariate sequence of complex data values.

2 Specification

SUBROUTINE C06FFF ( NDIM, L, ND, N, X, Y, WORK, LWORK, IFAIL)
INTEGER | NDIM, L, ND(NDIM), N, LWORK, IFAIL
REAL (KIND=nag_wp) | X(N), Y(N), WORK(LWORK)

3 Description

C06FFF computes the discrete Fourier transform of one variable (the lth say) in a multivariate sequence of complex data values z j 1 j 2 … jm , for j 1=0,1,…,n 1-1 and j 2=0,1,…,n 2-1, and so on. Thus the individual dimensions are n 1, n 2, …, nm , and the total number of data values is n = n 1 × n 2 ×⋯× nm .
The routine computes n/nl one-dimensional transforms defined by
z^ j 1 … kl … jm = 1 nl ∑ jl=0 nl-1 z j 1 … jl … jm × exp - 2 π i jl kl nl ,
where kl = 0 , 1 ,…, nl-1 .
(Note the scale factor of 1 nl in this definition.)
To compute the inverse discrete Fourier transforms, defined with exp + 2 π i jl kl nl in the above formula instead of exp - 2 π i jl kl nl , this routine should be preceded and followed by the complex conjugation of the data values and the transform (by negating the imaginary parts stored in y).
The data values must be supplied in a pair of one-dimensional arrays (real and imaginary parts separately), in accordance with the Fortran convention for storing multidimensional data (i.e., with the first subscript j 1 varying most rapidly).
This routine calls C06FCF to perform one-dimensional discrete Fourier transforms by the fast Fourier transform (FFT) algorithm in Brigham (1974), and hence there are some restrictions on the values of nl (see Section 5).

4 References

Brigham E O (1974) The Fast Fourier Transform Prentice–Hall

5 Arguments

1:   NDIM – INTEGERInput
On entry: m, the number of dimensions (or variables) in the multivariate data.
Constraint: NDIM≥1.
2:   L – INTEGERInput
On entry: l, the index of the variable (or dimension) on which the discrete Fourier transform is to be performed.
Constraint: 1≤ L≤ NDIM.
3:   ND NDIM – INTEGER arrayInput
On entry: ND i must contain ni (the dimension of the ith variable) , for i=1,2,…,m. The largest prime factor of ND l must not exceed 19, and the total number of prime factors of ND l, counting repetitions, must not exceed 20.
Constraint: ND i≥1, for i=1,2,…,NDIM.
4:   N – INTEGERInput
On entry: n, the total number of data values.
Constraint: N = ND 1 × ND 2 ×⋯× ND NDIM.
5:   X N – REAL (KIND=nag_wp) arrayInput/Output
On entry: X 1 + j 1 + n 1 j 2 + n 1 n 2 j 3 + … must contain the real part of the complex data value z j 1 j 2 … jm , for 0 ≤ j 1 ≤ n 1 -1 , 0 ≤ j 2 ≤ n 2-1 , … ; i.e., the values are stored in consecutive elements of the array according to the Fortran convention for storing multidimensional arrays.
On exit: the real parts of the corresponding elements of the computed transform.
6:   Y N – REAL (KIND=nag_wp) arrayInput/Output
On entry: the imaginary parts of the complex data values, stored in the same way as the real parts in the array X.
On exit: the imaginary parts of the corresponding elements of the computed transform.
7:   WORK LWORK – REAL (KIND=nag_wp) arrayWorkspace
8:   LWORK – INTEGERInput
On entry: the dimension of the array WORK as declared in the (sub)program from which C06FFF is called.
Constraint: LWORK ≥ 3 × ND L .
9:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, NDIM<1.
IFAIL=2
On entry, N≠ ND 1× ND 2×⋯× ND NDIM.
IFAIL=3
On entry, L<1 or L>NDIM.
IFAIL=10×l+1
At least one of the prime factors of ND l is greater than 19.
IFAIL=10×l+2
ND l has more than 20 prime factors.
IFAIL=10×l+3
On entry, ND l<1.
IFAIL=10×l+4
On entry, LWORK<3×ND l.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

Some indication of accuracy can be obtained by performing a subsequent inverse transform and comparing the results with the original sequence (in exact arithmetic they would be identical).

8 Parallelism and Performance

C06FFF is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
C06FFF makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The time taken is approximately proportional to n×log⁡nl , but also depends on the factorization of nl . C06FFF is faster if the only prime factors of nl are 2, 3 or 5; and fastest of all if nl is a power of 2.

10 Example

This example reads in a bivariate sequence of complex data values and prints the discrete Fourier transform of the second variable. It then performs an inverse transform and prints the sequence so obtained, which may be compared with the original data values.

10.1 Program Text

Program Text (c06fffe.f90)

10.2 Program Data

Program Data (c06fffe.d)

10.3 Program Results

Program Results (c06fffe.r)

C06 Chapter Contents
C06 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


C06FJF : NAG Library, Mark 26

C06 Chapter Contents
C06 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

C06FJF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

C06FJF computes the multidimensional discrete Fourier transform of a multivariate sequence of complex data values.

2 Specification

SUBROUTINE C06FJF ( NDIM, ND, N, X, Y, WORK, LWORK, IFAIL)
INTEGER | NDIM, ND(NDIM), N, LWORK, IFAIL
REAL (KIND=nag_wp) | X(N), Y(N), WORK(LWORK)

3 Description

C06FJF computes the multidimensional discrete Fourier transform of a multidimensional sequence of complex data values z j 1 j 2 … jm , where j 1 = 0 , 1 ,…, n 1-1 ,   j 2 = 0 , 1 ,…, n 2-1 , and so on. Thus the individual dimensions are n 1 , n 2 ,…, nm , and the total number of data values is n = n 1 × n 2 ×⋯× nm .
The discrete Fourier transform is here defined (e.g., for m=2 ) by:
z^ k 1 , k 2 = 1 n ∑ j 1=0 n 1-1 ∑ j 2=0 n 2-1 z j 1j 2 × exp -2 πi j 1k 1 n 1 + j 2k 2 n 2 ,
where k 1 = 0 , 1 ,…, n 1-1 , k 2 = 0 , 1 ,…, n 2-1 .
The extension to higher dimensions is obvious. (Note the scale factor of 1 n in this definition.)
To compute the inverse discrete Fourier transform, defined with exp + 2 π i … in the above formula instead of exp - 2 π i … , this routine should be preceded and followed by the complex conjugation of the data values and the transform (by negating the imaginary parts stored in y).
The data values must be supplied in a pair of one-dimensional arrays (real and imaginary parts separately), in accordance with the Fortran convention for storing multidimensional data (i.e., with the first subscript j 1 varying most rapidly).
This routine calls C06FCF to perform one-dimensional discrete Fourier transforms by the fast Fourier transform (FFT) algorithm in Brigham (1974), and hence there are some restrictions on the values of the ni (see Section 5).

4 References

Brigham E O (1974) The Fast Fourier Transform Prentice–Hall

5 Arguments

1:   NDIM – INTEGERInput
On entry: m, the number of dimensions (or variables) in the multivariate data.
Constraint: NDIM≥1.
2:   ND NDIM – INTEGER arrayInput
On entry: ND i must contain ni (the dimension of the ith variable) , for i=1,2,…,m. The largest prime factor of each ND i must not exceed 19, and the total number of prime factors of ND i, counting repetitions, must not exceed 20.
Constraint: ND i≥1, for i=1,2,…,NDIM.
3:   N – INTEGERInput
On entry: n, the total number of data values.
Constraint: N = ND 1 × ND 2 ×⋯× ND NDIM.
4:   X N – REAL (KIND=nag_wp) arrayInput/Output
On entry: X 1 + j 1 + n 1 j 2 + n 1 n 2 j 3 + … must contain the real part of the complex data value z j 1 j 2 … jm , for 0 ≤ j 1 ≤ n 1 -1 , 0 ≤ j 2 ≤ n 2-1 , … ; i.e., the values are stored in consecutive elements of the array according to the Fortran convention for storing multidimensional arrays.
On exit: the real parts of the corresponding elements of the computed transform.
5:   Y N – REAL (KIND=nag_wp) arrayInput/Output
On entry: the imaginary parts of the complex data values, stored in the same way as the real parts in the array X.
On exit: the imaginary parts of the corresponding elements of the computed transform.
6:   WORK LWORK – REAL (KIND=nag_wp) arrayWorkspace
7:   LWORK – INTEGERInput
On entry: the dimension of the array WORK as declared in the (sub)program from which C06FJF is called.
Constraint: LWORK ≥ 3 × max ND i .
8:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, NDIM<1.
IFAIL=2
On entry, N≠ ND 1× ND 2×⋯× ND NDIM.
IFAIL=10×l+1
At least one of the prime factors of ND l is greater than 19.
IFAIL=10×l+2
ND l has more than 20 prime factors.
IFAIL=10×l+3
On entry, ND l<1.
IFAIL=10×l+4
On entry, LWORK<3×ND l.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

Some indication of accuracy can be obtained by performing a subsequent inverse transform and comparing the results with the original sequence (in exact arithmetic they would be identical).

8 Parallelism and Performance

C06FJF is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
C06FJF makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The time taken is approximately proportional to n×log n , but also depends on the factorization of the individual dimensions ND i . C06FJF is faster if the only prime factors are 2, 3 or 5; and fastest of all if they are powers of 2.

10 Example

This example reads in a bivariate sequence of complex data values and prints the two-dimensional Fourier transform. It then performs an inverse transform and prints the sequence so obtained, which may be compared to the original data values.

10.1 Program Text

Program Text (c06fjfe.f90)

10.2 Program Data

Program Data (c06fjfe.d)

10.3 Program Results

Program Results (c06fjfe.r)

C06 Chapter Contents
C06 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


C06FKF : NAG Library, Mark 26

C06 Chapter Contents
C06 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

C06FKF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

C06FKF calculates the circular convolution or correlation of two real vectors of period n (using a work array for extra speed).

2 Specification

SUBROUTINE C06FKF ( JOB, X, Y, N, WORK, IFAIL)
INTEGER | JOB, N, IFAIL
REAL (KIND=nag_wp) | X(N), Y(N), WORK(N)

3 Description

C06FKF computes:
  • if JOB=1, the discrete convolution of x and y, defined by
    zk = ∑ j=0 n-1 xj y k-j = ∑ j=0 n-1 x k-j yj ;
  • if JOB=2, the discrete correlation of x and y defined by
    wk = ∑ j=0 n-1 xj y k+j .
Here x and y are real vectors, assumed to be periodic, with period n, i.e., xj = x j±n = x j±2 n = … ; z and w are then also periodic with period n.
Note: this usage of the terms ‘convolution’ and ‘correlation’ is taken from Brigham (1974). The term ‘convolution’ is sometimes used to denote both these computations.
If x^ , y^ , z^ and w^ are the discrete Fourier transforms of these sequences, i.e.,
x^k = 1 n ∑ j=0 n-1 xj × exp -i 2 πjk n , etc.,
then z^k = n . x^k y^k and w^k = n . x^- k y^k (the bar denoting complex conjugate).
This routine calls the same auxiliary routines as C06PAF to compute discrete Fourier transforms.

4 References

Brigham E O (1974) The Fast Fourier Transform Prentice–Hall

5 Arguments

1:   JOB – INTEGERInput
On entry: the computation to be performed.
JOB=1
zk = ∑ j=0 n-1 x j y k-j (convolution);
JOB=2
w k = ∑ j=0 n-1 x j y k+j (correlation).
Constraint: JOB=1 or 2.
2:   X N – REAL (KIND=nag_wp) arrayInput/Output
On entry: the elements of one period of the vector x. If X is declared with bounds 0:N-1 in the subroutine from which C06FKF is called, then X j must contain xj, for j=0,1,…,n-1.
On exit: the corresponding elements of the discrete convolution or correlation.
3:   Y N – REAL (KIND=nag_wp) arrayInput/Output
On entry: the elements of one period of the vector y. If Y is declared with bounds 0:N-1 in the subroutine from which C06FKF is called, then Y j must contain yj, for j=0,1,…,n-1.
On exit: the discrete Fourier transform of the convolution or correlation returned in the array X; the transform is stored in Hermitian form; if the components of the transform zk are written as ak+i bk, then for 0≤k≤n/2, ak is contained in Y k, and for 1≤k≤n/2-1, bk is contained in Y n-k. (See also Section 2.1.2 in the C06 Chapter Introduction.)
4:   N – INTEGERInput
On entry: n, the number of values in one period of the vectors X and Y.
Constraint: N>1.
5:   WORK N – REAL (KIND=nag_wp) arrayWorkspace
6:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=3
On entry, N≤1.
IFAIL=4
On entry, JOB≠1 or 2.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

The results should be accurate to within a small multiple of the machine precision.

8 Parallelism and Performance

C06FKF is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
C06FKF makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The time taken is approximately proportional to n × log n, but also depends on the factorization of n. C06FKF is faster if the only prime factors of n are 2, 3 or 5; and fastest of all if n is a power of 2.

10 Example

This example reads in the elements of one period of two real vectors x and y, and prints their discrete convolution and correlation (as computed by C06FKF). In realistic computations the number of data values would be much larger.

10.1 Program Text

Program Text (c06fkfe.f90)

10.2 Program Data

Program Data (c06fkfe.d)

10.3 Program Results

Program Results (c06fkfe.r)

C06 Chapter Contents
C06 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


C06FPF : NAG Library, Mark 26

C06 Chapter Contents
C06 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

C06FPF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

C06FPF computes the discrete Fourier transforms of m sequences, each containing n real data values. This routine is designed to be particularly efficient on vector processors.

2 Specification

SUBROUTINE C06FPF ( M, N, X, INIT, TRIG, WORK, IFAIL)
INTEGER | M, N, IFAIL
REAL (KIND=nag_wp) | X(M*N), TRIG(2*N), WORK(M*N)
CHARACTER(1) | INIT

3 Description

Given m sequences of n real data values xjp , for j=0,1,…,n-1 and p=1,2,…,m, C06FPF simultaneously calculates the Fourier transforms of all the sequences defined by
z^ k p = 1 n ∑ j=0 n-1 xjp × exp -i 2 πjk n ,   k= 0, 1, …, n-1 ​ and ​ p= 1,2,…,m .
(Note the scale factor 1 n in this definition.)
The transformed values z^kp are complex, but for each value of p the z^kp form a Hermitian sequence (i.e., z^n-k p is the complex conjugate of z^kp ), so they are completely determined by mn real numbers (see also the C06 Chapter Introduction).
The discrete Fourier transform is sometimes defined using a positive sign in the exponential term:
z^kp = 1 n ∑ j=0 n-1 xjp × exp +i 2 πjk n .
To compute this form, this routine should be followed by forming the complex conjugates of the z^kp ; that is x k=-x k, for k=n/2+1×m+1,…,m×n.
The routine uses a variant of the fast Fourier transform (FFT) algorithm (see Brigham (1974)) known as the Stockham self-sorting algorithm, which is described in Temperton (1983). Special coding is provided for the factors 2, 3, 4, 5 and 6. This routine is designed to be particularly efficient on vector processors, and it becomes especially fast as m, the number of transforms to be computed in parallel, increases.

4 References

Brigham E O (1974) The Fast Fourier Transform Prentice–Hall
Temperton C (1983) Fast mixed-radix real Fourier transforms J. Comput. Phys. 52 340–350

5 Arguments

1:   M – INTEGERInput
On entry: m, the number of sequences to be transformed.
Constraint: M≥1.
2:   N – INTEGERInput
On entry: n, the number of real values in each sequence.
Constraint: N≥1.
3:   X M×N – REAL (KIND=nag_wp) arrayInput/Output
On entry: the data must be stored in X as if in a two-dimensional array of dimension 1:M,0:N-1; each of the m sequences is stored in a row of the array. In other words, if the data values of the pth sequence to be transformed are denoted by xjp, for j=0,1,…,n-1, then the mn elements of the array X must contain the values
x 01 , x 02 ,…, x 0 m , x 11 , x 12 ,…, x 1 m ,…, x n-1 1 , x n-1 2 ,…, x n-1 m .
On exit: the m discrete Fourier transforms stored as if in a two-dimensional array of dimension 1:M,0:N-1. Each of the m transforms is stored in a row of the array in Hermitian form, overwriting the corresponding original sequence. If the n components of the discrete Fourier transform z^ k p are written as akp + i bkp, then for 0 ≤ k ≤ n/2, akp is contained in X pk, and for 1 ≤ k ≤ n-1 / 2, bkp is contained in X p n-k. (See also Section 2.1.2 in the C06 Chapter Introduction.)
4:   INIT – CHARACTER(1)Input
On entry: indicates whether trigonometric coefficients are to be calculated.
INIT='I'
Calculate the required trigonometric coefficients for the given value of n, and store in the array TRIG.
INIT='S' or 'R'
The required trigonometric coefficients are assumed to have been calculated and stored in the array TRIG in a prior call to one of C06FPF or C06FQF. The routine performs a simple check that the current value of n is consistent with the values stored in TRIG.
Constraint: INIT='I', 'S' or 'R'.
5:   TRIG 2×N – REAL (KIND=nag_wp) arrayInput/Output
On entry: if INIT='S' or 'R', TRIG must contain the required trigonometric coefficients that have been previously calculated. Otherwise TRIG need not be set.
On exit: contains the required coefficients (computed by the routine if INIT='I').
6:   WORK M×N – REAL (KIND=nag_wp) arrayWorkspace
7:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, M<1.
IFAIL=2
On entry, N<1.
IFAIL=3
On entry, INIT≠'I', 'S' or 'R'.
IFAIL=4
Not used at this Mark.
IFAIL=5
On entry, INIT='S' or 'R', but the array TRIG and the current value of N are inconsistent.
IFAIL=6
An unexpected error has occurred in an internal call. Check all subroutine calls and array dimensions. Seek expert help.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

Some indication of accuracy can be obtained by performing a subsequent inverse transform and comparing the results with the original sequence (in exact arithmetic they would be identical).

8 Parallelism and Performance

C06FPF is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
C06FPF makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The time taken by C06FPF is approximately proportional to nm log n, but also depends on the factors of n. C06FPF is fastest if the only prime factors of n are 2, 3 and 5, and is particularly slow if n is a large prime, or has large prime factors.

10 Example

This example reads in sequences of real data values and prints their discrete Fourier transforms (as computed by C06FPF). The Fourier transforms are expanded into full complex form using and printed. Inverse transforms are then calculated by conjugating and calling C06FQF showing that the original sequences are restored.

10.1 Program Text

Program Text (c06fpfe.f90)

10.2 Program Data

Program Data (c06fpfe.d)

10.3 Program Results

Program Results (c06fpfe.r)

C06 Chapter Contents
C06 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


C06FQF : NAG Library, Mark 26

C06 Chapter Contents
C06 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

C06FQF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

C06FQF computes the discrete Fourier transforms of m Hermitian sequences, each containing n complex data values. This routine is designed to be particularly efficient on vector processors.

2 Specification

SUBROUTINE C06FQF ( M, N, X, INIT, TRIG, WORK, IFAIL)
INTEGER | M, N, IFAIL
REAL (KIND=nag_wp) | X(M*N), TRIG(2*N), WORK(M*N)
CHARACTER(1) | INIT

3 Description

Given m Hermitian sequences of n complex data values zjp , for j=0,1,…,n-1 and p=1,2,…,m, C06FQF simultaneously calculates the Fourier transforms of all the sequences defined by
x^kp = 1 n ∑ j=0 n-1 zjp × exp -i 2 πjk n ,   k= 0, 1, …, n-1 ​ and ​ p= 1, 2, …, m .
(Note the scale factor 1 n in this definition.)
The transformed values are purely real (see also the C06 Chapter Introduction).
The discrete Fourier transform is sometimes defined using a positive sign in the exponential term
x^kp = 1 n ∑ j=0 n-1 zjp × exp +i 2 πjk n .
To compute this form, this routine should be preceded by forming the complex conjugates of the z^kp ; that is x k=-x k, for k=n/2+1×m+1,…,m×n.
The routine uses a variant of the fast Fourier transform (FFT) algorithm (see Brigham (1974)) known as the Stockham self-sorting algorithm, which is described in Temperton (1983). Special coding is provided for the factors 2, 3, 4, 5 and 6. This routine is designed to be particularly efficient on vector processors, and it becomes especially fast as m, the number of transforms to be computed in parallel, increases.

4 References

Brigham E O (1974) The Fast Fourier Transform Prentice–Hall
Temperton C (1983) Fast mixed-radix real Fourier transforms J. Comput. Phys. 52 340–350

5 Arguments

1:   M – INTEGERInput
On entry: m, the number of sequences to be transformed.
Constraint: M≥1.
2:   N – INTEGERInput
On entry: n, the number of data values in each sequence.
Constraint: N≥1.
3:   X M×N – REAL (KIND=nag_wp) arrayInput/Output
On entry: the data must be stored in X as if in a two-dimensional array of dimension 1:M,0:N-1; each of the m sequences is stored in a row of the array in Hermitian form. If the n data values zjp are written as xjp + i yjp, then for 0 ≤ j ≤ n/2, xjp is contained in X pj, and for 1 ≤ j ≤ n-1/2, yjp is contained in X p n-j. (See also Section 2.1.2 in the C06 Chapter Introduction.)
On exit: the components of the m discrete Fourier transforms, stored as if in a two-dimensional array of dimension 1:M,0:N-1 . Each of the m transforms is stored as a row of the array, overwriting the corresponding original sequence. If the n components of the discrete Fourier transform are denoted by x^kp , for k=0,1,…,n-1, then the mn elements of the array X contain the values
x^01 , x^02 ,…, x^0 m , x^11 , x^12 ,…, x^1 m ,…, x^ n-1 1 , x^ n-1 2 ,…, x^ n-1 m .
4:   INIT – CHARACTER(1)Input
On entry: indicates whether trigonometric coefficients are to be calculated.
INIT='I'
Calculate the required trigonometric coefficients for the given value of n, and store in the array TRIG.
INIT='S' or 'R'
The required trigonometric coefficients are assumed to have been calculated and stored in the array TRIG in a prior call to one of C06FPF or C06FQF. The routine performs a simple check that the current value of n is consistent with the values stored in TRIG.
Constraint: INIT='I', 'S' or 'R'.
5:   TRIG 2×N – REAL (KIND=nag_wp) arrayInput/Output
On entry: if INIT='S' or 'R', TRIG must contain the required trigonometric coefficients that have been previously calculated. Otherwise TRIG need not be set.
On exit: contains the required coefficients (computed by the routine if INIT='I').
6:   WORK M×N – REAL (KIND=nag_wp) arrayWorkspace
7:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, M<1.
IFAIL=2
On entry, N<1.
IFAIL=3
On entry, INIT≠'I', 'S' or 'R'.
IFAIL=4
Not used at this Mark.
IFAIL=5
On entry, INIT='S' or 'R', but the array TRIG and the current value of N are inconsistent.
IFAIL=6
An unexpected error has occurred in an internal call. Check all subroutine calls and array dimensions. Seek expert help.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

Some indication of accuracy can be obtained by performing a subsequent inverse transform and comparing the results with the original sequence (in exact arithmetic they would be identical).

8 Parallelism and Performance

C06FQF is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
C06FQF makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The time taken by C06FQF is approximately proportional to nm log n, but also depends on the factors of n. C06FQF is fastest if the only prime factors of n are 2, 3 and 5, and is particularly slow if n is a large prime, or has large prime factors.

10 Example

This example reads in sequences of real data values which are assumed to be Hermitian sequences of complex data stored in Hermitian form. The sequences are expanded into full complex form and printed. The discrete Fourier transforms are then computed (using C06FQF) and printed out. Inverse transforms are then calculated by conjugating and calling C06FPF showing that the original sequences are restored.

10.1 Program Text

Program Text (c06fqfe.f90)

10.2 Program Data

Program Data (c06fqfe.d)

10.3 Program Results

Program Results (c06fqfe.r)

C06 Chapter Contents
C06 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


C06FXF : NAG Library, Mark 26

C06 Chapter Contents
C06 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

C06FXF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

C06FXF computes the three-dimensional discrete Fourier transform of a trivariate sequence of complex data values. This routine is designed to be particularly efficient on vector processors.

2 Specification

SUBROUTINE C06FXF ( N1, N2, N3, X, Y, INIT, TRIGN1, TRIGN2, TRIGN3, WORK, IFAIL)
INTEGER | N1, N2, N3, IFAIL
REAL (KIND=nag_wp) | X(N1*N2*N3), Y(N1*N2*N3), TRIGN1(1), TRIGN2(1), TRIGN3(1), WORK(1)
CHARACTER(1) | INIT

3 Description

C06FXF computes the three-dimensional discrete Fourier transform of a trivariate sequence of complex data values z j 1 j 2 j 3 , for j 1=0,1,…,n 1-1, j 2=0,1,…,n 2-1 and j 3=0,1,…,n 3-1.
The discrete Fourier transform is here defined by
z^ k 1 k 2 k 3 = 1 n 1 n 2 n 3 ∑ j 1=0 n 1-1 ∑ j 2=0 n 2-1 ∑ j 3=0 n 3-1 z j 1 j 2 j 3 × exp -2 πi j 1k 1 n 1 + j 2k 2 n 2 + j 3k 3 n 3 ,
where k 1=0,1,…,n 1-1 , k 2=0,1,…,n 2-1 , k 3=0,1,…,n 3-1 .
(Note the scale factor of 1 n 1 n 2 n 3 in this definition.)
To compute the inverse discrete Fourier transform, defined with exp +2 πi … in the above formula instead of exp -2 πi … , this routine should be preceded and followed by forming the complex conjugates of the data values and the transform.
This routine performs, for each dimension, multiple one-dimensional discrete Fourier transforms by the fast Fourier transform (FFT) algorithm (see Brigham (1974)). It is designed to be particularly efficient on vector processors.

4 References

Brigham E O (1974) The Fast Fourier Transform Prentice–Hall
Temperton C (1983) Self-sorting mixed-radix fast Fourier transforms J. Comput. Phys. 52 1–23

5 Arguments

1:   N1 – INTEGERInput
On entry: n 1, the first dimension of the transform.
Constraint: N1≥1.
2:   N2 – INTEGERInput
On entry: n 2, the second dimension of the transform.
Constraint: N2≥1.
3:   N3 – INTEGERInput
On entry: n 3, the third dimension of the transform.
Constraint: N3≥1.
4:   X N1×N2×N3 – REAL (KIND=nag_wp) arrayInput/Output
5:   Y N1×N2×N3 – REAL (KIND=nag_wp) arrayInput/Output
On entry: the real and imaginary parts of the complex data values must be stored in arrays X and Y respectively. If X and Y are regarded as three-dimensional arrays of dimension 0:N1-1,0:N2-1,0:N3-1, then X j 1j 2j 3 and Y j 1j 2j 3 must contain the real and imaginary parts of z j 1 j 2 j 3 .
On exit: the real and imaginary parts respectively of the corresponding elements of the computed transform.
6:   INIT – CHARACTER(1)Input
7:   TRIGN1 1 – REAL (KIND=nag_wp) arrayInput/Output
8:   TRIGN2 1 – REAL (KIND=nag_wp) arrayInput/Output
9:   TRIGN3 1 – REAL (KIND=nag_wp) arrayInput/Output
10:   WORK 1 – REAL (KIND=nag_wp) arrayOutput
These arguments are no longer accessed by C06FXF.
11:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, N1<1.
IFAIL=2
On entry, N2<1.
IFAIL=3
On entry, N3<1.
IFAIL=4
Not used at this Mark.
IFAIL=5
Not used at this Mark.
IFAIL=6
Not used at this Mark.
IFAIL=7
An unexpected error has occurred in an internal call. Check all subroutine calls and array dimensions. Seek expert help.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

Some indication of accuracy can be obtained by performing a subsequent inverse transform and comparing the results with the original sequence (in exact arithmetic they would be identical).

8 Parallelism and Performance

C06FXF is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
C06FXF makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The time taken is approximately proportional to n 1 n 2 n 3 × log n 1 n 2 n 3 , but also depends on the factorization of the individual dimensions n 1 , n 2 and n 3 . C06FXF is faster if the only prime factors are 2, 3 or 5; and fastest of all if they are powers of 2.

10 Example

This example reads in a trivariate sequence of complex data values and prints the three-dimensional Fourier transform. It then performs an inverse transform and prints the sequence so obtained, which may be compared to the original data values.

10.1 Program Text

Program Text (c06fxfe.f90)

10.2 Program Data

Program Data (c06fxfe.d)

10.3 Program Results

Program Results (c06fxfe.r)

C06 Chapter Contents
C06 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


C06 Chapter Introduction : NAG Library, Mark 26

C06 Chapter Contents
NAG Library Manual

NAG Library Chapter Introduction

C06 – Summation of Series

▸▿ Contents

1 Scope of the Chapter
▸▿ 2 Background to the Problems
▸▿ 2.1 Discrete Fourier Transforms
2.1.1 Complex transforms
2.1.2 Real transforms
2.1.3 Real symmetric transforms
2.1.4 Fourier integral transforms
2.1.5 Convolutions and correlations
2.1.6 Applications to solving partial differential equations (PDEs)
2.2 Inverse Laplace Transforms
2.3 Direct Summation of Orthogonal Series
2.4 Acceleration of Convergence
▸▿ 3 Recommendations on Choice and Use of Available Routines
▸▿ 3.1 One-dimensional Fourier Transforms
3.1.1 Real and Hermitian data
3.1.2 Complex data
3.2 Half- and Quarter-wave Transforms
3.3 Application to Elliptic Partial Differential Equations
3.4 Multidimensional Fourier Transforms
3.5 Convolution and Correlation
3.6 Inverse Laplace Transforms
3.7 Direct Summation of Orthogonal Series
3.8 Acceleration of Convergence
4 Decision Trees
5 Functionality Index
6 Auxiliary Routines Associated with Library Routine Arguments
7 Routines Withdrawn or Scheduled for Withdrawal
8 References

1 Scope of the Chapter

This chapter is concerned with the following tasks.
(a) | Calculating the discrete Fourier transform of a sequence of real or complex data values.
(b) | Calculating the discrete convolution or the discrete correlation of two sequences of real or complex data values using discrete Fourier transforms.
(c) | Calculating the inverse Laplace transform of a user-supplied subroutine.
(d) | Direct summation of orthogonal series.
(e) | Acceleration of convergence of a seuqnce of real values.

2 Background to the Problems

2.1 Discrete Fourier Transforms

2.1.1 Complex transforms

Most of the routines in this chapter calculate the finite discrete Fourier transform (DFT) of a sequence of n complex numbers zj , for j=0,1,…,n-1. The direct transform is defined by
z^k = 1 n ∑ j=0 n-1 zj exp -i 2 πjk n (1)
for k=0,1,…,n-1 . Note that equation (1) makes sense for all integral k and with this extension z^k is periodic with period n, i.e., z^k = z^ k±n , and in particular z^ -k = z^ n-k . Note also that the scale-factor of 1 n may be omitted in the definition of the DFT, and replaced by 1 n in the definition of the inverse.
If we write zj = xj + i yj and z^k = ak + i bk , then the definition of z^k may be written in terms of sines and cosines as
ak = 1 n ∑ j=0 n-1 xj cos 2 πjk n + yj sin 2 πjk n
bk = 1 n ∑ j= 0 n- 1 yj cos 2 πjk n - xj sin 2 πjk n .
The original data values zj may conversely be recovered from the transform z^k by an inverse discrete Fourier transform:
zj = 1 n ∑ k=0 n-1 z^k exp +i 2 πjk n (2)
for j=0,1,…,n-1 . If we take the complex conjugate of (2), we find that the sequence z-j is the DFT of the sequence z^- k . Hence the inverse DFT of the sequence z^k may be obtained by taking the complex conjugates of the z^k ; performing a DFT, and taking the complex conjugates of the result. (Note that the terms forward transform and backward transform are also used to mean the direct and inverse transforms respectively.)
The definition (1) of a one-dimensional transform can easily be extended to multidimensional transforms. For example, in two dimensions we have
z^ k 1 k 2 = 1 n 1 n 2 ∑ j 1=0 n 1-1 ∑ j 2=0 n 2-1 z j 1 j 2 exp -i 2 π j 1 k 1 n 1 exp -i 2 π j 2 k 2 n 2 . (3)
Note: definitions of the discrete Fourier transform vary. Sometimes (2) is used as the definition of the DFT, and (1) as the definition of the inverse.

2.1.2 Real transforms

If the original sequence is purely real valued, i.e., zj=xj , then
z^k = ak + i bk = 1 n ∑ j=0 n-1 xj exp -i 2 πjk n
and z^ n-k is the complex conjugate of z^k . Thus the DFT of a real sequence is a particular type of complex sequence, called a Hermitian sequence, or half-complex or conjugate symmetric, with the properties
a n-k = ak   b n-k = -b k   b 0 = 0
and, if n is even, b n/2 = 0 .
Thus a Hermitian sequence of n complex data values can be represented by only n, rather than 2 n , independent real values. This can obviously lead to economies in storage, with two schemes being used in this chapter. In the first (deprecated) scheme, which will be referred to as the real storage format for Hermitian sequences, the real parts ak for 0≤ k≤ n/2 are stored in normal order in the first n/2 + 1 locations of an array X of length n; the corresponding nonzero imaginary parts are stored in reverse order in the remaining locations of X. To clarify, if X is declared with bounds 0:n-1 in your calling subroutine, the following two tables illustrate the storage of the real and imaginary parts of z^k for the two cases: n even and n odd.
If n is even then the sequence has two purely real elements and is stored as follows:
Index of X | 0 | 1 | 2 | … | n/2 | … | n-2 | n-1
Sequence | a 0 | a 1 + ib 1 | a 2 + ib 2 | … | a n/2 | … | a 2 - ib 2 | a 1 - ib 1
Stored values | a 0 | a 1 | a 2 | … | a n/2 | … | b 2 | b 1
X k = ak , for ​ k= 0, 1, …, n/2 , and X n-k = bk , for ​ k= 1, 2, …, n/2-1 .
If n is odd then the sequence has one purely real element and, letting n=2 s+1 , is stored as follows:
Index of X | 0 | 1 | 2 | … | s | s+1 | … | n-2 | n-1
Sequence | a 0 | a 1 + ib 1 | a 2 + ib 2 | … | as + i bs | as - i bs | … | a 2 - ib 2 | a 1 - ib 1
Stored values | a 0 | a 1 | a 2 | … | as | bs | … | b 2 | b 1
X k = ak , for ​ k= 0, 1, …, s , and X n-k = bk , for ​ k= 1, 2, …, s .
The second (recommended) storage scheme, referred to in this chapter as the complex storage format for Hermitian sequences, stores the real and imaginary parts ak , bk , for 0≤ k≤ n/2 , in consecutive locations of an array X of length n+2 . If X is declared with bounds 0:n+1 in your calling subroutine, the following two tables illustrate the storage of the real and imaginary parts of z^k for the two cases: n even and n odd.
If n is even then the sequence has two purely real elements and is stored as follows:
Index of X | 0 | 1 | 2 | 3 | … | n-2 | n-1 | n | n+1
Stored values | a 0 | b 0=0 | a 1 | b 1 | … | a n/2-1 | b n/2-1 | a n/2 | b n/2 = 0
X 2×k = ak , for ​ k= 0, 1, …, n/2 , and X 2×k+1 = bk , for ​ k= 0, 1, …, n/2 .
If n is odd then the sequence has one purely real element and, letting n=2 s+1 , is stored as follows:
Index of X | 0 | 1 | 2 | 3 | … | n-2 | n-1 | n | n+1
Stored values | a 0 | b 0=0 | a 1 | b 1 | … | b s-1 | as | bs | 0
X 2×k = ak , for ​ k= 0, 1, …, s , and X 2×k+1 = bk , for ​ k= 0, 1, …, s .
Also, given a Hermitian sequence, the inverse (or backward) discrete transform produces a real sequence. That is,
xj = 1 n a 0 + 2 ∑ k=1 n/2-1 ak cos 2 πjk n - bk sin 2 πjk n + a n/2
where a n/2 = 0 if n is odd.
For real data that is two-dimensional or higher, the symmetry in the transform persists for the leading dimension only. So, using the notation of equation (3) for the complex two-dimensional discrete transform, we have that z^k 1k 2 is the complex conjugate of z^n 1-k 1 k 2. It is more convenient for transformed data of two or more dimensions to be stored as a complex sequence of length n 1/2+1×n 2×⋯×nd where d is the number of dimensions. The inverse discrete Fourier transform operating on such a complex sequence (Hermitian in the leading dimension) returns a real array of full dimension (n 1×n 2×⋯×nd).

2.1.3 Real symmetric transforms

In many applications the sequence xj will not only be real, but may also possess additional symmetries which we may exploit to reduce further the computing time and storage requirements. For example, if the sequence xj is odd, xj = -x n-j , then the discrete Fourier transform of xj contains only sine terms. Rather than compute the transform of an odd sequence, we define the sine transform of a real sequence by
x^k = 2 n ∑j=1 n-1 xj sin πjk n ,
which could have been computed using the Fourier transform of a real odd sequence of length 2 n . In this case the xj are arbitrary, and the symmetry only becomes apparent when the sequence is extended. Similarly we define the cosine transform of a real sequence by
x^k = 2 n 12 x 0 + ∑ j=1 n-1 xj cos πjk n + 12 -1 k xn
which could have been computed using the Fourier transform of a real even sequence of length 2 n .
In addition to these ‘half-wave’ symmetries described above, sequences arise in practice with ‘quarter-wave’ symmetries. We define the quarter-wave sine transform by
x^k = 1 n ∑ j=1 n-1 xj sin π j 2 k-1 2 n + 12 -1 k-1 xn
which could have been computed using the Fourier transform of a real sequence of length 4 n of the form
0,x 1,…,xn,x n-1 ,…,x 1,0,-x 1,…,-x n, -x n-1 ,…, -x 1 .
Similarly we may define the quarter-wave cosine transform by
x^k = 1 n 12 x 0 + ∑j= 1 n- 1 xj cos π j 2 k- 1 2 n
which could have been computed using the Fourier transform of a real sequence of length 4 n of the form
x 0,x 1,…, x n-1 ,0, -x n-1 ,…,-x 0,-x 1,…, -x n-1 ,0, x n-1 ,…,x 1 .

2.1.4 Fourier integral transforms

The usual application of the discrete Fourier transform is that of obtaining an approximation of the Fourier integral transform
F s = ∫ -∞ ∞ f t exp -i 2 π s t dt
when f t is negligible outside some region 0,c . Dividing the region into n equal intervals we have
F s ≅ cn ∑ j=0 n-1 fj exp -i 2 π s j c n
and so
Fk ≅ cn ∑ j= 0 n- 1 fj exp -i 2 π jk n
for k=0,1,…,n-1 , where fj = f jc/n and Fk = F k/c .
Hence the discrete Fourier transform gives an approximation to the Fourier integral transform in the region s=0 to s=n/c .
If the function f t is defined over some more general interval a,b , then the integral transform can still be approximated by the discrete transform provided a shift is applied to move the point a to the origin.

2.1.5 Convolutions and correlations

One of the most important applications of the discrete Fourier transform is to the computation of the discrete convolution or correlation of two vectors x and y defined (as in Brigham (1974)) by
  • convolution: zk = ∑ j=0 n-1 xj y k-j
  • correlation: wk = ∑j=0 n-1 x-j y k+j
(Here x and y are assumed to be periodic with period n.)
Under certain circumstances (see Brigham (1974)) these can be used as approximations to the convolution or correlation integrals defined by
z s = ∫ -∞ ∞ x t y s-t dt
and
w s = ∫ -∞ ∞ x- t y s+t dt ,   -∞ < s < ∞ .
For more general advice on the use of Fourier transforms, see Hamming (1962); more detailed information on the fast Fourier transform algorithm can be found in Gentleman and Sande (1966) and Brigham (1974).

2.1.6 Applications to solving partial differential equations (PDEs)

A further application of the fast Fourier transform, and in particular of the Fourier transforms of symmetric sequences, is in the solution of elliptic PDEs. If an equation is discretized using finite differences, then it is possible to reduce the problem of solving the resulting large system of linear equations to that of solving a number of tridiagonal systems of linear equations. This is accomplished by uncoupling the equations using Fourier transforms, where the nature of the boundary conditions determines the choice of transforms – see Section 3.3. Full details of the Fourier method for the solution of PDEs may be found in Swarztrauber (1977) and Swarztrauber (1984).

2.2 Inverse Laplace Transforms

Let f t be a real function of t, with f t=0 for t<0 , and be piecewise continuous and of exponential order α, i.e.,
f t ≤ M e αt
for large t, where α is the minimal such exponent.
The Laplace transform of f t is given by
F s = ∫0∞ e-st f t dt ,   t>0
where F s is defined for Re s > α .
The inverse transform is defined by the Bromwich integral
f t = 1 2 πi ∫ a-i∞ a+i∞ e st F s ds ,   t>0 .
The integration is performed along the line s=a in the complex plane, where a>α . This is equivalent to saying that the line s=a lies to the right of all singularities of F s . For this reason, the value of α is crucial to the correct evaluation of the inverse. It is not essential to know α exactly, but an upper bound must be known.
The problem of determining an inverse Laplace transform may be classified according to whether (a) F s is known for real values only, or (b) F s is known in functional form and can therefore be calculated for complex values of s. Problem (a) is very ill-defined and no routines are provided. Two methods are provided for problem (b).

2.3 Direct Summation of Orthogonal Series

For any series of functions ϕi which satisfy a recurrence
ϕ r+1 x + αr x ϕr x + βr x ϕ r-1 x =0
the sum
∑ r= 0 n ar ϕr x
is given by
∑ r=0 n ar ϕr x = b 0 x ϕ 0 x + b 1 x ϕ 1 x + α 0 x ϕ 0 x
where
br x + αr x b r+ 1 x + β r+ 1 x b r+ 2 x = ar b n+ 1 x = b n+ 2 x = 0 .
This may be used to compute the sum of the series. For further reading, see Hamming (1962).

2.4 Acceleration of Convergence

This device has applications in a large number of fields, such as summation of series, calculation of integrals with oscillatory integrands (including, for example, Hankel transforms), and root-finding. The mathematical description is as follows. Given a sequence of values sn , for n=m,…,m+2 l, then, except in certain singular cases, arguments, a, bi , ci may be determined such that
sn = a + ∑ i=1 l bi cin .
If the sequence sn converges, then a may be taken as an estimate of the limit. The method will also find a pseudo-limit of certain divergent sequences – see Shanks (1955) for details.
To use the method to sum a series, the terms sn of the sequence should be the partial sums of the series, e.g., sn = ∑ k=1 n tk , where tk is the kth term of the series. The algorithm can also be used to some advantage to evaluate integrals with oscillatory integrands; one approach is to write the integral (in this case over a semi-infinite interval) as
∫0∞ f x dx = ∫0 a 1 f x dx + ∫ a 1 a 2 f x dx + ∫ a 2 a 3 f x dx + …
and to consider the sequence of values
s 1 = ∫ 0 a 1 f x dx ,   s 2 = ∫ 0 a 2 f x dx = s 1 + ∫ a 1 a 2 f x dx , etc.,
where the integrals are evaluated using standard quadrature methods. In choosing the values of the ak , it is worth bearing in mind that C06BAF converges much more rapidly for sequences whose values oscillate about a limit. The ak should thus be chosen to be (close to) the zeros of f x , so that successive contributions to the integral are of opposite sign. As an example, consider the case where f x = M x sin⁡x and M x>0 : convergence will be much improved if ak = kπ rather than ak = 2 kπ .

3 Recommendations on Choice and Use of Available Routines

The fast Fourier transform algorithm ceases to be ‘fast’ if applied to values of n which cannot be expressed as a product of small prime factors. All the FFT routines in this chapter are particularly efficient if the only prime factors of n are 2, 3 or 5.

3.1 One-dimensional Fourier Transforms

The choice of routine is determined first of all by whether the data values constitute a real, Hermitian or general complex sequence. It is wasteful of time and storage to use an inappropriate routine.

3.1.1 Real and Hermitian data

C06PAF transforms a single sequence of real data onto (and in-place) a representation of the transformed Hermitian sequence using the complex storage scheme described in Section 2.1.2. C06PAF also performs the inverse transform using the representation of Hermitian data and transforming back to a real data sequence.
Alternatively, the two-dimensional routine C06PVF can be used (on setting the second dimension to 1) to transform a sequence of real data onto an Hermitian sequence whose first half is stored in a separate Complex array. The second half need not be stored since these are the complex conjugate of the first half in reverse order. C06PWF performs the inverse operation, transforming the the Hermitian sequence (half-)stored in a Complex array onto a separate real array.

3.1.2 Complex data

C06PCF transforms a single complex sequence in-place; it also performs the inverse transform. C06PSF transforms multiple complex sequences, each stored sequentially; it also performs the inverse transform on multiple complex sequences. This routine is designed to perform several transforms in a single call, all with the same value of n.
If extensive use is to be made of these routines and you are concerned about efficiency, you are advised to conduct your own timing tests.

3.2 Half- and Quarter-wave Transforms

Four routines are provided for computing fast Fourier transforms (FFTs) of real symmetric sequences. C06REF computes multiple Fourier sine transforms, C06RFF computes multiple Fourier cosine transforms, C06RGF computes multiple quarter-wave Fourier sine transforms, and C06RHF computes multiple quarter-wave Fourier cosine transforms.

3.3 Application to Elliptic Partial Differential Equations

As described in Section 2.1.6, Fourier transforms may be used in the solution of elliptic PDEs.
C06REF may be used to solve equations where the solution is specified along the boundary.
C06RFF may be used to solve equations where the derivative of the solution is specified along the boundary.
C06RGF may be used to solve equations where the solution is specified on the lower boundary, and the derivative of the solution is specified on the upper boundary.
C06RHF may be used to solve equations where the derivative of the solution is specified on the lower boundary, and the solution is specified on the upper boundary.
For equations with periodic boundary conditions the full-range Fourier transforms computed by C06PAF are appropriate.

3.4 Multidimensional Fourier Transforms

The following routines compute multidimensional discrete Fourier transforms of real, Hermitian and complex data stored in complex arrays:
 | real | Hermitian | complex
2 dimensions | C06PVF | C06PWF | C06PUF
3 dimensions | C06PYF | C06PZF | C06PXF
any number of dimensions |  |  | C06PJF
The Hermitian data, either transformed from or being transformed to real data, is compacted (due to symmetry) along its first dimension when stored in Complex arrays; thus approximately half the full Hermitian data is stored.
C06PUF and C06PXF should be used in preference to C06PJF for two- and three-dimensional transforms, as they are easier to use and are likely to be more efficient.
The transform of multidimensional real data is stored as a complex sequence that is Hermitian in its leading dimension. The inverse transform takes such a complex sequence and computes the real transformed sequence. Consequently, separate routines are provided for performing forward and inverse transforms.
C06PVF performs the forward two-dimensionsal transform while C06PWF performs the inverse of this transform.
C06PYF performs the forward three-dimensional transform while C06PZF performs the inverse of this transform.
The complex sequences computed by C06PVF and C06PYF contain roughly half of the Fourier coefficients; the remainder can be reconstructed by conjugation of those computed. For example, the Fourier coefficients of the two-dimensional transform z^n 1-k 1 k 2 are the complex conjugate of z^k 1k 2 for k 1=0,1,…,n 1/2, and k 2=0,1,…,n 2-1.

3.5 Convolution and Correlation

C06FKF computes either the discrete convolution or the discrete correlation of two real vectors.
C06PKF computes either the discrete convolution or the discrete correlation of two complex vectors.

3.6 Inverse Laplace Transforms

Two methods are provided: Weeks' method (C06LBF) and Crump's method (C06LAF). Both require the function F s to be evaluated for complex values of s. If in doubt which method to use, try Weeks' method (C06LBF) first; when it is suitable, it is usually much faster.
Typically the inversion of a Laplace transform becomes harder as t increases so that all numerical methods tend to have a limit on the range of t for which the inverse f t can be computed. C06LAF is useful for small and moderate values of t.
It is often convenient or necessary to scale a problem so that α is close to 0. For this purpose it is useful to remember that the inverse of F s+k is exp-kt f t . The method used by C06LAF is not so satisfactory when f t is close to zero, in which case a term may be added to F s , e.g., k/s + F s has the inverse k+f t .
Singularities in the inverse function f t generally cause numerical methods to perform less well. The positions of singularities can often be identified by examination of F s . If F s contains a term of the form exp-ks/s then a finite discontinuity may be expected in the inverse at t=k . C06LAF, for example, is capable of estimating a discontinuous inverse but, as the approximation used is continuous, Gibbs' phenomena (overshoots around the discontinuity) result. If possible, such singularities of F s should be removed before computing the inverse.

3.7 Direct Summation of Orthogonal Series

The only routine available is C06DCF, which sums a finite Chebyshev series
∑ j=0 n cj Tj x ,   ∑ j=0 n cj T 2 j x   or   ∑ j=0 n cj T 2 j+1 x
depending on the choice of argument.

3.8 Acceleration of Convergence

The only routine available is C06BAF.

4 Decision Trees

Tree 1: Fourier Transform of Discrete Complex Data

Is the data one-dimensional? |  |  | Multiple vectors? |  |  | Stored as rows? |  |  | C06PRF
 |  | yes |  |  | yes |  |  | yes
 | no |  |  | no |  |  | no |
 |  |  |  |  |  | Stored as columns? |  |  | C06PSF
 |  |  |  |  |  |  |  | yes
 |  |  | C06PCF
Is the data two-dimensional? |  |  | C06PUF
 |  | yes
 | no |
Is the data three-dimensional? |  |  | C06PXF
 |  | yes
 | no |
Transform on one dimension only? |  |  | C06PFF
 |  | yes
 | no |
Transform on all dimensions? |  |  | C06PJF
 |  | yes

Tree 2: Fourier Transform of Real Data or Data in Complex Hermitian Form Resulting from the Transform of Real Data

Quarter-wave sine (inverse) transform |  |  | C06RGF
 |  | yes
 | no |
Quarter-wave cosine (inverse) transform |  |  | C06RHF
 |  | yes
 | no |
Sine (inverse) transform |  |  | C06REF
 |  | yes
 | no |
Cosine (inverse) transform |  |  | C06RFF
 |  | yes
 | no |
Is the data three-dimensional? |  |  | Forward transform on real data |  |  | C06PYF
 |  | yes |  |  | yes
 | no |  |  | no |
 |  |  | Inverse transform on Hermitian data |  |  | C06PZF
 |  |  |  |  | yes
Is the data two-dimensional? |  |  | Forward transform on real data |  |  | C06PVF
 |  | yes |  |  | yes
 | no |  |  | no |
 |  |  | Inverse transform on Hermitian data |  |  | C06PWF
 |  |  |  |  | yes
Is the data multi one-dimensional? |  |  | Sequences stored by row |  |  | C06PPF
 |  | yes |  |  | yes
 | no |  |  | no |
 |  |  | Sequences stored by column |  |  | C06PQF
 |  |  |  |  | yes
C06PAF

5 Functionality Index

Acceleration of convergence C06BAF
Convolution or Correlation,
complex vectors C06PKF
real vectors,
time-saving C06FKF
Discrete Fourier Transform,
multidimensional,
complex sequence,
complex storage C06PJF
real storage C06FJF
multiple half- and quarter-wave transforms,
Fourier cosine transforms,
simple use C06RBF
Fourier cosine transforms, simple use C06RFF
Fourier sine transforms,
simple use C06RAF
Fourier sine transforms, simple use C06REF
quarter-wave cosine transforms,
simple use C06RDF
quarter-wave cosine transforms, simple use C06RHF
quarter-wave sine transforms,
simple use C06RCF
quarter-wave sine transforms, simple use C06RGF
one-dimensional,
multiple transforms,
complex sequence,
complex storage by columns C06PSF
complex storage by rows C06PRF
Hermitian/real sequence,
complex storage by columns C06PQF
complex storage by rows C06PPF
multi-variable,
complex sequence,
complex storage C06PFF
real storage C06FFF
single transforms,
complex sequence,
time-saving,
complex storage C06PCF
real storage C06FCF
Hermitian/real sequence,
time-saving,
complex storage C06PAF
Hermitian sequence,
time-saving,
real storage C06FBF
real sequence,
time-saving,
real storage C06FAF
three-dimensional,
complex sequence,
complex storage C06PXF
real storage C06FXF
Hermitian/real sequence,
complex-to-real C06PZF
real-to-complex C06PYF
two-dimensional,
complex sequence,
complex storage C06PUF
Hermitian/real sequence,
complex-to-real C06PWF
real-to-complex C06PVF
Inverse Laplace Transform,
Crump's method C06LAF
Weeks' method,
compute coefficients of solution C06LBF
evaluate solution C06LCF
Summation of Chebyshev series C06DCF

6 Auxiliary Routines Associated with Library Routine Arguments

None.

7 Routines Withdrawn or Scheduled for Withdrawal

The following lists all those routines that have been withdrawn since Mark 19 of the Library or are scheduled for withdrawal at one of the next two marks.
Withdrawn Routine | Mark of Withdrawal | Replacement Routine(s)
C06DBF | 25 | C06DCF
C06EAF | 26 | C06PAF
C06EBF | 26 | C06PAF
C06ECF | 26 | C06PCF
C06EKF | 26 | C06FKF
C06FPF | 28 | C06PQF
C06FQF | 28 | C06PQF
C06FRF | 26 | C06PSF
C06FUF | 26 | C06PUF
C06GBF | 26 | No replacement required
C06GCF | 26 | No replacement required
C06GQF | 26 | No replacement required
C06GSF | 26 | No replacement required
C06HAF | 26 | C06REF
C06HBF | 26 | C06RFF
C06HCF | 26 | C06RGF
C06HDF | 26 | C06RHF

8 References

Brigham E O (1974) The Fast Fourier Transform Prentice–Hall
Davies S B and Martin B (1979) Numerical inversion of the Laplace transform: A survey and comparison of methods J. Comput. Phys. 33 1–32
Fox L and Parker I B (1968) Chebyshev Polynomials in Numerical Analysis Oxford University Press
Gentleman W S and Sande G (1966) Fast Fourier transforms for fun and profit Proc. Joint Computer Conference, AFIPS 29 563–578
Hamming R W (1962) Numerical Methods for Scientists and Engineers McGraw–Hill
Shanks D (1955) Nonlinear transformations of divergent and slowly convergent sequences J. Math. Phys. 34 1–42
Swarztrauber P N (1977) The methods of cyclic reduction, Fourier analysis and the FACR algorithm for the discrete solution of Poisson's equation on a rectangle SIAM Rev. 19(3) 490–501
Swarztrauber P N (1984) Fast Poisson solvers Studies in Numerical Analysis (ed G H Golub) Mathematical Association of America
Swarztrauber P N (1986) Symmetric FFT's Math. Comput. 47(175) 323–346
Wynn P (1956) On a device for computing the em Sn transformation Math. Tables Aids Comput. 10 91–96
C06 Chapter Contents
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


C06LAF : NAG Library, Mark 26

C06 Chapter Contents
C06 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

C06LAF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
▸▿ 9 Further Comments
9.1 Timing
9.2 Precautions
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

C06LAF estimates values of the inverse Laplace transform of a given function using a Fourier series approximation. Real and imaginary parts of the function, and a bound on the exponential order of the inverse, are required.

2 Specification

SUBROUTINE C06LAF ( FUN, N, T, VALINV, ERREST, RELERR, ALPHAB, TFAC, MXTERM, NTERMS, NA, ALOW, AHIGH, NFEVAL, WORK, IFAIL)
INTEGER | N, MXTERM, NTERMS, NA, NFEVAL, IFAIL
REAL (KIND=nag_wp) | T(N), VALINV(N), ERREST(N), RELERR, ALPHAB, TFAC, ALOW, AHIGH, WORK(4*MXTERM+2)
EXTERNAL | FUN

3 Description

Given a function F p defined for complex values of p, C06LAF estimates values of its inverse Laplace transform by Crump's method (see Crump (1976)). (For a definition of the Laplace transform and its inverse, see the C06 Chapter Introduction.)
Crump's method applies the epsilon algorithm (see Wynn (1956)) to the summation in Durbin's Fourier series approximation (see Durbin (1974))
f tj ≃ e a tj τ 12 F a - ∑ k=1 ∞ Re F a + kπi τ cos⁡ kπ tj τ - Im F a + kπi τ sin⁡ kπ tj τ ,
for j=1,2,…,n , by choosing a such that a prescribed relative error should be achieved. The method is modified slightly if t=0.0 so that an estimate of f 0.0 can be obtained when it has a finite value. τ is calculated as tfac × max 0.01,tj , where tfac > 0.5 . You specify tfac and αb , an upper bound on the exponential order α of the inverse function f t . α has two alternative interpretations:
(i) α is the smallest number such that
f t ≤ m × exp αt
for large t,
(ii) α is the real part of the singularity of F p with largest real part.
The method depends critically on the value of α. See Section 9 for further details. The routine calculates at least two different values of the argument a, such that a>αb , in an attempt to achieve the requested relative error and provide error estimates. The values of tj , for j=1,2,…,n, must be supplied in monotonically increasing order. The routine calculates the values of the inverse function f tj in decreasing order of j.

4 References

Crump K S (1976) Numerical inversion of Laplace transforms using a Fourier series approximation J. Assoc. Comput. Mach. 23 89–96
Durbin F (1974) Numerical inversion of Laplace transforms: An efficient improvement to Dubner and Abate's method Comput. J. 17 371–376
Wynn P (1956) On a device for computing the em Sn transformation Math. Tables Aids Comput. 10 91–96

5 Arguments

1:   FUN – SUBROUTINE, supplied by the user.External Procedure
FUN must evaluate the real and imaginary parts of the function F p for a given value of p.
The specification of FUN is:
SUBROUTINE FUN ( PR, PI, FR, FI)
REAL (KIND=nag_wp) PR, PI, FR, FI
1:   PR – REAL (KIND=nag_wp)Input
2:   PI – REAL (KIND=nag_wp)Input
On entry: the real and imaginary parts of the argument p.
3:   FR – REAL (KIND=nag_wp)Output
4:   FI – REAL (KIND=nag_wp)Output
On exit: the real and imaginary parts of the value F p.
FUN must either be a module subprogram USEd by, or declared as EXTERNAL in, the (sub)program from which C06LAF is called. Arguments denoted as Input must not be changed by this procedure.
2:   N – INTEGERInput
On entry: n, the number of points at which the value of the inverse Laplace transform is required.
Constraint: N≥1.
3:   T N – REAL (KIND=nag_wp) arrayInput
On entry: each T j must specify a point at which the inverse Laplace transform is required , for j=1,2,…,n.
Constraint: 0.0 ≤ T 1 < T 2 <⋯< T n.
4:   VALINV N – REAL (KIND=nag_wp) arrayOutput
On exit: an estimate of the value of the inverse Laplace transform at t=T j, for j=1,2,…,n.
5:   ERREST N – REAL (KIND=nag_wp) arrayOutput
On exit: an estimate of the error in VALINV j. This is usually an estimate of relative error but, if VALINV j<RELERR, ERREST j estimates the absolute error. ERREST j is unreliable when VALINV j is small but slightly greater than RELERR.
6:   RELERR – REAL (KIND=nag_wp)Input
On entry: the required relative error in the values of the inverse Laplace transform. If the absolute value of the inverse is less than RELERR, then absolute accuracy is used instead. RELERR must be in the range 0.0≤RELERR<1.0. If RELERR is set too small or to 0.0, then the routine uses a value sufficiently larger than machine precision.
7:   ALPHAB – REAL (KIND=nag_wp)Input
On entry: αb, an upper bound for α (see Section 3). Usually, αb should be specified equal to, or slightly larger than, the value of α. If αb < α then the prescribed accuracy may not be achieved or completely incorrect results may be obtained. If αb is too large C06LAF will be inefficient and convergence may not be achieved.
Note: it is as important to specify αb correctly as it is to specify the correct function for inversion.
8:   TFAC – REAL (KIND=nag_wp)Input
On entry: tfac, a factor to be used in calculating the parameter τ. Larger values (e.g., 5.0) may be specified for difficult problems, but these may require very large values of MXTERM.
Suggested value: TFAC=0.8.
Constraint: TFAC>0.5.
9:   MXTERM – INTEGERInput
On entry: the maximum number of (complex) terms to be used in the evaluation of the Fourier series.
Suggested value: MXTERM≥100, except for very simple problems.
Constraint: MXTERM≥1.
10:   NTERMS – INTEGEROutput
On exit: the number of (complex) terms actually used.
11:   NA – INTEGEROutput
On exit: the number of values of a used by the routine. See Section 9.
12:   ALOW – REAL (KIND=nag_wp)Output
On exit: the smallest value of a used in the algorithm. This may be used for checking the value of ALPHAB- see Section 9.
13:   AHIGH – REAL (KIND=nag_wp)Output
On exit: the largest value of a used in the algorithm. This may be used for checking the value of ALPHAB- see Section 9.
14:   NFEVAL – INTEGEROutput
On exit: the number of calls to FUN made by the routine.
15:   WORK 4×MXTERM+2 – REAL (KIND=nag_wp) arrayWorkspace
16:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, because for this routine the values of the output arguments may be useful even if IFAIL≠0 on exit, the recommended value is -1. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Note: C06LAF may return useful information for one or more of the following detected errors or warnings.
Errors or warnings detected by the routine:
IFAIL=1
On entry, | N<1,
or | MXTERM<1,
or | RELERR<0.0 ,
or | RELERR≥1.0 ,
or | TFAC≤0.5 .
IFAIL=2
On entry, | T 1<0.0 ,
or | T 1 , T 2 ,…, T N are not in strictly increasing order.
IFAIL=3
T N is too large for this value of ALPHAB. If necessary, scale the problem as described in Section 9.
IFAIL=4
The required accuracy cannot be obtained. It is possible that ALPHAB is less than α. Alternatively, the problem may be especially difficult. Try increasing TFAC, ALPHAB or both.
IFAIL=5
Convergence failure in the epsilon algorithm. Some values of VALINV j may be calculated to the desired accuracy; this may be determined by examining the values of ERREST j . Try reducing the range of T or increasing MXTERM. If IFAIL=5 still results, try reducing TFAC.
IFAIL=6
All values of VALINV j have been calculated but not all are to the requested accuracy; the values of ERREST j should be examined carefully. Try reducing the range of t, or increasing TFAC, ALPHAB or both.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

The error estimates are often very close to the true error but, because the error control depends on an asymptotic formula, the required error may not always be met. There are two principal causes of this: Gibbs' phenomena, and zero or small values of the inverse Laplace transform.
Gibbs' phenomena (see the C06 Chapter Introduction) are exhibited near t=0.0 (due to the method) and around discontinuities in the inverse Laplace transform f t . If there is a discontinuity at t=c then the method converges such that f c → f c- + f c+ / 2 .
Apparent loss of accuracy, when f t is small, may not be serious. Crump's method keeps control of relative error so that good approximations to small function values may appear to be very inaccurate. If f t is estimated to be less than RELERR then this routine switches to absolute error estimation. However, when f t is slightly larger than RELERR the relative error estimates are likely to cause IFAIL=6. If this is found inconvenient it can sometimes be avoided by adding k/p to the function F p , which shifts the inverse to k+f t .
Loss of accuracy may also occur for highly oscillatory functions.
More serious loss of accuracy can occur if α is unknown and is incorrectly estimated. See Section 9.

8 Parallelism and Performance

C06LAF is not threaded in any implementation.

9 Further Comments

9.1 Timing

The value of n is less important in general than the value of NTERMS. Unless FUN is very inexpensive to compute, the timing is proportional to NA×NTERMS . For simple problems NA=2 but in difficult problems NA may be somewhat larger.

9.2 Precautions

You are referred to the C06 Chapter Introduction for advice on simplifying problems with particular difficulties, e.g., where the inverse is known to be a step function.
The method does not work well for large values of t when α is positive. It is advisable, especially if IFAIL=3 is obtained, to scale the problem if α is much greater than 1.0. See the C06 Chapter Introduction.
The range of values of t specified for a particular call should not be greater than about 10 units. This is because the method uses arguments based on the value T n and these tend to be less appropriate as t becomes smaller. However, as the timing of the routine is not especially dependent on n, it is usually far more efficient to evaluate the inverse for ranges of t than to make separate calls to the routine for each value of t.
The most important argument to specify correctly is ALPHAB, an upper bound for α. If, on entry, ALPHAB is sufficiently smaller than α then completely incorrect results will be obtained with IFAIL=0. Unless α is known theoretically it is strongly advised that you should test any estimated value used. This may be done by specifying a single value of t (i.e T n , n=1 ) with two sets of suitable values of TFAC, RELERR and MXTERM, and examining the resulting values of ALOW and AHIGH. The value of T 1 should be chosen very carefully and the following points should be borne in mind:
(i) | T 1 should be small but not too close to 0.0 because of Gibbs' phenomenon (see Section 7),
(ii) | the larger the value of T 1 , the smaller the range of values of a that will be used in the algorithm,
(iii) T 1 should ideally not be chosen such that f T 1=0.0 or a very small value. For suitable problems T 1 might be chosen as, say, 0.1 or 1.0 depending on these factors. The routine calculates ALOW from the formula
ALOW = ALPHAB - ln 0.1×RELERR 2×τ .
Additional values of a are computed by adding 1/τ to the previous value. As τ = TFAC × T n , it will be seen that large values of TFAC and RELERR will test for a close to ALPHAB. Small values of TFAC and RELERR will test for a large. If the result of both tests is IFAIL=0, with comparable values for the inverse, then this gives some credibility to the chosen value of ALPHAB. You should note that this test could be more computationally expensive than the calculation of the inverse itself. The example program (see Section 10) illustrates how such a test may be performed.

10 Example

This example estimates the inverse Laplace transform of the function F p=1/p+1/2 . The true inverse of F p is exp-t/2 . Two preliminary calls to the routine are made to verify that the chosen value of ALPHAB is suitable. For these tests the single value T 1=1.0 is used. To test values of a close to ALPHAB, the values TFAC=5.0 and RELERR=0.01 are chosen. To test larger a, the values TFAC=0.8 and RELERR=1.0E−3 are used. Because the values of the computed inverse are similar and IFAIL=0 in each case, these tests show that there is unlikely to be a singularity of F p in the region -0.04 ≤ Re p ≤ 6.51 .

10.1 Program Text

Program Text (c06lafe.f90)

10.2 Program Data

Program Data (c06lafe.d)

10.3 Program Results

Program Results (c06lafe.r)

GnuplotProduced by GNUPLOT 4.6 patchlevel 3 0 0.1 0.2 0.3 0.4 0.5 0.6 0.7 1 1.5 2 2.5 3 3.5 4 4.5 5 1e−06 1e−05 0.0001 0.001 f(t) Error t Example Program Inverse Laplace Transform of 1/(p+0.5) gnuplot_plot_1 result gnuplot_plot_2 exp(−t/2) gnuplot_plot_3 relative error gnuplot_plot_4 estimated error
C06 Chapter Contents
C06 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


C06LBF : NAG Library, Mark 26

C06 Chapter Contents
C06 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

C06LBF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
▸▿ 9 Further Comments
9.1 The Role of σ_0
9.2 Choice of σ
9.3 Choice of b
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

C06LBF computes the inverse Laplace transform f t of a user-supplied function F s , defined for complex s. The routine uses a modification of Weeks' method which is suitable when f t has continuous derivatives of all orders. The routine returns the coefficients of an expansion which approximates f t and can be evaluated for given values of t by subsequent calls of C06LCF.

2 Specification

SUBROUTINE C06LBF ( F, SIGMA0, SIGMA, B, EPSTOL, MMAX, M, ACOEF, ERRVEC, IFAIL)
INTEGER | MMAX, M, IFAIL
REAL (KIND=nag_wp) | SIGMA0, SIGMA, B, EPSTOL, ACOEF(MMAX), ERRVEC(8)
COMPLEX (KIND=nag_wp) | F
EXTERNAL | F

3 Description

Given a function f t of a real variable t, its Laplace transform F s is a function of a complex variable s, defined by
F s = ∫0∞ e-st f t dt ,   Re s > σ 0 .
Then f t is the inverse Laplace transform of F s . The value σ 0 is referred to as the abscissa of convergence of the Laplace transform; it is the rightmost real part of the singularities of F s .
C06LBF, along with its companion C06LCF, attempts to solve the following problem:
  • given a function F s , compute values of its inverse Laplace transform f t for specified values of t.
The method is a modification of Weeks' method (see Garbow et al. (1988a)), which approximates f t by a truncated Laguerre expansion:
f~ t = e σt ∑ i=0 m-1 ai e -bt / 2 Li bt ,   σ > σ 0 ,   b > 0
where Li x is the Laguerre polynomial of degree i. This routine computes the coefficients ai of the above Laguerre expansion; the expansion can then be evaluated for specified t by calling C06LCF. You must supply the value of σ 0 , and also suitable values for σ and b: see Section 9 for guidance.
The method is only suitable when f t has continuous derivatives of all orders. For such functions the approximation f~ t is usually good and inexpensive. The routine will fail with an error exit if the method is not suitable for the supplied function F s .
The routine is designed to satisfy an accuracy criterion of the form:
f t- f~t e σt < ε tol ,   for all ​t
where εtol is a user-supplied bound. The error measure on the left-hand side is referred to as the pseudo-relative error, or pseudo-error for short. Note that if σ>0 and t is large, the absolute error in f~ t may be very large.
C06LBF is derived from the subroutine MODUL1 in Garbow et al. (1988a).

4 References

Garbow B S, Giunta G, Lyness J N and Murli A (1988a) Software for an implementation of Weeks' method for the inverse laplace transform problem ACM Trans. Math. Software 14 163–170
Garbow B S, Giunta G, Lyness J N and Murli A (1988b) Algorithm 662: A Fortran software package for the numerical inversion of the Laplace transform based on Weeks' method ACM Trans. Math. Software 14 171–176

5 Arguments

1:   F – COMPLEX (KIND=nag_wp) FUNCTION, supplied by the user.External Procedure
F must return the value of the Laplace transform function F s for a given complex value of s.
The specification of F is:
FUNCTION F ( S)
COMPLEX (KIND=nag_wp) F
COMPLEX (KIND=nag_wp) S
1:   S – COMPLEX (KIND=nag_wp)Input
On entry: the value of s for which F s must be evaluated. The real part of S is greater than σ 0.
F must either be a module subprogram USEd by, or declared as EXTERNAL in, the (sub)program from which C06LBF is called. Arguments denoted as Input must not be changed by this procedure.
2:   SIGMA0 – REAL (KIND=nag_wp)Input
On entry: the abscissa of convergence of the Laplace transform, σ 0.
3:   SIGMA – REAL (KIND=nag_wp)Input/Output
On entry: the parameter σ of the Laguerre expansion. If on entry SIGMA≤σ 0, SIGMA is reset to σ 0+0.7.
On exit: the value actually used for σ, as just described.
4:   B – REAL (KIND=nag_wp)Input/Output
On entry: the parameter b of the Laguerre expansion. If on entry B < 2 σ - σ 0 , B is reset to 2.5 σ-σ 0.
On exit: the value actually used for b, as just described.
5:   EPSTOL – REAL (KIND=nag_wp)Input
On entry: the required relative pseudo-accuracy, that is, an upper bound on f t - f~ t e-σt.
6:   MMAX – INTEGERInput
On entry: an upper bound on the number of Laguerre expansion coefficients to be computed. The number of coefficients actually computed is always a power of 2, so MMAX should be a power of 2; if MMAX is not a power of 2 then the maximum number of coefficients calculated will be the largest power of 2 less than MMAX.
Suggested value: MMAX=1024 is sufficient for all but a few exceptional cases.
Constraint: MMAX≥8.
7:   M – INTEGEROutput
On exit: the number of Laguerre expansion coefficients actually computed. The number of calls to F is M/2+2.
8:   ACOEF MMAX – REAL (KIND=nag_wp) arrayOutput
On exit: the first M elements contain the computed Laguerre expansion coefficients, ai.
9:   ERRVEC 8 – REAL (KIND=nag_wp) arrayOutput
On exit: an 8-component vector of diagnostic information.
ERRVEC 1
Overall estimate of the pseudo-error f t - f~ t e-σt =ERRVEC 2 + ERRVEC 3 + ERRVEC 4.
ERRVEC 2
Estimate of the discretization pseudo-error.
ERRVEC 3
Estimate of the truncation pseudo-error.
ERRVEC 4
Estimate of the condition pseudo-error on the basis of minimal noise levels in function values.
ERRVEC 5
K, coefficient of a heuristic decay function for the expansion coefficients.
ERRVEC 6
R, base of the decay function for the expansion coefficients.
ERRVEC 7
Logarithm of the largest expansion coefficient.
ERRVEC 8
Logarithm of the smallest nonzero expansion coefficient.
The values K and R returned in ERRVEC 5 and ERRVEC 6 define a decay function K R-i constructed by the routine for the purposes of error estimation. It satisfies
ai < K R -i ,   ​ i= 1, 2, …, m .
10:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, because for this routine the values of the output arguments may be useful even if IFAIL≠0 on exit, the recommended value is -1. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Note: C06LBF may return useful information for one or more of the following detected errors or warnings.
Errors or warnings detected by the routine:
IFAIL=1
On entry, MMAX<8.
IFAIL=2
The estimated pseudo-error bounds are slightly larger than EPSTOL. Note, however, that the actual errors in the final results may be smaller than EPSTOL as bounds independent of the value of t are pessimistic.
IFAIL=3
Computation was terminated early because the estimate of rounding error was greater than EPSTOL. Increasing EPSTOL may help.
IFAIL=4
The decay rate of the coefficients is too small. Increasing MMAX may help.
IFAIL=5
The decay rate of the coefficients is too small. In addition the rounding error is such that the required accuracy cannot be obtained. Increasing MMAX or EPSTOL may help.
IFAIL=6
The behaviour of the coefficients does not enable reasonable prediction of error bounds. Check the value of SIGMA0. In this case, ERRVEC i is set to -1.0 , for i=1,2,…,5.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.
When IFAIL≥3, changing SIGMA or B may help. If not, the method should be abandoned.

7 Accuracy

The error estimate returned in ERRVEC 1 has been found in practice to be a highly reliable bound on the pseudo-error f t-f~t e-σt .

8 Parallelism and Performance

C06LBF is not threaded in any implementation.

9 Further Comments

9.1 The Role of σ 0

Nearly all techniques for inversion of the Laplace transform require you to supply the value of σ 0 , the convergence abscissa, or else an upper bound on σ 0 . For this routine, one of the reasons for having to supply σ 0 is that the argument σ must be greater than σ 0 ; otherwise the series for f~t will not converge.
If you do not know the value of σ 0 , you must be prepared for significant preliminary effort, either in experimenting with the method and obtaining chaotic results, or in attempting to locate the rightmost singularity of F s .
The value of σ 0 is also relevant in defining a natural accuracy criterion. For large t, f t is of uniform numerical order k e σ 0 t , so a natural measure of relative accuracy of the approximation f~ t is:
εnat t = f~ t - f t / e σ 0 t .
C06LBF uses the supplied value of σ 0 only in determining the values of σ and b (see Sections 9.2 and 9.3); thereafter it bases its computation entirely on σ and b.

9.2 Choice of σ

Even when the value of σ 0 is known, choosing a value for σ is not easy. Briefly, the series for f~t converges slowly when σ-σ 0 is small, and faster when σ-σ 0 is larger. However the natural accuracy measure satisfies
εnat t < εtol e σ - σ 0 t
and this degrades exponentially with t, the exponential constant being σ-σ 0 .
Hence, if you require meaningful results over a large range of values of t, you should choose σ-σ 0 small, in which case the series for f~t converges slowly; while for a smaller range of values of t, you can allow σ-σ 0 to be larger and obtain faster convergence.
The default value for σ used by C06LBF is σ 0+0.7 . There is no theoretical justification for this.

9.3 Choice of b

The simplest advice for choosing b is to set b/2 ≥ σ - σ 0 . The default value used by the routine is 2.5 σ - σ 0 . A more refined choice is to set
b/2 ≥ minj σ-sj
where sj are the singularities of F s .

10 Example

This example computes values of the inverse Laplace transform of the function
F s = 3 s 2-9 .
The exact answer is
f t = sinh⁡3 t .
The program first calls C06LBF to compute the coefficients of the Laguerre expansion, and then calls C06LCF to evaluate the expansion at t=0, 1, 2, 3, 4, 5.

10.1 Program Text

Program Text (c06lbfe.f90)

10.2 Program Data

Program Data (c06lbfe.d)

10.3 Program Results

Program Results (c06lbfe.r)

GnuplotProduced by GNUPLOT 4.6 patchlevel 3 1e−10 1e−08 1e−06 0.0001 0.01 1 100 10000 1e+06 1e+08 0 1 2 3 4 5 1e−10 1e−08 1e−06 0.0001 0.01 1 f(t) Pseudo Error t Example Program Inverse Laplace Transform of 3/(s2-9) f(t) pseudo error gnuplot_plot_1 gnuplot_plot_2
C06 Chapter Contents
C06 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


C06LCF : NAG Library, Mark 26

C06 Chapter Contents
C06 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

C06LCF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
10 Example

1 Purpose

C06LCF evaluates an inverse Laplace transform at a given point, using the expansion coefficients computed by C06LBF.

2 Specification

SUBROUTINE C06LCF ( T, SIGMA, B, M, ACOEF, ERRVEC, FINV, IFAIL)
INTEGER | M, IFAIL
REAL (KIND=nag_wp) | T, SIGMA, B, ACOEF(M), ERRVEC(8), FINV

3 Description

C06LCF is designed to be used following a call to C06LBF, which computes an inverse Laplace transform by representing it as a Laguerre expansion of the form:
f~ t = e σt ∑ i=0 m-1 ai e -bt/2 Li bt ,   σ > σO ,   b > 0
where Li x is the Laguerre polynomial of degree i.
This routine simply evaluates the above expansion for a specified value of t.
C06LCF is derived from the subroutine MODUL2 in Garbow et al. (1988)

4 References

Garbow B S, Giunta G, Lyness J N and Murli A (1988) Algorithm 662: A Fortran software package for the numerical inversion of the Laplace transform based on Weeks' method ACM Trans. Math. Software 14 171–176

5 Arguments

1:   T – REAL (KIND=nag_wp)Input
On entry: the value t for which the inverse Laplace transform f t must be evaluated.
2:   SIGMA – REAL (KIND=nag_wp)Input
3:   B – REAL (KIND=nag_wp)Input
4:   M – INTEGERInput
5:   ACOEF M – REAL (KIND=nag_wp) arrayInput
6:   ERRVEC 8 – REAL (KIND=nag_wp) arrayInput
On entry: SIGMA, B, M, ACOEF and ERRVEC must be unchanged from the previous call of C06LBF.
7:   FINV – REAL (KIND=nag_wp)Output
On exit: the approximation to the inverse Laplace transform at t.
8:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
The approximation to f t is too large to be representable: FINV is set to 0.0.
IFAIL=2
The approximation to f t is too small to be representable: FINV is set to 0.0.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

The error estimate returned by C06LBF in ERRVEC 1 has been found in practice to be a highly reliable bound on the pseudo-error f t - f~ t e-σt .

8 Parallelism and Performance

C06LCF is not threaded in any implementation.

9 Further Comments

C06LCF is primarily designed to evaluate f~t when t>0 . When t≤0 , the result approximates the analytic continuation of f t ; the approximation becomes progressively poorer as t becomes more negative.

10 Example

See example for C06LBF.
C06 Chapter Contents
C06 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


C06PAF : NAG Library, Mark 26

C06 Chapter Contents
C06 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

C06PAF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

C06PAF calculates the discrete Fourier transform of a sequence of n real data values or of a Hermitian sequence of n complex data values stored in compact form in a real array.

2 Specification

SUBROUTINE C06PAF ( DIRECT, X, N, WORK, IFAIL)
INTEGER | N, IFAIL
REAL (KIND=nag_wp) | X(N+2), WORK(*)
CHARACTER(1) | DIRECT

3 Description

Given a sequence of n real data values xj , for j=0,1,…,n-1, C06PAF calculates their discrete Fourier transform (in the forward direction) defined by
z^k = 1 n ∑ j=0 n-1 xj × exp -i 2 πjk n ,   k= 0, 1, …, n-1 .
The transformed values z^k are complex, but they form a Hermitian sequence (i.e., z^ n-k is the complex conjugate of z^k ), so they are completely determined by n real numbers (since z^0 is real, as is z^ n/2 for n even).
Alternatively, given a Hermitian sequence of n complex data values zj , this routine calculates their inverse (backward) discrete Fourier transform defined by
x^k = 1 n ∑ j=0 n-1 zj × exp i 2 πjk n ,   k= 0, 1, …, n-1 .
The transformed values x^k are real.
(Note the scale factor of 1 n in the above definitions.)
A call of C06PAF with DIRECT='F' followed by a call with DIRECT='B' will restore the original data.
C06PAF uses a variant of the fast Fourier transform (FFT) algorithm (see Brigham (1974)) known as the Stockham self-sorting algorithm, which is described in Temperton (1983).
The same functionality is available using the forward and backward transform routine pair: C06PVF and C06PWF on setting N=1. This pair use a different storage solution; real data is stored in a real array, while Hermitian data (the first unconjugated half) is stored in a complex array.

4 References

Brigham E O (1974) The Fast Fourier Transform Prentice–Hall
Temperton C (1983) Self-sorting mixed-radix fast Fourier transforms J. Comput. Phys. 52 1–23

5 Arguments

1:   DIRECT – CHARACTER(1)Input
On entry: if the forward transform as defined in Section 3 is to be computed, then DIRECT must be set equal to 'F'.
If the backward transform is to be computed then DIRECT must be set equal to 'B'.
Constraint: DIRECT='F' or 'B'.
2:   X N+2 – REAL (KIND=nag_wp) arrayInput/Output
On entry: if X is declared with bounds 0:N+1 in the subroutine from which C06PAF is called, then:
  • if DIRECT='F', X j must contain xj, for j=0,1,…,n-1;
  • if DIRECT='B', X 2×k and X 2×k+1 must contain the real and imaginary parts respectively of zk, for k=0,1,…,n/2. (Note that for the sequence zk to be Hermitian, the imaginary part of z 0, and of z n/2 for n even, must be zero.)
On exit:
  • if DIRECT='F' and X is declared with bounds 0:N+1, X 2×k and X 2×k+1 will contain the real and imaginary parts respectively of z^k, for k=0,1,…,n/2;
  • if DIRECT='B' and X is declared with bounds 0:N+1, X j will contain x^j, for j=0,1,…,n-1.
3:   N – INTEGERInput
On entry: n, the number of data values.
Constraint: N≥1.
4:   WORK* – REAL (KIND=nag_wp) arrayWorkspace
Note: the dimension of the array WORK must be at least 3 × N+100.
The workspace requirements as documented for C06PAF may be an overestimate in some implementations.
On exit: WORK 1 contains the minimum workspace required for the current value of N with this implementation.
5:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, N=value.
Constraint: N≥1.
IFAIL=2
value is an invalid value of DIRECT.
IFAIL=3
An internal error has occurred in this routine. Check the routine call and any array sizes. If the call is correct then please contact NAG for assistance.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

Some indication of accuracy can be obtained by performing a subsequent inverse transform and comparing the results with the original sequence (in exact arithmetic they would be identical).

8 Parallelism and Performance

C06PAF is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
C06PAF makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The time taken is approximately proportional to n × log n, but also depends on the factorization of n. C06PAF is faster if the only prime factors of n are 2, 3 or 5; and fastest of all if n is a power of 2.

10 Example

This example reads in a sequence of real data values and prints their discrete Fourier transform (as computed by C06PAF with DIRECT='F'), after expanding it from complex Hermitian form into a full complex sequence. It then performs an inverse transform using C06PAF with DIRECT='B', and prints the sequence so obtained alongside the original data values.

10.1 Program Text

Program Text (c06pafe.f90)

10.2 Program Data

Program Data (c06pafe.d)

10.3 Program Results

Program Results (c06pafe.r)

C06 Chapter Contents
C06 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


C06PCF : NAG Library, Mark 26

C06 Chapter Contents
C06 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

C06PCF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

C06PCF calculates the discrete Fourier transform of a sequence of n complex data values (using complex data type).

2 Specification

SUBROUTINE C06PCF ( DIRECT, X, N, WORK, IFAIL)
INTEGER | N, IFAIL
COMPLEX (KIND=nag_wp) | X(N), WORK(*)
CHARACTER(1) | DIRECT

3 Description

Given a sequence of n complex data values zj , for j=0,1,…,n-1, C06PCF calculates their (forward or backward) discrete Fourier transform (DFT) defined by
z^k = 1 n ∑ j=0 n-1 zj × exp ±i 2 πjk n ,   k= 0, 1, …, n-1 .
(Note the scale factor of 1 n in this definition.) The minus sign is taken in the argument of the exponential within the summation when the forward transform is required, and the plus sign is taken when the backward transform is required.
A call of C06PCF with DIRECT='F' followed by a call with DIRECT='B' will restore the original data.
C06PCF uses a variant of the fast Fourier transform (FFT) algorithm (see Brigham (1974)) known as the Stockham self-sorting algorithm, which is described in Temperton (1983). If n is a large prime number or if n contains large prime factors, then the Fourier transform is performed using Bluestein's algorithm (see Bluestein (1968)), which expresses the DFT as a convolution that in turn can be efficiently computed using FFTs of highly composite sizes.

4 References

Bluestein L I (1968) A linear filtering approach to the computation of the discrete Fourier transform Northeast Electronics Research and Engineering Meeting Record 10 218–219
Brigham E O (1974) The Fast Fourier Transform Prentice–Hall
Temperton C (1983) Self-sorting mixed-radix fast Fourier transforms J. Comput. Phys. 52 1–23

5 Arguments

1:   DIRECT – CHARACTER(1)Input
On entry: if the forward transform as defined in Section 3 is to be computed, then DIRECT must be set equal to 'F'.
If the backward transform is to be computed then DIRECT must be set equal to 'B'.
Constraint: DIRECT='F' or 'B'.
2:   X N – COMPLEX (KIND=nag_wp) arrayInput/Output
On entry: if X is declared with bounds 0:N-1 in the subroutine from which C06PCF is called, then X j must contain zj, for j=0,1,…,n-1.
On exit: the components of the discrete Fourier transform. If X is declared with bounds 0:N-1 in the subroutine from which C06PCF is called, then z^k is contained in X k, for 0≤k≤n-1.
3:   N – INTEGERInput
On entry: n, the number of data values.
Constraint: N≥1.
4:   WORK* – COMPLEX (KIND=nag_wp) arrayWorkspace
Note: the dimension of the array WORK must be at least 2 × N+15.
The workspace requirements as documented for C06PCF may be an overestimate in some implementations.
On exit: the real part of WORK 1 contains the minimum workspace required for the current value of N with this implementation.
5:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, N<1.
IFAIL=2
On entry, DIRECT≠'F' or 'B'.
IFAIL=4
An unexpected error has occurred in an internal call. Check all subroutine calls and array dimensions. Seek expert help.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

Some indication of accuracy can be obtained by performing a subsequent inverse transform and comparing the results with the original sequence (in exact arithmetic they would be identical).

8 Parallelism and Performance

C06PCF is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
C06PCF makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The time taken is approximately proportional to n × log n, but also depends on the factorization of n. C06PCF is faster if the only prime factors of n are 2, 3 or 5; and fastest of all if n is a power of 2. When the Bluestein's FFT algorithm is in use, an additional complex workspace of size approximately 8⁢n is allocated.

10 Example

This example reads in a sequence of complex data values and prints their discrete Fourier transform (as computed by C06PCF with DIRECT='F'). It then performs an inverse transform using C06PCF with DIRECT='B', and prints the sequence so obtained alongside the original data values.

10.1 Program Text

Program Text (c06pcfe.f90)

10.2 Program Data

Program Data (c06pcfe.d)

10.3 Program Results

Program Results (c06pcfe.r)

C06 Chapter Contents
C06 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


C06PFF : NAG Library, Mark 26

C06 Chapter Contents
C06 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

C06PFF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

C06PFF computes the discrete Fourier transform of one variable in a multivariate sequence of complex data values.

2 Specification

SUBROUTINE C06PFF ( DIRECT, NDIM, L, ND, N, X, WORK, LWORK, IFAIL)
INTEGER | NDIM, L, ND(NDIM), N, LWORK, IFAIL
COMPLEX (KIND=nag_wp) | X(N), WORK(LWORK)
CHARACTER(1) | DIRECT

3 Description

C06PFF computes the discrete Fourier transform of one variable (the lth say) in a multivariate sequence of complex data values z j 1 j 2 ⋯ jm , where j 1=0,1,…,n 1-1 ,   j 2=0,1,…,n 2-1 , and so on. Thus the individual dimensions are n 1, n 2, …, nm , and the total number of data values is n = n 1 × n 2 ×⋯× nm .
The routine computes n/nl one-dimensional transforms defined by
z^ j 1 … kl … jm = 1 nl ∑ jl=0 nl-1 z j 1 … jl … jm × exp ± 2 π i jl kl nl ,
where kl = 0 , 1 ,…, nl-1 . The plus or minus sign in the argument of the exponential terms in the above definition determine the direction of the transform: a minus sign defines the forward direction and a plus sign defines the backward direction.
(Note the scale factor of 1 nl in this definition.)
A call of C06PFF with DIRECT='F' followed by a call with DIRECT='B' will restore the original data.
The data values must be supplied in a one-dimensional complex array using column-major storage ordering of multidimensional data (i.e., with the first subscript j 1 varying most rapidly).
This routine calls C06PRF to perform one-dimensional discrete Fourier transforms. Hence, the routine uses a variant of the fast Fourier transform (FFT) algorithm (see Brigham (1974)) known as the Stockham self-sorting algorithm, which is described in Temperton (1983).

4 References

Brigham E O (1974) The Fast Fourier Transform Prentice–Hall
Temperton C (1983) Self-sorting mixed-radix fast Fourier transforms J. Comput. Phys. 52 1–23

5 Arguments

1:   DIRECT – CHARACTER(1)Input
On entry: if the forward transform as defined in Section 3 is to be computed, then DIRECT must be set equal to 'F'.
If the backward transform is to be computed then DIRECT must be set equal to 'B'.
Constraint: DIRECT='F' or 'B'.
2:   NDIM – INTEGERInput
On entry: m, the number of dimensions (or variables) in the multivariate data.
Constraint: NDIM≥1.
3:   L – INTEGERInput
On entry: l, the index of the variable (or dimension) on which the discrete Fourier transform is to be performed.
Constraint: 1≤ L≤ NDIM.
4:   ND NDIM – INTEGER arrayInput
On entry: the elements of ND must contain the dimensions of the NDIM variables; that is, ND i must contain the dimension of the ith variable.
Constraint: ND i≥1, for i=1,2,…,NDIM.
5:   N – INTEGERInput
On entry: n, the total number of data values.
Constraint: N must equal the product of the first NDIM elements of the array ND.
6:   X N – COMPLEX (KIND=nag_wp) arrayInput/Output
On entry: the complex data values. Data values are stored in X using column-major ordering for storing multidimensional arrays; that is, z j 1 j 2 ⋯ jm is stored in X 1 + j 1 + n 1 j 2 + n 1 n 2 j 3 + ⋯ .
On exit: the corresponding elements of the computed transform.
7:   WORK LWORK – COMPLEX (KIND=nag_wp) arrayWorkspace
The workspace requirements as documented for C06PFF may be an overestimate in some implementations.
On exit: the real part of WORK 1 contains the minimum workspace required for the current value of N with this implementation.
8:   LWORK – INTEGERInput
On entry: the dimension of the array WORK as declared in the (sub)program from which C06PFF is called.
Suggested value: LWORK ≥ N + ND L + 15 .
9:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, NDIM<1.
IFAIL=2
On entry, L<1 or L>NDIM.
IFAIL=3
On entry, DIRECT≠'F' or 'B'.
IFAIL=4
On entry, at least one of the first NDIM elements of ND is less than 1.
IFAIL=5
On entry, N does not equal the product of the first NDIM elements of ND.
IFAIL=6
On entry, LWORK is too small. The minimum amount of workspace required is returned in WORK 1.
IFAIL=8
An unexpected error has occurred in an internal call. Check all subroutine calls and array dimensions. Seek expert help.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

Some indication of accuracy can be obtained by performing a subsequent inverse transform and comparing the results with the original sequence (in exact arithmetic they would be identical).

8 Parallelism and Performance

C06PFF is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
C06PFF makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The time taken is approximately proportional to n×log⁡nl , but also depends on the factorization of nl . C06PFF is faster if the only prime factors of nl are 2, 3 or 5; and fastest of all if nl is a power of 2.

10 Example

This example reads in a bivariate sequence of complex data values and prints the discrete Fourier transform of the second variable. It then performs an inverse transform and prints the sequence so obtained, which may be compared with the original data values.

10.1 Program Text

Program Text (c06pffe.f90)

10.2 Program Data

Program Data (c06pffe.d)

10.3 Program Results

Program Results (c06pffe.r)

C06 Chapter Contents
C06 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


C06PJF : NAG Library, Mark 26

C06 Chapter Contents
C06 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

C06PJF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

C06PJF computes the multidimensional discrete Fourier transform of a multivariate sequence of complex data values.

2 Specification

SUBROUTINE C06PJF ( DIRECT, NDIM, ND, N, X, WORK, LWORK, IFAIL)
INTEGER | NDIM, ND(NDIM), N, LWORK, IFAIL
COMPLEX (KIND=nag_wp) | X(N), WORK(LWORK)
CHARACTER(1) | DIRECT

3 Description

C06PJF computes the multidimensional discrete Fourier transform of a multidimensional sequence of complex data values z j 1 j 2 … jm , where j 1 = 0 , 1 ,…, n 1-1 ,   j 2 = 0 , 1 ,…, n 2-1 , and so on. Thus the individual dimensions are n 1 , n 2 ,…, nm , and the total number of data values is n = n 1 × n 2 ×⋯× nm .
The discrete Fourier transform is here defined (e.g., for m=2 ) by:
z^ k 1 , k 2 = 1 n ∑ j 1=0 n 1-1 ∑ j 2=0 n 2-1 z j 1j 2 × exp ±2 πi j 1k 1 n 1 + j 2k 2 n 2 ,
where k 1 = 0 , 1 ,…, n 1-1 and k 2 = 0 , 1 ,…, n 2-1 . The plus or minus sign in the argument of the exponential terms in the above definition determine the direction of the transform: a minus sign defines the forward direction and a plus sign defines the backward direction.
The extension to higher dimensions is obvious. (Note the scale factor of 1 n in this definition.)
A call of C06PJF with DIRECT='F' followed by a call with DIRECT='B' will restore the original data.
The data values must be supplied in a one-dimensional array using column-major storage ordering of multidimensional data (i.e., with the first subscript j 1 varying most rapidly).
This routine calls C06PRF to perform one-dimensional discrete Fourier transforms. Hence, the routine uses a variant of the fast Fourier transform (FFT) algorithm (see Brigham (1974)) known as the Stockham self-sorting algorithm, which is described in Temperton (1983).

4 References

Brigham E O (1974) The Fast Fourier Transform Prentice–Hall
Temperton C (1983) Self-sorting mixed-radix fast Fourier transforms J. Comput. Phys. 52 1–23

5 Arguments

1:   DIRECT – CHARACTER(1)Input
On entry: if the forward transform as defined in Section 3 is to be computed, then DIRECT must be set equal to 'F'.
If the backward transform is to be computed then DIRECT must be set equal to 'B'.
Constraint: DIRECT='F' or 'B'.
2:   NDIM – INTEGERInput
On entry: m, the number of dimensions (or variables) in the multivariate data.
Constraint: NDIM≥1.
3:   ND NDIM – INTEGER arrayInput
On entry: the elements of ND must contain the dimensions of the NDIM variables; that is, ND i must contain the dimension of the ith variable.
Constraint: ND i≥1, for i=1,2,…,NDIM.
4:   N – INTEGERInput
On entry: n, the total number of data values.
Constraint: N must equal the product of the first NDIM elements of the array ND.
5:   X N – COMPLEX (KIND=nag_wp) arrayInput/Output
On entry: the complex data values. Data values are stored in X using column-major ordering for storing multidimensional arrays; that is, z j 1 j 2 ⋯ jm is stored in X 1 + j 1 + n 1 j 2 + n 1 n 2 j 3 + ⋯ .
On exit: the corresponding elements of the computed transform.
6:   WORK LWORK – COMPLEX (KIND=nag_wp) arrayWorkspace
The workspace requirements as documented for C06PJF may be an overestimate in some implementations.
On exit: the real part of WORK 1 contains the minimum workspace required for the current value of N with this implementation.
7:   LWORK – INTEGERInput
On entry: the dimension of the array WORK as declared in the (sub)program from which C06PJF is called.
Suggested value: LWORK ≥ N+3 × max ND i + 15, where i= 1, 2, …, NDIM.
8:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, NDIM<1.
IFAIL=2
On entry, DIRECT≠'F' or 'B'.
IFAIL=3
On entry, at least one of the first NDIM elements of ND is less than 1.
IFAIL=4
On entry, N does not equal the product of the first NDIM elements of ND.
IFAIL=5
On entry, LWORK is too small. The minimum amount of workspace required is returned in WORK 1.
IFAIL=7
An unexpected error has occurred in an internal call. Check all subroutine calls and array dimensions. Seek expert help.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

Some indication of accuracy can be obtained by performing a subsequent inverse transform and comparing the results with the original sequence (in exact arithmetic they would be identical).

8 Parallelism and Performance

C06PJF is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
C06PJF makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The time taken is approximately proportional to n×log n , but also depends on the factorization of the individual dimensions ND i . C06PJF is faster if the only prime factors are 2, 3 or 5; and fastest of all if they are powers of 2.

10 Example

This example reads in a bivariate sequence of complex data values and prints the two-dimensional Fourier transform. It then performs an inverse transform and prints the sequence so obtained, which may be compared to the original data values.

10.1 Program Text

Program Text (c06pjfe.f90)

10.2 Program Data

Program Data (c06pjfe.d)

10.3 Program Results

Program Results (c06pjfe.r)

C06 Chapter Contents
C06 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


C06PKF : NAG Library, Mark 26

C06 Chapter Contents
C06 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

C06PKF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

C06PKF calculates the circular convolution or correlation of two complex vectors of period n.

2 Specification

SUBROUTINE C06PKF ( JOB, X, Y, N, WORK, IFAIL)
INTEGER | JOB, N, IFAIL
COMPLEX (KIND=nag_wp) | X(N), Y(N), WORK(*)

3 Description

C06PKF computes:
  • if JOB=1 , the discrete convolution of x and y, defined by
    zk = ∑ j=0 n-1 xj y k-j = ∑ j=0 n-1 x k-j yj ;
  • if JOB=2 , the discrete correlation of x and y defined by
    wk = ∑ j=0 n-1 x-j y k+j .
Here x and y are complex vectors, assumed to be periodic, with period n, i.e., xj = x j±n = x j±2 n = … ; z and w are then also periodic with period n.
Note: this usage of the terms ‘convolution’ and ‘correlation’ is taken from Brigham (1974). The term ‘convolution’ is sometimes used to denote both these computations.
If x^ , y^ , z^ and w^ are the discrete Fourier transforms of these sequences, and x~ is the inverse discrete Fourier transform of the sequence xj , i.e.,
x^k = 1 n ∑ j=0 n-1 xj × exp -i 2 πjk n , etc.,
and
x~k = 1 n ∑ j= 0 n- 1 xj × exp i 2 πjk n ,
then z^k = n . x^k y^k and w^k = n . x^- k y^k (the bar denoting complex conjugate).

4 References

Brigham E O (1974) The Fast Fourier Transform Prentice–Hall

5 Arguments

1:   JOB – INTEGERInput
On entry: the computation to be performed:
JOB=1
zk = ∑ j=0 n-1 x j y k-j (convolution);
JOB=2
w k = ∑ j=0 n-1 x- j y k+j (correlation).
Constraint: JOB=1 or 2.
2:   X N – COMPLEX (KIND=nag_wp) arrayInput/Output
On entry: the elements of one period of the vector x. If X is declared with bounds 0:N-1 in the subroutine from which C06PKF is called, then X j must contain xj, for j=0,1,…,n-1.
On exit: the corresponding elements of the discrete convolution or correlation.
3:   Y N – COMPLEX (KIND=nag_wp) arrayInput/Output
On entry: the elements of one period of the vector y. If Y is declared with bounds 0:N-1 in the subroutine from which C06PKF is called, then Y j must contain yj, for j=0,1,…,n-1.
On exit: the discrete Fourier transform of the convolution or correlation returned in the array X.
4:   N – INTEGERInput
On entry: n, the number of values in one period of the vectors X and Y. The total number of prime factors of N, counting repetitions, must not exceed 30.
Constraint: N≥1.
5:   WORK* – COMPLEX (KIND=nag_wp) arrayWorkspace
Note: the dimension of the array WORK must be at least 2 × N+15.
The workspace requirements as documented for C06PKF may be an overestimate in some implementations.
On exit: the real part of WORK 1 contains the minimum workspace required for the current value of N with this implementation.
6:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, N<1.
IFAIL=2
On entry, JOB≠1 or 2.
IFAIL=3
An unexpected error has occurred in an internal call. Check all subroutine calls and array dimensions. Seek expert help.
IFAIL=4
On entry, N has more than 30 prime factors.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

The results should be accurate to within a small multiple of the machine precision.

8 Parallelism and Performance

C06PKF is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
C06PKF makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The time taken is approximately proportional to n × log n, but also depends on the factorization of n. C06PKF is faster if the only prime factors of n are 2, 3 or 5; and fastest of all if n is a power of 2.

10 Example

This example reads in the elements of one period of two complex vectors x and y, and prints their discrete convolution and correlation (as computed by C06PKF). In realistic computations the number of data values would be much larger.

10.1 Program Text

Program Text (c06pkfe.f90)

10.2 Program Data

Program Data (c06pkfe.d)

10.3 Program Results

Program Results (c06pkfe.r)

C06 Chapter Contents
C06 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


C06PPF : NAG Library, Mark 26

C06 Chapter Contents
C06 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

C06PPF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

C06PPF computes the discrete Fourier transforms of m sequences, each containing n real data values or a Hermitian complex sequence stored in a complex storage format.

2 Specification

SUBROUTINE C06PPF ( DIRECT, M, N, X, WORK, IFAIL)
INTEGER | M, N, IFAIL
REAL (KIND=nag_wp) | X(M*(N+2)), WORK(*)
CHARACTER(1) | DIRECT

3 Description

Given m sequences of n real data values xjp , for j=0,1,…,n-1 and p=1,2,…,m, C06PPF simultaneously calculates the Fourier transforms of all the sequences defined by
z^ k p = 1 n ∑ j=0 n-1 xjp × exp -i 2 πjk n ,   k= 0, 1, …, n-1 ​ and ​ p= 1, 2, …, m.
The transformed values z^kp are complex, but for each value of p the z^kp form a Hermitian sequence (i.e., z^n-k p is the complex conjugate of z^kp ), so they are completely determined by mn real numbers (since z^0 p is real, as is z^ n/2 p for n even).
Alternatively, given m Hermitian sequences of n complex data values zjp , this routine simultaneously calculates their inverse (backward) discrete Fourier transforms defined by
x^kp = 1 n ∑ j=0 n-1 zjp × exp i 2 πjk n ,   k=0,1,…,n-1 ​ and ​ p=1,2,…,m .
The transformed values x^kp are real.
(Note the scale factor 1 n in the above definition.)
A call of C06PPF with DIRECT='F' followed by a call with DIRECT='B' will restore the original data.
The routine uses a variant of the fast Fourier transform (FFT) algorithm (see Brigham (1974)) known as the Stockham self-sorting algorithm, which is described in Temperton (1983). Special coding is provided for the factors 2, 3, 4 and 5.

4 References

Brigham E O (1974) The Fast Fourier Transform Prentice–Hall
Temperton C (1983) Fast mixed-radix real Fourier transforms J. Comput. Phys. 52 340–350

5 Arguments

1:   DIRECT – CHARACTER(1)Input
On entry: if the forward transform as defined in Section 3 is to be computed, then DIRECT must be set equal to 'F'.
If the backward transform is to be computed then DIRECT must be set equal to 'B'.
Constraint: DIRECT='F' or 'B'.
2:   M – INTEGERInput
On entry: m, the number of sequences to be transformed.
Constraint: M≥1.
3:   N – INTEGERInput
On entry: n, the number of real or complex values in each sequence.
Constraint: N≥1.
4:   X M×N+2 – REAL (KIND=nag_wp) arrayInput/Output
On entry: the data must be stored in X as if in a two-dimensional array of dimension 1:M,0:N-1; each of the m sequences is stored in a row of the array. In other words, if the data values of the pth sequence to be transformed are denoted by xjp, for j=0,1,…,n-1, then:
  • if DIRECT='F', X j×M+p must contain xjp, for j=0,1,…,n-1 and p=1,2,…,m;
  • if DIRECT='B', X 2×k×M+p and X 2×k+1 × M+p must contain the real and imaginary parts respectively of z^kp, for k=0,1,…,n/2 and p=1,2,…,m. (Note that for the sequence z^kp to be Hermitian, the imaginary part of z^0 p, and of z^ n/2 p for n even, must be zero.)
On exit:
  • if DIRECT='F' and X is declared with bounds 1:M,0:N+1 then X p 2×k and X p 2×k+1 will contain the real and imaginary parts respectively of z^kp, for k=0,1,…,n/2 and p=1,2,…,m;
  • if DIRECT='B' and X is declared with bounds 1:M,0:N+1 then X pj will contain xjp, for j=0,1,…,n-1 and p=1,2,…,m.
5:   WORK* – REAL (KIND=nag_wp) arrayWorkspace
Note: the dimension of the array WORK must be at least M×N + 2×N + 2×M + 15.
The workspace requirements as documented for C06PPF may be an overestimate in some implementations.
On exit: WORK 1 contains the minimum workspace required for the current values of M and N with this implementation.
6:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, M<1.
IFAIL=2
On entry, N<1.
IFAIL=3
On entry, DIRECT≠'F' or 'B'.
IFAIL=4
An unexpected error has occurred in an internal call. Check all subroutine calls and array dimensions. Seek expert help.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

Some indication of accuracy can be obtained by performing a subsequent inverse transform and comparing the results with the original sequence (in exact arithmetic they would be identical).

8 Parallelism and Performance

C06PPF is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
C06PPF makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The time taken by C06PPF is approximately proportional to nm log n, but also depends on the factors of n. C06PPF is fastest if the only prime factors of n are 2, 3 and 5, and is particularly slow if n is a large prime, or has large prime factors.

10 Example

This example reads in sequences of real data values and prints their discrete Fourier transforms (as computed by C06PPF with DIRECT='F'), after expanding them from complex Hermitian form into a full complex sequences. Inverse transforms are then calculated by calling C06PPF with DIRECT='B' showing that the original sequences are restored.

10.1 Program Text

Program Text (c06ppfe.f90)

10.2 Program Data

Program Data (c06ppfe.d)

10.3 Program Results

Program Results (c06ppfe.r)

C06 Chapter Contents
C06 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


C06PQF : NAG Library, Mark 26

C06 Chapter Contents
C06 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

C06PQF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

C06PQF computes the discrete Fourier transforms of m sequences, each containing n real data values or a Hermitian complex sequence stored column-wise in a complex storage format.

2 Specification

SUBROUTINE C06PQF ( DIRECT, N, M, X, WORK, IFAIL)
INTEGER | N, M, IFAIL
REAL (KIND=nag_wp) | X((N+2)*M), WORK(*)
CHARACTER(1) | DIRECT

3 Description

Given m sequences of n real data values xjp , for j=0,1,…,n-1 and p= 1,2,…,m, C06PQF simultaneously calculates the Fourier transforms of all the sequences defined by
z^kp = 1 n ∑ j=0 n-1 xjp × exp -i 2 πjk n ,   k 0,1,…,n-1 ​ and ​ p=1,2,…,m .
The transformed values z^ k p are complex, but for each value of p the z^ k p form a Hermitian sequence (i.e., z^ n-k p is the complex conjugate of z^ k p ), so they are completely determined by mn real numbers (since z^0 p is real, as is z^ n/2 p for n even).
Alternatively, given m Hermitian sequences of n complex data values zjp , this routine simultaneously calculates their inverse (backward) discrete Fourier transforms defined by
x^kp = 1 n ∑ j=0 n-1 zjp × exp i 2 πjk n ,   k=0,1,…,n-1 ​ and ​ p=1,2,…,m .
The transformed values x^kp are real.
(Note the scale factor 1 n in the above definition.)
A call of C06PQF with DIRECT='F' followed by a call with DIRECT='B' will restore the original data.
The routine uses a variant of the fast Fourier transform (FFT) algorithm (see Brigham (1974)) known as the Stockham self-sorting algorithm, which is described in Temperton (1983). Special coding is provided for the factors 2, 3, 4 and 5.

4 References

Brigham E O (1974) The Fast Fourier Transform Prentice–Hall
Temperton C (1983) Fast mixed-radix real Fourier transforms J. Comput. Phys. 52 340–350

5 Arguments

1:   DIRECT – CHARACTER(1)Input
On entry: if the forward transform as defined in Section 3 is to be computed, then DIRECT must be set equal to 'F'.
If the backward transform is to be computed then DIRECT must be set equal to 'B'.
Constraint: DIRECT='F' or 'B'.
2:   N – INTEGERInput
On entry: n, the number of real or complex values in each sequence.
Constraint: N≥1.
3:   M – INTEGERInput
On entry: m, the number of sequences to be transformed.
Constraint: M≥1.
4:   X N+2×M – REAL (KIND=nag_wp) arrayInput/Output
On entry: the data must be stored in X as if in a two-dimensional array of dimension 0:N+1,1:M; each of the m sequences is stored in a column of the array. In other words, if the data values of the pth sequence to be transformed are denoted by xjp, for j=0,1,…,n-1, then:
  • if DIRECT='F', X p-1×N+2+j must contain xjp, for j=0,1,…,n-1 and p=1,2,…,m;
  • if DIRECT='B', X p-1 × N+2 + 2×k and X p-1 × N+2 + 2×k+1 must contain the real and imaginary parts respectively of z^kp, for k=0,1,…,n/2 and p=1,2,…,m. (Note that for the sequence z^kp to be Hermitian, the imaginary part of z^0 p, and of z^ n/2 p for n even, must be zero.)
On exit:
  • if DIRECT='F' and X is declared with bounds 0:N+1,1:M then X 2×k p and X 2×k+1 p will contain the real and imaginary parts respectively of z^ k p , for k=0,1,…,n/2 and p=1,2,…,m;
  • if DIRECT='B' and X is declared with bounds 0:N+1,1:M then X jp will contain xjp, for j=0,1,…,n-1 and p=1,2,…,m.
5:   WORK* – REAL (KIND=nag_wp) arrayWorkspace
Note: the dimension of the array WORK must be at least M+2 × N + 15.
The workspace requirements as documented for C06PQF may be an overestimate in some implementations.
On exit: WORK 1 contains the minimum workspace required for the current values of M and N with this implementation.
6:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, M<1.
IFAIL=2
On entry, N<1.
IFAIL=3
On entry, DIRECT≠'F' or 'B'.
IFAIL=4
An unexpected error has occurred in an internal call. Check all subroutine calls and array dimensions. Seek expert help.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

Some indication of accuracy can be obtained by performing a subsequent inverse transform and comparing the results with the original sequence (in exact arithmetic they would be identical).

8 Parallelism and Performance

C06PQF is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
C06PQF makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The time taken by C06PQF is approximately proportional to nm log n, but also depends on the factors of n. C06PQF is fastest if the only prime factors of n are 2, 3 and 5, and is particularly slow if n is a large prime, or has large prime factors.

10 Example

This example reads in sequences of real data values and prints their discrete Fourier transforms (as computed by C06PQF with DIRECT='F'), after expanding them from complex Hermitian form into a full complex sequences.
Inverse transforms are then calculated by calling C06PQF with DIRECT='B' showing that the original sequences are restored.

10.1 Program Text

Program Text (c06pqfe.f90)

10.2 Program Data

Program Data (c06pqfe.d)

10.3 Program Results

Program Results (c06pqfe.r)

C06 Chapter Contents
C06 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


C06PRF : NAG Library, Mark 26

C06 Chapter Contents
C06 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

C06PRF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

C06PRF computes the discrete Fourier transforms of m sequences, each containing n complex data values.

2 Specification

SUBROUTINE C06PRF ( DIRECT, M, N, X, WORK, IFAIL)
INTEGER | M, N, IFAIL
COMPLEX (KIND=nag_wp) | X(M*N), WORK(*)
CHARACTER(1) | DIRECT

3 Description

Given m sequences of n complex data values zjp , for j=0,1,…,n-1 and p=1,2,…,m, C06PRF simultaneously calculates the (forward or backward) discrete Fourier transforms of all the sequences defined by
z^kp = 1 n ∑ j=0 n-1 zjp × exp ±i 2 πjk n ,   k= 0, 1, …, n-1 ​ and ​ p= 1, 2, …, m .
(Note the scale factor 1 n in this definition.) The minus sign is taken in the argument of the exponential within the summation when the forward transform is required, and the plus sign is taken when the backward transform is required.
A call of C06PRF with DIRECT='F' followed by a call with DIRECT='B' will restore the original data.
The routine uses a variant of the fast Fourier transform (FFT) algorithm (see Brigham (1974)) known as the Stockham self-sorting algorithm, which is described in Temperton (1983). Special code is provided for the factors 2, 3, 4 and 5.

4 References

Brigham E O (1974) The Fast Fourier Transform Prentice–Hall
Temperton C (1983) Self-sorting mixed-radix fast Fourier transforms J. Comput. Phys. 52 1–23

5 Arguments

1:   DIRECT – CHARACTER(1)Input
On entry: if the forward transform as defined in Section 3 is to be computed, then DIRECT must be set equal to 'F'.
If the backward transform is to be computed then DIRECT must be set equal to 'B'.
Constraint: DIRECT='F' or 'B'.
2:   M – INTEGERInput
On entry: m, the number of sequences to be transformed.
Constraint: M≥1.
3:   N – INTEGERInput
On entry: n, the number of complex values in each sequence.
Constraint: N≥1.
4:   X M×N – COMPLEX (KIND=nag_wp) arrayInput/Output
On entry: the complex data must be stored in X as if in a two-dimensional array of dimension 1:M,0:N-1; each of the m sequences is stored in a row of each array. In other words, if the elements of the pth sequence to be transformed are denoted by zjp, for j=0,1,…,n-1, then X j×M+p must contain zjp.
On exit: is overwritten by the complex transforms.
5:   WORK* – COMPLEX (KIND=nag_wp) arrayWorkspace
Note: the dimension of the array WORK must be at least M×N + 2×N + 15.
The workspace requirements as documented for C06PRF may be an overestimate in some implementations.
On exit: the real part of WORK 1 contains the minimum workspace required for the current values of M and N with this implementation.
6:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, M<1.
IFAIL=2
On entry, N<1.
IFAIL=3
On entry, DIRECT≠'F' or 'B'.
IFAIL=5
An unexpected error has occurred in an internal call. Check all subroutine calls and array dimensions. Seek expert help.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

Some indication of accuracy can be obtained by performing a subsequent inverse transform and comparing the results with the original sequence (in exact arithmetic they would be identical).

8 Parallelism and Performance

C06PRF is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
C06PRF makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The time taken by C06PRF is approximately proportional to nm log n, but also depends on the factors of n. C06PRF is fastest if the only prime factors of n are 2, 3 and 5, and is particularly slow if n is a large prime, or has large prime factors.

10 Example

This example reads in sequences of complex data values and prints their discrete Fourier transforms (as computed by C06PRF with DIRECT='F'). Inverse transforms are then calculated using C06PRF with DIRECT='B' and printed out, showing that the original sequences are restored.

10.1 Program Text

Program Text (c06prfe.f90)

10.2 Program Data

Program Data (c06prfe.d)

10.3 Program Results

Program Results (c06prfe.r)

C06 Chapter Contents
C06 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


C06PSF : NAG Library, Mark 26

C06 Chapter Contents
C06 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

C06PSF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

C06PSF computes the discrete Fourier transforms of m sequences, stored as columns of an array, each containing n complex data values.

2 Specification

SUBROUTINE C06PSF ( DIRECT, N, M, X, WORK, IFAIL)
INTEGER | N, M, IFAIL
COMPLEX (KIND=nag_wp) | X(N*M), WORK(*)
CHARACTER(1) | DIRECT

3 Description

Given m sequences of n complex data values zjp , for j=0,1,…,n-1 and p=1,2,…,m, C06PSF simultaneously calculates the (forward or backward) discrete Fourier transforms of all the sequences defined by
z^kp=1 n ∑j=0 n-1 zjp×exp±i 2 πjk n ,  k=0,1,…,n-1​ and ​p=1,2,…,m.
(Note the scale factor 1 n in this definition.) The minus sign is taken in the argument of the exponential within the summation when the forward transform is required, and the plus sign is taken when the backward transform is required.
A call of C06PSF with DIRECT='F' followed by a call with DIRECT='B' will restore the original data.
The routine uses a variant of the fast Fourier transform (FFT) algorithm (see Brigham (1974)) known as the Stockham self-sorting algorithm, which is described in Temperton (1983). Special code is provided for the factors 2, 3 and 5.

4 References

Brigham E O (1974) The Fast Fourier Transform Prentice–Hall
Temperton C (1983) Self-sorting mixed-radix fast Fourier transforms J. Comput. Phys. 52 1–23

5 Arguments

1:   DIRECT – CHARACTER(1)Input
On entry: if the forward transform as defined in Section 3 is to be computed, then DIRECT must be set equal to 'F'.
If the backward transform is to be computed then DIRECT must be set equal to 'B'.
Constraint: DIRECT='F' or 'B'.
2:   N – INTEGERInput
On entry: n, the number of complex values in each sequence.
Constraint: N≥1.
3:   M – INTEGERInput
On entry: m, the number of sequences to be transformed.
Constraint: M≥1.
4:   X N×M – COMPLEX (KIND=nag_wp) arrayInput/Output
On entry: the complex data values zjp stored in X p-1×N+j+1, for j=0,1,…,N-1 and p=1,2,…,M.
On exit: is overwritten by the complex transforms.
5:   WORK* – COMPLEX (KIND=nag_wp) arrayWorkspace
Note: the dimension of the array WORK must be at least N×M + N + 15.
The workspace requirements as documented for C06PSF may be an overestimate in some implementations.
On exit: the real part of WORK 1 contains the minimum workspace required for the current values of M and N with this implementation.
6:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, M<1.
IFAIL=2
On entry, N<1.
IFAIL=3
On entry, DIRECT≠'F' or 'B'.
IFAIL=5
An unexpected error has occurred in an internal call. Check all subroutine calls and array dimensions. Seek expert help.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

Some indication of accuracy can be obtained by performing a subsequent inverse transform and comparing the results with the original sequence (in exact arithmetic they would be identical).

8 Parallelism and Performance

C06PSF is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
C06PSF makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The time taken by C06PSF is approximately proportional to nm log n, but also depends on the factors of n. C06PSF is fastest if the only prime factors of n are 2, 3 and 5, and is particularly slow if n is a large prime, or has large prime factors.

10 Example

This example reads in sequences of complex data values and prints their discrete Fourier transforms (as computed by C06PSF with DIRECT='F'). Inverse transforms are then calculated using C06PSF with DIRECT='B' and printed out, showing that the original sequences are restored.

10.1 Program Text

Program Text (c06psfe.f90)

10.2 Program Data

Program Data (c06psfe.d)

10.3 Program Results

Program Results (c06psfe.r)

C06 Chapter Contents
C06 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


C06PUF : NAG Library, Mark 26

C06 Chapter Contents
C06 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

C06PUF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

C06PUF computes the two-dimensional discrete Fourier transform of a bivariate sequence of complex data values (using complex data type).

2 Specification

SUBROUTINE C06PUF ( DIRECT, M, N, X, WORK, IFAIL)
INTEGER | M, N, IFAIL
COMPLEX (KIND=nag_wp) | X(M*N), WORK(*)
CHARACTER(1) | DIRECT

3 Description

C06PUF computes the two-dimensional discrete Fourier transform of a bivariate sequence of complex data values z j 1 j 2 , for j 1=0,1,…,m-1 and j 2=0,1,…,n-1.
The discrete Fourier transform is here defined by
z^ k 1 k 2 = 1 mn ∑ j 1=0 m-1 ∑ j 2=0 n-1 z j 1 j 2 × exp ±2 πi j 1 k 1 m + j 2 k 2 n ,
where k 1=0,1,…,m-1 and k 2=0,1,…,n-1 .
(Note the scale factor of 1 mn in this definition.) The minus sign is taken in the argument of the exponential within the summation when the forward transform is required, and the plus sign is taken when the backward transform is required.
A call of C06PUF with DIRECT='F' followed by a call with DIRECT='B' will restore the original data.
This routine calls C06PRF to perform multiple one-dimensional discrete Fourier transforms by the fast Fourier transform (FFT) algorithm in Brigham (1974).

4 References

Brigham E O (1974) The Fast Fourier Transform Prentice–Hall
Temperton C (1983) Self-sorting mixed-radix fast Fourier transforms J. Comput. Phys. 52 1–23

5 Arguments

1:   DIRECT – CHARACTER(1)Input
On entry: if the forward transform as defined in Section 3 is to be computed, then DIRECT must be set equal to 'F'.
If the backward transform is to be computed then DIRECT must be set equal to 'B'.
Constraint: DIRECT='F' or 'B'.
2:   M – INTEGERInput
On entry: m, the first dimension of the transform.
Constraint: M≥1.
3:   N – INTEGERInput
On entry: n, the second dimension of the transform.
Constraint: N≥1.
4:   X M×N – COMPLEX (KIND=nag_wp) arrayInput/Output
On entry: the complex data values. X M×j 2+j 1 must contain z j 1 j 2 , for j 1=1,2,…,M and j 2=1,2,…,N.
On exit: the corresponding elements of the computed transform.
5:   WORK* – COMPLEX (KIND=nag_wp) arrayWorkspace
Note: the dimension of the array WORK must be at least M × N + N + M + 30.
The workspace requirements as documented for C06PUF may be an overestimate in some implementations.
On exit: the real part of WORK 1 contains the minimum workspace required for the current values of M and N with this implementation.
6:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, M<1.
IFAIL=2
On entry, N<1.
IFAIL=3
On entry, DIRECT≠'F' or 'B'.
IFAIL=6
An unexpected error has occurred in an internal call. Check all subroutine calls and array dimensions. Seek expert help.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

Some indication of accuracy can be obtained by performing a subsequent inverse transform and comparing the results with the original sequence (in exact arithmetic they would be identical).

8 Parallelism and Performance

C06PUF is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
C06PUF makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The time taken is approximately proportional to mn × log mn , but also depends on the factorization of the individual dimensions m and n. C06PUF is faster if the only prime factors are 2, 3 or 5; and fastest of all if they are powers of 2.

10 Example

This example reads in a bivariate sequence of complex data values and prints the two-dimensional Fourier transform. It then performs an inverse transform and prints the sequence so obtained, which may be compared to the original data values.

10.1 Program Text

Program Text (c06pufe.f90)

10.2 Program Data

Program Data (c06pufe.d)

10.3 Program Results

Program Results (c06pufe.r)

C06 Chapter Contents
C06 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


C06PVF : NAG Library, Mark 26

C06 Chapter Contents
C06 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

C06PVF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

C06PVF computes the two-dimensional discrete Fourier transform of a bivariate sequence of real data values.

2 Specification

SUBROUTINE C06PVF ( M, N, X, Y, IFAIL)
INTEGER | M, N, IFAIL
REAL (KIND=nag_wp) | X(M*N)
COMPLEX (KIND=nag_wp) | Y((M/2+1)*N)

3 Description

C06PVF computes the two-dimensional discrete Fourier transform of a bivariate sequence of real data values x j 1j 2, for j 1=0,1,…,m-1 and j 2=0,1,…,n-1.
The discrete Fourier transform is here defined by
z^ k 1 k 2 = 1 mn ∑ j 1=0 m-1 ∑ j 2=0 n-1 x j 1 j 2 × exp -2 πi j 1 k 1 m + j 2 k 2 n ,
where k 1=0,1,…,m-1 and k 2=0,1,…,n-1. (Note the scale factor of 1 mn in this definition.)
The transformed values z^ k 1 k 2 are complex. Because of conjugate symmetry (i.e., z^ k 1 k 2 is the complex conjugate of z^ m-k 1 k 2 ), only slightly more than half of the Fourier coefficients need to be stored in the output.
A call of C06PVF followed by a call of C06PWF will restore the original data.
This routine calls C06PQF and C06PRF to perform multiple one-dimensional discrete Fourier transforms by the fast Fourier transform (FFT) algorithm in Brigham (1974) and Temperton (1983).

4 References

Brigham E O (1974) The Fast Fourier Transform Prentice–Hall
Temperton C (1983) Fast mixed-radix real Fourier transforms J. Comput. Phys. 52 340–350

5 Arguments

1:   M – INTEGERInput
On entry: m, the first dimension of the transform.
Constraint: M≥1.
2:   N – INTEGERInput
On entry: n, the second dimension of the transform.
Constraint: N≥1.
3:   X M×N – REAL (KIND=nag_wp) arrayInput
On entry: the real input dataset x, where x j 1 j 2 is stored in X j 2 × m+ j 1, for j 1=0,1,…,m-1 and j 2=0,1,…,n-1. That is, if X is regarded as a two-dimensional array of dimension 0:M-1,0:N-1 , then X j 1j 2 must contain x j 1 j 2 .
4:   Y M/2+1×N – COMPLEX (KIND=nag_wp) arrayOutput
On exit: the complex output dataset z^, where z^ k 1 k 2 is stored in Y k 2 × m/2+1 + k 1 , for k 1=0,1,…,m/2 and k 2=0,1,…,n-1. That is, if Y is regarded as a two-dimensional array of dimension 0:M/2,0:N-1 , then Y k 1k 2 contains z^ k 1 k 2 . Note the first dimension is cut roughly by half to remove the redundant information due to conjugate symmetry.
5:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, M=value.
Constraint: M≥1.
IFAIL=2
On entry, N=value.
Constraint: N≥1.
IFAIL=3
An internal error has occurred in this routine. Check the routine call and any array sizes. If the call is correct then please contact NAG for assistance.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

Some indication of accuracy can be obtained by performing a forward transform using C06PVF and a backward transform using C06PWF, and comparing the results with the original sequence (in exact arithmetic they would be identical).

8 Parallelism and Performance

C06PVF is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
C06PVF makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The time taken by C06PVF is approximately proportional to mn log mn , but also depends on the factors of m and n. C06PVF is fastest if the only prime factors of m and n are 2, 3 and 5, and is particularly slow if m or n is a large prime, or has large prime factors.
Workspace is internally allocated by C06PVF. The total size of these arrays is approximately proportional to mn.

10 Example

This example reads in a bivariate sequence of real data values and prints their discrete Fourier transforms as computed by C06PVF. Inverse transforms are then calculated by calling C06PWF showing that the original sequences are restored.

10.1 Program Text

Program Text (c06pvfe.f90)

10.2 Program Data

Program Data (c06pvfe.d)

10.3 Program Results

Program Results (c06pvfe.r)

C06 Chapter Contents
C06 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


C06PWF : NAG Library, Mark 26

C06 Chapter Contents
C06 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

C06PWF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
10 Example

1 Purpose

C06PWF computes the two-dimensional inverse discrete Fourier transform of a bivariate Hermitian sequence of complex data values.

2 Specification

SUBROUTINE C06PWF ( M, N, Y, X, IFAIL)
INTEGER | M, N, IFAIL
REAL (KIND=nag_wp) | X(M*N)
COMPLEX (KIND=nag_wp) | Y((M/2+1)*N)

3 Description

C06PWF computes the two-dimensional inverse discrete Fourier transform of a bivariate Hermitian sequence of complex data values z j 1j 2, for j 1=0,1,…,m-1 and j 2=0,1,…,n-1.
The discrete Fourier transform is here defined by
x^ k 1 k 2 = 1 mn ∑ j 1=0 m-1 ∑ j 2=0 n-1 z j 1 j 2 × exp 2 πi j 1 k 1 m + j 2 k 2 n ,
where k 1=0,1,…,m-1 and k 2=0,1,…,n-1. (Note the scale factor of 1 mn in this definition.)
Because the input data satisfies conjugate symmetry (i.e., z k 1 k 2 is the complex conjugate of z m-k 1 k 2 , the transformed values x^ k 1 k 2 are real.
A call of C06PVF followed by a call of C06PWF will restore the original data.
This routine calls C06PQF and C06PRF to perform multiple one-dimensional discrete Fourier transforms by the fast Fourier transform (FFT) algorithm in Brigham (1974) and Temperton (1983).

4 References

Brigham E O (1974) The Fast Fourier Transform Prentice–Hall
Temperton C (1983) Fast mixed-radix real Fourier transforms J. Comput. Phys. 52 340–350

5 Arguments

1:   M – INTEGERInput
On entry: m, the first dimension of the transform.
Constraint: M≥1.
2:   N – INTEGERInput
On entry: n, the second dimension of the transform.
Constraint: N≥1.
3:   Y M/2+1×N – COMPLEX (KIND=nag_wp) arrayInput
On entry: the Hermitian sequence of complex input dataset z, where z j 1 j 2 is stored in Y j 2 × m/2+1 + j 1 , for j 1=0,1,…,m/2 and j 2=0,1,…,n-1. That is, if Y is regarded as a two-dimensional array of dimension 0:M/2,0:N-1 , then Y j 1j 2 must contain z j 1 j 2 .
4:   X M×N – REAL (KIND=nag_wp) arrayOutput
On exit: the real output dataset x^, where x^ k 1 k 2 is stored in X k 2 × m+ k 1, for k 1=0,1,…,m-1 and k 2=0,1,…,n-1. That is, if X is regarded as a two-dimensional array of dimension 0:M-1,0:N-1 , then X k 1k 2 contains x^ k 1 k 2 .
5:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, M=value.
Constraint: M≥1.
IFAIL=2
On entry, N=value.
Constraint: N≥1.
IFAIL=3
An internal error has occurred in this routine. Check the routine call and any array sizes. If the call is correct then please contact NAG for assistance.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

Some indication of accuracy can be obtained by performing a forward transform using C06PVF and a backward transform using C06PWF, and comparing the results with the original sequence (in exact arithmetic they would be identical).

8 Parallelism and Performance

C06PWF is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
C06PWF makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The time taken by C06PWF is approximately proportional to mn log mn , but also depends on the factors of m and n. C06PWF is fastest if the only prime factors of m and n are 2, 3 and 5, and is particularly slow if m or n is a large prime, or has large prime factors.
Workspace is internally allocated by C06PWF. The total size of these arrays is approximately proportional to mn.

10 Example

See Section 10 in C06PVF.
C06 Chapter Contents
C06 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


C06PXF : NAG Library, Mark 26

C06 Chapter Contents
C06 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

C06PXF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

C06PXF computes the three-dimensional discrete Fourier transform of a trivariate sequence of complex data values (using complex data type).

2 Specification

SUBROUTINE C06PXF ( DIRECT, N1, N2, N3, X, WORK, IFAIL)
INTEGER | N1, N2, N3, IFAIL
COMPLEX (KIND=nag_wp) | X(N1*N2*N3), WORK(*)
CHARACTER(1) | DIRECT

3 Description

C06PXF computes the three-dimensional discrete Fourier transform of a trivariate sequence of complex data values z j 1 j 2 j 3 , for j 1=0,1,…,n 1-1, j 2=0,1,…,n 2-1 and j 3=0,1,…,n 3-1.
The discrete Fourier transform is here defined by
z^ k 1 k 2 k 3 = 1 n 1 n 2 n 3 ∑ j 1=0 n 1-1 ∑ j 2=0 n 2-1 ∑ j 3=0 n 3-1 z j 1 j 2 j 3 × exp ±2 πi j 1 k 1 n 1 + j 2 k 2 n 2 + j 3 k 3 n 3 ,
where k 1=0,1,…,n 1-1 , k 2=0,1,…,n 2-1 and k 3=0,1,…,n 3-1 .
(Note the scale factor of 1 n 1 n 2 n 3 in this definition.) The minus sign is taken in the argument of the exponential within the summation when the forward transform is required, and the plus sign is taken when the backward transform is required.
A call of C06PXF with DIRECT='F' followed by a call with DIRECT='B' will restore the original data.
This routine performs multiple one-dimensional discrete Fourier transforms by the fast Fourier transform (FFT) algorithm (see Brigham (1974)).

4 References

Brigham E O (1974) The Fast Fourier Transform Prentice–Hall
Temperton C (1983) Self-sorting mixed-radix fast Fourier transforms J. Comput. Phys. 52 1–23

5 Arguments

1:   DIRECT – CHARACTER(1)Input
On entry: if the forward transform as defined in Section 3 is to be computed, then DIRECT must be set equal to 'F'.
If the backward transform is to be computed then DIRECT must be set equal to 'B'.
Constraint: DIRECT='F' or 'B'.
2:   N1 – INTEGERInput
On entry: n 1, the first dimension of the transform.
Constraint: N1≥1.
3:   N2 – INTEGERInput
On entry: n 2, the second dimension of the transform.
Constraint: N2≥1.
4:   N3 – INTEGERInput
On entry: n 3, the third dimension of the transform.
Constraint: N3≥1.
5:   X N1×N2×N3 – COMPLEX (KIND=nag_wp) arrayInput/Output
On entry: the complex data values. Data values are stored in X using column-major ordering for storing multidimensional arrays; that is, z j 1 j 2 j 3 is stored in X 1 + j 1 + n 1 j 2 + n 1 n 2 j 3 .
On exit: the corresponding elements of the computed transform.
6:   WORK* – COMPLEX (KIND=nag_wp) arrayWorkspace
Note: the dimension of the array WORK must be at least N1 × N2 × N3 + N1 + N2 + N3 + 45.
The workspace requirements as documented for C06PXF may be an overestimate in some implementations.
On exit: the real part of WORK 1 contains the minimum workspace required for the current values of N1, N2 and N3 with this implementation.
7:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, N1<1.
IFAIL=2
On entry, N2<1.
IFAIL=3
On entry, N3<1.
IFAIL=4
On entry, DIRECT≠'F' or 'B'.
IFAIL=8
An unexpected error has occurred in an internal call. Check all subroutine calls and array dimensions. Seek expert help.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

Some indication of accuracy can be obtained by performing a subsequent inverse transform and comparing the results with the original sequence (in exact arithmetic they would be identical).

8 Parallelism and Performance

C06PXF is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
C06PXF makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The time taken is approximately proportional to n 1 n 2 n 3 × log n 1 n 2 n 3 , but also depends on the factorization of the individual dimensions n 1 , n 2 and n 3 . C06PXF is faster if the only prime factors are 2, 3 or 5; and fastest of all if they are powers of 2.

10 Example

This example reads in a trivariate sequence of complex data values and prints the three-dimensional Fourier transform. It then performs an inverse transform and prints the sequence so obtained, which may be compared to the original data values.

10.1 Program Text

Program Text (c06pxfe.f90)

10.2 Program Data

Program Data (c06pxfe.d)

10.3 Program Results

Program Results (c06pxfe.r)

C06 Chapter Contents
C06 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


C06PYF : NAG Library, Mark 26

C06 Chapter Contents
C06 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

C06PYF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

C06PYF computes the three-dimensional discrete Fourier transform of a trivariate sequence of real data values.

2 Specification

SUBROUTINE C06PYF ( N1, N2, N3, X, Y, IFAIL)
INTEGER | N1, N2, N3, IFAIL
REAL (KIND=nag_wp) | X(N1*N2*N3)
COMPLEX (KIND=nag_wp) | Y((N1/2+1)*N2*N3)

3 Description

C06PYF computes the three-dimensional discrete Fourier transform of a trivariate sequence of real data values x j 1 j 2 j 3 , for j 1=0,1,…,n 1-1, j 2=0,1,…,n 2-1 and j 3=0,1,…,n 3-1.
The discrete Fourier transform is here defined by
z^ k 1 k 2 k 3 = 1 n 1 n 2 n 3 ∑ j 1=0 n 1-1 ∑ j 2=0 n 2-1 ∑ j 3=0 n 3-1 x j 1 j 2 j 3 × exp -2 π i j 1 k 1 n 1 + j 2 k 2 n 2 + j 3 k 3 n 3 ,
where k 1 = 0,1,…, n 1-1 , k 2 = 0,1,…, n 2-1 and k 3 = 0,1,…, n 3-1 . (Note the scale factor of 1 n 1 n 2 n 3 in this definition.)
The transformed values z^ k 1 k 2 k 3 are complex. Because of conjugate symmetry (i.e., z^ k 1 k 2 k 3 is the complex conjugate of z^ n 1 - k 1 k 2 k 3 ), only slightly more than half of the Fourier coefficients need to be stored in the output.
A call of C06PYF followed by a call of C06PZF will restore the original data.
This routine calls C06PQF and C06PRF to perform multiple one-dimensional discrete Fourier transforms by the fast Fourier transform (FFT) algorithm in Brigham (1974) and Temperton (1983).

4 References

Brigham E O (1974) The Fast Fourier Transform Prentice–Hall
Temperton C (1983) Fast mixed-radix real Fourier transforms J. Comput. Phys. 52 340–350

5 Arguments

1:   N1 – INTEGERInput
On entry: n 1, the first dimension of the transform.
Constraint: N1≥1.
2:   N2 – INTEGERInput
On entry: n 2, the second dimension of the transform.
Constraint: N2≥1.
3:   N3 – INTEGERInput
On entry: n 3, the third dimension of the transform.
Constraint: N3≥1.
4:   X N1×N2×N3 – REAL (KIND=nag_wp) arrayInput
On entry: the real input dataset x, where x j 1 j 2 j 3 is stored in X j 3 × n 1 n 2 + j 2 × n 1 + j 1 +1 , for j 1=0,1,…,n 1-1, j 2=0,1,…,n 2-1 and j 3=0,1,…,n 3-1. That is, if X is regarded as a three-dimensional array of dimension 0:N1-1,0:N2-1,0:N3-1 , then X j 1j 2j 3 must contain x j 1j 2j 3.
5:   Y N1/2+1×N2×N3 – COMPLEX (KIND=nag_wp) arrayOutput
On exit: the complex output dataset z^, where z^ k 1 k 2 k 3 is stored in Y k 3 × n 1 /2+1 n 2 + k 2 × n 1 /2+1 + k 1 +1 , for k 1=0,1,…,n 1/2, k 2=0,1,…,n 2-1 and k 3=0,1,…,n 3-1. That is, if Y is regarded as a three-dimensional array of dimension 0:N1/2,0:N2-1,0:N3-1 , then Y k 1k 2k 3 contains z^k 1k 2k 3. Note the first dimension is cut roughly by half to remove the redundant information due to conjugate symmetry.
6:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, N1=value.
Constraint: N1≥1.
IFAIL=2
On entry, N2=value.
Constraint: N2≥1.
IFAIL=3
On entry, N3=value.
Constraint: N3≥1.
IFAIL=4
An internal error has occurred in this routine. Check the routine call and any array sizes. If the call is correct then please contact NAG for assistance.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

Some indication of accuracy can be obtained by performing a forward transform using C06PYF and a backward transform using C06PZF, and comparing the results with the original sequence (in exact arithmetic they would be identical).

8 Parallelism and Performance

C06PYF is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
C06PYF makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The time taken by C06PYF is approximately proportional to n 1 n 2 n 3 log n 1 n 2 n 3 , but also depends on the factors of n 1, n 2 and n 3. C06PYF is fastest if the only prime factors of n 1, n 2 and n 3 are 2, 3 and 5, and is particularly slow if one of the dimensions is a large prime, or has large prime factors.
Workspace is internally allocated by C06PYF. The total size of these arrays is approximately proportional to n 1 n 2 n 3 .

10 Example

This example reads in a trivariate sequence of real data values and prints their discrete Fourier transforms as computed by C06PYF. Inverse transforms are then calculated by calling C06PZF showing that the original sequences are restored.

10.1 Program Text

Program Text (c06pyfe.f90)

10.2 Program Data

Program Data (c06pyfe.d)

10.3 Program Results

Program Results (c06pyfe.r)

C06 Chapter Contents
C06 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


C06PZF : NAG Library, Mark 26

C06 Chapter Contents
C06 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

C06PZF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
10 Example

1 Purpose

C06PZF computes the three-dimensional inverse discrete Fourier transform of a trivariate Hermitian sequence of complex data values.

2 Specification

SUBROUTINE C06PZF ( N1, N2, N3, Y, X, IFAIL)
INTEGER | N1, N2, N3, IFAIL
REAL (KIND=nag_wp) | X(N1*N2*N3)
COMPLEX (KIND=nag_wp) | Y((N1/2+1)*N2*N3)

3 Description

C06PZF computes the three-dimensional inverse discrete Fourier transform of a trivariate Hermitian sequence of complex data values z j 1 j 2 j 3 , for j 1=0,1,…,n 1-1, j 2=0,1,…,n 2-1 and j 3=0,1,…,n 3-1.
The discrete Fourier transform is here defined by
x^ k 1 k 2 k 3 = 1 n 1 n 2 n 3 ∑ j 1=0 n 1-1 ∑ j 2=0 n 2-1 ∑ j 3=0 n 3-1 z j 1 j 2 j 3 × exp 2 π i j 1 k 1 n 1 + j 2 k 2 n 2 + j 3 k 3 n 3 ,
where k 1 = 0,1,…, n 1-1 , k 2 = 0,1,…, n 2-1 and k 3 = 0,1,…, n 3-1 . (Note the scale factor of 1 n 1 n 2 n 3 in this definition.)
Because the input data satisfies conjugate symmetry (i.e., z k 1 k 2 k 3 is the complex conjugate of z n 1 - k 1 k 2 k 3 ), the transformed values x^ k 1 k 2 k 3 are real.
A call of C06PYF followed by a call of C06PZF will restore the original data.
This routine calls C06PQF and C06PRF to perform multiple one-dimensional discrete Fourier transforms by the fast Fourier transform (FFT) algorithm in Brigham (1974) and Temperton (1983).

4 References

Brigham E O (1974) The Fast Fourier Transform Prentice–Hall
Temperton C (1983) Fast mixed-radix real Fourier transforms J. Comput. Phys. 52 340–350

5 Arguments

1:   N1 – INTEGERInput
On entry: n 1, the first dimension of the transform.
Constraint: N1≥1.
2:   N2 – INTEGERInput
On entry: n 2, the second dimension of the transform.
Constraint: N2≥1.
3:   N3 – INTEGERInput
On entry: n 3, the third dimension of the transform.
Constraint: N3≥1.
4:   Y N1/2+1×N2×N3 – COMPLEX (KIND=nag_wp) arrayInput
On entry: the Hermitian sequence of complex input dataset z, where z j 1 j 2 j 3 is stored in Y j 3 × n 1 /2+1 n 2 + j 2 × n 1 /2+1 + j 1 +1 , for j 1=0,1,…,n 1/2, j 2=0,1,…,n 2-1 and j 3=0,1,…,n 3-1. That is, if Y is regarded as a three-dimensional array of dimension 0:N1/2,0:N2-1,0:N3-1 , then Y j 1j 2j 3 must contain z j 1 j 2 j 3 .
5:   X N1×N2×N3 – REAL (KIND=nag_wp) arrayOutput
On exit: the real output dataset x^, where x^ k 1 k 2 k 3 is stored in X k 3 × n 1 n 2 + k 2 × n 1 + k 1 +1 , for k 1=0,1,…,n 1-1, k 2=0,1,…,n 2-1 and k 3=0,1,…,n 3-1. That is, if X is regarded as a three-dimensional array of dimension 0:N1-1,0:N2-1,0:N3-1 , then X k 1k 2k 3 contains x^ k 1 k 2 k 3 .
6:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, N1=value.
Constraint: N1≥1.
IFAIL=2
On entry, N2=value.
Constraint: N2≥1.
IFAIL=3
On entry, N3=value.
Constraint: N3≥1.
IFAIL=4
An internal error has occurred in this routine. Check the routine call and any array sizes. If the call is correct then please contact NAG for assistance.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

Some indication of accuracy can be obtained by performing a forward transform using C06PYF and a backward transform using C06PZF, and comparing the results with the original sequence (in exact arithmetic they would be identical).

8 Parallelism and Performance

C06PZF is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
C06PZF makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The time taken by C06PZF is approximately proportional to n 1 n 2 n 3 log n 1 n 2 n 3 , but also depends on the factors of n 1, n 2 and n 3. C06PZF is fastest if the only prime factors of n 1, n 2 and n 3 are 2, 3 and 5, and is particularly slow if one of the dimensions is a large prime, or has large prime factors.
Workspace is internally allocated by C06PZF. The total size of these arrays is approximately proportional to n 1 n 2 n 3 .

10 Example

See Section 10 in C06PYF.
C06 Chapter Contents
C06 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


C06RAF : NAG Library, Mark 26

C06 Chapter Contents
C06 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

C06RAF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

C06RAF computes the discrete Fourier sine transforms of m sequences of real data values.

2 Specification

SUBROUTINE C06RAF ( M, N, X, WORK, IFAIL)
INTEGER | M, N, IFAIL
REAL (KIND=nag_wp) | X(M*(N+2)), WORK(*)

3 Description

Given m sequences of n-1 real data values xjp , for j=1,2,…,n-1 and p=1,2,…,m, C06RAF simultaneously calculates the Fourier sine transforms of all the sequences defined by
x^ kp = 2 n ∑ j=1 n-1 xjp × sin jk πn ,   k= 1, 2, …, n-1 ​ and ​ p= 1, 2, …, m .
(Note the scale factor 2 n in this definition.)
Since the Fourier sine transform defined above is its own inverse, two consecutive calls of this routine will restore the original data.
The transform calculated by this routine can be used to solve Poisson's equation when the solution is specified at both left and right boundaries (see Swarztrauber (1977)).
The routine uses a variant of the fast Fourier transform (FFT) algorithm (see Brigham (1974)) known as the Stockham self-sorting algorithm, described in Temperton (1983), together with pre- and post-processing stages described in Swarztrauber (1982). Special coding is provided for the factors 2, 3, 4 and 5.

4 References

Brigham E O (1974) The Fast Fourier Transform Prentice–Hall
Swarztrauber P N (1977) The methods of cyclic reduction, Fourier analysis and the FACR algorithm for the discrete solution of Poisson's equation on a rectangle SIAM Rev. 19(3) 490–501
Swarztrauber P N (1982) Vectorizing the FFT's Parallel Computation (ed G Rodrique) 51–83 Academic Press
Temperton C (1983) Fast mixed-radix real Fourier transforms J. Comput. Phys. 52 340–350

5 Arguments

1:   M – INTEGERInput
On entry: m, the number of sequences to be transformed.
Constraint: M≥1.
2:   N – INTEGERInput
On entry: one more than the number of real values in each sequence, i.e., the number of values in each sequence is n-1.
Constraint: N≥1.
3:   X M×N+2 – REAL (KIND=nag_wp) arrayInput/Output
On entry: the data must be stored in X as if in a two-dimensional array of dimension 1:M,1:N+2; each of the m sequences is stored in a row of the array. In other words, if the n-1 data values of the pth sequence to be transformed are denoted by xjp, for j=1,2,…,n-1 and p=1,2,…,m, then the first m n-1 elements of the array X must contain the values
x 11 , x 12 ,…, x 1 m , x 21 , x 22 ,…, x 2 m ,…, x n-1 1 , x n-1 2 ,…, x n-1 m .
The nth to n+2th elements of each row xnp ,…, x n+2 p , for p=1,2,…,m, are required as workspace. These 3 m elements may contain arbitrary values as they are set to zero by the routine.
On exit: the m Fourier sine transforms stored as if in a two-dimensional array of dimension 1:M,1:N+2. Each of the m transforms is stored in a row of the array, overwriting the corresponding original sequence. If the n-1 components of the pth Fourier sine transform are denoted by x^kp, for k=1,2,…,n-1 and p=1,2,…,m, then the m n+2 elements of the array X contain the values
x^11 , x^12 ,…, x^1 m , x^21 , x^22 ,…, x^2 m ,…, x^ n-1 1 , x^ n-1 2 ,…, x^ n-1 m , 0 , 0 ,… , 0 3 m times .
4:   WORK* – REAL (KIND=nag_wp) arrayWorkspace
Note: the dimension of the array WORK must be at least M×N + 2×N + 2×M + 15.
The workspace requirements as documented for C06RAF may be an overestimate in some implementations.
On exit: WORK 1 contains the minimum workspace required for the current values of M and N with this implementation.
5:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, M<1.
IFAIL=2
On entry, N<1.
IFAIL=3
An unexpected error has occurred in an internal call. Check all subroutine calls and array dimensions. Seek expert help.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

Some indication of accuracy can be obtained by performing a subsequent inverse transform and comparing the results with the original sequence (in exact arithmetic they would be identical).

8 Parallelism and Performance

C06RAF is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
C06RAF makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The time taken by C06RAF is approximately proportional to nm log n, but also depends on the factors of n. C06RAF is fastest if the only prime factors of n are 2, 3 and 5, and is particularly slow if n is a large prime, or has large prime factors.

10 Example

This example reads in sequences of real data values and prints their Fourier sine transforms (as computed by C06RAF). It then calls C06RAF again and prints the results which may be compared with the original sequence.

10.1 Program Text

Program Text (c06rafe.f90)

10.2 Program Data

Program Data (c06rafe.d)

10.3 Program Results

Program Results (c06rafe.r)

C06 Chapter Contents
C06 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


C06RBF : NAG Library, Mark 26

C06 Chapter Contents
C06 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

C06RBF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

C06RBF computes the discrete Fourier cosine transforms of m sequences of real data values.

2 Specification

SUBROUTINE C06RBF ( M, N, X, WORK, IFAIL)
INTEGER | M, N, IFAIL
REAL (KIND=nag_wp) | X(M*(N+3)), WORK(*)

3 Description

Given m sequences of n+1 real data values xjp , for j=0,1,…,n and p=1,2,…,m, C06RBF simultaneously calculates the Fourier cosine transforms of all the sequences defined by
x^ k p = 2 n 12 x 0 p + ∑ j=1 n-1 xjp × cos jk πn + 12 -1 k xnp ,   k= 0, 1, …, n ​ and ​ p= 1, 2, …, m .
(Note the scale factor 2 n in this definition.)
Since the Fourier cosine transform is its own inverse, two consecutive calls of C06RBF will restore the original data.
The transform calculated by this routine can be used to solve Poisson's equation when the derivative of the solution is specified at both left and right boundaries (see Swarztrauber (1977)).
The routine uses a variant of the fast Fourier transform (FFT) algorithm (see Brigham (1974)) known as the Stockham self-sorting algorithm, described in Temperton (1983), together with pre- and post-processing stages described in Swarztrauber (1982). Special coding is provided for the factors 2, 3, 4 and 5.

4 References

Brigham E O (1974) The Fast Fourier Transform Prentice–Hall
Swarztrauber P N (1977) The methods of cyclic reduction, Fourier analysis and the FACR algorithm for the discrete solution of Poisson's equation on a rectangle SIAM Rev. 19(3) 490–501
Swarztrauber P N (1982) Vectorizing the FFT's Parallel Computation (ed G Rodrique) 51–83 Academic Press
Temperton C (1983) Fast mixed-radix real Fourier transforms J. Comput. Phys. 52 340–350

5 Arguments

1:   M – INTEGERInput
On entry: m, the number of sequences to be transformed.
Constraint: M≥1.
2:   N – INTEGERInput
On entry: one less than the number of real values in each sequence, i.e., the number of values in each sequence is n+1.
Constraint: N≥1.
3:   X M×N+3 – REAL (KIND=nag_wp) arrayInput/Output
On entry: the data must be stored in X as if in a two-dimensional array of dimension 1:M,0:N+2; each of the m sequences is stored in a row of the array. In other words, if the n+1 data values of the pth sequence to be transformed are denoted by xjp, for j=0,1,…,n and p=1,2,…,m, then the first m n+1 elements of the array X must contain the values
x 01 , x 02 ,…, x 0 m , x 11 , x 12 ,…, x 1 m ,…, xn 1 , xn 2 ,…, xnm .
The n+2th and n+3th elements of each row x n+2 p , x n+3 p , for p=1,2,…,m, are required as workspace. These 2 m elements may contain arbitrary values as they are set to zero by the routine.
On exit: the m Fourier cosine transforms stored as if in a two-dimensional array of dimension 1:M,0:N+2. Each of the m transforms is stored in a row of the array, overwriting the corresponding original data. If the n+1 components of the pth Fourier cosine transform are denoted by x^kp, for k=0,1,…,n and p=1,2,…,m, then the m n+3 elements of the array X contain the values
x^01 , x^02 ,…, x^0 m , x^11 , x^12 ,…, x^1 m ,…, x^n 1 , x^n 2 ,…, x^nm , 0 , 0 ,…,0 2 m times .
4:   WORK* – REAL (KIND=nag_wp) arrayWorkspace
Note: the dimension of the array WORK must be at least M×N + 2×N + 2×M + 15.
The workspace requirements as documented for C06RBF may be an overestimate in some implementations.
On exit: WORK 1 contains the minimum workspace required for the current values of M and N with this implementation.
5:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, M<1.
IFAIL=2
On entry, N<1.
IFAIL=3
An unexpected error has occurred in an internal call. Check all subroutine calls and array dimensions. Seek expert help.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

Some indication of accuracy can be obtained by performing a subsequent inverse transform and comparing the results with the original sequence (in exact arithmetic they would be identical).

8 Parallelism and Performance

C06RBF is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
C06RBF makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The time taken by C06RBF is approximately proportional to nm log n, but also depends on the factors of n. C06RBF is fastest if the only prime factors of n are 2, 3 and 5, and is particularly slow if n is a large prime, or has large prime factors.

10 Example

This example reads in sequences of real data values and prints their Fourier cosine transforms (as computed by C06RBF). It then calls the routine again and prints the results which may be compared with the original sequence.

10.1 Program Text

Program Text (c06rbfe.f90)

10.2 Program Data

Program Data (c06rbfe.d)

10.3 Program Results

Program Results (c06rbfe.r)

C06 Chapter Contents
C06 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


C06RCF : NAG Library, Mark 26

C06 Chapter Contents
C06 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

C06RCF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

C06RCF computes the discrete quarter-wave Fourier sine transforms of m sequences of real data values.

2 Specification

SUBROUTINE C06RCF ( DIRECT, M, N, X, WORK, IFAIL)
INTEGER | M, N, IFAIL
REAL (KIND=nag_wp) | X(M*(N+2)), WORK(*)
CHARACTER(1) | DIRECT

3 Description

Given m sequences of n real data values xjp , for j=1,2,…,n and p=1,2,…,m, C06RCF simultaneously calculates the quarter-wave Fourier sine transforms of all the sequences defined by
x^kp = 1 n ∑ j=1 n-1 xjp × sin j 2 k-1 π 2 n + 12 -1 k-1 xnp ,   if ​ DIRECT='F' ,
or its inverse
xkp = 2 n ∑ j=1 n x^ j p × sin 2 j- 1 k π 2 n ,   if ​ DIRECT='B' ,
where k=1,2,…,n and p=1,2,…,m.
(Note the scale factor 1 n in this definition.)
A call of C06RCF with DIRECT='F' followed by a call with DIRECT='B' will restore the original data.
The transform calculated by this routine can be used to solve Poisson's equation when the solution is specified at the left boundary, and the derivative of the solution is specified at the right boundary (see Swarztrauber (1977)).
The routine uses a variant of the fast Fourier transform (FFT) algorithm (see Brigham (1974)) known as the Stockham self-sorting algorithm, described in Temperton (1983), together with pre- and post-processing stages described in Swarztrauber (1982). Special coding is provided for the factors 2, 3, 4 and 5.

4 References

Brigham E O (1974) The Fast Fourier Transform Prentice–Hall
Swarztrauber P N (1977) The methods of cyclic reduction, Fourier analysis and the FACR algorithm for the discrete solution of Poisson's equation on a rectangle SIAM Rev. 19(3) 490–501
Swarztrauber P N (1982) Vectorizing the FFT's Parallel Computation (ed G Rodrique) 51–83 Academic Press
Temperton C (1983) Fast mixed-radix real Fourier transforms J. Comput. Phys. 52 340–350

5 Arguments

1:   DIRECT – CHARACTER(1)Input
On entry: if the forward transform as defined in Section 3 is to be computed, then DIRECT must be set equal to 'F'.
If the backward transform is to be computed then DIRECT must be set equal to 'B'.
Constraint: DIRECT='F' or 'B'.
2:   M – INTEGERInput
On entry: m, the number of sequences to be transformed.
Constraint: M≥1.
3:   N – INTEGERInput
On entry: n, the number of real values in each sequence.
Constraint: N≥1.
4:   X M×N+2 – REAL (KIND=nag_wp) arrayInput/Output
On entry: the data must be stored in X as if in a two-dimensional array of dimension 1:M,1:N+2; each of the m sequences is stored in a row of the array. In other words, if the data values of the pth sequence to be transformed are denoted by xjp, for j=1,2,…,n and p=1,2,…,m, then the first mn elements of the array X must contain the values
x 11 , x 12 ,…, x 1 m , x 21 , x 22 ,…, x 2 m ,…, xn 1 , xn 2 ,…, xnm .
The n+1th and n+2th elements of each row x n+1 p , x n+2 p , for p=1,2,…,m, are required as workspace. These 2 m elements may contain arbitrary values as they are set to zero by the routine.
On exit: the m quarter-wave sine transforms stored as if in a two-dimensional array of dimension 1:M,1:N+2. Each of the m transforms is stored in a row of the array, overwriting the corresponding original sequence. If the n components of the pth quarter-wave sine transform are denoted by x^kp, for k=1,2,…,n and p=1,2,…,m, then the m n+2 elements of the array X contain the values
x^11 , x^12 ,…, x^1 m , x^21 , x^22 ,…, x^2 m ,…, x^n 1 , x^n 2 ,…, x^nm , 0 , 0 ,…, 0 2 m times .
5:   WORK* – REAL (KIND=nag_wp) arrayWorkspace
Note: the dimension of the array WORK must be at least M×N + 2×N + 2×M + 15.
The workspace requirements as documented for C06RCF may be an overestimate in some implementations.
On exit: WORK 1 contains the minimum workspace required for the current values of M and N with this implementation.
6:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, M<1.
IFAIL=2
On entry, N<1.
IFAIL=3
On entry, DIRECT≠'F' or 'B'.
IFAIL=4
An unexpected error has occurred in an internal call. Check all subroutine calls and array dimensions. Seek expert help.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

Some indication of accuracy can be obtained by performing a subsequent inverse transform and comparing the results with the original sequence (in exact arithmetic they would be identical).

8 Parallelism and Performance

C06RCF is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
C06RCF makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The time taken by C06RCF is approximately proportional to nm log n, but also depends on the factors of n. C06RCF is fastest if the only prime factors of n are 2, 3 and 5, and is particularly slow if n is a large prime, or has large prime factors.

10 Example

This example reads in sequences of real data values and prints their quarter-wave sine transforms as computed by C06RCF with DIRECT='F'. It then calls the routine again with DIRECT='B' and prints the results which may be compared with the original data.

10.1 Program Text

Program Text (c06rcfe.f90)

10.2 Program Data

Program Data (c06rcfe.d)

10.3 Program Results

Program Results (c06rcfe.r)

C06 Chapter Contents
C06 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


C06RDF : NAG Library, Mark 26

C06 Chapter Contents
C06 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

C06RDF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

C06RDF computes the discrete quarter-wave Fourier cosine transforms of m sequences of real data values.

2 Specification

SUBROUTINE C06RDF ( DIRECT, M, N, X, WORK, IFAIL)
INTEGER | M, N, IFAIL
REAL (KIND=nag_wp) | X(M*(N+2)), WORK(*)
CHARACTER(1) | DIRECT

3 Description

Given m sequences of n real data values xjp , for j=0,1,…,n-1 and p=1,2,…,m, C06RDF simultaneously calculates the quarter-wave Fourier cosine transforms of all the sequences defined by
x^kp = 1 n 12 x 0 p + ∑ j=1 n-1 xjp × cos j 2 k-1 π 2 n ,   if ​ DIRECT='F' ,
or its inverse
xkp = 2 n ∑ j= 0 n- 1 x^ j p × cos 2 j- 1 k π 2 n ,   if ​ DIRECT='B' ,
where k=0,1,…,n-1 and p=1,2,…,m.
(Note the scale factor 1 n in this definition.)
A call of C06RDF with DIRECT='F' followed by a call with DIRECT='B' will restore the original data.
The transform calculated by this routine can be used to solve Poisson's equation when the derivative of the solution is specified at the left boundary, and the solution is specified at the right boundary (see Swarztrauber (1977)).
The routine uses a variant of the fast Fourier transform (FFT) algorithm (see Brigham (1974)) known as the Stockham self-sorting algorithm, described in Temperton (1983), together with pre- and post-processing stages described in Swarztrauber (1982). Special coding is provided for the factors 2, 3, 4 and 5.

4 References

Brigham E O (1974) The Fast Fourier Transform Prentice–Hall
Swarztrauber P N (1977) The methods of cyclic reduction, Fourier analysis and the FACR algorithm for the discrete solution of Poisson's equation on a rectangle SIAM Rev. 19(3) 490–501
Swarztrauber P N (1982) Vectorizing the FFT's Parallel Computation (ed G Rodrique) 51–83 Academic Press
Temperton C (1983) Fast mixed-radix real Fourier transforms J. Comput. Phys. 52 340–350

5 Arguments

1:   DIRECT – CHARACTER(1)Input
On entry: if the forward transform as defined in Section 3 is to be computed, then DIRECT must be set equal to 'F'.
If the backward transform is to be computed then DIRECT must be set equal to 'B'.
Constraint: DIRECT='F' or 'B'.
2:   M – INTEGERInput
On entry: m, the number of sequences to be transformed.
Constraint: M≥1.
3:   N – INTEGERInput
On entry: n, the number of real values in each sequence.
Constraint: N≥1.
4:   X M×N+2 – REAL (KIND=nag_wp) arrayInput/Output
On entry: the data must be stored in X as if in a two-dimensional array of dimension 1:M,0:N+1; each of the m sequences is stored in a row of the array. In other words, if the data values of the pth sequence to be transformed are denoted by xjp, for j=0,1,…,n-1 and p=1,2,…,m, then the first mn elements of the array X must contain the values
x 01 , x 02 ,…, x 0 m , x 11 , x 12 ,…, x 1 m ,…, x n-1 1 , x n-1 2 ,…, x n-1 m .
The n+1th and n+2th elements of each row xnp , x n+1 p , for p=1,2,…,m, are required as workspace. These 2 m elements may contain arbitrary values as they are set to zero by the routine.
On exit: the m quarter-wave cosine transforms stored as if in a two-dimensional array of dimension 1:M,0:N+1. Each of the m transforms is stored in a row of the array, overwriting the corresponding original sequence. If the n components of the pth quarter-wave cosine transform are denoted by x^kp, for k=0,1,…,n-1 and p=1,2,…,m, then the m n+2 elements of the array X contain the values
x^01 , x^02 ,…, x^0 m , x^11 , x^12 ,…, x^1 m ,…, x^ n-1 1 , x^ n-1 2 ,…, x^ n-1 m , 0 , 0 ,…, 0 2 m times .
5:   WORK* – REAL (KIND=nag_wp) arrayWorkspace
Note: the dimension of the array WORK must be at least M×N + 2×N + 2×M + 15.
The workspace requirements as documented for C06RDF may be an overestimate in some implementations.
On exit: WORK 1 contains the minimum workspace required for the current values of M and N with this implementation.
6:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, M<1.
IFAIL=2
On entry, N<1.
IFAIL=3
On entry, DIRECT≠'F' or 'B'.
IFAIL=4
An unexpected error has occurred in an internal call. Check all subroutine calls and array dimensions. Seek expert help.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

Some indication of accuracy can be obtained by performing a subsequent inverse transform and comparing the results with the original sequence (in exact arithmetic they would be identical).

8 Parallelism and Performance

C06RDF is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
C06RDF makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The time taken by C06RDF is approximately proportional to nm log n, but also depends on the factors of n. C06RDF is fastest if the only prime factors of n are 2, 3 and 5, and is particularly slow if n is a large prime, or has large prime factors.

10 Example

This example reads in sequences of real data values and prints their quarter-wave cosine transforms as computed by C06RDF with DIRECT='F'. It then calls the routine again with DIRECT='B' and prints the results which may be compared with the original data.

10.1 Program Text

Program Text (c06rdfe.f90)

10.2 Program Data

Program Data (c06rdfe.d)

10.3 Program Results

Program Results (c06rdfe.r)

C06 Chapter Contents
C06 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


C06REF : NAG Library, Mark 26

C06 Chapter Contents
C06 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

C06REF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

C06REF computes the discrete Fourier sine transforms of m sequences of real data values. The elements of each sequence and its transform are stored contiguously.

2 Specification

SUBROUTINE C06REF ( M, N, X, IFAIL)
INTEGER | M, N, IFAIL
REAL (KIND=nag_wp) | X(N-1,M)

3 Description

Given m sequences of n-1 real data values xjp , for j=1,2,…,n-1 and p=1,2,…,m, C06REF simultaneously calculates the Fourier sine transforms of all the sequences defined by
x^ k p = 2 n ∑ j=1 n-1 xjp × sin jk πn ,   k= 1, 2, …, n-1 ​ and ​ p= 1, 2, …, m .
(Note the scale factor 2 n in this definition.)
This transform is also known as type-I DST.
Since the Fourier sine transform defined above is its own inverse, two consecutive calls of C06REF will restore the original data.
The transform calculated by this routine can be used to solve Poisson's equation when the solution is specified at both left and right boundaries (see Swarztrauber (1977)).
The routine uses a variant of the fast Fourier transform (FFT) algorithm (see Brigham (1974)) known as the Stockham self-sorting algorithm, described in Temperton (1983), together with pre- and post-processing stages described in Swarztrauber (1982). Special coding is provided for the factors 2, 3, 4 and 5.

4 References

Brigham E O (1974) The Fast Fourier Transform Prentice–Hall
Swarztrauber P N (1977) The methods of cyclic reduction, Fourier analysis and the FACR algorithm for the discrete solution of Poisson's equation on a rectangle SIAM Rev. 19(3) 490–501
Swarztrauber P N (1982) Vectorizing the FFT's Parallel Computation (ed G Rodrique) 51–83 Academic Press
Temperton C (1983) Fast mixed-radix real Fourier transforms J. Comput. Phys. 52 340–350

5 Arguments

1:   M – INTEGERInput
On entry: m, the number of sequences to be transformed.
Constraint: M≥1.
2:   N – INTEGERInput
On entry: one more than the number of real values in each sequence, i.e., the number of values in each sequence is n-1.
Constraint: N≥1.
3:   X N-1 M – REAL (KIND=nag_wp) arrayInput/Output
On entry: the data values of the pth sequence to be transformed, denoted by xjp, for j=1,2,…,n-1 and p=1,2,…,m, must be stored in X jp.
On exit: the n-1 components of the pth Fourier sine transform, denoted by x^kp, for k=1,2,…,n-1 and p=1,2,…,m, are stored in X kp, overwriting the corresponding original values.
4:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, M=value.
Constraint: M≥1.
IFAIL=2
On entry, N=value.
Constraint: N≥1.
IFAIL=3
An internal error has occurred in this routine. Check the routine call and any array sizes. If the call is correct then please contact NAG for assistance.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

Some indication of accuracy can be obtained by performing a subsequent inverse transform and comparing the results with the original sequence (in exact arithmetic they would be identical).

8 Parallelism and Performance

C06REF is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The time taken by C06REF is approximately proportional to nm log n, but also depends on the factors of n. C06REF is fastest if the only prime factors of n are 2, 3 and 5, and is particularly slow if n is a large prime, or has large prime factors. Workspace of order O n is internally allocated by this routine.

10 Example

This example reads in sequences of real data values and prints their Fourier sine transforms (as computed by C06REF). It then calls C06REF again and prints the results which may be compared with the original sequence.

10.1 Program Text

Program Text (c06refe.f90)

10.2 Program Data

Program Data (c06refe.d)

10.3 Program Results

Program Results (c06refe.r)

C06 Chapter Contents
C06 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


C06RFF : NAG Library, Mark 26

C06 Chapter Contents
C06 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

C06RFF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

C06RFF computes the discrete Fourier cosine transforms of m sequences of real data values. The elements of each sequence and its transform are stored contiguously.

2 Specification

SUBROUTINE C06RFF ( M, N, X, IFAIL)
INTEGER | M, N, IFAIL
REAL (KIND=nag_wp) | X(0:N,M)

3 Description

Given m sequences of n+1 real data values xjp , for j=0,1,…,n and p=1,2,…,m, C06RFF simultaneously calculates the Fourier cosine transforms of all the sequences defined by
x^ k p = 2 n 12 x 0 p + ∑ j=1 n-1 xjp × cos jk πn + 12 -1 k xnp ,   k= 0, 1, …, n ​ and ​ p= 1, 2, …, m .
(Note the scale factor 2 n in this definition.)
This transform is also known as type-I DCT.
Since the Fourier cosine transform defined above is its own inverse, two consecutive calls of C06RFF will restore the original data.
The transform calculated by this routine can be used to solve Poisson's equation when the derivative of the solution is specified at both left and right boundaries (see Swarztrauber (1977)).
The routine uses a variant of the fast Fourier transform (FFT) algorithm (see Brigham (1974)) known as the Stockham self-sorting algorithm, described in Temperton (1983), together with pre- and post-processing stages described in Swarztrauber (1982). Special coding is provided for the factors 2, 3, 4 and 5.

4 References

Brigham E O (1974) The Fast Fourier Transform Prentice–Hall
Swarztrauber P N (1977) The methods of cyclic reduction, Fourier analysis and the FACR algorithm for the discrete solution of Poisson's equation on a rectangle SIAM Rev. 19(3) 490–501
Swarztrauber P N (1982) Vectorizing the FFT's Parallel Computation (ed G Rodrique) 51–83 Academic Press
Temperton C (1983) Fast mixed-radix real Fourier transforms J. Comput. Phys. 52 340–350

5 Arguments

1:   M – INTEGERInput
On entry: m, the number of sequences to be transformed.
Constraint: M≥1.
2:   N – INTEGERInput
On entry: one less than the number of real values in each sequence, i.e., the number of values in each sequence is n+1.
Constraint: N≥1.
3:   X 0:N M – REAL (KIND=nag_wp) arrayInput/Output
On entry: the data values of the pth sequence to be transformed, denoted by xjp, for j=0,1,…,n and p=1,2,…,m, must be stored in X jp.
On exit: the n+1 components of the pth Fourier cosine transform, denoted by x^kp, for k=0,1,…,n and p=1,2,…,m, are stored in X kp, overwriting the corresponding original values.
4:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, M=value.
Constraint: M≥1.
IFAIL=2
On entry, N=value.
Constraint: N≥1.
IFAIL=3
An internal error has occurred in this routine. Check the routine call and any array sizes. If the call is correct then please contact NAG for assistance.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

Some indication of accuracy can be obtained by performing a subsequent inverse transform and comparing the results with the original sequence (in exact arithmetic they would be identical).

8 Parallelism and Performance

C06RFF is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The time taken by C06RFF is approximately proportional to nm log n, but also depends on the factors of n. C06RFF is fastest if the only prime factors of n are 2, 3 and 5, and is particularly slow if n is a large prime, or has large prime factors. Workspace of order O n is internally allocated by this routine.

10 Example

This example reads in sequences of real data values and prints their Fourier cosine transforms (as computed by C06RFF). It then calls C06RFF again and prints the results which may be compared with the original sequence.

10.1 Program Text

Program Text (c06rffe.f90)

10.2 Program Data

Program Data (c06rffe.d)

10.3 Program Results

Program Results (c06rffe.r)

C06 Chapter Contents
C06 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


C06RGF : NAG Library, Mark 26

C06 Chapter Contents
C06 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

C06RGF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

C06RGF computes the discrete quarter-wave Fourier sine transforms of m sequences of real data values. The elements of each sequence and its transform are stored contiguously.

2 Specification

SUBROUTINE C06RGF ( IDIR, M, N, X, IFAIL)
INTEGER | IDIR, M, N, IFAIL
REAL (KIND=nag_wp) | X(N,M)

3 Description

Given m sequences of n real data values xjp , for j=1,2,…,n and p=1,2,…,m, C06RGF simultaneously calculates the quarter-wave Fourier sine transforms of all the sequences defined by
x^ k p = 1 n ∑ j=1 n-1 xjp × sin j 2 k-1 π 2 n + 12 -1 k-1 xnp ,   if ​ IDIR=1 ,
or its inverse
xkp = 2 n ∑ j=1 n x^ j p × sin 2 j-1 k π 2 n ,   if ​ IDIR=-1 ,
where k=1,2,…,n and p=1,2,…,m.
(Note the scale factor 1 n in this definition.)
A call of C06RGF with IDIR=1 followed by a call with IDIR=-1 will restore the original data.
The two transforms are also known as type-III DST and type-II DST, respectively.
The transform calculated by this routine can be used to solve Poisson's equation when the solution is specified at the left boundary, and the derivative of the solution is specified at the right boundary (see Swarztrauber (1977)).
The routine uses a variant of the fast Fourier transform (FFT) algorithm (see Brigham (1974)) known as the Stockham self-sorting algorithm, described in Temperton (1983), together with pre- and post-processing stages described in Swarztrauber (1982). Special coding is provided for the factors 2, 3, 4 and 5.

4 References

Brigham E O (1974) The Fast Fourier Transform Prentice–Hall
Swarztrauber P N (1977) The methods of cyclic reduction, Fourier analysis and the FACR algorithm for the discrete solution of Poisson's equation on a rectangle SIAM Rev. 19(3) 490–501
Swarztrauber P N (1982) Vectorizing the FFT's Parallel Computation (ed G Rodrique) 51–83 Academic Press
Temperton C (1983) Fast mixed-radix real Fourier transforms J. Comput. Phys. 52 340–350

5 Arguments

1:   IDIR – INTEGERInput
On entry: indicates the transform, as defined in Section 3, to be computed.
IDIR=1
Forward transform.
IDIR=-1
Inverse transform.
Constraint: IDIR=1 or -1.
2:   M – INTEGERInput
On entry: m, the number of sequences to be transformed.
Constraint: M≥1.
3:   N – INTEGERInput
On entry: n, the number of real values in each sequence.
Constraint: N≥1.
4:   X NM – REAL (KIND=nag_wp) arrayInput/Output
On entry: the data values of the pth sequence to be transformed, denoted by xjp, for j=1,2,…,n and p=1,2,…,m, must be stored in X jp.
On exit: the n components of the pth quarter-wave sine transform, denoted by x^kp, for k=1,2,…,n and p=1,2,…,m, are stored in X kp, overwriting the corresponding original values.
5:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, M=value.
Constraint: M≥1.
IFAIL=2
On entry, N=value.
Constraint: N≥1.
IFAIL=3
On entry, IDIR=value.
Constraint: IDIR=-1 or 1.
IFAIL=4
An internal error has occurred in this routine. Check the routine call and any array sizes. If the call is correct then please contact NAG for assistance.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

Some indication of accuracy can be obtained by performing a subsequent inverse transform and comparing the results with the original sequence (in exact arithmetic they would be identical).

8 Parallelism and Performance

C06RGF is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The time taken by C06RGF is approximately proportional to nm log n, but also depends on the factors of n. C06RGF is fastest if the only prime factors of n are 2, 3 and 5, and is particularly slow if n is a large prime, or has large prime factors. Workspace of order O n is internally allocated by this routine.

10 Example

This example reads in sequences of real data values and prints their quarter-wave sine transforms as computed by C06RGF with IDIR=1. It then calls the routine again with IDIR=-1 and prints the results which may be compared with the original data.

10.1 Program Text

Program Text (c06rgfe.f90)

10.2 Program Data

Program Data (c06rgfe.d)

10.3 Program Results

Program Results (c06rgfe.r)

C06 Chapter Contents
C06 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


C06RHF : NAG Library, Mark 26

C06 Chapter Contents
C06 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

C06RHF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

C06RHF computes the discrete quarter-wave Fourier cosine transforms of m sequences of real data values. The elements of each sequence and its transform are stored contiguously.

2 Specification

SUBROUTINE C06RHF ( IDIR, M, N, X, IFAIL)
INTEGER | IDIR, M, N, IFAIL
REAL (KIND=nag_wp) | X(0:N-1,M)

3 Description

Given m sequences of n real data values xjp , for j=0,1,…,n-1 and p=1,2,…,m, C06RHF simultaneously calculates the quarter-wave Fourier cosine transforms of all the sequences defined by
x^ k p = 1 n 12 x 0 p + ∑ j=1 n-1 xjp × cos j 2 k+1 π 2 n ,   if ​ IDIR=1 ,
or its inverse
xkp = 2 n ∑ j=0 n-1 x^ j p × cos 2 j+1 k π 2 n ,   if ​ IDIR=-1 ,
where k=0,1,…,n-1 and p=1,2,…,m.
(Note the scale factor 1 n in this definition.)
A call of C06RHF with IDIR=1 followed by a call with IDIR=-1 will restore the original data.
The two transforms are also known as type-III DCT and type-II DCT, respectively.
The transform calculated by this routine can be used to solve Poisson's equation when the derivative of the solution is specified at the left boundary, and the solution is specified at the right boundary (see Swarztrauber (1977)).
The routine uses a variant of the fast Fourier transform (FFT) algorithm (see Brigham (1974)) known as the Stockham self-sorting algorithm, described in Temperton (1983), together with pre- and post-processing stages described in Swarztrauber (1982). Special coding is provided for the factors 2, 3, 4 and 5.

4 References

Brigham E O (1974) The Fast Fourier Transform Prentice–Hall
Swarztrauber P N (1977) The methods of cyclic reduction, Fourier analysis and the FACR algorithm for the discrete solution of Poisson's equation on a rectangle SIAM Rev. 19(3) 490–501
Swarztrauber P N (1982) Vectorizing the FFT's Parallel Computation (ed G Rodrique) 51–83 Academic Press
Temperton C (1983) Fast mixed-radix real Fourier transforms J. Comput. Phys. 52 340–350

5 Arguments

1:   IDIR – INTEGERInput
On entry: indicates the transform, as defined in Section 3, to be computed.
IDIR=1
Forward transform.
IDIR=-1
Inverse transform.
Constraint: IDIR=1 or -1.
2:   M – INTEGERInput
On entry: m, the number of sequences to be transformed.
Constraint: M≥1.
3:   N – INTEGERInput
On entry: n, the number of real values in each sequence.
Constraint: N≥1.
4:   X 0:N-1 M – REAL (KIND=nag_wp) arrayInput/Output
On entry: the data values of the pth sequence to be transformed, denoted by xjp, for j=0,1,…,n-1 and p=1,2,…,m, must be stored in X jp.
On exit: the n components of the pth quarter-wave cosine transform, denoted by x^kp, for k=0,1,…,n-1 and p=1,2,…,m, are stored in X kp, overwriting the corresponding original values.
5:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, M=value.
Constraint: M≥1.
IFAIL=2
On entry, N=value.
Constraint: N≥1.
IFAIL=3
On entry, IDIR=value.
Constraint: IDIR=-1 or 1.
IFAIL=4
An internal error has occurred in this routine. Check the routine call and any array sizes. If the call is correct then please contact NAG for assistance.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

Some indication of accuracy can be obtained by performing a subsequent inverse transform and comparing the results with the original sequence (in exact arithmetic they would be identical).

8 Parallelism and Performance

C06RHF is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The time taken by C06RHF is approximately proportional to nm log n, but also depends on the factors of n. C06RHF is fastest if the only prime factors of n are 2, 3 and 5, and is particularly slow if n is a large prime, or has large prime factors. Workspace is internally allocated by this routine. The total amount of memory allocated is O n.

10 Example

This example reads in sequences of real data values and prints their quarter-wave cosine transforms as computed by C06RHF with IDIR=1. It then calls the routine again with IDIR=-1 and prints the results which may be compared with the original data.

10.1 Program Text

Program Text (c06rhfe.f90)

10.2 Program Data

Program Data (c06rhfe.d)

10.3 Program Results

Program Results (c06rhfe.r)

C06 Chapter Contents
C06 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


C09AAF : NAG Library, Mark 26

C09 Chapter Contents
C09 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

C09AAF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

C09AAF returns the details of the chosen one-dimensional discrete wavelet filter. For a chosen mother wavelet, discrete wavelet transform type (single-level or multi-level DWT or MODWT) and end extension method, this routine returns the maximum number of levels of resolution (appropriate to a multi-level transform), the filter length, and the number of approximation coefficients (equal to the number of detail coefficients) for a single-level DWT or MODWT or the total number of coefficients for a multi-level DWT or MODWT. This routine must be called before any of the one-dimensional discrete transform routines in this chapter.

2 Specification

SUBROUTINE C09AAF ( WAVNAM, WTRANS, MODE, N, NWLMAX, NF, NWC, ICOMM, IFAIL)
INTEGER | N, NWLMAX, NF, NWC, ICOMM(100), IFAIL
CHARACTER(*) | WAVNAM
CHARACTER(1) | WTRANS, MODE

3 Description

One-dimensional discrete wavelet transforms (DWT) or maximum overlap wavelet transforms (MODWT) are characterised by the mother wavelet, the end extension method and whether multiresolution analysis is to be performed. For the selected combination of choices for these three characteristics, and for a given length, n, of the input data array, x, C09AAF returns the dimension details for the transform determined by this combination. The dimension details are: lmax, the maximum number of levels of resolution that that could be computed were a multi-level DWT/MODWT applied; nf, the filter length; nc the number of approximation (or detail) coefficients for a single-level DWT/MODWT or the total number of coefficients generated by a multi-level DWT/MODWT over lmax levels. These values are also stored in the communication array ICOMM, as are the input choices, so that they may be conveniently communicated to the one-dimensional transform routines in this chapter.

4 References

None.

5 Arguments

1:   WAVNAM – CHARACTER(*)Input
On entry: the name of the mother wavelet. See the C09 Chapter Introduction for details.
WAVNAM='HAAR'
Haar wavelet.
WAVNAM='DB n', where n=2,3,…,10
Daubechies wavelet with n vanishing moments (2 n coefficients). For example, WAVNAM='DB4' is the name for the Daubechies wavelet with 4 vanishing moments (8 coefficients).
WAVNAM='BIOR x.y', where x.y can be one of 1.1, 1.3, 1.5, 2.2, 2.4, 2.6, 2.8, 3.1, 3.3, 3.5 or 3.7
Biorthogonal wavelet of order x.y. For example WAVNAM='BIOR3.1' is the name for the biorthogonal wavelet of order 3.1.
Constraint: WAVNAM='HAAR', 'DB2', 'DB3', 'DB4', 'DB5', 'DB6', 'DB7', 'DB8', 'DB9', 'DB10', 'BIOR1.1', 'BIOR1.3', 'BIOR1.5', 'BIOR2.2', 'BIOR2.4', 'BIOR2.6', 'BIOR2.8', 'BIOR3.1', 'BIOR3.3', 'BIOR3.5' or 'BIOR3.7'.
2:   WTRANS – CHARACTER(1)Input
On entry: the type of discrete wavelet transform that is to be applied.
WTRANS='S'
Single-level decomposition or reconstruction by discrete wavelet transform.
WTRANS='M'
Multiresolution, by a multi-level DWT or its inverse.
WTRANS='T'
Single-level decomposition or reconstruction by maximal overlap discrete wavelet transform.
WTRANS='U'
Multi-level resolution by a maximal overlap discrete wavelet transform or its inverse.
Constraint: WTRANS='S', 'M', 'T' or 'U'.
3:   MODE – CHARACTER(1)Input
On entry: the end extension method. Note that only periodic end extension is currently available for the MODWT.
MODE='P'
Periodic end extension.
MODE='H'
Half-point symmetric end extension.
MODE='W'
Whole-point symmetric end extension.
MODE='Z'
Zero end extension.
Constraints:
  • MODE='P', 'H', 'W' or 'Z' for DWT;
  • MODE='P' for MODWT.
4:   N – INTEGERInput
On entry: the number of elements, n, in the input data array, x.
Constraint: N≥2.
5:   NWLMAX – INTEGEROutput
On exit: the maximum number of levels of resolution, lmax, that can be computed when a multi-level discrete wavelet transform is applied. It is such that 2 lmax≤n<2 lmax+1, for lmax an integer.
6:   NF – INTEGEROutput
On exit: the filter length, nf, for the supplied mother wavelet. This is used to determine the number of coefficients to be generated by the chosen transform.
7:   NWC – INTEGEROutput
On exit: for a single-level transform (WTRANS='S' or 'T'), the number of approximation coefficients that would be generated for the given problem size, mother wavelet, extension method and type of transform; this is also the corresponding number of detail coefficients. For a multi-level transform (WTRANS='M' or 'U') the total number of coefficients that would be generated over lmax levels and with KEEPA='A' for MODWT.
8:   ICOMM 100 – INTEGER arrayCommunication Array
On exit: contains details of the wavelet transform and the problem dimension which is to be communicated to the one-dimensional discrete transform routines in this chapter.
9:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, WAVNAM=value was an illegal value.
IFAIL=2
On entry, WTRANS=value was an illegal value.
IFAIL=3
On entry, MODE=value was an illegal value.
On entry, WTRANS='T' or 'U' and MODE≠'P'.
Constraint: MODE='P' when WTRANS='T' or 'U'.
IFAIL=4
On entry, N=value.
Constraint: N≥2.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

Not applicable.

8 Parallelism and Performance

C09AAF is not threaded in any implementation.

9 Further Comments

None.

10 Example

This example computes the one-dimensional multi-level resolution for 8 values by a discrete wavelet transform using the Haar wavelet with zero end extensions. The length of the wavelet filter, the number of levels of resolution, the number of approximation coefficients at each level and the total number of wavelet coefficients are printed.

10.1 Program Text

Program Text (c09aafe.f90)

10.2 Program Data

Program Data (c09aafe.d)

10.3 Program Results

Program Results (c09aafe.r)

C09 Chapter Contents
C09 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


C09ABF : NAG Library, Mark 26

C09 Chapter Contents
C09 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

C09ABF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

C09ABF returns the details of the chosen two-dimensional discrete wavelet filter. For a chosen mother wavelet, discrete wavelet transform type (single-level or multi-level DWT) and end extension method, this routine returns the maximum number of levels of resolution (appropriate to a multi-level transform), the filter length, the total number of approximation, horizontal, vertical and diagonal coefficients and the number of coefficients in the second dimension for the single-level case. This routine must be called before any of the two-dimensional transform routines in this chapter.

2 Specification

SUBROUTINE C09ABF ( WAVNAM, WTRANS, MODE, M, N, NWLMAX, NF, NWCT, NWCN, ICOMM, IFAIL)
INTEGER | M, N, NWLMAX, NF, NWCT, NWCN, ICOMM(180), IFAIL
CHARACTER(*) | WAVNAM
CHARACTER(1) | WTRANS, MODE

3 Description

Two-dimensional discrete wavelet transforms (DWT) are characterised by the mother wavelet, the end extension method and whether multiresolution analysis is to be performed. For the selected combination of choices for these three characteristics, and for given dimensions (m×n) of data matrix A, C09ABF returns the dimension details for the transform determined by this combination. The dimension details are: lmax, the maximum number of levels of resolution that would be computed were a multi-level DWT applied; nf, the filter length; nct the total number of approximation, horizontal, vertical and diagonal coefficients (over all levels in the multi-level DWT case); and ncn, the number of coefficients in the second dimension for a single-level DWT. These values are also stored in the communication array ICOMM, as are the input choices, so that they may be conveniently communicated to the two-dimensional transform routines in this chapter.

4 References

None.

5 Arguments

1:   WAVNAM – CHARACTER(*)Input
On entry: the name of the mother wavelet. See the C09 Chapter Introduction for details.
WAVNAM='HAAR'
Haar wavelet.
WAVNAM='DB n', where n=2,3,…,10
Daubechies wavelet with n vanishing moments (2 n coefficients). For example, WAVNAM='DB4' is the name for the Daubechies wavelet with 4 vanishing moments (8 coefficients).
WAVNAM='BIOR x.y', where x.y can be one of 1.1, 1.3, 1.5, 2.2, 2.4, 2.6, 2.8, 3.1, 3.3, 3.5 or 3.7
Biorthogonal wavelet of order x.y. For example WAVNAM='BIOR3.1' is the name for the biorthogonal wavelet of order 3.1.
Constraint: WAVNAM='HAAR', 'DB2', 'DB3', 'DB4', 'DB5', 'DB6', 'DB7', 'DB8', 'DB9', 'DB10', 'BIOR1.1', 'BIOR1.3', 'BIOR1.5', 'BIOR2.2', 'BIOR2.4', 'BIOR2.6', 'BIOR2.8', 'BIOR3.1', 'BIOR3.3', 'BIOR3.5' or 'BIOR3.7'.
2:   WTRANS – CHARACTER(1)Input
On entry: the type of discrete wavelet transform that is to be applied.
WTRANS='S'
Single-level decomposition or reconstruction by discrete wavelet transform.
WTRANS='M'
Multiresolution, by a multi-level DWT or its inverse.
Constraint: WTRANS='S' or 'M'.
3:   MODE – CHARACTER(1)Input
On entry: the end extension method.
MODE='P'
Periodic end extension.
MODE='H'
Half-point symmetric end extension.
MODE='W'
Whole-point symmetric end extension.
MODE='Z'
Zero end extension.
Constraint: MODE='P', 'H', 'W' or 'Z'.
4:   M – INTEGERInput
On entry: the number of elements, m, in the first dimension (number of rows of data matrix A) of the input data.
Constraint: M≥2.
5:   N – INTEGERInput
On entry: the number of elements, n, in the second dimension (number of columns of data matrix A) of the input data.
Constraint: N≥2.
6:   NWLMAX – INTEGEROutput
On exit: the maximum number of levels of resolution, lmax, that can be computed if a multi-level discrete wavelet transform is applied (WTRANS='M'). It is such that 2 lmax≤min m,n<2 lmax+1, for lmax an integer.
If WTRANS='S', NWLMAX is not set.
7:   NF – INTEGEROutput
On exit: the filter length, nf, for the supplied mother wavelet. This is used to determine the number of coefficients to be generated by the chosen transform.
8:   NWCT – INTEGEROutput
On exit: the total number of wavelet coefficients, nct, that will be generated. When WTRANS='S' the number of rows required in each of the output coefficient matrices can be calculated as ncm=nct/4 ncn. When WTRANS='M' the length of the array used to store all of the coefficient matrices must be at least nct.
9:   NWCN – INTEGEROutput
On exit: for a single-level transform (WTRANS='S'), the number of coefficients that would be generated in the second dimension, ncn, for each coefficient type. For a multi-level transform (WTRANS='M') this is set to 1.
10:   ICOMM 180 – INTEGER arrayCommunication Array
On exit: contains details of the wavelet transform and the problem dimension which is to be communicated to the two-dimensional discrete transform routines in this chapter.
11:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, WAVNAM=value was an illegal value.
IFAIL=2
On entry, WTRANS=value was an illegal value.
IFAIL=3
On entry, MODE=value was an illegal value.
IFAIL=4
On entry, M=value.
Constraint: M≥2.
On entry, N=value.
Constraint: N≥2.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

Not applicable.

8 Parallelism and Performance

C09ABF is not threaded in any implementation.

9 Further Comments

None.

10 Example

This example computes the two-dimensional multi-level resolution for a 6×6 matrix by a discrete wavelet transform using the Haar wavelet with whole-point symmetric end extensions. The number of levels of transformation actually performed is one less than the maximum possible. This number of levels, the length of the wavelet filter, the total number of coefficients and the number of coefficients in each dimension for each level are printed along with the vertical detail coefficients from the first level, before a reconstruction is performed.

10.1 Program Text

Program Text (c09abfe.f90)

10.2 Program Data

Program Data (c09abfe.d)

10.3 Program Results

Program Results (c09abfe.r)

C09 Chapter Contents
C09 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


C09ACF : NAG Library, Mark 26

C09 Chapter Contents
C09 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

C09ACF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

C09ACF returns the details of the chosen three-dimensional discrete wavelet filter. For a chosen mother wavelet, discrete wavelet transform type (single-level or multi-level DWT) and end extension method, this routine returns the maximum number of levels of resolution (appropriate to a multi-level transform), the filter length, the total number of coefficients and the number of wavelet coefficients in the second and third dimensions for the single-level case. This routine must be called before any of the three-dimensional transform routines in this chapter.

2 Specification

SUBROUTINE C09ACF ( WAVNAM, WTRANS, MODE, M, N, FR, NWLMAX, NF, NWCT, NWCN, NWCFR, ICOMM, IFAIL)
INTEGER | M, N, FR, NWLMAX, NF, NWCT, NWCN, NWCFR, ICOMM(260), IFAIL
CHARACTER(*) | WAVNAM
CHARACTER(1) | WTRANS, MODE

3 Description

Three-dimensional discrete wavelet transforms (DWT) are characterised by the mother wavelet, the end extension method and whether multiresolution analysis is to be performed. For the selected combination of choices for these three characteristics, and for given dimensions (m×n×fr) of data array A, C09ACF returns the dimension details for the transform determined by this combination. The dimension details are: lmax, the maximum number of levels of resolution that would be computed were a multi-level DWT applied; nf, the filter length; nct the total number of wavelet coefficients (over all levels in the multi-level DWT case); ncn, the number of coefficients in the second dimension for a single-level DWT; and ncfr, the number of coefficients in the third dimension for a single-level DWT. These values are also stored in the communication array ICOMM, as are the input choices, so that they may be conveniently communicated to the three-dimensional transform routines in this chapter.

4 References

None.

5 Arguments

1:   WAVNAM – CHARACTER(*)Input
On entry: the name of the mother wavelet. See the C09 Chapter Introduction for details.
WAVNAM='HAAR'
Haar wavelet.
WAVNAM='DB n', where n=2,3,…,10
Daubechies wavelet with n vanishing moments (2 n coefficients). For example, WAVNAM='DB4' is the name for the Daubechies wavelet with 4 vanishing moments (8 coefficients).
WAVNAM='BIOR x.y', where x.y can be one of 1.1, 1.3, 1.5, 2.2, 2.4, 2.6, 2.8, 3.1, 3.3, 3.5 or 3.7
Biorthogonal wavelet of order x.y. For example WAVNAM='BIOR3.1' is the name for the biorthogonal wavelet of order 3.1.
Constraint: WAVNAM='HAAR', 'DB2', 'DB3', 'DB4', 'DB5', 'DB6', 'DB7', 'DB8', 'DB9', 'DB10', 'BIOR1.1', 'BIOR1.3', 'BIOR1.5', 'BIOR2.2', 'BIOR2.4', 'BIOR2.6', 'BIOR2.8', 'BIOR3.1', 'BIOR3.3', 'BIOR3.5' or 'BIOR3.7'.
2:   WTRANS – CHARACTER(1)Input
On entry: the type of discrete wavelet transform that is to be applied.
WTRANS='S'
Single-level decomposition or reconstruction by discrete wavelet transform.
WTRANS='M'
Multiresolution, by a multi-level DWT or its inverse.
Constraint: WTRANS='S' or 'M'.
3:   MODE – CHARACTER(1)Input
On entry: the end extension method.
MODE='P'
Periodic end extension.
MODE='H'
Half-point symmetric end extension.
MODE='W'
Whole-point symmetric end extension.
MODE='Z'
Zero end extension.
Constraint: MODE='P', 'H', 'W' or 'Z'.
4:   M – INTEGERInput
On entry: the number of elements, m, in the first dimension (number of rows of each two-dimensional frame) of the input data, A.
Constraint: M≥2.
5:   N – INTEGERInput
On entry: the number of elements, n, in the second dimension (number of columns of each two-dimensional frame) of the input data, A.
Constraint: N≥2.
6:   FR – INTEGERInput
On entry: the number of elements, fr, in the third dimension (number of frames) of the input data, A.
Constraint: FR≥2.
7:   NWLMAX – INTEGEROutput
On exit: the maximum number of levels of resolution, lmax, that can be computed if a multi-level discrete wavelet transform is applied (WTRANS='M'). It is such that 2 lmax ≤ min m,n,fr <2 lmax+1, for lmax an integer.
If WTRANS='S', NWLMAX is not set.
8:   NF – INTEGEROutput
On exit: the filter length, nf, for the supplied mother wavelet. This is used to determine the number of coefficients to be generated by the chosen transform.
9:   NWCT – INTEGEROutput
On exit: the total number of wavelet coefficients, nct, that will be generated. When WTRANS='S' the number of rows required (i.e., the first dimension of each two-dimensional frame) in each of the output coefficient arrays can be calculated as ncm=nct/8×ncn×ncfr. When WTRANS='M' the length of the array used to store all of the coefficient matrices must be at least nct.
10:   NWCN – INTEGEROutput
On exit: for a single-level transform (WTRANS='S'), the number of coefficients that would be generated in the second dimension, ncn, for each coefficient type. For a multi-level transform (WTRANS='M') this is set to 1.
11:   NWCFR – INTEGEROutput
On exit: for a single-level transform (WTRANS='S'), the number of coefficients that would be generated in the third dimension, ncfr, for each coefficient type. For a multi-level transform (WTRANS='M') this is set to 1.
12:   ICOMM 260 – INTEGER arrayCommunication Array
On exit: contains details of the wavelet transform and the problem dimension which is to be communicated to the two-dimensional discrete transform routines in this chapter.
13:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, WAVNAM=value was an illegal value.
IFAIL=2
On entry, WTRANS=value was an illegal value.
IFAIL=3
On entry, MODE=value was an illegal value.
IFAIL=4
On entry, FR=value.
Constraint: FR≥2.
On entry, M=value.
Constraint: M≥2.
On entry, N=value.
Constraint: N≥2.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

Not applicable.

8 Parallelism and Performance

C09ACF is not threaded in any implementation.

9 Further Comments

None.

10 Example

This example computes the three-dimensional multi-level resolution for 8×8×8 input data by a discrete wavelet transform using the Daubechies wavelet with four vanishing moments (see WAVNAM='DB4' in C09ACF) and zero end extension. The number of levels of transformation actually performed is one less than the maximum possible. This number of levels, the length of the wavelet filter, the total number of coefficients and the number of coefficients in each dimension for each level are printed along with the approximation coefficients before a reconstruction is performed. This example also demonstrates in general how to access any set of coefficients at any level following a multi-level transform.

10.1 Program Text

Program Text (c09acfe.f90)

10.2 Program Data

Program Data (c09acfe.d)

10.3 Program Results

Program Results (c09acfe.r)

C09 Chapter Contents
C09 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


C09BAF : NAG Library, Mark 26

C09 Chapter Contents
C09 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

C09BAF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

C09BAF computes the real, continuous wavelet transform in one dimension.

2 Specification

SUBROUTINE C09BAF ( WAVNAM, WPARAM, N, X, NSCAL, SCALES, C, IFAIL)
INTEGER | WPARAM, N, NSCAL, SCALES(NSCAL), IFAIL
REAL (KIND=nag_wp) | X(N), C(NSCAL,N)
CHARACTER(*) | WAVNAM

3 Description

C09BAF computes the real part of the one-dimensional, continuous wavelet transform
C s,k = ∫ ℝ x t 1 s ψ* t-k s dt ,
of a signal x t at scale s and position k, where the signal is sampled discretely at n equidistant points xi, for i=1,2,…,n. ψ is the wavelet function, which can be chosen to be the Morlet wavelet, the derivatives of a Gaussian or the Mexican hat wavelet (* denotes the complex conjugate). The integrals of the scaled, shifted wavelet function are approximated and the convolution is then computed.
The mother wavelets supplied for use with this routine are defined as follows.
1. The Morlet wavelet (real part) with nondimensional wave number κ is
ψ x = 1 π 1/4 cos κx - e -κ 2/2 e -x 2/2 ,
where the correction term, e-κ 2/2 (required to satisfy the admissibility condition) is included.
2. The derivatives of a Gaussian are obtained from
ψ^m x = dm e -x 2 d xm ,
taking m=1,…,8. These are the Hermite polynomials multiplied by the Gaussian. The sign is then adjusted to give ψ^m 0>0 when m is even while the sign of the succeeding odd derivative, ψ^m+1, is made consistent with the preceding even numbered derivative. They are normalized by the L 2-norm,
pm = ∫ -∞ ∞ ψ^ m x 2 d x 1/2
The resulting normalized derivatives can be written in terms of the Hermite polynomials, Hm x, as
ψ m x = α Hm x e -x 2 pm ,
where
α = 1, when ​m=0,3 mod 4; -1, when ​m=1,2 mod 4.
Thus, the derivatives of a Gaussian provided here are,
ψ 1 x = - 2 π 1/4 2 x e -x 2 ,
ψ 2 x = - 2 π 1/4 1 3 4 x 2 - 2 e -x 2 ,
ψ 3 x = 2 π 1/4 1 15 8 x 3 - 12 x e -x 2 ,
ψ 4 x = 2 π 1/4 1 105 16 x 4 - 48 x 2 + 12 e -x 2 ,
ψ 5 x = - 2 π 1/4 1 3 105 32 x 5 - 160 x 3 + 120 x e -x 2 ,
ψ 6 x = - 2 π 1/4 1 3 1155 64 x 6 - 480 x 4 + 720 x 2 - 120 e -x 2 ,
ψ 7 x = 2 π 1/4 1 3 15015 128 x 7 - 1344 x 5 + 3360 x 3 - 1680 x e -x 2 ,
ψ 8 x = 2 π 1/4 1 45 1001 256 x 8 - 3584 x 6 + 13440 x 4 - 13440 x 2 + 1680 e -x 2 .
3. The second derivative of a Gaussian is known as the Mexican hat wavelet and is supplied as an additional function in the form
ψ x = 2 3 π 1/4 1-x 2 e -x 2/2 .
The remaining normalized derivatives of a Gaussian can be expressed as multiples of the exponential e - t 2 / 2 by applying the substitution x = t / 2 followed by multiplication with the scaling factor, 1 / 24 .

4 References

Daubechies I (1992) Ten Lectures on Wavelets SIAM, Philadelphia

5 Arguments

1:   WAVNAM – CHARACTER(*)Input
On entry: the name of the mother wavelet. See the C09 Chapter Introduction for details.
WAVNAM='MORLET'
Morlet wavelet.
WAVNAM='DGAUSS'
Derivative of a Gaussian wavelet.
WAVNAM='MEXHAT'
Mexican hat wavelet.
Constraint: WAVNAM='MORLET', 'DGAUSS' or 'MEXHAT'.
2:   WPARAM – INTEGERInput
On entry: the nondimensional wave number for the Morlet wavelet or the order of the derivative for the Gaussian wavelet. It is not referenced when WAVNAM='MEXHAT'.
Constraints:
  • if WAVNAM='MORLET', 5≤WPARAM≤20;
  • if WAVNAM='DGAUSS', 1≤WPARAM≤8.
3:   N – INTEGERInput
On entry: the size, n, of the input dataset x.
Constraint: N≥2.
4:   X N – REAL (KIND=nag_wp) arrayInput
On entry: X contains the input dataset X j=xj, for j=1,2,…,n.
5:   NSCAL – INTEGERInput
On entry: the dimension of the array SCALES and the first dimension of the array C as declared in the (sub)program from which C09BAF is called. The number of scales to be computed.
Constraint: NSCAL≥1.
6:   SCALES NSCAL – INTEGER arrayInput
On entry: the scales at which the transform is to be computed.
Constraint: SCALES i≥1, for i=1,2,…,NSCAL.
7:   C NSCALN – REAL (KIND=nag_wp) arrayOutput
On exit: the transform coefficients at the requested scales, where C ij is the transform coefficient C i,j at scale i and position j.
8:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, WAVNAM=value was an illegal value.
IFAIL=2
On entry, WAVNAM='MORLET' and WPARAM=value.
Constraint: if WAVNAM='MORLET', 5≤WPARAM≤20.
On entry, WAVNAM='DGAUSS' and WPARAM=value.
Constraint: if WAVNAM='DGAUSS', 1≤WPARAM≤8.
IFAIL=3
On entry, N=value.
Constraint: N≥2.
IFAIL=5
On entry, NSCAL=value.
Constraint: NSCAL≥1.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

The accuracy of C09BAF is determined by the fact that the convolution must be computed as a discrete approximation to the continuous form. The input signal, x, is taken to be piecewise constant using the supplied discrete values.

8 Parallelism and Performance

C09BAF is not threaded in any implementation.

9 Further Comments

Workspace is internally allocated by C09BAF. The total size of these arrays is 213 + N + nk - 1 real elements and nk integer elements, where nk = k × max SCALES i and k=17 when WAVNAM='MORLET' or 'DGAUSS' and k=11 when WAVNAM='MEXHAT'.

10 Example

This example computes the continuous wavelet transform of a dataset containing a single nonzero value representing an impulse. The Morlet wavelet is used with wave number κ=5 and scales 1, 2, 3, 4.

10.1 Program Text

Program Text (c09bafe.f90)

10.2 Program Data

Program Data (c09bafe.d)

10.3 Program Results

Program Results (c09bafe.r)

C09 Chapter Contents
C09 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


C09CAF : NAG Library, Mark 26

C09 Chapter Contents
C09 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

C09CAF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

C09CAF computes the one-dimensional discrete wavelet transform (DWT) at a single level. The initialization routine C09AAF must be called first to set up the DWT options.

2 Specification

SUBROUTINE C09CAF ( N, X, LENC, CA, CD, ICOMM, IFAIL)
INTEGER | N, LENC, ICOMM(100), IFAIL
REAL (KIND=nag_wp) | X(N), CA(LENC), CD(LENC)

3 Description

C09CAF computes the one-dimensional DWT of a given input data array, xi, for i=1,2,…,n, at a single level. For a chosen wavelet filter pair, the output coefficients are obtained by applying convolution and downsampling by two to the input, x. The approximation (or smooth) coefficients, Ca, are produced by the low pass filter and the detail coefficients, Cd, by the high pass filter. To reduce distortion effects at the ends of the data array, several end extension methods are commonly used. Those provided are: periodic or circular convolution end extension, half-point symmetric end extension, whole-point symmetric end extension or zero end extension. The number nc, of coefficients Ca or Cd is returned by the initialization routine C09AAF.

4 References

Daubechies I (1992) Ten Lectures on Wavelets SIAM, Philadelphia

5 Arguments

1:   N – INTEGERInput
On entry: the number of elements, n, in the data array x.
Constraint: this must be the same as the value N passed to the initialization routine C09AAF.
2:   X N – REAL (KIND=nag_wp) arrayInput
On entry: X contains the input dataset xi, for i=1,2,…,n.
3:   LENC – INTEGERInput
On entry: the dimension of the arrays CA and CD as declared in the (sub)program from which C09CAF is called. This must be at least the number, nc, of approximation coefficients, Ca, and detail coefficients, Cd, of the discrete wavelet transform as returned in NWC by the call to the initialization routine C09AAF.
Constraint: LENC≥nc, where nc is the value returned in NWC by the call to the initialization routine C09AAF.
4:   CA LENC – REAL (KIND=nag_wp) arrayOutput
On exit: CA i contains the ith approximation coefficient, Ca i, for i=1,2,…,nc.
5:   CD LENC – REAL (KIND=nag_wp) arrayOutput
On exit: CD i contains the ith detail coefficient, Cd i, for i=1,2,…,nc.
6:   ICOMM 100 – INTEGER arrayCommunication Array
On entry: contains details of the discrete wavelet transform and the problem dimension as setup in the call to the initialization routine C09AAF.
On exit: contains additional information on the computed transform.
7:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, N is inconsistent with the value passed to the initialization routine: N=value, N should be value.
IFAIL=3
On entry, array dimension LENC not large enough: LENC=value but must be at least value.
IFAIL=6
Either the initialization routine has not been called first or array ICOMM has been corrupted.
Either the initialization routine was called with WTRANS='M' or array ICOMM has been corrupted.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

The accuracy of the wavelet transform depends only on the floating-point operations used in the convolution and downsampling and should thus be close to machine precision.

8 Parallelism and Performance

C09CAF is not threaded in any implementation.

9 Further Comments

None.

10 Example

This example computes the one-dimensional discrete wavelet decomposition for 8 values using the Daubechies wavelet, WAVNAM='DB4', with zero end extension.

10.1 Program Text

Program Text (c09cafe.f90)

10.2 Program Data

Program Data (c09cafe.d)

10.3 Program Results

Program Results (c09cafe.r)

C09 Chapter Contents
C09 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


C09CBF : NAG Library, Mark 26

C09 Chapter Contents
C09 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

C09CBF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
10 Example

1 Purpose

C09CBF computes the inverse one-dimensional discrete wavelet transform (DWT) at a single level. The initialization routine C09AAF must be called first to set up the DWT options.

2 Specification

SUBROUTINE C09CBF ( LENC, CA, CD, N, Y, ICOMM, IFAIL)
INTEGER | LENC, N, ICOMM(100), IFAIL
REAL (KIND=nag_wp) | CA(LENC), CD(LENC), Y(N)

3 Description

C09CBF performs the inverse operation of C09CAF. That is, given sets of nc approximation coefficients and detail coefficients, computed by C09CAF using a DWT as set up by the initialization routine C09AAF, on a real data array of length n, C09CBF will reconstruct the data array yi, for i=1,2,…,n, from which the coefficients were derived.

4 References

None.

5 Arguments

1:   LENC – INTEGERInput
On entry: the dimension of the arrays CA and CD as declared in the (sub)program from which C09CBF is called.
Constraint: LENC≥nc, where nc is the value returned in NWC by the call to the initialization routine C09AAF.
2:   CA LENC – REAL (KIND=nag_wp) arrayInput
On entry: the nc approximation coefficients, Ca. These will normally be the result of some transformation on the coefficients computed by C09CAF.
3:   CD LENC – REAL (KIND=nag_wp) arrayInput
On entry: the nc detail coefficients, Cd. These will normally be the result of some transformation on the coefficients computed by C09CAF.
4:   N – INTEGERInput
On entry: n, the length of the original data array from which the wavelet coefficients were computed by C09CAF and the length of the data array Y that is to be reconstructed by this routine.
Constraint: This must be the same as the value N passed to the initialization routine C09AAF.
5:   Y N – REAL (KIND=nag_wp) arrayOutput
On exit: the reconstructed data based on approximation and detail coefficients Ca and Cd and the transform options supplied to the initialization routine C09AAF.
6:   ICOMM 100 – INTEGER arrayCommunication Array
On entry: contains details of the discrete wavelet transform and the problem dimension and, possibly, additional information on the previously computed forward transform.
7:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, array dimension LENC not large enough: LENC=value but must be at least value.
IFAIL=4
On entry, N is inconsistent with the value passed to the initialization routine: N=value, N should be value.
IFAIL=6
Either the initialization routine has not been called first or array ICOMM has been corrupted.
Either the initialization routine was called with WTRANS='M' or array ICOMM has been corrupted.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

The accuracy of the wavelet transform depends only on the floating-point operations used in the convolution and downsampling and should thus be close to machine precision.

8 Parallelism and Performance

C09CBF is not threaded in any implementation.

9 Further Comments

None.

10 Example

See Section 10 in C09CAF.
C09 Chapter Contents
C09 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


C09CCF : NAG Library, Mark 26

C09 Chapter Contents
C09 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

C09CCF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

C09CCF computes the one-dimensional multi-level discrete wavelet transform (DWT). The initialization routine C09AAF must be called first to set up the DWT options.

2 Specification

SUBROUTINE C09CCF ( N, X, LENC, C, NWL, DWTLEV, ICOMM, IFAIL)
INTEGER | N, LENC, NWL, DWTLEV(NWL+1), ICOMM(100), IFAIL
REAL (KIND=nag_wp) | X(N), C(LENC)

3 Description

C09CCF computes the multi-level DWT of one-dimensional data. For a given wavelet and end extension method, C09CCF will compute a multi-level transform of a data array, xi, for i=1,2,…,n, using a specified number, nfwd, of levels. The number of levels specified, nfwd, must be no more than the value lmax returned in NWLMAX by the initialization routine C09AAF for the given problem. The transform is returned as a set of coefficients for the different levels (packed into a single array) and a representation of the multi-level structure.
The notation used here assigns level 0 to the input dataset, x, with level 1 being the first set of coefficients computed, with the detail coefficients, d 1, being stored while the approximation coefficients, a 1, are used as the input to a repeat of the wavelet transform. This process is continued until, at level nfwd, both the detail coefficients, d nfwd, and the approximation coefficients, a nfwd are retained. The output array, C, stores these sets of coefficients in reverse order, starting with a nfwd followed by d nfwd,d nfwd-1,…,d 1.

4 References

None.

5 Arguments

1:   N – INTEGERInput
On entry: the number of elements, n, in the data array x.
Constraint: this must be the same as the value N passed to the initialization routine C09AAF.
2:   X N – REAL (KIND=nag_wp) arrayInput
On entry: X contains the one-dimensional input dataset xi, for i=1,2,…,n.
3:   LENC – INTEGERInput
On entry: the dimension of the array C as declared in the (sub)program from which C09CCF is called. C must be large enough to contain the number, nc, of wavelet coefficients. The maximum value of nc is returned in NWC by the call to the initialization routine C09AAF and corresponds to the DWT being continued for the maximum number of levels possible for the given data set. When the number of levels, nfwd, is chosen to be less than the maximum, then nc is correspondingly smaller and LENC can be reduced by noting that the number of coefficients at each level is given by n-/2 for MODE='P' in C09AAF and n-+nf-1/2 for MODE='H', 'W' or 'Z', where n- is the number of input data at that level and nf is the filter length provided by the call to C09AAF. At the final level the storage is doubled to contain the set of approximation coefficients.
Constraint: LENC≥nc, where nc is the number of approximation and detail coefficients that correspond to a transform with NWLMAX levels.
4:   C LENC – REAL (KIND=nag_wp) arrayOutput
On exit: let q i denote the number of coefficients (of each type) produced by the wavelet transform at level i, for i=nfwd,nfwd-1,…,1. These values are returned in DWTLEV. Setting k 1=q nfwd and k j+1=kj+q nfwd-j+1, for j=1,2,…,nfwd, the coefficients are stored as follows:
C i, for i=1,2,…,k 1
Contains the level nfwd approximation coefficients, a nfwd.
C i, for i=k 1+1,…,k 2
Contains the level nfwd detail coefficients d nfwd.
C i, for i=kj+1,…,k j+1
Contains the level nfwd-j+1 detail coefficients, for j=2,3,…,nfwd.
5:   NWL – INTEGERInput
On entry: the number of levels, nfwd, in the multi-level resolution to be performed.
Constraint: 1≤NWL≤lmax, where lmax is the value returned in NWLMAX (the maximum number of levels) by the call to the initialization routine C09AAF.
6:   DWTLEV NWL+1 – INTEGER arrayOutput
On exit: the number of transform coefficients at each level. DWTLEV 1 and DWTLEV 2 contain the number, q nfwd, of approximation and detail coefficients respectively, for the final level of resolution (these are equal); DWTLEV i contains the number of detail coefficients, q nfwd-i+2, for the (nfwd-i+2)th level, for i=3,4,…,nfwd+1.
7:   ICOMM 100 – INTEGER arrayCommunication Array
On entry: contains details of the discrete wavelet transform and the problem dimension as setup in the call to the initialization routine C09AAF.
On exit: contains additional information on the computed transform.
8:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, N is inconsistent with the value passed to the initialization routine: N=value, N should be value.
IFAIL=3
On entry, LENC is set too small: LENC=value.
Constraint: LENC≥value.
IFAIL=5
On entry, NWL=value.
Constraint: NWL≥1.
On entry, NWL is larger than the maximum number of levels returned by the initialization routine: NWL=value, maximum =value.
IFAIL=7
Either the initialization routine has not been called first or array ICOMM has been corrupted.
Either the initialization routine was called with WTRANS='S' or array ICOMM has been corrupted.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

The accuracy of the wavelet transform depends only on the floating-point operations used in the convolution and downsampling and should thus be close to machine precision.

8 Parallelism and Performance

C09CCF is not threaded in any implementation.

9 Further Comments

The wavelet coefficients at each level can be extracted from the output array C using the information contained in DWTLEV on exit (see the descriptions of C and DWTLEV in Section 5). For example, given an input data set, x, denoising can be carried out by applying a thresholding operation to the detail coefficients at every level. The elements C i, for i = k 1+1 ,…, k nfwd + 1 , as described in Section 5, contain the detail coefficients, d^ij, for i=nfwd,nfwd-1,…,1 and j=1,2,…,q i, where d^ij=d ij+σ ε ij and σ ε ij is the transformed noise term. If some threshold parameter α is chosen, a simple hard thresholding rule can be applied as
d- ij = 0, if ​ d^ij ≤ α d^ij , if ​ d^ij > α,
taking d-ij to be an approximation to the required detail coefficient without noise, d ij. The resulting coefficients can then be used as input to C09CDF in order to reconstruct the denoised signal.
See the references given in the introduction to this chapter for a more complete account of wavelet denoising and other applications.

10 Example

This example performs a multi-level resolution of a dataset using the Daubechies wavelet (see WAVNAM='DB4' in C09AAF) using zero end extensions, the number of levels of resolution, the number of coefficients in each level and the coefficients themselves are reused. The original dataset is then reconstructed using C09CDF.

10.1 Program Text

Program Text (c09ccfe.f90)

10.2 Program Data

Program Data (c09ccfe.d)

10.3 Program Results

Program Results (c09ccfe.r)

C09 Chapter Contents
C09 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


C09CDF : NAG Library, Mark 26

C09 Chapter Contents
C09 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

C09CDF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
10 Example

1 Purpose

C09CDF computes the inverse one-dimensional multi-level discrete wavelet transform (DWT). This routine reconstructs data from (possibly filtered or otherwise manipulated) wavelet transform coefficients calculated by C09CCF from an original set of data. The initialization routine C09AAF must be called first to set up the DWT options.

2 Specification

SUBROUTINE C09CDF ( NWLINV, LENC, C, N, Y, ICOMM, IFAIL)
INTEGER | NWLINV, LENC, N, ICOMM(100), IFAIL
REAL (KIND=nag_wp) | C(LENC), Y(N)

3 Description

C09CDF performs the inverse operation of C09CCF. That is, given a set of wavelet coefficients, computed up to level nfwd by C09CCF using a DWT as set up by the initialization routine C09AAF, on a real data array of length n, C09CDF will reconstruct the data array yi, for i=1,2,…,n, from which the coefficients were derived. If the original input dataset is level 0, then it is possible to terminate reconstruction at a higher level by specifying fewer than the number of levels used in the call to C09CCF. This results in a partial reconstruction.

4 References

None.

5 Arguments

1:   NWLINV – INTEGERInput
On entry: the number of levels to be used in the inverse multi-level transform. The number of levels must be less than or equal to nfwd, which has the value of argument NWL as used in the computation of the wavelet coefficients using C09CCF. The data will be reconstructed to level NWL-NWLINV, where level 0 is the original input dataset provided to C09CCF.
Constraint: 1≤NWLINV≤NWL, where NWL is the value used in a preceding call to C09CCF.
2:   LENC – INTEGERInput
On entry: the dimension of the array C as declared in the (sub)program from which C09CDF is called.
Constraint: LENC≥nc, where nc is the total number of coefficients that correspond to a transform with NWLINV levels and is unchanged from the preceding call to C09CCF.
3:   C LENC – REAL (KIND=nag_wp) arrayInput
On entry: the coefficients of a multi-level wavelet transform of the dataset.
Let q i be the number of coefficients (of each type) at level i, for i=nfwd,nfwd-1,…,1. Then, setting k 1=q nfwd and k j+1=kj+q nfwd-j+1, for j=1,2,…,nfwd, the coefficients are stored in C as follows:
C i, for i=1,2,…,k 1
Contains the level nfwd approximation coefficients, a nfwd.
C i, for i=k 1+1,…,k 2
Contains the level nfwd detail coefficients d nfwd.
C i, for i=kj+1,…,k j+1
Contains the level nfwd-j+1 detail coefficients, for j=2,3,…,nfwd.
The values q i, for i=nfwd,nfwd-1,…,1, are contained in DWTLEV which is produced as output by a preceding call to C09CCF. See C09CCF for details.
4:   N – INTEGERInput
On entry: n, the length of the data array, y, to be reconstructed. For a full reconstruction of NWL levels, where NWL is as supplied to C09CCF, this must be the same as argument N used in the call to C09CCF. For a partial reconstruction of NWLINV<NWL, this must be equal to DWTLEV NWLINV+2, as returned from C09CCF.
5:   Y N – REAL (KIND=nag_wp) arrayOutput
On exit: the dataset reconstructed from the multi-level wavelet transform coefficients and the transformation options supplied to the initialization routine C09AAF.
6:   ICOMM 100 – INTEGER arrayCommunication Array
On entry: contains details of the discrete wavelet transform and the problem dimension for the forward transform previously computed by C09CCF.
7:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, NWLINV=value.
Constraint: NWLINV≥1.
On entry, NWLINV is larger than the number of levels computed by the preceding call to C09CCF: NWLINV=value, expected =value.
IFAIL=2
On entry, LENC is set too small: LENC=value.
Constraint: LENC≥value.
IFAIL=4
On entry, N is inconsistent with the value passed to the initialization routine: N=value, N should be value.
IFAIL=6
Either the initialization routine has not been called first or array ICOMM has been corrupted.
Either the initialization routine was called with WTRANS='S' or array ICOMM has been corrupted.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

The accuracy of the wavelet transform depends only on the floating-point operations used in the convolution and downsampling and should thus be close to machine precision.

8 Parallelism and Performance

C09CDF is not threaded in any implementation.

9 Further Comments

None.

10 Example

See Section 10 in C09CCF.
C09 Chapter Contents
C09 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


C09 Chapter Contents : NAG Library Manual, Mark 26

C09 Chapter Introduction
NAG Library Manual

NAG Library Chapter Contents

C09 – Wavelet Transforms

C09 Chapter Introduction – a description of the Chapter and an overview of the algorithms available

Routine Name | Mark of Introduction | Purpose
C09AAF Example Text Example Data | 22 | nagf_wav_1d_init One-dimensional wavelet filter initialization
C09ABF Example Text Example Data | 23 | nagf_wav_2d_init Two-dimensional wavelet filter initialization
C09ACF Example Text Example Data | 24 | nagf_wav_3d_init Three-dimensional wavelet filter initialization
C09BAF Example Text Example Data | 23 | nagf_wav_1d_cont One-dimensional real continuous wavelet transform
C09CAF Example Text Example Data | 22 | nagf_wav_1d_sngl_fwd One-dimensional discrete wavelet transform
C09CBF | 22 | nagf_wav_1d_sngl_inv One-dimensional inverse discrete wavelet transform
C09CCF Example Text Example Data | 22 | nagf_wav_1d_multi_fwd One-dimensional multi-level discrete wavelet transform
C09CDF | 22 | nagf_wav_1d_multi_inv One-dimensional inverse multi-level discrete wavelet transform
C09DAF Example Text Example Data | 25 | nagf_wav_1d_mxolap_fwd One-dimensional maximal overlap discrete wavelet transform (MODWT)
C09DBF | 25 | nagf_wav_1d_mxolap_inv One-dimensional inverse maximal overlap discrete wavelet transform (IMODWT)
C09DCF Example Text Example Data | 25 | nagf_wav_1d_mxolap_multi_fwd One-dimensional multi-level maximal overlap discrete wavelet transform (MODWT)
C09DDF | 25 | nagf_wav_1d_mxolap_multi_inv One-dimensional inverse multi-level maximal overlap discrete wavelet transform (IMODWT)
C09EAF Example Text Example Data | 23 | nagf_wav_2d_sngl_fwd Two-dimensional discrete wavelet transform
C09EBF | 23 | nagf_wav_2d_sngl_inv Two-dimensional inverse discrete wavelet transform
C09ECF Example Text Example Data | 23 | nagf_wav_2d_multi_fwd Two-dimensional multi-level discrete wavelet transform
C09EDF | 23 | nagf_wav_2d_multi_inv Two-dimensional inverse multi-level discrete wavelet transform
C09EYF | 25 | nagf_wav_2d_coeff_ext Two-dimensional discrete wavelet transform coefficient extraction
C09EZF Example Text Example Data | 25 | nagf_wav_2d_coeff_ins Two-dimensional discrete wavelet transform coefficient insertion
C09FAF Example Text Example Data | 24 | nagf_wav_3d_sngl_fwd Three-dimensional discrete wavelet transform
C09FBF | 24 | nagf_wav_3d_sngl_inv Three-dimensional inverse discrete wavelet transform
C09FCF Example Text Example Data | 24 | nagf_wav_3d_multi_fwd Three-dimensional multi-level discrete wavelet transform
C09FDF | 24 | nagf_wav_3d_mxolap_multi_inv Three-dimensional inverse multi-level discrete wavelet transform
C09FYF | 25 | nagf_wav_3d_coeff_ext Three-dimensional discrete wavelet transform coefficient extraction
C09FZF Example Text Example Data | 25 | nagf_wav_3d_coeff_ins Three-dimensional discrete wavelet transform coefficient insertion
C09 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


C09DAF : NAG Library, Mark 26

C09 Chapter Contents
C09 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

C09DAF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

C09DAF computes the one-dimensional maximal overlap discrete wavelet transform (MODWT) at a single level. The initialization routine C09AAF must be called first to set up the MODWT options.

2 Specification

SUBROUTINE C09DAF ( N, X, LENC, CA, CD, ICOMM, IFAIL)
INTEGER | N, LENC, ICOMM(100), IFAIL
REAL (KIND=nag_wp) | X(N), CA(LENC), CD(LENC)

3 Description

C09DAF computes the one-dimensional MODWT of a given input data array, xi, for i=1,2,…,n, at a single level. For a chosen wavelet filter pair, the output coefficients are obtained by applying convolution to the input, x. The approximation (or smooth) coefficients, Ca, are produced by the low pass filter and the detail coefficients, Cd, by the high pass filter. Periodic (circular) convolution is available as an end extension method for application to finite data sets. The number nc, of coefficients Ca or Cd is returned by the initialization routine C09AAF.

4 References

Percival D B and Walden A T (2000) Wavelet Methods for Time Series Analysis Cambridge University Press

5 Arguments

1:   N – INTEGERInput
On entry: the number of elements, n, in the data array x.
Constraint: this must be the same as the value N passed to the initialization routine C09AAF.
2:   X N – REAL (KIND=nag_wp) arrayInput
On entry: X contains the input dataset xi, for i=1,2,…,n.
3:   LENC – INTEGERInput
On entry: the dimension of the arrays CA and CD as declared in the (sub)program from which C09DAF is called. This must be at least the number, nc, of approximation coefficients, Ca, and detail coefficients, Cd, of the discrete wavelet transform as returned in NWC by the call to the initialization routine C09AAF. Note that nc=n for periodic end extension, but this is not the case for other end extension methods which will be available in future releases.
Constraint: LENC≥nc, where nc is the value returned in NWC by the call to the initialization routine C09AAF.
4:   CA LENC – REAL (KIND=nag_wp) arrayOutput
On exit: CA i contains the ith approximation coefficient, Ca i, for i=1,2,…,nc.
5:   CD LENC – REAL (KIND=nag_wp) arrayOutput
On exit: CD i contains the ith detail coefficient, Cd i, for i=1,2,…,nc.
6:   ICOMM 100 – INTEGER arrayCommunication Array
On entry: contains details of the discrete wavelet transform and the problem dimension as setup in the call to the initialization routine C09AAF.
On exit: contains additional information on the computed transform.
7:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, N is inconsistent with the value passed to the initialization routine: N=value, N should be value.
IFAIL=3
On entry, array dimension LENC not large enough: LENC=value but must be at least value.
IFAIL=6
On entry, the initialization routine C09AAF has not been called first or it has not been called with WTRANS='T', or the communication array ICOMM has become corrupted.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

The accuracy of the wavelet transform depends only on the floating-point operations used in the convolution and downsampling and should thus be close to machine precision.

8 Parallelism and Performance

C09DAF is not threaded in any implementation.

9 Further Comments

None.

10 Example

This example computes the one-dimensional maximal overlap discrete wavelet decomposition for 8 values using the Daubechies wavelet, WAVNAM='DB4'.

10.1 Program Text

Program Text (c09dafe.f90)

10.2 Program Data

Program Data (c09dafe.d)

10.3 Program Results

Program Results (c09dafe.r)

C09 Chapter Contents
C09 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


C09DBF : NAG Library, Mark 26

C09 Chapter Contents
C09 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

C09DBF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
10 Example

1 Purpose

C09DBF computes the inverse one-dimensional maximal overlap discrete wavelet transform (MODWT) at a single level. The initialization routine C09AAF must be called first to set up the MODWT options.

2 Specification

SUBROUTINE C09DBF ( LENC, CA, CD, N, Y, ICOMM, IFAIL)
INTEGER | LENC, N, ICOMM(100), IFAIL
REAL (KIND=nag_wp) | CA(LENC), CD(LENC), Y(N)

3 Description

C09DBF performs the inverse operation of C09DAF. That is, given sets of nc approximation coefficients and detail coefficients, computed by C09DAF using a MODWT as set up by the initialization routine C09AAF, on a real data array of length n, C09DBF will reconstruct the data array yi, for i=1,2,…,n, from which the coefficients were derived.

4 References

Percival D B and Walden A T (2000) Wavelet Methods for Time Series Analysis Cambridge University Press

5 Arguments

1:   LENC – INTEGERInput
On entry: the dimension of the arrays CA and CD as declared in the (sub)program from which C09DBF is called.
Constraint: LENC≥nc, where nc is the value returned in NWC by the call to the initialization routine C09AAF.
2:   CA LENC – REAL (KIND=nag_wp) arrayInput
On entry: the nc approximation coefficients, Ca. These will normally be the result of some transformation on the coefficients computed by C09DAF.
3:   CD LENC – REAL (KIND=nag_wp) arrayInput
On entry: the nc detail coefficients, Cd. These will normally be the result of some transformation on the coefficients computed by C09DAF.
4:   N – INTEGERInput
On entry: n, the length of the original data array from which the wavelet coefficients were computed by C09DAF and the length of the data array Y that is to be reconstructed by this routine.
Constraint: This must be the same as the value N passed to the initialization routine C09AAF.
5:   Y N – REAL (KIND=nag_wp) arrayOutput
On exit: the reconstructed data based on approximation and detail coefficients Ca and Cd and the transform options supplied to the initialization routine C09AAF.
6:   ICOMM 100 – INTEGER arrayCommunication Array
On entry: contains details of the discrete wavelet transform and the problem dimension and, possibly, additional information on the previously computed forward transform.
7:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, array dimension LENC not large enough: LENC=value but must be at least value.
IFAIL=4
On entry, N is inconsistent with the value passed to the initialization routine: N=value, N should be value.
IFAIL=6
On entry, the initialization routine C09AAF has not been called first or it has not been called with WTRANS='T', or the communication array ICOMM has become corrupted.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

The accuracy of the wavelet transform depends only on the floating-point operations used in the convolution and downsampling and should thus be close to machine precision.

8 Parallelism and Performance

C09DBF is not threaded in any implementation.

9 Further Comments

None.

10 Example

See Section 10 in C09DAF.
C09 Chapter Contents
C09 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


C09DCF : NAG Library, Mark 26

C09 Chapter Contents
C09 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

C09DCF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

C09DCF computes the one-dimensional multi-level maximal overlap discrete wavelet transform (MODWT). The initialization routine C09AAF must be called first to set up the MODWT options.

2 Specification

SUBROUTINE C09DCF ( N, X, KEEPA, LENC, C, NWL, NA, ICOMM, IFAIL)
INTEGER | N, LENC, NWL, NA, ICOMM(100), IFAIL
REAL (KIND=nag_wp) | X(N), C(LENC)
CHARACTER(1) | KEEPA

3 Description

C09DCF computes the multi-level MODWT for a data set, xi, for i=1,2,…,n, in one dimension. For a chosen number of levels, nl, with nl≤lmax, where lmax is returned by the initialization routine C09AAF in NWLMAX, the transform is returned as a set of coefficients for the different levels stored in a single array. Periodic reflection is currently the only available end extension method to reduce the edge effects caused by finite data sets.
The argument KEEPA can be set to retain both approximation and detail coefficients at each level resulting in nl×na+nd coefficients being returned in the output array, C, where na is the number of approximation coefficients and nd is the number of detail coefficients. Otherwise, only the detail coefficients are stored for each level along with the approximation coefficients for the final level, in which case the length of the output array, C, is na+nl×nd. In the present implementation, for simplicity, na and nd are chosen to be equal by adding zero padding to the wavelet filters where necessary.

4 References

Percival D B and Walden A T (2000) Wavelet Methods for Time Series Analysis Cambridge University Press

5 Arguments

1:   N – INTEGERInput
On entry: the number of elements, n, in the data array x.
Constraint: this must be the same as the value N passed to the initialization routine C09AAF.
2:   X N – REAL (KIND=nag_wp) arrayInput
On entry: X contains the input dataset xi, for i=1,2,…,n.
3:   KEEPA – CHARACTER(1)Input
On entry: determines whether the approximation coefficients are stored in array C for every level of the computed transform or else only for the final level. In both cases, the detail coefficients are stored in C for every level computed.
KEEPA='A'
Retain approximation coefficients for all levels computed.
KEEPA='F'
Retain approximation coefficients for only the final level computed.
Constraint: KEEPA='A' or 'F'.
4:   LENC – INTEGERInput
On entry: the dimension of the array C as declared in the (sub)program from which C09DCF is called. C must be large enough to contain the number of wavelet coefficients.
If KEEPA='F', the total number of coefficients, nc, is returned in NWC by the call to the initialization routine C09AAF and corresponds to the MODWT being continued for the maximum number of levels possible for the given data set. When the number of levels, nl, is chosen to be less than the maximum, then the number of stored coefficients is correspondingly smaller and LENC can be reduced by noting that nd detail coefficients are stored at each level, with the storage increased at the final level to contain the na approximation coefficients.
If KEEPA='A', nd detail coefficients and na approximation coefficients are stored for each level computed, requiring LENC≥nl×na+nd=2×nl×na, since the numbers of stored approximation and detail coefficients are equal. The number of approximation (or detail) coefficients at each level, na, is returned in NA.
Constraints:
  • if KEEPA='F', LENC≥nl+1×na;
  • if KEEPA='A', LENC≥2×nl×na.
5:   C LENC – REAL (KIND=nag_wp) arrayOutput
On exit: the coefficients of a multi-level wavelet transform of the dataset.
The coefficients are stored in C as follows:
If KEEPA='F',
C 1:na
Contains the level nl approximation coefficients;
C na + i-1 × nd+1 : na + i × nd
Contains the level nl-i+1 detail coefficients, for i=1,2,…,nl;
If KEEPA='A',
C i-1×na+1 : i×na
Contains the level nl-i+1 approximation coefficients, for i=1,2,…,nl;
C nl×na+i-1×nd+1 : nl×na+i×nd
Contains the level i detail coefficients, for i=1,2,…,nl;
The values na and nd denote the numbers of approximation and detail coefficients respectively, which are equal and returned in NA.
6:   NWL – INTEGERInput
On entry: the number of levels, nl, in the multi-level resolution to be performed.
Constraint: 1≤NWL≤lmax, where lmax is the value returned in NWLMAX (the maximum number of levels) by the call to the initialization routine C09AAF.
7:   NA – INTEGEROutput
On exit: NA contains the number of approximation coefficients, na, at each level which is equal to the number of detail coefficients, nd. With periodic end extension (MODE='P' in C09AAF) this is the same as the length, N, of the data array, X.
8:   ICOMM 100 – INTEGER arrayCommunication Array
On entry: contains details of the discrete wavelet transform and the problem dimension as setup in the call to the initialization routine C09AAF.
On exit: contains additional information on the computed transform.
9:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, N is inconsistent with the value passed to the initialization routine: N=value, N should be value.
IFAIL=2
On entry, KEEPA=value was an illegal value.
IFAIL=4
On entry, LENC is set too small: LENC=value.
Constraint: LENC≥value.
IFAIL=6
On entry, NWL=value.
Constraint: NWL≥1.
On entry, NWL is larger than the maximum number of levels returned by the initialization function: NWL=value, maximum = value.
IFAIL=8
On entry, the initialization routine C09AAF has not been called first or it has not been called with WTRANS='U', or the communication array ICOMM has become corrupted.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

The accuracy of the wavelet transform depends only on the floating-point operations used in the convolution and downsampling and should thus be close to machine precision.

8 Parallelism and Performance

C09DCF is not threaded in any implementation.

9 Further Comments

The wavelet coefficients at each level can be extracted from the output array C using the information contained in NA on exit.

10 Example

A set of data values (N=64) is decomposed using the MODWT over two levels and then the inverse (C09DDF) is applied to restore the original data set.

10.1 Program Text

Program Text (c09dcfe.f90)

10.2 Program Data

Program Data (c09dcfe.d)

10.3 Program Results

Program Results (c09dcfe.r)

C09 Chapter Contents
C09 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


C09DDF : NAG Library, Mark 26

C09 Chapter Contents
C09 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

C09DDF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
10 Example

1 Purpose

C09DDF computes the inverse one-dimensional multi-level maximal overlap discrete wavelet transform (MODWT). This routine reconstructs data from (possibly filtered or otherwise manipulated) wavelet transform coefficients calculated by C09DCF from an original set of data. The initialization routine C09AAF must be called first to set up the MODWT options.

2 Specification

SUBROUTINE C09DDF ( NWLINV, KEEPA, LENC, C, N, Y, ICOMM, IFAIL)
INTEGER | NWLINV, LENC, N, ICOMM(100), IFAIL
REAL (KIND=nag_wp) | C(LENC), Y(N)
CHARACTER(1) | KEEPA

3 Description

C09DDF performs the inverse operation of C09DCF. That is, given a set of wavelet coefficients computed by C09DCF using a MODWT as set up by the initialization routine C09AAF on a real array of length n, C09DDF will reconstruct the data array yi, for i=1,2,…,n, from which the coefficients were derived.

4 References

Percival D B and Walden A T (2000) Wavelet Methods for Time Series Analysis Cambridge University Press

5 Arguments

1:   NWLINV – INTEGERInput
On entry: the number of levels to be used in the inverse multi-level transform. The number of levels must be less than or equal to nfwd, which has the value of argument NWL as used in the computation of the wavelet coefficients using C09DCF. The data will be reconstructed to level NWL-NWLINV, where level 0 is the original input dataset provided to C09DCF.
Constraint: 1≤NWLINV≤NWL, where NWL is the value used in a preceding call to C09DCF.
2:   KEEPA – CHARACTER(1)Input
On entry: determines whether the approximation coefficients are stored in array C for every level of the computed transform or else only for the final level. In both cases, the detail coefficients are stored in C for every level computed.
KEEPA='A'
Retain approximation coefficients for all levels computed.
KEEPA='F'
Retain approximation coefficients for only the final level computed.
Constraint: KEEPA='A' or 'F'.
3:   LENC – INTEGERInput
On entry: the dimension of the array C as declared in the (sub)program from which C09DDF is called.
Constraints:
  • if KEEPA='F', LENC≥n l+1×na;
  • if KEEPA='A', LENC≥2×nl×na, where na is the number of approximation or detail coefficients at each level and is unchanged from the preceding call to C09DCF.
4:   C LENC – REAL (KIND=nag_wp) arrayInput
On entry: the coefficients of a multi-level wavelet transform of the dataset.
The coefficients are stored in C as follows:
If KEEPA='F',
C 1:na
Contains the level nl approximation coefficients;
C na + i-1×nd+1 : na+i×nd
Contains the level nl-i+1 detail coefficients, for i=1,2,…,nl;
If KEEPA='A',
C i-1 ×na+1:i×na
Contains the level nl-i+1 approximation coefficients, for i=1,2,…,nl;
C nl ×na+i-1 ×nd+1:nl ×na+i×nd
Contains the level i detail coefficients, for i=1,2,…,nl.
The values na and nd denote the numbers of approximation and detail coefficients respectively, which are equal. This number is returned as output in NA from a preceding call to C09DCF. See C09DCF for details.
5:   N – INTEGERInput
On entry: n, the length of the data array, y, to be reconstructed.
Constraint: This must be the same as the value N passed to the initialization routine C09AAF.
6:   Y N – REAL (KIND=nag_wp) arrayOutput
On exit: the dataset reconstructed from the multi-level wavelet transform coefficients and the transformation options supplied to the initialization routine C09AAF.
7:   ICOMM 100 – INTEGER arrayCommunication Array
On entry: contains details of the discrete wavelet transform and the problem dimension for the forward transform previously computed by C09DCF.
8:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, NWLINV=value.
Constraint: NWLINV≥1.
On entry, NWLINV is larger than the number of levels computed by the preceding call to C09DCF: NWLINV=value, expected value.
IFAIL=2
On entry, KEEPA=value was an illegal value.
IFAIL=3
On entry, LENC is set too small: LENC=value.
Constraint: LENC≥value.
IFAIL=5
On entry, N is inconsistent with the value passed to the initialization routine: N=value, N should be value.
IFAIL=7
On entry, the initialization routine C09AAF has not been called first or it has not been called with WTRANS='U', or the communication array ICOMM has become corrupted.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

The accuracy of the wavelet transform depends only on the floating-point operations used in the convolution and downsampling and should thus be close to machine precision.

8 Parallelism and Performance

C09DDF is not threaded in any implementation.

9 Further Comments

None.

10 Example

See Section 10 in C09DCF.
C09 Chapter Contents
C09 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


C09EAF : NAG Library, Mark 26

C09 Chapter Contents
C09 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

C09EAF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

C09EAF computes the two-dimensional discrete wavelet transform (DWT) at a single level. The initialization routine C09ABF must be called first to set up the DWT options.

2 Specification

SUBROUTINE C09EAF ( M, N, A, LDA, CA, LDCA, CH, LDCH, CV, LDCV, CD, LDCD, ICOMM, IFAIL)
INTEGER | M, N, LDA, LDCA, LDCH, LDCV, LDCD, ICOMM(180), IFAIL
REAL (KIND=nag_wp) | A(LDA,N), CA(LDCA,*), CH(LDCH,*), CV(LDCV,*), CD(LDCD,*)

3 Description

C09EAF computes the two-dimensional DWT of a given input data array, considered as a matrix A, at a single level. For a chosen wavelet filter pair, the output coefficients are obtained by applying convolution and downsampling by two to the input, A, first over columns and then to the result over rows. The matrix of approximation (or smooth) coefficients, Ca, is produced by the low pass filter over columns and rows; the matrix of horizontal coefficients, Ch, is produced by the high pass filter over columns and the low pass filter over rows; the matrix of vertical coefficients, Cv, is produced by the low pass filter over columns and the high pass filter over rows; and the matrix of diagonal coefficients, Cd, is produced by the high pass filter over columns and rows. To reduce distortion effects at the ends of the data array, several end extension methods are commonly used. Those provided are: periodic or circular convolution end extension, half-point symmetric end extension, whole-point symmetric end extension and zero end extension. The total number, nct, of coefficients computed for Ca, Ch, Cv, and Cd together and the number of columns of each coefficients matrix, ncn, are returned by the initialization routine C09ABF. These values can be used to calculate the number of rows of each coefficients matrix, ncm, using the formula ncm=nct/4⁢ncn.

4 References

Daubechies I (1992) Ten Lectures on Wavelets SIAM, Philadelphia

5 Arguments

1:   M – INTEGERInput
On entry: number of rows, m, of data matrix A.
Constraint: this must be the same as the value M passed to the initialization routine C09ABF.
2:   N – INTEGERInput
On entry: number of columns, n, of data matrix A.
Constraint: this must be the same as the value N passed to the initialization routine C09ABF.
3:   A LDAN – REAL (KIND=nag_wp) arrayInput
On entry: the m by n data matrix A.
4:   LDA – INTEGERInput
On entry: the first dimension of the array A as declared in the (sub)program from which C09EAF is called.
Constraint: LDA≥M.
5:   CA LDCA* – REAL (KIND=nag_wp) arrayOutput
Note: the second dimension of the array CA must be at least ncn where ncn is the argument NWCN returned by routine C09ABF.
On exit: contains the ncm by ncn matrix of approximation coefficients, Ca.
6:   LDCA – INTEGERInput
On entry: the first dimension of the array CA as declared in the (sub)program from which C09EAF is called.
Constraint: LDCA≥ncm where ncm=nct/4 ncn and ncn, nct are returned by the initialization routine C09ABF.
7:   CH LDCH* – REAL (KIND=nag_wp) arrayOutput
Note: the second dimension of the array CH must be at least ncn where ncn is the argument NWCN returned by routine C09ABF.
On exit: contains the ncm by ncn matrix of horizontal coefficients, Ch.
8:   LDCH – INTEGERInput
On entry: the first dimension of the array CH as declared in the (sub)program from which C09EAF is called.
Constraint: LDCH≥ncm where ncm=nct/4 ncn and ncn, nct are returned by the initialization routine C09ABF.
9:   CV LDCV* – REAL (KIND=nag_wp) arrayOutput
Note: the second dimension of the array CV must be at least ncn where ncn is the argument NWCN returned by routine C09ABF.
On exit: contains the ncm by ncn matrix of vertical coefficients, Cv.
10:   LDCV – INTEGERInput
On entry: the first dimension of the array CV as declared in the (sub)program from which C09EAF is called.
Constraint: LDCV≥ncm where ncm=nct/4 ncn and ncn, nct are returned by the initialization routine C09ABF.
11:   CD LDCD* – REAL (KIND=nag_wp) arrayOutput
Note: the second dimension of the array CD must be at least ncn where ncn is the argument NWCN returned by routine C09ABF.
On exit: contains the ncm by ncn matrix of diagonal coefficients, Cd.
12:   LDCD – INTEGERInput
On entry: the first dimension of the array CD as declared in the (sub)program from which C09EAF is called.
Constraint: LDCD≥ncm where ncm=nct/4 ncn and ncn, nct are returned by the initialization routine C09ABF.
13:   ICOMM 180 – INTEGER arrayCommunication Array
On entry: contains details of the discrete wavelet transform and the problem dimension as setup in the call to the initialization routine C09ABF.
14:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, M=value.
Constraint: M=value, the value of M on initialization (see C09ABF).
On entry, N=value.
Constraint: N=value, the value of N on initialization (see C09ABF).
IFAIL=2
On entry, LDA=value and M=value.
Constraint: LDA≥M.
IFAIL=3
On entry, LDCA=value.
Constraint: LDCA≥value, the number of wavelet coefficients in the first dimension.
On entry, LDCD=value.
Constraint: LDCD≥value, the number of wavelet coefficients in the first dimension.
On entry, LDCH=value.
Constraint: LDCH≥value, the number of wavelet coefficients in the first dimension.
On entry, LDCV=value.
Constraint: LDCV≥value, the number of wavelet coefficients in the first dimension.
IFAIL=6
Either the initialization routine has not been called first or ICOMM has been corrupted.
Either the initialization routine was called with WTRANS='M' or ICOMM has been corrupted.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

The accuracy of the wavelet transform depends only on the floating-point operations used in the convolution and downsampling and should thus be close to machine precision.

8 Parallelism and Performance

C09EAF is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

None.

10 Example

This example computes the two-dimensional discrete wavelet decomposition for a 6×6 input matrix using the Daubechies wavelet, WAVNAM='DB4', with half point symmetric end extension.

10.1 Program Text

Program Text (c09eafe.f90)

10.2 Program Data

Program Data (c09eafe.d)

10.3 Program Results

Program Results (c09eafe.r)

C09 Chapter Contents
C09 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


C09EBF : NAG Library, Mark 26

C09 Chapter Contents
C09 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

C09EBF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
10 Example

1 Purpose

C09EBF computes the inverse two-dimensional discrete wavelet transform (DWT) at a single level. The initialization routine C09ABF must be called first to set up the DWT options.

2 Specification

SUBROUTINE C09EBF ( M, N, CA, LDCA, CH, LDCH, CV, LDCV, CD, LDCD, B, LDB, ICOMM, IFAIL)
INTEGER | M, N, LDCA, LDCH, LDCV, LDCD, LDB, ICOMM(180), IFAIL
REAL (KIND=nag_wp) | CA(LDCA,*), CH(LDCH,*), CV(LDCV,*), CD(LDCD,*), B(LDB,N)

3 Description

C09EBF performs the inverse operation of routine C09EAF. That is, given sets of approximation, horizontal, vertical and diagonal coefficients computed by routine C09EAF using a DWT as set up by the initialization routine C09ABF, on a real matrix, B, C09EBF will reconstruct B.

4 References

None.

5 Arguments

1:   M – INTEGERInput
On entry: number of rows, m, of data matrix B.
Constraint: this must be the same as the value M passed to the initialization routine C09ABF.
2:   N – INTEGERInput
On entry: number of columns, n, of data matrix B.
Constraint: this must be the same as the value N passed to the initialization routine C09ABF.
3:   CA LDCA* – REAL (KIND=nag_wp) arrayInput
Note: the second dimension of the array CA must be at least ncn where ncn is the argument NWCN returned by routine C09ABF.
On entry: contains the ncm by ncn matrix of approximation coefficients, Ca. This array will normally be the result of some transformation on the coefficients computed by routine C09EAF.
4:   LDCA – INTEGERInput
On entry: the first dimension of the array CA as declared in the (sub)program from which C09EBF is called.
Constraint: LDCA≥ncm where ncm=nct/4 ncn and ncn, nct are returned by the initialization routine C09ABF.
5:   CH LDCH* – REAL (KIND=nag_wp) arrayInput
Note: the second dimension of the array CH must be at least ncn where ncn is the argument NWCN returned by routine C09ABF.
On entry: contains the ncm by ncn matrix of horizontal coefficients, Ch. This array will normally be the result of some transformation on the coefficients computed by routine C09EAF.
6:   LDCH – INTEGERInput
On entry: the first dimension of the array CH as declared in the (sub)program from which C09EBF is called.
Constraint: LDCH≥ncm where ncm=nct/4 ncn and ncn, nct are returned by the initialization routine C09ABF.
7:   CV LDCV* – REAL (KIND=nag_wp) arrayInput
Note: the second dimension of the array CV must be at least ncn where ncn is the argument NWCN returned by routine C09ABF.
On entry: contains the ncm by ncn matrix of vertical coefficients, Cv. This array will normally be the result of some transformation on the coefficients computed by routine C09EAF.
8:   LDCV – INTEGERInput
On entry: the first dimension of the array CV as declared in the (sub)program from which C09EBF is called.
Constraint: LDCV≥ncm where ncm=nct/4 ncn and ncn, nct are returned by the initialization routine C09ABF.
9:   CD LDCD* – REAL (KIND=nag_wp) arrayInput
Note: the second dimension of the array CD must be at least ncn where ncn is the argument NWCN returned by routine C09ABF.
On entry: contains the ncm by ncn matrix of diagonal coefficients, Cd. This array will normally be the result of some transformation on the coefficients computed by routine C09EAF.
10:   LDCD – INTEGERInput
On entry: the first dimension of the array CD as declared in the (sub)program from which C09EBF is called.
Constraint: LDCD≥ncm where ncm=nct/4 ncn and ncn, nct are returned by the initialization routine C09ABF.
11:   B LDBN – REAL (KIND=nag_wp) arrayOutput
On exit: the m by n reconstructed matrix, B, based on the input approximation, horizontal, vertical and diagonal coefficients and the transform options supplied to the initialization routine C09ABF.
12:   LDB – INTEGERInput
On entry: the first dimension of the array B as declared in the (sub)program from which C09EBF is called.
Constraint: LDB≥M.
13:   ICOMM 180 – INTEGER arrayCommunication Array
On entry: contains details of the discrete wavelet transform and the problem dimension as setup in the call to the initialization routine C09ABF.
14:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, LDCA=value.
Constraint: LDCA≥value, the number of wavelet coefficients in the first dimension.
On entry, LDCD=value.
Constraint: LDCD≥value, the number of wavelet coefficients in the first dimension.
On entry, LDCH=value.
Constraint: LDCH≥value, the number of wavelet coefficients in the first dimension.
On entry, LDCV=value.
Constraint: LDCV≥value, the number of wavelet coefficients in the first dimension.
IFAIL=2
On entry, LDB=value and M=value.
Constraint: LDB≥M.
IFAIL=4
On entry, M=value.
Constraint: M=value, the value of M on initialization (see C09ABF).
On entry, N=value.
Constraint: N=value, the value of N on initialization (see C09ABF).
IFAIL=6
Either the initialization routine has not been called first or ICOMM has been corrupted.
Either the initialization routine was called with WTRANS='M' or ICOMM has been corrupted.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

The accuracy of the wavelet transform depends only on the floating-point operations used in the convolution and downsampling and should thus be close to machine precision.

8 Parallelism and Performance

C09EBF is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

None.

10 Example

See Section 10 in C09EAF.
C09 Chapter Contents
C09 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


C09ECF : NAG Library, Mark 26

C09 Chapter Contents
C09 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

C09ECF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

C09ECF computes the two-dimensional multi-level discrete wavelet transform (DWT). The initialization routine C09ABF must be called first to set up the DWT options.

2 Specification

SUBROUTINE C09ECF ( M, N, A, LDA, LENC, C, NWL, DWTLVM, DWTLVN, ICOMM, IFAIL)
INTEGER | M, N, LDA, LENC, NWL, DWTLVM(NWL), DWTLVN(NWL), ICOMM(180), IFAIL
REAL (KIND=nag_wp) | A(LDA,N), C(LENC)

3 Description

C09ECF computes the multi-level DWT of two-dimensional data. For a given wavelet and end extension method, C09ECF will compute a multi-level transform of a matrix A, using a specified number, nfwd, of levels. The number of levels specified, nfwd, must be no more than the value lmax returned in NWLMAX by the initialization routine C09ABF for the given problem. The transform is returned as a set of coefficients for the different levels (packed into a single array) and a representation of the multi-level structure.
The notation used here assigns level 0 to the input matrix, A. Level 1 consists of the first set of coefficients computed: the vertical (v 1), horizontal (h 1) and diagonal (d 1) coefficients are stored at this level while the approximation (a 1) coefficients are used as the input to a repeat of the wavelet transform at the next level. This process is continued until, at level nfwd, all four types of coefficients are stored. The output array, C, stores these sets of coefficients in reverse order, starting with a nfwd followed by v nfwd , h nfwd , d nfwd , v nfwd-1 , h nfwd-1 , d nfwd-1 , … , v 1 , h 1 , d 1 .

4 References

None.

5 Arguments

1:   M – INTEGERInput
On entry: number of rows, m, of data matrix A.
Constraint: this must be the same as the value M passed to the initialization routine C09ABF.
2:   N – INTEGERInput
On entry: number of columns, n, of data matrix A.
Constraint: this must be the same as the value N passed to the initialization routine C09ABF.
3:   A LDAN – REAL (KIND=nag_wp) arrayInput
On entry: the m by n data matrix A.
4:   LDA – INTEGERInput
On entry: the first dimension of the array A as declared in the (sub)program from which C09ECF is called.
Constraint: LDA≥M.
5:   LENC – INTEGERInput
On entry: the dimension of the array C as declared in the (sub)program from which C09ECF is called. C must be large enough to contain, nct, wavelet coefficients. The maximum value of nct is returned in NWCT by the call to the initialization routine C09ABF and corresponds to the DWT being continued for the maximum number of levels possible for the given data set. When the number of levels, nfwd, is chosen to be less than the maximum, lmax, then nct is correspondingly smaller and LENC can be reduced by noting that the vertical, horizontal and diagonal coefficients are stored at every level and that in addition the approximation coefficients are stored for the final level only. The number of coefficients stored at each level is given by 3× m-/2 × n-/2 for MODE='P' in C09ABF and 3× m-+nf-1 / 2 × n-+nf-1 / 2 for MODE='H', 'W' or 'Z', where the input data is of dimension m-×n- at that level and nf is the filter length NF provided by the call to C09ABF. At the final level the storage is 4/3 times this value to contain the set of approximation coefficients.
Constraint: LENC≥nct, where nct is the total number of coefficients that correspond to a transform with NWL levels.
6:   C LENC – REAL (KIND=nag_wp) arrayOutput
On exit: the coefficients of the discrete wavelet transform. If you need to access or modify the approximation coefficients or any specific set of detail coefficients then the use of C09EYF or C09EZF is recommended. For completeness the following description provides details of precisely how the coefficient are stored in C but this information should only be required in rare cases.
Let q i denote the number of coefficients (of each type) at level i, for i=1,2,…,nfwd, such that q i = DWTLVM nfwd - i + 1 × DWTLVN nfwd - i + 1 . Then, letting k1=q nfwd and k j+1=kj+q nfwd-j/3+1, for j=1,2,…,3 nfwd, the coefficients are stored in C as follows:
C i, for i=1,2,…,k 1
Contains the level nfwd approximation coefficients, a nfwd.
C i, for i=kj+1,…,k j+1
Contains the level nfwd-j/3+1 vertical, horizontal and diagonal coefficients. These are:
  • vertical coefficients if j mod 3=1;
  • horizontal coefficients if j mod 3=2;
  • diagonal coefficients if j mod 3=0,
for j=1,…,3⁢nfwd.
7:   NWL – INTEGERInput
On entry: the number of levels, nfwd, in the multi-level resolution to be performed.
Constraint: 1≤NWL≤lmax, where lmax is the value returned in NWLMAX (the maximum number of levels) by the call to the initialization routine C09ABF.
8:   DWTLVM NWL – INTEGER arrayOutput
On exit: the number of coefficients in the first dimension for each coefficient type at each level. DWTLVM i contains the number of coefficients in the first dimension (for each coefficient type computed) at the (nfwd-i+1)th level of resolution, for i=1,2,…,nfwd. Thus for the first nfwd-1 levels of resolution, DWTLVM nfwd-i+1 is the size of the first dimension of the matrices of vertical, horizontal and diagonal coefficients computed at this level; for the final level of resolution, DWTLVM 1 is the size of the first dimension of the matrices of approximation, vertical, horizontal and diagonal coefficients computed.
9:   DWTLVN NWL – INTEGER arrayOutput
On exit: the number of coefficients in the second dimension for each coefficient type at each level. DWTLVN i contains the number of coefficients in the second dimension (for each coefficient type computed) at the (nfwd-i+1)th level of resolution, for i=1,2,…,nfwd. Thus for the first nfwd-1 levels of resolution, DWTLVN nfwd-i+1 is the size of the second dimension of the matrices of vertical, horizontal and diagonal coefficients computed at this level; for the final level of resolution, DWTLVN 1 is the size of the second dimension of the matrices of approximation, vertical, horizontal and diagonal coefficients computed.
10:   ICOMM 180 – INTEGER arrayCommunication Array
On entry: contains details of the discrete wavelet transform and the problem dimension as setup in the call to the initialization routine C09ABF.
On exit: contains additional information on the computed transform.
11:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, M=value.
Constraint: M=value, the value of M on initialization (see C09ABF).
On entry, N=value.
Constraint: N=value, the value of N on initialization (see C09ABF).
IFAIL=2
On entry, LDA=value and M=value.
Constraint: LDA≥M.
IFAIL=3
On entry, LENC=value.
Constraint: LENC≥value, the total number of coefficents to be generated.
IFAIL=5
On entry, NWL=value.
Constraint: NWL≥1.
On entry, NWL=value and NWLMAX=value in C09ABF.
Constraint: NWL≤NWLMAX in C09ABF.
IFAIL=7
Either the initialization routine has not been called first or ICOMM has been corrupted.
Either the initialization routine was called with WTRANS='S' or ICOMM has been corrupted.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

The accuracy of the wavelet transform depends only on the floating-point operations used in the convolution and downsampling and should thus be close to machine precision.

8 Parallelism and Performance

C09ECF is not threaded in any implementation.

9 Further Comments

The wavelet coefficients at each level can be extracted from the output array C using the information contained in DWTLVM and DWTLVN on exit (see the descriptions of C, DWTLVM and DWTLVN in Section 5). For example, given an input data set, A, denoising can be carried out by applying a thresholding operation to the detail (vertical, horizontal and diagonal) coefficients at every level. The elements C k 1+1 to C k nfwd+1, as described in Section 5, contain the detail coefficients, c^ij, for i=nfwd,nfwd-1,…,1 and j=1,2,…,3⁢q i, where q i is the number of each type of coefficient at level i and c^ij=c ij+σ ε ij and σ ε ij is the transformed noise term. If some threshold parameter α is chosen, a simple hard thresholding rule can be applied as
c- ij = 0, if ​ c^ij ≤ α c^ij , if ​ c^ij > α,
taking c-ij to be an approximation to the required detail coefficient without noise, c ij. The resulting coefficients can then be used as input to C09EDF in order to reconstruct the denoised signal. See Section 10 in C09EZF for a simple example of denoising.
See the references given in the introduction to this chapter for a more complete account of wavelet denoising and other applications.

10 Example

This example performs a multi-level resolution transform of a dataset using the Daubechies wavelet (see WAVNAM='DB2' in C09ABF) using half-point symmetric end extensions, the maximum possible number of levels of resolution, where the number of coefficients in each level and the coefficients themselves are not changed. The original dataset is then reconstructed using C09EDF.

10.1 Program Text

Program Text (c09ecfe.f90)

10.2 Program Data

Program Data (c09ecfe.d)

10.3 Program Results

Program Results (c09ecfe.r)

C09 Chapter Contents
C09 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


C09EDF : NAG Library, Mark 26

C09 Chapter Contents
C09 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

C09EDF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
10 Example

1 Purpose

C09EDF computes the inverse two-dimensional multi-level discrete wavelet transform (DWT). This routine reconstructs data from (possibly filtered or otherwise manipulated) wavelet transform coefficients calculated by C09ECF from an original input matrix. The initialization routine C09ABF must be called first to set up the DWT options.

2 Specification

SUBROUTINE C09EDF ( NWLINV, LENC, C, M, N, B, LDB, ICOMM, IFAIL)
INTEGER | NWLINV, LENC, M, N, LDB, ICOMM(180), IFAIL
REAL (KIND=nag_wp) | C(LENC), B(LDB,N)

3 Description

C09EDF performs the inverse operation of C09ECF. That is, given a set of wavelet coefficients, computed up to level nfwd by C09ECF using a DWT as set up by the initialization routine C09ABF, on a real matrix, A, C09EDF will reconstruct A. The reconstructed matrix is referred to as B in the following since it will not be identical to A when the DWT coefficients have been filtered or otherwise manipulated prior to reconstruction. If the original input matrix is level 0, then it is possible to terminate reconstruction at a higher level by specifying fewer than the number of levels used in the call to C09ECF. This results in a partial reconstruction.

4 References

None.

5 Arguments

1:   NWLINV – INTEGERInput
On entry: the number of levels to be used in the inverse multi-level transform. The number of levels must be less than or equal to nfwd, which has the value of argument NWL as used in the computation of the wavelet coefficients using C09ECF. The data will be reconstructed to level NWL-NWLINV, where level 0 is the original input dataset provided to C09ECF.
Constraint: 1≤NWLINV≤NWL, where NWL is the value used in a preceding call to C09ECF.
2:   LENC – INTEGERInput
On entry: the dimension of the array C as declared in the (sub)program from which C09EDF is called.
Constraint: LENC≥nct, where nct is the total number of coefficients that correspond to a transform with NWLINV levels and is unchanged from the preceding call to C09ECF.
3:   C LENC – REAL (KIND=nag_wp) arrayInput
On entry: the coefficients of a multi-level wavelet transform of the original matrix, A, which may have been filtered or otherwise manipulated.
Let q i be the number of coefficients (of each type) at level i, for i=nfwd,nfwd-1,…,1. Then, setting k 1=q nfwd and k j+1=kj+q nfwd-j/3+1, for j=1,2,…,3 nfwd, the coefficients are stored in C as follows:
C i, for i=1,2,…,k 1
Contains the level nfwd approximation coefficients, a nfwd.
C i, for i=kj+1,…,k j+1
Contains the level nfwd-j/3+1 vertical, horizontal and diagonal coefficients. These are:
  • vertical coefficients if j mod 3=1;
  • horizontal coefficients if j mod 3=2;
  • diagonal coefficients if j mod 3=0,
for j=1,…,3⁢nfwd.
Note that the coefficients in C may be extracted according to level and type into two-dimensional arrays using C09EYF, and inserted using C09EZF.
4:   M – INTEGERInput
On entry: the number of elements, m, in the first dimension of the reconstructed matrix B. For a full reconstruction of NWL levels, where NWL is as supplied to C09ECF, this must be the same as argument M used in the call to C09ECF. For a partial reconstruction of NWLINV<NWL levels, this must be equal to DWTLVM NWLINV+1, as returned from C09ECF.
5:   N – INTEGERInput
On entry: the number of elements, n, in the second dimension of the reconstructed matrix B. For a full reconstruction of NWL levels, where NWL is as supplied to C09FCF, this must be the same as argument N used in the call to C09ECF. For a partial reconstruction of NWLINV<NWL, this must be equal to DWTLVN NWLINV+1, as returned from C09ECF.
6:   B LDBN – REAL (KIND=nag_wp) arrayOutput
On exit: the m by n reconstructed matrix, B, based on the input multi-level wavelet transform coefficients and the transform options supplied to the initialization routine C09ABF.
7:   LDB – INTEGERInput
On entry: the first dimension of the array B as declared in the (sub)program from which C09EDF is called.
Constraint: LDB≥M.
8:   ICOMM 180 – INTEGER arrayCommunication Array
On entry: contains details of the discrete wavelet transform and the problem dimension as setup in the call to the initialization routine C09ABF.
9:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, NWLINV=value.
Constraint: NWLINV≥1.
On entry, NWLINV=value and nfwd=value.
Constraint: NWLINV≤nfwd.
IFAIL=2
On entry, LDB=value and M=value.
Constraint: LDB≥M.
IFAIL=3
On entry, LENC=value.
Constraint: LENC≥value, the total number of coefficients generated by the preceding call to C09ECF.
IFAIL=4
On entry, M=value.
Constraint: M≥value, the number of coefficients in the first dimension at the required level of reconstruction.
On entry, N=value.
Constraint: N≥value, the number of coefficients in the second dimension at the required level of reconstruction.
IFAIL=6
Either the initialization routine has not been called first or ICOMM has been corrupted.
Either the initialization routine was called with WTRANS='S' or ICOMM has been corrupted.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

The accuracy of the wavelet transform depends only on the floating-point operations used in the convolution and downsampling and should thus be close to machine precision.

8 Parallelism and Performance

C09EDF is not threaded in any implementation.

9 Further Comments

None.

10 Example

See Section 10 in C09ECF.
C09 Chapter Contents
C09 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


C09EYF : NAG Library, Mark 26

C09 Chapter Contents
C09 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

C09EYF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
10 Example

1 Purpose

C09EYF extracts a selected set of discrete wavelet transform (DWT) coefficients from the full set of coefficients stored in compact form, as computed by C09ECF (two-dimensional DWT).

2 Specification

SUBROUTINE C09EYF ( ILEV, CINDEX, LENC, C, D, LDD, ICOMM, IFAIL)
INTEGER | ILEV, CINDEX, LENC, LDD, ICOMM(180), IFAIL
REAL (KIND=nag_wp) | C(LENC), D(LDD,*)

3 Description

C09EYF is intended to be used after a call to C09ECF (two-dimensional DWT), which in turn should be preceded by a call to C09ABF (two-dimensional wavelet filter initialization). Given an initial two-dimensional data set A, a prior call to C09ECF computes the approximation coefficients (at the highest requested level) and three sets of detail coeficients at all levels and stores these in compact form in a one-dimensional array C. C09EYF can then extract either the approximation coefficients or one of the sets of detail coefficients at one of the levels into a matrix D. The dimensions of D depend on the level extracted and are available from the arrays DWTLVM and DWTLVN as returned by C09ECF which contain the first and second dimensions respectively. See Section 2.1 in the C09 Chapter Introduction for a discussion of the two-dimensional DWT.

4 References

None.

5 Arguments

Note: the following notation is used in this section:
  • ncm is the number of wavelet coefficients in the first dimension, which, at level ILEV, is equal to DWTLVM NWL-ILEV+1 as returned by a call to C09ECF transforming NWL levels.
  • ncn is the number of wavelet coefficients in the second dimension, which, at level ILEV, is equal to DWTLVN NWL-ILEV+1 as returned by a call to C09ECF transforming NWL levels.
1:   ILEV – INTEGERInput
On entry: the level at which coefficients are to be extracted.
Constraints:
  • 1≤ILEV≤NWL, where NWL is as used in a preceding call to C09ECF;
  • if CINDEX=0, ILEV=NWL.
2:   CINDEX – INTEGERInput
On entry: identifies which coefficients to extract. The coefficients are identified as follows:
CINDEX=0
The approximation coefficients, produced by application of the low pass filter over columns and rows of the original matrix (LL). The approximation coefficients are available only for ILEV=NWL, where NWL is the value used in a preceding call to C09ECF.
CINDEX=1
The vertical detail coefficients produced by applying the low pass filter over columns of the original matrix and the high pass filter over rows (LH).
CINDEX=2
The horizontal detail coefficients produced by applying the high pass filter over columns of the original matrix and the low pass filter over rows (HL).
CINDEX=3
The diagonal detail coefficients produced by applying the high pass filter over columns and rows of the original matrix (HH).
Constraint: 0≤CINDEX≤3 when ILEV=NWL as used in C09ECF, otherwise 1≤CINDEX≤3.
3:   LENC – INTEGERInput
On entry: the dimension of the array C as declared in the (sub)program from which C09EYF is called.
Constraint: LENC must be unchanged from the value used in the preceding call to C09ECF..
4:   C LENC – REAL (KIND=nag_wp) arrayInput
On entry: DWT coefficients, as computed by a preceding call to C09ECF.
5:   D LDD* – REAL (KIND=nag_wp) arrayOutput
Note: the second dimension of the array D must be at least ncn.
On exit: the requested coefficients.
If ILEV=NWL (as used in C09ECF) and CINDEX=0, the ncm by ncn approximation coefficients a ij are stored in D ij, for i=1,2,…,ncm and j=1,2,…,ncn.
Otherwise the ncm by ncn level ILEV detail coefficients (of type specified by CINDEX) d ij are stored in D ij, for i=1,2,…,ncm and j=1,2,…,ncn.
6:   LDD – INTEGERInput
On entry: the first dimension of the array D as declared in the (sub)program from which C09EYF is called.
Constraint: LDD≥ncm.
7:   ICOMM 180 – INTEGER arrayCommunication Array
On entry: contains details of the discrete wavelet transform and the problem dimension as setup in the call to the initialization routine C09ABF.
8:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, ILEV=value.
Constraint: ILEV≥1.
On entry, ILEV=value and NWL=value.
Constraint: ILEV≤NWL, where NWL is the number of levels used in the call to C09ECF.
IFAIL=2
On entry, CINDEX=value.
Constraint: CINDEX≤3.
On entry, CINDEX=value.
Constraint: CINDEX≥0.
IFAIL=3
On entry, LENC=value and nct=value.
Constraint: LENC≥nct, where nct is the number of DWT coefficients computed in a previous call to C09ECF.
IFAIL=4
On entry, LDD=value and ncm=value.
Constraint: LDD≥ncm, where ncm is the number of DWT coefficients in the first dimension at the selected level ILEV.
IFAIL=5
On entry, ILEV=value and NWL=value, but CINDEX=0.
Constraint: CINDEX>0 when ILEV<NWL in the preceding call to C09ECF.
IFAIL=6
Either the initialization routine has not been called first or ICOMM has been corrupted.
Either the initialization routine was called with WTRANS='S' or ICOMM has been corrupted.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

Not applicable.

8 Parallelism and Performance

C09EYF is not threaded in any implementation.

9 Further Comments

None.

10 Example

See Section 10 in C09ABF, C09ECF and C09EZF.
C09 Chapter Contents
C09 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


C09EZF : NAG Library, Mark 26

C09 Chapter Contents
C09 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

C09EZF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

C09EZF inserts a selected set of two-dimensional discrete wavelet transform (DWT) coefficients into the full set of coefficients stored in compact form, which may be later used as input to the multi-level reconstruction routine C09EDF.

2 Specification

SUBROUTINE C09EZF ( ILEV, CINDEX, LENC, C, D, LDD, ICOMM, IFAIL)
INTEGER | ILEV, CINDEX, LENC, LDD, ICOMM(180), IFAIL
REAL (KIND=nag_wp) | C(LENC), D(LDD,*)

3 Description

C09EZF inserts a selected set of two-dimensional DWT coefficients into the full set of coefficients stored in compact form in a one-dimensional array C. It is required that C09EZF is preceded by a call to the initialization routine C09ABF and the forward multi-level transform routine C09ECF.
Given an initial two-dimensional data set A, a prior call to C09ECF computes the approximation coefficients (at the highest requested level) and three sets of detail coeficients at all levels and stores these in compact form in a one-dimensional array C. C09EYF can then extract either the approximation coefficients or one of the sets of detail coefficients at one of the levels into a two-dimensional array, D. Following some calculation on this set of coefficients (for example, denoising), the updated coefficients in D are inserted back into the full set C using C09EZF. Several extractions and insertions may be performed at different levels. C09EDF can then be used to reconstruct a manipulated data set A~. The dimensions of D depend on the level extracted and are available from the arrays DWTLVM and DWTLVN as returned by C09ECF which contain the first and second dimensions respectively. See Section 2.1 in the C09 Chapter Introduction for a discussion of the multi-level two-dimensional DWT.

4 References

None.

5 Arguments

Note: the following notation is used in this section:
  • ncm is the number of wavelet coefficients in the first dimension, which, at level ILEV, is equal to DWTLVM NWL-ILEV+1 as returned by a call to C09ECF transforming NWL levels.
  • ncn is the number of wavelet coefficients in the second dimension, which, at level ILEV, is equal to DWTLVN NWL-ILEV+1 as returned by a call to C09ECF transforming NWL levels
1:   ILEV – INTEGERInput
On entry: the level at which coefficients are to be inserted.
Constraints:
  • 1≤ILEV≤NWL, where NWL is as used in a preceding call to C09ECF;
  • if CINDEX=0, ILEV=NWL.
2:   CINDEX – INTEGERInput
On entry: identifies which coefficients to insert. The coefficients are identified as follows:
CINDEX=0
The approximation coefficients, produced by application of the low pass filter over columns and rows of the original matrix (LL). The approximation coefficients are present only for ILEV=NWL, where NWL is the value used in a preceding call to C09ECF.
CINDEX=1
The vertical detail coefficients produced by applying the low pass filter over columns of the original matrix and the high pass filter over rows (LH).
CINDEX=2
The horizontal detail coefficients produced by applying the high pass filter over columns of the original matrix and the low pass filter over rows (HL).
CINDEX=3
The diagonal detail coefficients produced by applying the high pass filter over columns and rows of the original matrix (HH).
Constraint: 0≤CINDEX≤3 when ILEV=NWL as used in C09ECF, otherwise 1≤CINDEX≤3.
3:   LENC – INTEGERInput
On entry: the dimension of the array C as declared in the (sub)program from which C09EZF is called.
Constraint: LENC must be unchanged from the value used in the preceding call to C09ECF..
4:   C LENC – REAL (KIND=nag_wp) arrayInput/Output
On entry: contains the DWT coefficients inserted by previous calls to C09EZF, or computed by a previous call to C09ECF.
On exit: contains the same DWT coefficients provided on entry except for those identified by ILEV and CINDEX, which are updated with the values supplied in D, inserted into the correct locations as expected by the reconstruction routine C09EDF.
5:   D LDD* – REAL (KIND=nag_wp) arrayInput
Note: the second dimension of the array D must be at least ncn.
On entry: the coefficients to be inserted.
If ILEV=NWL (as used in C09ECF) and CINDEX=0, the ncm by ncn manipulated approximation coefficients a ij must be stored in D ij, for i=1,2,…,ncm and i=1,2,…,ncn.
Otherwise the ncm by ncn manipulated level ILEV detail coefficients (of type specified by CINDEX) d ij must be stored in D ij , for i=1,2,…,ncm and j=1,2,…,ncn.
6:   LDD – INTEGERInput
On entry: the first dimension of the array D as declared in the (sub)program from which C09EZF is called.
Constraint: LDD≥ncm.
7:   ICOMM 180 – INTEGER arrayCommunication Array
On entry: contains details of the discrete wavelet transform and the problem dimension as setup in the call to the initialization routine C09ABF.
8:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, ILEV=value.
Constraint: ILEV≥1.
On entry, ILEV=value and NWL=value.
Constraint: ILEV≤NWL, where NWL is the number of levels used in the call to C09ECF.
IFAIL=2
On entry, CINDEX=value.
Constraint: CINDEX≤3.
On entry, CINDEX=value.
Constraint: CINDEX≥0.
IFAIL=3
On entry, LENC=value and nct=value.
Constraint: LENC≥nct, where nct is the number of DWT coefficients computed in a previous call to C09ECF.
IFAIL=4
On entry, LDD=value and ncm=value.
Constraint: LDD≥ncm, where ncm is the number of DWT coefficients in the first dimension at the selected level ILEV.
IFAIL=5
On entry, ILEV=value and NWL=value, but CINDEX=0.
Constraint: CINDEX>0 when ILEV<NWL in the preceding call to C09ECF.
IFAIL=6
Either the initialization routine has not been called first or ICOMM has been corrupted.
Either the initialization routine was called with WTRANS='S' or ICOMM has been corrupted.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

Not applicable.

8 Parallelism and Performance

C09EZF is not threaded in any implementation.

9 Further Comments

None.

10 Example

The following example demonstrates using the coefficient extraction and insertion routines in order to apply denoising using a thresholding operation. The original input data, which is horizontally striped, has artificial noise introduced to it, taken from a normal random number distribution. Reconstruction then takes place on both the noisy data and denoised data. The Mean Square Errors (MSE) of the two reconstructions are printed along with the reconstruction of the denoised data. The MSE of the denoised reconstruction is less than that of the noisy reconstruction.

10.1 Program Text

Program Text (c09ezfe.f90)

10.2 Program Data

Program Data (c09ezfe.d)

10.3 Program Results

Program Results (c09ezfe.r)

C09 Chapter Contents
C09 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


C09FAF : NAG Library, Mark 26

C09 Chapter Contents
C09 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

C09FAF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

C09FAF computes the three-dimensional discrete wavelet transform (DWT) at a single level. The initialization routine C09ACF must be called first to set up the DWT options.

2 Specification

SUBROUTINE C09FAF ( M, N, FR, A, LDA, SDA, LENC, C, ICOMM, IFAIL)
INTEGER | M, N, FR, LDA, SDA, LENC, ICOMM(260), IFAIL
REAL (KIND=nag_wp) | A(LDA,SDA,FR), C(LENC)

3 Description

C09FAF computes the three-dimensional DWT of some given three-dimensional input data, considered as a number of two-dimensional frames, at a single level. For a chosen wavelet filter pair, the output coefficients are obtained by applying convolution and downsampling by two to the input data, A, first over columns, next over rows and finally across frames. The three-dimensional approximation coefficients are produced by the low pass filter over columns, rows and frames. In addition there are 7 sets of three-dimensional detail coefficients, each corresponding to a different order of low pass and high pass filters (see the C09 Chapter Introduction). All coefficients are packed into a single array. To reduce distortion effects at the ends of the data array, several end extension methods are commonly used. Those provided are: periodic or circular convolution end extension, half-point symmetric end extension, whole-point symmetric end extension and zero end extension. The total number, nct, of coefficients computed is returned by the initialization routine C09ACF.

4 References

Daubechies I (1992) Ten Lectures on Wavelets SIAM, Philadelphia

5 Arguments

1:   M – INTEGERInput
On entry: the number of rows of each two-dimensional frame.
Constraint: this must be the same as the value M passed to the initialization routine C09ACF.
2:   N – INTEGERInput
On entry: the number of columns of each two-dimensional frame.
Constraint: this must be the same as the value N passed to the initialization routine C09ACF.
3:   FR – INTEGERInput
On entry: the number of two-dimensional frames.
Constraint: this must be the same as the value FR passed to the initialization routine C09ACF.
4:   A LDASDAFR – REAL (KIND=nag_wp) arrayInput
On entry: the m by n by fr three-dimensional input data A, where A ijk is stored in A ijk.
5:   LDA – INTEGERInput
On entry: the first dimension of the array A as declared in the (sub)program from which C09FAF is called.
Constraint: LDA≥M.
6:   SDA – INTEGERInput
On entry: the second dimension of the array A as declared in the (sub)program from which C09FAF is called.
Constraint: SDA≥N.
7:   LENC – INTEGERInput
On entry: the dimension of the array C as declared in the (sub)program from which C09FAF is called.
Constraint: LENC≥nct, where nct is the total number of wavelet coefficients, as returned by C09ACF.
8:   C LENC – REAL (KIND=nag_wp) arrayOutput
On exit: the coefficients of the discrete wavelet transform. If you need to access or modify the approximation coefficients or any specific set of detail coefficients then the use of C09FYF or C09FZF is recommended. For completeness the following description provides details of precisely how the coefficients are stored in C but this information should only be required in rare cases.
The 8 sets of coefficients are stored in the following order: approximation coefficients (LLL) first, followed by 7 sets of detail coefficients: LLH, LHL, LHH, HLL, HLH, HHL, HHH, where L indicates the low pass filter, and H the high pass filter being applied to, respectively, the columns of length M, the rows of length N and then the frames of length FR. Note that for computational efficiency reasons each set of coefficients is stored in the order ncfr×ncm×ncn (see output arguments NWCFR, NWCT and NWCN in C09ACF). See Section 10 for details of how to access each set of coefficients in order to perform extraction from C following a call to this routine, or insertion into C before a call to the three-dimensional inverse routine C09FBF.
9:   ICOMM 260 – INTEGER arrayCommunication Array
On entry: contains details of the discrete wavelet transform and the problem dimension as setup in the call to the initialization routine C09ACF.
On exit: contains additional information on the computed transform.
10:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, FR=value.
Constraint: FR=value, the value of FR on initialization (see C09ACF).
On entry, M=value.
Constraint: M=value, the value of M on initialization (see C09ACF).
On entry, N=value.
Constraint: N=value, the value of N on initialization (see C09ACF).
IFAIL=2
On entry, LDA=value and M=value.
Constraint: LDA≥M.
On entry, SDA=value and N=value.
Constraint: SDA≥N.
IFAIL=3
On entry, LENC=value and nct=value.
Constraint: LENC≥nct, where nct is the number of DWT coefficients returned by C09ACF in argument NWCT.
IFAIL=6
Either the communication array ICOMM has been corrupted or there has not been a prior call to the initialization routine C09ACF.
The initialization routine was called with WTRANS='M'.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

The accuracy of the wavelet transform depends only on the floating-point operations used in the convolution and downsampling and should thus be close to machine precision.

8 Parallelism and Performance

C09FAF is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

None.

10 Example

This example computes the three-dimensional discrete wavelet decomposition for 5×4×3 input data using the Haar wavelet, WAVNAM='HAAR', with half point end extension, prints the wavelet coefficients and then reconstructs the original data using C09FBF. This example also demonstrates in general how to access any set of coefficients following a single level transform.

10.1 Program Text

Program Text (c09fafe.f90)

10.2 Program Data

Program Data (c09fafe.d)

10.3 Program Results

Program Results (c09fafe.r)

C09 Chapter Contents
C09 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


C09FBF : NAG Library, Mark 26

C09 Chapter Contents
C09 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

C09FBF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
10 Example

1 Purpose

C09FBF computes the three-dimensional inverse discrete wavelet transform (IDWT) at a single level. The initialization routine C09ACF must be called first to set up the DWT options.

2 Specification

SUBROUTINE C09FBF ( M, N, FR, LENC, C, B, LDB, SDB, ICOMM, IFAIL)
INTEGER | M, N, FR, LENC, LDB, SDB, ICOMM(260), IFAIL
REAL (KIND=nag_wp) | C(LENC), B(LDB,SDB,FR)

3 Description

C09FBF performs the inverse operation of routine C09FAF. That is, given sets of wavelet coefficients computed by routine C09FAF using a DWT as set up by the initialization routine C09ACF, on a real data array, B, C09FBF will reconstruct B.

4 References

None.

5 Arguments

1:   M – INTEGERInput
On entry: the number of rows of each two-dimensional frame.
Constraint: this must be the same as the value M passed to the initialization routine C09ACF.
2:   N – INTEGERInput
On entry: the number of columns of each two-dimensional frame.
Constraint: this must be the same as the value N passed to the initialization routine C09ACF.
3:   FR – INTEGERInput
On entry: the number two-dimensional frames.
Constraint: this must be the same as the value FR passed to the initialization routine C09ACF.
4:   LENC – INTEGERInput
On entry: the dimension of the array C as declared in the (sub)program from which C09FBF is called.
Constraint: LENC≥nct, where nct is the total number of wavelet coefficients, as returned by C09ACF.
5:   C LENC – REAL (KIND=nag_wp) arrayInput
On entry: the coefficients of the discrete wavelet transform. This will normally be the result of some transformation on the coefficients computed by routine C09FAF.
Note that the coefficients in C may be extracted according to type into three-dimensional arrays using C09FYF, and inserted using C09FZF.
6:   B LDBSDBFR – REAL (KIND=nag_wp) arrayOutput
On exit: the m by n by fr reconstructed array, B, with B ijk stored in B ijk. The reconstruction is based on the input wavelet coefficients and the transform options supplied to the initialization routine C09ACF.
7:   LDB – INTEGERInput
On entry: the first dimension of the array B as declared in the (sub)program from which C09FBF is called.
Constraint: LDB≥M.
8:   SDB – INTEGERInput
On entry: the second dimension of the array B as declared in the (sub)program from which C09FBF is called.
Constraint: SDB≥N.
9:   ICOMM 260 – INTEGER arrayCommunication Array
On entry: contains details of the discrete wavelet transform and the problem dimension as setup in the call to the initialization routine C09ACF.
10:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, FR=value.
Constraint: FR=value, the value of FR on initialization (see C09ACF).
On entry, M=value.
Constraint: M=value, the value of M on initialization (see C09ACF).
On entry, N=value.
Constraint: N=value, the value of N on initialization (see C09ACF).
IFAIL=2
On entry, LDB=value and M=value.
Constraint: LDB≥M.
On entry, SDB=value and N=value.
Constraint: SDB≥N.
IFAIL=3
On entry, LENC=value and nct=value.
Constraint: LENC≥nct, where nct is the number of DWT coefficients returned by C09ACF in argument NWCT.
IFAIL=6
Either the communication array ICOMM has been corrupted or there has not been a prior call to the initialization routine C09ACF.
The initialization routine was called with WTRANS='M'.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

The accuracy of the wavelet transform depends only on the floating-point operations used in the convolution and downsampling and should thus be close to machine precision.

8 Parallelism and Performance

C09FBF is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

None.

10 Example

See Section 10 in C09FAF.
C09 Chapter Contents
C09 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


C09FCF : NAG Library, Mark 26

C09 Chapter Contents
C09 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

C09FCF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

C09FCF computes the three-dimensional multi-level discrete wavelet transform (DWT). The initialization routine C09ACF must be called first to set up the DWT options.

2 Specification

SUBROUTINE C09FCF ( M, N, FR, A, LDA, SDA, LENC, C, NWL, DWTLVM, DWTLVN, DWTLVFR, ICOMM, IFAIL)
INTEGER | M, N, FR, LDA, SDA, LENC, NWL, DWTLVM(NWL), DWTLVN(NWL), DWTLVFR(NWL), ICOMM(260), IFAIL
REAL (KIND=nag_wp) | A(LDA,SDA,FR), C(LENC)

3 Description

C09FCF computes the multi-level DWT of three-dimensional data. For a given wavelet and end extension method, C09FCF will compute a multi-level transform of a three-dimensional array A, using a specified number, nfwd, of levels. The number of levels specified, nfwd, must be no more than the value lmax returned in NWLMAX by the initialization routine C09ACF for the given problem. The transform is returned as a set of coefficients for the different levels (packed into a single array) and a representation of the multi-level structure.
The notation used here assigns level 0 to the input data, A. Level 1 consists of the first set of coefficients computed: the seven sets of detail coefficients are stored at this level while the approximation coefficients are used as the input to a repeat of the wavelet transform at the next level. This process is continued until, at level nfwd, all eight types of coefficients are stored. All coefficients are packed into a single array.

4 References

Wang Y, Che X and Ma S (2012) Nonlinear filtering based on 3D wavelet transform for MRI denoising URASIP Journal on Advances in Signal Processing 2012:40

5 Arguments

1:   M – INTEGERInput
On entry: the number of rows of each two-dimensional frame.
Constraint: this must be the same as the value M passed to the initialization routine C09ACF.
2:   N – INTEGERInput
On entry: the number of columns of each two-dimensional frame.
Constraint: this must be the same as the value N passed to the initialization routine C09ACF.
3:   FR – INTEGERInput
On entry: the number of two-dimensional frames.
Constraint: this must be the same as the value FR passed to the initialization routine C09ACF.
4:   A LDASDAFR – REAL (KIND=nag_wp) arrayInput
On entry: the m by n by fr three-dimensional input data A, where with A ijk stored in A ijk.
5:   LDA – INTEGERInput
On entry: the first dimension of the array A as declared in the (sub)program from which C09FCF is called.
Constraint: LDA≥M.
6:   SDA – INTEGERInput
On entry: the second dimension of the array A as declared in the (sub)program from which C09FCF is called.
Constraint: SDA≥N.
7:   LENC – INTEGERInput
On entry: the dimension of the array C as declared in the (sub)program from which C09FCF is called.
Constraint: LENC≥nct, where nct is the total number of wavelet coefficients that correspond to a transform with NWL levels.
8:   C LENC – REAL (KIND=nag_wp) arrayOutput
On exit: the coefficients of the discrete wavelet transform. If you need to access or modify the approximation coefficients or any specific set of detail coefficients then the use of C09FYF or C09FZF is recommended. For completeness the following description provides details of precisely how the coefficients are stored in C but this information should only be required in rare cases.
Let q i denote the number of coefficients of each type at level i, for i=1,2,…,nfwd, such that q i= DWTLVM nfwd-i+1× DWTLVN nfwd-i+1× DWTLVFR nfwd-i+1 . Then, letting k1=q nfwd and k j+1=kj+q nfwd-j/7+1, for j=1,2,…,7 nfwd, the coefficients are stored in C as follows:
C i, for i=1,2,…,k 1
Contains the level nfwd approximation coefficients, a nfwd. Note that for computational efficiency reasons these coefficients are stored as DWTLVM 1× DWTLVN 1× DWTLVFR 1 in C.
C i, for i=kj+1,…,k j+1
Contains the level nfwd-j/7+1 detail coefficients. These are:
  • LLH coefficients if j mod 7=1;
  • LHL coefficients if j mod 7=2;
  • LHH coefficients if j mod 7=3;
  • HLL coefficients if j mod 7=4;
  • HLH coefficients if j mod 7=5;
  • HHL coefficients if j mod 7=6;
  • HHH coefficients if j mod 7=0,
for j=1,…,7⁢nfwd. See Section 2.1 in the C09 Chapter Introduction for a description of how these coefficients are produced.
Note that for computational efficiency reasons these coefficients are stored as DWTLVFR j/7 × DWTLVM j/7 × DWTLVN j/7 in C.
9:   NWL – INTEGERInput
On entry: the number of levels, nfwd, in the multi-level resolution to be performed.
Constraint: 1≤NWL≤lmax, where lmax is the value returned in NWLMAX (the maximum number of levels) by the call to the initialization routine C09ACF.
10:   DWTLVM NWL – INTEGER arrayOutput
On exit: the number of coefficients in the first dimension for each coefficient type at each level. DWTLVM i contains the number of coefficients in the first dimension (for each coefficient type computed) at the (nfwd-i+1)th level of resolution, for i=1,2,…,nfwd.
11:   DWTLVN NWL – INTEGER arrayOutput
On exit: the number of coefficients in the second dimension for each coefficient type at each level. DWTLVN i contains the number of coefficients in the second dimension (for each coefficient type computed) at the (nfwd-i+1)th level of resolution, for i=1,2,…,nfwd.
12:   DWTLVFR NWL – INTEGER arrayOutput
On exit: the number of coefficients in the third dimension for each coefficient type at each level. DWTLVFR i contains the number of coefficients in the third dimension (for each coefficient type computed) at the (nfwd-i+1)th level of resolution, for i=1,2,…,nfwd.
13:   ICOMM 260 – INTEGER arrayCommunication Array
On entry: contains details of the discrete wavelet transform and the problem dimension as setup in the call to the initialization routine C09ACF.
On exit: contains additional information on the computed transform.
14:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, FR=value.
Constraint: FR=value, the value of FR on initialization (see C09ACF).
On entry, M=value.
Constraint: M=value, the value of M on initialization (see C09ACF).
On entry, N=value.
Constraint: N=value, the value of N on initialization (see C09ACF).
IFAIL=2
On entry, LDA=value and M=value.
Constraint: LDA≥M.
On entry, SDA=value and N=value.
Constraint: SDA≥N.
IFAIL=3
On entry, LENC=value.
Constraint: LENC≥value, the total number of coefficents to be generated.
IFAIL=5
On entry, NWL=value.
Constraint: NWL≥1.
On entry, NWL=value and NWLMAX=value in C09ACF.
Constraint: NWL≤NWLMAX in C09ACF.
IFAIL=6
Either the communication array ICOMM has been corrupted or there has not been a prior call to the initialization routine C09ACF.
The initialization routine was called with WTRANS='S'.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

The accuracy of the wavelet transform depends only on the floating-point operations used in the convolution and downsampling and should thus be close to machine precision.

8 Parallelism and Performance

C09FCF is not threaded in any implementation.

9 Further Comments

The example program shows how the wavelet coefficients at each level can be extracted from the output array C. Denoising can be carried out by applying a thresholding operation to the detail coefficients at every level. If c ij is a detail coefficient then c^ij=c ij+σ ε ij and σ ε ij is the transformed noise term. If some threshold parameter α is chosen, a simple hard thresholding rule can be applied as
c- ij = 0, if ​ c^ij ≤ α c^ij , if ​ c^ij > α,
taking c-ij to be an approximation to the required detail coefficient without noise, c ij. The resulting coefficients can then be used as input to C09FDF in order to reconstruct the denoised signal. See Section 10 in C09FZF for a simple example of denoising.
See the references given in the introduction to this chapter for a more complete account of wavelet denoising and other applications.

10 Example

This example computes the three-dimensional multi-level discrete wavelet decomposition for 7×6×5 input data using the biorthogonal wavelet of order 1.1 (set WAVNAM='BIOR1.1' in C09ACF) with periodic end extension, prints a selected set of wavelet coefficients and then reconstructs and verifies that the reconstruction matches the original data.

10.1 Program Text

Program Text (c09fcfe.f90)

10.2 Program Data

Program Data (c09fcfe.d)

10.3 Program Results

Program Results (c09fcfe.r)

C09 Chapter Contents
C09 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


C09FDF : NAG Library, Mark 26

C09 Chapter Contents
C09 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

C09FDF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
10 Example

1 Purpose

C09FDF computes the inverse three-dimensional multi-level discrete wavelet transform (IDWT). This routine reconstructs data from (possibly filtered or otherwise manipulated) wavelet transform coefficients calculated by C09FCF from an original input array. The initialization routine C09ACF must be called first to set up the IDWT options.

2 Specification

SUBROUTINE C09FDF ( NWLINV, LENC, C, M, N, FR, B, LDB, SDB, ICOMM, IFAIL)
INTEGER | NWLINV, LENC, M, N, FR, LDB, SDB, ICOMM(260), IFAIL
REAL (KIND=nag_wp) | C(LENC), B(LDB,SDB,FR)

3 Description

C09FDF performs the inverse operation of C09FCF. That is, given a set of wavelet coefficients, computed up to level nfwd by C09FCF using a DWT as set up by the initialization routine C09ACF, on a real three-dimensional array, A, C09FDF will reconstruct A. The reconstructed array is referred to as B in the following since it will not be identical to A when the DWT coefficients have been filtered or otherwise manipulated prior to reconstruction. If the original input array is level 0, then it is possible to terminate reconstruction at a higher level by specifying fewer than the number of levels used in the call to C09FCF. This results in a partial reconstruction.

4 References

Wang Y, Che X and Ma S (2012) Nonlinear filtering based on 3D wavelet transform for MRI denoising URASIP Journal on Advances in Signal Processing 2012:40

5 Arguments

1:   NWLINV – INTEGERInput
On entry: the number of levels to be used in the inverse multi-level transform. The number of levels must be less than or equal to nfwd, which has the value of argument NWL as used in the computation of the wavelet coefficients using C09FCF. The data will be reconstructed to level NWL-NWLINV, where level 0 is the original input dataset provided to C09FCF.
Constraint: 1≤NWLINV≤NWL, where NWL is the value used in a preceding call to C09FCF.
2:   LENC – INTEGERInput
On entry: the dimension of the array C as declared in the (sub)program from which C09FDF is called.
Constraint: LENC≥nct, where nct is the total number of wavelet coefficients that correspond to a transform with NWLINV levels.
3:   C LENC – REAL (KIND=nag_wp) arrayInput
On entry: the coefficients of the multi-level discrete wavelet transform. This will normally be the result of some transformation on the coefficients computed by routine C09FCF.
Note that the coefficients in C may be extracted according to level and type into three-dimensional arrays using C09FYF, and inserted using C09FZF.
4:   M – INTEGERInput
On entry: the number of elements, m, in the first dimension of the reconstructed array B. For a full reconstruction of NWL levels, where NWL is as supplied to C09FCF, this must be the same as argument M used in a preceding call to C09FCF. For a partial reconstruction of NWLINV<NWL levels, this must be equal to DWTLVM NWLINV+1, as returned from C09FCF
5:   N – INTEGERInput
On entry: the number of elements, n, in the second dimension of the reconstructed array B. For a full reconstruction of NWL, levels, where NWL is as supplied to C09FCF, this must be the same as argument N used in a preceding call to C09FCF. For a partial reconstruction of NWLINV<NWL levels, this must be equal to DWTLVN NWLINV+1, as returned from C09FCF.
6:   FR – INTEGERInput
On entry: the number of elements, fr, in the third dimension of the reconstructed array B. For a full reconstruction of NWL levels, where NWL is as supplied to C09FCF, this must be the same as argument FR used in a preceding call to C09FCF. For a partial reconstruction of NWLINV<NWL levels, this must be equal to DWTLVFR NWLINV+1, as returned from C09FCF.
7:   B LDBSDBFR – REAL (KIND=nag_wp) arrayOutput
On exit: the m by n by fr reconstructed array, B, with B ijk stored in B ijk. The reconstruction is based on the input multi-level wavelet transform coefficients and the transform options supplied to the initialization routine C09ACF.
8:   LDB – INTEGERInput
On entry: the first dimension of the array B as declared in the (sub)program from which C09FDF is called.
Constraint: LDB≥M.
9:   SDB – INTEGERInput
On entry: the second dimension of the array B as declared in the (sub)program from which C09FDF is called.
Constraint: SDB≥N.
10:   ICOMM 260 – INTEGER arrayCommunication Array
On entry: contains details of the discrete wavelet transform and the problem dimension as setup in the call to the initialization routine C09ACF.
11:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, NWLINV=value.
Constraint: NWLINV≥1.
On entry, NWLINV=value and NWL=value where NWL is as used in the computation of the wavelet coefficients by a call to C09FCF.
Constraint: NWLINV≤NWL as used in the call to C09FCF.
IFAIL=2
On entry, LDB=value and M=value.
Constraint: LDB≥M.
On entry, SDB=value and N=value.
Constraint: SDB≥N.
IFAIL=3
On entry, LENC=value.
Constraint: LENC≥value, the number of wavelet coefficients required for a transform operating on NWLINV levels. If NWLINV=NWLMAX, the maximum number of levels as returned by the initial call to C09ACF, then LENC must be at least nct, the value returned in NWCT by the same call to C09ACF.
IFAIL=4
On entry, FR=value.
Constraint: FR≥value, the number of coefficients in the third dimension at the required level of reconstruction.
On entry, M=value.
Constraint: M≥value, the number of coefficients in the first dimension at the required level of reconstruction.
On entry, N=value.
Constraint: N≥value, the number of coefficients in the second dimension at the required level of reconstruction.
IFAIL=6
Either the communication array ICOMM has been corrupted or there has not been a prior call to the initialization routine C09ACF.
The initialization routine was called with WTRANS='S'.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

The accuracy of the wavelet transform depends only on the floating-point operations used in the convolution and downsampling and should thus be close to machine precision.

8 Parallelism and Performance

C09FDF is not threaded in any implementation.

9 Further Comments

None.

10 Example

See Section 10 in C09FCF.
C09 Chapter Contents
C09 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


C09FYF : NAG Library, Mark 26

C09 Chapter Contents
C09 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

C09FYF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
10 Example

1 Purpose

C09FYF extracts a selected set of discrete wavelet transform (DWT) coefficients from the full set of coefficients stored in compact form, as computed by C09FAF (single level three-dimensional DWT) or C09FCF (multi-level three-dimensional DWT).

2 Specification

SUBROUTINE C09FYF ( ILEV, CINDEX, LENC, C, D, LDD, SDD, ICOMM, IFAIL)
INTEGER | ILEV, CINDEX, LENC, LDD, SDD, ICOMM(260), IFAIL
REAL (KIND=nag_wp) | C(LENC), D(LDD,SDD,*)

3 Description

C09FYF is intended to be used after a call to either C09FAF (single level three-dimensional DWT) or C09FCF (multi-level three-dimensional DWT), either of which must be preceded by a call to C09ACF (three-dimensional wavelet filter initialization). Given an initial three-dimensional data set A, a prior call to C09FAF or C09FCF computes the approximation coefficients (at the highest requested level in the case of C09FCF) and seven sets of detail coefficients (at all levels in the case of C09FCF) and stores these in compact form in a one-dimensional array C. C09FYF can then extract either the approximation coefficients or one of the sets of detail coefficients (at one of the levels following C09FCF) into a three-dimensional data set stored in D.
If a multi-level DWT was performed by a prior call to C09FCF then the dimensions of the three-dimensional data stored in D depend on the level extracted and are available from the arrays DWTLVM, DWTLVN and DWTLVFR as returned by C09FCF which contain the first, second and third dimensions respectively.
If a single level DWT was performed by a prior call to C09FAF then the dimensions of the three-dimensional data stored in D can be determined from NWCT, NWCN and NWCFR as returned by the setup routine C09ACF.
See Section 2.1 in the C09 Chapter Introduction for a discussion of the three-dimensional DWT.

4 References

None.

5 Arguments

Note: the following notation is used in this section:
  • ncm is the number of wavelet coefficients in the first dimension. Following a call to C09FAF (i.e., when ILEV=0) this is equal to NWCT/8×NWCN×NWCFR as returned by C09ACF. Following a call to C09FCF transforming NWL levels, and when extracting at level ILEV>0, this is equal to DWTLVM NWL-ILEV+1.
  • ncn is the number of wavelet coefficients in the second dimension. Following a call to C09FAF (i.e., when ILEV=0) this is equal to NWCN as returned by C09ACF. Following a call to C09FCF transforming NWL levels, and when extracting at level ILEV>0, this is equal to DWTLVN NWL-ILEV+1.
  • ncfr is the number of wavelet coefficients in the third dimension. Following a call to C09FAF (i.e., when ILEV=0) this is equal to NWCFR as returned by C09ACF. Following a call to C09FCF transforming NWL levels, and when extracting at level ILEV>0, this is equal to DWTLVFR NWL-ILEV+1
1:   ILEV – INTEGERInput
On entry: the level at which coefficients are to be extracted.
If ILEV=0, it is assumed that the coefficient array C was produced by a preceding call to the single level routine C09FAF.
If ILEV>0, it is assumed that the coefficient array C was produced by a preceding call to the multi-level routine C09FCF.
Constraints:
  • ILEV=0 (following a call to C09FAF);
  • 0≤ILEV≤NWL, where NWL is as used in a preceding call to C09FCF;
  • if CINDEX=0, ILEV=NWL (following a call to C09FCF).
2:   CINDEX – INTEGERInput
On entry: identifies which coefficients to extract. The coefficients are identified as follows:
CINDEX=0
The approximation coefficients, produced by application of the low pass filter over columns, rows and frames of A (LLL). After a call to the multi-level transform routine C09FCF (which implies that ILEV>0) the approximation coefficients are available only for ILEV=NWL, where NWL is the value used in a preceding call to C09FCF.
CINDEX=1
The detail coefficients produced by applying the low pass filter over columns and rows of A and the high pass filter over frames (LLH).
CINDEX=2
The detail coefficients produced by applying the low pass filter over columns, high pass filter over rows and low pass filter over frames of A (LHL).
CINDEX=3
The detail coefficients produced by applying the low pass filter over columns of A and high pass filter over rows and frames (LHH).
CINDEX=4
The detail coefficients produced by applying the high pass filter over columns of A and low pass filter over rows and frames (HLL).
CINDEX=5
The detail coefficients produced by applying the high pass filter over columns, low pass filter over rows and high pass filter over frames of A (HLH).
CINDEX=6
The detail coefficients produced by applying the high pass filter over columns and rows of A and the low pass filter over frames (HHL).
CINDEX=7
The detail coefficients produced by applying the high pass filter over columns, rows and frames of A (HHH).
Constraints:
  • if ILEV=0, 0≤CINDEX≤7;
  • if ILEV=NWL, following a call to C09FCF transforming NWL levels, 0≤CINDEX≤7;
  • otherwise 1≤CINDEX≤7.
3:   LENC – INTEGERInput
On entry: the dimension of the array C as declared in the (sub)program from which C09FYF is called.
Constraint: LENC must be unchanged from the value used in the preceding call to either C09FAF or C09FCF..
4:   C LENC – REAL (KIND=nag_wp) arrayInput
On entry: DWT coefficients, as computed by C09FAF or C09FCF.
5:   D LDDSDD* – REAL (KIND=nag_wp) arrayOutput
Note: the last dimension of the array D must be at least ncfr.
On exit: the requested coefficients.
If the DWT coefficients were computed by C09FAF then
  • if CINDEX=0, the approximation coefficients are stored in D ijk, for i=1,2,…,ncm, j=1,2,…,ncn and k=1,2,…,ncfr;
  • if 1≤CINDEX≤7, the detail coefficients, as indicated by CINDEX, are stored in D ijk, for i=1,2,…,ncm, j=1,2,…,ncn and k=1,2,…,ncfr.
If the DWT coefficients were computed by C09FCF then
  • if CINDEX=0 and ILEV=NWL, the approximation coefficients are stored in D ijk, for i=1,2,…,ncm, j=1,2,…,ncn and k=1,2,…,ncfr;
  • if 1≤CINDEX≤7, the detail coefficients, as indicated by CINDEX, for level ILEV are stored in D ijk, for i=1,2,…,ncm, j=1,2,…,ncn and k=1,2,…,ncfr.
6:   LDD – INTEGERInput
On entry: the first dimension of the array D as declared in the (sub)program from which C09FYF is called.
Constraint: LDD≥ncm.
7:   SDD – INTEGERInput
On entry: the second dimension of the array D as declared in the (sub)program from which C09FYF is called.
Constraint: SDD≥ncn.
8:   ICOMM 260 – INTEGER arrayCommunication Array
On entry: contains details of the discrete wavelet transform and the problem dimension as setup in the call to the initialization routine C09ACF.
9:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, ILEV=value.
Constraint: ILEV=0 following a call to the single level routine C09FAF.
On entry, ILEV=value.
Constraint: ILEV>0 following a call to the multi-level routine C09FCF.
On entry, ILEV=value and NWL=value.
Constraint: ILEV≤NWL, where NWL is the number of levels used in the call to C09FCF.
IFAIL=2
On entry, CINDEX=value.
Constraint: CINDEX≤7.
On entry, CINDEX=value.
Constraint: CINDEX≥0.
IFAIL=3
On entry, LENC=value and nct=value.
Constraint: LENC≥nct, where nct is the number of DWT coefficients computed in the preceding call to C09FAF.
On entry, LENC=value and nct=value.
Constraint: LENC≥nct, where nct is the number of DWT coefficients computed in the preceding call to C09FCF.
IFAIL=4
On entry, LDD=value and ncm=value.
Constraint: LDD≥ncm, where ncm is the number of DWT coefficients in the first dimension at the selected level ILEV.
On entry, LDD=value and ncm=value.
Constraint: LDD≥ncm, where ncm is the number of DWT coefficients in the first dimension following the single level transform.
On entry, SDD=value and ncn=value.
Constraint: SDD≥ncn, where ncn is the number of DWT coefficients in the second dimension at the selected level ILEV.
On entry, SDD=value and ncn=value.
Constraint: SDD≥ncn, where ncn is the number of DWT coefficients in the second dimension following the single level transform.
IFAIL=5
On entry, ILEV=value and NWL=value, but CINDEX=0.
Constraint: CINDEX>0 when ILEV<NWL in the preceding call to C09FCF.
IFAIL=6
Either the initialization routine has not been called first or ICOMM has been corrupted.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

Not applicable.

8 Parallelism and Performance

C09FYF is not threaded in any implementation.

9 Further Comments

None.

10 Example

See Section 10 in C09ACF, C09FAF, C09FCF and C09FZF.
C09 Chapter Contents
C09 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


C09FZF : NAG Library, Mark 26

C09 Chapter Contents
C09 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

C09FZF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

C09FZF inserts a selected set of three-dimensional discrete wavelet transform (DWT) coefficients into the full set of coefficients stored in compact form, which may be later used as input to the reconstruction routines C09FBF or C09FDF.

2 Specification

SUBROUTINE C09FZF ( ILEV, CINDEX, LENC, C, D, LDD, SDD, ICOMM, IFAIL)
INTEGER | ILEV, CINDEX, LENC, LDD, SDD, ICOMM(260), IFAIL
REAL (KIND=nag_wp) | C(LENC), D(LDD,SDD,*)

3 Description

C09FZF inserts a selected set of three-dimensional DWT coefficients into the full set of coefficients stored in compact form in a one-dimensional array C. It is required that C09FZF is preceded by a call to the initialization routine C09ACF and either the forwards transform routine C09FAF or multi-level forwards transform routine C09FCF.
Given an initial three-dimensional data set A, a prior call to C09FAF or C09FCF computes the approximation coefficients (at the highest requested level in the case of C09FCF) and, seven sets of detail coefficients (at all levels in the case of C09FCF) and stores these in compact form in a one-dimensional array C. C09FYF can then extract either the approximation coefficients or one of the sets of detail coefficients (at one of the levels following C09FCF) into a three-dimensional array, D. Following some calculation on this set of coefficients (for example, denoising), the updated coefficients in D are inserted back into the full set C using C09FZF. Several extractions and insertions may be performed. C09FBF or C09FDF can then be used to reconstruct a manipulated data set A~. The dimensions of D depend on the level extracted and are available from either: the arrays DWTLVM, DWTLVN and DWTLVFR as returned by C09FCF if this was called first; or, otherwise from NWCT, NWCN and NWCFR as returned by C09ACF. See Section 2.1 in the C09 Chapter Introduction for a discussion of the three-dimensional DWT.

4 References

None.

5 Arguments

Note: the following notation is used in this section:
  • ncm is the number of wavelet coefficients in the first dimension. Following a call to C09FAF (i.e., when ILEV=0) this is equal to NWCT/8×NWCN×NWCFR as returned by C09ACF. Following a call to C09FCF transforming NWL levels, and when inserting at level ILEV>0, this is equal to DWTLVM NWL-ILEV+1.
  • ncn is the number of wavelet coefficients in the second dimension. Following a call to C09FAF (i.e., when ILEV=0) this is equal to NWCN as returned by C09ACF. Following a call to C09FCF transforming NWL levels, and when inserting at level ILEV>0, this is equal to DWTLVN NWL-ILEV+1.
  • ncfr is the number of wavelet coefficients in the third dimension. Following a call to C09FAF (i.e., when ILEV=0) this is equal to NWCFR as returned by C09ACF. Following a call to C09FCF transforming NWL levels, and when inserting at level ILEV>0, this is equal to DWTLVFR NWL-ILEV+1
1:   ILEV – INTEGERInput
On entry: the level at which coefficients are to be inserted.
If ILEV=0, it is assumed that the coefficient array C was produced by a preceding call to the single level routine C09FAF.
If ILEV>0, it is assumed that the coefficient array C was produced by a preceding call to the multi-level routine C09FCF.
Constraints:
  • ILEV=0 (following a call to C09FAF);
  • 0≤ILEV≤NWL, where NWL is as used in a preceding call to C09FCF;
  • if CINDEX=0, ILEV=NWL (following a call to C09FCF).
2:   CINDEX – INTEGERInput
On entry: identifies which coefficients to insert. The coefficients are identified as follows:
CINDEX=0
The approximation coefficients, produced by application of the low pass filter over columns, rows and frames of A (LLL). After a call to the multi-level transform routine C09FCF (which implies that ILEV>0) the approximation coefficients are present only for ILEV=NWL, where NWL is the value used in a preceding call to C09FCF.
CINDEX=1
The detail coefficients produced by applying the low pass filter over columns and rows of A and the high pass filter over frames (LLH).
CINDEX=2
The detail coefficients produced by applying the low pass filter over columns, high pass filter over rows and low pass filter over frames of A (LHL).
CINDEX=3
The detail coefficients produced by applying the low pass filter over columns of A and high pass filter over rows and frames (LHH).
CINDEX=4
The detail coefficients produced by applying the high pass filter over columns of A and low pass filter over rows and frames (HLL).
CINDEX=5
The detail coefficients produced by applying the high pass filter over columns, low pass filter over rows and high pass filter over frames of A (HLH).
CINDEX=6
The detail coefficients produced by applying the high pass filter over columns and rows of A and the low pass filter over frames (HHL).
CINDEX=7
The detail coefficients produced by applying the high pass filter over columns, rows and frames of A (HHH).
Constraints:
  • if ILEV=0, 0≤CINDEX≤7;
  • if ILEV=NWL, following a call to C09FCF transforming NWL levels, 0≤CINDEX≤7;
  • otherwise 1≤CINDEX≤7.
3:   LENC – INTEGERInput
On entry: the dimension of the array C as declared in the (sub)program from which C09FZF is called.
Constraint: LENC must be unchanged from the value used in the preceding call to either C09FAF or C09FCF..
4:   C LENC – REAL (KIND=nag_wp) arrayInput/Output
On entry: contains the DWT coefficients inserted by previous calls to C09FZF, or computed by a previous call to either C09FAF or C09FCF.
On exit: contains the same DWT coefficients provided on entry except for those identified by ILEV and CINDEX, which are updated with the values supplied in D, inserted into the correct locations as expected by one of the reconstruction routines C09FBF (if C09FAF was called previously) or C09FDF (if C09FCF was called previously).
5:   D LDDSDD* – REAL (KIND=nag_wp) arrayInput
Note: the last dimension of the array D must be at least ncfr.
On entry: the coefficients to be inserted.
If the DWT coefficients were computed by C09FAF then
  • if CINDEX=0, the approximation coefficients must be stored in D ijk, for i=1,2,…,ncm, j=1,2,…,ncn and k=1,2,…,ncfr;
  • if 1≤CINDEX≤7, the detail coefficients, as indicated by CINDEX, must be stored in D ijk, for i=1,2,…,ncm, j=1,2,…,ncn and k=1,2,…,ncfr.
If the DWT coefficients were computed by C09FCF then
  • if CINDEX=0 and ILEV=NWL, the approximation coefficients must be stored in D ijk, for i=1,2,…,ncm, j=1,2,…,ncn and k=1,2,…,ncfr;
  • if 1≤CINDEX≤7, the detail coefficients, as indicated by CINDEX, for level ILEV must be stored in D ijk, for i=1,2,…,ncm, j=1,2,…,ncn and k=1,2,…,ncfr.
6:   LDD – INTEGERInput
On entry: the first dimension of the array D as declared in the (sub)program from which C09FZF is called.
Constraint: LDD>ncm.
7:   SDD – INTEGERInput
On entry: the second dimension of the array D as declared in the (sub)program from which C09FZF is called.
Constraint: SDD>ncn.
8:   ICOMM 260 – INTEGER arrayCommunication Array
On entry: contains details of the discrete wavelet transform and the problem dimension as setup in the call to the initialization routine C09ACF.
9:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, ILEV=value.
Constraint: ILEV=0 following a call to the single level routine C09FAF.
On entry, ILEV=value.
Constraint: ILEV>0 following a call to the multi-level routine C09FCF.
On entry, ILEV=value and NWL=value.
Constraint: ILEV≤NWL, where NWL is the number of levels used in the call to C09FCF.
IFAIL=2
On entry, CINDEX=value.
Constraint: CINDEX≤7.
On entry, CINDEX=value.
Constraint: CINDEX≥0.
IFAIL=3
On entry, LENC=value and nct=value.
Constraint: LENC≥nct, where nct is the number of DWT coefficients computed in a previous call to C09FAF.
On entry, LENC=value and nct=value.
Constraint: LENC≥nct, where nct is the number of DWT coefficients computed in a previous call to C09FCF.
IFAIL=4
On entry, LDD=value and ncm=value.
Constraint: LDD≥ncm, where ncm is the number of DWT coefficients in the first dimension at the selected level ILEV.
On entry, LDD=value and ncm=value.
Constraint: LDD≥ncm, where ncm is the number of DWT coefficients in the first dimension following the single level transform.
On entry, SDD=value and ncn=value.
Constraint: SDD≥ncn, where ncn is the number of DWT coefficients in the second dimension at the selected level ILEV.
On entry, SDD=value and ncn=value.
Constraint: SDD≥ncn, where ncn is the number of DWT coefficients in the second dimension following the single level transform.
IFAIL=5
On entry, ILEV=value and NWL=value, but CINDEX=0.
Constraint: CINDEX>0 when ILEV<NWL in the preceding call to C09FCF.
IFAIL=6
Either the initialization routine has not been called first or ICOMM has been corrupted.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

Not applicable.

8 Parallelism and Performance

C09FZF is not threaded in any implementation.

9 Further Comments

None.

10 Example

The following example demonstrates using the coefficient extraction and insertion routines in order to apply denoising using a thresholding operation. The original input data has artificial noise introduced to it, taken from a normal random number distribution. Reconstruction then takes place on both the noisy data and denoised data. The Mean Square Errors (MSE) of the two reconstructions are printed along with the reconstruction of the denoised data. The MSE of the denoised reconstruction is less than that of the noisy reconstruction.

10.1 Program Text

Program Text (c09fzfe.f90)

10.2 Program Data

Program Data (c09fzfe.d)

10.3 Program Results

Program Results (c09fzfe.r)

C09 Chapter Contents
C09 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


C09 Chapter Introduction : NAG Library, Mark 26

C09 Chapter Contents
NAG Library Manual

NAG Library Chapter Introduction

C09 – Wavelet Transforms

▸▿ Contents

1 Scope of the Chapter
▸▿ 2 Background to the Problems
2.1 Multiresolution and higher dimensional DWT
3 Recommendations on Choice and Use of Available Routines
4 Functionality Index
5 Auxiliary Routines Associated with Library Routine Arguments
6 Routines Withdrawn or Scheduled for Withdrawal
7 References

1 Scope of the Chapter

This chapter is concerned with the analysis of datasets (or functions or operators) in terms of frequency and scale components using wavelet transforms. Wavelet transforms have been applied in many fields from time series analysis to image processing and the localization in either frequency or scale that they provide is useful for data compression or denoising. In general the standard wavelet transform uses dilation and scaling of a chosen function, ψ t, (called the mother wavelet) such that
ψ a,b t = 1 a ψ t-b a
where a gives the scaling and b determines the translation. Wavelet methods can be divided into continuous transforms and discrete transforms. In the continuous case, the pair a and b are real numbers with a>0. For the discrete transform, a and b can be chosen as a=2-j, b=k 2-j for integers j, k
ψ j,k t = 2 j/2 ψ 2 j t-k .
The continuous real valued, one-dimensional wavelet transform (CWT) is included in this chapter. The discrete wavelet transform (DWT) at a single level together with its inverse and the multi-level DWT with inverse are also provided for one, two and three dimensions. The Maximal Overlap DWT (MODWT) together with its inverse and the multi-level MODWT with inverse are provided for one dimension. The choice of wavelet for CWT includes the Morlet wavelet and derivatives of a Gaussian while the DWT and MODWT offer the orthogonal wavelets of Daubechies and a selection of biorthogonal wavelets.

2 Background to the Problems

The CWT computes a time-frequency analysis of a signal, x t, which can yield high localization in time of the high frequency features present. It is defined as
C a,b = ∫ -∞ +∞ 1 a ψ * t-b a x t dt
where ψ* denotes the complex conjugate of the wavelet function, a is the dilation parameter and b is the localization parameter. (Currently only the real valued transform is offered.)
The discrete wavelet transform (DWT) is defined by a mother wavelet function ψ t, and a related scaling function, ϕ t, where
ϕ t = ∑k gk 2 ϕ 2 t-k . ψ t = ∑k hk 2 ϕ 2 t-k .
These in turn are represented as a pair of filters with finite support. They can be viewed as a high pass filter, hk, for k=1,2,…,m, paired with a low pass filter, gk, for k=1,2,…,n. The DWT at a single level is carried out by convolution of the filter with the input data, followed by downsampling by two. The MODWT at a single level is carried out by convolution of the filter with the input data only; no downsampling is used in the MODWT. In order to obtain exact reconstruction of the original input these filters must satisfy certain conditions. For orthogonal wavelets, n=m, these are,
∑ k=1 m hk = 0 , ∑ k=1 m h k 2 = 1 , ∑ k=-∞ ∞ hk h k+2 l = 0 , ∑ k=1 m gk = 2 , ∑ k=1 m gk 2 = 1 , ∑ k=-∞ ∞ gk g k+2 l = 0 .
for all nonzero integers, l.
The DWT reconstruction algorithm convolves the inverse filters with the wavelet coefficients previously computed together with upsampling and summation to return to the original input. The MODWT reconstructs in the same way, except without upsampling. For orthogonal wavelets the inverse filters are the same as those for the forward DWT.
In the simplest case, the Haar wavelet, the nonzero filter coefficients are
h = -1 2 , 1 2 g = 1 2,1 2
while for the Daubechies wavelet with two vanishing moments and four nonzero coefficients, the filter coefficients are
h = -1+3 4 2 , 3+3 4 2 , -3+3 4 2 , 1-3 4 2 g = 1-3 4 2 , 3-3 4 2 , 3+3 4 2 , 1+3 4 2
In the orthogonal case the same filters are used for both decomposition and reconstruction.
Relaxing the orthogonality requirement allows for biorthogonal wavelets which consist of two dual wavelet bases. For example, the biorthogonal 2.2 filters are,
h = 2 14,-12,14 , g = 2 -18,14,34,14,-18 h′ = 2 18,14,-34,14,18 g′ = 2 14,12,14 .
Note that there are several possible interpretations of orthogonal and biorthorgonal wavelet filters which satisfy the requirements. These differ in the sign of the coefficients and the ordering of the filters.
In order to obtain exact reconstruction when applying the DWT or MODWT and its inverse to a finite dataset, say xt, for t=1,2,…,N, some method of extending the input at its end is required. Several methods which are in general use are: periodic extension, half-point symmetric extension, whole-point symmetric extension and zero end extension where the added data points are taken to be zero. The two types of symmetric end extension reflect the given data values from the end points for whole-point extension or else by repeating the end points and reflecting from points halfway between the end point and its repeat for half-point extension. Each of these end extension methods are available for the DWT. Only the periodic end extension is currently available for the MODWT.

2.1 Multiresolution and higher dimensional DWT

Rather than simply applying the wavelet transform at a single level the process is commonly repeated to give a multiresolution analysis. For the DWT, multiresolution is implemented as the pyramid (or cascade) algorithm. Applying the DWT at a given level, L, the detail coefficients (which are the output from the high pass filter) are stored while the approximation coefficients resulting from convolution with the low pass filter are passed to the next level and the processs is repeated. When the length of the initial data input is an array of length N=2 J, for some integer J (and assuming that the dataset is extended by periodic repetition) this can be continued until, at level J, there is a single detail coefficient from the high pass filter. The final coefficient from the action of the low pass filter is also stored. The result is an array of coefficients of the same length, N, as the input.
For the multi-level MODWT it is, in theory, possible to continue for any number of levels. However, in practice it is common to not exceed log 2 N levels in order to avoid scales that exceed the length of the input data, N. This restriction is enforced for the one-dimensional mutli-level MODWT routine in this chapter.
For two-dimensional data sets the DWT is computed as a series of one-dimensional DWTs, first over columns of the input data, and then over rows of the intermediate result. This produces four types of output coefficients: one set of approximation coefficients and three types of detail coefficients, containing information about the horizontal, vertical and diagonal components of the input data. The approximation coefficients are the result of applying convolution and downsampling with the low pass filter over both columns and rows; the horizontal detail coefficients are the result of applying convolution and downsampling with the high pass filter over columns and then the low pass filter over rows; the vertical detail coefficients are the result of applying convolution and downsampling with the low pass filter over columns and the high pass filter over rows; and the diagonal detail coefficients are the result of applying convolution and downsampling with the high pass filter over both columns and rows. An example of the single level decomposition of an image performed using C09EAF is given in Figure 1.
Figure 1: The original image (top, 996×1332 pixels) is transformed using routine C09EAF into the four coefficient (approximation, horizontal, vertical and diagonal) matrices (501×669) displayed below the original. The transformation was performed using the Daubechies wavelet with four vanishing moments and half-point end extension. Note that the approximation coefficients are a very close representation of the original image, while the horizontal, vertical and diagonal features of the image are visible in the respective coefficient matrices.
Similarly, for three-dimensional data sets the DWT is also computed as a series of three one-dimensional DWTs, first over columns of the input data, and then over rows of the intermediate result and finally over frames of the second intermediate result. This produces eight types of output coefficients: one set of approximation coefficients (labelled LLL since the low pass filter is applied over columns, rows and frames) and seven types of detail coefficients, labelled similarly according to whether the low pass (L) or high pass filter (H) is applied in each of the three dimensions. For the three-dimensional DWT this process is represented by Figure 2.
As in the one-dimensional case, the multi-level DWT in two and three dimensions is also implemented as the pyramid (or cascade) algorithm, where at a given level, L, all detail coefficients are stored, while the approximation coefficients are passed as input to the next level.
Figure 2: The three-dimensional DWT filter bank. The original input is downsampled by 2 and the high pass (H) and low pass (L) filters are applied along columns. This process is repeated along the rows and then frames to produce 8 sets of output coefficients – one set of approximation coefficients and 7 sets of detail coefficients.

3 Recommendations on Choice and Use of Available Routines

The one-dimensional real valued continuous wavelet transform is provided by C09BAF. It is useful for resolving discontinuities and high frequency features in a signal. It is a redundant representation of the input data containing repeated information and the set of coefficients produced as output is larger than the input data set.
The one-dimensional discrete wavelet transform at a single level is performed by C09CAF. The inverse or reconstruction is carried out by C09CBF.
The one-dimensional multi-level discrete wavelet transform is computed by C09CCF and the inverse or reconstruction is given by C09CDF. The discrete wavelet transform is widely used for image processing and data compression.
The one-dimensional maximal overlap discrete wavelet transform at a single level is performed by C09DAF. The inverse or reconstruction is carried out by C09DBF.
The one-dimensional multi-level maximal overlap discrete wavelet transform is performed by C09DCF. The inverse or reconstruction routine is C09DDF. The maximal overlap discrete wavelet transform overcomes the lack of translation invariance inherent in the DWT, and thus there are advantages to using the MODWT when carrying out multiresolution analysis.
C09AAF is provided to determine some of the input arguments for the one-dimensional discrete wavelet transform and maximal overlap discrete wavelet transform routines and must be called before the one-dimensional transform routines.
The two-dimensional discrete wavelet transform at a single level is performed by C09EAF. The inverse or reconstruction is carried out by C09EBF.
The two-dimensional multi-level discrete wavelet transform is computed by C09ECF and the inverse or reconstruction is given by C09EDF.
C09ECF and C09EDF use a one-dimensional array to store the discrete wavelet transform coefficients. These may be extracted into two-dimensional arrays using C09EYF. A complementary routine C09EZF allows for the insertion of coefficients held in a two-dimensional array back into the one-dimensional array.
C09ABF is provided to determine some of the input arguments for the two-dimensional discrete wavelet transform routines and must be called before the two-dimensional transform routines.
The three-dimensional multi-level discrete wavelet transform is computed by C09FCF and the inverse or reconstruction is given by C09FDF.
C09FAF, C09FBF, C09FCF and C09FDF use a one-dimensional array to store the discrete wavelet transform coefficients. These may be extracted into three-dimensional arrays using C09FYF. A complementary routine C09FZF allows for the insertion of coefficients held in a three-dimensional array back into the one-dimensional array.
C09ACF is provided to determine some of the input arguments for the three-dimensional discrete wavelet transform routines and must be called before the three-dimensional transform routines.

4 Functionality Index

One-dimensional
continuous
real wavelet transform C09BAF
discrete
multi-level
inverse wavelet transform C09CDF
wavelet transform C09CCF
single level
inverse wavelet transform C09CBF
wavelet transform C09CAF
maximal overlap discrete
multi-level
inverse wavelet transform C09DDF
wavelet transform C09DCF
single level
inverse wavelet transform C09DBF
wavelet transform C09DAF
wavelet filter details C09AAF
Three-dimensional
coefficient extraction C09FYF
coefficient insertion C09FZF
discrete
multi-level
inverse wavelet transform C09FDF
wavelet transform C09FCF
single level
inverse wavelet transform C09FBF
wavelet transform C09FAF
wavelet filter details C09ACF
Two-dimensional
coefficient extraction C09EYF
coefficient insertion C09EZF
discrete
multi-level
inverse wavelet transform C09EDF
wavelet transform C09ECF
single level
inverse wavelet transform C09EBF
wavelet transform C09EAF
wavelet filter details C09ABF

5 Auxiliary Routines Associated with Library Routine Arguments

None.

6 Routines Withdrawn or Scheduled for Withdrawal

None.

7 References

Daubechies I (1992) Ten Lectures on Wavelets SIAM, Philadelphia
Mallat S G (1998) A Wavelet Tour of Signal Processing Academic Press
Percival D B and Walden A T (2000) Wavelet Methods for Time Series Analysis Cambridge University Press
Strang G and Nguyen T (1996) Wavelets and Filter Banks Wellesley-Cambridge Press
Vidakovic B (1999) Statistical Modeling by Wavelets John Wiley and Sons Inc.
Wickerhauser M V (1994) Adapted Wavelet Analysis from Theory to Software A K Peters Ltd
C09 Chapter Contents
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


D01AHF : NAG Library, Mark 26

D01 Chapter Contents
D01 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

D01AHF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

D01AHF computes a definite integral over a finite range to a specified relative accuracy using a method described by Patterson.

2 Specification

FUNCTION D01AHF ( A, B, EPSR, NPTS, RELERR, F, NLIMIT, IFAIL)
REAL (KIND=nag_wp) D01AHF
INTEGER | NPTS, NLIMIT, IFAIL
REAL (KIND=nag_wp) | A, B, EPSR, RELERR, F
EXTERNAL | F

3 Description

D01AHF computes a definite integral of the form
∫ab f x dx.
The method uses as its basis a family of interlacing high precision rules (see Patterson (1968)) using 1, 3, 7, 15, 31, 63, 127 and 255 nodes. Initially the family is applied in sequence to the integrand. When two successive rules differ relatively by less than the required relative accuracy, the last rule used is taken as the value of the integral and the operation is regarded as successful. If all rules in the family have been applied unsuccessfully, subdivision is invoked. The subdivision strategy is as follows. The interval under scrutiny is divided into two sub-intervals (not always equal). The basic family is then applied to the first sub-interval. If the required accuracy is not obtained, the interval is stored for future examination (see IFAIL=2) and the second sub-interval is examined. Should the basic family again be unsuccessful, then the sub-interval is further subdivided and the whole process repeated. Successful integrations are accumulated as the partial value of the integral. When all possible successful integrations have been completed, those previously unsuccessful sub-intervals placed in store are examined.
A large number of refinements are incorporated to improve the performance. Some of these are:
(a) | The rate of convergence of the basic family is monitored and used to make a decision to abort and subdivide before the full sequence has been applied.
(b) | The ε-algorithm is applied to the basic results in an attempt to increase the convergence rate. See Wynn (1956).
(c) | An attempt is made to detect sharp end point peaks and singularities in each sub-interval and to apply appropriate transformations to smooth the integrand. This consideration is also used to select interval sizes in the subdivision process.
(d) | The relative accuracy sought in each sub-interval is adjusted in accordance with its likely contribution to the total integral.
(e) | Random transformations of the integrand are applied to improve reliability in some instances.

4 References

Patterson T N L (1968) The Optimum addition of points to quadrature formulae Math. Comput. 22 847–856
Wynn P (1956) On a device for computing the em Sn transformation Math. Tables Aids Comput. 10 91–96

5 Arguments

1:   A – REAL (KIND=nag_wp)Input
On entry: a, the lower limit of integration.
2:   B – REAL (KIND=nag_wp)Input
On entry: b, the upper limit of integration. It is not necessary that a<b.
3:   EPSR – REAL (KIND=nag_wp)Input
On entry: the relative accuracy required.
Constraint: EPSR>0.0.
4:   NPTS – INTEGEROutput
On exit: the number of function evaluations used in the calculation of the integral.
5:   RELERR – REAL (KIND=nag_wp)Output
On exit: a rough estimate of the relative error achieved.
6:   F – REAL (KIND=nag_wp) FUNCTION, supplied by the user.External Procedure
F must return the value of the integrand f at a given point.
The specification of F is:
FUNCTION F ( X)
REAL (KIND=nag_wp) F
REAL (KIND=nag_wp) X
1:   X – REAL (KIND=nag_wp)Input
On entry: the point at which the integrand f must be evaluated.
F must either be a module subprogram USEd by, or declared as EXTERNAL in, the (sub)program from which D01AHF is called. Arguments denoted as Input must not be changed by this procedure.
7:   NLIMIT – INTEGERInput
On entry: a limit to the number of function evaluations. If NLIMIT≤0, the routine uses a default limit of 10000.
8:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, because for this routine the values of the output arguments may be useful even if IFAIL≠0 on exit, the recommended value is -1. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Note: D01AHF may return useful information for one or more of the following detected errors or warnings.
Errors or warnings detected by the routine:
IFAIL=1
The integral has not converged to the accuracy requested. It may be worthwhile to try increasing NLIMIT.
IFAIL=2
Too many unsuccessful levels of subdivision have been invoked.
IFAIL=3
On entry, EPSR≤0.0.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.
When IFAIL=1 or 2 a result may be obtained by continuing without further subdivision, but this is likely to be inaccurate.

7 Accuracy

The relative accuracy required is specified by you in the variable EPSR. The routine will terminate whenever the relative accuracy specified by EPSR is judged to have been reached.
If on exit, IFAIL=0, then it is most likely that the result is correct to the specified accuracy. If, on exit, IFAIL=1 or 2, then it is likely that the specified accuracy has not been reached.
RELERR is a rough estimate of the relative error achieved. It is a by-product of the computation and is not used to effect the termination of the routine. The outcome of the integration must be judged by the value of IFAIL.

8 Parallelism and Performance

D01AHF is not threaded in any implementation.

9 Further Comments

The time taken by D01AHF depends on the complexity of the integrand and the accuracy required.

10 Example

This example evaluates the integral to a requested relative accuracy of 10-5
∫01 4 1+x 2 dx=π.

10.1 Program Text

Program Text (d01ahfe.f90)

10.2 Program Data

Program Data (d01ahfe.d)

10.3 Program Results

Program Results (d01ahfe.r)

D01 Chapter Contents
D01 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


D01AJF : NAG Library, Mark 26

D01 Chapter Contents
D01 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

D01AJF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

D01AJF is a general purpose integrator which calculates an approximation to the integral of a function f x over a finite interval a,b:
I= ∫ab f x dx .

2 Specification

SUBROUTINE D01AJF ( F, A, B, EPSABS, EPSREL, RESULT, ABSERR, W, LW, IW, LIW, IFAIL)
INTEGER | LW, IW(LIW), LIW, IFAIL
REAL (KIND=nag_wp) | F, A, B, EPSABS, EPSREL, RESULT, ABSERR, W(LW)
EXTERNAL | F

3 Description

D01AJF is based on the QUADPACK routine QAGS (see Piessens et al. (1983)). It is an adaptive routine, using the Gauss 10-point and Kronrod 21-point rules. The algorithm, described in de Doncker (1978), incorporates a global acceptance criterion (as defined by Malcolm and Simpson (1976)) together with the ε-algorithm (see Wynn (1956)) to perform extrapolation. The local error estimation is described in Piessens et al. (1983).
The routine is suitable as a general purpose integrator, and can be used when the integrand has singularities, especially when these are of algebraic or logarithmic type.
D01AJF requires you to supply a function to evaluate the integrand at a single point.
The routine D01ATF uses an identical algorithm but requires you to supply a subroutine to evaluate the integrand at an array of points. Therefore D01ATF may be more efficient for some problem types and some machine architectures.

4 References

de Doncker E (1978) An adaptive extrapolation algorithm for automatic integration ACM SIGNUM Newsl. 13(2) 12–18
Malcolm M A and Simpson R B (1976) Local versus global strategies for adaptive quadrature ACM Trans. Math. Software 1 129–146
Piessens R, de Doncker–Kapenga E, Überhuber C and Kahaner D (1983) QUADPACK, A Subroutine Package for Automatic Integration Springer–Verlag
Wynn P (1956) On a device for computing the em Sn transformation Math. Tables Aids Comput. 10 91–96

5 Arguments

1:   F – REAL (KIND=nag_wp) FUNCTION, supplied by the user.External Procedure
F must return the value of the integrand f at a given point.
The specification of F is:
FUNCTION F ( X)
REAL (KIND=nag_wp) F
REAL (KIND=nag_wp) X
1:   X – REAL (KIND=nag_wp)Input
On entry: the point at which the integrand f must be evaluated.
F must either be a module subprogram USEd by, or declared as EXTERNAL in, the (sub)program from which D01AJF is called. Arguments denoted as Input must not be changed by this procedure.
2:   A – REAL (KIND=nag_wp)Input
On entry: a, the lower limit of integration.
3:   B – REAL (KIND=nag_wp)Input
On entry: b, the upper limit of integration. It is not necessary that a<b.
4:   EPSABS – REAL (KIND=nag_wp)Input
On entry: the absolute accuracy required. If EPSABS is negative, the absolute value is used. See Section 7.
5:   EPSREL – REAL (KIND=nag_wp)Input
On entry: the relative accuracy required. If EPSREL is negative, the absolute value is used. See Section 7.
6:   RESULT – REAL (KIND=nag_wp)Output
On exit: the approximation to the integral I.
7:   ABSERR – REAL (KIND=nag_wp)Output
On exit: an estimate of the modulus of the absolute error, which should be an upper bound for I-RESULT.
8:   W LW – REAL (KIND=nag_wp) arrayOutput
On exit: details of the computation see Section 9 for more information.
9:   LW – INTEGERInput
On entry: the dimension of the array W as declared in the (sub)program from which D01AJF is called. The value of LW (together with that of LIW) imposes a bound on the number of sub-intervals into which the interval of integration may be divided by the routine. The number of sub-intervals cannot exceed LW/4. The more difficult the integrand, the larger LW should be.
Suggested value: LW=800 to 2000 is adequate for most problems.
Constraint: LW≥4.
10:   IW LIW – INTEGER arrayOutput
On exit: IW 1 contains the actual number of sub-intervals used. The rest of the array is used as workspace.
11:   LIW – INTEGERInput
On entry: the dimension of the array IW as declared in the (sub)program from which D01AJF is called. The number of sub-intervals into which the interval of integration may be divided cannot exceed LIW.
Suggested value: LIW=LW/4.
Constraint: LIW≥1.
12:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, because for this routine the values of the output arguments may be useful even if IFAIL≠0 on exit, the recommended value is -1. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Note: D01AJF may return useful information for one or more of the following detected errors or warnings.
Errors or warnings detected by the routine:
IFAIL=1
The maximum number of subdivisions allowed with the given workspace has been reached without the accuracy requirements being achieved. Look at the integrand in order to determine the integration difficulties. If the position of a local difficulty within the interval can be determined (e.g., a singularity of the integrand or its derivative, a peak, a discontinuity, etc.) you will probably gain from splitting up the interval at this point and calling the integrator on the subranges. If necessary, another integrator, which is designed for handling the type of difficulty involved, must be used. Alternatively, consider relaxing the accuracy requirements specified by EPSABS and EPSREL, or increasing the amount of workspace.
IFAIL=2
Round-off error prevents the requested tolerance from being achieved. Consider requesting less accuracy.
IFAIL=3
Extremely bad local integrand behaviour causes a very strong subdivision around one (or more) points of the interval. The same advice applies as in the case of IFAIL=1.
IFAIL=4
The requested tolerance cannot be achieved because the extrapolation does not increase the accuracy satisfactorily; the returned result is the best which can be obtained. The same advice applies as in the case of IFAIL=1.
IFAIL=5
The integral is probably divergent, or slowly convergent. Please note that divergence can occur with any nonzero value of IFAIL.
IFAIL=6
On entry, | LW<4,
or | LIW<1.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

D01AJF cannot guarantee, but in practice usually achieves, the following accuracy:
I-RESULT ≤ tol ,
where
tol = max EPSABS , EPSREL × I ,
and EPSABS and EPSREL are user-specified absolute and relative error tolerances. Moreover, it returns the quantity ABSERR which, in normal circumstances, satisfies
I-RESULT ≤ ABSERR ≤ tol .

8 Parallelism and Performance

D01AJF is not threaded in any implementation.

9 Further Comments

The time taken by D01AJF depends on the integrand and the accuracy required.
If IFAIL≠0 on exit, then you may wish to examine the contents of the array W, which contains the end points of the sub-intervals used by D01AJF along with the integral contributions and error estimates over the sub-intervals.
Specifically, for i=1,2,…,n, let ri denote the approximation to the value of the integral over the sub-interval ai,bi in the partition of a,b and ei be the corresponding absolute error estimate. Then, ∫ ai bi f x dx ≃ ri and RESULT = ∑ i=1 n ri , unless D01AJF terminates while testing for divergence of the integral (see Section 3.4.3 of Piessens et al. (1983)). In this case, RESULT (and ABSERR) are taken to be the values returned from the extrapolation process. The value of n is returned in IW 1, and the values ai, bi, ei and ri are stored consecutively in the array W, that is:
  • ai=W i,
  • bi=W n+i,
  • ei=W 2 n+i and
  • ri=W 3 n+i.

10 Example

This example computes
∫ 0 2 π x sin 30 x 1 - x/2 π 2 dx .

10.1 Program Text

Program Text (d01ajfe.f90)

10.2 Program Data

None.

10.3 Program Results

Program Results (d01ajfe.r)

D01 Chapter Contents
D01 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


D01AKF : NAG Library, Mark 26

D01 Chapter Contents
D01 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

D01AKF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

D01AKF is an adaptive integrator, especially suited to oscillating, nonsingular integrands, which calculates an approximation to the integral of a function f x over a finite interval a,b:
I= ∫ab f x dx .

2 Specification

SUBROUTINE D01AKF ( F, A, B, EPSABS, EPSREL, RESULT, ABSERR, W, LW, IW, LIW, IFAIL)
INTEGER | LW, IW(LIW), LIW, IFAIL
REAL (KIND=nag_wp) | F, A, B, EPSABS, EPSREL, RESULT, ABSERR, W(LW)
EXTERNAL | F

3 Description

D01AKF is based on the QUADPACK routine QAG (see Piessens et al. (1983)). It is an adaptive routine, using the Gauss 30-point and Kronrod 61-point rules. A ‘global’ acceptance criterion (as defined by Malcolm and Simpson (1976)) is used. The local error estimation is described in Piessens et al. (1983).
Because D01AKF is based on integration rules of high order, it is especially suitable for nonsingular oscillating integrands.
D01AKF requires you to supply a function to evaluate the integrand at a single point.
The routine D01AUF uses an identical algorithm but requires you to supply a subroutine to evaluate the integrand at an array of points. Therefore D01AUF will be more efficient if the evaluation can be performed in vector mode on a vector-processing machine.

4 References

Malcolm M A and Simpson R B (1976) Local versus global strategies for adaptive quadrature ACM Trans. Math. Software 1 129–146
Piessens R (1973) An algorithm for automatic integration Angew. Inf. 15 399–401
Piessens R, de Doncker–Kapenga E, Überhuber C and Kahaner D (1983) QUADPACK, A Subroutine Package for Automatic Integration Springer–Verlag

5 Arguments

1:   F – REAL (KIND=nag_wp) FUNCTION, supplied by the user.External Procedure
F must return the value of the integrand f at a given point.
The specification of F is:
FUNCTION F ( X)
REAL (KIND=nag_wp) F
REAL (KIND=nag_wp) X
1:   X – REAL (KIND=nag_wp)Input
On entry: the point at which the integrand f must be evaluated.
F must either be a module subprogram USEd by, or declared as EXTERNAL in, the (sub)program from which D01AKF is called. Arguments denoted as Input must not be changed by this procedure.
2:   A – REAL (KIND=nag_wp)Input
On entry: a, the lower limit of integration.
3:   B – REAL (KIND=nag_wp)Input
On entry: b, the upper limit of integration. It is not necessary that a<b.
4:   EPSABS – REAL (KIND=nag_wp)Input
On entry: the absolute accuracy required. If EPSABS is negative, the absolute value is used. See Section 7.
5:   EPSREL – REAL (KIND=nag_wp)Input
On entry: the relative accuracy required. If EPSREL is negative, the absolute value is used. See Section 7.
6:   RESULT – REAL (KIND=nag_wp)Output
On exit: the approximation to the integral I.
7:   ABSERR – REAL (KIND=nag_wp)Output
On exit: an estimate of the modulus of the absolute error, which should be an upper bound for I-RESULT.
8:   W LW – REAL (KIND=nag_wp) arrayOutput
On exit: details of the computation see Section 9 for more information.
9:   LW – INTEGERInput
On entry: the dimension of the array W as declared in the (sub)program from which D01AKF is called. The value of LW (together with that of LIW) imposes a bound on the number of sub-intervals into which the interval of integration may be divided by the routine. The number of sub-intervals cannot exceed LW/4. The more difficult the integrand, the larger LW should be.
Suggested value: LW=800 to 2000 is adequate for most problems.
Constraint: LW≥4.
10:   IW LIW – INTEGER arrayOutput
On exit: IW 1 contains the actual number of sub-intervals used. The rest of the array is used as workspace.
11:   LIW – INTEGERInput
On entry: the dimension of the array IW as declared in the (sub)program from which D01AKF is called. The number of sub-intervals into which the interval of integration may be divided cannot exceed LIW.
Suggested value: LIW=LW/4.
Constraint: LIW≥1.
12:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
The maximum number of subdivisions allowed with the given workspace has been reached without the accuracy requirements being achieved. Look at the integrand in order to determine the integration difficulties. If necessary, another integrator, which is designed for handling the type of difficulty involved, must be used. Alternatively, consider relaxing the accuracy requirements specified by EPSABS and EPSREL, or increasing the amount of workspace.
IFAIL=2
Round-off error prevents the requested tolerance from being achieved. Consider requesting less accuracy.
IFAIL=3
Extremely bad local integrand behaviour causes a very strong subdivision around one (or more) points of the interval. The same advice applies as in the case of IFAIL=1.
IFAIL=4
On entry, | LW<4,
or | LIW<1.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

D01AKF cannot guarantee, but in practice usually achieves, the following accuracy:
I-RESULT ≤ tol ,
where
tol=max EPSABS,EPSREL×I ,
and EPSABS and EPSREL are user-specified absolute and relative error tolerances. Moreover, it returns the quantity ABSERR which, in normal circumstances, satisfies
I-RESULT≤ABSERR≤tol.

8 Parallelism and Performance

D01AKF is not threaded in any implementation.

9 Further Comments

The time taken by D01AKF depends on the integrand and the accuracy required.
If IFAIL≠0 on exit, then you may wish to examine the contents of the array W, which contains the end points of the sub-intervals used by D01AKF along with the integral contributions and error estimates over these sub-intervals.
Specifically, for i=1,2,…,n, let ri denote the approximation to the value of the integral over the sub-interval ai,bi in the partition of a,b and ei be the corresponding absolute error estimate. Then, ∫ ai bi f x dx ≃ ri and RESULT = ∑ i=1 n ri . The value of n is returned in IW 1, and the values ai, bi, ei and ri are stored consecutively in the array W, that is:
  • ai=W i,
  • bi=W n+i,
  • ei=W 2 n+i and
  • ri=W 3 n+i.

10 Example

This example computes
∫ 0 2 π x sin 30 x cos⁡x dx .

10.1 Program Text

Program Text (d01akfe.f90)

10.2 Program Data

None.

10.3 Program Results

Program Results (d01akfe.r)

D01 Chapter Contents
D01 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


D01ALF : NAG Library, Mark 26

D01 Chapter Contents
D01 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

D01ALF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

D01ALF is a general purpose integrator which calculates an approximation to the integral of a function f x over a finite interval a,b:
I= ∫ab f x dx
where the integrand may have local singular behaviour at a finite number of points within the integration interval.

2 Specification

SUBROUTINE D01ALF ( F, A, B, NPTS, POINTS, EPSABS, EPSREL, RESULT, ABSERR, W, LW, IW, LIW, IFAIL)
INTEGER | NPTS, LW, IW(LIW), LIW, IFAIL
REAL (KIND=nag_wp) | F, A, B, POINTS(*), EPSABS, EPSREL, RESULT, ABSERR, W(LW)
EXTERNAL | F

3 Description

D01ALF is based on the QUADPACK routine QAGP (see Piessens et al. (1983)). It is very similar to D01AJF, but allows you to supply ‘break-points’, points at which the integrand is known to be difficult. It employs an adaptive algorithm, using the Gauss 10-point and Kronrod 21-point rules. The algorithm, described in de Doncker (1978), incorporates a global acceptance criterion (as defined by Malcolm and Simpson (1976)) together with the ε-algorithm (see Wynn (1956)) to perform extrapolation. The user-supplied ‘break-points’ always occur as the end points of some sub-interval during the adaptive process. The local error estimation is described in Piessens et al. (1983).

4 References

de Doncker E (1978) An adaptive extrapolation algorithm for automatic integration ACM SIGNUM Newsl. 13(2) 12–18
Malcolm M A and Simpson R B (1976) Local versus global strategies for adaptive quadrature ACM Trans. Math. Software 1 129–146
Piessens R, de Doncker–Kapenga E, Überhuber C and Kahaner D (1983) QUADPACK, A Subroutine Package for Automatic Integration Springer–Verlag
Wynn P (1956) On a device for computing the em Sn transformation Math. Tables Aids Comput. 10 91–96

5 Arguments

1:   F – REAL (KIND=nag_wp) FUNCTION, supplied by the user.External Procedure
F must return the value of the integrand f at a given point.
The specification of F is:
FUNCTION F ( X)
REAL (KIND=nag_wp) F
REAL (KIND=nag_wp) X
1:   X – REAL (KIND=nag_wp)Input
On entry: the point at which the integrand f must be evaluated.
F must either be a module subprogram USEd by, or declared as EXTERNAL in, the (sub)program from which D01ALF is called. Arguments denoted as Input must not be changed by this procedure.
2:   A – REAL (KIND=nag_wp)Input
On entry: a, the lower limit of integration.
3:   B – REAL (KIND=nag_wp)Input
On entry: b, the upper limit of integration. It is not necessary that a<b.
4:   NPTS – INTEGERInput
On entry: the number of user-supplied break-points within the integration interval.
Constraint: NPTS≥0 and NPTS<min LW-2×NPTS-4 / 4 , LIW-NPTS-2 / 2 .
5:   POINTS* – REAL (KIND=nag_wp) arrayInput
Note: the dimension of the array POINTS must be at least max 1,NPTS.
On entry: the user-specified break-points.
Constraint: the break-points must all lie within the interval of integration (but may be supplied in any order).
6:   EPSABS – REAL (KIND=nag_wp)Input
On entry: the absolute accuracy required. If EPSABS is negative, the absolute value is used. See Section 7.
7:   EPSREL – REAL (KIND=nag_wp)Input
On entry: the relative accuracy required. If EPSREL is negative, the absolute value is used. See Section 7.
8:   RESULT – REAL (KIND=nag_wp)Output
On exit: the approximation to the integral I.
9:   ABSERR – REAL (KIND=nag_wp)Output
On exit: an estimate of the modulus of the absolute error, which should be an upper bound for I-RESULT.
10:   W LW – REAL (KIND=nag_wp) arrayOutput
On exit: details of the computation see Section 9 for more information.
11:   LW – INTEGERInput
On entry: the dimension of the array W as declared in the (sub)program from which D01ALF is called. The value of LW (together with that of LIW) imposes a bound on the number of sub-intervals into which the interval of integration may be divided by the routine. The number of sub-intervals cannot exceed LW-2×NPTS-4/4. The more difficult the integrand, the larger LW should be.
Suggested value: a value in the range 800 to 2000 is adequate for most problems.
Constraint: LW≥2×NPTS+8.
12:   IW LIW – INTEGER arrayOutput
On exit: IW 1 contains the actual number of sub-intervals used. The rest of the array is used as workspace.
13:   LIW – INTEGERInput
On entry: the dimension of the array IW as declared in the (sub)program from which D01ALF is called. The number of sub-intervals into which the interval of integration may be divided cannot exceed LIW-NPTS-2/2.
Suggested value: LIW=LW/2.
Constraint: LIW≥NPTS+4.
14:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, because for this routine the values of the output arguments may be useful even if IFAIL≠0 on exit, the recommended value is -1. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Note: D01ALF may return useful information for one or more of the following detected errors or warnings.
Errors or warnings detected by the routine:
IFAIL=1
The maximum number of subdivisions allowed with the given workspace has been reached without the accuracy requirements being achieved. Look at the integrand in order to determine the integration difficulties. If the position of a local difficulty within the interval can be determined (e.g., a singularity of the integrand or its derivative, a peak, a discontinuity, etc.) it should be supplied to the routine as an element of the vector POINTS. If necessary, another integrator, which is designed for handling the type of difficulty involved, must be used. Alternatively, consider relaxing the accuracy requirements specified by EPSABS and EPSREL, or increasing the amount of workspace.
IFAIL=2
Round-off error prevents the requested tolerance from being achieved. Consider requesting less accuracy.
IFAIL=3
Extremely bad local integrand behaviour causes a very strong subdivision around one (or more) points of the interval. The same advice applies as in the case of IFAIL=1.
IFAIL=4
The requested tolerance cannot be achieved because the extrapolation does not increase the accuracy satisfactorily; the returned result is the best which can be obtained. The same advice applies as in the case of IFAIL=1.
IFAIL=5
The integral is probably divergent, or slowly convergent. Please note that divergence can occur with any nonzero value of IFAIL.
IFAIL=6
The input is invalid: break-points are specified outside the integration range, NPTS > min LW-2×NPTS-4/4 , LIW-NPTS-2/2 or NPTS<0. RESULT and ABSERR are set to zero.
IFAIL=7
On entry, | LW<2×NPTS+8,
or | LIW<NPTS+4.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

D01ALF cannot guarantee, but in practice usually achieves, the following accuracy:
I-RESULT≤tol,
where
tol= max EPSABS,EPSREL×I ,
and EPSABS and EPSREL are user-specified absolute and relative error tolerances. Moreover, it returns the quantity ABSERR which, in normal circumstances, satisfies
I-RESULT≤ABSERR≤tol.

8 Parallelism and Performance

D01ALF is not threaded in any implementation.

9 Further Comments

The time taken by D01ALF depends on the integrand and the accuracy required.
If IFAIL≠0 on exit, then you may wish to examine the contents of the array W, which contains the end points of the sub-intervals used by D01ALF along with the integral contributions and error estimates over these sub-intervals.
Specifically, for i=1,2,…,n, let ri denote the approximation to the value of the integral over the sub-interval ai,bi in the partition of a,b and ei be the corresponding absolute error estimate. Then, ∫ ai bi f x dx ≃ ri and RESULT = ∑ i=1 n ri unless D01ALF terminates while testing for divergence of the integral (see Section 3.4.3 of Piessens et al. (1983)). In this case, RESULT (and ABSERR) are taken to be the values returned from the extrapolation process. The value of n is returned in IW 1, and the values ai, bi, ei and ri are stored consecutively in the array W, that is:
  • ai=W i,
  • bi=W n+i,
  • ei=W 2 n+i and
  • ri=W 3 n+i.

10 Example

This example computes
∫ 0 1 1 x-1/7 dx .
A break-point is specified at x=1/7, at which point the integrand is infinite. (For definiteness the function FST returns the value 0.0 at this point.)

10.1 Program Text

Program Text (d01alfe.f90)

10.2 Program Data

None.

10.3 Program Results

Program Results (d01alfe.r)

D01 Chapter Contents
D01 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


D01AMF : NAG Library, Mark 26

D01 Chapter Contents
D01 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

D01AMF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

D01AMF calculates an approximation to the integral of a function f x over an infinite or semi-infinite interval a,b:
I= ∫ab f x dx .

2 Specification

SUBROUTINE D01AMF ( F, BOUND, INF, EPSABS, EPSREL, RESULT, ABSERR, W, LW, IW, LIW, IFAIL)
INTEGER | INF, LW, IW(LIW), LIW, IFAIL
REAL (KIND=nag_wp) | F, BOUND, EPSABS, EPSREL, RESULT, ABSERR, W(LW)
EXTERNAL | F

3 Description

D01AMF is based on the QUADPACK routine QAGI (see Piessens et al. (1983)). The entire infinite integration range is first transformed to 0,1 using one of the identities:
∫ -∞ a f x dx = ∫01 f a - 1-t t 1 t 2 dt
∫a∞ f x dx = ∫01 f a+ 1-t t 1 t 2 dt
∫ -∞ ∞ f x dx = ∫0∞ f x + f-x dx = ∫01 ​ ​ f 1-t t + f -1+t t 1 t 2 dt
where a represents a finite integration limit. An adaptive procedure, based on the Gauss 7-point and Kronrod 15-point rules, is then employed on the transformed integral. The algorithm, described in de Doncker (1978), incorporates a global acceptance criterion (as defined by Malcolm and Simpson (1976)) together with the ε-algorithm (see Wynn (1956)) to perform extrapolation. The local error estimation is described in Piessens et al. (1983).

4 References

de Doncker E (1978) An adaptive extrapolation algorithm for automatic integration ACM SIGNUM Newsl. 13(2) 12–18
Malcolm M A and Simpson R B (1976) Local versus global strategies for adaptive quadrature ACM Trans. Math. Software 1 129–146
Piessens R, de Doncker–Kapenga E, Überhuber C and Kahaner D (1983) QUADPACK, A Subroutine Package for Automatic Integration Springer–Verlag
Wynn P (1956) On a device for computing the em Sn transformation Math. Tables Aids Comput. 10 91–96

5 Arguments

1:   F – REAL (KIND=nag_wp) FUNCTION, supplied by the user.External Procedure
F must return the value of the integrand f at a given point.
The specification of F is:
FUNCTION F ( X)
REAL (KIND=nag_wp) F
REAL (KIND=nag_wp) X
1:   X – REAL (KIND=nag_wp)Input
On entry: the point at which the integrand f must be evaluated.
F must either be a module subprogram USEd by, or declared as EXTERNAL in, the (sub)program from which D01AMF is called. Arguments denoted as Input must not be changed by this procedure.
2:   BOUND – REAL (KIND=nag_wp)Input
On entry: the finite limit of the integration range (if present). BOUND is not used if the interval is doubly infinite.
3:   INF – INTEGERInput
On entry: indicates the kind of integration range.
INF=1
The range is BOUND,+∞.
INF=-1
The range is -∞,BOUND.
INF=2
The range is -∞,+∞.
Constraint: INF=-1, 1 or 2.
4:   EPSABS – REAL (KIND=nag_wp)Input
On entry: the absolute accuracy required. If EPSABS is negative, the absolute value is used. See Section 7.
5:   EPSREL – REAL (KIND=nag_wp)Input
On entry: the relative accuracy required. If EPSREL is negative, the absolute value is used. See Section 7.
6:   RESULT – REAL (KIND=nag_wp)Output
On exit: the approximation to the integral I.
7:   ABSERR – REAL (KIND=nag_wp)Output
On exit: an estimate of the modulus of the absolute error, which should be an upper bound for I-RESULT.
8:   W LW – REAL (KIND=nag_wp) arrayOutput
On exit: details of the computation see Section 9 for more information.
9:   LW – INTEGERInput
On entry: the dimension of the array W as declared in the (sub)program from which D01AMF is called. The value of LW (together with that of LIW) imposes a bound on the number of sub-intervals into which the interval of integration may be divided by the routine. The number of sub-intervals cannot exceed LW/4. The more difficult the integrand, the larger LW should be.
Suggested value: LW=800 to 2000 is adequate for most problems.
Constraint: LW≥4.
10:   IW LIW – INTEGER arrayOutput
On exit: IW 1 contains the actual number of sub-intervals used. The rest of the array is used as workspace.
11:   LIW – INTEGERInput
On entry: the dimension of the array IW as declared in the (sub)program from which D01AMF is called. The number of sub-intervals into which the interval of integration may be divided cannot exceed LIW.
Suggested value: LIW=LW/4.
Constraint: LIW≥1.
12:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, because for this routine the values of the output arguments may be useful even if IFAIL≠0 on exit, the recommended value is -1. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Note: D01AMF may return useful information for one or more of the following detected errors or warnings.
Errors or warnings detected by the routine:
IFAIL=1
The maximum number of subdivisions allowed with the given workspace has been reached without the accuracy requirements being achieved. Look at the integrand in order to determine the integration difficulties. If the position of a local difficulty within the interval can be determined (e.g., a singularity of the integrand or its derivative, a peak, a discontinuity, etc.) you will probably gain from splitting up the interval at this point and calling D01AMF on the infinite subrange and an appropriate integrator on the finite subrange. Alternatively, consider relaxing the accuracy requirements specified by EPSABS and EPSREL, or increasing the amount of workspace.
IFAIL=2
Round-off error prevents the requested tolerance from being achieved. Consider requesting less accuracy.
IFAIL=3
Extremely bad local integrand behaviour causes a very strong subdivision around one (or more) points of the interval. The same advice applies as in the case of IFAIL=1.
IFAIL=4
The requested tolerance cannot be achieved because the extrapolation does not increase the accuracy satisfactorily; the returned result is the best which can be obtained. The same advice applies as in the case of IFAIL=1.
IFAIL=5
The integral is probably divergent, or slowly convergent. Please note that divergence can occur with any nonzero value of IFAIL.
IFAIL=6
On entry, | LW<4,
or | LIW<1,
or | INF≠-1, 1 or 2.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

D01AMF cannot guarantee, but in practice usually achieves, the following accuracy:
I-RESULT≤tol,
where
tol=max EPSABS,EPSREL×I ,
and EPSABS and EPSREL are user-specified absolute and relative error tolerances. Moreover, it returns the quantity ABSERR which, in normal circumstances, satisfies
I-RESULT≤ABSERR≤tol.

8 Parallelism and Performance

D01AMF is not threaded in any implementation.

9 Further Comments

The time taken by D01AMF depends on the integrand and the accuracy required.
If IFAIL≠0 on exit, then you may wish to examine the contents of the array W, which contains the end points of the sub-intervals used by D01AMF along with the integral contributions and error estimates over these sub-intervals.
Specifically, for i=1,2,…,n, let ri denote the approximation to the value of the integral over the sub-interval ai,bi in the partition of a,b and ei be the corresponding absolute error estimate. Then, ∫ ai bi f x dx ≃ ri and RESULT = ∑ i=1 n ri , unless D01AMF terminates while testing for divergence of the integral (see Section 3.4.3 of Piessens et al. (1983)). In this case, RESULT (and ABSERR) are taken to be the values returned from the extrapolation process. The value of n is returned in IW 1, and the values ai, bi, ei and ri are stored consecutively in the array W, that is:
  • ai=W i,
  • bi=W n+i,
  • ei=W 2 n+i and
  • ri=W 3 n+i.
Note: this information applies to the integral transformed to 0,1 as described in Section 3, not to the original integral.

10 Example

This example computes
∫ 0 ∞ 1 x+1 x dx .
The exact answer is π.

10.1 Program Text

Program Text (d01amfe.f90)

10.2 Program Data

None.

10.3 Program Results

Program Results (d01amfe.r)

D01 Chapter Contents
D01 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


D01ANF : NAG Library, Mark 26

D01 Chapter Contents
D01 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

D01ANF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

D01ANF calculates an approximation to the sine or the cosine transform of a function g over a,b:
I=∫ab g x sin ω xdx  or  I=∫ab g x cos ω xdx
(for a user-specified value of ω).

2 Specification

SUBROUTINE D01ANF ( G, A, B, OMEGA, KEY, EPSABS, EPSREL, RESULT, ABSERR, W, LW, IW, LIW, IFAIL)
INTEGER | KEY, LW, IW(LIW), LIW, IFAIL
REAL (KIND=nag_wp) | G, A, B, OMEGA, EPSABS, EPSREL, RESULT, ABSERR, W(LW)
EXTERNAL | G

3 Description

D01ANF is based on the QUADPACK routine QFOUR (see Piessens et al. (1983)). It is an adaptive routine, designed to integrate a function of the form g x w x, where w x is either sin ωx or cos ωx. If a sub-interval has length
L=b-a 2-l
then the integration over this sub-interval is performed by means of a modified Clenshaw–Curtis procedure (see Piessens and Branders (1975)) if Lω>4 and l≤20. In this case a Chebyshev series approximation of degree 24 is used to approximate g x, while an error estimate is computed from this approximation together with that obtained using Chebyshev series of degree 12. If the above conditions do not hold then Gauss 7-point and Kronrod 15-point rules are used. The algorithm, described in Piessens et al. (1983), incorporates a global acceptance criterion (as defined in Malcolm and Simpson (1976)) together with the
ε-algorithm (see Wynn (1956)) to perform extrapolation. The local error estimation is described in
Piessens et al. (1983).

4 References

Malcolm M A and Simpson R B (1976) Local versus global strategies for adaptive quadrature ACM Trans. Math. Software 1 129–146
Piessens R and Branders M (1975) Algorithm 002: computation of oscillating integrals J. Comput. Appl. Math. 1 153–164
Piessens R, de Doncker–Kapenga E, Überhuber C and Kahaner D (1983) QUADPACK, A Subroutine Package for Automatic Integration Springer–Verlag
Wynn P (1956) On a device for computing the em Sn transformation Math. Tables Aids Comput. 10 91–96

5 Arguments

1:   G – REAL (KIND=nag_wp) FUNCTION, supplied by the user.External Procedure
G must return the value of the function g at a given point X.
The specification of G is:
FUNCTION G ( X)
REAL (KIND=nag_wp) G
REAL (KIND=nag_wp) X
1:   X – REAL (KIND=nag_wp)Input
On entry: the point at which the function g must be evaluated.
G must either be a module subprogram USEd by, or declared as EXTERNAL in, the (sub)program from which D01ANF is called. Arguments denoted as Input must not be changed by this procedure.
2:   A – REAL (KIND=nag_wp)Input
On entry: a, the lower limit of integration.
3:   B – REAL (KIND=nag_wp)Input
On entry: b, the upper limit of integration. It is not necessary that a<b.
4:   OMEGA – REAL (KIND=nag_wp)Input
On entry: the argument ω in the weight function of the transform.
5:   KEY – INTEGERInput
On entry: indicates which integral is to be computed.
KEY=1
w x=cos ωx.
KEY=2
w x=sin ωx.
Constraint: KEY=1 or 2.
6:   EPSABS – REAL (KIND=nag_wp)Input
On entry: the absolute accuracy required. If EPSABS is negative, the absolute value is used. See Section 7.
7:   EPSREL – REAL (KIND=nag_wp)Input
On entry: the relative accuracy required. If EPSREL is negative, the absolute value is used. See Section 7.
8:   RESULT – REAL (KIND=nag_wp)Output
On exit: the approximation to the integral I.
9:   ABSERR – REAL (KIND=nag_wp)Output
On exit: an estimate of the modulus of the absolute error, which should be an upper bound for I-RESULT.
10:   W LW – REAL (KIND=nag_wp) arrayOutput
On exit: details of the computation see Section 9 for more information.
11:   LW – INTEGERInput
On entry: the dimension of the array W as declared in the (sub)program from which D01ANF is called. The value of LW (together with that of LIW) imposes a bound on the number of sub-intervals into which the interval of integration may be divided by the routine. The number of sub-intervals cannot exceed LW/4. The more difficult the integrand, the larger LW should be.
Suggested value: LW=800 to 2000 is adequate for most problems.
Constraint: LW≥4.
12:   IW LIW – INTEGER arrayOutput
On exit: IW 1 contains the actual number of sub-intervals used. The rest of the array is used as workspace.
13:   LIW – INTEGERInput
On entry: the dimension of the array IW as declared in the (sub)program from which D01ANF is called. The number of sub-intervals into which the interval of integration may be divided cannot exceed LIW/2.
Suggested value: LIW=LW/2.
Constraint: LIW≥2.
14:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, because for this routine the values of the output arguments may be useful even if IFAIL≠0 on exit, the recommended value is -1. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Note: D01ANF may return useful information for one or more of the following detected errors or warnings.
Errors or warnings detected by the routine:
IFAIL=1
The maximum number of subdivisions allowed with the given workspace has been reached without the accuracy requirements being achieved. Look at the integrand in order to determine the integration difficulties. If the position of a local difficulty within the interval can be determined (e.g., a singularity of the integrand or its derivative, a peak, a discontinuity, etc.) you will probably gain from splitting up the interval at this point and calling the integrator on the subranges. If necessary, another integrator, which is designed for handling the type of difficulty involved, must be used. Alternatively, consider relaxing the accuracy requirements specified by EPSABS and EPSREL, or increasing the amount of workspace.
IFAIL=2
Round-off error prevents the requested tolerance from being achieved. Consider requesting less accuracy.
IFAIL=3
Extremely bad local behaviour of g x causes a very strong subdivision around one (or more) points of the interval. The same advice applies as in the case of IFAIL=1.
IFAIL=4
The requested tolerance cannot be achieved because the extrapolation does not increase the accuracy satisfactorily; the returned result is the best which can be obtained. The same advice applies as in the case of IFAIL=1.
IFAIL=5
The integral is probably divergent, or slowly convergent. Please note that divergence can occur with any nonzero value of IFAIL.
IFAIL=6
On entry, KEY≠1 or 2.
IFAIL=7
On entry, | LW<4,
or | LIW<2.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

D01ANF cannot guarantee, but in practice usually achieves, the following accuracy:
I-RESULT≤tol,
where
tol=max EPSABS,EPSREL×I ,
and EPSABS and EPSREL are user-specified absolute and relative tolerances. Moreover, it returns the quantity ABSERR which in normal circumstances, satisfies
I-RESULT≤ABSERR≤tol.

8 Parallelism and Performance

D01ANF is not threaded in any implementation.

9 Further Comments

The time taken by D01ANF depends on the integrand and the accuracy required.
If IFAIL≠0 on exit, then you may wish to examine the contents of the array W, which contains the end points of the sub-intervals used by D01ANF along with the integral contributions and error estimates over these sub-intervals.
Specifically, for i=1,2,…,n, let ri denote the approximation to the value of the integral over the sub-interval ai,bi in the partition of a,b and ei be the corresponding absolute error estimate. Then, ∫aibi g x w x dx≃ri and RESULT=∑i=1 n ri unless D01ANF terminates while testing for divergence of the integral (see Section 3.4.3 of Piessens et al. (1983)). In this case, RESULT (and ABSERR) are taken to be the values returned from the extrapolation process. The value of n is returned in IW 1, and the values ai, bi, ei and ri are stored consecutively in the array W, that is:
  • ai=W i,
  • bi=W n+i,
  • ei=W 2 n+i and
  • ri=W 3 n+i.

10 Example

This example computes
∫01 ln⁡x sin 10 πxdx.

10.1 Program Text

Program Text (d01anfe.f90)

10.2 Program Data

None.

10.3 Program Results

Program Results (d01anfe.r)

D01 Chapter Contents
D01 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


D01APF : NAG Library, Mark 26

D01 Chapter Contents
D01 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

D01APF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

D01APF is an adaptive integrator which calculates an approximation to the integral of a function g x w x over a finite interval a,b:
I= ∫ab g x w x dx
where the weight function w has end point singularities of algebraico-logarithmic type.

2 Specification

SUBROUTINE D01APF ( G, A, B, ALFA, BETA, KEY, EPSABS, EPSREL, RESULT, ABSERR, W, LW, IW, LIW, IFAIL)
INTEGER | KEY, LW, IW(LIW), LIW, IFAIL
REAL (KIND=nag_wp) | G, A, B, ALFA, BETA, EPSABS, EPSREL, RESULT, ABSERR, W(LW)
EXTERNAL | G

3 Description

D01APF is based on the QUADPACK routine QAWSE (see Piessens et al. (1983)) and integrates a function of the form g x w x, where the weight function w x may have algebraico-logarithmic singularities at the end points a and/or b. The strategy is a modification of that in D01AKF. We start by bisecting the original interval and applying modified Clenshaw–Curtis integration of orders 12 and 24 to both halves. Clenshaw–Curtis integration is then used on all sub-intervals which have a or b as one of their end points (see Piessens et al. (1974)). On the other sub-intervals Gauss–Kronrod (7–15 point) integration is carried out.
A ‘global’ acceptance criterion (as defined by Malcolm and Simpson (1976)) is used. The local error estimation control is described in Piessens et al. (1983).

4 References

Malcolm M A and Simpson R B (1976) Local versus global strategies for adaptive quadrature ACM Trans. Math. Software 1 129–146
Piessens R, de Doncker–Kapenga E, Überhuber C and Kahaner D (1983) QUADPACK, A Subroutine Package for Automatic Integration Springer–Verlag
Piessens R, Mertens I and Branders M (1974) Integration of functions having end-point singularities Angew. Inf. 16 65–68

5 Arguments

1:   G – REAL (KIND=nag_wp) FUNCTION, supplied by the user.External Procedure
G must return the value of the function g at a given point X.
The specification of G is:
FUNCTION G ( X)
REAL (KIND=nag_wp) G
REAL (KIND=nag_wp) X
1:   X – REAL (KIND=nag_wp)Input
On entry: the point at which the function g must be evaluated.
G must either be a module subprogram USEd by, or declared as EXTERNAL in, the (sub)program from which D01APF is called. Arguments denoted as Input must not be changed by this procedure.
2:   A – REAL (KIND=nag_wp)Input
On entry: a, the lower limit of integration.
3:   B – REAL (KIND=nag_wp)Input
On entry: b, the upper limit of integration.
Constraint: B>A.
4:   ALFA – REAL (KIND=nag_wp)Input
On entry: the argument α in the weight function.
Constraint: ALFA>-1.0.
5:   BETA – REAL (KIND=nag_wp)Input
On entry: the argument β in the weight function.
Constraint: BETA>-1.0.
6:   KEY – INTEGERInput
On entry: indicates which weight function is to be used.
KEY=1
w x=x-a αb-x β.
KEY=2
w x= x-a α b-x β ln x-a.
KEY=3
w x= x-a α b-x β ln b-x.
KEY=4
w x= x-a α b-x β ln x-aln b-x.
Constraint: KEY=1, 2, 3 or 4.
7:   EPSABS – REAL (KIND=nag_wp)Input
On entry: the absolute accuracy required. If EPSABS is negative, the absolute value is used. See Section 7.
8:   EPSREL – REAL (KIND=nag_wp)Input
On entry: the relative accuracy required. If EPSREL is negative, the absolute value is used. See Section 7.
9:   RESULT – REAL (KIND=nag_wp)Output
On exit: the approximation to the integral I.
10:   ABSERR – REAL (KIND=nag_wp)Output
On exit: an estimate of the modulus of the absolute error, which should be an upper bound for I-RESULT.
11:   W LW – REAL (KIND=nag_wp) arrayOutput
On exit: details of the computation see Section 9 for more information.
12:   LW – INTEGERInput
On entry: the dimension of the array W as declared in the (sub)program from which D01APF is called. The value of LW (together with that of LIW) imposes a bound on the number of sub-intervals into which the interval of integration may be divided by the routine. The number of sub-intervals cannot exceed LW/4. The more difficult the integrand, the larger LW should be.
Suggested value: LW=800 to 2000 is adequate for most problems.
Constraint: LW≥8.
13:   IW LIW – INTEGER arrayOutput
On exit: IW 1 contains the actual number of sub-intervals used. The rest of the array is used as workspace.
14:   LIW – INTEGERInput
On entry: the dimension of the array IW as declared in the (sub)program from which D01APF is called. The number of sub-intervals into which the interval of integration may be divided cannot exceed LIW.
Suggested value: LIW=LW/4.
Constraint: LIW≥2.
15:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, because for this routine the values of the output arguments may be useful even if IFAIL≠0 on exit, the recommended value is -1. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Note: D01APF may return useful information for one or more of the following detected errors or warnings.
Errors or warnings detected by the routine:
IFAIL=1
The maximum number of subdivisions allowed with the given workspace has been reached without the accuracy requirements being achieved. Look at the integrand in order to determine the integration difficulties. If the position of a discontinuity or a singularity of algebraico-logarithmic type within the interval can be determined, the interval must be split up at this point and the integrator called on the subranges. If necessary, another integrator, which is designed for handling the type of difficulty involved, must be used. Alternatively, consider relaxing the accuracy requirements specified by EPSABS and EPSREL, or increasing the amount of workspace.
IFAIL=2
Round-off error prevents the requested tolerance from being achieved. Consider requesting less accuracy.
IFAIL=3
Extremely bad local integrand behaviour causes a very strong subdivision around one (or more) points of the interval. The same advice applies as in the case of IFAIL=1.
IFAIL=4
On entry, | B≤A,
or | ALFA≤-1.0,
or | BETA≤-1.0,
or | KEY≠1, 2, 3 or 4.
IFAIL=5
On entry, | LW<8,
or | LIW<2.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

D01APF cannot guarantee, but in practice usually achieves, the following accuracy:
I-RESULT≤tol,
where
tol=max EPSABS,EPSREL×I ,
and EPSABS and EPSREL are user-specified absolute and relative error tolerances. Moreover, it returns the quantity ABSERR which, in normal circumstances, satisfies
I-RESULT≤ABSERR≤tol.

8 Parallelism and Performance

D01APF is not threaded in any implementation.

9 Further Comments

The time taken by D01APF depends on the integrand and the accuracy required.
If IFAIL≠0 on exit, then you may wish to examine the contents of the array W, which contains the end points of the sub-intervals used by D01APF along with the integral contributions and error estimates over these sub-intervals.
Specifically, for i=1,2,…,n, let ri denote the approximation to the value of the integral over the sub-interval ai,bi in the partition of a,b and ei be the corresponding absolute error estimate. Then, ∫ ai bi f x w x dx ≃ ri and RESULT = ∑ i=1 n ri . The value of n is returned in IW 1, and the values ai, bi, ei and ri are stored consecutively in the array W, that is:
  • ai=W i,
  • bi=W n+i,
  • ei=W 2 n+i and
  • ri=W 3 n+i.

10 Example

This example computes
∫ 0 1 ln⁡x cos 10 πx dx   and   ∫01 sin 10 x x 1-x dx .

10.1 Program Text

Program Text (d01apfe.f90)

10.2 Program Data

None.

10.3 Program Results

Program Results (d01apfe.r)

D01 Chapter Contents
D01 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


D01AQF : NAG Library, Mark 26

D01 Chapter Contents
D01 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

D01AQF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

D01AQF calculates an approximation to the Hilbert transform of a function g x over a,b:
I=∫ab g x x-c dx
for user-specified values of a, b and c.

2 Specification

SUBROUTINE D01AQF ( G, A, B, C, EPSABS, EPSREL, RESULT, ABSERR, W, LW, IW, LIW, IFAIL)
INTEGER | LW, IW(LIW), LIW, IFAIL
REAL (KIND=nag_wp) | G, A, B, C, EPSABS, EPSREL, RESULT, ABSERR, W(LW)
EXTERNAL | G

3 Description

D01AQF is based on the QUADPACK routine QAWC (see Piessens et al. (1983)) and integrates a function of the form g x w x, where the weight function
w x=1 x-c
is that of the Hilbert transform. (If a<c<b the integral has to be interpreted in the sense of a Cauchy principal value.) It is an adaptive routine which employs a ‘global’ acceptance criterion (as defined by Malcolm and Simpson (1976)). Special care is taken to ensure that c is never the end point of a sub-interval (see Piessens et al. (1976)). On each sub-interval c 1,c 2 modified Clenshaw–Curtis integration of orders 12 and 24 is performed if c 1-d≤c≤c 2+d where d=c 2-c 1/20. Otherwise the Gauss
7-point and Kronrod 15-point rules are used. The local error estimation is described by
Piessens et al. (1983).

4 References

Malcolm M A and Simpson R B (1976) Local versus global strategies for adaptive quadrature ACM Trans. Math. Software 1 129–146
Piessens R, de Doncker–Kapenga E, Überhuber C and Kahaner D (1983) QUADPACK, A Subroutine Package for Automatic Integration Springer–Verlag
Piessens R, van Roy–Branders M and Mertens I (1976) The automatic evaluation of Cauchy principal value integrals Angew. Inf. 18 31–35

5 Arguments

1:   G – REAL (KIND=nag_wp) FUNCTION, supplied by the user.External Procedure
G must return the value of the function g at a given point X.
The specification of G is:
FUNCTION G ( X)
REAL (KIND=nag_wp) G
REAL (KIND=nag_wp) X
1:   X – REAL (KIND=nag_wp)Input
On entry: the point at which the function g must be evaluated.
G must either be a module subprogram USEd by, or declared as EXTERNAL in, the (sub)program from which D01AQF is called. Arguments denoted as Input must not be changed by this procedure.
2:   A – REAL (KIND=nag_wp)Input
On entry: a, the lower limit of integration.
3:   B – REAL (KIND=nag_wp)Input
On entry: b, the upper limit of integration. It is not necessary that a<b.
4:   C – REAL (KIND=nag_wp)Input
On entry: the argument c in the weight function.
Constraint: C must not equal A or B.
5:   EPSABS – REAL (KIND=nag_wp)Input
On entry: the absolute accuracy required. If EPSABS is negative, the absolute value is used. See Section 7.
6:   EPSREL – REAL (KIND=nag_wp)Input
On entry: the relative accuracy required. If EPSREL is negative, the absolute value is used. See Section 7.
7:   RESULT – REAL (KIND=nag_wp)Output
On exit: the approximation to the integral I.
8:   ABSERR – REAL (KIND=nag_wp)Output
On exit: an estimate of the modulus of the absolute error, which should be an upper bound for I-RESULT.
9:   W LW – REAL (KIND=nag_wp) arrayOutput
On exit: details of the computation see Section 9 for more information.
10:   LW – INTEGERInput
On entry: the dimension of the array W as declared in the (sub)program from which D01AQF is called. The value of LW (together with that of LIW) imposes a bound on the number of sub-intervals into which the interval of integration may be divided by the routine. The number of sub-intervals cannot exceed LW/4. The more difficult the integrand, the larger LW should be.
Suggested value: LW=800 to 2000 is adequate for most problems.
Constraint: LW≥4.
11:   IW LIW – INTEGER arrayOutput
On exit: IW 1 contains the actual number of sub-intervals used. The rest of the array is used as workspace.
12:   LIW – INTEGERInput
On entry: the dimension of the array IW as declared in the (sub)program from which D01AQF is called. The number of sub-intervals into which the interval of integration may be divided cannot exceed LIW.
Suggested value: LIW=LW/4.
Constraint: LIW≥1.
13:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, because for this routine the values of the output arguments may be useful even if IFAIL≠0 on exit, the recommended value is -1. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Note: D01AQF may return useful information for one or more of the following detected errors or warnings.
Errors or warnings detected by the routine:
IFAIL=1
The maximum number of subdivisions allowed with the given workspace has been reached without the accuracy requirements being achieved. Look at the integrand in order to determine the integration difficulties. If necessary, another integrator, which is designed for handling the type of difficulty involved, must be used. Alternatively, consider relaxing the accuracy requirements specified by EPSABS and EPSREL, or increasing the amount of workspace.
IFAIL=2
Round-off error prevents the requested tolerance from being achieved. Consider requesting less accuracy.
IFAIL=3
Extremely bad local behaviour of g x causes a very strong subdivision around one (or more) points of the interval. The same advice applies as in the case of IFAIL=1.
IFAIL=4
On entry, C=A or C=B.
IFAIL=5
On entry, | LW<4,
or | LIW<1.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

D01AQF cannot guarantee, but in practice usually achieves, the following accuracy:
I-RESULT≤tol,
where
tol=max EPSABS,EPSREL×I ,
and EPSABS and EPSREL are user-specified absolute and relative error tolerances. Moreover, it returns the quantity ABSERR which, in normal circumstances satisfies:
I-RESULT≤ABSERR≤tol.

8 Parallelism and Performance

D01AQF is not threaded in any implementation.

9 Further Comments

The time taken by D01AQF depends on the integrand and the accuracy required.
If IFAIL≠0 on exit, then you may wish to examine the contents of the array W, which contains the end points of the sub-intervals used by D01AQF along with the integral contributions and error estimates over these sub-intervals.
Specifically, for i=1,2,…,n, let ri denote the approximation to the value of the integral over the sub-interval [ai,bi] in the partition of a,b and ei be the corresponding absolute error estimate. Then, ∫aibi g x w x dx≃ri and RESULT=∑i=1 n ri. The value of n is returned in IW 1, and the values ai, bi, ei and ri are stored consecutively in the array W, that is:
  • ai=W i,
  • bi=W n+i,
  • ei=W 2 n+i and
  • ri=W 3 n+i.

10 Example

This example computes the Cauchy principal value of
∫ -1 1 dx x 2 + 0.012 x - 12 .

10.1 Program Text

Program Text (d01aqfe.f90)

10.2 Program Data

None.

10.3 Program Results

Program Results (d01aqfe.r)

D01 Chapter Contents
D01 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


D01ARF : NAG Library, Mark 26

D01 Chapter Contents
D01 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

D01ARF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
▸▿ 3 Description
3.1 Definite Integrals
3.2 Indefinite Integrals
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

D01ARF computes definite and indefinite integrals over a finite range to a specified relative or absolute accuracy, using the method described in Patterson (1968).

2 Specification

SUBROUTINE D01ARF ( A, B, FUN, RELACC, ABSACC, MAXRUL, IPARM, ACC, ANS, N, ALPHA, IFAIL)
INTEGER | MAXRUL, IPARM, N, IFAIL
REAL (KIND=nag_wp) | A, B, FUN, RELACC, ABSACC, ACC, ANS, ALPHA(390)
EXTERNAL | FUN

3 Description

D01ARF evaluates definite and indefinite integrals of the form:
∫ab f t dt
using the method described in Patterson (1968).

3.1 Definite Integrals

In this case D01ARF must be called with IPARM=0. By linear transformation the integral is changed to
I=∫-1 +1 F x dx
where
F x=b-a 2 f b+a+b-a x 2
and is then approximated by an n-point quadrature rule
I=∑k=1 n wk F xk
where wk are the weights and xk are the abscissae.
The routine uses a family of nine interlacing rules based on the optimal extension of the three-point Gauss rule. These rules use 1, 3, 7, 15, 31, 63, 127, 255 and 511 points and have respective polynomial integrating degrees 1, 5, 11, 23, 47, 95, 191, 383 and 767. Each rule has the property that the next in sequence includes all the points of its predecessor and has the greatest possible increase in integrating degree.
The integration method is based on the successive application of these rules until the absolute value of the difference of two successive results differs by not more than ABSACC, or relatively by not more than RELACC. The result of the last rule used is taken as the value of the integral (ANS), and the absolute difference of the results of the last two rules used is taken as an estimate of the absolute error (ACC). Due to their interlacing form no integrand evaluations are wasted in passing from one rule to the next.

3.2 Indefinite Integrals

Suppose the value of the integral
∫cd f t dt
is required for a number of sub-intervals c,d, all of which lie in an interval a,b.
In this case D01ARF should first be called with the argument IPARM=1 and the interval set to a,b. The routine then calculates the integral over a,b and the Legendre expansion of the integrand, using the same integrand values. If the routine is subsequently called with IPARM=2 and the interval set to c,d, the integral over c,d is calculated by analytical integration of the Legendre expansion, without further evaluations of the integrand.
For the interval -1,1 the expansion takes the form
F x=∑i=0∞αiPi x
where Pi x is the order i Legendre polynomial. Assuming that the integral over the full range -1,1 was evaluated to the required accuracy using an n-point rule, then the coefficients
αi=12 2 i-1∫-1 +1 Pi x F x dx,  i=0,1,…,m
are evaluated by that same rule, up to
m=3 n- 1/4.
The accuracy for indefinite integration should be of the same order as that obtained for the definite integral over the full range. The indefinite integrals will be exact when F x is a polynomial of degree ≤m.

4 References

Patterson T N L (1968) The Optimum addition of points to quadrature formulae Math. Comput. 22 847–856

5 Arguments

1:   A – REAL (KIND=nag_wp)Input
On entry: a, the lower limit of integration.
2:   B – REAL (KIND=nag_wp)Input
On entry: b, the upper limit of integration. It is not necessary that a<b.
3:   FUN – REAL (KIND=nag_wp) FUNCTION, supplied by the user.External Procedure
FUN must return the value of the integrand f at a specified point.
The specification of FUN is:
FUNCTION FUN ( X)
REAL (KIND=nag_wp) FUN
REAL (KIND=nag_wp) X
1:   X – REAL (KIND=nag_wp)Input
On entry: the point in a,b at which the integrand f must be evaluated.
FUN must either be a module subprogram USEd by, or declared as EXTERNAL in, the (sub)program from which D01ARF is called. Arguments denoted as Input must not be changed by this procedure.
If IPARM=2, FUN is not called.
4:   RELACC – REAL (KIND=nag_wp)Input
On entry: the relative accuracy required. If convergence according to absolute accuracy is required, RELACC should be set to zero (but see also Section 7). If RELACC<0.0, its absolute value is used.
If IPARM=2, RELACC is not used.
5:   ABSACC – REAL (KIND=nag_wp)Input
On entry: the absolute accuracy required. If convergence according to relative accuracy is required, ABSACC should be set to zero (but see also Section 7). If ABSACC<0.0, its absolute value is used.
If IPARM=2, ABSACC is not used.
6:   MAXRUL – INTEGERInput
On entry: the maximum number of successive rules that may be used.
Constraint: 1≤MAXRUL≤9. If MAXRUL is outside these limits, the value 9 is assumed.
If IPARM=2, MAXRUL is not used.
7:   IPARM – INTEGERInput
On entry: indicates the task to be performed by the routine.
IPARM=0
Only the definite integral over a,b is evaluated.
IPARM=1
As well as the definite integral, the expansion of the integrand in Legendre polynomials over a,b is calculated, using the same values of the integrand as used to compute the integral. The expansion coefficients, and some other quantities, are returned in ALPHA for later use in computing indefinite integrals.
IPARM=2
f t is integrated analytically over a,b using the previously computed expansion, stored in ALPHA. No further evaluations of the integrand are required. The routine must previously have been called with IPARM=1 and the interval a,b must lie within that specified for the previous call. In this case only the arguments A, B, IPARM, ANS, ALPHA and IFAIL are used.
Constraint: IPARM=0, 1 or 2.
8:   ACC – REAL (KIND=nag_wp)Output
On exit: if IPARM=0 or 1, ACC contains the absolute value of the difference between the last two successive estimates of the integral. This may be used as a measure of the accuracy actually achieved.
If IPARM=2, ACC is not used.
9:   ANS – REAL (KIND=nag_wp)Output
On exit: the estimated value of the integral.
10:   N – INTEGEROutput
On exit: when IPARM=0 or 1, N contains the number of integrand evaluations used in the calculation of the integral.
If IPARM=2, N is not used.
11:   ALPHA 390 – REAL (KIND=nag_wp) arrayInput/Output
On entry: if IPARM=2, ALPHA must contain the coefficients of the Legendre expansions of the integrand, as returned by a previous call of D01ARF with IPARM=1 and a range containing the present range.
If IPARM=0 or 1, ALPHA need not be set on entry.
On exit: if IPARM=1, the first m elements of ALPHA hold the coefficients of the Legendre expansion of the integrand, and the value of m is stored in ALPHA 390. ALPHA must not be changed between a call with IPARM=1 and subsequent calls with IPARM=2.
If IPARM=2, the first m elements of ALPHA are unchanged on exit.
12:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, because for this routine the values of the output arguments may be useful even if IFAIL≠0 on exit, the recommended value is -1. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Note: D01ARF may return useful information for one or more of the following detected errors or warnings.
Errors or warnings detected by the routine:
IFAIL=1
If IPARM=0 or 1, this indicates that all MAXRUL rules have been used and the integral has not converged to the accuracy requested. In this case ANS contains the last approximation to the integral, and ACC contains the difference between the last two approximations. To check this estimate of the integral, D01ARF could be called again to evaluate
∫ab f t dt  as  ∫ac f t dt+∫cb f t dt  for some ​a<c<b.
If IPARM=2, this indicates failure of convergence during the run with IPARM=1 in which the Legendre expansion was created.
IFAIL=2
On entry, IPARM≠0, 1 or 2
IFAIL=3
The routine is called with IPARM=2 but a previous call with IPARM=1 has been omitted or was invoked with an integration interval of length zero.
IFAIL=4
On entry, with IPARM=2, the interval for indefinite integration is not contained within the interval specified when D01ARF was previously called with IPARM=1.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

The relative or absolute accuracy required is specified by you in the variables RELACC or ABSACC. D01ARF will terminate whenever either the relative accuracy specified by RELACC or the absolute accuracy specified by ABSACC is reached. One or other of these criteria may be ‘forced’ by setting the argument for the other to zero. If both RELACC and ABSACC are specified as zero, then the routine uses the value 10.0×machine precision for RELACC.
If on exit IFAIL=0, then it is likely that the result is correct to one or other of these accuracies. If on exit IFAIL=1, then it is likely that neither of the requested accuracies has been reached.
When you have no prior idea of the magnitude of the integral, it is possible that an unreasonable accuracy may be requested, e.g., a relative accuracy for an integral which turns out to be zero, or a small absolute accuracy for an integral which turns out to be very large. Even if failure is reported in such a case, the value of the integral may still be satisfactory. The device of setting the other ‘unused’ accuracy argument to a small positive value (e.g., 10-9 for an implementation of 11-digit precision) rather than zero, may prevent excessive calculation in such a situation.
To avoid spurious convergence, it is recommended that relative accuracies larger than about 10-3 be avoided.

8 Parallelism and Performance

D01ARF is not threaded in any implementation.

9 Further Comments

The time taken by D01ARF depends on the complexity of the integrand and the accuracy required.
This routine uses the Patterson method over the whole integration interval and should therefore be suitable for well behaved functions. However, for very irregular functions it would be more efficient to submit the differently behaved regions separately for integration.

10 Example

This example evaluates the following integrals
(i) Definite integral only IPARM=0 for
∫01 4 1+x 2 dx ABSACC=10-5.
(ii) Definite integral together with expansion coefficients IPARM=1 for
∫12 x 8 dx ABSACC=10-5.
(iii) Indefinite integral using previous expansion IPARM=2 for
∫1.21.8 x 8 dx ABSACC=10-5.

10.1 Program Text

Program Text (d01arfe.f90)

10.2 Program Data

None.

10.3 Program Results

Program Results (d01arfe.r)

D01 Chapter Contents
D01 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


D01ASF : NAG Library, Mark 26

D01 Chapter Contents
D01 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

D01ASF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

D01ASF calculates an approximation to the sine or the cosine transform of a function g over a,∞:
I = ∫a∞ g x sin ωx dx   or   I = ∫a∞ g x cos ωx dx
(for a user-specified value of ω).

2 Specification

SUBROUTINE D01ASF ( G, A, OMEGA, KEY, EPSABS, RESULT, ABSERR, LIMLST, LST, ERLST, RSLST, IERLST, W, LW, IW, LIW, IFAIL)
INTEGER | KEY, LIMLST, LST, IERLST(LIMLST), LW, IW(LIW), LIW, IFAIL
REAL (KIND=nag_wp) | G, A, OMEGA, EPSABS, RESULT, ABSERR, ERLST(LIMLST), RSLST(LIMLST), W(LW)
EXTERNAL | G

3 Description

D01ASF is based on the QUADPACK routine QAWFE (see Piessens et al. (1983)). It is an adaptive routine, designed to integrate a function of the form g x w x over a semi-infinite interval, where w x is either sin ωx or cos ω x.
Over successive intervals
Ck = a+k-1 c,a+kc ,   k=1,2,…,LST
integration is performed by the same algorithm as is used by D01ANF. The intervals Ck are of constant length
c = 2 ω +1 π/ω ,   ω≠0 ,
where ω represents the largest integer less than or equal to ω. Since c equals an odd number of half periods, the integral contributions over succeeding intervals will alternate in sign when the function g is positive and monotonically decreasing over a,∞. The algorithm, described in Piessens et al. (1983), incorporates a global acceptance criterion (as defined by Malcolm and Simpson (1976)) together with the ε-algorithm (see Wynn (1956)) to perform extrapolation. The local error estimation is described by Piessens et al. (1983).
If ω=0 and KEY=1, the routine uses the same algorithm as D01AMF (with EPSREL=0.0).
In contrast to the other routines in Chapter D01, D01ASF works only with an absolute error tolerance (EPSABS). Over the interval Ck it attempts to satisfy the absolute accuracy requirement
EPSAk = Uk×EPSABS ,
where Uk=1-p p k-1, for k=1,2,… and p=0.9.
However, when difficulties occur during the integration over the kth sub-interval Ck such that the error flag IERLST k is nonzero, the accuracy requirement over subsequent intervals is relaxed. See Piessens et al. (1983) for more details.

4 References

Malcolm M A and Simpson R B (1976) Local versus global strategies for adaptive quadrature ACM Trans. Math. Software 1 129–146
Piessens R, de Doncker–Kapenga E, Überhuber C and Kahaner D (1983) QUADPACK, A Subroutine Package for Automatic Integration Springer–Verlag
Wynn P (1956) On a device for computing the em Sn transformation Math. Tables Aids Comput. 10 91–96

5 Arguments

1:   G – REAL (KIND=nag_wp) FUNCTION, supplied by the user.External Procedure
G must return the value of the function g at a given point X.
The specification of G is:
FUNCTION G ( X)
REAL (KIND=nag_wp) G
REAL (KIND=nag_wp) X
1:   X – REAL (KIND=nag_wp)Input
On entry: the point at which the function g must be evaluated.
G must either be a module subprogram USEd by, or declared as EXTERNAL in, the (sub)program from which D01ASF is called. Arguments denoted as Input must not be changed by this procedure.
2:   A – REAL (KIND=nag_wp)Input
On entry: a, the lower limit of integration.
3:   OMEGA – REAL (KIND=nag_wp)Input
On entry: the argument ω in the weight function of the transform.
4:   KEY – INTEGERInput
On entry: indicates which integral is to be computed.
KEY=1
w x=cos ωx.
KEY=2
w x=sin ωx.
Constraint: KEY=1 or 2.
5:   EPSABS – REAL (KIND=nag_wp)Input
On entry: the absolute accuracy required. If EPSABS is negative, the absolute value is used. See Section 7.
6:   RESULT – REAL (KIND=nag_wp)Output
On exit: the approximation to the integral I.
7:   ABSERR – REAL (KIND=nag_wp)Output
On exit: an estimate of the modulus of the absolute error, which should be an upper bound for I-RESULT.
8:   LIMLST – INTEGERInput
On entry: an upper bound on the number of intervals Ck needed for the integration.
Suggested value: LIMLST=50 is adequate for most problems.
Constraint: LIMLST≥3.
9:   LST – INTEGEROutput
On exit: the number of intervals Ck actually used for the integration.
10:   ERLST LIMLST – REAL (KIND=nag_wp) arrayOutput
On exit: ERLST k contains the error estimate corresponding to the integral contribution over the interval Ck, for k=1,2,…,LST.
11:   RSLST LIMLST – REAL (KIND=nag_wp) arrayOutput
On exit: RSLST k contains the integral contribution over the interval Ck, for k=1,2,…,LST.
12:   IERLST LIMLST – INTEGER arrayOutput
On exit: IERLST k contains the error flag corresponding to RSLST k, for k=1,2,…,LST. See Section 6.
13:   W LW – REAL (KIND=nag_wp) arrayWorkspace
14:   LW – INTEGERInput
On entry: the dimension of the array W as declared in the (sub)program from which D01ASF is called. The value of LW (together with that of LIW) imposes a bound on the number of sub-intervals into which each interval Ck may be divided by the routine. The number of sub-intervals cannot exceed LW/4. The more difficult the integrand, the larger LW should be.
Suggested value: a value in the range 800 to 2000 is adequate for most problems.
Constraint: LW≥4.
15:   IW LIW – INTEGER arrayOutput
On exit: IW 1 contains the maximum number of sub-intervals actually used for integrating over any of the intervals Ck. The rest of the array is used as workspace.
16:   LIW – INTEGERInput
On entry: the dimension of the array IW as declared in the (sub)program from which D01ASF is called. The number of sub-intervals into which each interval Ck may be divided cannot exceed LIW/2.
Suggested value: LIW=LW/2.
Constraint: LIW≥2.
17:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, because for this routine the values of the output arguments may be useful even if IFAIL≠0 on exit, the recommended value is -1. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Note: D01ASF may return useful information for one or more of the following detected errors or warnings.
Errors or warnings detected by the routine:
IFAIL=1
The maximum number of subdivisions allowed with the given workspace has been reached without the accuracy requirements being achieved. Look at the integrand in order to determine the integration difficulties. If the position of a local difficulty within the interval can be determined (e.g., a singularity of the integrand or its derivative, a peak, a discontinuity, etc.) you will probably gain from splitting up the interval at this point and calling D01ASF on the infinite subrange and an appropriate integrator on the finite subrange. Alternatively, consider relaxing the accuracy requirements specified by EPSABS or increasing the amount of workspace.
IFAIL=2
Round-off error prevents the requested tolerance from being achieved. Consider requesting less accuracy.
IFAIL=3
Extremely bad local integrand behaviour causes a very strong subdivision around one (or more) points of the interval. The same advice applies as in the case of IFAIL=1.
IFAIL=4
The requested tolerance cannot be achieved because the extrapolation does not increase the accuracy satisfactorily; the returned result is the best which can be obtained. The same advice applies as in the case of IFAIL=1.
Look at the integrand in order to determine the integration difficulties. If the position of a local difficulty within the interval can be determined (e.g., a singularity of the integrand or its derivative, a peak, a discontinuity etc.) you will probably gain from splitting up the interval at this point and calling D01ASF on the infinite subrange and an appropriate integrator on the finite subrange. Alternatively, consider relaxing the accuracy requirements specified by EPSABS or increasing the amount of workspace.
Please note that divergence can occur with any nonzero value of IFAIL.
IFAIL=5
The integral is probably divergent, or slowly convergent. Please note that divergence can occur with any nonzero value of IFAIL.
IFAIL=6
On entry, | KEY≠1 or 2,
or | LIMLST<3.
IFAIL=7
Bad integration behaviour occurs within one or more of the intervals Ck. Location and type of the difficulty involved can be determined from the vector IERLST.
IFAIL=8
Maximum number of intervals Ck (=LIMLST) allowed has been achieved. Increase the value of LIMLST to allow more cycles.
IFAIL=9
The extrapolation table constructed for convergence acceleration of the series formed by the integral contribution over the intervals Ck, does not converge to the required accuracy.
IFAIL=10
On entry, | LW<4,
or | LIW<2.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.
In the cases IFAIL=7, 8 or 9, additional information about the cause of the error can be obtained from the array IERLST, as follows:
IERLST k=1
The maximum number of subdivisions=min LW/4,LIW/2 has been achieved on the kth interval.
IERLST k=2
Occurrence of round-off error is detected and prevents the tolerance imposed on the kth interval from being achieved.
IERLST k=3
Extremely bad integrand behaviour occurs at some points of the kth interval.
IERLST k=4
The integration procedure over the kth interval does not converge (to within the required accuracy) due to round-off in the extrapolation procedure invoked on this interval. It is assumed that the result on this interval is the best which can be obtained.
IERLST k=5
The integral over the kth interval is probably divergent or slowly convergent. It must be noted that divergence can occur with any other value of IERLST k.

7 Accuracy

D01ASF cannot guarantee, but in practice usually achieves, the following accuracy:
I-RESULT≤EPSABS,
where EPSABS is the user-specified absolute error tolerance. Moreover, it returns the quantity ABSERR, which, in normal circumstances, satisfies
I-RESULT≤ABSERR≤EPSABS.

8 Parallelism and Performance

D01ASF is not threaded in any implementation.

9 Further Comments

None.

10 Example

This example computes
∫0∞ 1 x cos πx/2 dx .

10.1 Program Text

Program Text (d01asfe.f90)

10.2 Program Data

None.

10.3 Program Results

Program Results (d01asfe.r)

D01 Chapter Contents
D01 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


D01ATF : NAG Library, Mark 26

D01 Chapter Contents
D01 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

D01ATF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

D01ATF is a general purpose integrator which calculates an approximation to the integral of a function f x over a finite interval a,b:
I= ∫ab f x dx .

2 Specification

SUBROUTINE D01ATF ( F, A, B, EPSABS, EPSREL, RESULT, ABSERR, W, LW, IW, LIW, IFAIL)
INTEGER | LW, IW(LIW), LIW, IFAIL
REAL (KIND=nag_wp) | A, B, EPSABS, EPSREL, RESULT, ABSERR, W(LW)
EXTERNAL | F

3 Description

D01ATF is based on the QUADPACK routine QAGS (see Piessens et al. (1983)). It is an adaptive routine, using the Gauss 10-point and Kronrod 21-point rules. The algorithm, described in de Doncker (1978), incorporates a global acceptance criterion (as defined by Malcolm and Simpson (1976)) together with the ε-algorithm (see Wynn (1956)) to perform extrapolation. The local error estimation is described in Piessens et al. (1983).
The routine is suitable as a general purpose integrator, and can be used when the integrand has singularities, especially when these are of algebraic or logarithmic type.
D01ATF requires a subroutine to evaluate the integrand at an array of different points and is therefore amenable to parallel execution. Otherwise the algorithm is identical to that used by D01AJF.

4 References

de Doncker E (1978) An adaptive extrapolation algorithm for automatic integration ACM SIGNUM Newsl. 13(2) 12–18
Malcolm M A and Simpson R B (1976) Local versus global strategies for adaptive quadrature ACM Trans. Math. Software 1 129–146
Piessens R, de Doncker–Kapenga E, Überhuber C and Kahaner D (1983) QUADPACK, A Subroutine Package for Automatic Integration Springer–Verlag
Wynn P (1956) On a device for computing the em Sn transformation Math. Tables Aids Comput. 10 91–96

5 Arguments

1:   F – SUBROUTINE, supplied by the user.External Procedure
F must return the values of the integrand f at a set of points.
The specification of F is:
SUBROUTINE F ( X, FV, N)
INTEGER | N
REAL (KIND=nag_wp) | X(N), FV(N)
1:   X N – REAL (KIND=nag_wp) arrayInput
On entry: the points at which the integrand f must be evaluated.
2:   FV N – REAL (KIND=nag_wp) arrayOutput
On exit: FV j must contain the value of f at the point X j, for j=1,2,…,N.
3:   N – INTEGERInput
On entry: the number of points at which the integrand is to be evaluated. The actual value of N is always 21.
F must either be a module subprogram USEd by, or declared as EXTERNAL in, the (sub)program from which D01ATF is called. Arguments denoted as Input must not be changed by this procedure.
2:   A – REAL (KIND=nag_wp)Input
On entry: a, the lower limit of integration.
3:   B – REAL (KIND=nag_wp)Input
On entry: b, the upper limit of integration. It is not necessary that a<b.
4:   EPSABS – REAL (KIND=nag_wp)Input
On entry: the absolute accuracy required. If EPSABS is negative, the absolute value is used. See Section 7.
5:   EPSREL – REAL (KIND=nag_wp)Input
On entry: the relative accuracy required. If EPSREL is negative, the absolute value is used. See Section 7.
6:   RESULT – REAL (KIND=nag_wp)Output
On exit: the approximation to the integral I.
7:   ABSERR – REAL (KIND=nag_wp)Output
On exit: an estimate of the modulus of the absolute error, which should be an upper bound for I-RESULT.
8:   W LW – REAL (KIND=nag_wp) arrayOutput
On exit: details of the computation see Section 9 for more information.
9:   LW – INTEGERInput
On entry: the dimension of the array W as declared in the (sub)program from which D01ATF is called. The value of LW (together with that of LIW) imposes a bound on the number of sub-intervals into which the interval of integration may be divided by the routine. The number of sub-intervals cannot exceed LW/4. The more difficult the integrand, the larger LW should be.
Suggested value: LW=800 to 2000 is adequate for most problems.
Constraint: LW≥4.
10:   IW LIW – INTEGER arrayOutput
On exit: IW 1 contains the actual number of sub-intervals used. The rest of the array is used as workspace.
11:   LIW – INTEGERInput
On entry: the dimension of the array IW as declared in the (sub)program from which D01ATF is called. The number of sub-intervals into which the interval of integration may be divided cannot exceed LIW.
Suggested value: LIW=LW/4.
Constraint: LIW≥1.
12:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, because for this routine the values of the output arguments may be useful even if IFAIL≠0 on exit, the recommended value is -1. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Note: D01ATF may return useful information for one or more of the following detected errors or warnings.
Errors or warnings detected by the routine:
IFAIL=1
The maximum number of subdivisions allowed with the given workspace has been reached without the accuracy requirements being achieved. Look at the integrand in order to determine the integration difficulties. If the position of a local difficulty within the interval can be determined (e.g., a singularity of the integrand or its derivative, a peak, a discontinuity, etc.) you will probably gain from splitting up the interval at this point and calling the integrator on the subranges. If necessary, another integrator, which is designed for handling the type of difficulty involved, must be used. Alternatively, consider relaxing the accuracy requirements specified by EPSABS and EPSREL, or increasing the amount of workspace.
IFAIL=2
Round-off error prevents the requested tolerance from being achieved. Consider requesting less accuracy.
IFAIL=3
Extremely bad local integrand behaviour causes a very strong subdivision around one (or more) points of the interval. The same advice applies as in the case of IFAIL=1.
IFAIL=4
The requested tolerance cannot be achieved because the extrapolation does not increase the accuracy satisfactorily; the returned result is the best which can be obtained. The same advice applies as in the case of IFAIL=1.
IFAIL=5
The integral is probably divergent, or slowly convergent. Please note that divergence can occur with any nonzero value of IFAIL.
IFAIL=6
On entry, | LW<4,
or | LIW<1.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

D01ATF cannot guarantee, but in practice usually achieves, the following accuracy:
I-RESULT ≤ tol ,
where
tol = max EPSABS , EPSREL × I ,
and EPSABS and EPSREL are user-specified absolute and relative error tolerances. Moreover, it returns the quantity ABSERR which, in normal circumstances, satisfies
I-RESULT ≤ ABSERR ≤ tol .

8 Parallelism and Performance

D01ATF is not threaded in any implementation.

9 Further Comments

If IFAIL≠0 on exit, then you may wish to examine the contents of the array W, which contains the end points of the sub-intervals used by D01ATF along with the integral contributions and error estimates over the sub-intervals.
Specifically, for i=1,2,…,n, let ri denote the approximation to the value of the integral over the sub-interval ai,bi in the partition of a,b and ei be the corresponding absolute error estimate. Then, ∫ ai bi f x dx ≃ ri and RESULT = ∑ i=1 n ri , unless D01ATF terminates while testing for divergence of the integral (see Section 3.4.3 of Piessens et al. (1983)). In this case, RESULT (and ABSERR) are taken to be the values returned from the extrapolation process. The value of n is returned in IW 1, and the values ai, bi, ei and ri are stored consecutively in the array W, that is:
  • ai=W i,
  • bi=W n+i,
  • ei=W 2 n+i and
  • ri=W 3 n+i.

10 Example

This example computes
∫ 0 2 π x sin 30 x 1 - x/2 π 2 dx .

10.1 Program Text

Program Text (d01atfe.f90)

10.2 Program Data

None.

10.3 Program Results

Program Results (d01atfe.r)

D01 Chapter Contents
D01 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


D01AUF : NAG Library, Mark 26

D01 Chapter Contents
D01 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

D01AUF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

D01AUF is an adaptive integrator, especially suited to oscillating, nonsingular integrands, which calculates an approximation to the integral of a function f x over a finite interval a,b:
I= ∫ab f x dx .

2 Specification

SUBROUTINE D01AUF ( F, A, B, KEY, EPSABS, EPSREL, RESULT, ABSERR, W, LW, IW, LIW, IFAIL)
INTEGER | KEY, LW, IW(LIW), LIW, IFAIL
REAL (KIND=nag_wp) | A, B, EPSABS, EPSREL, RESULT, ABSERR, W(LW)
EXTERNAL | F

3 Description

D01AUF is based on the QUADPACK routine QAG (see Piessens et al. (1983)). It is an adaptive routine, offering a choice of six Gauss–Kronrod rules. A global acceptance criterion (as defined by Malcolm and Simpson (1976)) is used. The local error estimation is described in Piessens et al. (1983).
Because D01AUF is based on integration rules of high order, it is especially suitable for nonsingular oscillating integrands.
D01AUF requires a subroutine to evaluate the integrand at an array of different points and is therefore amenable to parallel execution. Otherwise this algorithm with KEY=6 is identical to that used by D01AKF.

4 References

Malcolm M A and Simpson R B (1976) Local versus global strategies for adaptive quadrature ACM Trans. Math. Software 1 129–146
Piessens R (1973) An algorithm for automatic integration Angew. Inf. 15 399–401
Piessens R, de Doncker–Kapenga E, Überhuber C and Kahaner D (1983) QUADPACK, A Subroutine Package for Automatic Integration Springer–Verlag

5 Arguments

1:   F – SUBROUTINE, supplied by the user.External Procedure
F must return the values of the integrand f at a set of points.
The specification of F is:
SUBROUTINE F ( X, FV, N)
INTEGER | N
REAL (KIND=nag_wp) | X(N), FV(N)
1:   X N – REAL (KIND=nag_wp) arrayInput
On entry: the points at which the integrand f must be evaluated.
2:   FV N – REAL (KIND=nag_wp) arrayOutput
On exit: FV j must contain the value of f at the point X j, for j=1,2,…,N.
3:   N – INTEGERInput
On entry: the number of points at which the integrand is to be evaluated. The actual value of N is equal to the number of points in the Kronrod rule (see specification of KEY).
F must either be a module subprogram USEd by, or declared as EXTERNAL in, the (sub)program from which D01AUF is called. Arguments denoted as Input must not be changed by this procedure.
2:   A – REAL (KIND=nag_wp)Input
On entry: a, the lower limit of integration.
3:   B – REAL (KIND=nag_wp)Input
On entry: b, the upper limit of integration. It is not necessary that a<b.
4:   KEY – INTEGERInput
On entry: indicates which integration rule is to be used.
KEY=1
For the Gauss 7-point and Kronrod 15-point rule.
KEY=2
For the Gauss 10-point and Kronrod 21-point rule.
KEY=3
For the Gauss 15-point and Kronrod 31-point rule.
KEY=4
For the Gauss 20-point and Kronrod 41-point rule.
KEY=5
For the Gauss 25-point and Kronrod 51-point rule.
KEY=6
For the Gauss 30-point and Kronrod 61-point rule.
Suggested value: KEY=6.
Constraint: KEY=1, 2, 3, 4, 5 or 6.
5:   EPSABS – REAL (KIND=nag_wp)Input
On entry: the absolute accuracy required. If EPSABS is negative, the absolute value is used. See Section 7.
6:   EPSREL – REAL (KIND=nag_wp)Input
On entry: the relative accuracy required. If EPSREL is negative, the absolute value is used. See Section 7.
7:   RESULT – REAL (KIND=nag_wp)Output
On exit: the approximation to the integral I.
8:   ABSERR – REAL (KIND=nag_wp)Output
On exit: an estimate of the modulus of the absolute error, which should be an upper bound for I-RESULT.
9:   W LW – REAL (KIND=nag_wp) arrayOutput
On exit: details of the computation see Section 9 for more information.
10:   LW – INTEGERInput
On entry: the dimension of the array W as declared in the (sub)program from which D01AUF is called. The value of LW (together with that of LIW) imposes a bound on the number of sub-intervals into which the interval of integration may be divided by the routine. The number of sub-intervals cannot exceed LW/4. The more difficult the integrand, the larger LW should be.
Suggested value: LW=800 to 2000 is adequate for most problems.
Constraint: LW≥4.
11:   IW LIW – INTEGER arrayOutput
On exit: IW 1 contains the actual number of sub-intervals used. The rest of the array is used as workspace.
12:   LIW – INTEGERInput
On entry: the dimension of the array IW as declared in the (sub)program from which D01AUF is called.
The number of sub-intervals into which the interval of integration may be divided cannot exceed LIW.
Suggested value: LIW=LW/4.
Constraint: LIW≥1.
13:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, because for this routine the values of the output arguments may be useful even if IFAIL≠0 on exit, the recommended value is -1. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Note: D01AUF may return useful information for one or more of the following detected errors or warnings.
Errors or warnings detected by the routine:
IFAIL=1
The maximum number of subdivisions allowed with the given workspace has been reached without the accuracy requirements being achieved. Look at the integrand in order to determine the integration difficulties. If necessary, another integrator, which is designed for handling the type of difficulty involved, must be used. Alternatively, consider relaxing the accuracy requirements specified by EPSABS and EPSREL, or increasing the amount of workspace.
IFAIL=2
Round-off error prevents the requested tolerance from being achieved. Consider requesting less accuracy.
IFAIL=3
Extremely bad local integrand behaviour causes a very strong subdivision around one (or more) points of the interval. The same advice applies as in the case of IFAIL=1.
IFAIL=4
On entry, KEY≠1, 2, 3, 4, 5 or 6.
IFAIL=5
On entry, | LW<4,
or | LIW<1.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

D01AUF cannot guarantee, but in practice usually achieves, the following accuracy:
I-RESULT ≤ tol ,
where
tol=max EPSABS,EPSREL×I ,
and EPSABS and EPSREL are user-specified absolute and relative error tolerances. Moreover, it returns the quantity ABSERR which, in normal circumstances, satisfies
I-RESULT≤ABSERR≤tol.

8 Parallelism and Performance

D01AUF is not threaded in any implementation.

9 Further Comments

If IFAIL≠0 on exit, then you may wish to examine the contents of the array W, which contains the end points of the sub-intervals used by D01AUF along with the integral contributions and error estimates over these sub-intervals.
Specifically, for i=1,2,…,n, let ri denote the approximation to the value of the integral over the sub-interval ai,bi in the partition of a,b and ei be the corresponding absolute error estimate. Then, ∫ ai bi f x dx ≃ ri and RESULT = ∑ i=1 n ri . The value of n is returned in IW 1, and the values ai, bi, ei and ri are stored consecutively in the array W, that is:
  • ai=W i,
  • bi=W n+i,
  • ei=W 2 n+i and
  • ri=W 3 n+i.

10 Example

This example computes
∫ 0 2 π x sin 30 x cos⁡x dx .

10.1 Program Text

Program Text (d01aufe.f90)

10.2 Program Data

None.

10.3 Program Results

Program Results (d01aufe.r)

D01 Chapter Contents
D01 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


D01BCF : NAG Library, Mark 26

D01 Chapter Contents
D01 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

D01BCF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

D01BCF returns the weights (normal or adjusted) and abscissae for a Gaussian integration rule with a specified number of abscissae. Six different types of Gauss rule are allowed.

2 Specification

SUBROUTINE D01BCF ( ITYPE, A, B, C, D, N, WEIGHT, ABSCIS, IFAIL)
INTEGER | ITYPE, N, IFAIL
REAL (KIND=nag_wp) | A, B, C, D, WEIGHT(N), ABSCIS(N)

3 Description

D01BCF returns the weights wi and abscissae xi for use in the summation
S=∑i=1 n wi f xi
which approximates a definite integral (see Davis and Rabinowitz (1975) or Stroud and Secrest (1966)). The following types are provided:
(a) Gauss–Legendre
S≃∫ab f x dx,   exact for ​f x=P 2 n- 1 x.
Constraint: b>a.
(b) Gauss–Jacobi
normal weights:
S≃∫ab b-x cx-a d f x dx,   exact for ​f x=P 2 n-1 x,
adjusted weights:
S≃∫ab f x dx,   exact for ​f x=b-x cx-a d P 2 n- 1 x.
Constraint: c>-1, d>-1, b>a.
(c) Exponential Gauss
normal weights:
S≃ ∫ab x- a+b 2 c f x dx,   exact for ​f x=P 2 n-1 x,
adjusted weights:
S ≃ ∫ab f x dx,   exact for ​f x = x-a+b 2 c P 2 n- 1 x.
Constraint: c>-1, b>a.
(d) Gauss–Laguerre
normal weights:
S ≃∫a∞x-a ce-bx f x dx b>0, ≃∫-∞a x-a ce-bx f x dx b<0,   exact for ​f x=P 2 n-1 x,
adjusted weights:
S ≃∫a∞ f x dx  b> 0, ≃∫-∞a f x dx  b< 0,   exact for ​f x=x-a ce-bx P 2 n- 1 x.
Constraint: c>-1, b≠0.
(e) Gauss–Hermite
normal weights:
S≃∫-∞ +∞x-a ce-b x-a 2 f x dx,   exact for ​f x=P 2 n-1 x,
adjusted weights:
S≃∫-∞ +∞ f x dx,   exact for ​f x=x-a c e-b x-a 2 P 2 n- 1 x.
Constraint: c>-1, b>0.
(f) Rational Gauss
normal weights:
S ≃∫a∞x-a cx+b d f x dx a+b>0, ≃∫-∞a x-a cx+b d f x dx a+b<0,   exact for ​f x=P 2 n-1 1 x+b ,
adjusted weights:
S ≃∫a∞ f x dx  a+b> 0, ≃∫-∞a f x dx  a+b< 0,   exact for ​f x=x-a cx+b d P 2 n- 1 1 x+b .
Constraint: c>-1, d>c+1, a+b≠0.
In the above formulae, P 2 n-1 x stands for any polynomial of degree 2 n-1 or less in x.
The method used to calculate the abscissae involves finding the eigenvalues of the appropriate tridiagonal matrix (see Golub and Welsch (1969)). The weights are then determined by the formula
wi= ∑j=0 n-1 Pj* xi 2 -1
where Pj*x is the jth orthogonal polynomial with respect to the weight function over the appropriate interval.
The weights and abscissae produced by D01BCF may be passed to D01FBF, which will evaluate the summations in one or more dimensions.

4 References

Davis P J and Rabinowitz P (1975) Methods of Numerical Integration Academic Press
Golub G H and Welsch J H (1969) Calculation of Gauss quadrature rules Math. Comput. 23 221–230
Stroud A H and Secrest D (1966) Gaussian Quadrature Formulas Prentice–Hall

5 Arguments

1:   ITYPE – INTEGERInput
On entry: indicates the type of quadrature rule.
ITYPE=0
Gauss–Legendre, with normal weights.
ITYPE=1
Gauss–Jacobi, with normal weights.
ITYPE=-1
Gauss–Jacobi, with adjusted weights.
ITYPE=2
Exponential Gauss, with normal weights.
ITYPE=-2
Exponential Gauss, with adjusted weights.
ITYPE=3
Gauss–Laguerre, with normal weights.
ITYPE=-3
Gauss–Laguerre, with adjusted weights.
ITYPE=4
Gauss–Hermite, with normal weights.
ITYPE=-4
Gauss–Hermite, with adjusted weights.
ITYPE=5
Rational Gauss, with normal weights.
ITYPE=-5
Rational Gauss, with adjusted weights.
Constraint: ITYPE=0, 1, -1, 2, -2, 3, -3, 4, -4, 5 or -5.
2:   A – REAL (KIND=nag_wp)Input
3:   B – REAL (KIND=nag_wp)Input
4:   C – REAL (KIND=nag_wp)Input
5:   D – REAL (KIND=nag_wp)Input
On entry: the parameters a, b, c and d which occur in the quadrature formulae. C is not used if ITYPE=0; D is not used unless ITYPE=1, -1, 5 or -5. For some rules C and D must not be too large (see Section 6).
6:   N – INTEGERInput
On entry: n, the number of weights and abscissae to be returned. If ITYPE=-2 or -4 and C≠0.0, an odd value of N may raise problems (see IFAIL=6).
Constraint: N>0.
7:   WEIGHT N – REAL (KIND=nag_wp) arrayOutput
On exit: the N weights.
8:   ABSCIS N – REAL (KIND=nag_wp) arrayOutput
On exit: the N abscissae.
9:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
The algorithm for computing eigenvalues of a tridiagonal matrix has failed to obtain convergence. If the soft fail option is used, the values of the weights and abscissae on return are indeterminate.
IFAIL=2
On entry, | N<1,
or | ITYPE<-5,
or | ITYPE>5.
If the soft fail option is used, weights and abscissae are returned as zero.
IFAIL=3
A, B, C or D is not in the allowed range:
  • if ITYPE=0, A≥B;
  • if ITYPE=±1, A≥B or C≤-1.0 or D≤-1.0 or C+D+2.0>gmax;
  • if ITYPE=±2, A≥B or C≤-1.0;
  • if ITYPE=±3, B=0.0 or C≤-1.0 or C+1.0>gmax;
  • if ITYPE=±4, B≤0.0 or C≤-1.0 or C+1.0/2.0>gmax;
  • if ITYPE=±5, A+B=0.0 or C≤-1.0 or D≤C+1.0.
Here gmax is the (machine-dependent) largest integer value such that Γ gmax can be computed without overflow (see the Users' Note for your implementation for S14AAF).
If the soft fail option is used, weights and abscissae are returned as zero.
IFAIL=4
One or more of the weights are larger than rmax, the largest floating-point number on this machine. rmax is given by the function X02ALF. If the soft fail option is used, the overflowing weights are returned as rmax. Possible solutions are to use a smaller value of N; or, if using adjusted weights, to change to normal weights.
IFAIL=5
One or more of the weights are too small to be distinguished from zero on this machine. If the soft fail option is used, the underflowing weights are returned as zero, which may be a usable approximation. Possible solutions are to use a smaller value of N; or, if using normal weights, to change to adjusted weights.
IFAIL=6
Exponential Gauss or Gauss–Hermite adjusted weights with N odd and C≠0.0. Theoretically, in these cases:
  • for C>0.0, the central adjusted weight is infinite, and the exact function f x is zero at the central abscissa.
  • for C<0.0, the central adjusted weight is zero, and the exact function f x is infinite at the central abscissa.
In either case, the contribution of the central abscissa to the summation is indeterminate.
In practice, the central weight may not have overflowed or underflowed, if there is sufficient rounding error in the value of the central abscissa.
If the soft fail option is used, the weights and abscissa returned may be usable; you must be particularly careful not to ‘round’ the central abscissa to its true value without simultaneously ‘rounding’ the central weight to zero or ∞ as appropriate, or the summation will suffer. It would be preferable to use normal weights, if possible.
Note: remember that, when switching from normal weights to adjusted weights or vice versa, redefinition of f x is involved.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

The accuracy depends mainly on n, with increasing loss of accuracy for larger values of n. Typically, one or two decimal digits may be lost from machine accuracy with n≃20, and three or four decimal digits may be lost for n≃100.

8 Parallelism and Performance

D01BCF makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The major portion of the time is taken up during the calculation of the eigenvalues of the appropriate tridiagonal matrix, where the time is roughly proportional to n 3.

10 Example

This example returns the abscissae and (adjusted) weights for the seven-point Gauss–Laguerre formula.

10.1 Program Text

Program Text (d01bcfe.f90)

10.2 Program Data

None.

10.3 Program Results

Program Results (d01bcfe.r)

GnuplotProduced by GNUPLOT 4.6 patchlevel 3 0 1 2 3 4 5 6 7 8 9 −5 0 5 10 15 20 25 Weights at Abscissae x Example Program Abscissae and Weights for the 7-point Gauss-Laguerre Formula (a=0, b=1) gnuplot_plot_1
D01 Chapter Contents
D01 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


D01BDF : NAG Library, Mark 26

D01 Chapter Contents
D01 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

D01BDF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

D01BDF calculates an approximation to the integral of a function over a finite interval a,b:
I= ∫ab f x dx .
It is non-adaptive and as such is recommended for the integration of ‘smooth’ functions. These exclude integrands with singularities, derivative singularities or high peaks on a,b, or which oscillate too strongly on a,b.

2 Specification

SUBROUTINE D01BDF ( F, A, B, EPSABS, EPSREL, RESULT, ABSERR)
REAL (KIND=nag_wp) | F, A, B, EPSABS, EPSREL, RESULT, ABSERR
EXTERNAL | F

3 Description

D01BDF is based on the QUADPACK routine QNG (see Piessens et al. (1983)). It is a non-adaptive routine which uses as its basic rules, the Gauss 10-point and 21-point formulae. If the accuracy criterion is not met, formulae using 43 and 87 points are used successively, stopping whenever the accuracy criterion is satisfied.
This routine is designed for smooth integrands only.

4 References

Patterson T N L (1968) The Optimum addition of points to quadrature formulae Math. Comput. 22 847–856
Piessens R, de Doncker–Kapenga E, Überhuber C and Kahaner D (1983) QUADPACK, A Subroutine Package for Automatic Integration Springer–Verlag

5 Arguments

1:   F – REAL (KIND=nag_wp) FUNCTION, supplied by the user.External Procedure
F must return the value of the integrand f at a given point.
The specification of F is:
FUNCTION F ( X)
REAL (KIND=nag_wp) F
REAL (KIND=nag_wp) X
1:   X – REAL (KIND=nag_wp)Input
On entry: the point at which the integrand f must be evaluated.
F must either be a module subprogram USEd by, or declared as EXTERNAL in, the (sub)program from which D01BDF is called. Arguments denoted as Input must not be changed by this procedure.
2:   A – REAL (KIND=nag_wp)Input
On entry: a, the lower limit of integration.
3:   B – REAL (KIND=nag_wp)Input
On entry: b, the upper limit of integration. It is not necessary that a<b.
4:   EPSABS – REAL (KIND=nag_wp)Input
On entry: the absolute accuracy required. If EPSABS is negative, the absolute value is used. See Section 7.
5:   EPSREL – REAL (KIND=nag_wp)Input
On entry: the relative accuracy required. If EPSREL is negative, the absolute value is used. See Section 7.
6:   RESULT – REAL (KIND=nag_wp)Output
On exit: the approximation to the integral I.
7:   ABSERR – REAL (KIND=nag_wp)Output
On exit: an estimate of the modulus of the absolute error, which should be an upper bound for I-RESULT.

6 Error Indicators and Warnings

There are no specific errors detected by D01BDF. However, if ABSERR is greater than
max EPSABS,EPSREL×RESULT
this indicates that the routine has probably failed to achieve the requested accuracy within 87 function evaluations.

7 Accuracy

D01BDF attempts to compute an approximation, RESULT, such that:
I-RESULT ≤ tol ,
where
tol = max EPSABS , EPSREL × I ,
and EPSABS and EPSREL are user-specified absolute and relative error tolerances. There can be no guarantee that this is achieved, and you are advised to subdivide the interval if you have any doubts about the accuracy obtained. Note that ABSERR contains an estimated bound on I-RESULT.

8 Parallelism and Performance

D01BDF is not threaded in any implementation.

9 Further Comments

The time taken by D01BDF depends on the integrand and the accuracy required.

10 Example

This example computes
∫ 0 1 x 2 sin 10 πx dx .

10.1 Program Text

Program Text (d01bdfe.f90)

10.2 Program Data

None.

10.3 Program Results

Program Results (d01bdfe.r)

D01 Chapter Contents
D01 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


D01 Chapter Contents : NAG Library Manual, Mark 26

D01 Chapter Introduction
NAG Library Manual

NAG Library Chapter Contents

D01 – Quadrature

D01 Chapter Introduction – a description of the Chapter and an overview of the algorithms available

Routine Name | Mark of Introduction | Purpose
D01AHF Example Text Example Data | 8 | nagf_quad_1d_fin_well One-dimensional quadrature, adaptive, finite interval, strategy due to Patterson, suitable for well-behaved integrands
D01AJF Example Text | 8 | nagf_quad_1d_fin_bad One-dimensional quadrature, adaptive, finite interval, strategy due to Piessens and de Doncker, allowing for badly behaved integrands
D01AKF Example Text | 8 | nagf_quad_1d_fin_osc One-dimensional quadrature, adaptive, finite interval, method suitable for oscillating functions
D01ALF Example Text | 8 | nagf_quad_1d_fin_sing One-dimensional quadrature, adaptive, finite interval, allowing for singularities at user-specified break-points
D01AMF Example Text | 8 | nagf_quad_1d_inf One-dimensional quadrature, adaptive, infinite or semi-infinite interval
D01ANF Example Text | 8 | nagf_quad_1d_fin_wtrig One-dimensional quadrature, adaptive, finite interval, weight function cos ωx or sin ωx
D01APF Example Text | 8 | nagf_quad_1d_fin_wsing One-dimensional quadrature, adaptive, finite interval, weight function with end-point singularities of algebraico-logarithmic type
D01AQF Example Text | 8 | nagf_quad_1d_fin_wcauchy One-dimensional quadrature, adaptive, finite interval, weight function 1/x-c, Cauchy principal value (Hilbert transform)
D01ARF Example Text | 10 | nagf_quad_1d_indef One-dimensional quadrature, non-adaptive, finite interval with provision for indefinite integrals
D01ASF Example Text | 13 | nagf_quad_1d_inf_wtrig One-dimensional quadrature, adaptive, semi-infinite interval, weight function cos ωx or sin ωx
D01ATF Example Text | 13 | nagf_quad_1d_fin_bad_vec One-dimensional quadrature, adaptive, finite interval, variant of D01AJF efficient on vector machines
D01AUF Example Text | 13 | nagf_quad_1d_fin_osc_vec One-dimensional quadrature, adaptive, finite interval, variant of D01AKF efficient on vector machines
D01BCF Example Text Example Plot | 8 | nagf_quad_1d_gauss_wgen Calculation of weights and abscissae for Gaussian quadrature rules, general choice of rule
D01BDF Example Text | 8 | nagf_quad_1d_fin_smooth One-dimensional quadrature, non-adaptive, finite interval
D01DAF Example Text | 5 | nagf_quad_2d_fin Two-dimensional quadrature, finite region
D01EAF Example Text Example Plot | 12 | nagf_quad_md_adapt_multi Multidimensional adaptive quadrature over hyper-rectangle, multiple integrands
D01ESF Example Text | 25 | nagf_quad_md_sgq_multi_vec Multi-dimensional quadrature using sparse grids
D01FBF Example Text | 8 | nagf_quad_md_gauss Multidimensional Gaussian quadrature over hyper-rectangle
D01FCF Example Text | 8 | nagf_quad_md_adapt Multidimensional adaptive quadrature over hyper-rectangle
D01FDF Example Text | 10 | nagf_quad_md_sphere Multidimensional quadrature, Sag–Szekeres method, general product region or n-sphere
D01GAF Example Text Example Data | 5 | nagf_quad_1d_data One-dimensional quadrature, integration of function defined by data values, Gill–Miller method
D01GBF Example Text | 10 | nagf_quad_md_mcarlo Multidimensional quadrature over hyper-rectangle, Monte–Carlo method
D01GCF Example Text | 10 | nagf_quad_md_numth Multidimensional quadrature, general product region, number-theoretic method
D01GDF Example Text | 14 | nagf_quad_md_numth_vec Multidimensional quadrature, general product region, number-theoretic method, variant of D01GCF efficient on vector machines
D01GYF Example Text | 10 | nagf_quad_md_numth_coeff_prime Korobov optimal coefficients for use in D01GCF or D01GDF, when number of points is prime
D01GZF Example Text | 10 | nagf_quad_md_numth_coeff_2prime Korobov optimal coefficients for use in D01GCF or D01GDF, when number of points is product of two primes
D01JAF Example Text | 10 | nagf_quad_md_sphere_bad Multidimensional quadrature over an n-sphere, allowing for badly behaved integrands
D01PAF Example Text | 10 | nagf_quad_md_simplex Multidimensional quadrature over an n-simplex
D01RAF Example Text | 24 | nagf_quad_1d_gen_vec_multi_rcomm One-dimensional quadrature, adaptive, finite interval, multiple integrands, vectorized abscissae, reverse communication
D01RBF | 24 | nagf_quad_withdraw_1d_gen_vec_multi_diagnostic Diagnostic routine for D01RAF Note: this routine is scheduled for withdrawal at Mark 27, see Advice on Replacement Calls for Withdrawn/Superseded Routines for further information.
D01RCF | 24 | nagf_quad_1d_gen_vec_multi_dimreq Determine required array dimensions for D01RAF
D01RGF Example Text | 24 | nagf_quad_1d_fin_gonnet_vec One-dimensional quadrature, adaptive, finite interval, strategy due to Gonnet, allowing for badly behaved integrands
D01TBF Example Text | 24 | nagf_quad_1d_gauss_wres Pre-computed weights and abscissae for Gaussian quadrature rules, restricted choice of rule
D01TDF Example Text | 26 | nagf_quad_1d_gauss_wrec Calculation of weights and abscissae for Gaussian quadrature rules, method of Golub and Welsch
D01TEF Example Text | 26 | nagf_quad_1d_gauss_recm Generates recursion coefficients needed by D01TDF to calculate a Gaussian quadrature rule
D01UAF Example Text | 24 | nagf_quad_1d_gauss_vec One-dimensional Gaussian quadrature, choice of weight functions (vectorized)
D01UBF Example Text | 26 | nagf_quad_1d_inf_exp_wt Non-automatic routine to evaluate ∫0∞exp-x 2 f x dx
D01ZKF | 24 | nagf_quad_opt_set Option setting routine
D01ZLF | 24 | nagf_quad_opt_get Option getting routine
D01 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


D01DAF : NAG Library, Mark 26

D01 Chapter Contents
D01 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

D01DAF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

D01DAF attempts to evaluate a double integral to a specified absolute accuracy by repeated applications of the method described by Patterson (1968) and Patterson (1969).

2 Specification

SUBROUTINE D01DAF ( YA, YB, PHI1, PHI2, F, ABSACC, ANS, NPTS, IFAIL)
INTEGER | NPTS, IFAIL
REAL (KIND=nag_wp) | YA, YB, PHI1, PHI2, F, ABSACC, ANS
EXTERNAL | PHI1, PHI2, F

3 Description

D01DAF attempts to evaluate a definite integral of the form
I= ∫ab ∫ ϕ 1 y ϕ 2 y f x,y dx dy
where a and b are constants and ϕ 1 y and ϕ 2 y are functions of the variable y.
The integral is evaluated by expressing it as
I=∫ab F y dy,   where  F y= ∫ ϕ 1 y ϕ 2 y f x,y dx.
Both the outer integral I and the inner integrals F y are evaluated by the method, described by Patterson (1968) and Patterson (1969), of the optimum addition of points to Gauss quadrature formulae.
This method uses a family of interlacing common point formulae. Beginning with the 3-point Gauss rule, formulae using 7, 15, 31, 63, 127 and finally 255 points are derived. Each new formula contains all the points of the earlier formulae so that no function evaluations are wasted. Each integral is evaluated by applying these formulae successively until two results are obtained which differ by less than the specified absolute accuracy.

4 References

Patterson T N L (1968) On some Gauss and Lobatto based integration formulae Math. Comput. 22 877–881
Patterson T N L (1969) The optimum addition of points to quadrature formulae, errata Math. Comput. 23 892

5 Arguments

1:   YA – REAL (KIND=nag_wp)Input
On entry: a, the lower limit of the integral.
2:   YB – REAL (KIND=nag_wp)Input
On entry: b, the upper limit of the integral. It is not necessary that a<b.
3:   PHI1 – REAL (KIND=nag_wp) FUNCTION, supplied by the user.External Procedure
PHI1 must return the lower limit of the inner integral for a given value of y.
The specification of PHI1 is:
FUNCTION PHI1 ( Y)
REAL (KIND=nag_wp) PHI1
REAL (KIND=nag_wp) Y
1:   Y – REAL (KIND=nag_wp)Input
On entry: the value of y for which the lower limit must be evaluated.
PHI1 must either be a module subprogram USEd by, or declared as EXTERNAL in, the (sub)program from which D01DAF is called. Arguments denoted as Input must not be changed by this procedure.
4:   PHI2 – REAL (KIND=nag_wp) FUNCTION, supplied by the user.External Procedure
PHI2 must return the upper limit of the inner integral for a given value of y.
The specification of PHI2 is:
FUNCTION PHI2 ( Y)
REAL (KIND=nag_wp) PHI2
REAL (KIND=nag_wp) Y
1:   Y – REAL (KIND=nag_wp)Input
On entry: the value of y for which the upper limit must be evaluated.
PHI2 must either be a module subprogram USEd by, or declared as EXTERNAL in, the (sub)program from which D01DAF is called. Arguments denoted as Input must not be changed by this procedure.
5:   F – REAL (KIND=nag_wp) FUNCTION, supplied by the user.External Procedure
F must return the value of the integrand f at a given point.
The specification of F is:
FUNCTION F ( X, Y)
REAL (KIND=nag_wp) F
REAL (KIND=nag_wp) X, Y
1:   X – REAL (KIND=nag_wp)Input
2:   Y – REAL (KIND=nag_wp)Input
On entry: the coordinates of the point x,y at which the integrand f must be evaluated.
F must either be a module subprogram USEd by, or declared as EXTERNAL in, the (sub)program from which D01DAF is called. Arguments denoted as Input must not be changed by this procedure.
6:   ABSACC – REAL (KIND=nag_wp)Input
On entry: the absolute accuracy requested.
7:   ANS – REAL (KIND=nag_wp)Output
On exit: the estimated value of the integral.
8:   NPTS – INTEGEROutput
On exit: the total number of function evaluations.
9:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, because for this routine the values of the output arguments may be useful even if IFAIL≠0 on exit, the recommended value is -1. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Note: D01DAF may return useful information for one or more of the following detected errors or warnings.
Errors or warnings detected by the routine:
IFAIL=1
This indicates that 255 points have been used in the outer integral and convergence has not been obtained. All the inner integrals have, however, converged. In this case ANS may still contain an approximate estimate of the integral.
IFAIL=10×n
This indicates that the outer integral has converged but n inner integrals have failed to converge with the use of 255 points. In this case ANS may still contain an approximate estimate of the integral, but its reliability will decrease as n increases.
IFAIL=10×n+1
This indicates that both the outer integral and n of the inner integrals have not converged. ANS may still contain an approximate estimate of the integral, but its reliability will decrease as n increases.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

The absolute accuracy is specified by the variable ABSACC. If, on exit, IFAIL=0 then the result is most likely correct to this accuracy. Even if IFAIL is nonzero on exit, it is still possible that the calculated result could differ from the true value by less than the given accuracy.

8 Parallelism and Performance

D01DAF is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The time taken by D01DAF depends upon the complexity of the integrand and the accuracy requested.
With Patterson's method accidental convergence may occasionally occur, when two estimates of an integral agree to within the requested accuracy, but both estimates differ considerably from the true result. This could occur in either the outer integral or in one or more of the inner integrals.
If it occurs in the outer integral then apparent convergence is likely to be obtained with considerably fewer integrand evaluations than may be expected. If it occurs in an inner integral, the incorrect value could make the function F y appear to be badly behaved, in which case a very large number of pivots may be needed for the overall evaluation of the integral. Thus both unexpectedly small and unexpectedly large numbers of integrand evaluations should be considered as indicating possible trouble. If accidental convergence is suspected, the integral may be recomputed, requesting better accuracy; if the new request is more stringent than the degree of accidental agreement (which is of course unknown), improved results should be obtained. This is only possible when the accidental agreement is not better than machine accuracy. It should be noted that the routine requests the same accuracy for the inner integrals as for the outer integral. In practice it has been found that in the vast majority of cases this has proved to be adequate for the overall result of the double integral to be accurate to within the specified value.
The routine is not well-suited to non-smooth integrands, i.e., integrands having some kind of analytic discontinuity (such as a discontinuous or infinite partial derivative of some low-order) in, on the boundary of, or near, the region of integration. Warning: such singularities may be induced by incautiously presenting an apparently smooth interval over the positive quadrant of the unit circle, R
I=∫R x+y dx dy.
This may be presented to D01DAF as
I=∫01 dy ∫0 1-y 2 x+y dx=∫01 12 1-y 2+y⁢1-y 2 dy
but here the outer integral has an induced square-root singularity stemming from the way the region has been presented to D01DAF. This situation should be avoided by re-casting the problem. For the example given, the use of polar coordinates would avoid the difficulty:
I=∫01 dr∫0 π 2 r 2 cos⁡υ+sin⁡υ dυ.

10 Example

This example evaluates the integral discussed in Section 9, presenting it to D01DAF first as
∫01 ∫0 1-y 2 x+y dx dy
and then as
∫01∫0 π 2 r 2 cos⁡υ+sin⁡υ dυ dr.
Note the difference in the number of function evaluations.

10.1 Program Text

Program Text (d01dafe.f90)

10.2 Program Data

None.

10.3 Program Results

Program Results (d01dafe.r)

D01 Chapter Contents
D01 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


D01EAF : NAG Library, Mark 26

D01 Chapter Contents
D01 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

D01EAF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

D01EAF computes approximations to the integrals of a vector of similar functions, each defined over the same multidimensional hyper-rectangular region. The routine uses an adaptive subdivision strategy, and also computes absolute error estimates.

2 Specification

SUBROUTINE D01EAF ( NDIM, A, B, MINCLS, MAXCLS, NFUN, FUNSUB, ABSREQ, RELREQ, LENWRK, WRKSTR, FINEST, ABSEST, IFAIL)
INTEGER | NDIM, MINCLS, MAXCLS, NFUN, LENWRK, IFAIL
REAL (KIND=nag_wp) | A(NDIM), B(NDIM), ABSREQ, RELREQ, WRKSTR(LENWRK), FINEST(NFUN), ABSEST(NFUN)
EXTERNAL | FUNSUB

3 Description

D01EAF uses a globally adaptive method based on the algorithm described by van Dooren and de Ridder (1976) and Genz and Malik (1980). It is implemented for integrals in the form:
∫a 1b 1∫a 2b 2…∫anbn f 1,f 2,…,fm d xn…d x 2 d x 1,
where fi=fi x 1,x 2,…,xn, for i=1,2,…,m.
Upon entry, unless MINCLS has been set to a value less than or equal to 0, D01EAF divides the integration region into a number of subregions with randomly selected volumes. Inside each subregion the integrals and their errors are estimated. The initial number of subregions is chosen to be as large as possible without using more than MINCLS calls to FUNSUB. The results are stored in a partially ordered list (a heap). The routine then proceeds in stages. At each stage the subregion with the largest error (measured using the maximum norm) is halved along the coordinate axis where the integrands have largest absolute fourth differences. The basic rule is applied to each half of this subregion and the results are stored in the list. The results from the two halves are used to update the global integral and error estimates (FINEST and ABSEST) and the routine continues unless ABSEST≤max ABSREQ,FINEST×RELREQ where the norm . is the maximum norm, or further subdivision would use more than MAXCLS calls to FUNSUB. If at some stage there is insufficient working storage to keep the results for the next subdivision, the routine switches to a less efficient mode; only if this mode of operation breaks down is insufficient storage reported.

4 References

Genz A C and Malik A A (1980) An adaptive algorithm for numerical integration over an N-dimensional rectangular region J. Comput. Appl. Math. 6 295–302
van Dooren P and de Ridder L (1976) An adaptive algorithm for numerical integration over an N-dimensional cube J. Comput. Appl. Math. 2 207–217

5 Arguments

1:   NDIM – INTEGERInput
On entry: n, the number of dimensions of the integrals.
Constraint: NDIM≥1.
2:   A NDIM – REAL (KIND=nag_wp) arrayInput
On entry: the lower limits of integration, ai, for i=1,2,…,n.
3:   B NDIM – REAL (KIND=nag_wp) arrayInput
On entry: the upper limits of integration, bi, for i=1,2,…,n.
4:   MINCLS – INTEGERInput/Output
On entry: must be set either to the minimum number of FUNSUB calls to be allowed, in which case MINCLS≥0 or to a negative value. In this case, the routine continues the calculation started in a previous call with the same integrands and integration limits: no arguments other than MINCLS, MAXCLS, ABSREQ, RELREQ or IFAIL must be changed between the calls.
On exit: gives the number of FUNSUB calls actually used by D01EAF. For the continuation case (MINCLS<0 on entry) this is the number of new FUNSUB calls on the current call to D01EAF.
5:   MAXCLS – INTEGERInput
On entry: the maximum number of FUNSUB calls to be allowed. In the continuation case this is the number of new FUNSUB calls to be allowed.
Constraints:
  • MAXCLS≥MINCLS;
  • MAXCLS≥r;
  • where ​r=2 n+2⁢n 2+2 n+1, if ​n<11, or ​r=1+n 4⁢n 2-6 n+14/3, if ​n≥11.
6:   NFUN – INTEGERInput
On entry: m, the number of integrands.
Constraint: NFUN≥1.
7:   FUNSUB – SUBROUTINE, supplied by the user.External Procedure
FUNSUB must evaluate the integrands fi at a given point.
The specification of FUNSUB is:
SUBROUTINE FUNSUB ( NDIM, Z, NFUN, F)
INTEGER | NDIM, NFUN
REAL (KIND=nag_wp) | Z(NDIM), F(NFUN)
1:   NDIM – INTEGERInput
On entry: n, the number of dimensions of the integrals.
2:   Z NDIM – REAL (KIND=nag_wp) arrayInput
On entry: the coordinates of the point at which the integrands must be evaluated.
3:   NFUN – INTEGERInput
On entry: m, the number of integrands.
4:   F NFUN – REAL (KIND=nag_wp) arrayOutput
On exit: the value of the ith integrand at the given point.
FUNSUB must either be a module subprogram USEd by, or declared as EXTERNAL in, the (sub)program from which D01EAF is called. Arguments denoted as Input must not be changed by this procedure.
8:   ABSREQ – REAL (KIND=nag_wp)Input
On entry: the absolute accuracy required by you.
Constraint: ABSREQ≥0.0.
9:   RELREQ – REAL (KIND=nag_wp)Input
On entry: the relative accuracy required by you.
Constraint: RELREQ≥0.0.
10:   LENWRK – INTEGERInput
On entry: the dimension of the array WRKSTR as declared in the (sub)program from which D01EAF is called.
Suggested value: LENWRK≥6 n+9 m+n+m+21+p/r, where p is the value of MAXCLS and r is defined under MAXCLS. If LENWRK is significantly smaller than this, the routine will not work as efficiently and may even fail.
Constraint: LENWRK≥8×NDIM+11×NFUN+3.
11:   WRKSTR LENWRK – REAL (KIND=nag_wp) arrayInput/Output
On entry: if MINCLS<0, WRKSTR must be unchanged from the previous call of D01EAF.
On exit: contains information about the current subdivision which could be used in a continuation call.
12:   FINEST NFUN – REAL (KIND=nag_wp) arrayOutput
On exit: FINEST i specifies the best estimate obtained from the ith integral, for i=1,2,…,m.
13:   ABSEST NFUN – REAL (KIND=nag_wp) arrayOutput
On exit: ABSEST i specifies the estimated absolute accuracy of FINEST i, for i=1,2,…,m.
14:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, because for this routine the values of the output arguments may be useful even if IFAIL≠0 on exit, the recommended value is -1. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
MAXCLS was too small for D01EAF to obtain the required accuracy. The arrays FINEST and ABSEST respectively contain current estimates for the integrals and errors.
IFAIL=2
LENWRK is too small for the routine to continue. The arrays FINEST and ABSEST respectively contain current estimates for the integrals and errors.
IFAIL=3
On a continuation call, MAXCLS was set too small to make any progress. Increase MAXCLS before calling D01EAF again.
IFAIL=4
On entry, | NDIM<1,
or | NFUN<1,
or | MAXCLS<MINCLS,
or | MAXCLS<r (see MAXCLS),
or | ABSREQ<0.0,
or | RELREQ<0.0,
or | LENWRK<8×NDIM+11×NFUN+3.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

An absolute error estimate for each integrand is output in the array ABSEST. The routine exits with IFAIL=0 if
maxi ABSEST i≤max ABSREQ,RELREQ×maxi FINEST i.

8 Parallelism and Performance

D01EAF is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

Usually the running time for D01EAF will be dominated by the time in FUNSUB, so the maximum time that could be used by D01EAF will be proportional to MAXCLS multiplied by the cost of a call to FUNSUB.
On a normal call, you should set MINCLS=0 on entry.
For some integrands, particularly those that are poorly behaved in a small part of the integration region, D01EAF may terminate prematurely with values of ABSEST that are significantly smaller than the actual absolute errors. This behaviour should be suspected if the returned value of MINCLS is small relative to the expected difficulty of the integrals. When this occurs D01EAF should be called again, but with an entry value of MINCLS≥2 r, (see specification of MAXCLS) and the results compared with those from the previous call.
If the routine is called with MINCLS≥2 r, the exact values of FINEST and ABSEST on return will depend (within statistical limits) on the sequence of random numbers generated internally within D01EAF by calls to G05SAF. Separate runs will produce identical answers unless the part of the program executed prior to calling D01EAF also calls (directly or indirectly) routines from Chapter G05, and, in addition, the series of such calls differs between runs.
Because of moderate instability in the application of the basic integration rule, approximately the last 1+ log 10 n 3 decimal digits may be inaccurate when using D01EAF for large values of n.

10 Example

This example computes
∫01 ∫01 ∫01 ∫01 f 1,f 2,…,f 10 d x 4 d x 3 d x 2 d x 1 ,
where j=1,2,…,10, fj=ln x 1+2 x 2+3 x 3+4 x 4sin j+x 1+2 x 2+3 x 3+4 x 4. The program is intended to show how to exploit the continuation facility provided with D01EAF: the routine exits with IFAIL=1 (printing an explanatory error message) and is re-entered with MAXCLS reset to a larger value. The program can be used with any values of NDIM and NFUN, except that the expression for r must be changed if NDIM>10 (see specification of MAXCLS).

10.1 Program Text

Program Text (d01eafe.f90)

10.2 Program Data

None.

10.3 Program Results

Program Results (d01eafe.r)

GnuplotProduced by GNUPLOT 4.6 patchlevel 3 −0.4 −0.2 0 0.2 0.4 0 2 4 6 8 10 12 Integral Values Integrand Number Example Program Multi-dimensional Integrals of 10 Integrands with Various Numbers of Function Calls gnuplot_plot_1 57 calls gnuplot_plot_2 798 calls gnuplot_plot_3 912 calls
GnuplotProduced by GNUPLOT 4.6 patchlevel 3 0.0001 0.001 0.01 0.1 0 2 4 6 8 10 12 Estimated Error Integrand Number Errors in Computing Integrals of 10 Integrands with Various Numbers of Function Calls gnuplot_plot_1 57 calls gnuplot_plot_2 798 calls gnuplot_plot_3 912 calls
D01 Chapter Contents
D01 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


D01ESF : NAG Library, Mark 26

D01 Chapter Contents
D01 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

D01ESF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
▸▿ 3 Description
3.1 Comparing Quadrature Over Full and Sparse Grids
3.2 Sparse Grid Quadrature
3.3 Using D01ESF
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
▸▿ 8 Parallelism and Performance
8.1 Direct Threading
8.2 Parallelization of F
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results
▸▿ 11 Optional Parameters
11.1 Description of the Optional Parameters

1 Purpose

D01ESF approximates a vector of definite integrals F over the unit hypercube Ω=0,1 d, given the vector of integrands f x.
F = ∫ Ω f x dx = ∫ 0 1 ∫ 0 1 … ∫ 0 1 f x 1,x 2,…,xd d x 1 d x 2 … d xd .
The routine uses a sparse grid discretisation, allowing for computationally feasible estimations of integrals of high dimension (d∼O 100).

2 Specification

SUBROUTINE D01ESF ( NI, NDIM, F, MAXDLV, DINEST, ERREST, IVALID, IOPTS, OPTS, IUSER, RUSER, IFAIL)
INTEGER | NI, NDIM, MAXDLV(NDIM), IVALID(NI), IOPTS(100), IUSER(*), IFAIL
REAL (KIND=nag_wp) | DINEST(NI), ERREST(NI), OPTS(100), RUSER(*)
EXTERNAL | F

3 Description

D01ESF uses a sparse grid to generate a vector of approximations F^ to a vector of integrals F over the unit hypercube Ω=0,1 d, that is,
F^ ≈ F = ∫ 0,1 d f x dx .

3.1 Comparing Quadrature Over Full and Sparse Grids

Before illustrating the sparse grid construction, it is worth comparing integration over a sparse grid to integration over a full grid.
Given a one-dimensional quadrature rule with N abscissae, which accurately evaluates a polynomial of order PN, a full tensor product over d dimensions, a full grid, may be constructed with Nd multidimensional abscissae. Such a product will accurately integrate a polynomial where the maximum power of any dimension is PN. For example if d=2 and PN=3, such a rule will accurately integrate any polynomial whose highest order term is x 13x 23. Such a polynomial may be said to have a maximum combined order of PNd, provided no individual dimension contributes a power greater than PN. However, the number of multidimensional abscissae, or points, required increases exponentially with the dimension, rapidly making such a construction unusable.
The sparse grid technique was developed by Smolyak (Smolyak (1963)). In this, multiple one-dimensional quadrature rules of increasing accuracy are combined in such a way as to provide a multidimensional quadrature rule which will accurately evaluate the integral of a polynomial whose maximum order appears as a monomial. Hence a sparse grid construction whose highest level quadrature rule has polynomial order PN will accurately integrate a polynomial whose maximum combined order is also PN. Again taking PN=3, one may, theoretically, accurately integrate a polynomial such as x 3+x 2 y+y 3, but not a polynomial such as x 3y 3+xy. Whilst this has a lower maximum combined order than the full tensor product, the number of abscissae required increases significantly slower than the equivalent full grid, making some classes of integrals of dimension d∼O 100 tractable. Specifically, if a one-dimensional quadrature rule of level ℓ has N∼O 2 ℓ abscissae, the corresponding full grid will have O 2 ℓ d multidimensional abscissae, whereas the sparse grid will have O 2 ℓ d ℓ-1 . Figure 1 demonstrates this using a Gauss–Patterson rule with 15 points in 3 dimensions. The full grid requires 3375 points, whereas the sparse grid only requires 111.
Three-dimensional full (left) and sparse (right) grids, constructed from the 15 point Gauss–Patterson rule
Figure 1: Three-dimensional full (left) and sparse (right) grids, constructed from the 15 point Gauss–Patterson rule

3.2 Sparse Grid Quadrature

We now include a brief description of the sparse grid construction, sufficient for the understanding of the use of this routine. For a more detailed analysis, see Gerstner and Griebel (1998).
Consider a one-dimensional nℓ-point quadrature rule of level ℓ, Qℓ. The action of this rule on a integrand f is to approximate its definite one-dimensional integral F 1 as,
F 1 = ∫ 0 1 f x dx ≈ Qℓ f = ∑ i=1 nℓ w ℓ,i × f x ℓ,i ,
using weights w ℓ,i and abscissae x ℓ,i, for i=1,2,…,nℓ.
Now construct a set of one-dimensional quadrature rules, Qℓ ∣ ℓ=1,…,L , such that the accuracy of the quadrature rule increases with the level number. In this routine we exclusively use quadrature rules which are completely nested, implying that if an abscissae x ℓ,k is in level ℓ, it is also in level ℓ+1. The quantity L denotes some maximum level appropriate to the rules that have been selected.
Now define the action of the tensor product of d rules as,
Q ℓ 1 ⊗ ⋯ ⊗ Q ℓd f = ∑ i 1=1 n ℓ 1 ⋯ ∑ i d =1 n ℓ d w ℓ 1 , i 1 ⋯ w ℓd , id f x ℓ 1 , i 1 ,…, x ℓd , id ,
where the individual level indices ℓj are not necessarily ordered or unique. Each tensor product of d rules defines an action of the quadrature rules Qℓ, ℓ=ℓ 1,ℓ 2,…,ℓd over a subspace, which is given a level ℓ = ∑ j=1 d ℓj. If all rule levels are equal, this is the full tensor product of that level.
The sparse grid construction of level ℓ can then be declared as the sum of all actions of the quadrature differences Δk = Qk - Q k-1 , over all subspaces having a level at most ℓ-d+1,
F d ≈ Q ℓ d f = ∑ level at most ​ℓ-d+1 Δ k 1 ⊗ ⋯ ⊗ Δ kd f . (1)
By definition, all subspaces used for level ℓ-1 must also be used for level ℓ, and as such the difference between the result of all actions over subsequent sparse grid constructions may be used as an error estimate.
Let L be the maximum level allowable in a sparse grid construction. The classical sparse grid construction of ℓ=L allows each dimension to support a one-dimensional quadrature rule of level at most L, with such a quadrature rule being used in every dimension at least once. Such a construction lends equal weight to each dimension of the integration, and is termed here ‘isotropic’.
Define the set m=mj,j=1,2,…,d, where mj is the maximum quadrature rule allowed in the jth dimension, and mq to be the maximum quadrature rule used by any dimension. Let a subspace be identified by its quadrature difference levels, k = k 1,k 2,…,kd.
The classical construction may be extended by allowing different dimensions to have different values mj, and by allowing mq≤L. This creates non-isotropic constructions. These are especially useful in higher dimensions, where some dimensions contribute more than others to the result, as they can drastically reduce the number of function evaluations required.
For example, consider the two-dimensional construction with L=4. The classical isotropic construction would have the following subspaces.
Subspaces generated by a classical sparse grid with L=4.
Level | Subspaces
1 | 1,1
2 | 2,1, 1,2
3 | 3,1, 2,2, 1,3
4 | 4,1, 3,2, 2,3, 1,4
If the variation in the second dimension is sufficiently accurately described by a quadrature rule of level 2, the contributions of the subspaces 1,3 and 1,4 are probably negligible. Similarly, if the variation in the first dimension is sufficiently accurately described by a quadrature rule of level 3, the subspace 4,1 is probably negligible. Furthermore the subspace 2,3 would also probably have negligible impact, whereas the subspaces 2,2 and 3,2 would not. Hence restricting the first dimension to a maximum level of 3, and the second dimension to a maximum level of 2 would probably give a sufficiently acceptable estimate, and would generate the following subspaces.
Subspaces generated by a non-isotropic sparse grid with L=4, mq=3 and m=3,2.
Level | Subspaces
1 | 1,1
2 | 2,1, 1,2
3 | 3,1, 2,2
4 | 4,1, 3,2
Taking this to the extreme, if the variation in the first and second dimensions are sufficiently accurately described by a level 2 quadrature rule, restricting the maximum level of both dimensions to 2 would generate the following subspaces.
Subspaces generated by a sparse grid construction with L=4, mq=2 and m=2,2.
Level | Subspaces
1 | 1,1
2 | 2,1, 1,2
3 | 2,2
4 | None
Hence one subspace is generated at level 3, and no subspaces are generated at level 4. The level 3 subspace 2,2 actually indicates that this is the full grid of level 2.

3.3 Using D01ESF

D01ESF uses optional parameters, supplied in the option arrays IOPTS and OPTS. Before calling D01ESF, these option arrays must be initialized using D01ZKF. Once initialized, the required options may be set and queried using D01ZKF and D01ZLF respectively. A complete list of the options available may be found in Section 11.
You may control the maximum level required, L, using the optional parameter Maximum Level. Furthermore, you may control the first level at which the error comparison will take place using the optional parameter Minimum Level, allowing for the forced evaluation of a predetermined number of levels before the routine attempts to complete. Completion is flagged when the error estimate is sufficiently small:
F^ d k - F^ d k-1 ≤ max εa, εr × F^ d k ,
where εa and εr are the absolute and relative error tolerances, respectively, and k≤L is the highest level at which computation was performed. The tolerances εa and εr can be controlled by setting the optional parameters Absolute Tolerance and Relative Tolerance.
Owing to the interlacing nature of the quadrature rules used herein, abscissae x required in lower level subspaces will also appear in higher-level subspaces. This allows for calculations which will be repeated later to be stored and re-used. However, this is naturally at the expense of memory. It may also be at the expense of computational time, depending on the complexity of the integrands, as the lookup time for a given value is (at worst) O d. Furthermore, as the sparse grid level increases, fewer subsequent levels will require values from the current level. You may control the number of levels for which values are stored by setting the optional parameter Index Level.
Two different sets of interlacing quadrature rules are selectable using the optional parameter Quadrature Rule: Gauss–Patterson and Clenshaw–Curtis. Gauss–Patterson rules offer greater polynomial accuracy, whereas Clenshaw–Curtis rules are often effective for oscillatory integrands. Clenshaw–Curtis rules require function values to be evaluated on the boundary of the hypercube, whereas Gauss–Patterson rules do not. Both of these rules use precomputed weights, and as such there is an effective limit on mq; see the description of the optional parameter Quadrature Rule. The value of mq is returned by the queriable optional parameter Maximum Quadrature Level.
D01ESF also allows for non-isotropic sparse grids to be constructed. This is done by appropriately setting the array MAXDLV. It should be emphasised that a non-isometric construction should only be used if the integrands behave in a suitable way. For example, they may decay toward zero as the lesser dimensions approach their bounds of Ω. It should also be noted that setting MAXDLV k=1 will not reduce the dimension of the integrals, it will simply indicate that only one point in dimension k should be used. It is also advisable to approximate the integrals several times, once with an isometric construction of some level, and then with a non-isometric construction with higher levels in various dimensions. If the difference between the solutions is significantly more than the returned error estimates, the assumptions of dimensional importance are probably incorrect.
The abscissae in each subspace are generally expressible in a sparse manner, because many of the elements of each abscissa will in fact be the centre point of the dimension, which is termed here the ‘trivial’ element. In this routine the trivial element is always returned as 0.5 owing to the restriction to the 0,1 hypercube. As such, the subroutine F returns the abscissae in Compressed Column Storage (CCS) format (see the F11 Chapter Introduction). This has particular advantages when using accelerator hardware to evaluate the required functions, as much less data must be forwarded. It also, potentially, allows for calculations to be computed faster, as any sub-calculations dependent upon the trivial value may be potentially re-used. See the example in Section 10.

4 References

Caflisch R E, Morokoff W and Owen A B (1997) Valuation of mortgage backed securities using Brownian bridges to reduce effective dimension Journal of Computational Finance 1 27–46
Gerstner T and Griebel M (1998) Numerical integration using sparse grids Numerical Algorithms 18 209–232
Smolyak S A (1963) Quadrature and interpolation formulas for tensor products of certain classes of functions Dokl. Akad. Nauk SSSR 4 240–243

5 Arguments

1:   NI – INTEGERInput
On entry: ni, the number of integrands.
Constraint: NI≥1.
2:   NDIM – INTEGERInput
On entry: d, the number of dimensions.
Constraint: NDIM≥1.
3:   F – SUBROUTINE, supplied by the user.External Procedure
F must return the value of the integrands fj at a set of nx d-dimensional points xi, implicitly supplied as columns of a matrix X d,nx. If X was supplied explicitly you would find that most of the elements attain the same value, xtr; the larger the number of dimensions, the greater the proportion of elements of X would be equal to xtr. So, X is effectively a sparse matrix, except that the ‘zero’ elements are replaced by elements that are all equal to the value xtr. For this reason X is supplied, as though it were a sparse matrix, in compressed column storage (CCS) format (see the F11 Chapter Introduction).
Individual entries x k,i of X, for k=1,2,…,d, are either trivially valued, in which case x k,i=xtr, or are non-trivially valued. For point i, the non-trivial row indices and corresponding abscissae values are supplied in elements c i=ICOLZP i,…,ICOLZP i+1-1, for i=1,2,…,nx, of the arrays IROWIX and XS, respectively. Hence the ith column of the matrix X is retrievable as
X IROWIX c i ,i = XS c i , X k ∉ IROWIX c i ,i = xtr .
An equivalent integer valued matrix Q is also implicitly provided. This contains the unique indices q k,i of the underlying one-dimensional quadrature rule corresponding to the individual abscissae x k,i. For trivial abscissae, the implicit index q k,i=1. Q is supplied in the same CCS format as X, with the non-trivial values supplied in QS.
The specification of F is:
SUBROUTINE F ( NI, NDIM, NX, XTR, NNTR, ICOLZP, IROWIX, XS, QS, FM, IFLAG, IUSER, RUSER)
INTEGER | NI, NDIM, NX, NNTR, ICOLZP(NX+1), IROWIX(NNTR), QS(NNTR), IFLAG, IUSER(*)
REAL (KIND=nag_wp) | XTR, XS(NNTR), FM(NI,NX), RUSER(*)
1:   NI – INTEGERInput
On entry: ni, the number of integrands.
2:   NDIM – INTEGERInput
On entry: d, the number of dimensions.
3:   NX – INTEGERInput
On entry: nx, the number of points xi, corresponding to the number of columns of X, at which the set of integrands must be evaluated.
4:   XTR – REAL (KIND=nag_wp)Input
On entry: xtr, the value of the trivial elements of X.
5:   NNTR – INTEGERInput
On entry: if IFLAG>0, the number of non-trivial elements of X.
If IFLAG=0, the total number of abscissae from the underlying one-dimensional quadrature.
6:   ICOLZP NX+1 – INTEGER arrayInput
On entry: the set ICOLZP i,…,ICOLZP i+1 - 1 contains the indices of IROWIX and XS corresponding to the non-trivial elements of column i of X and hence of the point xi, for i=1,2,…,nx.
7:   IROWIX NNTR – INTEGER arrayInput
On entry: the row indices corresponding to the non-trivial elements of X.
8:   XS NNTR – REAL (KIND=nag_wp) arrayInput
On entry: x k,i≠xtr, the non-trivial entries of X.
9:   QS NNTR – INTEGER arrayInput
On entry: q k,i≠1, the indices of the underlying quadrature rules corresponding to x k,i≠xtr.
10:   FM NINX – REAL (KIND=nag_wp) arrayOutput
On exit: FM pi = fp xi , for i=1,2,…,nx and p=1,2,…,ni.
11:   IFLAG – INTEGERInput/Output
On entry: if IFLAG=0, this is the first call to F. nx=1, and the entire point x 1 will satisfy x k,1=xtr, for k=1,2,…,d. In addition, NNTR contains the total number of abscissae from the underlying one-dimensional quadrature; XS contains the complete set of abscissae and QS contains the corresponding quadrature indices, with XS 1 = xtr and QS 1 = 1 . This will always be called in serial.
In subsequent calls to F, IFLAG=1. Subsequent calls may be made from within an OpenMP parallel region. See Section 8 for details.
On exit: set IFLAG<0 if you wish to force an immediate exit from D01ESF with IFAIL=-1.
12:   IUSER* – INTEGER arrayUser Workspace
13:   RUSER* – REAL (KIND=nag_wp) arrayUser Workspace
14:   PUSER – TYPE (C_PTR)Communication Array
F is called with the arguments IUSER, RUSER and PUSER as supplied to D01ESF. You are free to use the arrays IUSER, RUSER and PUSER to supply information to F as an alternative to using COMMON global variables.
F must either be a module subprogram USEd by, or declared as EXTERNAL in, the (sub)program from which D01ESF is called. Arguments denoted as Input must not be changed by this procedure.
4:   MAXDLV NDIM – INTEGER arrayInput
On entry: m, the array of maximum levels for each dimension. MAXDLV j, for j=1,2,…,d, contains mj, the maximum level of quadrature rule dimension j will support.
The default value, min mq,L will be used if either MAXDLV j≤0 or MAXDLV j≥min mq,L (for details on the default values for mq and L and on how to change these values see the options Maximum Level, Maximum Quadrature Level and Quadrature Rule).
If MAXDLV j=1 for all j, only one evaluation will be performed, and as such no error estimation will be possible.
Suggested value: MAXDLV j=0 for all j=1,2,…,d.
Note: setting non-default values for some dimensions makes the assumption that the contribution from the omitted subspaces is 0. The integral and error estimates will only be based on included subspaces, which if the 0 contribution assumption is not valid will be erroneous.
5:   DINEST NI – REAL (KIND=nag_wp) arrayOutput
On exit: DINEST p contains the final estimate F^p of the definite integral Fp, for p=1,2,…,ni.
6:   ERREST NI – REAL (KIND=nag_wp) arrayOutput
On exit: ERREST p contains the final error estimate Ep of the definite integral Fp, for p=1,2,…,ni.
7:   IVALID NI – INTEGER arrayOutput
On exit: IVALID p indicates the final state of integral p, for p=1,2,…,ni.
IVALID p=0
The error estimate for integral p was below the requested tolerance.
IVALID p=1
The error estimate for integral p was below the requested tolerance. The final level used was non-isotropic.
IVALID p=2
The error estimate for integral p was above the requested tolerance.
IVALID p=3
The error estimate for integral p was above max 0.1 F^p,0.01.
IVALID p<0
You aborted the evaluation before an error estimate could be made.
8:   IOPTS 100 – INTEGER arrayCommunication Array
9:   OPTS 100 – REAL (KIND=nag_wp) arrayCommunication Array
The arrays IOPTS and OPTS must not be altered between calls to any of the routines D01ESF, D01ZKF and D01ZLF.
10:   IUSER* – INTEGER arrayUser Workspace
11:   RUSER* – REAL (KIND=nag_wp) arrayUser Workspace
12:   PUSER – TYPE (C_PTR)Communication Array
IUSER, RUSER and PUSER are not used by D01ESF, but are passed directly to F and may be used to pass information to this routine as an alternative to using COMMON global variables.
13:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, because for this routine the values of the output arguments may be useful even if IFAIL≠0 on exit, the recommended value is -1. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Note: D01ESF may return useful information for one or more of the following detected errors or warnings.
Errors or warnings detected by the routine:
IFAIL=1
The requested accuracy was not achieved for at least one integral.
IFAIL=2
No accuracy was achieved for at least one integral.
IFAIL=11
On entry, NI=value.
Constraint: NI≥1.
IFAIL=21
On entry, NDIM=value.
Constraint: NDIM≥1.
IFAIL=1001
Either the option arrays IOPTS and OPTS have not been initialized for D01ESF, or they have become corrupted.
IFAIL=-1
Exit requested from F with IFLAG=value.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

For each integral p, an error estimate Ep is returned, where,
Ep = F^ p k - F^ p k-1 ≈ F^p - Fp ,
where k ≤ L is the highest level at which computation was performed.

8 Parallelism and Performance

8.1 Direct Threading

D01ESF is directly threaded for parallel execution. For each level, at most nt threads will evaluate the integrands over independent subspaces of the construction, and will construct a partial sum of the level's contribution. Once all subspaces from a given level have been processed, the partial sums are combined to give the total contribution of the level, which is in turn added to the total solution. For a given number of threads, the division of subspaces between the threads, and the order in which a single thread operates over its assigned subspaces, is fixed. However, the order in which all subspaces are combined will necessarily be different to the single threaded case, which may result in some discrepency in the results between parallel and serial execution.
To mitigate this discrepency, it is recommended that D01ESF be instructed to use higher-than-working precision to accumulate the actions over the subspaces. This is done by setting the option Summation Precision=HIGHER, which is the default behaviour. This has some computational cost, although this is typically negligible in comparison to the overall runtime, particularly for non-trivial integrands.
If Summation Precision=WORKING, then the accumulation will be performed using working precision, which may provide some increase in performance. Again, this is probably negligible in comparison to the overall runtime.
For some problems, typically of lower dimension, there may be insufficient work to warrant direct threading at lower levels. For example, a three-dimensional problem will require at most 3 subspaces to be evaluated at level 2, and at most 6 subspaces at level 3. Furthermore, level 2 subspaces typically contain only 2 new multidimensional abscissae, while level 3 subspaces typically contain 2 or 4 new multidimensional abscissae depending on the Quadrature Rule. If there are more threads than the number of available subspaces at a given level, or the amount of work in each subspace is outweighed by the amount of work required to generate the parallel region, parallel efficiency will be decreased. This may be mitigated to some extent by evaluating the first sl levels in serial. The value of sl may be altered using the optional parameter Serial Levels. If sl≥L, then all levels will be evaluated in serial and no direct threading will be utilized.
If you use direct threading in the manner just described, you must ensure any access to the user arrays IUSER and RUSER is done in a thread-safe manner. These are classed as OpenMP SHARED, and are passed directly to the subroutine F for every thread.

8.2 Parallelization of F

The vectorized interface also allows for parallelization inside the subroutine F by evaluating the required integrands in parallel. Provided the values returned by F match those that would be returned without parallelizing F, the final result should match the serial result, barring any discrepencies in accumulation. If you wish to parallelize F, it is advisable to set a large value for Maximum Nx, although be aware that increasing Maximum Nx will increase the memory requirement of the routine. In general, parallelization of F should not be necessary, as the higher-level parallelism over different subspaces scales well for many problems.

9 Further Comments

Not applicable.

10 Example

The example program evaluates an estimate to the set of integrals
F = ∫ Ω sin 1+x ⋮ sin ni+x log x d x
where x = ∑ j=1 d j xj. It also demonstrates a simple method to safely use IUSER and RUSER as workspace for sub-calculations when running in parallel.

10.1 Program Text

Program Text (d01esfe.f90)

10.2 Program Data

None.

10.3 Program Results

Program Results (d01esfe.r)

11 Optional Parameters

Several optional parameters in D01ESF control aspects of the algorithm, methodology used, logic or output. Their values are contained in the arrays IOPTS and OPTS; these must be initialized before calling D01ESF by first calling D01ZKF with OPTSTR set to "Initialize = D01ESF".
Each optional parameter has an associated default value; to set any of them to a non-default value, or to reset any of them to the default value, use D01ZKF. The current value of an optional parameter can be queried using D01ZLF.
The remainder of this section can be skipped if you wish to use the default values for all optional parameters.
The following is a list of the optional parameters available. A full description of each optional parameter is provided in Section 11.1.
  • Absolute Tolerance
  • Index Level
  • Maximum Level
  • Maximum Nx
  • Maximum Quadrature Level
  • Minimum Level
  • Quadrature Rule
  • Relative Tolerance
  • Serial Levels
  • Summation Precision

11.1 Description of the Optional Parameters

For each option, we give a summary line, a description of the optional parameter and details of constraints.
The summary line contains:
  • the keywords, where the minimum abbreviation of each keyword is underlined;
  • a parameter value, where the letters a, i and r denote options that take character, integer and real values respectively.
  • the default value.
The following symbol represent various machine constants:
  • ε represents the machine precision (see X02AJF).
All options accept the value ‘DEFAULT’ in order to return single options to their default states.
Keywords and character values are case insensitive, however they must be separated by at least one space.
Queriable options will return the appropriate value when queried by calling D01ZLF. They will have no effect if passed to D01ZKF.
For D01ESF the maximum length of the argument CVALUE used by D01ZLF is 15.
Absolute Tolerance r Default =ε
r=εa, the absolute tolerance required.
Index Level i Default =4
The maximum level at which function values are stored for later use. Larger values use increasingly more memory, and require more time to access specific elements. Lower levels result in more repeated computation. The Maximum Quadrature Level, mq is the effective upper limit on Index Level. If i≥mq, D01ESF will use mq as the value of Index Level.
Constraint: i≥1.
Maximum Level i Default =5
i=L, the maximum number of levels to evaluate.
Constraint: 1<i≤20.
Note: the maximum allowable level in any single dimension, mq, is governed by the Quadrature Rule selected. If a value greater than mq is set, only a subset of subspaces from higher levels will be used. Should this subset be empty for a given level, computation will consider the preceding level to be the maximum level and will terminate.
Maximum Nx i Default =128
i=max nx, the maximum number of points to evaluate in a single call to F.
Constraint: 1≤i≤16384.
Maximum Quadrature Level i Queriable only
i=mq, the maximum level of the underlying one-dimensional quadrature rule (see Quadrature Rule).
Minimum Level i Default =2
The minimum number of levels which must be evaluated before an error estimate is used to determine convergence.
Constraint: i>1.
Note: if the minimum level is greater than the maximum computable level, the maximum level will be used.
Quadrature Rule a Default =Gauss–Patterson
The underlying one-dimensional quadrature rule to be used in the construction. Open rules do not require evaluations at boundaries.
Quadrature Rule=Gauss–Patterson or GP
The interlacing Gauss–Patterson rules. Level ℓ uses 2 ℓ-1 abscissae. All levels are open. These rules provide high order accuracy. mq=9.
Quadrature Rule=Clenshaw–Curtis or CC
The interlacing Clenshaw–Curtis rules. Level ℓ uses 2 ℓ-1+1 abscissae. All levels above level 1 are closed. mq=12.
Relative Tolerance r Default =ε
r=εa, the relative tolerance required.
Summation Precision a Default =HIGHER
Determines whether D01ESF uses working precision or higher-than-working precision to accumulate the actions over subspaces.
Summation Precision=HIGHER or H
Higher-than-working precision is used to accumulate the action over a subspace, and for the accumulation of all such actions. This is more expensive computationally, although this is probably negligible in comparison to the cost of evaluating the integrands and the overall runtime. This significantly reduces variation in the result when changing the number of threads.
Summation Precision=WORKING or W
Working precision is used to accumulate the actions over subspaces. This may provide some speedup, particularly if ni or nt is large. The results of parallel simulations will however be more prone to variation.
Note: the following option is relevant only to multithreaded implementations of the NAG Library.
Serial Levels i Default =1
i=sl, the number of levels to be evaluated in serial before initializing parallelization. For relatively trivial integrands, this may need to be set greater than the default to reduce parallel overhead.
D01 Chapter Contents
D01 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


D01FBF : NAG Library, Mark 26

D01 Chapter Contents
D01 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

D01FBF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

D01FBF computes an estimate of a multidimensional integral (from 1 to 20 dimensions), given the analytic form of the integrand and suitable Gaussian weights and abscissae.

2 Specification

FUNCTION D01FBF ( NDIM, NPTVEC, LWA, WEIGHT, ABSCIS, FUN, IFAIL)
REAL (KIND=nag_wp) D01FBF
INTEGER | NDIM, NPTVEC(NDIM), LWA, IFAIL
REAL (KIND=nag_wp) | WEIGHT(LWA), ABSCIS(LWA), FUN
EXTERNAL | FUN

3 Description

D01FBF approximates a multidimensional integral by evaluating the summation
∑i 1=1 l 1 w 1,i 1 ∑i 2=1 l 2 w 2,i 2 ⋯ ∑in=1 ln w n,in f x 1 , i 1 , x 2 , i 2 ,…, x n , in
given the weights w j,ij and abscissae x j,ij for a multidimensional product integration rule (see Davis and Rabinowitz (1975)). The number of dimensions may be anything from 1 to 20.
The weights and abscissae for each dimension must have been placed in successive segments of the arrays WEIGHT and ABSCIS; for example, by calling D01BCF or D01TBF once for each dimension using a quadrature formula and number of abscissae appropriate to the range of each xj and to the functional dependence of f on xj.
If normal weights are used, the summation will approximate the integral
∫w 1 x 1∫w 2 x 2⋯∫wn xn f x 1,x 2,…,xn d xn⋯d x 2 d x 1
where wj x is the weight function associated with the quadrature formula chosen for the jth dimension; while if adjusted weights are used, the summation will approximate the integral
∫∫⋯∫f x 1,x 2,…,xn d xn⋯d x 2 d x 1.
You must supply a subroutine to evaluate
f x 1,x 2,…,xn
at any values of x 1,x 2,…,xn within the range of integration.

4 References

Davis P J and Rabinowitz P (1975) Methods of Numerical Integration Academic Press

5 Arguments

1:   NDIM – INTEGERInput
On entry: n, the number of dimensions of the integral.
Constraint: 1≤NDIM≤20.
2:   NPTVEC NDIM – INTEGER arrayInput
On entry: NPTVEC j must specify the number of points in the jth dimension of the summation, for j=1,2,…,n.
3:   LWA – INTEGERInput
On entry: the dimension of the arrays WEIGHT and ABSCIS as declared in the (sub)program from which D01FBF is called.
Constraint: LWA≥NPTVEC 1+NPTVEC 2+⋯+NPTVEC NDIM.
4:   WEIGHT LWA – REAL (KIND=nag_wp) arrayInput
On entry: must contain in succession the weights for the various dimensions, i.e., WEIGHT k contains the ith weight for the jth dimension, with
k=NPTVEC 1+NPTVEC 2+⋯+NPTVEC j-1+i.
5:   ABSCIS LWA – REAL (KIND=nag_wp) arrayInput
On entry: must contain in succession the abscissae for the various dimensions, i.e., ABSCIS k contains the ith abscissa for the jth dimension, with
k=NPTVEC 1+NPTVEC 2+⋯+NPTVEC j-1+i.
6:   FUN – REAL (KIND=nag_wp) FUNCTION, supplied by the user.External Procedure
FUN must return the value of the integrand f at a specified point.
The specification of FUN is:
FUNCTION FUN ( NDIM, X)
REAL (KIND=nag_wp) FUN
INTEGER | NDIM
REAL (KIND=nag_wp) | X(NDIM)
1:   NDIM – INTEGERInput
On entry: n, the number of dimensions of the integral.
2:   X NDIM – REAL (KIND=nag_wp) arrayInput
On entry: the coordinates of the point at which the integrand f must be evaluated.
FUN must either be a module subprogram USEd by, or declared as EXTERNAL in, the (sub)program from which D01FBF is called. Arguments denoted as Input must not be changed by this procedure.
7:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, | NDIM<1,
or | NDIM>20,
or | LWA<NPTVEC 1+NPTVEC 2+⋯+NPTVEC NDIM.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

The accuracy of the computed multidimensional sum depends on the weights and the integrand values at the abscissae. If these numbers vary significantly in size and sign then considerable accuracy could be lost. If these numbers are all positive, then little accuracy will be lost in computing the sum.

8 Parallelism and Performance

D01FBF is not threaded in any implementation.

9 Further Comments

The total time taken by D01FBF will be proportional to
T×NPTVEC 1×NPTVEC 2×⋯×NPTVEC NDIM,
where T is the time taken for one evaluation of FUN.

10 Example

This example evaluates the integral
∫12∫0∞∫-∞∞∫1∞ x 1x 2x 3 6 x 4+2 8 e-2 x 2e-0.5 x 32 d x 4 d x 3 d x 2 d x 1
using adjusted weights. The quadrature formulae chosen are:
  • x 1: Gauss–Legendre, a=1.0, b=2.0,
  • x 2: Gauss–Laguerre, a=0.0, b=2.0,
  • x 3: Gauss–Hermite, a=0.0, b=0.5,
  • x 4: rational Gauss, a=1.0, b=2.0.
Four points are sufficient in each dimension, as this integral is in fact a product of four one-dimensional integrals, for each of which the chosen four-point formula is exact.

10.1 Program Text

Program Text (d01fbfe.f90)

10.2 Program Data

None.

10.3 Program Results

Program Results (d01fbfe.r)

D01 Chapter Contents
D01 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


D01FCF : NAG Library, Mark 26

D01 Chapter Contents
D01 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

D01FCF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

D01FCF attempts to evaluate a multidimensional integral (up to 15 dimensions), with constant and finite limits, to a specified relative accuracy, using an adaptive subdivision strategy.

2 Specification

SUBROUTINE D01FCF ( NDIM, A, B, MINPTS, MAXPTS, FUNCTN, EPS, ACC, LENWRK, WRKSTR, FINVAL, IFAIL)
INTEGER | NDIM, MINPTS, MAXPTS, LENWRK, IFAIL
REAL (KIND=nag_wp) | A(NDIM), B(NDIM), FUNCTN, EPS, ACC, WRKSTR(LENWRK), FINVAL
EXTERNAL | FUNCTN

3 Description

D01FCF returns an estimate of a multidimensional integral over a hyper-rectangle (i.e., with constant limits), and also an estimate of the relative error. You set the relative accuracy required, return values for the integrand via a routine argument FUNCTN, and also set the minimum and maximum acceptable number of calls to FUNCTN (in MINPTS and MAXPTS).
The routine operates by repeated subdivision of the hyper-rectangular region into smaller hyper-rectangles. In each subregion, the integral is estimated using a seventh-degree rule, and an error estimate is obtained by comparison with a fifth-degree rule which uses a subset of the same points. The fourth differences of the integrand along each coordinate axis are evaluated, and the subregion is marked for possible future subdivision in half along that coordinate axis which has the largest absolute fourth difference.
If the estimated errors, totalled over the subregions, exceed the requested relative error (or if fewer than MINPTS calls to FUNCTN have been made), further subdivision is necessary, and is performed on the subregion with the largest estimated error, that subregion being halved along the appropriate coordinate axis.
The routine will fail if the requested relative error level has not been attained by the time MAXPTS calls to FUNCTN have been made; or, if the amount LENWRK of working storage is insufficient. A formula for the recommended value of LENWRK is given in Section 5. If a smaller value is used, and is exhausted in the course of execution, the routine switches to a less efficient mode of operation; only if this mode also breaks down is insufficient storage reported.
D01FCF is based on the HALF subroutine developed by van Dooren and de Ridder (1976). It uses a different basic rule, described in Genz and Malik (1980).

4 References

Genz A C and Malik A A (1980) An adaptive algorithm for numerical integration over an N-dimensional rectangular region J. Comput. Appl. Math. 6 295–302
van Dooren P and de Ridder L (1976) An adaptive algorithm for numerical integration over an N-dimensional cube J. Comput. Appl. Math. 2 207–217

5 Arguments

1:   NDIM – INTEGERInput
On entry: n, the number of dimensions of the integral.
Constraint: 2≤NDIM≤15.
2:   A NDIM – REAL (KIND=nag_wp) arrayInput
On entry: the lower limits of integration, ai, for i=1,2,…,n.
3:   B NDIM – REAL (KIND=nag_wp) arrayInput
On entry: the upper limits of integration, bi, for i=1,2,…,n.
4:   MINPTS – INTEGERInput/Output
On entry: must be set to the minimum number of integrand evaluations to be allowed.
On exit: contains the actual number of integrand evaluations used by D01FCF.
5:   MAXPTS – INTEGERInput
On entry: the maximum number of integrand evaluations to be allowed.
Constraints:
  • MAXPTS≥MINPTS;
  • MAXPTS≥α, where α=2 NDIM+2×NDIM 2+2×NDIM+1.
6:   FUNCTN – REAL (KIND=nag_wp) FUNCTION, supplied by the user.External Procedure
FUNCTN must return the value of the integrand f at a given point.
The specification of FUNCTN is:
FUNCTION FUNCTN ( NDIM, Z)
REAL (KIND=nag_wp) FUNCTN
INTEGER | NDIM
REAL (KIND=nag_wp) | Z(NDIM)
1:   NDIM – INTEGERInput
On entry: n, the number of dimensions of the integral.
2:   Z NDIM – REAL (KIND=nag_wp) arrayInput
On entry: the coordinates of the point at which the integrand f must be evaluated.
FUNCTN must either be a module subprogram USEd by, or declared as EXTERNAL in, the (sub)program from which D01FCF is called. Arguments denoted as Input must not be changed by this procedure.
7:   EPS – REAL (KIND=nag_wp)Input
On entry: the relative error acceptable to you. When the solution is zero or very small relative accuracy may not be achievable but you may still set EPS to a reasonable value and check for the error exit IFAIL=2.
Constraint: EPS>0.0.
8:   ACC – REAL (KIND=nag_wp)Output
On exit: the estimated relative error in FINVAL.
9:   LENWRK – INTEGERInput
On entry: the dimension of the array WRKSTR as declared in the (sub)program from which D01FCF is called.
Suggested value: for maximum efficiency, LENWRK≥NDIM+2×1+MAXPTS/α (see argument MAXPTS for α).
If LENWRK is less than this, D01FCF will usually run less efficiently and may fail.
Constraint: LENWRK≥2×NDIM+4.
10:   WRKSTR LENWRK – REAL (KIND=nag_wp) arrayWorkspace
11:   FINVAL – REAL (KIND=nag_wp)Output
On exit: the best estimate obtained for the integral.
12:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, because for this routine the values of the output arguments may be useful even if IFAIL≠0 on exit, the recommended value is -1. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Note: D01FCF may return useful information for one or more of the following detected errors or warnings.
Errors or warnings detected by the routine:
IFAIL=1
On entry, | NDIM<2,
or | NDIM>15,
or | MAXPTS is too small,
or | LENWRK<2×NDIM+4,
or | EPS≤0.0.
IFAIL=2
MAXPTS was too small to obtain the required relative accuracy EPS. On soft failure, FINVAL and ACC contain estimates of the integral and the relative error, but ACC will be greater than EPS.
IFAIL=3
LENWRK was too small. On soft failure, FINVAL and ACC contain estimates of the integral and the relative error, but ACC will be greater than EPS.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

A relative error estimate is output through the argument ACC.

8 Parallelism and Performance

D01FCF is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
D01FCF makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

Execution time will usually be dominated by the time taken to evaluate FUNCTN, and hence the maximum time that could be taken will be proportional to MAXPTS.

10 Example

This example estimates the integral
∫01 ∫01 ∫01 ∫01 4 z 1 z 32 exp 2 z 1 z 3 1+ z 2+ z 4 2 d z 4 d z 3 d z 2 d z 1 = 0.575364 .
The accuracy requested is one part in 10000.

10.1 Program Text

Program Text (d01fcfe.f90)

10.2 Program Data

None.

10.3 Program Results

Program Results (d01fcfe.r)

D01 Chapter Contents
D01 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


D01FDF : NAG Library, Mark 26

D01 Chapter Contents
D01 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

D01FDF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

D01FDF calculates an approximation to a definite integral in up to 30 dimensions, using the method of Sag and Szekeres (see Sag and Szekeres (1964)). The region of integration is an n-sphere, or by built-in transformation via the unit n-cube, any product region.

2 Specification

SUBROUTINE D01FDF ( NDIM, F, SIGMA, REGION, LIMIT, R0, U, RESULT, NCALLS, IFAIL)
INTEGER | NDIM, LIMIT, NCALLS, IFAIL
REAL (KIND=nag_wp) | F, SIGMA, R0, U, RESULT
EXTERNAL | F, REGION

3 Description

D01FDF calculates an approximation to
∫ n-sphere of radius σ f x 1,x 2,…,xn d x 1 d x 2 ⋯ d xn (1)
or, more generally,
∫ c 1 d 1 d x 1 ⋯ ∫ cn dn d xn f x 1,…,xn (2)
where each ci and di may be functions of xj j<i.
The routine uses the method of Sag and Szekeres (1964), which exploits a property of the shifted p-point trapezoidal rule, namely, that it integrates exactly all polynomials of degree <p (see Krylov (1962)). An attempt is made to induce periodicity in the integrand by making a parameterised transformation to the unit n-sphere. The Jacobian of the transformation and all its direct derivatives vanish rapidly towards the surface of the unit n-sphere, so that, except for functions which have strong singularities on the boundary, the resulting integrand will be pseudo-periodic. In addition, the variation in the integrand can be considerably reduced, causing the trapezoidal rule to perform well.
Integrals of the form (1) are transformed to the unit n-sphere by the change of variables:
xi = yi σr tanh ur 1-r 2
where r 2=∑i=1 n yi 2 and u is an adjustable parameter.
Integrals of the form (2) are first of all transformed to the n-cube -1,1 n by a linear change of variables
xi=di+ci+di-ci yi/2
and then to the unit sphere by a further change of variables
yi=tanh u zi 1-r
where r 2=∑i=1 n zi 2 and u is again an adjustable parameter.
The parameter u in these transformations determines how the transformed integrand is distributed between the origin and the surface of the unit n-sphere. A typical value of u is 1.5. For larger u, the integrand is concentrated toward the centre of the unit n-sphere, while for smaller u it is concentrated toward the perimeter.
In performing the integration over the unit n-sphere by the trapezoidal rule, a displaced equidistant grid of size h is constructed. The points of the mesh lie on concentric layers of radius
ri=h 4 n+8 i-1,  i=1,2,3,….
The routine requires you to specify an approximate maximum number of points to be used, and then computes the largest number of whole layers to be used, subject to an upper limit of 400 layers.
In practice, the rapidly-decreasing Jacobian makes it unnecessary to include the whole unit n-sphere and the integration region is limited by a user-specified cut-off radius r 0<1. The grid-spacing h is determined by r 0 and the number of layers to be used. A typical value of r 0 is 0.8.
Some experimentation may be required with the choice of r 0 (which determines how much of the unit n-sphere is included) and u (which determines how the transformed integrand is distributed between the origin and surface of the unit n-sphere), to obtain best results for particular families of integrals. This matter is discussed further in Section 9.

4 References

Krylov V I (1962) Approximate Calculation of Integrals (trans A H Stroud) Macmillan
Sag T W and Szekeres G (1964) Numerical evaluation of high-dimensional integrals Math. Comput. 18 245–253

5 Arguments

1:   NDIM – INTEGERInput
On entry: n, the number of dimensions of the integral.
Constraint: 1≤NDIM≤30.
2:   F – REAL (KIND=nag_wp) FUNCTION, supplied by the user.External Procedure
F must return the value of the integrand f at a given point.
The specification of F is:
FUNCTION F ( NDIM, X)
REAL (KIND=nag_wp) F
INTEGER | NDIM
REAL (KIND=nag_wp) | X(NDIM)
1:   NDIM – INTEGERInput
On entry: n, the number of dimensions of the integral.
2:   X NDIM – REAL (KIND=nag_wp) arrayInput
On entry: the coordinates of the point at which the integrand f must be evaluated.
F must either be a module subprogram USEd by, or declared as EXTERNAL in, the (sub)program from which D01FDF is called. Arguments denoted as Input must not be changed by this procedure.
3:   SIGMA – REAL (KIND=nag_wp)Input
On entry: indicates the region of integration.
SIGMA≥0.0
The integration is carried out over the n-sphere of radius SIGMA, centred at the origin.
SIGMA<0.0
The integration is carried out over the product region described by REGION.
4:   REGION – SUBROUTINE, supplied by the NAG Library or the user.External Procedure
If SIGMA<0.0, REGION must evaluate the limits of integration in any dimension.
The specification of REGION is:
SUBROUTINE REGION ( NDIM, X, J, C, D)
INTEGER | NDIM, J
REAL (KIND=nag_wp) | X(NDIM), C, D
1:   NDIM – INTEGERInput
On entry: n, the number of dimensions of the integral.
2:   X NDIM – REAL (KIND=nag_wp) arrayInput
On entry: X 1,…,X j-1 contain the current values of the first j-1 variables, which may be used if necessary in calculating cj and dj.
3:   J – INTEGERInput
On entry: the index j for which the limits of the range of integration are required.
4:   C – REAL (KIND=nag_wp)Output
On exit: the lower limit cj of the range of xj.
5:   D – REAL (KIND=nag_wp)Output
On exit: the upper limit dj of the range of xj.
REGION must either be a module subprogram USEd by, or declared as EXTERNAL in, the (sub)program from which D01FDF is called. Arguments denoted as Input must not be changed by this procedure.
If SIGMA≥0.0, REGION is not called by D01FDF, but a dummy routine must be supplied (D01FDV may be used).
5:   LIMIT – INTEGERInput
On entry: the approximate maximum number of integrand evaluations to be used.
Constraint: LIMIT≥100.
6:   R0 – REAL (KIND=nag_wp)Input
On entry: the cut-off radius on the unit n-sphere, which may be regarded as an adjustable parameter of the method.
Suggested value: a typical value is R0=0.8. (See also Section 9.)
Constraint: 0.0<R0<1.0.
7:   U – REAL (KIND=nag_wp)Input
On entry: must specify an adjustable parameter of the transformation to the unit n-sphere.
Suggested value: a typical value is U=1.5. (See also Section 9.)
Constraint: U>0.0.
8:   RESULT – REAL (KIND=nag_wp)Output
On exit: the approximation to the integral I.
9:   NCALLS – INTEGEROutput
On exit: the actual number of integrand evaluations used. (See also Section 9.)
10:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, | NDIM<1,
or | NDIM>30.
IFAIL=2
On entry, LIMIT<100.
IFAIL=3
On entry, | R0≤0.0,
or | R0≥1.0.
IFAIL=4
On entry, U≤0.0.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

No error estimate is returned, but results may be verified by repeating with an increased value of LIMIT (provided that this causes an increase in the returned value of NCALLS).

8 Parallelism and Performance

D01FDF is not threaded in any implementation.

9 Further Comments

The time taken by D01FDF will be approximately proportional to the returned value of NCALLS, which, except in the circumstances outlined in (b) below, will be close to the given value of LIMIT.
(a) Choice of r 0 and u
If the chosen combination of r 0 and u is too large in relation to the machine accuracy it is possible that some of the points generated in the original region of integration may transform into points in the unit n-sphere which lie too close to the boundary surface to be distinguished from it to machine accuracy (despite the fact that r 0<1). To be specific, the combination of r 0 and u is too large if
u r 0 1-r 02 >0.3465 t-1,   if ​SIGMA≥0.0,
or
u r 0 1-r 0 > 0.3465 t- 1,   if ​ SIGMA< 0.0,
where t is the number of bits in the mantissa of a real number.
The contribution of such points to the integral is neglected. This may be justified by appeal to the fact that the Jacobian of the transformation rapidly approaches zero towards the surface. Neglect of these points avoids the occurrence of overflow with integrands which are infinite on the boundary.
(b) Values of LIMIT and NCALLS
LIMIT is an approximate upper limit to the number of integrand evaluations, and may not be chosen less than 100. There are two circumstances when the returned value of NCALLS (the actual number of evaluations used) may be significantly less than LIMIT.
Firstly, as explained in (a), an unsuitably large combination of r 0 and u may result in some of the points being unusable. Such points are not included in the returned value of NCALLS.
Secondly, no more than 400 layers will ever be used, no matter how high LIMIT is set. This places an effective upper limit on NCALLS as follows:
n=1: 56 n=2: 1252 n=3: 23690 n=4: 394528 n=5: 5956906

10 Example

This example calculates the integral
∫∫∫s d x 1 d x 2 d x 3 σ 2-r 2 =22.2066
where s is the 3-sphere of radius σ, r 2=x 12+x 22+x 32 and σ=1.5. Both sphere-to-sphere and general product region transformations are used. For the former, we use r 0=0.9 and u=1.5; for the latter, r 0=0.8 and u=1.5.

10.1 Program Text

Program Text (d01fdfe.f90)

10.2 Program Data

None.

10.3 Program Results

Program Results (d01fdfe.r)

D01 Chapter Contents
D01 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


D01GAF : NAG Library, Mark 26

D01 Chapter Contents
D01 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

D01GAF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

D01GAF integrates a function which is specified numerically at four or more points, over the whole of its specified range, using third-order finite difference formulae with error estimates, according to a method due to Gill and Miller (1972).

2 Specification

SUBROUTINE D01GAF ( X, Y, N, ANS, ER, IFAIL)
INTEGER | N, IFAIL
REAL (KIND=nag_wp) | X(N), Y(N), ANS, ER

3 Description

D01GAF evaluates the definite integral
I = ∫ x 1 xn y x dx ,
where the function y is specified at the n-points x 1,x 2,…,xn, which should be all distinct, and in either ascending or descending order. The integral between successive points is calculated by a four-point finite difference formula centred on the interval concerned, except in the case of the first and last intervals, where four-point forward and backward difference formulae respectively are employed. If n is less than 4, the routine fails. An approximation to the truncation error is integrated and added to the result. It is also returned separately to give an estimate of the uncertainty in the result. The method is due to Gill and Miller (1972).

4 References

Gill P E and Miller G F (1972) An algorithm for the integration of unequally spaced data Comput. J. 15 80–83

5 Arguments

1:   X N – REAL (KIND=nag_wp) arrayInput
On entry: the values of the independent variable, i.e., the x 1,x 2,…,xn.
Constraint: either X 1<X 2<⋯<X N or X 1>X 2>⋯>X N.
2:   Y N – REAL (KIND=nag_wp) arrayInput
On entry: the values of the dependent variable yi at the points xi, for i=1,2,…,n.
3:   N – INTEGERInput
On entry: n, the number of points.
Constraint: N≥4.
4:   ANS – REAL (KIND=nag_wp)Output
On exit: the estimated value of the integral.
5:   ER – REAL (KIND=nag_wp)Output
On exit: an estimate of the uncertainty in ANS.
6:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
Indicates that fewer than four points have been supplied to D01GAF.
IFAIL=2
Values of X are neither strictly increasing nor strictly decreasing.
IFAIL=3
Two points have the same X-value.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.
No error is reported arising from the relative magnitudes of ANS and ER on return, due to the difficulty when the true answer is zero.

7 Accuracy

No accuracy level is specified by you before calling D01GAF but on return the absolute value of ER is an approximation to, but not necessarily a bound for, I-ANS. If on exit IFAIL>0, both ANS and ER are returned as zero.

8 Parallelism and Performance

D01GAF is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The time taken by D01GAF depends on the number of points supplied, n.
In their paper, Gill and Miller (1972) do not add the quantity ER to ANS before return. However, extensive tests have shown that a dramatic reduction in the error often results from such addition. In other cases, it does not make an improvement, but these tend to be cases of low accuracy in which the modified answer is not significantly inferior to the unmodified one. You have the option of recovering the Gill–Miller answer by subtracting ER from ANS on return from the routine.

10 Example

This example evaluates the integral
∫01 4 1+x 2 dx = π
reading in the function values at 21 unequally spaced points.

10.1 Program Text

Program Text (d01gafe.f90)

10.2 Program Data

Program Data (d01gafe.d)

10.3 Program Results

Program Results (d01gafe.r)

D01 Chapter Contents
D01 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


D01GBF : NAG Library, Mark 26

D01 Chapter Contents
D01 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

D01GBF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
▸▿ 9 Further Comments
9.1 Additional Information
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

D01GBF returns an approximation to the integral of a function over a hyper-rectangular region, using a Monte–Carlo method. An approximate relative error estimate is also returned. This routine is suitable for low accuracy work.

2 Specification

SUBROUTINE D01GBF ( NDIM, A, B, MINCLS, MAXCLS, FUNCTN, EPS, ACC, LENWRK, WRKSTR, FINEST, IFAIL)
INTEGER | NDIM, MINCLS, MAXCLS, LENWRK, IFAIL
REAL (KIND=nag_wp) | A(NDIM), B(NDIM), FUNCTN, EPS, ACC, WRKSTR(LENWRK), FINEST
EXTERNAL | FUNCTN

3 Description

D01GBF uses an adaptive Monte–Carlo method based on the algorithm described in Lautrup (1971). It is implemented for integrals of the form:
∫ a 1 b 1 ∫ a 2 b 2 ⋯ ∫ an bn f x 1,x 2,…,xn d xn ⋯ d x 2 d x 1 .
Upon entry, unless LENWRK has been set to the minimum value 10×NDIM, the routine subdivides the integration region into a number of equal volume subregions. Inside each subregion the integral and the variance are estimated by means of pseudorandom sampling. All contributions are added together to produce an estimate for the whole integral and total variance. The variance along each coordinate axis is determined and the routine uses this information to increase the density and change the widths of the sub-intervals along each axis, so as to reduce the total variance. The total number of subregions is then increased by a factor of two and the program recycles for another iteration. The program stops when a desired accuracy has been reached or too many integral evaluations are needed for the next cycle.

4 References

Lautrup B (1971) An adaptive multi-dimensional integration procedure Proc. 2nd Coll. Advanced Methods in Theoretical Physics, Marseille

5 Arguments

1:   NDIM – INTEGERInput
On entry: n, the number of dimensions of the integral.
Constraint: NDIM≥1.
2:   A NDIM – REAL (KIND=nag_wp) arrayInput
On entry: the lower limits of integration, ai, for i=1,2,…,n.
3:   B NDIM – REAL (KIND=nag_wp) arrayInput
On entry: the upper limits of integration, bi, for i=1,2,…,n.
4:   MINCLS – INTEGERInput/Output
On entry: must be set
  • either to the minimum number of integrand evaluations to be allowed, in which case MINCLS≥0;
  • or to a negative value. In this case, the routine assumes that a previous call had been made with the same arguments NDIM, A and B and with either the same integrand (in which case D01GBF continues calculation) or a similar integrand (in which case D01GBF begins the calculation with the subdivision used in the last iteration of the previous call). See also WRKSTR.
On exit: contains the number of integrand evaluations actually used by D01GBF.
5:   MAXCLS – INTEGERInput
On entry: the maximum number of integrand evaluations to be allowed. In the continuation case this is the number of new integrand evaluations to be allowed. These counts do not include zero integrand values.
Constraints:
  • MAXCLS>MINCLS;
  • MAXCLS≥4×NDIM+1.
6:   FUNCTN – REAL (KIND=nag_wp) FUNCTION, supplied by the user.External Procedure
FUNCTN must return the value of the integrand f at a given point.
The specification of FUNCTN is:
FUNCTION FUNCTN ( NDIM, X)
REAL (KIND=nag_wp) FUNCTN
INTEGER | NDIM
REAL (KIND=nag_wp) | X(NDIM)
1:   NDIM – INTEGERInput
On entry: n, the number of dimensions of the integral.
2:   X NDIM – REAL (KIND=nag_wp) arrayInput
On entry: the coordinates of the point at which the integrand f must be evaluated.
FUNCTN must either be a module subprogram USEd by, or declared as EXTERNAL in, the (sub)program from which D01GBF is called. Arguments denoted as Input must not be changed by this procedure.
7:   EPS – REAL (KIND=nag_wp)Input
On entry: the relative accuracy required.
Constraint: EPS≥0.0.
8:   ACC – REAL (KIND=nag_wp)Output
On exit: the estimated relative accuracy of FINEST.
9:   LENWRK – INTEGERInput
On entry: the dimension of the array WRKSTR as declared in the (sub)program from which D01GBF is called.
For maximum efficiency, LENWRK should be about
3×NDIM×MAXCLS/4 1/NDIM+7×NDIM.
If LENWRK is given the value 10×NDIM then the subroutine uses only one iteration of a crude Monte–Carlo method with MAXCLS sample points.
Constraint: LENWRK≥10×NDIM.
10:   WRKSTR LENWRK – REAL (KIND=nag_wp) arrayInput/Output
On entry: if MINCLS<0, WRKSTR must be unchanged from the previous call of D01GBF – except that for a new integrand WRKSTR LENWRK must be set to 0.0. See also MINCLS.
On exit: contains information about the current sub-interval structure which could be used in later calls of D01GBF. In particular, WRKSTR j gives the number of sub-intervals used along the jth coordinate axis.
11:   FINEST – REAL (KIND=nag_wp)Input/Output
On entry: must be unchanged from a previous call to D01GBF.
On exit: the best estimate obtained for the integral.
12:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, because for this routine the values of the output arguments may be useful even if IFAIL≠0 on exit, the recommended value is -1. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, | NDIM<1,
or | MINCLS≥MAXCLS,
or | LENWRK<10×NDIM,
or | MAXCLS<4×NDIM+1,
or | EPS<0.0.
IFAIL=2
MAXCLS was too small for D01GBF to obtain the required relative accuracy EPS. In this case D01GBF returns a value of FINEST with estimated relative error ACC, but ACC will be greater than EPS. This error exit may be taken before MAXCLS nonzero integrand evaluations have actually occurred, if the routine calculates that the current estimates could not be improved before MAXCLS was exceeded.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

A relative error estimate is output through the argument ACC. The confidence factor is set so that the actual error should be less than ACC 90% of the time. If you want a higher confidence level then a smaller value of EPS should be used.

8 Parallelism and Performance

D01GBF is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The running time for D01GBF will usually be dominated by the time used to evaluate the integrand f, so the maximum time that could be used is approximately proportional to MAXCLS.
For some integrands, particularly those that are poorly behaved in a small part of the integration region, D01GBF may terminate with a value of ACC which is significantly smaller than the actual relative error. This should be suspected if the returned value of MINCLS is small relative to the expected difficulty of the integral. Where this occurs, D01GBF should be called again, but with a higher entry value of MINCLS (e.g., twice the returned value) and the results compared with those from the previous call.

9.1 Additional Information

The exact values of FINEST and ACC on return will depend (within statistical limits) on the sequence of random numbers generated within this routine.

10 Example

This example calculates the integral
∫01∫01∫01∫01 4 x 1x 3 exp 2 x 1x 3 1+x 2+x 4 2 d x 1 d x 2 d x 3 d x 4=0.575364.

10.1 Program Text

Program Text (d01gbfe.f90)

10.2 Program Data

None.

10.3 Program Results

Program Results (d01gbfe.r)

D01 Chapter Contents
D01 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


D01GCF : NAG Library, Mark 26

D01 Chapter Contents
D01 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

D01GCF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

D01GCF calculates an approximation to a definite integral in up to 20 dimensions, using the Korobov–Conroy number theoretic method.

2 Specification

SUBROUTINE D01GCF ( NDIM, F, REGION, NPTS, VK, NRAND, ITRANS, RES, ERR, IFAIL)
INTEGER | NDIM, NPTS, NRAND, ITRANS, IFAIL
REAL (KIND=nag_wp) | F, VK(NDIM), RES, ERR
EXTERNAL | F, REGION

3 Description

D01GCF calculates an approximation to the integral
I= ∫ c 1 d 1 d x 1 ,…, ∫ cn dn d xn   f x 1,x 2,…,xn (1)
using the Korobov–Conroy number theoretic method (see Korobov (1957), Korobov (1963) and Conroy (1967)). The region of integration defined in (1) is such that generally ci and di may be functions of x 1 , x 2 ,…, x i-1 , for i= 2 , 3 ,…, n , with c 1 and d 1 constants. The integral is first of all transformed to an integral over the n-cube 0,1 n by the change of variables
xi = ci + di - ci yi ,   i= 1 , 2 ,…, n .
The method then uses as its basis the number theoretic formula for the n-cube, 0,1 n :
∫01 d x 1 ⋯ ∫01 d xn g x 1,x 2,…,xn = 1 p ∑k=1 p g k a 1 p ,…, k an p - E (2)
where x denotes the fractional part of x, a 1 , a 2 ,…, an are the so-called optimal coefficients, E is the error, and p is a prime integer. (It is strictly only necessary that p be relatively prime to all a 1 , a 2 ,…, an and is in fact chosen to be even for some cases in Conroy (1967).) The method makes use of properties of the Fourier expansion of g x 1,x 2,…,xn which is assumed to have some degree of periodicity. Depending on the choice of a 1 , a 2 ,…, an the contributions from certain groups of Fourier coefficients are eliminated from the error, E. Korobov shows that a 1 , a 2 ,…, an can be chosen so that the error satisfies
E≤CK p-α ln αβ ⁡p (3)
where α and C are real numbers depending on the convergence rate of the Fourier series, β is a constant depending on n, and K is a constant depending on α and n. There are a number of procedures for calculating these optimal coefficients. Korobov imposes the constraint that
a 1 = 1   and   ai = a i-1 mod p (4)
and gives a procedure for calculating the argument, a, to satisfy the optimal conditions.
In this routine the periodisation is achieved by the simple transformation
xi = yi 2 3-2 yi ,   i= 1 , 2 ,…, n .
More sophisticated periodisation procedures are available but in practice the degree of periodisation does not appear to be a critical requirement of the method.
An easily calculable error estimate is not available apart from repetition with an increasing sequence of values of p which can yield erratic results. The difficulties have been studied by Cranley and Patterson (1976) who have proposed a Monte–Carlo error estimate arising from converting (2) into a stochastic integration rule by the inclusion of a random origin shift which leaves the form of the error (3) unchanged; i.e., in the formula (2), k ai p is replaced by αi+k ai p , for i= 1 , 2 ,…, n , where each αi , is uniformly distributed over 0,1 . Computing the integral for each of a sequence of random vectors α allows a ‘standard error’ to be estimated.
This routine provides built-in sets of optimal coefficients, corresponding to six different values of p. Alternatively, the optimal coefficients may be supplied by you. Routines D01GYF and D01GZF compute the optimal coefficients for the cases where p is a prime number or p is a product of two primes, respectively.

4 References

Conroy H (1967) Molecular Shroedinger equation VIII. A new method for evaluting multi-dimensional integrals J. Chem. Phys. 47 5307–5318
Cranley R and Patterson T N L (1976) Randomisation of number theoretic methods for mulitple integration SIAM J. Numer. Anal. 13 904–914
Korobov N M (1957) The approximate calculation of multiple integrals using number theoretic methods Dokl. Acad. Nauk SSSR 115 1062–1065
Korobov N M (1963) Number Theoretic Methods in Approximate Analysis Fizmatgiz, Moscow

5 Arguments

1:   NDIM – INTEGERInput
On entry: n, the number of dimensions of the integral.
Constraint: 1≤NDIM≤20.
2:   F – REAL (KIND=nag_wp) FUNCTION, supplied by the user.External Procedure
F must return the value of the integrand f at a given point.
The specification of F is:
FUNCTION F ( NDIM, X)
REAL (KIND=nag_wp) F
INTEGER | NDIM
REAL (KIND=nag_wp) | X(NDIM)
1:   NDIM – INTEGERInput
On entry: n, the number of dimensions of the integral.
2:   X NDIM – REAL (KIND=nag_wp) arrayInput
On entry: the coordinates of the point at which the integrand f must be evaluated.
F must either be a module subprogram USEd by, or declared as EXTERNAL in, the (sub)program from which D01GCF is called. Arguments denoted as Input must not be changed by this procedure.
3:   REGION – SUBROUTINE, supplied by the user.External Procedure
REGION must evaluate the limits of integration in any dimension.
The specification of REGION is:
SUBROUTINE REGION ( NDIM, X, J, C, D)
INTEGER | NDIM, J
REAL (KIND=nag_wp) | X(NDIM), C, D
1:   NDIM – INTEGERInput
On entry: n, the number of dimensions of the integral.
2:   X NDIM – REAL (KIND=nag_wp) arrayInput
On entry: X 1,…,X j-1 contain the current values of the first j-1 variables, which may be used if necessary in calculating cj and dj.
3:   J – INTEGERInput
On entry: the index j for which the limits of the range of integration are required.
4:   C – REAL (KIND=nag_wp)Output
On exit: the lower limit cj of the range of xj.
5:   D – REAL (KIND=nag_wp)Output
On exit: the upper limit dj of the range of xj.
REGION must either be a module subprogram USEd by, or declared as EXTERNAL in, the (sub)program from which D01GCF is called. Arguments denoted as Input must not be changed by this procedure.
4:   NPTS – INTEGERInput
On entry: the Korobov rule to be used. There are two alternatives depending on the value of NPTS.
(i) 1≤NPTS≤6.
In this case one of six preset rules is chosen using 2129, 5003, 10007, 20011, 40009 or 80021 points depending on the respective value of NPTS being 1, 2, 3, 4, 5 or 6.
(ii) NPTS>6.
NPTS is the number of actual points to be used with corresponding optimal coefficients supplied in the array VK.
Constraint: NPTS≥1.
5:   VK NDIM – REAL (KIND=nag_wp) arrayInput/Output
On entry: if NPTS>6, VK must contain the n optimal coefficients (which may be calculated using D01GYF or D01GZF).
If NPTS≤6, VK need not be set.
On exit: if NPTS>6, VK is unchanged.
If NPTS≤6, VK contains the n optimal coefficients used by the preset rule.
6:   NRAND – INTEGERInput
On entry: the number of random samples to be generated in the error estimation (generally a small value, say 3 to 5, is sufficient). The total number of integrand evaluations will be NRAND×NPTS.
Constraint: NRAND≥1.
7:   ITRANS – INTEGERInput
On entry: indicates whether the periodising transformation is to be used.
ITRANS='0'
The transformation is to be used.
ITRANS≠'0'
The transformation is to be suppressed (to cover cases where the integrand may already be periodic or where you want to specify a particular transformation in the definition of F).
Suggested value: ITRANS='0'.
8:   RES – REAL (KIND=nag_wp)Output
On exit: the approximation to the integral I.
9:   ERR – REAL (KIND=nag_wp)Output
On exit: the standard error as computed from NRAND sample values. If NRAND=1, then ERR contains zero.
10:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, | NDIM<1,
or | NDIM>20.
IFAIL=2
On entry, NPTS<1.
IFAIL=3
On entry, NRAND<1.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

An estimate of the absolute standard error is given by the value, on exit, of ERR.

8 Parallelism and Performance

D01GCF is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The time taken by D01GCF will be approximately proportional to NRAND×p, where p is the number of points used.
The exact values of RES and ERR on return will depend (within statistical limits) on the sequence of random numbers generated within D01GCF by calls to G05SAF. Separate runs will produce identical answers.

10 Example

This example calculates the integral
∫01 ∫01 ∫01 ∫01 cos 0.5+2 x 1 + x 2 + x 3 + x 4 - 4 d x 1 d x 2 d x 3 d x 4 .

10.1 Program Text

Program Text (d01gcfe.f90)

10.2 Program Data

None.

10.3 Program Results

Program Results (d01gcfe.r)

D01 Chapter Contents
D01 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


D01GDF : NAG Library, Mark 26

D01 Chapter Contents
D01 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

D01GDF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

D01GDF calculates an approximation to a definite integral in up to 20 dimensions, using the Korobov–Conroy number theoretic method. This routine is designed to be particularly efficient on vector processors.

2 Specification

SUBROUTINE D01GDF ( NDIM, VECFUN, VECREG, NPTS, VK, NRAND, ITRANS, RES, ERR, IFAIL)
INTEGER | NDIM, NPTS, NRAND, ITRANS, IFAIL
REAL (KIND=nag_wp) | VK(NDIM), RES, ERR
EXTERNAL | VECFUN, VECREG

3 Description

D01GDF calculates an approximation to the integral
I= ∫ c 1 d 1 ⋯ ∫ cn dn f x 1,…,xn d xn … d x 1 (1)
using the Korobov–Conroy number theoretic method (see Korobov (1957), Korobov (1963) and Conroy (1967)). The region of integration defined in (1) is such that generally ci and di may be functions of x 1 , x 2 ,…, x i-1 , for i= 2 , 3 ,…, n , with c 1 and d 1 constants. The integral is first of all transformed to an integral over the n-cube 0,1 n by the change of variables
xi = ci + di - ci yi ,   i= 1 , 2 ,…, n .
The method then uses as its basis the number theoretic formula for the n-cube, 0,1 n :
∫01 ⋯ ∫01 g x 1,…,xn d xn ⋯ d x 1 = 1 p ∑k=1 p g k a 1 p ,…, k an p - E (2)
where x denotes the fractional part of x, a 1 ,…, an are the so-called optimal coefficients, E is the error, and p is a prime integer. (It is strictly only necessary that p be relatively prime to all a 1 ,…, an and is in fact chosen to be even for some cases in Conroy (1967).) The method makes use of properties of the Fourier expansion of g x 1,…,xn which is assumed to have some degree of periodicity. Depending on the choice of a 1 ,…, an the contributions from certain groups of Fourier coefficients are eliminated from the error, E. Korobov shows that a 1 ,…, an can be chosen so that the error satisfies
E≤CK p-α ln αβ ⁡p (3)
where α and C are real numbers depending on the convergence rate of the Fourier series, β is a constant depending on n, and K is a constant depending on α and n. There are a number of procedures for calculating these optimal coefficients. Korobov imposes the constraint that
a 1 = 1   and   ai = a i-1 mod p (4)
and gives a procedure for calculating the argument, a, to satisfy the optimal conditions.
In this routine the periodisation is achieved by the simple transformation
xi = yi 2 3-2 yi ,   i= 1 , 2 ,…, n .
More sophisticated periodisation procedures are available but in practice the degree of periodisation does not appear to be a critical requirement of the method.
An easily calculable error estimate is not available apart from repetition with an increasing sequence of values of p which can yield erratic results. The difficulties have been studied by Cranley and Patterson (1976) who have proposed a Monte–Carlo error estimate arising from converting (2) into a stochastic integration rule by the inclusion of a random origin shift which leaves the form of the error (3) unchanged; i.e., in the formula (2), k ai p is replaced by αi+k ai p , for i= 1 , 2 ,…, n , where each αi , is uniformly distributed over 0,1 . Computing the integral for each of a sequence of random vectors α allows a ‘standard error’ to be estimated.
This routine provides built-in sets of optimal coefficients, corresponding to six different values of p. Alternatively, the optimal coefficients may be supplied by you. Routines D01GYF and D01GZF compute the optimal coefficients for the cases where p is a prime number or p is a product of two primes, respectively.
This routine is designed to be particularly efficient on vector processors, although it is very important that you also code VECFUN and VECREG efficiently.

4 References

Conroy H (1967) Molecular Shroedinger equation VIII. A new method for evaluting multi-dimensional integrals J. Chem. Phys. 47 5307–5318
Cranley R and Patterson T N L (1976) Randomisation of number theoretic methods for mulitple integration SIAM J. Numer. Anal. 13 904–914
Korobov N M (1957) The approximate calculation of multiple integrals using number theoretic methods Dokl. Acad. Nauk SSSR 115 1062–1065
Korobov N M (1963) Number Theoretic Methods in Approximate Analysis Fizmatgiz, Moscow

5 Arguments

1:   NDIM – INTEGERInput
On entry: n, the number of dimensions of the integral.
Constraint: 1≤NDIM≤20.
2:   VECFUN – SUBROUTINE, supplied by the user.External Procedure
VECFUN must evaluate the integrand at a specified set of points.
The specification of VECFUN is:
SUBROUTINE VECFUN ( NDIM, X, FV, M)
INTEGER | NDIM, M
REAL (KIND=nag_wp) | X(M,NDIM), FV(M)
1:   NDIM – INTEGERInput
On entry: n, the number of dimensions of the integral.
2:   X MNDIM – REAL (KIND=nag_wp) arrayInput
On entry: the coordinates of the m points at which the integrand must be evaluated. X ij contains the jth coordinate of the ith point.
3:   FV M – REAL (KIND=nag_wp) arrayOutput
On exit: FV i must contain the value of the integrand of the ith point, i.e., FV i=f X i 1,X i 2,…,X iNDIM, for i=1,2,…,M.
4:   M – INTEGERInput
On entry: the number of points m at which the integrand is to be evaluated.
VECFUN must either be a module subprogram USEd by, or declared as EXTERNAL in, the (sub)program from which D01GDF is called. Arguments denoted as Input must not be changed by this procedure.
3:   VECREG – SUBROUTINE, supplied by the user.External Procedure
VECREG must evaluate the limits of integration in any dimension for a set of points.
The specification of VECREG is:
SUBROUTINE VECREG ( NDIM, X, J, C, D, M)
INTEGER | NDIM, J, M
REAL (KIND=nag_wp) | X(M,NDIM), C(M), D(M)
1:   NDIM – INTEGERInput
On entry: n, the number of dimensions of the integral.
2:   X MNDIM – REAL (KIND=nag_wp) arrayInput
On entry: for i=1,2,…,m, X i 1, X i 2,…,X i j-1 contain the current values of the first j-1 coordinates of the ith point, which may be used if necessary in calculating the m values of cj and dj.
3:   J – INTEGERInput
On entry: the index j for which the limits of the range of integration are required.
4:   C M – REAL (KIND=nag_wp) arrayOutput
On exit: C i must be set to the lower limit of the range for X ij, for i=1,2,…,m.
5:   D M – REAL (KIND=nag_wp) arrayOutput
On exit: D i must be set to the upper limit of the range for X ij, for i=1,2,…,m.
6:   M – INTEGERInput
On entry: the number of points m at which the limits of integration must be specified.
VECREG must either be a module subprogram USEd by, or declared as EXTERNAL in, the (sub)program from which D01GDF is called. Arguments denoted as Input must not be changed by this procedure.
4:   NPTS – INTEGERInput
On entry: the Korobov rule to be used. There are two alternatives depending on the value of NPTS.
(i) 1≤NPTS≤6.
In this case one of six preset rules is chosen using 2129, 5003, 10007, 20011, 40009 or 80021 points depending on the respective value of NPTS being 1, 2, 3, 4, 5 or 6.
(ii) NPTS>6.
NPTS is the number of actual points to be used with corresponding optimal coefficients supplied in the array VK.
Constraint: NPTS≥1.
5:   VK NDIM – REAL (KIND=nag_wp) arrayInput/Output
On entry: if NPTS>6, VK must contain the n optimal coefficients (which may be calculated using D01GYF or D01GZF).
If NPTS≤6, VK need not be set.
On exit: if NPTS>6, VK is unchanged.
If NPTS≤6, VK contains the n optimal coefficients used by the preset rule.
6:   NRAND – INTEGERInput
On entry: the number of random samples to be generated (generally a small value, say 3 to 5, is sufficient). The estimate, RES, of the value of the integral returned by the routine is then the average of NRAND calculations with different random origin shifts. If NPTS>6, the total number of integrand evaluations will be NRAND×NPTS. If 1≤NPTS≤6, then the number of integrand evaluations will be NRAND×p, where p is the number of points corresponding to the six preset rules. For reasons of efficiency, these values are calculated a number at a time in VECFUN.
Constraint: NRAND≥1.
7:   ITRANS – INTEGERInput
On entry: indicates whether the periodising transformation is to be used.
ITRANS=0
The transformation is to be used.
ITRANS≠0
The transformation is to be suppressed (to cover cases where the integrand may already be periodic or where you want to specify a particular transformation in the definition of VECFUN).
Suggested value: ITRANS=0.
8:   RES – REAL (KIND=nag_wp)Output
On exit: the approximation to the integral I.
9:   ERR – REAL (KIND=nag_wp)Output
On exit: the standard error as computed from NRAND sample values. If NRAND=1, then ERR contains zero.
10:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, | NDIM<1,
or | NDIM>20.
IFAIL=2
On entry, NPTS<1.
IFAIL=3
On entry, NRAND<1.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

If NRAND>1, an estimate of the absolute standard error is given by the value, on exit, of ERR.

8 Parallelism and Performance

D01GDF is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

D01GDF performs the same computation as D01GCF. However, the interface has been modified so that it can perform more efficiently on machines with vector processing capabilities. In particular, VECFUN and VECREG must calculate the integrand and limits of integration at a set of points. For some problems the amount of time spent in these two subroutines, which must be supplied by you, may account for a significant part of the total computation time. For this reason it is vital that you consider the possibilities for vectorization in the code supplied for these two subroutines.
The time taken will be approximately proportional to NRAND×p, where p is the number of points used, but may depend significantly on the efficiency of the code provided by you in VECFUN and VECREG.
The exact values of RES and ERR on return will depend (within statistical limits) on the sequence of random numbers generated within D01GDF by calls to G05SAF. Separate runs will produce identical answers.

10 Example

This example calculates the integral
∫01 ∫01 ∫01 ∫01 cos 0.5+2 x 1 + x 2 + x 3 + x 4 - 4 d x 1 d x 2 d x 3 d x 4 .

10.1 Program Text

Program Text (d01gdfe.f90)

10.2 Program Data

None.

10.3 Program Results

Program Results (d01gdfe.r)

D01 Chapter Contents
D01 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


D01GYF : NAG Library, Mark 26

D01 Chapter Contents
D01 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

D01GYF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

D01GYF calculates the optimal coefficients for use by D01GCF and D01GDF, for prime numbers of points.

2 Specification

SUBROUTINE D01GYF ( NDIM, NPTS, VK, IFAIL)
INTEGER | NDIM, NPTS, IFAIL
REAL (KIND=nag_wp) | VK(NDIM)

3 Description

The Korobov (1963) procedure for calculating the optimal coefficients a 1,a 2,…,an for p-point integration over the n-cube 0,1 n imposes the constraint that
a 1=1  and  ai=a i-1 mod p,  i=1,2,…,n (1)
where p is a prime number and a is an adjustable argument. This argument is computed to minimize the error in the integral
3 n∫01 d x 1⋯∫01 d xn∏i=1 n 1-2 xi 2, (2)
when computed using the number theoretic rule, and the resulting coefficients can be shown to fit the Korobov definition of optimality.
The computation for large values of p is extremely time consuming (the number of elementary operations varying as p 2) and there is a practical upper limit to the number of points that can be used. Routine D01GZF is computationally more economical in this respect but the associated error is likely to be larger.

4 References

Korobov N M (1963) Number Theoretic Methods in Approximate Analysis Fizmatgiz, Moscow

5 Arguments

1:   NDIM – INTEGERInput
On entry: n, the number of dimensions of the integral.
Constraint: NDIM≥1.
2:   NPTS – INTEGERInput
On entry: p, the number of points to be used.
Constraint: NPTS must be a prime number ≥5.
3:   VK NDIM – REAL (KIND=nag_wp) arrayOutput
On exit: the n optimal coefficients.
4:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, NDIM<1.
IFAIL=2
On entry, NPTS<5.
IFAIL=3
On entry, NPTS is not a prime number.
IFAIL=4
The precision of the machine is insufficient to perform the computation exactly. Try a smaller value of NPTS, or use an implementation of higher precision.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

The optimal coefficients are returned as exact integers (though stored in a real array).

8 Parallelism and Performance

D01GYF is not threaded in any implementation.

9 Further Comments

The time taken is approximately proportional to p 2 (see Section 3).

10 Example

This example calculates the Korobov optimal coefficients where the number of dimensions is 4 and the number of points is 631.

10.1 Program Text

Program Text (d01gyfe.f90)

10.2 Program Data

None.

10.3 Program Results

Program Results (d01gyfe.r)

D01 Chapter Contents
D01 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


D01GZF : NAG Library, Mark 26

D01 Chapter Contents
D01 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

D01GZF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

D01GZF calculates the optimal coefficients for use by D01GCF and D01GDF, when the number of points is the product of two primes.

2 Specification

SUBROUTINE D01GZF ( NDIM, NP1, NP2, VK, IFAIL)
INTEGER | NDIM, NP1, NP2, IFAIL
REAL (KIND=nag_wp) | VK(NDIM)

3 Description

Korobov (1963) gives a procedure for calculating optimal coefficients for p-point integration over the n-cube 0,1 n, when the number of points is
p=p 1p 2 (1)
where p 1 and p 2 are distinct prime numbers.
The advantage of this procedure is that if p 1 is chosen to be the nearest prime integer to p 22, then the number of elementary operations required to compute the rule is of the order of p 4/3 which grows less rapidly than the number of operations required by D01GYF. The associated error is likely to be larger although it may be the only practical alternative for high values of p.

4 References

Korobov N M (1963) Number Theoretic Methods in Approximate Analysis Fizmatgiz, Moscow

5 Arguments

1:   NDIM – INTEGERInput
On entry: n, the number of dimensions of the integral.
Constraint: NDIM≥1.
2:   NP1 – INTEGERInput
On entry: the larger prime factor p 1 of the number of points in the integration rule.
Constraint: NP1 must be a prime number ≥5.
3:   NP2 – INTEGERInput
On entry: the smaller prime factor p 2 of the number of points in the integration rule. For maximum efficiency, p 22 should be close to p 1.
Constraint: NP2 must be a prime number such that NP1>NP2≥2.
4:   VK NDIM – REAL (KIND=nag_wp) arrayOutput
On exit: the n optimal coefficients.
5:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, NDIM<1.
IFAIL=2
On entry, | NP1<5,
or | NP2<2,
or | NP1≤NP2.
IFAIL=3
The value NP1×NP2 exceeds the largest integer representable on the machine, and hence the optimal coefficients could not be used in a valid call of D01GCF or D01GDF.
IFAIL=4
On entry, NP1 is not a prime number.
IFAIL=5
On entry, NP2 is not a prime number.
IFAIL=6
The precision of the machine is insufficient to perform the computation exactly. Try smaller values of NP1 or NP2, or use an implementation with higher precision.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

The optimal coefficients are returned as exact integers (though stored in a real array).

8 Parallelism and Performance

D01GZF is not threaded in any implementation.

9 Further Comments

The time taken by D01GZF grows at least as fast as p 1p 2 4/3. (See Section 3.)

10 Example

This example calculates the Korobov optimal coefficients where the number of dimensons is 4 and the number of points is the product of the two prime numbers, 89 and 11.

10.1 Program Text

Program Text (d01gzfe.f90)

10.2 Program Data

None.

10.3 Program Results

Program Results (d01gzfe.r)

D01 Chapter Contents
D01 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


D01 Chapter Introduction : NAG Library, Mark 26

D01 Chapter Contents
NAG Library Manual

NAG Library Chapter Introduction

D01 – Quadrature

▸▿ Contents

1 Scope of the Chapter
▸▿ 2 Background to the Problems
2.1 One-dimensional Integrals
2.2 Multidimensional Integrals
▸▿ 3 Recommendations on Choice and Use of Available Routines
3.1 Direct and Reverse Communication
3.2 Choice of Interface
3.3 One-dimensional Integrals over a Finite Interval
3.4 One-dimensional Integrals over a Semi-infinite or Infinite Interval
3.5 Multidimensional Integrals
4 Decision Trees
5 Functionality Index
6 Auxiliary Routines Associated with Library Routine Arguments
7 Routines Withdrawn or Scheduled for Withdrawal
8 References

1 Scope of the Chapter

This chapter provides routines for the numerical evaluation of definite integrals in one or more dimensions and for evaluating weights and abscissae of integration rules.

2 Background to the Problems

The routines in this chapter are designed to estimate:
(a) the value of a one-dimensional definite integral of the form
∫ab f x dx (1)
where f x is defined by you, either at a set of points xi,f xi, for i=1,2,…,n, where a=x 1<x 2<⋯<xn=b, or in the form of a function; and the limits of integration a,b may be finite or infinite.
Some methods are specially designed for integrands of the form
f x=w x g x (2)
which contain a factor w x, called the weight-function, of a specific form. These methods take full account of any peculiar behaviour attributable to the w x factor.
(b) the values of the one-dimensional indefinite integrals arising from (1) where the ranges of integration are interior to the interval a,b.
(c) the value of a multidimensional definite integral of the form
∫Rn f x 1,x 2,…,xn d xn⋯d x 2 d x 1 (3)
where f x 1,x 2,…,xn is a function defined by you and Rn is some region of n-dimensional space.
The simplest form of Rn is the n-rectangle defined by
ai≤xi≤bi,  i=1,2,…,n (4)
where ai and bi are constants. When ai and bi are functions of xj (j<i), the region can easily be transformed to the rectangular form (see page 266 of Davis and Rabinowitz (1975)). Some of the methods described incorporate the transformation procedure.

2.1 One-dimensional Integrals

To estimate the value of a one-dimensional integral, a quadrature rule uses an approximation in the form of a weighted sum of integrand values, i.e.,
∫ab f x dx≃∑i=1 N wi f xi. (5)
The points xi within the interval a,b are known as the abscissae, and the wi are known as the weights.
More generally, if the integrand has the form (2), the corresponding formula is
∫ab w x g x dx≃∑i=1 N wi g xi. (6)
If the integrand is known only at a fixed set of points, these points must be used as the abscissae, and the weighted sum is calculated using finite difference methods. However, if the functional form of the integrand is known, so that its value at any abscissa is easily obtained, then a wide variety of quadrature rules are available, each characterised by its choice of abscissae and the corresponding weights.
The appropriate rule to use will depend on the interval a,b – whether finite or otherwise – and on the form of any w x factor in the integrand. A suitable value of N depends on the general behaviour of f x; or of g x, if there is a w x factor present.
Among possible rules, we mention particularly the Gaussian formulae, which employ a distribution of abscissae which is optimal for f x or g x of polynomial form.
The choice of basic rules constitutes one of the principles on which methods for one-dimensional integrals may be classified. The other major basis of classification is the implementation strategy, of which some types are now presented.
(a) Single rule evaluation procedures
A fixed number of abscissae, N, is used. This number and the particular rule chosen uniquely determine the weights and abscissae. No estimate is made of the accuracy of the result.
(b) Automatic procedures
The number of abscissae, N, within a,b is gradually increased until consistency is achieved to within a level of accuracy (absolute or relative) you requested. There are essentially two ways of doing this; hybrid forms of these two methods are also possible:
(i) whole interval procedures (non-adaptive)
A series of rules using increasing values of N are successively applied over the whole interval a,b. It is clearly more economical if abscissae already used for a lower value of N can be used again as part of a higher-order formula. This principle is known as optimal extension. There is no overlap between the abscissae used in Gaussian formulae of different orders. However, the Kronrod formulae are designed to give an optimal 2 N+1-point formula by adding N+1 points to an N-point Gauss formula. Further extensions have been developed by Patterson.
(ii) adaptive procedures
The interval a,b is repeatedly divided into a number of sub-intervals, and integration rules are applied separately to each sub-interval. Typically, the subdivision process will be carried further in the neighbourhood of a sharp peak in the integrand than where the curve is smooth. Thus, the distribution of abscissae is adapted to the shape of the integrand.
Subdivision raises the problem of what constitutes an acceptable accuracy in each sub-interval. The usual global acceptability criterion demands that the sum of the absolute values of the error estimates in the sub-intervals should meet the conditions required of the error over the whole interval. Automatic extrapolation over several levels of subdivision may eliminate the effects of some types of singularities.
An ideal general-purpose method would be an automatic method which could be used for a wide variety of integrands, was efficient (i.e., required the use of as few abscissae as possible), and was reliable (i.e., always gave results to within the requested accuracy). Complete reliability is unobtainable, and generally higher reliability is obtained at the expense of efficiency, and vice versa. It must therefore be emphasized that the automatic routines in this chapter cannot be assumed to be 100% reliable. In general, however, the reliability is very high.

2.2 Multidimensional Integrals

A distinction must be made between cases of moderately low dimensionality (say, up to 4 or 5 dimensions), and those of higher dimensionality. Where the number of dimensions is limited, a one-dimensional method may be applied to each dimension, according to some suitable strategy, and high accuracy may be obtainable (using product rules). However, the number of integrand evaluations rises very rapidly with the number of dimensions, so that the accuracy obtainable with an acceptable amount of computational labour is limited; for example a product of 3-point rules in 20 dimensions would require more than 109 integrand evaluations. Special techniques such as the Monte–Carlo methods can be used to deal with high dimensions.
(a) Products of one-dimensional rules
Using a two-dimensional integral as an example, we have
∫a 1b 1∫a 2b 2 f x,y dy dx≃∑i=1 N wi ∫a 2b 2 f xi,y dy (7)
∫a 1b 1∫a 2b 2 f x,y dy dx≃∑i=1 N∑j=1 N wivj f xi,yj (8)
where wi,xi and vi,yi are the weights and abscissae of the rules used in the respective dimensions.
A different one-dimensional rule may be used for each dimension, as appropriate to the range and any weight function present, and a different strategy may be used, as appropriate to the integrand behaviour as a function of each independent variable.
For a rule-evaluation strategy in all dimensions, the formula (8) is applied in a straightforward manner. For automatic strategies (i.e., attempting to attain a requested accuracy), there is a problem in deciding what accuracy must be requested in the inner integral(s). Reference to formula (7) shows that the presence of a limited but random error in the y-integration for different values of xi can produce a ‘jagged’ function of x, which may be difficult to integrate to the desired accuracy and for this reason products of automatic one-dimensional routines should be used with caution (see Lyness (1983)).
(b) Monte–Carlo methods
These are based on estimating the mean value of the integrand sampled at points chosen from an appropriate statistical distribution function. Usually a variance reducing procedure is incorporated to combat the fundamentally slow rate of convergence of the rudimentary form of the technique. These methods can be effective by comparison with alternative methods when the integrand contains singularities or is erratic in some way, but they are of quite limited accuracy.
(c) Number theoretic methods
These are based on the work of Korobov and Conroy and operate by exploiting implicitly the properties of the Fourier expansion of the integrand. Special rules, constructed from so-called optimal coefficients, give a particularly uniform distribution of the points throughout n-dimensional space and from their number theoretic properties minimize the error on a prescribed class of integrals. The method can be combined with the Monte–Carlo procedure.
(d) Sag–Szekeres method
By transformation this method seeks to induce properties into the integrand which make it accurately integrable by the trapezoidal rule. The transformation also allows effective control over the number of integrand evaluations.
(e) Sparse grid methods
Given a set of one-dimensional quadrature rules of increasing levels of accuracy, the sparse grid method constructs an approximation to a multidimensional integral using d-dimensional tensor products of the differences between rules of adjacent levels. This provides a lower theoretical accuracy than the methods in (a), the full grid approach, which is nonetheless still sufficient for various classes of sufficiently smooth integrands. Furthermore, it requries substantially fewer evaluations than the full grid approach. Specifically, if a one-dimensional quadrature rule has N∼O 2 ℓ points, the full grid will require O 2 ld function evaluations, whereas the sparse grid of level ℓ will require O 2 ℓd ℓ-1. Hence a sparse grid approach is computationally feasible even for integrals over d∼O 100.
Sparse grid methods are deterministic, and may be viewed as automatic whole domain procedures if their level ℓ is allowed to increase.
(f) Automatic adaptive procedures
An automatic adaptive strategy in several dimensions normally involves division of the region into subregions, concentrating the divisions in those parts of the region where the integrand is worst behaved. It is difficult to arrange with any generality for variable limits in the inner integral(s). For this reason, some methods use a region where all the limits are constants; this is called a hyper-rectangle. Integrals over regions defined by variable or infinite limits may be handled by transformation to a hyper-rectangle. Integrals over regions so irregular that such a transformation is not feasible may be handled by surrounding the region by an appropriate hyper-rectangle and defining the integrand to be zero outside the desired region. Such a technique should always be followed by a Monte–Carlo method for integration.
The method used locally in each subregion produced by the adaptive subdivision process is usually one of three types: Monte–Carlo, number theoretic or deterministic. Deterministic methods are usually the most rapidly convergent but are often expensive to use for high dimensionality and not as robust as the other techniques.

3 Recommendations on Choice and Use of Available Routines

This section is divided into five subsections. The first subsection illustrates the difference between direct and reverse communication routines. The second subsection highlights the different levels of vectorization provided by different interfaces.
Sections 3.3, 3.4 and 3.5 consider in turn routines for: one-dimensional integrals over a finite interval, and over a semi-infinite or an infinite interval; and multidimensional integrals. Within each sub-section, routines are classified by the type of method, which ranges from simple rule evaluation to automatic adaptive algorithms. The recommendations apply particularly when the primary objective is simply to compute the value of one or more integrals, and in these cases the automatic adaptive routines are generally the most convenient and reliable, although also the most expensive in computing time.
Note however that in some circumstances it may be counter-productive to use an automatic routine. If the results of the quadrature are to be used in turn as input to a further computation (e.g., an ‘outer’ quadrature or an optimization problem), then this further computation may be adversely affected by the ‘jagged performance profile’ of an automatic routine; a simple rule-evaluation routine may provide much better overall performance. For further guidance, the article by Lyness (1983) is recommended.

3.1 Direct and Reverse Communication

Routines in this chapter which evaluate an integral value may be classified as either direct communication or reverse communication. See Section 3.3.3 in How to Use the NAG Library and its Documentation for a description of these terms.
Currently in this chapter the only routine explicitly using reverse communication is D01RAF.

3.2 Choice of Interface

This section concerns the design of the interface for the provision of abscissae, and the subsequent collection of calculated information, typically integrand evaluations. Vectorized interfaces typically allow for more efficient operation.
(a) Single abscissa interfaces
The algorithm will provide a single abscissa at which information is required. These are typically the most simple to use, although they may be significantly less efficient than a vectorized equivalent. Most of the algorithms in this chapter are of this type.
Examples of this include D01AJF and D01FBF.
(b) Vectorized abscissae interfaces
The algorithm will return a set of abscissae, at all of which information is required. While these are more complicated to use, they are typically more efficient than a non-vectorized equivalent. They reduce the overhead of function calls, allow the avoidance of repetition of computations common to each of the integrand evaluations, and offer greater scope for vectorization and parallelization of your code.
Examples include D01RGF, D01UAF, and the routines D01ATF and D01AUF, which are vectorized equivalents of D01AJF and D01AKF.
(c) Multiple integral interfaces
These are routines which allow for multiple integrals to be estimated simultaneously. As with (b) above, these are more complicated to use than single integral routines, however they can provide higher efficiency, particularly if several integrals require the same subcalculations at the same abscissae. They are most efficient if integrals which are supplied together are expected to have similar behaviour over the domain, particularly when the algorithm is adaptive.
Examples include D01EAF and D01RAF.

3.3 One-dimensional Integrals over a Finite Interval

(a) Integrand defined at a set of points
If f x is defined numerically at four or more points, then the Gill–Miller finite difference method (D01GAF) should be used. The interval of integration is taken to coincide with the range of x values of the points supplied. It is in the nature of this problem that any routine may be unreliable. In order to check results independently and so as to provide an alternative technique you may fit the integrand by Chebyshev series using E02ADF and then use routine E02AJF to evaluate its integral (which need not be restricted to the range of the integration points, as is the case for D01GAF). A further alternative is to fit a cubic spline to the data using E02BAF and then to evaluate its integral using E02BDF.
(b) Integrand defined as a function
If the functional form of f x is known, then one of the following approaches should be taken. They are arranged in the order from most specific to most general, hence the first applicable procedure in the list will be the most efficient. However, if you do not wish to make any assumptions about the integrand, the most reliable routines to use will be D01ATF (or D01AJF), D01AUF (or D01AKF), D01ALF, D01RGF or D01RAF, although these will in general be less efficient for simple integrals.
(i) Rule-evaluation routines
If f x is known to be sufficiently well behaved (more precisely, can be closely approximated by a polynomial of moderate degree), a Gaussian routine with a suitable number of abscissae may be used.
D01BCF or D01TBF with D01FBF may be used if it is required to examine the weights and abscissae.
D01TBF is faster and more accurate, whereas D01BCF is more general. D01UAF uses the same quadrature rules as D01TBF, and may be used if you do not explicitly require the weights and abscissae.
If f x is well behaved, apart from a weight-function of the form
x-a+b 2 c  or  b-x cx-a d,
D01BCF with D01FBF may be used.
D01BCF and D01TBF generate weights and abscissae for specific Gauss rules. Weights and abscissae for other quadrature formulae may be computed using routines D01TDF or D01TEF. Wherever possible use D01TDF in preference to D01TEF. The former however requires information that may not be readily available.
(ii) Automatic whole-interval routines
If f x is reasonably smooth, and the required accuracy is not too high, the automatic whole interval routines D01ARF and D01BDF may be used. Additionally, D01ESF with d=1 may be used with an appropriate transformation from the unit interval.
D01BDF uses the Gauss 10-point rule, with the 21 point Kronrod extension, and the subsequent 43 and 87 point Patterson extensions if required.
D01ESF supports multiple simultaneous integrals, and has a vectorized interface. Either high order Gauss–Patterson rules (of size 2 ℓ-1, for ℓ=1,…,9), or high order Clenshaw-Curtis rules (of size 2 ℓ-1+1, for ℓ=2,…,12). Gauss–Patterson rules possess greater polynomial accuracy, whereas Clenshaw–Curtis rules are often well suited to oscillatory integrals.
D01ARF incorporates the same high order Gauss–Patterson rules as D01ESF, and is the only routine that may be used for indefinite integration.
(iii) Automatic adaptive routines
Firstly, several routines are available for integrands of the form w x g x where g x is a ‘smooth’ function (i.e., has no singularities, sharp peaks or violent oscillations in the interval of integration) and w x is a weight function of one of the following forms.
1. | if w x= b-x α x-a β log b-x klog x-a l, where k,l=0​ or ​1, α,β>-1: use D01APF;
2. | if w x=1 x-c : use D01AQF (this integral is called the Hilbert transform of g);
3. | if w x=cos ωx or sin ωx: use D01ANF (this routine can also handle certain types of singularities in g x).
Secondly, there are multiple routines for general f x, using different strategies.
D01ATF (and D01AJF), and D01AUF (and D01AKF) use the strategy of Piessens et al. (1983), using repeated bisection of the interval, and in the first case the ε-algorithm (Wynn (1956)), to improve the integral estimate. This can cope with singularities away from the end points, provided singular points do not occur as abscissae, D01AUF tends to perform better than D01ATF on more oscillatory integrals.
D01ALF uses the same subdivision strategy as D01ATF over a set of initial interval segments determined by supplied break-points. It is hence suitable for integrals with discontinuities (including switches in definition) or sharp peaks occuring at known points. Such integrals may also be approximated using other routines which do not allow break-points, although such integrals should be evaluated over each of the sub-intervals seperately.
D01RAF again uses the strategy of Piessens et al. (1983), and provides the functionality of D01ALF, D01ATF and D01AUF in a reverse communication framework. It also supports multiple integrals and uses a vectorized interface for the abscissae. Hence it is likely to be more efficient if several similar integrals are required to be evaluated over the same domain. Furthermore, its behaviour can be tailored through the use of optional parameters.
D01AHF uses the strategy of Patterson (1968) and the ε-algorithm to adaptively evaluate the integral in question. It tends to be more efficient than the bisection based algorithms, although these tend to be more robust when singularities occur away from the end points.
D01RGF uses another adaptive scheme due to Gonnet (2010). This attempts to match the quadrature rule to the underlying integrand as well as subdividing the domain. Further, it can explicitly deal with singular points at abscissae, should NaN's or ∞ be returned by the user-supplied (sub)routine, provided the generation of these does not cause the program to halt (see Chapter X07).

3.4 One-dimensional Integrals over a Semi-infinite or Infinite Interval

(a) Integrand defined at a set of points
If f x is defined numerically at four or more points, and the portion of the integral lying outside the range of the points supplied may be neglected, then the Gill–Miller finite difference method, D01GAF, should be used.
(b) Integrand defined as a function
(i) Rule evaluation routines
If f x behaves approximately like a polynomial in x, apart from a weight function of the form:
1. | e-βx,β>0 (semi-infinite interval, lower limit finite); or
2. | e-βx,β<0 (semi-infinite interval, upper limit finite); or
3. | e-β x-α 2,β>0 (infinite interval),
or if f x behaves approximately like a polynomial in x+b-1 (semi-infinite range), then the Gaussian routines may be used.
D01UAF may be used if it is not required to examine the weights and abscissae.
D01BCF or D01TBF with D01FBF may be used if it is required to examine the weights and abscissae.
D01TBF is faster and more accurate, whereas D01BCF is more general.
D01UBF returns an approximation to the specific problem ∫0∞exp-x 2 g x dx.
(ii) Automatic adaptive routines
D01AMF may be used, except for integrands which decay slowly towards an infinite end point, and oscillate in sign over the entire range. For this class, it may be possible to calculate the integral by integrating between the zeros and invoking some extrapolation process (see C06BAF).
D01ASF may be used for integrals involving weight functions of the form cos ωx and sin ωx over a semi-infinite interval (lower limit finite).
The following alternative procedures are mentioned for completeness, though their use will rarely be necessary.
1. | If the integrand decays rapidly towards an infinite end point, a finite cut-off may be chosen, and the finite range methods applied.
2. | If the only irregularities occur in the finite part (apart from a singularity at the finite limit, with which D01AMF can cope), the range may be divided, with D01AMF used on the infinite part.
3. A transformation to finite range may be employed, e.g.,
x= 1-t t   or   x=- loge⁡t
will transform 0,∞ to 1,0 while for infinite ranges we have
∫-∞∞f x dx=∫0∞f x+f-x dx.
If the integrand behaves badly on -∞,0 and well on 0,∞ or vice versa it is better to compute it as ∫-∞0 f x dx+∫0∞f x dx. This saves computing unnecessary function values in the semi-infinite range where the function is well behaved.

3.5 Multidimensional Integrals

A number of techniques are available in this area and the choice depends to a large extent on the dimension and the required accuracy. It can be advantageous to use more than one technique as a confirmation of accuracy, particularly for high-dimensional integrations. Several routines include a transformation procedure, using a user-supplied subroutine, which allows general product regions to be easily dealt with in terms of conversion to the standard n-cube region.
(a) Products of one-dimensional rules (suitable for up to about 5 dimensions)
If f x 1,x 2,…,xn is known to be a sufficiently well behaved function of each variable xi, apart possibly from weight functions of the types provided, a product of Gaussian rules may be used. These are provided by D01BCF or D01TBF with D01FBF. Rules for finite, semi-infinite and infinite ranges are included.
For two-dimensional integrals only, unless the integrand is very badly behaved, the automatic whole-interval product procedure of D01DAF may be used. The limits of the inner integral may be user-specified functions of the outer variable. Infinite limits may be handled by transformation (see Section 3.4); end point singularities introduced by transformation should not be troublesome, as the integrand value will not be required on the boundary of the region.
If none of these routines proves suitable and convenient, the one-dimensional routines may be used recursively. For example, the two-dimensional integral
I=∫a 1b 1∫a 2b 2 f x,y dy dx
may be expressed as
I=∫a 1b 1 F x dx,   where   F x=∫a 2b 2 f x,y dy.
The user-supplied code to evaluate F x will call the integration routine for the y-integration, which will call more user-supplied code for f x,y as a function of y (x being effectively a constant).
From Mark 24 onwards, all direct communication routines may be called recursively. As such, you may use any routine, including the same routine, for each dimension. Note however, in previous releases, direct communication routines were not defined as recursive, and thus a different library integration routine must be used for each dimension if you are using an older product. Apart from this restriction, the following combinations were not permitted: D01AJF and D01ALF, D01ANF and D01APF, D01APF and D01AQF, D01ANF and D01AQF, D01ANF and D01ASF, D01AMF and D01ASF, D01ATF and D01AUF. Otherwise the full range of one-dimensional routines are available, for finite/infinite intervals, constant/variable limits, rule evaluation/automatic strategies etc.
The reverse communication routine D01RAF may be used by itself in a pseudo-recursive manner, in that it may be called to evaluate an inner integral for the integrand value of an outer integral also being calculated by D01RAF.
(b) Sag–Szekeres method
Two routines are based on this method.
D01FDF is particularly suitable for integrals of very large dimension although the accuracy is generally not high. It allows integration over either the general product region (with built-in transformation to the n-cube) or the n-sphere. Although no error estimate is provided, two adjustable arguments may be varied for checking purposes or may be used to tune the algorithm to particular integrals.
D01JAF is also based on the Sag–Szekeres method and integrates over the n-sphere. It uses improved transformations which may be varied according to the behaviour of the integrand. Although it can yield very accurate results it can only practically be employed for dimensions not exceeding 4.
(c) Number Theoretic method
Two subroutines are based on this method, D01GCF and a vectorized equivalent D01GDF.
Algorithms of this type carry out multidimensional integration using the Korobov–Conroy method over a product region with built-in transformation to the n-cube. A stochastic modification of this method is incorporated into the routines in this library, hybridising the technique with the Monte–Carlo procedure. An error estimate is provided in terms of the statistical standard error. A number of pre-computed optimal coefficient rules for up to 20 dimensions are provided; others can be computed using D01GYF and D01GZF. Like the Sag–Szekeres method it is suitable for large dimensional integrals although the accuracy is not high.
D01GCF requires a function to be provided to evaluate the value of the integrand at a single abscissa, and a subroutine to return the upper and lower limits of integration in a given dimension.
D01GDF has a vectorized interface which can result in faster execution, especially on vector-processing machines. You are required to provide two subroutines, the first to return an array of values of the integrand at each of an array of points, and the second to evaluate the limits of integration at each of an array of points. This reduces the overhead of function calls, avoids repetitions of computations common to each of the evaluations of the integral and limits of integration, and offers greater scope for vectorization of your code.
(d) A combinatorial extrapolation method
D01PAF computes a sequence of approximations and an error estimate to the integral of a function over a multidimensional simplex using a combinatorial method with extrapolation.
(e) Sparse Grid method
D01ESF implements a sparse grid quadrature scheme for the integration of a vector of multidimensional integrals over the unit hypercube,
F ≈ ∫ 0,1 d f x dx .
The routine uses a vectorized interface, which returns a set of points at which the integrands must be evaluated in a sparse storage format for efficiency.
Other domains can be readily integrated over by using an appropriate mapping inside the provided subroutine for evaluating the integrands. It is suitable for d up to O 100, although no upper bound on the number of dimensions is enforced. It will also evaluate one-dimensional integrals, although in this case the sparse grid used is in fact the full grid.
The routine uses optional parameters, set and queried using the routines D01ZKF and D01ZLF respectively. Amongst other options, these allow the parallelization of the routine to be controlled.
(f) Automatic routines (D01FCF and D01GBF)
Both routines are for integrals of the form
∫a 1b 1 ∫a 2b 2 ⋯ ∫anbn f x 1,x 2,…,xn d xn d x n-1⋯d x 1.
D01GBF is an adaptive Monte–Carlo routine. This routine is usually slow and not recommended for high-accuracy work. It is a robust routine that can often be used for low-accuracy results with highly irregular integrands or when n is large.
D01FCF is an adaptive deterministic routine. Convergence is fast for well behaved integrands. Highly accurate results can often be obtained for n between 2 and 5, using significantly fewer integrand evaluations than would be required by D01GBF. The routine will usually work when the integrand is mildly singular and for n≤10 should be used before D01GBF. If it is known in advance that the integrand is highly irregular, it is best to compare results from at least two different routines.
There are many problems for which one or both of the routines will require large amounts of computing time to obtain even moderately accurate results. The amount of computing time is controlled by the number of integrand evaluations you have allowed, and you should set this argument carefully, with reference to the time available and the accuracy desired.
D01EAF extends the technique of D01FCF to integrate adaptively more than one integrand, that is to calculate the set of integrals
∫a 1b 1 ∫a 2b 2 ⋯ ∫anbn f 1,f 2,…,fm d xn d x n-1⋯d x 1
for a set of similar integrands f 1,f 2,…,fm where fi=fi x 1,x 2,…,xn.

4 Decision Trees

Tree 1: One-dimensional integrals over a finite interval

Is the functional form of the integrand known? |  |  | Is indefinite integration required? |  |  | D01ARF
 |  | yes |  |  | yes
 | no |  |  | no |
 |  |  | Do you require reverse communication? |  |  | D01RAF
 |  |  |  |  | yes
 |  |  |  | no |
 |  |  | Are you concerned with efficiency for simple integrals? |  |  | Is the integrand smooth (polynomial-like) apart from weight function x-a+b/2 c or b-x c x-a d? |  |  | D01ARF, D01UAF, D01TBF or D01BCF and D01FBF, or D01GCF
 |  |  |  |  | yes |  |  | yes
 |  |  |  | no |  |  | no |
 |  |  |  |  |  | Is the integrand reasonably smooth and the required accuracy not too great? |  |  | D01ARF, D01BDF, D01ESF or D01UAF
 |  |  |  |  |  |  |  | yes
 |  |  |  |  |  |  | no |
 |  |  |  |  |  | Are multiple integrands to be integrated simultaneously? |  |  | D01ESF or D01RAF
 |  |  |  |  |  |  |  | yes
 |  |  |  |  |  |  | no |
 |  |  |  |  |  | Has the integrand discontinuities, sharp peaks or singularities at known points other than the end points? |  |  | Split the range and begin again; or use D01ALF or D01RGF
 |  |  |  |  |  |  |  | yes
 |  |  |  |  |  |  | no |
 |  |  |  |  |  | Is the integrand free of singularities, sharp peaks and violent oscillations apart from weight function b-x α x-a β log b-x k log x-a l ? |  |  | D01APF
 |  |  |  |  |  |  |  | yes
 |  |  |  |  |  |  | no |
 |  |  |  |  |  | Is the integrand free of singularities, sharp peaks and violent oscillations apart from weight function x-c-1 ? |  |  | D01AQF
 |  |  |  |  |  |  |  | yes
 |  |  |  |  |  |  | no |
 |  |  |  |  |  | Is the integrand free of violent oscillations apart from weight function cos ωx or sin ωx? |  |  | D01ANF
 |  |  |  |  |  |  |  | yes
 |  |  |  |  |  |  | no |
 |  |  |  |  |  | Is the integrand free of singularities? |  |  | D01AJF, D01AKF, D01AUF or D01ESF
 |  |  |  |  |  |  |  | yes
 |  |  |  |  |  |  | no |
 |  |  |  |  |  | Is the integrand free of discontinuities and of singularities except possibly at the end points? |  |  | D01AHF
 |  |  |  |  |  |  |  | yes
 |  |  |  |  |  |  | no |
 |  |  |  |  |  | D01AJF, D01ATF, D01RAF or D01RGF
 |  |  | D01AHF, D01AJF, D01ATF, D01RAF or D01RGF
D01GAF
Note: D01ATF, D01AUF, D01RAF and D01RGF are likely to be more efficient due to their vectorized interfaces than D01AJF and D01AKF, which use a more conventional user-interface, consistent with other routines in the chapter.

Tree 2: One-dimensional integrals over a semi-infinite or infinite interval

Is the functional form of the integrand known? |  |  | Are you concerned with efficiency for simple integrands? |  |  | Is the integrand smooth (polynomial-like) with no exceptions? |  |  | D01UAF, D01BDF, D01ARF or D01ESF with transformation. See Section 3.4 (b) (ii).
 |  | yes |  |  | yes |  |  | yes
 | no |  |  | no |  |  | no |
 |  |  |  |  |  | Is the integrand of the form ∫0∞exp-x 2 g x dx? |  |  | D01UBF
 |  |  |  |  |  |  |  | yes
 |  |  |  |  |  |  | no |
 |  |  |  |  |  | Is the integrand smooth (polynomial-like) apart from weight function e-β x (semi-infinite range) or e-β x-a 2 (infinite range) or is the integrand polynomial-like in 1 x+b? (semi-infinite range)? |  |  | D01UAF, or D01BCF and D01FBF, or, D01TBF and D01FBF, or D01TDF and D01FBF (D01TDF may require use of D01TEF)
 |  |  |  |  |  |  |  | yes
 |  |  |  |  |  |  | no |
 |  |  |  |  |  | Has integrand discontinuities, sharp peaks or singularities at known points other than a finite limit? |  |  | Split range; begin again using finite or infinite range trees
 |  |  |  |  |  |  |  | yes
 |  |  |  |  |  |  | no |
 |  |  |  |  |  | Does the integrand oscillate over the entire range? |  |  | Does the integrand decay rapidly towards an infinite limit? |  |  | Use D01AMF; or set cutoff and use finite range tree
 |  |  |  |  |  |  |  | yes |  |  | yes
 |  |  |  |  |  |  | no |  |  | no |
 |  |  |  |  |  |  |  |  | Is the integrand free of violent oscillations apart from weight function cos ωx or sin ωx (semi-infinite range)? |  |  | D01ASF
 |  |  |  |  |  |  |  |  |  |  | yes
 |  |  |  |  |  |  |  |  |  | no |
 |  |  |  |  |  |  |  |  | Use finite-range integration between the zeros and extrapolate (see C06BAF)
 |  |  |  |  |  | D01AMF
 |  |  | D01AMF
D01GAF (integrates over the range of the points supplied)

Tree 3: Multidimensional integrals

Is dimension =2 and product region? |  |  | D01DAF
 |  | yes
 | no |
Is dimension ≤4 |  |  | Is region an n-sphere? |  |  | D01FBF with user transformation or D01JAF
 |  | yes |  |  | yes
 | no |  |  | no |
 |  |  | Is region a Simplex? |  |  | D01FBF with user transformation or D01PAF
 |  |  |  |  | yes
 |  |  |  | no |
 |  |  | Is the integrand smooth (polynomial-like) in each dimension apart from weight function? |  |  | D01TBF or D01BCF with D01FBF
 |  |  |  |  | yes
 |  |  |  | no |
 |  |  | Is integrand free of extremely bad behaviour? |  |  | D01ESF, D01FCF, D01FDF or D01GCF
 |  |  |  |  | yes
 |  |  |  | no |
 |  |  | Is bad behaviour on the boundary? |  |  | D01FCF or D01FDF
 |  |  |  |  | yes
 |  |  |  | no |
 |  |  | Compare results from at least two of D01FCF, D01FDF, D01GBF and D01GCF, D01ESF and one-dimensional recursive application
Is region an n-sphere? |  |  | D01FDF
 |  | yes
 | no |
Is region a Simplex? |  |  | D01PAF
 |  | yes
 | no |
Is high accuracy required? |  |  | D01FDF with argument tuning
 |  | yes
 | no |
Is dimension high? |  |  | D01FDF, D01GCF or D01GDF, D01ESF
 |  | yes
 | no |
D01FCF
Note: in the case where there are many integrals to be evaluated D01EAF should be preferred to D01FCF.
D01GDF is likely to be more efficient than D01GCF, which uses a more conventional user-interface, consistent with other routines in the chapter.

5 Functionality Index

Korobov optimal coefficients for use in D01GCF and D01GDF:
when number of points is a product of 2 primes D01GZF
when number of points is prime D01GYF
Multidimensional quadrature,
over a finite two-dimensional region D01DAF
over a general product region,
Korobov–Conroy number-theoretic method D01GCF
Sag–Szekeres method (also over n-sphere) D01FDF
variant of D01GCF especially efficient on vector machines D01GDF
over a hyper-rectangle,
adaptive method D01FCF
adaptive method,
multiple integrands D01EAF
Gaussian quadrature rule-evaluation D01FBF
Monte–Carlo method D01GBF
sparse grid method (with user transformation),
muliple integrands, vectorized interface D01ESF
over an n-simplex D01PAF
over an n-sphere (n ≤ 4),
allowing for badly behaved integrands D01JAF
One-dimensional quadrature,
adaptive integration of a function over a finite interval,
strategy due to Gonnet,
suitable for badly behaved integrals,
vectorized interface D01RGF
strategy due to Patterson,
suitable for well-behaved integrands, except possibly at end-points D01AHF
strategy due to Piessens and de Doncker,
allowing for singularities at user-specified break-points D01ALF
suitable for badly behaved integrands,
single abscissa interface D01AJF
vectorized interface D01ATF
suitable for highly oscillatory integrals,
single abscissa interface D01AKF
vectorized interface D01AUF
weight function 1 / (x − c) Cauchy principal value (Hilbert transform) D01AQF
weight function cos(ωx) or sin(ωx) D01ANF
weight function with end-point singularities of algebraico-logarithmic type D01APF
adaptive integration of a function over an infinite interval or semi-infinite interval,
no weight function D01AMF
weight function cos(ωx) or sin(ωx) D01ASF
integration of a function defined by data values only,
Gill–Miller method D01GAF
non-adaptive integration over a finite, semi-infinite or infinite interval,
using pre-computed weights and abscissae
specific integral with weight exp( − x2) over semi-infinite interval D01UBF
vectorized interface D01UAF
non-adaptive integration over a finite interval D01BDF
non-adaptive integration over a finite interval,
with provision for indefinite integrals also D01ARF
reverse communication,
adaptive integration over a finite interval,
multiple integrands,
efficient on vector machines D01RAF
Service routines,
array size query for D01RAF D01RCF
general option getting D01ZLF
general option setting and initialization D01ZKF
Weights and abscissae for Gaussian quadrature rules,
method of Golub and Welsch,
calculating the weights and abscissae D01TDF
generate recursive coefficients D01TEF
more general choice of rule,
calculating the weights and abscissae D01BCF
restricted choice of rule,
using pre-computed weights and abscissae D01TBF

6 Auxiliary Routines Associated with Library Routine Arguments

D01FDV | nagf_quad_md_sphere_dummy_region See the description of the argument REGION in D01FDF.
D01RBM | nagf_quad_d01rb_dummy See the description of the argument MONIT in D01RBF.

7 Routines Withdrawn or Scheduled for Withdrawal

The following lists all those routines that have been withdrawn since Mark 19 of the Library or are scheduled for withdrawal at one of the next two marks.
Withdrawn Routine | Mark of Withdrawal | Replacement Routine(s)
D01BAF | 26 | D01UAF
D01BBF | 26 | D01TBF
D01RBF | 27 | No replacement required

8 References

Davis P J and Rabinowitz P (1975) Methods of Numerical Integration Academic Press
Gonnet P (2010) Increasing the reliability of adaptive quadrature using explicit interpolants ACM Trans. Math. software 37 26
Lyness J N (1983) When not to use an automatic quadrature routine SIAM Rev. 25 63–87
Patterson T N L (1968) The Optimum addition of points to quadrature formulae Math. Comput. 22 847–856
Piessens R, de Doncker–Kapenga E, Überhuber C and Kahaner D (1983) QUADPACK, A Subroutine Package for Automatic Integration Springer–Verlag
Sobol I M (1974) The Monte Carlo Method The University of Chicago Press
Stroud A H (1971) Approximate Calculation of Multiple Integrals Prentice–Hall
Wynn P (1956) On a device for computing the em Sn transformation Math. Tables Aids Comput. 10 91–96
D01 Chapter Contents
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


D01JAF : NAG Library, Mark 26

D01 Chapter Contents
D01 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

D01JAF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
▸▿ 9 Further Comments
9.1 Timing
9.2 Spherical Polar Coordinates
9.3 Machine Dependencies
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

D01JAF attempts to evaluate an integral over an n-dimensional sphere (n=2, 3, or 4), to a user-specified absolute or relative accuracy, by means of a modified Sag–Szekeres method. The routine can handle singularities on the surface or at the centre of the sphere, and returns an error estimate.

2 Specification

SUBROUTINE D01JAF ( F, NDIM, RADIUS, EPSA, EPSR, METHOD, ICOORD, RESULT, ESTERR, NEVALS, IFAIL)
INTEGER | NDIM, METHOD, ICOORD, NEVALS, IFAIL
REAL (KIND=nag_wp) | F, RADIUS, EPSA, EPSR, RESULT, ESTERR
EXTERNAL | F

3 Description

D01JAF calculates an approximation to the n-dimensional integral
I=∫⋯∫S F x 1,…,xn d x 1⋯d xn,  2≤n≤4,
where S is the hypersphere
x 12+⋯+xn 2≤α<∞
(the integrand function may also be defined in spherical coordinates). The algorithm is based on the Sag–Szekeres method (see Sag and Szekeres (1964)), applying the product trapezoidal formula after a suitable radial transformation. An improved transformation technique is developed: depending on the behaviour of the function and on the required accuracy, different transformations can be used, some of which are ‘double exponential’, as defined by Takahasi and Mori (1974). The resulting technique allows the routine to deal with integrand singularities on the surface or at the centre of the sphere. When the estimated error of the approximation with mesh size h is larger than the tolerated error, the trapezoidal formula with mesh size h/2 is calculated. A drawback of this method is the exponential growth of the number of function evaluations in the successive approximations (this number grows with a factor ≈2 n). This introduces the restriction n≤4. Because the convergence rate of the successive approximations is normally better than linear, the error estimate is based on the linear extrapolation of the difference between the successive approximations (see Robinson and de Doncker (1981) and Roose and de Doncker (1981)). For further details of the algorithm, see Roose and de Doncker (1981).

4 References

Robinson I and de Doncker E (1981) Automatic computation of improper integrals over a bounded or unbounded planar region Computing 27 89–284
Roose D and de Doncker E (1981) Automatic integration over a sphere J. Comput. Appl. Math. 7 203–224
Sag T W and Szekeres G (1964) Numerical evaluation of high-dimensional integrals Math. Comput. 18 245–253
Takahasi H and Mori M (1974) Double Exponential Formulas for Numerical Integration 9 Publ. RIMS, Kyoto University 721–741

5 Arguments

1:   F – REAL (KIND=nag_wp) FUNCTION, supplied by the user.External Procedure
F must return the value of the integrand f at a given point.
The specification of F is:
FUNCTION F ( NDIM, X)
REAL (KIND=nag_wp) F
INTEGER | NDIM
REAL (KIND=nag_wp) | X(NDIM)
1:   NDIM – INTEGERInput
On entry: n, the number of dimensions of the integral.
2:   X NDIM – REAL (KIND=nag_wp) arrayInput
On entry: the coordinates of the point at which the integrand f must be evaluated. These coordinates are given in Cartesian or spherical polar form according to the value of ICOORD.
F must either be a module subprogram USEd by, or declared as EXTERNAL in, the (sub)program from which D01JAF is called. Arguments denoted as Input must not be changed by this procedure.
See also Section 9.
2:   NDIM – INTEGERInput
On entry: n, the dimension of the sphere.
Constraint: 2≤NDIM≤4.
3:   RADIUS – REAL (KIND=nag_wp)Input
On entry: α, the radius of the sphere.
Constraint: RADIUS≥0.0.
4:   EPSA – REAL (KIND=nag_wp)Input
On entry: the requested absolute tolerance. If EPSA<0.0, its absolute value is used. See Section 7.
5:   EPSR – REAL (KIND=nag_wp)Input
On entry: the requested relative tolerance.
EPSR<0.0
Its absolute value is used.
EPSR<10×machine precision
The latter value is used as EPSR by the routine. See Section 7.
6:   METHOD – INTEGERInput
On entry: must specify the transformation to be used by the routine. The choice depends on the behaviour of the integrand and on the required accuracy.
For well-behaved functions and functions with mild singularities on the surface of the sphere only:
METHOD=1
Low accuracy required.
METHOD=2
High accuracy required.
For functions with severe singularities on the surface of the sphere only:
METHOD=3
Low accuracy required.
METHOD=4
High accuracy required.
(in this case ICOORD must be set to ICOORD=2, and the function defined in special spherical coordinates).
For functions with a singularity at the centre of the sphere (and possibly with singularities on the surface as well):
METHOD=5
Low accuracy required.
METHOD=6
High accuracy required.
METHOD=0 can be used as a default value and is equivalent to:
  • METHOD=1 if EPSR>10-6, and
  • METHOD=2 if EPSR≤10-6.
The distinction between low and high required accuracies, as mentioned above, depends also on the behaviour of the function. Roughly one may assume the critical value of EPSA and EPSR to be 10-6, but the critical value will be smaller for a well-behaved integrand and larger for an integrand with severe singularities.
Suggested value: METHOD=0.
Constraint: METHOD=0, 1, 2, 3, 4, 5 or 6.
If ICOORD=2, METHOD=3 or 4
7:   ICOORD – INTEGERInput
On entry: must specify which kind of coordinates are used in F.
ICOORD=0
Cartesian coordinates xi, for i=1,2,…,n.
ICOORD=1
Spherical coordinates (see Section 9.2): X 1=ρ; X i=θ i-1, for i=2,3,…,n.
ICOORD=2,
Special spherical polar coordinates (see Section 9.3), with the additional transformation ρ=α-λ: X 1=λ=α-ρ; X i=θ i-1, for i=2,3,…,n.
Constraint: ICOORD=0, 1 or 2.
If METHOD=3 or 4, ICOORD=2
8:   RESULT – REAL (KIND=nag_wp)Output
On exit: the approximation to the integral I.
9:   ESTERR – REAL (KIND=nag_wp)Output
On exit: an estimate of the modulus of the absolute error.
10:   NEVALS – INTEGEROutput
On exit: the number of function evaluations used.
11:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, because for this routine the values of the output arguments may be useful even if IFAIL≠0 on exit, the recommended value is -1. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Note: D01JAF may return useful information for one or more of the following detected errors or warnings.
Errors or warnings detected by the routine:
IFAIL=1
The required accuracy cannot be achieved within a limiting number of function evaluations (which is set by the routine).
IFAIL=2
The required accuracy cannot be achieved because of round-off error.
IFAIL=3
The required accuracy cannot be achieved because the maximum accuracy with respect to the machine constants X02AJF and X02AMF has been attained. If this maximum accuracy is rather low (compared with X02AJF), the cause of the problem is a severe singularity on the boundary or at the centre of the sphere. If METHOD=0, 1 or 2, then setting METHOD=3 or 4 may help.
IFAIL=4
On entry, | NDIM<2 or NDIM>4,
or | RADIUS<0.0,
or | METHOD≠0, 1, 2, 3, 4, 5 or 6,
or | ICOORD≠0, 1 or 2,
or | ICOORD=2 and METHOD≠3 or 4,
or | METHOD=3 or 4 and ICOORD≠2.
No calculations have been performed. RESULT and ESTERR are set to 0.0.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

You can specify an absolute and/or a relative tolerance, setting EPSA and EPSR. The routine attempts to calculate an approximation RESULT such that
I-RESULT≤max EPSA,EPSR×I.
If 0≤IFAIL≤3, ESTERR returns an estimate of, but not necessarily a bound for, I-RESULT.

8 Parallelism and Performance

D01JAF is not threaded in any implementation.

9 Further Comments

9.1 Timing

Timing depends on the integrand and the accuracy required.

9.2 Spherical Polar Coordinates

Cartesian coordinates are related to the spherical polar coordinates by:
x 1 = ρ.sin⁡θ 1⋯sin⁡θ n-2.sin⁡θ n-1 x 2 = ρ.sin⁡θ 1⋯sin⁡θ n-2.cos⁡θ n-1 x 3 = ρ.sin⁡θ 1⋯cos⁡θ n-2 ⋮ xn = ρ.cos⁡θ 1
where 0<θi<π, for i=1,2,…,n-2 and 0<θ n-1<2 π.

9.3 Machine Dependencies

As a consequence of the transformation technique, the severity of the singularities which can be handled by D01JAF depends on the precision and range of real numbers on the machine. METHOD=3 or 4 must be used when the singularity on the surface is ‘severe’ in view of the requested accuracy and machine precision. In practice one has to set METHOD=3 or 4 if D01JAF terminates with IFAIL=3 when called with METHOD=0, 1 or 2.
When integrating a function with a severe singular behaviour on the surface of the sphere, the additional transformation ρ=α-λ helps to avoid the loss of significant figures due to round-off error in the calculation of the integration nodes which are very close to the surface. For these points, the value of λ can be computed more accurately than the value of ρ. Naturally, care must be taken that the function subprogram does not contain expressions of the form α-λ, which could cause a large round-off error in the calculation of the integrand at the boundary of the sphere.
Care should be taken to avoid underflow and/or overflow problems in the function subprogram, because some of the integration nodes used by D01JAF may be very close to the surface or to the centre of the sphere.
Example:
  • suppose the function
    f ρ=1-ρ 2-0.7
    is to be integrated over the unit sphere, with METHOD=3 or 4. Then ICOORD should be set to 2; the transformation ρ=1-λ gives f ρ=2 λ-λ 2 -0.7; and F could be coded thus:
    F = 1.0
A = X(1)
IF (A.GT.0.0) F = 1.0/(A*(2.0-A))**0.7
RETURN
Note that D01JAF ensures that λ=X 1>X02AMF, but underflow could occur in the computation of λ 2.

10 Example

This example evaluates the integrals
∫⋯∫S 1 1-ρ 2 d x 1⋯d xn
where ρ=∑i=1 n xi 2, and S is the unit sphere of dimension n=2​ or ​4.
The exact values (to 12 decimal places) are 6.28318530718 and 13.1594725348.

10.1 Program Text

Program Text (d01jafe.f90)

10.2 Program Data

None.

10.3 Program Results

Program Results (d01jafe.r)

D01 Chapter Contents
D01 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


D01PAF : NAG Library, Mark 26

D01 Chapter Contents
D01 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

D01PAF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

D01PAF returns a sequence of approximations to the integral of a function over a multidimensional simplex, together with an error estimate for the last approximation.

2 Specification

SUBROUTINE D01PAF ( NDIM, VERT, LDVERT, SDVERT, FUNCTN, MINORD, MAXORD, FINVLS, ESTERR, IFAIL)
INTEGER | NDIM, LDVERT, SDVERT, MINORD, MAXORD, IFAIL
REAL (KIND=nag_wp) | VERT(LDVERT,SDVERT), FUNCTN, FINVLS(MAXORD), ESTERR
EXTERNAL | FUNCTN

3 Description

D01PAF computes a sequence of approximations FINVLS j, for j=MINORD+1,…,MAXORD, to an integral
∫S f x 1,x 2,…,xn d x 1 d x 2⋯d xn
where S is an n-dimensional simplex defined in terms of its n+1 vertices. FINVLS j is an approximation which will be exact (except for rounding errors) whenever the integrand is a polynomial of total degree 2 j-1 or less.
The type of method used has been described in Grundmann and Moller (1978), and is implemented in an extrapolated form using the theory from de Doncker (1979).

4 References

de Doncker E (1979) New Euler–Maclaurin Expansions and their application to quadrature over the s-dimensional simplex Math. Comput. 33 1003–1018
Grundmann A and Moller H M (1978) Invariant integration formulas for the n-simplex by combinatorial methods SIAM J. Numer. Anal. 15 282–290

5 Arguments

1:   NDIM – INTEGERInput
On entry: n, the number of dimensions of the integral.
Constraint: NDIM≥2.
2:   VERT LDVERTSDVERT – REAL (KIND=nag_wp) arrayInput/Output
On entry: VERT ij must be set to the jth component of the ith vertex for the simplex integration region, for i=1,2,…,n+1 and j=1,2,…,n. If MINORD>0, VERT must be unchanged since the previous call of D01PAF.
On exit: these values are unchanged. The rest of the array VERT is used for workspace and contains information to be used if another call of D01PAF is made with MINORD>0. In particular VERT n+12 n+2 contains the volume of the simplex.
3:   LDVERT – INTEGERInput
On entry: the first dimension of the array VERT as declared in the (sub)program from which D01PAF is called.
Constraint: LDVERT≥NDIM+1.
4:   SDVERT – INTEGERInput
On entry: the second dimension of the array VERT as declared in the (sub)program from which D01PAF is called.
Constraint: SDVERT≥2×NDIM+1.
5:   FUNCTN – REAL (KIND=nag_wp) FUNCTION, supplied by the user.External Procedure
FUNCTN must return the value of the integrand f at a given point.
The specification of FUNCTN is:
FUNCTION FUNCTN ( NDIM, X)
REAL (KIND=nag_wp) FUNCTN
INTEGER | NDIM
REAL (KIND=nag_wp) | X(NDIM)
1:   NDIM – INTEGERInput
On entry: n, the number of dimensions of the integral.
2:   X NDIM – REAL (KIND=nag_wp) arrayInput
On entry: the coordinates of the point at which the integrand f must be evaluated.
FUNCTN must either be a module subprogram USEd by, or declared as EXTERNAL in, the (sub)program from which D01PAF is called. Arguments denoted as Input must not be changed by this procedure.
6:   MINORD – INTEGERInput/Output
On entry: must specify the highest order of the approximations currently available in the array FINVLS. MINORD=0 indicates an initial call; MINORD>0 indicates that FINVLS 1,FINVLS 2,…,FINVLS MINORD have already been computed in a previous call of D01PAF.
Constraint: MINORD≥0.
On exit: MINORD=MAXORD.
7:   MAXORD – INTEGERInput
On entry: the highest order of approximation to the integral to be computed.
Constraint: MAXORD>MINORD.
8:   FINVLS MAXORD – REAL (KIND=nag_wp) arrayInput/Output
On entry: if MINORD>0, FINVLS 1,FINVLS 2,…,FINVLS MINORD must contain approximations to the integral previously computed by D01PAF.
On exit: contains these values unchanged, and the newly computed values FINVLS MINORD+1,FINVLS MINORD+2,…,FINVLS MAXORD. FINVLS j is an approximation to the integral of polynomial degree 2 j-1.
9:   ESTERR – REAL (KIND=nag_wp)Output
On exit: an absolute error estimate for FINVLS MAXORD.
10:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, LDVERT=value and NDIM=value.
Constraint: LDVERT≥NDIM+1.
On entry, MAXORD=value and MINORD=value.
Constraint: MAXORD>MINORD.
On entry, MINORD=value.
Constraint: MINORD≥0.
On entry, NDIM=value.
Constraint: NDIM≥2.
On entry, SDVERT=value and NDIM=value.
Constraint: SDVERT≥2×NDIM+1.
IFAIL=2
The volume of the simplex integration region is too large or too small to be represented on the machine.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

An absolute error estimate is output through the argument ESTERR.

8 Parallelism and Performance

D01PAF is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
D01PAF makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The running time for D01PAF will usually be dominated by the time used to evaluate the integrand FUNCTN. The maximum time that could be used by D01PAF will be approximately given by
T×MAXORD+NDIM! MAXORD-1!NDIM+1!
where T is the time needed for one call of FUNCTN.

10 Example

This example demonstrates the use of the subroutine with the integral
∫01 ∫0 1-x ∫0 1-x-y exp x+y+z cos x+y+z dz dy dx = 14 .

10.1 Program Text

Program Text (d01pafe.f90)

10.2 Program Data

None.

10.3 Program Results

Program Results (d01pafe.r)

D01 Chapter Contents
D01 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


D01RAF : NAG Library, Mark 26

D01 Chapter Contents
D01 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

D01RAF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.
Note: this routine uses optional parameters to define choices in the problem specification and in the details of the algorithm. If you wish to use default settings for all of the optional parameters, you need only read Sections 1 to 10 of this document. If, however, you wish to reset some or all of the settings please refer to Section 11 for a detailed description of the specification of the optional parameters.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
▸▿ 9 Further Comments
9.1 Details of the Computation
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results
▸▿ 11 Optional Parameters
11.1 Description of the Optional Parameters
11.2 Diagnostic Options

1 Purpose

D01RAF is a general purpose adaptive integrator which calculates an approximation to a vector of definite integrals F over a finite range a,b , given the vector of integrands f x.
F = ∫ a b f x d x
If the same subdivisions of the range are equally good for functions f 1 x and f 2 x, because f 1 x and f 2 x have common areas of the range where they vary slowly and where they vary quickly, then we say that f 1 x and f 2 x are ‘similar’. D01RAF is particularly effective for the integration of a vector of similar functions.

2 Specification

SUBROUTINE D01RAF ( IREVCM, NI, A, B, SID, NEEDI, X, LENX, NX, FM, LDFM, DINEST, ERREST, IOPTS, OPTS, ICOM, LICOM, COM, LCOM, IFAIL)
INTEGER | IREVCM, NI, SID, NEEDI(NI), LENX, NX, LDFM, IOPTS(100), ICOM(LICOM), LICOM, LCOM, IFAIL
REAL (KIND=nag_wp) | A, B, X(LENX), FM(LDFM,*), DINEST(NI), ERREST(NI), OPTS(100), COM(LCOM)

3 Description

D01RAF is an extension to various QUADPACK routines, including QAG, QAGS and QAGP. The extensions made allow multiple integrands to be evaluated simultaneously, using a vectorized interface and reverse communication.
The quadrature scheme employed by D01RAF can be chosen by you. Six Gauss–Kronrod schemes are available. The algorithm incorporates a global acceptance criterion (as defined by Malcolm and Simpson (1976)), optionally together with the ε-algorithm (see Wynn (1956)) to perform extrapolation. The local error estimation is described in Piessens et al. (1983).
D01RAF is the integration routine in the suite of routines D01RAF and D01RCF. It also uses optional parameters, which can be set and queried using the routines D01ZKF and D01ZLF respectively. The options available are described in Section 11.
First, the option arrays IOPTS and OPTS must be initialized using D01ZKF. Thereafter any required options must be set before calling D01RAF, or the routine D01RCF.
A typical usage of this suite of routines is (in pseudo-code for clarity),
Setup phase
liopts = 100
lopts = 100
allocate(iopts(liopts),opts(lopts))
call D01ZKF('initialize = d01raf',iopts,liopts,opts,lopts,ifail)
call D01ZKF('option = value',iopts,liopts,opts,lopts,ifail)
...
call D01RCF(ni,lenxrq,ldfmrq,sdfmrq,licmin,licmax,lcmin,lcmax, &
     iopts,opts,ifail)
lenx = lenxrq
ldfm = ldfmrq
sdfm = sdfmrq
licom = licmax
lcom = lcmax
allocate(icom(licom),com(lcom),x(lenx),fm(ldfm,sdfm),needi(ni), &
              dinest(ni),errest(ni))
Solve phase
irevcm = 1
while irevcm≠0
    call D01RAF(irevcm,ni,a,b,sid,needi,x,lenx,nx,fm,ldfm,   &
                dinest,errest,iopts,opts,icom,licom,com, &
                lcom,ifail)
    select case(irevcm)
    case(11)
          Initial solve phase
          evaluate fm(1:ni,1:nx)
    case(12)
          Adaptive solve phase
          evaluate fm(needi(1:ni)=1,1:nx)
    case(0)
          investigate ifail
    end select
end while
Diagnostic phase
call D01ZLF('option',ivalue,rvalue,cvalue,optype,iopts,opts,ifail)
...
During the initial solve phase, the first estimation of the definite integral and error estimate is constructed over the interval a,b . This will have been divided into spri level 1 segments, where spri is the number of Primary Divisions, and will use any provided break-points if Primary Division Mode=MANUAL.
Once a complete integral estimate over a,b is available, i.e., after all the estimates for the level 1 segments have been evaluated, the routine enters the adaptive phase. The estimated errors are tested against the requested tolerances εa and εr , corresponding to the Absolute Tolerance and Relative Tolerance respectively. Should this test fail, and additional subdivision be allowed, a segment is selected for subdivision, and is subsequently replaced by two new segments at the next level of refinement. How this segment is chosen may be altered by setting Prioritize Error to either favour the segment with the maximum error, or the segment with the lowest level supporting an unacceptable (although potentially non-maximal) error. Up to maxsdiv subdivisions are allowed if sufficient memory is provided, where maxsdiv is the value of Maximum Subdivisions.
Once a sufficient number of error estimates have been constructed for a particular integral, the routine may optionally use Extrapolation to attempt to accelerate convergence. This may significantly lower the amount of work required for a given integration. To minimize the risk of premature convergence from extrapolation, a safeguard εsafe can be set using Extrapolation Safeguard, and the extrapolated solution will only be considered if εsafe εq ≤ εex , where εq and εex are the estimated error directly from the quadrature and from the extrapolation respectively. If extrapolation is successful for the computation of integral j, the extrapolated solution will be returned in DINEST j on completion of D01RAF. Otherwise the direct solution will be returned in DINEST j. This is indicated by the value of NEEDI j on completion.

4 References

Malcolm M A and Simpson R B (1976) Local versus global strategies for adaptive quadrature ACM Trans. Math. Software 1 129–146
Piessens R (1973) An algorithm for automatic integration Angew. Inf. 15 399–401
Piessens R, de Doncker–Kapenga E, Überhuber C and Kahaner D (1983) QUADPACK, A Subroutine Package for Automatic Integration Springer–Verlag
Wynn P (1956) On a device for computing the em Sn transformation Math. Tables Aids Comput. 10 91–96

5 Arguments

Note: this routine uses reverse communication. Its use involves an initial entry, intermediate exits and re-entries, and a final exit, as indicated by the argument IREVCM. Between intermediate exits and re-entries, all arguments other than IREVCM, NEEDI and FM must remain unchanged.
1:   IREVCM – INTEGERInput/Output
On initial entry: IREVCM=1.
IREVCM=1
Sets up data structures in ICOM and COM and starts a new integration.
Constraint: IREVCM=1 on initial entry.
On intermediate exit: IREVCM=11 or 12.
IREVCM requests the integrands fj xi be evaluated for all required j∈1,…,ni as indicated by NEEDI, and at all the points xi, for i=1,2,…,nx. Abscissae xi are provided in X i and fj xi must be returned in FM ji.
During the initial solve phase:
IREVCM=11
Function values are required to construct the initial estimates of the definite integrals.
If NEEDI j=1, fj xi must be supplied in FM ji. This will be the case unless you have abandoned the evaluation of specific integrals on a previous call.
If NEEDI j=0, you have previously abandoned the evaluation of integral j, and hence should not supply the value of fj xi.
DINEST and ERREST contain incomplete information during this phase. As such you should not abandon the evaluation of any integrals during this phase unless you do not require their estimate.
If IREVCM is set to a negative value during this phase, NEEDI j, for j=1,2,…,ni, will be set to this negative value and IFAIL=-1 will be returned.
During the adaptive solve phase:
IREVCM=12
Function values are required to improve the estimates of the definite integrals.
If NEEDI j=0, any evaluation of fj xi will be discarded, so there is no need to provide them.
If NEEDI j=1, fj xi must be provided in FM ji.
If NEEDI j=2, 3 or 4, the current error estimate of integral j does not require integrand j to be evaluated and provided in FM ji. Should you choose to, integrand j can be evaluated in which case NEEDI j must be set to 1.
DINEST and ERREST contain complete information during this phase.
If IREVCM is set to a negative value during this phase IFAIL=1, 2 or 3 will be returned and the elements of NEEDI will reflect the current state of the adaptive process.
On intermediate re-entry: IREVCM should normally be left unchanged. However, if IREVCM is set to a negative value, D01RAF will terminate, (see IREVCM=11 and IREVCM=12 above).
On final exit: IREVCM=0.
IREVCM=0
Indicates the algorithm has completed.
2:   NI – INTEGERInput
On entry: ni, the number of integrands.
3:   A – REAL (KIND=nag_wp)Input
On entry: a, the lower bound of the domain.
4:   B – REAL (KIND=nag_wp)Input
On entry: b, the upper bound of the domain.
If b-a<10 ε, where ε is the machine precision (see X02AJF), then D01RAF will return DINEST j=ERREST j=0.0, for j=1,2,…,ni.
5:   SID – INTEGEROutput
For advanced users.
On intermediate exit: SID identifies a specific set of abscissae, x, returned during the integration process. When a new set of abscissae are generated the value of SID is incremented by 1. Advanced users may store calculations required for an identified set x, and reuse them should D01RAF return the same value of SID, i.e., the same set of abscissae was used.
6:   NEEDI NI – INTEGER arrayInput/Output
On initial entry: need not be set.
On intermediate exit: NEEDI j indicates what action must be taken for integral j=1,2,…ni (see IREVCM).
NEEDI j=0
Do not provide fj xi. Any provided values will be ignored.
NEEDI j=1
The values fj xi must be provided in FM ji, for i=1,2,…,nx.
NEEDI j=2
The values fj xi are not required, however the error estimate for integral j is still above the requested tolerance. If you wish to provide values for the evaluation of integral j, set NEEDI j=1, and supply fj xi in FM ji, for i=1,2,…,nx.
NEEDI j=3
The error estimate for integral j cannot be improved to below the requested tolerance directly, either because no more new splits may be performed due to exhaustion, or due to the detection of extremely bad integrand behaviour. However, providing the values fj xi may still lead to some improvement, and may lead to an acceptable error estimate indirectly using Wynn's epsilon algorithm. If you wish to provide values for the evaluation of integral j, set NEEDI j=1, and supply fj xi in FM ji, for i=1,2,…,nx.
NEEDI j=4
The error estimate of integral j is below the requested tolerance. If you believe this to be false, if for example the result in DINEST j is greatly different to what you may expect, you may force the algorithm to re-evaluate this conclusion by including the evaluations of integrand j at xi, for i=1,2,…,nx, and setting NEEDI j=1. Integral and error estimation will be performed again during the next iteration.
On intermediate re-entry: NEEDI j may be used to indicate what action you have taken for integral j.
NEEDI j=1
You have provided the values fj xi in FM ji, for i=1,2,…,nx.
NEEDI j<0
You are abandoning the evaluation of integral j. The current values of DINEST j and ERREST j will be returned on final completion.
Otherwise you have not provided the value fj xi.
On final exit: NEEDI j indicates the final state of integral j.
NEEDI j=0
The error estimate for Fj is below the requested tolerance.
NEEDI j=1
The error estimate for Fj is below the requested tolerance after extrapolation.
NEEDI j=2
The error estimate for Fj is above the requested tolerance.
NEEDI j=3
The error estimate for Fj is above the requested tolerance, and extremely bad behaviour of integral j has been detected.
NEEDI j<0
You prohibited further evaluation of integral j.
7:   X LENX – REAL (KIND=nag_wp) arrayInput/Output
On initial entry: if Primary Division Mode=AUTOMATIC, X need not be set. This is the default behaviour.
If Primary Division Mode=MANUAL, X is used to supply a set of initial ‘break-points’ inside the domain of integration. Specifically, X i must contain a break-point xi 0, for i=1,2,…,spri-1, where spri is the number of Primary Divisions.
Constraint: if break-points are supplied, xi 0∈a,b, xi 0-a>10.0 ε, xi 0-b>10.0 ε, for i=1,2,…,spri-1.
On intermediate exit: X i is the abscissa xi, for i=1,2,…,nx, at which the appropriate integrals must be evaluated.
8:   LENX – INTEGERInput
On entry: the dimension of the array X as declared in the (sub)program from which D01RAF is called. Currently LENX=max 122,spri-1 will be sufficient for all cases.
Constraint: LENX≥lenxrq, where lenxrq is dependent upon the options currently set (see Section 11). lenxrq is returned as LENXRQ from D01RCF.
9:   NX – INTEGERInput/Output
On initial entry: need not be set.
On intermediate exit: nx, the number of abscissae at which integrands are required.
On intermediate re-entry: must not be changed.
10:   FM LDFM* – REAL (KIND=nag_wp) arrayInput
Note: the second dimension of the array FM must be at least sdfmrq, where sdfmrq is dependent upon ni and the options currently set. sdfmrq is returned as SDFMRQ from D01RCF. If default options are chosen, sdfmrq=lenxrq.
On initial entry: need not be set.
On intermediate re-entry: if indicated by NEEDI j you must supply the values fj xi in FM ji, for i=1,2,…,nx and j=1,2,…,ni.
11:   LDFM – INTEGERInput
On entry: the first dimension of the array FM as declared in the (sub)program from which D01RAF is called.
Constraint: LDFM≥ldfmrq, where ldfmrq is dependent upon ni and the options currently set. ldfmrq is returned as LDFMRQ from D01RCF. If default options are chosen, ldfmrq=ni, implying LDFM≥NI.
12:   DINEST NI – REAL (KIND=nag_wp) arrayInput/Output
DINEST j contains the current estimate of the definite integral Fj.
On initial entry: need not be set.
On intermediate re-entry: must not be altered.
On exit: contains the current estimates of the NI integrals. If IREVCM=0, this will be the final solution.
13:   ERREST NI – REAL (KIND=nag_wp) arrayInput/Output
ERREST j contains the current error estimate of the definite integral Fj.
On initial entry: need not be set.
On intermediate re-entry: must not be altered.
On exit: contains the current error estimates for the NI integrals. If IREVCM=0, ERREST contains the final error estimates of the NI integrals.
14:   IOPTS 100 – INTEGER arrayCommunication Array
15:   OPTS 100 – REAL (KIND=nag_wp) arrayCommunication Array
The arrays IOPTS and OPTS must not be altered between calls to any of the routines D01RAF, D01RCF, D01ZKF and D01ZLF.
16:   ICOM LICOM – INTEGER arrayCommunication Array
ICOM contains details of the integration procedure, including information on the integration of the ni integrals over individual segments. This data is stored sequentially in the order that segments are created. For further information see Section 9.1.
17:   LICOM – INTEGERInput
On entry: the dimension of the array ICOM.
Constraint: LICOM≥licmin, where licmin is dependent upon NI and the current options set. licmin is returned as LICMIN from D01RCF. If the default options are set, then licmin=55+6×NI. Larger values than licmin are recommended if you anticipate that any integrals will require the domain to be further subdivided.
The maximum value that may be required, licmax, is returned as LICMAX from D01RCF. If default options are chosen, except for possibly increasing the value of spri, then licmax=50+5×NI+spri+100×5+NI.
18:   COM LCOM – REAL (KIND=nag_wp) arrayCommunication Array
COM contains details of the integration procedure, including information on the integration of the ni integrals over individual segments. This data is stored sequentially in the order that segments are created. For further information see Section 9.1.
19:   LCOM – INTEGERInput
On entry: the dimension of the array COM.
Constraint: LCOM>lcmin, where lcmin is dependent upon NI, spri and the current options set. lcmin is returned as LCMIN from D01RCF. If default options are set, then lcmin =96+12×NI. Larger values are recommended if you anticipate that any integrals will require the domain to be further subdivided.
Given the current options and arguments, the maximum value, lcmax, of LCOM that may be required, is returned as LCMAX from D01RCF. If default options are chosen, lcmax=94+9×NI+NI/2 +spri+100×2+NI/2+2×NI.
20:   IFAIL – INTEGERInput/Output
On initial entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, because for this routine the values of the output arguments may be useful even if IFAIL≠0 on exit, the recommended value is -1. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On final exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Note: D01RAF may return useful information for one or more of the following detected errors or warnings.
Errors or warnings detected by the routine:
IFAIL=1
At least one error estimate exceeded the requested tolerances.
IFAIL=2
Extremely bad behaviour was detected for at least one integral.
IFAIL=3
Extremely bad behaviour was detected for at least one integral. At least one other integral error estimate was above the requested tolerance.
IFAIL=11
IREVCM had an illegal value.
On entry, IREVCM=value.
IFAIL=21
On entry, NI=value.
Constraint: NI≥1.
IFAIL=71
On entry, Primary Division Mode=MANUAL and at least one supplied break-point in X is outside of the domain of integration.
IFAIL=81
LENX is insufficient for the chosen options.
On entry, LENX=value.
Constraint: LENX≥value.
IFAIL=111
LDFM<ldfmrq. If default options are chosen, this implies LDFM<NI.
On entry, LDFM=value.
Constraint: LDFM≥value.
IFAIL=171
LICOM is insufficient for additional subdivision.
On entry, LICOM=value.
Constraint: LICOM≥value.
IFAIL=191
LCOM is insufficient for additional subdivision.
On entry, LCOM=value.
Constraint: LCOM≥value.
IFAIL=1001
Either the option arrays IOPTS and OPTS have not been initialized for D01RAF, or they have become corrupted.
IFAIL=1101
On entry, one of ICOM and COM has become corrupted.
IFAIL=-1
Evaluation of all integrals has been stopped during the initial phase.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

D01RAF cannot guarantee, but in practice usually achieves, the following accuracy for each integral Fj:
Fj - DINEST j ≤ tol
where
tol = max εa, εr × Fj
εa and εr are the error tolerances Absolute Tolerance and Relative Tolerance respectively. Moreover, it returns ERREST, the entries of which in normal circumstances satisfy,
Fj - DINEST j ≤ ERREST j ≤ tol .

8 Parallelism and Performance

D01RAF is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
D01RAF makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The time required by D01RAF is usually dominated by the time required to evaluate the values of the integrands fj.
D01RAF will be most efficient if any badly behaved integrands provided have irregularities over similar subsections of the domain. For example, evaluation of the integrals,
∫ 0 1 log x x-12 x 2 dx
will be quite efficient, as the irregular behaviour of the first two integrands is at x=0. On the contrary, the evaluation of the integrals,
∫ 0 1 log x log 1-x dx
will be less efficient, as the two integrands have singularities at opposite ends of the domain, which will result in subdivisions which are only of use to one integrand. In such cases, it will be more efficient to use two sets of calls to D01RAF.
D01RAF will flag extremely bad behaviour if a sub-interval k- with bounds a k-,b k- satisfying b k- - a k- < max δa, δr × b-a has a local error estimate greater than the requested tolerance for at least one integral. The values δa and δr can be set through the optional parameters Absolute Interval Minimum and Relative Interval Minimum respectively.

9.1 Details of the Computation

This section is recommended for expert users only. It describes the contents of the arrays COM and ICOM upon exit from D01RAF with IFAIL=0, 1, 2 or 3, and provided at least one iteration completed, failure due to insufficient LICOM or LCOM.
The arrays ICOM and COM contain details of the integration, including various scalars, one-dimensional arrays, and (effectively) two-dimensional arrays. The dimensions of these arrays vary depending on the arguments and options used and the progress of the algorithm. Here we describe some of these details, including how and where they are stored in ICOM and COM.
Scalar quantities:
The indices in ICOM including the following scalars are available via query only options, see Section 11.2. For example, Ildi is the integer value returned by the option Index LDI.
ldi | The leading dimension of the two-dimensional integer arrays stored in ICOM detailed below. ldi=ICOM Ildi.
ldr | The leading dimension of the two-dimensional real arrays stored in COM detailed below. ldr=ICOM Ildr.
nsdiv | The number of segments that have been subdivided during the adaptive process. nsdiv=ICOM Insdiv.
nseg | The total number of segments formed. nseg=2 nsdiv+spri. nseg=ICOM Inseg.
dsp | The reference of the first element of the array ds stored in COM. dsp=ICOM Idsp.
esp | The reference of the first element of the array es stored in COM. esp=ICOM Iesp.
evalsp | The reference of the first element of the array evals stored in ICOM. evalsp=ICOM Ievalsp.
fcp | The reference of the first element of the array fcount stored in ICOM. fcp=ICOM Ifcp.
sinforp | The reference of the first element of the array sinfor stored in COM. sinforp=ICOM Isinforp.
sinfoip | The reference of the first element of the array sinfoi stored in ICOM. sinfoip=ICOM Isinfoip.
One-dimensional arrays:
fcount ni
fcount 1=ICOM fcp.
fcount j contains the number of different approximations of integral j calculated, for j=1,2,…,ni.
Two-dimensional arrays:
sinfoi 5 nseg
sinfoi 11=ICOM sinfoip.
sinfoi contains information about the hierarchy of splitting.
sinfoi 1 k contains the split identifier for segment k, for k=1,2,…,nseg.
sinfoi 2 k contains the parent segment number of segment k (i.e., the segment was split to create segment k), for k=1,2,…,nseg.
sinfoi 3 k and sinfoi 4 k contain the segment numbers of the two child segments formed from segment k, if segment k has been split. If segment k has not been split, these will be negative.
sinfoi 5 k contains the level at which the segment exists, corresponding to na+1, where na is the number of ancestor segments of segment k, for k=1,2,…,nseg. A negative level indicates that segment k will not be split further, the level is then given by the absolute value of sinfoi 5 k.
sinfor 2 nseg
sinfor 11=COM sinforp.
sinfor contains the bounds of each segment.
sinfor 1 k contains the lower bound of segment k, for k=1,2,…,nseg.
sinfor 2 k contains the upper bound of segment k, for k=1,2,…,nseg.
evals ni nseg
evals 11=ICOM evalsp.
evals contains information to indicate whether an estimate of the integral j has been obtained over segment k, and if so whether this evaluation still contributes to the direct estimate of Fj, for j=1,2,…,ni and k=1,2,…,nseg.
evals jk=0 indicates that integral j has not been evaluated over segment k.
evals jk=1 indicates that integral j has been evaluated over segment k, and that this evaluation contributes to the direct estimate of Fj.
evals jk=2 indicates that integral j has been evaluated over segment k, that this evaluation contributes to the direct estimate of Fj, and that you have requested no further evaluation of this integral at this segment by setting NEEDI j<0.
evals jk=3 indicates that integral j has been evaluated over segment k, and this evaluation no longer contributes to the direct estimate of Fj.
evals jk=4 indicates that integral j has been evaluated over segment k, that this evaluation contributes to the direct estimate of Fj, and that this segment is too small for any further splitting to be performed. Integral j also has a local error estimate over this segment above the requested tolerance. Such segments cause D01RAF to return IFAIL=2 or 3, indicating extremely bad behaviour.
evals jk=5 indicates that integral j has been evaluated over segment k, that this evaluation contributes to the direct estimate of Fj, and that this segment is too small for any further splitting to be performed. The local error estimate is however below the requested tolerance.
ds ni nseg
ds 11=COM dsp.
ds jk contains the definite integral estimate of the jth integral over the kth segment, ds j,k, provided it has been evaluated, for j=1,2,…,ni and k=1,2,…,nseg.
es ni nseg
es 11=COM esp.
es jk contains the definite integral error estimate of the jth integral over the kth segment, es j,k, provided it has been evaluated, for j=1,2,…,ni and k=1,2,…,nseg.
For each integral j, the direct approximation Dj of Fj, and its error estimate Ej, may be constructed as,
Fj ≈ Dj = ∑ Kj ds j,k , Fj-Dj ≈ Ej = ∑ Kj es j,k ,
where Kj is the set of all contributing segments, Kj=k∣evals jk=1, ​2, ​4​ or ​5, ​1≤k≤nseg. Dj will have been returned in DINEST j, unless extrapolation was successful, as indicated by NEEDI j.
Similarly, Ej will have been returned in ERREST j unless extrapolation was successful, in which case the error estimate from the extrapolation will have been returned. If for a given integral j one or more contributing segments have unacceptable error estimates, it may be possible to improve the direct approximation by replacing the contributions from these segments with more accurate estimates should these be calculable by some means. Indeed for any segment k-∈k, with lower bound a k-=sinfor 1,k- and upper bound b k-=sinfor 2,k-, one may alter the direct approximation Dj by the following,
ds j,k- new ≈ ∫ a k- b k- fj x ​ ​ dx Dj = ∑Kj ds j,k - ds j , k- + ds j,k- new .
The error estimate Ej may be altered similarly.

10 Example

This example integrates
F = ∫ 0 π x sin 2 x cos 15 x x 2 sin 2 x cos 50 x   dx .

10.1 Program Text

Program Text (d01rafe.f90)

10.2 Program Data

None.

10.3 Program Results

Program Results (d01rafe.r)

11 Optional Parameters

This section can be skipped if you wish to use the default values for all optional parameters, otherwise, the following is a list of the optional parameters available. A full description of each optional parameter is provided in Section 11.1.
  • Absolute Interval Minimum
  • Absolute Tolerance
  • Extrapolation
  • Extrapolation Safeguard
  • Maximum Subdivisions
  • Primary Division Mode
  • Primary Divisions
  • Prioritize Error
  • Quadrature Rule
  • Relative Interval Minimum
  • Relative Tolerance
The following optional parameters, see Section 11.2, may be utilized by expert users in conjunction with the information provided in Section 9.1.
  • Index LDI
  • Index LDR
  • Index NSDIV
  • Index NSEG
  • Index FCP
  • Index EVALSP
  • Index DSP
  • Index ESP
  • Index SINFOIP
  • Index SINFORP

11.1 Description of the Optional Parameters

For each option, we give a summary line, a description of the optional parameter and details of constraints.
The summary line contains:
  • the keywords, where the minimum abbreviation of each keyword is underlined;
  • a parameter value, where the letters a, i and r denote options that take character, integer and real values respectively;
  • the default value.
The following symbol represents various machine constants:
  • ε represents the machine precision (see X02AJF).
All options accept the value ‘DEFAULT’ in order to return single options to their default states.
Keywords and character values are case insensitive, however they must be separated by at least one space.
Unsetable options will return the appropriate value when calling D01ZLF. They will have no effect if passed to D01ZKF.
For D01RAF the maximum length of the argument CVALUE used by D01ZLF is 15.
Absolute Interval Minimum r Default =128.0 ε
r=δa, the absolute lower limit for a segment to be considered for subdivision. See also Relative Interval Minimum and Section 9.
Constraint: r≥128 ε.
Absolute Tolerance r Default =1024 ε
r=εa, the absolute tolerance required. See also Relative Tolerance and Section 3.
Constraint: r≥0.0.
Extrapolation a Default =ON
Activate or deactivate the use of the ε algorithm (Wynn (1956)). Extrapolation often reduces the number of iterations required to achieve the desired solution, but it can occasionally lead to premature convergence towards an incorrect answer.
ON
Use extrapolation.
OFF
Disable extrapolation.
Extrapolation Safeguard r Default =1.0E−12
r=εsafe. If εq is the estimated error from the quadrature evaluation alone, and εex is the error estimate determined using extrapolation, then the extrapolated solution will only be accepted if εsafe εq ≤ εex.
Maximum Subdivisions i Default =50
i=maxsdiv, the maximum number of subdivisions the algorithm may use in the adaptive phase, forming at most an additional 2×maxsdiv segments.
Primary Divisions i Default =1
i=spri, the number of initial segments of the domain a,b. By default the initial segment is the entire domain.
Constraint: 0<i<1000000.
Primary Division Mode a Default =AUTOMATIC
Determines how the initial set of spri segments will be generated.
AUTOMATIC
D01RAF will automatically generate spri segments of equal size covering the interval a,b.
MANUAL
D01RAF will use the break-points xi 0, for i=1,2,…,spri-1, supplied in X on initial entry to generate the initial segments covering a,b. These may be supplied in any order, however it will be more efficient to supply them in ascending (or descending if a>b) order. Repeated break-points are allowed, although this will generate fewer initial segments.
Note: an absolute bound on the size of an initial segment of 10.0 ε is automatically applied in all cases, and will result in fewer initial subdivisions being generated if automatically generated or supplied break-points result in segments smaller than this.
Prioritize Error a Default=LEVEL
Indicates how new subdivisions of segments sustaining unacceptable local errors for integrals should be prioritized.
LEVEL
Segments with lower level with unsatisfactory error estimates will be chosen over segments with greater error on higher levels. This will probably lead to more integrals being improved in earlier iterations of the algorithm, and hence will probably lead to fewer repeated returns (see argument SID), and to more integrals being satisfactorily estimated if computational exhaustion occurs.
MAXERR
The segment with the worst overall error will be split, regardless of level. This will more rapidly improve the worst integral estimates, although it will probably result in the fewest integrals being improved in earlier iterations, and may hence lead to more repeated returns (see argument SID), and potentially fewer integrals satisfying the requested tolerances if computational exhaustion occurs.
Quadrature Rule a Default =GK15
The basic quadrature rule to be used during the integration. Currently 6 Gauss–Kronrod rules are available, all identifiable by the letters GK followed by the number of points required by the Kronrod rule. Higher order rules generally provide higher accuracy with fewer subdivisons. However, for integrands with sharp singularities, lower order rules may be more efficient, particularly if the integrand away from the singularity is well behaved. With higher order rules, you may need to increase the Absolute Interval Minimum and the Relative Interval Minimum to maintain numerical difference between the abscissae and the segment bounds.
GK15
The Gauss–Kronrod rule based on 7 Gauss points and 15 Kronrod points.
GK21
The Gauss–Kronrod rule based on 10 Gauss points and 21 Kronrod points. This is the rule used by D01ATF
GK31
The Gauss–Kronrod rule based on 15 Gauss points and 31 Kronrod points.
GK41
The Gauss–Kronrod rule based on 20 Gauss points and 41 Kronrod points.
GK51
The Gauss–Kronrod rule based on 25 Gauss points and 51 Kronrod points.
GK61
The Gauss–Kronrod rule based on 30 Gauss points and 61 Kronrod points. This is the highest order rule, most suitable for highly oscilliatory integrals.
Relative Interval Minimum r Default =1.0E−6
r=δr, the relative factor in the lower limit, δr b-a, for a segment to be considered for subdivision. See also Absolute Interval Minimum and Section 9.
Constraint: r≥0.0.
Relative Tolerance r Default =ε
r=εr, the required relative tolerance. See also Absolute Tolerance and Section 3.
Constraint: r≥0.0.
Note: setting both εr=εa=0.0 is possible, although it will most likely result in an excessive amount of computational effort.

11.2 Diagnostic Options

These options are provided for expert users who wish to examine and modify the precise details of the computation. They should only be used after D01RAF returns, as opposed to the options listed in Section 11.1 which must be used before the first call to D01RAF.
Index LDI i query only
Ildi, the index of ICOM required for obtaining ldi. See Section 9.1.
Index LDR i query only
Ildr, the index of ICOM required for obtaining ldr. See Section 9.1.
Index NSDIV i query only
Insdiv, the index of ICOM required for obtaining nsdiv. See Section 9.1.
Index NSEG i query only
Inseg, the index of ICOM required for obtaining nseg. See Section 9.1.
Index FCP i query only
Ifcp, the index of ICOM required for obtaining fcp. See Section 9.1.
Index EVALSP i query only
Ievalsp, the index of ICOM required for obtaining evalsp. See Section 9.1.
Index DSP i query only
Idsp, the index of ICOM required for obtaining dsp. See Section 9.1.
Index ESP i query only
Iesp, the index of ICOM required for obtaining esp. See Section 9.1.
Index SINFOIP i query only
Isinfoip, the index of ICOM required for obtaining sinfoip. See Section 9.1.
Index SINFORP i query only
Isinforp, the index of ICOM required for obtaining sinforp. See Section 9.1.
D01 Chapter Contents
D01 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


D01RBF : NAG Library, Mark 26

D01 Chapter Contents
D01 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

D01RBF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.
Note: please be advised that D01RBF has been deprecated. You are advised to follow the directions in Section 9.1 in D01RAF to replicate its functionality. Furthermore, any future diagnostic enhancements for D01RAF will only be available in this manner.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
10 Example

1 Purpose

D01RBF is an expert diagnostic routine associated with D01RAF to allow the arrays ICOM and COM to be examined. These arrays contain details of the adaptive process. Facilities are provided, via the argument MONIT, to refine the final answer by adjusting the contribution made by specific segments.

2 Specification

SUBROUTINE D01RBF ( MONIT, NI, DINEST, ERREST, ICOM, LICOM, LICUSD, COM, LCOM, LCUSD, IUSER, RUSER, IFAIL)
INTEGER | NI, ICOM(LICOM), LICOM, LICUSD, LCOM, LCUSD, IUSER(*), IFAIL
REAL (KIND=nag_wp) | DINEST(NI), ERREST(NI), COM(LCOM), RUSER(*)
EXTERNAL | MONIT

3 Description

The principal role of D01RBF is to take information about the adaptive process that is stored in COM and ICOM and present it in more intelligible arguments. A monitor routine, MONIT, allows you to report the progress of the adaptive process back to the calling program between those calls of D01RAF which have returned IREVCM=11 or 12.
A secondary role, useful only if you are an expert, is to utilize MONIT in such a way that it can override aspects of that information. Specifically, you may choose to remove the contributions of one or more individual segments from the estimates for individual integrals contained in DINEST and ERREST, and replace such information with a more accurate approximation you have calculated by some other means. Clearly this facility should only be used with care. We recommend that it be used only after D01RAF has returned with IREVCM=0, i.e., it has completed the computation of the approximations of the integrals.

4 References

None.

5 Arguments

1:   MONIT – SUBROUTINE, supplied by the NAG Library or the user.External Procedure
MONIT allows you to examine details of the adaptive process after a call of D01RAF returning IREVCM=11 or 12. Additionally, after a call of D01RAF returning IREVCM=0, MONIT may enhance the computed solution.
If no monitoring is required, MONIT may be the dummy monitoring routine D01RBM. (D01RBM is included in the NAG Library.)
The specification of MONIT is:
SUBROUTINE MONIT ( NI, NS, DINEST, ERREST, FCOUNT, SINFOI, EVALS, LDI, SINFOR, FS, ES, LDR, IUSER, RUSER)
INTEGER | NI, NS, FCOUNT(NI), SINFOI(LDI,*), EVALS(LDI,*), LDI, LDR, IUSER(*)
REAL (KIND=nag_wp) | DINEST(NI), ERREST(NI), SINFOR(LDR,*), FS(LDR,*), ES(LDR,*), RUSER(*)
1:   NI – INTEGERInput
On entry: ni, the number of integrands specified in D01RAF.
2:   NS – INTEGERInput
On entry: ns, the number of segments formed during the adaptive procedure that can currently be examined. ns=2 nsdiv+spri, where nsdiv is the number of segments that have been subdivided (the number of subdivisions).
3:   DINEST NI – REAL (KIND=nag_wp) arrayInput/Output
On entry: DINEST j contains the current estimate of the definite integral of integrand j, for j=1,2,…,ni.
On exit: you may refine the estimates in DINEST. This should only be done after D01RAF has returned IREVCM=0.
4:   ERREST NI – REAL (KIND=nag_wp) arrayInput/Output
On entry: ERREST j contains the current error estimate associated with integral j, for j=1,2,…,ni.
On exit: you may refine the estimates in ERREST. This should only be done after D01RAF has returned IREVCM=0.
5:   FCOUNT NI – INTEGER arrayInput
On entry: FCOUNT j contains the number of different approximations of integral j calculated so far, for j=1,2,…,ni.
6:   SINFOI LDI* – INTEGER arrayInput
On entry: SINFOI lk contains information about the hierarchy of splitting, for l=1,2,…,5 and k=1,2,…,ns.
SINFOI 1 k
Contains a unique identifier, the SID, related to segment k.
SINFOI 2 k
Contains the parent segment number of segment k, the reference to the segment that was split to create segment k.
SINFOI 3 k and SINFOI 4 k
Contain the segment numbers of the two child segments formed from segment k, if segment k has been split. If segment k has not been split, these will be negative.
SINFOI 5 k
Contains the level at which the segment exists, corresponding to na+1, where na is the number of ancestor segments of segment k.
If SINFOI 5 k<0, this segment is considered too small for further splitting, and its level is SINFOI 5 k.
7:   EVALS LDI* – INTEGER arrayInput
On entry: contains information to indicate whether an estimate of the integral j has been obtained over segment k, and if so whether this evaluation still contributes to the approximation in DINEST j, for j=1,2,…,ni and k=1,2,…,ns.
EVALS jk=0
Indicates that integral j has not been evaluated over segment k.
EVALS jk=1
Indicates that integral j has been evaluated over segment k, and that this evaluation contributes to the total approximation DINEST j.
EVALS jk=2
Indicates that integral j has been evaluated over segment k, that this evaluation contributes to the total approximation DINEST j, and that you have requested no further evaluation of this integral at this segment by setting NEEDI j<0.
EVALS jk=3
Indicates that integral j has been evaluated over segment k, and this evaluation no longer contributes to DINEST j.
EVALS jk=4
Indicates that integral j has been evaluated over segment k, that this evaluation contributes to the total approximation DINEST j, and that this segment is too small for any further splitting to be performed. Integral j also has a local error estimate over this segment above the requested tolerance. Such segments cause D01RAF to return IFAIL=2 or 3, indicating extremely bad behaviour.
EVALS jk=5
Indicates that integral j has been evaluated over segment k, that this evaluation contributes to the total approximation of DINEST j, and that this segment is too small for any further splitting to be performed. The local error estimate is however below the requested tolerance.
8:   LDI – INTEGERInput
On entry: the leading dimension of arrays SINFOI and EVALS.
9:   SINFOR LDR* – REAL (KIND=nag_wp) arrayInput
On entry: SINFOR contains the bounds of each segment k, for k=1,2,…,ns.
SINFOR 1 k
Contains the lower bound of segment k.
SINFOR 2 k
Contains the upper bound of segment k.
10:   FS LDR* – REAL (KIND=nag_wp) arrayInput
On entry: FS jk contains the definite integral estimate of the jth integral over the kth segment, for j=1,2,…,ni and k=1,2,…,ns.
11:   ES LDR* – REAL (KIND=nag_wp) arrayInput
On entry: ES jk contains the definite integral error estimate of the jth integral over the kth segment, for j=1,2,…,ni and k=1,2,…,ns.
12:   LDR – INTEGERInput
On entry: the leading dimension of arrays SINFOR, FS and ES.
13:   IUSER* – INTEGER arrayUser Workspace
14:   RUSER* – REAL (KIND=nag_wp) arrayUser Workspace
MONIT is called with the arguments IUSER and RUSER as supplied to D01RBF. You are free to use the arrays IUSER and RUSER to supply information to MONIT as an alternative to using COMMON global variables.
MONIT must either be a module subprogram USEd by, or declared as EXTERNAL in, the (sub)program from which D01RBF is called. Arguments denoted as Input must not be changed by this procedure.
2:   NI – INTEGERInput
On entry: ni, the number of integrals.
3:   DINEST NI – REAL (KIND=nag_wp) arrayInput/Output
On entry: DINEST j contains the current estimate of the definite integral of integrand j, for j=1,2,…,ni.
On exit: DINEST is not altered by D01RBF directly. It may be changed by MONIT.
4:   ERREST NI – REAL (KIND=nag_wp) arrayInput/Output
On entry: ERREST j contains the current error estimate associated with integral j, for j=1,2,…,ni.
On exit: ERREST is not altered by D01RBF directly. It may be changed by MONIT.
5:   ICOM LICOM – INTEGER arrayCommunication Array
On entry: the elements of this array must not be changed since the call of D01RAF.
6:   LICOM – INTEGERInput
On entry: the dimension of the array ICOM as declared in the (sub)program from which D01RBF is called. Normally this will be the same value LICOM passed to D01RAF.
Constraint: LICOM≥50.
Note: if LICOM<LICUSD, (i.e., LICOM is less than the value passed to D01RAF) not all segments may be investigated using MONIT (see argument NS) and D01RBF will return IFAIL=1.
7:   LICUSD – INTEGEROutput
On exit: the number of elements of the array ICOM, passed to D01RAF, actually used.
8:   COM LCOM – REAL (KIND=nag_wp) arrayCommunication Array
On entry: the elements of this array must not be changed since the call of D01RAF.
9:   LCOM – INTEGERInput
On entry: the dimension of the array COM as declared in the (sub)program from which D01RBF is called. Normally this will be the same value LCOM passed to D01RAF.
Constraint: LCOM≥50.
Note: if LCOM<LCUSD, (i.e., LCOM is less than the value passed to D01RAF) not all segments may be investigated using MONIT (see argument NS) and D01RBF will return IFAIL=1.
10:   LCUSD – INTEGEROutput
On exit: the number of elements of COM used by D01RAF.
11:   IUSER* – INTEGER arrayUser Workspace
12:   RUSER* – REAL (KIND=nag_wp) arrayUser Workspace
IUSER and RUSER are not used by D01RBF, but are passed directly to MONIT and may be used to pass information to this routine as an alternative to using COMMON global variables.
13:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, because for this routine the values of the output arguments may be useful even if IFAIL≠0 on exit, the recommended value is -1. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Note: D01RBF may return useful information for one or more of the following detected errors or warnings.
Errors or warnings detected by the routine:
IFAIL=1
On entry, LICOM=value, LCOM=value.
LICOM or LCOM is insufficient for a complete examination of the communication arrays. A maximum value segments out of value are examinable.
Constraint: LICOM≥value and LCOM≥value.
IFAIL=21
On entry, NI is not consistent with that used to construct the communication arrays.
On entry, NI=value.
Constraint: NI=value.
IFAIL=61
On entry, LICOM<50.
IFAIL=91
On entry, LCOM<50.
IFAIL=1101
Either the communication arrays have not been created by D01RAF, or they have become corrupted.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

Not applicable.

8 Parallelism and Performance

D01RBF is not threaded in any implementation.

9 Further Comments

When called after D01RAF has returned IREVCM=0, D01RBF may be used to modify DINEST and ERREST. For example if EVALS j k- =4 for some j∈1,…,ni, k-∈1,…,ns, indicating integral j was badly behaved over segment k-, then one may potentially modify DINEST j as follows:
  • a k- = SINFOR lk
  • b k- = SINFOR lk
  • F k-new = ∫ a k- b k- fj x dx: performed using accurate technique for specific function.
  • DINEST j = DINEST j - FS j k- + F k- new
ERREST may be similarly updated if required.
Note: if integral j has been approximated successfully due to extrapolation, indicated by NEEDI j=1 after D01RAF has completed, DINEST j will not be the direct sum of the contributing segments. You may however reconstruct the unextrapolated integral estimate as,
DINEST j = ∑ K FS jk + ∑ K- FS j k- ,
where K=k∣EVALS LDI×k+j=1,2,5 and K-=k-∣EVALS LDI×k-+j=4, the sets of all contributing segements where integral j has been evaluated accurately and inaccurately respectively. Some or all of the terms in the summation over K- may be replaced with more accurate approximations F k-new if available.

10 Example

See Section 10 in D01RAF.
D01 Chapter Contents
D01 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


D01RCF : NAG Library, Mark 26

D01 Chapter Contents
D01 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

D01RCF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
10 Example

1 Purpose

The dimension of the arrays that must be passed as actual arguments to D01RAF are dependent upon a number of factors. D01RCF returns the correct size of these arrays enabling D01RAF to be called successfully.

2 Specification

SUBROUTINE D01RCF ( NI, LENXRQ, LDFMRQ, SDFMRQ, LICMIN, LICMAX, LCMIN, LCMAX, IOPTS, OPTS, IFAIL)
INTEGER | NI, LENXRQ, LDFMRQ, SDFMRQ, LICMIN, LICMAX, LCMIN, LCMAX, IOPTS(*), IFAIL
REAL (KIND=nag_wp) | OPTS(*)

3 Description

D01RCF returns the minimum dimension of the arrays X (lenxrq), FM (ldfmrq×sdfmrq), ICOM (licmin) and COM (lcmin) that must be passed to D01RAF to enable the integration to commence given options currently set for the NI integrands. D01RCF also returns the upper bounds licmax and lcmax for the dimension of the arrays ICOM and COM, that could possibly be required with the chosen options.
All the minimum values lenxrq, ldfmrq, sdfmrq, licmin and lcmin, and subsequently all the maximum values licmax and lcmax may be affected if different options are set, and hence D01RCF should be called after any options are set, and before the first call to D01RAF.
A segment is here defined as a (possibly maximal) subset of the domain of integration. During subdivision, a segment is bisected into two new segments.

4 References

None.

5 Arguments

1:   NI – INTEGERInput
On entry: ni, the number of integrals which will be approximated in the subsequent call to D01RAF.
Constraint: NI>0.
2:   LENXRQ – INTEGEROutput
On exit: lenxrq, the minimum dimension of the array X that can be used in a subsequent call to D01RAF.
3:   LDFMRQ – INTEGEROutput
On exit: ldfmrq, the minimum leading dimension of the array FM that can be used in a subsequent call to D01RAF.
4:   SDFMRQ – INTEGEROutput
On exit: sdfmrq, the minimum second dimension of the array FM that can be used in a subsequent call to D01RAF.
Note: the minimum dimension of the array FM is ldfmrq×sdfmrq.
5:   LICMIN – INTEGEROutput
On exit: licmin, the minimum dimension of the array ICOM that must be passed to D01RAF to enable it to calculate a single approximation to all the ni integrals over the interval a,b with spri initial segments.
6:   LICMAX – INTEGEROutput
On exit: licmax the dimension of the array ICOM that must be passed to D01RAF to enable it to exhaust the adaptive process controlled by the currently set options for the ni integrals over the interval a,b with spri initial segments.
7:   LCMIN – INTEGEROutput
On exit: lcmin, the minimum dimension of the array COM that must be passed to D01RAF to enable it to calculate a single approximation to all the ni integrals over the interval a,b with spri initial segments.
8:   LCMAX – INTEGEROutput
On exit: lcmax, the dimension of the array COM that must be passed to D01RAF to enable it to exhaust the adaptive process controlled by the currently set options for the ni integrals over the interval a,b with spri initial segments.
9:   IOPTS* – INTEGER arrayCommunication Array
Note: the dimension of this array is dictated by the requirements of associated functions that must have been previously called. This array must be the same array passed as argument IOPTS in the previous call to D01ZKF.
On entry: the integer option array as returned by D01ZKF.
Constraint: IOPTS must not be changed between calls to D01ZKF, D01ZLF, D01RCF and D01RAF.
10:   OPTS* – REAL (KIND=nag_wp) arrayCommunication Array
Note: the dimension of this array is dictated by the requirements of associated functions that must have been previously called. This array must be the same array passed as argument OPTS in the previous call to D01ZKF.
On entry: the real option array as returned by D01ZKF.
Constraint: OPTS must not be changed between calls to D01ZKF, D01ZLF, D01RCF and D01RAF.
11:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=21
On entry, NI=value.
Constraint: NI>0.
IFAIL=1001
One of the option arrays IOPTS or OPTS has become corrupted. Re-initialize the arrays using D01ZKF.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

Not applicable.

8 Parallelism and Performance

D01RCF is not threaded in any implementation.

9 Further Comments

None.

10 Example

See Section 10 in D01RAF for examples of the usage of D01RCF.
D01 Chapter Contents
D01 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


D01RGF : NAG Library, Mark 26

D01 Chapter Contents
D01 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

D01RGF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

D01RGF is a general purpose integrator which calculates an approximation to the integral of a function f x over a finite interval a,b:
I= ∫ab f x dx .
The routine is suitable as a general purpose integrator, and can be used when the integrand has singularities and infinities. In particular, the routine can continue if the subroutine F explicitly returns a quiet or signalling NaN or a signed infinity.

2 Specification

SUBROUTINE D01RGF ( A, B, F, EPSABS, EPSREL, DINEST, ERREST, NEVALS, IUSER, RUSER, IFAIL)
INTEGER | NEVALS, IUSER(*), IFAIL
REAL (KIND=nag_wp) | A, B, EPSABS, EPSREL, DINEST, ERREST, RUSER(*)
EXTERNAL | F

3 Description

D01RGF uses the algorithm described in Gonnet (2010). It is an adaptive algorithm, similar to the QUADPACK routine QAGS (see Piessens et al. (1983), see also D01RAF) but includes significant differences regarding how the integrand is represented, how the integration error is estimated and how singularities and divergent integrals are treated. The local error estimation is described in Gonnet (2010).
D01RGF requires a subroutine to evaluate the integrand at an array of different points and is therefore amenable to parallel execution.

4 References

Gonnet P (2010) Increasing the reliability of adaptive quadrature using explicit interpolants ACM Trans. Math. software 37 26
Piessens R, de Doncker–Kapenga E, Überhuber C and Kahaner D (1983) QUADPACK, A Subroutine Package for Automatic Integration Springer–Verlag

5 Arguments

1:   A – REAL (KIND=nag_wp)Input
On entry: a, the lower limit of integration.
2:   B – REAL (KIND=nag_wp)Input
On entry: b, the upper limit of integration. It is not necessary that a<b.
Note: if A=B, the routine will immediately return DINEST=0.0, ERREST=0.0 and NEVALS=0.
3:   F – SUBROUTINE, supplied by the user.External Procedure
F must return the value of the integrand f at a set of points.
The specification of F is:
SUBROUTINE F ( X, NX, FV, IFLAG, IUSER, RUSER)
INTEGER | NX, IFLAG, IUSER(*)
REAL (KIND=nag_wp) | X(NX), FV(NX), RUSER(*)
1:   X NX – REAL (KIND=nag_wp) arrayInput
On entry: the abscissae, xi, for i=1,2,…,NX, at which function values are required.
2:   NX – INTEGERInput
On entry: the number of abscissae at which a function value is required.
3:   FV NX – REAL (KIND=nag_wp) arrayOutput
On exit: FV must contain the values of the integrand f. FV i=f xi for all i=1,2,…,NX.
4:   IFLAG – INTEGERInput/Output
On entry: IFLAG=0.
On exit: set IFLAG<0 to force an immediate exit with IFAIL=-1.
5:   IUSER* – INTEGER arrayUser Workspace
6:   RUSER* – REAL (KIND=nag_wp) arrayUser Workspace
F is called with the arguments IUSER and RUSER as supplied to D01RGF. You are free to use the arrays IUSER and RUSER to supply information to F as an alternative to using COMMON global variables.
F must either be a module subprogram USEd by, or declared as EXTERNAL in, the (sub)program from which D01RGF is called. Arguments denoted as Input must not be changed by this procedure.
4:   EPSABS – REAL (KIND=nag_wp)Input
On entry: the absolute accuracy required.
If EPSABS is negative, EPSABS is used. See Section 7.
If EPSABS=0.0, only the relative error will be used.
5:   EPSREL – REAL (KIND=nag_wp)Input
On entry: the relative accuracy required.
If EPSREL is negative, EPSREL is used. See Section 7.
If EPSREL=0.0, only the absolute error will be used otherwise the actual value of EPSREL used by D01RGF is max machine precision,EPSREL.
Constraint: at least one of EPSABS and EPSREL must be nonzero.
6:   DINEST – REAL (KIND=nag_wp)Output
On exit: the estimate of the definite integral F.
7:   ERREST – REAL (KIND=nag_wp)Output
On exit: the error estimate of the definite integral F.
8:   NEVALS – INTEGEROutput
On exit: the total number of points at which the integrand, f, has been evaluated.
9:   IUSER* – INTEGER arrayUser Workspace
10:   RUSER* – REAL (KIND=nag_wp) arrayUser Workspace
IUSER and RUSER are not used by D01RGF, but are passed directly to F and may be used to pass information to this routine as an alternative to using COMMON global variables.
11:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, because for this routine the values of the output arguments may be useful even if IFAIL≠0 on exit, the recommended value is -1. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Note: D01RGF may return useful information for one or more of the following detected errors or warnings.
Errors or warnings detected by the routine:
IFAIL=1
The requested accuracy was not achieved. Consider using larger values of EPSABS and EPSREL.
IFAIL=2
The integral is probably divergent or slowly convergent.
IFAIL=14
Both EPSABS=0.0 and EPSREL=0.0.
IFAIL=-1
Exit requested from F with IFLAG=value.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

D01RGF cannot guarantee, but in practice usually achieves, the following accuracy:
I-DINEST ≤ tol ,
where
tol = max EPSABS , EPSREL × I ,
and EPSABS and EPSREL are user-specified absolute and relative error tolerances. Moreover, it returns the quantity ERREST which, in normal circumstances, satisfies
I-DINEST ≤ ERREST ≤ tol .

8 Parallelism and Performance

D01RGF is currently neither directly nor indirectly threaded. In particular, the user-supplied subroutine F is not called from within a parallel region initialized inside D01RGF.
The user-supplied subroutine F uses a vectorized interface, allowing for the required vector of function values to be evaluated in parallel; for example by placing appropriate OpenMP directives in the code for the user-supplied subroutine F.

9 Further Comments

The time taken by D01RGF depends on the integrand and the accuracy required.
D01RGF is suitable for evaluating integrals that have singularities within the requested interval.
In particular, D01RGF accepts non-finite values on return from the user-supplied subroutine F, and will adapt the integration rule accordingly to eliminate such points. Non-finite values include NaNs and infinities.

10 Example

This example computes
∫ -1 1 sin x x ln 10 1 - x .

10.1 Program Text

Program Text (d01rgfe.f90)

10.2 Program Data

None.

10.3 Program Results

Program Results (d01rgfe.r)

D01 Chapter Contents
D01 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


D01TBF : NAG Library, Mark 26

D01 Chapter Contents
D01 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

D01TBF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

D01TBF returns the weights and abscissae appropriate to a Gaussian quadrature formula with a specified number of abscissae. The formulae provided are for Gauss–Legendre, rational Gauss, Gauss–Laguerre and Gauss–Hermite.

2 Specification

SUBROUTINE D01TBF ( KEY, A, B, N, WEIGHT, ABSCIS, IFAIL)
INTEGER | KEY, N, IFAIL
REAL (KIND=nag_wp) | A, B, WEIGHT(N), ABSCIS(N)

3 Description

D01TBF returns the weights and abscissae for use in the Gaussian quadrature of a function f x. The quadrature takes the form
S=∑i=1 n wi f xi
where wi are the weights and xi are the abscissae (see Davis and Rabinowitz (1975), Fröberg (1970), Ralston (1965) or Stroud and Secrest (1966)).
Weights and abscissae are available for Gauss–Legendre, rational Gauss, Gauss–Laguerre and Gauss–Hermite quadrature, and for a selection of values of n (see Section 5).
(a) Gauss–Legendre Quadrature:
S≃∫ab f x dx
where a and b are finite and it will be exact for any function of the form
f x=∑i=0 2 n-1 ci xi.
(b) Rational Gauss quadrature, adjusted weights:
S≃∫a∞f x dx  a+b> 0   or   S≃∫-∞a f x dx  a+b< 0
and will be exact for any function of the form
f x=∑i=2 2 n+1 ci x+b i=∑i=0 2 n-1 c 2 n+1-i x+b i x+b 2 n+1.
(c) Gauss–Laguerre quadrature, adjusted weights:
S≃∫a∞f x dx  b> 0   or   S≃∫-∞a f x dx  b< 0
and will be exact for any function of the form
f x=e-bx∑i=0 2 n-1 ci xi.
(d) Gauss–Hermite quadrature, adjusted weights:
S≃∫-∞ +∞ f x dx
and will be exact for any function of the form
f x=e-b x-a 2∑i=0 2 n-1 ci xi b>0.
(e) Gauss–Laguerre quadrature, normal weights:
S≃∫a∞e-bx f x dx  b> 0   or   S≃∫-∞a e-bx f x dx  b< 0
and will be exact for any function of the form
f x=∑i=0 2 n-1 ci xi.
(f) Gauss–Hermite quadrature, normal weights:
S≃∫-∞ +∞ e-b x-a 2 f x dx
and will be exact for any function of the form
f x=∑i=0 2 n-1 ci xi.
Note: the Gauss–Legendre abscissae, with a=-1, b=+1, are the zeros of the Legendre polynomials; the Gauss–Laguerre abscissae, with a=0, b=1, are the zeros of the Laguerre polynomials; and the Gauss–Hermite abscissae, with a=0, b=1, are the zeros of the Hermite polynomials.

4 References

Davis P J and Rabinowitz P (1975) Methods of Numerical Integration Academic Press
Fröberg C E (1970) Introduction to Numerical Analysis Addison–Wesley
Ralston A (1965) A First Course in Numerical Analysis pp. 87–90 McGraw–Hill
Stroud A H and Secrest D (1966) Gaussian Quadrature Formulas Prentice–Hall

5 Arguments

1:   KEY – INTEGERInput
On entry: indicates the quadrature formula.
KEY=0
Gauss–Legendre quadrature on a finite interval, using normal weights.
KEY=3
Gauss–Laguerre quadrature on a semi-infinite interval, using normal weights.
KEY=-3
Gauss–Laguerre quadrature on a semi-infinite interval, using adjusted weights.
KEY=4
Gauss–Hermite quadrature on an infinite interval, using normal weights.
KEY=-4
Gauss–Hermite quadrature on an infinite interval, using adjusted weights.
KEY=-5
Rational Gauss quadrature on a semi-infinite interval, using adjusted weights.
Constraint: KEY=0, 3, -3, 4, -4 or -5.
2:   A – REAL (KIND=nag_wp)Input
3:   B – REAL (KIND=nag_wp)Input
On entry: the quantities a and b as described in the appropriate sub-section of Section 3.
Constraints:
  • Rational Gauss: A+B≠0.0;
  • Gauss–Laguerre: B≠0.0;
  • Gauss–Hermite: B>0.
4:   N – INTEGERInput
On entry: n, the number of weights and abscissae to be returned.
Constraint: N=1, 2, 3, 4, 5, 6, 8, 10, 12, 14, 16, 20, 24, 32, 48 or 64.
Note: if n>0 and is not a member of the above list, the maxmium value of n stored below n will be used, and all subsequent elements of ABSCIS and WEIGHT will be returned as zero.
5:   WEIGHT N – REAL (KIND=nag_wp) arrayOutput
On exit: the N weights.
6:   ABSCIS N – REAL (KIND=nag_wp) arrayOutput
On exit: the N abscissae.
7:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
The N-point rule is not among those stored.
On entry: N=value.
N-rule used: N=value.
IFAIL=2
Underflow occurred in calculation of normal weights.
Reduce N or use adjusted weights: N=value.
IFAIL=3
No nonzero weights were generated for the provided parameters.
IFAIL=11
On entry, KEY=value.
Constraint: KEY=0, 3, -3, 4, -4 or -5.
IFAIL=12
The value of A and/or B is invalid for the chosen KEY. Either:
  • The value of A and/or B is invalid for Gauss-Hermite quadrature.
    On entry, KEY=value.
    On entry, A=value and B=value.
    Constraint: B>0.0.
  • The value of A and/or B is invalid for Gauss-Laguerre quadrature.
    On entry, KEY=value.
    On entry, A=value and B=value.
    Constraint: B>0.0.
  • The value of A and/or B is invalid for rational Gauss quadrature.
    On entry, KEY=value.
    On entry, A=value and B=value.
    Constraint: A+B>0.0.
IFAIL=14
On entry, N=value.
Constraint: N>0.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

The weights and abscissae are stored for standard values of A and B to full machine accuracy.

8 Parallelism and Performance

D01TBF is not threaded in any implementation.

9 Further Comments

Timing is negligible.

10 Example

This example returns the abscissae and (adjusted) weights for the six-point Gauss–Laguerre formula.

10.1 Program Text

Program Text (d01tbfe.f90)

10.2 Program Data

None.

10.3 Program Results

Program Results (d01tbfe.r)

D01 Chapter Contents
D01 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


D01TDF : NAG Library, Mark 26

D01 Chapter Contents
D01 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

D01TDF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

D01TDF computes the weights and abscissae of a Gaussian quadrature rule using the method of Golub and Welsch.

2 Specification

SUBROUTINE D01TDF ( N, A, B, C, MUZERO, WEIGHT, ABSCIS, IFAIL)
INTEGER | N, IFAIL
REAL (KIND=nag_wp) | A(N), B(N), C(N), MUZERO, WEIGHT(N), ABSCIS(N)

3 Description

A tri-diagonal system of equations is formed from the coefficients of an underlying three-term recurrence formula:
p jx=a j x+b j p j-1x-c j p j-2x
for a set of othogonal polynomials p j induced by the quadrature. This is described in greater detail in the D01 Chapter Introduction. The user is required to specify the three-term recurrence and the value of the integral of the chosen weight function over the chosen interval.
As described in Golub and Welsch (1969) the abscissae are computed from the eigenvalues of this matrix and the weights from the first component of the eigenvectors.
LAPACK routines are used for the linear algebra to speed up computation.

4 References

Golub G H and Welsch J H (1969) Calculation of Gauss quadrature rules Math. Comput. 23 221–230

5 Arguments

1:   N – INTEGERInput
On entry: n, the number of Gauss points required. The resulting quadrature rule will be exact for all polynomials of degree 2 n-1.
Constraint: N>0.
2:   A N – REAL (KIND=nag_wp) arrayInput
On entry: A contains the coefficients a j.
3:   B N – REAL (KIND=nag_wp) arrayInput/Output
On entry: B contains the coefficients b j.
On exit: elements of B are altered to make the underlying eigenvalue problem symmetric.
4:   C N – REAL (KIND=nag_wp) arrayInput/Output
On entry: C contains the coefficients c j.
On exit: elements of C are altered to make the underlying eigenvalue problem symmetric.
5:   MUZERO – REAL (KIND=nag_wp)Input
On entry: MUZERO contains the definite integral of the weight function for the interval of interest.
6:   WEIGHT N – REAL (KIND=nag_wp) arrayOutput
On exit: WEIGHT j contains the weight corresponding to the jth abscissa.
7:   ABSCIS N – REAL (KIND=nag_wp) arrayOutput
On exit: ABSCIS j the jth abscissa.
8:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
The number of weights and abscissae requested (N) is less than 1: N=value.
IFAIL=4
Unexpected failure in eigenvalue computation. Please contact NAG.
IFAIL=5
The algorithm failed to converge. The ith diagonal was not zero: i=value.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

In general the computed weights and abscissae are accurate to a reasonable multiple of machine precision.

8 Parallelism and Performance

D01TDF is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
D01TDF makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The weight function must be non-negative to obtain sensible results. This and the validity of MUZERO are not something that the routine can check, so please be particularly careful. If possible check the computed weights and abscissae by integrating a function with a function for which you already know the integral.

10 Example

This example program generates the weights and abscissae for the 4-point Gauss rules: Legendre, Chebyshev1, Chebyshev2, Jacobi, Laguerre and Hermite.

10.1 Program Text

Program Text (d01tdfe.f90)

10.2 Program Data

None.

10.3 Program Results

Program Results (d01tdfe.r)

D01 Chapter Contents
D01 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


D01TEF : NAG Library, Mark 26

D01 Chapter Contents
D01 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

D01TEF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

Given the 2 n+l moments of the weight function, D01TEF generates the recursion coefficients needed by D01TDF to calculate a Gaussian quadrature rule.

2 Specification

SUBROUTINE D01TEF ( N, MU, A, B, C, IFAIL)
INTEGER | N, IFAIL
REAL (KIND=nag_wp) | MU(0:2*N), A(N), B(N), C(N)

3 Description

D01TEF should only be used if the three-term recurrence cannot be determined analytically. A system of equations are formed, using the moments provided. This set of equations becomes ill-conditioned for moderate values of n, the number of abscissae and weights required. In most implementations quadruple precision calculation is used to maintain as much accuracy as possible.

4 References

Golub G H and Welsch J H (1969) Calculation of Gauss quadrature rules Math. Comput. 23 221–230

5 Arguments

1:   N – INTEGERInput
On entry: n, the number of weights and abscissae required.
Constraint: N>0.
2:   MU 0:2*N – REAL (KIND=nag_wp) arrayInput
On entry: MU i must contain the value of the moment with respect to xi i.e., ∫w x xi dx, for i=0,1,…,2 n.
3:   A N – REAL (KIND=nag_wp) arrayOutput
On exit: values helping define the three term recurrence used by D01TDF.
4:   B N – REAL (KIND=nag_wp) arrayOutput
On exit: values helping define the three term recurrence used by D01TDF.
5:   C N – REAL (KIND=nag_wp) arrayOutput
On exit: values helping define the three term recurrence used by D01TDF.
6:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
The number of weights and abscissae requested (N) is less than 1: N=value.
IFAIL=2
The problem is too ill conditioned, it breaks down at row value.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

Internally quadruple precision is used to minimize loss of accuracy as much as possible.

8 Parallelism and Performance

D01TEF is not threaded in any implementation.

9 Further Comments

Because the routine cannot check the validity of all the data presented, the user is advised to independently check the result, perhaps by integrating a function whose integral is known, using D01TEF and subsequently D01TDF, to compare answers.

10 Example

This example program uses D01TEF and moments to calculate a three-term recurrence relationship appropriate for Gauss–Legendre quadrature. It then uses the recurrence relationship to derive the weights and abscissae by calling D01TDF.

10.1 Program Text

Program Text (d01tefe.f90)

10.2 Program Data

None.

10.3 Program Results

Program Results (d01tefe.r)

D01 Chapter Contents
D01 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


D01UAF : NAG Library, Mark 26

D01 Chapter Contents
D01 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

D01UAF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
▸▿ 3 Description
3.1 General
3.2 Both Limits Finite
3.3 One Limit Infinite
3.4 Both Limits Infinite
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

D01UAF computes an estimate of the definite integral of a function of known analytical form, using a Gaussian quadrature formula with a specified number of abscissae. Formulae are provided for a finite interval (Gauss–Legendre), a semi-infinite interval (Gauss–Laguerre, rational Gauss), and an infinite interval (Gauss–Hermite).

2 Specification

SUBROUTINE D01UAF ( KEY, A, B, N, F, DINEST, IUSER, RUSER, IFAIL)
INTEGER | KEY, N, IUSER(*), IFAIL
REAL (KIND=nag_wp) | A, B, DINEST, RUSER(*)
EXTERNAL | F

3 Description

3.1 General

D01UAF evaluates an estimate of the definite integral of a function f x, over a finite or infinite range, by n-point Gaussian quadrature (see Davis and Rabinowitz (1975), Fröberg (1970), Ralston (1965) or Stroud and Secrest (1966)). The integral is approximated by a summation of the product of a set of weights and a set of function evaluations at a corresponding set of abscissae xi. For adjusted weights, the function values correspond to the values of the integrand f, and hence the sum will be
∑i=1 n wi f xi
where the wi are called the weights, and the xi the abscissae. A selection of values of n is available. (See Section 5.)
Where applicable, normal weights may instead be used, in which case the corresponding weight function ω is factored out of the integrand as f x=ω x g x and hence the sum will be
∑ i=-1 n w-i g x ,
where the normal weights w-i=wi ω xi are computed internally.
D01UAF uses a vectorized F to evaluate the integrand or normalized integrand at a set of abscissae, xi, for i=1,2,…,nx. If adjusted weights are used, the integrand f xi must be evaluated otherwise the normalized integrand g xi must be evaluated.

3.2 Both Limits Finite

∫ab f x dx.
The Gauss–Legendre weights and abscissae are used, and the formula is exact for any function of the form:
f x=∑i= 0 2 n- 1 ci xi.
The formula is appropriate for functions which can be well approximated by such a polynomial over a,b. It is inappropriate for functions with algebraic singularities at one or both ends of the interval, such as 1+x-1/2 on -1,1.

3.3 One Limit Infinite

∫a∞f x dx  or  ∫-∞a f x dx.
Two quadrature formulae are available for these integrals.
(a) The Gauss–Laguerre formula is exact for any function of the form:
f x=e-bx ∑i= 0 2 n- 1 ci xi.
This formula is appropriate for functions decaying exponentially at infinity; the argument b should be chosen if possible to match the decay rate of the function.
If the adjusted weights are selected, the complete integrand f x should be provided through F.
If the normal form is selected, the contribution of e-bx is accounted for internally, and F should only return g x, where f x=e-bx g x.
If b<0 is supplied, the interval of integration will be a,∞. Otherwise if b>0 is supplied, the interval of integration will be -∞,a.
(b) The rational Gauss formula is exact for any function of the form:
f x=∑i=2 2 n+1 ci x+b i=∑i=0 2 n-1 c 2 n+1-i x+b i x+b 2 n+1.
This formula is likely to be more accurate for functions having only an inverse power rate of decay for large x. Here the choice of a suitable value of b may be more difficult; unfortunately a poor choice of b can make a large difference to the accuracy of the computed integral.
Only the adjusted form of the rational Gauss formula is available, and as such, the complete integrand f x must be supplied in F.
If a+b<0, the interval of integration will be a,∞. Otherwise if a+b>0, the interval of integration will be -∞,a.

3.4 Both Limits Infinite

∫-∞ +∞f x dx.
The Gauss–Hermite weights and abscissae are used, and the formula is exact for any function of the form:
f x = e - b x-a 2 ∑ i=0 2 n- 1 ci xi ,
where b>0. Again, for general functions not of this exact form, the argument b should be chosen to match if possible the decay rate at ±∞.
If the adjusted weights are selected, the complete integrand f x should be provided through F.
If the normal form is selected, the contribution of e-b x-a 2 is accounted for internally, and F should only return g x, where f x=e-b x-a 2 g x.

4 References

Davis P J and Rabinowitz P (1975) Methods of Numerical Integration Academic Press
Fröberg C E (1970) Introduction to Numerical Analysis Addison–Wesley
Ralston A (1965) A First Course in Numerical Analysis pp. 87–90 McGraw–Hill
Stroud A H and Secrest D (1966) Gaussian Quadrature Formulas Prentice–Hall

5 Arguments

1:   KEY – INTEGERInput
On entry: indicates the quadrature formula.
KEY=0
Gauss–Legendre quadrature on a finite interval, using normal weights.
KEY=3
Gauss–Laguerre quadrature on a semi-infinite interval, using normal weights.
KEY=-3
Gauss–Laguerre quadrature on a semi-infinite interval, using adjusted weights.
KEY=4
Gauss–Hermite quadrature on an infinite interval, using normal weights.
KEY=-4
Gauss–Hermite quadrature on an infinite interval, using adjusted weights.
KEY=-5
Rational Gauss quadrature on a semi-infinite interval, using adjusted weights.
Constraint: KEY=0, 3, -3, 4, -4 or -5.
2:   A – REAL (KIND=nag_wp)Input
3:   B – REAL (KIND=nag_wp)Input
On entry: the quantities a and b as described in the appropriate subsection of Section 3.
Constraints:
  • Rational Gauss: A+B≠0.0;
  • Gauss–Laguerre: B≠0.0;
  • Gauss–Hermite: B>0.
4:   N – INTEGERInput
On entry: n, the number of abscissae to be used.
Constraint: N=1, 2, 3, 4, 5, 6, 8, 10, 12, 14, 16, 20, 24, 32, 48 or 64.
If the soft fail option is used, the answer is evaluated for the largest valid value of N less than the requested value.
5:   F – SUBROUTINE, supplied by the user.External Procedure
F must return the value of the integrand f, or the normalized integrand g, at a specified point.
The specification of F is:
SUBROUTINE F ( X, NX, FV, IFLAG, IUSER, RUSER)
INTEGER | NX, IFLAG, IUSER(*)
REAL (KIND=nag_wp) | X(NX), FV(NX), RUSER(*)
1:   X NX – REAL (KIND=nag_wp) arrayInput
On entry: the abscissae, xi, for i=1,2,…,nx at which function values are required.
2:   NX – INTEGERInput
On entry: nx, the number of abscissae.
3:   FV NX – REAL (KIND=nag_wp) arrayOutput
On exit: if adjusted weights are used, the values of the integrand f. FV i=f xi, for i=1,2,…,nx.
Otherwise the values of the normalized integrand g. FV i=g xi, for i=1,2,…,nx.
4:   IFLAG – INTEGERInput/Output
On entry: IFLAG=0.
On exit: set IFLAG<0 if you wish to force an immediate exit from D01UAF with IFAIL=-1.
5:   IUSER* – INTEGER arrayUser Workspace
6:   RUSER* – REAL (KIND=nag_wp) arrayUser Workspace
F is called with the arguments IUSER and RUSER as supplied to D01UAF. You are free to use the arrays IUSER and RUSER to supply information to F as an alternative to using COMMON global variables.
F must either be a module subprogram USEd by, or declared as EXTERNAL in, the (sub)program from which D01UAF is called. Arguments denoted as Input must not be changed by this procedure.
Some points to bear in mind when coding F are mentioned in Section 7.
6:   DINEST – REAL (KIND=nag_wp)Output
On exit: the estimate of the definite integral.
7:   IUSER* – INTEGER arrayUser Workspace
8:   RUSER* – REAL (KIND=nag_wp) arrayUser Workspace
IUSER and RUSER are not used by D01UAF, but are passed directly to F and may be used to pass information to this routine as an alternative to using COMMON global variables.
9:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, because for this routine the values of the output arguments may be useful even if IFAIL≠0 on exit, the recommended value is -1. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Note: D01UAF may return useful information for one or more of the following detected errors or warnings.
Errors or warnings detected by the routine:
IFAIL=1
The n-point rule is not among those stored.
On entry: N=value.
n-point rule used: N=value.
IFAIL=2
Underflow occurred in calculation of normal weights.
Reduce N or use adjusted weights: N=value.
IFAIL=3
No nonzero weights were generated for the provided parameters.
IFAIL=11
On entry, KEY=value.
Constraint: KEY=0, 3, -3, 4, -4 or -5.
IFAIL=12
The value of A and/or B is invalid for the chosen KEY. Either:
  • The value of A and/or B is invalid.
    On entry, KEY=value.
    On entry, A=value and B=value.
    Constraint: A+B>0.0.
  • The value of A and/or B is invalid.
    On entry, KEY=value.
    On entry, A=value and B=value.
    Constraint: B>0.0.
  • The value of A and/or B is invalid.
    On entry, KEY=value.
    On entry, A=value and B=value.
    Constraint: B>0.0.
IFAIL=14
On entry, N=value.
Constraint: N>0.
IFAIL=-1
Exit requested from F with IFLAG=value.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

The accuracy depends on the behaviour of the integrand, and on the number of abscissae used. No tests are carried out in D01UAF to estimate the accuracy of the result. If such an estimate is required, the routine may be called more than once, with a different number of abscissae each time, and the answers compared. It is to be expected that for sufficiently smooth functions a larger number of abscissae will give improved accuracy.
Alternatively, the range of integration may be subdivided, the integral estimated separately for each sub-interval, and the sum of these estimates compared with the estimate over the whole range.
The coding of F may also have a bearing on the accuracy. For example, if a high-order Gauss–Laguerre formula is used, and the integrand is of the form
f x=e-bx g x
it is possible that the exponential term may underflow for some large abscissae. Depending on the machine, this may produce an error, or simply be assumed to be zero. In any case, it would be better to evaluate the expression with
f x = sgn g x × exp -bx+ ln g x
Another situation requiring care is exemplified by
∫-∞ +∞e-x 2xm dx=0,  m​ odd.
The integrand here assumes very large values; for example, when m=63, the peak value exceeds 3×1033. Now, if the machine holds floating-point numbers to an accuracy of k significant decimal digits, we could not expect such terms to cancel in the summation leaving an answer of much less than 10 33-k (the weights being of order unity); that is, instead of zero we obtain a rather large answer through rounding error. Such situations are characterised by great variability in the answers returned by formulae with different values of n.
In general, you should be aware of the order of magnitude of the integrand, and should judge the answer in that light.

8 Parallelism and Performance

D01UAF is currently neither directly nor indirectly threaded. In particular, the user-supplied argument F is not called from within a parallel region initialized inside D01UAF.
The user-supplied argument F uses a vectorized interface, allowing for the required vector of function values to be evaluated in parallel; for example by placing appropriate OpenMP directives in the code for the user-supplied argument F.

9 Further Comments

The time taken by D01UAF depends on the complexity of the expression for the integrand and on the number of abscissae required.

10 Example

This example evaluates the integrals
∫01 4 1+x 2 dx=π
by Gauss–Legendre quadrature;
∫2∞ 1 x 2 ln⁡x dx =0.378671
by rational Gauss quadrature with b=0;
∫2∞e-x x dx=0.048901
by Gauss–Laguerre quadrature with b=1; and
∫-∞ +∞e-3⁢x 2-4 x-1 dx=∫-∞ +∞e-3⁢ x+1 2e 2 x+2 dx=1.428167
by Gauss–Hermite quadrature with a=-1 and b=3.
The formulae with n=2,4,8,16,32 and 64 are used in each case. Both adjusted and normal weights are used for Gauss–Laguerre and Gauss–Hermite quadrature.

10.1 Program Text

Program Text (d01uafe.f90)

10.2 Program Data

None.

10.3 Program Results

Program Results (d01uafe.r)

D01 Chapter Contents
D01 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


D01UBF : NAG Library, Mark 26

D01 Chapter Contents
D01 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

D01UBF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

D01UBF returns the Gaussian quadrature approximation for the specific problem ∫0∞exp-x 2 f x dx. The degrees of precision catered for are: 1, 3, 5, 7, 9, 19, 29, 39 and 49, corresponding to values of n=1, 2, 3, 4, 5, 10, 15, 20 and 25, where n is the number of weights.

2 Specification

SUBROUTINE D01UBF ( FUN, N, ANS, IUSER, RUSER, IFAIL)
INTEGER | N, IUSER(*), IFAIL
REAL (KIND=nag_wp) | ANS, RUSER(*)
EXTERNAL | FUN

3 Description

D01UBF uses the weights wi and the abscissae xi such that ∫0∞exp-x 2 f x is approximated by ∑ i=1 n wi f xi to maximum precision i.e., it is exact when f x is a polynomial of degree 2 n-1.

4 References

Golub G H and Welsch J H (1969) Calculation of Gauss quadrature rules Math. Comput. 23 221–230

5 Arguments

1:   FUN – SUBROUTINE, supplied by the user.External Procedure
FUN must return the integrands f xi in F i for each xi in X i, for i=1,2,…,N at a given point.
The specification of FUN is:
SUBROUTINE FUN ( X, F, N, IUSER, RUSER, ISTOP)
INTEGER | N, IUSER(*), ISTOP
REAL (KIND=nag_wp) | X(N), F(N), RUSER(*)
1:   X N – REAL (KIND=nag_wp) arrayInput
On entry: the points at which the integrand function f must be evaluated.
2:   F N – REAL (KIND=nag_wp) arrayOutput
On exit: F i must contain the value of the integrand f xi evaluated at the point X i, for i=1,2,…,N.
3:   N – INTEGERInput
On entry: N specifies the number of weights and abscissae to be used.
4:   IUSER* – INTEGER arrayUser Workspace
5:   RUSER* – REAL (KIND=nag_wp) arrayUser Workspace
FUN is called with the arguments IUSER and RUSER as supplied to D01UBF. You are free to use the arrays IUSER and RUSER to supply information to FUN as an alternative to using COMMON global variables.
6:   ISTOP – INTEGERInput/Output
On entry: ISTOP=0.
On exit: you may set ISTOP to a negative number if at any time it is impossible to evaluate the function f x. In this case D01UBF halts with IFAIL set to the value of ISTOP and the value returned in ANS will be that of a non-signalling NaN.
FUN must either be a module subprogram USEd by, or declared as EXTERNAL in, the (sub)program from which D01UBF is called. Arguments denoted as Input must not be changed by this procedure.
2:   N – INTEGERInput
On entry: N specifies the number of weights and abscissae to be used.
Constraint: N=1, 2, 3, 4, 5, 10, 15, 20 or 25.
3:   ANS – REAL (KIND=nag_wp)Output
On exit: if IFAIL=0, ANS contains an approximation to the integral. Otherwise, ANS will be a non-signalling NaN.
4:   IUSER* – INTEGER arrayUser Workspace
5:   RUSER* – REAL (KIND=nag_wp) arrayUser Workspace
IUSER and RUSER are not used by D01UBF, but are passed directly to FUN and may be used to pass information to this routine as an alternative to using COMMON global variables.
6:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL<0
The user has halted the calculation.
IFAIL=1
On entry, N=value.
Constraint: 1≤N≤25.
IFAIL=2
On entry, N=value.
N is not one of the allowed values.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

The weights and abscissae have been calculated using quadruple precision arithmetic.

8 Parallelism and Performance

D01UBF is not threaded in any implementation.

9 Further Comments

None.

10 Example

This example computes an approximation to ∫0∞exp-x 2 x dx.

10.1 Program Text

Program Text (d01ubfe.f90)

10.2 Program Data

None.

10.3 Program Results

Program Results (d01ubfe.r)

D01 Chapter Contents
D01 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


D01ZKF : NAG Library, Mark 26

D01 Chapter Contents
D01 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

D01ZKF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
10 Example

1 Purpose

D01ZKF either initializes or resets the optional parameter arrays or sets a single optional parameter for supported problem solving routines in Chapter D01.

2 Specification

SUBROUTINE D01ZKF ( OPTSTR, IOPTS, LIOPTS, OPTS, LOPTS, IFAIL)
INTEGER | IOPTS(LIOPTS), LIOPTS, LOPTS, IFAIL
REAL (KIND=nag_wp) | OPTS(LOPTS)
CHARACTER(*) | OPTSTR

3 Description

D01ZKF has three purposes: to initialize optional parameter arrays; to reset all optional parameters to their default values; or to set a single optional parameter to a user-supplied value.
Optional parameters and their values are, in general, presented as a character string, OPTSTR, of the form ‘option =optval’; alphabetic characters can be supplied in either upper or lower case. Both option and optval may consist of one or more tokens separated by white space. The tokens that comprise optval will normally be either an integer, real or character value as defined in the description of the specific optional argument. In addition all optional parameters can take an optval DEFAULT which resets the optional parameter to its default value.
It is imperative that optional parameter arrays are initialized before any options are set, before the relevant problem solving routine is called and before any options are queried using D01ZLF. To initialize the optional parameter arrays IOPTS and OPTS for a specific problem solving routine, the option Initialize is used with optval identifying the problem solving routine to be called, via its short name. For example, to initialize the optional parameter arrays to be passed to D01RAF and its associated routine D01RCF, D01ZKF is called as follows:
call D01ZKF('Initialize = d01raf', IOPTS, LIOPTS, OPTS, LOPTS, IFAIL)
The available option names and their corresponding valid values are given in Section 11 in D01ESF and D01RAF.

4 References

None.

5 Arguments

1:   OPTSTR – CHARACTER(*)Input
On entry: a string identifying the option to be set.
Initialize=routine name
Initialize the optional parameter arrays IOPTS and OPTS for use with routine routine name, where routine name is the short name associated with the routine of interest.
Defaults
Resets all options to their default values.
option=optval
See Section 11 in D01ESF and D01RAF for details of valid values for option and optval. The equals sign (=) delimiter must be used to separate the option from its optval value.
OPTSTR is case insensitive. Each token in the option and optval component must be separated by at least one space.
2:   IOPTS LIOPTS – INTEGER arrayCommunication Array
On entry: optional parameter array.
If OPTSTR has the form Initialize=routine name, the contents of IOPTS need not be set.
Otherwise, IOPTS must not have been altered since the last call to D01ZKF, D01ZLF or the selected problem solving routine.
On exit: dependent on the contents of OPTSTR, either an initialized, reset or updated version of the optional parameter array.
3:   LIOPTS – INTEGERInput
On entry: the length of the array IOPTS.
Constraint: unless otherwise stated in the documentation for a specific, supported, problem solving routine, LIOPTS≥100.
4:   OPTS LOPTS – REAL (KIND=nag_wp) arrayCommunication Array
On entry: optional parameter array.
If OPTSTR has the form Initialize=routine name, the contents of OPTS need not be set.
Otherwise, OPTS must not have been altered since the last call to D01ZKF, D01ZLF or the selected problem solving routine.
On exit: dependent on the contents of OPTSTR, either an initialized, reset or updated version of the optional parameter array.
5:   LOPTS – INTEGERInput
On entry: the length of the array OPTS.
Constraint: unless otherwise stated in the documentation for a specific, supported, problem solving routine, LOPTS≥100.
6:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=11
On entry, the optional parameter in OPTSTR was not recognized: OPTSTR=value.
IFAIL=12
On entry, the expected delimiter ‘=’ was not found in OPTSTR: OPTSTR=value.
IFAIL=13
On entry, could not convert the specified optval to an integer: OPTSTR=value.
On entry, could not convert the specified optval to a real: OPTSTR=value.
IFAIL=14
On entry, attempting to initialize the optional parameter arrays but specified routine name was not valid: name=value.
IFAIL=15
On entry, the optval supplied for the integer optional parameter is not valid.
OPTSTR=value.
IFAIL=16
On entry, the optval supplied for the real optional parameter is not valid.
OPTSTR=value.
IFAIL=17
On entry, the optval supplied for the character optional parameter is not valid.
OPTSTR=value.
IFAIL=21
On entry, either the option arrays have not been initialized or they have been corrupted.
IFAIL=31
On entry, LIOPTS=value.
Constraint: LIOPTS≥value.
IFAIL=51
On entry, LOPTS=value.
Constraint: LOPTS≥value.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

Not applicable.

8 Parallelism and Performance

D01ZKF is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

For suites of routines that share the same option arrays, the option arrays must be initialized using the primary (driver) routine name. For example for routines D01RAF and D01RCF, the option arrays must be initialized for D01RAF.
When encoding integer valued options in OPTSTR, the integer optval must be written as an explicit integer. For example, "Maximum Subdivisions = 12" is acceptable, whereas "Maximum Subdivisions = 12.0" and "Maximum Subdivisions = 0.12E2" are not.
When encoding real valued options in OPTSTR, the optval may be integral if appropriate. For example, "Absolute Tolerance = 10", "Absolute Tolerance = 10.0" and "Absolute Tolerance = 1.0E1" are all acceptable.

10 Example

See the example programs associated with the problem solving routine you wish to use for a demonstration of how to use D01ZKF to initialize option arrays and set options.
D01 Chapter Contents
D01 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


D01ZLF : NAG Library, Mark 26

D01 Chapter Contents
D01 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

D01ZLF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
10 Example

1 Purpose

D01ZLF is used to query the current value associated with an optional parameter for D01ESF and D01RAF.

2 Specification

SUBROUTINE D01ZLF ( OPTSTR, IVALUE, RVALUE, CVALUE, OPTYPE, IOPTS, OPTS, IFAIL)
INTEGER | IVALUE, OPTYPE, IOPTS(*), IFAIL
REAL (KIND=nag_wp) | RVALUE, OPTS(*)
CHARACTER(*) | OPTSTR, CVALUE

3 Description

D01ZLF is used to query the current value associated with optional parameters. It is necessary to initialize optional parameter arrays, IOPTS and OPTS, using D01ZKF before any optional parameters are queried.
D01ZLF will normally return either an integer, real or character value dependent upon the type associated with the optional parameter being queried. Some real and integer optional parameters also return additional information in CVALUE. Whether the optional parameter queried is of integer, real or character type, and whether additional information is returned in CVALUE, is indicated by the returned value of OPTYPE.
Information on optional parameter names and whether these options are real, integer or character can be found in Section 11 in D01ESF and D01RAF.

4 References

None.

5 Arguments

1:   OPTSTR – CHARACTER(*)Input
On entry: a string identifying the option whose current value is required. See Section 11 in D01ESF and D01RAF for information on valid optional parameters. In addition, the following is a valid option:
Identify
In which case D01ZLF returns in CVALUE the 6 character routine name supplied to D01ZKF when the optional parameter arrays IOPTS and OPTS were initialized.
2:   IVALUE – INTEGEROutput
On exit: if the optional parameter supplied in OPTSTR is an integer valued argument, IVALUE will hold that value.
3:   RVALUE – REAL (KIND=nag_wp)Output
On exit: if the optional parameter supplied in OPTSTR is a real valued argument, RVALUE will hold that value.
4:   CVALUE – CHARACTER(*)Output
Note: the string returned in CVALUE will never exceed 40 characters in length.
On exit: if the optional parameter supplied in OPTSTR is a character valued argument, CVALUE will hold that value. CVALUE will also contain additional information for some integer and real valued arguments, as indicated by OPTYPE.
5:   OPTYPE – INTEGEROutput
On exit: indicates whether the optional parameter supplied in OPTSTR is an integer, real or character valued argument and hence which of IVALUE, RVALUE or CVALUE holds the current value.
OPTYPE=1
OPTSTR is an integer valued optional parameter; its current value has been returned in IVALUE.
OPTYPE=2
OPTSTR is a real valued optional parameter; its current value has been returned in RVALUE.
OPTYPE=3
OPTSTR is a character valued optional parameter; its current value has been returned in CVALUE.
OPTYPE=4
OPTSTR is an integer valued optional parameter; its current value has been returned in IVALUE. Additional information has been returned in CVALUE.
OPTYPE=5
OPTSTR is a real valued optional parameter; its current value has been returned in RVALUE. Additional information has been returned in CVALUE.
6:   IOPTS* – INTEGER arrayCommunication Array
Note: the dimension of this array is dictated by the requirements of associated functions that must have been previously called. This array must be the same array passed as argument IOPTS in the previous call to D01ZKF.
7:   OPTS* – REAL (KIND=nag_wp) arrayCommunication Array
Note: the dimension of this array is dictated by the requirements of associated functions that must have been previously called. This array must be the same array passed as argument OPTS in the previous call to D01ZKF.
8:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=11
On entry, the optional parameter in OPTSTR was not recognized: OPTSTR=value.
IFAIL=41
On entry, OPTSTR indicates a character optional parameter, but CVALUE is too short to hold the stored value. The returned value will be truncated.
IFAIL=61
The arrays IOPTS and OPTS have either not been initialized, have become corrupted, or are not compatible with this option setting routine.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

Not applicable.

8 Parallelism and Performance

D01ZLF is not threaded in any implementation.

9 Further Comments

None.

10 Example

See the example programs associated with the problem solving routine you wish to use for a demonstration of how to use D01ZLF.
D01 Chapter Contents
D01 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


D02AGF : NAG Library, Mark 26

D02 Chapter Contents
D02 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

D02AGF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

D02AGF solves a two-point boundary value problem for a system of ordinary differential equations, using initial value techniques and Newton iteration; it generalizes D02HAF to include the case where parameters other than boundary values are to be determined.

2 Specification

SUBROUTINE D02AGF ( H, E, PARERR, PARAM, C, N, N1, M1, AUX, BCAUX, RAAUX, PRSOL, MAT, COPY, WSPACE, WSPAC1, WSPAC2, IFAIL)
INTEGER | N, N1, M1, IFAIL
REAL (KIND=nag_wp) | H, E(N), PARERR(N1), PARAM(N1), C(M1,N), MAT(N1,N1), COPY(1,1), WSPACE(N,9), WSPAC1(N), WSPAC2(N)
EXTERNAL | AUX, BCAUX, RAAUX, PRSOL

3 Description

D02AGF solves a two-point boundary value problem by determining the unknown parameters p 1,p 2,…,p n 1 of the problem. These parameters may be, but need not be, boundary values (as they are in D02HAF); they may include eigenvalue parameters in the coefficients of the differential equations, length of the range of integration, etc. The notation and methods used are similar to those of D02HAF and you are advised to study this first. (There the parameters p 1,p 2,…,p n 1 correspond to the unknown boundary conditions.) It is assumed that we have a system of n first-order ordinary differential equations of the form
d yi dx =fi x,y 1,y 2,…,yn,  i=1,2,…,n,
and that derivatives fi are evaluated by AUX. The system, including the boundary conditions given by BCAUX, and the range of integration and matching point, r, given by RAAUX, involves the n 1 unknown parameters p 1,p 2,…,p n 1 which are to be determined, and for which initial estimates must be supplied. The number of unknown parameters n 1 must not exceed the number of equations n. If n 1<n, we assume that n-n 1 equations of the system are not involved in the matching process. These are usually referred to as ‘driving equations’; they are independent of the parameters and of the solutions of the other n 1 equations. In numbering the equations for AUX, the driving equations must be put last.
The estimated values of the parameters are corrected by a form of Newton iteration. The Newton correction on each iteration is calculated using a matrix whose i,jth element depends on the derivative of the ith component of the solution, yi, with respect to the jth parameter, pj. This matrix is calculated by a simple numerical differentiation technique which requires n 1 evaluations of the differential system.

4 References

None.

5 Arguments

You are strongly recommended to read Sections 3 and 9 in conjunction with this section.
1:   H – REAL (KIND=nag_wp)Input/Output
On entry: H must be set to an estimate of the step size, h, needed for integration.
On exit: the last step length used.
2:   E N – REAL (KIND=nag_wp) arrayInput
On entry: E i must be set to a small quantity to control the ith solution component. The element E i is used:
(i) | in the bound on the local error in the ith component of the solution yi during integration,
(ii) | in the convergence test on the ith component of the solution yi at the matching point in the Newton iteration.
The elements E i should not be chosen too small. They should usually be several orders of magnitude larger than machine precision.
3:   PARERR N1 – REAL (KIND=nag_wp) arrayInput
On entry: PARERR i must be set to a small quantity to control the ith parameter component. The element PARERR i is used:
(i) | in the convergence test on the ith parameter in the Newton iteration,
(ii) | in perturbing the ith parameter when approximating the derivatives of the components of the solution with respect to the ith parameter, for use in the Newton iteration.
The elements PARERR i should not be chosen too small. They should usually be several orders of magnitude larger than machine precision.
4:   PARAM N1 – REAL (KIND=nag_wp) arrayInput/Output
On entry: PARAM i must be set to an estimate for the ith parameter, pi, for i=1,2,…,N1.
On exit: the corrected value for the ith parameter, unless an error has occurred, when it contains the last calculated value of the parameter (possibly perturbed by PARERR i×1+PARAM i if the error occurred when calculating the approximate derivatives).
5:   C M1N – REAL (KIND=nag_wp) arrayOutput
On exit: the solution when M1>1 (see M1).
If M1=1, the elements of C are not used.
6:   N – INTEGERInput
On entry: n, the total number of differential equations.
7:   N1 – INTEGERInput
On entry: n 1, the number of parameters.
If N1<N, the last N-N1 differential equations (in AUX) are driving equations (see Section 3).
Constraint: N1≤N.
8:   M1 – INTEGERInput
On entry: determines whether or not the final solution is computed as well as the parameter values.
M1=1
The final solution is not calculated;
M1>1
The final values of the solution at interval (length of range)/M1-1 are calculated and stored sequentially in the array C starting with the values of yi evaluated at the first end point (see RAAUX) stored in C 1 i.
9:   AUX – SUBROUTINE, supplied by the user.External Procedure
AUX must evaluate the functions fi (i.e., the derivatives yi′) for given values of its arguments, x,y 1,…,yn, p 1,…,p n 1.
The specification of AUX is:
SUBROUTINE AUX ( F, Y, X, PARAM)
REAL (KIND=nag_wp) F(*), Y(*), X, PARAM(*)
In the description of the arguments of D02AGF below, n and n1 denote the numerical values of N and N1 in the call of D02AGF.
1:   F* – REAL (KIND=nag_wp) arrayOutput
On exit: the value of fi, for i=1,2,…,n.
2:   Y* – REAL (KIND=nag_wp) arrayInput
On entry: yi, for i=1,2,…,n, the value of the argument.
3:   X – REAL (KIND=nag_wp)Input
On entry: x, the value of the argument.
4:   PARAM* – REAL (KIND=nag_wp) arrayInput
On entry: pi, for i=1,2,…,n 1, the value of the parameters.
AUX must either be a module subprogram USEd by, or declared as EXTERNAL in, the (sub)program from which D02AGF is called. Arguments denoted as Input must not be changed by this procedure.
10:   BCAUX – SUBROUTINE, supplied by the user.External Procedure
BCAUX must evaluate the values of yi at the end points of the range given the values of p 1,…,p n 1.
The specification of BCAUX is:
SUBROUTINE BCAUX ( G0, G1, PARAM)
REAL (KIND=nag_wp) G0(*), G1(*), PARAM(*)
In the description of the arguments of D02AGF below, n and n1 denote the numerical values of N and N1 in the call of D02AGF.
1:   G0* – REAL (KIND=nag_wp) arrayOutput
On exit: the values yi, for i=1,2,…,n, at the boundary point x 0 (see RAAUX).
2:   G1* – REAL (KIND=nag_wp) arrayOutput
On exit: the values yi, for i=1,2,…,n, at the boundary point x 1 (see RAAUX).
3:   PARAM* – REAL (KIND=nag_wp) arrayInput
On entry: pi, for i=1,2,…,n, the value of the parameters.
BCAUX must either be a module subprogram USEd by, or declared as EXTERNAL in, the (sub)program from which D02AGF is called. Arguments denoted as Input must not be changed by this procedure.
11:   RAAUX – SUBROUTINE, supplied by the user.External Procedure
RAAUX must evaluate the end points, x 0 and x 1, of the range and the matching point, r, given the values p 1,p 2,…,p n 1.
The specification of RAAUX is:
SUBROUTINE RAAUX ( X0, X1, R, PARAM)
REAL (KIND=nag_wp) X0, X1, R, PARAM(*)
In the description of the arguments of D02AGF below, n1 denotes the numerical value of N1 in the call of D02AGF.
1:   X0 – REAL (KIND=nag_wp)Output
On exit: must contain the left-hand end of the range, x 0.
2:   X1 – REAL (KIND=nag_wp)Output
On exit: must contain the right-hand end of the range x 1.
3:   R – REAL (KIND=nag_wp)Output
On exit: must contain the matching point, r.
4:   PARAM* – REAL (KIND=nag_wp) arrayInput
On entry: pi, for i=1,2,…,n 1, the value of the parameters.
RAAUX must either be a module subprogram USEd by, or declared as EXTERNAL in, the (sub)program from which D02AGF is called. Arguments denoted as Input must not be changed by this procedure.
12:   PRSOL – SUBROUTINE, supplied by the user.External Procedure
PRSOL is called at each iteration of the Newton method and can be used to print the current values of the parameters pi, for i=1,2,…,n 1, their errors, ei, and the sum of squares of the errors at the matching point, r.
The specification of PRSOL is:
SUBROUTINE PRSOL ( PARAM, RES, N1, ERR)
INTEGER | N1
REAL (KIND=nag_wp) | PARAM(N1), RES, ERR(N1)
1:   PARAM N1 – REAL (KIND=nag_wp) arrayInput
On entry: pi, for i=1,2,…,n 1, the current value of the parameters.
2:   RES – REAL (KIND=nag_wp)Input
On entry: the sum of squares of the errors in the arguments, ∑i=1 n 1 ei 2.
3:   N1 – INTEGERInput
On entry: n 1, the number of parameters.
4:   ERR N1 – REAL (KIND=nag_wp) arrayInput
On entry: the errors in the parameters, ei, for i=1,2,…,n 1.
PRSOL must either be a module subprogram USEd by, or declared as EXTERNAL in, the (sub)program from which D02AGF is called. Arguments denoted as Input must not be changed by this procedure.
13:   MAT N1N1 – REAL (KIND=nag_wp) arrayWorkspace
14:   COPY 11 – REAL (KIND=nag_wp) arrayInput
15:   WSPACE N 9 – REAL (KIND=nag_wp) arrayWorkspace
16:   WSPAC1 N – REAL (KIND=nag_wp) arrayWorkspace
17:   WSPAC2 N – REAL (KIND=nag_wp) arrayWorkspace
18:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
This indicates that N1>N on entry, that is the number of parameters is greater than the number of differential equations.
IFAIL=2
As for IFAIL=4 except that the integration failed while calculating the matrix for use in the Newton iteration.
IFAIL=3
The current matching point r does not lie between the current end points x 0 and x 1. If the values x 0, x 1 and r depend on the parameters pi, this may occur at any time in the Newton iteration if care is not taken to avoid it when coding RAAUX.
IFAIL=4
The step length for integration H has halved more than 13 times (or too many steps were needed to reach the end of the range of integration) in attempting to control the local truncation error whilst integrating to obtain the solution corresponding to the current values pi. If, on failure, H has the sign of r-x 0 then failure has occurred whilst integrating from x 0 to r, otherwise it has occurred whilst integrating from x 1 to r.
IFAIL=5
The matrix of the equations to be solved for corrections to the variable parameters in the Newton method is singular (as determined by F07ADF (DGETRF)).
IFAIL=6
A satisfactory correction to the parameters was not obtained on the last Newton iteration employed. A Newton iteration is deemed to be unsatisfactory if the sum of the squares of the residuals (which can be printed using PRSOL) has not been reduced after three iterations using a new Newton correction.
IFAIL=7
Convergence has not been obtained after 12 satisfactory iterations of the Newton method.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.
A further discussion of these errors and the steps which might be taken to correct them is given in Section 9.

7 Accuracy

If the process converges, the accuracy to which the unknown parameters are determined is usually close to that specified by you; and the solution, if requested, is usually determined to the accuracy specified.

8 Parallelism and Performance

D02AGF is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
D02AGF makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The time taken by D02AGF depends on the complexity of the system, and on the number of iterations required. In practice, integration of the differential equations is by far the most costly process involved.
There may be particular difficulty in integrating the differential equations in one direction (indicated by IFAIL=2 or 4). The value of r should be adjusted to avoid such difficulties.
If the matching point r is at one of the end points x 0 or x 1 and some of the parameters are used only to determine the boundary values at this point, then good initial estimates for these parameters are not required, since they are completely determined by the routine (for example, see p 2 in EX1 of Section 10).
Wherever they occur in the procedure, the error parameters contained in the arrays E and PARERR are used in ‘mixed’ form; that is E i always occurs in expressions of the form E i×1+yi, and PARERR i always occurs in expressions of the form PARERR i×1+pi. Though not ideal for every application, it is expected that this mixture of absolute and relative error testing will be adequate for most purposes.
Note that convergence is not guaranteed. You are strongly advised to provide an output PRSOL, as shown in EX1 of Section 10, in order to monitor the progress of the iteration. Failure of the Newton iteration to converge (see IFAIL=6 or 7) usually results from poor starting approximations to the parameters, though occasionally such failures occur because the elements of one or both of the arrays PARERR or E are too small. (It should be possible to distinguish these cases by studying the output from PRSOL.) Poor starting approximations can also result in the failure described under IFAIL=4 and 5 in Section 6 (especially if these errors occur after some Newton iterations have been completed, that is, after two or more calls of PRSOL). More frequently, a singular matrix in the Newton method (monitored as IFAIL=5) occurs because the mathematical problem has been posed incorrectly. The case IFAIL=4 usually occurs because h or r has been poorly estimated, so these values should be checked first. If IFAIL=2 is monitored, the solution y 1,y 2,…,yn is sensitive to perturbations in the parameters pi. Reduce the size of one or more values PARERR i to reduce the perturbations. Since only one value pi is perturbed at any time when forming the matrix, the perturbation which is too large can be located by studying the final output from PRSOL and the values of the parameters returned by D02AGF. If this change leads to other types of failure improve the initial values of pi by other means.
The computing time for integrating the differential equations can sometimes depend critically on the quality of the initial estimates for the parameters pi. If it seems that too much computing time is required and, in particular, if the values ERR i (available on each call of PRSOL) are much larger than the expected values of the solution at the matching point r, then the coding of AUX, BCAUX and RAAUX should be checked for errors. If no errors can be found, an independent attempt should be made to improve the initial estimates for PARAM i.
The subroutine can be used to solve a very wide range of problems, for example:
(a) | eigenvalue problems, including problems where the eigenvalue occurs in the boundary conditions;
(b) | problems where the differential equations depend on some parameters which are to be determined so as to satisfy certain boundary conditions (see EX1 in Section 10);
(c) | problems where one of the end points of the range of integration is to be determined as the point where a variable yi takes a particular value (see EX2 in Section 10);
(d) | singular problems and problems on infinite ranges of integration where the values of the solution at x 0 or x 1 or both are determined by a power series or an asymptotic expansion (or a more complicated expression) and where some of the coefficients in the expression are to be determined (see EX1 in Section 10); and
(e) | differential equations with certain terms defined by other independent (driving) differential equations.

10 Example

For this routine two examples are presented. There is a single example program for D02AGF, with a main program and the code to solve the two example problems given in Example 1 (EX1) and Example 2 (EX2).
Example 1 (EX1)
This example finds the solution of the differential equation
y′′=y 3-y′ 2 x
on the range 0≤x≤16, with boundary conditions y 0=0.1 and y 16=1/6.
We cannot use the differential equation at x=0 because it is singular, so we take the truncated series expansion
y x=110+p 1 x 10+x 100
near the origin (which is correct to the number of terms given in this case). Here p 1 is one of the parameters to be determined. We choose the range as 0.1,16 and setting p 2=y′16, we can determine all the boundary conditions. We take the matching point to be 16, the end of the range, and so a good initial guess for p 2 is not necessary. We write y=Y 1, y′=Y 2, and estimate p 1=PARAM 1=0.2, p 2=PARAM 2=0.0.
Example 2 (EX2)
This example finds the gravitational constant p 1 and the range p 2 over which a projectile must be fired to hit the target with a given velocity. The differential equations are
y′=tan⁡ϕ v′= -p 1 sin⁡ϕ+0.00002⁢v 2 v cos⁡ϕ ϕ′=-p 1 v 2 k
on the range 0<x<p 2 with boundary conditions
y=0, v=500, ϕ=0.5 at x=0 y=0, v=450, ϕ=p 3 at x=p 2.
We write y=Y 1, v=Y 2, ϕ=Y 3, and we take the matching point r=p 2. We estimate p 1=PARAM 1=32, p 2=PARAM 2=6000 and p 3=PARAM 3=0.54 (though this estimate is not important).

10.1 Program Text

Program Text (d02agfe.f90)

10.2 Program Data

Program Data (d02agfe.d)

10.3 Program Results

Program Results (d02agfe.r)

GnuplotProduced by GNUPLOT 4.6 patchlevel 3 0 0.02 0.04 0.06 0.08 0.1 0.12 0.14 0.16 0.18 0 2 4 6 8 10 12 14 16 Solution and Derivative x Example Program 1 Parameterized Two-point Boundary-value Problem solution y(x) derivative y'(x) param(2) gnuplot_plot_1 gnuplot_plot_2
GnuplotProduced by GNUPLOT 4.6 patchlevel 3 0 100 200 300 400 500 600 700 800 900 0 1000 2000 3000 4000 5000 6000 −0.6 −0.4 −0.2 0 0.2 0.4 0.6 Height and Velocity Angle x Example Program 2 Find Gravitational Constant and Range given Projectile Terminal Velocity height velocity angle gnuplot_plot_1 gnuplot_plot_2 gnuplot_plot_3
D02 Chapter Contents
D02 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


D02BGF : NAG Library, Mark 26

D02 Chapter Contents
D02 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

D02BGF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

D02BGF integrates a system of first-order ordinary differential equations over an interval with suitable initial conditions, using a Runge–Kutta–Merson method, until a specified component attains a given value.

2 Specification

SUBROUTINE D02BGF ( X, XEND, N, Y, TOL, HMAX, M, VAL, FCN, W, IFAIL)
INTEGER | N, M, IFAIL
REAL (KIND=nag_wp) | X, XEND, Y(N), TOL, HMAX, VAL, W(N,10)
EXTERNAL | FCN

3 Description

D02BGF advances the solution of a system of ordinary differential equations
yi′=fi x,y 1,y 2,…,yn,  i=1,2,…,n,
from x=X towards x=XEND using a Merson form of the Runge–Kutta method. The system is defined by FCN, which evaluates fi in terms of x and y 1,y 2,…,yn (see Section 5), and the values of y 1,y 2,…,yn must be given at x=X.
As the integration proceeds, a check is made on the specified component ym of the solution to determine an interval where it attains a given value α. The position where this value is attained is then determined accurately by interpolation on the solution and its derivative. It is assumed that the solution of ym=α can be determined by searching for a change in sign in the function ym-α.
The accuracy of the integration and, indirectly, of the determination of the position where ym=α is controlled by the argument TOL.
For a description of Runge–Kutta methods and their practical implementation see Hall and Watt (1976).

4 References

Hall G and Watt J M (ed.) (1976) Modern Numerical Methods for Ordinary Differential Equations Clarendon Press, Oxford

5 Arguments

1:   X – REAL (KIND=nag_wp)Input/Output
On entry: must be set to the initial value of the independent variable x.
On exit: the point where the component ym attains the value α unless an error has occurred, when it contains the value of x at the error. In particular, if ym≠α anywhere on the range x=X to x=XEND, it will contain XEND on exit.
2:   XEND – REAL (KIND=nag_wp)Input
On entry: the final value of the independent variable x.
If XEND<X on entry integration will proceed in the negative direction.
3:   N – INTEGERInput
On entry: n, the number of differential equations.
Constraint: N>0.
4:   Y N – REAL (KIND=nag_wp) arrayInput/Output
On entry: the initial values of the solution y 1,y 2,…,yn.
On exit: the computed values of the solution at a point near the solution X, unless an error has occurred when they contain the computed values at the final value of X.
5:   TOL – REAL (KIND=nag_wp)Input/Output
On entry: must be set to a positive tolerance for controlling the error in the integration and in the determination of the position where ym=α.
D02BGF has been designed so that, for most problems, a reduction in TOL leads to an approximately proportional reduction in the error in the solution obtained in the integration. The relation between changes in TOL and the error in the determination of the position where ym=α is less clear, but for TOL small enough the error should be approximately proportional to TOL. However, the actual relation between TOL and the accuracy cannot be guaranteed. You are strongly recommended to call D02BGF with more than one value for TOL and to compare the results obtained to estimate their accuracy. In the absence of any prior knowledge you might compare results obtained by calling D02BGF with TOL=10.0-p and TOL=10.0-p-1 if p correct decimal digits in the solution are required.
Constraint: TOL>0.0.
On exit: normally unchanged. However if the range from X to the position where ym=α (or to the final value of X if an error occurs) is so short that a small change in TOL is unlikely to make any change in the computed solution then, on return, TOL has its sign changed. To check results returned with TOL<0.0, D02BGF should be called again with a positive value of TOL whose magnitude is considerably smaller than that of the previous call.
6:   HMAX – REAL (KIND=nag_wp)Input
On entry: controls how the sign of ym-α is checked.
HMAX=0.0
ym-α is checked at every internal integration step.
HMAX≠0.0
The computed solution is checked for a change in sign of ym-α at steps of not greater than HMAX. This facility should be used if there is any chance of ‘missing’ the change in sign by checking too infrequently. For example, if two changes of sign of ym-α are expected within a distance h, say, of each other then a suitable value for HMAX might be HMAX=h/2. If only one change of sign in ym-α is expected on the range X to XEND then HMAX=0.0 is most appropriate.
7:   M – INTEGERInput
On entry: the index m of the component of the solution whose value is to be checked.
Constraint: 1≤M≤N.
8:   VAL – REAL (KIND=nag_wp)Input
On entry: the value of α in the equation ym=α to be solved for X.
9:   FCN – SUBROUTINE, supplied by the user.External Procedure
FCN must evaluate the functions fi (i.e., the derivatives yi′) for given values of its arguments x,y 1,…,yn.
The specification of FCN is:
SUBROUTINE FCN ( X, Y, F)
REAL (KIND=nag_wp) X, Y(*), F(*)
In the description of the arguments of D02BGF below, n denotes the actual value of N in the call of D02BGF.
1:   X – REAL (KIND=nag_wp)Input
On entry: x, the value of the argument.
2:   Y* – REAL (KIND=nag_wp) arrayInput
On entry: yi, for i=1,2,…,n, the value of the argument.
3:   F* – REAL (KIND=nag_wp) arrayOutput
On exit: the value of fi, for i=1,2,…,n.
FCN must either be a module subprogram USEd by, or declared as EXTERNAL in, the (sub)program from which D02BGF is called. Arguments denoted as Input must not be changed by this procedure.
10:   W N 10 – REAL (KIND=nag_wp) arrayWorkspace
11:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, | TOL≤0.0,
or | N≤0,
or | M≤0,
or | M>N.
IFAIL=2
With the given value of TOL, no further progress can be made across the integration range from the current point x=X, or dependence of the error on TOL would be lost if further progress across the integration range were attempted (see Section 9 for a discussion of this error exit). The components Y 1,Y 2,…,Y n contain the computed values of the solution at the current point x=X. No point at which ym-α changes sign has been located up to the point x=X.
IFAIL=3
TOL is too small for the routine to take an initial step (see Section 9). X and Y 1,Y 2,…,Y n retain their initial values.
IFAIL=4
At no point in the range X to XEND did the function ym-α change sign. It is assumed that ym-α has no solution.
IFAIL=5 (C05AZF)
A serious error has occurred in an internal call to the specified routine. Check all subroutine calls and array dimensions. Seek expert help.
IFAIL=6
A serious error has occurred in an internal call to an integration routine. Check all subroutine calls and array dimensions. Seek expert help.
IFAIL=7
A serious error has occurred in an internal call to an interpolation routine. Check all (sub)program calls and array dimensions. Seek expert help.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

The accuracy depends on TOL, on the mathematical properties of the differential system, on the position where ym=α and on the method. It can be controlled by varying TOL but the approximate proportionality of the error to TOL holds only for a restricted range of values of TOL. For TOL too large, the underlying theory may break down and the result of varying TOL may be unpredictable. For TOL too small, rounding error may affect the solution significantly and an error exit with IFAIL=2 or 3 is possible.

8 Parallelism and Performance

D02BGF is not threaded in any implementation.

9 Further Comments

The time taken by D02BGF depends on the complexity and mathematical properties of the system of differential equations defined by FCN, on the range, the position of solution and the tolerance. There is also an overhead of the form a+b×n where a and b are machine-dependent computing times.
For some problems it is possible that D02BGF will exit with IFAIL=4 due to inaccuracy of the computed value ym. For example, consider a case where the component ym has a maximum in the integration range and α is close to the maximum value. If TOL is too large, it is possible that the maximum might be estimated as less than α, or even that the integration step length chosen might be so long that the maximum of ym and the (two) positions where ym=α are all in the same step and so the position where ym=α remains undetected. Both these difficulties can be overcome by reducing TOL sufficiently and, if necessary, by choosing HMAX sufficiently small. For similar reasons, care should be taken when choosing XEND. If possible, you should choose XEND well beyond the point where ym is expected to equal α, for example XEND-X should be made about 50% longer than the expected range. As a simple check, if, with XEND fixed, a change in TOL does not lead to a significant change in ym at XEND, then inaccuracy is not a likely source of error.
If D02BGF fails with IFAIL=3, then it could be called again with a larger value of TOL if this has not already been tried. If the accuracy requested is really needed and cannot be obtained with this routine, the system may be very stiff (see below) or so badly scaled that it cannot be solved to the required accuracy.
If D02BGF fails with IFAIL=2, it is likely that it has been called with a value of TOL which is so small that a solution cannot be obtained on the range X to XEND. This can happen for well-behaved systems and very small values of TOL. You should, however, consider whether there is a more fundamental difficulty. For example:
(a) | in the region of a singularity (infinite value) of the solution, the routine will usually stop with IFAIL=2, unless overflow occurs first. If overflow occurs using D02BGF, routine D02PFF can be used instead to detect the increasing solution before overflow occurs. In any case, numerical integration cannot be continued through a singularity, and analytical treatment should be considered;
(b) | for ‘stiff’ equations, where the solution contains rapidly decaying components the routine will use very small steps in x (internally to D02BGF) to preserve stability. This will usually exhibit itself by making the computing time excessively long, or occasionally by an exit with IFAIL=2. Merson's method is not efficient in such cases, and you should try the method D02EJF which uses a Backward Differentiation Formula. To determine whether a problem is stiff, D02PEF may be used.
For well-behaved systems with no difficulties such as stiffness or singularities, the Merson method should work well for low accuracy calculations (three or four figures). For high accuracy calculations or where FCN is costly to evaluate, Merson's method may not be appropriate and a computationally less expensive method may be D02CJF which uses an Adams' method.
For problems for which D02BGF is not sufficiently general, you should consider the routines D02BHF and D02PFF. Routine D02BHF can be used to solve an equation involving the components y 1,y 2,…,yn and their derivatives (for example, to find where a component passes through zero or to find the maximum value of a component). It also permits a more general form of error control and may be preferred to D02BGF if the component whose value is to be determined is very small in modulus on the integration range. D02BHF can always be used in place of D02BGF, but will usually be computationally more expensive for solving the same problem. D02PFF is a more general routine with many facilities including a more general error control criterion. D02PFF can be combined with the root-finder C05AZF and the interpolation routine D02PSF to solve equations involving y 1,y 2,…,yn and their derivatives.
This routine is only intended to be used to locate the first zero of the function ym-α. If later zeros are required you are strongly advised to construct your own more general root-finding routines as discussed above.

10 Example

This example finds the value X>0.0 where y=0.0, where y, v, ϕ, are defined by
y′=tan⁡ϕ v′= -0.032 tan⁡ϕ v- 0.02 v cos⁡ϕ ϕ′= -0.032 v 2
and where at X=0.0 we are given y=0.5, v=0.5 and ϕ=π/5. We write y=Y 1, v=Y 2 and ϕ=Y 3 and we set TOL=1.0E−4 and TOL=1.0E−5 in turn so that we can compare the solutions obtained. We expect the solution X≃7.3 and we set XEND=10.0 so that the point where y=0.0 is not too near the end of the range of integration. The initial values and range are read from a data file.

10.1 Program Text

Program Text (d02bgfe.f90)

10.2 Program Data

Program Data (d02bgfe.d)

10.3 Program Results

Program Results (d02bgfe.r)

D02 Chapter Contents
D02 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


D02BHF : NAG Library, Mark 26

D02 Chapter Contents
D02 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

D02BHF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

D02BHF integrates a system of first-order ordinary differential equations over an interval with suitable initial conditions, using a Runge–Kutta–Merson method, until a user-specified function of the solution is zero.

2 Specification

SUBROUTINE D02BHF ( X, XEND, N, Y, TOL, IRELAB, HMAX, FCN, G, W, IFAIL)
INTEGER | N, IRELAB, IFAIL
REAL (KIND=nag_wp) | X, XEND, Y(N), TOL, HMAX, G, W(N,7)
EXTERNAL | FCN, G

3 Description

D02BHF advances the solution of a system of ordinary differential equations
yi′=fi x,y 1,y 2,…,yn,  i=1,2,…,n,
from x=X towards x=XEND using a Merson form of the Runge–Kutta method. The system is defined by FCN, which evaluates fi in terms of x and y 1,y 2,…,yn (see Section 5), and the values of y 1,y 2,…,yn must be given at x=X.
As the integration proceeds, a check is made on the function g x,y specified by you, to determine an interval where it changes sign. The position of this sign change is then determined accurately by interpolating for the solution and its derivative. It is assumed that g x,y is a continuous function of the variables, so that a solution of g x,y=0 can be determined by searching for a change in sign in g x,y.
The accuracy of the integration and, indirectly, of the determination of the position where g x,y=0, is controlled by TOL.
For a description of Runge–Kutta methods and their practical implementation see Hall and Watt (1976).

4 References

Hall G and Watt J M (ed.) (1976) Modern Numerical Methods for Ordinary Differential Equations Clarendon Press, Oxford

5 Arguments

1:   X – REAL (KIND=nag_wp)Input/Output
On entry: must be set to the initial value of the independent variable x.
On exit: the point where g x,y=0.0 unless an error has occurred, when it contains the value of x at the error. In particular, if g x,y≠0.0 anywhere on the range X to XEND, it will contain XEND on exit.
2:   XEND – REAL (KIND=nag_wp)Input
On entry: the final value of the independent variable x.
If XEND<X on entry, integration proceeds in a negative direction.
3:   N – INTEGERInput
On entry: n, the number of differential equations.
Constraint: N>0.
4:   Y N – REAL (KIND=nag_wp) arrayInput/Output
On entry: the initial values of the solution y 1,y 2,…,yn.
On exit: the computed values of the solution at the final point x=X.
5:   TOL – REAL (KIND=nag_wp)Input/Output
On entry: must be set to a positive tolerance for controlling the error in the integration and in the determination of the position where g x,y=0.0.
D02BHF has been designed so that, for most problems, a reduction in TOL leads to an approximately proportional reduction in the error in the solution obtained in the integration. The relation between changes in TOL and the error in the determination of the position where g x,y=0.0 is less clear, but for TOL small enough the error should be approximately proportional to TOL. However, the actual relation between TOL and the accuracy cannot be guaranteed. You are strongly recommended to call D02BHF with more than one value for TOL and to compare the results obtained to estimate their accuracy. In the absence of any prior knowledge you might compare results obtained by calling D02BHF with TOL=10.0-p and TOL=10.0-p-1 if p correct decimal digits in the solution are required.
Constraint: TOL>0.0.
On exit: normally unchanged. However if the range from x=X to the position where g x,y=0.0 (or to the final value of x if an error occurs) is so short that a small change in TOL is unlikely to make any change in the computed solution, then TOL is returned with its sign changed. To check results returned with TOL<0.0, D02BHF should be called again with a positive value of TOL whose magnitude is considerably smaller than that of the previous call.
6:   IRELAB – INTEGERInput
On entry: determines the type of error control. At each step in the numerical solution an estimate of the local error, est, is made. For the current step to be accepted the following condition must be satisfied:
IRELAB=0
est≤TOL×max 1.0,y 1,y 2,…,yn;
IRELAB=1
est≤TOL;
IRELAB=2
est≤TOL×max ε,y 1,y 2,…,yn, where ε is machine precision.
If the appropriate condition is not satisfied, the step size is reduced and the solution recomputed on the current step.
If you wish to measure the error in the computed solution in terms of the number of correct decimal places, then set IRELAB=1 on entry, whereas if the error requirement is in terms of the number of correct significant digits, then set IRELAB=2. Where there is no preference in the choice of error test, IRELAB=0 will result in a mixed error test. It should be borne in mind that the computed solution will be used in evaluating g x,y.
Constraint: IRELAB=0, 1 or 2.
7:   HMAX – REAL (KIND=nag_wp)Input
On entry: if HMAX=0.0, no special action is taken.
If HMAX≠0.0, a check is made for a change in sign of g x,y at steps not greater than HMAX. This facility should be used if there is any chance of ‘missing’ the change in sign by checking too infrequently. For example, if two changes of sign of g x,y are expected within a distance h, say, of each other, then a suitable value for HMAX might be HMAX=h/2. If only one change of sign in g x,y is expected on the range X to XEND, then the choice HMAX=0.0 is most appropriate.
8:   FCN – SUBROUTINE, supplied by the user.External Procedure
FCN must evaluate the functions fi (i.e., the derivatives yi′) for given values of its arguments x,y 1,…,yn.
The specification of FCN is:
SUBROUTINE FCN ( X, Y, F)
REAL (KIND=nag_wp) X, Y(*), F(*)
In the description of the arguments of D02BHF below, n denotes the value of N in the call of D02BHF.
1:   X – REAL (KIND=nag_wp)Input
On entry: x, the value of the argument.
2:   Y* – REAL (KIND=nag_wp) arrayInput
On entry: yi, for i=1,2,…,n, the value of the argument.
3:   F* – REAL (KIND=nag_wp) arrayOutput
On exit: the value of fi, for i=1,2,…,n.
FCN must either be a module subprogram USEd by, or declared as EXTERNAL in, the (sub)program from which D02BHF is called. Arguments denoted as Input must not be changed by this procedure.
9:   G – REAL (KIND=nag_wp) FUNCTION, supplied by the user.External Procedure
G must evaluate the function g x,y at a specified point.
The specification of G is:
FUNCTION G ( X, Y)
REAL (KIND=nag_wp) G
REAL (KIND=nag_wp) X, Y(*)
In the description of the arguments of D02BHF below, n denotes the value of N in the call of D02BHF.
1:   X – REAL (KIND=nag_wp)Input
On entry: x, the value of the independent variable.
2:   Y* – REAL (KIND=nag_wp) arrayInput
On entry: the value of yi, for i=1,2,…,n.
G must either be a module subprogram USEd by, or declared as EXTERNAL in, the (sub)program from which D02BHF is called. Arguments denoted as Input must not be changed by this procedure.
10:   W N 7 – REAL (KIND=nag_wp) arrayWorkspace
11:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, | TOL≤0.0,
or | N≤0,
or | IRELAB≠0, 1 or 2.
IFAIL=2
With the given value of TOL, no further progress can be made across the integration range from the current point x=X, or dependence of the error on TOL would be lost if further progress across the integration range were attempted (see Section 9 for a discussion of this error exit). The components Y 1,Y 2,…,Y n contain the computed values of the solution at the current point x=X. No point at which g x,y changes sign has been located up to the point x=X.
IFAIL=3
TOL is too small for D02BHF to take an initial step (see Section 9). X and Y 1,Y 2,…,Y n retain their initial values.
IFAIL=4
At no point in the range X to XEND did the function g x,y change sign. It is assumed that g x,y=0.0 has no solution.
IFAIL=5 (C05AZF)
A serious error has occurred in an internal call to the specified routine. Check all subroutine calls and array dimensions. Seek expert help.
IFAIL=6
A serious error has occurred in an internal call to an integration routine. Check all subroutine calls and array dimensions. Seek expert help.
IFAIL=7
A serious error has occurred in an internal call to an interpolation routine. Check all (sub)program calls and array dimensions. Seek expert help.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

The accuracy depends on TOL, on the mathematical properties of the differential system, on the position where g x,y=0.0 and on the method. It can be controlled by varying TOL but the approximate proportionality of the error to TOL holds only for a restricted range of values of TOL. For TOL too large, the underlying theory may break down and the result of varying TOL may be unpredictable. For TOL too small, rounding error may affect the solution significantly and an error exit with IFAIL=2 or 3 is possible.
The accuracy may also be restricted by the properties of g x,y. You should try to code G without introducing any unnecessary cancellation errors.

8 Parallelism and Performance

D02BHF is not threaded in any implementation.

9 Further Comments

The time taken by D02BHF depends on the complexity and mathematical properties of the system of differential equations defined by FCN, the complexity of G, on the range, the position of the solution and the tolerance. There is also an overhead of the form a+b×n where a and b are machine-dependent computing times.
For some problems it is possible that D02BHF will return IFAIL=4 because of inaccuracy of the computed values Y, leading to inaccuracy in the computed values of g x,y used in the search for the solution of g x,y=0.0. This difficulty can be overcome by reducing TOL sufficiently, and if necessary, by choosing HMAX sufficiently small. If possible, you should choose XEND well beyond the expected point where g x,y=0.0; for example make XEND-X about 50% larger than the expected range. As a simple check, if, with XEND fixed, a change in TOL does not lead to a significant change in Y at XEND, then inaccuracy is not a likely source of error.
If D02BHF fails with IFAIL=3, then it could be called again with a larger value of TOL if this has not already been tried. If the accuracy requested is really needed and cannot be obtained with this routine, the system may be very stiff (see below) or so badly scaled that it cannot be solved to the required accuracy.
If D02BHF fails with IFAIL=2, it is likely that it has been called with a value of TOL which is so small that a solution cannot be obtained on the range X to XEND. This can happen for well-behaved systems and very small values of TOL. You should, however, consider whether there is a more fundamental difficulty. For example:
(a) | in the region of a singularity (infinite value) of the solution, the routine will usually stop with IFAIL=2, unless overflow occurs first. If overflow occurs using D02BHF, D02PFF can be used instead to detect the increasing solution, before overflow occurs. In any case, numerical integration cannot be continued through a singularity, and analytical treatment should be considered;
(b) | for ‘stiff’ equations, where the solution contains rapidly decaying components, the routine will compute in very small steps in x (internally to D02BHF) to preserve stability. This will usually exhibit itself by making the computing time excessively long, or occasionally by an exit with IFAIL=2. Merson's method is not efficient in such cases, and you should try D02EJF which uses a Backward Differentiation Formula method. To determine whether a problem is stiff, D02PEF may be used.
For well-behaved systems with no difficulties such as stiffness or singularities, the Merson method should work well for low accuracy calculations (three or four figures). For high accuracy calculations or where FCN is costly to evaluate, Merson's method may not be appropriate and a computationally less expensive method may be D02CJF which uses an Adams' method.
For problems for which D02BHF is not sufficiently general, you should consider D02PFF. D02PFF is a more general routine with many facilities including a more general error control criterion. D02PFF can be combined with the rootfinder C05AZF and the interpolation routine D02PSF to solve equations involving y 1,y 2,…,yn and their derivatives.
D02BHF can also be used to solve an equation involving x, y 1,y 2,…,yn and the derivatives of y 1,y 2,…,yn. For example in Section 10, D02BHF is used to find a value of X>0.0 where Y 1=0.0. It could instead be used to find a turning-point of y 1 by replacing the function g x,y in the program by:
REAL (kind=nag_wp) FUNCTION G(X,Y)
REAL (kind=nag_wp) X,Y(3),F(3)
CALL FCN(X,Y,F)
G = F(1)
RETURN
END
This routine is only intended to locate the first zero of g x,y. If later zeros are required, you are strongly advised to construct your own more general root-finding routines as discussed above.

10 Example

This example finds the value X>0.0 at which y=0.0, where y, v, ϕ are defined by
y′ = tan⁡ϕ v′ = -0.032 tan⁡ϕ v- 0.02 v cos⁡ϕ ϕ′ = -0.032 v 2
and where at X=0.0 we are given y=0.5, v=0.5 and ϕ=π/5. We write y=Y 1, v=Y 2 and ϕ=Y 3 and we set TOL=1.0E−4 and TOL=1.0E−5 in turn so that we can compare the solutions. We expect the solution X≃7.3 and so we set XEND=10.0 to avoid determining the solution of y=0.0 too near the end of the range of integration. The initial values and range are read from a data file.

10.1 Program Text

Program Text (d02bhfe.f90)

10.2 Program Data

Program Data (d02bhfe.d)

10.3 Program Results

Program Results (d02bhfe.r)

D02 Chapter Contents
D02 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


D02BJF : NAG Library, Mark 26

D02 Chapter Contents
D02 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

D02BJF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

D02BJF integrates a system of first-order ordinary differential equations over an interval with suitable initial conditions, using a fixed order Runge–Kutta method, until a user-specified function, if supplied, of the solution is zero, and returns the solution at points specified by you, if desired.

2 Specification

SUBROUTINE D02BJF ( X, XEND, N, Y, FCN, TOL, RELABS, OUTPUT, G, W, IFAIL)
INTEGER | N, IFAIL
REAL (KIND=nag_wp) | X, XEND, Y(N), TOL, G, W(20*N)
CHARACTER(1) | RELABS
EXTERNAL | FCN, OUTPUT, G

3 Description

D02BJF advances the solution of a system of ordinary differential equations
yi′=fi x,y 1,y 2,…,yn,  i=1,2,…,n,
from x=X to x=XEND using a fixed order Runge–Kutta method. The system is defined by FCN, which evaluates fi in terms of x and y=y 1,y 2,…,yn. The initial values of y=y 1,y 2,…,yn must be given at x=X.
The solution is returned via the OUTPUT supplied by you and at points specified by you, if desired: this solution is obtained by C 1 interpolation on solution values produced by the method. As the integration proceeds a check can be made on the user-specified function g x,y to determine an interval where it changes sign. The position of this sign change is then determined accurately by C 1 interpolation to the solution. It is assumed that g x,y is a continuous function of the variables, so that a solution of g x,y=0 can be determined by searching for a change in sign in g x,y. The accuracy of the integration, the interpolation and, indirectly, of the determination of the position where g x,y=0, is controlled by the arguments TOL and RELABS.

4 References

Shampine L F (1994) Numerical solution of ordinary differential equations Chapman and Hall

5 Arguments

1:   X – REAL (KIND=nag_wp)Input/Output
On entry: the initial value of the independent variable x.
On exit: if g is supplied by you, it contains the point where g x,y=0, unless g x,y≠0 anywhere on the range X to XEND, in which case, X will contain XEND (and the error indicator IFAIL=6 is set); if g is not supplied by you it contains XEND. However, if an error has occurred, it contains the value of x at which the error occurred.
2:   XEND – REAL (KIND=nag_wp)Input
On entry: the final value of the independent variable. If XEND<X, integration will proceed in the negative direction.
Constraint: XEND≠X.
3:   N – INTEGERInput
On entry: n, the number of equations.
Constraint: N>0.
4:   Y N – REAL (KIND=nag_wp) arrayInput/Output
On entry: the initial values of the solution y 1,y 2,…,yn at x=X.
On exit: the computed values of the solution at the final point x=X.
5:   FCN – SUBROUTINE, supplied by the user.External Procedure
FCN must evaluate the functions fi (i.e., the derivatives yi′) for given values of its arguments x,y 1,…,yn.
The specification of FCN is:
SUBROUTINE FCN ( X, Y, F)
REAL (KIND=nag_wp) X, Y(*), F(*)
1:   X – REAL (KIND=nag_wp)Input
On entry: x, the value of the independent variable.
2:   Y* – REAL (KIND=nag_wp) arrayInput
On entry: yi, for i=1,2,…,n, the value of the variable.
3:   F* – REAL (KIND=nag_wp) arrayOutput
On exit: the value of fi, for i=1,2,…,n.
FCN must either be a module subprogram USEd by, or declared as EXTERNAL in, the (sub)program from which D02BJF is called. Arguments denoted as Input must not be changed by this procedure.
6:   TOL – REAL (KIND=nag_wp)Input
On entry: a positive tolerance for controlling the error in the integration. Hence TOL affects the determination of the position where g x,y=0, if g is supplied.
D02BJF has been designed so that, for most problems, a reduction in TOL leads to an approximately proportional reduction in the error in the solution. However, the actual relation between TOL and the accuracy achieved cannot be guaranteed. You are strongly recommended to call D02BJF with more than one value for TOL and to compare the results obtained to estimate their accuracy. In the absence of any prior knowledge, you might compare the results obtained by calling D02BJF with RELABS='D' and with each of TOL=10.0-p and TOL=10.0-p-1 where p correct significant digits are required in the solution, y. The accuracy of the value x such that g x,y=0 is indirectly controlled by varying TOL. You should experiment to determine this accuracy.
Constraint: 10.0×machine precision<TOL<0.01.
7:   RELABS – CHARACTER(1)Input
On entry: the type of error control. At each step in the numerical solution an estimate of the local error, est, is made. For the current step to be accepted the following condition must be satisfied:
est =max ei/ τr × max yi,τa ≤ 1.0
where τr and τa are defined by
RELABS | τr | τa
'M' | TOL | 1.0
'A' | εr | TOL/εr
'R' | TOL | εa
'D' | TOL | εa
where εr and εa are small machine-dependent numbers and ei is an estimate of the local error at yi, computed internally. If the condition is not satisfied, the step size is reduced and the solution is recomputed on the current step. If you wish to measure the error in the computed solution in terms of the number of correct decimal places, then RELABS should be set to 'A' on entry, whereas if the error requirement is in terms of the number of correct significant digits, then RELABS should be set to 'R'. If you prefer a mixed error test, then RELABS should be set to 'M', otherwise if you have no preference, RELABS should be set to the default 'D'. Note that in this case 'D' is taken to be 'R'.
Constraint: RELABS='M', 'A', 'R' or 'D'.
8:   OUTPUT – SUBROUTINE, supplied by the NAG Library or the user.External Procedure
OUTPUT permits access to intermediate values of the computed solution (for example to print or plot them), at successive user-specified points. It is initially called by D02BJF with XSOL=X (the initial value of x). You must reset XSOL to the next point (between the current XSOL and XEND) where OUTPUT is to be called, and so on at each call to OUTPUT. If, after a call to OUTPUT, the reset point XSOL is beyond XEND, D02BJF will integrate to XEND with no further calls to OUTPUT; if a call to OUTPUT is required at the point XSOL=XEND, then XSOL must be given precisely the value XEND.
The specification of OUTPUT is:
SUBROUTINE OUTPUT ( XSOL, Y)
REAL (KIND=nag_wp) XSOL, Y(*)
1:   XSOL – REAL (KIND=nag_wp)Input/Output
On entry: the output value of the independent variable x.
On exit: you must set XSOL to the next value of x at which OUTPUT is to be called.
2:   Y* – REAL (KIND=nag_wp) arrayInput
On entry: the computed solution at the point XSOL.
OUTPUT must either be a module subprogram USEd by, or declared as EXTERNAL in, the (sub)program from which D02BJF is called. Arguments denoted as Input must not be changed by this procedure.
If you do not wish to access intermediate output, the actual argument OUTPUT must be the dummy routine D02BJX. (D02BJX is included in the NAG Library.)
9:   G – REAL (KIND=nag_wp) FUNCTION, supplied by the user.External Procedure
G must evaluate the function g x,y for specified values x,y. It specifies the function g for which the first position x where g x,y=0 is to be found.
The specification of G is:
FUNCTION G ( X, Y)
REAL (KIND=nag_wp) G
REAL (KIND=nag_wp) X, Y(*)
where n is the value of N in the call of D02BJF.
1:   X – REAL (KIND=nag_wp)Input
On entry: x, the value of the independent variable.
2:   Y* – REAL (KIND=nag_wp) arrayInput
On entry: yi, for i=1,2,…,n, the value of the variable.
G must either be a module subprogram USEd by, or declared as EXTERNAL in, the (sub)program from which D02BJF is called. Arguments denoted as Input must not be changed by this procedure.
If you do not require the root-finding option, the actual argument G must be the dummy routine D02BJW. (D02BJW is included in the NAG Library.)
10:   W 20×N – REAL (KIND=nag_wp) arrayWorkspace
11:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, | TOL≥0.01,
or | TOL is too small
or | N≤0,
or | RELABS≠'M', 'A', 'R' or 'D',
or | X=XEND.
IFAIL=2
With the given value of TOL, no further progress can be made across the integration range from the current point x=X. (See Section 9 for a discussion of this error exit.) The components Y 1,Y 2,…,Y N contain the computed values of the solution at the current point x=X. If you have supplied g, then no point at which g x,y changes sign has been located up to the point x=X.
IFAIL=3
TOL is too small for D02BJF to take an initial step. X and Y 1,Y 2,…,Y N retain their initial values.
IFAIL=4
XSOL has not been reset or XSOL lies behind X in the direction of integration, after the initial call to OUTPUT, if the OUTPUT option was selected.
IFAIL=5
A value of XSOL returned by the OUTPUT has not been reset or lies behind the last value of XSOL in the direction of integration, if the OUTPUT option was selected.
IFAIL=6
At no point in the range X to XEND did the function g x,y change sign, if g was supplied. It is assumed that g x,y=0 has no solution.
IFAIL=7
A serious error has occurred in an internal call to an interpolation routine. Check all (sub)program calls and array dimensions. Seek expert help.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

The accuracy of the computation of the solution vector Y may be controlled by varying the local error tolerance TOL. In general, a decrease in local error tolerance should lead to an increase in accuracy. You are advised to choose RELABS='D' unless you have a good reason for a different choice.
If the problem is a root-finding one, then the accuracy of the root determined will depend on the properties of g x,y and on the values of TOL and RELABS. You should try to code G without introducing any unnecessary cancellation errors.

8 Parallelism and Performance

D02BJF makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

If more than one root is required, then to determine the second and later roots D02BJF may be called again starting a short distance past the previously determined roots. Alternatively you may construct your own root-finding code using C05AZF, D02PFF and D02PSF.
If D02BJF fails with IFAIL=3, then it can be called again with a larger value of TOL if this has not already been tried. If the accuracy requested is really needed and cannot be obtained with this routine, the system may be very stiff (see below) or so badly scaled that it cannot be solved to the required accuracy.
If D02BJF fails with IFAIL=2, it is probable that it has been called with a value of TOL which is so small that a solution cannot be obtained on the range X to XEND. This can happen for well-behaved systems and very small values of TOL. You should, however, consider whether there is a more fundamental difficulty. For example:
(a) | in the region of a singularity (infinite value) of the solution, the routine will usually stop with IFAIL=2, unless overflow occurs first. Numerical integration cannot be continued through a singularity, and analytic treatment should be considered;
(b) | for ‘stiff’ equations where the solution contains rapidly decaying components, the routine will use very small steps in x (internally to D02BJF) to preserve stability. This will exhibit itself by making the computing time excessively long, or occasionally by an exit with IFAIL=2. Runge–Kutta methods are not efficient in such cases, and you should try D02EJF.

10 Example

This example illustrates the solution of four different problems. In each case the differential system (for a projectile) is
y′=tan⁡ϕ v′= -0.032 tan⁡ϕ v- 0.02 v cos⁡ϕ ϕ′= -0.032 v 2
over an interval X=0.0 to XEND=10.0 starting with values y=0.5, v=0.5 and ϕ=π/5. We solve each of the following problems with local error tolerances 1.0E−4 and 1.0E−5.
(i) | To integrate to x=10.0 producing intermediate output at intervals of 2.0 until a root is encountered where y=0.0.
(ii) | As (i) but with no intermediate output.
(iii) | As (i) but with no termination on a root-finding condition.
(iv) | As (i) but with no intermediate output and no root-finding termination condition.

10.1 Program Text

Program Text (d02bjfe.f90)

10.2 Program Data

Program Data (d02bjfe.d)

10.3 Program Results

Program Results (d02bjfe.r)

GnuplotProduced by GNUPLOT 4.6 patchlevel 3 −4 −3 −2 −1 0 1 2 0 2 4 6 8 10 Solution x Example Program ODE Solution using Runge-Kutta with Root-finding height velocity angle height = 0 gnuplot_plot_1 gnuplot_plot_2 gnuplot_plot_3 gnuplot_plot_4
D02 Chapter Contents
D02 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


D02CJF : NAG Library, Mark 26

D02 Chapter Contents
D02 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

D02CJF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

D02CJF integrates a system of first-order ordinary differential equations over a range with suitable initial conditions, using a variable-order, variable-step Adams' method until a user-specified function, if supplied, of the solution is zero, and returns the solution at points specified by you, if desired.

2 Specification

SUBROUTINE D02CJF ( X, XEND, N, Y, FCN, TOL, RELABS, OUTPUT, G, W, IFAIL)
INTEGER | N, IFAIL
REAL (KIND=nag_wp) | X, XEND, Y(N), TOL, G, W(28+21*N)
CHARACTER(1) | RELABS
EXTERNAL | FCN, OUTPUT, G

3 Description

D02CJF advances the solution of a system of ordinary differential equations
yi′=fi x,y 1,y 2,…,yn,  i=1,2,…,n,
from x=X to x=XEND using a variable-order, variable-step Adams' method. The system is defined by FCN, which evaluates fi in terms of x and y 1,y 2,…,yn. The initial values of y 1,y 2,…,yn must be given at x=X.
The solution is returned via OUTPUT at points specified by you, if desired: this solution is obtained by C 1 interpolation on solution values produced by the method. As the integration proceeds a check can be made on the user-specified function g x,y to determine an interval where it changes sign. The position of this sign change is then determined accurately by C 1 interpolation to the solution. It is assumed that g x,y is a continuous function of the variables, so that a solution of g x,y=0.0 can be determined by searching for a change in sign in g x,y. The accuracy of the integration, the interpolation and, indirectly, of the determination of the position where g x,y=0.0, is controlled by the arguments TOL and RELABS.
For a description of Adams' methods and their practical implementation see Hall and Watt (1976).

4 References

Hall G and Watt J M (ed.) (1976) Modern Numerical Methods for Ordinary Differential Equations Clarendon Press, Oxford

5 Arguments

1:   X – REAL (KIND=nag_wp)Input/Output
On entry: the initial value of the independent variable x.
Constraint: X≠XEND.
On exit: if g is supplied by you, it contains the point where g x,y=0.0, unless g x,y≠0.0 anywhere on the range X to XEND, in which case, X will contain XEND. If g is not supplied by you it contains XEND, unless an error has occurred, when it contains the value of x at the error.
2:   XEND – REAL (KIND=nag_wp)Input
On entry: the final value of the independent variable. If XEND<X, integration will proceed in the negative direction.
Constraint: XEND≠X.
3:   N – INTEGERInput
On entry: n, the number of differential equations.
Constraint: N≥1.
4:   Y N – REAL (KIND=nag_wp) arrayInput/Output
On entry: the initial values of the solution y 1,y 2,…,yn at x=X.
On exit: the computed values of the solution at the final point x=X.
5:   FCN – SUBROUTINE, supplied by the user.External Procedure
FCN must evaluate the functions fi (i.e., the derivatives yi′) for given values of its arguments x,y 1,…,yn.
The specification of FCN is:
SUBROUTINE FCN ( X, Y, F)
REAL (KIND=nag_wp) X, Y(*), F(*)
1:   X – REAL (KIND=nag_wp)Input
On entry: x, the value of the independent variable.
2:   Y* – REAL (KIND=nag_wp) arrayInput
On entry: yi, for i=1,2,…,n, the value of the variable.
3:   F* – REAL (KIND=nag_wp) arrayOutput
On exit: the value of fi, for i=1,2,…,n.
FCN must either be a module subprogram USEd by, or declared as EXTERNAL in, the (sub)program from which D02CJF is called. Arguments denoted as Input must not be changed by this procedure.
6:   TOL – REAL (KIND=nag_wp)Input
On entry: a positive tolerance for controlling the error in the integration. Hence TOL affects the determination of the position where g x,y=0.0, if g is supplied.
D02CJF has been designed so that, for most problems, a reduction in TOL leads to an approximately proportional reduction in the error in the solution. However, the actual relation between TOL and the accuracy achieved cannot be guaranteed. You are strongly recommended to call D02CJF with more than one value for TOL and to compare the results obtained to estimate their accuracy. In the absence of any prior knowledge, you might compare the results obtained by calling D02CJF with TOL=10.0-p and TOL=10.0-p-1 where p correct decimal digits are required in the solution.
Constraint: TOL>0.0.
7:   RELABS – CHARACTER(1)Input
On entry: the type of error control. At each step in the numerical solution an estimate of the local error, est, is made. For the current step to be accepted the following condition must be satisfied:
est=∑i=1 n ei/τr×yi+τa 2≤1.0
where τr and τa are defined by
RELABS | τr | τa
'M' | TOL | TOL
'A' | 0.0 | TOL
'R' | TOL | ε
'D' | TOL | TOL
where ε is a small machine-dependent number and ei is an estimate of the local error at yi, computed internally. If the appropriate condition is not satisfied, the step size is reduced and the solution is recomputed on the current step. If you wish to measure the error in the computed solution in terms of the number of correct decimal places, then RELABS should be set to 'A' on entry, whereas if the error requirement is in terms of the number of correct significant digits, then RELABS should be set to 'R'. If you prefer a mixed error test, then RELABS should be set to 'M', otherwise if you have no preference, RELABS should be set to the default 'D'. Note that in this case 'D' is taken to be 'M'.
Constraint: RELABS='M', 'A', 'R' or 'D'.
8:   OUTPUT – SUBROUTINE, supplied by the NAG Library or the user.External Procedure
OUTPUT permits access to intermediate values of the computed solution (for example to print or plot them), at successive user-specified points. It is initially called by D02CJF with XSOL=X (the initial value of x). You must reset XSOL to the next point (between the current XSOL and XEND) where OUTPUT is to be called, and so on at each call to OUTPUT. If, after a call to OUTPUT, the reset point XSOL is beyond XEND, D02CJF will integrate to XEND with no further calls to OUTPUT; if a call to OUTPUT is required at the point XSOL=XEND, then XSOL must be given precisely the value XEND.
The specification of OUTPUT is:
SUBROUTINE OUTPUT ( XSOL, Y)
REAL (KIND=nag_wp) XSOL, Y(*)
1:   XSOL – REAL (KIND=nag_wp)Input/Output
On entry: the output value of the independent variable x.
On exit: you must set XSOL to the next value of x at which OUTPUT is to be called.
2:   Y* – REAL (KIND=nag_wp) arrayInput
On entry: the computed solution at the point XSOL.
OUTPUT must either be a module subprogram USEd by, or declared as EXTERNAL in, the (sub)program from which D02CJF is called. Arguments denoted as Input must not be changed by this procedure.
If you do not wish to access intermediate output, the actual argument OUTPUT must be the dummy routine D02CJX. (D02CJX is included in the NAG Library.)
9:   G – REAL (KIND=nag_wp) FUNCTION, supplied by the user.External Procedure
G must evaluate the function g x,y for specified values x,y. It specifies the function g for which the first position x where g x,y=0 is to be found.
The specification of G is:
FUNCTION G ( X, Y)
REAL (KIND=nag_wp) G
REAL (KIND=nag_wp) X, Y(*)
1:   X – REAL (KIND=nag_wp)Input
On entry: x, the value of the independent variable.
2:   Y* – REAL (KIND=nag_wp) arrayInput
On entry: yi, for i=1,2,…,n, the value of the variable.
G must either be a module subprogram USEd by, or declared as EXTERNAL in, the (sub)program from which D02CJF is called. Arguments denoted as Input must not be changed by this procedure.
If you do not require the root-finding option, the actual argument G must be the dummy routine D02CJW. (D02CJW is included in the NAG Library.)
10:   W 28+21×N – REAL (KIND=nag_wp) arrayWorkspace
11:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, | TOL≤0.0,
or | N≤0,
or | RELABS≠'M', 'A', 'R' or 'D',
or | X=XEND.
IFAIL=2
With the given value of TOL, no further progress can be made across the integration range from the current point x=X. (See Section 9 for a discussion of this error exit.) The components Y 1,Y 2,…,Y N contain the computed values of the solution at the current point x=X. If you have supplied g, then no point at which g x,y changes sign has been located up to the point x=X.
IFAIL=3
TOL is too small for D02CJF to take an initial step. X and Y 1,Y 2,…,Y N retain their initial values.
IFAIL=4
XSOL has not been reset or XSOL lies behind X in the direction of integration, after the initial call to OUTPUT, if the OUTPUT option was selected.
IFAIL=5
A value of XSOL returned by the OUTPUT has not been reset or lies behind the last value of XSOL in the direction of integration, if the OUTPUT option was selected.
IFAIL=6
At no point in the range X to XEND did the function g x,y change sign, if g was supplied. It is assumed that g x,y=0 has no solution.
IFAIL=7
A serious error has occurred in an internal call. Check all subroutine calls and array sizes. Seek expert help.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

The accuracy of the computation of the solution vector Y may be controlled by varying the local error tolerance TOL. In general, a decrease in local error tolerance should lead to an increase in accuracy. You are advised to choose RELABS='M' unless you have a good reason for a different choice.
If the problem is a root-finding one, then the accuracy of the root determined will depend on the properties of g x,y. You should try to code G without introducing any unnecessary cancellation errors.

8 Parallelism and Performance

D02CJF is not threaded in any implementation.

9 Further Comments

If more than one root is required then D02QFF should be used.
If D02CJF fails with IFAIL=3, then it can be called again with a larger value of TOL if this has not already been tried. If the accuracy requested is really needed and cannot be obtained with this routine, the system may be very stiff (see below) or so badly scaled that it cannot be solved to the required accuracy.
If D02CJF fails with IFAIL=2, it is probable that it has been called with a value of TOL which is so small that a solution cannot be obtained on the range X to XEND. This can happen for well-behaved systems and very small values of TOL. You should, however, consider whether there is a more fundamental difficulty. For example:
(a) | in the region of a singularity (infinite value) of the solution, the routine will usually stop with IFAIL=2, unless overflow occurs first. Numerical integration cannot be continued through a singularity, and analytic treatment should be considered;
(b) | for ‘stiff’ equations where the solution contains rapidly decaying components, the routine will use very small steps in x (internally to D02CJF) to preserve stability. This will exhibit itself by making the computing time excessively long, or occasionally by an exit with IFAIL=2. Adams' methods are not efficient in such cases, and you should try D02EJF.

10 Example

This example illustrates the solution of four different problems. In each case the differential system (for a projectile) is
y′ = tan⁡ϕ v′ = -0.032 tan⁡ϕ v-0.02 v cos⁡ϕ ϕ′ = -0.032 v 2
over an interval X=0.0 to XEND=10.0 starting with values y=0.5, v=0.5 and ϕ=π/5. We solve each of the following problems with local error tolerances 1.0E−4 and 1.0E−5.
(i) | To integrate to x=10.0 producing output at intervals of 2.0 until a point is encountered where y=0.0.
(ii) | As (i) but with no intermediate output.
(iii) | As (i) but with no termination on a root-finding condition.
(iv) | As (i) but with no intermediate output and no root-finding termination condition.

10.1 Program Text

Program Text (d02cjfe.f90)

10.2 Program Data

Program Data (d02cjfe.d)

10.3 Program Results

Program Results (d02cjfe.r)

GnuplotProduced by GNUPLOT 4.6 patchlevel 3 −4 −3 −2 −1 0 1 2 0 2 4 6 8 10 Solution x Example Program ODE Solution using Adams Method with Root-finding height velocity angle height = 0 gnuplot_plot_1 gnuplot_plot_2 gnuplot_plot_3 gnuplot_plot_4
D02 Chapter Contents
D02 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


D02 Chapter Contents : NAG Library Manual, Mark 26

D02 Chapter Introduction
NAG Library Manual

NAG Library Chapter Contents

D02 – Ordinary Differential Equations

D02 Chapter Introduction – a description of the Chapter and an overview of the algorithms available

D02M–N Sub-chapter Introduction

Routine Name | Mark of Introduction | Purpose
D02AGF Example Text Example Data Example Plot | 2 | nagf_ode_bvp_shoot_genpar_intern Ordinary differential equations, boundary value problem, shooting and matching technique, allowing interior matching point, general parameters to be determined
D02BGF Example Text Example Data | 7 | nagf_ode_ivp_rkm_val_simple Ordinary differential equations, initial value problem, Runge–Kutta–Merson method, until a component attains given value (simple driver)
D02BHF Example Text Example Data | 7 | nagf_ode_ivp_rkm_zero_simple Ordinary differential equations, initial value problem, Runge–Kutta–Merson method, until function of solution is zero (simple driver)
D02BJF Example Text Example Data Example Plot | 18 | nagf_ode_ivp_rk_zero_simple Ordinary differential equations, initial value problem, Runge–Kutta method, until function of solution is zero, integration over range with intermediate output (simple driver)
D02CJF Example Text Example Data Example Plot | 13 | nagf_ode_ivp_adams_zero_simple Ordinary differential equations, initial value problem, Adams' method, until function of solution is zero, intermediate output (simple driver)
D02EJF Example Text Example Data Example Plot | 12 | nagf_ode_ivp_bdf_zero_simple Ordinary differential equations, stiff initial value problem, backward differentiation formulae method, until function of solution is zero, intermediate output (simple driver)
D02GAF Example Text Example Data Example Plot | 8 | nagf_ode_bvp_fd_nonlin_fixedbc Ordinary differential equations, boundary value problem, finite difference technique with deferred correction, simple nonlinear problem
D02GBF Example Text Example Data Example Plot | 8 | nagf_ode_bvp_fd_lin_gen Ordinary differential equations, boundary value problem, finite difference technique with deferred correction, general linear problem
D02HAF Example Text Example Data Example Plot | 8 | nagf_ode_bvp_shoot_bval Ordinary differential equations, boundary value problem, shooting and matching, boundary values to be determined
D02HBF Example Text Example Data Example Plot | 8 | nagf_ode_bvp_shoot_genpar Ordinary differential equations, boundary value problem, shooting and matching, general parameters to be determined
D02JAF Example Text Example Data Example Plot | 8 | nagf_ode_bvp_coll_nth Ordinary differential equations, boundary value problem, collocation and least squares, single nth-order linear equation
D02JBF Example Text Example Data Example Plot | 8 | nagf_ode_bvp_coll_sys Ordinary differential equations, boundary value problem, collocation and least squares, system of first-order linear equations
D02KAF Example Text Example Data | 7 | nagf_ode_sl2_reg_finite Second-order Sturm–Liouville problem, regular system, finite range, eigenvalue only
D02KDF Example Text Example Data | 7 | nagf_ode_sl2_breaks_vals Second-order Sturm–Liouville problem, regular/singular system, finite/infinite range, eigenvalue only, user-specified break-points
D02KEF Example Text Example Data Example Plot | 8 | nagf_ode_sl2_breaks_funs Second-order Sturm–Liouville problem, regular/singular system, finite/infinite range, eigenvalue and eigenfunction, user-specified break-points
D02LAF Example Text Example Data Example Plot | 13 | nagf_ode_ivp_2nd_rkn Second-order ordinary differential equations, initial value problem, Runge–Kutta–Nystrom method
D02LXF | 13 | nagf_ode_ivp_2nd_rkn_setup Second-order ordinary differential equations, initial value problem, setup for D02LAF
D02LYF | 13 | nagf_ode_ivp_2nd_rkn_diag Second-order ordinary differential equations, initial value problem, diagnostics for D02LAF
D02LZF | 13 | nagf_ode_ivp_2nd_rkn_interp Second-order ordinary differential equations, initial value problem, interpolation for D02LAF
D02MCF | 22 | nagf_ode_dae_dassl_cont Implicit ordinary differential equations/DAEs, initial value problem, DASSL method continuation for D02NEF
D02MVF Example Text Example Data Example Plot | 14 | nagf_ode_ivp_stiff_dassl Ordinary differential equations, initial value problem, DASSL method, setup for D02M–N routines
D02MWF Example Text Example Data | 22 | nagf_ode_dae_dassl_setup Implicit ordinary differential equations/DAEs, initial value problem, setup for D02NEF
D02MZF Example Text Example Data | 14 | nagf_ode_ivp_stiff_interp Ordinary differential equations, initial value problem, interpolation for D02M–N routines (all integration methods), natural interpolant
D02NBF Example Text Example Data Example Plot | 12 | nagf_ode_ivp_stiff_exp_fulljac Explicit ordinary differential equations, stiff initial value problem, full Jacobian (comprehensive)
D02NCF Example Text Example Data Example Plot | 12 | nagf_ode_ivp_stiff_exp_bandjac Explicit ordinary differential equations, stiff initial value problem, banded Jacobian (comprehensive)
D02NDF Example Text Example Data Example Plot | 12 | nagf_ode_ivp_stiff_exp_sparjac Explicit ordinary differential equations, stiff initial value problem, sparse Jacobian (comprehensive)
D02NEF Example Text Example Data | 22 | nagf_ode_dae_dassl_gen Implicit ordinary differential equations/DAEs, initial value problem, DASSL method integrator
D02NGF Example Text Example Data Example Plot | 12 | nagf_ode_ivp_stiff_imp_fulljac Implicit/algebraic ordinary differential equations, stiff initial value problem, full Jacobian (comprehensive)
D02NHF Example Text Example Data | 12 | nagf_ode_ivp_stiff_imp_bandjac Implicit/algebraic ordinary differential equations, stiff initial value problem, banded Jacobian (comprehensive)
D02NJF Example Text Example Data Example Plot | 12 | nagf_ode_ivp_stiff_imp_sparjac Implicit/algebraic ordinary differential equations, stiff initial value problem, sparse Jacobian (comprehensive)
D02NMF Example Text Example Data Example Plot | 12 | nagf_ode_ivp_stiff_exp_revcom Explicit ordinary differential equations, stiff initial value problem (reverse communication, comprehensive)
D02NNF Example Text Example Data | 12 | nagf_ode_ivp_stiff_imp_revcom Implicit/algebraic ordinary differential equations, stiff initial value problem (reverse communication, comprehensive)
D02NPF | 22 | nagf_ode_dae_dassl_linalg Implicit ordinary differential equations/DAEs, initial value problem linear algebra setup routine for D02NEF
D02NRF | 12 | nagf_ode_ivp_stiff_sparjac_enq Ordinary differential equations, initial value problem, for use with D02M–N routines, sparse Jacobian, enquiry routine
D02NSF | 12 | nagf_ode_ivp_stiff_fulljac_setup Ordinary differential equations, initial value problem, for use with D02M–N routines, full Jacobian, linear algebra set up
D02NTF | 12 | nagf_ode_ivp_stiff_bandjac_setup Ordinary differential equations, initial value problem, for use with D02M–N routines, banded Jacobian, linear algebra set up
D02NUF | 12 | nagf_ode_ivp_stiff_sparjac_setup Ordinary differential equations, initial value problem, for use with D02M–N routines, sparse Jacobian, linear algebra set up
D02NVF | 12 | nagf_ode_ivp_stiff_bdf Ordinary differential equations, initial value problem, backward differentiation formulae method, setup for D02M–N routines
D02NWF | 12 | nagf_ode_ivp_stiff_blend Ordinary differential equations, initial value problem, Blend method, setup for D02M–N routines
D02NXF | 12 | nagf_ode_ivp_stiff_sparjac_diag Ordinary differential equations, initial value problem, sparse Jacobian, linear algebra diagnostics, for use with D02M–N routines
D02NYF | 12 | nagf_ode_ivp_stiff_integ_diag Ordinary differential equations, initial value problem, integrator diagnostics, for use with D02M–N routines
D02NZF | 12 | nagf_ode_ivp_stiff_contin Ordinary differential equations, initial value problem, setup for continuation calls to integrator, for use with D02M–N routines
D02PEF Example Text Example Data Example Plot | 24 | nagf_ode_ivp_rkts_range Ordinary differential equations, initial value problem, Runge–Kutta method, integration over range with output
D02PFF Example Text Example Data Example Plot | 24 | nagf_ode_ivp_rkts_onestep Ordinary differential equations, initial value problem, Runge–Kutta method, integration over one step
D02PGF Example Text Example Data Example Plot | 26 | nagf_ode_ivp_rk_step_revcomm Ordinary differential equations, initial value problem, Runge–Kutta method, integration by reverse communication
D02PHF | 26 | nagf_ode_ivp_rk_interp_setup Set up interpolant by reverse communication for solution and derivative evaluations at points within the range of the last integration step taken by D02PGF
D02PJF | 26 | nagf_ode_ivp_rk_interp_eval Evaluate interpolant, set up using D02PQF, to approximate solution and/or solution derivatives at a point within the range of the last integration step taken by D02PGF
D02PQF | 24 | nagf_ode_ivp_rkts_setup Ordinary differential equations, initial value problem, setup for D02PEF and D02PFF
D02PRF Example Text Example Data Example Plot | 24 | nagf_ode_ivp_rkts_reset_tend Ordinary differential equations, initial value problem, resets end of range for D02PFF
D02PSF Example Text Example Data Example Plot | 24 | nagf_ode_ivp_rkts_interp Ordinary differential equations, initial value problem, interpolation for D02PFF
D02PTF | 24 | nagf_ode_ivp_rkts_diag Ordinary differential equations, initial value problem, integration diagnostics for D02PEF and D02PFF
D02PUF Example Text Example Data Example Plot | 24 | nagf_ode_ivp_rkts_errass Ordinary differential equations, initial value problem, error assessment diagnostics for D02PEF and D02PFF
D02QFF Example Text Example Data | 13 | nagf_ode_ivp_adams_roots Ordinary differential equations, initial value problem, Adams' method with root-finding (direct communication, comprehensive)
D02QGF Example Text Example Data Example Plot | 13 | nagf_ode_ivp_adams_roots_revcom Ordinary differential equations, initial value problem, Adams' method with root-finding (reverse communication, comprehensive)
D02QWF | 13 | nagf_ode_ivp_adams_setup Ordinary differential equations, initial value problem, setup for D02QFF and D02QGF
D02QXF | 13 | nagf_ode_ivp_adams_diag Ordinary differential equations, initial value problem, diagnostics for D02QFF and D02QGF
D02QYF | 13 | nagf_ode_ivp_adams_rootdiag Ordinary differential equations, initial value problem, root-finding diagnostics for D02QFF and D02QGF
D02QZF Example Text Example Data Example Plot | 13 | nagf_ode_ivp_adams_interp Ordinary differential equations, initial value problem, interpolation for D02QFF or D02QGF
D02RAF Example Text Example Data Example Plot | 8 | nagf_ode_bvp_fd_nonlin_gen Ordinary differential equations, general nonlinear boundary value problem, finite difference technique with deferred correction, continuation facility
D02SAF Example Text Example Data Example Plot | 8 | nagf_ode_bvp_shoot_genpar_algeq Ordinary differential equations, boundary value problem, shooting and matching technique, subject to extra algebraic equations, general parameters to be determined
D02TGF Example Text Example Data Example Plot | 8 | nagf_ode_bvp_coll_nth_comp nth-order linear ordinary differential equations, boundary value problem, collocation and least squares
D02TKF Example Text Example Data Example Plot | 17 | nagf_ode_withdraw_bvp_coll_nlin Ordinary differential equations, general nonlinear boundary value problem, collocation technique Note: this routine is scheduled for withdrawal at Mark 27, see Advice on Replacement Calls for Withdrawn/Superseded Routines for further information.
D02TLF Example Text Example Data Example Plot | 25 | nagf_ode_bvp_coll_nlin_solve Ordinary differential equations, general nonlinear boundary value problem, collocation technique (thread safe)
D02TVF Example Text Example Data Example Plot | 17 | nagf_ode_bvp_coll_nlin_setup Ordinary differential equations, general nonlinear boundary value problem, setup for D02TLF
D02TXF Example Text Example Data Example Plot | 17 | nagf_ode_bvp_coll_nlin_contin Ordinary differential equations, general nonlinear boundary value problem, continuation facility for D02TLF
D02TYF Example Text Example Data Example Plot | 17 | nagf_ode_bvp_coll_nlin_interp Ordinary differential equations, general nonlinear boundary value problem, interpolation for D02TLF
D02TZF Example Text Example Data Example Plot | 17 | nagf_ode_bvp_coll_nlin_diag Ordinary differential equations, general nonlinear boundary value problem, diagnostics for D02TLF
D02UAF | 23 | nagf_ode_bvp_ps_lin_coeffs Coefficients of Chebyshev interpolating polynomial from function values on Chebyshev grid
D02UBF | 23 | nagf_ode_bvp_ps_lin_cgl_vals Function or low-order-derivative values on Chebyshev grid from coefficients of Chebyshev interpolating polynomial
D02UCF | 23 | nagf_ode_bvp_ps_lin_cgl_grid Chebyshev Gauss–Lobatto grid generation
D02UDF Example Text Example Data | 23 | nagf_ode_bvp_ps_lin_cgl_deriv Differentiate a function by the FFT using function values on Chebyshev grid
D02UEF Example Text Example Data | 23 | nagf_ode_bvp_ps_lin_solve Solve linear constant coefficient boundary value problem on Chebyshev grid, Integral formulation
D02UWF Example Text Example Data | 23 | nagf_ode_bvp_ps_lin_grid_vals Interpolate a function from Chebyshev grid to uniform grid using barycentric Lagrange interpolation
D02UYF Example Text Example Data | 23 | nagf_ode_bvp_ps_lin_quad_weights Clenshaw–Curtis quadrature weights for integration using computed Chebyshev coefficients
D02UZF Example Text Example Data | 23 | nagf_ode_bvp_ps_lin_cheb_eval Chebyshev polynomial evaluation, Tk x
D02XJF | 12 | nagf_ode_ivp_stiff_nat_interp Ordinary differential equations, initial value problem, interpolation for D02M–N routines (BLEND and BDF methods only), natural interpolant
D02XKF | 12 | nagf_ode_ivp_stiff_c1_interp Ordinary differential equations, initial value problem, interpolation for D02M–N routines, C 1 interpolant
D02ZAF Example Text Example Data | 12 | nagf_ode_ivp_stiff_errest Ordinary differential equations, initial value problem, weighted norm of local error estimate for D02M–N routines
D02 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


D02EJF : NAG Library, Mark 26

D02 Chapter Contents
D02 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

D02EJF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

D02EJF integrates a stiff system of first-order ordinary differential equations over an interval with suitable initial conditions, using a variable-order, variable-step method implementing the Backward Differentiation Formulae (BDF), until a user-specified function, if supplied, of the solution is zero, and returns the solution at points specified by you, if desired.

2 Specification

SUBROUTINE D02EJF ( X, XEND, N, Y, FCN, PEDERV, TOL, RELABS, OUTPUT, G, W, IW, IFAIL)
INTEGER | N, IW, IFAIL
REAL (KIND=nag_wp) | X, XEND, Y(N), TOL, G, W(IW)
CHARACTER(1) | RELABS
EXTERNAL | FCN, PEDERV, OUTPUT, G

3 Description

D02EJF advances the solution of a system of ordinary differential equations
yi′ = fi x,y 1,y 2,…,yn ,   i=1,2,…,n ,
from x=X to x=XEND using a variable-order, variable-step method implementing the BDF. The system is defined by FCN, which evaluates fi in terms of x and y 1 , y 2 , … , yn (see Section 5). The initial values of y 1 , y 2 , … , yn must be given at x=X.
The solution is returned via the OUTPUT at points specified by you, if desired: this solution is obtained by C 1 interpolation on solution values produced by the method. As the integration proceeds a check can be made on the user-specified function g x,y to determine an interval where it changes sign. The position of this sign change is then determined accurately by C 1 interpolation to the solution. It is assumed that g x,y is a continuous function of the variables, so that a solution of g x,y=0.0 can be determined by searching for a change in sign in g x,y. The accuracy of the integration, the interpolation and, indirectly, of the determination of the position where g x,y=0.0, is controlled by the arguments TOL and RELABS. The Jacobian of the system y′=f x,y may be supplied in PEDERV, if it is available.
For a description of BDF and their practical implementation see Hall and Watt (1976).

4 References

Hall G and Watt J M (ed.) (1976) Modern Numerical Methods for Ordinary Differential Equations Clarendon Press, Oxford

5 Arguments

1:   X – REAL (KIND=nag_wp)Input/Output
On entry: the initial value of the independent variable x.
Constraint: X≠XEND.
On exit: if G is supplied by you, X contains the point where g x,y=0.0, unless g x,y≠0.0 anywhere on the range X to XEND, in which case, X will contain XEND. If G is not supplied X contains XEND, unless an error has occurred, when it contains the value of x at the error.
2:   XEND – REAL (KIND=nag_wp)Input
On entry: the final value of the independent variable. If XEND<X, integration will proceed in the negative direction.
Constraint: XEND≠X.
3:   N – INTEGERInput
On entry: n, the number of differential equations.
Constraint: N≥1.
4:   Y N – REAL (KIND=nag_wp) arrayInput/Output
On entry: the initial values of the solution y 1,y 2,…,yn at x=X.
On exit: the computed values of the solution at the final point x=X.
5:   FCN – SUBROUTINE, supplied by the user.External Procedure
FCN must evaluate the functions fi (i.e., the derivatives yi′) for given values of its arguments x,y 1,…,yn.
The specification of FCN is:
SUBROUTINE FCN ( X, Y, F)
REAL (KIND=nag_wp) X, Y(n), F(n)
where n is the value of N in the call of D02EJF.
1:   X – REAL (KIND=nag_wp)Input
On entry: x, the value of the independent variable.
2:   Y n – REAL (KIND=nag_wp) arrayInput
On entry: yi, for i=1,2,…,n, the value of the variable.
3:   F n – REAL (KIND=nag_wp) arrayOutput
On exit: the value of fi, for i=1,2,…,n.
FCN must either be a module subprogram USEd by, or declared as EXTERNAL in, the (sub)program from which D02EJF is called. Arguments denoted as Input must not be changed by this procedure.
6:   PEDERV – SUBROUTINE, supplied by the NAG Library or the user.External Procedure
PEDERV must evaluate the Jacobian of the system (that is, the partial derivatives ∂fi ∂yj ) for given values of the variables x,y 1,y 2,…,yn.
The specification of PEDERV is:
SUBROUTINE PEDERV ( X, Y, PW)
REAL (KIND=nag_wp) X, Y(n), PW(*)
where n is the value of N in the call of D02EJF.
1:   X – REAL (KIND=nag_wp)Input
On entry: x, the value of the independent variable.
2:   Y n – REAL (KIND=nag_wp) arrayInput
On entry: yi, for i=1,2,…,n, the value of the variable.
3:   PW* – REAL (KIND=nag_wp) arrayOutput
On exit: PW n×i-1+j must contain the value of ∂fi ∂yj , for i=1,2,…,n and j=1,2,…,n.
PEDERV must either be a module subprogram USEd by, or declared as EXTERNAL in, the (sub)program from which D02EJF is called. Arguments denoted as Input must not be changed by this procedure.
If you do not wish to supply the Jacobian, the actual argument PEDERV must be the dummy routine D02EJY. (D02EJY is included in the NAG Library.)
7:   TOL – REAL (KIND=nag_wp)Input/Output
On entry: must be set to a positive tolerance for controlling the error in the integration. Hence TOL affects the determination of the position where g x,y=0.0, if G is supplied.
D02EJF has been designed so that, for most problems, a reduction in TOL leads to an approximately proportional reduction in the error in the solution. However, the actual relation between TOL and the accuracy achieved cannot be guaranteed. You are strongly recommended to call D02EJF with more than one value for TOL and to compare the results obtained to estimate their accuracy. In the absence of any prior knowledge, you might compare the results obtained by calling D02EJF with TOL=10-p and TOL=10-p-1 if p correct decimal digits are required in the solution.
Constraint: TOL>0.0.
On exit: normally unchanged. However if the range X to XEND is so short that a small change in TOL is unlikely to make any change in the computed solution, then, on return, TOL has its sign changed.
8:   RELABS – CHARACTER(1)Input
On entry: the type of error control. At each step in the numerical solution an estimate of the local error, est, is made. For the current step to be accepted the following condition must be satisfied:
est = 1 n ∑ i=1 n ei / τr × yi + τa 2 ≤ 1.0
where τr and τa are defined by
RELABS | τr | τa
'M' | TOL | TOL
'A' | 0.0 | TOL
'R' | TOL | ε
'D' | TOL | ε
where ε is a small machine-dependent number and ei is an estimate of the local error at yi, computed internally. If the appropriate condition is not satisfied, the step size is reduced and the solution is recomputed on the current step. If you wish to measure the error in the computed solution in terms of the number of correct decimal places, then RELABS should be set to 'A' on entry, whereas if the error requirement is in terms of the number of correct significant digits, then RELABS should be set to 'R'. If you prefer a mixed error test, then RELABS should be set to 'M', otherwise if you have no preference, RELABS should be set to the default 'D'. Note that in this case 'D' is taken to be 'R'.
Constraint: RELABS='A', 'M', 'R' or 'D'.
9:   OUTPUT – SUBROUTINE, supplied by the NAG Library or the user.External Procedure
OUTPUT permits access to intermediate values of the computed solution (for example to print or plot them), at successive user-specified points. It is initially called by D02EJF with XSOL=X (the initial value of x). You must reset XSOL to the next point (between the current XSOL and XEND) where OUTPUT is to be called, and so on at each call to OUTPUT. If, after a call to OUTPUT, the reset point XSOL is beyond XEND, D02EJF will integrate to XEND with no further calls to OUTPUT; if a call to OUTPUT is required at the point XSOL=XEND, then XSOL must be given precisely the value XEND.
The specification of OUTPUT is:
SUBROUTINE OUTPUT ( XSOL, Y)
REAL (KIND=nag_wp) XSOL, Y(n)
where n is the value of N in the call of D02EJF.
1:   XSOL – REAL (KIND=nag_wp)Input/Output
On entry: x, the value of the independent variable.
On exit: you must set XSOL to the next value of x at which OUTPUT is to be called.
2:   Y n – REAL (KIND=nag_wp) arrayInput
On entry: the computed solution at the point XSOL.
OUTPUT must either be a module subprogram USEd by, or declared as EXTERNAL in, the (sub)program from which D02EJF is called. Arguments denoted as Input must not be changed by this procedure.
If you do not wish to access intermediate output, the actual argument OUTPUT must be the dummy routine D02EJX. (D02EJX is included in the NAG Library.)
10:   G – REAL (KIND=nag_wp) FUNCTION, supplied by the user.External Procedure
G must evaluate the function g x,y for specified values x,y. It specifies the function g for which the first position x where g x,y=0 is to be found.
The specification of G is:
FUNCTION G ( X, Y)
REAL (KIND=nag_wp) G
REAL (KIND=nag_wp) X, Y(n)
where n is the value of N in the call of D02EJF.
1:   X – REAL (KIND=nag_wp)Input
On entry: x, the value of the independent variable.
2:   Y n – REAL (KIND=nag_wp) arrayInput
On entry: yi, for i=1,2,…,n, the value of the variable.
G must either be a module subprogram USEd by, or declared as EXTERNAL in, the (sub)program from which D02EJF is called. Arguments denoted as Input must not be changed by this procedure.
If you do not require the root-finding option, the actual argument G must be the dummy routine D02EJW. (D02EJW is included in the NAG Library.)
11:   W IW – REAL (KIND=nag_wp) arrayWorkspace
12:   IW – INTEGERInput
On entry: the dimension of the array W as declared in the (sub)program from which D02EJF is called.
Constraint: IW≥12+N×N+50.
13:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, | TOL≤0.0,
or | X=XEND,
or | N≤0,
or | RELABS≠'M','A','R','D',
or | IW<12+N×N+50.
IFAIL=2
With the given value of TOL, no further progress can be made across the integration range from the current point x=X. (See Section 5 for a discussion of this error test.) The components Y 1,Y 2,…,Y N contain the computed values of the solution at the current point x=X. If you have supplied G, then no point at which g x,y changes sign has been located up to the point x=X.
IFAIL=3
TOL is too small for D02EJF to take an initial step. X and Y 1,Y 2,…,Y N retain their initial values.
IFAIL=4
XSOL lies behind X in the direction of integration, after the initial call to OUTPUT, if the OUTPUT option was selected.
IFAIL=5
A value of XSOL returned by the OUTPUT lies behind the last value of XSOL in the direction of integration, if the OUTPUT option was selected.
IFAIL=6
At no point in the range X to XEND did the function g x,y change sign, if g was supplied. It is assumed that g x,y=0 has no solution.
IFAIL=7 (C05AZF)
A serious error has occurred in an internal call to the specified routine. Check all subroutine calls and array dimensions. Seek expert help.
IFAIL=8 (D02XKF)
A serious error has occurred in an internal call to the specified routine. Check all subroutine calls and array dimensions. Seek expert help.
IFAIL=9
A serious error has occurred in an internal call to an interpolation routine. Check all (sub)program calls and array dimensions. Seek expert help.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

The accuracy of the computation of the solution vector Y may be controlled by varying the local error tolerance TOL. In general, a decrease in local error tolerance should lead to an increase in accuracy. You are advised to choose RELABS='R' unless you have a good reason for a different choice. It is particularly appropriate if the solution decays.
If the problem is a root-finding one, then the accuracy of the root determined will depend strongly on ∂g ∂x and ∂g ∂yi , for i=1,2,…,n. Large values for these quantities may imply large errors in the root.

8 Parallelism and Performance

D02EJF is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
D02EJF makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

If more than one root is required, then to determine the second and later roots D02EJF may be called again starting a short distance past the previously determined roots. Alternatively you may construct your own root-finding code using D02NBF (and other routines in Sub-chapter D02M–N), C05AZF and D02XKF.
If it is easy to code, you should supply PEDERV. However, it is important to be aware that if PEDERV is coded incorrectly, a very inefficient integration may result and possibly even a failure to complete the integration (see IFAIL=2).

10 Example

We illustrate the solution of five different problems. In each case the differential system is the well-known stiff Robertson problem.
a′ = -0.04 a+104 bc b′ = 0.04 a-104 bc -3×107b 2 c′ = -3×107b 2
with initial conditions a=1.0, b=c=0.0 at x=0.0. We solve each of the following problems with local error tolerances 1.0E−3 and 1.0E−4.
(i) | To integrate to x=10.0 producing output at intervals of 2.0 until a point is encountered where a=0.9. The Jacobian is calculated numerically.
(ii) | As (i) but with the Jacobian calculated analytically.
(iii) | As (i) but with no intermediate output.
(iv) | As (i) but with no termination on a root-finding condition.
(v) | Integrating the equations as in (i) but with no intermediate output and no root-finding termination condition.

10.1 Program Text

Program Text (d02ejfe.f90)

10.2 Program Data

Program Data (d02ejfe.d)

10.3 Program Results

Program Results (d02ejfe.r)

GnuplotProduced by GNUPLOT 4.6 patchlevel 3 0 0.2 0.4 0.6 0.8 1 0 2 4 6 8 10 Solution (a,b,c) x Example Program ODE Solution using BDF Method with Root-finding a b c a = 0.9 gnuplot_plot_1 gnuplot_plot_2 gnuplot_plot_3 gnuplot_plot_4
D02 Chapter Contents
D02 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


D02GAF : NAG Library, Mark 26

D02 Chapter Contents
D02 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

D02GAF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

D02GAF solves a two-point boundary value problem with assigned boundary values for a system of ordinary differential equations, using a deferred correction technique and a Newton iteration.

2 Specification

SUBROUTINE D02GAF ( U, V, N, A, B, TOL, FCN, MNP, X, Y, NP, W, LW, IW, LIW, IFAIL)
INTEGER | N, MNP, NP, LW, IW(LIW), LIW, IFAIL
REAL (KIND=nag_wp) | U(N,2), V(N,2), A, B, TOL, X(MNP), Y(N,MNP), W(LW)
EXTERNAL | FCN

3 Description

D02GAF solves a two-point boundary value problem for a system of n differential equations in the interval [a,b]. The system is written in the form:
yi′=fi x,y 1,y 2,…,yn,  i=1,2,…,n (1)
and the derivatives fi are evaluated by FCN. Initially, n boundary values of the variables yi must be specified, some at a and some at b. You must supply estimates of the remaining n boundary values and all the boundary values are used in constructing an initial approximation to the solution. This approximate solution is corrected by a finite difference technique with deferred correction allied with a Newton iteration to solve the finite difference equations. The technique used is described fully in Pereyra (1979). The Newton iteration requires a Jacobian matrix ∂fi ∂yj and this is calculated by numerical differentiation using an algorithm described in Curtis et al. (1974).
You supply an absolute error tolerance and may also supply an initial mesh for the construction of the finite difference equations (alternatively a default mesh is used). The algorithm constructs a solution on a mesh defined by adding points to the initial mesh. This solution is chosen so that the error is everywhere less than your tolerance and so that the error is approximately equidistributed on the final mesh. The solution is returned on this final mesh.
If the solution is required at a few specific points then these should be included in the initial mesh. If on the other hand the solution is required at several specific points then you should use the interpolation routines provided in Chapter E01 if these points do not themselves form a convenient mesh.

4 References

Curtis A R, Powell M J D and Reid J K (1974) On the estimation of sparse Jacobian matrices J. Inst. Maths. Applics. 13 117–119
Pereyra V (1979) PASVA3: An adaptive finite-difference Fortran program for first order nonlinear, ordinary boundary problems Codes for Boundary Value Problems in Ordinary Differential Equations. Lecture Notes in Computer Science (eds B Childs, M Scott, J W Daniel, E Denman and P Nelson) 76 Springer–Verlag

5 Arguments

1:   U N 2 – REAL (KIND=nag_wp) arrayInput
On entry: U i 1 must be set to the known or estimated value of yi at a and U i 2 must be set to the known or estimated value of yi at b, for i=1,2,…,n.
2:   V N 2 – REAL (KIND=nag_wp) arrayInput
On entry: V ij must be set to 0.0 if U ij is a known value and to 1.0 if U ij is an estimated value, for i=1,2,…,n and j=1,2.
Constraint: precisely n of the V ij must be set to 0.0, i.e., precisely n of the U ij must be known values, and these must not be all at a or all at b.
3:   N – INTEGERInput
On entry: n, the number of equations.
Constraint: N≥2.
4:   A – REAL (KIND=nag_wp)Input
On entry: a, the left-hand boundary point.
5:   B – REAL (KIND=nag_wp)Input
On entry: b, the right-hand boundary point.
Constraint: B>A.
6:   TOL – REAL (KIND=nag_wp)Input
On entry: a positive absolute error tolerance. If
a=x 1<x 2<⋯<xNP=b
is the final mesh, zj xi is the jth component of the approximate solution at xi, and yj x is the jth component of the true solution of equation (1) (see Section 3) and the boundary conditions, then, except in extreme cases, it is expected that
zj xi-yj xi≤TOL,  i=1,2,…,NP​ and ​j=1,2,…,n. (2)
Constraint: TOL>0.0.
7:   FCN – SUBROUTINE, supplied by the user.External Procedure
FCN must evaluate the functions fi (i.e., the derivatives yi′), for i=1,2,…,n, at a general point x.
The specification of FCN is:
SUBROUTINE FCN ( X, Y, F)
REAL (KIND=nag_wp) X, Y(*), F(*)
In the description of the arguments of D02GAF below, n denotes the actual value of N in the call of D02GAF.
1:   X – REAL (KIND=nag_wp)Input
On entry: x, the value of the argument.
2:   Y* – REAL (KIND=nag_wp) arrayInput
On entry: yi, for i=1,2,…,n, the value of the argument.
3:   F* – REAL (KIND=nag_wp) arrayOutput
On exit: the values of fi, for i=1,2,…,n.
FCN must either be a module subprogram USEd by, or declared as EXTERNAL in, the (sub)program from which D02GAF is called. Arguments denoted as Input must not be changed by this procedure.
8:   MNP – INTEGERInput
On entry: the maximum permitted number of mesh points.
Constraint: MNP≥32.
9:   X MNP – REAL (KIND=nag_wp) arrayInput/Output
On entry: if NP≥4 (see NP), the first NP elements must define an initial mesh. Otherwise the elements of X need not be set.
Constraint:
A=X 1<X 2<⋯<X NP=B,   NP≥4. (3)
On exit: X 1,X 2,…,X NP define the final mesh (with the returned value of NP) satisfying the relation (3).
10:   Y NMNP – REAL (KIND=nag_wp) arrayOutput
On exit: the approximate solution zj xi satisfying (2), on the final mesh, that is
Y ji=zj xi,  i=1,2,…,NP​ and ​j=1,2,…,n,
where NP is the number of points in the final mesh.
The remaining columns of Y are not used.
11:   NP – INTEGERInput/Output
On entry: determines whether a default or user-supplied mesh is used.
NP=0
A default value of 4 for NP and a corresponding equispaced mesh X 1,X 2,…,X NP are used.
NP≥4
You must define an initial mesh using the array X as described.
Constraint: NP=0 or 4≤NP≤MNP.
On exit: the number of points in the final (returned) mesh.
12:   W LW – REAL (KIND=nag_wp) arrayWorkspace
13:   LW – INTEGERInput
On entry: the dimension of the array W as declared in the (sub)program from which D02GAF is called.
Constraint: LW≥MNP×3⁢N 2+6⁢N+2+4⁢N 2+4⁢N.
14:   IW LIW – INTEGER arrayWorkspace
15:   LIW – INTEGERInput
On entry: the dimension of the array IW as declared in the (sub)program from which D02GAF is called.
Constraint: LIW≥MNP×2⁢N+1+N 2+4⁢N+2.
16:   IFAIL – INTEGERInput/Output
For this routine, the normal use of IFAIL is extended to control the printing of error and warning messages as well as specifying hard or soft failure (see Section 3.4 in How to Use the NAG Library and its Documentation).
On entry: IFAIL must be set to a value with the decimal expansion cba, where each of the decimal digits c, b and a must have a value of 0 or 1.
a=0 | specifies hard failure, otherwise soft failure;
b=0 | suppresses error messages, otherwise error messages will be printed (see Section 6);
c=0 | suppresses warning messages, otherwise warning messages will be printed (see Section 6).
The recommended value for inexperienced users is 110 (i.e., hard failure with all messages printed).
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
One or more of the arguments N, TOL, NP, MNP, LW or LIW has been incorrectly set, or B≤A, or the condition (3) on X is not satisfied, or the number of known boundary values (specified by V) is not N.
IFAIL=2
The Newton iteration has failed to converge. This could be due to there being too few points in the initial mesh or to the initial approximate solution being too inaccurate. If this latter reason is suspected you should use D02RAF instead. If the warning ‘Jacobian matrix is singular’ is printed this could be due to specifying zero estimated boundary values and these should be varied. This warning could also be printed in the unlikely event of the Jacobian matrix being calculated inaccurately. If you cannot make changes to prevent the warning then D02RAF should be used.
IFAIL=3
The Newton iteration has reached round-off level. It could be, however, that the answer returned is satisfactory. This error might occur if too much accuracy is requested.
IFAIL=4
A finer mesh is required for the accuracy requested; that is MNP is not large enough.
IFAIL=5
A serious error has occurred in a call to D02GAF. Check all array subscripts and subroutine argument lists in calls to D02GAF. Seek expert help.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

The solution returned by the routine will be accurate to your tolerance as defined by the relation (2) except in extreme circumstances. If too many points are specified in the initial mesh, the solution may be more accurate than requested and the error may not be approximately equidistributed.

8 Parallelism and Performance

D02GAF is not thread safe and should not be called from a multithreaded user program. Please see Section 3.12.1 in How to Use the NAG Library and its Documentation for more information on thread safety.
D02GAF is not threaded in any implementation.

9 Further Comments

The time taken by D02GAF depends on the difficulty of the problem, the number of mesh points (and meshes) used, the number of Newton iterations and the number of deferred corrections.
You are strongly recommended to set IFAIL to obtain self-explanatory error messages, and also monitoring information about the course of the computation. You may select the unit numbers on which this output is to appear by calls of X04AAF (for error messages) or X04ABF (for monitoring information) – see Section 10 for an example. Otherwise the default unit numbers will be used, as specified in the Users' Note.
A common cause of convergence problems in the Newton iteration is that you have specified too few points in the initial mesh. Although the routine adds points to the mesh to improve accuracy it is unable to do so until the solution on the initial mesh has been calculated in the Newton iteration.
If you specify zero known and estimated boundary values, the routine constructs a zero initial approximation and in many cases the Jacobian is singular when evaluated for this approximation, leading to the breakdown of the Newton iteration.
You may be unable to provide a sufficiently good choice of initial mesh and estimated boundary values, and hence the Newton iteration may never converge. In this case the continuation facility provided in D02RAF is recommended.
In the case where you wish to solve a sequence of similar problems, the final mesh from solving one case is strongly recommended as the initial mesh for the next.

10 Example

This example solves the differential equation
y′′′=-y y′′-β 1-y′2
with boundary conditions
y 0=y′0= 0,   y′10=1
for β=0.0 and β=0.2 to an accuracy specified by TOL=1.0E−3. We solve first the simpler problem with β=0.0 using an equispaced mesh of 26 points and then we solve the problem with β=0.2 using the final mesh from the first problem.
Note the call to X04ABF prior to the call to D02GAF.

10.1 Program Text

Program Text (d02gafe.f90)

10.2 Program Data

Program Data (d02gafe.d)

10.3 Program Results

Program Results (d02gafe.r)

GnuplotProduced by GNUPLOT 4.6 patchlevel 3 0 1 2 3 4 5 6 7 8 9 10 0 2 4 6 8 10 Solution x Example Program Two-point Boundary-value Problem using Deferred Correction Technique (β = 0.0) y y' y'' gnuplot_plot_1 gnuplot_plot_2 gnuplot_plot_3
GnuplotProduced by GNUPLOT 4.6 patchlevel 3 0 1 2 3 4 5 6 7 8 9 10 0 2 4 6 8 10 Solution x Two-point Boundary-value Problem using Deferred Correction Technique (β = 0.2) y y' y'' gnuplot_plot_1 gnuplot_plot_2 gnuplot_plot_3
D02 Chapter Contents
D02 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


D02GBF : NAG Library, Mark 26

D02 Chapter Contents
D02 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

D02GBF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

D02GBF solves a general linear two-point boundary value problem for a system of ordinary differential equations, using a deferred correction technique.

2 Specification

SUBROUTINE D02GBF ( A, B, N, TOL, FCNF, FCNG, C, D, GAM, MNP, X, Y, NP, W, LW, IW, LIW, IFAIL)
INTEGER | N, MNP, NP, LW, IW(LIW), LIW, IFAIL
REAL (KIND=nag_wp) | A, B, TOL, C(N,N), D(N,N), GAM(N), X(MNP), Y(N,MNP), W(LW)
EXTERNAL | FCNF, FCNG

3 Description

D02GBF solves a linear two-point boundary value problem for a system of n ordinary differential equations in the interval [a,b]. The system is written in the form
y′=F x y+g x (1)
and the boundary conditions are written in the form
Cy a+Dy b=γ . (2)
Here F x, C and D are n by n matrices, and g x and γ are n-component vectors. The approximate solution to (1) and (2) is found using a finite difference method with deferred correction. The algorithm is a specialization of that used in subroutine D02RAF which solves a nonlinear version of (1) and (2). The nonlinear version of the algorithm is described fully in Pereyra (1979).
You supply an absolute error tolerance and may also supply an initial mesh for the construction of the finite difference equations (alternatively a default mesh is used). The algorithm constructs a solution on a mesh defined by adding points to the initial mesh. This solution is chosen so that the error is everywhere less than your tolerance and so that the error is approximately equidistributed on the final mesh. The solution is returned on this final mesh.
If the solution is required at a few specific points then these should be included in the initial mesh. If, on the other hand, the solution is required at several specific points, then you should use the interpolation routines provided in Chapter E01 if these points do not themselves form a convenient mesh.

4 References

Pereyra V (1979) PASVA3: An adaptive finite-difference Fortran program for first order nonlinear, ordinary boundary problems Codes for Boundary Value Problems in Ordinary Differential Equations. Lecture Notes in Computer Science (eds B Childs, M Scott, J W Daniel, E Denman and P Nelson) 76 Springer–Verlag

5 Arguments

1:   A – REAL (KIND=nag_wp)Input
On entry: a, the left-hand boundary point.
2:   B – REAL (KIND=nag_wp)Input
On entry: b, the right-hand boundary point.
Constraint: B>A.
3:   N – INTEGERInput
On entry: the number of equations; that is n is the order of system (1).
Constraint: N≥2.
4:   TOL – REAL (KIND=nag_wp)Input
On entry: a positive absolute error tolerance. If
a=x 1<x 2<⋯<xNP=b
is the final mesh, z x is the approximate solution from D02GBF and y x is the true solution of equations (1) and (2) then, except in extreme cases, it is expected that
z-y≤TOL (3)
where
u = max 1≤i≤N max 1≤j≤NP ui xj .
Constraint: TOL>0.0.
5:   FCNF – SUBROUTINE, supplied by the user.External Procedure
FCNF must evaluate the matrix F x in (1) at a general point x.
The specification of FCNF is:
SUBROUTINE FCNF ( X, F)
REAL (KIND=nag_wp) X, F(*)
In the description of the arguments of D02GBF below, n denotes the actual value of N in the call of D02GBF.
1:   X – REAL (KIND=nag_wp)Input
On entry: x, the value of the independent variable.
2:   F* – REAL (KIND=nag_wp) arrayOutput
On exit: F n×i-1+j must contain the i,jth element of the matrix F x, for i=1,2,…,n and j=1,2,…,n. (See Section 10 for an example.)
FCNF must either be a module subprogram USEd by, or declared as EXTERNAL in, the (sub)program from which D02GBF is called. Arguments denoted as Input must not be changed by this procedure.
6:   FCNG – SUBROUTINE, supplied by the user.External Procedure
FCNG must evaluate the vector g x in (1) at a general point x.
The specification of FCNG is:
SUBROUTINE FCNG ( X, G)
REAL (KIND=nag_wp) X, G(*)
In the description of the arguments of D02GBF below, n denotes the actual value of N in the call of D02GBF.
1:   X – REAL (KIND=nag_wp)Input
On entry: x, the value of the independent variable.
2:   G* – REAL (KIND=nag_wp) arrayOutput
On exit: the ith element of the vector g x, for i=1,2,…,n. (See Section 10 for an example.)
FCNG must either be a module subprogram USEd by, or declared as EXTERNAL in, the (sub)program from which D02GBF is called. Arguments denoted as Input must not be changed by this procedure.
7:   C NN – REAL (KIND=nag_wp) arrayInput/Output
8:   D NN – REAL (KIND=nag_wp) arrayInput/Output
9:   GAM N – REAL (KIND=nag_wp) arrayInput/Output
On entry: the arrays C and D must be set to the matrices C and D in (2)). GAM must be set to the vector γ in (2).
On exit: the rows of C and D and the components of GAM are reordered so that the boundary conditions are in the order:
(i) | conditions on y a only;
(ii) | condition involving y a and y b; and
(iii) | conditions on y b only.
The routine will be slightly more efficient if the arrays C, D and GAM are ordered in this way before entry, and in this event they will be unchanged on exit.
Note that the problems (1) and (2) must be of boundary value type, that is neither C nor D may be identically zero. Note also that the rank of the matrix C,D must be n for the problem to be properly posed. Any violation of these conditions will lead to an error exit.
10:   MNP – INTEGERInput
On entry: the maximum permitted number of mesh points.
Constraint: MNP≥32.
11:   X MNP – REAL (KIND=nag_wp) arrayInput/Output
On entry: if NP≥4 (see NP), the first NP elements must define an initial mesh. Otherwise the elements of x need not be set.
Constraint:
A=X 1<X 2<⋯<X NP=B,   NP≥4 . (4)
On exit: X 1,X 2,…,X NP define the final mesh (with the returned value of NP) satisfying the relation (4).
12:   Y NMNP – REAL (KIND=nag_wp) arrayOutput
On exit: the approximate solution z x satisfying (3), on the final mesh, that is
Y ji=zj xi,  i=1,2,…,NP​ and ​j=1,2,…,n
where NP is the number of points in the final mesh.
The remaining columns of Y are not used.
13:   NP – INTEGERInput/Output
On entry: determines whether a default mesh or user-supplied mesh is used.
NP=0
A default value of 4 for NP and a corresponding equispaced mesh X 1,X 2,…,X NP are used.
NP≥4
You must define an initial mesh X as in (4).
On exit: the number of points in the final (returned) mesh.
14:   W LW – REAL (KIND=nag_wp) arrayWorkspace
15:   LW – INTEGERInput
On entry: the dimension of the array W as declared in the (sub)program from which D02GBF is called.
Constraint: LW≥MNP×3⁢N 2+5⁢N+2+3⁢N 2+5⁢N.
16:   IW LIW – INTEGER arrayWorkspace
17:   LIW – INTEGERInput
On entry: the dimension of the array IW as declared in the (sub)program from which D02GBF is called.
Constraint: LIW≥MNP×2⁢N+1+N.
18:   IFAIL – INTEGERInput/Output
For this routine, the normal use of IFAIL is extended to control the printing of error and warning messages as well as specifying hard or soft failure (see Section 3.4 in How to Use the NAG Library and its Documentation).
On entry: IFAIL must be set to a value with the decimal expansion cba, where each of the decimal digits c, b and a must have a value of 0 or 1.
a=0 | specifies hard failure, otherwise soft failure;
b=0 | suppresses error messages, otherwise error messages will be printed (see Section 6);
c=0 | suppresses warning messages, otherwise warning messages will be printed (see Section 6).
The recommended value for inexperienced users is 110 (i.e., hard failure with all messages printed).
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
One or more of the arguments N, TOL, NP, MNP, LW or LIW is incorrectly set, B≤A or the condition (4) on X is not satisfied.
IFAIL=2
There are three possible reasons for this error exit to be taken:
(i) | one of the matrices C or D is identically zero (that is, the problem is of initial value and not boundary value type). In this case, IW 1=0 on exit;
(ii) | a row of C and the corresponding row of D are identically zero (that is, the boundary conditions are rank deficient). In this case, on exit IW 1 contains the index of the first such row encountered; and
(iii) | more than n of the columns of the n by 2 n matrix C,D are identically zero (that is, the boundary conditions are rank deficient). In this case, on exit IW 1 contains minus the number of non-identically zero columns.
IFAIL=3
The routine has failed to find a solution to the specified accuracy. There are a variety of possible reasons including:
(i) | the boundary conditions are rank deficient, which may be indicated by the message that the Jacobian is singular. However this is an unlikely explanation for the error exit as all rank deficient boundary conditions should lead instead to error exits with either IFAIL=2 or 5; see also (iv);
(ii) | not enough mesh points are permitted in order to attain the required accuracy. This is indicated by NP=MNP on return from a call to D02GBF. This difficulty may be aggravated by a poor initial choice of mesh points;
(iii) | the accuracy requested cannot be attained on the computer being used; and
(iv) | an unlikely combination of values of Fx has led to a singular Jacobian. The error should not persist if more mesh points are allowed.
IFAIL=4
A serious error has occurred in a call to D02GBF. Check all array subscripts and subroutine argument lists in calls to D02GBF. Seek expert help.
IFAIL=5
There are two possible reasons for this error exit which occurs when checking the rank of the boundary conditions by reduction to a row echelon form:
(i) | at least one row of the n by 2 n matrix C,D is a linear combination of the other rows and hence the boundary conditions are rank deficient. The index of the first such row encountered is given by IW 1 on exit; and
(ii) | as (i) but the rank deficiency implied by this error exit has only been determined up to a numerical tolerance. Minus the index of the first such row encountered is given by IW 1 on exit.
In case (ii) there is some doubt as to the rank deficiency of the boundary conditions. However even if the boundary conditions are not rank deficient they are not posed in a suitable form for use with this routine.
For example, if
C= 1 0 1 ε ,  D= 1 0 1 0 ,  γ= γ 1 γ 2
and ε is small enough, this error exit is likely to be taken. A better form for the boundary conditions in this case would be
C= 1 0 0 1 ,  D= 1 0 0 0 ,  γ= γ 1 ε-1 γ 2-γ 1 .
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

The solution returned by the routine will be accurate to your tolerance as defined by the relation (3) except in extreme circumstances. If too many points are specified in the initial mesh, the solution may be more accurate than requested and the error may not be approximately equidistributed.

8 Parallelism and Performance

D02GBF is not thread safe and should not be called from a multithreaded user program. Please see Section 3.12.1 in How to Use the NAG Library and its Documentation for more information on thread safety.
D02GBF makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The time taken by D02GBF depends on the difficulty of the problem, the number of mesh points (and meshes) used and the number of deferred corrections.
You are strongly recommended to set IFAIL to obtain self-explanatory error messages, and also monitoring information about the course of the computation. You may select the unit numbers on which this output is to appear by calls of X04AAF (for error messages) or X04ABF (for monitoring information) – see Section 10 for an example. Otherwise the default unit numbers will be used, as specified in the Users' Note.
In the case where you wish to solve a sequence of similar problems, the final mesh from solving one case is strongly recommended as the initial mesh for the next.

10 Example

This example solves the problem (written as a first-order system)
ε y′′+y′=0
with boundary conditions
y 0=0,  y 1=1
for the cases ε=10-1 and ε=10-2 using the default initial mesh in the first case, and the final mesh of the first case as initial mesh for the second (more difficult) case. We give the solution and the error at each mesh point to illustrate the accuracy of the method given the accuracy request TOL=1.0E−3.
Note the call to X04ABF prior to the call to D02GBF.

10.1 Program Text

Program Text (d02gbfe.f90)

10.2 Program Data

Program Data (d02gbfe.d)

10.3 Program Results

Program Results (d02gbfe.r)

GnuplotProduced by GNUPLOT 4.6 patchlevel 3 0 0.2 0.4 0.6 0.8 1 0 0.2 0.4 0.6 0.8 1 Solution x Example Program Solution to Simple Second-order Problem ε = 0.1 ε = 0.01 gnuplot_plot_1 gnuplot_plot_2
D02 Chapter Contents
D02 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


D02HAF : NAG Library, Mark 26

D02 Chapter Contents
D02 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

D02HAF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

D02HAF solves a two-point boundary value problem for a system of ordinary differential equations, using a Runge–Kutta–Merson method and a Newton iteration in a shooting and matching technique.

2 Specification

SUBROUTINE D02HAF ( U, V, N, A, B, TOL, FCN, SOLN, M1, W, SDW, IFAIL)
INTEGER | N, M1, SDW, IFAIL
REAL (KIND=nag_wp) | U(N,2), V(N,2), A, B, TOL, SOLN(N,M1), W(N,SDW)
EXTERNAL | FCN

3 Description

D02HAF solves a two-point boundary value problem for a system of n ordinary differential equations in the range a,b. The system is written in the form:
yi′=fi x,y 1,y 2,…,yn,  i=1,2,…,n (1)
and the derivatives fi are evaluated by FCN. Initially, n boundary values of the variables yi must be specified, some at a and some at b. You must supply estimates of the remaining n boundary values (called parameters below); the subroutine corrects these by a form of Newton iteration. It also calculates the complete solution on an equispaced mesh if required.
Starting from the known and estimated values of yi at a, the subroutine integrates the equations from a to b (using a Runge–Kutta–Merson method). The differences between the values of yi at b from integration and those specified initially should be zero for the true solution. (These differences are called residuals below.) The subroutine uses a generalized Newton method to reduce the residuals to zero, by calculating corrections to the estimated boundary values. This process is repeated iteratively until convergence is obtained, or until the routine can no longer reduce the residuals. See Hall and Watt (1976) for a simple discussion of shooting and matching techniques.

4 References

Hall G and Watt J M (ed.) (1976) Modern Numerical Methods for Ordinary Differential Equations Clarendon Press, Oxford

5 Arguments

1:   U N 2 – REAL (KIND=nag_wp) arrayInput/Output
On entry: U i 1 must be set to the known or estimated value of yi at a and U i 2 must be set to the known or estimated value of yi at b, for i=1,2,…,n.
On exit: the known values unaltered, and corrected values of the estimates, unless an error has occurred. If an error has occurred, U contains the known values and the latest values of the estimates.
2:   V N 2 – REAL (KIND=nag_wp) arrayInput
On entry: V ij must be set to 0.0 if U ij is a known value and to 1.0 if U ij is an estimated value, for i=1,2,…,n and j=1,2.
Constraint: precisely n of the V ij must be set to 0.0, i.e., precisely n of the U ij must be known values, and these must not be all at a or all at b.
3:   N – INTEGERInput
On entry: n, the number of equations.
Constraint: N≥1.
4:   A – REAL (KIND=nag_wp)Input
On entry: a, the initial point of the interval of integration.
5:   B – REAL (KIND=nag_wp)Input
On entry: b, the final point of the interval of integration.
6:   TOL – REAL (KIND=nag_wp)Input
On entry: must be set to a small quantity suitable for:
(a) | testing the local error in yi during integration,
(b) | testing for the convergence of yi at b,
(c) | calculating the perturbation in estimated boundary values for yi, which are used to obtain the approximate derivatives of the residuals for use in the Newton iteration.
You are advised to check your results by varying TOL.
Constraint: TOL>0.0.
7:   FCN – SUBROUTINE, supplied by the user.External Procedure
FCN must evaluate the functions fi (i.e., the derivatives yi′), for i=1,2,…,n, at a general point x.
The specification of FCN is:
SUBROUTINE FCN ( X, Y, F)
REAL (KIND=nag_wp) X, Y(*), F(*)
In the description of the arguments of D02HAF below, n denotes the actual value of N in the call of D02HAF.
1:   X – REAL (KIND=nag_wp)Input
On entry: x, the value of the argument.
2:   Y* – REAL (KIND=nag_wp) arrayInput
On entry: yi, for i=1,2,…,n, the value of the argument.
3:   F* – REAL (KIND=nag_wp) arrayOutput
On exit: the values of fi x, for i=1,2,…,n.
FCN must either be a module subprogram USEd by, or declared as EXTERNAL in, the (sub)program from which D02HAF is called. Arguments denoted as Input must not be changed by this procedure.
8:   SOLN NM1 – REAL (KIND=nag_wp) arrayOutput
On exit: the solution when M1>1.
9:   M1 – INTEGERInput
On entry: a value which controls output.
M1=1
The final solution is not evaluated.
M1>1
The final values of yi at interval b-a/M1-1 are calculated and stored in the array SOLN by columns, starting with values yi at a stored in SOLN i 1, for i=1,2,…,n.
Constraint: M1≥1.
10:   W NSDW – REAL (KIND=nag_wp) arrayOutput
On exit: if IFAIL=2, 3, 4 or 5, W i 1, for i=1,2,…,n, contains the solution at the point where the integration fails and the point of failure is returned in W 12.
11:   SDW – INTEGERInput
On entry: the second dimension of the array W as declared in the (sub)program from which D02HAF is called.
Constraint: SDW≥3⁢N+17+max 11,N.
12:   IFAIL – INTEGERInput/Output
For this routine, the normal use of IFAIL is extended to control the printing of error and warning messages as well as specifying hard or soft failure (see Section 3.4 in How to Use the NAG Library and its Documentation).
On entry: IFAIL must be set to a value with the decimal expansion cba, where each of the decimal digits c, b and a must have a value of 0 or 1.
a=0 | specifies hard failure, otherwise soft failure;
b=0 | suppresses error messages, otherwise error messages will be printed (see Section 6);
c=0 | suppresses warning messages, otherwise warning messages will be printed (see Section 6).
The recommended value for inexperienced users is 110 (i.e., hard failure with all messages printed).
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
One or more of the arguments V, N, M1, SDW, or TOL is incorrectly set.
IFAIL=2
The step length for the integration is too short whilst calculating the residual (see Section 9).
IFAIL=3
No initial step length could be chosen for the integration whilst calculating the residual.
Note: IFAIL=2 or 3 can occur due to choosing too small a value for TOL or due to choosing the wrong direction of integration. Try varying TOL and interchanging a and b. These error exits can also occur for very poor initial estimates of the unknown initial values and, in extreme cases, because D02HAF cannot be used to solve the problem posed.
IFAIL=4
As for IFAIL=2 but the error occurred when calculating the Jacobian of the derivatives of the residuals with respect to the parameters.
IFAIL=5
As for IFAIL=3 but the error occurred when calculating the derivatives of the residuals with respect to the parameters.
IFAIL=6
The calculated Jacobian has an insignificant column.
Note: IFAIL=4, 5 or 6 usually indicate a badly scaled problem. You may vary the size of TOL or change to one of the more general routines D02HBF or D02SAF which afford more control over the calculations.
IFAIL=7
The linear algebra routine (F08KBF (DGESVD)) used has failed. This error exit should not occur and can be avoided by changing the estimated initial values.
IFAIL=8
The Newton iteration has failed to converge.
Note: IFAIL=8 can indicate poor initial estimates or a very difficult problem. Consider varying TOL if the residuals are small in the monitoring output. If the residuals are large try varying the initial estimates.
IFAIL=9
IFAIL=10
IFAIL=11
IFAIL=12
IFAIL=13
Indicates that a serious error has occurred in an internal call. Check all array subscripts and subroutine argument lists in calls to D02HAF. Seek expert help.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

If the process converges, the accuracy to which the unknown parameters are determined is usually close to that specified by you; the solution, if requested, may be determined to a required accuracy by varying TOL.

8 Parallelism and Performance

D02HAF is not thread safe and should not be called from a multithreaded user program. Please see Section 3.12.1 in How to Use the NAG Library and its Documentation for more information on thread safety.
D02HAF makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The time taken by D02HAF depends on the complexity of the system, and on the number of iterations required. In practice, integration of the differential equations is by far the most costly process involved.
Wherever it occurs in the routine, the error argument TOL is used in ‘mixed’ form; that is TOL always occurs in expressions of the form TOL×1+yi. Though not ideal for every application, it is expected that this mixture of absolute and relative error testing will be adequate for most purposes.
You are strongly recommended to set IFAIL to obtain self-explanatory error messages, and also monitoring information about the course of the computation. You may select the unit numbers on which this output is to appear by calls of X04AAF (for error messages) or X04ABF (for monitoring information) – see Section 10 for an example. Otherwise the default unit numbers will be used, as specified in the Users' Note. The monitoring information produced at each iteration includes the current parameter values, the residuals and 2-norms: a basic norm and a current norm. At each iteration the aim is to find parameter values which make the current norm less than the basic norm. Both these norms should tend to zero as should the residuals. (They would all be zero if the exact parameters were used as input.) For more details, you may consult the specification of D02SAF, and especially the description of the argument MONIT there.
The computing time for integrating the differential equations can sometimes depend critically on the quality of the initial estimates. If it seems that too much computing time is required and, in particular, if the values of the residuals printed by the monitoring routine are much larger than the expected values of the solution at b, then the coding of FCN should be checked for errors. If no errors can be found, an independent attempt should be made to improve the initial estimates. In practical problems it is not uncommon for the differential equation to have a singular point at one or both ends of the range. Suppose a is a singular point; then the derivatives yi′ in (1) (in Section 3) cannot be evaluated at a, usually because one or more of the expressions for fi give overflow. In such a case it is necessary for you to take a a short distance away from the singularity, and to find values for yi at the new value of a (e.g., use the first one or two terms of an analytical (power series) solution). You should experiment with the new position of a; if it is taken too close to the singular point, the derivatives fi will be inaccurate, and the routine may sometimes fail with IFAIL=2 or 3 or, in extreme cases, with an overflow condition. A more general treatment of singular solutions is provided by the subroutine D02HBF.
Another difficulty which often arises in practice is the case when one end of the range, b say, is at infinity. You must approximate the end point by taking a finite value for b, which is obtained by estimating where the solution will reach its asymptotic state. The estimate can be checked by repeating the calculation with a larger value of b. If b is very large, and if the matching point is also at b, the numerical solution may suffer a considerable loss of accuracy in integrating across the range, and the program may fail with IFAIL=6 or 8. (In the former case, solutions from all initial values at a are tending to the same curve at infinity.) The simplest remedy is to try to solve the equations with a smaller value of b, and then to increase b in stages, using each solution to give boundary value estimates for the next calculation. For problems where some terms in the asymptotic form of the solution are known, D02HBF will be more successful.
If the unknown quantities are not boundary values, but are eigenvalues or the length of the range or some other parameters occurring in the differential equations, D02HBF may be used.

10 Example

This example finds the angle at which a projectile must be fired for a given range.
The differential equations are:
y′ = tan⁡ϕ v′ = -0.032 tan⁡ϕ v - 0.02 v cos⁡ϕ ϕ′ = -0.032 v 2 ,
with the following boundary conditions:
y= 0, v= 0.5 at   x= 0, y= 0 at   x= 5.
The remaining boundary conditions are estimated as:
ϕ=1.15 at  x=0, ϕ=1.2, v=0.46 at  x=5.
We write y=Z 1, v=Z 2, ϕ=Z 3. To check the accuracy of the results the problem is solved twice with TOL=5.0E−3 and 5.0E−4 respectively. Note the call to X04ABF before the call to D02HAF.

10.1 Program Text

Program Text (d02hafe.f90)

10.2 Program Data

Program Data (d02hafe.d)

10.3 Program Results

Program Results (d02hafe.r)

GnuplotProduced by GNUPLOT 4.6 patchlevel 3 −1.5 −1 −0.5 0 0.5 1 1.5 2 2.5 3 3.5 0 1 2 3 4 5 Solution x Example Program Solution of Two-point Boundary-value Problem using Runge-Kutta-Merson and Newton Correction in a Shooting Method height velocity angle gnuplot_plot_1 gnuplot_plot_2 gnuplot_plot_3
D02 Chapter Contents
D02 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


D02HBF : NAG Library, Mark 26

D02 Chapter Contents
D02 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

D02HBF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

D02HBF solves a two-point boundary value problem for a system of ordinary differential equations, using initial value techniques and Newton iteration; it generalizes subroutine D02HAF to include the case where parameters other than boundary values are to be determined.

2 Specification

SUBROUTINE D02HBF ( P, N1, PE, E, N, SOLN, M1, FCN, BC, RANGE, W, SDW, IFAIL)
INTEGER | N1, N, M1, SDW, IFAIL
REAL (KIND=nag_wp) | P(N1), PE(N1), E(N), SOLN(N,M1), W(N,SDW)
EXTERNAL | FCN, BC, RANGE

3 Description

D02HBF solves a two-point boundary value problem by determining the unknown parameters p 1,p 2,…,p n 1 of the problem. These parameters may be, but need not be, boundary values; they may include eigenvalue parameters in the coefficients of the differential equations, length of the range of integration, etc. The notation and methods used are similar to those of D02HAF and you are advised to study this first. (The parameters p 1,p 2,…,p n 1 correspond precisely to the unknown boundary conditions in D02HAF.) It is assumed that we have a system of n first-order ordinary differential equations of the form:
d yi dx =fi x,y 1,y 2,…,yn,  i=1,2,…,n,
and that the derivatives fi are evaluated by FCN. The system, including the boundary conditions given by BC and the range of integration given by RANGE, involves the n 1 unknown parameters p 1,p 2,…,p n 1 which are to be determined, and for which initial estimates must be supplied. The number of unknown parameters n 1 must not exceed the number of equations n. If n 1<n, we assume that n-n 1 equations of the system are not involved in the matching process. These are usually referred to as ‘driving equations’; they are independent of the parameters and of the solutions of the other n 1 equations. In numbering the equations for FCN, the driving equations must be put first.
The estimated values of the parameters are corrected by a form of Newton iteration. The Newton correction on each iteration is calculated using a Jacobian matrix whose i,jth element depends on the derivative of the ith component of the solution, yi, with respect to the jth parameter, pj. This matrix is calculated by a simple numerical differentiation technique which requires n 1 evaluations of the differential system.
If the argument IFAIL is set appropriately, the routine automatically prints messages to inform you of the flow of the calculation. These messages are discussed in detail in Section 9.
D02HBF is a simplified version of D02SAF which is described in detail in Gladwell (1979).

4 References

Gladwell I (1979) The development of the boundary value codes in the ordinary differential equations chapter of the NAG Library Codes for Boundary Value Problems in Ordinary Differential Equations. Lecture Notes in Computer Science (eds B Childs, M Scott, J W Daniel, E Denman and P Nelson) 76 Springer–Verlag

5 Arguments

You are strongly recommended to read Sections 3 and 9 in conjunction with this section.
1:   P N1 – REAL (KIND=nag_wp) arrayInput/Output
On entry: an estimate for the ith argument, pi, for i=1,2,…,n 1.
On exit: the corrected value for the ith argument, unless an error has occurred, when it contains the last calculated value of the argument.
2:   N1 – INTEGERInput
On entry: n 1, the number of arguments.
Constraint: 1≤N1≤N.
3:   PE N1 – REAL (KIND=nag_wp) arrayInput
On entry: the elements of PE must be given small positive values. The element PE i is used
(i) | in the convergence test on the ith argument in the Newton iteration, and
(ii) | in perturbing the ith argument when approximating the derivatives of the components of the solution with respect to this argument for use in the Newton iteration.
The elements PE i should not be chosen too small. They should usually be several orders of magnitude larger than machine precision.
Constraint: PE i>0.0, for i=1,2,…,N1.
4:   E N – REAL (KIND=nag_wp) arrayInput
On entry: the elements of E must be given positive values. The element E i is used in the bound on the local error in the ith component of the solution yi during integration.
The elements E i should not be chosen too small. They should usually be several orders of magnitude larger than machine precision.
Constraint: E i>0.0, for i=1,2,…,N.
5:   N – INTEGERInput
On entry: n, the total number of differential equations.
Constraint: N≥N1.
6:   SOLN NM1 – REAL (KIND=nag_wp) arrayOutput
On exit: the solution when M1>1.
7:   M1 – INTEGERInput
On entry: a value which controls exit values.
M1=1
The final solution is not calculated.
M1>1
The final values of the solution at interval (length of range)/M1-1 are calculated and stored sequentially in the array SOLN starting with the values of the solutions evaluated at the first end point (see RANGE) stored in the first column of SOLN.
Constraint: M1≥1.
8:   FCN – SUBROUTINE, supplied by the user.External Procedure
FCN must evaluate the functions fi (i.e., the derivatives yi′), for i=1,2,…,n, at a general point x.
The specification of FCN is:
SUBROUTINE FCN ( X, Y, F, P)
REAL (KIND=nag_wp) X, Y(*), F(*), P(*)
In the description of the arguments of D02HBF below, n and n1 denote the numerical values of N and N1 in the call of D02HBF.
1:   X – REAL (KIND=nag_wp)Input
On entry: x, the value of the argument.
2:   Y* – REAL (KIND=nag_wp) arrayInput
On entry: yi, for i=1,2,…,n, the value of the argument.
3:   F* – REAL (KIND=nag_wp) arrayOutput
On exit: the value of fi, for i=1,2,…,n. The fi may depend upon the parameters pj, for j=1,2,…,n 1. If there are any driving equations (see Section 3) then these must be numbered first in the ordering of the components of F in FCN.
4:   P* – REAL (KIND=nag_wp) arrayInput
On entry: the current estimate of the argument pi, for i=1,2,…,n 1.
FCN must either be a module subprogram USEd by, or declared as EXTERNAL in, the (sub)program from which D02HBF is called. Arguments denoted as Input must not be changed by this procedure.
9:   BC – SUBROUTINE, supplied by the user.External Procedure
BC must place in G1 and G2 the boundary conditions at a and b respectively (see RANGE).
The specification of BC is:
SUBROUTINE BC ( G1, G2, P)
REAL (KIND=nag_wp) G1(*), G2(*), P(*)
In the description of the arguments of D02HBF below, n and n1 denote the numerical values of N and N1 in the call of D02HBF.
1:   G1* – REAL (KIND=nag_wp) arrayOutput
On exit: the value of yi a, (where this may be a known value or a function of the parameters pj, for i=1,2,…,n and j=1,2,…,n 1).
2:   G2* – REAL (KIND=nag_wp) arrayOutput
On exit: the value of yi b, for i=1,2,…,n, (where these may be known values or functions of the parameters pj, for j=1,2,…,n 1). If n>n 1, so that there are some driving equations, then the first n-n 1 values of G2 need not be set since they are never used.
3:   P* – REAL (KIND=nag_wp) arrayInput
On entry: an estimate of the argument pi, for i=1,2,…,n 1.
BC must either be a module subprogram USEd by, or declared as EXTERNAL in, the (sub)program from which D02HBF is called. Arguments denoted as Input must not be changed by this procedure.
10:   RANGE – SUBROUTINE, supplied by the user.External Procedure
RANGE must evaluate the boundary points a and b, each of which may depend on the arguments p 1,p 2,…,p n 1. The integrations in the shooting method are always from a to b.
The specification of RANGE is:
SUBROUTINE RANGE ( A, B, P)
REAL (KIND=nag_wp) A, B, P(*)
In the description of the arguments of D02HBF below, n1 denotes the actual value of N1 in the call of D02HBF.
1:   A – REAL (KIND=nag_wp)Output
On exit: a, one of the boundary points.
2:   B – REAL (KIND=nag_wp)Output
On exit: the second boundary point, b. Note that B>A forces the direction of integration to be that of increasing x. If A and B are interchanged the direction of integration is reversed.
3:   P* – REAL (KIND=nag_wp) arrayInput
On entry: the current estimate of the ith argument, pi, for i=1,2,…,n 1.
RANGE must either be a module subprogram USEd by, or declared as EXTERNAL in, the (sub)program from which D02HBF is called. Arguments denoted as Input must not be changed by this procedure.
11:   W NSDW – REAL (KIND=nag_wp) arrayOutput
Used mainly for workspace.
On exit: with IFAIL=2, 3, 4 or 5 (see Section 6), W i 1, for i=1,2,…,n, contains the solution at the point x when the error occurred. W 12 contains x.
12:   SDW – INTEGERInput
On entry: the second dimension of the array W as declared in the (sub)program from which D02HBF is called.
Constraint: SDW≥3⁢N+14+max 11,N.
13:   IFAIL – INTEGERInput/Output
For this routine, the normal use of IFAIL is extended to control the printing of error and warning messages as well as specifying hard or soft failure (see Section 3.4 in How to Use the NAG Library and its Documentation).
On entry: IFAIL must be set to a value with the decimal expansion cba, where each of the decimal digits c, b and a must have a value of 0 or 1.
a=0 | specifies hard failure, otherwise soft failure;
b=0 | suppresses error messages, otherwise error messages will be printed (see Section 6);
c=0 | suppresses warning messages, otherwise warning messages will be printed (see Section 6).
The recommended value for inexperienced users is 110 (i.e., hard failure with all messages printed).
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
One or more of the arguments N, N1, M1, SDW, E or PE is incorrectly set.
IFAIL=2
The step length for the integration became too short whilst calculating the residual (see Section 9).
IFAIL=3
No initial step length could be chosen for the integration whilst calculating the residual.
Note: IFAIL=2 or 3 can occur due to choosing too small a value for E or due to choosing the wrong direction of integration. Try varying E and interchanging a and b. These error exits can also occur for very poor initial choices of the parameters in the array P and, in extreme cases, because D02HBF cannot be used to solve the problem posed.
IFAIL=4
As for IFAIL=2 but the error occurred when calculating the Jacobian.
IFAIL=5
As for IFAIL=3 but the error occurred when calculating the Jacobian.
IFAIL=6
The calculated Jacobian has an insignificant column. This can occur because a parameter pi is incorrectly entered when posing the problem.
Note: IFAIL=4, 5 or 6 usually indicate a badly scaled problem. You may vary the size of PE. Otherwise the use of the more general D02SAF which affords more control over the calculations is advised.
IFAIL=7
The linear algebra routine used (F08KBF (DGESVD)) has failed. This error exit should not occur and can be avoided by changing the initial estimates pi.
IFAIL=8
The Newton iteration has failed to converge. This can indicate a poor initial choice of parameters pi or a very difficult problem. Consider varying the elements PE i if the residuals are small in the monitoring output. If the residuals are large, try varying the initial parameters pi.
IFAIL=9
IFAIL=10
IFAIL=11
IFAIL=12
IFAIL=13
Indicates that a serious error has occurred in an internal call. Check all array subscripts and subroutine argument lists in the call to D02HBF. Seek expert help.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

If the process converges, the accuracy to which the unknown parameters are determined is usually close to that specified by you; the solution, if requested, may be determined to a required accuracy by varying E.

8 Parallelism and Performance

D02HBF is not thread safe and should not be called from a multithreaded user program. Please see Section 3.12.1 in How to Use the NAG Library and its Documentation for more information on thread safety.
D02HBF makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The time taken by D02HBF depends on the complexity of the system, and on the number of iterations required. In practice, integration of the differential equations is by far the most costly process involved.
Wherever they occur in the routine, the error arguments contained in the arrays E and PE are used in ‘mixed’ form; that is E i always occurs in expressions of the form
E i×1+yi
and PE i always occurs in expressions of the form
PE i×1+pi.
Though not ideal for every application, it is expected that this mixture of absolute and relative error testing will be adequate for most purposes.
You may determine a suitable direction of integration a to b and suitable values for E i by integrations with D02PEF. The best direction of integration is usually the direction of decreasing solutions.
You are strongly recommended to set IFAIL to obtain self-explanatory error messages, and also monitoring information about the course of the computation. You may select the unit numbers on which this output is to appear by calls of X04AAF (for error messages) or X04ABF (for monitoring information) – see Section 10 for an example. Otherwise the default unit numbers will be used, as specified in the Users' Note. The monitoring information produced at each iteration includes the current parameter values, the residuals and 2-norms: a basic norm and a current norm. At each iteration the aim is to find parameter values which make the current norm less than the basic norm. Both these norms should tend to zero as should the residuals. (They would all be zero if the exact parameters were used as input.) For more details, in particular about the other monitoring information printed, you are advised to consult the specification of D02SAF, and especially the description of the argument MONIT there.
The computing time for integrating the differential equations can sometimes depend critically on the quality of the initial estimates for the parameters pi. If it seems that too much computing time is required and, in particular, if the values of the residuals printed by the monitoring routine are much larger than the expected values of the solution at b, then the coding of FCN, BC and RANGE should be checked for errors. If no errors can be found, an independent attempt should be made to improve the initial estimates for pi.
The subroutine can be used to solve a very wide range of problems, for example:
(a) | eigenvalue problems, including problems where the eigenvalue occurs in the boundary conditions;
(b) | problems where the differential equations depend on some parameters which are to be determined so as to satisfy certain boundary conditions (see Example 2 in Section 10);
(c) | problems where one of the end points of the range of integration is to be determined as the point where a variable yi takes a particular value (see Example 2 in Section 10);
(d) | singular problems and problems on infinite ranges of integration where the values of the solution at a or b or both are determined by a power series or an asymptotic expansion (or a more complicated expression) and where some of the coefficients in the expression are to be determined (see Example 1 in Section 10); and
(e) | differential equations with certain terms defined by other independent (driving) differential equations.

10 Example

For this routine two examples are presented. There is a single example program for D02HBF, with a main program and the code to solve the two example problems given in Example 1 (EX1) and Example 2 (EX2).
Example 1 (EX1)
This example finds the solution of the differential equation
y′′=y 3-y′/2 x
on the range 0≤x≤16, with boundary conditions y 0=0.1 and y 16=1/6. We cannot use the differential equation at x=0 because it is singular, so we take a truncated power series expansion
y x=1/10+p 1×x/10+x/100
near the origin where p 1 is one of the parameters to be determined. We choose the interval as 0.1,16 and setting p 2=y′16, we can determine all the boundary conditions. We take X1=16. We write y=Y 1, y′=Y 2, and estimate PARAM 1=0.2, PARAM 2=0.0. Note the call to X04ABF before the call to D02HBF.
Example 2 (EX2)
This example finds the gravitational constant p 1 and the range p 2 over which a projectile must be fired to hit the target with a given velocity.
The differential equations are
y′ = tan⁡ϕ v′ = -p 1 sin⁡ϕ+0.00002⁢v 2 v cos⁡ϕ ϕ ′ = -p 1 v 2
on the range 0<x<p 2, with boundary conditions
y=0, v=500, ϕ=0.5 at x=0, y=0, v=450, ϕ=p 3 at x=p 2.
We write y=Y 1, v=Y 2, ϕ=Y 3. We estimate p 1=PARAM 1=32, p 2=PARAM 2=6000 and p 3=PARAM 3=0.54 (though this last estimate is not important).

10.1 Program Text

Program Text (d02hbfe.f90)

10.2 Program Data

Program Data (d02hbfe.d)

10.3 Program Results

Program Results (d02hbfe.r)

GnuplotProduced by GNUPLOT 4.6 patchlevel 3 0 0.02 0.04 0.06 0.08 0.1 0.12 0.14 0.16 0.18 0 2 4 6 8 10 12 14 16 0 0.02 0.04 0.06 0.08 0.1 0.12 0.14 0.16 0.18 Solution Derivative x Example Program 1 Parameterised Two-point Boundary-value Problem using Initial Value Techniques and Newton Iteration solution y(x) derivative y'(x) param(2) gnuplot_plot_1 gnuplot_plot_2
GnuplotProduced by GNUPLOT 4.6 patchlevel 3 0 100 200 300 400 500 600 700 800 900 0 1000 2000 3000 4000 5000 6000 −0.6 −0.4 −0.2 0 0.2 0.4 0.6 Height and Velocity Angle x Example Program 2 Find Gravitational Constant and Range Given Projectile Terminal Velocity height velocity angle gnuplot_plot_1 gnuplot_plot_2 gnuplot_plot_3
D02 Chapter Contents
D02 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


D02 Chapter Introduction : NAG Library, Mark 26

D02 Chapter Contents
NAG Library Manual

NAG Library Chapter Introduction

D02 – Ordinary Differential Equations

▸▿ Contents

1 Scope of the Chapter
▸▿ 2 Background to the Problems
2.1 Initial Value Problems
▸▿ 2.2 Boundary Value Problems
2.2.1 Collocation methods
2.2.2 Shooting methods
2.2.3 Finite difference methods
2.3 Chebyshev Collocation for Linear Differential Equations
2.4 Eigenvalue Problems
▸▿ 3 Recommendations on Choice and Use of Available Routines
▸▿ 3.1 Initial Value Problems
3.1.1 Runge–Kutta routines
3.1.2 Adams' routines
3.1.3 BDF routines
3.1.4 Runge–Kutta–Nystrom routines
▸▿ 3.2 Boundary Value Problems
3.2.1 Collocation methods
3.2.2 Shooting methods
3.2.3 Finite difference methods
3.2.4 Chebyshev integration method
3.3 Chebyshev Collocation Method
3.4 Eigenvalue Problems
3.5 Summary of Recommended Routines
4 Decision Trees
5 Functionality Index
6 Auxiliary Routines Associated with Library Routine Arguments
7 Routines Withdrawn or Scheduled for Withdrawal
8 References

1 Scope of the Chapter

This chapter is concerned with the numerical solution of ordinary differential equations. There are two main types of problem: those in which all boundary conditions are specified at one point (initial value problems), and those in which the boundary conditions are distributed between two or more points (boundary value problems and eigenvalue problems). Routines are available for initial value problems, two-point boundary value problems and Sturm–Liouville eigenvalue problems.

2 Background to the Problems

For most of the routines in this chapter a system of ordinary differential equations must be written in the form
y 1′=f 1 x,y 1,y 2,…,yn, y 2′=f 2 x,y 1,y 2,…,yn, ⋮ yn′=fn x,y 1,y 2,…,yn,
that is the system must be given in first-order form. The n dependent variables (also, the solution) y 1,y 2,…,yn are functions of the independent variable x, and the differential equations give expressions for the first derivatives yi′=d yi dx in terms of x and y 1,y 2,…,yn. For a system of n first-order equations, n associated boundary conditions are usually required to define the solution.
A more general system may contain derivatives of higher order, but such systems can almost always be reduced to the first-order form by introducing new variables. For example, suppose we have the third-order equation
z′′′+z z′′+k l-z′2=0.
We write y 1=z, y 2=z′, y 3=z′′, and the third-order equation may then be written as the system of first-order equations
y 1′=y 2 y 2′=y 3 y 3′=-y 1y 3-k l-y 22.
For this system n=3 and we require 3 boundary conditions in order to define the solution. These conditions must specify values of the dependent variables at certain points. For example, we have an initial value problem if the conditions are
y 1=0.1  at ​x=0 y 2=0.1  at ​x=0 y 3=0.1  at ​x=0.
These conditions would enable us to integrate the equations numerically from the point x=0 to some specified end point. We have a boundary value problem if the conditions are
y 1=0  at ​x=0 y 2=0  at ​x=0 y 2=1  at ​x=10.
These conditions would be sufficient to define a solution in the range 0≤x≤10, but the problem could not be solved by direct integration (see Section 2.2). More general boundary conditions are permitted in the boundary value case.
It is sometimes advantageous to solve higher-order systems directly. In particular, there is an initial value routine to solve a system of second-order ordinary differential equations of the special form
y 1′′=f 1 x,y 1,y 2,…,yn, y 2′′=f 2 x,y 1,y 2,…,yn, ⋮ yn′′=fn x,y 1,y 2,…,yn.
For this second-order system initial values of the derivatives of the dependent variables, yi′, for i=1,2,…,n, are required.
There is also a boundary value routine that can treat directly a mixed order system of ordinary differential equations.
There is a broader class of initial value problems known as differential algebraic systems which can be treated. Such a system may be defined as
y′ = f x,y,z 0 = g x,y,z
where y and f are vectors of length n and g and z are vectors of length m. The functions g represent the algebraic part of the system.
In addition implicit systems can also be solved, that is systems of the form
A x,y y′=f x,y
where A is a matrix of functions; such a definition can also incorporate algebraic equations. Note that general systems of this form may contain higher-order derivatives and that they can usually be transformed to first-order form, as above.

2.1 Initial Value Problems

To solve first-order systems, initial values of the dependent variables yi, for i=1,2,…,n, must be supplied at a given point, a. Also a point, b, at which the values of the dependent variables are required, must be specified. The numerical solution is then obtained by a step-by-step calculation which approximates values of the variables yi, for i=1,2,…,n, at finite intervals over the required range a,b. The routines in this chapter adjust the step length automatically to meet specified accuracy tolerances. Although the accuracy tests used are reliable over each step individually, in general an accuracy requirement cannot be guaranteed over a long range. For many problems there may be no serious accumulation of error, but for unstable systems small perturbations of the solution will often lead to rapid divergence of the calculated values from the true values. A simple check for stability is to carry out trial calculations with different tolerances; if the results differ appreciably the system is probably unstable. Over a short range, the difficulty may possibly be overcome by taking sufficiently small tolerances, but over a long range it may be better to try to reformulate the problem.
A special class of initial value problems are those for which the solutions contain rapidly decaying transient terms. Such problems are called stiff; an alternative way of describing them is to say that certain eigenvalues of the Jacobian matrix ∂fi ∂yj have large negative real parts when compared to others. These problems require special methods for efficient numerical solution; the methods designed for non-stiff problems when applied to stiff problems tend to be very slow, because they need small step lengths to avoid numerical instability. A full discussion is given in Hall and Watt (1976) and a discussion of the methods for stiff problems is given in Berzins et al. (1988).

2.2 Boundary Value Problems

In general, a system of nonlinear differential equations with boundary conditions at two or more points cannot be guaranteed to have a solution. The solution, if it exists, has to be determined iteratively. A comprehensive treatment of the numerical solution of boundary value problems can be found in Ascher et al. (1988) and Keller (1992). The methods for this chapter are discussed in Ascher et al. (1979), Ascher and Bader (1987) and Gladwell (1987).

2.2.1 Collocation methods

In the collocation method, the solution components are approximated by piecewise polynomials on a mesh. The coefficients of the polynomials form the unknowns to be computed. The approximation to the solution must satisfy the boundary conditions and the differential equations at collocation points in each mesh sub-interval. A modified Newton method is used to solve the nonlinear equations. The mesh is refined by trying to equidistribute the estimated error over the whole interval. An initial estimate of the solution across the mesh is required.

2.2.2 Shooting methods

In the shooting method, the unknown boundary values at the initial point are estimated to form an initial value problem, and the equations are then integrated to the final point. At the final point the computed solution and the known boundary conditions should be equal. The condition for equality gives a set of nonlinear equations for the estimated values, which can be solved by Newton's method or one of its variants. The iteration cannot be guaranteed to converge, but it is usually successful if
  • the system has a solution,
  • the system is not seriously unstable or very stiff for step-by-step solution, and
  • good initial estimates can be found for the unknown boundary conditions.
It may be necessary to simplify the problem and carry out some preliminary calculations, in order to obtain suitable starting values. A fuller discussion is given in Chapters 16, 17 and 18 of Hall and Watt (1976), Chapter 11 of Gladwell and Sayers (1980) and Chapter 8 of Gladwell (1979a).

2.2.3 Finite difference methods

If a boundary value problem seems insoluble by the above method and a good estimate for the solution of the problem is known at all points of the range then a finite difference method may be used. Finite difference equations are set up on a mesh of points and estimated values for the solution at the grid points are chosen. Using these estimated values as starting values a Newton iteration is used to solve the finite difference equations. The accuracy of the solution is then improved by deferred corrections or the addition of points to the mesh or a combination of both. The method does not suffer from the difficulties associated with the shooting method but good initial estimates of the solution may be required in some cases and the method is unlikely to be successful when the solution varies very rapidly over short ranges. A discussion is given in Chapters 9 and 11 of Gladwell and Sayers (1980) and Chapter 4 of Gladwell (1979a).

2.3 Chebyshev Collocation for Linear Differential Equations

The collocation method gives a different approach to the solution of ordinary differential equations. It can be applied to problems of either initial value or boundary value type. Suppose the approximate solution is represented in polynomial form, say as a series of Chebyshev polynomials. The coefficients may be determined by matching the series to the boundary conditions, and making it satisfy the differential equation at a number of selected points in the range. The calculation is straightforward for linear differential equations (nonlinear equations may also be solved by an iterative technique based on linearization). The result is a set of Chebyshev coefficients, from which the solution may be evaluated at any point using E02AKF. A fuller discussion is given in Chapter 24 of Gladwell (1979a) and Chapter 11 of Gladwell and Sayers (1980).
This method can be useful for obtaining approximations to standard mathematical functions. For example, suppose we require values of the Bessel function J 13 x over the range 0,5, for use in another calculation. We solve the Bessel differential equation by collocation and obtain the Chebyshev coefficients of the solution, which we can use to construct a function for J 13 x. (Note that routines for many common standard functions are already available in Chapter S.)

2.4 Eigenvalue Problems

Sturm–Liouville problems of the form
p x y′ ′ + q x,λ y=0
with appropriate boundary conditions given at two points, can be solved by a Scaled Prüfer method. In this method the differential equation is transformed to another which can be solved for a specified eigenvalue by a shooting method. A discussion is given in Chapter 11 of Gladwell and Sayers (1980) and a complete description is given in Pryce (1986). Some more general eigenvalue problems can be solved by the methods described in Section 2.2.

3 Recommendations on Choice and Use of Available Routines

There are no routines which deal directly with complex equations. These may however be transformed to larger systems of real equations of the required form. Split each equation into its real and imaginary parts and solve for the real and imaginary parts of each component of the solution. Whilst this process doubles the size of the system and may not always be appropriate it does make available for use the full range of routines provided presently.

3.1 Initial Value Problems

In general, for non-stiff first-order systems, Runge–Kutta (RK) routines should be used. For the usual requirement of integrating across a range the appropriate routines are D02PEF and D02PQF; D02PQF is a setup routine for D02PEF. For more complex tasks there are forward and reverse communication variants (Section 3.3.3 in How to Use the NAG Library and its Documentation) of single step routines with corresponding interpolator; for direct communication these are D02PFF and D02PSF, while for reverse communication these are D02PGF, D02PHF and D02PJF. There are also related utility routines D02PRF, D02PTF and D02PUF. When a system is to be integrated over a long range or with relatively high accuracy requirements the variable-order, variable-step Adams' codes may be more efficient. The appropriate routine in this case is D02CJF. For more complex tasks using an Adams' code there are a further six related routines: D02QFF, D02QGF, D02QWF, D02QXF, D02QYF and D02QZF.
For stiff systems, that is those which usually contain rapidly decaying transient components, the Backward Differentiation Formula (BDF) variable-order, variable-step codes should be used. The appropriate routine in this case is D02EJF. For more complex tasks where the system residual is difficult to evaluate in direct communication, or is coupled with algebraic equations, there are a collection of routines in Sub-chapter D02M–N. These routines can treat implicit differential algebraic systems, they also contain additional methods (beyond BDF techniques) which may be appropriate in some circumstances.
If you are not sure how to classify a problem, you are advised to perform some preliminary calculations with D02PEF, which can indicate whether the system is stiff. We also advise performing some trial calculations with D02PEF (RK), D02CJF (Adams) and D02EJF (BDF) so as to determine which type of routine is best applied to the problem. The conclusions should be based on the computer time used and the number of evaluations of the derivative function fi. See Gladwell (1979b) for more details.
For second-order systems of the special form described in Section 2 the Runge–Kutta–Nystrom (RKN) routine D02LAF should be used.

3.1.1 Runge–Kutta routines

The basic RK routines are D02PFF (direct communication) and D02PGF (reverse communication) which take one integration step at a time. An alternative to D02PFF is D02PEF, which provides output at user-specified points. The initialization of D02PEF, D02PFF or D02PGF and the setting of optional inputs, including choice of method, is made by a call to the setup routine D02PQF. Optional output information about the integration and about error assessment, if selected, can be obtained by calls to the diagnostic routines D02PTF and D02PUF respectively. D02PSF may be used to interpolate on information produced by D02PFF to give solution and derivative values between the integration points. Similarly D02PHF may be used to setup an interpolator on information produced by D02PGF, and D02PJF can evaluate that interpolator to give solution and derivative values between integration points; these routines are recommended when a high-order RK method is specified in the setup routine. D02PRF may be used to reset the end of the integration range whilst integrating using D02PFF or D02PGF.
There is a simple driving routine D02BJF, which integrates a system over a range and, optionally, computes intermediate output and/or determines the position where a specified function of the solution is zero.
For well-behaved systems with no difficulties such as stiffness or singularities, the Merson form of the RK method, as used by D02BGF, works well for low accuracy calculations. D02BHF also uses the Merson form and can additionally find a root of a supplied equation involving solution components.

3.1.2 Adams' routines

The general Adams' variable-order variable-step routine is D02QFF, which provides a choice of automatic error control and the option of a sophisticated root-finding technique. Reverse communication for both the differential equation and root definition function is provided in D02QGF, which otherwise has the same facilities as D02QFF. A reverse communication routine makes a return to the calling subroutine for evaluations of equations rather than calling a user-supplied procedure. The initialization of either of D02QFF and D02QGF and the setting of optional inputs is made by a call to the setup routine D02QWF. Optional output information about the integration and any roots detected can be obtained by calls to the diagnostic routines D02QXF and D02QYF respectively. D02QZF may be used to interpolate on information produced by D02QFF or D02QGF to give solution and derivative values between the integration points.
There is a simple driving routine D02CJF, which integrates a system over a range and, optionally, computes intermediate output and/or determines the position where a specified function of the solution is zero.

3.1.3 BDF routines

General routines for explicit and implicit ordinary differential equations with a wide range of options for integrator choice and special forms of numerical linear algebra are provided in Sub-chapter D02M–N. A separate document describing the use of this sub-chapter is given immediately before the routines of the sub-chapter.
There are three utility routines available for use with Sub-chapter D02M–N routines. D02XJF and D02XKF can be used to interpolate to a solution at a given point using the natural and C 1 interpolants respectively. D02ZAF can be used to return the weighted norm of the local error estimate calculated by Sub-chapter D02M–N routines.
There is a simple driving routine D02EJF, which integrates a system over a range and, optionally, computes intermediate output and/or determines the position where a specified function of the solution is zero. It has a specification similar to the Adams' routine D02CJF except that to solve the equations arising in the BDF method an approximation to the Jacobian ∂fi ∂yj is required. This approximation can be calculated internally but you may supply an analytic expression. In most cases supplying a correct analytic expression will reduce the amount of computer time used.

3.1.4 Runge–Kutta–Nystrom routines

The Runge–Kutta–Nystrom routine D02LAF uses either a low- or high-order method (chosen by you). The choice of method and error control and the setting of optional inputs is made by a call to the setup routine D02LXF. Optional output information about the integration can be obtained by a call to the diagnostic routine D02LYF. When the low-order method has been employed D02LZF may be used to interpolate on information produced by D02LAF to give the solution and derivative values between the integration points.

3.2 Boundary Value Problems

In general, for a nonlinear system of mixed order with separated boundary conditions, the collocation method (D02TLF and its associated routines) can be used. Problems of a more general nature can often be transformed into a suitable form for treatment by D02TLF, for example nonseparated boundary conditions or problems with unknown parameters (see Section 9 in D02TVF for details).
For simple boundary value problems with assigned boundary values you may prefer to use a code based on the shooting method or finite difference method for which there are routines with simple calling sequences (D02HAF and D02GAF).
For difficult boundary value problems, where you need to exercise some control over the calculation, and where the collocation method proves unsuccessful, you may wish to try the alternative methods of shooting (D02SAF) or finite differences (D02RAF).
Note that it is not possible to make a fully automatic boundary value routine, and you should be prepared to experiment with different starting values or a different routine if the problem is at all difficult.

3.2.1 Collocation methods

The collocation routine D02TLF solves a nonlinear system of mixed order boundary value problems with separated boundary conditions. The initial mesh and accuracy requirements must be specified by a call to the setup routine D02TVF. Optional output information about the final mesh and estimated maximum error can be obtained by a call to the diagnostic routine D02TZF. The solution anywhere on the mesh can be computed by a call to the interpolation routine D02TYF. If D02TLF is being used to solve a sequence of related problems then the continuation routine D02TXF should also be used.

3.2.2 Shooting methods

D02HAF may be used for simple boundary value problems, where the unknown arguments are the missing boundary conditions. More general boundary value problems may be handled by using D02HBF. This routine allows for a generalized argument structure, and is fairly complicated. The older routine D02AGF has been retained for use when an interior matching-point is essential; otherwise the newer routine D02HBF should be preferred.
For particularly complicated problems where, for example, the arguments must be constrained or the range of integration must be split to enable the shooting method to succeed, the recommended routine is D02SAF, which extends the facilities provided by D02HBF. If you are an experienced user D02SAF permits you much more control over the calculation than does D02HBF; in particular you are permitted precise control of solution output and intermediate monitoring information.

3.2.3 Finite difference methods

D02GAF may be used for simple boundary value problems with assigned boundary values. The calling sequence of D02GAF is very similar to that for D02HAF discussed above.
You may find that convergence is difficult to achieve using D02GAF since only specifying the unknown boundary values and the position of the finite difference mesh is permitted. In such cases you may use D02RAF, which permits specification of an initial estimate for the solution at all mesh points and allows the calculation to be influenced in other ways too. D02RAF is designed to solve a general nonlinear two-point boundary value problem with nonlinear boundary conditions.
A routine, D02GBF, is also supplied specifically for the general linear two-point boundary value problem written in a standard ‘textbook’ form.
You are advised to use interpolation routines from Chapter E01 to obtain solution values at points not on the final mesh.

3.2.4 Chebyshev integration method

The Chebyshev integration method is an implementation of the Chebyshev collocation method (see Section 3.3) which is fully described and compared against other implementations in Muite (2010). D02UEF solves a linear constant coefficient boundary value problem using the Chebyshev integration formulation on a Chebyshev Gauss–Lobatto grid and solving in the coefficient space. The required Chebyshev Gauss–Lobatto grid points on a given arbitrary interval a,b can first be generated using D02UCF. Then D02UAF obtains the Chebyshev coefficients for the right-hand side (of system) function discretized on the obtained Chebyshev Gauss–Lobatto grid. D02UEF then solves the problem in Chebyshev coefficient space using the integration formulation. Finally D02UBF evaluates the solution (or one of its lower order derivatives) from the set of Chebyshev coefficients returned by D02UEF on the Chebyshev Gauss–Lobatto grid on a,b. The set of routines can be used to solve up to fourth order boundary value problems.

3.3 Chebyshev Collocation Method

D02TGF may be used to obtain the approximate solution of a system of differential equations in the form of a Chebyshev series. The routine treats linear differential equations directly, and makes no distinction between initial value and boundary value problems. This routine is appropriate for problems where it is known that the solution is smooth and well-behaved over the range, so that each component can be represented by a single polynomial. Singular problems can be solved using D02TGF as long as their polynomial-like solutions are required.
D02TGF permits the differential equations to be specified in higher order form; that is without conversion to a first-order system. This type of specification leads to a complicated calling sequence. If you are an inexperienced user two simpler routines are supplied. D02JAF solves a single regular linear differential equation of any order whereas D02JBF solves a system of regular linear first-order differential equations.

3.4 Eigenvalue Problems

Two routines, D02KAF and D02KDF, may be used to find the eigenvalues of second-order Sturm–Liouville problems. D02KAF is designed to solve simple problems with regular boundary conditions. D02KAF calls D02KDF, which is designed to solve more difficult problems, for example with singular boundary conditions or on infinite ranges or with discontinuous coefficients.
If the eigenfunctions of the Sturm–Liouville problem are also required, D02KEF should be used. (D02KEF solves the same types of problem as D02KDF.)

3.5 Summary of Recommended Routines

Problem | Routine
 | RK Method | Adams' Method | BDF Method
Initial Value Problems Driver Routines |  |  |
Integration over a range with optional intermediate output and optional determination of position where a function of the solution becomes zero | D02BJF | D02CJF | D02EJF
Integration of a range with intermediate output | D02BJF | D02CJF | D02EJF
Integration of a range until function of solution becomes zero | D02BJF | D02CJF | D02EJF
Comprehensive Integration Routines | D02PEF, D02PFF, D02PGF, D02PHF, D02PJF, D02PQF, D02PRF, D02PSF, D02PTF and D02PUF | D02QFF, D02QGF, D02QWF, D02QXF, D02QYF and D02QZF | Sub-chapter D02M–N routines, D02XJF, D02XKF and D02ZAF
Package for Solving Stiff Equations | Sub-chapter D02M–N routines
Package for Solving Second-order Systems of Special Form | D02L routines
Boundary Value Problems Collocation Method, Mixed Order | D02TLF, D02TVF, D02TXF, D02TYF and D02TZF
Boundary Value Problems Shooting Method |
simple argument | D02HAF
generalized arguments | D02AGF and D02HBF
additional facilities | D02SAF
Boundary Value Problems Finite Difference Method |
simple argument | D02GAF
linear problem | D02GBF
full nonlinear problem | D02RAF
Boundary Value Problems Chebyshev Collocation, Integration Formulation |
single linear equation | D02UEF with D02UAF, D02UBF, D02UCF
Chebyshev Collocation, Linear Problems |
single equation | D02JAF
first-order system | D02JBF
general system | D02TGF
Sturm–Liouville Eigenvalue Problems |
regular problems | D02KAF
general problems | D02KDF
eigenfunction calculation | D02KEF

4 Decision Trees

Tree 1: Initial Value Problems

Is the problem first order? |  |  | Is the problem known to be stiff? |  |  | Use routines described in the D02M–N Sub-chapter Introduction, or their simple driver .
 |  | yes |  |  | yes
 | no |  |  | no |
 |  |  | Backward Differentiation Formula: Use routines described in the D02M–N Sub-chapter Introduction, or their simple driver D02EJF. Adams' method with driver routine: D02CJF Adams' method with comprehensive suite: D02QFF, D02QGF, D02QWF, D02QXF, D02QYF and D02QZF Runge–Kutta method with driver routine: D02BJF Runge–Kutta method with comprehensive suite: D02PEF, D02PFF, D02PGF, D02PHF, D02PJF, D02PQF, D02PRF, D02PSF, D02PTF and D02PUF
Is the problem of the form: y′′=f x,y |  |  | Use the D02L routines
 |  | yes
 | no |
Convert to first order problem: is the problem known to be stiff? |  |  | Use routines described in the D02M–N Sub-chapter Introduction, or their simple driver D02EJF.
 |  | yes
 | no |
Backward Differentiation Formula: use routines described in the D02M–N Sub-chapter Introduction, or their simple driver D02EJF. Adams' method with driver routine: D02CJF Adams' method with comprehensive suite: D02QFF, D02QGF, D02QWF, D02QXF, D02QYF and D02QZF Runge–Kutta method with driver routine: D02BJF Runge–Kutta method with comprehensive suite: D02PEF, D02PFF, D02PGF, D02PHF, D02PJF, D02PQF, D02PRF, D02PSF, D02PTF and D02PUF

Tree 2: Boundary Value Problems

Is the problem simply of the form y'=f x,y? |  |  | Are only boundary values to be determined? |  |  | Shooting method: D02HAF Finite differences: D02GAF Collocation: D02TLF
 |  | yes |  |  | yes
 | no |  |  | no |
 |  |  | Shooting method: D02HBF Finite differences: D02GBF Collocation, piecewise polynomials: D02TLF Collocation, Chebyshev polynomials: D02JAF, D02JBF or D02UEF
Shooting method: D02SAF Finite differences: D02RAF Collocation, piecewise polynomials: D02TLF Collocation, Chebyshev polynomials: D02JAF, D02JBF or D02UEF

5 Functionality Index

Differentiation of a function discretized on Chebyshev Gauss–Lobatto points D02UDF
Linear constant coefficient boundary value problem,
Chebyshev spectral integration method,
Chebyshev coefficients generator for a function discretized on Chebyshev Gauss–Lobatto grid D02UAF
Chebyshev coefficients to function values on Chebyshev Gauss–Lobatto grid D02UBF
Chebyshev Gauss–Lobatto grid generator D02UCF
Chebyshev integration solver for linear constant coefficient boundary value problem D02UEF
Clenshaw–Curtis quadrature weights generator at Chebyshev Gauss–Lobatto points D02UYF
Evaluation on uniform grid of function by Barycentric Lagrange interpolation D02UWF
value of kth Chebyshev polynomial D02UZF
Second-order Sturm–Liouville problems,
regular/singular system, finite/infinite range,
eigenvalue and eigenfunction D02KEF
eigenvalue only D02KDF
regular system, finite range, user-specified break-points,
eigenvalue only D02KAF
System of first-order ordinary differential equations, initial value problems,
C1-interpolant D02XKF
comprehensive integrator routines for stiff systems,
continuation to call D02NEF D02MCF
explicit ordinary differential equations,
banded Jacobian D02NCF
full Jacobian D02NBF
sparse Jacobian D02NDF
explicit ordinary differential equations (reverse communication):
full Jacobian D02NMF
implicit ordinary differential equations coupled with algebraic equations,
banded Jacobian D02NHF
banded Jacobian selector for DASSL integrator D02NPF
DASSL integrator D02NEF
full Jacobian D02NGF
integrator setup for DASSL D02MWF
sparse Jacobian D02NJF
implicit ordinary differential equations coupled with algebraic equations (reverse communication) D02NNF
comprehensive integrator routines using Adams' method with root-finding option,
diagnostic routine D02QXF
diagnostic routine for root-finding D02QYF
direct communication D02QFF
interpolant D02QZF
reverse communication D02QGF
setup routine D02QWF
comprehensive integrator routines using Runge–Kutta methods,
diagnostic routine D02PTF
diagnostic routine for global error assessment D02PUF
interpolant, reverse communication D02PHF
interpolant and interpolation, direct communication D02PSF
interpolation, reverse communication D02PJF
over a range with intermediate output D02PEF
over a step, direct communication D02PFF
over a step, reverse communication D02PGF
reset end of range D02PRF
setup routine D02PQF
compute weighted norm of local error estimate D02ZAF
enquiry routine for use with sparse Jacobian D02NRF
integrator diagnostic routine D02NYF
integrator setup for backward differentiation formulae method for SPRINT integrator D02NVF
integrator setup for Blend method for SPRINT integrator D02NWF
integrator setup for DASSL method for SPRINT integrator D02MVF
linear algebra diagnostic routine for sparse Jacobians D02NXF
linear algebra setup for banded Jacobians D02NTF
linear algebra setup for full Jacobians D02NSF
linear algebra setup for sparse Jacobians D02NUF
natural interpolant D02MZF
natural interpolant (for use by MONITR subroutine) D02XJF
setup routine for continuation calls to integrator D02NZF
simple driver routines,
Runge–Kutta–Merson method,
until a function of the solution is zero D02BHF
until a specified component attains a given value D02BGF
Runge–Kutta method,
until (optionally) a function of the solution is zero, with optional intermediate output D02BJF
variable-order variable-step Adams' method,
until (optionally) a function of the solution is zero, with optional intermediate output D02CJF
variable-order variable-step backward differentiation formulae method for stiff systems,
until (optionally) a function of the solution is zero, with optional intermediate output D02EJF
System of ordinary differential equations, boundary value problems,
collocation and least squares,
single nth-order linear equation D02JAF
system of first-order linear equations D02JBF
system of nth-order linear equations D02TGF
comprehensive routines using a collocation technique,
continuation routine D02TXF
diagnostic routine D02TZF
general nonlinear problem solver (thread safe) D02TLF
interpolation routine D02TYF
setup routine D02TVF
finite difference technique with deferred correction,
general linear problem D02GBF
general nonlinear problem, with continuation facility D02RAF
simple nonlinear problem D02GAF
shooting and matching technique,
boundary values to be determined D02HAF
general parameters to be determined D02HBF
general parameters to be determined, allowing interior matching-point D02AGF
general parameters to be determined, subject to extra algebraic equations D02SAF
System of second-order ordinary differential equations,
Runge–Kutta–Nystrom method,
diagnostic routine D02LYF
integrator D02LAF
interpolating solutions D02LZF
setup routine D02LXF

6 Auxiliary Routines Associated with Library Routine Arguments

D02BJW | nagf_ode_ivp_rk_zero_simple_dummy_g See the description of the argument G in D02BJF.
D02BJX | nagf_ode_ivp_rk_zero_simple_dummy_output See the description of the argument OUTPUT in D02BJF.
D02CJW | nagf_ode_ivp_adams_zero_simple_dummy_g See the description of the argument G in D02CJF.
D02CJX | nagf_ode_ivp_adams_zero_simple_dummy_output See the description of the argument OUTPUT in D02CJF.
D02EJW | nagf_ode_ivp_bdf_zero_simple_dummy_g See the description of the argument G in D02EJF.
D02EJX | nagf_ode_ivp_bdf_zero_simple_dummy_output See the description of the argument OUTPUT in D02EJF.
D02EJY | nagf_ode_ivp_bdf_zero_simple_dummy_pederv See the description of the argument PEDERV in D02EJF.
D02GAW | nagf_ode_bvp_fd_nonlin_gen_dummy_jacobf See the description of the argument JACEPS in D02RAF.
D02GAX | nagf_ode_bvp_fd_nonlin_gen_dummy_jacobg See the description of the argument JACGEP in D02RAF.
D02GAY | nagf_ode_bvp_fd_nonlin_gen_dummy_jaceps See the description of the argument JACOBG in D02RAF.
D02GAZ | nagf_ode_bvp_fd_nonlin_gen_dummy_jacgep See the description of the argument JACOBF in D02RAF.
D02HBW | nagf_ode_bvp_shoot_genpar_algeq_dummy_prsol See the description of the argument PRSOL in D02SAF.
D02HBX | nagf_ode_bvp_shoot_genpar_algeq_sample_monit See the description of the argument MONIT in D02SAF.
D02HBY | nagf_ode_bvp_shoot_genpar_algeq_dummy_constr See the description of the argument CONSTR in D02SAF.
D02HBZ | nagf_ode_bvp_shoot_genpar_algeq_dummy_eqn See the description of the argument EQN in D02SAF.
D02KAY | nagf_ode_sl2_reg_finite_dummy_monit See the description of the argument MONIT in D02KAF, D02KDF and D02KEF.
D02NBY | nagf_ode_ivp_stiff_exp_fulljac_dummy_monit See the description of the argument MONITR in D02NBF, D02NCF, D02NDF, D02NGF, D02NHF and D02NJF.
D02NBZ | nagf_ode_ivp_stiff_exp_fulljac_dummy_jac See the description of the argument JAC in D02NBF.
D02NCZ | nagf_ode_ivp_stiff_exp_bandjac_dummy_jac See the description of the argument JAC in D02NCF.
D02NDZ | nagf_ode_ivp_stiff_exp_sparjac_dummy_jac See the description of the argument JAC in D02NDF.
D02NEZ | nagf_ode_dae_dassl_gen_dummy_jac See the description of the argument JAC in D02NEF.
D02NGZ | nagf_ode_ivp_stiff_imp_fulljac_dummy_jac See the description of the argument JAC in D02NGF.
D02NHZ | nagf_ode_ivp_stiff_imp_bandjac_dummy_jac See the description of the argument JAC in D02NHF.
D02NJZ | nagf_ode_ivp_stiff_imp_sparjac_dummy_jac See the description of the argument JAC in D02NJF.
D02QFZ | nagf_ode_ivp_adams_roots_dummy_g See the description of the argument G in D02QFF.
D02SAS | nagf_ode_bvp_shoot_genpar_algeq_dummy_monit See the description of the argument MONIT in D02SAF.

7 Routines Withdrawn or Scheduled for Withdrawal

The following lists all those routines that have been withdrawn since Mark 19 of the Library or are scheduled for withdrawal at one of the next two marks.
Withdrawn Routine | Mark of Withdrawal | Replacement Routine(s)
D02PCF | 26 | D02PEF and associated D02P routines
D02PDF | 26 | D02PFF or D02PGF and associated D02P routines
D02PVF | 26 | D02PQF
D02PWF | 26 | D02PRF
D02PXF | 26 | D02PSF
D02PYF | 26 | D02PTF
D02PZF | 26 | D02PUF
D02TKF | 27 | D02TLF

8 References

Ascher U M and Bader G (1987) A new basis implementation for a mixed order boundary value ODE solver SIAM J. Sci. Stat. Comput. 8 483–500
Ascher U M, Christiansen J and Russell R D (1979) A collocation solver for mixed order systems of boundary value problems Math. Comput. 33 659–679
Ascher U M, Mattheij R M M and Russell R D (1988) Numerical Solution of Boundary Value Problems for Ordinary Differential Equations Prentice–Hall
Berzins M, Brankin R W and Gladwell I (1988) Design of the stiff integrators in the NAG Library SIGNUM Newsl. 23 16–23
Brenan K, Campbell S and Petzold L (1996) Numerical Solution of Initial-Value Problems in Differential-Algebraic Equations SIAM, Philadelphia
Gladwell I (1979a) The development of the boundary value codes in the ordinary differential equations chapter of the NAG Library Codes for Boundary Value Problems in Ordinary Differential Equations. Lecture Notes in Computer Science (eds B Childs, M Scott, J W Daniel, E Denman and P Nelson) 76 Springer–Verlag
Gladwell I (1979b) Initial value routines in the NAG Library ACM Trans. Math. Software 5 386–400
Gladwell I (1987) The NAG Library boundary value codes Numerical Analysis Report 134 Manchester University
Gladwell I and Sayers D K (ed.) (1980) Computational Techniques for Ordinary Differential Equations Academic Press
Hall G and Watt J M (ed.) (1976) Modern Numerical Methods for Ordinary Differential Equations Clarendon Press, Oxford
Keller H B (1992) Numerical Methods for Two-point Boundary-value Problems Dover, New York
Muite B K (2010) A numerical comparison of Chebyshev methods for solving fourth-order semilinear initial boundary value problems Journal of Computational and Applied Mathematics 234(2) 317–342
Pryce J D (1986) Error estimation for phase-function shooting methods for Sturm–Liouville problems IMA J. Numer. Anal. 6 103–123
D02 Chapter Contents
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


D02JAF : NAG Library, Mark 26

D02 Chapter Contents
D02 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

D02JAF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

D02JAF solves a regular linear two-point boundary value problem for a single nth-order ordinary differential equation by Chebyshev series using collocation and least squares.

2 Specification

SUBROUTINE D02JAF ( N, CF, BC, X0, X1, K1, KP, C, W, LW, IW, IFAIL)
INTEGER | N, K1, KP, LW, IW(K1), IFAIL
REAL (KIND=nag_wp) | CF, X0, X1, C(K1), W(LW)
EXTERNAL | CF, BC

3 Description

D02JAF calculates the solution of a regular two-point boundary value problem for a single nth-order linear ordinary differential equation as a Chebyshev series in the interval x 0,x 1. The differential equation
f n+1 x y n x+fn x y n-1 x+⋯+f 1 x y x=f 0 x
is defined by CF, and the boundary conditions at the points x 0 and x 1 are defined by BC.
You specify the degree of Chebyshev series required, K1-1, and the number of collocation points, KP. The routine sets up a system of linear equations for the Chebyshev coefficients, one equation for each collocation point and one for each boundary condition. The boundary conditions are solved exactly, and the remaining equations are then solved by a least squares method. The result produced is a set of coefficients for a Chebyshev series solution of the differential equation on an interval normalized to -1,1.
E02AKF can be used to evaluate the solution at any point on the interval x 0,x 1 – see Section 10 for an example. E02AHF followed by E02AKF can be used to evaluate its derivatives.

4 References

Picken S M (1970) Algorithms for the solution of differential equations in Chebyshev-series by the selected points method Report Math. 94 National Physical Laboratory

5 Arguments

1:   N – INTEGERInput
On entry: n, the order of the differential equation.
Constraint: N≥1.
2:   CF – REAL (KIND=nag_wp) FUNCTION, supplied by the user.External Procedure
CF defines the differential equation (see Section 3). It must return the value of a function fj x at a given point x, where, for 1≤j≤n+1, fj x is the coefficient of y j-1 x in the equation, and f 0 x is the right-hand side.
The specification of CF is:
FUNCTION CF ( J, X)
REAL (KIND=nag_wp) CF
INTEGER | J
REAL (KIND=nag_wp) | X
1:   J – INTEGERInput
On entry: the index of the function fj to be evaluated.
2:   X – REAL (KIND=nag_wp)Input
On entry: the point at which fj is to be evaluated.
CF must either be a module subprogram USEd by, or declared as EXTERNAL in, the (sub)program from which D02JAF is called. Arguments denoted as Input must not be changed by this procedure.
3:   BC – SUBROUTINE, supplied by the user.External Procedure
BC defines the boundary conditions, each of which has the form y k-1 x 1=sk or y k-1 x 0=sk. The boundary conditions may be specified in any order.
The specification of BC is:
SUBROUTINE BC ( I, J, RHS)
INTEGER | I, J
REAL (KIND=nag_wp) | RHS
1:   I – INTEGERInput
On entry: the index of the boundary condition to be defined.
2:   J – INTEGEROutput
On exit: must be set to -k if the boundary condition is y k-1 x 0=sk, and to +k if it is y k-1 x 1=sk.
J must not be set to the same value k for two different values of I.
3:   RHS – REAL (KIND=nag_wp)Output
On exit: must be set to the value sk.
BC must either be a module subprogram USEd by, or declared as EXTERNAL in, the (sub)program from which D02JAF is called. Arguments denoted as Input must not be changed by this procedure.
4:   X0 – REAL (KIND=nag_wp)Input
5:   X1 – REAL (KIND=nag_wp)Input
On entry: the left- and right-hand boundaries, x 0 and x 1, respectively.
Constraint: X1>X0.
6:   K1 – INTEGERInput
On entry: the number of coefficients to be returned in the Chebyshev series representation of the solution (hence the degree of the polynomial approximation is K1-1).
Constraint: K1≥N+1.
7:   KP – INTEGERInput
On entry: the number of collocation points to be used.
Constraint: KP≥K1-N.
8:   C K1 – REAL (KIND=nag_wp) arrayOutput
On exit: the computed Chebyshev coefficients; that is, the computed solution is:
∑′i=1 K1 C i T i-1 x
where Ti x is the ith Chebyshev polynomial of the first kind, and ∑′ denotes that the first coefficient, C 1, is halved.
9:   W LW – REAL (KIND=nag_wp) arrayWorkspace
10:   LW – INTEGERInput
On entry: the dimension of the array W as declared in the (sub)program from which D02JAF is called.
Constraint: LW≥2×KP+N×K1+1+7×K1.
11:   IW K1 – INTEGER arrayWorkspace
12:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, | N<1,
or | X0≥X1,
or | K1<N+1,
or | KP<K1-N.
IFAIL=2
On entry, LW<2×KP+N×K1+1+7×K1 (insufficient workspace).
IFAIL=3
Either the boundary conditions are not linearly independent (that is, in BC the variable J is set to the same value k for two different values of I), or the rank of the matrix of equations for the coefficients is less than the number of unknowns. Increasing KP may overcome this latter problem.
IFAIL=4
The least squares routine F04AMF has failed to correct the first approximate solution (see F04AMF).
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

The Chebyshev coefficients are determined by a stable numerical method. The accuracy of the approximate solution may be checked by varying the degree of the polynomial and the number of collocation points (see Section 9).

8 Parallelism and Performance

D02JAF is not thread safe and should not be called from a multithreaded user program. Please see Section 3.12.1 in How to Use the NAG Library and its Documentation for more information on thread safety.
D02JAF makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The time taken by D02JAF depends on the complexity of the differential equation, the degree of the polynomial solution, and the number of matching points.
The collocation points in the interval x 0,x 1 are chosen to be the extrema of the appropriate shifted Chebyshev polynomial. If KP=K1-N, then the least squares solution reduces to the solution of a system of linear equations, and true collocation results.
The accuracy of the solution may be checked by repeating the calculation with different values of K1 and with KP fixed but KP≫K1-N. If the Chebyshev coefficients decrease rapidly (and consistently for various K1 and KP), the size of the last two or three gives an indication of the error. If the Chebyshev coefficients do not decay rapidly, it is likely that the solution cannot be well-represented by Chebyshev series. Note that the Chebyshev coefficients are calculated for the interval -1,1.
Systems of regular linear differential equations can be solved using D02JBF. It is necessary before using D02JBF to write the differential equations as a first-order system. Linear systems of high-order equations in their original form, singular problems, and, indirectly, nonlinear problems can be solved using D02TGF.

10 Example

This example solves the equation
y′′ + y = 1
with boundary conditions
y-1 = y 1 = 0 .
We use K1=4, 6 and 8, and KP=10 and 15, so that the different Chebyshev series may be compared. The solution for K1=8 and KP=15 is evaluated by E02AKF at nine equally spaced points over the interval -1,1.

10.1 Program Text

Program Text (d02jafe.f90)

10.2 Program Data

Program Data (d02jafe.d)

10.3 Program Results

Program Results (d02jafe.r)

GnuplotProduced by GNUPLOT 4.6 patchlevel 3 −0.9 −0.8 −0.7 −0.6 −0.5 −0.4 −0.3 −0.2 −0.1 0 −1 −0.5 0 0.5 1 y x Example Program Two-point Boundary-value Problem for ODE by Chebyshev-series using Collocation and Least-squares gnuplot_plot_1
D02 Chapter Contents
D02 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


D02JBF : NAG Library, Mark 26

D02 Chapter Contents
D02 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

D02JBF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

D02JBF solves a regular linear two-point boundary value problem for a system of ordinary differential equations by Chebyshev series using collocation and least squares.

2 Specification

SUBROUTINE D02JBF ( N, CF, BC, X0, X1, K1, KP, C, LDC, W, LW, IW, LIW, IFAIL)
INTEGER | N, K1, KP, LDC, LW, IW(LIW), LIW, IFAIL
REAL (KIND=nag_wp) | CF, X0, X1, C(LDC,N), W(LW)
EXTERNAL | CF, BC

3 Description

D02JBF calculates the solution of a regular two-point boundary value problem for a regular linear nth-order system of first-order ordinary differential equations as a Chebyshev series in the interval x 0,x 1. The differential equation
y′=A x y+r x
is defined by CF, and the boundary conditions at the points x 0 and x 1 are defined by BC.
You specify the degree of Chebyshev series required, K1-1, and the number of collocation points, KP. The routine sets up a system of linear equations for the Chebyshev coefficients, n equations for each collocation point and one for each boundary condition. The boundary conditions are solved exactly, and the remaining equations are then solved by a least squares method. The result produced is a set of coefficients for a Chebyshev series solution for each component of the solution of the system of differential equations on an interval normalized to -1,1.
E02AKF can be used to evaluate the components of the solution at any point on the interval x 0,x 1 – see Section 10 for an example. E02AHF followed by E02AKF can be used to evaluate their derivatives.

4 References

Picken S M (1970) Algorithms for the solution of differential equations in Chebyshev-series by the selected points method Report Math. 94 National Physical Laboratory

5 Arguments

1:   N – INTEGERInput
On entry: n, the order of the system of differential equations.
Constraint: N≥1.
2:   CF – REAL (KIND=nag_wp) FUNCTION, supplied by the user.External Procedure
CF defines the system of differential equations (see Section 3). It must return the value of a coefficient function a i,j x, of A, at a given point x, or of a right-hand side function ri x if J=0.
The specification of CF is:
FUNCTION CF ( I, J, X)
REAL (KIND=nag_wp) CF
INTEGER | I, J
REAL (KIND=nag_wp) | X
1:   I – INTEGERInput
2:   J – INTEGERInput
On entry: indicate the function to be evaluated, namely a i,j x if 1≤J≤n, or ri x if J=0.
1≤I≤n, 0≤J≤n.
3:   X – REAL (KIND=nag_wp)Input
On entry: the point at which the function is to be evaluated.
CF must either be a module subprogram USEd by, or declared as EXTERNAL in, the (sub)program from which D02JBF is called. Arguments denoted as Input must not be changed by this procedure.
3:   BC – SUBROUTINE, supplied by the user.External Procedure
BC defines the n boundary conditions, which have the form yk x 0=s or yk x 1=s. The boundary conditions may be specified in any order.
The specification of BC is:
SUBROUTINE BC ( I, J, RHS)
INTEGER | I, J
REAL (KIND=nag_wp) | RHS
1:   I – INTEGERInput
On entry: the index of the boundary condition to be defined.
2:   J – INTEGEROutput
On exit: must be set to -k if the ith boundary condition is yk x 0=s, or to +k if it is yk x 1=s.
J must not be set to the same value k for two different values of I.
3:   RHS – REAL (KIND=nag_wp)Output
On exit: the value s.
BC must either be a module subprogram USEd by, or declared as EXTERNAL in, the (sub)program from which D02JBF is called. Arguments denoted as Input must not be changed by this procedure.
4:   X0 – REAL (KIND=nag_wp)Input
5:   X1 – REAL (KIND=nag_wp)Input
On entry: the left- and right-hand boundaries, x 0 and x 1, respectively.
Constraint: X1>X0.
6:   K1 – INTEGERInput
On entry: the number of coefficients to be returned in the Chebyshev series representation of the components of the solution (hence the degree of the polynomial approximation is K1-1).
Constraint: K1≥2.
7:   KP – INTEGERInput
On entry: the number of collocation points to be used.
Constraint: KP≥K1-1.
8:   C LDCN – REAL (KIND=nag_wp) arrayOutput
On exit: the computed Chebyshev coefficients of the kth component of the solution, yk; that is, the computed solution is:
yk=∑′i=1 K1 C ik T i-1 x,  1≤k≤n
where Ti x is the ith Chebyshev polynomial of the first kind, and ∑′ denotes that the first coefficient, C 1 k, is halved.
9:   LDC – INTEGERInput
On entry: the first dimension of the array C as declared in the (sub)program from which D02JBF is called.
Constraint: LDC≥K1.
10:   W LW – REAL (KIND=nag_wp) arrayWorkspace
11:   LW – INTEGERInput
On entry: the dimension of the array W as declared in the (sub)program from which D02JBF is called.
Constraint: LW≥2×N×KP+1×N×K1+1+7×N×K1.
12:   IW LIW – INTEGER arrayWorkspace
13:   LIW – INTEGERInput
On entry: the dimension of the array IW as declared in the (sub)program from which D02JBF is called.
Constraint: LIW≥N×K1+2.
14:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, | N<1,
or | X0≥X1,
or | K1<2,
or | KP<K1-1,
or | LDC<K1.
IFAIL=2
On entry, | LW<2×N×KP+1×N×K1+1+7×N×K1,
or | LIW<N×K1+2 (i.e., insufficient workspace).
IFAIL=3
Either the boundary conditions are not linearly independent (that is, in BC the variable J is set to the same value k for two different values of I), or the rank of the matrix of equations for the coefficients is less than the number of unknowns. Increasing KP may overcome this latter problem.
IFAIL=4
The least squares routine F04AMF has failed to correct the first approximate solution (see F04AMF).
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

The Chebyshev coefficients are determined by a stable numerical method. The accuracy of the approximate solution may be checked by varying the degree of the polynomials and the number of collocation points (see Section 9).

8 Parallelism and Performance

D02JBF is not thread safe and should not be called from a multithreaded user program. Please see Section 3.12.1 in How to Use the NAG Library and its Documentation for more information on thread safety.
D02JBF makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The time taken by D02JBF depends on the size and complexity of the differential system, the degree of the polynomial solution, and the number of matching points.
The collocation points in the interval x 0,x 1 are chosen to be the extrema of the appropriate shifted Chebyshev polynomial. If KP=K1-1, then the least squares solution reduces to the solution of a system of linear equations, and true collocation results.
The accuracy of the solution may be checked by repeating the calculation with different values of K1 and with KP fixed but KP≫K1-1. If the Chebyshev coefficients decrease rapidly for each component (and consistently for various K1 and KP), the size of the last two or three gives an indication of the error. If the Chebyshev coefficients do not decay rapidly, it is likely that the solution cannot be well-represented by Chebyshev series. Note that the Chebyshev coefficients are calculated for the interval -1,1.
Linear systems of high-order equations in their original form, singular problems, and, indirectly, nonlinear problems can be solved using D02TGF.

10 Example

This example solves the equation
y′′ + y = 1
with boundary conditions
y-1 = y 1 = 0 .
The equation is written as the first-order system
y 1′ y 2′ = 0 1 -1 0 y 1 y 2 + 0 1
for solution by D02JBF and the boundary conditions are written
y 1- 1=y 1 1=0.
We use K1=4, 6 and 8, and KP=10 and 15, so that the different Chebyshev series may be compared. The solution for K1=8 and KP=15 is evaluated by E02AKF at nine equally spaced points over the interval -1,1.

10.1 Program Text

Program Text (d02jbfe.f90)

10.2 Program Data

Program Data (d02jbfe.d)

10.3 Program Results

Program Results (d02jbfe.r)

GnuplotProduced by GNUPLOT 4.6 patchlevel 3 −2 −1.5 −1 −0.5 0 0.5 1 1.5 2 −1 −0.5 0 0.5 1 0 5e−05 0.0001 0.00015 0.0002 Solution Abolute Error x Example Program Two-point Boundary-value Problem for ODE System by Chebyshev-series using Collocation and Least-squares y y' error gnuplot_plot_1 gnuplot_plot_2 gnuplot_plot_3
D02 Chapter Contents
D02 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


D02KAF : NAG Library, Mark 26

D02 Chapter Contents
D02 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

D02KAF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

D02KAF finds a specified eigenvalue of a regular second-order Sturm–Liouville system defined on a finite range, using a Pruefer transformation and a shooting method.

2 Specification

SUBROUTINE D02KAF ( XL, XR, COEFFN, BCOND, K, TOL, ELAM, DELAM, MONIT, IFAIL)
INTEGER | K, IFAIL
REAL (KIND=nag_wp) | XL, XR, BCOND(3,2), TOL, ELAM, DELAM
EXTERNAL | COEFFN, MONIT

3 Description

D02KAF finds a specified eigenvalue λ~ of a Sturm–Liouville system defined by a self-adjoint differential equation of the second-order
p x y′ ′ + q x;λ y=0 ,   a<x<b ,
together with boundary conditions of the form
a 2 y a=a 1 p a y′a
b 2 y b=b 1 p b y′b
at the two, finite, end points a and b. The functions p and q, which are real-valued, are defined by COEFFN.
For the theoretical basis of the numerical method to be valid, the following conditions should hold on the coefficient functions:
(a) | p x must be nonzero and must not change sign throughout the closed interval a,b;
(b) | ∂q ∂λ must not change sign and must be nonzero throughout the open interval a,b and for all relevant values of λ, and must not be identically zero as x varies, for any relevant value λ; and,
(c) | p and q should (as functions of x) have continuous derivatives, preferably up to the fourth-order, on a,b. The differential equation code used will integrate through mild discontinuities, but probably with severely reduced efficiency. Therefore, if p and q violate this condition, D02KDF should be used.
The eigenvalue λ~ is determined by a shooting method based on a Pruefer transformation of the differential equations. Providing certain assumptions are met, the computed value of λ~ will be correct to within a mixed absolute/relative error specified by TOL. D02KAF is a driver routine for the more complicated routine D02KDF whose specification provides more details of the techniques used.
A good account of the theory of Sturm–Liouville systems, with some description of Pruefer transformations, is given in Chapter X of Birkhoff and Rota (1962). An introduction to the use of Pruefer transformations for the numerical solution of eigenvalue problems arising from physics and chemistry is given in Bailey (1966).

4 References

Bailey P B (1966) Sturm–Liouville eigenvalues via a phase function SIAM J. Appl. Math. 14 242–249
Birkhoff G and Rota G C (1962) Ordinary Differential Equations Ginn & Co., Boston and New York

5 Arguments

1:   XL – REAL (KIND=nag_wp)Input
2:   XR – REAL (KIND=nag_wp)Input
On entry: the left- and right-hand end points a and b respectively, of the interval of definition of the problem.
Constraint: XL<XR.
3:   COEFFN – SUBROUTINE, supplied by the user.External Procedure
COEFFN must compute the values of the coefficient functions p x and q x;λ for given values of x and λ. Section 3 states the conditions which p and q must satisfy.
The specification of COEFFN is:
SUBROUTINE COEFFN ( P, Q, DQDL, X, ELAM, JINT)
INTEGER | JINT
REAL (KIND=nag_wp) | P, Q, DQDL, X, ELAM
1:   P – REAL (KIND=nag_wp)Output
On exit: the value of p x for the current value of x.
2:   Q – REAL (KIND=nag_wp)Output
On exit: the value of q x;λ for the current value of x and the current trial value of λ.
3:   DQDL – REAL (KIND=nag_wp)Output
On exit: the value of ∂q ∂λ x;λ for the current value of x and the current trial value of λ. However DQDL is only used in error estimation and, in the rare cases where it may be difficult to evaluate, an approximation (say to within 20%) will suffice.
4:   X – REAL (KIND=nag_wp)Input
On entry: the current value of x.
5:   ELAM – REAL (KIND=nag_wp)Input
On entry: the current trial value of the eigenvalue argument λ.
6:   JINT – INTEGERInput
This argument is included for compatibility with the more complex routine D02KDF (which is called by D02KAF).
On entry: need not be set.
COEFFN must either be a module subprogram USEd by, or declared as EXTERNAL in, the (sub)program from which D02KAF is called. Arguments denoted as Input must not be changed by this procedure.
4:   BCOND 32 – REAL (KIND=nag_wp) arrayInput/Output
On entry: BCOND 11 and BCOND 21 must contain the numbers a 1, a 2 specifying the left-hand boundary condition in the form
a 2 y a = a 1 p a y′a
where a 2+a 1 p a≠0.
BCOND 12 and BCOND 22 must contain b 1, b 2 such that
b 2 y b = b 1 p b y′b
where b 2+b 1 p b≠0.
Note the occurrence of p a, p b in these formulae.
On exit: BCOND 31 and BCOND 32 hold values σl,σr estimating the sensitivity of the computed eigenvalue to changes in the boundary conditions. These values should only be of interest if the boundary conditions are, in some sense, an approximation to some ‘true’ boundary conditions. For example, if the range [XL, XR] should really be 0,∞ but instead XR has been given a large value and the boundary conditions at infinity applied at XR, then the sensitivity argument σr may be of interest. Refer to Section 9.5 in D02KDF, for the actual meaning of σr and σl.
5:   K – INTEGERInput
On entry: k, the index of the required eigenvalue when the eigenvalues are ordered
λ 0 < λ 1 < λ 2 < ⋯ < λk < ⋯ .
Constraint: K≥0.
6:   TOL – REAL (KIND=nag_wp)Input
On entry: the tolerance argument which determines the accuracy of the computed eigenvalue. The error estimate held in DELAM on exit satisfies the mixed absolute/relative error test
DELAM≤TOL×max 1.0,ELAM, (1)
where ELAM is the final estimate of the eigenvalue. DELAM is usually somewhat smaller than the right-hand side of (1) but not several orders of magnitude smaller.
Constraint: TOL>0.0.
7:   ELAM – REAL (KIND=nag_wp)Input/Output
On entry: an initial estimate of the eigenvalue λ~.
On exit: the final computed estimate, whether or not an error occurred.
8:   DELAM – REAL (KIND=nag_wp)Input/Output
On entry: an indication of the scale of the problem in the λ-direction. DELAM holds the initial ‘search step’ (positive or negative). Its value is not critical, but the first two trial evaluations are made at ELAM and ELAM+DELAM, so the routine will work most efficiently if the eigenvalue lies between these values. A reasonable choice (if a closer bound is not known) is about half the distance between adjacent eigenvalues in the neighbourhood of the one sought. In practice, there will often be a problem, similar to the one in hand but with known eigenvalues, which will help one to choose initial values for ELAM and DELAM.
If DELAM=0.0 on entry, it is given the default value of 0.25×max 1.0,ELAM.
On exit: if IFAIL=0, DELAM holds an estimate of the absolute error in the computed eigenvalue, that is λ~-ELAM≃DELAM, where λ~ is the true eigenvalue.
If IFAIL≠0, DELAM may hold an estimate of the error, or its initial value, depending on the value of IFAIL. See Section 6 for further details.
9:   MONIT – SUBROUTINE, supplied by the NAG Library or the user.External Procedure
MONIT is called by D02KAF at the end of each iteration for λ and allows you to monitor the course of the computation by printing out the arguments (see Section 10 for an example).
If no monitoring is required, the dummy (sub)program D02KAY may be used. (D02KAY is included in the NAG Library.)
The specification of MONIT is:
SUBROUTINE MONIT ( NIT, IFLAG, ELAM, FINFO)
INTEGER | NIT, IFLAG
REAL (KIND=nag_wp) | ELAM, FINFO(15)
1:   NIT – INTEGERInput
On entry: 15 minus the number of iterations used so far in the search for λ~. (Up to 15 iterations are permitted.)
2:   IFLAG – INTEGERInput
On entry: describes what phase the computation is in.
IFLAG<0
An error occurred in the computation at this iteration; an error exit from D02KAF will follow.
IFLAG=1
The routine is trying to bracket the eigenvalue λ~.
IFLAG=2
The routine is converging to the eigenvalue λ~ (having already bracketed it).
Normally, the iteration will terminate after a sequence of iterates with IFLAG=2, but occasionally the bracket on λ~ thus determined will not be sufficiently small and the iteration will be repeated with tighter accuracy control.
3:   ELAM – REAL (KIND=nag_wp)Input
On entry: the current trial value of λ~.
4:   FINFO 15 – REAL (KIND=nag_wp) arrayInput
On entry: information about the behaviour of the shooting method, and diagnostic information in the case of errors. It should not normally be printed in full if no error has occurred (that is, if IFLAG≥0), though the first few components may be of interest to you. In case of an error (IFLAG<0) all the components of FINFO should be printed.
The contents of FINFO are as follows:
FINFO 1
The current value of the ‘miss-distance’ or ‘residual’ function f λ on which the shooting method is based. f λ~=0 in theory. This is set to zero if IFLAG<0.
FINFO 2
An estimate of the quantity ∂λ defined as follows. Consider the perturbation in the miss-distance f λ that would result if the local error in the solution of the differential equation were always positive and equal to its maximum permitted value. Then ∂λ is the perturbation in λ that would have the same effect on f λ. Thus, at the zero of f λ,∂λ is an approximate bound on the perturbation of the zero (that is the eigenvalue) caused by errors in numerical solution. If ∂λ is very large then it is possible that there has been a programming error in COEFFN such that q is independent of λ. If this is the case, an error exit with IFAIL=5 should follow. FINFO 2 is set to zero if IFLAG<0.
FINFO 3
The number of internal iterations, using the same value of λ and tighter accuracy tolerances, needed to bring the accuracy (that is, the value of ∂λ) to an acceptable value. Its value should normally be 1.0, and should almost never exceed 2.0.
FINFO 4
The number of calls to COEFFN at this iteration.
FINFO 5
The number of successful steps taken by the internal differential equation solver at this iteration. A step is successful if it is used to advance the integration.
FINFO 6
The number of unsuccessful steps used by the internal integrator at this iteration.
FINFO 7
The number of successful steps at the maximum step size taken by the internal integrator at this iteration.
FINFO 8
Not used.
FINFO 9 to FINFO 15
Set to zero, unless IFLAG<0 in which case they hold the following values describing the point of failure:
FINFO 9
1 or 2 depending on whether integration was in a forward or backward direction at the time of failure.
FINFO 10
The value of the independent variable, x, the point at which the error occurred.
FINFO 11, FINFO 12, FINFO 13
The current values of the Pruefer dependent variables β, ϕ and ρ respectively. See Section 3 in D02KEF for a description of these variables.
FINFO 14
The local-error tolerance being used by the internal integrator at the point of failure.
FINFO 15
The last integration mesh point.
MONIT must either be a module subprogram USEd by, or declared as EXTERNAL in, the (sub)program from which D02KAF is called. Arguments denoted as Input must not be changed by this procedure.
10:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, | K<0,
or | TOL≤0.0.
IFAIL=2
On entry, | a 1=p a a 2=0,
or | b 1=p b b 2=0,
(the array BCOND has been set up incorrectly).
IFAIL=3
At some point between XL and XR the value of p x computed by COEFFN became zero or changed sign. See the last call of MONIT for details.
IFAIL=4
After 15 iterations the eigenvalue had not been found to the required accuracy.
IFAIL=5
The ‘bracketing’ phase (with IFLAG of the MONIT equal to 1) failed to bracket the eigenvalue within ten iterations. This is caused by an error in formulating the problem (for example, q is independent of λ), or by very poor initial estimates of ELAM and DELAM.
On exit, ELAM and ELAM+DELAM give the end points of the interval within which no eigenvalue was located by the routine.
IFAIL=6
To obtain the desired accuracy the local error tolerance was set so small at the start of some sub-interval that the differential equation solver could not choose an initial step size large enough to make significant progress. See the last call of MONIT for diagnostics.
IFAIL=7
At some point the step size in the differential equation solver was reduced to a value too small to make significant progress (for the same reasons as with IFAIL=6). This could be due to pathological behaviour of p x and q x;λ or to an unreasonable accuracy requirement or to the current value of λ making the equations ‘stiff’. See the last call of MONIT for details.
IFAIL=8
TOL is too small for the problem being solved and the machine precision being used. The local value of ELAM should be a very good approximation to the eigenvalue λ~.
IFAIL=9
C05AZF, called by D02KAF, has terminated with the error exit corresponding to a pole of the matching function. This error exit should not occur, but if it does, try solving the problem again with a smaller value for TOL.
Note: error exits with IFAIL=2, 3, 6, 7 or 9 are caused by the inability to set up or solve the differential equation at some iteration and will be immediately preceded by a call of MONIT giving diagnostic information.
IFAIL=10
IFAIL=11
IFAIL=12
A serious error has occurred in an internal call to an interpolation routine. Check all (sub)program calls and array dimensions. Seek expert help.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

The absolute accuracy of the computed eigenvalue is usually within a mixed absolute/relative bound defined by TOL (as defined above).

8 Parallelism and Performance

D02KAF is not threaded in any implementation.

9 Further Comments

The time taken by D02KAF depends on the complexity of the coefficient functions, whether they or their derivatives are rapidly changing, the tolerance demanded, and how many iterations are needed to obtain convergence. The amount of work per iteration is roughly doubled when TOL is divided by 16. To make the most economical use of the routine, one should try to obtain good initial values for ELAM and DELAM.
See Section 9 in D02KDF for a discussion of the technique used.

10 Example

This example finds the fourth eigenvalue of Mathieu's equations
y′′+λ-2 q cos⁡2 x y=0
with boundary conditions
y′0=y′π =0
and q=5. We use a starting value ELAM=15.0 and a step DELAM=4.0. We illustrate the effect of varying TOL by choosing TOL=1.0E−5 and 1.0E−6 (note the change in the output value of the error estimate DELAM). The range of integration and initial estimates are read from a data file.

10.1 Program Text

Program Text (d02kafe.f90)

10.2 Program Data

Program Data (d02kafe.d)

10.3 Program Results

Program Results (d02kafe.r)

D02 Chapter Contents
D02 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


D02KDF : NAG Library, Mark 26

D02 Chapter Contents
D02 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

D02KDF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
▸▿ 9 Further Comments
9.1 Timing
9.2 General Description of the Algorithm
9.3 The Position of the Shooting Matching Point c
9.4 Examples of Coding the COEFFN
9.5 Examples of Boundary Conditions at Singular Points
9.6 The Sensitivity Parameters σ_l and σ_r
9.7 Missed Zeros
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

D02KDF finds a specified eigenvalue of a regular or singular second-order Sturm–Liouville system on a finite or infinite interval, using a Pruefer transformation and a shooting method. Provision is made for discontinuities in the coefficient functions or their derivatives.

2 Specification

SUBROUTINE D02KDF ( XPOINT, M, COEFFN, BDYVAL, K, TOL, ELAM, DELAM, HMAX, MAXIT, MAXFUN, MONIT, IFAIL)
INTEGER | M, K, MAXIT, MAXFUN, IFAIL
REAL (KIND=nag_wp) | XPOINT(M), TOL, ELAM, DELAM, HMAX(2,M)
EXTERNAL | COEFFN, BDYVAL, MONIT

3 Description

D02KDF finds a specified eigenvalue λ~ of a Sturm–Liouville system defined by a self-adjoint differential equation of the second-order
p x y′ ′ + q x;λ y=0 ,   a<x<b ,
together with appropriate boundary conditions at the two, finite or infinite, end points a and b. The functions p and q, which are real-valued, are defined by COEFFN. The boundary conditions must be defined by BDYVAL, and, in the case of a singularity at a or b, take the form of an asymptotic formula for the solution near the relevant end point.
For the theoretical basis of the numerical method to be valid, the following conditions should hold on the coefficient functions:
(a) | p x must be nonzero and must not change sign throughout the interval a,b; and,
(b) | ∂q ∂λ must not change sign throughout the interval a,b for all relevant values of λ, and must not be identically zero as x varies, for any λ.
Points of discontinuity in the functions p and q or their derivatives are allowed, and should be included as ‘break-points’ in the array XPOINT.
The eigenvalue λ~ is determined by a shooting method based on the Scaled Pruefer form of the differential equation as described in Pryce (1981), with certain modifications. The Pruefer equations are integrated by a special internal routine using Merson's Runge–Kutta formula with automatic control of local error. Providing certain assumptions (see Section 9.1) are met, the computed value of λ~ will be correct to within a mixed absolute/relative error specified by TOL.
A good account of the theory of Sturm–Liouville systems, with some description of Pruefer transformations, is given in Chapter X of Birkhoff and Rota (1962). An introduction to the use of Pruefer transformations for the numerical solution of eigenvalue problems arising from physics and chemistry is given in Bailey (1966).
The scaled Pruefer method is described in a short note by Pryce and Hargrave (1977) and in some detail in the technical report by Pryce (1981).

4 References

Abramowitz M and Stegun I A (1972) Handbook of Mathematical Functions (3rd Edition) Dover Publications
Bailey P B (1966) Sturm–Liouville eigenvalues via a phase function SIAM J. Appl. Math. 14 242–249
Banks D O and Kurowski I (1968) Computation of eigenvalues of singular Sturm–Liouville Systems Math. Comput. 22 304–310
Birkhoff G and Rota G C (1962) Ordinary Differential Equations Ginn & Co., Boston and New York
Pryce J D (1981) Two codes for Sturm–Liouville problems Technical Report CS-81-01 Department of Computer Science, Bristol University
Pryce J D and Hargrave B A (1977) The scaled Prüfer method for one-parameter and multi-parameter eigenvalue problems in ODEs IMA Numerical Analysis Newsletter 1(3)

5 Arguments

1:   XPOINT M – REAL (KIND=nag_wp) arrayInput
On entry: the points where the boundary conditions computed by BDYVAL are to be imposed, and also any break-points, i.e., XPOINT 1 to XPOINT m must contain values x 1,…,xm such that
x 1≤x 2<x 3<⋯<x m-1≤xm
with the following meanings:
(a) x 1 and xm are the left- and right-hand end points, a and b, of the domain of definition of the Sturm–Liouville system if these are finite. If either a or b is infinite, the corresponding value x 1 or xm may be a more-or-less arbitrarily ‘large’ number of appropriate sign.
(b) x 2 and x m-1 are the Boundary Matching Points (BMPs), that is the points at which the left and right boundary conditions computed in BDYVAL are imposed.
If the left-hand end point is a regular point then you should set x 2=x 1 =a, while if it is a singular point you must set x 2>x 1. Similarly x m-1=xm (=b) if the right-hand end point is regular, and x m-1<xm if it is singular.
(c) The remaining m-4 points x 3,…,x m-2, if any, define ‘break-points’ which divide the interval x 2,x m-1 into m-3 sub-intervals
i 1=x 2,x 3,…,i m-3=x m-2,x m-1.
Numerical integration of the differential equation is stopped and restarted at each break-point. In simple cases no break-points are needed. However, if p x or q x;λ are given by different formulae in different parts of the interval, then integration is more efficient if the range is broken up by break-points in the appropriate way. Similarly points where any jumps occur in p x or q x;λ, or in their derivatives up to the fifth-order, should appear as break-points.
Examples are given in Sections 9 and 10. XPOINT determines the position of the Shooting Matching Point (SMP), as explained in Section 9.3.
Constraint: XPOINT 1≤XPOINT 2<⋯<XPOINT M-1≤XPOINT M.
2:   M – INTEGERInput
On entry: the number of points in the array XPOINT.
Constraint: M≥4.
3:   COEFFN – SUBROUTINE, supplied by the user.External Procedure
COEFFN must compute the values of the coefficient functions p x and q x;λ for given values of x and λ. Section 3 states the conditions which p and q must satisfy. See Sections 9.4 and 10 for examples.
The specification of COEFFN is:
SUBROUTINE COEFFN ( P, Q, DQDL, X, ELAM, JINT)
INTEGER | JINT
REAL (KIND=nag_wp) | P, Q, DQDL, X, ELAM
1:   P – REAL (KIND=nag_wp)Output
On exit: the value of p x for the current value of x.
2:   Q – REAL (KIND=nag_wp)Output
On exit: the value of q x;λ for the current value of x and the current trial value of λ.
3:   DQDL – REAL (KIND=nag_wp)Output
On exit: the value of ∂q ∂λ x;λ for the current value of x and the current trial value of λ. However DQDL is only used in error estimation and, in the rare cases where it may be difficult to evaluate, an approximation (say to within 20%) will suffice.
4:   X – REAL (KIND=nag_wp)Input
On entry: the current value of x.
5:   ELAM – REAL (KIND=nag_wp)Input
On entry: the current trial value of the eigenvalue argument λ.
6:   JINT – INTEGERInput
On entry: the index j of the sub-interval ij (see specification of XPOINT) in which x lies.
COEFFN must either be a module subprogram USEd by, or declared as EXTERNAL in, the (sub)program from which D02KDF is called. Arguments denoted as Input must not be changed by this procedure.
4:   BDYVAL – SUBROUTINE, supplied by the user.External Procedure
BDYVAL must define the boundary conditions. For each end point, BDYVAL must return (in YL or YR) values of y x and p x y′x which are consistent with the boundary conditions at the end points; only the ratio of the values matters. Here x is a given point (XL or XR) equal to, or close to, the end point.
For a regular end point (a, say), x=a, a boundary condition of the form
c 1 y a+c 2 y′a=0
can be handled by returning constant values in YL, e.g., YL 1=c 2 and YL 2=-c 1 p a.
For a singular end point however, YL 1 and YL 2 will in general be functions of XL and ELAM, and YR 1 and YR 2 functions of XR and ELAM, usually derived analytically from a power-series or asymptotic expansion. Examples are given in Sections 9.5 and 10.
The specification of BDYVAL is:
SUBROUTINE BDYVAL ( XL, XR, ELAM, YL, YR)
REAL (KIND=nag_wp) XL, XR, ELAM, YL(3), YR(3)
1:   XL – REAL (KIND=nag_wp)Input
On entry: if a is a regular end point of the system (so that a=x 1=x 2), then XL contains a. If a is a singular point (so that a≤x 1<x 2), then XL contains a point x such that x 1<x≤x 2.
2:   XR – REAL (KIND=nag_wp)Input
On entry: if b is a regular end point of the system (so that x m-1=xm=b), then XR contains b. If b is a singular point (so that x m-1<xm≤b), then XR contains a point x such that x m-1≤x<xm.
3:   ELAM – REAL (KIND=nag_wp)Input
On entry: the current trial value of λ.
4:   YL 3 – REAL (KIND=nag_wp) arrayOutput
On exit: YL 1 and YL 2 should contain values of y x and p x y′x respectively (not both zero) which are consistent with the boundary condition at the left-hand end point, given by x=XL. YL 3 should not be set.
5:   YR 3 – REAL (KIND=nag_wp) arrayOutput
On exit: YR 1 and YR 2 should contain values of y x and p x y′x respectively (not both zero) which are consistent with the boundary condition at the right-hand end point, given by x=XR. YR 3 should not be set.
BDYVAL must either be a module subprogram USEd by, or declared as EXTERNAL in, the (sub)program from which D02KDF is called. Arguments denoted as Input must not be changed by this procedure.
5:   K – INTEGERInput
On entry: k, the index of the required eigenvalue when the eigenvalues are ordered
λ 0 < λ 1 < λ 2 < ⋯ < λk < ⋯ .
Constraint: K≥0.
6:   TOL – REAL (KIND=nag_wp)Input
On entry: the tolerance argument which determines the accuracy of the computed eigenvalue. The error estimate held in DELAM on exit satisfies the mixed absolute/relative error test
DELAM≤TOL×max 1.0,ELAM, (1)
where ELAM is the final estimate of the eigenvalue. DELAM is usually somewhat smaller than the right-hand side of (1) but not several orders of magnitude smaller.
Constraint: TOL>0.0.
7:   ELAM – REAL (KIND=nag_wp)Input/Output
On entry: an initial estimate of the eigenvalue λ~.
On exit: the final computed estimate, whether or not an error occurred.
8:   DELAM – REAL (KIND=nag_wp)Input/Output
On entry: an indication of the scale of the problem in the λ-direction. DELAM holds the initial ‘search step’ (positive or negative). Its value is not critical, but the first two trial evaluations are made at ELAM and ELAM+DELAM, so the routine will work most efficiently if the eigenvalue lies between these values. A reasonable choice (if a closer bound is not known) is half the distance between adjacent eigenvalues in the neighbourhood of the one sought. In practice, there will often be a problem, similar to the one in hand but with known eigenvalues, which will help one to choose initial values for ELAM and DELAM.
If DELAM=0.0 on entry, it is given the default value of 0.25×max 1.0,ELAM.
On exit: if IFAIL=0, DELAM holds an estimate of the absolute error in the computed eigenvalue, that is λ~-ELAM≃DELAM. (In Section 9.2 we discuss the assumptions under which this is true.) The true error is rarely more than twice, or less than a tenth, of the estimated error.
If IFAIL≠0, DELAM may hold an estimate of the error, or its initial value, depending on the value of IFAIL. See Section 6 for further details.
9:   HMAX 2 M – REAL (KIND=nag_wp) arrayInput/Output
On entry: HMAX 1 j should contain a maximum step size to be used by the differential equation code in the jth sub-interval ij (as described in the specification of argument XPOINT), for j=1,2,…,m-3. If it is zero the routine generates a maximum step size internally.
It is recommended that HMAX 1 j be set to zero unless the coefficient functions p and q have features (such as a narrow peak) within the jth sub-interval that could be ‘missed’ if a long step were taken. In such a case HMAX 1 j should be set to about half the distance over which the feature should be observed. Too small a value will increase the computing time for the routine. See Section 9 for further suggestions.
The rest of the array is used as workspace.
On exit: HMAX 1 m-1 and HMAX 1 m contain the sensitivity coefficients σl,σr, described in Section 9.6. Other entries contain diagnostic output in the case of an error exit (see Section 6).
10:   MAXIT – INTEGERInput/Output
On entry: a bound on nr, the number of root-finding iterations allowed, that is the number of trial values of λ that are used. If MAXIT≤0, no such bound is assumed. (See also MAXFUN.)
Suggested value: MAXIT=0.
On exit: will have been decreased by the number of iterations actually performed, whether or not it was positive on entry.
11:   MAXFUN – INTEGERInput
On entry: a bound on nf, the number of calls to COEFFN made in any one root-finding iteration. If MAXFUN≤0, no such bound is assumed.
Suggested value: MAXFUN=0.
MAXFUN and MAXIT may be used to limit the computational cost of a call to D02KDF, which is roughly proportional to nr×nf.
12:   MONIT – SUBROUTINE, supplied by the NAG Library or the user.External Procedure
MONIT is called by D02KDF at the end of each root-finding iteration and allows you to monitor the course of the computation by printing out the arguments (see Section 10 for an example).
If no monitoring is required, the dummy (sub)program D02KAY may be used. (D02KAY is included in the NAG Library.)
The specification of MONIT is:
SUBROUTINE MONIT ( NIT, IFLAG, ELAM, FINFO)
INTEGER | NIT, IFLAG
REAL (KIND=nag_wp) | ELAM, FINFO(15)
1:   NIT – INTEGERInput
On entry: the current value of the argument MAXIT of D02KDF, this is decreased by one at each iteration.
2:   IFLAG – INTEGERInput
On entry: describes what phase the computation is in.
IFLAG<0
An error occurred in the computation at this iteration; an error exit from D02KDF with IFAIL=-IFLAG will follow.
IFLAG=1
The routine is trying to bracket the eigenvalue λ~.
IFLAG=2
The routine is converging to the eigenvalue λ~ (having already bracketed it).
3:   ELAM – REAL (KIND=nag_wp)Input
On entry: the current trial value of λ.
4:   FINFO 15 – REAL (KIND=nag_wp) arrayInput
On entry: information about the behaviour of the shooting method, and diagnostic information in the case of errors. It should not normally be printed in full if no error has occurred (that is, if IFLAG>0), though the first few components may be of interest to you. In case of an error (IFLAG<0) all the components of FINFO should be printed.
The contents of FINFO are as follows:
FINFO 1
The current value of the ‘miss-distance’ or ‘residual’ function f λ on which the shooting method is based. (See Section 9.2 for further information.) FINFO 1 is set to zero if IFLAG<0.
FINFO 2
An estimate of the quantity ∂λ defined as follows. Consider the perturbation in the miss-distance f λ that would result if the local error in the solution of the differential equation were always positive and equal to its maximum permitted value. Then ∂λ is the perturbation in λ that would have the same effect on f λ. Thus, at the zero of f λ,∂λ is an approximate bound on the perturbation of the zero (that is the eigenvalue) caused by errors in numerical solution. If ∂λ is very large then it is possible that there has been a programming error in COEFFN such that q is independent of λ. If this is the case, an error exit with IFAIL=5 should follow. FINFO 2 is set to zero if IFLAG<0.
FINFO 3
The number of internal iterations, using the same value of λ and tighter accuracy tolerances, needed to bring the accuracy (that is, the value of ∂λ) to an acceptable value. Its value should normally be 1.0, and should almost never exceed 2.0.
FINFO 4
The number of calls to COEFFN at this iteration.
FINFO 5
The number of successful steps taken by the internal differential equation solver at this iteration. A step is successful if it is used to advance the integration.
FINFO 6
The number of unsuccessful steps used by the internal integrator at this iteration.
FINFO 7
The number of successful steps at the maximum step size taken by the internal integrator at this iteration.
FINFO 8
Not used.
FINFO 9 to FINFO 15
Set to zero, unless IFLAG<0 in which case they hold the following values describing the point of failure:
FINFO 9
The index of the sub-interval where failure occurred, in the range 1 to m-3. In case of an error in BDYVAL, it is set to 0 or m-2 depending on whether the left or right boundary condition caused the error.
FINFO 10
The value of the independent variable, x, the point at which the error occurred. In case of an error in BDYVAL, it is set to the value of XL or XR as appropriate (see the specification of BDYVAL).
FINFO 11, FINFO 12, FINFO 13
The current values of the Pruefer dependent variables β, ϕ and ρ respectively. These are set to zero in case of an error in BDYVAL. (See D02KEF for a description of these variables.)
FINFO 14
The local-error tolerance being used by the internal integrator at the point of failure. This is set to zero in the case of an error in BDYVAL.
FINFO 15
The last integration mesh point. This is set to zero in the case of an error in BDYVAL.
MONIT must either be a module subprogram USEd by, or declared as EXTERNAL in, the (sub)program from which D02KDF is called. Arguments denoted as Input must not be changed by this procedure.
13:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
A argument error. All arguments (except IFAIL) are left unchanged. The reason for the error is shown by the value of HMAX 21 as follows:
HMAX 21=1: M<4;
HMAX 21=2: K<0;
HMAX 21=3: TOL≤0.0;
HMAX 21=4: XPOINT 1 to XPOINT m are not in ascending order. HMAX 22 gives the position i in XPOINT where this was detected.
IFAIL=2
At some call to BDYVAL, invalid values were returned, that is, either YL 1=YL 2=0.0, or YR 1=YR 2=0.0 (a programming error in BDYVAL). See the last call of MONIT for details.
This error exit will also occur if p x is zero at the point where the boundary condition is imposed. Probably BDYVAL was called with XL equal to a singular end point a or with XR equal to a singular end point b.
IFAIL=3
At some point between XL and XR the value of p x computed by COEFFN became zero or changed sign. See the last call of MONIT for details.
IFAIL=4
MAXIT>0 on entry, and after MAXIT iterations the eigenvalue had not been found to the required accuracy.
IFAIL=5
The ‘bracketing’ phase (with argument IFLAG of the MONIT equal to 1) failed to bracket the eigenvalue within ten iterations. This is caused by an error in formulating the problem (for example, q is independent of λ), or by very poor initial estimates of ELAM and DELAM.
On exit, ELAM and ELAM+DELAM give the end points of the interval within which no eigenvalue was located by the routine.
IFAIL=6
MAXFUN>0 on entry, and the last iteration was terminated because more than MAXFUN calls to COEFFN were used. See the last call of MONIT for details.
IFAIL=7
To obtain the desired accuracy the local error tolerance was set so small at the start of some sub-interval that the differential equation solver could not choose an initial step size large enough to make significant progress. See the last call of MONIT for diagnostics.
IFAIL=8
At some point inside a sub-interval the step size in the differential equation solver was reduced to a value too small to make significant progress (for the same reasons as with IFAIL=7). This could be due to pathological behaviour of p x and q x;λ or to an unreasonable accuracy requirement or to the current value of λ making the equations ‘stiff’. See the last call of MONIT for details.
IFAIL=9
TOL is too small for the problem being solved and the machine precision is being used. The final value of ELAM should be a very good approximation to the eigenvalue.
IFAIL=10
C05AZF, called by D02KDF, has terminated with the error exit corresponding to a pole of the residual function f λ. This error exit should not occur, but if it does, try solving the problem again with a smaller value for TOL.
IFAIL=11
IFAIL=12
A serious error has occurred in an internal call. Check all (sub)program calls and array dimensions. Seek expert help.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.
Note: error exits with IFAIL=2, 3, 6, 7, 8 or 11 are caused by being unable to set up or solve the differential equation at some iteration and will be immediately preceded by a call of MONIT giving diagnostic information. For other errors, diagnostic information is contained in HMAX 2 j, for j=1,2,…,m, where appropriate.

7 Accuracy

See the discussion in Section 9.2.

8 Parallelism and Performance

D02KDF is not threaded in any implementation.

9 Further Comments

9.1 Timing

The time taken by D02KDF depends on the complexity of the coefficient functions, whether they or their derivatives are rapidly changing, the tolerance demanded, and how many iterations are needed to obtain convergence. The amount of work per iteration is roughly doubled when TOL is divided by 16. To make the most economical use of the routine, one should try to obtain good initial values for ELAM and DELAM, and, where appropriate, good asymptotic formulae. Also the boundary matching points should not be set unnecessarily close to singular points.

9.2 General Description of the Algorithm

A shooting method, for differential equation problems containing unknown parameters, relies on the construction of a ‘miss-distance function’, which for given trial values of the parameters measures how far the conditions of the problem are from being met. The problem is then reduced to one of finding the values of the parameters for which the miss-distance function is zero, that is to a root-finding process. Shooting methods differ mainly in how the miss-distance is defined.
D02KDF defines a miss-distance f λ based on the rotation about the origin of the point P x=p x y′x,y x in the Phase Plane as the solution proceeds from a to b. The boundary conditions define the ray (i.e., two-sided line through the origin) on which p x should start, and the ray on which it should finish. The eigenvalue k defines the total number of half-turns it should make. Numerical solution is actually done by ‘shooting forward’ from x=a and ‘shooting backward’ from x=b to a matching point x=c. Then f λ is taken as the angle between the rays to the two resulting points Pa c and Pb c. A relative scaling of the p y′ and y axes, based on the behaviour of the coefficient functions p and q, is used to improve the numerical behaviour.
GnuplotProduced by GNUPLOT 4.6 patchlevel 3 P(a) P(b) Pb(c) Pa(c) py' y gnuplot_plot_1 gnuplot_plot_2
Figure 1
The resulting function f λ is monotonic over -∞<λ<∞, increasing if ∂q ∂λ >0 and decreasing if ∂q ∂λ <0, with a unique zero at the desired eigenvalue λ~. The routine measures f λ in units of a half-turn. This means that as λ increases, f λ varies by about 1 as each eigenvalue is passed. (This feature implies that the values of f λ at successive iterations – especially in the early stages of the iterative process – can be used with suitable extrapolation or interpolation to help the choice of initial estimates for eigenvalues near to the one currently being found.)
The routine actually computes a value for f λ with errors, arising from the local errors of the differential equation code and from the asymptotic formulae provided by you if singular points are involved. However, the error estimate output in DELAM is usually fairly realistic, in that the actual error λ~-ELAM is within an order of magnitude of DELAM.

9.3 The Position of the Shooting Matching Point c

This point is always one of the values xi in array XPOINT. It is chosen to be the value of that xi, 2≤i≤m-1, that lies closest to the middle of the interval x 2,x m-1. If there is a tie, the rightmost candidate is chosen. In particular if there are no break-points, then c=x m-1 (=x 3); that is, the shooting is from left to right in this case. A break-point may be inserted purely to move c to an interior point of the interval, even though the form of the equations does not require it. This often speeds up convergence especially with singular problems.

9.4 Examples of Coding the COEFFN

Coding COEFFN is straightforward except when break-points are needed. The examples below show:
(a) | a simple case,
(b) | a case in which discontinuities in the coefficient functions or their derivatives necessitate break-points, and
(c) | a case where break-points together with the HMAX argument are an efficient way to deal with a coefficient function that is well-behaved except over one short interval.
(Some of these cases are among the examples in Section 10.)
Example A
The modified Bessel equation
x x y′ ′ + λ x 2-ν 2 y=0 .
Assuming the interval of solution does not contain the origin and dividing through by x, we have p x=x and q x;λ=λx-ν 2/x. The code could be
SUBROUTINE COEFFN (P,Q,DQDL,X,ELAM,JINT)
...
P = X
Q = ELAM*X - NU*NU/X
DQDL = X
RETURN
END
where NU (standing for ν) is a real variable that might be defined in a DATA statement, or might be in user-declared COMMON so that its value could be set in the main program.
Example B
The Schroedinger equation
y′′+λ+q x y=0,
where
q x = x 2- 10 x≤ 4, 6 x x> 4,
over some interval ‘approximating to -∞,∞’, say -20,20. Here we need break-points at ±4, forming three sub-intervals i 1=-20,-4, i 2=-4,4, i 3=4,20. The code could be
SUBROUTINE COEFFN(P,Q,DQDL,X,ELAM,JINT)
...
IF (JINT.EQ.2) THEN
  Q = ELAM + X*X - 10.0E0
ELSE
  Q = ELAM + 6.0E0/ABS(X)
ENDIF
P = 1.0E0
DQDL = 1.0E0
RETURN
END
The array XPOINT would contain the values x 1, -20.0, -4.0, +4.0, +20.0, x 6 and m would be 6. The choice of appropriate values for x 1 and x 6 depends on the form of the asymptotic formula computed by BDYVAL and the technique is discussed in Section 9.5.
Example C
y′′+λ 1-2⁢e-100⁢x 2 y=0,  -10≤x≤10.
Here q x;λ is nearly constant over the range except for a sharp inverted spike over approximately -0.1≤x≤0.1. There is a danger that the routine will build up to a large step size and ‘step over’ the spike without noticing it. By using break-points – say at ±0.5 – one can restrict the step size near the spike without impairing the efficiency elsewhere.
The code for COEFFN could be
SUBROUTINE COEFFN(P,Q,DQDL,X,ELAM,JINT)
...
P = 1.0E0
DQDL = 1.0E0 - 2.0E0*EXP(-100.0E0*X*X)
Q = ELAM*DQDL
RETURN
END
XPOINT might contain -10.0, -10.0, -0.5, 0.5, 10.0, 10.0 (assuming ±10 are regular points) and m would be 6. HMAX 1 j, for j=1,2,3, might contain 0.0, 0.1 and 0.0.

9.5 Examples of Boundary Conditions at Singular Points

Quoting from page 243 of Bailey (1966): ‘Usually ... the differential equation has two essentially different types of solution near a singular point, and the boundary condition there merely serves to distinguish one kind from the other. This is the case in all the standard examples of mathematical physics.’
In most cases the behaviour of the ratio p x y′/y near the point is quite different for the two types of solution. Essentially what you provide through the BDYVAL is an approximation to this ratio, valid as x tends to the singular point (SP).
You must decide (a) how accurate to make this approximation or asymptotic formula, for example how many terms of a series to use, and (b) where to place the boundary matching point (BMP) at which the numerical solution of the differential equation takes over from the asymptotic formula. Taking the BMP closer to the SP will generally improve the accuracy of the asymptotic formula, but will make the computation more expensive as the Pruefer differential equations generally become progressively more ill-behaved as the SP is approached. You are strongly recommended to experiment with placing the BMPs. In many singular problems quite crude asymptotic formulae will do. To help you avoid needlessly accurate formulae, D02KDF outputs two ‘sensitivity coefficients’ σl,σr which estimate how much the errors at the BMPs affect the computed eigenvalue. They are described in detail in Section 9.6.
Example of coding BDYVAL:
The example below illustrates typical situations:
y′′+λ-x-2 x 2 y=0,  0<x<∞
the boundary conditions being that y should remain bounded as x tends to 0 and x tends to ∞.
At the end x=0 there is one solution that behaves like x 2 and another that behaves like x-1. For the first of these solutions p x y′/y is asymptotically 2/x while for the second it is asymptotically -1/x. Thus the desired ratio is specified by setting
YL 1=x  and  YL 2=2.0.
At the end x=∞ the equation behaves like Airy's equation shifted through λ, i.e., like y′′-ty=0 where t=x-λ, so again there are two types of solution. The solution we require behaves as
exp-23 t 32/t 4
and the other as
exp+23 t 32/t 4.
Hence, the desired solution has p x y′/y∼-t so that we could set YR 1=1.0 and YR 2=-x-λ. The complete subroutine might thus be
SUBROUTINE BDYVAL (XL,XR,ELAM,YL,YR)
real XL, XR, ELAM, YL(3), YR(3)
YL(1) = XL
YL(2) = 2.0E0
YR(1) = 1.0E0
YR(2) = -SQRT(XR-ELAM)
RETURN
END
Clearly for this problem it is essential that any value given by D02KDF to XR is well to the right of the value of ELAM, so that you must vary the right-hand BMP with the eigenvalue index k. One would expect λk to be near the kth zero of the Airy function Ai x, so there is no problem estimating ELAM.
More accurate asymptotic formulae are easily found: near x=0 by the standard Frobenius method, and near x=∞ by using standard asymptotics for Ai x, Ai′x, (see page 448 of Abramowitz and Stegun (1972)).
For example, by the Frobenius method the solution near x=0 has the expansion
y=x 2 c 0+c 1 x+c 2 x 2+⋯
with
c 0= 1,c 1= 0, c 2=-λ 10, c 3=118,⋯, cn=c n- 3-λ c n- 2 n n+ 3 .
This yields
p x y′y=2-25 λ x 2+⋯ x 1-λ 10 x 2+⋯ .

9.6 The Sensitivity Parameters σl and σr

The sensitivity parameters σl, σr (held in HMAX 1 m-1 and HMAX 1 m on output) estimate the effect of errors in the boundary conditions. For sufficiently small errors Δy, Δp y′ in y and p y′ respectively, the relations
Δλ≃y.Δp y′-p y′.Δy lσl Δλ≃y.Δp y′-p y′.Δy rσr
are satisfied, where the subscripts l, r denote errors committed at the left- and right-hand BMPs respectively, and Δλ denotes the consequent error in the computed eigenvalue.

9.7 ‘Missed Zeros’

This is a pitfall to beware of at a singular point. If the BMP is chosen so far from the SP that a zero of the desired eigenfunction lies in between them, then the routine will fail to ‘notice’ this zero. Since the index of k of an eigenvalue is the number of zeros of its eigenfunction, the result will be that
(a) | the wrong eigenvalue will be computed for the given index k – in fact some λ k+k′ will be found where k′≥1;
(b) | the same index k can cause convergence to any of several eigenvalues depending on the initial values of ELAM and DELAM.
It is up to you to take suitable precautions – for instance by varying the position of the BMPs in the light of knowledge of the asymptotic behaviour of the eigenfunction at different eigenvalues.

10 Example

This example finds the 11th eigenvalue of the example of Section 9.5, using the simple asymptotic formulae for the boundary conditions. The results exhibit slow convergence, mainly because XPOINT is set so that the shooting matching point c is at the right-hand end x=30.0. The example results for D02KEF show that much faster convergence is obtained if XPOINT is set to contain an additional break-point at or near the maximum of the coefficient function q x;λ, which in this case is at x=43.

10.1 Program Text

Program Text (d02kdfe.f90)

10.2 Program Data

Program Data (d02kdfe.d)

10.3 Program Results

Program Results (d02kdfe.r)

D02 Chapter Contents
D02 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


D02KEF : NAG Library, Mark 26

D02 Chapter Contents
D02 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

D02KEF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
▸▿ 9 Further Comments
9.1 Timing
9.2 General Description of the Algorithm
9.3 The Position of the Shooting Matching Point c
9.4 Examples of Coding the COEFFN
9.5 Examples of Boundary Conditions at Singular Points
9.6 The Sensitivity Parameters σ_l and σ_r
9.7 Missed Zeros
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

D02KEF finds a specified eigenvalue of a regular or singular second-order Sturm–Liouville system on a finite or infinite interval, using a Pruefer transformation and a shooting method. It also reports values of the eigenfunction and its derivatives. Provision is made for discontinuities in the coefficient functions or their derivatives.

2 Specification

SUBROUTINE D02KEF ( XPOINT, M, MATCH, COEFFN, BDYVAL, K, TOL, ELAM, DELAM, HMAX, MAXIT, MAXFUN, MONIT, REPORT, IFAIL)
INTEGER | M, MATCH, K, MAXIT, MAXFUN, IFAIL
REAL (KIND=nag_wp) | XPOINT(M), TOL, ELAM, DELAM, HMAX(2,M)
EXTERNAL | COEFFN, BDYVAL, MONIT, REPORT

3 Description

D02KEF has essentially the same purpose as D02KDF with minor modifications to enable values of the eigenfunction to be obtained after convergence to the eigenvalue has been achieved.
It first finds a specified eigenvalue λ~ of a Sturm–Liouville system defined by a self-adjoint differential equation of the second-order
p x y′ ′ + q x;λ y=0 ,   a<x<b ,
together with appropriate boundary conditions at the two, finite or infinite, end points a and b. The functions p and q, which are real-valued, are defined by COEFFN. The boundary conditions must be defined by BDYVAL, and, in the case of a singularity at a or b, take the form of an asymptotic formula for the solution near the relevant end point.
When the final estimate λ=λ~ of the eigenvalue has been found, the routine integrates the differential equation once more with that value of λ, and with initial conditions chosen so that the integral
S=∫ab y x 2 ∂q ∂λ x;λ dx
is approximately one. When q x;λ is of the form λw x+q x, which is the most common case, S represents the square of the norm of y induced by the inner product
f,g = ∫ab f x g x w x dx ,
with respect to which the eigenfunctions are mutually orthogonal. This normalization of y is only approximate, but experience shows that S generally differs from unity by only one or two per cent.
During this final integration the REPORT is called at each integration mesh point x. Sufficient information is returned to permit you to compute y x and y′x for printing or plotting. For reasons described in Section 9.2, D02KEF passes across to REPORT, not y and y′, but the Pruefer variables β, ϕ and ρ on which the numerical method is based. Their relationship to y and y′ is given by the equations
p x y′ = β exp ρ 2 cos ϕ 2 ,   y=1 β exp ρ 2 sin ϕ 2 .
A specimen REPORT is given in Section 10 below.
For the theoretical basis of the numerical method to be valid, the following conditions should hold on the coefficient functions:
(a) | p x must be nonzero and must not change sign throughout the interval a,b; and,
(b) | ∂q ∂λ must not change sign throughout the interval a,b for all relevant values of λ, and must not be identically zero as x varies, for any λ.
Points of discontinuity in the functions p and q or their derivatives are allowed, and should be included as ‘break-points’ in the array XPOINT.
A good account of the theory of Sturm–Liouville systems, with some description of Pruefer transformations, is given in Chapter X of Birkhoff and Rota (1962). An introduction to the use of Pruefer transformations for the numerical solution of eigenvalue problems arising from physics and chemistry is given in Bailey (1966).
The scaled Pruefer method is described in a short note by Pryce and Hargrave (1977) and in some detail in the technical report by Pryce (1981).

4 References

Abramowitz M and Stegun I A (1972) Handbook of Mathematical Functions (3rd Edition) Dover Publications
Bailey P B (1966) Sturm–Liouville eigenvalues via a phase function SIAM J. Appl. Math. 14 242–249
Banks D O and Kurowski I (1968) Computation of eigenvalues of singular Sturm–Liouville Systems Math. Comput. 22 304–310
Birkhoff G and Rota G C (1962) Ordinary Differential Equations Ginn & Co., Boston and New York
Pryce J D (1981) Two codes for Sturm–Liouville problems Technical Report CS-81-01 Department of Computer Science, Bristol University
Pryce J D and Hargrave B A (1977) The scaled Prüfer method for one-parameter and multi-parameter eigenvalue problems in ODEs IMA Numerical Analysis Newsletter 1(3)

5 Arguments

1:   XPOINT M – REAL (KIND=nag_wp) arrayInput
On entry: the points where the boundary conditions computed by BDYVAL are to be imposed, and also any break-points, i.e., XPOINT 1 to XPOINT m must contain values x 1,…,xm such that
x 1≤x 2<x 3<⋯<x m-1≤xm
with the following meanings:
(a) x 1 and xm are the left- and right-hand end points, a and b, of the domain of definition of the Sturm–Liouville system if these are finite. If either a or b is infinite, the corresponding value x 1 or xm may be a more-or-less arbitrarily ‘large’ number of appropriate sign.
(b) x 2 and x m-1 are the Boundary Matching Points (BMPs), that is the points at which the left and right boundary conditions computed in BDYVAL are imposed.
If the left-hand end point is a regular point then you should set x 2=x 1 =a, while if it is a singular point you must set x 2>x 1. Similarly x m-1=xm (=b) if the right-hand end point is regular, and x m-1<xm if it is singular.
(c) The remaining m-4 points x 3,…,x m-2, if any, define ‘break-points’ which divide the interval x 2,x m-1 into m-3 sub-intervals
i 1=x 2,x 3,…,i m-3=x m-2,x m-1.
Numerical integration of the differential equation is stopped and restarted at each break-point. In simple cases no break-points are needed. However, if p x or q x;λ are given by different formulae in different parts of the interval, then integration is more efficient if the range is broken up by break-points in the appropriate way. Similarly points where any jumps occur in p x or q x;λ, or in their derivatives up to the fifth-order, should appear as break-points.
Examples are given in Sections 9 and 10. XPOINT determines the position of the Shooting Matching Point (SMP), as explained in Section 9.3.
Constraint: XPOINT 1≤XPOINT 2<⋯<XPOINT M-1≤XPOINT M.
2:   M – INTEGERInput
On entry: the number of points in the array XPOINT.
Constraint: M≥4.
3:   MATCH – INTEGERInput/Output
On entry: must be set to the index of the ‘break-point’ to be used as the matching point (see Section 9.3). If MATCH is set to a value outside the range 2,m-1 then a default value is taken, corresponding to the break-point nearest the centre of the interval XPOINT 2,XPOINT m-1.
On exit: the index of the break-point actually used as the matching point.
4:   COEFFN – SUBROUTINE, supplied by the user.External Procedure
COEFFN must compute the values of the coefficient functions p x and q x;λ for given values of x and λ. Section 3 states the conditions which p and q must satisfy. See Sections 9.4 and 10 for examples.
The specification of COEFFN is:
SUBROUTINE COEFFN ( P, Q, DQDL, X, ELAM, JINT)
INTEGER | JINT
REAL (KIND=nag_wp) | P, Q, DQDL, X, ELAM
1:   P – REAL (KIND=nag_wp)Output
On exit: the value of p x for the current value of x.
2:   Q – REAL (KIND=nag_wp)Output
On exit: the value of q x;λ for the current value of x and the current trial value of λ.
3:   DQDL – REAL (KIND=nag_wp)Output
On exit: the value of ∂q ∂λ x;λ for the current value of x and the current trial value of λ. However DQDL is only used in error estimation and, in the rare cases where it may be difficult to evaluate, an approximation (say to within 20%) will suffice.
4:   X – REAL (KIND=nag_wp)Input
On entry: the current value of x.
5:   ELAM – REAL (KIND=nag_wp)Input
On entry: the current trial value of the eigenvalue argument λ.
6:   JINT – INTEGERInput
On entry: the index j of the sub-interval ij (see specification of XPOINT) in which x lies.
COEFFN must either be a module subprogram USEd by, or declared as EXTERNAL in, the (sub)program from which D02KEF is called. Arguments denoted as Input must not be changed by this procedure.
5:   BDYVAL – SUBROUTINE, supplied by the user.External Procedure
BDYVAL must define the boundary conditions. For each end point, BDYVAL must return (in YL or YR) values of y x and p x y′x which are consistent with the boundary conditions at the end points; only the ratio of the values matters. Here x is a given point (XL or XR) equal to, or close to, the end point.
For a regular end point (a, say), x=a, a boundary condition of the form
c 1 y a+c 2 y′a=0
can be handled by returning constant values in YL, e.g., YL 1=c 2 and YL 2=-c 1 p a.
For a singular end point however, YL 1 and YL 2 will in general be functions of XL and ELAM, and YR 1 and YR 2 functions of XR and ELAM, usually derived analytically from a power-series or asymptotic expansion. Examples are given in Sections 9.5 and 10.
The specification of BDYVAL is:
SUBROUTINE BDYVAL ( XL, XR, ELAM, YL, YR)
REAL (KIND=nag_wp) XL, XR, ELAM, YL(3), YR(3)
1:   XL – REAL (KIND=nag_wp)Input
On entry: if a is a regular end point of the system (so that a=x 1=x 2), then XL contains a. If a is a singular point (so that a≤x 1<x 2), then XL contains a point x such that x 1<x≤x 2.
2:   XR – REAL (KIND=nag_wp)Input
On entry: if b is a regular end point of the system (so that x m-1=xm=b), then XR contains b. If b is a singular point (so that x m-1<xm≤b), then XR contains a point x such that x m-1≤x<xm.
3:   ELAM – REAL (KIND=nag_wp)Input
On entry: the current trial value of λ.
4:   YL 3 – REAL (KIND=nag_wp) arrayOutput
On exit: YL 1 and YL 2 should contain values of y x and p x y′x respectively (not both zero) which are consistent with the boundary condition at the left-hand end point, given by x=XL. YL 3 should not be set.
5:   YR 3 – REAL (KIND=nag_wp) arrayOutput
On exit: YR 1 and YR 2 should contain values of y x and p x y′x respectively (not both zero) which are consistent with the boundary condition at the right-hand end point, given by x=XR. YR 3 should not be set.
BDYVAL must either be a module subprogram USEd by, or declared as EXTERNAL in, the (sub)program from which D02KEF is called. Arguments denoted as Input must not be changed by this procedure.
6:   K – INTEGERInput
On entry: k, the index of the required eigenvalue when the eigenvalues are ordered
λ 0 < λ 1 < λ 2 < ⋯ < λk < ⋯ .
Constraint: K≥0.
7:   TOL – REAL (KIND=nag_wp)Input
On entry: the tolerance argument which determines the accuracy of the computed eigenvalue. The error estimate held in DELAM on exit satisfies the mixed absolute/relative error test
DELAM≤TOL×max 1.0,ELAM, (1)
where ELAM is the final estimate of the eigenvalue. DELAM is usually somewhat smaller than the right-hand side of (1) but not several orders of magnitude smaller.
Constraint: TOL>0.0.
8:   ELAM – REAL (KIND=nag_wp)Input/Output
On entry: an initial estimate of the eigenvalue λ~.
On exit: the final computed estimate, whether or not an error occurred.
9:   DELAM – REAL (KIND=nag_wp)Input/Output
On entry: an indication of the scale of the problem in the λ-direction. DELAM holds the initial ‘search step’ (positive or negative). Its value is not critical, but the first two trial evaluations are made at ELAM and ELAM+DELAM, so the routine will work most efficiently if the eigenvalue lies between these values. A reasonable choice (if a closer bound is not known) is half the distance between adjacent eigenvalues in the neighbourhood of the one sought. In practice, there will often be a problem, similar to the one in hand but with known eigenvalues, which will help one to choose initial values for ELAM and DELAM.
If DELAM=0.0 on entry, it is given the default value of 0.25×max 1.0,ELAM.
On exit: if IFAIL=0, DELAM holds an estimate of the absolute error in the computed eigenvalue, that is λ~-ELAM≃DELAM. (In Section 9.2 we discuss the assumptions under which this is true.) The true error is rarely more than twice, or less than a tenth, of the estimated error.
If IFAIL≠0, DELAM may hold an estimate of the error, or its initial value, depending on the value of IFAIL. See Section 6 for further details.
10:   HMAX 2 M – REAL (KIND=nag_wp) arrayInput/Output
On entry: HMAX 1 j should contain a maximum step size to be used by the differential equation code in the jth sub-interval ij (as described in the specification of argument XPOINT), for j=1,2,…,m-3. If it is zero the routine generates a maximum step size internally.
It is recommended that HMAX 1 j be set to zero unless the coefficient functions p and q have features (such as a narrow peak) within the jth sub-interval that could be ‘missed’ if a long step were taken. In such a case HMAX 1 j should be set to about half the distance over which the feature should be observed. Too small a value will increase the computing time for the routine. See Section 9 for further suggestions.
The rest of the array is used as workspace.
On exit: HMAX 1 m-1 and HMAX 1 m contain the sensitivity coefficients σl,σr, described in Section 9.6. Other entries contain diagnostic output in the case of an error exit (see Section 6).
11:   MAXIT – INTEGERInput/Output
On entry: a bound on nr, the number of root-finding iterations allowed, that is the number of trial values of λ that are used. If MAXIT≤0, no such bound is assumed. (See also MAXFUN.)
Suggested value: MAXIT=0.
On exit: will have been decreased by the number of iterations actually performed, whether or not it was positive on entry.
12:   MAXFUN – INTEGERInput
On entry: a bound on nf, the number of calls to COEFFN made in any one root-finding iteration. If MAXFUN≤0, no such bound is assumed.
Suggested value: MAXFUN=0.
MAXFUN and MAXIT may be used to limit the computational cost of a call to D02KEF, which is roughly proportional to nr×nf.
13:   MONIT – SUBROUTINE, supplied by the NAG Library or the user.External Procedure
MONIT is called by D02KEF at the end of each root-finding iteration and allows you to monitor the course of the computation by printing out the arguments (see Section 10 for an example).
If no monitoring is required, the dummy (sub)program D02KAY may be used. (D02KAY is included in the NAG Library.)
The specification of MONIT is:
SUBROUTINE MONIT ( NIT, IFLAG, ELAM, FINFO)
INTEGER | NIT, IFLAG
REAL (KIND=nag_wp) | ELAM, FINFO(15)
1:   NIT – INTEGERInput
On entry: the current value of the argument MAXIT of D02KEF, this is decreased by one at each iteration.
2:   IFLAG – INTEGERInput
On entry: describes what phase the computation is in.
IFLAG<0
An error occurred in the computation at this iteration; an error exit from D02KEF with IFAIL=-IFLAG will follow.
IFLAG=1
The routine is trying to bracket the eigenvalue λ~.
IFLAG=2
The routine is converging to the eigenvalue λ~ (having already bracketed it).
3:   ELAM – REAL (KIND=nag_wp)Input
On entry: the current trial value of λ.
4:   FINFO 15 – REAL (KIND=nag_wp) arrayInput
On entry: information about the behaviour of the shooting method, and diagnostic information in the case of errors. It should not normally be printed in full if no error has occurred (that is, if IFLAG>0), though the first few components may be of interest to you. In case of an error (IFLAG<0) all the components of FINFO should be printed.
The contents of FINFO are as follows:
FINFO 1
The current value of the ‘miss-distance’ or ‘residual’ function f λ on which the shooting method is based. (See Section 9.2 for further information.) FINFO 1 is set to zero if IFLAG<0.
FINFO 2
An estimate of the quantity ∂λ defined as follows. Consider the perturbation in the miss-distance f λ that would result if the local error in the solution of the differential equation were always positive and equal to its maximum permitted value. Then ∂λ is the perturbation in λ that would have the same effect on f λ. Thus, at the zero of f λ,∂λ is an approximate bound on the perturbation of the zero (that is the eigenvalue) caused by errors in numerical solution. If ∂λ is very large then it is possible that there has been a programming error in COEFFN such that q is independent of λ. If this is the case, an error exit with IFAIL=5 should follow. FINFO 2 is set to zero if IFLAG<0.
FINFO 3
The number of internal iterations, using the same value of λ and tighter accuracy tolerances, needed to bring the accuracy (that is, the value of ∂λ) to an acceptable value. Its value should normally be 1.0, and should almost never exceed 2.0.
FINFO 4
The number of calls to COEFFN at this iteration.
FINFO 5
The number of successful steps taken by the internal differential equation solver at this iteration. A step is successful if it is used to advance the integration.
FINFO 6
The number of unsuccessful steps used by the internal integrator at this iteration.
FINFO 7
The number of successful steps at the maximum step size taken by the internal integrator at this iteration.
FINFO 8
Not used.
FINFO 9 to FINFO 15
Set to zero, unless IFLAG<0 in which case they hold the following values describing the point of failure:
FINFO 9
The index of the sub-interval where failure occurred, in the range 1 to m-3. In case of an error in BDYVAL, it is set to 0 or m-2 depending on whether the left or right boundary condition caused the error.
FINFO 10
The value of the independent variable, x, the point at which the error occurred. In case of an error in BDYVAL, it is set to the value of XL or XR as appropriate (see the specification of BDYVAL).
FINFO 11, FINFO 12, FINFO 13
The current values of the Pruefer dependent variables β, ϕ and ρ respectively. These are set to zero in case of an error in BDYVAL.
FINFO 14
The local-error tolerance being used by the internal integrator at the point of failure. This is set to zero in the case of an error in BDYVAL.
FINFO 15
The last integration mesh point. This is set to zero in the case of an error in BDYVAL.
MONIT must either be a module subprogram USEd by, or declared as EXTERNAL in, the (sub)program from which D02KEF is called. Arguments denoted as Input must not be changed by this procedure.
14:   REPORT – SUBROUTINE, supplied by the user.External Procedure
REPORT provides the means by which you may compute the eigenfunction y x and its derivative at each integration mesh point x. (See Section 9 for an example.)
The specification of REPORT is:
SUBROUTINE REPORT ( X, V, JINT)
INTEGER | JINT
REAL (KIND=nag_wp) | X, V(3)
1:   X – REAL (KIND=nag_wp)Input
On entry: the current value of the independent variable x. See Section 9.3 for the order in which values of x are supplied.
2:   V 3 – REAL (KIND=nag_wp) arrayInput
On entry: V 1, V 2, V 3 hold the current values of the Pruefer variables β, ϕ, ρ respectively.
3:   JINT – INTEGERInput
On entry: indicates the sub-interval between break-points in which X lies exactly as for COEFFN, except that at the extreme left-hand end point (when x=XPOINT 2) JINT is set to 0 and at the extreme right-hand end point (when x=xr=XPOINT m-1) JINT is set to m-2.
REPORT must either be a module subprogram USEd by, or declared as EXTERNAL in, the (sub)program from which D02KEF is called. Arguments denoted as Input must not be changed by this procedure.
15:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
A argument error. All arguments (except IFAIL) are left unchanged. The reason for the error is shown by the value of HMAX 21 as follows:
HMAX 21=1: M<4;
HMAX 21=2: K<0;
HMAX 21=3: TOL≤0.0;
HMAX 21=4: XPOINT 1 to XPOINT m are not in ascending order. HMAX 22 gives the position i in XPOINT where this was detected.
IFAIL=2
At some call to BDYVAL, invalid values were returned, that is, either YL 1=YL 2=0.0, or YR 1=YR 2=0.0 (a programming error in BDYVAL). See the last call of MONIT for details.
This error exit will also occur if p x is zero at the point where the boundary condition is imposed. Probably BDYVAL was called with XL equal to a singular end point a or with XR equal to a singular end point b.
IFAIL=3
At some point between XL and XR the value of p x computed by COEFFN became zero or changed sign. See the last call of MONIT for details.
IFAIL=4
MAXIT>0 on entry, and after MAXIT iterations the eigenvalue had not been found to the required accuracy.
IFAIL=5
The ‘bracketing’ phase (with argument IFLAG of the MONIT equal to 1) failed to bracket the eigenvalue within ten iterations. This is caused by an error in formulating the problem (for example, q is independent of λ), or by very poor initial estimates of ELAM and DELAM.
On exit, ELAM and ELAM+DELAM give the end points of the interval within which no eigenvalue was located by the routine.
IFAIL=6
MAXFUN>0 on entry, and the last iteration was terminated because more than MAXFUN calls to COEFFN were used. See the last call of MONIT for details.
IFAIL=7
To obtain the desired accuracy the local error tolerance was set so small at the start of some sub-interval that the differential equation solver could not choose an initial step size large enough to make significant progress. See the last call of MONIT for diagnostics.
IFAIL=8
At some point inside a sub-interval the step size in the differential equation solver was reduced to a value too small to make significant progress (for the same reasons as with IFAIL=7). This could be due to pathological behaviour of p x and q x;λ or to an unreasonable accuracy requirement or to the current value of λ making the equations ‘stiff’. See the last call of MONIT for details.
IFAIL=9
TOL is too small for the problem being solved and the machine precision is being used. The final value of ELAM should be a very good approximation to the eigenvalue.
IFAIL=10
C05AZF, called by D02KEF, has terminated with the error exit corresponding to a pole of the residual function f λ. This error exit should not occur, but if it does, try solving the problem again with a smaller value for TOL.
IFAIL=11
IFAIL=12
A serious error has occurred in an internal call. Check all (sub)program calls and array dimensions. Seek expert help.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.
Note: error exits with IFAIL=2, 3, 6, 7, 8 or 11 are caused by being unable to set up or solve the differential equation at some iteration and will be immediately preceded by a call of MONIT giving diagnostic information. For other errors, diagnostic information is contained in HMAX 2 j, for j=1,2,…,m, where appropriate.

7 Accuracy

See the discussion in Section 9.2.

8 Parallelism and Performance

D02KEF is not threaded in any implementation.

9 Further Comments

9.1 Timing

The time taken by D02KEF depends on the complexity of the coefficient functions, whether they or their derivatives are rapidly changing, the tolerance demanded, and how many iterations are needed to obtain convergence. The amount of work per iteration is roughly doubled when TOL is divided by 16. To make the most economical use of the routine, one should try to obtain good initial values for ELAM and DELAM, and, where appropriate, good asymptotic formulae. Also the boundary matching points should not be set unnecessarily close to singular points. The extra time needed to compute the eigenfunction is principally the cost of one additional integration once the eigenvalue has been found.

9.2 General Description of the Algorithm

A shooting method, for differential equation problems containing unknown parameters, relies on the construction of a ‘miss-distance function’, which for given trial values of the parameters measures how far the conditions of the problem are from being met. The problem is then reduced to one of finding the values of the parameters for which the miss-distance function is zero, that is to a root-finding process. Shooting methods differ mainly in how the miss-distance is defined.
D02KEF defines a miss-distance f λ based on the rotation about the origin of the point P x=p x y′x,y x in the Phase Plane as the solution proceeds from a to b. The boundary conditions define the ray (i.e., two-sided line through the origin) on which p x should start, and the ray on which it should finish. The eigenvalue k defines the total number of half-turns it should make. Numerical solution is actually done by ‘shooting forward’ from x=a and ‘shooting backward’ from x=b to a matching point x=c. Then f λ is taken as the angle between the rays to the two resulting points Pa c and Pb c. A relative scaling of the p y′ and y axes, based on the behaviour of the coefficient functions p and q, is used to improve the numerical behaviour.
Figure 1
The resulting function f λ is monotonic over -∞<λ<∞, increasing if ∂q ∂λ >0 and decreasing if ∂q ∂λ <0, with a unique zero at the desired eigenvalue λ~. The routine measures f λ in units of a half-turn. This means that as λ increases, f λ varies by about 1 as each eigenvalue is passed. (This feature implies that the values of f λ at successive iterations – especially in the early stages of the iterative process – can be used with suitable extrapolation or interpolation to help the choice of initial estimates for eigenvalues near to the one currently being found.)
The routine actually computes a value for f λ with errors, arising from the local errors of the differential equation code and from the asymptotic formulae provided by you if singular points are involved. However, the error estimate output in DELAM is usually fairly realistic, in that the actual error λ~-ELAM is within an order of magnitude of DELAM.
We pass the values of β, ϕ, ρ across through REPORT rather than converting them to values of y, y′ inside D02KEF, for the following reasons. First, there may be cases where auxiliary quantities can be more accurately computed from the Pruefer variables than from y and y′. Second, in singular problems on an infinite interval y and y′ may underflow towards the end of the range, whereas the Pruefer variables remain well-behaved. Third, with high-order eigenvalues (and therefore highly oscillatory eigenfunctions) the eigenfunction may have a complete oscillation (or more than one oscillation) between two mesh points, so that values of y and y′ at mesh points give a very poor representation of the curve. The probable behaviour of the Pruefer variables in this case is that β and ρ vary slowly whilst ϕ increases quickly: for all three Pruefer variables linear interpolation between the values at adjacent mesh points is probably sufficiently accurate to yield acceptable intermediate values of β, ϕ, ρ (and hence of y,y′) for graphical purposes.
Similar considerations apply to the exponentially decaying ‘tails’ of the eigenfunctions that often occur in singular problems. Here ϕ has approximately constant value whilst ρ increases rapidly in the direction of integration, though the step length is generally fairly small over such a range.
If the solution is output through REPORT at x values which are too widely spaced, the step length can be controlled by choosing HMAX suitably, or, preferably, by reducing TOL. Both these choices will lead to more accurate eigenvalues and eigenfunctions but at some computational cost.

9.3 The Position of the Shooting Matching Point c

This point is always one of the values xi in array XPOINT. It may be specified using the argument MATCH. The default value is chosen to be the value of that xi, 2≤i≤m-1, that lies closest to the middle of the interval x 2,x m-1. If there is a tie, the rightmost candidate is chosen. In particular if there are no break-points, then c=x m-1 (=x 3); that is, the shooting is from left to right in this case. A break-point may be inserted purely to move c to an interior point of the interval, even though the form of the equations does not require it. This often speeds up convergence especially with singular problems.
Note that the shooting method used by the code integrates first from the left-hand end xl, then from the right-hand end xr, to meet at the matching point c in the middle. This will of course be reflected in printed or graphical output. The diagram shows a possible sequence of nine mesh points τ 1 through τ 9 in the order in which they appear, assuming there are just two sub-intervals (so m=5).
Figure 2
Since the shooting method usually fails to match up the two ‘legs’ of the curve exactly, there is bound to be a jump in y, or in p x y′ or both, at the matching point c. The code in fact ‘shares’ the discrepancy out so that both y and p x y′ have a jump. A large jump does not imply an inaccurate eigenvalue, but implies either
(a) | a badly chosen matching point: if q x;λ has a ‘humped’ shape, c should be chosen near the maximum value of q, especially if q is negative at the ends of the interval;
(b) | an inherently ill-conditioned problem, typically one where another eigenvalue is pathologically close to the one being sought. In this case it is extremely difficult to obtain an accurate eigenfunction.
In Section 10, we find the 11th eigenvalue and corresponding eigenfunction of the equation
y′′+λ-x-2/x 2 y=0  on  0<x<∞,
the boundary conditions being that y should remain bounded as x tends to 0 and x tends to ∞. The coding of this problem is discussed in detail in Section 9.5.
The choice of matching point c is open. If we choose c=30.0 as in D02KDF example program we find that the exponentially increasing component of the solution dominates and we get extremely inaccurate values for the eigenfunction (though the eigenvalue is determined accurately). The values of the eigenfunction calculated with c=30.0 are given schematically in Figure 3.
Figure 3
If we choose c as the maximum of the hump in q x;λ (see item (a) above) we instead obtain the accurate results given in Figure 4
Figure 4

9.4 Examples of Coding the COEFFN

Coding COEFFN is straightforward except when break-points are needed. The examples below show:
(a) | a simple case,
(b) | a case in which discontinuities in the coefficient functions or their derivatives necessitate break-points, and
(c) | a case where break-points together with the HMAX argument are an efficient way to deal with a coefficient function that is well-behaved except over one short interval.
(Some of these cases are among the examples in Section 10.)
Example A
The modified Bessel equation
x x y′ ′ + λ x 2-ν 2 y=0 .
Assuming the interval of solution does not contain the origin and dividing through by x, we have p x=x and q x;λ=λx-ν 2/x. The code could be
SUBROUTINE COEFFN (P,Q,DQDL,X,ELAM,JINT)
...
P = X
Q = ELAM*X - NU*NU/X
DQDL = X
RETURN
END
where NU (standing for ν) is a real variable that might be defined in a DATA statement, or might be in user-declared COMMON so that its value could be set in the main program.
Example B
The Schroedinger equation
y′′+λ+q x y=0,
where
q x = x 2- 10 x≤ 4, 6 x x> 4,
over some interval ‘approximating to -∞,∞’, say -20,20. Here we need break-points at ±4, forming three sub-intervals i 1=-20,-4, i 2=-4,4, i 3=4,20. The code could be
SUBROUTINE COEFFN(P,Q,DQDL,X,ELAM,JINT)
...
IF (JINT.EQ.2) THEN
  Q = ELAM + X*X - 10.0E0
ELSE
  Q = ELAM + 6.0E0/ABS(X)
ENDIF
P = 1.0E0
DQDL = 1.0E0
RETURN
END
The array XPOINT would contain the values x 1, -20.0, -4.0, +4.0, +20.0, x 6 and m would be 6. The choice of appropriate values for x 1 and x 6 depends on the form of the asymptotic formula computed by BDYVAL and the technique is discussed in Section 9.5.
Example C
y′′+λ 1-2⁢e-100⁢x 2 y=0,  -10≤x≤10.
Here q x;λ is nearly constant over the range except for a sharp inverted spike over approximately -0.1≤x≤0.1. There is a danger that the routine will build up to a large step size and ‘step over’ the spike without noticing it. By using break-points – say at ±0.5 – one can restrict the step size near the spike without impairing the efficiency elsewhere.
The code for COEFFN could be
SUBROUTINE COEFFN(P,Q,DQDL,X,ELAM,JINT)
...
P = 1.0E0
DQDL = 1.0E0 - 2.0E0*EXP(-100.0E0*X*X)
Q = ELAM*DQDL
RETURN
END
XPOINT might contain -10.0, -10.0, -0.5, 0.5, 10.0, 10.0 (assuming ±10 are regular points) and m would be 6. HMAX 1 j, for j=1,2,3, might contain 0.0, 0.1 and 0.0.

9.5 Examples of Boundary Conditions at Singular Points

Quoting from page 243 of Bailey (1966): ‘Usually ... the differential equation has two essentially different types of solution near a singular point, and the boundary condition there merely serves to distinguish one kind from the other. This is the case in all the standard examples of mathematical physics.’
In most cases the behaviour of the ratio p x y′/y near the point is quite different for the two types of solution. Essentially what you provide through the BDYVAL is an approximation to this ratio, valid as x tends to the singular point (SP).
You must decide (a) how accurate to make this approximation or asymptotic formula, for example how many terms of a series to use, and (b) where to place the boundary matching point (BMP) at which the numerical solution of the differential equation takes over from the asymptotic formula. Taking the BMP closer to the SP will generally improve the accuracy of the asymptotic formula, but will make the computation more expensive as the Pruefer differential equations generally become progressively more ill-behaved as the SP is approached. You are strongly recommended to experiment with placing the BMPs. In many singular problems quite crude asymptotic formulae will do. To help you avoid needlessly accurate formulae, D02KEF outputs two ‘sensitivity coefficients’ σl,σr which estimate how much the errors at the BMPs affect the computed eigenvalue. They are described in detail in Section 9.6.
Example of coding BDYVAL:
The example below illustrates typical situations:
y′′+λ-x-2 x 2 y=0,  0<x<∞
the boundary conditions being that y should remain bounded as x tends to 0 and x tends to ∞.
At the end x=0 there is one solution that behaves like x 2 and another that behaves like x-1. For the first of these solutions p x y′/y is asymptotically 2/x while for the second it is asymptotically -1/x. Thus the desired ratio is specified by setting
YL 1=x  and  YL 2=2.0.
At the end x=∞ the equation behaves like Airy's equation shifted through λ, i.e., like y′′-ty=0 where t=x-λ, so again there are two types of solution. The solution we require behaves as
exp-23 t 32/t 4
and the other as
exp+23 t 32/t 4.
Hence, the desired solution has p x y′/y∼-t so that we could set YR 1=1.0 and YR 2=-x-λ. The complete subroutine might thus be
SUBROUTINE BDYVAL (XL,XR,ELAM,YL,YR)
real XL, XR, ELAM, YL(3), YR(3)
YL(1) = XL
YL(2) = 2.0E0
YR(1) = 1.0E0
YR(2) = -SQRT(XR-ELAM)
RETURN
END
Clearly for this problem it is essential that any value given by D02KEF to XR is well to the right of the value of ELAM, so that you must vary the right-hand BMP with the eigenvalue index k. One would expect λk to be near the kth zero of the Airy function Ai x, so there is no problem estimating ELAM.
More accurate asymptotic formulae are easily found: near x=0 by the standard Frobenius method, and near x=∞ by using standard asymptotics for Ai x, Ai′x, (see page 448 of Abramowitz and Stegun (1972)).
For example, by the Frobenius method the solution near x=0 has the expansion
y=x 2 c 0+c 1 x+c 2 x 2+⋯
with
c 0= 1,c 1= 0, c 2=-λ 10, c 3=118,⋯, cn=c n- 3-λ c n- 2 n n+ 3 .
This yields
p x y′y=2-25 λ x 2+⋯ x 1-λ 10 x 2+⋯ .

9.6 The Sensitivity Parameters σl and σr

The sensitivity parameters σl, σr (held in HMAX 1 m-1 and HMAX 1 m on output) estimate the effect of errors in the boundary conditions. For sufficiently small errors Δy, Δp y′ in y and p y′ respectively, the relations
Δλ≃y.Δp y′-p y′.Δy lσl Δλ≃y.Δp y′-p y′.Δy rσr
are satisfied, where the subscripts l, r denote errors committed at the left- and right-hand BMPs respectively, and Δλ denotes the consequent error in the computed eigenvalue.

9.7 ‘Missed Zeros’

This is a pitfall to beware of at a singular point. If the BMP is chosen so far from the SP that a zero of the desired eigenfunction lies in between them, then the routine will fail to ‘notice’ this zero. Since the index of k of an eigenvalue is the number of zeros of its eigenfunction, the result will be that
(a) | the wrong eigenvalue will be computed for the given index k – in fact some λ k+k′ will be found where k′≥1;
(b) | the same index k can cause convergence to any of several eigenvalues depending on the initial values of ELAM and DELAM.
It is up to you to take suitable precautions – for instance by varying the position of the BMPs in the light of knowledge of the asymptotic behaviour of the eigenfunction at different eigenvalues.

10 Example

This example finds the 11th eigenvalue and eigenfunction of the example of Section 9.5, using the simple asymptotic formulae for the boundary conditions.
Comparison of the results from this example program with the corresponding results from D02KDF example program shows that similar output is produced from MONIT, followed by the eigenfunction values from REPORT, and then a further line of information from MONIT (corresponding to the integration to find the eigenfunction). Final information is printed within the example program exactly as with D02KDF.
Note the discrepancy at the matching point c (=43, the maximum of q x;λ, in this case) between the solutions obtained by integrations from left- and right-hand end points.

10.1 Program Text

Program Text (d02kefe.f90)

10.2 Program Data

Program Data (d02kefe.d)

10.3 Program Results

Program Results (d02kefe.r)

GnuplotProduced by GNUPLOT 4.6 patchlevel 3 −10 −8 −6 −4 −2 0 2 4 6 8 10 0 5 10 15 20 25 30 Eigenfunction and Derivative x Example Program Regular Singular Second-order Sturm-Liouville System 11th Eigenfunction and Derivative p(x)y' y gnuplot_plot_1 gnuplot_plot_2
D02 Chapter Contents
D02 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


D02LAF : NAG Library, Mark 26

D02 Chapter Contents
D02 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

D02LAF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

D02LAF is a routine for integrating a non-stiff system of second-order ordinary differential equations using Runge–Kutta–Nystrom techniques.

2 Specification

SUBROUTINE D02LAF ( FCN, NEQ, T, TEND, Y, YP, YDP, RWORK, LRWORK, IFAIL)
INTEGER | NEQ, LRWORK, IFAIL
REAL (KIND=nag_wp) | T, TEND, Y(NEQ), YP(NEQ), YDP(NEQ), RWORK(LRWORK)
EXTERNAL | FCN

3 Description

Given the initial values x,y 1,y 2,…,yNEQ,y 1′,y 2′,…,yNEQ′ D02LAF integrates a non-stiff system of second-order differential equations of the type
yi′′=fi x,y 1,y 2,…,yNEQ,  i=1,2,…,NEQ,
from x=T to x=TEND using a Runge–Kutta–Nystrom formula pair. The system is defined by FCN, which evaluates fi in terms of x and y 1,y 2,…,yNEQ, where y 1,y 2,…,yNEQ are supplied at x.
There are two Runge–Kutta–Nystrom formula pairs implemented in this routine. The lower order method is intended if you have moderate accuracy requirements and may be used in conjunction with the interpolation routine D02LZF to produce solutions and derivatives at user-specified points. The higher order method is intended if you have high accuracy requirements.
In one-step mode the routine returns approximations to the solution, derivative and fi at each integration point. In interval mode these values are returned at the end of the integration range. You select the order of the method, the mode of operation, the error control and various optional inputs by a prior call to D02LXF.
For a description of the Runge–Kutta–Nystrom formula pairs see Dormand et al. (1986a) and Dormand et al. (1986b) and for a description of their practical implementation see Brankin et al. (1989).

4 References

Brankin R W, Dormand J R, Gladwell I, Prince P J and Seward W L (1989) Algorithm 670: A Runge–Kutta–Nystrom Code ACM Trans. Math. Software 15 31–40
Dormand J R, El–Mikkawy M E A and Prince P J (1986a) Families of Runge–Kutta–Nystrom formulae Mathematical Report TPMR 86-1 Teesside Polytechnic
Dormand J R, El–Mikkawy M E A and Prince P J (1986b) High order embedded Runge–Kutta–Nystrom formulae Mathematical Report TPMR 86-2 Teesside Polytechnic

5 Arguments

1:   FCN – SUBROUTINE, supplied by the user.External Procedure
FCN must evaluate the functions fi (that is the second derivatives yi′′) for given values of its arguments x, y 1,y 2,…,yNEQ.
The specification of FCN is:
SUBROUTINE FCN ( NEQ, T, Y, F)
INTEGER | NEQ
REAL (KIND=nag_wp) | T, Y(NEQ), F(NEQ)
1:   NEQ – INTEGERInput
On entry: the number of differential equations.
2:   T – REAL (KIND=nag_wp)Input
On entry: x, the value of the argument.
3:   Y NEQ – REAL (KIND=nag_wp) arrayInput
On entry: yi, for i=1,2,…,NEQ, the value of the argument.
4:   F NEQ – REAL (KIND=nag_wp) arrayOutput
On exit: the value of fi, for i=1,2,…,NEQ.
FCN must either be a module subprogram USEd by, or declared as EXTERNAL in, the (sub)program from which D02LAF is called. Arguments denoted as Input must not be changed by this procedure.
2:   NEQ – INTEGERInput
On entry: the number of second-order ordinary differential equations to be solved by D02LAF. It must contain the same value as the argument NEQ used in a prior call to D02LXF.
Constraint: NEQ≥1.
3:   T – REAL (KIND=nag_wp)Input/Output
On entry: the initial value of the independent variable x.
Constraint: T≠TEND.
On exit: the value of the independent variable, which is usually TEND, unless an error has occurred or the code is operating in one-step mode. If the integration is to be continued, possibly with a new value for TEND, T must not be changed.
4:   TEND – REAL (KIND=nag_wp)Input
On entry: the end point of the range of integration. If TEND<T on initial entry, integration will proceed in the negative direction. TEND may be reset, in the direction of integration, before any continuation call.
5:   Y NEQ – REAL (KIND=nag_wp) arrayInput/Output
On entry: the initial values of the solution y 1,y 2,…,yNEQ.
On exit: the computed values of the solution at the exit value of T. If the integration is to be continued, possibly with a new value for TEND, these values must not be changed.
6:   YP NEQ – REAL (KIND=nag_wp) arrayInput/Output
On entry: the initial values of the derivatives y 1′,y 2′,…,yNEQ′.
On exit: the computed values of the derivatives at the exit value of T. If the integration is to be continued, possibly with a new value for TEND, these values must not be changed.
7:   YDP NEQ – REAL (KIND=nag_wp) arrayInput/Output
On entry: must be unchanged from a previous call to D02LAF.
On exit: the computed values of the second derivative at the exit value of T, unless illegal input is detected, in which case the elements of YDP may not have been initialized. If the integration is to be continued, possibly with a new value for TEND, these values must not be changed.
8:   RWORK LRWORK – REAL (KIND=nag_wp) arrayCommunication Array
This must be the same argument RWORK as supplied to D02LXF. It is used to pass information from D02LXF to D02LAF, and from D02LAF to both D02LYF and D02LZF. Therefore the contents of this array must not be changed before the call to D02LAF or calling either of the routines D02LYF and D02LZF.
9:   LRWORK – INTEGERInput
On entry: the dimension of the array RWORK as declared in the (sub)program from which D02LAF is called.
This must be the same argument LRWORK as supplied to D02LXF.
10:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, because for this routine the values of the output arguments may be useful even if IFAIL≠0 on exit, the recommended value is -1. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
Illegal input detected, i.e., one of the following conditions:
  • on any call, T=TEND, or the value of NEQ or LRWORK has been altered;
  • on a continuation call, the direction of integration has been changed;
  • D02LXF had not been called previously, or the previous call to D02LXF resulted in an error exit.
This error exit can be caused if elements of RWORK have been overwritten.
IFAIL=2
The maximum number of steps has been attempted. (See argument MAXSTP in D02LXF.) If integration is to be continued then you need only reset IFAIL and call the routine again and a further MAXSTP steps will be attempted.
IFAIL=3
In order to satisfy the error requirements, the step size needed is too small for the machine precision being used.
IFAIL=4
The code has detected two successive error exits at the current value of x and cannot proceed. Check all input variables.
IFAIL=5
The code has detected inefficient use of the integration method. The step size has been reduced by a significant amount too often in order to hit the output points specified by TEND. (Of the last 100 or more successful steps more than 10% are steps with sizes that have had to be reduced by a factor of greater than a half.)
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

The accuracy of integration is determined by the arguments TOL, THRES and THRESP in a prior call to D02LXF. Note that only the local error at each step is controlled by these arguments. The error estimates obtained are not strict bounds but are usually reliable over one step. Over a number of steps the overall error may accumulate in various ways, depending on the system. The code is designed so that a reduction in TOL should lead to an approximately proportional reduction in the error. You are strongly recommended to call D02LAF with more than one value for TOL and to compare the results obtained to estimate their accuracy.
The accuracy obtained depends on the type of error test used. If the solution oscillates around zero a relative error test should be avoided, whereas if the solution is exponentially increasing an absolute error test should not be used. For a description of the error test see the specifications of the arguments TOL, THRES and THRESP in routine document D02LXF.

8 Parallelism and Performance

D02LAF is not thread safe and should not be called from a multithreaded user program. Please see Section 3.12.1 in How to Use the NAG Library and its Documentation for more information on thread safety.
D02LAF is not threaded in any implementation.

9 Further Comments

If D02LAF fails with IFAIL=3 then the value of TOL may be so small that a solution cannot be obtained, in which case the routine should be called again with a larger value for TOL. If the accuracy requested is really needed then you should consider whether there is a more fundamental difficulty. For example:
(a) | in the region of a singularity the solution components will usually be of a large magnitude. D02LAF could be used in one-step mode to monitor the size of the solution with the aim of trapping the solution before the singularity. In any case numerical integration cannot be continued through a singularity, and analytical treatment may be necessary;
(b) | if the solution contains fast oscillatory components, the routine will require a very small step size to preserve stability. This will usually be exhibited by excessive computing time and sometimes an error exit with IFAIL=3. The Runge–Kutta–Nystrom methods are not efficient in such cases and you should consider reposing your problem as a system of first-order ordinary differential equations and then using a routine from Sub-chapter D02M–N with the Blend formulae (see D02MVF).
D02LAF can be used for producing results at short intervals (for example, for tabulation), in two ways. By far the less efficient is to call D02LAF successively over short intervals, t+i-1×h to t+i×h, although this is the only way if the higher order method has been selected and precisely not what it is intended for. A more efficient way, only for use when the lower order method has been selected, is to use D02LAF in one-step mode. The output values of arguments Y, YP, YDP, T and RWORK are set correctly for a call to D02LZF to compute the solution and derivative at the required points.

10 Example

This example solves the following system (the two body problem)
y 1′′ = -y 1/y 12+y 22 3/2 y 2′′ = -y 2/y 12+y 22 3/2
over the range 0,20 with initial conditions y 1=1.0-ε, y 2=0.0, y 1′=0.0 and y 2′= 1+ε 1-ε where ε, the eccentricity, is 0.5. The system is solved using the lower order method with relative local error tolerances 1.0E−4 and 1.0E−5 and default threshold tolerances. D02LAF is used in one-step mode (ONESTP=.TRUE.) and D02LZF provides solution values at intervals of 2.0.

10.1 Program Text

Program Text (d02lafe.f90)

10.2 Program Data

Program Data (d02lafe.d)

10.3 Program Results

Program Results (d02lafe.r)

GnuplotProduced by GNUPLOT 4.6 patchlevel 3 −1 −0.8 −0.6 −0.4 −0.2 0 0.2 0.4 0.6 0.8 1 1.2 −1.6 −1.4 −1.2 −1 −0.8 −0.6 −0.4 −0.2 0 0.2 0.4 0.6 y x Example Program Second-order ODE Solution using Runge-Kutta-Nystrom The Two-body Problem (using shifts to distinguish orbits) o 1st orbit o 2nd orbit+(0,0.1) o 3rd orbit+(0,0.2) 1 2 3 gnuplot_plot_1 gnuplot_plot_2 gnuplot_plot_3
D02 Chapter Contents
D02 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


D02LXF : NAG Library, Mark 26

D02 Chapter Contents
D02 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

D02LXF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
10 Example

1 Purpose

D02LXF is a setup routine which must be called prior to the first call of the integrator D02LAF and may be called prior to any continuation call to D02LAF.

2 Specification

SUBROUTINE D02LXF ( NEQ, H, TOL, THRES, THRESP, MAXSTP, START, ONESTP, HIGH, RWORK, LRWORK, IFAIL)
INTEGER | NEQ, MAXSTP, LRWORK, IFAIL
REAL (KIND=nag_wp) | H, TOL, THRES(NEQ), THRESP(NEQ), RWORK(LRWORK)
LOGICAL | START, ONESTP, HIGH

3 Description

D02LXF permits you to set optional inputs prior to any call of D02LAF. It must be called before the first call of routine D02LAF and it may be called before any continuation call of routine D02LAF.

4 References

None.

5 Arguments

1:   NEQ – INTEGERInput
On entry: the number of second-order ordinary differential equations to be solved by D02LAF.
Constraint: NEQ≥1.
2:   H – REAL (KIND=nag_wp)Input
On entry: if START=.TRUE., H may specify an initial step size to be attempted in D02LAF.
If START=.FALSE., H may specify a step size to override the choice of next step attempted made internally to D02LAF.
The sign of H is not important, as the absolute value of H is chosen and the appropriate sign is selected by D02LAF.
If this option is not required then you must set H=0.0.
3:   TOL – REAL (KIND=nag_wp)Input
On entry: must be set to a relative tolerance for controlling the error in the integration by D02LAF. D02LAF has been designed so that, for most problems, a reduction in TOL leads to an approximately proportional reduction in the error in the solution. However the actual relation between TOL and the accuracy of the solution cannot be guaranteed. You are strongly recommended to repeat the integration with a smaller value of TOL and compare the results. See the description of THRES and THRESP for further details of how TOL is used.
Constraint: 10×ε≤TOL≤1.0 (ε is the machine precision, see X02AJF).
4:   THRES NEQ – REAL (KIND=nag_wp) arrayInput
5:   THRESP NEQ – REAL (KIND=nag_wp) arrayInput
On entry: THRES and THRESP may be set to thresholds for use in the error control of D02LAF. At each step in the numerical integration estimates of the local errors E1 i and E2 i in the solution, yi, and its derivative, yi′, respectively are computed, for i=1,2,…,NEQ. For the step to be accepted conditions of the following type must be satisfied:
max 1≤i≤NEQ E1 i max THRES i,yi ≤ TOL, max 1≤i≤NEQ E2 i max THRESP i,yi′ ≤TOL.
If one or both of these is not satisfied then the step size is reduced and the solution is recomputed.
If THRES 1≤0.0 on entry, then a value of 50.0×ε is used for THRES i, for i=1,2,…,NEQ, where ε is machine precision. Similarly for THRESP.
Constraints:
  • THRES 1≤0.0 or THRES i>0.0, for i=1,2,…,NEQ;
  • THRESP 1≤0.0 or THRESP i>0.0, for i=1,2,…,NEQ.
6:   MAXSTP – INTEGERInput
On entry: a bound on the number of steps attempted in any one call of D02LAF.
If MAXSTP≤0 on entry, a value of 1000 is used.
7:   START – LOGICALInput/Output
On entry: specifies whether or not the call of D02LAF is for a new problem. START=.TRUE. indicates that a new problem is to be solved. START=.FALSE. indicates the call of D02LXF is prior to a continuation call of D02LAF.
On exit: START=.FALSE..
8:   ONESTP – LOGICALInput
On entry: the mode of operation for D02LAF.
ONESTP=.TRUE.
D02LAF will operate in one-step mode, that is it will return after each successful step.
ONESTP=.FALSE.
D02LAF will operate in interval mode, that is it will return at the end of the integration interval.
9:   HIGH – LOGICALInput
On entry: if HIGH=.TRUE., a high-order method will be used, whereas if HIGH=.FALSE., a low-order method will be used. (See the specification of D02LAF for further details.)
10:   RWORK LRWORK – REAL (KIND=nag_wp) arrayCommunication Array
This must be the same argument RWORK supplied to D02LAF. It is used to pass information to D02LAF and therefore the contents of this array must not be changed before calling D02LAF.
11:   LRWORK – INTEGERInput
On entry: the dimension of the array RWORK as declared in the (sub)program from which D02LXF is called.
Constraints:
  • if HIGH=.TRUE., LRWORK≥16+20×NEQ;
  • if HIGH=.FALSE., LRWORK≥16+11×NEQ.
12:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
THRES 1>0.0 and for some i THRES i≤0.0, 1≤i≤NEQ, and/or, THRESP 1>0.0 and for some i THRESP i≤0.0, 1≤i≤NEQ.
IFAIL=2
LRWORK is too small.
IFAIL=3
TOL does not satisfy 10×ε≤TOL≤1.0 (ε is the machine precision, see X02AJF)
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

Not applicable.

8 Parallelism and Performance

D02LXF is not thread safe and should not be called from a multithreaded user program. Please see Section 3.12.1 in How to Use the NAG Library and its Documentation for more information on thread safety.
D02LXF is not threaded in any implementation.

9 Further Comments

Prior to a continuation call of D02LAF, you may reset any of the optional parameters by calling D02LXF with START=.FALSE.. You may reset:
H | to override the internal step size selection;
TOL, THRES, THRESP | to change the error requirements;
MAXSTP | to increase or decrease the number of steps attempted before an error exit is returned;
ONESTP | to change the mode of operation of D02LAF;
HIGH | to change the order of the method being used.

10 Example

See Section 10 in D02LAF.
D02 Chapter Contents
D02 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


D02LYF : NAG Library, Mark 26

D02 Chapter Contents
D02 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

D02LYF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
10 Example

1 Purpose

D02LYF is a diagnostic routine which may be called after a call of the integrator D02LAF.

2 Specification

SUBROUTINE D02LYF ( NEQ, HNEXT, HUSED, HSTART, NSUCC, NFAIL, NATT, THRES, THRESP, RWORK, LRWORK, IFAIL)
INTEGER | NEQ, NSUCC, NFAIL, NATT, LRWORK, IFAIL
REAL (KIND=nag_wp) | HNEXT, HUSED, HSTART, THRES(NEQ), THRESP(NEQ), RWORK(LRWORK)

3 Description

D02LYF permits you to extract information about the performance of D02LAF and the setting of some optional parameters. It may be called only after a call of D02LAF.

4 References

None.

5 Arguments

1:   NEQ – INTEGERInput
On entry: the number of second-order ordinary differential equations solved by D02LAF. It must be the same as the argument NEQ supplied to D02LAF and D02LXF.
2:   HNEXT – REAL (KIND=nag_wp)Output
On exit: the next step size which D02LAF, if called, would attempt.
3:   HUSED – REAL (KIND=nag_wp)Output
On exit: the last successful step size used by D02LAF.
4:   HSTART – REAL (KIND=nag_wp)Output
On exit: the initial step size used on the current integration problem by D02LAF.
5:   NSUCC – INTEGEROutput
On exit: the number of steps attempted by D02LAF that have been successful since the start of the current problem.
6:   NFAIL – INTEGEROutput
On exit: the number of steps attempted by D02LAF that have failed since the start of the current problem.
7:   NATT – INTEGEROutput
On exit: the number of steps attempted before the initial step was successful. Over a large number of problems the cost of an attempted step of this type is approximately half that of a normal attempted step.
8:   THRES NEQ – REAL (KIND=nag_wp) arrayOutput
On exit: the ith solution threshold value used in the error control strategy. (See D02LXF.)
9:   THRESP NEQ – REAL (KIND=nag_wp) arrayOutput
On exit: the ith derivative threshold value used in the error control strategy. (See D02LXF.)
10:   RWORK LRWORK – REAL (KIND=nag_wp) arrayCommunication Array
On entry: this must be the same argument RWORK as supplied to D02LAF. It is used to pass information from D02LAF to D02LYF and therefore the contents of this array must not be changed before calling D02LYF.
11:   LRWORK – INTEGERInput
On entry: the dimension of the array RWORK as declared in the (sub)program from which D02LYF is called.
This must be the same argument LRWORK as supplied to D02LXF.
12:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
D02LAF has not been called, or one or both of the arguments NEQ and LRWORK does not match the corresponding argument supplied to D02LXF.
This error exit can be caused if elements of RWORK have been overwritten.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

Not applicable.

8 Parallelism and Performance

D02LYF is not thread safe and should not be called from a multithreaded user program. Please see Section 3.12.1 in How to Use the NAG Library and its Documentation for more information on thread safety.
D02LYF is not threaded in any implementation.

9 Further Comments

None.

10 Example

See Section 10 in D02LAF.
D02 Chapter Contents
D02 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


D02LZF : NAG Library, Mark 26

D02 Chapter Contents
D02 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

D02LZF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
10 Example

1 Purpose

D02LZF interpolates components of the solution of a non-stiff system of second-order differential equations from information provided by the integrator D02LAF, when the low-order method has been used.

2 Specification

SUBROUTINE D02LZF ( NEQ, T, Y, YP, NWANT, TWANT, YWANT, YPWANT, RWORK, LRWORK, IFAIL)
INTEGER | NEQ, NWANT, LRWORK, IFAIL
REAL (KIND=nag_wp) | T, Y(NEQ), YP(NEQ), TWANT, YWANT(NWANT), YPWANT(NWANT), RWORK(LRWORK)

3 Description

D02LZF evaluates the first NWANT (≤NEQ) components of the solution of a non-stiff system of second-order ordinary differential equations at any point using a special Runge–Kutta–Nystrom formula (see Dormand and Prince (1986)) and information generated by D02LAF when the low-order method has been used. This information must be presented unchanged to D02LZF. D02LZF should not normally be used to extrapolate outside the range of the values from D02LAF.

4 References

Dormand J R and Prince P J (1986) Runge–Kutta–Nystrom triples Mathematical Report TP-CS-86-05 Teesside Polytechnic

5 Arguments

1:   NEQ – INTEGERInput
On entry: the number of second-order ordinary differential equations being solved by D02LAF. It must contain the same value as the argument NEQ in a prior call to D02LAF.
2:   T – REAL (KIND=nag_wp)Input
On entry: t, the current value at which the solution and its derivative have been computed (as returned in argument T on output from D02LAF).
3:   Y NEQ – REAL (KIND=nag_wp) arrayInput
On entry: the ith component of the solution at t, for i=1,2,…,NEQ, as returned from D02LAF.
4:   YP NEQ – REAL (KIND=nag_wp) arrayInput
On entry: the ith component of the derivative at t, for i=1,2,…,NEQ, as returned from D02LAF.
5:   NWANT – INTEGERInput
On entry: the number of components of the solution and derivative whose values at TWANT are required. The first NWANT components are evaluated.
Constraint: 1≤NWANT≤NEQ.
6:   TWANT – REAL (KIND=nag_wp)Input
On entry: the point at which components of the solution and derivative are to be evaluated. TWANT should not normally be an extrapolation point, that is TWANT should satisfy
told≤TWANT≤T,
or if integration is proceeding in the negative direction
told≥TWANT≥T,
where told is the previous integration point which is held in an element of the array RWORK and is, to within rounding, T-HUSED. (HUSED is given by D02LYF.) Extrapolation is permitted but not recommended, and IFAIL=2 is returned whenever extrapolation is attempted.
7:   YWANT NWANT – REAL (KIND=nag_wp) arrayOutput
On exit: the calculated value of the ith component of the solution at t=TWANT, for i=1,2,…,NWANT.
8:   YPWANT NWANT – REAL (KIND=nag_wp) arrayOutput
On exit: the calculated value of the ith component of the derivative at t=TWANT, for i=1,2,…,NWANT.
9:   RWORK LRWORK – REAL (KIND=nag_wp) arrayCommunication Array
On entry: this must be the same argument RWORK as supplied to D02LAF. It is used to pass information from D02LAF to D02LZF and therefore the contents of this array must not be changed before calling D02LZF.
10:   LRWORK – INTEGERInput
On entry: the dimension of the array RWORK as declared in the (sub)program from which D02LZF is called.
This must be the same argument LRWORK as supplied to the setup routine D02LXF.
11:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).
If D02LZF is to be used for extrapolation at TWANT, IFAIL should be set to 1 before entry. It is then essential to test the value of IFAIL on exit.

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
Illegal input detected, i.e., one of the following conditions:
– D02LAF has not been called;
– one or both of the arguments NEQ and LRWORK does not match the corresponding argument supplied to the setup routine D02LXF;
– no integration steps have been taken since the last call to D02LXF with START=.TRUE.;
– NWANT<1 or NWANT>NEQ.
This error exit can be caused if elements of RWORK have been overwritten.
IFAIL=2
D02LZF has been called for extrapolation. The values of the solution and its derivative at TWANT have been calculated and placed in YWANT and YPWANT before returning with this error number (see Section 7).
IFAIL=3
D02LAF last used the high order method to integrate the system of differential equations. Interpolation is not permitted with this method.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

The error in interpolation is of a similar order to the error arising from the integration using D02LAF with the lower order method.
The same order of accuracy can be expected when extrapolating using D02LZF. However, the actual error in extrapolation will, in general, be much larger than for interpolation.

8 Parallelism and Performance

D02LZF is not thread safe and should not be called from a multithreaded user program. Please see Section 3.12.1 in How to Use the NAG Library and its Documentation for more information on thread safety.
D02LZF is not threaded in any implementation.

9 Further Comments

When interpolation for only a few components is required then it is more efficient to order the components of interest so that they are numbered first.

10 Example

See Section 10 in D02LAF.
D02 Chapter Contents
D02 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


D02MCF : NAG Library, Mark 26

D02 Chapter Contents
D02 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

D02MCF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
10 Example

1 Purpose

D02MCF is a setup routine which must be called prior to a continuation call to D02NEF.

2 Specification

SUBROUTINE D02MCF ( ICOM)
INTEGER ICOM(15)

3 Description

D02MCF is provided to permit you to signal that the next call to D02NEF is a continuation call. In particular, if D02NEF exits because the maximum number of integration steps has been exceeded, then a call to D02MCF resets the step counter allowing the integration to proceed.

4 References

See Section 3 in D02NEF.

5 Arguments

1:   ICOM 15 – INTEGER arrayCommunication Array
This must be the same array ICOM as passed to the integration routine D02NEF; D02MCF does not require access to all of that array, hence the smaller dimension given here.
On entry: contains details of the current state of integration as returned by D02NEF.
On exit: one or more of the values is changed to signal to the integrator that a continuation call is being made. This will reset the step counter to zero.

6 Error Indicators and Warnings

None.

7 Accuracy

Not applicable.

8 Parallelism and Performance

D02MCF is not threaded in any implementation.

9 Further Comments

None.

10 Example

See Section 10 in D02NEF.
D02 Chapter Contents
D02 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


D02MN Sub-chapter Introduction : NAG Library, Mark 26

D02 Chapter Contents
NAG Library Manual

NAG Library Sub-chapter Introduction

D02M–N – Integrators for Stiff Ordinary Differential Systems

▸▿ Contents

1 Introduction
2 References

1 Introduction

This sub-chapter contains the specifications of the integrators, the setup routines and diagnostic routines which have been developed from the SPRINT package, Berzins and Furzeland (1985), and from the DASSL package, Brenan et al. (1996).
The SPRINT explicit integrators D02NBF, D02NCF and D02NDF are designed for solving stiff systems of explicitly defined ordinary differential equations,
y′=g t,y.
The SPRINT implicit integrators D02NGF, D02NHF and D02NJF are designed for solving stiff systems of implicitly defined ordinary differential equations,
A t,y y′=g t,y.
The DASSL integrator D02NEF is designed for solving systems of the form, F t,y,y′=0. These formulations permit solution of differential/algebraic systems (DAEs). The facilities provided are essentially those of the explicit solvers.
The SPRINT integrator routines have almost identical calling sequences but each is designed to solve a problem where the Jacobian is of a particular structure: full matrix (D02NBF and D02NGF), banded matrix (D02NCF and D02NHF) or sparse matrix (D02NDF and D02NJF). Each of these structures has associated with it a linear algebra setup routine: D02NSF, D02NTF and D02NUF respectively. A linear algebra setup routine must be called before the first call to the appropriate integrator. These linear algebra setup routines check various arguments of the corresponding integrator routine and set certain arguments for the linear algebra computations. A routine, D02NXF, is supplied which permits extraction of diagnostic information after a call to either of the sparse linear algebra solvers D02NDF and D02NJF.
With the SPRINT integrators are also associated three integrator setup routines D02MVF, D02NVF and D02NWF, one of which must be called before the first call to any integrator routine. They provide input to the Backward Differentiation Formulae (BDF), the Blend Formulae and the special fixed leading coefficient BDF codes respectively. On return from an integrator, if it is feasible to continue the integration, D02NZF may be called to reset various integration arguments. It is often of considerable interest to determine statistics concerning the integration process. D02NYF is provided with this aim in mind. It should prove especially useful to those who wish to integrate many similar problems as it provides suitable values for many of the input arguments and indications of the difficulties encountered when solving the problem.
Hence, the general form of a program calling one of the integrator routines D02NBF, D02NCF, D02NDF, D02NGF, D02NHF or D02NJF will be
declarations
   .
   .
call linear algebra setup routine
call integrator setup routine
call integrator
call integrator diagnostic routine (if required)
call linear algebra diagnostic routine (if appropriate and if required)
   .
   .
STOP
END
The DASSL integrator, D02NEF, has an associated setup routine D02MWF which must be called first. On return from the integrator, if it is feasible to continue the integration, the associated continuation call routine is D02MCF may be called to rest various integration parameters. The structure of the Jacobian is assumed to be full unless D02NPF is called following a call to the setup routine to specify that the Jacobian is banded and to supply its bandwidths.
The required calling sequence for different Jacobian structures and system types is represented diagrammatically in Figure 1.
Schema for SPRINT direct communication routine calling sequences
Figure 1: Schema for SPRINT direct communication routine calling sequences
The integrators D02NMF and D02NNF are reverse communication routines designed for solving explicit and implicit stiff ordinary differential systems respectively. You are warned that you should use these routines only when the integrators mentioned above are inadequate for their application. For example, if it is difficult to write one or more of the user-supplied routine FCN (RESID) or JAC (or MONITR) or if the integrators are to be embedded in a package, it may be advisable to consider these routines.
Since these routines use reverse communication you do not need to define any routines with a prescribed argument list. This makes them especially suitable for large scale computations where encapsulation of the definition of the differential system or its Jacobian matrix in a prescribed routine form may be particularly difficult to achieve.
D02NMF is the reverse communication counterpart of the direct communication routines D02NBF, D02NCF and D02NDF whereas D02NNF is the reverse communication counterpart of the direct communication routines D02NGF, D02NHF and D02NJF. When using these reverse communication routines it is necessary to call the same linear algebra and integrator setup routines as for the direct communication counterpart. All the other continuation and interrogation routines available for use with the direct communication routines are also available to you when calling the reverse communication routines.
There is also a routine, D02NRF, to tell you how to supply the Jacobian when the sparse linear algebra option is being employed with either of D02NMF and D02NNF. Hence, the general form of a program calling one of the integrator routines D02NMF or D02NNF will be
     declarations
     call linear algebra setup routine
     call integrator setup routine
     IREVCM = 0
1000 call integrator( ..., IREVCM, ...)
     IF (IREVCM.GT.0) THEN

        evaluate residual and Jacobian (including a call to D02NRF if
        sparse linear algebra is being used), call the MONITR routine etc.

        GO TO 1000
     ENDIF

     call integrator diagnostic routine (if required)
     call linear algebra diagnostic routine (if appropriate and if required)

     STOP
     END
The required calling sequence in the case of reverse communication, is represented diagramatically in Figure 2.
In the example programs for the eight SPRINT integrators D02NBF, D02NCF, D02NDF, D02NGF, D02NHF, D02NJF, D02NMF and D02NNF we attempt to illustrate the various options available. Many of these options are available in all the routines and you are invited to scan all the example programs for illustrations of their use. In each case we use as an example the stiff Robertson problem
a′ = -0.04 a + 104 bc b′ = 0.04 a - 104 bc - 3×107b 2 c′ = 3×107b 2
despite the fact that it is not a sensible choice to use either the banded or the sparse linear algebra for this problem. Their use here serves for illustration of the techniques involved. For the implicit integrators D02NGF, D02NHF and D02NJF we write the Robertson problem in residual form, as an implicit differential system and as a differential/algebraic system respectively. Here we are exploiting the fact that a+b+c is constant and hence one of the equations may be replaced by a+b+c ′ = 0.0 or a+b+c=1.0 (for our particular choice of initial conditions). For the reverse communication routines D02NMF and D02NNF our examples are intended only to illustrate the reverse communication technique.
Schema for SPRINT reverse communication routine calling sequences
Figure 2: Schema for SPRINT reverse communication routine calling sequences
The DASSL integrator D02NEF can solve DAEs of the fully implicit form F t,y,y′=0 and therefore has increased functionality over the SPRINT integrators. Additionally D02NEF can be used to solve difficult algebraic problems by continuation; for example, the nonlinear algebraic problem
f x=0
can be solved by integrating solutions of
f x + 1-t g x = 0
where the solution to f x +g x = 0 is known. The solution of this type of problem is illustrated in Section 10 in D02NEF.

2 References

Berzins M and Furzeland R M (1985) A user's manual for SPRINT – A versatile software package for solving systems of algebraic, ordinary and partial differential equations: Part 1 – Algebraic and ordinary differential equations Report TNER.85.085 Shell Research Limited
Brenan K, Campbell S and Petzold L (1996) Numerical Solution of Initial-Value Problems in Differential-Algebraic Equations SIAM, Philadelphia
D02 Chapter Contents
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


D02MVF : NAG Library, Mark 26

D02 Chapter Contents
D02 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

D02MVF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

D02MVF is an integration method specific setup routine which must be called prior to linear algebra setup routines and integrators from the SPRINT suite of routines, if the DASSL implementation of Backward Differentiation Formulae (BDF) is to be used. Note that this method is also available, independent from the SPRINT suite, using D02NEF

2 Specification

SUBROUTINE D02MVF ( NEQMAX, SDYSAV, MAXORD, CON, TCRIT, HMIN, HMAX, H0, MAXSTP, MXHNIL, NORM, RWORK, IFAIL)
INTEGER | NEQMAX, SDYSAV, MAXORD, MAXSTP, MXHNIL, IFAIL
REAL (KIND=nag_wp) | CON(3), TCRIT, HMIN, HMAX, H0, RWORK(50+4*NEQMAX)
CHARACTER(1) | NORM

3 Description

An integrator setup routine must be called before the call to any linear algebra setup routine or integrator from the SPRINT suite of routines in this sub-chapter. This setup routine, D02MVF, makes the choice of the DASSL integrator and permits you to define options appropriate to this choice. Alternative choices of integrator from this suite are the BDF method and the BLEND method which can be chosen by initial calls to D02NVF or D02NWF respectively.

4 References

See the D02M–N Sub-chapter Introduction.

5 Arguments

1:   NEQMAX – INTEGERInput
On entry: a bound on the maximum number of differential equations to be solved.
Constraint: NEQMAX≥1.
2:   SDYSAV – INTEGERInput
On entry: the second dimension of the array YSAV that will be supplied to the integrator, as declared in the (sub)program from which the integrator is called (e.g., see D02NBF).
Constraint: SDYSAV≥MAXORD+3.
3:   MAXORD – INTEGERInput
On entry: the maximum order to be used for the BDF method. If MAXORD=0 or MAXORD>5 then MAXORD=5 is assumed.
Constraint: MAXORD≥0.
4:   CON 3 – REAL (KIND=nag_wp) arrayInput/Output
On entry: values to be used to control step size choice during integration. If any CON i=0.0 on entry, it is replaced by its default value described below. In most cases this is the recommended setting.
CON 1, CON 2, and CON 3 are factors used to bound step size changes. If the current step size h fails, then the modulus of the next step size is bounded by CON 1×h. The default value of CON 1 is 2.0. Note that the new step size may be used with a method of different order to the failed step. If the initial step size is h, then the modulus of the step size on the second step is bounded by CON 3×h. At any other stage in the integration, if the current step size is h, then the modulus of the next step size is bounded by CON 2×h. The default values are 10.0 for CON 2 and 1000.0 for CON 3.
Constraints:
These constraints must be satisfied after any zero values have been replaced by default values.
  • 0.0<CON 1<CON 2<CON 3;
  • CON 2>1.0;
  • CON 3>1.0.
On exit: the values actually to be used by the integration routine.
5:   TCRIT – REAL (KIND=nag_wp)Input
On entry: a point beyond which integration must not be attempted. The use of TCRIT is described under the argument ITASK in the specification for the integrator (e.g., see D02NBF). A value, 0.0 say, must be specified even if ITASK subsequently specifies that TCRIT will not be used.
6:   HMIN – REAL (KIND=nag_wp)Input
On entry: the minimum absolute step size to be allowed. Set HMIN=0.0 if this option is not required.
7:   HMAX – REAL (KIND=nag_wp)Input
On entry: the maximum absolute step size to be allowed. Set HMAX=0.0 if this option is not required.
8:   H0 – REAL (KIND=nag_wp)Input
On entry: the step size to be attempted on the first step. Set H0=0.0 if the initial step size is calculated internally.
9:   MAXSTP – INTEGERInput
On entry: the maximum number of steps to be attempted during one call to the integrator after which it will return with IFAIL=2 (e.g., see D02NBF). Set MAXSTP=0 if no limit is to be imposed.
10:   MXHNIL – INTEGERInput
On entry: the maximum number of warnings printed (if ITRACE≥0, e.g., see D02NBF) per problem when t+h=t on a step (h=​ current step size). If MXHNIL≤0, a default value of 10 is assumed.
11:   NORM – CHARACTER(1)Input
On entry: indicates the type of norm to be used.
NORM='M'
Maximum norm.
NORM='A'
Averaged L2 norm.
NORM='D'
Is the same as 'A'.
If vnorm denotes the norm of the vector v of length n, then for the averaged L2 norm
vnormB=1 n∑i=1 n viwi 2,
while for the maximum norm
vnorm=max 1≤i≤n viwi .
If you wish to weight the maximum norm or the L2 norm, then RTOL and ATOL should be scaled appropriately on input to the integrator (see under ITOL in the specification of the integrator for the formulation of the weight vector wi from RTOL and ATOL, e.g., see D02NBF).
Only the first character to the actual argument NORM is passed to D02MVF; hence it is permissible for the actual argument to be more descriptive, e.g., ‘Maximum’, ‘Average L2’ or ‘Default’ in a call to D02MVF.
Constraint: NORM='M', 'A' or 'D'.
12:   RWORK 50+4×NEQMAX – REAL (KIND=nag_wp) arrayCommunication Array
This must be the same workspace array as the array RWORK supplied to the integrator. It is used to pass information from the setup routine to the integrator and therefore the contents of this array must not be changed before calling the integrator.
13:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, | NEQMAX<1,
or | SDYSAV<MAXORD+3,
or | MAXORD<0,
or | MAXORD>5,
or | invalid value for element of the array CON,
or | NORM≠'M', 'A' or 'D'.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

Not applicable.

8 Parallelism and Performance

D02MVF is not threaded in any implementation.

9 Further Comments

None.

10 Example

This example solves the plane pendulum problem defined by the equations:
x′ = u y′ = v u′ = -λx v′ = -λy-1 x 2+y 2 = 1
The additional algebraic constraint xu+yv=0 can be derived, and after appropriate substitution and manipulation to avoid a singular Jacobian solves the equations:
y 1′ = y 3-y 6y 1 y 2′ = y 4-y 6y 2 y 3′ = -y 5y 1 y 4′ = -y 5y 2-1 0 = y 1y 3+y 2y 4 0 = y 12+y 22-1
with given initial conditions and derivatives.

10.1 Program Text

Program Text (d02mvfe.f90)

10.2 Program Data

Program Data (d02mvfe.d)

10.3 Program Results

Program Results (d02mvfe.r)

GnuplotProduced by GNUPLOT 4.6 patchlevel 3 −1 −0.9 −0.8 −0.7 −0.6 −0.5 −0.4 −0.3 −0.2 −0.1 0 −1 −0.8 −0.6 −0.4 −0.2 0 0.2 0.4 0.6 0.8 1 Pendulum Displacement x Example Program DASSL Implementation of BDF Method for Stiff ODE Plane Pendulum Problem gnuplot_plot_1
D02 Chapter Contents
D02 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


D02MWF : NAG Library, Mark 26

D02 Chapter Contents
D02 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

D02MWF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

D02MWF is a setup routine which must be called prior to the integrator D02NEF, if the DASSL implementation of Backward Differentiation Formulae (BDF) is to be used.

2 Specification

SUBROUTINE D02MWF ( NEQ, MAXORD, JCEVAL, HMAX, H0, ITOL, ICOM, LICOM, COM, LCOM, IFAIL)
INTEGER | NEQ, MAXORD, ITOL, ICOM(LICOM), LICOM, LCOM, IFAIL
REAL (KIND=nag_wp) | HMAX, H0, COM(LCOM)
CHARACTER(1) | JCEVAL

3 Description

This integrator setup routine must be called before the first call to the integrator D02NEF. This setup routine D02MWF permits you to define options for the DASSL integrator, such as: whether the Jacobian is to be provided or is to be approximated numerically by the integrator; the initial and maximum step-sizes for the integration; whether relative and absolute tolerances are system wide or per system equation; and the maximum order of BDF method permitted.

4 References

None.

5 Arguments

1:   NEQ – INTEGERInput
On entry: the number of differential-algebraic equations to be solved.
Constraint: NEQ≥1.
2:   MAXORD – INTEGERInput
On entry: the maximum order to be used for the BDF method. Orders up to 5th order are available; setting MAXORD>5 means that the maximum order used will be 5.
Constraint: 1≤MAXORD.
3:   JCEVAL – CHARACTER(1)Input
On entry: specifies the technique to be used to compute the Jacobian.
JCEVAL='N'
The Jacobian is to be evaluated numerically by the integrator.
JCEVAL='A'
You must supply a subroutine to evaluate the Jacobian on a call to the integrator.
Only the first character of the actual paramater JCEVAL is passed to D02MWF; hence it is permissible for the actual argument to be more descriptive, e.g., ‘Numerical’ or ‘Analytical’, on a call to D02MWF.
Constraint: JCEVAL='N' or 'A'.
4:   HMAX – REAL (KIND=nag_wp)Input
On entry: the maximum absolute step size to be allowed. Set HMAX=0.0 if this option is not required.
Constraint: HMAX≥0.0.
5:   H0 – REAL (KIND=nag_wp)Input
On entry: the step size to be attempted on the first step. Set H0=0.0 if the initial step size is calculated internally.
6:   ITOL – INTEGERInput
On entry: a value to indicate the form of the local error test.
ITOL=0
RTOL and ATOL are single element vectors.
ITOL=1
RTOL and ATOL are vectors. This should be chosen if you want to apply different tolerances to each equation in the system.
See D02NEF.
Note: the tolerances must either both be single element vectors or both be vectors of length NEQ.
Constraint: ITOL=0 or 1.
7:   ICOM LICOM – INTEGER arrayCommunication Array
On exit: used to communicate details of the task to be carried out to the integration routine D02NEF.
8:   LICOM – INTEGERInput
On entry: the dimension of the array ICOM as declared in the (sub)program from which D02MWF is called.
Constraint: LICOM≥NEQ+50.
9:   COM LCOM – REAL (KIND=nag_wp) arrayCommunication Array
On exit: used to communicate problem parameters to the integration routine D02NEF. This must be the same communication array as the array COM supplied to D02NEF. In particular, the values of HMAX and H0 are contained in COM.
10:   LCOM – INTEGERInput
On entry: the dimension of the array COM as declared in the (sub)program from which D02MWF is called.
Constraints:
the array COM must be large enough for the requirements of D02NEF. That is:
  • if the system Jacobian is dense, LCOM ≥ 40 + MAXORD+4 × NEQ + NEQ 2 ;
  • if the system Jacobian is banded, LCOM ≥ 40 + MAXORD+4 × NEQ + 2×ML+MU+1 × NEQ + 2 × NEQ / ML + MU + 1 + 1 .
Here ML and MU are the lower and upper bandwidths respectively that are to be specified in a subsequent call to D02NPF.
11:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, NEQ=value.
Constraint: NEQ≥1.
IFAIL=2
On entry, MAXORD=value.
Constraint: MAXORD≥1.
IFAIL=3
On entry, JCEVAL has an illegal value: JCEVAL=value.
Constraint: JCEVAL='N' or 'A'.
IFAIL=4
On entry, HMAX=value.
Constraint: HMAX≥0.0.
IFAIL=6
On entry, ITOL=value.
Constraint: ITOL=0 or 1.
IFAIL=8
On entry, LICOM=value and NEQ=value.
Constraint: LICOM≥50+NEQ.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

Not applicable.

8 Parallelism and Performance

D02MWF is not threaded in any implementation.

9 Further Comments

None.

10 Example

This example solves the plane pendulum problem, defined by the following equations:
x′ = u y′ = v u′ = -λx v′ = -λy-1 x 2+y 2 = 1.
Differentiating the algebraic constraint once, a new algebraic constraint is obtained
xu+yv=0 .
Differentiating the algebraic constraint one more time, substituting for x′, y′, u′, v′ and using x 2+y 2-1=0, the corresponding DAE system includes the differential equations and the algebraic equation in λ:
u 2 + v 2 - λ - y = 0 .
We solve the reformulated DAE system
y 1′ = y 3 y 2′ = y 4 y 3′ = -y 5×y 1 y 4′ = -y 5×y 2-1 y 32 + y 42 - y 5 - y 2 = 0.
For our experiments, we take consistent initial values
y 1 0 = 1 , ​ y 2 0 = 0 , ​ y 3 0 = 0 , ​ y 4 0 = 1 ​ and ​ y 5 0 = 1
at t=0.

10.1 Program Text

Program Text (d02mwfe.f90)

10.2 Program Data

Program Data (d02mwfe.d)

10.3 Program Results

Program Results (d02mwfe.r)

D02 Chapter Contents
D02 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


D02MZF : NAG Library, Mark 26

D02 Chapter Contents
D02 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

D02MZF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

D02MZF interpolates components of the solution of a system of first-order differential equations from information provided by those integrators in Sub-chapter D02M–N using methods set up by calls to D02MVF, D02NVF or D02NWF.

2 Specification

SUBROUTINE D02MZF ( TSOL, SOL, M, LDYSAV, NEQ, YSAV, SDYSAV, RWORK, IFAIL)
INTEGER | M, LDYSAV, NEQ, SDYSAV, IFAIL
REAL (KIND=nag_wp) | TSOL, SOL(M), YSAV(LDYSAV,SDYSAV), RWORK(50+4*NEQ)

3 Description

D02MZF evaluates the first M components of the solution of a system of ordinary differential equations at any point using natural polynomial interpolation based on information generated by the integrator. This information must be passed unchanged to D02MZF. D02MZF should not normally be used to extrapolate outside the range of values obtained from the above routine.

4 References

See the D02M–N Sub-chapter Introduction.

5 Arguments

1:   TSOL – REAL (KIND=nag_wp)Input
On entry: the point at which the first M components of the solution are to be evaluated. TSOL should not normally be an extrapolation point. Extrapolation is permitted but not recommended.
2:   SOL M – REAL (KIND=nag_wp) arrayOutput
On exit: the calculated value of the solution at TSOL.
3:   M – INTEGERInput
On entry: the number of components of the solution whose values are required.
Constraint: 1≤M≤NEQ.
4:   LDYSAV – INTEGERInput
On entry: the value used for the argument LDYSAV when calling the integrator.
Constraint: LDYSAV≥1.
5:   NEQ – INTEGERInput
On entry: the value used for the argument NEQ when calling the integrator.
Constraint: 1≤NEQ≤LDYSAV.
6:   YSAV LDYSAVSDYSAV – REAL (KIND=nag_wp) arrayInput
On entry: the values provided in the array YSAV on return from the integrator.
7:   SDYSAV – INTEGERInput
On entry: the value used for the argument SDYSAV when calling the integrator.
8:   RWORK 50+4×NEQ – REAL (KIND=nag_wp) arrayInput
On entry: the values provided in the array RWORK on return from the integrator.
9:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, | M<1,
or | LDYSAV<1,
or | NEQ<1,
or | M>NEQ,
or | NEQ>LDYSAV.
IFAIL=2
On entry, when accessing an element of the array RWORK an unexpected quantity was found. You have not passed the correct array to D02MZF or has overwritten elements of this array.
IFAIL=3
On entry, D02MZF has been called for extrapolation. Before returning with this error exit, the value of the solution at TSOL is calculated and placed in SOL.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

The solution values returned will be of a similar accuracy to those computed by the integrator.

8 Parallelism and Performance

D02MZF is not thread safe and should not be called from a multithreaded user program. Please see Section 3.12.1 in How to Use the NAG Library and its Documentation for more information on thread safety.
D02MZF is not threaded in any implementation.

9 Further Comments

None.

10 Example

This example solves the well-known stiff Robertson problem written in implicit form
r 1 = -0.04 a + 1.0 E 4 bc - a′ r 2 = 0.04 a - 1.0 E 4 bc - 3.0 E 7⁢b 2 - b′ r 3 = 3.0 E 7⁢b 2 - c′
with initial conditions a=1.0 and b=c=0.0 over the range 0,0.1 with vector error control (ITOL=4), the BDF method (setup routine D02NVF) and functional iteration. The Jacobian is calculated numerically if the functional iteration encounters difficulty and the integration is in one-step mode (ITASK=2), with natural interpolation to calculate the solution at intervals of 0.02 using D02MZF externally. D02NBY is used for MONITR.

10.1 Program Text

Program Text (d02mzfe.f90)

10.2 Program Data

Program Data (d02mzfe.d)

10.3 Program Results

Program Results (d02mzfe.r)

D02 Chapter Contents
D02 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


D02NBF : NAG Library, Mark 26

D02 Chapter Contents
D02 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

D02NBF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

D02NBF is a direct communication routine for integrating stiff systems of explicit ordinary differential equations when the Jacobian is a full matrix.

2 Specification

SUBROUTINE D02NBF ( NEQ, LDYSAV, T, TOUT, Y, YDOT, RWORK, RTOL, ATOL, ITOL, INFORM, FCN, YSAV, SDYSAV, JAC, WKJAC, NWKJAC, MONITR, ITASK, ITRACE, IFAIL)
INTEGER | NEQ, LDYSAV, ITOL, INFORM(23), SDYSAV, NWKJAC, ITASK, ITRACE, IFAIL
REAL (KIND=nag_wp) | T, TOUT, Y(NEQ), YDOT(NEQ), RWORK(50+4*NEQ), RTOL(*), ATOL(*), YSAV(LDYSAV,SDYSAV), WKJAC(NWKJAC)
EXTERNAL | FCN, JAC, MONITR

3 Description

D02NBF is a general purpose routine for integrating the initial value problem for a stiff system of explicit ordinary differential equations,
y′=g t,y.
It is designed specifically for the case where the Jacobian ∂g ∂y is a full matrix.
Both interval and step oriented modes of operation are available and also modes designed to permit intermediate output within an interval oriented mode.
An outline of a typical calling program for D02NBF is given below. It calls the full matrix linear algebra setup routine D02NSF, the Backward Differentiation Formula (BDF) integrator setup routine D02NVF, and its diagnostic counterpart D02NYF.
!     Declarations

      EXTERNAL FCN, JAC, MONITR
          .
          .
          .
      IFAIL = 0
      CALL D02NVF(...,IFAIL)
      CALL D02NSF(NEQ, LDYSAV, JCEVAL, NWKJAC, RWORK, IFAIL)
      IFAIL = -1
      CALL D02NBF(NEQ, LDYSAV, T, TOUT, Y, YDOT, RWORK, RTOL,       &
        ATOL, ITOL, INFORM, FCN, YSAVE, SDYSAV, JAC, WKJAC, NWKJAC, &
        MONITR, ITASK, ITRACE, IFAIL)
      IF (IFAIL.EQ.1 .OR. IFAIL.GE.14) STOP
      IFAIL = 0
      CALL D02NYF(...)
          .
          .
          .
      STOP
      END
The linear algebra setup routine D02NSF and one of the integrator setup routines, D02NVF or D02NWF, must be called prior to the call of D02NBF. The integrator diagnostic routine D02NYF may be called after the call to D02NBF. There is also a routine, D02NZF, designed to permit you to change step size on a continuation call to D02NBF without restarting the integration process.

4 References

See the D02M–N Sub-chapter Introduction.

5 Arguments

1:   NEQ – INTEGERInput
On entry: the number of differential equations to be solved.
Constraint: NEQ≥1.
2:   LDYSAV – INTEGERInput
On entry: a bound on the maximum number of differential equations to be solved during the integration.
Constraint: LDYSAV≥NEQ.
3:   T – REAL (KIND=nag_wp)Input/Output
On entry: t, the value of the independent variable. The input value of T is used only on the first call as the initial point of the integration.
On exit: the value at which the computed solution y is returned (usually at TOUT).
4:   TOUT – REAL (KIND=nag_wp)Input
On entry: the next value of t at which a computed solution is desired. For the initial t, the input value of TOUT is used to determine the direction of integration. Integration is permitted in either direction (see also ITASK).
Constraint: TOUT≠T.
5:   Y NEQ – REAL (KIND=nag_wp) arrayInput/Output
On entry: the values of the dependent variables (solution). On the first call the first NEQ elements of Y must contain the vector of initial values.
On exit: the computed solution vector, evaluated at T (usually T=TOUT).
6:   YDOT NEQ – REAL (KIND=nag_wp) arrayOutput
On exit: the time derivatives y′ of the vector y at the last integration point.
7:   RWORK 50+4×NEQ – REAL (KIND=nag_wp) arrayCommunication Array
8:   RTOL* – REAL (KIND=nag_wp) arrayInput
Note: the dimension of the array RTOL must be at least 1 if ITOL=1 or 2, and at least NEQ otherwise.
On entry: the relative local error tolerance.
Constraint: RTOL i≥0.0 for all relevant i (see ITOL).
9:   ATOL* – REAL (KIND=nag_wp) arrayInput
Note: the dimension of the array ATOL must be at least 1 if ITOL=1 or 3, and at least NEQ otherwise.
On entry: the absolute local error tolerance.
Constraint: ATOL i≥0.0 for all relevant i (see ITOL).
10:   ITOL – INTEGERInput
On entry: a value to indicate the form of the local error test. ITOL indicates to D02NBF whether to interpret either or both of RTOL or ATOL as a vector or a scalar. The error test to be satisfied is ei/wi<1.0, where wi is defined as follows:
ITOL | RTOL | ATOL | wi
1 | scalar | scalar | RTOL 1×yi+ATOL 1
2 | scalar | vector | RTOL 1×yi+ATOL i
3 | vector | scalar | RTOL i×yi+ATOL 1
4 | vector | vector | RTOL i×yi+ATOL i
ei is an estimate of the local error in yi, computed internally, and the choice of norm to be used is defined by a previous call to an integrator setup routine.
Constraint: ITOL=1, 2, 3 or 4.
11:   INFORM 23 – INTEGER arrayCommunication Array
12:   FCN – SUBROUTINE, supplied by the user.External Procedure
FCN must evaluate the derivative vector for the explicit ordinary differential equation system, defined by y′=g t,y.
The specification of FCN is:
SUBROUTINE FCN ( NEQ, T, Y, F, IRES)
INTEGER | NEQ, IRES
REAL (KIND=nag_wp) | T, Y(NEQ), F(NEQ)
1:   NEQ – INTEGERInput
On entry: the number of differential equations being solved.
2:   T – REAL (KIND=nag_wp)Input
On entry: t, the current value of the independent variable.
3:   Y NEQ – REAL (KIND=nag_wp) arrayInput
On entry: the value of yi, for i=1,2,…,NEQ.
4:   F NEQ – REAL (KIND=nag_wp) arrayOutput
On exit: the value yi′, given by yi′=gi t,y, for i=1,2,…,NEQ.
5:   IRES – INTEGERInput/Output
On entry: IRES=1.
On exit: you may set IRES as follows to indicate certain conditions in FCN to the integrator:
IRES=1
Indicates a normal return from FCN, that is IRES has not been altered by you and integration continues.
IRES=2
Indicates to the integrator that control should be passed back immediately to the calling (sub)program with the error indicator set to IFAIL=11.
IRES=3
Indicates to the integrator that an error condition has occurred in the solution vector, its time derivative or in the value of t. The integrator will use a smaller time step to try to avoid this condition. If this is not possible the integrator returns to the calling (sub)program with the error indicator set to IFAIL=7.
IRES=4
Indicates to the integrator to stop its current operation and to enter MONITR immediately with argument IMON=-2.
FCN must either be a module subprogram USEd by, or declared as EXTERNAL in, the (sub)program from which D02NBF is called. Arguments denoted as Input must not be changed by this procedure.
13:   YSAV LDYSAVSDYSAV – REAL (KIND=nag_wp) arrayCommunication Array
14:   SDYSAV – INTEGERInput
On entry: the second dimension of the array YSAV as declared in the (sub)program from which D02NBF is called. An appropriate value for SDYSAV is described in the specification of the integrator setup routines D02NVF and D02NWF. This value must be the same as that supplied to the integrator setup routine.
15:   JAC – SUBROUTINE, supplied by the NAG Library or the user.External Procedure
JAC must evaluate the Jacobian of the system. If this option is not required, the actual argument for JAC must be the dummy routine D02NBZ. (D02NBZ is included in the NAG Library.) You must indicate to the integrator whether this option is to be used by setting the argument JCEVAL appropriately in a call to the full linear algebra setup routine D02NSF.
First we must define the system of nonlinear equations which is solved internally by the integrator. The time derivative, y′, generated internally, has the form
y′ = y-z / hd ,
where h is the current step size and d is an argument that depends on the integration method in use. The vector y is the current solution and the vector z depends on information from previous time steps. This means that d d y′ ​ ​ = hd d dy ​ ​ . The system of nonlinear equations that is solved has the form
y′ - g t,y = 0
but it is solved in the form
r t,y = 0 ,
where r is the function defined by
r t,y =hd y-z / hd - g t,y .
It is the Jacobian matrix ∂r ∂y that you must supply in JAC as follows:
∂ri ∂yj =1-hd ∂gi ∂yj , if ​i=j, ∂ri ∂yj = -hd ∂gi ∂yj , otherwise.
The specification of JAC is:
SUBROUTINE JAC ( NEQ, T, Y, H, D, P)
INTEGER | NEQ
REAL (KIND=nag_wp) | T, Y(NEQ), H, D, P(NEQ,NEQ)
1:   NEQ – INTEGERInput
On entry: the number of differential equations being solved.
2:   T – REAL (KIND=nag_wp)Input
On entry: t, the current value of the independent variable.
3:   Y NEQ – REAL (KIND=nag_wp) arrayInput
On entry: yi, for i=1,2,…,NEQ, the current solution component.
4:   H – REAL (KIND=nag_wp)Input
On entry: the current step size.
5:   D – REAL (KIND=nag_wp)Input
On entry: the argument d which depends on the integration method.
6:   P NEQNEQ – REAL (KIND=nag_wp) arrayInput/Output
On entry: is set to zero.
On exit: P ij must contain ∂ri ∂yj , for i=1,2,…,NEQ and j=1,2,…,NEQ.
Only the nonzero elements of this array need be set, since it is preset to zero before the call to JAC.
JAC must either be a module subprogram USEd by, or declared as EXTERNAL in, the (sub)program from which D02NBF is called. Arguments denoted as Input must not be changed by this procedure.
16:   WKJAC NWKJAC – REAL (KIND=nag_wp) arrayCommunication Array
17:   NWKJAC – INTEGERInput
On entry: the dimension of the array WKJAC as declared in the (sub)program from which D02NBF is called. This value must be the same as that supplied to the linear algebra setup routine D02NSF.
Constraint: NWKJAC≥LDYSAV×LDYSAV+1.
18:   MONITR – SUBROUTINE, supplied by the NAG Library or the user.External Procedure
MONITR performs tasks requested by you. If this option is not required, then the actual argument for MONITR must be the dummy routine D02NBY. (D02NBY is included in the NAG Library.)
The specification of MONITR is:
SUBROUTINE MONITR ( NEQ, LDYSAV, T, HLAST, HNEXT, Y, YDOT, YSAV, R, ACOR, IMON, INLN, HMIN, HMAX, NQU)
INTEGER | NEQ, LDYSAV, IMON, INLN, NQU
REAL (KIND=nag_wp) | T, HLAST, HNEXT, Y(NEQ), YDOT(NEQ), YSAV(LDYSAV,sdysav), R(NEQ), ACOR(NEQ,2), HMIN, HMAX
where sdysav is the numerical value of SDYSAV in the call of D02NBF.
1:   NEQ – INTEGERInput
On entry: the number of differential equations being solved.
2:   LDYSAV – INTEGERInput
On entry: an upper bound on the number of differential equations to be solved.
3:   T – REAL (KIND=nag_wp)Input
On entry: the current value of the independent variable.
4:   HLAST – REAL (KIND=nag_wp)Input
On entry: the last step size successfully used by the integrator.
5:   HNEXT – REAL (KIND=nag_wp)Input/Output
On entry: the step size that the integrator proposes to take on the next step.
On exit: the next step size to be used. If this is different from the input value, then IMON must be set to 4.
6:   Y NEQ – REAL (KIND=nag_wp) arrayInput/Output
On entry: y, the values of the dependent variables evaluated at t.
On exit: these values must not be changed unless IMON is set to 2.
7:   YDOT NEQ – REAL (KIND=nag_wp) arrayInput
On entry: the time derivatives y′ of the vector y.
8:   YSAV LDYSAVsdysav – REAL (KIND=nag_wp) arrayInput
On entry: workspace to enable you to carry out interpolation using either of the routines D02XJF or D02XKF.
9:   R NEQ – REAL (KIND=nag_wp) arrayInput
On entry: if IMON=0 and INLN=3, the first NEQ elements contain the residual vector, y′-g t,y.
10:   ACOR NEQ 2 – REAL (KIND=nag_wp) arrayInput
On entry: with IMON=1, ACOR i 1 contains the weight used for the ith equation when the norm is evaluated, and ACOR i 2 contains the estimated local error for the ith equation. The scaled local error at the end of a timestep may be obtained by calling the real function D02ZAF as follows:
 IFAIL = 1
 ERRLOC = D02ZAF(NEQ, ACOR(1,2), ACOR(1,1), IFAIL)
 ! CHECK IFAIL BEFORE PROCEEDING
11:   IMON – INTEGERInput/Output
On entry: a flag indicating under what circumstances MONITR was called:
IMON=-2
Entry from the integrator after IRES=4 (set in FCN) caused an early termination (this facility could be used to locate discontinuities).
IMON=-1
The current step failed repeatedly.
IMON=0
Entry after a call to the internal nonlinear equation solver (see INLN).
IMON=1
The current step was successful.
On exit: may be reset to determine subsequent action in D02NBF.
IMON=-2
Integration is to be halted. A return will be made from the integrator to the calling (sub)program with IFAIL=12.
IMON=-1
Allow the integrator to continue with its own internal strategy. The integrator will try up to three restarts unless IMON is set ≠-1 on exit.
IMON=0
Return to the internal nonlinear equation solver, where the action taken is determined by the value of INLN (see INLN).
IMON=1
Normal exit to the integrator to continue integration.
IMON=2
Restart the integration at the current time point. The integrator will restart from order 1 when this option is used. The solution Y, provided by MONITR, will be used for the initial conditions.
IMON=3
Try to continue with the same step size and order as was to be used before the call to MONITR. HMIN and HMAX may be altered if desired.
IMON=4
Continue the integration but using a new value of HNEXT and possibly new values of HMIN and HMAX.
12:   INLN – INTEGEROutput
On exit: the action to be taken by the internal nonlinear equation solver when MONITR is exited with IMON=0. By setting INLN=3 and returning to the integrator, the residual vector is evaluated and placed in the array R, and then MONITR is called again. At present this is the only option available: INLN must not be set to any other value.
13:   HMIN – REAL (KIND=nag_wp)Input/Output
On entry: the minimum step size to be taken on the next step.
On exit: the minimum step size to be used. If this is different from the input value, then IMON must be set to 3 or 4.
14:   HMAX – REAL (KIND=nag_wp)Input/Output
On entry: the maximum step size to be taken on the next step.
On exit: the maximum step size to be used. If this is different from the input value, then IMON must be set to 3 or 4. If HMAX is set to zero, no limit is assumed.
15:   NQU – INTEGERInput
On entry: the order of the integrator used on the last step. This is supplied to enable you to carry out interpolation using either of the routines D02XJF or D02XKF.
MONITR must either be a module subprogram USEd by, or declared as EXTERNAL in, the (sub)program from which D02NBF is called. Arguments denoted as Input must not be changed by this procedure.
19:   ITASK – INTEGERInput
On entry: the task to be performed by the integrator.
ITASK=1
Normal computation of output values of y t at t=TOUT (by overshooting and interpolating).
ITASK=2
Take one step only and return.
ITASK=3
Stop at the first internal integration point at or beyond t=TOUT and return.
ITASK=4
Normal computation of output values of y t at t=TOUT but without overshooting t=TCRIT (e.g., see D02MVF). TCRIT must be specified as an option in one of the integrator setup routines before the first call to the integrator, or specified in the optional input routine before a continuation call. TCRIT may be equal to or beyond TOUT, but not before it, in the direction of integration.
ITASK=5
Take one step only and return, without passing TCRIT (e.g., see D02MVF). TCRIT must be specified as under ITASK=4.
Constraint: ITASK=1, 2, 3, 4 or 5.
20:   ITRACE – INTEGERInput
On entry: the level of output that is printed by the integrator. ITRACE may take the value -1, 0, 1, 2 or 3.
ITRACE<-1
-1 is assumed and similarly if ITRACE>3, then 3 is assumed.
ITRACE=-1
No output is generated.
ITRACE=0
Only warning messages are printed on the current error message unit (see X04AAF).
ITRACE>0
Warning messages are printed as above, and on the current advisory message unit (see X04ABF) output is generated which details Jacobian entries, the nonlinear iteration and the time integration. The advisory messages are given in greater detail the larger the value of ITRACE.
21:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, because for this routine the values of the output arguments may be useful even if IFAIL≠0 on exit, the recommended value is -1. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
An illegal input was detected on entry, or after an internal call to MONITR. If ITRACE>-1, then the form of the error will be detailed on the current error message unit (see X04AAF).
IFAIL=2
The maximum number of steps specified has been taken (see the description of optional inputs in the integrator setup routines and the optional input continuation routine, D02NZF).
IFAIL=3
With the given values of RTOL and ATOL no further progress can be made across the integration range from the current point T. The components Y 1,Y 2,…,Y NEQ contain the computed values of the solution at the current point T.
IFAIL=4
There were repeated error test failures on an attempted step, before completing the requested task, but the integration was successful as far as T. The problem may have a singularity, or the local error requirements may be inappropriate.
IFAIL=5
There were repeated convergence test failures on an attempted step, before completing the requested task, but the integration was successful as far as T. This may be caused by an inaccurate Jacobian matrix or one which is incorrectly computed.
IFAIL=6
Some error weight wi became zero during the integration (see the description of ITOL). Pure relative error control (ATOL i=0.0) was requested on a variable (the ith) which has now vanished. The integration was successful as far as T.
IFAIL=7
FCN set its error flag (IRES=3) continually despite repeated attempts by the integrator to avoid this.
IFAIL=8
Not used for this integrator.
IFAIL=9
A singular Jacobian ∂r ∂y has been encountered. This error exit is unlikely to be taken when solving explicit ordinary differential equations. You should check the problem formulation and Jacobian calculation.
IFAIL=10
An error occurred during Jacobian formulation or back-substitution (a more detailed error description may be directed to the current error message unit, see X04AAF).
IFAIL=11
FCN signalled the integrator to halt the integration and return (IRES=2). Integration was successful as far as T.
IFAIL=12
MONITR set IMON=-2 and so forced a return but the integration was successful as far as T.
IFAIL=13
The requested task has been completed, but it is estimated that a small change in RTOL and ATOL is unlikely to produce any change in the computed solution. (Only applies when you are not operating in one step mode, that is when ITASK≠2 or 5.)
IFAIL=14
The values of RTOL and ATOL are so small that D02NBF is unable to start the integration.
IFAIL=15
The linear algebra setup routine D02NSF was not called prior to calling D02NBF.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

The accuracy of the numerical solution may be controlled by a careful choice of the arguments RTOL and ATOL, and to a much lesser extent by the choice of norm. You are advised to use scalar error control unless the components of the solution are expected to be poorly scaled. For the type of decaying solution typical of many stiff problems, relative error control with a small absolute error threshold will be most appropriate (that is, you are advised to choose ITOL=1 with ATOL 1 small but positive).

8 Parallelism and Performance

D02NBF is not thread safe and should not be called from a multithreaded user program. Please see Section 3.12.1 in How to Use the NAG Library and its Documentation for more information on thread safety.
D02NBF is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
D02NBF makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The cost of computing a solution depends critically on the size of the differential system and to a lesser extent on the degree of stiffness of the problem. For D02NBF the cost is proportional to NEQ 3, though for problems which are only mildly nonlinear the cost may be dominated by factors proportional to NEQ 2 except for very large problems.
In general, you are advised to choose the Backward Differentiation Formula option (setup routine D02NVF) but if efficiency is of great importance and especially if it is suspected that ∂g ∂y has complex eigenvalues near the imaginary axis for some part of the integration, you should try the BLEND option (setup routine D02NWF).

10 Example

This example solves the well-known stiff Robertson problem
a′ = -0.04 a + 1.0 E 4 bc b′ = 0.04 a - 1.0 E 4 bc - 3.0 E 7⁢b 2 c′ = 3.0 E 7⁢b 2
over the range 0,10 with initial conditions a=1.0 and b=c=0.0 using scalar error control (ITOL=1) and computation of the solution at TOUT=10.0 with TCRIT (e.g., see D02MVF) set to 10.0 (ITASK=4). D02NBY is used for MONITR, a BDF integrator (setup routine D02NVF) is used and a modified Newton method is selected. This example illustrates the use of both a numerical and an analytical Jacobian.

10.1 Program Text

Program Text (d02nbfe.f90)

10.2 Program Data

Program Data (d02nbfe.d)

10.3 Program Results

Program Results (d02nbfe.r)

GnuplotProduced by GNUPLOT 4.6 patchlevel 3 0 0.2 0.4 0.6 0.8 1 1e−10 1e−08 1e−06 0.0001 0.01 1 -1e−05 0 1e−05 2e−05 3e−05 4e−05 5e−05 6e−05 Solution (a,c) Solution (b) x(logscale) Example Program Stiff Explicit ODE, Full Jacobian Stiff Robertson Problem (BDF integrator) a b c gnuplot_plot_1 gnuplot_plot_2 gnuplot_plot_3
D02 Chapter Contents
D02 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


D02NCF : NAG Library, Mark 26

D02 Chapter Contents
D02 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

D02NCF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

D02NCF is a direct communication routine for integrating stiff systems of explicit ordinary differential equations when the Jacobian is a banded matrix.

2 Specification

SUBROUTINE D02NCF ( NEQ, LDYSAV, T, TOUT, Y, YDOT, RWORK, RTOL, ATOL, ITOL, INFORM, FCN, YSAV, SDYSAV, JAC, WKJAC, NWKJAC, JACPVT, NJCPVT, MONITR, ITASK, ITRACE, IFAIL)
INTEGER | NEQ, LDYSAV, ITOL, INFORM(23), SDYSAV, NWKJAC, JACPVT(NJCPVT), NJCPVT, ITASK, ITRACE, IFAIL
REAL (KIND=nag_wp) | T, TOUT, Y(NEQ), YDOT(NEQ), RWORK(50+4*NEQ), RTOL(*), ATOL(*), YSAV(LDYSAV,SDYSAV), WKJAC(NWKJAC)
EXTERNAL | FCN, JAC, MONITR

3 Description

D02NCF is a general purpose routine for integrating the initial value problem for a stiff system of explicit ordinary differential equations,
y′=g t,y.
It is designed specifically for the case where the Jacobian ∂g ∂y is a banded matrix.
Both interval and step oriented modes of operation are available and also modes designed to permit intermediate output within an interval oriented mode.
An outline of a typical calling program for D02NCF is given below. It calls the banded matrix linear algebra setup routine D02NTF, the Backward Differentiation Formula (BDF) integrator setup routine D02NVF, and its diagnostic counterpart D02NYF.
!     Declarations

      EXTERNAL FCN, JAC, MONITR
          .
          .
          .
      IFAIL = 0
      CALL D02NVF(...,IFAIL)
      CALL D02NTF(NEQ, NEQMAX, JCEVAL, ML, MU, NWKJAC, NJCPVT, &
                  RWORK, IFAIL)
      IFAIL = -1
      CALL D02NCF(NEQ, NEQMAX, T, TOUT, Y, YDOT, RWORK, RTOL,  &
                  ATOL, ITOL, INFORM, FCN, YSAVE, NY2DIM, JAC, &
                  WKJAC, NWKJAC,JACPVT, NJCPVT, MONITR, ITASK, &
           ITRACE, IFAIL)
      IF (IFAIL.EQ.1 .OR. IFAIL.GE.14) STOP
      IFAIL = 0
      CALL D02NYF(...)
          .
          .
          .
      STOP
      END
The linear algebra setup routine D02NTF and one of the integrator setup routines, D02NVF or D02NWF, must be called prior to the call of D02NCF. The integrator diagnostic routine D02NYF may be called after the call to D02NCF. There is also a routine, D02NZF, designed to permit you to change step size on a continuation call to D02NCF without restarting the integration process.

4 References

See the D02M–N Sub-chapter Introduction.

5 Arguments

1:   NEQ – INTEGERInput
On entry: the number of differential equations to be solved.
Constraint: NEQ≥1.
2:   LDYSAV – INTEGERInput
On entry: a bound on the maximum number of differential equations to be solved during the integration.
Constraint: LDYSAV≥NEQ.
3:   T – REAL (KIND=nag_wp)Input/Output
On entry: t, the value of the independent variable. The input value of T is used only on the first call as the initial point of the integration.
On exit: the value at which the computed solution y is returned (usually at TOUT).
4:   TOUT – REAL (KIND=nag_wp)Input
On entry: the next value of t at which a computed solution is desired. For the initial t, the input value of TOUT is used to determine the direction of integration. Integration is permitted in either direction (see also ITASK).
Constraint: TOUT≠T.
5:   Y NEQ – REAL (KIND=nag_wp) arrayInput/Output
On entry: the values of the dependent variables (solution). On the first call the first NEQ elements of Y must contain the vector of initial values.
On exit: the computed solution vector, evaluated at T (usually T=TOUT).
6:   YDOT NEQ – REAL (KIND=nag_wp) arrayOutput
On exit: the time derivatives y′ of the vector y at the last integration point.
7:   RWORK 50+4×NEQ – REAL (KIND=nag_wp) arrayCommunication Array
8:   RTOL* – REAL (KIND=nag_wp) arrayInput
Note: the dimension of the array RTOL must be at least 1 if ITOL=1 or 2, and at least NEQ otherwise.
On entry: the relative local error tolerance.
Constraint: RTOL i≥0.0 for all relevant i (see ITOL).
9:   ATOL* – REAL (KIND=nag_wp) arrayInput
Note: the dimension of the array ATOL must be at least 1 if ITOL=1 or 3, and at least NEQ otherwise.
On entry: the absolute local error tolerance.
Constraint: ATOL i≥0.0 for all relevant i (see ITOL).
10:   ITOL – INTEGERInput
On entry: a value to indicate the form of the local error test. ITOL indicates to D02NCF whether to interpret either or both of RTOL or ATOL as a vector or a scalar. The error test to be satisfied is ei/wi<1.0, where wi is defined as follows:
ITOL | RTOL | ATOL | wi
1 | scalar | scalar | RTOL 1×yi+ATOL 1
2 | scalar | vector | RTOL 1×yi+ATOL i
3 | vector | scalar | RTOL i×yi+ATOL 1
4 | vector | vector | RTOL i×yi+ATOL i
ei is an estimate of the local error in yi, computed internally, and the choice of norm to be used is defined by a previous call to an integrator setup routine.
Constraint: ITOL=1, 2, 3 or 4.
11:   INFORM 23 – INTEGER arrayCommunication Array
12:   FCN – SUBROUTINE, supplied by the user.External Procedure
FCN must evaluate the derivative vector for the explicit ordinary differential equation system, defined by y′=g t,y.
The specification of FCN is:
SUBROUTINE FCN ( NEQ, T, Y, F, IRES)
INTEGER | NEQ, IRES
REAL (KIND=nag_wp) | T, Y(NEQ), F(NEQ)
1:   NEQ – INTEGERInput
On entry: the number of differential equations being solved.
2:   T – REAL (KIND=nag_wp)Input
On entry: t, the current value of the independent variable.
3:   Y NEQ – REAL (KIND=nag_wp) arrayInput
On entry: the value of yi, for i=1,2,…,NEQ.
4:   F NEQ – REAL (KIND=nag_wp) arrayOutput
On exit: the value yi′, given by yi′=gi t,y, for i=1,2,…,NEQ.
5:   IRES – INTEGERInput/Output
On entry: IRES=1.
On exit: you may set IRES as follows to indicate certain conditions in FCN to the integrator:
IRES=1
Indicates a normal return from FCN, that is IRES has not been altered by you and integration continues.
IRES=2
Indicates to the integrator that control should be passed back immediately to the calling (sub)program with the error indicator set to IFAIL=11.
IRES=3
Indicates to the integrator that an error condition has occurred in the solution vector, its time derivative or in the value of t. The integrator will use a smaller time step to try to avoid this condition. If this is not possible the integrator returns to the calling (sub)program with the error indicator set to IFAIL=7.
IRES=4
Indicates to the integrator to stop its current operation and to enter MONITR immediately with argument IMON=-2.
FCN must either be a module subprogram USEd by, or declared as EXTERNAL in, the (sub)program from which D02NCF is called. Arguments denoted as Input must not be changed by this procedure.
13:   YSAV LDYSAVSDYSAV – REAL (KIND=nag_wp) arrayCommunication Array
14:   SDYSAV – INTEGERInput
On entry: the second dimension of the array YSAV as declared in the (sub)program from which D02NCF is called. An appropriate value for SDYSAV is described in the specification of the integrator setup routines D02NVF and D02NWF. This value must be the same as that supplied to the integrator setup routine.
15:   JAC – SUBROUTINE, supplied by the NAG Library or the user.External Procedure
JAC must evaluate the Jacobian of the system. If this option is not required, the actual argument for JAC must be the dummy routine D02NCZ. (D02NCZ is included in the NAG Library.) You must indicate to the integrator whether this option is to be used by setting the argument JCEVAL appropriately in a call to the banded linear algebra setup routine D02NTF.
First we must define the system of nonlinear equations which is solved internally by the integrator. The time derivative, y′, generated internally, has the form
y′ = y-z / hd ,
where h is the current step size and d is an argument that depends on the integration method in use. The vector y is the current solution and the vector z depends on information from previous time steps. This means that d d y′ ​ ​ = hd d dy ​ ​ . The system of nonlinear equations that is solved has the form
y′ - g t,y = 0
but it is solved in the form
r t,y = 0 ,
where r is the function defined by
r t,y =hd y-z / hd - g t,y .
It is the Jacobian matrix ∂r ∂y that you must supply in JAC as follows:
∂ri ∂yj =1-hd ∂gi ∂yj , if ​i=j, ∂ri ∂yj = -hd ∂gi ∂yj , otherwise.
The specification of JAC is:
SUBROUTINE JAC ( NEQ, T, Y, H, D, ML, MU, P)
INTEGER | NEQ, ML, MU
REAL (KIND=nag_wp) | T, Y(NEQ), H, D, P(ML+MU+1,NEQ)
1:   NEQ – INTEGERInput
On entry: the number of differential equations being solved.
2:   T – REAL (KIND=nag_wp)Input
On entry: t, the current value of the independent variable.
3:   Y NEQ – REAL (KIND=nag_wp) arrayInput
On entry: yi, for i=1,2,…,NEQ, the current solution component.
4:   H – REAL (KIND=nag_wp)Input
On entry: the current step size.
5:   D – REAL (KIND=nag_wp)Input
On entry: the argument d which depends on the integration method.
6:   ML – INTEGERInput
7:   MU – INTEGERInput
On entry: the number of subdiagonals and superdiagonals respectively in the band.
8:   P ML+MU+1 NEQ – REAL (KIND=nag_wp) arrayInput/Output
On entry: is set to zero.
On exit: elements of the Jacobian matrix ∂r ∂y stored as specified by the following pseudocode:
 DO 20 I = 1, NEQ
 J1 = MAX(I-ML,1)
 J2 = MIN(I+MU,NEQ)
 DO 10 J = J1, J2
 K = MIN(ML+1-I,0)+J
 P(K,I) = δR/δY(I,J)
 10 CONTINUE
 20 CONTINUE
See also F07BDF (DGBTRF).
Only nonzero elements of this array need be set, since it is preset to zero before the call to JAC.
JAC must either be a module subprogram USEd by, or declared as EXTERNAL in, the (sub)program from which D02NCF is called. Arguments denoted as Input must not be changed by this procedure.
16:   WKJAC NWKJAC – REAL (KIND=nag_wp) arrayCommunication Array
17:   NWKJAC – INTEGERInput
On entry: the dimension of the array WKJAC as declared in the (sub)program from which D02NCF is called. This value must be the same as that supplied to the linear algebra setup routine D02NTF.
Constraint: NWKJAC≥2 mL+mU+1×NEQ, where mL and mU are the number of subdiagonals and superdiagonals respectively in the band, defined by a call to D02NTF.
18:   JACPVT NJCPVT – INTEGER arrayCommunication Array
19:   NJCPVT – INTEGERInput
On entry: the dimension of the array JACPVT as declared in the (sub)program from which D02NCF is called. This value must be the same as that supplied to the linear algebra setup routine D02NTF.
Constraint: NJCPVT≥LDYSAV.
20:   MONITR – SUBROUTINE, supplied by the NAG Library or the user.External Procedure
MONITR performs tasks requested by you. If this option is not required, then the actual argument for MONITR must be the dummy routine D02NBY. (D02NBY is included in the NAG Library.)
The specification of MONITR is:
SUBROUTINE MONITR ( NEQ, LDYSAV, T, HLAST, HNEXT, Y, YDOT, YSAV, R, ACOR, IMON, INLN, HMIN, HMAX, NQU)
INTEGER | NEQ, LDYSAV, IMON, INLN, NQU
REAL (KIND=nag_wp) | T, HLAST, HNEXT, Y(NEQ), YDOT(NEQ), YSAV(LDYSAV,sdysav), R(NEQ), ACOR(NEQ,2), HMIN, HMAX
where sdysav is the numerical value of SDYSAV in the call of D02NCF.
1:   NEQ – INTEGERInput
On entry: the number of differential equations being solved.
2:   LDYSAV – INTEGERInput
On entry: an upper bound on the number of differential equations to be solved.
3:   T – REAL (KIND=nag_wp)Input
On entry: the current value of the independent variable.
4:   HLAST – REAL (KIND=nag_wp)Input
On entry: the last step size successfully used by the integrator.
5:   HNEXT – REAL (KIND=nag_wp)Input/Output
On entry: the step size that the integrator proposes to take on the next step.
On exit: the next step size to be used. If this is different from the input value, then IMON must be set to 4.
6:   Y NEQ – REAL (KIND=nag_wp) arrayInput/Output
On entry: y, the values of the dependent variables evaluated at t.
On exit: these values must not be changed unless IMON is set to 2.
7:   YDOT NEQ – REAL (KIND=nag_wp) arrayInput
On entry: the time derivatives y′ of the vector y.
8:   YSAV LDYSAVsdysav – REAL (KIND=nag_wp) arrayInput
On entry: workspace to enable you to carry out interpolation using either of the routines D02XJF or D02XKF.
9:   R NEQ – REAL (KIND=nag_wp) arrayInput
On entry: if IMON=0 and INLN=3, the first NEQ elements contain the residual vector, y′-g t,y.
10:   ACOR NEQ 2 – REAL (KIND=nag_wp) arrayInput
On entry: with IMON=1, ACOR i 1 contains the weight used for the ith equation when the norm is evaluated, and ACOR i 2 contains the estimated local error for the ith equation. The scaled local error at the end of a timestep may be obtained by calling the real function D02ZAF as follows:
 IFAIL = 1
 ERRLOC = D02ZAF(NEQ, ACOR(1,2), ACOR(1,1), IFAIL)
 ! CHECK IFAIL BEFORE PROCEEDING
11:   IMON – INTEGERInput/Output
On entry: a flag indicating under what circumstances MONITR was called:
IMON=-2
Entry from the integrator after IRES=4 (set in FCN) caused an early termination (this facility could be used to locate discontinuities).
IMON=-1
The current step failed repeatedly.
IMON=0
Entry after a call to the internal nonlinear equation solver (see INLN).
IMON=1
The current step was successful.
On exit: may be reset to determine subsequent action in D02NCF.
IMON=-2
Integration is to be halted. A return will be made from the integrator to the calling (sub)program with IFAIL=12.
IMON=-1
Allow the integrator to continue with its own internal strategy. The integrator will try up to three restarts unless IMON is set ≠-1 on exit.
IMON=0
Return to the internal nonlinear equation solver, where the action taken is determined by the value of INLN (see INLN).
IMON=1
Normal exit to the integrator to continue integration.
IMON=2
Restart the integration at the current time point. The integrator will restart from order 1 when this option is used. The solution Y, provided by MONITR, will be used for the initial conditions.
IMON=3
Try to continue with the same step size and order as was to be used before the call to MONITR. HMIN and HMAX may be altered if desired.
IMON=4
Continue the integration but using a new value of HNEXT and possibly new values of HMIN and HMAX.
12:   INLN – INTEGEROutput
On exit: the action to be taken by the internal nonlinear equation solver when MONITR is exited with IMON=0. By setting INLN=3 and returning to the integrator, the residual vector is evaluated and placed in the array R, and then MONITR is called again. At present this is the only option available: INLN must not be set to any other value.
13:   HMIN – REAL (KIND=nag_wp)Input/Output
On entry: the minimum step size to be taken on the next step.
On exit: the minimum step size to be used. If this is different from the input value, then IMON must be set to 3 or 4.
14:   HMAX – REAL (KIND=nag_wp)Input/Output
On entry: the maximum step size to be taken on the next step.
On exit: the maximum step size to be used. If this is different from the input value, then IMON must be set to 3 or 4. If HMAX is set to zero, no limit is assumed.
15:   NQU – INTEGERInput
On entry: the order of the integrator used on the last step. This is supplied to enable you to carry out interpolation using either of the routines D02XJF or D02XKF.
MONITR must either be a module subprogram USEd by, or declared as EXTERNAL in, the (sub)program from which D02NCF is called. Arguments denoted as Input must not be changed by this procedure.
21:   ITASK – INTEGERInput
On entry: the task to be performed by the integrator.
ITASK=1
Normal computation of output values of y t at t=TOUT (by overshooting and interpolating).
ITASK=2
Take one step only and return.
ITASK=3
Stop at the first internal integration point at or beyond t=TOUT and return.
ITASK=4
Normal computation of output values of y t at t=TOUT but without overshooting t=TCRIT. TCRIT must be specified as an option in one of the integrator setup routines before the first call to the integrator, or specified in the optional input routine before a continuation call. TCRIT may be equal to or beyond TOUT, but not before it, in the direction of integration.
ITASK=5
Take one step only and return, without passing TCRIT. TCRIT must be specified as under ITASK=4.
Constraint: ITASK=1, 2, 3, 4 or 5.
22:   ITRACE – INTEGERInput
On entry: the level of output that is printed by the integrator. ITRACE may take the value -1, 0, 1, 2 or 3.
ITRACE<-1
-1 is assumed and similarly if ITRACE>3, then 3 is assumed.
ITRACE=-1
No output is generated.
ITRACE=0
Only warning messages are printed on the current error message unit (see X04AAF).
ITRACE>0
Warning messages are printed as above, and on the current advisory message unit (see X04ABF) output is generated which details Jacobian entries, the nonlinear iteration and the time integration. The advisory messages are given in greater detail the larger the value of ITRACE.
23:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, because for this routine the values of the output arguments may be useful even if IFAIL≠0 on exit, the recommended value is -1. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
An illegal input was detected on entry, or after an internal call to MONITR. If ITRACE>-1, then the form of the error will be detailed on the current error message unit (see X04AAF).
IFAIL=2
The maximum number of steps specified has been taken (see the description of optional inputs in the integrator setup routines and the optional input continuation routine, D02NZF).
IFAIL=3
With the given values of RTOL and ATOL no further progress can be made across the integration range from the current point T. The components Y 1,Y 2,…,Y NEQ contain the computed values of the solution at the current point T.
IFAIL=4
There were repeated error test failures on an attempted step, before completing the requested task, but the integration was successful as far as T. The problem may have a singularity, or the local error requirements may be inappropriate.
IFAIL=5
There were repeated convergence test failures on an attempted step, before completing the requested task, but the integration was successful as far as T. This may be caused by an inaccurate Jacobian matrix or one which is incorrectly computed.
IFAIL=6
Some error weight wi became zero during the integration (see the description of ITOL). Pure relative error control (ATOL i=0.0) was requested on a variable (the ith) which has now vanished. The integration was successful as far as T.
IFAIL=7
FCN set its error flag (IRES=3) continually despite repeated attempts by the integrator to avoid this.
IFAIL=8
Not used for this integrator.
IFAIL=9
A singular Jacobian ∂r ∂y has been encountered. This error exit is unlikely to be taken when solving explicit ordinary differential equations. You should check the problem formulation and Jacobian calculation.
IFAIL=10
An error occurred during Jacobian formulation or back-substitution (a more detailed error description may be directed to the current error message unit, see X04AAF).
IFAIL=11
FCN signalled the integrator to halt the integration and return (IRES=2). Integration was successful as far as T.
IFAIL=12
MONITR set IMON=-2 and so forced a return but the integration was successful as far as T.
IFAIL=13
The requested task has been completed, but it is estimated that a small change in RTOL and ATOL is unlikely to produce any change in the computed solution. (Only applies when you are not operating in one step mode, that is when ITASK≠2 or 5.)
IFAIL=14
The values of RTOL and ATOL are so small that D02NCF is unable to start the integration.
IFAIL=15
The linear algebra setup routine D02NTF was not called prior to calling D02NCF.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

The accuracy of the numerical solution may be controlled by a careful choice of the arguments RTOL and ATOL, and to a much lesser extent by the choice of norm. You are advised to use scalar error control unless the components of the solution are expected to be poorly scaled. For the type of decaying solution typical of many stiff problems, relative error control with a small absolute error threshold will be most appropriate (that is, you are advised to choose ITOL=1 with ATOL 1 small but positive).

8 Parallelism and Performance

D02NCF is not thread safe and should not be called from a multithreaded user program. Please see Section 3.12.1 in How to Use the NAG Library and its Documentation for more information on thread safety.
D02NCF is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
D02NCF makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The cost of computing a solution depends critically on the size of the differential system and to a lesser extent on the degree of stiffness of the problem. For D02NCF the cost is proportional to NEQ× ML+MU+1 2 though for problems which are only mildly nonlinear the cost may be dominated by factors proportional to NEQ×ML+MU+1 except for very large problems.
In general, you are advised to choose the Backward Differentiation Formula option (setup routine D02NVF) but if efficiency is of great importance and especially if it is suspected that ∂g ∂y has complex eigenvalues near the imaginary axis for some part of the integration, you should try the BLEND option (setup routine D02NWF).

10 Example

This example solves the well-known stiff Robertson problem
a′ = -0.04 a + 1.0 E 4 bc b′ = 0.04 a - 1.0 E 4 bc - 3.0 E 7⁢b 2 c′ = 3.0 E 7⁢b 2
over the range 0,10 with initial conditions a=1.0 and b=c=0.0 using scalar relative error control and vector absolute error control ITOL=2. The solution is obtained at TOUT=5.0 and TOUT=10.0 by overshooting and internal C 0 interpolation ITASK=1. D02NBY is used for MONITR, the BLEND integrator (setup routine D02NWF) is used and the option of an analytical Jacobian is chosen.

10.1 Program Text

Program Text (d02ncfe.f90)

10.2 Program Data

Program Data (d02ncfe.d)

10.3 Program Results

Program Results (d02ncfe.r)

GnuplotProduced by GNUPLOT 4.6 patchlevel 3 0 0.2 0.4 0.6 0.8 1 0 1 2 3 4 5 6 7 8 9 0 2e−05 4e−05 6e−05 8e−05 0.0001 Solution (a,c) Solution (b) x Example Program Stiff Explicit ODE, Full Jacobian Stiff Robertson Problem (BLEND integrator) a b c gnuplot_plot_1 gnuplot_plot_2 gnuplot_plot_3
D02 Chapter Contents
D02 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


D02NDF : NAG Library, Mark 26

D02 Chapter Contents
D02 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

D02NDF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

D02NDF is a direct communication routine for integrating stiff systems of explicit ordinary differential equations when the Jacobian is a sparse matrix.

2 Specification

SUBROUTINE D02NDF ( NEQ, LDYSAV, T, TOUT, Y, YDOT, RWORK, RTOL, ATOL, ITOL, INFORM, FCN, YSAV, SDYSAV, JAC, WKJAC, NWKJAC, JACPVT, NJCPVT, MONITR, ITASK, ITRACE, IFAIL)
INTEGER | NEQ, LDYSAV, ITOL, INFORM(23), SDYSAV, NWKJAC, JACPVT(NJCPVT), NJCPVT, ITASK, ITRACE, IFAIL
REAL (KIND=nag_wp) | T, TOUT, Y(NEQ), YDOT(NEQ), RWORK(50+4*NEQ), RTOL(*), ATOL(*), YSAV(LDYSAV,SDYSAV), WKJAC(NWKJAC)
EXTERNAL | FCN, JAC, MONITR

3 Description

D02NDF is a general purpose routine for integrating the initial value problem for a stiff system of explicit ordinary differential equations,
y′ = g t,y .
It is designed specifically for the case where the Jacobian ∂g ∂y is a sparse matrix.
Both interval and step oriented modes of operation are available and also modes designed to permit intermediate output within an interval oriented mode.
An outline of a typical calling program for D02NDF is given below. It calls the sparse matrix linear algebra setup routine D02NUF, the Backward Differentiation Formula (BDF) integrator setup routine D02NVF, its diagnostic counterpart D02NYF, and the sparse linear algebra diagnostic routine D02NXF.
!     Declarations

      EXTERNAL FCN, JAC, MONITR
          .
          .
          .
      IFAIL = 0
      CALL D02NVF(...,IFAIL)
      CALL D02NUF(NEQ, NEQMAX, JCEVAL, NWKJAC, IA, NIA, JA, NJA, &
                  JACPVT, NJCPVT, SENS, U, ETA, LBLOCK, ISPLIT,  &
                  RWORK,IFAIL)
      IFAIL = -1
      CALL D02NDF(NEQ, NEQMAX, T, TOUT, Y, YDOT, RWORK, RTOL,    &
                  ATOL, ITOL, INFORM, FCN, YSAVE, NY2DIM, JAC,   &
                  WKJAC,NWKJAC, JACPVT, NJCPVT, MONITR, ITASK,   &
                  ITRACE, IFAIL)
      IF(IFAIL.EQ.1 .OR. IFAIL.GE.14) STOP
      IFAIL = 0
      CALL D02NXF(...)
      CALL D02NYF(...)
          .
          .
          .
      STOP
      END
The linear algebra setup routine D02NUF and one of the integrator setup routines, D02NVF or D02NWF, must be called prior to the call of D02NDF. Either or both of the integrator diagnostic routine D02NYF, or the sparse matrix linear algebra diagnostic routine D02NXF, may be called after the call to D02NDF. There is also a routine, D02NZF, designed to permit you to change step size on a continuation call to D02NDF without restarting the integration process.

4 References

See the D02M–N Sub-chapter Introduction.

5 Arguments

1:   NEQ – INTEGERInput
On entry: the number of differential equations to be solved.
Constraint: NEQ≥1.
2:   LDYSAV – INTEGERInput
On entry: a bound on the maximum number of differential equations to be solved during the integration.
Constraint: LDYSAV≥NEQ.
3:   T – REAL (KIND=nag_wp)Input/Output
On entry: t, the value of the independent variable. The input value of T is used only on the first call as the initial point of the integration.
On exit: the value at which the computed solution y is returned (usually at TOUT).
4:   TOUT – REAL (KIND=nag_wp)Input
On entry: the next value of t at which a computed solution is desired. For the initial t, the input value of TOUT is used to determine the direction of integration. Integration is permitted in either direction (see also ITASK).
Constraint: TOUT≠T.
5:   Y NEQ – REAL (KIND=nag_wp) arrayInput/Output
On entry: the values of the dependent variables (solution). On the first call the first NEQ elements of Y must contain the vector of initial values.
On exit: the computed solution vector, evaluated at T (usually T=TOUT).
6:   YDOT NEQ – REAL (KIND=nag_wp) arrayOutput
On exit: the time derivatives y′ of the vector y at the last integration point.
7:   RWORK 50+4×NEQ – REAL (KIND=nag_wp) arrayCommunication Array
8:   RTOL* – REAL (KIND=nag_wp) arrayInput
Note: the dimension of the array RTOL must be at least 1 if ITOL=1 or 2, and at least NEQ otherwise.
On entry: the relative local error tolerance.
Constraint: RTOL i≥0.0 for all relevant i (see ITOL).
9:   ATOL* – REAL (KIND=nag_wp) arrayInput
Note: the dimension of the array ATOL must be at least 1 if ITOL=1 or 3, and at least NEQ otherwise.
On entry: the absolute local error tolerance.
Constraint: ATOL i≥0.0 for all relevant i (see ITOL).
10:   ITOL – INTEGERInput
On entry: a value to indicate the form of the local error test. ITOL indicates to D02NDF whether to interpret either or both of RTOL or ATOL as a vector or a scalar. The error test to be satisfied is ei/wi<1.0, where wi is defined as follows:
ITOL | RTOL | ATOL | wi
1 | scalar | scalar | RTOL 1×yi+ATOL 1
2 | scalar | vector | RTOL 1×yi+ATOL i
3 | vector | scalar | RTOL i×yi+ATOL 1
4 | vector | vector | RTOL i×yi+ATOL i
ei is an estimate of the local error in yi, computed internally, and the choice of norm to be used is defined by a previous call to an integrator setup routine.
Constraint: ITOL=1, 2, 3 or 4.
11:   INFORM 23 – INTEGER arrayCommunication Array
12:   FCN – SUBROUTINE, supplied by the user.External Procedure
FCN must evaluate the derivative vector for the explicit ordinary differential equation system, defined by y′=g t,y.
The specification of FCN is:
SUBROUTINE FCN ( NEQ, T, Y, F, IRES)
INTEGER | NEQ, IRES
REAL (KIND=nag_wp) | T, Y(NEQ), F(NEQ)
1:   NEQ – INTEGERInput
On entry: the number of differential equations being solved.
2:   T – REAL (KIND=nag_wp)Input
On entry: t, the current value of the independent variable.
3:   Y NEQ – REAL (KIND=nag_wp) arrayInput
On entry: the value of yi, for i=1,2,…,NEQ.
4:   F NEQ – REAL (KIND=nag_wp) arrayOutput
On exit: the value yi′, given by yi′=gi t,y, for i=1,2,…,NEQ.
5:   IRES – INTEGERInput/Output
On entry: IRES=1.
On exit: you may set IRES as follows to indicate certain conditions in FCN to the integrator:
IRES=1
Indicates a normal return from FCN, that is IRES has not been altered by you and integration continues.
IRES=2
Indicates to the integrator that control should be passed back immediately to the calling (sub)program with the error indicator set to IFAIL=11.
IRES=3
Indicates to the integrator that an error condition has occurred in the solution vector, its time derivative or in the value of t. The integrator will use a smaller time step to try to avoid this condition. If this is not possible the integrator returns to the calling (sub)program with the error indicator set to IFAIL=7.
IRES=4
Indicates to the integrator to stop its current operation and to enter MONITR immediately with argument IMON=-2.
FCN must either be a module subprogram USEd by, or declared as EXTERNAL in, the (sub)program from which D02NDF is called. Arguments denoted as Input must not be changed by this procedure.
13:   YSAV LDYSAVSDYSAV – REAL (KIND=nag_wp) arrayCommunication Array
14:   SDYSAV – INTEGERInput
On entry: the second dimension of the array YSAV as declared in the (sub)program from which D02NDF is called. An appropriate value for SDYSAV is described in the specification of the integrator setup routines D02NVF and D02NWF. This value must be the same as that supplied to the integrator setup routine.
15:   JAC – SUBROUTINE, supplied by the NAG Library or the user.External Procedure
JAC must evaluate the Jacobian of the system. If this option is not required, the actual argument for JAC must be the dummy routine D02NDZ. (D02NDZ is included in the NAG Library.) You must indicate to the integrator whether this option is to be used by setting the argument JCEVAL appropriately in a call to the sparse linear algebra setup routine D02NUF.
First we must define the system of nonlinear equations which is solved internally by the integrator. The time derivative, y′, generated internally, has the form
y′ = y-z / hd ,
where h is the current step size and d is an argument that depends on the integration method in use. The vector y is the current solution and the vector z depends on information from previous time steps. This means that d d y′ ​ ​ = hd d dy ​ ​ . The system of nonlinear equations that is solved has the form
y′ - g t,y = 0
but it is solved in the form
r t,y = 0 ,
where r is the function defined by
r t,y =hd y-z / hd - g t,y .
It is the Jacobian matrix ∂r ∂y that you must supply in JAC as follows:
∂ri ∂yj =1-hd ∂gi ∂yj , if ​i=j, ∂ri ∂yj = -hd ∂gi ∂yj , otherwise.
The specification of JAC is:
SUBROUTINE JAC ( NEQ, T, Y, H, D, J, PDJ)
INTEGER | NEQ, J
REAL (KIND=nag_wp) | T, Y(NEQ), H, D, PDJ(NEQ)
1:   NEQ – INTEGERInput
On entry: the number of differential equations being solved.
2:   T – REAL (KIND=nag_wp)Input
On entry: t, the current value of the independent variable.
3:   Y NEQ – REAL (KIND=nag_wp) arrayInput
On entry: yi, for i=1,2,…,NEQ, the current solution component.
4:   H – REAL (KIND=nag_wp)Input
On entry: the current step size.
5:   D – REAL (KIND=nag_wp)Input
On entry: the argument d which depends on the integration method.
6:   J – INTEGERInput
On entry: the column of the Jacobian that JAC must return in the array PDJ.
7:   PDJ NEQ – REAL (KIND=nag_wp) arrayInput/Output
On entry: is set to zero.
On exit: PDJ i should be set to the i,jth element of the Jacobian, where j is given by J. Only nonzero elements of this array need be set, since it is preset to zero before the call to JAC.
JAC must either be a module subprogram USEd by, or declared as EXTERNAL in, the (sub)program from which D02NDF is called. Arguments denoted as Input must not be changed by this procedure.
16:   WKJAC NWKJAC – REAL (KIND=nag_wp) arrayCommunication Array
17:   NWKJAC – INTEGERInput
On entry: the dimension of the array WKJAC as declared in the (sub)program from which D02NDF is called. The actual size depends on whether the sparsity structure is supplied or whether it is to be estimated. An appropriate value for NWKJAC is described in the specification of the linear algebra setup routine D02NUF. This value must be the same as that supplied to D02NUF.
18:   JACPVT NJCPVT – INTEGER arrayCommunication Array
19:   NJCPVT – INTEGERInput
On entry: the dimension of the array JACPVT as declared in the (sub)program from which D02NDF is called. The actual size depends on whether the sparsity structure is supplied or whether it is to be estimated. An appropriate value for NJCPVT is described in the specification of the linear algebra setup routine D02NUF. This value must be the same as that supplied to D02NUF.
20:   MONITR – SUBROUTINE, supplied by the NAG Library or the user.External Procedure
MONITR performs tasks requested by you. If this option is not required, then the actual argument for MONITR must be the dummy routine D02NBY. (D02NBY is included in the NAG Library.)
The specification of MONITR is:
SUBROUTINE MONITR ( NEQ, LDYSAV, T, HLAST, HNEXT, Y, YDOT, YSAV, R, ACOR, IMON, INLN, HMIN, HMAX, NQU)
INTEGER | NEQ, LDYSAV, IMON, INLN, NQU
REAL (KIND=nag_wp) | T, HLAST, HNEXT, Y(NEQ), YDOT(NEQ), YSAV(LDYSAV,sdysav), R(NEQ), ACOR(NEQ,2), HMIN, HMAX
where sdysav is the numerical value of SDYSAV in the call of D02NDF.
1:   NEQ – INTEGERInput
On entry: the number of differential equations being solved.
2:   LDYSAV – INTEGERInput
On entry: an upper bound on the number of differential equations to be solved.
3:   T – REAL (KIND=nag_wp)Input
On entry: the current value of the independent variable.
4:   HLAST – REAL (KIND=nag_wp)Input
On entry: the last step size successfully used by the integrator.
5:   HNEXT – REAL (KIND=nag_wp)Input/Output
On entry: the step size that the integrator proposes to take on the next step.
On exit: the next step size to be used. If this is different from the input value, then IMON must be set to 4.
6:   Y NEQ – REAL (KIND=nag_wp) arrayInput/Output
On entry: y, the values of the dependent variables evaluated at t.
On exit: these values must not be changed unless IMON is set to 2.
7:   YDOT NEQ – REAL (KIND=nag_wp) arrayInput
On entry: the time derivatives y′ of the vector y.
8:   YSAV LDYSAVsdysav – REAL (KIND=nag_wp) arrayInput
On entry: workspace to enable you to carry out interpolation using either of the routines D02XJF or D02XKF.
9:   R NEQ – REAL (KIND=nag_wp) arrayInput
On entry: if IMON=0 and INLN=3, the first NEQ elements contain the residual vector, y′-g t,y.
10:   ACOR NEQ 2 – REAL (KIND=nag_wp) arrayInput
On entry: with IMON=1, ACOR i 1 contains the weight used for the ith equation when the norm is evaluated, and ACOR i 2 contains the estimated local error for the ith equation. The scaled local error at the end of a timestep may be obtained by calling the real function D02ZAF as follows:
 IFAIL = 1
 ERRLOC = D02ZAF(NEQ, ACOR(1,2), ACOR(1,1), IFAIL)
 ! CHECK IFAIL BEFORE PROCEEDING
11:   IMON – INTEGERInput/Output
On entry: a flag indicating under what circumstances MONITR was called:
IMON=-2
Entry from the integrator after IRES=4 (set in FCN) caused an early termination (this facility could be used to locate discontinuities).
IMON=-1
The current step failed repeatedly.
IMON=0
Entry after a call to the internal nonlinear equation solver (see INLN).
IMON=1
The current step was successful.
On exit: may be reset to determine subsequent action in D02NDF.
IMON=-2
Integration is to be halted. A return will be made from the integrator to the calling (sub)program with IFAIL=12.
IMON=-1
Allow the integrator to continue with its own internal strategy. The integrator will try up to three restarts unless IMON is set ≠-1 on exit.
IMON=0
Return to the internal nonlinear equation solver, where the action taken is determined by the value of INLN (see INLN).
IMON=1
Normal exit to the integrator to continue integration.
IMON=2
Restart the integration at the current time point. The integrator will restart from order 1 when this option is used. The solution Y, provided by MONITR, will be used for the initial conditions.
IMON=3
Try to continue with the same step size and order as was to be used before the call to MONITR. HMIN and HMAX may be altered if desired.
IMON=4
Continue the integration but using a new value of HNEXT and possibly new values of HMIN and HMAX.
12:   INLN – INTEGEROutput
On exit: the action to be taken by the internal nonlinear equation solver when MONITR is exited with IMON=0. By setting INLN=3 and returning to the integrator, the residual vector is evaluated and placed in the array R, and then MONITR is called again. At present this is the only option available: INLN must not be set to any other value.
13:   HMIN – REAL (KIND=nag_wp)Input/Output
On entry: the minimum step size to be taken on the next step.
On exit: the minimum step size to be used. If this is different from the input value, then IMON must be set to 3 or 4.
14:   HMAX – REAL (KIND=nag_wp)Input/Output
On entry: the maximum step size to be taken on the next step.
On exit: the maximum step size to be used. If this is different from the input value, then IMON must be set to 3 or 4. If HMAX is set to zero, no limit is assumed.
15:   NQU – INTEGERInput
On entry: the order of the integrator used on the last step. This is supplied to enable you to carry out interpolation using either of the routines D02XJF or D02XKF.
MONITR must either be a module subprogram USEd by, or declared as EXTERNAL in, the (sub)program from which D02NDF is called. Arguments denoted as Input must not be changed by this procedure.
21:   ITASK – INTEGERInput
On entry: the task to be performed by the integrator.
ITASK=1
Normal computation of output values of y t at t=TOUT (by overshooting and interpolating).
ITASK=2
Take one step only and return.
ITASK=3
Stop at the first internal integration point at or beyond t=TOUT and return.
ITASK=4
Normal computation of output values of y t at t=TOUT but without overshooting t=TCRIT (e.g., see D02MVF). TCRIT must be specified as an option in one of the integrator setup routines before the first call to the integrator, or specified in the optional input routine before a continuation call. TCRIT may be equal to or beyond TOUT, but not before it, in the direction of integration.
ITASK=5
Take one step only and return, without passing TCRIT (e.g., see D02MVF). TCRIT must be specified as under ITASK=4.
Constraint: ITASK=1, 2, 3, 4 or 5.
22:   ITRACE – INTEGERInput
On entry: the level of output that is printed by the integrator. ITRACE may take the value -1, 0, 1, 2 or 3.
ITRACE<-1
-1 is assumed and similarly if ITRACE>3, then 3 is assumed.
ITRACE=-1
No output is generated.
ITRACE=0
Only warning messages are printed on the current error message unit (see X04AAF).
ITRACE>0
Warning messages are printed as above, and on the current advisory message unit (see X04ABF) output is generated which details Jacobian entries, the nonlinear iteration and the time integration. The advisory messages are given in greater detail the larger the value of ITRACE.
23:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, because for this routine the values of the output arguments may be useful even if IFAIL≠0 on exit, the recommended value is -1. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
An illegal input was detected on entry, or after an internal call to MONITR. If ITRACE>-1, then the form of the error will be detailed on the current error message unit (see X04AAF).
IFAIL=2
The maximum number of steps specified has been taken (see the description of optional inputs in the integrator setup routines and the optional input continuation routine, D02NZF).
IFAIL=3
With the given values of RTOL and ATOL no further progress can be made across the integration range from the current point T. The components Y 1,Y 2,…,Y NEQ contain the computed values of the solution at the current point T.
IFAIL=4
There were repeated error test failures on an attempted step, before completing the requested task, but the integration was successful as far as T. The problem may have a singularity, or the local error requirements may be inappropriate.
IFAIL=5
There were repeated convergence test failures on an attempted step, before completing the requested task, but the integration was successful as far as T. This may be caused by an inaccurate Jacobian matrix or one which is incorrectly computed.
IFAIL=6
Some error weight wi became zero during the integration (see the description of ITOL). Pure relative error control (ATOL i=0.0) was requested on a variable (the ith) which has now vanished. The integration was successful as far as T.
IFAIL=7
FCN set its error flag (IRES=3) continually despite repeated attempts by the integrator to avoid this.
IFAIL=8
Not used for the integrator.
IFAIL=9
A singular Jacobian ∂r ∂y has been encountered. This error exit is unlikely to be taken when solving explicit ordinary differential equations. You should check the problem formulation and Jacobian calculation.
IFAIL=10
An error occurred during Jacobian formulation or back-substitution (a more detailed error description may be directed to the current error message unit, see X04AAF).
IFAIL=11
FCN signalled the integrator to halt the integration and return (IRES=2). Integration was successful as far as T.
IFAIL=12
MONITR set IMON=-2 and so forced a return but the integration was successful as far as T.
IFAIL=13
The requested task has been completed, but it is estimated that a small change in RTOL and ATOL is unlikely to produce any change in the computed solution. (Only applies when you are not operating in one step mode, that is when ITASK≠2 or 5.)
IFAIL=14
The values of RTOL and ATOL are so small that D02NDF is unable to start the integration.
IFAIL=15
The linear algebra setup routine D02NUF was not called prior to calling D02NDF.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

The accuracy of the numerical solution may be controlled by a careful choice of the arguments RTOL and ATOL, and to a much lesser extent by the choice of norm. You are advised to use scalar error control unless the components of the solution are expected to be poorly scaled. For the type of decaying solution typical of many stiff problems, relative error control with a small absolute error threshold will be most appropriate (that is, you are advised to choose ITOL=1 with ATOL 1 small but positive).

8 Parallelism and Performance

D02NDF is not thread safe and should not be called from a multithreaded user program. Please see Section 3.12.1 in How to Use the NAG Library and its Documentation for more information on thread safety.
D02NDF is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
D02NDF makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

Since numerical stability and memory are often conflicting requirements when solving ordinary differential systems where the Jacobian matrix is sparse, we provide a diagnostic routine, D02NXF, whose aim is to inform you how much memory is required to solve the problem and to give you some indication of numerical stability.
In general, you are advised to choose the Backward Differentiation Formula option (setup routine D02NVF) but if efficiency is of great importance and especially if it is suspected that ∂g ∂y has complex eigenvalues near the imaginary axis for some part of the integration, you should try the BLEND option (setup routine D02NWF).

10 Example

This example solves the well-known stiff Robertson problem
a′ = -0.04 a+1.0 E 4 bc b′ = -0.04 a-1.0 E 4 bc -3.0 E 7⁢b 2 c′ = -3.0 E 7⁢b 2
over the range 0,10.0 with initial conditions a=1.0 and b=c=0.0 using scalar error control (ITOL=1). The solution is computed up to 10.0 by overshooting and interpolating (ITASK=1) and the intermediate solution computed on an equispaced mesh through MONITR. The integration algorithm used is the BDF method (setup routine D02NVF) and a modified Newton method is also used. The use of the 'N' (Numerical) and 'S' (Structural) options are illustrated in turn for calculating the Jacobian.

10.1 Program Text

Program Text (d02ndfe.f90)

10.2 Program Data

Program Data (d02ndfe.d)

10.3 Program Results

Program Results (d02ndfe.r)

GnuplotProduced by GNUPLOT 4.6 patchlevel 3 0 0.2 0.4 0.6 0.8 1 0 2 4 6 8 10 0 5e−06 1e−05 1.5e−05 2e−05 2.5e−05 3e−05 3.5e−05 4e−05 Solution (a,c) Solution (b) x Example Program Stiff Robertson Problem BDF Method, Sparse Numerical Jacobian with Structure Supplied a b c gnuplot_plot_1 gnuplot_plot_2 gnuplot_plot_3
D02 Chapter Contents
D02 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


D02NEF : NAG Library, Mark 26

D02 Chapter Contents
D02 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

D02NEF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

D02NEF is a routine for integrating stiff systems of implicit ordinary differential equations coupled with algebraic equations.

2 Specification

SUBROUTINE D02NEF ( NEQ, T, TOUT, Y, YDOT, RTOL, ATOL, ITASK, RES, JAC, ICOM, COM, LCOM, IUSER, RUSER, IFAIL)
INTEGER | NEQ, ITASK, ICOM(50+NEQ), LCOM, IUSER(*), IFAIL
REAL (KIND=nag_wp) | T, TOUT, Y(NEQ), YDOT(NEQ), RTOL(*), ATOL(*), COM(LCOM), RUSER(*)
EXTERNAL | RES, JAC

3 Description

D02NEF is a general purpose routine for integrating the initial value problem for a stiff system of implicit ordinary differential equations with coupled algebraic equations written in the form
F t,y,y′ = 0 .
D02NEF uses the DASSL implementation of the Backward Differentiation Formulae (BDF) of orders one to five to solve a system of the above form for y (Y) and y′ (YDOT). Values for Y and YDOT at the initial time must be given as input. These values must be consistent, (i.e., if T, Y, YDOT are the given initial values, they must satisfy F T,Y,YDOT=0). The routine solves the system from t=T to t=TOUT.
An outline of a typical calling program for D02NEF is given below. It calls the DASSL implementation of the BDF integrator setup routine D02MWF and the banded matrix setup routine D02NPF (if required), and, if the integration needs to proceed, calls D02MCF before continuing the integration.
!     Declarations

      EXTERNAL RES, JAC
             .
             .
             .
!     Initialize the integrator
      CALL D02MWF(...)
!     Is the Jacobian matrix banded?
      IF (BANDED) CALL D02NPF(...)

!     Set DT to the required temporal resolution
!     Set TEND to the final time
!     Call the integrator for each temporal value:
1000  CALL D02NEF(...,RES,JAC,...)
!     Continue integration?
      IF (TOUT.LT.TEND .AND. ITASK.GE.0) THEN
        IF (ITASK.NE.1) TOUT = MIN(TOUT+DT,TEND)
!       Print solution
        CALL D02MCF(...)
        GO TO 1000
      ENDIF
             .
             .
             .

4 References

None.

5 Arguments

1:   NEQ – INTEGERInput
On entry: the number of differential-algebraic equations to be solved.
Constraint: NEQ≥1.
2:   T – REAL (KIND=nag_wp)Input/Output
On initial entry: the initial value of the independent variable, t.
On intermediate exit: t, the current value of the independent variable.
On final exit: the value of the independent variable at which the computed solution y is returned (usually at TOUT).
3:   TOUT – REAL (KIND=nag_wp)Input
On entry: the next value of t at which a computed solution is desired.
On initial entry: TOUT is used to determine the direction of integration. Integration is permitted in either direction (see also ITASK).
Constraint: TOUT≠T.
4:   Y NEQ – REAL (KIND=nag_wp) arrayInput/Output
On initial entry: the vector of initial values of the dependent variables y.
On intermediate exit: the computed solution vector, y, evaluated at t=T.
On final exit: the computed solution vector, evaluated at t (usually t=TOUT).
5:   YDOT NEQ – REAL (KIND=nag_wp) arrayInput/Output
On initial entry: YDOT must contain approximations to the time derivatives y' of the vector y evaluated at the initial value of the independent variable.
On exit: the time derivatives y' of the vector y at the last integration point.
6:   RTOL* – REAL (KIND=nag_wp) arrayInput/Output
Note: the dimension of the array RTOL depends on the value of ITOL as set in D02MWF; it must be at least NEQ if ITOL=.TRUE. and at least 1 if ITOL=.FALSE..
On entry: the relative local error tolerance.
Constraint: RTOL i≥0.0, for i=1,2,…,n
where n=NEQ when ITOL=.TRUE. and n=1 otherwise.
On exit: RTOL remains unchanged unless D02NEF exits with IFAIL=16 in which case the values may have been increased to values estimated to be appropriate for continuing the integration.
7:   ATOL* – REAL (KIND=nag_wp) arrayInput/Output
Note: the dimension of the array ATOL depends on the value of ITOL as set in D02MWF; it must be at least NEQ if ITOL=.TRUE. and at least 1 if ITOL=.FALSE..
On entry: the absolute local error tolerance.
Constraint: ATOL i≥0.0, for i=1,2,…,n
where n=NEQ when ITOL=.TRUE. and n=1 otherwise.
On exit: ATOL remains unchanged unless D02NEF exits with IFAIL=16 in which case the values may have been increased to values estimated to be appropriate for continuing the integration.
8:   ITASK – INTEGERInput/Output
On initial entry: need not be set.
On exit: the task performed by the integrator on successful completion or an indicator that a problem occurred during integration.
ITASK=2
The integration to TOUT was successfully completed (T=TOUT) by stepping exactly to TOUT.
ITASK=3
The integration to TOUT was successfully completed (T=TOUT) by stepping past TOUT. Y and YDOT are obtained by interpolation.
ITASK<0
Different negative values of ITASK returned correspond to different failure exits. IFAIL should always be checked in such cases and the corrective action taken where appropriate.
ITASK must remain unchanged between calls to D02NEF.
9:   RES – SUBROUTINE, supplied by the user.External Procedure
RES must evaluate the residual
R = F t,y,y′ .
The specification of RES is:
SUBROUTINE RES ( NEQ, T, Y, YDOT, R, IRES, IUSER, RUSER)
INTEGER | NEQ, IRES, IUSER(*)
REAL (KIND=nag_wp) | T, Y(NEQ), YDOT(NEQ), R(NEQ), RUSER(*)
1:   NEQ – INTEGERInput
On entry: the number of differential-algebraic equations being solved.
2:   T – REAL (KIND=nag_wp)Input
On entry: t, the current value of the independent variable.
3:   Y NEQ – REAL (KIND=nag_wp) arrayInput
On entry: yi, for i=1,2,…,NEQ, the current solution component.
4:   YDOT NEQ – REAL (KIND=nag_wp) arrayInput
On entry: the derivative of the solution at the current point t.
5:   R NEQ – REAL (KIND=nag_wp) arrayOutput
On exit: R i must contain the ith component of R, for i=1,2,…,NEQ where
R = F T,Y,YDOT .
6:   IRES – INTEGERInput/Output
On entry: is always equal to zero.
On exit: IRES should normally be left unchanged. However, if an illegal value of Y is encountered, IRES should be set to -1; D02NEF will then attempt to resolve the problem so that illegal values of Y are not encountered. IRES should be set to -2 if you wish to return control to the calling (sub)routine; this will cause D02NEF to exit with IFAIL=23.
7:   IUSER* – INTEGER arrayUser Workspace
8:   RUSER* – REAL (KIND=nag_wp) arrayUser Workspace
RES is called with the arguments IUSER and RUSER as supplied to D02NEF. You are free to use the arrays IUSER and RUSER to supply information to RES as an alternative to using COMMON global variables.
RES must either be a module subprogram USEd by, or declared as EXTERNAL in, the (sub)program from which D02NEF is called. Arguments denoted as Input must not be changed by this procedure.
10:   JAC – SUBROUTINE, supplied by the NAG Library or the user.External Procedure
Evaluates the matrix of partial derivatives, J, where
J ij = ∂Fi ∂yj + CJ × ∂Fi ∂y′j ,  i,j=1,2,…,NEQ .
If this option is not required, the actual argument for JAC must be the dummy routine D02NEZ. (D02NEZ is included in the NAG Library.) You must indicate to the integrator whether this option is to be used by setting the argument JCEVAL appropriately in a call to the setup routine D02MWF.
The specification of JAC is:
SUBROUTINE JAC ( NEQ, T, Y, YDOT, PD, CJ, IUSER, RUSER)
INTEGER | NEQ, IUSER(*)
REAL (KIND=nag_wp) | T, Y(NEQ), YDOT(NEQ), PD(*), CJ, RUSER(*)
1:   NEQ – INTEGERInput
On entry: the number of differential-algebraic equations being solved.
2:   T – REAL (KIND=nag_wp)Input
On entry: t, the current value of the independent variable.
3:   Y NEQ – REAL (KIND=nag_wp) arrayInput
On entry: yi, for i=1,2,…,NEQ, the current solution component.
4:   YDOT NEQ – REAL (KIND=nag_wp) arrayInput
On entry: the derivative of the solution at the current point t.
5:   PD* – REAL (KIND=nag_wp) arrayInput/Output
On entry: PD is preset to zero before the call to JAC.
On exit: if the Jacobian is full then PD j-1×NEQ+i=J ij, for i=1,2,…,NEQ and j=1,2,…,NEQ; if the Jacobian is banded then PD j-1×2 ML+MU+1+ML+MU+i-j+1=J ij, for max 1,j-MU≤i≤min n,j+ML; (see also in F07BDF (DGBTRF)).
6:   CJ – REAL (KIND=nag_wp)Input
On entry: CJ is a scalar constant which will be defined in D02NEF.
7:   IUSER* – INTEGER arrayUser Workspace
8:   RUSER* – REAL (KIND=nag_wp) arrayUser Workspace
JAC is called with the arguments IUSER and RUSER as supplied to D02NEF. You are free to use the arrays IUSER and RUSER to supply information to JAC as an alternative to using COMMON global variables.
JAC must either be a module subprogram USEd by, or declared as EXTERNAL in, the (sub)program from which D02NEF is called. Arguments denoted as Input must not be changed by this procedure.
11:   ICOM 50+NEQ – INTEGER arrayCommunication Array
ICOM contains information which is usually of no interest, but is necessary for subsequent calls. However you may find the following useful:
ICOM 22
The order of the method to be attempted on the next step.
ICOM 23
The order of the method used on the last step.
ICOM 26
The number of steps taken so far.
ICOM 27
The number of calls to RES so far.
ICOM 28
The number of evaluations of the matrix of partial derivatives needed so far.
ICOM 29
The total number of error test failures so far.
ICOM 30
The total number of convergence test failures so far.
12:   COM LCOM – REAL (KIND=nag_wp) arrayCommunication Array
COM contains information which is usually of no interest, but is necessary for subsequent calls. However you may find the following useful:
COM 3
The step size to be attempted on the next step.
COM 4
The current value of the independent variable, i.e., the farthest point integration has reached. This will be different from T only when interpolation has been performed (ITASK=3).
13:   LCOM – INTEGERInput
On entry: the dimension of the array COM as declared in the (sub)program from which D02NEF is called.
Constraint: LCOM≥40+maxorder+4×NEQ+NEQ×p+q where maxorder is the maximum order that can be used by the integration method (see MAXORD in D02MWF); p=NEQ when the Jacobian is full and p=2×ML+MU+1 when the Jacobian is banded; and, q=NEQ/ML+MU+1+1 when the Jacobian is to be evaluated numerically and q=0 otherwise.
14:   IUSER* – INTEGER arrayUser Workspace
15:   RUSER* – REAL (KIND=nag_wp) arrayUser Workspace
IUSER and RUSER are not used by D02NEF, but are passed directly to RES and JAC and may be used to pass information to these routines as an alternative to using COMMON global variables.
16:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, because for this routine the values of the output arguments may be useful even if IFAIL≠0 on exit, the recommended value is -1. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Note: D02NEF may return useful information for one or more of the following detected errors or warnings.
Errors or warnings detected by the routine:
IFAIL=1
On entry, NEQ=value.
Constraint: NEQ≥1.
IFAIL=3
On entry, T=value.
Constraint: TOUT≠T.
TOUT is behind T in the direction of h: TOUT-T=value, h=value.
TOUT is too close to T to start integration: TOUT-T=value: hmin=value.
IFAIL=6
Some element of RTOL is less than zero.
IFAIL=7
Some element of ATOL is less than zero.
IFAIL=8
A previous call to this routine returned with ITASK=value and no appropriate action was taken.
IFAIL=11
Either the initialization routine has not been called prior to the first call of this routine or a communication array has become corrupted.
IFAIL=12
Either the initialization routine has not been called prior to the first call of this routine or a communication array has become corrupted.
IFAIL=13
COM array is of insufficient length; length required =value; actual length LCOM=value.
IFAIL=14
All elements of RTOL and ATOL are zero.
IFAIL=15
Maximum number of steps taken on this call before reaching TOUT: T=value, maximum number of steps =value.
IFAIL=16
Too much accuracy requested for precision of machine. RTOL and ATOL were increased by scale factor R. Try running again with these scaled tolerances. T=value, R=value.
IFAIL=17
A solution component has become zero when a purely relative tolerance (zero absolute tolerance) was selected for that component. T=value, Y I=value for component I=value.
IFAIL=18
The error test failed repeatedly with h=hmin. T=value. Stepsize h=value.
IFAIL=19
The corrector repeatedly failed to converge with h=hmin. T=value. Stepsize h=value.
IFAIL=20
The iteration matrix is singular. T=value. Stepsize h=value.
IFAIL=21
The corrector could not converge and the error test failed repeatedly. T=value. Stepsize h=value.
IFAIL=22
IRES was set to -1 during a call to RES and could not be resolved. T=value. Stepsize h=value.
IFAIL=23
IRES was set to -2 during a call to RES. T=value. Stepsize =value.
IFAIL=24
The initial YDOT could not be computed. T=value. Stepsize h=value.
IFAIL=25
Repeated occurrences of input constraint violations have been detected. This could result in a potential infinite loop: ITASK=value. Current violation corresponds to exit with IFAIL=value.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

The accuracy of the numerical solution may be controlled by a careful choice of the arguments RTOL and ATOL. You are advised to use scalar error control unless the components of the solution are expected to be poorly scaled. For the type of decaying solution typical of many stiff problems, relative error control with a small absolute error threshold will be most appropriate (that is, you are advised to choose ITOL=0 with ATOL 1 small but positive).

8 Parallelism and Performance

D02NEF is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
D02NEF makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The cost of computing a solution depends critically on the size of the differential system and to a lesser extent on the degree of stiffness of the problem. For banded systems the cost is proportional to NEQ× ML+ MU+1 2 , while for full systems the cost is proportional to NEQ 3. Note however that for moderately sized problems which are only mildly nonlinear the cost may be dominated by factors proportional to NEQ×ML+MU+1 and NEQ 2 respectively.

10 Example

For this routine two examples are presented. There is a single example program for D02NEF, with a main program and the code to solve the two example problems given in Example 1 (EX1) and Example 2 (EX2).
Example 1 (EX1)
This example solves the well-known stiff Robertson problem written in implicit form
r 1 = -0.04 a + 1.0 E 4 bc - a′ r 2 = 0.04 a - 1.0 E 4 bc - 3.0 E 7⁢b 2 - b′ r 3 = 3.0 E 7⁢b 2 - c′
with initial conditions a=1.0 and b=c=0.0 over the range 0,0.1 the BDF method (setup routine D02MWF and D02NPF).
Example 2 (EX2)
This example illustrates the use of D02NEF to solve a simple algebraic problem by continuation. The equation 4-2 y+0.1 ey t=0 from t=0 (where y=2) to t=1.

10.1 Program Text

Program Text (d02nefe.f90)

10.2 Program Data

Program Data (d02nefe.d)

10.3 Program Results

Program Results (d02nefe.r)

D02 Chapter Contents
D02 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


D02NGF : NAG Library, Mark 26

D02 Chapter Contents
D02 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

D02NGF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

D02NGF is a direct communication routine for integrating stiff systems of implicit ordinary differential equations coupled with algebraic equations when the Jacobian is a full matrix.

2 Specification

SUBROUTINE D02NGF ( NEQ, LDYSAV, T, TOUT, Y, YDOT, RWORK, RTOL, ATOL, ITOL, INFORM, RESID, YSAV, SDYSAV, JAC, WKJAC, NWKJAC, MONITR, LDERIV, ITASK, ITRACE, IFAIL)
INTEGER | NEQ, LDYSAV, ITOL, INFORM(23), SDYSAV, NWKJAC, ITASK, ITRACE, IFAIL
REAL (KIND=nag_wp) | T, TOUT, Y(NEQ), YDOT(NEQ), RWORK(50+4*NEQ), RTOL(*), ATOL(*), YSAV(LDYSAV,SDYSAV), WKJAC(NWKJAC)
LOGICAL | LDERIV(2)
EXTERNAL | RESID, JAC, MONITR

3 Description

D02NGF is a general purpose routine for integrating the initial value problem for a stiff system of implicit ordinary differential equations coupled with algebraic equations, written in the form
A t,y y′=g t,y.
It is designed specifically for the case where the resulting Jacobian is a full matrix (see the description of JAC).
Both interval and step oriented modes of operation are available and also modes designed to permit intermediate output within an interval oriented mode.
An outline of a typical calling program for D02NGF is given below. It calls the full matrix linear algebra setup routine D02NSF, the Backward Differentiation Formula (BDF) integrator setup routine D02NVF, and its diagnostic counterpart D02NYF.
!     Declarations

      EXTERNAL RESID, JAC, MONITR
          .
          .
          .
      IFAIL = 0
      CALL D02NVF(...,IFAIL)
      CALL D02NSF(NEQ, NEQMAX, JCEVAL, NWKJAC, RWORK, IFAIL)
      IFAIL = -1
      CALL D02NGF(NEQ, NEQMAX, T, TOUT, Y, YDOT, RWORK, RTOL, &
                  ATOL, ITOL, INFORM, RESID, YSAVE, NY2DIM,   &
               JAC, WKJAC, NWKJAC, MONITR, LDERIV, ITASK,  &		  ITRACE, IFAIL)
      IF (IFAIL.EQ.1 .OR. IFAIL.GE.14) STOP
      IFAIL = 0
      CALL D02NYF(...)
          .
          .
          .
      STOP
      END
The linear algebra setup routine D02NSF and one of the integrator setup routines, D02MVF, D02NVF or D02NWF, must be called prior to the call of D02NGF. The integrator diagnostic routine D02NYF may be called after the call to D02NGF. There is also a routine, D02NZF, designed to permit you to change step size on a continuation call to D02NGF without restarting the integration process.

4 References

See the D02M–N Sub-chapter Introduction.

5 Arguments

1:   NEQ – INTEGERInput
On entry: the number of differential equations to be solved.
Constraint: NEQ≥1.
2:   LDYSAV – INTEGERInput
On entry: a bound on the maximum number of equations to be solved during the integration.
Constraint: LDYSAV≥NEQ.
3:   T – REAL (KIND=nag_wp)Input/Output
On entry: t, the value of the independent variable. The input value of T is used only on the first call as the initial point of the integration.
On exit: the value at which the computed solution y is returned (usually at TOUT).
4:   TOUT – REAL (KIND=nag_wp)Input/Output
On entry: the next value of t at which a computed solution is desired. For the initial t, the input value of TOUT is used to determine the direction of integration. Integration is permitted in either direction (see also ITASK).
Constraint: TOUT≠T.
On exit: normally unchanged. However, when ITASK=6, then TOUT contains the value of T at which initial values have been computed without performing any integration. See descriptions of ITASK and LDERIV.
5:   Y NEQ – REAL (KIND=nag_wp) arrayInput/Output
On entry: the values of the dependent variables (solution). On the first call the first NEQ elements of Y must contain the vector of initial values.
On exit: the computed solution vector, evaluated at T (usually T=TOUT).
6:   YDOT NEQ – REAL (KIND=nag_wp) arrayInput/Output
On entry: if LDERIV 1=.TRUE., YDOT must contain approximations to the time derivatives y′ of the vector y.
If LDERIV 1=.FALSE., YDOT need not be set on entry.
On exit: the time derivatives y′ of the vector y at the last integration point.
7:   RWORK 50+4×NEQ – REAL (KIND=nag_wp) arrayCommunication Array
8:   RTOL* – REAL (KIND=nag_wp) arrayInput
Note: the dimension of the array RTOL must be at least 1 if ITOL=1 or 2, and at least NEQ otherwise.
On entry: the relative local error tolerance.
Constraint: RTOL i≥0.0 for all relevant i (see ITOL).
9:   ATOL* – REAL (KIND=nag_wp) arrayInput
Note: the dimension of the array ATOL must be at least 1 if ITOL=1 or 3, and at least NEQ otherwise.
On entry: the absolute local error tolerance.
Constraint: ATOL i≥0.0 for all relevant i (see ITOL).
10:   ITOL – INTEGERInput
On entry: a value to indicate the form of the local error test. ITOL indicates to D02NGF whether to interpret either or both of RTOL or ATOL as a vector or a scalar. The error test to be satisfied is ei/wi<1.0, where wi is defined as follows:
ITOL | RTOL | ATOL | wi
1 | scalar | scalar | RTOL 1×yi+ATOL 1
2 | scalar | vector | RTOL 1×yi+ATOL i
3 | vector | scalar | RTOL i×yi+ATOL 1
4 | vector | vector | RTOL i×yi+ATOL i
ei is an estimate of the local error in yi, computed internally, and the choice of norm to be used is defined by a previous call to an integrator setup routine.
Constraint: ITOL=1, 2, 3 or 4.
11:   INFORM 23 – INTEGER arrayCommunication Array
12:   RESID – SUBROUTINE, supplied by the user.External Procedure
RESID must evaluate the residual
r=g t,y-A t,y y′
in one case and
r=-A t,y y′
in another.
The specification of RESID is:
SUBROUTINE RESID ( NEQ, T, Y, YDOT, R, IRES)
INTEGER | NEQ, IRES
REAL (KIND=nag_wp) | T, Y(NEQ), YDOT(NEQ), R(NEQ)
1:   NEQ – INTEGERInput
On entry: the number of equations being solved.
2:   T – REAL (KIND=nag_wp)Input
On entry: t, the current value of the independent variable.
3:   Y NEQ – REAL (KIND=nag_wp) arrayInput
On entry: the value of yi, for i=1,2,…,NEQ.
4:   YDOT NEQ – REAL (KIND=nag_wp) arrayInput
On entry: the value of yi′, for i=1,2,…,NEQ, at t.
5:   R NEQ – REAL (KIND=nag_wp) arrayOutput
On exit: R i must contain the ith component of r, for i=1,2,…,NEQ, where
r=g t,y-A t,y y′ (1)
or
r=-A t,y y′ (2)
and where the definition of r is determined by the input value of IRES.
6:   IRES – INTEGERInput/Output
On entry: the form of the residual that must be returned in array R.
IRES=-1
The residual defined in equation (2) must be returned.
IRES=1
The residual defined in equation (1) must be returned.
On exit: should be unchanged unless one of the following actions is required of the integrator, in which case IRES should be set accordingly.
IRES=2
Indicates to the integrator that control should be passed back immediately to the calling (sub)program with the error indicator set to IFAIL=11.
IRES=3
Indicates to the integrator that an error condition has occurred in the solution vector, its time derivative or in the value of t. The integrator will use a smaller time step to try to avoid this condition. If this is not possible, the integrator returns to the calling (sub)program with the error indicator set to IFAIL=7.
IRES=4
Indicates to the integrator to stop its current operation and to enter MONITR immediately with argument IMON=-2.
RESID must either be a module subprogram USEd by, or declared as EXTERNAL in, the (sub)program from which D02NGF is called. Arguments denoted as Input must not be changed by this procedure.
13:   YSAV LDYSAVSDYSAV – REAL (KIND=nag_wp) arrayCommunication Array
14:   SDYSAV – INTEGERInput
On entry: the second dimension of the array YSAV as declared in the (sub)program from which D02NGF is called. An appropriate value for SDYSAV is described in the specifications of the integrator setup routines D02MVF, D02NVF and D02NWF. This value must be the same as that supplied to the integrator setup routine.
15:   JAC – SUBROUTINE, supplied by the NAG Library or the user.External Procedure
JAC must evaluate the Jacobian of the system. If this option is not required, the actual argument for JAC must be the dummy routine D02NGZ. (D02NGZ is included in the NAG Library.) You must indicate to the integrator whether this option is to be used by setting the argument JCEVAL appropriately in a call to the full linear algebra setup routine D02NSF.
First we must define the system of nonlinear equations which is solved internally by the integrator. The time derivative, y′, generated internally, has the form
y′ = y-z / hd ,
where h is the current step size and d is an argument that depends on the integration method in use. The vector y is the current solution and the vector z depends on information from previous time steps. This means that d d y′ ​ ​ = hd d dy ​ ​ . The system of nonlinear equations that is solved has the form
A t,y y′ - g t,y = 0
but it is solved in the form
r t,y = 0 ,
where r is the function defined by
r t,y = hd A t,y y-z / hd - g t,y .
It is the Jacobian matrix ∂r ∂y that you must supply in JAC as follows:
∂ri ∂yj = a ij t,y + hd ∂ ∂yj ∑ k=1 NEQ a ik t,y yk′ - gi t,y .
The specification of JAC is:
SUBROUTINE JAC ( NEQ, T, Y, YDOT, H, D, P)
INTEGER | NEQ
REAL (KIND=nag_wp) | T, Y(NEQ), YDOT(NEQ), H, D, P(NEQ,NEQ)
1:   NEQ – INTEGERInput
On entry: the number of equations being solved.
2:   T – REAL (KIND=nag_wp)Input
On entry: t, the current value of the independent variable.
3:   Y NEQ – REAL (KIND=nag_wp) arrayInput
On entry: yi, for i=1,2,…,NEQ, the current solution component.
4:   YDOT NEQ – REAL (KIND=nag_wp) arrayInput
On entry: the derivative of the solution at the current point t.
5:   H – REAL (KIND=nag_wp)Input
On entry: the current step size.
6:   D – REAL (KIND=nag_wp)Input
On entry: the argument d which depends on the integration method.
7:   P NEQNEQ – REAL (KIND=nag_wp) arrayInput/Output
On entry: is set to zero.
On exit: P ij must contain ∂ri ∂yj , for i=1,2,…,NEQ and j=1,2,…,NEQ.
Only the nonzero elements of this array need be set, since it is preset to zero before the call to JAC.
JAC must either be a module subprogram USEd by, or declared as EXTERNAL in, the (sub)program from which D02NGF is called. Arguments denoted as Input must not be changed by this procedure.
16:   WKJAC NWKJAC – REAL (KIND=nag_wp) arrayCommunication Array
17:   NWKJAC – INTEGERInput
On entry: the dimension of the array WKJAC as declared in the (sub)program from which D02NGF is called. This value must be the same as that supplied to the linear algebra setup routine D02NSF.
Constraint: NWKJAC≥LDYSAV×LDYSAV+1.
18:   MONITR – SUBROUTINE, supplied by the NAG Library or the user.External Procedure
MONITR performs tasks requested by you. If this option is not required, then the actual argument for MONITR must be the dummy routine D02NBY. (D02NBY is included in the NAG Library.)
The specification of MONITR is:
SUBROUTINE MONITR ( NEQ, LDYSAV, T, HLAST, HNEXT, Y, YDOT, YSAV, R, ACOR, IMON, INLN, HMIN, HMAX, NQU)
INTEGER | NEQ, LDYSAV, IMON, INLN, NQU
REAL (KIND=nag_wp) | T, HLAST, HNEXT, Y(NEQ), YDOT(NEQ), YSAV(LDYSAV,sdysav), R(NEQ), ACOR(NEQ,2), HMIN, HMAX
where sdysav is the numerical value of SDYSAV in the call of D02NGF.
1:   NEQ – INTEGERInput
On entry: the number of equations being solved.
2:   LDYSAV – INTEGERInput
On entry: an upper bound on the number of equations to be solved.
3:   T – REAL (KIND=nag_wp)Input
On entry: the current value of the independent variable.
4:   HLAST – REAL (KIND=nag_wp)Input
On entry: the last step size successfully used by the integrator.
5:   HNEXT – REAL (KIND=nag_wp)Input/Output
On entry: the step size that the integrator proposes to take on the next step.
On exit: the next step size to be used. If this is different from the input value, then IMON must be set to 4.
6:   Y NEQ – REAL (KIND=nag_wp) arrayInput/Output
On entry: y, the values of the dependent variables evaluated at t.
On exit: these values must not be changed unless IMON is set to 2.
7:   YDOT NEQ – REAL (KIND=nag_wp) arrayInput
On entry: the time derivatives y′ of the vector y.
8:   YSAV LDYSAVsdysav – REAL (KIND=nag_wp) arrayInput
On entry: workspace to enable you to carry out interpolation using either of the routines D02XJF or D02XKF.
9:   R NEQ – REAL (KIND=nag_wp) arrayInput
On entry: if IMON=0 and INLN=3, then the first NEQ elements contain the residual vector A t,y y′-g t,y.
10:   ACOR NEQ 2 – REAL (KIND=nag_wp) arrayInput
On entry: with IMON=1, ACOR i 1 contains the weight used for the ith equation when the norm is evaluated, and ACOR i 2 contains the estimated local error for the ith equation. The scaled local error at the end of a timestep may be obtained by calling the real function D02ZAF as follows:
 IFAIL = 1
 ERRLOC = D02ZAF(NEQ, ACOR(1,2), ACOR(1,1), IFAIL)
 ! CHECK IFAIL BEFORE PROCEEDING
11:   IMON – INTEGERInput/Output
On entry: a flag indicating under what circumstances MONITR was called:
IMON=-2
Entry from the integrator after IRES=4 (set in RESID) caused an early termination (this facility could be used to locate discontinuities).
IMON=-1
The current step failed repeatedly.
IMON=0
Entry after a call to the internal nonlinear equation solver (see INLN).
IMON=1
The current step was successful.
On exit: may be reset to determine subsequent action in D02NGF.
IMON=-2
Integration is to be halted. A return will be made from the integrator to the calling (sub)program with IFAIL=12.
IMON=-1
Allow the integrator to continue with its own internal strategy. The integrator will try up to three restarts unless IMON≠-1 on exit.
IMON=0
Return to the internal nonlinear equation solver, where the action taken is determined by the value of INLN (see INLN).
IMON=1
Normal exit to the integrator to continue integration.
IMON=2
Restart the integration at the current time point. The integrator will restart from order 1 when this option is used. The solution Y, provided by MONITR, will be used for the initial conditions.
IMON=3
Try to continue with the same step size and order as was to be used before the call to MONITR. HMIN and HMAX may be altered if desired.
IMON=4
Continue the integration but using a new value of HNEXT and possibly new values of HMIN and HMAX.
12:   INLN – INTEGEROutput
On exit: the action to be taken by the internal nonlinear equation solver when MONITR is exited with IMON=0. By setting INLN=3 and returning to the integrator, the residual vector is evaluated and placed in the array R, and then MONITR is called again. At present this is the only option available: INLN must not be set to any other value.
13:   HMIN – REAL (KIND=nag_wp)Input/Output
On entry: the minimum step size to be taken on the next step.
On exit: the minimum step size to be used. If this is different from the input value, then IMON must be set to 3 or 4.
14:   HMAX – REAL (KIND=nag_wp)Input/Output
On entry: the maximum step size to be taken on the next step.
On exit: the maximum step size to be used. If this is different from the input value, then IMON must be set to 3 or 4. If HMAX is set to zero, no limit is assumed.
15:   NQU – INTEGERInput
On entry: the order of the integrator used on the last step. This is supplied to enable you to carry out interpolation using either of the routines D02XJF or D02XKF.
MONITR must either be a module subprogram USEd by, or declared as EXTERNAL in, the (sub)program from which D02NGF is called. Arguments denoted as Input must not be changed by this procedure.
19:   LDERIV 2 – LOGICAL arrayInput/Output
On entry: LDERIV 1 must be set to .TRUE. if you have supplied both an initial y and an initial y′. LDERIV 1 must be set to .FALSE. if only the initial y has been supplied.
LDERIV 2 must be set to .TRUE. if the integrator is to use a modified Newton method to evaluate the initial y and y′. Note that y and y′, if supplied, are used as initial estimates. This method involves taking a small step at the start of the integration, and if ITASK=6 on entry, T and TOUT will be set to the result of taking this small step. LDERIV 2 must be set to .FALSE. if the integrator is to use functional iteration to evaluate the initial y and y′, and if this fails a modified Newton method will then be attempted. LDERIV 2=.TRUE. is recommended if there are implicit equations or the initial y and y′ are zero.
On exit: LDERIV 1 is normally unchanged. However if ITASK=6 and internal initialization was successful then LDERIV 1=.TRUE..
LDERIV 2=.TRUE., if implicit equations were detected. Otherwise LDERIV 2=.FALSE..
20:   ITASK – INTEGERInput
On entry: the task to be performed by the integrator.
ITASK=1
Normal computation of output values of y t at t=TOUT (by overshooting and interpolating).
ITASK=2
Take one step only and return.
ITASK=3
Stop at the first internal integration point at or beyond t=TOUT and return.
ITASK=4
Normal computation of output values of y t at t=TOUT but without overshooting t=TCRIT. TCRIT must be specified as an option in one of the integrator setup routines before the first call to the integrator, or specified in the optional input routine before a continuation call. TCRIT may be equal to or beyond TOUT, but not before it, in the direction of integration.
ITASK=5
Take one step only and return, without passing TCRIT. TCRIT must be specified as under ITASK=4.
ITASK=6
The integrator will solve for the initial values of y and y′ only and then return to the calling (sub)program without doing the integration. This option can be used to check the initial values of y and y′. Functional iteration or a ‘small’ backward Euler method used in conjunction with a damped Newton iteration is used to calculate these values (see LDERIV). Note that if a backward Euler step is used then the value of t will have been advanced a short distance from the initial point.
Note: if D02NGF is recalled with a different value of ITASK (and TOUT altered), then the initialization procedure is repeated, possibly leading to different initial conditions.
Constraint: 1≤ITASK≤6.
21:   ITRACE – INTEGERInput
On entry: the level of output that is printed by the integrator. ITRACE may take the value -1, 0, 1, 2 or 3.
ITRACE<-1
-1 is assumed and similarly if ITRACE>3, then 3 is assumed.
ITRACE=-1
No output is generated.
ITRACE=0
Only warning messages are printed on the current error message unit (see X04AAF).
ITRACE>0
Warning messages are printed as above, and on the current advisory message unit (see X04ABF) output is generated which details Jacobian entries, the nonlinear iteration and the time integration. The advisory messages are given in greater detail the larger the value of ITRACE.
22:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, because for this routine the values of the output arguments may be useful even if IFAIL≠0 on exit, the recommended value is -1. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
An illegal input was detected on entry, or after an internal call to MONITR. If ITRACE>-1, then the form of the error will be detailed on the current error message unit (see X04AAF).
IFAIL=2
The maximum number of steps specified has been taken (see the description of optional inputs in the integrator setup routines and the optional input continuation routine, D02NZF).
IFAIL=3
With the given values of RTOL and ATOL no further progress can be made across the integration range from the current point T. The components Y 1,Y 2,…,Y NEQ contain the computed values of the solution at the current point T.
IFAIL=4
There were repeated error test failures on an attempted step, before completing the requested task, but the integration was successful as far as T. The problem may have a singularity, or the local error requirements may be inappropriate.
IFAIL=5
There were repeated convergence test failures on an attempted step, before completing the requested task, but the integration was successful as far as T. This may be caused by an inaccurate Jacobian matrix or one which is incorrectly computed.
IFAIL=6
Some error weight wi became zero during the integration (see the description of ITOL). Pure relative error control (ATOL i=0.0) was requested on a variable (the ith) which has now vanished. The integration was successful as far as T.
IFAIL=7
RESID set its error flag (IRES=3) continually despite repeated attempts by the integrator to avoid this.
IFAIL=8
LDERIV 1=.FALSE. on entry but the internal initialization routine was unable to initialize y′ (more detailed information may be directed to the current error message unit, see X04AAF).
IFAIL=9
A singular Jacobian ∂r ∂y has been encountered. You should check the problem formulation and Jacobian calculation.
IFAIL=10
An error occurred during Jacobian formulation or back-substitution (a more detailed error description may be directed to the current error message unit, see X04AAF).
IFAIL=11
RESID signalled the integrator to halt the integration and return (IRES=2). Integration was successful as far as T.
IFAIL=12
MONITR set IMON=-2 and so forced a return but the integration was successful as far as T.
IFAIL=13
The requested task has been completed, but it is estimated that a small change in RTOL and ATOL is unlikely to produce any change in the computed solution. (Only applies when you are not operating in one step mode, that is when ITASK≠2 or 5.)
IFAIL=14
The values of RTOL and ATOL are so small that D02NGF is unable to start the integration.
IFAIL=15
The linear algebra setup routine D02NSF was not called before the call to D02NGF.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

The accuracy of the numerical solution may be controlled by a careful choice of the arguments RTOL and ATOL, and to a much lesser extent by the choice of norm. You are advised to use scalar error control unless the components of the solution are expected to be poorly scaled. For the type of decaying solution typical of many stiff problems, relative error control with a small absolute error threshold will be most appropriate (that is, you are advised to choose ITOL=1 with ATOL 1 small but positive).

8 Parallelism and Performance

D02NGF is not thread safe and should not be called from a multithreaded user program. Please see Section 3.12.1 in How to Use the NAG Library and its Documentation for more information on thread safety.
D02NGF is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
D02NGF makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The cost of computing a solution depends critically on the size of the differential system and to a lesser extent on the degree of stiffness of the problem. For D02NGF the cost is proportional to NEQ 3, though for problems which are only mildly nonlinear the cost may be dominated by factors proportional to NEQ 2 except for very large problems.
In general, you are advised to choose the BDF option (setup routine D02NVF) but if efficiency is of great importance and especially if it is suspected that ∂ ∂y A-1 g has complex eigenvalues near the imaginary axis for some part of the integration, you should try the BLEND option (setup routine D02NWF).

10 Example

This example solves the well-known stiff Robertson problem written in implicit form
r 1 = -0.04 a + 1.0 E 4 bc - a′ r 2 = 0.04 a - 1.0 E 4 bc - 3.0 E 7⁢b 2 - b′ r 3 = 3.0 E 7⁢b 2 - c′
with initial conditions a=1.0 and b=c=0.0 over the range 0,0.1 with vector error control (ITOL=4), the BDF method (setup routine D02NVF) and functional iteration. The Jacobian is calculated numerically if the functional iteration encounters difficulty and the integration is in one-step mode (ITASK=2), with C 0 interpolation to calculate the solution at intervals of 0.02 using D02XJF externally. D02NBY is used for MONITR.

10.1 Program Text

Program Text (d02ngfe.f90)

10.2 Program Data

Program Data (d02ngfe.d)

10.3 Program Results

Program Results (d02ngfe.r)

GnuplotProduced by GNUPLOT 4.6 patchlevel 3 0 0.0005 0.001 0.0015 0.002 0.0025 0.003 0.0035 0.004 0 0.02 0.04 0.06 0.08 0.1 0.996 0.9965 0.997 0.9975 0.998 0.9985 0.999 0.9995 1 Solution (100*b,c) Solution (a) x Example Program Stiff DAE with Full Jacobian Stiff Robertson Problem using BDF and Functional Iteration a 100*b c gnuplot_plot_1 gnuplot_plot_2 gnuplot_plot_3
D02 Chapter Contents
D02 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


D02NHF : NAG Library, Mark 26

D02 Chapter Contents
D02 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

D02NHF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

D02NHF is a direct communication routine for integrating stiff systems of implicit ordinary differential equations coupled with algebraic equations when the Jacobian is a banded matrix.

2 Specification

SUBROUTINE D02NHF ( NEQ, LDYSAV, T, TOUT, Y, YDOT, RWORK, RTOL, ATOL, ITOL, INFORM, RESID, YSAV, SDYSAV, JAC, WKJAC, NWKJAC, JACPVT, NJCPVT, MONITR, LDERIV, ITASK, ITRACE, IFAIL)
INTEGER | NEQ, LDYSAV, ITOL, INFORM(23), SDYSAV, NWKJAC, JACPVT(NJCPVT), NJCPVT, ITASK, ITRACE, IFAIL
REAL (KIND=nag_wp) | T, TOUT, Y(NEQ), YDOT(NEQ), RWORK(50+4*NEQ), RTOL(*), ATOL(*), YSAV(LDYSAV,SDYSAV), WKJAC(NWKJAC)
LOGICAL | LDERIV(2)
EXTERNAL | RESID, JAC, MONITR

3 Description

D02NHF is a general purpose routine for integrating the initial value problem for a stiff system of implicit ordinary differential equations coupled with algebraic equations, written in the form
A t,y y′=g t,y.
It is designed specifically for the case where the resulting Jacobian is a banded matrix (see the description of JAC).
Both interval and step oriented modes of operation are available and also modes designed to permit intermediate output within an interval oriented mode.
An outline of a typical calling program for D02NHF is given below. It calls the banded matrix linear algebra setup routine D02NTF, the Backward Differentiation Formula (BDF) integrator setup routine D02NVF, and its diagnostic counterpart D02NYF.
!     Declarations

      EXTERNAL RESID, JAC, MONITR
          .
          .
          .
      IFAIL = 0
      CALL D02NVF(...,IFAIL)
      CALL D02NTF(NEQ, NEQMAX, JCEVAL, ML, MU, NWKJAC, NJCPVT, &
                    RWORK, IFAIL)
      IFAIL = -1
      CALL D02NHF(NEQ, NEQMAX, T, TOUT, Y, YDOT, RWORK, RTOL,  &
                  ATOL, ITOL, INFORM, RESID, YSAVE, NY2DIM,    &
               JAC, WKJAC, NWKJAC, JACPVT, NJCPVT, MONITR,  &
               LDERIV, ITASK, ITRACE, IFAIL)
      IF (IFAIL.EQ.1 .OR. IFAIL.GE.14) STOP
      IFAIL = 0
      CALL D02NYF(...)
          .
          .
          .
      STOP
      END
The linear algebra setup routine D02NTF and one of the integrator setup routines, D02MVF, D02NVF or D02NWF, must be called prior to the call of D02NHF. The integrator diagnostic routine D02NYF may be called after the call to D02NHF. There is also a routine, D02NZF, designed to permit you to change step size on a continuation call to D02NHF without restarting the integration process.

4 References

See the D02M–N Sub-chapter Introduction.

5 Arguments

1:   NEQ – INTEGERInput
On entry: the number of differential equations to be solved.
Constraint: NEQ≥1.
2:   LDYSAV – INTEGERInput
On entry: a bound on the maximum number of equations to be solved during the integration.
Constraint: LDYSAV≥NEQ.
3:   T – REAL (KIND=nag_wp)Input/Output
On entry: t, the value of the independent variable. The input value of T is used only on the first call as the initial point of the integration.
On exit: the value at which the computed solution y is returned (usually at TOUT).
4:   TOUT – REAL (KIND=nag_wp)Input/Output
On entry: the next value of t at which a computed solution is desired. For the initial t, the input value of TOUT is used to determine the direction of integration. Integration is permitted in either direction (see also ITASK).
Constraint: TOUT≠T.
On exit: normally unchanged. However, when ITASK=6, then TOUT contains the value of T at which initial values have been computed without performing any integration. See descriptions of ITASK and LDERIV.
5:   Y NEQ – REAL (KIND=nag_wp) arrayInput/Output
On entry: the values of the dependent variables (solution). On the first call the first NEQ elements of Y must contain the vector of initial values.
On exit: the computed solution vector, evaluated at T (usually T=TOUT).
6:   YDOT NEQ – REAL (KIND=nag_wp) arrayInput/Output
On entry: if LDERIV 1=.TRUE., YDOT must contain approximations to the time derivatives y′ of the vector y.
If LDERIV 1=.FALSE., YDOT need not be set on entry.
On exit: the time derivatives y′ of the vector y at the last integration point.
7:   RWORK 50+4×NEQ – REAL (KIND=nag_wp) arrayCommunication Array
8:   RTOL* – REAL (KIND=nag_wp) arrayInput
Note: the dimension of the array RTOL must be at least 1 if ITOL=1 or 2, and at least NEQ otherwise.
On entry: the relative local error tolerance.
Constraint: RTOL i≥0.0 for all relevant i (see ITOL).
9:   ATOL* – REAL (KIND=nag_wp) arrayInput
Note: the dimension of the array ATOL must be at least 1 if ITOL=1 or 3, and at least NEQ otherwise.
On entry: the absolute local error tolerance.
Constraint: ATOL i≥0.0 for all relevant i (see ITOL).
10:   ITOL – INTEGERInput
On entry: a value to indicate the form of the local error test. ITOL indicates to D02NHF whether to interpret either or both of RTOL or ATOL as a vector or a scalar. The error test to be satisfied is ei/wi<1.0, where wi is defined as follows:
ITOL | RTOL | ATOL | wi
1 | scalar | scalar | RTOL 1×yi+ATOL 1
2 | scalar | vector | RTOL 1×yi+ATOL i
3 | vector | scalar | RTOL i×yi+ATOL 1
4 | vector | vector | RTOL i×yi+ATOL i
ei is an estimate of the local error in yi, computed internally, and the choice of norm to be used is defined by a previous call to an integrator setup routine.
Constraint: ITOL=1, 2, 3 or 4.
11:   INFORM 23 – INTEGER arrayCommunication Array
12:   RESID – SUBROUTINE, supplied by the user.External Procedure
RESID must evaluate the residual
r=g t,y-A t,y y′
in one case and
r=-A t,y y′
in another.
The specification of RESID is:
SUBROUTINE RESID ( NEQ, T, Y, YDOT, R, IRES)
INTEGER | NEQ, IRES
REAL (KIND=nag_wp) | T, Y(NEQ), YDOT(NEQ), R(NEQ)
1:   NEQ – INTEGERInput
On entry: the number of equations being solved.
2:   T – REAL (KIND=nag_wp)Input
On entry: t, the current value of the independent variable.
3:   Y NEQ – REAL (KIND=nag_wp) arrayInput
On entry: the value of yi, for i=1,2,…,NEQ.
4:   YDOT NEQ – REAL (KIND=nag_wp) arrayInput
On entry: the value of yi′, for i=1,2,…,NEQ, at t.
5:   R NEQ – REAL (KIND=nag_wp) arrayOutput
On exit: R i must contain the ith component of r, for i=1,2,…,NEQ, where
r=g t,y-A t,y y′ (1)
or
r=-A t,y y′ (2)
and where the definition of r is determined by the input value of IRES.
6:   IRES – INTEGERInput/Output
On entry: the form of the residual that must be returned in array R.
IRES=-1
The residual defined in equation (2) must be returned.
IRES=1
The residual defined in equation (1) must be returned.
On exit: should be unchanged unless one of the following actions is required of the integrator, in which case IRES should be set accordingly.
IRES=2
Indicates to the integrator that control should be passed back immediately to the calling (sub)program with the error indicator set to IFAIL=11.
IRES=3
Indicates to the integrator that an error condition has occurred in the solution vector, its time derivative or in the value of t. The integrator will use a smaller time step to try to avoid this condition. If this is not possible, the integrator returns to the calling (sub)program with the error indicator set to IFAIL=7.
IRES=4
Indicates to the integrator to stop its current operation and to enter MONITR immediately with argument IMON=-2.
RESID must either be a module subprogram USEd by, or declared as EXTERNAL in, the (sub)program from which D02NHF is called. Arguments denoted as Input must not be changed by this procedure.
13:   YSAV LDYSAVSDYSAV – REAL (KIND=nag_wp) arrayCommunication Array
14:   SDYSAV – INTEGERInput
On entry: an appropriate value for SDYSAV is described in the specifications of the integrator setup routines D02MVF, D02NVF and D02NWF. This value must be the same as that supplied to the integrator setup routine.
15:   JAC – SUBROUTINE, supplied by the NAG Library or the user.External Procedure
JAC must evaluate the Jacobian of the system. If this option is not required, the actual argument for JAC must be the dummy routine D02NHZ. (D02NHZ is included in the NAG Library.) You must indicate to the integrator whether this option is to be used by setting the argument JCEVAL appropriately in a call to the banded linear algebra setup routine D02NTF.
First we must define the system of nonlinear equations which is solved internally by the integrator. The time derivative, y′, generated internally, has the form
y′ = y-z / hd ,
where h is the current step size and d is an argument that depends on the integration method in use. The vector y is the current solution and the vector z depends on information from previous time steps. This means that d d y′ ​ ​ = hd d dy ​ ​ . The system of nonlinear equations that is solved has the form
A t,y y′ - g t,y = 0
but it is solved in the form
r t,y = 0 ,
where r is the function defined by
r t,y = hd A t,y y-z / hd - g t,y .
It is the Jacobian matrix ∂r ∂y that you must supply in JAC as follows:
∂ri ∂yj = a ij t,y + hd ∂ ∂yj ∑ k=1 NEQ a ik t,y yk′ - gi t,y .
The specification of JAC is:
SUBROUTINE JAC ( NEQ, T, Y, YDOT, H, D, ML, MU, P)
INTEGER | NEQ, ML, MU
REAL (KIND=nag_wp) | T, Y(NEQ), YDOT(NEQ), H, D, P(ML+MU+1,NEQ)
1:   NEQ – INTEGERInput
On entry: the number of equations being solved.
2:   T – REAL (KIND=nag_wp)Input
On entry: t, the current value of the independent variable.
3:   Y NEQ – REAL (KIND=nag_wp) arrayInput
On entry: yi, for i=1,2,…,NEQ, the current solution component.
4:   YDOT NEQ – REAL (KIND=nag_wp) arrayInput
On entry: the derivative of the solution at the current point t.
5:   H – REAL (KIND=nag_wp)Input
On entry: the current step size.
6:   D – REAL (KIND=nag_wp)Input
On entry: the argument d which depends on the integration method.
7:   ML – INTEGERInput
8:   MU – INTEGERInput
On entry: the number of subdiagonals and superdiagonals respectively in the band.
9:   P ML+MU+1 NEQ – REAL (KIND=nag_wp) arrayInput/Output
On entry: is set to zero.
On exit: elements of the Jacobian matrix ∂r ∂y stored as specified by the following pseudocode
 DO 20 I = 1, NEQ
 J1 = MAX(I-ML,1)
 J2 = MIN(I+MU,NEQ)
 DO 10 J = J1, J2
 K = MIN(ML+1-I,0)+J
 P(K,I) = δR/δY(I,J)
 10 CONTINUE
 20 CONTINUE
See also the routine document for F07BDF (DGBTRF).
Only nonzero elements of this array need be set, since it is preset to zero before the call to JAC.
JAC must either be a module subprogram USEd by, or declared as EXTERNAL in, the (sub)program from which D02NHF is called. Arguments denoted as Input must not be changed by this procedure.
16:   WKJAC NWKJAC – REAL (KIND=nag_wp) arrayCommunication Array
17:   NWKJAC – INTEGERInput
On entry: the dimension of the array WKJAC as declared in the (sub)program from which D02NHF is called. This value must be the same as that supplied to the linear algebra setup routine D02NTF.
Constraint: NWKJAC≥2 mL+mU+1×NEQ, where mL and mU are the number of subdiagonals and superdiagonals respectively in the band, defined by a call to D02NTF.
18:   JACPVT NJCPVT – INTEGER arrayCommunication Array
19:   NJCPVT – INTEGERInput
On entry: the size of the array JACPVT. This value must be the same as that supplied to the linear algebra setup routine D02NTF.
Constraint: NJCPVT≥NEQ.
20:   MONITR – SUBROUTINE, supplied by the NAG Library or the user.External Procedure
MONITR performs tasks requested by you. If this option is not required, then the actual argument for MONITR must be the dummy routine D02NBY. (D02NBY is included in the NAG Library.)
The specification of MONITR is:
SUBROUTINE MONITR ( NEQ, LDYSAV, T, HLAST, HNEXT, Y, YDOT, YSAV, R, ACOR, IMON, INLN, HMIN, HMAX, NQU)
INTEGER | NEQ, LDYSAV, IMON, INLN, NQU
REAL (KIND=nag_wp) | T, HLAST, HNEXT, Y(NEQ), YDOT(NEQ), YSAV(LDYSAV,sdysav), R(NEQ), ACOR(NEQ,2), HMIN, HMAX
where sdysav is the numerical value of SDYSAV in the call of D02NHF.
1:   NEQ – INTEGERInput
On entry: the number of equations being solved.
2:   LDYSAV – INTEGERInput
On entry: an upper bound on the number of equations to be solved.
3:   T – REAL (KIND=nag_wp)Input
On entry: the current value of the independent variable.
4:   HLAST – REAL (KIND=nag_wp)Input
On entry: the last step size successfully used by the integrator.
5:   HNEXT – REAL (KIND=nag_wp)Input/Output
On entry: the step size that the integrator proposes to take on the next step.
On exit: the next step size to be used. If this is different from the input value, then IMON must be set to 4.
6:   Y NEQ – REAL (KIND=nag_wp) arrayInput/Output
On entry: y, the values of the dependent variables evaluated at t.
On exit: these values must not be changed unless IMON is set to 2.
7:   YDOT NEQ – REAL (KIND=nag_wp) arrayInput
On entry: the time derivatives y′ of the vector y.
8:   YSAV LDYSAVsdysav – REAL (KIND=nag_wp) arrayInput
On entry: workspace to enable you to carry out interpolation using either of the routines D02XJF or D02XKF.
9:   R NEQ – REAL (KIND=nag_wp) arrayInput
On entry: if IMON=0 and INLN=3, then the first NEQ elements contain the residual vector A t,y y′-g t,y.
10:   ACOR NEQ 2 – REAL (KIND=nag_wp) arrayInput
On entry: with IMON=1, ACOR i 1 contains the weight used for the ith equation when the norm is evaluated, and ACOR i 2 contains the estimated local error for the ith equation. The scaled local error at the end of a timestep may be obtained by calling the real function D02ZAF as follows:
 IFAIL = 1
 ERRLOC = D02ZAF(NEQ, ACOR(1,2), ACOR(1,1), IFAIL)
 ! CHECK IFAIL BEFORE PROCEEDING
11:   IMON – INTEGERInput/Output
On entry: a flag indicating under what circumstances MONITR was called:
IMON=-2
Entry from the integrator after IRES=4 (set in RESID) caused an early termination (this facility could be used to locate discontinuities).
IMON=-1
The current step failed repeatedly.
IMON=0
Entry after a call to the internal nonlinear equation solver (see INLN).
IMON=1
The current step was successful.
On exit: may be reset to determine subsequent action in D02NHF.
IMON=-2
Integration is to be halted. A return will be made from the integrator to the calling (sub)program with IFAIL=12.
IMON=-1
Allow the integrator to continue with its own internal strategy. The integrator will try up to three restarts unless IMON≠-1 on exit.
IMON=0
Return to the internal nonlinear equation solver, where the action taken is determined by the value of INLN (see INLN).
IMON=1
Normal exit to the integrator to continue integration.
IMON=2
Restart the integration at the current time point. The integrator will restart from order 1 when this option is used. The solution Y, provided by MONITR, will be used for the initial conditions.
IMON=3
Try to continue with the same step size and order as was to be used before the call to MONITR. HMIN and HMAX may be altered if desired.
IMON=4
Continue the integration but using a new value of HNEXT and possibly new values of HMIN and HMAX.
12:   INLN – INTEGEROutput
On exit: the action to be taken by the internal nonlinear equation solver when MONITR is exited with IMON=0. By setting INLN=3 and returning to the integrator, the residual vector is evaluated and placed in the array R, and then MONITR is called again. At present this is the only option available: INLN must not be set to any other value.
13:   HMIN – REAL (KIND=nag_wp)Input/Output
On entry: the minimum step size to be taken on the next step.
On exit: the minimum step size to be used. If this is different from the input value, then IMON must be set to 3 or 4.
14:   HMAX – REAL (KIND=nag_wp)Input/Output
On entry: the maximum step size to be taken on the next step.
On exit: the maximum step size to be used. If this is different from the input value, then IMON must be set to 3 or 4. If HMAX is set to zero, no limit is assumed.
15:   NQU – INTEGERInput
On entry: the order of the integrator used on the last step. This is supplied to enable you to carry out interpolation using either of the routines D02XJF or D02XKF.
MONITR must either be a module subprogram USEd by, or declared as EXTERNAL in, the (sub)program from which D02NHF is called. Arguments denoted as Input must not be changed by this procedure.
21:   LDERIV 2 – LOGICAL arrayInput/Output
On entry: LDERIV 1 must be set to .TRUE. if you have supplied both an initial y and an initial y′. LDERIV 1 must be set to .FALSE. if only the initial y has been supplied.
LDERIV 2 must be set to .TRUE. if the integrator is to use a modified Newton method to evaluate the initial y and y′. Note that y and y′, if supplied, are used as initial estimates. This method involves taking a small step at the start of the integration, and if ITASK=6 on entry, T and TOUT will be set to the result of taking this small step. LDERIV 2 must be set to .FALSE. if the integrator is to use functional iteration to evaluate the initial y and y′, and if this fails a modified Newton method will then be attempted. LDERIV 2=.TRUE. is recommended if there are implicit equations or the initial y and y′ are zero.
On exit: LDERIV 1 is normally unchanged. However if ITASK=6 and internal initialization was successful then LDERIV 1=.TRUE..
LDERIV 2=.TRUE., if implicit equations were detected. Otherwise LDERIV 2=.FALSE..
22:   ITASK – INTEGERInput
On entry: the task to be performed by the integrator.
ITASK=1
Normal computation of output values of y t at t=TOUT (by overshooting and interpolating).
ITASK=2
Take one step only and return.
ITASK=3
Stop at the first internal integration point at or beyond t=TOUT and return.
ITASK=4
Normal computation of output values of y t at t=TOUT but without overshooting t=TCRIT. TCRIT must be specified as an option in one of the integrator setup routines before the first call to the integrator, or specified in the optional input routine before a continuation call. TCRIT may be equal to or beyond TOUT, but not before it, in the direction of integration.
ITASK=5
Take one step only and return, without passing TCRIT. TCRIT must be specified as under ITASK=4.
ITASK=6
The integrator will solve for the initial values of y and y′ only and then return to the calling (sub)program without doing the integration. This option can be used to check the initial values of y and y′. Functional iteration or a ‘small’ backward Euler method used in conjunction with a damped Newton iteration is used to calculate these values (see LDERIV). Note that if a backward Euler step is used then the value of t will have been advanced a short distance from the initial point.
Note: if D02NHF is recalled with a different value of ITASK (and TOUT altered), then the initialization procedure is repeated, possibly leading to different initial conditions.
Constraint: 1≤ITASK≤6.
23:   ITRACE – INTEGERInput
On entry: the level of output that is printed by the integrator. ITRACE may take the value -1, 0, 1, 2 or 3.
ITRACE<-1
-1 is assumed and similarly if ITRACE>3, then 3 is assumed.
ITRACE=-1
No output is generated.
ITRACE=0
Only warning messages are printed on the current error message unit (see X04AAF).
ITRACE>0
Warning messages are printed as above, and on the current advisory message unit (see X04ABF) output is generated which details Jacobian entries, the nonlinear iteration and the time integration. The advisory messages are given in greater detail the larger the value of ITRACE.
24:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, because for this routine the values of the output arguments may be useful even if IFAIL≠0 on exit, the recommended value is -1. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
An illegal input was detected on entry, or after an internal call to MONITR. If ITRACE>-1, then the form of the error will be detailed on the current error message unit (see X04AAF).
IFAIL=2
The maximum number of steps specified has been taken (see the description of optional inputs in the integrator setup routines and the optional input continuation routine, D02NZF).
IFAIL=3
With the given values of RTOL and ATOL no further progress can be made across the integration range from the current point T. The components Y 1,Y 2,…,Y NEQ contain the computed values of the solution at the current point T.
IFAIL=4
There were repeated error test failures on an attempted step, before completing the requested task, but the integration was successful as far as T. The problem may have a singularity, or the local error requirements may be inappropriate.
IFAIL=5
There were repeated convergence test failures on an attempted step, before completing the requested task, but the integration was successful as far as T. This may be caused by an inaccurate Jacobian matrix or one which is incorrectly computed.
IFAIL=6
Some error weight wi became zero during the integration (see the description of ITOL). Pure relative error control (ATOL i=0.0) was requested on a variable (the ith) which has now vanished. The integration was successful as far as T.
IFAIL=7
RESID set its error flag (IRES=3) continually despite repeated attempts by the integrator to avoid this.
IFAIL=8
LDERIV 1=.FALSE. on entry but the internal initialization routine was unable to initialize y′ (more detailed information may be directed to the current error message unit, see X04AAF).
IFAIL=9
A singular Jacobian ∂r ∂y has been encountered. You should check the problem formulation and Jacobian calculation.
IFAIL=10
An error occurred during Jacobian formulation or back-substitution (a more detailed error description may be directed to the current error message unit, see X04AAF).
IFAIL=11
RESID signalled the integrator to halt the integration and return (IRES=2). Integration was successful as far as T.
IFAIL=12
MONITR set IMON=-2 and so forced a return but the integration was successful as far as T.
IFAIL=13
The requested task has been completed, but it is estimated that a small change in RTOL and ATOL is unlikely to produce any change in the computed solution. (Only applies when you are not operating in one step mode, that is when ITASK≠2 or 5.)
IFAIL=14
The values of RTOL and ATOL are so small that D02NHF is unable to start the integration.
IFAIL=15
The linear algebra setup routine D02NTF was not called before the call to D02NHF.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

The accuracy of the numerical solution may be controlled by a careful choice of the arguments RTOL and ATOL, and to a much lesser extent by the choice of norm. You are advised to use scalar error control unless the components of the solution are expected to be poorly scaled. For the type of decaying solution typical of many stiff problems, relative error control with a small absolute error threshold will be most appropriate (that is, you are advised to choose ITOL=1 with ATOL 1 small but positive).

8 Parallelism and Performance

D02NHF is not thread safe and should not be called from a multithreaded user program. Please see Section 3.12.1 in How to Use the NAG Library and its Documentation for more information on thread safety.
D02NHF is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
D02NHF makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The cost of computing a solution depends critically on the size of the differential system and to a lesser extent on the degree of stiffness of the problem. For D02NHF the cost is proportional to NEQ× ML+MU+1 2, though for problems which are only mildly nonlinear the cost may be dominated by factors proportional to NEQ×ML+MU+1 except for very large problems.
In general, you are advised to choose the BDF option (setup routine D02NVF) but if efficiency is of great importance and especially if it is suspected that ∂ ∂y A-1 g has complex eigenvalues near the imaginary axis for some part of the integration, you should try the BLEND option (setup routine D02NWF).

10 Example

This example solves the well-known stiff Robertson problem written as an implicit differential system and in implicit form
r 1 = a′ + b′ + c′ r 2 = 0.04 a - 1.0 E 4 bc - 3.0 E 7⁢b 2 - b′ r 3 = 3.0 E 7⁢b 2 - c′
exploiting the fact that we can show that a+b+c ′ = 0 for all time. Integration is over the range 0,10.0 with initial conditions a=1.0 and b=c=0.0 using scalar relative error control and vector absolute error control (ITOL=2). We integrate using a BDF method (setup routine D02NVF) and a modified Newton method. The Jacobian is calculated numerically and we employ a default monitor, dummy routine D02NBY. We perform a normal integration (ITASK=1) to obtain the value at TOUT=10.0 by integrating past TOUT and interpolating. We also illustrate the use of ITASK=6 to calculate initial values of y and y′ and then return without integrating further.

10.1 Program Text

Program Text (d02nhfe.f90)

10.2 Program Data

Program Data (d02nhfe.d)

10.3 Program Results

Program Results (d02nhfe.r)

D02 Chapter Contents
D02 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


D02NJF : NAG Library, Mark 26

D02 Chapter Contents
D02 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

D02NJF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

D02NJF is a direct communication routine for integrating stiff systems of implicit ordinary differential equations coupled with algebraic equations when the Jacobian is a sparse matrix.

2 Specification

SUBROUTINE D02NJF ( NEQ, LDYSAV, T, TOUT, Y, YDOT, RWORK, RTOL, ATOL, ITOL, INFORM, RESID, YSAV, SDYSAV, JAC, WKJAC, NWKJAC, JACPVT, NJCPVT, MONITR, LDERIV, ITASK, ITRACE, IFAIL)
INTEGER | NEQ, LDYSAV, ITOL, INFORM(23), SDYSAV, NWKJAC, JACPVT(NJCPVT), NJCPVT, ITASK, ITRACE, IFAIL
REAL (KIND=nag_wp) | T, TOUT, Y(NEQ), YDOT(NEQ), RWORK(50+4*NEQ), RTOL(*), ATOL(*), YSAV(LDYSAV,SDYSAV), WKJAC(NWKJAC)
LOGICAL | LDERIV(2)
EXTERNAL | RESID, JAC, MONITR

3 Description

D02NJF is a general purpose routine for integrating the initial value problem for a stiff system of implicit ordinary differential equations coupled with algebraic equations, written in the form
A t,y y′=g t,y.
It is designed specifically for the case where the resulting Jacobian is a sparse matrix (see the description of JAC).
Both interval and step oriented modes of operation are available and also modes designed to permit intermediate output within an interval oriented mode.
An outline of a typical calling program for D02NJF is given below. It calls the sparse matrix linear algebra setup routine D02NUF, the Backward Differentiation Formula (BDF) integrator setup routine D02NVF, its diagnostic counterpart D02NYF, and the sparse matrix linear algebra diagnostic routine D02NXF.
!     Declarations

      EXTERNAL RESID, JAC, MONITR
          .
          .
          .
      IFAIL = 0
      CALL D02NVF(...,IFAIL)
      CALL D02NUF(NEQ, NEQMAX, JCEVAL, NWKJAC, IA, NIA, JA, NJA, &
                   JACPVT, NJCPVT, SENS, U, ETA, LBLOCK, ISPLIT,  &
               RWORK, IFAIL)
      IFAIL = -1
      CALL D02NJF(NEQ, NEQMAX, T, TOUT, Y, YDOT, RWORK, RTOL,    &
                    ATOL, ITOL, INFORM, RESID, YSAVE, NY2DIM, JAC, &
               WKJAC, NWKJAC, JACPVT, NJCPVT, MONITR, LDERIV, &
               ITASK, ITRACE, IFAIL)
      IF(IFAIL.EQ.1 .OR. IFAIL.GE.14) STOP
      IFAIL = 0
      CALL D02NXF(...)
      CALL D02NYF(...)
          .
          .
          .
      STOP
      END
The linear algebra setup routine D02NUF and one of the integrator setup routines, D02MVF, D02NVF or D02NWF, must be called prior to the call of D02NJF. Either or both of the integrator diagnostic routine D02NYF, or the sparse matrix linear algebra diagnostic routine D02NXF, may be called after the call to D02NJF. There is also a routine, D02NZF, designed to permit you to change step size on a continuation call to D02NJF without restarting the integration process.

4 References

See the D02M–N Sub-chapter Introduction.

5 Arguments

1:   NEQ – INTEGERInput
On entry: the number of differential equations to be solved.
Constraint: NEQ≥1.
2:   LDYSAV – INTEGERInput
On entry: a bound on the maximum number of equations to be solved during the integration.
Constraint: LDYSAV≥NEQ.
3:   T – REAL (KIND=nag_wp)Input/Output
On entry: t, the value of the independent variable. The input value of T is used only on the first call as the initial point of the integration.
On exit: the value at which the computed solution y is returned (usually at TOUT).
4:   TOUT – REAL (KIND=nag_wp)Input/Output
On entry: the next value of t at which a computed solution is desired. For the initial t, the input value of TOUT is used to determine the direction of integration. Integration is permitted in either direction (see also ITASK).
On exit: normally unchanged. However, when ITASK=6, then TOUT contains the value of T at which initial values have been computed without performing any integration. See descriptions of ITASK and LDERIV.
5:   Y NEQ – REAL (KIND=nag_wp) arrayInput/Output
On entry: the values of the dependent variables (solution). On the first call the first NEQ elements of Y must contain the vector of initial values.
On exit: the computed solution vector, evaluated at T (usually T=TOUT).
6:   YDOT NEQ – REAL (KIND=nag_wp) arrayInput/Output
On entry: if LDERIV 1=.TRUE., YDOT must contain approximations to the time derivatives y′ of the vector y.
If LDERIV 1=.FALSE., YDOT need not be set on entry.
On exit: the time derivatives y′ of the vector y at the last integration point.
7:   RWORK 50+4×NEQ – REAL (KIND=nag_wp) arrayCommunication Array
8:   RTOL* – REAL (KIND=nag_wp) arrayInput
Note: the dimension of the array RTOL must be at least 1 if ITOL=1 or 2, and at least NEQ otherwise.
On entry: the relative local error tolerance.
Constraint: RTOL i≥0.0 for all relevant i (see ITOL).
9:   ATOL* – REAL (KIND=nag_wp) arrayInput
Note: the dimension of the array ATOL must be at least 1 if ITOL=1 or 3, and at least NEQ otherwise.
On entry: the absolute local error tolerance.
Constraint: ATOL i≥0.0 for all relevant i (see ITOL).
10:   ITOL – INTEGERInput
On entry: a value to indicate the form of the local error test. ITOL indicates to D02NJF whether to interpret either or both of RTOL or ATOL as a vector or a scalar. The error test to be satisfied is ei/wi<1.0, where wi is defined as follows:
ITOL | RTOL | ATOL | wi
1 | scalar | scalar | RTOL 1×yi+ATOL 1
2 | scalar | vector | RTOL 1×yi+ATOL i
3 | vector | scalar | RTOL i×yi+ATOL 1
4 | vector | vector | RTOL i×yi+ATOL i
ei is an estimate of the local error in yi, computed internally, and the choice of norm to be used is defined by a previous call to an integrator setup routine.
Constraint: ITOL=1, 2, 3 or 4.
11:   INFORM 23 – INTEGER arrayCommunication Array
12:   RESID – SUBROUTINE, supplied by the user.External Procedure
RESID must evaluate the residual
r=g t,y-A t,y y′
in one case and
r=-A t,y y′
in another.
The specification of RESID is:
SUBROUTINE RESID ( NEQ, T, Y, YDOT, R, IRES)
INTEGER | NEQ, IRES
REAL (KIND=nag_wp) | T, Y(NEQ), YDOT(NEQ), R(NEQ)
1:   NEQ – INTEGERInput
On entry: the number of equations being solved.
2:   T – REAL (KIND=nag_wp)Input
On entry: t, the current value of the independent variable.
3:   Y NEQ – REAL (KIND=nag_wp) arrayInput
On entry: the value of yi, for i=1,2,…,NEQ.
4:   YDOT NEQ – REAL (KIND=nag_wp) arrayInput
On entry: the value of yi′, for i=1,2,…,NEQ, at t.
5:   R NEQ – REAL (KIND=nag_wp) arrayOutput
On exit: R i must contain the ith component of r, for i=1,2,…,NEQ, where
r=g t,y-A t,y y′ (1)
or
r=-A t,y y′ (2)
and where the definition of r is determined by the input value of IRES.
6:   IRES – INTEGERInput/Output
On entry: the form of the residual that must be returned in array R.
IRES=-1
The residual defined in equation (2) must be returned.
IRES=1
The residual defined in equation (1) must be returned.
On exit: should be unchanged unless one of the following actions is required of the integrator, in which case IRES should be set accordingly.
IRES=2
Indicates to the integrator that control should be passed back immediately to the calling (sub)program with the error indicator set to IFAIL=11.
IRES=3
Indicates to the integrator that an error condition has occurred in the solution vector, its time derivative or in the value of t. The integrator will use a smaller time step to try to avoid this condition. If this is not possible, the integrator returns to the calling (sub)program with the error indicator set to IFAIL=7.
IRES=4
Indicates to the integrator to stop its current operation and to enter MONITR immediately with argument IMON=-2.
RESID must either be a module subprogram USEd by, or declared as EXTERNAL in, the (sub)program from which D02NJF is called. Arguments denoted as Input must not be changed by this procedure.
13:   YSAV LDYSAVSDYSAV – REAL (KIND=nag_wp) arrayCommunication Array
14:   SDYSAV – INTEGERInput
On entry: the second dimension of the array YSAV as declared in the (sub)program from which D02NJF is called. An appropriate value for SDYSAV is described in the specifications of the integrator setup routines D02MVF, D02NVF and D02NWF. This value must be the same as that supplied to the integrator setup routine.
15:   JAC – SUBROUTINE, supplied by the NAG Library or the user.External Procedure
JAC must evaluate the Jacobian of the system. If this option is not required, the actual argument for JAC must be the dummy routine D02NJZ. (D02NJZ is included in the NAG Library.) You must indicate to the integrator whether this option is to be used by setting the argument JCEVAL appropriately in a call to the sparse linear algebra setup routine D02NUF.
First we must define the system of nonlinear equations which is solved internally by the integrator. The time derivative, y′, generated internally, has the form
y′ = y-z / hd ,
where h is the current step size and d is an argument that depends on the integration method in use. The vector y is the current solution and the vector z depends on information from previous time steps. This means that d d y′ ​ ​ = hd d dy ​ ​ . The system of nonlinear equations that is solved has the form
A t,y y′ - g t,y = 0
but it is solved in the form
r t,y = 0 ,
where r is the function defined by
r t,y = hd A t,y y-z / hd - g t,y .
It is the Jacobian matrix ∂r ∂y that you must supply in JAC as follows:
∂ri ∂yj = a ij t,y + hd ∂ ∂yj ∑ k=1 NEQ a ik t,y yk′ - gi t,y .
The specification of JAC is:
SUBROUTINE JAC ( NEQ, T, Y, YDOT, H, D, J, PDJ)
INTEGER | NEQ, J
REAL (KIND=nag_wp) | T, Y(NEQ), YDOT(NEQ), H, D, PDJ(NEQ)
1:   NEQ – INTEGERInput
On entry: the number of equations being solved.
2:   T – REAL (KIND=nag_wp)Input
On entry: t, the current value of the independent variable.
3:   Y NEQ – REAL (KIND=nag_wp) arrayInput
On entry: yi, for i=1,2,…,NEQ, the current solution component.
4:   YDOT NEQ – REAL (KIND=nag_wp) arrayInput
On entry: the derivative of the solution at the current point t.
5:   H – REAL (KIND=nag_wp)Input
On entry: the current step size.
6:   D – REAL (KIND=nag_wp)Input
On entry: the argument d which depends on the integration method.
7:   J – INTEGERInput
On entry: the column of the Jacobian that JAC must return in the array PDJ.
8:   PDJ NEQ – REAL (KIND=nag_wp) arrayInput/Output
On entry: is set to zero.
On exit: PDJ i should be set to the i,jth element of the Jacobian, where j is given by J. Only nonzero elements of this array need be set, since it is preset to zero before the call to JAC.
JAC must either be a module subprogram USEd by, or declared as EXTERNAL in, the (sub)program from which D02NJF is called. Arguments denoted as Input must not be changed by this procedure.
16:   WKJAC NWKJAC – REAL (KIND=nag_wp) arrayCommunication Array
17:   NWKJAC – INTEGERInput
On entry: the dimension of the array WKJAC as declared in the (sub)program from which D02NJF is called. The actual size depends on whether the sparsity structure is supplied or whether it is to be estimated. An appropriate value for NWKJAC is described in the specification of the linear algebra setup routine D02NUF. This value must be the same as that supplied to D02NUF.
18:   JACPVT NJCPVT – INTEGER arrayCommunication Array
19:   NJCPVT – INTEGERInput
On entry: the dimension of the array JACPVT as declared in the (sub)program from which D02NJF is called. The actual size depends on whether the sparsity structure is supplied or whether it is to be estimated. An appropriate value for NJCPVT is described in the specification for the linear algebra setup routine D02NUF. This value must be same as that supplied to D02NUF.
20:   MONITR – SUBROUTINE, supplied by the NAG Library or the user.External Procedure
MONITR performs tasks requested by you. If this option is not required, then the actual argument for MONITR must be the dummy routine D02NBY. (D02NBY is included in the NAG Library.)
The specification of MONITR is:
SUBROUTINE MONITR ( NEQ, LDYSAV, T, HLAST, HNEXT, Y, YDOT, YSAV, R, ACOR, IMON, INLN, HMIN, HMAX, NQU)
INTEGER | NEQ, LDYSAV, IMON, INLN, NQU
REAL (KIND=nag_wp) | T, HLAST, HNEXT, Y(NEQ), YDOT(NEQ), YSAV(LDYSAV,sdysav), R(NEQ), ACOR(NEQ,2), HMIN, HMAX
where sdysav is the numerical value of SDYSAV in the call of D02NJF.
1:   NEQ – INTEGERInput
On entry: the number of equations being solved.
2:   LDYSAV – INTEGERInput
On entry: an upper bound on the number of equations to be solved.
3:   T – REAL (KIND=nag_wp)Input
On entry: the current value of the independent variable.
4:   HLAST – REAL (KIND=nag_wp)Input
On entry: the last step size successfully used by the integrator.
5:   HNEXT – REAL (KIND=nag_wp)Input/Output
On entry: the step size that the integrator proposes to take on the next step.
On exit: the next step size to be used. If this is different from the input value, then IMON must be set to 4.
6:   Y NEQ – REAL (KIND=nag_wp) arrayInput/Output
On entry: y, the values of the dependent variables evaluated at t.
On exit: these values must not be changed unless IMON is set to 2.
7:   YDOT NEQ – REAL (KIND=nag_wp) arrayInput
On entry: the time derivatives y′ of the vector y.
8:   YSAV LDYSAVsdysav – REAL (KIND=nag_wp) arrayInput
On entry: workspace to enable you to carry out interpolation using either of the routines D02XJF or D02XKF.
9:   R NEQ – REAL (KIND=nag_wp) arrayInput
On entry: if IMON=0 and INLN=3, then the first NEQ elements contain the residual vector A t,y y′-g t,y.
10:   ACOR NEQ 2 – REAL (KIND=nag_wp) arrayInput
On entry: with IMON=1, ACOR i 1 contains the weight used for the ith equation when the norm is evaluated, and ACOR i 2 contains the estimated local error for the ith equation. The scaled local error at the end of a timestep may be obtained by calling the real function D02ZAF as follows:
 IFAIL = 1
 ERRLOC = D02ZAF(NEQ, ACOR(1,2), ACOR(1,1), IFAIL)
 ! CHECK IFAIL BEFORE PROCEEDING
11:   IMON – INTEGERInput/Output
On entry: a flag indicating under what circumstances MONITR was called:
IMON=-2
Entry from the integrator after IRES=4 (set in RESID) caused an early termination (this facility could be used to locate discontinuities).
IMON=-1
The current step failed repeatedly.
IMON=0
Entry after a call to the internal nonlinear equation solver (see INLN).
IMON=1
The current step was successful.
On exit: may be reset to determine subsequent action in D02NJF.
IMON=-2
Integration is to be halted. A return will be made from the integrator to the calling (sub)program with IFAIL=12.
IMON=-1
Allow the integrator to continue with its own internal strategy. The integrator will try up to three restarts unless IMON≠-1 on exit.
IMON=0
Return to the internal nonlinear equation solver, where the action taken is determined by the value of INLN (see INLN).
IMON=1
Normal exit to the integrator to continue integration.
IMON=2
Restart the integration at the current time point. The integrator will restart from order 1 when this option is used. The solution Y, provided by MONITR, will be used for the initial conditions.
IMON=3
Try to continue with the same step size and order as was to be used before the call to MONITR. HMIN and HMAX may be altered if desired.
IMON=4
Continue the integration but using a new value of HNEXT and possibly new values of HMIN and HMAX.
12:   INLN – INTEGEROutput
On exit: the action to be taken by the internal nonlinear equation solver when MONITR is exited with IMON=0. By setting INLN=3 and returning to the integrator, the residual vector is evaluated and placed in the array R, and then MONITR is called again. At present this is the only option available: INLN must not be set to any other value.
13:   HMIN – REAL (KIND=nag_wp)Input/Output
On entry: the minimum step size to be taken on the next step.
On exit: the minimum step size to be used. If this is different from the input value, then IMON must be set to 3 or 4.
14:   HMAX – REAL (KIND=nag_wp)Input/Output
On entry: the maximum step size to be taken on the next step.
On exit: the maximum step size to be used. If this is different from the input value, then IMON must be set to 3 or 4. If HMAX is set to zero, no limit is assumed.
15:   NQU – INTEGERInput
On entry: the order of the integrator used on the last step. This is supplied to enable you to carry out interpolation using either of the routines D02XJF or D02XKF.
MONITR must either be a module subprogram USEd by, or declared as EXTERNAL in, the (sub)program from which D02NJF is called. Arguments denoted as Input must not be changed by this procedure.
21:   LDERIV 2 – LOGICAL arrayInput/Output
On entry: LDERIV 1 must be set to .TRUE. if you have supplied both an initial y and an initial y′. LDERIV 1 must be set to .FALSE. if only the initial y has been supplied.
LDERIV 2 must be set to .TRUE. if the integrator is to use a modified Newton method to evaluate the initial y and y′. Note that y and y′, if supplied, are used as initial estimates. This method involves taking a small step at the start of the integration, and if ITASK=6 on entry, T and TOUT will be set to the result of taking this small step. LDERIV 2 must be set to .FALSE. if the integrator is to use functional iteration to evaluate the initial y and y′, and if this fails a modified Newton method will then be attempted. LDERIV 2=.TRUE. is recommended if there are implicit equations or the initial y and y′ are zero.
On exit: LDERIV 1 is normally unchanged. However if ITASK=6 and internal initialization was successful then LDERIV 1=.TRUE..
LDERIV 2=.TRUE., if implicit equations were detected. Otherwise LDERIV 2=.FALSE..
22:   ITASK – INTEGERInput
On entry: the task to be performed by the integrator.
ITASK=1
Normal computation of output values of y t at t=TOUT (by overshooting and interpolating).
ITASK=2
Take one step only and return.
ITASK=3
Stop at the first internal integration point at or beyond t=TOUT and return.
ITASK=4
Normal computation of output values of y t at t=TOUT but without overshooting t=TCRIT. TCRIT must be specified as an option in one of the integrator setup routines before the first call to the integrator, or specified in the optional input routine before a continuation call. TCRIT may be equal to or beyond TOUT, but not before it, in the direction of integration.
ITASK=5
Take one step only and return, without passing TCRIT. TCRIT must be specified as under ITASK=4.
ITASK=6
The integrator will solve for the initial values of y and y′ only and then return to the calling (sub)program without doing the integration. This option can be used to check the initial values of y and y′. Functional iteration or a ‘small’ backward Euler method used in conjunction with a damped Newton iteration is used to calculate these values (see LDERIV). Note that if a backward Euler step is used then the value of t will have been advanced a short distance from the initial point.
Note: if D02NJF is recalled with a different value of ITASK (and TOUT altered), then the initialization procedure is repeated, possibly leading to different initial conditions.
Constraint: 1≤ITASK≤6.
23:   ITRACE – INTEGERInput
On entry: the level of output that is printed by the integrator. ITRACE may take the value -1, 0, 1, 2 or 3.
ITRACE<-1
-1 is assumed and similarly if ITRACE>3, then 3 is assumed.
ITRACE=-1
No output is generated.
ITRACE=0
Only warning messages are printed on the current error message unit (see X04AAF).
ITRACE>0
Warning messages are printed as above, and on the current advisory message unit (see X04ABF) output is generated which details Jacobian entries, the nonlinear iteration and the time integration. The advisory messages are given in greater detail the larger the value of ITRACE.
24:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, because for this routine the values of the output arguments may be useful even if IFAIL≠0 on exit, the recommended value is -1. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
An illegal input was detected on entry, or after an internal call to MONITR. If ITRACE>-1, then the form of the error will be detailed on the current error message unit (see X04AAF).
IFAIL=2
The maximum number of steps specified has been taken (see the description of optional inputs in the integrator setup routines and the optional input continuation routine, D02NZF).
IFAIL=3
With the given values of RTOL and ATOL no further progress can be made across the integration range from the current point T. The components Y 1,Y 2,…,Y NEQ contain the computed values of the solution at the current point T.
IFAIL=4
There were repeated error test failures on an attempted step, before completing the requested task, but the integration was successful as far as T. The problem may have a singularity, or the local error requirements may be inappropriate.
IFAIL=5
There were repeated convergence test failures on an attempted step, before completing the requested task, but the integration was successful as far as T. This may be caused by an inaccurate Jacobian matrix or one which is incorrectly computed.
IFAIL=6
Some error weight wi became zero during the integration (see the description of ITOL). Pure relative error control (ATOL i=0.0) was requested on a variable (the ith) which has now vanished. The integration was successful as far as T.
IFAIL=7
RESID set its error flag (IRES=3) continually despite repeated attempts by the integrator to avoid this.
IFAIL=8
LDERIV 1=.FALSE. on entry but the internal initialization routine was unable to initialize y′ (more detailed information may be directed to the current error message unit, see X04AAF).
IFAIL=9
A singular Jacobian ∂r ∂y has been encountered. You should check the problem formulation and Jacobian calculation.
IFAIL=10
An error occurred during Jacobian formulation or back-substitution (a more detailed error description may be directed to the current error message unit, see X04AAF).
IFAIL=11
RESID signalled the integrator to halt the integration and return (IRES=2). Integration was successful as far as T.
IFAIL=12
MONITR set IMON=-2 and so forced a return but the integration was successful as far as T.
IFAIL=13
The requested task has been completed, but it is estimated that a small change in RTOL and ATOL is unlikely to produce any change in the computed solution. (Only applies when you are not operating in one step mode, that is when ITASK≠2 or 5.)
IFAIL=14
The values of RTOL and ATOL are so small that D02NJF is unable to start the integration.
IFAIL=15
The linear algebra setup routine D02NUF was not called before the call to D02NJF.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

The accuracy of the numerical solution may be controlled by a careful choice of the arguments RTOL and ATOL, and to a much lesser extent by the choice of norm. You are advised to use scalar error control unless the components of the solution are expected to be poorly scaled. For the type of decaying solution typical of many stiff problems, relative error control with a small absolute error threshold will be most appropriate (that is, you are advised to choose ITOL=1 with ATOL 1 small but positive).

8 Parallelism and Performance

D02NJF is not thread safe and should not be called from a multithreaded user program. Please see Section 3.12.1 in How to Use the NAG Library and its Documentation for more information on thread safety.
D02NJF is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
D02NJF makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

Since numerical stability and memory are often conflicting requirements when solving ordinary differential systems where the Jacobian matrix is sparse we provide a diagnostic routine, D02NXF, whose aim is to inform you how much memory is required to solve the problem and to give you some indicators of numerical stability.
In general, you are advised to choose the BDF option (setup routine D02NVF) but if efficiency is of great importance and especially if it is suspected that ∂ ∂y A-1 g has complex eigenvalues near the imaginary axis for some part of the integration, you should try the BLEND option (setup routine D02NWF).

10 Example

This example solves the well-known stiff Robertson problem written as a mixed differential/algebraic system in implicit form
r 1 = a+b+c-1.0 r 2 = 0.04 a-1.0 E 4 bc-3.0 E 7⁢b 2-b′ r 3 = 0.04 a-1.0 E 4 bc-3.0 E 7⁢b 2-c′
exploiting the fact that, from the initial conditions a=1.0 and b=c=0.0, we know that a+b+c=1 for all time. We integrate over the range 0,10.0 with vector relative error control and scalar absolute error control (ITOL=3) and using the BDF integrator (setup routine D02NVF) and a modified Newton method. The Jacobian is evaluated, in turn, using the 'A' (Analytical) and 'F' (Full information) options. We provide a monitor routine to terminate the integration when the value of the component a falls below 0.9.

10.1 Program Text

Program Text (d02njfe.f90)

10.2 Program Data

Program Data (d02njfe.d)

10.3 Program Results

Program Results (d02njfe.r)

GnuplotProduced by GNUPLOT 4.6 patchlevel 3 0 0.2 0.4 0.6 0.8 1 1.2 0.001 0.01 0.1 1 10 0.00000 0.00001 0.00001 0.00002 0.00002 0.00003 0.00003 0.00004 Solution (a,c) Solution (b) x(logscale) Example Program Stiff DAE with Sparse Jacobian Stiff Robertson Problem using BDF with Newton Iterations a b c gnuplot_plot_1 gnuplot_plot_2 gnuplot_plot_3
D02 Chapter Contents
D02 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


D02NMF : NAG Library, Mark 26

D02 Chapter Contents
D02 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

D02NMF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

D02NMF is a reverse communication routine for integrating stiff systems of explicit ordinary differential equations.

2 Specification

SUBROUTINE D02NMF ( NEQ, LDYSAV, T, TOUT, Y, YDOT, RWORK, RTOL, ATOL, ITOL, INFORM, YSAV, SDYSAV, WKJAC, NWKJAC, JACPVT, NJCPVT, IMON, INLN, IRES, IREVCM, ITASK, ITRACE, IFAIL)
INTEGER | NEQ, LDYSAV, ITOL, INFORM(23), SDYSAV, NWKJAC, JACPVT(NJCPVT), NJCPVT, IMON, INLN, IRES, IREVCM, ITASK, ITRACE, IFAIL
REAL (KIND=nag_wp) | T, TOUT, Y(NEQ), YDOT(NEQ), RWORK(50+4*NEQ), RTOL(*), ATOL(*), YSAV(LDYSAV,SDYSAV), WKJAC(NWKJAC)

3 Description

D02NMF is a general purpose routine for integrating the initial value problem for a stiff system of explicit ordinary differential equations,
y′=g t,y.
An outline of a typical calling program is given below:
!     Declarations

      call linear algebra setup routine
      call integrator setup routine
      IREVCM=0
 1000 CALL D02NMF(NEQ, LDYSAV, T, TOUT, Y, YDOT, RWORK, RTOL,           &
                    ATOL, ITOL, INFORM, YSAVE, SDYSAV, WKJAC, NWKJAC,     &
               JACPVT, NJCPVT, IMON, INLN, IRES, IREVCM, ITASK,      &
          ITRACE, IFAIL)
      IF (IREVCM.GT.0) THEN
        IF (IREVCM. EQ. 8) THEN
          supply the Jacobian matrix                                  (i)
        ELSE IF(IREVCM.EQ.9) THEN
          perform monitoring tasks requested by the user             (ii)
        ELSE IF(IRECVM.EQ.1.OR.IREVCM.GE.3.AND.IREVCM.LE.5) THEN
          evaluate the derivative                                   (iii)
        ELSE IF(IREVCM.EQ.10) THEN
          indicates an unsuccessful step
        ENDIF
        GO TO 1000
      ENDIF

!     post processing (optional linear algebra diagnostic call
!     (sparse case only), optional integrator diagnostic call)

      STOP
      END
There are three major operations that may be required of the calling (sub)program on an intermeditate return (IREVCM≠0) from D02NMF; these are denoted (i), (ii) and (iii) above.
The following sections describe in greater detail exactly what is required of each of these operations.
(i) Supply the Jacobian Matrix
You need only provide this facility if the argument JCEVAL='A' (or JCEVAL='F' if using sparse matrix linear algebra) in a call to the linear algebra setup routine (see JCEVAL in D02NSF). If the Jacobian matrix is to be evaluated numerically by the integrator, then the remainder of section (i) can be ignored.
We must define the system of nonlinear equations which is solved internally by the integrator. The time derivative, y′, has the form
y′=y-z/hd,
where h is the current step size and d is an argument that depends on the integration method in use. The vector y is the current solution and the vector z depends on information from previous time steps. This means that d d y′ ​ ​ = hd d dy ​ ​ .
The system of nonlinear equations that is solved has the form
y′-g t,y=0
but is solved in the form
r t,y=0,
where the function r is defined by
r t,y=hdy-z/hd-g t,y.
It is the Jacobian matrix ∂r ∂y that you must supply as follows:
∂ri ∂yj =1-hd ∂gi ∂yj if ​i=j, ∂ri ∂yj =0-hd ∂gi ∂yj otherwise,
where t, h and d are located in RWORK 19, RWORK 16 and RWORK 20 respectively and the array Y contains the current values of the dependent variables. Only the nonzero elements of the Jacobian need be set, since the locations where it is to be stored are preset to zero.
Hereafter in this document this operation will be referred to as JAC.
(ii) Perform Tasks Requested by You
This operation is essentially a monitoring function and additionally provides the opportunity of changing the current values of Y, HNEXT (the step size that the integrator proposes to take on the next step), HMIN (the minimum step size to be taken on the next step), and HMAX (the maximum step size to be taken on the next step). The scaled local error at the end of a timestep may be obtained by calling real function D02ZAF as follows:
      IFAIL = 1
      ERRLOC = D02ZAF(NEQ,RWORK(51+NEQ),RWORK(51),IFAIL)
!     CHECK IFAIL BEFORE PROCEEDING
The following gives details of the location within the array RWORK of variables that may be of interest to you:
Variable | Specification | Location
TCURR | the current value of the independent variable | RWORK 19
HLAST | last step size successfully used by the integrator | RWORK 15
HNEXT | step size that the integrator proposes to take on the next step | RWORK 16
HMIN | minimum step size to be taken on the next step | RWORK 17
HMAX | maximum step size to be taken on the next step | RWORK 18
NQU | the order of the integrator used on the last step | RWORK 10
You are advised to consult the description of MONITR in D02NBF for details on what optional input can be made.
If Y is changed, then IMON must be set to 2 before return to D02NMF. If either of the values of HMIN or HMAX are changed, then IMON must be set ≥3 before return to D02NMF. If HNEXT is changed, then IMON must be set to 4 before return to D02NMF.
In addition you can force D02NMF to evaluate the residual vector
y′-g t,y
by setting IMON=0 and INLN=3 and then returning to D02NMF; on return to this monitoring operation the residual vector will be stored in RWORK 50+2×NEQ+i, for i=1,2,…,NEQ.
Hereafter in this document this operation will be referred to as MONITR.
(iii) Evaluate the Derivative
This operation must evaluate the derivative vector for the explicit ordinary differential equation system defined by
y′=g t,y,
where t is located in RWORK 19.
Hereafter in this document this operation will be referred to as FCN.

4 References

See the D02M–N Sub-chapter Introduction.

5 Arguments

Note: this routine uses reverse communication. Its use involves an initial entry, intermediate exits and re-entries, and a final exit, as indicated by the argument IREVCM. Between intermediate exits and re-entries, all arguments other than YDOT, RWORK, WKJAC, IMON, INLN and IRES must remain unchanged.
1:   NEQ – INTEGERInput
On initial entry: the number of differential equations to be solved.
Constraint: NEQ≥1.
2:   LDYSAV – INTEGERInput
On initial entry: an upper bound on the maximum number of differential equations to be solved during the integration.
Constraint: LDYSAV≥NEQ.
3:   T – REAL (KIND=nag_wp)Input/Output
On initial entry: t, the value of the independent variable. The input value of T is used only on the first call as the initial point of the integration.
On final exit: the value at which the computed solution y is returned (usually at TOUT).
4:   TOUT – REAL (KIND=nag_wp)Input
On initial entry: the next value of t at which a computed solution is desired. For the initial t, the input value of TOUT is used to determine the direction of integration. Integration is permitted in either direction (see also ITASK).
Constraint: TOUT≠T.
5:   Y NEQ – REAL (KIND=nag_wp) arrayInput/Output
On initial entry: the values of the dependent variables (solution). On the first call the first NEQ elements of y must contain the vector of initial values.
On final exit: the computed solution vector evaluated at T (usually t=TOUT).
6:   YDOT NEQ – REAL (KIND=nag_wp) arrayInput/Output
On intermediate re-entry: must be set to the derivatives as defined under the description of IREVCM.
On final exit: the time derivatives y′ of the vector y at the last integration point.
7:   RWORK 50+4×NEQ – REAL (KIND=nag_wp) arrayCommunication Array
On initial entry: must be the same array as used by one of the method setup routines D02MVF, D02NVF or D02NWF, and by one of the storage setup routines D02NTF, D02NUF or D02NVF. The contents of RWORK must not be changed between any call to a setup routine and the first call to D02NMF.
On intermediate re-entry: elements of RWORK must be set to quantities as defined under the description of IREVCM.
On intermediate exit: contains information for JAC, FCN and MONITR operations as described in Section 3 and the argument IREVCM.
8:   RTOL* – REAL (KIND=nag_wp) arrayInput
Note: the dimension of the array RTOL must be at least 1 if ITOL=1 or 2, and at least NEQ otherwise.
On initial entry: the relative local error tolerance.
Constraint: RTOL i≥0.0 for all relevant i (see ITOL).
9:   ATOL* – REAL (KIND=nag_wp) arrayInput
Note: the dimension of the array ATOL must be at least 1 if ITOL=1 or 3, and at least NEQ otherwise.
On initial entry: the absolute local error tolerance.
Constraint: ATOL i≥0.0 for all relevant i (see ITOL).
10:   ITOL – INTEGERInput
On initial entry: a value to indicate the form of the local error test. ITOL indicates to D02NMF whether to interpret either or both of RTOL or ATOL as a vector or a scalar. The error test to be satisfied is ei/wi<1.0, where wi is defined as follows:
ITOL | RTOL | ATOL | wi
1 | scalar | scalar | RTOL 1×yi+ATOL 1
2 | scalar | vector | RTOL 1×yi+ATOL i
3 | vector | scalar | RTOL i×yi+ATOL 1
4 | vector | vector | RTOL i×yi+ATOL i
ei is an estimate of the local error in yi, computed internally, and the choice of norm to be used is defined by a previous call to an integrator setup routine.
Constraint: ITOL=1, 2, 3 or 4.
11:   INFORM 23 – INTEGER arrayCommunication Array
12:   YSAV LDYSAVSDYSAV – REAL (KIND=nag_wp) arrayCommunication Array
13:   SDYSAV – INTEGERInput
On initial entry: the second dimension of the array YSAV as declared in the (sub)program from which D02NMF is called. An appropriate value for SDYSAV is described in the specifications of the integrator setup routines D02NVF and D02NWF. This value must be the same as that supplied to the integrator setup routine.
14:   WKJAC NWKJAC – REAL (KIND=nag_wp) arrayInput/Output
On intermediate re-entry: elements of the Jacobian as defined under the description of IREVCM. If a numerical Jacobian was requested then WKJAC is used for workspace.
On intermediate exit: the Jacobian is overwritten.
15:   NWKJAC – INTEGERInput
On initial entry: the dimension of the array WKJAC as declared in the (sub)program from which D02NMF is called. The actual size depends on the linear algebra method used. An appropriate value for NWKJAC is described in the specifications of the linear algebra setup routines D02NSF, D02NTF and D02NUF for full, banded and sparse matrix linear algebra respectively. This value must be the same as that supplied to the linear algebra setup routine.
16:   JACPVT NJCPVT – INTEGER arrayCommunication Array
17:   NJCPVT – INTEGERInput
On initial entry: the dimension of the array JACPVT as declared in the (sub)program from which D02NMF is called. The actual size depends on the linear algebra method used. An appropriate value for NJCPVT is described in the specifications of the linear algebra setup routines D02NTF and D02NUF for banded and sparse matrix linear algebra respectively. This value must be the same as that supplied to the linear algebra setup routine. When full matrix linear algebra is chosen, the array JACPVT is not used and hence NJCPVT should be set to 1.
18:   IMON – INTEGERInput/Output
On intermediate exit: used to pass information between D02NMF and the MONITR operation (see Section 3). With IREVCM=9, IMON contains a flag indicating under what circumstances the return from D02NMF occurred:
IMON=-2
Exit from D02NMF after IRES=4 caused an early termination (this facility could be used to locate discontinuities).
IMON=-1
The current step failed repeatedly.
IMON=0
Exit from D02NMF after a call to the internal nonlinear equation solver.
IMON=1
The current step was successful.
On intermediate re-entry: may be reset to determine subsequent action in D02NMF.
IMON=-2
Integration is to be halted. A return will be made from D02NMF to the calling (sub)program with IFAIL=12.
IMON=-1
Allow D02NMF to continue with its own internal strategy. The integrator will try up to three restarts unless IMON≠-1.
IMON=0
Return to the internal nonlinear equation solver, where the action taken is determined by the value of INLN.
IMON=1
Normal exit to D02NMF to continue integration.
IMON=2
Restart the integration at the current time point. The integrator will restart from order 1 when this option is used. The solution Y, provided by the MONITR operation (see Section 3), will be used for the initial conditions.
IMON=3
Try to continue with the same step size and order as was to be used before entering the MONITR operation (see Section 3). HMIN and HMAX may be altered if desired.
IMON=4
Continue the integration but using a new value of HNEXT and possibly new values of HMIN and HMAX.
19:   INLN – INTEGERInput/Output
On intermediate re-entry: with IMON=0 and IREVCM=9, INLN specifies the action to be taken by the internal nonlinear equation solver. By setting INLN=3 and returning to D02NMF, the residual vector is evaluated and placed in RWORK 50+2×NEQ+i, for i=1,2,…,NEQ and then the MONITR operation (see Section 3) is invoked again. At present this is the only option available: INLN must not be set to any other value.
On intermediate exit: contains a flag indicating the action to be taken, if any, by the internal nonlinear equation solver.
20:   IRES – INTEGERInput/Output
On intermediate exit: with IREVCM=1, 2, 3, 4 or 5, IRES contains the value 1.
On intermediate re-entry: should be unchanged unless one of the following actions is required of D02NMF in which case IRES should be set accordingly.
IRES=2
Indicates to D02NMF that control should be passed back immediately to the calling (sub)program with the error indicator set to IFAIL=11.
IRES=3
Indicates to D02NMF that an error condition has occurred in the solution vector, its time derivative or in the value of t. The integrator will use a smaller time step to try to avoid this condition. If this is not possible D02NMF returns to the calling (sub)program with the error indicator set to IFAIL=7.
IRES=4
Indicates to D02NMF to stop its current operation and to enter the MONITR operation (see Section 3) immediately.
21:   IREVCM – INTEGERInput/Output
On initial entry: must contain 0.
On intermediate re-entry: should remain unchanged.
On intermediate exit: indicates what action you must take before re-entering. The possible exit values of IREVCM are 1, 3, 4, 5, 8, 9 or 10, which should be interpreted as follows:
IREVCM=1, 3, 4 and 5
Indicates that an FCN operation (see Section 3) is required: y′=g t,y must be supplied, where Y i is located in yi, for i=1,2,…,NEQ.
For IREVCM=1 or 3, yi′ should be placed in location RWORK 50+2×NEQ+i, for i=1,2,…,NEQ.
For IREVCM=4, yi′ should be placed in location RWORK 50+NEQ+i, for i=1,2,…,NEQ.
For IREVCM=5, yi′ should be placed in location YDOT i, for i=1,2,…,NEQ.
IREVCM=8
Indicates that a JAC operation (see Section 3) is required: the Jacobian matrix must be supplied.
If full matrix linear algebra is being used, then the i,jth element of the Jacobian must be stored in WKJAC j-1×NEQ+i.
If banded matrix linear algebra is being used then the i,jth element of the Jacobian
must be stored in WKJAC i-1×mB+k, where mB=mL+mU+1 and
k=min mL-i+1,0+j; here mL and mU are the number of subdiagonals and superdiagonals, respectively, in the band.
If sparse matrix linear algebra is being used then D02NRF must be called to determine which column of the Jacobian is required and where it should be stored.
 CALL D02NRF(J, IPLACE, INFORM)
will return in J the number of the column of the Jacobian that is required and will set IPLACE=1 or 2. If IPLACE=1, then the i,jth element of the Jacobian must be stored in RWORK 50+2×NEQ+i; otherwise it must be stored in RWORK 50+NEQ+i.
IREVCM=9
Indicates that a MONITR operation (see Section 3) can be performed.
IREVCM=10
Indicates that the current step was not successful, due to error test failure or convergence test failure. The only information supplied to you on this return is the current value of the independent variable t, located in RWORK 19. No values must be changed before re-entering D02NMF; this facility enables you to determine the number of unsuccessful steps.
On final exit: IREVCM=0 indicated the user-specified task has been completed or an error has been encountered (see the descriptions for ITASK and IFAIL).
Constraint: IREVCM=0, 1, 3, 4, 5, 8, 9 or 10.
22:   ITASK – INTEGERInput
On initial entry: the task to be performed by the integrator.
ITASK=1
Normal computation of output values of y t at t=TOUT (by overshooting and interpolating).
ITASK=2
Take one step only and return.
ITASK=3
Stop at the first internal integration point at or beyond t=TOUT and return.
ITASK=4
Normal computation of output values of y t at t=TOUT but without overshooting t=TCRIT. TCRIT must be specified as an option in one of the integrator setup routines before the first call to the integrator, or specified in the optional input routine before a continuation call. TCRIT (e.g., see D02NVF) may be equal to or beyond TOUT, but not before it in the direction of integration.
ITASK=5
Take one step only and return, without passing TCRIT (e.g., see D02NVF). TCRIT must be specified under ITASK=4.
Constraint: 1≤ITASK≤5.
23:   ITRACE – INTEGERInput
On initial entry: the level of output that is printed by the integrator. ITRACE may take the value -1, 0, 1, 2 or 3.
ITRACE<-1
-1 is assumed and similarly if ITRACE>3, then 3 is assumed.
ITRACE=-1
No output is generated.
ITRACE=0
Only warning messages are printed on the current error message unit (see X04AAF).
ITRACE>0
Warning messages are printed as above, and on the current advisory message unit (see X04ABF) output is generated which details Jacobian entries, the nonlinear iteration and the time integration. The advisory messages are given in greater detail the larger the value of ITRACE.
24:   IFAIL – INTEGERInput/Output
On initial entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, because for this routine the values of the output arguments may be useful even if IFAIL≠0 on exit, the recommended value is -1. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On final exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, the integrator detected an illegal input, or that a linear algebra and/or integrator setup routine has not been called prior to the call to the integrator. If ITRACE≥0, the form of the error will be detailed on the current error message unit (see X04AAF).
IFAIL=2
The maximum number of steps specified has been taken (see the description of optional inputs in the integrator setup routines and the optional input continuation routine, D02NZF).
IFAIL=3
With the given values of RTOL and ATOL no further progress can be made across the integration range from the current point T. The components Y 1,Y 2,…,Y NEQ contain the computed values of the solution at the current point T.
IFAIL=4
There were repeated error test failures on an attempted step, before completing the requested task, but the integration was successful as far as T. The problem may have a singularity, or the local error requirements may be inappropriate.
IFAIL=5
There were repeated convergence test failures on an attempted step, before completing the requested task, but the integration was successful as far as T. This may be caused by an inaccurate Jacobian matrix or one which is incorrectly computed.
IFAIL=6
Some error weight wi became zero during the integration (see the description of ITOL). Pure relative error control ATOL i=0.0 was requested on a variable (the ith) which has now vanished. The integration was successful as far as T.
IFAIL=7
The FCN operation (see Section 3) set the error flag IRES=3 continually despite repeated attempts by the integrator to avoid this.
IFAIL=8
Not used for this integrator.
IFAIL=9
A singular Jacobian ∂r ∂y has been encountered. This error exit is unlikely to be taken when solving explicit ordinary differential equations. You should check the problem formulation and Jacobian calculation.
IFAIL=10
An error occurred during Jacobian formulation or back-substitution (a more detailed error description may be directed to the current error message unit, see X04AAF).
IFAIL=11
The FCN operation (see Section 3) signalled the integrator to halt the integration and return by setting IRES=2. Integration was successful as far as T.
IFAIL=12
The MONITR operation (see Section 3) set IMON=-2 and so forced a return but the integration was successful as far as T.
IFAIL=13
The requested task has been completed, but it is estimated that a small change in RTOL and ATOL is unlikely to produce any change in the computed solution. (Only applies when you are not operating in one step mode, that is when ITASK≠2 or 5.)
IFAIL=14
The values of RTOL and ATOL are so small that D02NMF is unable to start the integration.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

The accuracy of the numerical solution may be controlled by a careful choice of the arguments RTOL and ATOL, and to a much lesser extent by the choice of norm. You are advised to use scalar error control unless the components of the solution are expected to be poorly scaled. For the type of decaying solution typical of many stiff problems, relative error control with a small absolute error threshold will be most appropriate (that is, you are advised to choose ITOL=1 with ATOL 1 small but positive).

8 Parallelism and Performance

D02NMF is not thread safe and should not be called from a multithreaded user program. Please see Section 3.12.1 in How to Use the NAG Library and its Documentation for more information on thread safety.
D02NMF is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
D02NMF makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The cost of computing a solution depends critically on the size of the differential system and to a lesser extent on the degree of stiffness of the problem; also on the type of linear algebra being used. For further details see Section 9 of the documents for D02NBF (full matrix), D02NCF (banded matrix) or D02NDF (sparse matrix).
In general, you are advised to choose the backward differentiation formula option (setup routine D02NVF) but if efficiency is of great importance and especially if it is suspected that ∂g ∂y has complex eigenvalues near the imaginary axis for some part of the integration, you should try the BLEND option (setup routine D02NWF).

10 Example

This example solves the well-known stiff Robertson problem
a′ = -0.04 a+1.0E4 bc-3.0E7⁢b 2 b′ = -0.04 a-1.0E4 bc-3.0E7⁢b 2 c′ = -0.04 a-1.0E4 bc-3.0E7⁢b 2
over the range 0,10 with initial conditions a=1.0 and b=c=0.0 and with scalar error control (ITOL=1). The integration proceeds until TOUT=10.0 is passed, providing C 1 interpolation at intervals of 2.0 through a MONITR operation. The integration method used is the BDF method (setup routine D02NVF) with a modified Newton method. The Jacobian is a full matrix, which is specified using the setup routine D02NSF; this Jacobian is to be calculated numerically.

10.1 Program Text

Program Text (d02nmfe.f90)

10.2 Program Data

Program Data (d02nmfe.d)

10.3 Program Results

Program Results (d02nmfe.r)

GnuplotProduced by GNUPLOT 4.6 patchlevel 3 0 0.2 0.4 0.6 0.8 1 1.2 0.0001 0.001 0.01 0.1 1 10 0 5e−06 1e−05 1.5e−05 2e−05 2.5e−05 3e−05 3.5e−05 4e−05 Solution (a,c) Solution (b) x(logscale) Example Program Stiff Explicit ODE, Reverse Communication Stiff Robertson Problem using BDF with Newton Iterations a b c gnuplot_plot_1 gnuplot_plot_2 gnuplot_plot_3
D02 Chapter Contents
D02 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


D02NNF : NAG Library, Mark 26

D02 Chapter Contents
D02 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

D02NNF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

D02NNF is a reverse communication routine for integrating stiff systems of implicit ordinary differential equations coupled with algebraic equations.

2 Specification

SUBROUTINE D02NNF ( NEQ, LDYSAV, T, TOUT, Y, YDOT, RWORK, RTOL, ATOL, ITOL, INFORM, YSAV, SDYSAV, WKJAC, NWKJAC, JACPVT, NJCPVT, IMON, INLN, IRES, IREVCM, LDERIV, ITASK, ITRACE, IFAIL)
INTEGER | NEQ, LDYSAV, ITOL, INFORM(23), SDYSAV, NWKJAC, JACPVT(NJCPVT), NJCPVT, IMON, INLN, IRES, IREVCM, ITASK, ITRACE, IFAIL
REAL (KIND=nag_wp) | T, TOUT, Y(NEQ), YDOT(NEQ), RWORK(50+4*NEQ), RTOL(*), ATOL(*), YSAV(LDYSAV,SDYSAV), WKJAC(NWKJAC)
LOGICAL | LDERIV(2)

3 Description

D02NNF is a general purpose routine for integrating the initial value problem for a stiff system of implicit ordinary differential equations coupled with algebraic equations, written in the form
A t,y y′=g t,y.
An outline of a typical calling program is given below:
!     Declarations

      call linear algebra setup routine
      call integrator setup routine
      IREVCM=0
 1000 CALL D02NNF(NEQ, NEQMAX, T, TOUT, Y, YDOT, RWORK, RTOL,
       ATOL, ITOL, INFORM, YSAVE, NY2DIM, WKJAC, NWKJAC, JACPVT,
       NJCPVT, IMON, INLN, IRES, IREVCM, LDERIV,
       ITASK, ITRACE, IFAIL)

      IF (IREVCM.GT.0) THEN
        IF (IREVCM.GT.7 .AND. IREVCM.LT.11) THEN
          IF (IREVCM.EQ.8) THEN
            supply the Jacobian matrix                        (i)
          ELSE IF (IREVCM.EQ.9) THEN
            perform monitoring tasks requested by the user   (ii)
          ELSE IF (IREVCM.EQ.10) THEN
            indicates an unsuccessful step
          END IF
        ELSE
          evaluate the residual                             (iii)
        ENDIF
        GO TO 1000
      END IF

!     post processing (optional linear algebra diagnostic call
!     (sparse case only), optional integrator diagnostic call)

      STOP
      END
There are three major operations that may be required of the calling subroutine on an intermediate return (IREVCM≠0) from D02NNF; these are denoted (i), (ii) and (iii).
The following sections describe in greater detail exactly what is required of each of these operations.
(i) Supply the Jacobian matrix
You need only provide this facility if the argument JCEVAL='A' (or JCEVAL='F' if using sparse matrix linear algebra) in a call to the linear algebra setup routine (see JCEVAL in D02NUF). If the Jacobian matrix is to be evaluated numerically by the integrator, then the remainder of section (i) can be ignored.
We must define the system of nonlinear equations which is solved internally by the integrator. The time derivative, y′, has the form
y′=y-z/hd,
where h is the current step size and d is an argument that depends on the integration method in use. The vector y is the current solution and the vector z depends on information from previous time steps. This means that d d y′ ​ ​ = hd d dy ​ ​ .
The system of nonlinear equations that is solved has the form
A t,y y′-g t,y=0
but is solved in the form
f t,y = 0 ,
where f is the function defined by
f t,y = hd A t,y y-z / hd - g t,y .
It is the Jacobian matrix ∂r ∂y that you must supply as follows:
∂fi ∂yj = a ij t,y+hd ∂∂yj ∑k=1 NEQ a ik t,y y′k-gi t,y ,
where t, h and d are located in RWORK 19, RWORK 16 and RWORK 20 respectively and the arrays Y and YDOT contain the current solution and time derivatives respectively. Only the nonzero elements of the Jacobian need be set, since the locations where it is to be stored are preset to zero.
Hereafter in this document this operation will be referred to as JAC.
(ii) Perform tasks requested by you
This operation is essentially a monitoring function and additionally provides the opportunity of changing the current values of Y, YDOT, HNEXT (the step size that the integrator proposes to take on the next step), HMIN (the minimum step size to be taken on the next step), and HMAX (the maximum step size to be taken on the next step). The scaled local error at the end of a time step may be obtained by calling the real function D02ZAF as follows:
      IFAIL = 1
      ERRLOC = D02ZAF(NEQ,ROWK(51+NEQMAX),RWORK(51),IFAIL)
!     CHECK IFAIL BEFORE PROCEEDING
The following gives details of the location within the array RWORK of variables that may be of interest to you:
Variable | Specification | Location
TCURR | the current value of the independent variable | RWORK 19
HLAST | last step size successfully used by the integrator | RWORK 15
HNEXT | step size that the integrator proposes to take on the next step | RWORK 16
HMIN | minimum step size to be taken on the next step | RWORK 17
HMAX | maximum step size to be taken on the next step | RWORK 18
NQU | the order of the integrator used on the last step | RWORK 10
You are advised to consult the description of MONITR in D02NGF for details on what optional input can be made.
If either Y or YDOT are changed, then IMON must be set to 2 before return to D02NNF. If either of the values HMIN or HMAX are changed, then IMON must be set ≥3 before return to D02NNF. If HNEXT is changed, then IMON must be set to 4 before return to D02NNF.
In addition you can force D02NNF to evaluate the residual vector
A t,y y′-g t,y
by setting IMON=0 and INLN=3 and then returning to D02NNF; on return to this monitoring operation the residual vector will be stored in RWORK 50+2×NEQ+i, for i=1,2,…,NEQ.
Hereafter in this document this operation will be referred to as MONITR.
(iii) Evaluate the residual
This operation must evaluate the residual
-r = g t,y - A t,y y′ (1)
in one case and the reduced residual
-r^ = -A t,y y′ (2)
in another, where t is located in RWORK 19. The form of the residual that is returned is determined by the value of IRES returned by D02NNF. If IRES=-1, then the residual defined by equation (2) above must be returned; if IRES=1, then the residual returned by equation (1) above must be returned.
Hereafter in this document this operation will be referred to as RESID.

4 References

See the D02M–N Sub-chapter Introduction.

5 Arguments

Note: this routine uses reverse communication. Its use involves an initial entry, intermediate exits and re-entries, and a final exit, as indicated by the argument IREVCM. Between intermediate exits and re-entries, all arguments other than YDOT, RWORK, WKJAC, IMON, INLN and IRES must remain unchanged.
1:   NEQ – INTEGERInput
On initial entry: the number of equations to be solved.
Constraint: NEQ≥1.
2:   LDYSAV – INTEGERInput
On initial entry: a bound on the maximum number of equations to be solved during the integration.
Constraint: LDYSAV≥NEQ.
3:   T – REAL (KIND=nag_wp)Input/Output
On initial entry: t, the value of the independent variable. The input value of T is used only on the first call as the initial point of the integration.
On final exit: the value at which the computed solution y is returned (usually at TOUT).
4:   TOUT – REAL (KIND=nag_wp)Input/Output
On initial entry: the next value of t at which a computed solution is desired. For the initial t, the input value of TOUT is used to determine the direction of integration. Integration is permitted in either direction (see also ITASK).
Constraint: TOUT≠T.
On exit: is unaltered unless ITASK=6 and LDERIV 2=.TRUE. on entry (see also ITASK and LDERIV) in which case TOUT will be set to the result of taking a small step at the start of the integration.
5:   Y NEQ – REAL (KIND=nag_wp) arrayInput/Output
On initial entry: the values of the dependent variables (solution). On the first call the first NEQ elements of y must contain the vector of initial values.
On final exit: the computed solution vector evaluated at T (usually t=TOUT).
6:   YDOT NEQ – REAL (KIND=nag_wp) arrayInput/Output
On initial entry: if LDERIV 1=.TRUE., YDOT must contain approximations to the time derivatives y′ of the vector y. If LDERIV 1=.FALSE., then YDOT need not be set on entry.
On final exit: contains the time derivatives y′ of the vector y at the last integration point.
7:   RWORK 50+4×NEQ – REAL (KIND=nag_wp) arrayCommunication Array
On initial entry: must be the same array as used by one of the method setup routines D02MVF, D02NVF or D02NWF, and by one of the storage setup routines D02NSF, D02NTF or D02NUF. The contents of RWORK must not be changed between any call to a setup routine and the first call to D02NNF.
On intermediate re-entry: must contain residual evaluations as described under the argument IREVCM.
On intermediate exit: contains information for JAC, RESID and MONITR operations as described under Section 3 and the argument IREVCM.
8:   RTOL* – REAL (KIND=nag_wp) arrayInput
Note: the dimension of the array RTOL must be at least 1 if ITOL=1 or 2, and at least NEQ otherwise.
On initial entry: the relative local error tolerance.
Constraint: RTOL i≥0.0 for all relevant i (see ITOL).
9:   ATOL* – REAL (KIND=nag_wp) arrayInput
Note: the dimension of the array ATOL must be at least 1 if ITOL=1 or 3, and at least NEQ otherwise.
On initial entry: the absolute local error tolerance.
Constraint: ATOL i≥0.0 for all relevant i (see ITOL).
10:   ITOL – INTEGERInput
On initial entry: a value to indicate the form of the local error test. ITOL indicates to D02NNF whether to interpret either or both of RTOL or ATOL as a vector or a scalar. The error test to be satisfied is ei/wi<1.0, where wi is defined as follows:
ITOL | RTOL | ATOL | wi
1 | scalar | scalar | RTOL 1×yi+ATOL 1
2 | scalar | vector | RTOL 1×yi+ATOL i
3 | vector | scalar | RTOL i×yi+ATOL 1
4 | vector | vector | RTOL i×yi+ATOL i
ei is an estimate of the local error in yi, computed internally, and the choice of norm to be used is defined by a previous call to an integrator setup routine.
Constraint: ITOL=1, 2, 3 or 4.
11:   INFORM 23 – INTEGER arrayCommunication Array
12:   YSAV LDYSAVSDYSAV – REAL (KIND=nag_wp) arrayCommunication Array
13:   SDYSAV – INTEGERInput
On initial entry: the second dimension of the array YSAV as declared in the (sub)program from which D02NNF is called. An appropriate value for SDYSAV is described in the specifications of the integrator setup routines D02MVF, D02NVF and D02NWF. This value must be the same as that supplied to the integrator setup routine.
14:   WKJAC NWKJAC – REAL (KIND=nag_wp) arrayInput/Output
On intermediate re-entry: elements of the Jacobian as defined under the description of IREVCM. If a numerical Jacobian was requested then WKJAC is used for workspace.
On intermediate exit: the Jacobian is overwritten.
15:   NWKJAC – INTEGERInput
On initial entry: the dimension of the array WKJAC as declared in the (sub)program from which D02NNF is called. The actual size depends on the linear algebra method used. An appropriate value for NWKJAC is described in the specifications of the linear algebra setup routines D02NSF, D02NTF and D02NUF for full, banded and sparse matrix linear algebra respectively. This value must be the same as that supplied to the linear algebra setup routine.
16:   JACPVT NJCPVT – INTEGER arrayCommunication Array
17:   NJCPVT – INTEGERInput
On initial entry: the dimension of the array JACPVT as declared in the (sub)program from which D02NNF is called. The actual size depends on the linear algebra method used. An appropriate value for NJCPVT is described in the specifications of the linear algebra setup routines D02NTF and D02NUF for banded and sparse matrix linear algebra respectively. This value must be the same as that supplied to the linear algebra setup routine. When full matrix linear algebra is chosen, the array JACPVT is not used and hence NJCPVT should be set to 1.
18:   IMON – INTEGERInput/Output
On intermediate exit: used to pass information between D02NNF and the MONITR operation (see Section 3). With IREVCM=9, IMON contains a flag indicating under what circumstances the return from D02NNF occurred:
IMON=-2
Exit from D02NNF after IRES=4 (set in the RESID operation (see Section 3) caused an early termination (this facility could be used to locate discontinuities).
IMON=-1
The current step failed repeatedly.
IMON=0
Exit from D02NNF after a call to the internal nonlinear equation solver.
IMON=1
The current step was successful.
On intermediate re-entry: may be reset to determine subsequent action in D02NNF.
IMON=-2
Integration is to be halted. A return will be made from D02NNF to the calling (sub)program with IFAIL=12.
IMON=-1
Allow D02NNF to continue with its own internal strategy. The integrator will try up to three restarts unless IMON≠-1.
IMON=0
Return to the internal nonlinear equation solver, where the action taken is determined by the value of INLN.
IMON=1
Normal exit to D02NNF to continue integration.
IMON=2
Restart the integration at the current time point. The integrator will restart from order 1 when this option is used. The internal initialization module solves for new values of y and y′ by using the values supplied in Y and YDOT by the MONITR operation (see Section 3) as initial estimates.
IMON=3
Try to continue with the same step size and order as was to be used before entering the MONITR operation (see Section 3). HMIN and HMAX may be altered if desired.
IMON=4
Continue the integration but using a new value of HNEXT and possibly new values of HMIN and HMAX.
19:   INLN – INTEGERInput/Output
On intermediate re-entry: with IMON=0 and IREVCM=9, INLN specifies the action to be taken by the internal nonlinear equation solver. By setting INLN=3 and returning to D02NNF, the residual vector is evaluated and placed in RWORK 50+2×NEQ+i, for i=1,2,…,NEQ and then the MONITR operation (see Section 3) is invoked again. At present this is the only option available: INLN must not be set to any other value.
On intermediate exit: contains a flag indicating the action to be taken, if any, by the internal nonlinear equation solver.
20:   IRES – INTEGERInput/Output
On intermediate exit: with IREVCM=1, 2, 3, 4, 5, 6, 7 or 11, IRES specifies the form of the residual to be returned by the RESID operation (see Section 3).
If IRES=1, then -r=g t,y-A t,y y′ must be returned.
If IRES=-1, then -r^=-A t,y y′ must be returned.
On intermediate re-entry: should be unchanged unless one of the following actions is required of D02NNF in which case IRES should be set accordingly.
IRES=2
Indicates to D02NNF that control should be passed back immediately to the calling (sub)program with the error indicator set to IFAIL=11.
IRES=3
Indicates to D02NNF that an error condition has occurred in the solution vector, its time derivative or in the value of t. The integrator will use a smaller time step to try to avoid this condition. If this is not possible D02NNF returns to the calling (sub)program with the error indicator set to IFAIL=7.
IRES=4
Indicates to D02NNF to stop its current operation and to enter the MONITR operation (see Section 3) immediately.
21:   IREVCM – INTEGERInput/Output
On initial entry: must contain 0.
On intermediate re-entry: should remain unchanged.
On intermediate exit: indicates what action you must take before re-entering D02NNF. The possible exit values of IREVCM are 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 or 11 which should be interpreted as follows:
IREVCM=1, 2, 3, 4, 5, 6, 7 or 11
Indicates that a RESID operation (see Section 3) is required: you must supply the residual of the system. For each of these values of IREVCM, yi is located in Y i, for i=1,2,…,NEQ.
For IREVCM=1, 3, 6 or 11, yi′ is located in YDOT i and ri should be stored in RWORK 50+2×NEQ+i, for i=1,2,…,NEQ.
For IREVCM=2, yi′ is located in RWORK 50+NEQ+i and ri should be stored in RWORK 50+2×NEQ+i, for i=1,2,…,NEQ.
For IREVCM=4 or 7, yi′ is located in YDOT i and ri should be stored in RWORK 50+NEQ+i, for i=1,2,…,NEQ.
For IREVCM=5, yi′ is located in RWORK 50+2×NEQ+i and ri should be stored in YDOT i, for i=1,2,…,NEQ.
IREVCM=8
Indicates that a JAC operation (see Section 3) is required: you must supply the Jacobian matrix.
If full matrix linear algebra is being used, then the i,jth element of the Jacobian must be stored in WKJAC j-1×NEQ+i.
If banded matrix linear algebra is being used, then the i,jth element of the Jacobian
must be stored in WKJAC i-1×mB+k, where mB=mL+mU+1 and k=min mL-i+1,0+j; here mL and mU are the number of subdiagonals and superdiagonals, respectively, in the band.
If sparse matrix linear algebra is being used, then D02NRF must be called to determine which column of the Jacobian is required and where it should be stored.
 CALL D02NRF(J, IPLACE, INFORM)
will return in J the number of the column of the Jacobian that is required and will set IPLACE=1 or 2 (see D02NRF). If IPLACE=1, you must store the nonzero element i,j of the Jacobian in RWORK 50+2×NEQ+i; otherwise it must be stored in RWORK 50+NEQ+i.
IREVCM=9
Indicates that a MONITR operation (see Section 3) can be performed.
IREVCM=10
Indicates that the current step was not successful, due to error test failure or convergence test failure. The only information supplied to you on this return is the current value of the variable t, located in RWORK 19. No values must be changed before re-entering D02NNF; this facility enables you to determine the number of unsuccessful steps.
On final exit: IREVCM=0 indicating that the user-specified task has been completed or an error has been encountered (see the descriptions for ITASK and IFAIL).
Constraint: 0≤IREVCM≤11.
22:   LDERIV 2 – LOGICAL arrayInput/Output
On initial entry: LDERIV 1 must be set to .TRUE. if you have supplied both an initial y and an initial y′. LDERIV 1 must be set to .FALSE. if only the initial y has been supplied.
LDERIV 2 must be set to .TRUE. if the integrator is to use a modified Newton method to evaluate the initial y and y′. Note that y and y′, if supplied, are used as initial estimates. This method involves taking a small step at the start of the integration, and if ITASK=6 on entry, T and TOUT will be set to the result of taking this small step. LDERIV 2 must be set to .FALSE. if the integrator is to use functional iteration to evaluate the initial y and y′, and if this fails a modified Newton method will then be attempted. LDERIV 2=.TRUE. is recommended if there are implicit equations or the initial y and y′ are zero.
On final exit: LDERIV 1 is normally unchanged. However if ITASK=6 and internal initialization was successful then LDERIV 1=.TRUE..
LDERIV 2=.TRUE., if implicit equations were detected. Otherwise LDERIV 2=.FALSE..
23:   ITASK – INTEGERInput
On initial entry: the task to be performed by the integrator.
ITASK=1
Normal computation of output values of y t at t=TOUT (by overshooting and interpolating).
ITASK=2
Take one step only and return.
ITASK=3
Stop at the first internal integration point at or beyond t=TOUT and return.
ITASK=4
Normal computation of output values of y t at t=TOUT but without overshooting t=TCRIT. TCRIT must be specified as an option in one of the integrator setup routines before the first call to the integrator, or specified in the optional input routine before a continuation call. TCRIT (e.g., see D02NVF) may be equal to or beyond TOUT, but not before it in the direction of integration.
ITASK=5
Take one step only and return, without passing TCRIT (e.g., see D02NVF). TCRIT must be specified under ITASK=4.
ITASK=6
The integrator will solve for the initial values of y and y′ only and then return to the calling (sub)program without doing the integration. This option can be used to check the initial values of y and y′. Functional iteration or a ‘small’ backward Euler method used in conjunction with a damped Newton iteration is used to calculate these values (see LDERIV). Note that if a backward Euler step is used then the value of t will have been advanced a short distance from the initial point.
Note: if D02NNF is recalled with a different value of ITASK (and TOUT altered) then the initialization procedure is repeated, possibly leading to different initial conditions.
Constraint: 1≤ITASK≤6.
24:   ITRACE – INTEGERInput
On initial entry: the level of output that is printed by the integrator. ITRACE may take the value -1, 0, 1, 2 or 3.
ITRACE<-1
-1 is assumed and similarly if ITRACE>3, then 3 is assumed.
ITRACE=-1
No output is generated.
ITRACE=0
Only warning messages are printed on the current error message unit (see X04AAF).
ITRACE>0
Warning messages are printed as above, and on the current advisory message unit (see X04ABF) output is generated which details Jacobian entries, the nonlinear iteration and the time integration. The advisory messages are given in greater detail the larger the value of ITRACE.
25:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, because for this routine the values of the output arguments may be useful even if IFAIL≠0 on exit, the recommended value is -1. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, the integrator detected an illegal input, or that a linear algebra and/or integrator setup routine has not been called prior to the call to the integrator. If ITRACE≥0, the form of the error will be detailed on the current error message unit (see X04AAF).
IFAIL=2
The maximum number of steps specified has been taken (see the description of optional inputs in the integrator setup routines and the optional input continuation routine, D02NZF).
IFAIL=3
With the given values of RTOL and ATOL no further progress can be made across the integration range from the current point T. The components Y 1,Y 2,…,Y NEQ contain the computed values of the solution at the current point T.
IFAIL=4
There were repeated error test failures on an attempted step, before completing the requested task, but the integration was successful as far as T. The problem may have a singularity, or the local error requirements may be inappropriate.
IFAIL=5
There were repeated convergence test failures on an attempted step, before completing the requested task, but the integration was successful as far as T. This may be caused by an inaccurate Jacobian matrix or one which is incorrectly computed.
IFAIL=6
Some error weight wi became zero during the integration (see the description of ITOL). Pure relative error control (ATOL i=0.0) was requested on a variable (the ith) which has now vanished. The integration was successful as far as T.
IFAIL=7
The RESID operation (see Section 3) set the error flag IRES=3 continually despite repeated attempts by the integrator to avoid this.
IFAIL=8
LDERIV 1=.FALSE. on entry but the internal initialization routine was unable to initialize y′ (more detailed information may be directed to the current error message unit, see X04AAF).
IFAIL=9
A singular Jacobian ∂r ∂y has been encountered. You should check the problem formulation and Jacobian calculation.
IFAIL=10
An error occurred during Jacobian formulation or back-substitution (a more detailed error description may be directed to the current error message unit, see X04AAF).
IFAIL=11
The RESID operation (see Section 3) signalled the integrator to halt the integration and return by setting IRES=2. Integration was successful as far as T.
IFAIL=12
The MONITR operation (see Section 3) set IMON=-2 and so forced a return but the integration was successful as far as T.
IFAIL=13
The requested task has been completed, but it is estimated that a small change in RTOL and ATOL is unlikely to produce any change in the computed solution. (Only applies when you are not operating in one step mode, that is when ITASK≠2 or 5.)
IFAIL=14
The values of RTOL and ATOL are so small that D02NNF is unable to start the integration.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

The accuracy of the numerical solution may be controlled by a careful choice of the arguments RTOL and ATOL, and to a much lesser extent by the choice of norm. You are advised to use scalar error control unless the components of the solution are expected to be poorly scaled. For the type of decaying solution typical of many stiff problems, relative error control with a small absolute error threshold will be most appropriate (that is, you are advised to choose ITOL=1 with ATOL 1 small but positive).

8 Parallelism and Performance

D02NNF is not thread safe and should not be called from a multithreaded user program. Please see Section 3.12.1 in How to Use the NAG Library and its Documentation for more information on thread safety.
D02NNF is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
D02NNF makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The cost of computing a solution depends critically on the size of the differential system and to a lesser extent on the degree of stiffness of the problem; also on the type of linear algebra being used. For further details see Section 9 in D02NGF, D02NHF and D02NJF of the documents for D02NGF (full matrix), D02NHF (banded matrix) or D02NJF (sparse matrix).
In general, you are advised to choose the Backward Differentiation Formula option (setup routine D02NVF) but if efficiency is of great importance and especially if it is suspected that ∂ ∂y A-1 g has complex eigenvalues near the imaginary axis for some part of the integration, you should try the BLEND option (setup routine D02NWF).

10 Example

We solve the well-known stiff Robertson problem written as a differential system in implicit form
r 1=a′+b′+c′ r 2=0.04 a-1.0 E 4 bc-3.0 E 7⁢b 2-b′ r 3=0.04 a-1.0 E 4 bc-3.0 E 7⁢b 2-c′
over the range 0,10 with initial conditions a=1.0 and b=c=0.0 and with scalar error control (ITOL=1). We integrate to the first internal integration point past TOUT=10.0 (ITASK=3), using a BDF method (setup routine D02MVF) and a modified Newton method. We treat the Jacobian as sparse (setup routine D02NUF) and we calculate it analytically. In this program we also illustrate the monitoring of step failures (IREVCM=10) and the forcing of a return when the component falls below 0.9 in the evaluation of the residual by setting IRES=2.

10.1 Program Text

Program Text (d02nnfe.f90)

10.2 Program Data

Program Data (d02nnfe.d)

10.3 Program Results

Program Results (d02nnfe.r)

D02 Chapter Contents
D02 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


D02NPF : NAG Library, Mark 26

D02 Chapter Contents
D02 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

D02NPF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
10 Example

1 Purpose

D02NPF is a setup routine which you must call prior to D02NEF and after a call to D02MWF, if the Jacobian is to be considered as having a banded structure.

2 Specification

SUBROUTINE D02NPF ( NEQ, ML, MU, ICOM, LICOM, IFAIL)
INTEGER NEQ, ML, MU, ICOM(LICOM), LICOM, IFAIL

3 Description

A call to D02NPF specifies that the Jacobian to be used is banded in structure. If D02NPF is not called before a call to D02NEF then the Jacobian is assumed to be full.

4 References

None.

5 Arguments

1:   NEQ – INTEGERInput
On entry: the number of differential-algebraic equations to be solved.
Constraint: 1≤NEQ.
2:   ML – INTEGERInput
On entry: mL, the number of subdiagonals in the band.
Constraint: 0≤ML≤NEQ-1.
3:   MU – INTEGERInput
On entry: mU, the number of superdiagonals in the band.
Constraint: 0≤MU≤NEQ-1.
4:   ICOM LICOM – INTEGER arrayCommunication Array
ICOM is used to communicate details of the integration from D02MWF and details of the banded structure of the Jacobian to D02NEF.
5:   LICOM – INTEGERInput
On entry: the dimension of the array ICOM as declared in the (sub)program from which D02NPF is called.
Constraint: LICOM≥50+NEQ.
6:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, NEQ=value.
Constraint: NEQ≥1.
IFAIL=2
On entry, ML=value.
Constraint: ML≥0.
On entry, ML=value and NEQ=value.
Constraint: ML≤NEQ-1.
IFAIL=3
On entry, MU=value.
Constraint: MU≥0.
On entry, MU=value and NEQ=value.
Constraint: MU≤NEQ-1.
IFAIL=4
Either the initialization routine has not been called prior to the first call of this routine or the communication array has become corrupted.
IFAIL=5
On entry, LICOM is too small: LICOM=value.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

Not applicable.

8 Parallelism and Performance

D02NPF is not threaded in any implementation.

9 Further Comments

None.

10 Example

See Section 10 in D02NEF and D02MWF.
D02 Chapter Contents
D02 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


D02NRF : NAG Library, Mark 26

D02 Chapter Contents
D02 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

D02NRF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
10 Example

1 Purpose

D02NRF is an enquiry routine for communicating with D02NMF or D02NNF when supplying columns of a sparse Jacobian matrix.

2 Specification

SUBROUTINE D02NRF ( J, IPLACE, INFORM)
INTEGER J, IPLACE, INFORM(23)

3 Description

D02NRF is required when D02NMF or D02NNF is being used with sparse matrix linear algebra. After an exit from D02NMF or D02NNF with IREVCM=8, D02NRF must be called to determine which column of the Jacobian is required and where it is to be placed in the array RWORK (a argument of D02NMF or D02NNF).

4 References

See the D02M–N Sub-chapter Introduction.

5 Arguments

1:   J – INTEGEROutput
On exit: the index j of the column of the Jacobian which is required.
2:   IPLACE – INTEGEROutput
On exit: indicates which locations in the array RWORK to fill with the jth column.
If IPLACE=1, the i,jth element of the Jacobian must be placed in RWORK 50+2×LDYSAV+i, otherwise the i,jth element must be placed in RWORK 50+LDYSAV+i.
If JCEVAL='F', in the previous call to D02NUF, then IPLACE=2 always, hence the jth column of the Jacobian must be placed in RWORK 50+LDYSAV+i, for i=1,2,…,NEQ.
RWORK, NEQ and LDYSAV are arguments of D02NMF and D02NNF.
3:   INFORM 23 – INTEGER arrayCommunication Array
On entry: contains information supplied by the integrator.

6 Error Indicators and Warnings

None.

7 Accuracy

Not applicable.

8 Parallelism and Performance

D02NRF is not threaded in any implementation.

9 Further Comments

None.

10 Example

See Section 10 in D02NNF.
D02 Chapter Contents
D02 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


D02NSF : NAG Library, Mark 26

D02 Chapter Contents
D02 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

D02NSF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
10 Example

1 Purpose

D02NSF is a setup routine which must be called prior to an integrator in Sub-chapter D02M–N, if full matrix linear algebra is required.

2 Specification

SUBROUTINE D02NSF ( NEQ, NEQMAX, JCEVAL, NWKJAC, RWORK, IFAIL)
INTEGER | NEQ, NEQMAX, NWKJAC, IFAIL
REAL (KIND=nag_wp) | RWORK(50+4*NEQMAX)
CHARACTER(1) | JCEVAL

3 Description

D02NSF defines the linear algebra to be used as full matrix linear algebra, permits you to specify the method for calculating the Jacobian and checks the validity of certain input values.

4 References

See the D02M–N Sub-chapter Introduction.

5 Arguments

1:   NEQ – INTEGERInput
On entry: the number of differential equations.
Constraint: 1≤NEQ≤NEQMAX.
2:   NEQMAX – INTEGERInput
On entry: a bound on the maximum number of differential equations to be solved during the integration.
Constraint: NEQMAX≥NEQ.
3:   JCEVAL – CHARACTER(1)Input
On entry: specifies the technique to be used to compute the Jacobian.
JCEVAL='N'
The Jacobian is to be evaluated numerically by the integrator. If this option is used, then the actual argument corresponding to JAC in the call to D02NBF or D02NGF must be either D02NBZ or D02NGZ respectively.
JCEVAL='A'
You must supply a (sub)program to evaluate the Jacobian on a call to the integrator.
JCEVAL='D'
The default choice is to be made. In this case 'D' is interpreted as 'N'.
Only the first character of the actual argument JCEVAL is passed to D02NSF; hence it is permissible for the actual argument to be more descriptive ‘Numerical’, ‘Analytical’ or ‘Default’ on a call to D02NSF.
Constraint: JCEVAL='N', 'A' or 'D'.
4:   NWKJAC – INTEGERInput
On entry: the size of the workspace array WKJAC, which you are supplying to the integrator, as declared in the (sub)program from which D02NSF is called.
Constraint: NWKJAC≥NEQMAX×NEQMAX+1.
5:   RWORK 50+4×NEQMAX – REAL (KIND=nag_wp) arrayCommunication Array
This must be the same workspace array as the array RWORK supplied to the integrator. It is used to pass information from the setup routine to the integrator and therefore the contents of this array must not be changed before calling the integrator.
6:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, | NEQ<1,
or | NEQ>NEQMAX,
or | NWKJAC<NEQMAX×NEQMAX+1,
or | JCEVAL≠'N', 'A' or 'D'.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

Not applicable.

8 Parallelism and Performance

D02NSF is not thread safe and should not be called from a multithreaded user program. Please see Section 3.12.1 in How to Use the NAG Library and its Documentation for more information on thread safety.
D02NSF is not threaded in any implementation.

9 Further Comments

D02NSF must be called as a setup routine before a call to either D02NBF or D02NGF and may be called as the linear algebra setup routine before a call to either D02NMF or D02NNF.

10 Example

See Section 10 in D02NBF, D02NGF and D02NMF.
D02 Chapter Contents
D02 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


D02NTF : NAG Library, Mark 26

D02 Chapter Contents
D02 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

D02NTF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
10 Example

1 Purpose

D02NTF is a setup routine which you must call prior to an integrator in Sub-chapter D02M–N, if banded matrix linear algebra is required.

2 Specification

SUBROUTINE D02NTF ( NEQ, NEQMAX, JCEVAL, ML, MU, NWKJAC, NJCPVT, RWORK, IFAIL)
INTEGER | NEQ, NEQMAX, ML, MU, NWKJAC, NJCPVT, IFAIL
REAL (KIND=nag_wp) | RWORK(50+4*NEQMAX)
CHARACTER(1) | JCEVAL

3 Description

D02NTF defines the linear algebra to be used as banded matrix linear algebra, permits you to specify the method for calculating the Jacobian and checks the validity of certain input values.

4 References

See the D02M–N Sub-chapter Introduction.

5 Arguments

1:   NEQ – INTEGERInput
On entry: the number of differential equations.
Constraint: 1≤NEQ≤NEQMAX.
2:   NEQMAX – INTEGERInput
On entry: a bound on the maximum number of differential equations to be solved during the integration.
Constraint: NEQMAX≥NEQ.
3:   JCEVAL – CHARACTER(1)Input
On entry: specifies the technique to be used to compute the Jacobian as follows:
JCEVAL='N'
The Jacobian is to be evaluated numerically by the integrator. If this option is used, then the actual argument corresponding to JAC in the call to D02NCF or D02NHF must be either D02NCZ or D02NHZ respectively.
JCEVAL='A'
You must supply a (sub)program to evaluate the Jacobian on a call to the integrator.
JCEVAL='D'
The default choice is to be made. In this case 'D' is interpreted as 'N'.
Only the first character of the actual argument JCEVAL is passed to D02NTF; hence it is permissible for the actual argument to be more descriptive, e.g., ‘Numerical’, ‘Analytical’ or ‘Default’, on a call to D02NTF.
Constraint: JCEVAL='N', 'A' or 'D'.
4:   ML – INTEGERInput
On entry: mL, the number of subdiagonals in the band.
Constraint: 0≤ML≤NEQ-1.
5:   MU – INTEGERInput
On entry: mU, the number of superdiagonals in the band.
Constraint: 0≤MU≤NEQ-1.
6:   NWKJAC – INTEGERInput
On entry: the size of the workspace array WKJAC, which you are supplying to the integrator, as declared in the (sub)program from which D02NTF is called.
Constraint: NWKJAC≥2×ML+MU+1×NEQMAX.
7:   NJCPVT – INTEGERInput
On entry: the size of the workspace array JACPVT, which you are supplying to the integrator, as declared in the (sub)program from which D02NTF is called.
Constraint: NJCPVT≥NEQMAX.
8:   RWORK 50+4×NEQMAX – REAL (KIND=nag_wp) arrayCommunication Array
This must be the same workspace array as the array RWORK supplied to the integrator. It is used to pass information from the setup routine to the integrator and therefore the contents of this array must not be changed before calling the integrator.
9:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, | JCEVAL≠'N', 'A' or 'D',
or | NEQ<1,
or | ML<0 or ML>NEQ-1,
or | MU<0 or MU>NEQ-1,
or | NEQ>NEQMAX,
or | NJCPVT<NEQMAX,
or | NWKJAC<2×ML+MU+1×NEQMAX.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

Not applicable.

8 Parallelism and Performance

D02NTF is not thread safe and should not be called from a multithreaded user program. Please see Section 3.12.1 in How to Use the NAG Library and its Documentation for more information on thread safety.
D02NTF is not threaded in any implementation.

9 Further Comments

D02NTF must be called as a setup routine before a call to either D02NCF or D02NHF and may be called as the linear algebra setup routine before a call to either D02NMF or D02NNF.

10 Example

See Section 10 in D02NCF and D02NHF.
D02 Chapter Contents
D02 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


D02NUF : NAG Library, Mark 26

D02 Chapter Contents
D02 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

D02NUF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
10 Example

1 Purpose

D02NUF is a setup routine which must be called prior to an integrator in Sub-chapter D02M–N, if sparse matrix linear algebra is required.

2 Specification

SUBROUTINE D02NUF ( NEQ, NEQMAX, JCEVAL, NWKJAC, IA, NIA, JA, NJA, JACPVT, NJCPVT, SENS, U, ETA, LBLOCK, ISPLIT, RWORK, IFAIL)
INTEGER | NEQ, NEQMAX, NWKJAC, IA(NIA), NIA, JA(NJA), NJA, JACPVT(NJCPVT), NJCPVT, ISPLIT, IFAIL
REAL (KIND=nag_wp) | SENS, U, ETA, RWORK(50+4*NEQMAX)
LOGICAL | LBLOCK
CHARACTER(1) | JCEVAL

3 Description

D02NUF defines the linear algebra to be used as sparse matrix linear algebra, permits you to specify the method for calculating the Jacobian and its structure, and checks the validity of certain input values.

4 References

See the D02M–N Sub-chapter Introduction.

5 Arguments

1:   NEQ – INTEGERInput
On entry: the number of differential equations.
Constraint: 1≤NEQ≤NEQMAX.
2:   NEQMAX – INTEGERInput
On entry: a bound on the maximum number of differential equations to be solved during the integration.
Constraint: NEQMAX≥NEQ.
3:   JCEVAL – CHARACTER(1)Input
On entry: specifies the technique to be used to compute the Jacobian.
JCEVAL='N'
The sparsity structure and the value of the Jacobian are to be determined numerically by the integrator.
JCEVAL='S'
The sparsity structure of the Jacobian is supplied in the arrays IA and JA but its value is to be determined numerically. This is the recommended mode of operation unless it is a simple matter to supply the Jacobian.
JCEVAL='A'
The Jacobian will be evaluated by calls to JAC. The sparsity structure will be estimated by calls to JAC; that is, no explicit sparsity structure need be supplied in the arrays IA and JA.
JCEVAL='F'
The sparsity structure of the Jacobian is supplied in IA and JA, and its value will be determined by calls to JAC. This is the recommended mode of operation if the JAC is simple to form.
JCEVAL='D'
The default choice is to be made. In this case 'D' is interpreted as 'S'.
If the sparsity structure is supplied in arrays IA and JA, then any evidence from the numerical or analytical formation of the Jacobian that this structure is not correct, is ignored.
Only the first character of the actual argument JCEVAL is passed to D02NUF; hence it is permissible for the actual argument to be more descriptive, e.g., ‘Numerical’, ‘Structural’, ‘Analytical’, ‘Full information’ or ‘Default’ in a call to D02NUF.
If the option JCEVAL='N', 'S' or 'D' is used then the actual argument corresponding to JAC in the call to D02NDF or D02NJF must be either D02NDZ or D02NJZ respectively.
If integration is to be performed by reverse communication (D02NMF or D02NNF) then JCEVAL should be set to either 'N' or 'A'. In this case IA and JA are not used and their lengths may be set to 1.
Constraint: JCEVAL='N', 'S', 'A', 'F' or 'D'.
4:   NWKJAC – INTEGERInput
On entry: the size of the array WKJAC, which you are supplying to the integrator, as declared in the (sub)program from which D02NUF is called.
Suggested value: NWKJAC=4×NEQMAX if JCEVAL='N' or 'A'. If NWKJAC is less than this estimate, then a message is printed on the current advisory message unit (see X04ABF), and execution continues.
Constraint: if JCEVAL='S', 'F' or 'D', NWKJAC≥nelement+2×NEQ, where nelement is the total number of nonzeros.
5:   IA NIA – INTEGER arrayInput
On entry: if JCEVAL='S', 'F' or 'D', IA must contain details of the sparsity pattern to be used for the Jacobian. See JA.
IA is not used if JCEVAL='N' or 'A'.
6:   NIA – INTEGERInput
On entry: the dimension of the array IA as declared in the (sub)program from which D02NUF is called.
Constraints:
  • if JCEVAL='S', 'F' or 'D', NIA≥NEQ+1;
  • otherwise NIA≥1.
7:   JA NJA – INTEGER arrayInput
On entry: if JCEVAL='S', 'F' or 'D', JA must contain details of the sparsity pattern to be used for the Jacobian. JA contains the row indices where nonzero elements occur, reading in column-wise order, and IA contains the starting locations in JA of the descriptions of columns 1,2,…,NEQ in that order, with IA 1=1. Thus for each column index j=1,2,…,NEQ, the values of the row index i in column j where a nonzero element may occur are given by
i=JA k
where IA j≤k<IA j+1.
Thus the total number of nonzeros, nelement, must be IA NEQ+1-1. For example, for the following matrix
x 0 x 0 0 0 x x x 0 x x x 0 0 x 0 0 x x 0 0 0 x x
where x represents nonzero elements (13 in all) the arrays IA and JA should be
IA k 1 4 6 9 12 14 JA k 1 3 4 2 0 3 0 1 2 3 2 4 5 4 5
JA is not used if JCEVAL='N' or 'A'.
8:   NJA – INTEGERInput
On entry: the dimension of the array JA as declared in the (sub)program from which D02NUF is called.
Constraints:
  • if JCEVAL='S', 'F' or 'D', NJA≥IA NEQ+1-1;
  • otherwise NJA≥1.
9:   JACPVT NJCPVT – INTEGER arrayCommunication Array
On exit: data relating to the Jacobian sparsity structure.
10:   NJCPVT – INTEGERInput
On entry: the length of the array JACPVT, which you are supplying to the integrator, as dimensioned in the sub(program) from which D02NUF is called.
Suggested value: NJCPVT=20×NEQMAX if JCEVAL='N' or 'A'. If NJCPVT is less than this estimate, then a message is printed on the current advisory message unit (see X04ABF), and execution continues.
Constraint: if JCEVAL='S', 'F' or 'D', NJCPVT≥3×nelement+14×NEQ, where nelement is the total number of nonzeros.
11:   SENS – REAL (KIND=nag_wp)Input
On entry: a threshold argument used to determine whether or not a matrix element is zero; when SENS is set to 0.0 on entry, the routine will use SENS=100.0×machine precision. Otherwise the absolute value of SENS is used.
12:   U – REAL (KIND=nag_wp)Input
On entry: should have a value between 0.0 and 0.9999. Otherwise a default value of 0.1 is used. When the sparsity pattern has been evaluated, the first Jacobian computed is decomposed with U governing the choice of pivots; subsequent Jacobian decompositions use the same pattern of decomposition until the sparsity pattern is re-evaluated. When searching a row for a pivot, any element is excluded from the search which is less than U times the largest of those elements in the row available as pivots. Thus decreasing U biases the algorithm towards maintaining sparsity at the expense of numerical stability.
13:   ETA – REAL (KIND=nag_wp)Input
On entry: a relative pivot threshold, below which on subsequent decompositions (as described under U), an internal error is provoked.
ETA>1.0
No check on pivot size is made.
ETA≤0.0
The default value ETA=1.0E−4 is used.
14:   LBLOCK – LOGICALInput
On entry: indicates if preordering is used before decomposition.
If LBLOCK=.TRUE., on entry, the Jacobian matrix is preordered to block lower triangular form before a decomposition is performed (this is the recommended mode). If you know the structure of the Jacobian to be irreducible, that is not permutable to block lower triangular form, then you should set LBLOCK=.FALSE.. For example, a Jacobian arising from using the method of lines for parabolic partial differential equations would normally be irreducible. (See the specification of D02NXF for optional output concerning LBLOCK.)
15:   ISPLIT – INTEGERInput
On entry: this argument is used for splitting the integer workspace JACPVT to effect an efficient decomposition. It must satisfy 1≤ISPLIT≤99. If ISPLIT lies outside this range on entry, a default value of 73 is used. An appropriate value for ISPLIT for subsequent runs on similar problems is available via the optional output D02NXF.
Suggested value: ISPLIT=73, unless you have information from a previous run of a similar problem.
16:   RWORK 50+4×NEQMAX – REAL (KIND=nag_wp) arrayCommunication Array
This must be the same workspace array as the array RWORK supplied to the integrator. It is used to pass information from the setup routine to the integrator and therefore the contents of this array must not be changed before calling the integrator.
17:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, an illegal input was detected.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

Not applicable.

8 Parallelism and Performance

D02NUF is not thread safe and should not be called from a multithreaded user program. Please see Section 3.12.1 in How to Use the NAG Library and its Documentation for more information on thread safety.
D02NUF is not threaded in any implementation.

9 Further Comments

D02NUF must be called as a setup routine before a call to either D02NDF or D02NJF and may be called as the linear algebra setup routine before a call to D02NMF or D02NNF.

10 Example

See Section 10 in D02NDF, D02NJF and D02NNF.
D02 Chapter Contents
D02 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


D02NVF : NAG Library, Mark 26

D02 Chapter Contents
D02 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

D02NVF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
10 Example

1 Purpose

D02NVF is a setup routine which must be called prior to linear algebra setup routines and integrators from the SPRINT suite of routines, if Backward Differentiation Formulae (BDF) are to be used.

2 Specification

SUBROUTINE D02NVF ( NEQMAX, SDYSAV, MAXORD, METHOD, PETZLD, CON, TCRIT, HMIN, HMAX, H0, MAXSTP, MXHNIL, NORM, RWORK, IFAIL)
INTEGER | NEQMAX, SDYSAV, MAXORD, MAXSTP, MXHNIL, IFAIL
REAL (KIND=nag_wp) | CON(6), TCRIT, HMIN, HMAX, H0, RWORK(50+4*NEQMAX)
LOGICAL | PETZLD
CHARACTER(1) | METHOD, NORM

3 Description

An integrator setup routine must be called before the call to any linear algebra setup routine or integrator from the SPRINT suite of routines in this sub-chapter. This setup routine, D02NVF, makes the choice of the BDF integrator and permits you to define options appropriate to this choice. Alternative choices of integrator from this suite are the BLEND method and the DASSL implementation of the BDF method which can be chosen by initial calls to D02NWF or D02MVF respectively.

4 References

See the D02M–N Sub-chapter Introduction.

5 Arguments

1:   NEQMAX – INTEGERInput
On entry: a bound on the maximum number of differential equations to be solved.
Constraint: NEQMAX≥1.
2:   SDYSAV – INTEGERInput
On entry: the second dimension of the array YSAV that will be supplied to the integrator, as declared in the (sub)program from which the integrator is called.
Constraint: SDYSAV≥MAXORD+1.
3:   MAXORD – INTEGERInput
On entry: the maximum order to be used for the BDF method.
Constraint: 0<MAXORD≤5.
4:   METHOD – CHARACTER(1)Input
On entry: specifies the method to be used to solve the system of nonlinear equations arising on each step of the BDF code.
METHOD='N'
A modified Newton iteration is used.
METHOD='F'
Functional iteration is used.
METHOD='D'
A modified Newton iteration is used.
Note: a linear algebra setup routine must be called even when using functional iteration, since if difficulty is encountered a switch is made to a modified Newton method.
Only the first character of the actual argument METHOD is passed to D02NVF; hence it is permissible for the actual argument to be more descriptive e.g., ‘Newton’, ‘Functional iteration’ or ‘Default’ in a call to D02NVF.
Constraint: METHOD='N', 'F' or 'D'.
5:   PETZLD – LOGICALInput
On entry: specifies whether the Petzold local error test is to be used. If PETZLD is set to .TRUE. on entry, then the Petzold local error test is used, otherwise a conventional test is used. The Petzold test results in extra overhead cost but is more stable and reliable for differential/algebraic equations.
6:   CON 6 – REAL (KIND=nag_wp) arrayInput/Output
On entry: values to be used to control step size choice during integration. If any CON i=0.0 on entry, it is replaced by its default value described below. In most cases this is the recommended setting.
CON 1, CON 2, and CON 3 are factors used to bound step size changes. If the current step size h fails, then the modulus of the next step size is bounded by CON 1×h. The default value of CON 1 is 2.0. Note that the new step size may be used with a method of different order to the failed step. If the initial step size is h, then the modulus of the step size on the second step is bounded by CON 3×h. At any other stage in the integration, if the current step size is h, then the modulus of the next step size is bounded by CON 2×h. The default values are 10.0 for CON 2 and 1000.0 for CON 3.
CON 4, CON 5 and CON 6 are ‘tuning’ constants used in determining the next order and step size. They are used to scale the error estimates used in determining whether to keep the same order of the BDF method, decrease the order or increase the order respectively. The larger the value of CON i, for i=4,5,6, the less likely the choice of the corresponding order. The default values are: CON 4=1.2, CON 5=1.3, CON 6=1.4.
Constraints:
These constraints must be satisfied after any zero values have been replaced by their default values.
  • 0.0<CON 1≤CON 2≤CON 3;
  • CON i≥1.0, for i=2,3,…,6.
On exit: the values actually used by D02NVF.
7:   TCRIT – REAL (KIND=nag_wp)Input
On entry: a point beyond which integration must not be attempted. The use of TCRIT is described under the argument ITASK in the specification for the integrator (e.g., see D02NBF). A value, 0.0 say, must be specified even if ITASK subsequently specifies that TCRIT will not be used.
8:   HMIN – REAL (KIND=nag_wp)Input
On entry: the minimum absolute step size to be allowed. Set HMIN=0.0 if this option is not required.
9:   HMAX – REAL (KIND=nag_wp)Input
On entry: the maximum absolute step size to be allowed. Set HMAX=0.0 if this option is not required.
10:   H0 – REAL (KIND=nag_wp)Input
On entry: the step size to be attempted on the first step. Set H0=0.0 if the initial step size is calculated internally.
11:   MAXSTP – INTEGERInput
On entry: the maximum number of steps to be attempted during one call to the integrator after which it will return with IFAIL=2. Set MAXSTP=0 if no limit is to be imposed.
12:   MXHNIL – INTEGERInput
On entry: the maximum number of warnings printed (if ITRACE≥0) per problem when t+h=t on a step (h= current step size). If MXHNIL≤0, a default value of 10 is assumed.
13:   NORM – CHARACTER(1)Input
On entry: indicates the type of norm to be used.
NORM='M'
Maximum norm.
NORM='A'
Averaged L2 norm.
NORM='D'
Is the same as NORM='A'.
If vnorm denotes the norm of the vector v of length n, then for the averaged L2 norm
vnorm=1 n∑i=1 n vi/wi 2,
while for the maximum norm
vnorm=maxi vi/wi.
If you wish to weight the maximum norm or the L2 norm, then RTOL and ATOL should be scaled appropriately on input to the integrator (see under ITOL in the specification of the integrator for the formulation of the weight vector wi from RTOL and ATOL, e.g., see D02NBF).
Only the first character to the actual argument NORM is passed to D02NVF; hence it is permissible for the actual argument to be more descriptive e.g., ‘Maximum’, ‘Average L2’ or ‘Default’ in a call to D02NVF.
Constraint: NORM='M', 'A' or 'D'.
14:   RWORK 50+4×NEQMAX – REAL (KIND=nag_wp) arrayCommunication Array
This must be the same workspace array as the array RWORK supplied to the integrator. It is used to pass information from the setup routine to the integrator and therefore the contents of this array must not be changed before calling the integrator.
15:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, an illegal input was detected.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

Not applicable.

8 Parallelism and Performance

D02NVF is not threaded in any implementation.

9 Further Comments

None.

10 Example

See Section 10 in D02NBF.
D02 Chapter Contents
D02 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


D02NWF : NAG Library, Mark 26

D02 Chapter Contents
D02 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

D02NWF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
10 Example

1 Purpose

D02NWF is a setup routine which must be called prior to linear algebra setup routines and integrators from the SPRINT suite of routines, if the BLEND formulae are to be used.

2 Specification

SUBROUTINE D02NWF ( NEQMAX, SDYSAV, MAXORD, CON, TCRIT, HMIN, HMAX, H0, MAXSTP, MXHNIL, NORM, RWORK, IFAIL)
INTEGER | NEQMAX, SDYSAV, MAXORD, MAXSTP, MXHNIL, IFAIL
REAL (KIND=nag_wp) | CON(6), TCRIT, HMIN, HMAX, H0, RWORK(50+4*NEQMAX)
CHARACTER(1) | NORM

3 Description

An integrator setup routine must be called before the call to any linear algebra setup routine or integrator from the SPRINT suite of routines in this sub-chapter. This setup routine, D02NWF, makes the choice of the BLEND integrator and permits you to define options appropriate to this choice. Alternative choices of integrator from this suite are the BDF method and the DASSL implementation of the BDF method which can be chosen by initial calls to D02NVF or D02MVF respectively.

4 References

See the D02M–N Sub-chapter Introduction.

5 Arguments

1:   NEQMAX – INTEGERInput
On entry: a bound on the maximum number of differential equations to be solved.
Constraint: NEQMAX≥1.
2:   SDYSAV – INTEGERInput
On entry: the second dimension of the array YSAV that will be supplied to the integrator, as declared in the (sub)program from which the integrator is called (e.g., see D02NBF).
Constraint: SDYSAV≥MAXORD+3.
3:   MAXORD – INTEGERInput
On entry: the maximum order to be used for the BLEND method.
Constraint: 0<MAXORD≤11.
4:   CON 6 – REAL (KIND=nag_wp) arrayInput/Output
On entry: values to be used to control step size choice during integration. If any CON i=0.0 on entry, it is replaced by its default value described below. In most cases this is the recommended setting.
CON 1, CON 2, and CON 3 are factors used to bound step size changes. If the current step size h fails, then the modulus of the next step size is bounded by CON 1×h. The default value of CON 1 is 2.0. Note that the new step size may be used with a method of different order to the failed step. If the initial step size is h, then the modulus of the step size on the second step is bounded by CON 3×h. At any other stage in the integration, if the current step size is h, then the modulus of the next step size is bounded by CON 2×h. The default values are 10.0 for CON 2 and 1000.0 for CON 3.
CON 4, CON 5 and CON 6 are ‘tuning’ constants used in determining the next order and step size. They are used to scale the error estimates used in determining whether to keep the same order of the BLEND method, decrease the order or increase the order respectively. The larger the value of CON i, for i=4,5,6, the less likely the choice of the corresponding order. The default values are: CON 4=1.2, CON 5=1.3, CON 6=1.4.
Constraints:
These constraints must be satisfied after any zero values have been replaced by their default values.
  • 0.0<CON 1≤CON 2≤CON 3;
  • CON i≥1.0, for i=2,3,…,6.
On exit: the values actually used by D02NWF.
5:   TCRIT – REAL (KIND=nag_wp)Input
On entry: a point beyond which integration must not be attempted. The use of TCRIT is described under the argument ITASK in the specification for the integrator (e.g., see D02NBF). A value, 0.0 say, must be specified even if ITASK subsequently specifies that TCRIT will not be used.
6:   HMIN – REAL (KIND=nag_wp)Input
On entry: the minimum absolute step size to be allowed. Set HMIN=0.0 if this option is not required.
7:   HMAX – REAL (KIND=nag_wp)Input
On entry: the maximum absolute step size to be allowed. Set HMAX=0.0 if this option is not required.
8:   H0 – REAL (KIND=nag_wp)Input
On entry: the step size to be attempted on the first step. Set H0=0.0 if the initial step size is calculated internally.
9:   MAXSTP – INTEGERInput
On entry: the maximum number of steps to be attempted during one call to the integrator after which it will return with IFAIL=2. Set MAXSTP=0 if no limit is to be imposed.
10:   MXHNIL – INTEGERInput
On entry: the maximum number of warnings printed (if ITRACE≥0, e.g., see D02NBF) per problem when t+h=t on a step (h=​ current step size). If MXHNIL≤0, a default value of 10 is assumed.
11:   NORM – CHARACTER(1)Input
On entry: indicates the type of norm to be used.
NORM='M'
Maximum norm.
NORM='A'
Averaged L2 norm.
NORM='D'
Is the same as 'A'.
If vnorm denotes the norm of the vector v of length n, then for the averaged L2 norm
vnorm=1 n∑i=1 n vi/wi 2,
while for the maximum norm
vnorm=maxi vi/wi.
If you wish to weight the maximum norm or the L2 norm, then RTOL and ATOL should be scaled appropriately on input to the integrator (see under ITOL in the specification of the integrator for the formulation of the weight vector wi from RTOL and ATOL, e.g., D02NBF).
Only the first character of the actual argument NORM is passed to D02NWF; hence it is permissible for the actual argument to be more descriptive e.g., ‘Maximum’, ‘Average L2’ or ‘Default’ in a call to D02NWF.
Constraint: NORM='M', 'A' or 'D'.
12:   RWORK 50+4×NEQMAX – REAL (KIND=nag_wp) arrayCommunication Array
This must be the same workspace array as the array RWORK supplied to the integrator. It is used to pass information from the setup routine to the integrator and therefore the contents of this array must not be changed before calling the integrator.
13:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, an illegal input was detected.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

Not applicable.

8 Parallelism and Performance

D02NWF is not threaded in any implementation.

9 Further Comments

None.

10 Example

See Section 10 in D02NCF.
D02 Chapter Contents
D02 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


D02NXF : NAG Library, Mark 26

D02 Chapter Contents
D02 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

D02NXF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
10 Example

1 Purpose

D02NXF is an optional output routine which you may call, on exit from an integrator in Sub-chapter D02M–N, if sparse matrix linear algebra has been selected.

2 Specification

SUBROUTINE D02NXF ( ICALL, LIWREQ, LIWUSD, LRWREQ, LRWUSD, NLU, NNZ, NGP, ISPLIT, IGROW, LBLOCK, NBLOCK, INFORM)
INTEGER | ICALL, LIWREQ, LIWUSD, LRWREQ, LRWUSD, NLU, NNZ, NGP, ISPLIT, IGROW, NBLOCK, INFORM(23)
LOGICAL | LBLOCK

3 Description

D02NXF permits you to examine the various outputs from the sparse linear algebra routines called by the integrator.

4 References

See the D02M–N Sub-chapter Introduction.

5 Arguments

1:   ICALL – INTEGERInput
On entry: indicates whether or not all output arguments have been set during the call to the integrator. If so, that is, if the integrator returned with IFAIL=0 or 12, then ICALL must be set to 0. Otherwise ICALL must be set to 1, indicating that integration did not take place due to lack of space in arrays WKJAC and JACPVT, and only LIWREQ, LIWUSD, LRWREQ, LRWUSD have been set.
2:   LIWREQ – INTEGEROutput
On exit: the length of the integer workspace JACPVT reserved for the sparse matrix routines.
3:   LIWUSD – INTEGEROutput
On exit: the length of the integer workspace JACPVT actually used by the sparse matrix routines.
4:   LRWREQ – INTEGEROutput
On exit: the length of the real workspace WKJAC reserved for the sparse matrix routines.
5:   LRWUSD – INTEGEROutput
On exit: the length of the real workspace WKJAC actually used by the sparse matrix routines.
6:   NLU – INTEGEROutput
On exit: the number of LU decompositions done during the integration.
7:   NNZ – INTEGEROutput
On exit: the number of nonzeros in the Jacobian.
8:   NGP – INTEGEROutput
On exit: the number of FCN or RESID calls needed to form the Jacobian.
9:   ISPLIT – INTEGEROutput
On exit: an appropriate value for the argument ISPLIT when calling D02NUF for subsequent runs of similar problems.
10:   IGROW – INTEGEROutput
On exit: an estimate of the growth of the elements encountered during the last LU decomposition performed. If the actual estimate exceeds the largest possible integer value for the machine being used (see X02BBF) IGROW is set to the value returned by X02BBF.
11:   LBLOCK – LOGICALInput
On entry: the value used for the argument LBLOCK when calling D02NUF.
12:   NBLOCK – INTEGEROutput
On exit: if LBLOCK=.TRUE., NBLOCK contains the number of diagonal blocks in the Jacobian matrix permuted to block lower triangular form. If NBLOCK=1 then on subsequent runs of a similar problem LBLOCK should be set to .FALSE. in the call to D02NUF.
If LBLOCK=.FALSE., NBLOCK=1.
13:   INFORM 23 – INTEGER arrayCommunication Array
On entry: contains information supplied by the integrator.

6 Error Indicators and Warnings

None.

7 Accuracy

Not applicable.

8 Parallelism and Performance

D02NXF is not threaded in any implementation.

9 Further Comments

The output from D02NXF, in particular the values of LIWREQ, LIWUSD, LRWREQ, LRWUSD, ISPLIT and IGROW, should be used to determine appropriate values for the arguments of the setup routine D02NUF on further calls to the integrator for the same or similar problems.

10 Example

See Section 10 in D02NDF, D02NJF and D02NNF.
D02 Chapter Contents
D02 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


D02NYF : NAG Library, Mark 26

D02 Chapter Contents
D02 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

D02NYF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
10 Example

1 Purpose

D02NYF is a diagnostic routine which you may call either after any user-specified exit or after a mid-integration error exit from any of those integrators in Sub-chapter D02M–N that use methods set up by calls to D02MVF, D02NVF or D02NWF.

2 Specification

SUBROUTINE D02NYF ( NEQ, NEQMAX, HU, H, TCUR, TOLSF, RWORK, NST, NRE, NJE, NQU, NQ, NITER, IMXER, ALGEQU, INFORM, IFAIL)
INTEGER | NEQ, NEQMAX, NST, NRE, NJE, NQU, NQ, NITER, IMXER, INFORM(23), IFAIL
REAL (KIND=nag_wp) | HU, H, TCUR, TOLSF, RWORK(50+4*NEQ)
LOGICAL | ALGEQU(NEQ)

3 Description

D02NYF permits you to inspect statistics produced by any integrator in this sub-chapter that has been set up a call to one of D02MVF, D02NVF or D02NWF. These statistics concern the integration only.

4 References

See the D02M–N Sub-chapter Introduction.

5 Arguments

1:   NEQ – INTEGERInput
On entry: the value used for the argument NEQ when calling the integrator.
Constraint: NEQ≥1.
2:   NEQMAX – INTEGERInput
On entry: the value used for the argument NEQMAX when calling the integrator.
Constraint: NEQMAX≥NEQ.
3:   HU – REAL (KIND=nag_wp)Output
On exit: the last successful step size.
4:   H – REAL (KIND=nag_wp)Output
On exit: the proposed next step size for continuing the integration.
5:   TCUR – REAL (KIND=nag_wp)Output
On exit: t, the value of the independent variable which the integrator has actually reached. TCUR will always be at least as far as the output value of the argument t in the direction of integration, but may be further (if overshooting and interpolation at TOUT was specified, e.g., see D02NBF).
6:   TOLSF – REAL (KIND=nag_wp)Output
On exit: a tolerance scale factor, TOLSF≥1.0, which is computed when a request for too much accuracy is detected by the integrator (indicated by a return with IFAIL=3 or 14). If ITOL is left unaltered but RTOL and ATOL are uniformly scaled up by a factor of TOLSF the next call to the integrator is deemed likely to succeed.
7:   RWORK 50+4×NEQ – REAL (KIND=nag_wp) arrayCommunication Array
On entry: contains information supplied by the integrator.
8:   NST – INTEGEROutput
On exit: the number of steps taken in the integration so far.
9:   NRE – INTEGEROutput
On exit: the number of function or residual evaluations (FCN (e.g., see D02NBF) or RESID (e.g., see D02NGF) calls) used in the integration so far.
10:   NJE – INTEGEROutput
On exit: the number of Jacobian evaluations used in the integration so far. This equals the number of matrix LU decompositions.
11:   NQU – INTEGEROutput
On exit: the order of the method last used (successfully) in the integration.
12:   NQ – INTEGEROutput
On exit: the proposed order of the method for continuing the integration.
13:   NITER – INTEGEROutput
On exit: the number of iterations performed in the integration so far by the nonlinear equation solver.
14:   IMXER – INTEGEROutput
On exit: the index of the component of largest magnitude in the weighted local error vector ei/wi, for i=1,2,…,NEQ.
15:   ALGEQU NEQ – LOGICAL arrayOutput
On exit: ALGEQU i=.TRUE. if the ith equation integrated was detected to be algebraic, otherwise ALGEQU i=.FALSE.. Note that when the integrators for explicit equations are being used, then ALGEQU i=.FALSE., for i=1,2,…,NEQ.
16:   INFORM 23 – INTEGER arrayCommunication Array
On entry: contains information supplied by the integrator.
17:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, | NEQ<1,
or | NEQMAX<1,
or | NEQ>NEQMAX.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

Not applicable.

8 Parallelism and Performance

D02NYF is not threaded in any implementation.

9 Further Comments

Statistics for sparse matrix linear algebra calls (if appropriate) may be determined by a call to D02NXF.

10 Example

See Section 10 in D02NBF.
D02 Chapter Contents
D02 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


D02NZF : NAG Library, Mark 26

D02 Chapter Contents
D02 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

D02NZF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
10 Example

1 Purpose

D02NZF is a setup routine which must be called, if optional inputs need resetting, prior to a continuation call to any of those integrators in Sub-chapter D02M–N that use methods set up by calls to D02MVF, D02NVF or D02NWF.

2 Specification

SUBROUTINE D02NZF ( NEQMAX, TCRIT, H, HMIN, HMAX, MAXSTP, MXHNIL, RWORK, IFAIL)
INTEGER | NEQMAX, MAXSTP, MXHNIL, IFAIL
REAL (KIND=nag_wp) | TCRIT, H, HMIN, HMAX, RWORK(50+4*NEQMAX)

3 Description

D02NZF is provided to permit you to reset many of the arguments which control the integration ‘on the fly’, that is in conjunction with the interrupt facility permitted through the argument ITASK of the integrator (e.g., see D02NBF). In addition to a number of arguments which you can set initially through one of the integrator setup routines, the step size to be attempted on the next step may be changed.

4 References

See the D02M–N Sub-chapter Introduction.

5 Arguments

1:   NEQMAX – INTEGERInput
On entry: the value used for the argument NEQMAX when calling the integrator.
Constraint: NEQMAX≥1.
2:   TCRIT – REAL (KIND=nag_wp)Input
On entry: a point beyond which integration must not be attempted. The use of TCRIT is described under the argument ITASK in the specification for the integrator (e.g., see D02NBF). A value, 0.0 say, must be specified even if ITASK subsequently specifies that TCRIT will not be used.
3:   H – REAL (KIND=nag_wp)Input
On entry: the next step size to be attempted. Set H=0.0 if the current value of H is not to be changed.
4:   HMIN – REAL (KIND=nag_wp)Input
On entry: the minimum absolute step size to be allowed. Set HMIN=0.0 if this option is not required. Set HMIN<0.0 if the current value of HMIN is not to be changed.
5:   HMAX – REAL (KIND=nag_wp)Input
On entry: the maximum absolute step size to be allowed. Set HMAX=0.0 if this option is not required. Set HMAX<0.0 if the current value of HMAX is not to be changed.
6:   MAXSTP – INTEGERInput
On entry: the maximum number of steps to be attempted during one call to the integrator after which it will return with IFAIL=2 (see D02NCF). Set MAXSTP=0 if this option is not required. Set MAXSTP<0 if the current value of MAXSTP is not to be changed.
7:   MXHNIL – INTEGERInput
On entry: the maximum number of warnings printed (if ITRACE≥0, e.g., see D02NBF) per problem when t+h=t on a step (h=​ current step size). If MXHNIL≤0, a default value of 10 is assumed.
8:   RWORK 50+4×NEQMAX – REAL (KIND=nag_wp) arrayCommunication Array
This must be the same workspace array as the array RWORK supplied to the integrator. It is used to pass information from the integrator to D02NZF and therefore its contents must not be changed before calling D02NZF.
9:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
NEQMAX<1.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

Not applicable.

8 Parallelism and Performance

D02NZF is not threaded in any implementation.

9 Further Comments

None.

10 Example

See Section 10 in D02NCF.
D02 Chapter Contents
D02 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


D02PEF : NAG Library, Mark 26

D02 Chapter Contents
D02 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

D02PEF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

D02PEF solves an initial value problem for a first-order system of ordinary differential equations using Runge–Kutta methods.

2 Specification

SUBROUTINE D02PEF ( F, N, TWANT, TGOT, YGOT, YPGOT, YMAX, IUSER, RUSER, IWSAV, RWSAV, IFAIL)
INTEGER | N, IUSER(*), IWSAV(130), IFAIL
REAL (KIND=nag_wp) | TWANT, TGOT, YGOT(N), YPGOT(N), YMAX(N), RUSER(*), RWSAV(32*N+350)
EXTERNAL | F

3 Description

D02PEF and its associated routines (D02PQF, D02PTF and D02PUF) solve an initial value problem for a first-order system of ordinary differential equations. The routines, based on Runge–Kutta methods and derived from RKSUITE (see Brankin et al. (1991)), integrate
y′=f t,y  given  y t 0=y 0
where y is the vector of n solution components and t is the independent variable.
D02PEF is designed for the usual task, namely to compute an approximate solution at a sequence of points. You must first call D02PQF to specify the problem and how it is to be solved. Thereafter you call D02PEF repeatedly with successive values of TWANT, the points at which you require the solution, in the range from TSTART to TEND (as specified in D02PQF). In this manner D02PEF returns the point at which it has computed a solution TGOT (usually TWANT), the solution there (YGOT) and its derivative (YPGOT). If D02PEF encounters some difficulty in taking a step toward TWANT, then it returns the point of difficulty (TGOT) and the solution and derivative computed there (YGOT and YPGOT, respectively).
In the call to D02PQF you can specify either the first step size for D02PEF to attempt or that it computes automatically an appropriate value. Thereafter D02PEF estimates an appropriate step size for its next step. This value and other details of the integration can be obtained after any call to D02PEF by a call to D02PTF. The local error is controlled at every step as specified in D02PQF. If you wish to assess the true error, you must set METHOD to a positive value in the call to D02PQF. This assessment can be obtained after any call to D02PEF by a call to D02PUF.
For more complicated tasks, you are referred to routines D02PFF, D02PRF and D02PSF, all of which are used by D02PEF.

4 References

Brankin R W, Gladwell I and Shampine L F (1991) RKSUITE: A suite of Runge–Kutta codes for the initial value problems for ODEs SoftReport 91-S1 Southern Methodist University

5 Arguments

1:   F – SUBROUTINE, supplied by the user.External Procedure
F must evaluate the functions fi (that is the first derivatives yi′) for given values of the arguments t, yi.
The specification of F is:
SUBROUTINE F ( T, N, Y, YP, IUSER, RUSER)
INTEGER | N, IUSER(*)
REAL (KIND=nag_wp) | T, Y(N), YP(N), RUSER(*)
1:   T – REAL (KIND=nag_wp)Input
On entry: t, the current value of the independent variable.
2:   N – INTEGERInput
On entry: n, the number of ordinary differential equations in the system to be solved.
3:   Y N – REAL (KIND=nag_wp) arrayInput
On entry: the current values of the dependent variables, yi, for i=1,2,…,n.
4:   YP N – REAL (KIND=nag_wp) arrayOutput
On exit: the values of fi, for i=1,2,…,n.
5:   IUSER* – INTEGER arrayUser Workspace
6:   RUSER* – REAL (KIND=nag_wp) arrayUser Workspace
F is called with the arguments IUSER and RUSER as supplied to D02PEF. You are free to use the arrays IUSER and RUSER to supply information to F as an alternative to using COMMON global variables.
F must either be a module subprogram USEd by, or declared as EXTERNAL in, the (sub)program from which D02PEF is called. Arguments denoted as Input must not be changed by this procedure.
2:   N – INTEGERInput
On entry: n, the number of ordinary differential equations in the system to be solved.
Constraint: N≥1.
3:   TWANT – REAL (KIND=nag_wp)Input
On entry: t, the next value of the independent variable where a solution is desired.
Constraint: TWANT must be closer to TEND than the previous value of TGOT (or TSTART on the first call to D02PEF); see D02PQF for a description of TSTART and TEND. TWANT must not lie beyond TEND in the direction of integration.
4:   TGOT – REAL (KIND=nag_wp)Output
On exit: t, the value of the independent variable at which a solution has been computed. On successful exit with IFAIL=0, TGOT will equal TWANT. On exit with IFAIL>1, a solution has still been computed at the value of TGOT but in general TGOT will not equal TWANT.
5:   YGOT N – REAL (KIND=nag_wp) arrayInput/Output
On entry: on the first call to D02PEF, YGOT need not be set. On all subsequent calls YGOT must remain unchanged.
On exit: an approximation to the true solution at the value of TGOT. At each step of the integration to TGOT, the local error has been controlled as specified in D02PQF. The local error has still been controlled even when TGOT≠TWANT, that is after a return with IFAIL>1.
6:   YPGOT N – REAL (KIND=nag_wp) arrayOutput
On exit: an approximation to the first derivative of the true solution at TGOT.
7:   YMAX N – REAL (KIND=nag_wp) arrayInput/Output
On entry: on the first call to D02PEF, YMAX need not be set. On all subsequent calls YMAX must remain unchanged.
On exit: YMAX i contains the largest value of yi computed at any step in the integration so far.
8:   IUSER* – INTEGER arrayUser Workspace
9:   RUSER* – REAL (KIND=nag_wp) arrayUser Workspace
IUSER and RUSER are not used by D02PEF, but are passed directly to F and may be used to pass information to this routine as an alternative to using COMMON global variables.
10:   IWSAV 130 – INTEGER arrayCommunication Array
11:   RWSAV 32×N+350 – REAL (KIND=nag_wp) arrayCommunication Array
On entry: these must be the same arrays supplied in a previous call to D02PQF. They must remain unchanged between calls.
On exit: information about the integration for use on subsequent calls to D02PEF or other associated routines.
12:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, because for this routine the values of the output arguments may be useful even if IFAIL≠0 on exit, the recommended value is -1. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, a previous call to the setup routine has not been made or the communication arrays have become corrupted.
On entry, N=value, but the value passed to the setup routine was N=value.
On entry, the communication arrays have become corrupted, or a catastrophic error has already been detected elsewhere. You cannot continue integrating the problem.
TEND (setup) had already been reached in a previous call.
To start a new problem, you will need to call the setup routine.
TWANT does not lie in the direction of integration. TWANT=value.
TWANT is too close to the last value of TGOT (TSTART on setup).
When using the method of order 8 at setup, these must differ by at least value. Their absolute difference is value.
TWANT lies beyond TEND (setup) in the direction of integration, but is very close to TEND.
You may have intended TWANT=TEND.
TWANT-TEND=value.
TWANT lies beyond TEND (setup) in the direction of integration.
TWANT=value and TEND=value.
You cannot call this routine after it has returned an error.
You must call the setup routine to start another problem.
You cannot call this routine when you have specified, in the setup routine, that the step integrator will be used.
IFAIL=2
This routine is being used inefficiently because the step size has been reduced drastically many times to obtain answers at many points. Using the order 4 and 5 pair method at setup is more appropriate here. You can continue integrating this problem.
IFAIL=3
Approximately value function evaluations have been used to compute the solution since the integration started or since this message was last printed. However, you can continue integrating the problem.
IFAIL=4
Approximately value function evaluations have been used to compute the solution since the integration started or since this message was last printed. Your problem has been diagnosed as stiff. If the situation persists, it will cost roughly value times as much to reach TEND (setup) as it has cost to reach the current time. You should probably call routines intended for stiff problems. However, you can continue integrating the problem.
IFAIL=5
In order to satisfy your error requirements the solver has to use a step size of value at the current time, value. This step size is too small for the machine precision, and is smaller than value.
IFAIL=6
The global error assessment algorithm failed at start of integration.
The integration is being terminated.
The global error assessment may not be reliable for times beyond value.
The integration is being terminated.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

The accuracy of integration is determined by the arguments TOL and THRESH in a prior call to D02PQF (see the routine document for D02PQF for further details and advice). Note that only the local error at each step is controlled by these arguments. The error estimates obtained are not strict bounds but are usually reliable over one step. Over a number of steps the overall error may accumulate in various ways, depending on the properties of the differential system.

8 Parallelism and Performance

D02PEF makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

If D02PEF returns with IFAIL=5 and the accuracy specified by TOL and THRESH is really required then you should consider whether there is a more fundamental difficulty. For example, the solution may contain a singularity. In such a region the solution components will usually be large in magnitude. Successive output values of YGOT and YMAX should be monitored (or D02PFF should be used since this takes one integration step at a time) with the aim of trapping the solution before the singularity. In any case numerical integration cannot be continued through a singularity, and analytical treatment may be necessary.
Performance statistics are available after any return from D02PEF by a call to D02PTF. If METHOD>0 in the call to D02PQF, global error assessment is available after a return from D02PEF with IFAIL=0, 2, 3, 4, 5 or 6 by a call to D02PUF.
After a failure with IFAIL=5 or 6 each of the diagnostic routines D02PTF and D02PUF may be called only once.
If D02PEF returns with IFAIL=4 then it is advisable to change to another code more suited to the solution of stiff problems. D02PEF will not return with IFAIL=4 if the problem is actually stiff but it is estimated that integration can be completed using less function evaluations than already computed.

10 Example

This example solves the equation
y′′=-y,  y 0=0,   y′0=1
reposed as
y 1′=y 2
y 2′=-y 1
over the range 0,2 π with initial conditions y 1=0.0 and y 2=1.0. Relative error control is used with threshold values of 1.0E−8 for each solution component and compute the solution at intervals of length π/4 across the range. A low-order Runge–Kutta method (see D02PQF) is also used with tolerances TOL=1.0E−3 and TOL=1.0E−4 in turn so that the solutions can be compared.
See also Section 10 in D02PUF.

10.1 Program Text

Program Text (d02pefe.f90)

10.2 Program Data

Program Data (d02pefe.d)

10.3 Program Results

Program Results (d02pefe.r)

GnuplotProduced by GNUPLOT 4.6 patchlevel 3 −1 −0.5 0 0.5 1 0 2 4 6 8 10 1e−07 1e−06 1e−05 0.0001 0.001 0.01 Solution (y,y') abs(Error) t Example Program First-order ODEs using Runge-Kutta Low-order Method using Two Tolerances y' y-error (tol = 0.001) y-error (tol = 0.0001) y gnuplot_plot_1 gnuplot_plot_2 gnuplot_plot_3 gnuplot_plot_4
D02 Chapter Contents
D02 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


D02PFF : NAG Library, Mark 26

D02 Chapter Contents
D02 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

D02PFF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

D02PFF is a one-step routine for solving an initial value problem for a first-order system of ordinary differential equations using Runge–Kutta methods.

2 Specification

SUBROUTINE D02PFF ( F, N, TNOW, YNOW, YPNOW, IUSER, RUSER, IWSAV, RWSAV, IFAIL)
INTEGER | N, IUSER(*), IWSAV(130), IFAIL
REAL (KIND=nag_wp) | TNOW, YNOW(N), YPNOW(N), RUSER(*), RWSAV(32*N+350)
EXTERNAL | F

3 Description

D02PFF and its associated routines (D02PQF, D02PRF, D02PSF, D02PTF and D02PUF) solve an initial value problem for a first-order system of ordinary differential equations. The routines, based on Runge–Kutta methods and derived from RKSUITE (see Brankin et al. (1991)), integrate
y′=f t,y  given  y t 0=y 0
where y is the vector of n solution components and t is the independent variable.
D02PFF is designed to be used in complicated tasks when solving systems of ordinary differential equations. You must first call D02PQF to specify the problem and how it is to be solved. Thereafter you (repeatedly) call D02PFF to take one integration step at a time from TSTART in the direction of TEND (as specified in D02PQF). In this manner D02PFF returns an approximation to the solution YNOW and its derivative YPNOW at successive points TNOW. If D02PFF encounters some difficulty in taking a step, the integration is not advanced and the routine returns with the same values of TNOW, YNOW and YPNOW as returned on the previous successful step. D02PFF tries to advance the integration as far as possible subject to passing the test on the local error and not going past TEND.
In the call to D02PQF you can specify either the first step size for D02PFF to attempt or that it computes automatically an appropriate value. Thereafter D02PFF estimates an appropriate step size for its next step. This value and other details of the integration can be obtained after any call to D02PFF by a call to D02PTF. The local error is controlled at every step as specified in D02PQF. If you wish to assess the true error, you must set METHOD to a positive value in the call to D02PQF. This assessment can be obtained after any call to D02PFF by a call to D02PUF.
If you want answers at specific points there are two ways to proceed:
(i) | The more efficient way is to step past the point where a solution is desired, and then call D02PSF to get an answer there. Within the span of the current step, you can get all the answers you want at very little cost by repeated calls to D02PSF. This is very valuable when you want to find where something happens, e.g., where a particular solution component vanishes. You cannot proceed in this way with METHOD=3 or -3.
(ii) | The other way to get an answer at a specific point is to set TEND to this value and integrate to TEND. D02PFF will not step past TEND, so when a step would carry it past, it will reduce the step size so as to produce an answer at TEND exactly. After getting an answer there (TNOW=TEND), you can reset TEND to the next point where you want an answer, and repeat. TEND could be reset by a call to D02PQF, but you should not do this. You should use D02PRF instead because it is both easier to use and much more efficient. This way of getting answers at specific points can be used with any of the available methods, but it is the only way with METHOD=3 or -3. It can be inefficient. Should this be the case, the code will bring the matter to your attention.

4 References

Brankin R W, Gladwell I and Shampine L F (1991) RKSUITE: A suite of Runge–Kutta codes for the initial value problems for ODEs SoftReport 91-S1 Southern Methodist University

5 Arguments

1:   F – SUBROUTINE, supplied by the user.External Procedure
F must evaluate the functions fi (that is the first derivatives yi′) for given values of the arguments t, yi.
The specification of F is:
SUBROUTINE F ( T, N, Y, YP, IUSER, RUSER)
INTEGER | N, IUSER(*)
REAL (KIND=nag_wp) | T, Y(N), YP(N), RUSER(*)
1:   T – REAL (KIND=nag_wp)Input
On entry: t, the current value of the independent variable.
2:   N – INTEGERInput
On entry: n, the number of ordinary differential equations in the system to be solved.
3:   Y N – REAL (KIND=nag_wp) arrayInput
On entry: the current values of the dependent variables, yi, for i=1,2,…,n.
4:   YP N – REAL (KIND=nag_wp) arrayOutput
On exit: the values of fi, for i=1,2,…,n.
5:   IUSER* – INTEGER arrayUser Workspace
6:   RUSER* – REAL (KIND=nag_wp) arrayUser Workspace
F is called with the arguments IUSER and RUSER as supplied to D02PFF. You are free to use the arrays IUSER and RUSER to supply information to F as an alternative to using COMMON global variables.
F must either be a module subprogram USEd by, or declared as EXTERNAL in, the (sub)program from which D02PFF is called. Arguments denoted as Input must not be changed by this procedure.
2:   N – INTEGERInput
On entry: n, the number of ordinary differential equations in the system to be solved.
Constraint: N≥1.
3:   TNOW – REAL (KIND=nag_wp)Output
On exit: t, the value of the independent variable at which a solution has been computed.
4:   YNOW N – REAL (KIND=nag_wp) arrayOutput
On exit: an approximation to the solution at TNOW. The local error of the step to TNOW was no greater than permitted by the specified tolerances (see D02PQF).
5:   YPNOW N – REAL (KIND=nag_wp) arrayOutput
On exit: an approximation to the first derivative of the solution at TNOW.
6:   IUSER* – INTEGER arrayUser Workspace
7:   RUSER* – REAL (KIND=nag_wp) arrayUser Workspace
IUSER and RUSER are not used by D02PFF, but are passed directly to F and may be used to pass information to this routine as an alternative to using COMMON global variables.
8:   IWSAV 130 – INTEGER arrayCommunication Array
9:   RWSAV 32×N+350 – REAL (KIND=nag_wp) arrayCommunication Array
On entry: these must be the same arrays supplied in a previous call to D02PQF. They must remain unchanged between calls.
On exit: information about the integration for use on subsequent calls to D02PFF or other associated routines.
10:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, because for this routine the values of the output arguments may be useful even if IFAIL≠0 on exit, the recommended value is -1. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
A call to this routine cannot be made after it has returned an error.
The setup routine must be called to start another problem.
On entry, N=value, but the value passed to the setup routine was N=value.
On entry, the communication arrays have become corrupted, or a catastrophic error has already been detected elsewhere. You cannot continue integrating the problem.
TEND, as specified in the setup routine, has already been reached. To start a new problem, you will need to call the setup routine. To continue integration beyond TEND then D02PRF must first be called to reset TEND to a new end value.
IFAIL=2
More than 100 output points have been obtained by integrating to TEND (as specified in the setup routine). They have been so clustered that it would probably be (much) more efficient to use the interpolation routine (if METHOD=3, switch to METHOD=2 at setup). However, you can continue integrating the problem.
IFAIL=3
Approximately value function evaluations have been used to compute the solution since the integration started or since this message was last printed. However, you can continue integrating the problem.
IFAIL=4
Approximately value function evaluations have been used to compute the solution since the integration started or since this message was last printed. Your problem has been diagnosed as stiff. If the situation persists, it will cost roughly value times as much to reach TEND (setup) as it has cost to reach the current time. You should probably call routines intended for stiff problems. However, you can continue integrating the problem.
IFAIL=5
In order to satisfy your error requirements the solver has to use a step size of value at the current time, value. This step size is too small for the machine precision, and is smaller than value.
IFAIL=6
The global error assessment algorithm failed at start of integration.
The integration is being terminated.
The global error assessment may not be reliable for times beyond value.
The integration is being terminated.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

The accuracy of integration is determined by the arguments TOL and THRESH in a prior call to D02PQF (see the routine document for D02PQF for further details and advice). Note that only the local error at each step is controlled by these arguments. The error estimates obtained are not strict bounds but are usually reliable over one step. Over a number of steps the overall error may accumulate in various ways, depending on the properties of the differential system.

8 Parallelism and Performance

D02PFF makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

If D02PFF returns with IFAIL=5 and the accuracy specified by TOL and THRESH is really required then you should consider whether there is a more fundamental difficulty. For example, the solution may contain a singularity. In such a region the solution components will usually be large in magnitude. Successive output values of YNOW should be monitored with the aim of trapping the solution before the singularity. In any case numerical integration cannot be continued through a singularity, and analytical treatment may be necessary.
Performance statistics are available after any return from D02PFF (except when IFAIL=1) by a call to D02PTF. If METHOD>0 in the call to D02PQF, global error assessment is available after any return from D02PFF (except when IFAIL=1) by a call to D02PUF.
After a failure with IFAIL=5 or 6 each of the diagnostic routines D02PTF and D02PUF may be called only once.
If D02PFF returns with IFAIL=4 then it is advisable to change to another code more suited to the solution of stiff problems. D02PFF will not return with IFAIL=4 if the problem is actually stiff but it is estimated that integration can be completed using less function evaluations than already computed.

10 Example

This example solves the equation
y′′ = -y ,   y 0 = 0 ,   y′0 = 1
reposed as
y 1′ = y 2
y 2′ = -y 1
over the range 0,2 π with initial conditions y 1 = 0.0 and y 2 = 1.0 . We use relative error control with threshold values of 1.0E−8 for each solution component and print the solution at each integration step across the range. We use a medium order Runge–Kutta method (METHOD=2) with tolerances TOL=1.0E−4 and TOL=1.0E−5 in turn so that we may compare the solutions.

10.1 Program Text

Program Text (d02pffe.f90)

10.2 Program Data

Program Data (d02pffe.d)

10.3 Program Results

Program Results (d02pffe.r)

GnuplotProduced by GNUPLOT 4.6 patchlevel 3 −1 −0.5 0 0.5 1 0 1 2 3 4 5 6 7 0.00000 0.00000 0.00000 0.00000 0.00001 0.00010 Solution (y,y') abs(Error) t Example Program First-order ODEs using Step-by-step Runge-Kutta Medium-order Method using Two Tolerances gnuplot_plot_1 y-solution gnuplot_plot_2 y'-solution gnuplot_plot_3 y-error (tol = 0.00001) gnuplot_plot_4 y-error (tol = 0.0001) gnuplot_plot_5 sin(x) gnuplot_plot_6 cos(x)
D02 Chapter Contents
D02 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


D02PGF : NAG Library, Mark 26

D02 Chapter Contents
D02 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

D02PGF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

D02PGF is a reverse communication one-step routine for solving an initial value problem for a first-order system of ordinary differential equations using Runge–Kutta methods. The direct communication version of this routine is D02PFF. See Section 3.3.3 in How to Use the NAG Library and its Documentation for the difference between forward and reverse communication.

2 Specification

SUBROUTINE D02PGF ( IREVCM, N, T, Y, YP, IWSAV, RWSAV, IFAIL)
INTEGER | IREVCM, N, IWSAV(130), IFAIL
REAL (KIND=nag_wp) | T, Y(N), YP(N), RWSAV(32*N+350)

3 Description

D02PGF and its associated routines (D02PHF, D02PJF, D02PQF, D02PRF, D02PTF and D02PUF) solve an initial value problem for a first-order system of ordinary differential equations. The routines, based on Runge–Kutta methods and derived from RKSUITE (see Brankin et al. (1991)), integrate
y′=f t,y  given  y t 0=y 0
where y is the vector of n solution components and t is the independent variable.
D02PGF is designed to be used in complicated tasks when solving systems of ordinary differential equations. You must first call D02PQF to specify the problem and how it is to be solved. Thereafter you (repeatedly) call D02PGF in reverse communication loops to take one integration step at a time from TSTART in the direction of TEND (as specified in D02PQF). In this manner D02PGF returns an approximation to the solution Y and its derivative YP at successive points T. If D02PGF encounters some difficulty in taking a step, the integration is not advanced and the routine returns with the same values of T, Y and YP as returned on the previous successful step. D02PGF tries to advance the integration as far as possible subject to passing the test on the local error and not going past TEND.
In the call to D02PQF you can specify either the first step size for D02PGF to attempt or it computes automatically an appropriate value. Thereafter D02PGF estimates an appropriate step size for its next step. This value and other details of the integration can be obtained after a completed step by D02PGF by a call to D02PTF. The local error is controlled at every step as specified in D02PQF. If you wish to assess the true error, you must set METHOD to a positive value in the call to D02PQF. This assessment can be obtained after any call to D02PGF by a call to D02PUF.
If you want answers at specific points there are two ways to proceed:
(i) | The more efficient way is to step past the point where a solution is desired, and then call D02PHF and D02PJF to get an answer there. Within the span of the current step, you can get all the answers you want at very little cost by repeated calls to D02PJF. This is very valuable when you want to find where something happens, e.g., where a particular solution component vanishes.
(ii) | Alternatively, set TEND to the desired value and integrate to TEND. D02PGF will not step past TEND, so when a step would carry it past, it will reduce the step size so as to produce an answer at TEND exactly. After getting an answer there (T=TEND), you can reset TEND to the next point where you want an answer, and repeat. TEND could be reset by a call to D02PQF, but you should not do this. You should use D02PRF instead because it is both easier to use and much more efficient. This way of getting answers at specific points can be used with any of the available methods, but it can be inefficient. Should this be the case, the code will bring the matter to your attention.

4 References

Brankin R W, Gladwell I and Shampine L F (1991) RKSUITE: A suite of Runge–Kutta codes for the initial value problems for ODEs SoftReport 91-S1 Southern Methodist University

5 Arguments

Note: this routine uses reverse communication. Its use involves an initial entry, intermediate exits and re-entries, and a final exit, as indicated by the argument IREVCM. Between intermediate exits and re-entries, all arguments other than those specified by the value of IREVCM must remain unchanged.
1:   IREVCM – INTEGERInput/Output
On initial entry: IREVCM must be set to zero to indicate that a new step is being taken.
On intermediate re-entry: IREVCM should remain unchanged.
On intermediate exit: IREVCM returns a value >0 to indicate that a function evaluation is required prior to re-entry; the value of the derivatives y′=f t,y must be returned in YP where the value of t is supplied in T and the values y t are supplied in the array Y. The value of IREVCM indicates the reason for the function evaluation as follows:
IREVCM=1
For initial entry values of T and Y.
IREVCM=2
To determine stiffness of system.
IREVCM=3
For the stages of the primary step.
IREVCM=4
A final stage of the primary step.
IREVCM=5
For the stages of a secondary step (if global error assessment is required).
On final exit:
IREVCM=-1
Successful exit; T, Y and YP contain the solution at the end of a successful integration step.
IREVCM=-2
Error exit; IFAIL should be interrogated to determine the nature of the error.
2:   N – INTEGERInput
On entry: n, the number of ordinary differential equations in the system to be solved.
Constraint: N≥1. This must be the same value as supplied in a previous call to D02PQF.
3:   T – REAL (KIND=nag_wp)Output
On intermediate exit: T contains the value of the independent variable t at which the derivatives y′ are to be evaluated.
On final exit: the value of t at which a solution has been computed following a successful step.
4:   Y N – REAL (KIND=nag_wp) arrayOutput
On intermediate exit: Y contains the value of the solution y at which the derivatives y′ are to be evaluated.
On final exit: the approximation to the solution computed following a successful step.
5:   YP N – REAL (KIND=nag_wp) arrayInput
On initial entry: YP need not be set.
On intermediate re-entry: YP must contain the value of the derivatives y′=f t,y where t is supplied in T and y is supplied in the array Y.
6:   IWSAV 130 – INTEGER arrayCommunication Array
7:   RWSAV 32×N+350 – REAL (KIND=nag_wp) arrayCommunication Array
On entry: these must be the same arrays supplied in a previous call to D02PQF. They must remain unchanged between calls.
On exit: information about the integration for use on subsequent calls to D02PGF or other associated routines.
8:   IFAIL – INTEGERInput/Output
On initial entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, because for this routine the values of the output arguments may be useful even if IFAIL≠0 on exit, the recommended value is -1. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On final exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
A call to this routine cannot be made after it has returned an error.
The setup routine must be called to start another problem.
IREVCM<0 on entry.
On entry, a previous call to the setup routine has not been made or the communication arrays have become corrupted.
On entry, N=value, but the value passed to the setup routine was N=value.
On entry, the communication arrays have become corrupted, or a catastrophic error has already been detected elsewhere. You cannot continue integrating the problem.
TEND, as specified in the setup routine, has already been reached. To start a new problem, you will need to call the setup routine. To continue integration beyond TEND then D02PRF must first be called to reset TEND to a new end value.
IFAIL=2
More than 100 output points have been obtained by integrating to TEND (as specified in the setup routine). They have been so clustered that it would probably be (much) more efficient to use the interpolation routine. However, you can continue integrating the problem.
IFAIL=3
Approximately value function evaluations have been used to compute the solution since the integration started or since this message was last printed. However, you can continue integrating the problem.
IFAIL=4
Approximately value function evaluations have been used to compute the solution since the integration started or since this message was last printed. Your problem has been diagnosed as stiff. If the situation persists, it will cost roughly value times as much to reach TEND (setup) as it has cost to reach the current time. You should probably call routines intended for stiff problems. However, you can continue integrating the problem.
IFAIL=5
In order to satisfy your error requirements the solver has to use a step size of value at the current time, value. This step size is too small for the machine precision, and is smaller than value.
IFAIL=6
The global error assessment algorithm failed at start of integration.
The integration is being terminated.
The global error assessment may not be reliable for times beyond value.
The integration is being terminated.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

The accuracy of integration is determined by the arguments TOL and THRESH in a prior call to D02PQF (see the routine document for D02PQF for further details and advice). Note that only the local error at each step is controlled by these arguments. The error estimates obtained are not strict bounds but are usually reliable over one step. Over a number of steps the overall error may accumulate in various ways, depending on the properties of the differential system.

8 Parallelism and Performance

D02PGF makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

If D02PGF returns with IFAIL>1 then the values returned in T and Y are for the last successful step, or the initial conditions supplied if no successful step has been taken.
If D02PGF returns with IFAIL=5 and the accuracy specified by TOL and THRESH is really required then you should consider whether there is a more fundamental difficulty. For example, the solution may contain a singularity. In such a region the solution components will usually be large in magnitude. Successive output values of Y should be monitored with the aim of trapping the solution before the singularity. In any case, numerical integration cannot be continued through a singularity and analytical treatment may be necessary.
Performance statistics are available after any return from D02PGF (except when IFAIL=1) by a call to D02PTF. If METHOD>0 in the call to D02PQF, global error assessment is available after any return from D02PGF (except when IFAIL=1) by a call to D02PUF.
After a failure with IFAIL=5 or 6 each of the diagnostic routines D02PTF and D02PUF may be called only once.
If D02PGF returns with IFAIL=4 then it is advisable to change to another code more suited to the solution of stiff problems. D02PGF will not return with IFAIL=4 if the problem is actually stiff but it is estimated that integration can be completed using less function evaluations than already computed.

10 Example

This example solves the equation
y′′ = -y ,   y 0 = 0 ,   y′0 = 1
reposed as
y 1′ = y 2
y 2′ = -y 1
over the range 0,2 π with initial conditions y 1 = 0.0 and y 2 = 1.0 . We use relative error control with threshold values of 1.0E−8 for each solution component and print the solution at regular intervals using the interpolation routines D02PHF and D02PJF within integration steps across the range; points on the range at which y 1 or y 2 change sign are also evaluated using a combination of the root finding routine C05AZF and the interpolation routines. We use a medium order Runge–Kutta method (METHOD=2) with tolerance TOL=1.0E−5.

10.1 Program Text

Program Text (d02pgfe.f90)

10.2 Program Data

Program Data (d02pgfe.d)

10.3 Program Results

Program Results (d02pgfe.r)

GnuplotProduced by GNUPLOT 4.6 patchlevel 3 −1 −0.5 0 0.5 1 0 1 2 3 4 5 6 7 0.00000 0.00000 0.00000 0.00000 0.00001 0.00010 Solution (y,y') abs(Error) t Example Program First-order ODEs using Step-by-step Runge-Kutta Medium-order Method using Two Tolerances gnuplot_plot_1 y-solution gnuplot_plot_2 y'-solution gnuplot_plot_3 y-error (tol = 0.00001) gnuplot_plot_4 y-error (tol = 0.0001) gnuplot_plot_5 sin(x) gnuplot_plot_6 cos(x)
D02 Chapter Contents
D02 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


D02PHF : NAG Library, Mark 26

D02 Chapter Contents
D02 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

D02PHF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
10 Example

1 Purpose

D02PHF is a reverse communication routine that computes the interpolant for evaluation by D02PJF anywhere on an integration step taken by D02PGF. The direct communication version of the D02PHF and D02PJF pair is D02PSF. A significant difference in functionality between the forward and reverse communication versions is that D02PHF and D02PJF can interpolate for the high-order Runge–Kutta method.

2 Specification

SUBROUTINE D02PHF ( IREVCM, N, NWANT, T, Y, YP, WCOMM, LWCOMM, IWSAV, RWSAV, IFAIL)
INTEGER | IREVCM, N, NWANT, LWCOMM, IWSAV(130), IFAIL
REAL (KIND=nag_wp) | T, Y(N), YP(N), WCOMM(LWCOMM), RWSAV(32*N+350)

3 Description

D02PHF and its associated routines (D02PGF, D02PJF, D02PQF, D02PRF, D02PTF and D02PUF) solve the initial value problem for a first-order system of ordinary differential equations. The routines, based on Runge–Kutta methods and derived from RKSUITE (see Brankin et al. (1991)), integrate
y′=f t,y  given  y t 0=y 0
where y is the vector of n solution components and t is the independent variable.
D02PGF computes the solution at the end of an integration step. Using the information computed on that step D02PHF computes the interpolant which can be evaluated at any point on that step by D02PJF. If METHOD=1 or -1 then there is enough information available from the stages of the last step to provide an interpolant of sufficient order of accuracy; no further derivative evaluations will therefore be requested. If METHOD=2 or -2 then the interpolant is an order 8 continuous Runge–Kutta process that requires a further 3 stages of derivative evaluations that will be requested in turn before a final exit. If METHOD=3 or -3 was specified in the call to setup routine D02PQF then the interpolant is a continuous Runge–Kutta process requiring a further 7 stages of derivative evaluations that will be requested in turn.

4 References

Brankin R W, Gladwell I and Shampine L F (1991) RKSUITE: A suite of Runge–Kutta codes for the initial value problems for ODEs SoftReport 91-S1 Southern Methodist University

5 Arguments

Note: this routine uses reverse communication. Its use involves an initial entry, intermediate exits and re-entries, and a final exit, as indicated by the argument IREVCM. Between intermediate exits and re-entries, all arguments other than those specified by the value of IREVCM must remain unchanged.
1:   IREVCM – INTEGERInput/Output
On initial entry: IREVCM must be set to zero to indicate that the interpolant for a new step is being taken.
On intermediate re-entry: IREVCM should remain unchanged.
On intermediate exit: IREVCM returns a value 1 to indicate that a function evaluation is required prior to re-entry; the value of the derivatives must be returned in YP where the value of t is supplied in T and the values y t are supplied in the array Y.
On final exit:
IREVCM=-1
Successful exit; RWSAV and WCOMM contain details of the interpolant.
IREVCM=-2
Error exit; IFAIL should be interrogated to determine the nature of the error.
2:   N – INTEGERInput
On entry: n, the number of ordinary differential equations in the system to be solved by the integration routine.
Constraint: N≥1. This must be the same value as supplied in a previous call to D02PQF.
3:   NWANT – INTEGERInput
On entry: the number of components of the solution to be computed. The first NWANT components are evaluated.
Constraint: 1≤NWANT≤N.
4:   T – REAL (KIND=nag_wp)Output
On intermediate exit: T contains the value of the independent variable t at which the derivatives y′ are to be evaluated.
On final exit: contains no useful information.
5:   Y N – REAL (KIND=nag_wp) arrayOutput
On intermediate exit: Y contains the value of the solution y at which the derivatives y′ are to be evaluated.
On final exit: contains no useful information.
6:   YP N – REAL (KIND=nag_wp) arrayInput
On initial entry: need not be set.
On intermediate re-entry: YP must contain the values of the derivatives yi′ for the given values of the arguments t, yi.
7:   WCOMM LWCOMM – REAL (KIND=nag_wp) arrayCommunication Array
On entry: WCOMM need not be set.
On intermediate re-entry: WCOMM contains the partial computation of the polynomial coefficients corresponding to a continuous Runge–Kutta process for interpolating medium and high order Runge–Kutta methods.
On final exit: if METHOD=2, -2, 3 or -3, WCOMM contains details of the interpolant which must be passed unchanged to D02PJF for evaluation of the interpolant.
8:   LWCOMM – INTEGERInput
On entry: length of WCOMM.
If in a previous call to D02PQF:
  • METHOD=1 or -1, LWCOMM must be at least 1.
  • METHOD=2 or -2, LWCOMM must be at least N+max N,5×NWANT.
  • METHOD=3 or -3, LWCOMM must be at least 8×NWANT.
9:   IWSAV 130 – INTEGER arrayCommunication Array
10:   RWSAV 32×N+350 – REAL (KIND=nag_wp) arrayCommunication Array
On entry: these must be the same arrays supplied in a previous call D02PGF. They must remain unchanged between calls.
On exit: information about the integration for use on subsequent calls to D02PGF, D02PJF or other associated routines.
11:   IFAIL – INTEGERInput/Output
On initial entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, because for this routine the values of the output arguments may be useful even if IFAIL≠0 on exit, the recommended value is -1. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On final exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, a previous call to the setup routine has not been made or the communication arrays have become corrupted, or a catastrophic error has already been detected elsewhere.
You cannot continue integrating the problem.
On entry, LWCOMM=value, N=value and NWANT=value.
Constraint: for METHOD=-2 or 2, LWCOMM≥N+max N,5×NWANT.
On entry, LWCOMM=value.
Constraint: for METHOD=-1 or 1, LWCOMM≥1.
On entry, LWCOMM=value and NWANT=value.
Constraint: for METHOD=-3 or 3, LWCOMM≥8×NWANT.
On entry, N=value, but the value passed to the setup routine was N=value.
On entry, NWANT=value and N=value.
Constraint: 1≤NWANT≤N.
You cannot call this routine after the integrator has returned an error.
You cannot call this routine after the range integrator has been called.
You cannot call this routine before you have called the step integrator.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

The computed values will be of a similar accuracy to that computed by D02PGF.

8 Parallelism and Performance

D02PHF makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

None.

10 Example

See Section 10 in D02PGF.
D02 Chapter Contents
D02 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


D02PJF : NAG Library, Mark 26

D02 Chapter Contents
D02 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

D02PJF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
10 Example

1 Purpose

D02PJF evaluates the interpolant calculated by D02PHF, following an integration step performed by D02PGF to solve an initial value problem.

2 Specification

SUBROUTINE D02PJF ( ICHECK, N, NWANT, T, IDERIV, SOL, WCOMM, LWCOMM, IWSAV, RWSAV, IFAIL)
INTEGER | ICHECK, N, NWANT, IDERIV, LWCOMM, IWSAV(130), IFAIL
REAL (KIND=nag_wp) | T, SOL(NWANT), WCOMM(LWCOMM), RWSAV(32*N+350)

3 Description

When integrating using the reverse communication Runge–Kutta integrator D02PGF, the solution or its derivatives can be obtained inexpensively between steps by interpolation. D02PHF is called after a step by D02PGF from a previous value of t (=t k-1) to its current value, t=tk (i.e., a kth successful time-step has been taken). D02PJF can then be called to evaluate interpolated approximations of the function or its derivatives at any value of t in the interval t k-1,tk.

4 References

Brankin R W, Gladwell I and Shampine L F (1991) RKSUITE: A suite of Runge–Kutta codes for the initial value problems for ODEs SoftReport 91-S1 Southern Methodist University

5 Arguments

1:   ICHECK – INTEGERInput
On entry: indicates whether consistency checks on input arguments should be performed
ICHECK≠1
Don't perform checks on input arguments.
ICHECK=1
Perform consistency checks on input arguments.
It is recommended to use ICHECK=1 on the first call following a call to D02PHF and to set ICHECK≠1 on subsequent calls within the last step to avoid the overhead of argument checking.
2:   N – INTEGERInput
On entry: n, the dimension of the system of ODEs being integrated.
Constraint: this must be the same value as supplied in a previous call to D02PQF.
3:   NWANT – INTEGERInput
On entry: only the first NWANT system components to be computed. This should be the same value as passed to D02PHF when computing the interpolant.
Constraint: NWANT=NWANT passed to D02PHF.
4:   T – REAL (KIND=nag_wp)Input
On entry: t, the value of the independent variable where a solution is desired. Although any value of t can be supplied, accurate solutions can only be obtained for values in the range of the last time-step taken by D02PGF.
5:   IDERIV – INTEGERInput
On entry:
IDERIV=0
Compute approximations to the first NWANT components of the solution y t.
IDERIV=1
Compute approximations to the first NWANT components of the first derivatives of the solution y′t.
Constraint: IDERIV=0 or 1.
6:   SOL NWANT – REAL (KIND=nag_wp) arrayOutput
On exit:
IDERIV=0
The first NWANT components of the solution y t.
IDERIV=1
The first NWANT components of the first derivatives of the solution y′t.
7:   WCOMM LWCOMM – REAL (KIND=nag_wp) arrayCommunication Array
On entry: this must be the same array supplied in a previous call to D02PHF. It must remain unchanged between calls.
8:   LWCOMM – INTEGERInput
On entry: length of WCOMM. This should be the same value as supplied in a previous call to D02PHF.
If in a previous call to D02PQF:
  • METHOD=1 or -1, LWCOMM must be at least 1.
  • METHOD=2 or -2, LWCOMM must be at least N+max N,5×NWANT.
  • METHOD=3 or -3, LWCOMM≥8×NWANT.
9:   IWSAV 130 – INTEGER arrayCommunication Array
10:   RWSAV 32×N+350 – REAL (KIND=nag_wp) arrayCommunication Array
On entry: these must be the same arrays supplied in a previous call D02PGF. They must remain unchanged between calls.
On exit: information about the integration for use on subsequent calls to D02PGF, D02PHF or other associated routines.
11:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, a previous call to the setup routine has not been made or the communication arrays have become corrupted, or a catastrophic error has already been detected elsewhere.
You cannot continue integrating the problem.
On entry, IDERIV=value.
Constraint: IDERIV=0 or 1.
On entry, LWCOMM=value, N=value and NWANT=value.
Constraint: for METHOD=-2 or 2, LWCOMM≥N+max N,5×NWANT.
On entry, LWCOMM=value.
Constraint: for METHOD=-1 or 1, LWCOMM≥1.
On entry, LWCOMM=value and NWANT=value.
Constraint: for METHOD=-3 or 3, LWCOMM≥8×NWANT.
On entry, N=value, but the value passed to the setup routine was N=value.
On entry, NWANT=value, but on interpolation setup NWANT=value.
Constraint: NWANT must be unchanged from setup.
The previous call to the interpolation setup routine returned an error.
You cannot call this routine before you have called the interpolation setup.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

The computed values will be of a similar accuracy to that computed by D02PGF.

8 Parallelism and Performance

D02PJF is not threaded in any implementation.

9 Further Comments

None.

10 Example

See Section 10 in D02PGF.
D02 Chapter Contents
D02 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


D02PQF : NAG Library, Mark 26

D02 Chapter Contents
D02 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

D02PQF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
10 Example

1 Purpose

D02PQF is a setup routine which must be called prior to the first call of either of the integration routines D02PEF, D02PFF and D02PGF.

2 Specification

SUBROUTINE D02PQF ( N, TSTART, TEND, YINIT, TOL, THRESH, METHOD, HSTART, IWSAV, RWSAV, IFAIL)
INTEGER | N, METHOD, IWSAV(130), IFAIL
REAL (KIND=nag_wp) | TSTART, TEND, YINIT(N), TOL, THRESH(N), HSTART, RWSAV(32*N+350)

3 Description

D02PQF and its associated routines (D02PEF, D02PFF, D02PGF, D02PHF, D02PJF, D02PRF, D02PSF, D02PTF and D02PUF) solve the initial value problem for a first-order system of ordinary differential equations. The routines, based on Runge–Kutta methods and derived from RKSUITE (see Brankin et al. (1991)), integrate
y′=f t,y  given  y t 0=y 0
where y is the vector of n solution components and t is the independent variable.
The integration proceeds by steps from the initial point t 0 towards the final point tf. An approximate solution y is computed at each step. For each component yi, for i=1,2,…,n, the error made in the step, i.e., the local error, is estimated. The step size is chosen automatically so that the integration will proceed efficiently while keeping this local error estimate smaller than a tolerance that you specify by means of arguments TOL and THRESH.
D02PEF can be used to solve the ‘usual task’, namely integrating the system of differential equations to obtain answers at points you specify. D02PFF is used for more ‘complicated’ tasks where f t,y can readily be coded within a routine argument and high-order interpolation is not required. D02PGF is used for the most ‘complicated’ tasks where f t,y is best evaluated outside the integrator or where high-order interpolation is required.
You should consider carefully how you want the local error to be controlled. Essentially the code uses relative local error control, with TOL being the desired relative accuracy. For reliable computation, the code must work with approximate solutions that have some correct digits, so there is an upper bound on the value used for TOL. It is impossible to compute a numerical solution that is more accurate than the correctly rounded value of the true solution, so you are not allowed to specify TOL too small for the precision you are using. The magnitude of the local error in yi on any step will not be greater than TOL×max μi,THRESH i where μi is an average magnitude of yi over the step. If THRESH i is smaller than the current value of μi, this is a relative error test and TOL indicates how many significant digits you want in yi. If THRESH i is larger than the current value of μi, this is an absolute error test with tolerance TOL×THRESH i. Relative error control is the recommended mode of operation, but pure relative error control, THRESH i=0.0, is not permitted. See Section 9 for further information about error control.
D02PEF, D02PFF and D02PGF control local error rather than the true (global) error, the difference between the numerical and true solution. Control of the local error controls the true error indirectly. Roughly speaking, the code produces a solution that satisfies the differential equation with a discrepancy bounded in magnitude by the error tolerance. What this implies about how close the numerical solution is to the true solution depends on the stability of the problem. Most practical problems are at least moderately stable, and the true error is then comparable to the error tolerance. To judge the accuracy of the numerical solution, you could reduce TOL substantially, e.g., use 0.1×TOL, and solve the problem again. This will usually result in a rather more accurate solution, and the true error of the first integration can be estimated by comparison. Alternatively, a global error assessment can be computed automatically using the argument METHOD. Because indirect control of the true error by controlling the local error is generally satisfactory and because both ways of assessing true errors cost twice, or more, the cost of the integration itself, such assessments are used mostly for spot checks, selecting appropriate tolerances for local error control, and exploratory computations.
D02PEF, D02PFF and D02PGF each implement three Runge–Kutta formula pairs, and you must select one for the integration. The best choice for METHOD depends on the problem. The order of accuracy is 3, 5 and 8 respectively. As a rule, the smaller TOL is, the larger you should take the order of the METHOD. If the components THRESH are small enough that you are effectively specifying relative error control, experience suggests
TOL | efficient METHOD
10-2-10-4 | order 2 and 3 pair
10-3-10-6 | order 4 and 5 pair
10-5- | order 7 and 8 pair
The overlap in the ranges of tolerances appropriate for a given METHOD merely reflects the dependence of efficiency on the problem being solved. Making TOL smaller will normally make the integration more expensive. However, in the range of tolerances appropriate to a METHOD, the increase in cost is modest. There are situations for which one METHOD, or even this kind of code, is a poor choice. You should not specify a very small value for THRESH i, when the ith solution component might vanish. In particular, you should not do this when yi=0.0. If you do, the code will have to work hard with any value for METHOD to compute significant digits, but the lowest order method is a particularly poor choice in this situation. All three methods are inefficient when the problem is ‘stiff’. If it is only mildly stiff, you can solve it with acceptable efficiency with the order 2 and 3 pair, but if it is moderately or very stiff, a code designed specifically for such problems will be much more efficient. The higher the order the more smoothness is required of the solution in order for the method to be efficient.
When assessment of the true (global) error is requested, this error assessment is updated at each step. Its value can be obtained at any time by a call to D02PUF. The code monitors the computation of the global error assessment and reports any doubts it has about the reliability of the results. The assessment scheme requires some smoothness of f t,y, and it can be deceived if f is insufficiently smooth. At very crude tolerances the numerical solution can become so inaccurate that it is impossible to continue assessing the accuracy reliably. At very stringent tolerances the effects of finite precision arithmetic can make it impossible to assess the accuracy reliably. The cost of this is roughly twice the cost of the integration itself with the 5th and 8th order methods, and three times with the 3rd order method.
The first step of the integration is critical because it sets the scale of the problem. The integrator will find a starting step size automatically if you set the argument HSTART to 0.0. Automatic selection of the first step is so effective that you should normally use it. Nevertheless, you might want to specify a trial value for the first step to be certain that the code recognizes the scale on which phenomena occur near the initial point. Also, automatic computation of the first step size involves some cost, so supplying a good value for this step size will result in a less expensive start. If you are confident that you have a good value, provide it via the argument HSTART.

4 References

Brankin R W, Gladwell I and Shampine L F (1991) RKSUITE: A suite of Runge–Kutta codes for the initial value problems for ODEs SoftReport 91-S1 Southern Methodist University

5 Arguments

1:   N – INTEGERInput
On entry: n, the number of ordinary differential equations in the system to be solved by the integration routine.
Constraint: N≥1.
2:   TSTART – REAL (KIND=nag_wp)Input
On entry: the initial value of the independent variable, t 0.
3:   TEND – REAL (KIND=nag_wp)Input
On entry: the final value of the independent variable, tf, at which the solution is required. TSTART and TEND together determine the direction of integration.
Constraint: TEND must be distinguishable from TSTART for the method and the precision of the machine being used.
4:   YINIT N – REAL (KIND=nag_wp) arrayInput
On entry: y 0, the initial values of the solution, yi, for i=1,2,…,n.
5:   TOL – REAL (KIND=nag_wp)Input
On entry: a relative error tolerance. The actual tolerance used is max 10×machine precision,min TOL,0.01; that is, the minimum tolerance is set at 10 times machine precision and the maximum tolerance is set at 0.01.
6:   THRESH N – REAL (KIND=nag_wp) arrayInput
On entry: a vector of thresholds. For the ith component, the actual threshold used is max safe range,THRESH i, where safe range is the value returned by X02AMF.
7:   METHOD – INTEGERInput
On entry: the Runge–Kutta method to be used.
METHOD=1 or -1
A 2 3 pair is used.
METHOD=2 or -2
A 4 5 pair is used.
METHOD=3 or -3
A 7 8 pair is used.
Constraint: METHOD=1, -1, 2, -2, 3 or -3. Note: if METHOD>0 then global error assessment is to be computed with the main integration; if METHOD<0 then global error assessment will not be computed.
8:   HSTART – REAL (KIND=nag_wp)Input
On entry: a value for the size of the first step in the integration to be attempted. The absolute value of HSTART is used with the direction being determined by TSTART and TEND. The actual first step taken by the integrator may be different to HSTART if the underlying algorithm determines that HSTART is unsuitable. If HSTART=0.0 then the size of the first step is computed automatically.
Suggested value: HSTART=0.0.
9:   IWSAV 130 – INTEGER arrayCommunication Array
10:   RWSAV 32×N+350 – REAL (KIND=nag_wp) arrayCommunication Array
On exit: the contents of the communication arrays must not be changed prior to calling one of the integration routines.
11:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, METHOD=value.
Constraint: METHOD=-3, -2, -1, 1, 2 or 3.
On entry, N=value.
Constraint: N≥1.
On entry, too much workspace required.
Workspace provided was value, workspace required is value.
On entry, TSTART=value.
Constraint: TSTART≠TEND.
On entry, TSTART is too close to TEND.
TSTART-TEND=value, but this quantity should be at least value.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

Not applicable.

8 Parallelism and Performance

D02PQF is not threaded in any implementation.

9 Further Comments

If D02PFF and D02PGF is to be used for the integration then the value of the argument TEND may be reset during the integration without the overhead associated with a complete restart; this can be achieved by a call to D02PRF.
It is often the case that a solution component (the ith, say) is of no interest when it is smaller in magnitude than a certain threshold. You can inform the code of this by setting the ith component of THRESH to this threshold. In this way you avoid the cost of computing significant digits in the ith component of y when it is smaller than the threshold of interest. This matter is important when a component of y vanishes, and in particular, when the initial value is zero. An appropriate threshold depends on the general size of y in the course of the integration. Physical reasoning may help you select suitable threshold values. If you do not know what to expect of y, you can find out by a preliminary integration using D02PEF with nominal values of THRESH. As D02PEF integrates by steps in time, it stores, for each component, the largest magnitude of solution computed so far; these values are output in the array YMAX. This can help determine more appropriate values for THRESH for an accurate integration. For example, the values in THRESH could be set to 10×machine precision times the final value of YMAX.

10 Example

See Section 10 in D02PEF, D02PFF, D02PRF, D02PSF and D02PUF.
D02 Chapter Contents
D02 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


D02PRF : NAG Library, Mark 26

D02 Chapter Contents
D02 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

D02PRF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

D02PRF resets the end point in an integration performed by D02PFF and D02PGF.

2 Specification

SUBROUTINE D02PRF ( TENDNU, IWSAV, RWSAV, IFAIL)
INTEGER | IWSAV(130), IFAIL
REAL (KIND=nag_wp) | TENDNU, RWSAV(350)

3 Description

D02PRF and its associated routines (D02PFF, D02PGF, D02PHF, D02PJF, D02PQF, D02PSF, D02PTF and D02PUF) solve the initial value problem for a first-order system of ordinary differential equations. The routines, based on Runge–Kutta methods and derived from RKSUITE (see Brankin et al. (1991)), integrate
y′=f t,y  given  y t 0=y 0
where y is the vector of n solution components and t is the independent variable.
D02PRF is used to reset the final value of the independent variable, tf, when the integration is already underway. It can be used to extend or reduce the range of integration. The new value must be beyond the current value of the independent variable (as returned in TNOW by D02PFF or D02PGF) in the current direction of integration. It is much more efficient to use D02PRF for this purpose than to use D02PQF which involves the overhead of a complete restart of the integration.
If you want to change the direction of integration then you must restart by a call to D02PQF.

4 References

Brankin R W, Gladwell I and Shampine L F (1991) RKSUITE: A suite of Runge–Kutta codes for the initial value problems for ODEs SoftReport 91-S1 Southern Methodist University

5 Arguments

1:   TENDNU – REAL (KIND=nag_wp)Input
On entry: the new value for tf.
Constraint: sign TENDNU-TNOW=sign TEND-TSTART, where TSTART and TEND are as supplied in the previous call to D02PQF and TNOW is returned by the preceding call to D02PFF or D02PGF (i.e., integration must proceed in the same direction as before). TENDNU must be distinguishable from TNOW for the method and the machine precision being used.
2:   IWSAV 130 – INTEGER arrayCommunication Array
3:   RWSAV 350 – REAL (KIND=nag_wp) arrayCommunication Array
Note: the communication array RWSAV used by the other routines in the suite must be used here however, only the first 350 elements will be referenced.
On entry: these must be the same arrays supplied in a previous call to D02PFF or D02PGF. They must remain unchanged between calls.
On exit: information about the integration for use on subsequent calls to D02PFF or D02PGF or other associated routines.
4:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, a previous call to the setup routine has not been made or the communication arrays have become corrupted, or a catastrophic error has already been detected elsewhere. You cannot continue integrating the problem.
On entry, TENDNU is not beyond TNOW (step integrator) in the direction of integration.
The direction is negative, TENDNU=value and TNOW=value.
On entry, TENDNU is not beyond TNOW (step integrator) in the direction of integration.
The direction is positive, TENDNU=value and TNOW=value.
On entry, TENDNU is too close to TNOW (step integrator). Their difference is value, but this quantity must be at least value.
You cannot call this routine after the integrator has returned an error.
You cannot call this routine before you have called the setup routine.
You cannot call this routine before you have called the step integrator.
You cannot call this routine when the range integrator has been used.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

Not applicable.

8 Parallelism and Performance

D02PRF is not threaded in any implementation.

9 Further Comments

None.

10 Example

This example integrates a two body problem. The equations for the coordinates x t,y t of one body as functions of time t in a suitable frame of reference are
x′′=-x r 3
y′′=-y r 3,   r=x 2+y 2.
The initial conditions
x 0=1-ε, x′0=0 y 0=0, y′0= 1+ε 1-ε
lead to elliptic motion with 0<ε<1. ε=0.7 is selected and the system of ODEs is reposed as
y 1′=y 3 y 2′=y 4 y 3′=- y 1 r 3 y 4′=- y 2 r 3
over the range 0,6 π. Relative error control is used with threshold values of 1.0E−10 for each solution component and compute the solution at intervals of length π across the range using D02PRF to reset the end of the integration range. A high-order Runge–Kutta method (METHOD=-3) is also used with tolerances TOL=1.0E−4 and TOL=1.0E−5 in turn so that the solutions may be compared.

10.1 Program Text

Program Text (d02prfe.f90)

10.2 Program Data

Program Data (d02prfe.d)

10.3 Program Results

Program Results (d02prfe.r)

GnuplotProduced by GNUPLOT 4.6 patchlevel 3 −0.8 −0.6 −0.4 −0.2 0 0.2 0.4 0.6 0.8 −2 −1.5 −1 −0.5 0 0.5 −0.1 −0.05 0 0.05 0.1 −0.25 −0.2 −0.15 −0.1 −0.05 0 0.05 Orbit - y y Deviation from True Ellipse Orbit - x Example Program Solution with TOL = 0.1e−04 x Deviation from True Ellipse orbit deviation o gnuplot_plot_1 gnuplot_plot_2
D02 Chapter Contents
D02 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


D02PSF : NAG Library, Mark 26

D02 Chapter Contents
D02 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

D02PSF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

D02PSF computes the solution of a system of ordinary differential equations using interpolation anywhere on an integration step taken by D02PFF.

2 Specification

SUBROUTINE D02PSF ( N, TWANT, IDERIV, NWANT, YWANT, YPWANT, F, WCOMM, LWCOMM, IUSER, RUSER, IWSAV, RWSAV, IFAIL)
INTEGER | N, IDERIV, NWANT, LWCOMM, IUSER(*), IWSAV(130), IFAIL
REAL (KIND=nag_wp) | TWANT, YWANT(NWANT), YPWANT(NWANT), WCOMM(LWCOMM), RUSER(*), RWSAV(32*N+350)
EXTERNAL | F

3 Description

D02PSF and its associated routines (D02PFF, D02PQF, D02PRF, D02PTF and D02PUF) solve the initial value problem for a first-order system of ordinary differential equations. The routines, based on Runge–Kutta methods and derived from RKSUITE (see Brankin et al. (1991)), integrate
y′=f t,y  given  y t 0=y 0
where y is the vector of n solution components and t is the independent variable.
D02PFF computes the solution at the end of an integration step. Using the information computed on that step D02PSF computes the solution by interpolation at any point on that step. It cannot be used if METHOD=3 or -3 was specified in the call to setup routine D02PQF.

4 References

Brankin R W, Gladwell I and Shampine L F (1991) RKSUITE: A suite of Runge–Kutta codes for the initial value problems for ODEs SoftReport 91-S1 Southern Methodist University

5 Arguments

1:   N – INTEGERInput
On entry: n, the number of ordinary differential equations in the system to be solved by the integration routine.
Constraint: N≥1.
2:   TWANT – REAL (KIND=nag_wp)Input
On entry: t, the value of the independent variable where a solution is desired.
3:   IDERIV – INTEGERInput
On entry: determines whether the solution and/or its first derivative are to be computed
IDERIV=0
compute approximate solution.
IDERIV=1
compute approximate first derivative.
IDERIV=2
compute approximate solution and first derivative.
Constraint: IDERIV=0, 1 or 2.
4:   NWANT – INTEGERInput
On entry: the number of components of the solution to be computed. The first NWANT components are evaluated.
Constraint: 1≤NWANT≤N.
5:   YWANT NWANT – REAL (KIND=nag_wp) arrayOutput
On exit: an approximation to the first NWANT components of the solution at TWANT if IDERIV=0 or 2. Otherwise YWANT is not defined.
6:   YPWANT NWANT – REAL (KIND=nag_wp) arrayOutput
On exit: an approximation to the first NWANT components of the first derivative at TWANT if IDERIV=1 or 2. Otherwise YPWANT is not defined.
7:   F – SUBROUTINE, supplied by the user.External Procedure
F must evaluate the functions fi (that is the first derivatives yi′) for given values of the arguments t,yi. It must be the same procedure as supplied to D02PFF.
The specification of F is:
SUBROUTINE F ( T, N, Y, YP, IUSER, RUSER)
INTEGER | N, IUSER(*)
REAL (KIND=nag_wp) | T, Y(N), YP(N), RUSER(*)
1:   T – REAL (KIND=nag_wp)Input
On entry: t, the current value of the independent variable.
2:   N – INTEGERInput
On entry: n, the number of ordinary differential equations in the system to be solved.
3:   Y N – REAL (KIND=nag_wp) arrayInput
On entry: the current values of the dependent variables, yi, for i=1,2,…,n.
4:   YP N – REAL (KIND=nag_wp) arrayOutput
On exit: the values of fi, for i=1,2,…,n.
5:   IUSER* – INTEGER arrayUser Workspace
6:   RUSER* – REAL (KIND=nag_wp) arrayUser Workspace
F is called with the arguments IUSER and RUSER as supplied to D02PSF. You are free to use the arrays IUSER and RUSER to supply information to F as an alternative to using COMMON global variables.
F must either be a module subprogram USEd by, or declared as EXTERNAL in, the (sub)program from which D02PSF is called. Arguments denoted as Input must not be changed by this procedure.
8:   WCOMM LWCOMM – REAL (KIND=nag_wp) arrayCommunication Array
On entry: this array stores information that can be utilized on subsequent calls to D02PSF.
9:   LWCOMM – INTEGERInput
On entry: length of WCOMM.
If in a previous call to D02PQF:
  • METHOD=1 or -1 then LWCOMM must be at least 1.
  • METHOD=2 or -2 then LWCOMM must be at least N+max N,5×NWANT.
  • METHOD=3 or -3 then WCOMM and LWCOMM are not referenced.
10:   IUSER* – INTEGER arrayUser Workspace
11:   RUSER* – REAL (KIND=nag_wp) arrayUser Workspace
IUSER and RUSER are not used by D02PSF, but are passed directly to F and may be used to pass information to this routine as an alternative to using COMMON global variables.
12:   IWSAV 130 – INTEGER arrayCommunication Array
13:   RWSAV 32×N+350 – REAL (KIND=nag_wp) arrayCommunication Array
On entry: these must be the same arrays supplied in a previous call D02PFF. They must remain unchanged between calls.
On exit: information about the integration for use on subsequent calls to D02PFF, D02PSF or other associated routines.
14:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
METHOD=-3 or 3 in setup, but interpolation is not available for this method. Either use METHOD=-2 or 2 in setup or use reset routine to force the integrator to step to particular points.
On entry, a previous call to the setup routine has not been made or the communication arrays have become corrupted, or a catastrophic error has already been detected elsewhere.
You cannot continue integrating the problem.
On entry, IDERIV=value.
Constraint: IDERIV=0, 1 or 2.
On entry, LWCOMM=value, N=value and NWANT=value.
Constraint: for METHOD=-2 or 2, LWCOMM≥N+max N,5×NWANT.
On entry, LWCOMM=value.
Constraint: for METHOD=-1 or 1, LWCOMM≥1.
On entry, N=value, but the value passed to the setup routine was N=value.
On entry, NWANT=value and N=value.
Constraint: 1≤NWANT≤N.
You cannot call this routine after the integrator has returned an error.
You cannot call this routine before you have called the step integrator.
You cannot call this routine when you have specified, in the setup routine, that the range integrator will be used.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

The computed values will be of a similar accuracy to that computed by D02PFF.

8 Parallelism and Performance

D02PSF makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

None.

10 Example

This example solves the equation
y′′ = -y ,   y 0=0,   y′0=1
reposed as
y 1′ = y 2
y 2′ = -y 1
over the range 0,2 π with initial conditions y 1=0.0 and y 2=1.0. Relative error control is used with threshold values of 1.0E−8 for each solution component. D02PFF is used to integrate the problem one step at a time and D02PSF is used to compute the first component of the solution and its derivative at intervals of length π/8 across the range whenever these points lie in one of those integration steps. A low order Runge–Kutta method (METHOD=-1) is also used with tolerances TOL=1.0E−4 and TOL=1.0E−5 in turn so that solutions may be compared.

10.1 Program Text

Program Text (d02psfe.f90)

10.2 Program Data

Program Data (d02psfe.d)

10.3 Program Results

Program Results (d02psfe.r)

GnuplotProduced by GNUPLOT 4.6 patchlevel 3 −1 −0.5 0 0.5 1 0 1 2 3 4 5 6 7 Solution t Example Program Simple Sine Solution, TOL = 0.001 solution derivative gnuplot_plot_1 gnuplot_plot_2
D02 Chapter Contents
D02 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


D02PTF : NAG Library, Mark 26

D02 Chapter Contents
D02 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

D02PTF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
10 Example

1 Purpose

D02PTF provides details about an integration performed by either D02PEF, D02PFF or D02PGF.

2 Specification

SUBROUTINE D02PTF ( FEVALS, STEPCOST, WASTE, STEPSOK, HNEXT, IWSAV, RWSAV, IFAIL)
INTEGER | FEVALS, STEPCOST, STEPSOK, IWSAV(130), IFAIL
REAL (KIND=nag_wp) | WASTE, HNEXT, RWSAV(350)

3 Description

D02PTF and its associated routines (D02PEF, D02PFF, D02PGF, D02PHF, D02PJF, D02PQF, D02PRF, D02PSF and D02PUF) solve the initial value problem for a first-order system of ordinary differential equations. The routines, based on Runge–Kutta methods and derived from RKSUITE (see Brankin et al. (1991)), integrate
y′ = f t,y   given   y t 0=y 0
where y is the vector of n solution components and t is the independent variable.
After a call to D02PEF, D02PFF or D02PGF, D02PTF can be called to obtain information about the cost of the integration and the size of the next step.

4 References

Brankin R W, Gladwell I and Shampine L F (1991) RKSUITE: A suite of Runge–Kutta codes for the initial value problems for ODEs SoftReport 91-S1 Southern Methodist University

5 Arguments

1:   FEVALS – INTEGEROutput
On exit: the total number of evaluations of f used in the integration so far; this includes evaluations of f required for the secondary integration necessary if D02PQF had previously been called with METHOD>0.
2:   STEPCOST – INTEGEROutput
On exit: the cost in terms of number of evaluations of f of a typical step with the method being used for the integration. The method is specified by the argument METHOD in a prior call to D02PQF.
3:   WASTE – REAL (KIND=nag_wp)Output
On exit: the number of attempted steps that failed to meet the local error requirement divided by the total number of steps attempted so far in the integration. A ‘large’ fraction indicates that the integrator is having trouble with the problem being solved. This can happen when the problem is ‘stiff’ and also when the solution has discontinuities in a low-order derivative.
4:   STEPSOK – INTEGEROutput
On exit: the number of accepted steps.
5:   HNEXT – REAL (KIND=nag_wp)Output
On exit: the step size the integrator will attempt to use for the next step.
6:   IWSAV 130 – INTEGER arrayCommunication Array
7:   RWSAV 350 – REAL (KIND=nag_wp) arrayCommunication Array
Note: the communication RWSAV used by the other routines in the suite must be used here however, only the first 350 elements will be referenced.
On entry: these must be the same arrays supplied in a previous call to D02PEF, D02PFF or D02PGF. They must remain unchanged between calls.
On exit: information about the integration for use on subsequent calls to D02PEF, D02PFF or D02PGF or other associated routines.
8:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, a previous call to the setup routine has not been made or the communication arrays have become corrupted, or a catastrophic error has already been detected elsewhere.
You cannot continue integrating the problem.
You cannot call this routine before you have called the integrator.
You have already made one call to this routine after the integrator could not achieve specified accuracy.
You cannot call this routine again.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

Not applicable.

8 Parallelism and Performance

D02PTF is not threaded in any implementation.

9 Further Comments

When a secondary integration has taken place, that is when global error assessment has been specified using METHOD>0 in a prior call to D02PQF, then the approximate number of evaluations of f used in this secondary integration is given by 2×STEPSOK×STEPCOST for METHOD=2 or 3 and 3×STEPSOK×STEPCOST for METHOD=1.

10 Example

See Section 10 in D02PEF, D02PFF, D02PRF, D02PSF and D02PUF.
D02 Chapter Contents
D02 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


D02PUF : NAG Library, Mark 26

D02 Chapter Contents
D02 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

D02PUF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

D02PUF provides details about global error assessment computed during an integration with either D02PEF, D02PFF or D02PGF.

2 Specification

SUBROUTINE D02PUF ( N, RMSERR, ERRMAX, TERRMX, IWSAV, RWSAV, IFAIL)
INTEGER | N, IWSAV(130), IFAIL
REAL (KIND=nag_wp) | RMSERR(N), ERRMAX, TERRMX, RWSAV(32*N+350)

3 Description

D02PUF and its associated routines (D02PEF, D02PFF, D02PGF, D02PHF, D02PJF, D02PQF, D02PRF, D02PSF and D02PTF) solve the initial value problem for a first-order system of ordinary differential equations. The routines, based on Runge–Kutta methods and derived from RKSUITE (see Brankin et al. (1991)), integrate
y′=f t,y  given  y t 0=y 0
where y is the vector of n solution components and t is the independent variable.
After a call to D02PEF, D02PFF or D02PGF, D02PUF can be called for information about error assessment, if this assessment was specified in the setup routine D02PQF. A more accurate ‘true’ solution y^ is computed in a secondary integration. The error is measured as specified in D02PQF for local error control. At each step in the primary integration, an average magnitude μi of component yi is computed, and the error in the component is
yi-y^i max μi,THRESH i .
It is difficult to estimate reliably the true error at a single point. For this reason the RMS (root-mean-square) average of the estimated global error in each solution component is computed. This average is taken over all steps from the beginning of the integration through to the current integration point. If all has gone well, the average errors reported will be comparable to TOL (see D02PQF). The maximum error seen in any component in the integration so far and the point where the maximum error first occurred are also reported.

4 References

Brankin R W, Gladwell I and Shampine L F (1991) RKSUITE: A suite of Runge–Kutta codes for the initial value problems for ODEs SoftReport 91-S1 Southern Methodist University

5 Arguments

1:   N – INTEGERInput
On entry: n, the number of ordinary differential equations in the system to be solved by the integration routine.
Constraint: N≥1.
2:   RMSERR N – REAL (KIND=nag_wp) arrayOutput
On exit: RMSERR i approximates the RMS average of the true error of the numerical solution for the ith solution component, for i=1,2,…,n. The average is taken over all steps from the beginning of the integration to the current integration point.
3:   ERRMAX – REAL (KIND=nag_wp)Output
On exit: the maximum weighted approximate true error taken over all solution components and all steps.
4:   TERRMX – REAL (KIND=nag_wp)Output
On exit: the first value of the independent variable where an approximate true error attains the maximum value, ERRMAX.
5:   IWSAV 130 – INTEGER arrayCommunication Array
6:   RWSAV 32×N+350 – REAL (KIND=nag_wp) arrayCommunication Array
On entry: these must be the same arrays supplied in a previous call to D02PEF, D02PFF or D02PGF. They must remain unchanged between calls.
On exit: information about the integration for use on subsequent calls to D02PEF, D02PFF or D02PGF or other associated routines.
7:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
No error assessment is available since the integrator has not actually taken any successful steps.
No error assessment is available since you did not ask for it in your call to the setup routine.
On entry, a previous call to the setup routine has not been made or the communication arrays have become corrupted, or a catastrophic error has already been detected elsewhere.
You cannot continue integrating the problem.
On entry, N=value, but the value passed to the setup routine was N=value.
You cannot call this routine before you have called the integrator.
You have already made one call to this routine after the integrator could not achieve specified accuracy.
You cannot call this routine again.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

Not applicable.

8 Parallelism and Performance

D02PUF is not threaded in any implementation.

9 Further Comments

If the integration has proceeded ‘well’ and the problem is smooth enough, stable and not too difficult then the values returned in the arguments RMSERR and ERRMAX should be comparable to the value of TOL specified in the prior call to D02PQF.

10 Example

This example integrates a two body problem. The equations for the coordinates x t,y t of one body as functions of time t in a suitable frame of reference are
x′′=-x r 3
y′′=-y r 3,   r=x 2+y 2.
The initial conditions
x 0=1-ε, x′0=0 y 0=0, y′0= 1+ε 1-ε
lead to elliptic motion with 0<ε<1. ε=0.7 is selected and the system of ODEs is reposed as
y 1′=y 3 y 2′=y 4 y 3′=- y 1 r 3 y 4′=- y 2 r 3
over the range 0,3 π. Relative error control is used with threshold values of 1.0E−10 for each solution component and a high-order Runge–Kutta method (METHOD=3) with tolerance TOL=1.0E−6.
Note that for illustration purposes since it is not necessary for this problem, this example integrates to the end of the range regardless of efficiency concerns (i.e., returns from D02PEF with IFAIL=2, 3 or 4).

10.1 Program Text

Program Text (d02pufe.f90)

10.2 Program Data

Program Data (d02pufe.d)

10.3 Program Results

Program Results (d02pufe.r)

GnuplotProduced by GNUPLOT 4.6 patchlevel 3 −0.8 −0.6 −0.4 −0.2 0 0.2 0.4 0.6 0.8 −2 −1.5 −1 −0.5 0 0.5 −0.1 −0.05 0 0.05 0.1 −0.25 −0.2 −0.15 −0.1 −0.05 0 0.05 Orbit - y y Deviation from True Ellipse Orbit - x Example Program Solution to a Two-body Problem using High-order Runge-Kutta x Deviation from True Ellipse orbit deviation o gnuplot_plot_1 gnuplot_plot_2
D02 Chapter Contents
D02 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


D02QFF : NAG Library, Mark 26

D02 Chapter Contents
D02 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

D02QFF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

D02QFF is a routine for integrating a non-stiff system of first-order ordinary differential equations using a variable-order variable-step Adams' method. A root-finding facility is provided.

2 Specification

SUBROUTINE D02QFF ( FCN, NEQF, T, Y, TOUT, G, NEQG, ROOT, RWORK, LRWORK, IWORK, LIWORK, IFAIL)
INTEGER | NEQF, NEQG, LRWORK, IWORK(LIWORK), LIWORK, IFAIL
REAL (KIND=nag_wp) | T, Y(NEQF), TOUT, G, RWORK(LRWORK)
LOGICAL | ROOT
EXTERNAL | FCN, G

3 Description

Given the initial values x,y 1,y 2,…,yNEQF D02QFF integrates a non-stiff system of first-order differential equations of the type
yi′=fi x,y 1,y 2,…,yNEQF,  i=1,2,…,NEQF,
from x=T to x=TOUT using a variable-order variable-step Adams' method. The system is defined by FCN, which evaluates fi in terms of x and y 1,y 2,…,yNEQF, and y 1,y 2,…,yNEQF are supplied at x=T. The routine is capable of finding roots (values of x) of prescribed event functions of the form
gj x,y,y′ = 0 ,   j=1,2,…,NEQG .
(See D02QWF for the specification of NEQG.)
Each gj is considered to be independent of the others so that roots are sought of each gj individually. The root reported by the routine will be the first root encountered by any gj. Two techniques for determining the presence of a root in an integration step are available: the sophisticated method described in Watts (1985) and a simplified method whereby sign changes in each gj are looked for at the ends of each integration step. The event functions are defined by G supplied by you which evaluates gj in terms of x,y 1,…,yNEQF and y 1′,…,yNEQF′. In one-step mode the routine returns an approximation to the solution at each integration point. In interval mode this value is returned at the end of the integration range. If a root is detected this approximation is given at the root. You select the mode of operation, the error control, the root-finding technique and various optional inputs by a prior call to the setup routine D02QWF.
For a description of the practical implementation of an Adams' formula see Shampine and Gordon (1975) and Shampine and Watts (1979).

4 References

Shampine L F and Gordon M K (1975) Computer Solution of Ordinary Differential Equations – The Initial Value Problem W H Freeman & Co., San Francisco
Shampine L F and Watts H A (1979) DEPAC – design of a user oriented package of ODE solvers Report SAND79-2374 Sandia National Laboratory
Watts H A (1985) RDEAM – An Adams ODE code with root solving capability Report SAND85-1595 Sandia National Laboratory

5 Arguments

1:   FCN – SUBROUTINE, supplied by the user.External Procedure
FCN must evaluate the functions fi (that is the first derivatives yi′) for given values of its arguments x, y 1,y 2,…,yNEQF.
The specification of FCN is:
SUBROUTINE FCN ( NEQF, X, Y, F)
INTEGER | NEQF
REAL (KIND=nag_wp) | X, Y(NEQF), F(NEQF)
1:   NEQF – INTEGERInput
On entry: the number of differential equations.
2:   X – REAL (KIND=nag_wp)Input
On entry: the current value of the argument x.
3:   Y NEQF – REAL (KIND=nag_wp) arrayInput
On entry: yi, for i=1,2,…,NEQF, the current value of the argument.
4:   F NEQF – REAL (KIND=nag_wp) arrayOutput
On exit: the value of fi, for i=1,2,…,NEQF.
FCN must either be a module subprogram USEd by, or declared as EXTERNAL in, the (sub)program from which D02QFF is called. Arguments denoted as Input must not be changed by this procedure.
2:   NEQF – INTEGERInput
On entry: the number of first-order ordinary differential equations to be solved by D02QFF. It must contain the same value as the argument NEQF used in a prior call to D02QWF.
Constraint: NEQF≥1.
3:   T – REAL (KIND=nag_wp)Input/Output
On entry: after a call to D02QWF with STATEF='S' (i.e., an initial entry), T must be set to the initial value of the independent variable x.
On exit: the value of x at which y has been computed. This may be an intermediate output point, a root, TOUT or a point at which an error has occurred. If the integration is to be continued, possibly with a new value for TOUT, T must not be changed.
4:   Y NEQF – REAL (KIND=nag_wp) arrayInput/Output
On entry: the initial values of the solution y 1,y 2,…,yNEQF.
On exit: the computed values of the solution at the exit value of T. If the integration is to be continued, possibly with a new value for TOUT, these values must not be changed.
5:   TOUT – REAL (KIND=nag_wp)Input
On entry: the next value of x at which a computed solution is required. For the initial T, the input value of TOUT is used to determine the direction of integration. Integration is permitted in either direction. If TOUT=T on exit, TOUT must be reset beyond T in the direction of integration, before any continuation call.
6:   G – REAL (KIND=nag_wp) FUNCTION, supplied by the user.External Procedure
G must evaluate a given component of g x,y,y′ at a specified point.
If root-finding is not required the actual argument for G must be the dummy routine D02QFZ. (D02QFZ is included in the NAG Library.)
The specification of G is:
FUNCTION G ( NEQF, X, Y, YP, K)
REAL (KIND=nag_wp) G
INTEGER | NEQF, K
REAL (KIND=nag_wp) | X, Y(NEQF), YP(NEQF)
1:   NEQF – INTEGERInput
On entry: the number of differential equations being solved.
2:   X – REAL (KIND=nag_wp)Input
On entry: the current value of the independent variable.
3:   Y NEQF – REAL (KIND=nag_wp) arrayInput
On entry: the current values of the dependent variables.
4:   YP NEQF – REAL (KIND=nag_wp) arrayInput
On entry: the current values of the derivatives of the dependent variables.
5:   K – INTEGERInput
On entry: the component of g which must be evaluated.
G must either be a module subprogram USEd by, or declared as EXTERNAL in, the (sub)program from which D02QFF is called. Arguments denoted as Input must not be changed by this procedure.
7:   NEQG – INTEGERInput
On entry: the number of event functions which you are defining for root-finding. If root-finding is not required the value for NEQG must be ≤0. Otherwise it must be the same argument NEQG used in the prior call to D02QWF.
8:   ROOT – LOGICALOutput
On exit: if root-finding was required (NEQG>0 on entry), then ROOT specifies whether or not the output value of the argument T is a root of one of the event functions. If ROOT=.FALSE., then no root was detected, whereas ROOT=.TRUE. indicates a root and you should make a call to D02QYF for further information.
If root-finding was not required (NEQG=0 on entry), then on exit ROOT=.FALSE..
9:   RWORK LRWORK – REAL (KIND=nag_wp) arrayCommunication Array
This must be the same argument RWORK as supplied to D02QWF. It is used to pass information from D02QWF to D02QFF, and from D02QFF to D02QXF, D02QYF and D02QZF. Therefore the contents of this array must not be changed before the call to D02QFF or calling any of the routines D02QXF, D02QYF and D02QZF.
10:   LRWORK – INTEGERInput
On entry: the dimension of the array RWORK as declared in the (sub)program from which D02QFF is called.
This must be the same argument LRWORK as supplied to D02QWF.
11:   IWORK LIWORK – INTEGER arrayCommunication Array
This must be the same argument IWORK as supplied to D02QWF. It is used to pass information from D02QWF to D02QFF, and from D02QFF to D02QXF, D02QYF and D02QZF. Therefore the contents of this array must not be changed before the call to D02QFF or calling any of the routines D02QXF, D02QYF and D02QZF.
12:   LIWORK – INTEGERInput
On entry: the dimension of the array IWORK as declared in the (sub)program from which D02QFF is called.
This must be the same argument LIWORK as supplied to D02QWF.
13:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, because for this routine the values of the output arguments may be useful even if IFAIL≠0 on exit, the recommended value is -1. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, the integrator detected an illegal input, or D02QWF has not been called before the call to the integrator.
This error may be caused by overwriting elements of RWORK and IWORK.
IFAIL=2
The maximum number of steps has been attempted (at a cost of about 2 calls to FCN per step). (See argument MAXSTP in D02QWF.) If integration is to be continued then you need only reset IFAIL and call the routine again and a further MAXSTP steps will be attempted.
IFAIL=3
The step size needed to satisfy the error requirements is too small for the machine precision being used. (See argument TOLFAC in D02QXF.)
IFAIL=4
Some error weight wi became zero during the integration (see arguments VECTOL, RTOL and ATOL in D02QWF.) Pure relative error control (ATOL=0.0) was requested on a variable (the ith) which has now become zero. (See argument BADCMP in D02QXF.) The integration was successful as far as T.
IFAIL=5
The problem appears to be stiff (see the D02 Chapter Introduction for a discussion of the term ‘stiff’). Although it is inefficient to use this integrator to solve stiff problems, integration may be continued by resetting IFAIL and calling the routine again.
IFAIL=6
A change in sign of an event function has been detected but the root-finding process appears to have converged to a singular point T rather than a root. Integration may be continued by resetting IFAIL and calling the routine again.
IFAIL=7
The code has detected two successive error exits at the current value of T and cannot proceed. Check all input variables.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

The accuracy of integration is determined by the arguments VECTOL, RTOL and ATOL in a prior call to D02QWF. Note that only the local error at each step is controlled by these arguments. The error estimates obtained are not strict bounds but are usually reliable over one step. Over a number of steps the overall error may accumulate in various ways, depending on the properties of the differential equation system. The code is designed so that a reduction in the tolerances should lead to an approximately proportional reduction in the error. You are strongly recommended to call D02QFF with more than one set of tolerances and to compare the results obtained to estimate their accuracy.
The accuracy obtained depends on the type of error test used. If the solution oscillates around zero a relative error test should be avoided, whereas if the solution is exponentially increasing an absolute error test should not be used. If different accuracies are required for different components of the solution then a component-wise error test should be used. For a description of the error test see the specifications of the arguments VECTOL, ATOL and RTOL in the routine document for D02QWF.
The accuracy of any roots located will depend on the accuracy of integration and may also be restricted by the numerical properties of g x,y,y′. When evaluating g you should try to write the code so that unnecessary cancellation errors will be avoided.

8 Parallelism and Performance

D02QFF is not thread safe and should not be called from a multithreaded user program. Please see Section 3.12.1 in How to Use the NAG Library and its Documentation for more information on thread safety.
D02QFF is not threaded in any implementation.

9 Further Comments

If D02QFF fails with IFAIL=3 then the combination of ATOL and RTOL may be so small that a solution cannot be obtained, in which case the routine should be called again with larger values for RTOL and/or ATOL (see D02QWF). If the accuracy requested is really needed then you should consider whether there is a more fundamental difficulty. For example:
(a) | in the region of a singularity the solution components will usually be of a large magnitude. D02QFF could be used in one-step mode to monitor the size of the solution with the aim of trapping the solution before the singularity. In any case numerical integration cannot be continued through a singularity, and analytical treatment may be necessary;
(b) | for ‘stiff’ equations, where the solution contains rapidly decaying components, the routine will require a very small step size to preserve stability. This will usually be exhibited by excessive computing time and sometimes an error exit with IFAIL=3, but usually an error exit with IFAIL=2 or 5. The Adams' methods are not efficient in such cases and you should consider using a routine from the Sub-chapter D02M–N. A high proportion of failed steps (see argument NFAIL) may indicate stiffness but there may be other reasons for this phenomenon.
D02QFF can be used for producing results at short intervals (for example, for graph plotting); you should set CRIT=.TRUE. and TCRIT to the last output point required in a prior call to D02QWF and then set TOUT appropriately for each output point in turn in the call to D02QFF.

10 Example

This example solves the equation
y′′=-y,  y 0=0,  y′0=1
reposed as
y 1′=y 2 y 2′=-y 1
over the range 0,10.0 with initial conditions y 1=0.0 and y 2=1.0 using vector error control (VECTOL=.TRUE.) and computation of the solution at TOUT=10.0 with TCRIT=10.0 (CRIT=.TRUE.). Also, we use D02QFF to locate the positions where y 1=0.0 or where the first component has a turning-point, that is y 1′=0.0.

10.1 Program Text

Program Text (d02qffe.f90)

10.2 Program Data

Program Data (d02qffe.d)

10.3 Program Results

Program Results (d02qffe.r)

D02 Chapter Contents
D02 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


D02QGF : NAG Library, Mark 26

D02 Chapter Contents
D02 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

D02QGF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

D02QGF is a reverse communication routine for integrating a non-stiff system of first-order ordinary differential equations using a variable-order variable-step Adams' method. A root-finding facility is provided.

2 Specification

SUBROUTINE D02QGF ( NEQF, T, Y, TOUT, NEQG, ROOT, IREVCM, TRVCM, YRVCM, YPRVCM, GRVCM, KGRVCM, RWORK, LRWORK, IWORK, LIWORK, IFAIL)
INTEGER | NEQF, NEQG, IREVCM, YRVCM, YPRVCM, KGRVCM, LRWORK, IWORK(LIWORK), LIWORK, IFAIL
REAL (KIND=nag_wp) | T, Y(NEQF), TOUT, TRVCM, GRVCM, RWORK(LRWORK)
LOGICAL | ROOT

3 Description

Given the initial values x,y 1,y 2,…,yNEQF D02QGF integrates a non-stiff system of first-order differential equations of the type
yi′=fi x,y 1,y 2,…,yNEQF,  i=1,2,…,NEQF,
from x=T to x=TOUT using a variable-order variable-step Adams' method. You define the system by reverse communication, evaluating fi in terms of x and y 1,y 2,…,yNEQF, and y 1,y 2,…,yNEQF are supplied at x=T by D02QGF. The routine is capable of finding roots (values of x) of prescribed event functions of the form
gj x,y,y′ = 0 ,   j=1,2,…,NEQG.
Each gj is considered to be independent of the others so that roots are sought of each gj individually. The root reported by the routine will be the first root encountered by any gj. Two techniques for determining the presence of a root in an integration step are available: the sophisticated method described in Watts (1985) and a simplified method whereby sign changes in each gj are looked for at the ends of each integration step. You also define each gj by reverse communication. In one-step mode the routine returns an approximation to the solution at each integration point. In interval mode this value is returned at the end of the integration range. If a root is detected this approximation is given at the root. You select the mode of operation, the error control, the root-finding technique and various optional inputs by a prior call to the setup routine D02QWF.
For a description of the practical implementation of an Adams' formula see Shampine and Gordon (1975).

4 References

Shampine L F and Gordon M K (1975) Computer Solution of Ordinary Differential Equations – The Initial Value Problem W H Freeman & Co., San Francisco
Shampine L F and Watts H A (1979) DEPAC – design of a user oriented package of ODE solvers Report SAND79-2374 Sandia National Laboratory
Watts H A (1985) RDEAM – An Adams ODE code with root solving capability Report SAND85-1595 Sandia National Laboratory

5 Arguments

Note: this routine uses reverse communication. Its use involves an initial entry, intermediate exits and re-entries, and a final exit, as indicated by the argument IREVCM. Between intermediate exits and re-entries, all arguments other than GRVCM and RWORK must remain unchanged.
1:   NEQF – INTEGERInput
On initial entry: the number of first-order ordinary differential equations to be solved by D02QGF. It must contain the same value as the argument NEQF used in the prior call to D02QWF.
Constraint: NEQF≥1.
2:   T – REAL (KIND=nag_wp)Input/Output
On initial entry: that is after a call to D02QWF with STATEF='S', T must be set to the initial value of the independent variable x.
On final exit: the value of x at which y has been computed. This may be an intermediate output point, a root, TOUT or a point at which an error has occurred. If the integration is to be continued, possibly with a new value for TOUT, T must not be changed.
3:   Y NEQF – REAL (KIND=nag_wp) arrayInput/Output
On initial entry: the initial values of the solution y 1,y 2,…,yNEQF.
On final exit: the computed values of the solution at the exit value of T. If the integration is to be continued, possibly with a new value for TOUT, these values must not be changed.
4:   TOUT – REAL (KIND=nag_wp)Input
On initial entry: the next value of x at which a computed solution is required. For the initial T, the input value of TOUT is used to determine the direction of integration. Integration is permitted in either direction. If TOUT=T on exit, TOUT must be reset beyond T in the direction of integration, before any continuation call.
5:   NEQG – INTEGERInput
On initial entry: the number of event functions which you are defining for root-finding. If root-finding is not required the value for NEQG must be ≤0. Otherwise it must be the same value as the argument NEQG used in the prior call to D02QWF.
6:   ROOT – LOGICALOutput
On final exit: if root-finding was required (NEQG>0 on entry), then ROOT specifies whether or not the output value of the argument T is a root of one of the event functions. If ROOT=.FALSE., then no root was detected, whereas ROOT=.TRUE. indicates a root and you should make a call to D02QYF for further information.
If root-finding was not required (NEQG=0 on entry), then ROOT=.FALSE..
7:   IREVCM – INTEGERInput/Output
On initial entry: must have the value 0.
On intermediate exit: specifies what action you must take before re-entering D02QGF with IREVCM unchanged.
IREVCM=1, 2, 3, 4, 5, 6 or 7
Indicates that you must supply y′=f x,y, where x is given by TRVCM and yi is returned in Y i, for i=1,2,…,NEQF when YRVCM=0 and RWORK YRVCM+i-1, for i=1,2,…,NEQF when YRVCM≠0. yi′ should be placed in location RWORK YPRVCM+i-1, for i=1,2,…,NEQF.
IREVCM=8
Indicates that the current step was not successful due to error test failure. The only information supplied to you on this return is the current value of the independent variable T, as given by TRVCM. No values must be changed before re-entering D02QGF. This facility enables you to determine the number of unsuccessful steps.
IREVCM=9, 10, 11 or 12
Indicates that you must supply gk x,y,y′, where k is given by KGRVCM, x is given by TRVCM, yi is given by Y i and yi′ is given by RWORK YPRVCM-1+i. The result gk should be placed in the variable GRVCM.
On final exit: has the value 0, which indicates that an output point or root has been reached or an error has occurred (see IFAIL).
8:   TRVCM – REAL (KIND=nag_wp)Output
On intermediate exit: the current value of the independent variable.
9:   YRVCM – INTEGEROutput
On intermediate exit: with IREVCM=1, 2, 3, 4, 5, 6, 7, 9, 10, 11 or 12, YRVCM specifies the locations of the dependent variables y for use in evaluating the differential system or the event functions.
YRVCM=0
yi is given by Y i, for i=1,2,…,NEQF.
YRVCM≠0
yi is given by RWORK YRVCM+i-1, for i=1,2,…,NEQF.
10:   YPRVCM – INTEGEROutput
On intermediate exit: with IREVCM=1, 2, 3, 4, 5, 6 or 7, YPRVCM specifies the positions in RWORK at which you should place the derivatives y′. yi′ should be placed in location RWORK YPRVCM+i-1, for i=1,2,…,NEQF.
With IREVCM=9, 10, 11 or 12, YPRVCM specifies the locations of the derivatives y′ for use in evaluating the event functions. yi′ is given by RWORK YPRVCM+i-1, for i=1,2,…,NEQF.
11:   GRVCM – REAL (KIND=nag_wp)Input
On initial entry: need not be set.
On intermediate re-entry: with IREVCM=9, 10, 11 or 12, GRVCM must contain the value of gk x,y,y′, where k is given by KGRVCM.
12:   KGRVCM – INTEGERInput/Output
On intermediate re-entry: with IREVCM=9, 10, 11 or 12, KGRVCM must remain unchanged from a previous call to D02QGF.
On intermediate exit: with IREVCM=9, 10, 11 or 12, KGRVCM specifies which event function gk x,y,y′ you must evaluate.
13:   RWORK LRWORK – REAL (KIND=nag_wp) arrayCommunication Array
This must be the same argument RWORK as supplied to D02QWF. It is used to pass information from D02QWF to D02QGF, and from D02QGF to D02QXF, D02QYF and D02QZF. Therefore the contents of this array must not be changed before the call to D02QGF or calling any of the routines D02QXF, D02QYF and D02QZF.
14:   LRWORK – INTEGERInput
On initial entry: the dimension of the array RWORK as declared in the (sub)program from which D02QGF is called.
This must be the same argument LRWORK as supplied to D02QWF.
15:   IWORK LIWORK – INTEGER arrayCommunication Array
This must be the same argument IWORK as supplied to D02QWF. It is used to pass information from D02QWF to D02QGF, and from D02QGF to D02QXF, D02QYF and D02QZF. Therefore the contents of this array must not be changed before the call to D02QGF or calling any of the routines D02QXF, D02QYF and D02QZF.
16:   LIWORK – INTEGERInput
On initial entry: the dimension of the array IWORK as declared in the (sub)program from which D02QGF is called.
This must be the same argument LIWORK as supplied to D02QWF.
17:   IFAIL – INTEGERInput/Output
On initial entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, because for this routine the values of the output arguments may be useful even if IFAIL≠0 on exit, the recommended value is -1. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On final exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, the integrator detected an illegal input, or D02QWF has not been called before the call to the integrator.
This error may be caused by overwriting elements of RWORK and IWORK.
IFAIL=2
The maximum number of steps has been attempted (at a cost of about 2 derivative evaluations per step). (See argument MAXSTP in D02QWF.) If integration is to be continued then you need only reset IFAIL and call the routine again and a further MAXSTP steps will be attempted.
IFAIL=3
The step size needed to satisfy the error requirements is too small for the machine precision being used. (See argument TOLFAC in D02QXF.)
IFAIL=4
Some error weight wi became zero during the integration (see arguments VECTOL, RTOL and ATOL in D02QWF.) Pure relative error control (ATOL=0.0) was requested on a variable (the ith) which has now become zero. (See argument BADCMP in D02QXF.) The integration was successful as far as T.
IFAIL=5
The problem appears to be stiff (see the D02 Chapter Introduction for a discussion of the term ‘stiff’). Although it is inefficient to use this integrator to solve stiff problems, integration may be continued by resetting IFAIL and calling the routine again.
IFAIL=6
A change in sign of an event function has been detected but the root-finding process appears to have converged to a singular point T rather than a root. Integration may be continued by resetting IFAIL and calling the routine again.
IFAIL=7
The code has detected two successive error exits at the current value of T and cannot proceed. Check all input variables.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

The accuracy of integration is determined by the arguments VECTOL, RTOL and ATOL in a prior call to D02QWF. Note that only the local error at each step is controlled by these arguments. The error estimates obtained are not strict bounds but are usually reliable over one step. Over a number of steps the overall error may accumulate in various ways, depending on the properties of the differential equation system. The code is designed so that a reduction in the tolerances should lead to an approximately proportional reduction in the error. You are strongly recommended to call D02QGF with more than one set of tolerances and to compare the results obtained to estimate their accuracy.
The accuracy obtained depends on the type of error test used. If the solution oscillates around zero a relative error test should be avoided, whereas if the solution is exponentially increasing an absolute error test should not be used. If different accuracies are required for different components of the solution then a component-wise error test should be used. For a description of the error test see the specifications of the arguments VECTOL, RTOL and ATOL in the routine document for D02QWF.
The accuracy of any roots located will depend on the accuracy of integration and may also be restricted by the numerical properties of g x,y,y′. When evaluating g you should try to write the code so that unnecessary cancellation errors will be avoided.

8 Parallelism and Performance

D02QGF is not thread safe and should not be called from a multithreaded user program. Please see Section 3.12.1 in How to Use the NAG Library and its Documentation for more information on thread safety.
D02QGF is not threaded in any implementation.

9 Further Comments

If D02QGF fails with IFAIL=3 then the combination of ATOL and RTOL may be so small that a solution cannot be obtained, in which case the routine should be called again with larger values for RTOL and/or ATOL (see D02QWF). If the accuracy requested is really needed then you should consider whether there is a more fundamental difficulty. For example:
(a) | in the region of a singularity the solution components will usually be of a large magnitude. D02QGF could be used in one-step mode to monitor the size of the solution with the aim of trapping the solution before the singularity. In any case numerical integration cannot be continued through a singularity, and analytical treatment may be necessary;
(b) | for ‘stiff’ equations, where the solution contains rapidly decaying components, the routine will require a very small step size to preserve stability. This will usually be exhibited by excessive computing time and sometimes an error exit with IFAIL=3, but usually an error exit with IFAIL=2 or 5. The Adams' methods are not efficient in such cases and you should consider using a routine from the Sub-chapter D02M–N. A high proportion of failed steps (see argument NFAIL in D02QXF) may indicate stiffness but there may be other reasons for this phenomenon.
D02QGF can be used for producing results at short intervals (for example, for graph plotting); you should set CRIT=.TRUE. and TCRIT to the last output point required in a prior call to D02QWF and then set TOUT appropriately for each output point in turn in the call to D02QGF.

10 Example

This example solves the following system (for a projectile)
y′=tan⁡ϕ v′= -0.032 tan⁡ϕ v - 0.02 v cos⁡ϕ ϕ′= -0.032 v 2
over an interval 0.0,10.0 starting with values y=0.5, v=0.5 and ϕ=π/5 using scalar error control (VECTOL=.FALSE.) until the first point where y=0.0 is encountered.
Also, D02QGF is used to produce output at intervals of 2.0.

10.1 Program Text

Program Text (d02qgfe.f90)

10.2 Program Data

Program Data (d02qgfe.d)

10.3 Program Results

Program Results (d02qgfe.r)

GnuplotProduced by GNUPLOT 4.6 patchlevel 3 −1 −0.5 0 0.5 1 1.5 2 0 1 2 3 4 5 6 7 8 Solution x Example Program ODE Solution using Adams Method with Root-finding height velocity angle gnuplot_plot_1 gnuplot_plot_2 gnuplot_plot_3
D02 Chapter Contents
D02 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


D02QWF : NAG Library, Mark 26

D02 Chapter Contents
D02 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

D02QWF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
10 Example

1 Purpose

D02QWF is a setup routine which must be called prior to the first call of either of the integrators D02QFF and D02QGF and may be called prior to any continuation call to these routines.

2 Specification

SUBROUTINE D02QWF ( STATEF, NEQF, VECTOL, ATOL, LATOL, RTOL, LRTOL, ONESTP, CRIT, TCRIT, HMAX, MAXSTP, NEQG, ALTERG, SOPHST, RWORK, LRWORK, IWORK, LIWORK, IFAIL)
INTEGER | NEQF, LATOL, LRTOL, MAXSTP, NEQG, LRWORK, IWORK(LIWORK), LIWORK, IFAIL
REAL (KIND=nag_wp) | ATOL(LATOL), RTOL(LRTOL), TCRIT, HMAX, RWORK(LRWORK)
LOGICAL | VECTOL, ONESTP, CRIT, ALTERG, SOPHST
CHARACTER(1) | STATEF

3 Description

D02QWF permits initialization of the integration method and setting of optional inputs prior to any call of D02QFF or D02QGF. It must be called before the first call of either of the routines D02QFF or D02QGF and it may be called before any continuation call of either of the routines D02QFF or D02QGF.

4 References

None.

5 Arguments

1:   STATEF – CHARACTER(1)Input/Output
On entry: specifies whether the integration routine (D02QFF or D02QGF) is to start a new system of ordinary differential equations, restart a system or continue with a system.
STATEF='S'
Start integration with a new differential system.
STATEF='R'
Restart integration with the current differential system.
STATEF='C'
Continue integration with the current differential system.
Constraint: STATEF='S', 'R' or 'C'.
On exit: is set to 'C', except that if an error is detected, STATEF is unchanged.
2:   NEQF – INTEGERInput
On entry: the number of ordinary differential equations to be solved by the integration routine. NEQF must remain unchanged on subsequent calls to D02QWF with STATEF='C' or 'R'.
Constraint: NEQF≥1.
3:   VECTOL – LOGICALInput
On entry: specifies whether vector or scalar error control is to be employed for the local error test in the integration.
If VECTOL=.TRUE., then vector error control will be used and you must specify values of RTOL i and ATOL i, for i=1,2,…,NEQF.
Otherwise scalar error control will be used and you must specify values of just RTOL 1 and ATOL 1.
The error test to be satisfied is of the form
∑i=1 NEQF eiwi 2≤1.0.
where wi is defined as follows:
VECTOL | wi
.TRUE. | RTOL i×yi+ATOL i
.FALSE. | RTOL 1×yi+ATOL 1
and ei is an estimate of the local error in yi, computed internally. VECTOL must remain unchanged on subsequent calls to D02QWF with STATEF='C' or 'R'.
4:   ATOL LATOL – REAL (KIND=nag_wp) arrayInput
On entry: the absolute local error tolerance (see VECTOL).
Constraint: ATOL i≥0.0.
5:   LATOL – INTEGERInput
On entry: the dimension of the array ATOL as declared in the (sub)program from which D02QWF is called.
Constraints:
  • if VECTOL=.TRUE., LATOL≥NEQF;
  • if VECTOL=.FALSE., LATOL≥1.
6:   RTOL LRTOL – REAL (KIND=nag_wp) arrayInput
On entry: the relative local error tolerance (see VECTOL).
Constraints:
  • RTOL i≥0.0;
  • if ATOL i=0.0, RTOL i≥4.0×machine precision.
7:   LRTOL – INTEGERInput
On entry: the dimension of the array RTOL as declared in the (sub)program from which D02QWF is called.
Constraints:
  • if VECTOL=.TRUE., LRTOL≥NEQF;
  • if VECTOL=.FALSE., LRTOL≥1.
8:   ONESTP – LOGICALInput
On entry: the mode of operation of the integration routine. If ONESTP=.TRUE., the integration routine will operate in one-step mode, that is it will return after each successful step. Otherwise the integration routine will operate in interval mode, that is it will return at the end of the integration interval.
9:   CRIT – LOGICALInput
On entry: specifies whether or not there is a value for the independent variable beyond which integration is not to be attempted. Setting CRIT=.TRUE. indicates that there is such a point, whereas CRIT=.FALSE. indicates that there is no such restriction.
10:   TCRIT – REAL (KIND=nag_wp)Input
On entry: with CRIT=.TRUE., TCRIT must be set to a value of the independent variable beyond which integration is not to be attempted. Otherwise TCRIT is not referenced.
11:   HMAX – REAL (KIND=nag_wp)Input
On entry: if HMAX≠0.0, a bound on the absolute step size during the integration is taken to be HMAX.
If HMAX=0.0, no bound is assumed on the step size during the integration.
A bound may be required if there are features of the solution on very short ranges of integration which may be missed. You should try HMAX=0.0 first.
Note: this argument only affects the step size if the option CRIT=.TRUE. is being used.
12:   MAXSTP – INTEGERInput
On entry: a bound on the number of attempted steps in any one call to the integration routine. If MAXSTP≤0 on entry, a value of 1000 is used.
13:   NEQG – INTEGERInput
On entry: specifies whether or not root-finding is required in D02QFF or D02QGF.
NEQG≤0
No root-finding is attempted.
NEQG>0
Root-finding is required and NEQG event functions will be specified for the integration routine.
14:   ALTERG – LOGICALInput/Output
On entry: specifies whether or not the event functions have been redefined. ALTERG need not be set if STATEF='S'. On subsequent calls to D02QWF, if NEQG has been set positive, then ALTERG=.FALSE. specifies that the event functions remain unchanged, whereas ALTERG=.TRUE. specifies that the event functions have changed. Because of the expense in reinitializing the root searching procedure, ALTERG should be set to .TRUE. only if the event functions really have been altered. ALTERG need not be set if the root-finding option is not used.
On exit: is set to .FALSE..
15:   SOPHST – LOGICALInput
On entry: the type of search technique to be used in the root-finding. If SOPHST=.TRUE. then a sophisticated and reliable but expensive technique will be used, whereas for SOPHST=.FALSE. a simple but less reliable technique will be used. If NEQG≤0, SOPHST is not referenced.
16:   RWORK LRWORK – REAL (KIND=nag_wp) arrayCommunication Array
This must be the same argument RWORK supplied to the integration routine. It is used to pass information to the integration routine and therefore the contents of this array must not be changed before calling the integration routine.
17:   LRWORK – INTEGERInput
On entry: the dimension of the array RWORK as declared in the (sub)program from which D02QWF is called.
Constraint: LRWORK≥21×1+NEQF+2×J+K×NEQG+2, where
J= NEQF if ​VECTOL=.TRUE. 1 if ​VECTOL=.FALSE.
and
K= 14 if ​ SOPHST=.TRUE. 5 if ​ SOPHST=.FALSE.
.
18:   IWORK LIWORK – INTEGER arrayCommunication Array
This must be the same argument IWORK supplied to the integration routine. It is used to pass information to the integration routine and therefore the contents of this array must not be changed before calling the integration routine.
19:   LIWORK – INTEGERInput
On entry: the dimension of the array IWORK as declared in the (sub)program from which D02QWF is called.
Constraints:
  • if SOPHST=.TRUE., LIWORK≥21+4×NEQG;
  • if SOPHST=.FALSE., LIWORK≥21+NEQG.
20:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
Illegal input detected.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

Not applicable.

8 Parallelism and Performance

D02QWF is not thread safe and should not be called from a multithreaded user program. Please see Section 3.12.1 in How to Use the NAG Library and its Documentation for more information on thread safety.
D02QWF is not threaded in any implementation.

9 Further Comments

Prior to a continuation call of the integration routine, you may reset any of the optional parameters by calling D02QWF with STATEF='C'. You may reset:
HMAX | to alter the maximum step size selection;
RTOL, ATOL | to change the error requirements;
MAXSTP | to increase or decrease the number of attempted steps before an error exit is returned;
ONESTP | to change the operation mode of the integration routine;
CRIT, TCRIT | to alter the point beyond which integration must not be attempted; and
NEQG, ALTERG, SOPHST | to alter the number and type of event functions, and also the search method.
If the behaviour of the system of differential equations has altered and you wish to restart the integration method from the value of T output from the integration routine (see D02QFF and D02QGF), then STATEF should be set to STATEF='R' and any of the optional parameters may be reset also. If you want to redefine the system of differential equations or start a new integration problem, then STATEF should be set to STATEF='S'. Resetting STATEF='R' or 'S' on normal continuation calls causes a restart in the integration process, which is very inefficient when not needed.

10 Example

See Section 10 in D02QFF and D02QGF.
D02 Chapter Contents
D02 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


D02QXF : NAG Library, Mark 26

D02 Chapter Contents
D02 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

D02QXF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
10 Example

1 Purpose

D02QXF is a diagnostic routine which may be called after a call to either of the integration routines D02QFF and D02QGF.

2 Specification

SUBROUTINE D02QXF ( NEQF, YP, TCURR, HLAST, HNEXT, ODLAST, ODNEXT, NSUCC, NFAIL, TOLFAC, BADCMP, RWORK, LRWORK, IWORK, LIWORK, IFAIL)
INTEGER | NEQF, ODLAST, ODNEXT, NSUCC, NFAIL, BADCMP, LRWORK, IWORK(LIWORK), LIWORK, IFAIL
REAL (KIND=nag_wp) | YP(NEQF), TCURR, HLAST, HNEXT, TOLFAC, RWORK(LRWORK)

3 Description

D02QXF permits you to extract information about the performance of D02QFF or D02QGF. It may only be called after a call to D02QFF or D02QGF.

4 References

None.

5 Arguments

1:   NEQF – INTEGERInput
On entry: the number of first-order ordinary differential equations solved by the integration routine. It must be the same argument NEQF supplied to the setup routine D02QWF and the integration routines D02QFF or D02QGF.
2:   YP NEQF – REAL (KIND=nag_wp) arrayOutput
On exit: the approximate derivative of the solution component yi, as supplied in yi on output from the integration routine at the output value of T. These values are obtained by the evaluation of y′=f x,y except when the output value of the argument T in the call to the integration routine is TOUT and TCURR≠TOUT, in which case they are obtained by interpolation.
3:   TCURR – REAL (KIND=nag_wp)Output
On exit: the value of the independent variable which the integrator has actually reached. TCURR will always be at least as far as the output value of the argument T (from the integration routine) in the direction of integration, but may be further.
4:   HLAST – REAL (KIND=nag_wp)Output
On exit: the last successful step size used by the integrator.
5:   HNEXT – REAL (KIND=nag_wp)Output
On exit: the next step size which the integration routine would attempt.
6:   ODLAST – INTEGEROutput
On exit: the order of the method last used (successfully) by the integration routine.
7:   ODNEXT – INTEGEROutput
On exit: the order of the method which the integration routine would attempt on the next step.
8:   NSUCC – INTEGEROutput
On exit: the number of steps attempted by the integration routine that have been successful since the start of the current problem.
9:   NFAIL – INTEGEROutput
On exit: the number of steps attempted by the integration routine that have failed since the start of the current problem.
10:   TOLFAC – REAL (KIND=nag_wp)Output
On exit: a tolerance scale factor, TOLFAC≥1.0, returned when the integration routine exits with IFAIL=3. If RTOL and ATOL are uniformly scaled up by a factor of TOLFAC and D02QWF is called, the next call to the integration routine is deemed likely to succeed.
11:   BADCMP – INTEGEROutput
On exit: if the integration routine returned with IFAIL=4, then BADCMP specifies the index of the component which forced the error exit. Otherwise BADCMP is 0.
12:   RWORK LRWORK – REAL (KIND=nag_wp) arrayCommunication Array
On entry: this must be the same argument RWORK as supplied to D02QFF or D02QGF. It is used to pass information from the integration routine to D02QXF and therefore the contents of this array must not be changed before calling D02QXF.
13:   LRWORK – INTEGERInput
On entry: the dimension of the array RWORK as declared in the (sub)program from which D02QXF is called.
This must be the same argument LRWORK as supplied to D02QWF.
14:   IWORK LIWORK – INTEGER arrayCommunication Array
On entry: this must be the same argument IWORK as supplied to D02QFF or D02QGF. It is used to pass information from the integration routine to D02QXF and therefore the contents of this array must not be changed before calling D02QXF.
15:   LIWORK – INTEGERInput
On entry: the dimension of the array IWORK as declared in the (sub)program from which D02QXF is called.
This must be the same argument LIWORK as supplied to D02QWF.
16:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
An integration routine (D02QFF or D02QGF) has not been called or one or more of the arguments LRWORK, LIWORK and NEQF does not match the corresponding argument supplied to D02QWF.
This error exit may be caused by overwriting elements of RWORK.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

Not applicable.

8 Parallelism and Performance

D02QXF is not thread safe and should not be called from a multithreaded user program. Please see Section 3.12.1 in How to Use the NAG Library and its Documentation for more information on thread safety.
D02QXF is not threaded in any implementation.

9 Further Comments

You should call D02QYF for information about any roots detected by D02QFF or D02QGF.

10 Example

See Section 10 in D02QFF.
D02 Chapter Contents
D02 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


D02QYF : NAG Library, Mark 26

D02 Chapter Contents
D02 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

D02QYF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
10 Example

1 Purpose

D02QYF is a diagnostic routine which may be called after a call to the integrator routines D02QFF or D02QGF.

2 Specification

SUBROUTINE D02QYF ( NEQG, INDEX, ITYPE, EVENTS, RESIDS, RWORK, LRWORK, IWORK, LIWORK, IFAIL)
INTEGER | NEQG, INDEX, ITYPE, EVENTS(NEQG), LRWORK, IWORK(LIWORK), LIWORK, IFAIL
REAL (KIND=nag_wp) | RESIDS(NEQG), RWORK(LRWORK)

3 Description

D02QYF should be called only after a call to D02QFF or D02QGF results in the output value ROOT=.TRUE., indicating that a root has been detected. D02QYF permits you to examine information about the root detected, such as the indices of the event equations for which there is a root, the type of root (odd or even) and the residuals of the event equations.

4 References

None.

5 Arguments

1:   NEQG – INTEGERInput
On entry: the number of event functions defined for the integration routine. It must be the same argument NEQG supplied to the setup routine D02QWF and to the integration routine (D02QFF or D02QGF).
2:   INDEX – INTEGEROutput
On exit: the index k of the event equation gk x,y,y′=0 for which the root has been detected.
3:   ITYPE – INTEGEROutput
On exit: information about the root detected for the event equation defined by INDEX. The possible values of ITYPE with their interpretations are as follows:
ITYPE=1
A simple root, or lack of distinguishing information available.
ITYPE=2
A root of even multiplicity is believed to have been detected, that is no change in sign of the event function was found.
ITYPE=3
A high-order root of odd multiplicity.
ITYPE=4
A possible root, but due to high multiplicity or a clustering of roots accurate evaluation of the event function was prohibited by round-off error and/or cancellation.
In general, the accuracy of the root is less reliable for values of ITYPE>1.
4:   EVENTS NEQG – INTEGER arrayOutput
On exit: information about the kth event function on a very small interval containing the root, T (see D02QFF and D02QGF), as output from the integration routine. All roots lying in this interval are considered indistinguishable numerically and therefore should be regarded as defining a root at T. The possible values of EVENTS k with their interpretations are as follows:
EVENTS k=0
The kth event function did not have a root.
EVENTS k=-1
The kth event function changed sign from positive to negative about a root, in the direction of integration.
EVENTS k=1
The kth event function changed sign from negative to positive about a root, in the direction of integration.
EVENTS k=2
A root was identified, but no change in sign was observed.
5:   RESIDS NEQG – REAL (KIND=nag_wp) arrayOutput
On exit: the value of the kth event function computed at the root, T (see D02QFF and D02QGF).
6:   RWORK LRWORK – REAL (KIND=nag_wp) arrayCommunication Array
On entry: this must be the same argument RWORK as supplied to D02QFF or D02QGF. It is used to pass information from the integration routine to D02QYF and therefore the contents of this array must not be changed before calling D02QYF.
7:   LRWORK – INTEGERInput
On entry: the dimension of the array RWORK as declared in the (sub)program from which D02QYF is called.
This must be the same argument LRWORK as supplied to D02QWF.
8:   IWORK LIWORK – INTEGER arrayCommunication Array
On entry: this must be the same argument IWORK as supplied to D02QFF or D02QGF. It is used to pass information from the integration routine to D02QYF and therefore the contents of this array must not be changed before calling D02QYF.
9:   LIWORK – INTEGERInput
On entry: the dimension of the array IWORK as declared in the (sub)program from which D02QYF is called.
This must be the same argument LIWORK as supplied to D02QWF.
10:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
An integration routine (D02QFF or D02QGF) has not been called, no root was detected or one or more of the arguments LRWORK, LIWORK and NEQG does not match the corresponding values supplied to D02QWF. Values for the arguments INDEX, ITYPE, EVENTS and RESIDS will not have been set.
This error exit may be caused by overwriting elements of IWORK.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

Not applicable.

8 Parallelism and Performance

D02QYF is not thread safe and should not be called from a multithreaded user program. Please see Section 3.12.1 in How to Use the NAG Library and its Documentation for more information on thread safety.
D02QYF is not threaded in any implementation.

9 Further Comments

None.

10 Example

See Section 10 in D02QFF.
D02 Chapter Contents
D02 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


D02QZF : NAG Library, Mark 26

D02 Chapter Contents
D02 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

D02QZF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

D02QZF interpolates components of the solution of a non-stiff system of first-order differential equations from information provided by the integrator routines D02QFF or D02QGF.

2 Specification

SUBROUTINE D02QZF ( NEQF, TWANT, NWANT, YWANT, YPWANT, RWORK, LRWORK, IWORK, LIWORK, IFAIL)
INTEGER | NEQF, NWANT, LRWORK, IWORK(LIWORK), LIWORK, IFAIL
REAL (KIND=nag_wp) | TWANT, YWANT(NWANT), YPWANT(NWANT), RWORK(LRWORK)

3 Description

D02QZF evaluates the first NWANT components of the solution of a non-stiff system of first-order ordinary differential equations at any point using the method of Watts and Shampine (1986) and information generated by D02QFF or D02QGF. D02QZF should not normally be used to extrapolate outside the current range of the values produced by the integration routine.

4 References

Watts H A and Shampine L F (1986) Smoother interpolants for Adams codes SIAM J. Sci. Statist. Comput. 7 334–345

5 Arguments

1:   NEQF – INTEGERInput
On entry: the number of first-order ordinary differential equations being solved by the integration routine. It must contain the same value as the argument NEQF in a prior call to the setup routine D02QWF.
2:   TWANT – REAL (KIND=nag_wp)Input
On entry: the point at which components of the solution and derivative are to be evaluated. TWANT should not normally be an extrapolation point, that is TWANT should satisfy
  • told≤TWANT≤T,
or if integration is proceeding in the negative direction
  • told≥TWANT≥T,
where told is the previous integration point and is, to within rounding, TCURR – HLAST (see D02QXF). Extrapolation is permitted but not recommended and IFAIL=2 is returned whenever extrapolation is attempted.
3:   NWANT – INTEGERInput
On entry: the number of components of the solution and derivative whose values at TWANT are required. The first NWANT components are evaluated.
Constraint: 1≤NWANT≤NEQF.
4:   YWANT NWANT – REAL (KIND=nag_wp) arrayOutput
On exit: the calculated value of the ith component of the solution at TWANT, for i=1,2,…,NWANT.
5:   YPWANT NWANT – REAL (KIND=nag_wp) arrayOutput
On exit: the calculated value of the ith component of the derivative at TWANT, for i=1,2,…,NWANT.
6:   RWORK LRWORK – REAL (KIND=nag_wp) arrayCommunication Array
On entry: this must be the same argument RWORK as supplied to D02QWF and to D02QFF or D02QGF. It is used to pass information from these routines to D02QZF. Therefore its contents must not be changed before a call to D02QZF.
7:   LRWORK – INTEGERInput
On entry: the dimension of the array RWORK as declared in the (sub)program from which D02QZF is called.
This must be the same argument LRWORK as supplied to D02QWF.
8:   IWORK LIWORK – INTEGER arrayCommunication Array
On entry: this must be the same argument IWORK as supplied to D02QWF and to D02QFF or D02QGF. It is used to pass information from these routines to D02QZF. Therefore its contents must not be changed before a call to D02QZF.
9:   LIWORK – INTEGERInput
On entry: the dimension of the array IWORK as declared in the (sub)program from which D02QZF is called.
This must be the same argument LIWORK as supplied to D02QWF.
10:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
An integration routine (D02QFF or D02QGF) has not been called, no integration steps have been taken since the last call to D02QWF with STATEF='S', one or more of the arguments LRWORK, LIWORK and NEQF does not match the same argument supplied to D02QWF, or NWANT does not satisfy 1≤NWANT≤NEQF.
IFAIL=2
D02QZF has been called for extrapolation. The values of the solution and its derivative at TWANT have been calculated and placed in YWANT and YPWANT before returning with this warning (see Section 7).
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.
These error exits may be caused by overwriting elements of RWORK and IWORK.

7 Accuracy

The error in interpolation is of a similar order to the error arising from the integration. The same order of accuracy can be expected when extrapolating using D02QZF. However, the actual error in extrapolation will, in general, be much larger than for interpolation.

8 Parallelism and Performance

D02QZF is not thread safe and should not be called from a multithreaded user program. Please see Section 3.12.1 in How to Use the NAG Library and its Documentation for more information on thread safety.
D02QZF is not threaded in any implementation.

9 Further Comments

When interpolation for only a few components is required then it is more efficient to order the components of interest so that they are numbered first.

10 Example

This example solves the equation
y′′=-y,  y 0=0,  y′0=1
reposed as
y 1′=y 2 y 2′=-y 1
over the range 0,π/2 with initial conditions y 1=0 and y 2=1 using vector error control (VECTOL=.TRUE.) and D02QFF in one-step mode (ONESTP=.TRUE.). D02QZF is used to provide solution values at intervals of π/16.

10.1 Program Text

Program Text (d02qzfe.f90)

10.2 Program Data

Program Data (d02qzfe.d)

10.3 Program Results

Program Results (d02qzfe.r)

GnuplotProduced by GNUPLOT 4.6 patchlevel 3 0 0.2 0.4 0.6 0.8 1 0 0.2 0.4 0.6 0.8 1 1.2 1.4 1.6 1e−06 1e−05 0.0001 0.001 0.01 0.1 1 Solution Error x Example Program A Simple Problem with Sine Solution y y' error in y gnuplot_plot_1 gnuplot_plot_2 gnuplot_plot_3
D02 Chapter Contents
D02 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


D02RAF : NAG Library, Mark 26

D02 Chapter Contents
D02 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

D02RAF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

D02RAF solves a two-point boundary value problem with general boundary conditions for a system of ordinary differential equations, using a deferred correction technique and Newton iteration.

2 Specification

SUBROUTINE D02RAF ( N, MNP, NP, NUMBEG, NUMMIX, TOL, INIT, X, Y, LDY, ABT, FCN, G, IJAC, JACOBF, JACOBG, DELEPS, JACEPS, JACGEP, WORK, LWORK, IWORK, LIWORK, IFAIL)
INTEGER | N, MNP, NP, NUMBEG, NUMMIX, INIT, LDY, IJAC, LWORK, IWORK(LIWORK), LIWORK, IFAIL
REAL (KIND=nag_wp) | TOL, X(MNP), Y(LDY,MNP), ABT(N), DELEPS, WORK(LWORK)
EXTERNAL | FCN, G, JACOBF, JACOBG, JACEPS, JACGEP

3 Description

D02RAF solves a two-point boundary value problem for a system of n ordinary differential equations in the interval a,b with b>a. The system is written in the form
yi′ = f i x, y 1 , y 2 ,…, y n ,   i=1,2,…,n (1)
and the derivatives fi are evaluated by FCN. With the differential equations (1) must be given a system of n (nonlinear) boundary conditions
gi y a,y b = 0 ,   i=1,2,…,n ,
where
y x = y 1 x , y 2 x ,…, y n x T . (2)
The functions gi are evaluated by G. The solution is computed using a finite difference technique with deferred correction allied to a Newton iteration to solve the finite difference equations. The technique used is described fully in Pereyra (1979).
You must supply an absolute error tolerance and may also supply an initial mesh for the finite difference equations and an initial approximate solution (alternatively a default mesh and approximation are used). The approximate solution is corrected using Newton iteration and deferred correction. Then, additional points are added to the mesh and the solution is recomputed with the aim of making the error everywhere less than your tolerance and of approximately equidistributing the error on the final mesh. The solution is returned on this final mesh.
If the solution is required at a few specific points then these should be included in the initial mesh. If, on the other hand, the solution is required at several specific points then you should use the interpolation routines provided in Chapter E01 if these points do not themselves form a convenient mesh.
The Newton iteration requires Jacobian matrices
∂fi ∂yj , ∂gi ∂yj a  and  ∂gi ∂yj b .
These may be supplied through JACOBF for ∂fi ∂yj and JACOBG for the others. Alternatively the Jacobians may be calculated by numerical differentiation using the algorithm described in Curtis et al. (1974).
For problems of the type (1) and (2) for which it is difficult to determine an initial approximation from which the Newton iteration will converge, a continuation facility is provided. You must set up a family of problems
y′ = f x,y,ε ,   g y a,y b,ε = 0 , (3)
where f = f 1 , f 2 ,…, f n T etc., and where ε is a continuation parameter. The choice ε=0 must give a problem (3) which is easy to solve and ε=1 must define the problem whose solution is actually required. The routine solves a sequence of problems with ε values
0 = ε 1 < ε 2 < ⋯ < εp = 1 . (4)
The number p and the values εi are chosen by the routine so that each problem can be solved using the solution of its predecessor as a starting approximation. Jacobians ∂f ∂ε and ∂g ∂ε are required and they may be supplied by you via JACEPS and JACGEP respectively or may be computed by numerical differentiation.

4 References

Curtis A R, Powell M J D and Reid J K (1974) On the estimation of sparse Jacobian matrices J. Inst. Maths. Applics. 13 117–119
Pereyra V (1979) PASVA3: An adaptive finite-difference Fortran program for first order nonlinear, ordinary boundary problems Codes for Boundary Value Problems in Ordinary Differential Equations. Lecture Notes in Computer Science (eds B Childs, M Scott, J W Daniel, E Denman and P Nelson) 76 Springer–Verlag

5 Arguments

1:   N – INTEGERInput
On entry: n, the number of differential equations.
Constraint: N>0.
2:   MNP – INTEGERInput
On entry: MNP must be set to the maximum permitted number of points in the finite difference mesh. If LWORK or LIWORK are too small then internally MNP will be replaced by the maximum permitted by these values. (A warning message will be output if on entry IFAIL is set to obtain monitoring information.)
Constraint: MNP≥32.
3:   NP – INTEGERInput/Output
On entry: must be set to the number of points to be used in the initial mesh.
Constraint: 4≤NP≤MNP.
On exit: the number of points in the final mesh.
4:   NUMBEG – INTEGERInput
On entry: the number of left-hand boundary conditions (that is the number involving y a only).
Constraint: 0≤NUMBEG<N.
5:   NUMMIX – INTEGERInput
On entry: the number of coupled boundary conditions (that is the number involving both y a and y b).
Constraint: 0≤NUMMIX≤N-NUMBEG.
6:   TOL – REAL (KIND=nag_wp)Input
On entry: a positive absolute error tolerance. If
a=x 1<x 2<⋯<xNP=b
is the final mesh, zj xi is the jth component of the approximate solution at xi, and yj x is the jth component of the true solution of (1) and (2), then, except in extreme circumstances, it is expected that
zj xi-yj xi≤TOL,  i=1,2,…,NP​ and ​j=1,2,…,n. (5)
Constraint: TOL>0.0.
7:   INIT – INTEGERInput
On entry: indicates whether you wish to supply an initial mesh and approximate solution (INIT=1) or whether default values are to be used, (INIT=0).
Constraint: INIT=0 or 1.
8:   X MNP – REAL (KIND=nag_wp) arrayInput/Output
On entry: you must set X 1=a and X NP=b. If INIT=0 on entry a default equispaced mesh will be used, otherwise you must specify a mesh by setting X i=xi, for i=2,3,…,NP-1.
Constraints:
  • if INIT=0, X 1<X NP;
  • if INIT=1, X 1<X 2<⋯<X NP.
On exit: X 1,X 2,…,X NP define the final mesh (with the returned value of NP) and X 1=a and X NP=b.
9:   Y LDYMNP – REAL (KIND=nag_wp) arrayInput/Output
On entry: if INIT=0, then Y need not be set.
If INIT=1, then the array Y must contain an initial approximation to the solution such that Y ji contains an approximation to
yj xi,  i=1,2,…,NP​ and ​j=1,2,…,n.
On exit: the approximate solution zj xi satisfying (5) on the final mesh, that is
Y ji=zj xi,  i=1,2,…,NP​ and ​j=1,2,…,n,
where NP is the number of points in the final mesh. If an error has occurred then Y contains the latest approximation to the solution. The remaining columns of Y are not used.
10:   LDY – INTEGERInput
On entry: the first dimension of the array Y as declared in the (sub)program from which D02RAF is called.
Constraint: LDY≥N.
11:   ABT N – REAL (KIND=nag_wp) arrayOutput
On exit: ABT i, for i=1,2,…,n, holds the largest estimated error (in magnitude) of the ith component of the solution over all mesh points.
12:   FCN – SUBROUTINE, supplied by the user.External Procedure
FCN must evaluate the functions fi (i.e., the derivatives yi′) at a general point x for a given value of ε, the continuation parameter (see Section 3).
The specification of FCN is:
SUBROUTINE FCN ( X, EPS, Y, F, N)
INTEGER | N
REAL (KIND=nag_wp) | X, EPS, Y(N), F(N)
1:   X – REAL (KIND=nag_wp)Input
On entry: x, the value of the independent variable.
2:   EPS – REAL (KIND=nag_wp)Input
On entry: ε, the value of the continuation parameter. This is 1 if continuation is not being used.
3:   Y N – REAL (KIND=nag_wp) arrayInput
On entry: yi, for i=1,2,…,n, the values of the dependent variables at x.
4:   F N – REAL (KIND=nag_wp) arrayOutput
On exit: the values of the derivatives fi evaluated at x given ε, for i=1,2,…,n.
5:   N – INTEGERInput
On entry: n, the number of equations.
FCN must either be a module subprogram USEd by, or declared as EXTERNAL in, the (sub)program from which D02RAF is called. Arguments denoted as Input must not be changed by this procedure.
13:   G – SUBROUTINE, supplied by the user.External Procedure
G must evaluate the boundary conditions in equation (3) and place them in the array BC.
The specification of G is:
SUBROUTINE G ( EPS, YA, YB, BC, N)
INTEGER | N
REAL (KIND=nag_wp) | EPS, YA(N), YB(N), BC(N)
1:   EPS – REAL (KIND=nag_wp)Input
On entry: ε, the value of the continuation parameter. This is 1 if continuation is not being used.
2:   YA N – REAL (KIND=nag_wp) arrayInput
On entry: the value yi a, for i=1,2,…,n.
3:   YB N – REAL (KIND=nag_wp) arrayInput
On entry: the value yi b, for i=1,2,…,n.
4:   BC N – REAL (KIND=nag_wp) arrayOutput
On exit: the values gi y a,y b,ε , for i=1,2,…,n. These must be ordered as follows:
(i) | first, the conditions involving only y a (see NUMBEG);
(ii) | next, the NUMMIX coupled conditions involving both y a and y b (see NUMMIX); and,
(iii) | finally, the conditions involving only y b (N-NUMBEG-NUMMIX).
5:   N – INTEGERInput
On entry: n, the number of equations.
G must either be a module subprogram USEd by, or declared as EXTERNAL in, the (sub)program from which D02RAF is called. Arguments denoted as Input must not be changed by this procedure.
14:   IJAC – INTEGERInput
On entry: indicates whether or not you are supplying Jacobian evaluation routines.
IJAC≠0
You must supply JACOBF and JACOBG and also, when continuation is used, JACEPS and JACGEP.
IJAC=0
Numerical differentiation is used to calculate the Jacobian and the routines D02GAW, D02GAX, D02GAY and D02GAZ respectively may be used as the dummy arguments.
15:   JACOBF – SUBROUTINE, supplied by the NAG Library or the user.External Procedure
JACOBF evaluates the Jacobian ∂fi ∂yj , for i=1,2,…,n and j=1,2,…,n, given x and yj, for j=1,2,…,n.
If IJAC=0, then numerical differentiation is used to calculate the Jacobian and the routine D02GAZ may be substituted for this argument.
The specification of JACOBF is:
SUBROUTINE JACOBF ( X, EPS, Y, F, N)
INTEGER | N
REAL (KIND=nag_wp) | X, EPS, Y(N), F(N,N)
1:   X – REAL (KIND=nag_wp)Input
On entry: x, the value of the independent variable.
2:   EPS – REAL (KIND=nag_wp)Input
On entry: ε, the value of the continuation parameter. This is 1 if continuation is not being used.
3:   Y N – REAL (KIND=nag_wp) arrayInput
On entry: yi, for i=1,2,…,n, the values of the dependent variables at x.
4:   F NN – REAL (KIND=nag_wp) arrayOutput
On exit: F ji must be set to the value of ∂fi ∂yj , evaluated at the point x,y, for i=1,2,…,n and j=1,2,…,n.
5:   N – INTEGERInput
On entry: n, the number of equations.
JACOBF must either be a module subprogram USEd by, or declared as EXTERNAL in, the (sub)program from which D02RAF is called. Arguments denoted as Input must not be changed by this procedure.
16:   JACOBG – SUBROUTINE, supplied by the NAG Library or the user.External Procedure
JACOBG evaluates the Jacobians ∂gi ∂yj a and ∂gi ∂yj b . The ordering of the rows of AJ and BJ must correspond to the ordering of the boundary conditions described in the specification of G.
If IJAC=0, then numerical differentiation is used to calculate the Jacobian and the routine D02GAY may be substituted for this argument.
The specification of JACOBG is:
SUBROUTINE JACOBG ( EPS, YA, YB, AJ, BJ, N)
INTEGER | N
REAL (KIND=nag_wp) | EPS, YA(N), YB(N), AJ(N,N), BJ(N,N)
1:   EPS – REAL (KIND=nag_wp)Input
On entry: ε, the value of the continuation parameter. This is 1 if continuation is not being used.
2:   YA N – REAL (KIND=nag_wp) arrayInput
On entry: the value yi a, for i=1,2,…,n.
3:   YB N – REAL (KIND=nag_wp) arrayInput
On entry: the value yi b, for i=1,2,…,n.
4:   AJ NN – REAL (KIND=nag_wp) arrayOutput
On exit: AJ ij must be set to the value ∂gi ∂yj a , for i=1,2,…,n and j=1,2,…,n.
5:   BJ NN – REAL (KIND=nag_wp) arrayOutput
On exit: BJ ij must be set to the value ∂gi ∂yj b , for i=1,2,…,n and j=1,2,…,n.
6:   N – INTEGERInput
On entry: n, the number of equations.
JACOBG must either be a module subprogram USEd by, or declared as EXTERNAL in, the (sub)program from which D02RAF is called. Arguments denoted as Input must not be changed by this procedure.
17:   DELEPS – REAL (KIND=nag_wp)Input/Output
On entry: must be given a value which specifies whether continuation is required. If DELEPS≤0.0 or DELEPS≥1.0 then it is assumed that continuation is not required. If 0.0<DELEPS<1.0 then it is assumed that continuation is required unless DELEPS<machine precision when an error exit is taken. DELEPS is used as the increment ε 2-ε 1 (see (4)) and the choice DELEPS=0.1 is recommended.
On exit: an overestimate of the increment εp-ε p-1 (in fact the value of the increment which would have been tried if the restriction εp=1 had not been imposed). If continuation was not requested then DELEPS=0.0.
If continuation is not requested then JACEPS and JACGEP may each be replaced by dummy actual arguments in the call to D02RAF. (D02GAW and D02GAX respectively may be used as the dummy arguments.)
18:   JACEPS – SUBROUTINE, supplied by the NAG Library or the user.External Procedure
JACEPS evaluates the derivative ∂fi ∂ε given x and y if continuation is being used.
If all Jacobians (derivatives) are to be approximated internally by numerical differentiation, or continuation is not being used, the routine D02GAW may be substituted for this argument.
The specification of JACEPS is:
SUBROUTINE JACEPS ( X, EPS, Y, F, N)
INTEGER | N
REAL (KIND=nag_wp) | X, EPS, Y(N), F(N)
1:   X – REAL (KIND=nag_wp)Input
On entry: x, the value of the independent variable.
2:   EPS – REAL (KIND=nag_wp)Input
On entry: ε, the value of the continuation parameter.
3:   Y N – REAL (KIND=nag_wp) arrayInput
On entry: the solution values yi, for i=1,2,…,n, at the point x.
4:   F N – REAL (KIND=nag_wp) arrayOutput
On exit: F i must contain the value ∂fi ∂ε at the point x,y, for i=1,2,…,n.
5:   N – INTEGERInput
On entry: n, the number of equations.
JACEPS must either be a module subprogram USEd by, or declared as EXTERNAL in, the (sub)program from which D02RAF is called. Arguments denoted as Input must not be changed by this procedure.
19:   JACGEP – SUBROUTINE, supplied by the NAG Library or the user.External Procedure
JACGEP evaluates the derivatives ∂gi ∂ε if continuation is being used.
If all Jacobians (derivatives) are to be approximated internally by numerical differentiation, or continuation is not being used, the routine D02GAX may be substituted for this argument.
The specification of JACGEP is:
SUBROUTINE JACGEP ( EPS, YA, YB, BCEP, N)
INTEGER | N
REAL (KIND=nag_wp) | EPS, YA(N), YB(N), BCEP(N)
1:   EPS – REAL (KIND=nag_wp)Input
On entry: ε, the value of the continuation parameter.
2:   YA N – REAL (KIND=nag_wp) arrayInput
On entry: the value of yi a, for i=1,2,…,n.
3:   YB N – REAL (KIND=nag_wp) arrayInput
On entry: the value of yi b, for i=1,2,…,n.
4:   BCEP N – REAL (KIND=nag_wp) arrayOutput
On exit: BCEP i must contain the value of ∂gi ∂ε , for i=1,2,…,n.
5:   N – INTEGERInput
On entry: n, the number of equations.
JACGEP must either be a module subprogram USEd by, or declared as EXTERNAL in, the (sub)program from which D02RAF is called. Arguments denoted as Input must not be changed by this procedure.
20:   WORK LWORK – REAL (KIND=nag_wp) arrayWorkspace
21:   LWORK – INTEGERInput
On entry: the dimension of the array WORK as declared in the (sub)program from which D02RAF is called.
Constraint: LWORK≥MNP×3⁢N 2+6⁢N+2+4⁢N 2+3⁢N.
22:   IWORK LIWORK – INTEGER arrayWorkspace
23:   LIWORK – INTEGERInput
On entry: the dimension of the array IWORK as declared in the (sub)program from which D02RAF is called.
Constraints:
  • if IJAC≠0, LIWORK≥MNP×2×N+1+N;
  • if IJAC=0, LIWORK≥MNP×2×N+1+N 2+4×N+2.
24:   IFAIL – INTEGERInput/Output
For this routine, the normal use of IFAIL is extended to control the printing of error and warning messages as well as specifying hard or soft failure (see Section 3.4 in How to Use the NAG Library and its Documentation).
On entry: IFAIL must be set to a value with the decimal expansion cba, where each of the decimal digits c, b and a must have a value of 0 or 1.
a=0 | specifies hard failure, otherwise soft failure;
b=0 | suppresses error messages, otherwise error messages will be printed (see Section 6);
c=0 | suppresses warning messages, otherwise warning messages will be printed (see Section 6).
The recommended value for inexperienced users is 110 (i.e., hard failure with all messages printed).
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
One or more of the arguments N, MNP, NP, NUMBEG, NUMMIX, TOL, DELEPS, LWORK or LIWORK is incorrectly set, or X 1≥X NP or the mesh points X i are not in strictly ascending order.
IFAIL=2
A finer mesh is required for the accuracy requested; that is MNP is not large enough. This error exit normally occurs when the problem being solved is difficult (for example, there is a boundary layer) and high accuracy is requested. A poor initial choice of mesh points will make this error exit more likely.
IFAIL=3
The Newton iteration has failed to converge. There are several possible causes for this error:
(i) | faulty coding in one of the Jacobian calculation routines;
(ii) | if IJAC=0 then inaccurate Jacobians may have been calculated numerically (this is a very unlikely cause); or,
(iii) | a poor initial mesh or initial approximate solution has been selected either by you or by default or there are not enough points in the initial mesh. Possibly, you should try the continuation facility.
IFAIL=4
The Newton iteration has reached round-off error level. It could be however that the answer returned is satisfactory. The error is likely to occur if too high an accuracy is requested.
IFAIL=5
The Jacobian calculated by JACOBG (or the equivalent matrix calculated by numerical differentiation) is singular. This may occur due to faulty coding of JACOBG or, in some circumstances, to a zero initial choice of approximate solution (such as is chosen when INIT=0).
IFAIL=6
There is no dependence on ε when continuation is being used. This can be due to faulty coding of JACEPS or JACGEP or, in some circumstances, to a zero initial choice of approximate solution (such as is chosen when INIT=0).
IFAIL=7
DELEPS is required to be less than machine precision for continuation to proceed. It is likely that either the problem (3) has no solution for some value near the current value of ε (see the advisory print out from D02RAF) or that the problem is so difficult that even with continuation it is unlikely to be solved using this routine. If the latter cause is suspected then using more mesh points initially may help.
IFAIL=8
IFAIL=9
A serious error has occurred in an internal call. Check all array subscripts and subroutine argument lists in calls to D02RAF. Seek expert help.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

The solution returned by the routine will be accurate to your tolerance as defined by the relation (5) except in extreme circumstances. The final error estimate over the whole mesh for each component is given in the array ABT. If too many points are specified in the initial mesh, the solution may be more accurate than requested and the error may not be approximately equidistributed.

8 Parallelism and Performance

D02RAF is not thread safe and should not be called from a multithreaded user program. Please see Section 3.12.1 in How to Use the NAG Library and its Documentation for more information on thread safety.
D02RAF is not threaded in any implementation.

9 Further Comments

There are too many factors present to quantify the timing. The time taken by D02RAF is negligible only on very simple problems.
You are strongly recommended to set IFAIL to obtain self-explanatory error messages, and also monitoring information about the course of the computation. Monitoring information is written to a logical advisory message unit which normally default to the same unit number as the error message unit (see Section 3.5 in How to Use the NAG Library and its Documentation for details); the advisory message unit number can be changed by calling X04ABF.
In the case where you wish to solve a sequence of similar problems, the use of the final mesh and solution from one case as the initial mesh is strongly recommended for the next.

10 Example

This example solves the differential equation
y′′′=-y y′′-2 ε 1-y′2
with ε=1 and boundary conditions
y 0=y′0=0,  y′10=1
to an accuracy specified by TOL=1.0E−4. The continuation facility is used with the continuation parameter ε introduced as in the differential equation above and with DELEPS=0.1 initially. (The continuation facility is not needed for this problem and is used here for illustration.)

10.1 Program Text

Program Text (d02rafe.f90)

10.2 Program Data

Program Data (d02rafe.d)

10.3 Program Results

Program Results (d02rafe.r)

GnuplotProduced by GNUPLOT 4.6 patchlevel 3 0 2 4 6 8 10 0 2 4 6 8 10 0 0.2 0.4 0.6 0.8 1 1.2 1.4 1.6 1.8 y y' and y'' x Example Program Solution of Third-order BVP y y' y'' gnuplot_plot_1 gnuplot_plot_2 gnuplot_plot_3
D02 Chapter Contents
D02 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


D02SAF : NAG Library, Mark 26

D02 Chapter Contents
D02 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

D02SAF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

D02SAF solves a two-point boundary value problem for a system of first-order ordinary differential equations with boundary conditions, combined with additional algebraic equations. It uses initial value techniques and a modified Newton iteration in a shooting and matching method.

2 Specification

SUBROUTINE D02SAF ( P, M, N, N1, PE, PF, E, DP, NPOINT, SWP, LDSWP, ICOUNT, RANGE, BC, FCN, EQN, CONSTR, YMAX, MONIT, PRSOL, W, LDW, SDW, IFAIL)
INTEGER | M, N, N1, NPOINT, LDSWP, ICOUNT, LDW, SDW, IFAIL
REAL (KIND=nag_wp) | P(M), PE(M), PF(M), E(N), DP(M), SWP(LDSWP,6), YMAX, W(LDW,SDW)
LOGICAL | CONSTR
EXTERNAL | RANGE, BC, FCN, EQN, CONSTR, MONIT, PRSOL

3 Description

D02SAF solves a two-point boundary value problem for a system of n first-order ordinary differential equations with separated boundary conditions by determining certain unknown arguments p 1,p 2,…,pm. (There may also be additional algebraic equations to be solved in the determination of the arguments and, if so, these equations are defined by EQN.) The arguments may be, but need not be, boundary values; they may include eigenvalues, arguments in the coefficients of the differential equations, coefficients in series expansions or asymptotic expansions for boundary values, the length of the range of definition of the system of differential equations, etc.
It is assumed that we have a system of n differential equations of the form
y′ = f x,y,p , (1)
where p = p 1,p 2,…,pm T is the vector of arguments, and that the derivative f is evaluated by FCN. Also, n 1 of the equations are assumed to depend on p. For n 1<n the n-n 1 equations of the system are not involved in the matching process. These are the driving equations; they should be independent of p and of the solution of the other n 1 equations. In numbering the equations in FCN and BC the driving equations must be put first (as they naturally occur in most applications). The range of definition [a,b] of the differential equations is defined by RANGE and may depend on the arguments p 1,p 2,…,pm (that is, on p). RANGE must define the points x 1,x 2,…,xNPOINT, NPOINT≥2, which must satisfy
a=x 1<x 2<⋯<xNPOINT=b (2)
(or a similar relationship with all the inequalities reversed).
If NPOINT>2 the points x 1,x 2,…,xNPOINT can be used to break up the range of definition. Integration is restarted at each of these points. This means that the differential equations (1) can be defined differently in each sub-interval xi,x i+1 , for i=1,2,…,NPOINT-1. Also, since initial and maximum integration step sizes can be supplied on each sub-interval (via the array SWP), you can indicate parts of the range a,b where the solution y x may be difficult to obtain accurately and can take appropriate action.
The boundary conditions may also depend on the arguments and are applied at a=x 1 and b=xNPOINT. They are defined (in BC) in the form
y a=g 1 p,>y b=g 2 p. (3)
The boundary value problem is solved by determining the unknown arguments p by a shooting and matching technique. The differential equations are always integrated from a to b with initial values y a=g 1 p. The solution vector thus obtained at x=b is subtracted from the vector g 2 p to give the n 1 residuals r 1 p, ignoring the first n-n 1, driving equations. Because the direction of integration is always from a to b, it is unnecessary, in BC, to supply values for the first n-n 1 boundary values at b, that is the first n-n 1 components of g 2 in (3). For n 1<m then r 1 p. Together with the m-n 1 equations defined by EQN,
r 2 p=0, (4)
these give a vector of residuals r, which at the solution, p, must satisfy
r 1 p r 2 p =0. (5)
These equations are solved by a pseudo-Newton iteration which uses a modified singular value decomposition of J= ∂r ∂p when solving the linear equations which arise. The Jacobian J used in Newton's method is obtained by numerical differentiation. The arguments at each Newton iteration are accepted only if the norm D-1J~+r 2 is much reduced from its previous value. Here J~+ is the pseudo-inverse, calculated from the singular value decomposition, of a modified version of the Jacobian J (J+ is actually the inverse of the Jacobian in well-conditioned cases). D is a diagonal matrix with
d ii=max pi,PF i (6)
where PF is an array of floor values.
See Deuflhard (1974) for further details of the variants of Newton's method used, Gay (1976) for the modification of the singular value decomposition and Gladwell (1979) for an overview of the method used.
Two facilities are provided to prevent the pseudo-Newton iteration running into difficulty. First, you are permitted to specify constraints on the values of the arguments p via a CONSTR. These constraints are only used to prevent the Newton iteration using values for p which would violate them; that is, they are not used to determine the values of p. Secondly, you are permitted to specify a maximum value ymax for y x∞ at all points in the range a,b. It is intended that this facility be used to prevent machine ‘overflow’ in the integrations of equation (1) due to poor choices of the arguments p which might arise during the Newton iteration. When using this facility, it is presumed that you have an estimate of the likely size of y x∞ at all points x∈a,b. ymax should then be chosen rather larger (say by a factor of 10) than this estimate.
You are strongly advised to supply a MONIT (or to call the ‘default’ routine D02HBX, see MONIT) to monitor the progress of the pseudo-Newton iteration. You can output the solution of the problem y x by supplying a suitable PRSOL (an example is given in Section 10 of a routine designed to output the solution at equally spaced points).
D02SAF is designed to try all possible options before admitting failure and returning to you. Provided the routine can start the Newton iteration from the initial point p it will exhaust all the options available to it (though you can override this by specifying a maximum number of iterations to be taken). The fact that all its options have been exhausted is the only error exit from the iteration. Other error exits are possible, however, whilst setting up the Newton iteration and when computing the final solution.
If you require more background information about the solution of boundary value problems by shooting methods you are recommended to read the appropriate chapters of Hall and Watt (1976), and for a detailed description of D02SAF Gladwell (1979) is recommended.

4 References

Deuflhard P (1974) A modified Newton method for the solution of ill-conditioned systems of nonlinear equations with application to multiple shooting Numer. Math. 22 289–315
Gay D (1976) On modifying singular values to solve possibly singular systems of nonlinear equations Working Paper 125 Computer Research Centre, National Bureau for Economics and Management Science, Cambridge, MA
Gladwell I (1979) The development of the boundary value codes in the ordinary differential equations chapter of the NAG Library Codes for Boundary Value Problems in Ordinary Differential Equations. Lecture Notes in Computer Science (eds B Childs, M Scott, J W Daniel, E Denman and P Nelson) 76 Springer–Verlag
Hall G and Watt J M (ed.) (1976) Modern Numerical Methods for Ordinary Differential Equations Clarendon Press, Oxford

5 Arguments

1:   P M – REAL (KIND=nag_wp) arrayInput/Output
On entry: P i must be set to an estimate of the ith argument, pi, for i=1,2,…,m.
On exit: the corrected value for the ith argument, unless an error has occurred, when it contains the last calculated value of the argument.
2:   M – INTEGERInput
On entry: m, the number of arguments.
Constraint: M>0.
3:   N – INTEGERInput
On entry: n, the total number of differential equations.
Constraint: N>0.
4:   N1 – INTEGERInput
On entry: n 1, the number of differential equations active in the matching process. The active equations must be placed last in the numbering in FCN and BC. The first N-N1 equations are used as the driving equations.
Constraint: N1≤N, N1≤M and N1>0.
5:   PE M – REAL (KIND=nag_wp) arrayInput
On entry: PE i, for i=1,2,…,m, must be set to a positive value for use in the convergence test in the ith argument pi. See the description of PF for further details.
Constraint: PE i>0.0, for i=1,2,…,m.
6:   PF M – REAL (KIND=nag_wp) arrayInput/Output
On entry: PF i, for i=1,2,…,m, should be set to a ‘floor’ value in the convergence test on the ith argument pi. If PF i≤0.0 on entry then it is set to the small positive value ε (where ε may in most cases be considered to be machine precision); otherwise it is used unchanged.
The Newton iteration is presumed to have converged if a full Newton step is taken (ISTATE=1 in the specification of MONIT), the singular values of the Jacobian are not being significantly perturbed (also see MONIT) and if the Newton correction Ci satisfies
Ci≤PE i×max pi,PF i,  i=1,2,…,m,
where pi is the current value of the ith argument. The values PF i are also used in determining the Newton iterates as discussed in Section 3, see equation (6).
On exit: the values actually used.
7:   E N – REAL (KIND=nag_wp) arrayInput
On entry: values for use in controlling the local error in the integration of the differential equations. If erri is an estimate of the local error in yi, for i=1,2,…,n, then
err i ≤ E i × max ε,yi ,
where ε may in most cases be considered to be machine precision.
Suggested value: E i=10-5.
Constraint: E i>0.0, for i=1,2,…,N.
8:   DP M – REAL (KIND=nag_wp) arrayInput/Output
On entry: a value to be used in perturbing the argument pi in the numerical differentiation to estimate the Jacobian used in Newton's method. If DP i=0.0 on entry, an estimate is made internally by setting
DP i = ε × max PF i,pi , (7)
where pi is the initial value of the argument supplied by you and ε may in most cases be considered to be machine precision. The estimate of the Jacobian, J, is made using forward differences, that is for each i, for i=1,2,…,m, pi is perturbed to pi+DP i and the ith column of J is estimated as
r pi+DP i-r pi/DP i
where the other components of p are unchanged (see (3) for the notation used). If this fails to produce a Jacobian with significant columns, backward differences are tried by perturbing pi to pi-DP i and if this also fails then central differences are used with pi perturbed to pi+10.0×DP i. If this also fails then the calculation of the Jacobian is abandoned. If the Jacobian has not previously been calculated then an error exit is taken. If an earlier estimate of the Jacobian is available then the current argument set, pi, for i=1,2,…,m, is abandoned in favour of the last argument set from which useful progress was made and the singular values of the Jacobian used at the point are modified before proceeding with the Newton iteration. You are recommended to use the default value DP i=0.0 unless you have prior knowledge of a better choice. If any of the perturbations described are likely to lead to an unfortunate set of argument values then you should use the LOGICAL FUNCTION CONSTR to prevent such perturbations (all changes of arguments are checked by a call to CONSTR).
On exit: the values actually used.
9:   NPOINT – INTEGERInput
On entry: 2 plus the number of break-points in the range of definition of the system of differential equations (1).
Constraint: NPOINT≥2.
10:   SWP LDSWP 6 – REAL (KIND=nag_wp) arrayInput/Output
On entry: SWP i 1 must contain an estimate for an initial step size for integration across the ith sub-interval X i,X i+1 , for i=1,2,…,NPOINT-1, (see RANGE). SWP i 1 should have the same sign as X i+1-X i if it is nonzero. If SWP i 1=0.0, on entry, a default value for the initial step size is calculated internally. This is the recommended mode of entry.
SWP i 3 must contain a lower bound for the modulus of the step size on the ith sub-interval X i ,X i + 1 , for i=1,2,…,NPOINT-1. If SWP i 3=0.0 on entry, a very small default value is used. By setting SWP i 3>0.0 but smaller than the expected step sizes (assuming you have some insight into the likely step sizes) expensive integrations with arguments p far from the solution can be avoided.
SWP i 2 must contain an upper bound on the modulus of the step size to be used in the integration on X i ,X i + 1 , for i=1,2,…,NPOINT-1. If SWP i 2=0.0 on entry no bound is assumed. This is the recommended mode of entry unless the solution is expected to have important features which might be ‘missed’ in the integration if the step size were permitted to be chosen freely.
On exit: SWP i 1 contains the initial step size used on the last integration on X i ,X i + 1 , for i=1,2,…,NPOINT-1, (excluding integrations during the calculation of the Jacobian).
SWP i 2, for i=1,2,…,NPOINT-1, is usually unchanged. If the maximum step size SWP i 2 is so small or the length of the range X i ,X i + 1 is so short that on the last integration the step size was not controlled in the main by the size of the error tolerances E i but by these other factors, then SWP NPOINT 2 is set to the floating-point value of i if the problem last occurred in X i ,X i + 1 . Any results obtained when this value is returned as nonzero should be viewed with caution.
SWP i 3, for i=1,2,…,NPOINT-1, are unchanged.
If an error exit with IFAIL=4, 5 or 6 (see Section 6) occurs on the integration made from X i to X i+1 the floating-point value of i is returned in SWP NPOINT 1. The actual point x ∈ X i ,X i + 1 where the error occurred is returned in SWP 15 (see also the specification of W). The floating-point value of NPOINT is returned in SWP NPOINT 1 if the error exit is caused by a call to BC.
If an error exit occurs when estimating the Jacobian matrix (IFAIL=7, 8, 9, 10, 11 or 12, see Section 6) and if argument pi was the cause of the failure then on exit SWP NPOINT 1 contains the floating-point value of i.
SWP i 4 contains the point X i, for i=1,2,…,NPOINT, used at the solution p or at the final values of p if an error occurred.
SWP is also partly used as workspace.
11:   LDSWP – INTEGERInput
On entry: the first dimension of the array SWP as declared in the (sub)program from which D02SAF is called.
Constraint: LDSWP≥NPOINT.
12:   ICOUNT – INTEGERInput
On entry: an upper bound on the number of Newton iterations. If ICOUNT=0 on entry, no check on the number of iterations is made (this is the recommended mode of entry).
Constraint: ICOUNT≥0.
13:   RANGE – SUBROUTINE, supplied by the user.External Procedure
RANGE must specify the break-points xi, for i=1,2,…,NPOINT, which may depend on the arguments pj, for j=1,2,…,m.
The specification of RANGE is:
SUBROUTINE RANGE ( X, NPOINT, P, M)
INTEGER | NPOINT, M
REAL (KIND=nag_wp) | X(NPOINT), P(M)
1:   X NPOINT – REAL (KIND=nag_wp) arrayOutput
On exit: the ith break-point, for i=1,2,…,NPOINT. The sequence X i must be strictly monotonic, that is either
a=X 1<X 2<⋯<X NPOINT=b
or
a=X 1>X 2>⋯>X NPOINT=b.
2:   NPOINT – INTEGERInput
On entry: 2 plus the number of break-points in a,b.
3:   P M – REAL (KIND=nag_wp) arrayInput
On entry: the current estimate of the ith argument, for i=1,2,…,m.
4:   M – INTEGERInput
On entry: m, the number of arguments.
RANGE must either be a module subprogram USEd by, or declared as EXTERNAL in, the (sub)program from which D02SAF is called. Arguments denoted as Input must not be changed by this procedure.
14:   BC – SUBROUTINE, supplied by the user.External Procedure
BC must place in G1 and G2 the boundary conditions at a and b respectively.
The specification of BC is:
SUBROUTINE BC ( G1, G2, P, M, N)
INTEGER | M, N
REAL (KIND=nag_wp) | G1(N), G2(N), P(M)
1:   G1 N – REAL (KIND=nag_wp) arrayOutput
On exit: the value of yi a, for i=1,2,…,n, (where this may be a known value or a function of the parameters pj, for j=1,2,…,m).
2:   G2 N – REAL (KIND=nag_wp) arrayOutput
On exit: the value of yi b, for i=1,2,…,n, (where these may be known values or functions of the parameters pj, for j=1,2,…,m). If n>n 1, so that there are some driving equations, then the first n-n 1 values of G2 need not be set since they are never used.
3:   P M – REAL (KIND=nag_wp) arrayInput
On entry: an estimate of the ith argument, pi, for i=1,2,…,m.
4:   M – INTEGERInput
On entry: m, the number of arguments.
5:   N – INTEGERInput
On entry: n, the number of differential equations.
BC must either be a module subprogram USEd by, or declared as EXTERNAL in, the (sub)program from which D02SAF is called. Arguments denoted as Input must not be changed by this procedure.
15:   FCN – SUBROUTINE, supplied by the user.External Procedure
FCN must evaluate the functions fi (i.e., the derivatives yi′), for i=1,2,…,n.
The specification of FCN is:
SUBROUTINE FCN ( X, Y, F, N, P, M, I)
INTEGER | N, M, I
REAL (KIND=nag_wp) | X, Y(N), F(N), P(M)
1:   X – REAL (KIND=nag_wp)Input
On entry: x, the value of the argument.
2:   Y N – REAL (KIND=nag_wp) arrayInput
On entry: yi, for i=1,2,…,n, the value of the argument.
3:   F N – REAL (KIND=nag_wp) arrayOutput
On exit: the derivative of yi, for i=1,2,…,n, evaluated at x. F i may depend upon the parameters pj, for j=1,2,…,m. If there are any driving equations (see Section 3) then these must be numbered first in the ordering of the components of F.
4:   N – INTEGERInput
On entry: n, the number of equations.
5:   P M – REAL (KIND=nag_wp) arrayInput
On entry: the current estimate of the ith argument pi, for i=1,2,…,m.
6:   M – INTEGERInput
On entry: m, the number of arguments.
7:   I – INTEGERInput
On entry: specifies the sub-interval xi,x i+1 on which the derivatives are to be evaluated.
FCN must either be a module subprogram USEd by, or declared as EXTERNAL in, the (sub)program from which D02SAF is called. Arguments denoted as Input must not be changed by this procedure.
16:   EQN – SUBROUTINE, supplied by the NAG Library or the user.External Procedure
EQN is used to describe the additional algebraic equations to be solved in the determination of the parameters, pi, for i=1,2,…,m. If there are no additional algebraic equations (i.e., m=n 1) then EQN is never called and the dummy routine D02HBZ should be used as the actual argument.
The specification of EQN is:
SUBROUTINE EQN ( E, Q, P, M)
INTEGER | Q, M
REAL (KIND=nag_wp) | E(Q), P(M)
1:   E Q – REAL (KIND=nag_wp) arrayOutput
On exit: the vector of residuals, r 2 p, that is the amount by which the current estimates of the arguments fail to satisfy the algebraic equations.
2:   Q – INTEGERInput
On entry: the number of algebraic equations, m-n 1.
3:   P M – REAL (KIND=nag_wp) arrayInput
On entry: the current estimate of the ith argument pi, for i=1,2,…,m.
4:   M – INTEGERInput
On entry: m, the number of arguments.
EQN must either be a module subprogram USEd by, or declared as EXTERNAL in, the (sub)program from which D02SAF is called. Arguments denoted as Input must not be changed by this procedure.
17:   CONSTR – LOGICAL FUNCTION, supplied by the user.External Procedure
CONSTR is used to prevent the pseudo-Newton iteration running into difficulty. CONSTR should return the value .TRUE. if the constraints are satisfied by the parameters p 1,p 2,…,pm. Otherwise CONSTR should return the value .FALSE.. Usually the dummy function D02HBY, which returns the value .TRUE. at all times, will suffice and in the first instance this is recommended as the actual argument.
The specification of CONSTR is:
FUNCTION CONSTR ( P, M)
LOGICAL CONSTR
INTEGER | M
REAL (KIND=nag_wp) | P(M)
1:   P M – REAL (KIND=nag_wp) arrayInput
On entry: an estimate of the ith argument, pi, for i=1,2,…,m.
2:   M – INTEGERInput
On entry: m, the number of arguments.
CONSTR must either be a module subprogram USEd by, or declared as EXTERNAL in, the (sub)program from which D02SAF is called. Arguments denoted as Input must not be changed by this procedure.
18:   YMAX – REAL (KIND=nag_wp)Input
On entry: a non-negative value which is used as a bound on all values y x∞ where y x is the solution at any point x between X 1 and X NPOINT for the current arguments p 1,p 2,…,pm. If this bound is exceeded the integration is terminated and the current arguments are rejected. Such a rejection will result in an error exit if it prevents the initial residual or Jacobian, or the final solution, being calculated. If YMAX=0 on entry, no bound on the solution y is used; that is the integrations proceed without any checking on the size of y∞.
19:   MONIT – SUBROUTINE, supplied by the NAG Library or the user.External Procedure
MONIT enables you to monitor the values of various quantities during the calculation. It is called by D02SAF after every calculation of the norm D-1J~+r 2 which determines the strategy of the Newton method, every time there is an internal error exit leading to a change of strategy, and before an error exit when calculating the initial Jacobian. Usually the routine D02HBX will be adequate and you are advised to use this as the actual argument for MONIT in the first instance. (In this case a call to X04ABF must be made before the call of D02SAF.) If no monitoring is required, the dummy routine D02SAS may be used.
The specification of MONIT is:
SUBROUTINE MONIT ( ISTATE, IFLAG, IFAIL1, P, M, F, PNORM, PNORM1, EPS, D)
INTEGER | ISTATE, IFLAG, IFAIL1, M
REAL (KIND=nag_wp) | P(M), F(M), PNORM, PNORM1, EPS, D(M)
1:   ISTATE – INTEGERInput
On entry: the state of the Newton iteration.
ISTATE=0
The calculation of the residual, Jacobian and D-1J~+r 2 are taking place.
ISTATE=1 to 5
During the Newton iteration a factor of 2-ISTATE+1 of the Newton step is being used to try to reduce the norm.
ISTATE=6
The current Newton step has been rejected and the Jacobian is being re-calculated.
ISTATE=-6 to -1
An internal error exit has caused the rejection of the current set of argument values, p. -ISTATE is the value which ISTATE would have taken if the error had not occurred.
ISTATE=-7
An internal error exit has occurred when calculating the initial Jacobian.
2:   IFLAG – INTEGERInput
On entry: whether or not the Jacobian being used has been calculated at the beginning of the current iteration. If the Jacobian has been updated then IFLAG=1; otherwise IFLAG=2. The Jacobian is only calculated when convergence to the current argument values has been slow.
3:   IFAIL1 – INTEGERInput
On entry: if -6≤ISTATE≤-1, IFAIL1 specifies the IFAIL error number that would be produced were control returned to you. IFAIL1 is unspecified for values of ISTATE outside this range.
4:   P M – REAL (KIND=nag_wp) arrayInput
On entry: the current estimate of the ith argument pi, for i=1,2,…,m.
5:   M – INTEGERInput
On entry: m, the number of arguments.
6:   F M – REAL (KIND=nag_wp) arrayInput
On entry: r, the residual corresponding to the current argument values, provided 1≤ISTATE≤5 or ISTATE=-7. F is unspecified for other values of ISTATE.
7:   PNORM – REAL (KIND=nag_wp)Input
On entry: a quantity against which all reductions in norm are currently measured.
8:   PNORM1 – REAL (KIND=nag_wp)Input
On entry: p, the norm of the current arguments. It is set for 1≤ISTATE≤5 and is undefined for other values of ISTATE.
9:   EPS – REAL (KIND=nag_wp)Input
On entry: gives some indication of the convergence rate. It is the current singular value modification factor (see Gay (1976)). It is zero initially and whenever convergence is proceeding steadily. EPS is ε 3/8 or greater (where ε may in most cases be considered machine precision) when the singular values of J are approximately zero or when convergence is not being achieved. The larger the value of EPS the worse the convergence rate. When EPS becomes too large the Newton iteration is terminated.
10:   D M – REAL (KIND=nag_wp) arrayInput
On entry: J, the singular values of the current modified Jacobian matrix. If D m is small relative to D 1 for a number of Jacobians corresponding to different argument values then the computed results should be viewed with suspicion. It could be that the matching equations do not depend significantly on some argument (which could be due to a programming error in FCN, BC, RANGE or EQN). Alternatively, the system of differential equations may be very ill-conditioned when viewed as an initial value problem, in which case D02SAF is unsuitable. This may also be indicated by some singular values being very large. These values of D i, for i=1,2,…,m, should not be changed.
MONIT must either be a module subprogram USEd by, or declared as EXTERNAL in, the (sub)program from which D02SAF is called. Arguments denoted as Input must not be changed by this procedure.
20:   PRSOL – SUBROUTINE, supplied by the NAG Library or the user.External Procedure
PRSOL can be used to obtain values of the solution y at a selected point z by integration across the final range X 1,X NPOINT . If no output is required D02HBW can be used as the actual argument.
The specification of PRSOL is:
SUBROUTINE PRSOL ( Z, Y, N)
INTEGER | N
REAL (KIND=nag_wp) | Z, Y(N)
1:   Z – REAL (KIND=nag_wp)Input/Output
On entry: contains x 1 on the first call. On subsequent calls Z contains its previous output value.
On exit: the next point at which output is required. The new point must be nearer X NPOINT than the old.
If Z is set to a point outside X 1,X NPOINT the process stops and control returns from D02SAF to the (sub)program from which D02SAF is called. Otherwise the next call to PRSOL is made by D02SAF at the point Z, with solution values y 1,y 2,…,yn at Z contained in Y. If Z is set to X NPOINT exactly, the final call to PRSOL is made with y 1,y 2,…,yn as values of the solution at X NPOINT produced by the integration. In general the solution values obtained at X NPOINT from PRSOL will differ from the values obtained at this point by a call to BC. The difference between the two solutions is the residual r. You are reminded that the points X 1,X 2,…,X NPOINT are available in the locations SWP 14,SWP 24,…,SWP NPOINT 4 at all times.
2:   Y N – REAL (KIND=nag_wp) arrayInput
On entry: the solution value yi, for i=1,2,…,n, at z.
3:   N – INTEGERInput
On entry: n, the total number of differential equations.
PRSOL must either be a module subprogram USEd by, or declared as EXTERNAL in, the (sub)program from which D02SAF is called. Arguments denoted as Input must not be changed by this procedure.
21:   W LDWSDW – REAL (KIND=nag_wp) arrayOutput
On exit: in the case of an error exit of the type where the point of failure is returned in SWP 15, the solution at this point of failure is returned in W i 1, for i=1,2,…,n.
Otherwise W is used for workspace.
22:   LDW – INTEGERInput
On entry: the first dimension of the array W as declared in the (sub)program from which D02SAF is called.
Constraint: LDW≥max N,M.
23:   SDW – INTEGERInput
On entry: the second dimension of the array W as declared in the (sub)program from which D02SAF is called.
Constraint: SDW≥3×M+12+max 11,M.
24:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
One or more of the arguments N, N1, M, LDSWP, NPOINT, ICOUNT, LDW, SDW, E, PE or YMAX is incorrectly set.
IFAIL=2
The constraints have been violated by the initial arguments.
IFAIL=3
The condition X 1<X 2<⋯<X NPOINT (or X 1>X 2>⋯>X NPOINT) has been violated on a call to RANGE with the initial arguments.
IFAIL=4
In the integration from X 1 to X NPOINT with the initial or the final arguments, the step size was reduced too far for the integration to proceed. Consider reversing the order of the points X 1,X 2,…,X NPOINT. If this error exit still results, it is likely that D02SAF is not a suitable method for solving the problem, or the initial choice of arguments is very poor, or the accuracy requirement specified by E i, for i=1,2,…,n, is too stringent.
IFAIL=5
In the integration from X 1 to X NPOINT with the initial or final arguments, an initial step could not be found to start the integration on one of the intervals X i to X i+1. Consider reversing the order of the points. If this error exit still results it is likely that D02SAF is not a suitable routine for solving the problem, or the initial choice of arguments is very poor, or the accuracy requirement specified by E i, for i=1,2,…,n, is much too stringent.
IFAIL=6
In the integration from X 1 to X NPOINT with the initial or final arguments, the solution exceeded YMAX in magnitude (when YMAX>0.0). It is likely that the initial choice of arguments was very poor or YMAX was incorrectly set.
Note: on an error with IFAIL=4, 5 or 6 with the initial arguments, the interval in which failure occurs is contained in SWP NPOINT 1. If a MONIT similar to the one in Section 10 is being used then it is a simple matter to distinguish between errors using the initial and final arguments. None of the error exits IFAIL=4, 5 or 6 should occur on the final integration (when computing the solution) as this integration has already been performed previously with exactly the same arguments pi, for i=1,2,…,m. Seek expert help if this error occurs.
IFAIL=7
On calculating the initial approximation to the Jacobian, the constraints were violated.
IFAIL=8
On perturbing the arguments when calculating the initial approximation to the Jacobian, the condition X 1<X 2<⋯<X NPOINT (or X 1>X 2>⋯>X NPOINT) is violated.
IFAIL=9
On calculating the initial approximation to the Jacobian, the integration step size was reduced too far to make further progress (see IFAIL=4).
IFAIL=10
On calculating the initial approximation to the Jacobian, the initial integration step size on some interval was too small (see IFAIL=5).
IFAIL=11
On calculating the initial approximation to the Jacobian, the solution of the system of differential equations exceeded YMAX in magnitude (when YMAX>0.0).
Note: all the error exits IFAIL=7, 8, 9, 10 and 11 can be treated by reducing the size of some or all the elements of DP.
IFAIL=12
On calculating the initial approximation to the Jacobian, a column of the Jacobian is found to be insignificant. This could be due to an element DP i being too small (but nonzero) or the solution having no dependence on one of the arguments (a programming error).
Note: on an error exit with IFAIL=7, 8, 9, 10, 11 or 12, if a perturbation of the argument pi is the cause of the error then SWP NPOINT 1 will contain the floating-point value of i.
IFAIL=13
After calculating the initial approximation to the Jacobian, the calculation of its singular value decomposition failed. It is likely that the error will never occur as it is usually associated with the Jacobian having multiple singular values. To remedy the error it should only be necessary to change the initial arguments. If the error persists it is likely that the problem has not been correctly formulated.
IFAIL=14
The Newton iteration has failed to converge after exercising all its options. You are strongly recommended to monitor the progress of the iteration via MONIT. There are many possible reasons for the iteration not converging. Amongst the most likely are:
(a) | there is no solution;
(b) | the initial arguments are too far away from the correct arguments;
(c) | the problem is too ill-conditioned as an initial value problem for Newton's method to choose suitable corrections;
(d) | the accuracy requirements for convergence are too restrictive, that is some of the components of PE (and maybe PF) are too small – in this case the final value of this norm output via MONIT will usually be very small; or
(e) | the initial arguments are so close to the solution arguments p that the Newton iteration cannot find improved arguments. The norm output by MONIT should be very small.
IFAIL=15
The number of iterations permitted by ICOUNT has been exceeded (in the case when ICOUNT>0 on entry).
IFAIL=16
IFAIL=17
IFAIL=18
IFAIL=19
These indicate that there has been a serious error in an internal call. Check all subroutine calls and array dimensions. Seek expert help.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

If the iteration converges, the accuracy to which the unknown arguments are determined is usually close to that specified by you. The accuracy of the solution (output via PRSOL) depends on the error tolerances E i, for i=1,2,…,n. You are strongly recommended to vary all tolerances to check the accuracy of the arguments p and the solution y.

8 Parallelism and Performance

D02SAF is not thread safe and should not be called from a multithreaded user program. Please see Section 3.12.1 in How to Use the NAG Library and its Documentation for more information on thread safety.
D02SAF makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The time taken by D02SAF depends on the complexity of the system of differential equations and on the number of iterations required. In practice, the integration of the differential system (1) is usually by far the most costly process involved. The computing time for integrating the differential equations can sometimes depend critically on the quality of the initial estimates for the arguments p. If it seems that too much computing time is required and, in particular, if the values of the residuals (output in MONIT) are much larger than expected given your knowledge of the expected solution, then the coding of FCN, EQN, RANGE and BC should be checked for errors. If no errors can be found then an independent attempt should be made to improve the initial estimates p.
In the case of an error exit in the integration of the differential system indicated by IFAIL=4, 5, 9 or 10 you are strongly recommended to perform trial integrations with D02PFF to determine the effects of changes of the local error tolerances and of changes to the initial choice of the arguments pi, for i=1,2,…,m, (that is the initial choice of p).
It is possible that by following the advice given in Section 6 an error exit with IFAIL=7, 8, 9, 10 or 11 might be followed by one with IFAIL=12 (or vice-versa) where the advice given is the opposite. If you are unable to refine the choice of DP i, for i=1,2,…,n, such that both these types of exits are avoided then the problem should be rescaled if possible or the method must be abandoned.
The choice of the ‘floor’ values PF i, for i=1,2,…,m, may be critical in the convergence of the Newton iteration. For each value i, the initial choice of pi and the choice of PF i should not both be very small unless it is expected that the final argument pi will be very small and that it should be determined accurately in a relative sense.
For many problems it is critical that a good initial estimate be found for the arguments p or the iteration will not converge or may even break down with an error exit. There are many mathematical techniques which obtain good initial estimates for p in simple cases but which may fail to produce useful estimates in harder cases. If no such technique is available it is recommended that you try a continuation (homotopy) technique preferably based on a physical argument (e.g., the Reynolds or Prandtl number is often a suitable continuation argument). In a continuation method a sequence of problems is solved, one for each choice of the continuation argument, starting with the problem of interest. At each stage the arguments p calculated at earlier stages are used to compute a good initial estimate for the arguments at the current stage (see Hall and Watt (1976) for more details).

10 Example

This example intends to illustrate the use of the break-point and equation solving facilities of D02SAF. Most of the facilities which are common to D02SAF and D02HBF are illustrated in the example in the specification of D02HBF (which should also be consulted).
The program solves a projectile problem in two media determining the position of change of media, p 3, and the gravity and viscosity in the second medium (p 2 represents gravity and p 4 represents viscosity).

10.1 Program Text

Program Text (d02safe.f90)

10.2 Program Data

Program Data (d02safe.d)

10.3 Program Results

Program Results (d02safe.r)

GnuplotProduced by GNUPLOT 4.6 patchlevel 3 −2 −1 0 1 2 3 4 0 1 2 3 4 5 Solution x Example Program Projectile in Two Media Problem height velocity angle determined interface position gnuplot_plot_1 gnuplot_plot_2 gnuplot_plot_3 gnuplot_plot_4
D02 Chapter Contents
D02 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


D02TGF : NAG Library, Mark 26

D02 Chapter Contents
D02 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

D02TGF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

D02TGF solves a system of linear ordinary differential equations by least squares fitting of a series of Chebyshev polynomials using collocation.

2 Specification

SUBROUTINE D02TGF ( N, M, L, X0, X1, K1, KP, C, LDC, COEFF, BDYC, W, LW, IW, LIW, IFAIL)
INTEGER | N, M(N), L(N), K1, KP, LDC, LW, IW(LIW), LIW, IFAIL
REAL (KIND=nag_wp) | X0, X1, C(LDC,N), W(LW)
EXTERNAL | COEFF, BDYC

3 Description

D02TGF calculates an approximate solution of a linear or linearized system of ordinary differential equations as a Chebyshev series. Suppose there are n differential equations for n variables y 1,y 2,…,yn, over the range x 0,x 1. Let the ith equation be
∑ j=1 mi+1 ∑ k=1 n f kj i x y k j-1 x= ri x
where yk j x=dj yk x d xj . COEFF evaluates the coefficients f kj i x and the right-hand side ri x for each i, 1≤i≤n, at any point x. The boundary conditions may be applied either at the end points or at intermediate points; they are written in the same form as the differential equations, and specified by BDYC. For example the jth boundary condition out of those associated with the ith differential equation takes the form
∑ j=1 li+1 ∑ k=1 n f kj ij x ij yk j-1 x ij=r ij x ij ,
where x ij lies between x 0 and x 1. It is assumed in this routine that certain of the boundary conditions are associated with each differential equation. This is for your convenience; the grouping does not affect the results.
The degree of the polynomial solution must be the same for all variables. You specify the degree required, k 1-1, and the number of collocation points, kp, in the range. The routine sets up a system of linear equations for the Chebyshev coefficients, with n equations for each collocation point and one for each boundary condition. The collocation points are chosen at the extrema of a shifted Chebyshev polynomial of degree kp-1. The boundary conditions are satisfied exactly, and the remaining equations are solved by a least squares method. The result produced is a set of Chebyshev coefficients for the n functions y 1,y 2,…,yn, with the range normalized to -1,1.
E02AKF can be used to evaluate the components of the solution at any point on the range x 0,x 1 (see Section 10 for an example). E02AHF and E02AJF may be used to obtain Chebyshev series representations of derivatives and integrals (respectively) of the components of the solution.

4 References

Picken S M (1970) Algorithms for the solution of differential equations in Chebyshev-series by the selected points method Report Math. 94 National Physical Laboratory

5 Arguments

1:   N – INTEGERInput
On entry: n, the number of differential equations in the system.
Constraint: N≥1.
2:   M N – INTEGER arrayInput
On entry: M i must be set to the highest order derivative occurring in the ith equation, for i=1,2,…,n.
Constraint: M i≥1, for i=1,2,…,n.
3:   L N – INTEGER arrayInput
On entry: L i must be set to the number of boundary conditions associated with the ith equation, for i=1,2,…,n.
Constraint: L i≥0, for i=1,2,…,n.
4:   X0 – REAL (KIND=nag_wp)Input
On entry: the left-hand boundary, x 0.
5:   X1 – REAL (KIND=nag_wp)Input
On entry: the right-hand boundary, x 1.
Constraint: X1>X0.
6:   K1 – INTEGERInput
On entry: the number of coefficients, k 1, to be returned in the Chebyshev series representation of the solution (hence, the degree of the polynomial approximation is K1-1).
Constraint: K1≥1+ max 1≤i≤N M i.
7:   KP – INTEGERInput
On entry: the number of collocation points to be used, kp.
Constraint: N×KP≥N×K1+ ∑ i=1 N L i .
8:   C LDCN – REAL (KIND=nag_wp) arrayOutput
On exit: the kth column of C contains the computed Chebyshev coefficients of the kth component of the solution, yk; that is, the computed solution is:
yk=∑′i=1 k 1 C ik T i-1 x,  1≤k≤n,
where Ti x is the Chebyshev polynomial of the first kind and ∑′ denotes that the first coefficient, C 1 k, is halved.
9:   LDC – INTEGERInput
On entry: the first dimension of the array C as declared in the (sub)program from which D02TGF is called.
Constraint: LDC≥K1.
10:   COEFF – SUBROUTINE, supplied by the user.External Procedure
COEFF defines the system of differential equations (see Section 3). It must evaluate the coefficient functions f kj i x and the right-hand side function ri x of the ith equation at a given point. Only nonzero entries of the array A and RHS need be specifically assigned, since all elements are set to zero by D02TGF before calling COEFF.
The specification of COEFF is:
SUBROUTINE COEFF ( X, I, A, IA, IA1, RHS)
INTEGER | I, IA, IA1
REAL (KIND=nag_wp) | X, A(IA,IA1), RHS
Important: the dimension declaration for A must contain the variable IA, not an integer constant.
1:   X – REAL (KIND=nag_wp)Input
On entry: x, the point at which the functions must be evaluated.
2:   I – INTEGERInput
On entry: the equation for which the coefficients and right-hand side are to be evaluated.
3:   A IAIA1 – REAL (KIND=nag_wp) arrayInput/Output
On entry: all elements of A are set to zero.
On exit: A kj must contain the value f kj i x, for 1≤k≤n, 1≤j≤mi+1.
4:   IA – INTEGERInput
5:   IA1 – INTEGERInput
On entry: the first dimension of the array A and the second dimension of the array A as declared in the (sub)program from which D02TGF is called.
6:   RHS – REAL (KIND=nag_wp)Input/Output
On entry: is set to zero.
On exit: it must contain the value ri x.
COEFF must either be a module subprogram USEd by, or declared as EXTERNAL in, the (sub)program from which D02TGF is called. Arguments denoted as Input must not be changed by this procedure.
11:   BDYC – SUBROUTINE, supplied by the user.External Procedure
BDYC defines the boundary conditions (see Section 3). It must evaluate the coefficient functions f kj ij and right-hand side function r ij in the jth boundary condition associated with the ith equation, at the point x ij at which the boundary condition is applied. Only nonzero entries of the array A and RHS need be specifically assigned, since all elements are set to zero by D02TGF before calling BDYC.
The specification of BDYC is:
SUBROUTINE BDYC ( X, I, J, A, IA, IA1, RHS)
INTEGER | I, J, IA, IA1
REAL (KIND=nag_wp) | X, A(IA,IA1), RHS
Important: the dimension declaration for A must contain the variable IA, not an integer constant.
1:   X – REAL (KIND=nag_wp)Output
On exit: x ij, the value at which the boundary condition is applied.
2:   I – INTEGERInput
On entry: the differential equation with which the condition is associated.
3:   J – INTEGERInput
On entry: the boundary condition for which the coefficients and right-hand side are to be evaluated.
4:   A IAIA1 – REAL (KIND=nag_wp) arrayInput/Output
On entry: all elements of A are set to zero.
On exit: the value f kj ij x ij , for 1≤k≤n, 1≤j≤mi+1.
5:   IA – INTEGERInput
6:   IA1 – INTEGERInput
On entry: the first dimension of the array A and the second dimension of the array A as declared in the (sub)program from which D02TGF is called.
7:   RHS – REAL (KIND=nag_wp)Input/Output
On entry: is set to zero.
On exit: the value r ij x ij .
BDYC must either be a module subprogram USEd by, or declared as EXTERNAL in, the (sub)program from which D02TGF is called. Arguments denoted as Input must not be changed by this procedure.
12:   W LW – REAL (KIND=nag_wp) arrayWorkspace
13:   LW – INTEGERInput
On entry: the dimension of the array W as declared in the (sub)program from which D02TGF is called.
Constraint: LW≥2× N×KP+NL × N×K1+1 + 7×N×K1 , where NL= ∑ i=1 n L i .
14:   IW LIW – INTEGER arrayWorkspace
15:   LIW – INTEGERInput
On entry: the dimension of the array IW as declared in the (sub)program from which D02TGF is called.
Constraint: LIW≥N×K1+1.
16:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, | N<1,
or | M i<1 for some i,
or | L i<0 for some i,
or | X0≥X1,
or | K1<1+M i for some i,
or | N×KP<N×K1+ ∑ i=1 n L i ,
or | LDC<K1.
IFAIL=2
On entry, | LW is too small (see Section 5),
or | LIW<N×K1.
IFAIL=3
Either the boundary conditions are not linearly independent, or the rank of the matrix of equations for the coefficients is less than the number of unknowns. Increasing KP may overcome this latter problem.
IFAIL=4
The least squares routine F04AMF has failed to correct the first approximate solution (see F04AMF). Increasing KP may remove this difficulty.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

Estimates of the accuracy of the solution may be obtained by using the checks described in Section 9. The Chebyshev coefficients are calculated by a stable numerical method.

8 Parallelism and Performance

D02TGF makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The time taken by D02TGF depends on the complexity of the system of differential equations, the degree of the polynomial solution and the number of matching points.
If the number of matching points kp is equal to the number of coefficients k 1 minus the average number of boundary conditions 1 n ∑ i=1 n li , then the least squares solution reduces to simple solution of linear equations and true collocation results. The accuracy of the solution may be checked by repeating the calculation with different values of k 1. If the Chebyshev coefficients decrease rapidly, the size of the last two or three gives an indication of the error. If they do not decrease rapidly, it may be desirable to use a different method. Note that the Chebyshev coefficients are calculated for the range normalized to -1,1.
Generally the number of boundary conditions required is equal to the sum of the orders of the n differential equations. However, in some cases fewer boundary conditions are needed, because the assumption of a polynomial solution is equivalent to one or more boundary conditions (since it excludes singular solutions).
A system of nonlinear differential equations must be linearized before using the routine. The calculation is repeated iteratively. On each iteration the linearized equation is used. In the example in Section 10, the y variables are to be determined at the current iteration whilst the z variables correspond to the solution determined at the previous iteration, (or the initial approximation on the first iteration). For a starting approximation, we may take, say, a linear function, and set up the appropriate Chebyshev coefficients before starting the iteration. For example, if y 1=ax+b in the range x 0,x 1, we set B, the array of coefficients,
  • B 1,1=a×x 0+x 1+2×b,
  • B 1,2=a×x 1-x 0/2,
  • and the remainder of the entries to zero.
In some cases a better initial approximation may be needed and can be obtained by using E02ADF or E02AFF to obtain a Chebyshev series for an approximate solution. The coefficients of the current iterate must be communicated to COEFF and BDYC, e.g., in COMMON. (See Section 10.) The convergence of the (Newton) iteration cannot be guaranteed in general, though it is usually satisfactory from a good starting approximation.

10 Example

This example solves the nonlinear system
2 y 1′+y 22-1 y 1+y 2=0, 2 y 2′′-y 1′=0,
in the range -1,1, with y 1=0, y 2=3, y 2′=0 at x=-1.
Suppose an approximate solution is z 1, z 2 such that y 1∼z 1, y 2∼z 2: then the first equation gives, on linearizing,
2 y 1′+z 22-1 y 1+2 z 1z 2+1 y 2=2 z 1 z 22.
The starting approximation is taken to be z 1=0, z 2=3. In the program below, the array B is used to hold the coefficients of the previous iterate (or of the starting approximation). We iterate until the Chebyshev coefficients converge to five figures. E02AKF is used to calculate the solution from its Chebyshev coefficients.

10.1 Program Text

Program Text (d02tgfe.f90)

10.2 Program Data

Program Data (d02tgfe.d)

10.3 Program Results

Program Results (d02tgfe.r)

GnuplotProduced by GNUPLOT 4.6 patchlevel 3 −0.5 −0.4 −0.3 −0.2 −0.1 0 0.1 −1 −0.5 0 0.5 1 2.6 2.7 2.8 2.9 3 3.1 3.2 y1 y2 x Example Program Solution of Linearised System by Chebyshev Collocation y1 y2 gnuplot_plot_1 gnuplot_plot_2
D02 Chapter Contents
D02 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


D02TKF : NAG Library, Mark 26

D02 Chapter Contents
D02 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

D02TKF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

D02TKF solves a general two-point boundary value problem for a nonlinear mixed order system of ordinary differential equations.

2 Specification

SUBROUTINE D02TKF ( FFUN, FJAC, GAFUN, GBFUN, GAJAC, GBJAC, GUESS, RCOMM, ICOMM, IFAIL)
INTEGER | ICOMM(*), IFAIL
REAL (KIND=nag_wp) | RCOMM(*)
EXTERNAL | FFUN, FJAC, GAFUN, GBFUN, GAJAC, GBJAC, GUESS

3 Description

D02TKF and its associated routines (D02TVF, D02TXF, D02TYF and D02TZF) solve the two-point boundary value problem for a nonlinear mixed order system of ordinary differential equations
y 1 m 1 x = f 1 x,y 1,y 1 1,…,y 1 m 1-1,y 2,…,yn mn-1 y 2 m 2 x = f 2 x,y 1,y 1 1,…,y 1 m 1-1,y 2,…,yn mn-1 ⋮ yn mn x = fn x,y 1,y 1 1,…,y 1 m 1-1,y 2,…,yn mn-1
over an interval a,b subject to p (>0) nonlinear boundary conditions at a and q (>0) nonlinear boundary conditions at b, where p+q = ∑ i=1 n mi . Note that yi m x is the mth derivative of the ith solution component. Hence yi 0 x=yi x. The left boundary conditions at a are defined as
gi z y a=0,  i=1,2,…,p,
and the right boundary conditions at b as
g-j z y b=0,  j=1,2,…,q,
where y=y 1,y 2,…,yn and
z y x = y 1 x, y 1 1 x ,…, y 1 m 1-1 x ,y 2 x,…, yn mn-1 x .
First, D02TVF must be called to specify the initial mesh, error requirements and other details. Note that the error requirements apply only to the solution components y 1,y 2,…,yn and that no error control is applied to derivatives of solution components. (If error control is required on derivatives then the system must be reduced in order by introducing the derivatives whose error is to be controlled as new variables. See Section 9 in D02TVF.) Then, D02TKF can be used to solve the boundary value problem. After successful computation, D02TZF can be used to ascertain details about the final mesh and other details of the solution procedure, and D02TYF can be used to compute the approximate solution anywhere on the interval a,b.
A description of the numerical technique used in D02TKF is given in Section 3 in D02TVF.
D02TKF can also be used in the solution of a series of problems, for example in performing continuation, when the mesh used to compute the solution of one problem is to be used as the initial mesh for the solution of the next related problem. D02TXF should be used in between calls to D02TKF in this context.
See Section 9 in D02TVF for details of how to solve boundary value problems of a more general nature.
The routines are based on modified versions of the codes COLSYS and COLNEW (see Ascher et al. (1979) and Ascher and Bader (1987)). A comprehensive treatment of the numerical solution of boundary value problems can be found in Ascher et al. (1988) and Keller (1992).

4 References

Ascher U M and Bader G (1987) A new basis implementation for a mixed order boundary value ODE solver SIAM J. Sci. Stat. Comput. 8 483–500
Ascher U M, Christiansen J and Russell R D (1979) A collocation solver for mixed order systems of boundary value problems Math. Comput. 33 659–679
Ascher U M, Mattheij R M M and Russell R D (1988) Numerical Solution of Boundary Value Problems for Ordinary Differential Equations Prentice–Hall
Keller H B (1992) Numerical Methods for Two-point Boundary-value Problems Dover, New York

5 Arguments

1:   FFUN – SUBROUTINE, supplied by the user.External Procedure
FFUN must evaluate the functions fi for given values x,z y x.
The specification of FFUN is:
SUBROUTINE FFUN ( X, Y, NEQ, M, F)
INTEGER | NEQ, M(NEQ)
REAL (KIND=nag_wp) | X, Y(NEQ,*), F(NEQ)
1:   X – REAL (KIND=nag_wp)Input
On entry: x, the independent variable.
2:   Y NEQ* – REAL (KIND=nag_wp) arrayInput
On entry: Y ij contains yi j x, for i=1,2,…,NEQ and j=0,1,…,M i-1.
Note: yi 0 x=yi x.
3:   NEQ – INTEGERInput
On entry: the number of differential equations.
4:   M NEQ – INTEGER arrayInput
On entry: M i contains mi, the order of the ith differential equation, for i=1,2,…,NEQ.
5:   F NEQ – REAL (KIND=nag_wp) arrayOutput
On exit: F i must contain fi, for i=1,2,…,NEQ.
FFUN must either be a module subprogram USEd by, or declared as EXTERNAL in, the (sub)program from which D02TKF is called. Arguments denoted as Input must not be changed by this procedure.
2:   FJAC – SUBROUTINE, supplied by the user.External Procedure
FJAC must evaluate the partial derivatives of fi with respect to the elements of
z y x=y 1 x,y 11 x,…,y 1 m 1-1 x,y 2 x,…,yn mn-1 x.
The specification of FJAC is:
SUBROUTINE FJAC ( X, Y, NEQ, M, DFDY)
INTEGER | NEQ, M(NEQ)
REAL (KIND=nag_wp) | X, Y(NEQ,*), DFDY(NEQ,NEQ,*)
1:   X – REAL (KIND=nag_wp)Input
On entry: x, the independent variable.
2:   Y NEQ* – REAL (KIND=nag_wp) arrayInput
On entry: Y ij contains yi j x, for i=1,2,…,NEQ and j=0,1,…,M i-1.
Note: yi 0 x=yi x.
3:   NEQ – INTEGERInput
On entry: the number of differential equations.
4:   M NEQ – INTEGER arrayInput
On entry: M i contains mi, the order of the ith differential equation, for i=1,2,…,NEQ.
5:   DFDY NEQNEQ* – REAL (KIND=nag_wp) arrayOutput
On exit: DFDY ijk must contain the partial derivative of fi with respect to yj k , for i=1,2,…,NEQ, j=1,2,…,NEQ and k=0,1,…,M j-1. Only nonzero partial derivatives need be set.
FJAC must either be a module subprogram USEd by, or declared as EXTERNAL in, the (sub)program from which D02TKF is called. Arguments denoted as Input must not be changed by this procedure.
3:   GAFUN – SUBROUTINE, supplied by the user.External Procedure
GAFUN must evaluate the boundary conditions at the left-hand end of the range, that is functions gi z y a for given values of z y a.
The specification of GAFUN is:
SUBROUTINE GAFUN ( YA, NEQ, M, NLBC, GA)
INTEGER | NEQ, M(NEQ), NLBC
REAL (KIND=nag_wp) | YA(NEQ,*), GA(NLBC)
1:   YA NEQ* – REAL (KIND=nag_wp) arrayInput
On entry: YA ij contains yi j a, for i=1,2,…,NEQ and j=0,1,…,M i-1.
Note: yi 0 a=yi a.
2:   NEQ – INTEGERInput
On entry: the number of differential equations.
3:   M NEQ – INTEGER arrayInput
On entry: M i contains mi, the order of the ith differential equation, for i=1,2,…,NEQ.
4:   NLBC – INTEGERInput
On entry: the number of boundary conditions at a.
5:   GA NLBC – REAL (KIND=nag_wp) arrayOutput
On exit: GA i must contain gi z y a, for i=1,2,…,NLBC.
GAFUN must either be a module subprogram USEd by, or declared as EXTERNAL in, the (sub)program from which D02TKF is called. Arguments denoted as Input must not be changed by this procedure.
4:   GBFUN – SUBROUTINE, supplied by the user.External Procedure
GBFUN must evaluate the boundary conditions at the right-hand end of the range, that is functions g-i z y b for given values of z y b.
The specification of GBFUN is:
SUBROUTINE GBFUN ( YB, NEQ, M, NRBC, GB)
INTEGER | NEQ, M(NEQ), NRBC
REAL (KIND=nag_wp) | YB(NEQ,*), GB(NRBC)
1:   YB NEQ* – REAL (KIND=nag_wp) arrayInput
On entry: YB ij contains yi j b, for i=1,2,…,NEQ and j=0,1,…,M i-1.
Note: yi 0 b=yi b.
2:   NEQ – INTEGERInput
On entry: the number of differential equations.
3:   M NEQ – INTEGER arrayInput
On entry: M i contains mi, the order of the ith differential equation, for i=1,2,…,NEQ.
4:   NRBC – INTEGERInput
On entry: the number of boundary conditions at b.
5:   GB NRBC – REAL (KIND=nag_wp) arrayOutput
On exit: GB i must contain g-i z y b, for i=1,2,…,NRBC.
GBFUN must either be a module subprogram USEd by, or declared as EXTERNAL in, the (sub)program from which D02TKF is called. Arguments denoted as Input must not be changed by this procedure.
5:   GAJAC – SUBROUTINE, supplied by the user.External Procedure
GAJAC must evaluate the partial derivatives of gi z y a with respect to the elements of z y a=y 1 a,y 11 a,…,y 1 m 1-1 a,y 2 a,…,yn mn-1 a.
The specification of GAJAC is:
SUBROUTINE GAJAC ( YA, NEQ, M, NLBC, DGADY)
INTEGER | NEQ, M(NEQ), NLBC
REAL (KIND=nag_wp) | YA(NEQ,*), DGADY(NLBC,NEQ,*)
1:   YA NEQ* – REAL (KIND=nag_wp) arrayInput
On entry: YA ij contains yi j a, for i=1,2,…,NEQ and j=0,1,…,M i-1.
Note: yi 0 a=yi a.
2:   NEQ – INTEGERInput
On entry: the number of differential equations.
3:   M NEQ – INTEGER arrayInput
On entry: M i contains mi, the order of the ith differential equation, for i=1,2,…,NEQ.
4:   NLBC – INTEGERInput
On entry: the number of boundary conditions at a.
5:   DGADY NLBCNEQ* – REAL (KIND=nag_wp) arrayOutput
On exit: DGADY ijk must contain the partial derivative of gi z y a with respect to yj k a, for i=1,2,…,NLBC, j=1,2,…,NEQ and k=0,1,…,M j-1. Only nonzero partial derivatives need be set.
GAJAC must either be a module subprogram USEd by, or declared as EXTERNAL in, the (sub)program from which D02TKF is called. Arguments denoted as Input must not be changed by this procedure.
6:   GBJAC – SUBROUTINE, supplied by the user.External Procedure
GBJAC must evaluate the partial derivatives of g-i z y b with respect to the elements of z y b=y 1 b,y 11 b,…,y 1 m 1-1 b,y 2 b,…,yn mn-1 b.
The specification of GBJAC is:
SUBROUTINE GBJAC ( YB, NEQ, M, NRBC, DGBDY)
INTEGER | NEQ, M(NEQ), NRBC
REAL (KIND=nag_wp) | YB(NEQ,*), DGBDY(NRBC,NEQ,*)
1:   YB NEQ* – REAL (KIND=nag_wp) arrayInput
On entry: YB ij contains yi j b, for i=1,2,…,NEQ and j=0,1,…,M i-1.
Note: yi 0 b=yi b.
2:   NEQ – INTEGERInput
On entry: the number of differential equations.
3:   M NEQ – INTEGER arrayInput
On entry: M i contains mi, the order of the ith differential equation, for i=1,2,…,NEQ.
4:   NRBC – INTEGERInput
On entry: the number of boundary conditions at b.
5:   DGBDY NRBCNEQ* – REAL (KIND=nag_wp) arrayOutput
On exit: DGBDY ijk must contain the partial derivative of g-i z y b with respect to yj k b, for i=1,2,…,NRBC, j=1,2,…,NEQ and k=0,1,…,M j-1. Only nonzero partial derivatives need be set.
GBJAC must either be a module subprogram USEd by, or declared as EXTERNAL in, the (sub)program from which D02TKF is called. Arguments denoted as Input must not be changed by this procedure.
7:   GUESS – SUBROUTINE, supplied by the user.External Procedure
GUESS must return initial approximations for the solution components yi j and the derivatives yi mi , for i=1,2,…,NEQ and j=0,1,…,M i-1. Try to compute each derivative yi mi such that it corresponds to your approximations to y i j , for j=0,1,…,M i-1. You should not call FFUN to compute yi mi .
If D02TKF is being used in conjunction with D02TXF as part of a continuation process, then GUESS is not called by D02TKF after the call to D02TXF.
The specification of GUESS is:
SUBROUTINE GUESS ( X, NEQ, M, Y, DYM)
INTEGER | NEQ, M(NEQ)
REAL (KIND=nag_wp) | X, Y(NEQ,*), DYM(NEQ)
1:   X – REAL (KIND=nag_wp)Input
On entry: x, the independent variable; x∈a,b.
2:   NEQ – INTEGERInput
On entry: the number of differential equations.
3:   M NEQ – INTEGER arrayInput
On entry: M i contains mi, the order of the ith differential equation, for i=1,2,…,NEQ.
4:   Y NEQ* – REAL (KIND=nag_wp) arrayOutput
On exit: Y ij must contain yi j x, for i=1,2,…,NEQ and j=0,1,…,M i-1.
Note: yi 0 x=yi x.
5:   DYM NEQ – REAL (KIND=nag_wp) arrayOutput
On exit: DYM i must contain yi mi x, for i=1,2,…,NEQ.
GUESS must either be a module subprogram USEd by, or declared as EXTERNAL in, the (sub)program from which D02TKF is called. Arguments denoted as Input must not be changed by this procedure.
8:   RCOMM* – REAL (KIND=nag_wp) arrayCommunication Array
On entry: this must be the same array as supplied to D02TVF and must remain unchanged between calls.
On exit: contains information about the solution for use on subsequent calls to associated routines.
9:   ICOMM* – INTEGER arrayCommunication Array
On entry: this must be the same array as supplied to D02TVF and must remain unchanged between calls.
On exit: contains information about the solution for use on subsequent calls to associated routines.
10:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, because for this routine the values of the output arguments may be useful even if IFAIL≠0 on exit, the recommended value is -1. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Note: D02TKF may return useful information for one or more of the following detected errors or warnings.
Errors or warnings detected by the routine:
IFAIL=1
On entry, an invalid call was made to D02TKF, for example, without a previous call to the setup routine D02TVF.
IFAIL=2
Numerical singularity has been detected in the Jacobian used in the underlying Newton iteration. No meaningful results have been computed. You should check carefully how you have coded FJAC, GAJAC and GBJAC. If the user-supplied routines have been coded correctly then supplying a different initial approximation to the solution in GUESS might be appropriate. See also Section 9.
IFAIL=3
The nonlinear iteration has failed to converge. At no time during the computation was convergence obtained and no meaningful results have been computed. You should check carefully how you have coded procedures FJAC, GAJAC and GBJAC. If the procedures have been coded correctly then supplying a better initial approximation to the solution in GUESS might be appropriate. See also Section 9.
IFAIL=4
The nonlinear iteration has failed to converge. At some earlier time during the computation convergence was obtained and the corresponding results have been returned for diagnostic purposes and may be inspected by a call to D02TZF. Nothing can be said regarding the suitability of these results for use in any subsequent computation for the same problem. You should try to provide a better mesh and initial approximation to the solution in GUESS. See also Section 9.
IFAIL=5
The expected number of sub-intervals required exceeds the maximum number specified by the argument MXMESH in the setup routine D02TVF. Results for the last mesh on which convergence was obtained have been returned. Nothing can be said regarding the suitability of these results for use in any subsequent computation for the same problem. An indication of the error in the solution on the last mesh where convergence was obtained can be obtained by calling D02TZF. The error requirements may need to be relaxed and/or the maximum number of mesh points may need to be increased. See also Section 9.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

The accuracy of the solution is determined by the argument TOLS in the prior call to D02TVF (see Sections 3 and 9 in D02TVF for details and advice). Note that error control is applied only to solution components (variables) and not to any derivatives of the solution. An estimate of the maximum error in the computed solution is available by calling D02TZF.

8 Parallelism and Performance

D02TKF is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
D02TKF makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

If D02TKF returns with IFAIL=2, 3, 4 or 5 and the call to D02TKF was a part of some continuation procedure for which successful calls to D02TKF have already been made, then it is possible that the adjustment(s) to the continuation argument(s) between calls to D02TKF is (are) too large for the problem under consideration. More conservative adjustment(s) to the continuation argument(s) might be appropriate.

10 Example

The following example is used to illustrate the treatment of a high-order system, control of the error in a derivative of a component of the original system, and the use of continuation. See also D02TVF, D02TXF, D02TYF and D02TZF, for the illustration of other facilities.
Consider the steady flow of an incompressible viscous fluid between two infinite coaxial rotating discs. See Ascher et al. (1979) and the references therein. The governing equations are
1 R f′′′+f f′′′+g g′ = 0 1 R g′′+f g′-f′g = 0
subject to the boundary conditions
f 0=f′0= 0,   g 0=Ω 0,   f 1=f′1= 0,   g 1=Ω 1,
where R is the Reynolds number and Ω 0,Ω 1 are the angular velocities of the disks.
We consider the case of counter-rotation and a symmetric solution, that is Ω 0=1, Ω 1=-1. This problem is more difficult to solve, the larger the value of R. For illustration, we use simple continuation to compute the solution for three different values of R (=106,108,1010). However, this problem can be addressed directly for the largest value of R considered here. Instead of the values suggested in Section 5 in D02TXF for NMESH, IPMESH and MESH in the call to D02TXF prior to a continuation call, we use every point of the final mesh for the solution of the first value of R, that is we must modify the contents of IPMESH. For illustrative purposes we wish to control the computed error in f′ and so recast the equations as
y 1′ = y 2 y 2′′′ = -R y 1 y 2′′+y 3 y 3′ y 3′′ = R y 2y 3-y 1 y 3′
subject to the boundary conditions
y 1 0=y 2 0= 0,   y 3 0=Ω,   y 1 1=y 2 1= 0,   y 3 1=-Ω,   Ω=1.
For the symmetric boundary conditions considered, there exists an odd solution about x=0.5. Hence, to satisfy the boundary conditions, we use the following initial approximations to the solution in GUESS:
y 1 x = -x 2 x-12 x-1 2 y 2 x = -x x-15⁢x 2-5 x+1 y 3 x = -8 Ω x-12 3.

10.1 Program Text

Program Text (d02tkfe.f90)

10.2 Program Data

Program Data (d02tkfe.d)

10.3 Program Results

Program Results (d02tkfe.r)

GnuplotProduced by GNUPLOT 4.6 patchlevel 3 −0.1 −0.05 0 0.05 0.1 0.15 0.2 0 0.2 0.4 0.6 0.8 1 −1 −0.5 0 0.5 1 f and f' g X Example Program Incompressible Fluid Flow between Coaxial Rotating Discs Solutions for Reynold's Number 1,000,000 f f' g gnuplot_plot_1 gnuplot_plot_2 gnuplot_plot_3
GnuplotProduced by GNUPLOT 4.6 patchlevel 3 −0.02 0 0.02 0.04 0.06 0.08 0.1 0.12 0.14 0.16 0.18 0 0.2 0.4 0.6 0.8 1 −1 −0.5 0 0.5 1 f and f' g X Incompressible Fluid Flow between Coaxial Rotating Discs Solutions for Reynold's Number 100,000,000 f f' g gnuplot_plot_1 gnuplot_plot_2 gnuplot_plot_3
GnuplotProduced by GNUPLOT 4.6 patchlevel 3 −0.02 0 0.02 0.04 0.06 0.08 0.1 0.12 0.14 0.16 0.18 0 0.2 0.4 0.6 0.8 1 −1 −0.5 0 0.5 1 f and f' g X Incompressible Fluid Flow between Coaxial Rotating Discs Solutions for Reynold's Number 10,000,000,000 f f' g gnuplot_plot_1 gnuplot_plot_2 gnuplot_plot_3
D02 Chapter Contents
D02 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


D02TLF : NAG Library, Mark 26

D02 Chapter Contents

D02 Chapter Introduction

NAG Library Manual

NAG Library Routine Document

D02TLF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose

2 Specification

3 Description

4 References

5 Arguments

6 Error Indicators and Warnings

7 Accuracy

8 Parallelism and Performance

9 Further Comments

▸▿ 10 Example

10.1 Program Text

10.2 Program Data

10.3 Program Results

1 Purpose

D02TLF solves a general two-point boundary value problem for a nonlinear mixed order system of ordinary differential equations.

2 Specification

SUBROUTINE D02TLF (

FFUN, FJAC, GAFUN, GBFUN, GAJAC, GBJAC, GUESS, RCOMM, ICOMM, IUSER, RUSER, IFAIL)

INTEGER

ICOMM(*), IUSER(*), IFAIL

REAL (KIND=nag_wp)

RCOMM(*), RUSER(*)

EXTERNAL

FFUN, FJAC, GAFUN, GBFUN, GAJAC, GBJAC, GUESS

3 Description

D02TLF and its associated routines (D02TVF, D02TXF, D02TYF and D02TZF) solve the two-point boundary value problem for a nonlinear mixed order system of ordinary differential equations

y 1 m 1 x = f 1 x,y 1,y 1 1,…,y 1 m 1-1,y 2,…,yn mn-1 y 2 m 2 x = f 2 x,y 1,y 1 1,…,y 1 m 1-1,y 2,…,yn mn-1 ⋮ yn mn x = fn x,y 1,y 1 1,…,y 1 m 1-1,y 2,…,yn mn-1

over an interval a,b subject to p (>0) nonlinear boundary conditions at a and q (>0) nonlinear boundary conditions at b, where p+q = ∑ i=1 n mi . Note that yi m x is the mth derivative of the ith solution component. Hence yi 0 x=yi x. The left boundary conditions at a are defined as

gi z y a=0,  i=1,2,…,p,

and the right boundary conditions at b as

g-j z y b=0,  j=1,2,…,q,

where y=y 1,y 2,…,yn and

z y x = y 1 x, y 1 1 x ,…, y 1 m 1-1 x ,y 2 x,…, yn mn-1 x .

First, D02TVF must be called to specify the initial mesh, error requirements and other details. Note that the error requirements apply only to the solution components y 1,y 2,…,yn and that no error control is applied to derivatives of solution components. (If error control is required on derivatives then the system must be reduced in order by introducing the derivatives whose error is to be controlled as new variables. See Section 9 in D02TVF.) Then, D02TLF can be used to solve the boundary value problem. After successful computation, D02TZF can be used to ascertain details about the final mesh and other details of the solution procedure, and D02TYF can be used to compute the approximate solution anywhere on the interval a,b.

A description of the numerical technique used in D02TLF is given in Section 3 in D02TVF.

D02TLF can also be used in the solution of a series of problems, for example in performing continuation, when the mesh used to compute the solution of one problem is to be used as the initial mesh for the solution of the next related problem. D02TXF should be used in between calls to D02TLF in this context.

See Section 9 in D02TVF for details of how to solve boundary value problems of a more general nature.

The routines are based on modified versions of the codes COLSYS and COLNEW (see Ascher et al. (1979) and Ascher and Bader (1987)). A comprehensive treatment of the numerical solution of boundary value problems can be found in Ascher et al. (1988) and Keller (1992).

4 References

Ascher U M and Bader G (1987) A new basis implementation for a mixed order boundary value ODE solver SIAM J. Sci. Stat. Comput. 8 483–500

Ascher U M, Christiansen J and Russell R D (1979) A collocation solver for mixed order systems of boundary value problems Math. Comput. 33 659–679

Ascher U M, Mattheij R M M and Russell R D (1988) Numerical Solution of Boundary Value Problems for Ordinary Differential Equations Prentice–Hall

Keller H B (1992) Numerical Methods for Two-point Boundary-value Problems Dover, New York

5 Arguments

1:   FFUN – SUBROUTINE, supplied by the user.External Procedure

FFUN must evaluate the functions fi for given values x,z y x.

The specification of FFUN is:

SUBROUTINE FFUN (

X, Y, NEQ, M, F, IUSER, RUSER)

INTEGER

NEQ, M(NEQ), IUSER(*)

REAL (KIND=nag_wp)

X, Y(NEQ,0:*), F(NEQ), RUSER(*)

1:   X – REAL (KIND=nag_wp)Input

On entry: x, the independent variable.

2:   Y NEQ 0:* – REAL (KIND=nag_wp) arrayInput

On entry: Y ij contains yi j x, for i=1,2,…,NEQ and j=0,1,…,M i-1.
Note: yi 0 x=yi x.

3:   NEQ – INTEGERInput

On entry: the number of differential equations.

4:   M NEQ – INTEGER arrayInput

On entry: M i contains mi, the order of the ith differential equation, for i=1,2,…,NEQ.

5:   F NEQ – REAL (KIND=nag_wp) arrayOutput

On exit: F i must contain fi, for i=1,2,…,NEQ.

6:   IUSER* – INTEGER arrayUser Workspace

7:   RUSER* – REAL (KIND=nag_wp) arrayUser Workspace

FFUN is called with the arguments IUSER and RUSER as supplied to D02TLF. You are free to use the arrays IUSER and RUSER to supply information to FFUN as an alternative to using COMMON global variables.

FFUN must either be a module subprogram USEd by, or declared as EXTERNAL in, the (sub)program from which D02TLF is called. Arguments denoted as Input must not be changed by this procedure.

2:   FJAC – SUBROUTINE, supplied by the user.External Procedure

FJAC must evaluate the partial derivatives of fi with respect to the elements of
z y x=y 1 x,y 11 x,…,y 1 m 1-1 x,y 2 x,…,yn mn-1 x.

The specification of FJAC is:

SUBROUTINE FJAC (

X, Y, NEQ, M, DFDY, IUSER, RUSER)

INTEGER

NEQ, M(NEQ), IUSER(*)

REAL (KIND=nag_wp)

X, Y(NEQ,0:*), DFDY(NEQ,NEQ,0:*), RUSER(*)

1:   X – REAL (KIND=nag_wp)Input

On entry: x, the independent variable.

2:   Y NEQ 0:* – REAL (KIND=nag_wp) arrayInput

On entry: Y ij contains yi j x, for i=1,2,…,NEQ and j=0,1,…,M i-1.
Note: yi 0 x=yi x.

3:   NEQ – INTEGERInput

On entry: the number of differential equations.

4:   M NEQ – INTEGER arrayInput

On entry: M i contains mi, the order of the ith differential equation, for i=1,2,…,NEQ.

5:   DFDY NEQNEQ 0:* – REAL (KIND=nag_wp) arrayInput/Output

On entry: set to zero.

On exit: DFDY ijk must contain the partial derivative of fi with respect to yj k , for i=1,2,…,NEQ, j=1,2,…,NEQ and k=0,1,…,M j-1. Only nonzero partial derivatives need be set.

6:   IUSER* – INTEGER arrayUser Workspace

7:   RUSER* – REAL (KIND=nag_wp) arrayUser Workspace

FJAC is called with the arguments IUSER and RUSER as supplied to D02TLF. You are free to use the arrays IUSER and RUSER to supply information to FJAC as an alternative to using COMMON global variables.

FJAC must either be a module subprogram USEd by, or declared as EXTERNAL in, the (sub)program from which D02TLF is called. Arguments denoted as Input must not be changed by this procedure.

3:   GAFUN – SUBROUTINE, supplied by the user.External Procedure

GAFUN must evaluate the boundary conditions at the left-hand end of the range, that is functions gi z y a for given values of z y a.

The specification of GAFUN is:

SUBROUTINE GAFUN (

YA, NEQ, M, NLBC, GA, IUSER, RUSER)

INTEGER

NEQ, M(NEQ), NLBC, IUSER(*)

REAL (KIND=nag_wp)

YA(NEQ,0:*), GA(NLBC), RUSER(*)

1:   YA NEQ 0:* – REAL (KIND=nag_wp) arrayInput

On entry: YA ij contains yi j a, for i=1,2,…,NEQ and j=0,1,…,M i-1.
Note: yi 0 a=yi a.

2:   NEQ – INTEGERInput

On entry: the number of differential equations.

3:   M NEQ – INTEGER arrayInput

On entry: M i contains mi, the order of the ith differential equation, for i=1,2,…,NEQ.

4:   NLBC – INTEGERInput

On entry: the number of boundary conditions at a.

5:   GA NLBC – REAL (KIND=nag_wp) arrayOutput

On exit: GA i must contain gi z y a, for i=1,2,…,NLBC.

6:   IUSER* – INTEGER arrayUser Workspace

7:   RUSER* – REAL (KIND=nag_wp) arrayUser Workspace

GAFUN is called with the arguments IUSER and RUSER as supplied to D02TLF. You are free to use the arrays IUSER and RUSER to supply information to GAFUN as an alternative to using COMMON global variables.

GAFUN must either be a module subprogram USEd by, or declared as EXTERNAL in, the (sub)program from which D02TLF is called. Arguments denoted as Input must not be changed by this procedure.

4:   GBFUN – SUBROUTINE, supplied by the user.External Procedure

GBFUN must evaluate the boundary conditions at the right-hand end of the range, that is functions g-i z y b for given values of z y b.

The specification of GBFUN is:

SUBROUTINE GBFUN (

YB, NEQ, M, NRBC, GB, IUSER, RUSER)

INTEGER

NEQ, M(NEQ), NRBC, IUSER(*)

REAL (KIND=nag_wp)

YB(NEQ,0:*), GB(NRBC), RUSER(*)

1:   YB NEQ 0:* – REAL (KIND=nag_wp) arrayInput

On entry: YB ij contains yi j b, for i=1,2,…,NEQ and j=0,1,…,M i-1.
Note: yi 0 b=yi b.

2:   NEQ – INTEGERInput

On entry: the number of differential equations.

3:   M NEQ – INTEGER arrayInput

On entry: M i contains mi, the order of the ith differential equation, for i=1,2,…,NEQ.

4:   NRBC – INTEGERInput

On entry: the number of boundary conditions at b.

5:   GB NRBC – REAL (KIND=nag_wp) arrayOutput

On exit: GB i must contain g-i z y b, for i=1,2,…,NRBC.

6:   IUSER* – INTEGER arrayUser Workspace

7:   RUSER* – REAL (KIND=nag_wp) arrayUser Workspace

GBFUN is called with the arguments IUSER and RUSER as supplied to D02TLF. You are free to use the arrays IUSER and RUSER to supply information to GBFUN as an alternative to using COMMON global variables.

GBFUN must either be a module subprogram USEd by, or declared as EXTERNAL in, the (sub)program from which D02TLF is called. Arguments denoted as Input must not be changed by this procedure.

5:   GAJAC – SUBROUTINE, supplied by the user.External Procedure

GAJAC must evaluate the partial derivatives of gi z y a with respect to the elements of z y a=y 1 a,y 11 a,…,y 1 m 1-1 a,y 2 a,…,yn mn-1 a.

The specification of GAJAC is:

SUBROUTINE GAJAC (

YA, NEQ, M, NLBC, DGADY, IUSER, RUSER)

INTEGER

NEQ, M(NEQ), NLBC, IUSER(*)

REAL (KIND=nag_wp)

YA(NEQ,0:*), DGADY(NLBC,NEQ,0:*), RUSER(*)

1:   YA NEQ 0:* – REAL (KIND=nag_wp) arrayInput

On entry: YA ij contains yi j a, for i=1,2,…,NEQ and j=0,1,…,M i-1.
Note: yi 0 a=yi a.

2:   NEQ – INTEGERInput

On entry: the number of differential equations.

3:   M NEQ – INTEGER arrayInput

On entry: M i contains mi, the order of the ith differential equation, for i=1,2,…,NEQ.

4:   NLBC – INTEGERInput

On entry: the number of boundary conditions at a.

5:   DGADY NLBCNEQ 0:* – REAL (KIND=nag_wp) arrayInput/Output

On entry: set to zero.

On exit: DGADY ijk must contain the partial derivative of gi z y a with respect to yj k a, for i=1,2,…,NLBC, j=1,2,…,NEQ and k=0,1,…,M j-1. Only nonzero partial derivatives need be set.

6:   IUSER* – INTEGER arrayUser Workspace

7:   RUSER* – REAL (KIND=nag_wp) arrayUser Workspace

GAJAC is called with the arguments IUSER and RUSER as supplied to D02TLF. You are free to use the arrays IUSER and RUSER to supply information to GAJAC as an alternative to using COMMON global variables.

GAJAC must either be a module subprogram USEd by, or declared as EXTERNAL in, the (sub)program from which D02TLF is called. Arguments denoted as Input must not be changed by this procedure.

6:   GBJAC – SUBROUTINE, supplied by the user.External Procedure

GBJAC must evaluate the partial derivatives of g-i z y b with respect to the elements of z y b=y 1 b,y 11 b,…,y 1 m 1-1 b,y 2 b,…,yn mn-1 b.

The specification of GBJAC is:

SUBROUTINE GBJAC (

YB, NEQ, M, NRBC, DGBDY, IUSER, RUSER)

INTEGER

NEQ, M(NEQ), NRBC, IUSER(*)

REAL (KIND=nag_wp)

YB(NEQ,0:*), DGBDY(NRBC,NEQ,0:*), RUSER(*)

1:   YB NEQ 0:* – REAL (KIND=nag_wp) arrayInput

On entry: YB ij contains yi j b, for i=1,2,…,NEQ and j=0,1,…,M i-1.
Note: yi 0 b=yi b.

2:   NEQ – INTEGERInput

On entry: the number of differential equations.

3:   M NEQ – INTEGER arrayInput

On entry: M i contains mi, the order of the ith differential equation, for i=1,2,…,NEQ.

4:   NRBC – INTEGERInput

On entry: the number of boundary conditions at b.

5:   DGBDY NRBCNEQ 0:* – REAL (KIND=nag_wp) arrayInput/Output

On entry: set to zero.

On exit: DGBDY ijk must contain the partial derivative of g-i z y b with respect to yj k b, for i=1,2,…,NRBC, j=1,2,…,NEQ and k=0,1,…,M j-1. Only nonzero partial derivatives need be set.

6:   IUSER* – INTEGER arrayUser Workspace

7:   RUSER* – REAL (KIND=nag_wp) arrayUser Workspace

GBJAC is called with the arguments IUSER and RUSER as supplied to D02TLF. You are free to use the arrays IUSER and RUSER to supply information to GBJAC as an alternative to using COMMON global variables.

GBJAC must either be a module subprogram USEd by, or declared as EXTERNAL in, the (sub)program from which D02TLF is called. Arguments denoted as Input must not be changed by this procedure.

7:   GUESS – SUBROUTINE, supplied by the user.External Procedure

GUESS must return initial approximations for the solution components yi j and the derivatives yi mi , for i=1,2,…,NEQ and j=0,1,…,M i-1. Try to compute each derivative yi mi such that it corresponds to your approximations to y i j , for j=0,1,…,M i-1. You should not call FFUN to compute yi mi .

If D02TLF is being used in conjunction with D02TXF as part of a continuation process, then GUESS is not called by D02TLF after the call to D02TXF.

The specification of GUESS is:

SUBROUTINE GUESS (

X, NEQ, M, Y, DYM, IUSER, RUSER)

INTEGER

NEQ, M(NEQ), IUSER(*)

REAL (KIND=nag_wp)

X, Y(NEQ,0:*), DYM(NEQ), RUSER(*)

1:   X – REAL (KIND=nag_wp)Input

On entry: x, the independent variable; x∈a,b.

2:   NEQ – INTEGERInput

On entry: the number of differential equations.

3:   M NEQ – INTEGER arrayInput

On entry: M i contains mi, the order of the ith differential equation, for i=1,2,…,NEQ.

4:   Y NEQ 0:* – REAL (KIND=nag_wp) arrayOutput

On exit: Y ij must contain yi j x, for i=1,2,…,NEQ and j=0,1,…,M i-1.
Note: yi 0 x=yi x.

5:   DYM NEQ – REAL (KIND=nag_wp) arrayOutput

On exit: DYM i must contain yi mi x, for i=1,2,…,NEQ.

6:   IUSER* – INTEGER arrayUser Workspace

7:   RUSER* – REAL (KIND=nag_wp) arrayUser Workspace

GUESS is called with the arguments IUSER and RUSER as supplied to D02TLF. You are free to use the arrays IUSER and RUSER to supply information to GUESS as an alternative to using COMMON global variables.

GUESS must either be a module subprogram USEd by, or declared as EXTERNAL in, the (sub)program from which D02TLF is called. Arguments denoted as Input must not be changed by this procedure.

8:   RCOMM* – REAL (KIND=nag_wp) arrayCommunication Array

Note: the dimension of this array is dictated by the requirements of associated functions that must have been previously called. This array must be the same array passed as argument RCOMM in the previous call to D02TVF.

On entry: this must be the same array as supplied to D02TVF and must remain unchanged between calls.

On exit: contains information about the solution for use on subsequent calls to associated routines.

9:   ICOMM* – INTEGER arrayCommunication Array

Note: the dimension of this array is dictated by the requirements of associated functions that must have been previously called. This array must be the same array passed as argument ICOMM in the previous call to D02TVF.

On entry: this must be the same array as supplied to D02TVF and must remain unchanged between calls.

On exit: contains information about the solution for use on subsequent calls to associated routines.

10:   IUSER* – INTEGER arrayUser Workspace

11:   RUSER* – REAL (KIND=nag_wp) arrayUser Workspace

IUSER and RUSER are not used by D02TLF, but are passed directly to FFUN, FJAC, GAFUN, GBFUN, GAJAC, GBJAC and GUESS and may be used to pass information to these routines as an alternative to using COMMON global variables.

12:   IFAIL – INTEGERInput/Output

On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, because for this routine the values of the output arguments may be useful even if IFAIL≠0 on exit, the recommended value is -1. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.

On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).

Note: D02TLF may return useful information for one or more of the following detected errors or warnings.

Errors or warnings detected by the routine:

IFAIL=1

Either the setup routine has not been called or the communication arrays have become corrupted. No solution will be computed.

IFAIL=2

Numerical singularity has been detected in the Jacobian used in the Newton iteration.
No results have been generated. Check the coding of the routines for calculating the Jacobians of system and boundary conditions.

IFAIL=3

All Newton iterations that have been attempted have failed to converge.
No results have been generated. Check the coding of the routines for calculating the Jacobians of system and boundary conditions.
Try to provide a better initial solution approximation.

IFAIL=4

A Newton iteration has failed to converge. The computation has not succeeded but results have been returned for an intermediate mesh on which convergence was achieved.
These results should be treated with extreme caution.

IFAIL=5

The expected number of sub-intervals required to continue the computation exceeds the maximum specified: value.
Results have been generated which may be useful.
Try increasing this number or relaxing the error requirements.

IFAIL=-99

An unexpected error has been triggered by this routine. Please contact NAG.

See Section 3.9 in How to Use the NAG Library and its Documentation for further information.

IFAIL=-399

Your licence key may have expired or may not have been installed correctly.

See Section 3.8 in How to Use the NAG Library and its Documentation for further information.

IFAIL=-999

Dynamic memory allocation failed.

See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

The accuracy of the solution is determined by the argument TOLS in the prior call to D02TVF (see Sections 3 and 9 in D02TVF for details and advice). Note that error control is applied only to solution components (variables) and not to any derivatives of the solution. An estimate of the maximum error in the computed solution is available by calling D02TZF.

8 Parallelism and Performance

D02TLF is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.

D02TLF makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.

Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

If D02TLF returns with IFAIL=2, 3, 4 or 5 and the call to D02TLF was a part of some continuation procedure for which successful calls to D02TLF have already been made, then it is possible that the adjustment(s) to the continuation parameter(s) between calls to D02TLF is (are) too large for the problem under consideration. More conservative adjustment(s) to the continuation parameter(s) might be appropriate.

10 Example

The following example is used to illustrate the treatment of a high-order system, control of the error in a derivative of a component of the original system, and the use of continuation. See also D02TVF, D02TXF, D02TYF and D02TZF, for the illustration of other facilities.

Consider the steady flow of an incompressible viscous fluid between two infinite coaxial rotating discs. See Ascher et al. (1979) and the references therein. The governing equations are

1 R f′′′+f f′′′+g g′ = 0 1 R g′′+f g′-f′g = 0

subject to the boundary conditions

f 0=f′0= 0,   g 0=Ω 0,   f 1=f′1= 0,   g 1=Ω 1,

where R is the Reynolds number and Ω 0,Ω 1 are the angular velocities of the disks.

We consider the case of counter-rotation and a symmetric solution, that is Ω 0=1, Ω 1=-1. This problem is more difficult to solve, the larger the value of R. For illustration, we use simple continuation to compute the solution for three different values of R (=106,108,1010). However, this problem can be addressed directly for the largest value of R considered here. Instead of the values suggested in Section 5 in D02TXF for NMESH, IPMESH and MESH in the call to D02TXF prior to a continuation call, we use every point of the final mesh for the solution of the first value of R, that is we must modify the contents of IPMESH. For illustrative purposes we wish to control the computed error in f′ and so recast the equations as

y 1′ = y 2 y 2′′′ = -R y 1 y 2′′+y 3 y 3′ y 3′′ = R y 2y 3-y 1 y 3′

subject to the boundary conditions

y 1 0=y 2 0= 0,   y 3 0=Ω,   y 1 1=y 2 1= 0,   y 3 1=-Ω,   Ω=1.

For the symmetric boundary conditions considered, there exists an odd solution about x=0.5. Hence, to satisfy the boundary conditions, we use the following initial approximations to the solution in GUESS:

y 1 x = -x 2 x-12 x-1 2 y 2 x = -x x-15⁢x 2-5 x+1 y 3 x = -8 Ω x-12 3.

10.1 Program Text

Program Text (d02tlfe.f90)

10.2 Program Data

Program Data (d02tlfe.d)

10.3 Program Results

Program Results (d02tlfe.r)

D02 Chapter Contents

D02 Chapter Introduction

NAG Library Manual

© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


D02TVF : NAG Library, Mark 26

D02 Chapter Contents
D02 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

D02TVF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
▸▿ 9 Further Comments
9.1 Nonseparated Boundary Conditions
9.2 Multipoint Boundary Value Problems
9.3 High Order Systems
9.4 Fixed Points and Singularities
9.5 Numerical Jacobians
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

D02TVF is a setup routine which must be called prior to the first call of the nonlinear two-point boundary value solver D02TLF.

2 Specification

SUBROUTINE D02TVF ( NEQ, M, NLBC, NRBC, NCOL, TOLS, MXMESH, NMESH, MESH, IPMESH, RCOMM, LRCOMM, ICOMM, LICOMM, IFAIL)
INTEGER | NEQ, M(NEQ), NLBC, NRBC, NCOL, MXMESH, NMESH, IPMESH(MXMESH), LRCOMM, ICOMM(LICOMM), LICOMM, IFAIL
REAL (KIND=nag_wp) | TOLS(NEQ), MESH(MXMESH), RCOMM(LRCOMM)

3 Description

D02TVF and its associated routines (D02TLF, D02TXF, D02TYF and D02TZF) solve the two-point boundary value problem for a nonlinear system of ordinary differential equations
y 1 m 1 x = f 1 x,y 1,y 1 1,…,y 1 m 1-1,y 2,…,yn mn-1 y 2 m 2 x = f 2 x,y 1,y 1 1,…,y 1 m 1-1,y 2,…,yn mn-1 ⋮ yn mn x = fn x,y 1,y 1 1,…,y 1 m 1-1,y 2,…,yn mn-1
over an interval a,b subject to p (>0) nonlinear boundary conditions at a and q (>0) nonlinear boundary conditions at b, where p+q = ∑ i=1 n mi . Note that yi m x is the mth derivative of the ith solution component. Hence yi 0 x=yi x. The left boundary conditions at a are defined as
gi z y a=0,  i=1,2,…,p,
and the right boundary conditions at b as
g-j z y b=0,  j=1,2,…,q,
where y=y 1,y 2,…,yn and
z y x = y 1 x, y 1 1 x ,…, y 1 m 1-1 x ,y 2 x,…, yn mn-1 x .
See Section 9 for information on how boundary value problems of a more general nature can be treated.
D02TVF is used to specify an initial mesh, error requirements and other details. D02TLF is then used to solve the boundary value problem.
The solution routine D02TLF proceeds as follows. A modified Newton method is applied to the equations
yi mi x-fi x,z y x= 0,   i= 1,…,n
and the boundary conditions. To solve these equations numerically the components yi are approximated by piecewise polynomials v ij using a monomial basis on the jth mesh sub-interval. The coefficients of the polynomials v ij form the unknowns to be computed. Collocation is applied at Gaussian points
v ij mi x jk-fi x jk,z v x jk=0,  i=1,2,…,n,
where x jk is the kth collocation point in the jth mesh sub-interval. Continuity at the mesh points is imposed, that is
v ij x j+1-v i,j+1 x j+1=0,  i=1,2,…,n,
where x j+1 is the right-hand end of the jth mesh sub-interval. The linearized collocation equations and boundary conditions, together with the continuity conditions, form a system of linear algebraic equations, an almost block diagonal system which is solved using special linear solvers. To start the modified Newton process, an approximation to the solution on the initial mesh must be supplied via the procedure argument GUESS of D02TLF.
The solver attempts to satisfy the conditions
yi-vi 1.0+vi ≤TOLS i,  i=1,2,…,n, (1)
where vi is the approximate solution for the ith solution component and TOLS is supplied by you. The mesh is refined by trying to equidistribute the estimated error in the computed solution over all mesh sub-intervals, and an extrapolation-like test (doubling the number of mesh sub-intervals) is used to check for (1).
The routines are based on modified versions of the codes COLSYS and COLNEW (see Ascher et al. (1979) and Ascher and Bader (1987)). A comprehensive treatment of the numerical solution of boundary value problems can be found in Ascher et al. (1988) and Keller (1992).

4 References

Ascher U M and Bader G (1987) A new basis implementation for a mixed order boundary value ODE solver SIAM J. Sci. Stat. Comput. 8 483–500
Ascher U M, Christiansen J and Russell R D (1979) A collocation solver for mixed order systems of boundary value problems Math. Comput. 33 659–679
Ascher U M, Mattheij R M M and Russell R D (1988) Numerical Solution of Boundary Value Problems for Ordinary Differential Equations Prentice–Hall
Gill P E, Murray W and Wright M H (1981) Practical Optimization Academic Press
Keller H B (1992) Numerical Methods for Two-point Boundary-value Problems Dover, New York
Schwartz I B (1983) Estimating regions of existence of unstable periodic orbits using computer-based techniques SIAM J. Sci. Statist. Comput. 20(1) 106–120

5 Arguments

1:   NEQ – INTEGERInput
On entry: n, the number of ordinary differential equations to be solved.
Constraint: NEQ≥1.
2:   M NEQ – INTEGER arrayInput
On entry: M i must contain mi, the order of the ith differential equation, for i=1,2,…,n.
Constraint: 1≤M i≤4, for i=1,2,…,n.
3:   NLBC – INTEGERInput
On entry: p, the number of left boundary conditions defined at the left-hand end, a (=MESH 1).
Constraint: NLBC≥1.
4:   NRBC – INTEGERInput
On entry: q, the number of right boundary conditions defined at the right-hand end, b (=MESH NMESH).
Constraints:
  • NRBC≥1;
  • NLBC+NRBC=∑i=1 n M i.
5:   NCOL – INTEGERInput
On entry: the number of collocation points to be used in each mesh sub-interval.
Constraint: mmax≤NCOL≤7, where mmax=max M i.
6:   TOLS NEQ – REAL (KIND=nag_wp) arrayInput
On entry: TOLS i must contain the error requirement for the ith solution component.
Constraint: 100×machine precision<TOLS i<1.0, for i=1,2,…,n.
7:   MXMESH – INTEGERInput
On entry: the maximum number of mesh points to be used during the solution process.
Constraint: MXMESH≥2×NMESH-1.
8:   NMESH – INTEGERInput
On entry: the number of points to be used in the initial mesh of the solution process.
Constraint: NMESH≥6.
9:   MESH MXMESH – REAL (KIND=nag_wp) arrayInput
On entry: the positions of the initial NMESH mesh points. The remaining elements of MESH need not be set. You should try to place the mesh points in areas where you expect the solution to vary most rapidly. In the absence of any other information the points should be equally distributed on a,b.
MESH 1 must contain the left boundary point, a, and MESH NMESH must contain the right boundary point, b.
Constraint: MESH i<MESH i+1, for i=1,2,…,NMESH-1.
10:   IPMESH MXMESH – INTEGER arrayInput
On entry: IPMESH i specifies whether or not the initial mesh point defined in MESH i, for i=1,2,…,NMESH, should be a fixed point in all meshes computed during the solution process. The remaining elements of IPMESH need not be set.
IPMESH i=1
Indicates that MESH i should be a fixed point in all meshes.
IPMESH i=2
Indicates that MESH i is not a fixed point.
Constraints:
  • IPMESH 1=1 and IPMESH NMESH=1, (i.e., the left and right boundary points, a and b, must be fixed points, in all meshes);
  • IPMESH i=1 or 2, for i=2,3,…,NMESH-1.
11:   RCOMM LRCOMM – REAL (KIND=nag_wp) arrayCommunication Array
On exit: contains information for use by D02TLF. This must be the same array as will be supplied to D02TLF. The contents of this array must remain unchanged between calls.
12:   LRCOMM – INTEGERInput
On entry: the dimension of the array RCOMM as declared in the (sub)program from which D02TVF is called. If LRCOMM=0, a communication array size query is requested. In this case there is an immediate return with communication array dimensions stored in ICOMM; ICOMM 1 contains the required dimension of RCOMM, while ICOMM 2 contains the required dimension of ICOMM.
Constraint: LRCOMM=0, or LRCOMM≥51+NEQ+MXMESH×2+m*+kn-kn+MXMESH/2, where m*=∑i=1 n M i and kn=NCOL×NEQ.
13:   ICOMM LICOMM – INTEGER arrayCommunication Array
On exit: contains information for use by D02TLF. This must be the same array as will be supplied to D02TLF. The contents of this array must remain unchanged between calls. If LRCOMM=0, a communication array size query is requested. In this case, on immediate return, ICOMM 1 will contain the required dimension for RCOMM while ICOMM 2 will contain the required dimension for ICOMM.
14:   LICOMM – INTEGERInput
On entry: the dimension of the array ICOMM as declared in the (sub)program from which D02TVF is called. If LRCOMM=0, a communication array size query is requested. In this case ICOMM need only be of dimension 2 in order to hold the required communication array dimensions for the given problem and algorithmic parameters.
Constraints:
  • if LRCOMM=0, LICOMM≥2;
  • otherwise LICOMM≥23+NEQ+MXMESH.
15:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, IPMESH 1 or IPMESH NMESH does not equal 1.
On entry, IPMESH i≠1 or 2 for some i.
On entry, LICOMM=value.
Constraint: LICOMM≥value.
On entry, LRCOMM=value.
Constraint: LRCOMM=0 or LRCOMM≥value.
On entry, M value=value.
Constraint: 1≤M i≤4 for all i.
On entry, MXMESH=value and NMESH=value.
Constraint: MXMESH≥2×NMESH-1.
On entry, NCOL=value and max M i=value.
Constraint: max M i≤NCOL≤7.
On entry, NEQ=value.
Constraint: NEQ≥1.
On entry, NLBC=value, NRBC=value and sum M i=value.
Constraint: NLBC+NRBC=sum M i.
On entry, NLBC=value and NRBC=value.
Constraint: NLBC≥1 and NRBC≥1.
On entry, NMESH=value.
Constraint: NMESH≥6.
On entry, the elements of MESH are not strictly increasing.
On entry, TOLS value=value.
Constraint: TOLS i>value for all i.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

Not applicable.

8 Parallelism and Performance

D02TVF is not threaded in any implementation.

9 Further Comments

For problems where sharp changes of behaviour are expected over short intervals it may be advisable to:
– | use a large value for NCOL;
– | cluster the initial mesh points where sharp changes in behaviour are expected;
– | maintain fixed points in the mesh using the argument IPMESH to ensure that the remeshing process does not inadvertently remove mesh points from areas of known interest before they are detected automatically by the algorithm.

9.1 Nonseparated Boundary Conditions

A boundary value problem with nonseparated boundary conditions can be treated by transformation to an equivalent problem with separated conditions. As a simple example consider the system
y 1′=f 1 x,y 1,y 2 y 2′=f 2 x,y 1,y 2
on a,b subject to the boundary conditions
g 1 y 1 a=0 g 2 y 2 a,y 2 b=0.
By adjoining the trivial ordinary differential equation
r′=0,
which implies r a=r b, and letting r b=y 2 b, say, we have a new system
y 1′ = f 1 x,y 1,y 2 y 2′ = f 2 x,y 1,y 2 r′ = 0,
subject to the separated boundary conditions
g 1 y 1 a=0 g 2 y 2 a,r a=0 y 2 b-r b=0.
There is an obvious overhead in adjoining an extra differential equation: the system to be solved is increased in size.

9.2 Multipoint Boundary Value Problems

Multipoint boundary value problems, that is problems where conditions are specified at more than two points, can also be transformed to an equivalent problem with two boundary points. Each sub-interval defined by the multipoint conditions can be transformed onto the interval 0,1, say, leading to a larger set of differential equations. The boundary conditions of the transformed system consist of the original boundary conditions and the conditions imposed by the requirement that the solution components be continuous at the interior break-points. For example, consider the equation
y 3 =f t,y,y 1 ,y 2   on  a,c
subject to the conditions
y a=A y b=B y 1 c=C
where a<b<c. This can be transformed to the system
y 1 3 = f t,y 1,y 1 1 ,y 1 2 y 2 3 = f t,y 2,y 2 1 ,y 2 2   on ​ 0,1
where
y 1 ≡ y   on   a,b y 2 ≡ y   on   b,c,
subject to the boundary conditions
y 1 0 = A y 1 1 = B y 2 1 1 = C y 2 0 = B from ​ y 1 1=y 2 0 y 1 1 1 = y 2 1 0 y 1 2 1 = y 2 2 0.
In this instance two of the resulting boundary conditions are nonseparated but they may next be treated as described above.

9.3 High Order Systems

Systems of ordinary differential equations containing derivatives of order greater than four can always be reduced to systems of order suitable for treatment by D02TVF and its related routines. For example suppose we have the sixth-order equation
y 6 =-y.
Writing the variables y 1=y and y 2=y 4 we obtain the system
y 1 4 = y 2 y 2 2 = -y 1
which has maximal order four, or writing the variables y 1=y and y 2=y 3 we obtain the system
y 1 3 = y 2 y 2 3 = -y 1
which has maximal order three. The best choice of reduction by choosing new variables will depend on the structure and physical meaning of the system. Note that you will control the error in each of the variables y 1 and y 2. Indeed, if you wish to control the error in certain derivatives of the solution of an equation of order greater than one, then you should make those derivatives new variables.

9.4 Fixed Points and Singularities

The solver routine D02TLF employs collocation at Gaussian points in each sub-interval of the mesh. Hence the coefficients of the differential equations are not evaluated at the mesh points. Thus, fixed points should be specified in the mesh where either the coefficients are singular, or the solution has less smoothness, or where the differential equations should not be evaluated. Singular coefficients at boundary points often arise when physical symmetry is used to reduce partial differential equations to ordinary differential equations. These do not pose a direct numerical problem for using this code but they can severely impact its convergence.

9.5 Numerical Jacobians

The solver routine D02TLF requires an external routine FJAC to evaluate the partial derivatives of fi with respect to the elements of z y (=y 1,y 11,…,y 1 m 1-1 ,y 2,…,yn mn-1 ). In cases where the partial derivatives are difficult to evaluate, numerical approximations can be used. However, this approach might have a negative impact on the convergence of the modified Newton method. You could consider the use of symbolic mathematic packages and/or automatic differentiation packages if available to you.
See Section 10 in D02TZF for an example using numerical approximations to the Jacobian. There central differences are used and each fi is assumed to depend on all the components of z. This requires two evaluations of the system of differential equations for each component of z. The perturbation used depends on the size of each component of z and a minimum quantity dependent on the machine precision. The cost of this approach could be reduced by employing an alternative difference scheme and/or by only perturbing the components of z which appear in the definitions of the fi. A discussion on the choice of perturbation factors for use in finite difference approximations to partial derivatives can be found in Gill et al. (1981).

10 Example

The following example is used to illustrate the treatment of nonseparated boundary conditions. See also D02TLF, D02TXF, D02TYF and D02TZF, for the illustration of other facilities.
The following equations model of the spread of measles. See Schwartz (1983). Under certain assumptions the dynamics of the model can be expressed as
y 1′=μ-β x y 1y 3 y 2′=β x y 1y 3-y 2/λ y 3′=y 2/λ-y 3/η
subject to the periodic boundary conditions
yi 0=yi 1 ,   i= 1,2,3.
Here y 1,y 2 and y 3 are respectively the proportions of susceptibles, infectives and latents to the whole population. λ (=0.0279 years) is the latent period, η (=0.01 years) is the infectious period and μ (=0.02) is the population birth rate. β x=β 0 1.0+cos⁡2 πx is the contact rate where β 0=1575.0.
The nonseparated boundary conditions are treated as described in Section 9 by adjoining the trivial differential equations
y 4′=0 y 5′=0 y 6′=0
that is y 4,y 5 and y 6 are constants. The boundary conditions of the augmented system can then be posed in the separated form
y 1 0-y 4 0=0 y 2 0-y 5 0=0 y 3 0-y 6 0=0 y 1 1-y 4 1=0 y 2 1-y 5 1=0 y 3 1-y 6 1=0.
This is a relatively easy problem and an (arbitrary) initial guess of 1 for each component suffices, even though two components of the solution are much smaller than 1.

10.1 Program Text

Program Text (d02tvfe.f90)

10.2 Program Data

Program Data (d02tvfe.d)

10.3 Program Results

Program Results (d02tvfe.r)

GnuplotProduced by GNUPLOT 4.6 patchlevel 3 0.01 0.02 0.03 0.04 0.05 0.06 0.08 0 0.2 0.4 0.6 0.8 1 1e−08 1e−07 1e−06 1e−05 0.0001 0.001 0.01 0.1 Susceptibles Infectives and Latents Time Example Program Model of Spread of Measles susceptibles infectives latents gnuplot_plot_1 gnuplot_plot_2 gnuplot_plot_3
D02 Chapter Contents
D02 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


D02TXF : NAG Library, Mark 26

D02 Chapter Contents
D02 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

D02TXF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

D02TXF allows a solution to a nonlinear two-point boundary value problem computed by D02TLF to be used as an initial approximation in the solution of a related nonlinear two-point boundary value problem in a continuation call to D02TLF.

2 Specification

SUBROUTINE D02TXF ( MXMESH, NMESH, MESH, IPMESH, RCOMM, ICOMM, IFAIL)
INTEGER | MXMESH, NMESH, IPMESH(MXMESH), ICOMM(*), IFAIL
REAL (KIND=nag_wp) | MESH(MXMESH), RCOMM(*)

3 Description

D02TXF and its associated routines (D02TLF, D02TVF, D02TYF and D02TZF) solve the two-point boundary value problem for a nonlinear system of ordinary differential equations
y 1 m 1 x = f 1 x,y 1,y 1 1,…,y 1 m 1-1,y 2,…,yn mn-1 y 2 m 2 x = f 2 x,y 1,y 1 1,…,y 1 m 1-1,y 2,…,yn mn-1 ⋮ yn mn x = fn x,y 1,y 1 1,…,y 1 m 1-1,y 2,…,yn mn-1
over an interval a,b subject to p (>0) nonlinear boundary conditions at a and q (>0) nonlinear boundary conditions at b, where p+q = ∑ i=1 n mi . Note that yi m x is the mth derivative of the ith solution component. Hence yi 0 x=yi x. The left boundary conditions at a are defined as
gi z y a=0,  i=1,2,…,p,
and the right boundary conditions at b as
g-j z y b=0,  j=1,2,…,q,
where y=y 1,y 2,…,yn and
z y x = y 1 x, y 1 1 x ,…, y 1 m 1-1 x ,y 2 x,…, yn mn-1 x .
First, D02TVF must be called to specify the initial mesh, error requirements and other details. Then, D02TLF can be used to solve the boundary value problem. After successful computation, D02TZF can be used to ascertain details about the final mesh. D02TYF can be used to compute the approximate solution anywhere on the interval a,b using interpolation.
If the boundary value problem being solved is one of a sequence of related problems, for example as part of some continuation process, then D02TXF should be used between calls to D02TLF. This avoids the overhead of a complete initialization when the setup routine D02TVF is used. D02TXF allows the solution values computed in the previous call to D02TLF to be used as an initial approximation for the solution in the next call to D02TLF.
You must specify the new initial mesh. The previous mesh can be obtained by a call to D02TZF. It may be used unchanged as the new mesh, in which case any fixed points in the previous mesh remain as fixed points in the new mesh. Fixed and other points may be added or subtracted from the mesh by manipulation of the contents of the array argument IPMESH. Initial values for the solution components on the new mesh are computed by interpolation on the values for the solution components on the previous mesh.
The routines are based on modified versions of the codes COLSYS and COLNEW (see Ascher et al. (1979) and Ascher and Bader (1987)). A comprehensive treatment of the numerical solution of boundary value problems can be found in Ascher et al. (1988) and Keller (1992).

4 References

Ascher U M and Bader G (1987) A new basis implementation for a mixed order boundary value ODE solver SIAM J. Sci. Stat. Comput. 8 483–500
Ascher U M, Christiansen J and Russell R D (1979) A collocation solver for mixed order systems of boundary value problems Math. Comput. 33 659–679
Ascher U M, Mattheij R M M and Russell R D (1988) Numerical Solution of Boundary Value Problems for Ordinary Differential Equations Prentice–Hall
Keller H B (1992) Numerical Methods for Two-point Boundary-value Problems Dover, New York

5 Arguments

1:   MXMESH – INTEGERInput
On entry: the maximum number of points allowed in the mesh.
Constraint: this must be identical to the value supplied for the argument MXMESH in the prior call to D02TVF.
2:   NMESH – INTEGERInput
On entry: the number of points to be used in the new initial mesh. It is strongly recommended that if this routine is called that the suggested value (see below) for NMESH is used. In this case the arrays MESH and IPMESH returned by D02TZF can be passed to this routine without any modification.
Suggested value: n*+1/2, where n* is the number of mesh points used in the previous mesh as returned in the argument NMESH of D02TZF.
Constraint: 6≤NMESH≤MXMESH+1/2.
3:   MESH MXMESH – REAL (KIND=nag_wp) arrayInput
On entry: the NMESH points to be used in the new initial mesh as specified by IPMESH.
Suggested value: the argument MESH returned from a call to D02TZF.
Constraint: MESH ij < MESH i j+1, for j=1,2,…,NMESH-1, the values of i 1,i 2,…,iNMESH are defined in IPMESH.
MESH i 1 must contain the left boundary point, a, and MESH iNMESH must contain the right boundary point, b, as specified in the previous call to D02TVF.
4:   IPMESH MXMESH – INTEGER arrayInput
On entry: specifies the points in MESH to be used as the new initial mesh. Let ij:j=1,2,…,NMESH be the set of array indices of IPMESH such that IPMESH ij=1​ or ​2 and 1=i 1<i 2<⋯<iNMESH. Then MESH ij will be included in the new initial mesh.
If IPMESH ij=1, MESH ij will be a fixed point in the new initial mesh.
If IPMESH k=3 for any k, then MESH k will not be included in the new mesh.
Suggested value: the argument IPMESH returned in a call to D02TZF.
Constraints:
  • IPMESH k=1, 2 or 3, for k=1,2,…,iNMESH;
  • IPMESH 1=IPMESH iNMESH=1.
5:   RCOMM* – REAL (KIND=nag_wp) arrayCommunication Array
Note: the dimension of this array is dictated by the requirements of associated functions that must have been previously called. This array must be the same array passed as argument RCOMM in the previous call to D02TLF.
On entry: this must be the same array as supplied to D02TLF and must remain unchanged between calls.
On exit: contains information about the solution for use on subsequent calls to associated routines.
6:   ICOMM* – INTEGER arrayCommunication Array
Note: the dimension of this array is dictated by the requirements of associated functions that must have been previously called. This array must be the same array passed as argument ICOMM in the previous call to D02TLF.
On entry: this must be the same array as supplied to D02TLF and must remain unchanged between calls.
On exit: contains information about the solution for use on subsequent calls to associated routines.
7:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
An element of IPMESH was set to -1 before NMESH elements containing 1 or 2 were detected.
Expected value elements of IPMESH to be 1 or 2, but value such elements found.
IPMESH i≠-1, 1, 2 or 3 for some i.
On entry, IPMESH 1=value.
Constraint: IPMESH 1=1.
On entry, MXMESH=value and MXMESH=value in D02TVF.
Constraint: MXMESH=MXMESH in D02TVF.
On entry, NMESH=value.
Constraint: NMESH≥6.
On entry, NMESH=value and MXMESH=value.
Constraint: NMESH≤MXMESH+1/2.
The entries in MESH are not strictly increasing.
The first element of array MESH does not coincide with the left hand end of the range previously specified.
First element of MESH: value; left hand of the range: value.
The last point of the new mesh does not coincide with the right hand end of the range previously specified.
Last point of the new mesh: value; right hand end of the range: value.
The solver routine did not produce any results suitable for remeshing.
The solver routine does not appear to have been called.
You have set the element of IPMESH corresponding to the last element of MESH to be included in the new mesh as value, which is not 1.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

Not applicable.

8 Parallelism and Performance

D02TXF is not threaded in any implementation.

9 Further Comments

For problems where sharp changes of behaviour are expected over short intervals it may be advisable to:
– | cluster the mesh points where sharp changes in behaviour are expected;
– | maintain fixed points in the mesh using the argument IPMESH to ensure that the remeshing process does not inadvertently remove mesh points from areas of known interest.
In the absence of any other information about the expected behaviour of the solution, using the values suggested in Section 5 for NMESH, IPMESH and MESH is strongly recommended.

10 Example

This example illustrates the use of continuation, solution on an infinite range, and solution of a system of two differential equations of orders 3 and 2. See also D02TLF, D02TVF, D02TYF and D02TZF, for the illustration of other facilities.
Consider the problem of swirling flow over an infinite stationary disk with a magnetic field along the axis of rotation. See Ascher et al. (1988) and the references therein. After transforming from a cylindrical coordinate system r,θ,z, in which the θ component of the corresponding velocity field behaves like r-n, the governing equations are
f′′′+12 3-n f f′′+n f′ 2+g 2-s f′ = γ 2 g′′+12 3-n f g′+n-1 g f′-s g-1 = 0
with boundary conditions
f 0=f′0=g 0= 0,   f′∞= 0,   g∞=γ,
where s is the magnetic field strength, and γ is the Rossby number.
Some solutions of interest are for γ=1, small n and s→0. An added complication is the infinite range, which we approximate by 0,L. We choose n=0.2 and first solve for L=60.0,s=0.24 using the initial approximations f x=-x 2e-x and g x=1.0-e-x, which satisfy the boundary conditions, on a uniform mesh of 21 points. Simple continuation on the parameters L and s using the values L=120.0,s=0.144 and then L=240.0,s=0.0864 is used to compute further solutions. We use the suggested values for NMESH, IPMESH and MESH in the call to D02TXF prior to a continuation call, that is only every second point of the preceding mesh is used.
The equations are first mapped onto 0,1 to yield
f′′′ = L 3 γ 2-g 2+L 2 s f′-L 12 3-n f f′′+n f′ 2 g′′ = L 2 s g-1-L 12 3-n f g′+n-1 f′g.

10.1 Program Text

Program Text (d02txfe.f90)

10.2 Program Data

Program Data (d02txfe.d)

10.3 Program Results

Program Results (d02txfe.r)

GnuplotProduced by GNUPLOT 4.6 patchlevel 3 −3 −2.5 −2 −1.5 −1 −0.5 0 0.5 1 1.5 0 10 20 30 40 50 60 Velocities Radial Distance from Magnetic Field Example Program Swirling Flow over Disc under Axial Magnetic Field using L=60 and Magnetic Field Strength, s=0.24 tangential velocity axial velocity gnuplot_plot_1 gnuplot_plot_2
GnuplotProduced by GNUPLOT 4.6 patchlevel 3 −5 −4 −3 −2 −1 0 1 2 0 20 40 60 80 100 120 Velocities Radial Distance from Magnetic Field Swirling Flow over Disc under Axial Magnetic Field Continued to L=120 and Magnetic Field Strength, s=0.144 tangential velocity axial velocity gnuplot_plot_1 gnuplot_plot_2
GnuplotProduced by GNUPLOT 4.6 patchlevel 3 −7 −6 −5 −4 −3 −2 −1 0 1 2 0 50 100 150 200 250 Velocities Radial Distance from Magnetic Field Swirling Flow over Disc under Axial Magnetic Field Continued to L=240 and Magnetic Field Strength, s=0.0864 tangential velocity axial velocity gnuplot_plot_1 gnuplot_plot_2
D02 Chapter Contents
D02 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


D02TYF : NAG Library, Mark 26

D02 Chapter Contents
D02 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

D02TYF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

D02TYF interpolates on the solution of a general two-point boundary value problem computed by D02TLF.

2 Specification

SUBROUTINE D02TYF ( X, Y, NEQ, MMAX, RCOMM, ICOMM, IFAIL)
INTEGER | NEQ, MMAX, ICOMM(*), IFAIL
REAL (KIND=nag_wp) | X, Y(NEQ,MMAX), RCOMM(*)

3 Description

D02TYF and its associated routines (D02TLF, D02TVF, D02TXF and D02TZF) solve the two-point boundary value problem for a nonlinear mixed order system of ordinary differential equations
y 1 m 1 x = f 1 x,y 1,y 1 1,…,y 1 m 1-1,y 2,…,yn mn-1 y 2 m 2 x = f 2 x,y 1,y 1 1,…,y 1 m 1-1,y 2,…,yn mn-1 ⋮ yn mn x = fn x,y 1,y 1 1,…,y 1 m 1-1,y 2,…,yn mn-1
over an interval a,b subject to p (>0) nonlinear boundary conditions at a and q (>0) nonlinear boundary conditions at b, where p+q = ∑ i=1 n mi . Note that yi m x is the mth derivative of the ith solution component. Hence yi 0 x=yi x. The left boundary conditions at a are defined as
gi z y a=0,  i=1,2,…,p,
and the right boundary conditions at b as
g-j z y b=0,  j=1,2,…,q,
where y=y 1,y 2,…,yn and
z y x = y 1 x, y 1 1 x ,…, y 1 m 1-1 x ,y 2 x,…, yn mn-1 x .
First, D02TVF must be called to specify the initial mesh, error requirements and other details. Then, D02TLF can be used to solve the boundary value problem. After successful computation, D02TZF can be used to ascertain details about the final mesh and other details of the solution procedure, and D02TYF can be used to compute the approximate solution anywhere on the interval a,b using interpolation.
The routines are based on modified versions of the codes COLSYS and COLNEW (see Ascher et al. (1979) and Ascher and Bader (1987)). A comprehensive treatment of the numerical solution of boundary value problems can be found in Ascher et al. (1988) and Keller (1992).

4 References

Ascher U M and Bader G (1987) A new basis implementation for a mixed order boundary value ODE solver SIAM J. Sci. Stat. Comput. 8 483–500
Ascher U M, Christiansen J and Russell R D (1979) A collocation solver for mixed order systems of boundary value problems Math. Comput. 33 659–679
Ascher U M, Mattheij R M M and Russell R D (1988) Numerical Solution of Boundary Value Problems for Ordinary Differential Equations Prentice–Hall
Grossman C (1992) Enclosures of the solution of the Thomas–Fermi equation by monotone discretization J. Comput. Phys. 98 26–32
Keller H B (1992) Numerical Methods for Two-point Boundary-value Problems Dover, New York

5 Arguments

1:   X – REAL (KIND=nag_wp)Input
On entry: x, the independent variable.
Constraint: a≤X≤b, i.e., not outside the range of the original mesh specified in the initialization call to D02TVF.
2:   Y NEQMMAX – REAL (KIND=nag_wp) arrayOutput
On exit: Y ij contains an approximation to yi j x, for i=1,2,…,NEQ and j=0,1,…,mi-1. The remaining elements of Y (where mi<MMAX) are initialized to 0.0.
3:   NEQ – INTEGERInput
On entry: the number of differential equations.
Constraint: NEQ must be the same value as supplied to D02TVF.
4:   MMAX – INTEGERInput
On entry: the maximal order of the differential equations, max mi, for i=1,2,…,NEQ.
Constraint: MMAX must contain the maximum value of the components of the argument M as supplied to D02TVF.
5:   RCOMM* – REAL (KIND=nag_wp) arrayCommunication Array
Note: the dimension of this array is dictated by the requirements of associated functions that must have been previously called. This array must be the same array passed as argument RCOMM in the previous call to D02TLF.
On entry: this must be the same array as supplied to D02TLF and must remain unchanged between calls.
On exit: contains information about the solution for use on subsequent calls to associated routines.
6:   ICOMM* – INTEGER arrayCommunication Array
Note: the dimension of this array is dictated by the requirements of associated functions that must have been previously called. This array must be the same array passed as argument ICOMM in the previous call to D02TLF.
On entry: this must be the same array as supplied to D02TLF and must remain unchanged between calls.
On exit: contains information about the solution for use on subsequent calls to associated routines.
7:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, because for this routine the values of the output arguments may be useful even if IFAIL≠0 on exit, the recommended value is -1. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Note: D02TYF may return useful information for one or more of the following detected errors or warnings.
Errors or warnings detected by the routine:
IFAIL=1
On entry, MMAX=value and max⁡M i=value.
Constraint: MMAX=max⁡M i.
On entry, NEQ=value and NEQ=value in D02TVF.
Constraint: NEQ=NEQ in D02TVF.
On entry, X=value.
Constraint: X≤value.
On entry, X=value.
Constraint: X≥value.
The solver routine did not produce any results suitable for interpolation.
The solver routine does not appear to have been called.
IFAIL=2
The solver routine did not converge to a suitable solution.
A converged intermediate solution has been used.
Interpolated values should be treated with caution.
The solver routine did not satisfy the error requirements.
Interpolated values should be treated with caution.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

If D02TYF returns the value IFAIL=0, the computed values of the solution components yi should be of similar accuracy to that specified by the argument TOLS of D02TVF. Note that during the solution process the error in the derivatives yi j, for j=1,2,…,mi-1, has not been controlled and that the derivative values returned by D02TYF are computed via differentiation of the piecewise polynomial approximation to yi. See also Section 9.

8 Parallelism and Performance

D02TYF makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

If D02TYF returns the value IFAIL=2 in this routine and IFAIL=5 in D02TLF, then the accuracy of the interpolated values may be proportional to the quantity ERMX as returned by D02TZF.
If D02TLF returned a value for IFAIL other than IFAIL=0, then nothing can be said regarding either the quality or accuracy of the values computed by D02TYF.

10 Example

The following example is used to illustrate that a system with singular coefficients can be treated without modification of the system definition. See also D02TLF, D02TVF, D02TXF and D02TZF, for the illustration of other facilities.
Consider the Thomas–Fermi equation used in the investigation of potentials and charge densities of ionized atoms. See Grossman (1992), for example, and the references therein. The equation is
y′′=x-1/2y 3/2
with boundary conditions
y 0= 1,   y a= 0,   a> 0.
The coefficient x-1/2 implies a singularity at the left-hand boundary x=0.
We use the initial approximation y x=1-x/a, which satisfies the boundary conditions, on a uniform mesh of six points. For illustration we choose a=1, as in Grossman (1992). Note that in FFUN and FJAC (see D02TLF) we have taken the precaution of setting the function value and Jacobian value to 0.0 in case a value of y becomes negative, although starting from our initial solution profile this proves unnecessary during the solution phase. Of course the true solution y x is positive for all x<a.

10.1 Program Text

Program Text (d02tyfe.f90)

10.2 Program Data

Program Data (d02tyfe.d)

10.3 Program Results

Program Results (d02tyfe.r)

GnuplotProduced by GNUPLOT 4.6 patchlevel 3 −2 −1.5 −1 −0.5 0 0.5 1 0 0.2 0.4 0.6 0.8 1 Effective Nuclear Charge Relative Distance Example Program Thomas-Fermi Equation for Determining Effective Nuclear Charge in Heavy Atoms nuclear charge charge gradient gnuplot_plot_1 gnuplot_plot_2
D02 Chapter Contents
D02 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


D02TZF : NAG Library, Mark 26

D02 Chapter Contents
D02 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

D02TZF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

D02TZF returns information about the solution of a general two-point boundary value problem computed by D02TLF.

2 Specification

SUBROUTINE D02TZF ( MXMESH, NMESH, MESH, IPMESH, ERMX, IERMX, IJERMX, RCOMM, ICOMM, IFAIL)
INTEGER | MXMESH, NMESH, IPMESH(MXMESH), IERMX, IJERMX, ICOMM(*), IFAIL
REAL (KIND=nag_wp) | MESH(MXMESH), ERMX, RCOMM(*)

3 Description

D02TZF and its associated routines (D02TLF, D02TVF, D02TXF and D02TYF) solve the two-point boundary value problem for a nonlinear mixed order system of ordinary differential equations
y 1 m 1 x = f 1 x,y 1,y 1 1,…,y 1 m 1-1,y 2,…,yn mn-1 y 2 m 2 x = f 2 x,y 1,y 1 1,…,y 1 m 1-1,y 2,…,yn mn-1 ⋮ yn mn x = fn x,y 1,y 1 1,…,y 1 m 1-1,y 2,…,yn mn-1
over an interval a,b subject to p (>0) nonlinear boundary conditions at a and q (>0) nonlinear boundary conditions at b, where p+q = ∑ i=1 n mi . Note that yi m x is the mth derivative of the ith solution component. Hence yi 0 x=yi x. The left boundary conditions at a are defined as
gi z y a=0,  i=1,2,…,p,
and the right boundary conditions at b as
g-j z y b=0,  j=1,2,…,q,
where y=y 1,y 2,…,yn and
z y x = y 1 x, y 1 1 x ,…, y 1 m 1-1 x ,y 2 x,…, yn mn-1 x .
First, D02TVF must be called to specify the initial mesh, error requirements and other details. Then, D02TLF can be used to solve the boundary value problem. After successful computation, D02TZF can be used to ascertain details about the final mesh. D02TYF can be used to compute the approximate solution anywhere on the interval a,b using interpolation.
The routines are based on modified versions of the codes COLSYS and COLNEW (see Ascher et al. (1979) and Ascher and Bader (1987)). A comprehensive treatment of the numerical solution of boundary value problems can be found in Ascher et al. (1988) and Keller (1992).

4 References

Ascher U M and Bader G (1987) A new basis implementation for a mixed order boundary value ODE solver SIAM J. Sci. Stat. Comput. 8 483–500
Ascher U M, Christiansen J and Russell R D (1979) A collocation solver for mixed order systems of boundary value problems Math. Comput. 33 659–679
Ascher U M, Mattheij R M M and Russell R D (1988) Numerical Solution of Boundary Value Problems for Ordinary Differential Equations Prentice–Hall
Cole J D (1968) Perturbation Methods in Applied Mathematics Blaisdell, Waltham, Mass.
Keller H B (1992) Numerical Methods for Two-point Boundary-value Problems Dover, New York

5 Arguments

1:   MXMESH – INTEGERInput
On entry: the maximum number of points allowed in the mesh.
Constraint: this must be identical to the value supplied for the argument MXMESH in the prior call to D02TVF.
2:   NMESH – INTEGEROutput
On exit: the number of points in the mesh last used by D02TLF.
3:   MESH MXMESH – REAL (KIND=nag_wp) arrayOutput
On exit: MESH i contains the ith point of the mesh last used by D02TLF, for i=1,2,…,NMESH. MESH 1 will contain a and MESH NMESH will contain b. The remaining elements of MESH are not initialized.
4:   IPMESH MXMESH – INTEGER arrayOutput
On exit: IPMESH i specifies the nature of the point MESH i, for i=1,2,…,NMESH, in the final mesh computed by D02TLF.
IPMESH i=1
Indicates that the ith point is a fixed point and was used by the solver before an extrapolation-like error test.
IPMESH i=2
Indicates that the ith point was used by the solver before an extrapolation-like error test.
IPMESH i=3
Indicates that the ith point was used by the solver only as part of an extrapolation-like error test.
The remaining elements of IPMESH are initialized to -1.
See Section 9 for advice on how these values may be used in conjunction with a continuation process.
5:   ERMX – REAL (KIND=nag_wp)Output
On exit: an estimate of the maximum error in the solution computed by D02TLF, that is
ERMX=max⁡yi-vi 1.0+vi
where vi is the approximate solution for the ith solution component. If D02TLF returned successfully with IFAIL=0, then ERMX will be less than TOLS IJERMX where TOLS contains the error requirements as specified in Sections 3 and 5 in D02TVF.
If D02TLF returned with IFAIL=5, then ERMX will be greater than TOLS IJERMX.
If D02TLF returned any other value for IFAIL then an error estimate is not available and ERMX is initialized to 0.0.
6:   IERMX – INTEGEROutput
On exit: indicates the mesh sub-interval where the value of ERMX has been computed, that is MESH IERMX ,MESH IERMX + 1 .
If an estimate of the error is not available then IERMX is initialized to 0.
7:   IJERMX – INTEGEROutput
On exit: indicates the component i (=IJERMX) of the solution for which ERMX has been computed, that is the approximation of yi on MESH IERMX,MESH IERMX+1 is estimated to have the largest error of all components yi over mesh sub-intervals defined by MESH.
If an estimate of the error is not available then IJERMX is initialized to 0.
8:   RCOMM* – REAL (KIND=nag_wp) arrayCommunication Array
Note: the dimension of this array is dictated by the requirements of associated functions that must have been previously called. This array must be the same array passed as argument RCOMM in the previous call to D02TLF.
On entry: this must be the same array as supplied to D02TLF and must remain unchanged between calls.
On exit: contains information about the solution for use on subsequent calls to associated routines.
9:   ICOMM* – INTEGER arrayCommunication Array
Note: the dimension of this array is dictated by the requirements of associated functions that must have been previously called. This array must be the same array passed as argument ICOMM in the previous call to D02TLF.
On entry: this must be the same array as supplied to D02TLF and must remain unchanged between calls.
On exit: contains information about the solution for use on subsequent calls to associated routines.
10:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, because for this routine the values of the output arguments may be useful even if IFAIL≠0 on exit, the recommended value is -1. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Note: D02TZF may return useful information for one or more of the following detected errors or warnings.
Errors or warnings detected by the routine:
IFAIL=1
On entry, an illegal value for MXMESH was specified, or an invalid call to D02TZF was made, for example without a previous call to the solver routine D02TLF.
IFAIL=2
The solver routine D02TLF did not converge to a solution or did not satisfy the error requirements. The last mesh computed by D02TLF has been returned by D02TZF. This mesh should be treated with extreme caution as nothing can be said regarding its quality or suitability for any subsequent computation.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

Not applicable.

8 Parallelism and Performance

D02TZF is not threaded in any implementation.

9 Further Comments

Note that:
  • if D02TLF returned IFAIL=0, 4 or 5 then it will always be the case that IPMESH 1=IPMESH NMESH=1;
  • if D02TLF returned IFAIL=0 or 5 then it will always be the case that IPMESH i=3, for i=2,4,…,NMESH-1 (even i) and IPMESH i=1 or 2, for i=3,5,…,NMESH-2 (odd i);
  • if D02TLF returned IFAIL=4 then it will always be the case that IPMESH i=1​ or ​2, for i=2,3,…,NMESH-1.
If D02TZF returns IFAIL=0, then examination of the mesh may provide assistance in determining a suitable starting mesh for D02TVF in any subsequent attempts to solve similar problems.
If the problem being treated by D02TLF is one of a series of related problems (for example, as part of a continuation process), then the values of IPMESH and MESH may be suitable as input arguments to D02TXF. Using the mesh points not involved in the extrapolation error test is usually appropriate. IPMESH and MESH should be passed unchanged to D02TXF but NMESH should be replaced by NMESH+1/2.
If D02TZF returns IFAIL=2, nothing can be said regarding the quality of the mesh returned. However, it may be a useful starting mesh for D02TVF in any subsequent attempts to solve the same problem.
If D02TLF returns IFAIL=5, this corresponds to the solver requiring more than MXMESH mesh points to satisfy the error requirements. If MXMESH can be increased and the preceding call to D02TLF was not part, or was the first part, of a continuation process then the values in MESH may provide a suitable mesh with which to initialize a subsequent attempt to solve the same problem. If it is not possible to provide more mesh points then relaxing the error requirements by setting TOLS IJERMX to ERMX might lead to a successful solution. It may be necessary to reset the other components of TOLS. Note that resetting the tolerances can lead to a different sequence of meshes being computed and hence to a different solution being computed.

10 Example

The following example is used to illustrate the use of fixed mesh points, simple continuation and numerical approximation of a Jacobian. See also D02TLF, D02TVF, D02TXF and D02TYF, for the illustration of other facilities.
Consider the Lagerstrom–Cole equation
y′′=y-y y′/ε
with the boundary conditions
y 0=α y 1=β, (1)
where ε is small and positive. The nature of the solution depends markedly on the values of α,β. See Cole (1968).
We choose α=-13,β=13 for which the solution is known to have corner layers at x=13,23 . We choose an initial mesh of seven points 0.0,0.15,0.3,0.5,0.7,0.85,1.0 and ensure that the points x=0.3,0.7 near the corner layers are fixed, that is the corresponding elements of the array IPMESH are set to 1. First we compute the solution for ε=1.0E−4 using in GUESS the initial approximation y x=α+β-α x which satisfies the boundary conditions. Then we use simple continuation to compute the solution for ε=1.0E−5. We use the suggested values for NMESH, IPMESH and MESH in the call to D02TXF prior to the continuation call, that is only every second point of the preceding mesh is used and the fixed mesh points are retained.
Although the analytic Jacobian for this system is easy to evaluate, for illustration the procedure FJAC uses central differences and calls to FFUN to compute a numerical approximation to the Jacobian.

10.1 Program Text

Program Text (d02tzfe.f90)

10.2 Program Data

Program Data (d02tzfe.d)

10.3 Program Results

Program Results (d02tzfe.r)

GnuplotProduced by GNUPLOT 4.6 patchlevel 3 −0.4 −0.3 −0.2 −0.1 0 0.1 0.2 0.3 0.4 0 0.2 0.4 0.6 0.8 1 0 0.2 0.4 0.6 0.8 1 1.2 Solution Derivative x Example Program Lagerstrom-Cole Equation (−1/3,1/3) with ε=0.0001 solution derivative gnuplot_plot_1 gnuplot_plot_2
GnuplotProduced by GNUPLOT 4.6 patchlevel 3 −0.4 −0.3 −0.2 −0.1 0 0.1 0.2 0.3 0.4 0 0.2 0.4 0.6 0.8 1 0 0.2 0.4 0.6 0.8 1 1.2 Solution Derivative x Lagerstrom-Cole Equation (−1/3,1/3) with ε=0.00001 solution derivative gnuplot_plot_1 gnuplot_plot_2
D02 Chapter Contents
D02 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


D02UAF : NAG Library, Mark 26

D02 Chapter Contents
D02 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

D02UAF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
10 Example

1 Purpose

D02UAF obtains the Chebyshev coefficients of a function discretized on Chebyshev Gauss–Lobatto points. The set of discretization points on which the function is evaluated is usually obtained by a previous call to D02UCF.

2 Specification

SUBROUTINE D02UAF ( N, F, C, IFAIL)
INTEGER | N, IFAIL
REAL (KIND=nag_wp) | F(N+1), C(N+1)

3 Description

D02UAF computes the coefficients cj, for j=1,2,…,n+1, of the interpolating Chebyshev series
12 c 1 T 0 x- + c 2 T 1 x- + c 3T 2 x- +⋯+ c n+1 Tn x- ,
which interpolates the function f x evaluated at the Chebyshev Gauss–Lobatto points
x-r = - cos r-1 π/n ,   r=1,2,…,n+1 .
Here Tj x- denotes the Chebyshev polynomial of the first kind of degree j with argument x- defined on -1,1. In terms of your original variable, x say, the input values at which the function values are to be provided are
xr = - 12 b - a cos π r-1 /n + 1 2 b + a ,   r=1,2,…,n+1 , ​
where b and a are respectively the upper and lower ends of the range of x over which the function is required.

4 References

Canuto C (1988) Spectral Methods in Fluid Dynamics 502 Springer
Canuto C, Hussaini M Y, Quarteroni A and Zang T A (2006) Spectral Methods: Fundamentals in Single Domains Springer
Trefethen L N (2000) Spectral Methods in MATLAB SIAM

5 Arguments

1:   N – INTEGERInput
On entry: n, where the number of grid points is n+1. This is also the largest order of Chebyshev polynomial in the Chebyshev series to be computed.
Constraint: N>0 and N is even.
2:   F N+1 – REAL (KIND=nag_wp) arrayInput
On entry: the function values f xr, for r=1,2,…,n+1.
3:   C N+1 – REAL (KIND=nag_wp) arrayOutput
On exit: the Chebyshev coefficients, cj, for j=1,2,…,n+1.
4:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, N=value.
Constraint: N>1.
On entry, N=value.
Constraint: N is even.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

The Chebyshev coefficients computed should be accurate to within a small multiple of machine precision.

8 Parallelism and Performance

D02UAF is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
D02UAF makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The number of operations is of the order n log n and the memory requirements are O n ; thus the computation remains efficient and practical for very fine discretizations (very large values of n).

10 Example

See Section 10 in D02UEF.
D02 Chapter Contents
D02 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


D02UBF : NAG Library, Mark 26

D02 Chapter Contents
D02 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

D02UBF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
10 Example

1 Purpose

D02UBF evaluates a function, or one of its lower order derivatives, from its Chebyshev series representation at Chebyshev Gauss–Lobatto points on a,b. The coefficients of the Chebyshev series representation required are usually derived from those returned by D02UAF or D02UEF.

2 Specification

SUBROUTINE D02UBF ( N, A, B, Q, C, F, IFAIL)
INTEGER | N, Q, IFAIL
REAL (KIND=nag_wp) | A, B, C(N+1), F(N+1)

3 Description

D02UBF evaluates the Chebyshev series
S x- = 12 c 1 T 0 x- + c 2 T 1 x- + c 3T 2 x- +⋯+ c n+1 Tn x- ,
or its derivative (up to fourth order) at the Chebyshev Gauss–Lobatto points on a,b. Here Tj x- denotes the Chebyshev polynomial of the first kind of degree j with argument x- defined on -1,1. In terms of your original variable, x say, the input values at which the function values are to be provided are
xr = - 12 b - a cos π r-1 /n + 1 2 b + a ,   r=1,2,…,n+1 , ​
where b and a are respectively the upper and lower ends of the range of x over which the function is required.
The calculation is implemented by a forward one-dimensional discrete Fast Fourier Transform (DFT).

4 References

Canuto C (1988) Spectral Methods in Fluid Dynamics 502 Springer
Canuto C, Hussaini M Y, Quarteroni A and Zang T A (2006) Spectral Methods: Fundamentals in Single Domains Springer
Trefethen L N (2000) Spectral Methods in MATLAB SIAM

5 Arguments

1:   N – INTEGERInput
On entry: n, where the number of grid points is n+1. This is also the largest order of Chebyshev polynomial in the Chebyshev series to be computed.
Constraint: N>0 and N is even.
2:   A – REAL (KIND=nag_wp)Input
On entry: a, the lower bound of domain a,b.
Constraint: A<B.
3:   B – REAL (KIND=nag_wp)Input
On entry: b, the upper bound of domain a,b.
Constraint: B>A.
4:   Q – INTEGERInput
On entry: the order, q, of the derivative to evaluate.
Constraint: 0≤Q≤4.
5:   C N+1 – REAL (KIND=nag_wp) arrayInput
On entry: the Chebyshev coefficients, ci, for i=1,2,…,n+1.
6:   F N+1 – REAL (KIND=nag_wp) arrayOutput
On exit: the derivatives S q xi , for i=1,2,…,n+1, of the Chebyshev series, S.
7:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, N=value.
Constraint: N>0.
On entry, N=value.
Constraint: N is even.
IFAIL=2
On entry, A=value and B=value.
Constraint: A<B.
IFAIL=3
On entry, Q=value.
Constraint: 0≤Q≤4.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

Evaluations of DFT to obtain function or derivative values should be an order n multiple of machine precision assuming full accuracy to machine precision in the given Chebyshev series representation.

8 Parallelism and Performance

D02UBF is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
D02UBF makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The number of operations is of the order n log n and the memory requirements are O n; thus the computation remains efficient and practical for very fine discretizations (very large values of n).

10 Example

See Section 10 in D02UEF.
D02 Chapter Contents
D02 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


D02UCF : NAG Library, Mark 26

D02 Chapter Contents
D02 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

D02UCF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
10 Example

1 Purpose

D02UCF returns the Chebyshev Gauss–Lobatto grid points on a,b.

2 Specification

SUBROUTINE D02UCF ( N, A, B, X, IFAIL)
INTEGER | N, IFAIL
REAL (KIND=nag_wp) | A, B, X(N+1)

3 Description

D02UCF returns the Chebyshev Gauss–Lobatto grid points on a,b. The Chebyshev Gauss–Lobatto points on -1,1 are computed as ti = - cos i-1 π n , for i=1,2,…,n+1. The Chebyshev Gauss–Lobatto points on an arbitrary domain a,b are:
xi = b-a 2 ti + a+b 2 ,   i=1,2,…,n+1 .

4 References

Trefethen L N (2000) Spectral Methods in MATLAB SIAM

5 Arguments

1:   N – INTEGERInput
On entry: n, where the number of grid points is n+1. This is also the largest order of Chebyshev polynomial in the Chebyshev series to be computed.
Constraint: N>0 and N is even.
2:   A – REAL (KIND=nag_wp)Input
On entry: a, the lower bound of domain a,b.
Constraint: A<B.
3:   B – REAL (KIND=nag_wp)Input
On entry: b, the upper bound of domain a,b.
Constraint: B>A.
4:   X N+1 – REAL (KIND=nag_wp) arrayOutput
On exit: the Chebyshev Gauss–Lobatto grid points, xi, for i=1,2,…,n+1, on a,b.
5:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, N=value.
Constraint: N>0.
On entry, N=value.
Constraint: N is even.
IFAIL=2
On entry, A=value and B=value.
Constraint: A<B.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

The Chebyshev Gauss–Lobatto grid points computed should be accurate to within a small multiple of machine precision.

8 Parallelism and Performance

D02UCF is not threaded in any implementation.

9 Further Comments

The number of operations is of the order n log n and there are no internal memory requirements; thus the computation remains efficient and practical for very fine discretizations (very large values of n).

10 Example

See Section 10 in D02UEF.
D02 Chapter Contents
D02 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


D02UDF : NAG Library, Mark 26

D02 Chapter Contents
D02 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

D02UDF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

D02UDF differentiates a function discretized on Chebyshev Gauss–Lobatto points. The grid points on which the function values are to be provided are normally returned by a previous call to D02UCF.

2 Specification

SUBROUTINE D02UDF ( N, F, FD, IFAIL)
INTEGER | N, IFAIL
REAL (KIND=nag_wp) | F(N+1), FD(N+1)

3 Description

D02UDF differentiates a function discretized on Chebyshev Gauss–Lobatto points on -1,1. The polynomial interpolation on Chebyshev points is equivalent to trigonometric interpolation on equally spaced points. Hence the differentiation on the Chebyshev points can be implemented by the Fast Fourier transform (FFT).
Given the function values f xi on Chebyshev Gauss–Lobatto points xi = - cos i-1 π / n , for i=1,2,…,n+1, f is differentiated with respect to x by means of forward and backward FFTs on the function values f xi. D02UDF returns the computed derivative values f′xi, for i=1,2,…,n+1. The derivatives are computed with respect to the standard Chebyshev Gauss–Lobatto points on -1,1; for derivatives of a function on a,b the returned values have to be scaled by a factor 2/b-a.

4 References

Canuto C, Hussaini M Y, Quarteroni A and Zang T A (2006) Spectral Methods: Fundamentals in Single Domains Springer
Greengard L (1991) Spectral integration and two-point boundary value problems SIAM J. Numer. Anal. 28(4) 1071–80
Trefethen L N (2000) Spectral Methods in MATLAB SIAM

5 Arguments

1:   N – INTEGERInput
On entry: n, where the number of grid points is n+1.
Constraint: N>0 and N is even.
2:   F N+1 – REAL (KIND=nag_wp) arrayInput
On entry: the function values f xi, for i=1,2,…,n+1
3:   FD N+1 – REAL (KIND=nag_wp) arrayOutput
On exit: the approximations to the derivatives of the function evaluated at the Chebyshev Gauss–Lobatto points. For functions defined on a,b, the returned derivative values (corresponding to the domain -1,1) must be multiplied by the factor 2/b-a to obtain the correct values on a,b.
4:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, N=value.
Constraint: N>0.
On entry, N=value.
Constraint: N is even.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

The accuracy is close to machine precision for small numbers of grid points, typically less than 100. For larger numbers of grid points, the error in differentiation grows with the number of grid points. See Greengard (1991) for more details.

8 Parallelism and Performance

D02UDF is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
D02UDF makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The number of operations is of the order n log n and the memory requirements are O n; thus the computation remains efficient and practical for very fine discretizations (very large values of n).

10 Example

The function 2 x+exp-x, defined on 0,1.5, is supplied and then differentiated on a grid.

10.1 Program Text

Program Text (d02udfe.f90)

10.2 Program Data

Program Data (d02udfe.d)

10.3 Program Results

Program Results (d02udfe.r)

D02 Chapter Contents
D02 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


D02UEF : NAG Library, Mark 26

D02 Chapter Contents
D02 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

D02UEF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

D02UEF finds the solution of a linear constant coefficient boundary value problem by using the Chebyshev integration formulation on a Chebyshev Gauss–Lobatto grid.

2 Specification

SUBROUTINE D02UEF ( N, A, B, M, C, BMAT, Y, BVEC, F, UC, RESID, IFAIL)
INTEGER | N, M, IFAIL
REAL (KIND=nag_wp) | A, B, C(N+1), BMAT(M,M+1), Y(M), BVEC(M), F(M+1), UC(N+1,M+1), RESID

3 Description

D02UEF solves the constant linear coefficient ordinary differential problem
∑ j=0 m f j+1 dj u d xj = f x ,  x ∈ a,b
subject to a set of m linear constraints at points yi∈a,b , for i=1,2,…,m:
∑ j=0 m B i,j+1 dj u dx j x=yi = βi ,
where 1≤m≤4, B is an m×m+1 matrix of constant coefficients and βi are constants. The points yi are usually either a or b.
The function f x is supplied as an array of Chebyshev coefficients cj, j=0,1,…,n for the function discretized on n+1 Chebyshev Gauss–Lobatto points (as returned by D02UCF); the coefficients are normally obtained by a previous call to D02UAF. The solution and its derivatives (up to order m) are returned, in the form of their Chebyshev series representation, as arrays of Chebyshev coefficients; subsequent calls to D02UBF will return the corresponding function and derivative values at the Chebyshev Gauss–Lobatto discretization points on a,b. Function and derivative values can be obtained on any uniform grid over the same range a,b by calling the interpolation routine D02UWF.

4 References

Clenshaw C W (1957) The numerical solution of linear differential equations in Chebyshev series Proc. Camb. Phil. Soc. 53 134–149
Coutsias E A, Hagstrom T and Torres D (1996) An efficient spectral method for ordinary differential equations with rational function coefficients Mathematics of Computation 65(214) 611–635
Greengard L (1991) Spectral integration and two-point boundary value problems SIAM J. Numer. Anal. 28(4) 1071–80
Lundbladh A, Hennigson D S and Johannson A V (1992) An efficient spectral integration method for the solution of the Navier–Stokes equations Technical report FFA–TN 1992–28 Aeronautical Research Institute of Sweden
Muite B K (2010) A numerical comparison of Chebyshev methods for solving fourth-order semilinear initial boundary value problems Journal of Computational and Applied Mathematics 234(2) 317–342

5 Arguments

1:   N – INTEGERInput
On entry: n, where the number of grid points is n+1.
Constraint: N≥8 and N is even.
2:   A – REAL (KIND=nag_wp)Input
On entry: a, the lower bound of domain a,b.
Constraint: A<B.
3:   B – REAL (KIND=nag_wp)Input
On entry: b, the upper bound of domain a,b.
Constraint: B>A.
4:   M – INTEGERInput
On entry: the order, m, of the boundary value problem to be solved.
Constraint: 1≤M≤4.
5:   C N+1 – REAL (KIND=nag_wp) arrayInput
On entry: the Chebyshev coefficients cj, j=0,1,…,n, for the right hand side of the boundary value problem. Usually these are obtained by a previous call of D02UAF.
6:   BMAT M M+1 – REAL (KIND=nag_wp) arrayInput/Output
On entry: BMAT i j+1 must contain the coefficients B i,j+1, for i=1,2,…,m and j=0,1,…,m, in the problem formulation of Section 3.
On exit: the coefficients have been scaled to form an equivalent problem defined on the domain -1,1.
7:   Y M – REAL (KIND=nag_wp) arrayInput
On entry: the points, yi, for i=1,2,…,m, where the boundary conditions are discretized.
8:   BVEC M – REAL (KIND=nag_wp) arrayInput
On entry: the values, βi, for i=1,2,…,m, in the formulation of the boundary conditions given in Section 3.
9:   F M+1 – REAL (KIND=nag_wp) arrayInput/Output
On entry: the coefficients, fj, for j=1,2,…,m+1, in the formulation of the linear boundary value problem given in Section 3. The highest order term, F M+1, needs to be nonzero to have a well posed problem.
On exit: the coefficients have been scaled to form an equivalent problem defined on the domain -1,1.
10:   UC N+1M+1 – REAL (KIND=nag_wp) arrayOutput
On exit: the Chebyshev coefficients in the Chebyshev series representations of the solution and derivatives of the solution to the boundary value problem. The n+1 elements UC 1:N+1 1 contain the coefficients representing the solution U xi, for i=0,1,…,n. UC 1:N+1j+1 contains the coefficients representing the jth derivative of U, for j=1,2,…,m.
11:   RESID – REAL (KIND=nag_wp)Output
On exit: the maximum residual resulting from substituting the solution vectors returned in UC into both linear equations of Section 3 representing the linear boundary value problem and associated boundary conditions. That is
max max i=1,m ∑ j=0 m B i,j+1 dj u d xj x=yi - βi , max i=1, n+1 ∑ j=0 m f j+1 dj u dx j x=xi - f x .
12:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, N=value.
Constraint: N is even.
On entry, N=value.
Constraint: N≥8.
IFAIL=2
On entry, A=value and B=value.
Constraint: A<B.
IFAIL=3
On entry, F M+1=0.0.
IFAIL=6
On entry, M=value.
Constraint: 1≤M≤4.
IFAIL=7
Internal error while unpacking matrix during iterative refinement.
Please contact NAG.
IFAIL=8
Singular matrix encountered during iterative refinement.
Please check that your system is well posed.
IFAIL=9
During iterative refinement, the maximum number of iterations was reached.
Number of iterations=value and residual achieved=value.
IFAIL=10
During iterative refinement, convergence was achieved, but the residual is more than 100×machine precision. Residual achieved on convergence=value.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

The accuracy should be close to machine precision for well conditioned boundary value problems.

8 Parallelism and Performance

D02UEF is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
D02UEF makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The number of operations is of the order n log n and the memory requirements are O n; thus the computation remains efficient and practical for very fine discretizations (very large values of n). Collocation methods will be faster for small problems, but the method of D02UEF should be faster for larger discretizations.

10 Example

This example solves the third-order problem 4 U xxx + 3 U xx + 2 Ux + U = 2 sin⁡x - 2 cos⁡x on -π/2,π/2 subject to the boundary conditions U -π/2 = 0 , 3 U xx -π/2 + 2 Ux -π/2 + U -π/2 =2, and 3 U xx π/2 + 2 Ux π/2 + U π/2 =-2 using the Chebyshev integration formulation on a Chebyshev Gauss–Lobatto grid of order 16.

10.1 Program Text

Program Text (d02uefe.f90)

10.2 Program Data

Program Data (d02uefe.d)

10.3 Program Results

Program Results (d02uefe.r)

D02 Chapter Contents
D02 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


D02UWF : NAG Library, Mark 26

D02 Chapter Contents
D02 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

D02UWF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

D02UWF interpolates from a set of function values on a supplied grid onto a set of values for a uniform grid on the same range. The interpolation is performed using barycentric Lagrange interpolation. D02UWF is primarily a utility routine to map a set of function values specified on a Chebyshev Gauss–Lobatto grid onto a uniform grid.

2 Specification

SUBROUTINE D02UWF ( N, NIP, X, F, XIP, FIP, IFAIL)
INTEGER | N, NIP, IFAIL
REAL (KIND=nag_wp) | X(N+1), F(N+1), XIP(NIP), FIP(NIP)

3 Description

D02UWF interpolates from a set of n+1 function values, f xi, on a supplied grid, xi, for i=0,1,…,n, onto a set of m values, f^x^j, on a uniform grid, x^j, for j=1,2,…,m. The image x^ has the same range as x, so that x^j = xmin + j-1 / m-1 × xmax - xmin , for j=1,2,…,m. The interpolation is performed using barycentric Lagrange interpolation as described in Berrut and Trefethen (2004).
D02UWF is primarily a utility routine to map a set of function values specified on a Chebyshev Gauss–Lobatto grid computed by D02UCF onto an evenly-spaced grid with the same range as the original grid.

4 References

Berrut J P and Trefethen L N (2004) Barycentric lagrange interpolation SIAM Rev. 46(3) 501–517

5 Arguments

1:   N – INTEGERInput
On entry: n, where the number of grid points for the input data is n+1.
Constraint: N>0 and N is even.
2:   NIP – INTEGERInput
On entry: the number, m, of grid points in the uniform mesh x^ onto which function values are interpolated. If NIP=1 then on successful exit from D02UWF, FIP 1 will contain the value f xn.
Constraint: NIP>0.
3:   X N+1 – REAL (KIND=nag_wp) arrayInput
On entry: the grid points, xi, for i=0,1,…,n, at which the function is specified.
Usually this should be the array of Chebyshev Gauss–Lobatto points returned in D02UCF.
4:   F N+1 – REAL (KIND=nag_wp) arrayInput
On entry: the function values, f xi, for i=0,1,…,n.
5:   XIP NIP – REAL (KIND=nag_wp) arrayOutput
On exit: the evenly-spaced grid points, x^j, for j=1,2,…,m.
6:   FIP NIP – REAL (KIND=nag_wp) arrayOutput
On exit: the set of interpolated values f^x^j, for j=1,2,…,m. Here f^x^j≈f x=x^j.
7:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, N=value.
Constraint: N>0.
On entry, N=value.
Constraint: N is even.
IFAIL=2
On entry, NIP=value.
Constraint: NIP>0.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

D02UWF is intended, primarily, for use with Chebyshev Gauss–Lobatto input grids. For such input grids and for well-behaved functions (no discontinuities, peaks or cusps), the accuracy should be a small multiple of machine precision.

8 Parallelism and Performance

D02UWF is not threaded in any implementation.

9 Further Comments

None.

10 Example

This example interpolates the function x+cos 5 x, as specified on a 65-point Gauss–Lobatto grid on -1,1, onto a coarse uniform grid.

10.1 Program Text

Program Text (d02uwfe.f90)

10.2 Program Data

Program Data (d02uwfe.d)

10.3 Program Results

Program Results (d02uwfe.r)

D02 Chapter Contents
D02 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


D02UYF : NAG Library, Mark 26

D02 Chapter Contents
D02 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

D02UYF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

D02UYF obtains the weights for Clenshaw–Curtis quadrature at Chebyshev points. This allows for fast approximations of integrals for functions specified on Chebyshev Gauss–Lobatto points on -1,1.

2 Specification

SUBROUTINE D02UYF ( N, W, IFAIL)
INTEGER | N, IFAIL
REAL (KIND=nag_wp) | W(N+1)

3 Description

D02UYF obtains the weights for Clenshaw–Curtis quadrature at Chebyshev points.
Given the (Clenshaw–Curtis) weights wi, for i=0,1,…,n, and function values fi=f ti (where ti=-cos i×π/n, for i=0,1,…,n, are the Chebyshev Gauss–Lobatto points), then ∫ -1 1 f x dx ≈ ∑ i=0 n wi fi .
For a function discretized on a Chebyshev Gauss–Lobatto grid on a,b the resultant summation must be multiplied by the factor b-a/2.

4 References

Trefethen L N (2000) Spectral Methods in MATLAB SIAM

5 Arguments

1:   N – INTEGERInput
On entry: n, where the number of grid points is n+1.
Constraint: N>0 and N is even.
2:   W N+1 – REAL (KIND=nag_wp) arrayOutput
On exit: the Clenshaw–Curtis quadrature weights, wi, for i=0,1,…,n.
3:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, N=value.
Constraint: N>0.
On entry, N=value.
Constraint: N is even.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

The accuracy should be close to machine precision.

8 Parallelism and Performance

D02UYF is not threaded in any implementation.

9 Further Comments

A real array of length 2 n is internally allocated.

10 Example

This example approximates the integral ∫ -1 3 3 x 2 dx using 65 Clenshaw–Curtis weights and a 65-point Chebyshev Gauss–Lobatto grid on -1,3.

10.1 Program Text

Program Text (d02uyfe.f90)

10.2 Program Data

Program Data (d02uyfe.d)

10.3 Program Results

Program Results (d02uyfe.r)

D02 Chapter Contents
D02 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


D02UZF : NAG Library, Mark 26

D02 Chapter Contents
D02 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

D02UZF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

D02UZF returns the value of the kth Chebyshev polynomial evaluated at a point x∈-1,1. D02UZF is primarily a utility routine for use by the Chebyshev boundary value problem solvers.

2 Specification

SUBROUTINE D02UZF ( K, X, T, IFAIL)
INTEGER | K, IFAIL
REAL (KIND=nag_wp) | X, T

3 Description

D02UZF returns the value, T, of the kth Chebyshev polynomial evaluated at a point x∈-1,1; that is, T=cos k×arccos x.

4 References

Trefethen L N (2000) Spectral Methods in MATLAB SIAM

5 Arguments

1:   K – INTEGERInput
On entry: the order of the Chebyshev polynomial.
Constraint: K≥0.
2:   X – REAL (KIND=nag_wp)Input
On entry: the point at which to evaluate the polynomial.
Constraint: -1.0≤X≤1.0.
3:   T – REAL (KIND=nag_wp)Output
On exit: the value, T, of the Chebyshev polynomial order k evaluated at x.
4:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, K=value.
Constraint: K≥0.
IFAIL=2
On entry, X=value.
Constraint: -1.0≤X≤1.0.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

The accuracy should be close to machine precision.

8 Parallelism and Performance

D02UZF is not threaded in any implementation.

9 Further Comments

None.

10 Example

A set of Chebyshev coefficients is obtained for the function x+exp-x defined on -0.24×π,0.5×π using D02UCF. At each of a set of new grid points in the domain of the function D02UZF is used to evaluate each Chebshev polynomial in the series representation. The values obtained are multiplied to the Chebyshev coefficients and summed to obtain approximations to the given function at the new grid points.

10.1 Program Text

Program Text (d02uzfe.f90)

10.2 Program Data

Program Data (d02uzfe.d)

10.3 Program Results

Program Results (d02uzfe.r)

D02 Chapter Contents
D02 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


D02XJF : NAG Library, Mark 26

D02 Chapter Contents
D02 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

D02XJF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
10 Example

1 Purpose

D02XJF interpolates components of the solution of a system of first-order ordinary differential equations from information provided by the integrators in Sub-chapter D02M–N.

2 Specification

SUBROUTINE D02XJF ( XSOL, SOL, M, YSAV, LDYSAV, SDYSAV, NEQ, X, NQU, HU, H, IFAIL)
INTEGER | M, LDYSAV, SDYSAV, NEQ, NQU, IFAIL
REAL (KIND=nag_wp) | XSOL, SOL(M), YSAV(LDYSAV,SDYSAV), X, HU, H

3 Description

D02XJF evaluates the first m components of the solution of a system of ordinary differential equations at any point using natural polynomial interpolation based on information generated by the integrator. This information must be passed unchanged to D02XJF. D02XJF should not normally be used to extrapolate outside the range of values obtained from the above routines.

4 References

None.

5 Arguments

1:   XSOL – REAL (KIND=nag_wp)Input
On entry: the point at which the first m components of the solution are to be evaluated. XSOL should not be an extrapolation point, that is XSOL should satisfy XSOL-X×HU≤0.0. Extrapolation is permitted but not recommended.
2:   SOL M – REAL (KIND=nag_wp) arrayOutput
On exit: the calculated value of the ith component of the solution at XSOL, for i=1,2,…,m.
3:   M – INTEGERInput
On entry: m, the number of components of the solution whose values at XSOL are required. The first M components are evaluated.
Constraint: 1≤M≤NEQ.
4:   YSAV LDYSAVSDYSAV – REAL (KIND=nag_wp) arrayInput
On entry: the values provided in the argument YSAV on return from the integrator.
5:   LDYSAV – INTEGERInput
On entry: the value used for the argument LDYSAV when calling the integrator.
Constraint: LDYSAV≥1.
6:   SDYSAV – INTEGERInput
On entry: the value used for the argument SDYSAV when calling the integrator.
Constraint: SDYSAV≥NQU+1.
7:   NEQ – INTEGERInput
On entry: the value used for the argument NEQ when calling the integrator.
Constraint: 1≤NEQ≤LDYSAV.
8:   X – REAL (KIND=nag_wp)Input
On entry: the latest value at which the solution has been computed, as provided in the argument TCUR on return from the optional output D02NYF.
9:   NQU – INTEGERInput
On entry: the order of the method used up to the latest value at which the solution has been computed, as provided in the argument NQU on return from the optional output D02NYF.
Constraint: NQU≥1.
10:   HU – REAL (KIND=nag_wp)Input
On entry: the last successful step used, that is the step used in the integration to get to X, as provided in the argument HU on return from the optional output D02NYF.
11:   H – REAL (KIND=nag_wp)Input
On entry: the next step size to be attempted in the integration, as provided in the argument H on return from the optional output D02NYF.
12:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).
If D02XJF is to be used for extrapolation, IFAIL must be set to 1 before entry. It is then essential to test the value of IFAIL on exit for IFAIL=1 or 2.

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, | M<1,
or | NEQ<1,
or | LDYSAV<1,
or | NEQ>LDYSAV,
or | M>NEQ,
or | NQU<1,
or | SDYSAV<NQU+1.
IFAIL=2
On entry, HU=0.0 or H=0.0. This error can only occur if H and HU have been changed by you or possibly if the integrator has failed before calling D02XJF.
IFAIL=3
D02XJF has been called for extrapolation. Before returning with this error exit, the value of the solution at XSOL is calculated and placed in SOL.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

The solution values returned will be of a similar accuracy to those computed by the integrator.

8 Parallelism and Performance

D02XJF is not threaded in any implementation.

9 Further Comments

D02XJF is that employed for prediction purposes internally by the integrator. It is supplied for purposes of consistency only. You are recommended to employ the C 1 interpolant provided by D02XKF wherever possible.

10 Example

See Section 10 in D02NGF.
D02 Chapter Contents
D02 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


D02XKF : NAG Library, Mark 26

D02 Chapter Contents
D02 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

D02XKF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
10 Example

1 Purpose

D02XKF interpolates components of the solution of a system of first-order ordinary differential equations from information provided by the integrators in Sub-chapter D02M–N. It provides C 1 interpolation suitable for general use.

2 Specification

SUBROUTINE D02XKF ( XSOL, SOL, M, YSAV, LDYSAV, SDYSAV, ACOR, NEQ, X, NQU, HU, H, IFAIL)
INTEGER | M, LDYSAV, SDYSAV, NEQ, NQU, IFAIL
REAL (KIND=nag_wp) | XSOL, SOL(M), YSAV(LDYSAV,SDYSAV), ACOR(NEQ), X, HU, H

3 Description

D02XKF evaluates the first m components of the solution of a system of ordinary differential equations at any point using C 1 polynomial interpolation based on information generated by the integrator. This information must be passed unchanged to D02XKF. D02XKF should not normally be used to extrapolate outside the range of values obtained from the above routines.
It may be used with the D02N routines only when the BDF integration method is being employed (setup routine D02NVF), provided the Petzold error test was not selected.

4 References

None.

5 Arguments

1:   XSOL – REAL (KIND=nag_wp)Input
On entry: the point at which the first m components of the solution are to be evaluated. XSOL should not be an extrapolation point, that is XSOL should satisfy XSOL-X×HU≤0.0. Extrapolation is permitted but not recommended.
2:   SOL M – REAL (KIND=nag_wp) arrayOutput
On exit: the calculated value of the ith component of the solution at XSOL, for i=1,2,…,m.
3:   M – INTEGERInput
On entry: the number of components of the solution whose values at XSOL are required. The first m components are evaluated.
Constraint: 1≤M≤NEQ.
4:   YSAV LDYSAVSDYSAV – REAL (KIND=nag_wp) arrayInput
On entry: the values provided in the argument YSAV on return from the integrator.
5:   LDYSAV – INTEGERInput
On entry: the value used for the argument LDYSAV when calling the integrator.
Constraint: LDYSAV≥1.
6:   SDYSAV – INTEGERInput
On entry: the value used for the argument SDYSAV when calling the integrator.
Constraint: SDYSAV≥NQU+1.
7:   ACOR NEQ – REAL (KIND=nag_wp) arrayInput
On entry: the value returned in position LDYSAV+50+i, for i=1,2,…,NEQ, of the argument RWORK returned by the integrator. If one of the direct communication D02N routines is being employed and D02XKF is to be used in MONITR, then ACOR i must contain the value given in position i,2 of the MONITR argument ACOR, for i=1,2,…,NEQ (e.g., see D02NBF).
8:   NEQ – INTEGERInput
On entry: the value used for the argument NEQ when calling the integrator.
Constraint: 1≤NEQ≤LDYSAV.
9:   X – REAL (KIND=nag_wp)Input
On entry: the latest value at which the solution has been computed, as provided in the argument TCUR on return from the optional output D02NYF.
10:   NQU – INTEGERInput
On entry: the order of the method used up to the latest value at which the solution has been computed, as provided in the argument NQU on return from the optional output D02NYF.
Constraint: NQU≥1.
11:   HU – REAL (KIND=nag_wp)Input
On entry: the last successful step used, that is the step used in the integration to get to X, as provided in the argument HU on return from the optional output D02NYF.
12:   H – REAL (KIND=nag_wp)Input
On entry: the next step size to be attempted in the integration, as provided in the argument H on return from the optional output D02NYF.
13:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).
If D02XKF is to be used for extrapolation, IFAIL must be set to 1 before entry. It is then essential to test the value of IFAIL on exit for IFAIL=1 or 2.

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, | M<1,
or | NEQ<1,
or | LDYSAV<1,
or | NEQ>LDYSAV,
or | M>NEQ,
or | NQU<1,
or | SDYSAV<NQU+1,
or | the BDF integrator was not previously used,
or | the Petzold error test, if applicable, was used.
IFAIL=2
On entry, HU=0.0 or H=0.0. This error can only occur if H and HU have been changed by you or possibly if the integrator has failed before calling D02XKF.
IFAIL=3
D02XKF has been called for extrapolation. Before returning with this error exit, the value of the solution at XSOL is calculated and placed in SOL.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

The solution values returned will be of a similar accuracy to those computed by the integrator.

8 Parallelism and Performance

D02XKF is not thread safe and should not be called from a multithreaded user program. Please see Section 3.12.1 in How to Use the NAG Library and its Documentation for more information on thread safety.
D02XKF is not threaded in any implementation.

9 Further Comments

D02XKF provides a C 1 interpolant and as such is ideal for most applications, for example for tabulation and root-finding. In general D02XKF should be preferred to D02XJF for interpolation as the latter provides only a C 0 interpolant. D02XJF is the natural interpolant employed by the BDF method and it is supplied only to permit you to reproduce the internal values used by the integrator.

10 Example

See Section 10 in D02NDF and D02NMF.
D02 Chapter Contents
D02 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


D02ZAF : NAG Library, Mark 26

D02 Chapter Contents
D02 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

D02ZAF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

D02ZAF calculates the weighted norm of the local error estimate from inside a MONITR called from an integrator in Sub-chapter D02M–N (e.g., see D02NBF).

2 Specification

FUNCTION D02ZAF ( NEQ, V, W, IFAIL)
REAL (KIND=nag_wp) D02ZAF
INTEGER | NEQ, IFAIL
REAL (KIND=nag_wp) | V(NEQ), W(NEQ)

3 Description

D02ZAF is for use with the direct communication integrators D02NBF, D02NCF, D02NDF, D02NGF, D02NHF and D02NJF and the reverse communication integrators D02NMF and D02NNF. It must be used only inside MONITR (if this option is selected) for the direct communication routines or on the equivalent return for the reverse communication routines. It may be used to evaluate the norm of the scaled local error estimate, v, where the weights used are contained in w and the norm used is as defined by an earlier call to the integrator setup routine (D02MVF, D02NVF or D02NWF). Its use is described under the description of MONITR in the specifications for the direct communication integrators mentioned above.

4 References

None.

5 Arguments

1:   NEQ – INTEGERInput
On entry: the number of differential equations, as defined for the integrator being used.
2:   V NEQ – REAL (KIND=nag_wp) arrayInput
On entry: the vector, the weighted norm of which is to be evaluated by D02ZAF. V is calculated internally by the integrator being used.
3:   W NEQ – REAL (KIND=nag_wp) arrayInput
On entry: the weights, calculated internally by the integrator, to be used in the norm evaluation.
4:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, because for this routine the values of the output arguments may be useful even if IFAIL≠0 on exit, the recommended value is -1. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Note: D02ZAF may return useful information for one or more of the following detected errors or warnings.
Errors or warnings detected by the routine:
IFAIL=1
The value of the norm would either overflow or is close to overflowing. A value close to the square root of the largest number on the computer is returned.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

The result is calculated close to machine precision except in the case when the routine exits with IFAIL=1.

8 Parallelism and Performance

D02ZAF is not thread safe and should not be called from a multithreaded user program. Please see Section 3.12.1 in How to Use the NAG Library and its Documentation for more information on thread safety.
D02ZAF is not threaded in any implementation.

9 Further Comments

D02ZAF should only be used within MONITR associated with the integrators in Sub-chapter D02M–N (e.g., see D02NBF). Its use and only valid calling sequence are fully documented in the description of MONITR in the routine documents for the integrators.

10 Example

This example solves the well-known stiff Robertson problem
a′ = -0.04 a + 1.0 E 4 bc b′ = 0.04 a - 1.0 E 4 bc - 3.0 E 7⁢b 2 c′ = 3.0 E 7⁢b 2
over the range 0,10 with initial conditions a=1.0 and b=c=0.0 using scalar error control (ITOL=1) and computation of the solution at TOUT=10.0 with TCRIT (e.g., see D02MVF) set to 10.0 (ITASK=4). A BDF integrator (setup routine D02NVF) is used and a modified Newton method is selected. This example illustrates the use of D02ZAF within a monitor routine MONITR to output intermediate results during the integration. The same problem is solved in the example program for D02NBF where no monitoring was performed and so no intermediate solution information is output.

10.1 Program Text

Program Text (d02zafe.f90)

10.2 Program Data

Program Data (d02zafe.d)

10.3 Program Results

Program Results (d02zafe.r)

D02 Chapter Contents
D02 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


D03 Chapter Contents : NAG Library Manual, Mark 26

D03 Chapter Introduction
NAG Library Manual

NAG Library Chapter Contents

D03 – Partial Differential Equations

D03 Chapter Introduction – a description of the Chapter and an overview of the algorithms available

Routine Name | Mark of Introduction | Purpose
D03EAF Example Text Example Data | 7 | nagf_pde_2d_laplace Elliptic PDE, Laplace's equation, two-dimensional arbitrary domain
D03EBF Example Text Example Data Example Plot | 7 | nagf_pde_2d_ellip_fd Elliptic PDE, solution of finite difference equations by SIP, five-point two-dimensional molecule, iterate to convergence
D03ECF Example Text Example Data Example Plot | 8 | nagf_pde_3d_ellip_fd Elliptic PDE, solution of finite difference equations by SIP for seven-point three-dimensional molecule, iterate to convergence
D03EDF Example Text Example Data Example Plot | 12 | nagf_pde_2d_ellip_mgrid Elliptic PDE, solution of finite difference equations by a multigrid technique
D03EEF Example Text Example Data Example Plot | 13 | nagf_pde_2d_ellip_discret Discretize a second-order elliptic PDE on a rectangle
D03FAF Example Text Example Data | 14 | nagf_pde_3d_ellip_helmholtz Elliptic PDE, Helmholtz equation, three-dimensional Cartesian coordinates
D03MAF Example Text Example Data Example Plot | 7 | nagf_pde_2d_triangulate Triangulation of plane region
D03NCF Example Text Example Data Example Plot | 20 | nagf_pde_1d_blackscholes_fd Finite difference solution of the Black–Scholes equations
D03NDF Example Text Example Data Example Plot | 20 | nagf_pde_1d_blackscholes_closed Analytic solution of the Black–Scholes equations
D03NEF Example Text Example Data Example Plot | 20 | nagf_pde_1d_blackscholes_means Compute average values for D03NDF
D03PCA Example Text Example Data Example Plot | 20 | nagf_pde_1d_parab_fd General system of parabolic PDEs, method of lines, finite differences, one space variable
D03PCF Example Text Example Data Example Plot | 15 | nagf_pde_1d_parab_fd_old General system of parabolic PDEs, method of lines, finite differences, one space variable
D03PDA Example Text Example Data Example Plot | 20 | nagf_pde_1d_parab_coll General system of parabolic PDEs, method of lines, Chebyshev C 0 collocation, one space variable
D03PDF Example Text Example Data Example Plot | 15 | nagf_pde_1d_parab_coll_old General system of parabolic PDEs, method of lines, Chebyshev C 0 collocation, one space variable
D03PEF Example Text Example Data Example Plot | 16 | nagf_pde_1d_parab_keller General system of first-order PDEs, method of lines, Keller box discretization, one space variable
D03PFF Example Text Example Data | 17 | nagf_pde_1d_parab_convdiff General system of convection-diffusion PDEs with source terms in conservative form, method of lines, upwind scheme using numerical flux function based on Riemann solver, one space variable
D03PHA Example Text Example Data Example Plot | 20 | nagf_pde_1d_parab_dae_fd General system of parabolic PDEs, coupled DAEs, method of lines, finite differences, one space variable
D03PHF Example Text Example Data Example Plot | 15 | nagf_pde_1d_parab_dae_fd_old General system of parabolic PDEs, coupled DAEs, method of lines, finite differences, one space variable
D03PJA Example Text Example Data Example Plot | 20 | nagf_pde_1d_parab_dae_coll General system of parabolic PDEs, coupled DAEs, method of lines, Chebyshev C 0 collocation, one space variable
D03PJF Example Text Example Data Example Plot | 15 | nagf_pde_1d_parab_dae_coll_old General system of parabolic PDEs, coupled DAEs, method of lines, Chebyshev C 0 collocation, one space variable
D03PKF Example Text Example Data Example Plot | 16 | nagf_pde_1d_parab_dae_keller General system of first-order PDEs, coupled DAEs, method of lines, Keller box discretization, one space variable
D03PLF Example Text Example Data Example Plot | 17 | nagf_pde_1d_parab_convdiff_dae General system of convection-diffusion PDEs with source terms in conservative form, coupled DAEs, method of lines, upwind scheme using numerical flux function based on Riemann solver, one space variable
D03PPA Example Text Example Data Example Plot | 20 | nagf_pde_1d_parab_remesh_fd General system of parabolic PDEs, coupled DAEs, method of lines, finite differences, remeshing, one space variable
D03PPF Example Text Example Data Example Plot | 16 | nagf_pde_1d_parab_remesh_fd_old General system of parabolic PDEs, coupled DAEs, method of lines, finite differences, remeshing, one space variable
D03PRF Example Text Example Data Example Plot | 16 | nagf_pde_1d_parab_remesh_keller General system of first-order PDEs, coupled DAEs, method of lines, Keller box discretization, remeshing, one space variable
D03PSF Example Text Example Data Example Plot | 17 | nagf_pde_1d_parab_convdiff_remesh General system of convection-diffusion PDEs, coupled DAEs, method of lines, upwind scheme, remeshing, one space variable
D03PUF | 17 | nagf_pde_1d_parab_euler_roe Roe's approximate Riemann solver for Euler equations in conservative form, for use with D03PFF, D03PLF and D03PSF
D03PVF | 17 | nagf_pde_1d_parab_euler_osher Osher's approximate Riemann solver for Euler equations in conservative form, for use with D03PFF, D03PLF and D03PSF
D03PWF Example Text Example Data Example Plot | 18 | nagf_pde_1d_parab_euler_hll Modified HLL Riemann solver for Euler equations in conservative form, for use with D03PFF, D03PLF and D03PSF
D03PXF Example Text Example Data Example Plot | 18 | nagf_pde_1d_parab_euler_exact Exact Riemann solver for Euler equations in conservative form, for use with D03PFF, D03PLF and D03PSF
D03PYF | 15 | nagf_pde_1d_parab_coll_interp PDEs, spatial interpolation with D03PDF/D03PDA or D03PJF/D03PJA
D03PZF | 15 | nagf_pde_1d_parab_fd_interp PDEs, spatial interpolation with D03PCF/D03PCA, D03PEF, D03PFF, D03PHF/D03PHA, D03PKF, D03PLF, D03PPF/D03PPA, D03PRF or D03PSF
D03RAF Example Text Example Data Example Plot | 18 | nagf_pde_2d_gen_order2_rectangle General system of second-order PDEs, method of lines, finite differences, remeshing, two space variables, rectangular region
D03RBF Example Text Example Data | 18 | nagf_pde_2d_gen_order2_rectilinear General system of second-order PDEs, method of lines, finite differences, remeshing, two space variables, rectilinear region
D03RYF | 18 | nagf_pde_2d_gen_order2_checkgrid Check initial grid data in D03RBF
D03RZF | 18 | nagf_pde_2d_gen_order2_rectilinear_extractgrid Extract grid data from D03RBF
D03UAF Example Text Example Data Example Plot | 7 | nagf_pde_2d_ellip_fd_iter Elliptic PDE, solution of finite difference equations by SIP, five-point two-dimensional molecule, one iteration
D03UBF Example Text Example Data Example Plot | 8 | nagf_pde_3d_ellip_fd_iter Elliptic PDE, solution of finite difference equations by SIP, seven-point three-dimensional molecule, one iteration
D03 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


D03EAF : NAG Library, Mark 26

D03 Chapter Contents
D03 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

D03EAF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

D03EAF solves Laplace's equation in two dimensions for an arbitrary domain bounded internally or externally by one or more closed contours, given the value of either the unknown function or its normal derivative (into the domain) at each point of the boundary.

2 Specification

SUBROUTINE D03EAF ( STAGE1, EXT, DORM, N, P, Q, X, Y, N1P1, PHI, PHID, ALPHA, C, LDC, NP4, ICINT, NP1, IFAIL)
INTEGER | N, N1P1, LDC, NP4, ICINT(NP1), NP1, IFAIL
REAL (KIND=nag_wp) | P, Q, X(N1P1), Y(N1P1), PHI(N), PHID(N), ALPHA, C(LDC,NP4)
LOGICAL | STAGE1, EXT, DORM

3 Description

D03EAF uses an integral equation method, based upon Green's formula, which yields the solution, ϕ, within the domain, given its value or that of its normal derivative at each point of the boundary (except possibly at a finite number of discrete points). The solution is obtained in two stages. The first, which is executed once only, determines the complementary boundary values, i.e., ϕ, where its normal derivative is known and vice versa. The second stage is entered once for each point at which the solution is required.
The boundary is divided into a number of intervals in each of which ϕ and its normal derivative are approximated by constants. Of these half are evaluated by applying the given boundary conditions at one ‘nodal’ point within each interval while the remainder are determined (in stage 1) by solving a set of simultaneous linear equations. Here this is achieved by means of auxiliary routine F08AAF (DGELS), which will yield the least squares solution of an overdetermined system of equations as well as the unique solution of a square nonsingular system.
In exterior domains the solution behaves as c+s   log r + O 1/r as r tends to infinity, where c is a constant, s is the total integral of the normal derivative around the boundary and r is the radial distance from the origin of coordinates. For the Neumann problem (when the normal derivative is given along the whole boundary) s is fixed by the boundary conditions whilst c is chosen by you. However, for a Dirichlet problem (when ϕ is given along the whole boundary) or for a mixed problem, stage 1 produces a value of c for which s=0; then as r tends to infinity the solution tends to the constant c.

4 References

Symm G T and Pitfield R A (1974) Solution of Laplace's equation in two dimensions NPL Report NAC 44 National Physical Laboratory

5 Arguments

1:   STAGE1 – LOGICALInput
On entry: indicates whether the routine call is for stage 1 of the computation as defined in Section 3.
STAGE1=.TRUE.
The call is for stage 1.
STAGE1=.FALSE.
The call is for stage 2.
2:   EXT – LOGICALInput
On entry: the form of the domain. If EXT=.TRUE., the domain is unbounded. Otherwise the domain is an interior one.
3:   DORM – LOGICALInput
On entry: the form of the boundary conditions. If DORM=.TRUE., then the problem is a Dirichlet or mixed boundary value problem. Otherwise it is a Neumann problem.
4:   N – INTEGERInput
On entry: the number of intervals into which the boundary is divided (see Sections 7 and 9).
5:   P – REAL (KIND=nag_wp)Input
6:   Q – REAL (KIND=nag_wp)Input
On entry: to stage 2, P and Q must specify the x and y coordinates respectively of a point at which the solution is required.
When STAGE1 is .TRUE., P and Q are ignored.
7:   X N1P1 – REAL (KIND=nag_wp) arrayInput
8:   Y N1P1 – REAL (KIND=nag_wp) arrayInput
On entry: the x and y coordinates respectively of points on the one or more closed contours which define the domain of the problem.
Note: each contour is described in such a manner that the subscripts of the coordinates increase when the domain is kept on the left. The final point on each contour coincides with the first and, if a further contour is to be described, the coordinates of this point are repeated in the arrays. In this way each interval is defined by three points, the second of which (the nodal point) always has an even subscript. In the case of the interior Neumann problem, the outermost boundary contour must be given first, if there is more than one.
9:   N1P1 – INTEGERInput
On entry: the value 2⁢N+M-1, where M denotes the number of closed contours which make up the boundary.
10:   PHI N – REAL (KIND=nag_wp) arrayInput/Output
On entry: for stage 1, PHI must contain the nodal values of ϕ or its normal derivative (into the domain) as prescribed in each interval. For stage 2 it must retain its output values from stage 1.
On exit: from stage 1, it contains the constants which approximate ϕ in each interval. It remains unchanged on exit from stage 2.
11:   PHID N – REAL (KIND=nag_wp) arrayInput/Output
On entry: for stage 1, PHID i must hold the value 0.0 or 1.0 accordingly as PHI i contains a value of ϕ or its normal derivative, for i=1,2,…,N. For stage 2 it must retain its output values from stage 1.
On exit: from stage 1, PHID contains the constants which approximate the normal derivative of ϕ in each interval. It remains unchanged on exit from stage 2.
12:   ALPHA – REAL (KIND=nag_wp)Input/Output
On entry: for stage 1, the use of ALPHA depends on the nature of the problem:
  • if DORM=.TRUE., ALPHA need not be set;
  • if DORM=.FALSE. and EXT=.TRUE., ALPHA must contain the prescribed constant c (see Section 3);
  • if DORM=.FALSE. and EXT=.FALSE., ALPHA must contain an appropriate value (often zero) for the integral of ϕ around the outermost boundary.
For stage 2, on every call ALPHA must contain the value returned at stage 1.
On exit: from stage 1:
  • if EXT=.FALSE., ALPHA contains 0.0;
  • if EXT=.TRUE. and DORM=.FALSE. ALPHA is unchanged;
  • if EXT=.TRUE. and DORM=.TRUE. ALPHA contains a computed estimate for c.
From stage 2:
  • ALPHA contains the computed value of ϕ at the point (P,Q).
13:   C LDCNP4 – REAL (KIND=nag_wp) arrayWorkspace
14:   LDC – INTEGERInput
On entry: the first dimension of the array C as declared in the (sub)program from which D03EAF is called.
Constraint: LDC≥N+1.
15:   NP4 – INTEGERInput
On entry: the value N+4.
16:   ICINT NP1 – INTEGER arrayWorkspace
17:   NP1 – INTEGERInput
On entry: the value N+1.
18:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
Invalid tolerance used in an internal call to an auxiliary routine:
ICINT 1=0
Indicates too large a tolerance.
ICINT 1>0
Indicates too small a tolerance.
Note: this error is only possible in stage 1, and the circumstances under which it may occur cannot be foreseen. In the event of a failure, it is suggested that you change the scale of the domain of the problem and apply the routine again.
IFAIL=2
Incorrect rank obtained by an auxiliary routine; ICINT 1 contains the computed rank.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

The accuracy of the computed solution depends upon how closely ϕ and its normal derivative may be approximated by constants in each interval of the boundary and upon how well the boundary contours are represented by polygons with vertices at the selected points X i,Y i , for i=1,2,…,2 N+M-1 .
Consequently, in general, the accuracy increases as the boundary is subdivided into smaller and smaller intervals and by comparing solutions for successive subdivisions one may obtain an indication of the error in these solutions.
Alternatively, since the point of maximum error always lies on the boundary of the domain, an estimate of the error may be obtained by computing ϕ at a sufficient number of points on the boundary where the true solution is known. The latter method (not applicable to the Neumann problem) is most useful in the case where ϕ alone is prescribed on the boundary (the Dirichlet problem).

8 Parallelism and Performance

D03EAF is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
D03EAF makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The time taken for stage 1, which is executed once only, is roughly proportional to N 2, being dominated by the time taken to compute the coefficients. The time for each stage 2 application is proportional to N.
The intervals into which the boundary is divided need not be of equal lengths.
For many practical problems useful results may be obtained with 20 to 40 intervals per boundary contour.

10 Example

An interior Neumann problem to solve Laplace's equation in the domain bounded externally by the triangle with vertices 3,0, -3,0 and 0,4, and internally by the triangle with vertices 2,1, (-2,1) and 0,3, given that the normal derivative of the solution ϕ is zero on each side of each triangle and, for uniqueness that the total integral of ϕ around the outer triangle is 16 (the length of the contour).
Figure 1
This trivial example has the obvious solution ϕ=1 throughout the domain. However it provides a useful illustration of data input for a doubly-connected domain. The solution is computed at one corner of each triangle and at one point inside the domain.
The program is written to handle any of the different types of problem that the routine can solve. The array dimensions must be increased for larger problems.

10.1 Program Text

Program Text (d03eafe.f90)

10.2 Program Data

Program Data (d03eafe.d)

10.3 Program Results

Program Results (d03eafe.r)

D03 Chapter Contents
D03 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


D03EBF : NAG Library, Mark 26

D03 Chapter Contents
D03 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

D03EBF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

D03EBF uses the Strongly Implicit Procedure to calculate the solution to a system of simultaneous algebraic equations of five-point molecule form on a two-dimensional topologically-rectangular mesh. (‘Topological’ means that a polar grid, for example r,θ, can be used, being equivalent to a rectangular box.)

2 Specification

SUBROUTINE D03EBF ( N1, N2, LDA, A, B, C, D, E, Q, T, APARAM, ITMAX, ITCOUN, ITUSED, NDIR, IXN, IYN, CONRES, CONCHN, RESIDS, CHNGS, WRKSP1, WRKSP2, WRKSP3, IFAIL)
INTEGER | N1, N2, LDA, ITMAX, ITCOUN, ITUSED, NDIR, IXN, IYN, IFAIL
REAL (KIND=nag_wp) | A(LDA,N2), B(LDA,N2), C(LDA,N2), D(LDA,N2), E(LDA,N2), Q(LDA,N2), T(LDA,N2), APARAM, CONRES, CONCHN, RESIDS(ITMAX), CHNGS(ITMAX), WRKSP1(LDA,N2), WRKSP2(LDA,N2), WRKSP3(LDA,N2)

3 Description

Given a set of simultaneous equations
Mt=q (1)
(which could be nonlinear) derived, for example, from a finite difference representation of a two-dimensional elliptic partial differential equation and its boundary conditions, the routine determines the values of the dependent variable t. q is a known vector of length n 1×n 2 and M is a square n 1×n 2 by n 1×n 2 matrix.
The equations must be of five-diagonal form:
a ijt i,j-1+b ijt i-1,j+c ijt ij+d ijt i+1,j+e ijt i,j+1=q ij
for i=1,2,…,n 1 and j=1,2,…,n 2, provided c ij≠0.0. Indeed, if c ij=0.0, then the equation is assumed to be
t ij=q ij.
For example, if n 1=3 and n 2=2, the equations take the form:
c 11 d 11 e 11 b 21 c 21 d 21 e 21 b 31 c 31 e 31 a 12 c 12 d 12 a 22 b 22 c 22 d 22 a 32 b 32 c 32 t 11 t 21 t 31 t 12 t 22 t 32 = q 11 q 21 q 31 q 12 q 22 q 32 .
The system is solved iteratively, from a starting approximation t 1 , by the formulae
r n =q-M t n M s n =r n t n+1 =t n +s n .
Thus r n is the residual of the nth approximate solution t n , and s n is the update change vector. The calling program supplies an initial approximation for the values of the dependent variable in the array T, the coefficients of the five-point molecule system of equations in the arrays A, B, C, D and E, and the source terms in the array Q. The routine derives the residual of the latest approximate solution and then uses the approximate LU factorization of the Strongly Implicit Procedure with the necessary acceleration argument adjustment by calling D03UAF at each iteration. D03EBF combines the newly derived change with the old approximation to obtain the new approximate solution for t. The new solution is checked for convergence against the user-supplied convergence criteria and if these have not been achieved the iterative cycle is repeated. Convergence is based on both the maximum absolute normalized residuals (calculated with reference to the previous approximate solution as these are calculated at the commencement of each iteration) and on the maximum absolute change made to the values of t.
Problems in topologically non-rectangular regions can be solved using the routine by surrounding the region by a circumscribing topological rectangle. The equations for the nodal values external to the region of interest are set to zero (i.e., c ij=t ij=0) and the boundary conditions are incorporated into the equations for the appropriate nodes.
If there is no better initial approximation when starting the iterative cycle, an array of all zeros can be used as the initial approximation.
The routine can be used to solve linear elliptic equations in which case the arrays A, B, C, D, E and Q are constants and for which a single call provides the required solution. It can also be used to solve nonlinear elliptic equations in which case some or all of these arrays may require updating during the progress of the iterations as more accurate solutions are derived. The routine will then have to be called repeatedly in an outer iterative cycle. Dependent on the nonlinearity, some under relaxation of the coefficients and/or source terms may be needed during their recalculation using the new estimates of the solution.
The routine can also be used to solve each step of a time-dependent parabolic equation in two space dimensions. The solution at each time step can be expressed in terms of an elliptic equation if the Crank–Nicolson or other form of implicit time integration is used.
Neither diagonal dominance, nor positive-definiteness, of the matrix M formed from the arrays A, B, C, D, E is necessary to ensure convergence.
For problems in which the solution is not unique in the sense that an arbitrary constant can be added to the solution, for example Laplace's equation with all Neumann boundary conditions, an argument is incorporated so that the solution can be rescaled by subtracting a specified nodal value from the whole solution t after the completion of every iteration to keep rounding errors to a minimum for those cases when the convergence is slow.

4 References

Jacobs D A H (1972) The strongly implicit procedure for the numerical solution of parabolic and elliptic partial differential equations Note RD/L/N66/72 Central Electricity Research Laboratory
Stone H L (1968) Iterative solution of implicit approximations of multi-dimensional partial differential equations SIAM J. Numer. Anal. 5 530–558

5 Arguments

1:   N1 – INTEGERInput
On entry: the number of nodes in the first coordinate direction, n 1.
Constraint: N1>1.
2:   N2 – INTEGERInput
On entry: the number of nodes in the second coordinate direction, n 2.
Constraint: N2>1.
3:   LDA – INTEGERInput
On entry: the first dimension of the arrays A, B, C, D, E, Q, T, WRKSP1, WRKSP2 and WRKSP3 as declared in the (sub)program from which D03EBF is called.
Constraint: LDA≥N1.
4:   A LDAN2 – REAL (KIND=nag_wp) arrayInput
On entry: A ij must contain the coefficient of the ‘southerly’ term involving t i,j-1 in the i,jth equation of the system (1), for i=1,2,…,N1 and j=1,2,…,N2. The elements of A, for j=1, must be zero after incorporating the boundary conditions, since they involve nodal values from outside the rectangle.
5:   B LDAN2 – REAL (KIND=nag_wp) arrayInput
On entry: B ij must contain the coefficient of the ‘westerly’ term involving t i-1,j in the i,jth equation of the system (1), for i=1,2,…,N1 and j=1,2,…,N2. The elements of B, for i=1, must be zero after incorporating the boundary conditions, since they involve nodal values from outside the rectangle.
6:   C LDAN2 – REAL (KIND=nag_wp) arrayInput
On entry: C ij must contain the coefficient of the ‘central’ term involving t ij in the i,jth equation of the system (1), for i=1,2,…,N1 and j=1,2,…,N2. The elements of C are checked to ensure that they are nonzero. If any element is found to be zero, the corresponding algebraic equation is assumed to be t ij=q ij. This feature can be used to define the equations for nodes at which, for example, Dirichlet boundary conditions are applied, or for nodes external to the problem of interest, by setting C ij=0.0 at appropriate points, and the corresponding value of Q ij to the appropriate value, namely the prescribed value of T ij in the Dirichlet case or zero at an external point.
7:   D LDAN2 – REAL (KIND=nag_wp) arrayInput
On entry: D ij must contain the coefficient of the ‘easterly’ term involving t i+1,j in the i,jth equation of the system (1), for i=1,2,…,N1 and j=1,2,…,N2. The elements of D, for i=N1, must be zero after incorporating the boundary conditions, since they involve nodal values from outside the rectangle.
8:   E LDAN2 – REAL (KIND=nag_wp) arrayInput
On entry: E ij must contain the coefficient of the ‘northerly’ term involving t i,j+1 in the i,jth equation of the system (1), for i=1,2,…,N1 and j=1,2,…,N2. The elements of E, for j=N2 must be zero after incorporating the boundary conditions, since they involve nodal values from outside the rectangle.
9:   Q LDAN2 – REAL (KIND=nag_wp) arrayInput
On entry: Q ij must contain q ij, for i=1,2,…,N1 and j=1,2,…,N2, i.e., the source term values at the nodal points for the system (1).
10:   T LDAN2 – REAL (KIND=nag_wp) arrayInput/Output
On entry: T ij must contain the element t ij of the approximate solution to the equations supplied by the calling program as an initial starting value, for i=1,2,…,N1 and j=1,2,…,N2.
If no better approximation is known, an array of zeros can be used.
On exit: the solution derived by the routine.
11:   APARAM – REAL (KIND=nag_wp)Input
On entry: the iteration acceleration factor. A value of 1.0 is adequate for most typical problems. However, if convergence is slow, the value can be reduced, typically to 0.2 or 0.1. If divergence is obtained, the value can be increased, typically to 2.0, 5.0 or 10.0.
Constraint: 0.0<APARAM≤ N1-1 2+ N2-1 2/2.0.
12:   ITMAX – INTEGERInput
On entry: the maximum number of iterations to be used by the routine in seeking the solution. A reasonable value might be 30 if N1=N2=10 or 100 if N1=N2=50.
13:   ITCOUN – INTEGERInput/Output
On entry: on the first call of D03EBF, ITCOUN must be set to 0. On subsequent entries, its value must be unchanged from the previous call.
On exit: its value is increased by the number of iterations used on this call (namely ITUSED). It therefore stores the accumulated number of iterations actually used. For subsequent calls for the same problem, i.e., with the same N1 and N2 but possibly different coefficients and/or source terms, as occur with nonlinear systems or with time-dependent systems, ITCOUN is the accumulated number of iterations. This applies to the second and subsequent calls to D03EBF. In this way a suitable cycling of the sequence of iteration arguments is obtained in the calls to D03UAF.
14:   ITUSED – INTEGEROutput
On exit: the number of iterations actually used on that call.
15:   NDIR – INTEGERInput
On entry: indicates whether or not the system of equations has a unique solution. For systems which have a unique solution, NDIR must be set to any nonzero value. For systems derived from, for example, Laplace's equation with all Neumann boundary conditions, i.e., problems in which an arbitrary constant can be added to the solution, NDIR should be set to 0 and the values of the next two arguments must be specified. For such problems the routine subtracts the value of the function derived at the node (IXN, IYN) from the whole solution after each iteration to reduce the possibility of large rounding errors. You must also ensure that for such problems the appropriate consistency condition on the source terms Q is satisfied.
16:   IXN – INTEGERInput
On entry: is ignored unless NDIR is equal to zero, in which case it must specify the first index of the nodal point at which the solution is to be set to zero. The node should not correspond to a corner node, or to a node external to the region of interest.
17:   IYN – INTEGERInput
On entry: is ignored unless NDIR is equal to zero, in which case it must specify the second index of the nodal point at which the solution is to be set to zero. The node should not correspond to a corner node, or to a node external to the region of interest.
18:   CONRES – REAL (KIND=nag_wp)Input
On entry: the convergence criterion to be used on the maximum absolute value of the normalized residual vector components. The latter is defined as the residual of the algebraic equation divided by the central coefficient when the latter is not equal to 0.0, and defined as the residual when the central coefficient is zero.
Clearly CONRES should not be less than a reasonable multiple of the machine precision.
19:   CONCHN – REAL (KIND=nag_wp)Input
On entry: the convergence criterion to be used on the maximum absolute value of the change made at each iteration to the elements of the array T, namely the dependent variable. Clearly CONCHN should not be less than a reasonable multiple of the machine precision multiplied by the maximum value of T attained.
Convergence is achieved when both the convergence criteria are satisfied. You can therefore set convergence on either the residual or on the change, or (as is recommended) on a requirement that both are below prescribed limits.
20:   RESIDS ITMAX – REAL (KIND=nag_wp) arrayOutput
On exit: the maximum absolute value of the residuals calculated at the ith iteration, for i=1,2,…,ITUSED. If you want to know the maximum absolute residual of the solution which is returned you must calculate this in the calling program. The sequence of values RESIDS indicates the rate of convergence.
21:   CHNGS ITMAX – REAL (KIND=nag_wp) arrayOutput
On exit: the maximum absolute value of the changes made to the components of the dependent variable T at the ith iteration, for i=1,2,…,ITUSED. The sequence of values CHNGS indicates the rate of convergence.
22:   WRKSP1 LDAN2 – REAL (KIND=nag_wp) arrayWorkspace
23:   WRKSP2 LDAN2 – REAL (KIND=nag_wp) arrayWorkspace
24:   WRKSP3 LDAN2 – REAL (KIND=nag_wp) arrayWorkspace
25:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, | N1<2,
or | N2<2.
IFAIL=2
On entry, LDA<N1.
IFAIL=3
On entry, APARAM≤0.0.
IFAIL=4
On entry, APARAM> N1-1 2+ N2-1 2/2.0.
IFAIL=5
Convergence was not achieved after ITMAX iterations.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

The improvement in accuracy for each iteration depends on the size of the system and on the condition of the update matrix characterised by the five-diagonal coefficient arrays. The ultimate accuracy obtainable depends on the above factors and on the machine precision. The rate of convergence obtained with the Strongly Implicit Procedure is not always smooth because of the cyclic use of nine acceleration arguments. The convergence may become slow with very large problems, for example when N1=N2=60. The final accuracy may be judged approximately from the rate of convergence determined from the sequence of values returned in CHNGS and the magnitude of the maximum absolute value of the change vector on the last iteration stored in CHNGS ITUSED.

8 Parallelism and Performance

D03EBF is not threaded in any implementation.

9 Further Comments

The time taken per iteration is approximately proportional to N1×N2.
Convergence may not always be obtained when the problem is very large and/or the coefficients of the equations have widely disparate values. The latter case is often associated with a near ill-conditioned matrix.

10 Example

This example solves Laplace's equation in a rectangle with a non-uniform grid spacing in the x and y coordinate directions and with Dirichlet boundary conditions specifying the function on the perimeter of the rectangle equal to
e 1.0+x/y n 2×cos y/y n 2.

10.1 Program Text

Program Text (d03ebfe.f90)

10.2 Program Data

Program Data (d03ebfe.d)

10.3 Program Results

Program Results (d03ebfe.r)

GnuplotProduced by GNUPLOT 4.6 patchlevel 3 Example Program Solution to Laplace's Equation using the Strongly Implicit Procedure on a Five-point Molecule Discretisation gnuplot_plot_1 gnuplot_plot_2 0 5 10 15 20 25 30 35 40 45 Y 0 2 4 6 8 10 12 14 16 X 0.5 0.6 0.7 0.8 0.9 1 1.1 1.2 1.3 1.4 1.5 U
D03 Chapter Contents
D03 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


D03ECF : NAG Library, Mark 26

D03 Chapter Contents
D03 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

D03ECF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

D03ECF uses the Strongly Implicit Procedure to calculate the solution to a system of simultaneous algebraic equations of seven-point molecule form on a three-dimensional topologically-rectangular mesh. (‘Topological’ means that a polar grid, for example, can be used if it is equivalent to a rectangular box.)

2 Specification

SUBROUTINE D03ECF ( N1, N2, N3, LDA, SDA, A, B, C, D, E, F, G, Q, T, APARAM, ITMAX, ITCOUN, ITUSED, NDIR, IXN, IYN, IZN, CONRES, CONCHN, RESIDS, CHNGS, WRKSP1, WRKSP2, WRKSP3, WRKSP4, IFAIL)
INTEGER | N1, N2, N3, LDA, SDA, ITMAX, ITCOUN, ITUSED, NDIR, IXN, IYN, IZN, IFAIL
REAL (KIND=nag_wp) | A(LDA,SDA,N3), B(LDA,SDA,N3), C(LDA,SDA,N3), D(LDA,SDA,N3), E(LDA,SDA,N3), F(LDA,SDA,N3), G(LDA,SDA,N3), Q(LDA,SDA,N3), T(LDA,SDA,N3), APARAM, CONRES, CONCHN, RESIDS(ITMAX), CHNGS(ITMAX), WRKSP1(LDA,SDA,N3), WRKSP2(LDA,SDA,N3), WRKSP3(LDA,SDA,N3), WRKSP4(LDA,SDA,N3)

3 Description

Given a set of simultaneous equations
Mt=q (1)
(which could be nonlinear) derived, for example, from a finite difference representation of a three-dimensional elliptic partial differential equation and its boundary conditions, the routine determines the values of the dependent variable t. M is a square n 1×n 2×n 3 by n 1×n 2×n 3 matrix and q is a known vector of length n 1×n 2×n 3.
The equations must be of seven-diagonal form:
a ijkt ij,k-1+b ijkt i,j-1,k+c ijkt i-1,jk+d ijkt ijk+e ijkt i+1,jk+f ijkt i,j+1,k+g ijkt ij,k+1=q ijk
for i=1,2,…,n 1, j=1,2,…,n 2 and k=1,2,…,n 3, provided that d ijk≠0.0.
Indeed, if d ijk=0.0, then the equation is assumed to be:
t ijk=q ijk.
The system is solved iteratively from a starting approximation t 1 by the formulae:
r n = q-M t n M s n = r n t n+1 = t n +s n .
Thus r n is the residual of the nth approximate solution t n , and s n is the update change vector.
The calling program supplies an initial approximation for the values of the dependent variable in the array T, the coefficients of the seven-point molecule system of equations in the arrays A, B, C, D, E, F and G, and the source terms in the array Q. The routine derives the residual of the latest approximate solution, and then uses the approximate LU factorization of the Strongly Implicit Procedure with the necessary acceleration argument adjustment by calling D03UBF at each iteration. D03ECF combines the newly derived change with the old approximation to obtain the new approximate solution for t. The new solution is checked for convergence against the user-supplied convergence criteria, and if these have not been satisfied, the iterative cycle is repeated. Convergence is based on both the maximum absolute normalized residuals (calculated with reference to the previous approximate solution as these are calculated at the commencement of each iteration) and on the maximum absolute change made to the values of t.
Problems in topologically non-rectangular-box-shaped regions can be solved using the routine by surrounding the region by a circumscribing topologically rectangular box. The equations for the nodal values external to the region of interest are set to zero (i.e., d ijk=t ijk=0) and the boundary conditions are incorporated into the equations for the appropriate nodes.
If there is no better initial approximation when starting the iterative cycle, one can use an array of zeros as the initial approximation.
The routine can be used to solve linear elliptic equations in which case the arrays A, B, C, D, E, F, G and Q remain constant and for which a single call provides the required solution. It can also be used to solve nonlinear elliptic equations, in which case some or all of these arrays may require updating during the progress of the iterations as more accurate solutions are derived. The routine will then have to be called repeatedly in an outer iterative cycle. Dependent on the nonlinearity, some under-relaxation of the coefficients and/or source terms may be needed during their recalculation using the new estimates of the solution.
The routine can also be used to solve each step of a time-dependent parabolic equation in three space dimensions. The solution at each time step can be expressed in terms of an elliptic equation if the Crank–Nicolson or other form of implicit time integration is used.
Neither diagonal dominance, nor positive-definiteness, of the matrix M formed from the arrays A, B, C, D, E, F and G is necessary to ensure convergence.
For problems in which the solution is not unique in the sense that an arbitrary constant can be added to the solution (for example Poisson's equation with all Neumann boundary conditions), an argument is incorporated so that the solution can be rescaled. A specified nodal value is subtracted from the whole solution t after the completion of every iteration. This keeps rounding errors to a minimum for those cases when convergence is slow. For such problems there is generally an associated compatibility condition. For the example mentioned this compatibility condition equates the total net source within the region (i.e., the source integrated over the region) with the total net outflow across the boundaries defined by the Neumann conditions (i.e., the normal derivative integrated along the whole boundary). It is very important that the algebraic equations derived to model such a problem implement accurately the compatibility condition. If they do not, a net source or sink is very likely to be represented by the set of algebraic equations and no steady-state solution of the equations exists.

4 References

Jacobs D A H (1972) The strongly implicit procedure for the numerical solution of parabolic and elliptic partial differential equations Note RD/L/N66/72 Central Electricity Research Laboratory
Stone H L (1968) Iterative solution of implicit approximations of multi-dimensional partial differential equations SIAM J. Numer. Anal. 5 530–558
Weinstein H G, Stone H L and Kwan T V (1969) Iterative procedure for solution of systems of parabolic and elliptic equations in three dimensions Industrial and Engineering Chemistry Fundamentals 8 281–287

5 Arguments

1:   N1 – INTEGERInput
On entry: the number of nodes in the first coordinate direction, n 1.
Constraint: N1>1.
2:   N2 – INTEGERInput
On entry: the number of nodes in the second coordinate direction, n 2.
Constraint: N2>1.
3:   N3 – INTEGERInput
On entry: the number of nodes in the third coordinate direction, n 3.
Constraint: N3>1.
4:   LDA – INTEGERInput
On entry: the first dimension of the arrays A, B, C, D, E, F, G, Q, T, WRKSP1, WRKSP2, WRKSP3 and WRKSP4 as declared in the (sub)program from which D03ECF is called.
Constraint: LDA≥N1.
5:   SDA – INTEGERInput
On entry: the second dimension of the arrays A, B, C, D, E, F, G, Q, T, WRKSP1, WRKSP2, WRKSP3 and WRKSP4 as declared in the (sub)program from which D03ECF is called.
Constraint: SDA≥N2.
6:   A LDASDAN3 – REAL (KIND=nag_wp) arrayInput
On entry: A ijk must contain the coefficient of t ij,k-1 in the i,j,kth equation of the system (1), for i=1,2,…,N1, j=1,2,…,N2 and k=1,2,…,N3. The elements of A, for k=1, must be zero after incorporating the boundary conditions, since they involve nodal values from outside the box.
7:   B LDASDAN3 – REAL (KIND=nag_wp) arrayInput
On entry: B ijk must contain the coefficient of t i,j-1,k in the i,j,kth equation of the system (1), for i=1,2,…,N1, j=1,2,…,N2 and k=1,2,…,N3. The elements of B, for j=1, must be zero after incorporating the boundary conditions, since they involve nodal values from outside the box.
8:   C LDASDAN3 – REAL (KIND=nag_wp) arrayInput
On entry: C ijk must contain the coefficient of t i-1,jk in the i,j,kth equation of the system (1), for i=1,2,…,N1, j=1,2,…,N2 and k=1,2,…,N3. The elements of C, for i=1, must be zero after incorporating the boundary conditions, since they involve nodal values from outside the box.
9:   D LDASDAN3 – REAL (KIND=nag_wp) arrayInput
On entry: D ijk must contain the coefficient of t ijk (the ‘central’ term) in the i,j,kth equation of the system (1), for i=1,2,…,N1, j=1,2,…,N2 and k=1,2,…,N3. The elements of D are checked to ensure that they are nonzero. If any element is found to be zero, the corresponding algebraic equation is assumed to be t ijk=q ijk. This feature can be used to define the equations for nodes at which, for example, Dirichlet boundary conditions are applied, or for nodes external to the problem of interest. Setting D ijk=0.0 at appropriate points, and the corresponding value of Q ijk to the appropriate value, namely the prescribed value of T ijk in the Dirichlet case, or to zero at an external point.
10:   E LDASDAN3 – REAL (KIND=nag_wp) arrayInput
On entry: E ijk must contain the coefficient of t i+1,jk in the i,j,kth equation of the system (1), for i=1,2,…,N1, j=1,2,…,N2 and k=1,2,…,N3. The elements of E, for i=N1, must be zero after incorporating the boundary conditions, since they involve nodal values from outside the box.
11:   F LDASDAN3 – REAL (KIND=nag_wp) arrayInput
On entry: F ijk must contain the coefficient of t i,j+1,k in the i,j,kth equation of the system (1), , for i=1,2,…,N1, j=1,2,…,N2 and k=1,2,…,N3. The elements of F, for j=N2, must be zero after incorporating the boundary conditions, since they involve nodal values from outside the box.
12:   G LDASDAN3 – REAL (KIND=nag_wp) arrayInput
On entry: G ijk must contain the coefficient of t ij,k+1 in the i,j,kth equation of the system (1), for i=1,2,…,N1, j=1,2,…,N2 and k=1,2,…,N3. The elements of G, for k=N3, must be zero after incorporating the boundary conditions, since they involve nodal values from outside the box.
13:   Q LDASDAN3 – REAL (KIND=nag_wp) arrayInput
On entry: Q ijk must contain q ijk, for i=1,2,…,N1, j=1,2,…,N2 and k=1,2,…,N3, i.e., the source-term values at the nodal points of the system (1).
14:   T LDASDAN3 – REAL (KIND=nag_wp) arrayInput/Output
On entry: T ijk must contain the element t ijk of an approximate solution to the equations, for i=1,2,…,N1, j=1,2,…,N2 and k=1,2,…,N3.
If no better approximation is known, an array of zeros can be used.
On exit: the solution derived by the routine.
15:   APARAM – REAL (KIND=nag_wp)Input
On entry: the iteration acceleration factor. A value of 1.0 is adequate for most typical problems. However, if convergence is slow, the value can be reduced, typically to 0.2 or 0.1. If divergence is obtained, the value can be increased, typically to 2.0, 5.0 or 10.0.
Constraint: 0.0<APARAM≤N1-1 2+N2-1 2+N3-1 2/3.0.
16:   ITMAX – INTEGERInput
On entry: the maximum number of iterations to be used by the routine in seeking the solution. A reasonable value might be 20 for a problem with 3000 nodes and convergence criteria of about 10-3 of the original residual and change.
17:   ITCOUN – INTEGERInput/Output
On entry: on the first call of D03ECF, ITCOUN must be set to 0. On subsequent entries, its value must be unchanged from the previous call.
On exit: its value is increased by the number of iterations used on this call (namely ITUSED). It therefore stores the accumulated number of iterations actually used.
For subsequent calls for the same problem, i.e., with the same N1, N2 and N3 but possibly different coefficients and/or source terms, as occur with nonlinear systems or with time-dependent systems, ITCOUN should not be reset, i.e., it must contain the accumulated number of iterations. In this way a suitable cycling of the sequence of iteration arguments is obtained in the calls to D03UBF.
18:   ITUSED – INTEGEROutput
On exit: the number of iterations actually used on that call.
19:   NDIR – INTEGERInput
On entry: indicates whether or not the system of equations has a unique solution. For systems which have a unique solution, NDIR must be set to any nonzero value. For systems derived from problems to which an arbitrary constant can be added to the solution, for example Poisson's equation with all Neumann boundary conditions, NDIR should be set to 0 and the values of the next three arguments must be specified. For such problems the routine subtracts the value of the function derived at the node (IXN, IYN, IZN) from the whole solution after each iteration to reduce the possibility of large rounding errors. You must also ensure for such problems that the appropriate compatibility condition on the source terms Q is satisfied. See the comments at the end of Section 3.
20:   IXN – INTEGERInput
On entry: is ignored unless NDIR is equal to zero, in which case it must specify the first index of the nodal point at which the solution is to be set to zero. The node should not correspond to a corner node, or to a node external to the region of interest.
21:   IYN – INTEGERInput
On entry: is ignored unless NDIR is equal to zero, in which case it must specify the second index of the nodal point at which the solution is to be set to zero. The node should not correspond to a corner node, or to a node external to the region of interest.
22:   IZN – INTEGERInput
On entry: is ignored unless NDIR is equal to zero, in which case it must specify the third index of the nodal point at which the solution is to be set to zero. The node should not correspond to a corner node, or to a node external to the region of interest.
23:   CONRES – REAL (KIND=nag_wp)Input
On entry: the convergence criterion to be used on the maximum absolute value of the normalized residual vector components. The latter is defined as the residual of the algebraic equation divided by the central coefficient when the latter is not equal to 0.0, and defined as the residual when the central coefficient is zero.
CONRES should not be less than a reasonable multiple of the machine precision.
24:   CONCHN – REAL (KIND=nag_wp)Input
On entry: the convergence criterion to be used on the maximum absolute value of the change made at each iteration to the elements of the array T, namely the dependent variable. CONCHN should not be less than a reasonable multiple of the machine accuracy multiplied by the maximum value of T attained.
Convergence is achieved when both the convergence criteria are satisfied. You can therefore set convergence on either the residual or on the change, or (as is recommended) on a requirement that both are below prescribed limits.
25:   RESIDS ITMAX – REAL (KIND=nag_wp) arrayOutput
On exit: the maximum absolute value of the residuals calculated at the ith iteration, for i=1,2,…,ITUSED. If the residual of the solution is sought you must calculate this in the subroutine from which D03ECF is called. The sequence of values RESIDS indicates the rate of convergence.
26:   CHNGS ITMAX – REAL (KIND=nag_wp) arrayOutput
On exit: the maximum absolute value of the changes made to the components of the dependent variable T at the ith iteration, for i=1,2,…,ITUSED. The sequence of values CHNGS indicates the rate of convergence.
27:   WRKSP1 LDASDAN3 – REAL (KIND=nag_wp) arrayWorkspace
28:   WRKSP2 LDASDAN3 – REAL (KIND=nag_wp) arrayWorkspace
29:   WRKSP3 LDASDAN3 – REAL (KIND=nag_wp) arrayWorkspace
30:   WRKSP4 LDASDAN3 – REAL (KIND=nag_wp) arrayWorkspace
31:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, because for this routine the values of the output arguments may be useful even if IFAIL≠0 on exit, the recommended value is -1. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Note: D03ECF may return useful information for one or more of the following detected errors or warnings.
Errors or warnings detected by the routine:
IFAIL=1
On entry, | N1<2,
or | N2<2,
or | N3<2.
IFAIL=2
On entry, | LDA<N1,
or | SDA<N2.
IFAIL=3
On entry, APARAM≤0.0.
IFAIL=4
On entry, APARAM>N1-1 2+N2-1 2+N3-1 2/3.0.
IFAIL=5
Convergence was not achieved after ITMAX iterations.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

The improvement in accuracy for each iteration depends on the size of the system and on the condition of the update matrix characterised by the seven-diagonal coefficient arrays. The ultimate accuracy obtainable depends on the above factors and on the machine precision. The rate of convergence obtained with the Strongly Implicit Procedure is not always smooth because of the cyclic use of nine acceleration arguments. The convergence may become slow with very large problems. The final accuracy obtained may be judged approximately from the rate of convergence determined from the sequence of values returned in the arrays RESIDS and CHNGS and the magnitude of the maximum absolute value of the change vector on the last iteration stored in CHNGS ITUSED.

8 Parallelism and Performance

D03ECF is not threaded in any implementation.

9 Further Comments

The time taken per iteration is approximately proportional to N1×N2×N3.
Convergence may not always be obtained when the problem is very large and/or the coefficients of the equations have widely disparate values. The latter case is often associated with a near ill-conditioned matrix.

10 Example

This example solves Laplace's equation in a rectangular box with a non-uniform grid spacing in the x, y, and z coordinate directions and with Dirichlet boundary conditions specifying the function on the surfaces of the box equal to
e 1.0+x/y n 2×cos 2 y/y n 2×e-1.0-z/y n 2.
Note that this is the same problem as that solved in the example for D03UBF. The differences in the maximum residuals obtained at each iteration between the two test runs are explained by the fact that in D03ECF the residual at each node is normalized by dividing by the central coefficient, whereas this normalization has not been used in the example program for D03UBF.

10.1 Program Text

Program Text (d03ecfe.f90)

10.2 Program Data

Program Data (d03ecfe.d)

10.3 Program Results

Program Results (d03ecfe.r)

GnuplotProduced by GNUPLOT 4.6 patchlevel 3 Example Program Solution in Y-Z Planes for x=6 u(x=6,y,z) gnuplot_plot_1 gnuplot_plot_2 0 2 4 6 8 10 y 0 5 10 15 z 0.2 0.4 0.6 0.8 1 1.2 1.4 1.6 1.8 2
GnuplotProduced by GNUPLOT 4.6 patchlevel 3 0 0.5 1 1.5 2 0 2 4 6 8 10 u(x=X,y,z=0) y Solution Profiles u(x=X,y,z=0) for Four Values X= 0,1,3,6 z=0 x=0 x=1 x=3 x=6 gnuplot_plot_1 gnuplot_plot_2 gnuplot_plot_3 gnuplot_plot_4
GnuplotProduced by GNUPLOT 4.6 patchlevel 3 0 0.1 0.2 0.3 0.4 0.5 0 2 4 6 8 10 u(x=X,y,z=0) y Solution Profiles u(x=X,y,z=15) for Four Values X=0,1,3,6 z=15 x=6 x=3 x=1 x=0 gnuplot_plot_1 gnuplot_plot_2 gnuplot_plot_3 gnuplot_plot_4
D03 Chapter Contents
D03 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


D03EDF : NAG Library, Mark 26

D03 Chapter Contents
D03 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

D03EDF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

D03EDF solves seven-diagonal systems of linear equations which arise from the discretization of an elliptic partial differential equation on a rectangular region. This routine uses a multigrid technique.

2 Specification

SUBROUTINE D03EDF ( NGX, NGY, LDA, A, RHS, UB, MAXIT, ACC, US, U, IOUT, NUMIT, IFAIL)
INTEGER | NGX, NGY, LDA, MAXIT, IOUT, NUMIT, IFAIL
REAL (KIND=nag_wp) | A(LDA,7), RHS(LDA), UB(NGX*NGY), ACC, US(LDA), U(LDA)

3 Description

D03EDF solves, by multigrid iteration, the seven-point scheme
A i,j 6 u i-1,j+1 + A i,j 7 u i,j+1 + A i,j 3 u i-1,j + A i,j 4 u ij + A i,j 5 u i+1,j + A i,j 1 u i,j-1 + A i,j 2 u i+1,j-1=f ij,  i=1,2,…,nx​ and ​j=1,2,…,ny,
which arises from the discretization of an elliptic partial differential equation of the form
α x,y U xx+β x,y U xy+γ x,y U yy+δ x,y Ux+ε x,y Uy+ϕ x,y U=ψ x,y
and its boundary conditions, defined on a rectangular region. This we write in matrix form as
Au=f.
The algorithm is described in separate reports by Wesseling (1982a), Wesseling (1982b) and McCarthy (1983).
Systems of linear equations, matching the seven-point stencil defined above, are solved by a multigrid iteration. An initial estimate of the solution must be provided by you. A zero guess may be supplied if no better approximation is available.
A ‘smoother’ based on incomplete Crout decomposition is used to eliminate the high frequency components of the error. A restriction operator is then used to map the system on to a sequence of coarser grids. The errors are then smoothed and prolongated (mapped onto successively finer grids). When the finest cycle is reached, the approximation to the solution is corrected. The cycle is repeated for MAXIT iterations or until the required accuracy, ACC, is reached.
D03EDF will automatically determine the number l of possible coarse grids, ‘levels’ of the multigrid scheme, for a particular problem. In other words, D03EDF determines the maximum integer l so that nx and ny can be expressed in the form
nx = m 2 l-1 + 1 ,   ny = n 2 l-1 + 1 ,   with   m≥2 ​ and ​ n≥2 .
It should be noted that the rate of convergence improves significantly with the number of levels used (see McCarthy (1983)), so that nx and ny should be carefully chosen so that nx-1 and ny-1 have factors of the form 2 l, with l as large as possible. For good convergence the integer l should be at least 2.
D03EDF has been found to be robust in application, but being an iterative method the problem of divergence can arise. For a strictly diagonally dominant matrix A
A ij 4 > ∑k≠4 A ij k ,   i=1,2,…,nx ​ and ​ j=1,2,…,ny
no such problem is foreseen. The diagonal dominance of A is not a necessary condition, but should this condition be strongly violated then divergence may occur. The quickest test is to try the routine.

4 References

McCarthy G J (1983) Investigation into the multigrid code MGD1 Report AERE-R 10889 Harwell
Wesseling P (1982a) MGD1 – a robust and efficient multigrid method Multigrid Methods. Lecture Notes in Mathematics 960 614–630 Springer–Verlag
Wesseling P (1982b) Theoretical aspects of a multigrid method SIAM J. Sci. Statist. Comput. 3 387–407

5 Arguments

1:   NGX – INTEGERInput
On entry: the number of interior grid points in the x-direction, nx. NGX-1 should preferably be divisible by as high a power of 2 as possible.
Constraint: NGX≥3.
2:   NGY – INTEGERInput
On entry: the number of interior grid points in the y-direction, ny. NGY-1 should preferably be divisible by as high a power of 2 as possible.
Constraint: NGY≥3.
3:   LDA – INTEGERInput
On entry: the first dimension of the array A, which must also be a lower bound for the dimension of the arrays RHS, US and U as declared in the (sub)program from which D03EDF is called. It is always sufficient to set LDA≥4×NGX+1×NGY+1/3, but slightly smaller values may be permitted, depending on the values of NGX and NGY. If on entry, LDA is too small, an error message gives the minimum permitted value. (LDA must be large enough to allow space for the coarse-grid approximations.)
4:   A LDA 7 – REAL (KIND=nag_wp) arrayInput/Output
On entry: A i+j-1×NGX k must be set to A ij k, for i=1,2,…,NGX, j=1,2,…,NGY and k=1,2,…,7.
On exit: is overwritten.
5:   RHS LDA – REAL (KIND=nag_wp) arrayInput/Output
On entry: RHS i+j-1×NGX must be set to f ij, for i=1,2,…,NGX and j=1,2,…,NGY.
On exit: the first NGX×NGY elements are unchanged and the rest of the array is used as workspace.
6:   UB NGX×NGY – REAL (KIND=nag_wp) arrayInput/Output
On entry: UB i+j-1×NGX must be set to the initial estimate for the solution u ij.
On exit: the corresponding component of the residual r=f-Au.
7:   MAXIT – INTEGERInput
On entry: the maximum permitted number of multigrid iterations. If MAXIT=0, no multigrid iterations are performed, but the coarse-grid approximations and incomplete Crout decompositions are computed, and may be output if IOUT is set accordingly.
Constraint: MAXIT≥0.
8:   ACC – REAL (KIND=nag_wp)Input
On entry: the required tolerance for convergence of the residual 2-norm:
r 2=∑k=1 NGX×NGY rk 2
where r=f-Au and u is the computed solution. Note that the norm is not scaled by the number of equations. The routine will stop after fewer than MAXIT iterations if the residual 2-norm is less than the specified tolerance. (If MAXIT>0, at least one iteration is always performed.)
If on entry ACC=0.0, then the machine precision is used as a default value for the tolerance; if ACC>0.0, but ACC is less than the machine precision, then the routine will stop when the residual 2-norm is less than the machine precision and IFAIL will be set to 4.
Constraint: ACC≥0.0.
9:   US LDA – REAL (KIND=nag_wp) arrayOutput
On exit: the residual 2-norm, stored in element US 1.
10:   U LDA – REAL (KIND=nag_wp) arrayOutput
On exit: the computed solution u ij is returned in U i+j-1×NGX, for i=1,2,…,NGX and j=1,2,…,NGY.
11:   IOUT – INTEGERInput
On entry: controls the output of printed information to the advisory message unit as returned by X04ABF:
IOUT=0
No output.
IOUT=1
The solution u ij, for i=1,2,…,NGX and j=1,2,…,NGY.
IOUT=2
The residual 2-norm after each iteration, with the reduction factor over the previous iteration.
IOUT=3
As for IOUT=1 and IOUT=2.
IOUT=4
As for IOUT=3, plus the final residual (as returned in UB).
IOUT=5
As for IOUT=4, plus the initial elements of A and RHS.
IOUT=6
As for IOUT=5, plus the Galerkin coarse grid approximations.
IOUT=7
As for IOUT=6, plus the incomplete Crout decompositions.
IOUT=8
As for IOUT=7, plus the residual after each iteration.
The elements A pk, the Galerkin coarse grid approximations and the incomplete Crout decompositions are output in the format:
  • Y-index =j
  • X-index =i A p 1A p 2A p 3A p 4A p 5A p 6A p 7
  • where p=i+j-1×NGX, for i=1,2,…,NGX and j=1,2,…,NGY.
The vectors U p, UB p, RHS p are output in matrix form with NGY rows and NGX columns. Where NGX>10, the NGX values for a given j value are produced in rows of 10. Values of IOUT>4 may yield considerable amounts of output.
Constraint: 0≤IOUT≤8.
12:   NUMIT – INTEGEROutput
On exit: the number of iterations performed.
13:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, | NGX<3,
or | NGY<3,
or | LDA is too small,
or | ACC<0.0,
or | MAXIT<0,
or | IOUT<0,
or | IOUT>8.
IFAIL=2
MAXIT iterations have been performed with the residual 2-norm decreasing at each iteration but the residual 2-norm has not been reduced to less than the specified tolerance (see ACC). Examine the progress of the iteration by setting IOUT≥2.
IFAIL=3
As for IFAIL=2, except that at one or more iterations the residual 2-norm did not decrease. It is likely that the method fails to converge for the given matrix A.
IFAIL=4
On entry, ACC is less than the machine precision. The routine terminated because the residual norm is less than the machine precision.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

See ACC (Section 5).

8 Parallelism and Performance

D03EDF is not threaded in any implementation.

9 Further Comments

The rate of convergence of this routine is strongly dependent upon the number of levels, l, in the multigrid scheme, and thus the choice of NGX and NGY is very important. You are advised to experiment with different values of NGX and NGY to see the effect they have on the rate of convergence; for example, using a value such as NGX=65 (=26+1) followed by NGX=64 (for which l=1).

10 Example

The program solves the elliptic partial differential equation
U xx-α U xy+U yy=-4,  α=1.7
on the unit square 0≤x,y≤1, with boundary conditions
U=0 ​ on ​ x=0, 0≤y≤1 y=0, 0≤x≤1 y=1, 0≤x≤1 U=1​ on ​x=1,  0≤y≤1.
For the equation to be elliptic, α must be less than 2.
The equation is discretized on a square grid with mesh spacing h in both directions using the following approximations:
Figure 1
U xx ≃ 1 h 2 UE-2 UO+UW U yy ≃ 1 h 2 UN-2 UO+US U xy ≃ 1 2⁢h 2 UN-UNW +UE-2 UO+UW-USE +US.
Thus the following equations are solved:
12 α u i- 1,j+ 1 + 1-12 α u i,j+ 1 + 1-12 α u i+ 1,j + - 4+α u ij + 1-12 α u i+ 1,j + 1-12 α u i,j- 1 + 12 α u i+ 1,j- 1=-4 h 2

10.1 Program Text

Program Text (d03edfe.f90)

10.2 Program Data

Program Data (d03edfe.d)

10.3 Program Results

Program Results (d03edfe.r)

GnuplotProduced by GNUPLOT 4.6 patchlevel 3 Example Program Solution of Elliptic PDE using Multigrid Iteration on System Resulting from Seven-point Stencil gnuplot_plot_1 gnuplot_plot_2 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9 x 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9 y 0 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9 1 U
D03 Chapter Contents
D03 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


D03EEF : NAG Library, Mark 26

D03 Chapter Contents
D03 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

D03EEF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

D03EEF discretizes a second-order elliptic partial differential equation (PDE) on a rectangular region.

2 Specification

SUBROUTINE D03EEF ( XMIN, XMAX, YMIN, YMAX, PDEF, BNDY, NGX, NGY, LDA, A, RHS, SCHEME, IFAIL)
INTEGER | NGX, NGY, LDA, IFAIL
REAL (KIND=nag_wp) | XMIN, XMAX, YMIN, YMAX, A(LDA,7), RHS(LDA)
CHARACTER(1) | SCHEME
EXTERNAL | PDEF, BNDY

3 Description

D03EEF discretizes a second-order linear elliptic partial differential equation of the form
α x,y ∂2 U ∂x 2 + β x,y ∂2 U ∂x ∂y + γ x,y ∂2 U ∂y 2 + δ x,y ∂U ∂x +ε x,y ∂U ∂y + ϕ x,y U = ψ x,y (1)
on a rectangular region
xA≤x≤xB yA≤y≤yB
subject to boundary conditions of the form
a x,y U+ b x,y ∂U ∂n = c x,y
where ∂U ∂n denotes the outward pointing normal derivative on the boundary. Equation (1) is said to be elliptic if
4 α x,y γ x,y ≥ β x,y 2
for all points in the rectangular region. The linear equations produced are in a form suitable for passing directly to the multigrid routine D03EDF.
The equation is discretized on a rectangular grid, with nx grid points in the x-direction and ny grid points in the y-direction. The grid spacing used is therefore
hx=xB-xA/nx-1 hy=yB-yA/ny-1
and the coordinates of the grid points xi,yj are
xi=xA+i-1 hx,  i=1,2,…,nx, yj=yA+j-1 hy,  j=1,2,…,ny.
At each grid point xi,yj six neighbouring grid points are used to approximate the partial differential equation, so that the equation is discretized on the seven-point stencil shown in Figure 1.
Figure 1
For convenience the approximation u ij to the exact solution U xi,yj is denoted by uO, and the neighbouring approximations are labelled according to points of the compass as shown. Where numerical labels for the seven points are required, these are also shown.
The following approximations are used for the second derivatives:
∂2 U ∂x 2 ≃ 1 hx 2 uE-2 uO+uW ∂2 U ∂y 2 ≃ 1 hy 2 uN-2 uO+uS ∂2 U ∂x∂y ≃ 1 2 hxhy uN-uNW+uE-2 uO+uW-uSE+uS.
Two possible schemes may be used to approximate the first derivatives:
Central Differences
∂U ∂x ≃ 1 2 hx uE-uW ∂U ∂y ≃ 1 2 hy uN-uS
Upwind Differences
∂U ∂x ≃ 1 hx uO-uW if  δ x,y>0 ∂U ∂x ≃ 1 hx uE-uO if  δ x,y<0 ∂U ∂y ≃ 1 hy uN-uO if  ε x,y>0 ∂U ∂y ≃ 1 hy uO-uS if  ε x,y<0.
Central differences are more accurate than upwind differences, but upwind differences may lead to a more diagonally dominant matrix for those problems where the coefficients of the first derivatives are significantly larger than the coefficients of the second derivatives.
The approximations used for the first derivatives may be written in a more compact form as follows:
∂U ∂x ≃ 1 2 hx kx- 1 uW- 2 kxuO+kx+ 1 uE ∂U ∂y ≃ 1 2 hy ky- 1 uS- 2 kyuO+ky+ 1 uN
where kx=sign⁡δ and ky=sign⁡ε for upwind differences, and kx=ky=0 for central differences.
At all points in the rectangular domain, including the boundary, the coefficients in the partial differential equation are evaluated by calling PDEF, and applying the approximations. This leads to a seven-diagonal system of linear equations of the form:
A ij 6 u i-1,j+1 + A ij 7 u i,j+1 + A ij 3 u i-1,j + A ij 4 u ij + A ij 5 u i+1,j + A ij 1 u i,j-1 + A ij 2 u i+1,j-1=f ij,  i=1,2,…,nx​ and ​j=1,2,…,ny,
where the coefficients are given by
A ij 1 = β xi,yj 1 2 hxhy +γ xi,yj 1 hy 2 +ε xi,yj 1 2 hy ky- 1 A ij 2 = -β xi,yj 1 2 hxhy A ij 3 = α xi,yj 1 hx 2 +β xi,yj 1 2 hxhy +δ xi,yj 1 2 hx kx- 1 A ij 4 = -α xi,yj 2 hx 2 -β xi,yj 1 hxhy -γ xi,yj 2 hy 2 -δ xi,yj kyhx-ε xi,yj kyhy-ϕ xi,yj A ij 5 = α xi,yj 1 hx 2 +β xi,yj 1 2 hxhy +δ xi,yj 1 2 hx kx+ 1 A ij 6 = -β xi,yj 1 2 hxhy A ij 7 = β xi,yj 1 2 hxhy +γ xi,yj 1 hy 2 +ε xi,yj 1 2 hy ky+ 1 f ij = ψ xi,yj
These equations then have to be modified to take account of the boundary conditions. These may be Dirichlet (where the solution is given), Neumann (where the derivative of the solution is given), or mixed (where a linear combination of solution and derivative is given).
If the boundary conditions are Dirichlet, there are an infinity of possible equations which may be applied:
μ u ij = μ f ij , μ≠0 . (2)
If D03EDF is used to solve the discretized equations, it turns out that the choice of μ can have a dramatic effect on the rate of convergence, and the obvious choice μ=1 is not the best. Some choices may even cause the multigrid method to fail altogether. In practice it has been found that a value of the same order as the other diagonal elements of the matrix is best, and the following value has been found to work well in practice:
μ=min ij -2 hx 2 +2 hy 2 ,A ij 4 .
If the boundary conditions are either mixed or Neumann (i.e., B≠0 on return from BNDY), then one of the points in the seven-point stencil lies outside the domain. In this case the normal derivative in the boundary conditions is used to eliminate the ‘fictitious’ point, u outside:
∂U ∂n ≃1 2 h uoutside-uinside. (3)
It should be noted that if the boundary conditions are Neumann and ϕ x,y≡0, then there is no unique solution. The routine returns with IFAIL=5 in this case, and the seven-diagonal matrix is singular.
The four corners are treated separately. BNDY is called twice, once along each of the edges meeting at the corner. If both boundary conditions at this point are Dirichlet and the prescribed solution values agree, then this value is used in an equation of the form (2). If the prescribed solution is discontinuous at the corner, then the average of the two values is used. If one boundary condition is Dirichlet and the other is mixed, then the value prescribed by the Dirichlet condition is used in an equation of the form given above. Finally, if both conditions are mixed or Neumann, then two ‘fictitious’ points are eliminated using two equations of the form (3).
It is possible that equations for which the solution is known at all points on the boundary, have coefficients which are not defined on the boundary. Since this routine calls PDEF at all points in the domain, including boundary points, arithmetic errors may occur in PDEF which this routine cannot trap. If you have an equation with Dirichlet boundary conditions (i.e., B=0 at all points on the boundary), but with PDE coefficients which are singular on the boundary, then D03EDF could be called directly only using interior grid points at your discretization.
After the equations have been set up as described above, they are checked for diagonal dominance. That is to say,
A ij 4 > ∑k≠4 A ij k ,   i=1,2,…,nx ​ and ​ j=1,2,…,ny .
If this condition is not satisfied then the routine returns with IFAIL=6. The multigrid routineD03EDF may still converge in this case, but if the coefficients of the first derivatives in the partial differential equation are large compared with the coefficients of the second derivative, you should consider using upwind differences (SCHEME='U').
Since this routine is designed primarily for use with D03EDF, this document should be read in conjunction with the document for that routine.

4 References

Wesseling P (1982) MGD1 – a robust and efficient multigrid method Multigrid Methods. Lecture Notes in Mathematics 960 614–630 Springer–Verlag

5 Arguments

1:   XMIN – REAL (KIND=nag_wp)Input
2:   XMAX – REAL (KIND=nag_wp)Input
On entry: the lower and upper x coordinates of the rectangular region respectively, xA and xB.
Constraint: XMIN<XMAX.
3:   YMIN – REAL (KIND=nag_wp)Input
4:   YMAX – REAL (KIND=nag_wp)Input
On entry: the lower and upper y coordinates of the rectangular region respectively, yA and yB.
Constraint: YMIN<YMAX.
5:   PDEF – SUBROUTINE, supplied by the user.External Procedure
PDEF must evaluate the functions α x,y, β x,y, γ x,y, δ x,y, ε x,y, ϕ x,y and ψ x,y which define the equation at a general point x,y.
The specification of PDEF is:
SUBROUTINE PDEF ( X, Y, ALPHA, BETA, GAMMA, DELTA, EPSLON, PHI, PSI)
REAL (KIND=nag_wp) X, Y, ALPHA, BETA, GAMMA, DELTA, EPSLON, PHI, PSI
1:   X – REAL (KIND=nag_wp)Input
2:   Y – REAL (KIND=nag_wp)Input
On entry: the x and y coordinates of the point at which the coefficients of the partial differential equation are to be evaluated.
3:   ALPHA – REAL (KIND=nag_wp)Output
4:   BETA – REAL (KIND=nag_wp)Output
5:   GAMMA – REAL (KIND=nag_wp)Output
6:   DELTA – REAL (KIND=nag_wp)Output
7:   EPSLON – REAL (KIND=nag_wp)Output
8:   PHI – REAL (KIND=nag_wp)Output
9:   PSI – REAL (KIND=nag_wp)Output
On exit: ALPHA, BETA, GAMMA, DELTA, EPSLON, PHI and PSI must be set to the values of α x,y, β x,y, γ x,y, δ x,y, ε x,y, ϕ x,y and ψ x,y respectively at the point specified by X and Y.
PDEF must either be a module subprogram USEd by, or declared as EXTERNAL in, the (sub)program from which D03EEF is called. Arguments denoted as Input must not be changed by this procedure.
6:   BNDY – SUBROUTINE, supplied by the user.External Procedure
BNDY must evaluate the functions a x,y, b x,y, and c x,y involved in the boundary conditions.
The specification of BNDY is:
SUBROUTINE BNDY ( X, Y, A, B, C, IBND)
INTEGER | IBND
REAL (KIND=nag_wp) | X, Y, A, B, C
1:   X – REAL (KIND=nag_wp)Input
2:   Y – REAL (KIND=nag_wp)Input
On entry: the x and y coordinates of the point at which the boundary conditions are to be evaluated.
3:   A – REAL (KIND=nag_wp)Output
4:   B – REAL (KIND=nag_wp)Output
5:   C – REAL (KIND=nag_wp)Output
On exit: A, B and C must be set to the values of the functions appearing in the boundary conditions.
6:   IBND – INTEGERInput
On entry: specifies on which boundary the point (X,Y) lies. IBND=0, 1, 2 or 3 according as the point lies on the bottom, right, top or left boundary.
BNDY must either be a module subprogram USEd by, or declared as EXTERNAL in, the (sub)program from which D03EEF is called. Arguments denoted as Input must not be changed by this procedure.
7:   NGX – INTEGERInput
8:   NGY – INTEGERInput
On entry: the number of interior grid points in the x- and y-directions respectively, nx and ny. If the seven-diagonal equations are to be solved by D03EDF, then NGX-1 and NGY-1 should preferably be divisible by as high a power of 2 as possible.
Constraints:
  • NGX≥3;
  • NGY≥3.
9:   LDA – INTEGERInput
On entry: the first dimension of the array A and the dimension of the array RHS as declared in the (sub)program from which D03EEF is called.
Constraint: if only the seven-diagonal equations are required, then LDA≥NGX×NGY. If a call to this routine is to be followed by a call to D03EDF to solve the seven-diagonal linear equations, LDA≥4×NGX+1×NGY+1/3.
Note: this routine only checks the former condition. D03EDF, if called, will check the latter condition.
10:   A LDA 7 – REAL (KIND=nag_wp) arrayOutput
On exit: A ij, for i=1,2,…,NGX×NGY and j=1,2,…,7, contains the seven-diagonal linear equations produced by the discretization described above. If LDA>NGX×NGY, the remaining elements are not referenced by the routine, but if LDA≥4×NGX+1×NGY+1/3 then the array A can be passed directly to D03EDF, where these elements are used as workspace.
11:   RHS LDA – REAL (KIND=nag_wp) arrayOutput
On exit: the first NGX×NGY elements contain the right-hand sides of the seven-diagonal linear equations produced by the discretization described above. If LDA>NGX×NGY, the remaining elements are not referenced by the routine, but if LDA≥4×NGY+1×NGY+1/3 then the array RHS can be passed directly to D03EDF, where these elements are used as workspace.
12:   SCHEME – CHARACTER(1)Input
On entry: the type of approximation to be used for the first derivatives which occur in the partial differential equation.
SCHEME='C'
Central differences are used.
SCHEME='U'
Upwind differences are used.
Constraint: SCHEME='C' or 'U'.
Note: generally speaking, if at least one of the coefficients multiplying the first derivatives (DELTA or EPSLON as returned by PDEF) are large compared with the coefficients multiplying the second derivatives, then upwind differences may be more appropriate. Upwind differences are less accurate than central differences, but may result in more rapid convergence for strongly convective equations. The easiest test is to try both schemes.
13:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, because for this routine the values of the output arguments may be useful even if IFAIL≠0 on exit, the recommended value is -1. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Note: D03EEF may return useful information for one or more of the following detected errors or warnings.
Errors or warnings detected by the routine:
IFAIL=1
On entry, | XMIN≥XMAX,
or | YMIN≥YMAX,
or | NGX<3,
or | NGY<3,
or | LDA<NGX×NGY,
or | SCHEME is not one of 'C' or 'U'.
IFAIL=2
At some point on the boundary there is a derivative in the boundary conditions (B≠0 on return from BNDY) and there is a nonzero coefficient of the mixed derivative ∂2 U ∂x∂y (BETA≠0 on return from PDEF).
IFAIL=3
A null boundary has been specified, i.e., at some point both A and B are zero on return from a call to BNDY.
IFAIL=4
The equation is not elliptic, i.e., 4×ALPHA×GAMMA<BETA 2 after a call to PDEF. The discretization has been completed, but the convergence of D03EDF cannot be guaranteed.
IFAIL=5
The boundary conditions are purely Neumann (only the derivative is specified) and there is, in general, no unique solution.
IFAIL=6
The equations were not diagonally dominant. (See Section 3.)
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

Not applicable.

8 Parallelism and Performance

D03EEF is not threaded in any implementation.

9 Further Comments

If this routine is used as a preprocessor to the multigrid routine D03EDF it should be noted that the rate of convergence of that routine is strongly dependent upon the number of levels in the multigrid scheme, and thus the choice of NGX and NGY is very important.

10 Example

The program solves the elliptic partial differential equation
∂2 U ∂x 2 + ∂2 U ∂y 2 +50 ∂U ∂x + ∂U ∂y =f x,y
on the unit square 0≤x, y≤1, with boundary conditions
  • ∂U ∂n given on x=0 and y=0,
  • U given on x=1 and y=1.
The function f x,y and the exact form of the boundary conditions are derived from the exact solution U x,y=sin⁡xsin⁡y.
The equation is first solved using central differences. Since the coefficients of the first derivatives are large, the linear equations are not diagonally dominated, and convergence is slow. The equation is solved a second time with upwind differences, showing that convergence is more rapid, but the solution is less accurate.

10.1 Program Text

Program Text (d03eefe.f90)

10.2 Program Data

Program Data (d03eefe.d)

10.3 Program Results

Program Results (d03eefe.r)

GnuplotProduced by GNUPLOT 4.6 patchlevel 3 Example Program Solution of Elliptic PDE using Central Differences gnuplot_plot_1 gnuplot_plot_2 0 0.2 0.4 0.6 0.8 1 x 0 0.2 0.4 0.6 0.8 1 y −0.1 0 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 U
D03 Chapter Contents
D03 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


D03FAF : NAG Library, Mark 26

D03 Chapter Contents
D03 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

D03FAF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

D03FAF solves the Helmholtz equation in Cartesian coordinates in three dimensions using the standard seven-point finite difference approximation. This routine is designed to be particularly efficient on vector processors.

2 Specification

SUBROUTINE D03FAF ( XS, XF, L, LBDCND, BDXS, BDXF, YS, YF, M, MBDCND, BDYS, BDYF, ZS, ZF, N, NBDCND, BDZS, BDZF, LAMBDA, LDF, LDF2, F, PERTRB, W, LWRK, IFAIL)
INTEGER | L, LBDCND, M, MBDCND, N, NBDCND, LDF, LDF2, LWRK, IFAIL
REAL (KIND=nag_wp) | XS, XF, BDXS(LDF2,N+1), BDXF(LDF2,N+1), YS, YF, BDYS(LDF,N+1), BDYF(LDF,N+1), ZS, ZF, BDZS(LDF,M+1), BDZF(LDF,M+1), LAMBDA, F(LDF,LDF2,N+1), PERTRB, W(LWRK)

3 Description

D03FAF solves the three-dimensional Helmholtz equation in Cartesian coordinates:
∂2 u ∂x 2 + ∂2 u ∂y 2 + ∂2 u ∂z 2 +λu=f x,y,z.
This subroutine forms the system of linear equations resulting from the standard seven-point finite difference equations, and then solves the system using a method based on the fast Fourier transform (FFT) described by Swarztrauber (1984). This subroutine is based on the routine HW3CRT from FISHPACK (see Swarztrauber and Sweet (1979)).
More precisely, the routine replaces all the second derivatives by second-order central difference approximations, resulting in a block tridiagonal system of linear equations. The equations are modified to allow for the prescribed boundary conditions. Either the solution or the derivative of the solution may be specified on any of the boundaries, or the solution may be specified to be periodic in any of the three dimensions. By taking the discrete Fourier transform in the x- and y-directions, the equations are reduced to sets of tridiagonal systems of equations. The Fourier transforms required are computed using the multiple FFT routines found in Chapter C06.

4 References

Swarztrauber P N (1984) Fast Poisson solvers Studies in Numerical Analysis (ed G H Golub) Mathematical Association of America
Swarztrauber P N and Sweet R A (1979) Efficient Fortran subprograms for the solution of separable elliptic partial differential equations ACM Trans. Math. Software 5 352–364

5 Arguments

1:   XS – REAL (KIND=nag_wp)Input
On entry: the lower bound of the range of x, i.e., XS≤x≤XF.
Constraint: XS<XF.
2:   XF – REAL (KIND=nag_wp)Input
On entry: the upper bound of the range of x, i.e., XS≤x≤XF.
Constraint: XS<XF.
3:   L – INTEGERInput
On entry: the number of panels into which the interval (XS,XF) is subdivided. Hence, there will be L+1 grid points in the x-direction given by xi=XS+i-1×δx, for i=1,2,…,L+1, where δx=XF-XS/L is the panel width.
Constraint: L≥5.
4:   LBDCND – INTEGERInput
On entry: indicates the type of boundary conditions at x=XS and x=XF.
LBDCND=0
If the solution is periodic in x, i.e., u XS,y,z=u XF,y,z.
LBDCND=1
If the solution is specified at x=XS and x=XF.
LBDCND=2
If the solution is specified at x=XS and the derivative of the solution with respect to x is specified at x=XF.
LBDCND=3
If the derivative of the solution with respect to x is specified at x=XS and x=XF.
LBDCND=4
If the derivative of the solution with respect to x is specified at x=XS and the solution is specified at x=XF.
Constraint: 0≤LBDCND≤4.
5:   BDXS LDF2 N+1 – REAL (KIND=nag_wp) arrayInput
On entry: the values of the derivative of the solution with respect to x at x=XS. When LBDCND=3 or 4, BDXS jk=ux XS,yj,zk, for j=1,2,…,M+1 and k=1,2,…,N+1.
When LBDCND has any other value, BDXS is not referenced.
6:   BDXF LDF2 N+1 – REAL (KIND=nag_wp) arrayInput
On entry: the values of the derivative of the solution with respect to x at x=XF. When LBDCND=2 or 3, BDXF jk=ux XF,yj,zk, for j=1,2,…,M+1 and k=1,2,…,N+1.
When LBDCND has any other value, BDXF is not referenced.
7:   YS – REAL (KIND=nag_wp)Input
On entry: the lower bound of the range of y, i.e., YS≤y≤YF.
Constraint: YS<YF.
8:   YF – REAL (KIND=nag_wp)Input
On entry: the upper bound of the range of y, i.e., YS≤y≤YF.
Constraint: YS<YF.
9:   M – INTEGERInput
On entry: the number of panels into which the interval (YS,YF) is subdivided. Hence, there will be M+1 grid points in the y-direction given by yj=YS+j-1×δy, for j=1,2,…,M+1, where δy=YF-YS/M is the panel width.
Constraint: M≥5.
10:   MBDCND – INTEGERInput
On entry: indicates the type of boundary conditions at y=YS and y=YF.
MBDCND=0
If the solution is periodic in y, i.e., u x,YF,z=u x,YS,z.
MBDCND=1
If the solution is specified at y=YS and y=YF.
MBDCND=2
If the solution is specified at y=YS and the derivative of the solution with respect to y is specified at y=YF.
MBDCND=3
If the derivative of the solution with respect to y is specified at y=YS and y=YF.
MBDCND=4
If the derivative of the solution with respect to y is specified at y=YS and the solution is specified at y=YF.
Constraint: 0≤MBDCND≤4.
11:   BDYS LDF N+1 – REAL (KIND=nag_wp) arrayInput
On entry: the values of the derivative of the solution with respect to y at y=YS. When MBDCND=3 or 4, BDYS ik=uy xi,YS,zk, for i=1,2,…,L+1 and k=1,2,…,N+1.
When MBDCND has any other value, BDYS is not referenced.
12:   BDYF LDF N+1 – REAL (KIND=nag_wp) arrayInput
On entry: the values of the derivative of the solution with respect to y at y=YF. When MBDCND=2 or 3, BDYF ik=uy xi,YF,zk, for i=1,2,…,L+1 and k=1,2,…,N+1.
When MBDCND has any other value, BDYF is not referenced.
13:   ZS – REAL (KIND=nag_wp)Input
On entry: the lower bound of the range of z, i.e., ZS≤z≤ZF.
Constraint: ZS<ZF.
14:   ZF – REAL (KIND=nag_wp)Input
On entry: the upper bound of the range of z, i.e., ZS≤z≤ZF.
Constraint: ZS<ZF.
15:   N – INTEGERInput
On entry: the number of panels into which the interval (ZS,ZF) is subdivided. Hence, there will be N+1 grid points in the z-direction given by zk=ZS+k-1×δz, for k=1,2,…,N+1, where δz=ZF-ZS/N is the panel width.
Constraint: N≥5.
16:   NBDCND – INTEGERInput
On entry: specifies the type of boundary conditions at z=ZS and z=ZF.
NBDCND=0
if the solution is periodic in z, i.e., u x,y,ZF=u x,y,ZS.
NBDCND=1
if the solution is specified at z=ZS and z=ZF.
NBDCND=2
if the solution is specified at z=ZS and the derivative of the solution with respect to z is specified at z=ZF.
NBDCND=3
if the derivative of the solution with respect to z is specified at z=ZS and z=ZF.
NBDCND=4
if the derivative of the solution with respect to z is specified at z=ZS and the solution is specified at z=ZF.
Constraint: 0≤NBDCND≤4.
17:   BDZS LDF M+1 – REAL (KIND=nag_wp) arrayInput
On entry: the values of the derivative of the solution with respect to z at z=ZS. When NBDCND=3 or 4, BDZS ij=uz xi,yj,ZS, for i=1,2,…,L+1 and j=1,2,…,M+1.
When NBDCND has any other value, BDZS is not referenced.
18:   BDZF LDF M+1 – REAL (KIND=nag_wp) arrayInput
On entry: the values of the derivative of the solution with respect to z at z=ZF. When NBDCND=2 or 3, BDZF ij=uz xi,yj,ZF, for i=1,2,…,L+1 and j=1,2,…,M+1.
When NBDCND has any other value, BDZF is not referenced.
19:   LAMBDA – REAL (KIND=nag_wp)Input
On entry: the constant λ in the Helmholtz equation. For certain positive values of λ a solution to the differential equation may not exist, and close to these values the solution of the discretized problem will be extremely ill-conditioned. If λ>0, then D03FAF will set IFAIL=3, but will still attempt to find a solution. However, since in general the values of λ for which no solution exists cannot be predicted a priori, you are advised to treat any results computed with λ>0 with great caution.
20:   LDF – INTEGERInput
On entry: the first dimension of the arrays F, BDYS, BDYF, BDZS and BDZF as declared in the (sub)program from which D03FAF is called.
Constraint: LDF≥L+1.
21:   LDF2 – INTEGERInput
On entry: the second dimension of the array F and the first dimension of the arrays BDXS and BDXF as declared in the (sub)program from which D03FAF is called.
Constraint: LDF2≥M+1.
22:   F LDFLDF2 N+1 – REAL (KIND=nag_wp) arrayInput/Output
On entry: the values of the right-side of the Helmholtz equation and boundary values (if any).
F ijk = f xi,yj,zk i=2,3,…,L, j=2,3,…,M ​ and ​ k=2,3,…,N.
On the boundaries F is defined by
LBDCND | F 1 jk | F L+1 jk
0 | f XS,yj,zk | f XS,yj,zk
1 | u XS,yj,zk | u XF,yj,zk
2 | u XS,yj,zk | f XF,yj,zk | j=1,2,…,M+1
3 | f XS,yj,zk | f XF,yj,zk | k=1,2,…,N+1
4 | f XS,yj,zk | u XF,yj,zk
MBDCND | F i 1 k | F i M+1 k
0 | f xi,YS,zk | f xi,YS,zk
1 | u xi,YS,zk | u xi,YF,zk
2 | u xi,YS,zk | f xi,YF,zk | i=1,2,…,L+1
3 | f xi,YS,zk | f xi,YF,zk | k=1,2,…,N+1
4 | f xi,YS,zk | u xi,YF,zk
NBDCND | F ij 1 | F ij N+1
0 | f xi,yj,ZS | f xi,yj,ZS
1 | u xi,yj,ZS | u xi,yj,ZF
2 | u xi,yj,ZS | f xi,yj,ZF | i=1,2,…,L+1
3 | f xi,yj,ZS | f xi,yj,ZF | j=1,2,…,M+1
4 | f xi,yj,ZS | u xi,yj,ZF
Note: if the table calls for both the solution u and the right-hand side f on a boundary, then the solution must be specified.
On exit: contains the solution u i,j,k of the finite difference approximation for the grid point xi,yj,zk, for i=1,2,…,L+1, j=1,2,…,M+1 and k=1,2,…,N+1.
23:   PERTRB – REAL (KIND=nag_wp)Output
On exit: PERTRB=0, unless a solution to Poisson's equation λ=0 is required with a combination of periodic or derivative boundary conditions (LBDCND, MBDCND and NBDCND=0 or 3). In this case a solution may not exist. PERTRB is a constant, calculated and subtracted from the array F, which ensures that a solution exists. D03FAF then computes this solution, which is a least squares solution to the original approximation. This solution is not unique and is unnormalized. The value of PERTRB should be small compared to the right-hand side F, otherwise a solution has been obtained to an essentially different problem. This comparison should always be made to ensure that a meaningful solution has been obtained.
24:   W LWRK – REAL (KIND=nag_wp) arrayWorkspace
25:   LWRK – INTEGERInput
On entry: the dimension of the array W as declared in the (sub)program from which D03FAF is called. W is no longer used as workspace, LWRK can therefore be safely set to zero.
Constraint: LWRK≥0.
26:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, | XS≥XF,
or | L<5,
or | LBDCND<0,
or | LBDCND>4,
or | YS≥YF,
or | M<5,
or | MBDCND<0,
or | MBDCND>4,
or | ZS≥ZF,
or | N<5,
or | NBDCND<0,
or | NBDCND>4,
or | LDF<L+1,
or | LDF2<M+1.
IFAIL=2
On entry, LWRK<0.
IFAIL=3
On entry, λ>0.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

Not applicable.

8 Parallelism and Performance

D03FAF is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
D03FAF makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The execution time is roughly proportional to L×M×N× log 2⁡L + log 2⁡M +5 , but also depends on input arguments LBDCND and MBDCND.

10 Example

This example solves the Helmholz equation
∂2 u ∂x 2 + ∂2 u ∂y 2 + ∂2 u ∂z 2 +λ u=f x,y,z
for x,y,z∈0,1×0,2 π×0,π 2, where λ=-2, and f x,y,z is derived from the exact solution
u x,y,z=x 4 sin⁡ycos⁡z.
The equation is subject to the following boundary conditions, again derived from the exact solution given above.
  • u 0,y,z and u 1,y,z are prescribed (i.e., LBDCND=1).
  • u x,0,z=u x,2 π,z (i.e., MBDCND=0).
  • u x,y,0 and uz x,y,π 2 are prescribed (i.e., NBDCND=2).

10.1 Program Text

Program Text (d03fafe.f90)

10.2 Program Data

Program Data (d03fafe.d)

10.3 Program Results

Program Results (d03fafe.r)

D03 Chapter Contents
D03 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


D03 Chapter Introduction : NAG Library, Mark 26

D03 Chapter Contents
NAG Library Manual

NAG Library Chapter Introduction

D03 – Partial Differential Equations

▸▿ Contents

1 Scope of the Chapter
2 Background to the Problems
▸▿ 3 Recommendations on Choice and Use of Available Routines
3.1 Thread Safe Routines
3.2 Elliptic Equations
3.3 Hyperbolic Equations
3.4 Parabolic Equations
3.5 Black–Scholes Equations
3.6 First-order Systems in One Space Dimension
3.7 Second-order Systems in Two Space Dimensions
3.8 Convection-diffusion Systems
3.9 Automatic Mesh Generation
3.10 Utility Routines
4 Decision Trees
5 Functionality Index
6 Auxiliary Routines Associated with Library Routine Arguments
7 Routines Withdrawn or Scheduled for Withdrawal
8 References

1 Scope of the Chapter

This chapter is concerned with the numerical solution of partial differential equations.

2 Background to the Problems

The definition of a partial differential equation problem includes not only the equation itself but also the domain of interest and appropriate subsidiary conditions. Indeed, partial differential equations are usually classified as elliptic, hyperbolic or parabolic according to the form of the equation and the form of the subsidiary conditions which must be assigned to produce a well-posed problem. The routines in this chapter will often call upon routines from other chapters, such as Chapter F04 (Simultaneous Linear Equations) and Chapter D02 (Ordinary Differential Equations). Other chapters also contain relevant routines, in particular Chapter D06 (Mesh Generation) and Chapter F11 (Large Scale Linear Systems).
The classification of partial differential equations is easily described in the case of linear equations of the second order in two independent variables, i.e., equations of the form
a u xx+2 b u xy+c u yy+d ux+e uy+fu+g=0, (1)
where a, b, c, d, e, f and g are functions of x and y only. Equation (1) is called elliptic, hyperbolic or parabolic according to whether ac-b 2 is positive, negative or zero, respectively. Useful definitions of the concepts of elliptic, hyperbolic and parabolic character can also be given for differential equations in more than two independent variables, for systems and for nonlinear differential equations.
For elliptic equations, of which Laplace's equation
u xx+u yy=0 (2)
is the simplest example of second order, the subsidiary conditions take the form of boundary conditions, i.e., conditions which provide information about the solution at all points of a closed boundary. For example, if equation (2) holds in a plane domain D bounded by a contour C, a solution u may be sought subject to the condition
u=f  on  C, (3)
where f is a given function. The condition (3) is known as a Dirichlet boundary condition. Equally common is the Neumann boundary condition
u′=g  on  C, (4)
which is one form of a more general condition
u′+fu=g  on  C, (5)
where u′ denotes the derivative of u normal to the contour C, and f and g are given functions. Provided that f and g satisfy certain restrictions, condition (5) yields a well-posed boundary value problem for Laplace's equation. In the case of the Neumann problem, one further piece of information, e.g., the value of u at a particular point, is necessary for uniqueness of the solution. Boundary conditions similar to the above are applicable to more general second-order elliptic equations, whilst two such conditions are required for equations of fourth order.
For hyperbolic equations, the wave equation
u tt-u xx=0 (6)
is the simplest example of second order. It is equivalent to a first-order system
ut-vx=0,  vt-ux=0. (7)
The subsidiary conditions may take the form of initial conditions, i.e., conditions which provide information about the solution at points on a suitable open boundary. For example, if equation (6) is satisfied for t>0, a solution u may be sought such that
u x,0 = f x ,   u t x,0 = g x , (8)
where f and g are given functions. This is an example of an initial value problem, sometimes known as Cauchy's problem.
For parabolic equations, of which the heat conduction equation
ut-u xx=0 (9)
is the simplest example, the subsidiary conditions always include some of initial type and may also include some of boundary type. For example, if equation (9) is satisfied for t>0 and 0<x<1, a solution u may be sought such that
u x,0 = f x ,   0 < x < 1 , (10)
and
u 0,t = 0 ,   u 1,t = 1 ,   t > 0 . (11)
This is an example of a mixed initial/boundary value problem.
For all types of partial differential equations, finite difference methods (see Mitchell and Griffiths (1980)) and finite element methods (see Wait and Mitchell (1985)) are the most common means of solution. The use of finite difference methods features prominently in this chapter, however, the use of finite element methods is sufficiently large in scope to warrant a separate library of routines for their implementation. NAG no longer provides a companion finite element library, but there are several such specialist libraries available, including ParaFEM. Some of the utility routines in this chapter are concerned with the solution of the large sparse systems of equations which arise from finite difference and finite element methods. Further routines for this purpose are provided in Chapter F11.
Alternative methods of solution are often suitable for special classes of problems. For example, the method of characteristics is the most common for hyperbolic equations involving time and one space dimension (see Smith (1985)). The method of lines (see Mikhlin and Smolitsky (1967)) may be used to reduce a parabolic equation to a (stiff) system of ordinary differential equations, which may be solved by means of routines from Chapter D02 (Ordinary Differential Equations). Similarly, integral equation or boundary element methods (see Jaswon and Symm (1977)) are frequently used for elliptic equations. Typically, in the latter case, the solution of a boundary value problem is represented in terms of certain boundary functions by an integral expression which satisfies the differential equation throughout the relevant domain. The boundary functions are obtained by applying the given boundary conditions to this representation. Implementation of this method necessitates discretization of only the boundary of the domain, the dimensionality of the problem thus being effectively reduced by one. The boundary conditions yield a full system of simultaneous equations, as opposed to the sparse systems yielded by finite difference and finite element methods, but the full system is usually of much lower order. Solution of this system yields the boundary functions, from which the solution of the problem may be obtained, by quadrature, as and where required.

3 Recommendations on Choice and Use of Available Routines

The choice of routine will depend first of all upon the type of partial differential equation to be solved. At present no special allowances are made for problems with boundary singularities such as may arise at corners of domains or at points where boundary conditions change. For such problems results should be treated with caution. The choice of routine may also depend on whether or not it is to be used in a multithreaded environment.
You may wish to construct your own partial differential equation solution software for problems not solvable by the routines described in Section 3.2 to Section 3.8 below. In such cases you can employ appropriate routines from the Linear Algebra Chapters to solve the resulting linear systems; see Section 3.10 for further details.

3.1 Thread Safe Routines

Some of the routines in this chapter come in pairs, with each routine in the pair having exactly the same functionality, except that one of them has additional arguments in order to make it safe for use in multithreaded applications. The routine that is safe for use in multithreaded applicatons has an ‘A’ as the last character in the name, in place of the usual ‘F’. An example of such a pair is D03PCA and D03PCF.
For some routines there is no thread safe alternative and if this is the case it is clearly stated in the routine document.

3.2 Elliptic Equations

The routine D03EAF solves Laplace's equation in two dimensions, equation (2), by an integral equation method. This routine is applicable to an arbitrary domain bounded internally or externally by one or more closed contours, when the value of either the unknown function u or its normal derivative u′ is given at each point of the boundary.
The routines D03EBF and D03ECF solve a system of simultaneous algebraic equations of five-point and seven-point molecule form (see Mikhlin and Smolitsky (1967)) on two-dimensional and three-dimensional topologically-rectangular meshes respectively, using Stone's Strongly Implicit Procedure (SIP). These routines, which make repeated calls of the utility routines D03UAF and D03UBF respectively, may be used to solve any boundary value problem whose finite difference representation takes the appropriate form.
The routine D03EDF solves a system of seven-point difference equations in a rectangular grid (in two dimensions), using the multigrid iterative method. The equations are supplied by you, and the seven-point form allows cross-derivative terms to be represented (see Mitchell and Griffiths (1980)). The method is particularly efficient for large systems of equations with diagonal dominance and should be preferred to D03EBF whenever it is appropriate for the solution of the problem.
The routine D03EEF discretizes a second-order equation on a two-dimensional rectangular region using finite differences and a seven-point molecule. The routine allows for cross-derivative terms, Dirichlet, Neumann or mixed boundary conditions, and either central or upwind differences. The resulting seven-diagonal difference equations are in a form suitable for passing directly to the multigrid routine D03EDF, although other solution methods could just as easily be used.
The routine D03FAF, based on the routine HW3CRT from FISHPACK (see Swarztrauber and Sweet (1979)), solves the Helmholtz equation in a three-dimensional cuboidal region, with any combination of Dirichlet, Neumann or periodic boundary conditions. The method used is based on the fast Fourier transform algorithm, and is likely to be particularly efficient on vector-processing machines.

3.3 Hyperbolic Equations

See Section 3.8.

3.4 Parabolic Equations

There are five routines available for solving general parabolic equations in one space dimension:
  • D03PCF/D03PCA,
  • D03PDF/D03PDA,
  • D03PHF/D03PHA,
  • D03PJF/D03PJA,
  • D03PPF/D03PPA.
Equations may include nonlinear terms but the true derivative ut should occur linearly and equations should usually contain a second-order space derivative u xx. There are certain restrictions on the coefficients to try to ensure that the problems posed can be solved by the above routines.
The method of solution is to discretize the space derivatives using finite differences or collocation, and to solve the resulting system of ordinary differential equations using a ‘stiff’ solver.
D03PCF/D03PCA and D03PDF/D03PDA can solve a system of parabolic equations of the form
∑ j = 1 n P i j x,t,U, U x ∂ U j ∂ t + Q i x,t,U, U x = x - m ∂ ∂ x x m R i x,t,U, U x ,
where i=1,2,…,n, a≤x≤b, t≥t 0.
The parameter m allows the routine to handle different coordinate systems easily (Cartesian, cylindrical polars and spherical polars). D03PCF/D03PCA uses a finite differences spatial discretization and D03PDF/D03PDA uses a collocation spatial discretization.
D03PHF/D03PHA and D03PJF/D03PJA are similar to D03PCF/D03PCA and D03PDF/D03PDA respectively, except that they provide scope for coupled differential-algebraic systems. This extended functionality allows for the solution of more complex and more general problems, e.g., periodic boundary conditions and integro-differential equations.
D03PPF/D03PPA is similar to D03PHF/D03PHA but allows remeshing to take place in the spatial direction. This facility can be very useful when the nature of the solution in the spatial direction varies considerably over time.
For parabolic systems in two space dimensions see Section 3.7.

3.5 Black–Scholes Equations

D03NCF solves the Black–Scholes equation
∂f ∂t +r-q S ∂f ∂S +σ 2S 2 2 ∂2 f ∂S 2 =rf
Smin<S<Smax,   tmin<t<tmax,
for the value f of a European or American, put or call stock option. The parameters r, q and σ may each be either constant or time-dependent. The values of the Greeks are also returned.
In certain cases an analytic solution of the Black–Scholes equation is available. In these cases the solution may be computed by D03NDF. More generally, Chapter S contains a set of option pricing routines that evaluate the closed form solutions or approximations to the equations that define mathematical models for the prices of selected financial option contracts, including the Black–Scholes equation (S30AAF).

3.6 First-order Systems in One Space Dimension

There are three routines available for solving systems of first-order partial differential equations:
  • D03PEF,
  • D03PKF,
  • D03PRF.
Equations may include nonlinear terms but the time derivative should occur linearly. There are certain restrictions on the coefficients to ensure that the problems posed can be solved by the above routines.
The method of solution is to discretize the space derivatives using the Keller box scheme and to solve the resulting system of ordinary differential equations using a ‘stiff’ solver.
D03PEF is designed to solve a system of the form
∑ j = 1 n P i j x,t,U, U x ∂ U j ∂ t + Q i x,t,U, U x = 0 ,
where i=1,2,…,n, a≤x≤b, t≥t 0.
D03PKF is similar to D03PEF except that it provides scope for coupled differential algebraic systems. This extended functionality allows for the solution of more complex problems.
D03PRF is similar to D03PKF but allows remeshing to take place in the spatial direction. This facility can be very useful when the nature of the solution in the spatial direction varies considerably over time.
D03PEF, D03PKF or D03PRF may also be used to solve systems of higher or mixed order partial differential equations which have been reduced to first-order. Note that in general these routines are unsuitable for hyperbolic first-order equations, for which an appropriate upwind discretization scheme should be used (see Section 3.8 for example).

3.7 Second-order Systems in Two Space Dimensions

There are two routines available for solving nonlinear second-order time-dependent systems in two space dimensions:
  • D03RAF,
  • D03RBF.
These routines are formally applicable to the general nonlinear system
F j t,x,y,u, u t , u x , u y , u x x , u x y , u y y = 0 ,
where j=1,2,…,NPDE, x,y∈Ω, t 0≤t≤tout. However, they should not be used to solve purely hyperbolic systems, or time-independent problems.
D03RAF solves the nonlinear system in a rectangular domain, while D03RBF solves in a rectilinear region, i.e., a domain bounded by perpendicular straight lines.
Both routines use the method of lines and solve the resulting system of ordinary differential equations using a backward differentiation formula (BDF) method, modified Newton method, and BiCGSTAB iterative linear solver. Local uniform grid refinement is used to improve accuracy.
Utility routines D03RYF and D03RZF may be used in conjunction with D03RBF to check the user-supplied initial mesh, and extract mesh coordinate data.

3.8 Convection-diffusion Systems

There are three routines available for solving systems of convection-diffusion equations with optional source terms:
  • D03PFF,
  • D03PLF,
  • D03PSF.
Equations may include nonlinear terms but the time derivative should occur linearly. There are certain restrictions on the coefficients to ensure that the problems posed can be solved by the above routines, in particular the system must be posed in conservative form (see below). The routines may also be used to solve hyperbolic convection-only systems.
Convection terms are discretized using an upwind scheme involving a numerical flux function based on the solution of a Riemann problem at each mesh point (see LeVeque (1990)); and diffusion and source terms are discretized using central differences. The resulting system of ordinary differential equations is solved using a ‘stiff’ solver. In the case of Euler equations for a perfect gas various approximate and exact Riemann solvers are provided in D03PUF, D03PVF, D03PWF and D03PXF. These routines may be used in conjunction with D03PFF, D03PLF and D03PSF.
D03PFF is designed to solve systems of the form
∑ j = 1 n P i j x,t,U ∂ U j ∂ t + ∂ ∂ x F i x,t,U = C i x,t,U ∂ ∂ x D i x,t,U, U x + S i x,t,U ,
or hyperbolic convection-only systems of the form
∑ j = 1 n P i j x,t,U ∂ U j ∂ t + ∂ F i x,t,U ∂ x = 0 ,
where i=1,2,…,n, a≤x≤b, t≥t 0.
D03PLF is similar to D03PFF except that it provides scope for coupled differential algebraic systems. This extended functionality allows for the solution of more complex problems.
D03PSF is similar to D03PLF but allows remeshing to take place in the spatial direction. This facility can be very useful when the nature of the solution in the spatial direction varies considerably over time.

3.9 Automatic Mesh Generation

The routine D03MAF places a triangular mesh over a given two-dimensional region. The region may have any shape and may include holes. It may also be used in conjunction with routines from the NAG Finite Element Library. A wider range of mesh generation routines are available in Chapter D06.

3.10 Utility Routines

D03UAF (D03UBF) calculates, by the Strongly Implicit Procedure, an approximate correction to a current estimate of the solution of a system of simultaneous algebraic equations for which the iterative update matrix is of five (seven) point molecule form on a two- (three-) dimensional topologically-rectangular mesh.
Routines are available in the Linear Algebra Chapters for the direct and iterative solution of linear equations. Here we point to some of the routines that may be of use in solving the linear systems that arise from finite difference or finite element approximations to partial differential equation solutions. Chapters F01, F04, F07, F08 and F11 should be consulted for further information and for the appropriate routine documents. Decision trees for the solution of linear systems are given in Section 4 in the F04 Chapter Introduction.
The following routines allow the direct solution of symmetric positive definite systems:
Band | F07HDF (DPBTRF) and F07HEF (DPBTRS)
Variable band (skyline) | F01MCF and F04MCF
Tridiagonal | F07JAF (DPTSV), F07JDF (DPTTRF) and F07JEF (DPTTRS)
Sparse | F11JAF* and F11JBF
(* the description of F11JBF explains how F11JAF should be called to obtain a direct method) and the following routines allow the iterative solution of symmetric positive definite and symmetric-indefinite systems:
Sparse F11GDF, F11GEF, F11GFF, F11JAF, F11JCF and F11JEF.
The latter two routines above are black box routines which include Incomplete Cholesky, SSOR or Jacobi preconditioning.
The following routines allow the direct solution of nonsymmetric systems:
Band | F07BDF (DGBTRF) and F07BEF (DGBTRS)
Almost block-diagonal | F01LHF and F04LHF
Tridiagonal | F01LEF, F04LEF or F07CAF (DGTSV)
Sparse | F01BRF (and F01BSF) and F04AXF
and the following routines allow the iterative solution of nonsymmetric systems:
Sparse F11BDF, F11BEF, F11BFF, F11DAF, F11DCF and F11DEF.
The latter two routines above are black box routines which include incomplete LU, SSOR and Jacobi preconditioning.
The routines D03PYF and D03PZF use linear interpolation to compute the solution to a parabolic problem and its first derivative at the user-specified points. D03PZF may be used in conjunction with D03PCF/D03PCA, D03PEF, D03PHF/D03PHA, D03PKF, D03PPF/D03PPA and D03PRF. D03PYF may be used in conjunction with D03PDF/D03PDA and D03PJF/D03PJA.
D03RYF and D03RZF are utility routines for use in conjunction with D03RBF. They can be called to check the user-specified initial mesh and to extract mesh coordinate data.

4 Decision Trees

Tree 1

Does PDE have a time derivative? |  |  | Does PDE have second derivatives? |  |  | see Tree 4 Parabolic branch
 |  | yes |  |  | yes
 | no |  |  | no |
 |  |  | Is PDE hyperbolic? |  |  | see Tree 3 Hyperbolic branch
 |  |  |  |  | yes
 |  |  |  | no |
 |  |  | 1 space dimension? |  |  | Does PDE have coupled ODEs? |  |  | Is a remeshing process required? |  |  | D03PRF
 |  |  |  |  | yes |  |  | yes |  |  | yes
 |  |  |  | no |  |  | no |  |  | no |
 |  |  |  |  |  |  |  |  | D03PKF
 |  |  |  |  |  | D03PEF
 |  |  | N/A
see Tree 2 Elliptic branch

Tree 2: Elliptic branch

2 space dimensions? |  |  | Is the domain arbitrary? |  |  | D03EAF
 |  | yes |  |  | yes
 | no |  |  | no |
 |  |  | Is the domain topologically rectangular? |  |  | Do you want to use a multigrid scheme? |  |  | D03EDF with D03EEF
 |  |  |  |  | yes |  |  | yes
 |  |  |  | no |  |  | no |
 |  |  |  |  |  | D03EBF or D03UAF
 |  |  | D03EAF
3 space dimensions? |  |  | Is the domain topologically equivalent to a brick? |  |  | Is the PDE the Helmholtz equation? |  |  | D03FAF
 |  | yes |  |  | yes |  |  | yes
 | no |  |  | no |  |  | no |
 |  |  |  |  |  | D03ECF or D03UBF
 |  |  | N/A
N/A

Tree 3: Hyperbolic branch

1 space dimension? |  |  | Does PDE have coupled ODEs? |  |  | Is a remeshing process required? |  |  | D03PSF
 |  | yes |  |  | yes |  |  | yes
 | no |  |  | no |  |  | no |
 |  |  |  |  |  | D03PLF
 |  |  | D03PFF
N/A

Tree 4: Parabolic branch

1 space dimension? |  |  | Is PDE the Black–Scholes equations? |  |  | D03NCF or D03NDF
 |  | yes |  |  | yes
 | no |  |  | no |
 |  |  | Is PDE in conservative form? |  |  | Does PDE have coupled ODEs? |  |  | Is a remeshing process required? |  |  | D03PSF
 |  |  |  |  | yes |  |  | yes |  |  | yes
 |  |  |  | no |  |  | no |  |  | no |
 |  |  |  |  |  |  |  |  | D03PLF
 |  |  |  |  |  | D03PFF
 |  |  | see Tree 5 Branch for parabolic PDE in non-conservative form
2 space dimensions? |  |  | Is the domain rectangular? |  |  | D03RAF
 |  | yes |  |  | yes
 | no |  |  | no |
 |  |  | Is the domain rectilinear? |  |  | D03RBF
 |  |  |  |  | yes
 |  |  |  | no |
 |  |  | N/A
N/A

Tree 5: Branch for parabolic PDE in non-conservative form

Do you want to use finite differences? |  |  | Does PDE have coupled ODEs? |  |  | Is a remeshing process required? |  |  | D03PPF
 |  | yes |  |  | yes |  |  | yes
 | no |  |  | no |  |  | no |
 |  |  |  |  |  | D03PHF
 |  |  | D03PCF
Do you want to use Chebyshev collocation? |  |  | Does PDE have coupled ODEs? |  |  | D03PJF
 |  | yes |  |  | yes
 | no |  |  | no |
 |  |  | D03PDF
N/A

5 Functionality Index

Automatic mesh generation,
triangles over a plane domain D03MAF
Black–Scholes equation,
analytic D03NDF
finite difference D03NCF
Convection-diffusion system(s),
nonlinear,
one space dimension,
using upwind difference scheme based on Riemann solvers D03PFF
using upwind difference scheme based on Riemann solvers,
with coupled differential algebraic system D03PLF
with remeshing D03PSF
Elliptic equations,
discretization on rectangular grid (seven-point two-dimensional molecule) D03EEF
equations on rectangular grid (seven-point two-dimensional molecule) D03EDF
finite difference equations (five-point two-dimensional molecule) D03EBF
finite difference equations (seven-point three-dimensional molecule) D03ECF
Helmholtz's equation in three dimensions D03FAF
Laplace's equation in two dimensions D03EAF
First-order system(s),
nonlinear,
one space dimension,
using Keller box scheme D03PEF
using Keller box scheme,
with coupled differential algebraic system D03PKF
with remeshing D03PRF
PDEs, general system, one space variable, method of lines,
parabolic,
collocation spatial discretization,
coupled DAEs, comprehensive D03PJF
easy-to-use D03PDF
finite differences spatial discretization,
coupled DAEs, comprehensive D03PHF
coupled DAEs, remeshing, comprehensive D03PPF
easy-to-use D03PCF
Second order system(s),
nonlinear,
two space dimensions,
in rectangular domain D03RAF
in rectilinear domain D03RBF
Utility routine,
average values for D03NDF D03NEF
basic SIP for five-point two-dimensional molecule D03UAF
basic SIP for seven-point three-dimensional molecule D03UBF
check initial grid data for D03RBF D03RYF
exact Riemann solver for Euler equations D03PXF
HLL Riemann solver for Euler equations D03PWF
interpolation routine for collocation scheme D03PYF
interpolation routine for finite difference,
Keller box and upwind scheme D03PZF
Osher's Riemann solver for Euler equations D03PVF
return coordinates of grid points for D03RBF D03RZF
Roe's Riemann solver for Euler equations D03PUF

6 Auxiliary Routines Associated with Library Routine Arguments

D53PCK | nagf_pde_1d_parab_remesh_fd_dummy_odedef See the description of the argument ODEDEF in D03PHF/D03PHA, D03PJF/D03PJA and D03PPF/D03PPA.
D03PCK | nagf_pde_1d_parab_remesh_fd_dummy_odedef_old See the description of the argument ODEDEF in D03PHF/D03PHA, D03PJF/D03PJA and D03PPF/D03PPA.
D53PCL | nagf_pde_1d_parab_remesh_fd_dummy_monitf See the description of the argument MONITF in D03PPF/D03PPA.
D03PCL | nagf_pde_1d_parab_remesh_fd_dummy_monitf_old See the description of the argument MONITF in D03PPF/D03PPA.
D03PEK | nagf_pde_1d_parab_dae_keller_remesh_fd_dummy_odedef See the description of the argument ODEDEF in D03PKF, D03PLF, D03PRF and D03PSF.
D03PEL | nagf_pde_1d_parab_dae_keller_remesh_fd_dummy_monitf See the description of the argument MONITF in D03PRF and D03PSF.
D03PFP | nagf_pde_1d_parab_convdiff_sample_pdedef See the description of the argument PDEDEF in D03PFF.
D03PLP | nagf_pde_1d_parab_convdiff_dae_sample_pdedef See the description of the argument PDEDEF in D03PLF and D03PSF.

7 Routines Withdrawn or Scheduled for Withdrawal

None.

8 References

Ames W F (1977) Nonlinear Partial Differential Equations in Engineering (2nd Edition) Academic Press
Berzins M (1990) Developments in the NAG Library software for parabolic equations Scientific Software Systems (eds J C Mason and M G Cox) 59–72 Chapman and Hall
Jaswon M A and Symm G T (1977) Integral Equation Methods in Potential Theory and Elastostatics Academic Press
LeVeque R J (1990) Numerical Methods for Conservation Laws Birkhäuser Verlag
Mikhlin S G and Smolitsky K L (1967) Approximate Methods for the Solution of Differential and Integral Equations Elsevier
Mitchell A R and Griffiths D F (1980) The Finite Difference Method in Partial Differential Equations Wiley
Pennington S V and Berzins M (1994) New NAG Library software for first-order partial differential equations ACM Trans. Math. Softw. 20 63–99
Richtmyer R D and Morton K W (1967) Difference Methods for Initial-value Problems (2nd Edition) Interscience
Smith G D (1985) Numerical Solution of Partial Differential Equations: Finite Difference Methods (3rd Edition) Oxford University Press
Swarztrauber P N and Sweet R A (1979) Efficient Fortran subprograms for the solution of separable elliptic partial differential equations ACM Trans. Math. Software 5 352–364
Wait R and Mitchell A R (1985) Finite Element Analysis and Application Wiley
D03 Chapter Contents
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


D03MAF : NAG Library, Mark 26

D03 Chapter Contents
D03 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

D03MAF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

D03MAF places a triangular mesh over a given two-dimensional region. The region may have any shape, including one with holes.

2 Specification

SUBROUTINE D03MAF ( H, M, N, NB, NPTS, PLACES, INDX, SDINDX, ISIN, DIST, SDDIST, IFAIL)
INTEGER | M, N, NB, NPTS, INDX(4,SDINDX), SDINDX, ISIN, SDDIST, IFAIL
REAL (KIND=nag_wp) | H, PLACES(2,SDINDX), DIST(4,SDDIST)
EXTERNAL | ISIN

3 Description

D03MAF begins with a uniform triangular grid as shown in Figure 1 and assumes that the region to be triangulated lies within the rectangle given by the inequalities
0<x<3 m-1 h,  0<y<n-1 h.
This rectangle is drawn in bold in Figure 1. The region is specified by the ISIN which must determine whether any given point x,y lies in the region. The uniform grid is processed column-wise, with x 1,y 1 preceding x 2,y 2 if x 1<x 2 or x 1=x 2, y 1<y 2. Points near the boundary are moved onto it and points well outside the boundary are omitted. The direction of movement is chosen to avoid pathologically thin triangles. The points accepted are numbered in exactly the same order as the corresponding points of the uniform grid were scanned. The output consists of the x,y coordinates of all grid points and integers indicating whether they are internal and to which other points they are joined by triangle sides.
The mesh size h must be chosen small enough for the essential features of the region to be apparent from testing all points of the original uniform grid for being inside the region. For instance if any hole is within 2 h of another hole or the outer boundary then a triangle may be found with all vertices within 12 h of a boundary. Such a triangle is taken to be external to the region so the effect will be to join the hole to another hole or to the external region.
Further details of the algorithm are given in the references.
Figure 1

4 References

Reid J K (1970) Fortran subroutines for the solutions of Laplace's equation over a general routine in two dimensions Harwell Report TP422
Reid J K (1972) On the construction and convergence of a finite-element solution of Laplace's equation J. Instr. Math. Appl. 9 1–13

5 Arguments

1:   H – REAL (KIND=nag_wp)Input
On entry: h, the required length for the sides of the triangles of the uniform mesh.
2:   M – INTEGERInput
3:   N – INTEGERInput
On entry: values m and n such that all points x,y inside the region satisfy the inequalities
0≤x≤3 m-1 h, 0≤y≤n-1 h.
Constraint: M=N>2.
4:   NB – INTEGERInput
On entry: the number of times a triangle side is bisected to find a point on the boundary. A value of 10 is adequate for most purposes (see Section 7).
Constraint: NB≥1.
5:   NPTS – INTEGEROutput
On exit: the number of points in the triangulation.
6:   PLACES 2 SDINDX – REAL (KIND=nag_wp) arrayOutput
On exit: the x and y coordinates respectively of the ith point of the triangulation.
7:   INDX 4 SDINDX – INTEGER arrayOutput
On exit: INDX 1 i contains i if point i is inside the region and -i if it is on the boundary. For each triangle side between points i and j with j>i, INDX ki, k>1, contains j or -j according to whether point j is internal or on the boundary. There can never be more than three such points. If there are less, then some values INDX ki, k>1, are zero.
8:   SDINDX – INTEGERInput
On entry: the second dimension of the arrays PLACES and INDX as declared in the (sub)program from which D03MAF is called.
Constraint: SDINDX≥NPTS.
9:   ISIN – INTEGER FUNCTION, supplied by the user.External Procedure
ISIN must return the value 1 if the given point (X,Y) lies inside the region, and 0 if it lies outside.
The specification of ISIN is:
FUNCTION ISIN ( X, Y)
INTEGER ISIN
REAL (KIND=nag_wp) X, Y
1:   X – REAL (KIND=nag_wp)Input
2:   Y – REAL (KIND=nag_wp)Input
On entry: the coordinates of the given point.
ISIN must either be a module subprogram USEd by, or declared as EXTERNAL in, the (sub)program from which D03MAF is called. Arguments denoted as Input must not be changed by this procedure.
10:   DIST 4 SDDIST – REAL (KIND=nag_wp) arrayWorkspace
11:   SDDIST – INTEGERInput
On entry: the second dimension of the array DIST as declared in the (sub)program from which D03MAF is called.
Constraint: SDDIST≥4⁢N.
12:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
SDINDX is too small.
IFAIL=2
A point inside the region violates one of the constraints (see arguments M and N).
IFAIL=3
SDDIST is too small.
IFAIL=4
M≤2.
IFAIL=5
N≤2.
IFAIL=6
NB≤0.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

Points are moved onto the boundary by bisecting a triangle side NB times. The accuracy is therefore h×2-NB.

8 Parallelism and Performance

D03MAF is not threaded in any implementation.

9 Further Comments

The time taken is approximately proportional to m×n.

10 Example

The following program triangulates the circle with centre 7.0,7.0 and radius 6.0 using a basic grid size h=4.0.

10.1 Program Text

Program Text (d03mafe.f90)

10.2 Program Data

Program Data (d03mafe.d)

10.3 Program Results

Program Results (d03mafe.r)

GnuplotProduced by GNUPLOT 4.6 patchlevel 3 0 2 4 6 8 10 12 14 0 2 4 6 8 10 12 14 y x Example Program Triangulation of a Circle with centre (7,7) and radius 6 using grid size=4 gnuplot_plot_1
D03 Chapter Contents
D03 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


D03NCF : NAG Library, Mark 26

D03 Chapter Contents
D03 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

D03NCF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
▸▿ 9 Further Comments
9.1 Timing
9.2 Algorithmic Details
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

D03NCF solves the Black–Scholes equation for financial option pricing using a finite difference scheme.

2 Specification

SUBROUTINE D03NCF ( KOPT, X, MESH, NS, S, NT, T, TDPAR, R, Q, SIGMA, ALPHA, NTKEEP, F, THETA, DELTA, GAMMA, LAMBDA, RHO, LDF, WORK, IWORK, IFAIL)
INTEGER | KOPT, NS, NT, NTKEEP, LDF, IWORK(NS), IFAIL
REAL (KIND=nag_wp) | X, S(NS), T(NT), R(*), Q(*), SIGMA(*), ALPHA, F(LDF,NTKEEP), THETA(LDF,NTKEEP), DELTA(LDF,NTKEEP), GAMMA(LDF,NTKEEP), LAMBDA(LDF,NTKEEP), RHO(LDF,NTKEEP), WORK(4*NS)
LOGICAL | TDPAR(3)
CHARACTER(1) | MESH

3 Description

D03NCF solves the Black–Scholes equation (see Hull (1989) and Wilmott et al. (1995))
∂f ∂t +r-q S ∂f ∂S +σ 2S 2 2 ∂2 f ∂S 2 =rf (1)
Smin<S<Smax,  tmin<t<tmax, (2)
for the value f of a European or American, put or call stock option, with exercise price X. In equation (1) t is time, S is the stock price, r is the risk free interest rate, q is the continuous dividend, and σ is the stock volatility. According to the values in the array TDPAR, the arguments r, q and σ may each be either constant or functions of time. The routine also returns values of various Greeks.
D03NCF uses a finite difference method with a choice of time-stepping schemes. The method is explicit for ALPHA=0.0 and implicit for nonzero values of ALPHA. Second order time accuracy can be obtained by setting ALPHA=0.5. According to the value of the argument MESH the finite difference mesh may be either uniform, or user-defined in both S and t directions.

4 References

Hull J (1989) Options, Futures and Other Derivative Securities Prentice–Hall
Wilmott P, Howison S and Dewynne J (1995) The Mathematics of Financial Derivatives Cambridge University Press

5 Arguments

1:   KOPT – INTEGERInput
On entry: specifies the kind of option to be valued.
KOPT=1
A European call option.
KOPT=2
An American call option.
KOPT=3
A European put option.
KOPT=4
An American put option.
Constraint: KOPT=1, 2, 3 or 4.
2:   X – REAL (KIND=nag_wp)Input
On entry: the exercise price X.
3:   MESH – CHARACTER(1)Input
On entry: indicates the type of finite difference mesh to be used:
MESH='U'
Uniform mesh.
MESH='C'
Custom mesh supplied by you.
Constraint: MESH='U' or 'C'.
4:   NS – INTEGERInput
On entry: the number of stock prices to be used in the finite difference mesh.
Constraint: NS≥2.
5:   S NS – REAL (KIND=nag_wp) arrayInput/Output
On entry: if MESH='C', S i must contain the ith stock price in the mesh, for i=1,2,…,NS. These values should be in increasing order, with S 1=Smin and S NS=Smax.
If MESH='U', S 1 must be set to Smin and S NS to Smax, but S 2,S 3,…,S NS-1 need not be initialized, as they will be set internally by the routine in order to define a uniform mesh.
On exit: if MESH='U', the elements of S define a uniform mesh over Smin,Smax.
If MESH='C', the elements of S are unchanged.
Constraints:
  • if MESH='C', S 1≥0.0 and S i<S i+1, for i=1,2,…,NS-1;
  • if MESH='U', 0.0≤S 1<S NS.
6:   NT – INTEGERInput
On entry: the number of time-steps to be used in the finite difference method.
Constraint: NT≥2.
7:   T NT – REAL (KIND=nag_wp) arrayInput/Output
On entry: if MESH='C' then T j must contain the jth time in the mesh, for j=1,2,…,NT. These values should be in increasing order, with T 1=tmin and T NT=tmax.
If MESH='U' then T 1 must be set to tmin and T NT to tmax, but T 2,T 3,…,T NT-1 need not be initialized, as they will be set internally by the routine in order to define a uniform mesh.
On exit: if MESH='U', the elements of T define a uniform mesh over tmin,tmax.
If MESH='C', the elements of T are unchanged.
Constraints:
  • if MESH='C', T 1≥0.0 and T j<T j+1, for j=1,2,…,NT-1;
  • if MESH='U', 0.0≤T 1<T NT.
8:   TDPAR 3 – LOGICAL arrayInput
On entry: specifies whether or not various arguments are time-dependent. More precisely, r is time-dependent if TDPAR 1=.TRUE. and constant otherwise. Similarly, TDPAR 2 specifies whether q is time-dependent and TDPAR 3 specifies whether σ is time-dependent.
9:   R* – REAL (KIND=nag_wp) arrayInput
Note: the dimension of the array R must be at least NT if TDPAR 1=.TRUE., and at least 1 otherwise.
On entry: if TDPAR 1=.TRUE. then R j must contain the value of the risk-free interest rate r t at the jth time in the mesh, for j=1,2,…,NT.
If TDPAR 1=.FALSE. then R 1 must contain the constant value of the risk-free interest rate r. The remaining elements need not be set.
10:   Q* – REAL (KIND=nag_wp) arrayInput
Note: the dimension of the array Q must be at least NT if TDPAR 2=.TRUE., and at least 1 otherwise.
On entry: if TDPAR 2=.TRUE. then Q j must contain the value of the continuous dividend q t at the jth time in the mesh, for j=1,2,…,NT.
If TDPAR 2=.FALSE. then Q 1 must contain the constant value of the continuous dividend q. The remaining elements need not be set.
11:   SIGMA* – REAL (KIND=nag_wp) arrayInput
Note: the dimension of the array SIGMA must be at least NT if TDPAR 3=.TRUE., and at least 1 otherwise.
On entry: if TDPAR 3=.TRUE. then SIGMA j must contain the value of the volatility σ t at the jth time in the mesh, for j=1,2,…,NT.
If TDPAR 3=.FALSE. then SIGMA 1 must contain the constant value of the volatility σ. The remaining elements need not be set.
12:   ALPHA – REAL (KIND=nag_wp)Input
On entry: the value of λ to be used in the time-stepping scheme. Typical values include:
ALPHA=0.0
Explicit forward Euler scheme.
ALPHA=0.5
Implicit Crank–Nicolson scheme.
ALPHA=1.0
Implicit backward Euler scheme.
The value 0.5 gives second-order accuracy in time. Values greater than 0.5 give unconditional stability. Since 0.5 is at the limit of unconditional stability this value does not damp oscillations.
Suggested value: ALPHA=0.55.
Constraint: 0.0≤ALPHA≤1.0.
13:   NTKEEP – INTEGERInput
On entry: the number of solutions to be stored in the time direction. The routine calculates the solution backwards from T NT to T 1 at all times in the mesh. These time solutions and the corresponding Greeks will be stored at times T i, for i=1,2,…,NTKEEP, in the arrays F, THETA, DELTA, GAMMA, LAMBDA and RHO. Other time solutions will be discarded. To store all time solutions set NTKEEP=NT.
Constraint: 1≤NTKEEP≤NT.
14:   F LDFNTKEEP – REAL (KIND=nag_wp) arrayOutput
On exit: F ij, for i=1,2,…,NS and j=1,2,…,NTKEEP, contains the value f of the option at the ith mesh point S i at time T j.
15:   THETA LDFNTKEEP – REAL (KIND=nag_wp) arrayOutput
16:   DELTA LDFNTKEEP – REAL (KIND=nag_wp) arrayOutput
17:   GAMMA LDFNTKEEP – REAL (KIND=nag_wp) arrayOutput
18:   LAMBDA LDFNTKEEP – REAL (KIND=nag_wp) arrayOutput
19:   RHO LDFNTKEEP – REAL (KIND=nag_wp) arrayOutput
On exit: the values of various Greeks at the ith mesh point S i at time T j, as follows:
THETA ij= ∂f ∂t , DELTA ij= ∂f ∂S , GAMMA ij= ∂2 f ∂S 2 , LAMBDA ij= ∂f ∂σ , RHO ij= ∂f ∂r .
20:   LDF – INTEGERInput
On entry: the first dimension of the arrays F, THETA, DELTA, GAMMA, LAMBDA and RHO as declared in the (sub)program from which D03NCF is called.
Constraint: LDF≥NS.
21:   WORK 4×NS – REAL (KIND=nag_wp) arrayWorkspace
22:   IWORK NS – INTEGER arrayWorkspace
23:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, | KOPT<1,
or | KOPT>4,
or | MESH≠'U' or 'C',
or | NS<2,
or | NT<2,
or | S 1<0.0,
or | T 1<0.0,
or | ALPHA<0.0,
or | ALPHA>1.0,
or | NTKEEP<1,
or | NTKEEP>NT,
or | LDF<NS.
IFAIL=2
MESH='U' and the constraints:
  • S 1<S NS,
  • T 1<T NT
are violated. Thus the end points of the uniform mesh are not in order.
IFAIL=3
MESH='C' and the constraints:
  • S i<S i+1, for i=1,2,…,NS-1,
  • T i<T i+1, for i=1,2,…,NT-1
are violated. Thus the mesh points are not in order.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

The accuracy of the solution f and the various derivatives returned by the routine is dependent on the values of NS and NT supplied, the distribution of the mesh points, and the value of ALPHA chosen. For most choices of ALPHA the solution has a truncation error which is second-order accurate in S and first order accurate in t. For ALPHA=0.5 the truncation error is also second-order accurate in t.
The simplest approach to improving the accuracy is to increase the values of both NS and NT.

8 Parallelism and Performance

D03NCF is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
D03NCF makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

9.1 Timing

Each time-step requires the construction and solution of a tridiagonal system of linear equations. To calculate each of the derivatives LAMBDA and RHO requires a repetition of the entire solution process. The time taken for a call to the routine is therefore proportional to NS×NT.

9.2 Algorithmic Details

D03NCF solves equation (1) using a finite difference method. The solution is computed backwards in time from tmax to tmin using a λ scheme, which is implicit for all nonzero values of λ, and is unconditionally stable for values of λ>0.5. For each time-step a tridiagonal system is constructed and solved to obtain the solution at the earlier time. For the explicit scheme (λ=0) this tridiagonal system degenerates to a diagonal matrix and is solved trivially. For American options the solution at each time-step is inspected to check whether early exercise is beneficial, and amended accordingly.
To compute the arrays LAMBDA and RHO, which are derivatives of the stock value f with respect to the problem arguments σ and r respectively, the entire solution process is repeated with perturbed values of these arguments.

10 Example

This example, taken from Hull (1989), solves the one-dimensional Black–Scholes equation for valuation of a 5-month American put option on a non-dividend-paying stock with an exercise price of $50. The risk-free interest rate is 10% per annum, and the stock volatility is 40% per annum.
A fully implicit backward Euler scheme is used, with a mesh of 20 stock price intervals and 10 time intervals.

10.1 Program Text

Program Text (d03ncfe.f90)

10.2 Program Data

Program Data (d03ncfe.d)

10.3 Program Results

Program Results (d03ncfe.r)

GnuplotProduced by GNUPLOT 4.6 patchlevel 3 −40 −20 0 20 40 0 20 40 60 80 100 −10 −5 0 5 10 15 Option Values Derivatives Stock Price Example Program Option Values and Derivatives at 5 Months to Maturity option values θ δ γ λ ρ gnuplot_plot_1 gnuplot_plot_2 gnuplot_plot_3 gnuplot_plot_4 gnuplot_plot_5 gnuplot_plot_6
GnuplotProduced by GNUPLOT 4.6 patchlevel 3 −40 −20 0 20 40 0 20 40 60 80 100 −8 −6 −4 −2 0 2 4 6 8 10 12 Option Values Derivatives Stock Price Option Values and Derivatives at 3.5 Months to Maturity option values θ δ γ λ ρ gnuplot_plot_1 gnuplot_plot_2 gnuplot_plot_3 gnuplot_plot_4 gnuplot_plot_5 gnuplot_plot_6
D03 Chapter Contents
D03 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


D03NDF : NAG Library, Mark 26

D03 Chapter Contents
D03 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

D03NDF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
▸▿ 9 Further Comments
9.1 Algorithmic Details
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

D03NDF computes an analytic solution to the Black–Scholes equation for a certain set of option types.

2 Specification

SUBROUTINE D03NDF ( KOPT, X, S, T, TMAT, TDPAR, R, Q, SIGMA, F, THETA, DELTA, GAMMA, LAMBDA, RHO, IFAIL)
INTEGER | KOPT, IFAIL
REAL (KIND=nag_wp) | X, S, T, TMAT, R(*), Q(*), SIGMA(*), F, THETA, DELTA, GAMMA, LAMBDA, RHO
LOGICAL | TDPAR(3)

3 Description

D03NDF computes an analytic solution to the Black–Scholes equation (see Hull (1989) and Wilmott et al. (1995))
∂f ∂t + r-q S ∂f ∂S + σ 2 S 2 2 ∂2 f ∂S 2 =rf (1)
Smin< S<Smax,   tmin<t< tmax, (2)
for the value f of a European put or call option, or an American call option with zero dividend q. In equation (1) t is time, S is the stock price, X is the exercise price, r is the risk free interest rate, q is the continuous dividend, and σ is the stock volatility. The parameter r, q and σ may be either constant, or functions of time. In the latter case their average instantaneous values over the remaining life of the option should be provided to D03NDF. An auxiliary routine D03NEF is available to compute such averages from values at a set of discrete times. Equation (1) is subject to different boundary conditions depending on the type of option. For a call option the boundary condition is
f S, t = tmat = max 0,S-X
where tmat is the maturity time of the option. For a put option the equation (1) is subject to
f S, t = tmat = max 0,X-S .
D03NDF also returns values of the Greeks
Θ= ∂f ∂t ,   Δ= ∂f ∂x ,   Γ= ∂2 f ∂x 2 ,   Λ= ∂f ∂σ ,   ρ= ∂f ∂r .
S30ABF also computes the European option price given by the Black–Scholes–Merton formula together with a more comprehensive set of sensitivities (Greeks).
Further details of the analytic solution returned are given in Section 9.1.

4 References

Hull J (1989) Options, Futures and Other Derivative Securities Prentice–Hall
Wilmott P, Howison S and Dewynne J (1995) The Mathematics of Financial Derivatives Cambridge University Press

5 Arguments

1:   KOPT – INTEGERInput
On entry: specifies the kind of option to be valued:
KOPT=1
A European call option.
KOPT=2
An American call option.
KOPT=3
A European put option.
Constraints:
  • KOPT=1, 2 or 3;
  • if q≠0, KOPT≠2.
2:   X – REAL (KIND=nag_wp)Input
On entry: the exercise price X.
Constraint: X≥0.0.
3:   S – REAL (KIND=nag_wp)Input
On entry: the stock price at which the option value and the Greeks should be evaluated.
Constraint: S≥0.0.
4:   T – REAL (KIND=nag_wp)Input
On entry: the time at which the option value and the Greeks should be evaluated.
Constraint: T≥0.0.
5:   TMAT – REAL (KIND=nag_wp)Input
On entry: the maturity time of the option.
Constraint: TMAT≥T.
6:   TDPAR 3 – LOGICAL arrayInput
On entry: specifies whether or not various arguments are time-dependent. More precisely, r is time-dependent if TDPAR 1=.TRUE. and constant otherwise. Similarly, TDPAR 2 specifies whether q is time-dependent and TDPAR 3 specifies whether σ is time-dependent.
7:   R* – REAL (KIND=nag_wp) arrayInput
Note: the dimension of the array R must be at least 3 if TDPAR 1=.TRUE., and at least 1 otherwise.
On entry: if TDPAR 1=.FALSE. then R 1 must contain the constant value of r. The remaining elements need not be set.
If TDPAR 1=.TRUE. then R 1 must contain the value of r at time T and R 2 must contain its average instantaneous value over the remaining life of the option:
r^=∫TTMAT r ζ dζ.
The auxiliary routine D03NEF may be used to construct R from a set of values of r at discrete times.
8:   Q* – REAL (KIND=nag_wp) arrayInput
Note: the dimension of the array Q must be at least 3 if TDPAR 2=.TRUE., and at least 1 otherwise.
On entry: if TDPAR 2=.FALSE. then Q 1 must contain the constant value of q. The remaining elements need not be set.
If TDPAR 2=.TRUE. then Q 1 must contain the constant value of q and Q 2 must contain its average instantaneous value over the remaining life of the option:
q^=∫TTMAT q ζ dζ.
The auxiliary routine D03NEF may be used to construct Q from a set of values of q at discrete times.
9:   SIGMA* – REAL (KIND=nag_wp) arrayInput
Note: the dimension of the array SIGMA must be at least 3 if TDPAR 3=.TRUE., and at least 1 otherwise.
On entry: if TDPAR 3=.FALSE. then SIGMA 1 must contain the constant value of σ. The remaining elements need not be set.
If TDPAR 3=.TRUE. then SIGMA 1 must contain the value of σ at time T, SIGMA 2 the average instantaneous value σ^, and SIGMA 3 the second-order average σ-, where:
σ^=∫TTMAT σ ζ dζ,
σ-= ∫TTMAT σ 2 ζ dζ 1/2 .
The auxiliary routine D03NEF may be used to compute SIGMA from a set of values at discrete times.
Constraints:
  • if TDPAR 3=.FALSE., SIGMA 1>0.0;
  • if TDPAR 3=.TRUE., SIGMA i>0.0, for i=1,2,3.
10:   F – REAL (KIND=nag_wp)Output
On exit: the value f of the option at the stock price S and time T.
11:   THETA – REAL (KIND=nag_wp)Output
12:   DELTA – REAL (KIND=nag_wp)Output
13:   GAMMA – REAL (KIND=nag_wp)Output
14:   LAMBDA – REAL (KIND=nag_wp)Output
15:   RHO – REAL (KIND=nag_wp)Output
On exit: the values of various Greeks at the stock price S and time T, as follows:
THETA=Θ= ∂f ∂t , DELTA=Δ= ∂f ∂S , GAMMA=Γ= ∂2 f ∂S 2 , LAMBDA=Λ= ∂f ∂σ , RHO=ρ= ∂f ∂r .
16:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, | KOPT<1,
or | KOPT>3,
or | KOPT=2 when q≠0,
or | X<0.0,
or | S<0.0,
or | T<0.0,
or | TMAT<T,
or | SIGMA 1≤0.0, with TDPAR 3=.FALSE.,
or | SIGMA i≤0.0, with TDPAR 3=.TRUE., for some i=1, 2 or 3.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

Given accurate values of R, Q and SIGMA no further approximations are made in the evaluation of the Black–Scholes analytic formulae, and the results should therefore be within machine accuracy. The values of R, Q and SIGMA returned from D03NEF are exact for polynomials of degree up to 3.

8 Parallelism and Performance

D03NDF is not threaded in any implementation.

9 Further Comments

9.1 Algorithmic Details

The Black–Scholes analytic formulae are used to compute the solution. For a European call option these are as follows:
f= S e -q^ T-t N d 1- X e -r^ T-t N d 2
where
d 1 = log S/X+r^-q^+σ-2/2T-t σ-T-t , d 2 = log S/X+r^-q^-σ-2/2T-t σ-T-t =d 1-σ-T-t,
N x is the cumulative Normal distribution function and N′x is its derivative
N x = 1 2 π ∫-∞x e-ζ 2/2 dζ, N′x = 1 2 π e-x 2/2.
The functions q^, r^, σ^ and σ- are average values of q, r and σ over the time to maturity:
q^ = 1 T-t ∫tT q ζ dζ, r^ = 1 T-t ∫tT r ζ dζ, σ^ = 1 T-t ∫tT σ ζ dζ, σ- = 1 T-t ∫tT σ 2 ζ dζ 1/2 .
The Greeks are then calculated as follows:
Δ = ∂f ∂S =e-q^T-t N d 1+ S e-q^T-t N′d 1-X e-r^T-t N′d 2 σ-S⁢T-t , Γ = ∂2 f ∂S 2 = S e-q^T-t N′d 1+X e-r^T-t N′d 2 σ-S 2 T-t + S e-q^T-t N′d 1-X e-r^T-t N′d 2 σ-2S 2 T-t , Θ = ∂f ∂t =rf+q-r SΔ- σ 2 S 2 2 Γ, Λ = ∂f ∂σ = X d 1 e-r^T-t N′d 2-S d 2 e-q^T-t N′d 1 σ-2 σ^, ρ = ∂f ∂r =X T-t e-r^T-t N d 2+ S e-q^T-t N′d 1-X e-r^T-t N′d 2 T-t σ-.
Note: that Θ is obtained from substitution of other Greeks in the Black–Scholes partial differential equation, rather than differentiation of f. The values of q, r and σ appearing in its definition are the instantaneous values, not the averages. Note also that both the first-order average σ^ and the second-order average σ- appear in the expression for Λ. This results from the fact that Λ is the derivative of f with respect to σ, not σ^.
For a European put option the equivalent equations are:
f = X e-r^T-t N-d 2-S e-q^T-t N-d 1, Δ = ∂f ∂S =-e-q^T-t N-d 1+ S e-q^T-t N′-d 1-X e-r^T-t N′-d 2 σ-S⁢T-t , Γ = ∂2 f ∂S 2 = X e-r^T-t N′-d 2+S e-q^T-t N′-d 1 σ-S 2 T-t + X e-r^T-t N′′-d 2-S e-q^T-t N′′-d 1 σ-2S 2 T-t , Θ = ∂f ∂t =rf+q-r SΔ- σ 2S 2 2 Γ, Λ = ∂f ∂σ = X d 1 e-r^T-t N′-d 2-S d 2 e-q^T-t N′-d 1 σ-2 σ^, ρ = ∂f ∂r =-X T-t e-r^T-t N-d 2+ S e-q^T-t N′-d 1-X e-r^T-t N′-d 2 T-t σ^.
The analytic solution for an American call option with q=0 is identical to that for a European call, since early exercise is never optimal in this case. For all other cases no analytic solution is known.

10 Example

This example solves the Black–Scholes equation for valuation of a 5-month American call option on a non-dividend-paying stock with an exercise price of $50. The risk-free interest rate is 10% per annum, and the stock volatility is 40% per annum.
The option is valued at a range of times and stock prices.

10.1 Program Text

Program Text (d03ndfe.f90)

10.2 Program Data

Program Data (d03ndfe.d)

10.3 Program Results

Program Results (d03ndfe.r)

GnuplotProduced by GNUPLOT 4.6 patchlevel 3 −30 −20 −10 0 10 20 30 40 50 0 20 40 60 80 100 −10 −5 0 5 10 15 20 Option Values Derivatives Stock Price Example Program 1 Option Values and Derivatives at 5 Months to Maturity option values θ δ γ λ ρ gnuplot_plot_1 gnuplot_plot_2 gnuplot_plot_3 gnuplot_plot_4 gnuplot_plot_5 gnuplot_plot_6
GnuplotProduced by GNUPLOT 4.6 patchlevel 3 −30 −20 −10 0 10 20 30 40 50 0 20 40 60 80 100 −10 −5 0 5 10 15 20 Option Values Derivatives Stock Price Example Program 2 Option Values and Derivatives at 3.5 Months to Maturity option values θ δ γ λ ρ gnuplot_plot_1 gnuplot_plot_2 gnuplot_plot_3 gnuplot_plot_4 gnuplot_plot_5 gnuplot_plot_6
D03 Chapter Contents
D03 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


D03NEF : NAG Library, Mark 26

D03 Chapter Contents
D03 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

D03NEF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
▸▿ 9 Further Comments
9.1 Timing
9.2 Use with D03NDF
9.3 Algorithmic Details
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

D03NEF computes average values of a continuous function of time over the remaining life of an option. It is used together with D03NDF to value options with time-dependent arguments.

2 Specification

SUBROUTINE D03NEF ( T0, TMAT, NTD, TD, PHID, PHIAV, WORK, LWORK, IFAIL)
INTEGER | NTD, LWORK, IFAIL
REAL (KIND=nag_wp) | T0, TMAT, TD(NTD), PHID(NTD), PHIAV(3), WORK(LWORK)

3 Description

D03NEF computes the quantities
ϕ t 0,   ϕ^=1 T-t 0 ∫t 0 T ϕ ζ dζ,   ϕ-= 1 T-t 0 ∫t 0 T ϕ 2 ζ dζ 1/2
from a given set of values PHID of a continuous time-dependent function ϕ t at a set of discrete points TD, where t 0 is the current time and T is the maturity time. Thus ϕ^ and ϕ- are first and second order averages of ϕ over the remaining life of an option.
The routine may be used in conjunction with D03NDF in order to value an option in the case where the risk-free interest rate r, the continuous dividend q, or the stock volatility σ is time-dependent and is described by values at a set of discrete times (see Section 9.2). This is illustrated in Section 10.

4 References

None.

5 Arguments

1:   T0 – REAL (KIND=nag_wp)Input
On entry: the current time t 0.
Constraint: TD 1≤T0≤TD NTD.
2:   TMAT – REAL (KIND=nag_wp)Input
On entry: the maturity time T.
Constraint: TD 1≤TMAT≤TD NTD.
3:   NTD – INTEGERInput
On entry: the number of discrete times at which ϕ is given.
Constraint: NTD≥2.
4:   TD NTD – REAL (KIND=nag_wp) arrayInput
On entry: the discrete times at which ϕ is specified.
Constraint: TD 1<TD 2<⋯<TD NTD.
5:   PHID NTD – REAL (KIND=nag_wp) arrayInput
On entry: PHID i must contain the value of ϕ at time TD i, for i=1,2,…,NTD.
6:   PHIAV 3 – REAL (KIND=nag_wp) arrayOutput
On exit: PHIAV 1 contains the value of ϕ interpolated to t 0, PHIAV 2 contains the first-order average ϕ^ and PHIAV 3 contains the second-order average ϕ-, where:
ϕ^=1 T-t 0 ∫t 0 T ϕ ζ dζ ,   ϕ-= 1 T-t 0 ∫t 0 T ϕ 2 ζ dζ 1/2 .
7:   WORK LWORK – REAL (KIND=nag_wp) arrayWorkspace
8:   LWORK – INTEGERInput
On entry: the dimension of the array WORK as declared in the (sub)program from which D03NEF is called.
Constraint: LWORK≥9×NTD+24.
9:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, | T0 lies outside the range [TD 1,TD NTD],
or | TMAT lies outside the range [TD 1,TD NTD],
or | NTD<2,
or | TD badly ordered,
or | LWORK<9×NTD+24.
IFAIL=2
Unexpected failure in internal call to E01BAF or E02BBF.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

If ϕ∈C 4 t 0,T then the error in the approximation of ϕ t 0 and ϕ^ is O H 4, where H=maxi T i+1-T i, for i=1,2,…,NTD-1. The approximation is exact for polynomials of degree up to 3.
The third quantity ϕ- is O H 2, and exact for linear functions.

8 Parallelism and Performance

D03NEF is not threaded in any implementation.

9 Further Comments

9.1 Timing

The time taken is proportional to NTD.

9.2 Use with D03NDF

Suppose you wish to evaluate the analytic solution of the Black–Scholes equation in the case when the risk-free interest rate r is a known function of time, and is represented as a set of values at discrete times. A call to D03NEF providing these values in PHID produces an output array PHIAV suitable for use as the argument R in a subsequent call to D03NDF.
Time-dependent values of the continuous dividend Q and the volatility σ may be handled in the same way.

9.3 Algorithmic Details

The NTD data points are fitted with a cubic B-spline using the routine E01BAF. Evaluation is then performed using E02BBF, and the definite integrals are computed using direct integration of the cubic splines in each interval. The special case of T=to is handled by interpolating ϕ at that point.

10 Example

This example demonstrates the use of the routine in conjunction with D03NDF to solve the Black–Scholes equation for valuation of a 5-month American call option on a non-dividend-paying stock with an exercise price of $50. The risk-free interest rate varies linearly with time and the stock volatility has a quadratic variation. Since these functions are integrated exactly by D03NEF the solution of the Black–Scholes equation by D03NDF is also exact.
The option is valued at a range of times and stock prices.

10.1 Program Text

Program Text (d03nefe.f90)

10.2 Program Data

Program Data (d03nefe.d)

10.3 Program Results

Program Results (d03nefe.r)

GnuplotProduced by GNUPLOT 4.6 patchlevel 3 −30 −20 −10 0 10 20 30 40 50 0 20 40 60 80 100 −10 −5 0 5 10 15 20 Option Values Derivatives Stock Price Example Program 1 Option Values and Derivatives at 5 Months to Maturity option values θ δ γ λ ρ gnuplot_plot_1 gnuplot_plot_2 gnuplot_plot_3 gnuplot_plot_4 gnuplot_plot_5 gnuplot_plot_6
GnuplotProduced by GNUPLOT 4.6 patchlevel 3 −30 −20 −10 0 10 20 30 40 50 0 20 40 60 80 100 −10 −5 0 5 10 15 20 Option Values Derivatives Stock Price Example Program 2 Option Values and Derivatives at 3.5 Months to Maturity option values θ δ γ λ ρ gnuplot_plot_1 gnuplot_plot_2 gnuplot_plot_3 gnuplot_plot_4 gnuplot_plot_5 gnuplot_plot_6
D03 Chapter Contents
D03 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


D03PCF/D03PCA : NAG Library, Mark 26

D03 Chapter Contents
D03 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

D03PCF/D03PCA

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
▸▿ 2 Specification
2.1 Specification for D03PCF
2.2 Specification for D03PCA
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

D03PCF/D03PCA integrates a system of linear or nonlinear parabolic partial differential equations (PDEs) in one space variable. The spatial discretization is performed using finite differences, and the method of lines is employed to reduce the PDEs to a system of ordinary differential equations (ODEs). The resulting system is solved using a backward differentiation formula method.
D03PCA is a version of D03PCF that has additional arguments in order to make it safe for use in multithreaded applications (see Section 5).

2 Specification

2.1 Specification for D03PCF

SUBROUTINE D03PCF ( NPDE, M, TS, TOUT, PDEDEF, BNDARY, U, NPTS, X, ACC, RSAVE, LRSAVE, ISAVE, LISAVE, ITASK, ITRACE, IND, IFAIL)
INTEGER | NPDE, M, NPTS, LRSAVE, ISAVE(LISAVE), LISAVE, ITASK, ITRACE, IND, IFAIL
REAL (KIND=nag_wp) | TS, TOUT, U(NPDE,NPTS), X(NPTS), ACC, RSAVE(LRSAVE)
EXTERNAL | PDEDEF, BNDARY

2.2 Specification for D03PCA

SUBROUTINE D03PCA ( NPDE, M, TS, TOUT, PDEDEF, BNDARY, U, NPTS, X, ACC, RSAVE, LRSAVE, ISAVE, LISAVE, ITASK, ITRACE, IND, IUSER, RUSER, CWSAV, LWSAV, IWSAV, RWSAV, IFAIL)
INTEGER | NPDE, M, NPTS, LRSAVE, ISAVE(LISAVE), LISAVE, ITASK, ITRACE, IND, IUSER(*), IWSAV(505), IFAIL
REAL (KIND=nag_wp) | TS, TOUT, U(NPDE,NPTS), X(NPTS), ACC, RSAVE(LRSAVE), RUSER(*), RWSAV(1100)
LOGICAL | LWSAV(100)
CHARACTER(80) | CWSAV(10)
EXTERNAL | PDEDEF, BNDARY

3 Description

D03PCF/D03PCA integrates the system of parabolic equations:
∑j=1 NPDE P i,j ∂Uj ∂t +Qi=x-m ∂∂x xm Ri,  i=1,2,…,NPDE,  a≤x≤b,  t≥t 0, (1)
where P i,j, Qi and Ri depend on x, t, U, Ux and the vector U is the set of solution values
U x,t = U 1 x,t ,…, U NPDE x,t T , (2)
and the vector Ux is its partial derivative with respect to x. Note that P i,j, Qi and Ri must not depend on ∂U ∂t .
The integration in time is from t 0 to tout, over the space interval a≤x≤b, where a=x 1 and b=xNPTS are the leftmost and rightmost points of a user-defined mesh x 1,x 2,…,xNPTS. The coordinate system in space is defined by the value of m; m=0 for Cartesian coordinates, m=1 for cylindrical polar coordinates and m=2 for spherical polar coordinates. The mesh should be chosen in accordance with the expected behaviour of the solution.
The system is defined by the functions P i,j, Qi and Ri which must be specified in PDEDEF.
The initial values of the functions U x,t must be given at t=t 0. The functions Ri, for i=1,2,…,NPDE, which may be thought of as fluxes, are also used in the definition of the boundary conditions for each equation. The boundary conditions must have the form
βi x,t Ri x,t,U,Ux=γi x,t,U,Ux,  i=1,2,…,NPDE, (3)
where x=a or x=b.
The boundary conditions must be specified in BNDARY.
The problem is subject to the following restrictions:
(i) | t 0<tout, so that integration is in the forward direction;
(ii) | P i,j, Qi and the flux Ri must not depend on any time derivatives;
(iii) | the evaluation of the functions P i,j, Qi and Ri is done at the mid-points of the mesh intervals by calling the PDEDEF for each mid-point in turn. Any discontinuities in these functions must therefore be at one or more of the mesh points x 1,x 2,…,xNPTS;
(iv) | at least one of the functions P i,j must be nonzero so that there is a time derivative present in the problem; and
(v) | if m>0 and x 1=0.0, which is the left boundary point, then it must be ensured that the PDE solution is bounded at this point. This can be done by either specifying the solution at x=0.0 or by specifying a zero flux there, that is βi=1.0 and γi=0.0. See also Section 9.
The parabolic equations are approximated by a system of ODEs in time for the values of Ui at mesh points. For simple problems in Cartesian coordinates, this system is obtained by replacing the space derivatives by the usual central, three-point finite difference formula. However, for polar and spherical problems, or problems with nonlinear coefficients, the space derivatives are replaced by a modified three-point formula which maintains second-order accuracy. In total there are NPDE×NPTS ODEs in the time direction. This system is then integrated forwards in time using a backward differentiation formula method.

4 References

Berzins M (1990) Developments in the NAG Library software for parabolic equations Scientific Software Systems (eds J C Mason and M G Cox) 59–72 Chapman and Hall
Berzins M, Dew P M and Furzeland R M (1989) Developing software for time-dependent problems using the method of lines and differential-algebraic integrators Appl. Numer. Math. 5 375–397
Dew P M and Walsh J (1981) A set of library routines for solving parabolic equations in one space variable ACM Trans. Math. Software 7 295–314
Skeel R D and Berzins M (1990) A method for the spatial discretization of parabolic equations in one space variable SIAM J. Sci. Statist. Comput. 11(1) 1–32

5 Arguments

1:   NPDE – INTEGERInput
On entry: the number of PDEs in the system to be solved.
Constraint: NPDE≥1.
2:   M – INTEGERInput
On entry: the coordinate system used:
M=0
Indicates Cartesian coordinates.
M=1
Indicates cylindrical polar coordinates.
M=2
Indicates spherical polar coordinates.
Constraint: M=0, 1 or 2.
3:   TS – REAL (KIND=nag_wp)Input/Output
On entry: the initial value of the independent variable t.
On exit: the value of t corresponding to the solution values in U. Normally TS=TOUT.
Constraint: TS<TOUT.
4:   TOUT – REAL (KIND=nag_wp)Input
On entry: the final value of t to which the integration is to be carried out.
5:   PDEDEF – SUBROUTINE, supplied by the user.External Procedure
PDEDEF must compute the functions P i,j, Qi and Ri which define the system of PDEs. PDEDEF is called approximately midway between each pair of mesh points in turn by D03PCF/D03PCA.
The specification of PDEDEF for D03PCF is:
SUBROUTINE PDEDEF ( NPDE, T, X, U, UX, P, Q, R, IRES)
INTEGER | NPDE, IRES
REAL (KIND=nag_wp) | T, X, U(NPDE), UX(NPDE), P(NPDE,NPDE), Q(NPDE), R(NPDE)
The specification of PDEDEF for D03PCA is:
SUBROUTINE PDEDEF ( NPDE, T, X, U, UX, P, Q, R, IRES, IUSER, RUSER)
INTEGER | NPDE, IRES, IUSER(*)
REAL (KIND=nag_wp) | T, X, U(NPDE), UX(NPDE), P(NPDE,NPDE), Q(NPDE), R(NPDE), RUSER(*)
1:   NPDE – INTEGERInput
On entry: the number of PDEs in the system.
2:   T – REAL (KIND=nag_wp)Input
On entry: the current value of the independent variable t.
3:   X – REAL (KIND=nag_wp)Input
On entry: the current value of the space variable x.
4:   U NPDE – REAL (KIND=nag_wp) arrayInput
On entry: U i contains the value of the component Ui x,t, for i=1,2,…,NPDE.
5:   UX NPDE – REAL (KIND=nag_wp) arrayInput
On entry: UX i contains the value of the component ∂Ui x,t ∂x , for i=1,2,…,NPDE.
6:   P NPDENPDE – REAL (KIND=nag_wp) arrayOutput
On exit: P ij must be set to the value of P i,j x,t,U,Ux, for i=1,2,…,NPDE and j=1,2,…,NPDE.
7:   Q NPDE – REAL (KIND=nag_wp) arrayOutput
On exit: Q i must be set to the value of Qi x,t,U,Ux, for i=1,2,…,NPDE.
8:   R NPDE – REAL (KIND=nag_wp) arrayOutput
On exit: R i must be set to the value of Ri x,t,U,Ux, for i=1,2,…,NPDE.
9:   IRES – INTEGERInput/Output
On entry: set to -1​ or ​1.
On exit: should usually remain unchanged. However, you may set IRES to force the integration routine to take certain actions as described below:
IRES=2
Indicates to the integrator that control should be passed back immediately to the calling (sub)routine with the error indicator set to IFAIL=6.
IRES=3
Indicates to the integrator that the current time step should be abandoned and a smaller time step used instead. You may wish to set IRES=3 when a physically meaningless input or output value has been generated. If you consecutively set IRES=3, then D03PCF/D03PCA returns to the calling subroutine with the error indicator set to IFAIL=4.
Note: the following are additional arguments for specific use with D03PCA. Users of D03PCF therefore need not read the remainder of this description.
10:   IUSER* – INTEGER arrayUser Workspace
11:   RUSER* – REAL (KIND=nag_wp) arrayUser Workspace
PDEDEF is called with the arguments IUSER and RUSER as supplied to D03PCF/D03PCA. You are free to use the arrays IUSER and RUSER to supply information to PDEDEF as an alternative to using COMMON global variables.
PDEDEF must either be a module subprogram USEd by, or declared as EXTERNAL in, the (sub)program from which D03PCF/D03PCA is called. Arguments denoted as Input must not be changed by this procedure.
6:   BNDARY – SUBROUTINE, supplied by the user.External Procedure
BNDARY must compute the functions βi and γi which define the boundary conditions as in equation (3).
The specification of BNDARY for D03PCF is:
SUBROUTINE BNDARY ( NPDE, T, U, UX, IBND, BETA, GAMMA, IRES)
INTEGER | NPDE, IBND, IRES
REAL (KIND=nag_wp) | T, U(NPDE), UX(NPDE), BETA(NPDE), GAMMA(NPDE)
The specification of BNDARY for D03PCA is:
SUBROUTINE BNDARY ( NPDE, T, U, UX, IBND, BETA, GAMMA, IRES, IUSER, RUSER)
INTEGER | NPDE, IBND, IRES, IUSER(*)
REAL (KIND=nag_wp) | T, U(NPDE), UX(NPDE), BETA(NPDE), GAMMA(NPDE), RUSER(*)
1:   NPDE – INTEGERInput
On entry: the number of PDEs in the system.
2:   T – REAL (KIND=nag_wp)Input
On entry: the current value of the independent variable t.
3:   U NPDE – REAL (KIND=nag_wp) arrayInput
On entry: U i contains the value of the component Ui x,t at the boundary specified by IBND, for i=1,2,…,NPDE.
4:   UX NPDE – REAL (KIND=nag_wp) arrayInput
On entry: UX i contains the value of the component ∂Ui x,t ∂x at the boundary specified by IBND, for i=1,2,…,NPDE.
5:   IBND – INTEGERInput
On entry: determines the position of the boundary conditions.
IBND=0
BNDARY must set up the coefficients of the left-hand boundary, x=a.
IBND≠0
Indicates that BNDARY must set up the coefficients of the right-hand boundary, x=b.
6:   BETA NPDE – REAL (KIND=nag_wp) arrayOutput
On exit: BETA i must be set to the value of βi x,t at the boundary specified by IBND, for i=1,2,…,NPDE.
7:   GAMMA NPDE – REAL (KIND=nag_wp) arrayOutput
On exit: GAMMA i must be set to the value of γi x,t,U,Ux at the boundary specified by IBND, for i=1,2,…,NPDE.
8:   IRES – INTEGERInput/Output
On entry: set to -1​ or ​1.
On exit: should usually remain unchanged. However, you may set IRES to force the integration routine to take certain actions as described below:
IRES=2
Indicates to the integrator that control should be passed back immediately to the calling (sub)routine with the error indicator set to IFAIL=6.
IRES=3
Indicates to the integrator that the current time step should be abandoned and a smaller time step used instead. You may wish to set IRES=3 when a physically meaningless input or output value has been generated. If you consecutively set IRES=3, then D03PCF/D03PCA returns to the calling subroutine with the error indicator set to IFAIL=4.
Note: the following are additional arguments for specific use with D03PCA. Users of D03PCF therefore need not read the remainder of this description.
9:   IUSER* – INTEGER arrayUser Workspace
10:   RUSER* – REAL (KIND=nag_wp) arrayUser Workspace
BNDARY is called with the arguments IUSER and RUSER as supplied to D03PCF/D03PCA. You are free to use the arrays IUSER and RUSER to supply information to BNDARY as an alternative to using COMMON global variables.
BNDARY must either be a module subprogram USEd by, or declared as EXTERNAL in, the (sub)program from which D03PCF/D03PCA is called. Arguments denoted as Input must not be changed by this procedure.
7:   U NPDENPTS – REAL (KIND=nag_wp) arrayInput/Output
On entry: the initial values of U x,t at t=TS and the mesh points X j, for j=1,2,…,NPTS.
On exit: U ij will contain the computed solution at t=TS.
8:   NPTS – INTEGERInput
On entry: the number of mesh points in the interval a,b.
Constraint: NPTS≥3.
9:   X NPTS – REAL (KIND=nag_wp) arrayInput
On entry: the mesh points in the spatial direction. X 1 must specify the left-hand boundary, a, and X NPTS must specify the right-hand boundary, b.
Constraint: X 1<X 2<⋯<X NPTS.
10:   ACC – REAL (KIND=nag_wp)Input
On entry: a positive quantity for controlling the local error estimate in the time integration. If E i,j is the estimated error for Ui at the jth mesh point, the error test is:
E i,j=ACC×1.0+U ij.
Constraint: ACC>0.0.
11:   RSAVE LRSAVE – REAL (KIND=nag_wp) arrayCommunication Array
If IND=0, RSAVE need not be set on entry.
If IND=1, RSAVE must be unchanged from the previous call to the routine because it contains required information about the iteration.
12:   LRSAVE – INTEGERInput
On entry: the dimension of the array RSAVE as declared in the (sub)program from which D03PCF/D03PCA is called.
Constraint: LRSAVE≥6×NPDE+10×NPDE×NPTS+3×NPDE+21×NPDE+7×NPTS+54.
13:   ISAVE LISAVE – INTEGER arrayCommunication Array
If IND=0, ISAVE need not be set on entry.
If IND=1, ISAVE must be unchanged from the previous call to the routine because it contains required information about the iteration. In particular:
ISAVE 1
Contains the number of steps taken in time.
ISAVE 2
Contains the number of residual evaluations of the resulting ODE system used. One such evaluation involves computing the PDE functions at all the mesh points, as well as one evaluation of the functions in the boundary conditions.
ISAVE 3
Contains the number of Jacobian evaluations performed by the time integrator.
ISAVE 4
Contains the order of the last backward differentiation formula method used.
ISAVE 5
Contains the number of Newton iterations performed by the time integrator. Each iteration involves an ODE residual evaluation followed by a back-substitution using the LU decomposition of the Jacobian matrix.
14:   LISAVE – INTEGERInput
On entry: the dimension of the array ISAVE as declared in the (sub)program from which D03PCF/D03PCA is called.
Constraint: LISAVE≥NPDE×NPTS+24.
15:   ITASK – INTEGERInput
On entry: specifies the task to be performed by the ODE integrator.
ITASK=1
Normal computation of output values U at t=TOUT.
ITASK=2
One step and return.
ITASK=3
Stop at first internal integration point at or beyond t=TOUT.
Constraint: ITASK=1, 2 or 3.
16:   ITRACE – INTEGERInput
On entry: the level of trace information required from D03PCF/D03PCA and the underlying ODE solver. ITRACE may take the value -1, 0, 1, 2 or 3.
ITRACE=-1
No output is generated.
ITRACE=0
Only warning messages from the PDE solver are printed on the current error message unit (see X04AAF).
ITRACE>0
Output from the underlying ODE solver is printed on the current advisory message unit (see X04ABF). This output contains details of Jacobian entries, the nonlinear iteration and the time integration during the computation of the ODE system.
If ITRACE<-1, then -1 is assumed and similarly if ITRACE>3, then 3 is assumed.
The advisory messages are given in greater detail as ITRACE increases. You are advised to set ITRACE=0, unless you are experienced with Sub-chapter D02M–N.
17:   IND – INTEGERInput/Output
On entry: indicates whether this is a continuation call or a new integration.
IND=0
Starts or restarts the integration in time.
IND=1
Continues the integration after an earlier exit from the routine. In this case, only the arguments TOUT and IFAIL should be reset between calls to D03PCF/D03PCA.
Constraint: IND=0 or 1.
On exit: IND=1.
18:   IFAIL – INTEGERInput/Output
Note: for D03PCA, IFAIL does not occur in this position in the argument list. See the additional arguments described below.
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).
Note: the following are additional arguments for specific use with D03PCA. Users of D03PCF therefore need not read the remainder of this description.
18:   IUSER* – INTEGER arrayUser Workspace
19:   RUSER* – REAL (KIND=nag_wp) arrayUser Workspace
IUSER and RUSER are not used by D03PCF/D03PCA, but are passed directly to PDEDEF and BNDARY and may be used to pass information to these routines as an alternative to using COMMON global variables.
20:   CWSAV 10 – CHARACTER(80) arrayCommunication Array
If IND=0, CWSAV need not be set on entry.
If IND=1, CWSAV must be unchanged from the previous call to the routine.
21:   LWSAV 100 – LOGICAL arrayCommunication Array
If IND=0, LWSAV need not be set on entry.
If IND=1, LWSAV must be unchanged from the previous call to the routine.
22:   IWSAV 505 – INTEGER arrayCommunication Array
If IND=0, IWSAV need not be set on entry.
If IND=1, IWSAV must be unchanged from the previous call to the routine.
23:   RWSAV 1100 – REAL (KIND=nag_wp) arrayCommunication Array
If IND=0, RWSAV need not be set on entry.
If IND=1, RWSAV must be unchanged from the previous call to the routine.
24:   IFAIL – INTEGERInput/Output
Note: see the argument description for IFAIL above.

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, | TOUT≤TS,
or | TOUT-TS is too small,
or | ITASK≠1, 2 or 3,
or | M≠0, 1 or 2,
or | M>0 and X 1<0.0,
or | the mesh points ​X i are not ordered,
or | NPTS<3,
or | NPDE<1,
or | ACC≤0.0,
or | IND≠0 or 1,
or | LRSAVE is too small,
or | LISAVE is too small.
IFAIL=2
The underlying ODE solver cannot make any further progress across the integration range from the current point t=TS with the supplied value of ACC. The components of U contain the computed values at the current point t=TS.
IFAIL=3
In the underlying ODE solver, there were repeated errors or corrector convergence test failures on an attempted step, before completing the requested task. The problem may have a singularity or ACC is too small for the integration to continue. Integration was successful as far as t=TS.
IFAIL=4
In setting up the ODE system, the internal initialization routine was unable to initialize the derivative of the ODE system. This could be due to the fact that IRES was repeatedly set to 3 in at least PDEDEF or BNDARY, when the residual in the underlying ODE solver was being evaluated.
IFAIL=5
In solving the ODE system, a singular Jacobian has been encountered. You should check your problem formulation.
IFAIL=6
When evaluating the residual in solving the ODE system, IRES was set to 2 in at least PDEDEF or BNDARY. Integration was successful as far as t=TS.
IFAIL=7
The value of ACC is so small that the routine is unable to start the integration in time.
IFAIL=8
In one of PDEDEF or BNDARY, IRES was set to an invalid value.
IFAIL=9 (D02NNF)
A serious error has occurred in an internal call to the specified routine. Check the problem specification and all arguments and array dimensions. Setting ITRACE=1 may provide more information. If the problem persists, contact NAG.
IFAIL=10
The required task has been completed, but it is estimated that a small change in ACC is unlikely to produce any change in the computed solution. (Only applies when you are not operating in one step mode, that is when ITASK≠2.)
IFAIL=11
An error occurred during Jacobian formulation of the ODE system (a more detailed error description may be directed to the current error message unit).
IFAIL=12
Not applicable.
IFAIL=13
Not applicable.
IFAIL=14
The flux function Ri was detected as depending on time derivatives, which is not permissible.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

D03PCF/D03PCA controls the accuracy of the integration in the time direction but not the accuracy of the approximation in space. The spatial accuracy depends on both the number of mesh points and on their distribution in space. In the time integration only the local error over a single step is controlled and so the accuracy over a number of steps cannot be guaranteed. You should therefore test the effect of varying the accuracy argument, ACC.

8 Parallelism and Performance

D03PCF/D03PCA is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
D03PCF/D03PCA makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

D03PCF/D03PCA is designed to solve parabolic systems (possibly including some elliptic equations) with second-order derivatives in space. The argument specification allows you to include equations with only first-order derivatives in the space direction but there is no guarantee that the method of integration will be satisfactory for such systems. The position and nature of the boundary conditions in particular are critical in defining a stable problem. It may be advisable in such cases to reduce the whole system to first-order and to use the Keller box scheme routine D03PEF.
The time taken depends on the complexity of the parabolic system and on the accuracy requested.

10 Example

We use the example given in Dew and Walsh (1981) which consists of an elliptic-parabolic pair of PDEs. The problem was originally derived from a single third-order in space PDE. The elliptic equation is
1 r ∂∂r r 2 ∂U 1 ∂r =4 α U 2+r ∂U 2 ∂r
and the parabolic equation is
1-r 2 ∂U 2 ∂t =1 r ∂∂r r ∂U 2 ∂r -U 2U 1
where r,t∈0,1×0,1. The boundary conditions are given by
U 1= ∂U 2 ∂r =0  at ​r=0,
and
∂∂r r U 1= 0   and   U 2= 0   at ​ r=1.
The first of these boundary conditions implies that the flux term in the second PDE, ∂U 2 ∂r - U 2 U 1 , is zero at r=0.
The initial conditions at t=0 are given by
U 1=2 αr  and  U 2=1.0,   ​r∈0,1.
The value α=1 was used in the problem definition. A mesh of 20 points was used with a circular mesh spacing to cluster the points towards the right-hand side of the spatial interval, r=1.

10.1 Program Text

Note: the following programs illustrate the use of D03PCF and D03PCA.

Program Text (d03pcfe.f90)

Program Text (d03pcae.f90)

10.2 Program Data

Program Data (d03pcfe.d)

Program Data (d03pcae.d)

10.3 Program Results

Program Results (d03pcfe.r)

Program Results (d03pcae.r)

GnuplotProduced by GNUPLOT 5.0 patchlevel 0 Example Program Solution, U(1,x,t), of Elliptic-parabolic Pair using Method of Lines and BDF Method U(1,x,t) gnuplot_plot_1 gnuplot_plot_2 0.000010 0.000100 0.001000 0.010000 0.100000 1.000000 Time (logscale) 0 0.2 0.4 0.6 0.8 1 x 0 0.2 0.4 0.6 0.8 1 1.2 1.4 1.6 1.8 2
GnuplotProduced by GNUPLOT 5.0 patchlevel 0 Solution, U(2,x,t), of Elliptic-parabolic Pair using Finite-differences and BDF U(2,x,t) gnuplot_plot_1 gnuplot_plot_2 0.000010 0.000100 0.001000 0.010000 0.100000 1.000000 Time (logscale) 0 0.2 0.4 0.6 0.8 1 x 0 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9 1
D03 Chapter Contents
D03 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


D03PDF/D03PDA : NAG Library, Mark 26

D03 Chapter Contents
D03 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

D03PDF/D03PDA

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
▸▿ 2 Specification
2.1 Specification for D03PDF
2.2 Specification for D03PDA
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

D03PDF/D03PDA integrates a system of linear or nonlinear parabolic partial differential equations (PDEs) in one space variable. The spatial discretization is performed using a Chebyshev C 0 collocation method, and the method of lines is employed to reduce the PDEs to a system of ordinary differential equations (ODEs). The resulting system is solved using a backward differentiation formula method.
D03PDA is a version of D03PDF that has additional arguments in order to make it safe for use in multithreaded applications (see Section 5).

2 Specification

2.1 Specification for D03PDF

SUBROUTINE D03PDF ( NPDE, M, TS, TOUT, PDEDEF, BNDARY, U, NBKPTS, XBKPTS, NPOLY, NPTS, X, UINIT, ACC, RSAVE, LRSAVE, ISAVE, LISAVE, ITASK, ITRACE, IND, IFAIL)
INTEGER | NPDE, M, NBKPTS, NPOLY, NPTS, LRSAVE, ISAVE(LISAVE), LISAVE, ITASK, ITRACE, IND, IFAIL
REAL (KIND=nag_wp) | TS, TOUT, U(NPDE,NPTS), XBKPTS(NBKPTS), X(NPTS), ACC, RSAVE(LRSAVE)
EXTERNAL | PDEDEF, BNDARY, UINIT

2.2 Specification for D03PDA

SUBROUTINE D03PDA ( NPDE, M, TS, TOUT, PDEDEF, BNDARY, U, NBKPTS, XBKPTS, NPOLY, NPTS, X, UINIT, ACC, RSAVE, LRSAVE, ISAVE, LISAVE, ITASK, ITRACE, IND, IUSER, RUSER, CWSAV, LWSAV, IWSAV, RWSAV, IFAIL)
INTEGER | NPDE, M, NBKPTS, NPOLY, NPTS, LRSAVE, ISAVE(LISAVE), LISAVE, ITASK, ITRACE, IND, IUSER(*), IWSAV(505), IFAIL
REAL (KIND=nag_wp) | TS, TOUT, U(NPDE,NPTS), XBKPTS(NBKPTS), X(NPTS), ACC, RSAVE(LRSAVE), RUSER(*), RWSAV(1100)
LOGICAL | LWSAV(100)
CHARACTER(80) | CWSAV(10)
EXTERNAL | PDEDEF, BNDARY, UINIT

3 Description

D03PDF/D03PDA integrates the system of parabolic equations:
∑j=1 NPDE P i,j ∂Uj ∂t +Qi=x-m ∂∂x xm Ri,  i=1,2,…,NPDE,  a≤x≤b,t≥t 0, (1)
where P i,j, Qi and Ri depend on x, t, U, Ux and the vector U is the set of solution values
U x,t = U 1 x,t ,…, U NPDE x,t T , (2)
and the vector Ux is its partial derivative with respect to x. Note that P i,j, Qi and Ri must not depend on ∂U ∂t .
The integration in time is from t 0 to tout, over the space interval a≤x≤b, where a=x 1 and b=xNBKPTS are the leftmost and rightmost of a user-defined set of break-points x 1,x 2,…,xNBKPTS. The coordinate system in space is defined by the value of m; m=0 for Cartesian coordinates, m=1 for cylindrical polar coordinates and m=2 for spherical polar coordinates.
The system is defined by the functions P i,j, Qi and Ri which must be specified in PDEDEF.
The initial values of the functions U x,t must be given at t=t 0, and must be specified in UINIT.
The functions Ri, for i=1,2,…,NPDE, which may be thought of as fluxes, are also used in the definition of the boundary conditions for each equation. The boundary conditions must have the form
βi x,t Ri x,t,U,Ux=γi x,t,U,Ux,  i=1,2,…,NPDE, (3)
where x=a or x=b.
The boundary conditions must be specified in BNDARY. Thus, the problem is subject to the following restrictions:
(i) | t 0<tout, so that integration is in the forward direction;
(ii) | P i,j, Qi and the flux Ri must not depend on any time derivatives;
(iii) | the evaluation of the functions P i,j, Qi and Ri is done at both the break-points and internally selected points for each element in turn, that is P i,j, Qi and Ri are evaluated twice at each break-point. Any discontinuities in these functions must therefore be at one or more of the break-points x 1,x 2,…,xNBKPTS;
(iv) | at least one of the functions P i,j must be nonzero so that there is a time derivative present in the problem;
(v) | if m>0 and x 1=0.0, which is the left boundary point, then it must be ensured that the PDE solution is bounded at this point. This can be done by either specifying the solution at x=0.0 or by specifying a zero flux there, that is βi=1.0 and γi=0.0. See also Section 9.
The parabolic equations are approximated by a system of ODEs in time for the values of Ui at the mesh points. This ODE system is obtained by approximating the PDE solution between each pair of break-points by a Chebyshev polynomial of degree NPOLY. The interval between each pair of break-points is treated by D03PDF/D03PDA as an element, and on this element, a polynomial and its space and time derivatives are made to satisfy the system of PDEs at NPOLY-1 spatial points, which are chosen internally by the code and the break-points. In the case of just one element, the break-points are the boundaries. The user-defined break-points and the internally selected points together define the mesh. The smallest value that NPOLY can take is one, in which case, the solution is approximated by piecewise linear polynomials between consecutive break-points and the method is similar to an ordinary finite element method.
In total there are NBKPTS-1×NPOLY+1 mesh points in the spatial direction, and NPDE×NBKPTS-1×NPOLY+1 ODEs in the time direction; one ODE at each break-point for each PDE component and (NPOLY-1) ODEs for each PDE component between each pair of break-points. The system is then integrated forwards in time using a backward differentiation formula method.

4 References

Berzins M (1990) Developments in the NAG Library software for parabolic equations Scientific Software Systems (eds J C Mason and M G Cox) 59–72 Chapman and Hall
Berzins M and Dew P M (1991) Algorithm 690: Chebyshev polynomial software for elliptic-parabolic systems of PDEs ACM Trans. Math. Software 17 178–206
Zaturska N B, Drazin P G and Banks W H H (1988) On the flow of a viscous fluid driven along a channel by a suction at porous walls Fluid Dynamics Research 4

5 Arguments

1:   NPDE – INTEGERInput
On entry: the number of PDEs in the system to be solved.
Constraint: NPDE≥1.
2:   M – INTEGERInput
On entry: the coordinate system used:
M=0
Indicates Cartesian coordinates.
M=1
Indicates cylindrical polar coordinates.
M=2
Indicates spherical polar coordinates.
Constraint: M=0, 1 or 2.
3:   TS – REAL (KIND=nag_wp)Input/Output
On entry: the initial value of the independent variable t.
On exit: the value of t corresponding to the solution values in U. Normally TS=TOUT.
Constraint: TS<TOUT.
4:   TOUT – REAL (KIND=nag_wp)Input
On entry: the final value of t to which the integration is to be carried out.
5:   PDEDEF – SUBROUTINE, supplied by the user.External Procedure
PDEDEF must compute the values of the functions P i,j, Qi and Ri which define the system of PDEs. The functions may depend on x, t, U and Ux and must be evaluated at a set of points.
The specification of PDEDEF for D03PDF is:
SUBROUTINE PDEDEF ( NPDE, T, X, NPTL, U, UX, P, Q, R, IRES)
INTEGER | NPDE, NPTL, IRES
REAL (KIND=nag_wp) | T, X(NPTL), U(NPDE,NPTL), UX(NPDE,NPTL), P(NPDE,NPDE,NPTL), Q(NPDE,NPTL), R(NPDE,NPTL)
The specification of PDEDEF for D03PDA is:
SUBROUTINE PDEDEF ( NPDE, T, X, NPTL, U, UX, P, Q, R, IRES, IUSER, RUSER)
INTEGER | NPDE, NPTL, IRES, IUSER(*)
REAL (KIND=nag_wp) | T, X(NPTL), U(NPDE,NPTL), UX(NPDE,NPTL), P(NPDE,NPDE,NPTL), Q(NPDE,NPTL), R(NPDE,NPTL), RUSER(*)
1:   NPDE – INTEGERInput
On entry: the number of PDEs in the system.
2:   T – REAL (KIND=nag_wp)Input
On entry: the current value of the independent variable t.
3:   X NPTL – REAL (KIND=nag_wp) arrayInput
On entry: contains a set of mesh points at which P i,j, Qi and Ri are to be evaluated. X 1 and X NPTL contain successive user-supplied break-points and the elements of the array will satisfy X 1<X 2<⋯<X NPTL.
4:   NPTL – INTEGERInput
On entry: the number of points at which evaluations are required (the value of NPOLY+1).
5:   U NPDENPTL – REAL (KIND=nag_wp) arrayInput
On entry: U ij contains the value of the component Ui x,t where x=X j, for i=1,2,…,NPDE and j=1,2,…,NPTL.
6:   UX NPDENPTL – REAL (KIND=nag_wp) arrayInput
On entry: UX ij contains the value of the component ∂Ui x,t ∂x where x=X j, for i=1,2,…,NPDE and j=1,2,…,NPTL.
7:   P NPDENPDENPTL – REAL (KIND=nag_wp) arrayOutput
On exit: P ijk must be set to the value of P i,j x,t,U,Ux where x=X k, for i=1,2,…,NPDE, j=1,2,…,NPDE and k=1,2,…,NPTL.
8:   Q NPDENPTL – REAL (KIND=nag_wp) arrayOutput
On exit: Q ij must be set to the value of Qi x,t,U,Ux where x=X j, for i=1,2,…,NPDE and j=1,2,…,NPTL.
9:   R NPDENPTL – REAL (KIND=nag_wp) arrayOutput
On exit: R ij must be set to the value of Ri x,t,U,Ux where x=X j, for i=1,2,…,NPDE and j=1,2,…,NPTL.
10:   IRES – INTEGERInput/Output
On entry: set to -1​ or ​1.
On exit: should usually remain unchanged. However, you may set IRES to force the integration routine to take certain actions as described below:
IRES=2
Indicates to the integrator that control should be passed back immediately to the calling (sub)routine with the error indicator set to IFAIL=6.
IRES=3
Indicates to the integrator that the current time step should be abandoned and a smaller time step used instead. You may wish to set IRES=3 when a physically meaningless input or output value has been generated. If you consecutively set IRES=3, then D03PDF/D03PDA returns to the calling subroutine with the error indicator set to IFAIL=4.
Note: the following are additional arguments for specific use with D03PDA. Users of D03PDF therefore need not read the remainder of this description.
11:   IUSER* – INTEGER arrayUser Workspace
12:   RUSER* – REAL (KIND=nag_wp) arrayUser Workspace
PDEDEF is called with the arguments IUSER and RUSER as supplied to D03PDF/D03PDA. You are free to use the arrays IUSER and RUSER to supply information to PDEDEF as an alternative to using COMMON global variables.
PDEDEF must either be a module subprogram USEd by, or declared as EXTERNAL in, the (sub)program from which D03PDF/D03PDA is called. Arguments denoted as Input must not be changed by this procedure.
6:   BNDARY – SUBROUTINE, supplied by the user.External Procedure
BNDARY must compute the functions βi and γi which define the boundary conditions as in equation (3).
The specification of BNDARY for D03PDF is:
SUBROUTINE BNDARY ( NPDE, T, U, UX, IBND, BETA, GAMMA, IRES)
INTEGER | NPDE, IBND, IRES
REAL (KIND=nag_wp) | T, U(NPDE), UX(NPDE), BETA(NPDE), GAMMA(NPDE)
The specification of BNDARY for D03PDA is:
SUBROUTINE BNDARY ( NPDE, T, U, UX, IBND, BETA, GAMMA, IRES, IUSER, RUSER)
INTEGER | NPDE, IBND, IRES, IUSER(*)
REAL (KIND=nag_wp) | T, U(NPDE), UX(NPDE), BETA(NPDE), GAMMA(NPDE), RUSER(*)
1:   NPDE – INTEGERInput
On entry: the number of PDEs in the system.
2:   T – REAL (KIND=nag_wp)Input
On entry: the current value of the independent variable t.
3:   U NPDE – REAL (KIND=nag_wp) arrayInput
On entry: U i contains the value of the component Ui x,t at the boundary specified by IBND, for i=1,2,…,NPDE.
4:   UX NPDE – REAL (KIND=nag_wp) arrayInput
On entry: UX i contains the value of the component ∂Ui x,t ∂x at the boundary specified by IBND, for i=1,2,…,NPDE.
5:   IBND – INTEGERInput
On entry: specifies which boundary conditions are to be evaluated.
IBND=0
BNDARY must set up the coefficients of the left-hand boundary, x=a.
IBND≠0
BNDARY must set up the coefficients of the right-hand boundary, x=b.
6:   BETA NPDE – REAL (KIND=nag_wp) arrayOutput
On exit: BETA i must be set to the value of βi x,t at the boundary specified by IBND, for i=1,2,…,NPDE.
7:   GAMMA NPDE – REAL (KIND=nag_wp) arrayOutput
On exit: GAMMA i must be set to the value of γi x,t,U,Ux at the boundary specified by IBND, for i=1,2,…,NPDE.
8:   IRES – INTEGERInput/Output
On entry: set to -1​ or ​1.
On exit: should usually remain unchanged. However, you may set IRES to force the integration routine to take certain actions as described below:
IRES=2
Indicates to the integrator that control should be passed back immediately to the calling (sub)routine with the error indicator set to IFAIL=6.
IRES=3
Indicates to the integrator that the current time step should be abandoned and a smaller time step used instead. You may wish to set IRES=3 when a physically meaningless input or output value has been generated. If you consecutively set IRES=3, then D03PDF/D03PDA returns to the calling subroutine with the error indicator set to IFAIL=4.
Note: the following are additional arguments for specific use with D03PDA. Users of D03PDF therefore need not read the remainder of this description.
9:   IUSER* – INTEGER arrayUser Workspace
10:   RUSER* – REAL (KIND=nag_wp) arrayUser Workspace
BNDARY is called with the arguments IUSER and RUSER as supplied to D03PDF/D03PDA. You are free to use the arrays IUSER and RUSER to supply information to BNDARY as an alternative to using COMMON global variables.
BNDARY must either be a module subprogram USEd by, or declared as EXTERNAL in, the (sub)program from which D03PDF/D03PDA is called. Arguments denoted as Input must not be changed by this procedure.
7:   U NPDENPTS – REAL (KIND=nag_wp) arrayInput/Output
On entry: if IND=1 the value of U must be unchanged from the previous call.
On exit: U ij will contain the computed solution at t=TS.
8:   NBKPTS – INTEGERInput
On entry: the number of break-points in the interval a,b.
Constraint: NBKPTS≥2.
9:   XBKPTS NBKPTS – REAL (KIND=nag_wp) arrayInput
On entry: the values of the break-points in the space direction. XBKPTS 1 must specify the left-hand boundary, a, and XBKPTS NBKPTS must specify the right-hand boundary, b.
Constraint: XBKPTS 1<XBKPTS 2<⋯<XBKPTS NBKPTS.
10:   NPOLY – INTEGERInput
On entry: the degree of the Chebyshev polynomial to be used in approximating the PDE solution between each pair of break-points.
Constraint: 1≤NPOLY≤49.
11:   NPTS – INTEGERInput
On entry: the number of mesh points in the interval a,b.
Constraint: NPTS=NBKPTS-1×NPOLY+1.
12:   X NPTS – REAL (KIND=nag_wp) arrayOutput
On exit: the mesh points chosen by D03PDF/D03PDA in the spatial direction. The values of X will satisfy X 1<X 2<⋯<X NPTS.
13:   UINIT – SUBROUTINE, supplied by the user.External Procedure
UINIT must compute the initial values of the PDE components Ui xj,t 0, for i=1,2,…,NPDE and j=1,2,…,NPTS.
The specification of UINIT for D03PDF is:
SUBROUTINE UINIT ( NPDE, NPTS, X, U)
INTEGER | NPDE, NPTS
REAL (KIND=nag_wp) | X(NPTS), U(NPDE,NPTS)
The specification of UINIT for D03PDA is:
SUBROUTINE UINIT ( NPDE, NPTS, X, U, IUSER, RUSER)
INTEGER | NPDE, NPTS, IUSER(*)
REAL (KIND=nag_wp) | X(NPTS), U(NPDE,NPTS), RUSER(*)
1:   NPDE – INTEGERInput
On entry: the number of PDEs in the system.
2:   NPTS – INTEGERInput
On entry: the number of mesh points in the interval a,b.
3:   X NPTS – REAL (KIND=nag_wp) arrayInput
On entry: X j, contains the values of the jth mesh point, for j=1,2,…,NPTS.
4:   U NPDENPTS – REAL (KIND=nag_wp) arrayOutput
On exit: U ij must be set to the initial value Ui xj,t 0, for i=1,2,…,NPDE and j=1,2,…,NPTS.
Note: the following are additional arguments for specific use with D03PDA. Users of D03PDF therefore need not read the remainder of this description.
5:   IUSER* – INTEGER arrayUser Workspace
6:   RUSER* – REAL (KIND=nag_wp) arrayUser Workspace
UINIT is called with the arguments IUSER and RUSER as supplied to D03PDF/D03PDA. You are free to use the arrays IUSER and RUSER to supply information to UINIT as an alternative to using COMMON global variables.
UINIT must either be a module subprogram USEd by, or declared as EXTERNAL in, the (sub)program from which D03PDF/D03PDA is called. Arguments denoted as Input must not be changed by this procedure.
14:   ACC – REAL (KIND=nag_wp)Input
On entry: a positive quantity for controlling the local error estimate in the time integration. If E i,j is the estimated error for Ui at the jth mesh point, the error test is:
E i,j=ACC×1.0+U ij.
Constraint: ACC>0.0.
15:   RSAVE LRSAVE – REAL (KIND=nag_wp) arrayCommunication Array
If IND=0, RSAVE need not be set on entry.
If IND=1, RSAVE must be unchanged from the previous call to the routine because it contains required information about the iteration.
16:   LRSAVE – INTEGERInput
On entry: the dimension of the array RSAVE as declared in the (sub)program from which D03PDF/D03PDA is called.
Constraint: LRSAVE≥11×NPDE×NPTS+50+nwkres+lenode.
17:   ISAVE LISAVE – INTEGER arrayCommunication Array
If IND=0, ISAVE need not be set on entry.
If IND=1, ISAVE must be unchanged from the previous call to the routine because it contains required information about the iteration. In particular:
ISAVE 1
Contains the number of steps taken in time.
ISAVE 2
Contains the number of residual evaluations of the resulting ODE system used. One such evaluation involves computing the PDE functions at all the mesh points, as well as one evaluation of the functions in the boundary conditions.
ISAVE 3
Contains the number of Jacobian evaluations performed by the time integrator.
ISAVE 4
Contains the order of the last backward differentiation formula method used.
ISAVE 5
Contains the number of Newton iterations performed by the time integrator. Each iteration involves an ODE residual evaluation followed by a back-substitution using the LU decomposition of the Jacobian matrix.
18:   LISAVE – INTEGERInput
On entry: the dimension of the array ISAVE as declared in the (sub)program from which D03PDF/D03PDA is called.
Constraint: LISAVE≥NPDE×NPTS+24.
19:   ITASK – INTEGERInput
On entry: specifies the task to be performed by the ODE integrator.
ITASK=1
Normal computation of output values U at t=TOUT.
ITASK=2
One step and return.
ITASK=3
Stop at first internal integration point at or beyond t=TOUT.
Constraint: ITASK=1, 2 or 3.
20:   ITRACE – INTEGERInput
On entry: the level of trace information required from D03PDF/D03PDA and the underlying ODE solver. ITRACE may take the value -1, 0, 1, 2 or 3.
ITRACE=-1
No output is generated.
ITRACE=0
Only warning messages from the PDE solver are printed on the current error message unit (see X04AAF).
ITRACE>0
Output from the underlying ODE solver is printed on the current advisory message unit (see X04ABF). This output contains details of Jacobian entries, the nonlinear iteration and the time integration during the computation of the ODE system.
If ITRACE<-1, then -1 is assumed and similarly if ITRACE>3, then 3 is assumed.
The advisory messages are given in greater detail as ITRACE increases. You are advised to set ITRACE=0, unless you are experienced with Sub-chapter D02M–N.
21:   IND – INTEGERInput/Output
On entry: indicates whether this is a continuation call or a new integration.
IND=0
Starts or restarts the integration in time.
IND=1
Continues the integration after an earlier exit from the routine. In this case, only the arguments TOUT and IFAIL should be reset between calls to D03PDF/D03PDA.
Constraint: IND=0 or 1.
On exit: IND=1.
22:   IFAIL – INTEGERInput/Output
Note: for D03PDA, IFAIL does not occur in this position in the argument list. See the additional arguments described below.
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).
Note: the following are additional arguments for specific use with D03PDA. Users of D03PDF therefore need not read the remainder of this description.
22:   IUSER* – INTEGER arrayUser Workspace
IUSER is not used by D03PDF/D03PDA, but is passed directly to PDEDEF, BNDARY and UINIT and may be used to pass information to these routines as an alternative to using COMMON global variables.
23:   RUSER* – REAL (KIND=nag_wp) arrayUser Workspace
24:   CWSAV 10 – CHARACTER(80) arrayCommunication Array
25:   LWSAV 100 – LOGICAL arrayCommunication Array
26:   IWSAV 505 – INTEGER arrayCommunication Array
27:   RWSAV 1100 – REAL (KIND=nag_wp) arrayCommunication Array
28:   IFAIL – INTEGERInput/Output
Note: see the argument description for IFAIL above.

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, | TOUT≤TS,
or | TOUT-TS is too small,
or | ITASK≠1, 2 or 3,
or | M≠0, 1 or 2,
or | M>0 and XBKPTS 1<0.0,
or | NPDE<1,
or | NBKPTS<2,
or | NPOLY<1 or NPOLY>49,
or | NPTS≠NBKPTS-1×NPOLY+1,
or | ACC≤0.0,
or | IND≠0 or 1,
or | break-points XBKPTS i are not ordered,
or | LRSAVE is too small,
or | LISAVE is too small.
IFAIL=2
The underlying ODE solver cannot make any further progress across the integration range from the current point t=TS with the supplied value of ACC. The components of U contain the computed values at the current point t=TS.
IFAIL=3
In the underlying ODE solver, there were repeated errors or corrector convergence test failures on an attempted step, before completing the requested task. The problem may have a singularity or ACC is too small for the integration to continue. Integration was successful as far as t=TS.
IFAIL=4
In setting up the ODE system, the internal initialization routine was unable to initialize the derivative of the ODE system. This could be due to the fact that IRES was repeatedly set to 3 in at least PDEDEF or BNDARY, when the residual in the underlying ODE solver was being evaluated.
IFAIL=5
In solving the ODE system, a singular Jacobian has been encountered. You should check your problem formulation.
IFAIL=6
When evaluating the residual in solving the ODE system, IRES was set to 2 in at least PDEDEF or BNDARY. Integration was successful as far as t=TS.
IFAIL=7
The value of ACC is so small that the routine is unable to start the integration in time.
IFAIL=8
In one of PDEDEF or BNDARY, IRES was set to an invalid value.
IFAIL=9 (D02NNF)
A serious error has occurred in an internal call to the specified routine. Check the problem specification and all arguments and array dimensions. Setting ITRACE=1 may provide more information. If the problem persists, contact NAG.
IFAIL=10
The required task has been completed, but it is estimated that a small change in ACC is unlikely to produce any change in the computed solution. (Only applies when you are not operating in one step mode, that is when ITASK≠2.)
IFAIL=11
An error occurred during Jacobian formulation of the ODE system (a more detailed error description may be directed to the current error message unit).
IFAIL=12
Not applicable.
IFAIL=13
Not applicable.
IFAIL=14
The flux function Ri was detected as depending on time derivatives, which is not permissible.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

D03PDF/D03PDA controls the accuracy of the integration in the time direction but not the accuracy of the approximation in space. The spatial accuracy depends on the degree of the polynomial approximation NPOLY, and on both the number of break-points and on their distribution in space. In the time integration only the local error over a single step is controlled and so the accuracy over a number of steps cannot be guaranteed. You should therefore test the effect of varying the accuracy argument, ACC.

8 Parallelism and Performance

D03PDF/D03PDA is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
D03PDF/D03PDA makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

D03PDF/D03PDA is designed to solve parabolic systems (possibly including elliptic equations) with second-order derivatives in space. The argument specification allows you to include equations with only first-order derivatives in the space direction but there is no guarantee that the method of integration will be satisfactory for such systems. The position and nature of the boundary conditions in particular are critical in defining a stable problem.
The time taken depends on the complexity of the parabolic system and on the accuracy requested.

10 Example

The problem consists of a fourth-order PDE which can be written as a pair of second-order elliptic-parabolic PDEs for U 1 x,t and U 2 x,t,
0= ∂2 U 1 ∂x 2 -U 2 (4)
∂U 2 ∂t = ∂2 U 2 ∂x 2 +U 2 ∂U 1 ∂x -U 1 ∂U 2 ∂x (5)
where -1≤x≤1 and t≥0. The boundary conditions are given by
∂U 1 ∂x =0  and  U 1=1  at ​x=-1,   and ∂U 1 ∂x =0  and  U 1=-1  at ​x=1.
The initial conditions at t=0 are given by
U 1=-sin⁡πx 2  and  U 2=π 2 4 sin⁡πx 2.
The absence of boundary conditions for U 2 x,t does not pose any difficulties provided that the derivative flux boundary conditions are assigned to the first PDE (4) which has the correct flux, ∂U 1 ∂x . The conditions on U 1 x,t at the boundaries are assigned to the second PDE by setting β 2=0.0 in equation (3) and placing the Dirichlet boundary conditions on U 1 x,t in the function γ 2.

10.1 Program Text

Note: the following programs illustrate the use of D03PDF and D03PDA.

Program Text (d03pdfe.f90)

Program Text (d03pdae.f90)

10.2 Program Data

Program Data (d03pdfe.d)

Program Data (d03pdae.d)

10.3 Program Results

Program Results (d03pdfe.r)

Program Results (d03pdae.r)

GnuplotProduced by GNUPLOT 5.0 patchlevel 0 Example Program Solution, U(1,x,t), of Elliptic-parabolic Pair using Chebyshev Collocation and BDF U(1,x,t) gnuplot_plot_1 gnuplot_plot_2 0.000010 0.000100 0.001000 0.010000 0.100000 1.000000 Time (logscale) −1 −0.5 0 0.5 1 x −1 −0.5 0 0.5 1
GnuplotProduced by GNUPLOT 5.0 patchlevel 0 Solution, U(2,x,t), of Elliptic-parabolic Pair using Chebyshev Collocation and BDF U(2,x,t) gnuplot_plot_1 gnuplot_plot_2 0.000010 0.000100 0.001000 0.010000 0.100000 1.000000 Time (logscale) −1 −0.5 0 0.5 1 x −3 −2 −1 0 1 2 3
D03 Chapter Contents
D03 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


D03PEF : NAG Library, Mark 26

D03 Chapter Contents
D03 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

D03PEF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

D03PEF integrates a system of linear or nonlinear, first-order, time-dependent partial differential equations (PDEs) in one space variable. The spatial discretization is performed using the Keller box scheme and the method of lines is employed to reduce the PDEs to a system of ordinary differential equations (ODEs). The resulting system is solved using a Backward Differentiation Formula (BDF) method.

2 Specification

SUBROUTINE D03PEF ( NPDE, TS, TOUT, PDEDEF, BNDARY, U, NPTS, X, NLEFT, ACC, RSAVE, LRSAVE, ISAVE, LISAVE, ITASK, ITRACE, IND, IFAIL)
INTEGER | NPDE, NPTS, NLEFT, LRSAVE, ISAVE(LISAVE), LISAVE, ITASK, ITRACE, IND, IFAIL
REAL (KIND=nag_wp) | TS, TOUT, U(NPDE,NPTS), X(NPTS), ACC, RSAVE(LRSAVE)
EXTERNAL | PDEDEF, BNDARY

3 Description

D03PEF integrates the system of first-order PDEs
Gi x,t,U,Ux,Ut=0,  i=1,2,…,NPDE. (1)
In particular the functions Gi must have the general form
Gi=∑j=1 NPDE P i,j ∂Uj ∂t +Qi,  i=1,2,…,NPDE,  a≤x≤b,t≥t 0, (2)
where P i,j and Qi depend on x, t, U, Ux and the vector U is the set of solution values
U x,t = U 1 x,t ,…, U NPDE x,t T , (3)
and the vector Ux is its partial derivative with respect to x. Note that P i,j and Qi must not depend on ∂U ∂t .
The integration in time is from t 0 to tout, over the space interval a≤x≤b, where a=x 1 and b=xNPTS are the leftmost and rightmost points of a user-defined mesh x 1,x 2,…,xNPTS. The mesh should be chosen in accordance with the expected behaviour of the solution.
The PDE system which is defined by the functions Gi must be specified in PDEDEF.
The initial values of the functions U x,t must be given at t=t 0. For a first-order system of PDEs, only one boundary condition is required for each PDE component Ui. The NPDE boundary conditions are separated into na at the left-hand boundary x=a, and nb at the right-hand boundary x=b, such that na+nb=NPDE. The position of the boundary condition for each component should be chosen with care; the general rule is that if the characteristic direction of Ui at the left-hand boundary (say) points into the interior of the solution domain, then the boundary condition for Ui should be specified at the left-hand boundary. Incorrect positioning of boundary conditions generally results in initialization or integration difficulties in the underlying time integration routines.
The boundary conditions have the form:
GiL x,t,U,Ut=0  at ​x=a,  i=1,2,…,na (4)
at the left-hand boundary, and
GiR x,t,U,Ut=0  at ​x=b,  i=1,2,…,nb (5)
at the right-hand boundary.
Note that the functions GiL and GiR must not depend on Ux, since spatial derivatives are not determined explicitly in the Keller box scheme (see Keller (1970)). If the problem involves derivative (Neumann) boundary conditions then it is generally possible to restate such boundary conditions in terms of permissible variables. Also note that GiL and GiR must be linear with respect to time derivatives, so that the boundary conditions have the general form
∑j=1 NPDE E i,j L ∂Uj ∂t +SiL=0,   i=1,2,…,na (6)
at the left-hand boundary, and
∑j=1 NPDE E i,j R ∂Uj ∂t +SiR=0,   i=1,2,…,nb (7)
at the right-hand boundary, where E i,j L, E i,j R, SiL, and SiR depend on x, t and U only.
The boundary conditions must be specified in BNDARY.
The problem is subject to the following restrictions:
(i) | t 0<tout, so that integration is in the forward direction;
(ii) | P i,j and Qi must not depend on any time derivatives;
(iii) | The evaluation of the function Gi is done at the mid-points of the mesh intervals by calling the PDEDEF for each mid-point in turn. Any discontinuities in the function must therefore be at one or more of the mesh points x 1,x 2,…,xNPTS;
(iv) | At least one of the functions P i,j must be nonzero so that there is a time derivative present in the problem.
In this method of lines approach the Keller box scheme (see Keller (1970)) is applied to each PDE in the space variable only, resulting in a system of ODEs in time for the values of Ui at each mesh point. In total there are NPDE×NPTS ODEs in the time direction. This system is then integrated forwards in time using a BDF method.

4 References

Berzins M (1990) Developments in the NAG Library software for parabolic equations Scientific Software Systems (eds J C Mason and M G Cox) 59–72 Chapman and Hall
Berzins M, Dew P M and Furzeland R M (1989) Developing software for time-dependent problems using the method of lines and differential-algebraic integrators Appl. Numer. Math. 5 375–397
Keller H B (1970) A new difference scheme for parabolic problems Numerical Solutions of Partial Differential Equations (ed J Bramble) 2 327–350 Academic Press
Pennington S V and Berzins M (1994) New NAG Library software for first-order partial differential equations ACM Trans. Math. Softw. 20 63–99

5 Arguments

1:   NPDE – INTEGERInput
On entry: the number of PDEs in the system to be solved.
Constraint: NPDE≥1.
2:   TS – REAL (KIND=nag_wp)Input/Output
On entry: the initial value of the independent variable t.
Constraint: TS<TOUT.
On exit: the value of t corresponding to the solution values in U. Normally TS=TOUT.
3:   TOUT – REAL (KIND=nag_wp)Input
On entry: the final value of t to which the integration is to be carried out.
4:   PDEDEF – SUBROUTINE, supplied by the user.External Procedure
PDEDEF must compute the functions Gi which define the system of PDEs. PDEDEF is called approximately midway between each pair of mesh points in turn by D03PEF.
The specification of PDEDEF is:
SUBROUTINE PDEDEF ( NPDE, T, X, U, UT, UX, RES, IRES)
INTEGER | NPDE, IRES
REAL (KIND=nag_wp) | T, X, U(NPDE), UT(NPDE), UX(NPDE), RES(NPDE)
1:   NPDE – INTEGERInput
On entry: the number of PDEs in the system.
2:   T – REAL (KIND=nag_wp)Input
On entry: the current value of the independent variable t.
3:   X – REAL (KIND=nag_wp)Input
On entry: the current value of the space variable x.
4:   U NPDE – REAL (KIND=nag_wp) arrayInput
On entry: U i contains the value of the component Ui x,t, for i=1,2,…,NPDE.
5:   UT NPDE – REAL (KIND=nag_wp) arrayInput
On entry: UT i contains the value of the component ∂Ui x,t ∂t , for i=1,2,…,NPDE.
6:   UX NPDE – REAL (KIND=nag_wp) arrayInput
On entry: UX i contains the value of the component ∂Ui x,t ∂x , for i=1,2,…,NPDE.
7:   RES NPDE – REAL (KIND=nag_wp) arrayOutput
On exit: RES i must contain the ith component of G, for i=1,2,…,NPDE, where G is defined as
Gi=∑j=1 NPDE P i,j ∂Uj ∂t , (8)
i.e., only terms depending explicitly on time derivatives, or
Gi=∑j=1 NPDE P i,j ∂Uj ∂t +Qi, (9)
i.e., all terms in equation (2).
The definition of G is determined by the input value of IRES.
8:   IRES – INTEGERInput/Output
On entry: the form of Gi that must be returned in the array RES.
IRES=-1
Equation (8) must be used.
IRES=1
Equation (9) must be used.
On exit: should usually remain unchanged. However, you may set IRES to force the integration routine to take certain actions, as described below:
IRES=2
Indicates to the integrator that control should be passed back immediately to the calling (sub)routine with the error indicator set to IFAIL=6.
IRES=3
Indicates to the integrator that the current time step should be abandoned and a smaller time step used instead. You may wish to set IRES=3 when a physically meaningless input or output value has been generated. If you consecutively set IRES=3, then D03PEF returns to the calling subroutine with the error indicator set to IFAIL=4.
PDEDEF must either be a module subprogram USEd by, or declared as EXTERNAL in, the (sub)program from which D03PEF is called. Arguments denoted as Input must not be changed by this procedure.
5:   BNDARY – SUBROUTINE, supplied by the user.External Procedure
BNDARY must compute the functions GiL and GiR which define the boundary conditions as in equations (4) and (5).
The specification of BNDARY is:
SUBROUTINE BNDARY ( NPDE, T, IBND, NOBC, U, UT, RES, IRES)
INTEGER | NPDE, IBND, NOBC, IRES
REAL (KIND=nag_wp) | T, U(NPDE), UT(NPDE), RES(NOBC)
1:   NPDE – INTEGERInput
On entry: the number of PDEs in the system.
2:   T – REAL (KIND=nag_wp)Input
On entry: the current value of the independent variable t.
3:   IBND – INTEGERInput
On entry: determines the position of the boundary conditions.
IBND=0
BNDARY must compute the left-hand boundary condition at x=a.
IBND≠0
Indicates that BNDARY must compute the right-hand boundary condition at x=b.
4:   NOBC – INTEGERInput
On entry: specifies the number of boundary conditions at the boundary specified by IBND.
5:   U NPDE – REAL (KIND=nag_wp) arrayInput
On entry: U i contains the value of the component Ui x,t at the boundary specified by IBND, for i=1,2,…,NPDE.
6:   UT NPDE – REAL (KIND=nag_wp) arrayInput
On entry: UT i contains the value of the component ∂Ui x,t ∂t at the boundary specified by IBND, for i=1,2,…,NPDE.
7:   RES NOBC – REAL (KIND=nag_wp) arrayOutput
On exit: RES i must contain the ith component of GL or GR, depending on the value of IBND, for i=1,2,…,NOBC, where GL is defined as
GiL=∑j=1 NPDE E i,j L ∂Uj ∂t , (10)
i.e., only terms depending explicitly on time derivatives, or
GiL=∑j=1 NPDE E i,j L ∂Uj ∂t +SiL, (11)
i.e., all terms in equation (6), and similarly for GiR.
The definitions of GL and GR are determined by the input value of IRES.
8:   IRES – INTEGERInput/Output
On entry: the form GiL (or GiR) that must be returned in the array RES.
IRES=-1
Equation (10) must be used.
IRES=1
Equation (11) must be used.
On exit: should usually remain unchanged. However, you may set IRES to force the integration routine to take certain actions, as described below:
IRES=2
Indicates to the integrator that control should be passed back immediately to the calling (sub)routine with the error indicator set to IFAIL=6.
IRES=3
Indicates to the integrator that the current time step should be abandoned and a smaller time step used instead. You may wish to set IRES=3 when a physically meaningless input or output value has been generated. If you consecutively set IRES=3, then D03PEF returns to the calling subroutine with the error indicator set to IFAIL=4.
BNDARY must either be a module subprogram USEd by, or declared as EXTERNAL in, the (sub)program from which D03PEF is called. Arguments denoted as Input must not be changed by this procedure.
6:   U NPDENPTS – REAL (KIND=nag_wp) arrayInput/Output
On entry: the initial values of U x,t at t=TS and the mesh points X j, for j=1,2,…,NPTS.
On exit: U ij will contain the computed solution at t=TS.
7:   NPTS – INTEGERInput
On entry: the number of mesh points in the interval a,b.
Constraint: NPTS≥3.
8:   X NPTS – REAL (KIND=nag_wp) arrayInput
On entry: the mesh points in the spatial direction. X 1 must specify the left-hand boundary, a, and X NPTS must specify the right-hand boundary, b.
Constraint: X 1<X 2<⋯<X NPTS.
9:   NLEFT – INTEGERInput
On entry: the number na of boundary conditions at the left-hand mesh point X 1.
Constraint: 0≤NLEFT≤NPDE.
10:   ACC – REAL (KIND=nag_wp)Input
On entry: a positive quantity for controlling the local error estimate in the time integration. If E i,j is the estimated error for Ui at the jth mesh point, the error test is:
E i,j=ACC×1.0+U ij.
Constraint: ACC>0.0.
11:   RSAVE LRSAVE – REAL (KIND=nag_wp) arrayCommunication Array
If IND=0, RSAVE need not be set on entry.
If IND=1, RSAVE must be unchanged from the previous call to the routine because it contains required information about the iteration.
12:   LRSAVE – INTEGERInput
On entry: the dimension of the array RSAVE as declared in the (sub)program from which D03PEF is called.
Constraint: LRSAVE≥4×NPDE+NLEFT+14×NPDE×NPTS+3×NPDE+21×NPDE+7×NPTS+54.
13:   ISAVE LISAVE – INTEGER arrayCommunication Array
If IND=0, ISAVE need not be set on entry.
If IND=1, ISAVE must be unchanged from the previous call to the routine because it contains required information about the iteration. In particular:
ISAVE 1
Contains the number of steps taken in time.
ISAVE 2
Contains the number of residual evaluations of the resulting ODE system used. One such evaluation involves computing the PDE functions at all the mesh points, as well as one evaluation of the functions in the boundary conditions.
ISAVE 3
Contains the number of Jacobian evaluations performed by the time integrator.
ISAVE 4
Contains the order of the last backward differentiation formula method used.
ISAVE 5
Contains the number of Newton iterations performed by the time integrator. Each iteration involves an ODE residual evaluation followed by a back-substitution using the LU decomposition of the Jacobian matrix.
14:   LISAVE – INTEGERInput
On entry: the dimension of the array ISAVE as declared in the (sub)program from which D03PEF is called.
Constraint: LISAVE≥NPDE×NPTS+24.
15:   ITASK – INTEGERInput
On entry: specifies the task to be performed by the ODE integrator.
ITASK=1
Normal computation of output values U at t=TOUT.
ITASK=2
Take one step and return.
ITASK=3
Stop at the first internal integration point at or beyond t=TOUT.
Constraint: ITASK=1, 2 or 3.
16:   ITRACE – INTEGERInput
On entry: the level of trace information required from D03PEF and the underlying ODE solver as follows:
ITRACE≤-1
No output is generated.
ITRACE=0
Only warning messages from the PDE solver are printed on the current error message unit (see X04AAF).
ITRACE=1
Output from the underlying ODE solver is printed on the current advisory message unit (see X04ABF). This output contains details of Jacobian entries, the nonlinear iteration and the time integration during the computation of the ODE system.
ITRACE=2
Output from the underlying ODE solver is similar to that produced when ITRACE=1, except that the advisory messages are given in greater detail.
ITRACE≥3
Output from the underlying ODE solver is similar to that produced when ITRACE=2, except that the advisory messages are given in greater detail.
You are advised to set ITRACE=0, unless you are experienced with Sub-chapter D02M–N.
17:   IND – INTEGERInput/Output
On entry: indicates whether this is a continuation call or a new integration.
IND=0
Starts or restarts the integration in time.
IND=1
Continues the integration after an earlier exit from the routine. In this case, only the arguments TOUT and IFAIL should be reset between calls to D03PEF.
Constraint: IND=0 or 1.
On exit: IND=1.
18:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, | TOUT≤TS,
or | TOUT-TS is too small,
or | ITASK≠1, 2 or 3,
or | mesh points ​X i are not ordered correctly,
or | NPTS<3,
or | NPDE<1,
or | NLEFT is not in the range 0 to NPDE,
or | ACC≤0.0,
or | IND≠0 or 1,
or | LRSAVE is too small,
or | LISAVE is too small,
or | D03PEF called initially with IND=1.
IFAIL=2
The underlying ODE solver cannot make any further progress across the integration range from the current point t=TS with the supplied value of ACC. The components of U contain the computed values at the current point t=TS.
IFAIL=3
In the underlying ODE solver, there were repeated errors or corrector convergence test failures on an attempted step, before completing the requested task. The problem may have a singularity or ACC is too small for the integration to continue. Incorrect positioning of boundary conditions may also result in this error. Integration was successful as far as t=TS.
IFAIL=4
In setting up the ODE system, the internal initialization routine was unable to initialize the derivative of the ODE system. This could be due to the fact that IRES was repeatedly set to 3 in the PDEDEF or BNDARY, when the residual in the underlying ODE solver was being evaluated. Incorrect positioning of boundary conditions may also result in this error.
IFAIL=5
In solving the ODE system, a singular Jacobian has been encountered. You should check their problem formulation.
IFAIL=6
When evaluating the residual in solving the ODE system, IRES was set to 2 in one of PDEDEF or BNDARY. Integration was successful as far as t=TS.
IFAIL=7
The value of ACC is so small that the routine is unable to start the integration in time.
IFAIL=8
In either, PDEDEF or BNDARY, IRES was set to an invalid value.
IFAIL=9 (D02NNF)
A serious error has occurred in an internal call to the specified routine. Check the problem specification and all arguments and array dimensions. Setting ITRACE=1 may provide more information. If the problem persists, contact NAG.
IFAIL=10
The required task has been completed, but it is estimated that a small change in ACC is unlikely to produce any change in the computed solution. (Only applies when you are not operating in one step mode, that is when ITASK≠2.)
IFAIL=11
An error occurred during Jacobian formulation of the ODE system (a more detailed error description may be directed to the current advisory message unit).
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

D03PEF controls the accuracy of the integration in the time direction but not the accuracy of the approximation in space. The spatial accuracy depends on both the number of mesh points and on their distribution in space. In the time integration only the local error over a single step is controlled and so the accuracy over a number of steps cannot be guaranteed. You should therefore test the effect of varying the accuracy argument, ACC.

8 Parallelism and Performance

D03PEF is not thread safe and should not be called from a multithreaded user program. Please see Section 3.12.1 in How to Use the NAG Library and its Documentation for more information on thread safety.
D03PEF is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
D03PEF makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The Keller box scheme can be used to solve higher-order problems which have been reduced to first-order by the introduction of new variables (see the example problem in D03PKF). In general, a second-order problem can be solved with slightly greater accuracy using the Keller box scheme instead of a finite difference scheme (D03PCF/D03PCA or D03PHF/D03PHA for example), but at the expense of increased CPU time due to the larger number of function evaluations required.
It should be noted that the Keller box scheme, in common with other central-difference schemes, may be unsuitable for some hyperbolic first-order problems such as the apparently simple linear advection equation Ut+a Ux=0, where a is a constant, resulting in spurious oscillations due to the lack of dissipation. This type of problem requires a discretization scheme with upwind weighting (D03PFF for example), or the addition of a second-order artificial dissipation term.
The time taken depends on the complexity of the system and on the accuracy requested.

10 Example

This example is the simple first-order system
∂U 1 ∂t + ∂U 1 ∂x + ∂U 2 ∂x =0, ∂U 2 ∂t +4 ∂U 1 ∂x + ∂U 2 ∂x =0,
for t∈0,1 and x∈0,1.
The initial conditions are
U 1 x,0=exp x,  U 2 x,0=sin x,
and the Dirichlet boundary conditions for U 1 at x=0 and U 2 at x=1 are given by the exact solution:
U 1 x,t=12 exp x+t+exp x-3 t+14 sin x-3 t-sin x+t , U 2 x,t=exp x-3 t-exp x+t+12 sin x+t+sin x-3 t .

10.1 Program Text

Program Text (d03pefe.f90)

10.2 Program Data

Program Data (d03pefe.d)

10.3 Program Results

Program Results (d03pefe.r)

GnuplotProduced by GNUPLOT 5.0 patchlevel 0 Example Program Solution, U(1,x,t), of First-order System using Keller, Box and BDF U(1,x,t) gnuplot_plot_1 gnuplot_plot_2 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9 1 Time 0 0.2 0.4 0.6 0.8 1 x 0.5 1 1.5 2 2.5 3 3.5
GnuplotProduced by GNUPLOT 5.0 patchlevel 0 Solution, U(2,x,t), of First-order System using Keller, Box and BDF U(2,x,t) gnuplot_plot_1 gnuplot_plot_2 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9 1 Time 0 0.2 0.4 0.6 0.8 1 x −8 −7 −6 −5 −4 −3 −2 −1 0
D03 Chapter Contents
D03 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


D03PFF : NAG Library, Mark 26

D03 Chapter Contents
D03 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

D03PFF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

D03PFF integrates a system of linear or nonlinear convection-diffusion equations in one space dimension, with optional source terms. The system must be posed in conservative form. Convection terms are discretized using a sophisticated upwind scheme involving a user-supplied numerical flux function based on the solution of a Riemann problem at each mesh point. The method of lines is employed to reduce the PDEs to a system of ordinary differential equations (ODEs), and the resulting system is solved using a backward differentiation formula (BDF) method.

2 Specification

SUBROUTINE D03PFF ( NPDE, TS, TOUT, PDEDEF, NUMFLX, BNDARY, U, NPTS, X, ACC, TSMAX, RSAVE, LRSAVE, ISAVE, LISAVE, ITASK, ITRACE, IND, IFAIL)
INTEGER | NPDE, NPTS, LRSAVE, ISAVE(LISAVE), LISAVE, ITASK, ITRACE, IND, IFAIL
REAL (KIND=nag_wp) | TS, TOUT, U(NPDE,NPTS), X(NPTS), ACC(2), TSMAX, RSAVE(LRSAVE)
EXTERNAL | PDEDEF, NUMFLX, BNDARY

3 Description

D03PFF integrates the system of convection-diffusion equations in conservative form:
∑j=1 NPDE P i,j ∂Uj ∂t + ∂Fi ∂x =Ci ∂Di ∂x +Si, (1)
or the hyperbolic convection-only system:
∂Ui ∂t + ∂Fi ∂x =0, (2)
for i=1,2,…,NPDE,  a≤x≤b,  t≥t 0, where the vector U is the set of solution values
U x,t = U 1 x,t ,…, U NPDE x,t T .
The functions P i,j, Fi, Ci and Si depend on x, t and U; and Di depends on x, t, U and Ux, where Ux is the spatial derivative of U. Note that P i,j, Fi, Ci and Si must not depend on any space derivatives; and none of the functions may depend on time derivatives. In terms of conservation laws, Fi, Ci∂Di ∂x and Si are the convective flux, diffusion and source terms respectively.
The integration in time is from t 0 to tout, over the space interval a≤x≤b, where a=x 1 and b=xNPTS are the leftmost and rightmost points of a user-defined mesh x 1,x 2,…,xNPTS. The initial values of the functions U x,t must be given at t=t 0.
The PDEs are approximated by a system of ODEs in time for the values of Ui at mesh points using a spatial discretization method similar to the central-difference scheme used in D03PCF/D03PCA, D03PHF/D03PHA and D03PPF/D03PPA, but with the flux Fi replaced by a numerical flux, which is a representation of the flux taking into account the direction of the flow of information at that point (i.e., the direction of the characteristics). Simple central differencing of the numerical flux then becomes a sophisticated upwind scheme in which the correct direction of upwinding is automatically achieved.
The numerical flux vector, F^i say, must be calculated by you in terms of the left and right values of the solution vector U (denoted by UL and UR respectively), at each mid-point of the mesh x j-1/2=x j-1+xj/2, for j=2,3,…,NPTS. The left and right values are calculated by D03PFF from two adjacent mesh points using a standard upwind technique combined with a Van Leer slope-limiter (see LeVeque (1990)). The physically correct value for F^i is derived from the solution of the Riemann problem given by
∂Ui ∂t + ∂Fi ∂y =0, (3)
where y=x-x j-1/2, i.e., y=0 corresponds to x=x j-1/2, with discontinuous initial values U=UL for y<0 and U=UR for y>0, using an approximate Riemann solver. This applies for either of the systems (1) or (2); the numerical flux is independent of the functions P i,j, Ci, Di and Si. A description of several approximate Riemann solvers can be found in LeVeque (1990) and Berzins et al. (1989). Roe's scheme (see Roe (1981)) is perhaps the easiest to understand and use, and a brief summary follows. Consider the system of PDEs Ut+Fx=0 or equivalently Ut+A Ux=0. Provided the system is linear in U, i.e., the Jacobian matrix A does not depend on U, the numerical flux F^ is given by
F^=12 FL+FR-12∑k=1 NPDE αk λk ek, (4)
where FL (FR) is the flux F calculated at the left (right) value of U, denoted by UL (UR); the λk are the eigenvalues of A; the ek are the right eigenvectors of A; and the αk are defined by
UR-UL=∑k=1 NPDE αkek. (5)
An example is given in Section 10.
If the system is nonlinear, Roe's scheme requires that a linearized Jacobian is found (see Roe (1981)).
The functions P i,j, Ci, Di and Si (but not Fi) must be specified in a PDEDEF. The numerical flux F^i must be supplied in a separate NUMFLX. For problems in the form (2), the actual argument D03PFP may be used for PDEDEF. D03PFP is included in the NAG Library and sets the matrix with entries P i,j to the identity matrix, and the functions Ci, Di and Si to zero.
The boundary condition specification has sufficient flexibility to allow for different types of problems. For second-order problems, i.e., Di depending on Ux, a boundary condition is required for each PDE at both boundaries for the problem to be well-posed. If there are no second-order terms present, then the continuous PDE problem generally requires exactly one boundary condition for each PDE, that is NPDE boundary conditions in total. However, in common with most discretization schemes for first-order problems, a numerical boundary condition is required at the other boundary for each PDE. In order to be consistent with the characteristic directions of the PDE system, the numerical boundary conditions must be derived from the solution inside the domain in some manner (see below). You must supply both types of boundary conditions, i.e., a total of NPDE conditions at each boundary point.
The position of each boundary condition should be chosen with care. In simple terms, if information is flowing into the domain then a physical boundary condition is required at that boundary, and a numerical boundary condition is required at the other boundary. In many cases the boundary conditions are simple, e.g., for the linear advection equation. In general you should calculate the characteristics of the PDE system and specify a physical boundary condition for each of the characteristic variables associated with incoming characteristics, and a numerical boundary condition for each outgoing characteristic.
A common way of providing numerical boundary conditions is to extrapolate the characteristic variables from the inside of the domain. Note that only linear extrapolation is allowed in this routine (for greater flexibility the routine D03PLF should be used). For problems in which the solution is known to be uniform (in space) towards a boundary during the period of integration then extrapolation is unnecessary; the numerical boundary condition can be supplied as the known solution at the boundary. Examples can be found in Section 10.
The boundary conditions must be specified in BNDARY in the form
GiL x,t,U=0  at ​x=a,  i=1,2,…,NPDE, (6)
at the left-hand boundary, and
GiR x,t,U=0  at ​x=b,  i=1,2,…,NPDE, (7)
at the right-hand boundary.
Note that spatial derivatives at the boundary are not passed explicitly to BNDARY, but they can be calculated using values of U at and adjacent to the boundaries if required. However, it should be noted that instabilities may occur if such one-sided differencing opposes the characteristic direction at the boundary.
The problem is subject to the following restrictions:
(i) | P i,j, Fi, Ci and Si must not depend on any space derivatives;
(ii) | P i,j, Fi, Ci, Di and Si must not depend on any time derivatives;
(iii) | t 0<tout, so that integration is in the forward direction;
(iv) | The evaluation of the terms P i,j, Ci, Di and Si is done by calling the PDEDEF at a point approximately midway between each pair of mesh points in turn. Any discontinuities in these functions must therefore be at one or more of the mesh points x 1,x 2,…,xNPTS;
(v) | At least one of the functions P i,j must be nonzero so that there is a time derivative present in the PDE problem.
In total there are NPDE×NPTS ODEs in the time direction. This system is then integrated forwards in time using a BDF method.
For further details of the algorithm, see Pennington and Berzins (1994) and the references therein.

4 References

Berzins M, Dew P M and Furzeland R M (1989) Developing software for time-dependent problems using the method of lines and differential-algebraic integrators Appl. Numer. Math. 5 375–397
Hirsch C (1990) Numerical Computation of Internal and External Flows, Volume 2: Computational Methods for Inviscid and Viscous Flows John Wiley
LeVeque R J (1990) Numerical Methods for Conservation Laws Birkhäuser Verlag
Pennington S V and Berzins M (1994) New NAG Library software for first-order partial differential equations ACM Trans. Math. Softw. 20 63–99
Roe P L (1981) Approximate Riemann solvers, parameter vectors, and difference schemes J. Comput. Phys. 43 357–372

5 Arguments

1:   NPDE – INTEGERInput
On entry: the number of PDEs to be solved.
Constraint: NPDE≥1.
2:   TS – REAL (KIND=nag_wp)Input/Output
On entry: the initial value of the independent variable t.
On exit: the value of t corresponding to the solution values in U. Normally TS=TOUT.
Constraint: TS<TOUT.
3:   TOUT – REAL (KIND=nag_wp)Input
On entry: the final value of t to which the integration is to be carried out.
4:   PDEDEF – SUBROUTINE, supplied by the NAG Library or the user.External Procedure
PDEDEF must evaluate the functions P i,j, Ci, Di and Si which partially define the system of PDEs. P i,j, Ci and Si may depend on x, t and U; Di may depend on x, t, U and Ux. PDEDEF is called approximately midway between each pair of mesh points in turn by D03PFF. The actual argument D03PFP may be used for PDEDEF for problems in the form (2). (D03PFP is included in the NAG Library.)
The specification of PDEDEF is:
SUBROUTINE PDEDEF ( NPDE, T, X, U, UX, P, C, D, S, IRES)
INTEGER | NPDE, IRES
REAL (KIND=nag_wp) | T, X, U(NPDE), UX(NPDE), P(NPDE,NPDE), C(NPDE), D(NPDE), S(NPDE)
1:   NPDE – INTEGERInput
On entry: the number of PDEs in the system.
2:   T – REAL (KIND=nag_wp)Input
On entry: the current value of the independent variable t.
3:   X – REAL (KIND=nag_wp)Input
On entry: the current value of the space variable x.
4:   U NPDE – REAL (KIND=nag_wp) arrayInput
On entry: U i contains the value of the component Ui x,t, for i=1,2,…,NPDE.
5:   UX NPDE – REAL (KIND=nag_wp) arrayInput
On entry: UX i contains the value of the component ∂Ui x,t ∂x , for i=1,2,…,NPDE.
6:   P NPDENPDE – REAL (KIND=nag_wp) arrayOutput
On exit: P ij must be set to the value of P i,j x,t,U, for i=1,2,…,NPDE and j=1,2,…,NPDE.
7:   C NPDE – REAL (KIND=nag_wp) arrayOutput
On exit: C i must be set to the value of Ci x,t,U, for i=1,2,…,NPDE.
8:   D NPDE – REAL (KIND=nag_wp) arrayOutput
On exit: D i must be set to the value of Di x,t,U,Ux, for i=1,2,…,NPDE.
9:   S NPDE – REAL (KIND=nag_wp) arrayOutput
On exit: S i must be set to the value of Si x,t,U, for i=1,2,…,NPDE.
10:   IRES – INTEGERInput/Output
On entry: set to -1​ or ​1.
On exit: should usually remain unchanged. However, you may set IRES to force the integration routine to take certain actions as described below:
IRES=2
Indicates to the integrator that control should be passed back immediately to the calling subroutine with the error indicator set to IFAIL=6.
IRES=3
Indicates to the integrator that the current time step should be abandoned and a smaller time step used instead. You may wish to set IRES=3 when a physically meaningless input or output value has been generated. If you consecutively set IRES=3, then D03PFF returns to the calling subroutine with the error indicator set to IFAIL=4.
PDEDEF must either be a module subprogram USEd by, or declared as EXTERNAL in, the (sub)program from which D03PFF is called. Arguments denoted as Input must not be changed by this procedure.
5:   NUMFLX – SUBROUTINE, supplied by the user.External Procedure
NUMFLX must supply the numerical flux for each PDE given the left and right values of the solution vector U. NUMFLX is called approximately midway between each pair of mesh points in turn by D03PFF.
The specification of NUMFLX is:
SUBROUTINE NUMFLX ( NPDE, T, X, ULEFT, URIGHT, FLUX, IRES)
INTEGER | NPDE, IRES
REAL (KIND=nag_wp) | T, X, ULEFT(NPDE), URIGHT(NPDE), FLUX(NPDE)
1:   NPDE – INTEGERInput
On entry: the number of PDEs in the system.
2:   T – REAL (KIND=nag_wp)Input
On entry: the current value of the independent variable t.
3:   X – REAL (KIND=nag_wp)Input
On entry: the current value of the space variable x.
4:   ULEFT NPDE – REAL (KIND=nag_wp) arrayInput
On entry: ULEFT i contains the left value of the component Ui x, for i=1,2,…,NPDE.
5:   URIGHT NPDE – REAL (KIND=nag_wp) arrayInput
On entry: URIGHT i contains the right value of the component Ui x, for i=1,2,…,NPDE.
6:   FLUX NPDE – REAL (KIND=nag_wp) arrayOutput
On exit: FLUX i must be set to the numerical flux F^i, for i=1,2,…,NPDE.
7:   IRES – INTEGERInput/Output
On entry: set to -1​ or ​1.
On exit: should usually remain unchanged. However, you may set IRES to force the integration routine to take certain actions as described below:
IRES=2
Indicates to the integrator that control should be passed back immediately to the calling subroutine with the error indicator set to IFAIL=6.
IRES=3
Indicates to the integrator that the current time step should be abandoned and a smaller time step used instead. You may wish to set IRES=3 when a physically meaningless input or output value has been generated. If you consecutively set IRES=3, then D03PFF returns to the calling subroutine with the error indicator set to IFAIL=4.
NUMFLX must either be a module subprogram USEd by, or declared as EXTERNAL in, the (sub)program from which D03PFF is called. Arguments denoted as Input must not be changed by this procedure.
6:   BNDARY – SUBROUTINE, supplied by the user.External Procedure
BNDARY must evaluate the functions GiL and GiR which describe the physical and numerical boundary conditions, as given by (6) and (7).
The specification of BNDARY is:
SUBROUTINE BNDARY ( NPDE, NPTS, T, X, U, IBND, G, IRES)
INTEGER | NPDE, NPTS, IBND, IRES
REAL (KIND=nag_wp) | T, X(NPTS), U(NPDE,3), G(NPDE)
1:   NPDE – INTEGERInput
On entry: the number of PDEs in the system.
2:   NPTS – INTEGERInput
On entry: the number of mesh points in the interval a,b.
3:   T – REAL (KIND=nag_wp)Input
On entry: the current value of the independent variable t.
4:   X NPTS – REAL (KIND=nag_wp) arrayInput
On entry: the mesh points in the spatial direction. X 1 corresponds to the left-hand boundary, a, and X NPTS corresponds to the right-hand boundary, b.
5:   U NPDE 3 – REAL (KIND=nag_wp) arrayInput
On entry: contains the value of solution components in the boundary region.
If IBND=0, U ij contains the value of the component Ui x ,t at x=X j, for i=1,2,…,NPDE and j=1,2,3.
If IBND≠0, U ij contains the value of the component Ui x,t at x=X NPTS-j+1, for i=1,2,…,NPDE and j=1,2,3.
6:   IBND – INTEGERInput
On entry: specifies which boundary conditions are to be evaluated.
IBND=0
BNDARY must evaluate the left-hand boundary condition at x=a.
IBND≠0
BNDARY must evaluate the right-hand boundary condition at x=b.
7:   G NPDE – REAL (KIND=nag_wp) arrayOutput
On exit: G i must contain the ith component of either GL or GR in (6) and (7), depending on the value of IBND, for i=1,2,…,NPDE.
8:   IRES – INTEGERInput/Output
On entry: set to -1​ or ​1.
On exit: should usually remain unchanged. However, you may set IRES to force the integration routine to take certain actions as described below:
IRES=2
Indicates to the integrator that control should be passed back immediately to the calling subroutine with the error indicator set to IFAIL=6.
IRES=3
Indicates to the integrator that the current time step should be abandoned and a smaller time step used instead. You may wish to set IRES=3 when a physically meaningless input or output value has been generated. If you consecutively set IRES=3, then D03PFF returns to the calling subroutine with the error indicator set to IFAIL=4.
BNDARY must either be a module subprogram USEd by, or declared as EXTERNAL in, the (sub)program from which D03PFF is called. Arguments denoted as Input must not be changed by this procedure.
7:   U NPDENPTS – REAL (KIND=nag_wp) arrayInput/Output
On entry: U ij must contain the initial value of Ui x,t at x=X j and t=TS, for i=1,2,…,NPDE and j=1,2,…,NPTS.
On exit: U ij will contain the computed solution Ui x,t at x=X j and t=TS, for i=1,2,…,NPDE and j=1,2,…,NPTS.
8:   NPTS – INTEGERInput
On entry: the number of mesh points in the interval a,b.
Constraint: NPTS≥3.
9:   X NPTS – REAL (KIND=nag_wp) arrayInput
On entry: the mesh points in the space direction. X 1 must specify the left-hand boundary, a, and X NPTS must specify the right-hand boundary, b.
Constraint: X 1<X 2<⋯<X NPTS.
10:   ACC 2 – REAL (KIND=nag_wp) arrayInput
On entry: the components of ACC contain the relative and absolute error tolerances used in the local error test in the time integration.
If E i,j is the estimated error for Ui at the jth mesh point, the error test is
E i,j=ACC 1×U ij+ACC 2.
Constraint: ACC 1 and ACC 2≥0.0 (but not both zero).
11:   TSMAX – REAL (KIND=nag_wp)Input
On entry: the maximum absolute step size to be allowed in the time integration. If TSMAX=0.0 then no maximum is imposed.
Constraint: TSMAX≥0.0.
12:   RSAVE LRSAVE – REAL (KIND=nag_wp) arrayCommunication Array
If IND=0, RSAVE need not be set on entry.
If IND=1, RSAVE must be unchanged from the previous call to the routine because it contains required information about the iteration.
13:   LRSAVE – INTEGERInput
On entry: the dimension of the array RSAVE as declared in the (sub)program from which D03PFF is called.
Constraint: LRSAVE≥11+9×NPDE×NPDE×NPTS+32+3×NPDE×NPDE+7×NPTS+54.
14:   ISAVE LISAVE – INTEGER arrayCommunication Array
If IND=0, ISAVE need not be set on entry.
If IND=1, ISAVE must be unchanged from the previous call to the routine because it contains required information about the iteration. In particular:
ISAVE 1
Contains the number of steps taken in time.
ISAVE 2
Contains the number of residual evaluations of the resulting ODE system used. One such evaluation involves computing the PDE functions at all the mesh points, as well as one evaluation of the functions in the boundary conditions.
ISAVE 3
Contains the number of Jacobian evaluations performed by the time integrator.
ISAVE 4
Contains the order of the last backward differentiation formula method used.
ISAVE 5
Contains the number of Newton iterations performed by the time integrator. Each iteration involves an ODE residual evaluation followed by a back-substitution using the LU decomposition of the Jacobian matrix.
15:   LISAVE – INTEGERInput
On entry: the dimension of the array ISAVE as declared in the (sub)program from which D03PFF is called.
Constraint: LISAVE≥NPDE×NPTS+24.
16:   ITASK – INTEGERInput
On entry: the task to be performed by the ODE integrator.
ITASK=1
Normal computation of output values U at t=TOUT (by overshooting and interpolating).
ITASK=2
Take one step in the time direction and return.
ITASK=3
Stop at first internal integration point at or beyond t=TOUT.
Constraint: ITASK=1, 2 or 3.
17:   ITRACE – INTEGERInput
On entry: the level of trace information required from D03PFF and the underlying ODE solver. ITRACE may take the value -1, 0, 1, 2 or 3.
ITRACE=-1
No output is generated.
ITRACE=0
Only warning messages from the PDE solver are printed on the current error message unit (see X04AAF).
ITRACE>0
Output from the underlying ODE solver is printed on the current advisory message unit (see X04ABF). This output contains details of Jacobian entries, the nonlinear iteration and the time integration during the computation of the ODE system.
If ITRACE<-1, then -1 is assumed and similarly if ITRACE>3, then 3 is assumed.
The advisory messages are given in greater detail as ITRACE increases. You are advised to set ITRACE=0, unless you are experienced with Sub-chapter D02M–N.
18:   IND – INTEGERInput/Output
On entry: indicates whether this is a continuation call or a new integration.
IND=0
Starts or restarts the integration in time.
IND=1
Continues the integration after an earlier exit from the routine. In this case, only the arguments TOUT and IFAIL should be reset between calls to D03PFF.
Constraint: IND=0 or 1.
On exit: IND=1.
19:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, | TS≥TOUT,
or | TOUT-TS is too small,
or | ITASK=1, 2 or 3,
or | NPTS<3,
or | NPDE<1,
or | IND≠0 or 1,
or | incorrect user-defined mesh, i.e., X i≥X i+1 for some i=1,2,…,NPTS-1,
or | LRSAVE or LISAVE are too small,
or | IND=1 on initial entry to D03PFF,
or | ACC 1 or ACC 2<0.0,
or | ACC 1 or ACC 2 are both zero,
or | TSMAX<0.0.
IFAIL=2
The underlying ODE solver cannot make any further progress, with the values of ACC, across the integration range from the current point t=TS. The components of U contain the computed values at the current point t=TS.
IFAIL=3
In the underlying ODE solver, there were repeated error test failures on an attempted step, before completing the requested task, but the integration was successful as far as t=TS. The problem may have a singularity, or the error requirement may be inappropriate. Incorrect specification of boundary conditions may also result in this error.
IFAIL=4
In setting up the ODE system, the internal initialization routine was unable to initialize the derivative of the ODE system. This could be due to the fact that IRES was repeatedly set to 3 in one of PDEDEF, NUMFLX or BNDARY when the residual in the underlying ODE solver was being evaluated. Incorrect specification of boundary conditions may also result in this error.
IFAIL=5
In solving the ODE system, a singular Jacobian has been encountered. Check the problem formulation.
IFAIL=6
When evaluating the residual in solving the ODE system, IRES was set to 2 in at least one of PDEDEF, NUMFLX or BNDARY. Integration was successful as far as t=TS.
IFAIL=7
The values of ACC 1 and ACC 2 are so small that the routine is unable to start the integration in time.
IFAIL=8
In either, PDEDEF, NUMFLX or BNDARY, IRES was set to an invalid value.
IFAIL=9 (D02NNF)
A serious error has occurred in an internal call to the specified routine. Check the problem specification and all arguments and array dimensions. Setting ITRACE=1 may provide more information. If the problem persists, contact NAG.
IFAIL=10
The required task has been completed, but it is estimated that a small change in the values of ACC is unlikely to produce any change in the computed solution. (Only applies when you are not operating in one step mode, that is when ITASK≠2.)
IFAIL=11
An error occurred during Jacobian formulation of the ODE system (a more detailed error description may be directed to the current advisory message unit when ITRACE≥1).
IFAIL=12
Not applicable.
IFAIL=13
Not applicable.
IFAIL=14
One or more of the functions P i,j, Di or Ci was detected as depending on time derivatives, which is not permissible.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

D03PFF controls the accuracy of the integration in the time direction but not the accuracy of the approximation in space. The spatial accuracy depends on both the number of mesh points and on their distribution in space. In the time integration only the local error over a single step is controlled and so the accuracy over a number of steps cannot be guaranteed. You should therefore test the effect of varying the components of the accuracy argument, ACC.

8 Parallelism and Performance

D03PFF is not thread safe and should not be called from a multithreaded user program. Please see Section 3.12.1 in How to Use the NAG Library and its Documentation for more information on thread safety.
D03PFF is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
D03PFF makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

D03PFF is designed to solve systems of PDEs in conservative form, with optional source terms which are independent of space derivatives, and optional second-order diffusion terms. The use of the routine to solve systems which are not naturally in this form is discouraged, and you are advised to use one of the central-difference schemes for such problems.
You should be aware of the stability limitations for hyperbolic PDEs. For most problems with small error tolerances the ODE integrator does not attempt unstable time steps, but in some cases a maximum time step should be imposed using TSMAX. It is worth experimenting with this argument, particularly if the integration appears to progress unrealistically fast (with large time steps). Setting the maximum time step to the minimum mesh size is a safe measure, although in some cases this may be too restrictive.
Problems with source terms should be treated with caution, as it is known that for large source terms stable and reasonable looking solutions can be obtained which are in fact incorrect, exhibiting non-physical speeds of propagation of discontinuities (typically one spatial mesh point per time step). It is essential to employ a very fine mesh for problems with source terms and discontinuities, and to check for non-physical propagation speeds by comparing results for different mesh sizes. Further details and an example can be found in Pennington and Berzins (1994).
The time taken depends on the complexity of the system and on the accuracy requested.

10 Example

For this routine two examples are presented. There is a single example program for D03PFF, with a main program and the code to solve the two example problems given in Example 1 (EX1) and Example 2 (EX2).
Example 1 (EX1)
This example is a simple first-order system which illustrates the calculation of the numerical flux using Roe's approximate Riemann solver, and the specification of numerical boundary conditions using extrapolated characteristic variables. The PDEs are
∂U 1 ∂t + ∂U 1 ∂x + ∂U 2 ∂x = 0, ∂U 2 ∂t +4 ∂U 1 ∂x + ∂U 2 ∂x = 0,
for x ∈ 0,1 and t ≥ 0 . The PDEs have an exact solution given by
U 1 x,t = 12 exp x + t + exp x-3 t + 14 sin 2 π x-3 t 2 - sin 2 π x+t 2 + 2 t 2 - 2 x t , U 2 x,t = exp x-3 t - exp x+t + 12 sin 2 π x-3 t 2 + sin 2 π x - 3 t 2 + x 2 + 5 t 2 - 2 x t .
The initial conditions are given by the exact solution. The characteristic variables are 2 U 1+U 2 and 2 U 1-U 2 corresponding to the characteristics given by dx/dt=3 and dx/dt=-1 respectively. Hence a physical boundary condition is required for 2 U 1+U 2 at the left-hand boundary, and for 2 U 1-U 2 at the right-hand boundary (corresponding to the incoming characteristics); and a numerical boundary condition is required for 2 U 1-U 2 at the left-hand boundary, and for 2 U 1+U 2 at the right-hand boundary (outgoing characteristics). The physical boundary conditions are obtained from the exact solution, and the numerical boundary conditions are calculated by linear extrapolation of the appropriate characteristic variable. The numerical flux is calculated using Roe's approximate Riemann solver: Using the notation in Section 3, the flux vector F and the Jacobian matrix A are
F= U 1+U 2 4 U 1+U 2   and   A= 1 1 4 1 ,
and the eigenvalues of A are 3 and -1 with right eigenvectors 12 T and -12 T respectively. Using equation (4) the αk are given by
U 1 R-U 1 L U 2 R-U 2 L =α 1 1 2 +α 2 -1 2 ,
that is
α 1 = 14 2 U 1 R - 2 U 1 L + U 2 R - U 2 L   and   α 2 = 14 -2 U 1 R + 2 U 1 L + U 2 R - U 2 L .
FL is given by
FL = U 1 L+U 2 L 4 U 1 L+U 2 L ,
and similarly for FR. From equation (4), the numerical flux vector is
F^ = 12 U 1 L+U 2 L+0 U 1 R+U 2 R 4 U 1 L+U 2 L+4 U 1 R+U 2 R - 12 α 1 3 1 2 - 12 α 2 -1 -1 2 ,
that is
F^ = 12 3 U 1 L-0 U 1 R+32 U 2 L+12 U 2 R 6 U 1 L+ 2 U 1 R+ 3 U 2 L-0 U 2 R .
Example 2 (EX2)
This example is an advection-diffusion equation in which the flux term depends explicitly on x:
∂U ∂t +x ∂U ∂x =ε ∂2 U ∂x 2 ,
for x∈-1,1 and 0≤t≤10. The argument ε is taken to be 0.01. The two physical boundary conditions are U-1,t=3.0 and U 1,t=5.0 and the initial condition is U x,0=x+4. The integration is run to steady state at which the solution is known to be U=4 across the domain with a narrow boundary layer at both boundaries. In order to write the PDE in conservative form, a source term must be introduced, i.e.,
∂U ∂t + ∂xU ∂x =ε ∂2 U ∂x 2 +U.
As in Example 1, the numerical flux is calculated using the Roe approximate Riemann solver. The Riemann problem to solve locally is
∂U ∂t + ∂x U ∂x =0.
The x in the flux term is assumed to be constant at a local level, and so using the notation in Section 3, F=xU and A=x. The eigenvalue is x and the eigenvector (a scalar in this case) is 1. The numerical flux is therefore
F^= x UL if ​x≥0, x UR if ​x<0.

10.1 Program Text

Program Text (d03pffe.f90)

10.2 Program Data

Program Data (d03pffe.d)

10.3 Program Results

Program Results (d03pffe.r)

D03 Chapter Contents
D03 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


D03PHF/D03PHA : NAG Library, Mark 26

D03 Chapter Contents
D03 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

D03PHF/D03PHA

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
▸▿ 2 Specification
2.1 Specification for D03PHF
2.2 Specification for D03PHA
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

D03PHF/D03PHA integrates a system of linear or nonlinear parabolic partial differential equations (PDEs) in one space variable, with scope for coupled ordinary differential equations (ODEs). The spatial discretization is performed using finite differences, and the method of lines is employed to reduce the PDEs to a system of ODEs. The resulting system is solved using a backward differentiation formula method or a Theta method (switching between Newton's method and functional iteration).
D03PHA is a version of D03PHF that has additional arguments in order to make it safe for use in multithreaded applications (see Section 5).

2 Specification

2.1 Specification for D03PHF

SUBROUTINE D03PHF ( NPDE, M, TS, TOUT, PDEDEF, BNDARY, U, NPTS, X, NCODE, ODEDEF, NXI, XI, NEQN, RTOL, ATOL, ITOL, NORM, LAOPT, ALGOPT, RSAVE, LRSAVE, ISAVE, LISAVE, ITASK, ITRACE, IND, IFAIL)
INTEGER | NPDE, M, NPTS, NCODE, NXI, NEQN, ITOL, LRSAVE, ISAVE(LISAVE), LISAVE, ITASK, ITRACE, IND, IFAIL
REAL (KIND=nag_wp) | TS, TOUT, U(NEQN), X(NPTS), XI(NXI), RTOL(*), ATOL(*), ALGOPT(30), RSAVE(LRSAVE)
CHARACTER(1) | NORM, LAOPT
EXTERNAL | PDEDEF, BNDARY, ODEDEF

2.2 Specification for D03PHA

SUBROUTINE D03PHA ( NPDE, M, TS, TOUT, PDEDEF, BNDARY, U, NPTS, X, NCODE, ODEDEF, NXI, XI, NEQN, RTOL, ATOL, ITOL, NORM, LAOPT, ALGOPT, RSAVE, LRSAVE, ISAVE, LISAVE, ITASK, ITRACE, IND, IUSER, RUSER, CWSAV, LWSAV, IWSAV, RWSAV, IFAIL)
INTEGER | NPDE, M, NPTS, NCODE, NXI, NEQN, ITOL, LRSAVE, ISAVE(LISAVE), LISAVE, ITASK, ITRACE, IND, IUSER(*), IWSAV(505), IFAIL
REAL (KIND=nag_wp) | TS, TOUT, U(NEQN), X(NPTS), XI(NXI), RTOL(*), ATOL(*), ALGOPT(30), RSAVE(LRSAVE), RUSER(*), RWSAV(1100)
LOGICAL | LWSAV(100)
CHARACTER(1) | NORM, LAOPT
CHARACTER(80) | CWSAV(10)
EXTERNAL | PDEDEF, BNDARY, ODEDEF

3 Description

D03PHF/D03PHA integrates the system of parabolic-elliptic equations and coupled ODEs
∑j=1 NPDE P i,j ∂Uj ∂t +Qi=x-m ∂∂x xm Ri,  i=1,2,…,NPDE,  a≤x≤b,  t≥t 0, (1)
Fi t,V,V.,ξ,U*,Ux*,R*,Ut*,U xt*=0,  i=1,2,…,NCODE, (2)
where (1) defines the PDE part and (2) generalizes the coupled ODE part of the problem.
In (1), P i,j and Ri depend on x, t, U, Ux and V; Qi depends on x, t, U, Ux, V and linearly on V.. The vector U is the set of PDE solution values
U x,t = U 1 x,t ,…, U NPDE x,t T ,
and the vector Ux is the partial derivative with respect to x. The vector V is the set of ODE solution values
V t = V 1 t ,…, V NCODE t T ,
and V. denotes its derivative with respect to time.
In (2), ξ represents a vector of nξ spatial coupling points at which the ODEs are coupled to the PDEs. These points may or may not be equal to some of the PDE spatial mesh points. U*, Ux*, R*, Ut* and U xt* are the functions U, Ux, R, Ut and U xt evaluated at these coupling points. Each Fi may only depend linearly on time derivatives. Hence the equation (2) may be written more precisely as
F=G-A V.-B Ut* U xt* , (3)
where F=F 1,…,FNCODE T, G is a vector of length NCODE, A is an NCODE by NCODE matrix, B is an NCODE by nξ×NPDE matrix and the entries in G, A and B may depend on t, ξ, U*, Ux* and V. In practice you only need to supply a vector of information to define the ODEs and not the matrices A and B. (See Section 5 for the specification of ODEDEF.)
The integration in time is from t 0 to tout, over the space interval a≤x≤b, where a=x 1 and b=xNPTS are the leftmost and rightmost points of a user-defined mesh x 1,x 2,…,xNPTS. The coordinate system in space is defined by the values of m; m=0 for Cartesian coordinates, m=1 for cylindrical polar coordinates and m=2 for spherical polar coordinates.
The PDE system which is defined by the functions P i,j, Qi and Ri must be specified in PDEDEF.
The initial values of the functions U x,t and V t must be given at t=t 0.
The functions Ri which may be thought of as fluxes, are also used in the definition of the boundary conditions. The boundary conditions must have the form
βi x,t Ri x,t,U,Ux,V=γi x,t,U,Ux,V,V.,  i=1,2,…,NPDE, (4)
where x=a or x=b.
The boundary conditions must be specified in BNDARY. The function γi may depend linearly on V..
The problem is subject to the following restrictions:
(i) | In (1), V.j t, for j=1,2,…,NCODE, may only appear linearly in the functions Qi, for i=1,2,…,NPDE, with a similar restriction for γ;
(ii) | P i,j and the flux Ri must not depend on any time derivatives;
(iii) | t 0<tout, so that integration is in the forward direction;
(iv) | the evaluation of the terms P i,j, Qi and Ri is done approximately at the mid-points of the mesh X i, for i=1,2,…,NPTS, by calling the PDEDEF for each mid-point in turn. Any discontinuities in these functions must therefore be at one or more of the mesh points x 1,x 2,…,xNPTS;
(v) | at least one of the functions P i,j must be nonzero so that there is a time derivative present in the PDE problem;
(vi) | if m>0 and x 1=0.0, which is the left boundary point, then it must be ensured that the PDE solution is bounded at this point. This can be done by either specifying the solution at x=0.0 or by specifying a zero flux there, that is βi=1.0 and γi=0.0. See also Section 9 below.
The algebraic-differential equation system which is defined by the functions Fi must be specified in ODEDEF. You must also specify the coupling points ξ in the array XI.
The parabolic equations are approximated by a system of ODEs in time for the values of Ui at mesh points. For simple problems in Cartesian coordinates, this system is obtained by replacing the space derivatives by the usual central, three-point finite difference formula. However, for polar and spherical problems, or problems with nonlinear coefficients, the space derivatives are replaced by a modified three-point formula which maintains second order accuracy. In total there are NPDE×NPTS+NCODE ODEs in the time direction. This system is then integrated forwards in time using a backward differentiation formula (BDF) or a Theta method.

4 References

Berzins M (1990) Developments in the NAG Library software for parabolic equations Scientific Software Systems (eds J C Mason and M G Cox) 59–72 Chapman and Hall
Berzins M, Dew P M and Furzeland R M (1989) Developing software for time-dependent problems using the method of lines and differential-algebraic integrators Appl. Numer. Math. 5 375–397
Berzins M and Furzeland R M (1992) An adaptive theta method for the solution of stiff and nonstiff differential equations Appl. Numer. Math. 9 1–19
Skeel R D and Berzins M (1990) A method for the spatial discretization of parabolic equations in one space variable SIAM J. Sci. Statist. Comput. 11(1) 1–32

5 Arguments

1:   NPDE – INTEGERInput
On entry: the number of PDEs to be solved.
Constraint: NPDE≥1.
2:   M – INTEGERInput
On entry: the coordinate system used:
M=0
Indicates Cartesian coordinates.
M=1
Indicates cylindrical polar coordinates.
M=2
Indicates spherical polar coordinates.
Constraint: M=0, 1 or 2.
3:   TS – REAL (KIND=nag_wp)Input/Output
On entry: the initial value of the independent variable t.
On exit: the value of t corresponding to the solution values in U. Normally TS=TOUT.
Constraint: TS<TOUT.
4:   TOUT – REAL (KIND=nag_wp)Input
On entry: the final value of t to which the integration is to be carried out.
5:   PDEDEF – SUBROUTINE, supplied by the user.External Procedure
PDEDEF must evaluate the functions P i,j, Qi and Ri which define the system of PDEs. The functions may depend on x, t, U, Ux and V. Qi may depend linearly on V.. PDEDEF is called approximately midway between each pair of mesh points in turn by D03PHF/D03PHA.
The specification of PDEDEF for D03PHF is:
SUBROUTINE PDEDEF ( NPDE, T, X, U, UX, NCODE, V, VDOT, P, Q, R, IRES)
INTEGER | NPDE, NCODE, IRES
REAL (KIND=nag_wp) | T, X, U(NPDE), UX(NPDE), V(NCODE), VDOT(NCODE), P(NPDE,NPDE), Q(NPDE), R(NPDE)
The specification of PDEDEF for D03PHA is:
SUBROUTINE PDEDEF ( NPDE, T, X, U, UX, NCODE, V, VDOT, P, Q, R, IRES, IUSER, RUSER)
INTEGER | NPDE, NCODE, IRES, IUSER(*)
REAL (KIND=nag_wp) | T, X, U(NPDE), UX(NPDE), V(NCODE), VDOT(NCODE), P(NPDE,NPDE), Q(NPDE), R(NPDE), RUSER(*)
1:   NPDE – INTEGERInput
On entry: the number of PDEs in the system.
2:   T – REAL (KIND=nag_wp)Input
On entry: the current value of the independent variable t.
3:   X – REAL (KIND=nag_wp)Input
On entry: the current value of the space variable x.
4:   U NPDE – REAL (KIND=nag_wp) arrayInput
On entry: U i contains the value of the component Ui x,t, for i=1,2,…,NPDE.
5:   UX NPDE – REAL (KIND=nag_wp) arrayInput
On entry: UX i contains the value of the component ∂Ui x,t ∂x , for i=1,2,…,NPDE.
6:   NCODE – INTEGERInput
On entry: the number of coupled ODEs in the system.
7:   V NCODE – REAL (KIND=nag_wp) arrayInput
On entry: if NCODE>0, V i contains the value of the component Vi t, for i=1,2,…,NCODE.
8:   VDOT NCODE – REAL (KIND=nag_wp) arrayInput
On entry: if NCODE>0, VDOT i contains the value of component V.i t, for i=1,2,…,NCODE.
Note: V.i t, for i=1,2,…,NCODE, may only appear linearly in Qj, for j=1,2,…,NPDE.
9:   P NPDENPDE – REAL (KIND=nag_wp) arrayOutput
On exit: P ij must be set to the value of P i,j x,t,U,Ux,V, for i=1,2,…,NPDE and j=1,2,…,NPDE.
10:   Q NPDE – REAL (KIND=nag_wp) arrayOutput
On exit: Q i must be set to the value of Qi x,t,U,Ux,V,V., for i=1,2,…,NPDE.
11:   R NPDE – REAL (KIND=nag_wp) arrayOutput
On exit: R i must be set to the value of Ri x,t,U,Ux,V, for i=1,2,…,NPDE.
12:   IRES – INTEGERInput/Output
On entry: set to -1​ or ​1.
On exit: should usually remain unchanged. However, you may set IRES to force the integration routine to take certain actions as described below:
IRES=2
Indicates to the integrator that control should be passed back immediately to the calling (sub)routine with the error indicator set to IFAIL=6.
IRES=3
Indicates to the integrator that the current time step should be abandoned and a smaller time step used instead. You may wish to set IRES=3 when a physically meaningless input or output value has been generated. If you consecutively set IRES=3, then D03PHF/D03PHA returns to the calling subroutine with the error indicator set to IFAIL=4.
Note: the following are additional arguments for specific use with D03PHA. Users of D03PHF therefore need not read the remainder of this description.
13:   IUSER* – INTEGER arrayUser Workspace
14:   RUSER* – REAL (KIND=nag_wp) arrayUser Workspace
PDEDEF is called with the arguments IUSER and RUSER as supplied to D03PHF/D03PHA. You are free to use the arrays IUSER and RUSER to supply information to PDEDEF as an alternative to using COMMON global variables.
PDEDEF must either be a module subprogram USEd by, or declared as EXTERNAL in, the (sub)program from which D03PHF/D03PHA is called. Arguments denoted as Input must not be changed by this procedure.
6:   BNDARY – SUBROUTINE, supplied by the user.External Procedure
BNDARY must evaluate the functions βi and γi which describe the boundary conditions, as given in (4).
The specification of BNDARY for D03PHF is:
SUBROUTINE BNDARY ( NPDE, T, U, UX, NCODE, V, VDOT, IBND, BETA, GAMMA, IRES)
INTEGER | NPDE, NCODE, IBND, IRES
REAL (KIND=nag_wp) | T, U(NPDE), UX(NPDE), V(NCODE), VDOT(NCODE), BETA(NPDE), GAMMA(NPDE)
The specification of BNDARY for D03PHA is:
SUBROUTINE BNDARY ( NPDE, T, U, UX, NCODE, V, VDOT, IBND, BETA, GAMMA, IRES, IUSER, RUSER)
INTEGER | NPDE, NCODE, IBND, IRES, IUSER(*)
REAL (KIND=nag_wp) | T, U(NPDE), UX(NPDE), V(NCODE), VDOT(NCODE), BETA(NPDE), GAMMA(NPDE), RUSER(*)
1:   NPDE – INTEGERInput
On entry: the number of PDEs in the system.
2:   T – REAL (KIND=nag_wp)Input
On entry: the current value of the independent variable t.
3:   U NPDE – REAL (KIND=nag_wp) arrayInput
On entry: U i contains the value of the component Ui x,t at the boundary specified by IBND, for i=1,2,…,NPDE.
4:   UX NPDE – REAL (KIND=nag_wp) arrayInput
On entry: UX i contains the value of the component ∂Ui x,t ∂x at the boundary specified by IBND, for i=1,2,…,NPDE.
5:   NCODE – INTEGERInput
On entry: the number of coupled ODEs in the system.
6:   V NCODE – REAL (KIND=nag_wp) arrayInput
On entry: if NCODE>0, V i contains the value of the component Vi t, for i=1,2,…,NCODE.
7:   VDOT NCODE – REAL (KIND=nag_wp) arrayInput
On entry: if NCODE>0, VDOT i contains the value of component V.i t, for i=1,2,…,NCODE.
Note: V.i t, for i=1,2,…,NCODE, may only appear linearly in Qj, for j=1,2,…,NPDE.
8:   IBND – INTEGERInput
On entry: specifies which boundary conditions are to be evaluated.
IBND=0
BNDARY must set up the coefficients of the left-hand boundary, x=a.
IBND≠0
BNDARY must set up the coefficients of the right-hand boundary, x=b.
9:   BETA NPDE – REAL (KIND=nag_wp) arrayOutput
On exit: BETA i must be set to the value of βi x,t at the boundary specified by IBND, for i=1,2,…,NPDE.
10:   GAMMA NPDE – REAL (KIND=nag_wp) arrayOutput
On exit: GAMMA i must be set to the value of γi x,t,U,Ux,V,V. at the boundary specified by IBND, for i=1,2,…,NPDE.
11:   IRES – INTEGERInput/Output
On entry: set to -1​ or ​1.
On exit: should usually remain unchanged. However, you may set IRES to force the integration routine to take certain actions as described below:
IRES=2
Indicates to the integrator that control should be passed back immediately to the calling (sub)routine with the error indicator set to IFAIL=6.
IRES=3
Indicates to the integrator that the current time step should be abandoned and a smaller time step used instead. You may wish to set IRES=3 when a physically meaningless input or output value has been generated. If you consecutively set IRES=3, then D03PHF/D03PHA returns to the calling subroutine with the error indicator set to IFAIL=4.
Note: the following are additional arguments for specific use with D03PHA. Users of D03PHF therefore need not read the remainder of this description.
12:   IUSER* – INTEGER arrayUser Workspace
13:   RUSER* – REAL (KIND=nag_wp) arrayUser Workspace
BNDARY is called with the arguments IUSER and RUSER as supplied to D03PHF/D03PHA. You are free to use the arrays IUSER and RUSER to supply information to BNDARY as an alternative to using COMMON global variables.
BNDARY must either be a module subprogram USEd by, or declared as EXTERNAL in, the (sub)program from which D03PHF/D03PHA is called. Arguments denoted as Input must not be changed by this procedure.
7:   U NEQN – REAL (KIND=nag_wp) arrayInput/Output
On entry: the initial values of the dependent variables defined as follows:
  • U NPDE×j-1+i contain Ui xj,t 0, for i=1,2,…,NPDE and j=1,2,…,NPTS, and
  • U NPTS×NPDE+i contain Vi t 0, for i=1,2,…,NCODE.
On exit: the computed solution Ui xj,t, for i=1,2,…,NPDE and j=1,2,…,NPTS, and Vk t, for k=1,2,…,NCODE, evaluated at t=TS.
8:   NPTS – INTEGERInput
On entry: the number of mesh points in the interval a,b.
Constraint: NPTS≥3.
9:   X NPTS – REAL (KIND=nag_wp) arrayInput
On entry: the mesh points in the space direction. X 1 must specify the left-hand boundary, a, and X NPTS must specify the right-hand boundary, b.
Constraint: X 1<X 2<⋯<X NPTS.
10:   NCODE – INTEGERInput
On entry: the number of coupled ODE components.
Constraint: NCODE≥0.
11:   ODEDEF – SUBROUTINE, supplied by the NAG Library or the user.External Procedure
ODEDEF must evaluate the functions F, which define the system of ODEs, as given in (3).
If you wish to compute the solution of a system of PDEs only (NCODE=0), ODEDEF must be the dummy routine D03PCK for D03PHF (or D53PCK for D03PHA). D03PCK and D53PCK are included in the NAG Library.
The specification of ODEDEF for D03PHF is:
SUBROUTINE ODEDEF ( NPDE, T, NCODE, V, VDOT, NXI, XI, UCP, UCPX, RCP, UCPT, UCPTX, F, IRES)
INTEGER | NPDE, NCODE, NXI, IRES
REAL (KIND=nag_wp) | T, V(NCODE), VDOT(NCODE), XI(NXI), UCP(NPDE,*), UCPX(NPDE,*), RCP(NPDE,*), UCPT(NPDE,*), UCPTX(NPDE,*), F(NCODE)
The specification of ODEDEF for D03PHA is:
SUBROUTINE ODEDEF ( NPDE, T, NCODE, V, VDOT, NXI, XI, UCP, UCPX, RCP, UCPT, UCPTX, F, IRES, IUSER, RUSER)
INTEGER | NPDE, NCODE, NXI, IRES, IUSER(*)
REAL (KIND=nag_wp) | T, V(NCODE), VDOT(NCODE), XI(NXI), UCP(NPDE,*), UCPX(NPDE,*), RCP(NPDE,*), UCPT(NPDE,*), UCPTX(NPDE,*), F(NCODE), RUSER(*)
1:   NPDE – INTEGERInput
On entry: the number of PDEs in the system.
2:   T – REAL (KIND=nag_wp)Input
On entry: the current value of the independent variable t.
3:   NCODE – INTEGERInput
On entry: the number of coupled ODEs in the system.
4:   V NCODE – REAL (KIND=nag_wp) arrayInput
On entry: if NCODE>0, V i contains the value of the component Vi t, for i=1,2,…,NCODE.
5:   VDOT NCODE – REAL (KIND=nag_wp) arrayInput
On entry: if NCODE>0, VDOT i contains the value of component V.i t, for i=1,2,…,NCODE.
6:   NXI – INTEGERInput
On entry: the number of ODE/PDE coupling points.
7:   XI NXI – REAL (KIND=nag_wp) arrayInput
On entry: if NXI>0, XI i contains the ODE/PDE coupling points, ξi, for i=1,2,…,NXI.
8:   UCP NPDE* – REAL (KIND=nag_wp) arrayInput
On entry: if NXI>0, UCP ij contains the value of Ui x,t at the coupling point x=ξj, for i=1,2,…,NPDE and j=1,2,…,NXI.
9:   UCPX NPDE* – REAL (KIND=nag_wp) arrayInput
On entry: if NXI>0, UCPX ij contains the value of ∂Ui x,t ∂x at the coupling point x=ξj, for i=1,2,…,NPDE and j=1,2,…,NXI.
10:   RCP NPDE* – REAL (KIND=nag_wp) arrayInput
On entry: RCP ij contains the value of the flux Ri at the coupling point x=ξj, for i=1,2,…,NPDE and j=1,2,…,NXI.
11:   UCPT NPDE* – REAL (KIND=nag_wp) arrayInput
On entry: if NXI>0, UCPT ij contains the value of ∂Ui ∂t at the coupling point x=ξj, for i=1,2,…,NPDE and j=1,2,…,NXI.
12:   UCPTX NPDE* – REAL (KIND=nag_wp) arrayInput
On entry: UCPTX ij contains the value of ∂2 Ui ∂x ∂t at the coupling point x=ξj, for i=1,2,…,NPDE and j=1,2,…,NXI.
13:   F NCODE – REAL (KIND=nag_wp) arrayOutput
On exit: F i must contain the ith component of F, for i=1,2,…,NCODE, where F is defined as
F=G-A V.-B Ut* U xt* , (5)
or
F=-A V.-B Ut* U xt* . (6)
The definition of F is determined by the input value of IRES.
14:   IRES – INTEGERInput/Output
On entry: the form of F that must be returned in the array F.
IRES=1
Equation (5) must be used.
IRES=-1
Equation (6) must be used.
On exit: should usually remain unchanged. However, you may reset IRES to force the integration routine to take certain actions as described below:
IRES=2
Indicates to the integrator that control should be passed back immediately to the calling (sub)routine with the error indicator set to IFAIL=6.
IRES=3
Indicates to the integrator that the current time step should be abandoned and a smaller time step used instead. You may wish to set IRES=3 when a physically meaningless input or output value has been generated. If you consecutively set IRES=3, then D03PHF/D03PHA returns to the calling subroutine with the error indicator set to IFAIL=4.
Note: the following are additional arguments for specific use with D03PHA. Users of D03PHF therefore need not read the remainder of this description.
15:   IUSER* – INTEGER arrayUser Workspace
16:   RUSER* – REAL (KIND=nag_wp) arrayUser Workspace
ODEDEF is called with the arguments IUSER and RUSER as supplied to D03PHF/D03PHA. You are free to use the arrays IUSER and RUSER to supply information to ODEDEF as an alternative to using COMMON global variables.
ODEDEF must either be a module subprogram USEd by, or declared as EXTERNAL in, the (sub)program from which D03PHF/D03PHA is called. Arguments denoted as Input must not be changed by this procedure.
12:   NXI – INTEGERInput
On entry: the number of ODE/PDE coupling points.
Constraints:
  • if NCODE=0, NXI=0;
  • if NCODE>0, NXI≥0.
13:   XI NXI – REAL (KIND=nag_wp) arrayInput
On entry: if NXI>0, XI i, for i=1,2,…,NXI, must be set to the ODE/PDE coupling points.
Constraint: X 1≤XI 1<XI 2<⋯<XI NXI≤X NPTS.
14:   NEQN – INTEGERInput
On entry: the number of ODEs in the time direction.
Constraint: NEQN=NPDE×NPTS+NCODE.
15:   RTOL* – REAL (KIND=nag_wp) arrayInput
Note: the dimension of the array RTOL must be at least 1 if ITOL=1 or 2 and at least NEQN if ITOL=3 or 4.
On entry: the relative local error tolerance.
Constraint: RTOL i≥0.0 for all relevant i.
16:   ATOL* – REAL (KIND=nag_wp) arrayInput
Note: the dimension of the array ATOL must be at least 1 if ITOL=1 or 3 and at least NEQN if ITOL=2 or 4.
On entry: the absolute local error tolerance.
Constraint: ATOL i≥0.0 for all relevant i.
Note: corresponding elements of RTOL and ATOL cannot both be 0.0.
17:   ITOL – INTEGERInput
On entry: a value to indicate the form of the local error test. ITOL indicates to D03PHF/D03PHA whether to interpret either or both of RTOL or ATOL as a vector or scalar. The error test to be satisfied is ei/wi<1.0, where wi is defined as follows:
ITOL | RTOL | ATOL | wi
1 | scalar | scalar | RTOL 1×Ui+ATOL 1
2 | scalar | vector | RTOL 1×Ui+ATOL i
3 | vector | scalar | RTOL i×Ui+ATOL 1
4 | vector | vector | RTOL i×Ui+ATOL i
In the above, ei denotes the estimated local error for the ith component of the coupled PDE/ODE system in time, U i, for i=1,2,…,NEQN.
The choice of norm used is defined by the argument NORM.
Constraint: 1≤ITOL≤4.
18:   NORM – CHARACTER(1)Input
On entry: the type of norm to be used.
NORM='M'
Maximum norm.
NORM='A'
Averaged L 2 norm.
If Unorm denotes the norm of the vector U of length NEQN, then for the averaged L 2 norm
Unorm=1 NEQN∑i=1 NEQN U i/wi 2,
while for the maximum norm
U norm = maxi U i / wi .
See the description of ITOL for the formulation of the weight vector w.
Constraint: NORM='M' or 'A'.
19:   LAOPT – CHARACTER(1)Input
On entry: the type of matrix algebra required.
LAOPT='F'
Full matrix methods to be used.
LAOPT='B'
Banded matrix methods to be used.
LAOPT='S'
Sparse matrix methods to be used.
Constraint: LAOPT='F', 'B' or 'S'.
Note: you are recommended to use the banded option when no coupled ODEs are present (i.e., NCODE=0).
20:   ALGOPT 30 – REAL (KIND=nag_wp) arrayInput
On entry: may be set to control various options available in the integrator. If you wish to employ all the default options, then ALGOPT 1 should be set to 0.0. Default values will also be used for any other elements of ALGOPT set to zero. The permissible values, default values, and meanings are as follows:
ALGOPT 1
Selects the ODE integration method to be used. If ALGOPT 1=1.0, a BDF method is used and if ALGOPT 1=2.0, a Theta method is used. The default value is ALGOPT 1=1.0.
If ALGOPT 1=2.0, then ALGOPT i, for i=2,3,4 are not used.
ALGOPT 2
Specifies the maximum order of the BDF integration formula to be used. ALGOPT 2 may be 1.0, 2.0, 3.0, 4.0 or 5.0. The default value is ALGOPT 2=5.0.
ALGOPT 3
Specifies what method is to be used to solve the system of nonlinear equations arising on each step of the BDF method. If ALGOPT 3=1.0 a modified Newton iteration is used and if ALGOPT 3=2.0 a functional iteration method is used. If functional iteration is selected and the integrator encounters difficulty, then there is an automatic switch to the modified Newton iteration. The default value is ALGOPT 3=1.0.
ALGOPT 4
Specifies whether or not the Petzold error test is to be employed. The Petzold error test results in extra overhead but is more suitable when algebraic equations are present, such as P i,j=0.0, for j=1,2,…,NPDE, for some i or when there is no V.i t dependence in the coupled ODE system. If ALGOPT 4=1.0, then the Petzold test is used. If ALGOPT 4=2.0, then the Petzold test is not used. The default value is ALGOPT 4=1.0.
If ALGOPT 1=1.0, then ALGOPT i, for i=5,6,7, are not used.
ALGOPT 5
Specifies the value of Theta to be used in the Theta integration method. 0.51≤ALGOPT 5≤0.99. The default value is ALGOPT 5=0.55.
ALGOPT 6
Specifies what method is to be used to solve the system of nonlinear equations arising on each step of the Theta method. If ALGOPT 6=1.0, a modified Newton iteration is used and if ALGOPT 6=2.0, a functional iteration method is used. The default value is ALGOPT 6=1.0.
ALGOPT 7
Specifies whether or not the integrator is allowed to switch automatically between modified Newton and functional iteration methods in order to be more efficient. If ALGOPT 7=1.0, then switching is allowed and if ALGOPT 7=2.0, then switching is not allowed. The default value is ALGOPT 7=1.0.
ALGOPT 11
Specifies a point in the time direction, tcrit, beyond which integration must not be attempted. The use of tcrit is described under the argument ITASK. If ALGOPT 1≠0.0, a value of 0.0 for ALGOPT 11, say, should be specified even if ITASK subsequently specifies that tcrit will not be used.
ALGOPT 12
Specifies the minimum absolute step size to be allowed in the time integration. If this option is not required, ALGOPT 12 should be set to 0.0.
ALGOPT 13
Specifies the maximum absolute step size to be allowed in the time integration. If this option is not required, ALGOPT 13 should be set to 0.0.
ALGOPT 14
Specifies the initial step size to be attempted by the integrator. If ALGOPT 14=0.0, then the initial step size is calculated internally.
ALGOPT 15
Specifies the maximum number of steps to be attempted by the integrator in any one call. If ALGOPT 15=0.0, then no limit is imposed.
ALGOPT 23
Specifies what method is to be used to solve the nonlinear equations at the initial point to initialize the values of U, Ut, V and V.. If ALGOPT 23=1.0, a modified Newton iteration is used and if ALGOPT 23=2.0, functional iteration is used. The default value is ALGOPT 23=1.0.
ALGOPT 29 and ALGOPT 30 are used only for the sparse matrix algebra option, LAOPT='S'.
ALGOPT 29
Governs the choice of pivots during the decomposition of the first Jacobian matrix. It should lie in the range 0.0<ALGOPT 29<1.0, with smaller values biasing the algorithm towards maintaining sparsity at the expense of numerical stability. If ALGOPT 29 lies outside this range then the default value is used. If the routines regard the Jacobian matrix as numerically singular then increasing ALGOPT 29 towards 1.0 may help, but at the cost of increased fill-in. The default value is ALGOPT 29=0.1.
ALGOPT 30
Is used as a relative pivot threshold during subsequent Jacobian decompositions (see ALGOPT 29) below which an internal error is invoked. If ALGOPT 30 is greater than 1.0 no check is made on the pivot size, and this may be a necessary option if the Jacobian is found to be numerically singular (see ALGOPT 29). The default value is ALGOPT 30=0.0001.
21:   RSAVE LRSAVE – REAL (KIND=nag_wp) arrayCommunication Array
If IND=0, RSAVE need not be set on entry.
If IND=1, RSAVE must be unchanged from the previous call to the routine because it contains required information about the iteration.
22:   LRSAVE – INTEGERInput
On entry: the dimension of the array RSAVE as declared in the (sub)program from which D03PHF/D03PHA is called.
Constraint:
If LAOPT='F', LRSAVE≥NEQN×NEQN+NEQN+nwkres+lenode.
If LAOPT='B', LRSAVE≥3×mlu+1×NEQN+nwkres+lenode.
If LAOPT='S', LRSAVE≥4×NEQN+11×NEQN/2+1+nwkres+lenode.
Where
mlu is the lower or upper half bandwidths such that
mlu=3×NPDE-1, for PDE problems only (no coupled ODEs); or
mlu=NEQN-1, for coupled PDE/ODE problems.
nwkres= NPDE×2×NPTS+6×NXI+3×NPDE+26+NXI+NCODE+7×NPTS+2, when ​NCODE>0​ and ​NXI>0; NPDE×2×NPTS+3×NPDE+32+NCODE+7×NPTS+3, when ​NCODE>0​ and ​NXI=0; NPDE×2×NPTS+3×NPDE+32+7×NPTS+4, when ​NCODE=0.
lenode= 6+int ALGOPT 2×NEQN+50, when the BDF method is used; or 9×NEQN+50, when the Theta method is used.
Note: when LAOPT='S', the value of LRSAVE may be too small when supplied to the integrator. An estimate of the minimum size of LRSAVE is printed on the current error message unit if ITRACE>0 and the routine returns with IFAIL=15.
.
23:   ISAVE LISAVE – INTEGER arrayCommunication Array
If IND=0, ISAVE need not be set on entry.
If IND=1, ISAVE must be unchanged from the previous call to the routine because it contains required information about the iteration. In particular:
ISAVE 1
Contains the number of steps taken in time.
ISAVE 2
Contains the number of residual evaluations of the resulting ODE system used. One such evaluation involves computing the PDE functions at all the mesh points, as well as one evaluation of the functions in the boundary conditions.
ISAVE 3
Contains the number of Jacobian evaluations performed by the time integrator.
ISAVE 4
Contains the order of the last backward differentiation formula method used.
ISAVE 5
Contains the number of Newton iterations performed by the time integrator. Each iteration involves an ODE residual evaluation followed by a back-substitution using the LU decomposition of the Jacobian matrix.
24:   LISAVE – INTEGERInput
On entry: the dimension of the array ISAVE as declared in the (sub)program from which D03PHF/D03PHA is called. Its size depends on the type of matrix algebra selected:
  • if LAOPT='F', LISAVE≥24;
  • if LAOPT='B', LISAVE≥NEQN+24;
  • if LAOPT='S', LISAVE≥25×NEQN+24.
Note: when using the sparse option, the value of LISAVE may be too small when supplied to the integrator. An estimate of the minimum size of LISAVE is printed on the current error message unit if ITRACE>0 and the routine returns with IFAIL=15.
25:   ITASK – INTEGERInput
On entry: specifies the task to be performed by the ODE integrator.
ITASK=1
Normal computation of output values U at t=TOUT.
ITASK=2
One step and return.
ITASK=3
Stop at first internal integration point at or beyond t=TOUT.
ITASK=4
Normal computation of output values U at t=TOUT but without overshooting t=tcrit where tcrit is described under the argument ALGOPT.
ITASK=5
Take one step in the time direction and return, without passing tcrit, where tcrit is described under the argument ALGOPT.
Constraint: ITASK=1, 2, 3, 4 or 5.
26:   ITRACE – INTEGERInput
On entry: the level of trace information required from D03PHF/D03PHA and the underlying ODE solver. ITRACE may take the value -1, 0, 1, 2 or 3.
ITRACE=-1
No output is generated.
ITRACE=0
Only warning messages from the PDE solver are printed on the current error message unit (see X04AAF).
ITRACE>0
Output from the underlying ODE solver is printed on the current advisory message unit (see X04ABF). This output contains details of Jacobian entries, the nonlinear iteration and the time integration during the computation of the ODE system.
If ITRACE<-1, then -1 is assumed and similarly if ITRACE>3, then 3 is assumed.
The advisory messages are given in greater detail as ITRACE increases. You are advised to set ITRACE=0, unless you are experienced with Sub-chapter D02M–N.
27:   IND – INTEGERInput/Output
On entry: indicates whether this is a continuation call or a new integration.
IND=0
Starts or restarts the integration in time.
IND=1
Continues the integration after an earlier exit from the routine. In this case, only the arguments TOUT and IFAIL should be reset between calls to D03PHF/D03PHA.
Constraint: IND=0 or 1.
On exit: IND=1.
28:   IFAIL – INTEGERInput/Output
Note: for D03PHA, IFAIL does not occur in this position in the argument list. See the additional arguments described below.
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).
Note: the following are additional arguments for specific use with D03PHA. Users of D03PHF therefore need not read the remainder of this description.
28:   IUSER* – INTEGER arrayUser Workspace
29:   RUSER* – REAL (KIND=nag_wp) arrayUser Workspace
IUSER and RUSER are not used by D03PHF/D03PHA, but are passed directly to PDEDEF, BNDARY and ODEDEF and may be used to pass information to these routines as an alternative to using COMMON global variables.
30:   CWSAV 10 – CHARACTER(80) arrayCommunication Array
31:   LWSAV 100 – LOGICAL arrayCommunication Array
32:   IWSAV 505 – INTEGER arrayCommunication Array
33:   RWSAV 1100 – REAL (KIND=nag_wp) arrayCommunication Array
34:   IFAIL – INTEGERInput/Output
Note: see the argument description for IFAIL above.

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, | TOUT-TS is too small,
or | ITASK≠1, 2, 3, 4 or 5,
or | M≠0, 1 or 2,
or | at least one of the coupling points defined in array XI is outside the interval [X 1,X NPTS],
or | M>0 and X 1<0.0,
or | NPTS<3,
or | NPDE<1,
or | NORM≠'A' or 'M',
or | LAOPT≠'F', 'B' or 'S',
or | ITOL≠1, 2, 3 or 4,
or | IND≠0 or 1,
or | mesh points X i are badly ordered,
or | LRSAVE is too small,
or | LISAVE is too small,
or | NCODE and NXI are incorrectly defined,
or | NEQN≠NPDE×NPTS+NCODE,
or | either an element of RTOL or ATOL<0.0,
or | all the elements of RTOL and ATOL are zero.
IFAIL=2
The underlying ODE solver cannot make any further progress, with the values of ATOL and RTOL, across the integration range from the current point t=TS. The components of U contain the computed values at the current point t=TS.
IFAIL=3
In the underlying ODE solver, there were repeated error test failures on an attempted step, before completing the requested task, but the integration was successful as far as t=TS. The problem may have a singularity, or the error requirement may be inappropriate.
IFAIL=4
In setting up the ODE system, the internal initialization routine was unable to initialize the derivative of the ODE system. This could be due to the fact that IRES was repeatedly set to 3 in at least PDEDEF, BNDARY or ODEDEF, when the residual in the underlying ODE solver was being evaluated.
IFAIL=5
In solving the ODE system, a singular Jacobian has been encountered. You should check your problem formulation.
IFAIL=6
When evaluating the residual in solving the ODE system, IRES was set to 2 in at least PDEDEF, BNDARY or ODEDEF. Integration was successful as far as t=TS.
IFAIL=7
The values of ATOL and RTOL are so small that the routine is unable to start the integration in time.
IFAIL=8
In one of PDEDEF, BNDARY or ODEDEF, IRES was set to an invalid value.
IFAIL=9 (D02NNF)
A serious error has occurred in an internal call to the specified routine. Check the problem specification and all arguments and array dimensions. Setting ITRACE=1 may provide more information. If the problem persists, contact NAG.
IFAIL=10
The required task has been completed, but it is estimated that a small change in ATOL and RTOL is unlikely to produce any change in the computed solution. (Only applies when you are not operating in one step mode, that is when ITASK≠2 or 5.)
IFAIL=11
An error occurred during Jacobian formulation of the ODE system (a more detailed error description may be directed to the current error message unit). If using the sparse matrix algebra option, the values of ALGOPT 29 and ALGOPT 30 may be inappropriate.
IFAIL=12
In solving the ODE system, the maximum number of steps specified in ALGOPT 15 have been taken.
IFAIL=13
Some error weights wi became zero during the time integration (see the description of ITOL). Pure relative error control (ATOL i=0.0) was requested on a variable (the ith) which has become zero. The integration was successful as far as t=TS.
IFAIL=14
The flux function Ri was detected as depending on time derivatives, which is not permissible.
IFAIL=15
When using the sparse option, the value of LISAVE or LRSAVE was not sufficient (more detailed information may be directed to the current error message unit).
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

D03PHF/D03PHA controls the accuracy of the integration in the time direction but not the accuracy of the approximation in space. The spatial accuracy depends on both the number of mesh points and on their distribution in space. In the time integration only the local error over a single step is controlled and so the accuracy over a number of steps cannot be guaranteed. You should therefore test the effect of varying the accuracy arguments ATOL and RTOL.

8 Parallelism and Performance

D03PHF/D03PHA is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
D03PHF/D03PHA makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The argument specification allows you to include equations with only first-order derivatives in the space direction but there is no guarantee that the method of integration will be satisfactory for such systems. The position and nature of the boundary conditions in particular are critical in defining a stable problem. It may be advisable in such cases to reduce the whole system to first-order and to use the Keller box scheme routine D03PKF.
The time taken depends on the complexity of the parabolic system and on the accuracy requested. For a given system and a fixed accuracy it is approximately proportional to NEQN.

10 Example

This example provides a simple coupled system of one PDE and one ODE.
V 1 2 ∂ U 1 ∂ t - x V 1 V . 1 ∂ U 1 ∂ x = ∂ 2 y U 1 ∂ x 2 V . 1 = V 1 U 1 + ∂ U 1 ∂ x + 1 + t ,
for t∈10-4,0.1×2 i ; i=1,2,…,5 ; x∈0,1 .
The left boundary condition at x=0 is
∂U 1 ∂x =-V 1 exp⁡t.
The right boundary condition at x=1 is
∂U 1 ∂x = -V 1 V.1 .
The initial conditions at t=10-4 are defined by the exact solution:
V 1 = t ,   and   U 1 x,t = exp t 1-x - 1.0 , x∈0,1 ,
and the coupling point is at ξ 1=1.0.

10.1 Program Text

Note: the following programs illustrate the use of D03PHF and D03PHA.

Program Text (d03phfe.f90)

Program Text (d03phae.f90)

10.2 Program Data

Program Data (d03phfe.d)

Program Data (d03phae.d)

10.3 Program Results

Program Results (d03phfe.r)

Program Results (d03phae.r)

GnuplotProduced by GNUPLOT 5.0 patchlevel 0 Example Program Parabolic PDE Coupled with ODE using Finite-differences and BDF U(x,t) gnuplot_plot_1 gnuplot_plot_2 0.1 0.5 1 2 3 Time (logscale) 0 0.2 0.4 0.6 0.8 1 x 0 5 10 15 20 25
D03 Chapter Contents
D03 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


D03PJF/D03PJA : NAG Library, Mark 26

D03 Chapter Contents
D03 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

D03PJF/D03PJA

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
▸▿ 2 Specification
2.1 Specification for D03PJF
2.2 Specification for D03PJA
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

D03PJF/D03PJA integrates a system of linear or nonlinear parabolic partial differential equations (PDEs), in one space variable with scope for coupled ordinary differential equations (ODEs). The spatial discretization is performed using a Chebyshev C 0 collocation method, and the method of lines is employed to reduce the PDEs to a system of ODEs. The resulting system is solved using a backward differentiation formula (BDF) method or a Theta method (switching between Newton's method and functional iteration).
D03PJA is a version of D03PJF that has additional arguments in order to make it safe for use in multithreaded applications (see Section 5).

2 Specification

2.1 Specification for D03PJF

SUBROUTINE D03PJF ( NPDE, M, TS, TOUT, PDEDEF, BNDARY, U, NBKPTS, XBKPTS, NPOLY, NPTS, X, NCODE, ODEDEF, NXI, XI, NEQN, UVINIT, RTOL, ATOL, ITOL, NORM, LAOPT, ALGOPT, RSAVE, LRSAVE, ISAVE, LISAVE, ITASK, ITRACE, IND, IFAIL)
INTEGER | NPDE, M, NBKPTS, NPOLY, NPTS, NCODE, NXI, NEQN, ITOL, LRSAVE, ISAVE(LISAVE), LISAVE, ITASK, ITRACE, IND, IFAIL
REAL (KIND=nag_wp) | TS, TOUT, U(NEQN), XBKPTS(NBKPTS), X(NPTS), XI(*), RTOL(*), ATOL(*), ALGOPT(30), RSAVE(LRSAVE)
CHARACTER(1) | NORM, LAOPT
EXTERNAL | PDEDEF, BNDARY, ODEDEF, UVINIT

2.2 Specification for D03PJA

SUBROUTINE D03PJA ( NPDE, M, TS, TOUT, PDEDEF, BNDARY, U, NBKPTS, XBKPTS, NPOLY, NPTS, X, NCODE, ODEDEF, NXI, XI, NEQN, UVINIT, RTOL, ATOL, ITOL, NORM, LAOPT, ALGOPT, RSAVE, LRSAVE, ISAVE, LISAVE, ITASK, ITRACE, IND, IUSER, RUSER, CWSAV, LWSAV, IWSAV, RWSAV, IFAIL)
INTEGER | NPDE, M, NBKPTS, NPOLY, NPTS, NCODE, NXI, NEQN, ITOL, LRSAVE, ISAVE(LISAVE), LISAVE, ITASK, ITRACE, IND, IUSER(*), IWSAV(505), IFAIL
REAL (KIND=nag_wp) | TS, TOUT, U(NEQN), XBKPTS(NBKPTS), X(NPTS), XI(*), RTOL(*), ATOL(*), ALGOPT(30), RSAVE(LRSAVE), RUSER(*), RWSAV(1100)
LOGICAL | LWSAV(100)
CHARACTER(1) | NORM, LAOPT
CHARACTER(80) | CWSAV(10)
EXTERNAL | PDEDEF, BNDARY, ODEDEF, UVINIT

3 Description

D03PJF/D03PJA integrates the system of parabolic-elliptic equations and coupled ODEs
∑j=1 NPDE P i,j ∂Uj ∂t +Qi=x-m ∂∂x xm Ri,  i=1,2,…,NPDE,  a≤x≤b,t≥t 0, (1)
Fi t,V,V.,ξ,U*,Ux*,R*,Ut*,U xt*=0,  i=1,2,…,NCODE, (2)
where (1) defines the PDE part and (2) generalizes the coupled ODE part of the problem.
In (1), P i,j and Ri depend on x, t, U, Ux, and V; Qi depends on x, t, U, Ux, V and linearly on V.. The vector U is the set of PDE solution values
U x,t = U 1 x,t ,…, U NPDE x,t T ,
and the vector Ux is the partial derivative with respect to x. Note that P i,j, Qi and Ri must not depend on ∂U ∂t . The vector V is the set of ODE solution values
V t=V 1 t,…,VNCODE t T,
and V. denotes its derivative with respect to time.
In (2), ξ represents a vector of nξ spatial coupling points at which the ODEs are coupled to the PDEs. These points may or may not be equal to some of the PDE spatial mesh points. U*, Ux*, R*, Ut* and U xt* are the functions U, Ux, R, Ut and U xt evaluated at these coupling points. Each Fi may only depend linearly on time derivatives. Hence the equation (2) may be written more precisely as
F=G-A V.-B Ut* U xt* , (3)
where F = F 1,…,FNCODE T , G is a vector of length NCODE, A is an NCODE by NCODE matrix, B is an NCODE by nξ×NPDE matrix and the entries in G, A and B may depend on t, ξ, U*, Ux* and V. In practice you need only supply a vector of information to define the ODEs and not the matrices A and B. (See Section 5 for the specification of ODEDEF.)
The integration in time is from t 0 to tout, over the space interval a≤x≤b, where a=x 1 and b=xNBKPTS are the leftmost and rightmost of a user-defined set of break-points x 1,x 2,…,xNBKPTS. The coordinate system in space is defined by the value of m; m=0 for Cartesian coordinates, m=1 for cylindrical polar coordinates and m=2 for spherical polar coordinates.
The PDE system which is defined by the functions P i,j, Qi and Ri must be specified in PDEDEF.
The initial values of the functions U x,t and V t must be given at t=t 0. These values are calculated in UVINIT.
The functions Ri which may be thought of as fluxes, are also used in the definition of the boundary conditions. The boundary conditions must have the form
βi x,t Ri x,t,U,Ux,V=γi x,t,U,Ux,V,V.,  i=1,2,…,NPDE, (4)
where x=a or x=b. The functions γi may only depend linearly on V..
The boundary conditions must be specified in BNDARY.
The algebraic-differential equation system which is defined by the functions Fi must be specified in ODEDEF. You must also specify the coupling points ξ in the array XI. Thus, the problem is subject to the following restrictions:
(i) | in (1), V.j t, for j=1,2,…,NCODE, may only appear linearly in the functions Qi, for i=1,2,…,NPDE, with a similar restriction for γ;
(ii) | P i,j and the flux Ri must not depend on any time derivatives;
(iii) | t 0<tout, so that integration is in the forward direction;
(iv) | the evaluation of the functions P i,j, Qi and Ri is done at both the break-points and internally selected points for each element in turn, that is P i,j, Qi and Ri are evaluated twice at each break-point. Any discontinuities in these functions must therefore be at one or more of the mesh points;
(v) | at least one of the functions P i,j must be nonzero so that there is a time derivative present in the PDE problem;
(vi) | if m>0 and x 1=0.0, which is the left boundary point, then it must be ensured that the PDE solution is bounded at this point. This can be done either by specifying the solution at x=0.0 or by specifying a zero flux there, that is βi=1.0 and γi=0.0.
The parabolic equations are approximated by a system of ODEs in time for the values of Ui at the mesh points. This ODE system is obtained by approximating the PDE solution between each pair of break-points by a Chebyshev polynomial of degree NPOLY. The interval between each pair of break-points is treated by D03PJF/D03PJA as an element, and on this element, a polynomial and its space and time derivatives are made to satisfy the system of PDEs at NPOLY-1 spatial points, which are chosen internally by the code and the break-points. The user-defined break-points and the internally selected points together define the mesh. The smallest value that NPOLY can take is one, in which case, the solution is approximated by piecewise linear polynomials between consecutive break-points and the method is similar to an ordinary finite element method.
In total there are NBKPTS-1×NPOLY+1 mesh points in the spatial direction, and NPDE×NBKPTS-1×NPOLY+1+NCODE ODEs in the time direction; one ODE at each break-point for each PDE component, NPOLY-1 ODEs for each PDE component between each pair of break-points, and NCODE coupled ODEs. The system is then integrated forwards in time using a Backward Differentiation Formula (BDF) method or a Theta method.

4 References

Berzins M (1990) Developments in the NAG Library software for parabolic equations Scientific Software Systems (eds J C Mason and M G Cox) 59–72 Chapman and Hall
Berzins M and Dew P M (1991) Algorithm 690: Chebyshev polynomial software for elliptic-parabolic systems of PDEs ACM Trans. Math. Software 17 178–206
Berzins M, Dew P M and Furzeland R M (1988) Software tools for time-dependent equations in simulation and optimization of large systems Proc. IMA Conf. Simulation and Optimization (ed A J Osiadcz) 35–50 Clarendon Press, Oxford
Berzins M and Furzeland R M (1992) An adaptive theta method for the solution of stiff and nonstiff differential equations Appl. Numer. Math. 9 1–19
Zaturska N B, Drazin P G and Banks W H H (1988) On the flow of a viscous fluid driven along a channel by a suction at porous walls Fluid Dynamics Research 4

5 Arguments

1:   NPDE – INTEGERInput
On entry: the number of PDEs to be solved.
Constraint: NPDE≥1.
2:   M – INTEGERInput
On entry: the coordinate system used:
M=0
Indicates Cartesian coordinates.
M=1
Indicates cylindrical polar coordinates.
M=2
Indicates spherical polar coordinates.
Constraint: M=0, 1 or 2.
3:   TS – REAL (KIND=nag_wp)Input/Output
On entry: the initial value of the independent variable t.
On exit: the value of t corresponding to the solution values in U. Normally TS=TOUT.
Constraint: TS<TOUT.
4:   TOUT – REAL (KIND=nag_wp)Input
On entry: the final value of t to which the integration is to be carried out.
5:   PDEDEF – SUBROUTINE, supplied by the user.External Procedure
PDEDEF must compute the functions P i,j, Qi and Ri which define the system of PDEs. The functions may depend on x, t, U, Ux and V; Qi may depend linearly on V.. The functions must be evaluated at a set of points.
The specification of PDEDEF for D03PJF is:
SUBROUTINE PDEDEF ( NPDE, T, X, NPTL, U, UX, NCODE, V, VDOT, P, Q, R, IRES)
INTEGER | NPDE, NPTL, NCODE, IRES
REAL (KIND=nag_wp) | T, X(NPTL), U(NPDE,NPTL), UX(NPDE,NPTL), V(NCODE), VDOT(NCODE), P(NPDE,NPDE,NPTL), Q(NPDE,NPTL), R(NPDE,NPTL)
The specification of PDEDEF for D03PJA is:
SUBROUTINE PDEDEF ( NPDE, T, X, NPTL, U, UX, NCODE, V, VDOT, P, Q, R, IRES, IUSER, RUSER)
INTEGER | NPDE, NPTL, NCODE, IRES, IUSER(*)
REAL (KIND=nag_wp) | T, X(NPTL), U(NPDE,NPTL), UX(NPDE,NPTL), V(NCODE), VDOT(NCODE), P(NPDE,NPDE,NPTL), Q(NPDE,NPTL), R(NPDE,NPTL), RUSER(*)
1:   NPDE – INTEGERInput
On entry: the number of PDEs in the system.
2:   T – REAL (KIND=nag_wp)Input
On entry: the current value of the independent variable t.
3:   X NPTL – REAL (KIND=nag_wp) arrayInput
On entry: contains a set of mesh points at which P i,j, Qi and Ri are to be evaluated. X 1 and X NPTL contain successive user-supplied break-points and the elements of the array will satisfy X 1<X 2<⋯<X NPTL.
4:   NPTL – INTEGERInput
On entry: the number of points at which evaluations are required (the value of NPOLY+1).
5:   U NPDENPTL – REAL (KIND=nag_wp) arrayInput
On entry: U ij contains the value of the component Ui x,t where x=X j, for i=1,2,…,NPDE and j=1,2,…,NPTL.
6:   UX NPDENPTL – REAL (KIND=nag_wp) arrayInput
On entry: UX ij contains the value of the component ∂Ui x,t ∂x where x=X j, for i=1,2,…,NPDE and j=1,2,…,NPTL.
7:   NCODE – INTEGERInput
On entry: the number of coupled ODEs in the system.
8:   V NCODE – REAL (KIND=nag_wp) arrayInput
On entry: if NCODE>0, V i contains the value of the component Vi t, for i=1,2,…,NCODE.
9:   VDOT NCODE – REAL (KIND=nag_wp) arrayInput
On entry: if NCODE>0, VDOT i contains the value of component V.i t, for i=1,2,…,NCODE.
Note: V.i t, for i=1,2,…,NCODE, may only appear linearly in Qj, for j=1,2,…,NPDE.
10:   P NPDENPDENPTL – REAL (KIND=nag_wp) arrayOutput
On exit: P ijk must be set to the value of P i,j x,t,U,Ux,V where x=X k, for i=1,2,…,NPDE, j=1,2,…,NPDE and k=1,2,…,NPTL.
11:   Q NPDENPTL – REAL (KIND=nag_wp) arrayOutput
On exit: Q ij must be set to the value of Qi x,t,U,Ux,V,V. where x=X j, for i=1,2,…,NPDE and j=1,2,…,NPTL.
12:   R NPDENPTL – REAL (KIND=nag_wp) arrayOutput
On exit: R ij must be set to the value of Ri x,t,U,Ux,V where x=X i, for i=1,2,…,NPDE and j=1,2,…,NPTL.
13:   IRES – INTEGERInput/Output
On entry: set to -1​ or ​1.
On exit: should usually remain unchanged. However, you may set IRES to force the integration routine to take certain actions as described below:
IRES=2
Indicates to the integrator that control should be passed back immediately to the calling (sub)routine with the error indicator set to IFAIL=6.
IRES=3
Indicates to the integrator that the current time step should be abandoned and a smaller time step used instead. You may wish to set IRES=3 when a physically meaningless input or output value has been generated. If you consecutively set IRES=3, then D03PJF/D03PJA returns to the calling subroutine with the error indicator set to IFAIL=4.
Note: the following are additional arguments for specific use with D03PJA. Users of D03PJF therefore need not read the remainder of this description.
14:   IUSER* – INTEGER arrayUser Workspace
15:   RUSER* – REAL (KIND=nag_wp) arrayUser Workspace
PDEDEF is called with the arguments IUSER and RUSER as supplied to D03PJF/D03PJA. You are free to use the arrays IUSER and RUSER to supply information to PDEDEF as an alternative to using COMMON global variables.
PDEDEF must either be a module subprogram USEd by, or declared as EXTERNAL in, the (sub)program from which D03PJF/D03PJA is called. Arguments denoted as Input must not be changed by this procedure.
6:   BNDARY – SUBROUTINE, supplied by the user.External Procedure
BNDARY must compute the functions βi and γi which define the boundary conditions as in equation (4).
The specification of BNDARY for D03PJF is:
SUBROUTINE BNDARY ( NPDE, T, U, UX, NCODE, V, VDOT, IBND, BETA, GAMMA, IRES)
INTEGER | NPDE, NCODE, IBND, IRES
REAL (KIND=nag_wp) | T, U(NPDE), UX(NPDE), V(NCODE), VDOT(NCODE), BETA(NPDE), GAMMA(NPDE)
The specification of BNDARY for D03PJA is:
SUBROUTINE BNDARY ( NPDE, T, U, UX, NCODE, V, VDOT, IBND, BETA, GAMMA, IRES, IUSER, RUSER)
INTEGER | NPDE, NCODE, IBND, IRES, IUSER(*)
REAL (KIND=nag_wp) | T, U(NPDE), UX(NPDE), V(NCODE), VDOT(NCODE), BETA(NPDE), GAMMA(NPDE), RUSER(*)
1:   NPDE – INTEGERInput
On entry: the number of PDEs in the system.
2:   T – REAL (KIND=nag_wp)Input
On entry: the current value of the independent variable t.
3:   U NPDE – REAL (KIND=nag_wp) arrayInput
On entry: U i contains the value of the component Ui x,t at the boundary specified by IBND, for i=1,2,…,NPDE.
4:   UX NPDE – REAL (KIND=nag_wp) arrayInput
On entry: UX i contains the value of the component ∂Ui x,t ∂x at the boundary specified by IBND, for i=1,2,…,NPDE.
5:   NCODE – INTEGERInput
On entry: the number of coupled ODEs in the system.
6:   V NCODE – REAL (KIND=nag_wp) arrayInput
On entry: if NCODE>0, V i contains the value of the component Vi t, for i=1,2,…,NCODE.
7:   VDOT NCODE – REAL (KIND=nag_wp) arrayInput
On entry: if NCODE>0, VDOT i contains the value of component V.i t, for i=1,2,…,NCODE.
Note: V.i t, for i=1,2,…,NCODE, may only appear linearly in Qj, for j=1,2,…,NPDE.
8:   IBND – INTEGERInput
On entry: specifies which boundary conditions are to be evaluated.
IBND=0
BNDARY must set up the coefficients of the left-hand boundary, x=a.
IBND≠0
BNDARY must set up the coefficients of the right-hand boundary, x=b.
9:   BETA NPDE – REAL (KIND=nag_wp) arrayOutput
On exit: BETA i must be set to the value of βi x,t at the boundary specified by IBND, for i=1,2,…,NPDE.
10:   GAMMA NPDE – REAL (KIND=nag_wp) arrayOutput
On exit: GAMMA i must be set to the value of γi x,t,U,Ux,V,V. at the boundary specified by IBND, for i=1,2,…,NPDE.
11:   IRES – INTEGERInput/Output
On entry: set to -1​ or ​1.
On exit: should usually remain unchanged. However, you may set IRES to force the integration routine to take certain actions as described below:
IRES=2
Indicates to the integrator that control should be passed back immediately to the calling (sub)routine with the error indicator set to IFAIL=6.
IRES=3
Indicates to the integrator that the current time step should be abandoned and a smaller time step used instead. You may wish to set IRES=3 when a physically meaningless input or output value has been generated. If you consecutively set IRES=3, then D03PJF/D03PJA returns to the calling subroutine with the error indicator set to IFAIL=4.
Note: the following are additional arguments for specific use with D03PJA. Users of D03PJF therefore need not read the remainder of this description.
12:   IUSER* – INTEGER arrayUser Workspace
13:   RUSER* – REAL (KIND=nag_wp) arrayUser Workspace
BNDARY is called with the arguments IUSER and RUSER as supplied to D03PJF/D03PJA. You are free to use the arrays IUSER and RUSER to supply information to BNDARY as an alternative to using COMMON global variables.
BNDARY must either be a module subprogram USEd by, or declared as EXTERNAL in, the (sub)program from which D03PJF/D03PJA is called. Arguments denoted as Input must not be changed by this procedure.
7:   U NEQN – REAL (KIND=nag_wp) arrayInput/Output
On entry: if IND=1 the value of U must be unchanged from the previous call.
On exit: the computed solution Ui xj,t, for i=1,2,…,NPDE and j=1,2,…,NPTS, and Vk t, for k=1,2,…,NCODE, evaluated at t=TS, as follows:
  • U NPDE×j-1+i contain Ui xj,t, for i=1,2,…,NPDE and j=1,2,…,NPTS, and
  • U NPTS×NPDE+i contain Vi t, for i=1,2,…,NCODE.
8:   NBKPTS – INTEGERInput
On entry: the number of break-points in the interval a,b.
Constraint: NBKPTS≥2.
9:   XBKPTS NBKPTS – REAL (KIND=nag_wp) arrayInput
On entry: the values of the break-points in the space direction. XBKPTS 1 must specify the left-hand boundary, a, and XBKPTS NBKPTS must specify the right-hand boundary, b.
Constraint: XBKPTS 1<XBKPTS 2<⋯<XBKPTS NBKPTS.
10:   NPOLY – INTEGERInput
On entry: the degree of the Chebyshev polynomial to be used in approximating the PDE solution between each pair of break-points.
Constraint: 1≤NPOLY≤49.
11:   NPTS – INTEGERInput
On entry: the number of mesh points in the interval a,b.
Constraint: NPTS=NBKPTS-1×NPOLY+1.
12:   X NPTS – REAL (KIND=nag_wp) arrayOutput
On exit: the mesh points chosen by D03PJF/D03PJA in the spatial direction. The values of X will satisfy X 1<X 2<⋯<X NPTS.
13:   NCODE – INTEGERInput
On entry: the number of coupled ODE components.
Constraint: NCODE≥0.
14:   ODEDEF – SUBROUTINE, supplied by the NAG Library or the user.External Procedure
ODEDEF must evaluate the functions F, which define the system of ODEs, as given in (3).
If you wish to compute the solution of a system of PDEs only (NCODE=0), ODEDEF must be the dummy routine D03PCK for D03PJF (or D53PCK for D03PJA). D03PCK and D53PCK are included in the NAG Library.
The specification of ODEDEF for D03PJF is:
SUBROUTINE ODEDEF ( NPDE, T, NCODE, V, VDOT, NXI, XI, UCP, UCPX, RCP, UCPT, UCPTX, F, IRES)
INTEGER | NPDE, NCODE, NXI, IRES
REAL (KIND=nag_wp) | T, V(NCODE), VDOT(NCODE), XI(NXI), UCP(NPDE,*), UCPX(NPDE,*), RCP(NPDE,*), UCPT(NPDE,*), UCPTX(NPDE,*), F(NCODE)
The specification of ODEDEF for D03PJA is:
SUBROUTINE ODEDEF ( NPDE, T, NCODE, V, VDOT, NXI, XI, UCP, UCPX, RCP, UCPT, UCPTX, F, IRES, IUSER, RUSER)
INTEGER | NPDE, NCODE, NXI, IRES, IUSER(*)
REAL (KIND=nag_wp) | T, V(NCODE), VDOT(NCODE), XI(NXI), UCP(NPDE,*), UCPX(NPDE,*), RCP(NPDE,*), UCPT(NPDE,*), UCPTX(NPDE,*), F(NCODE), RUSER(*)
1:   NPDE – INTEGERInput
On entry: the number of PDEs in the system.
2:   T – REAL (KIND=nag_wp)Input
On entry: the current value of the independent variable t.
3:   NCODE – INTEGERInput
On entry: the number of coupled ODEs in the system.
4:   V NCODE – REAL (KIND=nag_wp) arrayInput
On entry: if NCODE>0, V i contains the value of the component Vi t, for i=1,2,…,NCODE.
5:   VDOT NCODE – REAL (KIND=nag_wp) arrayInput
On entry: if NCODE>0, VDOT i contains the value of component V.i t, for i=1,2,…,NCODE.
6:   NXI – INTEGERInput
On entry: the number of ODE/PDE coupling points.
7:   XI NXI – REAL (KIND=nag_wp) arrayInput
On entry: if NXI>0, XI i contains the ODE/PDE coupling points, ξi, for i=1,2,…,NXI.
8:   UCP NPDE* – REAL (KIND=nag_wp) arrayInput
On entry: if NXI>0, UCP ij contains the value of Ui x,t at the coupling point x=ξj, for i=1,2,…,NPDE and j=1,2,…,NXI.
9:   UCPX NPDE* – REAL (KIND=nag_wp) arrayInput
On entry: if NXI>0, UCPX ij contains the value of ∂Ui x,t ∂x at the coupling point x=ξj, for i=1,2,…,NPDE and j=1,2,…,NXI.
10:   RCP NPDE* – REAL (KIND=nag_wp) arrayInput
On entry: RCP ij contains the value of the flux Ri at the coupling point x=ξj, for i=1,2,…,NPDE and j=1,2,…,NXI.
11:   UCPT NPDE* – REAL (KIND=nag_wp) arrayInput
On entry: if NXI>0, UCPT ij contains the value of ∂Ui ∂t at the coupling point x=ξj, for i=1,2,…,NPDE and j=1,2,…,NXI.
12:   UCPTX NPDE* – REAL (KIND=nag_wp) arrayInput
On entry: UCPTX ij contains the value of ∂2 Ui ∂x ∂t at the coupling point x=ξj, for i=1,2,…,NPDE and j=1,2,…,NXI.
13:   F NCODE – REAL (KIND=nag_wp) arrayOutput
On exit: F i must contain the ith component of F, for i=1,2,…,NCODE, where F is defined as
F=G-A V.-B Ut* U xt* , (5)
or
F=-A V.-B Ut* U xt* . (6)
The definition of F is determined by the input value of IRES.
14:   IRES – INTEGERInput/Output
On entry: the form of F that must be returned in the array F.
IRES=1
Equation (5) must be used.
IRES=-1
Equation (6) must be used.
On exit: should usually remain unchanged. However, you may reset IRES to force the integration routine to take certain actions as described below:
IRES=2
Indicates to the integrator that control should be passed back immediately to the calling (sub)routine with the error indicator set to IFAIL=6.
IRES=3
Indicates to the integrator that the current time step should be abandoned and a smaller time step used instead. You may wish to set IRES=3 when a physically meaningless input or output value has been generated. If you consecutively set IRES=3, then D03PJF/D03PJA returns to the calling subroutine with the error indicator set to IFAIL=4.
Note: the following are additional arguments for specific use with D03PJA. Users of D03PJF therefore need not read the remainder of this description.
15:   IUSER* – INTEGER arrayUser Workspace
16:   RUSER* – REAL (KIND=nag_wp) arrayUser Workspace
ODEDEF is called with the arguments IUSER and RUSER as supplied to D03PJF/D03PJA. You are free to use the arrays IUSER and RUSER to supply information to ODEDEF as an alternative to using COMMON global variables.
ODEDEF must either be a module subprogram USEd by, or declared as EXTERNAL in, the (sub)program from which D03PJF/D03PJA is called. Arguments denoted as Input must not be changed by this procedure.
15:   NXI – INTEGERInput
On entry: the number of ODE/PDE coupling points.
Constraints:
  • if NCODE=0, NXI=0;
  • if NCODE>0, NXI≥0.
16:   XI* – REAL (KIND=nag_wp) arrayInput
Note: the dimension of the array XI must be at least max 1,NXI.
On entry: XI i, for i=1,2,…,NXI, must be set to the ODE/PDE coupling points.
Constraint: XBKPTS 1≤XI 1<XI 2<⋯<XI NXI≤XBKPTS NBKPTS.
17:   NEQN – INTEGERInput
On entry: the number of ODEs in the time direction.
Constraint: NEQN=NPDE×NPTS+NCODE.
18:   UVINIT – SUBROUTINE, supplied by the user.External Procedure
UVINIT must compute the initial values of the PDE and the ODE components Ui xj,t 0, for i=1,2,…,NPDE and j=1,2,…,NPTS, and Vk t 0, for k=1,2,…,NCODE.
The specification of UVINIT for D03PJF is:
SUBROUTINE UVINIT ( NPDE, NPTS, X, U, NCODE, V)
INTEGER | NPDE, NPTS, NCODE
REAL (KIND=nag_wp) | X(NPTS), U(NPDE,NPTS), V(NCODE)
The specification of UVINIT for D03PJA is:
SUBROUTINE UVINIT ( NPDE, NPTS, X, U, NCODE, V, IUSER, RUSER)
INTEGER | NPDE, NPTS, NCODE, IUSER(*)
REAL (KIND=nag_wp) | X(NPTS), U(NPDE,NPTS), V(NCODE), RUSER(*)
1:   NPDE – INTEGERInput
On entry: the number of PDEs in the system.
2:   NPTS – INTEGERInput
On entry: the number of mesh points in the interval a,b.
3:   X NPTS – REAL (KIND=nag_wp) arrayInput
On entry: X i, for i=1,2,…,NPTS, contains the current values of the space variable xi.
4:   U NPDENPTS – REAL (KIND=nag_wp) arrayOutput
On exit: if NXI>0, U ij contains the value of the component Ui xj,t 0, for i=1,2,…,NPDE and j=1,2,…,NPTS.
5:   NCODE – INTEGERInput
On entry: the number of coupled ODEs in the system.
6:   V NCODE – REAL (KIND=nag_wp) arrayOutput
On exit: V i contains the value of component Vi t 0, for i=1,2,…,NCODE.
Note: the following are additional arguments for specific use with D03PJA. Users of D03PJF therefore need not read the remainder of this description.
7:   IUSER* – INTEGER arrayUser Workspace
8:   RUSER* – REAL (KIND=nag_wp) arrayUser Workspace
UVINIT is called with the arguments IUSER and RUSER as supplied to D03PJF/D03PJA. You are free to use the arrays IUSER and RUSER to supply information to UVINIT as an alternative to using COMMON global variables.
UVINIT must either be a module subprogram USEd by, or declared as EXTERNAL in, the (sub)program from which D03PJF/D03PJA is called. Arguments denoted as Input must not be changed by this procedure.
19:   RTOL* – REAL (KIND=nag_wp) arrayInput
Note: the dimension of the array RTOL must be at least 1 if ITOL=1 or 2 and at least NEQN if ITOL=3 or 4.
On entry: the relative local error tolerance.
Constraint: RTOL i≥0.0 for all relevant i.
20:   ATOL* – REAL (KIND=nag_wp) arrayInput
Note: the dimension of the array ATOL must be at least 1 if ITOL=1 or 3 and at least NEQN if ITOL=2 or 4.
On entry: the absolute local error tolerance.
Constraint: ATOL i≥0.0 for all relevant i.
Note: corresponding elements of RTOL and ATOL cannot both be 0.0.
21:   ITOL – INTEGERInput
On entry: a value to indicate the form of the local error test. ITOL indicates to D03PJF/D03PJA whether to interpret either or both of RTOL or ATOL as a vector or scalar. The error test to be satisfied is ei/wi<1.0, where wi is defined as follows:
ITOL | RTOL | ATOL | wi
1 | scalar | scalar | RTOL 1×Ui+ATOL 1
2 | scalar | vector | RTOL 1×Ui+ATOL i
3 | vector | scalar | RTOL i×Ui+ATOL 1
4 | vector | vector | RTOL i×Ui+ATOL i
In the above, ei denotes the estimated local error for the ith component of the coupled PDE/ODE system in time, U i, for i=1,2,…,NEQN.
The choice of norm used is defined by the argument NORM.
Constraint: 1≤ITOL≤4.
22:   NORM – CHARACTER(1)Input
On entry: the type of norm to be used.
NORM='M'
Maximum norm.
NORM='A'
Averaged L 2 norm.
If Unorm denotes the norm of the vector U of length NEQN, then for the averaged L 2 norm
Unorm=1 NEQN∑i=1 NEQN U i/wi 2,
while for the maximum norm
U norm = maxi U i / wi .
See the description of ITOL for the formulation of the weight vector w.
Constraint: NORM='M' or 'A'.
23:   LAOPT – CHARACTER(1)Input
On entry: the type of matrix algebra required.
LAOPT='F'
Full matrix methods to be used.
LAOPT='B'
Banded matrix methods to be used.
LAOPT='S'
Sparse matrix methods to be used.
Constraint: LAOPT='F', 'B' or 'S'.
Note: you are recommended to use the banded option when no coupled ODEs are present (i.e., NCODE=0).
24:   ALGOPT 30 – REAL (KIND=nag_wp) arrayInput
On entry: may be set to control various options available in the integrator. If you wish to employ all the default options, then ALGOPT 1 should be set to 0.0. Default values will also be used for any other elements of ALGOPT set to zero. The permissible values, default values, and meanings are as follows:
ALGOPT 1
Selects the ODE integration method to be used. If ALGOPT 1=1.0, a BDF method is used and if ALGOPT 1=2.0, a Theta method is used. The default value is ALGOPT 1=1.0.
If ALGOPT 1=2.0, then ALGOPT i, for i=2,3,4 are not used.
ALGOPT 2
Specifies the maximum order of the BDF integration formula to be used. ALGOPT 2 may be 1.0, 2.0, 3.0, 4.0 or 5.0. The default value is ALGOPT 2=5.0.
ALGOPT 3
Specifies what method is to be used to solve the system of nonlinear equations arising on each step of the BDF method. If ALGOPT 3=1.0 a modified Newton iteration is used and if ALGOPT 3=2.0 a functional iteration method is used. If functional iteration is selected and the integrator encounters difficulty, then there is an automatic switch to the modified Newton iteration. The default value is ALGOPT 3=1.0.
ALGOPT 4
Specifies whether or not the Petzold error test is to be employed. The Petzold error test results in extra overhead but is more suitable when algebraic equations are present, such as P i,j=0.0, for j=1,2,…,NPDE, for some i or when there is no V.i t dependence in the coupled ODE system. If ALGOPT 4=1.0, then the Petzold test is used. If ALGOPT 4=2.0, then the Petzold test is not used. The default value is ALGOPT 4=1.0.
If ALGOPT 1=1.0, then ALGOPT i, for i=5,6,7, are not used.
ALGOPT 5
Specifies the value of Theta to be used in the Theta integration method. 0.51≤ALGOPT 5≤0.99. The default value is ALGOPT 5=0.55.
ALGOPT 6
Specifies what method is to be used to solve the system of nonlinear equations arising on each step of the Theta method. If ALGOPT 6=1.0, a modified Newton iteration is used and if ALGOPT 6=2.0, a functional iteration method is used. The default value is ALGOPT 6=1.0.
ALGOPT 7
Specifies whether or not the integrator is allowed to switch automatically between modified Newton and functional iteration methods in order to be more efficient. If ALGOPT 7=1.0, then switching is allowed and if ALGOPT 7=2.0, then switching is not allowed. The default value is ALGOPT 7=1.0.
ALGOPT 11
Specifies a point in the time direction, tcrit, beyond which integration must not be attempted. The use of tcrit is described under the argument ITASK. If ALGOPT 1≠0.0, a value of 0.0 for ALGOPT 11, say, should be specified even if ITASK subsequently specifies that tcrit will not be used.
ALGOPT 12
Specifies the minimum absolute step size to be allowed in the time integration. If this option is not required, ALGOPT 12 should be set to 0.0.
ALGOPT 13
Specifies the maximum absolute step size to be allowed in the time integration. If this option is not required, ALGOPT 13 should be set to 0.0.
ALGOPT 14
Specifies the initial step size to be attempted by the integrator. If ALGOPT 14=0.0, then the initial step size is calculated internally.
ALGOPT 15
Specifies the maximum number of steps to be attempted by the integrator in any one call. If ALGOPT 15=0.0, then no limit is imposed.
ALGOPT 23
Specifies what method is to be used to solve the nonlinear equations at the initial point to initialize the values of U, Ut, V and V.. If ALGOPT 23=1.0, a modified Newton iteration is used and if ALGOPT 23=2.0, functional iteration is used. The default value is ALGOPT 23=1.0.
ALGOPT 29 and ALGOPT 30 are used only for the sparse matrix algebra option, LAOPT='S'.
ALGOPT 29
Governs the choice of pivots during the decomposition of the first Jacobian matrix. It should lie in the range 0.0<ALGOPT 29<1.0, with smaller values biasing the algorithm towards maintaining sparsity at the expense of numerical stability. If ALGOPT 29 lies outside this range then the default value is used. If the routines regard the Jacobian matrix as numerically singular then increasing ALGOPT 29 towards 1.0 may help, but at the cost of increased fill-in. The default value is ALGOPT 29=0.1.
ALGOPT 30
Is used as a relative pivot threshold during subsequent Jacobian decompositions (see ALGOPT 29) below which an internal error is invoked. If ALGOPT 30 is greater than 1.0 no check is made on the pivot size, and this may be a necessary option if the Jacobian is found to be numerically singular (see ALGOPT 29). The default value is ALGOPT 30=0.0001.
25:   RSAVE LRSAVE – REAL (KIND=nag_wp) arrayCommunication Array
If IND=0, RSAVE need not be set on entry.
If IND=1, RSAVE must be unchanged from the previous call to the routine because it contains required information about the iteration.
26:   LRSAVE – INTEGERInput
On entry: the dimension of the array RSAVE as declared in the (sub)program from which D03PJF/D03PJA is called. Its size depends on the type of matrix algebra selected.
If LAOPT='F', LRSAVE≥NEQN×NEQN+NEQN+nwkres+lenode.
If LAOPT='B', LRSAVE≥3×mlu+1×NEQN+nwkres+lenode.
If LAOPT='S', LRSAVE≥4×NEQN+11×NEQN/2+1+nwkres+lenode.
Where
mlu is the lower or upper half bandwidths such that
mlu=3×NPDE-1, for PDE problems only (no coupled ODEs); or
mlu=NEQN-1, for coupled PDE/ODE problems.
nwkres= 3×NPOLY+1 2+NPOLY+1×NPDE 2+6×NPDE+NBKPTS+1+8×NPDE+NXI×5×NPDE+1+NCODE+3, when ​NCODE>0​ and ​NXI>0; or 3×NPOLY+1 2+NPOLY+1×NPDE 2+6×NPDE+NBKPTS+1+13×NPDE+NCODE+4, when ​NCODE>0​ and ​NXI=0; or 3×NPOLY+1 2+NPOLY+1×NPDE 2+6×NPDE+NBKPTS+1+13×NPDE+5, when ​NCODE=0.
lenode= 6+int ALGOPT 2×NEQN+50, when the BDF method is used; or 9×NEQN+50, when the Theta method is used.
Note: when LAOPT='S', the value of LRSAVE may be too small when supplied to the integrator. An estimate of the minimum size of LRSAVE is printed on the current error message unit if ITRACE>0 and the routine returns with IFAIL=15.
27:   ISAVE LISAVE – INTEGER arrayCommunication Array
If IND=0, ISAVE need not be set on entry.
If IND=1, ISAVE must be unchanged from the previous call to the routine because it contains required information about the iteration required for subsequent calls. In particular:
ISAVE 1
Contains the number of steps taken in time.
ISAVE 2
Contains the number of residual evaluations of the resulting ODE system used. One such evaluation involves computing the PDE functions at all the mesh points, as well as one evaluation of the functions in the boundary conditions.
ISAVE 3
Contains the number of Jacobian evaluations performed by the time integrator.
ISAVE 4
Contains the order of the ODE method last used in the time integration.
ISAVE 5
Contains the number of Newton iterations performed by the time integrator. Each iteration involves residual evaluation of the resulting ODE system followed by a back-substitution using the LU decomposition of the Jacobian matrix.
28:   LISAVE – INTEGERInput
On entry: the dimension of the array ISAVE as declared in the (sub)program from which D03PJF/D03PJA is called. Its size depends on the type of matrix algebra selected:
  • if LAOPT='F', LISAVE≥24;
  • if LAOPT='B', LISAVE≥NEQN+24;
  • if LAOPT='S', LISAVE≥25×NEQN+24.
Note: when using the sparse option, the value of LISAVE may be too small when supplied to the integrator. An estimate of the minimum size of LISAVE is printed on the current error message unit if ITRACE>0 and the routine returns with IFAIL=15.
29:   ITASK – INTEGERInput
On entry: specifies the task to be performed by the ODE integrator.
ITASK=1
Normal computation of output values U at t=TOUT.
ITASK=2
One step and return.
ITASK=3
Stop at first internal integration point at or beyond t=TOUT.
ITASK=4
Normal computation of output values U at t=TOUT but without overshooting t=tcrit where tcrit is described under the argument ALGOPT.
ITASK=5
Take one step in the time direction and return, without passing tcrit, where tcrit is described under the argument ALGOPT.
Constraint: ITASK=1, 2, 3, 4 or 5.
30:   ITRACE – INTEGERInput
On entry: the level of trace information required from D03PJF/D03PJA and the underlying ODE solver. ITRACE may take the value -1, 0, 1, 2 or 3.
ITRACE=-1
No output is generated.
ITRACE=0
Only warning messages from the PDE solver are printed on the current error message unit (see X04AAF).
ITRACE>0
Output from the underlying ODE solver is printed on the current advisory message unit (see X04ABF). This output contains details of Jacobian entries, the nonlinear iteration and the time integration during the computation of the ODE system.
If ITRACE<-1, then -1 is assumed and similarly if ITRACE>3, then 3 is assumed.
The advisory messages are given in greater detail as ITRACE increases. You are advised to set ITRACE=0, unless you are experienced with Sub-chapter D02M–N.
31:   IND – INTEGERInput/Output
On entry: indicates whether this is a continuation call or a new integration.
IND=0
Starts or restarts the integration in time.
IND=1
Continues the integration after an earlier exit from the routine. In this case, only the arguments TOUT and IFAIL should be reset between calls to D03PJF/D03PJA.
Constraint: IND=0 or 1.
On exit: IND=1.
32:   IFAIL – INTEGERInput/Output
Note: for D03PJA, IFAIL does not occur in this position in the argument list. See the additional arguments described below.
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).
Note: the following are additional arguments for specific use with D03PJA. Users of D03PJF therefore need not read the remainder of this description.
32:   IUSER* – INTEGER arrayUser Workspace
33:   RUSER* – REAL (KIND=nag_wp) arrayUser Workspace
IUSER and RUSER are not used by D03PJF/D03PJA, but are passed directly to PDEDEF, BNDARY, ODEDEF and UVINIT and may be used to pass information to these routines as an alternative to using COMMON global variables.
34:   CWSAV 10 – CHARACTER(80) arrayCommunication Array
35:   LWSAV 100 – LOGICAL arrayCommunication Array
36:   IWSAV 505 – INTEGER arrayCommunication Array
37:   RWSAV 1100 – REAL (KIND=nag_wp) arrayCommunication Array
38:   IFAIL – INTEGERInput/Output
Note: see the argument description for IFAIL above.

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, | TOUT-TS is too small,
or | ITASK≠1, 2, 3, 4 or 5,
or | M≠0, 1 or 2,
or | at least one of the coupling point in array XI is outside the interval [XBKPTS 1,XBKPTS NBKPTS],
or | NPTS≠NBKPTS-1×NPOLY+1,
or | NBKPTS<2,
or | NPDE≤0,
or | NORM≠'A' or 'M',
or | ITOL≠1, 2, 3 or 4,
or | NPOLY<1 or NPOLY>49,
or | NCODE and NXI are incorrectly defined,
or | NEQN≠NPDE×NPTS+NCODE,
or | LAOPT≠'F', 'B' or 'S',
or | IND≠0 or 1,
or | break-points XBKPTS i are badly ordered,
or | LRSAVE is too small,
or | LISAVE is too small,
or | the ODE integrator has not been correctly defined; check ALGOPT argument,
or | either an element of RTOL or ATOL<0.0,
or | all the elements of RTOL and ATOL are zero.
IFAIL=2
The underlying ODE solver cannot make any further progress, with the values of ATOL and RTOL, across the integration range from the current point t=TS. The components of U contain the computed values at the current point t=TS.
IFAIL=3
In the underlying ODE solver, there were repeated error test failures on an attempted step, before completing the requested task, but the integration was successful as far as t=TS. The problem may have a singularity, or the error requirement may be inappropriate.
IFAIL=4
In setting up the ODE system, the internal initialization routine was unable to initialize the derivative of the ODE system. This could be due to the fact that IRES was repeatedly set to 3 in at least PDEDEF, BNDARY or ODEDEF, when the residual in the underlying ODE solver was being evaluated.
IFAIL=5
In solving the ODE system, a singular Jacobian has been encountered. You should check your problem formulation.
IFAIL=6
When evaluating the residual in solving the ODE system, IRES was set to 2 in at least PDEDEF, BNDARY or ODEDEF. Integration was successful as far as t=TS.
IFAIL=7
The values of ATOL and RTOL are so small that the routine is unable to start the integration in time.
IFAIL=8
In one of PDEDEF, BNDARY or ODEDEF, IRES was set to an invalid value.
IFAIL=9 (D02NNF)
A serious error has occurred in an internal call to the specified routine. Check the problem specification and all arguments and array dimensions. Setting ITRACE=1 may provide more information. If the problem persists, contact NAG.
IFAIL=10
The required task has been completed, but it is estimated that a small change in ATOL and RTOL is unlikely to produce any change in the computed solution. (Only applies when you are not operating in one step mode, that is when ITASK≠2 or 5.)
IFAIL=11
An error occurred during Jacobian formulation of the ODE system (a more detailed error description may be directed to the current error message unit).
IFAIL=12
In solving the ODE system, the maximum number of steps specified in ALGOPT 15 have been taken.
IFAIL=13
Some error weights wi became zero during the time integration (see the description of ITOL). Pure relative error control (ATOL i=0.0) was requested on a variable (the ith) which has become zero. The integration was successful as far as t=TS.
IFAIL=14
The flux function Ri was detected as depending on time derivatives, which is not permissible.
IFAIL=15
When using the sparse option, the value of LISAVE or LRSAVE was not sufficient (more detailed information may be directed to the current error message unit).
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

D03PJF/D03PJA controls the accuracy of the integration in the time direction but not the accuracy of the approximation in space. The spatial accuracy depends on both the number of mesh points and on their distribution in space. In the time integration only the local error over a single step is controlled and so the accuracy over a number of steps cannot be guaranteed. You should therefore test the effect of varying the accuracy argument ATOL and RTOL.

8 Parallelism and Performance

D03PJF/D03PJA is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
D03PJF/D03PJA makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The argument specification allows you to include equations with only first-order derivatives in the space direction but there is no guarantee that the method of integration will be satisfactory for such systems. The position and nature of the boundary conditions in particular are critical in defining a stable problem.
The time taken depends on the complexity of the parabolic system and on the accuracy requested.

10 Example

This example provides a simple coupled system of one PDE and one ODE.
V 1 2 ∂ U 1 ∂ t -x V 1 V . 1 ∂ U 1 ∂ x = ∂ 2 U 1 ∂ x 2 V . 1 = V 1 U 1 + ∂ U 1 ∂ x +1 +t ,
for t∈10-4,0.1×2 i,  i=1,2,…,5,x∈0,1.
The left boundary condition at x=0 is
∂U 1 ∂x =-V 1 exp⁡t.
The right boundary condition at x=1 is
U 1=-V 1V.1.
The initial conditions at t=10-4 are defined by the exact solution:
V 1=t,   and  U 1 x,t=exp t 1-x-1.0,  x∈0,1,
and the coupling point is at ξ 1=1.0.

10.1 Program Text

Note: the following programs illustrate the use of D03PJF and D03PJA.

Program Text (d03pjfe.f90)

Program Text (d03pjae.f90)

10.2 Program Data

Program Data (d03pjfe.d)

Program Data (d03pjae.d)

10.3 Program Results

Program Results (d03pjfe.r)

Program Results (d03pjae.r)

GnuplotProduced by GNUPLOT 5.0 patchlevel 0 Example Program Parabolic PDE Coupled with ODE using Collocation and BDF U(x,t) gnuplot_plot_1 gnuplot_plot_2 0.1 0.5 1 2 3 Time (logscale) 0 0.2 0.4 0.6 0.8 1 x −5 0 5 10 15 20 25
D03 Chapter Contents
D03 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


D03PKF : NAG Library, Mark 26

D03 Chapter Contents
D03 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

D03PKF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

D03PKF integrates a system of linear or nonlinear, first-order, time-dependent partial differential equations (PDEs) in one space variable, with scope for coupled ordinary differential equations (ODEs). The spatial discretization is performed using the Keller box scheme and the method of lines is employed to reduce the PDEs to a system of ODEs. The resulting system is solved using a Backward Differentiation Formula (BDF) method or a Theta method (switching between Newton's method and functional iteration).

2 Specification

SUBROUTINE D03PKF ( NPDE, TS, TOUT, PDEDEF, BNDARY, U, NPTS, X, NLEFT, NCODE, ODEDEF, NXI, XI, NEQN, RTOL, ATOL, ITOL, NORM, LAOPT, ALGOPT, RSAVE, LRSAVE, ISAVE, LISAVE, ITASK, ITRACE, IND, IFAIL)
INTEGER | NPDE, NPTS, NLEFT, NCODE, NXI, NEQN, ITOL, LRSAVE, ISAVE(LISAVE), LISAVE, ITASK, ITRACE, IND, IFAIL
REAL (KIND=nag_wp) | TS, TOUT, U(NEQN), X(NPTS), XI(*), RTOL(*), ATOL(*), ALGOPT(30), RSAVE(LRSAVE)
CHARACTER(1) | NORM, LAOPT
EXTERNAL | PDEDEF, BNDARY, ODEDEF

3 Description

D03PKF integrates the system of first-order PDEs and coupled ODEs
Gi x,t,U,Ux,Ut,V,V. = 0 ,   i=1,2,…,NPDE ,   a≤x≤b,t≥t 0 , (1)
Ri t,V,V.,ξ,U*,Ux*,Ut* = 0 ,   i=1,2,…,NCODE . (2)
In the PDE part of the problem given by (1), the functions Gi must have the general form
Gi = ∑ j=1 NPDE P i,j ∂Uj ∂t + ∑ j=1 NCODE Q i,j V.j + Si = 0 ,   i=1,2,…,NPDE , (3)
where P i,j, Q i,j and Si depend on x,t,U,Ux and V.
The vector U is the set of PDE solution values
U x,t = U 1 x,t ,…, U NPDE x,t T ,
and the vector Ux is the partial derivative with respect to x. The vector V is the set of ODE solution values
V t=V 1 t,…,VNCODE t T,
and V. denotes its derivative with respect to time.
In the ODE part given by (2), ξ represents a vector of nξ spatial coupling points at which the ODEs are coupled to the PDEs. These points may or may not be equal to some of the PDE spatial mesh points. U*, Ux* and Ut* are the functions U, Ux and Ut evaluated at these coupling points. Each Ri may only depend linearly on time derivatives. Hence equation (2) may be written more precisely as
R=A-B V.-C Ut*, (4)
where R=R 1,…,RNCODE T, A is a vector of length NCODE, B is an NCODE by NCODE matrix, C is an NCODE by nξ×NPDE matrix. The entries in A, B and C may depend on t, ξ, U*, Ux* and V. In practice you only need to supply a vector of information to define the ODEs and not the matrices B and C. (See Section 5 for the specification of ODEDEF.)
The integration in time is from t 0 to tout, over the space interval a≤x≤b, where a=x 1 and b=xNPTS are the leftmost and rightmost points of a user-defined mesh x 1,x 2,…,xNPTS.
The PDE system which is defined by the functions Gi must be specified in PDEDEF.
The initial values of the functions U x,t and V t must be given at t=t 0.
For a first-order system of PDEs, only one boundary condition is required for each PDE component Ui. The NPDE boundary conditions are separated into na at the left-hand boundary x=a, and nb at the right-hand boundary x=b, such that na+nb=NPDE. The position of the boundary condition for each component should be chosen with care; the general rule is that if the characteristic direction of Ui at the left-hand boundary (say) points into the interior of the solution domain, then the boundary condition for Ui should be specified at the left-hand boundary. Incorrect positioning of boundary conditions generally results in initialization or integration difficulties in the underlying time integration routines.
The boundary conditions have the form:
G i L x,t,U, U t ,V, V . = 0   at ​ x = a ,   i=1,2,…,na , (5)
at the left-hand boundary, and
G i R x,t,U, U t ,V, V . = 0   at ​ x = b,   i=1,2,…,nb, (6)
at the right-hand boundary.
Note that the functions GiL and GiR must not depend on Ux, since spatial derivatives are not determined explicitly in the Keller box scheme. If the problem involves derivative (Neumann) boundary conditions then it is generally possible to restate such boundary conditions in terms of permissible variables. Also note that GiL and GiR must be linear with respect to time derivatives, so that the boundary conditions have the general form:
∑j=1 NPDE E i,j L ∂Uj ∂t +∑j=1 NCODE H i,j L V.j+KiL=0,   i=1,2,…,na, (7)
at the left-hand boundary, and
∑j=1 NPDE E i,j R ∂Uj ∂t +∑j=1 NCODE H i,j R V.j+KiR=0,   i=1,2,…,nb, (8)
at the right-hand boundary, where E i,j L, E i,j R, H i,j L, H i,j R, KiL and KiR depend on x,t,U and V only.
The boundary conditions must be specified in BNDARY.
The problem is subject to the following restrictions:
(i) | P i,j, Q i,j and Si must not depend on any time derivatives;
(ii) | t 0<tout, so that integration is in the forward direction;
(iii) | The evaluation of the function Gi is done approximately at the mid-points of the mesh X i, for i=1,2,…,NPTS, by calling the PDEDEF for each mid-point in turn. Any discontinuities in the function must therefore be at one or more of the mesh points x 1,x 2,…,xNPTS;
(iv) | At least one of the functions P i,j must be nonzero so that there is a time derivative present in the PDE problem.
The algebraic-differential equation system which is defined by the functions Ri must be specified in ODEDEF. You must also specify the coupling points ξ in the array XI.
The parabolic equations are approximated by a system of ODEs in time for the values of Ui at mesh points. In this method of lines approach the Keller box scheme (see Keller (1970)) is applied to each PDE in the space variable only, resulting in a system of ODEs in time for the values of Ui at each mesh point. In total there are NPDE×NPTS+NCODE ODEs in time direction. This system is then integrated forwards in time using a Backward Differentiation Formula (BDF) or a Theta method.

4 References

Berzins M (1990) Developments in the NAG Library software for parabolic equations Scientific Software Systems (eds J C Mason and M G Cox) 59–72 Chapman and Hall
Berzins M, Dew P M and Furzeland R M (1989) Developing software for time-dependent problems using the method of lines and differential-algebraic integrators Appl. Numer. Math. 5 375–397
Berzins M and Furzeland R M (1992) An adaptive theta method for the solution of stiff and nonstiff differential equations Appl. Numer. Math. 9 1–19
Keller H B (1970) A new difference scheme for parabolic problems Numerical Solutions of Partial Differential Equations (ed J Bramble) 2 327–350 Academic Press
Pennington S V and Berzins M (1994) New NAG Library software for first-order partial differential equations ACM Trans. Math. Softw. 20 63–99

5 Arguments

1:   NPDE – INTEGERInput
On entry: the number of PDEs to be solved.
Constraint: NPDE≥1.
2:   TS – REAL (KIND=nag_wp)Input/Output
On entry: the initial value of the independent variable t.
Constraint: TS<TOUT.
On exit: the value of t corresponding to the solution in U. Normally TS=TOUT.
3:   TOUT – REAL (KIND=nag_wp)Input
On entry: the final value of t to which the integration is to be carried out.
4:   PDEDEF – SUBROUTINE, supplied by the user.External Procedure
PDEDEF must evaluate the functions Gi which define the system of PDEs. PDEDEF is called approximately midway between each pair of mesh points in turn by D03PKF.
The specification of PDEDEF is:
SUBROUTINE PDEDEF ( NPDE, T, X, U, UT, UX, NCODE, V, VDOT, RES, IRES)
INTEGER | NPDE, NCODE, IRES
REAL (KIND=nag_wp) | T, X, U(NPDE), UT(NPDE), UX(NPDE), V(NCODE), VDOT(NCODE), RES(NPDE)
1:   NPDE – INTEGERInput
On entry: the number of PDEs in the system.
2:   T – REAL (KIND=nag_wp)Input
On entry: the current value of the independent variable t.
3:   X – REAL (KIND=nag_wp)Input
On entry: the current value of the space variable x.
4:   U NPDE – REAL (KIND=nag_wp) arrayInput
On entry: U i contains the value of the component Ui x,t, for i=1,2,…,NPDE.
5:   UT NPDE – REAL (KIND=nag_wp) arrayInput
On entry: UT i contains the value of the component ∂Ui x,t ∂t , for i=1,2,…,NPDE.
6:   UX NPDE – REAL (KIND=nag_wp) arrayInput
On entry: UX i contains the value of the component ∂Ui x,t ∂x , for i=1,2,…,NPDE.
7:   NCODE – INTEGERInput
On entry: the number of coupled ODEs in the system.
8:   V NCODE – REAL (KIND=nag_wp) arrayInput
On entry: if NCODE>0, V i contains the value of the component Vi t, for i=1,2,…,NCODE.
9:   VDOT NCODE – REAL (KIND=nag_wp) arrayInput
On entry: if NCODE>0, VDOT i contains the value of component V.i t, for i=1,2,…,NCODE.
10:   RES NPDE – REAL (KIND=nag_wp) arrayOutput
On exit: RES i must contain the ith component of G, for i=1,2,…,NPDE, where G is defined as
Gi=∑j=1 NPDE P i,j ∂Uj ∂t +∑j=1 NCODE Q i,jV.j, (9)
i.e., only terms depending explicitly on time derivatives, or
Gi=∑j=1 NPDE P i,j ∂Uj ∂t +∑j=1 NCODE Q i,jV.j+Si, (10)
i.e., all terms in equation (3).
The definition of G is determined by the input value of IRES.
11:   IRES – INTEGERInput/Output
On entry: the form of Gi that must be returned in the array RES.
IRES=-1
Equation (9) must be used.
IRES=1
Equation (10) must be used.
On exit: should usually remain unchanged. However, you may set IRES to force the integration routine to take certain actions, as described below:
IRES=2
Indicates to the integrator that control should be passed back immediately to the calling (sub)routine with the error indicator set to IFAIL=6.
IRES=3
Indicates to the integrator that the current time step should be abandoned and a smaller time step used instead. You may wish to set IRES=3 when a physically meaningless input or output value has been generated. If you consecutively set IRES=3, then D03PKF returns to the calling subroutine with the error indicator set to IFAIL=4.
PDEDEF must either be a module subprogram USEd by, or declared as EXTERNAL in, the (sub)program from which D03PKF is called. Arguments denoted as Input must not be changed by this procedure.
5:   BNDARY – SUBROUTINE, supplied by the user.External Procedure
BNDARY must evaluate the functions GiL and GiR which describe the boundary conditions, as given in (5) and (6).
The specification of BNDARY is:
SUBROUTINE BNDARY ( NPDE, T, IBND, NOBC, U, UT, NCODE, V, VDOT, RES, IRES)
INTEGER | NPDE, IBND, NOBC, NCODE, IRES
REAL (KIND=nag_wp) | T, U(NPDE), UT(NPDE), V(NCODE), VDOT(NCODE), RES(NOBC)
1:   NPDE – INTEGERInput
On entry: the number of PDEs in the system.
2:   T – REAL (KIND=nag_wp)Input
On entry: the current value of the independent variable t.
3:   IBND – INTEGERInput
On entry: specifies which boundary conditions are to be evaluated.
IBND=0
BNDARY must compute the left-hand boundary condition at x=a.
IBND≠0
BNDARY must compute the right-hand boundary condition at x=b.
4:   NOBC – INTEGERInput
On entry: specifies the number of boundary conditions at the boundary specified by IBND.
5:   U NPDE – REAL (KIND=nag_wp) arrayInput
On entry: U i contains the value of the component Ui x,t at the boundary specified by IBND, for i=1,2,…,NPDE.
6:   UT NPDE – REAL (KIND=nag_wp) arrayInput
On entry: UT i contains the value of the component ∂Ui x,t ∂t at the boundary specified by IBND, for i=1,2,…,NPDE.
7:   NCODE – INTEGERInput
On entry: the number of coupled ODEs in the system.
8:   V NCODE – REAL (KIND=nag_wp) arrayInput
On entry: if NCODE>0, V i contains the value of the component Vi t, for i=1,2,…,NCODE.
9:   VDOT NCODE – REAL (KIND=nag_wp) arrayInput
On entry: if NCODE>0, VDOT i contains the value of component V.i t, for i=1,2,…,NCODE.
Note: VDOT i, for i=1,2,…,NCODE, may only appear linearly as in (7) and (8).
10:   RES NOBC – REAL (KIND=nag_wp) arrayOutput
On exit: RES i must contain the ith component of GL or GR, depending on the value of IBND, for i=1,2,…,NOBC, where GL is defined as
GiL=∑j=1 NPDE E i,j L ∂Uj ∂t +∑j=1 NCODE H i,j L V.j, (11)
i.e., only terms depending explicitly on time derivatives, or
GiL=∑j=1 NPDE E i,j L ∂Uj ∂t +∑j=1 NCODE H i,j L V.j+KiL, (12)
i.e., all terms in equation (7), and similarly for GiR.
The definitions of GL and GR are determined by the input value of IRES.
11:   IRES – INTEGERInput/Output
On entry: the form of GiL (or GiR) that must be returned in the array RES.
IRES=-1
Equation (11) must be used.
IRES=1
Equation (12) must be used.
On exit: should usually remain unchanged. However, you may set IRES to force the integration routine to take certain actions as described below:
IRES=2
Indicates to the integrator that control should be passed back immediately to the calling (sub)routine with the error indicator set to IFAIL=6.
IRES=3
Indicates to the integrator that the current time step should be abandoned and a smaller time step used instead. You may wish to set IRES=3 when a physically meaningless input or output value has been generated. If you consecutively set IRES=3, then D03PKF returns to the calling subroutine with the error indicator set to IFAIL=4.
BNDARY must either be a module subprogram USEd by, or declared as EXTERNAL in, the (sub)program from which D03PKF is called. Arguments denoted as Input must not be changed by this procedure.
6:   U NEQN – REAL (KIND=nag_wp) arrayInput/Output
On entry: the initial values of the dependent variables defined as follows:
  • U NPDE×j-1+i contain Ui xj,t 0, for i=1,2,…,NPDE and j=1,2,…,NPTS, and
  • U NPTS×NPDE+i contain Vi t 0, for i=1,2,…,NCODE.
On exit: the computed solution Ui xj,t, for i=1,2,…,NPDE and j=1,2,…,NPTS, and Vk t, for k=1,2,…,NCODE, evaluated at t=TS.
7:   NPTS – INTEGERInput
On entry: the number of mesh points in the interval a,b.
Constraint: NPTS≥3.
8:   X NPTS – REAL (KIND=nag_wp) arrayInput
On entry: the mesh points in the space direction. X 1 must specify the left-hand boundary, a, and X NPTS must specify the right-hand boundary, b.
Constraint: X 1<X 2<⋯<X NPTS.
9:   NLEFT – INTEGERInput
On entry: the number na of boundary conditions at the left-hand mesh point X 1.
Constraint: 0≤NLEFT≤NPDE.
10:   NCODE – INTEGERInput
On entry: the number of coupled ODE components.
Constraint: NCODE≥0.
11:   ODEDEF – SUBROUTINE, supplied by the NAG Library or the user.External Procedure
ODEDEF must evaluate the functions R, which define the system of ODEs, as given in (4).
If you wish to compute the solution of a system of PDEs only (i.e., NCODE=0), ODEDEF must be the dummy routine D03PEK. (D03PEK is included in the NAG Library.)
The specification of ODEDEF is:
SUBROUTINE ODEDEF ( NPDE, T, NCODE, V, VDOT, NXI, XI, UCP, UCPX, UCPT, R, IRES)
INTEGER | NPDE, NCODE, NXI, IRES
REAL (KIND=nag_wp) | T, V(NCODE), VDOT(NCODE), XI(NXI), UCP(NPDE,*), UCPX(NPDE,*), UCPT(NPDE,*), R(NCODE)
1:   NPDE – INTEGERInput
On entry: the number of PDEs in the system.
2:   T – REAL (KIND=nag_wp)Input
On entry: the current value of the independent variable t.
3:   NCODE – INTEGERInput
On entry: the number of coupled ODEs in the system.
4:   V NCODE – REAL (KIND=nag_wp) arrayInput
On entry: if NCODE>0, V i contains the value of the component Vi t, for i=1,2,…,NCODE.
5:   VDOT NCODE – REAL (KIND=nag_wp) arrayInput
On entry: if NCODE>0, VDOT i contains the value of component V.i t, for i=1,2,…,NCODE.
6:   NXI – INTEGERInput
On entry: the number of ODE/PDE coupling points.
7:   XI NXI – REAL (KIND=nag_wp) arrayInput
On entry: if NXI>0, XI i contains the ODE/PDE coupling points, ξi, for i=1,2,…,NXI.
8:   UCP NPDE* – REAL (KIND=nag_wp) arrayInput
On entry: if NXI>0, UCP ij contains the value of Ui x,t at the coupling point x=ξj, for i=1,2,…,NPDE and j=1,2,…,NXI.
9:   UCPX NPDE* – REAL (KIND=nag_wp) arrayInput
On entry: if NXI>0, UCPX ij contains the value of ∂Ui x,t ∂x at the coupling point x=ξj, for i=1,2,…,NPDE and j=1,2,…,NXI.
10:   UCPT NPDE* – REAL (KIND=nag_wp) arrayInput
On entry: if NXI>0, UCPT ij contains the value of ∂Ui ∂t at the coupling point x=ξj, for i=1,2,…,NPDE and j=1,2,…,NXI.
11:   R NCODE – REAL (KIND=nag_wp) arrayOutput
On exit: if NCODE>0, R i must contain the ith component of R, for i=1,2,…,NCODE, where R is defined as
R=-B V.-C Ut*, (13)
i.e., only terms depending explicitly on time derivatives, or
R=A-B V.-C Ut*, (14)
i.e., all terms in equation (4). The definition of R is determined by the input value of IRES.
12:   IRES – INTEGERInput/Output
On entry: the form of R that must be returned in the array R.
IRES=-1
Equation (13) must be used.
IRES=1
Equation (14) must be used.
On exit: should usually remain unchanged. However, you may reset IRES to force the integration routine to take certain actions, as described below:
IRES=2
Indicates to the integrator that control should be passed back immediately to the calling (sub)routine with the error indicator set to IFAIL=6.
IRES=3
Indicates to the integrator that the current time step should be abandoned and a smaller time step used instead. You may wish to set IRES=3 when a physically meaningless input or output value has been generated. If you consecutively set IRES=3, then D03PKF returns to the calling subroutine with the error indicator set to IFAIL=4.
ODEDEF must either be a module subprogram USEd by, or declared as EXTERNAL in, the (sub)program from which D03PKF is called. Arguments denoted as Input must not be changed by this procedure.
12:   NXI – INTEGERInput
On entry: the number of ODE/PDE coupling points.
Constraints:
  • if NCODE=0, NXI=0;
  • if NCODE>0, NXI≥0.
13:   XI* – REAL (KIND=nag_wp) arrayInput
Note: the dimension of the array XI must be at least max 1,NXI.
On entry: XI i, for i=1,2,…,NXI, must be set to the ODE/PDE coupling points, ξi.
Constraint: X 1≤XI 1<XI 2<⋯<XI NXI≤X NPTS.
14:   NEQN – INTEGERInput
On entry: the number of ODEs in the time direction.
Constraint: NEQN=NPDE×NPTS+NCODE.
15:   RTOL* – REAL (KIND=nag_wp) arrayInput
Note: the dimension of the array RTOL must be at least 1 if ITOL=1 or 2 and at least NEQN if ITOL=3 or 4.
On entry: the relative local error tolerance.
Constraint: RTOL i≥0.0 for all relevant i.
16:   ATOL* – REAL (KIND=nag_wp) arrayInput
Note: the dimension of the array ATOL must be at least 1 if ITOL=1 or 3 and at least NEQN if ITOL=2 or 4.
On entry: the absolute local error tolerance.
Constraint: ATOL i≥0.0 for all relevant i.
Note: corresponding elements of RTOL and ATOL cannot both be 0.0.
17:   ITOL – INTEGERInput
On entry: a value to indicate the form of the local error test. ITOL indicates to D03PKF whether to interpret either or both of RTOL or ATOL as a vector or scalar. The error test to be satisfied is ei/wi<1.0, where wi is defined as follows:
ITOL | RTOL | ATOL | wi
1 | scalar | scalar | RTOL 1×U i+ATOL 1
2 | scalar | vector | RTOL 1×U i+ATOL i
3 | vector | scalar | RTOL i×U i+ATOL 1
4 | vector | vector | RTOL i×U i+ATOL i
In the above, ei denotes the estimated local error for the ith component of the coupled PDE/ODE system in time, U i, for i=1,2,…,NEQN.
The choice of norm used is defined by the argument NORM.
Constraint: 1≤ITOL≤4.
18:   NORM – CHARACTER(1)Input
On entry: the type of norm to be used.
NORM='M'
Maximum norm.
NORM='A'
Averaged L 2 norm.
If Unorm denotes the norm of the vector U of length NEQN, then for the averaged L 2 norm
Unorm=1 NEQN∑i=1 NEQN U i/wi 2,
while for the maximum norm
U norm = maxi U i / wi .
See the description of ITOL for the formulation of the weight vector w.
Constraint: NORM='M' or 'A'.
19:   LAOPT – CHARACTER(1)Input
On entry: the type of matrix algebra required.
LAOPT='F'
Full matrix methods to be used.
LAOPT='B'
Banded matrix methods to be used.
LAOPT='S'
Sparse matrix methods to be used.
Constraint: LAOPT='F', 'B' or 'S'.
Note: you are recommended to use the banded option when no coupled ODEs are present (i.e., NCODE=0).
20:   ALGOPT 30 – REAL (KIND=nag_wp) arrayInput
On entry: may be set to control various options available in the integrator. If you wish to employ all the default options, then ALGOPT 1 should be set to 0.0. Default values will also be used for any other elements of ALGOPT set to zero. The permissible values, default values, and meanings are as follows:
ALGOPT 1
Selects the ODE integration method to be used. If ALGOPT 1=1.0, a BDF method is used and if ALGOPT 1=2.0, a Theta method is used. The default value is ALGOPT 1=1.0.
If ALGOPT 1=2.0, then ALGOPT i, for i=2,3,4, are not used.
ALGOPT 2
Specifies the maximum order of the BDF integration formula to be used. ALGOPT 2 may be 1.0, 2.0, 3.0, 4.0 or 5.0. The default value is ALGOPT 2=5.0.
ALGOPT 3
Specifies what method is to be used to solve the system of nonlinear equations arising on each step of the BDF method. If ALGOPT 3=1.0 a modified Newton iteration is used and if ALGOPT 3=2.0 a functional iteration method is used. If functional iteration is selected and the integrator encounters difficulty, then there is an automatic switch to the modified Newton iteration. The default value is ALGOPT 3=1.0.
ALGOPT 4
Specifies whether or not the Petzold error test is to be employed. The Petzold error test results in extra overhead but is more suitable when algebraic equations are present, such as P i,j=0.0, for j=1,2,…,NPDE, for some i or when there is no V.i t dependence in the coupled ODE system. If ALGOPT 4=1.0, then the Petzold test is used. If ALGOPT 4=2.0, then the Petzold test is not used. The default value is ALGOPT 4=1.0.
If ALGOPT 1=1.0, then ALGOPT i, for i=5,6,7, are not used.
ALGOPT 5
Specifies the value of Theta to be used in the Theta integration method. 0.51≤ALGOPT 5≤0.99. The default value is ALGOPT 5=0.55.
ALGOPT 6
Specifies what method is to be used to solve the system of nonlinear equations arising on each step of the Theta method. If ALGOPT 6=1.0, a modified Newton iteration is used and if ALGOPT 6=2.0, a functional iteration method is used. The default value is ALGOPT 6=1.0.
ALGOPT 7
Specifies whether or not the integrator is allowed to switch automatically between modified Newton and functional iteration methods in order to be more efficient. If ALGOPT 7=1.0, then switching is allowed and if ALGOPT 7=2.0, then switching is not allowed. The default value is ALGOPT 7=1.0.
ALGOPT 11
Specifies a point in the time direction, tcrit, beyond which integration must not be attempted. The use of tcrit is described under the argument ITASK. If ALGOPT 1≠0.0, a value of 0.0, for ALGOPT 11, say, should be specified even if ITASK subsequently specifies that tcrit will not be used.
ALGOPT 12
Specifies the minimum absolute step size to be allowed in the time integration. If this option is not required, ALGOPT 12 should be set to 0.0.
ALGOPT 13
Specifies the maximum absolute step size to be allowed in the time integration. If this option is not required, ALGOPT 13 should be set to 0.0.
ALGOPT 14
Specifies the initial step size to be attempted by the integrator. If ALGOPT 14=0.0, then the initial step size is calculated internally.
ALGOPT 15
Specifies the maximum number of steps to be attempted by the integrator in any one call. If ALGOPT 15=0.0, then no limit is imposed.
ALGOPT 23
Specifies what method is to be used to solve the nonlinear equations at the initial point to initialize the values of U, Ut, V and V.. If ALGOPT 23=1.0, a modified Newton iteration is used and if ALGOPT 23=2.0, functional iteration is used. The default value is ALGOPT 23=1.0.
ALGOPT 29 and ALGOPT 30 are used only for the sparse matrix algebra option, i.e., LAOPT='S'.
ALGOPT 29
Governs the choice of pivots during the decomposition of the first Jacobian matrix. It should lie in the range 0.0<ALGOPT 29<1.0, with smaller values biasing the algorithm towards maintaining sparsity at the expense of numerical stability. If ALGOPT 29 lies outside this range then the default value is used. If the routines regard the Jacobian matrix as numerically singular then increasing ALGOPT 29 towards 1.0 may help, but at the cost of increased fill-in. The default value is ALGOPT 29=0.1.
ALGOPT 30
Used as a relative pivot threshold during subsequent Jacobian decompositions (see ALGOPT 29) below which an internal error is invoked. ALGOPT 30 must be greater than zero, otherwise the default value is used. If ALGOPT 30 is greater than 1.0 no check is made on the pivot size, and this may be a necessary option if the Jacobian is found to be numerically singular (see ALGOPT 29). The default value is ALGOPT 30=0.0001.
21:   RSAVE LRSAVE – REAL (KIND=nag_wp) arrayCommunication Array
If IND=0, RSAVE need not be set on entry.
If IND=1, RSAVE must be unchanged from the previous call to the routine because it contains required information about the iteration.
22:   LRSAVE – INTEGERInput
On entry: the dimension of the array RSAVE as declared in the (sub)program from which D03PKF is called. Its size depends on the type of matrix algebra selected.
If LAOPT='F', LRSAVE≥NEQN×NEQN+NEQN+nwkres+lenode.
If LAOPT='B', LRSAVE≥2×ml+mu+2×NEQN+nwkres+lenode.
If LAOPT='S', LRSAVE≥4×NEQN+11×NEQN/2+1+nwkres+lenode.
Where
ml and mu are the lower and upper half bandwidths given by ml=NPDE+NLEFT-1 such that
mu=2×NPDE-NLEFT-1, for problems involving PDEs only; or
ml=mu=NEQN-1, for coupled PDE/ODE problems.
nwkres= NPDE×3×NPDE+6×NXI+NPTS+15+NXI+NCODE+7×NPTS+2, when ​NCODE>0​ and ​NXI>0; or NPDE×3×NPDE+NPTS+21+NCODE+7×NPTS+3, when ​NCODE>0​ and ​NXI=0; or NPDE×3×NPDE+NPTS+21+7×NPTS+4, when ​NCODE=0.
lenode= 6+int ALGOPT 2×NEQN+50, when the BDF method is used; or 9×NEQN+50, when the Theta method is used.
Note: when using the sparse option, the value of LRSAVE may be too small when supplied to the integrator. An estimate of the minimum size of LRSAVE is printed on the current error message unit if ITRACE>0 and the routine returns with IFAIL=15.
23:   ISAVE LISAVE – INTEGER arrayCommunication Array
If IND=0, ISAVE need not be set.
If IND=1, ISAVE must be unchanged from the previous call to the routine because it contains required information about the iteration. In particular the following components of the array ISAVE concern the efficiency of the integration:
ISAVE 1
Contains the number of steps taken in time.
ISAVE 2
Contains the number of residual evaluations of the resulting ODE system used. One such evaluation involves evaluating the PDE functions at all the mesh points, as well as one evaluation of the functions in the boundary conditions.
ISAVE 3
Contains the number of Jacobian evaluations performed by the time integrator.
ISAVE 4
Contains the order of the ODE method last used in the time integration.
ISAVE 5
Contains the number of Newton iterations performed by the time integrator. Each iteration involves residual evaluation of the resulting ODE system followed by a back-substitution using the LU decomposition of the Jacobian matrix.
24:   LISAVE – INTEGERInput
On entry: the dimension of the array ISAVE as declared in the (sub)program from which D03PKF is called. Its size depends on the type of matrix algebra selected:
  • if LAOPT='F', LISAVE≥24;
  • if LAOPT='B', LISAVE≥NEQN+24;
  • if LAOPT='S', LISAVE≥25×NEQN+24.
Note: when using the sparse option, the value of LISAVE may be too small when supplied to the integrator. An estimate of the minimum size of LISAVE is printed on the current error message unit if ITRACE>0 and the routine returns with IFAIL=15.
25:   ITASK – INTEGERInput
On entry: the task to be performed by the ODE integrator.
ITASK=1
Normal computation of output values U at t=TOUT (by overshooting and interpolating).
ITASK=2
Take one step in the time direction and return.
ITASK=3
Stop at first internal integration point at or beyond t=TOUT.
ITASK=4
Normal computation of output values U at t=TOUT but without overshooting t=tcrit where tcrit is described under the argument ALGOPT.
ITASK=5
Take one step in the time direction and return, without passing tcrit, where tcrit is described under the argument ALGOPT.
Constraint: ITASK=1, 2, 3, 4 or 5.
26:   ITRACE – INTEGERInput
On entry: the level of trace information required from D03PKF and the underlying ODE solver as follows:
ITRACE≤-1
No output is generated.
ITRACE=0
Only warning messages from the PDE solver are printed on the current error message unit (see X04AAF).
ITRACE=1
Output from the underlying ODE solver is printed on the current advisory message unit (see X04ABF). This output contains details of Jacobian entries, the nonlinear iteration and the time integration during the computation of the ODE system.
ITRACE=2
Output from the underlying ODE solver is similar to that produced when ITRACE=1, except that the advisory messages are given in greater detail.
ITRACE≥3
Output from the underlying ODE solver is similar to that produced when ITRACE=2, except that the advisory messages are given in greater detail.
You advised to set ITRACE=0, unless you are experienced with Sub-chapter D02M–N.
27:   IND – INTEGERInput/Output
On entry: indicates whether this is a continuation call or a new integration.
IND=0
Starts or restarts the integration in time.
IND=1
Continues the integration after an earlier exit from the routine. In this case, only the arguments TOUT and IFAIL should be reset between calls to D03PKF.
Constraint: IND=0 or 1.
On exit: IND=1.
28:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, | TOUT-TS is too small,
or | ITASK≠1, 2, 3, 4 or 5,
or | at least one of the coupling points defined in array XI is outside the interval [X 1,X NPTS],
or | NPTS<3,
or | NPDE<1,
or | NLEFT not in range 0 to NPDE,
or | NORM≠'A' or 'M',
or | LAOPT≠'F', 'B' or 'S',
or | ITOL≠1, 2, 3 or 4,
or | IND≠0 or 1,
or | mesh points X i are badly ordered,
or | LRSAVE or LISAVE are too small,
or | NCODE and NXI are incorrectly defined,
or | IND=1 on initial entry to D03PKF,
or | an element of RTOL or ATOL<0.0,
or | corresponding elements of ATOL and RTOL are both 0.0,
or | NEQN≠NPDE×NPTS+NCODE.
IFAIL=2
The underlying ODE solver cannot make any further progress, with the values of ATOL and RTOL, across the integration range from the current point t=TS. The components of U contain the computed values at the current point t=TS.
IFAIL=3
In the underlying ODE solver, there were repeated error test failures on an attempted step, before completing the requested task, but the integration was successful as far as t=TS. The problem may have a singularity, or the error requirement may be inappropriate. Incorrect positioning of boundary conditions may also result in this error.
IFAIL=4
In setting up the ODE system, the internal initialization routine was unable to initialize the derivative of the ODE system. This could be due to the fact that IRES was repeatedly set to 3 in one of PDEDEF, BNDARY or ODEDEF, when the residual in the underlying ODE solver was being evaluated. Incorrect positioning of boundary conditions may also result in this error.
IFAIL=5
In solving the ODE system, a singular Jacobian has been encountered. You should check their problem formulation.
IFAIL=6
When evaluating the residual in solving the ODE system, IRES was set to 2 in one of PDEDEF, BNDARY or ODEDEF. Integration was successful as far as t=TS.
IFAIL=7
The values of ATOL and RTOL are so small that the routine is unable to start the integration in time.
IFAIL=8
In either, PDEDEF, BNDARY or ODEDEF, IRES was set to an invalid value.
IFAIL=9 (D02NNF)
A serious error has occurred in an internal call to the specified routine. Check the problem specification and all arguments and array dimensions. Setting ITRACE=1 may provide more information. If the problem persists, contact NAG.
IFAIL=10
The required task has been completed, but it is estimated that a small change in ATOL and RTOL is unlikely to produce any change in the computed solution. (Only applies when you are not operating in one step mode, that is when ITASK≠2 or 5.)
IFAIL=11
An error occurred during Jacobian formulation of the ODE system (a more detailed error description may be directed to the current advisory message unit). If using the sparse matrix algebra option, the values of ALGOPT 29 and ALGOPT 30 may be inappropriate.
IFAIL=12
In solving the ODE system, the maximum number of steps specified in ALGOPT 15 has been taken.
IFAIL=13
Some error weights wi became zero during the time integration (see the description of ITOL). Pure relative error control ATOL i=0.0 was requested on a variable (the ith) which has become zero. The integration was successful as far as t=TS.
IFAIL=14
Not applicable.
IFAIL=15
When using the sparse option, the value of LISAVE or LRSAVE was insufficient (more detailed information may be directed to the current error message unit).
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

D03PKF controls the accuracy of the integration in the time direction but not the accuracy of the approximation in space. The spatial accuracy depends on both the number of mesh points and on their distribution in space. In the time integration only the local error over a single step is controlled and so the accuracy over a number of steps cannot be guaranteed. You should therefore test the effect of varying the accuracy arguments, ATOL and RTOL.

8 Parallelism and Performance

D03PKF is not thread safe and should not be called from a multithreaded user program. Please see Section 3.12.1 in How to Use the NAG Library and its Documentation for more information on thread safety.
D03PKF is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
D03PKF makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The Keller box scheme can be used to solve higher-order problems which have been reduced to first-order by the introduction of new variables (see the example in Section 10). In general, a second-order problem can be solved with slightly greater accuracy using the Keller box scheme instead of a finite difference scheme (see D03PCF/D03PCA or D03PHF/D03PHA for example), but at the expense of increased CPU time due to the larger number of function evaluations required.
It should be noted that the Keller box scheme, in common with other central-difference schemes, may be unsuitable for some hyperbolic first-order problems such as the apparently simple linear advection equation Ut+a Ux=0, where a is a constant, resulting in spurious oscillations due to the lack of dissipation. This type of problem requires a discretization scheme with upwind weighting (D03PLF for example), or the addition of a second-order artificial dissipation term.
The time taken depends on the complexity of the system and on the accuracy requested. For a given system and a fixed accuracy it is approximately proportional to NEQN.

10 Example

This example provides a simple coupled system of two PDEs and one ODE.
V 1 2 ∂U 1 ∂t -x V 1V.1U 2- ∂U 2 ∂x =0, U 2- ∂U 1 ∂x =0, V.1-V 1U 1-U 2-1-t=0,
for t∈10-4,0.1×2 i, for i=1,2,…,5,x∈0,1. The left boundary condition at x=0 is
U 2=-V 1 exp⁡t,
and the right boundary condition at x=1 is
U 2=-V 1V.1.
The initial conditions at t=10-4 are defined by the exact solution:
V 1 = t , U 1 x,t = exp t 1-x - 1.0   and   U 2 x,t = - t exp t 1-x , ​ x ∈ 0,1 ,
and the coupling point is at ξ 1=1.0.
This problem is exactly the same as the D03PHF/D03PHA example problem, but reduced to first-order by the introduction of a second PDE variable (as mentioned in Section 9).

10.1 Program Text

Program Text (d03pkfe.f90)

10.2 Program Data

Program Data (d03pkfe.d)

10.3 Program Results

Program Results (d03pkfe.r)

GnuplotProduced by GNUPLOT 5.0 patchlevel 0 Example Program Two PDEs Coupled with One ODE using Keller, Box and BDF Solution U(1,x,t) U(1,x,t) gnuplot_plot_1 gnuplot_plot_2 0.1 0.5 1 2 3 Time (logscale) 0 0.2 0.4 0.6 0.8 1 x −5 0 5 10 15 20 25
GnuplotProduced by GNUPLOT 5.0 patchlevel 0 Two PDEs Coupled with One ODE using Keller, Box and BDF Solution U(2,x,t) U(2,x,t) gnuplot_plot_1 gnuplot_plot_2 0.1 0.5 1 2 3 Time (logscale) 0 0.2 0.4 0.6 0.8 1 x −80 −70 −60 −50 −40 −30 −20 −10 0
D03 Chapter Contents
D03 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


D03PLF : NAG Library, Mark 26

D03 Chapter Contents

D03 Chapter Introduction

NAG Library Manual

NAG Library Routine Document

D03PLF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose

2 Specification

3 Description

4 References

5 Arguments

6 Error Indicators and Warnings

7 Accuracy

8 Parallelism and Performance

9 Further Comments

▸▿ 10 Example

10.1 Program Text

10.2 Program Data

10.3 Program Results

1 Purpose

D03PLF integrates a system of linear or nonlinear convection-diffusion equations in one space dimension, with optional source terms and scope for coupled ordinary differential equations (ODEs). The system must be posed in conservative form. Convection terms are discretized using a sophisticated upwind scheme involving a user-supplied numerical flux function based on the solution of a Riemann problem at each mesh point. The method of lines is employed to reduce the partial differential equations (PDEs) to a system of ODEs, and the resulting system is solved using a backward differentiation formula (BDF) method or a Theta method.

2 Specification

SUBROUTINE D03PLF (

NPDE, TS, TOUT, PDEDEF, NUMFLX, BNDARY, U, NPTS, X, NCODE, ODEDEF, NXI, XI, NEQN, RTOL, ATOL, ITOL, NORM, LAOPT, ALGOPT, RSAVE, LRSAVE, ISAVE, LISAVE, ITASK, ITRACE, IND, IFAIL)

INTEGER

NPDE, NPTS, NCODE, NXI, NEQN, ITOL, LRSAVE, ISAVE(LISAVE), LISAVE, ITASK, ITRACE, IND, IFAIL

REAL (KIND=nag_wp)

TS, TOUT, U(NEQN), X(NPTS), XI(*), RTOL(*), ATOL(*), ALGOPT(30), RSAVE(LRSAVE)

CHARACTER(1)

NORM, LAOPT

EXTERNAL

PDEDEF, NUMFLX, BNDARY, ODEDEF

3 Description

D03PLF integrates the system of convection-diffusion equations in conservative form:

∑j=1 NPDE P i,j ∂Uj ∂t + ∂Fi ∂x =Ci ∂Di ∂x +Si,

(1)

or the hyperbolic convection-only system:

∂Ui ∂t + ∂Fi ∂x =0,

(2)

for i=1,2,…,NPDE,  a≤x≤b,  t≥t 0, where the vector U is the set of PDE solution values

U x,t=U 1 x,t,…,UNPDE x,t T.

The optional coupled ODEs are of the general form

Ri t,V,V.,ξ,U*,Ux*,Ut*=0,  i=1,2,…,NCODE,

(3)

where the vector V is the set of ODE solution values

V t=V 1 t,…,VNCODE t T,

V. denotes its derivative with respect to time, and Ux is the spatial derivative of U.

In (1), P i,j, Fi and Ci depend on x, t, U and V; Di depends on x, t, U, Ux and V; and Si depends on x, t, U, V and linearly on V.. Note that P i,j, Fi, Ci and Si must not depend on any space derivatives, and P i,j, Fi, Ci and Di must not depend on any time derivatives. In terms of conservation laws, Fi, Ci∂Di ∂x and Si are the convective flux, diffusion and source terms respectively.

In (3), ξ represents a vector of nξ spatial coupling points at which the ODEs are coupled to the PDEs. These points may or may not be equal to PDE spatial mesh points. U*, Ux* and Ut* are the functions U, Ux and Ut evaluated at these coupling points. Each Ri may depend only linearly on time derivatives. Hence (3) may be written more precisely as

R=L-M V.-N Ut*,

(4)

where R=R 1,…,RNCODE T, L is a vector of length NCODE, M is an NCODE by NCODE matrix, N is an NCODE by nξ×NPDE matrix and the entries in L, M and N may depend on t, ξ, U*, Ux* and V. In practice you only need to supply a vector of information to define the ODEs and not the matrices L, M and N. (See Section 5 for the specification of ODEDEF.)

The integration in time is from t 0 to tout, over the space interval a≤x≤b, where a=x 1 and b=xNPTS are the leftmost and rightmost points of a user-defined mesh x 1,x 2,…,xNPTS. The initial values of the functions U x,t and V t must be given at t=t 0.

The PDEs are approximated by a system of ODEs in time for the values of Ui at mesh points using a spatial discretization method similar to the central-difference scheme used in D03PCF/D03PCA, D03PHF/D03PHA and D03PPF/D03PPA, but with the flux Fi replaced by a numerical flux, which is a representation of the flux taking into account the direction of the flow of information at that point (i.e., the direction of the characteristics). Simple central differencing of the numerical flux then becomes a sophisticated upwind scheme in which the correct direction of upwinding is automatically achieved.

The numerical flux vector, F^i say, must be calculated by you in terms of the left and right values of the solution vector U (denoted by UL and UR respectively), at each mid-point of the mesh x j-12=x j-1+xj/2, for j=2,3,…,NPTS. The left and right values are calculated by D03PLF from two adjacent mesh points using a standard upwind technique combined with a Van Leer slope-limiter (see LeVeque (1990)). The physically correct value for F^i is derived from the solution of the Riemann problem given by

∂Ui ∂t + ∂Fi ∂y =0,

(5)

where y=x-x j-12, i.e., y=0 corresponds to x=x j-12, with discontinuous initial values U=UL for y<0 and U=UR for y>0, using an approximate Riemann solver. This applies for either of the systems (1) or (2); the numerical flux is independent of the functions P i,j, Ci, Di and Si. A description of several approximate Riemann solvers can be found in LeVeque (1990) and Berzins et al. (1989). Roe's scheme (see Roe (1981)) is perhaps the easiest to understand and use, and a brief summary follows. Consider the system of PDEs Ut+Fx=0 or equivalently Ut+A Ux=0. Provided the system is linear in U, i.e., the Jacobian matrix A does not depend on U, the numerical flux F^ is given by

F^=12 FL+FR-12∑k=1 NPDE αk λk ek,

(6)

where FL (FR) is the flux F calculated at the left (right) value of U, denoted by UL (UR); the λk are the eigenvalues of A; the ek are the right eigenvectors of A; and the αk are defined by

UR - UL = ∑ k=1 NPDE αk ek .

(7)

An example is given in Section 10 and in the D03PFF documentation.

If the system is nonlinear, Roe's scheme requires that a linearized Jacobian is found (see Roe (1981)).

The functions P i,j, Ci, Di and Si (but not Fi) must be specified in PDEDEF. The numerical flux F^i must be supplied in a separate NUMFLX. For problems in the form (2), the actual argument D03PLP may be used for PDEDEF. D03PLP is included in the NAG Library and sets the matrix with entries P i,j to the identity matrix, and the functions Ci, Di and Si to zero.

The boundary condition specification has sufficient flexibility to allow for different types of problems. For second-order problems, i.e., Di depending on Ux, a boundary condition is required for each PDE at both boundaries for the problem to be well-posed. If there are no second-order terms present, then the continuous PDE problem generally requires exactly one boundary condition for each PDE, that is NPDE boundary conditions in total. However, in common with most discretization schemes for first-order problems, a numerical boundary condition is required at the other boundary for each PDE. In order to be consistent with the characteristic directions of the PDE system, the numerical boundary conditions must be derived from the solution inside the domain in some manner (see below). You must supply both types of boundary condition, i.e., a total of NPDE conditions at each boundary point.

The position of each boundary condition should be chosen with care. In simple terms, if information is flowing into the domain then a physical boundary condition is required at that boundary, and a numerical boundary condition is required at the other boundary. In many cases the boundary conditions are simple, e.g., for the linear advection equation. In general you should calculate the characteristics of the PDE system and specify a physical boundary condition for each of the characteristic variables associated with incoming characteristics, and a numerical boundary condition for each outgoing characteristic.

A common way of providing numerical boundary conditions is to extrapolate the characteristic variables from the inside of the domain (note that when using banded matrix algebra the fixed bandwidth means that only linear extrapolation is allowed, i.e., using information at just two interior points adjacent to the boundary). For problems in which the solution is known to be uniform (in space) towards a boundary during the period of integration then extrapolation is unnecessary; the numerical boundary condition can be supplied as the known solution at the boundary. Another method of supplying numerical boundary conditions involves the solution of the characteristic equations associated with the outgoing characteristics. Examples of both methods can be found in Section 10 and in the D03PFF documentation.

The boundary conditions must be specified in BNDARY in the form

GiL x,t,U,V,V.=0  at ​x=a,  i=1,2,…,NPDE,

(8)

at the left-hand boundary, and

GiR x,t,U,V,V.=0  at ​x=b,  i=1,2,…,NPDE,

(9)

at the right-hand boundary.

Note that spatial derivatives at the boundary are not passed explicitly to BNDARY, but they can be calculated using values of U at and adjacent to the boundaries if required. However, it should be noted that instabilities may occur if such one-sided differencing opposes the characteristic direction at the boundary.

The algebraic-differential equation system which is defined by the functions Ri must be specified in ODEDEF. You must also specify the coupling points ξ (if any) in the array XI.

The problem is subject to the following restrictions:

(i)

In (1), V.j t, for j=1,2,…,NCODE, may only appear linearly in the functions Si, for i=1,2,…,NPDE, with a similar restriction for GiL and GiR;

(ii)

P i,j, Fi, Ci and Si must not depend on any space derivatives; and P i,j, Fi, Ci and Di must not depend on any time derivatives;

(iii)

t 0<tout, so that integration is in the forward direction;

(iv)

The evaluation of the terms P i,j, Ci, Di and Si is done by calling the PDEDEF at a point approximately midway between each pair of mesh points in turn. Any discontinuities in these functions must therefore be at one or more of the mesh points x 1,x 2,…,xNPTS;

(v)

At least one of the functions P i,j must be nonzero so that there is a time derivative present in the PDE problem.

In total there are NPDE×NPTS+NCODE ODEs in the time direction. This system is then integrated forwards in time using a BDF or Theta method, optionally switching between Newton's method and functional iteration (see Berzins et al. (1989)).

For further details of the scheme, see Pennington and Berzins (1994) and the references therein.

4 References

Berzins M, Dew P M and Furzeland R M (1989) Developing software for time-dependent problems using the method of lines and differential-algebraic integrators Appl. Numer. Math. 5 375–397

Hirsch C (1990) Numerical Computation of Internal and External Flows, Volume 2: Computational Methods for Inviscid and Viscous Flows John Wiley

LeVeque R J (1990) Numerical Methods for Conservation Laws Birkhäuser Verlag

Pennington S V and Berzins M (1994) New NAG Library software for first-order partial differential equations ACM Trans. Math. Softw. 20 63–99

Roe P L (1981) Approximate Riemann solvers, parameter vectors, and difference schemes J. Comput. Phys. 43 357–372

Sod G A (1978) A survey of several finite difference methods for systems of nonlinear hyperbolic conservation laws J. Comput. Phys. 27 1–31

5 Arguments

1:   NPDE – INTEGERInput

On entry: the number of PDEs to be solved.

Constraint: NPDE≥1.

2:   TS – REAL (KIND=nag_wp)Input/Output

On entry: the initial value of the independent variable t.

On exit: the value of t corresponding to the solution values in U. Normally TS=TOUT.

Constraint: TS<TOUT.

3:   TOUT – REAL (KIND=nag_wp)Input

On entry: the final value of t to which the integration is to be carried out.

4:   PDEDEF – SUBROUTINE, supplied by the NAG Library or the user.External Procedure

PDEDEF must evaluate the functions P i,j, Ci, Di and Si which partially define the system of PDEs. P i,j and Ci may depend on x, t, U and V; Di may depend on x, t, U, Ux and V; and Si may depend on x, t, U, V and linearly on V.. PDEDEF is called approximately midway between each pair of mesh points in turn by D03PLF. The actual argument D03PLP may be used for PDEDEF for problems in the form (2). (D03PLP is included in the NAG Library.)

The specification of PDEDEF is:

SUBROUTINE PDEDEF (

NPDE, T, X, U, UX, NCODE, V, VDOT, P, C, D, S, IRES)

INTEGER

NPDE, NCODE, IRES

REAL (KIND=nag_wp)

T, X, U(NPDE), UX(NPDE), V(NCODE), VDOT(NCODE), P(NPDE,NPDE), C(NPDE), D(NPDE), S(NPDE)

1:   NPDE – INTEGERInput

On entry: the number of PDEs in the system.

2:   T – REAL (KIND=nag_wp)Input

On entry: the current value of the independent variable t.

3:   X – REAL (KIND=nag_wp)Input

On entry: the current value of the space variable x.

4:   U NPDE – REAL (KIND=nag_wp) arrayInput

On entry: U i contains the value of the component Ui x,t, for i=1,2,…,NPDE.

5:   UX NPDE – REAL (KIND=nag_wp) arrayInput

On entry: UX i contains the value of the component ∂Ui x,t ∂x , for i=1,2,…,NPDE.

6:   NCODE – INTEGERInput

On entry: the number of coupled ODEs in the system.

7:   V NCODE – REAL (KIND=nag_wp) arrayInput

On entry: if NCODE>0, V i contains the value of the component Vi t, for i=1,2,…,NCODE.

8:   VDOT NCODE – REAL (KIND=nag_wp) arrayInput

On entry: if NCODE>0, VDOT i contains the value of component V.i t, for i=1,2,…,NCODE.
Note: V.i t, for i=1,2,…,NCODE, may only appear linearly in Sj, for j=1,2,…,NPDE.

9:   P NPDENPDE – REAL (KIND=nag_wp) arrayOutput

On exit: P ij must be set to the value of P i,j x,t,U,V, for i=1,2,…,NPDE and j=1,2,…,NPDE.

10:   C NPDE – REAL (KIND=nag_wp) arrayOutput

On exit: C i must be set to the value of Ci x,t,U,V, for i=1,2,…,NPDE.

11:   D NPDE – REAL (KIND=nag_wp) arrayOutput

On exit: D i must be set to the value of Di x,t,U,Ux,V, for i=1,2,…,NPDE.

12:   S NPDE – REAL (KIND=nag_wp) arrayOutput

On exit: S i must be set to the value of Si x,t,U,V,V., for i=1,2,…,NPDE.

13:   IRES – INTEGERInput/Output

On entry: set to -1​ or ​1.

On exit: should usually remain unchanged. However, you may set IRES to force the integration routine to take certain actions as described below:
IRES=2

Indicates to the integrator that control should be passed back immediately to the calling subroutine with the error indicator set to IFAIL=6.

IRES=3

Indicates to the integrator that the current time step should be abandoned and a smaller time step used instead. You may wish to set IRES=3 when a physically meaningless input or output value has been generated. If you consecutively set IRES=3, then D03PLF returns to the calling subroutine with the error indicator set to IFAIL=4.

PDEDEF must either be a module subprogram USEd by, or declared as EXTERNAL in, the (sub)program from which D03PLF is called. Arguments denoted as Input must not be changed by this procedure.

5:   NUMFLX – SUBROUTINE, supplied by the user.External Procedure

NUMFLX must supply the numerical flux for each PDE given the left and right values of the solution vector U. NUMFLX is called approximately midway between each pair of mesh points in turn by D03PLF.

The specification of NUMFLX is:

SUBROUTINE NUMFLX (

NPDE, T, X, NCODE, V, ULEFT, URIGHT, FLUX, IRES)

INTEGER

NPDE, NCODE, IRES

REAL (KIND=nag_wp)

T, X, V(NCODE), ULEFT(NPDE), URIGHT(NPDE), FLUX(NPDE)

1:   NPDE – INTEGERInput

On entry: the number of PDEs in the system.

2:   T – REAL (KIND=nag_wp)Input

On entry: the current value of the independent variable t.

3:   X – REAL (KIND=nag_wp)Input

On entry: the current value of the space variable x.

4:   NCODE – INTEGERInput

On entry: the number of coupled ODEs in the system.

5:   V NCODE – REAL (KIND=nag_wp) arrayInput

On entry: if NCODE>0, V i contains the value of the component Vi t, for i=1,2,…,NCODE.

6:   ULEFT NPDE – REAL (KIND=nag_wp) arrayInput

On entry: ULEFT i contains the left value of the component Ui x, for i=1,2,…,NPDE.

7:   URIGHT NPDE – REAL (KIND=nag_wp) arrayInput

On entry: URIGHT i contains the right value of the component Ui x, for i=1,2,…,NPDE.

8:   FLUX NPDE – REAL (KIND=nag_wp) arrayOutput

On exit: FLUX i must be set to the numerical flux F^i, for i=1,2,…,NPDE.

9:   IRES – INTEGERInput/Output

On entry: set to -1​ or ​1.

On exit: should usually remain unchanged. However, you may set IRES to force the integration routine to take certain actions as described below:
IRES=2

Indicates to the integrator that control should be passed back immediately to the calling subroutine with the error indicator set to IFAIL=6.

IRES=3

Indicates to the integrator that the current time step should be abandoned and a smaller time step used instead. You may wish to set IRES=3 when a physically meaningless input or output value has been generated. If you consecutively set IRES=3, then D03PLF returns to the calling subroutine with the error indicator set to IFAIL=4.

NUMFLX must either be a module subprogram USEd by, or declared as EXTERNAL in, the (sub)program from which D03PLF is called. Arguments denoted as Input must not be changed by this procedure.

6:   BNDARY – SUBROUTINE, supplied by the user.External Procedure

BNDARY must evaluate the functions GiL and GiR which describe the physical and numerical boundary conditions, as given by (8) and (9).

The specification of BNDARY is:

SUBROUTINE BNDARY (

NPDE, NPTS, T, X, U, NCODE, V, VDOT, IBND, G, IRES)

INTEGER

NPDE, NPTS, NCODE, IBND, IRES

REAL (KIND=nag_wp)

T, X(NPTS), U(NPDE,NPTS), V(NCODE), VDOT(NCODE), G(NPDE)

1:   NPDE – INTEGERInput

On entry: the number of PDEs in the system.

2:   NPTS – INTEGERInput

On entry: the number of mesh points in the interval a,b.

3:   T – REAL (KIND=nag_wp)Input

On entry: the current value of the independent variable t.

4:   X NPTS – REAL (KIND=nag_wp) arrayInput

On entry: the mesh points in the spatial direction. X 1 corresponds to the left-hand boundary, a, and X NPTS corresponds to the right-hand boundary, b.

5:   U NPDENPTS – REAL (KIND=nag_wp) arrayInput

On entry: U ij contains the value of the component Ui x,t at x=X j, for i=1,2,…,NPDE and j=1,2,…,NPTS.
Note: if banded matrix algebra is to be used then the functions GiL and GiR may depend on the value of Ui x,t at the boundary point and the two adjacent points only.

6:   NCODE – INTEGERInput

On entry: the number of coupled ODEs in the system.

7:   V NCODE – REAL (KIND=nag_wp) arrayInput

On entry: if NCODE>0, V i contains the value of the component Vi t, for i=1,2,…,NCODE.

8:   VDOT NCODE – REAL (KIND=nag_wp) arrayInput

On entry: if NCODE>0, VDOT i contains the value of component V.i t, for i=1,2,…,NCODE.
Note: V.i t, for i=1,2,…,NCODE, may only appear linearly in GjL and GjR, for j=1,2,…,NPDE.

9:   IBND – INTEGERInput

On entry: specifies which boundary conditions are to be evaluated.
IBND=0

BNDARY must evaluate the left-hand boundary condition at x=a.

IBND≠0

BNDARY must evaluate the right-hand boundary condition at x=b.

10:   G NPDE – REAL (KIND=nag_wp) arrayOutput

On exit: G i must contain the ith component of either GiL or GiR in (8) and (9), depending on the value of IBND, for i=1,2,…,NPDE.

11:   IRES – INTEGERInput/Output

On entry: set to -1​ or ​1.

On exit: should usually remain unchanged. However, you may set IRES to force the integration routine to take certain actions as described below:
IRES=2

Indicates to the integrator that control should be passed back immediately to the calling subroutine with the error indicator set to IFAIL=6.

IRES=3

Indicates to the integrator that the current time step should be abandoned and a smaller time step used instead. You may wish to set IRES=3 when a physically meaningless input or output value has been generated. If you consecutively set IRES=3, then D03PLF returns to the calling subroutine with the error indicator set to IFAIL=4.

BNDARY must either be a module subprogram USEd by, or declared as EXTERNAL in, the (sub)program from which D03PLF is called. Arguments denoted as Input must not be changed by this procedure.

7:   U NEQN – REAL (KIND=nag_wp) arrayInput/Output

On entry: the initial values of the dependent variables defined as follows:

U NPDE×j-1+i contain Ui xj,t 0, for i=1,2,…,NPDE and j=1,2,…,NPTS, and

U NPTS×NPDE+k contain Vk t 0, for k=1,2,…,NCODE.

On exit: the computed solution Ui xj,t, for i=1,2,…,NPDE and j=1,2,…,NPTS, and Vk t, for k=1,2,…,NCODE, all evaluated at t=TS.

8:   NPTS – INTEGERInput

On entry: the number of mesh points in the interval a,b.

Constraint: NPTS≥3.

9:   X NPTS – REAL (KIND=nag_wp) arrayInput

On entry: the mesh points in the space direction. X 1 must specify the left-hand boundary, a, and X NPTS must specify the right-hand boundary, b.

Constraint: X 1<X 2<⋯<X NPTS.

10:   NCODE – INTEGERInput

On entry: the number of coupled ODE components.

Constraint: NCODE≥0.

11:   ODEDEF – SUBROUTINE, supplied by the NAG Library or the user.External Procedure

ODEDEF must evaluate the functions R, which define the system of ODEs, as given in (4).

If you wish to compute the solution of a system of PDEs only (i.e., NCODE=0), ODEDEF must be the dummy routine D03PEK. (D03PEK is included in the NAG Library.)

The specification of ODEDEF is:

SUBROUTINE ODEDEF (

NPDE, T, NCODE, V, VDOT, NXI, XI, UCP, UCPX, UCPT, R, IRES)

INTEGER

NPDE, NCODE, NXI, IRES

REAL (KIND=nag_wp)

T, V(NCODE), VDOT(NCODE), XI(NXI), UCP(NPDE,*), UCPX(NPDE,*), UCPT(NPDE,*), R(NCODE)

1:   NPDE – INTEGERInput

On entry: the number of PDEs in the system.

2:   T – REAL (KIND=nag_wp)Input

On entry: the current value of the independent variable t.

3:   NCODE – INTEGERInput

On entry: the number of coupled ODEs in the system.

4:   V NCODE – REAL (KIND=nag_wp) arrayInput

On entry: if NCODE>0, V i contains the value of the component Vi t, for i=1,2,…,NCODE.

5:   VDOT NCODE – REAL (KIND=nag_wp) arrayInput

On entry: if NCODE>0, VDOT i contains the value of component V.i t, for i=1,2,…,NCODE.

6:   NXI – INTEGERInput

On entry: the number of ODE/PDE coupling points.

7:   XI NXI – REAL (KIND=nag_wp) arrayInput

On entry: if NXI>0, XI i contains the ODE/PDE coupling point, ξi, for i=1,2,…,NXI.

8:   UCP NPDE* – REAL (KIND=nag_wp) arrayInput

On entry: if NXI>0, UCP ij contains the value of Ui x,t at the coupling point x=ξj, for i=1,2,…,NPDE and j=1,2,…,NXI.

9:   UCPX NPDE* – REAL (KIND=nag_wp) arrayInput

On entry: if NXI>0, UCPX ij contains the value of ∂Ui x,t ∂x at the coupling point x=ξj, for i=1,2,…,NPDE and j=1,2,…,NXI.

10:   UCPT NPDE* – REAL (KIND=nag_wp) arrayInput

On entry: if NXI>0, UCPT ij contains the value of ∂Ui ∂t at the coupling point x=ξj, for i=1,2,…,NPDE and j=1,2,…,NXI.

11:   R NCODE – REAL (KIND=nag_wp) arrayOutput

On exit: R i must contain the ith component of R, for i=1,2,…,NCODE, where R is defined as

R=L-M V.-N Ut*,

(10)

or

R=-M V.-N Ut*.

(11)

The definition of R is determined by the input value of IRES.

12:   IRES – INTEGERInput/Output

On entry: the form of R that must be returned in the array R.
IRES=1

Equation (10) must be used.

IRES=-1

Equation (11) must be used.

On exit: should usually remain unchanged. However, you may reset IRES to force the integration routine to take certain actions, as described below:
IRES=2

Indicates to the integrator that control should be passed back immediately to the calling (sub)routine with the error indicator set to IFAIL=6.

IRES=3

Indicates to the integrator that the current time step should be abandoned and a smaller time step used instead. You may wish to set IRES=3 when a physically meaningless input or output value has been generated. If you consecutively set IRES=3, then D03PLF returns to the calling subroutine with the error indicator set to IFAIL=4.

ODEDEF must either be a module subprogram USEd by, or declared as EXTERNAL in, the (sub)program from which D03PLF is called. Arguments denoted as Input must not be changed by this procedure.

12:   NXI – INTEGERInput

On entry: the number of ODE/PDE coupling points.

Constraints:

if NCODE=0, NXI=0;

if NCODE>0, NXI≥0.

13:   XI* – REAL (KIND=nag_wp) arrayInput

Note: the dimension of the array XI must be at least max 1,NXI.

On entry: XI i, for i=1,2,…,NXI, must be set to the ODE/PDE coupling points.

Constraint: X 1≤XI 1<XI 2<⋯<XI NXI≤X NPTS.

14:   NEQN – INTEGERInput

On entry: the number of ODEs in the time direction.

Constraint: NEQN=NPDE×NPTS+NCODE.

15:   RTOL* – REAL (KIND=nag_wp) arrayInput

Note: the dimension of the array RTOL must be at least 1 if ITOL=1 or 2 and at least NEQN if ITOL=3 or 4.

On entry: the relative local error tolerance.

Constraint: RTOL i≥0.0 for all relevant i.

16:   ATOL* – REAL (KIND=nag_wp) arrayInput

Note: the dimension of the array ATOL must be at least 1 if ITOL=1 or 3 and at least NEQN if ITOL=2 or 4.

On entry: the absolute local error tolerance.

Constraint: ATOL i≥0.0 for all relevant i.
Note: corresponding elements of RTOL and ATOL cannot both be 0.0.

17:   ITOL – INTEGERInput

On entry: a value to indicate the form of the local error test. If ei is the estimated local error for U i, for i=1,2,…,NEQN, and   denotes the norm, then the error test to be satisfied is ei<1.0. ITOL indicates to D03PLF whether to interpret either or both of RTOL and ATOL as a vector or scalar in the formation of the weights wi used in the calculation of the norm (see the description of NORM):

ITOL

RTOL

ATOL

wi

1

scalar

scalar

RTOL 1×U i+ATOL 1

2

scalar

vector

RTOL 1×U i+ATOL i

3

vector

scalar

RTOL i×U i+ATOL 1

4

vector

vector

RTOL i×U i+ATOL i

Constraint: 1≤ITOL≤4.

18:   NORM – CHARACTER(1)Input

On entry: the type of norm to be used.
NORM='1'

Averaged L 1 norm.

NORM='2'

Averaged L 2 norm.

If Unorm denotes the norm of the vector U of length NEQN, then for the averaged L 1 norm

U norm=1 NEQN∑i=1 NEQN U i/wi,

and for the averaged L 2 norm

U norm=1 NEQN∑i=1 NEQN U i/wi 2.

See the description of ITOL for the formulation of the weight vector w.

Constraint: NORM='1' or '2'.

19:   LAOPT – CHARACTER(1)Input

On entry: the type of matrix algebra required.
LAOPT='F'

Full matrix methods to be used.

LAOPT='B'

Banded matrix methods to be used.

LAOPT='S'

Sparse matrix methods to be used.

Constraint: LAOPT='F', 'B' or 'S'.

Note: you are recommended to use the banded option when no coupled ODEs are present (NCODE=0). Also, the banded option should not be used if the boundary conditions involve solution components at points other than the boundary and the immediately adjacent two points.

20:   ALGOPT 30 – REAL (KIND=nag_wp) arrayInput

On entry: may be set to control various options available in the integrator. If you wish to employ all the default options, then ALGOPT 1 should be set to 0.0. Default values will also be used for any other elements of ALGOPT set to zero. The permissible values, default values, and meanings are as follows:
ALGOPT 1

Selects the ODE integration method to be used. If ALGOPT 1=1.0, a BDF method is used and if ALGOPT 1=2.0, a Theta method is used. The default is ALGOPT 1=1.0.

If ALGOPT 1=2.0, then ALGOPT i, for i=2,3,4, are not used.

ALGOPT 2

Specifies the maximum order of the BDF integration formula to be used. ALGOPT 2 may be 1.0, 2.0, 3.0, 4.0 or 5.0. The default value is ALGOPT 2=5.0.

ALGOPT 3

Specifies what method is to be used to solve the system of nonlinear equations arising on each step of the BDF method. If ALGOPT 3=1.0 a modified Newton iteration is used and if ALGOPT 3=2.0 a functional iteration method is used. If functional iteration is selected and the integrator encounters difficulty, then there is an automatic switch to the modified Newton iteration. The default value is ALGOPT 3=1.0.

ALGOPT 4

Specifies whether or not the Petzold error test is to be employed. The Petzold error test results in extra overhead but is more suitable when algebraic equations are present, such as P i,j=0.0, for j=1,2,…,NPDE, for some i or when there is no V.i t dependence in the coupled ODE system. If ALGOPT 4=1.0, then the Petzold test is used. If ALGOPT 4=2.0, then the Petzold test is not used. The default value is ALGOPT 4=1.0.

If ALGOPT 1=1.0, then ALGOPT i, for i=5,6,7, are not used.

ALGOPT 5

Specifies the value of Theta to be used in the Theta integration method. 0.51≤ALGOPT 5≤0.99. The default value is ALGOPT 5=0.55.

ALGOPT 6

Specifies what method is to be used to solve the system of nonlinear equations arising on each step of the Theta method. If ALGOPT 6=1.0, a modified Newton iteration is used and if ALGOPT 6=2.0, a functional iteration method is used. The default value is ALGOPT 6=1.0.

ALGOPT 7

Specifies whether or not the integrator is allowed to switch automatically between modified Newton and functional iteration methods in order to be more efficient. If ALGOPT 7=1.0, then switching is allowed and if ALGOPT 7=2.0, then switching is not allowed. The default value is ALGOPT 7=1.0.

ALGOPT 11

Specifies a point in the time direction, tcrit, beyond which integration must not be attempted. The use of tcrit is described under the argument ITASK. If ALGOPT 1≠0.0, a value of 0.0 for ALGOPT 11, say, should be specified even if ITASK subsequently specifies that tcrit will not be used.

ALGOPT 12

Specifies the minimum absolute step size to be allowed in the time integration. If this option is not required, ALGOPT 12 should be set to 0.0.

ALGOPT 13

Specifies the maximum absolute step size to be allowed in the time integration. If this option is not required, ALGOPT 13 should be set to 0.0.

ALGOPT 14

Specifies the initial step size to be attempted by the integrator. If ALGOPT 14=0.0, then the initial step size is calculated internally.

ALGOPT 15

Specifies the maximum number of steps to be attempted by the integrator in any one call. If ALGOPT 15=0.0, then no limit is imposed.

ALGOPT 23

Specifies what method is to be used to solve the nonlinear equations at the initial point to initialize the values of U, Ut, V and V.. If ALGOPT 23=1.0, a modified Newton iteration is used and if ALGOPT 23=2.0, functional iteration is used. The default value is ALGOPT 23=1.0.

ALGOPT 29 and ALGOPT 30 are used only for the sparse matrix algebra option, i.e., LAOPT='S'.

ALGOPT 29

Governs the choice of pivots during the decomposition of the first Jacobian matrix. It should lie in the range 0.0<ALGOPT 29<1.0, with smaller values biasing the algorithm towards maintaining sparsity at the expense of numerical stability. If ALGOPT 29 lies outside the range then the default value is used. If the routines regard the Jacobian matrix as numerically singular, then increasing ALGOPT 29 towards 1.0 may help, but at the cost of increased fill-in. The default value is ALGOPT 29=0.1.

ALGOPT 30

Used as the relative pivot threshold during subsequent Jacobian decompositions (see ALGOPT 29) below which an internal error is invoked. ALGOPT 30 must be greater than zero, otherwise the default value is used. If ALGOPT 30 is greater than 1.0 no check is made on the pivot size, and this may be a necessary option if the Jacobian matrix is found to be numerically singular (see ALGOPT 29). The default value is ALGOPT 30=0.0001.

21:   RSAVE LRSAVE – REAL (KIND=nag_wp) arrayCommunication Array

If IND=0, RSAVE need not be set on entry.

If IND=1, RSAVE must be unchanged from the previous call to the routine because it contains required information about the iteration.

22:   LRSAVE – INTEGERInput

On entry: the dimension of the array RSAVE as declared in the (sub)program from which D03PLF is called. Its size depends on the type of matrix algebra selected.
If LAOPT='F', LRSAVE≥NEQN×NEQN+NEQN+nwkres+lenode.

If LAOPT='B', LRSAVE≥3×mlu+1×NEQN+nwkres+lenode.

If LAOPT='S', LRSAVE≥4×NEQN+11×NEQN/2+1+nwkres+lenode.

Where

mlu is the lower or upper half bandwidths such that
mlu=3×NPDE-1, for PDE problems only (no coupled ODEs); or
mlu=NEQN-1, for coupled PDE/ODE problems.

nwkres= NPDE×2×NPTS+6×NXI+3×NPDE+26+NXI+NCODE+7×NPTS+2, when ​NCODE>0​ and ​NXI>0; NPDE×2×NPTS+3×NPDE+32+NCODE+7×NPTS+3, when ​NCODE>0​ and ​NXI=0; NPDE×2×NPTS+3×NPDE+32+7×NPTS+4, when ​NCODE=0.

lenode= 6+int ALGOPT 2×NEQN+50, when the BDF method is used; or 9×NEQN+50, when the Theta method is used.

Note: when LAOPT='S', the value of LRSAVE may be too small when supplied to the integrator. An estimate of the minimum size of LRSAVE is printed on the current error message unit if ITRACE>0 and the routine returns with IFAIL=15.

23:   ISAVE LISAVE – INTEGER arrayCommunication Array

If IND=0, ISAVE need not be set.

If IND=1, ISAVE must be unchanged from the previous call to the routine because it contains required information about the iteration. In particular the following components of the array ISAVE concern the efficiency of the integration:
ISAVE 1

Contains the number of steps taken in time.

ISAVE 2

Contains the number of residual evaluations of the resulting ODE system used. One such evaluation involves evaluating the PDE functions at all the mesh points, as well as one evaluation of the functions in the boundary conditions.

ISAVE 3

Contains the number of Jacobian evaluations performed by the time integrator.

ISAVE 4

Contains the order of the BDF method last used in the time integration, if applicable. When the Theta method is used, ISAVE 4 contains no useful information.

ISAVE 5

Contains the number of Newton iterations performed by the time integrator. Each iteration involves residual evaluation of the resulting ODE system followed by a back-substitution using the LU decomposition of the Jacobian matrix.

24:   LISAVE – INTEGERInput

On entry: the dimension of the array ISAVE as declared in the (sub)program from which D03PLF is called. Its size depends on the type of matrix algebra selected:

if LAOPT='F', LISAVE≥24;

if LAOPT='B', LISAVE≥NEQN+24;

if LAOPT='S', LISAVE≥25×NEQN+24.

Note: when using the sparse option, the value of LISAVE may be too small when supplied to the integrator. An estimate of the minimum size of LISAVE is printed on the current error message unit if ITRACE>0 and the routine returns with IFAIL=15.

25:   ITASK – INTEGERInput

On entry: the task to be performed by the ODE integrator.
ITASK=1

Normal computation of output values U at t=TOUT (by overshooting and interpolating).

ITASK=2

Take one step in the time direction and return.

ITASK=3

Stop at first internal integration point at or beyond t=TOUT.

ITASK=4

Normal computation of output values U at t=TOUT but without overshooting t=tcrit where tcrit is described under the argument ALGOPT.

ITASK=5

Take one step in the time direction and return, without passing tcrit, where tcrit is described under the argument ALGOPT.

Constraint: ITASK=1, 2, 3, 4 or 5.

26:   ITRACE – INTEGERInput

On entry: the level of trace information required from D03PLF and the underlying ODE solver. ITRACE may take the value -1, 0, 1, 2 or 3.
ITRACE=-1

No output is generated.

ITRACE=0

Only warning messages from the PDE solver are printed on the current error message unit (see X04AAF).

ITRACE>0

Output from the underlying ODE solver is printed on the current advisory message unit (see X04ABF). This output contains details of Jacobian entries, the nonlinear iteration and the time integration during the computation of the ODE system.

If ITRACE<-1, then -1 is assumed and similarly if ITRACE>3, then 3 is assumed.

The advisory messages are given in greater detail as ITRACE increases. You are advised to set ITRACE=0, unless you are experienced with Sub-chapter D02M–N.

27:   IND – INTEGERInput/Output

On entry: indicates whether this is a continuation call or a new integration.
IND=0

Starts or restarts the integration in time.

IND=1

Continues the integration after an earlier exit from the routine. In this case, only the arguments TOUT and IFAIL should be reset between calls to D03PLF.

Constraint: IND=0 or 1.

On exit: IND=1.

28:   IFAIL – INTEGERInput/Output

On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.

On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).

Errors or warnings detected by the routine:

IFAIL=1

On entry,

TS≥TOUT,

or

TOUT-TS is too small,

or

ITASK≠1, 2, 3, 4 or 5,

or

at least one of the coupling points defined in array XI is outside the interval [X 1,X NPTS],

or

the coupling points are not in strictly increasing order,

or

NPTS<3,

or

NPDE<1,

or

LAOPT≠'F', 'B' or 'S',

or

ITOL≠1, 2, 3 or 4,

or

IND≠0 or 1,

or

mesh points X i are badly ordered,

or

LRSAVE or LISAVE are too small,

or

NCODE and NXI are incorrectly defined,

or

IND=1 on initial entry to D03PLF,

or

NEQN≠NPDE×NPTS+NCODE,

or

an element of RTOL or ATOL<0.0,

or

corresponding elements of RTOL and ATOL are both 0.0,

or

NORM≠1 or 2.

IFAIL=2

The underlying ODE solver cannot make any further progress, with the values of ATOL and RTOL, across the integration range from the current point t=TS. The components of U contain the computed values at the current point t=TS.

IFAIL=3

In the underlying ODE solver, there were repeated error test failures on an attempted step, before completing the requested task, but the integration was successful as far as t=TS. The problem may have a singularity, or the error requirement may be inappropriate. Incorrect specification of boundary conditions may also result in this error.

IFAIL=4

In setting up the ODE system, the internal initialization routine was unable to initialize the derivative of the ODE system. This could be due to the fact that IRES was repeatedly set to 3 in one of PDEDEF, NUMFLX, BNDARY or ODEDEF, when the residual in the underlying ODE solver was being evaluated. Incorrect specification of boundary conditions may also result in this error.

IFAIL=5

In solving the ODE system, a singular Jacobian has been encountered. Check the problem formulation.

IFAIL=6

When evaluating the residual in solving the ODE system, IRES was set to 2 in at least one of PDEDEF, NUMFLX, BNDARY or ODEDEF. Integration was successful as far as t=TS.

IFAIL=7

The values of ATOL and RTOL are so small that the routine is unable to start the integration in time.

IFAIL=8

In either, PDEDEF, NUMFLX, BNDARY or ODEDEF, IRES was set to an invalid value.

IFAIL=9 (D02NNF)

A serious error has occurred in an internal call to the specified routine. Check the problem specification and all arguments and array dimensions. Setting ITRACE=1 may provide more information. If the problem persists, contact NAG.

IFAIL=10

The required task has been completed, but it is estimated that a small change in ATOL and RTOL is unlikely to produce any change in the computed solution. (Only applies when you are not operating in one step mode, that is when ITASK≠2 or 5.)

IFAIL=11

An error occurred during Jacobian formulation of the ODE system (a more detailed error description may be directed to the current advisory message unit when ITRACE≥1). If using the sparse matrix algebra option, the values of ALGOPT 29 and ALGOPT 30 may be inappropriate.

IFAIL=12

In solving the ODE system, the maximum number of steps specified in ALGOPT 15 has been taken.

IFAIL=13

Some error weights wi became zero during the time integration (see the description of ITOL). Pure relative error control (ATOL i=0.0) was requested on a variable (the ith) which has become zero. The integration was successful as far as t=TS.

IFAIL=14

One or more of the functions P i,j, Di or Ci was detected as depending on time derivatives, which is not permissible.

IFAIL=15

When using the sparse option, the value of LISAVE or LRSAVE was not sufficient (more detailed information may be directed to the current error message unit).

IFAIL=-99

An unexpected error has been triggered by this routine. Please contact NAG.

See Section 3.9 in How to Use the NAG Library and its Documentation for further information.

IFAIL=-399

Your licence key may have expired or may not have been installed correctly.

See Section 3.8 in How to Use the NAG Library and its Documentation for further information.

IFAIL=-999

Dynamic memory allocation failed.

See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

D03PLF controls the accuracy of the integration in the time direction but not the accuracy of the approximation in space. The spatial accuracy depends on both the number of mesh points and on their distribution in space. In the time integration only the local error over a single step is controlled and so the accuracy over a number of steps cannot be guaranteed. You should therefore test the effect of varying the accuracy arguments, ATOL and RTOL.

8 Parallelism and Performance

D03PLF is not thread safe and should not be called from a multithreaded user program. Please see Section 3.12.1 in How to Use the NAG Library and its Documentation for more information on thread safety.

D03PLF is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.

D03PLF makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.

Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

D03PLF is designed to solve systems of PDEs in conservative form, with optional source terms which are independent of space derivatives, and optional second-order diffusion terms. The use of the routine to solve systems which are not naturally in this form is discouraged, and you are advised to use one of the central-difference schemes for such problems.

You should be aware of the stability limitations for hyperbolic PDEs. For most problems with small error tolerances the ODE integrator does not attempt unstable time steps, but in some cases a maximum time step should be imposed using ALGOPT 13. It is worth experimenting with this argument, particularly if the integration appears to progress unrealistically fast (with large time steps). Setting the maximum time step to the minimum mesh size is a safe measure, although in some cases this may be too restrictive.

Problems with source terms should be treated with caution, as it is known that for large source terms stable and reasonable looking solutions can be obtained which are in fact incorrect, exhibiting non-physical speeds of propagation of discontinuities (typically one spatial mesh point per time step). It is essential to employ a very fine mesh for problems with source terms and discontinuities, and to check for non-physical propagation speeds by comparing results for different mesh sizes. Further details and an example can be found in Pennington and Berzins (1994).

The time taken depends on the complexity of the system and on the accuracy requested. For a given system and a fixed accuracy it is approximately proportional to NEQN.

10 Example

For this routine two examples are presented, with a main program and two example problems given in Example 1 (EX1) and Example 2 (EX2).

Example 1 (EX1)

This example is a simple first-order system with coupled ODEs arising from the use of the characteristic equations for the numerical boundary conditions.

The PDEs are

∂U 1 ∂t + ∂U 1 ∂x +2 ∂U 2 ∂x =0, ∂U 2 ∂t +2 ∂U 1 ∂x + ∂U 2 ∂x =0,

for x∈0,1 and t≥0.

The PDEs have an exact solution given by

U 1 x,t=f x-3 t+g x+t,   U 2 x,t=f x-3 t-g x+t,

where f z=exp πzsin 2 πz, g z=exp-2 πzcos 2 πz.

The initial conditions are given by the exact solution.

The characteristic variables are W 1=U 1-U 2 and W 2=U 1+U 2, corresponding to the characteristics given by dx/dt=-1 and dx/dt=3 respectively. Hence we require a physical boundary condition for W 2 at the left-hand boundary and for W 1 at the right-hand boundary (corresponding to the incoming characteristics), and a numerical boundary condition for W 1 at the left-hand boundary and for W 2 at the right-hand boundary (outgoing characteristics).

The physical boundary conditions are obtained from the exact solution, and the numerical boundary conditions are supplied in the form of the characteristic equations for the outgoing characteristics, that is

∂W 1 ∂t - ∂W 1 ∂x =0

at the left-hand boundary, and

∂W 2 ∂t + 3 ∂W 2 ∂x =0

at the right-hand boundary.

In order to specify these boundary conditions, two ODE variables V 1 and V 2 are introduced, defined by

V 1 t=W 1 0,t=U 1 0,t-U 2 0,t, V 2 t=W 2 1,t=U 1 1,t+U 2 1,t.

The coupling points are therefore at x=0 and x=1.

The numerical boundary conditions are now

V.1- ∂W 1 ∂x =0

at the left-hand boundary, and

V.2+ 3 ∂W 2 ∂x =0

at the right-hand boundary.

The spatial derivatives are evaluated at the appropriate boundary points in BNDARY using one-sided differences (into the domain and therefore consistent with the characteristic directions).

The numerical flux is calculated using Roe's approximate Riemann solver (see Section 3 for details), giving

F^=12 3 U 1 L-U 1 R+3 U 2 L+U 2 R 3 U 1 L+U 1 R+3 U 2 L-U 2 R .

Example 2 (EX2)

This example is the standard shock-tube test problem proposed by Sod (1978) for the Euler equations of gas dynamics. The problem models the flow of a gas in a long tube following the sudden breakdown of a diaphragm separating two initial gas states at different pressures and densities. There is an exact solution to this problem which is not included explicitly as the calculation is quite lengthy. The PDEs are

∂ρ ∂t + ∂m ∂x = 0, ∂m ∂t + ∂∂x m 2 ρ+γ- 1 e-m 2 2 ρ = 0, ∂e ∂t + ∂∂x m e ρ+mρ γ- 1 e-m 2 2 ρ = 0,

where ρ is the density; m is the momentum, such that m=ρu, where u is the velocity; e is the specific energy; and γ is the (constant) ratio of specific heats. The pressure p is given by

p=γ-1 e-ρ u 2 2 .

The solution domain is 0≤x≤1 for 0<t≤0.2, with the initial discontinuity at x=0.5, and initial conditions

ρ x,0=1, m x,0=0, e x,0=2.5,   for ​x<0.5, ρ x,0=0.125, m x,0=0, e x,0=0.25,   for ​x>0.5.

The solution is uniform and constant at both boundaries for the spatial domain and time of integration stated, and hence the physical and numerical boundary conditions are indistinguishable and are both given by the initial conditions above. The evaluation of the numerical flux for the Euler equations is not trivial; the Roe algorithm given in Section 3 cannot be used directly as the Jacobian is nonlinear. However, an algorithm is available using the argument-vector method (see Roe (1981)), and this is provided in the utility routine D03PUF. An alternative Approxiate Riemann Solver using Osher's scheme is provided in D03PVF. Either D03PUF or D03PVF can be called from NUMFLX.

10.1 Program Text

Program Text (d03plfe.f90)

10.2 Program Data

Program Data (d03plfe.d)

10.3 Program Results

Program Results (d03plfe.r)

D03 Chapter Contents

D03 Chapter Introduction

NAG Library Manual

© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


D03PPF/D03PPA : NAG Library, Mark 26

D03 Chapter Contents

D03 Chapter Introduction

NAG Library Manual

NAG Library Routine Document

D03PPF/D03PPA

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose

▸▿ 2 Specification

2.1 Specification for D03PPF

2.2 Specification for D03PPA

3 Description

4 References

5 Arguments

6 Error Indicators and Warnings

7 Accuracy

8 Parallelism and Performance

9 Further Comments

▸▿ 10 Example

10.1 Program Text

10.2 Program Data

10.3 Program Results

1 Purpose

D03PPF/D03PPA integrates a system of linear or nonlinear parabolic partial differential equations (PDEs) in one space variable, with scope for coupled ordinary differential equations (ODEs), and automatic adaptive spatial remeshing. The spatial discretization is performed using finite differences, and the method of lines is employed to reduce the PDEs to a system of ODEs. The resulting system is solved using a Backward Differentiation Formula (BDF) method or a Theta method (switching between Newton's method and functional iteration).

D03PPA is a version of D03PPF that has additional arguments in order to make it safe for use in multithreaded applications (see Section 5).

2 Specification

2.1 Specification for D03PPF

SUBROUTINE D03PPF (

NPDE, M, TS, TOUT, PDEDEF, BNDARY, UVINIT, U, NPTS, X, NCODE, ODEDEF, NXI, XI, NEQN, RTOL, ATOL, ITOL, NORM, LAOPT, ALGOPT, REMESH, NXFIX, XFIX, NRMESH, DXMESH, TRMESH, IPMINF, XRATIO, CON, MONITF, RSAVE, LRSAVE, ISAVE, LISAVE, ITASK, ITRACE, IND, IFAIL)

INTEGER

NPDE, M, NPTS, NCODE, NXI, NEQN, ITOL, NXFIX, NRMESH, IPMINF, LRSAVE, ISAVE(LISAVE), LISAVE, ITASK, ITRACE, IND, IFAIL

REAL (KIND=nag_wp)

TS, TOUT, U(NEQN), X(NPTS), XI(NXI), RTOL(*), ATOL(*), ALGOPT(30), XFIX(*), DXMESH, TRMESH, XRATIO, CON, RSAVE(LRSAVE)

LOGICAL

REMESH

CHARACTER(1)

NORM, LAOPT

EXTERNAL

PDEDEF, BNDARY, UVINIT, ODEDEF, MONITF

2.2 Specification for D03PPA

SUBROUTINE D03PPA (

NPDE, M, TS, TOUT, PDEDEF, BNDARY, UVINIT, U, NPTS, X, NCODE, ODEDEF, NXI, XI, NEQN, RTOL, ATOL, ITOL, NORM, LAOPT, ALGOPT, REMESH, NXFIX, XFIX, NRMESH, DXMESH, TRMESH, IPMINF, XRATIO, CON, MONITF, RSAVE, LRSAVE, ISAVE, LISAVE, ITASK, ITRACE, IND, IUSER, RUSER, CWSAV, LWSAV, IWSAV, RWSAV, IFAIL)

INTEGER

NPDE, M, NPTS, NCODE, NXI, NEQN, ITOL, NXFIX, NRMESH, IPMINF, LRSAVE, ISAVE(LISAVE), LISAVE, ITASK, ITRACE, IND, IUSER(*), IWSAV(505), IFAIL

REAL (KIND=nag_wp)

TS, TOUT, U(NEQN), X(NPTS), XI(NXI), RTOL(*), ATOL(*), ALGOPT(30), XFIX(*), DXMESH, TRMESH, XRATIO, CON, RSAVE(LRSAVE), RUSER(*), RWSAV(1100)

LOGICAL

REMESH, LWSAV(100)

CHARACTER(1)

NORM, LAOPT

CHARACTER(80)

CWSAV(10)

EXTERNAL

PDEDEF, BNDARY, UVINIT, ODEDEF, MONITF

3 Description

D03PPF/D03PPA integrates the system of parabolic-elliptic equations and coupled ODEs

∑j=1 NPDE P i,j ∂Uj ∂t +Qi=x-m ∂∂x xm Ri,  i=1,2,…,NPDE ,   a≤x≤b,t≥t 0,

(1)

Fi t,V,V.,ξ,U*,Ux*,R*,Ut*,U xt*=0,  i=1,2,…,NCODE,

(2)

where (1) defines the PDE part and (2) generalizes the coupled ODE part of the problem.

In (1), P i,j and Ri depend on x, t, U, Ux, and V; Qi depends on x, t, U, Ux, V and linearly on V.. The vector U is the set of PDE solution values

U x,t=U 1 x,t,…,UNPDE x,t T,

and the vector Ux is the partial derivative with respect to x. The vector V is the set of ODE solution values

V t=V 1 t,…,VNCODE t T,

and V. denotes its derivative with respect to time.

In (2), ξ represents a vector of nξ spatial coupling points at which the ODEs are coupled to the PDEs. These points may or may not be equal to some of the PDE spatial mesh points. U*, Ux*, R*, Ut* and U xt* are the functions U, Ux, R, Ut and U xt evaluated at these coupling points. Each Fi may only depend linearly on time derivatives. Hence the equation (2) may be written more precisely as

F=G-A V.-B Ut* U xt* ,

(3)

where F=F 1,…,FNCODE T, G is a vector of length NCODE, A is an NCODE by NCODE matrix, B is an NCODE by nξ×NPDE matrix and the entries in G, A and B may depend on t, ξ, U*, Ux* and V. In practice you only need to supply a vector of information to define the ODEs and not the matrices A and B. (See Section 5 for the specification of ODEDEF.)

The integration in time is from t 0 to tout, over the space interval a≤x≤b, where a=x 1 and b=xNPTS are the leftmost and rightmost points of a mesh x 1,x 2,…,xNPTS defined initially by you and (possibly) adapted automatically during the integration according to user-specified criteria. The coordinate system in space is defined by the following values of m; m=0 for Cartesian coordinates, m=1 for cylindrical polar coordinates and m=2 for spherical polar coordinates.

The PDE system which is defined by the functions P i,j, Qi and Ri must be specified in PDEDEF.

The initial t=t 0 values of the functions U x,t and V t must be specified in UVINIT. Note that UVINIT will be called again following any initial remeshing, and so U x,t 0 should be specified for all values of x in the interval a≤x≤b, and not just the initial mesh points.

The functions Ri which may be thought of as fluxes, are also used in the definition of the boundary conditions. The boundary conditions must have the form

βi x,t Ri x,t,U,Ux,V=γi x,t,U,Ux,V,V.,  i=1,2,…,NPDE,

(4)

where x=a or x=b.

The boundary conditions must be specified in BNDARY. The function γi may depend linearly on V..

The problem is subject to the following restrictions:

(i)

In (1), V.j t, for j=1,2,…,NCODE, may only appear linearly in the functions Qi, for i=1,2,…,NPDE, with a similar restriction for γ;

(ii)

P i,j and the flux Ri must not depend on any time derivatives;

(iii)

t 0<tout, so that integration is in the forward direction;

(iv)

The evaluation of the terms P i,j, Qi and Ri is done approximately at the mid-points of the mesh X i, for i=1,2,…,NPTS, by calling the PDEDEF for each mid-point in turn. Any discontinuities in these functions must therefore be at one or more of the fixed mesh points specified by XFIX;

(v)

At least one of the functions P i,j must be nonzero so that there is a time derivative present in the PDE problem;

(vi)

If m>0 and x 1=0.0, which is the left boundary point, then it must be ensured that the PDE solution is bounded at this point. This can be done by either specifying the solution at x=0.0 or by specifying a zero flux there, that is βi=1.0 and γi=0.0. See also Section 9.

The algebraic-differential equation system which is defined by the functions Fi must be specified in ODEDEF. You must also specify the coupling points ξ in the array XI.

The parabolic equations are approximated by a system of ODEs in time for the values of Ui at mesh points. For simple problems in Cartesian coordinates, this system is obtained by replacing the space derivatives by the usual central, three-point finite difference formula. However, for polar and spherical problems, or problems with nonlinear coefficients, the space derivatives are replaced by a modified three-point formula which maintains second order accuracy. In total there are NPDE×NPTS+NCODE ODEs in time direction. This system is then integrated forwards in time using a Backward Differentiation Formula (BDF) or a Theta method.

The adaptive space remeshing can be used to generate meshes that automatically follow the changing time-dependent nature of the solution, generally resulting in a more efficient and accurate solution using fewer mesh points than may be necessary with a fixed uniform or non-uniform mesh. Problems with travelling wavefronts or variable-width boundary layers for example will benefit from using a moving adaptive mesh. The discrete time-step method used here (developed by Furzeland (1984)) automatically creates a new mesh based on the current solution profile at certain time-steps, and the solution is then interpolated onto the new mesh and the integration continues.

The method requires you to supply a MONITF which specifies in an analytical or numerical form the particular aspect of the solution behaviour you wish to track. This so-called monitor function is used to choose a mesh which equally distributes the integral of the monitor function over the domain. A typical choice of monitor function is the second space derivative of the solution value at each point (or some combination of the second space derivatives if there is more than one solution component), which results in refinement in regions where the solution gradient is changing most rapidly.

You must specify the frequency of mesh updates together with certain other criteria such as adjacent mesh ratios. Remeshing can be expensive and you are encouraged to experiment with the different options in order to achieve an efficient solution which adequately tracks the desired features of the solution.

Note that unless the monitor function for the initial solution values is zero at all user-specified initial mesh points, a new initial mesh is calculated and adopted according to the user-specified remeshing criteria. UVINIT will then be called again to determine the initial solution values at the new mesh points (there is no interpolation at this stage) and the integration proceeds.

4 References

Berzins M (1990) Developments in the NAG Library software for parabolic equations Scientific Software Systems (eds J C Mason and M G Cox) 59–72 Chapman and Hall

Berzins M, Dew P M and Furzeland R M (1989) Developing software for time-dependent problems using the method of lines and differential-algebraic integrators Appl. Numer. Math. 5 375–397

Berzins M and Furzeland R M (1992) An adaptive theta method for the solution of stiff and nonstiff differential equations Appl. Numer. Math. 9 1–19

Furzeland R M (1984) The construction of adaptive space meshes TNER.85.022 Thornton Research Centre, Chester

Skeel R D and Berzins M (1990) A method for the spatial discretization of parabolic equations in one space variable SIAM J. Sci. Statist. Comput. 11(1) 1–32

5 Arguments

1:   NPDE – INTEGERInput

On entry: the number of PDEs to be solved.

Constraint: NPDE≥1.

2:   M – INTEGERInput

On entry: the coordinate system used:
M=0

Indicates Cartesian coordinates.

M=1

Indicates cylindrical polar coordinates.

M=2

Indicates spherical polar coordinates.

Constraint: M=0, 1 or 2.

3:   TS – REAL (KIND=nag_wp)Input/Output

On entry: the initial value of the independent variable t.

On exit: the value of t corresponding to the solution values in U. Normally TS=TOUT.

Constraint: TS<TOUT.

4:   TOUT – REAL (KIND=nag_wp)Input

On entry: the final value of t to which the integration is to be carried out.

5:   PDEDEF – SUBROUTINE, supplied by the user.External Procedure

PDEDEF must evaluate the functions P i,j, Qi and Ri which define the system of PDEs. The functions may depend on x, t, U, Ux and V. Qi may depend linearly on V.. PDEDEF is called approximately midway between each pair of mesh points in turn by D03PPF/D03PPA.

The specification of PDEDEF for D03PPF is:

SUBROUTINE PDEDEF (

NPDE, T, X, U, UX, NCODE, V, VDOT, P, Q, R, IRES)

INTEGER

NPDE, NCODE, IRES

REAL (KIND=nag_wp)

T, X, U(NPDE), UX(NPDE), V(NCODE), VDOT(NCODE), P(NPDE,NPDE), Q(NPDE), R(NPDE)

The specification of PDEDEF for D03PPA is:

SUBROUTINE PDEDEF (

NPDE, T, X, U, UX, NCODE, V, VDOT, P, Q, R, IRES, IUSER, RUSER)

INTEGER

NPDE, NCODE, IRES, IUSER(*)

REAL (KIND=nag_wp)

T, X, U(NPDE), UX(NPDE), V(NCODE), VDOT(NCODE), P(NPDE,NPDE), Q(NPDE), R(NPDE), RUSER(*)

1:   NPDE – INTEGERInput

On entry: the number of PDEs in the system.

2:   T – REAL (KIND=nag_wp)Input

On entry: the current value of the independent variable t.

3:   X – REAL (KIND=nag_wp)Input

On entry: the current value of the space variable x.

4:   U NPDE – REAL (KIND=nag_wp) arrayInput

On entry: U i contains the value of the component Ui x,t, for i=1,2,…,NPDE.

5:   UX NPDE – REAL (KIND=nag_wp) arrayInput

On entry: UX i contains the value of the component ∂Ui x,t ∂x , for i=1,2,…,NPDE.

6:   NCODE – INTEGERInput

On entry: the number of coupled ODEs in the system.

7:   V NCODE – REAL (KIND=nag_wp) arrayInput

On entry: if NCODE>0, V i contains the value of the component Vi t, for i=1,2,…,NCODE.

8:   VDOT NCODE – REAL (KIND=nag_wp) arrayInput

On entry: if NCODE>0, VDOT i contains the value of component V.i t, for i=1,2,…,NCODE.
Note: V.i t, for i=1,2,…,NCODE, may only appear linearly in Qj, for j=1,2,…,NPDE.

9:   P NPDENPDE – REAL (KIND=nag_wp) arrayOutput

On exit: P ij must be set to the value of P i,j x,t,U,Ux,V, for i=1,2,…,NPDE and j=1,2,…,NPDE.

10:   Q NPDE – REAL (KIND=nag_wp) arrayOutput

On exit: Q i must be set to the value of Qi x,t,U,Ux,V,V., for i=1,2,…,NPDE.

11:   R NPDE – REAL (KIND=nag_wp) arrayOutput

On exit: R i must be set to the value of Ri x,t,U,Ux,V, for i=1,2,…,NPDE.

12:   IRES – INTEGERInput/Output

On entry: set to -1​ or ​1.

On exit: should usually remain unchanged. However, you may set IRES to force the integration routine to take certain actions as described below:
IRES=2

Indicates to the integrator that control should be passed back immediately to the calling (sub)routine with the error indicator set to IFAIL=6.

IRES=3

Indicates to the integrator that the current time step should be abandoned and a smaller time step used instead. You may wish to set IRES=3 when a physically meaningless input or output value has been generated. If you consecutively set IRES=3, then D03PPF/D03PPA returns to the calling subroutine with the error indicator set to IFAIL=4.

Note: the following are additional arguments for specific use with D03PPA. Users of D03PPF therefore need not read the remainder of this description.

13:   IUSER* – INTEGER arrayUser Workspace

14:   RUSER* – REAL (KIND=nag_wp) arrayUser Workspace

PDEDEF is called with the arguments IUSER and RUSER as supplied to D03PPF/D03PPA. You are free to use the arrays IUSER and RUSER to supply information to PDEDEF as an alternative to using COMMON global variables.

PDEDEF must either be a module subprogram USEd by, or declared as EXTERNAL in, the (sub)program from which D03PPF/D03PPA is called. Arguments denoted as Input must not be changed by this procedure.

6:   BNDARY – SUBROUTINE, supplied by the user.External Procedure

BNDARY must evaluate the functions βi and γi which describe the boundary conditions, as given in (4).

The specification of BNDARY for D03PPF is:

SUBROUTINE BNDARY (

NPDE, T, U, UX, NCODE, V, VDOT, IBND, BETA, GAMMA, IRES)

INTEGER

NPDE, NCODE, IBND, IRES

REAL (KIND=nag_wp)

T, U(NPDE), UX(NPDE), V(NCODE), VDOT(NCODE), BETA(NPDE), GAMMA(NPDE)

The specification of BNDARY for D03PPA is:

SUBROUTINE BNDARY (

NPDE, T, U, UX, NCODE, V, VDOT, IBND, BETA, GAMMA, IRES, IUSER, RUSER)

INTEGER

NPDE, NCODE, IBND, IRES, IUSER(*)

REAL (KIND=nag_wp)

T, U(NPDE), UX(NPDE), V(NCODE), VDOT(NCODE), BETA(NPDE), GAMMA(NPDE), RUSER(*)

1:   NPDE – INTEGERInput

On entry: the number of PDEs in the system.

2:   T – REAL (KIND=nag_wp)Input

On entry: the current value of the independent variable t.

3:   U NPDE – REAL (KIND=nag_wp) arrayInput

On entry: U i contains the value of the component Ui x,t at the boundary specified by IBND, for i=1,2,…,NPDE.

4:   UX NPDE – REAL (KIND=nag_wp) arrayInput

On entry: UX i contains the value of the component ∂Ui x,t ∂x at the boundary specified by IBND, for i=1,2,…,NPDE.

5:   NCODE – INTEGERInput

On entry: the number of coupled ODEs in the system.

6:   V NCODE – REAL (KIND=nag_wp) arrayInput

On entry: if NCODE>0, V i contains the value of the component Vi t, for i=1,2,…,NCODE.

7:   VDOT NCODE – REAL (KIND=nag_wp) arrayInput

On entry: VDOT i contains the value of component V.i t, for i=1,2,…,NCODE.
Note: V.i t, for i=1,2,…,NCODE, may only appear linearly in γj, for j=1,2,…,NPDE.

8:   IBND – INTEGERInput

On entry: specifies which boundary conditions are to be evaluated.
IBND=0

BNDARY must set up the coefficients of the left-hand boundary, x=a.

IBND≠0

BNDARY must set up the coefficients of the right-hand boundary, x=b.

9:   BETA NPDE – REAL (KIND=nag_wp) arrayOutput

On exit: BETA i must be set to the value of βi x,t at the boundary specified by IBND, for i=1,2,…,NPDE.

10:   GAMMA NPDE – REAL (KIND=nag_wp) arrayOutput

On exit: GAMMA i must be set to the value of γi x,t,U,Ux,V,V. at the boundary specified by IBND, for i=1,2,…,NPDE.

11:   IRES – INTEGERInput/Output

On entry: set to -1​ or ​1.

On exit: should usually remain unchanged. However, you may set IRES to force the integration routine to take certain actions as described below:
IRES=2

Indicates to the integrator that control should be passed back immediately to the calling (sub)routine with the error indicator set to IFAIL=6.

IRES=3

Indicates to the integrator that the current time step should be abandoned and a smaller time step used instead. You may wish to set IRES=3 when a physically meaningless input or output value has been generated. If you consecutively set IRES=3, then D03PPF/D03PPA returns to the calling subroutine with the error indicator set to IFAIL=4.

Note: the following are additional arguments for specific use with D03PPA. Users of D03PPF therefore need not read the remainder of this description.

12:   IUSER* – INTEGER arrayUser Workspace

13:   RUSER* – REAL (KIND=nag_wp) arrayUser Workspace

BNDARY is called with the arguments IUSER and RUSER as supplied to D03PPF/D03PPA. You are free to use the arrays IUSER and RUSER to supply information to BNDARY as an alternative to using COMMON global variables.

BNDARY must either be a module subprogram USEd by, or declared as EXTERNAL in, the (sub)program from which D03PPF/D03PPA is called. Arguments denoted as Input must not be changed by this procedure.

7:   UVINIT – SUBROUTINE, supplied by the user.External Procedure

UVINIT must supply the initial t=t 0 values of U x,t and V t for all values of x in the interval a≤x≤b.

The specification of UVINIT for D03PPF is:

SUBROUTINE UVINIT (

NPDE, NPTS, NXI, X, XI, U, NCODE, V)

INTEGER

NPDE, NPTS, NXI, NCODE

REAL (KIND=nag_wp)

X(NPTS), XI(NXI), U(NPDE,NPTS), V(NCODE)

The specification of UVINIT for D03PPA is:

SUBROUTINE UVINIT (

NPDE, NPTS, NXI, X, XI, U, NCODE, V, IUSER, RUSER)

INTEGER

NPDE, NPTS, NXI, NCODE, IUSER(*)

REAL (KIND=nag_wp)

X(NPTS), XI(NXI), U(NPDE,NPTS), V(NCODE), RUSER(*)

1:   NPDE – INTEGERInput

On entry: the number of PDEs in the system.

2:   NPTS – INTEGERInput

On entry: the number of mesh points in the interval a,b.

3:   NXI – INTEGERInput

On entry: the number of ODE/PDE coupling points.

4:   X NPTS – REAL (KIND=nag_wp) arrayInput

On entry: the current mesh. X i contains the value of xi, for i=1,2,…,NPTS.

5:   XI NXI – REAL (KIND=nag_wp) arrayInput

On entry: if NXI>0, XI i contains the value of the ODE/PDE coupling point, ξi, for i=1,2,…,NXI.

6:   U NPDENPTS – REAL (KIND=nag_wp) arrayOutput

On exit: if NXI>0, U ij contains the value of the component Ui xj,t 0, for i=1,2,…,NPDE and j=1,2,…,NPTS.

7:   NCODE – INTEGERInput

On entry: the number of coupled ODEs in the system.

8:   V NCODE – REAL (KIND=nag_wp) arrayOutput

On exit: V i contains the value of component Vi t 0, for i=1,2,…,NCODE.

Note: the following are additional arguments for specific use with D03PPA. Users of D03PPF therefore need not read the remainder of this description.

9:   IUSER* – INTEGER arrayUser Workspace

10:   RUSER* – REAL (KIND=nag_wp) arrayUser Workspace

UVINIT is called with the arguments IUSER and RUSER as supplied to D03PPF/D03PPA. You are free to use the arrays IUSER and RUSER to supply information to UVINIT as an alternative to using COMMON global variables.

UVINIT must either be a module subprogram USEd by, or declared as EXTERNAL in, the (sub)program from which D03PPF/D03PPA is called. Arguments denoted as Input must not be changed by this procedure.

8:   U NEQN – REAL (KIND=nag_wp) arrayInput/Output

On entry: if IND=1, the value of U must be unchanged from the previous call.

On exit: U NPDE×j-1+i contains the computed solution Ui xj,t, for i=1,2,…,NPDE and j=1,2,…,NPTS, and U NPTS×NPDE+k contains Vk t, for k=1,2,…,NCODE, evaluated at t=TS.

9:   NPTS – INTEGERInput

On entry: the number of mesh points in the interval a,b.

Constraint: NPTS≥3.

10:   X NPTS – REAL (KIND=nag_wp) arrayInput/Output

On entry: the initial mesh points in the space direction. X 1 must specify the left-hand boundary, a, and X NPTS must specify the right-hand boundary, b.

Constraint: X 1<X 2<⋯<X NPTS.

On exit: the final values of the mesh points.

11:   NCODE – INTEGERInput

On entry: the number of coupled ODE in the system.

Constraint: NCODE≥0.

12:   ODEDEF – SUBROUTINE, supplied by the NAG Library or the user.External Procedure

ODEDEF must evaluate the functions F, which define the system of ODEs, as given in (3).

If you wish to compute the solution of a system of PDEs only (NCODE=0), ODEDEF must be the dummy routine D03PCK for D03PPF (or D53PCK for D03PPA). D03PCK and D53PCK are included in the NAG Library.

The specification of ODEDEF for D03PPF is:

SUBROUTINE ODEDEF (

NPDE, T, NCODE, V, VDOT, NXI, XI, UCP, UCPX, RCP, UCPT, UCPTX, F, IRES)

INTEGER

NPDE, NCODE, NXI, IRES

REAL (KIND=nag_wp)

T, V(NCODE), VDOT(NCODE), XI(NXI), UCP(NPDE,*), UCPX(NPDE,*), RCP(NPDE,*), UCPT(NPDE,*), UCPTX(NPDE,*), F(NCODE)

The specification of ODEDEF for D03PPA is:

SUBROUTINE ODEDEF (

NPDE, T, NCODE, V, VDOT, NXI, XI, UCP, UCPX, RCP, UCPT, UCPTX, F, IRES, IUSER, RUSER)

INTEGER

NPDE, NCODE, NXI, IRES, IUSER(*)

REAL (KIND=nag_wp)

T, V(NCODE), VDOT(NCODE), XI(NXI), UCP(NPDE,*), UCPX(NPDE,*), RCP(NPDE,*), UCPT(NPDE,*), UCPTX(NPDE,*), F(NCODE), RUSER(*)

1:   NPDE – INTEGERInput

On entry: the number of PDEs in the system.

2:   T – REAL (KIND=nag_wp)Input

On entry: the current value of the independent variable t.

3:   NCODE – INTEGERInput

On entry: the number of coupled ODEs in the system.

4:   V NCODE – REAL (KIND=nag_wp) arrayInput

On entry: if NCODE>0, V i contains the value of the component Vi t, for i=1,2,…,NCODE.

5:   VDOT NCODE – REAL (KIND=nag_wp) arrayInput

On entry: if NCODE>0, VDOT i contains the value of component V.i t, for i=1,2,…,NCODE.

6:   NXI – INTEGERInput

On entry: the number of ODE/PDE coupling points.

7:   XI NXI – REAL (KIND=nag_wp) arrayInput

On entry: if NXI>0, XI i contains the ODE/PDE coupling points, ξi, for i=1,2,…,NXI.

8:   UCP NPDE* – REAL (KIND=nag_wp) arrayInput

On entry: if NXI>0, UCP ij contains the value of Ui x,t at the coupling point x=ξj, for i=1,2,…,NPDE and j=1,2,…,NXI.

9:   UCPX NPDE* – REAL (KIND=nag_wp) arrayInput

On entry: if NXI>0, UCPX ij contains the value of ∂Ui x,t ∂x at the coupling point x=ξj, for i=1,2,…,NPDE and j=1,2,…,NXI.

10:   RCP NPDE* – REAL (KIND=nag_wp) arrayInput

On entry: RCP ij contains the value of the flux Ri at the coupling point x=ξj, for i=1,2,…,NPDE and j=1,2,…,NXI.

11:   UCPT NPDE* – REAL (KIND=nag_wp) arrayInput

On entry: if NXI>0, UCPT ij contains the value of ∂Ui ∂t at the coupling point x=ξj, for i=1,2,…,NPDE and j=1,2,…,NXI.

12:   UCPTX NPDE* – REAL (KIND=nag_wp) arrayInput

On entry: UCPTX ij contains the value of ∂2 Ui ∂x ∂t at the coupling point x=ξj, for i=1,2,…,NPDE and j=1,2,…,NXI.

13:   F NCODE – REAL (KIND=nag_wp) arrayOutput

On exit: F i must contain the ith component of F, for i=1,2,…,NCODE, where F is defined as

F=G-A V.-B Ut* U xt* ,

(5)

or

F=-A V.-B Ut* U xt* .

(6)

The definition of F is determined by the input value of IRES.

14:   IRES – INTEGERInput/Output

On entry: the form of F that must be returned in the array F.
IRES=1

Equation (5) must be used.

IRES=-1

Equation (6) must be used.

On exit: should usually remain unchanged. However, you may reset IRES to force the integration routine to take certain actions as described below:
IRES=2

Indicates to the integrator that control should be passed back immediately to the calling (sub)routine with the error indicator set to IFAIL=6.

IRES=3

Indicates to the integrator that the current time step should be abandoned and a smaller time step used instead. You may wish to set IRES=3 when a physically meaningless input or output value has been generated. If you consecutively set IRES=3, then D03PPF/D03PPA returns to the calling subroutine with the error indicator set to IFAIL=4.

Note: the following are additional arguments for specific use with D03PPA. Users of D03PPF therefore need not read the remainder of this description.

15:   IUSER* – INTEGER arrayUser Workspace

16:   RUSER* – REAL (KIND=nag_wp) arrayUser Workspace

ODEDEF is called with the arguments IUSER and RUSER as supplied to D03PPF/D03PPA. You are free to use the arrays IUSER and RUSER to supply information to ODEDEF as an alternative to using COMMON global variables.

ODEDEF must either be a module subprogram USEd by, or declared as EXTERNAL in, the (sub)program from which D03PPF/D03PPA is called. Arguments denoted as Input must not be changed by this procedure.

13:   NXI – INTEGERInput

On entry: the number of ODE/PDE coupling points.

Constraints:

if NCODE=0, NXI=0;

if NCODE>0, NXI≥0.

14:   XI NXI – REAL (KIND=nag_wp) arrayInput

On entry: if NXI>0, XI i, for i=1,2,…,NXI, must be set to the ODE/PDE coupling points.

Constraint: X 1≤XI 1<XI 2<⋯<XI NXI≤X NPTS.

15:   NEQN – INTEGERInput

On entry: the number of ODEs in the time direction.

Constraint: NEQN=NPDE×NPTS+NCODE.

16:   RTOL* – REAL (KIND=nag_wp) arrayInput

Note: the dimension of the array RTOL must be at least 1 if ITOL=1 or 2 and at least NEQN if ITOL=3 or 4.

On entry: the relative local error tolerance.

Constraint: RTOL i≥0.0 for all relevant i.

17:   ATOL* – REAL (KIND=nag_wp) arrayInput

Note: the dimension of the array ATOL must be at least 1 if ITOL=1 or 3 and at least NEQN if ITOL=2 or 4.

On entry: the absolute local error tolerance.

Constraints:

ATOL i≥0.0 for all relevant i;

Corresponding elements of ATOL and RTOL cannot both be 0.0.

18:   ITOL – INTEGERInput

On entry: a value to indicate the form of the local error test. ITOL indicates to D03PPF/D03PPA whether to interpret either or both of RTOL or ATOL as a vector or scalar. The error test to be satisfied is ei/wi<1.0, where wi is defined as follows:

ITOL

RTOL

ATOL

wi

1

scalar

scalar

RTOL 1×Ui+ATOL 1

2

scalar

vector

RTOL 1×Ui+ATOL i

3

vector

scalar

RTOL i×Ui+ATOL 1

4

vector

vector

RTOL i×Ui+ATOL i

In the above, ei denotes the estimated local error for the ith component of the coupled PDE/ODE system in time, U i, for i=1,2,…,NEQN.

The choice of norm used is defined by the argument NORM.

Constraint: 1≤ITOL≤4.

19:   NORM – CHARACTER(1)Input

On entry: the type of norm to be used.
NORM='M'

Maximum norm.

NORM='A'

Averaged L 2 norm.

If Unorm denotes the norm of the vector U of length NEQN, then for the averaged L 2 norm

Unorm=1 NEQN∑i=1 NEQN U i/wi 2,

while for the maximum norm

U norm = maxi U i / wi .

See the description of ITOL for the formulation of the weight vector w.

Constraint: NORM='M' or 'A'.

20:   LAOPT – CHARACTER(1)Input

On entry: the type of matrix algebra required.
LAOPT='F'

Full matrix methods to be used.

LAOPT='B'

Banded matrix methods to be used.

LAOPT='S'

Sparse matrix methods to be used.

Constraint: LAOPT='F', 'B' or 'S'.

Note: you are recommended to use the banded option when no coupled ODEs are present (i.e., NCODE=0).

21:   ALGOPT 30 – REAL (KIND=nag_wp) arrayInput

On entry: may be set to control various options available in the integrator. If you wish to employ all the default options, then ALGOPT 1 should be set to 0.0. Default values will also be used for any other elements of ALGOPT set to zero. The permissible values, default values, and meanings are as follows:
ALGOPT 1

Selects the ODE integration method to be used. If ALGOPT 1=1.0, a BDF method is used and if ALGOPT 1=2.0, a Theta method is used. The default value is ALGOPT 1=1.0.

If ALGOPT 1=2.0, then ALGOPT i, for i=2,3,4 are not used.

ALGOPT 2

Specifies the maximum order of the BDF integration formula to be used. ALGOPT 2 may be 1.0, 2.0, 3.0, 4.0 or 5.0. The default value is ALGOPT 2=5.0.

ALGOPT 3

Specifies what method is to be used to solve the system of nonlinear equations arising on each step of the BDF method. If ALGOPT 3=1.0 a modified Newton iteration is used and if ALGOPT 3=2.0 a functional iteration method is used. If functional iteration is selected and the integrator encounters difficulty, then there is an automatic switch to the modified Newton iteration. The default value is ALGOPT 3=1.0.

ALGOPT 4

Specifies whether or not the Petzold error test is to be employed. The Petzold error test results in extra overhead but is more suitable when algebraic equations are present, such as P i,j=0.0, for j=1,2,…,NPDE, for some i or when there is no V.i t dependence in the coupled ODE system. If ALGOPT 4=1.0, then the Petzold test is used. If ALGOPT 4=2.0, then the Petzold test is not used. The default value is ALGOPT 4=1.0.

If ALGOPT 1=1.0, then ALGOPT i, for i=5,6,7, are not used.

ALGOPT 5

Specifies the value of Theta to be used in the Theta integration method. 0.51≤ALGOPT 5≤0.99. The default value is ALGOPT 5=0.55.

ALGOPT 6

Specifies what method is to be used to solve the system of nonlinear equations arising on each step of the Theta method. If ALGOPT 6=1.0, a modified Newton iteration is used and if ALGOPT 6=2.0, a functional iteration method is used. The default value is ALGOPT 6=1.0.

ALGOPT 7

Specifies whether or not the integrator is allowed to switch automatically between modified Newton and functional iteration methods in order to be more efficient. If ALGOPT 7=1.0, then switching is allowed and if ALGOPT 7=2.0, then switching is not allowed. The default value is ALGOPT 7=1.0.

ALGOPT 11

Specifies a point in the time direction, tcrit, beyond which integration must not be attempted. The use of tcrit is described under the argument ITASK. If ALGOPT 1≠0.0, a value of 0.0 for ALGOPT 11, say, should be specified even if ITASK subsequently specifies that tcrit will not be used.

ALGOPT 12

Specifies the minimum absolute step size to be allowed in the time integration. If this option is not required, ALGOPT 12 should be set to 0.0.

ALGOPT 13

Specifies the maximum absolute step size to be allowed in the time integration. If this option is not required, ALGOPT 13 should be set to 0.0.

ALGOPT 14

Specifies the initial step size to be attempted by the integrator. If ALGOPT 14=0.0, then the initial step size is calculated internally.

ALGOPT 15

Specifies the maximum number of steps to be attempted by the integrator in any one call. If ALGOPT 15=0.0, then no limit is imposed.

ALGOPT 23

Specifies what method is to be used to solve the nonlinear equations at the initial point to initialize the values of U, Ut, V and V.. If ALGOPT 23=1.0, a modified Newton iteration is used and if ALGOPT 23=2.0, functional iteration is used. The default value is ALGOPT 23=1.0.

ALGOPT 29 and ALGOPT 30 are used only for the sparse matrix algebra option, LAOPT='S'.

ALGOPT 29

Governs the choice of pivots during the decomposition of the first Jacobian matrix. It should lie in the range 0.0<ALGOPT 29<1.0, with smaller values biasing the algorithm towards maintaining sparsity at the expense of numerical stability. If ALGOPT 29 lies outside this range then the default value is used. If the routines regard the Jacobian matrix as numerically singular then increasing ALGOPT 29 towards 1.0 may help, but at the cost of increased fill-in. The default value is ALGOPT 29=0.1.

ALGOPT 30

Is used as a relative pivot threshold during subsequent Jacobian decompositions (see ALGOPT 29) below which an internal error is invoked. If ALGOPT 30 is greater than 1.0 no check is made on the pivot size, and this may be a necessary option if the Jacobian is found to be numerically singular (see ALGOPT 29). The default value is ALGOPT 30=0.0001.

22:   REMESH – LOGICALInput

On entry: indicates whether or not spatial remeshing should be performed.
REMESH=.TRUE.

Indicates that spatial remeshing should be performed as specified.

REMESH=.FALSE.

Indicates that spatial remeshing should be suppressed.

Note: REMESH should not be changed between consecutive calls to D03PPF/D03PPA. Remeshing can be switched off or on at specified times by using appropriate values for the arguments NRMESH and TRMESH at each call.

23:   NXFIX – INTEGERInput

On entry: the number of fixed mesh points.

Constraint: 0≤NXFIX≤NPTS-2.
Note: the end points X 1 and X NPTS are fixed automatically and hence should not be specified as fixed points.

24:   XFIX* – REAL (KIND=nag_wp) arrayInput

Note: the dimension of the array XFIX must be at least max 1,NXFIX.

On entry: XFIX i, for i=1,2,…,NXFIX, must contain the value of the x coordinate at the ith fixed mesh point.

Constraints:

XFIX i<XFIX i+1, for i=1,2,…,NXFIX-1;

each fixed mesh point must coincide with a user-supplied initial mesh point, that is XFIX i=X j for some j, 2≤j≤NPTS-1.

Note: the positions of the fixed mesh points in the array X remain fixed during remeshing, and so the number of mesh points between adjacent fixed points (or between fixed points and end points) does not change. You should take this into account when choosing the initial mesh distribution.

25:   NRMESH – INTEGERInput

On entry: specifies the spatial remeshing frequency and criteria for the calculation and adoption of a new mesh.
NRMESH<0

Indicates that a new mesh is adopted according to the argument DXMESH. The mesh is tested every NRMESH timesteps.

NRMESH=0

Indicates that remeshing should take place just once at the end of the first time step reached when t>TRMESH.

NRMESH>0

Indicates that remeshing will take place every NRMESH time steps, with no testing using DXMESH.

Note: NRMESH may be changed between consecutive calls to D03PPF/D03PPA to give greater flexibility over the times of remeshing.

26:   DXMESH – REAL (KIND=nag_wp)Input

On entry: determines whether a new mesh is adopted when NRMESH is set less than zero. A possible new mesh is calculated at the end of every NRMESH time steps, but is adopted only if

xi new>xi old +DXMESH×x i+1 old -xi old

or

xi new<xi old -DXMESH×xi old -x i- 1 old

DXMESH thus imposes a lower limit on the difference between one mesh and the next.

Constraint: DXMESH≥0.0.

27:   TRMESH – REAL (KIND=nag_wp)Input

On entry: specifies when remeshing will take place when NRMESH is set to zero. Remeshing will occur just once at the end of the first time step reached when t is greater than TRMESH.
Note: TRMESH may be changed between consecutive calls to D03PPF/D03PPA to force remeshing at several specified times.

28:   IPMINF – INTEGERInput

On entry: the level of trace information regarding the adaptive remeshing. Details are directed to the current advisory message unit (see X04ABF).
IPMINF=0

No trace information.

IPMINF=1

Brief summary of mesh characteristics.

IPMINF=2

More detailed information, including old and new mesh points, mesh sizes and monitor function values.

Constraint: IPMINF=0, 1 or 2.

29:   XRATIO – REAL (KIND=nag_wp)Input

On entry: an input bound on the adjacent mesh ratio (greater than 1.0 and typically in the range 1.5 to 3.0). The remeshing routines will attempt to ensure that

xi-x i-1/XRATIO<x i+1-xi<XRATIO×xi-x i-1.

Suggested value: XRATIO=1.5.

Constraint: XRATIO>1.0.

30:   CON – REAL (KIND=nag_wp)Input

On entry: an input bound on the sub-integral of the monitor function Fmon x over each space step. The remeshing routines will attempt to ensure that

∫xix i+1 Fmon x dx≤CON∫x 1xNPTS Fmon x dx,

(see Furzeland (1984)). CON gives you more control over the mesh distribution e.g., decreasing CON allows more clustering. A typical value is 2/NPTS-1, but you are encouraged to experiment with different values. Its value is not critical and the mesh should be qualitatively correct for all values in the range given below.

Suggested value: CON=2.0/NPTS-1.

Constraint: 0.1/NPTS-1≤CON≤10.0/NPTS-1.

31:   MONITF – SUBROUTINE, supplied by the NAG Library or the user.External Procedure

MONITF must supply and evaluate a remesh monitor function to indicate the solution behaviour of interest.

If you specify REMESH=.FALSE., i.e., no remeshing, then MONITF will not be called and the dummy routine D03PCL for D03PPF (or D53PCL for D03PPA) may be used for MONITF. (D03PCL and D53PCL are included in the NAG Library.)

The specification of MONITF for D03PPF is:

SUBROUTINE MONITF (

T, NPTS, NPDE, X, U, R, FMON)

INTEGER

NPTS, NPDE

REAL (KIND=nag_wp)

T, X(NPTS), U(NPDE,NPTS), R(NPDE,NPTS), FMON(NPTS)

The specification of MONITF for D03PPA is:

SUBROUTINE MONITF (

T, NPTS, NPDE, X, U, R, FMON, IUSER, RUSER)

INTEGER

NPTS, NPDE, IUSER(*)

REAL (KIND=nag_wp)

T, X(NPTS), U(NPDE,NPTS), R(NPDE,NPTS), FMON(NPTS), RUSER(*)

1:   T – REAL (KIND=nag_wp)Input

On entry: the current value of the independent variable t.

2:   NPTS – INTEGERInput

On entry: the number of mesh points in the interval a,b.

3:   NPDE – INTEGERInput

On entry: the number of PDEs in the system.

4:   X NPTS – REAL (KIND=nag_wp) arrayInput

On entry: the current mesh. X i contains the value of xi, for i=1,2,…,NPTS.

5:   U NPDENPTS – REAL (KIND=nag_wp) arrayInput

On entry: U ij contains the value of Ui x,t at x=X j and time t, for i=1,2,…,NPDE and j=1,2,…,NPTS.

6:   R NPDENPTS – REAL (KIND=nag_wp) arrayInput

On entry: R ij contains the value of Ri x,t,U,Ux,V at x=X j and time t, for i=1,2,…,NPDE and j=1,2,…,NPTS.

7:   FMON NPTS – REAL (KIND=nag_wp) arrayOutput

On exit: FMON i must contain the value of the monitor function Fmon x at mesh point x=X i.

Constraint: FMON i≥0.0.

Note: the following are additional arguments for specific use with D03PPA. Users of D03PPF therefore need not read the remainder of this description.

8:   IUSER* – INTEGER arrayUser Workspace

9:   RUSER* – REAL (KIND=nag_wp) arrayUser Workspace

MONITF is called with the arguments IUSER and RUSER as supplied to D03PPF/D03PPA. You are free to use the arrays IUSER and RUSER to supply information to MONITF as an alternative to using COMMON global variables.

MONITF must either be a module subprogram USEd by, or declared as EXTERNAL in, the (sub)program from which D03PPF/D03PPA is called. Arguments denoted as Input must not be changed by this procedure.

32:   RSAVE LRSAVE – REAL (KIND=nag_wp) arrayCommunication Array

If IND=0, RSAVE need not be set on entry.

If IND=1, RSAVE must be unchanged from the previous call to the routine because it contains required information about the iteration.

33:   LRSAVE – INTEGERInput

On entry: the dimension of the array RSAVE as declared in the (sub)program from which D03PPF/D03PPA is called. Its size depends on the type of matrix algebra selected.
If LAOPT='F', LRSAVE≥NEQN×NEQN+NEQN+nwkres+lenode.

If LAOPT='B', LRSAVE≥3×mlu+1×NEQN+nwkres+lenode.

If LAOPT='S', LRSAVE≥4×NEQN+11×NEQN/2+1+nwkres+lenode.

Where

mlu is the lower or upper half bandwidths such that
mlu=2×NPDE-1, for PDE problems only; or
mlu=NEQN-1, for coupled PDE/ODE problems.

nwkres= NPDE×3×NPDE+6×NXI+NPTS+15+NXI+NCODE+7×NPTS+NXFIX+1, when ​NCODE>0​ and ​NXI>0; NPDE×3×NPDE+NPTS+21+NCODE+7×NPTS+NXFIX+2, when ​NCODE>0​ and ​NXI=0; or NPDE×3×NPDE+NPTS+21+7×NPTS+NXFIX+3, when ​NCODE=0.

lenode= 6+int ALGOPT 2×NEQN+50, when the BDF method is used; 9×NEQN+50, when the Theta method is used.

Note: when using the sparse option, the value of LRSAVE may be too small when supplied to the integrator. An estimate of the minimum size of LRSAVE is printed on the current error message unit if ITRACE>0 and the routine returns with IFAIL=15.

34:   ISAVE LISAVE – INTEGER arrayCommunication Array

If IND=0, ISAVE need not be set on entry.

If IND=1, ISAVE must be unchanged from the previous call to the routine because it contains required information about the iteration required for subsequent calls. In particular:
ISAVE 1

Contains the number of steps taken in time.

ISAVE 2

Contains the number of residual evaluations of the resulting ODE system used. One such evaluation involves computing the PDE functions at all the mesh points, as well as one evaluation of the functions in the boundary conditions.

ISAVE 3

Contains the number of Jacobian evaluations performed by the time integrator.

ISAVE 4

Contains the order of the ODE method last used in the time integration.

ISAVE 5

Contains the number of Newton iterations performed by the time integrator. Each iteration involves residual evaluation of the resulting ODE system followed by a back-substitution using the LU decomposition of the Jacobian matrix.

The rest of the array is used as workspace.

35:   LISAVE – INTEGERInput

On entry: the dimension of the array ISAVE as declared in the (sub)program from which D03PPF/D03PPA is called.
Its size depends on the type of matrix algebra selected:

if LAOPT='B', LISAVE≥NEQN+25+NXFIX;

if LAOPT='F', LISAVE≥25+NXFIX;

if LAOPT='S', LISAVE≥25×NEQN+25+NXFIX.

Note: when using the sparse option, the value of LISAVE may be too small when supplied to the integrator. An estimate of the minimum size of LISAVE is printed on the current error message unit if ITRACE>0 and the routine returns with IFAIL=15.

36:   ITASK – INTEGERInput

On entry: specifies the task to be performed by the ODE integrator.
ITASK=1

Normal computation of output values U at t=TOUT.

ITASK=2

One step and return.

ITASK=3

Stop at first internal integration point at or beyond t=TOUT.

ITASK=4

Normal computation of output values U at t=TOUT but without overshooting t=tcrit where tcrit is described under the argument ALGOPT.

ITASK=5

Take one step in the time direction and return, without passing tcrit, where tcrit is described under the argument ALGOPT.

Constraint: ITASK=1, 2, 3, 4 or 5.

37:   ITRACE – INTEGERInput

On entry: the level of trace information required from D03PPF/D03PPA and the underlying ODE solver:
ITRACE≤-1

No output is generated.

ITRACE=0

Only warning messages from the PDE solver are printed on the current error message unit (see X04AAF).

ITRACE=1

Output from the underlying ODE solver is printed on the current advisory message unit (see X04ABF). This output contains details of Jacobian entries, the nonlinear iteration and the time integration during the computation of the ODE system.

ITRACE=2

Output from the underlying ODE solver is similar to that produced when ITRACE=1, except that the advisory messages are given in greater detail.

ITRACE≥3

Output from the underlying ODE solver is similar to that produced when ITRACE=2, except that the advisory messages are given in greater detail.

You are advised to set ITRACE=0, unless you are experienced with Sub-chapter D02M–N.

38:   IND – INTEGERInput/Output

On entry: must be set to 0 or 1.
IND=0

Starts or restarts the integration in time.

IND=1

Continues the integration after an earlier exit from the routine. In this case, only the arguments TOUT and IFAIL and the remeshing arguments NRMESH, DXMESH, TRMESH, XRATIO and CON may be reset between calls to D03PPF/D03PPA.

Constraint: 0≤IND≤1.

On exit: IND=1.

39:   IFAIL – INTEGERInput/Output

Note: for D03PPA, IFAIL does not occur in this position in the argument list. See the additional arguments described below.

On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.

On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

Note: the following are additional arguments for specific use with D03PPA. Users of D03PPF therefore need not read the remainder of this description.

39:   IUSER* – INTEGER arrayUser Workspace

40:   RUSER* – REAL (KIND=nag_wp) arrayUser Workspace

IUSER and RUSER are not used by D03PPF/D03PPA, but are passed directly to PDEDEF, BNDARY, UVINIT, ODEDEF and MONITF and may be used to pass information to these routines as an alternative to using COMMON global variables.

41:   CWSAV 10 – CHARACTER(80) arrayCommunication Array

42:   LWSAV 100 – LOGICAL arrayCommunication Array

43:   IWSAV 505 – INTEGER arrayCommunication Array

44:   RWSAV 1100 – REAL (KIND=nag_wp) arrayCommunication Array

45:   IFAIL – INTEGERInput/Output

Note: see the argument description for IFAIL above.

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).

Errors or warnings detected by the routine:

IFAIL=1

On entry,

TOUT-TS is too small,

or

ITASK≠1, 2, 3, 4 or 5,

or

M≠0, 1 or 2,

or

at least one of the coupling points defined in array XI is outside the interval X 1,X NPTS,

or

M>0 and X 1<0.0,

or

NPTS<3,

or

NPDE<1,

or

NORM≠'A' or 'M',

or

LAOPT≠'F', 'B' or 'S',

or

ITOL≠1, 2, 3 or 4,

or

IND≠0 or 1,

or

mesh points X i are badly ordered,

or

LRSAVE is too small,

or

LISAVE is too small,

or

NCODE and NXI are incorrectly defined,

or

an element of RTOL or ATOL<0.0,

or

corresponding elements of RTOL and ATOL are both 0.0,

or

NEQN≠NPDE×NPTS+NCODE,

or

NXFIX not in the range 0 to NPTS-2,

or

fixed mesh point(s) do not coincide with any of the user-supplied mesh points,

or

DXMESH<0.0,

or

IPMINF≠0, 1 or 2,

or

XRATIO≤1.0,

or

CON not in the range 0.1/NPTS-1 to 10/NPTS-1.

IFAIL=2

The underlying ODE solver cannot make any further progress, with the values of ATOL and RTOL, across the integration range from the current point t=TS. The components of U contain the computed values at the current point t=TS.

IFAIL=3

In the underlying ODE solver, there were repeated error test failures on an attempted step, before completing the requested task, but the integration was successful as far as t=TS. The problem may have a singularity, or the error requirement may be inappropriate.

IFAIL=4

In setting up the ODE system, the internal initialization routine was unable to initialize the derivative of the ODE system. This could be due to the fact that IRES was repeatedly set to 3 in at least PDEDEF, BNDARY or ODEDEF, when the residual in the underlying ODE solver was being evaluated.

IFAIL=5

In solving the ODE system, a singular Jacobian has been encountered. You should check your problem formulation.

IFAIL=6

When evaluating the residual in solving the ODE system, IRES was set to 2 in at least PDEDEF, BNDARY or ODEDEF. Integration was successful as far as t=TS.

IFAIL=7

The values of ATOL and RTOL are so small that the routine is unable to start the integration in time.

IFAIL=8

In one of PDEDEF, BNDARY or ODEDEF, IRES was set to an invalid value.

IFAIL=9 (D02NNF)

A serious error has occurred in an internal call to the specified routine. Check the problem specification and all arguments and array dimensions. Setting ITRACE=1 may provide more information. If the problem persists, contact NAG.

IFAIL=10

The required task has been completed, but it is estimated that a small change in ATOL and RTOL is unlikely to produce any change in the computed solution. (Only applies when you are not operating in one step mode, that is when ITASK≠2 or 5.)

IFAIL=11

An error occurred during Jacobian formulation of the ODE system (a more detailed error description may be directed to the current error message unit). If using the sparse matrix algebra option, the values of ALGOPT 29 and ALGOPT 30 may be inappropriate.

IFAIL=12

In solving the ODE system, the maximum number of steps specified in ALGOPT 15 have been taken.

IFAIL=13

Some error weights wi became zero during the time integration (see the description of ITOL). Pure relative error control (ATOL i=0.0) was requested on a variable (the ith) which has become zero. The integration was successful as far as t=TS.

IFAIL=14

The flux function Ri was detected as depending on time derivatives, which is not permissible.

IFAIL=15

When using the sparse option, the value of LISAVE or LRSAVE was not sufficient (more detailed information may be directed to the current error message unit).

IFAIL=16

REMESH has been changed between calls to D03PPF/D03PPA, which is not permissible.

IFAIL=17

The remeshing process has produced zero or negative mesh spacing. You are advised to check MONITF and to try adjusting the values of DXMESH, XRATIO and CON. Setting IPMINF=1 may provide more information.

IFAIL=-99

An unexpected error has been triggered by this routine. Please contact NAG.

See Section 3.9 in How to Use the NAG Library and its Documentation for further information.

IFAIL=-399

Your licence key may have expired or may not have been installed correctly.

See Section 3.8 in How to Use the NAG Library and its Documentation for further information.

IFAIL=-999

Dynamic memory allocation failed.

See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

D03PPF/D03PPA controls the accuracy of the integration in the time direction but not the accuracy of the approximation in space. The spatial accuracy depends on both the number of mesh points and on their distribution in space. In the time integration only the local error over a single step is controlled and so the accuracy over a number of steps cannot be guaranteed. You should therefore test the effect of varying the accuracy arguments, ATOL and RTOL.

8 Parallelism and Performance

D03PPF/D03PPA is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.

D03PPF/D03PPA makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.

Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The argument specification allows you to include equations with only first-order derivatives in the space direction but there is no guarantee that the method of integration will be satisfactory for such systems. The position and nature of the boundary conditions in particular are critical in defining a stable problem. It may be advisable in such cases to reduce the whole system to first-order and to use the Keller box scheme routine D03PRF.

The time taken depends on the complexity of the parabolic system, the accuracy requested, and the frequency of the mesh updates. For a given system with fixed accuracy and mesh-update frequency it is approximately proportional to NEQN.

10 Example

This example uses Burgers Equation, a common test problem for remeshing algorithms, given by

∂U ∂t =-U ∂U ∂x +E ∂2 U ∂x 2 ,

for x∈0,1 and t∈0,1, where E is a small constant.

The initial and boundary conditions are given by the exact solution

U x,t=0.1 exp-A+0.5 exp-B+exp-C exp-A+exp-B+exp-C ,

where

A = 50 E x- 0.5+ 4.95 t, B = 250 E x- 0.5+ 0.75 t, C = 500 E x- 0.375.

10.1 Program Text

Note: the following programs illustrate the use of D03PPF and D03PPA.

Program Text (d03ppfe.f90)

Program Text (d03ppae.f90)

10.2 Program Data

Program Data (d03ppfe.d)

Program Data (d03ppae.d)

10.3 Program Results

Program Results (d03ppfe.r)

Program Results (d03ppae.r)

D03 Chapter Contents

D03 Chapter Introduction

NAG Library Manual

© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


D03PRF : NAG Library, Mark 26

D03 Chapter Contents

D03 Chapter Introduction

NAG Library Manual

NAG Library Routine Document

D03PRF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose

2 Specification

3 Description

4 References

5 Arguments

6 Error Indicators and Warnings

7 Accuracy

8 Parallelism and Performance

9 Further Comments

▸▿ 10 Example

10.1 Program Text

10.2 Program Data

10.3 Program Results

1 Purpose

D03PRF integrates a system of linear or nonlinear, first-order, time-dependent partial differential equations (PDEs) in one space variable, with scope for coupled ordinary differential equations (ODEs), and automatic adaptive spatial remeshing. The spatial discretization is performed using the Keller box scheme (see Keller (1970)) and the method of lines is employed to reduce the PDEs to a system of ODEs. The resulting system is solved using a Backward Differentiation Formula (BDF) method or a Theta method (switching between Newton's method and functional iteration).

2 Specification

SUBROUTINE D03PRF (

NPDE, TS, TOUT, PDEDEF, BNDARY, UVINIT, U, NPTS, X, NLEFT, NCODE, ODEDEF, NXI, XI, NEQN, RTOL, ATOL, ITOL, NORM, LAOPT, ALGOPT, REMESH, NXFIX, XFIX, NRMESH, DXMESH, TRMESH, IPMINF, XRATIO, CON, MONITF, RSAVE, LRSAVE, ISAVE, LISAVE, ITASK, ITRACE, IND, IFAIL)

INTEGER

NPDE, NPTS, NLEFT, NCODE, NXI, NEQN, ITOL, NXFIX, NRMESH, IPMINF, LRSAVE, ISAVE(LISAVE), LISAVE, ITASK, ITRACE, IND, IFAIL

REAL (KIND=nag_wp)

TS, TOUT, U(NEQN), X(NPTS), XI(*), RTOL(*), ATOL(*), ALGOPT(30), XFIX(*), DXMESH, TRMESH, XRATIO, CON, RSAVE(LRSAVE)

LOGICAL

REMESH

CHARACTER(1)

NORM, LAOPT

EXTERNAL

PDEDEF, BNDARY, UVINIT, ODEDEF, MONITF

3 Description

D03PRF integrates the system of first-order PDEs and coupled ODEs given by the master equations:

Gi x,t,U,Ux,Ut,V,V. = 0 ,   i=1,2,…,NPDE ,   a≤x≤b,t≥t 0,

(1)

Ri t,V,V.,ξ,U*,Ux*,Ut*=0,  i=1,2,…,NCODE.

(2)

In the PDE part of the problem given by (1), the functions Gi must have the general form

Gi=∑j=1 NPDE P i,j ∂Uj ∂t +∑j=1 NCODE Q i,jV.j+Si=0,  i=1,2,…,NPDE,

(3)

where P i,j, Q i,j and Si depend on x, t, U, Ux and V.

The vector U is the set of PDE solution values

U x,t=U 1 x,t,…,UNPDE x,t T,

and the vector Ux is the partial derivative with respect to x. The vector V is the set of ODE solution values

V t=V 1 t,…,VNCODE t T,

and V. denotes its derivative with respect to time.

In the ODE part given by (2), ξ represents a vector of nξ spatial coupling points at which the ODEs are coupled to the PDEs. These points may or may not be equal to some of the PDE spatial mesh points. U*, Ux* and Ut* are the functions U, Ux and Ut evaluated at these coupling points. Each Ri may only depend linearly on time derivatives. Hence equation (2) may be written more precisely as

R=A-B V.-C Ut*,

(4)

where R=R 1,…,RNCODE T, A is a vector of length NCODE, B is an NCODE by NCODE matrix, C is an NCODE by nξ×NPDE matrix and the entries in A, B and C may depend on t, ξ, U*, Ux* and V. In practice you only need to supply a vector of information to define the ODEs and not the matrices B and C. (See Section 5 for the specification of ODEDEF.)

The integration in time is from t 0 to tout, over the space interval a≤x≤b, where a=x 1 and b=xNPTS are the leftmost and rightmost points of a mesh x 1,x 2,…,xNPTS defined initially by you and (possibly) adapted automatically during the integration according to user-specified criteria.

The PDE system which is defined by the functions Gi must be specified in PDEDEF.

The initial t=t 0 values of the functions U x,t and V t must be specified in UVINIT. Note that UVINIT will be called again following any remeshing, and so U x,t 0 should be specified for all values of x in the interval a≤x≤b, and not just the initial mesh points.

For a first-order system of PDEs, only one boundary condition is required for each PDE component Ui. The NPDE boundary conditions are separated into na at the left-hand boundary x=a, and nb at the right-hand boundary x=b, such that na+nb=NPDE. The position of the boundary condition for each component should be chosen with care; the general rule is that if the characteristic direction of Ui at the left-hand boundary (say) points into the interior of the solution domain, then the boundary condition for Ui should be specified at the left-hand boundary. Incorrect positioning of boundary conditions generally results in initialization or integration difficulties in the underlying time integration routines.

The boundary conditions have the master equation form:

GiL x,t,U,Ut,V,V. = 0   at ​ x = a ,   i=1,2,…,na ,

(5)

at the left-hand boundary, and

GiR x,t,U,Ut,V,V. = 0   at ​ x = b ,   i=1,2,…,nb ,

(6)

at the right-hand boundary.

Note that the functions GiL and GiR must not depend on Ux, since spatial derivatives are not determined explicitly in the Keller box scheme routines. If the problem involves derivative (Neumann) boundary conditions then it is generally possible to restate such boundary conditions in terms of permissible variables. Also note that GiL and GiR must be linear with respect to time derivatives, so that the boundary conditions have the general form:

∑ j=1 NPDE E i,j L ∂Uj ∂t + ∑ j=1 NCODE H i,j L V.j + KiL = 0 ,   i=1,2,…,na ,

(7)

at the left-hand boundary, and

∑ j=1 NPDE E i,j R ∂Uj ∂t + ∑ j=1 NCODE H i,j R V.j + KiR = 0 ,   i=1,2,…,nb ,

(8)

at the right-hand boundary, where E i,j L, E i,j R, H i,j L, H i,j R, KiL and KiR depend on x,t,U and V only.

The boundary conditions must be specified in BNDARY.

The problem is subject to the following restrictions:

(i)

P i,j, Q i,j and Si must not depend on any time derivatives;

(ii)

t 0<tout, so that integration is in the forward direction;

(iii)

The evaluation of the function Gi is done approximately at the mid-points of the mesh X i, for i=1,2,…,NPTS, by calling PDEDEF for each mid-point in turn. Any discontinuities in the function must therefore be at one or more of the fixed mesh points specified by XFIX;

(iv)

At least one of the functions P i,j must be nonzero so that there is a time derivative present in the PDE problem.

The algebraic-differential equation system which is defined by the functions Ri must be specified in ODEDEF. You must also specify the coupling points ξ in the array XI.

The first-order equations are approximated by a system of ODEs in time for the values of Ui at mesh points. In this method of lines approach the Keller box scheme is applied to each PDE in the space variable only, resulting in a system of ODEs in time for the values of Ui at each mesh point. In total there are NPDE×NPTS+NCODE ODEs in time direction. This system is then integrated forwards in time using a Backward Differentiation Formula (BDF) or a Theta method.

The adaptive space remeshing can be used to generate meshes that automatically follow the changing time-dependent nature of the solution, generally resulting in a more efficient and accurate solution using fewer mesh points than may be necessary with a fixed uniform or non-uniform mesh. Problems with travelling wavefronts or variable-width boundary layers for example will benefit from using a moving adaptive mesh. The discrete time-step method used here (developed by Furzeland (1984)) automatically creates a new mesh based on the current solution profile at certain time-steps, and the solution is then interpolated onto the new mesh and the integration continues.

The method requires you to supply MONITF which specifies in an analytic or numeric form the particular aspect of the solution behaviour you wish to track. This so-called monitor function is used to choose a mesh which equally distributes the integral of the monitor function over the domain. A typical choice of monitor function is the second space derivative of the solution value at each point (or some combination of the second space derivatives if more than one solution component), which results in refinement in regions where the solution gradient is changing most rapidly.

You must specify the frequency of mesh updates along with certain other criteria such as adjacent mesh ratios. Remeshing can be expensive and you are encouraged to experiment with the different options in order to achieve an efficient solution which adequately tracks the desired features of the solution.

Note that unless the monitor function for the initial solution values is zero at all user-specified initial mesh points, a new initial mesh is calculated and adopted according to the user-specified remeshing criteria. UVINIT will then be called again to determine the initial solution values at the new mesh points (there is no interpolation at this stage) and the integration proceeds.

4 References

Berzins M (1990) Developments in the NAG Library software for parabolic equations Scientific Software Systems (eds J C Mason and M G Cox) 59–72 Chapman and Hall

Berzins M, Dew P M and Furzeland R M (1989) Developing software for time-dependent problems using the method of lines and differential-algebraic integrators Appl. Numer. Math. 5 375–397

Berzins M and Furzeland R M (1992) An adaptive theta method for the solution of stiff and nonstiff differential equations Appl. Numer. Math. 9 1–19

Furzeland R M (1984) The construction of adaptive space meshes TNER.85.022 Thornton Research Centre, Chester

Keller H B (1970) A new difference scheme for parabolic problems Numerical Solutions of Partial Differential Equations (ed J Bramble) 2 327–350 Academic Press

Pennington S V and Berzins M (1994) New NAG Library software for first-order partial differential equations ACM Trans. Math. Softw. 20 63–99

5 Arguments

1:   NPDE – INTEGERInput

On entry: the number of PDEs to be solved.

Constraint: NPDE≥1.

2:   TS – REAL (KIND=nag_wp)Input/Output

On entry: the initial value of the independent variable t.

Constraint: TS<TOUT.

On exit: the value of t corresponding to the solution values in U. Normally TS=TOUT.

3:   TOUT – REAL (KIND=nag_wp)Input

On entry: the final value of t to which the integration is to be carried out.

4:   PDEDEF – SUBROUTINE, supplied by the user.External Procedure

PDEDEF must evaluate the functions Gi which define the system of PDEs. PDEDEF is called approximately midway between each pair of mesh points in turn by D03PRF.

The specification of PDEDEF is:

SUBROUTINE PDEDEF (

NPDE, T, X, U, UDOT, UX, NCODE, V, VDOT, RES, IRES)

INTEGER

NPDE, NCODE, IRES

REAL (KIND=nag_wp)

T, X, U(NPDE), UDOT(NPDE), UX(NPDE), V(NCODE), VDOT(NCODE), RES(NPDE)

1:   NPDE – INTEGERInput

On entry: the number of PDEs in the system.

2:   T – REAL (KIND=nag_wp)Input

On entry: the current value of the independent variable t.

3:   X – REAL (KIND=nag_wp)Input

On entry: the current value of the space variable x.

4:   U NPDE – REAL (KIND=nag_wp) arrayInput

On entry: U i contains the value of the component Ui x,t, for i=1,2,…,NPDE.

5:   UDOT NPDE – REAL (KIND=nag_wp) arrayInput

On entry: UDOT i contains the value of the component ∂Ui x,t ∂t , for i=1,2,…,NPDE.

6:   UX NPDE – REAL (KIND=nag_wp) arrayInput

On entry: UX i contains the value of the component ∂Ui x,t ∂x , for i=1,2,…,NPDE.

7:   NCODE – INTEGERInput

On entry: the number of coupled ODEs in the system.

8:   V NCODE – REAL (KIND=nag_wp) arrayInput

On entry: if NCODE>0, V i contains the value of the component Vi t, for i=1,2,…,NCODE.

9:   VDOT NCODE – REAL (KIND=nag_wp) arrayInput

On entry: if NCODE>0, VDOT i contains the value of component V.i t, for i=1,2,…,NCODE.

10:   RES NPDE – REAL (KIND=nag_wp) arrayOutput

On exit: RES i must contain the ith component of G, for i=1,2,…,NPDE, where G is defined as

Gi=∑j=1 NPDE P i,j ∂Uj ∂t +∑j=1 NCODE Q i,jV.j,

(9)

i.e., only terms depending explicitly on time derivatives, or

Gi=∑j=1 NPDE P i,j ∂Uj ∂t +∑j=1 NCODE Q i,jV.j+Si,

(10)

i.e., all terms in equation (3).
The definition of G is determined by the input value of IRES.

11:   IRES – INTEGERInput/Output

On entry: the form of Gi that must be returned in the array RES.
IRES=-1

Equation (9) must be used.

IRES=1

Equation (10) must be used.

On exit: should usually remain unchanged. However, you may set IRES to force the integration routine to take certain actions, as described below:
IRES=2

Indicates to the integrator that control should be passed back immediately to the calling (sub)routine with the error indicator set to IFAIL=6.

IRES=3

Indicates to the integrator that the current time step should be abandoned and a smaller time step used instead. You may wish to set IRES=3 when a physically meaningless input or output value has been generated. If you consecutively set IRES=3, then D03PRF returns to the calling subroutine with the error indicator set to IFAIL=4.

PDEDEF must either be a module subprogram USEd by, or declared as EXTERNAL in, the (sub)program from which D03PRF is called. Arguments denoted as Input must not be changed by this procedure.

5:   BNDARY – SUBROUTINE, supplied by the user.External Procedure

BNDARY must evaluate the functions GiL and GiR which describe the boundary conditions, as given in (5) and (6).

The specification of BNDARY is:

SUBROUTINE BNDARY (

NPDE, T, IBND, NOBC, U, UDOT, NCODE, V, VDOT, RES, IRES)

INTEGER

NPDE, IBND, NOBC, NCODE, IRES

REAL (KIND=nag_wp)

T, U(NPDE), UDOT(NPDE), V(NCODE), VDOT(NCODE), RES(NOBC)

1:   NPDE – INTEGERInput

On entry: the number of PDEs in the system.

2:   T – REAL (KIND=nag_wp)Input

On entry: the current value of the independent variable t.

3:   IBND – INTEGERInput

On entry: specifies which boundary conditions are to be evaluated.
IBND=0

BNDARY must compute the left-hand boundary condition at x=a.

IBND≠0

BNDARY must compute of the right-hand boundary condition at x=b.

4:   NOBC – INTEGERInput

On entry: specifies the number na of boundary conditions at the boundary specified by IBND.

5:   U NPDE – REAL (KIND=nag_wp) arrayInput

On entry: U i contains the value of the component Ui x,t at the boundary specified by IBND, for i=1,2,…,NPDE.

6:   UDOT NPDE – REAL (KIND=nag_wp) arrayInput

On entry: UDOT i contains the value of the component ∂Ui x,t ∂t , for i=1,2,…,NPDE.

7:   NCODE – INTEGERInput

On entry: the number of coupled ODEs in the system.

8:   V NCODE – REAL (KIND=nag_wp) arrayInput

On entry: if NCODE>0, V i contains the value of the component Vi t, for i=1,2,…,NCODE.

9:   VDOT NCODE – REAL (KIND=nag_wp) arrayInput

On entry: if NCODE>0, VDOT i contains the value of component V.i t, for i=1,2,…,NCODE.
Note: VDOT i, for i=1,2,…,NCODE, may only appear linearly as in (11) and (12).

10:   RES NOBC – REAL (KIND=nag_wp) arrayOutput

On exit: RES i must contain the ith component of GL or GR, depending on the value of IBND, for i=1,2,…,NOBC, where GL is defined as

GiL=∑j=1 NPDE E i,j L ∂Uj ∂t +∑j=1 NCODE H i,j L V.j,

(11)

i.e., only terms depending explicitly on time derivatives, or

GiL=∑j=1 NPDE E i,j L ∂Uj ∂t +∑j=1 NCODE H i,j L V.j+KiL,

(12)

i.e., all terms in equation (7), and similarly for GiR.
The definitions of GL and GR are determined by the input value of IRES.

11:   IRES – INTEGERInput/Output

On entry: the form of GiL (or GiR) that must be returned in the array RES.
IRES=-1

Equation (11) must be used.

IRES=1

Equation (12) must be used.

On exit: should usually remain unchanged. However, you may set IRES to force the integration routine to take certain actions as described below:
IRES=2

Indicates to the integrator that control should be passed back immediately to the calling (sub)routine with the error indicator set to IFAIL=6.

IRES=3

Indicates to the integrator that the current time step should be abandoned and a smaller time step used instead. You may wish to set IRES=3 when a physically meaningless input or output value has been generated. If you consecutively set IRES=3, then D03PRF returns to the calling subroutine with the error indicator set to IFAIL=4.

BNDARY must either be a module subprogram USEd by, or declared as EXTERNAL in, the (sub)program from which D03PRF is called. Arguments denoted as Input must not be changed by this procedure.

6:   UVINIT – SUBROUTINE, supplied by the user.External Procedure

UVINIT must supply the initial t=t 0 values of U x,t and V t for all values of x in the interval a,b.

The specification of UVINIT is:

SUBROUTINE UVINIT (

NPDE, NPTS, NXI, X, XI, U, NCODE, V)

INTEGER

NPDE, NPTS, NXI, NCODE

REAL (KIND=nag_wp)

X(NPTS), XI(NXI), U(NPDE,NPTS), V(NCODE)

1:   NPDE – INTEGERInput

On entry: the number of PDEs in the system.

2:   NPTS – INTEGERInput

On entry: the number of mesh points in the interval a,b.

3:   NXI – INTEGERInput

On entry: the number of ODE/PDE coupling points.

4:   X NPTS – REAL (KIND=nag_wp) arrayInput

On entry: the current mesh. X i contains the value of xi, for i=1,2,…,NPTS.

5:   XI NXI – REAL (KIND=nag_wp) arrayInput

On entry: if NXI>0, XI i contains the ODE/PDE coupling point, ξi, for i=1,2,…,NXI.

6:   U NPDENPTS – REAL (KIND=nag_wp) arrayOutput

On exit: if NXI>0, U ij contains the value of the component Ui xj,t 0, for i=1,2,…,NPDE and j=1,2,…,NPTS.

7:   NCODE – INTEGERInput

On entry: the number of coupled ODEs in the system.

8:   V NCODE – REAL (KIND=nag_wp) arrayOutput

On exit: if NCODE>0, V i must contain the value of component Vi t 0, for i=1,2,…,NCODE.

UVINIT must either be a module subprogram USEd by, or declared as EXTERNAL in, the (sub)program from which D03PRF is called. Arguments denoted as Input must not be changed by this procedure.

7:   U NEQN – REAL (KIND=nag_wp) arrayInput/Output

On entry: if IND=1, the value of U must be unchanged from the previous call.

On exit: U NPDE×j-1+i contains the computed solution Ui xj,t, for i=1,2,…,NPDE and j=1,2,…,NPTS, evaluated at t=TS.

8:   NPTS – INTEGERInput

On entry: the number of mesh points in the interval [a,b].

Constraint: NPTS≥3.

9:   X NPTS – REAL (KIND=nag_wp) arrayInput/Output

On entry: the initial mesh points in the space direction. X 1 must specify the left-hand boundary, a, and X NPTS must specify the right-hand boundary, b.

Constraint: X 1<X 2<⋯<X NPTS.

On exit: the final values of the mesh points.

10:   NLEFT – INTEGERInput

On entry: the number na of boundary conditions at the left-hand mesh point X 1.

Constraint: 0≤NLEFT≤NPDE.

11:   NCODE – INTEGERInput

On entry: the number of coupled ODE components.

Constraint: NCODE≥0.

12:   ODEDEF – SUBROUTINE, supplied by the NAG Library or the user.External Procedure

ODEDEF must evaluate the functions R, which define the system of ODEs, as given in (4).

If you wish to compute the solution of a system of PDEs only (i.e., NCODE=0), ODEDEF must be the dummy routine D03PEK. (D03PEK is included in the NAG Library.)

The specification of ODEDEF is:

SUBROUTINE ODEDEF (

NPDE, T, NCODE, V, VDOT, NXI, XI, UCP, UCPX, UCPT, R, IRES)

INTEGER

NPDE, NCODE, NXI, IRES

REAL (KIND=nag_wp)

T, V(NCODE), VDOT(NCODE), XI(NXI), UCP(NPDE,*), UCPX(NPDE,*), UCPT(NPDE,*), R(NCODE)

1:   NPDE – INTEGERInput

On entry: the number of PDEs in the system.

2:   T – REAL (KIND=nag_wp)Input

On entry: the current value of the independent variable t.

3:   NCODE – INTEGERInput

On entry: the number of coupled ODEs in the system.

4:   V NCODE – REAL (KIND=nag_wp) arrayInput

On entry: if NCODE>0, V i contains the value of the component Vi t, for i=1,2,…,NCODE.

5:   VDOT NCODE – REAL (KIND=nag_wp) arrayInput

On entry: if NCODE>0, VDOT i contains the value of component V.i t, for i=1,2,…,NCODE.

6:   NXI – INTEGERInput

On entry: the number of ODE/PDE coupling points.

7:   XI NXI – REAL (KIND=nag_wp) arrayInput

On entry: if NXI>0, XI i contains the ODE/PDE coupling point, ξi, for i=1,2,…,NXI.

8:   UCP NPDE* – REAL (KIND=nag_wp) arrayInput

On entry: if NXI>0, UCP ij contains the value of Ui x,t at the coupling point x=ξj, for i=1,2,…,NPDE and j=1,2,…,NXI.

9:   UCPX NPDE* – REAL (KIND=nag_wp) arrayInput

On entry: if NXI>0, UCPX ij contains the value of ∂Ui x,t ∂x at the coupling point x=ξj, for i=1,2,…,NPDE and j=1,2,…,NXI.

10:   UCPT NPDE* – REAL (KIND=nag_wp) arrayInput

On entry: if NXI>0, UCPT ij contains the value of ∂Ui ∂t at the coupling point x=ξj, for i=1,2,…,NPDE and j=1,2,…,NXI.

11:   R NCODE – REAL (KIND=nag_wp) arrayOutput

On exit: if NCODE>0, R i must contain the ith component of R, for i=1,2,…,NCODE, where R is defined as

R=-B V.-C Ut*,

(13)

i.e., only terms depending explicitly on time derivatives, or

R=A-B V.-C Ut*,

(14)

i.e., all terms in equation (4). The definition of R is determined by the input value of IRES.

12:   IRES – INTEGERInput/Output

On entry: the form of R that must be returned in the array R.
IRES=-1

Equation (13) must be used.

IRES=1

Equation (14) must be used.

On exit: should usually remain unchanged. However, you may reset IRES to force the integration routine to take certain actions, as described below:
IRES=2

Indicates to the integrator that control should be passed back immediately to the calling (sub)routine with the error indicator set to IFAIL=6.

IRES=3

Indicates to the integrator that the current time step should be abandoned and a smaller time step used instead. You may wish to set IRES=3 when a physically meaningless input or output value has been generated. If you consecutively set IRES=3, then D03PRF returns to the calling subroutine with the error indicator set to IFAIL=4.

ODEDEF must either be a module subprogram USEd by, or declared as EXTERNAL in, the (sub)program from which D03PRF is called. Arguments denoted as Input must not be changed by this procedure.

13:   NXI – INTEGERInput

On entry: the number of ODE/PDE coupling points.

Constraints:

if NCODE=0, NXI=0;

if NCODE>0, NXI≥0.

14:   XI* – REAL (KIND=nag_wp) arrayInput

Note: the dimension of the array XI must be at least max 1,NXI.

On entry: XI i, for i=1,2,…,NXI, must be set to the ODE/PDE coupling points, ξi.

Constraint: X 1≤XI 1<XI 2<⋯<XI NXI≤X NPTS.

15:   NEQN – INTEGERInput

On entry: the number of ODEs in the time direction.

Constraint: NEQN=NPDE×NPTS+NCODE.

16:   RTOL* – REAL (KIND=nag_wp) arrayInput

Note: the dimension of the array RTOL must be at least 1 if ITOL=1 or 2 and at least NEQN if ITOL=3 or 4.

On entry: the relative local error tolerance.

Constraint: RTOL i≥0.0 for all relevant i.

17:   ATOL* – REAL (KIND=nag_wp) arrayInput

Note: the dimension of the array ATOL must be at least 1 if ITOL=1 or 3 and at least NEQN if ITOL=2 or 4.

On entry: the absolute local error tolerance.

Constraint: ATOL i≥0.0 for all relevant i.
Note: corresponding elements of RTOL and ATOL cannot both be 0.0.

18:   ITOL – INTEGERInput

A value to indicate the form of the local error test. ITOL indicates to D03PRF whether to interpret either or both of RTOL or ATOL as a vector or scalar. The error test to be satisfied is ei/wi<1.0, where wi is defined as follows:

On entry:

ITOL

RTOL

ATOL

wi

1

scalar

scalar

RTOL 1×U i+ATOL 1

2

scalar

vector

RTOL 1×U i+ATOL i

3

vector

scalar

RTOL i×U i+ATOL 1

4

vector

vector

RTOL i×U i+ATOL i

In the above, ei denotes the estimated local error for the ith component of the coupled PDE/ODE system in time, U i, for i=1,2,…,NEQN.

The choice of norm used is defined by the argument NORM.

Constraint: ITOL=1, 2, 3 or 4.

19:   NORM – CHARACTER(1)Input

On entry: the type of norm to be used.
NORM='M'

Maximum norm.

NORM='A'

Averaged L 2 norm.

If Unorm denotes the norm of the vector U of length NEQN, then for the averaged L 2 norm

Unorm= 1 NEQN ∑i=1 NEQN U i/wi 2 ,

while for the maximum norm

Unorm=maxi U i/wi.

See the description of ITOL for the formulation of the weight vector w.

Constraint: NORM='M' or 'A'.

20:   LAOPT – CHARACTER(1)Input

On entry: the type of matrix algebra required.
LAOPT='F'

Full matrix methods to be used.

LAOPT='B'

Banded matrix methods to be used.

LAOPT='S'

Sparse matrix methods to be used.

Constraint: LAOPT='F', 'B' or 'S'.
Note: you are recommended to use the banded option when no coupled ODEs are present (i.e., NCODE=0).

21:   ALGOPT 30 – REAL (KIND=nag_wp) arrayInput

On entry: may be set to control various options available in the integrator. If you wish to employ all the default options, then ALGOPT 1 should be set to 0.0. Default values will also be used for any other elements of ALGOPT set to zero. The permissible values, default values, and meanings are as follows:
ALGOPT 1

Selects the ODE integration method to be used. If ALGOPT 1=1.0, a BDF method is used and if ALGOPT 1=2.0, a Theta method is used. The default value is ALGOPT 1=1.0.

If ALGOPT 1=2.0, then ALGOPT i, for i=2,3,4, are not used.

ALGOPT 2

Specifies the maximum order of the BDF integration formula to be used. ALGOPT 2 may be 1.0, 2.0, 3.0, 4.0 or 5.0. The default value is ALGOPT 2=5.0.

ALGOPT 3

Specifies what method is to be used to solve the system of nonlinear equations arising on each step of the BDF method. If ALGOPT 3=1.0 a modified Newton iteration is used and if ALGOPT 3=2.0 a functional iteration method is used. If functional iteration is selected and the integrator encounters difficulty, then there is an automatic switch to the modified Newton iteration. The default value is ALGOPT 3=1.0.

ALGOPT 4

Specifies whether or not the Petzold error test is to be employed. The Petzold error test results in extra overhead but is more suitable when algebraic equations are present, such as P i,j=0.0, for j=1,2,…,NPDE, for some i or when there is no V.i t dependence in the coupled ODE system. If ALGOPT 4=1.0, then the Petzold test is used. If ALGOPT 4=2.0, then the Petzold test is not used. The default value is ALGOPT 4=1.0.

If ALGOPT 1=1.0, then ALGOPT i, for i=5,6,7, are not used.

ALGOPT 5

Specifies the value of Theta to be used in the Theta integration method. 0.51≤ALGOPT 5≤0.99. The default value is ALGOPT 5=0.55.

ALGOPT 6

Specifies what method is to be used to solve the system of nonlinear equations arising on each step of the Theta method. If ALGOPT 6=1.0, a modified Newton iteration is used and if ALGOPT 6=2.0, a functional iteration method is used. The default value is ALGOPT 6=1.0.

ALGOPT 7

Specifies whether or not the integrator is allowed to switch automatically between modified Newton and functional iteration methods in order to be more efficient. If ALGOPT 7=1.0, then switching is allowed and if ALGOPT 7=2.0, then switching is not allowed. The default value is ALGOPT 7=1.0.

ALGOPT 11

Specifies a point in the time direction, tcrit, beyond which integration must not be attempted. The use of tcrit is described under the argument ITASK. If ALGOPT 1≠0.0, a value of 0.0, for ALGOPT 11, say, should be specified even if ITASK subsequently specifies that tcrit will not be used.

ALGOPT 12

Specifies the minimum absolute step size to be allowed in the time integration. If this option is not required, ALGOPT 12 should be set to 0.0.

ALGOPT 13

Specifies the maximum absolute step size to be allowed in the time integration. If this option is not required, ALGOPT 13 should be set to 0.0.

ALGOPT 14

Specifies the initial step size to be attempted by the integrator. If ALGOPT 14=0.0, then the initial step size is calculated internally.

ALGOPT 15

Specifies the maximum number of steps to be attempted by the integrator in any one call. If ALGOPT 15=0.0, then no limit is imposed.

ALGOPT 23

Specifies what method is to be used to solve the nonlinear equations at the initial point to initialize the values of U, Ut, V and V.. If ALGOPT 23=1.0, a modified Newton iteration is used and if ALGOPT 23=2.0, functional iteration is used. The default value is ALGOPT 23=1.0.

ALGOPT 29 and ALGOPT 30 are used only for the sparse matrix algebra option, i.e., LAOPT='S'.

ALGOPT 29

Governs the choice of pivots during the decomposition of the first Jacobian matrix. It should lie in the range 0.0<ALGOPT 29<1.0, with smaller values biasing the algorithm towards maintaining sparsity at the expense of numerical stability. If ALGOPT 29 lies outside this range then the default value is used. If the routines regard the Jacobian matrix as numerically singular then increasing ALGOPT 29 towards 1.0 may help, but at the cost of increased fill-in. The default value is ALGOPT 29=0.1.

ALGOPT 30

Used as a relative pivot threshold during subsequent Jacobian decompositions (see ALGOPT 29) below which an internal error is invoked. ALGOPT 30 must be greater than zero, otherwise the default value is used. If ALGOPT 30 is greater than 1.0 no check is made on the pivot size, and this may be a necessary option if the Jacobian is found to be numerically singular (see ALGOPT 29). The default value is ALGOPT 30=0.0001.

22:   REMESH – LOGICALInput

On entry: indicates whether or not spatial remeshing should be performed.
REMESH=.TRUE.

Indicates that spatial remeshing should be performed as specified.

REMESH=.FALSE.

Indicates that spatial remeshing should be suppressed.

Note: REMESH should not be changed between consecutive calls to D03PRF. Remeshing can be switched off or on at specified times by using appropriate values for the arguments NRMESH and TRMESH at each call.

23:   NXFIX – INTEGERInput

On entry: the number of fixed mesh points.

Constraint: 0≤NXFIX≤NPTS-2.
Note: the end points X 1 and X NPTS are fixed automatically and hence should not be specified as fixed points.

24:   XFIX* – REAL (KIND=nag_wp) arrayInput

Note: the dimension of the array XFIX must be at least max 1,NXFIX.

On entry: XFIX i, for i=1,2,…,NXFIX, must contain the value of the x coordinate at the ith fixed mesh point.

Constraint: XFIX i<XFIX i+1, for i=1,2,…,NXFIX-1, and each fixed mesh point must coincide with a user-supplied initial mesh point, that is XFIX i=X j for some j, 2≤j≤NPTS-1.
Note: the positions of the fixed mesh points in the array X remain fixed during remeshing, and so the number of mesh points between adjacent fixed points (or between fixed points and end points) does not change. You should take this into account when choosing the initial mesh distribution.

25:   NRMESH – INTEGERInput

On entry: indicates the form of meshing to be performed.
NRMESH<0

Indicates that a new mesh is adopted according to the argument DXMESH. The mesh is tested every NRMESH timesteps.

NRMESH=0

Indicates that remeshing should take place just once at the end of the first time step reached when t>TRMESH.

NRMESH>0

Indicates that remeshing will take place every NRMESH time steps, with no testing using DXMESH.

Note: NRMESH may be changed between consecutive calls to D03PRF to give greater flexibility over the times of remeshing.

26:   DXMESH – REAL (KIND=nag_wp)Input

On entry: determines whether a new mesh is adopted when NRMESH is set less than zero. A possible new mesh is calculated at the end of every NRMESH time steps, but is adopted only if

xinew>xiold+DXMESH×x i+1 old-xiold,

or

xinew<xiold-DXMESH×xiold-x i- 1 old.

DXMESH thus imposes a lower limit on the difference between one mesh and the next.

Constraint: DXMESH≥0.0.

27:   TRMESH – REAL (KIND=nag_wp)Input

On entry: specifies when remeshing will take place when NRMESH is set to zero. Remeshing will occur just once at the end of the first time step reached when t is greater than TRMESH.
Note: TRMESH may be changed between consecutive calls to D03PRF to force remeshing at several specified times.

28:   IPMINF – INTEGERInput

On entry: the level of trace information regarding the adaptive remeshing. Details are directed to the current advisory message unit (see X04ABF).
IPMINF=0

No trace information.

IPMINF=1

Brief summary of mesh characteristics.

IPMINF=2

More detailed information, including old and new mesh points, mesh sizes and monitor function values.

Constraint: IPMINF=0, 1 or 2.

29:   XRATIO – REAL (KIND=nag_wp)Input

On entry: input bound on adjacent mesh ratio (greater than 1.0 and typically in the range 1.5 to 3.0). The remeshing routines will attempt to ensure that

xi-x i-1/XRATIO<x i+1-xi<XRATIO×xi-x i-1.

Suggested value: XRATIO=1.5.

Constraint: XRATIO>1.0.

30:   CON – REAL (KIND=nag_wp)Input

On entry: an input bound on the sub-integral of the monitor function Fmon x over each space step. The remeshing routines will attempt to ensure that

∫x 1x i+1 Fmon x dx≤CON∫x 1xNPTS Fmon x dx,

(see Furzeland (1984)). CON gives you more control over the mesh distribution e.g., decreasing CON allows more clustering. A typical value is 2/NPTS-1, but you are encouraged to experiment with different values. Its value is not critical and the mesh should be qualitatively correct for all values in the range given below.

Suggested value: CON=2.0/NPTS-1.

Constraint: 0.1/NPTS-1≤CON≤10.0/NPTS-1.

31:   MONITF – SUBROUTINE, supplied by the NAG Library or the user.External Procedure

MONITF must supply and evaluate a remesh monitor function to indicate the solution behaviour of interest.

If you specify REMESH=.FALSE., i.e., no remeshing, then MONITF will not be called and the dummy routine D03PEL may be used for MONITF. (D03PEL is included in the NAG Library.)

The specification of MONITF is:

SUBROUTINE MONITF (

T, NPTS, NPDE, X, U, FMON)

INTEGER

NPTS, NPDE

REAL (KIND=nag_wp)

T, X(NPTS), U(NPDE,NPTS), FMON(NPTS)

1:   T – REAL (KIND=nag_wp)Input

On entry: the current value of the independent variable t.

2:   NPTS – INTEGERInput

On entry: the number of mesh points in the interval a,b.

3:   NPDE – INTEGERInput

On entry: the number of PDEs in the system.

4:   X NPTS – REAL (KIND=nag_wp) arrayInput

On entry: the current mesh. X i contains the value of xi, for i=1,2,…,NPTS.

5:   U NPDENPTS – REAL (KIND=nag_wp) arrayInput

On entry: U ij contains the value of Ui x,t at x=X j and time t, for i=1,2,…,NPDE and j=1,2,…,NPTS.

6:   FMON NPTS – REAL (KIND=nag_wp) arrayOutput

On exit: FMON i must contain the value of the monitor function Fmon x at mesh point x=X i.

Constraint: FMON i≥0.0.

MONITF must either be a module subprogram USEd by, or declared as EXTERNAL in, the (sub)program from which D03PRF is called. Arguments denoted as Input must not be changed by this procedure.

32:   RSAVE LRSAVE – REAL (KIND=nag_wp) arrayCommunication Array

If IND=0, RSAVE need not be set on entry.

If IND=1, RSAVE must be unchanged from the previous call to the routine because it contains required information about the iteration.

33:   LRSAVE – INTEGERInput

On entry: the dimension of the array RSAVE as declared in the (sub)program from which D03PRF is called. Its size depends on the type of matrix algebra selected.
If LAOPT='F', LRSAVE≥NEQN×NEQN+NEQN+nwkres+lenode.

If LAOPT='B', LRSAVE≥3×ml+mu+2×NEQN+nwkres+lenode.

If LAOPT='S', LRSAVE≥4×NEQN+11×NEQN/2+1+nwkres+lenode.

Where

ml and mu are the lower and upper half bandwidths given by ml=NPDE+NLEFT-1 such that
mu=2×NPDE-NLEFT-1, for problems involving PDEs only; or
ml=mu=NEQN-1, for coupled PDE/ODE problems.

nwkres= NPDE×3×NPDE+6×NXI+NPTS+15+NXI+NCODE+7×NPTS+NXFIX+1, when ​NCODE>0​ and ​NXI>0; or NPDE×3×NPDE+NPTS+21+NCODE+7×NPTS+NXFIX+2, when ​NCODE>0​ and ​NXI=0; or NPDE×3×NPDE+NPTS+21+7×NPTS+NXFIX+3, when ​NCODE=0.

lenode= 6+int ALGOPT 2×NEQN+50, when the BDF method is used; or 9×NEQN+50, when the Theta method is used.

Note: when using the sparse option, the value of LRSAVE may be too small when supplied to the integrator. An estimate of the minimum size of LRSAVE is printed on the current error message unit if ITRACE>0 and the routine returns with IFAIL=15.

34:   ISAVE LISAVE – INTEGER arrayCommunication Array

If IND=0, ISAVE need not be set.

If IND=1, ISAVE must be unchanged from the previous call to the routine because it contains required information about the iteration. In particular the following components of the array ISAVE concern the efficiency of the integration:
ISAVE 1

Contains the number of steps taken in time.

ISAVE 2

Contains the number of residual evaluations of the resulting ODE system used. One such evaluation involves evaluating the PDE functions at all the mesh points, as well as one evaluation of the functions in the boundary conditions.

ISAVE 3

Contains the number of Jacobian evaluations performed by the time integrator.

ISAVE 4

Contains the order of the ODE method last used in the time integration.

ISAVE 5

Contains the number of Newton iterations performed by the time integrator. Each iteration involves residual evaluation of the resulting ODE system followed by a back-substitution using the LU decomposition of the Jacobian matrix.

The rest of the array is used as workspace.

35:   LISAVE – INTEGERInput

On entry: the dimension of the array ISAVE as declared in the (sub)program from which D03PRF is called. Its size depends on the type of matrix algebra selected:

if LAOPT='F', LISAVE≥25+NXFIX;

if LAOPT='B', LISAVE≥NEQN+25+NXFIX;

if LAOPT='S', LISAVE≥25×NEQN+25+NXFIX.

Note: when using the sparse option, the value of LISAVE may be too small when supplied to the integrator. An estimate of the minimum size of LISAVE is printed on the current error message unit if ITRACE>0 and the routine returns with IFAIL=15.

36:   ITASK – INTEGERInput

On entry: the task to be performed by the ODE integrator.
ITASK=1

Normal computation of output values U at t=TOUT (by overshooting and interpolating).

ITASK=2

Take one step in the time direction and return.

ITASK=3

Stop at first internal integration point at or beyond t=TOUT.

ITASK=4

Normal computation of output values U at t=TOUT but without overshooting t=tcrit where tcrit is described under the argument ALGOPT.

ITASK=5

Take one step in the time direction and return, without passing tcrit, where tcrit is described under the argument ALGOPT.

Constraint: ITASK=1, 2, 3, 4 or 5.

37:   ITRACE – INTEGERInput

On entry: the level of trace information required from D03PRF and the underlying ODE solver as follows:
ITRACE≤-1

No output is generated.

ITRACE=0

Only warning messages from the PDE solver are printed on the current error message unit (see X04AAF).

ITRACE=1

Output from the underlying ODE solver is printed on the current advisory message unit (see X04ABF). This output contains details of Jacobian entries, the nonlinear iteration and the time integration during the computation of the ODE system.

ITRACE=2

Output from the underlying ODE solver is similar to that produced when ITRACE=1, except that the advisory messages are given in greater detail.

ITRACE≥3

The output from the underlying ODE solver is similar to that produced when ITRACE=2, except that the advisory messages are given in greater detail.

You are advised to set ITRACE=0, unless you are experienced with Sub-chapter D02M–N.

38:   IND – INTEGERInput/Output

On entry: indicates whether this is a continuation call or a new integration.
IND=0

Starts or restarts the integration in time.

IND=1

Continues the integration after an earlier exit from the routine. In this case, only the arguments TOUT and IFAIL and the remeshing arguments NRMESH, DXMESH, TRMESH, XRATIO and CON may be reset between calls to D03PRF.

Constraint: IND=0 or 1.

On exit: IND=1.

39:   IFAIL – INTEGERInput/Output

On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.

On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).

Errors or warnings detected by the routine:

IFAIL=1

On entry,

TOUT-TS is too small,

or

ITASK≠1, 2, 3, 4 or 5,

or

at least one of the coupling points defined in array XI is outside the interval [X 1,X NPTS],

or

NPTS<3,

or

NPDE<1,

or

NLEFT not in the range 0 to NPDE,

or

NORM≠'A' or 'M',

or

LAOPT≠'F', 'B' or 'S',

or

ITOL≠1, 2, 3 or 4,

or

IND≠0 or 1,

or

mesh points X i are badly ordered,

or

LRSAVE is too small,

or

LISAVE is too small,

or

NCODE and NXI are incorrectly defined,

or

IND=1 on initial entry to D03PRF,

or

an element of RTOL or ATOL<0.0,

or

corresponding elements of RTOL and ATOL are both 0.0,

or

NEQN≠NPDE×NPTS+NCODE,

or

NXFIX not in the range 0 to NPTS-2,

or

fixed mesh point(s) do not coincide with any of the user-supplied mesh points,

or

DXMESH<0.0,

or

IPMINF≠0, 1 or 2,

or

XRATIO≤1.0,

or

CON not in the range 0.1/NPTS-1 to 10/NPTS-1.

IFAIL=2

The underlying ODE solver cannot make any further progress, with the values of ATOL and RTOL, across the integration range from the current point t=TS. The components of U contain the computed values at the current point t=TS.

IFAIL=3

In the underlying ODE solver, there were repeated error test failures on an attempted step, before completing the requested task, but the integration was successful as far as t=TS. The problem may have a singularity, or the error requirement may be inappropriate. Incorrect positioning of boundary conditions may also result in this error.

IFAIL=4

In setting up the ODE system, the internal initialization routine was unable to initialize the derivative of the ODE system. This could be due to the fact that IRES was repeatedly set to 3 in one of PDEDEF, BNDARY or ODEDEF, when the residual in the underlying ODE solver was being evaluated. Incorrect positioning of boundary conditions may also result in this error.

IFAIL=5

In solving the ODE system, a singular Jacobian has been encountered. You should check their problem formulation.

IFAIL=6

When evaluating the residual in solving the ODE system, IRES was set to 2 in one of PDEDEF, BNDARY or ODEDEF. Integration was successful as far as t=TS.

IFAIL=7

The values of ATOL and RTOL are so small that the routine is unable to start the integration in time.

IFAIL=8

In either, PDEDEF, BNDARY or ODEDEF, IRES was set to an invalid value.

IFAIL=9 (D02NNF)

A serious error has occurred in an internal call to the specified routine. Check the problem specification an all arguments and array dimensions. Setting ITRACE=1 may provide more information. If the problem persists, contact NAG.

IFAIL=10

The required task has been completed, but it is estimated that a small change in ATOL and RTOL is unlikely to produce any change in the computed solution. (Only applies when you are not operating in one step mode, that is when ITASK≠2 or 5.)

IFAIL=11

An error occurred during Jacobian formulation of the ODE system (a more detailed error description may be directed to the current advisory message unit). If using the sparse matrix algebra option, the values of ALGOPT 29 and ALGOPT 30 may be inappropriate.

IFAIL=12

In solving the ODE system, the maximum number of steps specified in ALGOPT 15 have been taken.

IFAIL=13

Some error weights wi became zero during the time integration (see the description of ITOL). Pure relative error control ATOL i=0.0 was requested on a variable (the ith) which has become zero. The integration was successful as far as t=TS.

IFAIL=14

Not applicable.

IFAIL=15

When using the sparse option, the value of LISAVE or LRSAVE was insufficient (more detailed information may be directed to the current error message unit).

IFAIL=16

REMESH has been changed between calls to D03PRF.

IFAIL=-99

An unexpected error has been triggered by this routine. Please contact NAG.

See Section 3.9 in How to Use the NAG Library and its Documentation for further information.

IFAIL=-399

Your licence key may have expired or may not have been installed correctly.

See Section 3.8 in How to Use the NAG Library and its Documentation for further information.

IFAIL=-999

Dynamic memory allocation failed.

See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

D03PRF controls the accuracy of the integration in the time direction but not the accuracy of the approximation in space. The spatial accuracy depends on both the number of mesh points and on their distribution in space. In the time integration only the local error over a single step is controlled and so the accuracy over a number of steps cannot be guaranteed. You should therefore test the effect of varying the accuracy arguments, ATOL and RTOL.

8 Parallelism and Performance

D03PRF is not thread safe and should not be called from a multithreaded user program. Please see Section 3.12.1 in How to Use the NAG Library and its Documentation for more information on thread safety.

D03PRF is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.

D03PRF makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.

Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The Keller box scheme can be used to solve higher-order problems which have been reduced to first-order by the introduction of new variables (see the example in Section 10). In general, a second-order problem can be solved with slightly greater accuracy using the Keller box scheme instead of a finite difference scheme (D03PPF/D03PPA for example), but at the expense of increased CPU time due to the larger number of function evaluations required.

It should be noted that the Keller box scheme, in common with other central-difference schemes, may be unsuitable for some hyperbolic first-order problems such as the apparently simple linear advection equation Ut+a Ux=0, where a is a constant, resulting in spurious oscillations due to the lack of dissipation. This type of problem requires a discretization scheme with upwind weighting (D03PSF for example), or the addition of a second-order artificial dissipation term.

The time taken depends on the complexity of the system, the accuracy requested, and the frequency of the mesh updates. For a given system with fixed accuracy and mesh-update frequency it is approximately proportional to NEQN.

10 Example

This example is the first-order system

∂U 1 ∂t + ∂U 1 ∂x + ∂U 2 ∂x = 0, ∂U 2 ∂t +4 ∂U 1 ∂x + ∂U 2 ∂x = 0,

for x∈0,1 and t≥0.

The initial conditions are

U 1 x,0 = ex, U 2 x,0 = x 2+sin 2 π x 2,

and the Dirichlet boundary conditions for U 1 at x=0 and U 2 at x=1 are given by the exact solution:

U 1 x,t = 12 e x+t+e x-3 t+14 sin 2 π x-3 t 2-sin 2 π x+t 2+2⁢t 2-2 xt, U 2 x,t = e x-3 t-e x+t+12 sin 2 π x-3 t 2+sin 2 π x+t 2+x 2+5⁢t 2-2 xt.

10.1 Program Text

Program Text (d03prfe.f90)

10.2 Program Data

Program Data (d03prfe.d)

10.3 Program Results

Program Results (d03prfe.r)

D03 Chapter Contents

D03 Chapter Introduction

NAG Library Manual

© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


D03PSF : NAG Library, Mark 26

D03 Chapter Contents

D03 Chapter Introduction

NAG Library Manual

NAG Library Routine Document

D03PSF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose

2 Specification

3 Description

4 References

5 Arguments

6 Error Indicators and Warnings

7 Accuracy

8 Parallelism and Performance

9 Further Comments

▸▿ 10 Example

10.1 Program Text

10.2 Program Data

10.3 Program Results

1 Purpose

D03PSF integrates a system of linear or nonlinear convection-diffusion equations in one space dimension, with optional source terms and scope for coupled ordinary differential equations (ODEs). The system must be posed in conservative form. This routine also includes the option of automatic adaptive spatial remeshing. Convection terms are discretized using a sophisticated upwind scheme involving a user-supplied numerical flux function based on the solution of a Riemann problem at each mesh point. The method of lines is employed to reduce the partial differential equations (PDEs) to a system of ODEs, and the resulting system is solved using a backward differentiation formula (BDF) method or a Theta method.

2 Specification

SUBROUTINE D03PSF (

NPDE, TS, TOUT, PDEDEF, NUMFLX, BNDARY, UVINIT, U, NPTS, X, NCODE, ODEDEF, NXI, XI, NEQN, RTOL, ATOL, ITOL, NORM, LAOPT, ALGOPT, REMESH, NXFIX, XFIX, NRMESH, DXMESH, TRMESH, IPMINF, XRATIO, CON, MONITF, RSAVE, LRSAVE, ISAVE, LISAVE, ITASK, ITRACE, IND, IFAIL)

INTEGER

NPDE, NPTS, NCODE, NXI, NEQN, ITOL, NXFIX, NRMESH, IPMINF, LRSAVE, ISAVE(LISAVE), LISAVE, ITASK, ITRACE, IND, IFAIL

REAL (KIND=nag_wp)

TS, TOUT, U(NEQN), X(NPTS), XI(NXI), RTOL(*), ATOL(*), ALGOPT(30), XFIX(*), DXMESH, TRMESH, XRATIO, CON, RSAVE(LRSAVE)

LOGICAL

REMESH

CHARACTER(1)

NORM, LAOPT

EXTERNAL

PDEDEF, NUMFLX, BNDARY, UVINIT, ODEDEF, MONITF

3 Description

D03PSF integrates the system of convection-diffusion equations in conservative form:

∑j=1 NPDE P i,j ∂Uj ∂t + ∂Fi ∂x =Ci ∂Di ∂x +Si,

(1)

or the hyperbolic convection-only system:

∂Ui ∂t + ∂Fi ∂x =0,

(2)

for i=1,2,…,NPDE, a≤x≤b, t≥t 0, where the vector U is the set of PDE solution values

U x,t=U 1 x,t,…,UNPDE x,t T.

The optional coupled ODEs are of the general form

Ri t,V,V.,ξ,U*,Ux*,Ut*=0,  i=1,2,…,NCODE,

(3)

where the vector V is the set of ODE solution values

V t=V 1 t,…,VNCODE t T,

V. denotes its derivative with respect to time, and Ux is the spatial derivative of U.

In (2), P i,j, Fi and Ci depend on x, t, U and V; Di depends on x, t, U, Ux and V; and Si depends on x, t, U, V and linearly on V.. Note that P i,j, Fi, Ci and Si must not depend on any space derivatives, and P i,j, Fi, Ci and Di must not depend on any time derivatives. In terms of conservation laws, Fi, Ci∂Di ∂x and Si are the convective flux, diffusion and source terms respectively.

In (3), ξ represents a vector of nξ spatial coupling points at which the ODEs are coupled to the PDEs. These points may or may not be equal to PDE spatial mesh points. U*, Ux* and Ut* are the functions U, Ux and Ut evaluated at these coupling points. Each Ri may depend only linearly on time derivatives. Hence (3) may be written more precisely as

R=L-M V.-N Ut*,

(4)

where R=R 1,…,RNCODE T, L is a vector of length NCODE, M is an NCODE by NCODE matrix, N is an NCODE by nξ×NPDE matrix and the entries in L, M and N may depend on t, ξ, U*, Ux* and V. In practice you only need to supply a vector of information to define the ODEs and not the matrices L, M and N. (See Section 5 for the specification of ODEDEF.)

The integration in time is from t 0 to tout, over the space interval a≤x≤b, where a=x 1 and b=xNPTS are the leftmost and rightmost points of a user-defined mesh x 1,x 2,…,xNPTS defined initially by you and (possibly) adapted automatically during the integration according to user-specified criteria.

The initial t=t 0 values of the functions U x,t and V t must be specified in UVINIT. Note that UVINIT will be called again following any initial remeshing, and so U x,t 0 should be specified for all values of x in the interval a≤x≤b, and not just the initial mesh points.

The PDEs are approximated by a system of ODEs in time for the values of Ui at mesh points using a spatial discretization method similar to the central-difference scheme used in D03PCF/D03PCA, D03PHF/D03PHA and D03PPF/D03PPA, but with the flux Fi replaced by a numerical flux, which is a representation of the flux taking into account the direction of the flow of information at that point (i.e., the direction of the characteristics). Simple central differencing of the numerical flux then becomes a sophisticated upwind scheme in which the correct direction of upwinding is automatically achieved.

The numerical flux, F^i say, must be calculated by you in terms of the left and right values of the solution vector U (denoted by UL and UR respectively), at each mid-point of the mesh x j-12=x j-1+xj/2, for j=2,3,…,NPTS. The left and right values are calculated by D03PSF from two adjacent mesh points using a standard upwind technique combined with a Van Leer slope-limiter (see LeVeque (1990)). The physically correct value for F^i is derived from the solution of the Riemann problem given by

∂Ui ∂t + ∂Fi ∂y =0,

(5)

where y=x-x j-12, i.e., y=0 corresponds to x=x j-12, with discontinuous initial values U=UL for y<0 and U=UR for y>0, using an approximate Riemann solver. This applies for either of the systems (1) or (2); the numerical flux is independent of the functions P i,j, Ci, Di and Si. A description of several approximate Riemann solvers can be found in LeVeque (1990) and Berzins et al. (1989). Roe's scheme (see Roe (1981)) is perhaps the easiest to understand and use, and a brief summary follows. Consider the system of PDEs Ut+Fx=0 or equivalently Ut+A Ux=0. Provided the system is linear in U, i.e., the Jacobian matrix A does not depend on U, the numerical flux F^ is given by

F^=12 FL+FR-12∑k=1 NPDE αk λk ek,

(6)

where FL (FR) is the flux F calculated at the left (right) value of U, denoted by UL (UR); the λk are the eigenvalues of A; the ek are the right eigenvectors of A; and the αk are defined by

UR-UL=∑k=1 NPDE αkek.

(7)

Examples are given in the documents for D03PFF and D03PLF.

If the system is nonlinear, Roe's scheme requires that a linearized Jacobian is found (see Roe (1981)).

The functions P i,j, Ci, Di and Si (but not Fi) must be specified in PDEDEF. The numerical flux F^i must be supplied in NUMFLX. For problems in the form (2), the actual argument D03PLP may be used for PDEDEF. D03PLP is included in the NAG Library and sets the matrix with entries P i,j to the identity matrix, and the functions Ci, Di and Si to zero.

For second-order problems, i.e., diffusion terms are present, a boundary condition is required for each PDE at both boundaries for the problem to be well-posed. If there are no diffusion terms present, then the continuous PDE problem generally requires exactly one boundary condition for each PDE, that is NPDE boundary conditions in total. However, in common with most discretization schemes for first-order problems, a numerical boundary condition is required at the other boundary for each PDE. In order to be consistent with the characteristic directions of the PDE system, the numerical boundary conditions must be derived from the solution inside the domain in some manner (see below). You must supply both types of boundary conditions, i.e., a total of NPDE conditions at each boundary point.

The position of each boundary condition should be chosen with care. In simple terms, if information is flowing into the domain then a physical boundary condition is required at that boundary, and a numerical boundary condition is required at the other boundary. In many cases the boundary conditions are simple, e.g., for the linear advection equation. In general you should calculate the characteristics of the PDE system and specify a physical boundary condition for each of the characteristic variables associated with incoming characteristics, and a numerical boundary condition for each outgoing characteristic.

A common way of providing numerical boundary conditions is to extrapolate the characteristic variables from the inside of the domain (note that when using banded matrix algebra the fixed bandwidth means that only linear extrapolation is allowed, i.e., using information at just two interior points adjacent to the boundary). For problems in which the solution is known to be uniform (in space) towards a boundary during the period of integration then extrapolation is unnecessary; the numerical boundary condition can be supplied as the known solution at the boundary. Another method of supplying numerical boundary conditions involves the solution of the characteristic equations associated with the outgoing characteristics. Examples of both methods can be found in the documents for D03PFF and D03PLF.

The boundary conditions must be specified in BNDARY in the form

GiL x,t,U,V,V.=0  at ​x=a,  i=1,2,…,NPDE,

(8)

at the left-hand boundary, and

GiR x,t,U,V,V.=0  at ​x=b,  i=1,2,…,NPDE,

(9)

at the right-hand boundary.

Note that spatial derivatives at the boundary are not passed explicitly to BNDARY, but they can be calculated using values of U at and adjacent to the boundaries if required. However, it should be noted that instabilities may occur if such one-sided differencing opposes the characteristic direction at the boundary.

The algebraic-differential equation system which is defined by the functions Ri must be specified in ODEDEF. You must also specify the coupling points ξ (if any) in the array XI.

In total there are NPDE×NPTS+NCODE ODEs in the time direction. This system is then integrated forwards in time using a BDF or Theta method, optionally switching between Newton's method and functional iteration (see Berzins et al. (1989) and the references therein).

The adaptive space remeshing can be used to generate meshes that automatically follow the changing time-dependent nature of the solution, generally resulting in a more efficient and accurate solution using fewer mesh points than may be necessary with a fixed uniform or non-uniform mesh. Problems with travelling wavefronts or variable-width boundary layers for example will benefit from using a moving adaptive mesh. The discrete time-step method used here (developed by Furzeland (1984)) automatically creates a new mesh based on the current solution profile at certain time-steps, and the solution is then interpolated onto the new mesh and the integration continues.

The method requires you to supply a MONITF which specifies in an analytical or numerical form the particular aspect of the solution behaviour you wish to track. This so-called monitor function is used by the routine to choose a mesh which equally distributes the integral of the monitor function over the domain. A typical choice of monitor function is the second space derivative of the solution value at each point (or some combination of the second space derivatives if there is more than one solution component), which results in refinement in regions where the solution gradient is changing most rapidly.

You must specify the frequency of mesh updates together with certain other criteria such as adjacent mesh ratios. Remeshing can be expensive and you are encouraged to experiment with the different options in order to achieve an efficient solution which adequately tracks the desired features of the solution.

Note that unless the monitor function for the initial solution values is zero at all user-specified initial mesh points, a new initial mesh is calculated and adopted according to the user-specified remeshing criteria. UVINIT will then be called again to determine the initial solution values at the new mesh points (there is no interpolation at this stage) and the integration proceeds.

The problem is subject to the following restrictions:

(i)

In (1), V.j t, for j=1,2,…,NCODE, may only appear linearly in the functions Si, for i=1,2,…,NPDE, with a similar restriction for GiL and GiR;

(ii)

P i,j, Fi, Ci and Si must not depend on any space derivatives; and P i,j, Ci, Di and Fi must not depend on any time derivatives;

(iii)

t 0<tout, so that integration is in the forward direction;

(iv)

The evaluation of the terms P i,j, Ci, Di and Si is done by calling the PDEDEF at a point approximately midway between each pair of mesh points in turn. Any discontinuities in these functions must therefore be at one or more of the fixed mesh points specified by XFIX;

(v)

At least one of the functions P i,j must be nonzero so that there is a time derivative present in the PDE problem.

For further details of the scheme, see Pennington and Berzins (1994) and the references therein.

4 References

Berzins M, Dew P M and Furzeland R M (1989) Developing software for time-dependent problems using the method of lines and differential-algebraic integrators Appl. Numer. Math. 5 375–397

Furzeland R M (1984) The construction of adaptive space meshes TNER.85.022 Thornton Research Centre, Chester

Hirsch C (1990) Numerical Computation of Internal and External Flows, Volume 2: Computational Methods for Inviscid and Viscous Flows John Wiley

LeVeque R J (1990) Numerical Methods for Conservation Laws Birkhäuser Verlag

Pennington S V and Berzins M (1994) New NAG Library software for first-order partial differential equations ACM Trans. Math. Softw. 20 63–99

Roe P L (1981) Approximate Riemann solvers, parameter vectors, and difference schemes J. Comput. Phys. 43 357–372

5 Arguments

1:   NPDE – INTEGERInput

On entry: the number of PDEs to be solved.

Constraint: NPDE≥1.

2:   TS – REAL (KIND=nag_wp)Input/Output

On entry: the initial value of the independent variable t.

On exit: the value of t corresponding to the solution values in U. Normally TS=TOUT.

Constraint: TS<TOUT.

3:   TOUT – REAL (KIND=nag_wp)Input

On entry: the final value of t to which the integration is to be carried out.

4:   PDEDEF – SUBROUTINE, supplied by the NAG Library or the user.External Procedure

PDEDEF must evaluate the functions P i,j, Ci, Di and Si which partially define the system of PDEs. P i,j and Ci may depend on x, t, U and V; Di may depend on x, t, U, Ux and V; and Si may depend on x, t, U, V and linearly on V.. PDEDEF is called approximately midway between each pair of mesh points in turn by D03PSF. The actual argument D03PLP may be used for PDEDEF for problems in the form (2). (D03PLP is included in the NAG Library.)

The specification of PDEDEF is:

SUBROUTINE PDEDEF (

NPDE, T, X, U, UX, NCODE, V, VDOT, P, C, D, S, IRES)

INTEGER

NPDE, NCODE, IRES

REAL (KIND=nag_wp)

T, X, U(NPDE), UX(NPDE), V(NCODE), VDOT(NCODE), P(NPDE,NPDE), C(NPDE), D(NPDE), S(NPDE)

1:   NPDE – INTEGERInput

On entry: the number of PDEs in the system.

2:   T – REAL (KIND=nag_wp)Input

On entry: the current value of the independent variable t.

3:   X – REAL (KIND=nag_wp)Input

On entry: the current value of the space variable x.

4:   U NPDE – REAL (KIND=nag_wp) arrayInput

On entry: U i contains the value of the component Ui x,t, for i=1,2,…,NPDE.

5:   UX NPDE – REAL (KIND=nag_wp) arrayInput

On entry: UX i contains the value of the component ∂Ui x,t ∂x , for i=1,2,…,NPDE.

6:   NCODE – INTEGERInput

On entry: the number of coupled ODEs in the system.

7:   V NCODE – REAL (KIND=nag_wp) arrayInput

On entry: if NCODE>0, V i contains the value of the component Vi t, for i=1,2,…,NCODE.

8:   VDOT NCODE – REAL (KIND=nag_wp) arrayInput

On entry: if NCODE>0, VDOT i contains the value of component V.i t, for i=1,2,…,NCODE.
Note: V.i t, for i=1,2,…,NCODE, may only appear linearly in Sj, for j=1,2,…,NPDE.

9:   P NPDENPDE – REAL (KIND=nag_wp) arrayOutput

On exit: P ij must be set to the value of P i,j x,t,U,V, for i=1,2,…,NPDE and j=1,2,…,NPDE.

10:   C NPDE – REAL (KIND=nag_wp) arrayOutput

On exit: C i must be set to the value of Ci x,t,U,V, for i=1,2,…,NPDE.

11:   D NPDE – REAL (KIND=nag_wp) arrayOutput

On exit: D i must be set to the value of Di x,t,U,Ux,V, for i=1,2,…,NPDE.

12:   S NPDE – REAL (KIND=nag_wp) arrayOutput

On exit: S i must be set to the value of Si x,t,U,V,V., for i=1,2,…,NPDE.

13:   IRES – INTEGERInput/Output

On entry: set to -1​ or ​1.

On exit: should usually remain unchanged. However, you may set IRES to force the integration routine to take certain actions as described below:
IRES=2

Indicates to the integrator that control should be passed back immediately to the calling (sub)routine with the error indicator set to IFAIL=6.

IRES=3

Indicates to the integrator that the current time step should be abandoned and a smaller time step used instead. You may wish to set IRES=3 when a physically meaningless input or output value has been generated. If you consecutively set IRES=3, then D03PSF returns to the calling subroutine with the error indicator set to IFAIL=4.

PDEDEF must either be a module subprogram USEd by, or declared as EXTERNAL in, the (sub)program from which D03PSF is called. Arguments denoted as Input must not be changed by this procedure.

5:   NUMFLX – SUBROUTINE, supplied by the user.External Procedure

NUMFLX must supply the numerical flux for each PDE given the left and right values of the solution vector U. NUMFLX is called approximately midway between each pair of mesh points in turn by D03PSF.

The specification of NUMFLX is:

SUBROUTINE NUMFLX (

NPDE, T, X, NCODE, V, ULEFT, URIGHT, FLUX, IRES)

INTEGER

NPDE, NCODE, IRES

REAL (KIND=nag_wp)

T, X, V(NCODE), ULEFT(NPDE), URIGHT(NPDE), FLUX(NPDE)

1:   NPDE – INTEGERInput

On entry: the number of PDEs in the system.

2:   T – REAL (KIND=nag_wp)Input

On entry: the current value of the independent variable t.

3:   X – REAL (KIND=nag_wp)Input

On entry: the current value of the space variable x.

4:   NCODE – INTEGERInput

On entry: the number of coupled ODEs in the system.

5:   V NCODE – REAL (KIND=nag_wp) arrayInput

On entry: if NCODE>0, V i contains the value of the component Vi t, for i=1,2,…,NCODE.

6:   ULEFT NPDE – REAL (KIND=nag_wp) arrayInput

On entry: ULEFT i contains the left value of the component Ui x, for i=1,2,…,NPDE.

7:   URIGHT NPDE – REAL (KIND=nag_wp) arrayInput

On entry: URIGHT i contains the right value of the component Ui x, for i=1,2,…,NPDE.

8:   FLUX NPDE – REAL (KIND=nag_wp) arrayOutput

On exit: FLUX i must be set to the numerical flux F^i, for i=1,2,…,NPDE.

9:   IRES – INTEGERInput/Output

On entry: set to -1​ or ​1.

On exit: should usually remain unchanged. However, you may set IRES to force the integration routine to take certain actions as described below:
IRES=2

Indicates to the integrator that control should be passed back immediately to the calling (sub)routine with the error indicator set to IFAIL=6.

IRES=3

Indicates to the integrator that the current time step should be abandoned and a smaller time step used instead. You may wish to set IRES=3 when a physically meaningless input or output value has been generated. If you consecutively set IRES=3, then D03PSF returns to the calling subroutine with the error indicator set to IFAIL=4.

NUMFLX must either be a module subprogram USEd by, or declared as EXTERNAL in, the (sub)program from which D03PSF is called. Arguments denoted as Input must not be changed by this procedure.

6:   BNDARY – SUBROUTINE, supplied by the user.External Procedure

BNDARY must evaluate the functions GiL and GiR which describe the physical and numerical boundary conditions, as given by (8) and (9).

The specification of BNDARY is:

SUBROUTINE BNDARY (

NPDE, NPTS, T, X, U, NCODE, V, VDOT, IBND, G, IRES)

INTEGER

NPDE, NPTS, NCODE, IBND, IRES

REAL (KIND=nag_wp)

T, X(NPTS), U(NPDE,NPTS), V(NCODE), VDOT(NCODE), G(NPDE)

1:   NPDE – INTEGERInput

On entry: the number of PDEs in the system.

2:   NPTS – INTEGERInput

On entry: the number of mesh points in the interval a,b.

3:   T – REAL (KIND=nag_wp)Input

On entry: the current value of the independent variable t.

4:   X NPTS – REAL (KIND=nag_wp) arrayInput

On entry: the mesh points in the spatial direction. X 1 corresponds to the left-hand boundary, a, and X NPTS corresponds to the right-hand boundary, b.

5:   U NPDENPTS – REAL (KIND=nag_wp) arrayInput

On entry: U ij contains the value of the component Ui x,t at x=X j, for i=1,2,…,NPDE and j=1,2,…,NPTS.
Note: if banded matrix algebra is to be used then the functions GiL and GiR may depend on the value of Ui x,t at the boundary point and the two adjacent points only.

6:   NCODE – INTEGERInput

On entry: the number of coupled ODEs in the system.

7:   V NCODE – REAL (KIND=nag_wp) arrayInput

On entry: if NCODE>0, V i contains the value of the component Vi t, for i=1,2,…,NCODE.

8:   VDOT NCODE – REAL (KIND=nag_wp) arrayInput

On entry: if NCODE>0, VDOT i contains the value of component V.i t, for i=1,2,…,NCODE.
Note: V.i t, for i=1,2,…,NCODE, may only appear linearly in GjL and GjR, for j=1,2,…,NPDE.

9:   IBND – INTEGERInput

On entry: specifies which boundary conditions are to be evaluated.
IBND=0

BNDARY must evaluate the left-hand boundary condition at x=a.

IBND≠0

BNDARY must evaluate the right-hand boundary condition at x=b.

10:   G NPDE – REAL (KIND=nag_wp) arrayOutput

On exit: G i must contain the ith component of either GiL or GiR in (8) and (9), depending on the value of IBND, for i=1,2,…,NPDE.

11:   IRES – INTEGERInput/Output

On entry: set to -1​ or ​1.

On exit: should usually remain unchanged. However, you may set IRES to force the integration routine to take certain actions as described below:
IRES=2

Indicates to the integrator that control should be passed back immediately to the calling (sub)routine with the error indicator set to IFAIL=6.

IRES=3

Indicates to the integrator that the current time step should be abandoned and a smaller time step used instead. You may wish to set IRES=3 when a physically meaningless input or output value has been generated. If you consecutively set IRES=3, then D03PSF returns to the calling subroutine with the error indicator set to IFAIL=4.

BNDARY must either be a module subprogram USEd by, or declared as EXTERNAL in, the (sub)program from which D03PSF is called. Arguments denoted as Input must not be changed by this procedure.

7:   UVINIT – SUBROUTINE, supplied by the user.External Procedure

UVINIT must supply the initial t=t 0 values of U x,t and V t for all values of x in the interval a≤x≤b.

The specification of UVINIT is:

SUBROUTINE UVINIT (

NPDE, NPTS, NXI, X, XI, U, NCODE, V)

INTEGER

NPDE, NPTS, NXI, NCODE

REAL (KIND=nag_wp)

X(NPTS), XI(NXI), U(NPDE,NPTS), V(NCODE)

1:   NPDE – INTEGERInput

On entry: the number of PDEs in the system.

2:   NPTS – INTEGERInput

On entry: the number of mesh points in the interval [a,b].

3:   NXI – INTEGERInput

On entry: the number of ODE/PDE coupling points.

4:   X NPTS – REAL (KIND=nag_wp) arrayInput

On entry: the current mesh. X i contains the value of xi, for i=1,2,…,NPTS.

5:   XI NXI – REAL (KIND=nag_wp) arrayInput

On entry: if NXI>0, XI i contains the ODE/PDE coupling point, ξi, for i=1,2,…,NXI.

6:   U NPDENPTS – REAL (KIND=nag_wp) arrayOutput

On exit: if NXI>0, U ij contains the value of the component Ui xj,t 0, for i=1,2,…,NPDE and j=1,2,…,NPTS.

7:   NCODE – INTEGERInput

On entry: the number of coupled ODEs in the system.

8:   V NCODE – REAL (KIND=nag_wp) arrayOutput

On exit: if NCODE>0, V i must contain the value of component Vi t 0, for i=1,2,…,NCODE.

UVINIT must either be a module subprogram USEd by, or declared as EXTERNAL in, the (sub)program from which D03PSF is called. Arguments denoted as Input must not be changed by this procedure.

8:   U NEQN – REAL (KIND=nag_wp) arrayInput/Output

On entry: if IND=1 the value of U must be unchanged from the previous call.

On exit: U NPDE×j-1+i contains the computed solution Ui xj,t, for i=1,2,…,NPDE and j=1,2,…,NPTS, and U NPTS×NPDE+k contains Vk t, for k=1,2,…,NCODE, all evaluated at t=TS.

9:   NPTS – INTEGERInput

On entry: the number of mesh points in the interval a,b.

Constraint: NPTS≥3.

10:   X NPTS – REAL (KIND=nag_wp) arrayInput/Output

On entry: the mesh points in the space direction. X 1 must specify the left-hand boundary, a, and X NPTS must specify the right-hand boundary, b.

Constraint: X 1<X 2<⋯<X NPTS.

On exit: the final values of the mesh points.

11:   NCODE – INTEGERInput

On entry: the number of coupled ODE components.

Constraint: NCODE≥0.

12:   ODEDEF – SUBROUTINE, supplied by the NAG Library or the user.External Procedure

ODEDEF must evaluate the functions R, which define the system of ODEs, as given in (4).

If you wish to compute the solution of a system of PDEs only (i.e., NCODE=0), ODEDEF must be the dummy routine D03PEK. (D03PEK is included in the NAG Library.)

The specification of ODEDEF is:

SUBROUTINE ODEDEF (

NPDE, T, NCODE, V, VDOT, NXI, XI, UCP, UCPX, UCPT, R, IRES)

INTEGER

NPDE, NCODE, NXI, IRES

REAL (KIND=nag_wp)

T, V(NCODE), VDOT(NCODE), XI(NXI), UCP(NPDE,*), UCPX(NPDE,*), UCPT(NPDE,*), R(NCODE)

1:   NPDE – INTEGERInput

On entry: the number of PDEs in the system.

2:   T – REAL (KIND=nag_wp)Input

On entry: the current value of the independent variable t.

3:   NCODE – INTEGERInput

On entry: the number of coupled ODEs in the system.

4:   V NCODE – REAL (KIND=nag_wp) arrayInput

On entry: if NCODE>0, V i contains the value of the component Vi t, for i=1,2,…,NCODE.

5:   VDOT NCODE – REAL (KIND=nag_wp) arrayInput

On entry: if NCODE>0, VDOT i contains the value of component V.i t, for i=1,2,…,NCODE.

6:   NXI – INTEGERInput

On entry: the number of ODE/PDE coupling points.

7:   XI NXI – REAL (KIND=nag_wp) arrayInput

On entry: if NXI>0, XI i contains the ODE/PDE coupling point, ξi, for i=1,2,…,NXI.

8:   UCP NPDE* – REAL (KIND=nag_wp) arrayInput

On entry: if NXI>0, UCP ij contains the value of Ui x,t at the coupling point x=ξj, for i=1,2,…,NPDE and j=1,2,…,NXI.

9:   UCPX NPDE* – REAL (KIND=nag_wp) arrayInput

On entry: if NXI>0, UCPX ij contains the value of ∂Ui x,t ∂x at the coupling point x=ξj, for i=1,2,…,NPDE and j=1,2,…,NXI.

10:   UCPT NPDE* – REAL (KIND=nag_wp) arrayInput

On entry: if NXI>0, UCPT ij contains the value of ∂Ui ∂t at the coupling point x=ξj, for i=1,2,…,NPDE and j=1,2,…,NXI.

11:   R NCODE – REAL (KIND=nag_wp) arrayOutput

On exit: R i must contain the ith component of R, for i=1,2,…,NCODE, where R is defined as

R=L-M V.-N Ut*,

(10)

or

R=-M V.-N Ut*.

(11)

The definition of R is determined by the input value of IRES.

12:   IRES – INTEGERInput/Output

On entry: the form of R that must be returned in the array R.
IRES=1

Equation (10) must be used.

IRES=-1

Equation (11) must be used.

On exit: should usually remain unchanged. However, you may reset IRES to force the integration routine to take certain actions, as described below:
IRES=2

Indicates to the integrator that control should be passed back immediately to the calling (sub)routine with the error indicator set to IFAIL=6.

IRES=3

Indicates to the integrator that the current time step should be abandoned and a smaller time step used instead. You may wish to set IRES=3 when a physically meaningless input or output value has been generated. If you consecutively set IRES=3, then D03PSF returns to the calling subroutine with the error indicator set to IFAIL=4.

ODEDEF must either be a module subprogram USEd by, or declared as EXTERNAL in, the (sub)program from which D03PSF is called. Arguments denoted as Input must not be changed by this procedure.

13:   NXI – INTEGERInput

On entry: the number of ODE/PDE coupling points.

Constraints:

if NCODE=0, NXI=0;

if NCODE>0, NXI≥0.

14:   XI NXI – REAL (KIND=nag_wp) arrayInput

On entry: if NXI>0, XI i, for i=1,2,…,NXI, must be set to the ODE/PDE coupling points.

Constraint: X 1≤XI 1<XI 2<⋯<XI NXI≤X NPTS.

15:   NEQN – INTEGERInput

On entry: the number of ODEs in the time direction.

Constraint: NEQN=NPDE×NPTS+NCODE.

16:   RTOL* – REAL (KIND=nag_wp) arrayInput

Note: the dimension of the array RTOL must be at least 1 if ITOL=1 or 2 and at least NEQN if ITOL=3 or 4.

On entry: the relative local error tolerance.

Constraint: RTOL i≥0.0 for all relevant i.

17:   ATOL* – REAL (KIND=nag_wp) arrayInput

Note: the dimension of the array ATOL must be at least 1 if ITOL=1 or 3 and at least NEQN if ITOL=2 or 4.

On entry: the absolute local error tolerance.

Constraint: ATOL i≥0.0 for all relevant i.
Note: corresponding elements of RTOL and ATOL cannot both be 0.0.

18:   ITOL – INTEGERInput

On entry: a value to indicate the form of the local error test. If ei is the estimated local error for U i, for i=1,2,…,NEQN, and  , denotes the norm, then the error test to be satisfied is ei<1.0. ITOL indicates to D03PSF whether to interpret either or both of RTOL and ATOL as a vector or scalar in the formation of the weights wi used in the calculation of the norm (see the description of NORM):

ITOL

RTOL

ATOL

wi

1

scalar

scalar

RTOL 1×U i+ATOL 1

2

scalar

vector

RTOL 1×U i+ATOL i

3

vector

scalar

RTOL i×U i+ATOL 1

4

vector

vector

RTOL i×U i+ATOL i

Constraint: ITOL=1, 2, 3 or 4.

19:   NORM – CHARACTER(1)Input

On entry: the type of norm to be used.
NORM='1'

Averaged L 1 norm.

NORM='2'

Averaged L 2 norm.

If Unorm denotes the norm of the vector U of length NEQN, then for the averaged L 1 norm

Unorm=1 NEQN∑i=1 NEQN U i/wi,

and for the averaged L 2 norm

Unorm=1 NEQN∑i=1 NEQN U i/wi 2,

See the description of ITOL for the formulation of the weight vector w.

Constraint: NORM='1' or '2'.

20:   LAOPT – CHARACTER(1)Input

On entry: the type of matrix algebra required.
LAOPT='F'

Full matrix methods to be used.

LAOPT='B'

Banded matrix methods to be used.

LAOPT='S'

Sparse matrix methods to be used.

Constraint: LAOPT='F', 'B' or 'S'.

Note: you are recommended to use the banded option when no coupled ODEs are present (NCODE=0). Also, the banded option should not be used if the boundary conditions involve solution components at points other than the boundary and the immediately adjacent two points.

21:   ALGOPT 30 – REAL (KIND=nag_wp) arrayInput

On entry: may be set to control various options available in the integrator. If you wish to employ all the default options, then ALGOPT 1 should be set to 0.0. Default values will also be used for any other elements of ALGOPT set to zero. The permissible values, default values, and meanings are as follows:
ALGOPT 1

Selects the ODE integration method to be used. If ALGOPT 1=1.0, a BDF method is used and if ALGOPT 1=2.0, a Theta method is used. The default is ALGOPT 1=1.0.

If ALGOPT 1=2.0, then ALGOPT i, for i=2,3,4, are not used.

ALGOPT 2

Specifies the maximum order of the BDF integration formula to be used. ALGOPT 2 may be 1.0, 2.0, 3.0, 4.0 or 5.0. The default value is ALGOPT 2=5.0.

ALGOPT 3

Specifies what method is to be used to solve the system of nonlinear equations arising on each step of the BDF method. If ALGOPT 3=1.0 a modified Newton iteration is used and if ALGOPT 3=2.0 a functional iteration method is used. If functional iteration is selected and the integrator encounters difficulty, then there is an automatic switch to the modified Newton iteration. The default value is ALGOPT 3=1.0.

ALGOPT 4

Specifies whether or not the Petzold error test is to be employed. The Petzold error test results in extra overhead but is more suitable when algebraic equations are present, such as P i,j=0.0, for j=1,2,…,NPDE, for some i or when there is no V.i t dependence in the coupled ODE system. If ALGOPT 4=1.0, then the Petzold test is used. If ALGOPT 4=2.0, then the Petzold test is not used. The default value is ALGOPT 4=1.0.

If ALGOPT 1=1.0, then ALGOPT i, for i=5,6,7, are not used.

ALGOPT 5

Specifies the value of Theta to be used in the Theta integration method. 0.51≤ALGOPT 5≤0.99. The default value is ALGOPT 5=0.55.

ALGOPT 6

Specifies what method is to be used to solve the system of nonlinear equations arising on each step of the Theta method. If ALGOPT 6=1.0, a modified Newton iteration is used and if ALGOPT 6=2.0, a functional iteration method is used. The default value is ALGOPT 6=1.0.

ALGOPT 7

Specifies whether or not the integrator is allowed to switch automatically between modified Newton and functional iteration methods in order to be more efficient. If ALGOPT 7=1.0, then switching is allowed and if ALGOPT 7=2.0, then switching is not allowed. The default value is ALGOPT 7=1.0.

ALGOPT 11

Specifies a point in the time direction, tcrit, beyond which integration must not be attempted. The use of tcrit is described under the argument ITASK. If ALGOPT 1≠0.0, a value of 0.0 for ALGOPT 11, say, should be specified even if ITASK subsequently specifies that tcrit will not be used.

ALGOPT 12

Specifies the minimum absolute step size to be allowed in the time integration. If this option is not required, ALGOPT 12 should be set to 0.0.

ALGOPT 13

Specifies the maximum absolute step size to be allowed in the time integration. If this option is not required, ALGOPT 13 should be set to 0.0.

ALGOPT 14

Specifies the initial step size to be attempted by the integrator. If ALGOPT 14=0.0, then the initial step size is calculated internally.

ALGOPT 15

Specifies the maximum number of steps to be attempted by the integrator in any one call. If ALGOPT 15=0.0, then no limit is imposed.

ALGOPT 23

Specifies what method is to be used to solve the nonlinear equations at the initial point to initialize the values of U, Ut, V and V.. If ALGOPT 23=1.0, a modified Newton iteration is used and if ALGOPT 23=2.0, functional iteration is used. The default value is ALGOPT 23=1.0.

ALGOPT 29 and ALGOPT 30 are used only for the sparse matrix algebra option, i.e., LAOPT='S'.

ALGOPT 29

Governs the choice of pivots during the decomposition of the first Jacobian matrix. It should lie in the range 0.0<ALGOPT 29<1.0, with smaller values biasing the algorithm towards maintaining sparsity at the expense of numerical stability. If ALGOPT 29 lies outside the range then the default value is used. If the routines regard the Jacobian matrix as numerically singular, then increasing ALGOPT 29 towards 1.0 may help, but at the cost of increased fill-in. The default value is ALGOPT 29=0.1.

ALGOPT 30

Used as the relative pivot threshold during subsequent Jacobian decompositions (see ALGOPT 29) below which an internal error is invoked. ALGOPT 30 must be greater than zero, otherwise the default value is used. If ALGOPT 30 is greater than 1.0 no check is made on the pivot size, and this may be a necessary option if the Jacobian matrix is found to be numerically singular (see ALGOPT 29). The default value is ALGOPT 30=0.0001.

22:   REMESH – LOGICALInput

On entry: indicates whether or not spatial remeshing should be performed.
REMESH=.TRUE.

Indicates that spatial remeshing should be performed as specified.

REMESH=.FALSE.

Indicates that spatial remeshing should be suppressed.

Note: REMESH should not be changed between consecutive calls to D03PSF. Remeshing can be switched off or on at specified times by using appropriate values for the arguments NRMESH and TRMESH at each call.

23:   NXFIX – INTEGERInput

On entry: the number of fixed mesh points.

Constraint: 0≤NXFIX≤NPTS-2.
Note: the end points X 1 and X NPTS are fixed automatically and hence should not be specified as fixed points.

24:   XFIX* – REAL (KIND=nag_wp) arrayInput

Note: the dimension of the array XFIX must be at least max 1,NXFIX.

On entry: XFIX i, for i=1,2,…,NXFIX, must contain the value of the x coordinate at the ith fixed mesh point.

Constraints:

XFIX i<XFIX i+1, for i=1,2,…,NXFIX-1;

each fixed mesh point must coincide with a user-supplied initial mesh point, that is XFIX i=X j for some j, 2≤j≤NPTS-1..

Note: the positions of the fixed mesh points in the array X NPTS remain fixed during remeshing, and so the number of mesh points between adjacent fixed points (or between fixed points and end points) does not change. You should take this into account when choosing the initial mesh distribution.

25:   NRMESH – INTEGERInput

On entry: specifies the spatial remeshing frequency and criteria for the calculation and adoption of a new mesh.
NRMESH<0

Indicates that a new mesh is adopted according to the argument DXMESH. The mesh is tested every NRMESH timesteps.

NRMESH=0

Indicates that remeshing should take place just once at the end of the first time step reached when t>TRMESH.

NRMESH>0

Indicates that remeshing will take place every NRMESH time steps, with no testing using DXMESH.

Note: NRMESH may be changed between consecutive calls to D03PSF to give greater flexibility over the times of remeshing.

26:   DXMESH – REAL (KIND=nag_wp)Input

On entry: determines whether a new mesh is adopted when NRMESH is set less than zero. A possible new mesh is calculated at the end of every NRMESH time steps, but is adopted only if

xinew>xiold+DXMESH×x i+1 old-xiold

or

xinew<xiold-DXMESH×xiold-x i- 1 old

DXMESH thus imposes a lower limit on the difference between one mesh and the next.

Constraint: DXMESH≥0.0.

27:   TRMESH – REAL (KIND=nag_wp)Input

On entry: specifies when remeshing will take place when NRMESH is set to zero. Remeshing will occur just once at the end of the first time step reached when t is greater than TRMESH.
Note: TRMESH may be changed between consecutive calls to D03PSF to force remeshing at several specified times.

28:   IPMINF – INTEGERInput

On entry: the level of trace information regarding the adaptive remeshing. Details are directed to the current advisory message unit (see X04ABF).
IPMINF=0

No trace information.

IPMINF=1

Brief summary of mesh characteristics.

IPMINF=2

More detailed information, including old and new mesh points, mesh sizes and monitor function values.

Constraint: IPMINF=0, 1 or 2.

29:   XRATIO – REAL (KIND=nag_wp)Input

On entry: an input bound on the adjacent mesh ratio (greater than 1.0 and typically in the range 1.5 to 3.0). The remeshing routines will attempt to ensure that

xi-x i-1/XRATIO<x i+1-xi<XRATIO×xi-x i-1.

Suggested value: XRATIO=1.5.

Constraint: XRATIO>1.0.

30:   CON – REAL (KIND=nag_wp)Input

On entry: an input bound on the sub-integral of the monitor function Fmon x over each space step. The remeshing routines will attempt to ensure that

∫xix i+1 Fmon x dx≤CON∫x 1xNPTS Fmon x dx,

(see Furzeland (1984)). CON gives you more control over the mesh distribution, e.g., decreasing CON allows more clustering. A typical value is 2.0/NPTS-1, but you are encouraged to experiment with different values. Its value is not critical and the mesh should be qualitatively correct for all values in the range given below.

Suggested value: CON=2.0/NPTS-1.

Constraint: 0.1/NPTS-1≤CON≤10.0/NPTS-1.

31:   MONITF – SUBROUTINE, supplied by the NAG Library or the user.External Procedure

MONITF must supply and evaluate a remesh monitor function to indicate the solution behaviour of interest.

If you specify REMESH=.FALSE., i.e., no remeshing, then MONITF will not be called and the dummy routine D03PEL may be used for MONITF. (D03PEL is included in the NAG Library.)

The specification of MONITF is:

SUBROUTINE MONITF (

T, NPTS, NPDE, X, U, FMON)

INTEGER

NPTS, NPDE

REAL (KIND=nag_wp)

T, X(NPTS), U(NPDE,NPTS), FMON(NPTS)

1:   T – REAL (KIND=nag_wp)Input

On entry: the current value of the independent variable t.

2:   NPTS – INTEGERInput

On entry: the number of mesh points in the interval a,b.

3:   NPDE – INTEGERInput

On entry: the number of PDEs in the system.

4:   X NPTS – REAL (KIND=nag_wp) arrayInput

On entry: the current mesh. X i contains the value of xi, for i=1,2,…,NPTS.

5:   U NPDENPTS – REAL (KIND=nag_wp) arrayInput

On entry: U ij contains the value of Ui x,t at x=X j and time t, for i=1,2,…,NPDE and j=1,2,…,NPTS.

6:   FMON NPTS – REAL (KIND=nag_wp) arrayOutput

On exit: FMON i must contain the value of the monitor function Fmon x at mesh point x=X i.

Constraint: FMON i≥0.0.

MONITF must either be a module subprogram USEd by, or declared as EXTERNAL in, the (sub)program from which D03PSF is called. Arguments denoted as Input must not be changed by this procedure.

32:   RSAVE LRSAVE – REAL (KIND=nag_wp) arrayCommunication Array

If IND=0, RSAVE need not be set on entry.

If IND=1, RSAVE must be unchanged from the previous call to the routine because it contains required information about the iteration.

33:   LRSAVE – INTEGERInput

On entry: the dimension of the array RSAVE as declared in the (sub)program from which D03PSF is called. Its size depends on the type of matrix algebra selected.
If LAOPT='F', LRSAVE≥NEQN×NEQN+NEQN+nwkres+lenode.

If LAOPT='B', LRSAVE≥3×mlu+1×NEQN+nwkres+lenode.

If LAOPT='S', LRSAVE≥4×NEQN+11×NEQN/2+1+nwkres+lenode.

Where

mlu is the lower or upper half bandwidths such that
mlu=3×NPDE-1, for PDE problems only (no coupled ODEs); or
mlu=NEQN-1, for coupled PDE/ODE problems.

nwkres= NPDE×2×NPTS+6×NXI+3×NPDE+26+NXI+NCODE+7×NPTS+NXFIX+1, when ​NCODE>0​ and ​NXI>0; or NPDE×2×NPTS+3×NPDE+32+NCODE+7×NPTS+NXFIX+2, when ​NCODE>0​ and ​NXI=0; or ​ NPDE×2×NPTS+3×NPDE+32+7×NPTS+NXFIX+3, when ​NCODE=0.

lenode= 6+int ALGOPT 2×NEQN+50, when the BDF method is used; or 9×NEQN+50, when the Theta method is used.

Note: when LAOPT='S', the value of LRSAVE may be too small when supplied to the integrator. An estimate of the minimum size of LRSAVE is printed on the current error message unit if ITRACE>0 and the routine returns with IFAIL=15.

34:   ISAVE LISAVE – INTEGER arrayCommunication Array

If IND=0, ISAVE need not be set.

If IND=1, ISAVE must be unchanged from the previous call to the routine because it contains required information about the iteration. In particular the following components of the array ISAVE concern the efficiency of the integration:
ISAVE 1

Contains the number of steps taken in time.

ISAVE 2

Contains the number of residual evaluations of the resulting ODE system used. One such evaluation involves evaluating the PDE functions at all the mesh points, as well as one evaluation of the functions in the boundary conditions.

ISAVE 3

Contains the number of Jacobian evaluations performed by the time integrator.

ISAVE 4

Contains the order of the BDF method last used in the time integration, if applicable. When the Theta method is used, ISAVE 4 contains no useful information.

ISAVE 5

Contains the number of Newton iterations performed by the time integrator. Each iteration involves residual evaluation of the resulting ODE system followed by a back-substitution using the LU decomposition of the Jacobian matrix.

35:   LISAVE – INTEGERInput

On entry: the dimension of the array ISAVE as declared in the (sub)program from which D03PSF is called. Its size depends on the type of matrix algebra selected:

if LAOPT='F', LISAVE≥25;

if LAOPT='B', LISAVE≥NEQN+NXFIX+25;

if LAOPT='S', LISAVE≥25×NEQN+NXFIX+25.

Note: when using the sparse option, the value of LISAVE may be too small when supplied to the integrator. An estimate of the minimum size of LISAVE is printed on the current error message unit if ITRACE>0 and the routine returns with IFAIL=15.

36:   ITASK – INTEGERInput

On entry: the task to be performed by the ODE integrator.
ITASK=1

Normal computation of output values U at t=TOUT (by overshooting and interpolating).

ITASK=2

Take one step in the time direction and return.

ITASK=3

Stop at first internal integration point at or beyond t=TOUT.

ITASK=4

Normal computation of output values U at t=TOUT but without overshooting t=tcrit where tcrit is described under the argument ALGOPT.

ITASK=5

Take one step in the time direction and return, without passing tcrit, where tcrit is described under the argument ALGOPT.

Constraint: ITASK=1, 2, 3, 4 or 5.

37:   ITRACE – INTEGERInput

On entry: the level of trace information required from D03PSF and the underlying ODE solver. ITRACE may take the value -1, 0, 1, 2 or 3.
ITRACE=-1

No output is generated.

ITRACE=0

Only warning messages from the PDE solver are printed on the current error message unit (see X04AAF).

ITRACE>0

Output from the underlying ODE solver is printed on the current advisory message unit (see X04ABF). This output contains details of Jacobian entries, the nonlinear iteration and the time integration during the computation of the ODE system.

If ITRACE<-1, then -1 is assumed and similarly if ITRACE>3, then 3 is assumed.

The advisory messages are given in greater detail as ITRACE increases. You are advised to set ITRACE=0, unless you are experienced with Sub-chapter D02M–N.

38:   IND – INTEGERInput/Output

On entry: indicates whether this is a continuation call or a new integration.
IND=0

Starts or restarts the integration in time.

IND=1

Continues the integration after an earlier exit from the routine. In this case, only the arguments TOUT, IFAIL, NRMESH and TRMESH may be reset between calls to D03PSF.

Constraint: IND=0 or 1.

On exit: IND=1.

39:   IFAIL – INTEGERInput/Output

On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.

On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).

Errors or warnings detected by the routine:

IFAIL=1

On entry,

TS≥TOUT,

or

TOUT-TS is too small,

or

ITASK≠1, 2, 3, 4 or 5,

or

at least one of the coupling points defined in array XI is outside the interval [X 1,X NPTS],

or

the coupling points are not in strictly increasing order,

or

NPTS<3,

or

NPDE<1,

or

LAOPT≠'F', 'B' or 'S',

or

ITOL≠1, 2, 3 or 4,

or

IND≠0 or 1,

or

mesh points X i are badly ordered,

or

LRSAVE is too small,

or

LISAVE is too small,

or

NCODE and NXI are incorrectly defined,

or

IND=1 on initial entry to D03PSF,

or

NEQN≠NPDE×NPTS+NCODE,

or

an element of RTOL or ATOL<0.0,

or

corresponding elements of RTOL and ATOL are both 0.0,

or

NORM≠'1' or '2',

or

NXFIX not in the range 0 to NPTS-2,

or

fixed mesh point(s) do not coincide with any of the user-supplied mesh points,

or

DXMESH<0.0,

or

IPMINF≠0, 1 or 2,

or

XRATIO≤1.0,

or

CON not in the range 0.1/NPTS-1 to 10.0/NPTS-1.

IFAIL=2

The underlying ODE solver cannot make any further progress, with the values of ATOL and RTOL, across the integration range from the current point t=TS. The components of U contain the computed values at the current point t=TS.

IFAIL=3

In the underlying ODE solver, there were repeated error test failures on an attempted step, before completing the requested task, but the integration was successful as far as t=TS. The problem may have a singularity, or the error requirement may be inappropriate. Incorrect specification of boundary conditions may also result in this error.

IFAIL=4

In setting up the ODE system, the internal initialization routine was unable to initialize the derivative of the ODE system. This could be due to the fact that IRES was repeatedly set to 3 in one of PDEDEF, NUMFLX, BNDARY or ODEDEF, when the residual in the underlying ODE solver was being evaluated. Incorrect specification of boundary conditions may also result in this error.

IFAIL=5

In solving the ODE system, a singular Jacobian has been encountered. Check the problem formulation.

IFAIL=6

When evaluating the residual in solving the ODE system, IRES was set to 2 in at least one of PDEDEF, NUMFLX, BNDARY or ODEDEF. Integration was successful as far as t=TS.

IFAIL=7

The values of ATOL and RTOL are so small that the routine is unable to start the integration in time.

IFAIL=8

In one of PDEDEF, NUMFLX, BNDARY or ODEDEF, IRES was set to an invalid value.

IFAIL=9 (D02NNF)

A serious error has occurred in an internal call to the specified routine. Check the problem specification and all arguments and array dimensions. Setting ITRACE=1 may provide more information. If the problem persists, contact NAG.

IFAIL=10

The required task has been completed, but it is estimated that a small change in ATOL and RTOL is unlikely to produce any change in the computed solution. (Only applies when you are not operating in one step mode, that is when ITASK≠2 or 5.)

IFAIL=11

An error occurred during Jacobian formulation of the ODE system (a more detailed error description may be directed to the current advisory message unit when ITRACE≥1). If using the sparse matrix algebra option, the values of ALGOPT 29 and ALGOPT 30 may be inappropriate.

IFAIL=12

In solving the ODE system, the maximum number of steps specified in ALGOPT 15 have been taken.

IFAIL=13

Some error weights wi became zero during the time integration (see the description of ITOL). Pure relative error control (ATOL i=0.0) was requested on a variable (the ith) which has become zero. The integration was successful as far as t=TS.

IFAIL=14

One or more of the functions P i,j, Di or Ci was detected as depending on time derivatives, which is not permissible.

IFAIL=15

When using the sparse option, the value of LISAVE or LRSAVE was not sufficient (more detailed information may be directed to the current error message unit, see X04AAF).

IFAIL=16

REMESH has been changed between calls to D03PSF.

IFAIL=17

FMON is negative at one or more mesh points, or zero mesh spacing has been obtained due to an inappropriate choice of monitor function.

IFAIL=-99

An unexpected error has been triggered by this routine. Please contact NAG.

See Section 3.9 in How to Use the NAG Library and its Documentation for further information.

IFAIL=-399

Your licence key may have expired or may not have been installed correctly.

See Section 3.8 in How to Use the NAG Library and its Documentation for further information.

IFAIL=-999

Dynamic memory allocation failed.

See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

D03PSF controls the accuracy of the integration in the time direction but not the accuracy of the approximation in space. The spatial accuracy depends on both the number of mesh points and on their distribution in space. In the time integration only the local error over a single step is controlled and so the accuracy over a number of steps cannot be guaranteed. You should therefore test the effect of varying the accuracy arguments, ATOL and RTOL.

8 Parallelism and Performance

D03PSF is not thread safe and should not be called from a multithreaded user program. Please see Section 3.12.1 in How to Use the NAG Library and its Documentation for more information on thread safety.

D03PSF is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.

D03PSF makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.

Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

D03PSF is designed to solve systems of PDEs in conservative form, with optional source terms which are independent of space derivatives, and optional second-order diffusion terms. The use of the routine to solve systems which are not naturally in this form is discouraged, and you are advised to use one of the central-difference scheme routines for such problems.

You should be aware of the stability limitations for hyperbolic PDEs. For most problems with small error tolerances the ODE integrator does not attempt unstable time steps, but in some cases a maximum time step should be imposed using ALGOPT 13. It is worth experimenting with this argument, particularly if the integration appears to progress unrealistically fast (with large time steps). Setting the maximum time step to the minimum mesh size is a safe measure, although in some cases this may be too restrictive.

Problems with source terms should be treated with caution, as it is known that for large source terms stable and reasonable looking solutions can be obtained which are in fact incorrect, exhibiting non-physical speeds of propagation of discontinuities (typically one spatial mesh point per time step). It is essential to employ a very fine mesh for problems with source terms and discontinuities, and to check for non-physical propagation speeds by comparing results for different mesh sizes. Further details and an example can be found in Pennington and Berzins (1994).

The time taken depends on the complexity of the system, the accuracy requested, and the frequency of the mesh updates. For a given system with fixed accuracy and mesh-update frequency it is approximately proportional to NEQN.

10 Example

For this routine two examples are presented, with a main program and two example problems given in Example 1 (EX1) and Example 2 (EX2).

Example 1 (EX1)

This example is a simple model of the advection and diffusion of a cloud of material:

∂U ∂t + W ∂U ∂x = C ∂2 U ∂x 2 ,

for x∈0,1 and t≤0≤0.3. In this example the constant wind speed W=1 and the diffusion coefficient C=0.002.

The cloud does not reach the boundaries during the time of integration, and so the two (physical) boundary conditions are simply U 0,t=U 1,t=0.0, and the initial condition is

U x,0 = sin π x-a b-a ,  a≤x≤b,

and U x,0=0 elsewhere, where a=0.2 and b=0.4.

The numerical flux is simply F^=W UL.

The monitor function for remeshing is taken to be the absolute value of the second derivative of U.

Example 2 (EX2)

This example is a linear advection equation with a nonlinear source term and discontinuous initial profile:

∂u ∂t + ∂u ∂x =-pu u-1u-12,

for 0≤x≤1 and t≥0. The discontinuity is modelled by a ramp function of width 0.01 and gradient 100, so that the exact solution at any time t≥0 is

u x,t=1.0+max min δ,0,-1,

where δ=100 0.1-x+t. The initial profile is given by the exact solution. The characteristic points into the domain at x=0 and out of the domain at x=1, and so a physical boundary condition u 0,t=1 is imposed at x=0, with a numerical boundary condition at x=1 which can be specified as u 1,t=0 since the discontinuity does not reach x=1 during the time of integration.

The numerical flux is simply F^=UL at all times.

The remeshing monitor function (described below) is chosen to create an increasingly fine mesh towards the discontinuity in order to ensure good resolution of the discontinuity, but without loss of efficiency in the surrounding regions. However, refinement must be limited so that the time step required for stability does not become unrealistically small. The region of refinement must also keep up with the discontinuity as it moves across the domain, and hence it cannot be so small that the discontinuity moves out of the refined region between remeshing.

The above requirements mean that the use of the first or second spatial derivative of U for the monitor function is inappropriate; the large relative size of either derivative in the region of the discontinuity leads to extremely small mesh-spacing in a very limited region, and the solution is then far more expensive than for a very fine fixed mesh.

An alternative monitor function based on a cosine function proves very successful. It is only semi-automatic as it requires some knowledge of the solution (for problems without an exact solution an initial approximate solution can be obtained using a coarse fixed mesh). On each call to MONITF the discontinuity is located by finding the maximum spatial derivative of the solution. On the first call the desired width of the region of nonzero monitor function is set (this can be changed at a later time if desired). Then on each call the monitor function is assigned using a cosine function so that it has a value of one at the discontinuity down to zero at the edges of the predetermined region of refinement, and zero outside the region. Thus the monitor function and the subsequent refinement are limited, and the region is large enough to ensure that there is always sufficient refinement at the discontinuity.

10.1 Program Text

Program Text (d03psfe.f90)

10.2 Program Data

Program Data (d03psfe.d)

10.3 Program Results

Program Results (d03psfe.r)

D03 Chapter Contents

D03 Chapter Introduction

NAG Library Manual

© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


D03PUF : NAG Library, Mark 26

D03 Chapter Contents
D03 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

D03PUF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
10 Example

1 Purpose

D03PUF calculates a numerical flux function using Roe's Approximate Riemann Solver for the Euler equations in conservative form. It is designed primarily for use with the upwind discretization schemes D03PFF, D03PLF or D03PSF, but may also be applicable to other conservative upwind schemes requiring numerical flux functions.

2 Specification

SUBROUTINE D03PUF ( ULEFT, URIGHT, GAMMA, FLUX, IFAIL)
INTEGER | IFAIL
REAL (KIND=nag_wp) | ULEFT(3), URIGHT(3), GAMMA, FLUX(3)

3 Description

D03PUF calculates a numerical flux function at a single spatial point using Roe's Approximate Riemann Solver (see Roe (1981)) for the Euler equations (for a perfect gas) in conservative form. You must supply the left and right solution values at the point where the numerical flux is required, i.e., the initial left and right states of the Riemann problem defined below.
In the routines D03PFF, D03PLF and D03PSF, the left and right solution values are derived automatically from the solution values at adjacent spatial points and supplied to the subroutine argument NUMFLX from which you may call D03PUF.
The Euler equations for a perfect gas in conservative form are:
∂U ∂t + ∂F ∂x = 0 , (1)
with
U = ρ m e and F = m m 2 ρ + γ-1 e - m 2 2 ρ me ρ + mρ γ-1 e - m 2 2 ρ , (2)
where ρ is the density, m is the momentum, e is the specific total energy, and γ is the (constant) ratio of specific heats. The pressure p is given by
p=γ-1 e-ρ u 2 2 , (3)
where u=m/ρ is the velocity.
The routine calculates the Roe approximation to the numerical flux function F UL,UR=F U*UL,UR, where U=UL and U=UR are the left and right solution values, and U*UL,UR is the intermediate state ω 0 arising from the similarity solution U y,t=ω y/t of the Riemann problem defined by
∂U ∂t + ∂F ∂y =0, (4)
with U and F as in (2), and initial piecewise constant values U=UL for y<0 and U=UR for y>0. The spatial domain is -∞<y<∞, where y=0 is the point at which the numerical flux is required. This implementation of Roe's scheme for the Euler equations uses the so-called argument-vector method described in Roe (1981).

4 References

LeVeque R J (1990) Numerical Methods for Conservation Laws Birkhäuser Verlag
Quirk J J (1994) A contribution to the great Riemann solver debate Internat. J. Numer. Methods Fluids 18 555–574
Roe P L (1981) Approximate Riemann solvers, parameter vectors, and difference schemes J. Comput. Phys. 43 357–372

5 Arguments

1:   ULEFT 3 – REAL (KIND=nag_wp) arrayInput
On entry: ULEFT i must contain the left value of the component Ui, for i=1,2,3. That is, ULEFT 1 must contain the left value of ρ, ULEFT 2 must contain the left value of m and ULEFT 3 must contain the left value of e.
Constraints:
  • ULEFT 1≥0.0;
  • Left pressure, pl≥0.0, where pl is calculated using (3).
2:   URIGHT 3 – REAL (KIND=nag_wp) arrayInput
On entry: URIGHT i must contain the right value of the component Ui, for i=1,2,3. That is, URIGHT 1 must contain the right value of ρ, URIGHT 2 must contain the right value of m and URIGHT 3 must contain the right value of e.
Constraints:
  • URIGHT 1≥0.0;
  • Right pressure, pr≥0.0, where pr is calculated using (3).
3:   GAMMA – REAL (KIND=nag_wp)Input
On entry: the ratio of specific heats, γ.
Constraint: GAMMA>0.0.
4:   FLUX 3 – REAL (KIND=nag_wp) arrayOutput
On exit: FLUX i contains the numerical flux component F^i, for i=1,2,3.
5:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).
Note: if the left and/or right values of ρ or p (from (3)) are found to be negative, then the routine will terminate with an error exit (IFAIL=2). If the routine is being called from the NUMFLX etc., then a soft fail option (IFAIL=1 or -1) is recommended so that a recalculation of the current time step can be forced using the NUMFLX argument IRES (see D03PFF or D03PLF).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, GAMMA≤0.0.
IFAIL=2
On entry, the left and/or right density or pressure value is less than 0.0.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

D03PUF performs an exact calculation of the Roe numerical flux function, and so the result will be accurate to machine precision.

8 Parallelism and Performance

D03PUF is not thread safe and should not be called from a multithreaded user program. Please see Section 3.12.1 in How to Use the NAG Library and its Documentation for more information on thread safety.
D03PUF is not threaded in any implementation.

9 Further Comments

D03PUF must only be used to calculate the numerical flux for the Euler equations in exactly the form given by (2), with ULEFT i and URIGHT i containing the left and right values of ρ,m and e, for i=1,2,3, respectively. It should be noted that Roe's scheme, in common with all Riemann solvers, may be unsuitable for some problems (see Quirk (1994) for examples). In particular Roe's scheme does not satisfy an ‘entropy condition’ which guarantees that the approximate solution of the PDE converges to the correct physical solution, and hence it may admit non-physical solutions such as expansion shocks. The algorithm used in this routine does not detect or correct any entropy violation. The time taken is independent of the input arguments.

10 Example

See Section 10 in D03PLF.
D03 Chapter Contents
D03 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


D03PVF : NAG Library, Mark 26

D03 Chapter Contents
D03 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

D03PVF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
10 Example

1 Purpose

D03PVF calculates a numerical flux function using Osher's Approximate Riemann Solver for the Euler equations in conservative form. It is designed primarily for use with the upwind discretization schemes D03PFF, D03PLF or D03PSF, but may also be applicable to other conservative upwind schemes requiring numerical flux functions.

2 Specification

SUBROUTINE D03PVF ( ULEFT, URIGHT, GAMMA, PATH, FLUX, IFAIL)
INTEGER | IFAIL
REAL (KIND=nag_wp) | ULEFT(3), URIGHT(3), GAMMA, FLUX(3)
CHARACTER(1) | PATH

3 Description

D03PVF calculates a numerical flux function at a single spatial point using Osher's Approximate Riemann Solver (see Hemker and Spekreijse (1986) and Pennington and Berzins (1994)) for the Euler equations (for a perfect gas) in conservative form. You must supply the left and right solution values at the point where the numerical flux is required, i.e., the initial left and right states of the Riemann problem defined below. In the routines D03PFF, D03PLF and D03PSF, the left and right solution values are derived automatically from the solution values at adjacent spatial points and supplied to the subroutine argument NUMFLX from which you may call D03PVF.
The Euler equations for a perfect gas in conservative form are:
∂U ∂t + ∂F ∂x =0, (1)
with
U= ρ m e and F= m m 2 ρ+γ-1 e-m 2 2 ρ me ρ+mρ γ-1 e-m 2 2 ρ , (2)
where ρ is the density, m is the momentum, e is the specific total energy, and γ is the (constant) ratio of specific heats. The pressure p is given by
p=γ-1 e-ρ u 2 2 , (3)
where u=m/ρ is the velocity.
The routine calculates the Osher approximation to the numerical flux function F UL,UR=F U*UL,UR, where U=UL and U=UR are the left and right solution values, and U*UL,UR is the intermediate state ω 0 arising from the similarity solution U y,t=ω y/t of the Riemann problem defined by
∂U ∂t + ∂F ∂y =0, (4)
with U and F as in (2), and initial piecewise constant values U=UL for y<0 and U=UR for y>0. The spatial domain is -∞<y<∞, where y=0 is the point at which the numerical flux is required. Osher's solver carries out an integration along a path in the phase space of U consisting of subpaths which are piecewise parallel to the eigenvectors of the Jacobian of the PDE system. There are two variants of the Osher solver termed O (original) and P (physical), which differ in the order in which the subpaths are taken. The P-variant is generally more efficient, but in some rare cases may fail (see Hemker and Spekreijse (1986) for details). The argument PATH specifies which variant is to be used. The algorithm for Osher's solver for the Euler equations is given in detail in the Appendix of Pennington and Berzins (1994).

4 References

Hemker P W and Spekreijse S P (1986) Multiple grid and Osher's scheme for the efficient solution of the steady Euler equations Applied Numerical Mathematics 2 475–493
Pennington S V and Berzins M (1994) New NAG Library software for first-order partial differential equations ACM Trans. Math. Softw. 20 63–99
Quirk J J (1994) A contribution to the great Riemann solver debate Internat. J. Numer. Methods Fluids 18 555–574

5 Arguments

1:   ULEFT 3 – REAL (KIND=nag_wp) arrayInput
On entry: ULEFT i must contain the left value of the component Ui, for i=1,2,3. That is, ULEFT 1 must contain the left value of ρ, ULEFT 2 must contain the left value of m and ULEFT 3 must contain the left value of e.
Constraints:
  • ULEFT 1≥0.0;
  • Left pressure, pl≥0.0, where pl is calculated using (3).
2:   URIGHT 3 – REAL (KIND=nag_wp) arrayInput
On entry: URIGHT i must contain the right value of the component Ui, for i=1,2,3. That is, URIGHT 1 must contain the right value of ρ, URIGHT 2 must contain the right value of m and URIGHT 3 must contain the right value of e.
Constraints:
  • URIGHT 1≥0.0;
  • Right pressure, pr≥0.0, where pr is calculated using (3).
3:   GAMMA – REAL (KIND=nag_wp)Input
On entry: the ratio of specific heats, γ.
Constraint: GAMMA>0.0.
4:   PATH – CHARACTER(1)Input
On entry: the variant of the Osher scheme.
PATH='O'
Original.
PATH='P'
Physical.
Constraint: PATH='O' or 'P'.
5:   FLUX 3 – REAL (KIND=nag_wp) arrayOutput
On exit: FLUX i contains the numerical flux component F^i, for i=1,2,3.
6:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).
Note: if the left and/or right values of ρ or p (from (3)) are found to be negative, then the routine will terminate with an error exit (IFAIL=2). If the routine is being called from the NUMFLX etc., then a soft fail option (IFAIL=1 or -1) is recommended so that a recalculation of the current time step can be forced using the NUMFLX argument IRES (see D03PFF or D03PLF).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, | GAMMA≤0.0,
or | PATH≠'O' or 'P'.
IFAIL=2
On entry, the left and/or right density or pressure value is less than 0.0.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

D03PVF performs an exact calculation of the Osher numerical flux function, and so the result will be accurate to machine precision.

8 Parallelism and Performance

D03PVF is not thread safe and should not be called from a multithreaded user program. Please see Section 3.12.1 in How to Use the NAG Library and its Documentation for more information on thread safety.
D03PVF is not threaded in any implementation.

9 Further Comments

D03PVF must only be used to calculate the numerical flux for the Euler equations in exactly the form given by (2), with ULEFT i and URIGHT i containing the left and right values of ρ,m and e, for i=1,2,3, respectively. It should be noted that Osher's scheme, in common with all Riemann solvers, may be unsuitable for some problems (see Quirk (1994) for examples). The time taken depends on the input argument PATH and on the left and right solution values, since inclusion of each subpath depends on the signs of the eigenvalues. In general this cannot be determined in advance.

10 Example

See Section 10 in D03PLF.
D03 Chapter Contents
D03 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


D03PWF : NAG Library, Mark 26

D03 Chapter Contents

D03 Chapter Introduction

NAG Library Manual

NAG Library Routine Document

D03PWF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose

2 Specification

3 Description

4 References

5 Arguments

6 Error Indicators and Warnings

7 Accuracy

8 Parallelism and Performance

9 Further Comments

▸▿ 10 Example

10.1 Program Text

10.2 Program Data

10.3 Program Results

1 Purpose

D03PWF calculates a numerical flux function using a modified HLL (Harten–Lax–van Leer) Approximate Riemann Solver for the Euler equations in conservative form. It is designed primarily for use with the upwind discretization schemes D03PFF, D03PLF or D03PSF, but may also be applicable to other conservative upwind schemes requiring numerical flux functions.

2 Specification

SUBROUTINE D03PWF (

ULEFT, URIGHT, GAMMA, FLUX, IFAIL)

INTEGER

IFAIL

REAL (KIND=nag_wp)

ULEFT(3), URIGHT(3), GAMMA, FLUX(3)

3 Description

D03PWF calculates a numerical flux function at a single spatial point using a modified HLL (Harten–Lax–van Leer) Approximate Riemann Solver (see Toro (1992), Toro (1996) and Toro et al. (1994)) for the Euler equations (for a perfect gas) in conservative form. You must supply the left and right solution values at the point where the numerical flux is required, i.e., the initial left and right states of the Riemann problem defined below. In D03PFF, D03PLF and D03PSF, the left and right solution values are derived automatically from the solution values at adjacent spatial points and supplied to the subroutine argument NUMFLX from which you may call D03PWF.

The Euler equations for a perfect gas in conservative form are:

∂U ∂t + ∂F ∂x =0,

(1)

with

U= ρ m e and F= m m 2 ρ+γ-1 e-m 2 2 ρ me ρ+mρ γ-1 e-m 2 2 ρ ,

(2)

where ρ is the density, m is the momentum, e is the specific total energy and γ is the (constant) ratio of specific heats. The pressure p is given by

p=γ-1 e-ρ u 2 2 ,

(3)

where u=m/ρ is the velocity.

The routine calculates an approximation to the numerical flux function F UL,UR=F U*UL,UR, where U=UL and U=UR are the left and right solution values, and U*UL,UR is the intermediate state ω 0 arising from the similarity solution U y,t=ω y/t of the Riemann problem defined by

∂U ∂t + ∂F ∂y =0,

(4)

with U and F as in (2), and initial piecewise constant values U=UL for y<0 and U=UR for y>0. The spatial domain is -∞<y<∞, where y=0 is the point at which the numerical flux is required.

4 References

Toro E F (1992) The weighted average flux method applied to the Euler equations Phil. Trans. R. Soc. Lond. A341 499–530

Toro E F (1996) Riemann Solvers and Upwind Methods for Fluid Dynamics Springer–Verlag

Toro E F, Spruce M and Spears W (1994) Restoration of the contact surface in the HLL Riemann solver J. Shock Waves 4 25–34

5 Arguments

1:   ULEFT 3 – REAL (KIND=nag_wp) arrayInput

On entry: ULEFT i must contain the left value of the component Ui, for i=1,2,3. That is, ULEFT 1 must contain the left value of ρ, ULEFT 2 must contain the left value of m and ULEFT 3 must contain the left value of e.

Constraints:

ULEFT 1≥0.0;

Left pressure, pl≥0.0, where pl is calculated using (3).

2:   URIGHT 3 – REAL (KIND=nag_wp) arrayInput

On entry: URIGHT i must contain the right value of the component Ui, for i=1,2,3. That is, URIGHT 1 must contain the right value of ρ, URIGHT 2 must contain the right value of m and URIGHT 3 must contain the right value of e.

Constraints:

URIGHT 1≥0.0;

Right pressure, pr≥0.0, where pr is calculated using (3).

3:   GAMMA – REAL (KIND=nag_wp)Input

On entry: the ratio of specific heats, γ.

Constraint: GAMMA>0.0.

4:   FLUX 3 – REAL (KIND=nag_wp) arrayOutput

On exit: FLUX i contains the numerical flux component F^i, for i=1,2,3.

5:   IFAIL – INTEGERInput/Output

On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.

On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

Note: if the left and/or right values of ρ or p (from (3)) are found to be negative, then the routine will terminate with an error exit (IFAIL=2). If the routine is being called from the NUMFLX etc., then a soft fail option (IFAIL=1 or -1) is recommended so that a recalculation of the current time step can be forced using the NUMFLX argument IRES (see D03PFF or D03PLF).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).

Errors or warnings detected by the routine:

IFAIL=1

On entry,

GAMMA≤0.0.

IFAIL=2

On entry,

the left and/or right density or derived pressure value is less than 0.0.

IFAIL=-99

An unexpected error has been triggered by this routine. Please contact NAG.

See Section 3.9 in How to Use the NAG Library and its Documentation for further information.

IFAIL=-399

Your licence key may have expired or may not have been installed correctly.

See Section 3.8 in How to Use the NAG Library and its Documentation for further information.

IFAIL=-999

Dynamic memory allocation failed.

See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

D03PWF performs an exact calculation of the HLL (Harten–Lax–van Leer) numerical flux function, and so the result will be accurate to machine precision.

8 Parallelism and Performance

D03PWF is not thread safe and should not be called from a multithreaded user program. Please see Section 3.12.1 in How to Use the NAG Library and its Documentation for more information on thread safety.

D03PWF is not threaded in any implementation.

9 Further Comments

D03PWF must only be used to calculate the numerical flux for the Euler equations in exactly the form given by (2), with ULEFT i and URIGHT i containing the left and right values of ρ,m and e, for i=1,2,3, respectively. The time taken is independent of the input arguments.

10 Example

This example uses D03PLF and D03PWF to solve the Euler equations in the domain 0≤x≤1 for 0<t≤0.035 with initial conditions for the primitive variables ρ x,t, u x,t and p x,t given by

ρ x,0=5.99924, u x,0=-19.5975, p x,0=460.894,   for ​x<0.5, ρ x,0=5.99242, u x,0=-6.19633, p x,0=0 46.095,   for ​x>0.5.

This test problem is taken from Toro (1996) and its solution represents the collision of two strong shocks travelling in opposite directions, consisting of a left facing shock (travelling slowly to the right), a right travelling contact discontinuity and a right travelling shock wave. There is an exact solution to this problem (see Toro (1996)) but the calculation is lengthy and has therefore been omitted.

10.1 Program Text

Program Text (d03pwfe.f90)

10.2 Program Data

Program Data (d03pwfe.d)

10.3 Program Results

Program Results (d03pwfe.r)

D03 Chapter Contents

D03 Chapter Introduction

NAG Library Manual

© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


D03PXF : NAG Library, Mark 26

D03 Chapter Contents

D03 Chapter Introduction

NAG Library Manual

NAG Library Routine Document

D03PXF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose

2 Specification

3 Description

4 References

5 Arguments

6 Error Indicators and Warnings

7 Accuracy

8 Parallelism and Performance

9 Further Comments

▸▿ 10 Example

10.1 Program Text

10.2 Program Data

10.3 Program Results

1 Purpose

D03PXF calculates a numerical flux function using an Exact Riemann Solver for the Euler equations in conservative form. It is designed primarily for use with the upwind discretization schemes D03PFF, D03PLF or D03PSF, but may also be applicable to other conservative upwind schemes requiring numerical flux functions.

2 Specification

SUBROUTINE D03PXF (

ULEFT, URIGHT, GAMMA, TOL, NITER, FLUX, IFAIL)

INTEGER

NITER, IFAIL

REAL (KIND=nag_wp)

ULEFT(3), URIGHT(3), GAMMA, TOL, FLUX(3)

3 Description

D03PXF calculates a numerical flux function at a single spatial point using an Exact Riemann Solver (see Toro (1996) and Toro (1989)) for the Euler equations (for a perfect gas) in conservative form. You must supply the left and right solution values at the point where the numerical flux is required, i.e., the initial left and right states of the Riemann problem defined below. In D03PFF, D03PLF and D03PSF, the left and right solution values are derived automatically from the solution values at adjacent spatial points and supplied to the subroutine argument NUMFLX from which you may call D03PXF.

The Euler equations for a perfect gas in conservative form are:

∂U ∂t + ∂F ∂x =0,

(1)

with

U= ρ m e and F= m m 2 ρ+γ-1 e-m 2 2 ρ me ρ+mρ γ-1 e-m 2 2 ρ ,

(2)

where ρ is the density, m is the momentum, e is the specific total energy and γ is the (constant) ratio of specific heats. The pressure p is given by

p=γ-1 e-ρ u 2 2 ,

(3)

where u=m/ρ is the velocity.

The routine calculates the numerical flux function F UL,UR=F U*UL,UR, where U=UL and U=UR are the left and right solution values, and U*UL,UR is the intermediate state ω 0 arising from the similarity solution U y,t=ω y/t of the Riemann problem defined by

∂U ∂t + ∂F ∂y =0,

(4)

with U and F as in (2), and initial piecewise constant values U=UL for y<0 and U=UR for y>0. The spatial domain is -∞<y<∞, where y=0 is the point at which the numerical flux is required.

The algorithm is termed an Exact Riemann Solver although it does in fact calculate an approximate solution to a true Riemann problem, as opposed to an Approximate Riemann Solver which involves some form of alternative modelling of the Riemann problem. The approximation part of the Exact Riemann Solver is a Newton–Raphson iterative procedure to calculate the pressure, and you must supply a tolerance TOL and a maximum number of iterations NITER. Default values for these arguments can be chosen.

A solution cannot be found by this routine if there is a vacuum state in the Riemann problem (loosely characterised by zero density), or if such a state is generated by the interaction of two non-vacuum data states. In this case a Riemann solver which can handle vacuum states has to be used (see Toro (1996)).

4 References

Toro E F (1989) A weighted average flux method for hyperbolic conservation laws Proc. Roy. Soc. Lond. A423 401–418

Toro E F (1996) Riemann Solvers and Upwind Methods for Fluid Dynamics Springer–Verlag

5 Arguments

1:   ULEFT 3 – REAL (KIND=nag_wp) arrayInput

On entry: ULEFT i must contain the left value of the component Ui, for i=1,2,3. That is, ULEFT 1 must contain the left value of ρ, ULEFT 2 must contain the left value of m and ULEFT 3 must contain the left value of e.

2:   URIGHT 3 – REAL (KIND=nag_wp) arrayInput

On entry: URIGHT i must contain the right value of the component Ui, for i=1,2,3. That is, URIGHT 1 must contain the right value of ρ, URIGHT 2 must contain the right value of m and URIGHT 3 must contain the right value of e.

3:   GAMMA – REAL (KIND=nag_wp)Input

On entry: the ratio of specific heats, γ.

Constraint: GAMMA>0.0.

4:   TOL – REAL (KIND=nag_wp)Input

On entry: the tolerance to be used in the Newton–Raphson procedure to calculate the pressure. If TOL is set to zero then the default value of 1.0×10-6 is used.

Constraint: TOL≥0.0.

5:   NITER – INTEGERInput

On entry: the maximum number of Newton–Raphson iterations allowed. If NITER is set to zero then the default value of 20 is used.

Constraint: NITER≥0.

6:   FLUX 3 – REAL (KIND=nag_wp) arrayOutput

On exit: FLUX i contains the numerical flux component F^i, for i=1,2,3.

7:   IFAIL – INTEGERInput/Output

On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.

On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

Note: if the left and/or right values of ρ or p (from (3)) are found to be negative, then the routine will terminate with an error exit (IFAIL=2). If the routine is being called from the NUMFLX etc., then a soft fail option (IFAIL=1 or -1) is recommended so that a recalculation of the current time step can be forced using the NUMFLX argument IRES (see D03PFF or D03PLF).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).

Errors or warnings detected by the routine:

IFAIL=1

On entry,

GAMMA≤0.0,

or

TOL<0.0,

or

NITER<0.

IFAIL=2

On entry,

the left and/or right density or derived pressure value is less than 0.0.

IFAIL=3

A vacuum condition has been detected therefore a solution cannot be found using this routine. You are advised to check your problem formulation.

IFAIL=4

The internal Newton–Raphson iterative procedure used to solve for the pressure has failed to converge. The value of TOL or NITER may be too small, but if the problem persists try an Approximate Riemann Solver (D03PUF, D03PVF or D03PWF).

IFAIL=-99

An unexpected error has been triggered by this routine. Please contact NAG.

See Section 3.9 in How to Use the NAG Library and its Documentation for further information.

IFAIL=-399

Your licence key may have expired or may not have been installed correctly.

See Section 3.8 in How to Use the NAG Library and its Documentation for further information.

IFAIL=-999

Dynamic memory allocation failed.

See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

The algorithm is exact apart from the calculation of the pressure which uses a Newton–Raphson iterative procedure, the accuracy of which is controlled by the argument TOL. In some cases the initial guess for the Newton–Raphson procedure is exact and no further iterations are required.

8 Parallelism and Performance

D03PXF is not thread safe and should not be called from a multithreaded user program. Please see Section 3.12.1 in How to Use the NAG Library and its Documentation for more information on thread safety.

D03PXF is not threaded in any implementation.

9 Further Comments

D03PXF must only be used to calculate the numerical flux for the Euler equations in exactly the form given by (2), with ULEFT i and URIGHT i containing the left and right values of ρ,m and e, for i=1,2,3, respectively.

For some problems the routine may fail or be highly inefficient in comparison with an Approximate Riemann Solver (e.g., D03PUF, D03PVF or D03PWF). Hence it is advisable to try more than one Riemann solver and to compare the performance and the results.

The time taken by the routine is independent of all input arguments other than TOL.

10 Example

This example uses D03PLF and D03PXF to solve the Euler equations in the domain 0≤x≤1 for 0<t≤0.035 with initial conditions for the primitive variables ρ x,t, u x,t and p x,t given by

ρ x,0=5.99924, u x,0=-19.5975, p x,0=460.894,   for ​x<0.5, ρ x,0=5.99242, u x,0=-6.19633, p x,0=0 46.095,   for ​x>0.5.

This test problem is taken from Toro (1996) and its solution represents the collision of two strong shocks travelling in opposite directions, consisting of a left facing shock (travelling slowly to the right), a right travelling contact discontinuity and a right travelling shock wave. There is an exact solution to this problem (see Toro (1996)) but the calculation is lengthy and has therefore been omitted.

10.1 Program Text

Program Text (d03pxfe.f90)

10.2 Program Data

Program Data (d03pxfe.d)

10.3 Program Results

Program Results (d03pxfe.r)

D03 Chapter Contents

D03 Chapter Introduction

NAG Library Manual

© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


D03PYF : NAG Library, Mark 26

D03 Chapter Contents
D03 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

D03PYF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
10 Example

1 Purpose

D03PYF may be used in conjunction with either D03PDF/D03PDA or D03PJF/D03PJA. It computes the solution and its first derivative at user-specified points in the spatial coordinate.

2 Specification

SUBROUTINE D03PYF ( NPDE, U, NBKPTS, XBKPTS, NPOLY, NPTS, XP, INTPTS, ITYPE, UP, RSAVE, LRSAVE, IFAIL)
INTEGER | NPDE, NBKPTS, NPOLY, NPTS, INTPTS, ITYPE, LRSAVE, IFAIL
REAL (KIND=nag_wp) | U(NPDE,NPTS), XBKPTS(NBKPTS), XP(INTPTS), UP(NPDE,INTPTS,ITYPE), RSAVE(LRSAVE)

3 Description

D03PYF is an interpolation routine for evaluating the solution of a system of partial differential equations (PDEs), or the PDE components of a system of PDEs with coupled ordinary differential equations (ODEs), at a set of user-specified points. The solution of a system of equations can be computed using D03PDF/D03PDA or D03PJF/D03PJA on a set of mesh points; D03PYF can then be employed to compute the solution at a set of points other than those originally used in D03PDF/D03PDA or D03PJF/D03PJA. It can also evaluate the first derivative of the solution. Polynomial interpolation is used between each of the break-points XBKPTS i, for i=1,2,…,NBKPTS. When the derivative is needed (ITYPE=2), the array XP INTPTS must not contain any of the break-points, as the method, and consequently the interpolation scheme, assumes that only the solution is continuous at these points.

4 References

None.

5 Arguments

Note: the arguments U, NPTS, NPDE, XBKPTS, NBKPTS, RSAVE and LRSAVE must be supplied unchanged from either D03PDF/D03PDA or D03PJF/D03PJA.
1:   NPDE – INTEGERInput
On entry: the number of PDEs.
Constraint: NPDE≥1.
2:   U NPDENPTS – REAL (KIND=nag_wp) arrayInput
On entry: the PDE part of the original solution returned in the argument U by the routine D03PDF/D03PDA or D03PJF/D03PJA.
3:   NBKPTS – INTEGERInput
On entry: the number of break-points.
Constraint: NBKPTS≥2.
4:   XBKPTS NBKPTS – REAL (KIND=nag_wp) arrayInput
On entry: XBKPTS i, for i=1,2,…,NBKPTS, must contain the break-points as used by D03PDF/D03PDA or D03PJF/D03PJA.
Constraint: XBKPTS 1<XBKPTS 2<⋯<XBKPTS NBKPTS.
5:   NPOLY – INTEGERInput
On entry: the degree of the Chebyshev polynomial used for approximation as used by D03PDF/D03PDA or D03PJF/D03PJA.
Constraint: 1≤NPOLY≤49.
6:   NPTS – INTEGERInput
On entry: the number of mesh points as used by D03PDF/D03PDA or D03PJF/D03PJA.
Constraint: NPTS=NBKPTS-1×NPOLY+1.
7:   XP INTPTS – REAL (KIND=nag_wp) arrayInput
On entry: XP i, for i=1,2,…,INTPTS, must contain the spatial interpolation points.
Constraints:
  • XBKPTS 1≤XP 1<XP 2<⋯<XP INTPTS≤XBKPTS NBKPTS;
  • if ITYPE=2, XP i≠XBKPTS j, for i=1,2,…,INTPTS and j=2,3,…,NBKPTS-1.
8:   INTPTS – INTEGERInput
On entry: the number of interpolation points.
Constraint: INTPTS≥1.
9:   ITYPE – INTEGERInput
On entry: specifies the interpolation to be performed.
ITYPE=1
The solution at the interpolation points are computed.
ITYPE=2
Both the solution and the first derivative at the interpolation points are computed.
Constraint: ITYPE=1 or 2.
10:   UP NPDEINTPTSITYPE – REAL (KIND=nag_wp) arrayOutput
On exit: if ITYPE=1, UP ij 1, contains the value of the solution Ui xj,tout, at the interpolation points xj=XP j, for j=1,2,…,INTPTS and i=1,2,…,NPDE.
If ITYPE=2, UP ij 1 contains Ui xj,tout and UP ij 2 contains ∂Ui ∂x at these points.
11:   RSAVE LRSAVE – REAL (KIND=nag_wp) arrayCommunication Array
The array RSAVE contains information required by D03PYF as returned by D03PDF/D03PDA or D03PJF/D03PJA. The contents of RSAVE must not be changed from the call to D03PDF/D03PDA or D03PJF/D03PJA. Some elements of this array are overwritten on exit.
12:   LRSAVE – INTEGERInput
On entry: the size of the workspace RSAVE, as in D03PDF/D03PDA or D03PJF/D03PJA.
13:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, | ITYPE≠1 or 2,
or | NPOLY<1,
or | NPDE<1,
or | NBKPTS<2,
or | INTPTS<1,
or | NPTS≠NBKPTS-1×NPOLY+1,
or | XBKPTS i, for i=1,2,…,NBKPTS, are not ordered.
IFAIL=2
On entry, the interpolation points XP i, for i=1,2,…,INTPTS, are not in strictly increasing order, or when ITYPE=2, at least one of the interpolation points stored in XP is equal to one of the break-points stored in XBKPTS.
IFAIL=3
You are attempting extrapolation, that is, one of the interpolation points XP i, for some i, lies outside the interval [XBKPTS 1,XBKPTS NBKPTS]. Extrapolation is not permitted.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

See the documents for D03PDF/D03PDA or D03PJF/D03PJA.

8 Parallelism and Performance

D03PYF is not threaded in any implementation.

9 Further Comments

None.

10 Example

See Section 10 in D03PDF/D03PDA.
D03 Chapter Contents
D03 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


D03PZF : NAG Library, Mark 26

D03 Chapter Contents
D03 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

D03PZF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
10 Example

1 Purpose

D03PZF interpolates in the spatial coordinate the solution and derivative of a system of partial differential equations (PDEs). The solution must first be computed using one of the finite difference schemes D03PCF/D03PCA, D03PHF/D03PHA or D03PPF/D03PPA, or one of the Keller box schemes D03PEF, D03PKF or D03PRF.

2 Specification

SUBROUTINE D03PZF ( NPDE, M, U, NPTS, X, XP, INTPTS, ITYPE, UP, IFAIL)
INTEGER | NPDE, M, NPTS, INTPTS, ITYPE, IFAIL
REAL (KIND=nag_wp) | U(NPDE,NPTS), X(NPTS), XP(INTPTS), UP(NPDE,INTPTS,ITYPE)

3 Description

D03PZF is an interpolation routine for evaluating the solution of a system of partial differential equations (PDEs), at a set of user-specified points. The solution of the system of equations (possibly with coupled ordinary differential equations) must be computed using a finite difference scheme or a Keller box scheme on a set of mesh points. D03PZF can then be employed to compute the solution at a set of points anywhere in the range of the mesh. It can also evaluate the first spatial derivative of the solution. It uses linear interpolation for approximating the solution.

4 References

None.

5 Arguments

Note: the arguments X, M, U, NPTS and NPDE must be supplied unchanged from the PDE routine.
1:   NPDE – INTEGERInput
On entry: the number of PDEs.
Constraint: NPDE≥1.
2:   M – INTEGERInput
On entry: the coordinate system used. If the call to D03PZF follows one of the finite difference routines then M must be the same argument M as used in that call. For the Keller box scheme only Cartesian coordinate systems are valid and so M must be set to zero. No check will be made by D03PZF in this case.
M=0
Indicates Cartesian coordinates.
M=1
Indicates cylindrical polar coordinates.
M=2
Indicates spherical polar coordinates.
Constraints:
  • 0≤M≤2 following a finite difference routine;
  • M=0 following a Keller box scheme routine.
3:   U NPDENPTS – REAL (KIND=nag_wp) arrayInput
On entry: the PDE part of the original solution returned in the argument U by the PDE routine.
Constraint: NPDE≥1.
4:   NPTS – INTEGERInput
On entry: the number of mesh points.
Constraint: NPTS≥3.
5:   X NPTS – REAL (KIND=nag_wp) arrayInput
On entry: X i, for i=1,2,…,NPTS, must contain the mesh points as used by the PDE routine.
6:   XP INTPTS – REAL (KIND=nag_wp) arrayInput
On entry: XP i, for i=1,2,…,INTPTS, must contain the spatial interpolation points.
Constraint: X 1≤XP 1<XP 2<⋯<XP INTPTS≤X NPTS.
7:   INTPTS – INTEGERInput
On entry: the number of interpolation points.
Constraint: INTPTS≥1.
8:   ITYPE – INTEGERInput
On entry: specifies the interpolation to be performed.
ITYPE=1
The solutions at the interpolation points are computed.
ITYPE=2
Both the solutions and their first derivatives at the interpolation points are computed.
Constraint: ITYPE=1 or 2.
9:   UP NPDEINTPTSITYPE – REAL (KIND=nag_wp) arrayOutput
On exit: if ITYPE=1, UP ij 1, contains the value of the solution Ui xj,tout, at the interpolation points xj=XP j, for j=1,2,…,INTPTS and i=1,2,…,NPDE.
If ITYPE=2, UP ij 1 contains Ui xj,tout and UP ij 2 contains ∂Ui ∂x at these points.
10:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, | ITYPE≠1 or 2,
or | INTPTS<1,
or | NPDE<1,
or | NPTS<3,
or | M≠0, 1 or 2,
or | the mesh points X i, for i=1,2,…,NPTS, are not in strictly increasing order.
IFAIL=2
On entry, the interpolation points XP i, for i=1,2,…,INTPTS, are not in strictly increasing order.
IFAIL=3
You are attempting extrapolation, that is, one of the interpolation points XP i, for some i, lies outside the interval [X 1,X NPTS]. Extrapolation is not permitted.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

See the PDE routine documents.

8 Parallelism and Performance

D03PZF is not threaded in any implementation.

9 Further Comments

None.

10 Example

See Section 10 in D03PCF/D03PCA, D03PPF/D03PPA and D03PRF.
D03 Chapter Contents
D03 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


D03RAF : NAG Library, Mark 26

D03 Chapter Contents
D03 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

D03RAF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
▸▿ 9 Further Comments
9.1 Algorithm Outline
9.2 Refinement Strategy
9.3 Time Integration
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

D03RAF integrates a system of linear or nonlinear, time-dependent partial differential equations (PDEs) in two space dimensions on a rectangular domain. The method of lines is employed to reduce the PDEs to a system of ordinary differential equations (ODEs) which are solved using a backward differentiation formula (BDF) method. The resulting system of nonlinear equations is solved using a modified Newton method and a Bi-CGSTAB iterative linear solver with ILU preconditioning. Local uniform grid refinement is used to improve the accuracy of the solution. D03RAF originates from the VLUGR2 package (see Blom and Verwer (1993) and Blom et al. (1996)).

2 Specification

SUBROUTINE D03RAF ( NPDE, TS, TOUT, DT, XMIN, XMAX, YMIN, YMAX, NX, NY, TOLS, TOLT, PDEDEF, BNDARY, PDEIV, MONITR, OPTI, OPTR, RWK, LENRWK, IWK, LENIWK, LWK, LENLWK, ITRACE, IND, IFAIL)
INTEGER | NPDE, NX, NY, OPTI(4), LENRWK, IWK(LENIWK), LENIWK, LENLWK, ITRACE, IND, IFAIL
REAL (KIND=nag_wp) | TS, TOUT, DT(3), XMIN, XMAX, YMIN, YMAX, TOLS, TOLT, OPTR(3,NPDE), RWK(LENRWK)
LOGICAL | LWK(LENLWK)
EXTERNAL | PDEDEF, BNDARY, PDEIV, MONITR

3 Description

D03RAF integrates the system of PDEs:
Fj t,x,y,u,ut,ux,uy,u xx,u xy,u yy=0,  j=1,2,…,NPDE, (1)
for x and y in the rectangular domain xmin≤x≤xmax, ymin≤y≤ymax, and time interval t 0≤t≤tout, where the vector u is the set of solution values
u x,y,t=u 1 x,y,t,…,uNPDE x,y,t T,
and ut denotes partial differentiation with respect to t, and similarly for ux etc.
The functions Fj must be supplied by you in PDEDEF. Similarly the initial values of the functions u x,y,t must be specified at t=t 0 in PDEIV.
Note that whilst complete generality is offered by the master equations (1), D03RAF is not appropriate for all PDEs. In particular, hyperbolic systems should not be solved using this routine. Also, at least one component of ut must appear in the system of PDEs.
The boundary conditions must be supplied by you in BNDARY in the form
Gj t,x,y,u,ut,ux,uy = 0 , (2)
for all y when xmin or xmax and for all x when y=ymin or y=ymax and j=1,2,…,NPDE
The domain is covered by a uniform coarse base grid of size nx×ny specified by you, and nested finer uniform subgrids are subsequently created in regions with high spatial activity. The refinement is controlled using a space monitor which is computed from the current solution and a user-supplied space tolerance TOLS. A number of optional parameters, e.g., the maximum number of grid levels at any time, and some weighting factors, can be specified in the arrays OPTI and OPTR. Further details of the refinement strategy can be found in Section 9.
The system of PDEs and the boundary conditions are discretized in space on each grid using a standard second-order finite difference scheme (centred on the internal domain and one-sided at the boundaries), and the resulting system of ODEs is integrated in time using a second-order, two-step, implicit BDF method with variable step size. The time integration is controlled using a time monitor computed at each grid level from the current solution and a user-supplied time tolerance TOLT, and some further optional user-specified weighting factors held in OPTR (see Section 9 for details). The time monitor is used to compute a new step size, subject to restrictions on the size of the change between steps, and (optional) user-specified maximum and minimum step sizes held in DT. The step size is adjusted so that the remaining integration interval is an integer number times Δt. In this way a solution is obtained at t=tout.
A modified Newton method is used to solve the nonlinear equations arising from the time integration. You may specify (in OPTI) the maximum number of Newton iterations to be attempted. A Jacobian matrix is calculated at the beginning of each time step. If the Newton process diverges or the maximum number of iterations is exceeded, a new Jacobian is calculated using the most recent iterates and the Newton process is restarted. If convergence is not achieved after the (optional) user-specified maximum number of new Jacobian evaluations, the time step is retried with Δt=Δt/4. The linear systems arising from the Newton iteration are solved using a Bi-CGSTAB iterative method, in combination with ILU preconditioning. The maximum number of iterations can be specified by you in OPTI.
The solution at all grid levels is stored in the workspace arrays, along with other information needed for a restart (i.e., a continuation call). It is not intended that you extract the solution from these arrays, indeed the necessary information regarding these arrays is not included. The user-supplied monitor MONITR should be used to obtain the solution at particular levels and times. MONITR is called at the end of every time step, with the last step being identified via the input argument TLAST.
Within PDEIV, PDEDEF, BNDARY and MONITR the data structure is as follows. Each point on a particular grid is given an index (ranging from 1 to the total number of points on the grid) and all coordinate or solution information is stored in arrays according to this index, e.g., X i and Y i contain the x- and y coordinate of point i, and U ij contains the jth solution component uj at point i.
Further details of the underlying algorithm can be found in Section 9 and in Blom and Verwer (1993) and Blom et al. (1996) and the references therein.

4 References

Adjerid S and Flaherty J E (1988) A local refinement finite element method for two-dimensional parabolic systems SIAM J. Sci. Statist. Comput. 9 792–811
Blom J G, Trompert R A and Verwer J G (1996) Algorithm 758. VLUGR2: A vectorizable adaptive grid solver for PDEs in 2D Trans. Math. Software 22 302–328
Blom J G and Verwer J G (1993) VLUGR2: A vectorized local uniform grid refinement code for PDEs in 2D Report NM-R9306 CWI, Amsterdam
Brown P N, Hindmarsh A C and Petzold L R (1994) Using Krylov methods in the solution of large scale differential-algebraic systems SIAM J. Sci. Statist. Comput. 15 1467–1488
Trompert R A (1993) Local uniform grid refinement and systems of coupled partial differential equations Appl. Numer. Maths 12 331–355
Trompert R A and Verwer J G (1993) Analysis of the implicit Euler local uniform grid refinement method SIAM J. Sci. Comput. 14 259–278

5 Arguments

1:   NPDE – INTEGERInput
On entry: the number of PDEs in the system.
Constraint: NPDE≥1.
2:   TS – REAL (KIND=nag_wp)Input/Output
On entry: the initial value of the independent variable t.
On exit: the value of t which has been reached. Normally TS=TOUT.
Constraint: TS<TOUT.
3:   TOUT – REAL (KIND=nag_wp)Input
On entry: the final value of t to which the integration is to be carried out.
4:   DT 3 – REAL (KIND=nag_wp) arrayInput/Output
On entry: the initial, minimum and maximum time step sizes respectively.
DT 1
Specifies the initial time step size to be used on the first entry, i.e., when IND=0. If DT 1=0.0 then the default value DT 1=0.01×TOUT-TS is used. On subsequent entries (IND=1), the value of DT 1 is not referenced.
DT 2
Specifies the minimum time step size to be attempted by the integrator. If DT 2=0.0 the default value DT 2=10.0×machine precision is used.
DT 3
Specifies the maximum time step size to be attempted by the integrator. If DT 3=0.0 the default value DT 3=TOUT-TS is used.
On exit: DT 1 contains the time step size for the next time step. DT 2 and DT 3 are unchanged or set to their default values if zero on entry.
Constraints:
  • if IND=0, DT 1≥0.0;
  • if IND=0 and DT 1>0.0, 10.0×machine precision×max TS,TOUT≤DT 1≤TOUT-TS and DT 2≤DT 1≤DT 3, where the values of DT 2 and DT 3 will have been reset to their default values if zero on entry;
  • 0≤ DT 2≤ DT 3 .
5:   XMIN – REAL (KIND=nag_wp)Input
6:   XMAX – REAL (KIND=nag_wp)Input
On entry: the extents of the rectangular domain in the x-direction, i.e., the x coordinates of the left and right boundaries respectively.
Constraint: XMIN<XMAX and XMAX must be sufficiently distinguishable from XMIN for the precision of the machine being used.
7:   YMIN – REAL (KIND=nag_wp)Input
8:   YMAX – REAL (KIND=nag_wp)Input
On entry: the extents of the rectangular domain in the y-direction, i.e., the y coordinates of the lower and upper boundaries respectively.
Constraint: YMIN<YMAX and YMAX must be sufficiently distinguishable from YMIN for the precision of the machine being used.
9:   NX – INTEGERInput
On entry: the number of grid points in the x-direction (including the boundary points).
Constraint: NX≥4.
10:   NY – INTEGERInput
On entry: the number of grid points in the y-direction (including the boundary points).
Constraint: NY≥4.
11:   TOLS – REAL (KIND=nag_wp)Input
On entry: the space tolerance used in the grid refinement strategy (σ in equation (4)). See Section 9.2.
Constraint: TOLS>0.0.
12:   TOLT – REAL (KIND=nag_wp)Input
On entry: the time tolerance used to determine the time step size (τ in equation (7)). See Section 9.3.
Constraint: TOLT>0.0.
13:   PDEDEF – SUBROUTINE, supplied by the user.External Procedure
PDEDEF must evaluate the functions Fj, for j=1,2,…,NPDE, in equation (1) which define the system of PDEs (i.e., the residuals of the resulting ODE system) at all interior points of the domain. Values at points on the boundaries of the domain are ignored and will be overwritten by BNDARY. PDEDEF is called for each subgrid in turn.
The specification of PDEDEF is:
SUBROUTINE PDEDEF ( NPTS, NPDE, T, X, Y, U, UT, UX, UY, UXX, UXY, UYY, RES)
INTEGER | NPTS, NPDE
REAL (KIND=nag_wp) | T, X(NPTS), Y(NPTS), U(NPTS,NPDE), UT(NPTS,NPDE), UX(NPTS,NPDE), UY(NPTS,NPDE), UXX(NPTS,NPDE), UXY(NPTS,NPDE), UYY(NPTS,NPDE), RES(NPTS,NPDE)
1:   NPTS – INTEGERInput
On entry: the number of grid points in the current grid.
2:   NPDE – INTEGERInput
On entry: the number of PDEs in the system.
3:   T – REAL (KIND=nag_wp)Input
On entry: the current value of the independent variable t.
4:   X NPTS – REAL (KIND=nag_wp) arrayInput
On entry: X i contains the x coordinate of the ith grid point, for i=1,2,…,NPTS.
5:   Y NPTS – REAL (KIND=nag_wp) arrayInput
On entry: Y i contains the y coordinate of the ith grid point, for i=1,2,…,NPTS.
6:   U NPTSNPDE – REAL (KIND=nag_wp) arrayInput
On entry: U ij contains the value of the jth PDE component at the ith grid point, for i=1,2,…,NPTS and j=1,2,…,NPDE.
7:   UT NPTSNPDE – REAL (KIND=nag_wp) arrayInput
On entry: UT ij contains the value of ∂u ∂t for the jth PDE component at the ith grid point, for i=1,2,…,NPTS and j=1,2,…,NPDE.
8:   UX NPTSNPDE – REAL (KIND=nag_wp) arrayInput
On entry: UX ij contains the value of ∂u ∂x for the jth PDE component at the ith grid point, for i=1,2,…,NPTS and j=1,2,…,NPDE.
9:   UY NPTSNPDE – REAL (KIND=nag_wp) arrayInput
On entry: UY ij contains the value of ∂u ∂y for the jth PDE component at the ith grid point, for i=1,2,…,NPTS and j=1,2,…,NPDE.
10:   UXX NPTSNPDE – REAL (KIND=nag_wp) arrayInput
On entry: UXX ij contains the value of ∂2 u ∂x 2 for the jth PDE component at the ith grid point, for i=1,2,…,NPTS and j=1,2,…,NPDE.
11:   UXY NPTSNPDE – REAL (KIND=nag_wp) arrayInput
On entry: UXY ij contains the value of ∂2 u ∂x∂y for the jth PDE component at the ith grid point, for i=1,2,…,NPTS and j=1,2,…,NPDE.
12:   UYY NPTSNPDE – REAL (KIND=nag_wp) arrayInput
On entry: UYY ij contains the value of ∂2 u ∂y 2 for the jth PDE component at the ith grid point, for i=1,2,…,NPTS and j=1,2,…,NPDE.
13:   RES NPTSNPDE – REAL (KIND=nag_wp) arrayOutput
On exit: RES ij must contain the value of Fj, for j=1,2,…,NPDE, at the ith grid point, for i=1,2,…,NPTS, although the residuals at boundary points will be ignored (and overwritten later on) and so they need not be specified here.
PDEDEF must either be a module subprogram USEd by, or declared as EXTERNAL in, the (sub)program from which D03RAF is called. Arguments denoted as Input must not be changed by this procedure.
14:   BNDARY – SUBROUTINE, supplied by the user.External Procedure
BNDARY must evaluate the functions Gj, for j=1,2,…,NPDE, in equation (2) which define the boundary conditions at all boundary points of the domain. Residuals at interior points must not be altered by this subroutine.
The specification of BNDARY is:
SUBROUTINE BNDARY ( NPTS, NPDE, T, X, Y, U, UT, UX, UY, NBPTS, LBND, RES)
INTEGER | NPTS, NPDE, NBPTS, LBND(NBPTS)
REAL (KIND=nag_wp) | T, X(NPTS), Y(NPTS), U(NPTS,NPDE), UT(NPTS,NPDE), UX(NPTS,NPDE), UY(NPTS,NPDE), RES(NPTS,NPDE)
1:   NPTS – INTEGERInput
On entry: the number of grid points in the current grid.
2:   NPDE – INTEGERInput
On entry: the number of PDEs in the system.
3:   T – REAL (KIND=nag_wp)Input
On entry: the current value of the independent variable t.
4:   X NPTS – REAL (KIND=nag_wp) arrayInput
On entry: X i contains the x coordinate of the ith grid point, for i=1,2,…,NPTS.
5:   Y NPTS – REAL (KIND=nag_wp) arrayInput
On entry: Y i contains the y coordinate of the ith grid point, for i=1,2,…,NPTS.
6:   U NPTSNPDE – REAL (KIND=nag_wp) arrayInput
On entry: U ij contains the value of the jth PDE component at the ith grid point, for i=1,2,…,NPTS and j=1,2,…,NPDE.
7:   UT NPTSNPDE – REAL (KIND=nag_wp) arrayInput
On entry: UT ij contains the value of ∂u ∂t for the jth PDE component at the ith grid point, for i=1,2,…,NPTS and j=1,2,…,NPDE.
8:   UX NPTSNPDE – REAL (KIND=nag_wp) arrayInput
On entry: UX ij contains the value of ∂u ∂x for the jth PDE component at the ith grid point, for i=1,2,…,NPTS and j=1,2,…,NPDE.
9:   UY NPTSNPDE – REAL (KIND=nag_wp) arrayInput
On entry: UY ij contains the value of ∂u ∂y for the jth PDE component at the ith grid point, for i=1,2,…,NPTS and j=1,2,…,NPDE.
10:   NBPTS – INTEGERInput
On entry: the number of boundary points in the grid.
11:   LBND NBPTS – INTEGER arrayInput
On entry: LBND i contains the grid index for the ith boundary point, for i=1,2,…,NBPTS. Hence the ith boundary point has coordinates X LBND i and Y LBND i, and the corresponding solution values are U LBND i NPDE, etc.
12:   RES NPTSNPDE – REAL (KIND=nag_wp) arrayInput/Output
On entry: RES ij contains the value of Fj, for i=1,2,…,NPDE, at the ith grid point, for i=1,2,…,NPTS, as returned by PDEDEF. The residuals at the boundary points will be overwritten and so need not have been set by PDEDEF.
On exit: RES LBND i j must contain the value of Gj, for j=1,2,…,NPDE, at the ith boundary point, for i=1,2,…,NBPTS.
Note: elements of RES corresponding to interior points must not be altered.
BNDARY must either be a module subprogram USEd by, or declared as EXTERNAL in, the (sub)program from which D03RAF is called. Arguments denoted as Input must not be changed by this procedure.
15:   PDEIV – SUBROUTINE, supplied by the user.External Procedure
PDEIV must specify the initial values of the PDE components u at all points in the grid. PDEIV is not referenced if, on entry, IND=1.
The specification of PDEIV is:
SUBROUTINE PDEIV ( NPTS, NPDE, T, X, Y, U)
INTEGER | NPTS, NPDE
REAL (KIND=nag_wp) | T, X(NPTS), Y(NPTS), U(NPTS,NPDE)
1:   NPTS – INTEGERInput
On entry: the number of grid points in the grid.
2:   NPDE – INTEGERInput
On entry: the number of PDEs in the system.
3:   T – REAL (KIND=nag_wp)Input
On entry: the (initial) value of the independent variable t.
4:   X NPTS – REAL (KIND=nag_wp) arrayInput
On entry: X i contains the x coordinate of the ith grid point, for i=1,2,…,NPTS.
5:   Y NPTS – REAL (KIND=nag_wp) arrayInput
On entry: Y i contains the y coordinate of the ith grid point, for i=1,2,…,NPTS.
6:   U NPTSNPDE – REAL (KIND=nag_wp) arrayOutput
On exit: U ij must contain the value of the jth PDE component at the ith grid point, for i=1,2,…,NPTS and j=1,2,…,NPDE.
PDEIV must either be a module subprogram USEd by, or declared as EXTERNAL in, the (sub)program from which D03RAF is called. Arguments denoted as Input must not be changed by this procedure.
16:   MONITR – SUBROUTINE, supplied by the user.External Procedure
MONITR is called by D03RAF at the end of every successful time step, and may be used to examine or print the solution or perform other tasks such as error calculations, particularly at the final time step, indicated by the argument TLAST. The input arguments contain information about the grid and solution at all grid levels used.
MONITR can also be used to force an immediate tidy termination of the solution process and return to the calling program.
The specification of MONITR is:
SUBROUTINE MONITR ( NPDE, T, DT, DTNEW, TLAST, NLEV, NGPTS, XPTS, YPTS, LSOL, SOL, IERR)
INTEGER | NPDE, NLEV, NGPTS(NLEV), LSOL(NLEV), IERR
REAL (KIND=nag_wp) | T, DT, DTNEW, XPTS(*), YPTS(*), SOL(*)
LOGICAL | TLAST
1:   NPDE – INTEGERInput
On entry: the number of PDEs in the system.
2:   T – REAL (KIND=nag_wp)Input
On entry: the current value of the independent variable t, i.e., the time at the end of the integration step just completed.
3:   DT – REAL (KIND=nag_wp)Input
On entry: the current time step size Δt, i.e., the time step size used for the integration step just completed.
4:   DTNEW – REAL (KIND=nag_wp)Input
On entry: the step size that will be used for the next time step.
5:   TLAST – LOGICALInput
On entry: indicates if intermediate or final time step. TLAST=.FALSE. for an intermediate step, TLAST=.TRUE. for the last call to MONITR before returning to your program.
6:   NLEV – INTEGERInput
On entry: the number of grid levels used at time T.
7:   NGPTS NLEV – INTEGER arrayInput
On entry: NGPTS l contains the number of grid points at level l, for l=1,2,…,NLEV.
8:   XPTS* – REAL (KIND=nag_wp) arrayInput
On entry: contains the x coordinates of the grid points in each level in turn, i.e., X i, for i=1,2,…,NGPTS l and l=1,2,…,NLEV.
So for level l, X i=XPTS k+i, where k=NGPTS 1+NGPTS 2+⋯+NGPTS l-1, for i=1,2,…,NGPTS l and l=1,2,…,NLEV.
9:   YPTS* – REAL (KIND=nag_wp) arrayInput
On entry: contains the y coordinates of the grid points in each level in turn, i.e., Y i, for i=1,2,…,NGPTS l and l=1,2,…,NLEV.
So for level l, Y i=YPTS k+i, where k=NGPTS 1+NGPTS 2+⋯+NGPTS l-1, for i=1,2,…,NGPTS l and l=1,2,…,NLEV.
10:   LSOL NLEV – INTEGER arrayInput
On entry: LSOL l contains the pointer to the solution in SOL at grid level l and time T. (LSOL l actually contains the array index immediately preceding the start of the solution in SOL.)
11:   SOL* – REAL (KIND=nag_wp) arrayInput
On entry: contains the solution U NGPTS l NPDE at time T for each grid level l in turn, positioned according to LSOL, i.e., for level l, U ij=SOL LSOL l+j-1×NGPTS l+i, for i=1,2,…,NGPTS l, j=1,2,…,NPDE and l=1,2,…,NLEV.
12:   IERR – INTEGERInput/Output
On entry: will be set to 0.
On exit: should be set to 1 to force a tidy termination and an immediate return to the calling program with IFAIL=4. IERR should remain unchanged otherwise.
MONITR must either be a module subprogram USEd by, or declared as EXTERNAL in, the (sub)program from which D03RAF is called. Arguments denoted as Input must not be changed by this procedure.
17:   OPTI 4 – INTEGER arrayInput
On entry: may be set to control various options available in the integrator.
OPTI 1=0
All the default options are employed.
OPTI 1>0
The default value of OPTI i, for i=2,3,4, can be obtained by setting OPTI i=0.
OPTI 1
Specifies the maximum number of grid levels allowed (including the base grid). OPTI 1≥0. The default value is OPTI 1=3.
OPTI 2
Specifies the maximum number of Jacobian evaluations allowed during each nonlinear equations solution. OPTI 2≥0. The default value is OPTI 2=2.
OPTI 3
Specifies the maximum number of Newton iterations in each nonlinear equations solution. OPTI 3≥0. The default value is OPTI 3=10.
OPTI 4
Specifies the maximum number of iterations in each linear equations solution. OPTI 4≥0. The default value is OPTI 4=100.
Constraint: OPTI 1≥0 and if OPTI 1>0, OPTI i≥0, for i=2,3,4.
18:   OPTR 3 NPDE – REAL (KIND=nag_wp) arrayInput
On entry: may be used to specify the optional vectors umax, ws and wt in the space and time monitors (see Section 9).
If an optional vector is not required then all its components should be set to 1.0.
OPTR 1 j, for j=1,2,…,NPDE, specifies ujmax, the approximate maximum absolute value of the jth component of u, as used in (4) and (7). OPTR 1 j>0.0, for j=1,2,…,NPDE.
OPTR 2 j, for j=1,2,…,NPDE, specifies wjs, the weighting factors used in the space monitor (see (4)) to indicate the relative importance of the jth component of u on the space monitor. OPTR 2 j≥0.0, for j=1,2,…,NPDE.
OPTR 3 j, for j=1,2,…,NPDE, specifies wjt, the weighting factors used in the time monitor (see (6)) to indicate the relative importance of the jth component of u on the time monitor. OPTR 3 j≥0.0, for j=1,2,…,NPDE.
Constraints:
  • OPTR 1 j>0.0, for j=1,2,…,NPDE;
  • OPTR ij≥0.0, for i=2,3 and j=1,2,…,NPDE.
19:   RWK LENRWK – REAL (KIND=nag_wp) arrayCommunication Array
20:   LENRWK – INTEGERInput
On entry: the dimension of the array RWK as declared in the (sub)program from which D03RAF is called.
The required value of LENRWK cannot be determined exactly in advance, but a suggested value is
LENRWK=maxpts×NPDE×5×l+18×NPDE+9+2×maxpts,
where l=OPTI 1 if OPTI 1≠0 and l=3 otherwise, and maxpts is the expected maximum number of grid points at any one level. If during the execution the supplied value is found to be too small then the routine returns with IFAIL=3 and an estimated required size is printed on the current error message unit (see X04AAF).
Constraint: LENRWK≥NX×NY×NPDE×14+18×NPDE+2×NX×NY (the required size for the initial grid).
21:   IWK LENIWK – INTEGER arrayCommunication Array
On entry: if IND=0, IWK need not be set. Otherwise IWK must remain unchanged from a previous call to D03RAF.
On exit: the following components of the array IWK concern the efficiency of the integration. Here, m is the maximum number of grid levels allowed (m=OPTI 1 if OPTI 1>1 and m=3 otherwise), and l is a grid level taking the values l=1,2,…,nl, where nl is the number of levels used.
IWK 1
Contains the number of steps taken in time.
IWK 2
Contains the number of rejected time steps.
IWK 2+l
Contains the total number of residual evaluations performed (i.e., the number of times PDEDEF was called) at grid level l.
IWK 2+m+l
Contains the total number of Jacobian evaluations performed at grid level l.
IWK 2+2×m+l
Contains the total number of Newton iterations performed at grid level l.
IWK 2+3×m+l
Contains the total number of linear solver iterations performed at grid level l.
IWK 2+4×m+l
Contains the maximum number of Newton iterations performed at any one time step at grid level l.
IWK 2+5×m+l
Contains the maximum number of linear solver iterations performed at any one time step at grid level l.
Note: the total and maximum numbers are cumulative over all calls to D03RAF. If the specified maximum number of Newton or linear solver iterations is exceeded at any stage, then the maximums above are set to the specified maximum plus one.
22:   LENIWK – INTEGERInput
On entry: the dimension of the array IWK as declared in the (sub)program from which D03RAF is called.
The required value of LENIWK cannot be determined exactly in advance, but a suggested value is
LENIWK=maxpts×14+5×m+7×m+2,
where maxpts is the expected maximum number of grid points at any one level and m=OPTI 1 if OPTI 1>0 and m=3 otherwise. If during the execution the supplied value is found to be too small then the routine returns with IFAIL=3 and an estimated required size is printed on the current error message unit (see X04AAF).
Constraint: LENIWK≥19×NX×NY+9 (the required size for the initial grid).
23:   LWK LENLWK – LOGICAL arrayWorkspace
24:   LENLWK – INTEGERInput
On entry: the dimension of the array LWK as declared in the (sub)program from which D03RAF is called.
The required value of LENLWK cannot be determined exactly in advanced, but a suggested value is
LENLWK=maxpts+1,
where maxpts is the expected maximum number of grid points at any one level. If during the execution the supplied value is found to be too small then the routine returns with IFAIL=3 and an estimated required size is printed on the current error message unit (see X04AAF).
Constraint: LENLWK≥NX×NY+1 (the required size for the initial grid).
25:   ITRACE – INTEGERInput
On entry: the level of trace information required from D03RAF. ITRACE may take the value -1, 0, 1, 2 or 3.
ITRACE=-1
No output is generated.
ITRACE=0
Only warning messages are printed.
ITRACE>0
Output from the underlying solver is printed on the current advisory message unit (see X04ABF). This output contains details of the time integration, the nonlinear iteration and the linear solver.
If ITRACE<-1, then -1 is assumed and similarly if ITRACE>3, then 3 is assumed.
The advisory messages are given in greater detail as ITRACE increases. Setting ITRACE=1 allows you to monitor the progress of the integration without possibly excessive information.
26:   IND – INTEGERInput/Output
On entry: must be set to 0 or 1, alternatively 10 or 11.
IND=0
Starts the integration in time. PDEDEF is assumed to be serial.
IND=1
Continues the integration after an earlier exit from the routine. In this case, only the following parameters may be reset between calls to D03RAF: TOUT, DT, TOLS, TOLT, OPTI, OPTR, ITRACE and IFAIL. PDEDEF is assumed to be serial.
IND=10
Starts the integration in time. PDEDEF is assumed to have been parallelized by you, as described in Section 8. In all other respects, this is equivalent to IND=0.
IND=11
Continues the integration after an earlier exit from the routine. In this case, only the following parameters may be reset between calls to D03RAF: TOUT, DT, TOLS, TOLT, OPTI, OPTR, ITRACE and IFAIL. PDEDEF is assumed to have been parallelized by you, as described in Section 8. In all other respects, this is equivalent to IND=1.
Constraint: 0≤IND≤1 or 10≤IND≤11.
On exit: IND=1, if IND on input was 0 or 1, or IND=11, if IND on input was 10 or 11.
Note: for users of serial versions of the NAG Library, it is recommended that you only use IND=0 or 1. See Section 8 for more information on the use of IND.
27:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, | NPDE<1,
or | TOUT≤TS,
or | TOUT is too close to TS,
or | IND=0 and DT 1<0.0,
or | DT i<0.0, for i=2​ or ​3,
or | DT 2>DT 3,
or | IND=0 and 0.0<DT 1<10×machine precision×max TS,TOUT,
or | IND=0 and DT 1>TOUT-TS,
or | IND=0 and DT 1<DT 2 or DT 1>DT 3,
or | XMIN≥XMAX,
or | XMAX too close to XMIN,
or | YMIN≥YMAX,
or | YMAX too close to YMIN,
or | NX or NY<4,
or | TOLS or TOLT≤0.0,
or | OPTI 1<0,
or | OPTI 1>0 and OPTI j<0, for j=2, 3 or 4,
or | OPTR 1 j≤0.0, for some j=1,2,…,NPDE,
or | OPTR 2 j<0.0, for some j=1,2,…,NPDE,
or | OPTR 3 j<0.0, for some j=1,2,…,NPDE,
or | LENRWK, LENIWK or LENLWK too small for initial grid level,
or | IND≠0 or 1,
or | IND=1 on initial entry to D03RAF.
IFAIL=2
The time step size to be attempted is less than the specified minimum size. This may occur following time step failures and subsequent step size reductions caused by one or more of the following:
  • the requested accuracy could not be achieved, i.e., TOLT is too small,
  • the maximum number of linear solver iterations, Newton iterations or Jacobian evaluations is too small,
  • ILU decomposition of the Jacobian matrix could not be performed, possibly due to singularity of the Jacobian.
Setting ITRACE to a higher value may provide further information.
In the latter two cases you are advised to check their problem formulation in PDEDEF and/or BNDARY, and the initial values in PDEIV if appropriate.
IFAIL=3
One or more of the workspace arrays is too small for the required number of grid points. An estimate of the required sizes for the current stage is output, but more space may be required at a later stage.
IFAIL=4
IERR was set to 1 in MONITR, forcing control to be passed back to calling program. Integration was successful as far as T=TS.
IFAIL=5
The integration has been completed but the maximum number of levels specified in OPTI 1 was insufficient at one or more time steps, meaning that the requested space accuracy could not be achieved. To avoid this warning either increase the value of OPTI 1 or decrease the value of TOLS.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

There are three sources of error in the algorithm: space and time discretization, and interpolation (linear) between grid levels. The space and time discretization errors are controlled separately using the arguments TOLS and TOLT described in the following section, and you should test the effects of varying these arguments. Interpolation errors are generally implicitly controlled by the refinement criterion since in areas where interpolation errors are potentially large, the space monitor will also be large. It can be shown that the global spatial accuracy is comparable to that which would be obtained on a uniform grid of the finest grid size. A full error analysis can be found in Trompert and Verwer (1993).

8 Parallelism and Performance

D03RAF is not thread safe and should not be called from a multithreaded user program. Please see Section 3.12.1 in How to Use the NAG Library and its Documentation for more information on thread safety.
D03RAF is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
D03RAF makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.
D03RAF requires a user-supplied routine PDEDEF to evaluate the functions Fj, for j=1,2,…,NPDE. The parallelism within D03RAF will be more efficient if PDEDEF can also be parallelized. This is often the case, but you must add some OpenMP directives to your version of PDEDEF to implement the parallelism. For example, if the body of code for PDEDEF is as follows (adapted from the first test case in the document for D03RAF):
res(1:npts,1:npde) = ut(1:npts,1:npde) - diffusion*(uxx(1:npts,1:         &
  npde)+uyy(1:npts,1:npde)) - damkohler*(one+heat_release-u(1:npts,       &
  1:npde))*exp(-activ_energy/u(1:npts,1:npde))
This example can be parallelized, as the updating of RES for each value in the range 1,…,NPTS is independent of every other value. Thus this should be parallelized in OpenMP (using an explicit loop rather than Fortran array syntax) as follows:
!$OMP DO
   Do i = 1, npts
      res(i,1:npde) = ut(i,1:npde) -diffusion*(uxx(i,1:npde)+uyy(i,1:npde &
       )) - damkohler*(1.0E0_nag_wp+heat_release-u(i,1:npde))*exp(-       &
        activ_energy/u(i,1:npde))
   End Do
!$OMP END DO
Note that the OpenMP PARALLEL directive must not be specified, as the OpenMP DO directive will bind to the PARALLEL region within the D03RAF code. Also note that this assumes the default OpenMP behaviour that all variables are SHARED, except for loop indices that are PRIVATE.
To avoid problems for existing library users, who will not have specified any OpenMP directives in their PDEDEF routine, the default assumption of D03RAF is that PDEDEF has not been parallelized, and executes calls to PDEDEF in serial mode. You must indicate that PDEDEF has been parallelized by setting IND to 10 or 11 as appropriate. See Section 5 for details.
If the code within PDEDEF cannot be parallelized, you must not add any OpenMP directives to your code, and must not set IND to 10 or 11. If IND is set to 10 or 11 and PDEDEF has not been parallelized, results on multiple threads will be unpredictable and may give rise to incorrect results and/or program crashes or deadlocks. Please contact NAG for advice if required. Overloading IND in this manner is not entirely satisfactory, consequently it is likely that replacement interfaces for D03RAF will be included in a future NAG Library release.

9 Further Comments

9.1 Algorithm Outline

The local uniform grid refinement method is summarised as follows:
1. | Initialize the course base grid, an initial solution and an initial time step.
2. | Solve the system of PDEs on the current grid with the current time step.
3. If the required accuracy in space and the maximum number of grid levels have not yet been reached:
(a) | Determine new finer grid at forward time level.
(b) | Get solution values at previous time level(s) on new grid.
(c) | Interpolate internal boundary values from old grid at forward time.
(d) | Get initial values for the Newton process at forward time.
(e) | Go to 2.
4. | Update the coarser grid solution using the finer grid values.
5. | Estimate error in time integration. If time error is acceptable advance time level.
6. | Determine new step size then go to 2 with coarse base as current grid.

9.2 Refinement Strategy

For each grid point i a space monitor μis is determined by
μ i s = max j=1,NPDE γ j Δ x 2 ∂ 2 ∂ x 2 u j x i , y i ,t + Δ y 2 ∂ 2 ∂ y 2 u j x i , y i ,t , (3)
where Δx and Δy are the grid widths in the x and y directions; and xi, yi are the x and y coordinates at grid point i. The argument γj is obtained from
γj=wjs ujmax σ , (4)
where σ is the user-supplied space tolerance; wjs is a weighting factor for the relative importance of the jth PDE component on the space monitor; and ujmax is the approximate maximum absolute value of the jth component. A value for σ must be supplied by you. Values for wjs and ujmax must also be supplied but may be set to the value 1.0 if little information about the solution is known.
A new level of refinement is created if
maxi μis>0.9  or  1.0, (5)
depending on the grid level at the previous step in order to avoid fluctuations in the number of grid levels between time steps. If (5) is satisfied then all grid points for which μis>0.25 are flagged and surrounding cells are quartered in size.
No derefinement takes place as such, since at each time step the solution on the base grid is computed first and new finer grids are then created based on the new solution. Hence derefinement occurs implicitly. See Section 9.1.

9.3 Time Integration

The time integration is controlled using a time monitor calculated at each level l up to the maximum level used, given by
μlt=1 N∑j=1 NPDE wjt∑i=1 NGPTS l Δt α ij ut xi,yi,t 2 (6)
where NGPTS l is the total number of points on grid level l; N=NGPTS l×NPDE; Δt is the current time step; ut is the time derivative of u which is approximated by first-order finite differences; wjt is the time equivalent of the space weighting factor wjs; and α ij is given by
α ij=τ ujmax 100+u xi,yi,t (7)
where ujmax is as before, and τ is the user-specified time tolerance.
An integration step is rejected and retried at all levels if
maxl μlt>1.0. (8)

10 Example

For this routine two examples are presented, with a main program and two example problems given in Example 1 (EX1) and Example 2 (EX2).
Example 1 (EX1)
This example stems from combustion theory and is a model for a single, one-step reaction of a mixture of two chemicals (see Adjerid and Flaherty (1988)). The PDE for the temperature of the mixture u is
∂u ∂t =d ∂2 u ∂x 2 + ∂2 u ∂y 2 +D 1+α-u exp-δu
for 0≤x,y≤1 and t≥0, with initial conditions u x,y,0=1 for 0≤x,y≤1, and boundary conditions
ux 0,y,t = 0, u 1,y,t = 1   for ​ 0≤y≤1,
uy x,0,t = 0, u x,1,t = 1   for ​ 0≤x≤ 1.
The heat release argument α=1, the Damkohler number D=R exp δ/αδ, the activation energy δ=20, the reaction rate R=5, and the diffusion argument d=0.1.
For small times the temperature gradually increases in a circular region about the origin, and at about t=0.24 ‘ignition’ occurs causing the temperature to suddenly jump from near unity to 1+α, and a reaction front forms and propagates outwards, becoming steeper. Thus during the solution, just one grid level is used up to the ignition point, then two levels, and then three as the reaction front steepens.
Example 2 (EX2)
This example is taken from a multispecies food web model, in which predator-prey relationships in a spatial domain are simulated (see Brown et al. (1994)). In this example there is just one species each of prey and predator, and the two PDEs for the concentrations c 1 and c 2 of the prey and the predator respectively are
∂c 1 ∂t =c 1 b 1+a 11c 1+a 12c 2+d 1 ∂2 c 1 ∂x 2 + ∂2 c 1 ∂y 2 ,
0=c 2 b 2+a 21c 1+a 22c 2+d 2 ∂2 c 2 ∂x 2 + ∂2 c 2 ∂y 2 ,
with
a 11=a 22=-1, a 12=-0.5×10-6, and a 21=104, and b 1=1+αxy+β sin 4 πxsin 4 πy,
where α=50 and β=300, and b 2=-b 1.
The initial conditions are taken to be simple peaked functions which satisfy the boundary conditions and very nearly satisfy the PDEs:
c 1=10+16 x 1-x y 1-y 2,
c 2=b 2+a 21c 1,
and the boundary conditions are of Neumann type, i.e., zero normal derivatives everywhere.
During the solution a number of peaks and troughs develop across the domain, and so the number of levels required increases with time. Since the solution varies rapidly in space across the whole of the domain, refinement at intermediate levels tends to occur at all points of the domain.

10.1 Program Text

Program Text (d03rafe.f90)

10.2 Program Data

Program Data (d03rafe.d)

10.3 Program Results

Program Results (d03rafe.r)

GnuplotProduced by GNUPLOT 4.6 patchlevel 3 Example Program 1 Model for a Single, One-step Reaction of a Mixture of Two Chemicals U(x,y,t) gnuplot_plot_1 gnuplot_plot_2 t = 0.001 gnuplot_plot_3 t = 0.228 gnuplot_plot_4 t = 0.240 gnuplot_plot_5 t = 0.25 0 0.2 0.4 0.6 0.8 1 y 0 0.2 0.4 0.6 0.8 1 x 1 1.2 1.4 1.6 1.8 2
GnuplotProduced by GNUPLOT 4.6 patchlevel 3 Example Program 2 Multispecies Food Web Model Concentrations of Predator Predator Concentration gnuplot_plot_1 gnuplot_plot_2 t = 0.0005 gnuplot_plot_3 t = 0.0076 gnuplot_plot_4 t = 0.0173 gnuplot_plot_5 t = 0.025 0 0.2 0.4 0.6 0.8 1 y 0 0.2 0.4 0.6 0.8 1 x 0 20 40 60 80 100 120 140
GnuplotProduced by GNUPLOT 4.6 patchlevel 3 Multispecies Food Web Model Concentrations of Prey Prey Concentration gnuplot_plot_1 gnuplot_plot_2 t = 0.0005 gnuplot_plot_3 t = 0.0076 gnuplot_plot_4 t = 0.0173 gnuplot_plot_5 t = 0.025 0 0.2 0.4 0.6 0.8 1 y 0 0.2 0.4 0.6 0.8 1 x 0 200000 400000 600000 800000 1e+06 1.2e+06 1.4e+06
D03 Chapter Contents
D03 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


D03RBF : NAG Library, Mark 26

D03 Chapter Contents
D03 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

D03RBF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
▸▿ 9 Further Comments
9.1 Algorithm Outline
9.2 Refinement Strategy
9.3 Time Integration
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

D03RBF integrates a system of linear or nonlinear, time-dependent partial differential equations (PDEs) in two space dimensions on a rectilinear domain. The method of lines is employed to reduce the NPDEs to a system of ordinary differential equations (ODEs) which are solved using a backward differentiation formula (BDF) method. The resulting system of nonlinear equations is solved using a modified Newton method and a Bi-CGSTAB iterative linear solver with ILU preconditioning. Local uniform grid refinement is used to improve the accuracy of the solution. D03RBF originates from the VLUGR2 package (see Blom and Verwer (1993) and Blom et al. (1996)).

2 Specification

SUBROUTINE D03RBF ( NPDE, TS, TOUT, DT, TOLS, TOLT, INIDOM, PDEDEF, BNDARY, PDEIV, MONITR, OPTI, OPTR, RWK, LENRWK, IWK, LENIWK, LWK, LENLWK, ITRACE, IND, IFAIL)
INTEGER | NPDE, OPTI(4), LENRWK, IWK(LENIWK), LENIWK, LENLWK, ITRACE, IND, IFAIL
REAL (KIND=nag_wp) | TS, TOUT, DT(3), TOLS, TOLT, OPTR(3,NPDE), RWK(LENRWK)
LOGICAL | LWK(LENLWK)
EXTERNAL | INIDOM, PDEDEF, BNDARY, PDEIV, MONITR

3 Description

D03RBF integrates the system of PDEs:
Fj t,x,y,u,ut,ux,uy,u xx,u xy,u yy = 0 ,   j=1,2,…,NPDE ,   x,y ∈ Ω ,   t 0 ≤ t ≤ tout , (1)
where Ω is an arbitrary rectilinear domain, i.e., a domain bounded by perpendicular straight lines. If the domain is rectangular then it is recommended that D03RAF is used.
The vector u is the set of solution values
u x,y,t=u 1 x,y,t,…,uNPDE x,y,t T,
and ut denotes partial differentiation with respect to t, and similarly for ux, etc.
The functions Fj must be supplied by you in PDEDEF. Similarly the initial values of the functions u x,y,t for x,y∈Ω must be specified at t=t 0 in PDEIV.
Note that whilst complete generality is offered by the master equations (1), D03RBF is not appropriate for all PDEs. In particular, hyperbolic systems should not be solved using this routine. Also, at least one component of ut must appear in the system of PDEs.
The boundary conditions must be supplied by you in BNDARY in the form
Gj t,x,y,u,ut,ux,uy = 0 ,   j=1,2,…,NPDE ,   x,y∈∂Ω ,   t 0≤t≤tout . (2)
The domain is covered by a uniform coarse base grid specified by you, and nested finer uniform subgrids are subsequently created in regions with high spatial activity. The refinement is controlled using a space monitor which is computed from the current solution and a user-supplied space tolerance TOLS. A number of optional parameters, e.g., the maximum number of grid levels at any time, and some weighting factors, can be specified in the arrays OPTI and OPTR. Further details of the refinement strategy can be found in Section 9.
The system of PDEs and the boundary conditions are discretized in space on each grid using a standard second-order finite difference scheme (centred on the internal domain and one-sided at the boundaries), and the resulting system of ODEs is integrated in time using a second-order, two-step, implicit BDF method with variable step size. The time integration is controlled using a time monitor computed at each grid level from the current solution and a user-supplied time tolerance TOLT, and some further optional user-specified weighting factors held in OPTR (see Section 9 for details). The time monitor is used to compute a new step size, subject to restrictions on the size of the change between steps, and (optional) user-specified maximum and minimum step sizes held in DT. The step size is adjusted so that the remaining integration interval is an integer number times Δt. In this way a solution is obtained at t=tout.
A modified Newton method is used to solve the nonlinear equations arising from the time integration. You may specify (in OPTI) the maximum number of Newton iterations to be attempted. A Jacobian matrix is calculated at the beginning of each time step. If the Newton process diverges or the maximum number of iterations is exceeded, a new Jacobian is calculated using the most recent iterates and the Newton process is restarted. If convergence is not achieved after the (optional) user-specified maximum number of new Jacobian evaluations, the time step is retried with Δt=Δt/4. The linear systems arising from the Newton iteration are solved using a Bi-CGSTAB iterative method, in combination with ILU preconditioning. The maximum number of iterations can be specified by you in OPTI.
In order to define the base grid you must first specify a virtual uniform rectangular grid which contains the entire base grid. The position of the virtual grid in physical x,y space is given by the x,y coordinates of its boundaries. The number of points nx and ny in the x and y directions must also be given, corresponding to the number of columns and rows respectively. This is sufficient to determine precisely the x,y coordinates of all virtual grid points. Each virtual grid point is then referred to by integer coordinates vx,vy, where 0,0 corresponds to the lower-left corner and nx-1,ny-1 corresponds to the upper-right corner. vx and vy are also referred to as the virtual column and row indices respectively.
The base grid is then specified with respect to the virtual grid, with each base grid point coinciding with a virtual grid point. Each base grid point must be given an index, starting from 1, and incrementing row-wise from the leftmost point of the lowest row. Also, each base grid row must be numbered consecutively from the lowest row in the grid, so that row 1 contains grid point 1.
As an example, consider the domain consisting of the two separate squares shown in Figure 1. The left-hand diagram shows the virtual grid and its integer coordinates (i.e., its column and row indices), and the right-hand diagram shows the base grid point indices and the base row indices (in brackets).
Figure 1
Hence the base grid point with index 6 say is in base row 2, virtual column 4, and virtual row 1, i.e., virtual grid integer coordinates 4,1; and the base grid point with index 19 say is in base row 5, virtual column 2, and virtual row 5, i.e., virtual grid integer coordinates 2,5.
The base grid must then be defined in INIDOM by specifying the number of base grid rows, the number of base grid points, the number of boundaries, the number of boundary points, and the following integer arrays:
  • LROW contains the base grid indices of the starting points of the base grid rows;
  • IROW contains the virtual row numbers vy of the base grid rows;
  • ICOL contains the virtual column numbers vx of the base grid points;
  • LBND contains the grid indices of the boundary edges (without corners) and corner points;
  • LLBND contains the starting elements of the boundaries and corners in LBND.
Finally, ILBND contains the types of the boundaries and corners, as follows:
Boundaries:
  • 1 – lower boundary
  • 2 – left boundary
  • 3 – upper boundary
  • 4 – right boundary
External corners (90°):
  • 12 – lower-left corner
  • 23 – upper-left corner
  • 34 – upper-right corner
  • 41 – lower-right corner
Internal corners (270°):
  • 21 – lower-left corner
  • 32 – upper-left corner
  • 43 – upper-right corner
  • 14 – lower-right corner
Figure 2 shows the boundary types of a domain with a hole. Notice the logic behind the labelling of the corners: each one includes the types of the two adjacent boundary edges, in a clockwise fashion (outside the domain).
Figure 2
As an example, consider the domain shown in Figure 3. The left-hand diagram shows the physical domain and the right-hand diagram shows the base and virtual grids. The numbers outside the base grid are the indices of the left and rightmost base grid points, and the numbers inside the base grid are the boundary or corner numbers, indicating the order in which the boundaries are stored in LBND.
Figure 3
For this example we have
NROWS = 11
NPTS = 105
NBNDS = 28
NBPTS = 72

LROW = (1,4,15,26,37,46,57,68,79,88,97)

IROW = (0,1,2,3,4,5,6,7,8,9,10)

ICOL = (0,1,2,
        0,1,2,3,4,5,6,7,8,9,10,
        0,1,2,3,4,5,6,7,8,9,10,
        0,1,2,3,4,5,6,7,8,9,10,
        0,1,2,3,4,5,8,9,10,
        0,1,2,3,4,5,6,7,8,9,10,
        0,1,2,3,4,5,6,7,8,9,10,
        0,1,2,3,4,5,6,7,8,9,10,
        0,1,2,3,4,5,6,7,8,
        0,1,2,3,4,5,6,7,8,
        0,1,2,3,4,5,6,7,8)

LBND = (2,
        4,15,26,37,46,57,68,79,88,
        98,99,100,101,102,103,104,
        96,
        86,85,84,83,82,
        70,59,48,39,28,17,6,
        8,9,10,11,12,13,
        18,29,40,49,60,
        72,73,74,75,76,77,
        67,56,45,36,25,
        33,32,
        42,
        52,53,
        43,
        1,97,105,87,81,3,7,71,78,14,31,51,54,34)

LLBND = (1,2,11,18,19,24,31,37,42,48,53,55,56,58,59,60,
         61,62,63,64,65,66,67,68,69,70,71,72)

ILBND = (1,2,3,4,1,4,1,2,3,4,3,4,1,2,12,23,34,41,14,41,
         12,23,34,41,43,14,21,32)
This particular domain is used in the example in Section 10, and data statements are used to define the above arrays in that example program. For less complicated domains it is simpler to assign the values of the arrays in do-loops. This also allows flexibility in the number of base grid points.
The routine D03RYF can be called from INIDOM to obtain a simple graphical representation of the base grid, and to verify the data that you have specified in INIDOM.
Subgrids are stored internally using the same data structure, and solution information is communicated to you in PDEIV, PDEDEF and BNDARY in arrays according to the grid index on the particular level, e.g., X i and Y i contain the x,y coordinates of grid point i, and U ij contains the jth solution component uj at grid point i.
The grid data and the solutions at all grid levels are stored in the workspace arrays, along with other information needed for a restart (i.e., a continuation call). It is not intended that you extract the solution from these arrays, indeed the necessary information regarding these arrays is not provided. The user-supplied monitor (MONITR) should be used to obtain the solution at particular levels and times. MONITR is called at the end of every time step, with the last step being identified via the input argument TLAST. The routine D03RZF should be called from MONITR to obtain grid information at a particular level.
Further details of the underlying algorithm can be found in Section 9 and in Blom and Verwer (1993) and Blom et al. (1996) and the references therein.

4 References

Blom J G, Trompert R A and Verwer J G (1996) Algorithm 758. VLUGR2: A vectorizable adaptive grid solver for PDEs in 2D Trans. Math. Software 22 302–328
Blom J G and Verwer J G (1993) VLUGR2: A vectorized local uniform grid refinement code for PDEs in 2D Report NM-R9306 CWI, Amsterdam
Trompert R A (1993) Local uniform grid refinement and systems of coupled partial differential equations Appl. Numer. Maths 12 331–355
Trompert R A and Verwer J G (1993) Analysis of the implicit Euler local uniform grid refinement method SIAM J. Sci. Comput. 14 259–278

5 Arguments

1:   NPDE – INTEGERInput
On entry: the number of PDEs in the system.
Constraint: NPDE≥1.
2:   TS – REAL (KIND=nag_wp)Input/Output
On entry: the initial value of the independent variable t.
On exit: the value of t which has been reached. Normally TS=TOUT.
Constraint: TS<TOUT.
3:   TOUT – REAL (KIND=nag_wp)Input
On entry: the final value of t to which the integration is to be carried out.
4:   DT 3 – REAL (KIND=nag_wp) arrayInput/Output
On entry: the initial, minimum and maximum time step sizes respectively.
DT 1
Specifies the initial time step size to be used on the first entry, i.e., when IND=0. If DT 1=0.0 then the default value DT 1=0.01×TOUT-TS is used. On subsequent entries (IND=1), the value of DT 1 is not referenced.
DT 2
Specifies the minimum time step size to be attempted by the integrator. If DT 2=0.0 the default value DT 2=10.0×machine precision is used.
DT 3
Specifies the maximum time step size to be attempted by the integrator. If DT 3=0.0 the default value DT 3=TOUT-TS is used.
On exit: DT 1 contains the time step size for the next time step. DT 2 and DT 3 are unchanged or set to their default values if zero on entry.
Constraints:
  • if IND=0, DT 1≥0.0;
  • if IND=0 and DT 1>0.0, 10.0×machine precision×max TS,TOUT≤DT 1≤TOUT-TS and DT 2≤DT 1≤DT 3, where the values of DT 2 and DT 3 will have been reset to their default values if zero on entry;
  • 0≤ DT 2≤ DT 3 .
5:   TOLS – REAL (KIND=nag_wp)Input
On entry: the space tolerance used in the grid refinement strategy (σ in equation (4)). See Section 9.2.
Constraint: TOLS>0.0.
6:   TOLT – REAL (KIND=nag_wp)Input
On entry: the time tolerance used to determine the time step size (τ in equation (7)). See Section 9.3.
Constraint: TOLT>0.0.
7:   INIDOM – SUBROUTINE, supplied by the user.External Procedure
INIDOM must specify the base grid in terms of the data structure described in Section 3. INIDOM is not referenced if, on entry, IND=1. D03RYF can be called from INIDOM to obtain a simple graphical representation of the base grid, and to verify the data that you have specified in INIDOM. D03RBF also checks the validity of the data, but you are strongly advised to call D03RYF to ensure that the base grid is exactly as required.
Note: the boundaries of the base grid should consist of as many points as are necessary to employ second-order space discretization, i.e., a boundary enclosing the internal part of the domain must include at least 3 grid points including the corners. If Neumann boundary conditions are to be applied the minimum is 4.
The specification of INIDOM is:
SUBROUTINE INIDOM ( MAXPTS, XMIN, XMAX, YMIN, YMAX, NX, NY, NPTS, NROWS, NBNDS, NBPTS, LROW, IROW, ICOL, LLBND, ILBND, LBND, IERR)
INTEGER | MAXPTS, NX, NY, NPTS, NROWS, NBNDS, NBPTS, LROW(*), IROW(*), ICOL(*), LLBND(*), ILBND(*), LBND(*), IERR
REAL (KIND=nag_wp) | XMIN, XMAX, YMIN, YMAX
1:   MAXPTS – INTEGERInput
On entry: the maximum number of base grid points allowed by the available workspace.
2:   XMIN – REAL (KIND=nag_wp)Output
3:   XMAX – REAL (KIND=nag_wp)Output
On exit: the extents of the virtual grid in the x-direction, i.e., the x coordinates of the left and right boundaries respectively.
Constraint: XMIN<XMAX and XMAX must be sufficiently distinguishable from XMIN for the precision of the machine being used.
4:   YMIN – REAL (KIND=nag_wp)Output
5:   YMAX – REAL (KIND=nag_wp)Output
On exit: the extents of the virtual grid in the y-direction, i.e., the y coordinates of the left and right boundaries respectively.
Constraint: YMIN<YMAX and YMAX must be sufficiently distinguishable from YMIN for the precision of the machine being used.
6:   NX – INTEGEROutput
7:   NY – INTEGEROutput
On exit: the number of virtual grid points in the x- and y-direction respectively (including the boundary points).
Constraint: NX and NY≥4.
8:   NPTS – INTEGEROutput
On exit: the total number of points in the base grid. If the required number of points is greater than MAXPTS then INIDOM must be exited immediately with IERR set to -1 to avoid overwriting memory.
Constraint: NPTS≤NX×NY and if IERR≠-1 on exit, NPTS≤MAXPTS.
9:   NROWS – INTEGEROutput
On exit: the total number of rows of the virtual grid that contain base grid points. This is the maximum base row index.
Constraint: 4≤NROWS≤NY.
10:   NBNDS – INTEGEROutput
On exit: the total number of physical boundaries and corners in the base grid.
Constraint: NBNDS≥8.
11:   NBPTS – INTEGEROutput
On exit: the total number of boundary points in the base grid.
Constraint: 12≤NBPTS<NPTS.
12:   LROW* – INTEGER arrayOutput
On exit: LROW i, for i=1,2,…,NROWS, must contain the base grid index of the first grid point in base grid row i.
Constraints:
  • 1≤LROW i≤NPTS, for i=1,2,…,NROWS;
  • LROW i-1<LROW i, for i=2,3,…,NROWS.
13:   IROW* – INTEGER arrayOutput
On exit: IROW i, for i=1,2,…,NROWS, must contain the virtual row number vy that corresponds to base grid row i.
Constraints:
  • 0≤IROW i≤NY, for i=1,2,…,NROWS;
  • IROW i-1<IROW i, for i=2,3,…,NROWS.
14:   ICOL* – INTEGER arrayOutput
On exit: ICOL i, for i=1,2,…,NPTS, must contain the virtual column number vx that contains base grid point i.
Constraint: 0≤ICOL i≤NX, for i=1,2,…,NPTS.
15:   LLBND* – INTEGER arrayOutput
On exit: LLBND i, for i=1,2,…,NBNDS, must contain the element of LBND corresponding to the start of the ith boundary or corner.
Note: the order of the boundaries and corners in LLBND must be first all the boundaries and then all the corners. The end points of a boundary (i.e., the adjacent corner points) must not be included in the list of points on that boundary. Also, if a corner is shared by two pairs of physical boundaries then it has two types and must therefore be treated as two corners.
Constraints:
  • 1≤LLBND i≤NBPTS, for i=1,2,…,NBNDS;
  • LLBND i-1<LLBND i, for i=2,3,…,NBNDS.
16:   ILBND* – INTEGER arrayOutput
On exit: ILBND i, for i=1,2,…,NBNDS, must contain the type of the ith boundary (or corner), as given in Section 3.
Constraint: ILBND i must be equal to one of the following: 1, 2, 3, 4, 12, 23, 34, 41, 21, 32, 43 or 14, for i=1,2,…,NBNDS.
17:   LBND* – INTEGER arrayOutput
On exit: LBND i, for i=1,2,…,NBPTS, must contain the grid index of the ith boundary point. The order of the boundaries is as specified in LLBND, but within this restriction the order of the points in LBND is arbitrary.
Constraint: 1≤LBND i≤NPTS, for i=1,2,…,NBPTS.
18:   IERR – INTEGERInput/Output
On entry: will be initialized by D03RBF to some value prior to internal calls to INIDOM.
On exit: if the required number of grid points is larger than MAXPTS, IERR must be set to -1 to force a termination of the integration and an immediate return to the calling program with IFAIL=3. Otherwise, IERR should remain unchanged.
INIDOM must either be a module subprogram USEd by, or declared as EXTERNAL in, the (sub)program from which D03RBF is called. Arguments denoted as Input must not be changed by this procedure.
8:   PDEDEF – SUBROUTINE, supplied by the user.External Procedure
PDEDEF must evaluate the functions Fj, for j=1,2,…,NPDE, in equation (1) which define the system of PDEs (i.e., the residuals of the resulting ODE system) at all interior points of the domain. Values at points on the boundaries of the domain are ignored and will be overwritten by BNDARY. PDEDEF is called for each subgrid in turn.
The specification of PDEDEF is:
SUBROUTINE PDEDEF ( NPTS, NPDE, T, X, Y, U, UT, UX, UY, UXX, UXY, UYY, RES)
INTEGER | NPTS, NPDE
REAL (KIND=nag_wp) | T, X(NPTS), Y(NPTS), U(NPTS,NPDE), UT(NPTS,NPDE), UX(NPTS,NPDE), UY(NPTS,NPDE), UXX(NPTS,NPDE), UXY(NPTS,NPDE), UYY(NPTS,NPDE), RES(NPTS,NPDE)
1:   NPTS – INTEGERInput
On entry: the number of grid points in the current grid.
2:   NPDE – INTEGERInput
On entry: the number of PDEs in the system.
3:   T – REAL (KIND=nag_wp)Input
On entry: the current value of the independent variable t.
4:   X NPTS – REAL (KIND=nag_wp) arrayInput
On entry: X i contains the x coordinate of the ith grid point, for i=1,2,…,NPTS.
5:   Y NPTS – REAL (KIND=nag_wp) arrayInput
On entry: Y i contains the y coordinate of the ith grid point, for i=1,2,…,NPTS.
6:   U NPTSNPDE – REAL (KIND=nag_wp) arrayInput
On entry: U ij contains the value of the jth PDE component at the ith grid point, for i=1,2,…,NPTS and j=1,2,…,NPDE.
7:   UT NPTSNPDE – REAL (KIND=nag_wp) arrayInput
On entry: UT ij contains the value of ∂u ∂t for the jth PDE component at the ith grid point, for i=1,2,…,NPTS and j=1,2,…,NPDE.
8:   UX NPTSNPDE – REAL (KIND=nag_wp) arrayInput
On entry: UX ij contains the value of ∂u ∂x for the jth PDE component at the ith grid point, for i=1,2,…,NPTS and j=1,2,…,NPDE.
9:   UY NPTSNPDE – REAL (KIND=nag_wp) arrayInput
On entry: UY ij contains the value of ∂u ∂y for the jth PDE component at the ith grid point, for i=1,2,…,NPTS and j=1,2,…,NPDE.
10:   UXX NPTSNPDE – REAL (KIND=nag_wp) arrayInput
On entry: UXX ij contains the value of ∂2 u ∂x 2 for the jth PDE component at the ith grid point, for i=1,2,…,NPTS and j=1,2,…,NPDE.
11:   UXY NPTSNPDE – REAL (KIND=nag_wp) arrayInput
On entry: UXY ij contains the value of ∂2 u ∂x∂y for the jth PDE component at the ith grid point, for i=1,2,…,NPTS and j=1,2,…,NPDE.
12:   UYY NPTSNPDE – REAL (KIND=nag_wp) arrayInput
On entry: UYY ij contains the value of ∂2 u ∂y 2 for the jth PDE component at the ith grid point, for i=1,2,…,NPTS and j=1,2,…,NPDE.
13:   RES NPTSNPDE – REAL (KIND=nag_wp) arrayOutput
On exit: RES ij must contain the value of Fj, for j=1,2,…,NPDE, at the ith grid point, for i=1,2,…,NPTS, although the residuals at boundary points will be ignored (and overwritten later on) and so they need not be specified here.
PDEDEF must either be a module subprogram USEd by, or declared as EXTERNAL in, the (sub)program from which D03RBF is called. Arguments denoted as Input must not be changed by this procedure.
9:   BNDARY – SUBROUTINE, supplied by the user.External Procedure
BNDARY must evaluate the functions Gj, for j=1,2,…,NPDE, in equation (2) which define the boundary conditions at all boundary points of the domain. Residuals at interior points must not be altered by this subroutine.
The specification of BNDARY is:
SUBROUTINE BNDARY ( NPTS, NPDE, T, X, Y, U, UT, UX, UY, NBNDS, NBPTS, LLBND, ILBND, LBND, RES)
INTEGER | NPTS, NPDE, NBNDS, NBPTS, LLBND(NBNDS), ILBND(NBNDS), LBND(NBPTS)
REAL (KIND=nag_wp) | T, X(NPTS), Y(NPTS), U(NPTS,NPDE), UT(NPTS,NPDE), UX(NPTS,NPDE), UY(NPTS,NPDE), RES(NPTS,NPDE)
1:   NPTS – INTEGERInput
On entry: the number of grid points in the current grid.
2:   NPDE – INTEGERInput
On entry: the number of PDEs in the system.
3:   T – REAL (KIND=nag_wp)Input
On entry: the current value of the independent variable t.
4:   X NPTS – REAL (KIND=nag_wp) arrayInput
On entry: X i contains the x coordinate of the ith grid point, for i=1,2,…,NPTS.
5:   Y NPTS – REAL (KIND=nag_wp) arrayInput
On entry: Y i contains the y coordinate of the ith grid point, for i=1,2,…,NPTS.
6:   U NPTSNPDE – REAL (KIND=nag_wp) arrayInput
On entry: U ij contains the value of the jth PDE component at the ith grid point, for i=1,2,…,NPTS and j=1,2,…,NPDE.
7:   UT NPTSNPDE – REAL (KIND=nag_wp) arrayInput
On entry: UT ij contains the value of ∂u ∂t for the jth PDE component at the ith grid point, for i=1,2,…,NPTS and j=1,2,…,NPDE.
8:   UX NPTSNPDE – REAL (KIND=nag_wp) arrayInput
On entry: UX ij contains the value of ∂u ∂x for the jth PDE component at the ith grid point, for i=1,2,…,NPTS and j=1,2,…,NPDE.
9:   UY NPTSNPDE – REAL (KIND=nag_wp) arrayInput
On entry: UY ij contains the value of ∂u ∂y for the jth PDE component at the ith grid point, for i=1,2,…,NPTS and j=1,2,…,NPDE.
10:   NBNDS – INTEGERInput
On entry: the total number of physical boundaries and corners in the grid.
11:   NBPTS – INTEGERInput
On entry: the total number of boundary points in the grid.
12:   LLBND NBNDS – INTEGER arrayInput
On entry: LLBND i, for i=1,2,…,NBNDS, contains the element of LBND corresponding to the start of the ith boundary (or corner).
13:   ILBND NBNDS – INTEGER arrayInput
On entry: ILBND i, for i=1,2,…,NBNDS, contains the type of the ith boundary, as given in Section 3.
14:   LBND NBPTS – INTEGER arrayInput
On entry: LBND i, contains the grid index of the ith boundary point, where the order of the boundaries is as specified in LLBND. Hence the ith boundary point has coordinates X LBND i and Y LBND i, and the corresponding solution values are U LBND i j, for i=1,2,…,NBPTS and j=1,2,…,NPDE.
15:   RES NPTSNPDE – REAL (KIND=nag_wp) arrayInput/Output
On entry: contains function values returned by PDEDEF.
On exit: RES LBND i j must contain the value of Gj, for j=1,2,…,NPDE, at the ith boundary point, for i=1,2,…,NBPTS.
Note: elements of RES corresponding to interior points, i.e., points not included in LBND, must not be altered.
BNDARY must either be a module subprogram USEd by, or declared as EXTERNAL in, the (sub)program from which D03RBF is called. Arguments denoted as Input must not be changed by this procedure.
10:   PDEIV – SUBROUTINE, supplied by the user.External Procedure
PDEIV must specify the initial values of the PDE components u at all points in the base grid. PDEIV is not referenced if, on entry, IND=1.
The specification of PDEIV is:
SUBROUTINE PDEIV ( NPTS, NPDE, T, X, Y, U)
INTEGER | NPTS, NPDE
REAL (KIND=nag_wp) | T, X(NPTS), Y(NPTS), U(NPTS,NPDE)
1:   NPTS – INTEGERInput
On entry: the number of grid points in the base grid.
2:   NPDE – INTEGERInput
On entry: the number of PDEs in the system.
3:   T – REAL (KIND=nag_wp)Input
On entry: the (initial) value of the independent variable t.
4:   X NPTS – REAL (KIND=nag_wp) arrayInput
On entry: X i contains the x coordinate of the ith grid point, for i=1,2,…,NPTS.
5:   Y NPTS – REAL (KIND=nag_wp) arrayInput
On entry: Y i contains the y coordinate of the ith grid point, for i=1,2,…,NPTS.
6:   U NPTSNPDE – REAL (KIND=nag_wp) arrayOutput
On exit: U ij must contain the value of the jth PDE component at the ith grid point, for i=1,2,…,NPTS and j=1,2,…,NPDE.
PDEIV must either be a module subprogram USEd by, or declared as EXTERNAL in, the (sub)program from which D03RBF is called. Arguments denoted as Input must not be changed by this procedure.
11:   MONITR – SUBROUTINE, supplied by the user.External Procedure
MONITR is called by D03RBF at the end of every successful time step, and may be used to examine or print the solution or perform other tasks such as error calculations, particularly at the final time step, indicated by the argument TLAST.
The input arguments contain information about the grid and solution at all grid levels used. D03RZF should be called from MONITR in order to extract the number of points and their x,y coordinates on a particular grid.
MONITR can also be used to force an immediate tidy termination of the solution process and return to the calling program.
The specification of MONITR is:
SUBROUTINE MONITR ( NPDE, T, DT, DTNEW, TLAST, NLEV, XMIN, YMIN, DXB, DYB, LGRID, ISTRUC, LSOL, SOL, IERR)
INTEGER | NPDE, NLEV, LGRID(*), ISTRUC(*), LSOL(NLEV), IERR
REAL (KIND=nag_wp) | T, DT, DTNEW, XMIN, YMIN, DXB, DYB, SOL(*)
LOGICAL | TLAST
1:   NPDE – INTEGERInput
On entry: the number of PDEs in the system.
2:   T – REAL (KIND=nag_wp)Input
On entry: the current value of the independent variable t, i.e., the time at the end of the integration step just completed.
3:   DT – REAL (KIND=nag_wp)Input
On entry: the current time step size Δt, i.e., the time step size used for the integration step just completed.
4:   DTNEW – REAL (KIND=nag_wp)Input
On entry: the time step size that will be used for the next time step.
5:   TLAST – LOGICALInput
On entry: indicates if intermediate or final time step. TLAST=.FALSE. for an intermediate step, TLAST=.TRUE. for the last call to MONITR before returning to your program.
6:   NLEV – INTEGERInput
On entry: the number of grid levels used at time T.
7:   XMIN – REAL (KIND=nag_wp)Input
8:   YMIN – REAL (KIND=nag_wp)Input
On entry: the x,y coordinates of the lower-left corner of the virtual grid.
9:   DXB – REAL (KIND=nag_wp)Input
10:   DYB – REAL (KIND=nag_wp)Input
On entry: the sizes of the base grid spacing in the x- and y-direction respectively.
11:   LGRID* – INTEGER arrayInput
On entry: contains pointers to the start of the grid structures in ISTRUC, and must be passed unchanged to D03RZF in order to extract the grid information.
12:   ISTRUC* – INTEGER arrayInput
On entry: contains the grid structures for each grid level and must be passed unchanged to D03RZF in order to extract the grid information.
13:   LSOL NLEV – INTEGER arrayInput
On entry: LSOL l contains the pointer to the solution in SOL at grid level l and time T. (LSOL l actually contains the array index immediately preceding the start of the solution in SOL.)
14:   SOL* – REAL (KIND=nag_wp) arrayInput
On entry: contains the solution u at time T for each grid level l in turn, positioned according to LSOL. More precisely
U ij= SOL LSOL l+ j-1 × nl+i
represents the jth component of the solution at the ith grid point in the lth level, for i=1,2,…,nl, j=1,2,…,NPDE and l=1,2,…,NLEV, where nl is the number of grid points at level l (obtainable by a call to D03RZF).
15:   IERR – INTEGERInput/Output
On entry: will be initialized by D03RBF to some value prior to internal calls to IERR.
On exit: should be set to 1 to force a termination of the integration and an immediate return to the calling program with IFAIL=4. IERR should remain unchanged otherwise.
MONITR must either be a module subprogram USEd by, or declared as EXTERNAL in, the (sub)program from which D03RBF is called. Arguments denoted as Input must not be changed by this procedure.
12:   OPTI 4 – INTEGER arrayInput
On entry: may be set to control various options available in the integrator.
OPTI 1=0
All the default options are employed.
OPTI 1>0
The default value of OPTI i, for i=2,3,4, can be obtained by setting OPTI i=0.
OPTI 1
Specifies the maximum number of grid levels allowed (including the base grid). OPTI 1≥0. The default value is OPTI 1=3.
OPTI 2
Specifies the maximum number of Jacobian evaluations allowed during each nonlinear equations solution. OPTI 2≥0. The default value is OPTI 2=2.
OPTI 3
Specifies the maximum number of Newton iterations in each nonlinear equations solution. OPTI 3≥0. The default value is OPTI 3=10.
OPTI 4
Specifies the maximum number of iterations in each linear equations solution. OPTI 4≥0. The default value is OPTI 4=100.
Constraint: OPTI 1≥0 and if OPTI 1>0, OPTI i≥0, for i=2,3,4.
13:   OPTR 3 NPDE – REAL (KIND=nag_wp) arrayInput
On entry: may be used to specify the optional vectors umax, ws and wt in the space and time monitors (see Section 9).
If an optional vector is not required then all its components should be set to 1.0.
OPTR 1 j, for j=1,2,…,NPDE, specifies ujmax, the approximate maximum absolute value of the jth component of u, as used in (4) and (7). OPTR 1 j>0.0, for j=1,2,…,NPDE.
OPTR 2 j, for j=1,2,…,NPDE, specifies wjs, the weighting factors used in the space monitor (see (4)) to indicate the relative importance of the jth component of u on the space monitor. OPTR 2 j≥0.0, for j=1,2,…,NPDE.
OPTR 3 j, for j=1,2,…,NPDE, specifies wjt, the weighting factors used in the time monitor (see (6)) to indicate the relative importance of the jth component of u on the time monitor. OPTR 3 j≥0.0, for j=1,2,…,NPDE.
Constraints:
  • OPTR 1 j>0.0, for j=1,2,…,NPDE;
  • OPTR ij≥0.0, for i=2,3 and j=1,2,…,NPDE.
14:   RWK LENRWK – REAL (KIND=nag_wp) arrayCommunication Array
15:   LENRWK – INTEGERInput
On entry: the dimension of the array RWK as declared in the (sub)program from which D03RBF is called.
The required value of LENRWK cannot be determined exactly in advance, but a suggested value is
LENRWK=maxpts×NPDE×5×l+18×NPDE+9+2×maxpts,
where l=OPTI 1 if OPTI 1≠0 and l=3 otherwise, and maxpts is the expected maximum number of grid points at any one level. If during the execution the supplied value is found to be too small then the routine returns with IFAIL=3 and an estimated required size is printed on the current error message unit (see X04AAF).
Note: the size of LENRWK cannot be checked upon initial entry to D03RBF since the number of grid points on the base grid is not known.
16:   IWK LENIWK – INTEGER arrayCommunication Array
On entry: if IND=0, IWK need not be set. Otherwise IWK must remain unchanged from a previous call to D03RBF.
On exit: the following components of the array IWK concern the efficiency of the integration. Here, m is the maximum number of grid levels allowed (m=OPTI 1 if OPTI 1>1 and m=3 otherwise), and l is a grid level taking the values l=1,2,…,nl, where nl is the number of levels used.
IWK 1
Contains the number of steps taken in time.
IWK 2
Contains the number of rejected time steps.
IWK 2+l
Contains the total number of residual evaluations performed (i.e., the number of times PDEDEF was called) at grid level l.
IWK 2+m+l
Contains the total number of Jacobian evaluations performed at grid level l.
IWK 2+2×m+l
Contains the total number of Newton iterations performed at grid level l.
IWK 2+3×m+l
Contains the total number of linear solver iterations performed at grid level l.
IWK 2+4×m+l
Contains the maximum number of Newton iterations performed at any one time step at grid level l.
IWK 2+5×m+l
Contains the maximum number of linear solver iterations performed at any one time step at grid level l.
Note: the total and maximum numbers are cumulative over all calls to D03RBF. If the specified maximum number of Newton or linear solver iterations is exceeded at any stage, then the maximums above are set to the specified maximum plus one.
17:   LENIWK – INTEGERInput
On entry: the dimension of the array IWK as declared in the (sub)program from which D03RBF is called.
The required value of LENIWK cannot be determined exactly in advance, but a suggested value is
LENIWK=maxpts×14+5×m+7×m+2,
where maxpts is the expected maximum number of grid points at any one level and m=OPTI 1 if OPTI 1>0 and m=3 otherwise. If during the execution the supplied value is found to be too small then the routine returns with IFAIL=3 and an estimated required size is printed on the current error message unit (see X04AAF).
Note: the size of LENIWK cannot be checked upon initial entry to D03RBF since the number of grid points on the base grid is not known.
18:   LWK LENLWK – LOGICAL arrayWorkspace
19:   LENLWK – INTEGERInput
On entry: the dimension of the array LWK as declared in the (sub)program from which D03RBF is called.
The required value of LENLWK cannot be determined exactly in advance, but a suggested value is
LENLWK=maxpts+1,
where maxpts is the expected maximum number of grid points at any one level. If during the execution the supplied value is found to be too small then the routine returns with IFAIL=3 and an estimated required size is printed on the current error message unit (see X04AAF).
Note: the size of LENLWK cannot be checked upon initial entry to D03RBF since the number of grid points on the base grid is not known.
20:   ITRACE – INTEGERInput
On entry: the level of trace information required from D03RBF. ITRACE may take the value -1, 0, 1, 2 or 3.
ITRACE=-1
No output is generated.
ITRACE=0
Only warning messages are printed.
ITRACE>0
Output from the underlying solver is printed on the current advisory message unit (see X04ABF). This output contains details of the time integration, the nonlinear iteration and the linear solver.
If ITRACE<-1, then -1 is assumed and similarly if ITRACE>3, then 3 is assumed.
The advisory messages are given in greater detail as ITRACE increases. Setting ITRACE=1 allows you to monitor the progress of the integration without possibly excessive information.
21:   IND – INTEGERInput/Output
On entry: must be set to 0 or 1, alternatively 10 or 11.
IND=0
Starts the integration in time. PDEDEF is assumed to be serial.
IND=1
Continues the integration after an earlier exit from the routine. In this case, only the following parameters may be reset between calls to D03RBF: TOUT, DT, TOLS, TOLT, OPTI, OPTR, ITRACE and IFAIL. PDEDEF is assumed to be serial.
IND=10
Starts the integration in time. PDEDEF is assumed to have been parallelized by you, as described in Section 8. In all other respects, this is equivalent to IND=0.
IND=11
Continues the integration after an earlier exit from the routine. In this case, only the following parameters may be reset between calls to D03RAF: TOUT, DT, TOLS, TOLT, OPTI, OPTR, ITRACE and IFAIL. PDEDEF is assumed to have been parallelized by you, as described in Section 8. In all other respects, this is equivalent to IND=1.
Constraint: 0≤IND≤1 or 10≤IND≤11.
On exit: IND=1, if IND on input was 0 or 1, or IND=11, if IND on input was 10 or 11.
Note: for users of serial versions of the NAG Library, it is recommended that you only use IND=0 or 1. See Section 8 for more information on the use of IND.
22:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, | NPDE<1,
or | TOUT≤TS,
or | TOUT is too close to TS,
or | IND=0 and DT 1<0.0,
or | DT i<0.0, for i=2​ or ​3,
or | DT 2>DT 3,
or | IND=0 and 0.0<DT 1<10×machine precision×max TS,TOUT,
or | IND=0 and DT 1>TOUT-TS,
or | IND=0 and DT 1<DT 2​ or ​DT 1>DT 3,
or | TOLS or TOLT≤0.0,
or | OPTI 1<0,
or | OPTI 1>0 and OPTI j<0, for j=2, 3 or 4,
or | OPTR 1 j≤0.0, for some j=1,2,…,NPDE,
or | OPTR 2 j<0.0, for some j=1,2,…,NPDE,
or | OPTR 3 j<0.0, for some j=1,2,…,NPDE,
or | IND≠0 or 1,
or | IND=1 on initial entry to D03RBF.
IFAIL=2
The time step size to be attempted is less than the specified minimum size. This may occur following time step failures and subsequent step size reductions caused by one or more of the following:
  • the requested accuracy could not be achieved, i.e., TOLT is too small,
  • the maximum number of linear solver iterations, Newton iterations or Jacobian evaluations is too small,
  • ILU decomposition of the Jacobian matrix could not be performed, possibly due to singularity of the Jacobian.
Setting ITRACE to a higher value may provide further information.
In the latter two cases you are advised to check their problem formulation in PDEDEF and/or BNDARY, and the initial values in PDEIV if appropriate.
IFAIL=3
One or more of the workspace arrays is too small for the required number of grid points. At the initial time step this error may result because you set IERR to -1 in INIDOM or the internal check on the number of grid points following the call to INIDOM. An estimate of the required sizes for the current stage is output, but more space may be required at a later stage.
IFAIL=4
IERR was set to 1 in MONITR, forcing control to be passed back to calling program. Integration was successful as far as T=TS.
IFAIL=5
The integration has been completed but the maximum number of levels specified in OPTI 1 was insufficient at one or more time steps, meaning that the requested space accuracy could not be achieved. To avoid this warning either increase the value of OPTI 1 or decrease the value of TOLS.
IFAIL=6
One or more of the output arguments of INIDOM was incorrectly specified, i.e.,
XMIN≥XMAX,
or | XMAX too close to XMIN,
or | YMIN≥YMAX,
or | YMAX too close to YMIN,
or | NX or NY<4,
or | NROWS<4,
or | NROWS>NY,
or | NPTS>NX×NY,
or | NBNDS<8,
or | NBPTS<12,
or | NBPTS≥NPTS,
or | LROW i<1 or LROW i>NPTS, for some i=1,2,…,NROWS,
or | LROW i≤LROW i-1, for some i=2,3,…,NROWS,
or | IROW i<0 or IROW i>NY, for some i=1,2,…,NROWS,
or | IROW i≤IROW i-1, for some i=2,3,…,NROWS,
or | ICOL i<0 or ICOL i>NX, for some i=1,2,…,NPTS,
or | LLBND i<1 or LLBND i>NBPTS, for some i=1,2,…,NBNDS,
or | LLBND i≤LLBND i-1, for some i=2,3,…,NBNDS,
or | ILBND i≠1, 2, 3, 4, 12, 23, 34, 41, 21, 32, 43 or 14, for some i=1,2,…,NBNDS,
or | LBND i<1 or LBND i>NPTS, for some i=1,2,…,NBPTS.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

There are three sources of error in the algorithm: space and time discretization, and interpolation (linear) between grid levels. The space and time discretization errors are controlled separately using the arguments TOLS and TOLT described in Section 9, and you should test the effects of varying these arguments. Interpolation errors are generally implicitly controlled by the refinement criterion since in areas where interpolation errors are potentially large, the space monitor will also be large. It can be shown that the global spatial accuracy is comparable to that which would be obtained on a uniform grid of the finest grid size. A full error analysis can be found in Trompert and Verwer (1993).

8 Parallelism and Performance

D03RBF requires a user-supplied routine PDEDEF to evaluate the functions Fj, for j=1,2,…,NPDE. The parallelism within D03RBF will be more efficient if PDEDEF can also be parallelized. This is often the case, but you must add some OpenMP directives to your version of PDEDEF to implement the parallelism. For example, if the body of code for PDEDEF is as follows (adapted from the first test case in the document for D03RBF):
res(1:npts,1:npde) = ut(1:npts,1:npde) - diffusion*(uxx(1:npts,1:         &
  npde)+uyy(1:npts,1:npde)) - damkohler*(one+heat_release-u(1:npts,       &
  1:npde))*exp(-activ_energy/u(1:npts,1:npde))
This example can be parallelized, as the updating of RES for each value in the range 1,…,NPTS is independent of every other value. Thus this should be parallelized in OpenMP (using an explicit loop rather than Fortran array syntax) as follows:
!$OMP DO
   Do i = 1, npts
      res(i,1:npde) = ut(i,1:npde) -diffusion*(uxx(i,1:npde)+uyy(i,1:npde &
       )) - damkohler*(1.0E0_nag_wp+heat_release-u(i,1:npde))*exp(-       &
        activ_energy/u(i,1:npde))
   End Do
!$OMP END DO
Note that the OpenMP PARALLEL directive must not be specified, as the OpenMP DO directive will bind to the PARALLEL region within the D03RBF code. Also note that this assumes the default OpenMP behaviour that all variables are SHARED, except for loop indices that are PRIVATE.
To avoid problems for existing library users, who will not have specified any OpenMP directives in their PDEDEF routine, the default assumption of D03RBF is that PDEDEF has not been parallelized, and executes calls to PDEDEF in serial mode. You must indicate that PDEDEF has been parallelized by setting IND to 10 or 11 as appropriate. See Section 5 for details.
If the code within PDEDEF cannot be parallelized, you must not add any OpenMP directives to your code, and must not set IND to 10 or 11. If IND is set to 10 or 11 and PDEDEF has not been parallelized, results on multiple threads will be unpredictable and may give rise to incorrect results and/or program crashes or deadlocks. Please contact NAG for advice if required. Overloading IND in this manner is not entirely satisfactory, consequently it is likely that replacement interfaces for D03RBF will be included in a future NAG Library release.

9 Further Comments

9.1 Algorithm Outline

The local uniform grid refinement method is summarised as follows.
1. | Initialize the course base grid, an initial solution and an initial time step.
2. | Solve the system of PDEs on the current grid with the current time step.
3. If the required accuracy in space and the maximum number of grid levels have not yet been reached:
(a) | Determine new finer grid at forward time level.
(b) | Get solution values at previous time level(s) on new grid.
(c) | Interpolate internal boundary values from old grid at forward time.
(d) | Get initial values for the Newton process at forward time.
(e) | Go to 2.
4. | Update the coarser grid solution using the finer grid values.
5. | Estimate error in time integration. If time error is acceptable advance time level.
6. | Determine new step size then go to 2 with coarse base as current grid.

9.2 Refinement Strategy

For each grid point i a space monitor μis is determined by
μ i s = max j = 1 , NPDE γ j Δ x 2 ∂ 2 ∂ x 2 u j x i , y i ,t + Δ y 2 ∂ 2 ∂ y 2 uj x i , y i ,t , (3)
where Δx and Δy are the grid widths in the x and y directions; and xi, yi are the x,y coordinates at grid point i. The argument γj is obtained from
γj=wjs ujmax σ , (4)
where σ is the user-supplied space tolerance; wjs is a weighting factor for the relative importance of the jth PDE component on the space monitor; and ujmax is the approximate maximum absolute value of the jth component. A value for σ must be supplied by you. Values for wjs and ujmax must also be supplied but may be set to the values 1.0 if little information about the solution is known.
A new level of refinement is created if
maxi μis>0.9  or   1.0, (5)
depending on the grid level at the previous step in order to avoid fluctuations in the number of grid levels between time steps. If (5) is satisfied then all grid points for which μis>0.25 are flagged and surrounding cells are quartered in size.
No derefinement takes place as such, since at each time step the solution on the base grid is computed first and new finer grids are then created based on the new solution. Hence derefinement occurs implicitly. See Section 9.1.

9.3 Time Integration

The time integration is controlled using a time monitor calculated at each level l up to the maximum level used, given by
μ l t = 1 N ∑ j = 1 NPDE w j t ∑ i = 1 ngpts l Δ t α i j u t x i , y i ,t 2 (6)
where ngpts l is the total number of points on grid level l; N=ngpts l×NPDE; Δt is the current time step; ut is the time derivative of u which is approximated by first-order finite differences; wjt is the time equivalent of the space weighting factor wjs; and α ij is given by
α i j = τ u j max 100 + u x i , y i ,t (7)
where ujmax is as before, and τ is the user-specified time tolerance.
An integration step is rejected and retried at all levels if
maxl μlt>1.0. (8)

10 Example

This example is taken from Blom and Verwer (1993) and is the two-dimensional Burgers' system
∂u ∂t =-u ∂u ∂x -v ∂u ∂y +ε ∂2 u ∂x 2 + ∂2 u ∂y 2 ,
∂v ∂t =-u ∂v ∂x -v ∂v ∂y +ε ∂2 v ∂x 2 + ∂2 v ∂y 2 ,
with ε=10-3 on the domain given in Figure 3. Dirichlet boundary conditions are used on all boundaries using the exact solution
u=34-1 4 1+exp-4 x+4 y-t/32 ε ,
v = 3 4 + 1 4 1 + exp - 4 x + 4 y - t / 32 ε .
The solution contains a wave front at y=x+0.25 t which propagates in a direction perpendicular to the front with speed 2/8.

10.1 Program Text

Program Text (d03rbfe.f90)

10.2 Program Data

Program Data (d03rbfe.d)

10.3 Program Results

Program Results (d03rbfe.r)

D03 Chapter Contents
D03 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


D03RYF : NAG Library, Mark 26

D03 Chapter Contents
D03 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

D03RYF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
10 Example

1 Purpose

D03RYF is designed to be used in conjunction with D03RBF. It can be called from the INIDOM to check the user-specified initial grid data and to obtain a simple graphical representation of the initial grid.

2 Specification

SUBROUTINE D03RYF ( NX, NY, NPTS, NROWS, NBNDS, NBPTS, LROW, IROW, ICOL, LLBND, ILBND, LBND, IWK, LENIWK, PGRID, IFAIL)
INTEGER | NX, NY, NPTS, NROWS, NBNDS, NBPTS, LROW(NROWS), IROW(NROWS), ICOL(NPTS), LLBND(NBNDS), ILBND(NBNDS), LBND(NBPTS), IWK(LENIWK), LENIWK, IFAIL
CHARACTER(*) | PGRID(NY)

3 Description

D03RYF outputs a character array which can be printed to provide a simple graphical representation of the virtual and base grids supplied to D03RBF. It must be called only from within the INIDOM after all output arguments of INIDOM (other than IERR) have been set. D03RYF also checks the validity of the grid data specified in INIDOM.
You are strongly advised to call D03RYF during the initial call of D03RBF (at least) and to print the resulting character array in order to check that the base grid is exactly as required.
D03RYF writes a representation of each point in the virtual and base grids to the character array PGRID as follows:
– | internal base grid points are written as two dots (..);
– | boundary base grid points are written as the ILBND value (i.e., the type) of the boundary;
– | points external to the base grid are written as XX.
As an example, consider a rectangular domain with a rectangular hole in which the virtual domain extends by one base grid point beyond the actual domain in all directions. The output when each row of PGRID is printed consecutively is as follows:
 XX XX XX XX XX XX XX XX XX XX XX XX XX XX
 XX 23  3  3  3  3  3  3  3  3  3  3 34 XX
 XX  2 .. .. .. .. .. .. .. .. .. ..  4 XX
 XX  2 .. .. .. .. .. .. .. .. .. ..  4 XX
 XX  2 .. .. 14  1  1  1  1 21 .. ..  4 XX
 XX  2 .. ..  4 XX XX XX XX  2 .. ..  4 XX
 XX  2 .. ..  4 XX XX XX XX  2 .. ..  4 XX
 XX  2 .. ..  4 XX XX XX XX  2 .. ..  4 XX
 XX  2 .. ..  4 XX XX XX XX  2 .. ..  4 XX
 XX  2 .. ..  4 XX XX XX XX  2 .. ..  4 XX
 XX  2 .. .. 43  3  3  3  3 32 .. ..  4 XX
 XX  2 .. .. .. .. .. .. .. .. .. ..  4 XX
 XX  2 .. .. .. .. .. .. .. .. .. ..  4 XX
 XX 12  1  1  1  1  1  1  1  1  1  1 41 XX
 XX XX XX XX XX XX XX XX XX XX XX XX XX XX

4 References

None.

5 Arguments

1:   NX – INTEGERInput
2:   NY – INTEGERInput
On entry: the number of virtual grid points in the x- and y-direction respectively (including the boundary points).
Constraint: NX and NY≥4.
3:   NPTS – INTEGERInput
On entry: the total number of points in the base grid.
Constraint: NPTS≤NX×NY.
4:   NROWS – INTEGERInput
On entry: the total number of rows of the virtual grid that contain base grid points.
Constraint: 4≤NROWS≤NY.
5:   NBNDS – INTEGERInput
On entry: the total number of physical boundaries and corners in the base grid.
Constraint: NBNDS≥8.
6:   NBPTS – INTEGERInput
On entry: the total number of boundary points in the base grid.
Constraint: 12≤NBPTS<NPTS.
7:   LROW NROWS – INTEGER arrayInput
On entry: LROW i, for i=1,2,…,NROWS, contains the base grid index of the first grid point in base grid row i.
Constraints:
  • 1≤LROW i≤NPTS, for i=1,2,…,NROWS;
  • LROW i-1<LROW i, for i=2,3,…,NROWS.
8:   IROW NROWS – INTEGER arrayInput
On entry: IROW i, for i=1,2,…,NROWS, contains the virtual grid row number that corresponds to base grid row i.
Constraints:
  • 0≤IROW i≤NY, for i=1,2,…,NROWS;
  • IROW i-1<IROW i, for i=2,3,…,NROWS.
9:   ICOL NPTS – INTEGER arrayInput
On entry: ICOL i, for i=1,2,…,NPTS, contains the virtual grid column number that contains base grid point i.
Constraint: 0≤ICOL i≤NX, for i=1,2,…,NPTS.
10:   LLBND NBNDS – INTEGER arrayInput
On entry: LLBND i, for i=1,2,…,NBNDS, contains the element of LBND corresponding to the start of the ith boundary (or corner).
Constraints:
  • 1≤LLBND i≤NBPTS, for i=1,2,…,NBNDS;
  • LLBND i-1<LLBND i, for i=2,3,…,NBNDS.
11:   ILBND NBNDS – INTEGER arrayInput
On entry: ILBND i, for i=1,2,…,NBNDS, contains the type of the ith boundary (or corner), as defined in D03RBF.
Constraint: ILBND i must be equal to one of the following: 1, 2, 3, 4, 12, 23, 34, 41, 21, 32, 43 or 14, for i=1,2,…,NBNDS.
12:   LBND NBPTS – INTEGER arrayInput
On entry: LBND i, for i=1,2,…,NBPTS, contains the grid index of the ith boundary point.
Constraint: 1≤LBND i≤NPTS, for i=1,2,…,NBPTS.
13:   IWK LENIWK – INTEGER arrayWorkspace
14:   LENIWK – INTEGERInput
On entry: the dimension of the array IWK as declared in the (sub)program from which D03RYF is called.
Constraint: LENIWK≥NX×NY+1.
15:   PGRID NY – CHARACTER(*) arrayOutput
On exit: PGRID i, for i=1,2,…,NY, contains a graphical representation of row NY-i+1 of the virtual grid (see Section 3).
Constraint: LEN PGRID 1≥3×NX.
16:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, | NX or NY<4,
or | NPTS>NX×NY,
or | NROWS<4,
or | NROWS>NY,
or | NBNDS<8,
or | NBPTS<12,
or | NBPTS≥NPTS,
or | LROW i<1, for some i=1,2,…,NROWS,
or | LROW i>NPTS, for some i=1,2,…,NROWS,
or | LROW i≤LROW i-1, for some i=2,3,…,NROWS,
or | IROW i<0, for some i=1,2,…,NROWS,
or | IROW i>NY, for some i=1,2,…,NROWS,
or | IROW i≤IROW i-1, for some i=2,3,…,NROWS,
or | ICOL i<0, for some i=1,2,…,NPTS,
or | ICOL i>NX, for some i=1,2,…,NPTS,
or | LLBND i<1, for some i=1,2,…,NBNDS,
or | LLBND i>NBPTS, for some i=1,2,…,NBNDS,
or | LLBND i≤LLBND i-1, for some i=2,3,…,NBPTS,
or | ILBND i≠1, 2, 3, 4, 12, 23, 34, 41, 21, 32, 43 or 14, for some i=1,2,…,NBNDS,
or | LBND i<1, for some i=1,2,…,NBPTS,
or | LBND i>NPTS, for some i=1,2,…,NBPTS,
or | LENIWK<NX×NY+1,
or | LEN PGRID 1<3×NX.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

Not applicable.

8 Parallelism and Performance

D03RYF is not threaded in any implementation.

9 Further Comments

None.

10 Example

See Section 10 in D03RBF.
D03 Chapter Contents
D03 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


D03RZF : NAG Library, Mark 26

D03 Chapter Contents
D03 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

D03RZF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
10 Example

1 Purpose

D03RZF is designed to be used in conjunction with D03RBF. It can be called from the MONITR to obtain the number of grid points and their x,y coordinates on a solution grid.

2 Specification

SUBROUTINE D03RZF ( LEVEL, NLEV, XMIN, YMIN, DXB, DYB, LGRID, ISTRUC, NPTS, X, Y, LENXY, IFAIL)
INTEGER | LEVEL, NLEV, LGRID(*), ISTRUC(*), NPTS, LENXY, IFAIL
REAL (KIND=nag_wp) | XMIN, YMIN, DXB, DYB, X(LENXY), Y(LENXY)

3 Description

D03RZF extracts the number of grid points and their x,y coordinates on a specific solution grid produced by D03RBF. It must be called only from within the MONITR. The arguments NLEV, XMIN, YMIN, DXB, DYB, LGRID and ISTRUC to MONITR must be passed unchanged to D03RZF.

4 References

None.

5 Arguments

1:   LEVEL – INTEGERInput
On entry: the grid level at which the coordinates are required.
Constraint: 1≤LEVEL≤NLEV.
2:   NLEV – INTEGERInput
3:   XMIN – REAL (KIND=nag_wp)Input
4:   YMIN – REAL (KIND=nag_wp)Input
5:   DXB – REAL (KIND=nag_wp)Input
6:   DYB – REAL (KIND=nag_wp)Input
On entry: NLEV, XMIN, YMIN, DXB and DYB as supplied to MONITR must be passed unchanged to D03RZF.
7:   LGRID* – INTEGER arrayInput
Note: the dimension of the array LGRID must be at least NLEV.
On entry: LGRID as supplied to MONITR must be passed unchanged to D03RZF.
8:   ISTRUC* – INTEGER arrayInput
Note: the dimension of the array ISTRUC must be at least LGRID NLEV+2×nrows+NPTS+1 where nrows is stored in ISTRUC LGRID NLEV and is the number of rows in the grid at level NLEV.
On entry: ISTRUC as supplied to MONITR must be passed unchanged to D03RZF.
9:   NPTS – INTEGEROutput
On exit: the number of grid points in the grid level LEVEL.
10:   X LENXY – REAL (KIND=nag_wp) arrayOutput
11:   Y LENXY – REAL (KIND=nag_wp) arrayOutput
On exit: X i and Y i contain the x,y coordinates respectively of the ith grid point, for i=1,2,…,NPTS.
12:   LENXY – INTEGERInput
On entry: the dimension of the arrays X and Y as declared in the (sub)program from which D03RZF is called.
Constraint: LENXY≥NPTS.
13:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, | LEVEL<1,
or | LEVEL>NLEV.
IFAIL=2
The dimension of the arrays X and Y is too small for the requested grid level, i.e., LENXY<NPTS.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

Not applicable.

8 Parallelism and Performance

D03RZF is not threaded in any implementation.

9 Further Comments

None.

10 Example

See Section 10 in D03RBF.
D03 Chapter Contents
D03 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


D03UAF : NAG Library, Mark 26

D03 Chapter Contents
D03 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

D03UAF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

D03UAF performs at each call one iteration of the Strongly Implicit Procedure. It is used to calculate on successive calls a sequence of approximate corrections to the current estimate of the solution when solving a system of simultaneous algebraic equations for which the iterative update matrix is of five-point molecule form on a two-dimensional topologically-rectangular mesh. (‘Topological’ means that a polar grid r,θ, for example, can be used as it is equivalent to a rectangular box.)

2 Specification

SUBROUTINE D03UAF ( N1, N2, LDA, A, B, C, D, E, APARAM, IT, R, WRKSP1, WRKSP2, IFAIL)
INTEGER | N1, N2, LDA, IT, IFAIL
REAL (KIND=nag_wp) | A(LDA,N2), B(LDA,N2), C(LDA,N2), D(LDA,N2), E(LDA,N2), APARAM, R(LDA,N2), WRKSP1(LDA,N2), WRKSP2(LDA,N2)

3 Description

Given a set of simultaneous equations
Mt=q (1)
(which could be nonlinear) derived, for example, from a finite difference representation of a two-dimensional elliptic partial differential equation and its boundary conditions, the solution t may be obtained iteratively from a starting approximation t 1 by the formulae
r n = q-M t n M s n = r n t n+1 = t n +s n .
Thus r n is the residual of the nth approximate solution t n , and s n is the update change vector.
D03UAF determines the approximate change vector s corresponding to a given residual r, i.e., it determines an approximate solution to a set of equations
Ms=r (2)
where M is a square n 1×n 2 by n 1×n 2 matrix and r is a known vector of length n 1×n 2. The set of equations (2) must be of five-diagonal form
a ij s i,j-1 + b ij s i-1,j + c ij s ij + d ij s i+1,j + e ij s i,j+1 = r ij ,
for i=1,2,…,n 1 and j=1,2,…,n 2, provided that c ij≠0.0. Indeed, if c ij=0.0, then the equation is assumed to be
s ij=r ij.
For example, if n 1=3 and n 2=2, the equations take the form
c 11 d 11 e 11 b 21 c 21 d 21 e 21 b 31 c 31 e 31 a 12 c 12 d 12 a 22 b 22 c 22 d 22 a 32 b 32 c 32   s 11 s 21 s 31 s 12 s 22 s 32 = r 11 r 21 r 31 r 12 r 22 r 32 .
The calling program supplies the current residual r at each iteration and the coefficients of the five-point molecule system of equations on which the update procedure is based. The routine performs one iteration, using the approximate LU factorization of the Strongly Implicit Procedure with the necessary acceleration argument adjustment, to calculate the approximate solution s of the set of equations (2). The change s overwrites the residual array for return to the calling program. The calling program must combine this change stored in r with the old approximation to obtain the new approximate solution for t. It must then recalculate the residuals and, if the accuracy requirements have not been satisfied, commence the next iterative cycle.
Clearly there is no requirement that the iterative update matrix passed in the form of the five-diagonal element arrays A, B, C, D and E is the same as that used to calculate the residuals, and therefore the one governing the problem. However, the convergence may be impaired if they are not equal. Indeed, if the system of equations (1) is not precisely of the five-diagonal form illustrated above but has a few additional terms, then the methods of deferred or defect correction can be employed. The residual is calculated by the calling program using the full system of equations, but the update formula is based on a five-diagonal system (2) of the form given above. For example, the solution of a system of nine-diagonal equations each involving the combination of terms with t i±1,j±1,t i±1,j,t i,j±1 and t ij could use the five-diagonal coefficients on which to base the update, provided these incorporate the major features of the equations.
Problems in topologically non-rectangular regions can be solved using the routine by surrounding the region with a circumscribing topological rectangle. The equations for the nodal values external to the region of interest are set to zero (i.e., c ij=r ij=0) and the boundary conditions are incorporated into the equations for the appropriate nodes.
If there is no better initial approximation when starting the iterative cycle, one can use an array of all zeros as the initial approximation from which the first set of residuals are determined.
The routine can be used to solve linear elliptic equations in which case the arrays A, B, C, D, E and the quantities q will be unchanged during the iterative cycles, or for solving nonlinear elliptic equations in which case some or all of these arrays may require updating as each new approximate solution is derived. Depending on the nonlinearity, some under-relaxation of the coefficients and/or source terms may be needed during their recalculation using the new estimates of the solution (see Jacobs (1972)).
The routine can also be used to solve each step of a time-dependent parabolic equation in two space dimensions. The solution at each time step can be expressed in terms of an elliptic equation if the Crank–Nicolson or other form of implicit time integration is used.
Neither diagonal dominance, nor positive-definiteness, of the matrix M or of the update matrix formed from the arrays A, B, C, D and E is necessary to ensure convergence.
For problems in which the solution is not unique, in the sense that an arbitrary constant can be added to the solution (for example Laplace's equation with all Neumann boundary conditions), the calling program should subtract a typical nodal value from the whole solution t at every iteration to keep rounding errors to a minimum.

4 References

Ames W F (1977) Nonlinear Partial Differential Equations in Engineering (2nd Edition) Academic Press
Jacobs D A H (1972) The strongly implicit procedure for the numerical solution of parabolic and elliptic partial differential equations Note RD/L/N66/72 Central Electricity Research Laboratory
Stone H L (1968) Iterative solution of implicit approximations of multi-dimensional partial differential equations SIAM J. Numer. Anal. 5 530–558

5 Arguments

1:   N1 – INTEGERInput
On entry: the number of nodes in the first coordinate direction, n 1.
Constraint: N1>1.
2:   N2 – INTEGERInput
On entry: the number of nodes in the second coordinate direction, n 2.
Constraint: N2>1.
3:   LDA – INTEGERInput
On entry: the first dimension of the arrays A, B, C, D, E, R, WRKSP1 and WRKSP2 as declared in the (sub)program from which D03UAF is called.
Constraint: LDA≥N1.
4:   A LDAN2 – REAL (KIND=nag_wp) arrayInput
On entry: A ij must contain the coefficient of the ‘southerly’ term involving s i,j-1 in the i,jth equation of the system (2), for i=1,2,…,N1 and j=1,2,…,N2. The elements of A, for j=1, must be zero after incorporating the boundary conditions, since they involve nodal values from outside the rectangle.
5:   B LDAN2 – REAL (KIND=nag_wp) arrayInput
On entry: B ij must contain the coefficient of the ‘westerly’ term involving s i-1,j in the i,jth equation of the system (2), for i=1,2,…,N1 and j=1,2,…,N2. The elements of B, for i=1, must be zero after incorporating the boundary conditions, since they involve nodal values from outside the rectangle.
6:   C LDAN2 – REAL (KIND=nag_wp) arrayInput
On entry: C ij must contain the coefficient of the ‘central’ term involving s ij in the i,jth equation of the system (2), for i=1,2,…,N1 and j=1,2,…,N2. The elements of C are checked to ensure that they are nonzero. If any element is found to be zero, the corresponding algebraic equation is assumed to be s ij=r ij. This feature can be used to define the equations for nodes at which, for example, Dirichlet boundary conditions are applied, or for nodes external to the problem of interest, by setting C ij=0.0 at appropriate points. The corresponding value of R ij is set equal to the appropriate value, namely the difference between the prescribed value of t ij and the current value of t ij in the Dirichlet case, or zero at an external point.
7:   D LDAN2 – REAL (KIND=nag_wp) arrayInput
On entry: D ij must contain the coefficient of the ‘easterly’ term involving s i+1,j in the i,jth equation of the system (2), for i=1,2,…,N1 and j=1,2,…,N2. The elements of D, for i=N1, must be zero after incorporating the boundary conditions, since they involve nodal values from outside the rectangle.
8:   E LDAN2 – REAL (KIND=nag_wp) arrayInput
On entry: E ij must contain the coefficient of the ‘northerly’ term involving s i,j+1 in the i,jth equation of the system (2), for i=1,2,…,N1 and j=1,2,…,N2. The elements of E, for j=N2, must be zero after incorporating the boundary conditions, since they involve nodal values from outside the rectangle.
9:   APARAM – REAL (KIND=nag_wp)Input
On entry: the iteration acceleration factor. A value of 1.0 is adequate for most typical problems. However, if convergence is slow, the value can be reduced, typically to 0.2 or 0.1. If divergence is obtained, the value can be increased, typically to 2.0, 5.0 or 10.0.
Constraint: 0.0<APARAM≤ N1-1 2+ N2-1 2/2.0.
10:   IT – INTEGERInput
On entry: the iteration number. It must be initialized, but not necessarily to 1, before the first call, and must be incremented by one in the calling program for each subsequent call. D03UAF uses the counter to select the appropriate acceleration argument from a sequence of nine, each one being used twice in succession. (Note that the acceleration argument depends on the value of APARAM.)
11:   R LDAN2 – REAL (KIND=nag_wp) arrayInput/Output
On entry: R ij must contain the current residual r ij on the right-hand side of the i,jth equation of the system (2), for i=1,2,…,N1 and j=1,2,…,N2.
On exit: these residuals are overwritten by the corresponding components of solution s to the system (2), i.e., the changes to be made to the vector t to reduce the residuals supplied.
12:   WRKSP1 LDAN2 – REAL (KIND=nag_wp) arrayWorkspace
13:   WRKSP2 LDAN2 – REAL (KIND=nag_wp) arrayWorkspace
14:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, | N1<2,
or | N2<2.
IFAIL=2
On entry, LDA<N1.
IFAIL=3
On entry, APARAM≤0.0.
IFAIL=4
On entry, APARAM> N1-1 2+ N2-1 2/2.0.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

The improvement in accuracy for each iteration, i.e., on each call, depends on the size of the system and on the condition of the update matrix characterised by the five-diagonal coefficient arrays. The ultimate accuracy obtainable depends on the above factors and on the machine precision. However, since D03UAF works with residuals and the update vector, the calling program can, in most cases where at each iteration all the residuals are usually of about the same size, calculate the residuals from extended precision values of the function, source term and equation coefficients if greater accuracy is required. The rate of convergence obtained with the Strongly Implicit Procedure is not always smooth because of the cyclic use of nine acceleration arguments. The convergence may become slow with very large problems. The final accuracy obtained can be judged approximately from the rate of convergence determined from the changes to the dependent variable t and in particular the change on the last iteration.

8 Parallelism and Performance

D03UAF is not threaded in any implementation.

9 Further Comments

The time taken is approximately proportional to N1×N2 for each call.
When used with deferred or defect correction, the residual is calculated in the calling program from a different system of equations to those represented by the five-point molecule coefficients used by D03UAF as the basis of the iterative update procedure. When using deferred correction the overall rate of convergence depends not only on the items detailed in Section 7 but also on the difference between the two coefficient matrices used.
Convergence may not always be obtained when the problem is very large and/or the coefficients of the equations have widely disparate values. The latter case may be associated with an ill-conditioned matrix.

10 Example

This example solves Laplace's equation in a rectangle with a non-uniform grid spacing in the x and y coordinate directions and with Dirichlet boundary conditions specifying the function on the perimeter of the rectangle equal to e 1.0+x/y n 2×cos y/y n 2.

10.1 Program Text

Program Text (d03uafe.f90)

10.2 Program Data

Program Data (d03uafe.d)

10.3 Program Results

Program Results (d03uafe.r)

GnuplotProduced by GNUPLOT 4.6 patchlevel 3 Example Program Laplace's Equation on a Non-uniform Grid gnuplot_plot_1 gnuplot_plot_2 0 2 4 6 8 10 12 14 16 x 0 5 10 15 20 25 30 35 40 45 y 0.5 0.6 0.7 0.8 0.9 1 1.1 1.2 1.3 1.4 1.5 U
D03 Chapter Contents
D03 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


D03UBF : NAG Library, Mark 26

D03 Chapter Contents
D03 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

D03UBF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

D03UBF performs at each call one iteration of the Strongly Implicit Procedure. It is used to calculate on successive calls a sequence of approximate corrections to the current estimate of the solution when solving a system of simultaneous algebraic equations for which the iterative update matrix is of seven-point molecule form on a three-dimensional topologically-rectangular mesh. (‘Topological’ means that a polar grid r,θ, for example, can be used as it is equivalent to a rectangular box.)

2 Specification

SUBROUTINE D03UBF ( N1, N2, N3, LDA, SDA, A, B, C, D, E, F, G, APARAM, IT, R, WRKSP1, WRKSP2, WRKSP3, IFAIL)
INTEGER | N1, N2, N3, LDA, SDA, IT, IFAIL
REAL (KIND=nag_wp) | A(LDA,SDA,N3), B(LDA,SDA,N3), C(LDA,SDA,N3), D(LDA,SDA,N3), E(LDA,SDA,N3), F(LDA,SDA,N3), G(LDA,SDA,N3), APARAM, R(LDA,SDA,N3), WRKSP1(LDA,SDA,N3), WRKSP2(LDA,SDA,N3), WRKSP3(LDA,SDA,N3)

3 Description

Given a set of simultaneous equations
Mt=q (1)
(which could be nonlinear) derived, for example, from a finite difference representation of a three-dimensional elliptic partial differential equation and its boundary conditions, the solution t may be obtained iteratively from a starting approximation t 1 by the formulae
r n = q-M t n M s n = r n t n+1 = t n +s n .
Thus r n is the residual of the nth approximate solution t n , and s n is the update change vector.
D03UBF determines the approximate change vector s corresponding to a given residual r, i.e., it determines an approximate solution to a set of equations
Ms=r (2)
where M is a square n 1×n 2×n 3 by n 1×n 2×n 3 matrix and r is a known vector of length n 1×n 2×n 3. The set of equations (2) must be of seven-diagonal form
a ijks ij,k-1+b ijks i,j-1,k+c ijks i-1,jk+d ijks ijk+e ijks i+1,jk+f ijks i,j+1,k+g ijks ij,k+1=r ijk
for i=1,2,…,n 1, j=1,2,…,n 2 and k=1,2,…,n 3, provided that d ijk≠0.0. Indeed, if d ijk=0.0, then the equation is assumed to be
s ijk=r ijk.
The calling program supplies the current residual r at each iteration and the coefficients of the seven-point molecule system of equations on which the update procedure is based. The routine performs one iteration, using the approximate LU factorization of the Strongly Implicit Procedure with the necessary acceleration argument adjustment, to calculate the approximate solution s of the set of equations (2). The change s overwrites the residual array for return to the calling program. The calling program must combine this change stored in r with the old approximation to obtain the new approximate solution for t. It must then recalculate the residuals and, if the accuracy requirements have not been satisfied, commence the next iterative cycle.
Clearly there is no requirement that the iterative update matrix passed in the form of the seven-diagonal element arrays A, B, C, D, E, F and G is the same as that used to calculate the residuals, and therefore the one governing the problem. However, the convergence may be impaired if they are not equal. Indeed, if the system of equations (1) is not precisely of the seven-diagonal form illustrated above but has a few additional terms, then the methods of deferred or defect correction can be employed. The residual is calculated by the calling program using the full system of equations, but the update formula is based on a seven-diagonal system (2) of the form given above. For example, the solution of a system of eleven-diagonal equations each involving the combination of terms with t i±1,j±1,k,t i±1,j,k,t i,j±1,k,t i,j,k±1 and t ijk could use the seven-diagonal coefficients on which to base the update, provided these incorporate the major features of the equations.
Problems in topologically non-rectangular box-shaped regions can be solved using the routine by surrounding the region with a circumscribing topologically rectangular box. The equations for the nodal values external to the region of interest are set to zero (i.e., d ijk=r ijk=0) and the boundary conditions are incorporated into the equations for the appropriate nodes.
If there is no better initial approximation when starting the iterative cycle, one can use an array of all zeros as the initial approximation from which the first set of residuals are determined.
The routine can be used to solve linear elliptic equations in which case the arrays A, B, C, D, E, F and G and the quantities q will be unchanged during the iterative cycles, or for solving nonlinear elliptic equations in which case some or all of these arrays may require updating as each new approximate solution is derived. Depending on the nonlinearity, some under-relaxation of the coefficients and/or source terms may be needed during their recalculation using the new estimates of the solution (see Jacobs (1972)).
The routine can also be used to solve each step of a time-dependent parabolic equation in three space dimensions. The solution at each time step can be expressed in terms of an elliptic equation if the Crank–Nicolson or other form of implicit time integration is used.
Neither diagonal dominance, nor positive-definiteness, of the matrix M or of the update matrix formed from the arrays A, B, C, D, E, F and G is necessary to ensure convergence.
For problems in which the solution is not unique, in the sense that an arbitrary constant can be added to the solution (for example Poisson's equation with all Neumann boundary conditions), the calling program should subtract a typical nodal value from the whole solution t at every iteration to keep rounding errors to a minimum for those cases when convergence is slow. For such problems there is generally an associated compatibility condition. For the example mentioned this compatibility condition equates the total net source within the region (i.e., the source integrated over the region) with the total net outflow across the boundaries defined by the Neumann conditions (i.e., the normal derivative integrated along the whole boundary). It is very important that the algebraic equations derived to model such a problem accurately implement the compatibility condition. If they do not, a net source or sink is very likely to be represented by the set of algebraic equations and no steady-state solution of the equations exists.

4 References

Ames W F (1977) Nonlinear Partial Differential Equations in Engineering (2nd Edition) Academic Press
Jacobs D A H (1972) The strongly implicit procedure for the numerical solution of parabolic and elliptic partial differential equations Note RD/L/N66/72 Central Electricity Research Laboratory
Stone H L (1968) Iterative solution of implicit approximations of multi-dimensional partial differential equations SIAM J. Numer. Anal. 5 530–558
Weinstein H G, Stone H L and Kwan T V (1969) Iterative procedure for solution of systems of parabolic and elliptic equations in three dimensions Industrial and Engineering Chemistry Fundamentals 8 281–287

5 Arguments

1:   N1 – INTEGERInput
On entry: the number of nodes in the first coordinate direction, n 1.
Constraint: N1>1.
2:   N2 – INTEGERInput
On entry: the number of nodes in the second coordinate direction, n 2.
Constraint: N2>1.
3:   N3 – INTEGERInput
On entry: the number of nodes in the third coordinate direction, n 3.
Constraint: N3>1.
4:   LDA – INTEGERInput
On entry: the first dimension of the arrays A, B, C, D, E, F, G, R, WRKSP1, WRKSP2 and WRKSP3 as declared in the (sub)program from which D03UBF is called.
Constraint: LDA≥N1.
5:   SDA – INTEGERInput
On entry: the second dimension of the arrays A, B, C, D, E, F, G, R, WRKSP1, WRKSP2 and WRKSP3 as declared in the (sub)program from which D03UBF is called.
Constraint: SDA≥N2.
6:   A LDASDAN3 – REAL (KIND=nag_wp) arrayInput
On entry: A ijk must contain the coefficient of s ij,k-1 in the i,j,kth equation of the system (2), for i=1,2,…,N1, j=1,2,…,N2 and k=1,2,…,N3. The elements of A, for k=1, must be zero after incorporating the boundary conditions, since they involve nodal values from outside the box.
7:   B LDASDAN3 – REAL (KIND=nag_wp) arrayInput
On entry: B ijk must contain the coefficient of s i,j-1,k in the i,j,kth equation of the system (2), for i=1,2,…,N1, j=1,2,…,N2 and k=1,2,…,N3. The elements of B, for j=1, must be zero after incorporating the boundary conditions, since they involve nodal values from outside the box.
8:   C LDASDAN3 – REAL (KIND=nag_wp) arrayInput
On entry: C ijk must contain the coefficient of s i-1,j,k in the i,j,kth equation of the system (2), for i=1,2,…,N1, j=1,2,…,N2 and k=1,2,…,N3. The elements of C, for i=1, must be zero after incorporating the boundary conditions, since they involve nodal values from outside the box.
9:   D LDASDAN3 – REAL (KIND=nag_wp) arrayInput
On entry: D ijk must contain the coefficient of s ijk, the ‘central’ term, in the i,j,kth equation of the system (2), for i=1,2,…,N1, j=1,2,…,N2 and k=1,2,…,N3. The elements of D are checked to ensure that they are nonzero. If any element is found to be zero, the corresponding algebraic equation is assumed to be s ijk=r ijk. This feature can be used to define the equations for nodes at which, for example, Dirichlet boundary conditions are applied, or for nodes external to the problem of interest, by setting D ijk=0.0 at appropriate points. The corresponding value of r ijk is set equal to the appropriate value, namely the difference between the prescribed value of t ijk and the current value in the Dirichlet case, or zero at an external point.
10:   E LDASDAN3 – REAL (KIND=nag_wp) arrayInput
On entry: E ijk must contain the coefficient of s i+1,j,k in the i,j,kth equation of the system (2), for i=1,2,…,N1, j=1,2,…,N2 and k=1,2,…,N3. The elements of E, for i=N1, must be zero after incorporating the boundary conditions, since they involve nodal values from outside the box.
11:   F LDASDAN3 – REAL (KIND=nag_wp) arrayInput
On entry: F ijk must contain the coefficient of s i,j+1,k in the i,j,kth equation of the system (2), for i=1,2,…,N1, j=1,2,…,N2 and k=1,2,…,N3. The elements of F, for j=N2, must be zero after incorporating the boundary conditions, since they involve nodal values from outside the box.
12:   G LDASDAN3 – REAL (KIND=nag_wp) arrayInput
On entry: G ijk must contain the coefficient of s i,j,k+1 in the i,j,kth equation of the system (2), for i=1,2,…,N1, j=1,2,…,N2 and k=1,2,…,N3. The elements of G, for k=N3, must be zero after incorporating the boundary conditions, since they involve nodal values from outside the box.
13:   APARAM – REAL (KIND=nag_wp)Input
On entry: the iteration acceleration factor. A value of 1.0 is adequate for most typical problems. However, if convergence is slow, the value can be reduced, typically to 0.2 or 0.1. If divergence is obtained, the value can be increased, typically to 2.0, 5.0 or 10.0.
Constraint: 0.0<APARAM≤N1-1 2+N2-1 2+N3-1 2/3.0.
14:   IT – INTEGERInput
On entry: the iteration number. It must be initialized, but not necessarily to 1, before the first call, and should be incremented by one in the calling program for each subsequent call. The routine uses this counter to select the appropriate acceleration argument from a sequence of nine, each one being used twice in succession. (Note that the acceleration argument depends on the value of APARAM.)
15:   R LDASDAN3 – REAL (KIND=nag_wp) arrayInput/Output
On entry: the current residual r ijk on the right-hand side of the i,j,kth equation of the system (2), for i=1,2,…,N1, j=1,2,…,N2 and k=1,2,…,N3.
On exit: these residuals are overwritten by the corresponding components of the solution s of the system (2), i.e., the changes to be made to the vector t to reduce the residuals supplied.
16:   WRKSP1 LDASDAN3 – REAL (KIND=nag_wp) arrayWorkspace
17:   WRKSP2 LDASDAN3 – REAL (KIND=nag_wp) arrayWorkspace
18:   WRKSP3 LDASDAN3 – REAL (KIND=nag_wp) arrayWorkspace
19:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, | N1<2,
or | N2<2,
or | N3<2.
IFAIL=2
On entry, | LDA<N1,
or | SDA<N2.
IFAIL=3
On entry, APARAM≤0.0.
IFAIL=4
On entry, APARAM>N1-1 2+N2-1 2+N3-1 2/3.0.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

The improvement in accuracy for each iteration, i.e., on each call, depends on the size of the system and on the condition of the update matrix characterised by the seven-diagonal coefficient arrays. The ultimate accuracy obtainable depends on the above factors and on the machine precision. However, since D03UBF works with residuals and the update vector, the calling program can, in most cases where at each iteration all the residuals are usually of about the same size, calculate the residuals from extended precision values of the function, source term and equation coefficients if greater accuracy is required. The rate of convergence obtained with the Strongly Implicit Procedure is not always smooth because of the cyclic use of nine acceleration arguments. The convergence may become slow with very large problems. The final accuracy obtained can be judged approximately from the rate of convergence determined from the changes to the dependent variable t and in particular the change on the last iteration.

8 Parallelism and Performance

D03UBF is not threaded in any implementation.

9 Further Comments

The time taken is approximately proportional to N1×N2×N3 for each call.
When used with deferred or defect correction, the residual is calculated in the calling program from a different system of equations to those represented by the seven-point molecule coefficients used by D03UBF as the basis of the iterative update procedure. When using deferred correction the overall rate of convergence depends not only on the items detailed in Section 7 but also on the difference between the two coefficient matrices used.
Convergence may not always be obtained when the problem is very large and/or the coefficients of the equations have widely disparate values. The latter case may be associated with an ill-conditioned matrix.

10 Example

This example solves Laplace's equation in a rectangular box with a non-uniform grid spacing in the x, y and z coordinate directions and with Dirichlet boundary conditions specifying the function on the surfaces of the box equal to
e 1.0+x/y n 2×cos 2 y/y n 2×e-1.0-z/y n 2.
Note that this is the same problem as that solved in the example for D03ECF. The differences in the maximum residuals obtained at each iteration between the two test runs are explained by the fact that in D03ECF the residual at each node is normalized by dividing by the central coefficient, whereas this normalization has not been used in the example program for D03UBF.

10.1 Program Text

Program Text (d03ubfe.f90)

10.2 Program Data

Program Data (d03ubfe.d)

10.3 Program Results

Program Results (d03ubfe.r)

GnuplotProduced by GNUPLOT 4.6 patchlevel 3 Example Program Solution of Three-dimensional Laplace's Equation in a Box Solutions in the xy-plane for Various Values of z U gnuplot_plot_1 gnuplot_plot_2 z = 0 gnuplot_plot_3 z = 2 gnuplot_plot_4 z = 7.4 0 1 2 3 4 5 6 x 0 2 4 6 8 10 y 0 0.2 0.4 0.6 0.8 1 1.2 1.4 1.6 1.8 2
D03 Chapter Contents
D03 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


D04AAF : NAG Library, Mark 26

D04 Chapter Contents
D04 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

D04AAF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

D04AAF calculates a set of derivatives (up to order 14) of a function of one real variable at a point, together with a corresponding set of error estimates, using an extension of the Neville algorithm.

2 Specification

SUBROUTINE D04AAF ( XVAL, NDER, HBASE, DER, EREST, FUN, IFAIL)
INTEGER | NDER, IFAIL
REAL (KIND=nag_wp) | XVAL, HBASE, DER(14), EREST(14), FUN
EXTERNAL | FUN

3 Description

D04AAF provides a set of approximations:
DER j,  j=1,2,…,n
to the derivatives:
f j x 0,   j= 1,2,…,n
of a real valued function f x at a real abscissa x 0, together with a set of error estimates:
EREST j,  j=1,2,…,n
which hopefully satisfy:
DER j-f j x 0<EREST j,   j= 1,2,…,n.
You must provide the value of x 0, a value of n (which is reduced to 14 should it exceed 14), a subroutine which evaluates f x for all real x, and a step length h. The results DER j and EREST j are based on 21 function values:
f x 0,f x 0±2 i-1 h,  i=1,2,…,10.
Internally D04AAF calculates the odd order derivatives and the even order derivatives separately. There is an option you can use for restricting the calculation to only odd (or even) order derivatives. For each derivative the routine employs an extension of the Neville Algorithm (see Lyness and Moler (1969)) to obtain a selection of approximations.
For example, for odd derivatives, based on 20 function values, D04AAF calculates a set of numbers:
T k,p,s,   p=s,s+ 1,…,6,   k= 0,1,…,9-p
each of which is an approximation to f 2 s+1 x 0/2 s+1!. A specific approximation T k,p,s is of polynomial degree 2 p+2 and is based on polynomial interpolation using function values f x 0±2 i-1 h, for k=k,…,k+p. In the absence of round-off error, the better approximations would be associated with the larger values of p and of k. However, round-off error in function values has an increasingly contaminating effect for successively larger values of p. This routine proceeds to make a judicious choice between all the approximations in the following way.
For a specified value of s, let:
Rp = Up - Lp ,   p=s,s+1,…,6
where Up = maxk T k,p,s and Lp = mink T k,p,s , for k=0,1,…,9-p, and let p- be such that R p- = minp Rp , for p=s,…,6.
The routine returns:
DER 2 s+1 = 1 8-p- × ∑ k=0 9-p- T k, p-, s - U p- - L p- ⁢ 2 s+1 !
and
EREST 2 s+1 = R p- × 2 s+1 ! × K 2 s+1
where Kj is a safety factor which has been assigned the values:
Kj=1, | j≤9
Kj=1.5, | j=10,11
Kj=2 | j≥12,
on the basis of performance statistics.
The even order derivatives are calculated in a precisely analogous manner.

4 References

Lyness J N and Moler C B (1966) van der Monde systems and numerical differentiation Numer. Math. 8 458–464
Lyness J N and Moler C B (1969) Generalised Romberg methods for integrals of derivatives Numer. Math. 14 1–14

5 Arguments

1:   XVAL – REAL (KIND=nag_wp)Input
On entry: the point at which the derivatives are required, x 0.
2:   NDER – INTEGERInput
On entry: must be set so that its absolute value is the highest order derivative required.
NDER>0
All derivatives up to order min NDER,14 are calculated.
NDER<0 and NDER is even
Only even order derivatives up to order min-NDER,14 are calculated.
NDER<0 and NDER is odd
Only odd order derivatives up to order min-NDER,13 are calculated.
3:   HBASE – REAL (KIND=nag_wp)Input
On entry: the initial step length which may be positive or negative. For advice on the choice of HBASE see Section 9.
Constraint: HBASE≠0.0.
4:   DER 14 – REAL (KIND=nag_wp) arrayOutput
On exit: DER j contains an approximation to the jth derivative of f x at x=XVAL, so long as the jth derivative is one of those requested by you when specifying NDER. For other values of j, DER j is unused.
5:   EREST 14 – REAL (KIND=nag_wp) arrayOutput
On exit: an estimate of the absolute error in the corresponding result DER j so long as the jth derivative is one of those requested by you when specifying NDER. The sign of EREST j is positive unless the result DER j is questionable. It is set negative when DER j<EREST j or when for some other reason there is doubt about the validity of the result DER j (see Section 6). For other values of j, EREST j is unused.
6:   FUN – REAL (KIND=nag_wp) FUNCTION, supplied by the user.External Procedure
FUN must evaluate the function f x at a specified point.
The specification of FUN is:
FUNCTION FUN ( X)
REAL (KIND=nag_wp) FUN
REAL (KIND=nag_wp) X
1:   X – REAL (KIND=nag_wp)Input
On entry: the value of the argument x.
If you have equally spaced tabular data, the following information may be useful:
(i) | in any call of D04AAF the only values of x for which f x will be required are x=XVAL and x=XVAL±2 j-1 HBASE, for j=1,2,…,10; and
(ii) | f x 0 is always computed, but it is disregarded when only odd order derivatives are required.
FUN must either be a module subprogram USEd by, or declared as EXTERNAL in, the (sub)program from which D04AAF is called. Arguments denoted as Input must not be changed by this procedure.
7:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, | NDER=0,
or | HBASE=0.0.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.
If IFAIL has a value zero on exit then D04AAF has terminated successfully, but before any use is made of a derivative DER j the value of EREST j must be checked.

7 Accuracy

The accuracy of the results is problem dependent. An estimate of the accuracy of each result DER j is returned in EREST j (see Sections 3, 5 and 9).
A basic feature of any floating-point routine for numerical differentiation based on real function values on the real axis is that successively higher order derivative approximations are successively less accurate. It is expected that in most cases DER 14 will be unusable. As an aid to this process, the sign of EREST j is set negative when the estimated absolute error is greater than the approximate derivative itself, i.e., when the approximate derivative may be so inaccurate that it may even have the wrong sign. It is also set negative in some other cases when information available to the routine indicates that the corresponding value of DER j is questionable.
The actual values in EREST depend on the accuracy of the function values, the properties of the machine arithmetic, the analytic properties of the function being differentiated and the user-supplied step length HBASE (see Section 9). The only hard and fast rule is that for a given FUN XVAL and HBASE, the values of EREST j increase with increasing j. The limit of 14 is dictated by experience. Only very rarely can one obtain meaningful approximations for higher order derivatives on conventional machines.

8 Parallelism and Performance

D04AAF is not threaded in any implementation.

9 Further Comments

The time taken by D04AAF depends on the time spent for function evaluations. Otherwise the time is roughly equivalent to that required to evaluate the function 21 times and calculate a finite difference table having about 200 entries in total.
The results depend very critically on the choice of the user-supplied step length HBASE. The overall accuracy is diminished as HBASE becomes small (because of the effect of round-off error) and as HBASE becomes large (because the discretization error also becomes large). If the routine is used four or five times with different values of HBASE one can find a reasonably good value. A process in which the value of HBASE is successively halved (or doubled) is usually quite effective. Experience has shown that in cases in which the Taylor series for FUN X about XVAL has a finite radius of convergence R, the choices of HBASE>R/19 are not likely to lead to good results. In this case some function values lie outside the circle of convergence.

10 Example

This example evaluates the odd-order derivatives of the function:
f x = 12 e 2 x-1
up to order 7 at the point x=12 . Several different values of HBASE are used, to illustrate that:
(i) | extreme choices of HBASE, either too large or too small, yield poor results;
(ii) | the quality of these results is adequately indicated by the values of EREST.

10.1 Program Text

Program Text (d04aafe.f90)

10.2 Program Data

None.

10.3 Program Results

Program Results (d04aafe.r)

D04 Chapter Contents
D04 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


D04BAF : NAG Library, Mark 26

D04 Chapter Contents
D04 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

D04BAF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

D04BAF calculates a set of derivatives (up to order 14) of a function at a point with respect to a single variable. A corresponding set of error estimates is also returned. Derivatives are calculated using an extension of the Neville algorithm. This routine differs from D04AAF, in that the abscissae and corresponding function values must be calculated before this routine is called. The abscissae may be generated using D04BBF.

2 Specification

SUBROUTINE D04BAF ( XVAL, FVAL, DER, EREST, IFAIL)
INTEGER | IFAIL
REAL (KIND=nag_wp) | XVAL(21), FVAL(21), DER(14), EREST(14)

3 Description

D04BAF provides a set of approximations:
DER j ,   j=1,2,…,14
to the derivatives:
f j x 0 ,   j=1,2,…,14
of a real valued function f x at a real abscissa x 0, together with a set of error estimates:
EREST j ,   j=1,2,…,14
which hopefully satisfy:
DER j - f j x 0 < EREST j ,   j= 1,2,…,14 .
The results DER j and EREST j are based on 21 function values:
f x 0 , f x 0 ± 2 i-1 h ,   i=1,2,…,10 .
The abscissae x and the corresponding function values f x should be passed into D04BAF as the vectors XVAL and FVAL respectively. The step size h is derived from the abscissae in XVAL. See Section 9 for a discussion of how the derived value of h may affect the results of D04BAF. The order in which the abscissae and function values are stored in XVAL and FVAL is irrelevant, provided that the function value at any given index corresponds to the value of the abscissa at the same index. Abscissae may be automatically generated using D04BBF if desired. For each derivative D04BAF employs an extension of the Neville Algorithm (see Lyness and Moler (1969)) to obtain a selection of approximations.
For example, for odd derivatives, this routine calculates a set of numbers:
T k,p,s ,   p=s,s+1,…,6 ,   k=0,1,…,9-p
each of which is an approximation to f 2 s+1 x 0 / 2 s+1 ! . A specific approximation T k,p,s is of polynomial degree 2 p+2 and is based on polynomial interpolation using function values f x 0±2 i-1 h, for k=k,…,k+p. In the absence of round-off error, the better approximations would be associated with the larger values of p and of k. However, round-off error in function values has an increasingly contaminating effect for successively larger values of p. This routine proceeds to make a judicious choice between all the approximations in the following way.
For a specified value of s, let:
Rp = Up - Lp ,   p=s,s+1,…,6
where Up = maxk T k,p,s and Lp = mink T k,p,s , for k=0,1,…,9-p, and let p- be such that R p- = minp Rp , for p=s,…,6.
This routine returns:
DER 2 s+1 = 1 8-p- × ∑ k=0 9-p- T k, p-, s - U p- - L p- ⁢ 2 s+1 !
and
EREST 2 s+1 = R p- × 2 s+1 ! × K 2 s+1
where Kj is a safety factor which has been assigned the values:
Kj=1, | j≤9
Kj=1.5, | j=10,11
Kj=2 | j≥12,
on the basis of performance statistics.
The even order derivatives are calculated in a precisely analogous manner.

4 References

Lyness J N and Moler C B (1969) Generalised Romberg methods for integrals of derivatives Numer. Math. 14 1–14

5 Arguments

1:   XVAL 21 – REAL (KIND=nag_wp) arrayInput
On entry: the abscissae at which the function has been evaluated, as described in Section 3. These can be generated by calling D04BBF. The order of the abscissae is irrelevant.
Constraint: the values in XVAL must span the set x 0, x 0 ± 2 j-1 h , for j=1,2,…,10.
2:   FVAL 21 – REAL (KIND=nag_wp) arrayInput
On entry: FVAL j must contain the function value at XVAL j, for j=1,2,…,21.
3:   DER 14 – REAL (KIND=nag_wp) arrayOutput
On exit: the 14 derivative estimates.
4:   EREST 14 – REAL (KIND=nag_wp) arrayOutput
On exit: the 14 error estimates for the derivatives.
5:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, the values of XVAL are not correctly spaced.
Derived h=value.
The derived h is below tolerance.
Derived h>value is required. Derived h=value.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

The accuracy of the results is problem dependent. An estimate of the accuracy of each result DER j is returned in EREST j (see Sections 3, 5 and 9).
A basic feature of any floating-point routine for numerical differentiation based on real function values on the real axis is that successively higher order derivative approximations are successively less accurate. It is expected that in most cases DER 14 will be unusable. As an aid to this process, the sign of EREST j is set negative when the estimated absolute error is greater than the approximate derivative itself, i.e., when the approximate derivative may be so inaccurate that it may even have the wrong sign. It is also set negative in some other cases when information available to D04BAF indicates that the corresponding value of DER j is questionable.
The actual values in EREST depend on the accuracy of the function values, the properties of the machine arithmetic, the analytic properties of the function being differentiated and the step length h (see Section 9). The only hard and fast rule is that for a given objective function and h, the values of EREST j increase with increasing j. The limit of 14 is dictated by experience. Only very rarely can one obtain meaningful approximations for higher order derivatives on conventional machines.

8 Parallelism and Performance

D04BAF is not threaded in any implementation.

9 Further Comments

The results depend very critically on the choice of the step length h. The overall accuracy is diminished as h becomes small (because of the effect of round-off error) and as h becomes large (because the discretization error also becomes large). If this routine is used four or five times with different values of h one can find a reasonably good value. A process in which the value of h is successively halved (or doubled) is usually quite effective. Experience has shown that in cases in which the Taylor series for the objective function about x 0 has a finite radius of convergence R, the choices of h>R/19 are not likely to lead to good results. In this case some function values lie outside the circle of convergence.
As mentioned, the order of the abscissae in XVAL does not matter, provided the corresponding values of FVAL are ordered identically. If the abscissae are generated by D04BBF, then they will be in ascending order. In particular, the target abscissa x 0 will be stored in XVAL 11.

10 Example

This example evaluates the derivatives of the polygamma function, calculated using S14AEF, and compares the first 3 derivatives calculated to those found using S14AEF.

10.1 Program Text

Program Text (d04bafe.f90)

10.2 Program Data

None.

10.3 Program Results

Program Results (d04bafe.r)

D04 Chapter Contents
D04 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


D04BBF : NAG Library, Mark 26

D04 Chapter Contents
D04 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

D04BBF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
10 Example

1 Purpose

D04BBF generates abscissae about a target abscissa x 0 for use in a subsequent call to D04BAF.

2 Specification

SUBROUTINE D04BBF ( X_0, HBASE, XVAL)
REAL (KIND=nag_wp) X_0, HBASE, XVAL(21)

3 Description

D04BBF may be used to generate the necessary abscissae about a target abscissa x 0 for the calculation of derivatives using D04BAF.
For a given x 0 and h, the abscissae correspond to the set x 0, x 0 ± 2 j-1 h , for j=1,2,…,10. These 21 points will be returned in ascending order in XVAL. In particular, XVAL 11 will be equal to x 0.

4 References

Lyness J N and Moler C B (1969) Generalised Romberg methods for integrals of derivatives Numer. Math. 14 1–14

5 Arguments

1:   X_0 – REAL (KIND=nag_wp)Input
On entry: the abscissa x 0 at which derivatives are required.
2:   HBASE – REAL (KIND=nag_wp)Input
On entry: the chosen step size h. If h<10 ε, where ε=X02AJF, then the default h=ε 1/4 will be used.
3:   XVAL 21 – REAL (KIND=nag_wp) arrayOutput
On exit: the abscissae for passing to D04BAF.

6 Error Indicators and Warnings

None.

7 Accuracy

Not applicable.

8 Parallelism and Performance

D04BBF is not threaded in any implementation.

9 Further Comments

The results computed by D04BAF depend very critically on the choice of the user-supplied step length h. The overall accuracy is diminished as h becomes small (because of the effect of round-off error) and as h becomes large (because the discretization error also becomes large). If the process of calculating derivatives is repeated four or five times with different values of h one can find a reasonably good value. A process in which the value of h is successively halved (or doubled) is usually quite effective. Experience has shown that in cases in which the Taylor series for for the objective function about x 0 has a finite radius of convergence R, the choices of h>R/19 are not likely to lead to good results. In this case some function values lie outside the circle of convergence.

10 Example

See Section 10 in D04BAF.
D04 Chapter Contents
D04 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


D04 Chapter Contents : NAG Library Manual, Mark 26

D04 Chapter Introduction
NAG Library Manual

NAG Library Chapter Contents

D04 – Numerical Differentiation

D04 Chapter Introduction – a description of the Chapter and an overview of the algorithms available

Routine Name | Mark of Introduction | Purpose
D04AAF Example Text | 5 | nagf_numdiff Numerical differentiation, derivatives up to order 14, function of one real variable
D04BAF Example Text | 23 | nagf_numdiff_rcomm Numerical differentiation, user-supplied function values, derivatives up to order 14, derivatives with respect to one real variable
D04BBF | 23 | nagf_numdiff_sample Generates sample points for function evaluations by D04BAF
D04 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


D04 Chapter Introduction : NAG Library, Mark 26

D04 Chapter Contents
NAG Library Manual

NAG Library Chapter Introduction

D04 – Numerical Differentiation

▸▿ Contents

1 Scope of the Chapter
▸▿ 2 Background to the Problems
2.1 Description of the Problem
2.2 Examples of Applications for Numerical Differentiation Routines
3 Recommendations on Choice and Use of Available Routines
4 Functionality Index
5 Auxiliary Routines Associated with Library Routine Arguments
6 Routines Withdrawn or Scheduled for Withdrawal
7 References

1 Scope of the Chapter

This chapter is concerned with calculating approximations to derivatives of a function f.

2 Background to the Problems

2.1 Description of the Problem

The problem of numerical differentiation does not receive very much attention nowadays. Although the Taylor series plays a key role in much of classical analysis, the poor reputation enjoyed by numerical differentiation has led numerical analysts to construct techniques for most problems which avoid the explicit use of numerical differentiation.
One may briefly and roughly define the term numerical differentiation as any process in which numerical values of derivatives f s x 0 are obtained from evaluations f xi of the function f x at several abscissae xi near x 0. This problem can be stable, well-conditioned, and accurate when complex-valued abscissae are used. This was first pointed out by Lyness and Moler (1967). An item of numerical software for this appears in Lyness and Ande (1971). However, in many applications the use of complex-valued abscissae is either prohibitive or prohibited. The main difficulty in using real abscissae is that amplification of round-off error can completely obliterate meaningful results. In the days when one relied on hand calculating machines and tabular data, the frustration caused by this effect led to the abandonment of serious use of the process.
There are several reasons for believing that, in the present-day computing environment, numerical differentiation might find a useful role. The first is that, by present standards, it is rather a small-scale calculation, so its cost may well be negligible compared with any overall saving in cost that might result from its use. Secondly, the assignment of a step length h is now generally open. One does not have to rely on tabular data. Thirdly, although the amplification of round-off error is an integral part of the calculation, its effect can be measured reliably and automatically by the routine at the time of the calculation.
Thus you do not have to gauge the round-off level (or noise level) of the function values or assess the effect of this on the accuracy of the results. A routine does this automatically, returning with each result an error estimate which has already taken round-off error amplification into account.
We now illustrate, by means of a very simple example, the importance of the round-off error effect. A very simple approximation of f′0, based on the identity
f′0=f h-f-h/2 h+h 2/3! f′′′ξ, (1)
is
f h-f-h/2 h.
If there were no precision problem, this formula would be the only one needed in the theory of first-order numerical differentiation. We could simply take h=10-40 (or h=10-1000) to obtain an excellent approximation based on two function values. It is only when we consider in detail how a machine with finite precision comes to calculate f h-f-h/2 h that the necessity for a sophisticated theory becomes apparent.
To simplify the subsequent description we shall assume that the quantities involved are neither so close to zero that the machine underflow characteristics need be considered nor so large that machine overflow occurs. The approximation mentioned above involves the function values f h and f-h. In general no computer has available these numbers exactly. Instead it uses approximations f^h and f^-h whose relative accuracy is less than some tolerance εf. If the function f x is a library function, for example sin⁡x, εf may coincide with the machine accuracy parameter εm. More generally the function f x is calculated in a user-supplied routine and εf is larger than εm by a small factor 5 or 6 if the calculation is short or by some larger factor in an extended calculation. This factor is not usually known by you.
f^h and f^-h are related to f h and f-h by
f^h=f h1+θ 1εf, θ 1≤1 f^-h=f-h1+θ 2εf, θ 2≤1.
Thus even if the rest of the calculation were carried out exactly, it is trivial to show that
f^h-f^-h 2 h -f h-f-h 2 h ≃ 2 ϕ εf f ξ 2 h ,   ϕ ≤ 1.
The difference between the quantity actually calculated and the quantity which one attempts to calculate may be as large as εf f ξ/h; for example using h=10-40 and εm=10-7 this gives a ‘conditioning error’ of 1033 f ξ.
In practice much more sophisticated formulae than (1) above are used, and for these and for the corresponding higher-derivative formulae the error analysis is different and more complicated in detail. But invariably the theory contains the same overall feature. In a finite length calculation, the error is composed of two main parts: a discretization error which increases as h becomes large and is zero for h=0; and a ‘conditioning’ error due to amplification of round-off error in function evaluation, which increases as h becomes small and is infinite for h=0.
The routines in this chapter have to take into account internally both these sources of error in the results. Thus they return pairs of results, DER j and EREST j where DER j is an approximation to f j x 0 and EREST j is an estimate of the error in the approximation DER j. If the routine has not been misled, DER j and EREST j satisfy
DER j-f j x 0≤EREST j.
In this respect, numerical differentiation routines are fundamentally different from other routines. You do not specify an error criterion. Instead the routine provides the error estimate and this may be very large.
We mention here a terminological distinction. A fully automatic routine is one in which you do not need to provide any information other than that required to specify the problem. Such a routine (at a cost in computing time) decides an appropriate internal parameter such as the step length h by itself. On the other hand a routine which requires you to provide a step length h, but automatically chooses from several different formulae each based on the specified step length, is termed a semi-automatic routine.
The situation described above must have seemed rather depressing when hand machines were in common use. For example in the simple illustration one does not know the values of the quantities f′′′ξ or εf involved in the error estimates, and the idea of altering the value of h and starting again must have seemed appalling. However, by present-day standards, it is a relatively simple matter to write a program which carries out all the previously considered time-consuming calculations which may seem necessary. None of the routines in this chapter are particularly revolutionary in concept. They simply utilize the computer for the sort of task for which it was originally designed. It carries out simple tedious calculations which are necessary to estimate the accuracy of the results of other even simpler tedious calculations.

2.2 Examples of Applications for Numerical Differentiation Routines

(a) One immediate use to which a set of derivatives at a point is likely to be put is that of constructing a Taylor series representation:
f x=f x 0+∑j=1 n f j x 0 j! x-x 0 j+f n+1 ξ n+1! x-x 0 n+1,  ξ-x 0≤x.
This infinite series converges so long as x-x 0<Rc (the radius of convergence) and it is only for these values of x that such a series is likely to be used. In this case in forming the sum, the required accuracy in f j x 0 diminishes with increasing j.
The series formed from the Taylor series using elementary operations such as integration or differentiation has the same overall characteristic. A technique based on a Taylor series expansion may be quite accurate, even if the individual derivatives are not, so long as the less accurate derivatives are associated with known small coefficients.
The error introduced by using n approximate derivatives DER j is bounded by
∑j=1 n EREST j x-x 0 j/j!
Thus, if you are prepared to base the result on a truncated Taylor series, the additional error introduced by using approximate Taylor coefficients can be readily bounded from the values of EREST j. However, in an automatic code you must be prepared to introduce some alternative approach in case this error bound turns out to be unduly high.
In this sort of application the accuracy of the result depends on the size of the errors in the numerical differentiation. There are other applications where the effect of large errors EREST j is merely to prolong a calculation, but not to impair the final accuracy.
(b) A simple Taylor series approach such as described in (a) is used to find a starting value for a rapidly converging but extremely local iterative process.
(c) The technique known as ‘subtracting out the singularity’ as a preliminary to numerical quadrature may be extended and may be carried out approximately. Thus suppose we are interested in evaluating
∫01 x-1/2 ϕ x dx,
we have an automatic quadrature routine available, and we have a routine available for ϕ x which we know to be an analytic function. An integrand function like x-1/2 ϕ x is generally accepted to be difficult for an automatic integrator because of the singularity. If ϕ x and some of its derivatives at the singularity x=0 are known one may effectively ‘subtract out’ the singularity using the following identity:
∫01 x-1/2 ϕ x dx=∫01 x-1/2 ϕ x-ϕ 0-Ax-B x 2/2 dx+2 ϕ 0+2 A/3+B/5 (2)
with A=ϕ′0 and B=ϕ′′0.
The integrand function on the right of (2) has no singularity, but its third derivative does. Thus using numerical quadrature for this integral is much cheaper than using numerical quadrature for the original integral (in the left-hand side of (2)).
However, (2) is an identity whatever values of A and B are assigned. Thus the same procedure can be used with A and B being approximations to ϕ′0 and ϕ′′0 provided by a numerical differentiation routine. The integrand would now be more difficult to integrate than if A and B were correct but still much less difficult than the original integrand (on the left-hand side of (2)). But, assuming that the automatic quadrature routine is reliable, the overall result would still be correct. The effect of using approximate derivatives rather than exact derivatives does not impair the accuracy of the result. It simply makes the result more expensive to obtain, but not nearly as expensive as if no derivatives were used at all.
(d) The calculation of a definite integral may be based on the Euler–Maclaurin expansion
∫01 f x dx=1 m∑j=0 m′′f j/m-∑s=1 l B 2 s 2 s! f 2 s-1 1-f 2 s-1 0 m 2 s+O m -2 l-2 .
Here B 2 s is a Bernoulli number. If one fixes a value of l then as m is increased the right-hand side (without the remainder term) approaches the true value of the integral. This statement remains true whatever values are used to replace f 2 s-1 1 and f 2 s-1 0. If no derivatives are available, and this formula is used (effectively with the derivatives replaced by zero) the rate of convergence is slow (like m-2) and a large number of function evaluations may be used in calculating the trapezoidal rule sum for large m before a sufficiently accurate result is attained. However, if approximate derivatives are used, the initial rate of convergence is enhanced. In fact, in this example any derivative approximation which is closer than the approximation zero is helpful. Thus the use of inaccurate derivatives may have the effect of shortening the overall calculation, since a sufficiently accurate result may be obtained using a smaller value of m, without impairing the accuracy of the result. (The resemblance with Gregory's formula is superficial. Here l is kept fixed and m is increased, ensuring a convergent process.)
The examples given above are only intended to illustrate the sort of use to which approximate derivatives may be put. Very simple illustrations have been used for clarity, and in such simple cases there are usually more efficient approaches to the problem. The same ideas applied in a more complicated or restrictive setting may provide an efficient approach to a problem for which no simple standard approach exists.

3 Recommendations on Choice and Use of Available Routines

(a) At the present, there is only one numerical differentiation algorithm available in this chapter accessible using direct communication in D04AAF, and using reverse communication in D04BAF (see Section 3.3.3 in How to Use the NAG Library and its Documentation for a description of the difference between these two conventions). These are semi-automatic routines for obtaining approximations to the first fourteen derivatives of a real valued function f x at a specified point x 0. For D04AAF, you must provide a FUNCTION representing f x, the value of x 0, an upper limit n≤14 on the order of the derivatives required and a step length h. For D04BAF, you must supply the value of x 0, 20 other abscissae and the function values at those abscissae. Both routines return a set of approximations DER j and corresponding error estimates EREST j which hopefully satisfy
DER j-f j x 0≤EREST j,  j=1,2,…,n≤14.
It is important that the error estimate EREST j be taken into consideration before any use of DER j is made. The actual size of EREST j depends on the analytic structure of the function, on the computational precision used and on the step size h, and is difficult to predict. Thus you have to run the routine to find out how accurate the results are. Usually you will find the higher-order derivatives are successively more inaccurate and that past a certain order, say 10 or 11, the size of EREST j actually exceeds DER j. Clearly when this happens the approximation DER j is unusable.
(b) | There is available in the algorithm section of CACM (see Lyness and Ande (1971)) a semi-automatic Fortran routine for numerical differentiation of an analytical function f z at a possibly complex abscissa z 0. This is a stable problem. It can be used for any problem for which D04AAF might be used and produces more accurate results, and derivatives of arbitrary high order. However, even if z 0 is real and f z is real for z, this routine requires a user-supplied FUNCTION which evaluates f z for complex values of z and it makes use of complex arithmetic.
(c) | Routines are available in Chapter E02 to differentiate functions which are polynomials (in Chebyshev series representation) or cubic splines (in B-spline representation).

4 Functionality Index

Generates abscissae for D04BAF D04BBF
Numerical derivatives,
direct communication D04AAF
reverse communication D04BAF

5 Auxiliary Routines Associated with Library Routine Arguments

None.

6 Routines Withdrawn or Scheduled for Withdrawal

None.

7 References

Lyness J N and Ande G (1971) Algorithm 413, ENTCAF and ENTCRE: evaluation of normalised Taylor coefficients of an analytic function Comm. ACM 14(10) 669–675
Lyness J N and Moler C B (1967) Numerical differentiation of analytic functions SIAM J. Numer. Anal. 4(2) 202–210
D04 Chapter Contents
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


D05AAF : NAG Library, Mark 26

D05 Chapter Contents
D05 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

D05AAF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

D05AAF solves a linear, nonsingular Fredholm equation of the second kind with a split kernel.

2 Specification

SUBROUTINE D05AAF ( LAMBDA, A, B, K1, K2, G, F, C, N, IND, W1, W2, WD, LDW1, LDW2, IFAIL)
INTEGER | N, IND, LDW1, LDW2, IFAIL
REAL (KIND=nag_wp) | LAMBDA, A, B, K1, K2, G, F(N), C(N), W1(LDW1,LDW2), W2(LDW2,4), WD(LDW2)
EXTERNAL | K1, K2, G

3 Description

D05AAF solves an integral equation of the form
f x-λ∫ab k x,s f s ds=g x
for a≤x≤b, when the kernel k is defined in two parts: k=k 1 for a≤s≤x and k=k 2 for x<s≤b. The method used is that of El–Gendi (1969) for which, it is important to note, each of the functions k 1 and k 2 must be defined, smooth and nonsingular, for all x and s in the interval a,b.
An approximation to the solution f x is found in the form of an n term Chebyshev series ∑′i=1 n ciTi x, where ′ indicates that the first term is halved in the sum. The coefficients ci, for i=1,2,…,n, of this series are determined directly from approximate values fi, for i=1,2,…,n, of the function f x at the first n of a set of m+1 Chebyshev points:
xi=12 a+b+b-a cos i-1 π/m,  i=1,2,…,m+1.
The values fi are obtained by solving simultaneous linear algebraic equations formed by applying a quadrature formula (equivalent to the scheme of Clenshaw and Curtis (1960)) to the integral equation at the above points.
In general m=n-1. However, if the kernel k is centro-symmetric in the interval a,b, i.e., if k x,s=k a+b-x,a+b-s, then the routine is designed to take advantage of this fact in the formation and solution of the algebraic equations. In this case, symmetry in the function g x implies symmetry in the function f x. In particular, if g x is even about the mid-point of the range of integration, then so also is f x, which may be approximated by an even Chebyshev series with m=2 n-1. Similarly, if g x is odd about the mid-point then f x may be approximated by an odd series with m=2 n.

4 References

Clenshaw C W and Curtis A R (1960) A method for numerical integration on an automatic computer Numer. Math. 2 197–205
El–Gendi S E (1969) Chebyshev solution of differential, integral and integro-differential equations Comput. J. 12 282–287

5 Arguments

1:   LAMBDA – REAL (KIND=nag_wp)Input
On entry: the value of the parameter λ of the integral equation.
2:   A – REAL (KIND=nag_wp)Input
On entry: a, the lower limit of integration.
3:   B – REAL (KIND=nag_wp)Input
On entry: b, the upper limit of integration.
Constraint: B>A.
4:   K1 – REAL (KIND=nag_wp) FUNCTION, supplied by the user.External Procedure
K1 must evaluate the kernel k x,s=k 1 x,s of the integral equation for a≤s≤x.
The specification of K1 is:
FUNCTION K1 ( X, S)
REAL (KIND=nag_wp) K1
REAL (KIND=nag_wp) X, S
1:   X – REAL (KIND=nag_wp)Input
2:   S – REAL (KIND=nag_wp)Input
On entry: the values of x and s at which k 1 x,s is to be evaluated.
K1 must either be a module subprogram USEd by, or declared as EXTERNAL in, the (sub)program from which D05AAF is called. Arguments denoted as Input must not be changed by this procedure.
5:   K2 – REAL (KIND=nag_wp) FUNCTION, supplied by the user.External Procedure
K2 must evaluate the kernel k x,s=k 2 x,s of the integral equation for x<s≤b.
The specification of K2 is:
FUNCTION K2 ( X, S)
REAL (KIND=nag_wp) K2
REAL (KIND=nag_wp) X, S
1:   X – REAL (KIND=nag_wp)Input
2:   S – REAL (KIND=nag_wp)Input
On entry: the values of x and s at which k 2 x,s is to be evaluated.
K2 must either be a module subprogram USEd by, or declared as EXTERNAL in, the (sub)program from which D05AAF is called. Arguments denoted as Input must not be changed by this procedure.
Note that the functions k 1 and k 2 must be defined, smooth and nonsingular for all x and s in the interval [a,b].
6:   G – REAL (KIND=nag_wp) FUNCTION, supplied by the user.External Procedure
G must evaluate the function g x for a≤x≤b.
The specification of G is:
FUNCTION G ( X)
REAL (KIND=nag_wp) G
REAL (KIND=nag_wp) X
1:   X – REAL (KIND=nag_wp)Input
On entry: the values of x at which g x is to be evaluated.
G must either be a module subprogram USEd by, or declared as EXTERNAL in, the (sub)program from which D05AAF is called. Arguments denoted as Input must not be changed by this procedure.
7:   F N – REAL (KIND=nag_wp) arrayOutput
On exit: the approximate values fi, for i=1,2,…,N, of f x evaluated at the first N of m+1 Chebyshev points xi, (see Section 3).
If IND=0 or 3, m=N-1.
If IND=1, m=2×N.
If IND=2, m=2×N-1.
8:   C N – REAL (KIND=nag_wp) arrayOutput
On exit: the coefficients ci, for i=1,2,…,N, of the Chebyshev series approximation to f x.
If IND=1 this series contains polynomials of odd order only and if IND=2 the series contains even order polynomials only.
9:   N – INTEGERInput
On entry: the number of terms in the Chebyshev series required to approximate f x.
Constraint: N≥1.
10:   IND – INTEGERInput
On entry: determines the forms of the kernel, k x,s, and the function g x.
IND=0
k x,s is not centro-symmetric (or no account is to be taken of centro-symmetry).
IND=1
k x,s is centro-symmetric and g x is odd.
IND=2
k x,s is centro-symmetric and g x is even.
IND=3
k x,s is centro-symmetric but g x is neither odd nor even.
Constraint: IND=0, 1, 2 or 3.
11:   W1 LDW1LDW2 – REAL (KIND=nag_wp) arrayWorkspace
12:   W2 LDW2 4 – REAL (KIND=nag_wp) arrayWorkspace
13:   WD LDW2 – REAL (KIND=nag_wp) arrayWorkspace
14:   LDW1 – INTEGERInput
On entry: the first dimension of the array W1 as declared in the (sub)program from which D05AAF is called.
Constraint: LDW1≥N.
15:   LDW2 – INTEGERInput
On entry: the second dimension of the array W1 and the first dimension of the array W2 and the dimension of the array WD as declared in the (sub)program from which D05AAF is called.
Constraint: LDW2≥2×N+2.
16:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, A≥B or N<1.
IFAIL=2
A failure has occurred due to proximity to an eigenvalue. In general, if LAMBDA is near an eigenvalue of the integral equation, the corresponding matrix will be nearly singular. In the special case, m=1, the matrix reduces to a zero-valued number.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

No explicit error estimate is provided by the routine but it is usually possible to obtain a good indication of the accuracy of the solution either
(i) | by examining the size of the later Chebyshev coefficients ci, or
(ii) | by comparing the coefficients ci or the function values fi for two or more values of N.

8 Parallelism and Performance

D05AAF is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
D05AAF makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The time taken by D05AAF increases with N.
This routine may be used to solve an equation with a continuous kernel by defining K1 and K2 to be identical.
This routine may also be used to solve a Volterra equation by defining K2 (or K1) to be identically zero.

10 Example

This example solves the equation
f x - ∫01 k x,s f s ds = 1 - 1 π 2 sin πx
where
k x,s = s 1-x   for ​ 0≤s≤x , x 1-s   for ​ x<s≤1 .
Five terms of the Chebyshev series are sought, taking advantage of the centro-symmetry of the k x,s and even nature of g x about the mid-point of the range 0,1.
The approximate solution at the point x=0.1 is calculated by calling C06DCF.

10.1 Program Text

Program Text (d05aafe.f90)

10.2 Program Data

None.

10.3 Program Results

Program Results (d05aafe.r)

D05 Chapter Contents
D05 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


D05ABF : NAG Library, Mark 26

D05 Chapter Contents
D05 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

D05ABF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

D05ABF solves any linear nonsingular Fredholm integral equation of the second kind with a smooth kernel.

2 Specification

SUBROUTINE D05ABF ( K, G, LAMBDA, A, B, ODOREV, EV, N, CM, F1, WK, LDCM, NT2P1, F, C, IFAIL)
INTEGER | N, LDCM, NT2P1, IFAIL
REAL (KIND=nag_wp) | K, G, LAMBDA, A, B, CM(LDCM,LDCM), F1(LDCM,1), WK(2,NT2P1), F(N), C(N)
LOGICAL | ODOREV, EV
EXTERNAL | K, G

3 Description

D05ABF uses the method of El–Gendi (1969) to solve an integral equation of the form
f x-λ∫ab k x,s f s ds=g x
for the function f x in the range a≤x≤b.
An approximation to the solution f x is found in the form of an n term Chebyshev series ∑′i=1 n ciTi x, where ′ indicates that the first term is halved in the sum. The coefficients ci, for i=1,2,…,n, of this series are determined directly from approximate values fi, for i=1,2,…,n, of the function f x at the first n of a set of m+1 Chebyshev points
xi=12 a+b+b-a×cos i-1×π/m,  i=1,2,…,m+1.
The values fi are obtained by solving a set of simultaneous linear algebraic equations formed by applying a quadrature formula (equivalent to the scheme of Clenshaw and Curtis (1960)) to the integral equation at each of the above points.
In general m=n-1. However, advantage may be taken of any prior knowledge of the symmetry of f x. Thus if f x is symmetric (i.e., even) about the mid-point of the range a,b, it may be approximated by an even Chebyshev series with m=2 n-1. Similarly, if f x is anti-symmetric (i.e., odd) about the mid-point of the range of integration, it may be approximated by an odd Chebyshev series with m=2 n.

4 References

Clenshaw C W and Curtis A R (1960) A method for numerical integration on an automatic computer Numer. Math. 2 197–205
El–Gendi S E (1969) Chebyshev solution of differential, integral and integro-differential equations Comput. J. 12 282–287

5 Arguments

1:   K – REAL (KIND=nag_wp) FUNCTION, supplied by the user.External Procedure
K must compute the value of the kernel k x,s of the integral equation over the square a≤x≤b, a≤s≤b.
The specification of K is:
FUNCTION K ( X, S)
REAL (KIND=nag_wp) K
REAL (KIND=nag_wp) X, S
1:   X – REAL (KIND=nag_wp)Input
2:   S – REAL (KIND=nag_wp)Input
On entry: the values of x and s at which k x,s is to be calculated.
K must either be a module subprogram USEd by, or declared as EXTERNAL in, the (sub)program from which D05ABF is called. Arguments denoted as Input must not be changed by this procedure.
2:   G – REAL (KIND=nag_wp) FUNCTION, supplied by the user.External Procedure
G must compute the value of the function g x of the integral equation in the interval a≤x≤b.
The specification of G is:
FUNCTION G ( X)
REAL (KIND=nag_wp) G
REAL (KIND=nag_wp) X
1:   X – REAL (KIND=nag_wp)Input
On entry: the value of x at which g x is to be calculated.
G must either be a module subprogram USEd by, or declared as EXTERNAL in, the (sub)program from which D05ABF is called. Arguments denoted as Input must not be changed by this procedure.
3:   LAMBDA – REAL (KIND=nag_wp)Input
On entry: the value of the parameter λ of the integral equation.
4:   A – REAL (KIND=nag_wp)Input
On entry: a, the lower limit of integration.
5:   B – REAL (KIND=nag_wp)Input
On entry: b, the upper limit of integration.
Constraint: B>A.
6:   ODOREV – LOGICALInput
On entry: indicates whether it is known that the solution f x is odd or even about the mid-point of the range of integration. If ODOREV is .TRUE. then an odd or even solution is sought depending upon the value of EV.
7:   EV – LOGICALInput
On entry: is ignored if ODOREV is .FALSE.. Otherwise, if EV is .TRUE., an even solution is sought, whilst if EV is .FALSE., an odd solution is sought.
8:   N – INTEGERInput
On entry: the number of terms in the Chebyshev series which approximates the solution f x.
Constraint: N≥1.
9:   CM LDCMLDCM – REAL (KIND=nag_wp) arrayWorkspace
10:   F1 LDCM 1 – REAL (KIND=nag_wp) arrayWorkspace
11:   WK 2 NT2P1 – REAL (KIND=nag_wp) arrayWorkspace
12:   LDCM – INTEGERInput
On entry: the first dimension of the arrays CM and F1 and the second dimension of the array CM as declared in the (sub)program from which D05ABF is called.
Constraint: LDCM≥N.
13:   NT2P1 – INTEGERInput
On entry: the second dimension of the array WK as declared in the (sub)program from which D05ABF is called. The value 2×N+1.
14:   F N – REAL (KIND=nag_wp) arrayOutput
On exit: the approximate values fi, for i=1,2,…,N, of the function f x at the first N of m+1 Chebyshev points (see Section 3), where
m=2 N-1 | if ODOREV=.TRUE. and EV=.TRUE..
m=2 N | if ODOREV=.TRUE. and EV=.FALSE..
m=N-1 | if ODOREV=.FALSE..
15:   C N – REAL (KIND=nag_wp) arrayOutput
On exit: the coefficients ci, for i=1,2,…,N, of the Chebyshev series approximation to f x. When ODOREV is .TRUE., this series contains polynomials of even order only or of odd order only, according to EV being .TRUE. or .FALSE. respectively.
16:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, A≥B or N<1.
IFAIL=2
A failure has occurred due to proximity to an eigenvalue. In general, if LAMBDA is near an eigenvalue of the integral equation, the corresponding matrix will be nearly singular. In the special case, m=1, the matrix reduces to a zero-valued number.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

No explicit error estimate is provided by the routine but it is possible to obtain a good indication of the accuracy of the solution either
(i) | by examining the size of the later Chebyshev coefficients ci, or
(ii) | by comparing the coefficients ci or the function values fi for two or more values of N.

8 Parallelism and Performance

D05ABF is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
D05ABF makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The time taken by D05ABF depends upon the value of N and upon the complexity of the kernel function k x,s.

10 Example

This example solves Love's equation:
f x+1 π ∫-1 1 f s 1+ x-s 2 ds=1 .
It will solve the slightly more general equation:
f x-λ ∫ab k x,s f s ds=1
where k x,s=α/α 2+ x-s 2. The values λ=-1/π,a=-1,b=1,α=1 are used below.
It is evident from the symmetry of the given equation that f x is an even function. Advantage is taken of this fact both in the application of D05ABF, to obtain the fi≃f xi and the ci, and in subsequent applications of C06DCF to obtain f x at selected points.
The program runs for N=5 and N=10.

10.1 Program Text

Program Text (d05abfe.f90)

10.2 Program Data

None.

10.3 Program Results

Program Results (d05abfe.r)

D05 Chapter Contents
D05 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


D05BAF : NAG Library, Mark 26

D05 Chapter Contents
D05 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

D05BAF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

D05BAF computes the solution of a nonlinear convolution Volterra integral equation of the second kind using a reducible linear multi-step method.

2 Specification

SUBROUTINE D05BAF ( CK, CG, CF, METHOD, IORDER, ALIM, TLIM, YN, ERREST, NMESH, TOL, THRESH, WORK, LWK, IFAIL)
INTEGER | IORDER, NMESH, LWK, IFAIL
REAL (KIND=nag_wp) | CK, CG, CF, ALIM, TLIM, YN(NMESH), ERREST(NMESH), TOL, THRESH, WORK(LWK)
CHARACTER(1) | METHOD
EXTERNAL | CK, CG, CF

3 Description

D05BAF computes the numerical solution of the nonlinear convolution Volterra integral equation of the second kind
y t=f t+∫at k t-s g s,y s ds,  a≤t≤T. (1)
It is assumed that the functions involved in (1) are sufficiently smooth. The routine uses a reducible linear multi-step formula selected by you to generate a family of quadrature rules. The reducible formulae available in D05BAF are the Adams–Moulton formulae of orders 3 to 6, and the backward differentiation formulae (BDF) of orders 2 to 5. For more information about the behaviour and the construction of these rules we refer to Lubich (1983) and Wolkenfelt (1982).
The algorithm is based on computing the solution in a step-by-step fashion on a mesh of equispaced points. The initial step size which is given by T-a/N, N being the number of points at which the solution is sought, is halved and another approximation to the solution is computed. This extrapolation procedure is repeated until successive approximations satisfy a user-specified error requirement.
The above methods require some starting values. For the Adams' formula of order greater than 3 and the BDF of order greater than 2 we employ an explicit Dormand–Prince–Shampine Runge–Kutta method (see Shampine (1986)). The above scheme avoids the calculation of the kernel, k t, on the negative real line.

4 References

Lubich Ch (1983) On the stability of linear multi-step methods for Volterra convolution equations IMA J. Numer. Anal. 3 439–465
Shampine L F (1986) Some practical Runge–Kutta formulas Math. Comput. 46(173) 135–150
Wolkenfelt P H M (1982) The construction of reducible quadrature rules for Volterra integral and integro-differential equations IMA J. Numer. Anal. 2 131–152

5 Arguments

1:   CK – REAL (KIND=nag_wp) FUNCTION, supplied by the user.External Procedure
CK must evaluate the kernel k t of the integral equation (1).
The specification of CK is:
FUNCTION CK ( T)
REAL (KIND=nag_wp) CK
REAL (KIND=nag_wp) T
1:   T – REAL (KIND=nag_wp)Input
On entry: t, the value of the independent variable.
CK must either be a module subprogram USEd by, or declared as EXTERNAL in, the (sub)program from which D05BAF is called. Arguments denoted as Input must not be changed by this procedure.
2:   CG – REAL (KIND=nag_wp) FUNCTION, supplied by the user.External Procedure
CG must evaluate the function g s,y s in (1).
The specification of CG is:
FUNCTION CG ( S, Y)
REAL (KIND=nag_wp) CG
REAL (KIND=nag_wp) S, Y
1:   S – REAL (KIND=nag_wp)Input
On entry: s, the value of the independent variable.
2:   Y – REAL (KIND=nag_wp)Input
On entry: the value of the solution y at the point S.
CG must either be a module subprogram USEd by, or declared as EXTERNAL in, the (sub)program from which D05BAF is called. Arguments denoted as Input must not be changed by this procedure.
3:   CF – REAL (KIND=nag_wp) FUNCTION, supplied by the user.External Procedure
CF must evaluate the function f t in (1).
The specification of CF is:
FUNCTION CF ( T)
REAL (KIND=nag_wp) CF
REAL (KIND=nag_wp) T
1:   T – REAL (KIND=nag_wp)Input
On entry: t, the value of the independent variable.
CF must either be a module subprogram USEd by, or declared as EXTERNAL in, the (sub)program from which D05BAF is called. Arguments denoted as Input must not be changed by this procedure.
4:   METHOD – CHARACTER(1)Input
On entry: the type of method which you wish to employ.
METHOD='A'
For Adams' type formulae.
METHOD='B'
For backward differentiation formulae.
Constraint: METHOD='A' or 'B'.
5:   IORDER – INTEGERInput
On entry: the order of the method to be used.
Constraints:
  • if METHOD='A', 3≤IORDER≤6;
  • if METHOD='B', 2≤IORDER≤5.
6:   ALIM – REAL (KIND=nag_wp)Input
On entry: a, the lower limit of the integration interval.
Constraint: ALIM≥0.0.
7:   TLIM – REAL (KIND=nag_wp)Input
On entry: the final point of the integration interval, T.
Constraint: TLIM>ALIM.
8:   YN NMESH – REAL (KIND=nag_wp) arrayOutput
On exit: YN i contains the most recent approximation of the true solution y t at the specified point t=ALIM+i×H, for i=1,2,…,NMESH, where H=TLIM-ALIM/NMESH.
9:   ERREST NMESH – REAL (KIND=nag_wp) arrayOutput
On exit: ERREST i contains the most recent approximation of the relative error in the computed solution at the point t=ALIM+i×H, for i=1,2,…,NMESH, where H=TLIM-ALIM/NMESH.
10:   NMESH – INTEGERInput
On entry: the number of equidistant points at which the solution is sought.
Constraints:
  • if METHOD='A', NMESH≥IORDER-1;
  • if METHOD='B', NMESH≥IORDER.
11:   TOL – REAL (KIND=nag_wp)Input
On entry: the relative accuracy required in the computed values of the solution.
Constraint: ε≤TOL≤1.0, where ε is the machine precision.
12:   THRESH – REAL (KIND=nag_wp)Input
On entry: the threshold value for use in the evaluation of the estimated relative errors. For two successive meshes the following condition must hold at each point of the coarser mesh
Y 1-Y 2 max Y 1,Y 2,THRESH ≤TOL,
where Y 1 is the computed solution on the coarser mesh and Y 2 is the computed solution at the corresponding point in the finer mesh. If this condition is not satisfied then the step size is halved and the solution is recomputed.
Note: THRESH can be used to effect a relative, absolute or mixed error test. If THRESH=0.0 then pure relative error is measured and, if the computed solution is small and THRESH=1.0, absolute error is measured.
13:   WORK LWK – REAL (KIND=nag_wp) arrayOutput
14:   LWK – INTEGERInput
On entry: the dimension of the array WORK as declared in the (sub)program from which D05BAF is called.
Constraint: LWK≥10×NMESH+6.
Note: the above value of LWK is sufficient for D05BAF to perform only one extrapolation on the initial mesh as defined by NMESH. In general much more workspace is required and in the case when a large step size is supplied (i.e., NMESH is small), you must provide a considerably larger workspace.
On exit: if IFAIL=5 or 6, WORK 1 contains the size of LWK required for the algorithm to proceed further.
15:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, | METHOD≠'A' or 'B',
or | IORDER<2 or IORDER>6,
or | METHOD='A' and IORDER=2,
or | METHOD='B' and IORDER=6,
or | ALIM<0.0,
or | TLIM≤ALIM,
or | TOL<ε or TOL>1.0, where ε is the machine precision.
IFAIL=2
On entry, | NMESH≤IORDER-2, when METHOD='A',
or | NMESH≤IORDER-1, when METHOD='B'.
IFAIL=3
On entry, LWK<10×NMESH+6.
IFAIL=4
The solution of the nonlinear equation (2) (see Section 9 for further details) could not be computed by C05AVF and C05AZF.
IFAIL=5
The size of the workspace LWK is too small for the required accuracy. The computation has failed in its initial phase (see Section 9 for further details).
IFAIL=6
The size of the workspace LWK is too small for the required accuracy on the interval ALIM,TLIM (see Section 9 for further details).
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

The accuracy depends on TOL, the theoretical behaviour of the solution of the integral equation, the interval of integration and on the method being used. It can be controlled by varying TOL and THRESH; you are recommended to choose a smaller value for TOL, the larger the value of IORDER.
You are warned not to supply a very small TOL, because the required accuracy may never be achieved. This will usually force an error exit with IFAIL=5 or 6.
In general, the higher the order of the method, the faster the required accuracy is achieved with less workspace. For non-stiff problems (see Section 9) you are recommended to use the Adams' method (METHOD='A') of order greater than 4 (IORDER>4).

8 Parallelism and Performance

D05BAF is not threaded in any implementation.

9 Further Comments

When solving (1), the solution of a nonlinear equation of the form
Yn-αg tn,Yn-Ψn=0, (2)
is required, where Ψn and α are constants. D05BAF calls C05AVF to find an interval for the zero of this equation followed by C05AZF to find its zero.
There is an initial phase of the algorithm where the solution is computed only for the first few points of the mesh. The exact number of these points depends on IORDER and METHOD. The step size is halved until the accuracy requirements are satisfied on these points and only then the solution on the whole mesh is computed. During this initial phase, if LWK is too small, D05BAF will exit with IFAIL=5.
In the case IFAIL=4 or 5, you may be dealing with a ‘stiff’ equation; an equation where the Lipschitz constant L of the function g t,y in (1) with respect to its second argument is large, viz,
g t,u-g t,v≤L u-v. (3)
In this case, if a BDF method (METHOD='B') has been used, you are recommended to choose a smaller step size by increasing the value of NMESH, or provide a larger workspace. But, if an Adams' method (METHOD='A') has been selected, you are recommended to switch to a BDF method instead.
In the case IFAIL=6, the specified accuracy has not been attained but YN and ERREST contain the most recent approximation to the computed solution and the corresponding error estimate. In this case, the error message informs you of the number of extrapolations performed and the size of LWK required for the algorithm to proceed further. The latter quantity will also be available in WORK 1.

10 Example

Consider the following integral equation
y t=e-t+∫0 t e-t-s y s+e-y s ds,  0≤t≤20 (4)
with the solution y t=ln t+e. In this example, the Adams' method of order 6 is used to solve this equation with TOL=1.E−4.

10.1 Program Text

Program Text (d05bafe.f90)

10.2 Program Data

None.

10.3 Program Results

Program Results (d05bafe.r)

D05 Chapter Contents
D05 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


D05BDF : NAG Library, Mark 26

D05 Chapter Contents
D05 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

D05BDF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

D05BDF computes the solution of a weakly singular nonlinear convolution Volterra–Abel integral equation of the second kind using a fractional Backward Differentiation Formulae (BDF) method.

2 Specification

SUBROUTINE D05BDF ( CK, CF, CG, INITWT, IORDER, TLIM, TOLNL, NMESH, YN, WORK, LWK, NCT, IFAIL)
INTEGER | IORDER, NMESH, LWK, NCT(NMESH/32+1), IFAIL
REAL (KIND=nag_wp) | CK, CF, CG, TLIM, TOLNL, YN(NMESH), WORK(LWK)
CHARACTER(1) | INITWT
EXTERNAL | CK, CF, CG

3 Description

D05BDF computes the numerical solution of the weakly singular convolution Volterra–Abel integral equation of the second kind
y t = f t + 1 π ∫0 t k t-s t-s g s,y s ds ,   0≤t≤T . (1)
Note the constant 1 π in (1). It is assumed that the functions involved in (1) are sufficiently smooth.
The routine uses a fractional BDF linear multi-step method to generate a family of quadrature rules (see D05BYF). The BDF methods available in D05BDF are of orders 4, 5 and 6 (=p say). For a description of the theoretical and practical background to these methods we refer to Lubich (1985) and to Baker and Derakhshan (1987) and Hairer et al. (1988) respectively.
The algorithm is based on computing the solution y t in a step-by-step fashion on a mesh of equispaced points. The size of the mesh is given by T/N-1, N being the number of points at which the solution is sought. These methods require 2 p-1 (including y 0) starting values which are evaluated internally. The computation of the lag term arising from the discretization of (1) is performed by fast Fourier transform (FFT) techniques when N>32+2 p-1, and directly otherwise. The routine does not provide an error estimate and you are advised to check the behaviour of the solution with a different value of N. An option is provided which avoids the re-evaluation of the fractional weights when D05BDF is to be called several times (with the same value of N) within the same program unit with different functions.

4 References

Baker C T H and Derakhshan M S (1987) FFT techniques in the numerical solution of convolution equations J. Comput. Appl. Math. 20 5–24
Hairer E, Lubich Ch and Schlichte M (1988) Fast numerical solution of weakly singular Volterra integral equations J. Comput. Appl. Math. 23 87–98
Lubich Ch (1985) Fractional linear multistep methods for Abel–Volterra integral equations of the second kind Math. Comput. 45 463–469

5 Arguments

1:   CK – REAL (KIND=nag_wp) FUNCTION, supplied by the user.External Procedure
CK must evaluate the kernel k t of the integral equation (1).
The specification of CK is:
FUNCTION CK ( T)
REAL (KIND=nag_wp) CK
REAL (KIND=nag_wp) T
1:   T – REAL (KIND=nag_wp)Input
On entry: t, the value of the independent variable.
CK must either be a module subprogram USEd by, or declared as EXTERNAL in, the (sub)program from which D05BDF is called. Arguments denoted as Input must not be changed by this procedure.
2:   CF – REAL (KIND=nag_wp) FUNCTION, supplied by the user.External Procedure
CF must evaluate the function f t in (1).
The specification of CF is:
FUNCTION CF ( T)
REAL (KIND=nag_wp) CF
REAL (KIND=nag_wp) T
1:   T – REAL (KIND=nag_wp)Input
On entry: t, the value of the independent variable.
CF must either be a module subprogram USEd by, or declared as EXTERNAL in, the (sub)program from which D05BDF is called. Arguments denoted as Input must not be changed by this procedure.
3:   CG – REAL (KIND=nag_wp) FUNCTION, supplied by the user.External Procedure
CG must evaluate the function g s,y s in (1).
The specification of CG is:
FUNCTION CG ( S, Y)
REAL (KIND=nag_wp) CG
REAL (KIND=nag_wp) S, Y
1:   S – REAL (KIND=nag_wp)Input
On entry: s, the value of the independent variable.
2:   Y – REAL (KIND=nag_wp)Input
On entry: the value of the solution y at the point S.
CG must either be a module subprogram USEd by, or declared as EXTERNAL in, the (sub)program from which D05BDF is called. Arguments denoted as Input must not be changed by this procedure.
4:   INITWT – CHARACTER(1)Input
On entry: if the fractional weights required by the method need to be calculated by the routine then set INITWT='I' (Initial call).
If INITWT='S' (Subsequent call), the routine assumes the fractional weights have been computed on a previous call and are stored in WORK.
Constraint: INITWT='I' or 'S'.
Note: when D05BDF is re-entered with the value of INITWT='S', the values of NMESH, IORDER and the contents of WORK must not be changed.
5:   IORDER – INTEGERInput
On entry: p, the order of the BDF method to be used.
Suggested value: IORDER=4.
Constraint: 4≤IORDER≤6.
6:   TLIM – REAL (KIND=nag_wp)Input
On entry: the final point of the integration interval, T.
Constraint: TLIM>10×machine precision.
7:   TOLNL – REAL (KIND=nag_wp)Input
On entry: the accuracy required for the computation of the starting value and the solution of the nonlinear equation at each step of the computation (see Section 9).
Suggested value: TOLNL=ε where ε is the machine precision.
Constraint: TOLNL>10×machine precision.
8:   NMESH – INTEGERInput
On entry: N, the number of equispaced points at which the solution is sought.
Constraint: NMESH=2 m+2×IORDER-1, where m≥1.
9:   YN NMESH – REAL (KIND=nag_wp) arrayOutput
On exit: YN i contains the approximate value of the true solution y t at the point t=i-1×h, for i=1,2,…,NMESH, where h=TLIM/NMESH-1.
10:   WORK LWK – REAL (KIND=nag_wp) arrayCommunication Array
On entry: if INITWT='S', WORK must contain fractional weights computed by a previous call of D05BDF (see description of INITWT).
On exit: contains fractional weights which may be used by a subsequent call of D05BDF.
11:   LWK – INTEGERInput
On entry: the dimension of the array WORK as declared in the (sub)program from which D05BDF is called.
Constraint: LWK≥2×IORDER+6×NMESH+8×IORDER 2-16×IORDER+1.
12:   NCT NMESH/32+1 – INTEGER arrayWorkspace
13:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, | IORDER<4 or IORDER>6,
or | TLIM≤10×machine precision,
or | INITWT≠'I' or 'S',
or | INITWT='S' on the first call to D05BDF,
or | TOLNL≤10×machine precision,
or | NMESH≠2 m+2×IORDER-1,m≥1,
or | LWK<2×IORDER+6×NMESH+8×IORDER 2-16×IORDER+1.
IFAIL=2
The routine cannot compute the 2 p-1 starting values due to an error solving the system of nonlinear equations. Relaxing the value of TOLNL and/or increasing the value of NMESH may overcome this problem (see Section 9 for further details).
IFAIL=3
The routine cannot compute the solution at a specific step due to an error in the solution of the nonlinear equation (2). Relaxing the value of TOLNL and/or increasing the value of NMESH may overcome this problem (see Section 9 for further details).
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

The accuracy depends on NMESH and TOLNL, the theoretical behaviour of the solution of the integral equation and the interval of integration. The value of TOLNL controls the accuracy required for computing the starting values and the solution of (2) at each step of computation. This value can affect the accuracy of the solution. However, for most problems, the value of ε, where ε is the machine precision, should be sufficient.

8 Parallelism and Performance

D05BDF is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
D05BDF makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

In solving (1), initially, D05BDF computes the solution of a system of nonlinear equations for obtaining the 2 p-1 starting values. C05QDF is used for this purpose. When a failure with IFAIL=2 occurs (which corresponds to an error exit from C05QDF), you are advised to either relax the value of TOLNL or choose a smaller step size by increasing the value of NMESH. Once the starting values are computed successfully, the solution of a nonlinear equation of the form
Yn-αg tn,Yn-Ψn=0, (2)
is required at each step of computation, where Ψn and α are constants. D05BDF calls C05AXF to find the root of this equation.
If a failure with IFAIL=3 occurs (which corresponds to an error exit from C05AXF), you are advised to relax the value of the TOLNL or choose a smaller step size by increasing the value of NMESH.
If a failure with IFAIL=2 or 3 persists even after adjustments to TOLNL and/or NMESH then you should consider whether there is a more fundamental difficulty. For example, the problem is ill-posed or the functions in (1) are not sufficiently smooth.

10 Example

In this example we solve the following integral equations
y t = t + 38 π t 2 - ∫0 t 1 t-s y s 3 ds ,   0≤t≤7 ,
with the solution y t=t, and
y t = 3-t t - ∫0 t 1 t-s exp s 1-s 2 - y s 2 d s ,   0≤t≤5 ,
with the solution y t=1-t t. In the above examples, the fourth-order BDF is used, and NMESH is set to 26+7.

10.1 Program Text

Program Text (d05bdfe.f90)

10.2 Program Data

None.

10.3 Program Results

Program Results (d05bdfe.r)

D05 Chapter Contents
D05 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


D05BEF : NAG Library, Mark 26

D05 Chapter Contents
D05 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

D05BEF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

D05BEF computes the solution of a weakly singular nonlinear convolution Volterra–Abel integral equation of the first kind using a fractional Backward Differentiation Formulae (BDF) method.

2 Specification

SUBROUTINE D05BEF ( CK, CF, CG, INITWT, IORDER, TLIM, TOLNL, NMESH, YN, WORK, LWK, NCT, IFAIL)
INTEGER | IORDER, NMESH, LWK, NCT(NMESH/32+1), IFAIL
REAL (KIND=nag_wp) | CK, CF, CG, TLIM, TOLNL, YN(NMESH), WORK(LWK)
CHARACTER(1) | INITWT
EXTERNAL | CK, CF, CG

3 Description

D05BEF computes the numerical solution of the weakly singular convolution Volterra–Abel integral equation of the first kind
f t+1 π∫0 t k t-s t-s g s,y s ds=0,  0≤t≤T. (1)
Note the constant 1 π in (1). It is assumed that the functions involved in (1) are sufficiently smooth and if
f t=tβ w t  with  β>-12​ and ​w t​ smooth, (2)
then the solution y t is unique and has the form y t=t β-1/2 z t, (see Lubich (1987)). It is evident from (1) that f 0=0. You are required to provide the value of y t at t=0. If y 0 is unknown, Section 9 gives a description of how an approximate value can be obtained.
The routine uses a fractional BDF linear multi-step method selected by you to generate a family of quadrature rules (see D05BYF). The BDF methods available in D05BEF are of orders 4, 5 and 6 (=p say). For a description of the theoretical and practical background related to these methods we refer to Lubich (1987) and to Baker and Derakhshan (1987) and Hairer et al. (1988) respectively.
The algorithm is based on computing the solution y t in a step-by-step fashion on a mesh of equispaced points. The size of the mesh is given by T/N-1, N being the number of points at which the solution is sought. These methods require 2 p-2 starting values which are evaluated internally. The computation of the lag term arising from the discretization of (1) is performed by fast Fourier transform (FFT) techniques when N>32+2 p-1, and directly otherwise. The routine does not provide an error estimate and you are advised to check the behaviour of the solution with a different value of N. An option is provided which avoids the re-evaluation of the fractional weights when D05BEF is to be called several times (with the same value of N) within the same program with different functions.

4 References

Baker C T H and Derakhshan M S (1987) FFT techniques in the numerical solution of convolution equations J. Comput. Appl. Math. 20 5–24
Gorenflo R and Pfeiffer A (1991) On analysis and discretization of nonlinear Abel integral equations of first kind Acta Math. Vietnam 16 211–262
Hairer E, Lubich Ch and Schlichte M (1988) Fast numerical solution of weakly singular Volterra integral equations J. Comput. Appl. Math. 23 87–98
Lubich Ch (1987) Fractional linear multistep methods for Abel–Volterra integral equations of the first kind IMA J. Numer. Anal 7 97–106

5 Arguments

1:   CK – REAL (KIND=nag_wp) FUNCTION, supplied by the user.External Procedure
CK must evaluate the kernel k t of the integral equation (1).
The specification of CK is:
FUNCTION CK ( T)
REAL (KIND=nag_wp) CK
REAL (KIND=nag_wp) T
1:   T – REAL (KIND=nag_wp)Input
On entry: t, the value of the independent variable.
CK must either be a module subprogram USEd by, or declared as EXTERNAL in, the (sub)program from which D05BEF is called. Arguments denoted as Input must not be changed by this procedure.
2:   CF – REAL (KIND=nag_wp) FUNCTION, supplied by the user.External Procedure
CF must evaluate the function f t in (1).
The specification of CF is:
FUNCTION CF ( T)
REAL (KIND=nag_wp) CF
REAL (KIND=nag_wp) T
1:   T – REAL (KIND=nag_wp)Input
On entry: t, the value of the independent variable.
CF must either be a module subprogram USEd by, or declared as EXTERNAL in, the (sub)program from which D05BEF is called. Arguments denoted as Input must not be changed by this procedure.
3:   CG – REAL (KIND=nag_wp) FUNCTION, supplied by the user.External Procedure
CG must evaluate the function g s,y s in (1).
The specification of CG is:
FUNCTION CG ( S, Y)
REAL (KIND=nag_wp) CG
REAL (KIND=nag_wp) S, Y
1:   S – REAL (KIND=nag_wp)Input
On entry: s, the value of the independent variable.
2:   Y – REAL (KIND=nag_wp)Input
On entry: the value of the solution y at the point S.
CG must either be a module subprogram USEd by, or declared as EXTERNAL in, the (sub)program from which D05BEF is called. Arguments denoted as Input must not be changed by this procedure.
4:   INITWT – CHARACTER(1)Input
On entry: if the fractional weights required by the method need to be calculated by the routine then set INITWT='I' (Initial call).
If INITWT='S' (Subsequent call), the routine assumes the fractional weights have been computed by a previous call and are stored in WORK.
Constraint: INITWT='I' or 'S'.
Note: when D05BEF is re-entered with a value of INITWT='S', the values of NMESH, IORDER and the contents of WORK must not be changed.
5:   IORDER – INTEGERInput
On entry: p, the order of the BDF method to be used.
Suggested value: IORDER=4.
Constraint: 4≤IORDER≤6.
6:   TLIM – REAL (KIND=nag_wp)Input
On entry: the final point of the integration interval, T.
Constraint: TLIM>10×machine precision.
7:   TOLNL – REAL (KIND=nag_wp)Input
On entry: the accuracy required for the computation of the starting value and the solution of the nonlinear equation at each step of the computation (see Section 9).
Suggested value: TOLNL=ε where ε is the machine precision.
Constraint: TOLNL>10×machine precision.
8:   NMESH – INTEGERInput
On entry: N, the number of equispaced points at which the solution is sought.
Constraint: NMESH=2 m+2×IORDER-1, where m≥1.
9:   YN NMESH – REAL (KIND=nag_wp) arrayInput/Output
On entry: YN 1 must contain the value of y t at t=0 (see Section 9).
On exit: YN i contains the approximate value of the true solution y t at the point t=i-1×h, for i=1,2,…,NMESH, where h=TLIM/NMESH-1.
10:   WORK LWK – REAL (KIND=nag_wp) arrayCommunication Array
On entry: if INITWT='S', WORK must contain fractional weights computed by a previous call of D05BEF (see description of INITWT).
On exit: contains fractional weights which may be used by a subsequent call of D05BEF.
11:   LWK – INTEGERInput
On entry: the dimension of the array WORK as declared in the (sub)program from which D05BEF is called.
Constraint: LWK≥2×IORDER+6×NMESH+8×IORDER 2-16×IORDER+1.
12:   NCT NMESH/32+1 – INTEGER arrayWorkspace
13:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, | IORDER<4 or IORDER>6,
or | TLIM≤10×machine precision,
or | INITWT≠'I' or 'S',
or | INITWT='S' on the first call to D05BEF,
or | TOLNL≤10×machine precision,
or | NMESH≠2 m+2×IORDER-1,m≥1,
or | LWK<2×IORDER+6×NMESH+8×IORDER 2-16×IORDER+1.
IFAIL=2
The routine cannot compute the 2 p-2 starting values due to an error in solving the system of nonlinear equations. Relaxing the value of TOLNL and/or increasing the value of NMESH may overcome this problem (see Section 9 for further details).
IFAIL=3
The routine cannot compute the solution at a specific step due to an error in the solution of the single nonlinear equation (3). Relaxing the value of TOLNL and/or increasing the value of NMESH may overcome this problem (see Section 9 for further details).
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

The accuracy depends on NMESH and TOLNL, the theoretical behaviour of the solution of the integral equation and the interval of integration. The value of TOLNL controls the accuracy required for computing the starting values and the solution of (3) at each step of computation. This value can affect the accuracy of the solution. However, for most problems, the value of ε, where ε is the machine precision, should be sufficient.

8 Parallelism and Performance

D05BEF is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
D05BEF makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

Also when solving (1) the initial value y 0 is required. This value may be computed from the limit relation (see Gorenflo and Pfeiffer (1991))
-2 π k 0 g 0,y 0 = lim t→0 f t t . (3)
If the value of the above limit is known then by solving the nonlinear equation (3) an approximation to y 0 can be computed. If the value of the above limit is not known, an approximation should be provided. Following the analysis presented in Gorenflo and Pfeiffer (1991), the following pth-order approximation can be used:
lim t→0 f t t ≃ f hp h p/2 . (4)
However, it must be emphasized that the approximation in (4) may result in an amplification of the rounding errors and hence you are advised (if possible) to determine lim t→0 f t t by analytical methods.
Also when solving (1), initially, D05BEF computes the solution of a system of nonlinear equation for obtaining the 2 p-2 starting values. C05QDF is used for this purpose. If a failure with IFAIL=2 occurs (corresponding to an error exit from C05QDF), you are advised to either relax the value of TOLNL or choose a smaller step size by increasing the value of NMESH. Once the starting values are computed successfully, the solution of a nonlinear equation of the form
Yn-αg tn,Yn-Ψn=0, (5)
is required at each step of computation, where Ψn and α are constants. D05BEF calls C05AXF to find the root of this equation.
When a failure with IFAIL=3 occurs (which corresponds to an error exit from C05AXF), you are advised to either relax the value of the TOLNL or choose a smaller step size by increasing the value of NMESH.
If a failure with IFAIL=2 or 3 persists even after adjustments to TOLNL and/or NMESH then you should consider whether there is a more fundamental difficulty. For example, the problem is ill-posed or the functions in (1) are not sufficiently smooth.

10 Example

We solve the following integral equations.
Example 1
The density of the probability that a Brownian motion crosses a one-sided moving boundary a t before time t, satisfies the integral equation (see Hairer et al. (1988))
-1 t exp 12-a t 2/t+∫0 t exp -12 a t-a s 2/t-s t-s y s ds=0,  0≤t≤7.
In the case of a straight line a t=1+t, the exact solution is known to be
y t=1 2 π t 3 exp- 1+t 2/2 t
Example 2
In this example we consider the equation
-2 log 1+t+t 1+t +∫0 t y s t-s ds= 0,   0≤t≤ 5.
The solution is given by y t=1 1+t .
In the above examples, the fourth-order BDF is used, and NMESH is set to 26+7.

10.1 Program Text

Program Text (d05befe.f90)

10.2 Program Data

None.

10.3 Program Results

Program Results (d05befe.r)

D05 Chapter Contents
D05 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


D05BWF : NAG Library, Mark 26

D05 Chapter Contents
D05 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

D05BWF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

D05BWF computes the quadrature weights associated with the Adams' methods of orders three to six and the Backward Differentiation Formulae (BDF) methods of orders two to five. These rules, which are referred to as reducible quadrature rules, can then be used in the solution of Volterra integral and integro-differential equations.

2 Specification

SUBROUTINE D05BWF ( METHOD, IORDER, OMEGA, NOMG, LENSW, SW, LDSW, NWT, IFAIL)
INTEGER | IORDER, NOMG, LENSW, LDSW, NWT, IFAIL
REAL (KIND=nag_wp) | OMEGA(NOMG), SW(LDSW,NWT)
CHARACTER(1) | METHOD

3 Description

D05BWF computes the weights W i,j and ωi for a family of quadrature rules related to the Adams' methods of orders three to six and the BDF methods of orders two to five, for approximating the integral:
∫0 t ϕ s ds ≃h ∑ j=0 p-1 W i,j ϕ j×h + h ∑ j=p i ω i-j ϕ j×h ,   0≤t≤T , (1)
with t=i×h, for i=0,1,…,n, for some given constant h.
In (1), h is a uniform mesh, p is related to the order of the method being used and W i,j, ωi are the starting and the convolution weights respectively. The mesh size h is determined as h=Tn, where n=nw+p-1 and nw is the chosen number of convolution weights wj, for j=1,2,…,nw-1. A description of how these weights can be used in the solution of a Volterra integral equation of the second kind is given in Section 9. For a general discussion of these methods, see Wolkenfelt (1982) for more details.

4 References

Lambert J D (1973) Computational Methods in Ordinary Differential Equations John Wiley
Wolkenfelt P H M (1982) The construction of reducible quadrature rules for Volterra integral and integro-differential equations IMA J. Numer. Anal. 2 131–152

5 Arguments

1:   METHOD – CHARACTER(1)Input
On entry: the type of method to be used.
METHOD='A'
For Adams' type formulae.
METHOD='B'
For Backward Differentiation Formulae.
Constraint: METHOD='A' or 'B'.
2:   IORDER – INTEGERInput
On entry: the order of the method to be used. The number of starting weights, p is determined by METHOD and IORDER.
If METHOD='A', p=IORDER-1.
If METHOD='B', p=IORDER.
Constraints:
  • if METHOD='A', 3≤IORDER≤6;
  • if METHOD='B', 2≤IORDER≤5.
3:   OMEGA NOMG – REAL (KIND=nag_wp) arrayOutput
On exit: contains the first NOMG convolution weights.
4:   NOMG – INTEGERInput
On entry: the number of convolution weights, nw.
Constraint: NOMG≥1.
5:   LENSW – INTEGEROutput
On exit: the number of rows in the weights W i,j.
6:   SW LDSWNWT – REAL (KIND=nag_wp) arrayOutput
On exit: SW i j+1 contains the weights W i,j, for i=1,2,…,LENSW and j=0,1,…,NWT-1, where n is as defined in Section 3.
7:   LDSW – INTEGERInput
On entry: the first dimension of the array SW as declared in the (sub)program from which D05BWF is called.
Constraints:
  • if METHOD='A', LDSW≥NOMG+IORDER-2;
  • if METHOD='B', LDSW≥NOMG+IORDER-1.
8:   NWT – INTEGERInput
On entry: p, the number of columns in the starting weights.
Constraints:
  • if METHOD='A', NWT=IORDER-1;
  • if METHOD='B', NWT=IORDER.
9:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, METHOD≠'A' or 'B'.
IFAIL=2
On entry, | IORDER<2 or IORDER>6,
or | NOMG<1.
IFAIL=3
On entry, | METHOD='A' and IORDER=2,
or | METHOD='B' and IORDER=6.
IFAIL=4
On entry, | METHOD='A' and NWT≠IORDER-1,
or | METHOD='B' and NWT≠IORDER.
IFAIL=5
On entry, | METHOD='A' and LDSW<NOMG+IORDER-2,
or | METHOD='B' and LDSW<NOMG+IORDER-1.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

Not applicable.

8 Parallelism and Performance

D05BWF is not threaded in any implementation.

9 Further Comments

Reducible quadrature rules are most appropriate for solving Volterra integral equations (and integro-differential equations). In this section, we propose the following algorithm which you may find useful in solving a linear Volterra integral equation of the form
y t=f t+∫0 t K t,s y s ds,  0≤t≤T, (2)
using D05BWF. In (2), K t,s and f t are given and the solution y t is sought on a uniform mesh of size h such that T=nh. Discretization of (2) yields
yi=f i×h+h∑j=0 p-1 W i,j K i,h,j,h yj+h∑j=p i ω i-j K i,h,j,h yj, (3)
where yi≃y i×h. We propose the following algorithm for computing yi from (3) after a call to D05BWF:
(a) Equation (3) requires starting values, yj, for j=1,2,…,NWT-1, with y 0=f 0. These starting values can be computed by solving the linear system
yi = f i×h + h ∑ j=0 NWT-1 SW i j+1 K i,h,j,h yj ,   i=1,2,…,NWT-1 .
(b) Compute the inhomogeneous terms
σi = f i×h + h ∑ j= 0 NWT-1 SW i j+1 K i,h,j,h yj ,   i=NWT,NWT+ 1,…,n .
(c) Start the iteration for i=NWT,NWT+1,…,n to compute yi from:
1 - h × OMEGA 1 K i,h,i,h y i = σ i + h ∑ j = NWT i - 1 OMEGA i - j + 1 K i,h,j,h y j .
Note that for a nonlinear integral equation, the solution of a nonlinear algebraic system is required at step (a) and a single nonlinear equation at step (c).

10 Example

The following example generates the first ten convolution and thirteen starting weights generated by the fourth-order BDF method.

10.1 Program Text

Program Text (d05bwfe.f90)

10.2 Program Data

None.

10.3 Program Results

Program Results (d05bwfe.r)

D05 Chapter Contents
D05 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


D05BYF : NAG Library, Mark 26

D05 Chapter Contents
D05 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

D05BYF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

D05BYF computes the fractional quadrature weights associated with the Backward Differentiation Formulae (BDF) of orders 4, 5 and 6. These weights can then be used in the solution of weakly singular equations of Abel type.

2 Specification

SUBROUTINE D05BYF ( IORDER, IQ, LENFW, WT, SW, LDSW, WORK, LWK, IFAIL)
INTEGER | IORDER, IQ, LENFW, LDSW, LWK, IFAIL
REAL (KIND=nag_wp) | WT(LENFW), SW(LDSW,2*IORDER-1), WORK(LWK)

3 Description

D05BYF computes the weights W i,j and ωi for a family of quadrature rules related to a BDF method for approximating the integral:
1 π∫0 t ϕ s t-s ds≃h∑j=0 2 p-2 W i,j ϕ j×h+h∑j=2 p-1 i ω i-j ϕ j×h,  0≤t≤T, (1)
with t=i×h i≥0, for some given h. In (1), p is the order of the BDF method used and W i,j, ωi are the fractional starting and the fractional convolution weights respectively. The algorithm for the generation of ωi is based on Newton's iteration. Fast Fourier transform (FFT) techniques are used for computing these weights and subsequently W i,j (see Baker and Derakhshan (1987) and Henrici (1979) for practical details and Lubich (1986) for theoretical details). Some special functions can be represented as the fractional integrals of simpler functions and fractional quadratures can be employed for their computation (see Lubich (1986)). A description of how these weights can be used in the solution of weakly singular equations of Abel type is given in Section 9.

4 References

Baker C T H and Derakhshan M S (1987) Computational approximations to some power series Approximation Theory (eds L Collatz, G Meinardus and G Nürnberger) 81 11–20
Henrici P (1979) Fast Fourier methods in computational complex analysis SIAM Rev. 21 481–529
Lubich Ch (1986) Discretized fractional calculus SIAM J. Math. Anal. 17 704–719

5 Arguments

1:   IORDER – INTEGERInput
On entry: p, the order of the BDF method to be used.
Constraint: 4≤IORDER≤6.
2:   IQ – INTEGERInput
On entry: determines the number of weights to be computed. By setting IQ to a value, 2 IQ+1 fractional convolution weights are computed.
Constraint: IQ≥0.
3:   LENFW – INTEGERInput
On entry: the dimension of the array WT as declared in the (sub)program from which D05BYF is called.
Constraint: LENFW≥2 IQ+2.
4:   WT LENFW – REAL (KIND=nag_wp) arrayOutput
On exit: the first 2 IQ+1 elements of WT contains the fractional convolution weights ωi, for i=0,1,…,2 IQ+1-1. The remainder of the array is used as workspace.
5:   SW LDSW 2×IORDER-1 – REAL (KIND=nag_wp) arrayOutput
On exit: SW i j+1 contains the fractional starting weights W i-1,j , for i=1,2,…,N and j=0,1,…,2×IORDER-2, where N=2 IQ+1+2×IORDER-1.
6:   LDSW – INTEGERInput
On entry: the first dimension of the array SW as declared in the (sub)program from which D05BYF is called.
Constraint: LDSW≥2 IQ+1+2×IORDER-1.
7:   WORK LWK – REAL (KIND=nag_wp) arrayWorkspace
8:   LWK – INTEGERInput
On entry: the dimension of the array WORK as declared in the (sub)program from which D05BYF is called.
Constraint: LWK≥2 IQ+3.
9:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, | IORDER<4 or IORDER>6,
or | IQ<0,
or | LENFW<2 IQ+2,
or | LDSW<2 IQ+1+2×IORDER-1,
or | LWK<2 IQ+3.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

Not applicable.

8 Parallelism and Performance

D05BYF is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
D05BYF makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

Fractional quadrature weights can be used for solving weakly singular integral equations of Abel type. In this section, we propose the following algorithm which you may find useful in solving a linear weakly singular integral equation of the form
y t=f t+1 π∫0 t K t,s y s t-s ds,  0≤t≤T, (2)
using D05BYF. In (2), K t,s and f t are given and the solution y t is sought on a uniform mesh of size h such that T=N×h. Discretization of (2) yields
yi = f i×h + h ∑ j=0 2 p-2 W i,j K i×h,j×h yj + h ∑ j=2 p-1 i ω i-j K i×h,j×h yj , (3)
where yi≃y i×h, for i=1,2,…,N. We propose the following algorithm for computing yi from (3) after a call to D05BYF:
(a) Set N=2 IQ+1+2×IORDER-2 and h=T/N.
(b) Equation (3) requires 2×IORDER-2 starting values, yj, for j=1,2,…,2×IORDER-2, with y 0=f 0. These starting values can be computed by solving the system
yi = f i×h + h ∑ j=0 2×IORDER-2 SW i+1j+1 K i×h,j×h yj ,  i=1,2,…,2×IORDER-2 .
(c) Compute the inhomogeneous terms
σi = f i×h + h ∑ j=0 2×IORDER- 2 SW i+1j+1 K i×h,j×h yj ,   i = 2 × IORDER-1 , 2×IORDER , … , N .
(d) Start the iteration for i=2×IORDER-1,2×IORDER,…,N to compute yi from:
1 - h WT 1 K i×h,i×h yi = σi + h ∑ j=2×IORDER-1 i-1 WT i-j+1 K i×h,j×h yj .
Note that for nonlinear weakly singular equations, the solution of a nonlinear algebraic system is required at step (b) and a single nonlinear equation at step (d).

10 Example

The following example generates the first 16 fractional convolution and 23 fractional starting weights generated by the fourth-order BDF method.

10.1 Program Text

Program Text (d05byfe.f90)

10.2 Program Data

None.

10.3 Program Results

Program Results (d05byfe.r)

D05 Chapter Contents
D05 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


D05 Chapter Contents : NAG Library Manual, Mark 26

D05 Chapter Introduction
NAG Library Manual

NAG Library Chapter Contents

D05 – Integral Equations

D05 Chapter Introduction – a description of the Chapter and an overview of the algorithms available

Routine Name | Mark of Introduction | Purpose
D05AAF Example Text | 5 | nagf_inteq_fredholm2_split Linear nonsingular Fredholm integral equation, second kind, split kernel
D05ABF Example Text | 6 | nagf_inteq_fredholm2_smooth Linear nonsingular Fredholm integral equation, second kind, smooth kernel
D05BAF Example Text | 14 | nagf_inteq_volterra2 Nonlinear Volterra convolution equation, second kind
D05BDF Example Text | 16 | nagf_inteq_abel2_weak Nonlinear convolution Volterra–Abel equation, second kind, weakly singular
D05BEF Example Text | 16 | nagf_inteq_abel1_weak Nonlinear convolution Volterra–Abel equation, first kind, weakly singular
D05BWF Example Text | 16 | nagf_inteq_volterra_weights Generate weights for use in solving Volterra equations
D05BYF Example Text | 16 | nagf_inteq_abel_weak_weights Generate weights for use in solving weakly singular Abel-type equations
D05 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


D05 Chapter Introduction : NAG Library, Mark 26

D05 Chapter Contents
NAG Library Manual

NAG Library Chapter Introduction

D05 – Integral Equations

▸▿ Contents

1 Scope of the Chapter
▸▿ 2 Background to the Problems
2.1 Introduction
2.2 Classification of Integral Equations
2.3 Structure of Kernel
2.4 Singular and Weakly Singular Equations
▸▿ 2.5 Fredholm Integral Equations
2.5.1 Eigenvalue problem
2.5.2 Equations of the first kind
2.5.3 Equations of the second kind
▸▿ 2.6 Volterra Integral Equations
2.6.1 Equations of the first kind
2.6.2 Equations of the second kind
▸▿ 3 Recommendations on Choice and Use of Available Routines
3.1 Fredholm Equations of the Second Kind
3.2 Volterra Equations of the Second Kind
3.3 Volterra Equations of the First Kind
3.4 Utility Routines
3.5 User-supplied Routines
4 Functionality Index
5 Auxiliary Routines Associated with Library Routine Arguments
6 Routines Withdrawn or Scheduled for Withdrawal
7 References

1 Scope of the Chapter

This chapter is concerned with the numerical solution of integral equations. Provision will be made for most of the standard types of equation (see Section 2). The following are, however, specifically excluded:
(a) | Equations arising in the solution of partial differential equations by integral equation methods. In cases where the prime purpose of an algorithm is the solution of a partial differential equation it will normally be included in Chapter D03.
(b) | Calculation of inverse integral transforms. This problem falls within the scope of Chapter C06.

2 Background to the Problems

2.1 Introduction

Any functional equation in which the unknown function appears under the sign of integration is called an integral equation. Integral equations arise in a great many branches of science; for example, in potential theory, acoustics, elasticity, fluid mechanics, radiative transfer, theory of population, etc. In many instances the integral equation originates from the conversion of a boundary value problem or an initial value problem associated with a partial or an ordinary differential equation, but many problems lead directly to integral equations and cannot be formulated in terms of differential equations.
Integral equations are of many types; here we attempt to indicate some of the main distinguishing features with particular regard to the use and construction of algorithms.

2.2 Classification of Integral Equations

In the classical theory of integral equations one distinguishes between Fredholm equations and Volterra equations. In a Fredholm equation the region of integration is fixed, whereas in a Volterra equation the region is variable. Thus, the equation
cy t=f t+λ∫ab K t,s,y s ds,  a≤t≤b (1)
is an example of Fredholm equation, and the equation
cy t=f t+λ∫at K t,s,y s ds,  a≤t (2)
is an example of a Volterra equation.
Here the forcing function f t and the kernel function K t,s,y s are prescribed, while y t is the unknown function to be determined. (More generally the integration and the domain of definition of the functions may extend to more than one dimension.) The parameter λ is often omitted; it is, however, of importance in certain theoretical investigations (e.g., stability) and in the eigenvalue problem discussed below.
If in (1) or (2), c=0, the integral equation is said to be of the first kind. If c=1, the equation is said to be of the second kind.
Equations (1) and (2) are linear if the kernel K t,s,y s=k t,s y s, otherwise they are nonlinear.
Note: in a linear integral equation, k t,s is usually referred to as the kernel. We adopt this convention throughout.
These two types of equations are broadly analogous to problems of initial- and boundary value type for an ordinary differential equation (ODE); thus the Volterra equation, characterised by a variable upper limit of integration, is amenable to solution by methods of marching type whilst most methods for treating Fredholm equations lead ultimately to the solution of an approximating system of simultaneous algebraic equations. For comprehensive discussion of numerical methods see Atkinson (1976), Baker (1977), Brunner and van der Houwen (1986) and Delves and Walsh (1974). In what follows, the term ‘integral equation’ is used in its general sense, and the type is distinguished when appropriate.

2.3 Structure of Kernel

When considering numerical methods for integral equations, particular attention should be paid to the character of the kernel, which is usually the main factor governing the choice of an appropriate quadrature formula or system of approximating functions. Various commonly occurring types of singularity call for individual treatment.
Likewise provision can be made for cases of symmetry, periodicity or other special structure, where the solution may have special properties and/or economies may be effected in the solution process. We note in particular the following cases to which we shall often have occasion to refer in the description of individual algorithms.
(a) | A linear integral equation with a kernel k t,s=k s,t is said to be symmetric. This property plays a key role in the theory of Fredholm integral equations.
(b) | If k t,s=k a+b-t,a+b-s in a linear integral equation, the kernel is called centro-symmetric.
(c) | If in Equations (1) or (2) the kernel has the form K t,s,y s=k t-s g s,y s, the equation is called a convolution integral equation; in the linear case g s,y s=y s.
(d) If the kernel in (1) has the form
K t,s,y s=K 1 t,s,y s,  a≤s≤t, K t,s,y s=K 2 t,s,y s,  t<s≤b,
where the functions K 1 and K 2 are well behaved, whilst K or its s-derivative is possibly discontinuous, may be described as discontinuous or of ‘split’ type; in the linear case K t,s,y s=k t,s y s and consequently K 1=k 1 y and K 2=k 2 y. Examples are the commonly occurring kernels of the type k t-s and the Green's functions (influence functions) which arise in the conversion of ODE boundary value problems to integral equations. It is also of interest to note that the Volterra equation (2) may be conceived as a Fredholm equation with kernel of split type, with K 2 t,s,y s≡0; consequently methods designed for the solution of Fredholm equations with split kernels are also applicable to Volterra equations.

2.4 Singular and Weakly Singular Equations

An integral equation may be called singular if either
(a) | its kernel contains a singularity, or
(b) | the range of integration is infinite,
and it is said to be weakly singular if the kernel becomes infinite at s=t.
Sometimes a solution can be effected by a simple adaptation of a method applicable to a nonsingular equation: for example, an infinite range may be truncated at a suitably chosen point. In other cases, however, theoretical considerations will dictate the need for special methods and algorithms. Examples are:
(i) | Integral equations with singular kernels of Cauchy type;
(ii) | Equations of Wiener–Hopf type;
(iii) | Various dual integral equations arising in the solution of boundary value problems of mathematical physics;
(iv) | The well-known Abel integral equation, an equation of Volterra type, whose kernel contains an inverse square root singularity at s=t.
Problems of inversion of integral transforms also fall under this heading but, as already remarked, they lie outside the scope of this chapter.

2.5 Fredholm Integral Equations

2.5.1 Eigenvalue problem

Closely connected with the linear Fredholm integral equation of the second kind is the eigenvalue problem represented by the homogeneous equation
y t-λ∫ab k t,s y s ds=0,  a≤t≤b. (3)
If λ is chosen arbitrarily this equation in general possesses only the trivial solution y t=0. However, for a certain critical set of values of λ, the characteristic values or eigenvalues (the latter term is sometimes reserved for the reciprocals μ=1/λ), there exist nontrivial solutions y t, termed characteristic functions or eigenfunctions, which are of fundamental importance in many investigations. The analogy with the eigenproblem of linear algebra is readily apparent, and indeed most methods of solution of equation (3) entail reduction to an approximately equivalent algebraic problem
K-μI y=0. (4)

2.5.2 Equations of the first kind

The Fredholm integral equation of the first kind
∫ab k t,s y s ds=f t,  a≤t≤b, (5)
belong to the class of ‘ill-posed’ problems; even supposing that a solution corresponding to the prescribed f t exists, a slight perturbation of f t may give rise to an arbitrarily large variation in the solution y t. Hence the equation may be closely satisfied by a function bearing little resemblance to the ‘true’ solution. The difficulty associated with this instability is aggravated by the fact that in practice the specification of f t is usually inexact.
Nevertheless a great many physical problems (e.g., in radiography, spectroscopy, stereology, chemical analysis) are appropriately formulated in terms of integral equations of the first kind, and useful and meaningful ‘solutions’ can be obtained with the aid of suitable stabilizing procedures. See Chapters 12 and 13 of Delves and Walsh (1974) for further discussion and references.

2.5.3 Equations of the second kind

Consider the nonlinear Fredholm equation of the second kind
y t=f t+∫ab K t,s,y s ds,  a≤t≤b. (6)
The numerical solution of equation (6) is usually accomplished either by simple iteration or by a more sophisticated iterative scheme based on Newton's method; in the latter case it is necessary to solve a sequence of linear integral equations. Convergence may be demonstrated subject to suitable conditions of Lipschitz continuity of the functions K with respect to the parameter y.
Examples of Fredholm type (for which the provision of algorithms is contemplated) are:
(a) the Uryson equation
u t-∫01 F t,s,u s ds=0,  0≤t≤1, (7)
(b) the Hammerstein equation
u t-∫01 k t,s g s,u s ds=0,  0≤t≤1, (8)
where F and g are arbitrary functions.

2.6 Volterra Integral Equations

2.6.1 Equations of the first kind

Consider the Volterra integral equation of the first kind
∫at k t,s y s ds=f t,  a≤t. (9)
Clearly it is necessary that f a=0; otherwise no solution to (9) can exist. The following types of Volterra integral equations of the first kind occur in real life problems:
  • equations with unbounded kernel at s=t,
  • equations with sufficiently smooth kernel.
These types belong also to the class of ‘ill-posed’ problems. However, the instability is appreciably less severe in the equations with unbounded kernel. In general, a nonsingular Volterra equation of the first kind presents less computational difficulty than the Fredholm equation (5) with a smooth kernel.
A Volterra equation of the first kind may, under suitable conditions, be converted by differentiation to one of the second kind or by integration by parts to an equation of the second kind for the integral of the wanted function.

2.6.2 Equations of the second kind

A very general Volterra equation of the second kind is given by
y t=f t+∫at K t,s,y s ds,  a≤t. (10)
The resemblance of Volterra equations to ODEs suggests that the underlying methods for ODE problems can be applied to Volterra equations. Indeed this turns out to be the case. The main advantages of implementing these methods are their well-developed theoretical background, i.e., convergence and stability; see Brunner and van der Houwen (1986) and Wolkenfelt (1982).
Many Volterra integral equations arising in real life problems have a convolution kernel (see Section 2.3(c)); see Brunner and van der Houwen (1986) for references. However, a subclass of these equations which have kernels of the form
k t-s=∑j=0 M λj t-s j, (11)
where λj are real, can be converted into a system of linear or nonlinear ODEs; see Brunner and van der Houwen (1986).
For more information on the theoretical and the numerical treatment of integral equations we refer you to Atkinson (1976), Baker (1977), Brunner and van der Houwen (1986), Cochran (1972) and Delves and Walsh (1974).

3 Recommendations on Choice and Use of Available Routines

The choice of routine will depend first of all upon the type of integral equation to be solved.

3.1 Fredholm Equations of the Second Kind

(a) Linear equations
D05AAF is applicable to an equation with a discontinuous or ‘split’ kernel as defined in Section 2.3(d). Here, however, both the functions k 1 and k 2 are required to be defined (and well-behaved) throughout the square a≤s, t≤b.
D05ABF is applicable to an equation with a smooth kernel. Note that D05AAF may also be applied to this case, by setting k 1=k 2=k, but D05ABF is more efficient.

3.2 Volterra Equations of the Second Kind

(a) Linear equations
D05AAF may be used to solve a Volterra equation by defining k 2 (or k 1) to be identically zero. (See also (b).)
(b) Nonlinear equations
D05BAF is applicable to a nonlinear convolution Volterra integral equation of the second kind. The kernel function has the form
K t,s,y s=k t-s g s,y s.
The underlying methods used in the routine are the reducible linear multistep methods. You have a choice of variety of these methods. This routine can also be used for linear g.
D05BDF is applicable to a nonlinear convolution equation having a weakly-singular kernel (Abel). The kernel function has the form
K t,s,y s=k t-s t-s g s,y s.
The underlying methods used in the routine are the fractional linear multistep methods based on Backward Difference Formula (BDF, see Section 3.1 in the D02 Chapter Introduction) methods. This routine can also be used for linear g.

3.3 Volterra Equations of the First Kind

(a) Linear equations
See (b).
(b) Nonlinear equations
D05BEF is applicable to a nonlinear equation having a weakly-singular kernel (Abel). The kernel function has the form
K t,s,y s=k t-s t-s g s,y s.
The underlying methods used in the routine are the fractional linear multistep methods based on BDF methods. This routine can also be used for linear g.

3.4 Utility Routines

D05BWF generates the weights associated with Adams' and BDF linear multistep methods. These weights can be used for the solution of nonsingular Volterra integral and integro-differential equations of general type.
D05BYF generates the weights associated with BDF linear multistep methods. These weights can be used for the solution of weakly-singular Volterra (Abel) integral equations of general type.

3.5 User-supplied Routines

Many of the routines in this chapter require you to supply procedures defining the kernels and other given functions in the equations. It is important to test these independently before using them in conjunction with NAG Library routines.

4 Functionality Index

Fredholm equation of second kind,
linear,
nonsingular discontinuous or ‘split’ kernel D05AAF
nonsingular smooth kernel D05ABF
Volterra equation of first kind,
nonlinear,
weakly-singular,
convolution equation (Abel): D05BEF
Volterra equation of second kind,
nonlinear,
nonsingular,
convolution equation D05BAF
weakly-singular,
convolution equation (Abel): D05BDF
Weight generating routines,
weights for general solution of Volterra equations D05BWF
weights for general solution of Volterra equations with weakly-singular kernel D05BYF

5 Auxiliary Routines Associated with Library Routine Arguments

None.

6 Routines Withdrawn or Scheduled for Withdrawal

None.

7 References

Atkinson K E (1976) A Survey of Numerical Methods for the Solution of Fredholm Integral Equations of the Second Kind SIAM, Philadelphia
Baker C T H (1977) The Numerical Treatment of Integral Equations Oxford University Press
Brunner H and van der Houwen P J (1986) The Numerical Solution of Volterra Equations CWI Monographs, North-Holland, Amsterdam
Cochran J A (1972) The Analysis of Linear Integral Equations McGraw–Hill
Delves L M and Walsh J (1974) Numerical Solution of Integral Equations Clarendon Press, Oxford
Wolkenfelt P H M (1982) The construction of reducible quadrature rules for Volterra integral and integro-differential equations IMA J. Numer. Anal. 2 131–152
D05 Chapter Contents
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


D06AAF : NAG Library, Mark 26

D06 Chapter Contents
D06 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

D06AAF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

D06AAF generates a triangular mesh of a closed polygonal region in ℝ 2, given a mesh of its boundary. It uses a simple incremental method.

2 Specification

SUBROUTINE D06AAF ( NVB, NVMAX, NEDGE, EDGE, NV, NELT, COOR, CONN, BSPACE, SMOOTH, COEF, POWER, ITRACE, RWORK, LRWORK, IWORK, LIWORK, IFAIL)
INTEGER | NVB, NVMAX, NEDGE, EDGE(3,NEDGE), NV, NELT, CONN(3,2*(NVMAX-1)), ITRACE, LRWORK, IWORK(LIWORK), LIWORK, IFAIL
REAL (KIND=nag_wp) | COOR(2,NVMAX), BSPACE(NVB), COEF, POWER, RWORK(LRWORK)
LOGICAL | SMOOTH

3 Description

D06AAF generates the set of interior vertices using a process based on a simple incremental method. A smoothing of the mesh is optionally available. For more details about the triangulation method, consult the D06 Chapter Introduction as well as George and Borouchaki (1998).
This routine is derived from material in the MODULEF package from INRIA (Institut National de Recherche en Informatique et Automatique).

4 References

George P L and Borouchaki H (1998) Delaunay Triangulation and Meshing: Application to Finite Elements Editions HERMES, Paris

5 Arguments

1:   NVB – INTEGERInput
On entry: the number of vertices in the input boundary mesh.
Constraint: 3≤NVB≤NVMAX.
2:   NVMAX – INTEGERInput
On entry: the maximum number of vertices in the mesh to be generated.
3:   NEDGE – INTEGERInput
On entry: the number of boundary edges in the input mesh.
Constraint: NEDGE≥1.
4:   EDGE 3 NEDGE – INTEGER arrayInput
On entry: the specification of the boundary edges. EDGE 1 j and EDGE 2 j contain the vertex numbers of the two end points of the jth boundary edge. EDGE 3 j is a user-supplied tag for the jth boundary edge and is not used by D06AAF.
Constraint: 1≤EDGE ij≤NVB and EDGE 1 j≠EDGE 2 j, for i=1,2 and j=1,2,…,NEDGE.
5:   NV – INTEGEROutput
On exit: the total number of vertices in the output mesh (including both boundary and interior vertices). If NVB=NVMAX, no interior vertices will be generated and NV=NVB.
6:   NELT – INTEGEROutput
On exit: the number of triangular elements in the mesh.
7:   COOR 2 NVMAX – REAL (KIND=nag_wp) arrayInput/Output
On entry: COOR 1 i contains the x coordinate of the ith input boundary mesh vertex; while COOR 2 i contains the corresponding y coordinate, for i=1,2,…,NVB.
On exit: COOR 1 i will contain the x coordinate of the i-NVBth generated interior mesh vertex; while COOR 2 i will contain the corresponding y coordinate, for i=NVB+1,…,NV. The remaining elements are unchanged.
8:   CONN 3 2×NVMAX-1 – INTEGER arrayOutput
On exit: the connectivity of the mesh between triangles and vertices. For each triangle j, CONN ij gives the indices of its three vertices (in anticlockwise order), for i=1,2,3 and j=1,2,…,NELT.
9:   BSPACE NVB – REAL (KIND=nag_wp) arrayInput
On entry: the desired mesh spacing (triangle diameter, which is the length of the longer edge of the triangle) near the boundary vertices.
Constraint: BSPACE i>0.0, for i=1,2,…,NVB.
10:   SMOOTH – LOGICALInput
On entry: indicates whether or not mesh smoothing should be performed.
If SMOOTH=.TRUE., the smoothing is performed; otherwise no smoothing is performed.
11:   COEF – REAL (KIND=nag_wp)Input
On entry: the coefficient in the stopping criteria for the generation of interior vertices. This argument controls the triangle density and the number of triangles generated is in O COEF 2. The mesh will be finer if COEF is greater than 0.7165 and 0.75 is a good value.
Suggested value: 0.75.
12:   POWER – REAL (KIND=nag_wp)Input
On entry: controls the rate of change of the mesh size during the generation of interior vertices. The smaller the value of POWER, the faster the decrease in element size away from the boundary.
Suggested value: 0.25.
Constraint: 0.1≤POWER≤10.0.
13:   ITRACE – INTEGERInput
On entry: the level of trace information required from D06AAF.
ITRACE≤0
No output is generated.
ITRACE≥1
Output from the meshing solver is printed on the current advisory message unit (see X04ABF). This output contains details of the vertices and triangles generated by the process.
You are advised to set ITRACE=0, unless you are experienced with finite element mesh generation.
14:   RWORK LRWORK – REAL (KIND=nag_wp) arrayWorkspace
15:   LRWORK – INTEGERInput
On entry: the dimension of the array RWORK as declared in the (sub)program from which D06AAF is called.
Constraint: LRWORK≥NVMAX.
16:   IWORK LIWORK – INTEGER arrayWorkspace
17:   LIWORK – INTEGERInput
On entry: the dimension of the array IWORK as declared in the (sub)program from which D06AAF is called.
Constraint: LIWORK≥16×NVMAX+2×NEDGE+max 4×NVMAX+2,NEDGE-14.
18:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, | NVB<3 or NVB>NVMAX,
or | NEDGE<1,
or | EDGE ij<1 or EDGE ij>NVB, for some i=1,2 and j=1,2,…,NEDGE,
or | EDGE 1 j=EDGE 2 j, for some j=1,2,…,NEDGE,
or | BSPACE i≤0.0, for some i=1,2,…,NVB,
or | POWER<0.1 or POWER>10.0,
or | LIWORK<16×NVMAX+2×NEDGE+max 4×NVMAX+2,NEDGE-14,
or | LRWORK<NVMAX.
IFAIL=2
An error has occurred during the generation of the interior mesh. Check the definition of the boundary (arguments COOR and EDGE) as well as the orientation of the boundary (especially in the case of a multiple connected component boundary). Setting ITRACE>0 may provide more details.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

Not applicable.

8 Parallelism and Performance

D06AAF is not threaded in any implementation.

9 Further Comments

The position of the internal vertices is a function of the positions of the vertices on the given boundary. A fine mesh on the boundary results in a fine mesh in the interior. The algorithm allows you to obtain a denser interior mesh by varying NVMAX, BSPACE, COEF and POWER. But you are advised to manipulate the last two arguments with care.
You are advised to take care to set the boundary inputs properly, especially for a boundary with multiply connected components. The orientation of the interior boundaries should be in clockwise order and opposite to that of the exterior boundary. If the boundary has only one connected component, its orientation should be anticlockwise.

10 Example

In this example, a geometry with two holes (two interior circles inside an exterior one) is meshed using the simple incremental method (see the D06 Chapter Introduction). The exterior circle is centred at the origin with a radius 1.0, the first interior circle is centred at the point -0.5,0.0 with a radius 0.49, and the second one is centred at the point -0.5,0.65 with a radius 0.15. Note that the points -1.0,0.0 and -0.5,0.5) are points of ‘near tangency’ between the exterior circle and the first and second circles.
The boundary mesh has 100 vertices and 100 edges (see Figure 1 in Section 10.3). Note that the particular mesh generated could be sensitive to the machine precision and therefore may differ from one implementation to another. Figure 2 in Section 10.3 contains the output mesh.

10.1 Program Text

Program Text (d06aafe.f90)

10.2 Program Data

Program Data (d06aafe.d)

10.3 Program Results

Program Results (d06aafe.r)

GnuplotProduced by GNUPLOT 4.6 patchlevel 3 Example Program Figure 1: The Geometry of Circular Region With Two Holes gnuplot_plot_1
GnuplotProduced by GNUPLOT 4.6 patchlevel 3 Figure 2: Mesh Generated on the Geometry With Two Holes gnuplot_plot_1
D06 Chapter Contents
D06 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


D06ABF : NAG Library, Mark 26

D06 Chapter Contents
D06 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

D06ABF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

D06ABF generates a triangular mesh of a closed polygonal region in ℝ 2, given a mesh of its boundary. It uses a Delaunay–Voronoi process, based on an incremental method.

2 Specification

SUBROUTINE D06ABF ( NVB, NVINT, NVMAX, NEDGE, EDGE, NV, NELT, COOR, CONN, WEIGHT, NPROPA, ITRACE, RWORK, LRWORK, IWORK, LIWORK, IFAIL)
INTEGER | NVB, NVINT, NVMAX, NEDGE, EDGE(3,NEDGE), NV, NELT, CONN(3,2*NVMAX+5), NPROPA, ITRACE, LRWORK, IWORK(LIWORK), LIWORK, IFAIL
REAL (KIND=nag_wp) | COOR(2,NVMAX), WEIGHT(*), RWORK(LRWORK)

3 Description

D06ABF generates the set of interior vertices using a Delaunay–Voronoi process, based on an incremental method. It allows you to specify a number of fixed interior mesh vertices together with weights which allow concentration of the mesh in their neighbourhood. For more details about the triangulation method, consult the D06 Chapter Introduction as well as George and Borouchaki (1998).
This routine is derived from material in the MODULEF package from INRIA (Institut National de Recherche en Informatique et Automatique).

4 References

George P L and Borouchaki H (1998) Delaunay Triangulation and Meshing: Application to Finite Elements Editions HERMES, Paris

5 Arguments

1:   NVB – INTEGERInput
On entry: the number of vertices in the input boundary mesh.
Constraint: NVB≥3.
2:   NVINT – INTEGERInput
On entry: the number of fixed interior mesh vertices to which a weight will be applied.
Constraint: NVINT≥0.
3:   NVMAX – INTEGERInput
On entry: the maximum number of vertices in the mesh to be generated.
Constraint: NVMAX≥NVB+NVINT.
4:   NEDGE – INTEGERInput
On entry: the number of boundary edges in the input mesh.
Constraint: NEDGE≥1.
5:   EDGE 3 NEDGE – INTEGER arrayInput
On entry: the specification of the boundary edges. EDGE 1 j and EDGE 2 j contain the vertex numbers of the two end points of the jth boundary edge. EDGE 3 j is a user-supplied tag for the jth boundary edge and is not used by D06ABF.
Constraint: 1≤EDGE ij≤NVB and EDGE 1 j≠EDGE 2 j, for i=1,2 and j=1,2,…,NEDGE.
6:   NV – INTEGEROutput
On exit: the total number of vertices in the output mesh (including both boundary and interior vertices). If NVB+NVINT=NVMAX, no interior vertices will be generated and NV=NVMAX.
7:   NELT – INTEGEROutput
On exit: the number of triangular elements in the mesh.
8:   COOR 2 NVMAX – REAL (KIND=nag_wp) arrayInput/Output
On entry: COOR 1 i contains the x coordinate of the ith input boundary mesh vertex, for i=1,2,…,NVB. COOR 1 i contains the x coordinate of the i-NVBth fixed interior vertex, for i=NVB+1,…,NVB+NVINT. For boundary and interior vertices, COOR 2 i contains the corresponding y coordinate, for i=1,2,…,NVB+NVINT.
On exit: COOR 1 i will contain the x coordinate of the i-NVB-NVINTth generated interior mesh vertex, for i=NVB+NVINT+1,…,NV; while COOR 2 i will contain the corresponding y coordinate. The remaining elements are unchanged.
9:   CONN 3 2×NVMAX+5 – INTEGER arrayOutput
On exit: the connectivity of the mesh between triangles and vertices. For each triangle j, CONN ij gives the indices of its three vertices (in anticlockwise order), for i=1,2,3 and j=1,2,…,NELT.
10:   WEIGHT* – REAL (KIND=nag_wp) arrayInput
Note: the dimension of the array WEIGHT must be at least max 1,NVINT.
On entry: the weight of fixed interior vertices. It is the diameter of triangles (length of the longer edge) created around each of the given interior vertices.
Constraint: if NVINT>0, WEIGHT i>0.0, for i=1,2,…,NVINT.
11:   NPROPA – INTEGERInput
On entry: the propagation type and coefficient, the argument NPROPA is used when the internal points are created. They are distributed in a geometric manner if NPROPA is positive and in an arithmetic manner if it is negative. For more details see Section 9.
Constraint: NPROPA≠0.
12:   ITRACE – INTEGERInput
On entry: the level of trace information required from D06ABF.
ITRACE≤0
No output is generated.
ITRACE≥1
Output from the meshing solver is printed on the current advisory message unit (see X04ABF). This output contains details of the vertices and triangles generated by the process.
You are advised to set ITRACE=0, unless you are experienced with finite element mesh generation.
13:   RWORK LRWORK – REAL (KIND=nag_wp) arrayWorkspace
14:   LRWORK – INTEGERInput
On entry: the dimension of the array RWORK as declared in the (sub)program from which D06ABF is called.
Constraint: LRWORK≥12×NVMAX+15.
15:   IWORK LIWORK – INTEGER arrayWorkspace
16:   LIWORK – INTEGERInput
On entry: the dimension of the array IWORK as declared in the (sub)program from which D06ABF is called.
Constraint: LIWORK≥6×NEDGE+32×NVMAX+2×NVB+78.
17:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, | NVB<3,
or | NVINT<0,
or | NVB+NVINT>NVMAX,
or | NEDGE<1,
or | EDGE ij<1 or EDGE ij>NVB, for some i=1,2 and j=1,2,…,NEDGE,
or | EDGE 1 j=EDGE 2 j, for some j=1,2,…,NEDGE,
or | NPROPA=0;
or | if NVINT>0, WEIGHT i≤0.0, for some i=1,2,…,NVINT;
or | LRWORK<12×NVMAX+15,
or | LIWORK<6×NEDGE+32×NVMAX+2×NVB+78.
IFAIL=2
An error has occurred during the generation of the interior mesh. Check the definition of the boundary (arguments COOR and EDGE) as well as the orientation of the boundary (especially in the case of a multiple connected component boundary). Setting ITRACE>0 may provide more details.
IFAIL=3
An error has occurred during the generation of the boundary mesh. It appears that NVMAX is not large enough.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

Not applicable.

8 Parallelism and Performance

D06ABF makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The position of the internal vertices is a function position of the vertices on the given boundary. A fine mesh on the boundary results in a fine mesh in the interior. To dilute the influence of the data on the interior of the domain, the value of NPROPA can be changed. The propagation coefficient is calculated as: ω=1+ a-1.0 20.0 , where a is the absolute value of NPROPA. During the process vertices are generated on edges of the mesh Ti to obtain the mesh T i+1 in the general incremental method (consult the D06 Chapter Introduction or George and Borouchaki (1998)). This generation uses the coefficient ω, and it is geometric if NPROPA>0, and arithmetic otherwise. But increasing the value of a may lead to failure of the process, due to precision, especially in geometries with holes. So you are advised to manipulate the argument NPROPA with care.
You are advised to take care to set the boundary inputs properly, especially for a boundary with multiply connected components. The orientation of the interior boundaries should be in clockwise order and opposite to that of the exterior boundary. If the boundary has only one connected component, its orientation should be anticlockwise.

10 Example

In this example, a geometry with two holes (two wings inside an exterior circle) is meshed using a Delaunay–Voronoi method. The exterior circle is centred at the point 1.0,0.0 with a radius 3. The main wing, using aerofoil RAE 2822 data, lies between the origin and the centre of the circle, while the secondary aerofoil is produced from the first by performing a translation, a scale reduction and a rotation. To be able to carry out some realistic computation on that geometry, some interior points have been introduced to have a finer mesh in the wake of those aerofoils.
The boundary mesh has 296 vertices and 296 edges (see Section 10.3 top). Note that the particular mesh generated could be sensitive to the machine precision and therefore may differ from one implementation to another. The interior meshes for different values of NPROPA are given in Section 10.3.

10.1 Program Text

Program Text (d06abfe.f90)

10.2 Program Data

Program Data (d06abfe.d)

10.3 Program Results

Program Results (d06abfe.r)

GnuplotProduced by GNUPLOT 4.6 patchlevel 3 Example Program Geometry for Generating Meshes gnuplot_plot_1
GnuplotProduced by GNUPLOT 4.6 patchlevel 3 Mesh Generated Using Arithmetic Coefficient ω=1.2 gnuplot_plot_1
GnuplotProduced by GNUPLOT 4.6 patchlevel 3 Mesh Generated Using Arithmetic Coefficient ω=1.0 gnuplot_plot_1
GnuplotProduced by GNUPLOT 4.6 patchlevel 3 Mesh Generated Using Geometric Coefficient ω=1.0 gnuplot_plot_1
D06 Chapter Contents
D06 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


D06ACF : NAG Library, Mark 26

D06 Chapter Contents
D06 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

D06ACF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

D06ACF generates a triangular mesh of a closed polygonal region in ℝ 2, given a mesh of its boundary. It uses an Advancing Front process, based on an incremental method.

2 Specification

SUBROUTINE D06ACF ( NVB, NVINT, NVMAX, NEDGE, EDGE, NV, NELT, COOR, CONN, WEIGHT, ITRACE, RWORK, LRWORK, IWORK, LIWORK, IFAIL)
INTEGER | NVB, NVINT, NVMAX, NEDGE, EDGE(3,NEDGE), NV, NELT, CONN(3,2*NVMAX+5), ITRACE, LRWORK, IWORK(LIWORK), LIWORK, IFAIL
REAL (KIND=nag_wp) | COOR(2,NVMAX), WEIGHT(*), RWORK(LRWORK)

3 Description

D06ACF generates the set of interior vertices using an Advancing Front process, based on an incremental method. It allows you to specify a number of fixed interior mesh vertices together with weights which allow concentration of the mesh in their neighbourhood. For more details about the triangulation method, consult the D06 Chapter Introduction as well as George and Borouchaki (1998).
This routine is derived from material in the MODULEF package from INRIA (Institut National de Recherche en Informatique et Automatique).

4 References

George P L and Borouchaki H (1998) Delaunay Triangulation and Meshing: Application to Finite Elements Editions HERMES, Paris

5 Arguments

1:   NVB – INTEGERInput
On entry: the number of vertices in the input boundary mesh.
Constraint: NVB≥3.
2:   NVINT – INTEGERInput
On entry: the number of fixed interior mesh vertices to which a weight will be applied.
Constraint: NVINT≥0.
3:   NVMAX – INTEGERInput
On entry: the maximum number of vertices in the mesh to be generated.
Constraint: NVMAX≥NVB+NVINT.
4:   NEDGE – INTEGERInput
On entry: the number of boundary edges in the input mesh.
Constraint: NEDGE≥1.
5:   EDGE 3 NEDGE – INTEGER arrayInput
On entry: the specification of the boundary edges. EDGE 1 j and EDGE 2 j contain the vertex numbers of the two end points of the jth boundary edge. EDGE 3 j is a user-supplied tag for the jth boundary edge and is not used by D06ACF.
Constraint: 1≤EDGE ij≤NVB and EDGE 1 j≠EDGE 2 j, for i=1,2 and j=1,2,…,NEDGE.
6:   NV – INTEGEROutput
On exit: the total number of vertices in the output mesh (including both boundary and interior vertices). If NVB+NVINT=NVMAX, no interior vertices will be generated and NV=NVMAX.
7:   NELT – INTEGEROutput
On exit: the number of triangular elements in the mesh.
8:   COOR 2 NVMAX – REAL (KIND=nag_wp) arrayInput/Output
On entry: COOR 1 i contains the x coordinate of the ith input boundary mesh vertex, for i=1,2,…,NVB. COOR 1 i contains the x coordinate of the i-NVBth fixed interior vertex, for i=NVB+1,…,NVB+NVINT. For boundary and interior vertices, COOR 2 i contains the corresponding y coordinate, for i=1,2,…,NVB+NVINT.
On exit: COOR 1 i will contain the x coordinate of the i-NVB-NVINTth generated interior mesh vertex, for i=NVB+NVINT+1,…,NV; while COOR 2 i will contain the corresponding y coordinate. The remaining elements are unchanged.
9:   CONN 3 2×NVMAX+5 – INTEGER arrayOutput
On exit: the connectivity of the mesh between triangles and vertices. For each triangle j, CONN ij gives the indices of its three vertices (in anticlockwise order), for i=1,2,3 and j=1,2,…,NELT.
10:   WEIGHT* – REAL (KIND=nag_wp) arrayInput
Note: the dimension of the array WEIGHT must be at least max 1,NVINT.
On entry: the weight of fixed interior vertices. It is the diameter of triangles (length of the longer edge) created around each of the given interior vertices.
Constraint: if NVINT>0, WEIGHT i>0.0, for i=1,2,…,NVINT.
11:   ITRACE – INTEGERInput
On entry: the level of trace information required from D06ACF.
ITRACE≤0
No output is generated.
ITRACE≥1
Output from the meshing solver is printed on the current advisory message unit (see X04ABF). This output contains details of the vertices and triangles generated by the process.
You are advised to set ITRACE=0, unless you are experienced with finite element mesh generation.
12:   RWORK LRWORK – REAL (KIND=nag_wp) arrayWorkspace
13:   LRWORK – INTEGERInput
On entry: the dimension of the array RWORK as declared in the (sub)program from which D06ACF is called.
Constraint: LRWORK≥12×NVMAX+30015.
14:   IWORK LIWORK – INTEGER arrayWorkspace
15:   LIWORK – INTEGERInput
On entry: the dimension of the array IWORK as declared in the (sub)program from which D06ACF is called.
Constraint: LIWORK≥8×NEDGE+53×NVMAX+2×NVB+10078.
16:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, | NVB<3,
or | NVINT<0,
or | NVB+NVINT>NVMAX,
or | NEDGE<1,
or | EDGE ij<1 or EDGE ij>NVB, for some i=1,2 and j=1,2,…,NEDGE,
or | EDGE 1 j=EDGE 2 j, for some j=1,2,…,NEDGE,
or | if NVINT>0, WEIGHT i≤0.0, for some i=1,2,…,NVINT;
or | LRWORK<12×NVMAX+30015,
or | LIWORK<8×NEDGE+53×NVMAX+2×NVB+10078.
IFAIL=2
An error has occurred during the generation of the interior mesh. Check the definition of the boundary (arguments COOR and EDGE) as well as the orientation of the boundary (especially in the case of a multiple connected component boundary). Setting ITRACE>0 may provide more details.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

Not applicable.

8 Parallelism and Performance

D06ACF makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The position of the internal vertices is a function position of the vertices on the given boundary. A fine mesh on the boundary results in a fine mesh in the interior. During the process vertices are generated on edges of the mesh Ti to obtain the mesh T i+1 in the general incremental method (consult the D06 Chapter Introduction or George and Borouchaki (1998)).
You are advised to take care to set the boundary inputs properly, especially for a boundary with multiply connected components. The orientation of the interior boundaries should be in clockwise order and opposite to that of the exterior boundary. If the boundary has only one connected component, its orientation should be anticlockwise.

10 Example

In this example, a geometry with two holes (two wings inside an exterior circle) is meshed using a Delaunay–Voronoi method. The exterior circle is centred at the point 1.5,0.0 with a radius 4.5, the first wing begins at the origin and it is normalized, finally the last wing is also normalized and begins at the point 0.8,-0.3. To be able to carry out some realistic computation on that geometry, some interior points have been introduced to have a finer mesh in the wake of those airfoils.
The boundary mesh has 120 vertices and 120 edges (see Figure 1 top). Note that the particular mesh generated could be sensitive to the machine precision and therefore may differ from one implementation to another.

10.1 Program Text

Program Text (d06acfe.f90)

10.2 Program Data

Program Data (d06acfe.d)

10.3 Program Results

Program Results (d06acfe.r)

The boundary mesh (top), the interior mesh (bottom) of a double wing inside a circle geometry
Figure 1: The boundary mesh (top), the interior mesh (bottom) of a
double wing inside a circle geometry
D06 Chapter Contents
D06 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


D06BAF : NAG Library, Mark 26

D06 Chapter Contents
D06 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

D06BAF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

D06BAF generates a boundary mesh on a closed connected subdomain Ω of ℝ 2.

2 Specification

SUBROUTINE D06BAF ( NLINES, COORCH, LINED, FBND, CRUS, SDCRUS, RATE, NCOMP, NLCOMP, LCOMP, NVMAX, NEDMX, NVB, COOR, NEDGE, EDGE, ITRACE, RUSER, IUSER, RWORK, LRWORK, IWORK, LIWORK, IFAIL)
INTEGER | NLINES, LINED(4,NLINES), SDCRUS, NCOMP, NLCOMP(NCOMP), LCOMP(NLINES), NVMAX, NEDMX, NVB, NEDGE, EDGE(3,NEDMX), ITRACE, IUSER(*), LRWORK, IWORK(LIWORK), LIWORK, IFAIL
REAL (KIND=nag_wp) | COORCH(2,NLINES), FBND, CRUS(2,SDCRUS), RATE(NLINES), COOR(2,NVMAX), RUSER(*), RWORK(LRWORK)
EXTERNAL | FBND

3 Description

Given a closed connected subdomain Ω of ℝ 2, whose boundary ∂Ω is divided by characteristic points into m distinct line segments, D06BAF generates a boundary mesh on ∂Ω. Each line segment may be a straight line, a curve defined by the equation f x,y=0, or a polygonal curve defined by a set of given boundary mesh points.
This routine is primarily designed for use with either D06AAF (a simple incremental method) or D06ABF (Delaunay–Voronoi method) or D06ACF (Advancing Front method) to triangulate the interior of the domain Ω. For more details about the boundary and interior mesh generation, consult the D06 Chapter Introduction as well as George and Borouchaki (1998).
This routine is derived from material in the MODULEF package from INRIA (Institut National de Recherche en Informatique et Automatique).

4 References

George P L and Borouchaki H (1998) Delaunay Triangulation and Meshing: Application to Finite Elements Editions HERMES, Paris

5 Arguments

1:   NLINES – INTEGERInput
On entry: m, the number of lines that define the boundary of the closed connected subdomain (this equals the number of characteristic points which separate the entire boundary ∂Ω into lines).
Constraint: NLINES≥1.
2:   COORCH 2 NLINES – REAL (KIND=nag_wp) arrayInput
On entry: COORCH 1 i contains the x coordinate of the ith characteristic point, for i=1,2,…,NLINES; while COORCH 2 i contains the corresponding y coordinate.
3:   LINED 4 NLINES – INTEGER arrayInput
On entry: the description of the lines that define the boundary domain. The line i, for i=1,2,…,m, is defined as follows:
LINED 1 i
The number of points on the line, including two end points.
LINED 2 i
The first end point of the line. If LINED 2 i=j, then the coordinates of the first end point are those stored in COORCH:j.
LINED 3 i
The second end point of the line. If LINED 3 i=k, then the coordinates of the second end point are those stored in COORCH:k.
LINED 4 i
This defines the type of line segment connecting the end points. Additional information is conveyed by the numerical value of LINED 4 i as follows:
(i) | LINED 4 i>0, the line is described in FBND with LINED 4 i as the index. In this case, the line must be described in the trigonometric (anticlockwise) direction;
(ii) | LINED 4 i=0, the line is a straight line;
(iii) | if LINED 4 i<0, say (-p), then the line is a polygonal arc joining the end points and interior points specified in CRUS. In this case the line contains the points whose coordinates are stored in COORCH:j , CRUS:p , CRUS:p+1 ,…, CRUS:p+r-3 , COORCH:k , where z∈1,2, r=LINED 1 i, j=LINED 2 i and k=LINED 3 i.
Constraints:
  • 2≤LINED 1 i;
  • 1≤LINED 2 i≤NLINES;
  • 1≤LINED 3 i≤NLINES;
  • LINED 2 i≠LINED 3 i, for i=1,2,…,NLINES.
For each line described by FBND (lines with LINED 4 i > 0 , for i=1,2,…,NLINES) the two end points ( LINED 2 i and LINED 3 i ) lie on the curve defined by index LINED 4 i in FBND, i.e.,
FBND LINED 4 i,COORCH 1 LINED 2 i,COORCH 2 LINED 2 i,RUSER,IUSER = 0 ;
FBND LINED 4 i,COORCH 1 LINED 3 i,COORCH 2 LINED 3 i,RUSER,IUSER = 0 , for i=1,2,…,NLINES.
For all lines described as polygonal arcs (lines with LINED 4 i < 0 , for i=1,2,…,NLINES) the sets of intermediate points (i.e., -LINED 4 i : -LINED 4 i + LINED 1 i - 3 for all i such that LINED 4 i<0) are not overlapping. This can be expressed as:
-LINED 4 i + LINED 1 i - 3 = ∑ i,LINED 4 i<0 LINED 1 i - 2
or
-LINED 4 i + LINED 1 i - 2 = -LINED 4 j ,
for a j such that j=1,2,…,NLINES, j≠i and LINED 4 j<0.
4:   FBND – REAL (KIND=nag_wp) FUNCTION, supplied by the user.External Procedure
FBND must be supplied to calculate the value of the function which describes the curve x,y ∈ℝ 2; such that ​f x,y=0 on segments of the boundary for which LINED 4 i>0. If there are no boundaries for which LINED 4 i>0 FBND will never be referenced by D06BAF and FBND may be the dummy function D06BAD. (D06BAD is included in the NAG Library.)
The specification of FBND is:
FUNCTION FBND ( I, X, Y, RUSER, IUSER)
REAL (KIND=nag_wp) FBND
INTEGER | I, IUSER(*)
REAL (KIND=nag_wp) | X, Y, RUSER(*)
1:   I – INTEGERInput
On entry: LINED 4 i, the reference index of the line (portion of the contour) i described.
2:   X – REAL (KIND=nag_wp)Input
3:   Y – REAL (KIND=nag_wp)Input
On entry: the values of x and y at which f x,y is to be evaluated.
4:   RUSER* – REAL (KIND=nag_wp) arrayUser Workspace
5:   IUSER* – INTEGER arrayUser Workspace
FBND is called with the arguments RUSER and IUSER as supplied to D06BAF. You are free to use the arrays RUSER and IUSER to supply information to FBND as an alternative to using COMMON global variables.
FBND must either be a module subprogram USEd by, or declared as EXTERNAL in, the (sub)program from which D06BAF is called. Arguments denoted as Input must not be changed by this procedure.
5:   CRUS 2 SDCRUS – REAL (KIND=nag_wp) arrayInput
On entry: the coordinates of the intermediate points for polygonal arc lines. For a line i defined as a polygonal arc (i.e., LINED 4 i<0), if p=-LINED 4 i, then CRUS 1 k, for k=p,…,p+LINED 1 i-3, must contain the x coordinate of the consecutive intermediate points for this line. Similarly CRUS 2 k, for k=p,…,p+LINED 1 i-3, must contain the corresponding y coordinate.
6:   SDCRUS – INTEGERInput
On entry: the second dimension of the array CRUS as declared in the (sub)program from which D06BAF is called.
Constraint: SDCRUS≥∑i,LINED 4 i<0 LINED 1 i-2.
7:   RATE NLINES – REAL (KIND=nag_wp) arrayInput
On entry: RATE i is the geometric progression ratio between the points to be generated on the line i, for i=1,2,…,m and LINED 4 i≥0.
If LINED 4 i<0, RATE i is not referenced.
Constraint: if LINED 4 i≥0, RATE i>0.0, for i=1,2,…,NLINES.
8:   NCOMP – INTEGERInput
On entry: n, the number of separately connected components of the boundary.
Constraint: NCOMP≥1.
9:   NLCOMP NCOMP – INTEGER arrayInput
On entry: NLCOMP k is the number of line segments in component k of the contour. The line i of component k runs in the direction LINED 2 i to LINED 3 i if NLCOMP k>0, and in the opposite direction otherwise; for k=1,2,…,n.
Constraints:
  • 1≤NLCOMP k≤NLINES, for k=1,2,…,NCOMP;
  • ∑ k =1 n NLCOMP k =NLINES .
10:   LCOMP NLINES – INTEGER arrayInput
On entry: LCOMP must contain the list of line numbers for the each component of the boundary. Specifically, the line numbers for the kth component of the boundary, for k=1,2,…,NCOMP, must be in elements l 1-1 to l 2-1 of LCOMP, where l 2 = ∑ i=1 k NLCOMP i and l 1=l 2+1-NLCOMP k.
Constraint: LCOMP must hold a valid permutation of the integers 1,NLINES.
11:   NVMAX – INTEGERInput
On entry: the maximum number of the boundary mesh vertices to be generated.
Constraint: NVMAX≥NLINES.
12:   NEDMX – INTEGERInput
On entry: the maximum number of boundary edges in the boundary mesh to be generated.
Constraint: NEDMX≥1.
13:   NVB – INTEGEROutput
On exit: the total number of boundary mesh vertices generated.
14:   COOR 2 NVMAX – REAL (KIND=nag_wp) arrayOutput
On exit: COOR 1 i will contain the x coordinate of the ith boundary mesh vertex generated, for i=1,2,…,NVB; while COOR 2 i will contain the corresponding y coordinate.
15:   NEDGE – INTEGEROutput
On exit: the total number of boundary edges in the boundary mesh.
16:   EDGE 3 NEDMX – INTEGER arrayOutput
On exit: the specification of the boundary edges. EDGE 1 j and EDGE 2 j will contain the vertex numbers of the two end points of the jth boundary edge. EDGE 3 j is a reference number for the jth boundary edge and
  • EDGE 3 j=LINED 4 i, where i and j are such that the jth edges is part of the ith line of the boundary and LINED 4 i≥0;
  • EDGE 3 j=100+LINED 4 i, where i and j are such that the jth edges is part of the ith line of the boundary and LINED 4 i<0.
17:   ITRACE – INTEGERInput
On entry: the level of trace information required from D06BAF.
ITRACE=0 or ITRACE<-1
No output is generated.
ITRACE=1
Output from the boundary mesh generator is printed on the current advisory message unit (see X04ABF). This output contains the input information of each line and each connected component of the boundary.
ITRACE=-1
An analysis of the output boundary mesh is printed on the current advisory message unit. This analysis includes the orientation (clockwise or anticlockwise) of each connected component of the boundary. This information could be of interest to you, especially if an interior meshing is carried out using the output of this routine, calling either D06AAF, D06ABF or D06ACF.
ITRACE>1
The output is similar to that produced when ITRACE=1, but the coordinates of the generated vertices on the boundary are also output.
You are advised to set ITRACE=0, unless you are experienced with finite element mesh generation.
18:   RUSER* – REAL (KIND=nag_wp) arrayUser Workspace
19:   IUSER* – INTEGER arrayUser Workspace
RUSER and IUSER are not used by D06BAF, but are passed directly to FBND and may be used to pass information to this routine as an alternative to using COMMON global variables.
20:   RWORK LRWORK – REAL (KIND=nag_wp) arrayWorkspace
21:   LRWORK – INTEGERInput
On entry: the dimension of the array RWORK as declared in the (sub)program from which D06BAF is called.
Constraint: LRWORK≥2×NLINES+SDCRUS+2×max i=1,2,…,m LINED 1 i×NLINES.
22:   IWORK LIWORK – INTEGER arrayWorkspace
23:   LIWORK – INTEGERInput
On entry: the dimension of the array IWORK as declared in the (sub)program from which D06BAF is called.
Constraint: LIWORK≥∑i,LINED 4 i<0 LINED 1 i-2+8×NLINES+NVMAX+3×NEDMX+2×SDCRUS.
24:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, | NLINES<1;
or | NVMAX<NLINES;
or | NEDMX<1;
or | NCOMP<1;
or | LRWORK<2×NLINES+SDCRUS+2×max i=1,2,…,m LINED 1 i×NLINES;
or | LIWORK < ∑ i, LINED 4 i < 0 LINED 1 i -2 +8 × NLINES +NVMAX +3 × NEDMX +2 × SDCRUS ;
or | SDCRUS < ∑ i, LINED 4 i < 0 LINED 1 i -2 ;
or | RATE i<0.0 for some i=1,2,…,NLINES with LINED 4 i≥0;
or | LINED 1 i<2 for some i=1,2,…,NLINES;
or | LINED 2 i<1 or LINED 2 i>NLINES for some i=1,2,…,NLINES;
or | LINED 3 i<1 or LINED 3 i>NLINES for some i=1,2,…,NLINES;
or | LINED 2 i=LINED 3 i for some i=1,2,…,NLINES;
or | NLCOMP k=0, or NLCOMP k>NLINES for a k=1,2,…,NCOMP;
or | ∑ k =1 n NLCOMP k ≠ NLINES ;
or | LCOMP does not represent a valid permutation of the integers in 1,NLINES;
or | one of the end points for a line i described by the user-supplied function (lines with LINED 4 i>0, for i=1,2,…,NLINES) does not belong to the corresponding curve in FBND;
or | the intermediate points for the lines described as polygonal arcs (lines with LINED 4 i<0, for i=1,2,…,NLINES) are overlapping.
IFAIL=2
An error has occurred during the generation of the boundary mesh. It appears that NEDMX is not large enough, so you are advised to increase the value of NEDMX.
IFAIL=3
An error has occurred during the generation of the boundary mesh. It appears that NVMAX is not large enough, so you are advised to increase the value of NVMAX.
IFAIL=4
An error has occurred during the generation of the boundary mesh. Check the definition of each line (the argument LINED) and each connected component of the boundary (the arguments NLCOMP, and LCOMP, as well as the coordinates of the characteristic points. Setting ITRACE>0 may provide more details.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

Not applicable.

8 Parallelism and Performance

D06BAF is not threaded in any implementation.

9 Further Comments

The boundary mesh generation technique in this routine has a ‘tree’ structure. The boundary should be partitioned into geometrically simple segments (straight lines or curves) delimited by characteristic points. Then, the lines should be assembled into connected components of the boundary domain.
Using this strategy, the inputs to that routine can be built up, following the requirements stated in Section 5:
  • the characteristic and the user-supplied intermediate points:
    • NLINES, SDCRUS, COORCH and CRUS;
  • the characteristic lines:
    • LINED, FBND, RATE;
  • finally the assembly of lines into the connected components of the boundary:
    • NCOMP, and
    • NLCOMP, LCOMP.
The example below details the use of this strategy.

10 Example

The NAG logo is taken as an example of a geometry with holes. The boundary has been partitioned in 40 lines characteristic points; including 4 for the exterior boundary and 36 for the logo itself. All line geometry specifications have been considered, see the description of LINED, including 4 lines defined as polygonal arc, 4 defined by FBND and all the others are straight lines.

10.1 Program Text

Program Text (d06bafe.f90)

10.2 Program Data

Program Data (d06bafe.d)

10.3 Program Results

Program Results (d06bafe.r)

GnuplotProduced by GNUPLOT 4.6 patchlevel 3 Example Program Boundary Mesh of the NAG Logo with 259 Nodes and 259 Edges gnuplot_plot_1
GnuplotProduced by GNUPLOT 4.6 patchlevel 3 Final Mesh Built Using the Delaunay-Voronoi Method gnuplot_plot_1
GnuplotProduced by GNUPLOT 4.6 patchlevel 3 Final Mesh Built Using the Advancing Front Method gnuplot_plot_1
D06 Chapter Contents
D06 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


D06CAF : NAG Library, Mark 26

D06 Chapter Contents
D06 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

D06CAF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

D06CAF uses a barycentering technique to smooth a given mesh.

2 Specification

SUBROUTINE D06CAF ( NV, NELT, NEDGE, COOR, EDGE, CONN, NVFIX, NUMFIX, ITRACE, NQINT, IWORK, LIWORK, RWORK, LRWORK, IFAIL)
INTEGER | NV, NELT, NEDGE, EDGE(3,NEDGE), CONN(3,NELT), NVFIX, NUMFIX(*), ITRACE, NQINT, IWORK(LIWORK), LIWORK, LRWORK, IFAIL
REAL (KIND=nag_wp) | COOR(2,NV), RWORK(LRWORK)

3 Description

D06CAF uses a barycentering approach to improve the smoothness of a given mesh. The measure of quality used for a triangle K is
QK=α hKρK;
where hK is the diameter (length of the longest edge) of K, ρK is the radius of its inscribed circle and α= 3 6 is a normalization factor chosen to give QK=1 for an equilateral triangle. QK ranges from 1, for an equilateral triangle, to ∞, for a totally flat triangle.
D06CAF makes small perturbation to vertices (using a barycenter formula) in order to give a reasonably good value of QK for all neighbouring triangles. Some vertices may optionally be excluded from this process.
For more details about the smoothing method, especially with regard to differing quality, consult the D06 Chapter Introduction as well as George and Borouchaki (1998).
This routine is derived from material in the MODULEF package from INRIA (Institut National de Recherche en Informatique et Automatique).

4 References

George P L and Borouchaki H (1998) Delaunay Triangulation and Meshing: Application to Finite Elements Editions HERMES, Paris

5 Arguments

1:   NV – INTEGERInput
On entry: the total number of vertices in the input mesh.
Constraint: NV≥3.
2:   NELT – INTEGERInput
On entry: the number of triangles in the input mesh.
Constraint: NELT≤2×NV-1.
3:   NEDGE – INTEGERInput
On entry: the number of the boundary and interface edges in the input mesh.
Constraint: NEDGE≥1.
4:   COOR 2 NV – REAL (KIND=nag_wp) arrayInput/Output
On entry: COOR 1 i contains the x coordinate of the ith input mesh vertex, for i=1,2,…,NV; while COOR 2 i contains the corresponding y coordinate.
On exit: COOR 1 i will contain the x coordinate of the ith smoothed mesh vertex, for i=1,2,…,NV; while COOR 2 i will contain the corresponding y coordinate. Note that the coordinates of boundary and interface edge vertices, as well as those specified by you (see the description of NUMFIX), are unchanged by the process.
5:   EDGE 3 NEDGE – INTEGER arrayInput
On entry: the specification of the boundary or interface edges. EDGE 1 j and EDGE 2 j contain the vertex numbers of the two end points of the jth boundary edge. EDGE 3 j is a user-supplied tag for the jth boundary or interface edge: EDGE 3 j=0 for an interior edge and has a nonzero tag otherwise.
Constraint: 1≤EDGE ij≤NV and EDGE 1 j≠EDGE 2 j, for i=1,2 and j=1,2,…,NEDGE.
6:   CONN 3 NELT – INTEGER arrayInput
On entry: the connectivity of the mesh between triangles and vertices. For each triangle j, CONN ij gives the indices of its three vertices (in anticlockwise order), for i=1,2,3 and j=1,2,…,NELT.
Constraint: 1≤CONN ij≤NV and CONN 1 j≠CONN 2 j and CONN 1 j≠CONN 3 j and CONN 2 j≠CONN 3 j, for i=1,2,3 and j=1,2,…,NELT.
7:   NVFIX – INTEGERInput
On entry: the number of fixed vertices in the input mesh.
Constraint: 0≤NVFIX≤NV.
8:   NUMFIX* – INTEGER arrayInput
Note: the dimension of the array NUMFIX must be at least max 1,NVFIX.
On entry: the indices in COOR of fixed interior vertices of the input mesh.
Constraint: if NVFIX>0, 1≤NUMFIX i≤NV, for i=1,2,…,NVFIX.
9:   ITRACE – INTEGERInput
On entry: the level of trace information required from D06CAF.
ITRACE≤0
No output is generated.
ITRACE=1
A histogram of the triangular element qualities is printed on the current advisory message unit (see X04ABF) before and after smoothing. This histogram gives the lowest and the highest triangle quality as well as the number of elements lying in each of the NQINT equal intervals between the extremes.
ITRACE>1
The output is similar to that produced when ITRACE=1 but the connectivity between vertices and triangles (for each vertex, the list of triangles in which it appears) is given.
You are advised to set ITRACE=0, unless you are experienced with finite element meshes.
10:   NQINT – INTEGERInput
On entry: the number of intervals between the extreme quality values for the input and the smoothed mesh.
If ITRACE=0, NQINT is not referenced.
11:   IWORK LIWORK – INTEGER arrayWorkspace
12:   LIWORK – INTEGERInput
On entry: the dimension of the array IWORK as declared in the (sub)program from which D06CAF is called.
Constraint: LIWORK≥8×NELT+2×NV.
13:   RWORK LRWORK – REAL (KIND=nag_wp) arrayWorkspace
14:   LRWORK – INTEGERInput
On entry: the dimension of the array RWORK as declared in the (sub)program from which D06CAF is called.
Constraint: LRWORK≥2×NV+NELT.
15:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, | NV<3,
or | NELT>2×NV-1,
or | NEDGE<1,
or | EDGE ij<1 or EDGE ij>NV for some i=1,2 and j=1,2,…,NEDGE,
or | EDGE 1 j=EDGE 2 j for some j=1,2,…,NEDGE,
or | CONN ij<1 or CONN ij>NV for some i=1,2,3 and j=1,2,…,NELT,
or | CONN 1 j=CONN 2 j or CONN 1 j=CONN 3 j or CONN 2 j=CONN 3 j for some j=1,2,…,NELT,
or | NVFIX<0 or NVFIX>NV,
or | NUMFIX i<1 or NUMFIX i>NV for some i=1,2,…,NVFIX if NVFIX>0,
or | LIWORK<8×NELT+2×NV,
or | LRWORK<2×NV+NELT.
IFAIL=2
A serious error has occurred in an internal call to an auxiliary routine. Check the input mesh, especially the connectivity between triangles and vertices (the argument CONN). Setting ITRACE>1 may provide more information. If the problem persists, contact NAG.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

Not applicable.

8 Parallelism and Performance

D06CAF makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

None.

10 Example

In this example, a uniform mesh on the unit square is randomly distorted using routines from Chapter G05. D06CAF is then used to smooth the distorted mesh and recover a uniform mesh.

10.1 Program Text

Program Text (d06cafe.f90)

10.2 Program Data

Program Data (d06cafe.d)

10.3 Program Results

Program Results (d06cafe.r)

GnuplotProduced by GNUPLOT 4.6 patchlevel 3 Example Program Randomly distorted uniform mesh gnuplot_plot_1
GnuplotProduced by GNUPLOT 4.6 patchlevel 3 Distorted mesh smoothed and a uniform mesh recovered gnuplot_plot_1
D06 Chapter Contents
D06 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


D06CBF : NAG Library, Mark 26

D06 Chapter Contents
D06 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

D06CBF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
10 Example

1 Purpose

D06CBF generates the sparsity pattern of a finite element matrix associated with a given mesh.

2 Specification

SUBROUTINE D06CBF ( NV, NELT, NNZMAX, CONN, NNZ, IROW, ICOL, IFAIL)
INTEGER NV, NELT, NNZMAX, CONN(3,NELT), NNZ, IROW(NNZMAX), ICOL(NNZMAX), IFAIL

3 Description

D06CBF generates the sparsity pattern of a finite element matrix associated with a given mesh. The sparsity pattern is returned in a coordinate storage format consistent with the sparse linear algebra routines in Chapter F11. More precisely D06CBF returns the number of nonzero elements in the associated sparse matrix, and their row and column indices. This is designed to assist you in applying finite element discretization to meshes from the D06 Chapter Introduction and in solving the resulting sparse linear system using routines from Chapter F11.
The output sparsity pattern is based on the fact that finite element matrix A has elements a ij satisfying:
a ij≠0 ⇒i​ and ​j ​ are vertices belonging to the same triangle.

4 References

None.

5 Arguments

1:   NV – INTEGERInput
On entry: the total number of vertices in the input mesh.
Constraint: NV≥3.
2:   NELT – INTEGERInput
On entry: the number of triangles in the input mesh.
Constraint: NELT≤2×NV-1.
3:   NNZMAX – INTEGERInput
On entry: the maximum number of nonzero entries in the matrix based on the input mesh. It is the dimension of the arrays IROW and ICOL as declared in the subroutine from which D06CBF is called.
Constraint: 4×NELT+NV≤NNZMAX≤NV 2.
4:   CONN 3 NELT – INTEGER arrayInput
On entry: the connectivity of the mesh between triangles and vertices. For each triangle j, CONN ij gives the indices of its three vertices (in anticlockwise order), for i=1,2,3 and j=1,2,…,NELT.
Constraint: 1≤CONN ij≤NV and CONN 1 j≠CONN 2 j and CONN 1 j≠CONN 3 j and CONN 2 j≠CONN 3 j, for i=1,2,3 and j=1,2,…,NELT.
5:   NNZ – INTEGEROutput
On exit: the number of nonzero entries in the matrix associated with the input mesh.
6:   IROW NNZMAX – INTEGER arrayOutput
7:   ICOL NNZMAX – INTEGER arrayOutput
On exit: the first NNZ elements contain the row and column indices of the nonzero elements supplied in the finite element matrix A.
8:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, | NV<3,
or | NELT>2×NV-1,
or | NNZMAX<4×NELT+NV or NNZMAX>NV 2
or | CONN ij<1 or CONN ij>NV for some i=1,3 and j, 1≤j≤NELT,
or CONN 1 j=CONN 2 j or CONN 1 j=CONN 3 j or
CONN 2 j=CONN 3 j for some j=1,2,…,NELT.
IFAIL=2
A serious error has occurred in an internal call to an auxiliary routine. Check the input mesh, especially the connectivity between triangles and vertices (the argument CONN). Array dimensions should be checked as well. If the problem persists, contact NAG.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

Not applicable.

8 Parallelism and Performance

D06CBF is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

None.

10 Example

See Section 10 in D06CCF.
D06 Chapter Contents
D06 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


D06CCF : NAG Library, Mark 26

D06 Chapter Contents
D06 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

D06CCF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

D06CCF renumbers the vertices of a given mesh using a Gibbs method, in order the reduce the bandwidth of Finite Element matrices associated with that mesh.

2 Specification

SUBROUTINE D06CCF ( NV, NELT, NEDGE, NNZMAX, NNZ, COOR, EDGE, CONN, IROW, ICOL, ITRACE, IWORK, LIWORK, RWORK, LRWORK, IFAIL)
INTEGER | NV, NELT, NEDGE, NNZMAX, NNZ, EDGE(3,NEDGE), CONN(3,NELT), IROW(NNZMAX), ICOL(NNZMAX), ITRACE, IWORK(LIWORK), LIWORK, LRWORK, IFAIL
REAL (KIND=nag_wp) | COOR(2,NV), RWORK(LRWORK)

3 Description

D06CCF uses a Gibbs method to renumber the vertices of a given mesh in order to reduce the bandwidth of the associated finite element matrix A. This matrix has elements a ij such that:
a ij≠0⇒i​ and ​j​ are vertices belonging to the same triangle.
This routine reduces the bandwidth m, which is the smallest integer such that a ij≠0 whenever i-j>m (see Gibbs et al. (1976) for details about that method). D06CCF also returns the sparsity structure of the matrix associated with the renumbered mesh.
This routine is derived from material in the MODULEF package from INRIA (Institut National de Recherche en Informatique et Automatique).

4 References

Gibbs N E, Poole W G Jr and Stockmeyer P K (1976) An algorithm for reducing the bandwidth and profile of a sparse matrix SIAM J. Numer. Anal. 13 236–250

5 Arguments

1:   NV – INTEGERInput
On entry: the total number of vertices in the input mesh.
Constraint: NV≥3.
2:   NELT – INTEGERInput
On entry: the number of triangles in the input mesh.
Constraint: NELT≤2×NV-1.
3:   NEDGE – INTEGERInput
On entry: the number of boundary edges in the input mesh.
Constraint: NEDGE≥1.
4:   NNZMAX – INTEGERInput
On entry: the maximum number of nonzero entries in the matrix based on the input mesh. It is the dimension of the arrays IROW and ICOL as declared in the subroutine from which D06CCF is called.
Constraint: 4×NELT+NV≤NNZMAX≤NV 2.
5:   NNZ – INTEGEROutput
On exit: the number of nonzero entries in the matrix based on the input mesh.
6:   COOR 2 NV – REAL (KIND=nag_wp) arrayInput/Output
On entry: COOR 1 i contains the x coordinate of the ith input mesh vertex, for i=1,2,…,NV; while COOR 2 i contains the corresponding y coordinate.
On exit: COOR 1 i will contain the x coordinate of the ith renumbered mesh vertex, for i=1,2,…,NV; while COOR 2 i will contain the corresponding y coordinate.
7:   EDGE 3 NEDGE – INTEGER arrayInput/Output
On entry: the specification of the boundary or interface edges. EDGE 1 j and EDGE 2 j contain the vertex numbers of the two end points of the jth boundary edge. EDGE 3 j is a user-supplied tag for the jth boundary or interface edge: EDGE 3 j=0 for an interior edge and has a nonzero tag otherwise.
Constraint: 1≤EDGE ij≤NV and EDGE 1 j≠EDGE 2 j, for i=1,2 and j=1,2,…,NEDGE.
On exit: the renumbered specification of the boundary or interface edges.
8:   CONN 3 NELT – INTEGER arrayInput/Output
On entry: the connectivity of the mesh between triangles and vertices. For each triangle j, CONN ij gives the indices of its three vertices (in anticlockwise order), for i=1,2,3 and j=1,2,…,NELT.
Constraint: 1≤CONN ij≤NV and CONN 1 j≠CONN 2 j and CONN 1 j≠CONN 3 j and CONN 2 j≠CONN 3 j, for i=1,2,3 and j=1,2,…,NELT.
On exit: the renumbered connectivity of the mesh between triangles and vertices.
9:   IROW NNZMAX – INTEGER arrayOutput
10:   ICOL NNZMAX – INTEGER arrayOutput
On exit: the first NNZ elements contain the row and column indices of the nonzero elements supplied in the finite element matrix A.
11:   ITRACE – INTEGERInput
On entry: the level of trace information required from D06CCF.
ITRACE≤0
No output is generated.
ITRACE=1
Information about the effect of the renumbering on the finite element matrix are output. This information includes the half bandwidth and the sparsity structure of this matrix before and after renumbering.
ITRACE>1
The output is similar to that produced when ITRACE=1 but the sparsities (for each row of the matrix, indices of nonzero entries) of the matrix before and after renumbering are also output.
12:   IWORK LIWORK – INTEGER arrayWorkspace
13:   LIWORK – INTEGERInput
On entry: the dimension of the array IWORK as declared in the (sub)program from which D06CCF is called.
Constraint: LIWORK≥max NNZMAX,20×NV.
14:   RWORK LRWORK – REAL (KIND=nag_wp) arrayWorkspace
15:   LRWORK – INTEGERInput
On entry: the dimension of the array RWORK as declared in the (sub)program from which D06CCF is called.
Constraint: LRWORK≥NV.
16:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, | NV<3,
or | NELT>2×NV-1,
or | NEDGE<1,
or | NNZMAX<4×NELT+NV or NNZMAX>NV 2
or | CONN ij<1 or CONN ij>NV for some i=1,2,3 and j=1,2,…,NELT,
or CONN 1 j=CONN 2 j or CONN 1 j=CONN 3 j or
CONN 2 j=CONN 3 j for some j=1,2,…,NELT,
or | EDGE ij<1 or EDGE ij>NV for some i=1,2 and j=1,2,…,NEDGE,
or | EDGE 1 j=EDGE 2 j for some j=1,2,…,NEDGE,
or | LIWORK<max NNZMAX,20×NV,
or | LRWORK<NV.
IFAIL=2
A serious error has occurred during the computation of the compact sparsity of the finite element matrix or in an internal call to the renumbering routine. Check the input mesh, especially the connectivity between triangles and vertices (the argument CONN). If the problem persists, contact NAG.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

Not applicable.

8 Parallelism and Performance

D06CCF is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

None.

10 Example

In this example, a geometry with two holes (two interior circles inside an exterior one) is considered. The geometry has been meshed using the simple incremental method (D06AAF) and it has 250 vertices and 402 triangles (see Figure 1 in Section 10.3). The routine D06BAF is used to renumber the vertices, and one can see the benefit in terms of the sparsity of the finite element matrix based on the renumbered mesh (see Figure 2 and 3 in Section 10.3).

10.1 Program Text

Program Text (d06ccfe.f90)

10.2 Program Data

None.

10.3 Program Results

Program Results (d06ccfe.r)

GnuplotProduced by GNUPLOT 4.6 patchlevel 3 Example Program Figure 1: Mesh of the Geometry gnuplot_plot_1
GnuplotProduced by GNUPLOT 4.6 patchlevel 3 Figure 2: Sparsity of the FE Matrix Before Renumbering gnuplot_plot_1
GnuplotProduced by GNUPLOT 4.6 patchlevel 3 Figure 3: Sparsity of the FE Matrix After Renumbering gnuplot_plot_1
D06 Chapter Contents
D06 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


D06 Chapter Contents : NAG Library Manual, Mark 26

D06 Chapter Introduction
NAG Library Manual

NAG Library Chapter Contents

D06 – Mesh Generation

D06 Chapter Introduction – a description of the Chapter and an overview of the algorithms available

Routine Name | Mark of Introduction | Purpose
D06AAF Example Text Example Data Example Plot | 20 | nagf_mesh_2d_gen_inc Generates a two-dimensional mesh using a simple incremental method
D06ABF Example Text Example Data Example Plot | 20 | nagf_mesh_2d_gen_delaunay Generates a two-dimensional mesh using a Delaunay–Voronoi process
D06ACF Example Text Example Data Example Plot | 20 | nagf_mesh_2d_gen_front Generates a two-dimensional mesh using an Advancing-front method
D06BAF Example Text Example Data Example Plot | 20 | nagf_mesh_2d_gen_boundary Generates a boundary mesh
D06CAF Example Text Example Data Example Plot | 20 | nagf_mesh_2d_smooth_bary Uses a barycentering technique to smooth a given mesh
D06CBF | 20 | nagf_mesh_2d_sparsity Generates a sparsity pattern of a Finite Element matrix associated with a given mesh
D06CCF Example Text Example Plot | 20 | nagf_mesh_2d_renumber Renumbers a given mesh using Gibbs method
D06DAF | 20 | nagf_mesh_2d_transform_affine Generates a mesh resulting from an affine transformation of a given mesh
D06DBF Example Text Example Data Example Plot | 20 | nagf_mesh_2d_join Joins together two given adjacent (possibly overlapping) meshes
D06 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


D06DAF : NAG Library, Mark 26

D06 Chapter Contents
D06 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

D06DAF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
10 Example

1 Purpose

D06DAF is a utility which performs an affine transformation of a given mesh.

2 Specification

SUBROUTINE D06DAF ( NV, NEDGE, NELT, NTRANS, ITYPE, TRANS, COORI, EDGEI, CONNI, COORO, EDGEO, CONNO, ITRACE, RWORK, LRWORK, IFAIL)
INTEGER | NV, NEDGE, NELT, NTRANS, ITYPE(NTRANS), EDGEI(3,NEDGE), CONNI(3,NELT), EDGEO(3,NEDGE), CONNO(3,NELT), ITRACE, LRWORK, IFAIL
REAL (KIND=nag_wp) | TRANS(6,NTRANS), COORI(2,NV), COORO(2,NV), RWORK(LRWORK)

3 Description

D06DAF generates a mesh (coordinates, triangle/vertex connectivities and edge/vertex connectivities) resulting from an affine transformation of a given mesh. This transformation is of the form Y=A×X+B, where
  • Y, X and B are in ℝ 2, and
  • A is a real 2 by 2 matrix.
Such a transformation includes a translation, a rotation, a scale reduction or increase, a symmetric transformation with respect to a user-supplied line, a user-supplied analytic transformation, or a composition of several transformations.
This routine is partly derived from material in the MODULEF package from INRIA (Institut National de Recherche en Informatique et Automatique).

4 References

None.

5 Arguments

1:   NV – INTEGERInput
On entry: the total number of vertices in the input mesh.
Constraint: NV≥3.
2:   NEDGE – INTEGERInput
On entry: the number of the boundary or interface edges in the input mesh.
Constraint: NEDGE≥1.
3:   NELT – INTEGERInput
On entry: the number of triangles in the input mesh.
Constraint: NELT≤2×NV-1.
4:   NTRANS – INTEGERInput
On entry: the number of transformations of the input mesh.
Constraint: NTRANS≥1.
5:   ITYPE NTRANS – INTEGER arrayInput
On entry: ITYPE i, for i=1,2,…,NTRANS, indicates the type of each transformation as follows:
ITYPE i=0
Identity transformation.
ITYPE i=1
Translation.
ITYPE i=2
Symmetric transformation with respect to a user-supplied line.
ITYPE i=3
Rotation.
ITYPE i=4
Scaling.
ITYPE i=10
User-supplied analytic transformation.
Note that the transformations are applied in the order described in ITYPE.
Constraint: ITYPE i=0, 1, 2, 3, 4 or 10, for i=1,2,…,NTRANS.
6:   TRANS 6 NTRANS – REAL (KIND=nag_wp) arrayInput
On entry: the arguments for each transformation. For i=1,2,…,NTRANS, TRANS 1 i to TRANS 6 i contain the arguments of the ith transformation.
If ITYPE i=0, elements TRANS 1 i to TRANS 6 i are not referenced.
If ITYPE i=1, the translation vector is u→= a b , where a=TRANS 1 i and b=TRANS 2 i, while elements TRANS 3 i to TRANS 6 i are not referenced.
If ITYPE i=2, the user-supplied line is the curve {x,y∈ℝ 2; such that ax+by+c=0}, where a=TRANS 1 i, b=TRANS 2 i and c=TRANS 3 i, while elements TRANS 4 i to TRANS 6 i are not referenced.
If ITYPE i=3, the centre of the rotation is x 0,y 0 where x 0=TRANS 1 i and y 0=TRANS 2 i, θ=TRANS 3 i is its angle in degrees, while elements TRANS 4 i to TRANS 6 i are not referenced.
If ITYPE i=4, a=TRANS 1 i is the scaling coefficient in the x-direction, b=TRANS 2 i is the scaling coefficient in the y-direction, and x 0,y 0 are the scaling centre coordinates, with x 0=TRANS 3 i and y 0=TRANS 4 i; while elements TRANS 5 i to TRANS 6 i are not referenced.
If ITYPE i=10, the user-supplied analytic affine transformation Y=A×X+B is such that A=a kl 1≤k,l≤2 and B=bk 1≤k≤2 wherea kl=TRANS 2×k-1+l i, and bk=TRANS 4+k i with k,l=1,2.
7:   COORI 2 NV – REAL (KIND=nag_wp) arrayInput/Output
On entry: COORI 1 i contains the x coordinate of the ith vertex of the input mesh, for i=1,2,…,NV; while COORI 2 i contains the corresponding y coordinate.
On exit: see Section 9.
8:   EDGEI 3 NEDGE – INTEGER arrayInput/Output
On entry: the specification of the boundary or interface edges. EDGEI 1 j and EDGEI 2 j contain the vertex numbers of the two end points of the jth boundary edge. EDGEI 3 j is a user-supplied tag for the jth boundary edge.
Constraint: 1≤EDGEI ij≤NV and EDGEI 1 j≠EDGEI 2 j, for i=1,2 and j=1,2,…,NEDGE.
On exit: see Section 9.
9:   CONNI 3 NELT – INTEGER arrayInput/Output
On entry: the connectivity of the input mesh between triangles and vertices. For each triangle j, CONNI ij gives the indices of its three vertices (in anticlockwise order), for i=1,2,3 and j=1,2,…,NELT.
Constraints:
  • 1≤CONNI ij≤NV;
  • CONNI 1 j≠CONNI 2 j;
  • CONNI 1 j≠CONNI 3 j and CONNI 2 j≠CONNI 3 j, for i=1,2,3 and j=1,2,…,NELT.
On exit: see Section 9.
10:   COORO 2 NV – REAL (KIND=nag_wp) arrayOutput
On exit: COORO 1 i will contain the x coordinate of the ith vertex of the transformed mesh, for i=1,2,…,NV; while COORO 2 i will contain the corresponding y coordinate.
11:   EDGEO 3 NEDGE – INTEGER arrayOutput
On exit: the specification of the boundary or interface edges of the transformed mesh. If the number of symmetric transformations is even or zero thenEDGEO ij=EDGEI ij, for i=1,2,3 and j=1,2,…,NEDGE; otherwise EDGEO 1 j=EDGEI 2 j,EDGEO 2 j=EDGEI 1 j and EDGEO 3 j=EDGEI 3 j, for j=1,2,…,NEDGE.
12:   CONNO 3 NELT – INTEGER arrayOutput
On exit: the connectivity of the transformed mesh between triangles and vertices. If the number of symmetric transformations is even or zero thenCONNO ij=CONNI ij, for i=1,2,3 and j=1,2,…,NELT; otherwise CONNO 1 j=CONNI 1 j, CONNO 2 j=CONNI 3 j and CONNO 3 j=CONNI 2 j, for j=1,2,…,NELT.
13:   ITRACE – INTEGERInput
On entry: the level of trace information required from D06DAF.
ITRACE≤0
No output is generated.
ITRACE≥1
Details of each transformation, the matrix A and the vector B of the final transformation, which is the composition of all the NTRANS transformations, are printed on the current advisory message unit (see X04ABF).
14:   RWORK LRWORK – REAL (KIND=nag_wp) arrayWorkspace
15:   LRWORK – INTEGERInput
On entry: the dimension of the array RWORK as declared in the (sub)program from which D06DAF is called.
Constraint: LRWORK≥12×NTRANS.
16:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, | NV<3;
or | NELT>2×NV-1;
or | NEDGE<1;
or | EDGEI ij<1 or EDGEI ij>NV for some i=1,2 and j=1,2,…,NEDGE;
or | EDGEI 1 j=EDGEI 2 j for some j=1,2,…,NEDGE;
or | CONNI ij<1 or CONNI ij>NV for some i=1,2,3 and j=1,2,…,NELT;
or CONNI 1 j=CONNI 2 j or CONNI 1 j=CONNI 3 j or
CONNI 2 j=CONNI 3 j for some j=1,2,…,NELT;
or | NTRANS<1;
or | ITYPE i≠0, 1, 2, 3, 4 or 10 for some i=1,2,…,NTRANS;
or | LRWORK<12×NTRANS.
IFAIL=2
A serious error has occurred in an internal call to an auxiliary routine. Check the input mesh especially the triangles/vertices and the edges/vertices connectivities as well as the details of each transformations.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

Not applicable.

8 Parallelism and Performance

D06DAF makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

You may not wish to save the input mesh (COORI, EDGEI and CONNI) and could call D06DAF using the same arguments for the input and the output (transformed) mesh.

10 Example

For an example of the use of this utility routine, see Section 10 in D06DBF.
D06 Chapter Contents
D06 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


D06DBF : NAG Library, Mark 26

D06 Chapter Contents
D06 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

D06DBF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

D06DBF joins together (restitches) two adjacent, or overlapping, meshes.

2 Specification

SUBROUTINE D06DBF ( EPS, NV1, NELT1, NEDGE1, COOR1, EDGE1, CONN1, REFT1, NV2, NELT2, NEDGE2, COOR2, EDGE2, CONN2, REFT2, NV3, NELT3, NEDGE3, COOR3, EDGE3, CONN3, REFT3, ITRACE, IWORK, LIWORK, IFAIL)
INTEGER | NV1, NELT1, NEDGE1, EDGE1(3,NEDGE1), CONN1(3,NELT1), REFT1(NELT1), NV2, NELT2, NEDGE2, EDGE2(3,NEDGE2), CONN2(3,NELT2), REFT2(NELT2), NV3, NELT3, NEDGE3, EDGE3(3,*), CONN3(3,*), REFT3(*), ITRACE, IWORK(LIWORK), LIWORK, IFAIL
REAL (KIND=nag_wp) | EPS, COOR1(2,NV1), COOR2(2,NV2), COOR3(2,*)

3 Description

D06DBF joins together two adjacent, or overlapping, meshes. If the two meshes are adjacent then vertices belonging to the part of the boundary forming the common interface should coincide. If the two meshes overlap then vertices and triangles in the overlapping zone should coincide too.
This routine is partly derived from material in the MODULEF package from INRIA (Institut National de Recherche en Informatique et Automatique).

4 References

None.

5 Arguments

1:   EPS – REAL (KIND=nag_wp)Input
On entry: the relative precision of the restitching of the two input meshes (see Section 9).
Suggested value: 0.001.
Constraint: EPS>0.0.
2:   NV1 – INTEGERInput
On entry: the total number of vertices in the first input mesh.
Constraint: NV1≥3.
3:   NELT1 – INTEGERInput
On entry: the number of triangular elements in the first input mesh.
Constraint: NELT1≤2×NV1-1.
4:   NEDGE1 – INTEGERInput
On entry: the number of boundary edges in the first input mesh.
Constraint: NEDGE1≥1.
5:   COOR1 2 NV1 – REAL (KIND=nag_wp) arrayInput
On entry: COOR1 1 i contains the x coordinate of the ith vertex of the first input mesh, for i=1,2,…,NV1; while COOR1 2 i contains the corresponding y coordinate.
6:   EDGE1 3 NEDGE1 – INTEGER arrayInput
On entry: the specification of the boundary edges of the first input mesh. EDGE1 1 j and EDGE1 2 j contain the vertex numbers of the two end points of the jth boundary edge. EDGE1 3 j is a user-supplied tag for the jth boundary edge.
Constraint: 1≤EDGE1 ij≤NV1 and EDGE1 1 j≠EDGE1 2 j, for i=1,2 and j=1,2,…,NEDGE1.
7:   CONN1 3 NELT1 – INTEGER arrayInput
On entry: the connectivity between triangles and vertices of the first input mesh. For each triangle j, CONN1 ij gives the indices of its three vertices (in anticlockwise order), for i=1,2,3 and j=1,2,…,NELT1.
Constraints:
  • 1≤CONN1 ij≤NV1;
  • CONN1 1 j≠CONN1 2 j;
  • CONN1 1 j≠CONN1 3 j and CONN1 2 j≠CONN1 3 j, for i=1,2,3 and j=1,2,…,NELT1.
8:   REFT1 NELT1 – INTEGER arrayInput
On entry: REFT1 k contains the user-supplied tag of the kth triangle from the first input mesh, for k=1,2,…,NELT1.
9:   NV2 – INTEGERInput
On entry: the total number of vertices in the second input mesh.
Constraint: NV2≥3.
10:   NELT2 – INTEGERInput
On entry: the number of triangular elements in the second input mesh.
Constraint: NELT2≤2×NV2-1.
11:   NEDGE2 – INTEGERInput
On entry: the number of boundary edges in the second input mesh.
Constraint: NEDGE2≥1.
12:   COOR2 2 NV2 – REAL (KIND=nag_wp) arrayInput
On entry: COOR2 1 i contains the x coordinate of the ith vertex of the second input mesh, for i=1,2,…,NV2; while COOR2 2 i contains the corresponding y coordinate.
13:   EDGE2 3 NEDGE2 – INTEGER arrayInput
On entry: the specification of the boundary edges of the second input mesh. EDGE2 1 j and EDGE2 2 j contain the vertex numbers of the two end points of the jth boundary edge. EDGE2 3 j is a user-supplied tag for the jth boundary edge.
Constraint: 1≤EDGE2 ij≤NV2 and EDGE2 1 j≠EDGE2 2 j, for i=1,2 and j=1,2,…,NEDGE2.
14:   CONN2 3 NELT2 – INTEGER arrayInput
On entry: the connectivity between triangles and vertices of the second input mesh. For each triangle j, CONN2 ij gives the indices of its three vertices (in anticlockwise order), for i=1,2,3 and j=1,2,…,NELT2.
Constraints:
  • 1≤CONN2 ij≤NV2;
  • CONN2 1 j≠CONN2 2 j;
  • CONN2 1 j≠CONN2 3 j and CONN2 2 j≠CONN2 3 j, for i=1,2,3 and j=1,2,…,NELT2.
15:   REFT2 NELT2 – INTEGER arrayInput
On entry: REFT2 k contains the user-supplied tag of the kth triangle from the second input mesh, for k=1,2,…,NELT2.
16:   NV3 – INTEGEROutput
On exit: the total number of vertices in the resulting mesh.
17:   NELT3 – INTEGEROutput
On exit: the number of triangular elements in the resulting mesh.
18:   NEDGE3 – INTEGEROutput
On exit: the number of boundary edges in the resulting mesh.
19:   COOR3 2* – REAL (KIND=nag_wp) arrayOutput
Note: the second dimension of the array COOR3 must be at least NV1+NV2.
On exit: COOR3 1 i will contain the x coordinate of the ith vertex of the resulting mesh, for i=1,2,…,NV3; while COOR3 2 i will contain the corresponding y coordinate.
20:   EDGE3 3* – INTEGER arrayOutput
Note: the second dimension of the array EDGE3 must be at least NEDGE1+NEDGE2. This may be reduced to NEDGE3 once that value is known.
On exit: the specification of the boundary edges of the resulting mesh. EDGE3 ij will contain the vertex number of the ith end point (i=1,2) of the jth boundary or interface edge.
If the two meshes overlap, EDGE3 3 j will contain the same tag as the corresponding edge belonging to the first and/or the second input mesh.
If the two meshes are adjacent,
(i) | if the jth edge is part of the partition interface, then EDGE3 3 j will contain the value 1000×k 1+k 2 where k 1 and k 2 are the tags for the same edge of the first and the second mesh respectively;
(ii) | otherwise, EDGE3 3 j will contain the same tag as the corresponding edge belonging to the first and/or the second input mesh.
21:   CONN3 3* – INTEGER arrayOutput
Note: the second dimension of the array CONN3 must be at least NELT1+NELT2. This may be reduced to NELT3 once that value is known.
On exit: the connectivity between triangles and vertices of the resulting mesh. CONN3 ij will give the indices of its three vertices (in anticlockwise order), for i=1,2,3 and j=1,2,…,NELT3.
22:   REFT3* – INTEGER arrayOutput
Note: the dimension of the array REFT3 must be at least NELT1+NELT2. This may be reduced to NELT3 once that value is known.
On exit: if the two meshes form a partition, REFT3 k will contain the same tag as the corresponding triangle belonging to the first or the second input mesh, for k=1,2,…,NELT3. If the two meshes overlap, then REFT3 k will contain the value 1000×k 1+k 2 where k 1 and k 2 are the user-supplied tags for the same triangle of the first and the second mesh respectively, for k=1,2,…,NELT3.
23:   ITRACE – INTEGERInput
On entry: the level of trace information required from D06DBF.
ITRACE≤0
No output is generated.
ITRACE≥1
Details about the common vertices, edges and triangles to both meshes are printed on the current advisory message unit (see X04ABF).
24:   IWORK LIWORK – INTEGER arrayWorkspace
25:   LIWORK – INTEGERInput
On entry: the dimension of the array IWORK as declared in the (sub)program from which D06DBF is called.
Constraint: LIWORK≥2×NV1+3×NV2+NELT1+NELT2+NEDGE1+NEDGE2+1024.
26:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, | EPS≤0.0,
or | NV1<3,
or | NELT1>2×NV1-1,
or | NEDGE1<1,
or | EDGE1 ij<1 or EDGE1 ij>NV1 for some i=1,2 and j=1,2,…,NEDGE1,
or | EDGE1 1 j=EDGE1 2 j for some j=1,2,…,NEDGE1,
or | CONN1 ij<1 or CONN1 ij>NV1 for some i=1,2,3 and j=1,2,…,NELT1,
or | CONN1 1 j=CONN1 2 j or CONN1 1 j=CONN1 3 j or CONN1 2 j=CONN1 3 j for some j=1,2,…,NELT1,
or | NV2<3,
or | NELT2>2×NV2-1,
or | NEDGE2<1,
or | EDGE2 ij<1 or EDGE2 ij>NV2 for some i=1,2 and j=1,2,…,NEDGE2,
or | EDGE2 1 j=EDGE2 2 j for some j=1,2,…,NEDGE2,
or | CONN2 ij<1 or CONN2 ij>NV2 for some i=1,2,3 and j=1,2,…,NELT2,
or CONN2 1 j=CONN2 2 j or CONN2 1 j=CONN2 3 j or
CONN2 2 j=CONN2 3 j for some j=1,2,…,NELT2,
or | LIWORK<2×NV1+3×NV2+NELT1+NELT2+NEDGE1+NEDGE2+1024.
IFAIL=2
Using the input precision EPS, the routine has detected fewer than two coincident vertices between the two input meshes. You are advised to try another value of EPS; if this error still occurs the two meshes are probably not stitchable.
IFAIL=3
A serious error has occurred in an internal call to the restitching routine. You should check the input of the two meshes, especially the edge/vertex and/or the triangle/vertex connectivities. If the problem persists, contact NAG.
IFAIL=4
The routine has detected a different number of coincident triangles from the two input meshes in the overlapping zone. You should check the input of the two meshes, especially the triangle/vertex connectivities.
IFAIL=5
The routine has detected a different number of coincident edges from the two meshes on the partition interface. You should check the input of the two meshes, especially the edge/vertex connectivities.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

Not applicable.

8 Parallelism and Performance

D06DBF is not threaded in any implementation.

9 Further Comments

D06DBF finds all the common vertices between the two input meshes using the relative precision of the restitching argument EPS. You are advised to vary the value of EPS in the neighbourhood of 0.001 with ITRACE≥1 to get the optimal value for the meshes under consideration.

10 Example

For this routine two examples are presented. There is a single example program for D06DBF, with a main program and the code to solve the two example problems given in Example 1 (EX1) and Example 2 (EX2).
Example 1 (EX1)
This example involves the unit square 0,1 2 meshed uniformly, and then translated by a vector u→= u 1 u 2 (using D06DAF). This translated mesh is then restitched with the original mesh. Two cases are considered:
(a) | overlapping meshes (u 1=15.0, u 2=17.0),
(b) | partitioned meshes (u 1=19.0, u 2=0.0).
The mesh on the unit square has 400 vertices, 722 triangles and its boundary has 76 edges. In the partitioned case the resulting geometry is shown in Figure 1 in Section 10.3 while the restitched mesh is shown in Figure 2 in Section 10.3. In the overlapping case the geometry and mesh are shown in Figure 3 and Figure 4 in Section 10.3.
Example 2 (EX2)
This example restitches three geometries by calling the routine D06DBF twice. The result is a mesh with three partitions. The first geometry is meshed by the Delaunay–Voronoi process (using D06ABF), the second one meshed by an Advancing Front algorithm (using D06ACF), while the third one is the result of a rotation (by -π/2) of the second one (using D06DAF). The resulting geometry is shown in Figure 5 in Section 10.3 and restitched mesh in Figure 6 in Section 10.3.

10.1 Program Text

Program Text (d06dbfe.f90)

10.2 Program Data

Program Data (d06dbfe.d)

10.3 Program Results

Program Results (d06dbfe.r)

GnuplotProduced by GNUPLOT 4.6 patchlevel 3 Example Program Figure 1: Boundary and Interior Interface of Partitioned Squares gnuplot_plot_1
GnuplotProduced by GNUPLOT 4.6 patchlevel 3 Figure 2: Interior Mesh of Partitioned Squares gnuplot_plot_1
GnuplotProduced by GNUPLOT 4.6 patchlevel 3 Figure 3: Boundary and Interior Interface of Overlapping Squares gnuplot_plot_1
GnuplotProduced by GNUPLOT 4.6 patchlevel 3 Figure 4: Interior Mesh of Overlapping Squares gnuplot_plot_1
GnuplotProduced by GNUPLOT 4.6 patchlevel 3 Figure 5: Boundary and Interior Interfaces for Key Shape gnuplot_plot_1
GnuplotProduced by GNUPLOT 4.6 patchlevel 3 Figure 6: Interior Mesh of KeyShape gnuplot_plot_1
D06 Chapter Contents
D06 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


D06 Chapter Introduction : NAG Library, Mark 26

D06 Chapter Contents
NAG Library Manual

NAG Library Chapter Introduction

D06 – Mesh Generation

▸▿ Contents

1 Scope of the Chapter
2 Background to the Problems
▸▿ 3 Recommendations on Choice and Use of Available Routines
3.1 Boundary Mesh Generation
3.2 Interior Mesh Generation
3.3 Mesh Management and Utility Routines
4 Example of Use in the Solution of a Partial Differential Equation
5 Functionality Index
6 Auxiliary Routines Associated with Library Routine Arguments
7 Routines Withdrawn or Scheduled for Withdrawal
8 References

1 Scope of the Chapter

This chapter is concerned with automatic mesh generation
  • with line segments, over the boundary of a closed two-dimensional connected polygonal domain;
  • with triangles, over a given two-dimensional region using only its boundary mesh.

2 Background to the Problems

An important area of scientific computing in engineering is the solution of partial differential equations of various type (for solid mechanics, fluid mechanics, thermal modelling, …) by means of the finite element method. In essence, the finite element method is a numerical technique which solves the governing equations of a complicated system through a discretization process. You may wish to consult Cheung et al. (1996) to see an application of the finite element method to solid mechanics and field problems.
A key requirement of the Finite Element method is a mesh, which subdivides the region on which the partial differential equations are defined. Note that such meshes are also essential to other discretization processes, such as the Finite Volume method. However, for the purpose this description we focus (without loss of generality) on the Finite Element method. Thus, meshing algorithms are of crucial importance in every numerical simulation based on the finite element method. In particular, the accuracy and even the validity of a solution is strongly tied to the properties of the underlying mesh of the domain under consideration.
In this chapter, the Delaunay constrained 2 D triangulation (see George and Borouchaki (1998) or Chapter 7 of Cheung et al. (1996)) is considered and routines are provided to triangulate a closed polygonal domain of ℝ 2, given a mesh of its boundary (in a later Mark of the Library, software for the 3 D case will be available). A domain in ℝ 2 is given via a discretization of its boundary. The boundary is described as a list of segments, with given end point coordinates. Then an incremental method is used to generate the set of interior vertices.
Let Ω be a closed bounded domain in ℝ 2 or ℝ 3. The question is how to construct a triangulation (mesh) of this domain suitable for a finite element framework. Following the definition in George and Borouchaki (1998):
  • T is a mesh of Ω if
    • Ω=⋃K∈T K.
  • Every element K in T is non-empty.
  • The intersection of the interior of any two elements is empty.
  • The intersection of any two elements in T is either,
    • the empty set,
    • a vertex,
    • an edge,
    • a face (in ℝ 3).
In the finite element method, the meshes are in general denoted T or Th, where the index h refers to a measure of the diameter (length of the longest edge) of the elements in the mesh. A triangulation is a set of entities described in a suitable manner by picking an adequate data structure. The algorithm for triangulation construction creates a table of elements in the triangulation as well as the neighbourhood relationships between the elements. Those elements are meant to satisfy the so-called ‘empty sphere criterion’ which means that the open ball associated with the element (the circumcircle of the triangle in 2 D, and the circumsphere of the tetrahedron in 3 D) does not contain any vertices (while the closed ball contains the vertices of the element in consideration only). This criterion is a characterisation of the Delaunay triangulation.
Given Ti the Delaunay triangulation of the convex hull of the first i points, the purpose of the incremental method (which is the main method to generate nodes and elements inside the domain) is to obtain T i+1 the Delaunay triangulation which includes an i+1th point P as an element vertex. To this end, one can introduce a procedure referred to as the ‘Delaunay kernel’ construction. This kernel is
T i+1=Ti-CP+BP,
where BP is the ball associated with P and CP is the associated cavity. The ball associated with a given point P is the set of elements in the triangulation including P as a vertex, while the cavity is the set of elements whose circumcircles or circumballs enclose the point P. One can prove that, given Ti a Delaunay triangulation of a convex hull of the first i points, then T i+1 is a Delaunay triangulation of the hull that includes P as the i+1th vertex. The completion of a Delaunay triangulation relies on applying the Delaunay kernel procedure to every point.
The problems here are
  • to choose the input data T 0 of the incremental method, and
  • to generate at each iteration this i+1th point, such that T i+1 is still a Delaunay triangulation of the convex hull of the i+1 points.
For a finite element application, it is required to construct a mesh of the domain Ω whose elements are as close to equilateral as possible.
The mesh generation methods include an initial creation stage resulting in a mesh T 0, without internal points, except for any specified interior points (see George and Borouchaki (1998) for more details). Such a mesh is referred to as the ‘empty mesh’. This mesh consists of a box which includes the whole geometry plus some vertices on the edge of that box. From here the methods differ in how the required internal points are created.
The general principle of interior mesh generation is to either create a point and insert it immediately by means of the Delaunay method (the so-called Delaunay kernel), repeating the process as long as points can be created, or to generate a series of points, insert this series and iterate the process as long as a non-empty series is created. At this stage it is quite useful to define the notion of a control space to govern the internal point creation. The ‘ideal’ control is the input of a function defined analytically at any point of ℝ 2 and which specifies the size and the direction features that must be conformed to anywhere in the space.
To construct such a function, one can consider several approaches. For our purpose in this chapter, this control function computes, from data, the local step sizes (the desired distance between two points) related to the given points. A generalized interpolation then enables us to obtain the function everywhere. This process is purely geometric in the sense that it relies only on the geometric data properties: boundary edge lengths, and so on. You are advised to consult George and Borouchaki (1998) for more details about this strategy, especially about the other approaches which can be considered to construct the control function.

3 Recommendations on Choice and Use of Available Routines

3.1 Boundary Mesh Generation

The first step to mesh any domain of ℝ 2 or ℝ 3 is to generate a mesh of the domain boundary. In this chapter, since only the 2 D case is considered, the relevant routine is D06BAF. This routine meshes with segments a boundary of a closed connected polygonal domain of ℝ 2, given a set of characteristic points and characteristic lines which define the shape of the frontier. The boundary has to be partitioned into geometrically simple lines. Each line segment may be a straight line, a curve defined by an equation of the type f x,y=0, or simply a polygonal curve, delimited by characteristic points (end points of the lines). Then, you can assemble those lines into connected components of the domain boundary.

3.2 Interior Mesh Generation

In this chapter three routines are provided to mesh a domain given a discretization of its boundary with optionally specified interior points.
  • D06ABF uses an internal point construction method along the internal edges. Using the control function, a small number of points are generated along each edge.
  • D06ACF uses a point creation method based on an advancing front point placement strategy, starting from the ‘empty mesh’.
  • D06AAF uses a simple incremental method based on a control function given analytically via the argument POWER.
Any point construction method results in a set of points. These points are then inserted by means of the Delaunay kernel.
The point insertion process is completed by successive waves. The first wave results from the empty mesh edge analysis (edge method) or from the empty mesh front analysis (advancing front method). Subsequent waves correspond to the analysis of the edges of the previous mesh. For the advancing front strategy, the waves follow the analysis of the front associated with the current mesh.
One can propose a general scheme for a mesh generation method. Seven steps can be identified as follows.
  • Preparation step.
    • Data input: point coordinates, boundary edges and internal edges (if any),
    • construction of the bounding box,
    • meshing of this box by means of a few triangles.
  • Construction of the box mesh.
    • Insertion of the given points in the box mesh using the Delaunay kernel.
  • Construction of the empty mesh.
    • Search for the missing specified edges,
    • enforcement of these edges,
    • definition of the connected components of the domain.
  • Internal point creation and point insertion.
    • Control space definition,
    • 1 internal edge analysis, point creation along these edges,
    • point insertion via the Delaunay kernel and return to 1.
  • Domain definition.
    • Removal of the elements exterior to the domain,
    • classification of the elements with respect to the connected components.
  • Optimization.
    • edge swapping,
    • point relocation, …
  • File output.
When using the advancing front approach described earlier, one has to replace the step denoted by 1 of the general scheme. The analysis of the edges of the current mesh is then replaced by the front analysis.
Due to the fact that the particular mesh generated by D06AAF, D06ABF and D06ACF may be sensitive to the platform being used; there may be differences between generated nodal coordinates and connectivities. However all meshes generated should be expected to satisfy the ‘empty sphere criterion’.

3.3 Mesh Management and Utility Routines

In addition to meshing routines, management and utility routines are also available in this chapter.
A mesh smoother routine D06CAF, is provided to improve mesh triangle quality.
Since the Finite Element framework includes a requirement to solve matrices based on meshes, the routine D06CBF generates the sparsity pattern of such a matrix. Due to the fact that the numbering of unknowns in a linear system could be crucial in term of storage and performance issues, a vertex renumbering routine D06CCF is provided. This routine also returns the new sparsity pattern based on the renumbered mesh.
To mesh a complicated geometry, it is sometimes better to partition the whole geometry into a set of geometrically simpler ones. Some geometry could also be deducted from another geometry by an affine transformation and D06DAF could be used for that purpose. D06DBF is provided to join all the simple geometry meshes. This routine can also handle the joining of two adjacent as well as overlapping meshes, which may be useful in a domain decomposition framework.

4 Example of Use in the Solution of a Partial Differential Equation

The use of Chapter D06 mesh generation routines, together with sparse solver routines from Chapter F11 to solve partial differential equations with the finite element method is described in a NAG Technical Report (see Bouhamou (2001)). This report, and accompanying source code, is available from the NAG web site, or by contacting one of the NAG Response Centres.

5 Functionality Index

Boundary mesh generation,
2 D boundary mesh generation D06BAF
Interior mesh generation,
2 D mesh generation using advancing front method D06ACF
2 D mesh generation using a simple incremental method D06AAF
2 D mesh generation using Delaunay–Voronoi method D06ABF
Mesh Management and Utility routine,
2 D mesh smoother using a barycentering technique D06CAF
2 D mesh transformer by an affine transformation D06DAF
2 D mesh vertex renumbering D06CCF
finite Element matrix sparsity pattern generation D06CBF
joins together two given adjacent (possibly overlapping) meshes D06DBF

6 Auxiliary Routines Associated with Library Routine Arguments

D06BAD nagf_mesh_2d_gen_boundary_dummy_fbnd
See the description of the argument FBND in D06BAF.

7 Routines Withdrawn or Scheduled for Withdrawal

None.

8 References

Bouhamou N (2001) The use of NAG mesh generation and sparse solver routines for solving partial differential equations NAG Technical Report TR 1/01 NAG Ltd, Oxford
Cheung Y K, Lo S H and Leung A Y T (1996) Finite Element Implementation Blackwell Science
George P L and Borouchaki H (1998) Delaunay Triangulation and Meshing: Application to Finite Elements Editions HERMES, Paris
Quarteroni A and Valli A (1997) Numerical approximation of partial differential equations Comp. Maths. 23
D06 Chapter Contents
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


E01AAF : NAG Library, Mark 26

E01 Chapter Contents
E01 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

E01AAF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

E01AAF interpolates a function of one variable at a given point x from a table of function values yi evaluated at equidistant or non-equidistant points xi, for i=1,2,…,n+1, using Aitken's technique of successive linear interpolations.

2 Specification

SUBROUTINE E01AAF ( A, B, C, N1, N2, N, X)
INTEGER | N1, N2, N
REAL (KIND=nag_wp) | A(N1), B(N1), C(N2), X

3 Description

E01AAF interpolates a function of one variable at a given point x from a table of values xi and yi, for i=1,2,…,n+1 using Aitken's method (see Fröberg (1970)). The intermediate values of linear interpolations are stored to enable an estimate of the accuracy of the results to be made.

4 References

Fröberg C E (1970) Introduction to Numerical Analysis Addison–Wesley

5 Arguments

1:   A N1 – REAL (KIND=nag_wp) arrayInput/Output
On entry: A i must contain the x-component of the ith data point, xi, for i=1,2,…,n+1.
On exit: A i contains the value xi-x, for i=1,2,…,n+1.
2:   B N1 – REAL (KIND=nag_wp) arrayInput/Output
On entry: B i must contain the y-component (function value) of the ith data point, yi, for i=1,2,…,n+1.
On exit: the contents of B are unspecified.
3:   C N2 – REAL (KIND=nag_wp) arrayOutput
On exit:
  • C 1,…,C n contain the first set of linear interpolations,
  • C n+1,…,C 2×n-1 contain the second set of linear interpolations,
  • C 2 n,…,C 3×n-3 contain the third set of linear interpolations,
  • ⋮
  • C n×n+1/2 contains the interpolated function value at the point x.
4:   N1 – INTEGERInput
On entry: the value n+1 where n is the number of intervals; that is, N1 is the number of data points.
5:   N2 – INTEGERInput
On entry: the value n×n+1/2 where n is the number of intervals.
6:   N – INTEGERInput
On entry: the number of intervals which are to be used in interpolating the value at x; that is, there are n+1 data points xi,yi.
Constraint: N>0.
7:   X – REAL (KIND=nag_wp)Input
On entry: the point x at which the interpolation is required.

6 Error Indicators and Warnings

None.

7 Accuracy

An estimate of the accuracy of the result can be made from a comparison of the final result and the previous interpolates, given in the array C. In particular, the first interpolate in the ith set, for i=1,2,…,n, is the value at x of the polynomial interpolating the first i+1 data points. It is given in position i-12 n-i+2/2 of the array C. Ideally, providing n is large enough, this set of n interpolates should exhibit convergence to the final value, the difference between one interpolate and the next settling down to a roughly constant magnitude (but with varying sign). This magnitude indicates the size of the error (any subsequent increase meaning that the value of n is too high). Better convergence will be obtained if the data points are supplied, not in their natural order, but ordered so that the first i data points give good coverage of the neighbourhood of x, for all i. To this end, the following ordering is recommended as widely suitable: first the point nearest to x, then the nearest point on the opposite side of x, followed by the remaining points in increasing order of their distance from x, that is of xr-x. With this modification the Aitken method will generally perform better than the related method of Neville, which is often given in the literature as superior to that of Aitken.

8 Parallelism and Performance

E01AAF is not threaded in any implementation.

9 Further Comments

The computation time for interpolation at any point x is proportional to n×n+1/2.

10 Example

This example interpolates at x=0.28 the function value of a curve defined by the points
xi -1.00 -0.50 0.00 0.50 1.00 1.50 yi 0.00 -0.53 -1.00 -0.46 2.00 11.09 .

10.1 Program Text

Program Text (e01aafe.f90)

10.2 Program Data

Program Data (e01aafe.d)

10.3 Program Results

Program Results (e01aafe.r)

E01 Chapter Contents
E01 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


E01ABF : NAG Library, Mark 26

E01 Chapter Contents
E01 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

E01ABF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

E01ABF interpolates a function of one variable at a given point x from a table of function values evaluated at equidistant points, using Everett's formula.

2 Specification

SUBROUTINE E01ABF ( N, P, A, G, N1, N2, IFAIL)
INTEGER | N, N1, N2, IFAIL
REAL (KIND=nag_wp) | P, A(N1), G(N2)

3 Description

E01ABF interpolates a function of one variable at a given point
x=x 0+ph,
where -1<p<1 and h is the interval of differencing, from a table of values xm=x 0+mh and ym where m=-n-1,-n-2,…,-1,0,1,…,n. The formula used is that of Fröberg (1970), neglecting the remainder term:
yp=∑r=0 n-1 1-p+r 2 r+1 δ 2 r y 0+∑r=0 n-1 p+r 2 r+1 δ 2 r y 1.
The values of δ 2 r y 0 and δ 2 r y 1 are stored on exit from the routine in addition to the interpolated function value yp.

4 References

Fröberg C E (1970) Introduction to Numerical Analysis Addison–Wesley

5 Arguments

1:   N – INTEGERInput
On entry: n, half the number of points to be used in the interpolation.
Constraint: N>0.
2:   P – REAL (KIND=nag_wp)Input
On entry: the point p at which the interpolated function value is required, i.e., p=x-x 0/h with -1.0<p<1.0.
Constraint: -1.0<P<1.0.
3:   A N1 – REAL (KIND=nag_wp) arrayInput/Output
On entry: A i must be set to the function value y i-n, for i=1,2,…,2 n.
On exit: the contents of A are unspecified.
4:   G N2 – REAL (KIND=nag_wp) arrayOutput
On exit: the array contains
δ 2 r y 0 | in G 1
δ 2 r y 1 | in G 2
δ 2 r y 0 | in G 2 r+1
δ 2 r y 1 | in G 2 r+2, for r=1,2,…,n-1.
The interpolated function value yp is stored in G 2 n+1.
5:   N1 – INTEGERInput
On entry: the value 2 n, that is, N1 is equal to the number of data points.
6:   N2 – INTEGERInput
On entry: the value 2 n+1, that is, N2 is one more than the number of data points.
7:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, | P≤-1.0,
or | P≥1.0.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

In general, increasing n improves the accuracy of the result until full attainable accuracy is reached, after which it might deteriorate. If x lies in the central interval of the data (i.e., 0.0≤p<1.0), as is desirable, an upper bound on the contribution of the highest order differences (which is usually an upper bound on the error of the result) is given approximately in terms of the elements of the array G by a×G 2 n-1+G 2 n, where a=0.1, 0.02, 0.005, 0.001, 0.0002 for n=1,2,3,4,5 respectively, thereafter decreasing roughly by a factor of 4 each time.

8 Parallelism and Performance

E01ABF is not threaded in any implementation.

9 Further Comments

The computation time increases as the order of n increases.

10 Example

This example interpolates at the point x=0.28 from the function values
xi -1.00 -0.50 0.00 0.50 1.00 1.50 yi 0.00 -0.53 -1.00 -0.46 2.00 11.09 .
We take n=3 and p=0.56.

10.1 Program Text

Program Text (e01abfe.f90)

10.2 Program Data

Program Data (e01abfe.d)

10.3 Program Results

Program Results (e01abfe.r)

E01 Chapter Contents
E01 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


E01AEF : NAG Library, Mark 26

E01 Chapter Contents
E01 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

E01AEF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
▸▿ 9 Further Comments
9.1 Timing
9.2 Divided-difference Strategy
9.3 Conversion to Chebyshev Form
9.4 Iterative Refinement
9.5 Workspace Information
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

E01AEF constructs the Chebyshev series representation of a polynomial interpolant to a set of data which may contain derivative values.

2 Specification

SUBROUTINE E01AEF ( M, XMIN, XMAX, X, Y, IP, N, ITMIN, ITMAX, A, WRK, LWRK, IWRK, LIWRK, IFAIL)
INTEGER | M, IP(M), N, ITMIN, ITMAX, LWRK, IWRK(LIWRK), LIWRK, IFAIL
REAL (KIND=nag_wp) | XMIN, XMAX, X(M), Y(N), A(N), WRK(LWRK)

3 Description

Let m distinct values xi of an independent variable x be given, with xmin≤xi≤xmax, for i=1,2,…,m. For each value xi, suppose that the value yi of the dependent variable y together with the first pi derivatives of y with respect to x are given. Each pi must therefore be a non-negative integer, with the total number of interpolating conditions, n, equal to m+∑i=1 m pi.
E01AEF calculates the unique polynomial q x of degree n-1 (or less) which is such that q k xi=yi k, for i=1,2,…,m and k=0,1,…,pi. Here q 0 xi means q xi. This polynomial is represented in Chebyshev series form in the normalized variable x-, as follows:
q x=12 a 0T 0 x-+a 1T 1 x-+⋯+a n-1T n-1 x-,
where
x-=2 x-xmin-xmax xmax-xmin
so that -1≤x-≤1 for x in the interval xmin to xmax, and where Ti x- is the Chebyshev polynomial of the first kind of degree i with argument x-.
(The polynomial interpolant can subsequently be evaluated for any value of x in the given range by using E02AKF. Chebyshev series representations of the derivative(s) and integral(s) of q x may be obtained by (repeated) use of E02AHF and E02AJF.)
The method used consists first of constructing a divided-difference table from the normalized x- values and the given values of y and its derivatives with respect to x-. The Newton form of q x is then obtained from this table, as described in Huddleston (1974) and Krogh (1970), with the modification described in Section 9.2. The Newton form of the polynomial is then converted to Chebyshev series form as described in Section 9.3.
Since the errors incurred by these stages can be considerable, a form of iterative refinement is used to improve the solution. This refinement is particularly useful when derivatives of rather high order are given in the data. In reasonable examples, the refinement will usually terminate with a certain accuracy criterion satisfied by the polynomial (see Section 7). In more difficult examples, the criterion may not be satisfied and refinement will continue until the maximum number of iterations (as specified by the input argument ITMAX) is reached.
In extreme examples, the iterative process may diverge (even though the accuracy criterion is satisfied): if a certain divergence criterion is satisfied, the process terminates at once. In all cases the routine returns the ‘best’ polynomial achieved before termination. For the definition of ‘best’ and details of iterative refinement and termination criteria, see Section 9.4.

4 References

Huddleston R E (1974) CDC 6600 routines for the interpolation of data and of data with derivatives SLL-74-0214 Sandia Laboratories (Reprint)
Krogh F T (1970) Efficient algorithms for polynomial interpolation and numerical differentiation Math. Comput. 24 185–190

5 Arguments

1:   M – INTEGERInput
On entry: m, the number of given values of the independent variable x.
Constraint: M≥1.
2:   XMIN – REAL (KIND=nag_wp)Input
3:   XMAX – REAL (KIND=nag_wp)Input
On entry: the lower and upper end points, respectively, of the interval xmin,xmax. If they are not determined by your problem, it is recommended that they be set respectively to the smallest and largest values among the xi.
Constraint: XMIN<XMAX.
4:   X M – REAL (KIND=nag_wp) arrayInput
On entry: the value of xi, for i=1,2,…,m. The X i need not be ordered.
Constraint: XMIN≤X i≤XMAX, and the X i must be distinct.
5:   Y N – REAL (KIND=nag_wp) arrayInput
On entry: the given values of the dependent variable, and derivatives, as follows:
The first p 1+1 elements contain y 1,y 1 1 ,…,y 1 p 1 in that order.
The next p 2+1 elements contain y 2,y 2 1 ,…,y 2 p 2 in that order.
 ⋮
The last pm+1 elements contain ym,ym 1 ,…,ym pm in that order.
6:   IP M – INTEGER arrayInput
On entry: pi, the order of the highest-order derivative whose value is given at xi, for i=1,2,…,m. If the value of y only is given for some xi then the corresponding value of IP i must be zero.
Constraint: IP i≥0, for i=1,2,…,M.
7:   N – INTEGERInput
On entry: n, the total number of interpolating conditions.
Constraint: N=M+∑ i=1 M IP i .
8:   ITMIN – INTEGERInput
9:   ITMAX – INTEGERInput
On entry: respectively the minimum and maximum number of iterations to be performed by the routine (for full details see Section 9.4). Setting ITMIN and/or ITMAX negative or zero invokes default value(s) of 2 and/or 10, respectively.
The default values will be satisfactory for most problems, but occasionally significant improvement will result from using higher values.
Suggested value: ITMIN=0 and ITMAX=0.
10:   A N – REAL (KIND=nag_wp) arrayOutput
On exit: A i+1 contains the coefficient ai in the Chebyshev series representation of q x, for i=0,1,…,n-1.
11:   WRK LWRK – REAL (KIND=nag_wp) arrayOutput
On exit: used as workspace, but see also Section 9.5.
12:   LWRK – INTEGERInput
On entry: the dimension of the array WRK as declared in the (sub)program from which E01AEF is called.
Constraint: LWRK≥7×N+5×max ipmax,0+M+7 , where ipmax is the largest element of IP i, for i=1,2,…,M.
13:   IWRK LIWRK – INTEGER arrayOutput
On exit: used as workspace, but see also Section 9.5.
14:   LIWRK – INTEGERInput
On entry: the dimension of the array IWRK as declared in the (sub)program from which E01AEF is called.
Constraint: LIWRK≥2×M+2.
15:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, | M<1,
or | N≠M+IP 1+IP 2+⋯+IP M,
or | LWRK<7×N+5×ipmax+M+7 (see LWRK for the definition of ipmax),
or | LIWRK<2×M+2.
IFAIL=2
On entry, IP i<0 for some i.
IFAIL=3
On entry, | XMIN≥XMAX,
or | X i<XMIN for some i,
or | X i>XMAX,
or | X i=X j for some i≠j.
IFAIL=4
Not all the performance indices are less than eight times the machine precision, although ITMAX iterations have been performed. Arguments A, WRK and IWRK relate to the best polynomial determined. A more accurate solution may possibly be obtained by increasing ITMAX and recalling the routine. See also Sections 7, 9.4 and 9.5.
IFAIL=5
The computation has been terminated because the iterative process appears to be diverging. (Arguments A, WRK and IWRK relate to the best polynomial determined.) Thus the problem specified by your data is probably too ill-conditioned for the solution to be satisfactory. This may result from some of the X i being very close together, or from the number of interpolating conditions, N, being large. If in such cases the conditions do not involve derivatives, you are likely to obtain a much more satisfactory solution to your problem either by cubic spline interpolation (see E01BAF) or by curve-fitting with a polynomial or spline in which the number of coefficients is less than N, preferably much less if N is large (see Chapter E02). But see Sections 7, 9.4 and 9.5.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

A complete error analysis is not currently available, but the method gives good results for reasonable problems.
It is important to realise that for some sets of data, the polynomial interpolation problem is ill-conditioned. That is, a small perturbation in the data may induce large changes in the polynomial, even in exact arithmetic. Though by no means the worst example, interpolation by a single polynomial to a large number of function values given at points equally spaced across the range is notoriously ill-conditioned and the polynomial interpolating such a dataset is prone to exhibit enormous oscillations between the data points, especially near the ends of the range. These will be reflected in the Chebyshev coefficients being large compared with the given function values. A more familiar example of ill-conditioning occurs in the solution of certain systems of linear algebraic equations, in which a small change in the elements of the matrix and/or in the components of the right-hand side vector induces a relatively large change in the solution vector. The best that can be achieved in these cases is to make the residual vector small in some sense. If this is possible, the computed solution is exact for a slightly perturbed set of data. Similar considerations apply to the interpolation problem.
The residuals yi k -q k xi are available for inspection (see Section 9.5). To assess whether these are reasonable, however, it is necessary to relate them to the largest function and derivative values taken by q x over the interval xmin,xmax. The following performance indices aim to do this. Let the kth derivative of q with respect to the normalized variable x- be given by the Chebyshev series
12 a 0 k T 0 x-+a 1 k T 1 x-+⋯+a n-1-k k T n-1-k x-.
Let Ak denote the sum of the moduli of these coefficients (this is an upper bound on the kth derivative in the interval and is taken as a measure of the maximum size of this derivative), and define
Sk = max i≤k Ai .
Then if the root-mean-square value of the residuals of q k , scaled so as to relate to the normalized variable x-, is denoted by rk, the performance indices are defined by
Pk=rk/Sk,   for ​k=0,1,…,maxi pi.
It is expected that, in reasonable cases, they will all be less than (say) 8 times the machine precision (this is the accuracy criterion mentioned in Section 3), and in many cases will be of the order of machine precision or less.

8 Parallelism and Performance

E01AEF is not threaded in any implementation.

9 Further Comments

9.1 Timing

Computation time is approximately proportional to it×n 3, where it is the number of iterations actually used. (See Section 9.5.)

9.2 Divided-difference Strategy

In constructing each new coefficient in the Newton form of the polynomial, a new xi must be brought into the computation. The xi chosen is that which yields the smallest new coefficient. This strategy increases the stability of the divided-difference technique, sometimes quite markedly, by reducing errors due to cancellation.

9.3 Conversion to Chebyshev Form

Conversion from the Newton form to Chebyshev series form is effected by evaluating the former at the n values of x- at which T n-1 x takes the value ±1, and then interpolating these n function values by a call of E02AFF, which provides the Chebyshev series representation of the polynomial with very small additional relative error.

9.4 Iterative Refinement

The iterative refinement process is performed as follows.
Firstly, an initial approximation, q 1 x say, is found by the technique described in Section 3. The rth step of the refinement process then consists of evaluating the residuals of the rth approximation qr x, and constructing an interpolant, d qr x, to these residuals. The next approximation q r+1 x to the interpolating polynomial is then obtained as
q r+1 x=qr x+d qr x.
This completes the description of the rth step.
The iterative process is terminated according to the following criteria. When a polynomial is found whose performance indices (as defined in Section 7) are all less than 8 times the machine precision, the process terminates after ITMIN further iterations (or after a total of ITMAX iterations if that occurs earlier). This will occur in most reasonable problems. The extra iterations are to allow for the possibility of further improvement. If no such polynomial is found, the process terminates after a total of ITMAX iterations. Both these criteria are over-ridden, however, in two special cases. Firstly, if for some value of r the sum of the moduli of the Chebyshev coefficients of d qr x is greater than that of qr x, it is concluded that the process is diverging and the process is terminated at once (q r+1 x is not computed).
Secondly, if at any stage, the performance indices are all computed as zero, again the process is terminated at once.
As the iterations proceed, a record is kept of the best polynomial. Subsequently, at the end of each iteration, the new polynomial replaces the current best polynomial if it satisfies two conditions (otherwise the best polynomial remains unchanged). The first condition is that at least one of its root-mean-square residual values, rk (see Section 7) is smaller than the corresponding value for the current best polynomial. The second condition takes two different forms according to whether or not the performance indices (see Section 7) of the current best polynomial are all less than 8 times the machine precision. If they are, then the largest performance index of the new polynomial is required to be less than that of the current best polynomial. If they are not, the number of indices which are less than 8 times the machine precision must not be smaller than for the current best polynomial. When the iterative process is terminated, it is the polynomial then recorded as best, which is returned to you as q x.

9.5 Workspace Information

On successful exit, and also if IFAIL=4 or 5 on exit, the following information is contained in the workspace arrays WRK and IWRK:
WRK k+1, for k=0,1,…,ipmax where ipmax=maxi pi, contains the ratio of pk, the performance index relating to the kth derivative of the q x finally provided, to 8 times the machine precision.
WRK ipmax+1+j, for j=1,2,…,n, contains the jth residual, i.e., the value of yi k -q k xi, where i and k are the appropriate values corresponding to the jth element in the array Y (see the description of Y in Section 5).
IWRK 1 contains the number of iterations actually performed in deriving q x.
If, on exit, IFAIL=4 or 5, the q x finally provided may still be adequate for your requirements. To assess this you should examine the residuals contained in WRK ipmax+1+j, for j=1,2,…,n, to see whether they are acceptably small.

10 Example

This example constructs an interpolant q x to the following data:
m=4, xmin=2, xmax=6, x 1=2, p 1=0, y 1=1, x 2=4, p 2=1, y 2=2, y 2 1 =-1, x 3=5, p 3=0, y 3=1, x 4=6, p 4=2, y 4=2, y 4 1 =4, y 4 2 =-2.
The coefficients in the Chebyshev series representation of q x are printed, and also the residuals corresponding to each of the given function and derivative values.
This program is written in a generalized form which can read any number of data-sets.

10.1 Program Text

Program Text (e01aefe.f90)

10.2 Program Data

Program Data (e01aefe.d)

10.3 Program Results

Program Results (e01aefe.r)

E01 Chapter Contents
E01 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


E01BAF : NAG Library, Mark 26

E01 Chapter Contents
E01 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

E01BAF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

E01BAF determines a cubic spline interpolant to a given set of data.

2 Specification

SUBROUTINE E01BAF ( M, X, Y, LAMDA, C, LCK, WRK, LWRK, IFAIL)
INTEGER | M, LCK, LWRK, IFAIL
REAL (KIND=nag_wp) | X(M), Y(M), LAMDA(LCK), C(LCK), WRK(LWRK)

3 Description

E01BAF determines a cubic spline s x, defined in the range x 1≤x≤xm, which interpolates (passes exactly through) the set of data points xi,yi, for i=1,2,…,m, where m≥4 and x 1<x 2<⋯<xm. Unlike some other spline interpolation algorithms, derivative end conditions are not imposed. The spline interpolant chosen has m-4 interior knots λ 5,λ 6,…,λm, which are set to the values of x 3,x 4,…,x m-2 respectively. This spline is represented in its B-spline form (see Cox (1975)):
s x=∑i=1 m ciNi x,
where Ni x denotes the normalized B-spline of degree 3, defined upon the knots λi,λ i+1,…,λ i+4, and ci denotes its coefficient, whose value is to be determined by the routine.
The use of B-splines requires eight additional knots λ 1, λ 2, λ 3, λ 4, λ m+1, λ m+2, λ m+3 and λ m+4 to be specified; E01BAF sets the first four of these to x 1 and the last four to xm.
The algorithm for determining the coefficients is as described in Cox (1975) except that QR factorization is used instead of LU decomposition. The implementation of the algorithm involves setting up appropriate information for the related routine E02BAF followed by a call of that routine. (See E02BAF for further details.)
Values of the spline interpolant, or of its derivatives or definite integral, can subsequently be computed as detailed in Section 9.

4 References

Cox M G (1975) An algorithm for spline interpolation J. Inst. Math. Appl. 15 95–108
Cox M G (1977) A survey of numerical methods for data and function approximation The State of the Art in Numerical Analysis (ed D A H Jacobs) 627–668 Academic Press

5 Arguments

1:   M – INTEGERInput
On entry: m, the number of data points.
Constraint: M≥4.
2:   X M – REAL (KIND=nag_wp) arrayInput
On entry: X i must be set to xi, the ith data value of the independent variable x, for i=1,2,…,m.
Constraint: X i<X i+1, for i=1,2,…,M-1.
3:   Y M – REAL (KIND=nag_wp) arrayInput
On entry: Y i must be set to yi, the ith data value of the dependent variable y, for i=1,2,…,m.
4:   LAMDA LCK – REAL (KIND=nag_wp) arrayOutput
On exit: the value of λi, the ith knot, for i=1,2,…,m+4.
5:   C LCK – REAL (KIND=nag_wp) arrayOutput
On exit: the coefficient ci of the B-spline Ni x, for i=1,2,…,m. The remaining elements of the array are not used.
6:   LCK – INTEGERInput
On entry: the dimension of the arrays LAMDA and C as declared in the (sub)program from which E01BAF is called.
Constraint: LCK≥M+4.
7:   WRK LWRK – REAL (KIND=nag_wp) arrayWorkspace
8:   LWRK – INTEGERInput
On entry: the dimension of the array WRK as declared in the (sub)program from which E01BAF is called.
Constraint: LWRK≥6×M+16.
9:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, | M<4,
or | LCK<M+4,
or | LWRK<6×M+16.
IFAIL=2
The X-values fail to satisfy the condition
X 1<X 2<X 3<⋯<X M.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

The rounding errors incurred are such that the computed spline is an exact interpolant for a slightly perturbed set of ordinates yi+δ yi. The ratio of the root-mean-square value of the δ yi to that of the yi is no greater than a small multiple of the relative machine precision.

8 Parallelism and Performance

E01BAF is not threaded in any implementation.

9 Further Comments

The time taken by E01BAF is approximately proportional to m.
All the xi are used as knot positions except x 2 and x m-1. This choice of knots (see Cox (1977)) means that s x is composed of m-3 cubic arcs as follows. If m=4, there is just a single arc space spanning the whole interval x 1 to x 4. If m≥5, the first and last arcs span the intervals x 1 to x 3 and x m-2 to xm respectively. Additionally if m≥6, the ith arc, for i=2,3,…,m-4, spans the interval x i+1 to x i+2.
After the call
CALL E01BAF (M, X, Y, LAMDA, C, LCK, WRK, LWRK, IFAIL)
the following operations may be carried out on the interpolant s x.
The value of s x at x=X can be provided in the real variable S by the call
CALL E02BBF (M+4, LAMDA, C, X, S, IFAIL)
(see E02BBF).
The values of s x and its first three derivatives at x=X can be provided in the real array S of dimension 4, by the call
CALL E02BCF (M+4, LAMDA, C, X, LEFT, S, IFAIL)
(see E02BCF).
Here LEFT must specify whether the left- or right-hand value of the third derivative is required (see E02BCF for details).
The value of the integral of s x over the range x 1 to xm can be provided in the real variable DINT by
CALL E02BDF (M+4, LAMDA, C, DINT, IFAIL)
(see E02BDF).

10 Example

This example sets up data from 7 values of the exponential function in the interval 0 to 1. E01BAF is then called to compute a spline interpolant to these data.
The spline is evaluated by E02BBF, at the data points and at points halfway between each adjacent pair of data points, and the spline values and the values of ex are printed out.

10.1 Program Text

Program Text (e01bafe.f90)

10.2 Program Data

None.

10.3 Program Results

Program Results (e01bafe.r)

E01 Chapter Contents
E01 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


E01BEF : NAG Library, Mark 26

E01 Chapter Contents
E01 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

E01BEF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

E01BEF computes a monotonicity-preserving piecewise cubic Hermite interpolant to a set of data points.

2 Specification

SUBROUTINE E01BEF ( N, X, F, D, IFAIL)
INTEGER | N, IFAIL
REAL (KIND=nag_wp) | X(N), F(N), D(N)

3 Description

E01BEF estimates first derivatives at the set of data points xr,fr, for r=1,2,…,n, which determine a piecewise cubic Hermite interpolant to the data, that preserves monotonicity over ranges where the data points are monotonic. If the data points are only piecewise monotonic, the interpolant will have an extremum at each point where monotonicity switches direction. The estimates of the derivatives are computed by a formula due to Brodlie, which is described in Fritsch and Butland (1984), with suitable changes at the boundary points.
The routine is derived from routine PCHIM in Fritsch (1982).
Values of the computed interpolant, and of its first derivative and definite integral, can subsequently be computed by calling E01BFF, E01BGF and E01BHF, as described in Section 9.

4 References

Fritsch F N (1982) PCHIP final specifications Report UCID-30194 Lawrence Livermore National Laboratory
Fritsch F N and Butland J (1984) A method for constructing local monotone piecewise cubic interpolants SIAM J. Sci. Statist. Comput. 5 300–304

5 Arguments

1:   N – INTEGERInput
On entry: n, the number of data points.
Constraint: N≥2.
2:   X N – REAL (KIND=nag_wp) arrayInput
On entry: X r must be set to xr, the rth value of the independent variable (abscissa), for r=1,2,…,n.
Constraint: X r<X r+1.
3:   F N – REAL (KIND=nag_wp) arrayInput
On entry: F r must be set to fr, the rth value of the dependent variable (ordinate), for r=1,2,…,n.
4:   D N – REAL (KIND=nag_wp) arrayOutput
On exit: estimates of derivatives at the data points. D r contains the derivative at X r.
5:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, N<2.
IFAIL=2
The values of X r, for r=1,2,…,N, are not in strictly increasing order.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

The computational errors in the array D should be negligible in most practical situations.

8 Parallelism and Performance

E01BEF is not threaded in any implementation.

9 Further Comments

The time taken by E01BEF is approximately proportional to n.
The values of the computed interpolant at the points PX i, for i=1,2,…,M, may be obtained in the real array PF, of length at least M, by the call:
CALL E01BFF(N,X,F,D,M,PX,PF,IFAIL)
where N, X and F are the input arguments to E01BEF and D is the output argument from E01BEF.
The values of the computed interpolant at the points PX i, for i=1,2,…,M, together with its first derivatives, may be obtained in the real arrays PF and PD, both of length at least M, by the call:
CALL E01BGF(N,X,F,D,M,PX,PF,PD,IFAIL)
where N, X, F and D are as described above.
The value of the definite integral of the interpolant over the interval A to B can be obtained in the real variable PINT by the call:
CALL E01BHF(N,X,F,D,A,B,PINT,IFAIL)
where N, X, F and D are as described above.

10 Example

This example reads in a set of data points, calls E01BEF to compute a piecewise monotonic interpolant, and then calls E01BFF to evaluate the interpolant at equally spaced points.

10.1 Program Text

Program Text (e01befe.f90)

10.2 Program Data

Program Data (e01befe.d)

10.3 Program Results

Program Results (e01befe.r)

E01 Chapter Contents
E01 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


E01BFF : NAG Library, Mark 26

E01 Chapter Contents
E01 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

E01BFF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

E01BFF evaluates a piecewise cubic Hermite interpolant at a set of points.

2 Specification

SUBROUTINE E01BFF ( N, X, F, D, M, PX, PF, IFAIL)
INTEGER | N, M, IFAIL
REAL (KIND=nag_wp) | X(N), F(N), D(N), PX(M), PF(M)

3 Description

E01BFF evaluates a piecewise cubic Hermite interpolant, as computed by E01BEF, at the points PX i, for i=1,2,…,m. If any point lies outside the interval from X 1 to X N, a value is extrapolated from the nearest extreme cubic, and a warning is returned.
The routine is derived from routine PCHFE in Fritsch (1982).

4 References

Fritsch F N (1982) PCHIP final specifications Report UCID-30194 Lawrence Livermore National Laboratory

5 Arguments

1:   N – INTEGERInput
2:   X N – REAL (KIND=nag_wp) arrayInput
3:   F N – REAL (KIND=nag_wp) arrayInput
4:   D N – REAL (KIND=nag_wp) arrayInput
On entry: N, X, F and D must be unchanged from the previous call of E01BEF.
5:   M – INTEGERInput
On entry: m, the number of points at which the interpolant is to be evaluated. If any point lies outside the interval from X 1) to X N, a value is extrapolated from the nearest extreme cubic, and a warning is returned. The extrapolation simply extends the final cubic at each end.
Constraint: M≥1.
6:   PX M – REAL (KIND=nag_wp) arrayInput
On entry: the m values of x at which the interpolant is to be evaluated.
7:   PF M – REAL (KIND=nag_wp) arrayOutput
On exit: PF i contains the value of the interpolant evaluated at the point PX i, for i=1,2,…,m.
8:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, N<2.
IFAIL=2
The values of X r, for r=1,2,…,N, are not in strictly increasing order.
IFAIL=3
On entry, M<1.
IFAIL=4
At least one of the points PX i, for i=1,2,…,M, lies outside the interval [X 1,X N], and extrapolation was performed at all such points. Values computed at such points may be very unreliable.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

The computational errors in the array PF should be negligible in most practical situations.

8 Parallelism and Performance

E01BFF is not threaded in any implementation.

9 Further Comments

The time taken by E01BFF is approximately proportional to the number of evaluation points, m. The evaluation will be most efficient if the elements of PX are in nondecreasing order (or, more generally, if they are grouped in increasing order of the intervals X r-1,X r). A single call of E01BFF with m>1 is more efficient than several calls with m=1.
As documented above, this routine will use extrapolation if presented with evaluation points outside the region x 1,xn . Since such extrapolated values are computed simply by extending the cubic approximation at each end interval, the values may not be suitable for all purposes. If you need more control over how values outside the original region are calculated, consider the following possible procedures for degree 0, 1 and 2 extrapolation.
(i) Flat extrapolation
  • For x<x 1 choose f = F 1;
  • for x>xn choose f=F N.
(ii) Linear extrapolation
  • For x<x 1 , call E01BGF using PX 1 = X 1 to obtain PD 1 , then choose f = PD 1 × x- X 1 + F 1 ;
  • for x>xn, call E01BGF using PX 1 = X N to obtain PD N , then choose f= PD N × x- X N + F N .
(iii) Quadratic extrapolation
  • For x<x 1 , call E01BGF to obtain derivative values PD 1 and PD 2 at x 1 and x 2,
    • if PD 2 ≥ PD 1 revert to linear extrapolation (ii),
    • otherwise let l 1 x = x-x 1 , l 2 x = x-x 2 and c=1/ x 1 - x 2 , then choose f x = PD 1 × l 1 x × l 2 x × c-F 1 × l 2 x × l 1 x + l 1 x 2 × c 2 + F 2 × l 1 x × c 2 ;
  • for x>xn, call E01BGF to obtain derivative values PD N and PD N-1 at xn and x n-1,
    • if PD N-1 ≥ PD N revert to linear extrapolation (ii),
    • otherwise let ln x = x-xn , l n-1 x = x - x n-1 and c=1/ xn- x n-1 , then choose f x = PD N × ln x × l n-1 x × c-F N × l n-1 x × ln x + ln x n-1 × c 2 + F N-1 × ln x × c 2 .

10 Example

This example reads in values of N, X, F and D, and then calls E01BFF to evaluate the interpolant at equally spaced points.

10.1 Program Text

Program Text (e01bffe.f90)

10.2 Program Data

Program Data (e01bffe.d)

10.3 Program Results

Program Results (e01bffe.r)

E01 Chapter Contents
E01 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


E01BGF : NAG Library, Mark 26

E01 Chapter Contents
E01 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

E01BGF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

E01BGF evaluates a piecewise cubic Hermite interpolant and its first derivative at a set of points.

2 Specification

SUBROUTINE E01BGF ( N, X, F, D, M, PX, PF, PD, IFAIL)
INTEGER | N, M, IFAIL
REAL (KIND=nag_wp) | X(N), F(N), D(N), PX(M), PF(M), PD(M)

3 Description

E01BGF evaluates a piecewise cubic Hermite interpolant, as computed by E01BEF, at the points PX i, for i=1,2,…,m. The first derivatives at the points are also computed. If any point lies outside the interval from X 1 to X N, values of the interpolant and its derivative are extrapolated from the nearest extreme cubic, and a warning is returned.
If values of the interpolant only, and not of its derivative, are required, E01BFF should be used.
The routine is derived from routine PCHFD in Fritsch (1982).

4 References

Fritsch F N (1982) PCHIP final specifications Report UCID-30194 Lawrence Livermore National Laboratory

5 Arguments

1:   N – INTEGERInput
2:   X N – REAL (KIND=nag_wp) arrayInput
3:   F N – REAL (KIND=nag_wp) arrayInput
4:   D N – REAL (KIND=nag_wp) arrayInput
On entry: N, X, F and D must be unchanged from the previous call of E01BEF.
5:   M – INTEGERInput
On entry: m, the number of points at which the interpolant is to be evaluated.
Constraint: M≥1.
6:   PX M – REAL (KIND=nag_wp) arrayInput
On entry: the m values of x at which the interpolant is to be evaluated.
7:   PF M – REAL (KIND=nag_wp) arrayOutput
On exit: PF i contains the value of the interpolant evaluated at the point PX i, for i=1,2,…,m.
8:   PD M – REAL (KIND=nag_wp) arrayOutput
On exit: PD i contains the first derivative of the interpolant evaluated at the point PX i, for i=1,2,…,m.
9:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, N<2.
IFAIL=2
The values of X r, for r=1,2,…,N, are not in strictly increasing order.
IFAIL=3
On entry, M<1.
IFAIL=4
At least one of the points PX i, for i=1,2,…,M, lies outside the interval [X 1,X N], and extrapolation was performed at all such points. Values computed at these points may be very unreliable.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

The computational errors in the arrays PF and PD should be negligible in most practical situations.

8 Parallelism and Performance

E01BGF is not threaded in any implementation.

9 Further Comments

The time taken by E01BGF is approximately proportional to the number of evaluation points, m. The evaluation will be most efficient if the elements of PX are in nondecreasing order (or, more generally, if they are grouped in increasing order of the intervals X r-1,X r). A single call of E01BGF with m>1 is more efficient than several calls with m=1.

10 Example

This example reads in values of N, X, F and D, and calls E01BGF to compute the values of the interpolant and its derivative at equally spaced points.

10.1 Program Text

Program Text (e01bgfe.f90)

10.2 Program Data

Program Data (e01bgfe.d)

10.3 Program Results

Program Results (e01bgfe.r)

GnuplotProduced by GNUPLOT 4.6 patchlevel 3 0 0.2 0.4 0.6 0.8 1 1.2 8 10 12 14 16 18 20 x Example Program Monotonic Hermite interpolant gnuplot_plot_1 Function gnuplot_plot_2 Derivative gnuplot_plot_3 Original data points
E01 Chapter Contents
E01 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


E01BHF : NAG Library, Mark 26

E01 Chapter Contents
E01 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

E01BHF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

E01BHF evaluates the definite integral of a piecewise cubic Hermite interpolant over the interval a,b.

2 Specification

SUBROUTINE E01BHF ( N, X, F, D, A, B, PINT, IFAIL)
INTEGER | N, IFAIL
REAL (KIND=nag_wp) | X(N), F(N), D(N), A, B, PINT

3 Description

E01BHF evaluates the definite integral of a piecewise cubic Hermite interpolant, as computed by E01BEF, over the interval a,b.
If either a or b lies outside the interval from X 1 to X N computation of the integral involves extrapolation and a warning is returned.
The routine is derived from routine PCHIA in Fritsch (1982).

4 References

Fritsch F N (1982) PCHIP final specifications Report UCID-30194 Lawrence Livermore National Laboratory

5 Arguments

1:   N – INTEGERInput
2:   X N – REAL (KIND=nag_wp) arrayInput
3:   F N – REAL (KIND=nag_wp) arrayInput
4:   D N – REAL (KIND=nag_wp) arrayInput
On entry: N, X, F and D must be unchanged from the previous call of E01BEF.
5:   A – REAL (KIND=nag_wp)Input
6:   B – REAL (KIND=nag_wp)Input
On entry: the interval a,b over which integration is to be performed.
7:   PINT – REAL (KIND=nag_wp)Output
On exit: the value of the definite integral of the interpolant over the interval a,b.
8:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, N<2.
IFAIL=2
The values of X r, for r=1,2,…,N, are not in strictly increasing order.
IFAIL=3
On entry, at least one of A or B lies outside the interval [X 1,X N], and extrapolation was performed to compute the integral. The value returned is therefore unreliable.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

The computational error in the value returned for PINT should be negligible in most practical situations.

8 Parallelism and Performance

E01BHF is not threaded in any implementation.

9 Further Comments

The time taken by E01BHF is approximately proportional to the number of data points included within the interval a,b.

10 Example

This example reads in values of N, X, F and D. It then reads in pairs of values for A and B, and evaluates the definite integral of the interpolant over the interval A,B until end-of-file is reached.

10.1 Program Text

Program Text (e01bhfe.f90)

10.2 Program Data

Program Data (e01bhfe.d)

10.3 Program Results

Program Results (e01bhfe.r)

E01 Chapter Contents
E01 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


E01 Chapter Contents : NAG Library Manual, Mark 26

E01 Chapter Introduction
NAG Library Manual

NAG Library Chapter Contents

E01 – Interpolation

E01 Chapter Introduction – a description of the Chapter and an overview of the algorithms available

Routine Name | Mark of Introduction | Purpose
E01AAF Example Text Example Data | 1 | nagf_interp_1d_aitken Interpolated values, Aitken's technique, unequally spaced data, one variable
E01ABF Example Text Example Data | 1 | nagf_interp_1d_everett Interpolated values, Everett's formula, equally spaced data, one variable
E01AEF Example Text Example Data | 8 | nagf_interp_1d_cheb Interpolating functions, polynomial interpolant, data may include derivative values, one variable
E01BAF Example Text | 8 | nagf_interp_1d_spline Interpolating functions, cubic spline interpolant, one variable
E01BEF Example Text Example Data | 13 | nagf_interp_1d_monotonic Interpolating functions, monotonicity-preserving, piecewise cubic Hermite, one variable
E01BFF Example Text Example Data | 13 | nagf_interp_1d_monotonic_eval Interpolated values, interpolant computed by E01BEF, function only, one variable
E01BGF Example Text Example Data Example Plot | 13 | nagf_interp_1d_monotonic_deriv Interpolated values, interpolant computed by E01BEF, function and first derivative, one variable
E01BHF Example Text Example Data | 13 | nagf_interp_1d_monotonic_intg Interpolated values, interpolant computed by E01BEF, definite integral, one variable
E01DAF Example Text Example Data | 14 | nagf_interp_2d_spline_grid Interpolating functions, fitting bicubic spline, data on rectangular grid
E01EAF Example Text Example Data Example Plot | 25 | nagf_interp_2d_triangulate Triangulation of two-dimensional scattered grid, method of Renka and Cline
E01EBF | 25 | nagf_interp_2d_triang_bary_eval Barycentric interpolation on function values provided on a two-dimensional scattered grid
E01RAF Example Text Example Data | 9 | nagf_interp_1d_ratnl Interpolating functions, rational interpolant, one variable
E01RBF Example Text Example Data | 9 | nagf_interp_1d_ratnl_eval Interpolated values, evaluate rational interpolant computed by E01RAF, one variable
E01SAF Example Text Example Data | 13 | nagf_interp_2d_scat Interpolating functions, method of Renka and Cline, two variables
E01SBF | 13 | nagf_interp_2d_scat_eval Interpolated values, evaluate interpolant computed by E01SAF, two variables
E01SGF Example Text Example Data | 18 | nagf_interp_2d_scat_shep Interpolating functions, modified Shepard's method, two variables
E01SHF | 18 | nagf_interp_2d_scat_shep_eval Interpolated values, evaluate interpolant computed by E01SGF, function and first derivatives, two variables
E01TGF Example Text Example Data | 18 | nagf_interp_3d_scat_shep Interpolating functions, modified Shepard's method, three variables
E01THF | 18 | nagf_interp_3d_scat_shep_eval Interpolated values, evaluate interpolant computed by E01TGF, function and first derivatives, three variables
E01TKF Example Text Example Data | 23 | nagf_interp_4d_scat_shep Interpolating functions, modified Shepard's method, four variables
E01TLF Example Text Example Data | 23 | nagf_interp_4d_scat_shep_eval Interpolated values, evaluate interpolant computed by E01TKF, function and first derivatives, four variables
E01TMF Example Text Example Data | 23 | nagf_interp_5d_scat_shep Interpolating functions, modified Shepard's method, five variables
E01TNF Example Text Example Data | 23 | nagf_interp_5d_scat_shep_eval Interpolated values, evaluate interpolant computed by E01TMF, function and first derivatives, five variables
E01ZMF Example Text Example Data | 24 | nagf_interp_nd_scat_shep Interpolating function, modified Shepard's method, d dimensions
E01ZNF Example Text Example Data | 24 | nagf_interp_nd_scat_shep_eval Interpolated values, evaluate interpolant computed by E01ZMF, function and first derivatives, d dimensions
E01 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


E01DAF : NAG Library, Mark 26

E01 Chapter Contents
E01 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

E01DAF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
▸▿ 9 Further Comments
9.1 Timing
9.2 Outline of Method Used
9.3 Evaluation of Computed Spline
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

E01DAF computes a bicubic spline interpolating surface through a set of data values, given on a rectangular grid in the x-y plane.

2 Specification

SUBROUTINE E01DAF ( MX, MY, X, Y, F, PX, PY, LAMDA, MU, C, WRK, IFAIL)
INTEGER | MX, MY, PX, PY, IFAIL
REAL (KIND=nag_wp) | X(MX), Y(MY), F(MX*MY), LAMDA(MX+4), MU(MY+4), C(MX*MY), WRK((MX+6)*(MY+6))

3 Description

E01DAF determines a bicubic spline interpolant to the set of data points x q , y r , f q , r , for q=1,2,…,mx and r=1,2,…,my. The spline is given in the B-spline representation
s x,y=∑i=1 mx∑j=1 my c ijMi x Nj y,
such that
s xq,yr=f q,r,
where Mi x and Nj y denote normalized cubic B-splines, the former defined on the knots λi to λ i+4 and the latter on the knots μj to μ j+4, and the c ij are the spline coefficients. These knots, as well as the coefficients, are determined by the routine, which is derived from the routine B2IRE in Anthony et al. (1982). The method used is described in Section 9.2.
For further information on splines, see Hayes and Halliday (1974) for bicubic splines and de Boor (1972) for normalized B-splines.
Values and derivatives of the computed spline can subsequently be computed by calling E02DEF, E02DFF or E02DHF as described in Section 9.3.

4 References

Anthony G T, Cox M G and Hayes J G (1982) DASL – Data Approximation Subroutine Library National Physical Laboratory
Cox M G (1975) An algorithm for spline interpolation J. Inst. Math. Appl. 15 95–108
de Boor C (1972) On calculating with B-splines J. Approx. Theory 6 50–62
Hayes J G and Halliday J (1974) The least squares fitting of cubic spline surfaces to general data sets J. Inst. Math. Appl. 14 89–103

5 Arguments

1:   MX – INTEGERInput
2:   MY – INTEGERInput
On entry: MX and MY must specify mx and my respectively, the number of points along the x and y axis that define the rectangular grid.
Constraint: MX≥4 and MY≥4.
3:   X MX – REAL (KIND=nag_wp) arrayInput
4:   Y MY – REAL (KIND=nag_wp) arrayInput
On entry: X q and Y r must contain xq, for q=1,2,…,mx, and yr, for r=1,2,…,my, respectively.
Constraints:
  • X q<X q+1, for q=1,2,…,mx-1;
  • Y r<Y r+1, for r=1,2,…,my-1.
5:   F MX×MY – REAL (KIND=nag_wp) arrayInput
On entry: F my×q-1+r must contain f q,r, for q=1,2,…,mx and r=1,2,…,my.
6:   PX – INTEGEROutput
7:   PY – INTEGEROutput
On exit: PX and PY contain mx+4 and my+4, the total number of knots of the computed spline with respect to the x and y variables, respectively.
8:   LAMDA MX+4 – REAL (KIND=nag_wp) arrayOutput
9:   MU MY+4 – REAL (KIND=nag_wp) arrayOutput
On exit: LAMDA contains the complete set of knots λi associated with the x variable, i.e., the interior knots LAMDA 5,LAMDA 6,…,LAMDA PX-4, as well as the additional knots
LAMDA 1=LAMDA 2=LAMDA 3=LAMDA 4=X 1
and
LAMDA PX-3=LAMDA PX-2=LAMDA PX-1=LAMDA PX=X MX
needed for the B-spline representation.
10:   C MX×MY – REAL (KIND=nag_wp) arrayOutput
On exit: the coefficients of the spline interpolant. C my×i-1+j contains the coefficient c ij described in Section 3.
11:   WRK MX+6×MY+6 – REAL (KIND=nag_wp) arrayWorkspace
12:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, | MX<4,
or | MY<4.
IFAIL=2
On entry, either the values in the X array or the values in the Y array are not in increasing order if not already there.
IFAIL=3
A system of linear equations defining the B-spline coefficients was singular; the problem is too ill-conditioned to permit solution.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

The main sources of rounding errors are in steps 2, 3, 6 and 7 of the algorithm described in Section 9.2. It can be shown (see Cox (1975)) that the matrix Ax formed in step 2 has elements differing relatively from their true values by at most a small multiple of 3 ε, where ε is the machine precision. Ax is ‘totally positive’, and a linear system with such a coefficient matrix can be solved quite safely by elimination without pivoting. Similar comments apply to steps 6 and 7. Thus the complete process is numerically stable.

8 Parallelism and Performance

E01DAF makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

9.1 Timing

The time taken by E01DAF is approximately proportional to mxmy.

9.2 Outline of Method Used

The process of computing the spline consists of the following steps:
1. | choice of the interior x-knots λ 5, λ 6,…,λ mx as λi=x i-2, for i=5,6,…,mx,
2. formation of the system
Ax E=F,
where Ax is a band matrix of order mx and bandwidth 4, containing in its qth row the values at xq of the B-splines in x, F is the mx by my rectangular matrix of values f q,r, and E denotes an mx by my rectangular matrix of intermediate coefficients,
3. | use of Gaussian elimination to reduce this system to band triangular form,
4. | solution of this triangular system for E,
5. | choice of the interior y knots μ 5, μ 6,…,μ my as μi=y i-2, for i=5,6,…,my,
6. formation of the system
Ay CT=ET,
where Ay is the counterpart of Ax for the y variable, and C denotes the mx by my rectangular matrix of values of c ij,
7. | use of Gaussian elimination to reduce this system to band triangular form,
8. | solution of this triangular system for CT and hence C.
For computational convenience, steps 2 and 3, and likewise steps 6 and 7, are combined so that the formation of Ax and Ay and the reductions to triangular form are carried out one row at a time.

9.3 Evaluation of Computed Spline

The values of the computed spline at the points xk,yk , for k=1,2,…,m, may be obtained in the real array FF (see E02DEF), of length at least m, by the following call:
IFAIL = 0
CALL E02DEF(M,PX,PY,X,Y,LAMDA,MU,C,FF,WRK,IWRK,IFAIL)
where M=m and the coordinates xk, yk are stored in X k, Y k. PX and PY, LAMDA, MU and C have the same values as PX and PY LAMDA, MU and C output from E01DAF. WRK is a real workspace array of length at least PY, and IWRK is an integer workspace array of length at least PY-4. (See E02DEF.)
To evaluate the computed spline on an mx by my rectangular grid of points in the x-y plane, which is defined by the x coordinates stored in X j, for j=1,2,…,mx, and the y coordinates stored in Y k, for k=1,2,…,my, returning the results in the real array FF (see E02DFF) which is of length at least MX×MY, the following call may be used:
 IFAIL = 0
 CALL E02DFF(MX,MY,PX,PY,X,Y,LAMDA,MU,C,FG,WRK,LWRK,
*            IWRK,LIWRK,IFAIL)
where MX=mx, MY=my. PX and PY, LAMDA, MU and C have the same values as PX, PY, LAMDA, MU and C output from E01DAF. WRK is a real workspace array of length at least LWRK = min nwrk1,nwrk2 , for nwrk1 = MX × 4 + PX , nwrk2 = MY × 4 + PY , and IWRK is an integer workspace array of length at least LIWRK = MY + PY - 4 if nwrk1 > nwrk2 , or MX + PX - 4 otherwise.
The result of the spline evaluated at grid point j,k is returned in element ( MY×j-1+k ) of the array FG.

10 Example

This example reads in values of mx, xq, for q=1,2,…,mx, my and yr, for r=1,2,…,my, followed by values of the ordinates f q,r defined at the grid points xq,yr.
It then calls E01DAF to compute a bicubic spline interpolant of the data values, and prints the values of the knots and B-spline coefficients. Finally it evaluates the spline at a small sample of points on a rectangular grid.

10.1 Program Text

Program Text (e01dafe.f90)

10.2 Program Data

Program Data (e01dafe.d)

10.3 Program Results

Program Results (e01dafe.r)

E01 Chapter Contents
E01 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


E01EAF : NAG Library, Mark 26

E01 Chapter Contents
E01 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

E01EAF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

E01EAF generates a triangulation for a given set of two-dimensional points using the method of Renka and Cline.

2 Specification

SUBROUTINE E01EAF ( N, X, Y, TRIANG, IFAIL)
INTEGER | N, TRIANG(7*N), IFAIL
REAL (KIND=nag_wp) | X(N), Y(N)

3 Description

E01EAF creates a Thiessen triangulation with a given set of two-dimensional data points as nodes. This triangulation will be as equiangular as possible (Cline and Renka (1984)). See Renka and Cline (1984) for more detailed information on the algorithm, a development of that by Lawson (1977). The code is derived from Renka (1984).
The computed triangulation is returned in a form suitable for passing to E01EBF which, for a set of nodal function values, computes interpolated values at a set of points.

4 References

Cline A K and Renka R L (1984) A storage-efficient method for construction of a Thiessen triangulation Rocky Mountain J. Math. 14 119–139
Lawson C L (1977) Software for C 1 surface interpolation Mathematical Software III (ed J R Rice) 161–194 Academic Press
Renka R L (1984) Algorithm 624: triangulation and interpolation of arbitrarily distributed points in the plane ACM Trans. Math. Software 10 440–442
Renka R L and Cline A K (1984) A triangle-based C 1 interpolation method Rocky Mountain J. Math. 14 223–237

5 Arguments

1:   N – INTEGERInput
On entry: n, the number of data points.
Constraint: N≥3.
2:   X N – REAL (KIND=nag_wp) arrayInput
On entry: the x coordinates of the n data points.
3:   Y N – REAL (KIND=nag_wp) arrayInput
On entry: the y coordinates of the n data points.
4:   TRIANG 7×N – INTEGER arrayOutput
On exit: a data structure defining the computed triangulation, in a form suitable for passing to E01EBF. Details of how the triangulation is encoded in TRIANG are given in Section 9. These details are most likely to be of use when plotting the computed triangulation which is demonstrated in Section 10.
5:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, N=value.
Constraint: N≥3.
IFAIL=2
On entry, all the x,y pairs are collinear.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

Not applicable.

8 Parallelism and Performance

E01EAF is not threaded in any implementation.

9 Further Comments

The time taken for a call of E01EAF is approximately proportional to the number of data points, n. The routine is more efficient if, before entry, the x,y pairs are arranged in X and Y such that the x values are in ascending order.
The triangulation is encoded in TRIANG as follows:
  • set j 0=0; for each node, k=1,2,…,n, (using the ordering inferred from X and Y)
    • ik = j k-1 +1
    • jk = TRIANG 6×N+k
    • TRIANG j, for j=ik,…,jk, contains the list of nodes to which node k is connected. If TRIANG jk=0 then node k is on the boundary of the mesh.

10 Example

In this example, E01EAF creates a triangulation from a set of data points. E01EBF then evaluates the interpolant at a sample of points using this triangulation. Note that this example is not typical of a realistic problem: the number of data points would normally be larger, so that interpolants can be more accurately evaluated at the fine triangulated grid.

10.1 Program Text

Program Text (e01eafe.f90)

10.2 Program Data

Program Data (e01eafe.d)

10.3 Program Results

Program Results (e01eafe.r)

GnuplotProduced by GNUPLOT 4.6 patchlevel 3 0 5 10 15 20 0 5 10 15 20 25 Example Program Thiessen Triangulation for given Data Points gnuplot_plot_1
E01 Chapter Contents
E01 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


E01EBF : NAG Library, Mark 26

E01 Chapter Contents
E01 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

E01EBF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
10 Example

1 Purpose

E01EBF performs barycentric interpolation, at a given set of points, using a set of function values on a scattered grid and a triangulation of that grid computed by E01EAF.

2 Specification

SUBROUTINE E01EBF ( M, N, X, Y, F, TRIANG, PX, PY, PF, IFAIL)
INTEGER | M, N, TRIANG(7*N), IFAIL
REAL (KIND=nag_wp) | X(N), Y(N), F(N), PX(M), PY(M), PF(M)

3 Description

E01EBF takes as input a set of scattered data points xr,yr,fr , for r=1,2,…,n, and a Thiessen triangulation of the xr,yr computed by E01EAF, and interpolates at a set of points pxi,pyi , for i=1,2,…,m.
If the ith interpolation point pxi,pyi is equal to xr,yr for some value of r, the returned value will be equal to fr; otherwise a barycentric transformation will be used to calculate the interpolant.
For each point pxi,pyi , a triangle is sought which contains the point; the vertices of the triangle and fr values at the vertices are then used to compute the value F pxi,pyi .
If any interpolation point lies outside the triangulation defined by the input arguments, the returned value is the value provided, fs, at the closest node xs,ys .
E01EBF must only be called after a call to E01EAF.

4 References

Cline A K and Renka R L (1984) A storage-efficient method for construction of a Thiessen triangulation Rocky Mountain J. Math. 14 119–139
Lawson C L (1977) Software for C 1 surface interpolation Mathematical Software III (ed J R Rice) 161–194 Academic Press
Renka R L (1984) Algorithm 624: triangulation and interpolation of arbitrarily distributed points in the plane ACM Trans. Math. Software 10 440–442
Renka R L and Cline A K (1984) A triangle-based C 1 interpolation method Rocky Mountain J. Math. 14 223–237

5 Arguments

1:   M – INTEGERInput
On entry: m, the number of points to interpolate.
Constraint: M≥1.
2:   N – INTEGERInput
On entry: n, the number of data points. N must be unchanged from the previous call of E01EAF.
Constraint: N≥3.
3:   X N – REAL (KIND=nag_wp) arrayInput
4:   Y N – REAL (KIND=nag_wp) arrayInput
On entry: the coordinates of the rth data point, xr,yr, for r=1,2,…,n. X and Y must be unchanged from the previous call of E01EAF.
5:   F N – REAL (KIND=nag_wp) arrayInput
On entry: the function values fr at xr,yr, for r=1,2,…,n.
6:   TRIANG 7×N – INTEGER arrayInput
On entry: the triangulation computed by the previous call of E01EAF. See Section 9 in E01EAF for details of how the triangulation used is encoded in TRIANG.
7:   PX M – REAL (KIND=nag_wp) arrayInput
8:   PY M – REAL (KIND=nag_wp) arrayInput
On entry: the coordinates pxi,pyi, for i=1,2,…,m, at which interpolated function values are sought.
9:   PF M – REAL (KIND=nag_wp) arrayOutput
On exit: the interpolated values F pxi,pyi, for i=1,2,…,m.
10:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, N=value.
Constraint: N≥3.
IFAIL=2
On entry, M=value.
Constraint: M≥1.
IFAIL=3
On entry, the triangulation information held in the array TRIANG does not specify a valid triangulation of the data points. TRIANG has been corrupted since the call to E01EAF.
IFAIL=4
At least one evaluation point lies outside the nodal triangulation. For each such point the value returned in PF is that corresponding to a node on the closest boundary line segment.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

Not applicable.

8 Parallelism and Performance

E01EBF is not threaded in any implementation.

9 Further Comments

The time taken for a call of E01EBF is approximately proportional to the number of interpolation points, m.

10 Example

See Section 10 in E01EAF.
E01 Chapter Contents
E01 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


E01 Chapter Introduction : NAG Library, Mark 26

E01 Chapter Contents
NAG Library Manual

NAG Library Chapter Introduction

E01 – Interpolation

▸▿ Contents

1 Scope of the Chapter
2 Background to the Problems
▸▿ 3 Recommendations on Choice and Use of Available Routines
3.1 General
▸▿ 3.2 One Independent Variable
3.2.1 Interpolated values: data without derivatives
3.2.2 Interpolating function: data without derivatives
3.2.3 Data containing derivatives
▸▿ 3.3 Two Independent Variables
3.3.1 Data on a rectangular mesh
3.3.2 Arbitrary data
▸▿ 3.4 Three Independent Variables
3.4.1 Arbitrary data
▸▿ 3.5 Four and Five Independent Variables
3.5.1 Arbitrary data
▸▿ 3.6 Multidimensional interpolation
3.6.1 Arbitrary data
4 Decision Tree
5 Functionality Index
6 Auxiliary Routines Associated with Library Routine Arguments
7 Routines Withdrawn or Scheduled for Withdrawal
8 References

1 Scope of the Chapter

This chapter is concerned with the interpolation of a function of one or more variables. When provided with the value of the function (and possibly one or more of its lowest-order derivatives) at each of a number of values of the variable(s), the NAG Library routines provide either an interpolating function or an interpolated value. For some of the interpolating functions, there are supporting NAG Library routines to evaluate, differentiate or integrate them.

2 Background to the Problems

In motivation and in some of its numerical processes, this chapter has much in common with Chapter E02 (Curve and Surface Fitting). For this reason, we shall adopt the same terminology and refer to dependent variable and independent variable(s) instead of function and variable(s). Where there is only one independent variable, we shall denote it by x and the dependent variable by y. Thus, in the basic problem considered in this chapter, we are given a set of distinct values x 1,x 2,…,xm of x and a corresponding set of values y 1,y 2,…,ym of y, and we shall describe the problem as being one of interpolating the data points xr,yr, rather than interpolating a function. In modern usage, however, interpolation can have either of two rather different meanings, both relevant to routines in this chapter. They are
(a) | the determination of a function of x which takes the value yr at x=xr, for r=1,2,…,m (an interpolating function or interpolant),
(b) | the determination of the value (interpolated value or interpolate) of an interpolating function at any given value, say x^, of x within the range of the xr (so as to estimate the value at x^ of the function underlying the data).
The latter is the older meaning, associated particularly with the use of mathematical tables. The term ‘function underlying the data’, like the other terminology described above, is used so as to cover situations additional to those in which the data points have been computed from a known function, as with a mathematical table. In some contexts, the function may be unknown, perhaps representing the dependency of one physical variable on another, say temperature upon time.
Whether the underlying function is known or unknown, the object of interpolation will usually be to approximate it to acceptable accuracy by a function which is easy to evaluate anywhere in some range of interest. Polynomials, rational functions (ratios of two polynomials) and piecewise polynomials, such as cubic splines (see Section 2.2 in the E02 Chapter Introduction for definitions of terms in the latter case), being easy to evaluate and also capable of approximating a wide variety of functions, are the types of function mostly used in this chapter as interpolating functions. An interpolating polynomial is taken to have degree m-1 when there are m data points, and so it is unique. It is called the Lagrange interpolating polynomial. The rational function, in the special form used, is also unique. An interpolating spline, on the other hand, depends on the choice made for the knots.
One way of achieving the objective in (b) above is, of course, through (a), but there are also methods which do not involve the explicit computation of the interpolating function. Everett's formula and Aitken's successive linear interpolation (see Dahlquist and Björck (1974)) provide two such methods. Both are used in this chapter and determine a value of the Lagrange interpolating polynomial.
It is important to appreciate, however, that the Lagrange interpolating polynomial often exhibits unwanted fluctuations between the data points. These tend to occur particularly towards the ends of the data range, and to get larger with increasing number of data points. In severe cases, such as with 30 or 40 equally spaced values of x, the polynomial can take on values several orders of magnitude larger than the data values. (Closer spacing near the ends of the range tends to improve the situation, and wider spacing tends to make it worse.) Clearly, therefore, the Lagrange polynomial often gives a very poor approximation to the function underlying the data. On the other hand, it can be perfectly satisfactory when its use is restricted to providing interpolated values away from the ends of the data range from a reasonably small number of data values.
In contrast, a cubic spline which interpolates a large number of data points can often be used satisfactorily over the whole of the data range. Unwanted fluctuations can still arise but much less frequently and much less severely than with polynomials. Rational functions, when appropriate, would also be used over the whole data range. The main danger with these functions is that their polynomial denominators may take zero values within that range. Unwanted fluctuations are avoided altogether by a routine using piecewise cubic polynomials having only first derivative continuity. It is designed especially for monotonic data, but for other data still provides an interpolant which increases, or decreases, over the same intervals as the data.
The concept of interpolation can be generalized in a number of ways. Firstly, at each x, the interpolating function may be required to take on not only a given value but also given values for all its derivatives up to some specified order (which can vary with r). This is the Hermite–Birkoff interpolation problem. Secondly, we may be required to estimate the value of the underlying function at a value x^ outside the range of the data. This is the process of extrapolation. In general, it is a good deal less accurate than interpolation and is to be avoided whenever possible.
Interpolation can also be extended to the case of two or more independent variables. If the data values are given at the intersections of a regular two-dimensional mesh bicubic splines (see Section 2.3.2 in the E02 Chapter Introduction) are very suitable and usually very effective for the problem. For other cases, perhaps where the data values are quite arbitrarily scattered, polynomials and splines are not at all appropriate and special forms of interpolating function have to be employed. Many such forms have been devised and two of the most successful are in routines in this chapter. They both have continuity in first, but not higher, derivatives.

3 Recommendations on Choice and Use of Available Routines

3.1 General

Before undertaking interpolation, in other than the simplest cases, you should seriously consider the alternative of using a routine from Chapter E02 to approximate the data by a polynomial or spline containing significantly fewer coefficients than the corresponding interpolating function. This approach is much less liable to produce unwanted fluctuations and so can often provide a better approximation to the function underlying the data.
When interpolation is employed to approximate either an underlying function or its values, you will need to be satisfied that the accuracy of approximation achieved is adequate. There may be a means for doing this which is particular to the application, or the routine used may itself provide a means. In other cases, one possibility is to repeat the interpolation using one or more extra data points, if they are available, or otherwise one or more fewer, and to compare the results. Other possibilities, if it is an interpolating function which is determined, are to examine the function graphically, if that gives sufficient accuracy, or to observe the behaviour of the differences in a finite difference table, formed from evaluations of the interpolating function at equally-spaced values of x over the range of interest. The spacing should be small enough to cause the typical size of the differences to decrease as the order of difference increases.

3.2 One Independent Variable

3.2.1 Interpolated values: data without derivatives

When the underlying function is well represented by data points on both sides of the value, x^, at which an interpolated value is required, E01ABF should be tried first if the data points are equally spaced, E01AAF if they are not. Both compute a value of the Lagrange interpolating polynomial, the first using Everett's formula, the second Aitken's successive linear interpolation. The first routine requires an equal (or nearly equal) number of data points on each side of x^; such a distribution of points is preferable also for the second routine. If there are many data points, this will be achieved simply by using only an appropriate subset for each value of x^. Ten to twelve data points are the most that would be required for many problems. Both routines provide a means of assessing the accuracy of an interpolated value, with E01ABF by examination of the size of the finite differences supplied, with E01AAF by intercomparison of the set of interpolated values obtained from polynomials of increasing degree.
In other cases, or when the above routines fail to produce a satisfactory result, one of the routines discussed in the next section should be used. The spline and other piecewise polynomial routines are the most generally applicable. They are particularly appropriate when interpolated values towards the ends of the range are required. They are also likely to be preferable, for reasons of economy, when many interpolated values are required.
E01AAF above, and three of the routines discussed in the next section, can be used to compute extrapolated values. These three are E01AEF, E01BEF and E01RAF based on polynomials, piecewise polynomials and rational functions respectively. Extrapolation is not recommended in general, but can sometimes give acceptable results if it is to a point not far outside the data range, and only the few nearest data points are used in the process. E01RAF is most likely to be successful.

3.2.2 Interpolating function: data without derivatives

E01AEF computes the Lagrange interpolating polynomial by a method (based on Newton's formula with divided differences (see Fröberg (1970)) which has proved numerically very stable. Thus, it can sometimes be used to provide interpolated values in more difficult cases than can E01AAF (see the previous section). However, the likelihood of the polynomial having unwanted fluctuations, particularly near the ends of the data range when a moderate or large number of data points are used, should be remembered.
Such fluctuations of the polynomial can be avoided if you are at liberty to choose the x values at which to provide data points. In this case, a routine from Chapter E02, namely E02AFF, should be used in the manner and with the x values discussed in Section 3.2.2 in the E02 Chapter Introduction.
Usually however, when the whole of the data range is of interest, it is preferable to use a cubic spline as the interpolating function. E01BAF computes an interpolating cubic spline, using a particular choice for the set of knots which has proved generally satisfactory in practice. If you wish to choose a different set, a cubic spline routine from Chapter E02, namely E02BAF, may be used in its interpolating mode, setting NCAP7=M+4 and all elements of the argument W to unity.
The cubic spline does not always avoid unwanted fluctuations, especially when the data shows a steep slope close to a region of small slope, or when the data inadequately represents the underlying curve. In such cases, E01BEF can be very useful. It derives a piecewise cubic polynomial (with first derivative continuity) which, between any adjacent pair of data points, either increases all the way, or decreases all the way (or stays constant). It is especially suited to data which is monotonic over the whole range.
In this routine, the interpolating function is represented simply by its value and first derivative at the data points. Supporting routines compute its value and first derivative elsewhere, as well as its definite integral over an arbitrary interval. The other routines mentioned, namely E01AEF and E01BAF, provide the interpolating function either in Chebyshev series form or in B-spline form (see Sections 2.2.1 and 2.2.2 in the E02 Chapter Introduction). Routines for evaluating, differentiating and integrating these forms are discussed in Section 3.7 in the E02 Chapter Introduction. The splines and other piecewise cubics will normally provide better estimates of the derivatives of the underlying function than will interpolating polynomials, at any rate away from the central part of the data range.
E01RAF computes an interpolating rational function. It is intended mainly for those cases where you know that this form of function is appropriate. However, it is also worth trying in cases where the other routines have proved unsatisfactory. E01RBF is available to compute values of the function provided by E01RAF.

3.2.3 Data containing derivatives

E01AEF (see Section 3.2.2) can also compute the polynomial which, at each xr, has not only a specified value yr but also a specified value of each derivative up to order pr.

3.3 Two Independent Variables

3.3.1 Data on a rectangular mesh

Given the value f qr of the dependent variable f at the point xq,yr in the plane of the independent variables x and y, for each q=1,2,…,m and r=1,2,…,n (so that the points xq,yr lie at the m×n intersections of a rectangular mesh), E01DAF computes an interpolating bicubic spline, using a particular choice for each of the spline's knot-set. This choice, the same as in E01BAF, has proved generally satisfactory in practice. If, instead, you wish to specify your own knots, a routine from Chapter E02, namely E02DAF, may be used (it is more cumbersome for the purpose, however, and much slower for larger problems). Using m and n in the above sense, the argument M must be set to m×n, PX and PY must be set to m+4 and n+4 respectively and all elements of W should be set to unity. The recommended value for EPS is zero.

3.3.2 Arbitrary data

As remarked at the end of Section 2, specific methods of interpolating are required for this problem, which can often be difficult to solve satisfactorily. Two of the most successful are employed in E01SAF and E01SGF, the two routines which (with their respective evaluation routines E01SBF and E01SHF) are provided for the problem. Definitions can be found in the routine documents. Both interpolants have first derivative continuity and are ‘local’, in that their value at any point depends only on data in the immediate neighbourhood of the point. This latter feature is necessary for large sets of data to avoid prohibitive computing time. E01SHF allows evaluation of the interpolant and its first partial derivatives.
The relative merits of the two methods vary with the data and it is not possible to predict which will be the better in any particular case.
E01SAF performs a triangulation of the scattered data points and then calculates a bicubic interpolant based on this triangulation and on the function values at the scattered points (which can be evaluated by E01SBF). Where derivative continuity is not essential and where bilinear interpolated values are sufficient, E01EAF (which performs the same triangulation as E01SAF) and E01EBF (which performs barycentric interpolation using the set of function values) may be used.

3.4 Three Independent Variables

3.4.1 Arbitrary data

The routine E01TGF and its evaluation routine E01THF are provided for interpolation of three-dimensional scattered data. As in the case of two independent variables, the method is local, and produces an interpolant with first derivative continuity. E01THF allows evaluation of the interpolant and its first partial derivatives.

3.5 Four and Five Independent Variables

3.5.1 Arbitrary data

The routine E01TKF and its evaluation routine E01TLF allow interpolation of four-dimensional scattered data, while the routine E01TMF and its evaluation routine E01TNF allow interpolation of five-dimensional scattered data. E01TKF and E01TMF are higher dimensional analogues to the routines E01SGF and E01TGF, while E01TLF and E01TNF are analogous to E01SHF and E01THF.

3.6 Multidimensional interpolation

3.6.1 Arbitrary data

Interpolation of scattered data in d-dimensions, where d>2, is provided by routine E01ZMF. This extends the local method of E01TGF and E01TKF to higher dimensions. Evaluation of the interpolant, which has continuous first derivatives, is carried out by routine E01ZNF.

4 Decision Tree

Tree 1

More than one independent variable? |  |  | Data on rectangular mesh? |  |  | E01DAF
 |  | yes |  |  | yes
 | no |  |  | no |
 |  |  | Two independent variables? |  |  | E01EAF, E01SAF or E01SGF
 |  |  |  |  | yes
 |  |  |  | no |
 |  |  | Three independent variables? |  |  | E01TGF
 |  |  |  |  | yes
 |  |  |  | no |
 |  |  | Four independent variables? |  |  | E01TKF
 |  |  |  |  | yes
 |  |  |  | no |
 |  |  | Five independent variables? |  |  | E01TMF
 |  |  |  |  | yes
 |  |  |  | no |
 |  |  | More than five independent variables? |  |  | E01ZMF
 |  |  |  |  | yes
Does data contain derivatives? |  |  | E01AEF
 |  | yes
 | no |
Interpolating function required? |  |  | Do you wish to impose monotonicity? |  |  | E01BEF
 |  | yes |  |  | yes
 | no |  |  | no |
 |  |  | Polynomial function required? |  |  | E01AEF
 |  |  |  |  | yes
 |  |  |  | no |
 |  |  | Rational function required? |  |  | E01RAF
 |  |  |  |  | yes
 |  |  |  | no |
 |  |  | E01BAF unless you have received an unacceptable result in which case E01BEF
Well away from end of data range? |  |  | Data points equally spaced? |  |  | E01ABF
 |  | yes |  |  | yes
 | no |  |  | no |
 |  |  | E01AAF
E01BAF unless you have received an unacceptable result in which case E01BEF

5 Functionality Index

Derivative,
of interpolant,
from E01BEF E01BGF
from E01SGF E01SHF
from E01TGF E01THF
from E01TKF E01TLF
from E01TMF E01TNF
from E01ZMF E01ZNF
Evaluation,
of interpolant,
from E01BEF E01BFF
from E01RAF E01RBF
from E01SAF E01SBF
from E01SGF E01SHF
from E01TGF E01THF
from E01TKF E01TLF
from E01TMF E01TNF
from E01ZMF E01ZNF
from triangulation from E01EAF E01EBF
Extrapolation,
one variable,
piecewise cubic E01BEF
polynomial,
data with or without derivatives E01AEF
general data E01AAF
rational function E01RAF
Integration (definite) of interpolant from E01BEF E01BHF
Interpolated values,
d variables,
from interpolant from E01ZMF E01ZNF
five variables,
from interpolant from E01TMF E01TNF
four variables,
from interpolant from E01TKF E01TLF
one variable,
from interpolant from E01BEF E01BFF
from interpolant from E01BEF (including derivative) E01BGF
from polynomial,
equally spaced data E01ABF
general data E01AAF
from rational function E01RBF
three variables,
from interpolant from E01TGF E01THF
two variables,
barycentric, from triangulation from E01EAF E01EBF
from interpolant from E01SAF E01SBF
from interpolant from E01SGF E01SHF
Interpolating function,
d variables,
modified Shepard method E01ZMF
five variables,
modified Shepard method E01TMF
four variables,
modified Shepard method E01TKF
one variable,
cubic spline E01BAF
other piecewise polynomial E01BEF
polynomial,
data with or without derivatives E01AEF
rational function E01RAF
three variables,
modified Shepard method E01TGF
two variables,
bicubic spline E01DAF
modified Shepard method E01SGF
other piecewise polynomial E01SAF
triangulation E01EAF

6 Auxiliary Routines Associated with Library Routine Arguments

None.

7 Routines Withdrawn or Scheduled for Withdrawal

The following lists all those routines that have been withdrawn since Mark 19 of the Library or are scheduled for withdrawal at one of the next two marks.
Withdrawn Routine | Mark of Withdrawal | Replacement Routine(s)
E01SEF | 20 | E01SGF
E01SFF | 20 | E01SHF

8 References

Dahlquist G and Björck Å (1974) Numerical Methods Prentice–Hall
Fröberg C E (1970) Introduction to Numerical Analysis Addison–Wesley
E01 Chapter Contents
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


E01RAF : NAG Library, Mark 26

E01 Chapter Contents
E01 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

E01RAF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

E01RAF produces, from a set of function values and corresponding abscissae, the coefficients of an interpolating rational function expressed in continued fraction form.

2 Specification

SUBROUTINE E01RAF ( N, X, F, M, A, U, IW, IFAIL)
INTEGER | N, M, IW(N), IFAIL
REAL (KIND=nag_wp) | X(N), F(N), A(N), U(N)

3 Description

E01RAF produces the parameters of a rational function R x which assumes prescribed values fi at prescribed values xi of the independent variable x, for i=1,2,…,n. More specifically, E01RAF determines the parameters aj, for j=1,2,…,m and uj, for j=1,2,…,m-1, in the continued fraction
R x=a 1+Rm x (1)
where
Ri x=a m-i+ 2 x-u m-i+ 1 1+R i- 1 x ,   for ​ i=m,m- 1,…,2,
and
R 1 x=0,
such that R xi=fi, for i=1,2,…,n. The value of m in (1) is determined by the routine; normally m=n. The values of uj form a reordered subset of the values of xi and their ordering is designed to ensure that a representation of the form (1) is determined whenever one exists.
The subsequent evaluation of (1) for given values of x can be carried out using E01RBF.
The computational method employed in E01RAF is the modification of the Thacher–Tukey algorithm described in Graves–Morris and Hopkins (1981).

4 References

Graves–Morris P R and Hopkins T R (1981) Reliable rational interpolation Numer. Math. 36 111–128

5 Arguments

1:   N – INTEGERInput
On entry: n, the number of data points.
Constraint: N>0.
2:   X N – REAL (KIND=nag_wp) arrayInput
On entry: X i must be set to the value of the ith data abscissa, xi, for i=1,2,…,n.
Constraint: the X i must be distinct.
3:   F N – REAL (KIND=nag_wp) arrayInput
On entry: F i must be set to the value of the data ordinate, fi, corresponding to xi, for i=1,2,…,n.
4:   M – INTEGEROutput
On exit: m, the number of terms in the continued fraction representation of R x.
5:   A N – REAL (KIND=nag_wp) arrayOutput
On exit: A j contains the value of the parameter aj in R x, for j=1,2,…,m. The remaining elements of A, if any, are set to zero.
6:   U N – REAL (KIND=nag_wp) arrayOutput
On exit: U j contains the value of the parameter uj in R x, for j=1,2,…,m-1. The uj are a permuted subset of the elements of X. The remaining n-m+1 locations contain a permutation of the remaining xi, which can be ignored.
7:   IW N – INTEGER arrayWorkspace
8:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, N≤0.
IFAIL=2
At least one pair of the values X i are equal (or so nearly so that a subsequent division will inevitably cause overflow).
IFAIL=3
A continued fraction of the required form does not exist.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

Usually, it is not the accuracy of the coefficients produced by this routine which is of prime interest, but rather the accuracy of the value of R x that is produced by the associated routine E01RBF when subsequently it evaluates the continued fraction (1) for a given value of x. This final accuracy will depend mainly on the nature of the interpolation being performed. If interpolation of a ‘well-behaved smooth’ function is attempted (and provided the data adequately represents the function), high accuracy will normally ensue, but, if the function is not so ‘smooth’ or extrapolation is being attempted, high accuracy is much less likely. Indeed, in extreme cases, results can be highly inaccurate.
There is no built-in test of accuracy but several courses are open to you to prevent the production or the acceptance of inaccurate results.
1. | If the origin of a variable is well outside the range of its data values, the origin should be shifted to correct this; and, if the new data values are still excessively large or small, scaling to make the largest value of the order of unity is recommended. Thus, normalization to the range -1.0 to +1.0 is ideal. This applies particularly to the independent variable; for the dependent variable, the removal of leading figures which are common to all the data values will usually suffice.
2. | To check the effect of rounding errors engendered in the routines themselves, E01RAF should be re-entered with x 1 interchanged with xi and f 1 with fi, i≠1. This will produce a completely different vector a and a reordered vector u, but any change in the value of R x subsequently produced by E01RBF will be due solely to rounding error.
3. | Even if the data consist of calculated values of a formal mathematical function, it is only in exceptional circumstances that bounds for the interpolation error (the difference between the true value of the function underlying the data and the value which would be produced by the two routines if exact arithmetic were used) can be derived that are sufficiently precise to be of practical use. Consequently, you are recommended to rely on comparison checks: if extra data points are available, the calculation may be repeated with one or more data pairs added or exchanged, or alternatively, one of the original data pairs may be omitted. If the algorithms are being used for extrapolation, the calculations should be performed repeatedly with the 2,3,… nearest points until, hopefully, successive values of R x for the given x agree to the required accuracy.

8 Parallelism and Performance

E01RAF is not threaded in any implementation.

9 Further Comments

The time taken by E01RAF is approximately proportional to n 2.
The continued fraction (1) when expanded produces a rational function in x, the degree of whose numerator is either equal to or exceeds by unity that of the denominator. Only if this rather special form of interpolatory rational function is needed explicitly, would this routine be used without subsequent entry (or entries) to E01RBF.

10 Example

This example reads in the abscissae and ordinates of 5 data points and prints the arguments aj and uj of a rational function which interpolates them.

10.1 Program Text

Program Text (e01rafe.f90)

10.2 Program Data

Program Data (e01rafe.d)

10.3 Program Results

Program Results (e01rafe.r)

E01 Chapter Contents
E01 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


E01RBF : NAG Library, Mark 26

E01 Chapter Contents
E01 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

E01RBF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

E01RBF evaluates continued fractions of the form produced by E01RAF.

2 Specification

SUBROUTINE E01RBF ( M, A, U, X, F, IFAIL)
INTEGER | M, IFAIL
REAL (KIND=nag_wp) | A(M), U(M), X, F

3 Description

E01RBF evaluates the continued fraction
R x=a 1+Rm x
where
Ri x=a m-i+ 2 x-u m-i+ 1 1+R i- 1 x ,   for ​ i=m,m- 1,…,2.
and
R 1 x=0
for a prescribed value of x. E01RBF is intended to be used to evaluate the continued fraction representation (of an interpolatory rational function) produced by E01RAF.

4 References

Graves–Morris P R and Hopkins T R (1981) Reliable rational interpolation Numer. Math. 36 111–128

5 Arguments

1:   M – INTEGERInput
On entry: m, the number of terms in the continued fraction.
Constraint: M≥1.
2:   A M – REAL (KIND=nag_wp) arrayInput
On entry: A j must be set to the value of the parameter aj in the continued fraction, for j=1,2,…,m.
3:   U M – REAL (KIND=nag_wp) arrayInput
On entry: U j must be set to the value of the parameter uj in the continued fraction, for j=1,2,…,m-1. (The element U m is not used).
4:   X – REAL (KIND=nag_wp)Input
On entry: the value of x at which the continued fraction is to be evaluated.
5:   F – REAL (KIND=nag_wp)Output
On exit: the value of the continued fraction corresponding to the value of x.
6:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
The value of X corresponds to a pole of R x or is so close that an overflow is likely to ensue.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

See Section 7 in E01RAF.

8 Parallelism and Performance

E01RBF is not threaded in any implementation.

9 Further Comments

The time taken by E01RBF is approximately proportional to m.

10 Example

This example reads in the arguments aj and uj of a continued fraction (as determined by the example for E01RAF) and evaluates the continued fraction at a point x.

10.1 Program Text

Program Text (e01rbfe.f90)

10.2 Program Data

Program Data (e01rbfe.d)

10.3 Program Results

Program Results (e01rbfe.r)

E01 Chapter Contents
E01 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


E01SAF : NAG Library, Mark 26

E01 Chapter Contents
E01 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

E01SAF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

E01SAF generates a two-dimensional surface interpolating a set of scattered data points, using the method of Renka and Cline.

2 Specification

SUBROUTINE E01SAF ( M, X, Y, F, TRIANG, GRADS, IFAIL)
INTEGER | M, TRIANG(7*M), IFAIL
REAL (KIND=nag_wp) | X(M), Y(M), F(M), GRADS(2,M)

3 Description

E01SAF constructs an interpolating surface F x,y through a set of m scattered data points xr,yr,fr, for r=1,2,…,m, using a method due to Renka and Cline. In the x,y plane, the data points must be distinct. The constructed surface is continuous and has continuous first derivatives.
The method involves firstly creating a triangulation with all the x,y data points as nodes, the triangulation being as nearly equiangular as possible (see Cline and Renka (1984)). Then gradients in the x- and y-directions are estimated at node r, for r=1,2,…,m, as the partial derivatives of a quadratic function of x and y which interpolates the data value fr, and which fits the data values at nearby nodes (those within a certain distance chosen by the algorithm) in a weighted least squares sense. The weights are chosen such that closer nodes have more influence than more distant nodes on derivative estimates at node r. The computed partial derivatives, with the fr values, at the three nodes of each triangle define a piecewise polynomial surface of a certain form which is the interpolant on that triangle. See Renka and Cline (1984) for more detailed information on the algorithm, a development of that by Lawson (1977). The code is derived from Renka (1984).
The interpolant F x,y can subsequently be evaluated at any point x,y inside or outside the domain of the data by a call to E01SBF. Points outside the domain are evaluated by extrapolation.

4 References

Cline A K and Renka R L (1984) A storage-efficient method for construction of a Thiessen triangulation Rocky Mountain J. Math. 14 119–139
Lawson C L (1977) Software for C 1 surface interpolation Mathematical Software III (ed J R Rice) 161–194 Academic Press
Renka R L (1984) Algorithm 624: triangulation and interpolation of arbitrarily distributed points in the plane ACM Trans. Math. Software 10 440–442
Renka R L and Cline A K (1984) A triangle-based C 1 interpolation method Rocky Mountain J. Math. 14 223–237

5 Arguments

1:   M – INTEGERInput
On entry: m, the number of data points.
Constraint: M≥3.
2:   X M – REAL (KIND=nag_wp) arrayInput
3:   Y M – REAL (KIND=nag_wp) arrayInput
4:   F M – REAL (KIND=nag_wp) arrayInput
On entry: the coordinates of the rth data point, for r=1,2,…,m. The data points are accepted in any order, but see Section 9.
Constraint: the x,y nodes must not all be collinear, and each node must be unique.
5:   TRIANG 7×M – INTEGER arrayOutput
On exit: a data structure defining the computed triangulation, in a form suitable for passing to E01SBF.
6:   GRADS 2 M – REAL (KIND=nag_wp) arrayOutput
On exit: the estimated partial derivatives at the nodes, in a form suitable for passing to E01SBF. The derivatives at node r with respect to x and y are contained in GRADS 1 r and GRADS 2 r respectively, for r=1,2,…,m.
7:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, M<3.
IFAIL=2
On entry, all the (X,Y) pairs are collinear.
IFAIL=3
On entry, X i,Y i=X j,Y j for some i≠j.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

On successful exit, the computational errors should be negligible in most situations but you should always check the computed surface for acceptability, by drawing contours for instance. The surface always interpolates the input data exactly.

8 Parallelism and Performance

E01SAF is not threaded in any implementation.

9 Further Comments

The time taken for a call of E01SAF is approximately proportional to the number of data points, m. The routine is more efficient if, before entry, the values in X, Y and F are arranged so that the X array is in ascending order.

10 Example

This example reads in a set of 30 data points and calls E01SAF to construct an interpolating surface. It then calls E01SBF to evaluate the interpolant at a sample of points on a rectangular grid.
Note that this example is not typical of a realistic problem: the number of data points would normally be larger, and the interpolant would need to be evaluated on a finer grid to obtain an accurate plot, say.

10.1 Program Text

Program Text (e01safe.f90)

10.2 Program Data

Program Data (e01safe.d)

10.3 Program Results

Program Results (e01safe.r)

E01 Chapter Contents
E01 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


E01SBF : NAG Library, Mark 26

E01 Chapter Contents
E01 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

E01SBF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
10 Example

1 Purpose

E01SBF evaluates at a given point the two-dimensional interpolant function computed by E01SAF.

2 Specification

SUBROUTINE E01SBF ( M, X, Y, F, TRIANG, GRADS, PX, PY, PF, IFAIL)
INTEGER | M, TRIANG(7*M), IFAIL
REAL (KIND=nag_wp) | X(M), Y(M), F(M), GRADS(2,M), PX, PY, PF

3 Description

E01SBF takes as input the arguments defining the interpolant F x,y of a set of scattered data points xr,yr,fr, for r=1,2,…,m, as computed by E01SAF, and evaluates the interpolant at the point px,py.
If px,py is equal to xr,yr for some value of r, the returned value will be equal to fr.
If px,py is not equal to xr,yr for any r, the derivatives in GRADS will be used to compute the interpolant. A triangle is sought which contains the point px,py, and the vertices of the triangle along with the partial derivatives and fr values at the vertices are used to compute the value F px,py. If the point px,py lies outside the triangulation defined by the input arguments, the returned value is obtained by extrapolation. In this case, the interpolating function F is extended linearly beyond the triangulation boundary. The method is described in more detail in Renka and Cline (1984) and the code is derived from Renka (1984).
E01SBF must only be called after a call to E01SAF.

4 References

Renka R L (1984) Algorithm 624: triangulation and interpolation of arbitrarily distributed points in the plane ACM Trans. Math. Software 10 440–442
Renka R L and Cline A K (1984) A triangle-based C 1 interpolation method Rocky Mountain J. Math. 14 223–237

5 Arguments

1:   M – INTEGERInput
2:   X M – REAL (KIND=nag_wp) arrayInput
3:   Y M – REAL (KIND=nag_wp) arrayInput
4:   F M – REAL (KIND=nag_wp) arrayInput
5:   TRIANG 7×M – INTEGER arrayInput
6:   GRADS 2 M – REAL (KIND=nag_wp) arrayInput
On entry: M, X, Y, F, TRIANG and GRADS must be unchanged from the previous call of E01SAF.
7:   PX – REAL (KIND=nag_wp)Input
8:   PY – REAL (KIND=nag_wp)Input
On entry: the point px,py at which the interpolant is to be evaluated.
9:   PF – REAL (KIND=nag_wp)Output
On exit: the value of the interpolant evaluated at the point px,py.
10:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, M<3.
IFAIL=2
On entry, the triangulation information held in the array TRIANG does not specify a valid triangulation of the data points. TRIANG may have been corrupted since the call to E01SAF.
IFAIL=3
The evaluation point (PX,PY) lies outside the nodal triangulation, and the value returned in PF is computed by extrapolation.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

Computational errors should be negligible in most practical situations.

8 Parallelism and Performance

E01SBF is not thread safe and should not be called from a multithreaded user program. Please see Section 3.12.1 in How to Use the NAG Library and its Documentation for more information on thread safety.
E01SBF is not threaded in any implementation.

9 Further Comments

The time taken for a call of E01SBF is approximately proportional to the number of data points, m.
The results returned by this routine are particularly suitable for applications such as graph plotting, producing a smooth surface from a number of scattered points.

10 Example

See Section 10 in E01SAF.
E01 Chapter Contents
E01 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


E01SGF : NAG Library, Mark 26

E01 Chapter Contents
E01 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

E01SGF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
▸▿ 9 Further Comments
9.1 Timing
9.2 Choice of N_w and N_q
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

E01SGF generates a two-dimensional interpolant to a set of scattered data points, using a modified Shepard method.

2 Specification

SUBROUTINE E01SGF ( M, X, Y, F, NW, NQ, IQ, LIQ, RQ, LRQ, IFAIL)
INTEGER | M, NW, NQ, IQ(LIQ), LIQ, LRQ, IFAIL
REAL (KIND=nag_wp) | X(M), Y(M), F(M), RQ(LRQ)

3 Description

E01SGF constructs a smooth function Q x,y which interpolates a set of m scattered data points xr,yr,fr, for r=1,2,…,m, using a modification of Shepard's method. The surface is continuous and has continuous first partial derivatives.
The basic Shepard (1968) method interpolates the input data with the weighted mean
Q x,y=∑r=1 m wr x,y qr ∑r=1 m wr x,y ,
where qr = fr , wr x,y = 1 dr 2 and dr 2 = x-xr 2 + y-yr 2 .
The basic method is global in that the interpolated value at any point depends on all the data, but this routine uses a modification (see Franke and Nielson (1980) and Renka (1988a)), whereby the method becomes local by adjusting each wr x,y to be zero outside a circle with centre xr,yr and some radius Rw. Also, to improve the performance of the basic method, each qr above is replaced by a function qr x,y, which is a quadratic fitted by weighted least squares to data local to xr,yr and forced to interpolate xr,yr,fr. In this context, a point x,y is defined to be local to another point if it lies within some distance Rq of it. Computation of these quadratics constitutes the main work done by this routine.
The efficiency of the routine is further enhanced by using a cell method for nearest neighbour searching due to Bentley and Friedman (1979).
The radii Rw and Rq are chosen to be just large enough to include Nw and Nq data points, respectively, for user-supplied constants Nw and Nq. Default values of these arguments are provided by the routine, and advice on alternatives is given in Section 9.2.
This routine is derived from the routine QSHEP2 described by Renka (1988b).
Values of the interpolant Q x,y generated by this routine, and its first partial derivatives, can subsequently be evaluated for points in the domain of the data by a call to E01SHF.

4 References

Bentley J L and Friedman J H (1979) Data structures for range searching ACM Comput. Surv. 11 397–409
Franke R and Nielson G (1980) Smooth interpolation of large sets of scattered data Internat. J. Num. Methods Engrg. 15 1691–1704
Renka R J (1988a) Multivariate interpolation of large sets of scattered data ACM Trans. Math. Software 14 139–148
Renka R J (1988b) Algorithm 660: QSHEP2D: Quadratic Shepard method for bivariate interpolation of scattered data ACM Trans. Math. Software 14 149–150
Shepard D (1968) A two-dimensional interpolation function for irregularly spaced data Proc. 23rd Nat. Conf. ACM 517–523 Brandon/Systems Press Inc., Princeton

5 Arguments

1:   M – INTEGERInput
On entry: m, the number of data points.
Constraint: M≥6.
2:   X M – REAL (KIND=nag_wp) arrayInput
3:   Y M – REAL (KIND=nag_wp) arrayInput
On entry: the Cartesian coordinates of the data points xr,yr, for r=1,2,…,m.
Constraint: these coordinates must be distinct, and must not all be collinear.
4:   F M – REAL (KIND=nag_wp) arrayInput
On entry: F r must be set to the data value fr, for r=1,2,…,m.
5:   NW – INTEGERInput
On entry: the number Nw of data points that determines each radius of influence Rw, appearing in the definition of each of the weights wr, for r=1,2,…,m (see Section 3). Note that Rw is different for each weight. If NW≤0 the default value NW=min 19,M-1 is used instead.
Constraint: NW≤min 40,M-1.
6:   NQ – INTEGERInput
On entry: the number Nq of data points to be used in the least squares fit for coefficients defining the nodal functions qr x,y (see Section 3). If NQ≤0 the default value NQ=min 13,M-1 is used instead.
Constraint: NQ≤0 or 5≤NQ≤min 40,M-1.
7:   IQ LIQ – INTEGER arrayOutput
On exit: integer data defining the interpolant Q x,y.
8:   LIQ – INTEGERInput
On entry: the dimension of the array IQ as declared in the (sub)program from which E01SGF is called.
Constraint: LIQ≥2×M+1.
9:   RQ LRQ – REAL (KIND=nag_wp) arrayOutput
On exit: real data defining the interpolant Q x,y.
10:   LRQ – INTEGERInput
On entry: the dimension of the array RQ as declared in the (sub)program from which E01SGF is called.
Constraint: LRQ≥6×M+5.
11:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, | M<6,
or | 0<NQ<5,
or | NQ > min 40,M-1 ,
or | NW > min 40,M-1 ,
or | LIQ<2×M+1,
or | LRQ<6×M+5.
IFAIL=2
On entry, X i,Y i=X j,Y j for some i≠j.
IFAIL=3
On entry, all the data points are collinear. No unique solution exists.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

On successful exit, the function generated interpolates the input data exactly and has quadratic accuracy.

8 Parallelism and Performance

E01SGF is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
E01SGF makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

9.1 Timing

The time taken for a call to E01SGF will depend in general on the distribution of the data points. If X and Y are uniformly randomly distributed, then the time taken should be O M. At worst O M 2 time will be required.

9.2 Choice of Nw and Nq

Default values of the arguments Nw and Nq may be selected by calling E01SGF with NW≤0 and NQ≤0. These default values may well be satisfactory for many applications.
If non-default values are required they must be supplied to E01SGF through positive values of NW and NQ. Increasing these arguments makes the method less local. This may increase the accuracy of the resulting interpolant at the expense of increased computational cost. The default values NW = min 19,M-1 and NQ = min 13,M-1 have been chosen on the basis of experimental results reported in Renka (1988a). In these experiments the error norm was found to vary smoothly with Nw and Nq, generally increasing monotonically and slowly with distance from the optimal pair. The method is not therefore thought to be particularly sensitive to the argument values. For further advice on the choice of these arguments see Renka (1988a).

10 Example

This program reads in a set of 30 data points and calls E01SGF to construct an interpolating function Q x,y. It then calls E01SHF to evaluate the interpolant at a set of points.
Note that this example is not typical of a realistic problem: the number of data points would normally be larger.

10.1 Program Text

Program Text (e01sgfe.f90)

10.2 Program Data

Program Data (e01sgfe.d)

10.3 Program Results

Program Results (e01sgfe.r)

E01 Chapter Contents
E01 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


E01SHF : NAG Library, Mark 26

E01 Chapter Contents
E01 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

E01SHF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
10 Example

1 Purpose

E01SHF evaluates the two-dimensional interpolating function generated by E01SGF and its first partial derivatives.

2 Specification

SUBROUTINE E01SHF ( M, X, Y, F, IQ, LIQ, RQ, LRQ, N, U, V, Q, QX, QY, IFAIL)
INTEGER | M, IQ(LIQ), LIQ, LRQ, N, IFAIL
REAL (KIND=nag_wp) | X(M), Y(M), F(M), RQ(LRQ), U(N), V(N), Q(N), QX(N), QY(N)

3 Description

E01SHF takes as input the interpolant Q x,y of a set of scattered data points xr,yr,fr, for r=1,2,…,m, as computed by E01SGF, and evaluates the interpolant and its first partial derivatives at the set of points ui,vi, for i=1,2,…,n.
E01SHF must only be called after a call to E01SGF.
This routine is derived from the routine QS2GRD described by Renka (1988).

4 References

Renka R J (1988) Algorithm 660: QSHEP2D: Quadratic Shepard method for bivariate interpolation of scattered data ACM Trans. Math. Software 14 149–150

5 Arguments

1:   M – INTEGERInput
2:   X M – REAL (KIND=nag_wp) arrayInput
3:   Y M – REAL (KIND=nag_wp) arrayInput
4:   F M – REAL (KIND=nag_wp) arrayInput
On entry: M, X, Y and F must be the same values as were supplied in the preceding call to E01SGF.
5:   IQ LIQ – INTEGER arrayInput
On entry: must be unchanged from the value returned from a previous call to E01SGF.
6:   LIQ – INTEGERInput
On entry: the dimension of the array IQ as declared in the (sub)program from which E01SHF is called.
Constraint: LIQ≥2×M+1.
7:   RQ LRQ – REAL (KIND=nag_wp) arrayInput
On entry: must be unchanged from the value returned from a previous call to E01SGF.
8:   LRQ – INTEGERInput
On entry: the dimension of the array RQ as declared in the (sub)program from which E01SHF is called.
Constraint: LRQ≥6×M+5.
9:   N – INTEGERInput
On entry: n, the number of evaluation points.
Constraint: N≥1.
10:   U N – REAL (KIND=nag_wp) arrayInput
11:   V N – REAL (KIND=nag_wp) arrayInput
On entry: the evaluation points ui,vi, for i=1,2,…,n.
12:   Q N – REAL (KIND=nag_wp) arrayOutput
On exit: the values of the interpolant at ui,vi, for i=1,2,…,n. If any of these evaluation points lie outside the region of definition of the interpolant the corresponding entries in Q are set to the largest machine representable number (see X02ALF), and E01SHF returns with IFAIL=3.
13:   QX N – REAL (KIND=nag_wp) arrayOutput
14:   QY N – REAL (KIND=nag_wp) arrayOutput
On exit: the values of the partial derivatives of the interpolant Q x,y at ui,vi, for i=1,2,…,n. If any of these evaluation points lie outside the region of definition of the interpolant, the corresponding entries in QX and QY are set to the largest machine representable number (see X02ALF), and E01SHF returns with IFAIL=3.
15:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, | M<6,
or | LIQ<2×M+1,
or | LRQ<6×M+5,
or | N<1.
IFAIL=2
Values supplied in IQ or RQ appear to be invalid. Check that these arrays have not been corrupted between the calls to E01SGF and E01SHF.
IFAIL=3
At least one evaluation point lies outside the region of definition of the interpolant. At all such points the corresponding values in Q, QX and QY have been set to the largest machine representable number (see X02ALF).
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

Computational errors should be negligible in most practical situations.

8 Parallelism and Performance

E01SHF is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The time taken for a call to E01SHF will depend in general on the distribution of the data points. If X and Y are approximately uniformly distributed, then the time taken should be only O n. At worst O mn time will be required.

10 Example

See Section 10 in E01SGF.
E01 Chapter Contents
E01 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


E01TGF : NAG Library, Mark 26

E01 Chapter Contents
E01 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

E01TGF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
▸▿ 9 Further Comments
9.1 Timing
9.2 Choice of N_w and N_q
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

E01TGF generates a three-dimensional interpolant to a set of scattered data points, using a modified Shepard method.

2 Specification

SUBROUTINE E01TGF ( M, X, Y, Z, F, NW, NQ, IQ, LIQ, RQ, LRQ, IFAIL)
INTEGER | M, NW, NQ, IQ(LIQ), LIQ, LRQ, IFAIL
REAL (KIND=nag_wp) | X(M), Y(M), Z(M), F(M), RQ(LRQ)

3 Description

E01TGF constructs a smooth function Q x,y,z which interpolates a set of m scattered data points xr,yr,zr,fr, for r=1,2,…,m, using a modification of Shepard's method. The surface is continuous and has continuous first partial derivatives.
The basic Shepard method, which is a generalization of the two-dimensional method described in Shepard (1968), interpolates the input data with the weighted mean
Q x,y,z=∑r=1 m wr x,y,z qr ∑r=1 m wr x,y,z ,
where
qr=fr ​ and ​ wr x,y,z= 1 dr 2 ​ and ​ dr 2= x-xr 2+ y-yr 2+ z-zr 2.
The basic method is global in that the interpolated value at any point depends on all the data, but this routine uses a modification (see Franke and Nielson (1980) and Renka (1988a)), whereby the method becomes local by adjusting each wr x,y,z to be zero outside a sphere with centre xr,yr,zr and some radius Rw. Also, to improve the performance of the basic method, each qr above is replaced by a function qr x,y,z, which is a quadratic fitted by weighted least squares to data local to xr,yr,zr and forced to interpolate xr,yr,zr,fr. In this context, a point x,y,z is defined to be local to another point if it lies within some distance Rq of it. Computation of these quadratics constitutes the main work done by this routine.
The efficiency of the routine is further enhanced by using a cell method for nearest neighbour searching due to Bentley and Friedman (1979).
The radii Rw and Rq are chosen to be just large enough to include Nw and Nq data points, respectively, for user-supplied constants Nw and Nq. Default values of these arguments are provided by the routine, and advice on alternatives is given in Section 9.2.
This routine is derived from the routine QSHEP3 described by Renka (1988b).
Values of the interpolant Q x,y,z generated by this routine, and its first partial derivatives, can subsequently be evaluated for points in the domain of the data by a call to E01THF.

4 References

Bentley J L and Friedman J H (1979) Data structures for range searching ACM Comput. Surv. 11 397–409
Franke R and Nielson G (1980) Smooth interpolation of large sets of scattered data Internat. J. Num. Methods Engrg. 15 1691–1704
Renka R J (1988a) Multivariate interpolation of large sets of scattered data ACM Trans. Math. Software 14 139–148
Renka R J (1988b) Algorithm 661: QSHEP3D: Quadratic Shepard method for trivariate interpolation of scattered data ACM Trans. Math. Software 14 151–152
Shepard D (1968) A two-dimensional interpolation function for irregularly spaced data Proc. 23rd Nat. Conf. ACM 517–523 Brandon/Systems Press Inc., Princeton

5 Arguments

1:   M – INTEGERInput
On entry: m, the number of data points.
Constraint: M≥10.
2:   X M – REAL (KIND=nag_wp) arrayInput
3:   Y M – REAL (KIND=nag_wp) arrayInput
4:   Z M – REAL (KIND=nag_wp) arrayInput
On entry: X r, Y r, Z r must be set to the Cartesian coordinates of the data point xr,yr,zr, for r=1,2,…,m.
Constraint: these coordinates must be distinct, and must not all be coplanar.
5:   F M – REAL (KIND=nag_wp) arrayInput
On entry: F r must be set to the data value fr, for r=1,2,…,m.
6:   NW – INTEGERInput
On entry: the number Nw of data points that determines each radius of influence Rw, appearing in the definition of each of the weights wr, for r=1,2,…,m (see Section 3). Note that Rw is different for each weight. If NW≤0 the default value NW=min 32,M-1 is used instead.
Constraint: NW≤min 40,M-1.
7:   NQ – INTEGERInput
On entry: the number Nq of data points to be used in the least squares fit for coefficients defining the nodal functions qr x,y,z (see Section 3). If NQ≤0 the default value NQ=min 17,M-1 is used instead.
Constraint: NQ≤0 or 9≤NQ≤min 40,M-1.
8:   IQ LIQ – INTEGER arrayOutput
On exit: integer data defining the interpolant Q x,y,z.
9:   LIQ – INTEGERInput
On entry: the dimension of the array IQ as declared in the (sub)program from which E01TGF is called.
Constraint: LIQ≥2×M+1.
10:   RQ LRQ – REAL (KIND=nag_wp) arrayOutput
On exit: real data defining the interpolant Q x,y,z.
11:   LRQ – INTEGERInput
On entry: the dimension of the array RQ as declared in the (sub)program from which E01TGF is called.
Constraint: LRQ≥10×M+7.
12:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, | M<10,
or | 0<NQ<9,
or | NQ > min 40,M-1 ,
or | NW > min 40,M-1 ,
or | LIQ<2×M+1,
or | LRQ<10×M+7.
IFAIL=2
On entry, X i,Y i,Z i=X j,Y j,Z j for some i≠j.
IFAIL=3
On entry, all the data points are coplanar. No unique solution exists.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

On successful exit, the function generated interpolates the input data exactly and has quadratic accuracy.

8 Parallelism and Performance

E01TGF is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
E01TGF makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

9.1 Timing

The time taken for a call to E01TGF will depend in general on the distribution of the data points. If X, Y and Z are uniformly randomly distributed, then the time taken should be O(M). At worst O M 2 time will be required.

9.2 Choice of Nw and Nq

Default values of the arguments Nw and Nq may be selected by calling E01TGF with NW≤0 and NQ≤0. These default values may well be satisfactory for many applications.
If non-default values are required they must be supplied to E01TGF through positive values of NW and NQ. Increasing these arguments makes the method less local. This may increase the accuracy of the resulting interpolant at the expense of increased computational cost. The default values NW = min 32,M-1 and NQ = min 17,M-1 have been chosen on the basis of experimental results reported in Renka (1988a). In these experiments the error norm was found to vary smoothly with Nw and Nq, generally increasing monotonically and slowly with distance from the optimal pair. The method is not therefore thought to be particularly sensitive to the argument values. For further advice on the choice of these arguments see Renka (1988a).

10 Example

This program reads in a set of 30 data points and calls E01TGF to construct an interpolating function Q x,y,z. It then calls E01THF to evaluate the interpolant at a set of points.
Note that this example is not typical of a realistic problem: the number of data points would normally be larger.

10.1 Program Text

Program Text (e01tgfe.f90)

10.2 Program Data

Program Data (e01tgfe.d)

10.3 Program Results

Program Results (e01tgfe.r)

E01 Chapter Contents
E01 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


E01THF : NAG Library, Mark 26

E01 Chapter Contents
E01 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

E01THF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
10 Example

1 Purpose

E01THF evaluates the three-dimensional interpolating function generated by E01TGF and its first partial derivatives.

2 Specification

SUBROUTINE E01THF ( M, X, Y, Z, F, IQ, LIQ, RQ, LRQ, N, U, V, W, Q, QX, QY, QZ, IFAIL)
INTEGER | M, IQ(LIQ), LIQ, LRQ, N, IFAIL
REAL (KIND=nag_wp) | X(M), Y(M), Z(M), F(M), RQ(LRQ), U(N), V(N), W(N), Q(N), QX(N), QY(N), QZ(N)

3 Description

E01THF takes as input the interpolant Q x,y,z of a set of scattered data points xr,yr,zr,fr, for r=1,2,…,m, as computed by E01TGF, and evaluates the interpolant and its first partial derivatives at the set of points ui,vi,wi, for i=1,2,…,n.
E01THF must only be called after a call to E01TGF.
This routine is derived from the routine QS3GRD described by Renka (1988).

4 References

Renka R J (1988) Algorithm 661: QSHEP3D: Quadratic Shepard method for trivariate interpolation of scattered data ACM Trans. Math. Software 14 151–152

5 Arguments

1:   M – INTEGERInput
2:   X M – REAL (KIND=nag_wp) arrayInput
3:   Y M – REAL (KIND=nag_wp) arrayInput
4:   Z M – REAL (KIND=nag_wp) arrayInput
5:   F M – REAL (KIND=nag_wp) arrayInput
On entry: M, X, Y, Z and F must be the same values as were supplied in the preceding call to E01TGF.
6:   IQ LIQ – INTEGER arrayInput
On entry: must be unchanged from the value returned from a previous call to E01TGF.
7:   LIQ – INTEGERInput
On entry: the dimension of the array IQ as declared in the (sub)program from which E01THF is called.
Constraint: LIQ≥2×M+1.
8:   RQ LRQ – REAL (KIND=nag_wp) arrayInput
On entry: must be unchanged from the value returned from a previous call to E01TGF.
9:   LRQ – INTEGERInput
On entry: the dimension of the array RQ as declared in the (sub)program from which E01THF is called.
Constraint: LRQ≥10×M+7.
10:   N – INTEGERInput
On entry: n, the number of evaluation points.
Constraint: N≥1.
11:   U N – REAL (KIND=nag_wp) arrayInput
12:   V N – REAL (KIND=nag_wp) arrayInput
13:   W N – REAL (KIND=nag_wp) arrayInput
On entry: U i, V i, W i must be set to the evaluation point ui,vi,wi, for i=1,2,…,n.
14:   Q N – REAL (KIND=nag_wp) arrayOutput
On exit: Q i contains the value of the interpolant, at ui,vi,wi, for i=1,2,…,n. If any of these evaluation points lie outside the region of definition of the interpolant the corresponding entries in Q are set to the largest machine representable number (see X02ALF), and E01THF returns with IFAIL=3.
15:   QX N – REAL (KIND=nag_wp) arrayOutput
16:   QY N – REAL (KIND=nag_wp) arrayOutput
17:   QZ N – REAL (KIND=nag_wp) arrayOutput
On exit: QX i, QY i, QZ i contains the value of the partial derivatives of the interpolant Q x,y,z at ui,vi,wi, for i=1,2,…,n. If any of these evaluation points lie outside the region of definition of the interpolant, the corresponding entries in QX, QY and QZ are set to the largest machine representable number (see X02ALF), and E01THF returns with IFAIL=3.
18:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, | M<10,
or | LIQ<2×M+1,
or | LRQ<10×M+7,
or | N<1.
IFAIL=2
Values supplied in IQ or RQ appear to be invalid. Check that these arrays have not been corrupted between the calls to E01TGF and E01THF.
IFAIL=3
At least one evaluation point lies outside the region of definition of the interpolant. At all such points the corresponding values in Q, QX, QY and QZ have been set to the largest machine representable number (see X02ALF).
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

Computational errors should be negligible in most practical situations.

8 Parallelism and Performance

E01THF is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The time taken for a call to E01THF will depend in general on the distribution of the data points. If X, Y and Z are approximately uniformly distributed, then the time taken should be only O N. At worst O MN time will be required.

10 Example

See Section 10 in E01TGF.
E01 Chapter Contents
E01 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


E01TKF : NAG Library, Mark 26

E01 Chapter Contents
E01 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

E01TKF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
▸▿ 9 Further Comments
9.1 Timing
9.2 Choice of N_w and N_q
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

E01TKF generates a four-dimensional interpolant to a set of scattered data points, using a modified Shepard method.

2 Specification

SUBROUTINE E01TKF ( M, X, F, NW, NQ, IQ, RQ, IFAIL)
INTEGER | M, NW, NQ, IQ(2*M+1), IFAIL
REAL (KIND=nag_wp) | X(4,M), F(M), RQ(15*M+9)

3 Description

E01TKF constructs a smooth function Q x , x∈ℝ 4 which interpolates a set of m scattered data points xr,fr , for r=1,2,…,m, using a modification of Shepard's method. The surface is continuous and has continuous first partial derivatives.
The basic Shepard method, which is a generalization of the two-dimensional method described in Shepard (1968), interpolates the input data with the weighted mean
Q x = ∑ r=1 m wr x qr ∑ r=1 m wr x ,
where qr = fr , wr x = 1 dr 2 and dr 2 = x-xr 2 2 .
The basic method is global in that the interpolated value at any point depends on all the data, but E01TKF uses a modification (see Franke and Nielson (1980) and Renka (1988a)), whereby the method becomes local by adjusting each wr x to be zero outside a hypersphere with centre xr and some radius Rw. Also, to improve the performance of the basic method, each qr above is replaced by a function qr x , which is a quadratic fitted by weighted least squares to data local to xr and forced to interpolate xr,fr . In this context, a point x is defined to be local to another point if it lies within some distance Rq of it.
The efficiency of E01TKF is enhanced by using a cell method for nearest neighbour searching due to Bentley and Friedman (1979) with a cell density of 3.
The radii Rw and Rq are chosen to be just large enough to include Nw and Nq data points, respectively, for user-supplied constants Nw and Nq. Default values of these arguments are provided by the routine, and advice on alternatives is given in Section 9.2.
E01TKF is derived from the new implementation of QSHEP3 described by Renka (1988b). It uses the modification for high-dimensional interpolation described by Berry and Minser (1999).
Values of the interpolant Q x generated by E01TKF, and its first partial derivatives, can subsequently be evaluated for points in the domain of the data by a call to E01TLF.

4 References

Bentley J L and Friedman J H (1979) Data structures for range searching ACM Comput. Surv. 11 397–409
Berry M W, Minser K S (1999) Algorithm 798: high-dimensional interpolation using the modified Shepard method ACM Trans. Math. Software 25 353–366
Franke R and Nielson G (1980) Smooth interpolation of large sets of scattered data Internat. J. Num. Methods Engrg. 15 1691–1704
Renka R J (1988a) Multivariate interpolation of large sets of scattered data ACM Trans. Math. Software 14 139–148
Renka R J (1988b) Algorithm 661: QSHEP3D: Quadratic Shepard method for trivariate interpolation of scattered data ACM Trans. Math. Software 14 151–152
Shepard D (1968) A two-dimensional interpolation function for irregularly spaced data Proc. 23rd Nat. Conf. ACM 517–523 Brandon/Systems Press Inc., Princeton

5 Arguments

1:   M – INTEGERInput
On entry: m, the number of data points.
Constraint: M≥16.
2:   X 4 M – REAL (KIND=nag_wp) arrayInput
On entry: X 1:4 r must be set to the Cartesian coordinates of the data point xr, for r=1,2,…,m.
Constraint: these coordinates must be distinct, and must not all lie on the same three-dimensional hypersurface.
3:   F M – REAL (KIND=nag_wp) arrayInput
On entry: F r must be set to the data value fr, for r=1,2,…,m.
4:   NW – INTEGERInput
On entry: the number Nw of data points that determines each radius of influence Rw, appearing in the definition of each of the weights wr, for r=1,2,…,m (see Section 3). Note that Rw is different for each weight. If NW≤0 the default value NW=min 32,M-1 is used instead.
Constraint: NW≤min 50,M-1.
5:   NQ – INTEGERInput
On entry: the number Nq of data points to be used in the least squares fit for coefficients defining the quadratic functions qr x (see Section 3). If NQ≤0 the default value NQ=min 38,M-1 is used instead.
Constraint: NQ≤0 or 14≤NQ≤min 50,M-1.
6:   IQ 2×M+1 – INTEGER arrayOutput
On exit: integer data defining the interpolant Q x.
7:   RQ 15×M+9 – REAL (KIND=nag_wp) arrayOutput
On exit: real data defining the interpolant Q x.
8:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, M=value.
Constraint: M≥16.
On entry, NQ=value.
Constraint: NQ≤0 or NQ≥14.
On entry, NQ=value and M=value.
Constraint: NQ≤min 50,M-1.
On entry, NW=value and M=value.
Constraint: NW≤min 50,M-1.
IFAIL=2
There are duplicate nodes in the dataset. X ik=X jk, for i=value, j=value and k=1,2,…,4. The interpolant cannot be derived.
IFAIL=3
On entry, all the data points lie on the same three-dimensional hypersurface. No unique solution exists.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

On successful exit, the routine generated interpolates the input data exactly and has quadratic precision. Overall accuracy of the interpolant is affected by the choice of arguments NW and NQ as well as the smoothness of the function represented by the input data.

8 Parallelism and Performance

E01TKF is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
E01TKF makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

9.1 Timing

The time taken for a call to E01TKF will depend in general on the distribution of the data points and on the choice of Nw and Nq parameters. If the data points are uniformly randomly distributed, then the time taken should be O m. At worst O m 2 time will be required.

9.2 Choice of Nw and Nq

Default values of the arguments Nw and Nq may be selected by calling E01TKF with NW≤0 and NQ≤0. These default values may well be satisfactory for many applications.
If non-default values are required they must be supplied to E01TKF through positive values of NW and NQ. Increasing these argument values makes the method less local. This may increase the accuracy of the resulting interpolant at the expense of increased computational cost.

10 Example

This program reads in a set of 30 data points and calls E01TKF to construct an interpolating function Q x . It then calls E01TLF to evaluate the interpolant at a set of points.
Note that this example is not typical of a realistic problem: the number of data points would normally be larger.
See also Section 10 in E01TLF.

10.1 Program Text

Program Text (e01tkfe.f90)

10.2 Program Data

Program Data (e01tkfe.d)

10.3 Program Results

Program Results (e01tkfe.r)

E01 Chapter Contents
E01 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


E01TLF : NAG Library, Mark 26

E01 Chapter Contents
E01 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

E01TLF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

E01TLF evaluates the four-dimensional interpolating function generated by E01TKF and its first partial derivatives.

2 Specification

SUBROUTINE E01TLF ( M, X, F, IQ, RQ, N, XE, Q, QX, IFAIL)
INTEGER | M, IQ(2*M+1), N, IFAIL
REAL (KIND=nag_wp) | X(4,M), F(M), RQ(15*M+9), XE(4,N), Q(N), QX(4,N)

3 Description

E01TLF takes as input the interpolant Q x , x∈ℝ 4 of a set of scattered data points xr,fr , for r=1,2,…,m, as computed by E01TKF, and evaluates the interpolant and its first partial derivatives at the set of points xi , for i=1,2,…,n.
E01TLF must only be called after a call to E01TKF.
E01TLF is derived from the new implementation of QS3GRD described by Renka (1988). It uses the modification for high-dimensional interpolation described by Berry and Minser (1999).

4 References

Berry M W, Minser K S (1999) Algorithm 798: high-dimensional interpolation using the modified Shepard method ACM Trans. Math. Software 25 353–366
Renka R J (1988) Algorithm 661: QSHEP3D: Quadratic Shepard method for trivariate interpolation of scattered data ACM Trans. Math. Software 14 151–152

5 Arguments

1:   M – INTEGERInput
On entry: must be the same value supplied for argument M in the preceding call to E01TKF.
Constraint: M≥16.
2:   X 4 M – REAL (KIND=nag_wp) arrayInput
Note: the coordinates of xr are stored in X 1 r … X 4 r .
On entry: must be the same array supplied as argument X in the preceding call to E01TKF. It must remain unchanged between calls.
3:   F M – REAL (KIND=nag_wp) arrayInput
On entry: must be the same array supplied as argument F in the preceding call to E01TKF. It must remain unchanged between calls.
4:   IQ 2×M+1 – INTEGER arrayInput
On entry: must be the same array returned as argument IQ in the preceding call to E01TKF. It must remain unchanged between calls.
5:   RQ 15×M+9 – REAL (KIND=nag_wp) arrayInput
On entry: must be the same array returned as argument RQ in the preceding call to E01TKF. It must remain unchanged between calls.
6:   N – INTEGERInput
On entry: n, the number of evaluation points.
Constraint: N≥1.
7:   XE 4 N – REAL (KIND=nag_wp) arrayInput
On entry: XE 1:4 i must be set to the evaluation point xi , for i=1,2,…,n.
8:   Q N – REAL (KIND=nag_wp) arrayOutput
On exit: Q i contains the value of the interpolant, at xi, for i=1,2,…,n. If any of these evaluation points lie outside the region of definition of the interpolant the corresponding entries in Q are set to the largest machine representable number (see X02ALF), and E01TLF returns with IFAIL=3.
9:   QX 4 N – REAL (KIND=nag_wp) arrayOutput
On exit: QX ji contains the value of the partial derivatives with respect to xj of the interpolant Q x at xi, for i=1,2,…,n, and for each of the four partial derivatives j=1,2,3,4. If any of these evaluation points lie outside the region of definition of the interpolant, the corresponding entries in QX are set to the largest machine representable number (see X02ALF), and E01TLF returns with IFAIL=3.
10:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, M=value.
Constraint: M≥16.
On entry, N=value.
Constraint: N≥1.
IFAIL=2
On entry, values in IQ appear to be invalid. Check that IQ has not been corrupted between calls to E01TKF and E01TLF.
On entry, values in RQ appear to be invalid. Check that RQ has not been corrupted between calls to E01TKF and E01TLF.
IFAIL=3
On entry, at least one evaluation point lies outside the region of definition of the interpolant. At all such points the corresponding values in Q and QX have been set to X02ALF: X02ALF=value.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

Computational errors should be negligible in most practical situations.

8 Parallelism and Performance

E01TLF is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The time taken for a call to E01TLF will depend in general on the distribution of the data points. If the data points are approximately uniformly distributed, then the time taken should be only O n. At worst O mn time will be required.

10 Example

This program evaluates the function
f x = 1.25 + cos 5.4 x 4 cos 6 x 1 cos 6 x 2 6 + 6 3 x 3 - 1 2
at a set of 30 randomly generated data points and calls E01TKF to construct an interpolating function Q x . It then calls E01TLF to evaluate the interpolant at a set of random points.
To reduce the time taken by this example, the number of data points is limited to 30. Increasing this value improves the interpolation accuracy at the expense of more time.
See also Section 10 in E01TKF.

10.1 Program Text

Program Text (e01tlfe.f90)

10.2 Program Data

Program Data (e01tlfe.d)

10.3 Program Results

Program Results (e01tlfe.r)

E01 Chapter Contents
E01 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


E01TMF : NAG Library, Mark 26

E01 Chapter Contents
E01 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

E01TMF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
▸▿ 9 Further Comments
9.1 Timing
9.2 Choice of N_w and N_q
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

E01TMF generates a five-dimensional interpolant to a set of scattered data points, using a modified Shepard method.

2 Specification

SUBROUTINE E01TMF ( M, X, F, NW, NQ, IQ, RQ, IFAIL)
INTEGER | M, NW, NQ, IQ(2*M+1), IFAIL
REAL (KIND=nag_wp) | X(5,M), F(M), RQ(21*M+11)

3 Description

E01TMF constructs a smooth function Q x , x∈ℝ 5 which interpolates a set of m scattered data points xr,fr , for r=1,2,…,m, using a modification of Shepard's method. The surface is continuous and has continuous first partial derivatives.
The basic Shepard method, which is a generalization of the two-dimensional method described in Shepard (1968), interpolates the input data with the weighted mean
Q x = ∑ r=1 m wr x qr ∑ r=1 m wr x ,
where qr = fr , wr x = 1 dr 2 and dr 2 = x-xr 2 2 .
The basic method is global in that the interpolated value at any point depends on all the data, but E01TMF uses a modification (see Franke and Nielson (1980) and Renka (1988a)), whereby the method becomes local by adjusting each wr x to be zero outside a hypersphere with centre xr and some radius Rw. Also, to improve the performance of the basic method, each qr above is replaced by a function qr x , which is a quadratic fitted by weighted least squares to data local to xr and forced to interpolate xr,fr . In this context, a point x is defined to be local to another point if it lies within some distance Rq of it.
The efficiency of E01TMF is enhanced by using a cell method for nearest neighbour searching due to Bentley and Friedman (1979) with a cell density of 3.
The radii Rw and Rq are chosen to be just large enough to include Nw and Nq data points, respectively, for user-supplied constants Nw and Nq. Default values of these arguments are provided, and advice on alternatives is given in Section 9.2.
E01TMF is derived from the new implementation of QSHEP3 described by Renka (1988b). It uses the modification for five-dimensional interpolation described by Berry and Minser (1999).
Values of the interpolant Q x generated by E01TMF, and its first partial derivatives, can subsequently be evaluated for points in the domain of the data by a call to E01TNF.

4 References

Bentley J L and Friedman J H (1979) Data structures for range searching ACM Comput. Surv. 11 397–409
Berry M W, Minser K S (1999) Algorithm 798: high-dimensional interpolation using the modified Shepard method ACM Trans. Math. Software 25 353–366
Franke R and Nielson G (1980) Smooth interpolation of large sets of scattered data Internat. J. Num. Methods Engrg. 15 1691–1704
Renka R J (1988a) Multivariate interpolation of large sets of scattered data ACM Trans. Math. Software 14 139–148
Renka R J (1988b) Algorithm 661: QSHEP3D: Quadratic Shepard method for trivariate interpolation of scattered data ACM Trans. Math. Software 14 151–152
Shepard D (1968) A two-dimensional interpolation function for irregularly spaced data Proc. 23rd Nat. Conf. ACM 517–523 Brandon/Systems Press Inc., Princeton

5 Arguments

1:   M – INTEGERInput
On entry: m, the number of data points.
Note: on the basis of experimental results reported in Berry and Minser (1999), it is recommended to use M≥4000.
Constraint: M≥23.
2:   X 5 M – REAL (KIND=nag_wp) arrayInput
On entry: X 1:5 r must be set to the Cartesian coordinates of the data point xr, for r=1,2,…,m.
Constraint: these coordinates must be distinct, and must not all lie on the same four-dimensional hypersurface.
3:   F M – REAL (KIND=nag_wp) arrayInput
On entry: F r must be set to the data value fr, for r=1,2,…,m.
4:   NW – INTEGERInput
On entry: the number Nw of data points that determines each radius of influence Rw, appearing in the definition of each of the weights wr, for r=1,2,…,m (see Section 3). Note that Rw is different for each weight. If NW≤0 the default value NW=min 32,M-1 is used instead.
Constraint: NW≤min 50,M-1.
5:   NQ – INTEGERInput
On entry: the number Nq of data points to be used in the least squares fit for coefficients defining the quadratic functions qr x (see Section 3). If NQ≤0 the default value NQ=min 50,M-1 is used instead.
Constraint: NQ≤0 or 20≤NQ≤min 70,M-1.
6:   IQ 2×M+1 – INTEGER arrayOutput
On exit: integer data defining the interpolant Q x.
7:   RQ 21×M+11 – REAL (KIND=nag_wp) arrayOutput
On exit: real data defining the interpolant Q x.
8:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, M=value.
Constraint: M≥23.
On entry, NQ=value.
Constraint: NQ≤0 or NQ≥20.
On entry, NQ=value and M=value.
Constraint: NQ≤min 70,M-1.
On entry, NW=value and M=value.
Constraint: NW≤min 50,M-1.
IFAIL=2
There are duplicate nodes in the dataset. X ik=X jk, for i=value, j=value and k=1,2,…,5. The interpolant cannot be derived.
IFAIL=3
On entry, all the data points lie on the same four-dimensional hypersurface. No unique solution exists.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

On successful exit, the routine generated interpolates the input data exactly and has quadratic precision. Overall accuracy of the interpolant is affected by the choice of arguments NW and NQ as well as the smoothness of the routine represented by the input data. Berry and Minser (1999) report on the results obtained for a set of test routines.

8 Parallelism and Performance

E01TMF is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
E01TMF makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

9.1 Timing

The time taken for a call to E01TMF will depend in general on the distribution of the data points and on the choice of Nw and Nq parameters. If the data points are uniformly randomly distributed, then the time taken should be O m. At worst O m 2 time will be required.

9.2 Choice of Nw and Nq

Default values of the arguments Nw and Nq may be selected by calling E01TMF with NW≤0 and NQ≤0. These default values may well be satisfactory for many applications.
If non-default values are required they must be supplied to E01TMF through positive values of NW and NQ. Increasing these argument values makes the method less local. This may increase the accuracy of the resulting interpolant at the expense of increased computational cost. The default values NW = min 32,M-1 and NQ = min 50,M-1 have been chosen on the basis of experimental results reported in Berry and Minser (1999). In these experiments the error norm was found to increase with the decrease of Nq, but to be little affected by the choice of Nw. The choice of both, directly affected the time taken by the routine. For further advice on the choice of these arguments see Berry and Minser (1999).

10 Example

This program reads in a set of 30 data points and calls E01TMF to construct an interpolating function Q x . It then calls E01TNF to evaluate the interpolant at a set of points.
Note that this example is not typical of a realistic problem: the number of data points would normally be larger.
See also Section 10 in E01TNF.

10.1 Program Text

Program Text (e01tmfe.f90)

10.2 Program Data

Program Data (e01tmfe.d)

10.3 Program Results

Program Results (e01tmfe.r)

E01 Chapter Contents
E01 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


E01TNF : NAG Library, Mark 26

E01 Chapter Contents
E01 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

E01TNF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

E01TNF evaluates the five-dimensional interpolating function generated by E01TMF and its first partial derivatives.

2 Specification

SUBROUTINE E01TNF ( M, X, F, IQ, RQ, N, XE, Q, QX, IFAIL)
INTEGER | M, IQ(2*M+1), N, IFAIL
REAL (KIND=nag_wp) | X(5,M), F(M), RQ(21*M+11), XE(5,N), Q(N), QX(5,N)

3 Description

E01TNF takes as input the interpolant Q x , x∈ℝ 5 of a set of scattered data points xr,fr , for r=1,2,…,m, as computed by E01TMF, and evaluates the interpolant and its first partial derivatives at the set of points xi, for i=1,2,…,n.
E01TNF must only be called after a call to E01TMF.
E01TNF is derived from the new implementation of QS3GRD described by Renka (1988). It uses the modification for five-dimensional interpolation described by Berry and Minser (1999).

4 References

Berry M W, Minser K S (1999) Algorithm 798: high-dimensional interpolation using the modified Shepard method ACM Trans. Math. Software 25 353–366
Renka R J (1988) Algorithm 661: QSHEP3D: Quadratic Shepard method for trivariate interpolation of scattered data ACM Trans. Math. Software 14 151–152

5 Arguments

1:   M – INTEGERInput
On entry: must be the same value supplied for argument M in the preceding call to E01TMF.
Constraint: M≥23.
2:   X 5 M – REAL (KIND=nag_wp) arrayInput
On entry: must be the same array supplied as argument X in the preceding call to E01TMF. It must remain unchanged between calls.
3:   F M – REAL (KIND=nag_wp) arrayInput
On entry: must be the same array supplied as argument F in the preceding call to E01TMF. It must remain unchanged between calls.
4:   IQ 2×M+1 – INTEGER arrayInput
On entry: must be the same array returned as argument IQ in the preceding call to E01TMF. It must remain unchanged between calls.
5:   RQ 21×M+11 – REAL (KIND=nag_wp) arrayInput
On entry: must be the same array returned as argument RQ in the preceding call to E01TMF. It must remain unchanged between calls.
6:   N – INTEGERInput
On entry: n, the number of evaluation points.
Constraint: N≥1.
7:   XE 5 N – REAL (KIND=nag_wp) arrayInput
On entry: XE 1:5 i must be set to the evaluation point xi , for i=1,2,…,n.
8:   Q N – REAL (KIND=nag_wp) arrayOutput
On exit: Q i contains the value of the interpolant, at xi, for i=1,2,…,n. If any of these evaluation points lie outside the region of definition of the interpolant the corresponding entries in Q are set to the largest machine representable number (see X02ALF), and E01TNF returns with IFAIL=3.
9:   QX 5 N – REAL (KIND=nag_wp) arrayOutput
On exit: QX ji contains the value of the partial derivatives with respect to xj of the interpolant Q x at xi, for i=1,2,…,n, and for each of the five partial derivatives j=1,2,3,4,5. If any of these evaluation points lie outside the region of definition of the interpolant, the corresponding entries in QX are set to the largest machine representable number (see X02ALF), and E01TNF returns with IFAIL=3.
10:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, M=value.
Constraint: M≥23.
On entry, N=value.
Constraint: N≥1.
IFAIL=2
On entry, values in IQ appear to be invalid. Check that IQ has not been corrupted between calls to E01TMF and E01TNF.
On entry, values in RQ appear to be invalid. Check that RQ has not been corrupted between calls to E01TMF and E01TNF.
IFAIL=3
On entry, at least one evaluation point lies outside the region of definition of the interpolant. At all such points the corresponding values in Q and QX have been set to X02ALF: X02ALF=value.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

Computational errors should be negligible in most practical situations.

8 Parallelism and Performance

E01TNF is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
E01TNF makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The time taken for a call to E01TNF will depend in general on the distribution of the data points. If the data points are approximately uniformly distributed, then the time taken should be only O n. At worst O mn time will be required.

10 Example

This program evaluates the function
f x = 1.25 + cos 5.4 x 5 cos 6 x 1 cos 6 x 2 cos 6 x 3 6 + 6 3 x 4 - 1 2
at a set of 30 randomly generated data points and calls E01TMF to construct an interpolating function Q x . It then calls E01TNF to evaluate the interpolant at a set of random points.
To reduce the time taken by this example, the number of data points is limited to 30. Increasing this value to the suggested minimum of 4000 improves the interpolation accuracy at the expense of more time.
See also Section 10 in E01TMF.

10.1 Program Text

Program Text (e01tnfe.f90)

10.2 Program Data

Program Data (e01tnfe.d)

10.3 Program Results

Program Results (e01tnfe.r)

E01 Chapter Contents
E01 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


E01ZMF : NAG Library, Mark 26

E01 Chapter Contents
E01 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

E01ZMF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
▸▿ 9 Further Comments
9.1 Timing
9.2 Choice of N_w and N_q
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

E01ZMF generates a multidimensional interpolant to a set of scattered data points, using a modified Shepard method. When the number of dimensions is no more than five, there are corresponding routines in Chapter E01 which are specific to the given dimensionality. E01SGF generates the two-dimensional interpolant, while E01TGF, E01TKF and E01TMF generate the three-, four- and five-dimensional interpolants respectively.

2 Specification

SUBROUTINE E01ZMF ( D, M, X, F, NW, NQ, IQ, RQ, IFAIL)
INTEGER | D, M, NW, NQ, IQ(2*M+1), IFAIL
REAL (KIND=nag_wp) | X(D,M), F(M), RQ(*)

3 Description

E01ZMF constructs a smooth function Q x , x∈ℝd which interpolates a set of m scattered data points xr,fr , for r=1,2,…,m, using a modification of Shepard's method. The surface is continuous and has continuous first partial derivatives.
The basic Shepard method, which is a generalization of the two-dimensional method described in Shepard (1968), interpolates the input data with the weighted mean
Q x = ∑ r=1 m wr x qr ∑ r=1 m wr x ,
where qr = fr , wr x = 1 x - xr 2 2 .
The basic method is global in that the interpolated value at any point depends on all the data, but E01ZMF uses a modification (see Franke and Nielson (1980) and Renka (1988a)), whereby the method becomes local by adjusting each wr x to be zero outside a hypersphere with centre xr and some radius Rw. Also, to improve the performance of the basic method, each qr above is replaced by a function qr x , which is a quadratic fitted by weighted least squares to data local to xr and forced to interpolate xr,fr . In this context, a point x is defined to be local to another point if it lies within some distance Rq of it.
The efficiency of E01ZMF is enhanced by using a cell method for nearest neighbour searching due to Bentley and Friedman (1979) with a cell density of 3.
The radii Rw and Rq are chosen to be just large enough to include Nw and Nq data points, respectively, for user-supplied constants Nw and Nq. Default values of these parameters are provided, and advice on alternatives is given in Section 9.2.
E01ZMF is derived from the new implementation of QSHEP3 described by Renka (1988b). It uses the modification for high-dimensional interpolation described by Berry and Minser (1999).
Values of the interpolant Q x generated by E01ZMF, and its first partial derivatives, can subsequently be evaluated for points in the domain of the data by a call to E01ZNF.

4 References

Bentley J L and Friedman J H (1979) Data structures for range searching ACM Comput. Surv. 11 397–409
Berry M W, Minser K S (1999) Algorithm 798: high-dimensional interpolation using the modified Shepard method ACM Trans. Math. Software 25 353–366
Franke R and Nielson G (1980) Smooth interpolation of large sets of scattered data Internat. J. Num. Methods Engrg. 15 1691–1704
Renka R J (1988a) Multivariate interpolation of large sets of scattered data ACM Trans. Math. Software 14 139–148
Renka R J (1988b) Algorithm 661: QSHEP3D: Quadratic Shepard method for trivariate interpolation of scattered data ACM Trans. Math. Software 14 151–152
Shepard D (1968) A two-dimensional interpolation function for irregularly spaced data Proc. 23rd Nat. Conf. ACM 517–523 Brandon/Systems Press Inc., Princeton

5 Arguments

1:   D – INTEGERInput
On entry: d, the number of dimensions.
Constraint: D≥2.
2:   M – INTEGERInput
On entry: m, the number of data points.
Note: on the basis of experimental results reported in Berry and Minser (1999), when D≥5 it is recommended to use M≥4000.
Constraint: M≥ D+1× D+2/ 2+2.
3:   X DM – REAL (KIND=nag_wp) arrayInput
On entry: X 1:D r must be set to the Cartesian coordinates of the data point xr, for r=1,2,…,m.
Constraint: these coordinates must be distinct, and must not all lie on the same d-1-dimensional hypersurface.
4:   F M – REAL (KIND=nag_wp) arrayInput
On entry: F r must be set to the data value fr, for r=1,2,…,m.
5:   NW – INTEGERInput
On entry: the number Nw of data points that determines each radius of influence Rw, appearing in the definition of each of the weights wr, for r=1,2,…,m (see Section 3). Note that Rw is different for each weight. If NW≤0 the default value NW= min 2× D+1× D+2 ,M-1 is used instead.
Suggested value: NW=-1.
Constraint: NW≤M-1.
6:   NQ – INTEGERInput
On entry: the number Nq of data points to be used in the least squares fit for coefficients defining the quadratic functions qr x (see Section 3). If NQ≤0 the default value NQ=min D+1×D+2×6/5,M-1 is used instead.
Suggested value: NQ=-1.
Constraint: NQ≤0 or D+1×D+2/2-1≤NQ≤M-1.
7:   IQ 2×M+1 – INTEGER arrayOutput
On exit: integer data defining the interpolant Q x.
8:   RQ* – REAL (KIND=nag_wp) arrayOutput
Note: the dimension of the array RQ must be at least D+1×D+2/2×M+2×D+1.
On exit: real data defining the interpolant Q x.
9:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, D=value.
Constraint: D≥2.
On entry, D+1×D+2/2×M+2×D+1 exceeds the largest machine integer.
D=value and M=value.
On entry, M=value and D=value.
Constraint: M≥D+1×D+2/2+2.
On entry, NQ=value and D=value.
Constraint: NQ≤0 or NQ≥D+1×D+2/2-1.
On entry, NQ=value and M=value.
Constraint: NQ≤M-1.
On entry, NW=value and M=value.
Constraint: NW≤M-1.
IFAIL=2
There are duplicate nodes in the dataset. X ki = X kj , for i=value, j=value and k=1,2,…,D. The interpolant cannot be derived.
IFAIL=3
On entry, all the data points lie on the same hypersurface. No unique solution exists.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

In experiments undertaken by Berry and Minser (1999), the accuracies obtained for a conditional function resulting in sharp functional transitions were of the order of 10-1 at best. In other cases in these experiments, the function generated interpolates the input data with maximum absolute error of the order of 10-2.

8 Parallelism and Performance

E01ZMF is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
E01ZMF makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

9.1 Timing

The time taken for a call to E01ZMF will depend in general on the distribution of the data points and on the choice of Nw and Nq parameters. If the data points are uniformly randomly distributed, then the time taken should be O m. At worst O m 2 time will be required.

9.2 Choice of Nw and Nq

Default values of the parameters Nw and Nq may be selected by calling E01ZMF with NW≤0 and NQ≤0. These default values may well be satisfactory for many applications.
If non-default values are required they must be supplied to E01ZMF through positive values of NW and NQ. Increasing these argument values makes the method less local. This may increase the accuracy of the resulting interpolant at the expense of increased computational cost. The default values NW = min 2× D+1× D+2 ,M-1 and NQ = min D+1× D+2× 6/5,M-1 have been chosen on the basis of experimental results reported in Renka (1988a) and Berry and Minser (1999). For further advice on the choice of these arguments see Renka (1988a) and Berry and Minser (1999).

10 Example

This program reads in a set of 30 data points and calls E01ZMF to construct an interpolating function Q x . It then calls E01ZNF to evaluate the interpolant at a set of points.
Note that this example is not typical of a realistic problem: the number of data points would normally be very much larger.
See also Section 10 in E01ZNF.

10.1 Program Text

Program Text (e01zmfe.f90)

10.2 Program Data

Program Data (e01zmfe.d)

10.3 Program Results

Program Results (e01zmfe.r)

E01 Chapter Contents
E01 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


E01ZNF : NAG Library, Mark 26

E01 Chapter Contents
E01 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

E01ZNF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

E01ZNF evaluates the multidimensional interpolating function generated by E01ZMF and its first partial derivatives.

2 Specification

SUBROUTINE E01ZNF ( D, M, X, F, IQ, RQ, N, XE, Q, QX, IFAIL)
INTEGER | D, M, IQ(2*M+1), N, IFAIL
REAL (KIND=nag_wp) | X(D,M), F(M), RQ(*), XE(D,N), Q(N), QX(D,N)

3 Description

E01ZNF takes as input the interpolant Q x , x∈ℝd of a set of scattered data points xr,fr , for r=1,2,…,m, as computed by E01ZMF, and evaluates the interpolant and its first partial derivatives at the set of points xi, for i=1,2,…,n.
E01ZNF must only be called after a call to E01ZMF.
E01ZNF is derived from the new implementation of QS3GRD described by Renka (1988). It uses the modification for high-dimensional interpolation described by Berry and Minser (1999).

4 References

Berry M W, Minser K S (1999) Algorithm 798: high-dimensional interpolation using the modified Shepard method ACM Trans. Math. Software 25 353–366
Renka R J (1988) Algorithm 661: QSHEP3D: Quadratic Shepard method for trivariate interpolation of scattered data ACM Trans. Math. Software 14 151–152

5 Arguments

1:   D – INTEGERInput
On entry: must be the same value supplied for argument D in the preceding call to E01ZMF.
Constraint: D≥2.
2:   M – INTEGERInput
On entry: must be the same value supplied for argument M in the preceding call to E01ZMF.
Constraint: M≥ D+1 × D+2 /2+2 .
3:   X DM – REAL (KIND=nag_wp) arrayInput
Note: the ith ordinate of the point xj is stored in X ij.
On entry: must be the same array supplied as argument X in the preceding call to E01ZMF. It must remain unchanged between calls.
4:   F M – REAL (KIND=nag_wp) arrayInput
On entry: must be the same array supplied as argument F in the preceding call to E01ZMF. It must remain unchanged between calls.
5:   IQ 2×M+1 – INTEGER arrayInput
On entry: must be the same array returned as argument IQ in the preceding call to E01ZMF. It must remain unchanged between calls.
6:   RQ* – REAL (KIND=nag_wp) arrayInput
Note: the dimension of the array RQ must be at least D+1×D+2/2×M+2×D+1.
On entry: must be the same array returned as argument RQ in the preceding call to E01ZMF. It must remain unchanged between calls.
7:   N – INTEGERInput
On entry: n, the number of evaluation points.
Constraint: N≥1.
8:   XE DN – REAL (KIND=nag_wp) arrayInput
Note: the ith ordinate of the point xj is stored in XE ij.
On entry: XE 1:D j must be set to the evaluation point xj, for j=1,2,…,n.
9:   Q N – REAL (KIND=nag_wp) arrayOutput
On exit: Q i contains the value of the interpolant, at xi, for i=1,2,…,n. If any of these evaluation points lie outside the region of definition of the interpolant the corresponding entries in Q are set to an extrapolated approximation, and E01ZNF returns with IFAIL=3.
10:   QX DN – REAL (KIND=nag_wp) arrayOutput
On exit: QX ij contains the value of the partial derivatives with respect to the ith independent variable (dimension) of the interpolant Q x at xj, for j=1,2,…,n, and for each of the partial derivatives i=1,2,…,d. If any of these evaluation points lie outside the region of definition of the interpolant, the corresponding entries in QX are set to extrapolated approximations to the partial derivatives, and E01ZNF returns with IFAIL=3.
11:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, D=value.
Constraint: D≥2.
On entry, D+1×D+2/2×M+2×D+1 exceeds the largest machine integer.
D=value and M=value.
On entry, M=value and D=value.
Constraint: M≥D+1×D+2/2+2.
On entry, N=value.
Constraint: N≥1.
IFAIL=2
On entry, values in IQ appear to be invalid. Check that IQ has not been corrupted between calls to E01ZMF and E01ZNF.
On entry, values in RQ appear to be invalid. Check that RQ has not been corrupted between calls to E01ZMF and E01ZNF.
IFAIL=3
On entry, at least one evaluation point lies outside the region of definition of the interpolant. At such points the corresponding values in Q and QX contain extrapolated approximations. Points should be evaluated one by one to identify extrapolated values.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

Computational errors should be negligible in most practical situations.

8 Parallelism and Performance

E01ZNF is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
E01ZNF makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The time taken for a call to E01ZNF will depend in general on the distribution of the data points. If the data points are approximately uniformly distributed, then the time taken should be only O n. At worst O mn time will be required.

10 Example

This program evaluates the function (in six variables)
f x = x 1 x 2 x 3 1 + 2 x 4 x 5 x 6
at a set of randomly generated data points and calls E01ZMF to construct an interpolating function Qx. It then calls E01ZNF to evaluate the interpolant at a set of points on the line xi=x, for i=1,2,…,6. To reduce the time taken by this example, the number of data points is limited. Increasing this value to the suggested minimum of 4000 improves the interpolation accuracy at the expense of more time.
See also Section 10 in E01ZMF.

10.1 Program Text

Program Text (e01znfe.f90)

10.2 Program Data

Program Data (e01znfe.d)

10.3 Program Results

Program Results (e01znfe.r)

E01 Chapter Contents
E01 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


E02ACF : NAG Library, Mark 26

E02 Chapter Contents
E02 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

E02ACF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

E02ACF calculates a minimax polynomial fit to a set of data points.

2 Specification

SUBROUTINE E02ACF ( X, Y, N, A, M1, REF)
INTEGER | N, M1
REAL (KIND=nag_wp) | X(N), Y(N), A(M1), REF

3 Description

Given a set of data points xi,yi, for i=1,2,…,n, E02ACF uses the exchange algorithm to compute an mth-order polynomial
P x=a 1+a 2 x+a 3 x 2+⋯+a m+1 xm
such that maxi 2 P xi-yi is a minimum.
The routine also returns a number whose absolute value is the final reference deviation (see Section 6). The routine is an adaptation of Boothroyd (1967).

4 References

Boothroyd J B (1967) Algorithm 318 Comm. ACM 10 801
Stieffel E (1959) Numerical methods of Tchebycheff approximation On Numerical Approximation (ed R E Langer) 217–232 University of Wisconsin Press

5 Arguments

1:   X N – REAL (KIND=nag_wp) arrayInput
On entry: the values of the x coordinates, xi, for i=1,2,…,n.
Constraint: x 1<x 2<⋯<xn.
2:   Y N – REAL (KIND=nag_wp) arrayInput
On entry: the values of the y coordinates, yi, for i=1,2,…,n.
3:   N – INTEGERInput
On entry: the number n of data points.
4:   A M1 – REAL (KIND=nag_wp) arrayOutput
On exit: the coefficients ai of the final polynomial, for i=1,2,…,m+1.
5:   M1 – INTEGERInput
On entry: m+1, where m is the order of the polynomial to be found.
Constraint: M1<min N,100.
6:   REF – REAL (KIND=nag_wp)Output
On exit: the final reference deviation (see Section 6).

6 Error Indicators and Warnings

If an error is detected in an input argument E02ACF will act as if a soft noisy exit has been requested (see Section 3.4.4 in How to Use the NAG Library and its Documentation).

7 Accuracy

This is wholly dependent on the given data points.

8 Parallelism and Performance

E02ACF makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The time taken increases with m.

10 Example

This example calculates a minimax fit with a polynomial of degree 5 to the exponential function evaluated at 21 points over the interval 0,1. It then prints values of the function and the fitted polynomial.

10.1 Program Text

Program Text (e02acfe.f90)

10.2 Program Data

None.

10.3 Program Results

Program Results (e02acfe.r)

GnuplotProduced by GNUPLOT 4.6 patchlevel 3 0 0.5 1 1.5 2 2.5 3 0 0.2 0.4 0.6 0.8 1 1e−07 1e−06 1e−05 0.0001 0.001 Polynomial P(x) |P(x) -exp(x)| x Example Program Minimax Fit to the Exponential Function on the Interval [0,1] using a Degree Five Polynomial, P(x), given exp(x) Evaluated at 21 Points |P(x) - exp(x)| polynomial fit gnuplot_plot_1 points on exp(x) gnuplot_plot_2 gnuplot_plot_3
E02 Chapter Contents
E02 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


E02ADF : NAG Library, Mark 26

E02 Chapter Contents
E02 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

E02ADF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

E02ADF computes weighted least squares polynomial approximations to an arbitrary set of data points.

2 Specification

SUBROUTINE E02ADF ( M, KPLUS1, LDA, X, Y, W, WORK1, WORK2, A, S, IFAIL)
INTEGER | M, KPLUS1, LDA, IFAIL
REAL (KIND=nag_wp) | X(M), Y(M), W(M), WORK1(3*M), WORK2(2*KPLUS1), A(LDA,KPLUS1), S(KPLUS1)

3 Description

E02ADF determines least squares polynomial approximations of degrees 0,1,…,k to the set of data points xr,yr with weights wr, for r=1,2,…,m.
The approximation of degree i has the property that it minimizes σi the sum of squares of the weighted residuals εr, where
εr=wr yr-fr
and fr is the value of the polynomial of degree i at the rth data point.
Each polynomial is represented in Chebyshev series form with normalized argument x-. This argument lies in the range -1 to +1 and is related to the original variable x by the linear transformation
x-= 2 x-xmax-xmin xmax-xmin .
Here xmax and xmin are respectively the largest and smallest values of xr. The polynomial approximation of degree i is represented as
12 a i+1,1T 0 x-+a i+1,2T 1 x-+a i+1,3T 2 x-+⋯+a i+1,i+1Ti x-,
where Tj x-, for j=0,1,…,i, are the Chebyshev polynomials of the first kind of degree j with argument x-.
For i=0,1,…,k, the routine produces the values of a i+1,j+1, for j=0,1,…,i, together with the value of the root-mean-square residual si=σi/m-i-1. In the case m=i+1 the routine sets the value of si to zero.
The method employed is due to Forsythe (1957) and is based on the generation of a set of polynomials orthogonal with respect to summation over the normalized dataset. The extensions due to Clenshaw (1960) to represent these polynomials as well as the approximating polynomials in their Chebyshev series forms are incorporated. The modifications suggested by Reinsch and Gentleman (see Gentleman (1969)) to the method originally employed by Clenshaw for evaluating the orthogonal polynomials from their Chebyshev series representations are used to give greater numerical stability.
For further details of the algorithm and its use see Cox (1974) and Cox and Hayes (1973).
Subsequent evaluation of the Chebyshev series representations of the polynomial approximations should be carried out using E02AEF.

4 References

Clenshaw C W (1960) Curve fitting with a digital computer Comput. J. 2 170–173
Cox M G (1974) A data-fitting package for the non-specialist user Software for Numerical Mathematics (ed D J Evans) Academic Press
Cox M G and Hayes J G (1973) Curve fitting: a guide and suite of algorithms for the non-specialist user NPL Report NAC26 National Physical Laboratory
Forsythe G E (1957) Generation and use of orthogonal polynomials for data fitting with a digital computer J. Soc. Indust. Appl. Math. 5 74–88
Gentleman W M (1969) An error analysis of Goertzel's (Watt's) method for computing Fourier coefficients Comput. J. 12 160–165
Hayes J G (ed.) (1970) Numerical Approximation to Functions and Data Athlone Press, London

5 Arguments

1:   M – INTEGERInput
On entry: the number m of data points.
Constraint: M≥mdist≥2, where mdist is the number of distinct x values in the data.
2:   KPLUS1 – INTEGERInput
On entry: k+1, where k is the maximum degree required.
Constraint: 0<KPLUS1≤mdist, where mdist is the number of distinct x values in the data.
3:   LDA – INTEGERInput
On entry: the first dimension of the array A as declared in the (sub)program from which E02ADF is called.
Constraint: LDA≥KPLUS1.
4:   X M – REAL (KIND=nag_wp) arrayInput
On entry: the values xr of the independent variable, for r=1,2,…,m.
Constraint: the values must be supplied in nondecreasing order with X M>X 1.
5:   Y M – REAL (KIND=nag_wp) arrayInput
On entry: the values yr of the dependent variable, for r=1,2,…,m.
6:   W M – REAL (KIND=nag_wp) arrayInput
On entry: the set of weights, wr, for r=1,2,…,m. For advice on the choice of weights, see Section 2.1.2 in the E02 Chapter Introduction.
Constraint: W r>0.0, for r=1,2,…,m.
7:   WORK1 3×M – REAL (KIND=nag_wp) arrayWorkspace
8:   WORK2 2×KPLUS1 – REAL (KIND=nag_wp) arrayWorkspace
9:   A LDAKPLUS1 – REAL (KIND=nag_wp) arrayOutput
On exit: the coefficients of Tj x- in the approximating polynomial of degree i. A i+1j+1 contains the coefficient a i+1,j+1, for i=0,1,…,k and j=0,1,…,i.
10:   S KPLUS1 – REAL (KIND=nag_wp) arrayOutput
On exit: S i+1 contains the root-mean-square residual si, for i=0,1,…,k, as described in Section 3. For the interpretation of the values of the si and their use in selecting an appropriate degree, see Section 3.1 in the E02 Chapter Introduction.
11:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
The weights are not all strictly positive.
IFAIL=2
The values of X r, for r=1,2,…,M, are not in nondecreasing order.
IFAIL=3
All X r have the same value: thus the normalization of X is not possible.
IFAIL=4
On entry, | KPLUS1<1 (so the maximum degree required is negative)
or | KPLUS1>mdist, where mdist is the number of distinct x values in the data (so there cannot be a unique solution for degree k=KPLUS1-1).
IFAIL=5
LDA<KPLUS1.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

No error analysis for the method has been published. Practical experience with the method, however, is generally extremely satisfactory.

8 Parallelism and Performance

E02ADF is not threaded in any implementation.

9 Further Comments

The time taken is approximately proportional to m k+1k+11.
The approximating polynomials may exhibit undesirable oscillations (particularly near the ends of the range) if the maximum degree k exceeds a critical value which depends on the number of data points m and their relative positions. As a rough guide, for equally-spaced data, this critical value is about 2×m. For further details see page 60 of Hayes (1970).

10 Example

Determine weighted least squares polynomial approximations of degrees 0, 1, 2 and 3 to a set of 11 prescribed data points. For the approximation of degree 3, tabulate the data and the corresponding values of the approximating polynomial, together with the residual errors, and also the values of the approximating polynomial at points half-way between each pair of adjacent data points.
The example program supplied is written in a general form that will enable polynomial approximations of degrees 0,1,…,k to be obtained to m data points, with arbitrary positive weights, and the approximation of degree k to be tabulated. E02AEF is used to evaluate the approximating polynomial. The program is self-starting in that any number of datasets can be supplied.

10.1 Program Text

Program Text (e02adfe.f90)

10.2 Program Data

Program Data (e02adfe.d)

10.3 Program Results

Program Results (e02adfe.r)

GnuplotProduced by GNUPLOT 4.6 patchlevel 3 0 10 20 30 40 0 2 4 6 8 10 −0.1 −0.05 0 0.05 0.1 y |P(xi) -f(xi)| x Example Program Least-squares Cubic Polynomial Approximation to a set of 11 Data Points P(xi) -f(xi) polynomial fit gnuplot_plot_1 points f(xi) gnuplot_plot_2 gnuplot_plot_3
E02 Chapter Contents
E02 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


E02AEF : NAG Library, Mark 26

E02 Chapter Contents
E02 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

E02AEF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

E02AEF evaluates a polynomial from its Chebyshev series representation.

2 Specification

SUBROUTINE E02AEF ( NPLUS1, A, XCAP, P, IFAIL)
INTEGER | NPLUS1, IFAIL
REAL (KIND=nag_wp) | A(NPLUS1), XCAP, P

3 Description

E02AEF evaluates the polynomial
12 a 1T 0 x-+a 2T 1 x-+a 3T 2 x-+⋯+a n+1Tn x-
for any value of x- satisfying -1≤x-≤1. Here Tj x- denotes the Chebyshev polynomial of the first kind of degree j with argument x-. The value of n is prescribed by you.
In practice, the variable x- will usually have been obtained from an original variable x, where xmin≤x≤xmax and
x-=x-xmin-xmax-x xmax-xmin
Note that this form of the transformation should be used computationally rather than the mathematical equivalent
x-= 2 x-xmin-xmax xmax-xmin
since the former guarantees that the computed value of x- differs from its true value by at most 4 ε, where ε is the machine precision, whereas the latter has no such guarantee.
The method employed is based on the three-term recurrence relation due to Clenshaw (1955), with modifications to give greater numerical stability due to Reinsch and Gentleman (see Gentleman (1969)).
For further details of the algorithm and its use see Cox (1974) and Cox and Hayes (1973).

4 References

Clenshaw C W (1955) A note on the summation of Chebyshev series Math. Tables Aids Comput. 9 118–120
Cox M G (1974) A data-fitting package for the non-specialist user Software for Numerical Mathematics (ed D J Evans) Academic Press
Cox M G and Hayes J G (1973) Curve fitting: a guide and suite of algorithms for the non-specialist user NPL Report NAC26 National Physical Laboratory
Gentleman W M (1969) An error analysis of Goertzel's (Watt's) method for computing Fourier coefficients Comput. J. 12 160–165

5 Arguments

1:   NPLUS1 – INTEGERInput
On entry: the number n+1 of terms in the series (i.e., one greater than the degree of the polynomial).
Constraint: NPLUS1≥1.
2:   A NPLUS1 – REAL (KIND=nag_wp) arrayInput
On entry: A i must be set to the value of the ith coefficient in the series, for i=1,2,…,n+1.
3:   XCAP – REAL (KIND=nag_wp)Input
On entry: x-, the argument at which the polynomial is to be evaluated. It should lie in the range -1 to +1, but a value just outside this range is permitted (see Section 6) to allow for possible rounding errors committed in the transformation from x to x- discussed in Section 3. Provided the recommended form of the transformation is used, a successful exit is thus assured whenever the value of x lies in the range xmin to xmax.
4:   P – REAL (KIND=nag_wp)Output
On exit: the value of the polynomial.
5:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
ABS XCAP>1.0+4 ε, where ε is the machine precision. In this case the value of P is set arbitrarily to zero.
IFAIL=2
On entry, NPLUS1<1.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

The rounding errors committed are such that the computed value of the polynomial is exact for a slightly perturbed set of coefficients ai+δ ai. The ratio of the sum of the absolute values of the δ ai to the sum of the absolute values of the ai is less than a small multiple of n+1×machine precision.

8 Parallelism and Performance

E02AEF is not threaded in any implementation.

9 Further Comments

The time taken is approximately proportional to n+1.
It is expected that a common use of E02AEF will be the evaluation of the polynomial approximations produced by E02ADF and E02AFF.

10 Example

Evaluate at 11 equally-spaced points in the interval -1≤x-≤1 the polynomial of degree 4 with Chebyshev coefficients, 2.0, 0.5, 0.25, 0.125, 0.0625.
The example program is written in a general form that will enable a polynomial of degree n in its Chebyshev series form to be evaluated at m equally-spaced points in the interval -1≤x-≤1. The program is self-starting in that any number of datasets can be supplied.

10.1 Program Text

Program Text (e02aefe.f90)

10.2 Program Data

Program Data (e02aefe.d)

10.3 Program Results

Program Results (e02aefe.r)

GnuplotProduced by GNUPLOT 4.6 patchlevel 3 0.6 0.8 1 1.2 1.4 1.6 1.8 2 −1 −0.5 0 0.5 1 P(x) x Example Program Points on a Degree Four Polynomial P(x) = 1+0.5T1(x)+0.25T2(x)+0.125T3(x)+0.0625T4(x) gnuplot_plot_1 gnuplot_plot_2
E02 Chapter Contents
E02 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


E02AFF : NAG Library, Mark 26

E02 Chapter Contents
E02 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

E02AFF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

E02AFF computes the coefficients of a polynomial, in its Chebyshev series form, which interpolates (passes exactly through) data at a special set of points. Least squares polynomial approximations can also be obtained.

2 Specification

SUBROUTINE E02AFF ( NPLUS1, F, A, IFAIL)
INTEGER | NPLUS1, IFAIL
REAL (KIND=nag_wp) | F(NPLUS1), A(NPLUS1)

3 Description

E02AFF computes the coefficients aj, for j=1,2,…,n+1, in the Chebyshev series
12 a 1T 0 x-+a 2T 1 x-+a 3T 2 x-+⋯+a n+1Tn x-,
which interpolates the data fr at the points
x-r=cos r-1 π/n ,  r=1,2,…,n+1.
Here Tj x- denotes the Chebyshev polynomial of the first kind of degree j with argument x-. The use of these points minimizes the risk of unwanted fluctuations in the polynomial and is recommended when the data abscissae can be chosen by you, e.g., when the data is given as a graph. For further advantages of this choice of points, see Clenshaw (1962).
In terms of your original variables, x say, the values of x at which the data fr are to be provided are
xr=12 xmax-xmin cos π r-1/n+12 xmax+xmin,  r=1,2,…,n+1
where xmax and xmin are respectively the upper and lower ends of the range of x over which you wish to interpolate.
Truncation of the resulting series after the term involving a i+1, say, yields a least squares approximation to the data. This approximation, p x-, say, is the polynomial of degree i which minimizes
12 ε 12+ε 22+ε 32+⋯+εn 2+12 ε n+1 2,
where the residual εr=p x-r-fr, for r=1,2,…,n+1.
The method employed is based on the application of the three-term recurrence relation due to Clenshaw (1955) for the evaluation of the defining expression for the Chebyshev coefficients (see, for example, Clenshaw (1962)). The modifications to this recurrence relation suggested by Reinsch and Gentleman (see Gentleman (1969)) are used to give greater numerical stability.
For further details of the algorithm and its use see Cox (1974) and Cox and Hayes (1973).
Subsequent evaluation of the computed polynomial, perhaps truncated after an appropriate number of terms, should be carried out using E02AEF.

4 References

Clenshaw C W (1955) A note on the summation of Chebyshev series Math. Tables Aids Comput. 9 118–120
Clenshaw C W (1962) Chebyshev Series for Mathematical Functions Mathematical tables HMSO
Cox M G (1974) A data-fitting package for the non-specialist user Software for Numerical Mathematics (ed D J Evans) Academic Press
Cox M G and Hayes J G (1973) Curve fitting: a guide and suite of algorithms for the non-specialist user NPL Report NAC26 National Physical Laboratory
Gentleman W M (1969) An error analysis of Goertzel's (Watt's) method for computing Fourier coefficients Comput. J. 12 160–165

5 Arguments

1:   NPLUS1 – INTEGERInput
On entry: the number n+1 of data points (one greater than the degree n of the interpolating polynomial).
Constraint: NPLUS1≥2.
2:   F NPLUS1 – REAL (KIND=nag_wp) arrayInput
On entry: for r=1,2,…,n+1, F r must contain fr the value of the dependent variable (ordinate) corresponding to the value
x-r=cos π r-1/n
of the independent variable (abscissa) x-, or equivalently to the value
x r=12 xmax-xmin cos π r-1/n+12 xmax+xmin
of your original variable x. Here xmax and xmin are respectively the upper and lower ends of the range over which you wish to interpolate.
3:   A NPLUS1 – REAL (KIND=nag_wp) arrayOutput
On exit: A j is the coefficient aj in the interpolating polynomial, for j=1,2,…,n+1.
4:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, NPLUS1<2.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

The rounding errors committed are such that the computed coefficients are exact for a slightly perturbed set of ordinates fr+δ fr. The ratio of the sum of the absolute values of the δ fr to the sum of the absolute values of the fr is less than a small multiple of n+1 ε, where ε is the machine precision.

8 Parallelism and Performance

E02AFF is not threaded in any implementation.

9 Further Comments

The time taken is approximately proportional to n+1 2+30.
For choice of degree when using the routine for least squares approximation, see Section 3.2 in the E02 Chapter Introduction.

10 Example

Determine the Chebyshev coefficients of the polynomial which interpolates the data x-r,fr, for r=1,2,…,11, where x-r=cos π×r-1/10 and fr=e x-r. Evaluate, for comparison with the values of fr, the resulting Chebyshev series at x-r, for r=1,2,…,11.
The example program supplied is written in a general form that will enable polynomial interpolations of arbitrary data at the cosine points cos π×r-1/n, for r=1,2,…,n+1, to be obtained for any n (=NPLUS1-1). Note that E02AEF is used to evaluate the interpolating polynomial. The program is self-starting in that any number of datasets can be supplied.

10.1 Program Text

Program Text (e02affe.f90)

10.2 Program Data

Program Data (e02affe.d)

10.3 Program Results

Program Results (e02affe.r)

GnuplotProduced by GNUPLOT 4.6 patchlevel 3 0 0.5 1 1.5 2 2.5 −1 −0.5 0 0.5 1 5e−05 0.0001 0.00015 P(x) |ex−P(x)| (error) x Example Program Interpolating Chebyshev Polynomial Chebyshev polynomial fit |ex−P(x)| gnuplot_plot_1 gnuplot_plot_2 gnuplot_plot_3
E02 Chapter Contents
E02 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


E02AGF : NAG Library, Mark 26

E02 Chapter Contents
E02 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

E02AGF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

E02AGF computes constrained weighted least squares polynomial approximations in Chebyshev series form to an arbitrary set of data points. The values of the approximations and any number of their derivatives can be specified at selected points.

2 Specification

SUBROUTINE E02AGF ( M, KPLUS1, LDA, XMIN, XMAX, X, Y, W, MF, XF, YF, LYF, IP, A, S, NP1, WRK, LWRK, IWRK, LIWRK, IFAIL)
INTEGER | M, KPLUS1, LDA, MF, LYF, IP(MF), NP1, LWRK, IWRK(LIWRK), LIWRK, IFAIL
REAL (KIND=nag_wp) | XMIN, XMAX, X(M), Y(M), W(M), XF(MF), YF(LYF), A(LDA,KPLUS1), S(KPLUS1), WRK(LWRK)

3 Description

E02AGF determines least squares polynomial approximations of degrees up to k to the set of data points xr,yr with weights wr, for r=1,2,…,m. The value of k, the maximum degree required, is to be prescribed by you. At each of the values xf r, for r=1,2,…,mf, of the independent variable x, the approximations and their derivatives up to order pr are constrained to have one of the values yf s, for s=1,2,…,n, specified by you, where n=mf+∑r=0mf pr.
The approximation of degree i has the property that, subject to the imposed constraints, it minimizes σi, the sum of the squares of the weighted residuals εr, for r=1,2,…,m, where
εr=wr yr-fi xr
and fi xr is the value of the polynomial approximation of degree i at the rth data point.
Each polynomial is represented in Chebyshev series form with normalized argument x-. This argument lies in the range -1 to +1 and is related to the original variable x by the linear transformation
x-=2 x-xmax+xmin xmax-xmin
where xmin and xmax, specified by you, are respectively the lower and upper end points of the interval of x over which the polynomials are to be defined.
The polynomial approximation of degree i can be written as
12 a i,0+a i,1T 1 x-+⋯+a ijTj x-+⋯+a iiTi x-
where Tj x- is the Chebyshev polynomial of the first kind of degree j with argument x-. For i=n,n+1,…,k, the routine produces the values of the coefficients a ij, for j=0,1,…,i, together with the value of the root mean square residual,
Si = σ i m ′ +n -i -1 ,
where m′ is the number of data points with nonzero weight.
Values of the approximations may subsequently be computed using E02AEF or E02AKF.
First E02AGF determines a polynomial μ x-, of degree n-1, which satisfies the given constraints, and a polynomial ν x-, of degree n, which has value (or derivative) zero wherever a constrained value (or derivative) is specified. It then fits yr-μ xr, for r=1,2,…,m, with polynomials of the required degree in x- each with factor ν x-. Finally the coefficients of μ x- are added to the coefficients of these fits to give the coefficients of the constrained polynomial approximations to the data points xr,yr, for r=1,2,…,m. The method employed is given in Hayes (1970): it is an extension of Forsythe's orthogonal polynomials method (see Forsythe (1957)) as modified by Clenshaw (see Clenshaw (1960)).

4 References

Clenshaw C W (1960) Curve fitting with a digital computer Comput. J. 2 170–173
Forsythe G E (1957) Generation and use of orthogonal polynomials for data fitting with a digital computer J. Soc. Indust. Appl. Math. 5 74–88
Hayes J G (ed.) (1970) Numerical Approximation to Functions and Data Athlone Press, London

5 Arguments

1:   M – INTEGERInput
On entry: m, the number of data points to be fitted.
Constraint: M≥1.
2:   KPLUS1 – INTEGERInput
On entry: k+1, where k is the maximum degree required.
Constraint: n+1≤KPLUS1≤m′′+n is the total number of constraints and m′′ is the number of data points with nonzero weights and distinct abscissae which do not coincide with any of the XF r.
3:   LDA – INTEGERInput
On entry: the first dimension of the array A as declared in the (sub)program from which E02AGF is called.
Constraint: LDA≥KPLUS1.
4:   XMIN – REAL (KIND=nag_wp)Input
5:   XMAX – REAL (KIND=nag_wp)Input
On entry: the lower and upper end points, respectively, of the interval xmin,xmax. Unless there are specific reasons to the contrary, it is recommended that XMIN and XMAX be set respectively to the lowest and highest value among the xr and xf r. This avoids the danger of extrapolation provided there is a constraint point or data point with nonzero weight at each end point.
Constraint: XMAX>XMIN.
6:   X M – REAL (KIND=nag_wp) arrayInput
On entry: X r must contain the value xr of the independent variable at the rth data point, for r=1,2,…,m.
Constraint: the X r must be in nondecreasing order and satisfy XMIN≤X r≤XMAX.
7:   Y M – REAL (KIND=nag_wp) arrayInput
On entry: Y r must contain yr, the value of the dependent variable at the rth data point, for r=1,2,…,m.
8:   W M – REAL (KIND=nag_wp) arrayInput
On entry: W r must contain the weight wr to be applied to the data point xr, for r=1,2,…,m. For advice on the choice of weights see the E02 Chapter Introduction. Negative weights are treated as positive. A zero weight causes the corresponding data point to be ignored. Zero weight should be given to any data point whose x and y values both coincide with those of a constraint (otherwise the denominators involved in the root mean square residuals Si will be slightly in error).
9:   MF – INTEGERInput
On entry: mf, the number of values of the independent variable at which a constraint is specified.
Constraint: MF≥1.
10:   XF MF – REAL (KIND=nag_wp) arrayInput
On entry: XF r must contain xf r, the value of the independent variable at which a constraint is specified, for r=1,2,…,MF.
Constraint: these values need not be ordered but must be distinct and satisfy XMIN≤XF r≤XMAX.
11:   YF LYF – REAL (KIND=nag_wp) arrayInput
On entry: the values which the approximating polynomials and their derivatives are required to take at the points specified in XF. For each value of XF r, YF contains in successive elements the required value of the approximation, its first derivative, second derivative, …,prth derivative, for r=1,2,…,mf. Thus the value, yf s, which the kth derivative of each approximation (k=0 referring to the approximation itself) is required to take at the point XF r must be contained in YF s, where
s=r+k+p 1+p 2+⋯+p r-1,
where k=0,1,…,pr and r=1,2,…,mf. The derivatives are with respect to the independent variable x.
12:   LYF – INTEGERInput
On entry: the dimension of the array YF as declared in the (sub)program from which E02AGF is called.
Constraint: LYF≥MF+ ∑ i=1 MF IP i.
13:   IP MF – INTEGER arrayInput
On entry: IP r must contain pr, the order of the highest-order derivative specified at XF r, for r=1,2,…,mf. pr=0 implies that the value of the approximation at XF r is specified, but not that of any derivative.
Constraint: IP r≥0, for r=1,2,…,MF.
14:   A LDAKPLUS1 – REAL (KIND=nag_wp) arrayOutput
On exit: A i+1j+1 contains the coefficient a ij in the approximating polynomial of degree i, for i=n,…,k and j=0,1,…,i.
15:   S KPLUS1 – REAL (KIND=nag_wp) arrayOutput
On exit: S i+1 contains Si, for i=n,…,k, the root mean square residual corresponding to the approximating polynomial of degree i. In the case where the number of data points with nonzero weight is equal to k+1-n, Si is indeterminate: the routine sets it to zero. For the interpretation of the values of Si and their use in selecting an appropriate degree, see Section 3.1 in the E02 Chapter Introduction.
16:   NP1 – INTEGEROutput
On exit: n+1, where n is the total number of constraint conditions imposed: n=mf+p 1+p 2+⋯+p mf.
17:   WRK LWRK – REAL (KIND=nag_wp) arrayOutput
On exit: contains weighted residuals of the highest degree of fit determined k. The residual at xr is in element 2 n+1+3 m+k+1+r, for r=1,2,…,m. The rest of the array is used as workspace.
18:   LWRK – INTEGERInput
On entry: the dimension of the array WRK as declared in the (sub)program from which E02AGF is called.
Constraint: LWRK≥max 4×M+3×KPLUS1,8×n+5×ipmax+MF+10+2×n+2, where ipmax=max IP r, for r=1,2,…,mf.
19:   IWRK LIWRK – INTEGER arrayWorkspace
20:   LIWRK – INTEGERInput
On entry: the dimension of the array IWRK as declared in the (sub)program from which E02AGF is called.
Constraint: LIWRK≥2×MF+2.
21:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, | M<1,
or | KPLUS1<n+1,
or | LDA<KPLUS1,
or | MF<1,
or | LYF<n,
or | LWRK is too small (see Section 5),
or | LIWRK<2×MF+2.
(Here n is the total number of constraint conditions.)
IFAIL=2
IP r<0 for some r=1,2,…,MF.
IFAIL=3
XMIN≥XMAX, or XF r is not in the interval XMIN to XMAX for some r=1,2,…,MF, or the XF r are not distinct.
IFAIL=4
X r is not in the interval XMIN to XMAX for some r=1,2,…,M.
IFAIL=5
X r<X r-1 for some r=2,3,…,M.
IFAIL=6
KPLUS1>m′′+n, where m′′ is the number of data points with nonzero weight and distinct abscissae which do not coincide with any XF r. Thus there is no unique solution.
IFAIL=7
The polynomials μ x and/or ν x cannot be determined. The problem supplied is too ill-conditioned. This may occur when the constraint points are very close together, or large in number, or when an attempt is made to constrain high-order derivatives.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

No complete error analysis exists for either the interpolating algorithm or the approximating algorithm. However, considerable experience with the approximating algorithm shows that it is generally extremely satisfactory. Also the moderate number of constraints, of low-order, which are typical of data fitting applications, are unlikely to cause difficulty with the interpolating routine.

8 Parallelism and Performance

E02AGF is not threaded in any implementation.

9 Further Comments

The time taken to form the interpolating polynomial is approximately proportional to n 3, and that to form the approximating polynomials is very approximately proportional to m k+1k+1-n.
To carry out a least squares polynomial fit without constraints, use E02ADF. To carry out polynomial interpolation only, use E01AEF.

10 Example

This example reads data in the following order, using the notation of the argument list above:
  • MF
  • IP i, XF i, Y-value and derivative values (if any) at XF i, for i=1,2,…,MF
  • M
  • X i, Y i, W i, for i=1,2,…,M
  • k, XMIN, XMAX
The output is:
  • the root mean square residual for each degree from n to k;
  • the Chebyshev coefficients for the fit of degree k;
  • the data points, and the fitted values and residuals for the fit of degree k.
The program is written in a generalized form which will read any number of datasets.
The dataset supplied specifies 5 data points in the interval 0.0,4.0 with unit weights, to which are to be fitted polynomials, p, of degrees up to 4, subject to the 3 constraints:
  • p 0.0=1.0,  p′0.0=-2.0,  p 4.0=9.0.

10.1 Program Text

Program Text (e02agfe.f90)

10.2 Program Data

Program Data (e02agfe.d)

10.3 Program Results

Program Results (e02agfe.r)

GnuplotProduced by GNUPLOT 4.6 patchlevel 3 −2 −1.5 −1 −0.5 0 0.5 1 1.5 2 0.5 1 1.5 2 2.5 3 −0.004 −0.002 0 0.002 0.004 Polynomial Fit P(x) Residual P(xi)−yi x Example Program Constrained Least-squares Polynomial Approximation residual polynomial fit gnuplot_plot_1 data points gnuplot_plot_2 gnuplot_plot_3
E02 Chapter Contents
E02 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


E02AHF : NAG Library, Mark 26

E02 Chapter Contents
E02 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

E02AHF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

E02AHF determines the coefficients in the Chebyshev series representation of the derivative of a polynomial given in Chebyshev series form.

2 Specification

SUBROUTINE E02AHF ( NP1, XMIN, XMAX, A, IA1, LA, PATM1, ADIF, IADIF1, LADIF, IFAIL)
INTEGER | NP1, IA1, LA, IADIF1, LADIF, IFAIL
REAL (KIND=nag_wp) | XMIN, XMAX, A(LA), PATM1, ADIF(LADIF)

3 Description

E02AHF forms the polynomial which is the derivative of a given polynomial. Both the original polynomial and its derivative are represented in Chebyshev series form. Given the coefficients ai, for i=0,1,…,n, of a polynomial p x of degree n, where
p x=12 a 0+a 1T 1 x-+⋯+anTn x-
the routine returns the coefficients a-i, for i=0,1,…,n-1, of the polynomial q x of degree n-1, where
q x=dp x dx =12 a-0+a-1T 1 x-+⋯+a-n-1T n-1 x-.
Here Tj x- denotes the Chebyshev polynomial of the first kind of degree j with argument x-. It is assumed that the normalized variable x- in the interval -1,+1 was obtained from your original variable x in the interval xmin,xmax by the linear transformation
x-=2 x-xmax+xmin xmax-xmin
and that you require the derivative to be with respect to the variable x. If the derivative with respect to x- is required, set xmax=1 and xmin=-1.
Values of the derivative can subsequently be computed, from the coefficients obtained, by using E02AKF.
The method employed is that of Chebyshev series (see Chapter 8 of Modern Computing Methods (1961)), modified to obtain the derivative with respect to x. Initially setting a-n+1=a-n=0, the routine forms successively
a-i-1=a-i+1+2 xmax-xmin 2 i ai,  i=n,n-1,…,1.

4 References

Modern Computing Methods (1961) Chebyshev-series NPL Notes on Applied Science 16 (2nd Edition) HMSO

5 Arguments

1:   NP1 – INTEGERInput
On entry: n+1, where n is the degree of the given polynomial p x. Thus NP1 is the number of coefficients in this polynomial.
Constraint: NP1≥1.
2:   XMIN – REAL (KIND=nag_wp)Input
3:   XMAX – REAL (KIND=nag_wp)Input
On entry: the lower and upper end points respectively of the interval xmin,xmax. The Chebyshev series representation is in terms of the normalized variable x-, where
x-=2 x-xmax+xmin xmax-xmin .
Constraint: XMAX>XMIN.
4:   A LA – REAL (KIND=nag_wp) arrayInput
On entry: the Chebyshev coefficients of the polynomial p x. Specifically, element i×IA1 of A must contain the coefficient ai, for i=0,1,…,n. Only these n+1 elements will be accessed.
Unchanged on exit, but see ADIF, below.
5:   IA1 – INTEGERInput
On entry: the index increment of A. Most frequently the Chebyshev coefficients are stored in adjacent elements of A, and IA1 must be set to 1. However, if for example, they are stored in A 1,A 4,A 7,…, then the value of IA1 must be 3. See also Section 9.
Constraint: IA1≥1.
6:   LA – INTEGERInput
On entry: the dimension of the array A as declared in the (sub)program from which E02AHF is called.
Constraint: LA≥1+NP1-1×IA1.
7:   PATM1 – REAL (KIND=nag_wp)Output
On exit: the value of p xmin. If this value is passed to the integration routine E02AJF with the coefficients of q x, then the original polynomial p x is recovered, including its constant coefficient.
8:   ADIF LADIF – REAL (KIND=nag_wp) arrayOutput
On exit: the Chebyshev coefficients of the derived polynomial q x. (The differentiation is with respect to the variable x.) Specifically, element i×IADIF1+1 of ADIF contains the coefficient a-i, for i=0,1,…,n-1. Additionally, element n×IADIF1+1 is set to zero. A call of the routine may have the array name ADIF the same as A, provided that note is taken of the order in which elements are overwritten, when choosing the starting elements and increments IA1 and IADIF1, i.e., the coefficients a 0,a 1,…,a i-1 must be intact after coefficient a-i is stored. In particular, it is possible to overwrite the ai completely by having IA1=IADIF1, and the actual arrays for A and ADIF identical.
9:   IADIF1 – INTEGERInput
On entry: the index increment of ADIF. Most frequently the Chebyshev coefficients are required in adjacent elements of ADIF, and IADIF1 must be set to 1. However, if, for example, they are to be stored in ADIF 1,ADIF 4,ADIF 7,…, then the value of IADIF1 must be 3. See Section 9.
Constraint: IADIF1≥1.
10:   LADIF – INTEGERInput
On entry: the dimension of the array ADIF as declared in the (sub)program from which E02AHF is called.
Constraint: LADIF≥1+NP1-1 ×IADIF1.
11:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, | NP1<1,
or | XMAX≤XMIN,
or | IA1<1,
or | LA≤NP1-1×IA1,
or | IADIF1<1,
or | LADIF≤NP1-1×IADIF1.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

There is always a loss of precision in numerical differentiation, in this case associated with the multiplication by 2 i in the formula quoted in Section 3.

8 Parallelism and Performance

E02AHF is not threaded in any implementation.

9 Further Comments

The time taken is approximately proportional to n+1.
The increments IA1, IADIF1 are included as arguments to give a degree of flexibility which, for example, allows a polynomial in two variables to be differentiated with respect to either variable without rearranging the coefficients.

10 Example

Suppose a polynomial has been computed in Chebyshev series form to fit data over the interval -0.5,2.5. The following program evaluates the first and second derivatives of this polynomial at 4 equally spaced points over the interval. (For the purposes of this example, XMIN, XMAX and the Chebyshev coefficients are simply supplied in DATA statements. Normally a program would first read in or generate data and compute the fitted polynomial.)

10.1 Program Text

Program Text (e02ahfe.f90)

10.2 Program Data

None.

10.3 Program Results

Program Results (e02ahfe.r)

GnuplotProduced by GNUPLOT 4.6 patchlevel 3 0 0.5 1 1.5 2 2.5 3 −0.5 0 0.5 1 1.5 2 2.5 P(x), P'(x), P''(x) x Example Program Evaluation of Chebyshev Polynomial and its Derivatives P(x) P'(x) P''(x) gnuplot_plot_1 gnuplot_plot_2 gnuplot_plot_3
E02 Chapter Contents
E02 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


E02AJF : NAG Library, Mark 26

E02 Chapter Contents
E02 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

E02AJF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

E02AJF determines the coefficients in the Chebyshev series representation of the indefinite integral of a polynomial given in Chebyshev series form.

2 Specification

SUBROUTINE E02AJF ( NP1, XMIN, XMAX, A, IA1, LA, QATM1, AINTC, IAINT1, LAINT, IFAIL)
INTEGER | NP1, IA1, LA, IAINT1, LAINT, IFAIL
REAL (KIND=nag_wp) | XMIN, XMAX, A(LA), QATM1, AINTC(LAINT)

3 Description

E02AJF forms the polynomial which is the indefinite integral of a given polynomial. Both the original polynomial and its integral are represented in Chebyshev series form. If supplied with the coefficients ai, for i=0,1,…,n, of a polynomial p x of degree n, where
p x=12 a 0+a 1T 1 x-+⋯+anTn x-,
the routine returns the coefficients ai′, for i=0,1,…,n+1, of the polynomial q x of degree n+1, where
q x=12 a 0′+a 1′T 1 x-+⋯+a n+1′T n+1 x-,
and
q x=∫p x dx.
Here Tj x- denotes the Chebyshev polynomial of the first kind of degree j with argument x-. It is assumed that the normalized variable x- in the interval -1,+1 was obtained from your original variable x in the interval xmin,xmax by the linear transformation
x-=2 x-xmax+xmin xmax-xmin
and that you require the integral to be with respect to the variable x. If the integral with respect to x- is required, set xmax=1 and xmin=-1.
Values of the integral can subsequently be computed, from the coefficients obtained, by using E02AKF.
The method employed is that of Chebyshev series (see Chapter 8 of Modern Computing Methods (1961)), modified for integrating with respect to x. Initially taking a n+1=a n+2=0, the routine forms successively
ai′=a i-1-a i+1 2 i ×xmax-xmin 2,  i=n+1,n,…,1.
The constant coefficient a 0′ is chosen so that q x is equal to a specified value, QATM1, at the lower end point of the interval on which it is defined, i.e., x-=-1, which corresponds to x=xmin.

4 References

Modern Computing Methods (1961) Chebyshev-series NPL Notes on Applied Science 16 (2nd Edition) HMSO

5 Arguments

1:   NP1 – INTEGERInput
On entry: n+1, where n is the degree of the given polynomial p x. Thus NP1 is the number of coefficients in this polynomial.
Constraint: NP1≥1.
2:   XMIN – REAL (KIND=nag_wp)Input
3:   XMAX – REAL (KIND=nag_wp)Input
On entry: the lower and upper end points respectively of the interval xmin,xmax. The Chebyshev series representation is in terms of the normalized variable x-, where
x-=2 x-xmax+xmin xmax-xmin .
Constraint: XMAX>XMIN.
4:   A LA – REAL (KIND=nag_wp) arrayInput
On entry: the Chebyshev coefficients of the polynomial p x. Specifically, element i×IA1+1 of A must contain the coefficient ai, for i=0,1,…,n. Only these n+1 elements will be accessed.
Unchanged on exit, but see AINTC, below.
5:   IA1 – INTEGERInput
On entry: the index increment of A. Most frequently the Chebyshev coefficients are stored in adjacent elements of A, and IA1 must be set to 1. However, if for example, they are stored in A 1,A 4,A 7,…, then the value of IA1 must be 3. See also Section 9.
Constraint: IA1≥1.
6:   LA – INTEGERInput
On entry: the dimension of the array A as declared in the (sub)program from which E02AJF is called.
Constraint: LA≥1+NP1-1×IA1.
7:   QATM1 – REAL (KIND=nag_wp)Input
On entry: the value that the integrated polynomial is required to have at the lower end point of its interval of definition, i.e., at x-=-1 which corresponds to x=xmin. Thus, QATM1 is a constant of integration and will normally be set to zero by you.
8:   AINTC LAINT – REAL (KIND=nag_wp) arrayOutput
On exit: the Chebyshev coefficients of the integral q x. (The integration is with respect to the variable x, and the constant coefficient is chosen so that q xmin equals QATM1). Specifically, element i×IAINT1+1 of AINTC contains the coefficient ai′, for i=0,1,…,n+1. A call of the routine may have the array name AINTC the same as A, provided that note is taken of the order in which elements are overwritten when choosing starting elements and increments IA1 and IAINT1: i.e., the coefficients, a 0,a 1,…,a i-2 must be intact after coefficient ai′ is stored. In particular it is possible to overwrite the ai entirely by having IA1=IAINT1, and the actual array for A and AINTC identical.
9:   IAINT1 – INTEGERInput
On entry: the index increment of AINTC. Most frequently the Chebyshev coefficients are required in adjacent elements of AINTC, and IAINT1 must be set to 1. However, if, for example, they are to be stored in AINTC 1,AINTC 4,AINTC 7,…, then the value of IAINT1 must be 3. See also Section 9.
Constraint: IAINT1≥1.
10:   LAINT – INTEGERInput
On entry: the dimension of the array AINTC as declared in the (sub)program from which E02AJF is called.
Constraint: LAINT≥1+NP1 ×IAINT1.
11:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, | NP1<1,
or | XMAX≤XMIN,
or | IA1<1,
or | LA≤NP1-1×IA1,
or | IAINT1<1,
or | LAINT≤NP1×IAINT1.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

In general there is a gain in precision in numerical integration, in this case associated with the division by 2 i in the formula quoted in Section 3.

8 Parallelism and Performance

E02AJF is not threaded in any implementation.

9 Further Comments

The time taken is approximately proportional to n+1.
The increments IA1, IAINT1 are included as arguments to give a degree of flexibility which, for example, allows a polynomial in two variables to be integrated with respect to either variable without rearranging the coefficients.

10 Example

Suppose a polynomial has been computed in Chebyshev series form to fit data over the interval -0.5,2.5. The following program evaluates the integral of the polynomial from 0.0 to 2.0. (For the purpose of this example, XMIN, XMAX and the Chebyshev coefficients are simply supplied in DATA statements. Normally a program would read in or generate data and compute the fitted polynomial).

10.1 Program Text

Program Text (e02ajfe.f90)

10.2 Program Data

None.

10.3 Program Results

Program Results (e02ajfe.r)

E02 Chapter Contents
E02 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


E02AKF : NAG Library, Mark 26

E02 Chapter Contents
E02 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

E02AKF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

E02AKF evaluates a polynomial from its Chebyshev series representation, allowing an arbitrary index increment for accessing the array of coefficients.

2 Specification

SUBROUTINE E02AKF ( NP1, XMIN, XMAX, A, IA1, LA, X, RESULT, IFAIL)
INTEGER | NP1, IA1, LA, IFAIL
REAL (KIND=nag_wp) | XMIN, XMAX, A(LA), X, RESULT

3 Description

If supplied with the coefficients ai, for i=0,1,…,n, of a polynomial p x- of degree n, where
p x-=12 a 0+a 1T 1 x-+⋯+anTn x-,
E02AKF returns the value of p x- at a user-specified value of the variable x. Here Tj x- denotes the Chebyshev polynomial of the first kind of degree j with argument x-. It is assumed that the independent variable x- in the interval -1,+1 was obtained from your original variable x in the interval xmin,xmax by the linear transformation
x-=2 x-xmax+xmin xmax-xmin .
The coefficients ai may be supplied in the array A, with any increment between the indices of array elements which contain successive coefficients. This enables the routine to be used in surface fitting and other applications, in which the array might have two or more dimensions.
The method employed is based on the three-term recurrence relation due to Clenshaw (see Clenshaw (1955)), with modifications due to Reinsch and Gentleman (see Gentleman (1969)). For further details of the algorithm and its use see Cox (1973) and Cox and Hayes (1973).

4 References

Clenshaw C W (1955) A note on the summation of Chebyshev series Math. Tables Aids Comput. 9 118–120
Cox M G (1973) A data-fitting package for the non-specialist user NPL Report NAC 40 National Physical Laboratory
Cox M G and Hayes J G (1973) Curve fitting: a guide and suite of algorithms for the non-specialist user NPL Report NAC26 National Physical Laboratory
Gentleman W M (1969) An error analysis of Goertzel's (Watt's) method for computing Fourier coefficients Comput. J. 12 160–165

5 Arguments

1:   NP1 – INTEGERInput
On entry: n+1, where n is the degree of the given polynomial p x-.
Constraint: NP1≥1.
2:   XMIN – REAL (KIND=nag_wp)Input
3:   XMAX – REAL (KIND=nag_wp)Input
On entry: the lower and upper end points respectively of the interval xmin,xmax. The Chebyshev series representation is in terms of the normalized variable x-, where
x-=2 x-xmax+xmin xmax-xmin .
Constraint: XMIN<XMAX.
4:   A LA – REAL (KIND=nag_wp) arrayInput
On entry: the Chebyshev coefficients of the polynomial p x-. Specifically, element i×IA1+1 must contain the coefficient ai, for i=0,1,…,n. Only these n+1 elements will be accessed.
5:   IA1 – INTEGERInput
On entry: the index increment of A. Most frequently, the Chebyshev coefficients are stored in adjacent elements of A, and IA1 must be set to 1. However, if, for example, they are stored in A 1,A 4,A 7,…, then the value of IA1 must be 3.
Constraint: IA1≥1.
6:   LA – INTEGERInput
On entry: the dimension of the array A as declared in the (sub)program from which E02AKF is called.
Constraint: LA≥NP1-1 ×IA1+1.
7:   X – REAL (KIND=nag_wp)Input
On entry: the argument x at which the polynomial is to be evaluated.
Constraint: XMIN≤X≤XMAX.
8:   RESULT – REAL (KIND=nag_wp)Output
On exit: the value of the polynomial p x-.
9:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, | NP1<1,
or | IA1<1,
or | LA≤NP1-1×IA1,
or | XMIN≥XMAX.
IFAIL=2
X does not satisfy the restriction XMIN≤X≤XMAX.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

The rounding errors are such that the computed value of the polynomial is exact for a slightly perturbed set of coefficients ai+δ ai. The ratio of the sum of the absolute values of the δ ai to the sum of the absolute values of the ai is less than a small multiple of n+1×machine precision.

8 Parallelism and Performance

E02AKF is not threaded in any implementation.

9 Further Comments

The time taken is approximately proportional to n+1.

10 Example

Suppose a polynomial has been computed in Chebyshev series form to fit data over the interval -0.5,2.5. The following program evaluates the polynomial at 4 equally spaced points over the interval. (For the purposes of this example, XMIN, XMAX and the Chebyshev coefficients are supplied in DATA statements. Normally a program would first read in or generate data and compute the fitted polynomial.)

10.1 Program Text

Program Text (e02akfe.f90)

10.2 Program Data

None.

10.3 Program Results

Program Results (e02akfe.r)

GnuplotProduced by GNUPLOT 4.6 patchlevel 3 0 0.5 1 1.5 2 2.5 3 −0.5 0 0.5 1 1.5 2 2.5 P(x) x Example Program Evaluation of Chebyshev Representation of Polynomial gnuplot_plot_1
E02 Chapter Contents
E02 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


E02ALF : NAG Library, Mark 26

E02 Chapter Contents
E02 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

E02ALF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

E02ALF calculates a minimax polynomial fit to a set of data points.

2 Specification

SUBROUTINE E02ALF ( N, X, Y, M, A, REF, IFAIL)
INTEGER | N, M, IFAIL
REAL (KIND=nag_wp) | X(N), Y(N), A(M+1), REF

3 Description

Given a set of data points xi,yi, for i=1,2,…,n, E02ALF uses the exchange algorithm to compute an mth-degree polynomial
P x = a 0 + a 1 x + a 2 x 2 + ⋯ + am xm
such that maxi P xi-yi is a minimum.
The routine also returns a number whose absolute value is the final reference deviation (see Section 5). The routine is an adaptation of Boothroyd (1967).

4 References

Boothroyd J B (1967) Algorithm 318 Comm. ACM 10 801
Stieffel E (1959) Numerical methods of Tchebycheff approximation On Numerical Approximation (ed R E Langer) 217–232 University of Wisconsin Press

5 Arguments

1:   N – INTEGERInput
On entry: n, the number of data points.
Constraint: N≥1.
2:   X N – REAL (KIND=nag_wp) arrayInput
On entry: the values of the x coordinates, xi, for i=1,2,…,n.
Constraint: x 1<x 2<…<xn.
3:   Y N – REAL (KIND=nag_wp) arrayInput
On entry: the values of the y coordinates, yi, for i=1,2,…,n.
4:   M – INTEGERInput
On entry: m, where m is the degree of the polynomial to be found.
Constraint: 0≤M<min 100,N-1.
5:   A M+1 – REAL (KIND=nag_wp) arrayOutput
On exit: the coefficients ai of the minimax polynomial, for i=0,1,…,m.
6:   REF – REAL (KIND=nag_wp)Output
On exit: the final reference deviation, i.e., the maximum deviation of the computed polynomial evaluated at xi from the reference values yi, for i=1,2,…,n. REF may return a negative value which indicates that the algorithm started to cycle due to round-off errors.
7:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, N=value.
Constraint: N≥1.
IFAIL=2
On entry, M=value.
Constraint: M<100.
On entry, M=value.
Constraint: M≥0.
On entry, M=value and N=value.
Constraint: M<N-1.
IFAIL=3
On entry, i=value, X i+1=value and X i=value.
Constraint: X i+1>X i.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

This is dependent on the given data points and on the degree of the polynomial. The data points should represent a fairly smooth function which does not contain regions with markedly different behaviours. For large numbers of data points (N>100, say), rounding error will affect the computation regardless of the quality of the data; in this case, relatively small degree polynomials (M≪N) may be used when this is consistent with the required approximation. A limit of 99 is placed on the degree of polynomial since it is known from experiment that a complete loss of accuracy often results from using such high degree polynomials in this form of the algorithm.

8 Parallelism and Performance

E02ALF makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The time taken increases with m.

10 Example

This example calculates a minimax fit with a polynomial of degree 5 to the exponential function evaluated at 21 points over the interval 0,1. It then prints values of the function and the fitted polynomial.

10.1 Program Text

Program Text (e02alfe.f90)

10.2 Program Data

Program Data (e02alfe.d)

10.3 Program Results

Program Results (e02alfe.r)

E02 Chapter Contents
E02 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


E02BAF : NAG Library, Mark 26

E02 Chapter Contents
E02 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

E02BAF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

E02BAF computes a weighted least squares approximation to an arbitrary set of data points by a cubic spline with knots prescribed by you. Cubic spline interpolation can also be carried out.

2 Specification

SUBROUTINE E02BAF ( M, NCAP7, X, Y, W, LAMDA, WORK1, WORK2, C, SS, IFAIL)
INTEGER | M, NCAP7, IFAIL
REAL (KIND=nag_wp) | X(M), Y(M), W(M), LAMDA(NCAP7), WORK1(M), WORK2(4*NCAP7), C(NCAP7), SS

3 Description

E02BAF determines a least squares cubic spline approximation s x to the set of data points xr,yr with weights wr, for r=1,2,…,m. The value of NCAP7=n-+7, where n- is the number of intervals of the spline (one greater than the number of interior knots), and the values of the knots λ 5,λ 6,…,λ n-+3, interior to the data interval, are prescribed by you.
s x has the property that it minimizes θ, the sum of squares of the weighted residuals εr, for r=1,2,…,m, where
εr=wr yr-s xr.
The routine produces this minimizing value of θ and the coefficients c 1,c 2,…,cq, where q=n-+3, in the B-spline representation
s x=∑i=1 q ciNi x.
Here Ni x denotes the normalized B-spline of degree 3 defined upon the knots λi,λ i+1,…,λ i+4.
In order to define the full set of B-splines required, eight additional knots λ 1,λ 2,λ 3,λ 4 and λ n-+4,λ n-+5,λ n-+6,λ n-+7 are inserted automatically by the routine. The first four of these are set equal to the smallest xr and the last four to the largest xr.
The representation of s x in terms of B-splines is the most compact form possible in that only n-+3 coefficients, in addition to the n-+7 knots, fully define s x.
The method employed involves forming and then computing the least squares solution of a set of m linear equations in the coefficients ci, for i=1,2,…,n-+3. The equations are formed using a recurrence relation for B-splines that is unconditionally stable (see Cox (1972) and de Boor (1972)), even for multiple (coincident) knots. The least squares solution is also obtained in a stable manner by using orthogonal transformations, viz. a variant of Givens rotations (see Gentleman (1974) and Gentleman (1973)). This requires only one equation to be stored at a time. Full advantage is taken of the structure of the equations, there being at most four nonzero values of Ni x for any value of x and hence at most four coefficients in each equation.
For further details of the algorithm and its use see Cox (1974), Cox (1975) and Cox and Hayes (1973).
Subsequent evaluation of s x from its B-spline representation may be carried out using E02BBF. If derivatives of s x are also required, E02BCF may be used. E02BDF can be used to compute the definite integral of s x.

4 References

Cox M G (1972) The numerical evaluation of B-splines J. Inst. Math. Appl. 10 134–149
Cox M G (1974) A data-fitting package for the non-specialist user Software for Numerical Mathematics (ed D J Evans) Academic Press
Cox M G (1975) Numerical methods for the interpolation and approximation of data by spline functions PhD Thesis City University, London
Cox M G and Hayes J G (1973) Curve fitting: a guide and suite of algorithms for the non-specialist user NPL Report NAC26 National Physical Laboratory
de Boor C (1972) On calculating with B-splines J. Approx. Theory 6 50–62
Gentleman W M (1973) Least squares computations by Givens transformations without square roots J. Inst. Math. Applic. 12 329–336
Gentleman W M (1974) Algorithm AS 75. Basic procedures for large sparse or weighted linear least squares problems Appl. Statist. 23 448–454
Schoenberg I J and Whitney A (1953) On Polya frequency functions III Trans. Amer. Math. Soc. 74 246–259

5 Arguments

1:   M – INTEGERInput
On entry: the number m of data points.
Constraint: M≥mdist≥4, where mdist is the number of distinct x values in the data.
2:   NCAP7 – INTEGERInput
On entry: n-+7, where n- is the number of intervals of the spline (which is one greater than the number of interior knots, i.e., the knots strictly within the range x 1 to xm) over which the spline is defined.
Constraint: 8≤NCAP7≤mdist+4, where mdist is the number of distinct x values in the data.
3:   X M – REAL (KIND=nag_wp) arrayInput
On entry: the values xr of the independent variable (abscissa), for r=1,2,…,m.
Constraint: x 1≤x 2≤⋯≤xm.
4:   Y M – REAL (KIND=nag_wp) arrayInput
On entry: the values yr of the dependent variable (ordinate), for r=1,2,…,m.
5:   W M – REAL (KIND=nag_wp) arrayInput
On entry: the values wr of the weights, for r=1,2,…,m. For advice on the choice of weights, see the E02 Chapter Introduction.
Constraint: W r>0.0, for r=1,2,…,m.
6:   LAMDA NCAP7 – REAL (KIND=nag_wp) arrayInput/Output
On entry: LAMDA i must be set to the i-4th (interior) knot, λi, for i=5,6,…,n-+3.
Constraint: X 1<LAMDA 5≤LAMDA 6≤⋯≤LAMDA NCAP7-4<X M.
On exit: the input values are unchanged, and LAMDA i, for i=1,2,3,4, NCAP7-3, NCAP7-2, NCAP7-1, NCAP7 contains the additional (exterior) knots introduced by the routine. For advice on the choice of knots, see Section 3.3 in the E02 Chapter Introduction.
7:   WORK1 M – REAL (KIND=nag_wp) arrayWorkspace
8:   WORK2 4×NCAP7 – REAL (KIND=nag_wp) arrayWorkspace
9:   C NCAP7 – REAL (KIND=nag_wp) arrayOutput
On exit: the coefficient ci of the B-spline Ni x, for i=1,2,…,n-+3. The remaining elements of the array are not used.
10:   SS – REAL (KIND=nag_wp)Output
On exit: the residual sum of squares, θ.
11:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
The knots fail to satisfy the condition
X 1<LAMDA 5≤LAMDA 6≤⋯≤LAMDA NCAP7-4<X M.
Thus the knots are not in correct order or are not interior to the data interval.
IFAIL=2
The weights are not all strictly positive.
IFAIL=3
The values of X r, for r=1,2,…,M, are not in nondecreasing order.
IFAIL=4
NCAP7<8 (so the number of interior knots is negative) or NCAP7>mdist+4, where mdist is the number of distinct x values in the data (so there cannot be a unique solution).
IFAIL=5
The conditions specified by Schoenberg and Whitney (1953) fail to hold for at least one subset of the distinct data abscissae. That is, there is no subset of NCAP7-4 strictly increasing values, X R 1, X R 2, …, X R NCAP7-4, among the abscissae such that
  • X R 1<LAMDA 1< X R 5,
  • X R 2<LAMDA 2< X R 6,
  • ⋮
  • X R NCAP7-8<LAMDA NCAP7-8< X R NCAP7-4.
This means that there is no unique solution: there are regions containing too many knots compared with the number of data points.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

The rounding errors committed are such that the computed coefficients are exact for a slightly perturbed set of ordinates yr+δ yr. The ratio of the root-mean-square value for the δ yr to the root-mean-square value of the yr can be expected to be less than a small multiple of κ×m×machine precision, where κ is a condition number for the problem. Values of κ for 20–30 practical datasets all proved to lie between 4.5 and 7.8 (see Cox (1975)). (Note that for these datasets, replacing the coincident end knots at the end points x 1 and xm used in the routine by various choices of non-coincident exterior knots gave values of κ between 16 and 180. Again see Cox (1975) for further details.) In general we would not expect κ to be large unless the choice of knots results in near-violation of the Schoenberg–Whitney conditions.
A cubic spline which adequately fits the data and is free from spurious oscillations is more likely to be obtained if the knots are chosen to be grouped more closely in regions where the function (underlying the data) or its derivatives change more rapidly than elsewhere.

8 Parallelism and Performance

E02BAF is not threaded in any implementation.

9 Further Comments

The time taken is approximately C×2 m+n-+7 seconds, where C is a machine-dependent constant.
Multiple knots are permitted as long as their multiplicity does not exceed 4, i.e., the complete set of knots must satisfy λi<λ i+4, for i=1,2,…,n-+3, (see Section 6). At a knot of multiplicity one (the usual case), s x and its first two derivatives are continuous. At a knot of multiplicity two, s x and its first derivative are continuous. At a knot of multiplicity three, s x is continuous, and at a knot of multiplicity four, s x is generally discontinuous.
The routine can be used efficiently for cubic spline interpolation, i.e., if m=n-+3. The abscissae must then of course satisfy x 1<x 2<⋯<xm. Recommended values for the knots in this case are λi=x i-2, for i=5,6,…,n-+3.

10 Example

Determine a weighted least squares cubic spline approximation with five intervals (four interior knots) to a set of 14 given data points. Tabulate the data and the corresponding values of the approximating spline, together with the residual errors, and also the values of the approximating spline at points half-way between each pair of adjacent data points.
The example program is written in a general form that will enable a cubic spline approximation with n- intervals (n--1 interior knots) to be obtained to m data points, with arbitrary positive weights, and the approximation to be tabulated. Note that E02BBF is used to evaluate the approximating spline. The program is self-starting in that any number of datasets can be supplied.

10.1 Program Text

Program Text (e02bafe.f90)

10.2 Program Data

Program Data (e02bafe.d)

10.3 Program Results

Program Results (e02bafe.r)

GnuplotProduced by GNUPLOT 4.6 patchlevel 3 −4 −2 0 2 4 6 8 10 0 2 4 6 8 10 12 −0.06 −0.04 −0.02 0 0.02 0.04 0.06 0.08 0.1 0.12 Cubic Spline Approximation Residual at Data Points x Example Program Weighted Least-squares Cubic Spline Approximation to a Set of 14 Data Points cubic spline fit residual gnuplot_plot_1 data points gnuplot_plot_2 gnuplot_plot_3
E02 Chapter Contents
E02 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


E02BBF : NAG Library, Mark 26

E02 Chapter Contents
E02 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

E02BBF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

E02BBF evaluates a cubic spline from its B-spline representation.

2 Specification

SUBROUTINE E02BBF ( NCAP7, LAMDA, C, X, S, IFAIL)
INTEGER | NCAP7, IFAIL
REAL (KIND=nag_wp) | LAMDA(NCAP7), C(NCAP7), X, S

3 Description

E02BBF evaluates the cubic spline s x at a prescribed argument x from its augmented knot set λi, for i=1,2,…,n+7, (see E02BAF) and from the coefficients ci, for i=1,2,…,qin its B-spline representation
s x=∑i=1 q ciNi x.
Here q=n-+3, where n- is the number of intervals of the spline, and Ni x denotes the normalized B-spline of degree 3 defined upon the knots λi,λ i+1,…,λ i+4. The prescribed argument x must satisfy λ 4≤x≤λ n-+4.
It is assumed that λj≥λ j-1, for j=2,3,…,n-+7, and λ n-+4>λ 4.
If x is a point at which 4 knots coincide, s x is discontinuous at x; in this case, S contains the value defined as x is approached from the right.
The method employed is that of evaluation by taking convex combinations due to de Boor (1972). For further details of the algorithm and its use see Cox (1972) and Cox and Hayes (1973).
It is expected that a common use of E02BBF will be the evaluation of the cubic spline approximations produced by E02BAF. A generalization of E02BBF which also forms the derivative of s x is E02BCF. E02BCF takes about 50% longer than E02BBF.

4 References

Cox M G (1972) The numerical evaluation of B-splines J. Inst. Math. Appl. 10 134–149
Cox M G (1978) The numerical evaluation of a spline from its B-spline representation J. Inst. Math. Appl. 21 135–143
Cox M G and Hayes J G (1973) Curve fitting: a guide and suite of algorithms for the non-specialist user NPL Report NAC26 National Physical Laboratory
de Boor C (1972) On calculating with B-splines J. Approx. Theory 6 50–62

5 Arguments

1:   NCAP7 – INTEGERInput
On entry: n-+7, where n- is the number of intervals (one greater than the number of interior knots, i.e., the knots strictly within the range λ 4 to λ n-+4) over which the spline is defined.
Constraint: NCAP7≥8.
2:   LAMDA NCAP7 – REAL (KIND=nag_wp) arrayInput
On entry: LAMDA j must be set to the value of the jth member of the complete set of knots, λj, for j=1,2,…,n-+7.
Constraint: the LAMDA j must be in nondecreasing order with LAMDA NCAP7-3> LAMDA 4.
3:   C NCAP7 – REAL (KIND=nag_wp) arrayInput
On entry: the coefficient ci of the B-spline Ni x, for i=1,2,…,n-+3. The remaining elements of the array are not referenced.
4:   X – REAL (KIND=nag_wp)Input
On entry: the argument x at which the cubic spline is to be evaluated.
Constraint: LAMDA 4≤X≤LAMDA NCAP7-3.
5:   S – REAL (KIND=nag_wp)Output
On exit: the value of the spline, s x.
6:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
The argument X does not satisfy LAMDA 4≤X≤LAMDA NCAP7-3.
In this case the value of S is set arbitrarily to zero.
IFAIL=2
NCAP7<8, i.e., the number of interior knots is negative.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

The computed value of s x has negligible error in most practical situations. Specifically, this value has an absolute error bounded in modulus by 18×cmax×machine precision, where cmax is the largest in modulus of cj,c j+1,c j+2 and c j+3, and j is an integer such that λ j+3≤x≤λ j+4. If cj,c j+1,c j+2 and c j+3 are all of the same sign, then the computed value of s x has a relative error not exceeding 20×machine precision in modulus. For further details see Cox (1978).

8 Parallelism and Performance

E02BBF is not threaded in any implementation.

9 Further Comments

The time taken is approximately C×1+0.1×log n-+7 seconds, where C is a machine-dependent constant.
Note: the routine does not test all the conditions on the knots given in the description of LAMDA in Section 5, since to do this would result in a computation time approximately linear in n-+7 instead of log n-+7. All the conditions are tested in E02BAF, however.

10 Example

Evaluate at nine equally-spaced points in the interval 1.0≤x≤9.0 the cubic spline with (augmented) knots 1.0, 1.0, 1.0, 1.0, 3.0, 6.0, 8.0, 9.0, 9.0, 9.0, 9.0 and normalized cubic B-spline coefficients 1.0, 2.0, 4.0, 7.0, 6.0, 4.0, 3.0.
The example program is written in a general form that will enable a cubic spline with n- intervals, in its normalized cubic B-spline form, to be evaluated at m equally-spaced points in the interval LAMDA 4≤x≤LAMDA n-+4. The program is self-starting in that any number of datasets may be supplied.

10.1 Program Text

Program Text (e02bbfe.f90)

10.2 Program Data

Program Data (e02bbfe.d)

10.3 Program Results

Program Results (e02bbfe.r)

GnuplotProduced by GNUPLOT 4.6 patchlevel 3 0 1 2 3 4 5 6 7 1 2 3 4 5 6 7 8 9 Cubic Spline x Example Program Evaluation of Cubic Spline Representation gnuplot_plot_1 gnuplot_plot_2 points of evaluation
E02 Chapter Contents
E02 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


E02BCF : NAG Library, Mark 26

E02 Chapter Contents
E02 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

E02BCF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

E02BCF evaluates a cubic spline and its first three derivatives from its B-spline representation.

2 Specification

SUBROUTINE E02BCF ( NCAP7, LAMDA, C, X, LEFT, S, IFAIL)
INTEGER | NCAP7, LEFT, IFAIL
REAL (KIND=nag_wp) | LAMDA(NCAP7), C(NCAP7), X, S(4)

3 Description

E02BCF evaluates the cubic spline s x and its first three derivatives at a prescribed argument x. It is assumed that s x is represented in terms of its B-spline coefficients ci, for i=1,2,…,n-+3 and (augmented) ordered knot set λi, for i=1,2,…,n-+7, (see E02BAF), i.e.,
s x = ∑ i=1 q ci Ni x .
Here q=n-+3, n- is the number of intervals of the spline and Ni x denotes the normalized B-spline of degree 3 (order 4) defined upon the knots λi,λ i+1,…,λ i+4. The prescribed argument x must satisfy
λ 4 ≤ x ≤ λ n-+4 .
At a simple knot λi (i.e., one satisfying λ i-1<λi<λ i+1), the third derivative of the spline is in general discontinuous. At a multiple knot (i.e., two or more knots with the same value), lower derivatives, and even the spline itself, may be discontinuous. Specifically, at a point x=u where (exactly) r knots coincide (such a point is termed a knot of multiplicity r), the values of the derivatives of order 4-j, for j=1,2,…,r, are in general discontinuous. (Here 1≤r≤4; r>4 is not meaningful.) You must specify whether the value at such a point is required to be the left- or right-hand derivative.
The method employed is based upon:
(i) | carrying out a binary search for the knot interval containing the argument x (see Cox (1978)),
(ii) | evaluating the nonzero B-splines of orders 1, 2, 3 and 4 by recurrence (see Cox (1972) and Cox (1978)),
(iii) | computing all derivatives of the B-splines of order 4 by applying a second recurrence to these computed B-spline values (see de Boor (1972)),
(iv) | multiplying the fourth-order B-spline values and their derivative by the appropriate B-spline coefficients, and summing, to yield the values of s x and its derivatives.
E02BCF can be used to compute the values and derivatives of cubic spline fits and interpolants produced by E02BAF.
If only values and not derivatives are required, E02BBF may be used instead of E02BCF, which takes about 50% longer than E02BBF.

4 References

Cox M G (1972) The numerical evaluation of B-splines J. Inst. Math. Appl. 10 134–149
Cox M G (1978) The numerical evaluation of a spline from its B-spline representation J. Inst. Math. Appl. 21 135–143
de Boor C (1972) On calculating with B-splines J. Approx. Theory 6 50–62

5 Arguments

1:   NCAP7 – INTEGERInput
On entry: n-+7, where n- is the number of intervals of the spline (which is one greater than the number of interior knots, i.e., the knots strictly within the range λ 4 to λ n-+4 over which the spline is defined).
Constraint: NCAP7≥8.
2:   LAMDA NCAP7 – REAL (KIND=nag_wp) arrayInput
On entry: LAMDA j must be set to the value of the jth member of the complete set of knots, λj, for j=1,2,…,n-+7.
Constraint: the LAMDA j must be in nondecreasing order with LAMDA NCAP7-3>LAMDA 4.
3:   C NCAP7 – REAL (KIND=nag_wp) arrayInput
On entry: the coefficient ci of the B-spline Ni x, for i=1,2,…,n-+3. The remaining elements of the array are not referenced.
4:   X – REAL (KIND=nag_wp)Input
On entry: the argument x at which the cubic spline and its derivatives are to be evaluated.
Constraint: LAMDA 4≤X≤LAMDA NCAP7-3.
5:   LEFT – INTEGERInput
On entry: specifies whether left- or right-hand values of the spline and its derivatives are to be computed (see Section 3). Left- or right-hand values are formed according to whether LEFT is equal or not equal to 1.
If x does not coincide with a knot, the value of LEFT is immaterial.
If x=LAMDA 4, right-hand values are computed.
If x=LAMDA NCAP7-3, left-hand values are formed, regardless of the value of LEFT.
6:   S 4 – REAL (KIND=nag_wp) arrayOutput
On exit: S j contains the value of the j-1th derivative of the spline at the argument x, for j=1,2,3,4. Note that S 1 contains the value of the spline.
7:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
NCAP7<8, i.e., the number of intervals is not positive.
IFAIL=2
Either LAMDA 4≥LAMDA NCAP7-3, i.e., the range over which s x is defined is null or negative in length, or X is an invalid argument, i.e., X<LAMDA 4 or X>LAMDA NCAP7-3.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

The computed value of s x has negligible error in most practical situations. Specifically, this value has an absolute error bounded in modulus by 18×cmax×machine precision, where cmax is the largest in modulus of cj,c j+1,c j+2 and c j+3, and j is an integer such that λ j+3≤x≤λ j+4. If cj,c j+1,c j+2 and c j+3 are all of the same sign, then the computed value of s x has relative error bounded by 20×machine precision. For full details see Cox (1978).
No complete error analysis is available for the computation of the derivatives of s x. However, for most practical purposes the absolute errors in the computed derivatives should be small.

8 Parallelism and Performance

E02BCF is not threaded in any implementation.

9 Further Comments

The time taken is approximately linear in log n-+7.
Note: the routine does not test all the conditions on the knots given in the description of LAMDA in Section 5, since to do this would result in a computation time approximately linear in n-+7 instead of log n-+7. All the conditions are tested in E02BAF, however.

10 Example

Compute, at the 7 arguments x=0, 1, 2, 3, 4, 5, 6, the left- and right-hand values and first 3 derivatives of the cubic spline defined over the interval 0≤x≤6 having the 6 interior knots x=1, 3, 3, 3, 4, 4, the 8 additional knots 0, 0, 0, 0, 6, 6, 6, 6, and the 10 B-spline coefficients 10, 12, 13, 15, 22, 26, 24, 18, 14, 12.
The input data items (using the notation of Section 5) comprise the following values in the order indicated:
n- | m
LAMDA j, | for j=1,2,…,NCAP7
C j, | for j=1,2,…,NCAP7-4
X i, | for i=1,2,…,m
This example program is written in a general form that will enable the values and derivatives of a cubic spline having an arbitrary number of knots to be evaluated at a set of arbitrary points. Any number of datasets may be supplied. The only changes required to the program relate to the dimensions of the arrays LAMDA and C.

10.1 Program Text

Program Text (e02bcfe.f90)

10.2 Program Data

Program Data (e02bcfe.d)

10.3 Program Results

Program Results (e02bcfe.r)

GnuplotProduced by GNUPLOT 4.6 patchlevel 3 −40 −30 −20 −10 0 10 20 30 40 0 1 2 3 4 5 6 x Example Program Cubic spline and its first three derivatives gnuplot_plot_1 Spline gnuplot_plot_2 1st Derivative (left) gnuplot_plot_3 2nd Derivative (left) gnuplot_plot_4 3rd Derivative (left)
E02 Chapter Contents
E02 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


E02BDF : NAG Library, Mark 26

E02 Chapter Contents
E02 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

E02BDF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

E02BDF computes the definite integral of a cubic spline from its B-spline representation.

2 Specification

SUBROUTINE E02BDF ( NCAP7, LAMDA, C, DINT, IFAIL)
INTEGER | NCAP7, IFAIL
REAL (KIND=nag_wp) | LAMDA(NCAP7), C(NCAP7), DINT

3 Description

E02BDF computes the definite integral of the cubic spline s x between the limits x=a and x=b, where a and b are respectively the lower and upper limits of the range over which s x is defined. It is assumed that s x is represented in terms of its B-spline coefficients ci, for i=1,2,…,n-+3 and (augmented) ordered knot set λi, for i=1,2,…,n-+7, with λi=a, for i=1,2,3,4 and λi=b, for i=n-+4,…,n-+7, (see E02BAF), i.e.,
s x=∑i=1 q ciNi x.
Here q=n-+3, n- is the number of intervals of the spline and Ni x denotes the normalized B-spline of degree 3 (order 4) defined upon the knots λi,λ i+1,…,λ i+4.
The method employed uses the formula given in Section 3 of Cox (1975).
E02BDF can be used to determine the definite integrals of cubic spline fits and interpolants produced by E02BAF.

4 References

Cox M G (1975) An algorithm for spline interpolation J. Inst. Math. Appl. 15 95–108

5 Arguments

1:   NCAP7 – INTEGERInput
On entry: n-+7, where n- is the number of intervals of the spline (which is one greater than the number of interior knots, i.e., the knots strictly within the range a to b) over which the spline is defined.
Constraint: NCAP7≥8.
2:   LAMDA NCAP7 – REAL (KIND=nag_wp) arrayInput
On entry: LAMDA j must be set to the value of the jth member of the complete set of knots, λj, for j=1,2,…,n-+7.
Constraint: the LAMDA j must be in nondecreasing order with LAMDA NCAP7-3> LAMDA 4 and satisfy LAMDA 1=LAMDA 2=LAMDA 3=LAMDA 4 and LAMDA NCAP7-3=LAMDA NCAP7-2= LAMDA NCAP7-1=LAMDA NCAP7.
3:   C NCAP7 – REAL (KIND=nag_wp) arrayInput
On entry: the coefficient ci of the B-spline Ni x, for i=1,2,…,n-+3. The remaining elements of the array are not referenced.
4:   DINT – REAL (KIND=nag_wp)Output
On exit: the value of the definite integral of s x between the limits x=a and x=b, where a=λ 4 and b=λ n-+4.
5:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
NCAP7<8, i.e., the number of intervals is not positive.
IFAIL=2
At least one of the following restrictions on the knots is violated:
  • LAMDA NCAP7-3>LAMDA 4,
  • LAMDA j≥LAMDA j-1,
for j=2,3,…,NCAP7, with equality in the cases j=2,3,4,NCAP7-2,NCAP7-1, and NCAP7.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

The rounding errors are such that the computed value of the integral is exact for a slightly perturbed set of B-spline coefficients ci differing in a relative sense from those supplied by no more than 2.2×n-+3×machine precision.

8 Parallelism and Performance

E02BDF is not threaded in any implementation.

9 Further Comments

The time taken is approximately proportional to n-+7.

10 Example

This example determines the definite integral over the interval 0≤x≤6 of a cubic spline having 6 interior knots at the positions λ=1, 3, 3, 3, 4, 4, the 8 additional knots 0, 0, 0, 0, 6, 6, 6, 6, and the 10 B-spline coefficients 10, 12, 13, 15, 22, 26, 24, 18, 14, 12.
The input data items (using the notation of Section 5) comprise the following values in the order indicated:
n- |
LAMDA j, | for j=1,2,…,NCAP7
C j, | for j=1,2,…,NCAP7-3

10.1 Program Text

Program Text (e02bdfe.f90)

10.2 Program Data

Program Data (e02bdfe.d)

10.3 Program Results

Program Results (e02bdfe.r)

E02 Chapter Contents
E02 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


E02BEF : NAG Library, Mark 26

E02 Chapter Contents
E02 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

E02BEF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
▸▿ 9 Further Comments
9.1 Timing
9.2 Choice of S
9.3 Outline of Method Used
9.4 Evaluation of Computed Spline
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

E02BEF computes a cubic spline approximation to an arbitrary set of data points. The knots of the spline are located automatically, but a single argument must be specified to control the trade-off between closeness of fit and smoothness of fit.

2 Specification

SUBROUTINE E02BEF ( START, M, X, Y, W, S, NEST, N, LAMDA, C, FP, WRK, LWRK, IWRK, IFAIL)
INTEGER | M, NEST, N, LWRK, IWRK(NEST), IFAIL
REAL (KIND=nag_wp) | X(M), Y(M), W(M), S, LAMDA(NEST), C(NEST), FP, WRK(LWRK)
CHARACTER(1) | START

3 Description

E02BEF determines a smooth cubic spline approximation s x to the set of data points xr,yr, with weights wr, for r=1,2,…,m.
The spline is given in the B-spline representation
s x=∑i=1 n-4 ciNi x, (1)
where Ni x denotes the normalized cubic B-spline defined upon the knots λi,λ i+1,…,λ i+4.
The total number n of these knots and their values λ 1,…,λn are chosen automatically by the routine. The knots λ 5,…,λ n-4 are the interior knots; they divide the approximation interval x 1,xm into n-7 sub-intervals. The coefficients c 1,c 2,…,c n-4 are then determined as the solution of the following constrained minimization problem:
minimize
η=∑i=5 n-4 δi 2 (2)
subject to the constraint
θ=∑r=1 m εr 2≤S, (3)
where | δi | stands for the discontinuity jump in the third order derivative of s x at the interior knot λi,
 | εr | denotes the weighted residual wr yr-s xr,
and | S | is a non-negative number to be specified by you.
The quantity η can be seen as a measure of the (lack of) smoothness of s x, while closeness of fit is measured through θ. By means of the argument S , ‘the smoothing factor’, you can then control the balance between these two (usually conflicting) properties. If S is too large, the spline will be too smooth and signal will be lost (underfit); if S is too small, the spline will pick up too much noise (overfit). In the extreme cases the routine will return an interpolating spline θ=0 if S is set to zero, and the weighted least squares cubic polynomial η=0 if S is set very large. Experimenting with S values between these two extremes should result in a good compromise. (See Section 9.2 for advice on choice of S .)
The method employed is outlined in Section 9.3 and fully described in Dierckx (1975), Dierckx (1981) and Dierckx (1982). It involves an adaptive strategy for locating the knots of the cubic spline (depending on the function underlying the data and on the value of S ), and an iterative method for solving the constrained minimization problem once the knots have been determined.
Values of the computed spline, or of its derivatives or definite integral, can subsequently be computed by calling E02BBF, E02BCF or E02BDF, as described in Section 9.4.

4 References

Dierckx P (1975) An algorithm for smoothing, differentiating and integration of experimental data using spline functions J. Comput. Appl. Math. 1 165–184
Dierckx P (1981) An improved algorithm for curve fitting with spline functions Report TW54 Department of Computer Science, Katholieke Univerciteit Leuven
Dierckx P (1982) A fast algorithm for smoothing data on a rectangular grid while using spline functions SIAM J. Numer. Anal. 19 1286–1304
Reinsch C H (1967) Smoothing by spline functions Numer. Math. 10 177–183

5 Arguments

1:   START – CHARACTER(1)Input
On entry: must be set to 'C' or 'W'.
START='C'
The routine will build up the knot set starting with no interior knots. No values need be assigned to the arguments N, LAMDA, WRK or IWRK.
START='W'
The routine will restart the knot-placing strategy using the knots found in a previous call of the routine. In this case, the arguments N, LAMDA, WRK, and IWRK must be unchanged from that previous call. This warm start can save much time in searching for a satisfactory value of S .
Constraint: START='C' or 'W'.
2:   M – INTEGERInput
On entry: m , the number of data points.
Constraint: M≥4.
3:   X M – REAL (KIND=nag_wp) arrayInput
On entry: the values xr of the independent variable (abscissa) x , for r=1,2,…,m.
Constraint: x 1<x 2<⋯<xm.
4:   Y M – REAL (KIND=nag_wp) arrayInput
On entry: the values yr of the dependent variable (ordinate) y , for r=1,2,…,m.
5:   W M – REAL (KIND=nag_wp) arrayInput
On entry: the values wr of the weights, for r=1,2,…,m. For advice on the choice of weights, see Section 2.1.2 in the E02 Chapter Introduction.
Constraint: W r>0.0, for r=1,2,…,m.
6:   S – REAL (KIND=nag_wp)Input
On entry: the smoothing factor, S .
If S=0.0, the routine returns an interpolating spline.
If S is smaller than machine precision, it is assumed equal to zero.
For advice on the choice of S, see Sections 3 and 9.2.
Constraint: S≥0.0.
7:   NEST – INTEGERInput
On entry: an overestimate for the number, n, of knots required.
Constraint: NEST≥8. In most practical situations, NEST=M/2 is sufficient. NEST never needs to be larger than M+4, the number of knots needed for interpolation S=0.0.
8:   N – INTEGERInput/Output
On entry: if the warm start option is used, the value of N must be left unchanged from the previous call.
On exit: the total number, n , of knots of the computed spline.
9:   LAMDA NEST – REAL (KIND=nag_wp) arrayInput/Output
On entry: if the warm start option is used, the values LAMDA 1,LAMDA 2,…,LAMDA N must be left unchanged from the previous call.
On exit: the knots of the spline, i.e., the positions of the interior knots LAMDA 5, LAMDA 6,…,LAMDA N-4 as well as the positions of the additional knots
LAMDA 1=LAMDA 2=LAMDA 3=LAMDA 4=x 1
and
LAMDA N-3=LAMDA N-2=LAMDA N-1=LAMDA N =xm
needed for the B-spline representation.
10:   C NEST – REAL (KIND=nag_wp) arrayOutput
On exit: the coefficient ci of the B-spline Ni x in the spline approximation s x, for i=1,2,…,n-4.
11:   FP – REAL (KIND=nag_wp)Output
On exit: the sum of the squared weighted residuals, θ, of the computed spline approximation. If FP=0.0, this is an interpolating spline. FP should equal S within a relative tolerance of 0.001 unless n=8 when the spline has no interior knots and so is simply a cubic polynomial. For knots to be inserted, S must be set to a value below the value of FP produced in this case.
12:   WRK LWRK – REAL (KIND=nag_wp) arrayCommunication Array
If the warm start option is used on entry, the values WRK 1,…,WRK n must be left unchanged from the previous call.
13:   LWRK – INTEGERInput
On entry: the dimension of the array WRK as declared in the (sub)program from which E02BEF is called.
Constraint: LWRK≥4×M+16×NEST+41.
14:   IWRK NEST – INTEGER arrayCommunication Array
If the warm start option is used, on entry, the values IWRK 1,…,IWRK n must be left unchanged from the previous call.
This array is used as workspace.
15:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, | START≠'C' or 'W',
or | M<4,
or | S<0.0,
or | S=0.0 and NEST<M+4,
or | NEST<8,
or | LWRK<4×M+16×NEST+41.
IFAIL=2
The weights are not all strictly positive.
IFAIL=3
The values of X r, for r=1,2,…,M, are not in strictly increasing order.
IFAIL=4
The number of knots required is greater than NEST. Try increasing NEST and, if necessary, supplying larger arrays for the arguments LAMDA, C, WRK and IWRK. However, if NEST is already large, say NEST>M/2, then this error exit may indicate that S is too small.
IFAIL=5
The iterative process used to compute the coefficients of the approximating spline has failed to converge. This error exit may occur if S has been set very small. If the error persists with increased S, contact NAG.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.
If IFAIL=4 or 5, a spline approximation is returned, but it fails to satisfy the fitting criterion (see (2) and (3)) – perhaps by only a small amount, however.

7 Accuracy

On successful exit, the approximation returned is such that its weighted sum of squared residuals θ (as in (3)) is equal to the smoothing factor S , up to a specified relative tolerance of 0.001 – except that if n=8, θ may be significantly less than S : in this case the computed spline is simply a weighted least squares polynomial approximation of degree 3, i.e., a spline with no interior knots.

8 Parallelism and Performance

E02BEF makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

9.1 Timing

The time taken for a call of E02BEF depends on the complexity of the shape of the data, the value of the smoothing factor S , and the number of data points. If E02BEF is to be called for different values of S , much time can be saved by setting START='W' after the first call.

9.2 Choice of S

If the weights have been correctly chosen (see Section 2.1.2 in the E02 Chapter Introduction), the standard deviation of wryr would be the same for all r , equal to σ, say. In this case, choosing the smoothing factor S in the range σ 2 m±2 m, as suggested by Reinsch (1967), is likely to give a good start in the search for a satisfactory value. Otherwise, experimenting with different values of S will be required from the start, taking account of the remarks in Section 3.
In that case, in view of computation time and memory requirements, it is recommended to start with a very large value for S and so determine the least squares cubic polynomial; the value returned in FP, call it θ 0, gives an upper bound for S . Then progressively decrease the value of S to obtain closer fits – say by a factor of 10 in the beginning, i.e., S=θ 0/10, S=θ 0/100, and so on, and more carefully as the approximation shows more details.
The number of knots of the spline returned, and their location, generally depend on the value of S and on the behaviour of the function underlying the data. However, if E02BEF is called with START='W', the knots returned may also depend on the smoothing factors of the previous calls. Therefore if, after a number of trials with different values of S and START='W', a fit can finally be accepted as satisfactory, it may be worthwhile to call E02BEF once more with the selected value for S but now using START='C'. Often, E02BEF then returns an approximation with the same quality of fit but with fewer knots, which is therefore better if data reduction is also important.

9.3 Outline of Method Used

If S=0, the requisite number of knots is known in advance, i.e., n=m+4; the interior knots are located immediately as λi=x i-2, for i=5,6,…,n-4. The corresponding least squares spline (see E02BAF) is then an interpolating spline and therefore a solution of the problem.
If S>0, a suitable knot set is built up in stages (starting with no interior knots in the case of a cold start but with the knot set found in a previous call if a warm start is chosen). At each stage, a spline is fitted to the data by least squares (see E02BAF) and θ, the weighted sum of squares of residuals, is computed. If θ>S , new knots are added to the knot set to reduce θ at the next stage. The new knots are located in intervals where the fit is particularly poor, their number depending on the value of S and on the progress made so far in reducing θ. Sooner or later, we find that θ≤S and at that point the knot set is accepted. The routine then goes on to compute the (unique) spline which has this knot set and which satisfies the full fitting criterion specified by (2) and (3). The theoretical solution has θ=S . The routine computes the spline by an iterative scheme which is ended when θ=S within a relative tolerance of 0.001. The main part of each iteration consists of a linear least squares computation of special form, done in a similarly stable and efficient manner as in E02BAF.
An exception occurs when the routine finds at the start that, even with no interior knots n=8, the least squares spline already has its weighted sum of squares of residuals ≤S . In this case, since this spline (which is simply a cubic polynomial) also has an optimal value for the smoothness measure η, namely zero, it is returned at once as the (trivial) solution. It will usually mean that S has been chosen too large.
For further details of the algorithm and its use, see Dierckx (1981).

9.4 Evaluation of Computed Spline

The value of the computed spline at a given value X may be obtained in the real variable S by the call:
CALL E02BBF(N,LAMDA,C,X,S,IFAIL)
where N, LAMDA and C are the output arguments of E02BEF.
The values of the spline and its first three derivatives at a given value X may be obtained in the real array S of dimension at least 4 by the call:
CALL E02BCF(N,LAMDA,C,X,LEFT,S,IFAIL)
where if LEFT=1, left-hand derivatives are computed and if LEFT≠1, right-hand derivatives are calculated. The value of LEFT is only relevant if X is an interior knot (see E02BCF).
The value of the definite integral of the spline over the interval X 1 to X M can be obtained in the real variable DINT by the call:
CALL E02BDF(N,LAMDA,C,DINT,IFAIL)
(see E02BDF).

10 Example

This example reads in a set of data values, followed by a set of values of S . For each value of S it calls E02BEF to compute a spline approximation, and prints the values of the knots and the B-spline coefficients ci.
The program includes code to evaluate the computed splines, by calls to E02BBF, at the points xr and at points mid-way between them. These values are not printed out, however; instead the results are illustrated by plots of the computed splines, together with the data points (indicated by ×) and the positions of the knots (indicated by vertical lines): the effect of decreasing S can be clearly seen.

10.1 Program Text

Program Text (e02befe.f90)

10.2 Program Data

Program Data (e02befe.d)

10.3 Program Results

Program Results (e02befe.r)

GnuplotProduced by GNUPLOT 4.6 patchlevel 3 −2 0 2 4 6 8 0 1 2 3 4 5 6 7 8 B-spline x Example Program Calculation and Evaluation of B-splines Representation Smoothing Factor S=1.0 gnuplot_plot_1 B-spline gnuplot_plot_2 gnuplot_plot_3 data points
GnuplotProduced by GNUPLOT 4.6 patchlevel 3 −2 0 2 4 6 8 0 1 2 3 4 5 6 7 8 B-spline x Smoothing Factor S=0.5 gnuplot_plot_1 B-spline gnuplot_plot_2 gnuplot_plot_3 data points
GnuplotProduced by GNUPLOT 4.6 patchlevel 3 −2 0 2 4 6 8 0 1 2 3 4 5 6 7 8 B-spline x Smoothing Factor S=0.1 gnuplot_plot_1 B-spline gnuplot_plot_2 gnuplot_plot_3 data points
E02 Chapter Contents
E02 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


E02BFF : NAG Library, Mark 26

E02 Chapter Contents
E02 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

E02BFF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

E02BFF evaluates a cubic spline and up to its first three derivatives from its B-spline representation at a vector of points. E02BFF can be used to compute the values and derivatives of cubic spline fits and interpolants produced by reference to E01BAF, E02BAF and E02BEF.

2 Specification

SUBROUTINE E02BFF ( START, NCAP7, LAMDA, C, DERIV, XORD, X, IXLOC, NX, S, LDS, IWRK, LIWRK, IFAIL)
INTEGER | START, NCAP7, DERIV, XORD, IXLOC(NX), NX, LDS, IWRK(LIWRK), LIWRK, IFAIL
REAL (KIND=nag_wp) | LAMDA(NCAP7), C(NCAP7), X(NX), S(LDS,*)

3 Description

E02BFF evaluates the cubic spline s x and optionally derivatives up to order 3 for a vector of points xj, for j=1,2,…,nx. It is assumed that s x is represented in terms of its B-spline coefficients ci, for i=1,2,…,n-+3, and (augmented) ordered knot set λi, for i=1,2,…,n-+7, (see E02BAF and E02BEF), i.e.,
s x = ∑ i=1 q ci Ni x .
Here q=n-+3, n- is the number of intervals of the spline and Ni x denotes the normalized B-spline of degree 3 (order 4) defined upon the knots λi,λ i+1,…,λ i+4. The knots λ 5,λ 6,…,λ n-+3 are the interior knots. The remaining knots, λ 1, λ 2, λ 3, λ 4 and λ n-+4, λ n-+5, λ n-+6, λ n+7- are the exterior knots. The knots λ 4 and λ n-+4 are the boundaries of the spline.
Only abscissae satisfying,
λ 4 ≤ xj ≤ λ n-+4 ,
will be evaluated. At a simple knot λi (i.e., one satisfying λ i-1<λi<λ i+1), the third derivative of the spline is, in general, discontinuous. At a multiple knot (i.e., two or more knots with the same value), lower derivatives, and even the spline itself, may be discontinuous. Specifically, at a point x=u where (exactly) r knots coincide (such a point is termed a knot of multiplicity r), the values of the derivatives of order 4-j, for j=1,2,…,r, are, in general, discontinuous. (Here 1≤r≤4; r>4 is not meaningful.) The maximum order of the derivatives to be evaluated Dord, and the left- or right-handedness of the computation when an abscissa corresponds exactly to an interior knot, are determined by the value of DERIV.
Each abscissa (point at which the spline is to be evaluated) xj contained in X has an associated enclosing interval number, ixlocj either supplied or returned in IXLOC (see argument START). A simple call to E02BFF would set START=0 and the contents of IXLOC need never be set nor referenced, and the following description on modes of operation can be ignored. However, where efficiency is an important consideration, the following description will help to choose the appropriate mode of operation.
The interval numbers are used to determine which B-splines must be evaluated for a given abscissa, and are defined as
ixlocj = ≤0 xj < λ 1 4 λ 4 = xj k λk < xj < λ k+1 k λ 4 < λk = xj left derivatives k xj = λ k+1 < λ n-+4 right derivatives or no derivatives n-+4 λ n-+4 = xj >n-+7 xj > λ n-+7 (1)
The algorithm has two modes of vectorization, termed here sorted and unsorted, which are selectable by the argument START.
Furthermore, if the supplied abscissae are sufficiently ordered, as indicated by the argument XORD, the algorithm will take advantage of significantly faster methods for the determination of both the interval numbers and the subsequent spline evaluations.
The sorted mode has two phases, a sorting phase and an evaluation phase. This mode is recommended if there are many abscissae to evaluate relative to the number of intervals of the spline, or the abscissae are distributed relatively densely over a subsection of the spline. In the first phase, ixlocj is determined for each xj and a permutation is calculated to sort the xj by interval number. The first phase may be either partially or completely by-passed using the argument START if the enclosing segments and/or the subsequent ordering are already known a priori, for example if multiple spline coefficients C are to be evaluated over the same set of knots LAMDA.
In the second phase of the sorted mode, spline approximations are evaluated by segment, so that non-abscissa dependent calculations over a segment may be reused in the evaluation for all abscissae belonging to a specific segment. For example, all third derivatives of all abscissae in the same segment will be identical.
In the unsorted mode of vectorization, no a priori segment sorting is performed, and if the abscissae are not sufficiently ordered, the evaluation at an abscissa will be independent of evaluations at other abscissae; also non-abscissa dependent calculations over a segment will be repeated for each abscissa in a segment. This may be quicker if the number of abscissa is small in comparison to the number of knots in the spline, and they are distributed sparsely throughout the domain of the spline. This is effectively a direct vectorization of E02BBF and E02BCF, although if the enclosing interval numbers ixlocj are known, these may again be provided.
If the abscissae are sufficiently ordered, then once the first abscissa in a segment is known, an efficient algorithm will be used to determine the location of the final abscissa in this segment. The spline will subsequently be evaluated in a vectorized manner for all the abscissae indexed between the first and last of the current segment.
If no derivatives are required, the spline evaluation is calculated by taking convex combinations due to de Boor (1972). Otherwise, the calculation of s x and its derivatives is based upon,
(i) | evaluating the nonzero B-splines of orders 1, 2, 3 and 4 by recurrence (see Cox (1972) and Cox (1978)),
(ii) | computing all derivatives of the B-splines of order 4 by applying a second recurrence to these computed B-spline values (see de Boor (1972)),
(iii) | multiplying the fourth-order B-spline values and their derivative by the appropriate B-spline coefficients, and summing, to yield the values of s x and its derivatives.
The method of convex combinations is significantly faster than the recurrence based method. If higher derivatives of order 2 or 3 are not required, as much computation as possible is avoided.

4 References

Cox M G (1972) The numerical evaluation of B-splines J. Inst. Math. Appl. 10 134–149
Cox M G (1978) The numerical evaluation of a spline from its B-spline representation J. Inst. Math. Appl. 21 135–143
de Boor C (1972) On calculating with B-splines J. Approx. Theory 6 50–62

5 Arguments

1:   START – INTEGERInput
On entry: indicates the completion state of the first phase of the algorithm.
START=0
The enclosing interval numbers ixlocj for the abscissae xj contained in X have not been determined, and you wish to use the sorted mode of vectorization.
START=1
The enclosing interval numbers ixlocj have been determined and are provided in IXLOC, however the required permutation and interval related information has not been determined and you wish to use the sorted mode of vectorization.
START=2
You wish to use the sorted mode of vectorization, and the entire first phase has been completed, with the enclosing interval numbers supplied in IXLOC, and the required permutation and interval related information provided in IWRK (from a previous call to E02BFF).
START=10
The enclosing interval numbers ixlocj for the abscissae xj contained in X have not been determined, and you wish to use the unsorted mode of vectorization.
START=11
The enclosing interval numbers ixlocj for the abscissae xj contained in X have been supplied in IXLOC, and you wish to use the unsorted mode of vectorization.
Constraint: START=0, 1, 2, 10 or 11.
Additional: START=0 or 10 should be used unless you are sure that the knot set is unchanged between calls.
2:   NCAP7 – INTEGERInput
On entry: n-+7, where n- is the number of intervals of the spline (which is one greater than the number of interior knots, i.e., the knots strictly within the range λ 4 to λ n-+4 over which the spline is defined). Note that if E02BEF was used to generate the knots and spline coefficients then NCAP7 should contain the same value as returned in N by E02BEF.
Constraint: NCAP7≥8.
3:   LAMDA NCAP7 – REAL (KIND=nag_wp) arrayInput
On entry: LAMDA j must be set to the value of the jth member of the complete set of knots, λj, for j=1,2,…,n-+7.
Constraint: the LAMDA j must be in nondecreasing order with LAMDA NCAP7-3>LAMDA 4.
4:   C NCAP7 – REAL (KIND=nag_wp) arrayInput
On entry: the coefficient ci of the B-spline Ni x, for i=1,2,…,n-+3. The remaining elements of the array are not referenced.
5:   DERIV – INTEGERInput
On entry: the order of derivatives required.
If DERIV<0 left derivatives are calculated, otherwise right derivatives are calculated. For abscissae satisfying xj=λ 4 or xj=λ n-+4 only right-handed or left-handed computation will be used respectively. For abscissae which do not coincide exactly with a knot, the handedness of the computation is immaterial.
DERIV=0
No derivatives required.
DERIV=±1
Only s x and its first derivative are required.
DERIV=±2
Only s x and its first and second derivatives are required.
DERIV=±3
s x and its first, second and third derivatives are required.
Note: if DERIV is greater than 3 only the derivatives up to and including 3 will be returned.
6:   XORD – INTEGERInput
On entry: indicates whether X is supplied in a sufficiently ordered manner. If X is sufficiently ordered E02BFF will complete faster.
XORD≠0
The abscissae in X are ordered at least by ascending interval, in that any two abscissae contained in the same interval are only separated by abscissae in the same interval, and the intervals are arranged in ascending order. For example, xj<x j+1, for j=1,2,…,NX-1.
XORD=0
The abscissae in X are not sufficiently ordered.
7:   X NX – REAL (KIND=nag_wp) arrayInput
On entry: the abscissae xj, for j=1,2,…,nx. If START=0 or 10 then evaluations will only be performed for these xj satisfying λ 4≤xj≤λ n-+4. Otherwise evaluation will be performed unless the corresponding element of IXLOC contains an invalid interval number. Please note that if the IXLOC j is a valid interval number then no check is made that X j actually lies in that interval.
Constraint: at least one abscissa must fall between LAMDA 4 and LAMDA NCAP7-3.
8:   IXLOC NX – INTEGER arrayInput/Output
On entry: if START=1, 2 or 11, if you wish xj to be evaluated, IXLOC j must be the enclosing interval number ixlocj of the abscissae xj (see (1)). If you do not wish xj to be evaluated, you may set the interval number to be either less than 4 or greater than n-+4.
Otherwise, IXLOC need not be set.
On exit: if START=1, 2 or 11, IXLOC is unchanged on exit.
Otherwise, IXLOC j, contains the enclosing interval number ixlocj, for the abscissa supplied in X j, for j=1,2,…,nx. Evaluations will only be performed for abscissae xj satisfying λ 4≤xj≤λ n-+4. If evaluation is not performed IXLOC j is set to 0 if xj<λ 4 or n-+7 if xj>λ n-+4.
Constraint: if START=1, 2 or 11, at least one element of IXLOC must be between 4 and NCAP7-3.
9:   NX – INTEGERInput
On entry: nx, the total number of abscissae contained in X, including any that will not be evaluated.
Constraint: NX≥1.
10:   S LDS* – REAL (KIND=nag_wp) arrayOutput
Note: the second dimension of the array S must be at least Dord +1 , see DERIV for the definition of Dord.
On exit: if xj is valid, S jd will contain the (d-1)th derivative of s x, for d=1,2,…,Dord+1 and j=1,2,…,nx. In particular, S j 1 will contain the approximation of s xj for all legal values in X.
11:   LDS – INTEGERInput
On entry: the first dimension of the array S as declared in the (sub)program from which E02BFF is called.
Constraint: LDS≥NX, regardless of the acceptability of the elements of X.
12:   IWRK LIWRK – INTEGER arrayInput/Output
On entry: if START=2, IWRK must be unchanged from a previous call to E02BFF with START=0 or 1.
Otherwise, IWRK need not be set.
On exit: if START=10 or 11, IWRK is unchanged on exit.
Otherwise, IWRK contains the required permutation of elements of X, if any, and information related to the division of the abscissae xj between the intervals derived from LAMDA.
13:   LIWRK – INTEGERInput
On entry: the dimension of the array IWRK as declared in the (sub)program from which E02BFF is called.
Constraint: if START=0, 1 or 2, LIWRK≥3+3×NX.
14:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, because for this routine the values of the output arguments may be useful even if IFAIL≠0 on exit, the recommended value is -1. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Note: E02BFF may return useful information for one or more of the following detected errors or warnings.
Errors or warnings detected by the routine:
IFAIL=1
On entry, at least one element of X has an enclosing interval number in IXLOC outside the set allowed by the provided spline. The spline has been evaluated for all X with enclosing interval numbers inside the allowable set.
value entries of X were indexed below the lower bound value.
value entries of X were indexed above the upper bound value.
IFAIL=2
On entry, all elements of X had enclosing interval numbers in IXLOC outside the domain allowed by the provided spline.
value entries of X were indexed below the lower bound value.
value entries of X were indexed above the upper bound value.
IFAIL=11
On entry, START=value.
Constraint: START=0, 1, 2, 10 or 11.
IFAIL=12
On entry, START=2 and NX is not consistent with the previous call to E02BFF.
On entry, NX=value.
Constraint: NX=value.
IFAIL=21
On entry, NCAP7=value.
Constraint: NCAP7≥8.
IFAIL=31
On entry, LAMDA 4=value, NCAP7=value and LAMDA NCAP7-3=value.
Constraint: LAMDA 4< LAMDA NCAP7-3.
IFAIL=91
On entry, NX=value.
Constraint: NX≥1.
IFAIL=111
On entry, LDS=value.
Constraint: LDS≥NX=value.
IFAIL=131
On entry, LIWRK=value.
Constraint: LIWRK≥3×NX+3=value.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

The computed value of s x has negligible error in most practical situations. Specifically, this value has an absolute error bounded in modulus by 18×cmax×machine precision, where cmax is the largest in modulus of cj, cj+1, cj+2 and cj+3, and j is an integer such that λj+3<x≤λj+4. If cj, cj+1, cj+2 and cj+3 are all of the same sign, then the computed value of s x has relative error bounded by 20×machine precision. For full details see Cox (1978).
No complete error analysis is available for the computation of the derivatives of s x. However, for most practical purposes the absolute errors in the computed derivatives should be small. Note that this is in comparison to the derivatives of the spline, which may or may not be comparable to the derivatives of the function that has been approximated by the spline.

8 Parallelism and Performance

E02BFF is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

If using the sorted mode of vectorization, the time required for the first phase to determine the enclosing intervals is approximately proportional to O nx log n-. The time required to then generate the required permutations and interval information is O nx if X is ordered sufficiently, or at worst O nx min nx,n- log min nx,n- if X is not ordered. The time required by the second phase is then proportional to O nx.
If using the unsorted mode of vectorization, the time required is proportional to O nx log n- if the enclosing interval numbers are not provided, or O nx if they are provided. However, the repeated calculation of various quantities will typically make this slower than the sorted mode when the ratio of abscissae to knots is high, or the abscissae are densely distributed over a relatively small subset of the intervals of the spline.
Note: the routine does not test all the conditions on the knots given in the description of LAMDA in Section 5, since to do this would result in a computation time with a linear dependency upon n- instead of log n-. All the conditions are tested in E02BAF and E02BEF, however.

10 Example

This example fits a spline through a set of data points using E02BEF and then evaluates the spline at a set of supplied abscissae.

10.1 Program Text

Program Text (e02bffe.f90)

10.2 Program Data

Program Data (e02bffe.d)

10.3 Program Results

Program Results (e02bffe.r)

E02 Chapter Contents
E02 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


E02CAF : NAG Library, Mark 26

E02 Chapter Contents
E02 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

E02CAF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

E02CAF forms an approximation to the weighted, least squares Chebyshev series surface fit to data arbitrarily distributed on lines parallel to one independent coordinate axis.

2 Specification

SUBROUTINE E02CAF ( M, N, K, L, X, Y, F, W, MTOT, A, NA, XMIN, XMAX, NUX, INUXP1, NUY, INUYP1, WORK, NWORK, IFAIL)
INTEGER | M(N), N, K, L, MTOT, NA, INUXP1, INUYP1, NWORK, IFAIL
REAL (KIND=nag_wp) | X(MTOT), Y(N), F(MTOT), W(MTOT), A(NA), XMIN(N), XMAX(N), NUX(INUXP1), NUY(INUYP1), WORK(NWORK)

3 Description

E02CAF determines a bivariate polynomial approximation of degree k in x and l in y to the set of data points x r,s,ys,f r,s, with weights w r,s, for s=1,2,…,n and r=1,2,…,ms. That is, the data points are on lines y=ys, but the x values may be different on each line. The values of k and l are prescribed by you (for guidance on their choice, see Section 9). The subroutine is based on the method described in Sections 5 and 6 of Clenshaw and Hayes (1965).
The polynomial is represented in double Chebyshev series form with arguments x- and y-. The arguments lie in the range -1 to +1 and are related to the original variables x and y by the transformations
x-=2 x-xmax+xmin xmax-xmin   and  y-=2 y-ymax+ymin ymax-ymin .
Here ymax and ymin are set by the subroutine to, respectively, the largest and smallest value of ys, but xmax and xmin are functions of y prescribed by you (see Section 9). For this subroutine, only their values x max s and x min s at each y=ys are required. For each s=1,2,…,n, x max s must not be less than the largest x r,s on the line y=ys, and, similarly, x min s must not be greater than the smallest x r,s.
The double Chebyshev series can be written as
∑i=0 k∑j=0 l a ijTi x-Tj y-
where Ti x- is the Chebyshev polynomial of the first kind of degree i with argument x-, and Tj y is similarly defined. However, the standard convention, followed in this subroutine, is that coefficients in the above expression which have either i or j zero are written as 12 a ij, instead of simply a ij, and the coefficient with both i and j equal to zero is written as 14 a 0,0. The series with coefficients output by the subroutine should be summed using this convention. E02CBF is available to compute values of the fitted function from these coefficients.
The subroutine first obtains Chebyshev series coefficients c s,i, for i=0,1,…,k, of the weighted least squares polynomial curve fit of degree k in x- to the data on each line y=ys, for s=1,2,…,n, in turn, using an auxiliary subroutine. The same subroutine is then called k+1 times to fit c s,i, for s=1,2,…,n, by a polynomial of degree l in y-, for each i=0,1,…,k. The resulting coefficients are the required a ij.
You can force the fit to contain a given polynomial factor. This allows for the surface fit to be constrained to have specified values and derivatives along the boundaries x=xmin, x=xmax, y=ymin and y=ymax or indeed along any lines x-= constant or y-= constant (see Section 8 of Clenshaw and Hayes (1965)).

4 References

Clenshaw C W and Hayes J G (1965) Curve and surface fitting J. Inst. Math. Appl. 1 164–183
Hayes J G (ed.) (1970) Numerical Approximation to Functions and Data Athlone Press, London

5 Arguments

1:   M N – INTEGER arrayInput
On entry: M s must be set to ms, the number of data x values on the line y=ys, for s=1,2,…,n.
Constraint: M s>0, for s=1,2,…,N.
2:   N – INTEGERInput
On entry: the number of lines y= constant on which data points are given.
Constraint: N>0.
3:   K – INTEGERInput
On entry: k, the required degree of x in the fit.
Constraint: for s=1,2,…,n, INUXP1-1≤K<mdist s+INUXP1-1, where mdist s is the number of distinct x values with nonzero weight on the line y=ys. See Section 9.
4:   L – INTEGERInput
On entry: l, the required degree of y in the fit.
Constraints:
  • L≥0;
  • INUYP1-1≤L<N+INUYP1-1.
5:   X MTOT – REAL (KIND=nag_wp) arrayInput
On entry: the x values of the data points. The sequence must be
  • all points on y=y 1, followed by
  • all points on y=y 2, followed by
  • ⋮
  • all points on y=yn.
Constraint: for each ys, the x values must be in nondecreasing order.
6:   Y N – REAL (KIND=nag_wp) arrayInput
On entry: Y s must contain the y value of line y=ys, for s=1,2,…,n, on which data is given.
Constraint: the ys values must be in strictly increasing order.
7:   F MTOT – REAL (KIND=nag_wp) arrayInput
On entry: f, the data values of the dependent variable in the same sequence as the x values.
8:   W MTOT – REAL (KIND=nag_wp) arrayInput
On entry: the weights to be assigned to the data points, in the same sequence as the x values. These weights should be calculated from estimates of the absolute accuracies of the fr, expressed as standard deviations, probable errors or some other measure which is of the same dimensions as fr. Specifically, each wr should be inversely proportional to the accuracy estimate of fr. Often weights all equal to unity will be satisfactory. If a particular weight is zero, the corresponding data point is omitted from the fit.
9:   MTOT – INTEGERInput
On entry: the dimension of the arrays X, F and W as declared in the (sub)program from which E02CAF is called.
Constraint: MTOT≥ ∑ s=1 N M s .
10:   A NA – REAL (KIND=nag_wp) arrayOutput
On exit: contains the Chebyshev coefficients of the fit. A i×L+1+j is the coefficient a ij of Section 3 defined according to the standard convention. These coefficients are used by E02CBF to calculate values of the fitted function.
11:   NA – INTEGERInput
On entry: the dimension of the array A as declared in the (sub)program from which E02CAF is called.
Constraint: NA≥K+1×L+1, the total number of coefficients in the fit.
12:   XMIN N – REAL (KIND=nag_wp) arrayInput
On entry: XMIN s must contain xmin s , the lower end of the range of x on the line y=ys, for s=1,2,…,n. It must not be greater than the lowest data value of x on the line. Each xmin s is scaled to -1.0 in the fit. (See also Section 9.)
13:   XMAX N – REAL (KIND=nag_wp) arrayInput
On entry: XMAX s must contain x max s , the upper end of the range of x on the line y=ys, for s=1,2,…,n. It must not be less than the highest data value of x on the line. Each xmax s is scaled to +1.0 in the fit. (See also Section 9.)
Constraint: XMAX s>XMIN s.
14:   NUX INUXP1 – REAL (KIND=nag_wp) arrayInput
On entry: NUX i must contain the coefficient of the Chebyshev polynomial of degree i-1 in x-, in the Chebyshev series representation of the polynomial factor in x- which you require the fit to contain, for i=1,2,…,INUXP1. These coefficients are defined according to the standard convention of Section 3.
Constraint: NUX INUXP1 must be nonzero, unless INUXP1=1, in which case NUX is ignored.
15:   INUXP1 – INTEGERInput
On entry: INUX+1, where INUX is the degree of a polynomial factor in x- which you require the fit to contain. (See Section 3, last paragraph.)
If this option is not required, INUXP1 should be set equal to 1.
Constraint: 1≤INUXP1≤K+1.
16:   NUY INUYP1 – REAL (KIND=nag_wp) arrayInput
On entry: NUY i must contain the coefficient of the Chebyshev polynomial of degree i-1 in y-, in the Chebyshev series representation of the polynomial factor which you require the fit to contain, for i=1,2,…,INUYP1. These coefficients are defined according to the standard convention of Section 3.
Constraint: NUY INUYP1 must be nonzero, unless INUYP1=1, in which case NUY is ignored.
17:   INUYP1 – INTEGERInput
On entry: INUY+1, where INUY is the degree of a polynomial factor in y- which you require the fit to contain. (See Section 3, last paragraph.) If this option is not required, INUYP1 should be set equal to 1.
18:   WORK NWORK – REAL (KIND=nag_wp) arrayWorkspace
19:   NWORK – INTEGERInput
On entry: the dimension of the array WORK as declared in the (sub)program from which E02CAF is called.
Constraint: NWORK ≥ 3 × MTOT + 2 × N × K + 2 + 5 × 1 + max K,L .
20:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, | K or L<0,
or | INUXP1 or INUYP1<1,
or | INUXP1>K+1,
or | INUYP1>L+1,
or | M i<K-INUXP1+2 for some i=1,2,…,N,
or | N<L-INUYP1+2,
or | NA is too small,
or | NWORK is too small,
or | MTOT is too small.
IFAIL=2
XMIN i and XMAX i do not span the data X values on Y=Y i for some i=1,2,…,N, possibly because XMIN i≥XMAX i.
IFAIL=3
The data X values on Y=Y i are not nondecreasing for some i=1,2,…,N, or the Y i themselves are not strictly increasing.
IFAIL=4
The number of distinct X values with nonzero weight on Y=Y i is less than K-INUXP1+2 for some i=1,2,…,N.
IFAIL=5
On entry, | NUX INUXP1=0.0 and INUXP1≠1,
or | NUY INUYP1=0.0 and INUYP1≠1.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

No error analysis for this method has been published. Practical experience with the method, however, is generally extremely satisfactory.

8 Parallelism and Performance

E02CAF is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The time taken is approximately proportional to k×k×MTOT+n×l 2.
The reason for allowing xmax and xmin (which are used to normalize the range of x) to vary with y is that unsatisfactory fits can result if the highest (or lowest) data values of the normalized x on each line y=ys are not approximately the same. (For an explanation of this phenomenon, see page 176 of Clenshaw and Hayes (1965).) Commonly in practice, the lowest (for example) data values x 1,s, while not being approximately constant, do lie close to some smooth curve in the x,y plane. Using values from this curve as the values of xmin, different in general on each line, causes the lowest transformed data values x-1,s to be approximately constant. Sometimes, appropriate curves for xmax and xmin will be clear from the context of the problem (they need not be polynomials). If this is not the case, suitable curves can often be obtained by fitting to the lowest data values x 1,s and to the corresponding highest data values of x, low degree polynomials in y, using routine E02ADF, and then shifting the two curves outwards by a small amount so that they just contain all the data between them. The complete curves are not in fact supplied to the present subroutine, only their values at each ys; and the values simply need to lie on smooth curves. More values on the complete curves will be required subsequently, when computing values of the fitted surface at arbitrary y values.
Naturally, a satisfactory approximation to the surface underlying the data cannot be expected if the character of the surface is not adequately represented by the data. Also, as always with polynomials, the approximating function may exhibit unwanted oscillations (particularly near the ends of the ranges) if the degrees k and l are taken greater than certain values, generally unknown but depending on the total number of coefficients k+1×l+1 should be significantly smaller than, say not more than half, the total number of data points. Similarly, k+1 should be significantly smaller than most (preferably all) the ms, and l+1 significantly smaller than n. Closer spacing of the data near the ends of the x and y ranges is an advantage. In particular, if y-s = - cos π s-1/ n-1 , for s=1,2,…,n and x-r,s = - cos π r-1/ m-1 , for r=1,2,…,m, (thus ms=m for all s), then the values k=m-1 and l=n-1 (so that the polynomial passes exactly through all the data points) should not give unwanted oscillations. Other datasets should be similarly satisfactory if they are everywhere at least as closely spaced as the above cosine values with m replaced by k+1 and n by l+1 (more precisely, if for every s the largest interval between consecutive values of arccos⁡x-r,s, for r=1,2,…,m, is not greater than π/k, and similarly for the y-s). The polynomial obtained should always be examined graphically before acceptance. Note that, for this purpose it is not sufficient to plot the polynomial only at the data values of x and y: intermediate values should also be plotted, preferably via a graphics facility.
Provided the data are adequate, and the surface underlying the data is of a form that can be represented by a polynomial of the chosen degrees, the subroutine should produce a good approximation to this surface. It is not, however, the true least squares surface fit nor even a polynomial in x and y, the original variables (see Section 6 of Clenshaw and Hayes (1965), ), except in certain special cases. The most important of these is where the data values of x are the same on each line y=ys, (i.e., the data points lie on a rectangular mesh in the x,y plane), the weights of the data points are all equal, and xmax and xmin are both constants (in this case they should be set to the largest and smallest data values of x, respectively).
If the dataset is such that it can be satisfactorily approximated by a polynomial of degrees k′ and l′, say, then if higher values are used for k and l in the subroutine, all the coefficients a ij for i>k′ or j>l′ will take apparently random values within a range bounded by the size of the data errors, or rather less. (This behaviour of the Chebyshev coefficients, most readily observed if they are set out in a rectangular array, closely parallels that in curve-fitting, examples of which are given in Section 8 of Hayes (1970).) In practice, therefore, to establish suitable values of k′ and l′, you should first be seeking (within the limitations discussed above) values for k and l which are large enough to exhibit the behaviour described. Values for k′ and l′ should then be chosen as the smallest which do not exclude any coefficients significantly larger than the random ones. A polynomial of degrees k′ and l′ should then be fitted to the data.
If the option to force the fit to contain a given polynomial factor in x is used and if zeros of the chosen factor coincide with data x values on any line, then the effective number of data points on that line is reduced by the number of such coincidences. A similar consideration applies when forcing the y-direction. No account is taken of this by the subroutine when testing that the degrees k and l have not been chosen too large.

10 Example

This example reads data in the following order, using the notation of the argument list for E02CAF above:
N K L Y i M i XMIN i XMAX i, for ​i=1,2,…,N X i F i W i, for ​i=1,2,…,MTOT.
The data points are fitted using E02CAF, and then the fitting polynomial is evaluated at the data points using E02CBF.
The output is:
  • the data points and their fitted values;
  • the Chebyshev coefficients of the fit.

10.1 Program Text

Program Text (e02cafe.f90)

10.2 Program Data

Program Data (e02cafe.d)

10.3 Program Results

Program Results (e02cafe.r)

GnuplotProduced by GNUPLOT 4.6 patchlevel 3 0 1 2 3 4 5 6 7 8 9 0 0.5 1 1.5 2 2.5 3 3.5 4 4.5 5 Fitted Polynomials P(x,y=Y) x Example Program Calculation and Evaluation of Least-squares Bi-variate Polynomial Fit y = 4 y = 2 y = 1 y = 0 gnuplot_plot_1 polynomials in x for constant y gnuplot_plot_2 50*residual gnuplot_plot_3 data points
E02 Chapter Contents
E02 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


E02CBF : NAG Library, Mark 26

E02 Chapter Contents
E02 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

E02CBF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

E02CBF evaluates a bivariate polynomial from the rectangular array of coefficients in its double Chebyshev series representation.

2 Specification

SUBROUTINE E02CBF ( MFIRST, MLAST, K, L, X, XMIN, XMAX, Y, YMIN, YMAX, FF, A, NA, WORK, NWORK, IFAIL)
INTEGER | MFIRST, MLAST, K, L, NA, NWORK, IFAIL
REAL (KIND=nag_wp) | X(MLAST), XMIN, XMAX, Y, YMIN, YMAX, FF(MLAST), A(NA), WORK(NWORK)

3 Description

This subroutine evaluates a bivariate polynomial (represented in double Chebyshev form) of degree k in one variable, x-, and degree l in the other, y-. The range of both variables is -1 to +1. However, these normalized variables will usually have been derived (as when the polynomial has been computed by E02CAF, for example) from your original variables x and y by the transformations
x-=2 x-xmax+xmin xmax-xmin   and  y-=2 y-ymax+ymin ymax-ymin .
(Here xmin and xmax are the ends of the range of x which has been transformed to the range -1 to +1 of x-. ymin and ymax are correspondingly for y. See Section 9). For this reason, the subroutine has been designed to accept values of x and y rather than x- and y-, and so requires values of xmin, etc. to be supplied by you. In fact, for the sake of efficiency in appropriate cases, the routine evaluates the polynomial for a sequence of values of x, all associated with the same value of y.
The double Chebyshev series can be written as
∑i=0 k∑j=0 l a ijTi x-Tj y-,
where Ti x- is the Chebyshev polynomial of the first kind of degree i and argument x-, and Tj y- is similarly defined. However the standard convention, followed in this subroutine, is that coefficients in the above expression which have either i or j zero are written 12 a ij, instead of simply a ij, and the coefficient with both i and j zero is written 14 a 0,0.
The subroutine first forms ci=∑j=0 l a ijTj y-, with a i,0 replaced by 12 a i,0, for each of i=0,1,…,k. The value of the double series is then obtained for each value of x, by summing ci×Ti x-, with c 0 replaced by 12 c 0, over i=0,1,…,k. The Clenshaw three term recurrence (see Clenshaw (1955)) with modifications due to Reinsch and Gentleman (1969) is used to form the sums.

4 References

Clenshaw C W (1955) A note on the summation of Chebyshev series Math. Tables Aids Comput. 9 118–120
Gentleman W M (1969) An error analysis of Goertzel's (Watt's) method for computing Fourier coefficients Comput. J. 12 160–165

5 Arguments

1:   MFIRST – INTEGERInput
2:   MLAST – INTEGERInput
On entry: the index of the first and last x value in the array x at which the evaluation is required respectively (see Section 9).
Constraint: MLAST≥MFIRST.
3:   K – INTEGERInput
4:   L – INTEGERInput
On entry: the degree k of x and l of y, respectively, in the polynomial.
Constraint: K≥0 and L≥0.
5:   X MLAST – REAL (KIND=nag_wp) arrayInput
On entry: X i, for i=MFIRST,…,MLAST, must contain the x values at which the evaluation is required.
Constraint: XMIN≤X i≤XMAX, for all i.
6:   XMIN – REAL (KIND=nag_wp)Input
7:   XMAX – REAL (KIND=nag_wp)Input
On entry: the lower and upper ends, xmin and xmax, of the range of the variable x (see Section 3).
The values of XMIN and XMAX may depend on the value of y (e.g., when the polynomial has been derived using E02CAF).
Constraint: XMAX>XMIN.
8:   Y – REAL (KIND=nag_wp)Input
On entry: the value of the y coordinate of all the points at which the evaluation is required.
Constraint: YMIN≤Y≤YMAX.
9:   YMIN – REAL (KIND=nag_wp)Input
10:   YMAX – REAL (KIND=nag_wp)Input
On entry: the lower and upper ends, ymin and ymax, of the range of the variable y (see Section 3).
Constraint: YMAX>YMIN.
11:   FF MLAST – REAL (KIND=nag_wp) arrayOutput
On exit: FF i gives the value of the polynomial at the point xi,y, for i=MFIRST,…,MLAST.
12:   A NA – REAL (KIND=nag_wp) arrayInput
On entry: the Chebyshev coefficients of the polynomial. The coefficient a ij defined according to the standard convention (see Section 3) must be in A i×l+1+j+1.
13:   NA – INTEGERInput
On entry: the dimension of the array A as declared in the (sub)program from which E02CBF is called.
Constraint: NA≥K+1×L+1, the number of coefficients in a polynomial of the specified degree.
14:   WORK NWORK – REAL (KIND=nag_wp) arrayWorkspace
15:   NWORK – INTEGERInput
On entry: the dimension of the array WORK as declared in the (sub)program from which E02CBF is called.
Constraint: NWORK≥K+1.
16:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, | MFIRST>MLAST,
or | K<0,
or | L<0,
or | NA<K+1×L+1,
or | NWORK<K+1.
IFAIL=2
On entry, | YMIN≥YMAX,
or | Y<YMIN,
or | Y>YMAX.
IFAIL=3
On entry, | XMIN≥XMAX,
or | X i<XMIN, or X i>XMAX, for some i=MFIRST,MFIRST+1,…,MLAST.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

The method is numerically stable in the sense that the computed values of the polynomial are exact for a set of coefficients which differ from those supplied by only a modest multiple of machine precision.

8 Parallelism and Performance

E02CBF is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The time taken is approximately proportional to k+1×m+l+1, where m=MLAST-MFIRST+1, the number of points at which the evaluation is required.
This subroutine is suitable for evaluating the polynomial surface fits produced by the subroutine E02CAF, which provides the real array A in the required form. For this use, the values of ymin and ymax supplied to the present subroutine must be the same as those supplied to E02CAF. The same applies to xmin and xmax if they are independent of y. If they vary with y, their values must be consistent with those supplied to E02CAF (see Section 9 in E02CAF).
The arguments MFIRST and MLAST are intended to permit the selection of a segment of the array X which is to be associated with a particular value of y, when, for example, other segments of X are associated with other values of y. Such a case arises when, after using E02CAF to fit a set of data, you wish to evaluate the resulting polynomial at all the data values. In this case, if the arguments X, Y, MFIRST and MLAST of the present routine are set respectively (in terms of arguments of E02CAF) to X, Y S, 1+∑i=1 s-1 M i and ∑i=1 s M i, the routine will compute values of the polynomial surface at all data points which have Y S as their y coordinate (from which values the residuals of the fit may be derived).

10 Example

This example reads data in the following order, using the notation of the argument list above:
N K L A i, for ​i=1,2,…,K+1×L+1 YMIN YMAX Y i M i XMIN i XMAX i X1 i XM i, for ​i=1,2,…,N.
For each line Y=Y i the polynomial is evaluated at M i equispaced points between X1 i and XM i inclusive.

10.1 Program Text

Program Text (e02cbfe.f90)

10.2 Program Data

Program Data (e02cbfe.d)

10.3 Program Results

Program Results (e02cbfe.r)

GnuplotProduced by GNUPLOT 4.6 patchlevel 3 Example Program Evaluation of Least-squares Bi-variate Polynomial Fit P(x,y) gnuplot_plot_1 gnuplot_plot_2 0 0.5 1 1.5 2 2.5 3 3.5 4 y 0 0.5 1 1.5 2 2.5 3 3.5 4 4.5 x −10 −5 0 5 10 15
E02 Chapter Contents
E02 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


E02 Chapter Contents : NAG Library Manual, Mark 26

E02 Chapter Introduction
NAG Library Manual

NAG Library Chapter Contents

E02 – Curve and Surface Fitting

E02 Chapter Introduction – a description of the Chapter and an overview of the algorithms available

Routine Name | Mark of Introduction | Purpose
E02ACF Example Text Example Plot | 1 | nagf_fit_withdraw_1dmmax Minimax curve fit by polynomials Note: this routine is scheduled for withdrawal at Mark 27, see Advice on Replacement Calls for Withdrawn/Superseded Routines for further information.
E02ADF Example Text Example Data Example Plot | 5 | nagf_fit_1dcheb_arb Least squares curve fit, by polynomials, arbitrary data points
E02AEF Example Text Example Data Example Plot | 5 | nagf_fit_1dcheb_eval Evaluation of fitted polynomial in one variable from Chebyshev series form (simplified parameter list)
E02AFF Example Text Example Data Example Plot | 5 | nagf_fit_1dcheb_glp Least squares polynomial fit, special data points (including interpolation)
E02AGF Example Text Example Data Example Plot | 8 | nagf_fit_1dcheb_con Least squares polynomial fit, values and derivatives may be constrained, arbitrary data points
E02AHF Example Text Example Plot | 8 | nagf_fit_1dcheb_deriv Derivative of fitted polynomial in Chebyshev series form
E02AJF Example Text | 8 | nagf_fit_1dcheb_integ Integral of fitted polynomial in Chebyshev series form
E02AKF Example Text Example Plot | 8 | nagf_fit_1dcheb_eval2 Evaluation of fitted polynomial in one variable from Chebyshev series form
E02ALF Example Text Example Data | 25 | nagf_1d_minimax_polynomial Minimax curve fit by polynomials
E02BAF Example Text Example Data Example Plot | 5 | nagf_fit_1dspline_knots Least squares curve cubic spline fit (including interpolation)
E02BBF Example Text Example Data Example Plot | 5 | nagf_fit_1dspline_eval Evaluation of fitted cubic spline, function only
E02BCF Example Text Example Data Example Plot | 7 | nagf_fit_1dspline_deriv Evaluation of fitted cubic spline, function and derivatives
E02BDF Example Text Example Data | 7 | nagf_fit_1dspline_integ Evaluation of fitted cubic spline, definite integral
E02BEF Example Text Example Data Example Plot | 13 | nagf_fit_1dspline_auto Least squares cubic spline curve fit, automatic knot placement
E02BFF Example Text Example Data | 24 | nagf_fit_1dspline_deriv_vector Evaluation of fitted cubic spline, function and optionally derivatives at a vector of points
E02CAF Example Text Example Data Example Plot | 7 | nagf_fit_2dcheb_lines Least squares surface fit by polynomials, data on lines parallel to one independent coordinate axis
E02CBF Example Text Example Data Example Plot | 7 | nagf_fit_2dcheb_eval Evaluation of fitted polynomial in two variables
E02DAF Example Text Example Data Example Plot | 6 | nagf_fit_2dspline_panel Least squares surface fit, bicubic splines
E02DCF Example Text Example Data Example Plot | 13 | nagf_fit_2dspline_grid Least squares surface fit by bicubic splines with automatic knot placement, data on rectangular grid
E02DDF Example Text Example Data Example Plot | 13 | nagf_fit_2dspline_sctr Least squares surface fit by bicubic splines with automatic knot placement, scattered data
E02DEF Example Text Example Data Example Plot | 14 | nagf_fit_2dspline_evalv Evaluation of fitted bicubic spline at a vector of points
E02DFF Example Text Example Data | 14 | nagf_fit_2dspline_evalm Evaluation of fitted bicubic spline at a mesh of points
E02DHF Example Text Example Data | 23 | nagf_fit_2dspline_derivm Evaluation of spline surface at mesh of points with derivatives
E02GAF Example Text Example Data | 7 | nagf_fit_glin_l1sol L 1-approximation by general linear function
E02GBF Example Text Example Data | 7 | nagf_fit_glinc_l1sol L 1-approximation by general linear function subject to linear inequality constraints
E02GCF Example Text Example Data | 8 | nagf_fit_glin_linf L∞-approximation by general linear function
E02JDF Example Text Example Data Example Plot | 24 | nagf_fit_2dspline_ts_sctr Spline approximation to a set of scattered data using a two-stage approximation method
E02JEF | 24 | nagf_fit_2dspline_ts_evalv Evaluation at a vector of points of a spline computed by E02JDF
E02JFF | 24 | nagf_fit_2dspline_ts_evalm Evaluation at a mesh of points of a spline computed by E02JDF
E02RAF Example Text | 7 | nagf_fit_pade_app Padé approximants
E02RBF Example Text Example Plot | 7 | nagf_fit_pade_eval Evaluation of fitted rational function as computed by E02RAF
E02ZAF Example Text Example Data | 6 | nagf_fit_2dspline_sort Sort two-dimensional data into panels for fitting bicubic splines
E02ZKF | 24 | nagf_fit_opt_set Option setting routine
E02ZLF | 24 | nagf_fit_opt_get Option getting routine
E02 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


E02DAF : NAG Library, Mark 26

E02 Chapter Contents
E02 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

E02DAF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

E02DAF forms a minimal, weighted least squares bicubic spline surface fit with prescribed knots to a given set of data points.

2 Specification

SUBROUTINE E02DAF ( M, PX, PY, X, Y, F, W, LAMDA, MU, POINT, NPOINT, DL, C, NC, WS, NWS, EPS, SIGMA, RANK, IFAIL)
INTEGER | M, PX, PY, POINT(NPOINT), NPOINT, NC, NWS, RANK, IFAIL
REAL (KIND=nag_wp) | X(M), Y(M), F(M), W(M), LAMDA(PX), MU(PY), DL(NC), C(NC), WS(NWS), EPS, SIGMA

3 Description

E02DAF determines a bicubic spline fit s x,y to the set of data points xr,yr,fr with weights wr, for r=1,2,…,m. The two sets of internal knots of the spline, λ and μ, associated with the variables x and y respectively, are prescribed by you. These knots can be thought of as dividing the data region of the x,y plane into panels (see Figure 1 in Section 5). A bicubic spline consists of a separate bicubic polynomial in each panel, the polynomials joining together with continuity up to the second derivative across the panel boundaries.
s x,y has the property that Σ, the sum of squares of its weighted residuals ρr, for r=1,2,…,m, where
ρr = wr s x r , y r - f r (1)
is as small as possible for a bicubic spline with the given knot sets. The routine produces this minimized value of Σ and the coefficients c ij in the B-spline representation of s x,y – see Section 9. E02DEF, E02DFF and E02DHF are available to compute values and derivatives of the fitted spline from the coefficients c ij.
The least squares criterion is not always sufficient to determine the bicubic spline uniquely: there may be a whole family of splines which have the same minimum sum of squares. In these cases, the routine selects from this family the spline for which the sum of squares of the coefficients c ij is smallest: in other words, the minimal least squares solution. This choice, although arbitrary, reduces the risk of unwanted fluctuations in the spline fit. The method employed involves forming a system of m linear equations in the coefficients c ij and then computing its least squares solution, which will be the minimal least squares solution when appropriate. The basis of the method is described in Hayes and Halliday (1974). The matrix of the equation is formed using a recurrence relation for B-splines which is numerically stable (see Cox (1972) and de Boor (1972) – the former contains the more elementary derivation but, unlike de Boor (1972), does not cover the case of coincident knots). The least squares solution is also obtained in a stable manner by using orthogonal transformations, viz. a variant of Givens rotation (see Gentleman (1973)). This requires only one row of the matrix to be stored at a time. Advantage is taken of the stepped-band structure which the matrix possesses when the data points are suitably ordered, there being at most sixteen nonzero elements in any row because of the definition of B-splines. First the matrix is reduced to upper triangular form and then the diagonal elements of this triangle are examined in turn. When an element is encountered whose square, divided by the mean squared weight, is less than a threshold ε, it is replaced by zero and the rest of the elements in its row are reduced to zero by rotations with the remaining rows. The rank of the system is taken to be the number of nonzero diagonal elements in the final triangle, and the nonzero rows of this triangle are used to compute the minimal least squares solution. If all the diagonal elements are nonzero, the rank is equal to the number of coefficients c ij and the solution obtained is the ordinary least squares solution, which is unique in this case.

4 References

Cox M G (1972) The numerical evaluation of B-splines J. Inst. Math. Appl. 10 134–149
de Boor C (1972) On calculating with B-splines J. Approx. Theory 6 50–62
Gentleman W M (1973) Least squares computations by Givens transformations without square roots J. Inst. Math. Applic. 12 329–336
Hayes J G and Halliday J (1974) The least squares fitting of cubic spline surfaces to general data sets J. Inst. Math. Appl. 14 89–103

5 Arguments

1:   M – INTEGERInput
On entry: m, the number of data points.
Constraint: M>1.
2:   PX – INTEGERInput
3:   PY – INTEGERInput
On entry: the total number of knots λ and μ associated with the variables x and y, respectively.
Constraint: PX≥8 and PY≥8.
(They are such that PX-8 and PY-8 are the corresponding numbers of interior knots.) The running time and storage required by the routine are both minimized if the axes are labelled so that PY is the smaller of PX and PY.
4:   X M – REAL (KIND=nag_wp) arrayInput
5:   Y M – REAL (KIND=nag_wp) arrayInput
6:   F M – REAL (KIND=nag_wp) arrayInput
On entry: the coordinates of the data point xr,yr,fr, for r=1,2,…,m. The order of the data points is immaterial, but see the array POINT.
7:   W M – REAL (KIND=nag_wp) arrayInput
On entry: the weight wr of the rth data point. It is important to note the definition of weight implied by the equation (1) in Section 3, since it is also common usage to define weight as the square of this weight. In this routine, each wr should be chosen inversely proportional to the (absolute) accuracy of the corresponding fr, as expressed, for example, by the standard deviation or probable error of the fr. When the fr are all of the same accuracy, all the wr may be set equal to 1.0.
8:   LAMDA PX – REAL (KIND=nag_wp) arrayInput/Output
On entry: LAMDA i+4 must contain the ith interior knot λ i+4 associated with the variable x, for i=1,2,…,PX-8. The knots must be in nondecreasing order and lie strictly within the range covered by the data values of x. A knot is a value of x at which the spline is allowed to be discontinuous in the third derivative with respect to x, though continuous up to the second derivative. This degree of continuity can be reduced, if you require, by the use of coincident knots, provided that no more than four knots are chosen to coincide at any point. Two, or three, coincident knots allow loss of continuity in, respectively, the second and first derivative with respect to x at the value of x at which they coincide. Four coincident knots split the spline surface into two independent parts. For choice of knots see Section 9.
On exit: the interior knots LAMDA 5 to LAMDA PX-4 are unchanged, and the segments LAMDA 1:4 and LAMDA PX-3:PX contain additional (exterior) knots introduced by the routine in order to define the full set of B-splines required. The four knots in the first segment are all set equal to the lowest data value of x and the other four additional knots are all set equal to the highest value: there is experimental evidence that coincident end-knots are best for numerical accuracy. The complete array must be left undisturbed if E02DEF or E02DFF is to be used subsequently.
9:   MU PY – REAL (KIND=nag_wp) arrayInput/Output
On entry: MU i+4 must contain the ith interior knot μ i+4 associated with the variable y, for i=1,2,…,PY-8.
On exit: the same remarks apply to MU as to LAMDA above, with Y replacing X, and y replacing x.
10:   POINT NPOINT – INTEGER arrayInput
On entry: indexing information usually provided by E02ZAF which enables the data points to be accessed in the order which produces the advantageous matrix structure mentioned in Section 3. This order is such that, if the x,y plane is thought of as being divided into rectangular panels by the two sets of knots, all data in a panel occur before data in succeeding panels, where the panels are numbered from bottom to top and then left to right with the usual arrangement of axes, as indicated in Figure 1.
Figure 1
A data point lying exactly on one or more panel sides is considered to be in the highest numbered panel adjacent to the point. E02ZAF should be called to obtain the array POINT, unless it is provided by other means.
11:   NPOINT – INTEGERInput
On entry: the dimension of the array POINT as declared in the (sub)program from which E02DAF is called.
Constraint: NPOINT≥M+PX-7×PY-7.
12:   DL NC – REAL (KIND=nag_wp) arrayOutput
On exit: gives the squares of the diagonal elements of the reduced triangular matrix, divided by the mean squared weight. It includes those elements, less than ε, which are treated as zero (see Section 3).
13:   C NC – REAL (KIND=nag_wp) arrayOutput
On exit: gives the coefficients of the fit. C PY-4× i-1 +j is the coefficient c ij of Sections 3 and 9, for i=1,2,…,PX-4 and j=1,2,…,PY-4. These coefficients are used by E02DEF or E02DFF to calculate values of the fitted function.
14:   NC – INTEGERInput
On entry: the value PX-4×PY-4.
15:   WS NWS – REAL (KIND=nag_wp) arrayWorkspace
16:   NWS – INTEGERInput
On entry: the dimension of the array WS as declared in the (sub)program from which E02DAF is called.
Constraint: NWS≥2×NC+1×3×PY-6-2.
17:   EPS – REAL (KIND=nag_wp)Input
On entry: a threshold ε for determining the effective rank of the system of linear equations. The rank is determined as the number of elements of the array DL which are nonzero. An element of DL is regarded as zero if it is less than ε. Machine precision is a suitable value for ε in most practical applications which have only 2 or 3 decimals accurate in data. If some coefficients of the fit prove to be very large compared with the data ordinates, this suggests that ε should be increased so as to decrease the rank. The array DL will give a guide to appropriate values of ε to achieve this, as well as to the choice of ε in other cases where some experimentation may be needed to determine a value which leads to a satisfactory fit.
18:   SIGMA – REAL (KIND=nag_wp)Output
On exit: Σ, the weighted sum of squares of residuals. This is not computed from the individual residuals but from the right-hand sides of the orthogonally-transformed linear equations. For further details see page 97 of Hayes and Halliday (1974). The two methods of computation are theoretically equivalent, but the results may differ because of rounding error.
19:   RANK – INTEGEROutput
On exit: the rank of the system as determined by the value of the threshold ε.
RANK=NC
The least squares solution is unique.
RANK≠NC
The minimal least squares solution is computed.
20:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
At least one set of knots is not in nondecreasing order, or an interior knot is outside the range of the data values.
IFAIL=2
More than four knots coincide at a single point, possibly because all data points have the same value of x (or y) or because an interior knot coincides with an extreme data value.
IFAIL=3
Array POINT does not indicate the data points in panel order. Call E02ZAF to obtain a correct array.
IFAIL=4
On entry, | M≤1,
or | PX<8,
or | PY<8,
or | NC≠PX-4×PY-4,
or | NWS is too small,
or | NPOINT is too small.
IFAIL=5
All the weights wr are zero or rank determined as zero.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

The computation of the B-splines and reduction of the observation matrix to triangular form are both numerically stable.

8 Parallelism and Performance

E02DAF is not threaded in any implementation.

9 Further Comments

The time taken is approximately proportional to the number of data points, m, and to 3×PY-4+4 2.
The B-spline representation of the bicubic spline is
s x,y = ∑i,j c ij Mi x Nj y
summed over i=1,2,…,PX-4 and over j=1,2,…,PY-4. Here Mi x and Nj y denote normalized cubic B-splines, the former defined on the knots λi,λ i+1,…,λ i+4 and the latter on the knots μj,μ j+1,…,μ j+4. For further details, see Hayes and Halliday (1974) for bicubic splines and de Boor (1972) for normalized B-splines.
The choice of the interior knots, which help to determine the spline's shape, must largely be a matter of trial and error. It is usually best to start with a small number of knots and, examining the fit at each stage, add a few knots at a time in places where the fit is particularly poor. In intervals of x or y where the surface represented by the data changes rapidly, in function value or derivatives, more knots will be needed than elsewhere. In some cases guidance can be obtained by analogy with the case of coincident knots: for example, just as three coincident knots can produce a discontinuity in slope, three close knots can produce rapid change in slope. Of course, such rapid changes in behaviour must be adequately represented by the data points, as indeed must the behaviour of the surface generally, if a satisfactory fit is to be achieved. When there is no rapid change in behaviour, equally-spaced knots will often suffice.
In all cases the fit should be examined graphically before it is accepted as satisfactory.
The fit obtained is not defined outside the rectangle
λ 4 ≤ x ≤ λ PX-3 , μ 4 ≤ y ≤ μ PY-3 .
The reason for taking the extreme data values of x and y for these four knots is that, as is usual in data fitting, the fit cannot be expected to give satisfactory values outside the data region. If, nevertheless, you require values over a larger rectangle, this can be achieved by augmenting the data with two artificial data points a,c,0 and b,d,0 with zero weight, where a≤x≤b, c≤y≤d defines the enlarged rectangle. In the case when the data are adequate to make the least squares solution unique (RANK=NC), this enlargement will not affect the fit over the original rectangle, except for possibly enlarged rounding errors, and will simply continue the bicubic polynomials in the panels bordering the rectangle out to the new boundaries: in other cases the fit will be affected. Even using the original rectangle there may be regions within it, particularly at its corners, which lie outside the data region and where, therefore, the fit will be unreliable. For example, if there is no data point in panel 1 of Figure 1 in Section 5, the least squares criterion leaves the spline indeterminate in this panel: the minimal spline determined by the subroutine in this case passes through the value zero at the point λ 4,μ 4.

10 Example

This example reads a value for ε, and a set of data points, weights and knot positions. If there are more y knots than x knots, it interchanges the x and y axes. It calls E02ZAF to sort the data points into panel order, E02DAF to fit a bicubic spline to them, and E02DEF to evaluate the spline at the data points.
Finally it prints:
– | the weighted sum of squares of residuals computed from the linear equations;
– | the rank determined by E02DAF;
– | data points, fitted values and residuals in panel order;
– | the weighted sum of squares of the residuals; and
– | the coefficients of the spline fit.
The program is written to handle any number of datasets.
Note: the data supplied in this example is not typical of a realistic problem: the number of data points would normally be much larger (in which case the array dimensions and the value of NWS in the program would have to be increased); and the value of ε would normally be much smaller on most machines (see Section 5; the relatively large value of 10-6 has been chosen in order to illustrate a minimal least squares solution when RANK<NC; in this example NC=24).

10.1 Program Text

Program Text (e02dafe.f90)

10.2 Program Data

Program Data (e02dafe.d)

10.3 Program Results

Program Results (e02dafe.r)

GnuplotProduced by GNUPLOT 4.6 patchlevel 3 Example Program Evaluation of Least-squares Bi-cubic Spline Fit Polynomial Surface gnuplot_plot_1 gnuplot_plot_2 −1 −0.5 0 0.5 1 y −1 −0.5 0 0.5 1 x −200 −150 −100 −50 0 50
E02 Chapter Contents
E02 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


E02DCF : NAG Library, Mark 26

E02 Chapter Contents
E02 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

E02DCF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
▸▿ 9 Further Comments
9.1 Timing
9.2 Weighting of Data Points
9.3 Choice of S
9.4 Choice of NXEST and NYEST
9.5 Outline of Method Used
9.6 Evaluation of Computed Spline
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

E02DCF computes a bicubic spline approximation to a set of data values, given on a rectangular grid in the x-y plane. The knots of the spline are located automatically, but a single argument must be specified to control the trade-off between closeness of fit and smoothness of fit.

2 Specification

SUBROUTINE E02DCF ( START, MX, X, MY, Y, F, S, NXEST, NYEST, NX, LAMDA, NY, MU, C, FP, WRK, LWRK, IWRK, LIWRK, IFAIL)
INTEGER | MX, MY, NXEST, NYEST, NX, NY, LWRK, IWRK(LIWRK), LIWRK, IFAIL
REAL (KIND=nag_wp) | X(MX), Y(MY), F(MX*MY), S, LAMDA(NXEST), MU(NYEST), C((NXEST-4)*(NYEST-4)), FP, WRK(LWRK)
CHARACTER(1) | START

3 Description

E02DCF determines a smooth bicubic spline approximation s x,y to the set of data points xq,yr,f q,r, for q=1,2,…,mx and r=1,2,…,my.
The spline is given in the B-spline representation
s x,y = ∑ i=1 nx-4 ∑ j=1 ny-4 c ij Mi x Nj y , (1)
where Mi x and Nj y denote normalized cubic B-splines, the former defined on the knots λi to λ i+4 and the latter on the knots μj to μ j+4. For further details, see Hayes and Halliday (1974) for bicubic splines and de Boor (1972) for normalized B-splines.
The total numbers nx and ny of these knots and their values λ 1,…,λ nx and μ 1,…,μ ny are chosen automatically by the routine. The knots λ 5,…,λ nx-4 and μ 5,…,μ ny-4 are the interior knots; they divide the approximation domain x 1,x mx×y 1,y my into nx-7×ny-7 subpanels λi,λ i+1×μj,μ j+1, for i=4,5,…,nx-4 and j=4,5,…,ny-4. Then, much as in the curve case (see E02BEF), the coefficients c ij are determined as the solution of the following constrained minimization problem:
minimize⁡η , (2)
subject to the constraint
θ = ∑ q=1 mx ∑ r=1 my ε q,r 2 ≤ S , (3)
where | η | is a measure of the (lack of) smoothness of s x,y. Its value depends on the discontinuity jumps in s x,y across the boundaries of the subpanels. It is zero only when there are no discontinuities and is positive otherwise, increasing with the size of the jumps (see Dierckx (1982) for details).
 | ε q,r | denotes the residual f q,r-s xq,yr,
and | S | is a non-negative number specified by you.
By means of the argument S, ‘the smoothing factor’, you will then control the balance between smoothness and closeness of fit, as measured by the sum of squares of residuals in (3). If S is too large, the spline will be too smooth and signal will be lost (underfit); if S is too small, the spline will pick up too much noise (overfit). In the extreme cases the routine will return an interpolating spline θ=0 if S is set to zero, and the least squares bicubic polynomial η=0 if S is set very large. Experimenting with S-values between these two extremes should result in a good compromise. (See Section 9.3 for advice on choice of S.)
The method employed is outlined in Section 9.5 and fully described in Dierckx (1981) and Dierckx (1982). It involves an adaptive strategy for locating the knots of the bicubic spline (depending on the function underlying the data and on the value of S), and an iterative method for solving the constrained minimization problem once the knots have been determined.
Values and derivatives of the computed spline can subsequently be computed by calling E02DEF, E02DFF or E02DHF as described in Section 9.6.

4 References

de Boor C (1972) On calculating with B-splines J. Approx. Theory 6 50–62
Dierckx P (1981) An improved algorithm for curve fitting with spline functions Report TW54 Department of Computer Science, Katholieke Univerciteit Leuven
Dierckx P (1982) A fast algorithm for smoothing data on a rectangular grid while using spline functions SIAM J. Numer. Anal. 19 1286–1304
Hayes J G and Halliday J (1974) The least squares fitting of cubic spline surfaces to general data sets J. Inst. Math. Appl. 14 89–103
Reinsch C H (1967) Smoothing by spline functions Numer. Math. 10 177–183

5 Arguments

1:   START – CHARACTER(1)Input
On entry: determines whether calculations are to be performed afresh (Cold Start) or whether knots found in previous calls are to be used as an initial estimate of knot placement (Warm Start).
START='C'
The routine will build up the knot set starting with no interior knots. No values need be assigned to the arguments NX, NY, LAMDA, MU, WRK or IWRK.
START='W'
The routine will restart the knot-placing strategy using the knots found in a previous call of the routine. In this case, the arguments NX, NY, LAMDA, MU, WRK and IWRK must be unchanged from that previous call. This warm start can save much time in determining a satisfactory set of knots for the given value of S. This is particularly useful when different smoothing factors are used for the same dataset.
Constraint: START='C' or 'W'.
2:   MX – INTEGERInput
On entry: mx, the number of grid points along the x axis.
Constraint: MX≥4.
3:   X MX – REAL (KIND=nag_wp) arrayInput
On entry: X q must be set to xq, the x coordinate of the qth grid point along the x axis, for q=1,2,…,mx.
Constraint: x 1<x 2<⋯<x mx.
4:   MY – INTEGERInput
On entry: my, the number of grid points along the y axis.
Constraint: MY≥4.
5:   Y MY – REAL (KIND=nag_wp) arrayInput
On entry: Y r must be set to yr, the y coordinate of the rth grid point along the y axis, for r=1,2,…,my.
Constraint: y 1<y 2<⋯<y my.
6:   F MX×MY – REAL (KIND=nag_wp) arrayInput
On entry: F my×q-1+r must contain the data value f q,r, for q=1,2,…,mx and r=1,2,…,my.
7:   S – REAL (KIND=nag_wp)Input
On entry: the smoothing factor, S.
If S=0.0, the routine returns an interpolating spline.
If S is smaller than machine precision, it is assumed equal to zero.
For advice on the choice of S, see Sections 3 and 9.3.
Constraint: S≥0.0.
8:   NXEST – INTEGERInput
9:   NYEST – INTEGERInput
On entry: an upper bound for the number of knots nx and ny required in the x- and y-directions respectively.
In most practical situations, NXEST=mx/2 and NYEST=my/2 is sufficient. NXEST and NYEST never need to be larger than mx+4 and my+4 respectively, the numbers of knots needed for interpolation S=0.0. See also Section 9.4.
Constraints:
  • NXEST≥8;
  • NYEST≥8.
10:   NX – INTEGERInput/Output
On entry: if the warm start option is used, the value of NX must be left unchanged from the previous call.
On exit: the total number of knots, nx, of the computed spline with respect to the x variable.
11:   LAMDA NXEST – REAL (KIND=nag_wp) arrayInput/Output
On entry: if the warm start option is used, the values LAMDA 1,LAMDA 2,…,LAMDA NX must be left unchanged from the previous call.
On exit: contains the complete set of knots λi associated with the x variable, i.e., the interior knots LAMDA 5,LAMDA 6,…,LAMDA NX-4 as well as the additional knots
LAMDA 1=LAMDA 2=LAMDA 3=LAMDA 4=X 1
and
LAMDA NX- 3=LAMDA NX- 2=LAMDA NX- 1=LAMDA NX=X MX
needed for the B-spline representation.
12:   NY – INTEGERInput/Output
On entry: if the warm start option is used, the value of NY must be left unchanged from the previous call.
On exit: the total number of knots, ny, of the computed spline with respect to the y variable.
13:   MU NYEST – REAL (KIND=nag_wp) arrayInput/Output
On entry: if the warm start option is used, the values MU 1,MU 2,…,MU NY must be left unchanged from the previous call.
On exit: contains the complete set of knots μi associated with the y variable, i.e., the interior knots MU 5,MU 6,…,MU NY-4 as well as the additional knots
MU 1=MU 2=MU 3=MU 4=Y 1
and
MU NY- 3=MU NY- 2=MU NY- 1=MU NY=Y MY
needed for the B-spline representation.
14:   C NXEST-4×NYEST-4 – REAL (KIND=nag_wp) arrayOutput
On exit: the coefficients of the spline approximation. C ny-4 × i-1 +j is the coefficient c ij defined in Section 3.
15:   FP – REAL (KIND=nag_wp)Output
On exit: the sum of squared residuals, θ, of the computed spline approximation. If FP=0.0, this is an interpolating spline. FP should equal S within a relative tolerance of 0.001 unless NX=NY=8, when the spline has no interior knots and so is simply a bicubic polynomial. For knots to be inserted, S must be set to a value below the value of FP produced in this case.
16:   WRK LWRK – REAL (KIND=nag_wp) arrayCommunication Array
If the warm start option is used, on entry, the values WRK 1,…,WRK 4 must be left unchanged from the previous call.
This array is used as workspace.
17:   LWRK – INTEGERInput
On entry: the dimension of the array WRK as declared in the (sub)program from which E02DCF is called.
Constraint: LWRK≥4×MX+MY+11×NXEST+NYEST+NXEST×MY+ max MY,NXEST+54.
18:   IWRK LIWRK – INTEGER arrayCommunication Array
If the warm start option is used, on entry, the values IWRK 1,…,IWRK 3 must be left unchanged from the previous call.
This array is used as workspace.
19:   LIWRK – INTEGERInput
On entry: the dimension of the array IWRK as declared in the (sub)program from which E02DCF is called.
Constraint: LIWRK≥3+MX+MY+NXEST+NYEST.
20:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, | START≠'C' or 'W',
or | MX<4,
or | MY<4,
or | S<0.0,
or | S=0.0 and NXEST<MX+4,
or | S=0.0 and NYEST<MY+4,
or | NXEST<8,
or | NYEST<8,
or | LWRK<4×MX+MY+11×NXEST+NYEST+NXEST×MY+ max MY,NXEST+54,
or | LIWRK<3+MX+MY+NXEST+NYEST.
IFAIL=2
The values of X q, for q=1,2,…,MX, are not in strictly increasing order.
IFAIL=3
The values of Y r, for r=1,2,…,MY, are not in strictly increasing order.
IFAIL=4
The number of knots required is greater than allowed by NXEST and NYEST. Try increasing NXEST and/or NYEST and, if necessary, supplying larger arrays for the arguments LAMDA, MU, C, WRK and IWRK. However, if NXEST and NYEST are already large, say NXEST>MX/2 and NYEST>MY/2, then this error exit may indicate that S is too small.
IFAIL=5
The iterative process used to compute the coefficients of the approximating spline has failed to converge. This error exit may occur if S has been set very small. If the error persists with increased S, contact NAG.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.
If IFAIL=4 or 5, a spline approximation is returned, but it fails to satisfy the fitting criterion (see (2) and (3) in Section 3) – perhaps by only a small amount, however.

7 Accuracy

On successful exit, the approximation returned is such that its sum of squared residuals FP is equal to the smoothing factor S, up to a specified relative tolerance of 0.001 – except that if nx=8 and ny=8, FP may be significantly less than S: in this case the computed spline is simply the least squares bicubic polynomial approximation of degree 3, i.e., a spline with no interior knots.

8 Parallelism and Performance

E02DCF makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

9.1 Timing

The time taken for a call of E02DCF depends on the complexity of the shape of the data, the value of the smoothing factor S, and the number of data points. If E02DCF is to be called for different values of S, much time can be saved by setting START='W' after the first call.

9.2 Weighting of Data Points

E02DCF does not allow individual weighting of the data values. If these were determined to widely differing accuracies, it may be better to use E02DDF. The computation time would be very much longer, however.

9.3 Choice of S

If the standard deviation of f q,r is the same for all q and r (the case for which E02DCF is designed – see Section 9.2.) and known to be equal, at least approximately, to σ, say, then following Reinsch (1967) and choosing the argument S in the range σ 2 m±2 m, where m=mxmy, is likely to give a good start in the search for a satisfactory value. If the standard deviations vary, the sum of their squares over all the data points could be used. Otherwise experimenting with different values of S will be required from the start, taking account of the remarks in Section 3.
In that case, in view of computation time and memory requirements, it is recommended to start with a very large value for S and so determine the least squares bicubic polynomial; the value returned for FP, call it FP 0, gives an upper bound for S. Then progressively decrease the value of S to obtain closer fits – say by a factor of 10 in the beginning, i.e., S=FP 0/10, S=FP 0/100, and so on, and more carefully as the approximation shows more details.
The number of knots of the spline returned, and their location, generally depend on the value of S and on the behaviour of the function underlying the data. However, if E02DCF is called with START='W', the knots returned may also depend on the smoothing factors of the previous calls. Therefore if, after a number of trials with different values of S and START='W', a fit can finally be accepted as satisfactory, it may be worthwhile to call E02DCF once more with the selected value for S but now using START='C'. Often, E02DCF then returns an approximation with the same quality of fit but with fewer knots, which is therefore better if data reduction is also important.

9.4 Choice of NXEST and NYEST

The number of knots may also depend on the upper bounds NXEST and NYEST. Indeed, if at a certain stage in E02DCF the number of knots in one direction (say nx) has reached the value of its upper bound (NXEST), then from that moment on all subsequent knots are added in the other y direction. Therefore you have the option of limiting the number of knots the routine locates in any direction. For example, by setting NXEST=8 (the lowest allowable value for NXEST), you can indicate that you want an approximation which is a simple cubic polynomial in the variable x.

9.5 Outline of Method Used

If S=0, the requisite number of knots is known in advance, i.e., nx=mx+4 and ny=my+4; the interior knots are located immediately as λi=x i-2 and μj=y j-2, for i=5,6,…,nx-4 and j=5,6,…,ny-4. The corresponding least squares spline is then an interpolating spline and therefore a solution of the problem.
If S>0, suitable knot sets are built up in stages (starting with no interior knots in the case of a cold start but with the knot set found in a previous call if a warm start is chosen). At each stage, a bicubic spline is fitted to the data by least squares, and θ, the sum of squares of residuals, is computed. If θ>S, new knots are added to one knot set or the other so as to reduce θ at the next stage. The new knots are located in intervals where the fit is particularly poor, their number depending on the value of S and on the progress made so far in reducing θ. Sooner or later, we find that θ≤S and at that point the knot sets are accepted. The routine then goes on to compute the (unique) spline which has these knot sets and which satisfies the full fitting criterion specified by (2) and (3). The theoretical solution has θ=S. The routine computes the spline by an iterative scheme which is ended when θ=S within a relative tolerance of 0.001. The main part of each iteration consists of a linear least squares computation of special form, done in a similarly stable and efficient manner as in E02BAF for least squares curve-fitting.
An exception occurs when the routine finds at the start that, even with no interior knots nx=ny=8, the least squares spline already has its sum of residuals ≤S. In this case, since this spline (which is simply a bicubic polynomial) also has an optimal value for the smoothness measure η, namely zero, it is returned at once as the (trivial) solution. It will usually mean that S has been chosen too large.
For further details of the algorithm and its use see Dierckx (1982).

9.6 Evaluation of Computed Spline

The values of the computed spline at the points xr,yr , for r=1,2,…,m, may be obtained in the real array FF (see E02DEF), of length at least m, by the following call:
IFAIL = 0
CALL E02DEF(M,PX,PY,X,Y,LAMDA,MU,C,FF,WRK,IWRK,IFAIL)
where M=m and the coordinates xr, yr are stored in X k, Y k. PX and PY have the same values as NX and NY as output from E02DCF, and LAMDA, MU and C have the same values as LAMDA, MU and C output from E02DCF. WRK is a real workspace array of length at least PY-4, and IWRK is an integer workspace array of length at least PY-4.
To evaluate the computed spline on a mx by my rectangular grid of points in the x-y plane, which is defined by the x coordinates stored in X q, for q=1,2,…,mx, and the y coordinates stored in Y r, for r=1,2,…,my, returning the results in the real array FF (see E02DFF) which is of length at least MX×MY, the following call may be used:
 IFAIL = 0
 CALL E02DFF(MX,MY,PX,PY,X,Y,LAMDA,MU,C,FG,WRK,LWRK,
*            IWRK,LIWRK,IFAIL)
where MX=mx, MY=my. PX and PY have the same values as NX and NY as output from E02DCF, and LAMDA, MU and C have the same values as LAMDA, MU and C output from E02DCF. WRK is a real workspace array of length at least LWRK = min nwrk1,nwrk2 , where nwrk1=MX×4+PX and nwrk2=MY×4+PY. IWRK is an integer workspace array of length at least LIWRK=MY+PY-4 if nwrk1≥nwrk2, or MX+PX-4 otherwise.
The result of the spline evaluated at grid point q,r is returned in element MY×q-1+r of the array FG.

10 Example

This example reads in values of MX, MY, xq, for q=1,2,…,MX, and yr, for r=1,2,…,MY, followed by values of the ordinates f q,r defined at the grid points xq,yr. It then calls E02DCF to compute a bicubic spline approximation for one specified value of S, and prints the values of the computed knots and B-spline coefficients. Finally it evaluates the spline at a small sample of points on a rectangular grid.

10.1 Program Text

Program Text (e02dcfe.f90)

10.2 Program Data

Program Data (e02dcfe.d)

10.3 Program Results

Program Results (e02dcfe.r)

GnuplotProduced by GNUPLOT 4.6 patchlevel 3 Example Program Calculation and Evaluation of Least Squares Bicubic Spline Fit gnuplot_plot_1 gnuplot_plot_2 0 1 2 3 4 5 y 0 0.5 1 1.5 2 2.5 3 3.5 4 x −6 −4 −2 0 2 4 6
E02 Chapter Contents
E02 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


E02DDF : NAG Library, Mark 26

E02 Chapter Contents
E02 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

E02DDF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
▸▿ 9 Further Comments
9.1 Timing
9.2 Choice of S
9.3 Choice of NXEST and NYEST
9.4 Restriction of the approximation domain
9.5 Outline of method used
9.6 Evaluation of Computed Spline
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

E02DDF computes a bicubic spline approximation to a set of scattered data. The knots of the spline are located automatically, but a single argument must be specified to control the trade-off between closeness of fit and smoothness of fit.

2 Specification

SUBROUTINE E02DDF ( START, M, X, Y, F, W, S, NXEST, NYEST, NX, LAMDA, NY, MU, C, FP, RANK, WRK, LWRK, IWRK, LIWRK, IFAIL)
INTEGER | M, NXEST, NYEST, NX, NY, RANK, LWRK, IWRK(LIWRK), LIWRK, IFAIL
REAL (KIND=nag_wp) | X(M), Y(M), F(M), W(M), S, LAMDA(NXEST), MU(NYEST), C((NXEST-4)*(NYEST-4)), FP, WRK(LWRK)
CHARACTER(1) | START

3 Description

E02DDF determines a smooth bicubic spline approximation s x,y to the set of data points xr,yr,fr with weights wr, for r=1,2,…,m.
The approximation domain is considered to be the rectangle xmin,xmax×ymin,ymax, where xmin ymin and xmax ymax denote the lowest and highest data values of x y.
The spline is given in the B-spline representation
s x,y=∑i=1 nx-4∑j=1 ny-4 c ijMi x Nj y, (1)
where Mi x and Nj y denote normalized cubic B-splines, the former defined on the knots λi to λ i+4 and the latter on the knots μj to μ j+4. For further details, see Hayes and Halliday (1974) for bicubic splines and de Boor (1972) for normalized B-splines.
The total numbers nx and ny of these knots and their values λ 1,…,λ nx and μ 1,…,μ ny are chosen automatically by the routine. The knots λ 5,…,λ nx-4 and μ 5,…,μ ny-4 are the interior knots; they divide the approximation domain xmin,xmax×ymin,ymax into nx-7×ny-7 subpanels λi,λ i+1×μj,μ j+1, for i=4,5,…,nx-4 and j=4,5,…,ny-4. Then, much as in the curve case (see E02BEF), the coefficients c ij are determined as the solution of the following constrained minimization problem:
minimize
η, (2)
subject to the constraint
θ=∑r=1 m εr 2≤S (3)
where: | η | is a measure of the (lack of) smoothness of s x,y. Its value depends on the discontinuity jumps in s x,y across the boundaries of the subpanels. It is zero only when there are no discontinuities and is positive otherwise, increasing with the size of the jumps (see Dierckx (1981b) for details).
 | εr | denotes the weighted residual w r f r - s x r , y r ,
and | S | is a non-negative number to be specified by you.
By means of the argument S, ‘the smoothing factor’, you will then control the balance between smoothness and closeness of fit, as measured by the sum of squares of residuals in (3). If S is too large, the spline will be too smooth and signal will be lost (underfit); if S is too small, the spline will pick up too much noise (overfit). In the extreme cases the method would return an interpolating spline θ=0 if S were set to zero, and returns the least squares bicubic polynomial η=0 if S is set very large. Experimenting with S-values between these two extremes should result in a good compromise. (See Section 9.2 for advice on choice of S.) Note however, that this routine, unlike E02BEF and E02DCF, does not allow S to be set exactly to zero: to compute an interpolant to scattered data, E01SAF or E01SGF should be used.
The method employed is outlined in Section 9.5 and fully described in Dierckx (1981a) and Dierckx (1981b). It involves an adaptive strategy for locating the knots of the bicubic spline (depending on the function underlying the data and on the value of S), and an iterative method for solving the constrained minimization problem once the knots have been determined.
Values and derivatives of the computed spline can subsequently be computed by calling E02DEF, E02DFF or E02DHF as described in Section 9.6.

4 References

de Boor C (1972) On calculating with B-splines J. Approx. Theory 6 50–62
Dierckx P (1981a) An improved algorithm for curve fitting with spline functions Report TW54 Department of Computer Science, Katholieke Univerciteit Leuven
Dierckx P (1981b) An algorithm for surface fitting with spline functions IMA J. Numer. Anal. 1 267–283
Hayes J G and Halliday J (1974) The least squares fitting of cubic spline surfaces to general data sets J. Inst. Math. Appl. 14 89–103
Peters G and Wilkinson J H (1970) The least squares problem and pseudo-inverses Comput. J. 13 309–316
Reinsch C H (1967) Smoothing by spline functions Numer. Math. 10 177–183

5 Arguments

1:   START – CHARACTER(1)Input
On entry: determines whether calculations are to be performed afresh (Cold Start) or whether knots found in previous calls are to be used as an initial estimate of knot placement (Warm Start).
START='C'
The routine will build up the knot set starting with no interior knots. No values need be assigned to the arguments NX, NY, LAMDA, MU or WRK.
START='W'
The routine will restart the knot-placing strategy using the knots found in a previous call of the routine. In this case, the arguments NX, NY, LAMDA, MU and WRK must be unchanged from that previous call. This warm start can save much time in determining a satisfactory set of knots for the given value of S. This is particularly useful when different smoothing factors are used for the same dataset.
Constraint: START='C' or 'W'.
2:   M – INTEGERInput
On entry: m, the number of data points.
The number of data points with nonzero weight (see W) must be at least 16.
3:   X M – REAL (KIND=nag_wp) arrayInput
4:   Y M – REAL (KIND=nag_wp) arrayInput
5:   F M – REAL (KIND=nag_wp) arrayInput
On entry: X r, Y r, F r must be set to the coordinates of xr,yr,fr, the rth data point, for r=1,2,…,m. The order of the data points is immaterial.
6:   W M – REAL (KIND=nag_wp) arrayInput
On entry: W r must be set to wr, the rth value in the set of weights, for r=1,2,…,m. Zero weights are permitted and the corresponding points are ignored, except when determining xmin, xmax, ymin and ymax (see Section 9.4). For advice on the choice of weights, see Section 2.1.2 in the E02 Chapter Introduction.
Constraint: the number of data points with nonzero weight must be at least 16.
7:   S – REAL (KIND=nag_wp)Input
On entry: the smoothing factor, S.
For advice on the choice of S, see Sections 3 and 9.2.
Constraint: S>0.0.
8:   NXEST – INTEGERInput
9:   NYEST – INTEGERInput
On entry: an upper bound for the number of knots nx and ny required in the x- and y-directions respectively.
In most practical situations, NXEST=NYEST=4+m/2 is sufficient. See also Section 9.3.
Constraint: NXEST≥8 and NYEST≥8.
10:   NX – INTEGERInput/Output
On entry: if the warm start option is used, the value of NX must be left unchanged from the previous call.
On exit: the total number of knots, nx, of the computed spline with respect to the x variable.
11:   LAMDA NXEST – REAL (KIND=nag_wp) arrayInput/Output
On entry: if the warm start option is used, the values LAMDA 1,LAMDA 2,…,LAMDA NX must be left unchanged from the previous call.
On exit: contains the complete set of knots λi associated with the x variable, i.e., the interior knots LAMDA 5,LAMDA 6,…,LAMDA NX-4 as well as the additional knots
LAMDA 1=LAMDA 2=LAMDA 3=LAMDA 4=xmin
and
LAMDA NX- 3=LAMDA NX- 2=LAMDA NX- 1=LAMDA NX=xmax
needed for the B-spline representation (where xmin and xmax are as described in Section 3).
12:   NY – INTEGERInput/Output
On entry: if the warm start option is used, the value of NY must be left unchanged from the previous call.
On exit: the total number of knots, ny, of the computed spline with respect to the y variable.
13:   MU NYEST – REAL (KIND=nag_wp) arrayInput/Output
On entry: if the warm start option is used, the values MU 1,MU 2,…,MU NY must be left unchanged from the previous call.
On exit: contains the complete set of knots μi associated with the y variable, i.e., the interior knots MU 5,MU 6,…,MU NY-4 as well as the additional knots
MU 1=MU 2=MU 3=MU 4=ymin
and
MU NY- 3=MU NY- 2=MU NY- 1=MU NY=ymax
needed for the B-spline representation (where ymin and ymax are as described in Section 3).
14:   C NXEST-4×NYEST-4 – REAL (KIND=nag_wp) arrayOutput
On exit: the coefficients of the spline approximation. C ny-4 × i-1 +j is the coefficient c ij defined in Section 3.
15:   FP – REAL (KIND=nag_wp)Output
On exit: the weighted sum of squared residuals, θ, of the computed spline approximation. FP should equal S within a relative tolerance of 0.001 unless NX=NY=8, when the spline has no interior knots and so is simply a bicubic polynomial. For knots to be inserted, S must be set to a value below the value of FP produced in this case.
16:   RANK – INTEGEROutput
On exit: gives the rank of the system of equations used to compute the final spline (as determined by a suitable machine-dependent threshold). When RANK=NX-4×NY-4, the solution is unique; otherwise the system is rank-deficient and the minimum-norm solution is computed. The latter case may be caused by too small a value of S.
17:   WRK LWRK – REAL (KIND=nag_wp) arrayCommunication Array
If the warm start option is used, on entry, the value of WRK 1 must be left unchanged from the previous call.
This array is used as workspace.
18:   LWRK – INTEGERInput
On entry: the dimension of the array WRK as declared in the (sub)program from which E02DDF is called.
Constraint: LWRK≥7×u×v+25×w×w+1+2×u+v+4×M+23×w+56,
where u=NXEST-4, v=NYEST-4 and w=max u,v.
For some problems, the routine may need to compute the minimal least squares solution of a rank-deficient system of linear equations (see Section 3). The amount of workspace required to solve such problems will be larger than specified by the value given above, which must be increased by an amount, lwrk2 say. An upper bound for lwrk2 is given by 4×u×v×w+ 2×u×v+ 4×w, where u, v and w are as above. However, if there are enough data points, scattered uniformly over the approximation domain, and if the smoothing factor S is not too small, there is a good chance that this extra workspace is not needed. A lot of memory might therefore be saved by assuming that no additional workspace is required (lwrk2=0).
19:   IWRK LIWRK – INTEGER arrayWorkspace
20:   LIWRK – INTEGERInput
On entry: the dimension of the array IWRK as declared in the (sub)program from which E02DDF is called.
Constraint: LIWRK≥M+2×NXEST-7×NYEST-7.
21:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, | START≠'C' or 'W',
or | the number of data points with nonzero weight <16,
or | S≤0.0,
or | NXEST<8,
or | NYEST<8,
or | LWRK<7×u×v+25×w×w+1+2×u+v+4×M+23×w+56, where u=NXEST-4, v=NYEST-4 and w=max u,v,
or | LIWRK<M+2×NXEST-7×NYEST-7.
IFAIL=2
On entry, either all the X r, for r=1,2,…,M, are equal, or all the Y r, for r=1,2,…,M, are equal.
IFAIL=3
The number of knots required is greater than allowed by NXEST and NYEST. Try increasing NXEST and/or NYEST and, if necessary, supplying larger arrays for the arguments LAMDA, MU, C, WRK and IWRK. However, if NXEST and NYEST are already large, say NXEST, NYEST>4+M/2, then this error exit may indicate that S is too small.
IFAIL=4
No more knots can be added because the number of B-spline coefficients NX-4×NY-4 already exceeds the number of data points M. This error exit may occur if either of S or M is too small.
IFAIL=5
No more knots can be added because the additional knot would (quasi) coincide with an old one. This error exit may occur if too large a weight has been given to an inaccurate data point, or if S is too small.
IFAIL=6
The iterative process used to compute the coefficients of the approximating spline has failed to converge. This error exit may occur if S has been set very small. If the error persists with increased S, contact NAG.
IFAIL=7
LWRK is too small; the routine needs to compute the minimal least squares solution of a rank-deficient system of linear equations, but there is not enough workspace. There is no approximation returned but, having saved the information contained in NX, LAMDA, NY, MU and WRK, and having adjusted the value of LWRK and the dimension of array WRK accordingly, you can continue at the point the program was left by calling E02DDF with START='W'. Note that the requested value for LWRK is only large enough for the current phase of the algorithm. If the routine is restarted with LWRK set to the minimum value requested, a larger request may be made at a later stage of the computation. See Section 5 for the upper bound on LWRK. On soft failure, the minimum requested value for LWRK is returned in IWRK 1 and the safe value for LWRK is returned in IWRK 2.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.
If IFAIL=3, 4, 5 or 6, a spline approximation is returned, but it fails to satisfy the fitting criterion (see (2) and (3) in Section 3 – perhaps only by a small amount, however.

7 Accuracy

On successful exit, the approximation returned is such that its weighted sum of squared residuals FP is equal to the smoothing factor S, up to a specified relative tolerance of 0.001 – except that if nx=8 and ny=8, FP may be significantly less than S: in this case the computed spline is simply the least squares bicubic polynomial approximation of degree 3, i.e., a spline with no interior knots.

8 Parallelism and Performance

E02DDF makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

9.1 Timing

The time taken for a call of E02DDF depends on the complexity of the shape of the data, the value of the smoothing factor S, and the number of data points. If E02DDF is to be called for different values of S, much time can be saved by setting START='W' after the first call.
It should be noted that choosing S very small considerably increases computation time.

9.2 Choice of S

If the weights have been correctly chosen (see Section 2.1.2 in the E02 Chapter Introduction), the standard deviation of wrfr would be the same for all r, equal to σ, say. In this case, choosing the smoothing factor S in the range σ 2 m±2 m, as suggested by Reinsch (1967), is likely to give a good start in the search for a satisfactory value. Otherwise, experimenting with different values of S will be required from the start.
In that case, in view of computation time and memory requirements, it is recommended to start with a very large value for S and so determine the least squares bicubic polynomial; the value returned for FP, call it FP 0, gives an upper bound for S. Then progressively decrease the value of S to obtain closer fits – say by a factor of 10 in the beginning, i.e., S=FP 0/10, S=FP 0/100, and so on, and more carefully as the approximation shows more details.
To choose S very small is strongly discouraged. This considerably increases computation time and memory requirements. It may also cause rank-deficiency (as indicated by the argument RANK) and endanger numerical stability.
The number of knots of the spline returned, and their location, generally depend on the value of S and on the behaviour of the function underlying the data. However, if E02DDF is called with START='W', the knots returned may also depend on the smoothing factors of the previous calls. Therefore if, after a number of trials with different values of S and START='W', a fit can finally be accepted as satisfactory, it may be worthwhile to call E02DDF once more with the selected value for S but now using START='C'. Often, E02DDF then returns an approximation with the same quality of fit but with fewer knots, which is therefore better if data reduction is also important.

9.3 Choice of NXEST and NYEST

The number of knots may also depend on the upper bounds NXEST and NYEST. Indeed, if at a certain stage in E02DDF the number of knots in one direction (say nx) has reached the value of its upper bound (NXEST), then from that moment on all subsequent knots are added in the other y direction. This may indicate that the value of NXEST is too small. On the other hand, it gives you the option of limiting the number of knots the routine locates in any direction. For example, by setting NXEST=8 (the lowest allowable value for NXEST), you can indicate that you want an approximation which is a simple cubic polynomial in the variable x.

9.4 Restriction of the approximation domain

The fit obtained is not defined outside the rectangle λ 4,λ nx-3×μ 4,μ ny-3. The reason for taking the extreme data values of x and y for these four knots is that, as is usual in data fitting, the fit cannot be expected to give satisfactory values outside the data region. If, nevertheless, you require values over a larger rectangle, this can be achieved by augmenting the data with two artificial data points a,c,0 and b,d,0 with zero weight, where a,b×c,d denotes the enlarged rectangle.

9.5 Outline of method used

First suitable knot sets are built up in stages (starting with no interior knots in the case of a cold start but with the knot set found in a previous call if a warm start is chosen). At each stage, a bicubic spline is fitted to the data by least squares and θ, the sum of squares of residuals, is computed. If θ>S, a new knot is added to one knot set or the other so as to reduce θ at the next stage. The new knot is located in an interval where the fit is particularly poor. Sooner or later, we find that θ≤S and at that point the knot sets are accepted. The routine then goes on to compute a spline which has these knot sets and which satisfies the full fitting criterion specified by (2) and (3). The theoretical solution has θ=S. The routine computes the spline by an iterative scheme which is ended when θ=S within a relative tolerance of 0.001. The main part of each iteration consists of a linear least squares computation of special form, done in a similarly stable and efficient manner as in E02DAF. As there also, the minimal least squares solution is computed wherever the linear system is found to be rank-deficient.
An exception occurs when the routine finds at the start that, even with no interior knots (N=8), the least squares spline already has its sum of squares of residuals ≤S. In this case, since this spline (which is simply a bicubic polynomial) also has an optimal value for the smoothness measure η, namely zero, it is returned at once as the (trivial) solution. It will usually mean that S has been chosen too large.
For further details of the algorithm and its use see Dierckx (1981b).

9.6 Evaluation of Computed Spline

The values of the computed spline at the points xr,yr , for r=1,2,…,n, may be obtained in the real array FF (see E02DEF), of length at least n, by the following call:
IFAIL = 0
CALL E02DEF(N,NX,NY,X,Y,LAMDA,MU,C,FF,WRK,IWRK,IFAIL)
where N=n and the coordinates xr, yr are stored in X k, Y k. PX and PY have the same values as NX and NY as output from E02DDF, and LAMDA, MU and C have the same values as LAMDA, MU and C output from E02DDF. WRK is a real workspace array of length at least PY-4, and IWRK is an integer workspace array of length at least PY-4.
To evaluate the computed spline on a kx by ky rectangular grid of points in the x-y plane, which is defined by the x coordinates stored in X q, for q=1,2,…,kx, and the y coordinates stored in Y r, for r=1,2,…,ky, returning the results in the real array FF (see E02DFF) which is of length at least MX×MY, the following call may be used:
 IFAIL = 0
 CALL E02DFF(KX,KY,NX,NY,TX,TY,LAMDA,MU,C,FG,WRK,LWRK,
*            IWRK,LIWRK,IFAIL)
where KX=kx, KY=ky. NX, NY, LAMDA, MU and C have the same values as NX, NY, LAMDA, MU and C output from E02DDF. WRK is a real workspace array of length at least LWRK = min nwrk1,nwrk2 , where nwrk1=KX×4+PX and nwrk2=KY×4+PY. IWRK is an integer workspace array of length at least LIWRK=KY+PY-4 if nwrk1≥nwrk2, or KX+PX-4 otherwise.
The result of the spline evaluated at grid point q,r is returned in element KY×q-1+r of the array FG.

10 Example

This example reads in a value of M, followed by a set of M data points xr,yr,fr and their weights wr. It then calls E02DDF to compute a bicubic spline approximation for one specified value of S, and prints the values of the computed knots and B-spline coefficients. Finally it evaluates the spline at a small sample of points on a rectangular grid.

10.1 Program Text

Program Text (e02ddfe.f90)

10.2 Program Data

Program Data (e02ddfe.d)

10.3 Program Results

Program Results (e02ddfe.r)

GnuplotProduced by GNUPLOT 4.6 patchlevel 3 Example Program Calculation and Evaluation of Least-squares Bicubic Spline Fit from Scattered Data gnuplot_plot_1 gnuplot_plot_2 4 6 8 10 12 14 16 18 20 x 2 4 6 8 10 12 14 16 y 5 10 15 20 25 30 35 40 45 50
E02 Chapter Contents
E02 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


E02DEF : NAG Library, Mark 26

E02 Chapter Contents
E02 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

E02DEF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

E02DEF calculates values of a bicubic spline from its B-spline representation.

2 Specification

SUBROUTINE E02DEF ( M, PX, PY, X, Y, LAMDA, MU, C, FF, WRK, IWRK, IFAIL)
INTEGER | M, PX, PY, IWRK(PY-4), IFAIL
REAL (KIND=nag_wp) | X(M), Y(M), LAMDA(PX), MU(PY), C((PX-4)*(PY-4)), FF(M), WRK(PY-4)

3 Description

E02DEF calculates values of the bicubic spline s x,y at prescribed points xr,yr, for r=1,2,…,m, from its augmented knot sets λ and μ and from the coefficients c ij, for i=1,2,…,PX-4 and j=1,2,…,PY-4, in its B-spline representation
s x,y=∑ij c ijMi x Nj y.
Here Mi x and Nj y denote normalized cubic B-splines, the former defined on the knots λi to λ i+4 and the latter on the knots μj to μ j+4.
This routine may be used to calculate values of a bicubic spline given in the form produced by E01DAF, E02DAF, E02DCF and E02DDF. It is derived from the routine B2VRE in Anthony et al. (1982).

4 References

Anthony G T, Cox M G and Hayes J G (1982) DASL – Data Approximation Subroutine Library National Physical Laboratory
Cox M G (1978) The numerical evaluation of a spline from its B-spline representation J. Inst. Math. Appl. 21 135–143

5 Arguments

1:   M – INTEGERInput
On entry: m, the number of points at which values of the spline are required.
Constraint: M≥1.
2:   PX – INTEGERInput
3:   PY – INTEGERInput
On entry: PX and PY must specify the total number of knots associated with the variables x and y respectively. They are such that PX-8 and PY-8 are the corresponding numbers of interior knots.
Constraint: PX≥8 and PY≥8.
4:   X M – REAL (KIND=nag_wp) arrayInput
5:   Y M – REAL (KIND=nag_wp) arrayInput
On entry: X and Y must contain xr and yr, for r=1,2,…,m, respectively. These are the coordinates of the points at which values of the spline are required. The order of the points is immaterial.
Constraint: X and Y must satisfy
LAMDA 4≤X r≤LAMDA PX-3
and
MU 4≤Y r≤MU PY- 3,   r= 1,2,…,m.
The spline representation is not valid outside these intervals
6:   LAMDA PX – REAL (KIND=nag_wp) arrayInput
7:   MU PY – REAL (KIND=nag_wp) arrayInput
On entry: LAMDA and MU must contain the complete sets of knots λ and μ associated with the x and y variables respectively.
Constraint: the knots in each set must be in nondecreasing order, with LAMDA PX-3>LAMDA 4 and MU PY-3>MU 4.
8:   C PX-4×PY-4 – REAL (KIND=nag_wp) arrayInput
On entry: C PY-4 × i-1 +j must contain the coefficient c ij described in Section 3, for i=1,2,…,PX-4 and j=1,2,…,PY-4.
9:   FF M – REAL (KIND=nag_wp) arrayOutput
On exit: FF r contains the value of the spline at the point xr,yr, for r=1,2,…,m.
10:   WRK PY-4 – REAL (KIND=nag_wp) arrayWorkspace
11:   IWRK PY-4 – INTEGER arrayWorkspace
12:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, | M<1,
or | PY<8,
or | PX<8.
IFAIL=2
On entry, the knots in array LAMDA, or those in array MU, are not in nondecreasing order, or LAMDA PX-3≤LAMDA 4, or MU PY-3≤MU 4.
IFAIL=3
On entry, at least one of the prescribed points xr,yr lies outside the rectangle defined by LAMDA 4, LAMDA PX-3 and MU 4, MU PY-3.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

The method used to evaluate the B-splines is numerically stable, in the sense that each computed value of s xr,yr can be regarded as the value that would have been obtained in exact arithmetic from slightly perturbed B-spline coefficients. See Cox (1978) for details.

8 Parallelism and Performance

E02DEF is not threaded in any implementation.

9 Further Comments

Computation time is approximately proportional to the number of points, m, at which the evaluation is required.

10 Example

This program reads in knot sets LAMDA 1,…,LAMDA PX and MU 1,…,MU PY, and a set of bicubic spline coefficients c ij. Following these are a value for m and the coordinates xr,yr, for r=1,2,…,m, at which the spline is to be evaluated.

10.1 Program Text

Program Text (e02defe.f90)

10.2 Program Data

Program Data (e02defe.d)

10.3 Program Results

Program Results (e02defe.r)

GnuplotProduced by GNUPLOT 4.6 patchlevel 3 1 1.2 1.4 1.6 1.8 2 0 0.2 0.4 0.6 0.8 1 1 1.5 2 2.5 3 3.5 4 4.5 5 Example Program Evaluation of Least-squares Bicubic Spline Fit at Scattered Points gnuplot_plot_1 Evaluatuation points gnuplot_plot_2 gnuplot_plot_3 Bicubic Spline Surface x y
E02 Chapter Contents
E02 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


E02DFF : NAG Library, Mark 26

E02 Chapter Contents
E02 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

E02DFF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

E02DFF calculates values of a bicubic spline from its B-spline representation. The spline is evaluated at all points on a rectangular grid.

2 Specification

SUBROUTINE E02DFF ( MX, MY, PX, PY, X, Y, LAMDA, MU, C, FF, WRK, LWRK, IWRK, LIWRK, IFAIL)
INTEGER | MX, MY, PX, PY, LWRK, IWRK(LIWRK), LIWRK, IFAIL
REAL (KIND=nag_wp) | X(MX), Y(MY), LAMDA(PX), MU(PY), C((PX-4)*(PY-4)), FF(MX*MY), WRK(LWRK)

3 Description

E02DFF calculates values of the bicubic spline s x,y on a rectangular grid of points in the x-y plane, from its augmented knot sets λ and μ and from the coefficients c ij, for i=1,2,…,PX-4 and j=1,2,…,PY-4, in its B-spline representation
s x,y = ∑ij c ij Mi x Nj y .
Here Mi x and Nj y denote normalized cubic B-splines, the former defined on the knots λi to λ i+4 and the latter on the knots μj to μ j+4.
The points in the grid are defined by coordinates xq, for q=1,2,…,mx, along the x axis, and coordinates yr, for r=1,2,…,my, along the y axis.
This routine may be used to calculate values of a bicubic spline given in the form produced by E01DAF, E02DAF, E02DCF and E02DDF. It is derived from the routine B2VRE in Anthony et al. (1982).

4 References

Anthony G T, Cox M G and Hayes J G (1982) DASL – Data Approximation Subroutine Library National Physical Laboratory
Cox M G (1978) The numerical evaluation of a spline from its B-spline representation J. Inst. Math. Appl. 21 135–143

5 Arguments

1:   MX – INTEGERInput
2:   MY – INTEGERInput
On entry: MX and MY must specify mx and my respectively, the number of points along the x and y axis that define the rectangular grid.
Constraint: MX≥1 and MY≥1.
3:   PX – INTEGERInput
4:   PY – INTEGERInput
On entry: PX and PY must specify the total number of knots associated with the variables x and y respectively. They are such that PX-8 and PY-8 are the corresponding numbers of interior knots.
Constraint: PX≥8 and PY≥8.
5:   X MX – REAL (KIND=nag_wp) arrayInput
6:   Y MY – REAL (KIND=nag_wp) arrayInput
On entry: X and Y must contain xq, for q=1,2,…,mx, and yr, for r=1,2,…,my, respectively. These are the x and y coordinates that define the rectangular grid of points at which values of the spline are required.
Constraint: X and Y must satisfy
LAMDA 4 ≤ X q < X q+1 ≤ LAMDA PX-3 ,   q=1,2,…,mx-1
and
MU 4 ≤ Y r < Y r+1 ≤ MU PY-3 ,   r= 1,2,…,my- 1 .
.
The spline representation is not valid outside these intervals.
7:   LAMDA PX – REAL (KIND=nag_wp) arrayInput
8:   MU PY – REAL (KIND=nag_wp) arrayInput
On entry: LAMDA and MU must contain the complete sets of knots λ and μ associated with the x and y variables respectively.
Constraint: the knots in each set must be in nondecreasing order, with LAMDA PX-3>LAMDA 4 and MU PY-3>MU 4.
9:   C PX-4×PY-4 – REAL (KIND=nag_wp) arrayInput
On entry: C PY-4 × i-1 +j must contain the coefficient c ij described in Section 3, for i=1,2,…,PX-4 and j=1,2,…,PY-4.
10:   FF MX×MY – REAL (KIND=nag_wp) arrayOutput
On exit: FF MY×q-1+r contains the value of the spline at the point xq,yr, for q=1,2,…,mx and r=1,2,…,my.
11:   WRK LWRK – REAL (KIND=nag_wp) arrayWorkspace
12:   LWRK – INTEGERInput
On entry: the dimension of the array WRK as declared in the (sub)program from which E02DFF is called.
Constraint: LWRK≥min 4×MX+PX,4×MY+PY.
13:   IWRK LIWRK – INTEGER arrayWorkspace
14:   LIWRK – INTEGERInput
On entry: the dimension of the array IWRK as declared in the (sub)program from which E02DFF is called.
Constraints:
  • if 4×MX+PX>4×MY+PY, LIWRK≥MY+PY-4;
  • otherwise LIWRK≥MX+PX-4.
15:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, | MX<1,
or | MY<1,
or | PY<8,
or | PX<8.
IFAIL=2
On entry, | LWRK is too small,
or | LIWRK is too small.
IFAIL=3
On entry, the knots in array LAMDA, or those in array MU, are not in nondecreasing order, or LAMDA PX-3≤LAMDA 4, or MU PY-3≤MU 4.
IFAIL=4
On entry, the restriction LAMDA 4≤X 1<⋯<X MX≤LAMDA PX-3, or the restriction MU 4≤Y 1<⋯<Y MY≤MU PY-3, is violated.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

The method used to evaluate the B-splines is numerically stable, in the sense that each computed value of s xr,yr can be regarded as the value that would have been obtained in exact arithmetic from slightly perturbed B-spline coefficients. See Cox (1978) for details.

8 Parallelism and Performance

E02DFF is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

Computation time is approximately proportional to mxmy+4 mx+my.

10 Example

This example reads in knot sets LAMDA 1,…,LAMDA PX and MU 1,…,MU PY, and a set of bicubic spline coefficients c ij. Following these are values for mx and the x coordinates xq, for q=1,2,…,mx, and values for my and the y coordinates yr, for r=1,2,…,my, defining the grid of points on which the spline is to be evaluated.

10.1 Program Text

Program Text (e02dffe.f90)

10.2 Program Data

Program Data (e02dffe.d)

10.3 Program Results

Program Results (e02dffe.r)

E02 Chapter Contents
E02 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


E02DHF : NAG Library, Mark 26

E02 Chapter Contents
E02 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

E02DHF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

E02DHF computes the partial derivative (of order νx, νy), of a bicubic spline approximation to a set of data values, from its B-spline representation, at points on a rectangular grid in the x-y plane. This routine may be used to calculate derivatives of a bicubic spline given in the form produced by E01DAF, E02DAF, E02DCF and E02DDF.

2 Specification

SUBROUTINE E02DHF ( MX, MY, PX, PY, X, Y, LAMDA, MU, C, NUX, NUY, Z, IFAIL)
INTEGER | MX, MY, PX, PY, NUX, NUY, IFAIL
REAL (KIND=nag_wp) | X(MX), Y(MY), LAMDA(PX), MU(PY), C((PX-4)*(PY-4)), Z(MX*MY)

3 Description

E02DHF determines the partial derivative ∂ νx + νy ∂ x νx ∂ y νy of a smooth bicubic spline approximation s x,y at the set of data points xq,yr.
The spline is given in the B-spline representation
s x,y = ∑ i=1 nx-4 ∑ j=1 ny-4 c ij Mi x Nj y , (1)
where Mi x and Nj y denote normalized cubic B-splines, the former defined on the knots λi to λ i+4 and the latter on the knots μj to μ j+4, with nx and ny the total numbers of knots of the computed spline with respect to the x and y variables respectively. For further details, see Hayes and Halliday (1974) for bicubic splines and de Boor (1972) for normalized B-splines. This routine is suitable for B-spline representations returned by E01DAF, E02DAF, E02DCF and E02DDF.
The partial derivatives can be up to order 2 in each direction; thus the highest mixed derivative available is ∂4 ∂x 2 ∂y 2 .
The points in the grid are defined by coordinates xq, for q=1,2,…,mx, along the x axis, and coordinates yr, for r=1,2,…,my, along the y axis.

4 References

de Boor C (1972) On calculating with B-splines J. Approx. Theory 6 50–62
Dierckx P (1981) An improved algorithm for curve fitting with spline functions Report TW54 Department of Computer Science, Katholieke Univerciteit Leuven
Dierckx P (1982) A fast algorithm for smoothing data on a rectangular grid while using spline functions SIAM J. Numer. Anal. 19 1286–1304
Hayes J G and Halliday J (1974) The least squares fitting of cubic spline surfaces to general data sets J. Inst. Math. Appl. 14 89–103
Reinsch C H (1967) Smoothing by spline functions Numer. Math. 10 177–183

5 Arguments

1:   MX – INTEGERInput
On entry: mx, the number of grid points along the x axis.
Constraint: MX≥1.
2:   MY – INTEGERInput
On entry: my, the number of grid points along the y axis.
Constraint: MY≥1.
3:   PX – INTEGERInput
On entry: the total number of knots in the x-direction of the bicubic spline approximation, e.g., the value NX as returned by E02DCF.
4:   PY – INTEGERInput
On entry: the total number of knots in the y-direction of the bicubic spline approximation, e.g., the value NY as returned by E02DCF.
5:   X MX – REAL (KIND=nag_wp) arrayInput
On entry: X q must be set to xq, the x coordinate of the qth grid point along the x axis, for q=1,2,…,mx, on which values of the partial derivative are sought.
Constraint: x 1<x 2<⋯<x mx.
6:   Y MY – REAL (KIND=nag_wp) arrayInput
On entry: Y r must be set to yr, the y coordinate of the rth grid point along the y axis, for r=1,2,…,my on which values of the partial derivative are sought.
Constraint: y 1<y 2<⋯<y my.
7:   LAMDA PX – REAL (KIND=nag_wp) arrayInput
On entry: contains the position of the knots in the x-direction of the bicubic spline approximation to be differentiated, e.g., LAMDA as returned by E02DCF.
8:   MU PY – REAL (KIND=nag_wp) arrayInput
On entry: contains the position of the knots in the y-direction of the bicubic spline approximation to be differentiated, e.g., MU as returned by E02DCF.
9:   C PX-4×PY-4 – REAL (KIND=nag_wp) arrayInput
On entry: the coefficients of the bicubic spline approximation to be differentiated, e.g., C as returned by E02DCF.
10:   NUX – INTEGERInput
On entry: specifies the order, νx of the partial derivative in the x-direction.
Constraint: 0≤NUX≤2.
11:   NUY – INTEGERInput
On entry: specifies the order, νy of the partial derivative in the y-direction.
Constraint: 0≤NUY≤2.
12:   Z MX×MY – REAL (KIND=nag_wp) arrayOutput
On exit: Z my×q-1+r contains the derivative ∂νx+νy ∂x νx ∂y νy s xq,yr , for q=1,2,…,mx and r=1,2,…,my.
13:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, NUX=value.
Constraint: 0≤NUX≤2.
IFAIL=2
On entry, NUY=value.
Constraint: 0≤NUY≤2.
IFAIL=3
On entry, MX=value.
Constraint: MX≥1.
IFAIL=4
On entry, MY=value.
Constraint: MY≥1.
IFAIL=5
On entry, for i=value, X i-1=value and X i=value.
Constraint: X i-1≤X i, for i=2,3,…,MX.
IFAIL=6
On entry, for i=value, Y i-1=value and Y i=value.
Constraint: Y i-1≤Y i, for i=2,3,…,MY.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

On successful exit, the partial derivatives on the given mesh are accurate to machine precision with respect to the supplied bicubic spline. Please refer to Section 7 in E01DAF, E02DAF, E02DCF and E02DDF of the routine document for the respective routine which calculated the spline approximant for details on the accuracy of that approximation.

8 Parallelism and Performance

E02DHF is not threaded in any implementation.

9 Further Comments

None.

10 Example

This example reads in values of mx, my, xq, for q=1,2,…,mx, and yr, for r=1,2,…,my, followed by values of the ordinates f q,r defined at the grid points xq,yr. It then calls E02DCF to compute a bicubic spline approximation for one specified value of S. Finally it evaluates the spline and its first x derivative at a small sample of points on a rectangular grid by calling E02DHF.

10.1 Program Text

Program Text (e02dhfe.f90)

10.2 Program Data

Program Data (e02dhfe.d)

10.3 Program Results

Program Results (e02dhfe.r)

E02 Chapter Contents
E02 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


E02GAF : NAG Library, Mark 26

E02 Chapter Contents
E02 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

E02GAF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

E02GAF calculates an l 1 solution to an over-determined system of linear equations.

2 Specification

SUBROUTINE E02GAF ( M, A, LDA, B, NPLUS2, TOLER, X, RESID, IRANK, ITER, IWORK, IFAIL)
INTEGER | M, LDA, NPLUS2, IRANK, ITER, IWORK(M), IFAIL
REAL (KIND=nag_wp) | A(LDA,NPLUS2), B(M), TOLER, X(NPLUS2), RESID

3 Description

Given a matrix A with m rows and n columns m≥n and a vector b with m elements, the routine calculates an l 1 solution to the over-determined system of equations
Ax=b.
That is to say, it calculates a vector x, with n elements, which minimizes the l 1 norm (the sum of the absolute values) of the residuals
r x=∑i=1 m ri,
where the residuals ri are given by
ri=bi-∑j=1 n a ijxj,  i=1,2,…,m.
Here a ij is the element in row i and column j of A, bi is the ith element of b and xj the jth element of x. The matrix A need not be of full rank.
Typically in applications to data fitting, data consisting of m points with coordinates ti,yi are to be approximated in the l 1 norm by a linear combination of known functions ϕj t,
α 1ϕ 1 t+α 2ϕ 2 t+⋯+αnϕn t.
This is equivalent to fitting an l 1 solution to the over-determined system of equations
∑j=1 n ϕj ti αj=yi,  i=1,2,…,m.
Thus if, for each value of i and j, the element a ij of the matrix A in the previous paragraph is set equal to the value of ϕj ti and bi is set equal to yi, the solution vector x will contain the required values of the αj. Note that the independent variable t above can, instead, be a vector of several independent variables (this includes the case where each ϕi is a function of a different variable, or set of variables).
The algorithm is a modification of the simplex method of linear programming applied to the primal formulation of the l 1 problem (see Barrodale and Roberts (1973) and Barrodale and Roberts (1974)). The modification allows several neighbouring simplex vertices to be passed through in a single iteration, providing a substantial improvement in efficiency.

4 References

Barrodale I and Roberts F D K (1973) An improved algorithm for discrete l 1 linear approximation SIAM J. Numer. Anal. 10 839–848
Barrodale I and Roberts F D K (1974) Solution of an overdetermined system of equations in the l 1-norm Comm. ACM 17(6) 319–320

5 Arguments

1:   M – INTEGERInput
On entry: the number of equations, m (the number of rows of the matrix A).
Constraint: M≥n≥1.
2:   A LDANPLUS2 – REAL (KIND=nag_wp) arrayInput/Output
On entry: A ij must contain a ij, the element in the ith row and jth column of the matrix A, for i=1,2,…,m and j=1,2,…,n. The remaining elements need not be set.
On exit: contains the last simplex tableau generated by the simplex method.
3:   LDA – INTEGERInput
On entry: the first dimension of the array A as declared in the (sub)program from which E02GAF is called.
Constraint: LDA≥M+2.
4:   B M – REAL (KIND=nag_wp) arrayInput/Output
On entry: B i must contain bi, the ith element of the vector b, for i=1,2,…,m.
On exit: the ith residual ri corresponding to the solution vector x, for i=1,2,…,m.
5:   NPLUS2 – INTEGERInput
On entry: n+2, where n is the number of unknowns (the number of columns of the matrix A).
Constraint: 3≤NPLUS2≤M+2.
6:   TOLER – REAL (KIND=nag_wp)Input
On entry: a non-negative value. In general TOLER specifies a threshold below which numbers are regarded as zero. The recommended threshold value is ε 2/3 where ε is the machine precision. The recommended value can be computed within the routine by setting TOLER to zero. If premature termination occurs a larger value for TOLER may result in a valid solution.
Suggested value: 0.0.
7:   X NPLUS2 – REAL (KIND=nag_wp) arrayOutput
On exit: X j contains the jth element of the solution vector x, for j=1,2,…,n. The elements X n+1 and X n+2 are unused.
8:   RESID – REAL (KIND=nag_wp)Output
On exit: the sum of the absolute values of the residuals for the solution vector x.
9:   IRANK – INTEGEROutput
On exit: the computed rank of the matrix A.
10:   ITER – INTEGEROutput
On exit: the number of iterations taken by the simplex method.
11:   IWORK M – INTEGER arrayWorkspace
12:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
An optimal solution has been obtained but this may not be unique.
IFAIL=2
The calculations have terminated prematurely due to rounding errors. Experiment with larger values of TOLER or try scaling the columns of the matrix (see Section 9).
IFAIL=3
On entry, | NPLUS2<3,
or | NPLUS2>M+2,
or | LDA<M+2.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

Experience suggests that the computational accuracy of the solution x is comparable with the accuracy that could be obtained by applying Gaussian elimination with partial pivoting to the n equations satisfied by this algorithm (i.e., those equations with zero residuals). The accuracy therefore varies with the conditioning of the problem, but has been found generally very satisfactory in practice.

8 Parallelism and Performance

E02GAF is not threaded in any implementation.

9 Further Comments

The effects of m and n on the time and on the number of iterations in the Simplex Method vary from problem to problem, but typically the number of iterations is a small multiple of n and the total time taken is approximately proportional to m n 2.
It is recommended that, before the routine is entered, the columns of the matrix A are scaled so that the largest element in each column is of the order of unity. This should improve the conditioning of the matrix, and also enable the argument TOLER to perform its correct function. The solution x obtained will then, of course, relate to the scaled form of the matrix. Thus if the scaling is such that, for each j=1,2,…,n, the elements of the jth column are multiplied by the constant kj, the element xj of the solution vector x must be multiplied by kj if it is desired to recover the solution corresponding to the original matrix A.

10 Example

Suppose we wish to approximate a set of data by a curve of the form
y=K et+L e-t+M
where K, L and M are unknown. Given values yi at 5 points ti we may form the over-determined set of equations for K, L and M
e xi K+e-xi L+M=yi,  i=1,2,…,5.
E02GAF is used to solve these in the l 1 sense.

10.1 Program Text

Program Text (e02gafe.f90)

10.2 Program Data

Program Data (e02gafe.d)

10.3 Program Results

Program Results (e02gafe.r)

E02 Chapter Contents
E02 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


E02GBF : NAG Library, Mark 26

E02 Chapter Contents
E02 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

E02GBF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

E02GBF calculates an l 1 solution to an over-determined system of linear equations, possibly subject to linear inequality constraints.

2 Specification

SUBROUTINE E02GBF ( M, N, MPL, E, LDE, F, X, MXS, MONIT, IPRINT, K, EL1N, INDX, W, IW, IFAIL)
INTEGER | M, N, MPL, LDE, MXS, IPRINT, K, INDX(MPL), IW, IFAIL
REAL (KIND=nag_wp) | E(LDE,MPL), F(MPL), X(N), EL1N, W(IW)
EXTERNAL | MONIT

3 Description

Given a matrix A with m rows and n columns m≥n and a vector b with m elements, the routine calculates an l 1 solution to the over-determined system of equations
Ax=b.
That is to say, it calculates a vector x, with n elements, which minimizes the l 1-norm (the sum of the absolute values) of the residuals
r x=∑i=1 m ri,
where the residuals ri are given by
ri=bi-∑j=1 n a ijxj,  i=1,2,…,m.
Here a ij is the element in row i and column j of A, bi is the ith element of b and xj the jth element of x.
If, in addition, a matrix C with l rows and n columns and a vector d with l elements, are given, the vector x computed by the routine is such as to minimize the l 1-norm r x subject to the set of inequality constraints Cx≥d.
The matrices A and C need not be of full rank.
Typically in applications to data fitting, data consisting of m points with coordinates ti,yi is to be approximated by a linear combination of known functions ϕi t,
α 1ϕ 1 t+α 2ϕ 2 t+⋯+αnϕn t,
in the l 1-norm, possibly subject to linear inequality constraints on the coefficients αj of the form Cα≥d where α is the vector of the αj and C and d are as in the previous paragraph. This is equivalent to finding an l 1 solution to the over-determined system of equations
∑j=1 n ϕj ti αj=yi,  i=1,2,…,m,
subject to Cα≥d.
Thus if, for each value of i and j, the element a ij of the matrix A above is set equal to the value of ϕj ti and bi is equal to yi and C and d are also supplied to the routine, the solution vector x will contain the required values of the αj. Note that the independent variable t above can, instead, be a vector of several independent variables (this includes the case where each of ϕi is a function of a different variable, or set of variables).
The algorithm follows the Conn–Pietrzykowski approach (see Bartels et al. (1978) and Conn and Pietrzykowski (1977)), which is via an exact penalty function
g x = γ r x - ∑ i=1 l min 0, ciT x-di ,
where γ is a penalty parameter, ciT is the ith row of the matrix C, and di is the ith element of the vector d. It proceeds in a step-by-step manner much like the simplex method for linear programming but does not move from vertex to vertex and does not require the problem to be cast in a form containing only non-negative unknowns. It uses stable procedures to update an orthogonal factorization of the current set of active equations and constraints.

4 References

Bartels R H, Conn A R and Charalambous C (1976) Minimisation techniques for piecewise Differentiable functions – the l∞ solution to an overdetermined linear system Technical Report No. 247, CORR 76/30 Mathematical Sciences Department, The John Hopkins University
Bartels R H, Conn A R and Sinclair J W (1976) A Fortran program for solving overdetermined systems of linear equations in the l 1 Sense Technical Report No. 236, CORR 76/7 Mathematical Sciences Department, The John Hopkins University
Bartels R H, Conn A R and Sinclair J W (1978) Minimisation techniques for piecewise differentiable functions – the l 1 solution to an overdetermined linear system SIAM J. Numer. Anal. 15 224–241
Conn A R and Pietrzykowski T (1977) A penalty-function method converging directly to a constrained optimum SIAM J. Numer. Anal. 14 348–375

5 Arguments

1:   M – INTEGERInput
On entry: the number of equations in the over-determined system, m (i.e., the number of rows of the matrix A).
Constraint: M≥N.
2:   N – INTEGERInput
On entry: the number of unknowns, n (the number of columns of the matrix A).
Constraint: N≥2.
3:   MPL – INTEGERInput
On entry: m+l, where l is the number of constraints (which may be zero).
Constraint: MPL≥M.
4:   E LDEMPL – REAL (KIND=nag_wp) arrayInput/Output
On entry: the equation and constraint matrices stored in the following manner.
The first m columns contain the m rows of the matrix A; element E ij specifying the element a ji in the jth row and ith column of A (the coefficient of the ith unknown in the jth equation), for i=1,2,…,n and j=1,2,…,m. The next l columns contain the l rows of the constraint matrix C; element E i j+m containing the element c ji in the jth row and ith column of C (the coefficient of the ith unknown in the jth constraint), for i=1,2,…,n and j=1,2,…,l.
On exit: unchanged, except possibly to the extent of a small multiple of the machine precision. (See Section 9.)
5:   LDE – INTEGERInput
On entry: the first dimension of the array E as declared in the (sub)program from which E02GBF is called.
Constraint: LDE≥N.
6:   F MPL – REAL (KIND=nag_wp) arrayInput
On entry: F i, for i=1,2,…,m, must contain bi (the ith element of the right-hand side vector of the over-determined system of equations) and F m+i, for i=1,2,…,l, must contain di (the ith element of the right-hand side vector of the constraints), where l is the number of constraints.
7:   X N – REAL (KIND=nag_wp) arrayInput/Output
On entry: X i must contain an estimate of the ith unknown, for i=1,2,…,n. If no better initial estimate for X i is available, set X i=0.0.
On exit: the latest estimate of the ith unknown, for i=1,2,…,n. If IFAIL=0 on exit, these are the solution values.
8:   MXS – INTEGERInput
On entry: the maximum number of steps to be allowed for the solution of the unconstrained problem. Typically this may be a modest multiple of n. If, on entry, MXS is zero or negative, the value returned by X02BBF is used.
9:   MONIT – SUBROUTINE, supplied by the user.External Procedure
MONIT can be used to print out the current values of any selection of its arguments. The frequency with which MONIT is called in E02GBF is controlled by IPRINT.
The specification of MONIT is:
SUBROUTINE MONIT ( N, X, NITER, K, EL1N)
INTEGER | N, NITER, K
REAL (KIND=nag_wp) | X(N), EL1N
1:   N – INTEGERInput
On entry: the number n of unknowns (the number of columns of the matrix A).
2:   X N – REAL (KIND=nag_wp) arrayInput
On entry: the latest estimate of the unknowns.
3:   NITER – INTEGERInput
On entry: the number of iterations so far carried out.
4:   K – INTEGERInput
On entry: the total number of equations and constraints which are currently active (i.e., the number of equations with zero residuals plus the number of constraints which are satisfied as equations).
5:   EL1N – REAL (KIND=nag_wp)Input
On entry: the l 1-norm of the current residuals of the over-determined system of equations.
MONIT must either be a module subprogram USEd by, or declared as EXTERNAL in, the (sub)program from which E02GBF is called. Arguments denoted as Input must not be changed by this procedure.
10:   IPRINT – INTEGERInput
On entry: the frequency of iteration print out.
IPRINT>0
MONIT is called every IPRINT iterations and at the solution.
IPRINT=0
Information is printed out at the solution only. Otherwise MONIT is not called (but a dummy routine must still be provided).
11:   K – INTEGEROutput
On exit: the total number of equations and constraints which are then active (i.e., the number of equations with zero residuals plus the number of constraints which are satisfied as equalities).
12:   EL1N – REAL (KIND=nag_wp)Output
On exit: the l 1-norm (sum of absolute values) of the equation residuals.
13:   INDX MPL – INTEGER arrayOutput
On exit: specifies which columns of E relate to the inactive equations and constraints. INDX 1 up to INDX K number the active columns and INDX K+1 up to INDX MPL number the inactive columns.
14:   W IW – REAL (KIND=nag_wp) arrayWorkspace
15:   IW – INTEGERInput
On entry: the dimension of the array W as declared in the (sub)program from which E02GBF is called.
Constraint: IW≥3×MPL+5×N+N 2+N+1×N+2/2.
16:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
The constraints cannot all be satisfied simultaneously: they are not compatible with one another. Hence no solution is possible.
IFAIL=2
The limit imposed by MXS has been reached without finding a solution. Consider restarting from the current point by simply calling E02GBF again without changing the arguments.
IFAIL=3
The routine has failed because of numerical difficulties; the problem is too ill-conditioned. Consider rescaling the unknowns.
IFAIL=4
Elements 1 to M of one of the first MPL columns of the array E are all zero – this corresponds to a zero row in either of the matrices A or C.
On entry, IW is too small. IW=value. Minimum possible dimension: value.
On entry, LDE=value and N=value.
Constraint: LDE≥N.
On entry, M=value and N=value.
Constraint: M≥N.
On entry, MPL=value and M=value.
Constraint: MPL≥M.
On entry, N=value.
Constraint: N≥2.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

The method is stable.

8 Parallelism and Performance

E02GBF is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The effect of m and n on the time and on the number of iterations varies from problem to problem, but typically the number of iterations is a small multiple of n and the total time taken is approximately proportional to m n 2.
Linear dependencies among the rows or columns of A and C are not necessarily a problem to the algorithm. Solutions can be obtained from rank-deficient A and C. However, the algorithm requires that at every step the currently active columns of E form a linearly independent set. If this is not the case at any step, small, random perturbations of the order of rounding error are added to the appropriate columns of E. Normally this perturbation process will not affect the solution significantly. It does mean, however, that results may not be exactly reproducible.

10 Example

Suppose we wish to approximate in 0,1 a set of data by a curve of the form
y=a x 3+b x 2+cx+d
which has non-negative slope at the data points. Given points ti,yi we may form the equations
yi=a ti 3+b ti 2+c ti+d
for i=1,2,…,6, for the 6 data points. The requirement of a non-negative slope at the data points demands
3 a ti 2+2 b ti+c≥0
for each ti and these form the constraints.
(Note that, for fitting with polynomials, it would usually be advisable to work with the polynomial expressed in Chebyshev series form (see the E02 Chapter Introduction). The power series form is used here for simplicity of exposition.)

10.1 Program Text

Program Text (e02gbfe.f90)

10.2 Program Data

Program Data (e02gbfe.d)

10.3 Program Results

Program Results (e02gbfe.r)

E02 Chapter Contents
E02 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


E02GCF : NAG Library, Mark 26

E02 Chapter Contents
E02 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

E02GCF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

E02GCF calculates an l∞ solution to an over-determined system of linear equations.

2 Specification

SUBROUTINE E02GCF ( M, N, SDA, LDA, A, B, TOL, RELERR, X, RESMAX, IRANK, ITER, IFAIL)
INTEGER | M, N, SDA, LDA, IRANK, ITER, IFAIL
REAL (KIND=nag_wp) | A(LDA,SDA), B(M), TOL, RELERR, X(N), RESMAX

3 Description

Given a matrix A with m rows and n columns m≥n and a vector b with m elements, the routine calculates an l∞ solution to the over-determined system of equations
Ax=b.
That is to say, it calculates a vector x, with n elements, which minimizes the l∞ norm of the residuals (the absolutely largest residual)
r x = max 1≤i≤m ri
where the residuals ri are given by
ri = bi - ∑ j=1 n a ij xj ,   i=1,2,…,m .
Here a ij is the element in row i and column j of A, bi is the ith element of b and xj the jth element of x. The matrix A need not be of full rank. The solution is not unique in this case, and may not be unique even if A is of full rank.
Alternatively, in applications where a complete minimization of the l∞ norm is not necessary, you may obtain an approximate solution, usually in shorter time, by giving an appropriate value to the argument RELERR.
Typically in applications to data fitting, data consisting of m points with coordinates ti,yi is to be approximated in the l∞ norm by a linear combination of known functions ϕj t,
α 1ϕ 1 t+α 2ϕ 2 t+⋯+αnϕn t.
This is equivalent to finding an l∞ solution to the over-determined system of equations
∑ j=1 n ϕj ti αj = yi ,   i=1,2,…,m .
Thus if, for each value of i and j the element a ij of the matrix A above is set equal to the value of ϕj ti and bi is set equal to yi, the solution vector x will contain the required values of the αj. Note that the independent variable t above can, instead, be a vector of several independent variables (this includes the case where each ϕi is a function of a different variable, or set of variables).
The algorithm is a modification of the simplex method of linear programming applied to the dual formation of the l∞ problem (see Barrodale and Phillips (1974) and Barrodale and Phillips (1975)). The modifications are designed to improve the efficiency and stability of the simplex method for this particular application.

4 References

Barrodale I and Phillips C (1974) An improved algorithm for discrete Chebyshev linear approximation Proc. 4th Manitoba Conf. Numerical Mathematics 177–190 University of Manitoba, Canada
Barrodale I and Phillips C (1975) Solution of an overdetermined system of linear equations in the Chebyshev norm [F4] (Algorithm 495) ACM Trans. Math. Software 1(3) 264–270

5 Arguments

1:   M – INTEGERInput
On entry: the number of equations, m (the number of rows of the matrix A).
Constraint: M≥N.
2:   N – INTEGERInput
On entry: the number of unknowns, n (the number of columns of the matrix A).
Constraint: N≥1.
3:   SDA – INTEGERInput
On entry: the second dimension of the array A as declared in the (sub)program from which E02GCF is called.
Constraint: SDA≥M+1.
4:   LDA – INTEGERInput
On entry: the first dimension of the array A as declared in the (sub)program from which E02GCF is called.
Constraint: LDA≥N+3.
5:   A LDASDA – REAL (KIND=nag_wp) arrayInput/Output
On entry: A ji must contain a ij, the element in the ith row and jth column of the matrix A, for i=1,2,…,m and j=1,2,…,n, (that is, the transpose of the matrix). The remaining elements need not be set. Preferably, the columns of the matrix A (rows of the argument A) should be scaled before entry: see Section 7.
On exit: contains the last simplex tableau.
6:   B M – REAL (KIND=nag_wp) arrayInput/Output
On entry: B i must contain bi, the ith element of the vector b, for i=1,2,…,m.
On exit: the ith residual ri corresponding to the solution vector x, for i=1,2,…,m. Note however that these residuals may contain few significant figures, especially when RESMAX is within one or two orders of magnitude of TOL. Indeed if RESMAX≤TOL, the elements B i may all be set to zero. It is therefore often advisable to compute the residuals directly.
7:   TOL – REAL (KIND=nag_wp)Input
On entry: a threshold below which numbers are regarded as zero. The recommended threshold value is 10.0×ε, where ε is the machine precision. If TOL≤0.0 on entry, the recommended value is used within the routine. If premature termination occurs, a larger value for TOL may result in a valid solution.
Suggested value: 0.0.
8:   RELERR – REAL (KIND=nag_wp)Input/Output
On entry: must be set to a bound on the relative error acceptable in the maximum residual at the solution.
If RELERR≤0.0, then the l∞ solution is computed, and RELERR is set to 0.0 on exit.
If RELERR>0.0, then the routine obtains instead an approximate solution for which the largest residual is less than 1.0+RELERR times that of the l∞ solution; on exit, RELERR contains a smaller value such that the above bound still applies. (The usual result of this option, say with RELERR=0.1, is a saving in the number of simplex iterations).
On exit: is altered as described above.
9:   X N – REAL (KIND=nag_wp) arrayOutput
On exit: if IFAIL=0 or 1, X j contains the jth element of the solution vector x, for j=1,2,…,n. Whether this is an l∞ solution or an approximation to one, depends on the value of RELERR on entry.
10:   RESMAX – REAL (KIND=nag_wp)Output
On exit: if IFAIL=0 or 1, RESMAX contains the absolute value of the largest residual(s) for the solution vector x. (See B.)
11:   IRANK – INTEGEROutput
On exit: if IFAIL=0 or 1, IRANK contains the computed rank of the matrix A.
12:   ITER – INTEGEROutput
On exit: if IFAIL=0 or 1, ITER contains the number of iterations taken by the simplex method.
13:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, because for this routine the values of the output arguments may be useful even if IFAIL≠0 on exit, the recommended value is -1. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Note: E02GCF may return useful information for one or more of the following detected errors or warnings.
Errors or warnings detected by the routine:
IFAIL=1
An optimal solution has been obtained but this may not be unique (perhaps simply because the matrix A is not of full rank, i.e., IRANK<N).
IFAIL=2
The calculations have terminated prematurely due to rounding errors. Experiment with larger values of TOL or try rescaling the columns of the matrix (see Section 9).
IFAIL=3
On entry, | LDA<N+3,
or | SDA<M+1,
or | M<N,
or | N<1.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

Experience suggests that the computational accuracy of the solution x is comparable with the accuracy that could be obtained by applying Gaussian elimination with partial pivoting to the n+1 equations which have residuals of largest absolute value. The accuracy therefore varies with the conditioning of the problem, but has been found generally very satisfactory in practice.

8 Parallelism and Performance

E02GCF is not threaded in any implementation.

9 Further Comments

The effects of m and n on the time and on the number of iterations in the simplex method vary from problem to problem, but typically the number of iterations is a small multiple of n and the total time is approximately proportional to m n 2.
It is recommended that, before the routine is entered, the columns of the matrix A are scaled so that the largest element in each column is of the order of unity. This should improve the conditioning of the matrix, and also enable the argument TOL to perform its correct function. The solution x obtained will then, of course, relate to the scaled form of the matrix. Thus if the scaling is such that, for each j=1,2,…,n, the elements of the jth column are multiplied by the constant kj, the element xj of the solution vector x must be multiplied by kj if it is desired to recover the solution corresponding to the original matrix A.

10 Example

This example approximates a set of data by a curve of the form
y=K et+L e-t+M
where K, L and M are unknown. Given values yi at 5 points ti we may form the over-determined set of equations for K, L and M
e ti K+e-ti L+M=yi,  i=1,2,…,5.
E02GCF is used to solve these in the l∞ sense.

10.1 Program Text

Program Text (e02gcfe.f90)

10.2 Program Data

Program Data (e02gcfe.d)

10.3 Program Results

Program Results (e02gcfe.r)

E02 Chapter Contents
E02 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


E02 Chapter Introduction : NAG Library, Mark 26

E02 Chapter Contents
NAG Library Manual

NAG Library Chapter Introduction

E02 – Curve and Surface Fitting

▸▿ Contents

1 Scope of the Chapter
▸▿ 2 Background to the Problems
▸▿ 2.1 Preliminary Considerations
2.1.1 Fitting criteria: norms
2.1.2 Weighting of data points
▸▿ 2.2 Curve Fitting
2.2.1 Representation of polynomials
2.2.2 Representation of cubic splines
▸▿ 2.3 Surface Fitting
2.3.1 Representation of bivariate polynomials
2.3.2 Bicubic splines: definition and representation
2.4 General Linear and Nonlinear Fitting Functions
2.5 Constrained Problems
2.6 Padé Approximants
▸▿ 3 Recommendations on Choice and Use of Available Routines
▸▿ 3.1 General
3.1.1 Data considerations
3.1.2 Transformation of variables
▸▿ 3.2 Polynomial Curves
3.2.1 Least squares polynomials: arbitrary data points
3.2.2 Least squares polynomials: selected data points
3.2.3 Minimax space polynomials
▸▿ 3.3 Cubic Spline Curves
3.3.1 Least squares cubic splines
3.3.2 Automatic fitting with cubic splines
▸▿ 3.4 Polynomial and Spline Surfaces
3.4.1 Least squares polynomials
3.4.2 Least squares bicubic splines
3.4.3 Automatic fitting with bicubic splines
3.4.4 Large data sets
▸▿ 3.5 General Linear and Nonlinear Fitting Functions
3.5.1 General linear functions
3.5.2 Nonlinear functions
3.6 Constraints
3.7 Evaluation, Differentiation and Integration
3.8 Padé Approximants
4 Decision Trees
5 Functionality Index
6 Auxiliary Routines Associated with Library Routine Arguments
7 Routines Withdrawn or Scheduled for Withdrawal
8 References

1 Scope of the Chapter

The main aim of this chapter is to assist you in finding a function which approximates a set of data points. Typically the data contain random errors, as of experimental measurement, which need to be smoothed out. To seek an approximation to the data, it is first necessary to specify for the approximating function a mathematical form (a polynomial, for example) which contains a number of unspecified coefficients: the appropriate fitting routine then derives for the coefficients the values which provide the best fit of that particular form. The chapter deals mainly with curve and surface fitting (i.e., fitting with functions of one and of two variables) when a polynomial or a cubic spline is used as the fitting function, since these cover the most common needs. However, fitting with other functions and/or more variables can be undertaken by means of general linear or nonlinear routines (some of which are contained in other chapters) depending on whether the coefficients in the function occur linearly or nonlinearly. Cases where a graph rather than a set of data points is given can be treated simply by first reading a suitable set of points from the graph.
The chapter also contains routines for evaluating, differentiating and integrating polynomial and spline curves and surfaces, once the numerical values of their coefficients have been determined.
There is also a routine for computing a Padé approximant of a mathematical function (see Sections 2.6 and 3.8).

2 Background to the Problems

2.1 Preliminary Considerations

In the curve-fitting problems considered in this chapter, we have a dependent variable y and an independent variable x, and we are given a set of data points xr,yr, for r=1,2,…,m. The preliminary matters to be considered in this section will, for simplicity, be discussed in this context of curve-fitting problems. In fact, however, these considerations apply equally well to surface and higher-dimensional problems. Indeed, the discussion presented carries over essentially as it stands if, for these cases, we interpret x as a vector of several independent variables and correspondingly each xr as a vector containing the rth data value of each independent variable.
We wish, then, to approximate the set of data points as closely as possible with a specified function, f x say, which is as smooth as possible: f x may, for example, be a polynomial. The requirements of smoothness and closeness conflict, however, and a balance has to be struck between them. Most often, the smoothness requirement is met simply by limiting the number of coefficients allowed in the fitting function – for example, by restricting the degree in the case of a polynomial. Given a particular number of coefficients in the function in question, the fitting routines of this chapter determine the values of the coefficients such that the ‘distance’ of the function from the data points is as small as possible. The necessary balance is struck when you compare a selection of such fits having different numbers of coefficients. If the number of coefficients is too low, the approximation to the data will be poor. If the number is too high, the fit will be too close to the data, essentially following the random errors and tending to have unwanted fluctuations between the data points. Between these extremes, there is often a group of fits all similarly close to the data points and then, particularly when least squares polynomials are used, the choice is clear: it is the fit from this group having the smallest number of coefficients.
You are in effect minimizing the smoothness measure (i.e., the number of coefficients) subject to the distance from the data points being acceptably small. Some of the routines, however, do this task themselves. They use a different measure of smoothness (in each case one that is continuous) and minimize it subject to the distance being less than a threshold specified by you. This is a much more automatic process, requiring only some experimentation with the threshold.

2.1.1 Fitting criteria: norms

A measure of the above ‘distance’ between the set of data points and the function f x is needed. The distance from a single data point xr,yr to the function can simply be taken as
εr=yr-f xr, (1)
and is called the residual of the point. (With this definition, the residual is regarded as a function of the coefficients contained in f x; however, the term is also used to mean the particular value of εr which corresponds to the fitted values of the coefficients.) However, we need a measure of distance for the set of data points as a whole. Three different measures are used in the different routines (which measure to select, according to circumstances, is discussed later in this sub-section). With εr defined in (1), these measures, or norms, are
∑r=1 m εr, (2)
∑r=1 m εr 2, (3)
and
maxr εr, (4)
respectively the ℓ 1 norm, the ℓ 2 norm and the ℓ∞ norm.
Minimization of one or other of these norms usually provides the fitting criterion, the minimization being carried out with respect to the coefficients in the mathematical form used for f x: with respect to the bi for example if the mathematical form is the power series in (8) below. The fit which results from minimizing (2) is known as the ℓ 1 fit, or the fit in the ℓ 1 norm: that which results from minimizing (3) is the ℓ 2 fit, the well-known least squares fit (minimizing (3) is equivalent to minimizing the square of (3), i.e., the sum of squares of residuals, and it is the latter which is used in practice), and that from minimizing (4) is the ℓ∞, or minimax, fit.
Strictly speaking, implicit in the use of the above norms are the statistical assumptions that the random errors in the yr are independent of one another and that any errors in the xr are negligible by comparison. From this point of view, the use of the ℓ 2 norm is appropriate when the random errors in the yr have a Normal distribution, and the ℓ∞ norm is appropriate when they have a rectangular distribution, as when fitting a table of values rounded to a fixed number of decimal places. The ℓ 1 norm is appropriate when the error distribution has its frequency function proportional to the negative exponential of the modulus of the normalized error – not a common situation.
However, it may be that you are indifferent to these statistical considerations, and simply seek a fit which can be assessed by inspection, perhaps visually from a graph of the results. In this event, the ℓ 1 norm is particularly appropriate when the data are thought to contain some ‘wild’ points (since fitting in this norm tends to be unaffected by the presence of a small number of such points), though of course in simple situations you may prefer to identify and reject these points. The ℓ∞ norm should be used only when the maximum residual is of particular concern, as may be the case for example when the data values have been obtained by accurate computation, as of a mathematical function. Generally, however, a routine based on least squares should be preferred, as being computationally faster and usually providing more information on which to assess the results. In many problems the three fits will not differ significantly for practical purposes.
Some of the routines based on the ℓ 2 norm do not minimize the norm itself but instead minimize some (intuitively acceptable) measure of smoothness subject to the norm being less than a user-specified threshold. These routines fit with cubic or bicubic splines (see (10) and (14) below) and the smoothing measures relate to the size of the discontinuities in their third derivatives. A much more automatic fitting procedure follows from this approach.

2.1.2 Weighting of data points

The use of the above norms also assumes that the data values yr are of equal (absolute) accuracy. Some of the routines enable an allowance to be made to take account of differing accuracies. The allowance takes the form of ‘weights’ applied to the y values so that those values known to be more accurate have a greater influence on the fit than others. These weights, to be supplied by you, should be calculated from estimates of the absolute accuracies of the y values, these estimates being expressed as standard deviations, probable errors or some other measure which has the same dimensions as y. Specifically, for each yr the corresponding weight wr should be inversely proportional to the accuracy estimate of yr. For example, if the percentage accuracy is the same for all yr, then the absolute accuracy of yr is proportional to yr (assuming yr to be positive, as it usually is in such cases) and so wr=K/yr, for r=1,2,…,m, for an arbitrary positive constant K. (This definition of weight is stressed because often weight is defined as the square of that used here.) The norms (2), (3) and (4) above are then replaced respectively by
∑r=1 m wrεr, (5)
∑r=1 m wr 2εr 2, (6)
and
maxr wrεr. (7)
Again it is the square of (6) which is used in practice rather than (6) itself.

2.2 Curve Fitting

When, as is commonly the case, the mathematical form of the fitting function is immaterial to the problem, polynomials and cubic splines are to be preferred because their simplicity and ease of handling confer substantial benefits. The cubic spline is the more versatile of the two. It consists of a number of cubic polynomial segments joined end to end with continuity in first and second derivatives at the joins. The third derivative at the joins is in general discontinuous. The x values of the joins are called knots, or, more precisely, interior knots. Their number determines the number of coefficients in the spline, just as the degree determines the number of coefficients in a polynomial.

2.2.1 Representation of polynomials

Two different forms for representing a polynomial are used in different routines. One is the usual power-series form
f x≡b 0+b 1 x+b 2 x 2+⋯+bk xk. (8)
The other is the Chebyshev series form
f x≡12 a 0T 0 x+a 1T 1 x+a 2T 2 x+⋯+akTk x, (9)
where Ti x is the Chebyshev polynomial of the first kind of degree i (see page 9 of Cox and Hayes (1973)), and where the range of x has been normalized to run from -1 to +1. The use of either form leads theoretically to the same fitted polynomial, but in practice results may differ substantially because of the effects of rounding error. The Chebyshev form is to be preferred, since it leads to much better accuracy in general, both in the computation of the coefficients and in the subsequent evaluation of the fitted polynomial at specified points. This form also has other advantages: for example, since the later terms in (9) generally decrease much more rapidly from left to right than do those in (8), the situation is more often encountered where the last terms are negligible and it is obvious that the degree of the polynomial can be reduced (note that on the interval -1≤x≤1 for all i, Ti x attains the value unity but never exceeds it, so that the coefficient ai gives directly the maximum value of the term containing it). If the power-series form is used it is most advisable to work with the variable x normalized to the range -1 to +1, carrying out the normalization before entering the relevant routine. This will often substantially improve computational accuracy.

2.2.2 Representation of cubic splines

A cubic spline is represented in the form
f x≡c 1N 1 x+c 2N 2 x+⋯+cpNp x, (10)
where Ni x, for i=1,2,…,p, is a normalized cubic B-spline (see Hayes (1974)). This form, also, has advantages of computational speed and accuracy over alternative representations.

2.3 Surface Fitting

There are now two independent variables, and we shall denote these by x and y. The dependent variable, which was denoted by y in the curve-fitting case, will now be denoted by f. (This is a rather different notation from that indicated for the general-dimensional problem in the first paragraph of Section 2.1, but it has some advantages in presentation.)
Again, in the absence of contrary indications in the particular application being considered, polynomials and splines are the approximating functions most commonly used.

2.3.1 Representation of bivariate polynomials

The type of bivariate polynomial currently considered in the chapter can be represented in either of the two forms
f x,y≡∑i=0 k∑j=0 ℓ b ij xiyj, (11)
and
f x,y ≡ ∑′ i=0 k ∑′ j=0 ℓ a ij Ti x Tj y, (12)
where Ti x is the Chebyshev polynomial of the first kind of degree i in the parameter x (see page 9 of Cox and Hayes (1973)), and correspondingly for Tj y. The prime on the two summation signs, following standard convention, indicates that the first term in each sum is halved, as shown for one variable in equation (9). The two forms (11) and (12) are mathematically equivalent, but again the Chebyshev form is to be preferred on numerical grounds, as discussed in Section 2.2.1.

2.3.2 Bicubic splines: definition and representation

The bicubic spline is defined over a rectangle R in the x,y plane, the sides of R being parallel to the x and y axes. R is divided into rectangular panels, again by lines parallel to the axes. Over each panel the bicubic spline is a bicubic polynomial, that is it takes the form
∑i=0 3∑j=0 3 a ij xiyj. (13)
Each of these polynomials joins the polynomials in adjacent panels with continuity up to the second derivative. The constant x values of the dividing lines parallel to the y-axis form the set of interior knots for the variable x, corresponding precisely to the set of interior knots of a cubic spline. Similarly, the constant y values of dividing lines parallel to the x-axis form the set of interior knots for the variable y. Instead of representing the bicubic spline in terms of the above set of bicubic polynomials, however, it is represented, for the sake of computational speed and accuracy, in the form
f x,y=∑i=1 p∑j=1 q c ijMi x Nj y, (14)
where Mi x, for i=1,2,…,p, and Nj y, for j=1,2,…,q, are normalized B-splines (see Hayes and Halliday (1974) for further details of bicubic splines and Hayes (1974) for normalized B-splines).

2.4 General Linear and Nonlinear Fitting Functions

We have indicated earlier that, unless the data-fitting application under consideration specifically requires some other type of fit, a polynomial or a spline is usually to be preferred. Special routines for these types, in one and in two variables, are provided in this chapter. When the application does specify some other form of fitting, however, it may be treated by a routine which deals with a general linear function, or by one for a general nonlinear function, depending on whether the coefficients occur linearly or nonlinearly.
The general linear fitting function can be written in the form
f x≡c 1ϕ 1 x+c 2ϕ 2 x+⋯+cpϕp x, (15)
where x is a vector of one or more independent variables, and the ϕi are any given functions of these variables (though they must be linearly independent of one another if there is to be the possibility of a unique solution to the fitting problem). This is not intended to imply that each ϕi is necessarily a function of all the variables: we may have, for example, that each ϕi is a function of a different single variable, and even that one of the ϕi is a constant. All that is required is that a value of each ϕi x can be computed when a value of each independent variable is given.
When the fitting function f x is not linear in its coefficients, no more specific representation is available in general than f x itself. However, we shall find it helpful later on to indicate the fact that f x contains a number of coefficients (to be determined by the fitting process) by using instead the notation f x;c, where c denotes the vector of coefficients. An example of a nonlinear fitting function is
f x;c≡c 1+c 2 exp-c 4 x+c 3 exp-c 5 x, (16)
which is in one variable and contains five coefficients. Note that here, as elsewhere in this Chapter Introduction, we use the term ‘coefficients’ to include all the quantities whose values are to be determined by the fitting process, not just those which occur linearly. We may observe that it is only the presence of the coefficients c 4 and c 5 which makes the form (16) nonlinear. If the values of these two coefficients were known beforehand, (16) would instead be a linear function which, in terms of the general linear form (15), has p=3 and
ϕ 1 x≡1,ϕ 2 x≡exp-c 4 x,and ​ϕ 3 x≡exp-c 5 x.
We may note also that polynomials and splines, such as (9) and (14), are themselves linear in their coefficients. Thus if, when fitting with these functions, a suitable special routine is not available (as when more than two independent variables are involved or when fitting in the ℓ 1 norm), it is appropriate to use a routine designed for a general linear function.

2.5 Constrained Problems

So far, we have considered only fitting processes in which the values of the coefficients in the fitting function are determined by an unconstrained minimization of a particular norm. Some fitting problems, however, require that further restrictions be placed on the determination of the coefficient values. Sometimes these restrictions are contained explicitly in the formulation of the problem in the form of equalities or inequalities which the coefficients, or some function of them, must satisfy. For example, if the fitting function contains a term A exp-kx, it may be required that k≥0. Often, however, the equality or inequality constraints relate to the value of the fitting function or its derivatives at specified values of the independent variable(s), but these too can be expressed in terms of the coefficients of the fitting function, and it is appropriate to do this if a general linear or nonlinear routine is being used. For example, if the fitting function is that given in (10), the requirement that the first derivative of the function at x=x 0 be non-negative can be expressed as
c 1 N 1′x 0+c 2 N 2′x 0+⋯+cp Np′x 0≥0, (17)
where the prime denotes differentiation with respect to x and each derivative is evaluated at x=x 0. On the other hand, if the requirement had been that the derivative at x=x 0 be exactly zero, the inequality sign in (17) would be replaced by an equality.
Routines which provide a facility for minimizing the appropriate norm subject to such constraints are discussed in Section 3.6.

2.6 Padé Approximants

A Padé approximant to a function f x is a rational function (ratio of two polynomials) whose Maclaurin series expansion is the same as that of f x up to and including the term in xk, where k is the sum of the degrees of the numerator and denominator of the approximant. Padé approximation can be a useful technique when values of a function are to be obtained from its Maclaurin series but convergence of the series is unacceptably slow or even nonexistent.

3 Recommendations on Choice and Use of Available Routines

3.1 General

The choice of a routine to treat a particular fitting problem will depend first of all on the fitting function and the norm to be used. Unless there is good reason to the contrary, the fitting function should be a polynomial or a cubic spline (in the appropriate number of variables) and the norm should be the ℓ 2 norm (leading to the least squares fit). If some other function is to be used, the choice of routine will depend on whether the function is nonlinear (in which case see Section 3.5.2) or linear in its coefficients (see Section 3.5.1), and, in the latter case, on whether the ℓ 1, ℓ 2 or ℓ∞ norm is to be used. The latter section is appropriate for polynomials and splines, too, if the ℓ 1 or ℓ∞ norm is preferred, with one exception: there is a special routine for fitting polynomial curves in the unweighted ℓ∞ norm (see Section 3.2.3).
In the case of a polynomial or cubic spline, if there is only one independent variable, you should choose a spline (see Section 3.3) when the curve represented by the data is of complicated form, perhaps with several peaks and troughs. When the curve is of simple form, first try a polynomial (see Section 3.2) of low degree, say up to degree 5 or 6, and then a spline if the polynomial fails to provide a satisfactory fit. (Of course, if third-derivative discontinuities are unacceptable, a polynomial is the only choice.) If the problem is one of surface fitting, the polynomial routine (see Section 3.4.1) should be tried first if the data arrangement happens to be appropriate, otherwise one of the spline routines (see Section 3.4.3). If the problem has more than two independent variables, it may be treated by the general linear routine in Section 3.5.1, again using a polynomial in the first instance.
Another factor which affects the choice of routine is the presence of constraints, as previously discussed on Section 2.5. Indeed this factor is likely to be overriding at present, because of the limited number of routines which have the necessary facility. Consequently those routines have been grouped together for discussion in Section 3.6.

3.1.1 Data considerations

A satisfactory fit cannot be expected by any means if the number and arrangement of the data points do not adequately represent the character of the underlying relationship: sharp changes in behaviour, in particular, such as sharp peaks, should be well covered. Data points should extend over the whole range of interest of the independent variable(s): extrapolation outside the data ranges is most unwise. Then, with polynomials, it is advantageous to have additional points near the ends of the ranges, to counteract the tendency of polynomials to develop fluctuations in these regions. When, with polynomial curves, you can precisely choose the x values of the data, the special points defined in Section 3.2.2 should be selected. With polynomial surfaces, each of these same x values should, where possible, be combined with each of a corresponding set of y values (not necessarily with the same value of n), thus forming a rectangular grid of x,y-values. With splines the choice is less critical as long as the character of the relationship is adequately represented. All fits should be tested graphically before accepting them as satisfactory.
For this purpose it should be noted that it is not sufficient to plot the values of the fitted function only at the data values of the independent variable(s); at the least, its values at a similar number of intermediate points should also be plotted, as unwanted fluctuations may otherwise go undetected. Such fluctuations are the less likely to occur the lower the number of coefficients chosen in the fitting function. No firm guide can be given, but as a rough rule, at least initially, the number of coefficients should not exceed half the number of data points (points with equal or nearly equal values of the independent variable, or both independent variables in surface fitting, counting as a single point for this purpose). However, the situation may be such, particularly with a small number of data points, that a satisfactorily close fit to the data cannot be achieved without unwanted fluctuations occurring. In such cases, it is often possible to improve the situation by a transformation of one or more of the variables, as discussed in the next section: otherwise it will be necessary to provide extra data points. Further advice on curve-fitting is given in Cox and Hayes (1973) and, for polynomials only, in Hayes (1970). Much of the advice applies also to surface fitting; see also the routine documents.

3.1.2 Transformation of variables

Before starting the fitting, consideration should be given to the choice of a good form in which to deal with each of the variables: often it will be satisfactory to use the variables as they stand, but sometimes the use of the logarithm, square root, or some other function of a variable will lead to a better-behaved relationship. This question is customarily taken into account in preparing graphs and tables of a relationship and the same considerations apply when curve or surface fitting. The practical context will often give a guide. In general, it is best to avoid having to deal with a relationship whose behaviour in one region is radically different from that in another. A steep rise at the left-hand end of a curve, for example, can often best be treated by curve-fitting in terms of log x+c with some suitable value of the constant c. A case when such a transformation gave substantial benefit is discussed in page 60 of Hayes (1970). According to the features exhibited in any particular case, transformation of either dependent variable or independent variable(s) or both may be beneficial. When there is a choice it is usually better to transform the independent variable(s): if the dependent variable is transformed, the weights attached to the data points must be adjusted. Thus (denoting the dependent variable by y, as in the notation for curves) if the yr to be fitted have been obtained by a transformation y=g Y from original data values Yr, with weights Wr, for r=1,2,…,m, we must take
wr=Wr/dy/dY, (18)
where the derivative is evaluated at Yr. Strictly, the transformation of Y and the adjustment of weights are valid only when the data errors in the Yr are small compared with the range spanned by the Yr, but this is usually the case.

3.2 Polynomial Curves

3.2.1 Least squares polynomials: arbitrary data points

E02ADF fits to arbitrary data points, with arbitrary weights, polynomials of all degrees up to a maximum degree k, which is a choice. If you are seeking only a low-degree polynomial, up to degree 5 or 6 say, k=10 is an appropriate value, providing there are about 20 data points or more. To assist in deciding the degree of polynomial which satisfactorily fits the data, the routine provides the root-mean-square residual si for all degrees i=1,2,…,k. In a satisfactory case, these si will decrease steadily as i increases and then settle down to a fairly constant value, as shown in the example
i si 0 3.5215 1 0.7708 2 0.1861 3 0.0820 4 0.0554 5 0.0251 6 0.0264 7 0.0280 8 0.0277 9 0.0297 10 0.0271
If the si values settle down in this way, it indicates that the closest polynomial approximation justified by the data has been achieved. The degree which first gives the approximately constant value of si (degree 5 in the example) is the appropriate degree to select. (If you are prepared to accept a fit higher than sixth degree you should simply find a high enough value of k to enable the type of behaviour indicated by the example to be detected: thus you should seek values of k for which at least 4 or 5 consecutive values of si are approximately the same.) If the degree were allowed to go high enough, si would, in most cases, eventually start to decrease again, indicating that the data points are being fitted too closely and that undesirable fluctuations are developing between the points. In some cases, particularly with a small number of data points, this final decrease is not distinguishable from the initial decrease in si. In such cases, you may seek an acceptable fit by examining the graphs of several of the polynomials obtained. Failing this, you may (a) seek a transformation of variables which improves the behaviour, (b) try fitting a spline, or (c) provide more data points. If data can be provided simply by drawing an approximating curve by hand and reading points from it, use the points discussed in Section 3.2.2.

3.2.2 Least squares polynomials: selected data points

When you are at liberty to choose the x values of data points, such as when the points are taken from a graph, it is most advantageous when fitting with polynomials to use the values xr=cos πr/n, for r=0,1,…,n for some value of n, a suitable value for which is discussed at the end of this section. Note that these xr relate to the variable x after it has been normalized so that its range of interest is -1 to +1. E02ADF may then be used as in Section 3.2.1 to seek a satisfactory fit. However, if the ordinate values are of equal weight, as would often be the case when they are read from a graph, E02AFF is to be preferred, as being simpler to use and faster. This latter algorithm provides the coefficients aj, for j=0,1,…,n, in the Chebyshev series form of the polynomial of degree n which interpolates the data. In a satisfactory case, the later coefficients in this series, after some initial significant ones, will exhibit a random behaviour, some positive and some negative, with a size about that of the errors in the data or less. All these ‘random’ coefficients should be discarded, and the remaining (initial) terms of the series be taken as the approximating polynomial. This truncated polynomial is a least squares fit to the data, though with the point at each end of the range given half the weight of each of the other points. The following example illustrates a case in which degree 5 or perhaps 6 would be chosen for the approximating polynomial.
j aj 0 0 9.315 1 -8.030 2 0.303 3 -1.483 4 0.256 5 -0.386 6 0.076 7 0.022 8 0.014 9 0.005 10 0.011 11 -0.040 12 0.017 13 -0.054 14 0.010 15 -0.034 16 -0.001
Basically, the value of n used needs to be large enough to exhibit the type of behaviour illustrated in the above example. A value of 16 is suggested as being satisfactory for very many practical problems, the required cosine values for this value of n being given on page 11 of Cox and Hayes (1973). If a satisfactory fit is not obtained, a spline fit should be tried, or, if you are prepared to accept a higher degree of polynomial, n should be increased: doubling n is an advantageous strategy, since the set of values cos πr/n, for r=0,1,…,n, contains all the values of cos πr/2 n, for r=0,1,…,n, so that the old dataset will then be re-used in the new one. Thus, for example, increasing n from 16 to 32 will require only 16 new data points, a smaller number than for any other increase of n. If data points are particularly expensive to obtain, a smaller initial value than 16 may be tried, provided you are satisfied that the number is adequate to reflect the character of the underlying relationship. Again, the number should be doubled if a satisfactory fit is not obtained.

3.2.3 Minimax space polynomials

E02ALF determines the polynomial of given degree which is a minimax space fit to arbitrary data points with equal weights. (If unequal weights are required, the polynomial must be treated as a general linear function and fitted using E02GCF.) To arrive at a satisfactory degree it will be necessary to try several different degrees and examine the results graphically. Initial guidance can be obtained from the value of the maximum residual: this will vary with the degree of the polynomial in very much the same way as does si in least squares fitting, but it is much more expensive to investigate this behaviour in the same detail.
The algorithm uses the power-series form of the polynomial so for numerical accuracy it is advisable to normalize the data range of x to -1,1.

3.3 Cubic Spline Curves

3.3.1 Least squares cubic splines

E02BAF fits to arbitrary data points, with arbitrary weights, a cubic spline with interior knots specified by you. The choice of these knots so as to give an acceptable fit must largely be a matter of trial and error, though with a little experience a satisfactory choice can often be made after one or two trials. It is usually best to start with a small number of knots (too many will result in unwanted fluctuations in the fit, or even in there being no unique solution) and, examining the fit graphically at each stage, to add a few knots at a time at places where the fit is particularly poor. Moving the existing knots towards these places will also often improve the fit. In regions where the behaviour of the curve underlying the data is changing rapidly, closer knots will be needed than elsewhere. Otherwise, positioning is not usually very critical and equally-spaced knots are often satisfactory. See also the next section, however.
A useful feature of the routine is that it can be used in applications which require the continuity to be less than the normal continuity of the cubic spline. For example, the fit may be required to have a discontinuous slope at some point in the range. This can be achieved by placing three coincident knots at the given point. Similarly a discontinuity in the second derivative at a point can be achieved by placing two knots there. Analogy with these discontinuous cases can provide guidance in more usual cases: for example, just as three coincident knots can produce a discontinuity in slope, so three close knots can produce a rapid change in slope. The closer the knots are, the more rapid can the change be.
An example set of data is given in Figure 1. It is a rather tricky set, because of the scarcity of data on the right, but it will serve to illustrate some of the above points and to show some of the dangers to be avoided. Three interior knots (indicated by the vertical lines at the top of the diagram) are chosen as a start. We see that the resulting curve is not steep enough in the middle and fluctuates at both ends, severely on the right. The spline is unable to cope with the shape and more knots are needed.
Figure 1
Figure 2
Figure 3
In Figure 2, three knots have been added in the centre, where the data shows a rapid change in behaviour, and one further out at each end, where the fit is poor. The fit is still poor, so a further knot is added in this region and, in Figure 3, disaster ensues in rather spectacular fashion.
The reason is that, at the right-hand end, the fits in Figures 1 and 2 have been interpreted as poor simply because of the fluctuations about the curve underlying the data (or what it is naturally assumed to be). But the fitting process knows only about the data and nothing else about the underlying curve, so it is important to consider only closeness to the data when deciding goodness-of-fit.
Thus, in Figure 1, the curve fits the last two data points quite well compared with the fit elsewhere, so no knot should have been added in this region. In Figure 2, the curve goes exactly through the last two points, so a further knot is certainly not needed here.
Figure 4 shows what can be achieved without the extra knot on each of the flat regions. Remembering that within each knot interval the spline is a cubic polynomial, there is really no need to have more than one knot interval covering each flat region.
Figure 4
What we have, in fact, in Figures 2 and 3 is a case of too many knots (so too many coefficients in the spline equation) for the number of data points. The warning in the second paragraph of Section 2.1 was that the fit will then be too close to the data, tending to have unwanted fluctuations between the data points. The warning applies locally for splines, in the sense that, in localities where there are plenty of data points, there can be a lot of knots, as long as there are few knots where there are few points, especially near the ends of the interval. In the present example, with so few data points on the right, just the one extra knot in Figure 2 is too many! The signs are clearly present, with the last two points fitted exactly (at least to the graphical accuracy and actually much closer than that) and fluctuations within the last two knot-intervals (see Figure 1, where only the final point is fitted exactly and one of the wobbles spans several data points).
The situation in Figure 3 is different. The fit, if computed exactly, would still pass through the last two data points, with even more violent fluctuations. However, the problem has become so ill-conditioned that all accuracy has been lost. Indeed, if the last interior knot were moved a tiny amount to the right, there would be no unique solution and an error message would have been caused. Near-singularity is, sadly, not picked up by the routine, but can be spotted readily in a graph, as Figure 3. B-spline coefficients becoming large, with alternating signs, is another indication. However, it is better to avoid such situations, firstly by providing, whenever possible, data adequately covering the range of interest, and secondly by placing knots only where there is a reasonable amount of data.
The example here could, in fact, have utilized from the start the observation made in the second paragraph of this section, that three close knots can produce a rapid change in slope. The example has two such rapid changes and so requires two sets of three close knots (in fact, the two sets can be so close that one knot can serve in both sets, so only five knots prove sufficient in Figure 4). It should be noted, however, that the rapid turn occurs within the range spanned by the three knots. This is the reason that the six knots in Figure 2 are not satisfactory as they do not quite span the two turns.
Some more examples to illustrate the choice of knots are given in Cox and Hayes (1973).

3.3.2 Automatic fitting with cubic splines

E02BEF fits cubic splines to arbitrary data points with arbitrary weights but itself chooses the number and positions of the knots. You have to supply only a threshold for the sum of squares of residuals. The routine first builds up a knot set by a series of trial fits in the ℓ 2 norm. Then, with the knot set decided, the final spline is computed to minimize a certain smoothing measure subject to satisfaction of the chosen threshold. Thus it is easier to use than E02BAF (see the previous section), requiring only some experimentation with this threshold. It should therefore be first choice unless you have a preference for the ordinary least squares fit or, for example, if you wish to experiment with knot positions, trying to keep their number down (E02BEF aims only to be reasonably frugal with knots).

3.4 Polynomial and Spline Surfaces

3.4.1 Least squares polynomials

E02CAF fits bivariate polynomials of the form (12), with k and ℓ specified by you, to data points in a particular, but commonly occurring, arrangement. This is such that, when the data points are plotted in the plane of the independent variables x and y, they lie on lines parallel to the x-axis. Arbitrary weights are allowed. The matter of choosing satisfactory values for k and ℓ is discussed in Section 9 in E02CAF.

3.4.2 Least squares bicubic splines

E02DAF fits to arbitrary data points, with arbitrary weights, a bicubic spline with its two sets of interior knots specified by you. For choosing these knots, the advice given for cubic splines, in Section 3.3.1 above, applies here too (see also the next section, however). If changes in the behaviour of the surface underlying the data are more marked in the direction of one variable than of the other, more knots will be needed for the former variable than the latter. Note also that, in the surface case, the reduction in continuity caused by coincident knots will extend across the whole spline surface: for example, if three knots associated with the variable x are chosen to coincide at a value L, the spline surface will have a discontinuous slope across the whole extent of the line x=L.
With some sets of data and some choices of knots, the least squares bicubic spline will not be unique. This will not occur, with a reasonable choice of knots, if the rectangle R is well covered with data points: here R is defined as the smallest rectangle in the x,y plane, with sides parallel to the axes, which contains all the data points. Where the least squares solution is not unique, the minimal least squares solution is computed, namely that least squares solution which has the smallest value of the sum of squares of the B-spline coefficients c ij (see the end of Section 2.3.2 above). This choice of least squares solution tends to minimize the risk of unwanted fluctuations in the fit. The fit will not be reliable, however, in regions where there are few or no data points.

3.4.3 Automatic fitting with bicubic splines

E02DDF fits bicubic splines to arbitrary data points with arbitrary weights but chooses the knot sets itself. You have to supply only a threshold for the sum of squares of residuals. Just like the automatic curve, E02BEF (see Section 3.3.2), E02DDF then builds up the knot sets and finally fits a spline minimizing a smoothing measure subject to satisfaction of the threshold. Again, this easier to use routine is normally to be preferred, at least in the first instance.
E02DCF is a very similar routine to E02DDF but deals with data points of equal weight which lie on a rectangular mesh in the x,y plane. This kind of data allows a very much faster computation and so is to be preferred when applicable. Substantial departures from equal weighting can be ignored if you are not concerned with statistical questions, though the quality of the fit will suffer if this is taken too far. In such cases, you should revert to E02DDF.

3.4.4 Large data sets

For fitting large sets of equally weighted, arbitrary data points, E02JDF provides a two stage method where local, least squares, polynomial fits are extended to form a C 1 surface.

3.5 General Linear and Nonlinear Fitting Functions

3.5.1 General linear functions

For the general linear function (15), routines are available for fitting in all three norms. The least squares routines (which are to be preferred unless there is good reason to use another norm – see Section 2.1.1) are in Chapters F04 and F08. The ℓ∞ routine is E02GCF. Two routines for the ℓ 1 norm are provided, E02GAF and E02GBF. Of these two, the former should be tried in the first instance, since it will be satisfactory in most cases, has a much shorter code and is faster. E02GBF, however, uses a more stable computational algorithm and therefore may provide a solution when E02GAF fails to do so. It also provides a facility for imposing linear inequality constraints on the solution (see Section 3.6).
All the above routines are essentially linear algebra routines, and in considering their use we need to view the fitting process in a slightly different way from hitherto. Taking y to be the dependent variable and x the vector of independent variables, we have, as for equation (1) but with each xr now a vector,
εr=yr-f xr,  r=1,2,…,m.
Substituting for f x the general linear form (15), we can write this as
c 1ϕ 1 xr+c 2ϕ 2 xr+⋯+cpϕp xr=yr-εr,  r=1,2,…,m. (19)
Thus we have a system of linear equations in the coefficients cj. Usually, in writing these equations, the εr are omitted and simply taken as implied. The system of equations is then described as an overdetermined system (since we must have m≥p if there is to be the possibility of a unique solution to our fitting problem), and the fitting process of computing the cj to minimize one or other of the norms (2), (3) and (4) can be described, in relation to the system of equations, as solving the overdetermined system in that particular norm. In matrix notation, the system can be written as
Φc=y, (20)
where Φ is the m by p matrix whose element in row r and column j is ϕj xr, for r=1,2,…,m and j=1,2,…,p. The vectors c and y respectively contain the coefficients cj and the data values yr.
All four routines, however, use the standard notation of linear algebra, the overdetermined system of equations being denoted by
Ax=b. (21)
(In fact, F04AMF can deal with several right-hand sides simultaneously, and thus is concerned with a matrix of right-hand sides, denoted by B, instead of the single vector b, and correspondingly with a matrix X of solutions instead of the single vector x.) The correspondence between this notation and that which we have used for the data-fitting problem (20) is therefore given by
A≡Φ, x≡c, b≡y. (22)
Note that the norms used by these routines are the unweighted norms (2), (3) and (4). If you wish to apply weights to the data points, that is to use the norms (5), (6) or (7), the equivalences (22) should be replaced by
A≡D Φ, x≡c, b≡Dy,
where D is a diagonal matrix with wr as the rth diagonal element. Here wr, for r=1,2,…,m, is the weight of the rth data point as defined in Section 2.1.2.

3.5.2 Nonlinear functions

Routines for fitting with a nonlinear function in the ℓ 2 norm are provided in Chapter E04. Consult the E04 Chapter Introduction for the appropriate choice of routine. Again, however, the notation adopted is different from that we have used for data fitting. In the latter, we denote the fitting function by f x;c, where x is the vector of independent variables and c is the vector of coefficients, whose values are to be determined. The squared ℓ 2 norm, to be minimized with respect to the elements of c, is then
∑r=1 m wr 2 yr-f xr;c 2 (23)
where yr is the rth data value of the dependent variable, xr is the vector containing the rth values of the independent variables, and wr is the corresponding weight as defined in Section 2.1.2.
On the other hand, in the nonlinear least squares routines of Chapter E04, the function to be minimized is denoted by
∑i=1 m fi 2 x, (24)
the minimization being carried out with respect to the elements of the vector x. The correspondence between the two notations is given by
x≡c​ and ​fi x≡wr yr-f xr;c,  i=r=1,2,…,m.
Note especially that the vector x of variables of the nonlinear least squares routines is the vector c of coefficients of the data-fitting problem, and in particular that, if the selected routine requires derivatives of the fi x to be provided, these are derivatives of wr yr-f xr;c with respect to the coefficients of the data-fitting problem.

3.6 Constraints

At present, there are only a limited number of routines which fit subject to constraints. E02GBF allows the imposition of linear inequality constraints (the inequality (17) for example) when fitting with the general linear function in the ℓ 1 norm. In addition, Chapter E04 contains a routine, E04USF/E04USA, which can be used for fitting with a nonlinear function in the ℓ 2 norm subject to general equality or inequality constraints.
The remaining two constraint routines relate to fitting with polynomials in the ℓ 2 norm. E02AGF deals with polynomial curves and allows precise values of the fitting function and (if required) all its derivatives up to a given order to be prescribed at one or more values of the independent variable. The related surface-fitting E02CAF, designed for data on lines as discussed in Section 3.4.1, has a feature which permits precise values of the function and its derivatives to be imposed all along one or more lines parallel to the x or y axes (see the routine document for the relationship between these normalized variables and your original variables). In this case, however, the prescribed values cannot be supplied directly to the routine: instead, you must provide modified data ordinates F r,s and polynomial factors γ 1 x and γ 2 x, as defined on page 95 of Hayes (1970).

3.7 Evaluation, Differentiation and Integration

Routines are available to evaluate, differentiate and integrate polynomials in Chebyshev series form and cubic or bicubic splines in B-spline form. These polynomials and splines may have been produced by the various fitting routines or, in the case of polynomials, from prior calls of the differentiation and integration routines themselves.
E02AEF and E02AKF evaluate polynomial curves: the latter has a longer argument list but does not require you to normalize the values of the independent variable and can accept coefficients which are not stored in contiguous locations. E02CBF evaluates polynomial surfaces, E02BBF cubic spline curves, E02DEF and E02DFF bicubic spline surfaces, and E02DHF bicubic spline surfaces with derivatives.
Differentiation and integration of polynomial curves are carried out by E02AHF and E02AJF respectively. The results are provided in Chebyshev series form and so repeated differentiation and integration are catered for. Values of the derivative or integral can then be computed using the appropriate evaluation routine. Polynomial surfaces can be treated by a sequence of calls of one or other of the same two routines, differentiating or integrating the form (12) piece by piece. For example, if, for some given value of j, the coefficients a ij, for i=0,1,…,k, are supplied to E02AHF, we obtain coefficients a-ij say, for i=0,1,…,k-1, which are the coefficients in the derivative with respect to x of the polynomial
∑′i=0 k a ijTi x.
If this is repeated for all values of j, we obtain all the coefficients in the derivative of the surface with respect to x, namely
∑′ i=0 k-1 ∑′j=0 ℓ a-ijTj y. (25)
The derivative of (12), or of (25), with respect to y can be obtained in a corresponding manner. In the latter case, for example, for each value of i in turn we supply the coefficients a-i 0,a-i 1,a-i 2,…, to the routine. Values of the resulting polynomials, such as (25), can subsequently be computed using E02CBF. It is important, however, to note one exception: the process described will not give valid results for differentiating or integrating a surface with respect to y if the normalization of x was made dependent upon y, an option which is available in the fitting routine E02CAF.
For splines the differentiation and integration routines provided are of a different nature from those for polynomials. E02BCF and E02BFF provide values of a cubic spline curve together with its first three derivatives (the rest, of course, are zero) at a given value, or vector of values, of x. E02BDF computes the value of the definite integral of a cubic spline over its whole range. Again the routines can be applied to surfaces, this time of the form (14). For example, if, for each value of j in turn, the coefficients c ij, for i=1,2,…,p, are supplied to E02BCF with x=x 0 and on each occasion we select from the output the value of the second derivative, dj say, and if the whole set of dj are then supplied to the same routine with x=y 0, the output will contain all the values at x 0,y 0 of
∂2 f ∂x 2   and   ∂r+2 f ∂x 2∂yr ,  r=1,2,3.
Equally, if after each of the first p calls of E02BCF we had selected the function value (E02BBF would also provide this) instead of the second derivative and we had supplied these values to E02BDF, the result obtained would have been the value of
∫AB f x 0,y dy,
where A and B are the end points of the y interval over which the spline was defined.

3.8 Padé Approximants

Given two non-negative integers ℓ and m, and the coefficients in the Maclaurin series expansion of a function up to degree ℓ+m, E02RAF calculates the Padé approximant of degree ℓ in the numerator and degree m in the denominator. See Sections 3 and 10 in E02RAF for further advice.
E02RBF is provided to compute values of the Padé approximant, once it has been obtained.

4 Decision Trees

Note: these Decision Trees are concerned with unconstrained fitting; for constrained fitting, consult Section 3.6.

Tree 1

Do you have reason to choose a type of fitting function other than polynomials or spline? |  |  | Are the fitting functions nonlinear? |  |  | See least squares routines in Chapter E04
 |  | yes |  |  | yes
 | no |  |  | no |
 |  |  | Do you prefer the ℓ 2 norm? |  |  | See the least squares routines in Chapters F04 and F08
 |  |  |  |  | yes
 |  |  |  | no |
 |  |  | Do you prefer the ℓ 1 norm? |  |  | E02GAF
 |  |  |  |  | yes
 |  |  |  | no |
 |  |  | Use the ℓ∞ norm, E02GCF
Does the problem have more than two independent variables? |  |  | Do you have a reason to prefer a norm other than the ℓ 2 norm? |  |  | Do you prefer the ℓ 1 norm? |  |  | E02GAF
 |  | yes |  |  | yes |  |  | yes
 | no |  |  | no |  |  | no |
 |  |  |  |  |  | use ℓ∞ norm, E02GCF
 |  |  | See the least squares routines in Chapters F04 and F08
Do you wish to use the ℓ 1 norm? |  |  | E02GAF
 |  | yes
 | no |
Is there just one independent variable (curve-fitting)? |  |  | Continue on Tree 2
 |  | yes
 | no |
Does the data have equal weights? |  |  | Does the data lie on a rectangular mesh? |  |  | E02DCF
 |  | yes |  |  | yes
 | no |  |  | no |
 |  |  | E02JDF
Are the data on lines? (see Section 3.4.1) |  |  | E02CAF
 |  | yes
 | no |
E02DDF or E02DAF

Tree 2

Do you wish to use the ℓ∞ norm? |  |  | Do you prefer splines? |  |  | E02GCF (using a spline basis)
 |  | yes |  |  | yes
 | no |  |  | no |
 |  |  | Have data points different weights? |  |  | E02GCF (using a polynomial basis)
 |  |  |  |  | yes
 |  |  |  | no |
 |  |  | E02ALF
Do you prefer polynomials? |  |  | Are the x values of data points different from the values defined in Section 3.2.2 or cannot be chosen to be so? |  |  | E02ADF
 |  | yes |  |  | yes
 | no |  |  | no |
 |  |  | Choose x values defined in Section 3.2.2. Have data points different weights? |  |  | E02ADF
 |  |  |  |  | yes
 |  |  |  | no |
 |  |  | E02AFF
Do you wish to use ℓ 2 norm? |  |  | E02BAF
 |  | yes
 | no |
E02BEF

5 Functionality Index

Automatic fitting,
with cubic splines E02BEF
Automatic knot placement,
with bicubic splines,
data on rectangular mesh E02DCF
Data on lines E02CAF
Data on rectangular mesh E02DCF
Differentiation,
of bicubic splines E02DHF
of polynomials E02AHF
Evaluation,
at a point,
of cubic splines E02BBF
of cubic splines and derivatives E02BCF
at vector of points,
of bicubic splines at vector of points E02DEF
of C1 scattered fit E02JEF
of cubic splines and optionally derivatives E02BFF
of polynomials,
in one variable E02AKF
in one variable (simple interface) E02AEF
in two variables E02CBF
of rational functions E02RBF
on mesh,
of bicubic splines E02DFF
of C1 scattered fit E02JFF
Integration,
of cubic splines (definite integral) E02BDF
of polynomials E02AJF
l1 fit,
with constraints E02GBF
with general linear function E02GAF
Least squares curve fit,
with cubic splines E02BAF
with polynomials,
arbitrary data points E02ADF
selected data points E02AFF
with constraints E02AGF
Least squares surface fit,
with bicubic splines E02DAF
with polynomials E02CAF
Minimax space fit,
with general linear function E02GCF
with polynomials in one variable E02ALF
Padé approximants E02RAF
Scattered data fit,
bicubic spline E02DDF
C1 spline E02JDF
Service routines,
general option getting routine E02ZLF
general option setting routine E02ZKF
Sorting E02ZAF

6 Auxiliary Routines Associated with Library Routine Arguments

None.

7 Routines Withdrawn or Scheduled for Withdrawal

The following lists all those routines that have been withdrawn since Mark 19 of the Library or are scheduled for withdrawal at one of the next two marks.
Withdrawn Routine | Mark of Withdrawal | Replacement Routine(s)
E02ACF | 27 | E02ALF

8 References

Baker G A (1975) Essentials of Padé Approximants Academic Press, New York
Cox M G and Hayes J G (1973) Curve fitting: a guide and suite of algorithms for the non-specialist user NPL Report NAC26 National Physical Laboratory
Hayes J G (ed.) (1970) Numerical Approximation to Functions and Data Athlone Press, London
Hayes J G (1974) Numerical methods for curve and surface fitting Bull. Inst. Math. Appl. 10 144–152
Hayes J G and Halliday J (1974) The least squares fitting of cubic spline surfaces to general data sets J. Inst. Math. Appl. 14 89–103
E02 Chapter Contents
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


E02JDF : NAG Library, Mark 26

E02 Chapter Contents
E02 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

E02JDF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.
Note: this routine uses optional parameters to define choices in the problem specification and in the details of the algorithm. If you wish to use default settings for all of the optional parameters, you need only read Sections 1 to 10 of this document. If, however, you wish to reset some or all of the settings please refer to Section 11 for a detailed description of the specification of the optional parameters produced by the routine.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results
▸▿ 11 Optional Parameters
11.1 Description of the Optional Parameters

1 Purpose

E02JDF computes a spline approximation to a set of scattered data using a two-stage approximation method.
The computational complexity of the method grows linearly with the number of data points; hence large datasets are easily accommodated.

2 Specification

SUBROUTINE E02JDF ( N, X, Y, F, LSMINP, LSMAXP, NXCELS, NYCELS, LCOEFS, COEFS, IOPTS, OPTS, IFAIL)
INTEGER | N, LSMINP, LSMAXP, NXCELS, NYCELS, LCOEFS, IOPTS(*), IFAIL
REAL (KIND=nag_wp) | X(N), Y(N), F(N), COEFS(LCOEFS), OPTS(*)
Before calling E02JDF, E02ZKF must be called with OPTSTR set to "Initialize = E02JDF". Settings for optional algorithmic arguments may be specified by calling E02ZKF before a call to E02JDF.

3 Description

E02JDF determines a smooth bivariate spline approximation to a set of data points xi,yi,fi, for i=1,2,…,n. Here, ‘smooth’ means C 1 or C 2. (You may select the degree of smoothing using the optional parameter Global Smoothing Level.)
The approximation domain is the bounding box xmin,xmax × ymin,ymax , where xmin (respectively ymin) and xmax (respectively ymax) denote the lowest and highest data values of the xi (respectively yi).
The spline is computed by local approximations on a uniform triangulation of the bounding box. These approximations are extended to a smooth spline representation of the surface over the domain. The local approximation scheme is controlled by the optional parameter Local Method. The schemes provided are: by least squares polynomial approximation (Davydov and Zeilfelder (2004)); by hybrid polynomial and radial basis function (RBF) approximation (Davydov et al. (2006)); or by pure RBF approximation (Davydov et al. (2005)).
The two-stage approximation method employed by E02JDF is derived from the TSFIT package of O. Davydov and F. Zeilfelder.
Values of the computed spline can subsequently be computed by calling E02JEF or E02JFF.

4 References

Davydov O, Morandi R and Sestini A (2006) Local hybrid approximation for scattered data fitting with bivariate splines Comput. Aided Geom. Design 23 703–721
Davydov O, Sestini A and Morandi R (2005) Local RBF approximation for scattered data fitting with bivariate splines Trends and Applications in Constructive Approximation M. G. de Bruin, D. H. Mache, and J. Szabados, Eds ISNM Vol. 151 Birkhauser 91–102
Davydov O and Zeilfelder F (2004) Scattered data fitting by direct extension of local polynomials to bivariate splines Advances in Comp. Math. 21 223–271

5 Arguments

1:   N – INTEGERInput
On entry: n, the number of data values to be fitted.
Constraint: N>1.
2:   X N – REAL (KIND=nag_wp) arrayInput
3:   Y N – REAL (KIND=nag_wp) arrayInput
4:   F N – REAL (KIND=nag_wp) arrayInput
On entry: the xi,yi,fi data values to be fitted.
Constraint: X j≠X 1 for some j=2,…,n and Y k≠Y 1 for some k=2,…,n; i.e., there are at least two distinct x and y values.
5:   LSMINP – INTEGERInput
6:   LSMAXP – INTEGERInput
On entry: are control parameters for the local approximations.
Each local approximation is computed on a local domain containing one of the triangles in the discretization of the bounding box. The size of each local domain will be adaptively chosen such that if it contains fewer than LSMINP sample points it is expanded, else if it contains greater than LSMAXP sample points a thinning method is applied. LSMAXP mainly controls computational cost (in that working with a thinned set of points is cheaper and may be appropriate if the input data is densely distributed), while LSMINP allows handling of different types of scattered data.
Setting LSMAXP<LSMINP, and therefore forcing either expansion or thinning, may be useful for computing initial coarse approximations. In general smaller values for these arguments reduces cost.
A calibration procedure (experimenting with a small subset of the data to be fitted and validating the results) may be needed to choose the most appropriate values for LSMINP and LSMAXP.
Constraints:
  • 1≤LSMINP≤N;
  • LSMAXP≥1.
7:   NXCELS – INTEGERInput
8:   NYCELS – INTEGERInput
On entry: NXCELS (respectively NYCELS) is the number of cells in the x (respectively y) direction that will be used to create the triangulation of the bounding box of the domain of the function to be fitted.
Greater efficiency generally comes when NXCELS and NYCELS are chosen to be of the same order of magnitude and are such that N is O NXCELS×NYCELS. Thus for a ‘square’ triangulation — when NXCELS=NYCELS — the quantities N and NXCELS should be of the same order of magnitude. See also Section 9.
Constraints:
  • NXCELS≥1;
  • NYCELS≥1.
9:   LCOEFS – INTEGERInput
10:   COEFS LCOEFS – REAL (KIND=nag_wp) arrayOutput
On exit: if IFAIL=0 on exit, COEFS contains the computed spline coefficients.
Constraints:
  • if Global Smoothing Level=1, LCOEFS ≥ NXCELS+2 × NYCELS+2 +1 /2 ×10+1;
  • if Global Smoothing Level=2, LCOEFS ≥ 28 × NXCELS+2 × NYCELS+2 × 4 + 1 .
11:   IOPTS* – INTEGER arrayCommunication Array
Note: the dimension of this array is dictated by the requirements of associated functions that must have been previously called. This array must be the same array passed as argument IOPTS in the previous call to E02ZKF.
On entry: the contents of IOPTS must not be modified in any way either directly or indirectly, by further calls to E02ZKF, before calling either or both of the evaluation routines E02JEF and E02JFF.
12:   OPTS* – REAL (KIND=nag_wp) arrayCommunication Array
Note: the dimension of this array is dictated by the requirements of associated functions that must have been previously called. This array must be the same array passed as argument OPTS in the previous call to E02ZKF.
On entry: the contents of OPTS must not be modified in any way either directly or indirectly, by further calls to E02ZKF, before calling either or both of the evaluation routines E02JEF and E02JFF.
13:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=2
On entry, N=value.
Constraint: N>1.
IFAIL=4
On entry, LSMINP=value and N=value.
Constraint: 1≤LSMINP≤N.
IFAIL=5
On entry, LSMAXP=value.
Constraint: LSMAXP≥1.
IFAIL=6
On entry, NXCELS=value.
Constraint: NXCELS≥1.
IFAIL=7
On entry, NYCELS=value.
Constraint: NYCELS≥1.
IFAIL=8
On entry, LCOEFS=value.
Constraint:
if Global Smoothing Level=1,
LCOEFS≥NXCELS+2×NYCELS+2+1/2×10+1;
if Global Smoothing Level=2,
LCOEFS≥28×NXCELS+2×NYCELS+2×4+1.
IFAIL=9
Option arrays are not initialized or are corrupted.
IFAIL=11
An unexpected algorithmic failure was encountered. Please contact NAG.
IFAIL=12
On entry, all elements of X or of Y are equal.
IFAIL=20
The selected radial basis function cannot be used with the RBF local method.
IFAIL=21
The value of optional parameter Polynomial Starting Degree was invalid.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

Technical results on error bounds can be found in Davydov and Zeilfelder (2004), Davydov et al. (2006) and Davydov et al. (2005).
Local approximation by polynomials of degree d for n data points has optimal approximation order n -d+1 / 2 . The improved approximation power of hybrid polynomial/RBF and of pure RBF approximations is shown in Davydov et al. (2006) and Davydov et al. (2005).
The approximation error for C 1 global smoothing is O n -2 . For C 2 smoothing the error is O n -7/2 when Supersmooth C2=YES and O n -3 when Supersmooth C2=NO.
Whether maximal accuracy is achieved depends on the distribution of the input data and the choices of the algorithmic parameters. The references above contain extensive numerical tests and further technical discussions of how best to configure the method.

8 Parallelism and Performance

E02JDF is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
E02JDF makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

n-linear complexity and memory usage can be attained for sufficiently dense input data if the triangulation parameters NXCELS and NYCELS are chosen as recommended in their descriptions above. For sparse input data on such triangulations, if many expansion steps are required (see LSMINP) the complexity may rise to be loglinear.
Parts of the pure RBF method used when Local Method=RBF have n-quadratic memory usage.
Note that if Local Method=HYBRID and an initial hybrid approximation is deemed unreliable (see the description of optional parameter Minimum Singular Value LHA), a pure polynomial approximation will be used instead on that local domain.

10 Example

The Franke function
f x,y = 0.75 ⁢ exp - 9⁢x-2 2 + 9⁢y-2 2 / 4 + 0.75 ⁢ exp - 9⁢x+1 2 / 49 - 9⁢y+1 / 10 + 0.5 ⁢ exp - 9⁢x-7 2 + 9⁢y-3 2 / 4 - 0.2 ⁢ exp - 9⁢x-4 2 - 9⁢y-7 2
is widely used for testing surface-fitting methods. The example program randomly generates a number of points on this surface. From these a spline is computed and then evaluated at a vector of points and on a mesh.

10.1 Program Text

Program Text (e02jdfe.f90)

10.2 Program Data

Program Data (e02jdfe.d)

10.3 Program Results

Program Results (e02jdfe.r)

GnuplotProduced by GNUPLOT 4.6 patchlevel 3 Example Program Calculation and Evaluation of Bivariate Spline Fit from Scattered Data using Two-Stage Approximation gnuplot_plot_1 gnuplot_plot_2 0 0.2 0.4 0.6 0.8 1 x 0 0.2 0.4 0.6 0.8 1 y −0.2 0 0.2 0.4 0.6 0.8 1 1.2

11 Optional Parameters

Several optional parameters in E02JDF control aspects of the algorithm, methodology used, logic or output. Their values are contained in the arrays IOPTS and OPTS; these must be initialized before calling E02JDF by first calling E02ZKF with OPTSTR set to "Initialize = E02JDF".
Each optional parameter has an associated default value; to set any of them to a non-default value, or to reset any of them to the default value, use E02ZKF. The current value of an optional parameter can be queried using E02ZLF.
The remainder of this section can be skipped if you wish to use the default values for all optional parameters.
The following is a list of the optional parameters available. A full description of each optional parameter is provided in Section 11.1.
  • Averaged Spline
  • Global Smoothing Level
  • Interpolation Only RBF
  • Local Method
  • Minimum Singular Value LHA
  • Minimum Singular Value LPA
  • Polynomial Starting Degree
  • Radial Basis Function
  • Scaling Coefficient RBF
  • Separation LRBFA
  • Supersmooth C2

11.1 Description of the Optional Parameters

For each option, we give a summary line, a description of the optional parameter and details of constraints.
The summary line contains:
  • the keywords;
  • a parameter value, where the letters a, i and r denote options that take character, integer and real values respectively;
  • the default value.
Keywords and character values are case insensitive.
For E02JDF the maximum length of the parameter CVALUE used by E02ZLF is 16.
Averaged Spline a Default =NO
When the bounding box is triangulated there are 8 equivalent configurations of the mesh. Setting Averaged Spline=YES will use the averaged value of the 8 possible local polynomial approximations over each triangle in the mesh. This usually gives better results but at (about 8 times) higher computational cost.
Constraint: Averaged Spline=YES or NO.
Global Smoothing Level i Default =1
The smoothness level for the global spline approximation.
Global Smoothing Level=1
Will use C 1 piecewise cubics.
Global Smoothing Level=2
Will use C 2 piecewise sextics.
Constraint: Global Smoothing Level=1 or 2.
Interpolation Only RBF a Default =YES
If Interpolation Only RBF=YES, each local RBF approximation is computed by interpolation.
If Interpolation Only RBF=NO, each local RBF approximation is computed by a discrete least squares approach. This is likely to be more accurate and more expensive than interpolation.
If Local Method=HYBRID or POLYNOMIAL, this option setting is ignored.
Constraint: Interpolation Only RBF=YES or NO.
Local Method a Default =POLYNOMIAL
The local approximation scheme to use.
Local Method=POLYNOMIAL
Uses least squares polynomial approximations.
Local Method=HYBRID
Uses hybrid polynomial and RBF approximations.
Local Method=RBF
Uses pure RBF approximations.
In general POLYNOMIAL is less computationally expensive than HYBRID is less computationally expensive than RBF with the reverse ordering holding for accuracy of results.
Constraint: Local Method=POLYNOMIAL, HYBRID or RBF.
Minimum Singular Value LHA r Default =1.0
A tolerance measure for accepting or rejecting a local hybrid approximation (LHA) as reliable.
The solution of a local least squares problem solved on each triangle subdomain is accepted as reliable if the minimum singular value σ of the collocation matrix (of polynomial and radial basis function terms) associated with the least squares problem satisfies Minimum Singular Value LHA≤σ.
In general the approximation power will be reduced as Minimum Singular Value LHA is reduced. (A small σ indicates that the local data has hidden redundancies which prevent it from carrying enough information for a good approximation to be made.) Setting Minimum Singular Value LHA very large may have the detrimental effect that only approximations of low degree are deemed reliable.
A calibration procedure (experimenting with a small subset of the data to be fitted and validating the results) may be needed to choose the most appropriate value for this parameter.
If Local Method=POLYNOMIAL or RBF, this option setting is ignored.
Constraint: Minimum Singular Value LHA≥0.0.
Minimum Singular Value LPA r Default =1.0
A tolerance measure for accepting or rejecting a local polynomial approximation (LPA) as reliable. Clearly this setting is relevant when Local Method=POLYNOMIAL, but it also may be used when Local Method=HYBRID (see Section 9.)
The solution of a local least squares problem solved on each triangle subdomain is accepted as reliable if the minimum singular value σ of the matrix (of Bernstein polynomial values) associated with the least squares problem satisfies Minimum Singular Value LPA≤σ.
In general the approximation power will be reduced as Minimum Singular Value LPA is reduced. (A small σ indicates that the local data has hidden redundancies which prevent it from carrying enough information for a good approximation to be made.) Setting Minimum Singular Value LPA very large may have the detrimental effect that only approximations of low degree are deemed reliable.
Minimum Singular Value LPA will have no effect if Polynomial Starting Degree=0, and it will have little effect if the input data is ‘smooth’ (e.g., from a known function).
A calibration procedure (experimenting with a small subset of the data to be fitted and validating the results) may be needed to choose the most appropriate value for this parameter.
If Local Method=RBF, this option setting is ignored.
Constraint: Minimum Singular Value LPA≥0.0.
Polynomial Starting Degree i Default =5 if Local Method=HYBRID,
Default =1 otherwise
The degree to be used for the polynomial part in the initial step of each local approximation.
At this initial step the method will attempt to fit with a local approximation having polynomial part of degree Polynomial Starting Degree. If Local Method=POLYNOMIAL and the approximation is deemed unreliable (according to Minimum Singular Value LPA), the degree will be decremented by one and a new local approximation computed, ending with a constant approximation if no other is reliable. If Local Method=HYBRID and the approximation is deemed unreliable (according to Minimum Singular Value LHA), a pure polynomial approximation of this degree will be tried instead. The method then proceeds as in the POLYNOMIAL case.
Polynomial Starting Degree is bounded from above by the maximum possible spline degree, which is 6 (when performing C 2 global super-smoothing). Note that the best-case approximation error (see Section 7) for C 2 smoothing with Supersmooth C2=NO is achieved for local polynomials of degree 5; that is, for this level of global smoothing no further benefit is gained by setting Polynomial Starting Degree=6.
The default value gives a good compromise between efficiency and accuracy. In general the best approximation can be obtained by setting:
  • If Local Method=POLYNOMIAL
    • if Global Smoothing Level=1, Polynomial Starting Degree=3;
    • if Global Smoothing Level=2;
      • if Supersmooth C2=NO, Polynomial Starting Degree=5;
      • otherwise Polynomial Starting Degree=6.
  • If Local Method=HYBRID, Polynomial Starting Degree as small as possible.
If Local Method=RBF, this option setting is ignored.
Constraints:
  • if Local Method=HYBRID,
    • if Radial Basis Function=MQ2, MQ3, TPS or POLYHARMONIC3, Polynomial Starting Degree≥1;
    • if Radial Basis Function=TPS4 or POLYHARMONIC5, Polynomial Starting Degree≥2;
    • if Radial Basis Function=TPS6 or POLYHARMONIC7, Polynomial Starting Degree≥3;
    • if Radial Basis Function=POLYHARMONIC9, Polynomial Starting Degree≥4;
  • otherwise Polynomial Starting Degree≥0;
  • if Local Method=POLYNOMIAL and Global Smoothing Level=1, Polynomial Starting Degree≤3;
  • otherwise Polynomial Starting Degree≤6.
Radial Basis Function a Default =MQ
Scaling Coefficient RBF r Default =1.0
Radial Basis Function selects the RBF to use in each local RBF approximation, while Scaling Coefficient RBF selects the scale factor to use in its evaluation, as described below.
A calibration procedure (experimenting with a small subset of the data to be fitted and validating the results) may be needed to choose the most appropriate scale factor and RBF.
If Local Method=POLYNOMIAL, these option settings are ignored.
If Local Method=HYBRID or RBF, the following (conditionally) positive definite functions may be chosen.
Define R=x 2+y 2 and ρ=R/r.
GAUSS | Gaussian exp-ρ 2
IMQ | inverse multiquadric 1/r 2+R 2
IMQ2 | inverse multiquadric 1/r 2+R 2
IMQ3 | inverse multiquadric 1/r 2+R 23/2
IMQ0_5 | inverse multiquadric 1/r 2+R 21/4
WENDLAND31 | H. Wendland's C 2 function max 0,1-ρ 4 ⁢ 4 ρ+1
WENDLAND32 | H. Wendland's C 4 function max 0,1-ρ 6 ⁢ 35 ⁢ ρ 2 + 18 ⁢ ρ +3
WENDLAND33 | H. Wendland's C 6 function max 0,1-ρ 8 ⁢ 32 ⁢ ρ 3 + 25 ⁢ ρ 2 +8⁢ρ+1
BUHMANNC3 | M. Buhmann's C 3 function 112/45 ρ 9/2 + 16/3 ρ 7/2 - 7 ρ 4 -14/15 ρ 2 + 1/9 if ρ≤1, 0 otherwise
MQ | multiquadric r 2 + R 2
MQ1_5 | multiquadric r 2 + R 2 1.5/2
POLYHARMONIC1_5 | polyharmonic spline ρ 1.5
POLYHARMONIC1_75 | polyharmonic spline ρ 1.75
If Local Method=HYBRID the following conditionally positive definite functions may also be chosen.
MQ2 | multiquadric r 2 + R 2 log r 2 + R 2
MQ3 | multiquadric r 2 + R 2 3/2
TPS | thin plate spline ρ 2 log⁡ρ 2
POLYHARMONIC3 | polyharmonic spline ρ 3
TPS4 | thin plate spline ρ 4 log⁡ρ 2
POLYHARMONIC5 | polyharmonic spline ρ 5
TPS6 | thin plate spline ρ 6 log⁡ρ 2
POLYHARMONIC7 | polyharmonic spline ρ 7
POLYHARMONIC9 | polyharmonic spline ρ 9
Constraints:
  • if Radial Basis Function=MQ2, MQ3, TPS or POLYHARMONIC3, Local Method=HYBRID and Polynomial Starting Degree≥1;
  • if Radial Basis Function=TPS4 or POLYHARMONIC5, Local Method=HYBRID and Polynomial Starting Degree≥2;
  • if Radial Basis Function=TPS6 or POLYHARMONIC7, Local Method=HYBRID and Polynomial Starting Degree≥3;
  • if Radial Basis Function=POLYHARMONIC9, Local Method=HYBRID and Polynomial Starting Degree≥4;
  • Scaling Coefficient RBF>0.0.
Separation LRBFA r Default =16.0/Scaling Coefficient RBF
A knot-separation parameter used to control the condition number of the matrix used in each local RBF approximation (LRBFA). A smaller value may mean greater numerical stability but fewer knots.
If Local Method=HYBRID or POLYNOMIAL, this option setting is ignored.
Constraint: Separation LRBFA>0.0.
Supersmooth C2 a Default =NO
If Supersmooth C2=YES, the C 2 spline is generated using additional smoothness constraints. This usually gives better results but at higher computational cost.
If Global Smoothing Level=1 this option setting is ignored.
Constraint: Supersmooth C2=YES or NO.
E02 Chapter Contents
E02 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


E02JEF : NAG Library, Mark 26

E02 Chapter Contents
E02 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

E02JEF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
10 Example

1 Purpose

E02JEF calculates a vector of values of a spline computed by E02JDF.

2 Specification

SUBROUTINE E02JEF ( NEVALV, XEVALV, YEVALV, COEFS, FEVALV, IOPTS, OPTS, IFAIL)
INTEGER | NEVALV, IOPTS(*), IFAIL
REAL (KIND=nag_wp) | XEVALV(NEVALV), YEVALV(NEVALV), COEFS(*), FEVALV(NEVALV), OPTS(*)

3 Description

E02JEF calculates values at prescribed points (xi,yi), for i=1,2,…,n, of a bivariate spline computed by E02JDF. It is derived from the TSFIT package of O. Davydov and F. Zeilfelder.

4 References

Davydov O, Morandi R and Sestini A (2006) Local hybrid approximation for scattered data fitting with bivariate splines Comput. Aided Geom. Design 23 703–721
Davydov O, Sestini A and Morandi R (2005) Local RBF approximation for scattered data fitting with bivariate splines Trends and Applications in Constructive Approximation M. G. de Bruin, D. H. Mache, and J. Szabados, Eds ISNM Vol. 151 Birkhauser 91–102
Davydov O and Zeilfelder F (2004) Scattered data fitting by direct extension of local polynomials to bivariate splines Advances in Comp. Math. 21 223–271
Farin G and Hansford D (2000) The Essentials of CAGD Natic, MA: A K Peters, Ltd.

5 Arguments

1:   NEVALV – INTEGERInput
On entry: n, the number of values at which the spline is to be evaluated.
Constraint: NEVALV≥1.
2:   XEVALV NEVALV – REAL (KIND=nag_wp) arrayInput
On entry: the xi values at which the spline is to be evaluated.
Constraint: for all i, XEVALV i must lie inside, or on the boundary of, the spline's bounding box as determined by E02JDF.
3:   YEVALV NEVALV – REAL (KIND=nag_wp) arrayInput
On entry: the yi values at which the spline is to be evaluated.
Constraint: for all i, YEVALV i must lie inside, or on the boundary of, the spline's bounding box as determined by E02JDF.
4:   COEFS* – REAL (KIND=nag_wp) arrayCommunication Array
Note: the dimension of this array is dictated by the requirements of associated functions that must have been previously called. This array must be the same array passed as argument COEFS in the previous call to E02JDF.
On entry: the computed spline coefficients as output from E02JDF.
5:   FEVALV NEVALV – REAL (KIND=nag_wp) arrayOutput
On exit: if IFAIL=0 on exit FEVALV i contains the computed spline value at xi,yi.
6:   IOPTS* – INTEGER arrayCommunication Array
Note: the dimension of this array is dictated by the requirements of associated functions that must have been previously called. This array must be the same array passed as argument IOPTS in the previous call to E02ZKF.
On entry: the contents of the array must not have been modified either directly or indirectly, by a call to E02ZKF, between calls to E02JDF and E02JEF.
7:   OPTS* – REAL (KIND=nag_wp) arrayCommunication Array
Note: the dimension of this array is dictated by the requirements of associated functions that must have been previously called. This array must be the same array passed as argument OPTS in the previous call to E02ZKF.
On entry: the contents of the array must not have been modified either directly or indirectly, by a call to E02ZKF, between calls to E02JDF and E02JEF.
8:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=2
On entry, NEVALV=value.
Constraint: NEVALV≥1.
IFAIL=9
Option arrays are not initialized or are corrupted.
IFAIL=10
The fitting routine has not been called, or the array of coefficients has been corrupted.
IFAIL=13
On entry, XEVALV value=value was outside the bounding box.
Constraint: value≤XEVALV i≤value for all i.
IFAIL=14
On entry, YEVALV value=value was outside the bounding box.
Constraint: value≤YEVALV i≤value for all i.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

E02JEF uses the de Casteljau algorithm and thus is numerically stable. See Farin and Hansford (2000) for details.

8 Parallelism and Performance

E02JEF is not threaded in any implementation.

9 Further Comments

To evaluate a C 1 approximation (i.e., when Global Smoothing Level=1), a real array of length O 1 is dynamically allocated by each invocation of E02JEF. No memory is allocated internally when evaluating a C 2 approximation.

10 Example

See Section 10 in E02JDF.
E02 Chapter Contents
E02 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


E02JFF : NAG Library, Mark 26

E02 Chapter Contents
E02 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

E02JFF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
10 Example

1 Purpose

E02JFF calculates a mesh of values of a spline computed by E02JDF.

2 Specification

SUBROUTINE E02JFF ( NXEVAL, NYEVAL, XEVALM, YEVALM, COEFS, FEVALM, IOPTS, OPTS, IFAIL)
INTEGER | NXEVAL, NYEVAL, IOPTS(*), IFAIL
REAL (KIND=nag_wp) | XEVALM(NXEVAL), YEVALM(NYEVAL), COEFS(*), FEVALM(NXEVAL,NYEVAL), OPTS(*)

3 Description

E02JFF calculates values on a rectangular mesh of a bivariate spline computed by E02JDF. The points in the mesh are defined by x coordinates (xi), for i=1,2,…,nx, and y coordinates (yj), for j=1,2,…,ny. This routine is derived from the TSFIT package of O. Davydov and F. Zeilfelder.

4 References

Davydov O, Morandi R and Sestini A (2006) Local hybrid approximation for scattered data fitting with bivariate splines Comput. Aided Geom. Design 23 703–721
Davydov O, Sestini A and Morandi R (2005) Local RBF approximation for scattered data fitting with bivariate splines Trends and Applications in Constructive Approximation M. G. de Bruin, D. H. Mache, and J. Szabados, Eds ISNM Vol. 151 Birkhauser 91–102
Davydov O and Zeilfelder F (2004) Scattered data fitting by direct extension of local polynomials to bivariate splines Advances in Comp. Math. 21 223–271
Farin G and Hansford D (2000) The Essentials of CAGD Natic, MA: A K Peters, Ltd.

5 Arguments

1:   NXEVAL – INTEGERInput
On entry: nx, the number of values in the x direction forming the mesh on which the spline is to be evaluated.
Constraint: NXEVAL≥1.
2:   NYEVAL – INTEGERInput
On entry: ny, the number of values in the y direction forming the mesh on which the spline is to be evaluated.
Constraint: NYEVAL≥1.
3:   XEVALM NXEVAL – REAL (KIND=nag_wp) arrayInput
On entry: the xi values forming the mesh on which the spline is to be evaluated.
Constraint: for all i, XEVALM i must lie inside, or on the boundary of, the spline's bounding box as determined by E02JDF.
4:   YEVALM NYEVAL – REAL (KIND=nag_wp) arrayInput
On entry: the yj values forming the mesh on which the spline is to be evaluated.
Constraint: for all j, YEVALM j must lie inside, or on the boundary of, the spline's bounding box as determined by E02JDF.
5:   COEFS* – REAL (KIND=nag_wp) arrayCommunication Array
Note: the dimension of this array is dictated by the requirements of associated functions that must have been previously called. This array must be the same array passed as argument COEFS in the previous call to E02JDF.
On entry: the computed spline coefficients as output from E02JDF.
6:   FEVALM NXEVALNYEVAL – REAL (KIND=nag_wp) arrayOutput
On exit: if IFAIL=0 on exit FEVALM ij contains the computed spline value at xi,yj.
7:   IOPTS* – INTEGER arrayCommunication Array
Note: the dimension of this array is dictated by the requirements of associated functions that must have been previously called. This array must be the same array passed as argument IOPTS in the previous call to E02ZKF.
On entry: the contents of the array must not have been modified either directly or indirectly, by a call to E02ZKF, between calls to E02JDF and E02JFF.
8:   OPTS* – REAL (KIND=nag_wp) arrayCommunication Array
Note: the dimension of this array is dictated by the requirements of associated functions that must have been previously called. This array must be the same array passed as argument OPTS in the previous call to E02ZKF.
On entry: the contents of the array must not have been modified either directly or indirectly, by a call to E02ZKF, between calls to E02JDF and E02JFF.
9:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=6
On entry, NXEVAL=value.
Constraint: NXEVAL≥1.
IFAIL=7
On entry, NYEVAL=value.
Constraint: NYEVAL≥1.
IFAIL=9
Option arrays are not initialized or are corrupted.
IFAIL=10
The fitting routine has not been called, or the array of coefficients has been corrupted.
IFAIL=13
On entry, XEVALM value=value was outside the bounding box.
Constraint: value≤XEVALM i≤value for all i.
IFAIL=14
On entry, YEVALM value=value was outside the bounding box.
Constraint: value≤YEVALM j≤value for all j.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

E02JFF uses the de Casteljau algorithm and thus is numerically stable. See Farin and Hansford (2000) for details.

8 Parallelism and Performance

E02JFF is not threaded in any implementation.

9 Further Comments

To evaluate a C 1 approximation (i.e., when Global Smoothing Level=1), a real array of length O 1 is dynamically allocated by each invocation of E02JFF. No memory is allocated internally when evaluating a C 2 approximation.

10 Example

See Section 10 in E02JDF.
E02 Chapter Contents
E02 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


E02RAF : NAG Library, Mark 26

E02 Chapter Contents
E02 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

E02RAF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

E02RAF calculates the coefficients in a Padé approximant to a function from its user-supplied Maclaurin expansion.

2 Specification

SUBROUTINE E02RAF ( IA, IB, C, IC, A, B, W, JW, IFAIL)
INTEGER | IA, IB, IC, JW, IFAIL
REAL (KIND=nag_wp) | C(IC), A(IA), B(IB), W(JW)

3 Description

Given a power series
c 0+c 1 x+c 2 x 2+⋯+c l+m x l+m+⋯
E02RAF uses the coefficients ci, for i=0,1,…,l+m, to form the l/m Padé approximant of the form
a 0+a 1 x+a 2 x 2+⋯+al xl b 0+b 1 x+b 2 x 2+⋯+bm xm
with b 0 defined to be unity. The two sets of coefficients aj, for j=0,1,…,l, and bk, for k=0,1,…,m, in the numerator and denominator are calculated by direct solution of the Padé equations (see Graves–Morris (1979)); these values are returned through the argument list unless the approximant is degenerate.
Padé approximation is a useful technique when values of a function are to be obtained from its Maclaurin expansion but convergence of the series is unacceptably slow or even nonexistent. It is based on the hypothesis of the existence of a sequence of convergent rational approximations, as described in Baker and Graves–Morris (1981) and Graves–Morris (1979).
Unless there are reasons to the contrary (as discussed in Chapter 4, Section 2, Chapters 5 and 6 of Baker and Graves–Morris (1981)), one normally uses the diagonal sequence of Padé approximants, namely
m/m,m=0,1,2,….
Subsequent evaluation of the approximant at a given value of x may be carried out using E02RBF.

4 References

Baker G A Jr and Graves–Morris P R (1981) Padé approximants, Part 1: Basic theory encyclopaedia of Mathematics and its Applications Addison–Wesley
Graves–Morris P R (1979) The numerical calculation of Padé approximants Padé Approximation and its Applications. Lecture Notes in Mathematics (ed L Wuytack) 765 231–245 Adison–Wesley

5 Arguments

1:   IA – INTEGERInput
2:   IB – INTEGERInput
On entry: IA must specify l+1 and IB must specify m+1, where l and m are the degrees of the numerator and denominator of the approximant, respectively.
Constraint: IA≥1 and IB≥1.
3:   C IC – REAL (KIND=nag_wp) arrayInput
On entry: C i must specify, for i=1,2,…,l+m+1, the coefficient of x i-1 in the given power series.
4:   IC – INTEGERInput
On entry: the dimension of the array C as declared in the (sub)program from which E02RAF is called.
Constraint: IC≥IA+IB-1.
5:   A IA – REAL (KIND=nag_wp) arrayOutput
On exit: A j+1, for j=1,2,…,l+1, contains the coefficient aj in the numerator of the approximant.
6:   B IB – REAL (KIND=nag_wp) arrayOutput
On exit: B k+1, for k=1,2,…,m+1, contains the coefficient bk in the denominator of the approximant.
7:   W JW – REAL (KIND=nag_wp) arrayWorkspace
8:   JW – INTEGERInput
On entry: the dimension of the array W as declared in the (sub)program from which E02RAF is called.
Constraint: JW≥IB×2×IB+3.
9:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, | JW<IB×2×IB+3,
or | IA<1,
or | IB<1,
or | IC<IA+IB-1
(so there are insufficient coefficients in the given power series to calculate the desired approximant).
IFAIL=2
The Padé approximant is degenerate.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

The solution should be the best possible to the extent to which the solution is determined by the input coefficients. It is recommended that you determine the locations of the zeros of the numerator and denominator polynomials, both to examine compatibility with the analytic structure of the given function and to detect defects. (Defects are nearby pole-zero pairs; defects close to x=0.0 characterise ill-conditioning in the construction of the approximant.) Defects occur in regions where the approximation is necessarily inaccurate. The example program calls C02AGF to determine the above zeros.
It is easy to test the stability of the computed numerator and denominator coefficients by making small perturbations of the original Maclaurin series coefficients (e.g., cl or c l+m). These questions of intrinsic error of the approximants and computational error in their calculation are discussed in Chapter 2 of Baker and Graves–Morris (1981).

8 Parallelism and Performance

E02RAF is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
E02RAF makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The time taken is approximately proportional to m 3.

10 Example

This example calculates the 4/4 Padé approximant of ex (whose power-series coefficients are first stored in the array C). The poles and zeros are then calculated to check the character of the 4/4 Padé approximant.

10.1 Program Text

Program Text (e02rafe.f90)

10.2 Program Data

None.

10.3 Program Results

Program Results (e02rafe.r)

E02 Chapter Contents
E02 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


E02RBF : NAG Library, Mark 26

E02 Chapter Contents
E02 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

E02RBF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

E02RBF evaluates a rational function at a user-supplied point, given the numerator and denominator coefficients.

2 Specification

SUBROUTINE E02RBF ( A, IA, B, IB, X, ANS, IFAIL)
INTEGER | IA, IB, IFAIL
REAL (KIND=nag_wp) | A(IA), B(IB), X, ANS

3 Description

Given a real value x and the coefficients aj, for j=0,1,…,l and bk, for k=0,1,…,m, E02RBF evaluates the rational function
∑j=0 l aj xj ∑k=0 m bk xk .
using nested multiplication (see Conte and de Boor (1965)).
A particular use of E02RBF is to compute values of the Padé approximants determined by E02RAF.

4 References

Conte S D and de Boor C (1965) Elementary Numerical Analysis McGraw–Hill
Peters G and Wilkinson J H (1971) Practical problems arising in the solution of polynomial equations J. Inst. Maths. Applics. 8 16–35

5 Arguments

1:   A IA – REAL (KIND=nag_wp) arrayInput
On entry: A j+1, for j=1,2,…,l+1, must contain the value of the coefficient aj in the numerator of the rational function.
2:   IA – INTEGERInput
On entry: the value of l+1, where l is the degree of the numerator.
Constraint: IA≥1.
3:   B IB – REAL (KIND=nag_wp) arrayInput
On entry: B k+1, for k=1,2,…,m+1, must contain the value of the coefficient bk in the denominator of the rational function.
Constraint: if IB=1, B 1≠0.0.
4:   IB – INTEGERInput
On entry: the value of m+1, where m is the degree of the denominator.
Constraint: IB≥1.
5:   X – REAL (KIND=nag_wp)Input
On entry: the point x at which the rational function is to be evaluated.
6:   ANS – REAL (KIND=nag_wp)Output
On exit: the result of evaluating the rational function at the given point x.
7:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
The rational function is being evaluated at or near a pole.
IFAIL=2
On entry, | IA<1,
or | IB<1,
or | B 1=0.0 when IB=1 (so the denominator is identically zero).
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

A running error analysis for polynomial evaluation by nested multiplication using the recurrence suggested by Kahan (see Peters and Wilkinson (1971)) is used to detect whether you are attempting to evaluate the approximant at or near a pole.

8 Parallelism and Performance

E02RBF is not threaded in any implementation.

9 Further Comments

The time taken is approximately proportional to l+m.

10 Example

This example first calls E02RAF to calculate the 4/4 Padé approximant to ex, and then uses E02RBF to evaluate the approximant at x=0.1,0.2,…,1.0.

10.1 Program Text

Program Text (e02rbfe.f90)

10.2 Program Data

None.

10.3 Program Results

Program Results (e02rbfe.r)

GnuplotProduced by GNUPLOT 4.6 patchlevel 3 0 2 4 6 8 10 12 14 16 18 20 22 0 0.5 1 1.5 2 2.5 3 1e−14 1e−12 1e−10 1e−08 1e−06 0.0001 0.01 y(x) Error x Example Program The [4|4] Pade Approximant of exp(x) gnuplot_plot_1 Pade gnuplot_plot_2 exp(x) gnuplot_plot_3 Error
E02 Chapter Contents
E02 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


E02ZAF : NAG Library, Mark 26

E02 Chapter Contents
E02 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

E02ZAF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

E02ZAF sorts two-dimensional data into rectangular panels.

2 Specification

SUBROUTINE E02ZAF ( PX, PY, LAMDA, MU, M, X, Y, POINT, NPOINT, ADRES, NADRES, IFAIL)
INTEGER | PX, PY, M, POINT(NPOINT), NPOINT, ADRES(NADRES), NADRES, IFAIL
REAL (KIND=nag_wp) | LAMDA(PX), MU(PY), X(M), Y(M)

3 Description

A set of m data points with rectangular Cartesian coordinates xr,yr are sorted into panels defined by lines parallel to the y and x axes. The intercepts of these lines on the x and y axes are given in LAMDA i, for i=5,6,…,PX-4 and MU j, for j=5,6,…,PY-4, respectively. The subroutine orders the data so that all points in a panel occur before data in succeeding panels, where the panels are numbered from bottom to top and then left to right, with the usual arrangement of axes, as shown in the diagram. Within a panel the points maintain their original order.
Figure 1
A data point lying exactly on one or more panel sides is taken to be in the highest-numbered panel adjacent to the point. The subroutine does not physically rearrange the data, but provides the array POINT which contains a linked list for each panel, pointing to the data in that panel. The total number of panels is PX-7×PY-7.

4 References

None.

5 Arguments

1:   PX – INTEGERInput
2:   PY – INTEGERInput
On entry: PX and PY must specify eight more than the number of intercepts on the x axis and y axis, respectively.
Constraint: PX≥8 and PY≥8.
3:   LAMDA PX – REAL (KIND=nag_wp) arrayInput
On entry: LAMDA 5 to LAMDA PX-4 must contain, in nondecreasing order, the intercepts on the x axis of the sides of the panels parallel to the y axis.
4:   MU PY – REAL (KIND=nag_wp) arrayInput
On entry: MU 5 to MU PY-4 must contain, in nondecreasing order, the intercepts on the y axis of the sides of the panels parallel to the x axis.
5:   M – INTEGERInput
On entry: the number m of data points.
6:   X M – REAL (KIND=nag_wp) arrayInput
7:   Y M – REAL (KIND=nag_wp) arrayInput
On entry: the coordinates of the rth data point xr,yr, for r=1,2,…,m.
8:   POINT NPOINT – INTEGER arrayOutput
On exit: for i=1,2,…,NPOINT, POINT m+i=I1 is the index of the first point in panel i, POINT I1=I2 is the index of the second point in panel i and so on.
POINT In=0 indicates that X In,Y In was the last point in the panel.
The coordinates of points in panel i can be accessed in turn by means of the following instructions:
 IN = M + I
 10 IN = POINT(IN)
 IF (IN.EQ. 0) GOTO 20
 XI = X(IN)
 YI = Y(IN)
 .
 .
 .
 GOTO 10
 20 ...
9:   NPOINT – INTEGERInput
On entry: the dimension of the array POINT as declared in the (sub)program from which E02ZAF is called.
Constraint: NPOINT≥M+PX-7×PY-7.
10:   ADRES NADRES – INTEGER arrayWorkspace
11:   NADRES – INTEGERInput
On entry: the value PX-7×PY-7, the number of panels into which the x,y plane is divided.
12:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
The intercepts in the array LAMDA, or in the array MU, are not in nondecreasing order.
IFAIL=2
On entry, | PX<8,
or | PY<8,
or | M≤0,
or | NADRES≠PX-7×PY-7,
or | NPOINT<M+PX-7×PY-7.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

Not applicable.

8 Parallelism and Performance

E02ZAF is not threaded in any implementation.

9 Further Comments

The time taken is approximately proportional to m×log NPOINT.
This subroutine was written to sort two-dimensional data in the manner required by routine E02DAF. The first 9 arguments of E02ZAF are the same as the arguments in E02DAF which have the same name.

10 Example

This example reads in data points and the intercepts of the panel sides on the x and y axes; it calls E02ZAF to set up the index array POINT; and finally it prints the data points in panel order.

10.1 Program Text

Program Text (e02zafe.f90)

10.2 Program Data

Program Data (e02zafe.d)

10.3 Program Results

Program Results (e02zafe.r)

E02 Chapter Contents
E02 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


E02ZKF : NAG Library, Mark 26

E02 Chapter Contents
E02 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

E02ZKF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
10 Example

1 Purpose

E02ZKF either initializes or resets the optional parameter arrays or sets a single optional parameter for supported problem solving routines in Chapter E02. Currently, only E02JDF is supported.

2 Specification

SUBROUTINE E02ZKF ( OPTSTR, IOPTS, LIOPTS, OPTS, LOPTS, IFAIL)
INTEGER | IOPTS(LIOPTS), LIOPTS, LOPTS, IFAIL
REAL (KIND=nag_wp) | OPTS(LOPTS)
CHARACTER(*) | OPTSTR

3 Description

E02ZKF has three purposes: to initialize optional parameter arrays, to reset all optional parameters to their default values or to set a single optional parameter to a user-supplied value.
Optional parameters and their values are, in general, presented as a character string, OPTSTR, of the form ‘option =optval’; alphabetic characters can be supplied in either upper or lower case. Both option and optval may consist of one or more tokens separated by white space. The tokens that comprise optval will normally be either an integer, real or character value as defined in the description of the specific optional argument. In addition all optional parameters can take an optval DEFAULT which resets the optional parameter to its default value.
It is imperative that optional parameter arrays are initialized before any options are set, before the relevant problem solving routine is called and before any options are queried using E02ZLF. To initialize the optional parameter arrays IOPTS and OPTS for a specific problem solving routine, the option Initialize is used with optval identifying the problem solving routine to be called, via its short name. For example, to initialize optional parameter arrays to be passed to E02JDF, E02ZKF is called as follows:
CALL E02ZKF('Initialize = e02jdf', IOPTS, LIOPTS, OPTS, LOPTS, IFAIL)
Information relating to available option names and their corresponding valid values is given in Section 11 in E02JDF.

4 References

None.

5 Arguments

1:   OPTSTR – CHARACTER(*)Input
On entry: a string identifying the option to be set.
Initialize=routine name
Initialize the optional parameter arrays IOPTS and OPTS for use with routine routine name, where routine name is the short name of the problem solving routine you wish to use.
Defaults
Resets all options to their default values.
option=optval
See Section 11 in E02JDF for details of valid values for option and optval. The equals sign (=) delimiter must be used to separate the option from its optval.
The processing of OPTSTR does not depend on its case. Each token in the option and optval component must be separated by at least one space.
2:   IOPTS LIOPTS – INTEGER arrayCommunication Array
On entry: optional parameter array.
If OPTSTR has the form Initialize=routine name, the contents of IOPTS need not be set.
Otherwise, IOPTS must not have been altered since the last call to E02ZKF, E02ZLF or the selected problem solving routine or suite of routines.
On exit: dependent on the contents of OPTSTR, either an initialized, reset or updated version of the optional parameter array.
3:   LIOPTS – INTEGERInput
On entry: the length of the array IOPTS.
Constraint: unless otherwise stated in the documentation for a specific, supported, problem solving routine, LIOPTS≥100.
4:   OPTS LOPTS – REAL (KIND=nag_wp) arrayCommunication Array
On entry: optional parameter array.
If OPTSTR has the form Initialize=routine name, the contents of OPTS need not be set.
Otherwise, OPTS must not have been altered since the last call to E02ZKF, E02ZLF or the selected problem solving routine or suite of routines.
On exit: dependent on the contents of OPTSTR, either an initialized, reset or updated version of the optional parameter array.
5:   LOPTS – INTEGERInput
On entry: the length of the array OPTS.
Constraint: unless otherwise stated in the documentation for a specific, supported, problem solving routine, LOPTS≥100.
6:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=11
On entry, the optional parameter in OPTSTR was not recognized: OPTSTR=value.
IFAIL=12
On entry, the expected delimiter ‘=’ was not found in OPTSTR: OPTSTR=value.
IFAIL=13
On entry, could not convert the specified optval to an integer: OPTSTR=value.
On entry, could not convert the specified optval to a real: OPTSTR=value.
IFAIL=14
On entry, attempting to initialize the optional parameter arrays but specified routine name was not valid: name=value.
IFAIL=15
On entry, the optval supplied for the integer optional parameter is not valid.
OPTSTR=value.
IFAIL=16
On entry, the optval supplied for the real optional parameter is not valid.
OPTSTR=value.
IFAIL=17
On entry, the optval supplied for the character optional parameter is not valid.
OPTSTR=value.
IFAIL=21
On entry, either the option arrays have not been initialized or they have been corrupted.
IFAIL=31
On entry, LIOPTS=value.
Constraint: LIOPTS≥value.
IFAIL=51
On entry, LOPTS=value.
Constraint: LOPTS≥value.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

Not applicable.

8 Parallelism and Performance

E02ZKF is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

None.

10 Example

See the example programs associated with the problem solving routine you wish to use for a demonstration of how to use E02ZKF to initialize option arrays and set options.
E02 Chapter Contents
E02 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


E02ZLF : NAG Library, Mark 26

E02 Chapter Contents
E02 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

E02ZLF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
10 Example

1 Purpose

E02ZLF is used to query the value of optional parameters available to supported problem solving routines in Chapter E02. Currently, only E02JDF is supported.

2 Specification

SUBROUTINE E02ZLF ( OPTSTR, IVALUE, RVALUE, CVALUE, OPTYPE, IOPTS, OPTS, IFAIL)
INTEGER | IVALUE, OPTYPE, IOPTS(*), IFAIL
REAL (KIND=nag_wp) | RVALUE, OPTS(*)
CHARACTER(*) | OPTSTR, CVALUE

3 Description

E02ZLF is used to query the current values of options. It is necessary to initalize optional parameter arrays using E02ZKF before any options are queried.
E02ZLF will normally return either an integer, real or character value dependent upon the type associated with the optional parameter being queried. Whether the option queried is of integer, real or character type is indicated by the returned value of OPTYPE.
Information on optional parameter names and whether these options are real, integer or character can be found in Section 11 in E02JDF.

4 References

None.

5 Arguments

1:   OPTSTR – CHARACTER(*)Input
On entry: a string identifying the option whose current value is required. See Section 11 in E02JDF for information on valid options. In addition, the following is a valid option:
Identify
E02ZLF returns in CVALUE the routine name supplied to E02ZKF when the optional parameter arrays IOPTS and OPTS were initialized.
2:   IVALUE – INTEGEROutput
On exit: if the optional parameter supplied in OPTSTR is an integer valued argument, IVALUE will hold its current value.
3:   RVALUE – REAL (KIND=nag_wp)Output
On exit: if the optional parameter supplied in OPTSTR is a real valued argument, RVALUE will hold its current value.
4:   CVALUE – CHARACTER(*)Output
Note: the maximum length of the string returned in CVALUE depends on the problem solving routine in use. See Section 11.1 of the relevant solver.
On exit: if the optional parameter supplied in OPTSTR is a character valued argument, CVALUE will hold its current value, unless Identify is specified (see OPTSTR).
5:   OPTYPE – INTEGEROutput
On exit: indicates whether the optional parameter supplied in OPTSTR is an integer, real or character valued argument and hence which of IVALUE, RVALUE or CVALUE holds the current value.
OPTYPE=1
OPTSTR is an integer valued optional parameter, its current value has been returned in IVALUE.
OPTYPE=2
OPTSTR is a real valued optional parameter, its current value has been returned in RVALUE.
OPTYPE=3
OPTSTR is a character valued optional parameter, its current value has been returned in CVALUE.
6:   IOPTS* – INTEGER arrayCommunication Array
Note: the dimension of this array is dictated by the requirements of associated functions that must have been previously called. This array must be the same array passed as argument IOPTS in the previous call to E02ZKF.
7:   OPTS* – REAL (KIND=nag_wp) arrayCommunication Array
Note: the dimension of this array is dictated by the requirements of associated functions that must have been previously called. This array must be the same array passed as argument OPTS in the previous call to E02ZKF.
8:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=11
On entry, the optional parameter in OPTSTR was not recognized: OPTSTR=value.
IFAIL=41
On entry, OPTSTR indicates a character optional parameter, but CVALUE is too short to hold the stored value. The returned value will be truncated.
IFAIL=61
On entry, either the option arrays have not been initialized or they have been corrupted.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

Not applicable.

8 Parallelism and Performance

E02ZLF is not threaded in any implementation.

9 Further Comments

None.

10 Example

See the example programs associated with the problem solving routine you wish to use for a demonstration of how to use E02ZLF to query options.
E02 Chapter Contents
E02 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


E04ABF/E04ABA : NAG Library, Mark 26

E04 Chapter Contents
E04 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

E04ABF/E04ABA

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
▸▿ 2 Specification
2.1 Specification for E04ABF
2.2 Specification for E04ABA
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

E04ABF/E04ABA searches for a minimum, in a given finite interval, of a continuous function of a single variable, using function values only. The method (based on quadratic interpolation) is intended for functions which have a continuous first derivative (although it will usually work if the derivative has occasional discontinuities).
E04ABA is a version of E04ABF that has additional arguments in order to make it safe for use in multithreaded applications (see Section 5).

2 Specification

2.1 Specification for E04ABF

SUBROUTINE E04ABF ( FUNCT, E1, E2, A, B, MAXCAL, X, F, IFAIL)
INTEGER | MAXCAL, IFAIL
REAL (KIND=nag_wp) | E1, E2, A, B, X, F
EXTERNAL | FUNCT

2.2 Specification for E04ABA

SUBROUTINE E04ABA ( FUNCT, E1, E2, A, B, MAXCAL, X, F, IUSER, RUSER, IFAIL)
INTEGER | MAXCAL, IUSER(*), IFAIL
REAL (KIND=nag_wp) | E1, E2, A, B, X, F, RUSER(*)
EXTERNAL | FUNCT

3 Description

E04ABF/E04ABA is applicable to problems of the form:
Minimize⁡F x  subject to  a≤x≤b.
It normally computes a sequence of x values which tend in the limit to a minimum of F x subject to the given bounds. It also progressively reduces the interval a,b in which the minimum is known to lie. It uses the safeguarded quadratic-interpolation method described in Gill and Murray (1973).
You must supply a FUNCT to evaluate F x. The arguments E1 and E2 together specify the accuracy
Tol x=E1×x+E2
to which the position of the minimum is required. Note that FUNCT is never called at any point which is closer than Tol x to a previous point.
If the original interval a,b contains more than one minimum, E04ABF/E04ABA will normally find one of the minima.

4 References

Gill P E and Murray W (1973) Safeguarded steplength algorithms for optimization using descent methods NPL Report NAC 37 National Physical Laboratory

5 Arguments

1:   FUNCT – SUBROUTINE, supplied by the user.External Procedure
You must supply this routine to calculate the value of the function F x at any point x in a,b. It should be tested separately before being used in conjunction with E04ABF/E04ABA.
The specification of FUNCT for E04ABF is:
SUBROUTINE FUNCT ( XC, FC)
REAL (KIND=nag_wp) XC, FC
The specification of FUNCT for E04ABA is:
SUBROUTINE FUNCT ( XC, FC, IUSER, RUSER)
INTEGER | IUSER(*)
REAL (KIND=nag_wp) | XC, FC, RUSER(*)
1:   XC – REAL (KIND=nag_wp)Input
On entry: the point x at which the value of F is required.
2:   FC – REAL (KIND=nag_wp)Output
On exit: must be set to the value of the function F at the current point x.
Note: the following are additional arguments for specific use with E04ABA. Users of E04ABF therefore need not read the remainder of this description.
3:   IUSER* – INTEGER arrayUser Workspace
4:   RUSER* – REAL (KIND=nag_wp) arrayUser Workspace
FUNCT is called with the arguments IUSER and RUSER as supplied to E04ABF/E04ABA. You are free to use the arrays IUSER and RUSER to supply information to FUNCT as an alternative to using COMMON global variables.
FUNCT must either be a module subprogram USEd by, or declared as EXTERNAL in, the (sub)program from which E04ABF/E04ABA is called. Arguments denoted as Input must not be changed by this procedure.
2:   E1 – REAL (KIND=nag_wp)Input/Output
On entry: the relative accuracy to which the position of a minimum is required. (Note that, since E1 is a relative tolerance, the scaling of x is automatically taken into account.)
E1 should be no smaller than 2 ε, and preferably not much less than ε, where ε is the machine precision.
On exit: if you set E1 to 0.0 (or to any value less than ε), E1 will be reset to the default value ε before starting the minimization process.
3:   E2 – REAL (KIND=nag_wp)Input/Output
On entry: the absolute accuracy to which the position of a minimum is required. E2 should be no smaller than 2 ε.
On exit: if you set E2 to 0.0 (or to any value less than ε), E2 will be reset to the default value ε.
4:   A – REAL (KIND=nag_wp)Input/Output
On entry: the lower bound a of the interval containing a minimum.
On exit: an improved lower bound on the position of the minimum.
5:   B – REAL (KIND=nag_wp)Input/Output
On entry: the upper bound b of the interval containing a minimum.
On exit: an improved upper bound on the position of the minimum.
6:   MAXCAL – INTEGERInput/Output
On entry: the maximum number of calls of F x to be allowed.
Constraint: MAXCAL≥3. (Few problems will require more than 30.)
There will be an error exit (see Section 6) after MAXCAL calls of FUNCT
On exit: the total number of times that FUNCT was actually called.
7:   X – REAL (KIND=nag_wp)Output
On exit: the estimated position of the minimum.
8:   F – REAL (KIND=nag_wp)Output
On exit: the function value at the final point given in X.
9:   IFAIL – INTEGERInput/Output
Note: for E04ABA, IFAIL does not occur in this position in the argument list. See the additional arguments described below.
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, because for this routine the values of the output arguments may be useful even if IFAIL≠0 on exit, the recommended value is -1. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).
Note: the following are additional arguments for specific use with E04ABA. Users of E04ABF therefore need not read the remainder of this description.
9:   IUSER* – INTEGER arrayUser Workspace
10:   RUSER* – REAL (KIND=nag_wp) arrayUser Workspace
IUSER and RUSER are not used by E04ABF/E04ABA, but are passed directly to FUNCT and may be used to pass information to this routine as an alternative to using COMMON global variables.
11:   IFAIL – INTEGERInput/Output
Note: see the argument description for IFAIL above.

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Note: E04ABF/E04ABA may return useful information for one or more of the following detected errors or warnings.
Errors or warnings detected by the routine:
IFAIL=1
On entry, | A+E2≥B,
or | MAXCAL<3,
IFAIL=2
The number of calls of FUNCT has exceeded MAXCAL. This may have happened simply because MAXCAL was set too small for a particular problem, or may be due to a mistake in FUNCT. If no mistake can be found in FUNCT, restart E04ABF/E04ABA (preferably with the values of A and B given on exit from the previous call of E04ABF/E04ABA).
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

If F x is δ-unimodal for some δ<Tol x, where Tol x=E1×x+E2, then, on exit, x approximates the minimum of F x in the original interval a,b with an error less than 3×Tol x.

8 Parallelism and Performance

E04ABF/E04ABA is not threaded in any implementation.

9 Further Comments

Timing depends on the behaviour of F x, the accuracy demanded and the length of the interval a,b. Unless F x can be evaluated very quickly, the run time will usually be dominated by the time spent in FUNCT.
If F x has more than one minimum in the original interval a,b, E04ABF/E04ABA will determine an approximation x (and improved bounds a and b) for one of the minima.
If E04ABF/E04ABA finds an x such that F x-δ 1>F x<F x+δ 2 for some δ 1,δ 2≥Tol x, the interval x-δ 1,x+δ 2 will be regarded as containing a minimum, even if F x is less than F x-δ 1 and F x+δ 2 only due to rounding errors in the subroutine. Therefore FUNCT should be programmed to calculate F x as accurately as possible, so that E04ABF/E04ABA will not be liable to find a spurious minimum.

10 Example

A sketch of the function
F x=sin⁡x x
shows that it has a minimum somewhere in the range 3.5,5.0. The following program shows how E04ABF/E04ABA can be used to obtain a good approximation to the position of a minimum.

10.1 Program Text

Note: the following programs illustrate the use of E04ABF and E04ABA.

Program Text (e04abfe.f90)

Program Text (e04abae.f90)

10.2 Program Data

None.

10.3 Program Results

Program Results (e04abfe.r)

Program Results (e04abae.r)

E04 Chapter Contents
E04 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


E04BBF/E04BBA : NAG Library, Mark 26

E04 Chapter Contents
E04 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

E04BBF/E04BBA

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
▸▿ 2 Specification
2.1 Specification for E04BBF
2.2 Specification for E04BBA
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

E04BBF/E04BBA searches for a minimum, in a given finite interval, of a continuous function of a single variable, using function and first derivative values. The method (based on cubic interpolation) is intended for functions which have a continuous first derivative (although it will usually work if the derivative has occasional discontinuities).
E04BBA is a version of E04BBF that has additional arguments in order to make it safe for use in multithreaded applications (see Section 5).

2 Specification

2.1 Specification for E04BBF

SUBROUTINE E04BBF ( FUNCT, E1, E2, A, B, MAXCAL, X, F, G, IFAIL)
INTEGER | MAXCAL, IFAIL
REAL (KIND=nag_wp) | E1, E2, A, B, X, F, G
EXTERNAL | FUNCT

2.2 Specification for E04BBA

SUBROUTINE E04BBA ( FUNCT, E1, E2, A, B, MAXCAL, X, F, G, IUSER, RUSER, IFAIL)
INTEGER | MAXCAL, IUSER(*), IFAIL
REAL (KIND=nag_wp) | E1, E2, A, B, X, F, G, RUSER(*)
EXTERNAL | FUNCT

3 Description

E04BBF/E04BBA is applicable to problems of the form:
Minimize⁡F x  subject to  a≤x≤b
when the first derivative dF dx can be calculated. The routine normally computes a sequence of x values which tend in the limit to a minimum of F x subject to the given bounds. It also progressively reduces the interval a,b in which the minimum is known to lie. It uses the safeguarded cubic-interpolation method described in Gill and Murray (1973).
You must supply a FUNCT to evaluate F x and dF dx . The arguments E1 and E2 together specify the accuracy
Tol x=E1×x+E2
to which the position of the minimum is required. Note that FUNCT is never called at a point which is closer than Tol x to a previous point.
If the original interval a,b contains more than one minimum, E04BBF/E04BBA will normally find one of the minima.

4 References

Gill P E and Murray W (1973) Safeguarded steplength algorithms for optimization using descent methods NPL Report NAC 37 National Physical Laboratory

5 Arguments

1:   FUNCT – SUBROUTINE, supplied by the user.External Procedure
You must supply this routine to calculate the values of F x and dF dx at any point x in a,b.
It should be tested separately before being used in conjunction with E04BBF/E04BBA.
The specification of FUNCT for E04BBF is:
SUBROUTINE FUNCT ( XC, FC, GC)
REAL (KIND=nag_wp) XC, FC, GC
The specification of FUNCT for E04BBA is:
SUBROUTINE FUNCT ( XC, FC, GC, IUSER, RUSER)
INTEGER | IUSER(*)
REAL (KIND=nag_wp) | XC, FC, GC, RUSER(*)
1:   XC – REAL (KIND=nag_wp)Input
On entry: the point x at which the values of F and dF dx are required.
2:   FC – REAL (KIND=nag_wp)Output
On exit: must be set to the value of the function F at the current point x.
3:   GC – REAL (KIND=nag_wp)Output
On exit: must be set to the value of the first derivative dF dx at the current point x.
Note: the following are additional arguments for specific use with E04BBA. Users of E04BBF therefore need not read the remainder of this description.
4:   IUSER* – INTEGER arrayUser Workspace
5:   RUSER* – REAL (KIND=nag_wp) arrayUser Workspace
FUNCT is called with the arguments IUSER and RUSER as supplied to E04BBF/E04BBA. You are free to use the arrays IUSER and RUSER to supply information to FUNCT as an alternative to using COMMON global variables.
FUNCT must either be a module subprogram USEd by, or declared as EXTERNAL in, the (sub)program from which E04BBF/E04BBA is called. Arguments denoted as Input must not be changed by this procedure.
2:   E1 – REAL (KIND=nag_wp)Input/Output
On entry: the relative accuracy to which the position of a minimum is required. (Note that, since E1 is a relative tolerance, the scaling of x is automatically taken into account.)
E1 should be no smaller than 2 ε, and preferably not much less than ε, where ε is the machine precision.
On exit: if you set E1 to 0.0 (or to any value less than ε), E1 will be reset to the default value ε before starting the minimization process.
3:   E2 – REAL (KIND=nag_wp)Input/Output
On entry: the absolute accuracy to which the position of a minimum is required. E2 should be no smaller than 2 ε.
On exit: if you set E2 to 0.0 (or to any value less than ε), E2 will be reset to the default value ε.
4:   A – REAL (KIND=nag_wp)Input/Output
On entry: the lower bound a of the interval containing a minimum.
On exit: an improved lower bound on the position of the minimum.
5:   B – REAL (KIND=nag_wp)Input/Output
On entry: the upper bound b of the interval containing a minimum.
On exit: an improved upper bound on the position of the minimum.
6:   MAXCAL – INTEGERInput/Output
On entry: the maximum number of calls of FUNCT to be allowed.
Constraint: MAXCAL≥2. (Few problems will require more than 20.)
There will be an error exit (see Section 6) after MAXCAL calls of FUNCT
On exit: the total number of times that FUNCT was actually called.
7:   X – REAL (KIND=nag_wp)Output
On exit: the estimated position of the minimum.
8:   F – REAL (KIND=nag_wp)Output
On exit: the function value at the final point given in X.
9:   G – REAL (KIND=nag_wp)Output
On exit: the value of the first derivative at the final point in X.
10:   IFAIL – INTEGERInput/Output
Note: for E04BBA, IFAIL does not occur in this position in the argument list. See the additional arguments described below.
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, because for this routine the values of the output arguments may be useful even if IFAIL≠0 on exit, the recommended value is -1. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).
Note: the following are additional arguments for specific use with E04BBA. Users of E04BBF therefore need not read the remainder of this description.
10:   IUSER* – INTEGER arrayUser Workspace
11:   RUSER* – REAL (KIND=nag_wp) arrayUser Workspace
IUSER and RUSER are not used by E04BBF/E04BBA, but are passed directly to FUNCT and may be used to pass information to this routine as an alternative to using COMMON global variables.
12:   IFAIL – INTEGERInput/Output
Note: see the argument description for IFAIL above.

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Note: E04BBF/E04BBA may return useful information for one or more of the following detected errors or warnings.
Errors or warnings detected by the routine:
IFAIL=1
On entry, | A+E2≥B,
or | MAXCAL<2.
IFAIL=2
The number of calls of FUNCT has exceeded MAXCAL. This may have happened simply because MAXCAL was set too small for a particular problem, or may be due to a mistake in FUNCT. If no mistake can be found in FUNCT, restart E04BBF/E04BBA (preferably with the values of A and B given on exit from the previous call of E04BBF/E04BBA).
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

If F x is δ-unimodal for some δ<Tol x, where Tol x=E1×x+E2, then, on exit, x approximates the minimum of F x in the original interval a,b with an error less than 3×Tol x.

8 Parallelism and Performance

E04BBF/E04BBA is not threaded in any implementation.

9 Further Comments

Timing depends on the behaviour of F x, the accuracy demanded and the length of the interval a,b. Unless F x and dF dx can be evaluated very quickly, the run time will usually be dominated by the time spent in FUNCT.
If F x has more than one minimum in the original interval a,b, E04BBF/E04BBA will determine an approximation x (and improved bounds a and b) for one of the minima.
If E04BBF/E04BBA finds an x such that F x-δ 1>F x<F x+δ 2 for some δ 1,δ 2≥Tol x, the interval x-δ 1,x+δ 2 will be regarded as containing a minimum, even if F x is less than F x-δ 1 and F x+δ 2 only due to rounding errors in the subroutine. Therefore FUNCT should be programmed to calculate F x as accurately as possible, so that E04BBF/E04BBA will not be liable to find a spurious minimum. (For similar reasons, dF dx should be evaluated as accurately as possible.)

10 Example

A sketch of the function
F x=sin⁡x x
shows that it has a minimum somewhere in the range 3.5,5.0. The following program shows how E04BBF/E04BBA can be used to obtain a good approximation to the position of a minimum.

10.1 Program Text

Note: the following programs illustrate the use of E04BBF and E04BBA.

Program Text (e04bbfe.f90)

Program Text (e04bbae.f90)

10.2 Program Data

None.

10.3 Program Results

Program Results (e04bbfe.r)

Program Results (e04bbae.r)

E04 Chapter Contents
E04 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


E04CBF : NAG Library, Mark 26

E04 Chapter Contents
E04 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

E04CBF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

E04CBF minimizes a general function F x of n independent variables x = x 1,x 2,…,xn T by the Nelder and Mead simplex method (see Nelder and Mead (1965)). Derivatives of the function need not be supplied.

2 Specification

SUBROUTINE E04CBF ( N, X, F, TOLF, TOLX, FUNCT, MONIT, MAXCAL, IUSER, RUSER, IFAIL)
INTEGER | N, MAXCAL, IUSER(*), IFAIL
REAL (KIND=nag_wp) | X(N), F, TOLF, TOLX, RUSER(*)
EXTERNAL | FUNCT, MONIT

3 Description

E04CBF finds an approximation to a minimum of a function F of n variables. You must supply a subroutine to calculate the value of F for any set of values of the variables.
The method is iterative. A simplex of n+1 points is set up in the n-dimensional space of the variables (for example, in 2 dimensions the simplex is a triangle) under the assumption that the problem has been scaled so that the values of the independent variables at the minimum are of order unity. The starting point you have provided is the first vertex of the simplex, the remaining n vertices are generated by E04CBF. The vertex of the simplex with the largest function value is reflected in the centre of gravity of the remaining vertices and the function value at this new point is compared with the remaining function values. Depending on the outcome of this test the new point is accepted or rejected, a further expansion move may be made, or a contraction may be carried out. See Nelder and Mead (1965) and Parkinson and Hutchinson (1972) for more details. When no further progress can be made the sides of the simplex are reduced in length and the method is repeated.
The method can be slow, but computational bottlenecks have been reduced following Singer and Singer (2004). However, E04CBF is robust, and therefore very useful for functions that are subject to inaccuracies.
There are the following options for successful termination of the method: based only on the function values at the vertices of the current simplex (see (1)); based only on a volume ratio between the current simplex and the initial one (see (2)); or based on which one of the previous two tests passes first. The volume test may be useful if F is discontinuous, while the function-value test should be sufficient on its own if F is continuous.

4 References

Nelder J A and Mead R (1965) A simplex method for function minimization Comput. J. 7 308–313
Parkinson J M and Hutchinson D (1972) An investigation into the efficiency of variants of the simplex method Numerical Methods for Nonlinear Optimization (ed F A Lootsma) Academic Press
Singer S and Singer S (2004) Efficient implementation of the Nelder–Mead search algorithm Appl. Num. Anal. Comp. Math. 1(3) 524–534

5 Arguments

1:   N – INTEGERInput
On entry: n, the number of variables.
Constraint: N≥1.
2:   X N – REAL (KIND=nag_wp) arrayInput/Output
On entry: a guess at the position of the minimum. Note that the problem should be scaled so that the values of the X i are of order unity.
On exit: the value of x corresponding to the function value in F.
3:   F – REAL (KIND=nag_wp)Output
On exit: the lowest function value found.
4:   TOLF – REAL (KIND=nag_wp)Input
On entry: the error tolerable in the function values, in the following sense. If fi, for i=1,2,…,n+1, are the individual function values at the vertices of the current simplex, and if fm is the mean of these values, then you can request that E04CBF should terminate if
1 n+1 ∑ i=1 n+1 fi - fm 2 < TOLF . (1)
You may specify TOLF=0 if you wish to use only the termination criterion (2) on the spatial values: see the description of TOLX.
Constraint: TOLF must be greater than or equal to the machine precision (see Chapter X02), or if TOLF equals zero then TOLX must be greater than or equal to the machine precision.
5:   TOLX – REAL (KIND=nag_wp)Input
On entry: the error tolerable in the spatial values, in the following sense. If LV denotes the ‘linearized’ volume of the current simplex, and if LV init denotes the ‘linearized’ volume of the initial simplex, then you can request that E04CBF should terminate if
LV LV init < TOLX . (2)
You may specify TOLX=0 if you wish to use only the termination criterion (1) on function values: see the description of TOLF.
Constraint: TOLX must be greater than or equal to the machine precision (see Chapter X02), or if TOLX equals zero then TOLF must be greater than or equal to the machine precision.
6:   FUNCT – SUBROUTINE, supplied by the user.External Procedure
FUNCT must evaluate the function F at a specified point. It should be tested separately before being used in conjunction with E04CBF.
The specification of FUNCT is:
SUBROUTINE FUNCT ( N, XC, FC, IUSER, RUSER)
INTEGER | N, IUSER(*)
REAL (KIND=nag_wp) | XC(N), FC, RUSER(*)
1:   N – INTEGERInput
On entry: n, the number of variables.
2:   XC N – REAL (KIND=nag_wp) arrayInput
On entry: the point at which the function value is required.
3:   FC – REAL (KIND=nag_wp)Output
On exit: the value of the function F at the current point x.
4:   IUSER* – INTEGER arrayUser Workspace
5:   RUSER* – REAL (KIND=nag_wp) arrayUser Workspace
FUNCT is called with the arguments IUSER and RUSER as supplied to E04CBF. You are free to use the arrays IUSER and RUSER to supply information to FUNCT as an alternative to using COMMON global variables.
FUNCT must either be a module subprogram USEd by, or declared as EXTERNAL in, the (sub)program from which E04CBF is called. Arguments denoted as Input must not be changed by this procedure.
7:   MONIT – SUBROUTINE, supplied by the NAG Library or the user.External Procedure
MONIT may be used to monitor the optimization process. It is invoked once every iteration.
If no monitoring is required, MONIT may be the dummy monitoring routine E04CBK supplied by the NAG Library.
The specification of MONIT is:
SUBROUTINE MONIT ( FMIN, FMAX, SIM, N, NCALL, SERROR, VRATIO, IUSER, RUSER)
INTEGER | N, NCALL, IUSER(*)
REAL (KIND=nag_wp) | FMIN, FMAX, SIM(N+1,N), SERROR, VRATIO, RUSER(*)
1:   FMIN – REAL (KIND=nag_wp)Input
On entry: the smallest function value in the current simplex.
2:   FMAX – REAL (KIND=nag_wp)Input
On entry: the largest function value in the current simplex.
3:   SIM N+1 N – REAL (KIND=nag_wp) arrayInput
On entry: the n+1 position vectors of the current simplex.
4:   N – INTEGERInput
On entry: n, the number of variables.
5:   NCALL – INTEGERInput
On entry: the number of times that FUNCT has been called so far.
6:   SERROR – REAL (KIND=nag_wp)Input
On entry: the current value of the standard deviation in function values used in termination test (1).
7:   VRATIO – REAL (KIND=nag_wp)Input
On entry: the current value of the linearized volume ratio used in termination test (2).
8:   IUSER* – INTEGER arrayUser Workspace
9:   RUSER* – REAL (KIND=nag_wp) arrayUser Workspace
MONIT is called with the arguments IUSER and RUSER as supplied to E04CBF. You are free to use the arrays IUSER and RUSER to supply information to MONIT as an alternative to using COMMON global variables.
MONIT must either be a module subprogram USEd by, or declared as EXTERNAL in, the (sub)program from which E04CBF is called. Arguments denoted as Input must not be changed by this procedure.
8:   MAXCAL – INTEGERInput
On entry: the maximum number of function evaluations to be allowed.
Constraint: MAXCAL≥1.
9:   IUSER* – INTEGER arrayUser Workspace
10:   RUSER* – REAL (KIND=nag_wp) arrayUser Workspace
IUSER and RUSER are not used by E04CBF, but are passed directly to FUNCT and MONIT and may be used to pass information to these routines as an alternative to using COMMON global variables.
11:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, MAXCAL=value.
Constraint: MAXCAL≥1.
On entry, N=value.
Constraint: N≥1.
On entry, TOLF=0.0 and TOLX=value.
Constraint: if TOLF=0.0 then TOLX is greater than or equal to the machine precision.
On entry, TOLF=value and TOLX=value.
Constraint: if TOLF≠0.0 and TOLX≠0.0 then both should be greater than or equal to the machine precision.
On entry, TOLX=0.0 and TOLF=value.
Constraint: if TOLX=0.0 then TOLF is greater than or equal to the machine precision.
IFAIL=2
MAXCAL function evaluations have been completed without any other termination test passing. Check the coding of FUNCT before increasing the value of MAXCAL.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

On a successful exit the accuracy will be as defined by TOLF or TOLX, depending on which criterion was satisfied first.

8 Parallelism and Performance

E04CBF is not threaded in any implementation.

9 Further Comments

Local workspace arrays of fixed lengths (depending on N) are allocated internally by E04CBF. The total size of these arrays amounts to N 2 + 6 N+2 real elements.
The time taken by E04CBF depends on the number of variables, the behaviour of the function and the distance of the starting point from the minimum. Each iteration consists of 1 or 2 function evaluations unless the size of the simplex is reduced, in which case n+1 function evaluations are required.

10 Example

This example finds a minimum of the function
F x 1,x 2 = e x 1 4 x 12 + 2 x 22 + 4 x 1 x 2 + 2 x 2 + 1 .
This example uses the initial point -1,1 (see Section 10.3), and we expect to reach the minimum at 0.5,-1 .

10.1 Program Text

Program Text (e04cbfe.f90)

10.2 Program Data

None.

10.3 Program Results

Program Results (e04cbfe.r)

GnuplotProduced by GNUPLOT 4.6 patchlevel 3 Example Program Contours of F Showing the Initial Point (X) and Local Minimum (*) * X gnuplot_plot_1 −1.5 −1 −0.5 0 0.5 1 1.5 −2 −1.5 −1 −0.5 0 0.5 1 1.5 2
E04 Chapter Contents
E04 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


E04 Chapter Contents : NAG Library Manual, Mark 26

E04 Chapter Introduction
NAG Library Manual

NAG Library Chapter Contents

E04 – Minimizing or Maximizing a Function

E04 Chapter Introduction – a description of the Chapter and an overview of the algorithms available

Routine Name | Mark of Introduction | Purpose
E04ABA Example Text | 20 | nagf_opt_one_var_func Minimum, function of one variable, using function values only
E04ABF Example Text | 6 | nagf_opt_one_var_func_old Minimum, function of one variable, using function values only
E04BBA Example Text | 20 | nagf_opt_one_var_deriv Minimum, function of one variable, using first derivative
E04BBF Example Text | 6 | nagf_opt_one_var_deriv_old Minimum, function of one variable, using first derivative
E04CBF Example Text Example Plot | 22 | nagf_opt_uncon_simplex Unconstrained minimum, Nelder–Mead simplex algorithm, using function values only
E04DGA Example Text Example Data | 20 | nagf_opt_uncon_conjgrd_comp Unconstrained minimum, preconditioned conjugate gradient algorithm, using first derivatives (comprehensive)
E04DGF Example Text Example Data | 12 | nagf_opt_uncon_conjgrd_comp_old Unconstrained minimum, preconditioned conjugate gradient algorithm, using first derivatives (comprehensive)
E04DJA Example Text Example Data Example Data | 20 | nagf_opt_uncon_conjgrd_option_file Supply optional parameter values for E04DGF/E04DGA from external file
E04DJF Example Text Example Options Example Data | 12 | nagf_opt_uncon_conjgrd_option_file_old Supply optional parameter values for E04DGF/E04DGA from external file
E04DKA | 20 | nagf_opt_uncon_conjgrd_option_string Supply optional parameter values to E04DGF/E04DGA from a character string
E04DKF | 12 | nagf_opt_uncon_conjgrd_option_string_old Supply optional parameter values to E04DGF/E04DGA from a character string
E04FCF Example Text Example Data | 7 | nagf_opt_lsq_uncon_mod_func_comp Unconstrained minimum of a sum of squares, combined Gauss–Newton and modified Newton algorithm, using function values only (comprehensive)
E04FYF Example Text Example Data | 18 | nagf_opt_lsq_uncon_mod_func_easy Unconstrained minimum of a sum of squares, combined Gauss–Newton and modified Newton algorithm, using function values only (easy-to-use)
E04GBF Example Text Example Data | 7 | nagf_opt_lsq_uncon_quasi_deriv_comp Unconstrained minimum of a sum of squares, combined Gauss–Newton and quasi-Newton algorithm, using first derivatives (comprehensive)
E04GDF Example Text Example Data | 7 | nagf_opt_lsq_uncon_mod_deriv_comp Unconstrained minimum of a sum of squares, combined Gauss–Newton and modified Newton algorithm, using first derivatives (comprehensive)
E04GYF Example Text Example Data | 18 | nagf_opt_lsq_uncon_quasi_deriv_easy Unconstrained minimum of a sum of squares, combined Gauss–Newton and quasi-Newton algorithm, using first derivatives (easy-to-use)
E04GZF Example Text Example Data | 18 | nagf_opt_lsq_uncon_mod_deriv_easy Unconstrained minimum of a sum of squares, combined Gauss–Newton and modified Newton algorithm, using first derivatives (easy-to-use)
E04HCF Example Text | 6 | nagf_opt_check_deriv Check user's routine for calculating first derivatives of function
E04HDF Example Text | 6 | nagf_opt_check_deriv2 Check user's routine for calculating second derivatives of function
E04HEF Example Text Example Data | 7 | nagf_opt_lsq_uncon_mod_deriv2_comp Unconstrained minimum of a sum of squares, combined Gauss–Newton and modified Newton algorithm, using second derivatives (comprehensive)
E04HYF Example Text Example Data | 18 | nagf_opt_lsq_uncon_mod_deriv2_easy Unconstrained minimum of a sum of squares, combined Gauss–Newton and modified Newton algorithm, using second derivatives (easy-to-use)
E04JCF Example Text | 23 | nagf_opt_bounds_bobyqa_func Bound constrained minimum, model-based algorithm, using function values only
E04JYF Example Text | 18 | nagf_opt_bounds_quasi_func_easy Bound constrained minimum, quasi-Newton algorithm, using function values only (easy-to-use)
E04KDF Example Text | 6 | nagf_opt_bounds_mod_deriv_comp Bound constrained minimum, modified Newton algorithm, using first derivatives (comprehensive)
E04KYF Example Text | 18 | nagf_opt_bounds_quasi_deriv_easy Bound constrained minimum, quasi-Newton algorithm, using first derivatives (easy-to-use)
E04KZF Example Text | 18 | nagf_opt_bounds_mod_deriv_easy Bound constrained minimum, modified Newton algorithm, using first derivatives (easy-to-use)
E04LBF Example Text | 6 | nagf_opt_bounds_mod_deriv2_comp Bound constrained minimum, modified Newton algorithm, using first and second derivatives (comprehensive)
E04LYF Example Text | 18 | nagf_opt_bounds_mod_deriv2_easy Bound constrained minimum, modified Newton algorithm, using first and second derivatives (easy-to-use)
E04MFA Example Text Example Data | 20 | nagf_opt_lp_solve Linear programming (LP), dense, active-set method
E04MFF Example Text Example Data | 16 | nagf_opt_lp_solve_old Linear programming (LP), dense, active-set method
E04MGA Example Text Example Data Example Data | 20 | nagf_opt_lp_option_file Supply optional parameter values for E04MFF/E04MFA from external file
E04MGF Example Text Example Options Example Data | 16 | nagf_opt_lp_option_file_old Supply optional parameter values for E04MFF/E04MFA from external file
E04MHA | 20 | nagf_opt_lp_option_string Supply optional parameter values to E04MFF/E04MFA from a character string
E04MHF | 16 | nagf_opt_lp_option_string_old Supply optional parameter values to E04MFF/E04MFA from a character string
E04MWF Example Text Example Data | 26 | nagf_opt_miqp_mps_write Write MPS data file defining LP, QP, MILP or MIQP problem
E04MXF Example Text Example Options | 24 | nagf_opt_miqp_mps_read Read MPS data file defining LP, QP, MILP or MIQP problem
E04MZF Example Text Example Options | 18 | nagf_opt_qpconvex1_sparse_mps Read MPS data file defining LP or QP problem, deprecated
E04NCA Example Text Example Data | 20 | nagf_opt_lsq_lincon_solve Linear programming (LP) convex quadratic programming (QP) or linearly-constrained linear least squares problem, dense
E04NCF Example Text Example Data | 12 | nagf_opt_lsq_lincon_solve_old Linear programming (LP) convex quadratic programming (QP) or linearly-constrained linear least squares problem, dense
E04NDA Example Text Example Data Example Data | 20 | nagf_opt_lsq_lincon_option_file Supply optional parameter values for E04NCF/E04NCA from external file
E04NDF Example Text Example Options Example Data | 12 | nagf_opt_lsq_lincon_option_file_old Supply optional parameter values for E04NCF/E04NCA from external file
E04NEA | 20 | nagf_opt_lsq_lincon_option_string Supply optional parameter values to E04NCF/E04NCA from a character string
E04NEF | 12 | nagf_opt_lsq_lincon_option_string_old Supply optional parameter values to E04NCF/E04NCA from a character string
E04NFA Example Text Example Data | 20 | nagf_opt_qp_dense_solve General (possibly non-convex) quadratic programming (QP) , dense, active-set method
E04NFF Example Text Example Data | 16 | nagf_opt_qp_dense_solve_old General (possibly non-convex) quadratic programming (QP) , dense, active-set method
E04NGA Example Text Example Data Example Data | 20 | nagf_opt_qp_dense_option_file Supply optional parameter values for E04NFF/E04NFA from external file
E04NGF Example Text Example Options Example Data | 16 | nagf_opt_qp_dense_option_file_old Supply optional parameter values for E04NFF/E04NFA from external file
E04NHA | 20 | nagf_opt_qp_dense_option_string Supply optional parameter values to E04NFF/E04NFA from a character string
E04NHF | 16 | nagf_opt_qp_dense_option_string_old Supply optional parameter values to E04NFF/E04NFA from a character string
E04NKA Example Text Example Data | 20 | nagf_opt_qpconvex1_sparse_solve Linear programming (LP) or convex quadratic programming (QP), sparse, active-set method
E04NKF Example Text Example Data | 18 | nagf_opt_qpconvex1_sparse_solve_old Linear programming (LP) or convex quadratic programming (QP), sparse, active-set method
E04NLA Example Text Example Data Example Data | 20 | nagf_opt_qpconvex1_sparse_option_file Supply optional parameter values for E04NKF/E04NKA from external file
E04NLF Example Text Example Options Example Data | 18 | nagf_opt_qpconvex1_sparse_option_file_old Supply optional parameter values for E04NKF/E04NKA from external file
E04NMA | 20 | nagf_opt_qpconvex1_sparse_option_string Supply optional parameter values to E04NKF/E04NKA from a character string
E04NMF | 18 | nagf_opt_qpconvex1_sparse_option_string_old Supply optional parameter values to E04NKF/E04NKA from a character string
E04NPF | 21 | nagf_opt_qpconvex2_sparse_init Initialization routine for E04NQF
E04NQF Example Text Example Data | 21 | nagf_opt_qpconvex2_sparse_solve Linear programming (LP) or convex quadratic programming (QP), sparse, active-set method, recommended
E04NRF Example Text Example Options Example Data | 21 | nagf_opt_qpconvex2_sparse_option_file Supply optional parameter values for E04NQF from external file
E04NSF | 21 | nagf_opt_qpconvex2_sparse_option_string Set a single option for E04NQF from a character string
E04NTF | 21 | nagf_opt_qpconvex2_sparse_option_integer_set Set a single option for E04NQF from an integer argument
E04NUF | 21 | nagf_opt_qpconvex2_sparse_option_double_set Set a single option for E04NQF from a real argument
E04NXF | 21 | nagf_opt_qpconvex2_sparse_option_integer_get Get the setting of an integer valued option of E04NQF
E04NYF | 21 | nagf_opt_qpconvex2_sparse_option_double_get Get the setting of a real valued option of E04NQF
E04PCF Example Text Example Data | 24 | nagf_bnd_lin_lsq Computes the least squares solution to a set of linear equations subject to fixed upper and lower bounds on the variables. An option is provided to return a minimal length solution if a solution is not unique
E04RAF | 26 | nagf_opt_handle_init Initialization of a handle for the NAG optimization modelling suite for problems, such as, quadratic programming (QP), nonlinear programming (NLP), linear semidefinite programming (SDP) or SDP with bilinear matrix inequalities (BMI-SDP)
E04RDF Example Text Example Options | 26 | nagf_opt_sdp_read_sdpa A reader of sparse SDPA data files for linear SDP problems
E04REF | 26 | nagf_opt_handle_set_linobj Define a linear objective function to a problem initialized by E04RAF
E04RFF Example Text Example Data | 26 | nagf_opt_handle_set_quadobj Define a linear or a quadratic objective function to a problem initialized by E04RAF
E04RGF | 26 | nagf_opt_handle_set_nlnobj Define a nonlinear objective function to a problem initialized by E04RAF
E04RHF Example Text Example Data | 26 | nagf_opt_handle_set_simplebounds Define bounds of variables of a problem initialized by E04RAF
E04RJF Example Text Example Options | 26 | nagf_opt_handle_set_linconstr Define a block of linear constraints to a problem initialized by E04RAF
E04RKF | 26 | nagf_opt_handle_set_nlnconstr Define a block of nonlinear constraints to a problem initialized by E04RAF
E04RLF | 26 | nagf_opt_handle_set_nlnhess Define a structure of Hessian of the objective, constraints or the Lagrangian to a problem initialized by E04RAF
E04RNF Example Text Example Data | 26 | nagf_opt_handle_set_linmatineq Add one or more linear matrix inequality constraints to a problem initialized by E04RAF
E04RPF Example Text Example Data | 26 | nagf_opt_handle_set_quadmatineq Define bilinear matrix terms to a problem initialized by E04RAF
E04RYF Example Text | 26 | nagf_opt_handle_print Print information about a problem handle initialized by E04RAF
E04RZF | 26 | nagf_opt_handle_free Destroy the problem handle initialized by E04RAF and deallocate all the memory used
E04STF Example Text | 26 | nagf_opt_handle_solve_ipopt Run an interior point solver on a sparse nonlinear programming problem (NLP) initialized by E04RAF and defined by other routines from the suite
E04SVF Example Text Example Data | 26 | nagf_opt_handle_solve_pennon Run the Pennon solver on a compatible problem initialized by E04RAF and defined by other routines from the suite, such as, semidefinite programming (SDP) and SDP with bilinear matrix inequalities (BMI)
E04UCA Example Text Example Data | 20 | nagf_opt_nlp1_solve Nonlinear programming (NLP), dense, active-set SQP method, using function values and optionally first derivatives, recommended
E04UCF Example Text Example Data | 12 | nagf_opt_nlp1_solve_old Nonlinear programming (NLP), dense, active-set SQP method, using function values and optionally first derivatives, recommended
E04UDA Example Text Example Data Example Data | 20 | nagf_opt_nlp1_option_file Supply optional parameter values for E04UCF/E04UCA or E04UFF/E04UFA from external file
E04UDF Example Text Example Options Example Data | 12 | nagf_opt_nlp1_option_file_old Supply optional parameter values for E04UCF/E04UCA or E04UFF/E04UFA from external file
E04UEA | 20 | nagf_opt_nlp1_option_string Supply optional parameter values to E04UCF/E04UCA or E04UFF/E04UFA from a character string
E04UEF | 12 | nagf_opt_nlp1_option_string_old Supply optional parameter values to E04UCF/E04UCA or E04UFF/E04UFA from a character string
E04UFA Example Text Example Data | 20 | nagf_opt_nlp1_rcomm Nonlinear programming (NLP), dense, active-set, SQP method, using function values and optionally first derivatives (reverse communication, comprehensive)
E04UFF Example Text Example Data | 18 | nagf_opt_nlp1_rcomm_old Nonlinear programming (NLP), dense, active-set, SQP method, using function values and optionally first derivatives (reverse communication, comprehensive)
E04UGA Example Text Example Data | 20 | nagf_opt_nlp1_sparse_solve Nonlinear programming (NLP), sparse, active-set SQP method, using function values and optionally first derivatives
E04UGF Example Text Example Data | 19 | nagf_opt_nlp1_sparse_solve_old Nonlinear programming (NLP), sparse, active-set SQP method, using function values and optionally first derivatives
E04UHA Example Text Example Data Example Data | 20 | nagf_opt_withdraw_nlp1_sparse_option_file Supply optional parameter values for E04UGF/E04UGA from external file
E04UHF Example Text Example Options Example Data | 19 | nagf_opt_nlp1_sparse_option_file_old Supply optional parameter values for E04UGF/E04UGA from external file
E04UJA | 20 | nagf_opt_nlp1_withdraw_sparse_option_string Supply optional parameter values to E04UGF/E04UGA from a character string
E04UJF | 19 | nagf_opt_nlp1_sparse_option_string_old Supply optional parameter values to E04UGF/E04UGA from a character string
E04UQA Example Text Example Data Example Data | 20 | nagf_opt_lsq_gencon_deriv_option_file Supply optional parameter values for E04USF/E04USA from external file
E04UQF Example Text Example Options Example Data | 14 | nagf_opt_lsq_gencon_deriv_option_file_old Supply optional parameter values for E04USF/E04USA from external file
E04URA | 20 | nagf_opt_lsq_gencon_deriv_option_string Supply optional parameter values to E04USF/E04USA from a character string
E04URF | 14 | nagf_opt_lsq_gencon_deriv_option_string_old Supply optional parameter values to E04USF/E04USA from a character string
E04USA Example Text Example Data | 20 | nagf_opt_lsq_gencon_deriv Minimum of a sum of squares, nonlinear constraints, dense, active-set SQP method, using function values and optionally first derivatives
E04USF Example Text Example Data | 14 | nagf_opt_lsq_gencon_deriv_old Minimum of a sum of squares, nonlinear constraints, dense, active-set SQP method, using function values and optionally first derivatives
E04VGF | 21 | nagf_opt_nlp2_sparse_init Initialization routine for E04VHF
E04VHF Example Text Example Data | 21 | nagf_opt_nlp2_sparse_solve Nonlinear programming (NLP), sparse, active-set SQP method, using function values and optionally first derivatives, recommended
E04VJF Example Text Example Data | 21 | nagf_opt_nlp2_sparse_jacobian Determine the pattern of nonzeros in the Jacobian matrix for E04VHF
E04VKF Example Text Example Options Example Data | 21 | nagf_opt_nlp2_sparse_option_file Supply optional parameter values for E04VHF from external file
E04VLF | 21 | nagf_opt_nlp2_sparse_option_string Set a single option for E04VHF from a character string
E04VMF | 21 | nagf_opt_nlp2_sparse_option_integer_set Set a single option for E04VHF from an integer argument
E04VNF | 21 | nagf_opt_nlp2_sparse_option_double_set Set a single option for E04VHF from a real argument
E04VRF | 21 | nagf_opt_nlp2_sparse_option_integer_get Get the setting of an integer valued option of E04VHF
E04VSF | 21 | nagf_opt_nlp2_sparse_option_double_get Get the setting of a real valued option of E04VHF
E04WBF | 20 | nagf_opt_init Initialization routine for E04DGA, E04MFA, E04NCA, E04NFA, E04NKA, E04UCA, E04UFA, E04UGA and E04USA
E04WCF | 21 | nagf_opt_nlp2_init Initialization routine for E04WDF
E04WDF Example Text Example Data | 21 | nagf_opt_nlp2_solve Nonlinear programming (NLP), dense, active-set SQP method, using function values and optionally first derivatives
E04WEF Example Text Example Options Example Data | 21 | nagf_opt_nlp2_option_file Supply optional parameter values for E04WDF from external file
E04WFF | 21 | nagf_opt_nlp2_option_string Set a single option for E04WDF from a character string
E04WGF | 21 | nagf_opt_nlp2_option_integer_set Set a single option for E04WDF from an integer argument
E04WHF | 21 | nagf_opt_nlp2_option_double_set Set a single option for E04WDF from a real argument
E04WKF | 21 | nagf_opt_nlp2_option_integer_get Get the setting of an integer valued option of E04WDF
E04WLF | 21 | nagf_opt_nlp2_option_double_get Get the setting of a real valued option of E04WDF
E04XAA Example Text | 20 | nagf_opt_estimate_deriv Estimate (using numerical differentiation) gradient and/or Hessian of a function
E04XAF Example Text | 12 | nagf_opt_estimate_deriv_old Estimate (using numerical differentiation) gradient and/or Hessian of a function
E04YAF Example Text Example Data | 7 | nagf_opt_lsq_check_deriv Check user's routine for calculating Jacobian of first derivatives
E04YBF Example Text Example Data | 7 | nagf_opt_lsq_check_hessian Check user's routine for calculating Hessian of a sum of squares
E04YCF Example Text Example Data | 11 | nagf_opt_lsq_uncon_covariance Covariance matrix for nonlinear least squares problem (unconstrained)
E04ZMF | 26 | nagf_opt_handle_opt_set Option setting routine for the solvers from the NAG optimization modelling suite
E04ZNF | 26 | nagf_opt_handle_opt_get Option getting routine for the solvers from the NAG optimization modelling suite
E04ZPF | 26 | nagf_opt_handle_opt_set_file Option setting routine for the solvers from the NAG optimization modelling suite from external file
E04 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


E04DGF/E04DGA : NAG Library, Mark 26

E04 Chapter Contents
E04 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

E04DGF/E04DGA

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.
Note: this routine uses optional parameters to define choices in the problem specification and in the details of the algorithm. If you wish to use default settings for all of the optional parameters, you need only read Sections 1 to 10 of this document. If, however, you wish to reset some or all of the settings please refer to Section 11 for a detailed description of the algorithm and to Section 12 for a detailed description of the specification of the optional parameters.

▸▿ Contents

1 Purpose
▸▿ 2 Specification
2.1 Specification for E04DGF
2.2 Specification for E04DGA
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
▸▿ 9 Further Comments
9.1 Description of Printed Output
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results
11 Algorithmic Details
▸▿ 12 Optional Parameters
12.1 Description of the Optional Parameters

1 Purpose

E04DGF/E04DGA minimizes an unconstrained nonlinear function of several variables using a pre-conditioned, limited memory quasi-Newton conjugate gradient method. First derivatives (or an ‘acceptable’ finite difference approximation to them) are required. It is intended for use on large scale problems.
E04DGA is a version of E04DGF that has additional arguments in order to make it safe for use in multithreaded applications (see Section 5). The initialization routine E04WBF must have been called before calling E04DGA.

2 Specification

2.1 Specification for E04DGF

SUBROUTINE E04DGF ( N, OBJFUN, ITER, OBJF, OBJGRD, X, IWORK, WORK, IUSER, RUSER, IFAIL)
INTEGER | N, ITER, IWORK(N+1), IUSER(*), IFAIL
REAL (KIND=nag_wp) | OBJF, OBJGRD(N), X(N), WORK(13*N), RUSER(*)
EXTERNAL | OBJFUN

2.2 Specification for E04DGA

SUBROUTINE E04DGA ( N, OBJFUN, ITER, OBJF, OBJGRD, X, IWORK, WORK, IUSER, RUSER, LWSAV, IWSAV, RWSAV, IFAIL)
INTEGER | N, ITER, IWORK(N+1), IUSER(*), IWSAV(610), IFAIL
REAL (KIND=nag_wp) | OBJF, OBJGRD(N), X(N), WORK(13*N), RUSER(*), RWSAV(475)
LOGICAL | LWSAV(120)
EXTERNAL | OBJFUN
Before calling E04DGA, or either of the option setting routines E04DJA or E04DKA, routine E04WBF must be called. The specification for E04WBF is:
SUBROUTINE E04WBF ( RNAME, CWSAV, LCWSAV, LWSAV, LLWSAV, IWSAV, LIWSAV, RWSAV, LRWSAV, IFAIL)
INTEGER | LCWSAV, LLWSAV, IWSAV(LIWSAV), LIWSAV, LRWSAV, IFAIL
REAL (KIND=nag_wp) | RWSAV(LRWSAV)
LOGICAL | LWSAV(LLWSAV)
CHARACTER(*) | RNAME
CHARACTER(80) | CWSAV(LCWSAV)
E04WBF should be called with RNAME='E04DGA'. LCWSAV, LLWSAV, LIWSAV and LRWSAV, the declared lengths of CWSAV, LWSAV, IWSAV and RWSAV respectively, must satisfy:
  • LCWSAV≥1
  • LLWSAV≥120
  • LIWSAV≥610
  • LRWSAV≥475
The contents of the arrays CWSAV, LWSAV, IWSAV and RWSAV must not be altered between calling routines E04DGA, E04DJA, E04DKA and E04WBF.

3 Description

E04DGF/E04DGA is designed to solve unconstrained minimization problems of the form
minimize x∈Rn F x  subject to  -∞≤x≤∞,
where x is an n-element vector.
You must supply an initial estimate of the solution.
For maximum reliability, it is preferable to provide all first partial derivatives. If all of the derivatives cannot be provided, you are recommended to obtain approximate values (using finite differences) by calling E04XAF/E04XAA from within OBJFUN. This is illustrated in Section 10 in E04DJF/E04DJA.
The method used by E04DGF/E04DGA is described in Section 11.

4 References

Gill P E and Murray W (1979) Conjugate-gradient methods for large-scale nonlinear optimization Technical Report SOL 79-15 Department of Operations Research, Stanford University
Gill P E, Murray W and Wright M H (1981) Practical Optimization Academic Press

5 Arguments

1:   N – INTEGERInput
On entry: n, the number of variables.
Constraint: N>0.
2:   OBJFUN – SUBROUTINE, supplied by the user.External Procedure
OBJFUN must calculate the objective function F x and possibly its gradient as well for a specified n-element vector x.
The specification of OBJFUN is:
SUBROUTINE OBJFUN ( MODE, N, X, OBJF, OBJGRD, NSTATE, IUSER, RUSER)
INTEGER | MODE, N, NSTATE, IUSER(*)
REAL (KIND=nag_wp) | X(N), OBJF, OBJGRD(N), RUSER(*)
1:   MODE – INTEGERInput/Output
On entry: indicates which values must be assigned during each call of OBJFUN. Only the following values need be assigned:
MODE=0
OBJF.
MODE=2
OBJF and OBJGRD.
On exit: may be set to a negative value if you wish to terminate the solution to the current problem, and in this case E04DGF/E04DGA will terminate with IFAIL set to MODE.
2:   N – INTEGERInput
On entry: n, the number of variables.
3:   X N – REAL (KIND=nag_wp) arrayInput
On entry: x, the vector of variables at which the objective function and its gradient are to be evaluated.
4:   OBJF – REAL (KIND=nag_wp)Output
On exit: the value of the objective function at x.
5:   OBJGRD N – REAL (KIND=nag_wp) arrayOutput
On exit: if MODE=2, OBJGRD i must contain the value of ∂F ∂xi evaluated at x, for i=1,2,…,n.
6:   NSTATE – INTEGERInput
On entry: will be 1 on the first call of OBJFUN by E04DGF/E04DGA, and 0 for all subsequent calls. Thus, you may wish to test, NSTATE within OBJFUN in order to perform certain calculations once only. For example, you may read data or initialize COMMON blocksglobal variables when NSTATE=1.
7:   IUSER* – INTEGER arrayUser Workspace
8:   RUSER* – REAL (KIND=nag_wp) arrayUser Workspace
OBJFUN is called with the arguments IUSER and RUSER as supplied to E04DGF/E04DGA. You are free to use the arrays IUSER and RUSER to supply information to OBJFUN as an alternative to using COMMON global variables.
OBJFUN must either be a module subprogram USEd by, or declared as EXTERNAL in, the (sub)program from which E04DGF/E04DGA is called. Arguments denoted as Input must not be changed by this procedure.
Note: OBJFUN should be tested separately before being used in conjunction with E04DGF/E04DGA. See also the description of the optional parameter Verify.
3:   ITER – INTEGEROutput
On exit: the total number of iterations performed.
4:   OBJF – REAL (KIND=nag_wp)Output
On exit: the value of the objective function at the final iterate.
5:   OBJGRD N – REAL (KIND=nag_wp) arrayOutput
On exit: the gradient of the objective function at the final iterate (or its finite difference approximation).
6:   X N – REAL (KIND=nag_wp) arrayInput/Output
On entry: an initial estimate of the solution.
On exit: the final estimate of the solution.
7:   IWORK N+1 – INTEGER arrayWorkspace
8:   WORK 13×N – REAL (KIND=nag_wp) arrayWorkspace
9:   IUSER* – INTEGER arrayUser Workspace
10:   RUSER* – REAL (KIND=nag_wp) arrayUser Workspace
IUSER and RUSER are not used by E04DGF/E04DGA, but are passed directly to OBJFUN and may be used to pass information to this routine as an alternative to using COMMON global variables.
11:   IFAIL – INTEGERInput/Output
Note: for E04DGA, IFAIL does not occur in this position in the argument list. See the additional arguments described below.
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, because for this routine the values of the output arguments may be useful even if IFAIL≠0 on exit, the recommended value is -1. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).
E04DGF/E04DGA returns with IFAIL=0 if the following three conditions are satisfied:
(i) | F k-1-Fk<τF 1+Fk
(ii) | x k-1-xk<τF 1+xk
(iii) | gk≤τF 3 1+Fk or gk<εA
where τF is the value of the optional parameter Optimality Tolerance (default value=ε 0.8) and εA is the absolute error associated with computing the objective function.
For a full discussion on termination criteria see Chapter 8 of Gill et al. (1981).
Note: the following are additional arguments for specific use with E04DGA. Users of E04DGF therefore need not read the remainder of this description.
11:   LWSAV 120 – LOGICAL arrayCommunication Array
12:   IWSAV 610 – INTEGER arrayCommunication Array
13:   RWSAV 475 – REAL (KIND=nag_wp) arrayCommunication Array
The arrays LWSAV, IWSAV and RWSAV must not be altered between calls to any of the routines E04DGA, E04DJA, E04DKA or E04WBF.
14:   IFAIL – INTEGERInput/Output
Note: see the argument description for IFAIL above.

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Note: E04DGF/E04DGA may return useful information for one or more of the following detected errors or warnings.
Errors or warnings detected by the routine:
IFAIL<0
A negative value of IFAIL indicates an exit from E04DGF/E04DGA because you set MODE<0 in OBJFUN. The value of IFAIL will be the same as your setting of MODE.
IFAIL=1
Not used by this routine.
IFAIL=2
Not used by this routine.
IFAIL=3
The limiting number of iterations (as determined by the optional parameter Iteration Limit (default value=max 50,5 n) has been reached.
If the algorithm appears to be making satisfactory progress, then optional parameter Iteration Limit may be too small. If so, increase its value and rerun E04DGF/E04DGA. If the algorithm seems to be making little or no progress, then you should check for incorrect gradients as described under IFAIL=7.
IFAIL=4
The computed upper bound on the step length taken during the linesearch was too small. A rerun with an increased value of the optional parameter Maximum Step Length (ρ say) may be successful unless ρ≥1020 (the default value), in which case the current point cannot be improved upon.
IFAIL=5
Not used by this routine.
IFAIL=6
The conditions for an acceptable solution (see argument IFAIL in Section 5) have not all been met, but a lower point could not be found.
If OBJFUN computes the objective function and its gradient correctly, then this may occur because an overly stringent accuracy has been requested, i.e., the value of the optional parameter Optimality Tolerance (default value=ε 0.8) is too small or if αk≃0. In this case you should apply the three tests described under IFAIL=0 to determine whether or not the final solution is acceptable. For a discussion of attainable accuracy see Gill et al. (1981).
If many iterations have occurred in which essentially no progress has been made or E04DGF/E04DGA has failed to move from the initial point, OBJFUN may be incorrect. You should refer to the comments below under IFAIL=7 and check the gradients using the optional parameter Verify (default value=0). Unfortunately, there may be small errors in the objective gradients that cannot be detected by the verification process. Finite difference approximations to first derivatives are catastrophically affected by even small inaccuracies.
IFAIL=7
The user-supplied derivatives of the objective function appear to be incorrect.
Large errors were found in the derivatives of the objective function. This value of IFAIL will occur if the verification process indicated that at least one gradient element had no correct figures. You should refer to the printed output to determine which elements are suspected to be in error.
As a first step, you should check that the code for the objective values is correct – for example, by computing the function at a point where the correct value is known. However, care should be taken that the chosen point fully tests the evaluation of the function. It is remarkable how often the values x=0 or x=1 are used to test function evaluation procedures, and how often the special properties of these numbers make the test meaningless.
Special care should be used in this test if computation of the objective function involves subsidiary data communicated in COMMON storage. Although the first evaluation of the function may be correct, subsequent calculations may be in error because some of the subsidiary data has accidentally been overwritten.
Errors in programming the function may be quite subtle in that the function value is almost correct. For example, the function may not be accurate to full precision because of the inaccurate calculation of a subsidiary quantity, or the limited accuracy of data upon which the function depends. A common error on machines where numerical calculations are usually performed in double precision is to include even one single precision constant in the calculation of the function; since some compilers do not convert such constants to double precision, half the correct figures may be lost by such a seemingly trivial error.
IFAIL=8
The gradient g= ∂F ∂x at the starting point x 0 is ‘too small’. More precisely, the value of g x 0 T g x 0 is less than εr 1+F x 0, where εr is the value of the optional parameter Function Precision (default value=ε 0.9).
The problem should be rerun from a different starting point.
IFAIL=9
An input argument is invalid.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

On successful exit (IFAIL=0) the accuracy of the solution will be as defined by the optional parameter Optimality Tolerance (default value=ε 0.8).

8 Parallelism and Performance

E04DGF/E04DGA makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

To evaluate an ‘acceptable’ set of finite difference intervals using E04XAF/E04XAA requires 2 function evaluations per variable for a well-scaled problem and up to 6 function evaluations per variable for a badly scaled problem.

9.1 Description of Printed Output

This section describes the intermediate printout and final printout produced by E04DGF/E04DGA. You can control the level of printed output (see the description of the optional parameter Print Level). Note that the intermediate printout and final printout are produced only if Print Level≥10 (the default for E04DGF, by default no output is produced by E04DGA).
The following line of summary output (<80 characters) is produced at every iteration. In all cases, the values of the quantities are those in effect on completion of the given iteration.
Itn | is the iteration count.
Step | is the step αk taken along the computed search direction. On reasonably well-behaved problems, the unit step (i.e., αk=1) will be taken as the solution is approached.
Nfun | is the cumulated number of evaluations of the objective function needed for the linesearch. Evaluations needed for the verification of the gradients by finite differences are not included. Nfun is printed as a guide to the amount of work required for the linesearch. E04DGF/E04DGA will perform at most 11 function evaluations per iteration.
Objective | is the value of the objective function at xk.
Norm G | is the Euclidean norm of the gradient of the objective function at xk.
Norm X | is the Euclidean norm of xk.
Norm (X(k-1)-X(k)) | is the Euclidean norm of x k-1-xk.
The following describes the printout for each variable.
Variable | gives the name (Varbl) and index j, for j=1,2,…,n of the variable.
Value | is the value of the variable at the final iteration.
Gradient Value | is the value of the gradient of the objective function with respect to the jth variable at the final iteration.
Numerical values are output with a fixed number of digits; they are not guaranteed to be accurate to this precision.

10 Example

This example finds a minimum of the function
F=e x 1 4 x 12+2 x 22+4 x 1x 2+2 x 2+1.
The initial point is
x 0 = -1.0,1.0 T ,
and F x 0=1.8394 (to five figures).
The optimal solution is
x* = 0.5,-1.0 T ,
and F x*=0.
The document for E04DJF/E04DJA includes an example program to solve the same problem using some of the optional parameters described in Section 12.

10.1 Program Text

Note: the following programs illustrate the use of E04DGF and E04DGA.

Program Text (e04dgfe.f90)

Program Text (e04dgae.f90)

10.2 Program Data

Program Data (e04dgfe.d)

Program Data (e04dgae.d)

10.3 Program Results

Program Results (e04dgfe.r)

Program Results (e04dgae.r)

Note: the remainder of this document is intended for more advanced users. Section 11 contains a detailed description of the algorithm which may be needed in order to understand Section 12. Section 12 describes the optional parameters which may be set by calls to E04DJF/E04DJA and/or E04DKF/E04DKA.

11 Algorithmic Details

This section contains a description of the method used by E04DGF/E04DGA.
E04DGF/E04DGA uses a pre-conditioned conjugate gradient method and is based upon algorithm PLMA as described in Section 4.8.3 of Gill and Murray (1979) and Gill et al. (1981).
The algorithm proceeds as follows:
Let x 0 be a given starting point and let k denote the current iteration, starting with k=0. The iteration requires gk, the gradient vector evaluated at xk, the kth estimate of the minimum. At each iteration a vector pk (known as the direction of search) is computed and the new estimate x k+1 is given by xk+αkpk where αk (the step length) minimizes the function F xk+αkpk with respect to the scalar αk. A choice of initial step α 0 is taken as
α 0 = min 1, 2 × Fk-Fest / gkT gk
where Fest is a user-supplied estimate of the function value at the solution. If Fest is not specified, the software always chooses the unit step length for α 0. Subsequent step length estimates are computed using cubic interpolation with safeguards.
A quasi-Newton method can be used to compute the search direction pk by updating the inverse of the approximate Hessian Hk and computing
p k+1=-H k+1g k+1. (1)
The updating formula for the approximate inverse is given by
H k+1 = Hk - 1 ykT sk Hk yk skT + sk ykT Hk + 1 ykT sk 1 + ykT Hk yk ykT sk sk skT , (2)
where yk=g k-1-gk and sk=x k+1-xk=αkpk.
The method used to obtain the search direction is based upon computing p k+1 as -H k+1 g k+1 where H k+1 is a matrix obtained by updating the identity matrix with a limited number of quasi-Newton corrections. The storage of an n by n matrix is avoided by storing only the vectors that define the rank two corrections – hence the term ‘limited-memory’ quasi-Newton method. The precise method depends upon the number of updating vectors stored. For example, the direction obtained with the ‘one-step’ limited memory update is given by (1) using (2) with Hk equal to the identity matrix, viz.
p k+1 = - g k+1 + 1 ykT sk skT g k+1 yk + ykT g k+1 sk - skT g k+1 ykT sk 1 + ykT yk ykT sk sk .
Using a limited-memory quasi-Newton formula, such as the one above, guarantees p k+1 to be a descent direction if all the inner products ykT sk are positive for all vectors yk and sk used in the updating formula.

12 Optional Parameters

Several optional parameters in E04DGF/E04DGA define choices in the problem specification or the algorithm logic. In order to reduce the number of formal arguments of E04DGF/E04DGA these optional parameters have associated default values that are appropriate for most problems. Therefore, you need only specify those optional parameters whose values are to be different from their default values.
The remainder of this section can be skipped if you wish to use the default values for all optional parameters.
The following is a list of the optional parameters available. A full description of each optional parameter is provided in Section 12.1.
  • Defaults
  • Estimated Optimal Function Value
  • Function Precision
  • Iteration Limit
  • Iters
  • Itns
  • Linesearch Tolerance
  • List
  • Maximum Step Length
  • Nolist
  • Optimality Tolerance
  • Print Level
  • Start Objective Check at Variable
  • Stop Objective Check at Variable
  • Verify
  • Verify Gradients
  • Verify Level
  • Verify Objective Gradients
Optional parameters may be specified by calling one, or both, of the routines E04DJF/E04DJA and E04DKF/E04DKA before a call to E04DGF/E04DGA.
E04DJF/E04DJA reads options from an external options file, with Begin and End as the first and last lines respectively and each intermediate line defining a single optional parameter. For example,
Begin
   Print Level = 1
End
The call
 CALL E04DJF (IOPTNS, INFORM)
can then be used to read the file on unit IOPTNS. INFORM will be zero on successful exit. E04DJF/E04DJA should be consulted for a full description of this method of supplying optional parameters.
E04DKF/E04DKA can be called to supply options directly, one call being necessary for each optional parameter. For example,
 CALL E04DKF ('Print Level = 1')
E04DKF/E04DKA should be consulted for a full description of this method of supplying optional parameters.
All optional parameters not specified by you are set to their default values. Optional parameters specified by you are unaltered by E04DGF/E04DGA (unless they define invalid values) and so remain in effect for subsequent calls unless altered by you.

12.1 Description of the Optional Parameters

For each option, we give a summary line, a description of the optional parameter and details of constraints.
The summary line contains:
  • the keywords, where the minimum abbreviation of each keyword is underlined (if no characters of an optional qualifier are underlined, the qualifier may be omitted);
  • a parameter value, where the letters a, i and r denote options that take character, integer and real values respectively;
  • the default value, where the symbol ε is a generic notation for machine precision (see X02AJF), and εr denotes the relative precision of the objective function Function Precision.
Keywords and character values are case and white space insensitive.
Defaults
This special keyword may be used to reset all optional parameters to their default values.
Estimated Optimal Function Value r
This value of r specifies the user-supplied guess of the optimum objective function value Fest. This value is used to calculate an initial step length α 0 (see Section 11). If the value of r is not specified (the default), then this has the effect of setting α 0 to unity. It should be noted that for badly scaled functions a unit step along the steepest descent direction will often compute the objective function at very large values of x.
Function Precision r Default =ε 0.9
The parameter defines εr, which is intended to be a measure of the accuracy with which the problem function F x can be computed. If r<ε or r≥1, the default value is used.
The value of εr should reflect the relative precision of 1+F x; i.e., εr acts as a relative precision when F is large, and as an absolute precision when F is small. For example, if F x is typically of order 1000 and the first six significant digits are known to be correct, an appropriate value for εr would be 10-6. In contrast, if F x is typically of order 10-4 and the first six significant digits are known to be correct, an appropriate value for εr would be 10-10. The choice of εr can be quite complicated for badly scaled problems; see Chapter 8 of Gill et al. (1981) for a discussion of scaling techniques. The default value is appropriate for most simple functions that are computed with full accuracy. However when the accuracy of the computed function values is known to be significantly worse than full precision, the value of εr should be large enough so that no attempt will be made to distinguish between function values that differ by less than the error inherent in the calculation.
Iteration Limit i Default =max 50,5 n
Iters
Itns
The value of i specifies the maximum number of iterations allowed before termination. If i<0, the default value is used.
Problems whose Hessian matrices at the solution contain sets of clustered eigenvalues are likely to be minimized in significantly fewer than n iterations. Problems without this property may require anything between n and 5 n iterations, with approximately 2 n iterations being a common figure for moderately difficult problems.
Linesearch Tolerance r Default =0.9
The value r controls the accuracy with which the step α taken during each iteration approximates a minimum of the function along the search direction (the smaller the value of r, the more accurate the linesearch). The default value r=0.9 requests an inaccurate search, and is appropriate for most problems. A more accurate search may be appropriate when it is desirable to reduce the number of iterations – for example, if the objective function is cheap to evaluate. If r<0 or r≥1, the default value is used.
List Default for E04DGF =List
Nolist Default for E04DGA =Nolist
Normally each optional parameter specification is printed as it is supplied. Optional parameter Nolist may be used to suppress the printing and optional parameter List may be used to restore printing.
Maximum Step Length r Default =1020
If r>0, the maximum allowable step length for the linesearch is taken as min 1 X02AMF,r pk . If r≤0, the default value is used.
Optimality Tolerance r Default =εR 0.8
The parameter r specifies the accuracy to which you wish the final iterate to approximate a solution of the problem. Broadly speaking, r indicates the number of correct figures desired in the objective function at the solution. For example, if r is 10-6 and termination occurs with IFAIL=0 (see Section 5), then the final point satisfies the termination criteria, where τF represents Optimality Tolerance. If r<εr or r≥1, the default value is used. If Optimality Tolerance is chosen below a certain threshold, it will automatically be reset to another value.
Print Level i Default for E04DGF =10
Default for E04DGA =0
The value i controls the amount of printout produced by E04DGF/E04DGA, as indicated below. A detailed description of the printout is given in Section 9.1 (summary output at each iteration and the final solution).
i | Output
0 0 | No output.
0 1 | The final solution only.
0 5 | One line of summary output (<80 characters; see Section 9.1) for each iteration (no printout of the final solution).
10 | The final solution and one line of summary output for each iteration.
Start Objective Check at Variable i 1 Default =1
Stop Objective Check at Variable i 2 Default =n
These keywords take effect only if Verify Level>0. They may be used to control the verification of gradient elements computed by OBJFUN. For example, if the first 30 elements of the objective gradient appeared to be correct in an earlier run, so that only element 31 remains questionable, it is reasonable to specify Start Objective Check at Variable=31. If the first 30 variables appear linearly in the objective, so that the corresponding gradient elements are constant, the above choice would also be appropriate.
If i 1≤0 or i 1>max 1,min n,i 2, the default value is used. If i 2≤0 or i 2>n, the default value is used.
Verify Level i Default =0
Verify
Verify Gradients
Verify Objective Gradients
These keywords refer to finite difference checks on the gradient elements computed by OBJFUN. Gradients are verified at the user-supplied initial estimate of the solution. The possible choices for i are as follows:
i | Meaning
-1 | No checks are performed.
-0 | Only a ‘cheap’ test will be performed, requiring one call to OBJFUN.
-1 | In addition to the ‘cheap’ test, individual gradient elements will also be checked using a reliable (but more expensive) test.
For example, the objective gradient will be verified if Verify, Verify=YES, Verify Gradients, Verify Objective Gradients or Verify Level=1 is specified.
E04 Chapter Contents
E04 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


E04DJF/E04DJA : NAG Library, Mark 26

E04 Chapter Contents
E04 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

E04DJF/E04DJA

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
▸▿ 2 Specification
2.1 Specification for E04DJF
2.2 Specification for E04DJA
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

To supply optional parameters to E04DGF/E04DGA from an external file. More precisely, E04DJF must be used to supply optional parameters to E04DGF and E04DJA must be used to supply optional parameters to E04DGA.
E04DJA is a version of E04DJF that has additional arguments in order to make it safe for use in multithreaded applications (see Section 5). The initialization routine E04WBF must have been called before calling E04DJA.

2 Specification

2.1 Specification for E04DJF

SUBROUTINE E04DJF ( IOPTNS, INFORM)
INTEGER IOPTNS, INFORM

2.2 Specification for E04DJA

SUBROUTINE E04DJA ( IOPTNS, LWSAV, IWSAV, RWSAV, INFORM)
INTEGER | IOPTNS, IWSAV(610), INFORM
REAL (KIND=nag_wp) | RWSAV(475)
LOGICAL | LWSAV(120)

3 Description

E04DJF/E04DJA may be used to supply values for optional parameters to E04DGF/E04DGA. E04DJF/E04DJA reads an external file and each line of the file defines a single optional parameter. It is only necessary to supply values for those arguments whose values are to be different from their default values.
Each optional parameter is defined by a single character string, of up to 72 characters, consisting of one or more items. The items associated with a given option must be separated by spaces, or equals signs =. Alphabetic characters may be upper or lower case. The string
Print Level = 1
is an example of a string used to set an optional parameter. For each option the string contains one or more of the following items:
– | a mandatory keyword;
– | a phrase that qualifies the keyword;
– | a number that specifies an integer or real value. Such numbers may be up to 40 contiguous characters in Fortran's I, F, E or D formats, terminated by a space if this is not the last item on the line.
Blank strings and comments are ignored. A comment begins with an asterisk (*) and all subsequent characters in the string are regarded as part of the comment.
The file containing the options must start with Begin and must finish with End. An example of a valid options file is:
Begin * Example options file
   Print level = 5
End
For E04DJF each line of the file is normally printed as it is read, on the current advisory message unit (see X04ABF), but printing may be suppressed using the keyword Nolist. To suppress printing of Begin, Nolist must be the first option supplied as in the file:
Begin
   Nolist
   Print level = 5
End
Printing will automatically be turned on again after a call to E04DGF or E04DJF and may be turned on again at any time using the keyword List.
For E04DJA printing is turned off by default, but may be turned on at any time using the keyword List.
Optional parameter settings are preserved following a call to E04DGF/E04DGA and so the keyword Defaults is provided to allow you to reset all the optional parameters to their default values before a subsequent call to E04DGF/E04DGA.
A complete list of optional parameters, their abbreviations, synonyms and default values is given in Section 12 in E04DGF/E04DGA.

4 References

None.

5 Arguments

1:   IOPTNS – INTEGERInput
On entry: the unit number of the options file to be read.
Constraint: 0≤IOPTNS≤99.
2:   INFORM – INTEGEROutput
Note: for E04DJA, INFORM does not occur in this position in the argument list. See the additional arguments described below.
On exit: contains zero if the options file has been successfully read and a value>0 otherwise (see Section 6).
Note: the following are additional arguments for specific use with E04DJA. Users of E04DJF therefore need not read the remainder of this description.
2:   LWSAV 120 – LOGICAL arrayCommunication Array
3:   IWSAV 610 – INTEGER arrayCommunication Array
4:   RWSAV 475 – REAL (KIND=nag_wp) arrayCommunication Array
The arrays LWSAV, IWSAV and RWSAV must not be altered between calls to any of the routines E04DJA, E04DGA, E04DKA or E04WBF.
5:   INFORM – INTEGEROutput
Note: see the argument description for INFORM above.

6 Error Indicators and Warnings

INFORM=1
IOPTNS is not in the range 0,99.
INFORM=2
Begin was found, but end-of-file was found before End was found.
INFORM=3
end-of-file was found before Begin was found.
INFORM=4
Not used.
INFORM=5
One or more lines of the options file is invalid. Check that all keywords are neither ambiguous nor misspelt.

7 Accuracy

Not applicable.

8 Parallelism and Performance

E04DJF/E04DJA is not threaded in any implementation.

9 Further Comments

E04DKF/E04DKA may also be used to supply optional parameters to E04DGF/E04DGA.

10 Example

This example solves the same problem as the example for E04DGF/E04DGA, but in addition illustrates the use of E04DJF/E04DJA and E04DKF/E04DKA to set optional parameters for E04DGF/E04DGA.
In this example the options file read by E04DJF/E04DJA is appended to the data file for the program (see Section 10.2). It would usually be more convenient in practice to keep the data file and the options file separate.

10.1 Program Text

Note: the following programs illustrate the use of E04DJF and E04DJA.

Program Text (e04djfe.f90)

Program Text (e04djae.f90)

10.2 Program Data

Program Options (e04djfe.opt)

Program Options (e04djae.opt)

Program Data (e04djfe.d)

Program Data (e04djae.d)

10.3 Program Results

Program Results (e04djfe.r)

Program Results (e04djae.r)

E04 Chapter Contents
E04 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


E04DKF/E04DKA : NAG Library, Mark 26

E04 Chapter Contents
E04 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

E04DKF/E04DKA

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
▸▿ 2 Specification
2.1 Specification for E04DKF
2.2 Specification for E04DKA
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
10 Example

1 Purpose

To supply individual optional parameters to E04DGF/E04DGA. More precisely, E04DKF must be used to supply optional parameters to E04DGF and E04DKA must be used to supply optional parameters to E04DGA.
E04DKA is a version of E04DKF that has additional arguments in order to make it safe for use in multithreaded applications (see Section 5). The initialization routine E04WBF must have been called before calling E04DKA.

2 Specification

2.1 Specification for E04DKF

SUBROUTINE E04DKF ( STR)
CHARACTER(*) STR

2.2 Specification for E04DKA

SUBROUTINE E04DKA ( STR, LWSAV, IWSAV, RWSAV, INFORM)
INTEGER | IWSAV(610), INFORM
REAL (KIND=nag_wp) | RWSAV(475)
LOGICAL | LWSAV(120)
CHARACTER(*) | STR

3 Description

E04DKF/E04DKA may be used to supply values for optional parameters to E04DGF/E04DGA. It is only necessary to call E04DKF/E04DKA for those arguments whose values are to be different from their default values. One call to E04DKF/E04DKA sets one argument value.
Each optional parameter is defined by a single character string, of up to 72 characters, consisting of one or more items. The items associated with a given option must be separated by spaces, or equals signs =. Alphabetic characters may be upper or lower case. The string
Print Level = 1
is an example of a string used to set an optional parameter. For each option the string contains one or more of the following items:
– | a mandatory keyword;
– | a phrase that qualifies the keyword;
– | a number that specifies an integer or real value. Such numbers may be up to 40 contiguous characters in Fortran's I, F, E or D formats, terminated by a space if this is not the last item on the line.
Blank strings and comments are ignored. A comment begins with an asterisk (*) and all subsequent characters in the string are regarded as part of the comment.
For E04DKF, each user-specified option is normally printed as it is defined, on the current advisory message unit (see X04ABF), but this printing may be suppressed using the keyword Nolist. Thus the statement
 CALL E04DKF ('Nolist')
suppresses printing of this and subsequent options. Printing will automatically be turned on again after a call to E04DGF and may be turned on again at any time using the keyword List.
For E04DKA printing is turned off by default, but may be turned on at any time using the keyword List.
Optional parameter settings are preserved following a call to E04DGF/E04DGA and so the keyword Defaults is provided to allow you to reset all the optional parameters to their default values before a subsequent call to E04DGF/E04DGA.
A complete list of optional parameters, their abbreviations, synonyms and default values is given in Section 12 in E04DGF/E04DGA.

4 References

None.

5 Arguments

1:   STR – CHARACTER(*)Input
On entry: a single valid option string (as described in Section 3 and in Section 12 in E04DGF/E04DGA).
Note: the following are additional arguments for specific use with E04DKA. Users of E04DKF therefore need not read the remainder of this description.
2:   LWSAV 120 – LOGICAL arrayCommunication Array
3:   IWSAV 610 – INTEGER arrayCommunication Array
4:   RWSAV 475 – REAL (KIND=nag_wp) arrayCommunication Array
The arrays LWSAV, IWSAV and RWSAV must not be altered between calls to any of the routines E04DKA, E04DGA, E04DJA or E04WBF.
5:   INFORM – INTEGEROutput
On exit: contains zero if a valid option string has been supplied and a value>0 otherwise (see Section 6).

6 Error Indicators and Warnings

INFORM=5
The supplied option is invalid. Check that the keywords are neither ambiguous nor misspelt.

7 Accuracy

Not applicable.

8 Parallelism and Performance

E04DKF/E04DKA is not threaded in any implementation.

9 Further Comments

E04DJF/E04DJA may also be used to supply optional parameters to E04DGF/E04DGA.

10 Example

See Section 10 in E04DJF/E04DJA.
E04 Chapter Contents
E04 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


E04FCF : NAG Library, Mark 26

E04 Chapter Contents
E04 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

E04FCF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

E04FCF is a comprehensive algorithm for finding an unconstrained minimum of a sum of squares of m nonlinear functions in n variables m≥n. No derivatives are required.
The routine is intended for functions which have continuous first and second derivatives (although it will usually work even if the derivatives have occasional discontinuities).

2 Specification

SUBROUTINE E04FCF ( M, N, LSQFUN, LSQMON, IPRINT, MAXCAL, ETA, XTOL, STEPMX, X, FSUMSQ, FVEC, FJAC, LDFJAC, S, V, LDV, NITER, NF, IW, LIW, W, LW, IFAIL)
INTEGER | M, N, IPRINT, MAXCAL, LDFJAC, LDV, NITER, NF, IW(LIW), LIW, LW, IFAIL
REAL (KIND=nag_wp) | ETA, XTOL, STEPMX, X(N), FSUMSQ, FVEC(M), FJAC(LDFJAC,N), S(N), V(LDV,N), W(LW)
EXTERNAL | LSQFUN, LSQMON

3 Description

E04FCF is essentially identical to the subroutine LSQNDN in the NPL Algorithms Library. It is applicable to problems of the form
Minimize⁡F x=∑i=1 m fi x 2
where x = x 1,x 2,…,xn T and m≥n. (The functions fi x are often referred to as ‘residuals’.)
You must supply LSQFUN to calculate the values of the fi x at any point x.
From a starting point x 1 supplied by you, the routine generates a sequence of points x 2 ,x 3 ,…, which is intended to converge to a local minimum of F x. The sequence of points is given by
x k+1 =x k +α kp k
where the vector p k is a direction of search, and α k is chosen such that F x k +α k p k is approximately a minimum with respect to α k .
The vector p k used depends upon the reduction in the sum of squares obtained during the last iteration. If the sum of squares was sufficiently reduced, then p k is an approximation to the Gauss–Newton direction; otherwise additional function evaluations are made so as to enable p k to be a more accurate approximation to the Newton direction.
The method is designed to ensure that steady progress is made whatever the starting point, and to have the rapid ultimate convergence of Newton's method.

4 References

Gill P E and Murray W (1978) Algorithms for the solution of the nonlinear least squares problem SIAM J. Numer. Anal. 15 977–992

5 Arguments

1:   M – INTEGERInput
2:   N – INTEGERInput
On entry: the number m of residuals, fi x, and the number n of variables, xj.
Constraint: 1≤N≤M.
3:   LSQFUN – SUBROUTINE, supplied by the user.External Procedure
LSQFUN must calculate the vector of values fi x at any point x. (However, if you do not wish to calculate the residuals at a particular x, there is the option of setting an argument to cause E04FCF to terminate immediately.)
The specification of LSQFUN is:
SUBROUTINE LSQFUN ( IFLAG, M, N, XC, FVEC, IW, LIW, W, LW)
INTEGER | IFLAG, M, N, IW(LIW), LIW, LW
REAL (KIND=nag_wp) | XC(N), FVEC(M), W(LW)
1:   IFLAG – INTEGERInput/Output
On entry: has a non-negative value.
On exit: if LSQFUN resets IFLAG to some negative number, E04FCF will terminate immediately, with IFAIL set to your setting of IFLAG.
2:   M – INTEGERInput
On entry: m, the numbers of residuals.
3:   N – INTEGERInput
On entry: n, the numbers of variables.
4:   XC N – REAL (KIND=nag_wp) arrayInput
On entry: the point x at which the values of the fi are required.
5:   FVEC M – REAL (KIND=nag_wp) arrayOutput
On exit: unless IFLAG is reset to a negative number, FVEC i must contain the value of fi at the point x, for i=1,2,…,m.
6:   IW LIW – INTEGER arrayWorkspace
7:   LIW – INTEGERInput
8:   W LW – REAL (KIND=nag_wp) arrayWorkspace
9:   LW – INTEGERInput
LSQFUN is called with these arguments as in the call to E04FCF, so you can pass quantities to LSQFUN from the subroutine which calls E04FCF by using partitions of IW and W beyond those used as workspace by E04FCF. However, because of the danger of mistakes in partitioning, it is recommended that this facility be used very selectively, e.g., for stable applications packages which need to pass their own variable dimension workspace to LSQFUN. It is recommended that the normal method for passing information from your subroutine to LSQFUN should be via COMMON global variables. In any case, you must not change LIW, LW or the elements of IW and W used as workspace by E04FCF.
LSQFUN must either be a module subprogram USEd by, or declared as EXTERNAL in, the (sub)program from which E04FCF is called. Arguments denoted as Input must not be changed by this procedure.
Note: LSQFUN should be tested separately before being used in conjunction with E04FCF.
4:   LSQMON – SUBROUTINE, supplied by the NAG Library or the user.External Procedure
If IPRINT≥0, you must supply LSQMON which is suitable for monitoring the minimization process. LSQMON must not change the values of any of its arguments.
If IPRINT<0, the dummy routine E04FDZ can be used as LSQMON.
The specification of LSQMON is:
SUBROUTINE LSQMON ( M, N, XC, FVEC, FJAC, LDFJAC, S, IGRADE, NITER, NF, IW, LIW, W, LW)
INTEGER | M, N, LDFJAC, IGRADE, NITER, NF, IW(LIW), LIW, LW
REAL (KIND=nag_wp) | XC(N), FVEC(M), FJAC(LDFJAC,N), S(N), W(LW)
Important: the dimension declaration for FJAC must contain the variable LDFJAC, not an integer constant.
1:   M – INTEGERInput
On entry: m, the numbers of residuals.
2:   N – INTEGERInput
On entry: n, the numbers of variables.
3:   XC N – REAL (KIND=nag_wp) arrayInput
On entry: the coordinates of the current point x.
4:   FVEC M – REAL (KIND=nag_wp) arrayInput
On entry: the values of the residuals fi at the current point x.
5:   FJAC LDFJACN – REAL (KIND=nag_wp) arrayInput
On entry: FJAC ij contains the value of ∂fi ∂xj at the current point x, for i=1,2,…,m and j=1,2,…,n.
6:   LDFJAC – INTEGERInput
On entry: the first dimension of the array FJAC as declared in the (sub)program from which E04FCF is called.
7:   S N – REAL (KIND=nag_wp) arrayInput
On entry: the singular values of the current approximation to the Jacobian matrix. Thus S may be useful as information about the structure of your problem.
8:   IGRADE – INTEGERInput
On entry: E04FCF estimates the dimension of the subspace for which the Jacobian matrix can be used as a valid approximation to the curvature (see Gill and Murray (1978)). This estimate is called the grade of the Jacobian matrix, and IGRADE gives its current value.
9:   NITER – INTEGERInput
On entry: the number of iterations which have been performed in E04FCF.
10:   NF – INTEGERInput
On entry: the number of times that LSQFUN has been called so far. (However, for intermediate calls of LSQMON, NF is calculated on the assumption that the latest linear search has been successful. If this is not the case, then the n evaluations allowed for approximating the Jacobian at the new point will not in fact have been made. NF will be accurate at the final call of LSQMON.)
11:   IW LIW – INTEGER arrayWorkspace
12:   LIW – INTEGERInput
13:   W LW – REAL (KIND=nag_wp) arrayWorkspace
14:   LW – INTEGERInput
These arguments correspond to the arguments IW, LIW, W and LW of E04FCF. They are included in LSQMON's argument list primarily for when E04FCF is called by other Library routines.
LSQMON must either be a module subprogram USEd by, or declared as EXTERNAL in, the (sub)program from which E04FCF is called. Arguments denoted as Input must not be changed by this procedure.
Note: you should normally print the sum of squares of residuals, so as to be able to examine the sequence of values of F x mentioned in Section 7. It is usually helpful to print XC, the estimated gradient of the sum of squares, NITER and NF.
5:   IPRINT – INTEGERInput
On entry: the frequency with which LSQMON is to be called.
If IPRINT>0, LSQMON is called once every IPRINT iterations and just before exit from E04FCF.
If IPRINT=0, LSQMON is just called at the final point.
If IPRINT<0, LSQMON is not called at all.
IPRINT should normally be set to a small positive number.
Suggested value: IPRINT=1.
6:   MAXCAL – INTEGERInput
On entry: the limit you set on the number of times that LSQFUN may be called by E04FCF. There will be an error exit (see Section 6) after MAXCAL calls of LSQFUN.
Suggested value: MAXCAL=400×n.
Constraint: MAXCAL≥1.
7:   ETA – REAL (KIND=nag_wp)Input
Every iteration of E04FCF involves a linear minimization, i.e., minimization of F x k +α k p k with respect to α k .
On entry: specifies how accurately the linear minimizations are to be performed. The minimum with respect to α k will be located more accurately for small values of ETA (say, 0.01) than for large values (say, 0.9). Although accurate linear minimizations will generally reduce the number of iterations performed by E04FCF, they will increase the number of calls of LSQFUN made each iteration. On balance it is usually more efficient to perform a low accuracy minimization.
Suggested value: ETA=0.5 (ETA=0.0 if N=1).
Constraint: 0.0≤ETA<1.0.
8:   XTOL – REAL (KIND=nag_wp)Input
On entry: the accuracy in x to which the solution is required.
If xtrue is the true value of x at the minimum, then xsol, the estimated position before a normal exit, is such that
xsol-xtrue<XTOL×1.0+xtrue,
where y=∑j=1 n yj 2. For example, if the elements of xsol are not much larger than 1.0 in modulus and if XTOL=1.0E−5, then xsol is usually accurate to about five decimal places. (For further details see Section 7.)
Suggested value: if F x and the variables are scaled roughly as described in Section 9 and ε is the machine precision, then a setting of order XTOL=ε will usually be appropriate. If XTOL is set to 0.0 or some positive value less than 10 ε, E04FCF will use 10 ε instead of XTOL, since 10 ε is probably the smallest reasonable setting.
Constraint: XTOL≥0.0.
9:   STEPMX – REAL (KIND=nag_wp)Input
On entry: an estimate of the Euclidean distance between the solution and the starting point supplied by you. (For maximum efficiency, a slight overestimate is preferable.) E04FCF will ensure that, for each iteration,
∑j=1 n xj k -xj k-1 2≤ STEPMX 2,
where k is the iteration number. Thus, if the problem has more than one solution, E04FCF is most likely to find the one nearest to the starting point. On difficult problems, a realistic choice can prevent the sequence x k entering a region where the problem is ill-behaved and can help avoid overflow in the evaluation of F x. However, an underestimate of STEPMX can lead to inefficiency.
Suggested value: STEPMX=100000.0.
Constraint: STEPMX≥XTOL.
10:   X N – REAL (KIND=nag_wp) arrayInput/Output
On entry: X j must be set to a guess at the jth component of the position of the minimum, for j=1,2,…,n.
On exit: the final point x k . Thus, if IFAIL=0 on exit, X j is the jth component of the estimated position of the minimum.
11:   FSUMSQ – REAL (KIND=nag_wp)Output
On exit: the value of F x, the sum of squares of the residuals fi x, at the final point given in X.
12:   FVEC M – REAL (KIND=nag_wp) arrayOutput
On exit: the value of the residual fi x at the final point given in X, for i=1,2,…,m.
13:   FJAC LDFJACN – REAL (KIND=nag_wp) arrayOutput
On exit: the estimate of the first derivative ∂fi ∂xj at the final point given in X, for i=1,2,…,m and j=1,2,…,n.
14:   LDFJAC – INTEGERInput
On entry: the first dimension of the array FJAC as declared in the (sub)program from which E04FCF is called.
Constraint: LDFJAC≥M.
15:   S N – REAL (KIND=nag_wp) arrayOutput
On exit: the singular values of the estimated Jacobian matrix at the final point. Thus S may be useful as information about the structure of your problem.
16:   V LDVN – REAL (KIND=nag_wp) arrayOutput
On exit: the matrix V associated with the singular value decomposition
J=US VT
of the estimated Jacobian matrix at the final point, stored by columns. This matrix may be useful for statistical purposes, since it is the matrix of orthonormalized eigenvectors of JT J.
17:   LDV – INTEGERInput
On entry: the first dimension of the array V as declared in the (sub)program from which E04FCF is called.
Constraint: LDV≥N.
18:   NITER – INTEGEROutput
On exit: the number of iterations which have been performed in E04FCF.
19:   NF – INTEGEROutput
On exit: the number of times that the residuals have been evaluated (i.e., number of calls of LSQFUN).
20:   IW LIW – INTEGER arrayCommunication Array
21:   LIW – INTEGERInput
On entry: the dimension of the array IW as declared in the (sub)program from which E04FCF is called.
Constraint: LIW≥1.
22:   W LW – REAL (KIND=nag_wp) arrayCommunication Array
23:   LW – INTEGERInput
On entry: the dimension of the array W as declared in the (sub)program from which E04FCF is called.
Constraints:
  • if N>1, LW≥6×N+M×N+2×M+N×N-1/2;
  • if N=1, LW≥7+3×M.
24:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, because for this routine the values of the output arguments may be useful even if IFAIL≠0 on exit, the recommended value is -1. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Note: E04FCF may return useful information for one or more of the following detected errors or warnings.
Errors or warnings detected by the routine:
IFAIL<0
A negative value of IFAIL indicates an exit from E04FCF because you have set IFLAG negative in LSQFUN. The value of IFAIL will be the same as your setting of IFLAG.
IFAIL=1
On entry, | N<1,
or | M<N,
or | MAXCAL<1,
or | ETA<0.0,
or | ETA≥1.0,
or | XTOL<0.0,
or | STEPMX<XTOL,
or | LDFJAC<M,
or | LDV<N,
or | LIW<1,
or | LW<6×N+M×N+2×M+N×N-1/2, when N>1,
or | LW<7+3×M, when N=1.
When this exit occurs, no values will have been assigned to FSUMSQ, or to the elements of FVEC, FJAC, S or V.
IFAIL=2
There have been MAXCAL calls of LSQFUN. If steady reductions in the sum of squares, F x, were monitored up to the point where this exit occurred, then the exit probably occurred simply because MAXCAL was set too small, so the calculations should be restarted from the final point held in X. This exit may also indicate that F x has no minimum.
IFAIL=3
The conditions for a minimum have not all been satisfied, but a lower point could not be found. This could be because XTOL has been set so small that rounding errors in the evaluation of the residuals make attainment of the convergence conditions impossible.
IFAIL=4
The method for computing the singular value decomposition of the estimated Jacobian matrix has failed to converge in a reasonable number of sub-iterations. It may be worth applying E04FCF again starting with an initial approximation which is not too close to the point at which the failure occurred.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.
The values IFAIL=2, 3 or 4 may also be caused by mistakes in LSQFUN, by the formulation of the problem or by an awkward function. If there are no such mistakes it is worth restarting the calculations from a different starting point (not the point at which the failure occurred) in order to avoid the region which caused the failure.

7 Accuracy

A successful exit (IFAIL=0) is made from E04FCF when (B1, B2 and B3) or B4 or B5 hold, where
B1 ≡ α k ×p k <XTOL+ε×1.0+x k B2 ≡ F k -F k-1 < XTOL+ε 2×1.0+F k B3 ≡ g k <ε 1/3+XTOL×1.0+F k B4 ≡ F k <ε 2 B5 ≡ g k <ε×F k 1/2
and where . and ε are as defined in Section 5, and F k and g k are the values of F x and its vector of estimated first derivatives at x k . If IFAIL=0 then the vector in X on exit, xsol, is almost certainly an estimate of xtrue, the position of the minimum to the accuracy specified by XTOL.
If IFAIL=3, then xsol may still be a good estimate of xtrue, but to verify this you should make the following checks. If
(a) | the sequence F x k converges to F xsol at a superlinear or a fast linear rate, and
(b) | g xsol T g xsol < 10 ε , where T denotes transpose, then it is almost certain that xsol is a close approximation to the minimum. When (b) is true, then usually F xsol is a close approximation to F xtrue. The values of F x k can be calculated in LSQMON, and the vector g xsol can be calculated from the contents of FVEC and FJAC on exit from E04FCF.
Further suggestions about confirmation of a computed solution are given in the E04 Chapter Introduction.

8 Parallelism and Performance

E04FCF is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
E04FCF makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The number of iterations required depends on the number of variables, the number of residuals, the behaviour of F x, the accuracy demanded and the distance of the starting point from the solution. The number of multiplications performed per iteration of E04FCF varies, but for m≫n is approximately n×m 2+O n 3. In addition, each iteration makes at least n+1 calls of LSQFUN. So, unless the residuals can be evaluated very quickly, the run time will be dominated by the time spent in LSQFUN.
Ideally, the problem should be scaled so that, at the solution, F x and the corresponding values of the xj are each in the range -1,+1, and so that at points one unit away from the solution, F x differs from its value at the solution by approximately one unit. This will usually imply that the Hessian matrix of F x at the solution is well-conditioned. It is unlikely that you will be able to follow these recommendations very closely, but it is worth trying (by guesswork), as sensible scaling will reduce the difficulty of the minimization problem, so that E04FCF will take less computer time.
When the sum of squares represents the goodness-of-fit of a nonlinear model to observed data, elements of the variance-covariance matrix of the estimated regression coefficients can be computed by a subsequent call to E04YCF, using information returned in the arrays S and V. See E04YCF for further details.

10 Example

This example finds least squares estimates of x 1,x 2 and x 3 in the model
y=x 1+t 1 x 2t 2+x 3t 3
using the 15 sets of data given in the following table.
y t 1 t 2 t 3 0.14 1.0 15.0 1.0 0.18 2.0 14.0 2.0 0.22 3.0 13.0 3.0 0.25 4.0 12.0 4.0 0.29 5.0 11.0 5.0 0.32 6.0 10.0 6.0 0.35 7.0 9.0 7.0 0.39 8.0 8.0 8.0 0.37 9.0 7.0 7.0 0.58 10.0 6.0 6.0 0.73 11.0 5.0 5.0 0.96 12.0 4.0 4.0 1.34 13.0 3.0 3.0 2.10 14.0 2.0 2.0 4.39 15.0 1.0 1.0
The program uses 0.5,1.0,1.5 as the initial guess at the position of the minimum.

10.1 Program Text

Program Text (e04fcfe.f90)

10.2 Program Data

Program Data (e04fcfe.d)

10.3 Program Results

Program Results (e04fcfe.r)

E04 Chapter Contents
E04 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


E04FYF : NAG Library, Mark 26

E04 Chapter Contents
E04 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

E04FYF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

E04FYF is an easy-to-use algorithm for finding an unconstrained minimum of a sum of squares of m nonlinear functions in n variables m≥n. No derivatives are required.
It is intended for functions which are continuous and which have continuous first and second derivatives (although it will usually work even if the derivatives have occasional discontinuities).

2 Specification

SUBROUTINE E04FYF ( M, N, LSFUN1, X, FSUMSQ, W, LW, IUSER, RUSER, IFAIL)
INTEGER | M, N, LW, IUSER(*), IFAIL
REAL (KIND=nag_wp) | X(N), FSUMSQ, W(LW), RUSER(*)
EXTERNAL | LSFUN1

3 Description

E04FYF is essentially identical to the subroutine LSNDN1 in the NPL Algorithms Library. It is applicable to problems of the form
MinimizeF x=∑i=1 m fi x 2
where x = x 1,x 2,…,xn T and m≥n. (The functions fi x are often referred to as ‘residuals’.)
You must supply a subroutine to evaluate functions fi x at any point x.
From a starting point supplied by you, a sequence of points is generated which is intended to converge to a local minimum of the sum of squares. These points are generated using estimates of the curvature of F x.

4 References

Gill P E and Murray W (1978) Algorithms for the solution of the nonlinear least squares problem SIAM J. Numer. Anal. 15 977–992

5 Arguments

1:   M – INTEGERInput
2:   N – INTEGERInput
On entry: the number m of residuals, fi x, and the number n of variables, xj.
Constraint: 1≤N≤M.
3:   LSFUN1 – SUBROUTINE, supplied by the user.External Procedure
You must supply this routine to calculate the vector of values fi x at any point x. It should be tested separately before being used in conjunction with E04FYF (see the E04 Chapter Introduction).
The specification of LSFUN1 is:
SUBROUTINE LSFUN1 ( M, N, XC, FVEC, IUSER, RUSER)
INTEGER | M, N, IUSER(*)
REAL (KIND=nag_wp) | XC(N), FVEC(M), RUSER(*)
1:   M – INTEGERInput
On entry: m, the numbers of residuals.
2:   N – INTEGERInput
On entry: n, the numbers of variables.
3:   XC N – REAL (KIND=nag_wp) arrayInput
On entry: the point x at which the values of the fi are required.
4:   FVEC M – REAL (KIND=nag_wp) arrayOutput
On exit: FVEC i must contain the value of fi at the point x, for i=1,2,…,m.
5:   IUSER* – INTEGER arrayUser Workspace
6:   RUSER* – REAL (KIND=nag_wp) arrayUser Workspace
LSFUN1 is called with the arguments IUSER and RUSER as supplied to E04FYF. You are free to use the arrays IUSER and RUSER to supply information to LSFUN1 as an alternative to using COMMON global variables.
LSFUN1 must either be a module subprogram USEd by, or declared as EXTERNAL in, the (sub)program from which E04FYF is called. Arguments denoted as Input must not be changed by this procedure.
4:   X N – REAL (KIND=nag_wp) arrayInput/Output
On entry: X j must be set to a guess at the jth component of the position of the minimum, for j=1,2,…,n.
On exit: the lowest point found during the calculations. Thus, if IFAIL=0 on exit, X j is the jth component of the position of the minimum.
5:   FSUMSQ – REAL (KIND=nag_wp)Output
On exit: the value of the sum of squares, F x, corresponding to the final point stored in X.
6:   W LW – REAL (KIND=nag_wp) arrayWorkspace
7:   LW – INTEGERInput
On entry: the dimension of the array W as declared in the (sub)program from which E04FYF is called.
Constraints:
  • if N>1, LW≥7×N+N×N+2×M×N+3×M+N×N-1/2;
  • if N=1, LW≥9+5×M.
8:   IUSER* – INTEGER arrayUser Workspace
9:   RUSER* – REAL (KIND=nag_wp) arrayUser Workspace
IUSER and RUSER are not used by E04FYF, but are passed directly to LSFUN1 and may be used to pass information to this routine as an alternative to using COMMON global variables.
10:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, because for this routine the values of the output arguments may be useful even if IFAIL≠0 on exit, the recommended value is -1. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Note: E04FYF may return useful information for one or more of the following detected errors or warnings.
Errors or warnings detected by the routine:
IFAIL=1
On entry, | N<1,
or | M<N,
or | LW<7×N+N×N+2×M×N+3×M+N×N-1/2, when N>1,
or | LW<9+5×M, when N=1.
IFAIL=2
There have been 400×n calls of LSFUN1, yet the algorithm does not seem to have converged. This may be due to an awkward function or to a poor starting point, so it is worth restarting E04FYF from the final point held in X.
IFAIL=3
The final point does not satisfy the conditions for acceptance as a minimum, but no lower point could be found.
IFAIL=4
An auxiliary routine has been unable to complete a singular value decomposition in a reasonable number of sub-iterations.
IFAIL=5
IFAIL=6
IFAIL=7
IFAIL=8
There is some doubt about whether the point X x found by E04FYF is a minimum of F x. The degree of confidence in the result decreases as IFAIL increases. Thus, when IFAIL=5, it is probable that the final x gives a good estimate of the position of a minimum, but when IFAIL=8 it is very unlikely that the routine has found a minimum.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.
If you are not satisfied with the result (e.g., because IFAIL lies between 3 and 8), it is worth restarting the calculations from a different starting point (not the point at which the failure occurred) in order to avoid the region which caused the failure. Repeated failure may indicate some defect in the formulation of the problem.

7 Accuracy

If the problem is reasonably well scaled and a successful exit is made, then, for a computer with a mantissa of t decimals, one would expect to get about t/2-1 decimals accuracy in the components of x and between t-1 (if F x is of order 1 at the minimum) and 2 t-2 (if F x is close to zero at the minimum) decimals accuracy in F x.

8 Parallelism and Performance

E04FYF is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
E04FYF makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The number of iterations required depends on the number of variables, the number of residuals and their behaviour, and the distance of the starting point from the solution. The number of multiplications performed per iteration of E04FYF varies, but for m≫n is approximately n×m 2+O n 3. In addition, each iteration makes at least n+1 calls of LSFUN1. So, unless the residuals can be evaluated very quickly, the run time will be dominated by the time spent in LSFUN1.
Ideally, the problem should be scaled so that the minimum value of the sum of squares is in the range 0,+1, and so that at points a unit distance away from the solution the sum of squares is approximately a unit value greater than at the minimum. It is unlikely that you will be able to follow these recommendations very closely, but it is worth trying (by guesswork), as sensible scaling will reduce the difficulty of the minimization problem, so that E04FYF will take less computer time.
When the sum of squares represents the goodness-of-fit of a nonlinear model to observed data, elements of the variance-covariance matrix of the estimated regression coefficients can be computed by a subsequent call to E04YCF, using information returned in segments of the workspace array W. See E04YCF for further details.

10 Example

This example finds least squares estimates of x 1, x 2 and x 3 in the model
y=x 1+t 1 x 2t 2+x 3t 3
using the 15 sets of data given in the following table.
y 0 t 1 0 t 2 0 t 3 0 0.14 1.0 15.0 1.0 0.18 2.0 14.0 2.0 0.22 3.0 13.0 3.0 0.25 4.0 12.0 4.0 0.29 5.0 11.0 5.0 0.32 6.0 10.0 6.0 0.35 7.0 9.0 7.0 0.39 8.0 8.0 8.0 0.37 9.0 7.0 7.0 0.58 10.0 6.0 6.0 0.73 11.0 5.0 5.0 0.96 12.0 4.0 4.0 1.34 13.0 3.0 3.0 2.10 14.0 2.0 2.0 4.39 15.0 1.0 1.0
The program uses 0.5,1.0,1.5 as the initial guess at the position of the minimum.

10.1 Program Text

Program Text (e04fyfe.f90)

10.2 Program Data

Program Data (e04fyfe.d)

10.3 Program Results

Program Results (e04fyfe.r)

E04 Chapter Contents
E04 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


E04GBF : NAG Library, Mark 26

E04 Chapter Contents
E04 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

E04GBF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

E04GBF is a comprehensive quasi-Newton algorithm for finding an unconstrained minimum of a sum of squares of m nonlinear functions in n variables m≥n. First derivatives are required.
The routine is intended for functions which have continuous first and second derivatives (although it will usually work even if the derivatives have occasional discontinuities).

2 Specification

SUBROUTINE E04GBF ( M, N, LSQLIN, LSQFUN, LSQMON, IPRINT, MAXCAL, ETA, XTOL, STEPMX, X, FSUMSQ, FVEC, FJAC, LDFJAC, S, V, LDV, NITER, NF, IW, LIW, W, LW, IFAIL)
INTEGER | M, N, IPRINT, MAXCAL, LDFJAC, LDV, NITER, NF, IW(LIW), LIW, LW, IFAIL
REAL (KIND=nag_wp) | ETA, XTOL, STEPMX, X(N), FSUMSQ, FVEC(M), FJAC(LDFJAC,N), S(N), V(LDV,N), W(LW)
EXTERNAL | LSQLIN, LSQFUN, LSQMON

3 Description

E04GBF is essentially identical to the subroutine LSQFDQ in the NPL Algorithms Library. It is applicable to problems of the form:
Minimize⁡F x=∑i=1 m fi x 2
where x = x 1,x 2,…,xn T and m≥n. (The functions fi x are often referred to as ‘residuals’.)
You must supply a subroutine to calculate the values of the fi x and their first derivatives ∂fi ∂xj at any point x.
From a starting point x 1 supplied by you, the routine generates a sequence of points x 2 ,x 3 ,…, which is intended to converge to a local minimum of F x. The sequence of points is given by
x k+1 =x k +α kp k
where the vector p k is a direction of search, and α k is chosen such that F x k +α kp k is approximately a minimum with respect to α k.
The vector p k used depends upon the reduction in the sum of squares obtained during the last iteration. If the sum of squares was sufficiently reduced, then p k is the Gauss–Newton direction; otherwise the second derivatives of the fi x are taken into account using a quasi-Newton updating scheme.
The method is designed to ensure that steady progress is made whatever the starting point, and to have the rapid ultimate convergence of Newton's method.

4 References

Gill P E and Murray W (1978) Algorithms for the solution of the nonlinear least squares problem SIAM J. Numer. Anal. 15 977–992

5 Arguments

1:   M – INTEGERInput
2:   N – INTEGERInput
On entry: the number m of residuals, fi x, and the number n of variables, xj.
Constraint: 1≤N≤M.
3:   LSQLIN – SUBROUTINE, supplied by the NAG Library.External Procedure
LSQLIN enables you to specify whether the linear minimizations (i.e., minimizations of F x k +α k p k with respect to α k) are to be performed by a routine which just requires the evaluation of the fi x (E04FCV), or by a routine which also requires the first derivatives of the fi x (E04HEV).
It will often be possible to evaluate the first derivatives of the residuals in about the same amount of computer time that is required for the evaluation of the residuals themselves – if this is so then E04GBF should be called with routine E04HEV as the argument LSQLIN. However, if the evaluation of the derivatives takes more than about 4 times as long as the evaluation of the residuals, then E04FCV will usually be preferable. If in doubt, use E04HEV as it is slightly more robust.
Whichever subroutine is used, must be declared as EXTERNAL in the subroutine from which E04GBF is called.
4:   LSQFUN – SUBROUTINE, supplied by the user.External Procedure
LSQFUN must calculate the vector of values fi x and Jacobian matrix of first derivatives ∂fi ∂xj at any point x. (However, if you do not wish to calculate the residuals or first derivatives at a particular x, there is the option of setting an argument to cause E04GBF to terminate immediately.)
The specification of LSQFUN is:
SUBROUTINE LSQFUN ( IFLAG, M, N, XC, FVEC, FJAC, LDFJAC, IW, LIW, W, LW)
INTEGER | IFLAG, M, N, LDFJAC, IW(LIW), LIW, LW
REAL (KIND=nag_wp) | XC(N), FVEC(M), FJAC(LDFJAC,N), W(LW)
Important: the dimension declaration for FJAC must contain the variable LDFJAC, not an integer constant.
1:   IFLAG – INTEGERInput/Output
On entry: will be set to 0, 1 or 2.
IFLAG=0
Indicates that only the residuals need to be evaluated
IFLAG=1
Indicates that only the Jacobian matrix needs to be evaluated
IFLAG=2
Indicates that both the residuals and the Jacobian matrix must be calculated.
If E04HEV is used as E04GBF's LSQLIN, LSQFUN will always be called with IFLAG set to 2.
On exit: if it is not possible to evaluate the fi x or their first derivatives at the point given in XC (or if it is wished to stop the calculations for any other reason), you should reset IFLAG to some negative number and return control to E04GBF. E04GBF will then terminate immediately, with IFAIL set to your setting of IFLAG.
2:   M – INTEGERInput
On entry: m, the number of residuals.
3:   N – INTEGERInput
On entry: n, the number of variables.
4:   XC N – REAL (KIND=nag_wp) arrayInput
On entry: the point x at which the values of the fi and the ∂fi ∂xj are required.
5:   FVEC M – REAL (KIND=nag_wp) arrayOutput
On exit: unless IFLAG=1 on entry, or IFLAG is reset to a negative number, then FVEC i must contain the value of fi at the point x, for i=1,2,…,m.
6:   FJAC LDFJACN – REAL (KIND=nag_wp) arrayOutput
On exit: unless IFLAG=0 on entry, or IFLAG is reset to a negative number, then FJAC ij must contain the value of ∂fi ∂xj at the point x, for i=1,2,…,m and j=1,2,…,n.
7:   LDFJAC – INTEGERInput
On entry: the first dimension of the array FJAC, set to m by E04GBF.
8:   IW LIW – INTEGER arrayWorkspace
9:   LIW – INTEGERInput
10:   W LW – REAL (KIND=nag_wp) arrayWorkspace
11:   LW – INTEGERInput
LSQFUN is called with E04GBF's arguments IW, LIW, W, LW as these arguments. They are present so that, when other library routines require the solution of a minimization subproblem, constants needed for the evaluation of residuals can be passed through IW and W. Similarly, you could pass quantities to LSQFUN from the segment which calls E04GBF by using partitions of IW and W beyond those used as workspace by E04GBF. However, because of the danger of mistakes in partitioning, it is recommended that you should pass information to LSQFUN via COMMON global variables and not use IW or W at all. In any case you must not change the elements of IW and W used as workspace by E04GBF.
LSQFUN must either be a module subprogram USEd by, or declared as EXTERNAL in, the (sub)program from which E04GBF is called. Arguments denoted as Input must not be changed by this procedure.
Note: LSQFUN should be tested separately before being used in conjunction with E04GBF.
5:   LSQMON – SUBROUTINE, supplied by the NAG Library or the user.External Procedure
If IPRINT≥0, you must supply LSQMON which is suitable for monitoring the minimization process. LSQMON must not change the values of any of its arguments.
If IPRINT<0, the NAG Library dummy routine E04FDZ can be used as LSQMON.
The specification of LSQMON is:
SUBROUTINE LSQMON ( M, N, XC, FVEC, FJAC, LDFJAC, S, IGRADE, NITER, NF, IW, LIW, W, LW)
INTEGER | M, N, LDFJAC, IGRADE, NITER, NF, IW(LIW), LIW, LW
REAL (KIND=nag_wp) | XC(N), FVEC(M), FJAC(LDFJAC,N), S(N), W(LW)
Important: the dimension declaration for FJAC must contain the variable LDFJAC, not an integer constant.
1:   M – INTEGERInput
On entry: m, the numbers of residuals.
2:   N – INTEGERInput
On entry: n, the numbers of variables.
3:   XC N – REAL (KIND=nag_wp) arrayInput
On entry: the coordinates of the current point x.
4:   FVEC M – REAL (KIND=nag_wp) arrayInput
On entry: the values of the residuals fi at the current point x.
5:   FJAC LDFJACN – REAL (KIND=nag_wp) arrayInput
On entry: FJAC ij contains the value of ∂fi ∂xj at the current point x, for i=1,2,…,m and j=1,2,…,n.
6:   LDFJAC – INTEGERInput
On entry: the first dimension of the array FJAC as declared in the (sub)program from which E04GBF is called.
7:   S N – REAL (KIND=nag_wp) arrayInput
On entry: the singular values of the current Jacobian matrix. Thus S may be useful as information about the structure of your problem.
8:   IGRADE – INTEGERInput
On entry: E04GBF estimates the dimension of the subspace for which the Jacobian matrix can be used as a valid approximation to the curvature (see Gill and Murray (1978)). This estimate is called the grade of the Jacobian matrix, and IGRADE gives its current value.
9:   NITER – INTEGERInput
On entry: the number of iterations which have been performed in E04GBF.
10:   NF – INTEGERInput
On entry: the number of evaluations of the residuals. (If E04HEV is used as LSQLIN, NF is also the number of evaluations of the Jacobian matrix.)
11:   IW LIW – INTEGER arrayWorkspace
12:   LIW – INTEGERInput
13:   W LW – REAL (KIND=nag_wp) arrayWorkspace
14:   LW – INTEGERInput
As in LSQFUN, these arguments correspond to the arguments IW, LIW, W, LW of E04GBF. They are included in LSQMON's argument list primarily for when E04GBF is called by other library routines.
LSQMON must either be a module subprogram USEd by, or declared as EXTERNAL in, the (sub)program from which E04GBF is called. Arguments denoted as Input must not be changed by this procedure.
Note: you should normally print the sum of squares of residuals, so as to be able to examine the sequence of values of F x mentioned in Section 7. It is usually helpful to also print XC, the gradient of the sum of squares, NITER and NF.
6:   IPRINT – INTEGERInput
On entry: the frequency with which LSQMON is to be called.
IPRINT>0
LSQMON is called once every IPRINT iterations and just before exit from E04GBF.
IPRINT=0
LSQMON is just called at the final point.
IPRINT<0
LSQMON is not called at all.
IPRINT should normally be set to a small positive number.
Suggested value: IPRINT=1.
7:   MAXCAL – INTEGERInput
On entry: enables you to limit the number of times that LSQFUN is called by E04GBF. There will be an error exit (see Section 6) after MAXCAL calls of LSQFUN.
Suggested values:
  • MAXCAL=75×n if E04FCV is used as LSQLIN,
  • MAXCAL=50×n if E04HEV is used as LSQLIN.
Constraint: MAXCAL≥1.
8:   ETA – REAL (KIND=nag_wp)Input
On entry: every iteration of E04GBF involves a linear minimization (i.e., minimization of F x k +α k p k with respect to α k ). ETA specifies how accurately these linear minimizations are to be performed. The minimum with respect to α k will be located more accurately for small values of ETA (say, 0.01) than for large values (say, 0.9).
Although accurate linear minimizations will generally reduce the number of iterations performed by E04GBF, they will increase the number of calls of LSQFUN made every iteration. On balance it is usually more efficient to perform a low accuracy minimization.
Suggested values:
  • ETA=0.9 if N>1 and E04HEV is used as LSQLIN,
  • ETA=0.5 if N>1 and E04FCV is uses as LSQLIN,
  • ETA=0.0 if N=1.
Constraint: 0.0≤ETA<1.0.
9:   XTOL – REAL (KIND=nag_wp)Input
On entry: the accuracy in x to which the solution is required.
If xtrue is the true value of x at the minimum, then xsol, the estimated position before a normal exit, is such that
xsol-xtrue<XTOL×1.0+xtrue,
where y=∑j=1 n yj 2. For example, if the elements of xsol are not much larger than 1.0 in modulus and if XTOL=1.0E−5, then xsol is usually accurate to about five decimal places. (For further details see Section 7.)
If F x and the variables are scaled roughly as described in Section 9 and ε is the machine precision, then a setting of order XTOL=ε will usually be appropriate. If XTOL is set to 0.0 or some positive value less than 10 ε, E04GBF will use 10 ε instead of XTOL, since 10 ε is probably the smallest reasonable setting.
Constraint: XTOL≥0.0.
10:   STEPMX – REAL (KIND=nag_wp)Input
On entry: an estimate of the Euclidean distance between the solution and the starting point supplied by you. (For maximum efficiency, a slight overestimate is preferable.)
E04GBF will ensure that, for each iteration,
∑j=1 n xj k -xj k-1 2≤ STEPMX 2
where k is the iteration number. Thus, if the problem has more than one solution, E04GBF is most likely to find the one nearest to the starting point. On difficult problems, a realistic choice can prevent the sequence of x k entering a region where the problem is ill-behaved and can help avoid overflow in the evaluation of F x. However, an underestimate of STEPMX can lead to inefficiency.
Suggested value: STEPMX=100000.0.
Constraint: STEPMX≥XTOL.
11:   X N – REAL (KIND=nag_wp) arrayInput/Output
On entry: X j must be set to a guess at the jth component of the position of the minimum, for j=1,2,…,n.
On exit: the final point x k . Thus, if IFAIL=0 on exit, X j is the jth component of the estimated position of the minimum.
12:   FSUMSQ – REAL (KIND=nag_wp)Output
On exit: the value of F x, the sum of squares of the residuals fi x, at the final point given in X.
13:   FVEC M – REAL (KIND=nag_wp) arrayOutput
On exit: the value of the residual fi x at the final point given in X, for i=1,2,…,m.
14:   FJAC LDFJACN – REAL (KIND=nag_wp) arrayOutput
On exit: the value of the first derivative ∂fi ∂xj evaluated at the final point given in X, for i=1,2,…,m and j=1,2,…,n.
15:   LDFJAC – INTEGERInput
On entry: the first dimension of the array FJAC as declared in the (sub)program from which E04GBF is called.
Constraint: LDFJAC≥M.
16:   S N – REAL (KIND=nag_wp) arrayOutput
On exit: the singular values of the Jacobian matrix at the final point. Thus S may be useful as information about the structure of your problem.
17:   V LDVN – REAL (KIND=nag_wp) arrayOutput
On exit: the matrix V associated with the singular value decomposition
J=US VT
of the Jacobian matrix at the final point, stored by columns. This matrix may be useful for statistical purposes, since it is the matrix of orthonormalized eigenvectors of JT J.
18:   LDV – INTEGERInput
On entry: the first dimension of the array V as declared in the (sub)program from which E04GBF is called.
Constraint: LDV≥N.
19:   NITER – INTEGEROutput
On exit: the number of iterations which have been performed in E04GBF.
20:   NF – INTEGEROutput
On exit: the number of times that the residuals have been evaluated (i.e., the number of calls of LSQFUN). If E04HEV is used as LSQLIN, NF is also the number of times that the Jacobian matrix has been evaluated.
21:   IW LIW – INTEGER arrayCommunication Array
22:   LIW – INTEGERInput
On entry: the dimension of the array IW as declared in the (sub)program from which E04GBF is called.
Constraint: LIW≥1.
23:   W LW – REAL (KIND=nag_wp) arrayCommunication Array
24:   LW – INTEGERInput
On entry: the dimension of the array W as declared in the (sub)program from which E04GBF is called.
Constraints:
  • if N>1, LW≥7×N+M×N+2×M+N×N;
  • if N=1, LW≥9+3×M.
25:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, because for this routine the values of the output arguments may be useful even if IFAIL≠0 on exit, the recommended value is -1. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Note: E04GBF may return useful information for one or more of the following detected errors or warnings.
Errors or warnings detected by the routine:
IFAIL<0
A negative value of IFAIL indicates an exit from E04GBF because you have set IFLAG negative in LSQFUN. The value of IFAIL will be the same as your setting of IFLAG.
IFAIL=1
On entry, | N<1,
or | M<N,
or | MAXCAL<1,
or | ETA<0.0,
or | ETA≥1.0,
or | XTOL<0.0,
or | STEPMX<XTOL,
or | LDFJAC<M,
or | LDV<N,
or | LIW<1,
or | LW<7×N+M×N+2×M+N×N when N>1,
or | LW<9+3×M when N=1.
When this exit occurs, no values will have been assigned to FSUMSQ, or to the elements of FVEC, FJAC, S or V.
IFAIL=2
There have been MAXCAL calls of LSQFUN. If steady reductions in the sum of squares, F x, were monitored up to the point where this exit occurred, then the exit probably occurred simply because MAXCAL was set too small, so the calculations should be restarted from the final point held in X. This exit may also indicate that F x has no minimum.
IFAIL=3
The conditions for a minimum have not all been satisfied, but a lower point could not be found. This could be because XTOL has been set so small that rounding errors in the evaluation of the residuals and derivatives make attainment of the convergence conditions impossible. See Section 7 for further information.
IFAIL=4
The method for computing the singular value decomposition of the Jacobian matrix has failed to converge in a reasonable number of sub-iterations. It may be worth applying E04GBF again starting with an initial approximation which is not too close to the point at which the failure occurred.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.
The values IFAIL=2, 3 or 4 may also be caused by mistakes in LSQFUN, by the formulation of the problem or by an awkward function. If there are no such mistakes it is worth restarting the calculations from a different starting point (not the point at which the failure occurred) in order to avoid the region which caused the failure.

7 Accuracy

A successful exit (IFAIL=0) is made from E04GBF when (B1, B2 and B3) or B4 or B5 hold, where
B1 ≡ α k ×p k <XTOL+ε×1.0+x k B2 ≡ F k -F k-1 < XTOL+ε 2×1.0+F k B3 ≡ g k <ε 1/3×1.0+F k B4 ≡ F k <ε 2 B5 ≡ g k < ε×F k 1/2
and where . and ε are as defined in XTOL, and F k and g k are the values of F x and its vector of first derivatives at x k .
If IFAIL=0, then the vector in X on exit, xsol, is almost certainly an estimate of xtrue, the position of the minimum to the accuracy specified by XTOL.
If IFAIL=3, then xsol may still be a good estimate of xtrue, but to verify this you should make the following checks. If
(a) | the sequence F x k converges to F xsol at a superlinear or a fast linear rate, and
(b) | g xsol T g xsol < 10 ε where T denotes transpose, then it is almost certain that xsol is a close approximation to the minimum.
When (b) is true, then usually F xsol is a close approximation to F xtrue. The values of F x k can be calculated in LSQMON, and the vector g xsol can be calculated from the contents of FVEC and FJAC on exit from E04GBF.
Further suggestions about confirmation of a computed solution are given in the E04 Chapter Introduction.

8 Parallelism and Performance

E04GBF is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
E04GBF makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The number of iterations required depends on the number of variables, the number of residuals, the behaviour of F x, the accuracy demanded and the distance of the starting point from the solution. The number of multiplications performed per iteration of E04GBF varies, but for m≫n is approximately n×m 2+O n 3. In addition, each iteration makes at least one call of LSQFUN. So, unless the residuals and their derivatives can be evaluated very quickly, the run time will be dominated by the time spent in LSQFUN.
Ideally, the problem should be scaled so that, at the solution, F x and the corresponding values of the xj are each in the range -1,+1, and so that at points one unit away from the solution F x differs from its value at the solution by approximately one unit. This will usually imply that the Hessian matrix of F x at the solution is well-conditioned. It is unlikely that you will be able to follow these recommendations very closely, but it is worth trying (by guesswork), as sensible scaling will reduce the difficulty of the minimization problem, so that E04GBF will take less computer time.
When the sum of squares represents the goodness-of-fit of a nonlinear model to observed data, elements of the variance-covariance matrix of the estimated regression coefficients can be computed by a subsequent call to E04YCF, using information returned in the arrays S and V. See E04YCF for further details.

10 Example

This example finds least squares estimates of x 1, x 2 and x 3 in the model
y=x 1+t 1 x 2t 2+x 3t 3
using the 15 sets of data given in the following table.
y t 1 t 2 t 3 0.14 1.0 15.0 1.0 0.18 2.0 14.0 2.0 0.22 3.0 13.0 3.0 0.25 4.0 12.0 4.0 0.29 5.0 11.0 5.0 0.32 6.0 10.0 6.0 0.35 7.0 9.0 7.0 0.39 8.0 8.0 8.0 0.37 9.0 7.0 7.0 0.58 10.0 6.0 6.0 0.73 11.0 5.0 5.0 0.96 12.0 4.0 4.0 1.34 13.0 3.0 3.0 2.10 14.0 2.0 2.0 4.39 15.0 1.0 1.0
Before calling E04GBF, the program calls E04YAF to check LSQFUN. It uses 0.5,1.0,1.5 as the initial guess at the position of the minimum.

10.1 Program Text

Program Text (e04gbfe.f90)

10.2 Program Data

Program Data (e04gbfe.d)

10.3 Program Results

Program Results (e04gbfe.r)

E04 Chapter Contents
E04 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


E04GDF : NAG Library, Mark 26

E04 Chapter Contents
E04 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

E04GDF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

E04GDF is a comprehensive modified Gauss–Newton algorithm for finding an unconstrained minimum of a sum of squares of m nonlinear functions in n variables m≥n. First derivatives are required.
The routine is intended for functions which have continuous first and second derivatives (although it will usually work even if the derivatives have occasional discontinuities).

2 Specification

SUBROUTINE E04GDF ( M, N, LSQFUN, LSQMON, IPRINT, MAXCAL, ETA, XTOL, STEPMX, X, FSUMSQ, FVEC, FJAC, LDFJAC, S, V, LDV, NITER, NF, IW, LIW, W, LW, IFAIL)
INTEGER | M, N, IPRINT, MAXCAL, LDFJAC, LDV, NITER, NF, IW(LIW), LIW, LW, IFAIL
REAL (KIND=nag_wp) | ETA, XTOL, STEPMX, X(N), FSUMSQ, FVEC(M), FJAC(LDFJAC,N), S(N), V(LDV,N), W(LW)
EXTERNAL | LSQFUN, LSQMON

3 Description

E04GDF is essentially identical to the subroutine LSQFDN in the NPL Algorithms Library. It is applicable to problems of the form
Minimize⁡F x=∑i=1 m fi x 2
where x = x 1,x 2,…,xn T and m≥n. (The functions fi x are often referred to as ‘residuals’.)
You must supply a subroutine to calculate the values of the fi x and their first derivatives ∂fi ∂xj at any point x.
From a starting point x 1 supplied by you, the routine generates a sequence of points x 2 ,x 3 ,…, which is intended to converge to a local minimum of F x. The sequence of points is given by
x k+1 =x k +α kp k
where the vector p k is a direction of search, and α k is chosen such that F x k +α kp k is approximately a minimum with respect to α k.
The vector p k used depends upon the reduction in the sum of squares obtained during the last iteration. If the sum of squares was sufficiently reduced, then p k is the Gauss–Newton direction; otherwise finite difference estimates of the second derivatives of the fi x are taken into account.
The method is designed to ensure that steady progress is made whatever the starting point, and to have the rapid ultimate convergence of Newton's method.

4 References

Gill P E and Murray W (1978) Algorithms for the solution of the nonlinear least squares problem SIAM J. Numer. Anal. 15 977–992

5 Arguments

1:   M – INTEGERInput
2:   N – INTEGERInput
On entry: the number m of residuals, fi x, and the number n of variables, xj.
Constraint: 1≤N≤M.
3:   LSQFUN – SUBROUTINE, supplied by the user.External Procedure
LSQFUN must calculate the vector of values fi x and Jacobian matrix of first derivatives ∂fi ∂xj at any point x. (However, if you do not wish to calculate the residuals or first derivatives at a particular x, there is the option of setting an argument to cause E04GDF to terminate immediately.)
The specification of LSQFUN is:
SUBROUTINE LSQFUN ( IFLAG, M, N, XC, FVEC, FJAC, LDFJAC, IW, LIW, W, LW)
INTEGER | IFLAG, M, N, LDFJAC, IW(LIW), LIW, LW
REAL (KIND=nag_wp) | XC(N), FVEC(M), FJAC(LDFJAC,N), W(LW)
Note: the dimension declaration for FJAC must contain the variable LDFJAC, not an integer constant.
1:   IFLAG – INTEGERInput/Output
On entry: to LSQFUN, IFLAG will be set to 1 or 2.
IFLAG=1
Indicates that only the Jacobian matrix needs to be evaluated
IFLAG=2
Indicates that both the residuals and the Jacobian matrix must be calculated
On exit: if it is not possible to evaluate the fi x or their first derivatives at the point given in XC (or if it wished to stop the calculations for any other reason), you should reset IFLAG to some negative number and return control to E04GDF. E04GDF will then terminate immediately, with IFAIL set to your setting of IFLAG.
2:   M – INTEGERInput
On entry: m, the numbers of residuals.
3:   N – INTEGERInput
On entry: n, the numbers of variables.
4:   XC N – REAL (KIND=nag_wp) arrayInput
On entry: the point x at which the values of the fi and the ∂fi ∂xj are required.
5:   FVEC M – REAL (KIND=nag_wp) arrayOutput
On exit: unless IFLAG=1 on entry, or IFLAG is reset to a negative number, then FVEC i must contain the value of fi at the point x, for i=1,2,…,m.
6:   FJAC LDFJACN – REAL (KIND=nag_wp) arrayOutput
On exit: unless IFLAG is reset to a negative number, FJAC ij must contain the value of ∂fi ∂xj at the point x, for i=1,2,…,m and j=1,2,…,n.
7:   LDFJAC – INTEGERInput
On entry: the first dimension of the array FJAC, set to m by E04GDF.
8:   IW LIW – INTEGER arrayWorkspace
9:   LIW – INTEGERInput
10:   W LW – REAL (KIND=nag_wp) arrayWorkspace
11:   LW – INTEGERInput
LSQFUN is called with E04GDF's arguments IW, LIW, W, LW as these arguments. They are present so that, when other library routines require the solution of a minimization subproblem, constants needed for the evaluation of residuals can be passed through IW and W. Similarly, you could pass quantities to LSQFUN from the segment which calls E04GDF by using partitions of IW and W beyond those used as workspace by E04GDF. However, because of the danger of mistakes in partitioning, it is recommended that you should pass information to LSQFUN via COMMON global variables and not use IW or W at all. In any case you must not change the elements of IW and W used as workspace by E04GDF.
LSQFUN must either be a module subprogram USEd by, or declared as EXTERNAL in, the (sub)program from which E04GDF is called. Arguments denoted as Input must not be changed by this procedure.
Note: LSQFUN should be tested separately before being used in conjunction with E04GDF.
4:   LSQMON – SUBROUTINE, supplied by the NAG Library or the user.External Procedure
If IPRINT≥0, you must supply LSQMON which is suitable for monitoring the minimization process. LSQMON must not change the values of any of its arguments.
If IPRINT<0, the dummy routine E04FDZ can be used as LSQMON.
The specification of LSQMON is:
SUBROUTINE LSQMON ( M, N, XC, FVEC, FJAC, LDFJAC, S, IGRADE, NITER, NF, IW, LIW, W, LW)
INTEGER | M, N, LDFJAC, IGRADE, NITER, NF, IW(LIW), LIW, LW
REAL (KIND=nag_wp) | XC(N), FVEC(M), FJAC(LDFJAC,N), S(N), W(LW)
Note: the dimension declaration for FJAC must contain the variable LDFJAC, not an integer constant.
1:   M – INTEGERInput
On entry: m, the numbers of residuals.
2:   N – INTEGERInput
On entry: n, the numbers of variables.
3:   XC N – REAL (KIND=nag_wp) arrayInput
On entry: the coordinates of the current point x.
4:   FVEC M – REAL (KIND=nag_wp) arrayInput
On entry: the values of the residuals fi at the current point x.
5:   FJAC LDFJACN – REAL (KIND=nag_wp) arrayInput
On entry: FJAC ij contains the value of ∂fi ∂xj at the current point x, for i=1,2,…,m and j=1,2,…,n.
6:   LDFJAC – INTEGERInput
On entry: the first dimension of the array FJAC as declared in the (sub)program from which E04GDF is called.
7:   S N – REAL (KIND=nag_wp) arrayInput
On entry: the singular values of the current Jacobian matrix. Thus S may be useful as information about the structure of your problem. (If IPRINT>0, LSQMON is called at the initial point before the singular values have been calculated. So the elements of S are set to zero for the first call of LSQMON.)
8:   IGRADE – INTEGERInput
On entry: E04GDF estimates the dimension of the subspace for which the Jacobian matrix can be used as a valid approximation to the curvature (see Gill and Murray (1978)). This estimate is called the grade of the Jacobian matrix, and IGRADE gives its current value.
9:   NITER – INTEGERInput
On entry: the number of iterations which have been performed in E04GDF.
10:   NF – INTEGERInput
On entry: the number of times that LSQFUN has been called so far with IFLAG=2. (In addition to these calls monitored by NF, LSQFUN is called not more than N times per iteration with IFLAG set to 1.)
11:   IW LIW – INTEGER arrayWorkspace
12:   LIW – INTEGERInput
13:   W LW – REAL (KIND=nag_wp) arrayWorkspace
14:   LW – INTEGERInput
As in LSQFUN, these arguments correspond to the arguments IW, LIW, W, LW of E04GDF. They are included in LSQMON's argument list primarily for when E04GDF is called by other library routines.
LSQMON must either be a module subprogram USEd by, or declared as EXTERNAL in, the (sub)program from which E04GDF is called. Arguments denoted as Input must not be changed by this procedure.
Note: you should normally print the sum of squares of residuals, so as to be able to examine the sequence of values of F x mentioned in Section 7. It is usually also helpful to print XC, the gradient of the sum of squares, NITER and NF.
5:   IPRINT – INTEGERInput
On entry: the frequency with which LSQMON is to be called.
IPRINT>0
LSQMON is called once every IPRINT iterations and just before exit from E04GDF.
IPRINT=0
LSQMON is just called at the final point.
IPRINT<0
LSQMON is not called at all.
IPRINT should normally be set to a small positive number.
Suggested value: IPRINT=1.
6:   MAXCAL – INTEGERInput
On entry: enables you to limit the number of times that LSQFUN is called by E04GDF. There will be an error exit (see Section 6) after MAXCAL evaluations of the residuals (i.e., calls of LSQFUN with IFLAG set to 2). It should be borne in mind that, in addition to the calls of LSQFUN which are limited directly by MAXCAL, there will be calls of LSQFUN (with IFLAG set to 1) to evaluate only first derivatives.
Suggested value: MAXCAL=50×n.
Constraint: MAXCAL≥1.
7:   ETA – REAL (KIND=nag_wp)Input
On entry: every iteration of E04GDF involves a linear minimization, i.e., minimization of F x k +α kp k with respect to α k. ETA specifies how accurately these linear minimizations are to be performed. The minimum with respect to α k will be located more accurately for small values of ETA (say, 0.01) than for large values (say, 0.9).
Although accurate linear minimizations will generally reduce the number of iterations, they will tend to increase the number of calls of LSQFUN (with IFLAG set to 2) needed for each linear minimization. On balance it is usually efficient to perform a low accuracy linear minimization.
Suggested value: ETA=0.5 (ETA=0.0 if N=1).
Constraint: 0.0≤ETA<1.0.
8:   XTOL – REAL (KIND=nag_wp)Input
On entry: the accuracy in x to which the solution is required.
If xtrue is the true value of x at the minimum, then xsol, the estimated position before a normal exit, is such that
xsol-xtrue<XTOL×1.0+xtrue
where y=∑j=1 n yj 2. For example, if the elements of xsol are not much larger than 1.0 in modulus and if XTOL=1.0E−5, then xsol is usually accurate to about five decimal places. (For further details see Section 7.)
If F x and the variables are scaled roughly as described in Section 9 and ε is the machine precision, then a setting of order XTOL=ε will usually be appropriate. If XTOL is set to 0.0 or some positive value less than 10 ε, E04GDF will use 10 ε instead of XTOL, since 10 ε is probably the smallest reasonable setting.
Constraint: XTOL≥0.0.
9:   STEPMX – REAL (KIND=nag_wp)Input
On entry: an estimate of the Euclidean distance between the solution and the starting point supplied by you. (For maximum efficiency, a slight overestimate is preferable.) E04GDF will ensure that, for each iteration,
∑j=1 n xj k -xj k-1 2≤ STEPMX 2
where k is the iteration number. Thus, if the problem has more than one solution, E04GDF is most likely to find the one nearest to the starting point. On difficult problems, a realistic choice can prevent the sequence of x k entering a region where the problem is ill-behaved and can help avoid overflow in the evaluation of F x. However, an underestimate of STEPMX can lead to inefficiency.
Suggested value: STEPMX=100000.0.
Constraint: STEPMX≥XTOL.
10:   X N – REAL (KIND=nag_wp) arrayInput/Output
On entry: X j must be set to a guess at the jth component of the position of the minimum, for j=1,2,…,n.
On exit: the final point x k . Thus, if IFAIL=0 on exit, X j is the jth component of the estimated position of the minimum.
11:   FSUMSQ – REAL (KIND=nag_wp)Output
On exit: the value of F x, the sum of squares of the residuals fi x, at the final point given in X.
12:   FVEC M – REAL (KIND=nag_wp) arrayOutput
On exit: the value of the residual fi x at the final point given in X, for i=1,2,…,m.
13:   FJAC LDFJACN – REAL (KIND=nag_wp) arrayOutput
On exit: the value of the first derivative ∂fi ∂xj evaluated at the final point given in X, for i=1,2,…,m and j=1,2,…,n.
14:   LDFJAC – INTEGERInput
On entry: the first dimension of the array FJAC as declared in the (sub)program from which E04GDF is called.
Constraint: LDFJAC≥M.
15:   S N – REAL (KIND=nag_wp) arrayOutput
On exit: the singular values of the Jacobian matrix at the final point. Thus S may be useful as information about the structure of your problem.
16:   V LDVN – REAL (KIND=nag_wp) arrayOutput
On exit: the matrix V associated with the singular value decomposition
J=US VT
of the Jacobian matrix at the final point, stored by columns. This matrix may be useful for statistical purposes, since it is the matrix of orthonormalized eigenvectors of JT J.
17:   LDV – INTEGERInput
On entry: the first dimension of the array V as declared in the (sub)program from which E04GDF is called.
Constraint: LDV≥N.
18:   NITER – INTEGEROutput
On exit: the number of iterations which have been performed in E04GDF.
19:   NF – INTEGEROutput
On exit: the number of times that the residuals have been evaluated (i.e., number of calls of LSQFUN with IFLAG set to 2).
20:   IW LIW – INTEGER arrayCommunication Array
21:   LIW – INTEGERInput
On entry: the dimension of the array IW as declared in the (sub)program from which E04GDF is called.
Constraint: LIW≥1.
22:   W LW – REAL (KIND=nag_wp) arrayCommunication Array
23:   LW – INTEGERInput
On entry: the dimension of the array W as declared in the (sub)program from which E04GDF is called.
Constraints:
  • if N>1, LW≥7×N+M×N+2×M+N×N;
  • if N=1, LW≥9+3×M.
24:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, because for this routine the values of the output arguments may be useful even if IFAIL≠0 on exit, the recommended value is -1. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Note: E04GDF may return useful information for one or more of the following detected errors or warnings.
Errors or warnings detected by the routine:
IFAIL<0
A negative value of IFAIL indicates an exit from E04GDF because you have set IFLAG negative in LSQFUN. The value of IFAIL will be the same as your setting of IFLAG.
IFAIL=1
On entry, | N<1,
or | M<N,
or | MAXCAL<1,
or | ETA<0.0,
or | ETA≥1.0,
or | XTOL<0.0,
or | STEPMX<XTOL,
or | LDFJAC<M,
or | LDV<N,
or | LIW<1,
or | LW<7×N+M×N+2×M+N×N when N>1,
or | LW<9+3×M when N=1.
When this exit occurs, no values will have been assigned to FSUMSQ, or to the elements of FVEC, FJAC, S or V.
IFAIL=2
There have been MAXCAL evaluations of the residuals. If steady reductions in the sum of squares, F x, were monitored up to the point where this exit occurred, then the exit probably occurred simply because MAXCAL was set too small, so the calculations should be restarted from the final point held in X. This exit may also indicate that F x has no minimum.
IFAIL=3
The conditions for a minimum have not all been satisfied, but a lower point could not be found. This could be because XTOL has been set so small that rounding errors in the evaluation of the residuals and derivatives make attainment of the convergence conditions impossible. See Section 7 for further information.
IFAIL=4
The method for computing the singular value decomposition of the Jacobian matrix has failed to converge in a reasonable number of sub-iterations. It may be worth applying E04GDF again starting with an initial approximation which is not too close to the point at which the failure occurred.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.
The values IFAIL=2, 3 or 4 may also be caused by mistakes in LSQFUN, by the formulation of the problem or by an awkward function. If there are no such mistakes it is worth restarting the calculations from a different starting point (not the point at which the failure occurred) in order to avoid the region which caused the failure.

7 Accuracy

A successful exit (IFAIL=0) is made from E04GDF when the matrix of approximate second derivatives of F x is positive definite, and when (B1, B2 and B3) or B4 or B5 hold, where
B1 ≡ α k×p k <XTOL+ε×1.0+x k B2 ≡ F k -F k-1 < XTOL+ε 2×1.0+F k B3 ≡ g k <ε 1/3×1.0+F k B4 ≡ F k <ε 2 B5 ≡ g k < ε×F k 1/2
and where . and ε are as defined in XTOL, and F k and g k are the values of F x and its vector of estimated first derivatives at x k .
If IFAIL=0 then the vector in X on exit, xsol, is almost certainly an estimate of xtrue, the position of the minimum to the accuracy specified by XTOL.
If IFAIL=3, then xsol may still be a good estimate of xtrue, but to verify this you should make the following checks. If
(a) | the sequence F x k converges to F xsol at a superlinear or a fast linear rate, and
(b) | g xsol T g xsol<10 ε, where T denotes transpose, then it is almost certain that xsol is a close approximation to the minimum.
When (b) is true, then usually F xsol is a close approximation to F xtrue. The values of F x k can be calculated in LSQMON, and the vector g xsol can be calculated from the contents of FVEC and FJAC on exit from E04GDF.
Further suggestions about confirmation of a computed solution are given in the E04 Chapter Introduction.

8 Parallelism and Performance

E04GDF is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
E04GDF makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The number of iterations required depends on the number of variables, the number of residuals, the behaviour of F x, the accuracy demanded and the distance of the starting point from the solution. The number of multiplications performed per iteration of E04GDF varies, but for m≫n is approximately n×m 2+O n 3. In addition, each iteration makes at least one call of LSQFUN. So, unless the residuals and their derivatives can be evaluated very quickly, the run time will be dominated by the time spent in LSQFUN.
Ideally, the problem should be scaled so that, at the solution, F x and the corresponding values of the xj are each in the range -1,+1, and so that at points one unit away from the solution, F x differs from its value at the solution by approximately one unit. This will usually imply that the Hessian matrix of F x at the solution is well-conditioned. It is unlikely that you will be able to follow these recommendations very closely, but it is worth trying (by guesswork), as sensible scaling will reduce the difficulty of the minimization problem, so that E04GDF will take less computer time.
When the sum of squares represents the goodness-of-fit of a nonlinear model to observed data, elements of the variance-covariance matrix of the estimated regression coefficients can be computed by a subsequent call to E04YCF, using information returned in the arrays S and V. See E04YCF for further details.

10 Example

This example finds least squares estimates of x 1, x 2 and x 3 in the model
y=x 1+t 1 x 2t 2+x 3t 3
using the 15 sets of data given in the following table.
y t 1 t 2 t 3 0.14 1.0 15.0 1.0 0.18 2.0 14.0 2.0 0.22 3.0 13.0 3.0 0.25 4.0 12.0 4.0 0.29 5.0 11.0 5.0 0.32 6.0 10.0 6.0 0.35 7.0 9.0 7.0 0.39 8.0 8.0 8.0 0.37 9.0 7.0 7.0 0.58 10.0 6.0 6.0 0.73 11.0 5.0 5.0 0.96 12.0 4.0 4.0 1.34 13.0 3.0 3.0 2.10 14.0 2.0 2.0 4.39 15.0 1.0 1.0
Before calling E04GDF, the program calls E04YAF to check LSQFUN. It uses 0.5,1.0,1.5 as the initial guess at the position of the minimum.

10.1 Program Text

Program Text (e04gdfe.f90)

10.2 Program Data

Program Data (e04gdfe.d)

10.3 Program Results

Program Results (e04gdfe.r)

E04 Chapter Contents
E04 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


E04GYF : NAG Library, Mark 26

E04 Chapter Contents
E04 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

E04GYF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

E04GYF is an easy-to-use quasi-Newton algorithm for finding an unconstrained minimum of a sum of squares of m nonlinear functions in n variables m≥n. First derivatives are required.
It is intended for functions which are continuous and which have continuous first and second derivatives (although it will usually work even if the derivatives have occasional discontinuities).

2 Specification

SUBROUTINE E04GYF ( M, N, LSFUN2, X, FSUMSQ, W, LW, IUSER, RUSER, IFAIL)
INTEGER | M, N, LW, IUSER(*), IFAIL
REAL (KIND=nag_wp) | X(N), FSUMSQ, W(LW), RUSER(*)
EXTERNAL | LSFUN2

3 Description

E04GYF is similar to the subroutine LSFDQ2 in the NPL Algorithms Library. It is applicable to problems of the form
Minimize⁡F x=∑i=1 m fi x 2
where x=x 1,x 2,…,xn T and m≥n. (The functions fi x are often referred to as ‘residuals’.) You must supply a subroutine to evaluate the residuals and their first derivatives at any point x.
Before attempting to minimize the sum of squares, the algorithm checks the subroutine for consistency. Then, from a starting point supplied by you, a sequence of points is generated which is intended to converge to a local minimum of the sum of squares. These points are generated using estimates of the curvature of F x.

4 References

Gill P E and Murray W (1978) Algorithms for the solution of the nonlinear least squares problem SIAM J. Numer. Anal. 15 977–992

5 Arguments

1:   M – INTEGERInput
2:   N – INTEGERInput
On entry: the number m of residuals, fi x, and the number n of variables, xj.
Constraint: 1≤N≤M.
3:   LSFUN2 – SUBROUTINE, supplied by the user.External Procedure
You must supply this routine to calculate the vector of values fi x and the Jacobian matrix of first derivatives ∂fi ∂xj at any point x. It should be tested separately before being used in conjunction with E04GYF (see the E04 Chapter Introduction).
The specification of LSFUN2 is:
SUBROUTINE LSFUN2 ( M, N, XC, FVEC, FJAC, LDFJAC, IUSER, RUSER)
INTEGER | M, N, LDFJAC, IUSER(*)
REAL (KIND=nag_wp) | XC(N), FVEC(M), FJAC(LDFJAC,N), RUSER(*)
Important: the dimension declaration for FJAC must contain the variable LDFJAC, not an integer constant.
1:   M – INTEGERInput
On entry: m, the numbers of residuals.
2:   N – INTEGERInput
On entry: n, the numbers of variables.
3:   XC N – REAL (KIND=nag_wp) arrayInput
On entry: the point x at which the values of the fi and the ∂fi ∂xj are required.
4:   FVEC M – REAL (KIND=nag_wp) arrayOutput
On exit: FVEC i must contain the value of fi at the point x, for i=1,2,…,m.
5:   FJAC LDFJACN – REAL (KIND=nag_wp) arrayOutput
On exit: FJAC ij must contain the value of ∂fi ∂xj at the point x, for i=1,2,…,m and j=1,2,…,n.
6:   LDFJAC – INTEGERInput
On entry: the first dimension of the array FJAC, set to m by E04GYF.
7:   IUSER* – INTEGER arrayUser Workspace
8:   RUSER* – REAL (KIND=nag_wp) arrayUser Workspace
LSFUN2 is called with the arguments IUSER and RUSER as supplied to E04GYF. You are free to use the arrays IUSER and RUSER to supply information to LSFUN2 as an alternative to using COMMON global variables.
LSFUN2 must either be a module subprogram USEd by, or declared as EXTERNAL in, the (sub)program from which E04GYF is called. Arguments denoted as Input must not be changed by this procedure.
4:   X N – REAL (KIND=nag_wp) arrayInput/Output
On entry: X j must be set to a guess at the jth component of the position of the minimum, for j=1,2,…,n. The routine checks the first derivatives calculated by LSFUN2 at the starting point and so is more likely to detect an error in your routine if the initial X j are nonzero and mutually distinct.
On exit: the lowest point found during the calculations. Thus, if IFAIL=0 on exit, X j is the jth component of the position of the minimum.
5:   FSUMSQ – REAL (KIND=nag_wp)Output
On exit: the value of the sum of squares, F x, corresponding to the final point stored in X.
6:   W LW – REAL (KIND=nag_wp) arrayWorkspace
7:   LW – INTEGERInput
On entry: the dimension of the array W as declared in the (sub)program from which E04GYF is called.
Constraints:
  • if N>1, LW≥8×N+2×N×N+2×M×N+3×M;
  • if N=1, LW≥11+5×M.
8:   IUSER* – INTEGER arrayUser Workspace
9:   RUSER* – REAL (KIND=nag_wp) arrayUser Workspace
IUSER and RUSER are not used by E04GYF, but are passed directly to LSFUN2 and may be used to pass information to this routine as an alternative to using COMMON global variables.
10:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, because for this routine the values of the output arguments may be useful even if IFAIL≠0 on exit, the recommended value is -1. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Note: E04GYF may return useful information for one or more of the following detected errors or warnings.
Errors or warnings detected by the routine:
IFAIL=1
On entry, | N<1,
or | M<N,
or | LW<8×N+2×N×N+2×M×N+3×M, when N>1,
or | LW<11+5×M, when N=1.
IFAIL=2
There have been 50×n calls of LSFUN2, yet the algorithm does not seem to have converged. This may be due to an awkward function or to a poor starting point, so it is worth restarting E04GYF from the final point held in X.
IFAIL=3
The final point does not satisfy the conditions for acceptance as a minimum, but no lower point could be found.
IFAIL=4
An auxiliary routine has been unable to complete a singular value decomposition in a reasonable number of sub-iterations.
IFAIL=5
IFAIL=6
IFAIL=7
IFAIL=8
There is some doubt about whether the point X x found by E04GYF is a minimum of F x. The degree of confidence in the result decreases as IFAIL increases. Thus, when IFAIL=5, it is probable that the final x gives a good estimate of the position of a minimum, but when IFAIL=8 it is very unlikely that the routine has found a minimum.
IFAIL=9
It is very likely that you have made an error in forming the derivatives ∂fi ∂xj in LSFUN2.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.
If you are not satisfied with the result (e.g., because IFAIL lies between 3 and 8), it is worth restarting the calculations from a different starting point (not the point at which the failure occurred) in order to avoid the region which caused the failure. Repeated failure may indicate some defect in the formulation of the problem.

7 Accuracy

If the problem is reasonably well scaled and a successful exit is made then, for a computer with a mantissa of t decimals, one would expect to get t/2-1 decimals accuracy in the components of x and between t-1 (if F x is of order 1 at the minimum) and 2 t-2 (if F x is close to zero at the minimum) decimals accuracy in F x.

8 Parallelism and Performance

E04GYF is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
E04GYF makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The number of iterations required depends on the number of variables, the number of residuals and their behaviour, and the distance of the starting point from the solution. The number of multiplications performed per iteration of E04GYF varies, but for m≫n is approximately n×m 2+O n 3. In addition, each iteration makes at least one call of LSFUN2. So, unless the residuals and their derivatives can be evaluated very quickly, the run time will be dominated by the time spent in LSFUN2.
Ideally the problem should be scaled so that the minimum value of the sum of squares is in the range 0,1 and so that at points a unit distance away from the solution the sum of squares is approximately a unit value greater than at the minimum. It is unlikely that you will be able to follow these recommendations very closely, but it is worth trying (by guesswork), as sensible scaling will reduce the difficulty of the minimization problem, so that E04GYF will take less computer time.
When the sum of squares represents the goodness-of-fit of a nonlinear model to observed data, elements of the variance-covariance matrix of the estimated regression coefficients can be computed by a subsequent call to E04YCF, using information returned in segments of the workspace array W. See E04YCF for further details.

10 Example

This example finds the least squares estimates of x 1, x 2 and x 3 in the model
y=x 1+t 1 x 2t 2+x 3t 3
using the 15 sets of data given in the following table.
y t 1 t 2 t 3 0.14 1.0 15.0 1.0 0.18 2.0 14.0 2.0 0.22 3.0 13.0 3.0 0.25 4.0 12.0 4.0 0.29 5.0 11.0 5.0 0.32 6.0 10.0 6.0 0.35 7.0 9.0 7.0 0.39 8.0 8.0 8.0 0.37 9.0 7.0 7.0 0.58 10.0 6.0 6.0 0.73 11.0 5.0 5.0 0.96 12.0 4.0 4.0 1.34 13.0 3.0 3.0 2.10 14.0 2.0 2.0 4.39 15.0 1.0 1.0
The program uses 0.5,1.0,1.5 as the initial guess at the position of the minimum.

10.1 Program Text

Program Text (e04gyfe.f90)

10.2 Program Data

Program Data (e04gyfe.d)

10.3 Program Results

Program Results (e04gyfe.r)

E04 Chapter Contents
E04 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


E04GZF : NAG Library, Mark 26

E04 Chapter Contents
E04 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

E04GZF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

E04GZF is an easy-to-use modified Gauss–Newton algorithm for finding an unconstrained minimum of a sum of squares of m nonlinear functions in n variables m≥n. First derivatives are required.
It is intended for functions which are continuous and which have continuous first and second derivatives (although it will usually work even if the derivatives have occasional discontinuities).

2 Specification

SUBROUTINE E04GZF ( M, N, LSFUN2, X, FSUMSQ, W, LW, IUSER, RUSER, IFAIL)
INTEGER | M, N, LW, IUSER(*), IFAIL
REAL (KIND=nag_wp) | X(N), FSUMSQ, W(LW), RUSER(*)
EXTERNAL | LSFUN2

3 Description

E04GZF is similar to the subroutine LSFDN2 in the NPL Algorithms Library. It is applicable to problems of the form
Minimize⁡F x=∑i=1 m fi x 2
where x=x 1,x 2,…,xn T and m≥n. (The functions fi x are often referred to as ‘residuals’.)
You must supply a subroutine to evaluate the residuals and their first derivatives at any point x.
Before attempting to minimize the sum of squares, the algorithm checks the subroutine for consistency. Then, from a starting point supplied by you, a sequence of points is generated which is intended to converge to a local minimum of the sum of squares. These points are generated using estimates of the curvature of F x.

4 References

Gill P E and Murray W (1978) Algorithms for the solution of the nonlinear least squares problem SIAM J. Numer. Anal. 15 977–992

5 Arguments

1:   M – INTEGERInput
2:   N – INTEGERInput
On entry: the number m of residuals, fi x, and the number n of variables, xj.
Constraint: 1≤N≤M.
3:   LSFUN2 – SUBROUTINE, supplied by the user.External Procedure
You must supply this routine to calculate the vector of values fi x and the Jacobian matrix of first derivatives ∂fi ∂xj at any point x. It should be tested separately before being used in conjunction with E04GZF.
The specification of LSFUN2 is:
SUBROUTINE LSFUN2 ( M, N, XC, FVEC, FJAC, LDFJAC, IUSER, RUSER)
INTEGER | M, N, LDFJAC, IUSER(*)
REAL (KIND=nag_wp) | XC(N), FVEC(M), FJAC(LDFJAC,N), RUSER(*)
Important: the dimension declaration for FJAC must contain the variable LDFJAC, not an integer constant.
1:   M – INTEGERInput
On entry: m, the numbers of residuals.
2:   N – INTEGERInput
On entry: n, the numbers of variables.
3:   XC N – REAL (KIND=nag_wp) arrayInput
On entry: the point x at which the values of the fi and the ∂fi ∂xj are required.
4:   FVEC M – REAL (KIND=nag_wp) arrayOutput
On exit: FVEC i must be set to the value of fi at the point x, for i=1,2,…,m.
5:   FJAC LDFJACN – REAL (KIND=nag_wp) arrayOutput
On exit: FJAC ij must be set to the value of ∂fi ∂xj at the point x, for i=1,2,…,m and j=1,2,…,n.
6:   LDFJAC – INTEGERInput
On entry: the first dimension of the array FJAC, set to m by E04GZF.
7:   IUSER* – INTEGER arrayUser Workspace
8:   RUSER* – REAL (KIND=nag_wp) arrayUser Workspace
LSFUN2 is called with the arguments IUSER and RUSER as supplied to E04GZF. You are free to use the arrays IUSER and RUSER to supply information to LSFUN2 as an alternative to using COMMON global variables.
LSFUN2 must either be a module subprogram USEd by, or declared as EXTERNAL in, the (sub)program from which E04GZF is called. Arguments denoted as Input must not be changed by this procedure.
4:   X N – REAL (KIND=nag_wp) arrayInput/Output
On entry: X j must be set to a guess at the jth component of the position of the minimum, for j=1,2,…,n. The routine checks the first derivatives calculated by LSFUN2 at the starting point and so is more likely to detect any error in your routines if the initial X j are nonzero and mutually distinct.
On exit: the lowest point found during the calculations. Thus, if IFAIL=0 on exit, X j is the jth component of the position of the minimum.
5:   FSUMSQ – REAL (KIND=nag_wp)Output
On exit: the value of the sum of squares, F x, corresponding to the final point stored in X.
6:   W LW – REAL (KIND=nag_wp) arrayWorkspace
7:   LW – INTEGERInput
On entry: the dimension of the array W as declared in the (sub)program from which E04GZF is called.
Constraints:
  • if N>1, LW≥8×N+2×N×N+2×M×N+3×M;
  • if N=1, LW≥11+5×M.
8:   IUSER* – INTEGER arrayUser Workspace
9:   RUSER* – REAL (KIND=nag_wp) arrayUser Workspace
IUSER and RUSER are not used by E04GZF, but are passed directly to LSFUN2 and may be used to pass information to this routine as an alternative to using COMMON global variables.
10:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, because for this routine the values of the output arguments may be useful even if IFAIL≠0 on exit, the recommended value is -1. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Note: E04GZF may return useful information for one or more of the following detected errors or warnings.
Errors or warnings detected by the routine:
IFAIL=1
On entry, | N<1,
or | M<N,
or | LW<8×N+2×N×N+2×M×N+3×M, when N>1,
or | LW<11+5×M, when N=1.
IFAIL=2
There have been 50×n calls of LSFUN2, yet the algorithm does not seem to have converged. This may be due to an awkward function or to a poor starting point, so it is worth restarting E04GZF from the final point held in X.
IFAIL=3
The final point does not satisfy the conditions for acceptance as a minimum, but no lower point could be found.
IFAIL=4
An auxiliary routine has been unable to complete a singular value decomposition in a reasonable number of sub-iterations.
IFAIL=5
IFAIL=6
IFAIL=7
IFAIL=8
There is some doubt about whether the point X x found by E04GZF is a minimum of F x. The degree of confidence in the result decreases as IFAIL increases. Thus, when IFAIL=5, it is probable that the final x gives a good estimate of the position of a minimum, but when IFAIL=8 it is very unlikely that the routine has found a minimum.
IFAIL=9
It is very likely that you have made an error in forming the derivatives ∂fi ∂xj in LSFUN2.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.
If you are not satisfied with the result (e.g., because IFAIL lies between 3 and 8), it is worth restarting the calculations from a different starting point (not the point at which the failure occurred) in order to avoid the region which caused the failure. Repeated failure may indicate some defect in the formulation of the problem.

7 Accuracy

If the problem is reasonably well scaled and a successful exit is made, then, for a computer with a mantissa of t decimals, one would expect to get about t/2-1 decimals accuracy in the components of x and between t-1 (if F x is of order 1 at the minimum) and 2 t-2 (if F x is close to zero at the minimum) decimals accuracy in F x.

8 Parallelism and Performance

E04GZF is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
E04GZF makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The number of iterations required depends on the number of variables, the number of residuals and their behaviour, and the distance of the starting point from the solution. The number of multiplications performed per iteration of E04GZF varies, but for m≫n is approximately n×m 2+O n 3. In addition, each iteration makes at least one call of LSFUN2. So, unless the residuals and their derivatives can be evaluated very quickly, the run time will be dominated by the time spent in LSFUN2.
Ideally, the problem should be scaled so that the minimum value of the sum of squares is in the range 0,+1 and so that at points a unit distance away from the solution the sum of squares is approximately a unit value greater than at the minimum. It is unlikely that you will be able to follow these recommendations very closely, but it is worth trying (by guesswork), as sensible scaling will reduce the difficulty of the minimization problem, so that E04GZF will take less computer time.
When the sum of squares represents the goodness-of-fit of a nonlinear model to observed data, elements of the variance-covariance matrix of the estimated regression coefficients can be computed by a subsequent call to E04YCF, using information returned in segments of the workspace array W. See E04YCF for further details.

10 Example

This example finds least squares estimates of x 1, x 2 and x 3 in the model
y=x 1+t 1 x 2t 2+x 3t 3
using the 15 sets of data given in the following table.
y t 1 t 2 t 3 0.14 1.0 15.0 1.0 0.18 2.0 14.0 2.0 0.22 3.0 13.0 3.0 0.25 4.0 12.0 4.0 0.29 5.0 11.0 5.0 0.32 6.0 10.0 6.0 0.35 7.0 9.0 7.0 0.39 8.0 8.0 8.0 0.37 9.0 7.0 7.0 0.58 10.0 6.0 6.0 0.73 11.0 5.0 5.0 0.96 12.0 4.0 4.0 1.34 13.0 3.0 3.0 2.10 14.0 2.0 2.0 4.39 15.0 1.0 1.0
The program uses 0.5,1.0,1.5 as the initial guess at the position of the minimum.

10.1 Program Text

Program Text (e04gzfe.f90)

10.2 Program Data

Program Data (e04gzfe.d)

10.3 Program Results

Program Results (e04gzfe.r)

E04 Chapter Contents
E04 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


E04HCF : NAG Library, Mark 26

E04 Chapter Contents
E04 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

E04HCF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

E04HCF checks that a subroutine for evaluating an objective function and its first derivatives produces derivative values which are consistent with the function values calculated.

2 Specification

SUBROUTINE E04HCF ( N, FUNCT, X, F, G, IW, LIW, W, LW, IFAIL)
INTEGER | N, IW(LIW), LIW, LW, IFAIL
REAL (KIND=nag_wp) | X(N), F, G(N), W(LW)
EXTERNAL | FUNCT

3 Description

Routines for minimizing a function of several variables may require you to supply a subroutine to evaluate the objective function F x 1,x 2,…,xn and its first derivatives. E04HCF is designed to check the derivatives calculated by such user-supplied subroutines . As well as the routine to be checked ( FUNCT), you must supply a point x=x 1,x 2,…,xn T at which the check will be made. Note that E04HCF checks routines of the form required for E04KDF and E04LBF.
E04HCF first calls FUNCT to evaluate F and its first derivatives gj= ∂F ∂xj , for j=1,2,…,n at x. The components of the user-supplied derivatives along two orthogonal directions (defined by unit vectors p 1 and p 2, say) are then calculated; these will be gT p 1 and gT p 2 respectively. The same components are also estimated by finite differences, giving quantities
vk=F x+h pk-F x h,  k=1,2
where h is a small positive scalar. If the relative difference between v 1 and gT p 1 or between v 2 and gT p 2 is judged too large, an error indicator is set.

4 References

None.

5 Arguments

1:   N – INTEGERInput
On entry: the number n of independent variables in the objective function.
Constraint: N≥1.
2:   FUNCT – SUBROUTINE, supplied by the user.External Procedure
FUNCT must evaluate the function and its first derivatives at a given point. (The minimization routines mentioned in Section 3 gives you the option of resetting arguments of FUNCT to cause the minimization process to terminate immediately. E04HCF will also terminate immediately, without finishing the checking process, if the argument in question is reset.)
The specification of FUNCT is:
SUBROUTINE FUNCT ( IFLAG, N, XC, FC, GC, IW, LIW, W, LW)
INTEGER | IFLAG, N, IW(LIW), LIW, LW
REAL (KIND=nag_wp) | XC(N), FC, GC(N), W(LW)
1:   IFLAG – INTEGERInput/Output
On entry: will be set to 2.
On exit: if you reset IFLAG to a negative number in FUNCT and return control to E04HCF, E04HCF will terminate immediately with IFAIL set to your setting of IFLAG.
2:   N – INTEGERInput
On entry: the number n of variables.
3:   XC N – REAL (KIND=nag_wp) arrayInput
On entry: the point x at which F and its derivatives are required.
4:   FC – REAL (KIND=nag_wp)Output
On exit: unless FUNCT resets IFLAG, FC must be set to the value of the function F at the current point x.
5:   GC N – REAL (KIND=nag_wp) arrayOutput
On exit: unless FUNCT resets IFLAG, GC j must be set to the value of the first derivative ∂F ∂xj at the point x, for j=1,2,…,n.
6:   IW LIW – INTEGER arrayWorkspace
7:   LIW – INTEGERInput
8:   W LW – REAL (KIND=nag_wp) arrayWorkspace
9:   LW – INTEGERInput
These arguments are present so that FUNCT will be of the form required by the minimization routines mentioned in Section 3. FUNCT is called with E04HCF's arguments IW, LIW, W, LW as these arguments. If the advice given in the minimization routine documents is being followed, you will have no reason to examine or change any elements of IW or W. In any case, FUNCT must not change the first 3×N elements of W.
FUNCT must either be a module subprogram USEd by, or declared as EXTERNAL in, the (sub)program from which E04HCF is called. Arguments denoted as Input must not be changed by this procedure.
3:   X N – REAL (KIND=nag_wp) arrayInput
On entry: X j, for j=1,2,…,n, must be set to the coordinates of a suitable point at which to check the derivatives calculated by FUNCT. ‘Obvious’ settings, such as 0.0 ​ or ​ 1.0, should not be used since, at such particular points, incorrect terms may take correct values (particularly zero), so that errors could go undetected. Similarly, it is preferable that no two elements of X should be the same.
4:   F – REAL (KIND=nag_wp)Output
On exit: unless you set IFLAG negative in the first call of FUNCT, F contains the value of the objective function F x at the point given by you in X.
5:   G N – REAL (KIND=nag_wp) arrayOutput
On exit: unless you set IFLAG negative in the first call of FUNCT, G j contains the value of the derivative ∂F ∂xj at the point given in X, as calculated by FUNCT, for j=1,2,…,n.
6:   IW LIW – INTEGER arrayCommunication Array
This array is in the argument list so that it can be used by other library routines for passing integer quantities to FUNCT. It is not examined or changed by E04HCF. Generally, you must provide an array IW but are advised not to use it.
7:   LIW – INTEGERInput
On entry: the dimension of the array IW as declared in the (sub)program from which E04HCF is called.
Constraint: LIW≥1.
8:   W LW – REAL (KIND=nag_wp) arrayCommunication Array
9:   LW – INTEGERInput
On entry: the dimension of the array W as declared in the (sub)program from which E04HCF is called.
Constraint: LW≥3×N.
10:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, because for this routine the values of the output arguments may be useful even if IFAIL≠0 on exit, the recommended value is -1. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Note: E04HCF may return useful information for one or more of the following detected errors or warnings.
Errors or warnings detected by the routine:
IFAIL<0
A negative value of IFAIL indicates an exit from E04HCF because you have set IFLAG negative in FUNCT. The setting of IFAIL will be the same as your setting of IFLAG. The check on FUNCT will not have been completed.
IFAIL=1
On entry, | N<1,
or | LIW<1,
or | LW<3×N.
IFAIL=2
You should check carefully the derivation and programming of expressions for the derivatives of F x, because it is very unlikely that FUNCT is calculating them correctly.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

IFAIL is set to 2 if
vk-gT pk 2≥h× gT pk 2+1
for k=1​ or ​2. (See Section 3 for definitions of the quantities involved.) The scalar h is set equal to ε, where ε is the machine precision as given by X02AJF.

8 Parallelism and Performance

E04HCF is not threaded in any implementation.

9 Further Comments

FUNCT is called 3 times.
Before using E04HCF to check the calculation of first derivatives, you should be confident that FUNCT is calculating F correctly. The usual way of checking the calculation of the function is to compare values of F x calculated by FUNCT at nontrivial points x with values calculated independently. (‘Non-trivial’ means that, as when setting x before calling E04HCF, coordinates such as 0.0 or 1.0 should be avoided.)
E04HCF only checks the derivatives calculated when IFLAG=2. So, if FUNCT is intended for use in conjunction with a minimization routine which may set IFLAG to 1, you must check that, for given settings of the XC j, FUNCT produces the same values for the GC j when IFLAG is set to 1 as when IFLAG is set to 2.

10 Example

Suppose that it is intended to use E04KDF to minimize
F= x 1+10 x 2 2+5⁢ x 3-x 4 2+ x 2-2 x 3 4+10⁢ x 1-x 4 4.
The following program could be used to check the first derivatives calculated by FUNCT. (The tests of whether IFLAG=0 or 1 in FUNCT are present ready for when FUNCT is called by E04KDF. E04HCF will always call FUNCT with IFLAG set to 2.)

10.1 Program Text

Program Text (e04hcfe.f90)

10.2 Program Data

None.

10.3 Program Results

Program Results (e04hcfe.r)

E04 Chapter Contents
E04 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


E04HDF : NAG Library, Mark 26

E04 Chapter Contents
E04 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

E04HDF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

E04HDF checks that a subroutine for calculating second derivatives of an objective function is consistent with a subroutine for calculating the corresponding first derivatives.

2 Specification

SUBROUTINE E04HDF ( N, FUNCT, H, X, G, HESL, LH, HESD, IW, LIW, W, LW, IFAIL)
INTEGER | N, LH, IW(LIW), LIW, LW, IFAIL
REAL (KIND=nag_wp) | X(N), G(N), HESL(LH), HESD(N), W(LW)
EXTERNAL | FUNCT, H

3 Description

Routines for minimizing a function F x 1,x 2,…,xn of the variables x 1,x 2,…,xn may require you to provide a subroutine to evaluate the second derivatives of F. E04HDF is designed to check the second derivatives calculated by such user-supplied subroutines. As well as the routine to be checked (H), you must supply a subroutine (FUNCT) to evaluate the first derivatives, and a point x=x 1,x 2,…,xn T at which the checks will be made. Note that E04HDF checks routines of the form required for E04LBF.
E04HDF first calls user-supplied subroutines FUNCT and H to evaluate the first and second derivatives of F at x. The user-supplied Hessian matrix (H, say) is projected onto two orthogonal vectors y and z to give the scalars yT Hy and zT Hz respectively. The same projections of the Hessian matrix are also estimated by finite differences, giving
p=yT g x+hy-yT g x/h and q=zT g x+hz-zT g x/h
respectively, where g denotes the vector of first derivatives at the point in brackets and h is a small positive scalar. If the relative difference between p and yT Hy or between q and zT Hz is judged too large, an error indicator is set.

4 References

None.

5 Arguments

1:   N – INTEGERInput
On entry: the number n of independent variables in the objective function.
Constraint: N≥1.
2:   FUNCT – SUBROUTINE, supplied by the user.External Procedure
FUNCT must evaluate the function and its first derivatives at a given point. (E04LBF gives you the option of resetting arguments of FUNCT to cause the minimization process to terminate immediately. E04HDF will also terminate immediately, without finishing the checking process, if the argument in question is reset.)
The specification of FUNCT is:
SUBROUTINE FUNCT ( IFLAG, N, XC, FC, GC, IW, LIW, W, LW)
INTEGER | IFLAG, N, IW(LIW), LIW, LW
REAL (KIND=nag_wp) | XC(N), FC, GC(N), W(LW)
1:   IFLAG – INTEGERInput/Output
On entry: to FUNCT, IFLAG will be set to 2.
On exit: if you set IFLAG to some negative number in FUNCT and return control to E04HDF, E04HDF will terminate immediately with IFAIL set to your setting of IFLAG.
2:   N – INTEGERInput
On entry: the number n of variables.
3:   XC N – REAL (KIND=nag_wp) arrayInput
On entry: the point x at which the function and first derivatives are required.
4:   FC – REAL (KIND=nag_wp)Output
On exit: unless FUNCT resets IFLAG, FC must be set to the value of the objective function F at the current point x.
5:   GC N – REAL (KIND=nag_wp) arrayOutput
On exit: unless FUNCT resets IFLAG, GC j must be set to the value of the first derivative ∂F ∂xj at the point x, for j=1,2,…,n.
6:   IW LIW – INTEGER arrayWorkspace
7:   LIW – INTEGERInput
8:   W LW – REAL (KIND=nag_wp) arrayWorkspace
9:   LW – INTEGERInput
These arguments are present so that FUNCT will be of the form required by E04LBF. FUNCT is called with E04HDF's arguments IW, LIW, W, LW as these arguments. If the advice given in E04LBF is being followed, you will have no reason to examine or change any elements of IW or W. In any case, FUNCT must not change the first 5×N elements of W.
FUNCT must either be a module subprogram USEd by, or declared as EXTERNAL in, the (sub)program from which E04HDF is called. Arguments denoted as Input must not be changed by this procedure.
E04HCF should be used to check the first derivatives calculated by FUNCT before E04HDF is used to check the second derivatives, since E04HDF assumes that the first derivatives are correct.
3:   H – SUBROUTINE, supplied by the user.External Procedure
H must evaluate the second derivatives of the function at a given point. (As with FUNCT, an argument can be set to cause immediate termination.)
The specification of H is:
SUBROUTINE H ( IFLAG, N, XC, FHESL, LH, FHESD, IW, LIW, W, LW)
INTEGER | IFLAG, N, LH, IW(LIW), LIW, LW
REAL (KIND=nag_wp) | XC(N), FHESL(LH), FHESD(N), W(LW)
1:   IFLAG – INTEGERInput/Output
On entry: is set to a non-negative number.
On exit: if H resets IFLAG to a negative number, E04HDF will terminate immediately with IFAIL set to your setting of IFLAG.
2:   N – INTEGERInput
On entry: the number n of variables.
3:   XC N – REAL (KIND=nag_wp) arrayInput
On entry: the point x at which the second derivatives of F x are required.
4:   FHESL LH – REAL (KIND=nag_wp) arrayOutput
On exit: unless IFLAG is reset, H must place the strict lower triangle of the second derivative matrix of F (evaluated at the point x) in FHESL, stored by rows, i.e., FHESL i-1i-2/2+j must be set to the value of ∂2 F ∂xi∂xj at the point x, for i=2,3,…,n and j=1,2,…,i-1. (The upper triangle is not required because the matrix is symmetric.)
5:   LH – INTEGERInput
On entry: the length of the array FHESL.
6:   FHESD N – REAL (KIND=nag_wp) arrayInput/Output
On entry: contains the value of ∂F ∂xj at the point x, for j=1,2,…,n. Routines written to take advantage of a similar feature of E04LBF can be tested as they stand by E04HDF.
On exit: unless IFLAG is reset, H must place the diagonal elements of the second derivative matrix of F (evaluated at the point x) in FHESD, i.e., FHESD j must be set to the value of ∂2 F ∂xj 2 at the point x, for j=1,2,…,n.
7:   IW LIW – INTEGER arrayWorkspace
8:   LIW – INTEGERInput
9:   W LW – REAL (KIND=nag_wp) arrayWorkspace
10:   LW – INTEGERInput
As in FUNCT, these arguments correspond to the arguments IW, LIW, W and LW of E04HDF. H must not change the first 5×N elements of W.
H must either be a module subprogram USEd by, or declared as EXTERNAL in, the (sub)program from which E04HDF is called. Arguments denoted as Input must not be changed by this procedure.
4:   X N – REAL (KIND=nag_wp) arrayInput
On entry: X j, for j=1,2,…,n, must contain the coordinates of a suitable point at which to check the derivatives calculated by FUNCT. ‘Obvious’ settings, such as 0.0 ​ or ​ 1.0, should not be used since, at such particular points, incorrect terms may take correct values (particularly zero), so that errors could go undetected. Similarly, it is advisable that no two elements of X should be the same.
5:   G N – REAL (KIND=nag_wp) arrayOutput
On exit: unless you set IFLAG negative in the first call of FUNCT, G j contains the value of the first derivative ∂F ∂xj at the point given in X, as calculated by FUNCT, for j=1,2,…,N.
6:   HESL LH – REAL (KIND=nag_wp) arrayOutput
On exit: unless you set IFLAG negative in H, HESL contains the strict lower triangle of the second derivative matrix of F, as evaluated by H at the point given in X, stored by rows.
7:   LH – INTEGERInput
On entry: the dimension of the array HESL as declared in the (sub)program from which E04HDF is called.
Constraint: LH≥max 1,N×N-1/2.
8:   HESD N – REAL (KIND=nag_wp) arrayOutput
On exit: unless you set IFLAG negative in H, HESD contains the diagonal elements of the second derivative matrix of F, as evaluated by H at the point given in X.
9:   IW LIW – INTEGER arrayCommunication Array
This array is in the argument list so that it can be used by other library routines for passing integer quantities to FUNCT or H. It is not examined or changed by E04HDF. In general you must provide an array IW, but are advised not to use it.
10:   LIW – INTEGERInput
On entry: the dimension of the array IW as declared in the (sub)program from which E04HDF is called.
Constraint: LIW≥1.
11:   W LW – REAL (KIND=nag_wp) arrayCommunication Array
12:   LW – INTEGERInput
On entry: the dimension of the array W as declared in the (sub)program from which E04HDF is called.
Constraint: LW≥5×N.
13:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, because for this routine the values of the output arguments may be useful even if IFAIL≠0 on exit, the recommended value is -1. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Note: E04HDF may return useful information for one or more of the following detected errors or warnings.
Errors or warnings detected by the routine:
IFAIL<0
A negative value of IFAIL indicates an exit from E04HDF because you have set IFLAG negative in FUNCT or H. The value of IFAIL will be the same as the value you set for IFLAG. The check on H will not have been completed.
IFAIL=1
On entry, | N<1,
or | LH < max 1,N×N-1/2 ,
or | LIW<1,
or | LW<5×N.
IFAIL=2
You should check carefully the derivation and programming of expressions for the second derivatives of F x, because it is very unlikely that H is calculating them correctly.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

IFAIL is set to 2 if
yT Hy-p≥h×yT Hy+1.0  or ​ zT Hz-q≥h×zT Hz+1.0
where h is set equal to ε (ε being the machine precision as given by X02AJF) and other quantities are as defined in Section 3.

8 Parallelism and Performance

E04HDF makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

E04HDF calls H once and FUNCT three times.

10 Example

Suppose that it is intended to use E04LBF to minimize
F= x 1+10 x 2 2+5⁢ x 3-x 4 2+ x 2-2 x 3 4+10⁢ x 1-x 4 4
The following program could be used to check the second derivatives calculated by H required. (The call of E04HDF is preceded by a call of E04HCF to check FUNCT which calculates the first derivatives.)

10.1 Program Text

Program Text (e04hdfe.f90)

10.2 Program Data

None.

10.3 Program Results

Program Results (e04hdfe.r)

E04 Chapter Contents
E04 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


E04HEF : NAG Library, Mark 26

E04 Chapter Contents
E04 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

E04HEF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

E04HEF is a comprehensive modified Gauss–Newton algorithm for finding an unconstrained minimum of a sum of squares of m nonlinear functions in n variables m≥n. First and second derivatives are required.
The routine is intended for functions which have continuous first and second derivatives (although it will usually work even if the derivatives have occasional discontinuities).

2 Specification

SUBROUTINE E04HEF ( M, N, LSQFUN, LSQHES, LSQMON, IPRINT, MAXCAL, ETA, XTOL, STEPMX, X, FSUMSQ, FVEC, FJAC, LDFJAC, S, V, LDV, NITER, NF, IW, LIW, W, LW, IFAIL)
INTEGER | M, N, IPRINT, MAXCAL, LDFJAC, LDV, NITER, NF, IW(LIW), LIW, LW, IFAIL
REAL (KIND=nag_wp) | ETA, XTOL, STEPMX, X(N), FSUMSQ, FVEC(M), FJAC(LDFJAC,N), S(N), V(LDV,N), W(LW)
EXTERNAL | LSQFUN, LSQHES, LSQMON

3 Description

E04HEF is essentially identical to the subroutine LSQSDN in the NPL Algorithms Library. It is applicable to problems of the form:
Minimize⁡F x=∑i=1 m fi x 2
where x=x 1,x 2,…,xn T and m≥n. (The functions fi x are often referred to as ‘residuals’.)
You must supply subroutines to calculate the values of the fi x and their first derivatives and second derivatives at any point x.
From a starting point x 1 supplied by you, the routine generates a sequence of points x 2 ,x 3 ,…, which is intended to converge to a local minimum of F x. The sequence of points is given by
x k+1 =x k +α kp k
where the vector p k is a direction of search, and α k is chosen such that F x k +α kp k is approximately a minimum with respect to α k .
The vector p k used depends upon the reduction in the sum of squares obtained during the last iteration. If the sum of squares was sufficiently reduced, then p k is the Gauss–Newton direction; otherwise the second derivatives of the fi x are taken into account.
The method is designed to ensure that steady progress is made whatever the starting point, and to have the rapid ultimate convergence of Newton's method.

4 References

Gill P E and Murray W (1978) Algorithms for the solution of the nonlinear least squares problem SIAM J. Numer. Anal. 15 977–992

5 Arguments

1:   M – INTEGERInput
2:   N – INTEGERInput
On entry: the number m of residuals, fi x, and the number n of variables, xj.
Constraint: 1≤N≤M.
3:   LSQFUN – SUBROUTINE, supplied by the user.External Procedure
LSQFUN must calculate the vector of values fi x and Jacobian matrix of first derivatives ∂fi ∂xj at any point x. (However, if you do not wish to calculate the residuals or first derivatives at a particular x, there is the option of setting an argument to cause E04HEF to terminate immediately.)
The specification of LSQFUN is:
SUBROUTINE LSQFUN ( IFLAG, M, N, XC, FVEC, FJAC, LDFJAC, IW, LIW, W, LW)
INTEGER | IFLAG, M, N, LDFJAC, IW(LIW), LIW, LW
REAL (KIND=nag_wp) | XC(N), FVEC(M), FJAC(LDFJAC,N), W(LW)
Important: the dimension declaration FJAC must contain the variable LDFJAC, not an integer constant.
1:   IFLAG – INTEGERInput/Output
On entry: to LSQFUN, IFLAG will be set to 2.
On exit: if it is not possible to evaluate the fi x or their first derivatives at the point given in XC (or if it wished to stop the calculations for any other reason), you should reset IFLAG to some negative number and return control to E04HEF. E04HEF will then terminate immediately, with IFAIL set to your setting of IFLAG.
2:   M – INTEGERInput
On entry: m, the numbers of residuals.
3:   N – INTEGERInput
On entry: n, the numbers of variables.
4:   XC N – REAL (KIND=nag_wp) arrayInput
On entry: the point x at which the values of the fi and the ∂fi ∂xj are required.
5:   FVEC M – REAL (KIND=nag_wp) arrayOutput
On exit: unless IFLAG is reset to a negative number, FVEC i must contain the value of fi at the point x, for i=1,2,…,m.
6:   FJAC LDFJACN – REAL (KIND=nag_wp) arrayOutput
On exit: unless IFLAG is reset to a negative number, FJAC ij must contain the value of ∂fi ∂xj at the point x, for i=1,2,…,m and j=1,2,…,n.
7:   LDFJAC – INTEGERInput
On entry: the first dimension of the array FJAC as declared in the (sub)program from which E04HEF is called.
8:   IW LIW – INTEGER arrayWorkspace
9:   LIW – INTEGERInput
10:   W LW – REAL (KIND=nag_wp) arrayWorkspace
11:   LW – INTEGERInput
LSQFUN is called with E04HEF's arguments IW, LIW, W, LW as these arguments. They are present so that, when other library routines require the solution of a minimization subproblem, constants needed for the evaluation of residuals can be passed through IW and W. Similarly, you could pass quantities of LSQFUN from the segment which calls E04HEF by using partitions of IW and W beyond those used as workspace by E04HEF. However, because of the danger of mistakes in partitioning, it is recommended that you should pass information to LSQFUN via COMMON global variables and not use IW or W at all. In any case you must not change the elements of IW and W used as workspace by E04HEF.
LSQFUN must either be a module subprogram USEd by, or declared as EXTERNAL in, the (sub)program from which E04HEF is called. Arguments denoted as Input must not be changed by this procedure.
Note: LSQFUN should be tested separately before being used in conjunction with E04HEF.
4:   LSQHES – SUBROUTINE, supplied by the user.External Procedure
LSQHES must calculate the elements of the symmetric matrix
B x=∑i=1 m fi x Gi x,
at any point x, where Gi x is the Hessian matrix of fi x. (As with LSQFUN, there is the option of causing E04HEF to terminate immediately.)
The specification of LSQHES is:
SUBROUTINE LSQHES ( IFLAG, M, N, FVEC, XC, B, LB, IW, LIW, W, LW)
INTEGER | IFLAG, M, N, LB, IW(LIW), LIW, LW
REAL (KIND=nag_wp) | FVEC(M), XC(N), B(LB), W(LW)
1:   IFLAG – INTEGERInput/Output
On entry: is set to a non-negative number.
On exit: if LSQHES resets IFLAG to some negative number, E04HEF will terminate immediately, with IFAIL set to your setting of IFLAG.
2:   M – INTEGERInput
On entry: m, the numbers of residuals.
3:   N – INTEGERInput
On entry: n, the numbers of variables.
4:   FVEC M – REAL (KIND=nag_wp) arrayInput
On entry: the value of the residual fi at the point x, for i=1,2,…,m, so that the values of the fi can be used in the calculation of the elements of B.
5:   XC N – REAL (KIND=nag_wp) arrayInput
On entry: the point x at which the elements of B are to be evaluated.
6:   B LB – REAL (KIND=nag_wp) arrayOutput
On exit: unless IFLAG is reset to a negative number, B must contain the lower triangle of the matrix B x, evaluated at the point x, stored by rows. (The upper triangle is not required because the matrix is symmetric.) More precisely, B j j-1/2+k must contain ∑i=1 m fi ∂2 fi ∂xj∂xk evaluated at the point x, for j=1,2,…,n and k=1,2,…,j.
7:   LB – INTEGERInput
On entry: the length of the array B.
8:   IW LIW – INTEGER arrayWorkspace
9:   LIW – INTEGERInput
10:   W LW – REAL (KIND=nag_wp) arrayWorkspace
11:   LW – INTEGERInput
As in LSQFUN, these arguments correspond to the arguments IW, LIW, W, LW of E04HEF. LSQHES must not change the sections of IW and W required as workspace by E04HEF. Again, it is recommended that you should pass quantities to LSQHES via COMMON global variables and not use IW or W at all.
LSQHES must either be a module subprogram USEd by, or declared as EXTERNAL in, the (sub)program from which E04HEF is called. Arguments denoted as Input must not be changed by this procedure.
Note: LSQHES should be tested separately before being used in conjunction with E04HEF.
5:   LSQMON – SUBROUTINE, supplied by the NAG Library or the user.External Procedure
If IPRINT≥0, you must supply LSQMON which is suitable for monitoring the minimization process. LSQMON must not change the values of any of its arguments.
If IPRINT<0, the dummy routine E04FDZ can be used as LSQMON.
The specification of LSQMON is:
SUBROUTINE LSQMON ( M, N, XC, FVEC, FJAC, LDFJAC, S, IGRADE, NITER, NF, IW, LIW, W, LW)
INTEGER | M, N, LDFJAC, IGRADE, NITER, NF, IW(LIW), LIW, LW
REAL (KIND=nag_wp) | XC(N), FVEC(M), FJAC(LDFJAC,N), S(N), W(LW)
Important: the dimension declaration for FJAC must contain the variable LDFJAC, not an integer constant.
1:   M – INTEGERInput
On entry: m, the numbers of residuals.
2:   N – INTEGERInput
On entry: n, the numbers of variables.
3:   XC N – REAL (KIND=nag_wp) arrayInput
On entry: the coordinates of the current point x.
4:   FVEC M – REAL (KIND=nag_wp) arrayInput
On entry: the values of the residuals fi at the current point x.
5:   FJAC LDFJACN – REAL (KIND=nag_wp) arrayInput
On entry: FJAC ij contains the value of ∂fi ∂xj at the current point x, for i=1,2,…,m and j=1,2,…,n.
6:   LDFJAC – INTEGERInput
On entry: the first dimension of the array FJAC as declared in the (sub)program from which E04HEF is called.
7:   S N – REAL (KIND=nag_wp) arrayInput
On entry: the singular values of the current Jacobian matrix. Thus S may be useful as information about the structure of your problem. (If IPRINT>0, LSQMON is called at the initial point before the singular values have been calculated, so the elements of S are set to zero for the first call of LSQMON.)
8:   IGRADE – INTEGERInput
On entry: E04HEF estimates the dimension of the subspace for which the Jacobian matrix can be used as a valid approximation to the curvature (see Gill and Murray (1978)). This estimate is called the grade of the Jacobian matrix, and IGRADE gives its current value.
9:   NITER – INTEGERInput
On entry: the number of iterations which have been performed in E04HEF.
10:   NF – INTEGERInput
On entry: the number of times that LSQFUN has been called so far. Thus NF gives the number of evaluations of the residuals and the Jacobian matrix.
11:   IW LIW – INTEGER arrayWorkspace
12:   LIW – INTEGERInput
13:   W LW – REAL (KIND=nag_wp) arrayWorkspace
14:   LW – INTEGERInput
As in LSQFUN and LSQHES, these arguments correspond to the arguments IW, LIW, W, LW of E04HEF. They are included in LSQMON's argument list primarily for when E04HEF is called by other library routines.
LSQMON must either be a module subprogram USEd by, or declared as EXTERNAL in, the (sub)program from which E04HEF is called. Arguments denoted as Input must not be changed by this procedure.
Note: you should normally print the sum of squares of residuals, so as to be able to examine the sequence of values of F x mentioned in Section 7. It is usually helpful to also print XC, the gradient of the sum of squares, NITER and NF.
6:   IPRINT – INTEGERInput
On entry: specifies the frequency with which LSQMON is to be called.
IPRINT>0
LSQMON is called once every IPRINT iterations and just before exit from E04HEF.
IPRINT=0
LSQMON is just called at the final point.
IPRINT<0
LSQMON is not called at all.
IPRINT should normally be set to a small positive number.
Suggested value: IPRINT=1.
7:   MAXCAL – INTEGERInput
On entry: this argument is present so as to enable you to limit the number of times that LSQFUN is called by E04HEF. There will be an error exit (see Section 6) after MAXCAL calls of LSQFUN.
Suggested value: MAXCAL=50×n.
Constraint: MAXCAL≥1.
8:   ETA – REAL (KIND=nag_wp)Input
On entry: every iteration of E04HEF involves a linear minimization (i.e., minimization of F x k +α k p k with respect to α k ). ETA must lie in the range 0.0≤ETA<1.0, and specifies how accurately these linear minimizations are to be performed. The minimum with respect to α k will be located more accurately for small values of ETA (say, 0.01) than for large values (say, 0.9).
Although accurate linear minimizations will generally reduce the number of iterations performed by E04HEF, they will increase the number of calls of LSQFUN made each iteration. On balance it is usually more efficient to perform a low accuracy minimization.
Suggested value: ETA=0.5 (ETA=0.0 if N=1).
Constraint: 0.0≤ETA<1.0.
9:   XTOL – REAL (KIND=nag_wp)Input
On entry: the accuracy in x to which the solution is required.
If xtrue is the true value of x at the minimum, then xsol, the estimated position before a normal exit, is such that
xsol-xtrue<XTOL×1.0+xtrue,
where y=∑j=1 n yj 2. For example, if the elements of xsol are not much larger than 1.0 in modulus and if XTOL=1.0E−5, then xsol is usually accurate to about five decimal places. (For further details see Section 7.)
If F x and the variables are scaled roughly as described in Section 9 and ε is the machine precision, then a setting of order XTOL=ε will usually be appropriate. If XTOL is set to 0.0 or some positive value less than 10 ε, E04HEF will use 10 ε instead of XTOL, since 10 ε is probably the smallest reasonable setting.
Constraint: XTOL≥0.0.
10:   STEPMX – REAL (KIND=nag_wp)Input
On entry: an estimate of the Euclidean distance between the solution and the starting point supplied by you. (For maximum efficiency, a slight overestimate is preferable.)
E04HEF will ensure that, for each iteration
∑j=1 n xj k -xj k-1 2≤ STEPMX 2,
where k is the iteration number. Thus, if the problem has more than one solution, E04HEF is most likely to find the one nearest to the starting point. On difficult problems, a realistic choice can prevent the sequence of x k entering a region where the problem is ill-behaved and can help avoid overflow in the evaluation of F x. However, an underestimate of STEPMX can lead to inefficiency.
Suggested value: STEPMX=100000.0.
Constraint: STEPMX≥XTOL.
11:   X N – REAL (KIND=nag_wp) arrayInput/Output
On entry: X j must be set to a guess at the jth component of the position of the minimum, for j=1,2,…,n.
On exit: the final point x k . Thus, if IFAIL=0 on exit, X j is the jth component of the estimated position of the minimum.
12:   FSUMSQ – REAL (KIND=nag_wp)Output
On exit: the value of F x, the sum of squares of the residuals fi x, at the final point given in X.
13:   FVEC M – REAL (KIND=nag_wp) arrayOutput
On exit: the value of the residual fi x at the final point given in X, for i=1,2,…,m.
14:   FJAC LDFJACN – REAL (KIND=nag_wp) arrayOutput
On exit: the value of the first derivative ∂fi ∂xj evaluated at the final point given in X, for i=1,2,…,m and j=1,2,…,n.
15:   LDFJAC – INTEGERInput
On entry: the first dimension of the array FJAC as declared in the (sub)program from which E04HEF is called.
Constraint: LDFJAC≥M.
16:   S N – REAL (KIND=nag_wp) arrayOutput
On exit: the singular values of the Jacobian matrix at the final point. Thus S may be useful as information about the structure of your problem.
17:   V LDVN – REAL (KIND=nag_wp) arrayOutput
On exit: the matrix V associated with the singular value decomposition
J=US VT
of the Jacobian matrix at the final point, stored by columns. This matrix may be useful for statistical purposes, since it is the matrix of orthonormalized eigenvectors of JT J.
18:   LDV – INTEGERInput
On entry: the first dimension of the array V as declared in the (sub)program from which E04HEF is called.
Constraint: LDV≥N.
19:   NITER – INTEGEROutput
On exit: the number of iterations which have been performed in E04HEF.
20:   NF – INTEGEROutput
On exit: the number of times that the residuals and Jacobian matrix have been evaluated (i.e., number of calls of LSQFUN).
21:   IW LIW – INTEGER arrayCommunication Array
22:   LIW – INTEGERInput
On entry: the dimension of the array IW as declared in the (sub)program from which E04HEF is called.
Constraint: LIW≥1.
23:   W LW – REAL (KIND=nag_wp) arrayCommunication Array
24:   LW – INTEGERInput
On entry: the dimension of the array W as declared in the (sub)program from which E04HEF is called.
Constraints:
  • if N>1, LW≥7×N+2×M×N+M+N×N;
  • if N=1, LW≥9+3×M.
25:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, because for this routine the values of the output arguments may be useful even if IFAIL≠0 on exit, the recommended value is -1. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Note: E04HEF may return useful information for one or more of the following detected errors or warnings.
Errors or warnings detected by the routine:
IFAIL<0
A negative value of IFAIL indicates an exit from E04HEF because you have set IFLAG negative in LSQFUN or LSQHES. The value of IFAIL will be the same as your setting of IFLAG.
IFAIL=1
On entry, | N<1,
or | M<N,
or | MAXCAL<1,
or | ETA<0.0,
or | ETA≥1.0,
or | XTOL<0.0,
or | STEPMX<XTOL,
or | LDFJAC<M,
or | LDV<N,
or | LIW<1,
or | LW<7×N+M×N+2×M+N×N when N>1,
or | LW<9+3×M when N=1.
When this exit occurs, no values will have been assigned to FSUMSQ, or to the elements of FVEC, FJAC, S or V.
IFAIL=2
There have been MAXCAL calls of LSQFUN. If steady reductions in the sum of squares, F x, were monitored up to the point where this exit occurred, then the exit probably occurred simply because MAXCAL was set too small, so the calculations should be restarted from the final point held in X. This exit may also indicate that F x has no minimum.
IFAIL=3
The conditions for a minimum have not all been satisfied, but a lower point could not be found. This could be because XTOL has been set so small that rounding errors in the evaluation of the residuals and derivatives make attainment of the convergence conditions impossible.
IFAIL=4
The method for computing the singular value decomposition of the Jacobian matrix has failed to converge in a reasonable number of sub-iterations. It may be worth applying E04HEF again starting with an initial approximation which is not too close to the point at which the failure occurred.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.
The values IFAIL=2, 3 and 4 may also be caused by mistakes in LSQFUN or LSQHES, by the formulation of the problem or by an awkward function. If there are no such mistakes it is worth restarting the calculations from a different starting point (not the point at which the failure occurred) in order to avoid the region which caused the failure.

7 Accuracy

A successful exit (IFAIL=0) is made from E04HEF when the matrix of second derivatives of F x is positive definite, and when (B1, B2 and B3) or B4 or B5 hold, where
B1 ≡ α k ×p k <XTOL+ε×1.0+x k B2 ≡ F k -F k-1 < XTOL+ε 2×1.0+F k B3 ≡ g k <ε 1/3×1.0+F k B4 ≡ F k <ε 2 B5 ≡ g k <ε×F k 1/2
and where . and ε are as defined in Section 5, and F k and g k are the values of F x and its vector of first derivatives at x k .
If IFAIL=0, then the vector in X on exit, xsol, is almost certainly an estimate of xtrue, the position of the minimum to the accuracy specified by XTOL.
If IFAIL=3, then xsol may still be a good estimate of xtrue, but to verify this you should make the following checks. If
(a) | the sequence F x k converges to F xsol at a superlinear or a fast linear rate, and
(b) | g xsol T g xsol<10 ε, where T denotes transpose, then it is almost certain that xsol is a close approximation to the minimum.
When (b) is true, then usually F xsol is a close approximation to F xtrue. The values of F x k can be calculated in LSQMON, and the vector g xsol can be calculated from the contents of FVEC and FJAC on exit from E04HEF.
Further suggestions about confirmation of a computed solution are given in the E04 Chapter Introduction.

8 Parallelism and Performance

E04HEF is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
E04HEF makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The number of iterations required depends on the number of variables, the number of residuals, the behaviour of F x, the accuracy demanded and the distance of the starting point from the solution. The number of multiplications performed per iteration of E04HEF varies, but for m≫n is approximately n×m 2+O n 3. In addition, each iteration makes at least one call of LSQFUN and some iterations may call LSQHES. So, unless the residuals and their derivatives can be evaluated very quickly, the run time will be dominated by the time spent in LSQFUN (and, to a lesser extent, in LSQHES).
Ideally, the problem should be scaled so that, at the solution, F x and the corresponding values of the xj are each in the range -1,+1, and so that at points one unit away from the solution, F x differs from its value at the solution by approximately one unit. This will usually imply that the Hessian matrix of F x at the solution is well-conditioned. It is unlikely that you will be able to follow these recommendations very closely, but it is worth trying (by guesswork), as sensible scaling will reduce the difficulty of the minimization problem, so that E04HEF will take less computer time.
When the sum of squares represents the goodness-of-fit of a nonlinear model to observed data, elements of the variance-covariance matrix of the estimated regression coefficients can be computed by a subsequent call to E04YCF, using information returned in the arrays S and V. See E04YCF for further details.

10 Example

This example finds least squares estimates of x 1,x 2 and x 3 in the model
y=x 1+t 1 x 2t 2+x 3t 3
using the 15 sets of data given in the following table.
y t 1 t 2 t 3 0.14 1.0 15.0 1.0 0.18 2.0 14.0 2.0 0.22 3.0 13.0 3.0 0.25 4.0 12.0 4.0 0.29 5.0 11.0 5.0 0.32 6.0 10.0 6.0 0.35 7.0 9.0 7.0 0.39 8.0 8.0 8.0 0.37 9.0 7.0 7.0 0.58 10.0 6.0 6.0 0.73 11.0 5.0 5.0 0.96 12.0 4.0 4.0 1.34 13.0 3.0 3.0 2.10 14.0 2.0 2.0 4.39 15.0 1.0 1.0
Before calling E04HEF, the program calls E04YAF and E04YBF to check LSQFUN and LSQHES. It uses 0.5,1.0,1.5 as the initial guess at the position of the minimum.

10.1 Program Text

Program Text (e04hefe.f90)

10.2 Program Data

Program Data (e04hefe.d)

10.3 Program Results

Program Results (e04hefe.r)

E04 Chapter Contents
E04 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


E04HYF : NAG Library, Mark 26

E04 Chapter Contents
E04 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

E04HYF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

E04HYF is an easy-to-use modified Gauss–Newton algorithm for finding an unconstrained minimum of a sum of squares of m nonlinear functions in n variables m≥n. First and second derivatives are required.
It is intended for functions which are continuous and which have continuous first and second derivatives (although it will usually work even if the derivatives have occasional discontinuities).

2 Specification

SUBROUTINE E04HYF ( M, N, LSFUN2, LSHES2, X, FSUMSQ, W, LW, IUSER, RUSER, IFAIL)
INTEGER | M, N, LW, IUSER(*), IFAIL
REAL (KIND=nag_wp) | X(N), FSUMSQ, W(LW), RUSER(*)
EXTERNAL | LSFUN2, LSHES2

3 Description

E04HYF is similar to the subroutine LSSDN2 in the NPL Algorithms Library. It is applicable to problems of the form:
Minimize⁡F x=∑i=1 m fi x 2
where x=x 1,x 2,…,xn T and m≥n. (The functions fi x are often referred to as ‘residuals’.)
You must supply a subroutine to evaluate the residuals and their first derivatives at any point x, and a subroutine to evaluate the elements of the second derivative term of the Hessian matrix of F x.
Before attempting to minimize the sum of squares, the algorithm checks the user-supplied subroutines for consistency. Then, from a starting point supplied by you, a sequence of points is generated which is intended to converge to a local minimum of the sum of squares. These points are generated using estimates of the curvature of F x.

4 References

Gill P E and Murray W (1978) Algorithms for the solution of the nonlinear least squares problem SIAM J. Numer. Anal. 15 977–992

5 Arguments

1:   M – INTEGERInput
2:   N – INTEGERInput
On entry: the number m of residuals, fi x, and the number n of variables, xj.
Constraint: 1≤N≤M.
3:   LSFUN2 – SUBROUTINE, supplied by the user.External Procedure
You must supply this routine to calculate the vector of values fi x and the Jacobian matrix of first derivatives ∂fi ∂xj at any point x. It should be tested separately before being used in conjunction with E04HYF (see the E04 Chapter Introduction).
The specification of LSFUN2 is:
SUBROUTINE LSFUN2 ( M, N, XC, FVEC, FJAC, LDFJAC, IUSER, RUSER)
INTEGER | M, N, LDFJAC, IUSER(*)
REAL (KIND=nag_wp) | XC(N), FVEC(M), FJAC(LDFJAC,N), RUSER(*)
Important: the dimension declaration for FJAC must contain the variable LDFJAC, not an integer constant.
1:   M – INTEGERInput
On entry: m, the numbers of residuals.
2:   N – INTEGERInput
On entry: n, the numbers of variables.
3:   XC N – REAL (KIND=nag_wp) arrayInput
On entry: the point x at which the values of the fi and the ∂fi ∂xj are required.
4:   FVEC M – REAL (KIND=nag_wp) arrayOutput
On exit: FVEC i must be set to the value of fi at the point x, for i=1,2,…,m.
5:   FJAC LDFJACN – REAL (KIND=nag_wp) arrayOutput
On exit: FJAC ij must be set to the value of ∂fi ∂xj at the point x, for i=1,2,…,m and j=1,2,…,n.
6:   LDFJAC – INTEGERInput
On entry: the first dimension of the array FJAC as declared in the (sub)program from which E04HYF is called.
7:   IUSER* – INTEGER arrayUser Workspace
8:   RUSER* – REAL (KIND=nag_wp) arrayUser Workspace
LSFUN2 is called with the arguments IUSER and RUSER as supplied to E04HYF. You are free to use the arrays IUSER and RUSER to supply information to LSFUN2 as an alternative to using COMMON global variables.
LSFUN2 must either be a module subprogram USEd by, or declared as EXTERNAL in, the (sub)program from which E04HYF is called. Arguments denoted as Input must not be changed by this procedure.
4:   LSHES2 – SUBROUTINE, supplied by the user.External Procedure
You must supply this routine to calculate the elements of the symmetric matrix
B x=∑i=1 m fi x Gi x,
at any point x, where Gi x is the Hessian matrix of fi x. It should be tested separately before being used in conjunction with E04HYF (see the E04 Chapter Introduction).
The specification of LSHES2 is:
SUBROUTINE LSHES2 ( M, N, FVEC, XC, B, LB, IUSER, RUSER)
INTEGER | M, N, LB, IUSER(*)
REAL (KIND=nag_wp) | FVEC(M), XC(N), B(LB), RUSER(*)
1:   M – INTEGERInput
On entry: m, the number of residuals.
2:   N – INTEGERInput
On entry: n, the number of residuals.
3:   FVEC M – REAL (KIND=nag_wp) arrayInput
On entry: the value of the residual fi at the point x, for i=1,2,…,m, so that the values of the fi can be used in the calculation of the elements of B.
4:   XC N – REAL (KIND=nag_wp) arrayInput
On entry: the point x at which the elements of B are to be evaluated.
5:   B LB – REAL (KIND=nag_wp) arrayOutput
On exit: must contain the lower triangle of the matrix B x, evaluated at the point x, stored by rows. (The upper triangle is not required because the matrix is symmetric.) More precisely, B j j-1/2+k must contain ∑i=1 m fi ∂2 fi ∂xj∂xk evaluated at the point x, for j=1,2,…,n and k=1,2,…,j.
6:   LB – INTEGERInput
On entry: the length of the array B.
7:   IUSER* – INTEGER arrayUser Workspace
8:   RUSER* – REAL (KIND=nag_wp) arrayUser Workspace
LSHES2 is called with the arguments IUSER and RUSER as supplied to E04HYF. You are free to use the arrays IUSER and RUSER to supply information to LSHES2 as an alternative to using COMMON global variables.
LSHES2 must either be a module subprogram USEd by, or declared as EXTERNAL in, the (sub)program from which E04HYF is called. Arguments denoted as Input must not be changed by this procedure.
5:   X N – REAL (KIND=nag_wp) arrayInput/Output
On entry: X j must be set to a guess at the jth component of the position of the minimum, for j=1,2,…,n. The routine checks LSFUN2 and LSHES2 at the starting point and so is more likely to detect any error in your routines if the initial X j are nonzero and mutually distinct.
On exit: the lowest point found during the calculations. Thus, if IFAIL=0 on exit, X j is the jth component of the position of the minimum.
6:   FSUMSQ – REAL (KIND=nag_wp)Output
On exit: the value of the sum of squares, F x, corresponding to the final point stored in X.
7:   W LW – REAL (KIND=nag_wp) arrayWorkspace
8:   LW – INTEGERInput
On entry: the dimension of the array W as declared in the (sub)program from which E04HYF is called.
Constraints:
  • if N>1, LW≥8×N+2×N×N+2×M×N+3×M;
  • if N=1, LW≥11+5×M.
9:   IUSER* – INTEGER arrayUser Workspace
10:   RUSER* – REAL (KIND=nag_wp) arrayUser Workspace
IUSER and RUSER are not used by E04HYF, but are passed directly to LSFUN2 and LSHES2 and may be used to pass information to these routines as an alternative to using COMMON global variables.
11:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, because for this routine the values of the output arguments may be useful even if IFAIL≠0 on exit, the recommended value is -1. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Note: E04HYF may return useful information for one or more of the following detected errors or warnings.
Errors or warnings detected by the routine:
IFAIL=1
On entry, | N<1,
or | M<N,
or | LW<8×N+2×N×N+2×M×N+3×M, when N>1,
or | LW<11+5×M, when N=1.
IFAIL=2
There have been 50×n calls of LSFUN2, yet the algorithm does not seem to have converged. This may be due to an awkward function or to a poor starting point, so it is worth restarting E04HYF from the final point held in X.
IFAIL=3
The final point does not satisfy the conditions for acceptance as a minimum, but no lower point could be found.
IFAIL=4
An auxiliary routine has been unable to complete a singular value decomposition in a reasonable number of sub-iterations.
IFAIL=5
IFAIL=6
IFAIL=7
IFAIL=8
There is some doubt about whether the point X x found by E04HYF is a minimum of F x. The degree of confidence in the result decreases as IFAIL increases. Thus, when IFAIL=5, it is probable that the final x gives a good estimate of the position of a minimum, but when IFAIL=8 it is very unlikely that the routine has found a minimum.
IFAIL=9
It is very likely that you have made an error in forming the derivatives ∂fi ∂xj in LSFUN2.
IFAIL=10
It is very likely that you have made an error in forming the quantities B jk in LSHES2.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.
If you are not satisfied with the result (e.g., because IFAIL lies between 3 and 8), it is worth restarting the calculations from a different starting point (not the point at which the failure occurred) in order to avoid the region which caused the failure. Repeated failure may indicate some defect in the formulation of the problem.

7 Accuracy

If the problem is reasonably well scaled and a successful exit is made, then, for a computer with a mantissa of t decimals, one would expect to get about t/2-1 decimals accuracy in the components of x and between t-1 (if F x is of order 1 at the minimum) and 2 t-2 (if F x is close to zero at the minimum) decimals accuracy in F x.

8 Parallelism and Performance

E04HYF is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
E04HYF makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The number of iterations required depends on the number of variables, the number of residuals and their behaviour, and the distance of the starting point from the solution. The number of multiplications performed per iteration of E04HYF varies, but for m≫n is approximately n×m 2+O n 3. In addition, each iteration makes at least one call of LSFUN2 and some iterations may call LSHES2. So, unless the residuals and their derivatives can be evaluated very quickly, the run time will be dominated by the time spent in LSFUN2 (and, to a lesser extent, in LSHES2).
Ideally, the problem should be scaled so that the minimum value of the sum of squares is in the range 0,+1 and so that at points a unit distance away from the solution the sum of squares is approximately a unit value greater than at the minimum. It is unlikely that you will be able to follow these recommendations very closely, but it is worth trying (by guesswork), as sensible scaling will reduce the difficulty of the minimization problem, so that E04HYF will take less computer time.
When the sum of squares represents the goodness-of-fit of a nonlinear model to observed data, elements of the variance-covariance matrix of the estimated regression coefficients can be computed by a subsequent call to E04YCF, using information returned in segments of the workspace array W. See E04YCF for further details.

10 Example

This example finds least squares estimates of x 1, x 2 and x 3 in the model
y=x 1+t 1 x 2t 2+x 3t 3
using the 15 sets of data given in the following table.
y t 1 t 2 t 3 0.14 1.0 15.0 1.0 0.18 2.0 14.0 2.0 0.22 3.0 13.0 3.0 0.25 4.0 12.0 4.0 0.29 5.0 11.0 5.0 0.32 6.0 10.0 6.0 0.35 7.0 9.0 7.0 0.39 8.0 8.0 8.0 0.37 9.0 7.0 7.0 0.58 10.0 6.0 6.0 0.73 11.0 5.0 5.0 0.96 12.0 4.0 4.0 1.34 13.0 3.0 3.0 2.10 14.0 2.0 2.0 4.39 15.0 1.0 1.0
The program uses 0.5,1.0,1.5 as the initial guess at the position of the minimum.

10.1 Program Text

Program Text (e04hyfe.f90)

10.2 Program Data

Program Data (e04hyfe.d)

10.3 Program Results

Program Results (e04hyfe.r)

E04 Chapter Contents
E04 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


E04 Chapter Introduction : NAG Library, Mark 26

E04 Chapter Contents
NAG Library Manual

NAG Library Chapter Introduction

E04 – Minimizing or Maximizing a Function

▸▿ Contents

1 Scope of the Chapter
▸▿ 2 Background to the Problems
2.1 Introduction to Mathematical Optimization
▸▿ 2.2 Classification of Optimization Problems
2.2.1 Types of objective functions
2.2.2 Types of constraints
2.2.3 Typical classes of optimization problems
2.2.4 Problem size, dense and sparse problems
2.2.5 Derivative information, smoothness, noise and derivative free optimization (DFO)
2.2.6 Minimization subject to bounds on the objective function
2.2.7 Multi-objective optimization
2.3 Geometric Representation
▸▿ 2.4 Sufficient Conditions for a Solution
2.4.1 Unconstrained minimization
2.4.2 Minimization subject to bounds on the variables
2.4.3 Linearly-constrained minimization
2.4.4 Nonlinearly-constrained minimization
▸▿ 2.5 Background to Optimization Methods
2.5.1 One-dimensional optimization
2.5.2 Methods for unconstrained optimization
2.5.3 Methods for nonlinear least squares problems
2.5.4 Methods for handling constraints
2.5.5 Methods for handling multi-objective optimization
▸▿ 2.6 Scaling
2.6.1 Transformation of variables
2.6.2 Scaling the objective function
2.6.3 Scaling the constraints
▸▿ 2.7 Analysis of Computed Results
2.7.1 Convergence criteria
2.7.2 Checking results
2.7.3 Monitoring progress
2.7.4 Confidence intervals for least squares solutions
▸▿ 3 Recommendations on Choice and Use of Available Routines
3.1 Easy-to-use and Comprehensive Routines
3.2 Thread Safe Routines
3.3 Reverse Communication Routines
3.4 Choosing Between Variant Routines for Some Problems
3.5 NAG Optimization Modelling Suite
3.6 Service Routines
3.7 Function Evaluations at Infeasible Points
3.8 Related Problems
4 Decision Trees
5 Functionality Index
6 Auxiliary Routines Associated with Library Routine Arguments
7 Routines Withdrawn or Scheduled for Withdrawal
8 References

1 Scope of the Chapter

This chapter provides routines for solving various mathematical optimization problems by solvers based on local stopping criteria. The main classes of problems covered in this chapter are:
  • Linear Programming (LP) – dense and sparse;
  • Quadratic Programming (QP) – convex and nonconvex, dense and sparse;
  • Nonlinear Programming (NLP) – dense and sparse, based on active-set SQP methods and interior point method (IPM);
  • Semidefinite Programming (SDP) – both linear matrix inequalities (LMI) and bilinear matrix inequalities (BMI);
  • Derivative Free Optimization (DFO);
  • Least Squares (LSQ), data fitting – linear and nonlinear, constrained and unconstrained.
For a full overview of the functionality offered in this chapter, see Section 5 or the Chapter Contents (Chapter E04).
See also other chapters in the Library relevant to optimization:
  • Chapter E05 contains routines to solve global optimization problems;
  • Chapter H addresses problems arising in operational research and focuses on Mixed Integer Programming (MIP);
  • Chapters F07 and F08 include several routines for linear algebra and in particular unconstrained linear least squares;
  • Chapter E02 focuses on curve and surface fitting, in which linear data fitting in l 1 norm migh be of interest.
This introduction is only a brief guide to the subject of optimization designed for the casual user. It discusses a classification of the optimization problems and presents an overview of the algorithms and their stopping criteria to assist choosing the right solver for a particular problem. Anyone with a difficult or protracted problem to solve will find it beneficial to consult a more detailed text, see Gill et al. (1981), Fletcher (1987) or Nocedal and Wright (1999). If you are unfamiliar with the mathematics of the subject you may find Sections 2.1, 2.2, 2.3, 2.6 and 3 a useful starting point.

2 Background to the Problems

2.1 Introduction to Mathematical Optimization

Mathematical Optimization, also known as Mathematical Programming, refers to the problem of finding values of the inputs from a given set so that a function (called the objective function) is minimized or maximized. The inputs are called decisions variables, primal variables or just variables. The given set from which the decision variables are selected is referred to as a feasible set and might be defined as a domain where constraints expressed as functions of the decision variables hold certain values. Each point of the feasible set is called a feasible point.
A general mathematical formulation of such a problem might be written as
minimize f x subject to x∈F
where x denotes the decision variables, f x the objective function and F the feasibility set. In this chapter we assume that F⊂ℝ n. Since maximization of the objective function f x is equivalent to minimizing -f x, only minimization is considered further in the text. Some routines allow you to specify whether you are solving a minimization or maximization problem, carrying out the required transformation of the objective function in the latter case.
A point x* is said to be a local minimum of a function f if it is feasible (x*∈F) and if f x≥f x* for all x∈F near x*. A point x* is a global minimum if it is a local minimum and f x≥f x* for all feasible x. The solvers in this chapter are based on algorithms which seek only a local minimum, however, many problems (such as convex optimization problems) have only one local minimum which is also the global minimum. In such cases the Chapter E04 solvers find the global minimum. See Chapter E05 for solvers which try to find a global solution even for nonconvex functions.

2.2 Classification of Optimization Problems

There is no single efficient solver for all optimization problems. Therefore it is important to choose a solver which matches the problem and any specific needs as closely as possible. A more generic solver might be applied, however, the performance deprecates in some cases depending on the underlying algorithm.
There are various criteria to help to classify optimization problems into particular categories. The main criteria are as follows:
  • Type of objective function;
  • Type of constraints;
  • Size of the problem;
  • Smoothness of the data and available derivative information.
Each of the criterion is discussed below to give the necessary information to identify the class of the optimization problem. Section 2.5 presents the basic properties of the algorithms and Section 3 advises on the choice of particular routines in the chapter.

2.2.1 Types of objective functions

In general, if there is a structure in the problem the solver should benefit from it. For example, a solver for problems with the sum of squares objective should work better than when this objective is treated as a general nonlinear objective. Therefore it is important to recognize typical types of the objective functions.
An optimization problem which has no objective is equivalent to having a constant zero objective, i.e., f x=0. It is usually called a feasible point problem. The task is to then find any point which satisfies the constraints.
A linear objective function is a function which is linear in all variables and therefore can be represented as
f x= cT x+c 0
where c∈ℝn. Scalar c 0 has no influence on the choice of decision variables x and is usually omitted. It will not be used further in this text.
A quadratic objective function is an extention of a linear function with quadratic terms as follows:
f x= 12 xT Hx+ cT x .
Here H is a real symmetric n×n matrix. In addition, if H is positive semidefinite (all its eigenvalues are non-negative), the objective is convex.
A general nonlinear objective function is any f:ℝn→ℝ without a special structure.
Special consideration is given to the objective function in the form of a sum of squares of functions, such as
f x= ∑i=1 m ri 2 x
where ri:ℝn→ℝ; often called residual functions. This form of the objective plays a key role in data fitting solved as a least squares problem as shown in Section 2.2.3.

2.2.2 Types of constraints

Not all optimization problems have to have constraints. If there are no restrictions on the choice of x except that x∈F=ℝ n, the problem is called unconstrained and thus every point is a feasible point.
Simple bounds on decision variables x∈ℝ n (also known as box constaints or bound constraints) restrict the value of the variables, e.g., x 5≤10. They might be written in a general form as
l xi ≤ xi ≤ u xi , for ​ i=1,…,n
or in the vector notation as
lx ≤x≤ ux
where lx and ux are n-dimensional vectors. Note that lower and upper bounds are specified for all the variables. By conceptually allowing l xi=-∞ and u xi=+∞ or l xi=u xi full generality in various types of constraints is allowed, such as unconstrained variables, one-sided inequalities, ranges or equalities (fixing the variable).
The same format of bounds is adopted to linear and nonlinear constraints in the whole chapter. Note that for the purpose of passing infinite bounds to the routines, all values above a certain threshold (typically 1020) are treated as +∞.
Linear constraints are defined as constraint functions that are linear in all of their variables, e.g., 3 x 1+2 x 2≥4. They can be stated in a matrix form as
lB ≤Bx≤ uB
where B is a general mB×n rectangular matrix and lB and uB are mB-dimensional vectors. Each row of B represents linear coefficients of one linear constraint. The same rules for bounds apply as in the simple bounds case.
Although the bounds on xi could be included in the definition of linear constraints, it is recommended to distinguish between them for reasons of computational efficiency as most of the solvers treat simple bounds explicitly.
A set of mg nonlinear constraints may be defined in terms of a nonlinear function g:ℝn→ℝ mg and the bounds lg and ug which follow the same format as simple bounds and linear constraints:
lg≤g x≤ug .
Although the linear constraints could be included in the definition of nonlinear constraints, again we prefer to distinguish between them for reasons of computational efficiency.
A matrix constraint (or matrix inequality) is a constraint on eigenvalues of a matrix operator. More precisely, let 𝕊m denote the space of real symmetric matrices m by m and let A be a matrix operator A:ℝn→𝕊m, i.e., it assigns a symmetric matrix A x for each x. The matrix constraint can be expressed as
A x⪰0
where the inequality S⪰0 for S∈𝕊m is meant in the eigenvalue sense, namely all eigenvalues of the matrix S should be non-negative (the matrix should be positive semidefinite).
There are two types of matrix constraints allowed in the current mark of the Library. The first is linear matrix inequality (LMI) formulated as
A x= ∑ i=1 n xi Ai - A 0 ⪰ 0
and the second one, bilinear matrix inequality (BMI), stated as
A x= ∑ i,j=1 n xi xj Q ij + ∑ i=1 n xi Ai - A 0 ⪰ 0 .
Here all matrices Ai, Q ij are given real symmetric matrices of the same dimension. Note that the latter type is in fact quadratic in x, nevertheless, it is referred to as bilinear for historical reasons.

2.2.3 Typical classes of optimization problems

Specific combinations of the types of the objective functions and constraints give rise to various classes of optimization problems. The common ones are presented below. It is always advisable to consider the closest formulation which covers your problem when choosing the solver. For more information see classical texts such as Dantzig (1963), Gill et al. (1981), Fletcher (1987), Nocedal and Wright (1999) or Chvátal (1983).
A Linear Programming (LP) problem is a problem with a linear objective function, linear constraints and simple bounds. It can be written as follows:
minimize x∈ℝ n cT x subject to lB≤Bx≤uB lx≤x≤ux
Quadratic Programming (QP) problems optimize a quadratic objective function over a set given by linear constraints and simple bounds. Depending on the convexity of the objective function, we can distinguish between convex and nonconvex (or general) QP.
minimize x∈ℝ n 12 xT Hx + cT x subject to lB≤Bx≤uB lx≤x≤ux
Nonlinear Programming (NLP) problems allow a general nonlinear objective function f x and any of the nonlinear, linear or bound constraints. Special cases when some (or all) of the constraints are missing are termed as unconstrained, bound-constrained or linearly-constrained nonlinear programming and might have a specific solver as some algorithms take special provision for each of the constraint type. Problems with a linear or quadratic objective and nonlinear constraints should be still solved as general NLPs.
minimize x∈ℝ n f x subject to lg≤g x≤ug lB≤Bx≤uB lx≤x≤ux
Semidefinite Programming (SDP) typically refers to linear semidefinite programming thus a problem with a linear objective function, linear constraints and linear matrix inequalities:
minimize x∈ℝ n cT x subject to   ∑ i=1 n xi Aik - A 0 k ⪰ 0 ,  k=1,…,mA lB≤Bx≤uB lx≤x≤ux
This problem can be extended with a quadratic objective and bilinear (in fact quadratic) matrix inequalities. We refer to it as a semidefinite programming problem with bilinear matrix inequalities (BMI-SDP):
minimize x∈ℝ n 12 xT Hx + cT x subject to   ∑ i,j=1 n xi xj Q ij k + ∑ i=1 n xi Aik - A 0 k ⪰ 0 ,  k=1,…,mA lB≤Bx≤uB lx≤x≤ux
A least squares (LSQ) problem is a problem where the objective function in the form of sum of squares is minimized subject to usual constraints. If the residual functions ri x are linear or nonlinear, the problem is known as linear or nonlinear least squares, respectively. Not all types of the constraints need to be present which brings up special cases of unconstrained, bound-constrained or linearly-constrained least squares problems as in NLP .
minimize x∈ℝ n ∑i=1 m ri 2 x subject to lg≤g x≤ug lB≤Bx≤uB lx≤x≤ux
This form of the problem is very common in data fitting as demonstrated on the following example. Let us consider a process that is observed at times ti and measured with results yi, for i=1,2,…,m. Furthermore, the process is assumed to behave according to a model ϕ t;x where x are parameters of the model. Given the fact that the measurements might be inaccurate and the process might not exactly follow the model, it is beneficial to find model parameters x so that the error of the fit of the model to the measurements is minimized. This can be formulated as an optimization problem in which x are decision variables and the objective function is the sum of squared errors of the fit at each individual measurement, thus:
minimize x∈ℝ n ∑i=1 m ri 2 x where ri x = ϕ ti;x -yi

2.2.4 Problem size, dense and sparse problems

The size of the optimization problem plays an important role in the choice of the solver. The size is usually understood to be the number of variables n and the number (and the type) of the constraints. Depending on the size of the problem we talk about small-scale, medium-scale or large-scale problems.
It is often more practical to look at the data and its structure rather than just the size of the problem. Typically in a large-scale problem not all variables interact with everything else. It is natural that only a small portion of the constraints (if any) involves all variables and the majority of the constraints depends only on small different subsets of the variables. This creates many explicit zeros in the data representation which it is beneficial to capture and pass to the solver. In such a case the problem is referred to as sparse. The data representation usually has the form of a sparse matrix which defines the linear constraint matrix B, Jacobian matrix of the nonlinear constraints gi or the Hessian of the objective H. Common sparse matrix formats are used, such as coordinate storage (CS) and compressed column storage (CCS) (see Section 2.1 in the F11 Chapter Introduction).
The counterpart to a sparse problem is a dense problem in which the matrices are stored in general full format and no structure is assumed or exploited. Whereas passing a dense problem to a sparse solver presents typically only a small overhead, calling a dense solver on a large-scale sparse problem is ill-advised; it leads to a significant performance degradation and memory overuse.

2.2.5 Derivative information, smoothness, noise and derivative free optimization (DFO)

Most of the classical optimization algorithms rely heavily on derivative information. It plays a key role in necessary and sufficient conditions (see Section 2.4) and in the computation of the search direction at each iteration (see Section 2.5). Therefore it is important that accurate derivatives of the nonlinear objective and nonlinear constraints are provided whenever possible.
Unless stated otherwise, it is assumed that the nonlinear functions are sufficiently smooth. The solvers will usually solve optimization problems even if there are isolated discontinuities away from the solution, however, it should always be considered if an alternative smooth representation of the problem exists. A typical example is an absolute value xi which does not have a first derivative for xi=0. Nevertheless, it can sometimes be transformed as
xi= xi+- xi- , xi= xi++ xi- , where xi+ , ​ xi- ≥0
which avoids the discontinuity of the first derivative. If many discontinuities are present, alternative methods need to be applied such as E04CBF or stochastic algorithms in Chapter E05, E05SAF or E05SBF.
The vector of first partial derivatives of a function is called the gradient vector, i.e.,
∇f x = ∂f x ∂x 1 , ∂f x ∂x 2 ,…, ∂f x ∂xn T ,
the matrix of second partial derivatives is termed the Hessian matrix, i.e.,
∇2 f x = ∂2 f x ∂xi∂xj i,j=1,…,n
and the matrix of first partial derivatives of the vector-valued function f:ℝn→ℝm is known as the Jacobian matrix:
J x = ∂fi x ∂xj i=1,…,m,j=1,…,n .
If the function is smooth and the derivative is unavailable, it is possible to approximate it by finite differences, a change in function values in response to small perturbations of the variables. Many routines in the Library estimate missing elements of the gradients automatically this way. The choice of the size of the perturbations strongly affects the quality of the approximation. Too small perturbations might spoil the approximation due to the rounding errors in floating-point arithmetic and too big reduce the match of the finite differences and the derivative (see E04XAF/E04XAA for optimal balance of the factors). In addition, finite differences are very sensitive to the accuracy of f x. They might be unreliable or fail completely if the function evaluation is inaccurate or noisy such as when f x is a result of a stochastic simulation or an approximate solution of a PDE.
Derivative free optimization (DFO) represents an alternative to derivative-based optimization algorithms. DFO solvers neither rely on derivative information nor approximate it by finite differences. They sample function evaluations across the domain to determine a new iteration point (for example, by a quadratic model through the sampled points). They are therefore less exposed to the relative error of the noise of the function because the sample points are never too close to each other to take the error into account. DFO might be useful even if the finite differences can be computed as the number of function evaluations is lower. This is particularly beneficial for problems where the evaluations of f are expensive. DFO solvers tend to exhibit a faster initial progress to the solution, however, they typically cannot achieve high-accurate solutions.

2.2.6 Minimization subject to bounds on the objective function

In all of the above problem categories it is assumed that
a≤f x≤b
where a=-∞ and b=+∞. Problems in which a and/or b are finite can be solved by adding an extra constraint of the appropriate type (i.e., linear or nonlinear) depending on the form of f x. Further advice is given in Section 3.7.

2.2.7 Multi-objective optimization

Sometimes a problem may have two or more objective functions which are to be optimized at the same time. Such problems are called multi-objective, multi-criteria or multi-attribute optimization. If the constraints are linear and the objectives are all linear then the terminology goal programming is also used.
Although there is no routine dealing with this type of problems explicitly in this mark of the Library, techniques used in this chapter and in Chapter E05 may be employed to address such problems, see Section 2.5.5.

2.3 Geometric Representation

To illustrate the nature of optimization problems it is useful to consider the following example in two dimensions:
f x = e x 1 4 x 12 + 2 x 22 + 4 x 1 x 2+2 x 2+1 .
(This function is used as the example function in the documentation for the unconstrained routines.)
Figure 1
Figure 1 is a contour diagram of f x. The contours labelled F 0 , F 1 ,…, F 4 are isovalue contours, or lines along which the function f x takes specific constant values. The point x* = 12 , -1 T is a local unconstrained minimum, that is, the value of f x* (=0) is less than at all the neighbouring points. A function may have several such minima. The point xs is said to be a saddle point because it is a minimum along the line AB, but a maximum along CD.
If we add the constraint x 1≥0 (a simple bound) to the problem of minimizing f x, the solution remains unaltered. In Figure 1 this constraint is represented by the straight line passing through x 1=0, and the shading on the line indicates the unacceptable region (i.e., x 1<0).
If we add the nonlinear constraint g 1 x : x 1+ x 2- x 1 x 2- 32≥0 , represented by the curved shaded line in Figure 1, then x* is not a feasible point because g 1 x*<0. The solution of the new constrained problem is xb≃ 1.1825,-1.7397 T , the feasible point with the smallest function value (where f xb≃3.0607).

2.4 Sufficient Conditions for a Solution

All nonlinear functions will be assumed to have continuous second derivatives in the neighbourhood of the solution.

2.4.1 Unconstrained minimization

The following conditions are sufficient for the point x* to be an unconstrained local minimum of f x:
(i) | ∇f x*=0; and
(ii) | ∇2 f x* is positive definite,
where · denotes the Euclidean norm.

2.4.2 Minimization subject to bounds on the variables

At the solution of a bounds-constrained problem, variables which are not on their bounds are termed free variables. If it is known in advance which variables are on their bounds at the solution, the problem can be solved as an unconstrained problem in just the free variables; thus, the sufficient conditions for a solution are similar to those for the unconstrained case, applied only to the free variables.
Sufficient conditions for a feasible point x* to be the solution of a bounds-constrained problem are as follows:
(i) | g-x*=0; and
(ii) | G-x* is positive definite; and
(iii) | ∂ ∂xj f x*<0,xj=uj; ∂ ∂xj f x*>0,xj=lj,
where g-x is the gradient of f x with respect to the free variables, and G-x is the Hessian matrix of f x with respect to the free variables. The extra condition (iii) ensures that f x cannot be reduced by moving off one or more of the bounds.

2.4.3 Linearly-constrained minimization

For the sake of simplicity, the following description does not include a specific treatment of bounds or range constraints, since the results for general linear inequality constraints can be applied directly to these cases.
At a solution x*, of a linearly-constrained problem, the constraints which hold as equalities are called the active or binding constraints. Assume that there are t active constraints at the solution x*, and let A^ denote the matrix whose columns are the columns of A corresponding to the active constraints, with b^ the vector similarly obtained from b; then
A^Tx*=b^.
The matrix Z is defined as an n×n-t matrix satisfying:
A^T Z=0; ZT Z=I.
The columns of Z form an orthogonal basis for the set of vectors orthogonal to the columns of A^.
Define
  • gZ x=ZT∇f x, the projected gradient vector of f x;
  • GZ x=ZT∇2 f x Z, the projected Hessian matrix of f x.
At the solution of a linearly-constrained problem, the projected gradient vector must be zero, which implies that the gradient vector ∇f x* can be written as a linear combination of the columns of A^, i.e., ∇f x*=∑i=1 t λi*a^i=A^λ*. The scalar λi* is defined as the Lagrange multiplier corresponding to the ith active constraint. A simple interpretation of the ith Lagrange multiplier is that it gives the gradient of f x along the ith active constraint normal; a convenient definition of the Lagrange multiplier vector (although not a recommended method for computation) is:
λ*=A^T A^-1A^T∇f x*.
Sufficient conditions for x* to be the solution of a linearly-constrained problem are:
(i) | x* is feasible, and A^Tx*=b^; and
(ii) | gZ x*=0, or equivalently, ∇f x*=A^λ*; and
(iii) | GZ x* is positive definite; and
(iv) | λi*>0 if λi* corresponds to a constraint a^iT x* ≥ b^i ; λi*<0 if λi* corresponds to a constraint a^iT x* ≤ b^i . The sign of λi* is immaterial for equality constraints, which by definition are always active.

2.4.4 Nonlinearly-constrained minimization

For nonlinearly-constrained problems, much of the terminology is defined exactly as in the linearly-constrained case. To simplify the notation, let us assume that all nonlinear constraints are in the form c x≥0. The set of active constraints at x again means the set of constraints that hold as equalities at x, with corresponding definitions of c^ and A^: the vector c^x contains the active constraint functions, and the columns of A^x are the gradient vectors of the active constraints. As before, Z is defined in terms of A^x as a matrix such that:
A^T Z=0; ZT Z=I
where the dependence on x has been suppressed for compactness.
The projected gradient vector gZ x is the vector ZT∇f x. At the solution x* of a nonlinearly-constrained problem, the projected gradient must be zero, which implies the existence of Lagrange multipliers corresponding to the active constraints, i.e., ∇f x*=A^x*λ*.
The Lagrangian function is given by:
L x,λ=f x-λT c^x.
We define gL x as the gradient of the Lagrangian function; GL x as its Hessian matrix, and G^L x as its projected Hessian matrix, i.e., G^L=ZT GL Z.
Sufficient conditions for x* to be the solution of a nonlinearly-constrained problem are:
(i) | x* is feasible, and c^x*=0; and
(ii) | gZ x*=0, or, equivalently, ∇f x*=A^x*λ*; and
(iii) | G^L x* is positive definite; and
(iv) | λi*>0 if λi* corresponds to a constraint of the form c^i≥0. The sign of λi* is immaterial for equality constraints, which by definition are always active.
Note that condition (ii) implies that the projected gradient of the Lagrangian function must also be zero at x*, since the application of ZT annihilates the matrix A^x*.

2.5 Background to Optimization Methods

All the algorithms contained in this chapter generate an iterative sequence x k that converges to the solution x* in the limit, except for some special problem categories (i.e., linear and quadratic programming). To terminate computation of the sequence, a convergence test is performed to determine whether the current estimate of the solution is an adequate approximation. The convergence tests are discussed in Section 2.7.
Most of the methods construct a sequence x k satisfying:
x k+1 =x k +α k p k ,
where the vector p k is termed the direction of search, and α k is the steplength. The steplength α k is chosen so that f x k+1 <f x k and is computed using one of the techniques for one-dimensional optimization referred to in Section 2.5.1.

2.5.1 One-dimensional optimization

The Library contains two special routines for minimizing a function of a single variable. Both routines are based on safeguarded polynomial approximation. One routine requires function evaluations only and fits a quadratic polynomial whilst the other requires function and gradient evaluations and fits a cubic polynomial. See Section 4.1 of Gill et al. (1981).

2.5.2 Methods for unconstrained optimization

The distinctions between methods arise primarily from the need to use varying levels of information about derivatives of f x in defining the search direction. We describe three basic approaches to unconstrained problems, which may be extended to other problem categories. Since a full description of the methods would fill several volumes, the discussion here can do little more than allude to the processes involved, and direct you to other sources for a full explanation.
(a) Newton-type Methods (Modified Newton Methods)
Newton-type methods use the Hessian matrix ∇2 f x k , or its finite difference approximation , to define the search direction. The routines in the Library either require a subroutine that computes the elements of the Hessian directly, or they approximate them by finite differences.
Newton-type methods are the most powerful methods available for general problems and will find the minimum of a quadratic function in one iteration. See Sections 4.4 and 4.5.1 of Gill et al. (1981).
(b) Quasi-Newton Methods
Quasi-Newton methods approximate the Hessian ∇2 f x k by a matrix B k which is modified at each iteration to include information obtained about the curvature of f along the current search direction p k. Although not as robust as Newton-type methods, quasi-Newton methods can be more efficient because the Hessian is not computed directly, or approximated by finite differences. Quasi-Newton methods minimize a quadratic function in n iterations, where n is the number of variables. See Section 4.5.2 of Gill et al. (1981).
(c) Conjugate-gradient Methods
Unlike Newton-type and quasi-Newton methods, conjugate-gradient methods do not require the storage of an n by n matrix and so are ideally suited to solve large problems. Conjugate-gradient type methods are not usually as reliable or efficient as Newton-type, or quasi-Newton methods. See Section 4.8.3 of Gill et al. (1981).

2.5.3 Methods for nonlinear least squares problems

These methods are similar to those for general nonlinear optimization, but exploit the special structure of the Hessian matrix to give improved computational efficiency.
Since
f x=∑i=1 m ri 2 x
the Hessian matrix is of the form
∇2 f x = 2 J x T J x + ∑i=1 m ri x ∇2 ri x ,
where J x is the Jacobian matrix of r x.
In the neighbourhood of the solution, r x is often small compared to J x T J x (for example, when r x represents the goodness-of-fit of a nonlinear model to observed data). In such cases, 2 J x T J x may be an adequate approximation to ∇2 f x, thereby avoiding the need to compute or approximate second derivatives of ri x. See Section 4.7 of Gill et al. (1981).

2.5.4 Methods for handling constraints

Bounds on the variables are dealt with by fixing some of the variables on their bounds and adjusting the remaining free variables to minimize the function. By examining estimates of the Lagrange multipliers it is possible to adjust the set of variables fixed on their bounds so that eventually the bounds active at the solution should be correctly identified. This type of method is called an active-set method. One feature of such a method is that, given an initial feasible point, all approximations x k are feasible. This approach can be extended to general linear constraints. At a point, x, the set of constraints which hold as equalities being used to predict, or approximate, the set of active constraints is called the working set.
Nonlinear constraints are more difficult to handle. If at all possible, it is usually beneficial to avoid including nonlinear constraints during the formulation of the problem. The methods currently implemented in the Library handle nonlinearly constrained problems by transforming them into a sequence of quadratic programming problems. A feature of such methods is that x k is not guaranteed to be feasible except in the limit, and this is certainly true of the routines currently in the Library. See Chapter 6, particularly Sections 6.4 and 6.5, of Gill et al. (1981).
Anyone interested in a detailed description of methods for optimization should consult the references.

2.5.5 Methods for handling multi-objective optimization

Suppose we have objective functions fi x, i>1, all of which we need to minimize at the same time. There are two main approaches to this problem:
(a) Combine the individual objectives into one composite objective. Typically this might be a weighted sum of the objectives, e.g.,
w 1 f 1 x + w 2 f 2 x + ⋯ + wn fn x
Here you choose the weights to express the relative importance of the corresponding objective. Ideally each of the fi x should be of comparable size at a solution.
(b) Order the objectives in order of importance. Suppose fi are ordered such that fi x is more important than f i+1 x, for i=1,2,…,n-1. Then in the lexicographical approach to multi-objective optimization a sequence of subproblems are solved. Firstly solve the problem for objective function f 1 x and denote by r 1 the value of this minimum. If i-1 subproblems have been solved with results r i-1 then subproblem i becomes min fi x subject to rk≤fk x≤rk, for k=1,2,…,i-1 plus the other constraints.
Clearly the bounds on fk might be relaxed at your discretion.
In general, if NAG routines from the Chapter E04 are used then only local minima are found. This means that a better solution to an individual objective might be found without worsening the optimal solutions to the other objectives. Ideally you seek a Pareto solution; one in which an improvement in one objective can only be achieved by a worsening of another objective.
To obtain a Pareto solution routines from Chapter E05 might be used or, alternatively, a pragmatic attempt to derive a global minimum might be tried (see E05UCF). In this approach a variety of different minima are computed for each subproblem by starting from a range of different starting points. The best solution achieved is taken to be the global minimum. The more starting points chosen the greater confidence you might have in the computed global minimum.

2.6 Scaling

Scaling (in a broadly defined sense) often has a significant influence on the performance of optimization methods.
Since convergence tolerances and other criteria are necessarily based on an implicit definition of ‘small’ and ‘large’, problems with unusual or unbalanced scaling may cause difficulties for some algorithms.
Although there are currently no user-callable scaling routines in the Library, scaling can be performed automatically in routines which solve sparse LP, QP or NLP problems and in some dense solver routines. Such routines have an optional parameter ‘Scale Option’ which can be set by the user; see individual routine documents for details.
The following sections present some general comments on problem scaling.

2.6.1 Transformation of variables

One method of scaling is to transform the variables from their original representation, which may reflect the physical nature of the problem, to variables that have certain desirable properties in terms of optimization. It is generally helpful for the following conditions to be satisfied:
(i) | the variables are all of similar magnitude in the region of interest;
(ii) | a fixed change in any of the variables results in similar changes in f x. Ideally, a unit change in any variable produces a unit change in f x;
(iii) | the variables are transformed so as to avoid cancellation error in the evaluation of f x.
Normally, you should restrict yourself to linear transformations of variables, although occasionally nonlinear transformations are possible. The most common such transformation (and often the most appropriate) is of the form
xnew=D xold,
where D is a diagonal matrix with constant coefficients. Our experience suggests that more use should be made of the transformation
xnew=D xold+v,
where v is a constant vector.
Consider, for example, a problem in which the variable x 3 represents the position of the peak of a Gaussian curve to be fitted to data for which the extreme values are 150 and 170; therefore x 3 is known to lie in the range 150–170. One possible scaling would be to define a new variable x-3, given by
x-3=x 3 170.
A better transformation, however, is given by defining x-3 as
x-3=x 3-160 10.
Frequently, an improvement in the accuracy of evaluation of f x can result if the variables are scaled before the routines to evaluate f x are coded. For instance, in the above problem just mentioned of Gaussian curve-fitting, x 3 may always occur in terms of the form x 3-xm, where xm is a constant representing the mean peak position.

2.6.2 Scaling the objective function

The objective function has already been mentioned in the discussion of scaling the variables. The solution of a given problem is unaltered if f x is multiplied by a positive constant, or if a constant value is added to f x. It is generally preferable for the objective function to be of the order of unity in the region of interest; thus, if in the original formulation f x is always of the order of 10+5 (say), then the value of f x should be multiplied by 10-5 when evaluating the function within an optimization routine. If a constant is added or subtracted in the computation of f x, usually it should be omitted, i.e., it is better to formulate f x as x 12+x 22 rather than as x 12+x 22+1000 or even x 12+x 22+1. The inclusion of such a constant in the calculation of f x can result in a loss of significant figures.

2.6.3 Scaling the constraints

A ‘well scaled’ set of constraints has two main properties. Firstly, each constraint should be well-conditioned with respect to perturbations of the variables. Secondly, the constraints should be balanced with respect to each other, i.e., all the constraints should have ‘equal weight’ in the solution process.
The solution of a linearly- or nonlinearly-constrained problem is unaltered if the ith constraint is multiplied by a positive weight wi. At the approximation of the solution determined by an active-set solver, any active linear constraints will (in general) be satisfied ‘exactly’ (i.e., to within the tolerance defined by machine precision) if they have been properly scaled. This is in contrast to any active nonlinear constraints, which will not (in general) be satisfied ‘exactly’ but will have ‘small’ values (for example, g^1 x*=10-8, g^2 x*=-10 -6, and so on). In general, this discrepancy will be minimized if the constraints are weighted so that a unit change in x produces a similar change in each constraint.
A second reason for introducing weights is related to the effect of the size of the constraints on the Lagrange multiplier estimates and, consequently, on the active-set strategy. This means that different sets of weights may cause an algorithm to produce different sequences of iterates. Additional discussion is given in Gill et al. (1981).

2.7 Analysis of Computed Results

2.7.1 Convergence criteria

The convergence criteria inevitably vary from routine to routine, since in some cases more information is available to be checked (for example, is the Hessian matrix positive definite?), and different checks need to be made for different problem categories (for example, in constrained minimization it is necessary to verify whether a trial solution is feasible). Nonetheless, the underlying principles of the various criteria are the same; in non-mathematical terms, they are:
(i) | is the sequence x k converging?
(ii) | is the sequence f k converging?
(iii) | are the necessary and sufficient conditions for the solution satisfied?
The decision as to whether a sequence is converging is necessarily speculative. The criterion used in the present routines is to assume convergence if the relative change occurring between two successive iterations is less than some prescribed quantity. Criterion (iii) is the most reliable but often the conditions cannot be checked fully because not all the required information may be available.

2.7.2 Checking results

Little a priori guidance can be given as to the quality of the solution found by a nonlinear optimization algorithm, since no guarantees can be given that the methods will not fail. Therefore, you should always check the computed solution even if the routine reports success. Frequently a ‘solution’ may have been found even when the routine does not report a success. The reason for this apparent contradiction is that the routine needs to assess the accuracy of the solution. This assessment is not an exact process and consequently may be unduly pessimistic. Any ‘solution’ is in general only an approximation to the exact solution, and it is possible that the accuracy you have specified is too stringent.
Further confirmation can be sought by trying to check whether or not convergence tests are almost satisfied, or whether or not some of the sufficient conditions are nearly satisfied. When it is thought that a routine has returned a nonzero value of IFAIL only because the requirements for ‘success’ were too stringent it may be worth restarting with increased convergence tolerances.
For constrained problems, check whether the solution returned is feasible, or nearly feasible; if not, the solution returned is not an adequate solution.
Confidence in a solution may be increased by resolving the problem with a different initial approximation to the solution. See Section 8.3 of Gill et al. (1981) for further information.

2.7.3 Monitoring progress

Many of the routines in the chapter have facilities to allow you to monitor the progress of the minimization process, and you are encouraged to make use of these facilities. Monitoring information can be a great aid in assessing whether or not a satisfactory solution has been obtained, and in indicating difficulties in the minimization problem or in the ability of the routine to cope with the problem.
The behaviour of the function, the estimated solution and first derivatives can help in deciding whether a solution is acceptable and what to do in the event of a return with a nonzero value of IFAIL.

2.7.4 Confidence intervals for least squares solutions

When estimates of the parameters in a nonlinear least squares problem have been found, it may be necessary to estimate the variances of the parameters and the fitted function. These can be calculated from the Hessian of the objective f x at the solution.
In many least squares problems, the Hessian is adequately approximated at the solution by G=2 JT J (see Section 2.5.3). The Jacobian, J, or a factorization of J is returned by all the comprehensive least squares routines and, in addition, a routine is available in the Library to estimate variances of the parameters following the use of most of the nonlinear least squares routines, in the case that G=2 JT J is an adequate approximation.
Let H be the inverse of G, and S be the sum of squares, both calculated at the solution x-; an unbiased estimate of the variance of the ith parameter xi is
var⁡x-i=2 S m-n H ii
and an unbiased estimate of the covariance of x-i and x-j is
covar x-i,x-j=2 S m-n H ij.
If x* is the true solution, then the 100 1-β% confidence interval on x- is
x-i-var⁡x-i. t 1-β/2,m-n<xi*<x-i+var⁡x-i.t 1-β/2,m-n,  i=1,2,…,n
where t 1-β/2,m-n is the 100 1-β/2 percentage point of the t-distribution with m-n degrees of freedom.
In the majority of problems, the residuals ri, for i=1,2,…,m, contain the difference between the values of a model function ϕ z,x calculated for m different values of the independent variable z, and the corresponding observed values at these points. The minimization process determines the parameters, or constants x, of the fitted function ϕ z,x. For any value, z-, of the independent variable z, an unbiased estimate of the variance of ϕ is
var⁡ϕ=2 S m-n ∑i=1 n ∑j=1 n ∂ϕ ∂xi z- ∂ϕ ∂xj z- H ij.
The 100 1-β% confidence interval on f at the point z- is
ϕ z-,x--var⁡ϕ.t β/2,m-n<ϕ z-,x*<ϕ z-,x-+var⁡ϕ.t β/2,m-n.
For further details on the analysis of least squares solutions see Bard (1974) and Wolberg (1967).

3 Recommendations on Choice and Use of Available Routines

The choice of routine depends on several factors: the type of problem (unconstrained, etc.); the level of derivative information available (function values only, etc.); your experience (there are easy-to-use versions of some routines); whether or not a problem is sparse; whether or not the routine is to be used in a multithreaded environment; and whether computational time has a high priority. Not all choices are catered for in the current version of the Library.

3.1 Easy-to-use and Comprehensive Routines

Many routines appear in the Library in two forms: a comprehensive form and an easy-to-use form. The objective in the easy-to-use forms is to make the routine simple to use by including in the calling sequence only those arguments absolutely essential to the definition of the problem, as opposed to arguments relevant to the solution method. If you are an experienced user the comprehensive routines have additional arguments which enable you to improve their efficiency by ‘tuning’ the method to a particular problem. If you are a casual or inexperienced user, this feature is of little value and may in some cases cause a failure because of a poor choice of some arguments.
In the easy-to-use routines, these extra arguments are determined either by fixing them at a known safe and reasonably efficient value, or by an auxiliary routine which generates a ‘good’ value automatically.
For routines introduced since Mark 12 of the Library a different approach has been adopted towards the choice of easy-to-use and comprehensive routines. The optimization routine has an easy-to-use argument list, but additional arguments may be changed from their default values by calling an ‘option’ setting routine before the call to the main optimization routine. This approach has the advantages of allowing the options to be given in the form of keywords and requiring only those options that are to be different from their default values to be set.

3.2 Thread Safe Routines

Many of the routines in this chapter come in pairs, with each routine in the pair having exactly the same functionality, except that one of them has additional arguments in order to make it safe for use in multithreaded applications. The routine that is safe for use in multithreaded applicatons has an ‘A’ as the last character in the name, in place of the usual ‘F’.
An example of such a pair is E04ABA and E04ABF.

3.3 Reverse Communication Routines

Most of the routines in this chapter are called just once in order to compute the minimum of a given objective function subject to a set of constraints on the variables. The objective function and nonlinear constraints (if any) are specified by you and written as subroutines to a very rigid format described in the relevant routine document.
This chapter also contains a pair of reverse communication routines, E04UFF/E04UFA, which solve dense NLP problems using a sequential quadratic programming method. These may be convenient to use when the minimization routine is being called from a computer language which does not fully support procedure arguments in a way that is compatible with the Library. See Section 3.3.3 in How to Use the NAG Library and its Documentation for more information about reverse communication routines.

3.4 Choosing Between Variant Routines for Some Problems

As evidenced by the wide variety of routines available in Chapter E04, it is clear that no single algorithm can solve all optimization problems. It is important to try to match the problem to the most suitable routine, and that is what the decision trees in Section 4 help to do.
Sometimes in Chapter E04 more than one routine is available to solve precisely the same minimization problem. Thus, for example, the general nonlinear programming routines E04UCF/E04UCA and E04WDF are based on similar methods. Experience shows that although both routines can usually solve the same problem and get similar results, sometimes one routine will be faster, sometimes one might find a different local minimum to the other, or, in difficult cases, one routine may obtain a solution when the other one fails.
After using one of these routines, if the results obtained are unacceptable for some reason, it may be worthwhile trying the other routine instead. In the absence of any other information, in the first instance you are recommended to try using E04UCF/E04UCA, and if that proves unsatisfactory, try using E04WDF. Although the algorithms used are very similar, the two routines each have slightly different optional parameters which may allow the course of the computation to be altered in different ways.
Other pairs of routines which solve the same kind of problem are E04NQF (recommended first choice) or E04NKF/E04NKA, for sparse quadratic or linear programming problems, and E04VHF (recommended) or E04UGF/E04UGA, for sparse nonlinear programming. In these cases the argument lists are not so similar as E04UCF/E04UCA or E04WDF, but the same considerations apply.

3.5 NAG Optimization Modelling Suite

Mark 26 of the Library introduced NAG optimization modelling suite, a suite of routines which allows you to define and solve various optimization problems in a uniform manner. The first key feature of the suite is that the definition of the optimization problem and the call to the solver have been separated so it is possible to set up a problem in the same way for different solvers. The second feature is that the problem representation is built up from basic components (for example, a QP problem is composed of a quadratic objective, simple bounds and linear constraints), therefore different types of problems reuse the same routines for their common parts.
A connecting element to all routines in the suite is a handle, a pointer to an internal data structure, which is passed among the routines. It holds all infomation about the problem, the solution and the solver. Each handle should go through four stages in its life: initialization, problem formulation, problem solution and deallocation.
The initialization is performed by E04RAF which creates an empty problem with n decision variables. A call to E04RZF marks the end of the life of the handle as it deallocates all the allocated memory and data within the handle and detroys the handle itself. After the initialization, the objective may be defined as one of the following:
  • E04REF – a linear objective as a dense vector;
  • E04RFF – a quadratic objective or a spare linear objective;
  • E04RGF – a nonlinear objective function.
The routines for constraint definition are
  • E04RHF – simple bounds;
  • E04RJF – linear constraints;
  • E04RKF – nonlinear constraints;
  • E04RLF – second derivatives for the objective and/or constraints;
  • E04RNF – linear matrix inequalities;
  • E04RPF – quadratic terms for bilinear matrix inequalities.
These routines may be called in an arbitrary order, however, a call to E04RNF must precede a call to E04RPF for the matrix inequalities with bilinear terms and the nonlinear objective or constraints (E04RGF or E04RKF) must precede the definition of the second derivatives by E04RLF. For further details please refer to the documentation of the individual routines.
The suite also includes the following service routines:
  • E04RYF – query/printing routine;
  • E04ZMF – supply an optional parameter from a character string;
  • E04ZPF – supply one or more optional parameters from a file;
  • E04ZNF – get the settings of an optional parameter.
When the problem is fully formulated, the handle can be passed to a solver which is compatible with the defined problem. At the current mark of the Library the NAG optimization modelling suite comprises of E04STF and E04SVF. The solver indicates by an error flag if it cannot deal with the given formulation. A diagram of the life cycle of the handle is depicted in Figure 2.
Figure 2

3.6 Service Routines

One of the most common errors in the use of optimization routines is that user-supplied subroutines do not evaluate the relevant partial derivatives correctly. Because exact gradient information normally enhances efficiency in all areas of optimization, you are encouraged to provide analytical derivatives whenever possible. However, mistakes in the computation of derivatives can result in serious and obscure run-time errors. Consequently, service routines are provided to perform an elementary check on the gradients you supplied. These routines are inexpensive to use in terms of the number of calls they require to user-supplied subroutines.
The appropriate checking routines are as follows:
Minimization routine | Checking routine(s)
E04KDF | E04HCF
E04LBF | E04HCF and E04HDF
E04GBF | E04YAF
E04GDF | E04YAF
E04HEF | E04YAF and E04YBF
It should be noted that routines E04STF, E04UCF/E04UCA, E04UFF/E04UFA, E04UGF/E04UGA, E04USF/E04USA, E04VHF and E04WDF each incorporate a check on the derivatives being supplied. This involves verifying the gradients at the first point that satisfies the linear constraints and bounds. There is also an option to perform a more reliable (but more expensive) check on the individual gradient elements being supplied. Note that the checks are not infallible.
A second type of service routine computes a set of finite differences to be used when approximating first derivatives. Such differences are required as input arguments by some routines that use only function evaluations.
E04YCF estimates selected elements of the variance-covariance matrix for the computed regression parameters following the use of a nonlinear least squares routine.
E04XAF/E04XAA estimates the gradient and Hessian of a function at a point, given a routine to calculate function values only, or estimates the Hessian of a function at a point, given a routine to calculate function and gradient values.

3.7 Function Evaluations at Infeasible Points

All the solvers for constrained problems based on active-set method will ensure that any evaluations of the objective function occur at points which approximately (up to the given tolerance) satisfy any simple bounds or linear constraints.
There is no attempt to ensure that the current iteration satisfies any nonlinear constraints. If you wish to prevent your objective function being evaluated outside some known region (where it may be undefined or not practically computable), you may try to confine the iteration within this region by imposing suitable simple bounds or linear constraints (but beware as this may create new local minima where these constraints are active).
Note also that some routines allow you to return the argument (IFLAG, INFORM, MODE or STATUS) with a negative value to indicate when the objective function (or nonlinear constraints where appropriate) cannot be evaluated. In case the routine cannot recover (e.g., cannot find a different trial point), it forces an immediate clean exit from the routine.

3.8 Related Problems

Apart from the standard types of optimization problem, there are other related problems which can be solved by routines in this or other chapters of the Library.
H02BBF solves dense integer LP problems, H02CBF solves dense integer QP problems, H02CEF solves sparse integer QP problems, H02DAF solves dense mixed integer NLP problems and H03ABF solves a special type of such problem known as a ‘transportation’ problem.
Several routines in Chapters F04 and F08 solve linear least squares problems, i.e., minimize⁡∑i=1 m ri x 2 where ri x=bi-∑j=1 n a ijxj.
E02GAF solves an overdetermined system of linear equations in the l 1 norm, i.e., minimizes ∑i=1 m ri x, with ri as above, and E02GBF solves the same problem subject to linear inequality constraints.
E02GCF solves an overdetermined system of linear equations in the l∞ norm, i.e., minimizes maxi ri x, with ri as above.
Chapter E05 contains routines for global minimization.
Section 2.5.5 describes how a multi-objective optimization problem might be addressed using routines from this chapter and from Chapter E05.

4 Decision Trees

 | no objective | linear | quadratic | nonlinear | sum of squares
unconstrained |  |  | QP See Tree 2 | NLP See Tree 3 | LSQ See Tree 4
simple bounds | LP See Tree 1 | LP See Tree 1 | QP See Tree 2 | NLP See Tree 3 | LSQ See Tree 4
linear | LP See Tree 1 | LP See Tree 1 | QP See Tree 2 | NLP See Tree 3 | LSQ See Tree 4
nonlinear | NLP See Tree 3 | NLP See Tree 3 | NLP See Tree 3 | NLP See Tree 3 | LSQ See Tree 4
matrix inequalities | E04SVF | E04SVF | E04SVF |  |
Table 1
Decision Matrix

Tree 1: Linear Programming (LP)

Is the problem sparse/large-scale? |  |  | E04NQF, E04NKF
 |  | yes
 | no |
E04MFF, E04NCF

Tree 2: Quadratic Programming (QP)

Is the problem sparse/large-scale? |  |  | Is it convex? |  |  | E04NQF, E04STF, E04NKF
 |  | yes |  |  | yes
 | no |  |  | no |
 |  |  | E04STF, E04VHF, E04UGF
Is it convex? |  |  | E04NCF
 |  | yes
 | no |
E04NFF

Tree 3: Nonlinear Programming (NLP)

Is the problem sparse/large-scale? |  |  | Is it unconstrained? |  |  | Are first derivatives available? |  |  | E04STF, E04DGF, E04VHF, E04UGF
 |  | yes |  |  | yes |  |  | yes
 | no |  |  | no |  |  | no |
 |  |  |  |  |  | E04VHF, E04UGF
 |  |  | Are first derivatives available? |  |  | Are second derivatives available? |  |  | E04STF
 |  |  |  |  | yes |  |  | yes
 |  |  |  | no |  |  | no |
 |  |  |  |  |  | E04VHF, E04STF, E04UGF
 |  |  | E04VHF, E04UGF
Are there linear or nonlinear constraints? |  |  | E04UCF, E04UFF, E04WDF
 |  | yes
 | no |
Is there only one variable? |  |  | Are first derivatives available? |  |  | E04BBF
 |  | yes |  |  | yes
 | no |  |  | no |
 |  |  | E04ABF
Is it unconstrained with the objective with many discontinuities? |  |  | E04CBF or E05SAF
 |  | yes
 | no |
Are first derivatives available? |  |  | Are second derivatives available? |  |  | Are you an experienced user? |  |  | E04LBF
 |  | yes |  |  | yes |  |  | yes
 | no |  |  | no |  |  | no |
 |  |  |  |  |  | E04LYF
 |  |  | Are many function evaluations problematic? |  |  | Are you an experienced user? |  |  | E04UCF, E04UFF, E04WDF
 |  |  |  |  | yes |  |  | yes
 |  |  |  | no |  |  | no |
 |  |  |  |  |  | E04KYF
 |  |  | Are you an experienced user? |  |  | E04KDF
 |  |  |  |  | yes
 |  |  |  | no |
 |  |  | E04KZF
Is the objective expensive to evaluate or noisy? |  |  | E04JCF
 |  | yes
 | no |
Are you an experienced user? |  |  | E04UCF, E04UFF, E04WDF
 |  | yes
 | no |
E04JYF

Tree 4: Least squares problems (LSQ)

Is the objective sum of squared linear functions and no nonlinear constraints? |  |  | Are there linear constraints? |  |  | E04NCF
 |  | yes |  |  | yes
 | no |  |  | no |
 |  |  | Are there simple bounds? |  |  | E04PCF, E04NCF
 |  |  |  |  | yes
 |  |  |  | no |
 |  |  | Chapters F04, F07 or F08 or E04PCF, E04NCF
Are there simple bounds, linear or nonlinear constraints? |  |  | E04USF
 |  | yes
 | no |
Are you an experienced user? |  |  | Are first derivatives available? |  |  | Are second derivatives available? |  |  | E04HEF
 |  | yes |  |  | yes |  |  | yes
 | no |  |  | no |  |  | no |
 |  |  |  |  |  | Are many function evaluations problematic? |  |  | E04GBF
 |  |  |  |  |  |  |  | yes
 |  |  |  |  |  |  | no |
 |  |  |  |  |  | E04GDF
 |  |  | E04FCF
Are first derivatives available? |  |  | Are second derivatives available? |  |  | E04HYF
 |  | yes |  |  | yes
 | no |  |  | no |
 |  |  | Are many function evaluations problematic? |  |  | E04GYF
 |  |  |  |  | yes
 |  |  |  | no |
 |  |  | E04GZF
E04FYF

5 Functionality Index

Linear programming (LP),
dense,
active-set method/primal simplex,
alternative 1 E04MFF
alternative 2 E04NCF
sparse,
active-set method/primal simplex,
recommended (see Section 3.4) E04NQF
alternative E04NKF
Quadratic programming (QP),
dense,
active-set method for (possibly nonconvex) QP problem E04NFF
active-set method for convex QP problem E04NCF
sparse,
active-set method sparse convex QP problem,
recommended (see Section 3.4) E04NQF
alternative E04NKF
interior point method (IPM) for (possibly nonconvex) QP problems E04STF
Nonlinear programming (NLP),
dense,
active-set sequential quadratic programming (SQP),
recommended (see Section 3.4) E04UCF
alternative E04WDF
reverse communication E04UFF
sparse,
interior point method (IPM) E04STF
active-set sequential quadratic programming (SQP),
recommended (see Section 3.4) E04VHF
alternative E04UGF
Nonlinear programming (NLP) – derivative free optimization (DFO),
model-based method for bound-constrained optimization E04JCF
Nelder–Mead simplex method for unconstrained optimization E04CBF
Nonlinear programming (NLP) – special cases,
unidimensional optimization (1D) with bound constraints,
method based on quadratic interpolation, no derivatives E04ABF
method based on cubic interpolation E04BBF
unconstrained,
preconditioned conjugate gradient method E04DGF
bound-constrained,
quasi-Newton algorithm, no derivatives E04JYF
quasi-Newton algorithm, first derivatives E04KYF
modified Newton algorithm, first derivatives E04KDF
modified Newton algorithm, first derivatives, easy-to-use E04KZF
modified Newton algorithm, first and second derivatives E04LBF
modified Newton algorithm, first and second derivatives, easy-to-use E04LYF
Semidefinite programming (SDP),
generalized augmented Lagrangian method for SDP and SDP with bilinear matrix inequalities (BMI-SDP) E04SVF
Linear least squares, linear regression, data fitting,
constrained,
bound-constrained least squares problem E04PCF
linearly-constrained active-set method E04NCF
Nonlinear least squares, data fitting,
unconstrained,
combined Gauss–Newton and modified Newton algorithm,
no derivatives E04FCF
no derivatives, easy-to-use E04FYF
first derivatives E04GDF
first derivatives, easy-to-use E04GZF
first and second derivatives E04HEF
first and second derivatives, easy-to-use E04HYF
combined Gauss–Newton and quasi-Newton algorithm,
first derivatives E04GBF
first derivatives, easy-to-use E04GYF
covariance matrix for nonlinear least squares problem (unconstrained) E04YCF
constrained,
nonlinear constraints active-set sequential quadratic programming (SQP) E04USF
NAG optimization modelling suite,
initialization of a handle for the NAG optimization modelling suite E04RAF
define a linear objective function E04REF
define a linear or a quadratic objective function E04RFF
define a nonlinear objective function E04RGF
define bounds of variables E04RHF
define a block of linear constraints E04RJF
define a block of nonlinear constraints E04RKF
define a structure of Hessian of the objective, constraints or the Lagrangian E04RLF
add one or more linear matrix inequality constraints E04RNF
define bilinear matrix terms E04RPF
print information about a problem handle E04RYF
destroy the problem handle E04RZF
interior point method (IPM) for nonlinear programming (NLP) E04STF
generalized augmented Lagrangian method for SDP and SDP with bilinear matrix inequalities (BMI-SDP) E04SVF
supply optional parameter values from a character string E04ZMF
get the setting of option E04ZNF
supply optional parameter values from external file E04ZPF
Service routines,
input and output (I/O),
read MPS data file defining LP, QP, MILP or MIQP problem E04MXF
write MPS data file defining LP, QP, MILP or MIQP problem E04MWF
read sparse SPDA data files for linear SDP problems E04RDF
read MPS data file defining LP or QP problem (deprecated) E04MZF
derivative check and approximation,
check user's routine for calculating first derivatives of function E04HCF
check user's routine for calculating second derivatives of function E04HDF
check user's routine for calculating Jacobian of first derivatives E04YAF
check user's routine for calculating Hessian of a sum of squares E04YBF
estimate (using numerical differentiation) gradient and/or Hessian of a function E04XAF
determine the pattern of nonzeros in the Jacobian matrix for E04VHF E04VJF
covariance matrix for nonlinear least squares problem (unconstrained) E04YCF
option setting routines,
NAG optimization modelling suite,
supply optional parameter values from a character string E04ZMF
get the setting of option E04ZNF
supply optional parameter values from external file E04ZPF
E04DGF/E04DGA,
initialization routine for E04DGA E04WBF
supply optional parameter values from external file E04DJF
supply optional parameter values from a character string E04DKF
E04MFF/E04MFA,
initialization routine for E04MFA E04WBF
supply optional parameter values from external file E04MGF
supply optional parameter values from a character string E04MHF
E04NCF/E04NCA,
initialization routine for E04NCA E04WBF
supply optional parameter values from external file E04NDF
supply optional parameter values from a character string E04NEF
E04NFF/E04NFA,
initialization routine for E04NFA E04WBF
supply optional parameter values from external file E04NGF
supply optional parameter values from a character string E04NHF
E04NKF/E04NKA,
initialization routine for E04NKA E04WBF
supply optional parameter values from external file E04NLF
supply optional parameter values from a character string E04NMF
E04NQF,
initialization routine E04NPF
supply optional parameter values from external file E04NRF
set a single option from a character string E04NSF
set a single option from an integer argument E04NTF
set a single option from a real argument E04NUF
get the setting of an integer valued option E04NXF
get the setting of a real valued option E04NYF
E04UCF/E04UCA and E04UFF/E04UFA,
initialization routine for E04UCA and E04UFA E04WBF
supply optional parameter values from external file E04UDF
supply optional parameter values from a character string E04UEF
E04UGF/E04UGA,
initialization routine for E04UGA E04WBF
supply optional parameter values from external file E04UHF
supply optional parameter values from a character string E04UJF
E04USF/E04USA,
initialization routine for E04USA E04WBF
supply optional parameter values from external file E04UQF
supply optional parameter values from a character string E04URF
E04VHF,
initialization routine E04VGF
supply optional parameter values from external file E04VKF
set a single option from a character string E04VLF
set a single option from an integer argument E04VMF
set a single option from a real argument E04VNF
get the setting of an integer valued option E04VRF
get the setting of a real valued option E04VSF
E04WDF,
initialization routine E04WCF
supply optional parameter values from external file E04WEF
set a single option from a character string E04WFF
set a single option from an integer argument E04WGF
set a single option from a real argument E04WHF
get the setting of an integer valued option E04WKF
get the setting of a real valued option E04WLF

6 Auxiliary Routines Associated with Library Routine Arguments

E04CBK | nagf_opt_uncon_simplex_dummy_monit See the description of the argument MONIT in E04CBF.
E04FCV | nagf_opt_lsq_uncon_quasi_deriv_comp_lsqlin_fun See the description of the argument LSQLIN in E04GBF.
E04FDZ | nagf_opt_lsq_dummy_lsqmon See the description of the argument LSQMON in E04FCF, E04GDF and E04HEF.
E04HEV | nagf_opt_lsq_uncon_quasi_deriv_comp_lsqlin_deriv See the description of the argument LSQLIN in E04GBF.
E04JCP | nagf_opt_bounds_bobyqa_func_dummy_monfun See the description of the argument MONFUN in E04JCF.
E54NFU | nagf_opt_qp_dense_sample_qphess See the description of the argument QPHESS in E04NFF/E04NFA and H02CBF.
E04NFU | nagf_opt_qp_dense_sample_qphess_old See the description of the argument QPHESS in E04NFF/E04NFA and H02CBF.
E54NKU | nagf_opt_qpconvex1_sparse_dummy_qphx See the description of the argument QPHX in E04NKF/E04NKA and H02CEF.
E04NKU | nagf_opt_qpconvex1_sparse_dummy_qphx_old See the description of the argument QPHX in E04NKF/E04NKA and H02CEF.
E04NSH | nagf_opt_qpconvex2_sparse_dummy_qphx See the description of the argument QPHX in E04NQF.
E04STU | nagf_opt_ipopt_dummy_mon See the description of the argument MON in E04STF.
E04STV | nagf_opt_ipopt_dummy_objfun See the description of the argument OBJFUN in E04STF.
E04STW | nagf_opt_ipopt_dummy_objgrd See the description of the argument OBJGRD in E04STF.
E04STX | nagf_opt_ipopt_dummy_confun See the description of the argument CONFUN in E04STF.
E04STY | nagf_opt_ipopt_dummy_congrd See the description of the argument CONGRD in E04STF.
E04STZ | nagf_opt_ipopt_dummy_hess See the description of the argument HESS in E04STF.
E04UDM | nagf_opt_nlp1_dummy_confun See the description of the argument CONFUN in E04UCF/E04UCA and E04USF/E04USA.
E04UGM | nagf_opt_nlp1_sparse_dummy_confun See the description of the argument CONFUN in E04UGF/E04UGA.
E04UGN | nagf_opt_nlp1_sparse_dummy_objfun See the description of the argument OBJFUN in E04UGF/E04UGA.
E04WDP | nagf_opt_nlp2_dummy_confun See the description of the argument CONFUN in E04WDF.

7 Routines Withdrawn or Scheduled for Withdrawal

The following lists all those routines that have been withdrawn since Mark 19 of the Library or are scheduled for withdrawal at one of the next two marks.
Withdrawn Routine | Mark of Withdrawal | Replacement Routine(s)
E04CCF/E04CCA | 24 | E04CBF
E04FDF | 19 | E04FYF
E04GCF | 19 | E04GYF
E04GEF | 19 | E04GZF
E04HFF | 19 | E04HYF
E04JAF | 19 | E04JYF
E04KAF | 19 | E04KYF
E04KCF | 19 | E04KZF
E04LAF | 19 | E04LYF
E04UNF | 22 | E04USF/E04USA
E04UPF | 19 | E04USF/E04USA
E04ZCF/E04ZCA | 24 | No longer required

8 References

Bard Y (1974) Nonlinear Parameter Estimation Academic Press
Chvátal V (1983) Linear Programming W.H. Freeman
Dantzig G B (1963) Linear Programming and Extensions Princeton University Press
Fletcher R (1987) Practical Methods of Optimization (2nd Edition) Wiley
Gill P E and Murray W (ed.) (1974) Numerical Methods for Constrained Optimization Academic Press
Gill P E, Murray W and Wright M H (1981) Practical Optimization Academic Press
Murray W (ed.) (1972) Numerical Methods for Unconstrained Optimization Academic Press
Nocedal J and Wright S J (1999) Numerical Optimization Springer Series in Operations Research, Springer, New York
Wolberg J R (1967) Prediction Analysis Van Nostrand
E04 Chapter Contents
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


E04JCF : NAG Library, Mark 26

E04 Chapter Contents
E04 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

E04JCF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

E04JCF is an easy-to-use algorithm that uses methods of quadratic approximation to find a minimum of an objective function F over x∈Rn, subject to fixed lower and upper bounds on the independent variables x 1,x 2,…,xn. Derivatives of F are not required.
The routine is intended for functions that are continuous and that have continuous first and second derivatives (although it will usually work even if the derivatives have occasional discontinuities). Efficiency is maintained for large n.

2 Specification

SUBROUTINE E04JCF ( OBJFUN, N, NPT, X, BL, BU, RHOBEG, RHOEND, MONFUN, MAXCAL, F, NF, IUSER, RUSER, IFAIL)
INTEGER | N, NPT, MAXCAL, NF, IUSER(*), IFAIL
REAL (KIND=nag_wp) | X(N), BL(N), BU(N), RHOBEG, RHOEND, F, RUSER(*)
EXTERNAL | OBJFUN, MONFUN

3 Description

E04JCF is applicable to problems of the form:
minimize x∈Rn F x   subject to   ℓ ≤ x ≤ u   and   ℓ≤u ,
where F is a nonlinear scalar function whose derivatives may be unavailable, and where the bound vectors are elements of Rn. Relational operators between vectors are interpreted elementwise.
Fixing variables (that is, setting ℓi=ui for some i) is allowed in E04JCF.
You must supply a subroutine to calculate the value of F at any given point x.
The method used by E04JCF is based on BOBYQA, the method of Bound Optimization BY Quadratic Approximation described in Powell (2009). In particular, each iteration of E04JCF generates a quadratic approximation Q to F that agrees with F at m automatically chosen interpolation points. The value of m is a constant prescribed by you. Updates to the independent variables mostly occur from approximate solutions to trust-region subproblems, using the current quadratic model.

4 References

Powell M J D (2009) The BOBYQA algorithm for bound constrained optimization without derivatives Report DAMTP 2009/NA06 University of Cambridge http://www.damtp.cam.ac.uk/user/na/NA_papers/NA2009_06.pdf

5 Arguments

1:   OBJFUN – SUBROUTINE, supplied by the user.External Procedure
OBJFUN must evaluate the objective function F at a specified vector x.
The specification of OBJFUN is:
SUBROUTINE OBJFUN ( N, X, F, IUSER, RUSER, INFORM)
INTEGER | N, IUSER(*), INFORM
REAL (KIND=nag_wp) | X(N), F, RUSER(*)
1:   N – INTEGERInput
On entry: n, the number of independent variables.
2:   X N – REAL (KIND=nag_wp) arrayInput
On entry: x, the vector at which the objective function is to be evaluated.
3:   F – REAL (KIND=nag_wp)Output
On exit: must be set to the value of the objective function at x, unless you have specified termination of the current problem using INFORM.
4:   IUSER* – INTEGER arrayUser Workspace
5:   RUSER* – REAL (KIND=nag_wp) arrayUser Workspace
OBJFUN is called with the arguments IUSER and RUSER as supplied to E04JCF. You are free to use the arrays IUSER and RUSER to supply information to OBJFUN as an alternative to using COMMON global variables.
6:   INFORM – INTEGEROutput
On exit: must be set to a value describing the action to be taken by the solver on return from OBJFUN. Specifically, if the value is negative the solution of the current problem will terminate immediately; otherwise, computations will continue.
OBJFUN must either be a module subprogram USEd by, or declared as EXTERNAL in, the (sub)program from which E04JCF is called. Arguments denoted as Input must not be changed by this procedure.
2:   N – INTEGERInput
On entry: n, the number of independent variables.
Constraint: N≥2 and nr≥2, where nr denotes the number of non-fixed variables.
3:   NPT – INTEGERInput
On entry: m, the number of interpolation conditions imposed on the quadratic approximation at each iteration.
Suggested value: NPT=2×nr+1, where nr denotes the number of non-fixed variables.
Constraint: nr+2≤NPT≤nr+1×nr+2 2, where nr denotes the number of non-fixed variables.
4:   X N – REAL (KIND=nag_wp) arrayInput/Output
On entry: an estimate of the position of the minimum. If any component is out-of-bounds it is replaced internally by the bound it violates.
On exit: the lowest point found during the calculations. Thus, if IFAIL=0 on exit, X is the position of the minimum.
5:   BL N – REAL (KIND=nag_wp) arrayInput
6:   BU N – REAL (KIND=nag_wp) arrayInput
On entry: the fixed vectors of bounds: the lower bounds ℓ and the upper bounds u, respectively. To signify that a variable is unbounded you should choose a large scalar r appropriate to your problem, then set the lower bound on that variable to -r and the upper bound to r. For well-scaled problems r=rmax 14 may be suitable, where rmax denotes the largest positive model number (see X02ALF).
Constraints:
  • if X i is to be fixed at BL i, then BL i=BU i;
  • otherwise BU i-BL i≥2.0×RHOBEG, for i=1,2,…,N.
7:   RHOBEG – REAL (KIND=nag_wp)Input
On entry: an initial lower bound on the value of the trust-region radius.
Suggested value: RHOBEG should be about one tenth of the greatest expected overall change to a variable: the initial quadratic model will be constructed by taking steps from the initial X of length RHOBEG along each coordinate direction.
Constraints:
  • RHOBEG>0.0;
  • RHOBEG≥RHOEND.
8:   RHOEND – REAL (KIND=nag_wp)Input
On entry: a final lower bound on the value of the trust-region radius.
Suggested value: RHOEND should indicate the absolute accuracy that is required in the final values of the variables.
Constraint: RHOEND≥macheps, where macheps=X02AJF, the machine precision..
9:   MONFUN – SUBROUTINE, supplied by the NAG Library or the user.External Procedure
MONFUN may be used to monitor the optimization process. It is invoked every time a new trust-region radius is chosen.
If no monitoring is required, MONFUN may be the dummy monitoring routine E04JCP supplied by the NAG Library.
The specification of MONFUN is:
SUBROUTINE MONFUN ( N, NF, X, F, RHO, IUSER, RUSER, INFORM)
INTEGER | N, NF, IUSER(*), INFORM
REAL (KIND=nag_wp) | X(N), F, RHO, RUSER(*)
1:   N – INTEGERInput
On entry: n, the number of independent variables.
2:   NF – INTEGERInput
On entry: the cumulative number of calls made to OBJFUN.
3:   X N – REAL (KIND=nag_wp) arrayInput
On entry: the current best point.
4:   F – REAL (KIND=nag_wp)Input
On entry: the value of OBJFUN at X.
5:   RHO – REAL (KIND=nag_wp)Input
On entry: a lower bound on the current trust-region radius.
6:   IUSER* – INTEGER arrayUser Workspace
7:   RUSER* – REAL (KIND=nag_wp) arrayUser Workspace
MONFUN is called with the arguments IUSER and RUSER as supplied to E04JCF. You are free to use the arrays IUSER and RUSER to supply information to MONFUN as an alternative to using COMMON global variables.
8:   INFORM – INTEGEROutput
On exit: must be set to a value describing the action to be taken by the solver on return from MONFUN. Specifically, if the value is negative the solution of the current problem will terminate immediately; otherwise, computations will continue.
MONFUN must either be a module subprogram USEd by, or declared as EXTERNAL in, the (sub)program from which E04JCF is called. Arguments denoted as Input must not be changed by this procedure.
10:   MAXCAL – INTEGERInput
On entry: the maximum permitted number of calls to OBJFUN.
Constraint: MAXCAL≥1.
11:   F – REAL (KIND=nag_wp)Output
On exit: the function value at the lowest point found (X).
12:   NF – INTEGEROutput
On exit: unless IFAIL=1 or -999 on exit, the total number of calls made to OBJFUN.
13:   IUSER* – INTEGER arrayUser Workspace
14:   RUSER* – REAL (KIND=nag_wp) arrayUser Workspace
IUSER and RUSER are not used by E04JCF, but are passed directly to OBJFUN and MONFUN and may be used to pass information to these routines as an alternative to using COMMON global variables.
15:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).
E04JCF returns with IFAIL=0 if the final trust-region radius has reached its lower bound RHOEND.

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, MAXCAL=value.
Constraint: MAXCAL≥1.
On entry, RHOBEG=value, BL i=value, BU i=value and i=value.
Constraint: if BL i≠BU i in coordinate i, then BU i-BL i≥2×RHOBEG.
On entry, RHOBEG=value.
Constraint: RHOBEG>0.0.
On entry, RHOBEG=value and RHOEND=value.
Constraint: RHOEND≤RHOBEG.
On entry, RHOEND=value.
Constraint: RHOEND≥macheps, where macheps=X02AJF, the machine precision.
There were nr=value unequal bounds.
Constraint: nr≥2.
There were nr=value unequal bounds and NPT=value on entry.
Constraint: nr+2≤NPT≤nr+1×nr+2 2.
IFAIL=2
The function evaluations limit was reached: OBJFUN has been called MAXCAL times.
IFAIL=3
The predicted reduction in a trust-region step was non-positive. Check your specification of OBJFUN and whether the function needs rescaling. Try a different initial X.
IFAIL=4
A rescue procedure has been called in order to correct damage from rounding errors when computing an update to a quadratic approximation of F, but no further progess could be made. Check your specification of OBJFUN and whether the function needs rescaling. Try a different initial X.
IFAIL=5
User-supplied monitoring routine requested termination.
User-supplied objective function requested termination.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

Experience shows that, in many cases, on successful termination the ∞-norm distance from the best point x to a local minimum of F is less than 10×RHOEND, unless RHOEND is so small that such accuracy is unattainable.

8 Parallelism and Performance

E04JCF makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

For each invocation of E04JCF, local workspace arrays of fixed length are allocated internally. The total size of these arrays amounts to NPT+6×NPT+nr+nr×3 nr+21 2 real elements and nr integer elements, where nr denotes the number of non-fixed variables; that is, the total size is O nr 4. If you follow the recommendation for the choice of NPT on entry, this total size reduces to O nr 2.
Usually the total number of function evaluations (NF) is substantially less than O nr 2, and often, if NPT=2×nr+1 on entry, NF is only of magnitude nr or less.

10 Example

This example involves the minimization of
F = x 1+10 x 2 2 +5⁢ x 3 - x 4 2 + x 2-2 x 3 4 +10⁢ x 1 - x 4 4
subject to
-1≤x 1≤ 3, -2≤x 2≤ 0, -1≤x 4≤ 3,
starting from the initial guess 3,-1,0,1 .

10.1 Program Text

Program Text (e04jcfe.f90)

10.2 Program Data

None.

10.3 Program Results

Program Results (e04jcfe.r)

E04 Chapter Contents
E04 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


E04JYF : NAG Library, Mark 26

E04 Chapter Contents
E04 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

E04JYF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

E04JYF is an easy-to-use quasi-Newton algorithm for finding a minimum of a function F x 1,x 2,…,xn, subject to fixed upper and lower bounds of the independent variables x 1,x 2,…,xn, using function values only.
It is intended for functions which are continuous and which have continuous first and second derivatives (although it will usually work even if the derivatives have occasional discontinuities).

2 Specification

SUBROUTINE E04JYF ( N, IBOUND, FUNCT1, BL, BU, X, F, IW, LIW, W, LW, IUSER, RUSER, IFAIL)
INTEGER | N, IBOUND, IW(LIW), LIW, LW, IUSER(*), IFAIL
REAL (KIND=nag_wp) | BL(N), BU(N), X(N), F, W(LW), RUSER(*)
EXTERNAL | FUNCT1

3 Description

E04JYF is applicable to problems of the form:
Minimize F x 1,x 2,…,xn  subject to  lj≤xj≤uj,  j=1,2,…,n
when derivatives of F x are unavailable.
Special provision is made for problems which actually have no bounds on the xj, problems which have only non-negativity bounds and problems in which l 1=l 2=⋯=ln and u 1=u 2=⋯=un. You must supply a subroutine to calculate the value of F x at any point x.
From a starting point you supplied there is generated, on the basis of estimates of the gradient and the curvature of F x, a sequence of feasible points which is intended to converge to a local minimum of the constrained function. An attempt is made to verify that the final point is a minimum.
A typical iteration starts at the current point x where nz (say) variables are free from both their bounds. The projected gradient vector gz, whose elements are finite difference approximations to the derivatives of F x with respect to the free variables, is known. A unit lower triangular matrix L and a diagonal matrix D (both of dimension nz), such that LD LT is a positive definite approximation of the matrix of second derivatives with respect to the free variables (i.e., the projected Hessian) are also held. The equations
LD LT pz=-gz
are solved to give a search direction pz, which is expanded to an n-vector p by an insertion of appropriate zero elements. Then α is found such that F x+αp is approximately a minimum (subject to the fixed bounds) with respect to α; x is replaced by x+αp, and the matrices L and D are updated so as to be consistent with the change produced in the estimated gradient by the step αp. If any variable actually reaches a bound during the search along p, it is fixed and nz is reduced for the next iteration. Most iterations calculate gz using forward differences, but central differences are used when they seem necessary.
There are two sets of convergence criteria – a weaker and a stronger. Whenever the weaker criteria are satisfied, the Lagrange multipliers are estimated for all the active constraints. If any Lagrange multiplier estimate is significantly negative, then one of the variables associated with a negative Lagrange multiplier estimate is released from its bound and the next search direction is computed in the extended subspace (i.e., nz is increased). Otherwise minimization continues in the current subspace provided that this is practicable. When it is not, or when the stronger convergence criteria are already satisfied, then, if one or more Lagrange multiplier estimates are close to zero, a slight perturbation is made in the values of the corresponding variables in turn until a lower function value is obtained. The normal algorithm is then resumed from the perturbed point.
If a saddle point is suspected, a local search is carried out with a view to moving away from the saddle point. A local search is also performed when a point is found which is thought to be a constrained minimum.

4 References

Gill P E and Murray W (1976) Minimization subject to bounds on the variables NPL Report NAC 72 National Physical Laboratory

5 Arguments

1:   N – INTEGERInput
On entry: the number n of independent variables.
Constraint: N≥1.
2:   IBOUND – INTEGERInput
On entry: indicates whether the facility for dealing with bounds of special forms is to be used.
It must be set to one of the following values:
IBOUND=0
If you are supplying all the lj and uj individually.
IBOUND=1
If there are no bounds on any xj.
IBOUND=2
If all the bounds are of the form 0≤xj.
IBOUND=3
If l 1=l 2=…=ln and u 1=u 2=…=un.
3:   FUNCT1 – SUBROUTINE, supplied by the user.External Procedure
You must supply FUNCT1 to calculate the value of the function F x at any point x. It should be tested separately before being used with E04JYF (see the E04 Chapter Introduction).
The specification of FUNCT1 is:
SUBROUTINE FUNCT1 ( N, XC, FC, IUSER, RUSER)
INTEGER | N, IUSER(*)
REAL (KIND=nag_wp) | XC(N), FC, RUSER(*)
1:   N – INTEGERInput
On entry: the number n of variables.
2:   XC N – REAL (KIND=nag_wp) arrayInput
On entry: the point x at which the function value is required.
3:   FC – REAL (KIND=nag_wp)Output
On exit: the value of the function F at the current point x.
4:   IUSER* – INTEGER arrayUser Workspace
5:   RUSER* – REAL (KIND=nag_wp) arrayUser Workspace
FUNCT1 is called with the arguments IUSER and RUSER as supplied to E04JYF. You are free to use the arrays IUSER and RUSER to supply information to FUNCT1 as an alternative to using COMMON global variables.
FUNCT1 must either be a module subprogram USEd by, or declared as EXTERNAL in, the (sub)program from which E04JYF is called. Arguments denoted as Input must not be changed by this procedure.
4:   BL N – REAL (KIND=nag_wp) arrayInput/Output
On entry: the lower bounds lj.
If IBOUND is set to 0, you must set BL j to lj, for j=1,2,…,n. (If a lower bound is not specified for a particular xj, the corresponding BL j should be set to -106.)
If IBOUND is set to 3, you must set BL 1 to l 1; E04JYF will then set the remaining elements of BL equal to BL 1.
On exit: the lower bounds actually used by E04JYF.
5:   BU N – REAL (KIND=nag_wp) arrayInput/Output
On entry: the upper bounds uj.
If IBOUND is set to 0, you must set BU j to uj, for j=1,2,…,n. (If an upper bound is not specified for a particular xj, the corresponding BU j should be set to 106.)
If IBOUND is set to 3, you must set BU 1 to u 1; E04JYF will then set the remaining elements of BU equal to BU 1.
On exit: the upper bounds actually used by E04JYF.
6:   X N – REAL (KIND=nag_wp) arrayInput/Output
On entry: X j must be set to an estimate of the jth component of the position of the minimum, for j=1,2,…,n.
On exit: the lowest point found during the calculations. Thus, if IFAIL=0 on exit, X j is the jth component of the position of the minimum.
7:   F – REAL (KIND=nag_wp)Output
On exit: the value of F x corresponding to the final point stored in X.
8:   IW LIW – INTEGER arrayOutput
On exit: if IFAIL=0, 3 or 5, the first N elements of IW contain information about which variables are currently on their bounds and which are free. Specifically, if xi is:
– fixed on its upper bound, IW i is -1;
– fixed on its lower bound, IW i is -2;
– effectively a constant (i.e., lj=uj), IW i is -3;
– free, IW i gives its position in the sequence of free variables.
In addition, IW N+1 contains the number of free variables (i.e., nz). The rest of the array is used as workspace.
9:   LIW – INTEGERInput
On entry: the dimension of the array IW as declared in the (sub)program from which E04JYF is called.
Constraint: LIW≥N+2.
10:   W LW – REAL (KIND=nag_wp) arrayOutput
On exit: if IFAIL=0, 3 or 5, W i contains a finite difference approximation to the ith element of the projected gradient vector gz, for i=1,2,…,N. In addition, W N+1 contains an estimate of the condition number of the projected Hessian matrix (i.e., k). The rest of the array is used as workspace.
11:   LW – INTEGERInput
On entry: the dimension of the array W as declared in the (sub)program from which E04JYF is called.
Constraint: LW≥max N×N-1/2+12×N,13.
12:   IUSER* – INTEGER arrayUser Workspace
13:   RUSER* – REAL (KIND=nag_wp) arrayUser Workspace
IUSER and RUSER are not used by E04JYF, but are passed directly to FUNCT1 and may be used to pass information to this routine as an alternative to using COMMON global variables.
14:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, because for this routine the values of the output arguments may be useful even if IFAIL≠0 on exit, the recommended value is -1. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Note: E04JYF may return useful information for one or more of the following detected errors or warnings.
Errors or warnings detected by the routine:
IFAIL=1
On entry, | N<1,
or | IBOUND<0,
or | IBOUND>3,
or | IBOUND=0 and BL j>BU j for some j,
or | IBOUND=3 and BL 1>BU 1,
or | LIW<N+2,
or | LW < max 13,12×N+N×N-1/2 .
IFAIL=2
There have been 400×n function evaluations, yet the algorithm does not seem to be converging. The calculations can be restarted from the final point held in X. The error may also indicate that F x has no minimum.
IFAIL=3
The conditions for a minimum have not all been met but a lower point could not be found and the algorithm has failed.
IFAIL=4
An overflow has occurred during the computation. This is an unlikely failure, but if it occurs you should restart at the latest point given in X.
IFAIL=5
IFAIL=6
IFAIL=7
IFAIL=8
There is some doubt about whether the point x found by E04JYF is a minimum. The degree of confidence in the result decreases as IFAIL increases. Thus, when IFAIL=5 it is probable that the final x gives a good estimate of the position of a minimum, but when IFAIL=8 it is very unlikely that the routine has found a minimum.
IFAIL=9
In the search for a minimum, the modulus of one of the variables has become very large ∼106. This indicates that there is a mistake in FUNCT1, that your problem has no finite solution, or that the problem needs rescaling (see Section 9).
IFAIL=10
The computed set of forward-difference intervals (stored in W 9×N+1,W 9×N+2,…, W 10×N) is such that X i+W 9×N+i≤X i for some i.
This is an unlikely failure, but if it occurs you should attempt to select another starting point.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.
If you are dissatisfied with the result (e.g., because IFAIL=5, 6, 7 or 8), it is worth restarting the calculations from a different starting point (not the point at which the failure occurred) in order to avoid the region which caused the failure. If persistent trouble occurs and the gradient can be calculated, it may be advisable to change to a routine which uses gradients (see the E04 Chapter Introduction).

7 Accuracy

A successful exit (IFAIL=0) is made from E04JYF when (B1, B2 and B3) or B4 hold, and the local search confirms a minimum, where
  • B1≡α k ×p k <xtol+ε×1.0+x k
  • B2≡F k -F k-1 <xtol 2+ε×1.0+F k
  • B3≡gz k <ε 1/3+xtol×1.0+F k
  • B4≡gz k <0.01×ε.
(Quantities with superscript k are the values at the kth iteration of the quantities mentioned in Section 3, xtol=100 ε, ε is the machine precision and . denotes the Euclidean norm. The vector gz is returned in the array W.)
If IFAIL=0, then the vector in X on exit, xsol, is almost certainly an estimate of the position of the minimum, xtrue, to the accuracy specified by xtol.
If IFAIL=3 or 5, xsol may still be a good estimate of xtrue, but the following checks should be made. Let k denote an estimate of the condition number of the projected Hessian matrix at xsol. (The value of k is returned in W N+1). If
(i) | the sequence F x k converges to F xsol at a superlinear or a fast linear rate,
(ii) | gz xxol 2<10.0×ε, and
(iii) | k<1.0/gz xsol,
then it is almost certain that xsol is a close approximation to the position of a minimum. When (ii) is true, then usually F xsol is a close approximation to F xtrue.
When a successful exit is made then, for a computer with a mantissa of t decimals, one would expect to get about t/2-1 decimals accuracy in x and about t-1 decimals accuracy in F, provided the problem is reasonably well scaled.

8 Parallelism and Performance

E04JYF is not threaded in any implementation.

9 Further Comments

The number of iterations required depends on the number of variables, the behaviour of F x and the distance of the starting point from the solution. The number of operations performed in an iteration of E04JYF is roughly proportional to n 2. In addition, each iteration makes at least m+1 calls of FUNCT1, where m is the number of variables not fixed on bounds. So, unless F x can be evaluated very quickly, the run time will be dominated by the time spent in FUNCT1.
Ideally the problem should be scaled so that at the solution the value of F x and the corresponding values of x 1,x 2,…,xn are each in the range -1,+1, and so that at points a unit distance away from the solution, F is approximately a unit value greater than at the minimum. It is unlikely that you will be able to follow these recommendations very closely, but it is worth trying (by guesswork), as sensible scaling will reduce the difficulty of the minimization problem, so that E04JYF will take less computer time.

10 Example

To minimize
F= x 1+10 x 2 2+5⁢ x 3-x 4 2+ x 2-2 x 3 4+10⁢ x 1-x 4 4
subject to
-1≤x 1≤ 3, -2≤x 2≤ 0, -1≤x 4≤ 3,
starting from the initial guess 3,-1,0,1 .

10.1 Program Text

Program Text (e04jyfe.f90)

10.2 Program Data

None.

10.3 Program Results

Program Results (e04jyfe.r)

E04 Chapter Contents
E04 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


E04KDF : NAG Library, Mark 26

E04 Chapter Contents
E04 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

E04KDF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
▸▿ 9 Further Comments
9.1 Timing
9.2 Scaling
9.3 Unconstrained Minimization
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

E04KDF is a comprehensive modified Newton algorithm for finding:
  • – an unconstrained minimum of a function of several variables;
  • – a minimum of a function of several variables subject to fixed upper and/or lower bounds on the variables.
First derivatives are required. The routine is intended for functions which have continuous first and second derivatives (although it will usually work even if the derivatives have occasional discontinuities).

2 Specification

SUBROUTINE E04KDF ( N, FUNCT, MONIT, IPRINT, MAXCAL, ETA, XTOL, DELTA, STEPMX, IBOUND, BL, BU, X, HESL, LH, HESD, ISTATE, F, G, IW, LIW, W, LW, IFAIL)
INTEGER | N, IPRINT, MAXCAL, IBOUND, LH, ISTATE(N), IW(LIW), LIW, LW, IFAIL
REAL (KIND=nag_wp) | ETA, XTOL, DELTA, STEPMX, BL(N), BU(N), X(N), HESL(LH), HESD(N), F, G(N), W(LW)
EXTERNAL | FUNCT, MONIT

3 Description

E04KDF is applicable to problems of the form:
Minimize⁡F x 1,x 2,…,xn  subject to  lj≤xj≤uj,  j=1,2,…,n.
Special provision is made for unconstrained minimization (i.e., problems which actually have no bounds on the xj), problems which have only non-negativity bounds, and problems in which l 1=l 2=⋯=ln and u 1=u 2=⋯=un. It is possible to specify that a particular xj should be held constant. You must supply a starting point, and a FUNCT to calculate the value of F x and its first derivatives ∂F ∂xj at any point x.
A typical iteration starts at the current point x where nz (say) variables are free from their bounds. The vector gz, whose elements are the derivatives of F x with respect to the free variables, is known. The matrix of second derivatives with respect to the free variables, H, is estimated by finite differences. (Note that gz and H are both of dimension nz.) The equations
H+E pz=-gz
are solved to give a search direction pz. (The matrix E is chosen so that H+E is positive definite.)
pz is then expanded to an n-vector p by the insertion of appropriate zero elements, α is found such that F x+αp is approximately a minimum (subject to the fixed bounds) with respect to α; and x is replaced by x+αp. (If a saddle point is found, a special search is carried out so as to move away from the saddle point.) If any variable actually reaches a bound, it is fixed and nz is reduced for the next iteration.
There are two sets of convergence criteria – a weaker and a stronger. Whenever the weaker criteria are satisfied, the Lagrange multipliers are estimated for all the active constraints. If any Lagrange multiplier estimate is significantly negative, then one of the variables associated with a negative Lagrange multiplier estimate is released from its bound and the next search direction is computed in the extended subspace (i.e., nz is increased). Otherwise minimization continues in the current subspace until the stronger convergence criteria are satisfied. If at this point there are no negative or near-zero Lagrange multiplier estimates, the process is terminated.
If you specify that the problem is unconstrained, E04KDF sets the lj to -106 and the uj to 106. Thus, provided that the problem has been sensibly scaled, no bounds will be encountered during the minimization process and E04KDF will act as an unconstrained minimization algorithm.

4 References

Gill P E and Murray W (1973) Safeguarded steplength algorithms for optimization using descent methods NPL Report NAC 37 National Physical Laboratory
Gill P E and Murray W (1974) Newton-type methods for unconstrained and linearly constrained optimization Math. Programming 7 311–350
Gill P E and Murray W (1976) Minimization subject to bounds on the variables NPL Report NAC 72 National Physical Laboratory

5 Arguments

1:   N – INTEGERInput
On entry: the number n of independent variables.
Constraint: N≥1.
2:   FUNCT – SUBROUTINE, supplied by the user.External Procedure
FUNCT must evaluate the function F x and its first derivatives ∂F ∂xj at a specified point. (However, if you do not wish to calculate F or its first derivatives at a particular x, there is the option of setting an argument to cause E04KDF to terminate immediately.)
The specification of FUNCT is:
SUBROUTINE FUNCT ( IFLAG, N, XC, FC, GC, IW, LIW, W, LW)
INTEGER | IFLAG, N, IW(LIW), LIW, LW
REAL (KIND=nag_wp) | XC(N), FC, GC(N), W(LW)
1:   IFLAG – INTEGERInput/Output
On entry: will have been set to 1 or 2. The value 1 indicates that only the first derivatives of F need be supplied, and the value 2 indicates that both F itself and its first derivatives must be calculated.
On exit: if it is not possible to evaluate F or its first derivatives at the point given in XC (or if it is wished to stop the calculations for any other reason) you should reset IFLAG to a negative number and return control to E04KDF. E04KDF will then terminate immediately, with IFAIL set to your setting of IFLAG.
2:   N – INTEGERInput
On entry: the number n of variables.
3:   XC N – REAL (KIND=nag_wp) arrayInput
On entry: the point x at which the ∂F ∂xj , or F and the ∂F ∂xj , are required.
4:   FC – REAL (KIND=nag_wp)Output
On exit: unless IFLAG=1 on entry or IFLAG is reset, FUNCT must set FC to the value of the objective function F at the current point x.
5:   GC N – REAL (KIND=nag_wp) arrayOutput
On exit: unless FUNCT resets IFLAG, it must set GC j to the value of the first derivative ∂F ∂xj at the point x, for j=1,2,…,n.
6:   IW LIW – INTEGER arrayWorkspace
7:   LIW – INTEGERInput
8:   W LW – REAL (KIND=nag_wp) arrayWorkspace
9:   LW – INTEGERInput
FUNCT is called with the same arguments IW, LIW, W, LW as for E04KDF. They are present so that, when other library routines require the solution of a minimization subproblem, constants needed for the function evaluation can be passed through IW and W. Similarly, you could use elements 3,4,…,LIW of IW and elements from max 8,7×N+N×N-1/2+1 onwards of W for passing quantities to FUNCT from the subroutine which calls E04KDF. However, because of the danger of mistakes in partitioning, it is recommended that you should pass information to FUNCT via COMMON global variables and not use IW or W at all. In any case you must not change the first 2 elements of IW or the first max 8,7×N+N×N-1/2 elements of W.
FUNCT must either be a module subprogram USEd by, or declared as EXTERNAL in, the (sub)program from which E04KDF is called. Arguments denoted as Input must not be changed by this procedure.
Note: FUNCT should be tested separately before being used in conjunction with E04KDF.
3:   MONIT – SUBROUTINE, supplied by the user.External Procedure
If IPRINT≥0, you must supply MONIT which is suitable for monitoring the minimization process. MONIT must not change the values of any of its arguments.
If IPRINT<0, a MONIT with the correct argument list must still be supplied, although it will not be called.
The specification of MONIT is:
SUBROUTINE MONIT ( N, XC, FC, GC, ISTATE, GPJNRM, COND, POSDEF, NITER, NF, IW, LIW, W, LW)
INTEGER | N, ISTATE(N), NITER, NF, IW(LIW), LIW, LW
REAL (KIND=nag_wp) | XC(N), FC, GC(N), GPJNRM, COND, W(LW)
LOGICAL | POSDEF
1:   N – INTEGERInput
On entry: the number n of variables.
2:   XC N – REAL (KIND=nag_wp) arrayInput
On entry: the coordinates of the current point x.
3:   FC – REAL (KIND=nag_wp)Input
On entry: the value of F x at the current point x.
4:   GC N – REAL (KIND=nag_wp) arrayInput
On entry: the value of ∂F ∂xj at the current point x, for j=1,2,…,n.
5:   ISTATE N – INTEGER arrayInput
On entry: information about which variables are currently fixed on their bounds and which are free.
If ISTATE j is negative, xj is currently:
– fixed on its upper bound if ISTATE j=-1
– fixed on its lower bound if ISTATE j=-2
– effectively a constant (i.e., lj=uj) if ISTATE j=-3
If ISTATE j is positive, its value gives the position of xj in the sequence of free variables.
6:   GPJNRM – REAL (KIND=nag_wp)Input
On entry: the Euclidean norm of the current projected gradient vector gz.
7:   COND – REAL (KIND=nag_wp)Input
On entry: the ratio of the largest to the smallest elements of the diagonal factor D of the approximated projected Hessian matrix. This quantity is usually a good estimate of the condition number of the projected Hessian matrix. (If no variables are currently free, COND is set to zero.)
8:   POSDEF – LOGICALInput
On entry: specifies .TRUE. or .FALSE. according to whether or not the approximation to the second derivative matrix for the current subspace, H, is positive definite.
9:   NITER – INTEGERInput
On entry: the number of iterations (as outlined in Section 3) which have been performed by E04KDF so far.
10:   NF – INTEGERInput
On entry: the number of evaluations of F x so far, i.e., the number of calls of FUNCT with IFLAG set to 2. Each such call of FUNCT also calculates the first derivatives of F. (In addition to these calls monitored by NF, FUNCT is called with IFLAG set to 1 not more than N times per iteration.)
11:   IW LIW – INTEGER arrayWorkspace
12:   LIW – INTEGERInput
13:   W LW – REAL (KIND=nag_wp) arrayWorkspace
14:   LW – INTEGERInput
As in FUNCT, these arguments correspond to the arguments IW, LIW, W, LW of E04KDF. They are included in MONIT's argument list primarily for when E04KDF is called by other library routines.
MONIT must either be a module subprogram USEd by, or declared as EXTERNAL in, the (sub)program from which E04KDF is called. Arguments denoted as Input must not be changed by this procedure.
You should normally print FC, GPJNRM and COND to be able to compare the quantities mentioned in Section 7. It is usually helpful to examine XC, POSDEF and NF too.
4:   IPRINT – INTEGERInput
On entry: the frequency with which MONIT is to be called.
IPRINT>0
MONIT is called once every IPRINT iterations and just before exit from E04KDF.
IPRINT=0
MONIT is just called at the final point.
IPRINT<0
MONIT is not called at all.
IPRINT should normally be set to a small positive number.
Suggested value: IPRINT=1.
5:   MAXCAL – INTEGERInput
On entry: the maximum permitted number of evaluations of F x, i.e., the maximum permitted number of calls of FUNCT with IFLAG set to 2. It should be borne in mind that, in addition to the calls of FUNCT which are limited directly by MAXCAL, there will be calls of FUNCT (with IFLAG set to 1) to evaluate only first derivatives.
Suggested value: MAXCAL=50×N.
Constraint: MAXCAL≥1.
6:   ETA – REAL (KIND=nag_wp)Input
On entry: every iteration of E04KDF involves a linear minimization (i.e., minimization of F x+αp with respect to α). ETA specifies how accurately these linear minimizations are to be performed. The minimum with respect to α will be located more accurately for small values of ETA (say, 0.01) than large values (say, 0.9).
Although accurate linear minimizations will generally reduce the number of iterations (and hence the number of calls of FUNCT to estimate the second derivatives), they will tend to increase the number of calls of FUNCT needed for each linear minimization. On balance, it is usually more efficient to perform a low accuracy linear minimization when n is small and a high accuracy minimization when n is large.
Suggested values:
  • ETA=0.5 if 1<n<10;
  • ETA=0.1 if 10≤n≤20;
  • ETA=0.01 if n>20.
If N=1, ETA should be set to 0.0 (also when the problem is effectively one-dimensional even though n>1; i.e., if for all except one of the variables the lower and upper bounds are equal).
Constraint: 0.0≤ETA<1.0.
7:   XTOL – REAL (KIND=nag_wp)Input
On entry: the accuracy in x to which the solution is required.
If xtrue is the true value of x at the minimum, then xsol, the estimated position before a normal exit, is such that xsol-xtrue<XTOL×1.0+xtrue where y=∑j=1 n yj 2. For example, if the elements of xsol are not much larger than 1.0 in modulus, and if XTOL is set to 10-5, then xsol is usually accurate to about five decimal places. (For further details see Section 7.)
If the problem is scaled as described in Section 9.2 and ε is the machine precision, then ε is probably the smallest reasonable choice for XTOL. This is because, normally, to machine accuracy, F x+ε ej=F x, for any j where ej is the jth column of the identity matrix. If you set XTOL to 0.0 (or any positive value less than ε), E04KDF will use 10.0×ε instead of XTOL.
Suggested value: XTOL=0.0.
Constraint: XTOL≥0.0.
8:   DELTA – REAL (KIND=nag_wp)Input
On entry: the differencing interval to be used for approximating the second derivatives of F x. Thus, for the finite difference approximations, the first derivatives of F x are evaluated at points which are DELTA apart. If ε is the machine precision, then ε will usually be a suitable setting for DELTA. If you set DELTA to 0.0 (or to any positive value less than ε), E04KDF will automatically use ε as the differencing interval.
Suggested value: DELTA=0.0.
Constraint: DELTA≥0.0.
9:   STEPMX – REAL (KIND=nag_wp)Input
On entry: an estimate of the Euclidean distance between the solution and the starting point supplied by you. (For maximum efficiency a slight overestimate is preferable.)
E04KDF will ensure that, for each iteration,
∑j=1 n xj k -xj k-1 2 ≤STEPMX,
where k is the iteration number. Thus, if the problem has more than one solution, E04KDF is most likely to find the one nearest to the starting point. On difficult problems, a realistic choice can prevent the sequence of x k entering a region where the problem is ill-behaved and can also help to avoid possible overflow in the evaluation of F x. However, an underestimate of STEPMX can lead to inefficiency.
Suggested value: STEPMX=100000.0.
Constraint: STEPMX≥XTOL.
10:   IBOUND – INTEGERInput
On entry: indicates whether the problem is unconstrained or bounded. If there are bounds on the variables, IBOUND can be used to indicate whether the facility for dealing with bounds of special forms is to be used. It must be set to one of the following values:
IBOUND=0
If the variables are bounded and you are supplying all the lj and uj individually.
IBOUND=1
If the problem is unconstrained.
IBOUND=2
If the variables are bounded, but all the bounds are of the form 0≤xj.
IBOUND=3
If all the variables are bounded, and l 1=l 2=⋯=ln and u 1=u 2=⋯=un.
IBOUND=4
If the problem is unconstrained. (The IBOUND=4 option is provided for consistency with other routines. In E04KDF it produces the same effect as IBOUND=1.)
Constraint: 0≤IBOUND≤4.
11:   BL N – REAL (KIND=nag_wp) arrayInput/Output
On entry: the fixed lower bounds lj.
If IBOUND is set to 0, you must set BL j to lj, for j=1,2,…,n. (If a lower bound is not specified for any xj, the corresponding BL j should be set to a large negative number, e.g., -106.)
If IBOUND is set to 3, you must set BL 1 to l 1; E04KDF will then set the remaining elements of BL equal to BL 1.
If IBOUND is set to 1, 2 or 4, BL will be initialized by E04KDF.
On exit: the lower bounds actually used by E04KDF, e.g., if IBOUND=2, BL 1=BL 2=⋯=BL n=0.0.
12:   BU N – REAL (KIND=nag_wp) arrayInput/Output
On entry: the fixed upper bounds uj.
If IBOUND is set to 0, you must set BU j to uj, for j=1,2,…,n. (If an upper bound is not specified for any variable, the corresponding BU j should be set to a large positive number, e.g., 106.)
If IBOUND is set to 3, you must set BU 1 to u 1; E04KDF will then set the remaining elements of BU equal to BU 1.
If IBOUND is set to 1, 2 or 4, BU will be initialized by E04KDF.
On exit: the upper bounds actually used by E04KDF, e.g., if IBOUND=2, BU 1=BU 2=⋯=BU n=106.
13:   X N – REAL (KIND=nag_wp) arrayInput/Output
On entry: X j must be set to a guess at the jth component of the position of the minimum, for j=1,2,…,n.
On exit: the final point x k . Thus, if IFAIL=0 on exit, X j is the jth component of the estimated position of the minimum.
14:   HESL LH – REAL (KIND=nag_wp) arrayOutput
On exit: during the determination of a direction pz (see Section 3), H+E is decomposed into the product LD LT, where L is a unit lower triangular matrix and D is a diagonal matrix. (The matrices H, E, L and D are all of dimension nz, where nz is the number of variables free from their bounds. H consists of those rows and columns of the full estimated second derivative matrix which relate to free variables. E is chosen so that H+E is positive definite.)
HESL and HESD are used to store the factors L and D. The elements of the strict lower triangle of L are stored row by row in the first nz nz-1/2 positions of HESL. The diagonal elements of D are stored in the first nz positions of HESD. In the last factorization before a normal exit, the matrix E will be zero, so that HESL and HESD will contain, on exit, the factors of the final estimated second derivative matrix H. The elements of HESD are useful for deciding whether to accept the results produced by E04KDF (see Section 7).
15:   LH – INTEGERInput
On entry: the dimension of the array HESL as declared in the (sub)program from which E04KDF is called.
Constraint: LH≥max N×N-1/2,1.
16:   HESD N – REAL (KIND=nag_wp) arrayOutput
On exit: during the determination of a direction pz (see Section 3), H+E is decomposed into the product LD LT, where L is a unit lower triangular matrix and D is a diagonal matrix. (The matrices H, E, L and D are all of dimension nz, where nz is the number of variables free from their bounds. H consists of those rows and columns of the full estimated second derivative matrix which relate to free variables. E is chosen so that H+E is positive definite.)
HESL and HESD are used to store the factors L and D. The elements of the strict lower triangle of L are stored row by row in the first nz nz-1/2 positions of HESL. The diagonal elements of D are stored in the first nz positions of HESD. In the last factorization before a normal exit, the matrix E will be zero, so that HESL and HESD will contain, on exit, the factors of the final estimated second derivative matrix H. The elements of HESD are useful for deciding whether to accept the results produced by E04KDF (see Section 7).
17:   ISTATE N – INTEGER arrayOutput
On exit: information about which variables are currently on their bounds and which are free. If ISTATE j is:
  • – equal to -1, xj is fixed on its upper bound;
  • – equal to -2, xj is fixed on its lower bound;
  • – equal to -3, xj is effectively a constant (i.e., lj=uj);
  • – positive, ISTATE j gives the position of xj in the sequence of free variables.
18:   F – REAL (KIND=nag_wp)Output
On exit: the function value at the final point given in X.
19:   G N – REAL (KIND=nag_wp) arrayOutput
On exit: the first derivative vector corresponding to the final point given in X. The components of G corresponding to free variables should normally be close to zero.
20:   IW LIW – INTEGER arrayCommunication Array
21:   LIW – INTEGERInput
On entry: the dimension of the array IW as declared in the (sub)program from which E04KDF is called.
Constraint: LIW≥2.
22:   W LW – REAL (KIND=nag_wp) arrayCommunication Array
23:   LW – INTEGERInput
On entry: the dimension of the array W as declared in the (sub)program from which E04KDF is called.
Constraint: LW≥max 7×N+N×N-1/2,8.
24:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, because for this routine the values of the output arguments may be useful even if IFAIL≠0 on exit, the recommended value is -1. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Note: E04KDF may return useful information for one or more of the following detected errors or warnings.
Errors or warnings detected by the routine:
IFAIL<0
A negative value of IFAIL indicates an exit from E04KDF because you have set IFLAG negative in FUNCT. The value of IFAIL will be the same as your setting of IFLAG.
IFAIL=1
On entry, | N<1,
or | MAXCAL<1,
or | ETA<0.0,
or | ETA≥1.0,
or | XTOL<0.0,
or | DELTA<0.0,
or | STEPMX<XTOL,
or | IBOUND<0,
or | IBOUND>4,
or | BL j>BU j for some j if IBOUND=0,
or | BL 1>BU 1 if IBOUND=3,
or | LH < max 1,N×N-1/2 ,
or | LIW<2,
or | LW < max 8,7×N+N×N-1/2 .
(Note that if you have set XTOL or DELTA to 0.0, E04KDF uses the default values and continues without failing.) When this exit occurs, no values will have been assigned to F or to the elements of HESL, HESD or G.
IFAIL=2
There have been MAXCAL function evaluations. If steady reductions in F x were monitored up to the point where this exit occurred, then the exit probably occurred simply because MAXCAL was set too small, so the calculations should be restarted from the final point held in X. This exit may also indicate that F x has no minimum.
IFAIL=3
The conditions for a minimum have not all been met, but a lower point could not be found.
Provided that, on exit, the first derivatives of F x with respect to the free variables are sufficiently small, and that the estimated condition number of the second derivative matrix is not too large, this error exit may simply mean that, although it has not been possible to satisfy the specified requirements, the algorithm has in fact found the minimum as far as the accuracy of the machine permits. Such a situation can arise, for instance, if XTOL has been set so small that rounding errors in the evaluation of F x or its derivatives make it impossible to satisfy the convergence conditions.
If the estimated condition number of the second derivative matrix at the final point is large, it could be that the final point is a minimum, but that the smallest eigenvalue of the Hessian matrix is so close to zero that it is not possible to recognize the point as a minimum.
IFAIL=4
Not used. (This is done to make the significance of IFAIL=5 similar for E04KDF and E04LBF.)
IFAIL=5
All the Lagrange multiplier estimates which are not indisputably positive lie relatively close to zero, but it is impossible either to continue minimizing on the current subspace or to find a feasible lower point by releasing and perturbing any of the fixed variables. You should investigate as for IFAIL=3.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.
The values IFAIL=2, 3 or 5 may also be caused by mistakes in FUNCT, by the formulation of the problem or by an awkward function. If there are no such mistakes, it is worth restarting the calculations from a different starting point (not the point at which the failure occurred) in order to avoid the region which caused the failure.

7 Accuracy

A successful exit (IFAIL=0) is made from E04KDF when H k is positive definite and when (B1, B2 and B3) or B4 hold, where
B1 ≡ α k ×p k <XTOL+ε×1.0+x k B2 ≡ F k -F k-1 <XTOL 2+ε×1.0+F k B3 ≡ gz k <ε 1/3+XTOL×1.0+F k B4 ≡ gz k <0.01×ε.
(Quantities with superscript k are the values at the kth iteration of the quantities mentioned in Section 3, ε is the machine precision and . denotes the Euclidean norm.)
If IFAIL=0, then the vector in X on exit, xsol, is almost certainly an estimate of the position of the minimum, xtrue, to the accuracy specified by XTOL.
If IFAIL=3 or 5, xsol may still be a good estimate of xtrue, but the following checks should be made. Let the largest of the first nz elements of HESD be HESD b, let the smallest be HESD s, and define k=HESD b/HESD s. The scalar k is usually a good estimate of the condition number of the projected Hessian matrix at xsol. If
(i) | the sequence F x k converges to F xsol at a superlinear or fast linear rate,
(ii) | gz xsol 2<10.0×ε, and
(iii) | k<1.0/gz xsol,
then it is almost certain that xsol is a close approximation to the position of a minimum. When (ii) is true, then usually F xsol is a close approximation to F xtrue. The quantities needed for these checks are all available via MONIT; in particular the value of COND in the last call of MONIT before exit gives k.
Further suggestions about confirmation of a computed solution are given in the E04 Chapter Introduction.

8 Parallelism and Performance

E04KDF is not threaded in any implementation.

9 Further Comments

9.1 Timing

The number of iterations required depends on the number of variables, the behaviour of F x, the accuracy demanded and the distance of the starting point from the solution. The number of multiplications performed in an iteration of E04KDF is nz 3 6+O nz 2. In addition, each iteration makes nz calls of FUNCT (with IFLAG set to 1) in approximating the projected Hessian matrix, and at least one other call of FUNCT (with IFLAG set to 2). So, unless F x and its first derivatives can be evaluated very quickly, the run time will be dominated by the time spent in FUNCT.

9.2 Scaling

Ideally, the problem should be scaled so that, at the solution, F x and the corresponding values of xj are each in the range -1,+1, and so that at points one unit away from the solution, F x differs from its value at the solution by approximately one unit. This will usually imply that the Hessian matrix at the solution is well-conditioned. It is unlikely that you will be able to follow these recommendations very closely, but it is worth trying (by guesswork), as sensible scaling will reduce the difficulty of the minimization problem, so that E04KDF will take less computer time.

9.3 Unconstrained Minimization

If a problem is genuinely unconstrained and has been scaled sensibly, the following points apply:
(a) | nz will always be n,
(b) | HESL and HESD will be factors of the full estimated second derivative matrix with elements stored in the natural order,
(c) | the elements of g should all be close to zero at the final point,
(d) | the values of the ISTATE j given by MONIT and on exit from E04KDF are unlikely to be of interest (unless they are negative, which would indicate that the modulus of one of the xj has reached 106 for some reason),
(e) | MONIT's argument GPJNRM simply gives the norm of the first derivative vector.
So the following routine (in which partitions of extended workspace arrays are used as BL, BU and ISTATE) could be used for unconstrained problems:
      SUBROUTINE UNCKDF(N,FUNCT,MONIT,IPRINT,MAXCAL,ETA,XTOL,DELTA,      &
                        STEPMX,X,HESL,LH,HESD,F,G,IWORK,LIWORK,WORK,     &
                        LWORK,IFAIL)

!     A ROUTINE TO APPLY E04KDF TO UNCONSTRAINED PROBLEMS.

!     THE REAL ARRAY WORK MUST BE OF DIMENSION AT LEAST
!     (9*N + MAX(1, N*(N-1)/2)).  ITS FIRST 7*N + MAX(1, N*(N-1)/2)
!     ELEMENTS WILL BE USED BY E04KDF AS THE ARRAY W.  ITS LAST
!     2*N ELEMENTS WILL BE USED AS THE ARRAYS BL AND BU.

!     THE INTEGER ARRAY IWORK MUST BE OF DIMENSION AT LEAST (N+2)
!     ITS FIRST 2 ELEMENTS WILL BE USED BY E04KDF AS THE ARRAY IW.
!     ITS LAST N ELEMENTS WILL BE USED AS THE ARRAY ISTATE.

!     LIWORK AND LWORK MUST BE SET TO THE ACTUAL LENGTHS OF IWORK
!     AND WORK RESPECTIVELY, AS DECLARED IN THE CALLING SEGMENT.

!     OTHER PARAMETERS ARE AS FOR E04KDF.

!     ..  Parameters ..
      INTEGER NOUT
      PARAMETER (NOUT=6)
!     ..  Scalar Arguments ..
      REAL (KIND=nag_wp) DELTA, ETA, F, STEPMX, XTOL
      INTEGER            IFAIL, IPRINT, LH, LIWORK, LWORK, MAXCAL, N
!     ..  Array Arguments ..
      REAL (KIND=nag_wp) G(N), HESD(N), HESL(LH), WORK(LWORK), X(N)
      INTEGER            IWORK(LIWORK)
!     ..  Subroutine Arguments ..
      EXTERNAL FUNCT, MONIT
!     ..  Local Scalars ..
      INTEGER IBOUND, J, JBL, JBU, NH
      LOGICAL TOOBIG
!     ..  External Subroutines ..
      EXTERNAL E04KDF
!     ..  Executable Statements ..
!     CHECK THAT SUFFICIENT WORKSPACE HAS BEEN SUPPLIED
      NH = N*(N-1)/2
      IF (NH.EQ.0) NH = 1
      IF (LWORK.LT.9*N+NH .OR.  LIWORK.LT.N+2) THEN
         WRITE (NOUT,FMT=99999)
         STOP
      END IF
!     JBL AND JBU SPECIFY THE PARTS OF WORK USED AS BL AND BU
      JBL = 7*N + NH + 1
      JBU = JBL + N
!     SPECIFY THAT THE PROBLEM IS UNCONSTRAINED
      IBOUND = 4
      CALL E04KDF(N,FUNCT,MONIT,IPRINT,MAXCAL,ETA,XTOL,DELTA,STEPMX,     &
                    IBOUND,WORK(JBL),WORK(JBU),X,HESL,LH,HESD,IWORK(3),    &
               F,G,IWORK,LIWORK,WORK,LWORK,IFAIL)
!     CHECK THE PART OF IWORK WHICH WAS USED AS ISTATE IN CASE
!     THE MODULUS OF SOME X(J) HAS REACHED E+6
      TOOBIG = .FALSE.
      DO 20 J = 1, N
         IF (IWORK(2+J).LT.0) TOOBIG = .TRUE.
   20 CONTINUE
      IF ( .NOT.  TOOBIG) RETURN
      WRITE (NOUT,FMT=99998)
      STOP

99999 FORMAT (' ***** INSUFFICIENT WORKSPACE HAS BEEN SUPPLIED *****')
99998 FORMAT (' ***** A VARIABLE HAS REACHED E+6 IN MODULUS - NO UNCON', &
                'STRAINED MINIMUM HAS BEEN FOUND *****')
      END

10 Example

A program to minimize
F= x 1+10 x 2 2+5⁢ x 3-x 4 2+ x 2-2 x 3 4+10⁢ x 1-x 4 4
subject to the bounds
1 ≤ x 1 ≤ 3 -2 ≤ x 2 ≤ 0 1 ≤ x 4 ≤ 3,
starting from the initial guess 3,-1,0,1 . Before calling E04KDF, the program calls E04HCF to check the first derivatives calculated by FUNCT.

10.1 Program Text

Program Text (e04kdfe.f90)

10.2 Program Data

None.

10.3 Program Results

Program Results (e04kdfe.r)

E04 Chapter Contents
E04 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


E04KYF : NAG Library, Mark 26

E04 Chapter Contents
E04 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

E04KYF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

E04KYF is an easy-to-use quasi-Newton algorithm for finding a minimum of a function F x 1,x 2,…,xn, subject to fixed upper and lower bounds on the independent variables x 1,x 2,…,xn, when first derivatives of F are available.
It is intended for functions which are continuous and which have continuous first and second derivatives (although it will usually work even if the derivatives have occasional discontinuities).

2 Specification

SUBROUTINE E04KYF ( N, IBOUND, FUNCT2, BL, BU, X, F, G, IW, LIW, W, LW, IUSER, RUSER, IFAIL)
INTEGER | N, IBOUND, IW(LIW), LIW, LW, IUSER(*), IFAIL
REAL (KIND=nag_wp) | BL(N), BU(N), X(N), F, G(N), W(LW), RUSER(*)
EXTERNAL | FUNCT2

3 Description

E04KYF is applicable to problems of the form:
Minimize⁡F x 1,x 2,…,xn  subject to  lj≤xj≤uj,  j=1,2,…,n
when first derivatives are available.
Special provision is made for problems which actually have no bounds on the xj, problems which have only non-negativity bounds, and problems in which l 1=l 2=…=ln and u 1=u 2=…=un. You must supply a subroutine to calculate the values of F x and its first derivatives at any point x.
From a starting point you supplied there is generated, on the basis of estimates of the curvature of F x, a sequence of feasible points which is intended to converge to a local minimum of the constrained function. An attempt is made to verify that the final point is a minimum.
A typical iteration starts at the current point x where nz (say) variables are free from both their bounds. The projected gradient vector gz, whose elements are the derivatives of F x with respect to the free variables, is known. A unit lower triangular matrix L and a diagonal matrix D (both of dimension nz), such that LD LT is a positive definite approximation of the matrix of second derivatives with respect to the free variables (i.e., the projected Hessian) are also held. The equations
LD LT pz=-gz
are solved to give a search direction pz, which is expanded to an n-vector p by an insertion of appropriate zero elements. Then α is found such that F x+αp is approximately a minimum (subject to the fixed bounds) with respect to α; x is replaced by x+αp, and the matrices L and D are updated so as to be consistent with the change produced in the gradient by the step αp. If any variable actually reaches a bound during the search along p, it is fixed and nz is reduced for the next iteration.
There are two sets of convergence criteria – a weaker and a stronger. Whenever the weaker criteria are satisfied, the Lagrange multipliers are estimated for all the active constraints. If any Lagrange multiplier estimate is significantly negative, then one of the variables associated with a negative Lagrange multiplier estimate is released from its bound and the next search direction is computed in the extended subspace (i.e., nz is increased). Otherwise minimization continues in the current subspace provided that this is practicable. When it is not, or when the stronger convergence criteria are already satisfied, then, if one or more Lagrange multiplier estimates are close to zero, a slight perturbation is made in the values of the corresponding variables in turn until a lower function value is obtained. The normal algorithm is then resumed from the perturbed point.
If a saddle point is suspected, a local search is carried out with a view to moving away from the saddle point. A local search is also performed when a point is found which is thought to be a constrained minimum.

4 References

Gill P E and Murray W (1976) Minimization subject to bounds on the variables NPL Report NAC 72 National Physical Laboratory

5 Arguments

1:   N – INTEGERInput
On entry: the number n of independent variables.
Constraint: N≥1.
2:   IBOUND – INTEGERInput
On entry: indicates whether the facility for dealing with bounds of special forms is to be used. It must be set to one of the following values:
IBOUND=0
If you are supplying all the lj and uj individually.
IBOUND=1
If there are no bounds on any xj.
IBOUND=2
If all the bounds are of the form 0≤xj.
IBOUND=3
If l 1=l 2=⋯=ln and u 1=u 2=⋯=un.
Constraint: 0≤IBOUND≤3.
3:   FUNCT2 – SUBROUTINE, supplied by the user.External Procedure
You must supply FUNCT2 to calculate the values of the function F x and its first derivative ∂F ∂xj at any point x. It should be tested separately before being used in conjunction with E04KYF (see the E04 Chapter Introduction).
The specification of FUNCT2 is:
SUBROUTINE FUNCT2 ( N, XC, FC, GC, IUSER, RUSER)
INTEGER | N, IUSER(*)
REAL (KIND=nag_wp) | XC(N), FC, GC(N), RUSER(*)
1:   N – INTEGERInput
On entry: the number n of variables.
2:   XC N – REAL (KIND=nag_wp) arrayInput
On entry: the point x at which the function and derivatives are required.
3:   FC – REAL (KIND=nag_wp)Output
On exit: the value of the function F at the current point x.
4:   GC N – REAL (KIND=nag_wp) arrayOutput
On exit: GC j must be set to the value of the first derivative ∂F ∂xj at the point x, for j=1,2,…,n.
5:   IUSER* – INTEGER arrayUser Workspace
6:   RUSER* – REAL (KIND=nag_wp) arrayUser Workspace
FUNCT2 is called with the arguments IUSER and RUSER as supplied to E04KYF. You are free to use the arrays IUSER and RUSER to supply information to FUNCT2 as an alternative to using COMMON global variables.
FUNCT2 must either be a module subprogram USEd by, or declared as EXTERNAL in, the (sub)program from which E04KYF is called. Arguments denoted as Input must not be changed by this procedure.
4:   BL N – REAL (KIND=nag_wp) arrayInput/Output
On entry: the lower bounds lj.
If IBOUND is set to 0, you must set BL j to lj, for j=1,2,…,n. (If a lower bound is not specified for a particular xj, the corresponding BL j should be set to -106.)
If IBOUND is set to 3, you must set BL 1 to l 1; E04KYF will then set the remaining elements of BL equal to BL 1.
On exit: the lower bounds actually used by E04KYF.
5:   BU N – REAL (KIND=nag_wp) arrayInput/Output
On entry: the upper bounds uj.
If IBOUND is set to 0, you must set BU j to uj, for j=1,2,…,n. (If an upper bound is not specified for a particular xj, the corresponding BU j should be set to 106.)
If IBOUND is set to 3, you must set BU 1 to u 1; E04KYF will then set the remaining elements of BU equal to BU 1.
On exit: the upper bounds actually used by E04KYF.
6:   X N – REAL (KIND=nag_wp) arrayInput/Output
On entry: X j must be set to a guess at the jth component of the position of the minimum, for j=1,2,…,n. The routine checks the gradient at the starting point, and is more likely to detect any error in your programming if the initial X j are nonzero and mutually distinct.
On exit: the lowest point found during the calculations. Thus, if IFAIL=0 on exit, X j is the jth component of the position of the minimum.
7:   F – REAL (KIND=nag_wp)Output
On exit: the value of F x corresponding to the final point stored in X.
8:   G N – REAL (KIND=nag_wp) arrayOutput
On exit: the value of ∂F ∂xj corresponding to the final point stored in X, for j=1,2,…,n; the value of G j for variables not on a bound should normally be close to zero.
9:   IW LIW – INTEGER arrayOutput
On exit: if IFAIL=0, 3 or 5, the first N elements of IW contain information about which variables are currently on their bounds and which are free. Specifically, if xi is:
– fixed on its upper bound, IW i is -1;
– fixed on its lower bound, IW i is -2;
– effectively a constant (i.e., lj=uj), IW i is -3;
– free, IW i gives its position in the sequence of free variables.
In addition, IW N+1 contains the number of free variables (i.e., nz). The rest of the array is used as workspace.
10:   LIW – INTEGERInput
On entry: the dimension of the array IW as declared in the (sub)program from which E04KYF is called.
Constraint: LIW≥N+2.
11:   W LW – REAL (KIND=nag_wp) arrayOutput
On exit: if IFAIL=0, 3 or 5, W i contains the ith element of the projected gradient vector gz, for i=1,2,…,N. In addition, W N+1 contains an estimate of the condition number of the projected Hessian matrix (i.e., k). The rest of the array is used as workspace.
12:   LW – INTEGERInput
On entry: the dimension of the array W as declared in the (sub)program from which E04KYF is called.
Constraint: LW≥max 10×N+N×N-1/2,11.
13:   IUSER* – INTEGER arrayUser Workspace
14:   RUSER* – REAL (KIND=nag_wp) arrayUser Workspace
IUSER and RUSER are not used by E04KYF, but are passed directly to FUNCT2 and may be used to pass information to this routine as an alternative to using COMMON global variables.
15:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, because for this routine the values of the output arguments may be useful even if IFAIL≠0 on exit, the recommended value is -1. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Note: E04KYF may return useful information for one or more of the following detected errors or warnings.
Errors or warnings detected by the routine:
IFAIL=1
On entry, | N<1,
or | IBOUND<0,
or | IBOUND>3,
or | IBOUND=0 and BL j>BU j for some j,
or | IBOUND=3 and BL 1>BU 1,
or | LIW<N+2,
or | LW < max 11,10×N+N×N-1/2 .
IFAIL=2
There have been 100×n function evaluations, yet the algorithm does not seem to be converging. The calculations can be restarted from the final point held in X. The error may also indicate that F x has no minimum.
IFAIL=3
The conditions for a minimum have not all been met but a lower point could not be found and the algorithm has failed.
IFAIL=4
An overflow has occurred during the computation. This is an unlikely failure, but if it occurs you should restart at the latest point given in X.
IFAIL=5
IFAIL=6
IFAIL=7
IFAIL=8
There is some doubt about whether the point x found by E04KYF is a minimum. The degree of confidence in the result decreases as IFAIL increases. Thus, when IFAIL=5 it is probable that the final x gives a good estimate of the position of a minimum, but when IFAIL=8 it is very unlikely that the routine has found a minimum.
IFAIL=9
In the search for a minimum, the modulus of one of the variables has become very large ∼106. This indicates that there is a mistake in FUNCT2, that your problem has no finite solution, or that the problem needs rescaling (see Section 9).
IFAIL=10
It is very likely that you have made an error in forming the gradient.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.
If you are dissatisfied with the result (e.g., because IFAIL=5, 6, 7 or 8), it is worth restarting the calculations from a different starting point (not the point at which the failure occurred) in order to avoid the region which caused the failure. If persistent trouble occurs it may be advisable to try E04KZF.

7 Accuracy

A successful exit (IFAIL=0) is made from E04KYF when (B1, B2 and B3) or B4 hold, and the local search confirms a minimum, where
  • B1≡α k ×p k <xtol+ε×1.0+x k
  • B2≡F k -F k-1 <xtol 2+ε×1.0+F k
  • B3≡gz k <ε 1/3+xtol×1.0+F k
  • B4≡gz k <0.01×ε.
(Quantities with superscript k are the values at the kth iteration of the quantities mentioned in Section 3, xtol=100 ε, ε is the machine precision and . denotes the Euclidean norm. The vector gz is returned in the array W.)
If IFAIL=0, then the vector in X on exit, xsol, is almost certainly an estimate of the position of the minimum, xtrue, to the accuracy specified by xtol.
If IFAIL=3 or 5, xsol may still be a good estimate of xtrue, but the following checks should be made. Let k denote an estimate of the condition number of the projected Hessian matrix at xsol. (The value of k is returned in W N+1). If
(i) | the sequence F x k converges to F xsol at a superlinear or a fast linear rate,
(ii) | gz xxol 2<10.0×ε and
(iii) | k<1.0/gz xsol,
then it is almost certain that xsol is a close approximation to the position of a minimum. When (ii) is true, then usually F xsol is a close approximation to F xtrue.
When a successful exit is made then, for a computer with a mantissa of t decimals, one would expect to get about t/2-1 decimals accuracy in x, and about t-1 decimals accuracy in F, provided the problem is reasonably well scaled.

8 Parallelism and Performance

E04KYF is not threaded in any implementation.

9 Further Comments

The number of iterations required depends on the number of variables, the behaviour of F x and the distance of the starting point from the solution. The number of operations performed in an iteration of E04KYF is roughly proportional to n 2. In addition, each iteration makes at least one call of FUNCT2. So, unless F x and the gradient vector can be evaluated very quickly, the run time will be dominated by the time spent in FUNCT2.
Ideally the problem should be scaled so that at the solution the value of F x and the corresponding values of x 1,x 2,…,xn are each in the range -1,+1, and so that at points a unit distance away from the solution, F is approximately a unit value greater than at the minimum. It is unlikely that you will be able to follow these recommendations very closely, but it is worth trying (by guesswork), as sensible scaling will reduce the difficulty of the minimization problem, so that E04KYF will take less computer time.

10 Example

A program to minimize
F= x 1+10 x 2 2+5⁢ x 3-x 4 2+ x 2-2 x 3 4+10⁢ x 1-x 4 4
subject to
-1≤x 1≤ 3, -2≤x 2≤ 0, -1≤x 4≤ 3,
starting from the initial guess 3,-1,0,1 .

10.1 Program Text

Program Text (e04kyfe.f90)

10.2 Program Data

None.

10.3 Program Results

Program Results (e04kyfe.r)

E04 Chapter Contents
E04 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


E04KZF : NAG Library, Mark 26

E04 Chapter Contents
E04 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

E04KZF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

E04KZF is an easy-to-use modified Newton algorithm for finding a minimum of a function F x 1,x 2,…,xn, subject to fixed upper and lower bounds on the independent variables x 1,x 2,…,xn, when first derivatives of F are available. It is intended for functions which are continuous and which have continuous first and second derivatives (although it will usually work even if the derivatives have occasional discontinuities).

2 Specification

SUBROUTINE E04KZF ( N, IBOUND, FUNCT2, BL, BU, X, F, G, IW, LIW, W, LW, IUSER, RUSER, IFAIL)
INTEGER | N, IBOUND, IW(LIW), LIW, LW, IUSER(*), IFAIL
REAL (KIND=nag_wp) | BL(N), BU(N), X(N), F, G(N), W(LW), RUSER(*)
EXTERNAL | FUNCT2

3 Description

E04KZF is applicable to problems of the form:
Minimize⁡F x 1,x 2,…,xn  subject to  lj≤xj≤uj,  j=1,2,…,n
when first derivatives are known.
Special provision is made for problems which actually have no bounds on the xj, problems which have only non-negativity bounds, and problems in which l 1=l 2=⋯=ln and u 1=u 2=⋯=un. You must supply a subroutine to calculate the values of F x and its first derivatives at any point x.
From a starting point you supplied there is generated, on the basis of estimates of the gradient of the curvature of F x, a sequence of feasible points which is intended to converge to a local minimum of the constrained function.

4 References

Gill P E and Murray W (1976) Minimization subject to bounds on the variables NPL Report NAC 72 National Physical Laboratory

5 Arguments

1:   N – INTEGERInput
On entry: the number n of independent variables.
Constraint: N≥1.
2:   IBOUND – INTEGERInput
On entry: indicates whether the facility for dealing with bounds of special forms is to be used. It must be set to one of the following values:
IBOUND=0
If you are supplying all the lj and uj individually.
IBOUND=1
If there are no bounds on any xj.
IBOUND=2
If all the bounds are of the form 0≤xj.
IBOUND=3
If l 1=l 2=⋯=ln and u 1=u 2=⋯=un.
Constraint: 0≤IBOUND≤3.
3:   FUNCT2 – SUBROUTINE, supplied by the user.External Procedure
You must supply this routine to calculate the values of the function F x and its first derivatives ∂F ∂xj at any point x. It should be tested separately before being used in conjunction with E04KZF (see Chapter E04).
The specification of FUNCT2 is:
SUBROUTINE FUNCT2 ( N, XC, FC, GC, IUSER, RUSER)
INTEGER | N, IUSER(*)
REAL (KIND=nag_wp) | XC(N), FC, GC(N), RUSER(*)
1:   N – INTEGERInput
On entry: the number n of variables.
2:   XC N – REAL (KIND=nag_wp) arrayInput
On entry: the point x at which the function and derivatives are required.
3:   FC – REAL (KIND=nag_wp)Output
On exit: the value of the function F at the current point x,
4:   GC N – REAL (KIND=nag_wp) arrayOutput
On exit: GC j must be set to the value of the first derivative ∂F ∂xj at the point x, for j=1,2,…,n.
5:   IUSER* – INTEGER arrayUser Workspace
6:   RUSER* – REAL (KIND=nag_wp) arrayUser Workspace
FUNCT2 is called with the arguments IUSER and RUSER as supplied to E04KZF. You are free to use the arrays IUSER and RUSER to supply information to FUNCT2 as an alternative to using COMMON global variables.
FUNCT2 must either be a module subprogram USEd by, or declared as EXTERNAL in, the (sub)program from which E04KZF is called. Arguments denoted as Input must not be changed by this procedure.
4:   BL N – REAL (KIND=nag_wp) arrayInput/Output
On entry: the lower bounds lj.
If IBOUND is set to 0, you must set BL j to lj, for j=1,2,…,n. (If a lower bound is not specified for a particular xj, the corresponding BL j should be set to -106.)
If IBOUND is set to 3, you must set BL 1 to l 1; E04KZF will then set the remaining elements of BL equal to BL 1.
On exit: the lower bounds actually used by E04KZF.
5:   BU N – REAL (KIND=nag_wp) arrayInput/Output
On entry: the upper bounds uj.
If IBOUND is set to 0, you must set BU j to uj, for j=1,2,…,n. (If an upper bound is not specified for a particular xj, the corresponding BU j should be set to 106.)
If IBOUND is set to 3, you must set BU 1 to u 1; E04KZF will then set the remaining elements of BU equal to BU 1.
On exit: the upper bounds actually used by E04KZF.
6:   X N – REAL (KIND=nag_wp) arrayInput/Output
On entry: X j must be set to a guess at the jth component of the position of the minimum, for j=1,2,…,n. The routine checks the gradient at the starting point, and is more likely to detect any error in your programming if the initial X j are nonzero and mutually distinct.
On exit: the lowest point found during the calculations of the position of the minimum.
7:   F – REAL (KIND=nag_wp)Output
On exit: the value of F x corresponding to the final point stored in X.
8:   G N – REAL (KIND=nag_wp) arrayOutput
On exit: the value of ∂F ∂xj corresponding to the final point stored in X, for j=1,2,…,n; the value of G j for variables not on a bound should normally be close to zero.
9:   IW LIW – INTEGER arrayWorkspace
10:   LIW – INTEGERInput
On entry: the dimension of the array IW as declared in the (sub)program from which E04KZF is called.
Constraint: LIW≥N+2.
11:   W LW – REAL (KIND=nag_wp) arrayWorkspace
12:   LW – INTEGERInput
On entry: the dimension of the array W as declared in the (sub)program from which E04KZF is called.
Constraint: LW≥max N×N+7,10.
13:   IUSER* – INTEGER arrayUser Workspace
14:   RUSER* – REAL (KIND=nag_wp) arrayUser Workspace
IUSER and RUSER are not used by E04KZF, but are passed directly to FUNCT2 and may be used to pass information to this routine as an alternative to using COMMON global variables.
15:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, because for this routine the values of the output arguments may be useful even if IFAIL≠0 on exit, the recommended value is -1. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Note: E04KZF may return useful information for one or more of the following detected errors or warnings.
Errors or warnings detected by the routine:
IFAIL=1
On entry, | N<1,
or | IBOUND<0,
or | IBOUND>3,
or | IBOUND=0 and BL j>BU j for some j,
or | IBOUND=3 and BL 1>BU 1,
or | LIW<N+2,
or | LW<max 10,N×N+7.
IFAIL=2
There has been a large number of function evaluations, yet the algorithm does not seem to be converging. The calculations can be restarted from the final point held in X. The error may also indicate that F x has no minimum.
IFAIL=3
The conditions for a minimum have not all been met but a lower point could not be found and the algorithm has failed.
IFAIL=4
Not used. (This value of the argument is included to make the significance of IFAIL=5 etc. consistent in the easy-to-use routines.)
IFAIL=5
IFAIL=6
IFAIL=7
IFAIL=8
There is some doubt about whether the point x found by E04KZF is a minimum. The degree of confidence in the result decreases as IFAIL increases. Thus, when IFAIL=5 it is probable that the final x gives a good estimate of the position of a minimum, but when IFAIL=8 it is very unlikely that the routine has found a minimum.
IFAIL=9
In the search for a minimum, the modulus of one of the variables has become very large ∼106. This indicates that there is a mistake in FUNCT2, that your problem has no finite solution, or that the problem needs rescaling (see Section 9).
IFAIL=10
It is very likely that you have made an error in forming the gradient.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.
If you are dissatisfied with the result (e.g., because IFAIL=5, 6, 7 or 8), it is worth restarting the calculations from a different starting point (not the point at which the failure occurred) in order to avoid the region which caused the failure. If persistent trouble occurs and it is possible to calculate second derivatives it may be advisable to change to a routine which uses second derivatives (see the E04 Chapter Introduction).

7 Accuracy

When a successful exit is made then, for a computer with a mantissa of t decimals, one would expect to get about t/2-1 decimals accuracy in x and about t-1 decimals accuracy in F, provided the problem is reasonably well scaled.

8 Parallelism and Performance

E04KZF is not threaded in any implementation.

9 Further Comments

The number of iterations required depends on the number of variables, the behaviour of F x and the distance of the starting point from the solution. The number of operations performed in an iteration of E04KZF is roughly proportional to n 3+O n 2. In addition, each iteration makes at least m+1 calls of FUNCT2 where m is the number of variables not fixed on bounds. So unless F x and the gradient vector can be evaluated very quickly, the run time will be dominated by the time spent in FUNCT2.
Ideally the problem should be scaled so that at the solution the value of F x and the corresponding values of x 1,x 2,…,xn are in the range -1,+1, and so that at points a unit distance away from the solution, F is approximately a unit value greater than at the minimum. It is unlikely that you will be able to follow these recommendations very closely, but it is worth trying (by guesswork), as sensible scaling will reduce the difficulty of the minimization problem, so that E04KZF will take less computer time.

10 Example

A program to minimize
F= x 1+10 x 2 2+5⁢ x 3-x 4 2+ x 2-2 x 3 4+10⁢ x 1-x 4 4
subject to
1 ≤ x 1 ≤ 3 -2 ≤ x 2 ≤ 0 1 ≤ x 4 ≤ 3
starting from the initial guess 3,-1,0,1 .
In practice, it is worth trying to make FUNCT2 as efficient as possible. This has not been done in the example program for reasons of clarity.

10.1 Program Text

Program Text (e04kzfe.f90)

10.2 Program Data

None.

10.3 Program Results

Program Results (e04kzfe.r)

E04 Chapter Contents
E04 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


E04LBF : NAG Library, Mark 26

E04 Chapter Contents
E04 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

E04LBF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
▸▿ 9 Further Comments
9.1 Timing
9.2 Scaling
9.3 Unconstrained Minimization
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

E04LBF is a comprehensive modified Newton algorithm for finding:
  • an unconstrained minimum of a function of several variables
  • a minimum of a function of several variables subject to fixed upper and/or lower bounds on the variables.
First and second derivatives are required. The routine is intended for functions which have continuous first and second derivatives (although it will usually work even if the derivatives have occasional discontinuities).

2 Specification

SUBROUTINE E04LBF ( N, FUNCT, H, MONIT, IPRINT, MAXCAL, ETA, XTOL, STEPMX, IBOUND, BL, BU, X, HESL, LH, HESD, ISTATE, F, G, IW, LIW, W, LW, IFAIL)
INTEGER | N, IPRINT, MAXCAL, IBOUND, LH, ISTATE(N), IW(LIW), LIW, LW, IFAIL
REAL (KIND=nag_wp) | ETA, XTOL, STEPMX, BL(N), BU(N), X(N), HESL(LH), HESD(N), F, G(N), W(LW)
EXTERNAL | FUNCT, H, MONIT

3 Description

E04LBF is applicable to problems of the form:
MinimizeF x 1,x 2,…,xn subject to ​lj≤xj≤uj,  j=1,2,…,n.
Special provision is made for unconstrained minimization (i.e., problems which actually have no bounds on the xj), problems which have only non-negativity bounds, and problems in which l 1=l 2=⋯=ln and u 1=u 2=⋯=un. It is possible to specify that a particular xj should be held constant. You must supply a starting point, a FUNCT to calculate the value of F x and its first derivatives ∂F ∂xj at any point x, and a H to calculate the second derivatives ∂2 F ∂xi∂xj .
A typical iteration starts at the current point x where nz (say) variables are free from both their bounds. The vector of first derivatives of F x with respect to the free variables, gz, and the matrix of second derivatives with respect to the free variables, H, are obtained. (These both have dimension nz.)
The equations
H+E pz=-gz
are solved to give a search direction pz. (The matrix E is chosen so that H+E is positive definite.)
pz is then expanded to an n-vector p by the insertion of appropriate zero elements; α is found such that F x+αp is approximately a minimum (subject to the fixed bounds) with respect to α, and x is replaced by x+αp. (If a saddle point is found, a special search is carried out so as to move away from the saddle point.)
If any variable actually reaches a bound, it is fixed and nz is reduced for the next iteration.
There are two sets of convergence criteria – a weaker and a stronger. Whenever the weaker criteria are satisfied, the Lagrange multipliers are estimated for all active constraints. If any Lagrange multiplier estimate is significantly negative, then one of the variables associated with a negative Lagrange multiplier estimate is released from its bound and the next search direction is computed in the extended subspace (i.e., nz is increased). Otherwise, minimization continues in the current subspace until the stronger criteria are satisfied. If at this point there are no negative or near-zero Lagrange multiplier estimates, the process is terminated.
If you specify that the problem is unconstrained, E04LBF sets the lj to -106 and the uj to 106. Thus, provided that the problem has been sensibly scaled, no bounds will be encountered during the minimization process and E04LBF will act as an unconstrained minimization algorithm.

4 References

Gill P E and Murray W (1973) Safeguarded steplength algorithms for optimization using descent methods NPL Report NAC 37 National Physical Laboratory
Gill P E and Murray W (1974) Newton-type methods for unconstrained and linearly constrained optimization Math. Programming 7 311–350
Gill P E and Murray W (1976) Minimization subject to bounds on the variables NPL Report NAC 72 National Physical Laboratory

5 Arguments

1:   N – INTEGERInput
On entry: the number n of independent variables.
Constraint: N≥1.
2:   FUNCT – SUBROUTINE, supplied by the user.External Procedure
FUNCT must evaluate the function F x and its first derivatives ∂F ∂xj at any point x. (However, if you do not wish to calculate F x or its first derivatives at a particular x, there is the option of setting an argument to cause E04LBF to terminate immediately.)
The specification of FUNCT is:
SUBROUTINE FUNCT ( IFLAG, N, XC, FC, GC, IW, LIW, W, LW)
INTEGER | IFLAG, N, IW(LIW), LIW, LW
REAL (KIND=nag_wp) | XC(N), FC, GC(N), W(LW)
1:   IFLAG – INTEGERInput/Output
On entry: will have been set to 2.
On exit: if it is not possible to evaluate F x or its first derivatives at the point x given in XC (or if it is wished to stop the calculation for any other reason) you should reset IFLAG to some negative number and return control to E04LBF. E04LBF will then terminate immediately with IFAIL set to your setting of IFLAG.
2:   N – INTEGERInput
On entry: the number n of variables.
3:   XC N – REAL (KIND=nag_wp) arrayInput
On entry: the point x at which F and the ∂F ∂xj are required.
4:   FC – REAL (KIND=nag_wp)Output
On exit: unless IFLAG is reset, FUNCT must set FC to the value of the objective function F at the current point x.
5:   GC N – REAL (KIND=nag_wp) arrayOutput
On exit: unless IFLAG is reset, FUNCT must set GC j to the value of the first derivative ∂F ∂xj at the point x, for j=1,2,…,n.
6:   IW LIW – INTEGER arrayWorkspace
7:   LIW – INTEGERInput
8:   W LW – REAL (KIND=nag_wp) arrayWorkspace
9:   LW – INTEGERInput
FUNCT is called with the same arguments IW, LIW, W and LW as for E04LBF. They are present so that, when other library routines require the solution of a minimization subproblem, constants needed for the function evaluation can be passed through IW and W. Similarly, you could use elements 3,4,…,LIW of IW and elements from max 8,7×N+N×N-1/2+1 onwards of W for passing quantities to FUNCT from the subroutine which calls E04LBF. However, because of the danger of mistakes in partitioning, it is recommended that you should pass information to FUNCT via COMMON global variables and not use IW or W at all. In any case FUNCT must not change the first 2 elements of IW or the first max 8,7×N+N×N-1/2 elements of W.
FUNCT must either be a module subprogram USEd by, or declared as EXTERNAL in, the (sub)program from which E04LBF is called. Arguments denoted as Input must not be changed by this procedure.
Note: FUNCT should be tested separately before being used in conjunction with E04LBF.
3:   H – SUBROUTINE, supplied by the user.External Procedure
H must calculate the second derivatives of F at any point x. (As with FUNCT, there is the option of causing E04LBF to terminate immediately.)
The specification of H is:
SUBROUTINE H ( IFLAG, N, XC, FHESL, LH, FHESD, IW, LIW, W, LW)
INTEGER | IFLAG, N, LH, IW(LIW), LIW, LW
REAL (KIND=nag_wp) | XC(N), FHESL(LH), FHESD(N), W(LW)
1:   IFLAG – INTEGERInput/Output
On entry: is set to a non-negative number.
On exit: if H resets IFLAG to some negative number, E04LBF will terminate immediately with IFAIL set to your setting of IFLAG.
2:   N – INTEGERInput
On entry: the number n of variables.
3:   XC N – REAL (KIND=nag_wp) arrayInput
On entry: the point x at which the second derivatives of F are required.
4:   FHESL LH – REAL (KIND=nag_wp) arrayOutput
On exit: unless IFLAG is reset, H must place the strict lower triangle of the second derivative matrix of F (evaluated at the point x) in FHESL, stored by rows, i.e., set FHESL i -1 i -2 / 2 +j = ∂ 2 F ∂ x i ∂ x j XC , for i=2,3,…,n and j=1,2,…,i-1. (The upper triangle is not required because the matrix is symmetric.)
5:   LH – INTEGERInput
On entry: the length of the array FHESL.
6:   FHESD N – REAL (KIND=nag_wp) arrayInput/Output
On entry: the value of ∂F ∂xj at the point x, for j=1,2,…,n.
These values may be useful in the evaluation of the second derivatives.
On exit: unless IFLAG is reset, H must place the diagonal elements of the second derivative matrix of F (evaluated at the point x) in FHESD, i.e., set FHESD j = ∂ 2 F ∂ x j 2 XC , j=1,2,…,n.
7:   IW LIW – INTEGER arrayWorkspace
8:   LIW – INTEGERInput
9:   W LW – REAL (KIND=nag_wp) arrayWorkspace
10:   LW – INTEGERInput
As in FUNCT, these arguments correspond to the arguments IW, LIW, W, LW of E04LBF. H must not change the first two elements of IW or the first max 8,7×N+N×N-1/2 elements of W. Again, it is recommended that you should pass quantities to H via COMMON global variables and not use IW or W at all.
H must either be a module subprogram USEd by, or declared as EXTERNAL in, the (sub)program from which E04LBF is called. Arguments denoted as Input must not be changed by this procedure.
Note: H should be tested separately before being used in conjunction with E04LBF.
4:   MONIT – SUBROUTINE, supplied by the user.External Procedure
If IPRINT≥0, you must supply MONIT which is suitable for monitoring the minimization process. MONIT must not change the values of any of its arguments.
If IPRINT<0, a MONIT with the correct argument list should still be supplied, although it will not be called.
The specification of MONIT is:
SUBROUTINE MONIT ( N, XC, FC, GC, ISTATE, GPJNRM, COND, POSDEF, NITER, NF, IW, LIW, W, LW)
INTEGER | N, ISTATE(N), NITER, NF, IW(LIW), LIW, LW
REAL (KIND=nag_wp) | XC(N), FC, GC(N), GPJNRM, COND, W(LW)
LOGICAL | POSDEF
1:   N – INTEGERInput
On entry: the number n of variables.
2:   XC N – REAL (KIND=nag_wp) arrayInput
On entry: the coordinates of the current point x.
3:   FC – REAL (KIND=nag_wp)Input
On entry: the value of F x at the current point x.
4:   GC N – REAL (KIND=nag_wp) arrayInput
On entry: the value of ∂F ∂xj at the current point x, for j=1,2,…,n.
5:   ISTATE N – INTEGER arrayInput
On entry: information about which variables are currently fixed on their bounds and which are free.
If ISTATE j is negative, xj is currently:
– fixed on its upper bound if ISTATE j=-1;
– fixed on its lower bound if ISTATE j=-2;
– effectively a constant (i.e., lj=uj) if ISTATE j=-3.
If ISTATE is positive, its value gives the position of xj in the sequence of free variables.
6:   GPJNRM – REAL (KIND=nag_wp)Input
On entry: the Euclidean norm of the projected gradient vector gz.
7:   COND – REAL (KIND=nag_wp)Input
On entry: the ratio of the largest to the smallest elements of the diagonal factor D of the projected Hessian matrix (see specification of H). This quantity is usually a good estimate of the condition number of the projected Hessian matrix. (If no variables are currently free, COND is set to zero.)
8:   POSDEF – LOGICALInput
On entry: is set .TRUE. or .FALSE. according to whether the second derivative matrix for the current subspace, H, is positive definite or not.
9:   NITER – INTEGERInput
On entry: the number of iterations (as outlined in Section 3) which have been performed by E04LBF so far.
10:   NF – INTEGERInput
On entry: the number of times that FUNCT has been called so far. Thus NF is the number of function and gradient evaluations made so far.
11:   IW LIW – INTEGER arrayWorkspace
12:   LIW – INTEGERInput
13:   W LW – REAL (KIND=nag_wp) arrayWorkspace
14:   LW – INTEGERInput
As in FUNCT, and H, these arguments correspond to the arguments IW, LIW, W, LW of E04LBF. They are included in MONIT's argument list primarily for when E04LBF is called by other library routines.
MONIT must either be a module subprogram USEd by, or declared as EXTERNAL in, the (sub)program from which E04LBF is called. Arguments denoted as Input must not be changed by this procedure.
You should normally print out FC, GPJNRM and COND so as to be able to compare the quantities mentioned in Section 7. It is normally helpful to examine XC, POSDEF and NF as well.
5:   IPRINT – INTEGERInput
On entry: the frequency with which MONIT is to be called.
IPRINT>0
MONIT is called once every IPRINT iterations and just before exit from E04LBF.
IPRINT=0
MONIT is just called at the final point.
IPRINT<0
MONIT is not called at all.
IPRINT should normally be set to a small positive number.
Suggested value: IPRINT=1.
6:   MAXCAL – INTEGERInput
On entry: the maximum permitted number of evaluations of F x, i.e., the maximum permitted number of calls of FUNCT.
Suggested value: MAXCAL=50×N.
Constraint: MAXCAL≥1.
7:   ETA – REAL (KIND=nag_wp)Input
On entry: every iteration of E04LBF involves a linear minimization (i.e., minimization of F x+αp with respect to α). ETA specifies how accurately these linear minimizations are to be performed. The minimum with respect to α will be located more accurately for small values of ETA (say, 0.01) than for large values (say, 0.9).
Although accurate linear minimizations will generally reduce the number of iterations of E04LBF, this usually results in an increase in the number of function and gradient evaluations required for each iteration. On balance, it is usually more efficient to perform a low accuracy linear minimization.
Suggested value: ETA=0.9 is usually a good choice although a smaller value may be warranted if the matrix of second derivatives is expensive to compute compared with the function and first derivatives.
If N=1, ETA should be set to 0.0 (also when the problem is effectively one-dimensional even though n>1; i.e., if for all except one of the variables the lower and upper bounds are equal).
Constraint: 0.0≤ETA<1.0.
8:   XTOL – REAL (KIND=nag_wp)Input
On entry: the accuracy in x to which the solution is required.
If xtrue is the true value of x at the minimum, then xsol, the estimated position before a normal exit, is such that xsol-xtrue<XTOL×1.0+xtrue, where y=∑j=1 n yj 2. For example, if the elements of xsol are not much larger than 1.0 in modulus, and if XTOL is set to 10-5 then xsol is usually accurate to about five decimal places. (For further details see Section 7.)
If the problem is scaled roughly as described in Section 9 and ε is the machine precision, then ε is probably the smallest reasonable choice for XTOL. (This is because, normally, to machine accuracy, F x+ε,ej=F x where ej is any column of the identity matrix.)
If you set XTOL to 0.0 (or any positive value less than ε), E04LBF will use 10.0×ε instead of XTOL.
Suggested value: XTOL=0.0.
Constraint: XTOL≥0.0.
9:   STEPMX – REAL (KIND=nag_wp)Input
On entry: an estimate of the Euclidean distance between the solution and the starting point supplied by you. (For maximum efficiency a slight overestimate is preferable.)
E04LBF will ensure that, for each iteration,
∑j=1 n xj k -xj k-1 2 ≤STEPMX
where k is the iteration number. Thus, if the problem has more than one solution, E04LBF is most likely to find the one nearest to the starting point. On difficult problems, a realistic choice can prevent the sequence of x k entering a region where the problem is ill-behaved and can also help to avoid possible overflow in the evaluation of F x. However, an underestimate of STEPMX can lead to inefficiency.
Suggested value: STEPMX=100000.0.
Constraint: STEPMX≥XTOL.
10:   IBOUND – INTEGERInput
On entry: specifies whether the problem is unconstrained or bounded. If there are bounds on the variables, IBOUND can be used to indicate whether the facility for dealing with bounds of special forms is to be used. It must be set to one of the following values:
IBOUND=0
If the variables are bounded and you are supplying all the lj and uj individually.
IBOUND=1
If the problem is unconstrained.
IBOUND=2
If the variables are bounded, but all the bounds are of the form 0≤xj.
IBOUND=3
If all the variables are bounded, and l 1=l 2=⋯=ln and u 1=u 2=⋯=un.
IBOUND=4
If the problem is unconstrained. (The IBOUND=4 option is provided purely for consistency with other routines. In E04LBF it produces the same effect as IBOUND=1.)
Constraint: 0≤IBOUND≤4.
11:   BL N – REAL (KIND=nag_wp) arrayInput/Output
On entry: the fixed lower bounds lj.
If IBOUND is set to 0, you must set BL j to lj, for j=1,2,…,n. (If a lower bound is not specified for any xj, the corresponding BL j should be set to a large negative number, e.g., -106.)
If IBOUND is set to 3, you must set BL 1 to l 1; E04LBF will then set the remaining elements of BL equal to BL 1.
If IBOUND is set to 1, 2 or 4, BL will be initialized by E04LBF.
On exit: the lower bounds actually used by E04LBF, e.g., if IBOUND=2, BL 1=BL 2=⋯=BL n=0.0.
12:   BU N – REAL (KIND=nag_wp) arrayInput/Output
On entry: the fixed upper bounds uj.
If IBOUND is set to 0, you must set BU j to uj, for j=1,2,…,n. (If an upper bound is not specified for any variable, the corresponding BU j should be set to a large positive number, e.g., 106.)
If IBOUND is set to 3, you must set BU 1 to u 1; E04LBF will then set the remaining elements of BU equal to BU 1.
If IBOUND is set to 1, 2 or 4, BU will then be initialized by E04LBF.
On exit: the upper bounds actually used by E04LBF, e.g., if IBOUND=2, BU 1=BU 2=⋯=BU N=106.
13:   X N – REAL (KIND=nag_wp) arrayInput/Output
On entry: X j must be set to a guess at the jth component of the position of the minimum, for j=1,2,…,n.
On exit: the final point x k . Thus, if IFAIL=0 on exit, X j is the jth component of the estimated position of the minimum.
14:   HESL LH – REAL (KIND=nag_wp) arrayOutput
On exit: during the determination of a direction pz (see Section 3), H+E is decomposed into the product LD LT, where L is a unit lower triangular matrix and D is a diagonal matrix. (The matrices H, E, L and D are all of dimension nz, where nz is the number of variables free from their bounds. H consists of those rows and columns of the full estimated second derivative matrix which relate to free variables. E is chosen so that H+E is positive definite.)
HESL and HESD are used to store the factors L and D. The elements of the strict lower triangle of L are stored row by row in the first nz nz-1/2 positions of HESL. The diagonal elements of D are stored in the first nz positions of HESD. In the last factorization before a normal exit, the matrix E will be zero, so that HESL and HESD will contain, on exit, the factors of the final estimated second derivative matrix H. The elements of HESD are useful for deciding whether to accept the results produced by E04LBF (see Section 7).
15:   LH – INTEGERInput
On entry: the dimension of the array HESL as declared in the (sub)program from which E04LBF is called.
Constraint: LH≥max N×N-1/2,1.
16:   HESD N – REAL (KIND=nag_wp) arrayOutput
On exit: during the determination of a direction pz (see Section 3), H+E is decomposed into the product LD LT, where L is a unit lower triangular matrix and D is a diagonal matrix. (The matrices H, E, L and D are all of dimension nz, where nz is the number of variables free from their bounds. H consists of those rows and columns of the full second derivative matrix which relate to free variables. E is chosen so that H+E is positive definite.)
HESL and HESD are used to store the factors L and D. The elements of the strict lower triangle of L are stored row by row in the first nz nz-1/2 positions of HESL. The diagonal elements of D are stored in the first nz positions of HESD.
In the last factorization before a normal exit, the matrix E will be zero, so that HESL and HESD will contain, on exit, the factors of the final second derivative matrix H. The elements of HESD are useful for deciding whether to accept the result produced by E04LBF (see Section 7).
17:   ISTATE N – INTEGER arrayOutput
On exit: information about which variables are currently on their bounds and which are free. If ISTATE j is:
  • – equal to -1, xj is fixed on its upper bound;
  • – equal to -2, xj is fixed on its lower bound;
  • – equal to -3, xj is effectively a constant (i.e., lj=uj);
  • – positive, ISTATE j gives the position of xj in the sequence of free variables.
18:   F – REAL (KIND=nag_wp)Output
On exit: the function value at the final point given in X.
19:   G N – REAL (KIND=nag_wp) arrayOutput
On exit: the first derivative vector corresponding to the final point given in X. The components of G corresponding to free variables should normally be close to zero.
20:   IW LIW – INTEGER arrayCommunication Array
21:   LIW – INTEGERInput
On entry: the dimension of the array IW as declared in the (sub)program from which E04LBF is called.
Constraint: LIW≥2.
22:   W LW – REAL (KIND=nag_wp) arrayCommunication Array
23:   LW – INTEGERInput
On entry: the dimension of the array W as declared in the (sub)program from which E04LBF is called.
Constraint: LW≥max 7×N+N×N-1/2,8.
24:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, because for this routine the values of the output arguments may be useful even if IFAIL≠0 on exit, the recommended value is -1. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Note: E04LBF may return useful information for one or more of the following detected errors or warnings.
Errors or warnings detected by the routine:
IFAIL<0
A negative value of IFAIL indicates an exit from E04LBF because you have set IFLAG negative in FUNCT or H. The value of IFAIL will be the same as your setting of IFLAG.
IFAIL=1
On entry, | N<1,
or | MAXCAL<1,
or | ETA<0.0,
or | ETA≥1.0,
or | XTOL<0.0,
or | STEPMX<XTOL,
or | IBOUND<0,
or | IBOUND>4,
or | BL j>BU j for some j if IBOUND=0,
or | BL 1>BU 1 if IBOUND=3,
or | LH < max 1,N×N-1/2 ,
or | LIW<2,
or | LW < max 8,7×N+N×N-1/2 .
(Note that if you have set XTOL to 0.0, E04LBF uses the default value and continues without failing.) When this exit occurs no values will have been assigned to F or to the elements of HESL, HESD or G.
IFAIL=2
There have been MAXCAL function evaluations. If steady reductions in F x were monitored up to the point where this exit occurred, then the exit probably occurred simply because MAXCAL was set too small, so the calculations should be restarted from the final point held in X. This exit may also indicate that F x has no minimum.
IFAIL=3
The conditions for a minimum have not all been met, but a lower point could not be found.
Provided that, on exit, the first derivatives of F x with respect to the free variables are sufficiently small, and that the estimated condition number of the second derivative matrix is not too large, this error exit may simply mean that, although it has not been possible to satisfy the specified requirements, the algorithm has in fact found the minimum as far as the accuracy of the machine permits. Such a situation can arise, for instance, if XTOL has been set so small that rounding errors in the evaluation of F x or its derivatives make it impossible to satisfy the convergence conditions.
If the estimated condition number of the second derivative matrix at the final point is large, it could be that the final point is a minimum, but that the smallest eigenvalue of the Hessian matrix is so close to zero that it is not possible to recognize the point as a minimum.
IFAIL=4
Not used. (This is done to make the significance of IFAIL=5 similar for E04KDF and E04LBF.)
IFAIL=5
All the Lagrange multiplier estimates which are not indisputably positive lie relatively close to zero, but it is impossible either to continue minimizing on the current subspace or to find a feasible lower point by releasing and perturbing any of the fixed variables. You should investigate as for IFAIL=3.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.
The values IFAIL=2, 3 or 5 may also be caused by mistakes in user-supplied subroutines FUNCT or H, by the formulation of the problem or by an awkward function. If there are no such mistakes, it is worth restarting the calculations from a different starting point (not the point at which the failure occurred) in order to avoid the region which caused the failure.

7 Accuracy

A successful exit (IFAIL=0) is made from E04LBF when H k is positive definite and when (B1, B2 and B3) or B4 hold, where
B1 ≡ α k ×p k <XTOL+ε×1.0+x k B2 ≡ F k -F k-1 <XTOL 2+ε×1.0+F k B3 ≡ gz k <ε 1/3+XTOL×1.0+F k B4 ≡ gz k <0.01×ε.
(Quantities with superscript k are the values at the kth iteration of the quantities mentioned in Section 3. ε is the machine precision and . denotes the Euclidean norm.)
If IFAIL=0, then the vector in X on exit, xsol, is almost certainly an estimate of the position of the minimum, xtrue, to the accuracy specified by XTOL.
If IFAIL=3 or 5, xsol may still be a good estimate of xtrue, but the following checks should be made. Let the largest of the first nz elements of HESD be HESD b, let the smallest be HESD s, and define k=HESD b/HESD s. The scalar k is usually a good estimate of the condition number of the projected Hessian matrix at xsol. If
(i) | the sequence F x k converges to F xsol at a superlinear or fast linear rate,
(ii) | gz xsol 2<10.0×ε, and
(iii) | k<1.0/gz xsol,
then it is almost certain that xsol is a close approximation to the position of a minimum. When (ii) is true, then usually F xsol is a close approximation to F xtrue. The quantities needed for these checks are all available via MONIT; in particular the value of COND in the last call of MONIT before exit gives k.
Further suggestions about confirmation of a computed solution are given in the E04 Chapter Introduction.

8 Parallelism and Performance

E04LBF is not threaded in any implementation.

9 Further Comments

9.1 Timing

The number of iterations required depends on the number of variables, the behaviour of F x, the accuracy demanded and the distance of the starting point from the solution. The number of multiplications performed in an iteration of E04LBF is nz 3 6+O nz 2. In addition, each iteration makes one call of H and at least one call of FUNCT. So, unless F x and its derivatives can be evaluated very quickly, the run time will be dominated by the time spent in FUNCT and H.

9.2 Scaling

Ideally, the problem should be scaled so that, at the solution, F x and the corresponding values of the xj are each in the range -1,+1, and so that at points one unit away from the solution, F x differs from its value at the solution by approximately one unit. This will usually imply that the Hessian matrix at the solution is well-conditioned. It is unlikely that you will be able to follow these recommendations very closely, but it is worth trying (by guesswork), as sensible scaling will reduce the difficulty of the minimization problem, so that E04LBF will take less computer time.

9.3 Unconstrained Minimization

If a problem is genuinely unconstrained and has been scaled sensibly, the following points apply:
(a) | nz will always be n,
(b) | HESL and HESD will be factors of the full second derivative matrix with elements stored in the natural order,
(c) | the elements of g should all be close to zero at the final point,
(d) | the values of the ISTATE j given by MONIT and on exit from E04LBF are unlikely to be of interest (unless they are negative, which would indicate that the modulus of one of the xj has reached 106 for some reason),
(e) | MONIT's argument GPJNRM simply gives the norm of the first derivative vector.
So the following routine (in which partitions of extended workspace arrays are used as BL, BU and ISTATE) could be used for unconstrained problems:
      SUBROUTINE UNCLBF(N,FUNCT,H,MONIT,IPRINT,MAXCAL,ETA,XTOL,          &
                        STEPMX,X,HESL,LH,HESD,F,G,IWORK,LIWORK,WORK,     &
                        LWORK,IFAIL)

!     A ROUTINE TO APPLY E04LBF TO UNCONSTRAINED PROBLEMS.

!     THE REAL ARRAY WORK MUST BE OF DIMENSION AT LEAST
!     (9*N + MAX(1, N*(N-1)/2)).  ITS FIRST 7*N + MAX(1, N*(N-1)/2)
!     ELEMENTS WILL BE USED BY E04LBF AS THE ARRAY W.  ITS LAST
!     2*N ELEMENTS WILL BE USED AS THE ARRAYS BL AND BU.

!     THE INTEGER ARRAY IWORK MUST BE OF DIMENSION AT LEAST (N+2)
!     ITS FIRST 2 ELEMENTS WILL BE USED BY E04LBF AS THE ARRAY IW.
!     ITS LAST N ELEMENTS WILL BE USED AS THE ARRAY ISTATE.

!     LIWORK AND LWORK MUST BE SET TO THE ACTUAL LENGTHS OF IWORK
!     AND WORK RESPECTIVELY, AS DECLARED IN THE CALLING SEGMENT.

!     OTHER PARAMETERS ARE AS FOR E04LBF.

!     ..  Parameters ..
      INTEGER NOUT
      PARAMETER (NOUT=6)
!     ..  Scalar Arguments ..
      REAL (KIND=nag_wp) ETA, F, STEPMX, XTOL
      INTEGER            IFAIL, IPRINT, LH, LIWORK, LWORK, MAXCAL, N
!     ..  Array Arguments ..
      REAL (KIND=nag_wp) G(N), HESD(N), HESL(LH), WORK(LWORK), X(N)
      INTEGER            IWORK(LIWORK)
!     ..  Subroutine Arguments ..
      EXTERNAL FUNCT, H, MONIT
!     ..  Local Scalars ..
      INTEGER IBOUND, J, JBL, JBU, NH
      LOGICAL TOOBIG
!     ..  External Subroutines ..
      EXTERNAL E04LBF
!     ..  Executable Statements ..
!     CHECK THAT SUFFICIENT WORKSPACE HAS BEEN SUPPLIED
      NH = N*(N-1)/2
      IF (NH.EQ.0) NH = 1
      IF (LWORK.LT.9*N+NH .OR.  LIWORK.LT.N+2) THEN
      WRITE (NOUT,FMT=99999)
      STOP
      END IF
!     JBL AND JBU SPECIFY THE PARTS OF WORK USED AS BL AND BU
      JBL = 7*N + NH + 1
      JBU = JBL + N
!     SPECIFY THAT THE PROBLEM IS UNCONSTRAINED
      IBOUND = 4
      CALL E04LBF(N,FUNCT,H,MONIT,IPRINT,MAXCAL,ETA,XTOL,STEPMX,         &
                  IBOUND,WORK(JBL),WORK(JBU),X,HESL,LH,HESD,IWORK(3),    &
               F,G,IWORK,LIWORK,WORK,LWORK,IFAIL)
!     CHECK THE PART OF IWORK WHICH WAS USED AS ISTATE IN CASE
!     THE MODULUS OF SOME X(J) HAS REACHED E+6
      TOOBIG = .FALSE.
      DO 20 J = 1, N
         IF (IWORK(2+J).LT.0) TOOBIG = .TRUE.
   20 CONTINUE
      IF ( .NOT.  TOOBIG) RETURN
      WRITE (NOUT,FMT=99998)
      STOP

99999 FORMAT (' ***** INSUFFICIENT WORKSPACE HAS BEEN SUPPLIED *****')
99998 FORMAT (' ***** A VARIABLE HAS REACHED E+6 IN MODULUS - NO UNCON', &
              'STRAINED MINIMUM HAS BEEN FOUND *****')
      END

10 Example

A program to minimize
F= x 1+10 x 2 2+5⁢ x 3-x 4 2+ x 2-2 x 3 4+10⁢ x 1-x 4 4
subject to the bounds
1 ≤ x 1 ≤ 3 -2 ≤ x 2 ≤ 0 1 ≤ x 4 ≤ 3.
starting from the initial guess 3,-1,0,1 . Before calling E04LBF, the program calls E04HCF and E04HDF to check the derivatives calculated by user-supplied subroutines FUNCT and H.

10.1 Program Text

Program Text (e04lbfe.f90)

10.2 Program Data

None.

10.3 Program Results

Program Results (e04lbfe.r)

E04 Chapter Contents
E04 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


E04LYF : NAG Library, Mark 26

E04 Chapter Contents
E04 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

E04LYF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

E04LYF is an easy-to-use modified-Newton algorithm for finding a minimum of a function, F x 1,x 2,…,xn subject to fixed upper and lower bounds on the independent variables, x 1,x 2,…,xn when first and second derivatives of F are available. It is intended for functions which are continuous and which have continuous first and second derivatives (although it will usually work even if the derivatives have occasional discontinuities).

2 Specification

SUBROUTINE E04LYF ( N, IBOUND, FUNCT2, HESS2, BL, BU, X, F, G, IW, LIW, W, LW, IUSER, RUSER, IFAIL)
INTEGER | N, IBOUND, IW(LIW), LIW, LW, IUSER(*), IFAIL
REAL (KIND=nag_wp) | BL(N), BU(N), X(N), F, G(N), W(LW), RUSER(*)
EXTERNAL | FUNCT2, HESS2

3 Description

E04LYF is applicable to problems of the form:
Minimize⁡F x 1,x 2,…,xn  subject to  lj≤xj≤uj,  j=1,2,…,n
when first and second derivatives of F x are available.
Special provision is made for problems which actually have no bounds on the xj, problems which have only non-negativity bounds and problems in which l 1=l 2=⋯=ln and u 1=u 2=⋯=un. You must supply a subroutine to calculate the values of F x and its first derivatives at any point x and a subroutine to calculate the second derivatives.
From a starting point you supplied there is generated, on the basis of estimates of the curvature of F x, a sequence of feasible points which is intended to converge to a local minimum of the constrained function.

4 References

Gill P E and Murray W (1976) Minimization subject to bounds on the variables NPL Report NAC 72 National Physical Laboratory

5 Arguments

1:   N – INTEGERInput
On entry: the number n of independent variables.
Constraint: N≥1.
2:   IBOUND – INTEGERInput
On entry: indicates whether the facility for dealing with bounds of special forms is to be used. It must be set to one of the following values:
IBOUND=0
If you are supplying all the lj and uj individually.
IBOUND=1
If there are no bounds on any xj.
IBOUND=2
If all the bounds are of the form 0≤xj.
IBOUND=3
If l 1=l 2=⋯=ln and u 1=u 2=⋯=un.
Constraint: 0≤IBOUND≤3.
3:   FUNCT2 – SUBROUTINE, supplied by the user.External Procedure
You must supply this routine to calculate the values of the function F x and its first derivatives ∂F ∂xj at any point x. It should be tested separately before being used in conjunction with E04LYF (see the E04 Chapter Introduction).
The specification of FUNCT2 is:
SUBROUTINE FUNCT2 ( N, XC, FC, GC, IUSER, RUSER)
INTEGER | N, IUSER(*)
REAL (KIND=nag_wp) | XC(N), FC, GC(N), RUSER(*)
1:   N – INTEGERInput
On entry: the number n of variables.
2:   XC N – REAL (KIND=nag_wp) arrayInput
On entry: the point x at which the function and its derivatives are required.
3:   FC – REAL (KIND=nag_wp)Output
On exit: the value of the function F at the current point x.
4:   GC N – REAL (KIND=nag_wp) arrayOutput
On exit: GC j must be set to the value of the first derivative ∂F ∂xj at the point x, for j=1,2,…,n.
5:   IUSER* – INTEGER arrayUser Workspace
6:   RUSER* – REAL (KIND=nag_wp) arrayUser Workspace
FUNCT2 is called with the arguments IUSER and RUSER as supplied to E04LYF. You are free to use the arrays IUSER and RUSER to supply information to FUNCT2 as an alternative to using COMMON global variables.
FUNCT2 must either be a module subprogram USEd by, or declared as EXTERNAL in, the (sub)program from which E04LYF is called. Arguments denoted as Input must not be changed by this procedure.
4:   HESS2 – SUBROUTINE, supplied by the user.External Procedure
You must supply this routine to evaluate the elements H ij= ∂2 F ∂xi∂xj of the matrix of second derivatives of F x at any point x. It should be tested separately before being used in conjunction with E04LYF (see the E04 Chapter Introduction).
The specification of HESS2 is:
SUBROUTINE HESS2 ( N, XC, HESLC, LH, HESDC, IUSER, RUSER)
INTEGER | N, LH, IUSER(*)
REAL (KIND=nag_wp) | XC(N), HESLC(LH), HESDC(N), RUSER(*)
1:   N – INTEGERInput
On entry: the number n of variables.
2:   XC N – REAL (KIND=nag_wp) arrayInput
On entry: the point x at which the derivatives are required.
3:   HESLC LH – REAL (KIND=nag_wp) arrayOutput
On exit: HESS2 must place the strict lower triangle of the second derivative matrix H in HESLC, stored by rows, i.e., set HESLC i-1i-2/2+j= ∂2 F ∂xi∂xj , for i=2,3,…,n and j=1,2,…,i-1. (The upper triangle is not required because the matrix is symmetric.)
4:   LH – INTEGERInput
On entry: the length of the array HESLC.
5:   HESDC N – REAL (KIND=nag_wp) arrayOutput
On exit: must contain the diagonal elements of the second derivative matrix, i.e., set HESDC j= ∂2 F ∂xj 2 , for j=1,2,…,n.
6:   IUSER* – INTEGER arrayUser Workspace
7:   RUSER* – REAL (KIND=nag_wp) arrayUser Workspace
HESS2 is called with the arguments IUSER and RUSER as supplied to E04LYF. You are free to use the arrays IUSER and RUSER to supply information to HESS2 as an alternative to using COMMON global variables.
HESS2 must either be a module subprogram USEd by, or declared as EXTERNAL in, the (sub)program from which E04LYF is called. Arguments denoted as Input must not be changed by this procedure.
5:   BL N – REAL (KIND=nag_wp) arrayInput/Output
On entry: the lower bounds lj.
If IBOUND is set to 0, BL j must be set to lj, for j=1,2,…,n. (If a lower bound is not specified for any xj, the corresponding BL j should be set to -106.)
If IBOUND is set to 3, you must set BL 1 to l 1; E04LYF will then set the remaining elements of BL equal to BL 1.
On exit: the lower bounds actually used by E04LYF.
6:   BU N – REAL (KIND=nag_wp) arrayInput/Output
On entry: the upper bounds uj.
If IBOUND is set to 0, BU j must be set to uj, for j=1,2,…,n. (If an upper bound is not specified for any xj the corresponding BU j should be set to 106.)
If IBOUND is set to 3, you must set BU 1 to u 1; E04LYF will then set the remaining elements of BU equal to BU 1.
On exit: the upper bounds actually used by E04LYF.
7:   X N – REAL (KIND=nag_wp) arrayInput/Output
On entry: X j must be set to a guess at the jth component of the position of the minimum, for j=1,2,…,n. The routine checks the gradient and the Hessian matrix at the starting point, and is more likely to detect any error in your programming if the initial X j are nonzero and mutually distinct.
On exit: the lowest point found during the calculations. Thus, if IFAIL=0 on exit, X j is the jth component of the position of the minimum.
8:   F – REAL (KIND=nag_wp)Output
On exit: the value of F x corresponding to the final point stored in X.
9:   G N – REAL (KIND=nag_wp) arrayOutput
On exit: the value of ∂F ∂xj corresponding to the final point stored in X, for j=1,2,…,n; the value of G j for variables not on a bound should normally be close to zero.
10:   IW LIW – INTEGER arrayWorkspace
11:   LIW – INTEGERInput
On entry: the dimension of the array IW as declared in the (sub)program from which E04LYF is called.
Constraint: LIW≥N+2.
12:   W LW – REAL (KIND=nag_wp) arrayWorkspace
13:   LW – INTEGERInput
On entry: the dimension of the array W as declared in the (sub)program from which E04LYF is called.
Constraint: LW≥max N×N+7,10.
14:   IUSER* – INTEGER arrayUser Workspace
15:   RUSER* – REAL (KIND=nag_wp) arrayUser Workspace
IUSER and RUSER are not used by E04LYF, but are passed directly to FUNCT2 and HESS2 and may be used to pass information to these routines as an alternative to using COMMON global variables.
16:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, because for this routine the values of the output arguments may be useful even if IFAIL≠0 on exit, the recommended value is -1. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Note: E04LYF may return useful information for one or more of the following detected errors or warnings.
Errors or warnings detected by the routine:
IFAIL=1
On entry, | N<1,
or | IBOUND<0,
or | IBOUND>3,
or | IBOUND=0 and BL j>BU j for some j,
or | IBOUND=3 and BL 1>BU 1,
or | LIW<N+2,
or | LW<max 10,N×N+7.
IFAIL=2
There have been 50×N function evaluations, yet the algorithm does not seem to be converging. The calculations can be restarted from the final point held in X. The error may also indicate that F x has no minimum.
IFAIL=3
The conditions for a minimum have not all been met but a lower point could not be found and the algorithm has failed.
IFAIL=4
Not used. (This value of the argument is included so as to make the significance of IFAIL=5 etc. consistent in the easy-to-use routines.)
IFAIL=5
IFAIL=6
IFAIL=7
IFAIL=8
There is some doubt about whether the point x found by E04LYF is a minimum. The degree of confidence in the result decreases as IFAIL increases. Thus, when IFAIL=5 it is probable that the final x gives a good estimate of the position of a minimum, but when IFAIL=8 it is very unlikely that the routine has found a minimum.
IFAIL=9
In the search for a minimum, the modulus of one of the variables has become very large ∼106. This indicates that there is a mistake in user-supplied subroutines FUNCT2 or HESS2, that your problem has no finite solution, or that the problem needs rescaling (see Section 9).
IFAIL=10
It is very likely that you have made an error in forming the gradient.
IFAIL=11
It is very likely that you have made an error in forming the second derivatives.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.
If you are dissatisfied with the result (e.g., because IFAIL=5, 6, 7 or 8), it is worth restarting the calculations from a different starting point (not the point at which the failure occurred) in order to avoid the region which caused the failure.

7 Accuracy

When a successful exit is made then, for a computer with a mantissa of t decimals, one would expect to get about t/2-1 decimals accuracy in x, and about t-1 decimals accuracy in F, provided the problem is reasonably well scaled.

8 Parallelism and Performance

E04LYF makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The number of iterations required depends on the number of variables, the behaviour of F x and the distance of the starting point from the solution. The number of operations performed in an iteration of E04LYF is roughly proportional to n 3+O n 2. In addition, each iteration makes one call of HESS2 and at least one call of FUNCT2. So, unless F x, the gradient vector and the matrix of second derivatives can be evaluated very quickly, the run time will be dominated by the time spent in user-supplied subroutines FUNCT2 and HESS2.
Ideally the problem should be scaled so that at the solution the value of F x and the corresponding values of x 1,x 2,…xn are each in the range -1,+1, and so that at points a unit distance away from the solution, F is approximately a unit value greater than at the minimum. It is unlikely that you will be able to follow these recommendations very closely, but it is worth trying (by guesswork), as sensible scaling will reduce the difficulty of the minimization problem, so that E04LYF will take less computer time.

10 Example

A program to minimize
F= x 1+10 x 2 2+5⁢ x 3-x 4 2+ x 2-2 x 3 4+10⁢ x 1-x 4 4
subject to
1 ≤ x 1 ≤ 3 -2 ≤ x 2 ≤ 0 1 ≤ x 4 ≤ 3.
starting from the initial guess 3,-1,0,1 . (In practice, it is worth trying to make user-supplied subroutines FUNCT2 and HESS2 as efficient as possible. This has not been done in the example program for reasons of clarity.)

10.1 Program Text

Program Text (e04lyfe.f90)

10.2 Program Data

None.

10.3 Program Results

Program Results (e04lyfe.r)

E04 Chapter Contents
E04 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


E04MFF/E04MFA : NAG Library, Mark 26

E04 Chapter Contents
E04 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

E04MFF/E04MFA

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.
Note: this routine uses optional parameters to define choices in the problem specification and in the details of the algorithm. If you wish to use default settings for all of the optional parameters, you need only read Sections 1 to 10 of this document. If, however, you wish to reset some or all of the settings please refer to Section 11 for a detailed description of the algorithm, to Section 12 for a detailed description of the specification of the optional parameters and to Section 13 for a detailed description of the monitoring information produced by the routine.

▸▿ Contents

1 Purpose
▸▿ 2 Specification
2.1 Specification for E04MFF
2.2 Specification for E04MFA
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
▸▿ 9 Further Comments
9.1 Scaling
9.2 Description of the Printed Output
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results
▸▿ 11 Algorithmic Details
11.1 Overview
11.2 Definition of Search Direction
11.3 Main Iteration
11.4 Choosing the Initial Working Set
▸▿ 12 Optional Parameters
12.1 Description of the Optional Parameters
13 Description of Monitoring Information

1 Purpose

E04MFF/E04MFA solves general linear programming problems. It is not intended for large sparse problems.
E04MFA is a version of E04MFF that has additional arguments in order to make it safe for use in multithreaded applications (see Section 5). The initialization routine E04WBF must have been called before calling E04MFA.

2 Specification

2.1 Specification for E04MFF

SUBROUTINE E04MFF ( N, NCLIN, A, LDA, BL, BU, CVEC, ISTATE, X, ITER, OBJ, AX, CLAMDA, IWORK, LIWORK, WORK, LWORK, IFAIL)
INTEGER | N, NCLIN, LDA, ISTATE(N+NCLIN), ITER, IWORK(LIWORK), LIWORK, LWORK, IFAIL
REAL (KIND=nag_wp) | A(LDA,*), BL(N+NCLIN), BU(N+NCLIN), CVEC(*), X(N), OBJ, AX(max(1,NCLIN)), CLAMDA(N+NCLIN), WORK(LWORK)

2.2 Specification for E04MFA

SUBROUTINE E04MFA ( N, NCLIN, A, LDA, BL, BU, CVEC, ISTATE, X, ITER, OBJ, AX, CLAMDA, IWORK, LIWORK, WORK, LWORK, LWSAV, IWSAV, RWSAV, IFAIL)
INTEGER | N, NCLIN, LDA, ISTATE(N+NCLIN), ITER, IWORK(LIWORK), LIWORK, LWORK, IWSAV(610), IFAIL
REAL (KIND=nag_wp) | A(LDA,*), BL(N+NCLIN), BU(N+NCLIN), CVEC(*), X(N), OBJ, AX(max(1,NCLIN)), CLAMDA(N+NCLIN), WORK(LWORK), RWSAV(475)
LOGICAL | LWSAV(120)
Before calling E04MFA, or either of the option setting routines E04MGA or E04MHA, E04WBF must be called. The specification for E04WBF is:
SUBROUTINE E04WBF ( RNAME, CWSAV, LCWSAV, LWSAV, LLWSAV, IWSAV, LIWSAV, RWSAV, LRWSAV, IFAIL)
INTEGER | LCWSAV, LLWSAV, IWSAV(LIWSAV), LIWSAV, LRWSAV, IFAIL
REAL (KIND=nag_wp) | RWSAV(LRWSAV)
LOGICAL | LWSAV(LLWSAV)
CHARACTER(*) | RNAME
CHARACTER(80) | CWSAV(LCWSAV)
E04WBF should be called with RNAME='E04MFA'. LCWSAV, LLWSAV, LIWSAV and LRWSAV, the declared lengths of CWSAV, LWSAV, IWSAV and RWSAV respectively, must satisfy:
  • LCWSAV≥1
  • LLWSAV≥120
  • LIWSAV≥610
  • LRWSAV≥475
The contents of the arrays CWSAV, LWSAV, IWSAV and RWSAV must not be altered between calling routines E04MFA, E04MGA, E04MHA and E04WBF.

3 Description

E04MFF/E04MFA is designed to solve linear programming (LP) problems of the form
minimize x∈Rn cT x,   subject to  l≤ x Ax ≤u,
where c is an n-element vector and A is an mL by n matrix.
This is the default type of problem, referred to as type LP. The optional parameter Problem Type may be used to specify an alternative problem type FP, in which the objective function is omitted and the routine attempts to find a feasible point for the set of constraints.
The constraints involving A are called the general constraints. Note that upper and lower bounds are specified for all the variables and for all the general constraints. An equality constraint can be specified by setting li=ui. If certain bounds are not present, the associated elements of l or u can be set to special values that will be treated as -∞ or +∞. (See the description of the optional parameter Infinite Bound Size.)
You must supply an initial estimate of the solution.
The method used by E04MFF/E04MFA is described in detail in Section 11.

4 References

Gill P E, Hammarling S, Murray W, Saunders M A and Wright M H (1986) Users' guide for LSSOL (Version 1.0) Report SOL 86-1 Department of Operations Research, Stanford University
Gill P E and Murray W (1978) Numerically stable methods for quadratic programming Math. Programming 14 349–372
Gill P E, Murray W, Saunders M A and Wright M H (1984) Procedures for optimization problems with a mixture of bounds and general linear constraints ACM Trans. Math. Software 10 282–298
Gill P E, Murray W, Saunders M A and Wright M H (1989) A practical anti-cycling procedure for linearly constrained optimization Math. Programming 45 437–474
Gill P E, Murray W, Saunders M A and Wright M H (1991) Inertia-controlling methods for general quadratic programming SIAM Rev. 33 1–36
Gill P E, Murray W and Wright M H (1981) Practical Optimization Academic Press

5 Arguments

1:   N – INTEGERInput
On entry: n, the number of variables.
Constraint: N>0.
2:   NCLIN – INTEGERInput
On entry: mL, the number of general linear constraints.
Constraint: NCLIN≥0.
3:   A LDA* – REAL (KIND=nag_wp) arrayInput
Note: the second dimension of the array A must be at least N if NCLIN>0 and at least 1 if NCLIN=0.
On entry: the ith row of A must contain the coefficients of the ith general linear constraint, for i=1,2,…,mL.
If NCLIN=0, A is not referenced.
4:   LDA – INTEGERInput
On entry: the first dimension of the array A as declared in the (sub)program from which E04MFF/E04MFA is called.
Constraint: LDA≥max 1,NCLIN.
5:   BL N+NCLIN – REAL (KIND=nag_wp) arrayInput
6:   BU N+NCLIN – REAL (KIND=nag_wp) arrayInput
On entry: must contain the lower bounds and BU the upper bounds, for all the constraints in the following order. The first n elements of each array must contain the bounds on the variables, and the next mL elements the bounds for the general linear constraints (if any). To specify a nonexistent lower bound (i.e., lj=-∞), set BL j≤-bigbnd, and to specify a nonexistent upper bound (i.e., uj=+∞), set BU j≥bigbnd; the default value of bigbnd is 1020, but this may be changed by the optional parameter Infinite Bound Size. To specify the jth constraint as an equality, set BL j=BU j=β, say, where β<bigbnd.
Constraints:
  • BL j≤BU j, for j=1,2,…,N+NCLIN;
  • if BL j=BU j=β, β<bigbnd.
7:   CVEC* – REAL (KIND=nag_wp) arrayInput
Note: the dimension of the array CVEC must be at least N if the problem is of type LP (the default), and at least 1 otherwise.
On entry: the coefficients of the objective function when the problem is of type LP.
If the problem is of type FP, CVEC is not referenced.
8:   ISTATE N+NCLIN – INTEGER arrayInput/Output
On entry: need not be set if the (default) optional parameter Cold Start is used.
If the optional parameter Warm Start has been chosen, ISTATE specifies the desired status of the constraints at the start of the feasibility phase. More precisely, the first n elements of ISTATE refer to the upper and lower bounds on the variables, and the next mL elements refer to the general linear constraints (if any). Possible values for ISTATE j are as follows:
ISTATE j | Meaning
0 | The corresponding constraint should not be in the initial working set.
1 | The constraint should be in the initial working set at its lower bound.
2 | The constraint should be in the initial working set at its upper bound.
3 | The constraint should be in the initial working set as an equality. This value must not be specified unless BL j=BU j.
The values -2, -1 and 4 are also acceptable but will be reset to zero by the routine. If E04MFF/E04MFA has been called previously with the same values of N and NCLIN, ISTATE already contains satisfactory information. (See also the description of the optional parameter Warm Start.) The routine also adjusts (if necessary) the values supplied in X to be consistent with ISTATE.
Constraint: -2≤ISTATE j≤4, for j=1,2,…,N+NCLIN.
On exit: the status of the constraints in the working set at the point returned in X. The significance of each possible value of ISTATE j is as follows:
ISTATE j | Meaning
-2 | The constraint violates its lower bound by more than the feasibility tolerance.
-1 | The constraint violates its upper bound by more than the feasibility tolerance.
-0 | The constraint is satisfied to within the feasibility tolerance, but is not in the working set.
-1 | This inequality constraint is included in the working set at its lower bound.
-2 | This inequality constraint is included in the working set at its upper bound.
-3 | This constraint is included in the working set as an equality. This value of ISTATE can occur only when BL j=BU j.
-4 | This corresponds to optimality being declared with X j being temporarily fixed at its current value. This value of ISTATE can occur only when IFAIL=1 on exit.
9:   X N – REAL (KIND=nag_wp) arrayInput/Output
On entry: an initial estimate of the solution.
On exit: the point at which E04MFF/E04MFA terminated. If IFAIL=0, 1 or 4, X contains an estimate of the solution.
10:   ITER – INTEGEROutput
On exit: the total number of iterations performed.
11:   OBJ – REAL (KIND=nag_wp)Output
On exit: the value of the objective function at x if x is feasible, or the sum of infeasibiliites at x otherwise. If the problem is of type FP and x is feasible, OBJ is set to zero.
12:   AX max 1,NCLIN – REAL (KIND=nag_wp) arrayOutput
On exit: the final values of the linear constraints Ax.
If NCLIN=0, AX is not referenced.
13:   CLAMDA N+NCLIN – REAL (KIND=nag_wp) arrayOutput
On exit: the values of the Lagrange multipliers for each constraint with respect to the current working set. The first n elements contain the multipliers for the bound constraints on the variables, and the next mL elements contain the multipliers for the general linear constraints (if any). If ISTATE j=0 (i.e., constraint j is not in the working set), CLAMDA j is zero. If x is optimal, CLAMDA j should be non-negative if ISTATE j=1, non-positive if ISTATE j=2 and zero if ISTATE j=4.
14:   IWORK LIWORK – INTEGER arrayWorkspace
15:   LIWORK – INTEGERInput
On entry: the dimension of the array IWORK as declared in the (sub)program from which E04MFF/E04MFA is called.
Constraint: LIWORK≥2×N+3.
16:   WORK LWORK – REAL (KIND=nag_wp) arrayWorkspace
17:   LWORK – INTEGERInput
On entry: the dimension of the array WORK as declared in the (sub)program from which E04MFF/E04MFA is called.
Constraints:
  • if the problem is of type LP (the default),
    • if NCLIN=0, LWORK≥7×N+1;
    • if NCLIN≥N, LWORK≥2×N 2+7×N+5×NCLIN;
    • otherwise LWORK≥2×NCLIN+1 2+7×N+5×NCLIN;
  • if the problem is of type FP,
    • if NCLIN=0, LWORK≥6×N+1;
    • if NCLIN≥N, LWORK≥2×N 2+6×N+5×NCLIN;
    • otherwise LWORK≥2×NCLIN+1 2+6×N+5×NCLIN.
The amounts of workspace provided and required are (by default) output on the current advisory message unit (as defined by X04ABF). As an alternative to computing LIWORK and LWORK from the formulas given above, you may prefer to obtain appropriate values from the output of a preliminary run with LIWORK and LWORK set to 1. (E04MFF/E04MFA will then terminate with IFAIL=6.)
18:   IFAIL – INTEGERInput/Output
Note: for E04MFA, IFAIL does not occur in this position in the argument list. See the additional arguments described below.
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, because for this routine the values of the output arguments may be useful even if IFAIL≠0 on exit, the recommended value is -1. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).
E04MFF/E04MFA returns with IFAIL=0 if x is a strong local minimizer, i.e., the reduced gradient (Norm Gz; see Section 9.2) is negligible and the Lagrange multipliers (Lagr Mult; see Section 9.2) are optimal.
Note: the following are additional arguments for specific use with E04MFA. Users of E04MFF therefore need not read the remainder of this description.
18:   LWSAV 120 – LOGICAL arrayCommunication Array
19:   IWSAV 610 – INTEGER arrayCommunication Array
20:   RWSAV 475 – REAL (KIND=nag_wp) arrayCommunication Array
The arrays LWSAV, IWSAV and RWSAV must not be altered between calls to any of the routines E04MFA, E04MGA, E04MHA or E04WBF.
21:   IFAIL – INTEGERInput/Output
Note: see the argument description for IFAIL above.

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Note: E04MFF/E04MFA may return useful information for one or more of the following detected errors or warnings.
Errors or warnings detected by the routine:
IFAIL=1
x is a weak local minimum (the projected gradient is negligible and the Lagrange multipliers are optimal but there is a small multiplier). This means that the solution is not unique.
IFAIL=2
The solution appears to be unbounded, i.e., the objective function is not bounded below in the feasible region. This value of IFAIL occurs if a step larger than Infinite Step Size (default value=1020) would have to be taken in order to continue the algorithm, or the next step would result in an element of x having magnitude larger than optional parameter Infinite Bound Size (default value=1020).
IFAIL=3
No feasible point was found, i.e., it was not possible to satisfy all the constraints to within the feasibility tolerance. In this case, the constraint violations at the final x will reveal a value of the tolerance for which a feasible point will exist – for example, when the feasibility tolerance for each violated constraint exceeds its Slack (see Section 9.2) at the final point. The modified problem (with an altered feasibility tolerance) may then be solved using a Warm Start. You should check that there are no constraint redundancies. If the data for the constraints are accurate only to the absolute precision σ, you should ensure that the value of the optional parameter Feasibility Tolerance (default value=ε, where ε is the machine precision) is greater than σ. For example, if all elements of A are of order unity and are accurate only to three decimal places, the Feasibility Tolerance should be at least 10-3.
IFAIL=4
The limiting number of iterations was reached before normal termination occurred.
The value of the optional parameter Iteration Limit ( default value = max 50,5 n+mL ) may be too small. If the method appears to be making progress (e.g., the objective function is being satisfactorily reduced), either rerun E04MFF/E04MFA with a larger value of Iteration Limit or, alternatively, rerun E04MFF/E04MFA using the Warm Start facility to specify the initial working set.
IFAIL=5
Not used by this routine.
IFAIL=6
An input argument is invalid.
IFAIL=7
The designated problem type was not FP or LP. Rerun E04MFF/E04MFA with the optional parameter Problem Type set to one of these values.
Overflow
If the printed output before the overflow error contains a warning about serious ill-conditioning in the working set when adding the jth constraint, it may be possible to avoid the difficulty by increasing the magnitude of the Feasibility Tolerance (default value=ε, where ε is the machine precision) and rerunning the program. If the message recurs even after this change, the offending linearly dependent constraint (with index ‘j’) must be removed from the problem.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

E04MFF/E04MFA implements a numerically stable active set strategy and returns solutions that are as accurate as the condition of the problem warrants on the machine.

8 Parallelism and Performance

E04MFF/E04MFA makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

This section contains some comments on scaling and a description of the printed output.

9.1 Scaling

Sensible scaling of the problem is likely to reduce the number of iterations required and make the problem less sensitive to perturbations in the data, thus improving the condition of the problem. In the absence of better information it is usually sensible to make the Euclidean lengths of each constraint of comparable magnitude. See the E04 Chapter Introduction and Gill et al. (1981) for further information and advice.

9.2 Description of the Printed Output

This section describes the intermediate printout and final printout produced by E04MFF/E04MFA. The intermediate printout is a subset of the monitoring information produced by the routine at every iteration (see Section 13). You can control the level of printed output (see the description of the optional parameter Print Level). Note that the intermediate printout and final printout are produced only if Print Level≥10 (the default for E04MFF, by default no output is produced by E04MFA).
The following line of summary output (<80 characters) is produced at every iteration. In all cases, the values of the quantities printed are those in effect on completion of the given iteration.
Itn | is the iteration count.
Step | is the step taken along the computed search direction. If a constraint is added during the current iteration, Step will be the step to the nearest constraint. When the problem is of type LP, the step can be greater than one during the optimality phase.
Ninf | is the number of violated constraints (infeasibilities). This will be zero during the optimality phase.
Sinf/Objective | is the value of the current objective function. If x is not feasible, Sinf gives a weighted sum of the magnitudes of constraint violations. If x is feasible, Objective is the value of the objective function of (1). The output line for the final iteration of the feasibility phase (i.e., the first iteration for which Ninf is zero) will give the value of the true objective at the first feasible point. During the optimality phase the value of the objective function will be nonincreasing. During the feasibility phase the number of constraint infeasibilities will not increase until either a feasible point is found or the optimality of the multipliers implies that no feasible point exists. Once optimal multipliers are obtained the number of infeasibilities can increase, but the sum of infeasibilities will either remain constant or be reduced until the minimum sum of infeasibilities is found.
Norm Gz | is ZRT gFR , the Euclidean norm of the reduced gradient with respect to ZR. During the optimality phase, this norm will be approximately zero after a unit step. (See Sections 11.2 and 11.4.)
The final printout includes a listing of the status of every variable and constraint.
The following describes the printout for each variable. A full stop (.) is printed for any numerical value that is zero.
Varbl | gives the name (V) and index j, for j=1,2,…,n, of the variable.
State gives the state of the variable (FR if neither bound is in the working set, EQ if a fixed variable, LL if on its lower bound, UL if on its upper bound, TF if temporarily fixed at its current value). If Value lies outside the upper or lower bounds by more than the Feasibility Tolerance, State will be ++ or -- respectively.
A key is sometimes printed before State.
A | Alternative optimum possible. The variable is active at one of its bounds, but its Lagrange multiplier is essentially zero. This means that if the variable were allowed to start moving away from its bound then there would be no change to the objective function. The values of the other free variables might change, giving a genuine alternative solution. However, if there are any degenerate variables (labelled D), the actual change might prove to be zero, since one of them could encounter a bound immediately. In either case the values of the Lagrange multipliers might also change.
D | Degenerate. The variable is free, but it is equal to (or very close to) one of its bounds.
I | Infeasible. The variable is currently violating one of its bounds by more than the Feasibility Tolerance.
Value | is the value of the variable at the final iteration.
Lower Bound | is the lower bound specified for the variable. None indicates that BL j≤-bigbnd.
Upper Bound | is the upper bound specified for the variable. None indicates that BU j≥bigbnd.
Lagr Mult | is the Lagrange multiplier for the associated bound. This will be zero if State is FR unless BL j≤-bigbnd and BU j≥bigbnd, in which case the entry will be blank. If x is optimal, the multiplier should be non-negative if State is LL and non-positive if State is UL.
Slack | is the difference between the variable Value and the nearer of its (finite) bounds BL j and BU j. A blank entry indicates that the associated variable is not bounded (i.e., BL j≤-bigbnd and BU j≥bigbnd).
The meaning of the printout for general constraints is the same as that given above for variables, with ‘variable’ replaced by ‘constraint’, BL j and BU j are replaced by BL n+j and BU n+j respectively, and with the following change in the heading:
L Con gives the name (L) and index j, for j=1,2,…,nL, of the linear constraint.
Note that movement off a constraint (as opposed to a variable moving away from its bound) can be interpreted as allowing the entry in the Slack column to become positive.
Numerical values are output with a fixed number of digits; they are not guaranteed to be accurate to this precision.

10 Example

This example minimizes the function
-0.02 x 1-0.2 x 2-0.2 x 3-0.2 x 4-0.2 x 5+0.04 x 6+0.04 x 7
subject to the bounds
-0.01≤x 1≤ 0.01 -0.1 0≤x 2≤ 0.15 -0.01≤x 3≤ 0.03 -0.04≤x 4≤ 0.02 -0.1 0≤x 5≤ 0.05 -0.01≤x 6 ≤ 0.00 -0.01≤x 7 ≤ 0.00
and the general constraints
x 1 + x 2 + x 3 + x 4 + x 5 + x 6 + x 7 = -0.13 0.15 x 1 + 0.04 x 2 + 0.02 x 3 + 0.04 x 4 + 0.02 x 5 + 0.01 x 6 + 0.03 x 7 ≤ -0.0049 0.03 x 1 + 0.05 x 2 + 0.08 x 3 + 0.02 x 4 + 0.06 x 5 + 0.01 x 6 ≤ -0.0064 0 0.02 x 1 + 0.04 x 2 + 0.01 x 3 + 0.02 x 4 + 0.02 x 5 ≤ -0.0037 0.02 x 1 + 0.03 x 2 + 0.01 x 5 ≤ -0.0012 -0.0992 ≤ 0.70 x 1 + 0.75 x 2 + 0.80 x 3 + 0.75 x 4 + 0.80 x 5 + 0.97 x 6 -0.003 ≤ 0.02 x 1 + 0.06 x 2 + 0.08 x 3 + 0.12 x 4 + 0.02 x 5 + 0.01 x 6 + 0.97 x 7 ≤ -0.002
The initial point, which is infeasible, is
x 0=-0.01,-0.03,0.0,-0.01,-0.1,0.02,0.01 T.
The optimal solution (to five figures) is
x*=-0.01,-0.1,0.03,0.02,-0.067485,-0.0022801,-0.00023453 T.
Four bound constraints and three general constraints are active at the solution.
The document for E04MGF/E04MGA includes an example program to solve the same problem using some of the optional parameters described in Section 12.

10.1 Program Text

Note: the following programs illustrate the use of E04MFF and E04MFA.

Program Text (e04mffe.f90)

Program Text (e04mfae.f90)

10.2 Program Data

Program Data (e04mffe.d)

Program Data (e04mfae.d)

10.3 Program Results

Program Results (e04mffe.r)

Program Results (e04mfae.r)

Note: the remainder of this document is intended for more advanced users. Section 11 contains a detailed description of the algorithm which may be needed in order to understand Sections 12 and 13. Section 12 describes the optional parameters which may be set by calls to E04MGF/E04MGA and/or E04MHF/E04MHA. Section 13 describes the quantities which can be requested to monitor the course of the computation.

11 Algorithmic Details

This section contains a detailed description of the method used by E04MFF/E04MFA.

11.1 Overview

E04MFF/E04MFA is based on an inertia-controlling method due to Gill and Murray (1978), and is described in detail by Gill et al. (1991). Here we briefly summarise the main features of the method. Where possible, explicit reference is made to the names of variables that are arguments of E04MFF/E04MFA or appear in the printed output. E04MFF/E04MFA has two phases: finding an initial feasible point by minimizing the sum of infeasibilities (the feasibility phase), and minimizing the linear objective function within the feasible region (the optimality phase). The computations in both phases are performed by the same subroutines. The two-phase nature of the algorithm is reflected by changing the function being minimized from the sum of infeasibilities to the linear objective function. The feasibility phase does not perform the standard simplex method (i.e., it does not necessarily find a vertex), except in the case when mL≤n. Once any iterate is feasible, all subsequent iterates remain feasible.
In general, an iterative process is required to solve a linear program. (For simplicity, we shall always consider a typical iteration and avoid reference to the index of the iteration.) Each new iterate x- is defined by
x-=x+αp, (1)
where the step length α is a non-negative scalar, and p is called the search direction.
At each point x, a working set of constraints is defined to be a linearly independent subset of the constraints that are satisfied ‘exactly’ (to within the tolerance defined by the optional parameter Feasibility Tolerance). The working set is the current prediction of the constraints that hold with equality at a solution of an LP problem. The search direction is constructed so that the constraints in the working set remain unaltered for any value of the step length. For a bound constraint in the working set, this property is achieved by setting the corresponding element of the search direction to zero. Thus, the associated variable is fixed, and specification of the working set induces a partition of x into fixed and free variables. During a given iteration, the fixed variables are effectively removed from the problem; since the relevant elements of the search direction are zero, the columns of A corresponding to fixed variables may be ignored.
Let mW denote the number of general constraints in the working set and let nFX denote the number of variables fixed at one of their bounds (mW and nFX are the quantities Lin and Bnd in the monitoring file output from E04MFF/E04MFA; see Section 13). Similarly, let nFR (nFR=n-nFX) denote the number of free variables. At every iteration, the variables are reordered so that the last nFX variables are fixed, with all other relevant vectors and matrices ordered accordingly.

11.2 Definition of Search Direction

Let AFR denote the mW by nFR sub-matrix of general constraints in the working set corresponding to the free variables, and let pFR denote the search direction with respect to the free variables only. The general constraints in the working set will be unaltered by any move along p if
AFRpFR=0. (2)
In order to compute pFR, the TQ factorization of AFR is used:
AFRQFR=0 T, (3)
where T is a nonsingular mW by mW upper triangular matrix (i.e., t ij=0 if i>j), and the nonsingular nFR by nFR matrix QFR is the product of orthogonal transformations (see Gill et al. (1984)). If the columns of QFR are partitioned so that
QFR=Z Y,
where Y is nFR by mW, then the nZ (nZ=nFR-mW) columns of Z form a basis for the null space of AFR. Let nR be an integer such that 0≤nR≤nZ, and let ZR denote a matrix whose nR columns are a subset of the columns of Z. (The integer nR is the quantity Zr in the monitoring file output from E04MFF/E04MFA. In many cases, ZR will include all the columns of Z.) The direction pFR will satisfy (2) if
pFR=ZRpR (4)
where pR is any nR-vector.

11.3 Main Iteration

Let Q denote the n by n matrix
Q= QFR IFX ,
where IFX is the identity matrix of order nFX. Let gQ denote the transformed gradient
gQ=QT c
and let the vector of the first nR elements of gQ be denoted by gR. The quantity gR is known as the reduced gradient of cT x. If the reduced gradient is zero, x is a constrained stationary point in the subspace defined by Z. During the feasibility phase, the reduced gradient will usually be zero only at a vertex (although it may be zero at non-vertices in the presence of constraint dependencies). During the optimality phase, a zero reduced gradient implies that x minimizes the linear objective when the constraints in the working set are treated as equalities. At a constrained stationary point, Lagrange multipliers λC and λB for the general and bound constraints are defined from the equations
AFRT λC=gFR  and  λB=gFX-AFXT λC. (5)
Given a positive constant δ of the order of the machine precision, a Lagrange multiplier λj corresponding to an inequality constraint in the working set is said to be optimal if λj≤δ when the associated constraint is at its upper bound, or if λj≥-δ when the associated constraint is at its lower bound. If a multiplier is nonoptimal, the objective function (either the true objective or the sum of infeasibilities) can be reduced by deleting the corresponding constraint (with index Jdel; see Section 13) from the working set.
If optimal multipliers occur during the feasibility phase and the sum of infeasibilities is nonzero, there is no feasible point, and you can force E04MFF/E04MFA to continue until the minimum value of the sum of infeasibilities has been found; see the discussion of the optional parameter Minimum Sum of Infeasibilities. At such a point, the Lagrange multiplier λj corresponding to an inequality constraint in the working set will be such that -1+δ≤λj≤δ when the associated constraint is at its upper bound, and -δ≤λj≤1+δ when the associated constraint is at its lower bound. Lagrange multipliers for equality constraints will satisfy λj≤1+δ.
If the reduced gradient is not zero, Lagrange multipliers need not be computed and the nonzero elements of the search direction p are given by ZRpR. The choice of step length is influenced by the need to maintain feasibility with respect to the satisfied constraints.
Each change in the working set leads to a simple change to AFR: if the status of a general constraint changes, a row of AFR is altered; if a bound constraint enters or leaves the working set, a column of AFR changes. Explicit representations are recurred of the matrices T and QFR; and of vectors QT g, and QT c.
One of the most important features of E04MFF/E04MFA is its control of the conditioning of the working set, whose nearness to linear dependence is estimated by the ratio of the largest to smallest diagonal elements of the TQ factor T (the printed value Cond T; see Section 13). In constructing the initial working set, constraints are excluded that would result in a large value of Cond T.
E04MFF/E04MFA includes a rigorous procedure that prevents the possibility of cycling at a point where the active constraints are nearly linearly dependent (see Gill et al. (1989)). The main feature of the anti-cycling procedure is that the feasibility tolerance is increased slightly at the start of every iteration. This not only allows a positive step to be taken at every iteration, but also provides, whenever possible, a choice of constraints to be added to the working set. Let αM denote the maximum step at which x+αM p does not violate any constraint by more than its feasibility tolerance. All constraints at a distance α (α≤αM) along p from the current point are then viewed as acceptable candidates for inclusion in the working set. The constraint whose normal makes the largest angle with the search direction is added to the working set.

11.4 Choosing the Initial Working Set

Let Z be partitioned as Z=ZRZA. A working set for which ZR defines the null space can be obtained by including the rows of ZAT as ‘artificial constraints’. Minimization of the objective function then proceeds within the subspace defined by ZR, as described in Section 11.2.
The artificially augmented working set is given by
A-FR= ZAT AFR , (6)
so that pFR will satisfy AFRpFR=0 and ZAT pFR = 0 . By definition of the TQ factorization, A-FR automatically satisfies the following:
A-FRQFR= ZAT AFR QFR= ZAT AFR ZR ZA Y = 0 T- ,
where
T-= I 0 0 T ,
and hence the TQ factorization of (6) is available trivially from T and QFR without additional expense.
The matrix ZA is not kept fixed, since its role is purely to define an appropriate null space; the TQ factorization can therefore be updated in the normal fashion as the iterations proceed. No work is required to ‘delete’ the artificial constraints associated with ZA when ZRT gFR = 0 , since this simply involves repartitioning QFR. The ‘artificial’ multiplier vector associated with the rows of ZAT is equal to ZAT gFR , and the multipliers corresponding to the rows of the ‘true’ working set are the multipliers that would be obtained if the artificial constraints were not present. If an artificial constraint is ‘deleted’ from the working set, an A appears alongside the entry in the Jdel column of the monitoring file output (see Section 13).
The number of columns in ZA and ZR and the Euclidean norm of ZRT gFR , appear in the monitoring file output as Art, Zr and Norm Gz respectively (see Section 13).
Under some circumstances, a different type of artificial constraint is used when solving a linear program. Although the algorithm of E04MFF/E04MFA does not usually perform simplex steps (in the traditional sense), there is one exception: a linear program with fewer general constraints than variables (i.e., mL≤n). Use of the simplex method in this situation leads to savings in storage. At the starting point, the ‘natural’ working set (the set of constraints exactly or nearly satisfied at the starting point) is augmented with a suitable number of ‘temporary’ bounds, each of which has the effect of temporarily fixing a variable at its current value. In subsequent iterations, a temporary bound is treated as a standard constraint until it is deleted from the working set, in which case it is never added again. If a temporary bound is ‘deleted’ from the working set, an F (for ‘Fixed’) appears alongside the entry in the Jdel column of the monitoring file output (see Section 13).

12 Optional Parameters

Several optional parameters in E04MFF/E04MFA define choices in the problem specification or the algorithm logic. In order to reduce the number of formal arguments of E04MFF/E04MFA these optional parameters have associated default values that are appropriate for most problems. Therefore, you need only specify those optional parameters whose values are to be different from their default values.
The remainder of this section can be skipped if you wish to use the default values for all optional parameters.
The following is a list of the optional parameters available. A full description of each optional parameter is provided in Section 12.1.
  • Check Frequency
  • Cold Start
  • Crash Tolerance
  • Defaults
  • Expand Frequency
  • Feasibility Tolerance
  • Infinite Bound Size
  • Infinite Step Size
  • Iteration Limit
  • Iters
  • Itns
  • List
  • Minimum Sum of Infeasibilities
  • Monitoring File
  • Nolist
  • Optimality Tolerance
  • Print Level
  • Problem Type
  • Warm Start
Optional parameters may be specified by calling one, or both, of the routines E04MGF/E04MGA and E04MHF/E04MHA before a call to E04MFF/E04MFA.
E04MGF/E04MGA reads options from an external options file, with Begin and End as the first and last lines respectively and each intermediate line defining a single optional parameter. For example,
Begin
  Print Level = 5
End
The call
 CALL E04MGF (IOPTNS, INFORM)
can then be used to read the file on unit IOPTNS. INFORM will be zero on successful exit. E04MGF/E04MGA should be consulted for a full description of this method of supplying optional parameters.
E04MHF/E04MHA can be called to supply options directly, one call being necessary for each optional parameter. For example,
 CALL E04MHF ('Print Level = 5')
E04MHF/E04MHA should be consulted for a full description of this method of supplying optional parameters.
All optional parameters not specified by you are set to their default values. Optional parameters specified by you are unaltered by E04MFF/E04MFA (unless they define invalid values) and so remain in effect for subsequent calls unless altered by you.

12.1 Description of the Optional Parameters

For each option, we give a summary line, a description of the optional parameter and details of constraints.
The summary line contains:
  • the keywords, where the minimum abbreviation of each keyword is underlined (if no characters of an optional qualifier are underlined, the qualifier may be omitted);
  • a parameter value, where the letters a, i and r denote options that take character, integer and real values respectively;
  • the default value, where the symbol ε is a generic notation for machine precision (see X02AJF).
Keywords and character values are case and white space insensitive.
Check Frequency i Default =50
Every ith iteration, a numerical test is made to see if the current solution x satisfies the constraints in the working set. If the largest residual of the constraints in the working set is judged to be too large, the current working set is refactorized and the variables are recomputed to satisfy the constraints more accurately. If i≤0, the default value is used.
Cold Start Default
Warm Start
This option specifies how the initial working set is chosen. With a Cold Start, E04MFF/E04MFA chooses the initial working set based on the values of the variables and constraints at the initial point. Broadly speaking, the initial working set will include equality constraints and bounds or inequality constraints that violate or ‘nearly’ satisfy their bounds (to within Crash Tolerance).
With a Warm Start, you must provide a valid definition of every element of the array ISTATE. E04MFF/E04MFA will override your specification of ISTATE if necessary, so that a poor choice of the working set will not cause a fatal error. For instance, any elements of ISTATE which are set to -2, -1​ or ​4 will be reset to zero, as will any elements which are set to 3 when the corresponding elements of BL and BU are not equal. A warm start will be advantageous if a good estimate of the initial working set is available – for example, when E04MFF/E04MFA is called repeatedly to solve related problems.
Crash Tolerance r Default =0.01
This value is used in conjunction with the optional parameter Cold Start (the default value) when E04MFF/E04MFA selects an initial working set. If 0≤r≤1, the initial working set will include (if possible) bounds or general inequality constraints that lie within r of their bounds. In particular, a constraint of the form ajT x≥l will be included in the initial working set if ajT x-l ≤ r 1+l . If r<0 or r>1, the default value is used.
Defaults
This special keyword may be used to reset all optional parameters to their default values.
Expand Frequency i Default =5
This option is part of an anti-cycling procedure designed to guarantee progress even on highly degenerate problems.
The strategy is to force a positive step at every iteration, at the expense of violating the constraints by a small amount. Suppose that the value of the optional parameter Feasibility Tolerance is δ. Over a period of i iterations, the feasibility tolerance actually used by E04MFF/E04MFA (i.e., the working feasibility tolerance) increases from 0.5 δ to δ (in steps of 0.5 δ/i).
At certain stages the following ‘resetting procedure’ is used to remove constraint infeasibilities. First, all variables whose upper or lower bounds are in the working set are moved exactly onto their bounds. A count is kept of the number of nontrivial adjustments made. If the count is positive, iterative refinement is used to give variables that satisfy the working set to (essentially) machine precision. Finally, the working feasibility tolerance is reinitialized to 0.5 δ.
If a problem requires more than i iterations, the resetting procedure is invoked and a new cycle of i iterations is started with i incremented by 10. (The decision to resume the feasibility phase or optimality phase is based on comparing any constraint infeasibilities with δ.)
The resetting procedure is also invoked when E04MFF/E04MFA reaches an apparently optimal, infeasible or unbounded solution, unless this situation has already occurred twice. If any nontrivial adjustments are made, iterations are continued.
If i≤0, the default value is used. If i≥9999999, no anti-cycling procedure is invoked.
Feasibility Tolerance r Default =ε
If r≥ε, r defines the maximum acceptable absolute violation in each constraint at a ‘feasible’ point. For example, if the variables and the coefficients in the general constraints are of order unity, and the latter are correct to about 6 decimal digits, it would be appropriate to specify r as 10-6. If 0≤r<ε, the default value is used.
E04MFF/E04MFA attempts to find a feasible solution before optimizing the objective function. If the sum of infeasibilities cannot be reduced to zero, the optional parameter Minimum Sum of Infeasibilities can be used to find the minimum value of the sum. Let Sinf be the corresponding sum of infeasibilities. If Sinf is quite small, it may be appropriate to raise r by a factor of 10 or 100. Otherwise, some error in the data should be suspected.
Note that a ‘feasible solution’ is a solution that satisfies the current constraints to within the tolerance r.
Infinite Bound Size r Default =1020
If r>0, r defines the ‘infinite’ bound bigbnd in the definition of the problem constraints. Any upper bound greater than or equal to bigbnd will be regarded as +∞ (and similarly any lower bound less than or equal to -bigbnd will be regarded as -∞). If r<0, the default value is used.
Infinite Step Size r Default =max bigbnd,1020
If r>0, r specifies the magnitude of the change in variables that will be considered a step to an unbounded solution. (Note that an unbounded solution can occur only when the problem is of type LP.) If the change in x during an iteration would exceed the value of r, the objective function is considered to be unbounded below in the feasible region. If r≤0, the default value is used.
Iteration Limit i Default =max 50,5 n+mL
Iters
Itns
The value of i specifies the maximum number of iterations allowed before termination. With i=0 and Print Level>0, the workspace needed will be computed and printed, but no iterations will be performed. If i<0, the default value is used.
List Default for E04MFF =List
Nolist Default for E04MFA =Nolist
Normally each optional parameter specification is printed as it is supplied. Optional parameter Nolist may be used to suppress the printing and optional parameter List may be used to restore printing.
Minimum Sum of Infeasibilities N o Default =NO
If no feasible point exists for the constraints, this option is used to control whether or not E04MFF/E04MFA will calculate a point that minimizes the constraint violations. If Minimum Sum of Infeasibilities=NO, E04MFF/E04MFA will terminate as soon as it is evident that no feasible point exists for the constraints. The final point will generally not be the point at which the sum of infeasibilities is minimized. If Minimum Sum of Infeasibilities=YES, E04MFF/E04MFA will continue until the sum of infeasibilities is minimized.
Monitoring File i Default =-1
If i≥0 and Print Level≥5, monitoring information produced by E04MFF/E04MFA at every iteration is sent to a file with logical unit number i. If i<0 and/or Print Level<5, no monitoring information is produced.
Optimality Tolerance r Default =ε 0.8
If r≥ε, r defines the tolerance used to determine if the bounds and general constraints have the right ‘sign’ for the solution to be judged to be optimal.
If 0≤r<ε, the default value is used.
Print Level i Default for E04MFF =10
Default for E04MFA =0
The value of i controls the amount of printout produced by E04MFF/E04MFA, as indicated below. A detailed description of the printed output is given in Section 9.2 (summary output at each iteration and the final solution) and Section 13 (monitoring information at each iteration).
The following printout is sent to the current advisory message unit (as defined by X04ABF):
i | Output
≥0 0 | No output.
≥0 1 | The final solution only.
≥0 5 | One line of summary output (<80 characters; see Section 9.2) for each iteration (no printout of the final solution).
≥10 | The final solution and one line of summary output for each iteration.
The following printout is sent to the logical unit number by the optional parameter Monitoring File:
i | Output
<0 5 | No output.
≥0 5 | One long line of output (>80 characters; see Section 13) for each iteration (no printout of the final solution).
≥20 | At each iteration, the Lagrange multipliers, the variables x, the constraint values Ax and the constraint status (see ISTATE).
≥30 | At each iteration, the diagonal elements of the upper triangular matrix T associated with the TQ factorization (3) (see Section 11.2) of the working set.
If Print Level≥5 and the unit number defined by the optional parameter Monitoring File is the same as that defined by X04ABF, then the summary output for each major iteration is suppressed.
Problem Type a Default = LP
This option specifies the type of objective function to be minimized during the optimality phase. The following is the optional keyword and the dimensions of the array that must be specified in order to define the objective function:
LP CVEC N required.
For problems of type FP, the objective function is omitted and CVEC is not referenced. The following keywords are also acceptable. The minimum abbreviation of each keyword is underlined.
a | Option
Linear | LP
Feasible | FP

13 Description of Monitoring Information

This section describes the long line of output (>80 characters) which forms part of the monitoring information produced by E04MFF/E04MFA. (See also the description of the optional parameters Monitoring File and Print Level.) You can control the level of printed output.
To aid interpretation of the printed results, the following convention is used for numbering the constraints: indices 1 through n refer to the bounds on the variables, and indices n+1 through n+mL refer to the general constraints. When the status of a constraint changes, the index of the constraint is printed, along with the designation L (lower bound), U (upper bound), E (equality), F (temporarily fixed variable) or A (artificial constraint).
When Print Level≥5 and Monitoring File≥0, the following line of output is produced at every iteration on the unit number specified by optional parameter Monitoring File. In all cases, the values of the quantities printed are those in effect on completion of the given iteration.
Itn | is the iteration count.
Jdel | is the index of the constraint deleted from the working set. If Jdel is zero, no constraint was deleted.
Jadd | is the index of the constraint added to the working set. If Jadd is zero, no constraint was added.
Step | is the step taken along the computed search direction. If a constraint is added during the current iteration, Step will be the step to the nearest constraint. When the problem is of type LP, the step can be greater than one during the optimality phase.
Ninf | is the number of violated constraints (infeasibilities). This will be zero during the optimality phase.
Sinf/Objective | is the value of the current objective function. If x is not feasible, Sinf gives a weighted sum of the magnitudes of constraint violations. If x is feasible, Objective is the value of the objective function of (1). The output line for the final iteration of the feasibility phase (i.e., the first iteration for which Ninf is zero) will give the value of the true objective at the first feasible point. During the optimality phase the value of the objective function will be nonincreasing. During the feasibility phase the number of constraint infeasibilities will not increase until either a feasible point is found or the optimality of the multipliers implies that no feasible point exists. Once optimal multipliers are obtained the number of infeasibilities can increase, but the sum of infeasibilities will either remain constant or be reduced until the minimum sum of infeasibilities is found.
Bnd | is the number of simple bound constraints in the current working set.
Lin | is the number of general linear constraints in the current working set.
Art | is the number of artificial constraints in the working set, i.e., the number of columns of ZA (see Section 11.4).
Zr | is the number of columns of ZR (see Section 11.2). Zr is the dimension of the subspace in which the objective function is currently being minimized. The value of Zr is the number of variables minus the number of constraints in the working set; i.e., Zr=n-Bnd+Lin+Art. The value of nZ, the number of columns of Z (see Section 11.2) can be calculated as nZ=n-Bnd+Lin. A zero value of nZ implies that x lies at a vertex of the feasible region.
Norm Gz | is ZRT gFR , the Euclidean norm of the reduced gradient with respect to ZR. During the optimality phase, this norm will be approximately zero after a unit step.
NOpt | is the number of nonoptimal Lagrange multipliers at the current point. NOpt is not printed if the current x is infeasible or no multipliers have been calculated. At a minimizer, NOpt will be zero.
Min Lm | is the value of the Lagrange multiplier associated with the deleted constraint. If Min Lm is negative, a lower bound constraint has been deleted, if Min Lm is positive, an upper bound constraint has been deleted. If no multipliers are calculated during a given iteration Min Lm will be zero.
Cond T | is a lower bound on the condition number of the working set.
E04 Chapter Contents
E04 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


E04MGF/E04MGA : NAG Library, Mark 26

E04 Chapter Contents
E04 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

E04MGF/E04MGA

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
▸▿ 2 Specification
2.1 Specification for E04MGF
2.2 Specification for E04MGA
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

To supply optional parameters to E04MFF/E04MFA from an external file. More precisely, E04MGF must be used to supply optional parameters to E04MFF and E04MGA must be used to supply optional parameters to E04MFA.
E04MGA is a version of E04MGF that has additional arguments in order to make it safe for use in multithreaded applications (see Section 5). The initialization routine E04WBF must have been called before calling E04MGA.

2 Specification

2.1 Specification for E04MGF

SUBROUTINE E04MGF ( IOPTNS, INFORM)
INTEGER IOPTNS, INFORM

2.2 Specification for E04MGA

SUBROUTINE E04MGA ( IOPTNS, LWSAV, IWSAV, RWSAV, INFORM)
INTEGER | IOPTNS, IWSAV(610), INFORM
REAL (KIND=nag_wp) | RWSAV(475)
LOGICAL | LWSAV(120)

3 Description

E04MGF/E04MGA may be used to supply values for optional parameters to E04MFF/E04MFA. E04MGF/E04MGA reads an external file and each line of the file defines a single optional parameter. It is only necessary to supply values for those arguments whose values are to be different from their default values.
Each optional parameter is defined by a single character string, of up to 72 characters, consisting of one or more items. The items associated with a given option must be separated by spaces, or equals signs =. Alphabetic characters may be upper or lower case. The string
Print Level = 1
is an example of a string used to set an optional parameter. For each option the string contains one or more of the following items:
– | a mandatory keyword;
– | a phrase that qualifies the keyword;
– | a number that specifies an integer or real value. Such numbers may be up to 40 contiguous characters in Fortran's I, F, E or D formats, terminated by a space if this is not the last item on the line.
Blank strings and comments are ignored. A comment begins with an asterisk (*) and all subsequent characters in the string are regarded as part of the comment.
The file containing the options must start with Begin and must finish with End. An example of a valid options file is:
Begin * Example options file
   Print level = 5
End
For E04MGF each line of the file is normally printed as it is read, on the current advisory message unit (see X04ABF), but printing may be suppressed using the keyword Nolist. To suppress printing of Begin, Nolist must be the first option supplied as in the file:
Begin
   Nolist
   Print level = 5
End
Printing will automatically be turned on again after a call to E04MFF or E04MGF and may be turned on again at any time using the keyword List.
For E04MGA printing is turned off by default, but may be turned on at any time using the keyword List.
Optional parameter settings are preserved following a call to E04MFF/E04MFA and so the keyword Defaults is provided to allow you to reset all the optional parameters to their default values before a subsequent call to E04MFF/E04MFA.
A complete list of optional parameters, their abbreviations, synonyms and default values is given in Section 12 in E04MFF/E04MFA.

4 References

None.

5 Arguments

1:   IOPTNS – INTEGERInput
On entry: the unit number of the options file to be read.
Constraint: 0≤IOPTNS≤99.
2:   INFORM – INTEGEROutput
Note: for E04MGA, INFORM does not occur in this position in the argument list. See the additional arguments described below.
On exit: contains zero if the options file has been successfully read and a value>0 otherwise (see Section 6).
Note: the following are additional arguments for specific use with E04MGA. Users of E04MGF therefore need not read the remainder of this description.
2:   LWSAV 120 – LOGICAL arrayCommunication Array
3:   IWSAV 610 – INTEGER arrayCommunication Array
4:   RWSAV 475 – REAL (KIND=nag_wp) arrayCommunication Array
The arrays LWSAV, IWSAV and RWSAV must not be altered between calls to any of the routines E04MGA, E04MFA, E04MHA or E04WBF.
5:   INFORM – INTEGEROutput
Note: see the argument description for INFORM above.

6 Error Indicators and Warnings

INFORM=1
IOPTNS is not in the range 0,99.
INFORM=2
Begin was found, but end-of-file was found before End was found.
INFORM=3
end-of-file was found before Begin was found.
INFORM=4
Not used.
INFORM=5
One or more lines of the options file is invalid. Check that all keywords are neither ambiguous nor misspelt.

7 Accuracy

Not applicable.

8 Parallelism and Performance

E04MGF/E04MGA is not threaded in any implementation.

9 Further Comments

E04MHF/E04MHA may also be used to supply optional parameters to E04MFF/E04MFA.

10 Example

This example solves the same problem as the example for E04MFF/E04MFA, but in addition illustrates the use of E04MGF/E04MGA and E04MHF/E04MHA to set optional parameters for E04MFF/E04MFA.
In this example the options file read by E04MGF/E04MGA is appended to the data file for the program (see Section 10.2). It would usually be more convenient in practice to keep the data file and the options file separate.

10.1 Program Text

Note: the following programs illustrate the use of E04MGF and E04MGA.

Program Text (e04mgfe.f90)

Program Text (e04mgae.f90)

10.2 Program Data

Program Options (e04mgfe.opt)

Program Options (e04mgae.opt)

Program Data (e04mgfe.d)

Program Data (e04mgae.d)

10.3 Program Results

Program Results (e04mgfe.r)

Program Results (e04mgae.r)

E04 Chapter Contents
E04 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


E04MHF/E04MHA : NAG Library, Mark 26

E04 Chapter Contents
E04 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

E04MHF/E04MHA

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
▸▿ 2 Specification
2.1 Specification for E04MHF
2.2 Specification for E04MHA
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
10 Example

1 Purpose

To supply individual optional parameters to E04MFF/E04MFA. More precisely, E04MHF must be used to supply optional parameters to E04MFF and E04MHA must be used to supply optional parameters to E04MFA.
E04MHA is a version of E04MHF that has additional arguments in order to make it safe for use in multithreaded applications (see Section 5). The initialization routine E04WBF must have been called before calling E04MHA.

2 Specification

2.1 Specification for E04MHF

SUBROUTINE E04MHF ( STR)
CHARACTER(*) STR

2.2 Specification for E04MHA

SUBROUTINE E04MHA ( STR, LWSAV, IWSAV, RWSAV, INFORM)
INTEGER | IWSAV(610), INFORM
REAL (KIND=nag_wp) | RWSAV(475)
LOGICAL | LWSAV(120)
CHARACTER(*) | STR

3 Description

E04MHF/E04MHA may be used to supply values for optional parameters to E04MFF/E04MFA. It is only necessary to call E04MHF/E04MHA for those arguments whose values are to be different from their default values. One call to E04MHF/E04MHA sets one argument value.
Each optional parameter is defined by a single character string, of up to 72 characters, consisting of one or more items. The items associated with a given option must be separated by spaces, or equals signs =. Alphabetic characters may be upper or lower case. The string
Print Level = 1
is an example of a string used to set an optional parameter. For each option the string contains one or more of the following items:
– | a mandatory keyword;
– | a phrase that qualifies the keyword;
– | a number that specifies an integer or real value. Such numbers may be up to 40 contiguous characters in Fortran's I, F, E or D formats, terminated by a space if this is not the last item on the line.
Blank strings and comments are ignored. A comment begins with an asterisk (*) and all subsequent characters in the string are regarded as part of the comment.
For E04MHF, each user-specified option is normally printed as it is defined, on the current advisory message unit (see X04ABF), but this printing may be suppressed using the keyword Nolist. Thus the statement
 CALL E04MHF ('Nolist')
suppresses printing of this and subsequent options. Printing will automatically be turned on again after a call to E04MFF and may be turned on again at any time using the keyword List.
For E04MHA printing is turned off by default, but may be turned on at any time using the keyword List.
Optional parameter settings are preserved following a call to E04MFF/E04MFA and so the keyword Defaults is provided to allow you to reset all the optional parameters to their default values before a subsequent call to E04MFF/E04MFA.
A complete list of optional parameters, their abbreviations, synonyms and default values is given in Section 12 in E04MFF/E04MFA.

4 References

None.

5 Arguments

1:   STR – CHARACTER(*)Input
On entry: a single valid option string (as described in Section 3 and in Section 12 in E04MFF/E04MFA).
Note: the following are additional arguments for specific use with E04MHA. Users of E04MHF therefore need not read the remainder of this description.
2:   LWSAV 120 – LOGICAL arrayCommunication Array
3:   IWSAV 610 – INTEGER arrayCommunication Array
4:   RWSAV 475 – REAL (KIND=nag_wp) arrayCommunication Array
The arrays LWSAV, IWSAV and RWSAV must not be altered between calls to any of the routines E04MHA, E04MFA, E04MGA or E04WBF.
5:   INFORM – INTEGEROutput
On exit: contains zero if a valid option string has been supplied and a value>0 otherwise (see Section 6).

6 Error Indicators and Warnings

INFORM=5
The supplied option is invalid. Check that the keywords are neither ambiguous nor misspelt.

7 Accuracy

Not applicable.

8 Parallelism and Performance

E04MHF/E04MHA is not threaded in any implementation.

9 Further Comments

E04MGF/E04MGA may also be used to supply optional parameters to E04MFF/E04MFA.

10 Example

See Section 10 in E04MGF/E04MGA.
E04 Chapter Contents
E04 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


E04MWF : NAG Library, Mark 26

E04 Chapter Contents
E04 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

E04MWF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

E04MWF writes data for sparse linear programming, mixed integer linear programming, quadratic programming or mixed integer quadratic programming problems to a file in MPS format.

2 Specification

SUBROUTINE E04MWF ( OUTFILE, N, M, NNZC, NNZA, NCOLH, NNZH, LINTVAR, IDXC, C, IOBJ, A, IROWA, ICCOLA, BL, BU, PNAMES, NNAME, CRNAME, H, IROWH, ICCOLH, MINMAX, INTVAR, IFAIL)
INTEGER | OUTFILE, N, M, NNZC, NNZA, NCOLH, NNZH, LINTVAR, IDXC(NNZC), IOBJ, IROWA(NNZA), ICCOLA(N+1), NNAME, IROWH(NNZH), ICCOLH(NCOLH+1), MINMAX, INTVAR(LINTVAR), IFAIL
REAL (KIND=nag_wp) | C(NNZC), A(NNZA), BL(N+M), BU(N+M), H(NNZH)
CHARACTER(8) | PNAMES(5), CRNAME(NNAME)

3 Description

E04MWF writes data for linear programming (LP) or quadratic programming (QP) problems (or their mixed integer variants) from an optimization problem to a MPS output file, see Section 3.1 in E04MXF for the format description. The problem is expected in the form
minimize x ⁡ cT x+12 xT Hx   subject to  l≤ x Ax ≤u.
Where n is the number of variables, m is the number of general linear constraints, A is the linear constraint matrix with dimension m by n, the vectors l and u are the lower and upper bounds, respectively. H is the Hessian matrix with dimension n by n, however, only leading NCOLH columns might contain nonzero elements and the rest is assumed to be zero.
Note that the linear term of the objective function c might be supplied either as C or via IOBJ. If C is supplied then IDXC contains the indices of the nonzero elements of sparse vector c, whereas if IOBJ is supplied (IOBJ>0), row IOBJ of matrix A is a free row storing the nonzero elements of c.
Note: that this routine uses fixed MPS format, see IBM (1971).

4 References

IBM (1971) MPSX – Mathematical programming system Program Number 5734 XM4 IBM Trade Corporation, New York

5 Arguments

1:   OUTFILE – INTEGERInput
On entry: the ID of the file to store the problem data as associated by a call to X04ACF.
Constraint: OUTFILE≥0.
2:   N – INTEGERInput
On entry: n, the number of variables in the problem.
Constraint: N≥1.
3:   M – INTEGERInput
On entry: m, the number of constraints in the problem. This is the number of rows in the linear constraint matrix A, including the free row (if any; see IOBJ).
Constraint: M≥0.
4:   NNZC – INTEGERInput
On entry: the number of nonzero elements in the sparse vector c.
If NNZC=0, the vector c is considered empty and the arrays IDXC and C will not be referenced. In this case the linear term of the objective function, if any, might be provided via IOBJ.
Constraints:
  • NNZC≥0;
  • if NNZC>0, IOBJ=0.
5:   NNZA – INTEGERInput
On entry: the number of nonzero elements in matrix A.
If NNZA=0, matrix A is considered empty, arrays A and IROWA will not be referenced, and ICCOLA should be the array of 1.
Constraint: NNZA≥0.
6:   NCOLH – INTEGERInput
On entry: the number of leading nonzero columns of the Hessian matrix H.
If NCOLH=0, the quadratic term H of the objective function is considered zero (e.g., LP problems), and arrays H, IROWH and ICCOLH will not be referenced.
Constraint: 0≤NCOLH≤N.
7:   NNZH – INTEGERInput
On entry: the number of nonzero elements of the Hessian matrix H.
Constraints:
  • if NCOLH>0, NNZH>0;
  • otherwise NNZH=0.
8:   LINTVAR – INTEGERInput
On entry: the number of integer variables in the problem.
If LINTVAR=0, all variables are considered continuous and array INTVAR will not be referenced.
Constraint: LINTVAR≥0.
9:   IDXC NNZC – INTEGER arrayInput
10:   C NNZC – REAL (KIND=nag_wp) arrayInput
On entry: the nonzero elements of sparse vector c. IDXC i must contain the index of C i in the vector, for i=1,2,…,NNZC.
The elements are stored in ascending order.
Constraints:
  • 1≤IDXC i≤N, for i=1,2,…,NNZC;
  • IDXC i<IDXC i+1, for i=1,2,…,NNZC.
11:   IOBJ – INTEGERInput
On entry: if IOBJ>0, row IOBJ of A is a free row containing the nonzero coefficients of the linear terms of the objective function. In this case NNZC is set to 0.
If IOBJ=0, there is no free row in A, and the linear terms might be supplied in array C.
Constraint: if IOBJ>0, NNZC=0.
12:   A NNZA – REAL (KIND=nag_wp) arrayInput
13:   IROWA NNZA – INTEGER arrayInput
14:   ICCOLA N+1 – INTEGER arrayInput
On entry: the nonzero elements of matrix A in compressed column storage (see Section 2.1.3 in the F11 Chapter Introduction). Arrays IROWA and A store the row indices and the values of the nonzero elements, respectively. The elements are sorted by columns and within each column in nondecreasing order. Duplicate entries are not allowed. ICCOLA contains the (one-based) indices to the beginning of each column in A and IROWA.
If NNZA=0, A and IROWA are not referenced.
Constraints:
  • 1≤IROWA i≤M, for i=1,2,…,NNZA;
  • ICCOLA 1=1;
  • ICCOLA i≤ICCOLA i+1, for i=1,2,…,N;
  • ICCOLA N+1=NNZA+1.
15:   BL N+M – REAL (KIND=nag_wp) arrayInput
16:   BU N+M – REAL (KIND=nag_wp) arrayInput
On entry: BL and BU contains the lower bounds l and the upper bounds u, respectively.
The first N elements refer to the bounds for the variables x and the rest to the bounds for the linear constraints (including the objective row IOBJ if present).
To specify a nonexistent lower bound (i.e., lj=-inf), set BL j≤-10 20; to specify a nonexistent upper bound, set BU j≥1020.
Constraints:
  • BL j≤BU j, for j=1,2,…,N+M;
  • BL j<1020, for j=1,2,…,N+M;
  • BU j>-1020, for j=1,2,…,N+M;
  • if IOBJ>0, BL IOBJ+N≤-1020 and BU IOBJ+N≥1020.
17:   PNAMES 5 – CHARACTER(8) arrayInput
On entry: a set of names associated with the MPSX form of the problem.
The names can be composed only from ‘printable’ characters (ASCII codes between 32 and 126).
If any of the names are blank, the default name is used.
PNAMES 1
Contains the name of the problem.
PNAMES 2
Contains the name of the objective row if the objective is provided in C instead of IOBJ and all names CRNAME are given. The name must be nonempty and unique. In all other cases PNAMES 2 is not used.
PNAMES 3
Contains the name of the RHS set.
PNAMES 4
Contains the name of the RANGE.
PNAMES 5
Contains the name of the BOUNDS.
18:   NNAME – INTEGERInput
On entry: the number of column (i.e., variable) and row names supplied in the array CRNAME.
If NNAME=0, the names are automatically generated and the array CRNAME is not referenced.
Constraint: NNAME=0 or N+M.
19:   CRNAME NNAME – CHARACTER(8) arrayInput
On entry: the names of all the variables and constraints in the problem in that order.
The names can be composed only from 'printable' characters and must be unique.
20:   H NNZH – REAL (KIND=nag_wp) arrayInput
21:   IROWH NNZH – INTEGER arrayInput
22:   ICCOLH NCOLH+1 – INTEGER arrayInput
On entry: the nonzero elements of the Hessian matrix H in compressed column storage (see Section 2.1.3 in the F11 Chapter Introduction). The Hessian matrix, H, is symmetric and its elements are stored in a lower triangular matrix.
Arrays IROWH and H store the row indices and the values of the nonzero elements, respectively. The elements are sorted by columns and within each column in nondecreasing order. Duplicate entries are not allowed. ICCOLH contains the (one-based) indices to the beginning of each column in H and IROWH.
If NCOLH=0, H is not referenced.
Constraints:
  • 1≤IROWH i≤NCOLH, for i=1,2,…,NNZH;
  • ICCOLH 1=1;
  • ICCOLH i≤ICCOLH i+1, for i=1,2,…,NCOLH;
  • ICCOLH NCOLH+1=NNZH+1.
23:   MINMAX – INTEGERInput
On entry: MINMAX defines the direction of optimization problem.
MINMAX=-1
Minimization.
MINMAX=1
Maximization.
Constraint: MINMAX=-1 or 1.
24:   INTVAR LINTVAR – INTEGER arrayInput
On entry: INTVAR contains the indices k of variables xk which are defined as integers. Duplicate indices are not allowed.
If LINTVAR=0, INTVAR is not referenced.
Constraint: 1≤INTVAR j≤N, for j=1,2,…,LINTVAR.
25:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, OUTFILE=value.
Constraint: OUTFILE≥0.
IFAIL=2
On entry, M=value.
Constraint: M≥0.
On entry, N=value.
Constraint: N≥1.
IFAIL=3
On entry, LINTVAR=value.
Constraint: LINTVAR≥0.
On entry, NNAME=value, N=value and M=value.
Constraint: NNAME=0 or N+M.
On entry, NNZA=value.
Constraint: NNZA≥0.
On entry, NNZC=value.
Constraint: NNZC≥0.
IFAIL=4
On entry, NCOLH=value and N=value.
Constraint: 0≤NCOLH≤N.
On entry, NCOLH=value and NNZH=value.
Constraint: if NCOLH>0, NNZH>0.
On entry, NCOLH=value and NNZH=value.
Constraint: if NCOLH=0, NNZH=0 .
IFAIL=5
On entry, j=value, IDXC j=value and IDXC j+1=value.
Constraint: IDXC j<IDXC j+1.
On entry, j=value, IDXC j=value and N=value.
Constraint: 1≤IDXC j≤N.
IFAIL=6
On entry, MINMAX=value.
Constraint: MINMAX=-1 or 1.
IFAIL=7
On entry, IOBJ=value and M=value.
Constraint: 0≤IOBJ≤M.
On entry, IOBJ=value and NNZC=value.
Constraint: at most one of IOBJ or NNZC may be nonzero.
IFAIL=8
On entry, IOBJ=value, BL j=value and BU j=value, if IOBJ>0 the bounds must be infinite.
Constraints: BL j≤-1E+20, BU j≥1E+20.
On entry, j=value, BL j=value and BU j=value, the integer variable j requires at least one bound finite.
Constraint: at least one of the following conditions must be met for integer variable j: BL j>−1E+20, BU j<1E+20.
On entry, j=value, BL j=value and BU j=value are incorrect.
Constraint: BL j≤BU j.
On entry, j=value and BL j=value, BL j is incorrect.
Constraint: BL j<1E+20.
On entry, j=value and BU j=value, BU j is incorrect.
Constraint: BU j>-1E+20.
IFAIL=9
On entry, CRNAME j for j=value has been already used.
Constraint: the names in CRNAME must be unique.
On entry, CRNAME j for j=value is incorrect.
Constraint: the names in CRNAME must consist only of printable characters.
On entry, PNAMES j for j=value is incorrect.
Constraint: the names in PNAMES must consist only of printable characters.
The name specified in PNAMES 2 is empty or has been already used among row names.
Constraint: the names in PNAMES 2 must be unique and nonempty if CRNAME is provided and NNZC>0.
IFAIL=10
On entry, INTVAR value=INTVAR value= value.
Constraint: all entries in INTVAR must be unique.
On entry, j=value, INTVAR j=value and LINTVAR=value.
Constraint: 1≤INTVAR j≤LINTVAR.
IFAIL=11
On entry, i=value, IROWA i=value and M=value.
Constraint: 1≤IROWA i≤M.
On entry, more than one element of A has row index value and column index value.
Constraint: each element of A must have a unique row and column index.
IFAIL=12
On entry, ICCOLA 1=value.
Constraint: ICCOLA 1=1.
On entry, ICCOLA N+1=value and NNZA=value.
Constraint: ICCOLA N+1=NNZA+1.
On entry, j=value, ICCOLA j=value and ICCOLA j+1=value, the values of ICCOLA must be nondecreasing.
Constraint: ICCOLA j≤ICCOLA j+1.
IFAIL=13
On entry, j=value, i=value, NCOLH=value and IROWH i=value
Constraint: j≤IROWH i≤NCOLH (within the lower triangle).
On entry, more than one element of H has row index value and column index value.
Constraint: each element of H must have a unique row and column index.
IFAIL=14
On entry, ICCOLH 1=value.
Constraint: ICCOLH 1=1.
On entry, ICCOLH NCOLH+1=value and NNZH=value.
Constraint: ICCOLH NCOLH+1=NNZH+1.
On entry, j=value, ICCOLH j=value and ICCOLH j+1=value, the values of ICCOLH must be nondecreasing.
Constraint: ICCOLH j≤ICCOLH j+1.
IFAIL=15
An error occurred when writing to file.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

Not applicable.

8 Parallelism and Performance

E04MWF is not threaded in any implementation.

9 Further Comments

None.

10 Example

This example shows how to store an optimization problem to a file in MPS format after it has been solved by E04NQF. The problem is a minimization of the quadratic function f x=cT x+12 xT Hx, where
c=-200.0,-2000.0,-2000.0,-2000.0,-2000.0,400.0,400.0 T
H= 2 0 0 0 0 0 0 0 2 0 0 0 0 0 0 0 2 2 0 0 0 0 0 2 2 0 0 0 0 0 0 0 2 0 0 0 0 0 0 0 2 2 0 0 0 0 0 2 2
subject to the bounds
00 0≤x 1≤0 200 00 0≤x 2≤2500 400≤x 3≤0 800 100≤x 4≤0 700 00 0≤x 5≤1500 00 0≤x 6≤1500 00 0≤x 7≤1500
and to the linear constraints
x 1 + x 2 + x 3 + x 4 + x 5 + x 6 + x 7 = 2000 0.15 x 1 + 0.04 x 2 + 0.02 x 3 + 0.04 x 4 + 0.02 x 5 + 0.01 x 6 + 0.03 x 7 ≤ 60 0.03 x 1 + 0.05 x 2 + 0.08 x 3 + 0.02 x 4 + 0.06 x 5 + 0.01 x 6 ≤ 100 0.02 x 1 + 0.04 x 2 + 0.01 x 3 + 0.02 x 4 + 0.02 x 5 ≤ 40 0.02 x 1 + 0.03 x 2 + 0.01 x 5 ≤ 30 1500 ≤ 0.70 x 1 + 0.75 x 2 + 0.80 x 3 + 0.75 x 4 + 0.80 x 5 + 0.97 x 6 250 ≤ 0.02 x 1 + 0.06 x 2 + 0.08 x 3 + 0.12 x 4 + 0.02 x 5 + 0.01 x 6 + 0.97 x 7 ≤ 300
The initial point, which is infeasible, is
x 0=0.0,0.0,0.0,0.0,0.0,0.0,0.0 T.
The optimal solution (to five figures) is
x*=0.0,349.40,648.85,172.85,407.52,271.36,150.02 T.
The generated file is called e04mwfe.mps.

10.1 Program Text

Program Text (e04mwfe.f90)

10.2 Program Data

Program Data (e04mwfe.d)

10.3 Program Results

Program Results (e04mwfe.r)

E04 Chapter Contents
E04 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


E04MXF : NAG Library, Mark 26

E04 Chapter Contents
E04 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

E04MXF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
▸▿ 3 Description
▸▿ 3.1 MPS input format
3.1.1 NAME Section (optional)
3.1.2 OBJSENSE Section (optional)
3.1.3 OBJNAME Section (optional)
3.1.4 ROWS Section
▸▿ 3.1.5 COLUMNS Section
3.1.5.1 Integer Markers
3.1.6 RHS Section
3.1.7 RANGES Section (optional)
3.1.8 BOUNDS Section (optional)
3.1.9 QUADOBJ Section (optional)
3.2 Query Mode
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

E04MXF reads data for sparse linear programming, mixed integer linear programming, quadratic programming or mixed integer quadratic programming problems from an external file which is in standard or compatible MPS input format.

2 Specification

SUBROUTINE E04MXF ( INFILE, MAXN, MAXM, MAXNNZ, MAXNCOLH, MAXNNZH, MAXLINTVAR, MPSLST, N, M, NNZ, NCOLH, NNZH, LINTVAR, IOBJ, A, IROWA, ICCOLA, BL, BU, PNAMES, NNAME, CRNAME, H, IROWH, ICCOLH, MINMAX, INTVAR, IFAIL)
INTEGER | INFILE, MAXN, MAXM, MAXNNZ, MAXNCOLH, MAXNNZH, MAXLINTVAR, MPSLST, N, M, NNZ, NCOLH, NNZH, LINTVAR, IOBJ, IROWA(MAXNNZ), ICCOLA(MAXN+1), NNAME, IROWH(MAXNNZH), ICCOLH(MAXNCOLH+1), MINMAX, INTVAR(MAXLINTVAR), IFAIL
REAL (KIND=nag_wp) | A(MAXNNZ), BL(MAXN+MAXM), BU(MAXN+MAXM), H(MAXNNZH)
CHARACTER(8) | PNAMES(5), CRNAME(MAXN+MAXM)

3 Description

E04MXF reads data for linear programming (LP) or quadratic programming (QP) problems (or their mixed integer variants) from an external file which is prepared in standard or compatible MPS (see IBM (1971)) input format. It then initializes n (the number of variables), m (the number of general linear constraints), the m by n matrix A, the vectors l, u, c (stored in row IOBJ of A) and the n by n Hessian matrix H for use with E04NKF/E04NKA and E04NQF. These routines are designed to solve problems of the form
minimize x ⁡ cT x+12 xT Hx   subject to  l≤ x Ax ≤u.

3.1 MPS input format

The input file of data may only contain two types of lines:
1. | Indicator lines (specifying the type of data which is to follow).
2. | Data lines (specifying the actual data).
A section is a combination of an indicator line and its corresponding data line(s). Any characters beyond column 80 are ignored. Indicator lines must not contain leading blank characters (in other words they must begin in column 1). The following displays the order in which the indicator lines must appear in the file:
NAME | user-supplied name | (optional)
OBJSENSE |  | (optional)
 | data line
OBJNAME |  | (optional)
 | data line
ROWS
 | data line(s)
COLUMNS
 | data line(s)
RHS
 | data line(s)
RANGES |  | (optional)
 | data line(s)
BOUNDS |  | (optional)
 | data line(s)
QUADOBJ |  | (optional)
 | data line(s)
ENDATA
A data line follows a fixed format, being made up of fields as defined below. The contents of the fields may have different significance depending upon the section of data in which they appear.
 | Field 1 | Field 2 | Field 3 | Field 4 | Field 5 | Field 6
Columns | 2–3 | 5–12 | 15–22 | 25–36 | 40–47 | 50–61
Contents | Code | Name | Name | Value | Name | Value
Each name and code must consist of ‘printable’ characters only; names and codes supplied must match the case used in the following descriptions. Values are read using a field width of 12. This allows values to be entered in several equivalent forms. For example, 1.2345678, 1.2345678E+0, 123.45678E−2 and 12345678E−07 all represent the same number. It is safest to include an explicit decimal point.
Lines with an asterisk (*) in column 1 will be considered comment lines and will be ignored by the routine.
Columns outside the six fields must be blank, except for columns 72–80, whose contents are ignored by the routine. A non-blank character outside the predefined six fields and columns 72–80 is considered to be a major error (IFAIL=16; see Section 6), unless it is part of a comment.

3.1.1 NAME Section (optional)

The NAME section is the only section where the data must be on the same line as the indicator. The ‘user-supplied name’ must be in field 3 but may be blank.
Field | Required | Description
3 | No | Name of the problem

3.1.2 OBJSENSE Section (optional)

The data line in this section can be used to specify the sense of the objective function. If this section is present it must contain only one data line. If the section is missing or empty, minimization is assumed.
Field | Required | Description
2 | No | Sense of the objective function
Field 2 may contain either MIN, MAX, MINIMIZE or MAXIMIZE.

3.1.3 OBJNAME Section (optional)

The data line in this section can be used to specify the name of a free row (see Section 3.1.4) that should be used as the objective function. If this section is present it must contain only one data line. If the section is missing or is empty, the first free row will be chosen instead. Alternatively, OBJNAME can be overridden by setting nonempty PNAMES 2 (see Section 5).
Field | Required | Description
2 | No | Row name to be used as the objective function
Field 2 must contain a valid row name.

3.1.4 ROWS Section

The data lines in this section specify unique row (constraint) names and their inequality types (i.e., unconstrained, =, ≥ or ≤).
Field | Required | Description
1 | Yes | Inequality key
2 | Yes | Row name
The inequality key specifies each row's type. It must be E, G, L or N and can be in either column 2 or 3.
Inequality Key | Description | l | u
N | Free row | -∞ | ∞
G | Greater than or equal to | finite | ∞
L | Less than or equal to | -∞ | finite
E | Equal to | finite | l
Row type N stands for ‘Not binding’. It can be used to define the objective row. The objective row is a free row that specifies the vector c in the linear objective term cT x. If there is more than one free row, the first free row is chosen, unless another free row name is specified by OBJNAME (see Section 3.1.3) or PNAMES 2 (see Section 5). Note that c is assumed to be zero if either the chosen row does not appear in the COLUMNS section (i.e., has no nonzero elements) or there are no free rows defined in the ROWS section.

3.1.5 COLUMNS Section

Data lines in this section specify the names to be assigned to the variables (columns) in the general linear constraint matrix A, and define, in terms of column vectors, the actual values of the corresponding matrix elements.
Field | Required | Description
2 | Yes | Column name
3 | Yes | Row name
4 | Yes | Value
5 | No | Row name
6 | No | Value
Each data line in the COLUMNS section defines the nonzero elements of A or c. Any elements of A or c that are undefined are assumed to be zero. Nonzero elements of A must be grouped by column, that is to say that all of the nonzero elements in the jth column of A must be specified before those in the j+1th column, for j=1,2,…,n-1. Rows may appear in any order within the column.
3.1.5.1 Integer Markers
For backward compatibility E04MXF allows you to define the integer variables within the COLUMNS section using integer markers, although this is not recommended as markers can be treated differently by different MPS readers; you should instead define any integer variables in the BOUNDS section (see below). Each marker line must have the following format:
Field | Required | Description
2 | No | Marker ID
3 | Yes | Marker tag
5 | Yes | Marker type
The marker tag must be ⁢′MARKER⁢′. The marker type must be ⁢′INTORG⁢′ to start reading integer variables and ⁢′INTEND⁢′ to finish reading integer variables. This implies that a row cannot be named ⁢′MARKER⁢′, ⁢′INTORG⁢′ or ⁢′INTEND⁢′. Please note that both marker tag and marker type comprise of 8 characters as a ⁢′ is the mandatory first and last character in the string. You may wish to have several integer marker sections within the COLUMNS section, in which case each marker section must begin with an ⁢′INTORG⁢′ marker and end with an ⁢′INTEND⁢′ marker and there should not be another marker between them.
Field 2 is ignored by E04MXF. When an integer variable is declared it will keep its default bounds unless they are changed in the BOUNDS section. This may vary between different MPS readers.

3.1.6 RHS Section

This section specifies the right-hand side values (if any) of the general linear constraint matrix A.
Field | Required | Description
2 | Yes | RHS name
3 | Yes | Row name
4 | Yes | Value
5 | No | Row name
6 | No | Value
The MPS file may contain several RHS sets distinguished by RHS name. If an RHS name is defined in PNAMES 3 (see Section 5) then E04MXF will read in only that RHS vector, otherwise the first RHS set will be used.
Only the nonzero RHS elements need to be specified. Note that if an RHS is given to the objective function it will be ignored by E04MXF. An RHS given to the objective function is dealt with differently by different MPS readers, therefore it is safer to not define an RHS of the objective function in your MPS file. Note that this section may be empty, in which case the RHS vector is assumed to be zero.

3.1.7 RANGES Section (optional)

Ranges are used to modify the interpretation of constraints defined in the ROWS section (see Section 3.1.4) to the form l≤Ax≤u, where both l and u are finite. The range of the constraint is r=u-l.
Field | Required | Description
2 | Yes | Range name
3 | Yes | Row name
4 | Yes | Value
5 | No | Row name
6 | No | Value
The range of each constraint implies an upper and lower bound dependent on the inequality key of each constraint, on the RHS b of the constraint (as defined in the RHS section), and on the range r.
Inequality Key | Sign of r | l | u
E | + | b | b+r
E | - | b+r | b
G | +/- | b | b+r
L | +/- | b-r | b
N | +/- | -∞ | +∞
If a range name is defined in PNAMES 4 (see Section 5) then the routine will read in only the range set of that name, otherwise the first set will be used.

3.1.8 BOUNDS Section (optional)

These lines specify limits on the values of the variables (the quantities l and u in l≤x≤u). If a variable is not specified in the bound set then it is automatically assumed to lie between 0 and +∞.
Field | Required | Description
1 | Yes | Bound type identifier
2 | Yes | Bound name
3 | Yes | Column name
4 | Yes/No | Value
Note: field 4 is required only if the bound type identifier is one of UP, LO, FX, UI or LI in which case it gives the value k below. If the bound type identifier is FR, MI, PL or BV, field 4 is ignored and it is recommended to leave it blank.
The table below describes the acceptable bound type identifiers and how each determines the variables' bounds.
Bound Type Identifier | l | u | Integer Variable?
UP | unchanged | k | No
LO | k | unchanged | No
FX | k | k | No
FR | -∞ | ∞ | No
MI | -∞ | unchanged | No
PL | unchanged | ∞ | No
BV | 0 | 1 | Yes
UI | unchanged | k | Yes
LI | k | unchanged | Yes
If a bound name is defined in PNAMES 5 (see Section 5) then the routine will read in only the bound set of that name, otherwise the first set will be used.

3.1.9 QUADOBJ Section (optional)

The QUADOBJ section defines nonzero elements of the upper or lower triangle of the Hessian matrix H.
Field | Required | Description
2 | Yes | Column name (HColumn Index)
3 | Yes | Column name (HRow Index)
4 | Yes | Value
5 | No | Column name (HRow Index)
6 | No | Value
Each data line in the QUADOBJ section defines one (or optionally two) nonzero elements H ij of the matrix H. Each element H ij is given as a triplet of row index i, column index j and a value. The column names (as defined in the COLUMNS section) are used to link the names of the variables and the indices i and j. More precisely, the matrix H on output will have a nonzero element
H ij = Value
where index j belongs to HColumn Index and index i to one of the HRow Indices such that
  • CRNAME j=Column name (HColumn Index) and
  • CRNAME i=Column name (HRow Index).
It is only necessary to define either the upper or lower triangle of the H matrix; either will suffice. Any elements that have been defined in the upper triangle of the matrix will be moved to the lower triangle of the matrix, then any repeated nonzeros will be summed.
Note: it is much more efficient for E04NKF/E04NKA and E04NQF to have the H matrix defined by the first NCOLH column names. If the nonzeros of H are defined by any columns that are not in the first NCOLH of N then E04MXF will rearrange the matrices A and H so that they are.

3.2 Query Mode

E04MXF offers a ‘query mode’ to quickly give upper estimates on the sizes of user arrays. In this mode any expensive checks of the data and of the file format are skipped, providing a prompt count of the number of variables, constraints and matrix nonzeros. This might be useful in the common case where the size of the problem is not known in advance.
You may activate query mode by setting any of the following: MAXN<1, MAXM<1, MAXNNZ<1, MAXNCOLH<0 or MAXNNZH<0. If no major formatting error is detected in the data file, IFAIL=0 is returned and the upper estimates are given as stated in Table 1. Alternatively, the routine switches to query mode while the file is being read if it is discovered that the provided space is insufficient (that is, if N>MAXN, M>MAXM, NNZ>MAXNNZ, NCOLH>MAXNCOLH, NNZH>MAXNNZH or LINTVAR>MAXLINTVAR). In this case IFAIL=2 is returned.
Argument Name | Upper Estimate for
N | MAXN
M | MAXM
NNZ | MAXNNZ
NCOLH | MAXNCOLH
NNZH | MAXNNZH
LINTVAR | MAXLINTVAR
Table 1
The recommended practice is shown in Section 10, where the routine is invoked twice. The first call queries the array lengths required, after which the data arrays are allocated to be of these sizes. The second call reads the data using the sufficiently-sized arrays.

4 References

IBM (1971) MPSX – Mathematical programming system Program Number 5734 XM4 IBM Trade Corporation, New York

5 Arguments

1:   INFILE – INTEGERInput
On entry: the ID of the MPSX data file to be read as returned by a call to X04ACF.
Constraint: INFILE≥0.
2:   MAXN – INTEGERInput
On entry: an upper limit for the number of variables in the problem.
If MAXN<1, E04MXF will start in query mode (see Section 3.2).
3:   MAXM – INTEGERInput
On entry: an upper limit for the number of general linear constraints (including the objective row) in the problem.
If MAXM<1, E04MXF will start in query mode (see Section 3.2).
4:   MAXNNZ – INTEGERInput
On entry: an upper limit for the number of nonzeros (including the objective row) in the problem.
If MAXNNZ<1, E04MXF will start in query mode (see Section 3.2).
5:   MAXNCOLH – INTEGERInput
On entry: an upper limit for the dimension of the matrix H.
If MAXNCOLH<0, E04MXF will start in query mode (see Section 3.2).
6:   MAXNNZH – INTEGERInput
On entry: an upper limit for the number of nonzeros of the matrix H.
If MAXNNZH<0, E04MXF will start in query mode (see Section 3.2).
7:   MAXLINTVAR – INTEGERInput
On entry: if MAXLINTVAR≥0, an upper limit for the number of integer variables.
If MAXLINTVAR<0, E04MXF will treat all integer variables in the file as continuous variables.
8:   MPSLST – INTEGERInput
On entry: if MPSLST≠0, summary messages are sent to the current advisory message unit (as defined by X04ABF) as E04MXF reads through the data file. This can be useful for debugging the file. If MPSLST=0, then no summary is produced.
9:   N – INTEGEROutput
On exit: if E04MXF was run in query mode (see Section 3.2), or returned with IFAIL=2, an upper estimate of the number of variables of the problem. Otherwise, n, the actual number of variables in the problem.
10:   M – INTEGEROutput
On exit: if E04MXF was run in query mode (see Section 3.2), or returned with IFAIL=2, an upper estimate of the number of general linear constraints in the problem (including the objective row). Otherwise m, the actual number of general linear constaints of the problem.
11:   NNZ – INTEGEROutput
On exit: if E04MXF was run in query mode (see Section 3.2), or returned with IFAIL=2, an upper estimate of the number of nonzeros in the problem (including the objective row). Otherwise the actual number of nonzeros in the problem (including the objective row).
12:   NCOLH – INTEGEROutput
On exit: if E04MXF was run in query mode (see Section 3.2), or returned with IFAIL=2, an upper estimate of the value of NCOLH required by E04NKF/E04NKA and E04NQF. In this context NCOLH is the number of leading nonzero columns of the Hessian matrix H. Otherwise, the actual dimension of the matrix H.
13:   NNZH – INTEGEROutput
On exit: if E04MXF was run in query mode (see Section 3.2), or returned with IFAIL=2, an upper estimate of the number of nonzeros of the matrix H. Otherwise, the actual number of nonzeros of the matrix H.
14:   LINTVAR – INTEGEROutput
On exit: if on entry MAXLINTVAR<0, all integer variables are treated as continuous and LINTVAR=-1.
If E04MXF was run in query mode (see Section 3.2), or returned with IFAIL=2, an upper estimate of the number of integer variables of the problem. Otherwise, the actual number of integer variables of the problem.
15:   IOBJ – INTEGEROutput
On exit: if IOBJ>0, row IOBJ of A is a free row containing the nonzero coefficients of the vector c.
If IOBJ=0, the coefficients of c are assumed to be zero.
If E04MXF is run in query mode (see Section 3.2) IOBJ is not referenced.
16:   A MAXNNZ – REAL (KIND=nag_wp) arrayOutput
On exit: the nonzero elements of A, ordered by increasing column index.
If E04MXF is run in query mode (see Section 3.2), A is not referenced.
17:   IROWA MAXNNZ – INTEGER arrayOutput
On exit: the row indices of the nonzero elements stored in A.
If E04MXF is run in query mode (see Section 3.2), IROWA is not referenced.
18:   ICCOLA MAXN+1 – INTEGER arrayOutput
On exit: a set of pointers to the beginning of each column of A. More precisely, ICCOLA i contains the index in A of the start of the ith column, for i=1,2,…,N. Note that ICCOLA 1=1 and ICCOLA N+1=NNZ+1.
If E04MXF is run in query mode (see Section 3.2), ICCOLA is not referenced.
19:   BL MAXN+MAXM – REAL (KIND=nag_wp) arrayOutput
20:   BU MAXN+MAXM – REAL (KIND=nag_wp) arrayOutput
On exit: BL contains the vector l (the lower bounds) and BU contains the vector u (the upper bounds), for all the variables and constraints in the following order. The first N elements of each array contains the bounds on the variables x and the next M elements contains the bounds for the linear objective term cT x and for the general linear constraints Ax (if any). Note that an ‘infinite’ lower bound is indicated by BL j = -1.0E+20 and an ‘infinite’ upper bound by BU j=+1.0E+20. In other words, any element of u greater than or equal to 1020 will be regarded as +∞ (and similarly any element of l less than or equal to -1020 will be regarded as -∞). If this value is deemed to be ‘inappropriate’, before calling E04NKF/E04NKA or E04NQF you are recommended to reset the value of its optional parameter E04NKF/E04NKA and E04NQF and make any necessary changes to BL and/or BU.
If E04MXF is run in query mode (see Section 3.2), BL and BU are not referenced.
21:   PNAMES 5 – CHARACTER(8) arrayInput/Output
On entry: a set of names associated with the MPSX form of the problem.
PNAMES 1
Must either contain the name of the problem or be blank.
PNAMES 2
Must either be blank or contain the name of the objective row (in which case it overrides OBJNAME section and the default choice of the first objective free row).
PNAMES 3
Must either contain the name of the RHS set to be used or be blank (in which case the first RHS set is used).
PNAMES 4
Must either contain the name of the RANGE set to be used or be blank (in which case the first RANGE set (if any) is used).
PNAMES 5
Must either contain the name of the BOUNDS set to be used or be blank (in which case the first BOUNDS set (if any) is used).
On exit: a set of names associated with the problem as defined in the MPSX data file as follows:
PNAMES 1
Contains the name of the problem (or blank if none).
PNAMES 2
Contains the name of the objective row (or blank if none).
PNAMES 3
Contains the name of the RHS set (or blank if none).
PNAMES 4
Contains the name of the RANGE set (or blank if none).
PNAMES 5
Contains the name of the BOUNDS set (or blank if none).
If E04MXF is run in query mode (see Section 3.2), PNAMES is not referenced.
22:   NNAME – INTEGEROutput
On exit: n+m, the total number of variables and constraints in the problem (including the objective row).
If E04MXF was run in query mode (see Section 3.2), or returned with IFAIL=2, NNAME is not set.
23:   CRNAME MAXN+MAXM – CHARACTER(8) arrayOutput
On exit: the MPS names of all the variables and constraints in the problem in the following order. The first N elements contain the MPS names for the variables and the next M elements contain the MPS names for the objective row and general linear constraints (if any). Note that the MPS name for the objective row is stored in CRNAME N+IOBJ.
If E04MXF is run in query mode (see Section 3.2), CRNAME is not referenced.
24:   H MAXNNZH – REAL (KIND=nag_wp) arrayOutput
On exit: the NNZH nonzero elements of H, arranged by increasing column index.
If E04MXF is run in query mode (see Section 3.2), H is not referenced.
25:   IROWH MAXNNZH – INTEGER arrayOutput
On exit: the NNZH row indices of the elements stored in H.
If E04MXF is run in query mode (see Section 3.2), IROWH is not referenced.
26:   ICCOLH MAXNCOLH+1 – INTEGER arrayOutput
On exit: a set of pointers to the beginning of each column of H. More precisely, ICCOLH i contains the index in H of the start of the ith column, for i=1,2,…,NCOLH. Note that ICCOLH 1=1 and ICCOLH NCOLH+1=NNZH+1.
If E04MXF is run in query mode (see Section 3.2), ICCOLH is not referenced.
27:   MINMAX – INTEGEROutput
On exit: MINMAX defines the direction of the optimization as read from the MPS file. By default the routine assumes the objective function should be minimized and will return MINMAX=-1. If the routine discovers in the OBJSENSE section that the objective function should be maximized it will return MINMAX=1. If the routine discovers that there is neither the linear objective term c (the objective row) nor the Hessian matrix H, the problem is considered as a feasible point problem and MINMAX=0 is returned.
If E04MXF was run in query mode (see Section 3.2), or returned with IFAIL=2, MINMAX is not set.
28:   INTVAR MAXLINTVAR – INTEGER arrayOutput
On exit: if MAXLINTVAR>0 on entry, INTVAR contains pointers to the columns that are defined as integer variables. More precisely, INTVAR i=k, where k is the index of a column that is defined as an integer variable, for i=1,2,…,LINTVAR.
If MAXLINTVAR≤0 on entry, or E04MXF was run in query mode (see Section 3.2), or it returned with IFAIL=2, INTVAR is not set.
29:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).
Note that if any of the relevant arguments are accidentally set to zero, or not set and assume zero values, then the routine will have executed in query mode. In this case only the size of the problem is returned and other arguments are not set. See Section 3.2.

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
Warning: MPS file not strictly fixed format, although the problem was read anyway. The data may have been read incorrectly. You should set MPSLST=1 and repeat the call to E04MXF for more details.
IFAIL=2
At least one of MAXM, MAXN, MAXNNZ, MAXNNZH, MAXNCOLH or MAXLINTVAR is too small. Suggested values are returned in M, N, NNZ, NNZH, NCOLH and LINTVAR respectively.
IFAIL=3
Incorrect ordering of indicator lines.
OBJNAME indicator line found after ROWS indicator line.
IFAIL=4
Incorrect ordering of indicator lines.
COLUMNS indicator line found before ROWS indicator line.
IFAIL=5
Incorrect ordering of indicator lines.
RHS indicator line found before COLUMNS indicator line.
IFAIL=6
Incorrect ordering of indicator lines.
RANGES indicator line found before RHS indicator line.
IFAIL=7
Incorrect ordering of indicator lines.
BOUNDS indicator line found before COLUMNS indicator line.
IFAIL=8
Incorrect ordering of indicator lines.
QUADOBJ indicator line found before BOUNDS indicator line.
IFAIL=9
Incorrect ordering of indicator lines.
QUADOBJ indicator line found before COLUMNS indicator line.
IFAIL=10
Unknown indicator line ‘value’.
IFAIL=12
Indicator line ‘value’ has been found more than once in the MPS file.
IFAIL=13
End of file found before ENDATA indicator line.
IFAIL=14
No indicator line found in file. It may be an empty file.
IFAIL=15
At least one mandatory section not found in MPS file.
IFAIL=16
An illegal line was detected in ‘value’ section.
This is neither a comment nor a valid data line.
IFAIL=17
Unknown inequality key ‘value’ in ROWS section.
Expected ‘N’, ‘G’, ‘L’ or ‘E’.
IFAIL=18
Empty ROWS section.
Neither the objective row nor the constraints were defined.
IFAIL=19
The supplied name, in PNAMES 2 or in OBJNAME, of the objective row was not found among the free rows in the ROWS section.
IFAIL=20
The supplied name, in PNAMES 5, of the BOUNDS set to be used was not found in the BOUNDS section.
IFAIL=21
The supplied name, in PNAMES 3, of the RHS set to be used was not found in the RHS section.
IFAIL=22
The supplied name, in PNAMES 4, of the RANGES set to be used was not found in the RANGES section.
IFAIL=23
Illegal row name.
Row names must consist of printable characters only.
IFAIL=24
Illegal column name.
Column names must consist of printable characters only.
IFAIL=25
Row name ‘value’ has been defined more than once in the ROWS section.
IFAIL=26
Column ‘value’ has been defined more than once in the COLUMNS section. Column definitions must be continuous. (See Section 3.1.5).
IFAIL=27
Found ‘INTORG’ marker within ‘INTORG’ to ‘INTEND’ range.
IFAIL=28
Found ‘INTEND’ marker without previous marker being ‘INTORG’.
IFAIL=29
Found ‘INTORG’ but not ‘INTEND’ before the end of the COLUMNS section.
IFAIL=30
Illegal marker type ‘value’.
Should be either ‘INTORG’ or ‘INTEND’.
IFAIL=31
Unknown row name ‘value’ in value section.
All row names must be specified in the ROWS section.
IFAIL=32
Unknown column name ‘value’ in value section.
All column names must be specified in the COLUMNS section.
IFAIL=33
Unknown bound type ‘value’ in BOUNDS section.
IFAIL=34
More than one nonzero of A has row name ‘value’ and column name ‘value’ in the COLUMNS section.
IFAIL=35
Field value did not contain a number (see Section 3).
IFAIL=36
On entry, INFILE=value.
Constraint: INFILE≥0.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

Not applicable.

8 Parallelism and Performance

E04MXF makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

None.

10 Example

This example solves the quadratic programming problem
minimize   cT x + 12 xT H x   subject to   l ≤Ax ≤u, -2 ≤A x ≤2,
where
c= -4.0 -1.0 -1.0 -1.0 -1.0 -1.0 -1.0 -0.1 -0.3 ,   H= 2 1 1 1 1 0 0 0 0 1 2 1 1 1 0 0 0 0 1 1 2 1 1 0 0 0 0 1 1 1 2 1 0 0 0 0 1 1 1 1 2 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 ,
A= 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 4.0 1.0 2.0 3.0 4.0 -2.0 1.0 1.0 1.0 1.0 1.0 -1.0 1.0 -1.0 1.0 1.0 1.0 1.0 1.0 ,
l= -2.0 -2.0 -2.0   and   u= 1.5 1.5 4.0 .
The optimal solution (to five figures) is
x*=2.0,-0.23333,-0.26667,-0.3,-0.1,2.0,2.0,-1.7777,-0.45555 T.
Three bound constraints and two general linear constraints are active at the solution. Note that, although the Hessian matrix is only positive semidefinite, the point x* is unique.
The MPS representation of the problem is given in Section 10.2.
Another example which shows how to use E04MXF together with the NAG optimization modelling suite is associated with E04RJF.

10.1 Program Text

Program Text (e04mxfe.f90)

10.2 Program Data

Program Options (e04mxfe.opt)

10.3 Program Results

Program Results (e04mxfe.r)

E04 Chapter Contents
E04 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


E04MZF : NAG Library, Mark 26

E04 Chapter Contents
E04 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

E04MZF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

E04MZF reads data for a sparse linear programming or quadratic programming problem from an external file which is in standard or compatible MPSX input format.

2 Specification

SUBROUTINE E04MZF ( INFILE, MAXN, MAXM, MAXNNZ, XBLDEF, XBUDEF, MPSLST, N, M, NNZ, IOBJ, NCOLH, A, HA, KA, BL, BU, START, NAMES, NNAME, CRNAME, XS, ISTATE, IFAIL)
INTEGER | INFILE, MAXN, MAXM, MAXNNZ, N, M, NNZ, IOBJ, NCOLH, HA(MAXNNZ), KA(MAXN+1), NNAME, ISTATE(MAXN+MAXM), IFAIL
REAL (KIND=nag_wp) | XBLDEF, XBUDEF, A(MAXNNZ), BL(MAXN+MAXM), BU(MAXN+MAXM), XS(MAXN+MAXM)
LOGICAL | MPSLST
CHARACTER(1) | START
CHARACTER(8) | NAMES(5), CRNAME(MAXN+MAXM)

3 Description

E04MZF reads linear programming (LP) or quadratic programming (QP) problem data from an external file which is prepared in standard or compatible MPSX (see IBM (1971)) input format and then initializes n (the number of variables), m (the number of general linear constraints), the m by n matrix A, and the vectors l, u and c (stored in row IOBJ of A) for use with E04NKF, which is designed to solve problems of the form
minimize x∈Rn cT x+12 xT Hx  subject to  l≤ x Ax ≤u.
For LP problems, H=0. For QP problems, you must set NCOLH>0 (see Section 5) and provide a subroutine to E04NKF to compute Hx for any given vector x. (This is illustrated in Section 10.) The optional parameter Maximize may be used to specify an alternative problem in which the objective function is maximized (see Section 12.1 in E04NKF/E04NKA).
MPSX input format
The input file of data may only contain two types of lines:
1. | Indicator lines (specifying the type of data which is to follow).
2. | Data lines (specifying the actual data).
The input file must not contain any blank lines. Any characters beyond column 80 are ignored. Indicator lines must not contain leading blank characters (in other words they must begin in column 1). The following displays the order in which the indicator lines must appear in the file:
NAME |  | user-supplied name
ROWS
 | data line(s)
COLUMNS
 | data line(s)
RHS
 | data line(s)
RANGES |  | (optional)
 | data line(s)
BOUNDS |  | (optional)
 | data line(s)
ENDATA
The ‘user-supplied name’ specifies a name for the problem and must occupy columns 15–22. The name can either be blank or up to a maximum of 8 characters.
A data line follows the same fixed format made up of fields defined below. The contents of the fields may have different significance depending upon the section of data in which they appear.
 | Field 1 | Field 2 | Field 3 | Field 4 | Field 5 | Field 6
Columns | 2–3 | 5–12 | 15–22 | 25–36 | 40–47 | 50–61
Contents | Code | Name | Name | Value | Name | Value
The names and codes consist of ‘alphanumeric’ characters (i.e., a–z, A–Z, 0–9, +, -, *, blank ( ), :, $ or full stop (.) only) and the names must not contain leading blank characters. Values are read using Fortran format E12.0. This allows values to be entered in several equivalent forms. For example, 1.2345678, 1.2345678E+0, 123.45678E−2 and 12345678E−07 all represent the same number. It is safest to include an explicit decimal point.
Note that in order to ensure numeric values are interpreted as intended, they should be right-justified in the 12-character field, with no trailing blanks. This is because in some situations trailing blanks may be interpreted as zeros and this can dramatically affect the interpretation of the value. This is relevant if the value contains an exponent, or if it contains neither an exponent nor an explicit decimal point. For example, the fields
%%%%1.23E-2%
%%%%%%%123%%
may be interpreted as 1.23E−20 and 12300 respectively (where % denotes a blank). The actual behaviour is system-dependent.
Comment lines are allowed in the data file. These must have an asterisk (*) in column 1 and any characters in columns 2–80. In any data line, a dollar sign ($) as the first character in Field 3 or 5 indicates that the information from that point through column 80 consists of comments.
Columns outside the six fields must be blank, except for columns 72–80, whose contents are ignored by the routine. These columns may be used to enter a sequence number. A non-blank character outside the predefined six fields and columns 72–80 is considered to be a major error (IFAIL=13; see Section 6), unless it is part of a comment.
ROWS Data Lines
These lines specify row (constraint) names and their inequality types (i.e., =, ≥ or ≤).
Field 1: | defines the constraint type. It may be in column 2 or column 3.
N | free row, that is no constraint. It may be used to define the objective row.
G | greater than or equal to (i.e., ≥).
L | less than or equal to (i.e., ≤).
E | exactly equal to (i.e., =).
Field 2: | defines the row name.
Row type N stands for ‘Not binding’, also known as ‘Free’. It can be used to define the objective row. The objective row is a free row that specifies the vector c in the linear objective term cT x. It is taken to be the first free row, unless some other free row name is specified by the NAMES array (see Section 5). Note that c is assumed to be zero if (for example) the line
%N%%DUMMYROW
(where % denotes a blank) appears in the ROWS section of the MPSX data file, and the row name DUMMYROW is omitted from the COLUMNS section.
COLUMNS Data Lines
These lines specify the names to be assigned to the variables (columns) in the general linear constraint matrix A, and define, in terms of column vectors, the actual values of the corresponding matrix elements.
  • Field 1: blank (ignored).
  • Field 2: gives the name of the column associated with the elements specified in the following fields.
  • Field 3: contains the name of a row.
  • Field 4: used in conjunction with Field 3 contains the value of the matrix element.
  • Field 5: is optional (may be used like Field 3).
  • Field 6: is optional (may be used like Field 4).
Note that only the nonzero elements of A and c need to be specified in the COLUMNS section, as any zero elements of A are removed and any unspecified elements of c are assumed to be zero. In addition, any nonzero elements in the jth column of A must be grouped together before those in the j+1th column, for j=1,2,…,n-1. Nonzero elements within a column may however appear in any order.
RHS Data Lines
This section specifies the right-hand side values of the general linear constraint matrix A (if any). The lines specify the name to be given to the right-hand side (RHS) vector along with the numerical values of the elements of the vector, which may appear in any order. The data lines have exactly the same format as the COLUMNS data lines, except that the column name is replaced by the RHS name. Only the nonzero elements need be specified. Note that this section may be empty, in which case the RHS vector is assumed to be zero.
RANGES Data Lines (optional)
Ranges are used for constraints of the form l≤Ax≤u, where both l and u are finite. The range of the constraint is r=u-l. Either l or u must be specified in the RHS section and r must be defined in this section. The data lines have exactly the same format as the COLUMNS data lines, except that the column name is replaced by the RANGES name.
BOUNDS Data Lines (optional)
These lines specify limits on the values of the variables (l and u in l≤x≤u). If the variable is not specified in the bound set then it is automatically assumed to lie between default lower and upper bounds (usually 0 and +∞). Like an RHS column which is given a name, the set of variables in one bound set is also given a name.
Field 1: | specifies the type of bound or defines the variable type.
LO | lower bound
UP | upper bound
FX | fixed variable
FR | free variable (-∞ to +∞)
MI | lower bound is -∞
PL | upper bound is +∞. This is the default variable type.
Field 2: | identifies a name for the bound set.
Field 3: | identifies the column name of the variable belonging to this set.
Field 4: | identifies the value of the bound; this has a numerical value only in association with LO, UP, FX in Field 1, otherwise it is blank.
Field 5: | is blank and ignored.
Field 6: | is blank and ignored.
Note that if RANGES and BOUNDS sections are both present, the RANGES section must appear first.

4 References

IBM (1971) MPSX – Mathematical programming system Program Number 5734 XM4 IBM Trade Corporation, New York

5 Arguments

1:   INFILE – INTEGERInput
On entry: the unit number associated with the MPSX data file.
Constraint: 0≤INFILE≤99.
2:   MAXN – INTEGERInput
On entry: an upper limit for the number of variables in the problem.
Constraint: MAXN≥1.
3:   MAXM – INTEGERInput
On entry: an upper limit for the number of constraints (including the objective row) in the problem.
Constraint: MAXM≥1.
4:   MAXNNZ – INTEGERInput
On entry: an upper limit for the number of nonzeros (including the objective row) in the problem.
Constraint: MAXNNZ≥1.
5:   XBLDEF – REAL (KIND=nag_wp)Input
On entry: the default lower bound to be used for the variables in the problem when none is specified in the BOUNDS section of the MPSX data file. For a standard LP or QP problem XBLDEF would normally be set to zero.
6:   XBUDEF – REAL (KIND=nag_wp)Input
On entry: the default upper bound to be used for the variables in the problem when none is specified in the BOUNDS section of the MPSX data file. For a standard LP or QP problem XBUDEF would normally be set to ‘infinity’ (i.e., XBUDEF≥1020).
Constraint: XBUDEF≥XBLDEF.
7:   MPSLST – LOGICALInput
On entry: if MPSLST=.TRUE., then a listing of the input data is sent to the current advisory message unit (as defined by X04ABF). This can be useful for debugging the MPSX data file. If MPSLST=.FALSE., then no listing is produced.
8:   N – INTEGEROutput
On exit: n, the actual number of variables in the problem.
9:   M – INTEGEROutput
On exit: m, the actual number of general linear constraints in the problem (including the objective row).
10:   NNZ – INTEGEROutput
On exit: the actual number of nonzeros in the problem (including the objective row).
11:   IOBJ – INTEGEROutput
On exit: if IOBJ>0, row IOBJ of A is a free row containing the nonzero coefficients of the vector c.
If IOBJ=0, the coefficients of c are assumed to be zero.
If IOBJ=-1, no such row was found and the routine terminates with IFAIL=4 or 5 (see Section 6).
12:   NCOLH – INTEGEROutput
On exit: NCOLH=0. For QP problems, NCOLH is the number of leading nonzero columns of the Hessian matrix H and must therefore be set >0 before calling E04NKF.
13:   A MAXNNZ – REAL (KIND=nag_wp) arrayOutput
On exit: the nonzero elements of A, ordered by increasing column index.
14:   HA MAXNNZ – INTEGER arrayOutput
On exit: the row indices of the nonzero elements stored in A.
15:   KA MAXN+1 – INTEGER arrayOutput
On exit: a set of pointers to the beginning of each column of A. More precisely, KA i contains the index in A of the start of the ith column, for i=1,2,…,N. Note that KA 1=1 and KA N+1=NNZ+1.
16:   BL MAXN+MAXM – REAL (KIND=nag_wp) arrayOutput
17:   BU MAXN+MAXM – REAL (KIND=nag_wp) arrayOutput
On exit: BL contains the vector l (the lower bounds) and BU contains the vector u (the upper bounds), for all the variables and constraints in the following order. The first N elements of each array contain the bounds on the variables x and the next M elements contain the bounds for the linear objective term cT x and the general linear constraints Ax (if any). Note that an ‘infinite’ lower bound is indicated by BL j = -1.0E+20, an ‘infinite’ upper bound by BU j=-1.0E+20 and an equality constraint by BL j=BU j. (The lower bound for cT x, stored in BL N+IOBJ, is set to -XBUDEF. The corresponding upper bound, stored in BU N+IOBJ, is set to XBUDEF.)
Note that E04MZF uses an ‘infinite’ bound size of 1020 in the definition of l and u. In other words, any element of u greater than or equal to 1020 will be regarded as +∞ (and similarly any element of l less than or equal to -1020 will be regarded as -∞). If this value is deemed to be ‘inappropriate’, you are recommended to reset the value of the optional parameter Infinite Bound Size and make any necessary changes to BL and/or BU before calling E04NKF.
18:   START – CHARACTER(1)Output
On exit: START='C' and an internal Crash procedure will be used by E04NKF to choose an initial basis.
19:   NAMES 5 – CHARACTER(8) arrayInput/Output
On entry: a set of names associated with the MPSX form of the problem.
NAMES 1
Must contain either the name of the problem or be blank.
NAMES 2
Must contain either the name of the objective row or be blank (in which case the first objective free row is used).
NAMES 3
Must contain either the name of the RHS set to be used or be blank (in which case the first RHS set is used).
NAMES 4
Must contain either the name of the RANGE set to be used or be blank (in which case the first RANGE set (if any) is used).
NAMES 5
Must contain either the name of the BOUNDS set to be used or be blank (in which case the first BOUNDS set (if any) is used).
On exit: a set of names associated with the problem as defined in the MPSX data file as follows:
NAMES 1
Contains the name of the problem (or blank if none).
NAMES 2
Contains the name of the objective row (or blank if none).
NAMES 3
Contains the name of the RHS set (or blank if none).
NAMES 4
Contains the name of the RANGE set (or blank if none).
NAMES 5
Contains the name of the BOUNDS set (or blank if none).
20:   NNAME – INTEGEROutput
On exit: n+m, the total number of variables and constraints in the problem.
21:   CRNAME MAXN+MAXM – CHARACTER(8) arrayOutput
On exit: the MPSX names of all the variables and constraints in the problem in the following order. The first N elements contain the MPSX names for the variables and the next M elements contain the MPSX names for the objective row and general linear constraints (if any). Note that the MPSX name for the objective row is stored in CRNAME N+IOBJ.
22:   XS MAXN+MAXM – REAL (KIND=nag_wp) arrayOutput
On exit: a set of initial values for the variables and constraints in the problem. More precisely,
XS j=min max 0.0,BL j,BU j, for j=1,2,…,NNAME.
23:   ISTATE MAXN+MAXM – INTEGER arrayOutput
On exit: a set of initial states for the variables and constraints in the problem. More precisely, ISTATE j=1 if XS j=BU j and 0 otherwise, for j=1,2,…,NNAME.
24:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
There are too many rows present in the data file. Increase MAXM by at least M-MAXM and rerun E04MZF.
IFAIL=2
There are too many columns present in the data file. Increase MAXN by at least N-MAXN and rerun E04MZF.
IFAIL=3
There are too many nonzeros present in the data file. Increase MAXNNZ by at least NNZ-MAXNNZ and rerun E04MZF.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.
The following error exits (apart from IFAIL=17) are caused by having either a corrupt or a nonstandard MPSX data file. Refer to Section 3 for a detailed description of the MPSX format which can be read by E04MZF. If MPSLST=.TRUE., the last line of printed output refers to the line in the MPSX data file which contains the reported error.
IFAIL=4
The objective row was not found. There must be at least one row in the ROWS section with row type N for the objective row.
IFAIL=5
An unknown objective row name was detected in the ROWS section.
IFAIL=6
There are no rows specified in the ROWS section.
IFAIL=7
An illegal constraint type was detected in the ROWS section. The constraint type must be either N, L, G or E.
IFAIL=8
An illegal row name was detected in the ROWS section. Names must be made up of ‘alphanumeric’ characters (see Section 3) with no leading blanks.
IFAIL=9
An illegal column name was detected in the COLUMNS section. Names must be made up of ‘alphanumeric’ characters (see Section 3) with no leading blanks.
IFAIL=10
An illegal bound type was detected in the BOUNDS section. The bound type must be either LO, UP, FX, FR, MI or PL.
IFAIL=11
An unknown column name was detected in the BOUNDS section. All the column names must be specified in the COLUMNS section.
IFAIL=12
The last line in the data file does not contain the ENDATA line indicator.
IFAIL=13
An illegal data line was detected in the file. This line is neither a comment line nor a valid data line.
IFAIL=14
An unknown row name was detected in COLUMNS, RHS or RANGES section. All the row names must be specified in the ROWS section.
IFAIL=15
There were no columns specified in the COLUMNS section.
IFAIL=16
The name of the RHS, RANGES or BOUNDS set to be used was not found in the data file.
IFAIL=17
On entry, | INFILE<0,
or | INFILE>99,
or | MAXN<1,
or | MAXM<1,
or | MAXNNZ<1,
or | XBLDEF>XBUDEF.

7 Accuracy

Not applicable.

8 Parallelism and Performance

E04MZF is not threaded in any implementation.

9 Further Comments

None.

10 Example

This example solves the quadratic programming problem
minimize   cT x + 12 xT H x   subject to   l ≤Ax ≤u, -2 ≤A x ≤2,
where
c= -4.0 -1.0 -1.0 -1.0 -1.0 -1.0 -1.0 -0.1 -0.3 ,   H= 2 1 1 1 1 0 0 0 0 1 2 1 1 1 0 0 0 0 1 1 2 1 1 0 0 0 0 1 1 1 2 1 0 0 0 0 1 1 1 1 2 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 ,   NCOLH=5,
A= 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 4.0 1.0 2.0 3.0 4.0 -2.0 1.0 1.0 1.0 1.0 1.0 -1.0 1.0 -1.0 1.0 1.0 1.0 1.0 1.0 ,
l= -2.0 -2.0 -2.0   and   u= 1.5 1.5 4.0 .
The optimal solution (to five figures) is
x*=2.0,-0.23333,-0.26667,-0.3,-0.1,2.0,2.0,-1.7777,-0.45555 T.
Three bound constraints and two general linear constraints are active at the solution. Note that, although the Hessian matrix is positive semidefinite, the point x* is unique.
The MPSX representation of the problem is given in Section 10.2.

10.1 Program Text

Program Text (e04mzfe.f90)

10.2 Program Data

Note: the MPSX data which is read by E04MZF begins with the second record of this data file; the first record is a caption which is read by the example program.

Program Options (e04mzfe.opt)

10.3 Program Results

Program Results (e04mzfe.r)

E04 Chapter Contents
E04 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


E04NCF/E04NCA : NAG Library, Mark 26

E04 Chapter Contents
E04 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

E04NCF/E04NCA

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.
Note: this routine uses optional parameters to define choices in the problem specification and in the details of the algorithm. If you wish to use default settings for all of the optional parameters, you need only read Sections 1 to 10 of this document. If, however, you wish to reset some or all of the settings please refer to Section 11 for a detailed description of the algorithm, to Section 12 for a detailed description of the specification of the optional parameters and to Section 13 for a detailed description of the monitoring information produced by the routine.

▸▿ Contents

1 Purpose
▸▿ 2 Specification
2.1 Specification for E04NCF
2.2 Specification for E04NCA
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
▸▿ 9 Further Comments
9.1 Scaling
9.2 Description of the Printed Output
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results
▸▿ 11 Algorithmic Details
11.1 Overview
11.2 Definition of Search Direction
11.3 Main Iteration
▸▿ 12 Optional Parameters
12.1 Description of the Optional Parameters
13 Description of Monitoring Information

1 Purpose

E04NCF/E04NCA solves linearly constrained linear least squares problems and convex quadratic programming problems. It is not intended for large sparse problems.
E04NCA is a version of E04NCF that has additional arguments in order to make it safe for use in multithreaded applications (see Section 5). The initialization routine E04WBF must have been called before calling E04NCA.

2 Specification

2.1 Specification for E04NCF

SUBROUTINE E04NCF ( M, N, NCLIN, LDC, LDA, C, BL, BU, CVEC, ISTATE, KX, X, A, B, ITER, OBJ, CLAMDA, IWORK, LIWORK, WORK, LWORK, IFAIL)
INTEGER | M, N, NCLIN, LDC, LDA, ISTATE(N+NCLIN), KX(N), ITER, IWORK(LIWORK), LIWORK, LWORK, IFAIL
REAL (KIND=nag_wp) | C(LDC,*), BL(N+NCLIN), BU(N+NCLIN), CVEC(*), X(N), A(LDA,*), B(*), OBJ, CLAMDA(N+NCLIN), WORK(LWORK)

2.2 Specification for E04NCA

SUBROUTINE E04NCA ( M, N, NCLIN, LDC, LDA, C, BL, BU, CVEC, ISTATE, KX, X, A, B, ITER, OBJ, CLAMDA, IWORK, LIWORK, WORK, LWORK, LWSAV, IWSAV, RWSAV, IFAIL)
INTEGER | M, N, NCLIN, LDC, LDA, ISTATE(N+NCLIN), KX(N), ITER, IWORK(LIWORK), LIWORK, LWORK, IWSAV(610), IFAIL
REAL (KIND=nag_wp) | C(LDC,*), BL(N+NCLIN), BU(N+NCLIN), CVEC(*), X(N), A(LDA,*), B(*), OBJ, CLAMDA(N+NCLIN), WORK(LWORK), RWSAV(475)
LOGICAL | LWSAV(120)
Before calling E04NCA, or either of the option setting routines E04NDA or E04NEA, E04WBF must be called. The specification for E04WBF is:
SUBROUTINE E04WBF ( RNAME, CWSAV, LCWSAV, LWSAV, LLWSAV, IWSAV, LIWSAV, RWSAV, LRWSAV, IFAIL)
INTEGER | LCWSAV, LLWSAV, IWSAV(LIWSAV), LIWSAV, LRWSAV, IFAIL
REAL (KIND=nag_wp) | RWSAV(LRWSAV)
LOGICAL | LWSAV(LLWSAV)
CHARACTER(*) | RNAME
CHARACTER(80) | CWSAV(LCWSAV)
E04WBF should be called with RNAME='E04NCA'. LCWSAV, LLWSAV, LIWSAV and LRWSAV, the declared lengths of CWSAV, LWSAV, IWSAV and RWSAV respectively, must satisfy:
  • LCWSAV≥1
  • LLWSAV≥120
  • LIWSAV≥610
  • LRWSAV≥475
The contents of the arrays CWSAV, LWSAV, IWSAV and RWSAV must not be altered between calling routines E04NCA, E04NDA, E04NEA and E04WBF.

3 Description

E04NCF/E04NCA is designed to solve a class of quadratic programming problems of the following general form:
minimize x∈Rn F x  subject to  l≤ x Cx ≤u (1)
where C is an nL by n matrix and the objective function F x may be specified in a variety of ways depending upon the particular problem to be solved. The available forms for F x are listed in Table 1, in which the prefixes FP, LP, QP and LS stand for ‘feasible point’, ‘linear programming’, ‘quadratic programming’ and ‘least squares’ respectively, c is an n-element vector, b is an m element vector and z denotes the Euclidean length of z.
Problem type | F x | Matrix A
FP | None | Not applicable
LP | cT x | Not applicable
QP1 | cT x+12 xT Ax | n by n symmetric positive semidefinite
QP2 | cT x+12 xT Ax | n by n symmetric positive semidefinite
QP3 | cT x+12 xTAT Ax | m by n upper trapezoidal
QP4 | cT x+12 xTAT Ax | m by n upper trapezoidal
LS1 | cT x+12 b-Ax 2 | m by n
LS2 | cT x+12 b-Ax 2 | m by n
LS3 | cT x+12 b-Ax 2 | m by n upper trapezoidal
LS4 | cT x+12 b-Ax 2 | m by n upper trapezoidal
Table 1
In the standard LS problem F x will usually have the form LS1, and in the standard convex QP problem F x will usually have the form QP2. The default problem type is LS1 and other objective functions are selected by using the optional parameter Problem Type.
When A is upper trapezoidal it will usually be the case that m=n, so that A is upper triangular, but full generality has been allowed for in the specification of the problem. The upper trapezoidal form is intended for cases where a previous factorization, such as a QR factorization, has been performed.
The constraints involving C are called the general constraints. Note that upper and lower bounds are specified for all the variables and for all the general constraints. An equality constraint can be specified by setting li=ui. If certain bounds are not present, the associated elements of l or u can be set to special values that will be treated as -∞ or +∞. (See the description of the optional parameter Infinite Bound Size.)
The defining feature of a quadratic function F x is that the second-derivative matrix H (the Hessian matrix) is constant. For the LP case H=0; for QP1 and QP2, H=A; for QP3 and QP4, H=AT A and for LS1 (the default), LS2, LS3 and LS4, H=AT A.
Problems of type QP3 and QP4 for which A is not in upper trapezoidal form should be solved as types LS1 and LS2 respectively, with b=0.
For problems of type LS, we refer to A as the least squares matrix, or the matrix of observations and to b as the vector of observations.
You must supply an initial estimate of the solution.
If H is nonsingular then E04NCF/E04NCA will obtain the unique (global) minimum. If H is singular then the solution may still be a global minimum if all active constraints have nonzero Lagrange multipliers. Otherwise the solution obtained will be either a weak minimum (i.e., with a unique optimal objective value, but an infinite set of optimal x), or else the objective function is unbounded below in the feasible region. The last case can only occur when F x contains an explicit linear term (as in problems LP, QP2, QP4, LS2 and LS4).
The method used by E04NCF/E04NCA is described in detail in Section 11.

4 References

Gill P E, Hammarling S, Murray W, Saunders M A and Wright M H (1986) Users' guide for LSSOL (Version 1.0) Report SOL 86-1 Department of Operations Research, Stanford University
Gill P E, Murray W, Saunders M A and Wright M H (1984) Procedures for optimization problems with a mixture of bounds and general linear constraints ACM Trans. Math. Software 10 282–298
Gill P E, Murray W and Wright M H (1981) Practical Optimization Academic Press
Stoer J (1971) On the numerical solution of constrained least squares problems SIAM J. Numer. Anal. 8 382–411

5 Arguments

1:   M – INTEGERInput
On entry: m, the number of rows in the matrix A. If the problem is specified as type FP or LP, M is not referenced and is assumed to be zero.
If the problem is of type QP, M will usually be n, the number of variables. However, a value of M less than n is appropriate for QP3 or QP4 if A is an upper trapezoidal matrix with m rows. Similarly, M may be used to define the dimension of a leading block of nonzeros in the Hessian matrices of QP1 or QP2, in which case the last n-m rows and columns of A are assumed to be zero. In the QP case, m should not be greater than n; if it is, the last m-n rows of A are ignored.
If the problem is of type LS1 (the default) or specified as type LS2, LS3 or LS4, M is also the dimension of the array B. Note that all possibilities (m<n, m=n and m>n) are allowed in this case.
Constraint: M>0 if the problem is not of type FP or LP.
2:   N – INTEGERInput
On entry: n, the number of variables.
Constraint: N>0.
3:   NCLIN – INTEGERInput
On entry: nL, the number of general linear constraints.
Constraint: NCLIN≥0.
4:   LDC – INTEGERInput
On entry: the first dimension of the array C as declared in the (sub)program from which E04NCF/E04NCA is called.
Constraint: LDC≥max 1,NCLIN.
5:   LDA – INTEGERInput
On entry: the first dimension of the array A as declared in the (sub)program from which E04NCF/E04NCA is called.
Constraint: LDA≥max 1,M.
6:   C LDC* – REAL (KIND=nag_wp) arrayInput
Note: the second dimension of the array C must be at least N if NCLIN>0, and at least 1 otherwise.
On entry: the ith row of C must contain the coefficients of the ith general constraint, for i=1,2,…,NCLIN.
If NCLIN=0, C is not referenced.
7:   BL N+NCLIN – REAL (KIND=nag_wp) arrayInput
8:   BU N+NCLIN – REAL (KIND=nag_wp) arrayInput
On entry: BL must contain the lower bounds and BU the upper bounds, for all the constraints, in the following order. The first n elements of each array must contain the bounds on the variables, and the next nL elements must contain the bounds for the general linear constraints (if any). To specify a nonexistent lower bound (i.e., lj=-∞), set BL j≤-bigbnd, and to specify a nonexistent upper bound (i.e., uj=+∞), set BU j≥bigbnd; the default value of bigbnd is 1020, but this may be changed by the optional parameter Infinite Bound Size. To specify the jth constraint as an equality, set BU j=BL j=β, say, where β<bigbnd.
Constraints:
  • BL j≤BU j, for j=1,2,…,N+NCLIN;
  • if BL j=BU j=β, β<bigbnd.
9:   CVEC* – REAL (KIND=nag_wp) arrayInput
Note: the dimension of the array CVEC must be at least N if the problem is of type LP, QP2, QP4, LS2 or LS4, and at least 1 otherwise.
On entry: the coefficients of the explicit linear term of the objective function.
If the problem is of type FP, QP1, QP3, LS1 (the default) or LS3, CVEC is not referenced.
10:   ISTATE N+NCLIN – INTEGER arrayInput/Output
On entry: need not be set if the (default) optional parameter Cold Start is used.
If the optional parameter Warm Start has been chosen, ISTATE specifies the desired status of the constraints at the start of the feasibility phase. More precisely, the first n elements of ISTATE refer to the upper and lower bounds on the variables, and the next nL elements refer to the general linear constraints (if any). Possible values for ISTATE j are as follows:
ISTATE j | Meaning
0 | The constraint should not be in the initial working set.
1 | The constraint should be in the initial working set at its lower bound.
2 | The constraint should be in the initial working set at its upper bound.
3 | The constraint should be in the initial working set as an equality. This value must not be specified unless BL j=BU j.
The values -2, -1 and 4 are also acceptable but will be reset to zero by the routine. If E04NCF/E04NCA has been called previously with the same values of N and NCLIN, ISTATE already contains satisfactory information. (See also the description of the optional parameter Warm Start.) The routine also adjusts (if necessary) the values supplied in X to be consistent with ISTATE.
Constraint: -2≤ISTATE j≤4, for j=1,2,…,N+NCLIN.
On exit: the status of the constraints in the working set at the point returned in X. The significance of each possible value of ISTATE j is as follows:
ISTATE j | Meaning
-2 | The constraint violates its lower bound by more than the feasibility tolerance.
-1 | The constraint violates its upper bound by more than the feasibility tolerance.
-0 | The constraint is satisfied to within the feasibility tolerance, but is not in the working set.
-1 | This inequality constraint is included in the working set at its lower bound.
-2 | This inequality constraint is included in the working set at its upper bound.
-3 | The constraint is included in the working set as an equality. This value of ISTATE can occur only when BL j=BU j.
-4 | This corresponds to optimality being declared with X j being temporarily fixed at its current value.
11:   KX N – INTEGER arrayInput/Output
On entry: need not be initialized for problems of type FP, LP, QP1, QP2, LS1 (the default) or LS2.
For problems QP3, QP4, LS3 or LS4, KX must specify the order of the columns of the matrix A with respect to the ordering of X. Thus if column j of A is the column associated with the variable xi then KX j=i.
Constraints:
  • 1≤KX i≤N, for i=1,2,…,N;
  • if i≠j, KX i≠KX j.
On exit: defines the order of the columns of A with respect to the ordering of X, as described above.
12:   X N – REAL (KIND=nag_wp) arrayInput/Output
On entry: an initial estimate of the solution.
Note: that it may be best to avoid the choice X=0.0.
On exit: the point at which E04NCF/E04NCA terminated. If IFAIL=0, 1 or 4, X contains an estimate of the solution.
13:   A LDA* – REAL (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array A must be at least N if the problem is of type QP1, QP2, QP3, QP4, LS1 (the default), LS2, LS3 or LS4, and at least 1 otherwise.
On entry: the array A must contain the matrix A as specified in Table 1 (see Section 3).
If the problem is of type QP1 or QP2, the first m rows and columns of A must contain the leading m by m rows and columns of the symmetric Hessian matrix. Only the diagonal and upper triangular elements of the leading m rows and columns of A are referenced. The remaining elements are assumed to be zero and need not be assigned.
For problems QP3, QP4, LS3 or LS4, the first m rows of A must contain an m by n upper trapezoidal factor of either the Hessian matrix or the least squares matrix, ordered according to the KX array. The factor need not be of full rank, i.e., some of the diagonals may be zero. However, as a general rule, the larger the dimension of the leading nonsingular sub-matrix of A, the fewer iterations will be required. Elements outside the upper triangular part of the first m rows of A are assumed to be zero and need not be assigned.
If a constrained least squares problem contains a very large number of observations, storage limitations may prevent storage of the entire least squares matrix. In such cases, you should transform the original A into a triangular matrix before the call to E04NCF/E04NCA and solve the problem as type LS3 or LS4.
On exit: if Hessian=NO and the problem is of type LS or QP, A contains the upper triangular Cholesky factor R of (8) (see Section 11.3), with columns ordered as indicated by KX.
If Hessian=YES and the problem is of type LS or QP, A contains the upper triangular Cholesky factor R of the Hessian matrix H, with columns ordered as indicated by KX. In either case R may be used to obtain the variance-covariance matrix or to recover the upper triangular factor of the original least squares matrix.
If the problem is of type FP or LP, A is not referenced.
14:   B* – REAL (KIND=nag_wp) arrayInput/Output
Note: the dimension of the array B must be at least M if the problem is of type LS1 (the default), LS2, LS3 or LS4, and at least 1 otherwise.
On entry: the m elements of the vector of observations.
On exit: the transformed residual vector of equation (10) (see Section 11.3).
If the problem is of type FP, LP, QP1, QP2, QP3 or QP4, B is not referenced.
15:   ITER – INTEGEROutput
On exit: the total number of iterations performed.
16:   OBJ – REAL (KIND=nag_wp)Output
On exit: the value of the objective function at x if x is feasible, or the sum of infeasibiliites at x otherwise. If the problem is of type FP and x is feasible, OBJ is set to zero.
17:   CLAMDA N+NCLIN – REAL (KIND=nag_wp) arrayOutput
On exit: the values of the Lagrange multipliers for each constraint with respect to the current working set. The first n elements contain the multipliers for the bound constraints on the variables, and the next nL elements contain the multipliers for the general linear constraints (if any). If ISTATE j=0 (i.e., constraint j is not in the working set), CLAMDA j is zero. If x is optimal, CLAMDA j should be non-negative if ISTATE j=1, non-positive if ISTATE j=2 and zero if ISTATE j=4.
18:   IWORK LIWORK – INTEGER arrayWorkspace
19:   LIWORK – INTEGERInput
On entry: the dimension of the array IWORK as declared in the (sub)program from which E04NCF/E04NCA is called.
Constraint: LIWORK≥N.
20:   WORK LWORK – REAL (KIND=nag_wp) arrayWorkspace
21:   LWORK – INTEGERInput
On entry: the dimension of the array WORK as declared in the (sub)program from which E04NCF/E04NCA is called.
Constraints:
  • if the problem is of type FP,
    • if NCLIN=0, LWORK≥6×N;
    • if NCLIN≥N, LWORK≥2×N 2+6×N+6×NCLIN;
    • otherwise LWORK≥2×NCLIN+1 2+6×N+6×NCLIN;
  • if the problem is of type LP,
    • if NCLIN=0, LWORK≥7×N;
    • if NCLIN≥N, LWORK≥2×N 2+7×N+6×NCLIN;
    • otherwise LWORK≥2×NCLIN+1 2+7×N+6×NCLIN;
  • if problems QP1, QP3, LS1 (the default) and LS3,
    • if NCLIN>0, LWORK≥2×N 2+9×N+6×NCLIN;
    • if NCLIN=0, LWORK≥9×N;
  • if problems QP2, QP4, LS2 and LS4,
    • if NCLIN>0, LWORK≥2×N 2+10×N+6×NCLIN;
    • if NCLIN=0, LWORK≥10×N.
The amounts of workspace provided and required are (by default) output on the current advisory message unit (as defined by X04ABF). As an alternative to computing LIWORK and LWORK from the formulas given above, you may prefer to obtain appropriate values from the output of a preliminary run with LIWORK and LWORK set to 1. (E04NCF/E04NCA will then terminate with IFAIL=6.)
22:   IFAIL – INTEGERInput/Output
Note: for E04NCA, IFAIL does not occur in this position in the argument list. See the additional arguments described below.
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, because for this routine the values of the output arguments may be useful even if IFAIL≠0 on exit, the recommended value is -1. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).
E04NCF/E04NCA returns with IFAIL=0 if x is a strong local minimizer, i.e., the projected gradient (Norm Gz; see Section 9.2) is negligible, the Lagrange multipliers (Lagr Mult; see Section 11.2) are optimal and RZ (see Section 11.3) is nonsingular.
Note: the following are additional arguments for specific use with E04NCA. Users of E04NCF therefore need not read the remainder of this description.
22:   LWSAV 120 – LOGICAL arrayCommunication Array
23:   IWSAV 610 – INTEGER arrayCommunication Array
24:   RWSAV 475 – REAL (KIND=nag_wp) arrayCommunication Array
The arrays LWSAV, IWSAV and RWSAV must not be altered between calls to any of the routines E04NCA, E04NDA or E04NEA.
25:   IFAIL – INTEGERInput/Output
Note: see the argument description for IFAIL above.

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Note: E04NCF/E04NCA may return useful information for one or more of the following detected errors or warnings.
Errors or warnings detected by the routine:
IFAIL=1
X is a weak local minimum, (i.e., the projected gradient is negligible, the Lagrange multipliers are optimal, but either RZ (see Section 11.3) is singular, or there is a small multiplier). This means that x is not unique.
IFAIL=2
The solution appears to be unbounded. This value of IFAIL implies that a step as large as Infinite Bound Size (default value=1020) would have to be taken in order to continue the algorithm. This situation can occur only when A is singular, there is an explicit linear term, and at least one variable has no upper or lower bound.
IFAIL=3
No feasible point was found, i.e., it was not possible to satisfy all the constraints to within the feasibility tolerance. In this case, the constraint violations at the final x will reveal a value of the tolerance for which a feasible point will exist – for example, when the feasibility tolerance for each violated constraint exceeds its Slack (see Section 9.2) at the final point. The modified problem (with an altered feasibility tolerance) may then be solved using a Warm Start. You should check that there are no constraint redundancies. If the data for the constraints are accurate only to the absolute precision σ, you should ensure that the value of the optional parameter Feasibility Tolerance (default value=ε, where ε is the machine precision) is greater than σ. For example, if all elements of C are of order unity and are accurate only to three decimal places, the Feasibility Tolerance should be at least 10-3.
IFAIL=4
The limiting number of iterations (determined by the optional parameters Feasibility Phase Iteration Limit (default value=max 50,5 n+nL) and Optimality Phase Iteration Limit (default value=max 50,5 n+nL)) was reached before normal termination occurred. If the method appears to be making progress (e.g., the objective function is being satisfactorily reduced), either increase the iterations limit and rerun E04NCF/E04NCA or, alternatively, rerun E04NCF/E04NCA using the Warm Start facility to specify the initial working set. If the iteration limit is already large, but some of the constraints could be nearly linearly dependent, check the monitoring information (see Section 13) for a repeated pattern of constraints entering and leaving the working set. (Near-dependencies are often indicated by wide variations in size in the diagonal elements of the matrix T (see Section 11.2), which will be printed if Print Level≥30 (default value=10). In this case, the algorithm could be cycling (see the comments for IFAIL=5).
IFAIL=5
The algorithm could be cycling, since a total of 50 changes were made to the working set without altering x. You should check the monitoring information (see Section 13) for a repeated pattern of constraint deletions and additions.
If a sequence of constraint changes is being repeated, the iterates are probably cycling. (E04NCF/E04NCA does not contain a method that is guaranteed to avoid cycling; such a method would be combinatorial in nature.) Cycling may occur in two circumstances: at a constrained stationary point where there are some small or zero Lagrange multipliers; or at a point (usually a vertex) where the constraints that are satisfied exactly are nearly linearly dependent. In the latter case, you have the option of identifying the offending dependent constraints and removing them from the problem, or restarting the run with a larger value of the optional parameter Feasibility Tolerance (default value=ε, where ε is the machine precision). If E04NCF/E04NCA terminates with IFAIL=5, but no suspicious pattern of constraint changes can be observed, it may be worthwhile to restart with the final x (with or without the Warm Start option).
Note: that this error exit may also occur if a poor starting point X is supplied (for example, X=0.0). You are advised to try a nonzero starting point.
IFAIL=6
An input argument is invalid.
IFAIL=7
The problem to be solved is of type QP1 or QP2, but the Hessian matrix supplied in A is not positive semidefinite.
Overflow
If the printed output before the overflow error contains a warning about serious ill-conditioning in the working set when adding the jth constraint, it may be possible to avoid the difficulty by increasing the magnitude of the Feasibility Tolerance (default value=ε, where ε is the machine precision) and rerunning the program. If the message recurs even after this change, the offending linearly dependent constraint (with index ‘j’) must be removed from the problem.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

E04NCF/E04NCA implements a numerically stable active set strategy and returns solutions that are as accurate as the condition of the problem warrants on the machine.

8 Parallelism and Performance

E04NCF/E04NCA is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
E04NCF/E04NCA makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

This section contains some comments on scaling and a description of the printed output.

9.1 Scaling

Sensible scaling of the problem is likely to reduce the number of iterations required and make the problem less sensitive to perturbations in the data, thus improving the condition of the problem. In the absence of better information it is usually sensible to make the Euclidean lengths of each constraint of comparable magnitude. See the E04 Chapter Introduction and Gill et al. (1981) for further information and advice.

9.2 Description of the Printed Output

This section describes the intermediate printout and final printout produced by E04NCF/E04NCA. The intermediate printout is a subset of the monitoring information produced by the routine at every iteration (see Section 13). You can control the level of printed output (see the description of the optional parameter Print Level). Note that the intermediate printout and final printout are produced only if Print Level≥10 (the default for E04NCF, by default no output is produced by E04NCA).
The following line of summary output (<80 characters) is produced at every iteration. In all cases, the values of the quantities printed are those in effect on completion of the given iteration.
Itn | is the iteration count.
Step | is the step taken along the computed search direction. If a constraint is added during the current iteration (i.e., Jadd is positive), Step will be the step to the nearest constraint. During the optimality phase, the step can be greater than one only if the factor RZ is singular. (See Section 11.3.)
Ninf | is the number of violated constraints (infeasibilities). This will be zero during the optimality phase.
Sinf/Objective | is the value of the current objective function. If x is not feasible, Sinf gives a weighted sum of the magnitudes of constraint violations. If x is feasible, Objective is the value of the objective function of (1). The output line for the final iteration of the feasibility phase (i.e., the first iteration for which Ninf is zero) will give the value of the true objective at the first feasible point. During the optimality phase the value of the objective function will be nonincreasing. During the feasibility phase the number of constraint infeasibilities will not increase until either a feasible point is found or the optimality of the multipliers implies that no feasible point exists. Once optimal multipliers are obtained the number of infeasibilities can increase, but the sum of infeasibilities will either remain constant or be reduced until the minimum sum of infeasibilities is found.
Norm Gz | is Z 1 T gFR , the Euclidean norm of the reduced gradient with respect to Z 1. During the optimality phase, this norm will be approximately zero after a unit step. (See Sections 11.2 and 11.3.)
The final printout includes a listing of the status of every variable and constraint.
The following describes the printout for each variable. A full stop (.) is printed for any numerical value that is zero.
Varbl | gives the name (V) and index j, for j=1,2,…,n, of the variable.
State gives the state of the variable (FR if neither bound is in the working set, EQ if a fixed variable, LL if on its lower bound, UL if on its upper bound, TF if temporarily fixed at its current value). If Value lies outside the upper or lower bounds by more than the Feasibility Tolerance, State will be ++ or -- respectively.
A key is sometimes printed before State.
A | Alternative optimum possible. The variable is active at one of its bounds, but its Lagrange multiplier is essentially zero. This means that if the variable were allowed to start moving away from its bound then there would be no change to the objective function. The values of the other free variables might change, giving a genuine alternative solution. However, if there are any degenerate variables (labelled D), the actual change might prove to be zero, since one of them could encounter a bound immediately. In either case the values of the Lagrange multipliers might also change.
D | Degenerate. The variable is free, but it is equal to (or very close to) one of its bounds.
I | Infeasible. The variable is currently violating one of its bounds by more than the Feasibility Tolerance.
Value | is the value of the variable at the final iteration.
Lower Bound | is the lower bound specified for the variable. None indicates that BL j≤-bigbnd.
Upper Bound | is the upper bound specified for the variable. None indicates that BU j≥bigbnd.
Lagr Mult | is the Lagrange multiplier for the associated bound. This will be zero if State is FR unless BL j≤-bigbnd and BU j≥bigbnd, in which case the entry will be blank. If x is optimal, the multiplier should be non-negative if State is LL and non-positive if State is UL.
Slack | is the difference between the variable Value and the nearer of its (finite) bounds BL j and BU j. A blank entry indicates that the associated variable is not bounded (i.e., BL j≤-bigbnd and BU j≥bigbnd).
The meaning of the printout for general constraints is the same as that given above for variables, with ‘variable’ replaced by ‘constraint’, BL j and BU j are replaced by BL n+j and BU n+j respectively, and with the following change in the heading:
L Con gives the name (L) and index j, for j=1,2,…,nL, of the linear constraint.
Note that movement off a constraint (as opposed to a variable moving away from its bound) can be interpreted as allowing the entry in the Slack column to become positive.
Numerical values are output with a fixed number of digits; they are not guaranteed to be accurate to this precision.

10 Example

This example minimizes the function 12 b-Ax 2, where
A= 1 1 1 1 1 1 1 1 1 1 2 1 1 1 1 2 0 0 1 1 3 1 1 1 -1 -1 -3 1 1 1 4 1 1 1 1 1 1 1 1 3 1 1 1 1 1 1 1 2 1 1 0 0 0 -1 1 1 1 1 0 1 1 1 1 1 1 1 0 1 1 1 1 1 1 1 0 1 1 1 2 2 3 1 0 1 1 1 1 0 2 2   and   b= 1 1 1 1 1 1 1 1 1 1
subject to the bounds
0≤x 1≤2 0≤x 2≤2 -∞≤x 3≤2 0≤x 4≤2 0≤x 5≤2 0≤x 6≤2 0≤x 7≤2 0≤x 8≤2 0≤x 9≤2
and to the general constraints
2.0 ≤ x 1 + x 2 + x 3 + x 4 + x 5 + x 6 + x 7 + x 8 + 4 x 9 ≤ ∞ -∞ ≤ x 1 + 2 x 2 + 3 x 3 + 4 x 4 - 2 x 5 + x 6 + x 7 + x 8 + x 9 ≤ 2.0 1.0 ≤ x 1 - x 2 + x 3 - x 4 + x 5 + x 6 + x 7 + x 8 + x 9 ≤ 4.0
The initial point, which is infeasible, is
x 0=1.0,0.5,0.3333,0.25,0.2,0.1667,0.1428,0.125,0.1111 T,
and F x 0=9.4746 (to five figures).
The optimal solution (to five figures) is
x*=0.0,0.041526,0.58718,0.0,0.099643,0.0,0.04906,0.0,0.30565 T,
and F x*=0.081341. Four bound constraints and all three general constraints are active at the solution.
The document for E04NDF/E04NDA includes an example program to solve a convex quadratic programming problem, using some of the optional parameters described in Section 12.

10.1 Program Text

Note: the following programs illustrate the use of E04NCF and E04NCA.

Program Text (e04ncfe.f90)

Program Text (e04ncae.f90)

10.2 Program Data

Program Data (e04ncfe.d)

Program Data (e04ncae.d)

10.3 Program Results

Program Results (e04ncfe.r)

Program Results (e04ncae.r)

Note: the remainder of this document is intended for more advanced users. Section 11 contains a detailed description of the algorithm which may be needed in order to understand Sections 12 and 13. Section 12 describes the optional parameters which may be set by calls to E04NDF/E04NDA and/or E04NEF/E04NEA. Section 13 describes the quantities which can be requested to monitor the course of the computation.

11 Algorithmic Details

This section contains a detailed description of the method used by E04NCF/E04NCA.

11.1 Overview

E04NCF/E04NCA is essentially identical to the subroutine LSSOL described in Gill et al. (1986). It is based on a two-phase (primal) quadratic programming method with features to exploit the convexity of the objective function due to Gill et al. (1984). (In the full-rank case, the method is related to that of Stoer (1971).) E04NCF/E04NCA has two phases: finding an initial feasible point by minimizing the sum of infeasibilities (the feasibility phase), and minimizing the quadratic objective function within the feasible region (the optimality phase). The two-phase nature of the algorithm is reflected by changing the function being minimized from the sum of infeasibilities to the quadratic objective function. The feasibility phase does not perform the standard simplex method (i.e., it does not necessarily find a vertex), except in the LP case when nL≤n. Once any iterate is feasible, all subsequent iterates remain feasible.
E04NCF/E04NCA has been designed to be efficient when used to solve a sequence of related problems – for example, within a sequential quadratic programming method for nonlinearly constrained optimization (e.g., E04UFF/E04UFA or E04WDF). In particular, you may specify an initial working set (the indices of the constraints believed to be satisfied exactly at the solution); see the discussion of the optional parameter Warm Start.
In general, an iterative process is required to solve a quadratic program. (For simplicity, we shall always consider a typical iteration and avoid reference to the index of the iteration.) Each new iterate x- is defined by
x-=x+αp, (2)
where the step length α is a non-negative scalar, and p is called the search direction.
At each point x, a working set of constraints is defined to be a linearly independent subset of the constraints that are satisfied ‘exactly’ (to within the tolerance defined by the optional parameter Feasibility Tolerance). The working set is the current prediction of the constraints that hold with equality at a solution of (1). The search direction is constructed so that the constraints in the working set remain unaltered for any value of the step length. For a bound constraint in the working set, this property is achieved by setting the corresponding element of the search direction to zero. Thus, the associated variable is fixed, and specification of the working set induces a partition of x into fixed and free variables. During a given iteration, the fixed variables are effectively removed from the problem; since the relevant elements of the search direction are zero, the columns of C corresponding to fixed variables may be ignored.
Let nW denote the number of general constraints in the working set and let nFX denote the number of variables fixed at one of their bounds (nW and nFX are the quantities Lin and Bnd in the monitoring file output from E04NCF/E04NCA; see Section 13). Similarly, let nFR nFR=n-nFX denote the number of free variables. At every iteration, the variables are reordered so that the last nFX variables are fixed, with all other relevant vectors and matrices ordered accordingly. The order of the variables is indicated by the contents of the array KX on exit (see Section 5).

11.2 Definition of Search Direction

Let CFR denote the nW by nFR sub-matrix of general constraints in the working set corresponding to the free variables, and let pFR denote the search direction with respect to the free variables only. The general constraints in the working set will be unaltered by any move along p if
CFRpFR=0. (3)
In order to compute pFR, the TQ factorization of CFR is used:
CFRQFR=0 T (4)
where T is a nonsingular nW by nW reverse-triangular matrix (i.e., t ij=0 if i+j<nW), and the nonsingular nFR by nFR matrix QFR is the product of orthogonal transformations (see Gill et al. (1984)). If the columns of QFR are partitioned so that
QFR=Z Y, (5)
where Y is nFR by nW, then the nZ nZ=nFR-nW columns of Z form a basis for the null space of CFR. Let nR be an integer such that 0≤nR≤nZ, and let Z 1 denote a matrix whose nR columns are a subset of the columns of Z. (The integer nR is the quantity Zr in the monitoring file output from E04NCF/E04NCA. In many cases, Z 1 will include all the columns of Z.) The direction pFR will satisfy (3) if
pFR=Z 1pZ (6)
where pZ is any nR-vector.

11.3 Main Iteration

Let Q denote the n by n matrix
Q= QFR IFX , (7)
where IFX is the identity matrix of order nFX. Let R denote an n by n upper triangular matrix (the Cholesky factor) such that
RT R=HQ≡QT H~Q, (8)
where H~ is the Hessian H with rows and columns permuted so that the free variables are first.
Let the matrix of the first nZ rows and columns of R be denoted by RZ. The definition of pZ in (6) depends on whether or not the matrix RZ is singular at x. In the nonsingular case, pZ satisfies the equations
RZT RZ pZ = - gZ (9)
where gZ denotes the vector ZT gFR and g denotes the objective gradient. (The norm of gFR is the printed quantity Norm Gf; see Section 13.) When pZ is defined by (9), x+p is the minimizer of the objective function subject to the constraints (bounds and general) in the working set treated as equalities. In general, a vector fZ is available such that RZT fZ = - gZ , which allows pZ to be computed from a single back-substitution RZpZ=fZ. For example, when solving problem LS1, fZ comprises the first nZ elements of the transformed residual vector
f=P b-Ax, (10)
which is recurred from one iteration to the next, where P is an orthogonal matrix.
In the singular case, pZ is defined such that
RZ pZ = 0   and   gZT pZ < 0 . (11)
This vector has the property that the objective function is linear along p and may be reduced by any step of the form x+αp, where α>0.
The vector ZT gFR is known as the projected gradient at x. If the projected gradient is zero, x is a constrained stationary point in the subspace defined by Z. During the feasibility phase, the projected gradient will usually be zero only at a vertex (although it may be zero at non-vertices in the presence of constraint dependencies). During the optimality phase, a zero projected gradient implies that x minimizes the quadratic objective when the constraints in the working set are treated as equalities. At a constrained stationary point, Lagrange multipliers λC and λB for the general and bound constraints are defined from the equations
CFRT λC=gFR and ​λB=gFX-CFXT λC. (12)
Given a positive constant δ of the order of the machine precision, the Lagrange multiplier λj corresponding to an inequality constraint in the working set is said to be optimal if λj≤δ when the associated constraint is at its upper bound, or if λj≥-δ when the associated constraint is at its lower bound. If a multiplier is nonoptimal, the objective function (either the true objective or the sum of infeasibilities) can be reduced by deleting the corresponding constraint (with index Jdel; see Section 13) from the working set.
If optimal multipliers occur during the feasibility phase and the sum of infeasibilities is nonzero, there is no feasible point, and E04NCF/E04NCA will continue until the minimum value of the sum of infeasibilities has been found. At this point, the Lagrange multiplier λj corresponding to an inequality constraint in the working set will be such that -1+δ≤λj≤δ when the associated constraint is at its upper bound, and -δ≤λj≤1+δ when the associated constraint is at its lower bound. Lagrange multipliers for equality constraints will satisfy λj≤1+δ.
The choice of step length is based on remaining feasible with respect to the satisfied constraints. If RZ is nonsingular and x+p is feasible, α will be taken as unity. In this case, the projected gradient at x- will be zero, and Lagrange multipliers are computed. Otherwise, α is set to αM, the step to the ‘nearest’ constraint (with index Jadd; see Section 13), which is added to the working set at the next iteration.
If A is not input as a triangular matrix, it is overwritten by a triangular matrix R satisfying (8) obtained using the Cholesky factorization in the QP case, or the QR factorization in the LS case. Column interchanges are used in both cases, and an estimate is made of the rank of the triangular factor. Thereafter, the dependent rows of R are eliminated from the problem.
Each change in the working set leads to a simple change to CFR: if the status of a general constraint changes, a row of CFR is altered; if a bound constraint enters or leaves the working set, a column of CFR changes. Explicit representations are recurred of the matrices T,QFR and R; and of vectors QT g, QT c and f, which are related by the formulae
f=Pb- R 0 QT x ,   b≡0 for the ​ QP ​ case ,
and
QT g=QT c-RT f.
Note that the triangular factor R associated with the Hessian of the original problem is updated during both the optimality and the feasibility phases.
The treatment of the singular case depends critically on the following feature of the matrix updating schemes used in E04NCF/E04NCA: if a given factor RZ is nonsingular, it can become singular during subsequent iterations only when a constraint leaves the working set, in which case only its last diagonal element can become zero. This property implies that a vector satisfying (11) may be found using the single back-substitution R-ZpZ=eZ, where R-Z is the matrix RZ with a unit last diagonal, and eZ is a vector of all zeros except in the last position. If H is singular, the matrix R (and hence RZ) may be singular at the start of the optimality phase. However, RZ will be nonsingular if enough constraints are included in the initial working set. (The matrix with no rows and columns is positive definite by definition, corresponding to the case when CFR contains nFR constraints.) The idea is to include as many general constraints as necessary to ensure a nonsingular RZ.
At the beginning of each phase, an upper triangular matrix R 1 is determined that is the largest nonsingular leading sub-matrix of RZ. The use of interchanges during the factorization of A tends to maximize the dimension of R 1. (The rank of R 1 is estimated using the optional parameter Rank Tolerance.) Let Z 1 denote the columns of Z corresponding to R 1, and let Z be partitioned as Z=Z 1 Z 2. A working set for which Z 1 defines the null space can be obtained by including the rows of Z 2 T as ‘artificial constraints’. Minimization of the objective function then proceeds within the subspace defined by Z 1.
The artificially augmented working set is given by
C-FR= CFR Z 2 T , (13)
so that pFR will satisfy CFRpFR=0 and Z 2 T pFR = 0 . By definition of the TQ factorization, C-FR automatically satisfies the following:
C-FRQFR= CFR Z 2 T QFR= CFR Z 2 T Z 1 Z 2 Y = 0 T- ,
where
T-= 0 T I 0 ,
and hence the TQ factorization of (13) requires no additional work.
The matrix Z 2 need not be kept fixed, since its role is purely to define an appropriate null space; the TQ factorization can therefore be updated in the normal fashion as the iterations proceed. No work is required to ‘delete’ the artificial constraints associated with Z 2 when Z 1 T gFR = 0 , since this simply involves repartitioning QFR. When deciding which constraint to delete, the ‘artificial’ multiplier vector associated with the rows of Z 2 T is equal to Z 2 T gFR , and the multipliers corresponding to the rows of the ‘true’ working set are the multipliers that would be obtained if the temporary constraints were not present.
The number of columns in Z 2 and Z 1 , the Euclidean norm of Z 1 T gFR , and the condition estimator of R 1 appear in the monitoring file output as Art, Zr, Norm Gz and Cond Rz respectively (see Section 13).
Although the algorithm of E04NCF/E04NCA does not perform simplex steps in general, there is one exception: a linear program with fewer general constraints than variables (i.e., nL≤n). Use of the simplex method in this situation leads to savings in storage. At the starting point, the ‘natural’ working set (the set of constraints exactly or nearly satisfied at the starting point) is augmented with a suitable number of ‘temporary’ bounds, each of which has the effect of temporarily fixing a variable at its current value. In subsequent iterations, a temporary bound is treated as a standard constraint until it is deleted from the working set, in which case it is never added again.
One of the most important features of E04NCF/E04NCA is its control of the conditioning of the working set, whose nearness to linear dependence is estimated by the ratio of the largest to smallest diagonals of the TQ factor T (the printed value Cond T; see Section 13). In constructing the initial working set, constraints are excluded that would result in a large value of Cond T. Thereafter, E04NCF/E04NCA allows constraints to be violated by as much as a user-specified optional parameter Feasibility Tolerance in order to provide, whenever possible, a choice of constraints to be added to the working set at a given iteration. Let αM denote the maximum step at which x+αM p does not violate any constraint by more than its feasibility tolerance. All constraints at distance α α≤αM along p from the current point are then viewed as acceptable candidates for inclusion in the working set. The constraint whose normal makes the largest angle with the search direction is added to the working set. In order to ensure that the new iterate satisfies the constraints in the working set as accurately as possible, the step taken is the exact distance to the newly added constraint. As a consequence, negative steps are occasionally permitted, since the current iterate may violate the constraint to be added by as much as the feasibility tolerance.

12 Optional Parameters

Several optional parameters in E04NCF/E04NCA define choices in the problem specification or the algorithm logic. In order to reduce the number of formal arguments of E04NCF/E04NCA these optional parameters have associated default values that are appropriate for most problems. Therefore, you need only specify those optional parameters whose values are to be different from their default values.
The remainder of this section can be skipped if you wish to use the default values for all optional parameters.
The following is a list of the optional parameters available. A full description of each optional parameter is provided in Section 12.1.
  • Cold Start
  • Crash Tolerance
  • Defaults
  • Feasibility Phase Iteration Limit
  • Feasibility Tolerance
  • Hessian
  • Infinite Bound Size
  • Infinite Step Size
  • Iteration Limit
  • Iters
  • Itns
  • List
  • Monitoring File
  • Nolist
  • Optimality Phase Iteration Limit
  • Print Level
  • Problem Type
  • Rank Tolerance
  • Warm Start
Optional parameters may be specified by calling one, or both, of the routines E04NDF/E04NDA and E04NEF/E04NEA before a call to E04NCF/E04NCA.
E04NDF/E04NDA reads options from an external options file, with Begin and End as the first and last lines respectively and each intermediate line defining a single optional parameter. For example,
Begin
  Print level = 1
End
The call
 CALL E04NDF (IOPTNS, INFORM)
can then be used to read the file on unit IOPTNS. INFORM will be zero on successful exit. E04NDF/E04NDA should be consulted for a full description of this method of supplying optional parameters.
E04NEF/E04NEA can be called to supply options directly, one call being necessary for each optional parameter. For example,
 CALL E04NEF ('Print Level = 1')
E04NEF/E04NEA should be consulted for a full description of this method of supplying optional parameters.
All optional parameters not specified by you are set to their default values. Optional parameters specified by you are unaltered by E04NCF/E04NCA (unless they define invalid values) and so remain in effect for subsequent calls unless altered by you.

12.1 Description of the Optional Parameters

For each option, we give a summary line, a description of the optional parameter and details of constraints.
The summary line contains:
  • the keywords, where the minimum abbreviation of each keyword is underlined (if no characters of an optional qualifier are underlined, the qualifier may be omitted);
  • a parameter value, where the letters a, i and r denote options that take character, integer and real values respectively;
  • the default value, where the symbol ε is a generic notation for machine precision (see X02AJF).
Keywords and character values are case and white space insensitive.
Cold Start Default
Warm Start
This option specifies how the initial working set is chosen. With a Cold Start, E04NCF/E04NCA chooses the initial working set based on the values of the variables and constraints at the initial point. Broadly speaking, the initial working set will include equality constraints and bounds or inequality constraints that violate or ‘nearly’ satisfy their bounds (to within Crash Tolerance).
With a Warm Start, you must provide a valid definition of every element of the array ISTATE. E04NCF/E04NCA will override your specification of ISTATE if necessary, so that a poor choice of the working set will not cause a fatal error. For instance, any elements of ISTATE which are set to -2, -1​ or ​4 will be reset to zero, as will any elements which are set to 3 when the corresponding elements of BL and BU are not equal. A warm start will be advantageous if a good estimate of the initial working set is available – for example, when E04NCF/E04NCA is called repeatedly to solve related problems.
Crash Tolerance r Default =0.01
This value is used in conjunction with the optional parameter Cold Start (the default value) when E04NCF/E04NCA selects an initial working set. If 0≤r≤1, the initial working set will include (if possible) bounds or general inequality constraints that lie within r of their bounds. In particular, a constraint of the form cjT x≥l will be included in the initial working set if cjT x-l ≤ r 1+l . If r<0 or r>1, the default value is used.
Defaults
This special keyword may be used to reset all optional parameters to their default values.
Feasibility Phase Iteration Limit i 1 Default =max 50,5 n+nL
Optimality Phase Iteration Limit i 2 Default =max 50,5 n+nL
The scalars i 1 and i 2 specify the maximum number of iterations allowed in the feasibility and optimality phases. Optional parameter Optimality Phase Iteration Limit is equivalent to optional parameter Iteration Limit. Setting i 2=0 and Print Level>0 means that the workspace needed will be computed and printed, but no iterations will be performed. If i 1<0 or i 2<0, the default value is used.
Feasibility Tolerance r Default =ε
If r>ε, r defines the maximum acceptable absolute violation in each constraint at a ‘feasible’ point. For example, if the variables and the coefficients in the general constaints are of order unity, and the latter are correct to about 6 decimal digits, it would be appropriate to specify r as 10-6. If 0≤r<ε, the default value is used.
Note that a ‘feasible solution’ is a solution that satisfies the current constraints to within the tolerance r.
Hessian N o Default =NO
This option controls the contents of the upper triangular matrix R (see the description of A in Section 5). E04NCF/E04NCA works exclusively with the transformed and reordered matrix HQ (8), and hence extra computation is required to form the Hessian itself. If Hessian=NO, A contains the Cholesky factor of the matrix HQ with columns ordered as indicated by KX (see Section 5). If Hessian=YES, A contains the Cholesky factor of the matrix H, with columns ordered as indicated by KX.
Infinite Bound Size r Default =1020
If r>0, r defines the ‘infinite’ bound bigbnd in the definition of the problem constraints. Any upper bound greater than or equal to bigbnd will be regarded as +∞ (and similarly any lower bound less than or equal to -bigbnd will be regarded as -∞). If r<0, the default value is used.
Infinite Step Size r Default =max bigbnd,1020
If r>0, r specifies the magnitude of the change in variables that will be considered a step to an unbounded solution. (Note that an unbounded solution can occur only when the Hessian is singular and the objective contains an explicit linear term.) If the change in x during an iteration would exceed the value of r, the objective function is considered to be unbounded below in the feasible region. If r≤0, the default value is used.
Iteration Limit i Default =max 50,5 n+nL
Iters
Itns
See optional parameter Feasibility Phase Iteration Limit.
List Default for E04NCF =List
Nolist Default for E04NCA =Nolist
Normally each optional parameter specification is printed as it is supplied. Optional parameter Nolist may be used to suppress the printing and optional parameter List may be used to restore printing.
Monitoring File i Default =-1
If i≥0 and Print Level≥5, monitoring information produced by E04NCF/E04NCA at every iteration is sent to a file with logical unit number i. If i<0 and/or Print Level<5, no monitoring information is produced.
Print Level i Default for E04NCF =10
Default for E04NCA =0
The value of i controls the amount of printout produced by E04NCF/E04NCA, as indicated below. A detailed description of the printed output is given in Section 9.2 (summary output at each iteration and the final solution) and Section 13 (monitoring information at each iteration).
The following printout is sent to the current advisory message unit (as defined by X04ABF):
i | Output
≥0 0 | No output.
≥0 1 | The final solution only.
≥0 5 | One line of summary output (<80 characters; see Section 9.2) for each iteration (no printout of the final solution).
≥10 | The final solution and one line of summary output for each iteration.
The following printout is sent to the logical unit number by the optional parameter Monitoring File:
i | Output
<5 | No output.
≥5 | One long line of output (>80 characters; see Section 13) for each iteration (no printout of the final solution).
≥20 | At each iteration, the Lagrange multipliers, the variables x, the constraint values Cx and the constraint status.
≥30 | At each iteration, the diagonal elements of the matrix T associated with the TQ factorization (4) (see Section 11.2) of the working set, and the diagonal elements of the upper triangular matrix R.
If Print Level≥5 and the unit number defined by the optional parameter Monitoring File is the same as that defined by X04ABF, then the summary output for each major iteration is suppressed.
Problem Type a Default = LS1
This option specifies the type of objective function to be minimized during the optimality phase. The following are the nine optional keywords and the dimensions of the arrays that must be specified in order to define the objective function:
LP | A and B not referenced, CVEC N;
QP1 | A LDAN symmetric, B and CVEC not referenced;
QP2 | A LDAN symmetric, B not referenced, CVEC N;
QP3 | A LDAN upper trapezoidal, KX N, B and CVEC not referenced;
QP4 | A LDAN upper trapezoidal, KX N, B not referenced, CVEC N;
LS1 | A LDAN, B M, CVEC not referenced;
LS2 | A LDAN, B M, CVEC N;
LS3 | A LDAN upper trapezoidal, KX N, B M, CVEC not referenced;
LS4 | A LDAN upper trapezoidal, KX N, B M, CVEC N.
For problems of type FP, the objective function is omitted and A, B and CVEC are not referenced.
The following keywords are also acceptable. The minimum abbreviation of each keyword is underlined.
a | Option
Least | LS1
Quadratic | QP2
Linear | LP
In addition, the keywords LS and LSQ are equivalent to the default option LS1, and the keyword QP is equivalent to the option QP2.
If A=0, i.e., the objective function is purely linear, the efficiency of E04NCF/E04NCA may be increased by specifying a as LP.
Rank Tolerance r Default =100 ε or 10 ε (see below)
Note that this option does not apply to problems of type FP or LP.
The default value of r depends on the problem type. If A occurs as a least squares matrix, as it does in problem types QP1, LS1 and LS3, then the default value of r is 100 ε. In all other cases, A is treated as the ‘square root’ of the Hessian matrix H and r has the default value 10 ε.
This parameter enables you to control the estimate of the triangular factor R 1 (see Section 11.3). If ρi denotes the function ρi=max R 11,R 22,…,R ii, the rank of R is defined to be smallest index i such that R i+1,i+1≤r ρ i+1. If r≤0, the default value is used.

13 Description of Monitoring Information

This section describes the long line of output (>80 characters) which forms part of the monitoring information produced by E04NCF/E04NCA. (See also the description of the optional parameters Monitoring File and Print Level.) You can control the level of printed output.
To aid interpretation of the printed results, the following convention is used for numbering the constraints: indices 1 through n refer to the bounds on the variables, and indices n+1 through n+nL refer to the general constraints. When the status of a constraint changes, the index of the constraint is printed, along with the designation L (lower bound), U (upper bound), E (equality), F (temporarily fixed variable) or A (artificial constraint).
When Print Level≥5 and Monitoring File≥0, the following line of output is produced at every iteration on the unit number specified by optional parameter Monitoring File. In all cases, the values of the quantities printed are those in effect on completion of the given iteration.
Itn | is the iteration count.
Jdel | is the index of the constraint deleted from the working set. If Jdel is zero, no constraint was deleted.
Jadd | is the index of the constraint added to the working set. If Jadd is zero, no constraint was added.
Step | is the step taken along the computed search direction. If a constraint is added during the current iteration (i.e., Jadd is positive), Step will be the step to the nearest constraint. During the optimality phase, the step can be greater than one only if the factor RZ is singular.
Ninf | is the number of violated constraints (infeasibilities). This will be zero during the optimality phase.
Sinf/Objective | is the value of the current objective function. If x is not feasible, Sinf gives a weighted sum of the magnitudes of constraint violations. If x is feasible, Objective is the value of the objective function of (1). The output line for the final iteration of the feasibility phase (i.e., the first iteration for which Ninf is zero) will give the value of the true objective at the first feasible point. During the optimality phase the value of the objective function will be nonincreasing. During the feasibility phase the number of constraint infeasibilities will not increase until either a feasible point is found or the optimality of the multipliers implies that no feasible point exists. Once optimal multipliers are obtained the number of infeasibilities can increase, but the sum of infeasibilities will either remain constant or be reduced until the minimum sum of infeasibilities is found.
Bnd | is the number of simple bound constraints in the current working set.
Lin | is the number of general linear constraints in the current working set.
Art | is the number of artificial constraints in the working set, i.e., the number of columns of Z 2 (see Section 11.3).
Zr | is the number of columns of Z 1 (see Section 11.2). Zr is the dimension of the subspace in which the objective function is currently being minimized. The value of Zr is the number of variables minus the number of constraints in the working set; i.e., Zr=n-Bnd+Lin+Art. The value of nZ, the number of columns of Z (see Section 11.2) can be calculated as nZ=n-Bnd+Lin. A zero value of nZ implies that x lies at a vertex of the feasible region.
Norm Gz | is Z 1 T gFR , the Euclidean norm of the reduced gradient with respect to Z 1. During the optimality phase, this norm will be approximately zero after a unit step.
Norm Gf | is the Euclidean norm of the gradient function with respect to the free variables, i.e., variables not currently held at a bound.
Cond T | is a lower bound on the condition number of the working set.
Cond Rz | is a lower bound on the condition number of the triangular factor R 1 (the first Zr rows and columns of the factor RZ). If the problem is specified to be of type LP or the estimated rank of the data matrix A is zero then Cond Rz is not printed.
E04 Chapter Contents
E04 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


E04NDF/E04NDA : NAG Library, Mark 26

E04 Chapter Contents
E04 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

E04NDF/E04NDA

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
▸▿ 2 Specification
2.1 Specification for E04NDF
2.2 Specification for E04NDA
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

To supply optional parameters to E04NCF/E04NCA from an external file. More precisely, E04NDF must be used to supply optional parameters to E04NCF and E04NDA must be used to supply optional parameters to E04NCA.
E04NDA is a version of E04NDF that has additional arguments in order to make it safe for use in multithreaded applications (see Section 5). The initialization routine E04WBF must have been called before calling E04NDA.

2 Specification

2.1 Specification for E04NDF

SUBROUTINE E04NDF ( IOPTNS, INFORM)
INTEGER IOPTNS, INFORM

2.2 Specification for E04NDA

SUBROUTINE E04NDA ( IOPTNS, LWSAV, IWSAV, RWSAV, INFORM)
INTEGER | IOPTNS, IWSAV(610), INFORM
REAL (KIND=nag_wp) | RWSAV(475)
LOGICAL | LWSAV(120)

3 Description

E04NDF/E04NDA may be used to supply values for optional parameters to E04NCF/E04NCA. E04NDF/E04NDA reads an external file and each line of the file defines a single optional parameter. It is only necessary to supply values for those arguments whose values are to be different from their default values.
Each optional parameter is defined by a single character string, of up to 72 characters, consisting of one or more items. The items associated with a given option must be separated by spaces, or equals signs =. Alphabetic characters may be upper or lower case. The string
Print Level = 1
is an example of a string used to set an optional parameter. For each option the string contains one or more of the following items:
– | a mandatory keyword;
– | a phrase that qualifies the keyword;
– | a number that specifies an integer or real value. Such numbers may be up to 40 contiguous characters in Fortran's I, F, E or D formats, terminated by a space if this is not the last item on the line.
Blank strings and comments are ignored. A comment begins with an asterisk (*) and all subsequent characters in the string are regarded as part of the comment.
The file containing the options must start with Begin and must finish with End. An example of a valid options file is:
Begin * Example options file
   Print level = 5
End
For E04NDF each line of the file is normally printed as it is read, on the current advisory message unit (see X04ABF), but printing may be suppressed using the keyword Nolist. To suppress printing of Begin, Nolist must be the first option supplied as in the file:
Begin
   Nolist
   Print level = 5
End
Printing will automatically be turned on again after a call to E04NCF or E04NDF and may be turned on again at any time using the keyword List.
For E04NDA printing is turned off by default, but may be turned on at any time using the keyword List.
Optional parameter settings are preserved following a call to E04NCF/E04NCA and so the keyword Defaults is provided to allow you to reset all the optional parameters to their default values before a subsequent call to E04NCF/E04NCA.
A complete list of optional parameters, their abbreviations, synonyms and default values is given in Section 12 in E04NCF/E04NCA.

4 References

None.

5 Arguments

1:   IOPTNS – INTEGERInput
On entry: the unit number of the options file to be read.
Constraint: 0≤IOPTNS≤99.
2:   INFORM – INTEGEROutput
Note: for E04NDA, INFORM does not occur in this position in the argument list. See the additional arguments described below.
On exit: contains zero if the options file has been successfully read and a value>0 otherwise (see Section 6).
Note: the following are additional arguments for specific use with E04NDA. Users of E04NDF therefore need not read the remainder of this description.
2:   LWSAV 120 – LOGICAL arrayCommunication Array
3:   IWSAV 610 – INTEGER arrayCommunication Array
4:   RWSAV 475 – REAL (KIND=nag_wp) arrayCommunication Array
The arrays LWSAV, IWSAV and RWSAV must not be altered between calls to any of the routines E04NDA, E04NCA, E04NEA or E04WBF.
5:   INFORM – INTEGEROutput
Note: see the argument description for INFORM above.

6 Error Indicators and Warnings

INFORM=1
IOPTNS is not in the range 0,99.
INFORM=2
Begin was found, but end-of-file was found before End was found.
INFORM=3
end-of-file was found before Begin was found.
INFORM=4
Not used.
INFORM=5
One or more lines of the options file is invalid. Check that all keywords are neither ambiguous nor misspelt.

7 Accuracy

Not applicable.

8 Parallelism and Performance

E04NDF/E04NDA is not threaded in any implementation.

9 Further Comments

E04NEF/E04NEA may also be used to supply optional parameters to E04NCF/E04NCA.

10 Example

This example minimizes the quadratic function cT x+12 xT Ax, where
c=-4.0,-1.0,-1.0,-1.0,-1.0,-1.0,-1.0,-0.1,-0.3 T,
A= 2 1 1 1 1 0 0 0 0 1 2 1 1 1 0 0 0 0 1 1 2 1 1 0 0 0 0 1 1 1 2 1 0 0 0 0 1 1 1 1 2 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
subject to the bounds
-2≤x 1≤2 -2≤x 2≤2 -2≤x 3≤2 -2≤x 4≤2 -2≤x 5≤2 -2≤x 6≤2 -2≤x 7≤2 -2≤x 8≤2 -2≤x 9≤2
and to the general constraints
-2.0≤x 1+0 x 2+0 x 3+0 x 4+0 x 5+x 6+x 7+x 8+ 4 x 9≤ 1.5 -2.0≤x 1+ 2 x 2+ 3 x 3+ 4 x 4- 2 x 5+x 6+x 7+x 8+0 x 9≤ 1.5 -2.0≤x 1-0 x 2+0 x 3-0 x 4+0 x 5+x 6+x 7+x 8+0 x 9≤ 4.0
The initial point, which is feasible, is
x 0=0,0,0,0,0,0,0,0,0 T,
and F x 0=0.
The optimal solution (to five figures) is
x*=2.0,-0.23333,-0.26667,-0.3,-0.1,2.0,2.0,-1.7777,-0.45555 T,
and F x*=-8.0678. Three bound constraints and two general constraints are active at the solution. Note that, although the Hessian matrix is positive semidefinite, the point x* is unique.
In this example the options file read by E04NDF/E04NDA is appended to the data file for the program (see Section 10.2). It would usually be more convenient in practice to keep the data file and the options file separate.

10.1 Program Text

Note: the following programs illustrate the use of E04NDF and E04NDA.

Program Text (e04ndfe.f90)

Program Text (e04ndae.f90)

10.2 Program Data

Program Options (e04ndfe.opt)

Program Options (e04ndae.opt)

Program Data (e04ndfe.d)

Program Data (e04ndae.d)

10.3 Program Results

Program Results (e04ndfe.r)

Program Results (e04ndae.r)

E04 Chapter Contents
E04 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


E04NEF/E04NEA : NAG Library, Mark 26

E04 Chapter Contents
E04 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

E04NEF/E04NEA

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
▸▿ 2 Specification
2.1 Specification for E04NEF
2.2 Specification for E04NEA
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
10 Example

1 Purpose

To supply individual optional parameters to E04NCF/E04NCA. More precisely, E04NEF must be used to supply optional parameters to E04NCF and E04NEA must be used to supply optional parameters to E04NCA.
E04NEA is a version of E04NEF that has additional arguments in order to make it safe for use in multithreaded applications (see Section 5). The initialization routine E04WBF must have been called before calling E04NEA.

2 Specification

2.1 Specification for E04NEF

SUBROUTINE E04NEF ( STR)
CHARACTER(*) STR

2.2 Specification for E04NEA

SUBROUTINE E04NEA ( STR, LWSAV, IWSAV, RWSAV, INFORM)
INTEGER | IWSAV(610), INFORM
REAL (KIND=nag_wp) | RWSAV(475)
LOGICAL | LWSAV(120)
CHARACTER(*) | STR

3 Description

E04NEF/E04NEA may be used to supply values for optional parameters to E04NCF/E04NCA. It is only necessary to call E04NEF/E04NEA for those arguments whose values are to be different from their default values. One call to E04NEF/E04NEA sets one argument value.
Each optional parameter is defined by a single character string, of up to 72 characters, consisting of one or more items. The items associated with a given option must be separated by spaces, or equals signs =. Alphabetic characters may be upper or lower case. The string
Print Level = 1
is an example of a string used to set an optional parameter. For each option the string contains one or more of the following items:
– | a mandatory keyword;
– | a phrase that qualifies the keyword;
– | a number that specifies an integer or real value. Such numbers may be up to 40 contiguous characters in Fortran's I, F, E or D formats, terminated by a space if this is not the last item on the line.
Blank strings and comments are ignored. A comment begins with an asterisk (*) and all subsequent characters in the string are regarded as part of the comment.
For E04NEF, each user-specified option is normally printed as it is defined, on the current advisory message unit (see X04ABF), but this printing may be suppressed using the keyword Nolist. Thus the statement
 CALL E04NEF ('Nolist')
suppresses printing of this and subsequent options. Printing will automatically be turned on again after a call to E04NCF and may be turned on again at any time using the keyword List.
For E04NEA printing is turned off by default, but may be turned on at any time using the keyword List.
Optional parameter settings are preserved following a call to E04NCF/E04NCA and so the keyword Defaults is provided to allow you to reset all the optional parameters to their default values before a subsequent call to E04NCF/E04NCA.
A complete list of optional parameters, their abbreviations, synonyms and default values is given in Section 12 in E04NCF/E04NCA.

4 References

None.

5 Arguments

1:   STR – CHARACTER(*)Input
On entry: a single valid option string (as described in Section 3 and in Section 12 in E04NCF/E04NCA).
Note: the following are additional arguments for specific use with E04NEA. Users of E04NEF therefore need not read the remainder of this description.
2:   LWSAV 120 – LOGICAL arrayCommunication Array
3:   IWSAV 610 – INTEGER arrayCommunication Array
4:   RWSAV 475 – REAL (KIND=nag_wp) arrayCommunication Array
The arrays LWSAV, IWSAV and RWSAV must not be altered between calls to any of the routines E04NEA, E04NCA, E04NDA or E04WBF.
5:   INFORM – INTEGEROutput
On exit: contains zero if a valid option string has been supplied and a value>0 otherwise (see Section 6).

6 Error Indicators and Warnings

INFORM=5
The supplied option is invalid. Check that the keywords are neither ambiguous nor misspelt.

7 Accuracy

Not applicable.

8 Parallelism and Performance

E04NEF/E04NEA is not threaded in any implementation.

9 Further Comments

E04NDF/E04NDA may also be used to supply optional parameters to E04NCF/E04NCA.

10 Example

See Section 10 in E04NDF/E04NDA.
E04 Chapter Contents
E04 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


E04NFF/E04NFA : NAG Library, Mark 26

E04 Chapter Contents
E04 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

E04NFF/E04NFA

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.
Note: this routine uses optional parameters to define choices in the problem specification and in the details of the algorithm. If you wish to use default settings for all of the optional parameters, you need only read Sections 1 to 10 of this document. If, however, you wish to reset some or all of the settings please refer to Section 11 for a detailed description of the algorithm, to Section 12 for a detailed description of the specification of the optional parameters and to Section 13 for a detailed description of the monitoring information produced by the routine.

▸▿ Contents

1 Purpose
▸▿ 2 Specification
2.1 Specification for E04NFF
2.2 Specification for E04NFA
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
▸▿ 9 Further Comments
9.1 Scaling
9.2 Description of the Printed Output
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results
▸▿ 11 Algorithmic Details
11.1 Overview
11.2 Definition of Search Direction
11.3 Main Iteration
11.4 Choosing the Initial Working Set
▸▿ 12 Optional Parameters
12.1 Description of the Optional Parameters
13 Description of Monitoring Information

1 Purpose

E04NFF/E04NFA solves general quadratic programming problems. It is not intended for large sparse problems.
E04NFA is a version of E04NFF that has additional arguments in order to make it safe for use in multithreaded applications (see Section 5). The initialization routine E04WBF must have been called before calling E04NFA.

2 Specification

2.1 Specification for E04NFF

SUBROUTINE E04NFF ( N, NCLIN, A, LDA, BL, BU, CVEC, H, LDH, QPHESS, ISTATE, X, ITER, OBJ, AX, CLAMDA, IWORK, LIWORK, WORK, LWORK, IFAIL)
INTEGER | N, NCLIN, LDA, LDH, ISTATE(N+NCLIN), ITER, IWORK(LIWORK), LIWORK, LWORK, IFAIL
REAL (KIND=nag_wp) | A(LDA,*), BL(N+NCLIN), BU(N+NCLIN), CVEC(*), H(LDH,*), X(N), OBJ, AX(max(1,NCLIN)), CLAMDA(N+NCLIN), WORK(LWORK)
EXTERNAL | QPHESS

2.2 Specification for E04NFA

SUBROUTINE E04NFA ( N, NCLIN, A, LDA, BL, BU, CVEC, H, LDH, QPHESS, ISTATE, X, ITER, OBJ, AX, CLAMDA, IWORK, LIWORK, WORK, LWORK, IUSER, RUSER, LWSAV, IWSAV, RWSAV, IFAIL)
INTEGER | N, NCLIN, LDA, LDH, ISTATE(N+NCLIN), ITER, IWORK(LIWORK), LIWORK, LWORK, IUSER(*), IWSAV(610), IFAIL
REAL (KIND=nag_wp) | A(LDA,*), BL(N+NCLIN), BU(N+NCLIN), CVEC(*), H(LDH,*), X(N), OBJ, AX(max(1,NCLIN)), CLAMDA(N+NCLIN), WORK(LWORK), RUSER(*), RWSAV(475)
LOGICAL | LWSAV(120)
EXTERNAL | QPHESS
Before calling E04NFA, or either of the option setting routines E04NGA or E04NHA, E04WBF must be called. The specification for E04WBF is:
SUBROUTINE E04WBF ( RNAME, CWSAV, LCWSAV, LWSAV, LLWSAV, IWSAV, LIWSAV, RWSAV, LRWSAV, IFAIL)
INTEGER | LCWSAV, LLWSAV, IWSAV(LIWSAV), LIWSAV, LRWSAV, IFAIL
REAL (KIND=nag_wp) | RWSAV(LRWSAV)
LOGICAL | LWSAV(LLWSAV)
CHARACTER(*) | RNAME
CHARACTER(80) | CWSAV(LCWSAV)
E04WBF should be called with RNAME='E04NFA'. LCWSAV, LLWSAV, LIWSAV and LRWSAV, the declared lengths of CWSAV, LWSAV, IWSAV and RWSAV respectively, must satisfy:
  • LCWSAV≥1
  • LLWSAV≥120
  • LIWSAV≥610
  • LRWSAV≥475
The contents of the arrays CWSAV, LWSAV, IWSAV and RWSAV must not be altered between calling routines E04NFA, E04NGA, E04NHA and E04WBF.

3 Description

E04NFF/E04NFA is designed to solve a class of quadratic programming problems that are assumed to be stated in the following general form:
minimize x∈Rn f x  subject to  l≤ x Ax ≤u,
where A is an mL by n matrix and f x may be specified in a variety of ways depending upon the particular problem to be solved. The available forms for f x are listed in Table 1, in which the prefixes FP, LP and QP stand for ‘feasible point’, ‘linear programming’ and ‘quadratic programming’ respectively and c is an n-element vector.
Problem type | f x | Matrix H
FP | Not applicable | Not applicable
LP | cT x | Not applicable
QP1 | cT x+12 xT Hx | symmetric
QP2 | cT x+12 xT Hx | symmetric
QP3 | cT x+12 xTHT Hx | m by n upper trapezoidal
QP4 | cT x+12 xTHT Hx | m by n upper trapezoidal
Table 1
There is no restriction on H or HT H apart from symmetry. If the quadratic function is convex, a global minimum is found; otherwise, a local minimum is found. The default problem type is QP2 and other objective functions are selected by using the optional parameter Problem Type. For problems of type FP, the objective function is omitted and the routine attempts to find a feasible point for the set of constraints.
The constraints involving A are called the general constraints. Note that upper and lower bounds are specified for all the variables and for all the general constraints. An equality constraint can be specified by setting li=ui. If certain bounds are not present, the associated elements of l or u can be set to special values that will be treated as -∞ or +∞. (See the description of the optional parameter Infinite Bound Size.)
The defining feature of a quadratic function f x is that the second-derivative matrix ∇2 f x (the Hessian matrix) is constant. For QP1 and QP2 (the default), ∇2 f x=H; for QP3 and QP4, ∇2 f x=HT H; and for the LP case, ∇2 f x=0. If H is positive semidefinite, it is usually more efficient to use E04NCF/E04NCA. If H is defined as the zero matrix, E04NFF/E04NFA will still attempt to solve the resulting linear programming problem; however, this can be accomplished more efficiently by setting the optional parameter Problem Type=LP, or by using E04MFF/E04MFA instead.
You must supply an initial estimate of the solution.
In the QP case, you may supply H either explicitly as an m by n matrix, or implicitly in a subroutine that computes the product Hx or HT Hx for any given vector x.
In general, a successful run of E04NFF/E04NFA will indicate one of three situations:
(i) | a minimizer has been found;
(ii) | the algorithm has terminated at a so-called dead-point; or
(iii) | the problem has no bounded solution.
If a minimizer is found, and ∇2 f x is positive definite or positive semidefinite, E04NFF/E04NFA will obtain a global minimizer; otherwise, the solution will be a local minimizer (which may or may not be a global minimizer). A dead-point is a point at which the necessary conditions for optimality are satisfied but the sufficient conditions are not. At such a point, a feasible direction of decrease may or may not exist, so that the point is not necessarily a local solution of the problem. Verification of optimality in such instances requires further information, and is in general an NP-hard problem (see Pardalos and Schnitger (1988)). Termination at a dead-point can occur only if ∇2 f x is not positive definite. If ∇2 f x is positive semidefinite, the dead-point will be a weak minimizer (i.e., with a unique optimal objective value, but an infinite set of optimal x).
The method used by E04NFF/E04NFA (see Section 11) is most efficient when many constraints or bounds are active at the solution.

4 References

Gill P E, Hammarling S, Murray W, Saunders M A and Wright M H (1986) Users' guide for LSSOL (Version 1.0) Report SOL 86-1 Department of Operations Research, Stanford University
Gill P E and Murray W (1978) Numerically stable methods for quadratic programming Math. Programming 14 349–372
Gill P E, Murray W, Saunders M A and Wright M H (1984) Procedures for optimization problems with a mixture of bounds and general linear constraints ACM Trans. Math. Software 10 282–298
Gill P E, Murray W, Saunders M A and Wright M H (1989) A practical anti-cycling procedure for linearly constrained optimization Math. Programming 45 437–474
Gill P E, Murray W, Saunders M A and Wright M H (1991) Inertia-controlling methods for general quadratic programming SIAM Rev. 33 1–36
Gill P E, Murray W and Wright M H (1981) Practical Optimization Academic Press
Pardalos P M and Schnitger G (1988) Checking local optimality in constrained quadratic programming is NP-hard Operations Research Letters 7 33–35

5 Arguments

1:   N – INTEGERInput
On entry: n, the number of variables.
Constraint: N>0.
2:   NCLIN – INTEGERInput
On entry: mL, the number of general linear constraints.
Constraint: NCLIN≥0.
3:   A LDA* – REAL (KIND=nag_wp) arrayInput
Note: the second dimension of the array A must be at least N if NCLIN>0 and at least 1 if NCLIN=0.
On entry: the ith row of A must contain the coefficients of the ith general linear constraint, for i=1,2,…,mL.
If NCLIN=0, A is not referenced.
4:   LDA – INTEGERInput
On entry: the first dimension of the array A as declared in the (sub)program from which E04NFF/E04NFA is called.
Constraint: LDA≥max 1,NCLIN.
5:   BL N+NCLIN – REAL (KIND=nag_wp) arrayInput
6:   BU N+NCLIN – REAL (KIND=nag_wp) arrayInput
On entry: BL must contain the lower bounds and BU the upper bounds, for all the constraints in the following order. The first n elements of each array must contain the bounds on the variables, and the next mL elements the bounds for the general linear constraints (if any). To specify a nonexistent lower bound (i.e., lj=-∞), set BL j≤-bigbnd, and to specify a nonexistent upper bound (i.e., uj=+∞), set BU j≥bigbnd; the default value of bigbnd is 1020, but this may be changed by the optional parameter Infinite Bound Size. To specify the jth constraint as an equality, set BL j=BU j=β, say, where β<bigbnd.
Constraints:
  • BL j≤BU j, for j=1,2,…,N+NCLIN;
  • if BL j=BU j=β, β<bigbnd.
7:   CVEC* – REAL (KIND=nag_wp) arrayInput
Note: the dimension of the array CVEC must be at least N if the problem is of type LP, QP2 (the default) or QP4, and at least 1 otherwise.
On entry: the coefficients of the explicit linear term of the objective function when the problem is of type LP, QP2 (the default) and QP4.
If the problem is of type FP, QP1, or QP3, CVEC is not referenced.
8:   H LDH* – REAL (KIND=nag_wp) arrayInput
Note: the second dimension of the array H must be at least N if it is to be used to store H explicitly, and at least 1 otherwise.
On entry: may be used to store the quadratic term H of the QP objective function if desired. In some cases, you need not use H to store H explicitly (see the specification of subroutine QPHESS). The elements of H are referenced only by subroutine QPHESS. The number of rows of H is denoted by m, whose default value is n. (The optional parameter Hessian Rows may be used to specify a value of m<n.)
If the default version of QPHESS is used and the problem is of type QP1 or QP2 (the default), the first m rows and columns of H must contain the leading m by m rows and columns of the symmetric Hessian matrix H. Only the diagonal and upper triangular elements of the leading m rows and columns of H are referenced. The remaining elements need not be assigned.
If the default version of QPHESS is used and the problem is of type QP3 or QP4, the first m rows of H must contain an m by n upper trapezoidal factor of the symmetric Hessian matrix HT H. The factor need not be of full rank, i.e., some of the diagonal elements may be zero. However, as a general rule, the larger the dimension of the leading nonsingular sub-matrix of H, the fewer iterations will be required. Elements outside the upper trapezoidal part of the first m rows of H need not be assigned.
If a non-default version of QPHESS is supplied, then in some cases it may be desirable to use a one-dimensional array to transmit data to QPHESS. (This is illustrated in the example program in Section 10 in E04NGF/E04NGA.) H is then declared as an LDH by 1 array, where LDH≥N×N+1/2.
In other situations, it may be desirable to compute Hx or HT Hx without accessing H – for example, if H or HT H is sparse or has special structure. The arguments H and LDH may then refer to any convenient array.
If the problem is of type FP or LP, H is not referenced.
9:   LDH – INTEGERInput
On entry: the first dimension of the array H as declared in the (sub)program from which E04NFF/E04NFA is called.
Constraints:
  • if the problem is of type QP1, QP2 (the default), QP3 or QP4, LDH≥N or at least the value of the optional parameter Hessian Rows;
  • if the problem is of type FP or LP, LDH≥1.
10:   QPHESS – SUBROUTINE, supplied by the NAG Library or the user.External Procedure
In general, you need not provide a version of QPHESS, because a ‘default’ subroutine with name E04NFU/E54NFU is included in the Library. However, the algorithm of E04NFF/E04NFA requires only the product of H or HT H and a vector x; and in some cases you may obtain increased efficiency by providing a version of QPHESS that avoids the need to define the elements of the matrices H or HT H explicitly.
QPHESS is not referenced if the problem is of type FP or LP, in which case QPHESS may be the routine E04NFU/E54NFU.
The specification of QPHESS for E04NFF is:
SUBROUTINE QPHESS ( N, JTHCOL, H, LDH, X, HX)
INTEGER | N, JTHCOL, LDH
REAL (KIND=nag_wp) | H(LDH,*), X(N), HX(N)
The specification of QPHESS for E04NFA is:
SUBROUTINE QPHESS ( N, JTHCOL, H, LDH, X, HX, IUSER, RUSER, IWSAV)
INTEGER | N, JTHCOL, LDH, IUSER(*), IWSAV(610)
REAL (KIND=nag_wp) | H(LDH,*), X(N), HX(N), RUSER(*)
1:   N – INTEGERInput
On entry: this is the same argument as supplied to this routine. See the description for the top level argument N.
2:   JTHCOL – INTEGERInput
On entry: specifies whether or not the vector x is a column of the identity matrix.
JTHCOL=j>0
The vector x is the jth column of the identity matrix, and hence Hx or HT Hx is the jth column of H or HT H, respectively. This may in some cases require very little computation and QPHESS may be coded to take advantage of this. However special code is not necessary because x is always stored explicitly in the array X.
JTHCOL=0
x has no special form.
3:   H LDH* – REAL (KIND=nag_wp) arrayInput
On entry: this is the same argument as supplied to this routine. See the description for the top level argument H.
4:   LDH – INTEGERInput
On entry: this is the same argument as supplied to this routine. See the description for the top level argument LDH.
5:   X N – REAL (KIND=nag_wp) arrayInput
On entry: the vector x.
6:   HX N – REAL (KIND=nag_wp) arrayOutput
On exit: the product Hx if the problem is of type QP1 or QP2 (the default), or the product HT Hx if the problem is of type QP3 or QP4.
Note: the following are additional arguments for specific use with E04NFA. Users of E04NFF therefore need not read the remainder of this description.
7:   IUSER* – INTEGER arrayUser Workspace
8:   RUSER* – REAL (KIND=nag_wp) arrayUser Workspace
QPHESS is called with the arguments IUSER and RUSER as supplied to E04NFF/E04NFA. You are free to use the arrays IUSER and RUSER to supply information to QPHESS as an alternative to using COMMON global variables.
9:   IWSAV 610 – INTEGER arrayCommunication Array
IWSAV contains information that is required by the default routine E54NFU.
QPHESS must either be a module subprogram USEd by, or declared as EXTERNAL in, the (sub)program from which E04NFF/E04NFA is called. Arguments denoted as Input must not be changed by this procedure.
11:   ISTATE N+NCLIN – INTEGER arrayInput/Output
On entry: need not be set if the (default) optional parameter Cold Start is used.
If the optional parameter Warm Start has been chosen, ISTATE specifies the desired status of the constraints at the start of the feasibility phase. More precisely, the first n elements of ISTATE refer to the upper and lower bounds on the variables, and the next mL elements refer to the general linear constraints (if any). Possible values for ISTATE j are as follows:
ISTATE j | Meaning
0 | The corresponding constraint should not be in the initial working set.
1 | The constraint should be in the initial working set at its lower bound.
2 | The constraint should be in the initial working set at its upper bound.
3 | The constraint should be in the initial working set as an equality. This value must not be specified unless BL j=BU j.
The values -2, -1 and 4 are also acceptable but will be reset to zero by the routine. If E04NFF/E04NFA has been called previously with the same values of N and NCLIN, ISTATE already contains satisfactory information. (See also the description of the optional parameter Warm Start.) The routine also adjusts (if necessary) the values supplied in X to be consistent with ISTATE.
Constraint: -2≤ISTATE j≤4, for j=1,2,…,N+NCLIN.
On exit: the status of the constraints in the working set at the point returned in X. The significance of each possible value of ISTATE j is as follows:
ISTATE j | Meaning
-2 | The constraint violates its lower bound by more than the feasibility tolerance.
-1 | The constraint violates its upper bound by more than the feasibility tolerance.
-0 | The constraint is satisfied to within the feasibility tolerance, but is not in the working set.
-1 | This inequality constraint is included in the working set at its lower bound.
-2 | This inequality constraint is included in the working set at its upper bound.
-3 | This constraint is included in the working set as an equality. This value of ISTATE can occur only when BL j=BU j.
-4 | This corresponds to optimality being declared with X j being temporarily fixed at its current value. This value of ISTATE can occur only when IFAIL=1 on exit.
12:   X N – REAL (KIND=nag_wp) arrayInput/Output
On entry: an initial estimate of the solution.
On exit: the point at which E04NFF/E04NFA terminated. If IFAIL=0, 1 or 4, X contains an estimate of the solution.
13:   ITER – INTEGEROutput
On exit: the total number of iterations performed.
14:   OBJ – REAL (KIND=nag_wp)Output
On exit: the value of the objective function at x if x is feasible, or the sum of infeasibilities at x otherwise. If the problem is of type FP and x is feasible, OBJ is set to zero.
15:   AX max 1,NCLIN – REAL (KIND=nag_wp) arrayOutput
On exit: the final values of the linear constraints Ax.
If NCLIN=0, AX is not referenced.
16:   CLAMDA N+NCLIN – REAL (KIND=nag_wp) arrayOutput
On exit: the values of the Lagrange multipliers for each constraint with respect to the current working set. The first n elements contain the multipliers for the bound constraints on the variables, and the next mL elements contain the multipliers for the general linear constraints (if any). If ISTATE j=0 (i.e., constraint j is not in the working set), CLAMDA j is zero. If x is optimal, CLAMDA j should be non-negative if ISTATE j=1, non-positive if ISTATE j=2 and zero if ISTATE j=4.
17:   IWORK LIWORK – INTEGER arrayWorkspace
18:   LIWORK – INTEGERInput
On entry: the dimension of the array IWORK as declared in the (sub)program from which E04NFF/E04NFA is called.
Constraint: LIWORK≥2×N+3.
19:   WORK LWORK – REAL (KIND=nag_wp) arrayWorkspace
20:   LWORK – INTEGERInput
On entry: the dimension of the array WORK as declared in the (sub)program from which E04NFF/E04NFA is called.
Constraints:
  • if the problem is of type QP2 (the default) or QP4,
    • if NCLIN>0, LWORK≥2×N 2+8×N+5×NCLIN;
    • if NCLIN=0, LWORK≥N 2+8×N;
  • if the problem is of type QP1 or QP3,
    • if NCLIN>0, LWORK≥2×N 2+7×N+5×NCLIN;
    • if NCLIN=0, LWORK≥N 2+7×N;
  • if the problem is of type LP,
    • if NCLIN=0, LWORK≥8×N+1;
    • if NCLIN≥N, LWORK≥2×N 2+8×N+5×NCLIN;
    • otherwise LWORK≥2×NCLIN+1 2+8×N+5×NCLIN;
  • if the problem is of type FP,
    • if NCLIN=0, LWORK≥7×N+1;
    • if NCLIN≥N, LWORK≥2×N 2+7×N+5×NCLIN;
    • otherwise LWORK≥2×NCLIN+1 2+7×N+5×NCLIN.
The amounts of workspace provided and required are (by default) output on the current advisory message unit (as defined by X04ABF). As an alternative to computing LIWORK and LWORK from the formulas given above, you may prefer to obtain appropriate values from the output of a preliminary run with LIWORK and LWORK set to 1. (E04NFF/E04NFA will then terminate with IFAIL=6.)
21:   IFAIL – INTEGERInput/Output
Note: for E04NFA, IFAIL does not occur in this position in the argument list. See the additional arguments described below.
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, because for this routine the values of the output arguments may be useful even if IFAIL≠0 on exit, the recommended value is -1. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).
E04NFF/E04NFA returns with IFAIL=0 if x is a strong local minimizer, i.e., the reduced gradient (Norm Gz; see Section 9.2) is negligible, the Lagrange multipliers (Lagr Mult; see Section 9.2) are optimal and HR (the reduced Hessian of f x; see Section 11.2) is positive semidefinite.
Note: the following are additional arguments for specific use with E04NFA. Users of E04NFF therefore need not read the remainder of this description.
21:   IUSER* – INTEGER arrayUser Workspace
22:   RUSER* – REAL (KIND=nag_wp) arrayUser Workspace
IUSER and RUSER are not used by E04NFF/E04NFA, but are passed directly to QPHESS and may be used to pass information to this routine as an alternative to using COMMON global variables.
23:   LWSAV 120 – LOGICAL arrayCommunication Array
24:   IWSAV 610 – INTEGER arrayCommunication Array
25:   RWSAV 475 – REAL (KIND=nag_wp) arrayCommunication Array
The arrays LWSAV, IWSAV and RWSAV must not be altered between calls to any of the routines E04NFA, E04NGA or E04NHA.
26:   IFAIL – INTEGERInput/Output
Note: see the argument description for IFAIL above.

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Note: E04NFF/E04NFA may return useful information for one or more of the following detected errors or warnings.
Errors or warnings detected by the routine:
IFAIL=1
The iterations were terminated at a dead-point. The necessary conditions for optimality are satisfied but the sufficient conditions are not. (The reduced gradient is negligible, the Lagrange multipliers are optimal, but HR is singular or there are some very small multipliers.) If ∇2 f x is not positive definite, x is not necessarily a local solution of the problem and verification of optimality requires further information. If ∇2 f x is positive semidefinite or the problem is of type LP, x gives the global minimum value of the objective function, but the final x is not unique.
IFAIL=2
The solution appears to be unbounded, i.e., the objective function is not bounded below in the feasible region. This value of IFAIL occurs if a step larger than Infinite Step Size (default value=1020) would have to be taken in order to continue the algorithm, or the next step would result in an element of x having magnitude larger than Infinite Bound Size (default value=1020).
IFAIL=3
No feasible point was found, i.e., it was not possible to satisfy all the constraints to within the feasibility tolerance. In this case, the constraint violations at the final x will reveal a value of the tolerance for which a feasible point will exist – for example, when the feasibility tolerance for each violated constraint exceeds its Slack (see Section 9.2) at the final point. The modified problem (with an altered feasibility tolerance) may then be solved using a Warm Start. You should check that there are no constraint redundancies. If the data for the constraints are accurate only to the absolute precision σ, you should ensure that the value of the optional parameter Feasibility Tolerance (default value=ε, where ε is the machine precision) is greater than σ. For example, if all elements of A are of order unity and are accurate only to three decimal places, the Feasibility Tolerance should be at least 10-3.
IFAIL=4
The limiting number of iterations was reached before normal termination occurred.
The values of the optional parameters Feasibility Phase Iteration Limit (default value=max 50,5 n+mL) and Optimality Phase Iteration Limit (default value=max 50,5 n+mL) may be too small. If the method appears to be making progress (e.g., the objective function is being satisfactorily reduced), either increase the iterations limit and rerun E04NFF/E04NFA or, alternatively, rerun E04NFF/E04NFA using the Warm Start facility to specify the initial working set.
IFAIL=5
The reduced Hessian exceeds its assigned dimension. The algorithm needed to expand the reduced Hessian when it was already at its maximum dimension, as specified by the optional parameter Maximum Degrees of Freedom (default value=n).
The value of the optional parameter Maximum Degrees of Freedom is too small. Rerun E04NFF/E04NFA with a larger value (possibly using the Warm Start facility to specify the initial working set).
IFAIL=6
An input argument is invalid.
IFAIL=7
The designated problem type was not FP, LP, QP1, QP2, QP3 or QP4. Rerun E04NFF/E04NFA with the optional parameter Problem Type set to one of these values.
Overflow
If the printed output before the overflow error contains a warning about serious ill-conditioning in the working set when adding the jth constraint, it may be possible to avoid the difficulty by increasing the magnitude of the Feasibility Tolerance (default value=ε, where ε is the machine precision) and rerunning the program. If the message recurs even after this change, the offending linearly dependent constraint (with index ‘j’) must be removed from the problem.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

E04NFF/E04NFA implements a numerically stable active set strategy and returns solutions that are as accurate as the condition of the problem warrants on the machine.

8 Parallelism and Performance

E04NFF/E04NFA makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

This section contains some comments on scaling and a description of the printed output.

9.1 Scaling

Sensible scaling of the problem is likely to reduce the number of iterations required and make the problem less sensitive to perturbations in the data, thus improving the condition of the problem. In the absence of better information it is usually sensible to make the Euclidean lengths of each constraint of comparable magnitude. See the E04 Chapter Introduction and Gill et al. (1981) for further information and advice.

9.2 Description of the Printed Output

This section describes the intermediate printout and final printout produced by E04NFF/E04NFA. The intermediate printout is a subset of the monitoring information produced by the routine at every iteration (see Section 13). You can control the level of printed output (see the description of the optional parameter Print Level). Note that the intermediate printout and final printout are produced only if Print Level≥10 (the default for E04NFF, by default no output is produced by E04NFA).
The following line of summary output (<80 characters) is produced at every iteration. In all cases, the values of the quantities printed are those in effect on completion of the given iteration.
Itn | is the iteration count.
Step | is the step taken along the computed search direction. If a constraint is added during the current iteration, Step will be the step to the nearest constraint. When the problem is of type LP, the step can be greater than one during the optimality phase.
Ninf | is the number of violated constraints (infeasibilities). This will be zero during the optimality phase.
Sinf/Objective | is the value of the current objective function. If x is not feasible, Sinf gives a weighted sum of the magnitudes of constraint violations. If x is feasible, Objective is the value of the objective function of (1). The output line for the final iteration of the feasibility phase (i.e., the first iteration for which Ninf is zero) will give the value of the true objective at the first feasible point. During the optimality phase the value of the objective function will be nonincreasing. During the feasibility phase the number of constraint infeasibilities will not increase until either a feasible point is found or the optimality of the multipliers implies that no feasible point exists. Once optimal multipliers are obtained the number of infeasibilities can increase, but the sum of infeasibilities will either remain constant or be reduced until the minimum sum of infeasibilities is found.
Norm Gz | is ZRT gFR , the Euclidean norm of the reduced gradient with respect to ZR. During the optimality phase, this norm will be approximately zero after a unit step. (See Sections 11.2 and 11.3.)
The final printout includes a listing of the status of every variable and constraint.
The following describes the printout for each variable. A full stop (.) is printed for any numerical value that is zero.
Varbl | gives the name (V) and index j, for j=1,2,…,n, of the variable.
State gives the state of the variable (FR if neither bound is in the working set, EQ if a fixed variable, LL if on its lower bound, UL if on its upper bound, TF if temporarily fixed at its current value). If Value lies outside the upper or lower bounds by more than the Feasibility Tolerance, State will be ++ or -- respectively.
A key is sometimes printed before State.
A | Alternative optimum possible. The variable is active at one of its bounds, but its Lagrange multiplier is essentially zero. This means that if the variable were allowed to start moving away from its bound then there would be no change to the objective function. The values of the other free variables might change, giving a genuine alternative solution. However, if there are any degenerate variables (labelled D), the actual change might prove to be zero, since one of them could encounter a bound immediately. In either case the values of the Lagrange multipliers might also change.
D | Degenerate. The variable is free, but it is equal to (or very close to) one of its bounds.
I | Infeasible. The variable is currently violating one of its bounds by more than the Feasibility Tolerance.
Value | is the value of the variable at the final iteration.
Lower Bound | is the lower bound specified for the variable. None indicates that BL j≤-bigbnd.
Upper Bound | is the upper bound specified for the variable. None indicates that BU j≥bigbnd.
Lagr Mult | is the Lagrange multiplier for the associated bound. This will be zero if State is FR unless BL j≤-bigbnd and BU j≥bigbnd, in which case the entry will be blank. If x is optimal, the multiplier should be non-negative if State is LL and non-positive if State is UL.
Slack | is the difference between the variable Value and the nearer of its (finite) bounds BL j and BU j. A blank entry indicates that the associated variable is not bounded (i.e., BL j≤-bigbnd and BU j≥bigbnd).
The meaning of the printout for general constraints is the same as that given above for variables, with ‘variable’ replaced by ‘constraint’, BL j and BU j are replaced by BL n+j and BU n+j respectively, and with the following change in the heading:
L Con gives the name (L) and index j, for j=1,2,…,nL, of the linear constraint.
Note that movement off a constraint (as opposed to a variable moving away from its bound) can be interpreted as allowing the entry in the Slack column to become positive.
Numerical values are output with a fixed number of digits; they are not guaranteed to be accurate to this precision.

10 Example

This example minimizes the quadratic function f x=cT x+12 xT Hx, where
c=-0.02,-0.2,-0.2,-0.2,-0.2,0.04,0.04 T
H= 2 0 0 0 0 -0 -0 0 2 0 0 0 -0 -0 0 0 2 2 0 -0 -0 0 0 2 2 0 -0 -0 0 0 0 0 2 -0 -0 0 0 0 0 0 -2 -2 0 0 0 0 0 -2 -2
subject to the bounds
-0.01≤x 1≤0.01 -0.1 0≤x 2≤0.15 -0.01≤x 3≤0.03 -0.04≤x 4≤0.02 -0.1 0≤x 5≤0.05 -0.01≤x 6≤0.00 -0.01≤x 7≤0.00
and to the general constraints
x 1 + x 2 + x 3 + x 4 + x 5 + x 6 + x 7 = -0.13 0.15 x 1 + 0.04 x 2 + 0.02 x 3 + 0.04 x 4 + 0.02 x 5 + 0.01 x 6 + 0.03 x 7 ≤ -0.0049 0.03 x 1 + 0.05 x 2 + 0.08 x 3 + 0.02 x 4 + 0.06 x 5 + 0.01 x 6 ≤ -0.0064 0 0.02 x 1 + 0.04 x 2 + 0.01 x 3 + 0.02 x 4 + 0.02 x 5 ≤ -0.0037 0.02 x 1 + 0.03 x 2 + 0.01 x 5 ≤ -0.0012 -0.0992 ≤ 0.70 x 1 + 0.75 x 2 + 0.80 x 3 + 0.75 x 4 + 0.80 x 5 + 0.97 x 6 -0.003 ≤ 0.02 x 1 + 0.06 x 2 + 0.08 x 3 + 0.12 x 4 + 0.02 x 5 + 0.01 x 6 + 0.97 x 7 ≤ -0.002
The initial point, which is infeasible, is
x 0 = -0.01,-0.03,0.0,-0.01,-0.1,0.02,0.01 T .
The optimal solution (to five figures) is
x*=-0.01,-0.069865,0.018259,-0.24261,-0.62006,0.013805,0.0040665 T.
One bound constraint and four general constraints are active at the solution.
The document for E04NGF/E04NGA includes an example program to solve the same problem using some of the optional parameters described in Section 12.

10.1 Program Text

Note: the following programs illustrate the use of E04NFF and E04NFA.

Program Text (e04nffe.f90)

Program Text (e04nfae.f90)

10.2 Program Data

Program Data (e04nffe.d)

Program Data (e04nfae.d)

10.3 Program Results

Program Results (e04nffe.r)

Program Results (e04nfae.r)

Note: the remainder of this document is intended for more advanced users. Section 11 contains a detailed description of the algorithm which may be needed in order to understand Sections 12 and 13. Section 12 describes the optional parameters which may be set by calls to E04NGF/E04NGA and/or E04NHF/E04NHA. Section 13 describes the quantities which can be requested to monitor the course of the computation.

11 Algorithmic Details

This section contains a detailed description of the method used by E04NFF/E04NFA.

11.1 Overview

E04NFF/E04NFA is based on an inertia-controlling method that maintains a Cholesky factorization of the reduced Hessian (see below). The method is based on that of Gill and Murray (1978), and is described in detail by Gill et al. (1991). Here we briefly summarise the main features of the method. Where possible, explicit reference is made to the names of variables that are arguments of E04NFF/E04NFA or appear in the printed output. E04NFF/E04NFA has two phases:
(i) | finding an initial feasible point by minimizing the sum of infeasibilities (the feasibility phase), and
(ii) | minimizing the quadratic objective function within the feasible region (the optimality phase).
The computations in both phases are performed by the same subroutines. The two-phase nature of the algorithm is reflected by changing the function being minimized from the sum of infeasibilities to the quadratic objective function. The feasibility phase does not perform the standard simplex method (i.e., it does not necessarily find a vertex), except in the LP case when mL≤n. Once any iterate is feasible, all subsequent iterates remain feasible.
E04NFF/E04NFA has been designed to be efficient when used to solve a sequence of related problems – for example, within a sequential quadratic programming method for nonlinearly constrained optimization (e.g., E04UFF/E04UFA or E04WDF). In particular, you may specify an initial working set (the indices of the constraints believed to be satisfied exactly at the solution); see the discussion of the optional parameter Warm Start.
In general, an iterative process is required to solve a quadratic program. (For simplicity, we shall always consider a typical iteration and avoid reference to the index of the iteration.) Each new iterate x- is defined by
x-=x+αp (1)
where the step length α is a non-negative scalar and p is called the search direction.
At each point x, a working set of constraints is defined to be a linearly independent subset of the constraints that are satisfied ‘exactly’ (to within the tolerance defined by the optional parameter Feasibility Tolerance). The working set is the current prediction of the constraints that hold with equality at the solution of a linearly constrained QP problem. The search direction is constructed so that the constraints in the working set remain unaltered for any value of the step length. For a bound constraint in the working set, this property is achieved by setting the corresponding element of the search direction to zero. Thus, the associated variable is fixed, and specification of the working set induces a partition of x into fixed and free variables. During a given iteration, the fixed variables are effectively removed from the problem; since the relevant elements of the search direction are zero, the columns of A corresponding to fixed variables may be ignored.
Let mW denote the number of general constraints in the working set and let nFX denote the number of variables fixed at one of their bounds (mW and nFX are the quantities Lin and Bnd in the monitoring file output from E04NFF/E04NFA; see Section 13). Similarly, let nFR (nFR=n-nFX) denote the number of free variables. At every iteration, the variables are reordered so that the last nFX variables are fixed, with all other relevant vectors and matrices ordered accordingly.

11.2 Definition of Search Direction

Let AFR denote the mW by nFR sub-matrix of general constraints in the working set corresponding to the free variables and let pFR denote the search direction with respect to the free variables only. The general constraints in the working set will be unaltered by any move along p if
AFRpFR=0. (2)
In order to compute pFR, the TQ factorization of AFR is used:
AFRQFR=0 T, (3)
where T is a nonsingular mW by mW upper triangular matrix (i.e., t ij=0 if i>j), and the nonsingular nFR by nFR matrix QFR is the product of orthogonal transformations (see Gill et al. (1984)). If the columns of QFR are partitioned so that
QFR=Z Y,
where Y is nFR by mW, then the nZ nZ=nFR-mW columns of Z form a basis for the null space of AFR. Let nR be an integer such that 0≤nR≤nZ, and let ZR denote a matrix whose nR columns are a subset of the columns of Z. (The integer nR is the quantity Zr in the monitoring output from E04NFF/E04NFA. In many cases, ZR will include all the columns of Z.) The direction pFR will satisfy (2) if
pFR=ZRpR, (4)
where pR is any nR-vector.
Let Q denote the n by n matrix
Q= QFR IFX ,
where IFX is the identity matrix of order nFX. Let HQ and gQ denote the n by n transformed Hessian and transformed gradient
HQ=QT HQ  and  gQ=QT c+Hx
and let the matrix of first nR rows and columns of HQ be denoted by HR and the vector of the first nR elements of gQ be denoted by gR. The quantities HR and gR are known as the reduced Hessian and reduced gradient of f x, respectively. Roughly speaking, gR and HR describe the first and second derivatives of an unconstrained problem for the calculation of pR.
At each iteration, a triangular factorization of HR is available. If HR is positive definite, HR=RT R, where R is the upper triangular Cholesky factor of HR. If HR is not positive definite, HR=RT DR, where D=diag 1,1,…,1,μ, with μ≤0.
The computation is arranged so that the reduced-gradient vector is a multiple of eR, a vector of all zeros except in the last (i.e., nRth) position. This allows the vector pR in (4) to be computed from a single back-substitution
R pR=γ eR (5)
where γ is a scalar that depends on whether or not the reduced Hessian is positive definite at x. In the positive definite case, x+p is the minimizer of the objective function subject to the constraints (bounds and general) in the working set treated as equalities. If HR is not positive definite pR satisfies the conditions
pRT HR pR < 0   and   gRT pR ≤ 0 ,
which allow the objective function to be reduced by any positive step of the form x+αp.

11.3 Main Iteration

If the reduced gradient is zero, x is a constrained stationary point in the subspace defined by Z. During the feasibility phase, the reduced gradient will usually be zero only at a vertex (although it may be zero at non-vertices in the presence of constraint dependencies). During the optimality phase a zero reduced gradient implies that x minimizes the quadratic objective when the constraints in the working set are treated as equalities. At a constrained stationary point, Lagrange multipliers λC and λB for the general and bound constraints are defined from the equations
AFRT λC=gFR  and  λB=gFX-AFXT λC. (6)
Given a positive constant δ of the order of the machine precision, a Lagrange multiplier λj corresponding to an inequality constraint in the working set is said to be optimal if λj≤δ when the associated constraint is at its upper bound, or if λj≥-δ when the associated constraint is at its lower bound. If a multiplier is nonoptimal, the objective function (either the true objective or the sum of infeasibilities) can be reduced by deleting the corresponding constraint (with index Jdel; see Section 13) from the working set.
If optimal multipliers occur during the feasibility phase and the sum of infeasibilities is nonzero, there is no feasible point, and you can force E04NFF/E04NFA to continue until the minimum value of the sum of infeasibilities has been found; see the discussion of the optional parameter Minimum Sum of Infeasibilities. At such a point, the Lagrange multiplier λj corresponding to an inequality constraint in the working set will be such that -1+δ≤λj≤δ when the associated constraint is at its upper bound, and -δ≤λj≤1+δ when the associated constraint is at its lower bound. Lagrange multipliers for equality constraints will satisfy λj≤1+δ.
If the reduced gradient is not zero, Lagrange multipliers need not be computed and the nonzero elements of the search direction p are given by ZRpR (see (4) and (5)). The choice of step length is influenced by the need to maintain feasibility with respect to the satisfied constraints. If HR is positive definite and x+p is feasible, α will be taken as unity. In this case, the reduced gradient at x- will be zero, and Lagrange multipliers are computed. Otherwise, α is set to αM, the step to the ‘nearest’ constraint (with index Jadd; see Section 13), which is added to the working set at the next iteration.
Each change in the working set leads to a simple change to AFR: if the status of a general constraint changes, a row of AFR is altered; if a bound constraint enters or leaves the working set, a column of AFR changes. Explicit representations are recurred of the matrices T, QFR and R; and of vectors QT g, and QT c. The triangular factor R associated with the reduced Hessian is only updated during the optimality phase.
One of the most important features of E04NFF/E04NFA is its control of the conditioning of the working set, whose nearness to linear dependence is estimated by the ratio of the largest to smallest diagonal elements of the TQ factor T (the printed value Cond T; see Section 13). In constructing the initial working set, constraints are excluded that would result in a large value of Cond T.
E04NFF/E04NFA includes a rigorous procedure that prevents the possibility of cycling at a point where the active constraints are nearly linearly dependent (see Gill et al. (1989)). The main feature of the anti-cycling procedure is that the feasibility tolerance is increased slightly at the start of every iteration. This not only allows a positive step to be taken at every iteration, but also provides, whenever possible, a choice of constraints to be added to the working set. Let αM denote the maximum step at which x+αM p does not violate any constraint by more than its feasibility tolerance. All constraints at a distance α (α≤αM) along p from the current point are then viewed as acceptable candidates for inclusion in the working set. The constraint whose normal makes the largest angle with the search direction is added to the working set.

11.4 Choosing the Initial Working Set

At the start of the optimality phase, a positive definite HR can be defined if enough constraints are included in the initial working set. (The matrix with no rows and columns is positive definite by definition, corresponding to the case when AFR contains nFR constraints.) The idea is to include as many general constraints as necessary to ensure that the reduced Hessian is positive definite.
Let HZ denote the matrix of the first nZ rows and columns of the matrix HQ=QT HQ at the beginning of the optimality phase. A partial Cholesky factorization is used to find an upper triangular matrix R that is the factor of the largest positive definite leading sub-matrix of HZ. The use of interchanges during the factorization of HZ tends to maximize the dimension of R. (The condition of R may be controlled using the optional parameter Rank Tolerance.) Let ZR denote the columns of Z corresponding to R, and let Z be partitioned as Z= ZR ZA . A working set for which ZR defines the null space can be obtained by including the rows of ZAT as ‘artificial constraints’. Minimization of the objective function then proceeds within the subspace defined by ZR, as described in Section 11.2.
The artificially augmented working set is given by
A-FR= ZAT AFR , (7)
so that pFR will satisfy AFRpFR=0 and ZAT pFR = 0 . By definition of the TQ factorization, A-FR automatically satisfies the following:
A-FRQFR= ZAT AFR QFR= ZAT AFR ZR ZA Y = 0 T- ,
where
T-= I 0 0 T ,
and hence the TQ factorization of (7) is available trivially from T and QFR without additional expense.
The matrix ZA is not kept fixed, since its role is purely to define an appropriate null space; the TQ factorization can therefore be updated in the normal fashion as the iterations proceed. No work is required to ‘delete’ the artificial constraints associated with ZA when ZRT gFR = 0 , since this simply involves repartitioning QFR. The ‘artificial’ multiplier vector associated with the rows of ZAT is equal to ZAT gFR , and the multipliers corresponding to the rows of the ‘true’ working set are the multipliers that would be obtained if the artificial constraints were not present. If an artificial constraint is ‘deleted’ from the working set, an A appears alongside the entry in the Jdel column of the monitoring file output (see Section 13).
The number of columns in ZA and ZR, the Euclidean norm of ZRT gFR , and the condition estimator of R appear in the monitoring file output as Art, Zr, Norm Gz and Cond Rz respectively (see Section 13).
Under some circumstances, a different type of artificial constraint isused when solving a linear program. Although the algorithm of E04NFF/E04NFA does not usually perform simplex steps (in the traditional sense), there is one exception: a linear program with fewer general constraints than variables (i.e., mL≤n). Use of the simplex method in this situation leads to savings in storage. At the starting point, the ‘natural’ working set (the set of constraints exactly or nearly satisfied at the starting point) is augmented with a suitable number of ‘temporary’ bounds, each of which has the effect of temporarily fixing a variable at its current value. In subsequent iterations, a temporary bound is treated as a standard constraint until it is deleted from the working set, in which case it is never added again. If a temporary bound is ‘deleted’ from the working set, an F (for ‘Fixed’) appears alongside the entry in the Jdel column of the monitoring file output (see Section 13).

12 Optional Parameters

Several optional parameters in E04NFF/E04NFA define choices in the problem specification or the algorithm logic. In order to reduce the number of formal arguments of E04NFF/E04NFA these optional parameters have associated default values that are appropriate for most problems. Therefore, you need only specify those optional parameters whose values are to be different from their default values.
The remainder of this section can be skipped if you wish to use the default values for all optional parameters.
The following is a list of the optional parameters available. A full description of each optional parameter is provided in Section 12.1.
  • Check Frequency
  • Cold Start
  • Crash Tolerance
  • Defaults
  • Expand Frequency
  • Feasibility Phase Iteration Limit
  • Feasibility Tolerance
  • Hessian Rows
  • Infinite Bound Size
  • Infinite Step Size
  • Iteration Limit
  • Iters
  • Itns
  • List
  • Maximum Degrees of Freedom
  • Minimum Sum of Infeasibilities
  • Monitoring File
  • Nolist
  • Optimality Phase Iteration Limit
  • Optimality Tolerance
  • Print Level
  • Problem Type
  • Rank Tolerance
  • Warm Start
Optional parameters may be specified by calling one, or both, of the routines E04NGF/E04NGA and E04NHF/E04NHA before a call to E04NFF/E04NFA.
E04NGF/E04NGA reads options from an external options file, with Begin and End as the first and last lines respectively and each intermediate line defining a single optional parameter. For example,
Begin
  Print Level = 5
End
The call
 CALL E04NGF (IOPTNS, INFORM)
can then be used to read the file on unit IOPTNS. INFORM will be zero on successful exit. E04NGF/E04NGA should be consulted for a full description of this method of supplying optional parameters.
E04NHF/E04NHA can be called to supply options directly, one call being necessary for each optional parameter. For example,
 CALL E04NHF ('Print Level = 5')
E04NHF/E04NHA should be consulted for a full description of this method of supplying optional parameters.
All optional parameters not specified by you are set to their default values. Optional parameters specified by you are unaltered by E04NFF/E04NFA (unless they define invalid values) and so remain in effect for subsequent calls unless altered by you.

12.1 Description of the Optional Parameters

For each option, we give a summary line, a description of the optional parameter and details of constraints.
The summary line contains:
  • the keywords, where the minimum abbreviation of each keyword is underlined (if no characters of an optional qualifier are underlined, the qualifier may be omitted);
  • a parameter value, where the letters a, i and r denote options that take character, integer and real values respectively;
  • the default value, where the symbol ε is a generic notation for machine precision (see X02AJF).
Keywords and character values are case and white space insensitive.
Check Frequency r Default =50
Every ith iteration, a numerical test is made to see if the current solution x satisfies the constraints in the working set. If the largest residual of the constraints in the working set is judged to be too large, the current working set is refactorized and the variables are recomputed to satisfy the constraints more accurately. If i≤0, the default value is used.
Cold Start Default
Warm Start
This option specifies how the initial working set is chosen. With a Cold Start, E04NFF/E04NFA chooses the initial working set based on the values of the variables and constraints at the initial point. Broadly speaking, the initial working set will include equality constraints and bounds or inequality constraints that violate or ‘nearly’ satisfy their bounds (to within Crash Tolerance).
With a Warm Start, you must provide a valid definition of every element of the array ISTATE. E04NFF/E04NFA will override your specification of ISTATE if necessary, so that a poor choice of the working set will not cause a fatal error. For instance, any elements of ISTATE which are set to -2, -1​ or ​4 will be reset to zero, as will any elements which are set to 3 when the corresponding elements of BL and BU are not equal. A warm start will be advantageous if a good estimate of the initial working set is available – for example, when E04NFF/E04NFA is called repeatedly to solve related problems.
Crash Tolerance r Default =0.01
This value is used in conjunction with the optional parameter Cold Start (the default value) when E04NFF/E04NFA selects an initial working set. If 0≤r≤1, the initial working set will include (if possible) bounds or general inequality constraints that lie within r of their bounds. In particular, a constraint of the form ajT x≥l will be included in the initial working set if ajT x-l ≤ r 1+l . If r<0 or r>1, the default value is used.
Defaults
This special keyword may be used to reset all optional parameters to their default values.
Expand Frequency i Default =5
This option is part of an anti-cycling procedure designed to guarantee progress even on highly degenerate problems.
The strategy is to force a positive step at every iteration, at the expense of violating the constraints by a small amount. Suppose that the value of the optional parameter Feasibility Tolerance is δ. Over a period of i iterations, the feasibility tolerance actually used by E04NFF/E04NFA (i.e., the working feasibility tolerance) increases from 0.5 δ to δ (in steps of 0.5 δ/i).
At certain stages the following ‘resetting procedure’ is used to remove constraint infeasibilities. First, all variables whose upper or lower bounds are in the working set are moved exactly onto their bounds. A count is kept of the number of nontrivial adjustments made. If the count is positive, iterative refinement is used to give variables that satisfy the working set to (essentially) machine precision. Finally, the working feasibility tolerance is reinitialized to 0.5 δ.
If a problem requires more than i iterations, the resetting procedure is invoked and a new cycle of i iterations is started with i incremented by 10. (The decision to resume the feasibility phase or optimality phase is based on comparing any constraint infeasibilities with δ.)
The resetting procedure is also invoked when E04NFF/E04NFA reaches an apparently optimal, infeasible or unbounded solution, unless this situation has already occurred twice. If any nontrivial adjustments are made, iterations are continued.
If i≤0, the default value is used. If i≥9999999, no anti-cycling procedure is invoked.
Feasibility Phase Iteration Limit i 1 Default =max 50,5 n+mL
Optimality Phase Iteration Limit i 2 Default =max 50,5 n+mL
For problems of type FP, the scalar i 1 specifies the maximum number of iterations allowed before temination. Setting i 1=0 and Print Level>0 means that the workspace needed will be computed and printed, but no iterations will be performed.
For problems of type LP, the maximum number of iterations allowed before temination is taken as max i 1,i 2. Setting i 1=0, i 2=0 and Print Level>0 means that the workspace needed will be computed and printed, but no iterations will be performed.
For problems of type QP, the scalars i 1 and i 2 specify the maximum number of iterations allowed in the feasibility and optimality phases. Optimality Phase Iteration Limit is equivalent to Iteration Limit. Setting i 1=0 and Print Level>0 means that the workspace needed will be computed and printed, but no iterations will be performed.
If i 1<0 or i 2<0, the default value is used.
Feasibility Tolerance r Default =ε
If r≥ε, r defines the maximum acceptable absolute violation in each constraint at a ‘feasible’ point. For example, if the variables and the coefficients in the general constraints are of order unity, and the latter are correct to about 6 decimal digits, it would be appropriate to specify r as 10-6. If 0≤r<ε, the default value is used.
E04NFF/E04NFA attempts to find a feasible solution before optimizing the objective function. If the sum of infeasibilities cannot be reduced to zero, the optional parameter Minimum Sum of Infeasibilities can be used to find the minimum value of the sum. Let Sinf be the corresponding sum of infeasibilities. If Sinf is quite small, it may be appropriate to raise r by a factor of 10 or 100. Otherwise, some error in the data should be suspected.
Note that a ‘feasible solution’ is a solution that satisfies the current constraints to within the tolerance r.
Hessian Rows i Default =n
Note that this option does not apply to problems of type FP or LP.
This specifies m, the number of rows of the Hessian matrix H. The default value of m is n, the number of variables of the problem.
If the problem is of type QP then m will usually be n, the number of variables. However, a value of m less than n is appropriate for QP3 or QP4 if H is an upper trapezoidal matrix with m rows. Similarly, m may be used to define the dimension of a leading block of nonzeros in the Hessian matrices of QP1 or QP2. In this case the last n-m rows and columns of H are assumed to be zero. In the QP case m should not be greater than n; if it is, the last m-n rows of H are ignored.
If i<0 or i>n, the default value is used.
Infinite Bound Size r Default =1020
If r>0, r defines the ‘infinite’ bound bigbnd in the definition of the problem constraints. Any upper bound greater than or equal to bigbnd will be regarded as +∞ (and similarly any lower bound less than or equal to -bigbnd will be regarded as -∞). If r<0, the default value is used.
Infinite Step Size r Default =max bigbnd,1020
If r>0, r specifies the magnitude of the change in variables that will be considered a step to an unbounded solution. (Note that an unbounded solution can occur only when the Hessian is not positive definite.) If the change in x during an iteration would exceed the value of r then the objective function is considered to be unbounded below in the feasible region. If r≤0, the default value is used.
Iteration Limit i Default =max 50,5 n+mL
Iters
Itns
See optional parameter Feasibility Phase Iteration Limit.
List Default for E04NFF =List
Nolist Default for E04NFA =Nolist
Normally each optional parameter specification is printed as it is supplied. Optional parameter Nolist may be used to suppress the printing and optional parameter List may be used to restore printing.
Maximum Degrees of Freedom i Default =n
Note that this option does not apply to problems of type FP or LP.
This places a limit on the storage allocated for the triangular factor R of the reduced Hessian HR. Ideally, i should be set slightly larger than the value of nR expected at the solution. It need not be larger than mN+1, where mN is the number of variables that appear nonlinearly in the quadratic objective function. For many problems it can be much smaller than mN.
For quadratic problems, a minimizer may lie on any number of constraints, so that nR may vary between 1 and n. The default value of i is therefore the number of variables n. If Hessian Rows m is specified, the default value of i is the same number, m.
Minimum Sum of Infeasibilities a Default =NO
If no feasible point exists for the constraints then this option is used to control whether or not E04NFF/E04NFA will calculate a point that minimizes the constraint violations. If Minimum Sum of Infeasibilities=NO, E04NFF/E04NFA will terminate as soon as it is evident that no feasible point exists for the constraints. The final point will generally not be the point at which the sum of infeasibilities is minimized. If Minimum Sum of Infeasibilities=YES, E04NFF/E04NFA will continue until the sum of infeasibilities is minimized.
Monitoring File i Default =-1
If i>6 and Print Level≥5, monitoring information produced by E04NFF/E04NFA at every iteration is sent to a file with logical unit number i.
If i<0 and/or Print Level<5, no monitoring information is produced.
Optimality Tolerance r Default =ε 0.5
If r≥ε, r defines the tolerance used to determine if the bounds and general constraints have the right ‘sign’ for the solution to be judged to be optimal.
If 0≤r<ε, the default value is used.
Print Level i Default for E04NFF =10
Default for E04NFA =0
The value of i controls the amount of printout produced by E04NFF/E04NFA, as indicated below. A detailed description of the printed output is given in Section 9.2 (summary output at each iteration and the final solution) and Section 13 (monitoring information at each iteration). If i<0, the default value is used.
The following printout is sent to the current advisory message unit (as defined by X04ABF):
i | Output
≥0 0 | No output.
≥0 1 | The final solution only.
≥0 5 | One line of summary output (<80 characters; see Section 9.2) for each iteration (no printout of the final solution).
≥10 | The final solution and one line of summary output for each iteration.
The following printout is sent to the logical unit number by the optional parameter Monitoring File:
i | Output
<5 | No output.
≥5 | One long line of output (>80 characters; see Section 13) for each iteration (no printout of the final solution).
≥20 | At each iteration: the Lagrange multipliers, the variables x, the constraint values Ax and the constraint status (see ISTATE).
≥30 | At each iteration: the diagonal elements of the upper triangular matrix T associated with the TQ factorization (3) (see Section 11.2) of the working set and the diagonal elements of the upper triangular matrix R.
If Print Level≥5 and the unit number defined by the optional parameter Monitoring File is the same as that defined by X04ABF, then the summary output is suppressed.
Problem Type a Default = QP2
This option specifies the type of objective function to be minimized during the optimality phase. The following are the five optional keywords and the dimensions of the arrays that must be specified in order to define the objective function:
LP | H not referenced, CVEC N required;
QP1 | H LDH* symmetric, CVEC not referenced;
QP2 | H LDH* symmetric, CVEC N required;
QP3 | H LDH* upper trapezoidal, CVEC not referenced;
QP4 | H LDH* upper trapezoidal, CVEC N required.
For problems of type FP the objective function is omitted and neither H nor CVEC are referenced.
The following keywords are also acceptable. The minimum abbreviation of each keyword is underlined.
a | Option
Quadratic | QP2
Linear | LP
Feasible | FP
In addition, the keyword QP is equivalent to the default option QP2.
If H=0 (i.e., the objective function is purely linear), the efficiency of E04NFF/E04NFA may be increased by specifying a as LP.
Rank Tolerance r Default =100 ε
Note that this option does not apply to problems of type FP or LP.
This optional parameter enables you to control the condition number of the triangular factor R (see Section 11). If ρi denotes the function ρi=max R 11,R 22,…,R ii, the dimension of R is defined to be smallest index i such that R i+1,i+1≤r ρ i+1. If r≤0, the default value is used.

13 Description of Monitoring Information

This section describes the long line of output (>80 characters) which forms part of the monitoring information produced by E04NFF/E04NFA. (See also the description of the optional parameters Monitoring File and Print Level.) You can control the level of printed output.
To aid interpretation of the printed results the following convention is used for numbering the constraints: indices 1 through n refer to the bounds on the variables and indices n+1 through n+mL refer to the general constraints. When the status of a constraint changes, the index of the constraint is printed, along with the designation L (lower bound), U (upper bound), E (equality), F (temporarily fixed variable) or A (artificial constraint).
When Print Level≥5 and Monitoring File≥0, the following line of output is produced at every iteration on the unit number specified by the Monitoring File. In all cases the values of the quantities printed are those in effect on completion of the given iteration.
Itn | is the iteration count.
Jdel | is the index of the constraint deleted from the working set. If Jdel is zero, no constraint was deleted.
Jadd | is the index of the constraint added to the working set. If Jadd is zero, no constraint was added.
Step | is the step taken along the computed search direction. If a constraint is added during the current iteration, Step will be the step to the nearest constraint. When the problem is of type LP, the step can be greater than one during the optimality phase.
Ninf | is the number of violated constraints (infeasibilities). This will be zero during the optimality phase.
Sinf/Objective | is the value of the current objective function. If x is not feasible, Sinf gives a weighted sum of the magnitudes of constraint violations. If x is feasible, Objective is the value of the objective function of (1). The output line for the final iteration of the feasibility phase (i.e., the first iteration for which Ninf is zero) will give the value of the true objective at the first feasible point. During the optimality phase the value of the objective function will be nonincreasing. During the feasibility phase the number of constraint infeasibilities will not increase until either a feasible point is found or the optimality of the multipliers implies that no feasible point exists. Once optimal multipliers are obtained the number of infeasibilities can increase, but the sum of infeasibilities will either remain constant or be reduced until the minimum sum of infeasibilities is found.
Bnd | is the number of simple bound constraints in the current working set.
Lin | is the number of general linear constraints in the current working set.
Art | is the number of artificial constraints in the working set, i.e., the number of columns of ZA (see Section 11.4).
Zr | is the number of columns of Z 1 (see Section 11.2). Zr is the dimension of the subspace in which the objective function is currently being minimized. The value of Zr is the number of variables minus the number of constraints in the working set; i.e., Zr=n-Bnd+Lin+Art. The value of nZ, the number of columns of Z (see Section 11.2) can be calculated as nZ=n-Bnd+Lin. A zero value of nZ implies that x lies at a vertex of the feasible region.
Norm Gz | is ZRT gFR , the Euclidean norm of the reduced gradient with respect to ZR. During the optimality phase, this norm will be approximately zero after a unit step.
NOpt | is the number of nonoptimal Lagrange multipliers at the current point. NOpt is not printed if the current x is infeasible or no multipliers have been calculated. At a minimizer, NOpt will be zero.
Min Lm | is the value of the Lagrange multiplier associated with the deleted constraint. If Min Lm is negative, a lower bound constraint has been deleted, if Min Lm is positive, an upper bound constraint has been deleted. If no multipliers are calculated during a given iteration Min Lm will be zero.
Cond T | is a lower bound on the condition number of the working set.
Cond Rz | is a lower bound on the condition number of the triangular factor R (the Cholesky factor of the current reduced Hessian; see Section 11.2). If the problem is specified to be of type LP then Cond Rz is not printed.
Rzz | is the last diagonal element μ of the matrix D associated with the RT DR factorization of the reduced Hessian HR (see Section 11.2). Rzz is only printed if HR is not positive definite (in which case μ≠1). If the printed value of Rzz is small in absolute value then HR is approximately singular. A negative value of Rzz implies that the objective function has negative curvature on the current working set.
E04 Chapter Contents
E04 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


E04NGF/E04NGA : NAG Library, Mark 26

E04 Chapter Contents
E04 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

E04NGF/E04NGA

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
▸▿ 2 Specification
2.1 Specification for E04NGF
2.2 Specification for E04NGA
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

To supply optional parameters to E04NFF/E04NFA from an external file. More precisely, E04NGF must be used to supply optional parameters to E04NFF and E04NGA must be used to supply optional parameters to E04NFA.
E04NGA is a version of E04NGF that has additional arguments in order to make it safe for use in multithreaded applications (see Section 5). The initialization routine E04WBF must have been called before calling E04NGA.

2 Specification

2.1 Specification for E04NGF

SUBROUTINE E04NGF ( IOPTNS, INFORM)
INTEGER IOPTNS, INFORM

2.2 Specification for E04NGA

SUBROUTINE E04NGA ( IOPTNS, LWSAV, IWSAV, RWSAV, INFORM)
INTEGER | IOPTNS, IWSAV(610), INFORM
REAL (KIND=nag_wp) | RWSAV(475)
LOGICAL | LWSAV(120)

3 Description

E04NGF/E04NGA may be used to supply values for optional parameters to E04NFF/E04NFA. E04NGF/E04NGA reads an external file and each line of the file defines a single optional parameter. It is only necessary to supply values for those arguments whose values are to be different from their default values.
Each optional parameter is defined by a single character string, of up to 72 characters, consisting of one or more items. The items associated with a given option must be separated by spaces, or equals signs =. Alphabetic characters may be upper or lower case. The string
Print Level = 1
is an example of a string used to set an optional parameter. For each option the string contains one or more of the following items:
– | a mandatory keyword;
– | a phrase that qualifies the keyword;
– | a number that specifies an integer or real value. Such numbers may be up to 40 contiguous characters in Fortran's I, F, E or D formats, terminated by a space if this is not the last item on the line.
Blank strings and comments are ignored. A comment begins with an asterisk (*) and all subsequent characters in the string are regarded as part of the comment.
The file containing the options must start with Begin and must finish with End. An example of a valid options file is:
Begin * Example options file
   Print level = 5
End
For E04NGF each line of the file is normally printed as it is read, on the current advisory message unit (see X04ABF), but printing may be suppressed using the keyword Nolist. To suppress printing of Begin, Nolist must be the first option supplied as in the file:
Begin
   Nolist
   Print level = 5
End
Printing will automatically be turned on again after a call to E04NFF or E04NGF and may be turned on again at any time using the keyword List.
For E04NGA printing is turned off by default, but may be turned on at any time using the keyword List.
Optional parameter settings are preserved following a call to E04NFF/E04NFA and so the keyword Defaults is provided to allow you to reset all the optional parameters to their default values before a subsequent call to E04NFF/E04NFA.
A complete list of optional parameters, their abbreviations, synonyms and default values is given in Section 12 in E04NFF/E04NFA.

4 References

None.

5 Arguments

1:   IOPTNS – INTEGERInput
On entry: the unit number of the options file to be read.
Constraint: 0≤IOPTNS≤99.
2:   INFORM – INTEGEROutput
Note: for E04NGA, INFORM does not occur in this position in the argument list. See the additional arguments described below.
On exit: contains zero if the options file has been successfully read and a value>0 otherwise (see Section 6).
Note: the following are additional arguments for specific use with E04NGA. Users of E04NGF therefore need not read the remainder of this description.
2:   LWSAV 120 – LOGICAL arrayCommunication Array
3:   IWSAV 610 – INTEGER arrayCommunication Array
4:   RWSAV 475 – REAL (KIND=nag_wp) arrayCommunication Array
The arrays LWSAV, IWSAV and RWSAV must not be altered between calls to any of the routines E04NGA, E04NFA, E04NHA or E04WBF.
5:   INFORM – INTEGEROutput
Note: see the argument description for INFORM above.

6 Error Indicators and Warnings

INFORM=1
IOPTNS is not in the range 0,99.
INFORM=2
Begin was found, but end-of-file was found before End was found.
INFORM=3
end-of-file was found before Begin was found.
INFORM=4
Not used.
INFORM=5
One or more lines of the options file is invalid. Check that all keywords are neither ambiguous nor misspelt.

7 Accuracy

Not applicable.

8 Parallelism and Performance

E04NGF/E04NGA is not threaded in any implementation.

9 Further Comments

E04NHF/E04NHA may also be used to supply optional parameters to E04NFF/E04NFA.

10 Example

This example solves the same problem as the example for E04NFF/E04NFA, but in addition illustrates the use of E04NGF/E04NGA and E04NHF/E04NHA to set optional parameters for E04NFF/E04NFA.
In this example the options file read by E04NGF/E04NGA is appended to the data file for the program (see Section 10.2). It would usually be more convenient in practice to keep the data file and the options file separate.

10.1 Program Text

Note: the following programs illustrate the use of E04NGF and E04NGA.

Program Text (e04ngfe.f90)

Program Text (e04ngae.f90)

10.2 Program Data

Program Options (e04ngfe.opt)

Program Options (e04ngae.opt)

Program Data (e04ngfe.d)

Program Data (e04ngae.d)

10.3 Program Results

Program Results (e04ngfe.r)

Program Results (e04ngae.r)

E04 Chapter Contents
E04 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


E04NHF/E04NHA : NAG Library, Mark 26

E04 Chapter Contents
E04 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

E04NHF/E04NHA

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
▸▿ 2 Specification
2.1 Specification for E04NHF
2.2 Specification for E04NHA
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
10 Example

1 Purpose

To supply individual optional parameters to E04NFF/E04NFA. More precisely, E04NHF must be used to supply optional parameters to E04NFF and E04NHA must be used to supply optional parameters to E04NFA.
E04NHA is a version of E04NHF that has additional arguments in order to make it safe for use in multithreaded applications (see Section 5). The initialization routine E04WBF must have been called before calling E04NHA.

2 Specification

2.1 Specification for E04NHF

SUBROUTINE E04NHF ( STR)
CHARACTER(*) STR

2.2 Specification for E04NHA

SUBROUTINE E04NHA ( STR, LWSAV, IWSAV, RWSAV, INFORM)
INTEGER | IWSAV(610), INFORM
REAL (KIND=nag_wp) | RWSAV(475)
LOGICAL | LWSAV(120)
CHARACTER(*) | STR

3 Description

E04NHF/E04NHA may be used to supply values for optional parameters to E04NFF/E04NFA. It is only necessary to call E04NHF/E04NHA for those arguments whose values are to be different from their default values. One call to E04NHF/E04NHA sets one argument value.
Each optional parameter is defined by a single character string, of up to 72 characters, consisting of one or more items. The items associated with a given option must be separated by spaces, or equals signs =. Alphabetic characters may be upper or lower case. The string
Print Level = 1
is an example of a string used to set an optional parameter. For each option the string contains one or more of the following items:
– | a mandatory keyword;
– | a phrase that qualifies the keyword;
– | a number that specifies an integer or real value. Such numbers may be up to 40 contiguous characters in Fortran's I, F, E or D formats, terminated by a space if this is not the last item on the line.
Blank strings and comments are ignored. A comment begins with an asterisk (*) and all subsequent characters in the string are regarded as part of the comment.
For E04NHF, each user-specified option is normally printed as it is defined, on the current advisory message unit (see X04ABF), but this printing may be suppressed using the keyword Nolist. Thus the statement
 CALL E04NHF ('Nolist')
suppresses printing of this and subsequent options. Printing will automatically be turned on again after a call to E04NFF and may be turned on again at any time using the keyword List.
For E04NHA printing is turned off by default, but may be turned on at any time using the keyword List.
Optional parameter settings are preserved following a call to E04NFF/E04NFA and so the keyword Defaults is provided to allow you to reset all the optional parameters to their default values before a subsequent call to E04NFF/E04NFA.
A complete list of optional parameters, their abbreviations, synonyms and default values is given in Section 12 in E04NFF/E04NFA.

4 References

None.

5 Arguments

1:   STR – CHARACTER(*)Input
On entry: a single valid option string (as described in Section 3 and in Section 12 in E04NFF/E04NFA).
Note: the following are additional arguments for specific use with E04NHA. Users of E04NHF therefore need not read the remainder of this description.
2:   LWSAV 120 – LOGICAL arrayCommunication Array
3:   IWSAV 610 – INTEGER arrayCommunication Array
4:   RWSAV 475 – REAL (KIND=nag_wp) arrayCommunication Array
The arrays LWSAV, IWSAV and RWSAV must not be altered between calls to any of the routines E04NHA, E04NKA, E04NLA or E04WBF.
5:   INFORM – INTEGEROutput
On exit: contains zero if a valid option string has been supplied and a value>0 otherwise (see Section 6).

6 Error Indicators and Warnings

INFORM=5
The supplied option is invalid. Check that the keywords are neither ambiguous nor misspelt.

7 Accuracy

Not applicable.

8 Parallelism and Performance

E04NHF/E04NHA is not threaded in any implementation.

9 Further Comments

E04NGF/E04NGA may also be used to supply optional parameters to E04NFF/E04NFA.

10 Example

See Section 10 in E04NGF/E04NGA.
E04 Chapter Contents
E04 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


E04NKF/E04NKA : NAG Library, Mark 26

E04 Chapter Contents
E04 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

E04NKF/E04NKA

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.
Note: this routine uses optional parameters to define choices in the problem specification and in the details of the algorithm. If you wish to use default settings for all of the optional parameters, you need only read Sections 1 to 10 of this document. If, however, you wish to reset some or all of the settings please refer to Section 11 for a detailed description of the algorithm, to Section 12 for a detailed description of the specification of the optional parameters and to Section 13 for a detailed description of the monitoring information produced by the routine.

▸▿ Contents

1 Purpose
▸▿ 2 Specification
2.1 Specification for E04NKF
2.2 Specification for E04NKA
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
▸▿ 9 Further Comments
9.1 Description of the Printed Output
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results
▸▿ 11 Algorithmic Details
11.1 Overview
11.2 Definition of the Working Set and Search Direction
11.3 Main Iteration
11.4 Miscellaneous
▸▿ 12 Optional Parameters
12.1 Description of the Optional Parameters
13 Description of Monitoring Information

1 Purpose

E04NKF/E04NKA solves sparse linear programming or convex quadratic programming problems.
E04NKA is a version of E04NKF that has additional arguments in order to make it safe for use in multithreaded applications (see Section 5). The initialization routine E04WBF must have been called before calling E04NKA.

2 Specification

2.1 Specification for E04NKF

SUBROUTINE E04NKF ( N, M, NNZ, IOBJ, NCOLH, QPHX, A, HA, KA, BL, BU, START, NAMES, NNAME, CRNAME, NS, XS, ISTATE, MINIZ, MINZ, NINF, SINF, OBJ, CLAMDA, IZ, LENIZ, Z, LENZ, IFAIL)
INTEGER | N, M, NNZ, IOBJ, NCOLH, HA(NNZ), KA(N+1), NNAME, NS, ISTATE(N+M), MINIZ, MINZ, NINF, IZ(LENIZ), LENIZ, LENZ, IFAIL
REAL (KIND=nag_wp) | A(NNZ), BL(N+M), BU(N+M), XS(N+M), SINF, OBJ, CLAMDA(N+M), Z(LENZ)
CHARACTER(1) | START
CHARACTER(8) | NAMES(5), CRNAME(NNAME)
EXTERNAL | QPHX

2.2 Specification for E04NKA

SUBROUTINE E04NKA ( N, M, NNZ, IOBJ, NCOLH, QPHX, A, HA, KA, BL, BU, START, NAMES, NNAME, CRNAME, NS, XS, ISTATE, MINIZ, MINZ, NINF, SINF, OBJ, CLAMDA, IZ, LENIZ, Z, LENZ, IUSER, RUSER, LWSAV, IWSAV, RWSAV, IFAIL)
INTEGER | N, M, NNZ, IOBJ, NCOLH, HA(NNZ), KA(N+1), NNAME, NS, ISTATE(N+M), MINIZ, MINZ, NINF, IZ(LENIZ), LENIZ, LENZ, IUSER(*), IWSAV(380), IFAIL
REAL (KIND=nag_wp) | A(NNZ), BL(N+M), BU(N+M), XS(N+M), SINF, OBJ, CLAMDA(N+M), Z(LENZ), RUSER(*), RWSAV(285)
LOGICAL | LWSAV(20)
CHARACTER(1) | START
CHARACTER(8) | NAMES(5), CRNAME(NNAME)
EXTERNAL | QPHX
Before calling E04NKA, or either of the option setting routines E04NLA or E04NMA, E04WBF must be called. The specification for E04WBF is:
SUBROUTINE E04WBF ( RNAME, CWSAV, LCWSAV, LWSAV, LLWSAV, IWSAV, LIWSAV, RWSAV, LRWSAV, IFAIL)
INTEGER | LCWSAV, LLWSAV, IWSAV(LIWSAV), LIWSAV, LRWSAV, IFAIL
REAL (KIND=nag_wp) | RWSAV(LRWSAV)
LOGICAL | LWSAV(LLWSAV)
CHARACTER(*) | RNAME
CHARACTER(80) | CWSAV(LCWSAV)
E04WBF should be called with RNAME='E04NKA'. LCWSAV, LLWSAV, LIWSAV and LRWSAV, the declared lengths of CWSAV, LWSAV, IWSAV and RWSAV respectively, must satisfy:
  • LCWSAV≥1
  • LLWSAV≥20
  • LIWSAV≥380
  • LRWSAV≥285
The contents of the arrays CWSAV, LWSAV, IWSAV and RWSAV must not be altered between calling routines E04NKA, E04NLA, E04NMA and E04WBF.

3 Description

E04NKF/E04NKA is designed to solve a class of quadratic programming problems that are assumed to be stated in the following general form:
minimize x∈Rn f x   subject to   l≤ x Ax ≤u, (1)
where x is a set of variables, A is an m by n matrix and the objective function f x may be specified in a variety of ways depending upon the particular problem to be solved. The optional parameter Maximize may be used to specify an alternative problem in which f x is maximized. The possible forms for f x are listed in Table 1, in which the prefixes FP, LP and QP stand for ‘feasible point’, ‘linear programming’ and ‘quadratic programming’ respectively, c is an n-element vector and H is the n by n second-derivative matrix ∇2 f x (the Hessian matrix).
Problem type | Objective function f x | Hessian matrix H
FP | Not applicable | Not applicable
LP | cT x | Not applicable
QP | cT x+12 xT Hx | Symmetric positive semidefinite
Table 1
For LP and QP problems, the unique global minimum value of f x is found. For FP problems, f x is omitted and the routine attempts to find a feasible point for the set of constraints. For QP problems, you must also provide a subroutine that computes Hx for any given vector x. (H need not be stored explicitly.) If H is the zero matrix, the routine will still solve the resulting LP problem; however, this can be accomplished more efficiently by setting NCOLH=0 (see Section 5).
The defining feature of a convex QP problem is that the matrix H must be positive semidefinite, i.e., it must satisfy xT Hx≥0 for all x. Otherwise, f x is said to be nonconvex and it may be more appropriate to call E04UGF/E04UGA instead.
E04NKF/E04NKA is intended to solve large-scale linear and quadratic programming problems in which the constraint matrix A is sparse (i.e., when the number of zero elements is sufficiently large that it is worthwhile using algorithms which avoid computations and storage involving zero elements). The routine also takes advantage of sparsity in c. (Sparsity in H can be exploited in the subroutine that computes Hx.) For problems in which A can be treated as a dense matrix, it is usually more efficient to use E04MFF/E04MFA, E04NCF/E04NCA or E04NFF/E04NFA.
The upper and lower bounds on the m elements of Ax are said to define the general constraints of the problem. Internally, E04NKF/E04NKA converts the general constraints to equalities by introducing a set of slack variables s, where s=s 1,s 2,…,sm T. For example, the linear constraint 5≤2 x 1+3 x 2≤+∞ is replaced by 2 x 1+3 x 2-s 1=0, together with the bounded slack 5≤s 1≤+∞. The problem defined by (1) can therefore be re-written in the following equivalent form:
minimize x∈Rn,s∈Rm f x   subject to   Ax-s=0,  l≤ x s ≤u.
Since the slack variables s are subject to the same upper and lower bounds as the elements of Ax, the bounds on Ax and x can simply be thought of as bounds on the combined vector x,s. (In order to indicate their special role in QP problems, the original variables x are sometimes known as ‘column variables’, and the slack variables s are known as ‘row variables’.)
Each LP or QP problem is solved using an active-set method. This is an iterative procedure with two phases: a feasibility phase, in which the sum of infeasibilities is minimized to find a feasible point; and an optimality phase, in which f x is minimized by constructing a sequence of iterations that lies within the feasible region.
A constraint is said to be active or binding at x if the associated element of either x or Ax is equal to one of its upper or lower bounds. Since an active constraint in Ax has its associated slack variable at a bound, the status of both simple and general upper and lower bounds can be conveniently described in terms of the status of the variables x,s. A variable is said to be nonbasic if it is temporarily fixed at its upper or lower bound. It follows that regarding a general constraint as being active is equivalent to thinking of its associated slack as being nonbasic.
At each iteration of an active-set method, the constraints Ax-s=0 are (conceptually) partitioned into the form
B xB+S xS+N xN=0,
where xN consists of the nonbasic elements of x,s and the basis matrix B is square and nonsingular. The elements of xB and xS are called the basic and superbasic variables respectively; with xN they are a permutation of the elements of x and s. At a QP solution, the basic and superbasic variables will lie somewhere between their upper or lower bounds, while the nonbasic variables will be equal to one of their bounds. At each iteration, xS is regarded as a set of independent variables that are free to move in any desired direction, namely one that will improve the value of the objective function (or sum of infeasibilities). The basic variables are then adjusted in order to ensure that x,s continues to satisfy Ax-s=0. The number of superbasic variables (nS say) therefore indicates the number of degrees of freedom remaining after the constraints have been satisfied. In broad terms, nS is a measure of how nonlinear the problem is. In particular, nS will always be zero for FP and LP problems.
If it appears that no improvement can be made with the current definition of B, S and N, a nonbasic variable is selected to be added to S, and the process is repeated with the value of nS increased by one. At all stages, if a basic or superbasic variable encounters one of its bounds, the variable is made nonbasic and the value of nS is decreased by one.
Associated with each of the m equality constraints Ax-s=0 is a dual variable πi. Similarly, each variable in x,s has an associated reduced gradient dj (also known as a reduced cost). The reduced gradients for the variables x are the quantities g-AT π, where g is the gradient of the QP objective function; and the reduced gradients for the slack variables s are the dual variables π. The QP subproblem is optimal if dj≥0 for all nonbasic variables at their lower bounds, dj≤0 for all nonbasic variables at their upper bounds and dj=0 for all superbasic variables. In practice, an approximate QP solution is found by slightly relaxing these conditions on dj (see the description of the optional parameter Optimality Tolerance).
The process of computing and comparing reduced gradients is known as pricing (a term first introduced in the context of the simplex method for linear programming). To ‘price’ a nonbasic variable xj means that the reduced gradient dj associated with the relevant active upper or lower bound on xj is computed via the formula dj=gj-aT π, where aj is the jth column of A -I . (The variable selected by such a process and the corresponding value of dj (i.e., its reduced gradient) are the quantities +S and dj in the monitoring file output; see Section 13.) If A has significantly more columns than rows (i.e., n≫m), pricing can be computationally expensive. In this case, a strategy known as partial pricing can be used to compute and compare only a subset of the dj's.
E04NKF/E04NKA is based on SQOPT, which is part of the SNOPT package described in Gill et al. (2002), which in turn utilizes routines from the MINOS package (see Murtagh and Saunders (1995)). It uses stable numerical methods throughout and includes a reliable basis package (for maintaining sparse LU factors of the basis matrix B), a practical anti-degeneracy procedure, efficient handling of linear constraints and bounds on the variables (by an active-set strategy), as well as automatic scaling of the constraints. Further details can be found in Section 11.

4 References

Fourer R (1982) Solving staircase linear programs by the simplex method Math. Programming 23 274–313
Gill P E and Murray W (1978) Numerically stable methods for quadratic programming Math. Programming 14 349–372
Gill P E, Murray W and Saunders M A (2002) SNOPT: An SQP Algorithm for Large-scale Constrained Optimization 12 979–1006 SIAM J. Optim.
Gill P E, Murray W, Saunders M A and Wright M H (1987) Maintaining LU factors of a general sparse matrix Linear Algebra and its Applics. 88/89 239–270
Gill P E, Murray W, Saunders M A and Wright M H (1989) A practical anti-cycling procedure for linearly constrained optimization Math. Programming 45 437–474
Gill P E, Murray W, Saunders M A and Wright M H (1991) Inertia-controlling methods for general quadratic programming SIAM Rev. 33 1–36
Hall J A J and McKinnon K I M (1996) The simplest examples where the simplex method cycles and conditions where EXPAND fails to prevent cycling Report MS 96–100 Department of Mathematics and Statistics, University of Edinburgh
Murtagh B A and Saunders M A (1995) MINOS 5.4 users' guide Report SOL 83-20R Department of Operations Research, Stanford University

5 Arguments

1:   N – INTEGERInput
On entry: n, the number of variables (excluding slacks). This is the number of columns in the linear constraint matrix A.
Constraint: N≥1.
2:   M – INTEGERInput
On entry: m, the number of general linear constraints (or slacks). This is the number of rows in A, including the free row (if any; see IOBJ).
Constraint: M≥1.
3:   NNZ – INTEGERInput
On entry: the number of nonzero elements in A.
Constraint: 1≤NNZ≤N×M.
4:   IOBJ – INTEGERInput
On entry: if IOBJ>0, row IOBJ of A is a free row containing the nonzero elements of the vector c appearing in the linear objective term cT x.
If IOBJ=0, there is no free row, i.e., the problem is either an FP problem (in which case IOBJ must be set to zero), or a QP problem with c=0.
Constraint: 0≤IOBJ≤M.
5:   NCOLH – INTEGERInput
On entry: nH, the number of leading nonzero columns of the Hessian matrix H. For FP and LP problems, NCOLH must be set to zero.
Constraint: 0≤NCOLH≤N.
6:   QPHX – SUBROUTINE, supplied by the NAG Library or the user.External Procedure
For QP problems, you must supply a version of QPHX to compute the matrix product Hx. If H has zero rows and columns, it is most efficient to order the variables x= yz T so that
Hx= H 10 00 y z = H 1 y 0 ,
where the nonlinear variables y appear first as shown. For FP and LP problems, QPHX will never be called by E04NKF/E04NKA and hence QPHX may be the dummy routine E04NKU/E54NKU.
The specification of QPHX for E04NKF is:
SUBROUTINE QPHX ( NSTATE, NCOLH, X, HX)
INTEGER | NSTATE, NCOLH
REAL (KIND=nag_wp) | X(NCOLH), HX(NCOLH)
The specification of QPHX for E04NKA is:
SUBROUTINE QPHX ( NSTATE, NCOLH, X, HX, IUSER, RUSER)
INTEGER | NSTATE, NCOLH, IUSER(*)
REAL (KIND=nag_wp) | X(NCOLH), HX(NCOLH), RUSER(*)
1:   NSTATE – INTEGERInput
On entry: if NSTATE=1, E04NKF/E04NKA is calling QPHX for the first time. This argument setting allows you to save computation time if certain data must be read or calculated only once.
If NSTATE≥2, E04NKF/E04NKA is calling QPHX for the last time. This argument setting allows you to perform some additional computation on the final solution. In general, the last call to QPHX is made with NSTATE=2+IFAIL (see Section 6).
Otherwise, NSTATE=0.
2:   NCOLH – INTEGERInput
On entry: this is the same argument NCOLH as supplied to E04NKF/E04NKA.
3:   X NCOLH – REAL (KIND=nag_wp) arrayInput
On entry: the first NCOLH elements of the vector x.
4:   HX NCOLH – REAL (KIND=nag_wp) arrayOutput
On exit: the product Hx.
Note: the following are additional arguments for specific use with E04NKA. Users of E04NKF therefore need not read the remainder of this description.
5:   IUSER* – INTEGER arrayUser Workspace
6:   RUSER* – REAL (KIND=nag_wp) arrayUser Workspace
QPHX is called with the arguments IUSER and RUSER as supplied to E04NKF/E04NKA. You are free to use the arrays IUSER and RUSER to supply information to QPHX as an alternative to using COMMON global variables.
QPHX must either be a module subprogram USEd by, or declared as EXTERNAL in, the (sub)program from which E04NKF/E04NKA is called. Arguments denoted as Input must not be changed by this procedure.
7:   A NNZ – REAL (KIND=nag_wp) arrayInput
On entry: the nonzero elements of A, ordered by increasing column index. Note that elements with the same row and column indices are not allowed.
8:   HA NNZ – INTEGER arrayInput
On entry: HA i must contain the row index of the nonzero element stored in A i, for i=1,2,…,NNZ. Note that the row indices for a column may be supplied in any order.
Constraint: 1≤HA i≤M, for i=1,2,…,NNZ.
9:   KA N+1 – INTEGER arrayInput
On entry: KA j must contain the index in A of the start of the jth column, for j=1,2,…,N. KA N+1 must be set to NNZ+1. To specify the jth column as empty, set KA j=KA j+1. As a consequence KA 1 is always 1.
Constraints:
  • KA 1=1;
  • KA j≥1, for j=2,3,…,N;
  • KA N+1=NNZ+1;
  • 0≤KA j+1-KA j≤M, for j=1,2,…,N.
10:   BL N+M – REAL (KIND=nag_wp) arrayInput
On entry: l, the lower bounds for all the variables and general constraints, in the following order. The first N elements of BL must contain the bounds on the variables x, and the next M elements the bounds for the general linear constraints Ax (or slacks s) and the free row (if any). To specify a nonexistent lower bound (i.e., lj=-∞), set BL j≤-bigbnd, where bigbnd is the value of the optional parameter Infinite Bound Size. To specify the jth constraint as an equality, set BL j=BU j=β, say, where β<bigbnd. Note that the lower bound corresponding to the free row must be set to -∞ and stored in BL N+IOBJ.
Constraint: if IOBJ>0, BL N+IOBJ≤-bigbnd
(See also the description for BU.)
11:   BU N+M – REAL (KIND=nag_wp) arrayInput
On entry: u, the upper bounds for all the variables and general constraints, in the following order. The first N elements of BU must contain the bounds on the variables x, and the next M elements the bounds for the general linear constraints Ax (or slacks s) and the free row (if any). To specify a nonexistent upper bound (i.e., uj=+∞), set BU j≥bigbnd. Note that the upper bound corresponding to the free row must be set to +∞ and stored in BU N+IOBJ.
Constraints:
  • if IOBJ>0, BU N+IOBJ≥bigbnd;
  • BL j≤BU j, for j=1,2,…,N+M;
  • if BL j=BU j=β, β<bigbnd.
12:   START – CHARACTER(1)Input
On entry: indicates how a starting basis is to be obtained.
START='C'
An internal Crash procedure will be used to choose an initial basis matrix B.
START='W'
A basis is already defined in ISTATE (probably from a previous call).
Constraint: START='C' or 'W'.
13:   NAMES 5 – CHARACTER(8) arrayInput
On entry: a set of names associated with the so-called MPSX form of the problem, as follows:
NAMES 1
Must contain the name for the problem (or be blank).
NAMES 2
Must contain the name for the free row (or be blank).
NAMES 3
Must contain the name for the constraint right-hand side (or be blank).
NAMES 4
Must contain the name for the ranges (or be blank).
NAMES 5
Must contain the name for the bounds (or be blank).
(These names are used in the monitoring file output; see Section 13.)
14:   NNAME – INTEGERInput
On entry: the number of column (i.e., variable) and row names supplied in CRNAME.
NNAME=1
There are no names. Default names will be used in the printed output.
NNAME=N+M
All names must be supplied.
Constraint: NNAME=1 or N+M.
15:   CRNAME NNAME – CHARACTER(8) arrayInput
On entry: the optional column and row names, respectively.
If NNAME=1, CRNAME is not referenced and the printed output will use default names for the columns and rows.
If NNAME=N+M, the first N elements must contain the names for the columns and the next M elements must contain the names for the rows. Note that the name for the free row (if any) must be stored in CRNAME N+IOBJ.
16:   NS – INTEGERInput/Output
On entry: nS, the number of superbasics. For QP problems, NS need not be specified if START='C', but must retain its value from a previous call when START='W'. For FP and LP problems, NS need not be initialized.
On exit: the final number of superbasics. This will be zero for FP and LP problems.
17:   XS N+M – REAL (KIND=nag_wp) arrayInput/Output
On entry: the initial values of the variables and slacks x,s. (See the description for ISTATE.)
On exit: the final values of the variables and slacks x,s.
18:   ISTATE N+M – INTEGER arrayInput/Output
On entry: if START='C', the first N elements of ISTATE and XS must specify the initial states and values, respectively, of the variables x. (The slacks s need not be initialized.) An internal Crash procedure is then used to select an initial basis matrix B. The initial basis matrix will be triangular (neglecting certain small elements in each column). It is chosen from various rows and columns of A -I . Possible values for ISTATE j are as follows:
ISTATE j | State of XS j during Crash procedure
0 or 1 | Eligible for the basis
2 | Ignored
3 | Eligible for the basis (given preference over 0 or 1)
4 or 5 | Ignored
If nothing special is known about the problem, or there is no wish to provide special information, you may set ISTATE j=0 and XS j=0.0, for j=1,2,…,N. All variables will then be eligible for the initial basis. Less trivially, to say that the jth variable will probably be equal to one of its bounds, set ISTATE j=4 and XS j=BL j or ISTATE j=5 and XS j=BU j as appropriate.
Following the Crash procedure, variables for which ISTATE j=2 are made superbasic. Other variables not selected for the basis are then made nonbasic at the value XS j if BL j≤XS j≤BU j, or at the value BL j or BU j closest to XS j.
If START='W', ISTATE and XS must specify the initial states and values, respectively, of the variables and slacks x,s. If E04NKF/E04NKA has been called previously with the same values of N and M, ISTATE already contains satisfactory information.
Constraints:
  • if START='C', 0≤ISTATE j≤5, for j=1,2,…,N;
  • if START='W', 0≤ISTATE j≤3, for j=1,2,…,N+M.
On exit: the final states of the variables and slacks x,s. The significance of each possible value of ISTATE j is as follows:
ISTATE j | State of variable j | Normal value of XS j
0 | Nonbasic | BL j
1 | Nonbasic | BU j
2 | Superbasic | Between BL j and BU j
3 | Basic | Between BL j and BU j
If NINF=0, basic and superbasic variables may be outside their bounds by as much as the value of the optional parameter Feasibility Tolerance. Note that unless the Scale Option=0 is specified, the optional parameter Feasibility Tolerance applies to the variables of the scaled problem. In this case, the variables of the original problem may be as much as 0.1 outside their bounds, but this is unlikely unless the problem is very badly scaled.
Very occasionally some nonbasic variables may be outside their bounds by as much as the optional parameter Feasibility Tolerance, and there may be some nonbasic variables for which XS j lies strictly between its bounds.
If NINF>0, some basic and superbasic variables may be outside their bounds by an arbitrary amount (bounded by SINF if Scale Option=0).
19:   MINIZ – INTEGEROutput
On exit: the minimum value of LENIZ required to start solving the problem. If IFAIL=12, E04NKF/E04NKA may be called again with LENIZ suitably larger than MINIZ. (The bigger the better, since it is not certain how much workspace the basis factors need.)
20:   MINZ – INTEGEROutput
On exit: the minimum value of LENZ required to start solving the problem. If IFAIL=13, E04NKF/E04NKA may be called again with LENZ suitably larger than MINZ. (The bigger the better, since it is not certain how much workspace the basis factors need.)
21:   NINF – INTEGEROutput
On exit: the number of infeasibilities. This will be zero if IFAIL=0 or 1.
22:   SINF – REAL (KIND=nag_wp)Output
On exit: the sum of infeasibilities. This will be zero if NINF=0. (Note that E04NKF/E04NKA does not attempt to compute the minimum value of SINF if IFAIL=3.)
23:   OBJ – REAL (KIND=nag_wp)Output
On exit: the value of the objective function.
If NINF=0, OBJ includes the quadratic objective term 12 xT Hx (if any).
If NINF>0, OBJ is just the linear objective term cT x (if any).
For FP problems, OBJ is set to zero.
24:   CLAMDA N+M – REAL (KIND=nag_wp) arrayOutput
On exit: a set of Lagrange multipliers for the bounds on the variables and the general constraints. More precisely, the first N elements contain the multipliers (reduced costs) for the bounds on the variables, and the next M elements contain the multipliers (shadow prices) for the general linear constraints.
25:   IZ LENIZ – INTEGER arrayWorkspace
26:   LENIZ – INTEGERInput
On entry: the dimension of the array IZ as declared in the (sub)program from which E04NKF/E04NKA is called.
Constraint: LENIZ≥1.
27:   Z LENZ – REAL (KIND=nag_wp) arrayWorkspace
28:   LENZ – INTEGERInput
On entry: the dimension of the array Z as declared in the (sub)program from which E04NKF/E04NKA is called.
Constraint: LENZ≥1.
The amounts of workspace provided (i.e., LENIZ and LENZ) and required (i.e., MINIZ and MINZ) are (by default for E04NKF) output on the current advisory message unit NADV (as defined by X04ABF). Since the minimum values of LENIZ and LENZ required to start solving the problem are returned in MINIZ and MINZ, respectively, you may prefer to obtain appropriate values from the output of a preliminary run with LENIZ and LENZ set to 1. (E04NKF/E04NKA will then terminate with IFAIL=12.)
29:   IFAIL – INTEGERInput/Output
Note: for E04NKA, IFAIL does not occur in this position in the argument list. See the additional arguments described below.
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, because for this routine the values of the output arguments may be useful even if IFAIL≠0 on exit, the recommended value is -1. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).
E04NKF/E04NKA returns with IFAIL=0 if the reduced gradient (Norm rg; see Section 9.1) is negligible, the Lagrange multipliers (Lagr Mult; see Section 9.1) are optimal and x satisfies the constraints to the accuracy requested by the value of the optional parameter Feasibility Tolerance (default value=max 10-6,ε, where ε is the machine precision).
Note: the following are additional arguments for specific use with E04NKA. Users of E04NKF therefore need not read the remainder of this description.
29:   IUSER* – INTEGER arrayUser Workspace
30:   RUSER* – REAL (KIND=nag_wp) arrayUser Workspace
IUSER and RUSER are not used by E04NKF/E04NKA, but are passed directly to QPHX and may be used to pass information to this routine as an alternative to using COMMON global variables.
31:   LWSAV 20 – LOGICAL arrayCommunication Array
32:   IWSAV 380 – INTEGER arrayCommunication Array
33:   RWSAV 285 – REAL (KIND=nag_wp) arrayCommunication Array
The arrays LWSAV, IWSAV and RWSAV must not be altered between calls to any of the routines E04NKA, E04NLA, E04NMA or E04WBF.
34:   IFAIL – INTEGERInput/Output
Note: see the argument description for IFAIL above.

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Note: E04NKF/E04NKA may return useful information for one or more of the following detected errors or warnings.
Errors or warnings detected by the routine:
IFAIL=1
Weak solution found. The final x is not unique, although x gives the global minimum value of the objective function.
IFAIL=2
The problem is unbounded (or badly scaled). The objective function is not bounded below in the feasible region.
IFAIL=3
The problem is infeasible. The general constraints cannot all be satisfied simultaneously to within the value of the optional parameter Feasibility Tolerance (default value=max 10-6,ε, where ε is the machine precision).
IFAIL=4
Too many iterations. The value of the optional parameter Iteration Limit (default value=max 50,5 n+m) is too small.
IFAIL=5
The reduced Hessian matrix ZT HZ (see Section 11.2) exceeds its assigned dimension. The value of the optional parameter Superbasics Limit (default value=min nH+1,n) is too small.
IFAIL=6
The Hessian matrix H appears to be indefinite. This sometimes occurs because the values of the optional parameters LU Factor Tolerance (default value=100.0) and LU Update Tolerance (default value=10.0) are too large. Check also that QPHX has been coded correctly and that all relevant elements of Hx have been assigned their correct values.
IFAIL=7
An input argument is invalid.
IFAIL=8
Numerical error in trying to satisfy the general constraints. The basis is very ill-conditioned.
IFAIL=9
Not enough integer workspace for the basis factors. Increase LENIZ and rerun E04NKF/E04NKA.
IFAIL=10
Not enough real workspace for the basis factors. Increase LENZ and rerun E04NKF/E04NKA.
IFAIL=11
The basis is singular after 15 attempts to factorize it (adding slacks where necessary). Either the problem is badly scaled or the value of the optional parameter LU Factor Tolerance (default value=100.0) is too large.
IFAIL=12
Not enough integer workspace to start solving the problem. Increase LENIZ to at least MINIZ and rerun E04NKF/E04NKA.
IFAIL=13
Not enough real workspace to start solving the problem. Increase LENZ to at least MINZ and rerun E04NKF/E04NKA.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

E04NKF/E04NKA implements a numerically stable active-set strategy and returns solutions that are as accurate as the condition of the problem warrants on the machine.

8 Parallelism and Performance

E04NKF/E04NKA makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

This section contains a description of the printed output.

9.1 Description of the Printed Output

This section describes the intermediate printout and final printout produced by E04NKF/E04NKA. The intermediate printout is a subset of the monitoring information produced by the routine at every iteration (see Section 13). You can control the level of printed output (see the description of the optional parameter Print Level). Note that the intermediate printout and final printout are produced only if Print Level≥10 (the default for E04NKF, by default no output is produced by E04NKA).
The following line of summary output (<80 characters) is produced at every iteration. In all cases, the values of the quantities printed are those in effect on completion of the given iteration.
Itn | is the iteration count.
Step | is the step taken along the computed search direction.
Ninf | is the number of violated constraints (infeasibilities). This will be zero during the optimality phase.
Sinf/Objective | is the value of the current objective function. If x is not feasible, Sinf gives the sum of the magnitudes of constraint violations. If x is feasible, Objective is the value of the objective function. The output line for the final iteration of the feasibility phase (i.e., the first iteration for which Ninf is zero) will give the value of the true objective at the first feasible point. During the optimality phase, the value of the objective function will be nonincreasing. During the feasibility phase, the number of constraint infeasibilities will not increase until either a feasible point is found, or the optimality of the multipliers implies that no feasible point exists.
Norm rg | is dS, the Euclidean norm of the reduced gradient (see Section 11.3). During the optimality phase, this norm will be approximately zero after a unit step. For FP and LP problems, Norm rg is not printed.
The final printout includes a listing of the status of every variable and constraint.
The following describes the printout for each variable. A full stop (.) is printed for any numerical value that is zero.
Variable | gives the name of the variable. If NNAME=1, a default name is assigned to the jth variable, for j=1,2,…,n. If NNAME=N+M, the name supplied in CRNAME j is assigned to the jth variable.
State gives the state of the variable (LL if nonbasic on its lower bound, UL if nonbasic on its upper bound, EQ if nonbasic and fixed, FR if nonbasic and strictly between its bounds, BS if basic and SBS if superbasic).
A key is sometimes printed before State. Note that unless the optional parameter Scale Option=0 (default value=2) is specified, the tests for assigning a key are applied to the variables of the scaled problem.
A | Alternative optimum possible. The variable is nonbasic, but its reduced gradient is essentially zero. This means that if the variable were allowed to start moving away from its bound, there would be no change in the value of the objective function. The values of the other free variables might change, giving a genuine alternative solution. However, if there are any degenerate variables (labelled D), the actual change might prove to be zero, since one of them could encounter a bound immediately. In either case, the values of the Lagrange multipliers might also change.
D | Degenerate. The variable is basic or superbasic, but it is equal (or very close) to one of its bounds.
I | Infeasible. The variable is basic or superbasic and is currently violating one of its bounds by more than the value of the Feasibility Tolerance.
N | Not precisely optimal. The variable is nonbasic or superbasic. If the value of the reduced gradient for the variable exceeds the value of the optional parameter Optimality Tolerance, the solution would not be declared optimal because the reduced gradient for the variable would not be considered negligible.
Value | is the value of the variable at the final iteration.
Lower Bound | is the lower bound specified for the variable. None indicates that BL j≤-bigbnd.
Upper Bound | is the upper bound specified for the variable. None indicates that BU j≥bigbnd.
Lagr Mult | is the Lagrange multiplier for the associated bound. This will be zero if State is FR. If x is optimal, the multiplier should be non-negative if State is LL, non-positive if State is UL and zero if State is BS or SBS.
Residual | is the difference between the variable Value and the nearer of its (finite) bounds BL j and BU j. A blank entry indicates that the associated variable is not bounded (i.e., BL j≤-bigbnd and BU j≥bigbnd).
The meaning of the printout for linear constraints is the same as that given above for variables, with ‘variable’ replaced by ‘constraint’, n replaced by m, CRNAME j replaced by CRNAME n+j, BL j and BU j are replaced by BL n+j and BU n+j respectively, and with the following change in the heading:
Constrnt gives the name of the linear constraint.
Note that movement off a constraint (as opposed to a variable moving away from its bound) can be interpreted as allowing the entry in the Residual column to become positive.
Numerical values are output with a fixed number of digits; they are not guaranteed to be accurate to this precision.

10 Example

This example minimizes the quadratic function f x=cT x+12 xT Hx, where
c=-200.0,-2000.0,-2000.0,-2000.0,-2000.0,400.0,400.0 T
H= 2 0 0 0 0 0 0 0 2 0 0 0 0 0 0 0 2 2 0 0 0 0 0 2 2 0 0 0 0 0 0 0 2 0 0 0 0 0 0 0 2 2 0 0 0 0 0 2 2
subject to the bounds
00 0≤x 1≤0 200 00 0≤x 2≤2500 400≤x 3≤0 800 100≤x 4≤0 700 00 0≤x 5≤1500 00 0≤x 6≤1500 00 0≤x 7≤1500
and to the linear constraints
1500≤ 0.00 x 1+0.00 x 2+0.00 x 3+0.00 x 4+0.00 x 5+0.00 x 6+0.00 x 7= 2000 1500≤0.15 x 1+ 0.04 x 2+ 0.02 x 3+ 0.04 x 4+ 0.02 x 5+ 0.01 x 6+ 0.03 x 7≤00 60 1500≤0.03 x 1+ 0.05 x 2+ 0.08 x 3+ 0.02 x 4+ 0.06 x 5+ 0.01 x 6 + 0.03 x 7 ≤0 100 1500≤0.02 x 1+ 0.04 x 2+ 0.01 x 3+ 0.02 x 4+ 0.02 x 5 + 0.01 x 6+ 0.03 x 7 ≤00 40 1500≤0.02 x 1+ 0.03 x 2 + 0.01 x 3+ 0.02 x 4+ 0.01 x 5 + 0.01 x 6+ 0.03 x 7≤00 30 1500≤ 0.70 x 1+ 0.75 x 2+ 0.80 x 3+ 0.75 x 4+ 0.80 x 5+ 0.97 x 6 + 0.03 x 7≤ 2000 0 250≤ 0.02 x 1+ 0.06 x 2+ 0.08 x 3+ 0.12 x 4+ 0.02 x 5+ 0.01 x 6+ 0.97 x 7≤0 300
The initial point, which is infeasible, is
x 0=0.0,0.0,0.0,0.0,0.0,0.0,0.0 T.
The optimal solution (to five figures) is
x*=0.0,349.40,648.85,172.85,407.52,271.36,150.02 T.
One bound constraint and four linear constraints are active at the solution. Note that the Hessian matrix H is positive semidefinite.

10.1 Program Text

Note: the following programs illustrate the use of E04NKF and E04NKA.

Program Text (e04nkfe.f90)

Program Text (e04nkae.f90)

10.2 Program Data

Program Data (e04nkfe.d)

Program Data (e04nkae.d)

10.3 Program Results

Program Results (e04nkfe.r)

Program Results (e04nkae.r)

Note: the remainder of this document is intended for more advanced users. Section 11 contains a detailed description of the algorithm which may be needed in order to understand Sections 12 and 13. Section 12 describes the optional parameters which may be set by calls to E04NLF/E04NLA and/or E04NMF/E04NMA. Section 13 describes the quantities which can be requested to monitor the course of the computation.

11 Algorithmic Details

This section contains a detailed description of the method used by E04NKF/E04NKA.

11.1 Overview

E04NKF/E04NKA is based on an inertia-controlling method that maintains a Cholesky factorization of the reduced Hessian (see below). The method is similar to that of Gill and Murray (1978), and is described in detail by Gill et al. (1991). Here we briefly summarise the main features of the method. Where possible, explicit reference is made to the names of variables that are arguments of the routine or appear in the printed output.
The method used has two distinct phases: finding an initial feasible point by minimizing the sum of infeasibilities (the feasibility phase), and minimizing the quadratic objective function within the feasible region (the optimality phase). The computations in both phases are performed by the same subroutines. The two-phase nature of the algorithm is reflected by changing the function being minimized from the sum of infeasibilities (the printed quantity Sinf; see Section 13) to the quadratic objective function (the printed quantity Objective; see Section 13).
In general, an iterative process is required to solve a quadratic program. Given an iterate x,s in both the original variables x and the slack variables s, a new iterate x-,s- is defined by
x- s- = x s +αp, (2)
where the step length α is a non-negative scalar (the printed quantity Step; see Section 13), and p is called the search direction. (For simplicity, we shall consider a typical iteration and avoid reference to the index of the iteration.) Once an iterate is feasible (i.e., satisfies the constraints), all subsequent iterates remain feasible.

11.2 Definition of the Working Set and Search Direction

At each iterate x,s, a working set of constraints is defined to be a linearly independent subset of the constraints that are satisfied ‘exactly’ (to within the value of the optional parameter Feasibility Tolerance). The working set is the current prediction of the constraints that hold with equality at a solution of the LP or QP problem. Let mW denote the number of constraints in the working set (including bounds), and let W denote the associated mW by n+m working set matrix consisting of the mW gradients of the working set constraints.
The search direction is defined so that constraints in the working set remain unaltered for any value of the step length. It follows that p must satisfy the identity
Wp=0. (3)
This characterisation allows p to be computed using any n by nZ full-rank matrix Z that spans the null space of W. (Thus, nZ=n-mW and WZ=0.) The null space matrix Z is defined from a sparse LU factorization of part of W (see (6) and (7)). The direction p will satisfy (3) if
p=Z pZ, (4)
where pZ is any nZ-vector.
The working set contains the constraints Ax-s=0 and a subset of the upper and lower bounds on the variables x,s. Since the gradient of a bound constraint xj≥lj or xj≤uj is a vector of all zeros except for ±1 in position j, it follows that the working set matrix contains the rows of A -I and the unit rows associated with the upper and lower bounds in the working set.
The working set matrix W can be represented in terms of a certain column partition of the matrix A -I by (conceptually) partitioning the constraints Ax-s=0 so that
B xB+S xS+N xN=0, (5)
where B is a square nonsingular basis and xB, xS and xN are the basic, superbasic and nonbasic variables respectively. The nonbasic variables are equal to their upper or lower bounds at x,s, and the superbasic variables are independent variables that are chosen to improve the value of the current objective function. The number of superbasic variables is nS (the printed quantity Ns; see Section 13). Given values of xN and xS, the basic variables xB are adjusted so that x,s satisfies (5).
If P is a permutation matrix such that A -I P= B S N , then W satisfies
WP= B S N 0 0 IN , (6)
where IN is the identity matrix with the same number of columns as N.
The null space matrix Z is defined from a sparse LU factorization of part of W. In particular, Z is maintained in ‘reduced gradient’ form, using the LUSOL package (see Gill et al. (1991)) to maintain sparse LU factors of the basis matrix B that alters as the working set W changes. Given the permutation P, the null space basis is given by
Z=P -B-1 S I 0 . (7)
This matrix is used only as an operator, i.e., it is never computed explicitly. Products of the form Zv and ZT g are obtained by solving with B or BT. This choice of Z implies that nZ, the number of ‘degrees of freedom’ at x,s, is the same as nS, the number of superbasic variables.
Let gZ and HZ denote the reduced gradient and reduced Hessian of the objective function:
gZ=ZT g  and  HZ=ZT HZ, (8)
where g is the objective gradient at x,s. Roughly speaking, gZ and HZ describe the first and second derivatives of an nS-dimensional unconstrained problem for the calculation of pZ. (The condition estimator of HZ is the quantity Cond Hz in the monitoring file output; see Section 13.)
At each iteration, an upper triangular factor R is available such that HZ=RT R. Normally, R is computed from RT R=ZT HZ at the start of the optimality phase and then updated as the QP working set changes. For efficiency, the dimension of R should not be excessive (say, nS≤1000). This is guaranteed if the number of nonlinear variables is ‘moderate’.
If the QP problem contains linear variables, H is positive semidefinite and R may be singular with at least one zero diagonal element. However, an inertia-controlling strategy is used to ensure that only the last diagonal element of R can be zero. (See Gill et al. (1991) for a discussion of a similar strategy for indefinite quadratic programming.)
If the initial R is singular, enough variables are fixed at their current value to give a nonsingular R. This is equivalent to including temporary bound constraints in the working set. Thereafter, R can become singular only when a constraint is deleted from the working set (in which case no further constraints are deleted until R becomes nonsingular).

11.3 Main Iteration

If the reduced gradient is zero, x,s is a constrained stationary point on the working set. During the feasibility phase, the reduced gradient will usually be zero only at a vertex (although it may be zero elsewhere in the presence of constraint dependencies). During the optimality phase, a zero reduced gradient implies that x minimizes the quadratic objective function when the constraints in the working set are treated as equalities. At a constrained stationary point, Lagrange multipliers λ are defined from the equations
WT λ=g x. (9)
A Lagrange multiplier λj corresponding to an inequality constraint in the working set is said to be optimal if λj≤σ when the associated constraint is at its upper bound, or if λj≥-σ when the associated constraint is at its lower bound, where σ depends on the value of the optional parameter Optimality Tolerance. If a multiplier is nonoptimal, the objective function (either the true objective or the sum of infeasibilities) can be reduced by continuing the minimization with the corresponding constraint excluded from the working set. (This step is sometimes referred to as ‘deleting’ a constraint from the working set.) If optimal multipliers occur during the feasibility phase but the sum of infeasibilities is nonzero, there is no feasible point and the routine terminates immediately with IFAIL=3 (see Section 6).
The special form (6) of the working set allows the multiplier vector λ, the solution of (9), to be written in terms of the vector
d= g 0 - A -I T π= g-AT π π , (10)
where π satisfies the equations BT π=gB, and gB denotes the basic elements of g. The elements of π are the Lagrange multipliers λj associated with the equality constraints Ax-s=0. The vector dN of nonbasic elements of d consists of the Lagrange multipliers λj associated with the upper and lower bound constraints in the working set. The vector dS of superbasic elements of d is the reduced gradient gZ in (8). The vector dB of basic elements of d is zero, by construction. (The Euclidean norm of dS and the final values of dS, g and π are the quantities Norm rg, Reduced Gradnt, Obj Gradient and Dual Activity in the monitoring file output; see Section 13.)
If the reduced gradient is not zero, Lagrange multipliers need not be computed and the search direction is given by p=Z pZ (see (7) and (11)). The step length is chosen to maintain feasibility with respect to the satisfied constraints.
There are two possible choices for pZ, depending on whether or not HZ is singular. If HZ is nonsingular, R is nonsingular and pZ in (4) is computed from the equations
RT R pZ=-gZ, (11)
where gZ is the reduced gradient at x. In this case, x,s+p is the minimizer of the objective function subject to the working set constraints being treated as equalities. If x,s+p is feasible, α is defined to be unity. In this case, the reduced gradient at x-,s- will be zero, and Lagrange multipliers are computed at the next iteration. Otherwise, α is set to αM, the step to the ‘nearest’ constraint along p. This constraint is then added to the working set at the next iteration.
If HZ is singular, then R must also be singular, and an inertia-controlling strategy is used to ensure that only the last diagonal element of R is zero. (See Gill et al. (1991) for a discussion of a similar strategy for indefinite quadratic programming.) In this case, pZ satisfies
pZT HZ pZ=0   and   gZT pZ≤0, (12)
which allows the objective function to be reduced by any step of the form x,s+αp, where α>0. The vector p=Z pZ is a direction of unbounded descent for the QP problem in the sense that the QP objective is linear and decreases without bound along p. If no finite step of the form x,s+αp (where α>0) reaches a constraint not in the working set, the QP problem is unbounded and the routine terminates immediately with IFAIL=2 (see Section 6). Otherwise, α is defined as the maximum feasible step along p and a constraint active at x,s+αp is added to the working set for the next iteration.

11.4 Miscellaneous

If the basis matrix is not chosen carefully, the condition of the null space matrix Z in (7) could be arbitrarily high. To guard against this, the routine implements a ‘basis repair’ feature in which the LUSOL package (see Gill et al. (1991)) is used to compute the rectangular factorization
B S T=LU, (13)
returning just the permutation P that makes PL PT unit lower triangular. The pivot tolerance is set to require PL PT ij≤2, and the permutation is used to define P in (6). It can be shown that Z is likely to be little more than unity. Hence, Z should be well-conditioned regardless of the condition of W. This feature is applied at the beginning of the optimality phase if a potential B-S ordering is known.
The EXPAND procedure (see Gill et al. (1989)) is used to reduce the possibility of cycling at a point where the active constraints are nearly linearly dependent. Although there is no absolute guarantee that cycling will not occur, the probability of cycling is extremely small (see Hall and McKinnon (1996)). The main feature of EXPAND is that the feasibility tolerance is increased at the start of every iteration. This allows a positive step to be taken at every iteration, perhaps at the expense of violating the bounds on x,s by a small amount.
Suppose that the value of the optional parameter Feasibility Tolerance is δ. Over a period of K iterations (where K is the value of the optional parameter Expand Frequency), the feasibility tolerance actually used by the routine (i.e., the working feasibility tolerance) increases from 0.5 δ to δ (in steps of 0.5 δ/K).
At certain stages the following ‘resetting procedure’ is used to remove small constraint infeasibilities. First, all nonbasic variables are moved exactly onto their bounds. A count is kept of the number of nontrivial adjustments made. If the count is nonzero, the basic variables are recomputed. Finally, the working feasibility tolerance is reinitialized to 0.5 δ.
If a problem requires more than K iterations, the resetting procedure is invoked and a new cycle of iterations is started. (The decision to resume the feasibility phase or optimality phase is based on comparing any constraint infeasibilities with δ.)
The resetting procedure is also invoked when the routine reaches an apparently optimal, infeasible or unbounded solution, unless this situation has already occurred twice. If any nontrivial adjustments are made, iterations are continued.
The EXPAND procedure not only allows a positive step to be taken at every iteration, but also provides a potential choice of constraints to be added to the working set. All constraints at a distance α (where α≤αM) along p from the current point are then viewed as acceptable candidates for inclusion in the working set. The constraint whose normal makes the largest angle with the search direction is added to the working set. This strategy helps keep the basis matrix B well-conditioned.

12 Optional Parameters

Several optional parameters in E04NKF/E04NKA define choices in the problem specification or the algorithm logic. In order to reduce the number of formal arguments of E04NKF/E04NKA these optional parameters have associated default values that are appropriate for most problems. Therefore, you need only specify those optional parameters whose values are to be different from their default values.
The remainder of this section can be skipped if you wish to use the default values for all optional parameters.
The following is a list of the optional parameters available. A full description of each optional parameter is provided in Section 12.1.
  • Check Frequency
  • Crash Option
  • Crash Tolerance
  • Defaults
  • Expand Frequency
  • Factorization Frequency
  • Feasibility Tolerance
  • Infinite Bound Size
  • Infinite Step Size
  • Iteration Limit
  • Iters
  • Itns
  • List
  • LU Factor Tolerance
  • LU Singularity Tolerance
  • LU Update Tolerance
  • Maximize
  • Minimize
  • Monitoring File
  • Nolist
  • Optimality Tolerance
  • Partial Price
  • Pivot Tolerance
  • Print Level
  • Rank Tolerance
  • Scale Option
  • Scale Tolerance
  • Superbasics Limit
Optional parameters may be specified by calling one, or both, of the routines E04NLF/E04NLA and E04NMF/E04NMA before a call to E04NKF/E04NKA.
E04NLF/E04NLA reads options from an external options file, with Begin and End as the first and last lines respectively and each intermediate line defining a single optional parameter. For example,
Begin
  Print Level = 5
End
The call
 CALL E04NLF (IOPTNS, INFORM)
can then be used to read the file on unit IOPTNS. INFORM will be zero on successful exit. E04NLF/E04NLA should be consulted for a full description of this method of supplying optional parameters.
E04NMF/E04NMA can be called to supply options directly, one call being necessary for each optional parameter. For example,
 CALL E04NMF ('Print Level = 5')
E04NMF/E04NMA should be consulted for a full description of this method of supplying optional parameters.
All optional parameters not specified by you are set to their default values. Optional parameters specified by you are unaltered by E04NKF/E04NKA (unless they define invalid values) and so remain in effect for subsequent calls unless altered by you.

12.1 Description of the Optional Parameters

For each option, we give a summary line, a description of the optional parameter and details of constraints.
The summary line contains:
  • the keywords, where the minimum abbreviation of each keyword is underlined (if no characters of an optional qualifier are underlined, the qualifier may be omitted);
  • a parameter value, where the letters a, i and r denote options that take character, integer and real values respectively;
  • the default value is used whenever the condition i≥100000000 is satisfied and where the symbol ε is a generic notation for machine precision (see X02AJF);
Keywords and character values are case and white space insensitive.
Check Frequency i Default =60
Every ith iteration after the most recent basis factorization, a numerical test is made to see if the current solution x,s satisfies the linear constraints Ax-s=0. If the largest element of the residual vector r=Ax-s is judged to be too large, the current basis is refactorized and the basic variables recomputed to satisfy the constraints more accurately. If i<0, the default value is used. If i=0, the value i=99999999 is used and effectively no checks are made.
Crash Option i Default =2
Note that this option does not apply when START='W' (see Section 5).
If START='C', an internal Crash procedure is used to select an initial basis from various rows and columns of the constraint matrix A -I . The value of i determines which rows and columns are initially eligible for the basis, and how many times the Crash procedure is called. If i=0, the all-slack basis B=-I is chosen. If i=1, the Crash procedure is called once (looking for a triangular basis in all rows and columns of the linear constraint matrix A). If i=2, the Crash procedure is called twice (looking at any equality constraints first followed by any inequality constraints). If i<0 or i>2, the default value is used.
If i=1​ or ​2, certain slacks on inequality rows are selected for the basis first. (If i=2, numerical values are used to exclude slacks that are close to a bound.) The Crash procedure then makes several passes through the columns of A, searching for a basis matrix that is essentially triangular. A column is assigned to ‘pivot’ on a particular row if the column contains a suitably large element in a row that has not yet been assigned. (The pivot elements ultimately form the diagonals of the triangular basis.) For remaining unassigned rows, slack variables are inserted to complete the basis.
Crash Tolerance r Default =0.1
This value allows the Crash procedure to ignore certain ‘small’ nonzero elements in the constraint matrix A while searching for a triangular basis. For each column of A, if amax is the largest element in the column, other nonzeros in that column are ignored if they are less than (or equal to) amax×r.
When r>0, the basis obtained by the Crash procedure may not be strictly triangular, but it is likely to be nonsingular and almost triangular. The intention is to obtain a starting basis with more column variables and fewer (arbitrary) slacks. A feasible solution may be reached earlier for some problems. If r<0 or r≥1, the default value is used.
Defaults
This special keyword may be used to reset all optional parameters to their default values.
Expand Frequency i Default =10000
This option is part of an anti-cycling procedure (see Section 11.4) designed to allow progress even on highly degenerate problems.
For LP problems, the strategy is to force a positive step at every iteration, at the expense of violating the constraints by a small amount. Suppose that the value of the optional parameter Feasibility Tolerance is δ. Over a period of i iterations, the feasibility tolerance actually used by E04NKF/E04NKA (i.e., the working feasibility tolerance) increases from 0.5 δ to δ (in steps of 0.5 δ/i).
For QP problems, the same procedure is used for iterations in which there is only one superbasic variable. (Cycling can only occur when the current solution is at a vertex of the feasible region.) Thus, zero steps are allowed if there is more than one superbasic variable, but otherwise positive steps are enforced.
Increasing the value of i helps reduce the number of slightly infeasible nonbasic basic variables (most of which are eliminated during the resetting procedure). However, it also diminishes the freedom to choose a large pivot element (see optional parameter Pivot Tolerance).
If i<0, the default value is used. If i=0, the value i=99999999 is used and effectively no anti-cycling procedure is invoked.
Factorization Frequency i Default =100
If i>0, at most i basis changes will occur between factorizations of the basis matrix. For LP problems, the basis factors are usually updated at every iteration. For QP problems, fewer basis updates will occur as the solution is approached. The number of iterations between basis factorizations will therefore increase. During these iterations a test is made regularly according to the value of optional parameter Check Frequency to ensure that the linear constraints Ax-s=0 are satisfied. If necessary, the basis will be refactorized before the limit of i updates is reached. If i≤0, the default value is used.
Feasibility Tolerance r Default =max 10-6,ε
If r≥ε, r defines the maximum acceptable absolute violation in each constraint at a ‘feasible’ point (including slack variables). For example, if the variables and the coefficients in the linear constraints are of order unity, and the latter are correct to about five decimal digits, it would be appropriate to specify r as 10-5. If r<ε, the default value is used.
E04NKF/E04NKA attempts to find a feasible solution before optimizing the objective function. If the sum of infeasibilities cannot be reduced to zero, the problem is assumed to be infeasible. Let Sinf be the corresponding sum of infeasibilities. If Sinf is quite small, it may be appropriate to raise r by a factor of 10 or 100. Otherwise, some error in the data should be suspected. Note that the routine does not attempt to find the minimum value of Sinf.
If the constraints and variables have been scaled (see Scale Option), then feasibility is defined in terms of the scaled problem (since it is more likely to be meaningful).
Infinite Bound Size r Default =1020
If r>0, r defines the ‘infinite’ bound bigbnd in the definition of the problem constraints. Any upper bound greater than or equal to bigbnd will be regarded as +∞ (and similarly any lower bound less than or equal to -bigbnd will be regarded as -∞). If r≤0, the default value is used.
Infinite Step Size r Default =max bigbnd,1020
If r>0, r specifies the magnitude of the change in variables that will be considered a step to an unbounded solution. (Note that an unbounded solution can occur only when the Hessian is not positive definite.) If the change in x during an iteration would exceed the value of r, the objective function is considered to be unbounded below in the feasible region. If r≤0, the default value is used.
Iteration Limit i Default =max 50,5 n+m
Iters
Itns
The value of i specifies the maximum number of iterations allowed before termination. Setting i=0 and Print Level>0 means that the workspace needed to start solving the problem will be computed and printed, but no iterations will be performed. If i<0, the default value is used.
List Default for E04NKF =List
Nolist Default for E04NKA =Nolist
Normally each optional parameter specification is printed as it is supplied. Optional parameter Nolist may be used to suppress the printing and optional parameter List may be used to restore printing.
LU Factor Tolerance r 1 Default =100.0
LU Update Tolerance r 2 Default =10.0
The values of r 1 and r 2 affect the stability and sparsity of the basis factorization B=LU, during refactorization and updates respectively. The lower triangular matrix L is a product of matrices of the form
1 0 μ 1
where the multipliers μ will satisfy μ≤ri. The default values of r 1 and r 2 usually strike a good compromise between stability and sparsity. For large and relatively dense problems, setting r 1 and r 2 to 25 (say) may give a marked improvement in sparsity without impairing stability to a serious degree.
Note that for band matrices it may be necessary to set r 1 in the range 1≤r 1<2 in order to achieve stability. If r 1<1 or r 2<1, the default value is used.
LU Singularity Tolerance r Default =ε 0.67
If r>0, r defines the singularity tolerance used to guard against ill-conditioned basis matrices. Whenever the basis is refactorized, the diagonal elements of U are tested as follows. If u jj≤r or u jj<r×maxi u ij, the jth column of the basis is replaced by the corresponding slack variable. If r≤0, the default value is used.
Minimize Default
Maximize
This option specifies the required direction of the optimization. It applies to both linear and nonlinear terms (if any) in the objective function. Note that if two problems are the same except that one minimizes f x and the other maximizes -f x, their solutions will be the same but the signs of the dual variables πi and the reduced gradients dj (see Section 11.3) will be reversed.
Monitoring File i Default =-1
If i≥0 and Print Level>0 (see Print Level), monitoring information produced by E04NKF/E04NKA is sent to a file with logical unit number i. If i<0 and/or Print Level=0, the default value is used and hence no monitoring information is produced.
Optimality Tolerance r Default =max 10-6,ε
If r≥ε, r is used to judge the size of the reduced gradients dj=gj-πT aj. By definition, the reduced gradients for basic variables are always zero. Optimality is declared if the reduced gradients for any nonbasic variables at their lower or upper bounds satisfy -r×max 1,π≤dj≤r×max 1,π, and if dj≤r×max 1,π for any superbasic variables. If r<ε, the default value is used.
Partial Price i Default =10
Note that this option does not apply to QP problems.
This option is recommended for large FP or LP problems that have significantly more variables than constraints (i.e., n≫m). It reduces the work required for each pricing operation (i.e., when a nonbasic variable is selected to enter the basis). If i=1, all columns of the constraint matrix A -I are searched. If i>1, A and -I are partitioned to give i roughly equal segments Aj,Kj, for j=1,2,…,p (modulo p). If the previous pricing search was successful on A j-1,K j-1, the next search begins on the segments Aj,Kj. If a reduced gradient is found that is larger than some dynamic tolerance, the variable with the largest such reduced gradient (of appropriate sign) is selected to enter the basis. If nothing is found, the search continues on the next segments A j+1,K j+1, and so on. If i≤0, the default value is used.
Pivot Tolerance r Default =ε 0.67
If r>0, r is used to prevent columns entering the basis if they would cause the basis to become almost singular. If r≤0, the default value is used.
Print Level i Default for E04NKF =10
Default for E04NKA =0
The value of i controls the amount of printout produced by E04NKF/E04NKA, as indicated below. A detailed description of the printed output is given in Section 9.1 (summary output at each iteration and the final solution) and Section 13 (monitoring information at each iteration). Note that the summary output will not exceed 80 characters per line and that the monitoring information will not exceed 120 characters per line. If i<0, the default value is used.
The following printout is sent to the current advisory message unit (as defined by X04ABF):
i | Output
≥0 0 | No output.
≥0 1 | The final solution only.
≥0 5 | One line of summary output for each iteration (no printout of the final solution).
≥10 | The final solution and one line of summary output for each iteration.
The following printout is sent to the logical unit number defined by the optional parameter Monitoring File:
i | Output
≥0 0 | No output.
≥0 1 | The final solution only.
≥0 5 | One long line of output for each iteration (no printout of the final solution).
≥10 | The final solution and one long line of output for each iteration.
≥20 | The final solution, one long line of output for each iteration, matrix statistics (initial status of rows and columns, number of elements, density, biggest and smallest elements, etc.), details of the scale factors resulting from the scaling procedure (if Scale Option=1 or 2 (see the description of the optional parameter Scale Option), basis factorization statistics and details of the initial basis resulting from the Crash procedure (if START='C'; see Section 5).
If Print Level>0 and the unit number defined by optional parameter Monitoring File is the same as that defined by X04ABF, then the summary output is suppressed.
Rank Tolerance r Default =100 ε
Scale Option i Default =2
This option enables you to scale the variables and constraints using an iterative procedure due to Fourer (1982), which attempts to compute row scales ri and column scales cj such that the scaled matrix coefficients a-ij=a ij×cj/ri are as close as possible to unity. This may improve the overall efficiency on some problems. (The lower and upper bounds on the variables and slacks for the scaled problem are redefined as l-j=lj/cj and u-j=uj/cj respectively, where cj≡r j-n if j>n.)
If i=0, no scaling is performed. If i=1, all rows and columns of the constraint matrix A are scaled. If i=2, an additional scaling is performed that may be helpful when the solution x is large; it takes into account columns of A -I that are fixed or have positive lower bounds or negative upper bounds. If i<0 or i>2, the default value is used.
Scale Tolerance r Default =0.9
Note that this option does not apply when Scale Option=0.
If 0<r<1, r is used to control the number of scaling passes to be made through the constraint matrix A. At least 3 (and at most 10) passes will be made. More precisely, let ap denote the largest column ratio (i.e., 'biggest'​ element 'smallest'​ element in some sense) after the pth scaling pass through A. The scaling procedure is terminated if ap≥a p-1×r for some p≥3. Thus, increasing the value of r from 0.9 to 0.99 (say) will probably increase the number of passes through A.
If r≤0 or r≥1, the default value is used.
Superbasics Limit i Default =min nH+1,n
Note that this option does not apply to FP or LP problems.
The value of i specifies ‘how nonlinear’ you expect the QP problem to be. If i≤0, the default value is used.

13 Description of Monitoring Information

This section describes the intermediate printout and final printout which constitutes the monitoring information produced by E04NKF/E04NKA. (See also the description of the optional parameters Monitoring File and Print Level.) You can control the level of printed output.
When Print Level=5 or ≥10 and Monitoring File≥0, the following line of intermediate printout (<120 characters) is produced at every iteration on the unit number specified by optional parameter Monitoring File. Unless stated otherwise, the values of the quantities printed are those in effect on completion of the given iteration.
Itn | is the iteration count.
pp | is the partial price indicator. The variable selected by the last pricing operation came from the ppth partition of A and -I. Note that pp is reset to zero whenever the basis is refactorized.
dj | is the value of the reduced gradient (or reduced cost) for the variable selected by the pricing operation at the start of the current iteration.
+S | is the variable selected by the pricing operation to be added to the superbasic set.
-S | is the variable chosen to leave the superbasic set.
-BS | is the variable removed from the basis (if any) to become nonbasic.
Step | is the value of the step length α taken along the current search direction p. The variables x have just been changed to x+αp. If a variable is made superbasic during the current iteration (i.e., +S is positive), Step will be the step to the nearest bound. During the optimality phase, the step can be greater than unity only if the reduced Hessian is not positive definite.
Pivot | is the rth element of a vector y satisfying By=aq whenever aq (the qth column of the constraint matrix A-I ) replaces the rth column of the basis matrix B. Wherever possible, Step is chosen so as to avoid extremely small values of Pivot (since they may cause the basis to be nearly singular). In extreme cases, it may be necessary to increase the value of the optional parameter Pivot Tolerance to exclude very small elements of y from consideration during the computation of Step.
Ninf | is the number of violated constraints (infeasibilities). This will be zero during the optimality phase.
Sinf/Objective | is the value of the current objective function. If x is not feasible, Sinf gives the sum of the magnitudes of constraint violations. If x is feasible, Objective is the value of the objective function. The output line for the final iteration of the feasibility phase (i.e., the first iteration for which Ninf is zero) will give the value of the true objective at the first feasible point. During the optimality phase, the value of the objective function will be nonincreasing. During the feasibility phase, the number of constraint infeasibilities will not increase until either a feasible point is found, or the optimality of the multipliers implies that no feasible point exists.
L | is the number of nonzeros in the basis factor L. Immediately after a basis factorization B=LU, this entry contains lenL. Further nonzeros are added to L when various columns of B are later replaced. (Thus, L increases monotonically.)
U | is the number of nonzeros in the basis factor U. Immediately after a basis factorization B=LU, this entry contains lenU. As columns of B are replaced, the matrix U is maintained explicitly (in sparse form). The value of U may fluctuate up or down; in general, it will tend to increase.
Ncp | is the number of compressions required to recover workspace in the data structure for U. This includes the number of compressions needed during the previous basis factorization. Normally, Ncp should increase very slowly. If it does not, increase LENIZ and LENZ by at least L+U and rerun E04NKF/E04NKA (possibly using START='W'; see Section 5).
Norm rg | is dS, the Euclidean norm of the reduced gradient (see Section 11.3). During the optimality phase, this norm will be approximately zero after a unit step. For FP and LP problems, Norm rg is not printed.
Ns | is the current number of superbasic variables. For FP and LP problems, Ns is not printed.
Cond Hz | is a lower bound on the condition number of the reduced Hessian (see Section 11.2). The larger this number, the more difficult the problem. For FP and LP problems, Cond Hz is not printed.
When Print Level≥20 and Monitoring File≥0, the following lines of intermediate printout (<120 characters) are produced on the unit number specified by optional parameter Monitoring File whenever the matrix B or BS= B S T is factorized. Gaussian elimination is used to compute an LU factorization of B or BS, where PL PT is a lower triangular matrix and PUQ is an upper triangular matrix for some permutation matrices P and Q. The factorization is stabilized in the manner described under the optional parameter LU Factor Tolerance (default value=100.0).
Factorize | is the factorization count.
Demand is a code giving the reason for the present factorization as follows:
Code | Meaning
01 0 | First LU factorization.
01 1 | The number of updates reached the value of the optional parameter Factorization Frequency.
01 2 | The number of nonzeros in the updated factors has increased significantly.
01 7 | Not enough storage to update factors.
0 10 | Row residuals too large (see the description for the optional parameter Check Frequency).
0 11 | Ill-conditioning has caused inconsistent results.
Iteration | is the iteration count.
Nonlinear | is the number of nonlinear variables in the current basis B (not printed if BS is factorized).
Linear | is the number of linear variables in B (not printed if BS is factorized).
Slacks | is the number of slack variables in B (not printed if BS is factorized).
Elems | is the number of nonzeros in B (not printed if BS is factorized).
Density | is the percentage nonzero density of B (not printed if BS is factorized). More precisely, Density=100×Elems/Nonlinear+Linear+Slacks 2.
Compressns | is the number of times the data structure holding the partially factorized matrix needed to be compressed, in order to recover unused workspace. Ideally, it should be zero. If it is more than 3 or 4, increase LENIZ and LENZ and rerun E04NKF/E04NKA (possibly using START='W'; see Section 5).
Merit | is the average Markowitz merit count for the elements chosen to be the diagonals of PUQ. Each merit count is defined to be c-1r-1, where c and r are the number of nonzeros in the column and row containing the element at the time it is selected to be the next diagonal. Merit is the average of m such quantities. It gives an indication of how much work was required to preserve sparsity during the factorization.
lenL | is the number of nonzeros in L.
lenU | is the number of nonzeros in U.
Increase | is the percentage increase in the number of nonzeros in L and U relative to the number of nonzeros in B. More precisely, Increase=100×lenL+lenU-Elems/Elems.
m | is the number of rows in the problem. Note that m=Ut+Lt+bp.
Ut | is the number of triangular rows of B at the top of U.
d1 | is the number of columns remaining when the density of the basis matrix being factorized reached 0.3.
Lmax | is the maximum subdiagonal element in the columns of L. This will not exceed the value of the optional parameter LU Factor Tolerance.
Bmax | is the maximum nonzero element in B (not printed if BS is factorized).
BSmax | is the maximum nonzero element in BS (not printed if B is factorized).
Umax is the maximum nonzero element in U, excluding elements of B that remain in U unchanged. (For example, if a slack variable is in the basis, the corresponding row of B will become a row of U without modification. Elements in such rows will not contribute to Umax. If the basis is strictly triangular then none of the elements of B will contribute and Umax will be zero.)
Ideally, Umax should not be significantly larger than Bmax. If it is several orders of magnitude larger, it may be advisable to reset the optional parameter LU Factor Tolerance to some value nearer unity.
Umax is not printed if BS is factorized.
Umin | is the magnitude of the smallest diagonal element of PUQ (not printed if BS is factorized).
Growth is the value of the ratio Umax/Bmax, which should not be too large.
Providing Lmax is not large (say, <10.0), the ratio max Bmax,Umax/Umin is an estimate of the condition number of B. If this number is extremely large, the basis is nearly singular and some numerical difficulties might occur. (However, an effort is made to avoid near-singularity by using slacks to replace columns of B that would have made Umin extremely small and the modified basis is refactorized.)
Growth is not printed if BS is factorized.
Lt | is the number of triangular columns of B at the left of L.
bp | is the size of the ‘bump’ or block to be factorized nontrivially after the triangular rows and columns of B have been removed.
d2 | is the number of columns remaining when the density of the basis matrix being factorized has reached 0.6.
When Print Level≥20 and Monitoring File≥0, the following lines of intermediate printout (<80 characters) are produced on the unit number specified by optional parameter Monitoring File whenever START='C' (see Section 5). They refer to the number of columns selected by the Crash procedure during each of several passes through A, whilst searching for a triangular basis matrix.
Slacks | is the number of slacks selected initially.
Free cols | is the number of free columns in the basis, including those whose bounds are rather far apart.
Preferred | is the number of ‘preferred’ columns in the basis (i.e., ISTATE j=3 for some j≤n). It will be a subset of the columns for which ISTATE j=3 was specified.
Unit | is the number of unit columns in the basis.
Double | is the number of double columns in the basis.
Triangle | is the number of triangular columns in the basis.
Pad | is the number of slacks used to pad the basis (to make it a nonsingular triangle).
When Print Level≥20 and Monitoring File≥0, the following lines of intermediate printout (<80 characters) are produced on the unit number specified by optional parameter Monitoring File. They refer to the elements of the NAMES array (see Section 5).
Name | gives the name for the problem (blank if problem unnamed).
Status | gives the exit status for the problem (i.e., Optimal soln, Weak soln, Unbounded, Infeasible, Excess itns, Error condn or Feasble soln) followed by details of the direction of the optimization (i.e., (Min) or (Max)).
Objective | gives the name of the free row for the problem (blank if objective unnamed).
RHS | gives the name of the constraint right-hand side for the problem (blank if objective unnamed).
Ranges | gives the name of the ranges for the problem (blank if objective unnamed).
Bounds | gives the name of the bounds for the problem (blank if objective unnamed).
When Print Level=1 or ≥10 and Monitoring File≥0, the following lines of final printout (<120 characters) are produced on the unit number specified by optional parameter Monitoring File.
Let aj denote the jth column of A, for j=1,2,…,n. The following describes the printout for each column (or variable). A full stop (.) is printed for any numerical value that is zero.
Number | is the column number j. (This is used internally to refer to xj in the intermediate output.)
Column | gives the name of xj.
State gives the state of the variable (LL if nonbasic on its lower bound, UL if nonbasic on its upper bound, EQ if nonbasic and fixed, FR if nonbasic and strictly between its bounds, BS if basic and SBS if superbasic).
A key is sometimes printed before State. Note that unless the optional parameter Scale Option=0 is specified, the tests for assigning a key are applied to the variables of the scaled problem.
A | Alternative optimum possible. The variable is nonbasic, but its reduced gradient is essentially zero. This means that if the variable were allowed to start moving away from its bound, there would be no change in the value of the objective function. The values of the other free variables might change, giving a genuine alternative solution. However, if there are any degenerate variables (labelled D), the actual change might prove to be zero, since one of them could encounter a bound immediately. In either case, the values of the Lagrange multipliers might also change.
D | Degenerate. The variable is basic or superbasic, but it is equal (or very close) to one of its bounds.
I | Infeasible. The variable is basic or superbasic and is currently violating one of its bounds by more than the value of the Feasibility Tolerance.
N | Not precisely optimal. The variable is nonbasic or superbasic. If the value of the reduced gradient for the variable exceeds the value of the optional parameter Optimality Tolerance, the solution would not be declared optimal because the reduced gradient for the variable would not be considered negligible.
Activity | is the value of xj at the final iterate.
Obj Gradient | is the value of gj at the final iterate. For FP problems, gj is set to zero.
Lower Bound | is the lower bound specified for the variable. None indicates that BL j≤-bigbnd.
Upper Bound | is the upper bound specified for the variable. None indicates that BU j≥bigbnd.
Reduced Gradnt | is the value of dj at the final iterate (see Section 11.3). For FP problems, dj is set to zero.
m + j | is the value of m+j.
Let vi denote the ith row of A, for i=1,2,…,m. The following describes the printout for each row (or constraint). A full stop (.) is printed for any numerical value that is zero.
Number | is the value of n+i. (This is used internally to refer to si in the intermediate output.)
Row | gives the name of νi.
State gives the state of vi (LL if active on its lower bound, UL if active on its upper bound, EQ if active and fixed, BS if inactive when si is basic and SBS if inactive when si is superbasic).
A key is sometimes printed before State. Note that unless the optional parameter Scale Option=0 is specified, the tests for assigning a key are applied to the variables of the scaled problem.
A | Alternative optimum possible. The variable is nonbasic, but its reduced gradient is essentially zero. This means that if the variable were allowed to start moving away from its bound, there would be no change in the value of the objective function. The values of the other free variables might change, giving a genuine alternative solution. However, if there are any degenerate variables (labelled D), the actual change might prove to be zero, since one of them could encounter a bound immediately. In either case, the values of the Lagrange multipliers might also change.
D | Degenerate. The variable is basic or superbasic, but it is equal (or very close) to one of its bounds.
I | Infeasible. The variable is basic or superbasic and is currently violating one of its bounds by more than the value of the Feasibility Tolerance.
N | Not precisely optimal. The variable is nonbasic or superbasic. If the value of the reduced gradient for the variable exceeds the value of the optional parameter Optimality Tolerance, the solution would not be declared optimal because the reduced gradient for the variable would not be considered negligible.
Activity | is the value of vi at the final iterate.
Slack Activity | is the value by which the row differs from its nearest bound. (For the free row (if any), it is set to Activity.)
Lower Bound | is the lower bound specified for the variable. None indicates that BL j≤-bigbnd.
Upper Bound | is the upper bound specified for the variable. None indicates that BU j≥bigbnd.
Dual Activity | is the value of the dual variable πi (the Lagrange multiplier for νi; see Section 11.3). For FP problems, πi is set to zero.
i | gives the index i of the ith row.
Numerical values are output with a fixed number of digits; they are not guaranteed to be accurate to this precision.
E04 Chapter Contents
E04 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


E04NLF/E04NLA : NAG Library, Mark 26

E04 Chapter Contents
E04 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

E04NLF/E04NLA

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
▸▿ 2 Specification
2.1 Specification for E04NLF
2.2 Specification for E04NLA
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

To supply optional parameters to E04NKF/E04NKA from an external file. More precisely, E04NLF must be used to supply optional parameters to E04NKF and E04NLA must be used to supply optional parameters to E04NKA.
E04NLA is a version of E04NLF that has additional arguments in order to make it safe for use in multithreaded applications (see Section 5). The initialization routine E04WBF must have been called before calling E04NLA.

2 Specification

2.1 Specification for E04NLF

SUBROUTINE E04NLF ( IOPTNS, INFORM)
INTEGER IOPTNS, INFORM

2.2 Specification for E04NLA

SUBROUTINE E04NLA ( IOPTNS, LWSAV, IWSAV, RWSAV, INFORM)
INTEGER | IOPTNS, IWSAV(380), INFORM
REAL (KIND=nag_wp) | RWSAV(285)
LOGICAL | LWSAV(20)

3 Description

E04NLF/E04NLA may be used to supply values for optional parameters to E04NKF/E04NKA. E04NLF/E04NLA reads an external file and each line of the file defines a single optional parameter. It is only necessary to supply values for those arguments whose values are to be different from their default values.
Each optional parameter is defined by a single character string, of up to 72 characters, consisting of one or more items. The items associated with a given option must be separated by spaces, or equals signs =. Alphabetic characters may be upper or lower case. The string
Print Level = 1
is an example of a string used to set an optional parameter. For each option the string contains one or more of the following items:
– | a mandatory keyword;
– | a phrase that qualifies the keyword;
– | a number that specifies an integer or real value. Such numbers may be up to 40 contiguous characters in Fortran's I, F, E or D formats, terminated by a space if this is not the last item on the line.
Blank strings and comments are ignored. A comment begins with an asterisk (*) and all subsequent characters in the string are regarded as part of the comment.
The file containing the options must start with Begin and must finish with End. An example of a valid options file is:
Begin * Example options file
   Print level = 5
End
For E04NLF each line of the file is normally printed as it is read, on the current advisory message unit (see X04ABF), but printing may be suppressed using the keyword Nolist. To suppress printing of Begin, Nolist must be the first option supplied as in the file:
Begin
   Nolist
   Print level = 5
End
Printing will automatically be turned on again after a call to E04NKF or E04NLF and may be turned on again at any time using the keyword List.
For E04NLA printing is turned off by default, but may be turned on at any time using the keyword List.
Optional parameter settings are preserved following a call to E04NKF/E04NKA and so the keyword Defaults is provided to allow you to reset all the optional parameters to their default values before a subsequent call to E04NKF/E04NKA.
A complete list of optional parameters, their abbreviations, synonyms and default values is given in Section 12 in E04NKF/E04NKA.

4 References

None.

5 Arguments

1:   IOPTNS – INTEGERInput
On entry: the unit number of the options file to be read.
Constraint: 0≤IOPTNS≤99.
2:   INFORM – INTEGEROutput
Note: for E04NLA, INFORM does not occur in this position in the argument list. See the additional arguments described below.
On exit: contains zero if the options file has been successfully read and a value>0 otherwise (see Section 6).
Note: the following are additional arguments for specific use with E04NLA. Users of E04NLF therefore need not read the remainder of this description.
2:   LWSAV 20 – LOGICAL arrayCommunication Array
3:   IWSAV 380 – INTEGER arrayCommunication Array
4:   RWSAV 285 – REAL (KIND=nag_wp) arrayCommunication Array
The arrays LWSAV, IWSAV and RWSAV must not be altered between calls to any of the routines E04NLA, E04NKA, E04NMA or E04WBF.
5:   INFORM – INTEGEROutput
Note: see the argument description for INFORM above.

6 Error Indicators and Warnings

INFORM=1
IOPTNS is not in the range 0,99.
INFORM=2
Begin was found, but end-of-file was found before End was found.
INFORM=3
end-of-file was found before Begin was found.
INFORM=4
Not used.
INFORM=5
One or more lines of the options file is invalid. Check that all keywords are neither ambiguous nor misspelt.

7 Accuracy

Not applicable.

8 Parallelism and Performance

E04NLF/E04NLA is not threaded in any implementation.

9 Further Comments

E04NMF/E04NMA may also be used to supply optional parameters to E04NKF/E04NKA.

10 Example

This example solves the same problem as the example for E04NKF/E04NKA, but in addition illustrates the use of E04NLF/E04NLA and E04NMF/E04NMA to set optional parameters for E04NKF/E04NKA.
In this example the options file read by E04NLF/E04NLA is appended to the data file for the program (see Section 10.2). It would usually be more convenient in practice to keep the data file and the options file separate.

10.1 Program Text

Note: the following programs illustrate the use of E04NLF and E04NLA.

Program Text (e04nlfe.f90)

Program Text (e04nlae.f90)

10.2 Program Data

Program Options (e04nlfe.opt)

Program Options (e04nlae.opt)

Program Data (e04nlfe.d)

Program Data (e04nlae.d)

10.3 Program Results

Program Results (e04nlfe.r)

Program Results (e04nlae.r)

E04 Chapter Contents
E04 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


E04NMF/E04NMA : NAG Library, Mark 26

E04 Chapter Contents
E04 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

E04NMF/E04NMA

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
▸▿ 2 Specification
2.1 Specification for E04NMF
2.2 Specification for E04NMA
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
10 Example

1 Purpose

To supply individual optional parameters to E04NKF/E04NKA. More precisely, E04NMF must be used to supply optional parameters to E04NKF and E04NMA must be used to supply optional parameters to E04NKA.
E04NMA is a version of E04NMF that has additional arguments in order to make it safe for use in multithreaded applications (see Section 5). The initialization routine E04WBF must have been called before calling E04NMA.

2 Specification

2.1 Specification for E04NMF

SUBROUTINE E04NMF ( STR)
CHARACTER(*) STR

2.2 Specification for E04NMA

SUBROUTINE E04NMA ( STR, LWSAV, IWSAV, RWSAV, INFORM)
INTEGER | IWSAV(380), INFORM
REAL (KIND=nag_wp) | RWSAV(285)
LOGICAL | LWSAV(20)
CHARACTER(*) | STR

3 Description

E04NMF/E04NMA may be used to supply values for optional parameters to E04NKF/E04NKA. It is only necessary to call E04NMF/E04NMA for those arguments whose values are to be different from their default values. One call to E04NMF/E04NMA sets one argument value.
Each optional parameter is defined by a single character string, of up to 72 characters, consisting of one or more items. The items associated with a given option must be separated by spaces, or equals signs =. Alphabetic characters may be upper or lower case. The string
Print Level = 1
is an example of a string used to set an optional parameter. For each option the string contains one or more of the following items:
– | a mandatory keyword;
– | a phrase that qualifies the keyword;
– | a number that specifies an integer or real value. Such numbers may be up to 40 contiguous characters in Fortran's I, F, E or D formats, terminated by a space if this is not the last item on the line.
Blank strings and comments are ignored. A comment begins with an asterisk (*) and all subsequent characters in the string are regarded as part of the comment.
For E04NMF, each user-specified option is normally printed as it is defined, on the current advisory message unit (see X04ABF), but this printing may be suppressed using the keyword Nolist. Thus the statement
 CALL E04NMF ('Nolist')
suppresses printing of this and subsequent options. Printing will automatically be turned on again after a call to E04NKF and may be turned on again at any time using the keyword List.
For E04NMA printing is turned off by default, but may be turned on at any time using the keyword List.
Optional parameter settings are preserved following a call to E04NKF/E04NKA and so the keyword Defaults is provided to allow you to reset all the optional parameters to their default values before a subsequent call to E04NKF/E04NKA.
A complete list of optional parameters, their abbreviations, synonyms and default values is given in Section 12 in E04NKF/E04NKA.

4 References

None.

5 Arguments

1:   STR – CHARACTER(*)Input
On entry: a single valid option string (as described in Section 3 and in Section 12 in E04NKF/E04NKA).
Note: the following are additional arguments for specific use with E04NMA. Users of E04NMF therefore need not read the remainder of this description.
2:   LWSAV 20 – LOGICAL arrayCommunication Array
3:   IWSAV 380 – INTEGER arrayCommunication Array
4:   RWSAV 285 – REAL (KIND=nag_wp) arrayCommunication Array
The arrays LWSAV, IWSAV and RWSAV must not be altered between calls to any of the routines E04NMA, E04NKA, E04NLA or E04WBF.
5:   INFORM – INTEGEROutput
On exit: contains zero if a valid option string has been supplied and a value>0 otherwise (see Section 6).

6 Error Indicators and Warnings

INFORM=5
The supplied option is invalid. Check that the keywords are neither ambiguous nor misspelt.

7 Accuracy

Not applicable.

8 Parallelism and Performance

E04NMF/E04NMA is not threaded in any implementation.

9 Further Comments

E04NLF/E04NLA may also be used to supply optional parameters to E04NKF/E04NKA.

10 Example

See Section 10 in E04NLF/E04NLA.
E04 Chapter Contents
E04 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


E04NPF : NAG Library, Mark 26

E04 Chapter Contents
E04 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

E04NPF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
10 Example

1 Purpose

E04NPF is used to initialize the routine E04NQF.

2 Specification

SUBROUTINE E04NPF ( CW, LENCW, IW, LENIW, RW, LENRW, IFAIL)
INTEGER | LENCW, IW(LENIW), LENIW, LENRW, IFAIL
REAL (KIND=nag_wp) | RW(LENRW)
CHARACTER(8) | CW(LENCW)

3 Description

E04NPF initializes the arrays CW, IW and RW for the routine E04NQF.

4 References

None.

5 Arguments

1:   CW LENCW – CHARACTER(8) arrayCommunication Array
2:   LENCW – INTEGERInput
On entry: the dimension of the array CW as declared in the (sub)program from which E04NPF is called.
Constraint: LENCW≥600, see routine E04NQF.
3:   IW LENIW – INTEGER arrayCommunication Array
4:   LENIW – INTEGERInput
On entry: the dimension of the array IW as declared in the (sub)program from which E04NPF is called.
Constraint: LENIW≥600, see routine E04NQF.
5:   RW LENRW – REAL (KIND=nag_wp) arrayCommunication Array
6:   LENRW – INTEGERInput
On entry: the dimension of the array RW as declared in the (sub)program from which E04NPF is called.
Constraint: LENRW≥600, see routine E04NQF.
7:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
One or more of the communication array lengths LENCW, LENIW or LENRW is less than 600.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

Not applicable.

8 Parallelism and Performance

E04NPF is not threaded in any implementation.

9 Further Comments

The time taken by E04NPF is negligible.

10 Example

See Section 10 in E04NQF and E04NRF.
E04 Chapter Contents
E04 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


E04NQF : NAG Library, Mark 26

E04 Chapter Contents
E04 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

E04NQF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.
Note: this routine uses optional parameters to define choices in the problem specification and in the details of the algorithm. If you wish to use default settings for all of the optional parameters, you need only read Sections 1 to 10 of this document. If, however, you wish to reset some or all of the settings please refer to Section 11 for a detailed description of the algorithm, to Section 12 for a detailed description of the specification of the optional parameters and to Section 13 for a detailed description of the monitoring information produced by the routine.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
▸▿ 9 Further Comments
9.1 Description of the Printed Output
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results
▸▿ 11 Algorithmic Details
11.1 Overview
11.2 Definition of the Working Set and Search Direction
11.3 Main Iteration
11.4 Miscellaneous
▸▿ 12 Optional Parameters
12.1 Description of the Optional Parameters
▸▿ 13 Description of Monitoring Information
13.1 Crash Statistics
13.2 Basis Factorization Statistics
13.3 Basis Map
▸▿ 13.4 Solution Output
13.4.1 The ROWS section
13.4.2 The COLUMNS Section
13.5 The Solution File
13.6 The Summary File

1 Purpose

E04NQF solves sparse linear programming or convex quadratic programming problems. The initialization routine E04NPF must have been called before calling E04NQF.

2 Specification

SUBROUTINE E04NQF ( START, QPHX, M, N, NE, NNAME, LENC, NCOLH, IOBJ, OBJADD, PROB, ACOL, INDA, LOCA, BL, BU, C, NAMES, HELAST, HS, X, PI, RC, NS, NINF, SINF, OBJ, CW, LENCW, IW, LENIW, RW, LENRW, CUSER, IUSER, RUSER, IFAIL)
INTEGER | M, N, NE, NNAME, LENC, NCOLH, IOBJ, INDA(NE), LOCA(N+1), HELAST(N+M), HS(N+M), NS, NINF, LENCW, IW(LENIW), LENIW, LENRW, IUSER(*), IFAIL
REAL (KIND=nag_wp) | OBJADD, ACOL(NE), BL(N+M), BU(N+M), C(max(1,LENC)), X(N+M), PI(M), RC(N+M), SINF, OBJ, RW(LENRW), RUSER(*)
CHARACTER(1) | START
CHARACTER(8) | PROB, NAMES(NNAME), CW(LENCW), CUSER(*)
EXTERNAL | QPHX
Before calling E04NQF or one of the option setting routines E04NRF, E04NSF, E04NTF or E04NUF, E04NPF must be called.
The specification for E04NPF is:
SUBROUTINE E04NPF ( CW, LENCW, IW, LENIW, RW, LENRW, IFAIL)
INTEGER | LENCW, IW(LENIW), LENIW, LENRW, IFAIL
REAL (KIND=nag_wp) | RW(LENRW)
CHARACTER(8) | CW(LENCW)
LENCW, LENIW and LENRW, the declared lengths of CW, IW and RW respectively, must satisfy:
  • LENCW≥600
  • LENIW≥600
  • LENRW≥600
The contents of the arrays CW, IW and RW must not be altered between calling routines E04NPF, E04NQF, E04NRF, E04NSF, E04NTF and E04NUF.
After calling E04NQF you can call one or both of the routines E04NXF or E04NYF to obtain the current value of an optional parameter.

3 Description

E04NQF is designed to solve large-scale linear or quadratic programming problems of the form:
minimize x∈Rn f x   subject to ​ l≤ x Ax ≤u, (1)
where x is an n-vector of variables, l and u are constant lower and upper bounds, A is an m by n sparse matrix and f x is a linear or quadratic objective function that may be specified in a variety of ways, depending upon the particular problem being solved. The optional parameter Maximize may be used to specify a problem in which f x is maximized instead of minimized.
Upper and lower bounds are specified for all variables and constraints. This form allows full generality in specifying various types of constraint. In particular, the jth constraint may be defined as an equality by setting lj=uj. If certain bounds are not present, the associated elements of l or u may be set to special values that are treated as -∞ or +∞.
The possible forms for the function f x are summarised in Table 1. The most general form for f x is
f x = q + cT x + 12 xT Hx = q + ∑ j=1 n cj xj + 12 ∑ i=1 n ∑ j=1 n xi H ij xj
where q is a constant, c is a constant n-vector and H is a constant symmetric n by n matrix with elements H ij . In this form, f is a quadratic function of x and (1) is known as a quadratic program (QP). E04NQF is suitable for all convex quadratic programs. The defining feature of a convex QP is that the matrix H must be positive semidefinite, i.e., it must satisfy xT H x ≥ 0 for all x. If not, f x is nonconvex and E04NQF will terminate with the error indicator IFAIL=11. If f x is nonconvex it may be more appropriate to call E04VHF instead.
Problem type | Objective function f x | Hessian matrix H
FP | Not applicable | q=c=H=0
LP | q+cT x | H=0
QP | q+cT x+12 xT Hx | Symmetric positive semidefinite
Table 1
Choices for the objective function f x
If H=0 , then f x = q+cT x and the problem is known as a linear program (LP). In this case, rather than defining an H with zero elements, you can define H to have no columns by setting NCOLH=0 (see Section 5).
If H=0 , q=0 , and c=0 , there is no objective function and the problem is a feasible point problem (FP), which is equivalent to finding a point that satisfies the constraints on x. In the situation where no feasible point exists, several options are available for finding a point that minimizes the constraint violations (see the description of the optional parameter Elastic Mode).
E04NQF is suitable for large LPs and QPs in which the matrix A is sparse, i.e., when the number of zero elements is sufficiently large that it is worthwhile using algorithms which avoid computations and storage involving zero elements. The matrix A is input to E04NQF by means of the three array arguments ACOL, INDA and LOCA. This allows you to specify the pattern of nonzero elements in A.
E04NQF exploits structure in H by requiring H to be defined implicitly in a subroutine that computes the product Hx for any given vector x. In many cases, the product Hx can be computed very efficiently for any given x, e.g., H may be a sparse matrix, or a sum of matrices of rank-one.
For problems in which A can be treated as a dense matrix, it is usually more efficient to use E04MFF/E04MFA, E04NCF/E04NCA or E04NFF/E04NFA.
There is considerable flexibility allowed in the definition of f x in Table 1. The vector c defining the linear term cT x can be input in three ways: as a sparse row of A; as an explicit dense vector c; or as both a sparse row and an explicit vector (in which case, cT x will be the sum of two linear terms). When stored in A, c is the IOBJth row of A, which is known as the objective row. The objective row must always be a free row of A in the sense that its lower and upper bounds must be -∞ and +∞ . Storing c as part of A is recommended if c is a sparse vector. Storing c as an explicit vector is recommended for a sequence of problems, each with a different objective (see arguments C and LENC).
The upper and lower bounds on the m elements of Ax are said to define the general constraints of the problem. Internally, E04NQF converts the general constraints to equalities by introducing a set of slack variables s, where s=s 1,s 2,…,sm T. For example, the linear constraint 5≤2 x 1+3 x 2≤+∞ is replaced by 2 x 1+3 x 2-s 1=0, together with the bounded slack 5≤s 1≤+∞. The problem defined by (1) can therefore be re-written in the following equivalent form:
minimize x ∈ Rn , s ∈ Rm f x  subject to ​ Ax-s=0 ,   l ≤ x s ≤u.
Since the slack variables s are subject to the same upper and lower bounds as the elements of Ax, the bounds on x and Ax can simply be thought of as bounds on the combined vector x,s. (In order to indicate their special role in QP problems, the original variables x are sometimes known as ‘column variables’, and the slack variables s are known as ‘row variables’.)
Each LP or QP problem is solved using a two-phase iterative procedure (in which the general constraints are satisfied throughout): a feasibility phase (Phase 1), in which the sum of infeasibilities with respect to the bounds on x and s is minimized to find a feasible point that satisfies all constraints within a specified feasibility tolerance; and an optimality phase (Phase 2), in which f x is minimized (or maximized) by constructing a sequence of iterates that lies within the feasible region.
Phase 1 involves solving a linear program of the form
Phase 1 |
 | minimize x, s, v, w ∑ j=1 n+m vj + wj
 | subject to ​ Ax-s=0 , l ≤ x s -v + w ≤ u , v ≥ 0 , w ≥ 0
which is equivalent to minimizing the sum of the constraint violations. If the constraints are feasible (i.e., at least one feasible point exists), eventually a point will be found at which both v and w are zero. Then the associated value of x,s satisfies the original constraints and is used as the starting point for the Phase 2 iterations for minimizing f x .
If the constraints are infeasible (i.e., v≠0 or w≠0 at the end of Phase 1), no solution exists for (1) and you have the option of either terminating or continuing in so-called elastic mode (see the discussion of the optional parameter Elastic Mode). In elastic mode, a ‘relaxed’ or ‘perturbed’ problem is solved in which f x is minimized while allowing some of the bounds to become ‘elastic’, i.e., to change from their specified values. Variables subject to elastic bounds are known as elastic variables. An elastic variable is free to violate one or both of its original upper or lower bounds. You are able to assign which bounds will become elastic if elastic mode is ever started (see the argument HELAST in Section 5).
To make the relaxed problem meaningful, E04NQF minimizes f x while (in some sense) finding the ‘smallest’ violation of the elastic variables. In the situation where all the variables are elastic, the relaxed problem has the form
Phase 2 (γ) |
 | minimize x, s, v, w f x + γ ∑ j=1 n+m vj + wj
 | subject to ​ Ax-s=0 , l ≤ x s -v + w ≤ u , v ≥ 0 , w ≥ 0 ,
where γ is a non-negative argument known as the elastic weight (see the description of the optional parameter Elastic Weight), and f x + γ ∑ j vj + wj is called the composite objective. In the more general situation where only a subset of the bounds are elastic, the v's and w's for the non-elastic bounds are fixed at zero.
The elastic weight can be chosen to make the composite objective behave like the original objective f x , the sum of infeasibilities, or anything in-between. If γ=0 , E04NQF will attempt to minimize f subject to the (true) upper and lower bounds on the non-elastic variables (and declare the problem infeasible if the non-elastic variables cannot be made feasible).
At the other extreme, choosing γ sufficiently large will have the effect of minimizing the sum of the violations of the elastic variables subject to the original constraints on the non-elastic variables. Choosing a large value of the elastic weight is useful for defining a ‘least-infeasible’ point for an infeasible problem.
In Phase 1 and elastic mode, all calculations involving v and w are done implicitly in the sense that an elastic variable xj is allowed to violate its lower bound (say) and an explicit value of v can be recovered as vj = lj - xj .
A constraint is said to be active or binding at x if the associated element of either x or Ax is equal to one of its upper or lower bounds. Since an active constraint in Ax has its associated slack variable at a bound, the status of both simple and general upper and lower bounds can be conveniently described in terms of the status of the variables x,s. A variable is said to be nonbasic if it is temporarily fixed at its upper or lower bound. It follows that regarding a general constraint as being active is equivalent to thinking of its associated slack as being nonbasic.
At each iteration of an active-set method, the constraints Ax-s=0 are (conceptually) partitioned into the form
B xB+S xS+N xN=0,
where xN consists of the nonbasic elements of x,s and the basis matrix B is square and nonsingular. The elements of xB and xS are called the basic and superbasic variables respectively; with xN they are a permutation of the elements of x and s. At a QP solution, the basic and superbasic variables will lie somewhere between their upper or lower bounds, while the nonbasic variables will be equal to one of their bounds. At each iteration, xS is regarded as a set of independent variables that are free to move in any desired direction, namely one that will improve the value of the objective function (or sum of infeasibilities). The basic variables are then adjusted in order to ensure that x,s continues to satisfy Ax-s=0. The number of superbasic variables (nS say) therefore indicates the number of degrees of freedom remaining after the constraints have been satisfied. In broad terms, nS is a measure of how nonlinear the problem is. In particular, nS will always be zero for FP and LP problems.
If it appears that no improvement can be made with the current definition of B, S and N, a nonbasic variable is selected to be added to S, and the process is repeated with the value of nS increased by one. At all stages, if a basic or superbasic variable encounters one of its bounds, the variable is made nonbasic and the value of nS is decreased by one.
Associated with each of the m equality constraints Ax-s=0 is a dual variable πi. Similarly, each variable in x,s has an associated reduced gradient dj (also known as a reduced cost). The reduced gradients for the variables x are the quantities g-AT π, where g is the gradient of the QP objective function, and the reduced gradients for the slack variables s are the dual variables π. The QP subproblem is optimal if dj≥0 for all nonbasic variables at their lower bounds, dj≤0 for all nonbasic variables at their upper bounds and dj=0 for all superbasic variables. In practice, an approximate QP solution is found by slightly relaxing these conditions on dj (see the description of the optional parameter Optimality Tolerance).
The process of computing and comparing reduced gradients is known as pricing (a term first introduced in the context of the simplex method for linear programming). To ‘price’ a nonbasic variable xj means that the reduced gradient dj associated with the relevant active upper or lower bound on xj is computed via the formula dj=gj-ajT π, where aj is the jth column of A -I . (The variable selected by such a process and the corresponding value of dj (i.e., its reduced gradient) are the quantities +SBS and dj in the monitoring file output; see Section 9.1.) If A has significantly more columns than rows (i.e., n≫m), pricing can be computationally expensive. In this case, a strategy known as partial pricing can be used to compute and compare only a subset of the djs.
E04NQF is based on SQOPT, which is part of the SNOPT package described in Gill et al. (2005a). It uses stable numerical methods throughout and includes a reliable basis package (for maintaining sparse LU factors of the basis matrix B), a practical anti-degeneracy procedure, efficient handling of linear constraints and bounds on the variables (by an active-set strategy), as well as automatic scaling of the constraints. Further details can be found in Section 11.

4 References

Fourer R (1982) Solving staircase linear programs by the simplex method Math. Programming 23 274–313
Gill P E and Murray W (1978) Numerically stable methods for quadratic programming Math. Programming 14 349–372
Gill P E, Murray W and Saunders M A (1995) User's guide for QPOPT 1.0: a Fortran package for quadratic programming Report SOL 95-4 Department of Operations Research, Stanford University
Gill P E, Murray W and Saunders M A (2005a) Users' guide for SQOPT 7: a Fortran package for large-scale linear and quadratic programming Report NA 05-1 Department of Mathematics, University of California, San Diego http://www.ccom.ucsd.edu/~peg/papers/sqdoc7.pdf
Gill P E, Murray W and Saunders M A (2005b) Users' guide for SNOPT 7.1: a Fortran package for large-scale linear nonlinear programming Report NA 05-2 Department of Mathematics, University of California, San Diego http://www.ccom.ucsd.edu/~peg/papers/sndoc7.pdf
Gill P E, Murray W, Saunders M A and Wright M H (1987) Maintaining LU factors of a general sparse matrix Linear Algebra and its Applics. 88/89 239–270
Gill P E, Murray W, Saunders M A and Wright M H (1989) A practical anti-cycling procedure for linearly constrained optimization Math. Programming 45 437–474
Gill P E, Murray W, Saunders M A and Wright M H (1991) Inertia-controlling methods for general quadratic programming SIAM Rev. 33 1–36
Hall J A J and McKinnon K I M (1996) The simplest examples where the simplex method cycles and conditions where EXPAND fails to prevent cycling Report MS 96–100 Department of Mathematics and Statistics, University of Edinburgh

5 Arguments

The first n entries of the arguments BL, BU, HS and X refer to the variables x. The last m entries refer to the slacks s.
1:   START – CHARACTER(1)Input
On entry: indicates how a starting basis (and certain other items) will be obtained.
START='C'
Requests that an internal Crash procedure be used to choose an initial basis, unless a Basis file is provided via optional parameters Old Basis File, Insert File or Load File.
START='B'
Is the same as START='C' but is more meaningful when a Basis file is given.
START='W'
Means that a basis is already defined in HS and a start point is already defined in X (probably from an earlier call).
Constraint: START='B', 'C' or 'W'.
2:   QPHX – SUBROUTINE, supplied by the NAG Library or the user.External Procedure
For QP problems, you must supply a version of QPHX to compute the matrix product Hx for a given vector x. If H has rows and columns of zeros, it is most efficient to order x so that the nonlinear variables appear first. For example, if x=y,z T and only y enters the objective quadratically then
H x= H 1 0 0 0 y z = H 1 y 0 . (2)
In this case, NCOLH should be the dimension of y, and QPHX should compute H 1 y. For FP and LP problems, QPHX will never be called by E04NQF and hence QPHX may be the dummy routine E04NSH.
The specification of QPHX is:
SUBROUTINE QPHX ( NCOLH, X, HX, NSTATE, CUSER, IUSER, RUSER)
INTEGER | NCOLH, NSTATE, IUSER(*)
REAL (KIND=nag_wp) | X(NCOLH), HX(NCOLH), RUSER(*)
CHARACTER(8) | CUSER(*)
1:   NCOLH – INTEGERInput
On entry: this is the same argument NCOLH as supplied to E04NQF.
2:   X NCOLH – REAL (KIND=nag_wp) arrayInput
On entry: the first NCOLH elements of the vector x.
3:   HX NCOLH – REAL (KIND=nag_wp) arrayOutput
On exit: the product Hx. If NCOLH is less than the input argument N, Hx is really the product H 1 y in (2).
4:   NSTATE – INTEGERInput
On entry: allows you to save computation time if certain data must be read or calculated only once. To preserve this data for a subsequent calculation place it in one of CUSER, RUSER or IUSER .
NSTATE=1
E04NQF is calling QPHX for the first time.
NSTATE=0
There is nothing special about the current call of QPHX.
NSTATE≥2
E04NQF is calling QPHX for the last time. This argument setting allows you to perform some additional computation on the final solution.
NSTATE=2
The current x is optimal.
NSTATE=3
The problem appears to be infeasible.
NSTATE=4
The problem appears to be unbounded.
NSTATE=5
The iterations limit was reached.
5:   CUSER* – CHARACTER(8) arrayUser Workspace
6:   IUSER* – INTEGER arrayUser Workspace
7:   RUSER* – REAL (KIND=nag_wp) arrayUser Workspace
QPHX must either be a module subprogram USEd by, or declared as EXTERNAL in, the (sub)program from which E04NQF is called. Arguments denoted as Input must not be changed by this procedure.
3:   M – INTEGERInput
On entry: m, the number of general linear constraints (or slacks). This is the number of rows in the linear constraint matrix A, including the free row (if any; see IOBJ). Note that A must have at least one row. If your problem has no constraints, or only upper or lower bounds on the variables, then you must include a dummy row with sufficiently wide upper and lower bounds (see also ACOL, INDA and LOCA).
Constraint: M≥1.
4:   N – INTEGERInput
On entry: n, the number of variables (excluding slacks). This is the number of columns in the linear constraint matrix A.
Constraint: N≥1.
5:   NE – INTEGERInput
On entry: the number of nonzero elements in A.
Constraint: 1≤NE≤N×M.
6:   NNAME – INTEGERInput
On entry: the number of column (i.e., variable) and row names supplied in the array NAMES.
NNAME=1
There are no names. Default names will be used in the printed output.
NNAME=N+M
All names must be supplied.
Constraint: NNAME=1 or N+M.
7:   LENC – INTEGERInput
On entry: the number of elements in the constant objective vector c.
If LENC>0, the first LENC elements of x belong to variables corresponding to the constant objective term c.
Constraint: 0≤LENC≤N.
8:   NCOLH – INTEGERInput
On entry: nH, the number of leading nonzero columns of the Hessian matrix H. For FP and LP problems, NCOLH must be set to zero.
The first NCOLH elements of x belong to variables corresponding to the nonzero block of the QP Hessian.
Constraint: 0≤NCOLH≤N.
9:   IOBJ – INTEGERInput
On entry: if IOBJ>0, row IOBJ of A is a free row containing the nonzero elements of the vector c appearing in the linear objective term cT x.
If IOBJ=0, there is no free row, and the linear objective vector should be supplied in array C.
Constraint: 0≤IOBJ≤M.
10:   OBJADD – REAL (KIND=nag_wp)Input
On entry: the constant q, to be added to the objective for printing purposes. Typically OBJADD=0.0E0.
11:   PROB – CHARACTER(8)Input
On entry: the name for the problem. It is used in the printed solution and in some routines that output Basis files. A blank name may be used.
12:   ACOL NE – REAL (KIND=nag_wp) arrayInput
On entry: the nonzero elements of A, ordered by increasing column index. Note that all elements must be assigned a value in the calling program.
13:   INDA NE – INTEGER arrayInput
On entry: INDA i must contain the row index of the nonzero element stored in ACOL i, for i=1,2,…,NE. Thus a pair of values ACOL i,INDA i contains a matrix element and its corresponding row index.
Note that the row indices for a column may be supplied in any order.
Constraint: 1≤INDA i≤M, for i=1,2,…,NE.
14:   LOCA N+1 – INTEGER arrayInput
On entry: LOCA j must contain the index in ACOL and INDA of the start of the jth column, for j=1,2,…,N. Thus for j=1:N, the entries of column j are held in ACOL k:l and their corresponding row indices are in INDA k:l, where k=LOCA j and l=LOCA j+1-1 . To specify the jth column as empty, set LOCA j=LOCA j+1. Note that the first and last elements of LOCA must be LOCA 1=1 and LOCA N+1=NE+1. If your problem has no constraints, or just bounds on the variables, you may include a dummy ‘free’ row with a single (zero) element by setting NE=1, ACOL 1=0.0, INDA 1=1, LOCA 1=1, and LOCA j=2, for j=2:N+1. This row is made ‘free’ by setting its bounds to be BL N+1=-bigbnd and BU N+1=bigbnd, where bigbnd is the value of the optional parameter Infinite Bound Size.
Constraints:
  • LOCA 1=1;
  • LOCA j≥1, for j=2,3,…,N;
  • LOCA N+1=NE+1;
  • 0≤LOCA j+1-LOCA j≤M, for j=1,2,…,N.
15:   BL N+M – REAL (KIND=nag_wp) arrayInput
On entry: l, the lower bounds for all the variables and general constraints, in the following order. The first N elements of BL must contain the bounds on the variables x, and the next M elements the bounds for the general linear constraints Ax (which, equivalently, are the bounds for the slacks, s) and the free row (if any). To fix the jth variable, set BL j=BU j=β, say, where β<bigbnd . To specify a nonexistent lower bound (i.e., lj=-∞), set BL j≤-bigbnd. Here, bigbnd is the value of the optional parameter Infinite Bound Size. To specify the jth constraint as an equality, set BL N+j=BU N+j=β, say, where β<bigbnd. Note that the lower bound corresponding to the free row must be set to -∞ and stored in BL N+IOBJ.
Constraint: if IOBJ>0, BL N+IOBJ≤-bigbnd
(See also the description for BU.)
16:   BU N+M – REAL (KIND=nag_wp) arrayInput
On entry: u, the upper bounds for all the variables and general constraints, in the following order. The first N elements of BU must contain the bounds on the variables x, and the next M elements the bounds for the general linear constraints Ax (which, equivalently, are the bounds for the slacks, s) and the free row (if any). To specify a nonexistent upper bound (i.e., uj=+∞), set BU j≥bigbnd. Note that the upper bound corresponding to the free row must be set to +∞ and stored in BU N+IOBJ.
Constraints:
  • if IOBJ>0, BU N+IOBJ≥bigbnd;
  • otherwise BL i≤BU i.
17:   C max 1,LENC – REAL (KIND=nag_wp) arrayInput
Note: the dimension of the array C must be at least max 1,LENC if IOBJ≠0, and at least 1 otherwise.
On entry: contains the explicit objective vector c (if any). If the problem is of type FP, or if LENC=0, then C is not referenced. (In that case, C may be dimensioned (1), or it could be any convenient array.)
18:   NAMES NNAME – CHARACTER(8) arrayInput
On entry: the optional column and row names, respectively.
If NNAME=1, NAMES is not referenced and the printed output will use default names for the columns and rows.
If NNAME=N+M, the first N elements must contain the names for the columns and the next M elements must contain the names for the rows. Note that the name for the free row (if any) must be stored in NAMES N+IOBJ.
19:   HELAST N+M – INTEGER arrayInput
On entry: defines which variables are to be treated as being elastic in elastic mode. The allowed values of HELAST are:
HELAST j | Status in elastic mode
0 | Variable j is non-elastic and cannot be infeasible
1 | Variable j can violate its lower bound
2 | Variable j can violate its upper bound
3 | Variable j can violate either its lower or upper bound
HELAST need not be assigned if optional parameter Elastic Mode=0.
Constraint: if Elastic Mode≠0, HELAST j=0,1,2,3, for j=1,2,…,N+M.
20:   HS N+M – INTEGER arrayInput/Output
On entry: if START='C' or 'B', and a Basis file of some sort is to be input (see the description of the optional parameters Old Basis File, Insert File or Load File), then HS and X need not be set at all.
If START='C' or 'B' and there is no Basis file, the first N elements of HS and X must specify the initial states and values, respectively, of the variables x. (The slacks s need not be initialized.) An internal Crash procedure is then used to select an initial basis matrix B. The initial basis matrix will be triangular (neglecting certain small elements in each column). It is chosen from various rows and columns of A -I . Possible values for HS j are as follows:
HS j | State of X j during Crash procedure
0 or 1 | Eligible for the basis
2 | Ignored
3 | Eligible for the basis (given preference over 0 or 1)
4 or 5 | Ignored
If nothing special is known about the problem, or there is no wish to provide special information, you may set HS j=0 and X j=0.0, for j=1,2,…,N. All variables will then be eligible for the initial basis. Less trivially, to say that the jth variable will probably be equal to one of its bounds, set HS j=4 and X j=BL j or HS j=5 and X j=BU j as appropriate.
Following the Crash procedure, variables for which HS j=2 are made superbasic. Other variables not selected for the basis are then made nonbasic at the value X j if BL j≤X j≤BU j, or at the value BL j or BU j closest to X j.
If START='W', HS and X must specify the initial states and values, respectively, of the variables and slacks x,s. If E04NQF has been called previously with the same values of N and M, HS already contains satisfactory information.
Constraints:
  • if START='C' or 'B', 0≤HS j≤5, for j=1,2,…,N;
  • if START='W', 0≤HS j≤3, for j=1,2,…,N+M.
On exit: the final states of the variables and slacks x,s. The significance of each possible value of HS j is as follows:
HS j | State of variable j | Normal value of X j
0 | Nonbasic | BL j
1 | Nonbasic | BU j
2 | Superbasic | Between BL j and BU j
3 | Basic | Between BL j and BU j
If NINF=0, basic and superbasic variables may be outside their bounds by as much as the value of the optional parameter Feasibility Tolerance. Note that unless the optional parameter Scale Option=0 is specified, the optional parameter Feasibility Tolerance applies to the variables of the scaled problem. In this case, the variables of the original problem may be as much as 0.1 outside their bounds, but this is unlikely unless the problem is very badly scaled.
Very occasionally some nonbasic variables may be outside their bounds by as much as the optional parameter Feasibility Tolerance, and there may be some nonbasic variables for which X j lies strictly between its bounds.
If NINF>0, some basic and superbasic variables may be outside their bounds by an arbitrary amount (bounded by SINF if Scale Option=0).
21:   X N+M – REAL (KIND=nag_wp) arrayInput/Output
On entry: the initial values of the variables x , and, if START='W', the slacks s , i.e., x,s. (See the description for argument HS.)
On exit: the final values of the variables and slacks x,s.
22:   PI M – REAL (KIND=nag_wp) arrayOutput
On exit: contains the dual variables π (a set of Lagrange multipliers (shadow prices) for the general constraints).
23:   RC N+M – REAL (KIND=nag_wp) arrayOutput
On exit: contains the reduced costs, g-A-I T π. The vector g is the gradient of the objective if X is feasible, otherwise it is the gradient of the Phase 1 objective. In the former case, g i=0, for i=N+1:M, hence RC N+1:M =π.
24:   NS – INTEGERInput/Output
On entry: nS, the number of superbasics. For QP problems, NS need not be specified if START='C', but must retain its value from a previous call when START='W'. For FP and LP problems, NS need not be initialized.
On exit: the final number of superbasics. This will be zero for FP and LP problems.
25:   NINF – INTEGEROutput
On exit: the number of infeasibilities.
26:   SINF – REAL (KIND=nag_wp)Output
On exit: the sum of the scaled infeasibilities. This will be zero if NINF=0, and is most meaningful when Scale Option=0.
27:   OBJ – REAL (KIND=nag_wp)Output
On exit: the value of the objective function.
If NINF=0, OBJ includes the quadratic objective term 12 xT Hx (if any).
If NINF>0, OBJ is just the linear objective term cT x (if any).
For FP problems, OBJ is set to zero.
Note that OBJ does not include contributions from the constant term OBJADD or the objective row, if any.
28:   CW LENCW – CHARACTER(8) arrayCommunication Array
29:   LENCW – INTEGERInput
On entry: the dimension of the array CW as declared in the (sub)program from which E04NQF is called.
Constraint: LENCW≥600.
30:   IW LENIW – INTEGER arrayCommunication Array
31:   LENIW – INTEGERInput
On entry: the dimension of the array IW as declared in the (sub)program from which E04NQF is called.
Constraint: LENIW≥600.
32:   RW LENRW – REAL (KIND=nag_wp) arrayCommunication Array
33:   LENRW – INTEGERInput
On entry: the dimension of the array RW as declared in the (sub)program from which E04NQF is called.
Constraint: LENRW≥600.
34:   CUSER* – CHARACTER(8) arrayUser Workspace
CUSER is not used by E04NQF, but is passed directly to QPHX and may be used to pass information to this routine as an alternative to using COMMON global variables.
35:   IUSER* – INTEGER arrayUser Workspace
IUSER is not used by E04NQF, but is passed directly to QPHX and may be used to pass information to this routine as an alternative to using COMMON global variables.
36:   RUSER* – REAL (KIND=nag_wp) arrayUser Workspace
RUSER is not used by E04NQF, but is passed directly to QPHX and may be used to pass information to this routine as an alternative to using COMMON global variables.
37:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, because for this routine the values of the output arguments may be useful even if IFAIL≠0 on exit, the recommended value is -1. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).
E04NQF returns with IFAIL=0 if the reduced gradient (rgNorm; see Section 9.1) is negligible, the Lagrange multipliers (Lagr Mult; see Section 9.1) are optimal, x satisfies the constraints to the accuracy requested by the value of the optional parameter Feasibility Tolerance and the reduced Hessian factor R (see Section 11.2) is nonsingular.

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Note: E04NQF may return useful information for one or more of the following detected errors or warnings.
Errors or warnings detected by the routine:
IFAIL=1
On entry, LENCW=value.
Constraint: LENCW≥600.
On entry, LENIW=value.
Constraint: LENIW≥600.
On entry, LENRW=value.
Constraint: LENRW≥600.
The initialization routine E04NPF has not been called.
IFAIL=2
An error has occurred in the basis package, perhaps indicating incorrect setup of arrays INDA and LOCA. Set the optional parameter Print File and examine the output carefully for further information.
Basis file dimensions do not match this problem.
On entry, bounds BL and BU for value are equal and infinite: BL=BU=value and infbnd=value.
On entry, bounds BL and BU for value are equal and infinite. BL=BU=value and infbnd=value.
On entry, bounds for value are inconsistent. BL=value and BU=value.
On entry, IOBJ=value and M=value.
Constraint: 0≤IOBJ≤M.
On entry, LENC=value and N=value.
Constraint: 0≤LENC≤N.
On entry, LOCA 1=value, LOCA value=value, NE=value.
Constraint: LOCA 1=1 or LOCA value=NE+1.
On entry, M=value.
Constraint: M≥value.
On entry, N=value.
Constraint: N≥value.
On entry, NCOLH=value and N=value.
Constraint: 0≤NCOLH≤N.
On entry, NE=value, N=value and M=value.
Constraint: 1≤NE≤N×M.
On entry, NE is not equal to the number of nonzeros in ACOL. NE=value, nonzeros in ACOL=value.
On entry, NNAME=value, N=value and M=value.
Constraint: NNAME=1 or N+M.
On entry, row index value in INDA value is outside the range 1 to M=value.
On entry, START=value.
Constraint: START='B', 'C' or 'W'.
IFAIL=3
The requested accuracy could not be achieved.
IFAIL=4
Weak solution found – the solution is not unique.
IFAIL=5
The linear constraints appear to be infeasible.
The problem appears to be infeasible. Infeasibilites have been minimized.
The problem appears to be infeasible. Nonlinear infeasibilites have been minimized.
The problem appears to be infeasible. The linear equality constraints could not be satisfied.
The problem is infeasible. The general constraints cannot all be satisfied simultaneously to within the value of the optional parameter Feasibility Tolerance.
Feasibility is measured with respect to the upper and lower bounds on the variables and slacks. The message tells us that among all the points satisfying the general constraints Ax-s=0 , there is apparently no point that satisfies the bounds on x and s . Violations as small as the Feasibility Tolerance are ignored, but at least one component of x or s violates a bound by more than the tolerance.
Note: although the objective function is the sum of infeasibilities (when NINF>0), this sum will not necessarily have been minimized when Elastic Mode = 1 .
If Elastic Mode ≠ 0 , E04NQF will optimize the QP objective and the sum of infeasibilities, suitably weighted using the optional parameter Elastic Mode. The routine will tend to determine a ‘good’ infeasible point if the elastic weight is sufficiently large.
IFAIL=6
The problem appears to be unbounded. The constraint violation limit has been reached.
The problem appears to be unbounded. The objective function is unbounded.
The problem is unbounded (or badly scaled). For a minimization problem, the objective function is not bounded below in the feasible region.
For linear problems, unboundedness is detected by the simplex method when a nonbasic variable can be increased or decreased by an arbitrary amount without causing a basic variable to violate a bound. Consider adding an upper or lower bound to the variable. Also, examine the constraints that have nonzeros in the associated column, to see if they have been formulated as intended.
Very rarely, the scaling of the problem could be so poor that numerical error will give an erroneous indication of unboundedness. Consider using the optional parameter Scale Option.
IFAIL=7
Iteration limit reached.
Major iteration limit reached.
Too many iterations. The value of the optional parameter Iterations Limit is too small.
The Iterations limit was exceeded before the required solution could be found. Check the iteration log to be sure that progress was being made. If so, restart the run using a Basis file that was saved at the end of the run.
IFAIL=8
The value of the optional parameter Superbasics Limit is too small.
The current set of basic and superbasic variables have been optimized as much as possible and a pricing operation is necessary to continue, but there are already Superbasics Limit superbasics (and no room for any more).
In general, raise the Superbasics Limit s by a reasonable amount, bearing in mind the storage needed for reduced Hessian (see Section 11.2). (The Reduced Hessian Dimension h will also increase to s unless specified otherwise, and the associated storage will be about 12 s 2 words.) In some cases you may have to set h<s to conserve storage, but beware that the rate of convergence will probably fall off severely.
IFAIL=9
The basis is singular after several attempts to factorize it (and add slacks where necessary).
Either the problem is badly scaled or the value of the optional parameter LU Factor Tolerance is too large.
IFAIL=10
Numerical difficulties have been encountered and no further progress can be made.
Numerical error in trying to satisfy the general constraints. The basis is very ill-conditioned.
An LU factorization of the basis has just been obtained and used to recompute the basic variables xB , given the present values of the superbasic and nonbasic variables. However, a row check has revealed that the resulting solution does not satisfy the current constraints Ax-s=0 sufficiently well.
This probably means that the current basis is very ill-conditioned. Request the Scale Option if there are any linear constraints and variables.
For certain highly structured basis matrices (notably those with band structure), a systematic growth may occur in the factor U . Consult the description of Umax, Umin and Growth in Section 13, and set the optional parameter LU Factor Tolerance to 2.0 (or possibly even smaller, but not less than 1.0).
IFAIL=11
Error in QPHX: the QP Hessian is indefinite.
An indefinite matrix was detected during the computation of the reduced Hessian factor R (see Section 11.2). This may be caused by H being indefinite. Check also that QPHX has been coded correctly and that all relevant elements of Hx have been assigned their correct values. If QPHX is coded correctly and H is positive semidefinite, the failure may be caused by ill conditioning. Try reducing the values of the optional parameters LU Factor Tolerance and LU Update Tolerance. If there are very large values in H, check the scaling of the variables and constraints.
IFAIL=12
Internal memory allocation failed when attempting to obtain workspace sizes value, value and value. Please contact NAG.
IFAIL=13
Internal memory allocation was insufficient. Please contact NAG.
IFAIL=14
An error has occurred in the basis package, perhaps indicating incorrect setup of arrays INDA and LOCA. Set the optional parameter Print File and examine the output carefully for further information.
IFAIL=15
An unexpected error has occurred. Set the optional parameter Print File and examine the output carefully for further information.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

E04NQF implements a numerically stable active-set strategy and returns solutions that are as accurate as the condition of the problem warrants on the machine.

8 Parallelism and Performance

E04NQF makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

This section contains a description of the printed output.

9.1 Description of the Printed Output

If Print Level > 0 , one line of information is output to the Print File every k th iteration, where k is the specified Print Frequency. A heading is printed before the first such line following a basis factorization. The heading contains the items described below. In this description, a pricing operation is defined to be the process by which one or more nonbasic variables are selected to become superbasic (in addition to those already in the superbasic set). The variable selected will be denoted by jq. If the problem is purely linear, variable jq will usually become basic immediately (unless it should happen to reach its opposite bound and return to the nonbasic set).
If optional parameter Partial Price is in effect, variable jq is selected from App or Ipp , the ppth segments of the constraint matrix A -I .
Label | Description
Itn | is the iteration count.
pp | is the partial-price indicator. The variable selected by the last pricing operation came from the ppth partition of A and -I. Note that pp is reset to zero whenever the basis is refactorized.
dj is the value of the reduced gradient (or reduced cost) for the variable selected by the pricing operation at the start of the current iteration.
Algebraically, dj is dj = gj - πT aj , for j = jq , where gj is the gradient of the current objective function, π is the vector of dual variables, and aj is the j th column of the constraint matrix A -I .
Note that dj is the norm of the reduced-gradient vector at the start of the iteration, just after the pricing operation.
+SBS | is the variable jq selected by the pricing operation to be added to the superbasic set.
-SBS | is the variable chosen to leave the superbasic set. It has become basic if the entry under -B is nonzero, otherwise it becomes nonbasic.
-BS | is the variable removed from the basis to become nonbasic.
Step | is the value of the step length α taken along the current search direction p. The variables x have just been changed to x+αp. If a variable is made superbasic during the current iteration (i.e., +SBS is positive), Step will be the step to the nearest bound. During the optimality phase, the step can be greater than unity only if the reduced Hessian is not positive definite.
Pivot | is the rth element of a vector y satisfying By=aq whenever aq (the qth column of the constraint matrix A -I replaces the rth column of the basis matrix B. Wherever possible, Step is chosen so as to avoid extremely small values of Pivot (since they may cause the basis to be nearly singular). In extreme cases, it may be necessary to increase the value of the optional parameter Pivot Tolerance to exclude very small elements of y from consideration during the computation of Step.
nInf | is the number of violated constraints (infeasibilities) before the present iteration. This number will not increase unless iterations are in elastic mode.
sInf | is the sum of infeasibilities before the present iteration. It will usually decrease at each nonzero step, but if nInf decreases by 2 or more, sInf may occasionally increase. However, in elastic mode it will decrease monotonically.
Objective | is the value of the current objective function after the present iteration. Note, if Elastic Mode is 2, the heading is Composite Obj.
L+U | L is the number of nonzeros in the basis factor L. Immediately after a basis factorization B=LU, L contains lenL (see Section 13). Further nonzeros are added to L when various columns of B are later replaced. (Thus, L increases monotonically.) U is the number of nonzeros in the basis factor U. Immediately after a basis factorization B=LU, U contains lenU (see Section 13). As columns of B are replaced, the matrix U is maintained explicitly (in sparse form). The value of U may fluctuate up or down; in general, it will tend to increase.
ncp | is the number of compressions required to recover workspace in the data structure for U. This includes the number of compressions needed during the previous basis factorization. Normally, ncp should increase very slowly.
The following will be output if the problem is QP or if the superbasic set is non-empty.
Label | Description
rgNorm | is the largest reduced-gradient among the superbasic variables after the current iteration. During the optimality phase, this will be approximately zero after a unit step.
nS | is the current number of superbasic variables.
condHz | is a lower bound on the condition number of the reduced Hessian (see Section 11.2). The larger this number, the more difficult the problem. Attention should be given to the scaling of the variables and the constraints to guard against high values of condHz.

10 Example

This example minimizes the quadratic function f x=cT x+12 xT Hx, where
c=-200.0,-2000.0,-2000.0,-2000.0,-2000.0,400.0,400.0 T
H= 2 0 0 0 0 0 0 0 2 0 0 0 0 0 0 0 2 2 0 0 0 0 0 2 2 0 0 0 0 0 0 0 2 0 0 0 0 0 0 0 2 2 0 0 0 0 0 2 2
subject to the bounds
00 0≤x 1≤0 200 00 0≤x 2≤2500 400≤x 3≤0 800 100≤x 4≤0 700 00 0≤x 5≤1500 00 0≤x 6≤1500 00 0≤x 7≤1500
and to the linear constraints
x 1 + x 2 + x 3 + x 4 + x 5 + x 6 + x 7 = 2000 0.15 x 1 + 0.04 x 2 + 0.02 x 3 + 0.04 x 4 + 0.02 x 5 + 0.01 x 6 + 0.03 x 7 ≤ 60 0.03 x 1 + 0.05 x 2 + 0.08 x 3 + 0.02 x 4 + 0.06 x 5 + 0.01 x 6 + 0.03 x 7 ≤ 100 0.02 x 1 + 0.04 x 2 + 0.01 x 3 + 0.02 x 4 + 0.02 x 5 ≤ 40 0.02 x 1 + 0.03 x 2 + 0.01 x 5 ≤ 30 1500 ≤ 0.70 x 1 + 0.75 x 2 + 0.80 x 3 + 0.75 x 4 + 0.80 x 5 + 0.97 x 6 250 ≤ 0.02 x 1 + 0.06 x 2 + 0.08 x 3 + 0.12 x 4 + 0.02 x 5 + 0.01 x 6 + 0.97 x 7 ≤ 300
The initial point, which is infeasible, is
x 0=0.0,0.0,0.0,0.0,0.0,0.0,0.0 T.
The optimal solution (to five figures) is
x*=0.0,349.40,648.85,172.85,407.52,271.36,150.02 T.
One bound constraint and four linear constraints are active at the solution. Note that the Hessian matrix H is positive semidefinite.

10.1 Program Text

Program Text (e04nqfe.f90)

10.2 Program Data

Program Data (e04nqfe.d)

10.3 Program Results

Program Results (e04nqfe.r)

Note: the remainder of this document is intended for more advanced users. Section 11 contains a detailed description of the algorithm which may be needed in order to understand Sections 12 and 13. Section 12 describes the optional parameters which may be set by calls to E04NRF, E04NSF, E04NTF and/or E04NUF. Section 13 describes the quantities which can be requested to monitor the course of the computation.

11 Algorithmic Details

This section contains a detailed description of the method used by E04NQF.

11.1 Overview

E04NQF is based on an inertia-controlling method that maintains a Cholesky factorization of the reduced Hessian (see below). The method is similar to that of Gill and Murray (1978), and is described in detail by Gill et al. (1991). Here we briefly summarise the main features of the method. Where possible, explicit reference is made to the names of variables that are arguments of the routine or appear in the printed output.
The method used has two distinct phases: finding an initial feasible point by minimizing the sum of infeasibilities (the feasibility phase), and minimizing the quadratic objective function within the feasible region (the optimality phase). The computations in both phases are performed by the same subroutines. The two-phase nature of the algorithm is reflected by changing the function being minimized from the sum of infeasibilities (the printed quantity sInf; see Section 9.1) to the quadratic objective function (the printed quantity Objective; see Section 9.1).
In general, an iterative process is required to solve a quadratic program. Given an iterate x,s in both the original variables x and the slack variables s, a new iterate x-,s- is defined by
x- s- = x s +αp, (3)
where the step length α is a non-negative scalar (the printed quantity Step; see Section 13), and p is called the search direction. (For simplicity, we shall consider a typical iteration and avoid reference to the index of the iteration.) Once an iterate is feasible (i.e., satisfies the constraints), all subsequent iterates remain feasible.

11.2 Definition of the Working Set and Search Direction

At each iterate x,s, a working set of constraints is defined to be a linearly independent subset of the constraints that are satisfied ‘exactly’ (to within the value of the optional parameter Feasibility Tolerance). The working set is the current prediction of the constraints that hold with equality at a solution of the LP or QP problem. Let mW denote the number of constraints in the working set (including bounds), and let W denote the associated mW by n+m working set matrix consisting of the mW gradients of the working set constraints.
The search direction is defined so that constraints in the working set remain unaltered for any value of the step length. It follows that p must satisfy the identity
Wp=0. (4)
This characterisation allows p to be computed using any n by nZ full-rank matrix Z that spans the null space of W. (Thus, nZ=n-mW and WZ=0.) The null space matrix Z is defined from a sparse LU factorization of part of W (see (7) and (8)). The direction p will satisfy (4) if
p=Z pZ, (5)
where pZ is any nZ-vector.
The working set contains the constraints Ax-s=0 and a subset of the upper and lower bounds on the variables x,s. Since the gradient of a bound constraint xj≥lj or xj≤uj is a vector of all zeros except for ±1 in position j, it follows that the working set matrix contains the rows of A -I and the unit rows associated with the upper and lower bounds in the working set.
The working set matrix W can be represented in terms of a certain column partition of the matrix A -I by (conceptually) partitioning the constraints Ax-s=0 so that
B xB+S xS+N xN=0, (6)
where B is a square nonsingular basis and xB, xS and xN are the basic, superbasic and nonbasic variables respectively. The nonbasic variables are equal to their upper or lower bounds at x,s, and the superbasic variables are independent variables that are chosen to improve the value of the current objective function. The number of superbasic variables is nS (the printed quantity nS; see Section 9.1). Given values of xN and xS, the basic variables xB are adjusted so that x,s satisfies (6).
If P is a permutation matrix such that A -I P= B S N , then W satisfies
WP= B S N 0 0 IN , (7)
where IN is the identity matrix with the same number of columns as N.
The null space matrix Z is defined from a sparse LU factorization of part of W. In particular, Z is maintained in ‘reduced gradient’ form, using the LUSOL package (see Gill et al. (1991)) to maintain sparse LU factors of the basis matrix B as the BSN partition changes. Given the permutation P, the null space basis is given by
Z=P -B-1 S I 0 . (8)
This matrix is used only as an operator, i.e., it is never computed explicitly. Products of the form Zv and ZT g are obtained by solving with B or BT. This choice of Z implies that nZ, the number of ‘degrees of freedom’ at x,s, is the same as nS, the number of superbasic variables.
Let gZ and HZ denote the reduced gradient and reduced Hessian of the objective function:
gZ=ZT g  and  HZ=ZT HZ, (9)
where g is the objective gradient at x,s. Roughly speaking, gZ and HZ describe the first and second derivatives of an nS-dimensional unconstrained problem for the calculation of pZ. (The condition estimator of HZ is the quantity condHz in the monitoring file output; see Section 9.1.)
At each iteration, an upper triangular factor R is available such that HZ=RT R. Normally, R is computed from RT R=ZT HZ at the start of the optimality phase and then updated as the QP working set changes. For efficiency, the dimension of R should not be excessive (say, nS≤1000). This is guaranteed if the number of nonlinear variables is ‘moderate’.
If the QP problem contains linear variables, H is positive semidefinite and R may be singular with at least one zero diagonal element. However, an inertia-controlling strategy is used to ensure that only the last diagonal element of R can be zero. (See Gill et al. (1991) for a discussion of a similar strategy for indefinite quadratic programming.)
If the initial R is singular, enough variables are fixed at their current value to give a nonsingular R. This is equivalent to including temporary bound constraints in the working set. Thereafter, R can become singular only when a constraint is deleted from the working set (in which case no further constraints are deleted until R becomes nonsingular).

11.3 Main Iteration

If the reduced gradient is zero, x,s is a constrained stationary point on the working set. During the feasibility phase, the reduced gradient will usually be zero only at a vertex (although it may be zero elsewhere in the presence of constraint dependencies). During the optimality phase, a zero reduced gradient implies that x minimizes the quadratic objective function when the constraints in the working set are treated as equalities. At a constrained stationary point, Lagrange multipliers λ are defined from the equations
WT λ=g x. (10)
A Lagrange multiplier, λj, corresponding to an inequality constraint in the working set is said to be optimal if λj≤σ when the associated constraint is at its upper bound, or if λj≥-σ when the associated constraint is at its lower bound, where σ depends on the value of the optional parameter Optimality Tolerance. If a multiplier is nonoptimal, the objective function (either the true objective or the sum of infeasibilities) can be reduced by continuing the minimization with the corresponding constraint excluded from the working set. (This step is sometimes referred to as ‘deleting’ a constraint from the working set.) If optimal multipliers occur during the feasibility phase but the sum of infeasibilities is nonzero, there is no feasible point and the routine terminates immediately with IFAIL=3.
The special form (7) of the working set allows the multiplier vector λ, the solution of (10), to be written in terms of the vector
d= g 0 - AT -I π= g-AT π π , (11)
where π satisfies the equations BT π=gB, and gB denotes the basic elements of g. The elements of π are the Lagrange multipliers λj associated with the equality constraints Ax-s=0. The vector dN of nonbasic elements of d consists of the Lagrange multipliers λj associated with the upper and lower bound constraints in the working set. The vector dS of superbasic elements of d is the reduced gradient gZ in (9). The vector dB of basic elements of d is zero, by construction. (The Euclidean norm of dS and the final values of dS, g and π are the quantities rgNorm, Reduced Gradnt, Obj Gradient and Dual Activity in the monitoring file output; see Section 13.)
If the reduced gradient is not zero, Lagrange multipliers need not be computed and the search direction is given by p=Z pZ (see (8) and (12)). The step length is chosen to maintain feasibility with respect to the satisfied constraints.
There are two possible choices for pZ, depending on whether or not HZ is singular. If HZ is nonsingular, R is nonsingular and pZ in (5) is computed from the equations
RT R pZ=-gZ, (12)
where gZ is the reduced gradient at x. In this case, x,s+p is the minimizer of the objective function subject to the working set constraints being treated as equalities. If x,s+p is feasible, α is defined to be unity. In this case, the reduced gradient at x-,s- will be zero, and Lagrange multipliers are computed at the next iteration. Otherwise, α is set to αN, the step to the ‘nearest’ constraint along p. This constraint is then added to the working set at the next iteration.
If HZ is singular, then R must also be singular, and an inertia-controlling strategy is used to ensure that only the last diagonal element of R is zero. (See Gill et al. (1991) for a discussion of a similar strategy for indefinite quadratic programming.) In this case, pZ satisfies
pZT HZ pZ=0   and   gZT pZ≤0, (13)
which allows the objective function to be reduced by any step of the form x,s + α p , where α > 0 . The vector p = Z pZ is a direction of unbounded descent for the QP problem in the sense that the QP objective is linear and decreases without bound along p . If no finite step of the form x,s + α p (where α > 0 ) reaches a constraint not in the working set, the QP problem is unbounded and the routine terminates immediately with IFAIL=6. Otherwise, α is defined as the maximum feasible step along p and a constraint active at x,s + α p is added to the working set for the next iteration.
E04NQF makes explicit allowance for infeasible constraints. Infeasible linear constraints are detected first by solving a problem of the form
minimize x,v,w eT v+w   subject to ​ l ≤ x Gx-v+w ≤u,   v≥0,   w≥0, (14)
where eT = 1,1,…,1 . This is equivalent to minimizing the sum of the general linear constraint violations subject to the simple bounds. (In the linear programming literature, the approach is often called elastic programming.)

11.4 Miscellaneous

If the basis matrix is not chosen carefully, the condition of the null space matrix Z in (8) could be arbitrarily high. To guard against this, the routine implements a ‘basis repair’ feature in which the LUSOL package (see Gill et al. (1991)) is used to compute the rectangular factorization
B S T=LU, (15)
returning just the permutation P that makes PL PT unit lower triangular. The pivot tolerance is set to require PL PT ij≤2, and the permutation is used to define P in (7). It can be shown that Z is likely to be little more than unity. Hence, Z should be well-conditioned regardless of the condition of W. This feature is applied at the beginning of the optimality phase if a potential B-S ordering is known.
The EXPAND procedure (see Gill et al. (1989)) is used to reduce the possibility of cycling at a point where the active constraints are nearly linearly dependent. Although there is no absolute guarantee that cycling will not occur, the probability of cycling is extremely small (see Hall and McKinnon (1996)). The main feature of EXPAND is that the feasibility tolerance is increased at the start of every iteration. This allows a positive step to be taken at every iteration, perhaps at the expense of violating the bounds on x,s by a small amount.
Suppose that the value of the optional parameter Feasibility Tolerance is δ. Over a period of K iterations (where K is the value of the optional parameter Expand Frequency), the feasibility tolerance actually used by the routine (i.e., the working feasibility tolerance) increases from 0.5 δ to δ (in steps of 0.5 δ/K).
At certain stages the following ‘resetting procedure’ is used to remove small constraint infeasibilities. First, all nonbasic variables are moved exactly onto their bounds. A count is kept of the number of nontrivial adjustments made. If the count is nonzero, the basic variables are recomputed. Finally, the working feasibility tolerance is reinitialized to 0.5 δ.
If a problem requires more than K iterations, the resetting procedure is invoked and a new cycle of iterations is started. (The decision to resume the feasibility phase or optimality phase is based on comparing any constraint infeasibilities with δ.)
The resetting procedure is also invoked when the routine reaches an apparently optimal, infeasible or unbounded solution, unless this situation has already occurred twice. If any nontrivial adjustments are made, iterations are continued.
The EXPAND procedure not only allows a positive step to be taken at every iteration, but also provides a potential choice of constraints to be added to the working set. All constraints at a distance α (where α≤αN) along p from the current point are then viewed as acceptable candidates for inclusion in the working set. The constraint whose normal makes the largest angle with the search direction is added to the working set. This strategy helps keep the basis matrix B well-conditioned.

12 Optional Parameters

Several optional parameters in E04NQF define choices in the problem specification or the algorithm logic. In order to reduce the number of formal arguments of E04NQF these optional parameters have associated default values that are appropriate for most problems. Therefore, you need only specify those optional parameters whose values are to be different from their default values.
The remainder of this section can be skipped if you wish to use the default values for all optional parameters.
The following is a list of the optional parameters available. A full description of each optional parameter is provided in Section 12.1.
  • Backup Basis File
  • Check Frequency
  • Crash Option
  • Crash Tolerance
  • Defaults
  • Dump File
  • Elastic Mode
  • Elastic Objective
  • Elastic Weight
  • Expand Frequency
  • Factorization Frequency
  • Feasibility Tolerance
  • Feasible Point
  • Infinite Bound Size
  • Insert File
  • Iterations Limit
  • List
  • Load File
  • LU Complete Pivoting
  • LU Density Tolerance
  • LU Factor Tolerance
  • LU Partial Pivoting
  • LU Rook Pivoting
  • LU Singularity Tolerance
  • LU Update Tolerance
  • Maximize
  • Minimize
  • New Basis File
  • Nolist
  • Old Basis File
  • Optimality Tolerance
  • Partial Price
  • Pivot Tolerance
  • Print File
  • Print Frequency
  • Print Level
  • Punch File
  • QPSolver CG
  • QPSolver Cholesky
  • QPSolver QN
  • Reduced Hessian Dimension
  • Save Frequency
  • Scale Option
  • Scale Print
  • Scale Tolerance
  • Solution File
  • Solution No
  • Solution Yes
  • Summary File
  • Summary Frequency
  • Superbasics Limit
  • Suppress Parameters
  • System Information No
  • System Information Yes
  • Timing Level
  • Unbounded Step Size
Optional parameters may be specified by calling one, or any, of the routines E04NRF, E04NSF, E04NTF and E04NUF before a call to E04NQF, but after a call to E04NPF.
E04NRF reads options from an external options file, with Begin and End as the first and last lines respectively and each intermediate line defining a single optional parameter. For example,
Begin
   Print Level = 5
End
The call
 CALL E04NRF (ISPECS, CW, IW, RW, IFAIL)
can then be used to read the file on unit ISPECS. IFAIL will be zero on successful exit. E04NRF should be consulted for a full description of this method of supplying optional parameters.
E04NSF, E04NTF or E04NUF can be called to supply options directly, one call being necessary for each optional parameter. E04NSF, E04NTF or E04NUF should be consulted for a full description of this method of supplying optional parameters.
All optional parameters not specified by you are set to their default values. Optional parameters specified by you are unaltered by E04NQF (unless they define invalid values) and so remain in effect for subsequent calls unless altered by you.

12.1 Description of the Optional Parameters

For each option, we give a summary line, a description of the optional parameter and details of constraints.
The summary line contains:
  • the keywords;
  • a parameter value, where the letters a, i and r denote options that take character, integer and real values respectively;
  • the default value is used whenever the condition i≥100000000 is satisfied and where the symbol ε is a generic notation for machine precision (see X02AJF);
  • The variable bigbnd holds the value of Infinite Bound Size.
Keywords and character values are case and white space insensitive.
Check Frequency i Default =60
Every ith iteration after the most recent basis factorization, a numerical test is made to see if the current solution x,s satisfies the linear constraints Ax-s=0. If the largest element of the residual vector r=Ax-s is judged to be too large, the current basis is refactorized and the basic variables recomputed to satisfy the constraints more accurately. If i≤0, the value i=99999999 is used and effectively no checks are made.
Check Frequency=1 is useful for debugging purposes, but otherwise this option should not be needed.
Crash Option i Default =3
Crash Tolerance r Default =0.1
Note that these options do not apply when START='W' (see Section 5).
If START='C', an internal Crash procedure is used to select an initial basis from various rows and columns of the constraint matrix A -I . The value of i determines which rows and columns of A are initially eligible for the basis, and how many times the Crash procedure is called. Columns of -I are used to pad the basis where necessary.
i | Meaning
0 | The initial basis contains only slack variables: B=I.
1 | The Crash procedure is called once, looking for a triangular basis in all rows and columns of the matrix A.
2 | The Crash procedure is called once, looking for a triangular basis in rows.
3 | The Crash procedure is called twice, treating linear equalities and linear inequalities separately.
If i≥1, certain slacks on inequality rows are selected for the basis first. (If i≥2, numerical values are used to exclude slacks that are close to a bound.) The Crash procedure then makes several passes through the columns of A, searching for a basis matrix that is essentially triangular. A column is assigned to ‘pivot’ on a particular row if the column contains a suitably large element in a row that has not yet been assigned. (The pivot elements ultimately form the diagonals of the triangular basis.) For remaining unassigned rows, slack variables are inserted to complete the basis.
The Crash Tolerance allows the Crash procedure to ignore certain ‘small’ nonzero elements in each column of A. If amax is the largest element in column j, other nonzeros a ij in the column are ignored if a ij ≤ amax × r . (To be meaningful, r should be in the range 0 ≤ r < 1 .)
When r>0.0, the basis obtained by the Crash procedure may not be strictly triangular, but it is likely to be nonsingular and almost triangular. The intention is to obtain a starting basis containing more columns of A and fewer (arbitrary) slacks. A feasible solution may be reached sooner on some problems.
For example, suppose the first m columns of A form the matrix shown under LU Factor Tolerance; i.e., a tridiagonal matrix with entries -1, 4, -1. To help the Crash procedure choose all m columns for the initial basis, we would specify a Crash Tolerance of r for some value of r>0.5.
Defaults
This special keyword may be used to reset all optional parameters to their default values.
Dump File i 1 Default =0
Load File i 2 Default =0
Optional parameters Dump File and Load File are similar to optional parameters Punch File and Insert File, but they record solution information in a manner that is more direct and more easily modified. A full description of information recorded in optional parameters Dump File and Load File is given in Gill et al. (2005a).
If i 1>0, the last solution obtained will be output to the file with unit number i.
If i 2>0 , the Load File containing basis information will be read. The file will usually have been output previously as a Dump File. The file will not be accessed if optional parameters Old Basis File or Insert File are specified.
Elastic Mode i Default =1
This argument determines if (and when) elastic mode is to be started. Three elastic modes are available as follows:
i | Meaning
0 | Elastic mode is never invoked. E04NQF will terminate as soon as infeasibility is detected. There may be other points with significantly smaller sums of infeasibilities.
1 | Elastic mode is invoked only if the constraints are found to be infeasible (the default). If the constraints are infeasible, continue in elastic mode with the composite objective determined by the values of the optional parameters Elastic Objective and Elastic Weight.
2 | The iterations start and remain in elastic mode. This option allows you to minimize the composite objective function directly without first performing Phase 1 iterations. The success of this option will depend critically on your choice of Elastic Weight. If Elastic Weight is sufficiently large and the constraints are feasible, the minimizer of the composite objective and the solution of the original problem are identical. However, if the Elastic Weight is not sufficiently large, the minimizer of the composite function may be infeasible, even if a feasible point exists.
Elastic Objective i Default =1
This determines the form of the composite objective f x + γ ∑j vj + wj in Phase 2 (γ). Three types of composite objectives are available.
i | Meaning
0 | Include only the true objective f x in the composite objective. This option sets γ=0 in the composite objective and allows E04NQF to ignore the elastic bounds and find a solution that minimizes f x subject to the non-elastic constraints. This option is useful if there are some ‘soft’ constraints that you would like to ignore if the constraints are infeasible.
1 | Use a composite objective defined with γ determined by the value of Elastic Weight. This value is intended to be used in conjunction with Elastic Mode=2.
2 | Include only the elastic variables in the composite objective. The elastics are weighted by γ=1. This choice minimizes the violations of the elastic variables at the expense of possibly increasing the true objective. This option can be used to find a point that minimizes the sum of the violations of a subset of constraints specified by the input array HELAST.
Elastic Weight r Default =1.0
This defines the value of γ in the composite objective in Phase 2 (γ).
At each iteration of elastic mode, the composite objective is defined to be
minimize​ ​σ ​ ​ f x + γ ​ (sum of infeasibilities);
where σ=1 for Minimize, σ=-1 for Maximize, and f x is the quadratic objective.
Note that the effect of γ is not disabled once a feasible point is obtained.
Expand Frequency i Default =10000
This option is part of an anti-cycling procedure (see Section 11.4) designed to allow progress even on highly degenerate problems.
The strategy is to force a positive step at every iteration, at the expense of violating the constraints by a small amount. Suppose that the value of the optional parameter Feasibility Tolerance is δ. Over a period of i iterations, the feasibility tolerance actually used by E04NQF (i.e., the working feasibility tolerance) increases from 0.5 δ to δ (in steps of 0.5 δ/i).
Increasing the value of i helps reduce the number of slightly infeasible nonbasic variables (most of which are eliminated during the resetting procedure). However, it also diminishes the freedom to choose a large pivot element (see the description of the optional parameter Pivot Tolerance).
If i≤0, the value i=99999999 is used and effectively no anti-cycling procedure is invoked.
Factorization Frequency i Default =100 LP or 50 QP
If i>0, at most i basis changes will occur between factorizations of the basis matrix.
For LP problems, the basis factors are usually updated at every iteration. Higher values of i may be more efficient on problems that are extremely sparse and well scaled.
For QP problems, fewer basis updates will occur as the solution is approached. The number of iterations between basis factorizations will therefore increase. During these iterations a test is made regularly according to the value of optional parameter Check Frequency to ensure that the linear constraints Ax-s=0 are satisfied. Occasionally, the basis will be refactorized before the limit of i updates is reached. If i≤0, the default value is used.
Feasibility Tolerance r Default = max 10-6,ε
A feasible problem is one in which all variables satisfy their upper and lower bounds to within the absolute tolerance r. (This includes slack variables. Hence, the general constraints are also satisfied to within r.)
E04NQF attempts to find a feasible solution before optimizing the objective function. If the sum of infeasibilities cannot be reduced to zero, the problem is assumed to be infeasible. Let sInf be the corresponding sum of infeasibilities. If sInf is quite small, it may be appropriate to raise r by a factor of 10 or 100. Otherwise, some error in the data should be suspected.
Note that if sInf is not small and you have not asked E04NQF to minimize the violations of the elastic variables (i.e., you have not specified Elastic Objective=2), there may be other points that have a significantly smaller sum of infeasibilities. E04NQF will not attempt to find the solution that minimizes the sum unless Elastic Objective=2.
If the constraints and variables have been scaled (see the description of the optional parameter Scale Option), then feasibility is defined in terms of the scaled problem (since it is more likely to be meaningful).
Infinite Bound Size r Default =1020
If r≥0, r defines the ‘infinite’ bound infbnd in the definition of the problem constraints. Any upper bound greater than or equal to infbnd will be regarded as +∞ (and similarly any lower bound less than or equal to -infbnd will be regarded as -∞). If r<0, the default value is used.
Iterations Limit i Default = max 10000, 10 max m,n
The value of i specifies the maximum number of iterations allowed before termination. Setting i=0 and Print Level>0 means that: the workspace needed to start solving the problem will be computed and printed; and feasibility and optimality will be checked. No iterations will be performed. If i<0, the default value is used.
LU Density Tolerance r 1 Default = 0.6
LU Singularity Tolerance r 2 Default = ε 23
The density tolerance r 1 is used during LU factorization of the basis matrix. Columns of L and rows of U are formed one at a time, and the remaining rows and columns of the basis are altered appropriately. At any stage, if the density of the remaining matrix exceeds r 1, the Markowitz strategy for choosing pivots is terminated. The remaining matrix is factored by a dense LU procedure. Raising the density tolerance towards 1.0 may give slightly sparser LU factors, with a slight increase in factorization time.
If r 2>0, r 2 defines the singularity tolerance used to guard against ill-conditioned basis matrices. After B is refactorized, the diagonal elements of U are tested as follows. If u jj≤r 2 or u jj<r 2 maxi u ij, the jth column of the basis is replaced by the corresponding slack variable. If r 2≤0, the default value is used.
LU Factor Tolerance r 1 Default =100.0
LU Update Tolerance r 2 Default =10.0
The values of r 1 and r 2 affect the stability and sparsity of the basis factorization B=LU, during refactorization and updates respectively. The lower triangular matrix L is a product of matrices of the form
1 0 μ 1
where the multipliers μ will satisfy μ≤ri. The default values of r 1 and r 2 usually strike a good compromise between stability and sparsity. They must satisfy r 1, r 2≥1.0.
For large and relatively dense problems, r 1=10.0​ or ​5.0 (say) may give a useful improvement in stability without impairing sparsity to a serious degree.
For certain very regular structures (e.g., band matrices) it may be necessary to reduce r 1​ and/or ​r 2 in order to achieve stability. For example, if the columns of A include a sub-matrix of the form
4 -1 -1 4 -1 -1 4 -1 … … … -1 4 -1 -1 4 ,
one should set both r 1 and r 2 to values in the range 1.0≤ri<4.0.
LU Partial Pivoting Default
LU Complete Pivoting
LU Rook Pivoting
The LU factorization implements a Markowitz-type search for pivots that locally minimize the fill-in subject to a threshold pivoting stability criterion. The default option is to use threshold partial pivoting. The options LU Complete Pivoting and LU Rook Pivoting are more expensive but more stable and better at revealing rank, as long as the LU Factor Tolerance is not too large (say <2.0).
Minimize Default
Maximize
Feasible Point
This option specifies the required direction of the optimization. It applies to both linear and nonlinear terms (if any) in the objective function. Note that if two problems are the same except that one minimizes f x and the other maximizes -f x, their solutions will be the same but the signs of the dual variables πi and the reduced gradients dj (see Section 11.3) will be reversed.
The option Feasible Point means ‘ignore the objective function, while finding a feasible point for the linear constraints’. It can be used to check that the constraints are feasible without altering the call to E04NQF.
New Basis File i 1 Default =0
Backup Basis File i 2 Default =0
Save Frequency i 3 Default =100
Optional parameters New Basis File and Backup Basis File are sometimes referred to as basis maps. They contain the most compact representation of the state of each variable. They are intended for restarting the solution of a problem at a point that was reached by an earlier run. For nontrivial problems, it is advisable to save basis maps at the end of a run, in order to restart the run if necessary.
If i 1>0 , a basis map will be saved on file i 1 every i 3 th iteration, where i 3 is the Save Frequency. The first record of the file will contain the word PROCEEDING if the run is still in progress. A basis map will also be saved at the end of a run, with some other word indicating the final solution status.
Use of i 2>0 is intended as a safeguard against losing the results of a long run. Suppose that a New Basis File is being saved every 100 (Save Frequency) iterations, and that E04NQF is about to save such a basis at iteration 2000. It is conceivable that the run may be interrupted during the next few milliseconds (in the middle of the save). In this case the Basis file will be corrupted and the run will have been essentially wasted.
To eliminate this risk, both a New Basis File and a Backup Basis File may be specified. The following would be suitable for the above example:
Backup Basis File 11
New Basis File 12
The current basis will then be saved every 100 iterations, first on File 12 and then immediately on File 11. If the run is interrupted at iteration 2000 during the save on File 12, there will still be a usable basis on File 11 (corresponding to iteration 1900).
Note that a new basis will be saved in New Basis File at the end of a run if it terminates normally, but it will not be saved in Backup Basis File. In the above example, if an optimum solution is found at iteration 2050 (or if the iteration limit is 2050), the final basis on File 12 will correspond to iteration 2050, but the last basis saved on File 11 will be the one for iteration 2000.
A full description of information recorded in New Basis File and Backup Basis File is given in Gill et al. (2005a).
Nolist Default
List
Normally each optional parameter specification is printed to unit Print File as it is supplied. Optional parameter Nolist may be used to suppress the printing and optional parameter List may be used to restore printing.
Old Basis File i Default =0
If i>0 , the basis maps information will be obtained from this file. The file will usually have been output previously as a New Basis File or Backup Basis File. A full description of information recorded in New Basis File and Backup Basis File is given in Gill et al. (2005a).
The file will not be acceptable if the number of rows or columns in the problem has been altered.
Optimality Tolerance r Default = max 10-6,ε
This is used to judge the size of the reduced gradients dj=gj - ajT π , where gj is the jth component of the gradient, aj is the associated column of the constraint matrix A -I , and π is the set of dual variables.
By construction, the reduced gradients for basic variables are always zero. The problem will be declared optimal if the reduced gradients for nonbasic variables at their lower or upper bounds satisfy
dj / π ≥ -r  or  dj / π ≤ r
respectively, and if dj / π ≤ r for superbasic variables.
In the above tests, π is a measure of the size of the dual variables. It is included to make the tests independent of a scale factor on the objective function. The quantity π actually used is defined by
π=max σ/m,1 , where ​ σ= ∑ i=1 m πi,
so that only large scale factors are allowed for.
If the objective is scaled down to be very small, the optimality test reduces to comparing dj against 0.01 r .
Partial Price i Default =10 LP or 1 QP
This option is recommended for large FP or LP problems that have significantly more variables than constraints (i.e., n≫m). It reduces the work required for each pricing operation (i.e., when a nonbasic variable is selected to enter the basis). If i=1, all columns of the constraint matrix A -I are searched. If i>1, A and I are partitioned to give i roughly equal segments Aj,Ij, for j=1,2,…,i (modulo i). If the previous pricing search was successful on A j-1,I j-1, the next search begins on the segments Aj and Ij. If a reduced gradient is found that is larger than some dynamic tolerance, the variable with the largest such reduced gradient (of appropriate sign) is selected to enter the basis. If nothing is found, the search continues on the next segments A j+1,I j+1, and so on. If i≤0, the default value is used.
Pivot Tolerance r Default =ε 23
Broadly speaking, the pivot tolerance is used to prevent columns entering the basis if they would cause the basis to become almost singular.
When x changes to x+αp for some search direction p , a ‘ratio test’ determines which component of x reaches an upper or lower bound first. The corresponding element of p is called the pivot element. Elements of p are ignored (and therefore cannot be pivot elements) if they are smaller than the pivot tolerance r .
It is common for two or more variables to reach a bound at essentially the same time. In such cases, the optional parameter Feasibility Tolerance (say t ) provides some freedom to maximize the pivot element and thereby improve numerical stability. Excessively small values of t should therefore not be specified. To a lesser extent, the optional parameter Expand Frequency (say f ) also provides some freedom to maximize the pivot element. Excessively large values of f should therefore not be specified.
Print File i Default =0
If i>0 , the following information is output to i during the solution of each problem:
– | a listing of the optional parameters;
– | some statistics about the problem;
– | the amount of storage available for the LU factorization of the basis matrix;
– | notes about the initial basis resulting from a Crash procedure or a Basis file;
– | the iteration log;
– | basis factorization statistics;
– | the exit IFAIL condition and some statistics about the solution obtained;
– | the printed solution, if requested.
The last four items are described in Sections 9 and 13. Further brief output may be directed to the Summary File.
Print Frequency i Default =100
If i>0 , one line of the iteration log will be printed every i th iteration. A value such as i=10 is suggested for those interested only in the final solution. If i≤0, the value of i=99999999 is used and effectively no checks are made.
Print Level i Default =1
This controls the amount of printing produced by E04NQF as follows.
i | Meaning
0 | No output except error messages. If you want to suppress all output, set Print File=0.
=1 | The set of selected options, problem statistics, summary of the scaling procedure, information about the initial basis resulting from a Crash or a Basis file, a single line of output at each iteration (controlled by the optional parameter Print Frequency), and the exit condition with a summary of the final solution.
≥10 | Basis factorization statistics.
Punch File i 1 Default =0
Insert File i 2 Default =0
These files provide compatibility with commercial mathematical programming systems. The Punch File from a previous run may be used as an Insert File for a later run on the same problem. A full description of information recorded in Insert File and Punch File is given in Gill et al. (2005a).
If i 1>0 , the final solution obtained will be output to file i 1 . For linear programs, this format is compatible with various commercial systems.
If i 2>0 , the Insert File containing basis information will be read. The file will usually have been output previously as a Punch File. The file will not be accessed if Old Basis File is specified.
QPSolver Cholesky Default
QPSolver CG
QPSolver QN
Specifies the active-set algorithm used to solve the quadratic program in Phase 2 (γ). QPSolver Cholesky holds the full Cholesky factor R of the reduced Hessian ZT HZ. As the QP iterations proceed, the dimension of R changes with the number of superbasic variables. If the number of superbasic variables needs to increase beyond the value of Reduced Hessian Dimension, the reduced Hessian cannot be stored and the solver switches to QPSolver CG. The Cholesky solver is reactivated if the number of superbasics stabilizes at a value less than Reduced Hessian Dimension.
QPSolver QN solves the QP using a quasi-Newton method. In this case, R is the factor of a quasi-Newton approximate Hessian.
QPSolver CG uses an active-set method similar to QPSolver QN, but uses the conjugate-gradient method to solve all systems involving the reduced Hessian.
The Cholesky QP solver is the most robust, but may require a significant amount of computation if there are many superbasics.
The quasi-Newton QP solver does not require computation of the exact R at the start of Phase 2 (γ). It may be appropriate when the number of superbasics is large but relatively few iterations are needed to reach a solution (e.g., if E04NQF is called with a Warm Start).
The conjugate-gradient QP solver is appropriate for problems with many degrees of freedom (say, more than 2000 superbasics).
Reduced Hessian Dimension i Default = 1 LP ​ or ​ min 2000,nH+1,n QP
This specifies that an i by i triangular matrix R (to define the reduced Hessian according to RT R = ZT HZ ). is to be available for use by the Cholesky QP solver.
Scale Option i Default =2
Scale Tolerance r Default =0.9
Scale Print
Three scale options are available as follows:
i | Meaning
0 | No scaling. This is recommended if it is known that x and the constraint matrix never have very large elements (say, larger than 100).
1 | The constraints and variables are scaled by an iterative procedure that attempts to make the matrix coefficients as close as possible to 1.0 (see Fourer (1982)). This will sometimes improve the performance of the solution procedures.
2 | The constraints and variables are scaled by the iterative procedure. Also, a certain additional scaling is performed that may be helpful if the right-hand side b or the solution x is large. This takes into account columns of A -I that are fixed or have positive lower bounds or negative upper bounds.
Optional parameter Scale Tolerance affects how many passes might be needed through the constraint matrix. On each pass, the scaling procedure computes the ratio of the largest and smallest nonzero coefficients in each column:
ρj=maxj a ij / mini a ij   a ij ≠ 0 .
If maxj ρj is less than r times its previous value, another scaling pass is performed to adjust the row and column scales. Raising r from 0.9 to 0.99 (say) usually increases the number of scaling passes through A . At most 10 passes are made. The value of r should lie in the range 0<r<1.
Scale Print causes the row scales r i and column scales c j to be printed to Print File, if System Information Yes has been specified. The scaled matrix coefficients are a- ij = a ij c j / r i, and the scaled bounds on the variables and slacks are l-j = lj / c j , u-j = uj / c j , where c j = r j-n if j>n.
Solution Yes Default
Solution No
This option determines if the final obtained solution is to be output to the Print File. Note that the Solution File option operates independently.
Solution File i Default =0
If i>0 , the final solution will be output to file i (whether optimal or not).
To see more significant digits in the printed solution, it will sometimes be useful to make i refer to the system Print File.
Summary File i 1 Default =0
Summary Frequency i 2 Default =100
If i 1>0 , the Summary File is output to file i 1 , including a line of the iteration log every i 2 th iteration. In an interactive environment, it is useful to direct this output to the terminal, to allow a run to be monitored online. (If something looks wrong, the run can be manually terminated.) Further details are given in Section 13. If i 2≤0, the value of i 2=99999999 is used and effectively no checks are made.
Superbasics Limit i Default = 1 LP ​ or ​ min nH + 1 ,n QP
This places a limit on the storage allocated for superbasic variables. Ideally, i should be set slightly larger than the ‘number of degrees of freedom’ expected at an optimal solution.
For linear programs, an optimum is normally a basic solution with no degrees of freedom. (The number of variables lying strictly between their bounds is no more than m , the number of general constraints.) The default value of i is therefore 1.
For quadratic problems, the number of degrees of freedom is often called the ‘number of independent variables’. Normally, i need not be greater than nH+1 , where nH is the number of leading nonzero columns of H . For many problems, i may be considerably smaller than nH. This will save storage if nH is very large.
Suppress Parameters
Normally E04NQF prints the options file as it is being read, and then prints a complete list of the available keywords and their final values. The optional parameter Suppress Parameters tells E04NQF not to print the full list.
System Information No Default
System Information Yes
This option prints additional information on the progress of major and minor iterations, and Crash statistics. See Section 13.
Timing Level i Default =0
If i>0 , some timing information will be output to the Print file, if Print File>0.
Unbounded Step Size r Default =infbnd
If r>0, r specifies the magnitude of the change in variables that will be considered a step to an unbounded solution. (Note that an unbounded solution can occur only when the Hessian is not positive definite.) If the change in x during an iteration would exceed the value of r, the objective function is considered to be unbounded below in the feasible region. If r≤0, the default value is used. See Infinite Bound Size for the definition of infbnd.

13 Description of Monitoring Information

This section describes the intermediate printout and final printout which constitutes the monitoring information produced by E04NQF. (See also the description of the optional parameters Print File and Print Level.) You can control the level of printed output.

13.1 Crash Statistics

When Print Level ≥ 10 , Print File > 0 and System Information Yes has been specified, the following lines of intermediate printout (less than 120 characters) are produced on the unit number specified by optional parameter Print File whenever START='C' (see Section 5). They refer to the number of columns selected by the Crash procedure during each of several passes through A, whilst searching for a triangular basis matrix.
Label | Description
Slacks | is the number of slacks selected initially.
Free cols | is the number of free columns in the basis, including those whose bounds are rather far apart.
Preferred | is the number of ‘preferred’ columns in the basis (i.e., HS j=3 for some j≤n). It will be a subset of the columns for which HS j=3 was specified.
Unit | is the number of unit columns in the basis.
Double | is the number of double columns in the basis.
Triangle | is the number of triangular columns in the basis.
Pad | is the number of slacks used to pad the basis (to make it a nonsingular triangle).

13.2 Basis Factorization Statistics

When Print Level ≥ 10 and Print File > 0 , the first seven items of intermediate printout in the list below are produced on the unit number specified by optional parameter Print File whenever the matrix B or BS= B S T is factorized. Gaussian elimination is used to compute an LU factorization of B or BS, where PL PT is a lower triangular matrix and PUQ is an upper triangular matrix for some permutation matrices P and Q. The factorization is stabilized in the manner described under the optional parameter LU Factor Tolerance. In addition, if System Information Yes has been specified, the entries from Elems onwards are also output.
Label | Description
Factor | the number of factorizations since the start of the run.
Demand a code giving the reason for the present factorization, as follows:
Code | Meaning
0 | First LU factorization.
1 | The number of updates reached the Factorization Frequency.
2 | The nonzeros in the updated factors have increased significantly.
7 | Not enough storage to update factors.
10 | Row residuals are too large (see the description of the optional parameter Check Frequency).
11 | Ill-conditioning has caused inconsistent results.
Itn | is the current minor iteration number.
Nonlin | is the number of nonlinear variables in the current basis B .
Linear | is the number of linear variables in B .
Slacks | is the number of slack variables in B .
B, BR, BS or BT factorize is the type of LU factorization.
B | periodic factorization of the basis B .
BR | more careful rank-revealing factorization of B using threshold rook pivoting. This occurs mainly at the start, if the first basis factors seem singular or ill-conditioned. Followed by a normal B factorize.
BS | BS is factorized to choose a well-conditioned B from the current B S . Followed by a normal B factorize.
BT | same as BS except the current B is tried first and accepted if it appears to be not much more ill-conditioned than after the previous BS factorize.
m | is the number of rows in B or BS .
n | is the number of columns in B or BS . Preceded by ‘=’ or ‘>’ respectively.
Elems | is the number of nonzero elements in B or BS .
Amax | is the largest nonzero in B or BS .
Density | is the percentage nonzero density of B or BS .
Merit/MerRP/MerCP | Merit is the average Markowitz merit count for the elements chosen to be the diagonals of PUQ . Each merit count is defined to be c-1 r-1 where c and r are the number of nonzeros in the column and row containing the element at the time it is selected to be the next diagonal. Merit is the average of n such quantities. It gives an indication of how much work was required to preserve sparsity during the factorization. If LU Complete Pivoting or LU Rook Pivoting has been selected, this heading is changed to MerCP, respectively MerRP.
lenL | is the number of nonzeros in L .
L+U | is the number of nonzeros representing the basis factors L and U . Immediately after a basis factorization B=LU , this is lenL+lenU, the number of subdiagonal elements in the columns of a lower triangular matrix and the number of diagonal and superdiagonal elements in the rows of an upper-triangular matrix. Further nonzeros are added to L when various columns of B are later replaced. As columns of B are replaced, the matrix U is maintained explicitly (in sparse form). The value of L will steadily increase, whereas the value of U may fluctuate up or down. Thus the value of L+U may fluctuate up or down (in general, it will tend to increase).
Cmpressns | is the number of times the data structure holding the partially factored matrix needed to be compressed to recover unused storage. Ideally this number should be zero. If it is more than 3 or 4, the amount of workspace available to E04NQF should be increased for efficiency.
Incres | is the percentage increase in the number of nonzeros in L and U relative to the number of nonzeros in B or BS .
Utri | is the number of triangular rows of B or BS at the top of U .
lenU | the number of nonzeros in U , including its diagonals.
Ltol | is the largest subdiagonal element allowed in L . This is the specified LU Factor Tolerance or a smaller value that is currently being used for greater stability.
Umax | the maximum nonzero element in U .
Ugrwth is the ratio Umax/Amax , which ideally should not be substantially larger than 10.0 or 100.0. If it is orders of magnitude larger, it may be advisable to reduce the LU Factor Tolerance to 5.0, 4.0, 3.0 or 2.0, say (but bigger than 1.0).
As long as Lmax is not large (say 5.0 or less), max Amax,Umax / DUmin gives an estimate of the condition number B . If this is extremely large, the basis is nearly singular. Slacks are used to replace suspect columns of B and the modified basis is refactored.
Ltri | is the number of triangular columns of B or BS at the left of L .
dense1 | is the number of columns remaining when the density of the basis matrix being factorized reached 0.3.
Lmax | is the actual maximum subdiagonal element in L (bounded by Ltol).
Akmax | is the largest nonzero generated at any stage of the LU factorization. (Values much larger than Amax indicate instability.) Akmax is not printed if LU Partial Pivoting is selected.
Agrwth | is the ratio Akmax/Amax . Values much larger than 100 (say) indicate instability. Agrwth is not printed if LU Partial Pivoting is selected.
bump | is the size of the block to be factorized nontrivially after the triangular rows and columns of B or BS have been removed.
dense2 | is the number of columns remaining when the density of the basis matrix being factorized reached 0.6. (The Markowitz pivot strategy searches fewer columns at that stage.)
DUmax | is the largest diagonal of PUQ .
DUmin | is the smallest diagonal of PUQ .
condU | the ratio DUmax/DUmin , which estimates the condition number of U (and of B if Ltol is less than 5.0, say).

13.3 Basis Map

When Print Level ≥ 10 and Print File > 0 , the following lines of intermediate printout (less than 80 characters) are produced on the unit number specified by optional parameter Print File. They refer to the elements of the NAMES array (see Section 5).
Label | Description
Name | gives the name for the problem (blank if problem unnamed).
Infeasibilities | gives the number of infeasibilities. Printed only if the final point is infeasible.
Objective Value | gives the objective value at the final point (or the value of the sum of infeasibilities). Printed only if the final point is feasible.
Status | gives the exit status for the problem (i.e., Optimal soln, Weak soln, Unbounded, Infeasible, Excess itns, Error condn or Feasble soln) followed by details of the direction of the optimization (i.e., (Min) or (Max)).
Iteration | gives the iteration number when the file was created.
Superbasics | gives the number of superbasic variables.
Objective | gives the name of the free row for the problem (blank if objective unnamed).
RHS | gives the name of the constraint right-hand side for the problem (blank if objective unnamed).
Ranges | gives the name of the ranges for the problem (blank if objective unnamed).
Bounds | gives the name of the bounds for the problem (blank if objective unnamed).

13.4 Solution Output

At the end of a run, the final solution will be output to the Print file. Some header information appears first to identify the problem and the final state of the optimization procedure. A ROWS section and a COLUMNS section then follow, giving one line of information for each row and column.

13.4.1 The ROWS section

General constraints take the form l ≤ Ax ≤ u . The i th constraint is therefore of the form
α ≤ νi x ≤ β ,
where νi is the i th row of A .
Internally, the constraints take the form Ax - s = 0 , where s is the set of slack variables (which happen to satisfy the bounds l ≤ s ≤ u ). For the i th constraint, the slack variable si is directly available, and it is sometimes convenient to refer to its state. It should satisfy α≤ si≤ β . A fullstop (.) is printed for any numerical value that is exactly zero.
Label | Description
Number | is the value of n+i. (This is used internally to refer to si in the intermediate output.)
Row | gives the name of νi.
State the state of νi (the state of si relative to the bounds α and β ). The various states possible are as follows:
LL | si is nonbasic at its lower limit, α .
UL | si is nonbasic at its upper limit, β .
EQ | si is nonbasic and fixed at the value α=β .
FR | si is nonbasic and currently zero, even though it is free to take any value between its bounds α and β .
BS | si is basic.
SBS | si is superbasic.
A key is sometimes printed before State. Note that unless the optional parameter Scale Option=0 is specified, the tests for assigning a key are applied to the variables of the scaled problem.
A | Alternative optimum possible. The variable is nonbasic, but its reduced gradient is essentially zero. This means that if the variable were allowed to start moving away from its bound, there would be no change in the value of the objective function. The values of the other free variables might change, giving a genuine alternative solution. However, if there are any degenerate variables (labelled D), the actual change might prove to be zero, since one of them could encounter a bound immediately. In either case, the values of the Lagrange multipliers might also change.
D | Degenerate. The variable is basic or superbasic, but it is equal (or very close) to one of its bounds.
I | Infeasible. The variable is basic or superbasic and is currently violating one of its bounds by more than the value of the Feasibility Tolerance.
N | Not precisely optimal. If the slack is superbasic, the dual variable πi is not sufficiently small, as measured by the Optimality Tolerance. If the slack is nonbasic, πi is not sufficiently positive or negative. If a loose Optimality Tolerance has been used, or if iterations were terminated before optimality, this key might be helpful in deciding whether or not to restart the run.
Activity | is the value of νi x at the final iterate.
Slack Activity | is the value by which the row differs from its nearest bound. (For the free row (if any), it is set to Activity.)
Lower Limit | is α, the lower bound specified for the variable si. None indicates that BL j≤-infbnd.
Upper Limit | is β, the upper bound specified for the variable si. None indicates that BU j≥infbnd.
Dual Activity | is the value of the dual variable πi (the Lagrange multiplier for νi; see Section 11.3). For FP problems, πi is set to zero.
i | gives the index i of the ith row.

13.4.2 The COLUMNS Section

Let the j th component of x be the variable xj and assume that it satisfies the bounds α ≤ xj ≤ β . A fullstop (.) is printed for any numerical value that is exactly zero.
Label | Description
Number | is the column number j. (This is used internally to refer to xj in the intermediate output.)
Column | gives the name of xj.
State the state of xj relative to the bounds α and β . The various states possible are as follows:
LL | xj is nonbasic at its lower limit, α .
UL | xj is nonbasic at its upper limit, β .
EQ | xj is nonbasic and fixed at the value α = β .
FR | xj is nonbasic and currently zero, even though it is free to take any value between its bounds α and β .
BS | xj is basic.
SBS | xj is superbasic.
A key is sometimes printed before State. Note that unless the optional parameter Scale Option=0 is specified, the tests for assigning a key are applied to the variables of the scaled problem.
A | Alternative optimum possible. The variable is nonbasic, but its reduced gradient is essentially zero. This means that if the variable were allowed to start moving away from its bound, there would be no change in the value of the objective function. The values of the other free variables might change, giving a genuine alternative solution. However, if there are any degenerate variables (labelled D), the actual change might prove to be zero, since one of them could encounter a bound immediately. In either case, the values of the Lagrange multipliers might also change.
D | Degenerate. The variable is basic or superbasic, but it is equal (or very close) to one of its bounds.
I | Infeasible. The variable is basic or superbasic and is currently violating one of its bounds by more than the value of the Feasibility Tolerance.
N | Not precisely optimal. If the slack is superbasic, the dual variable πi is not sufficiently small, as measured by the Optimality Tolerance. If the slack is nonbasic, πi is not sufficiently positive or negative. If a loose Optimality Tolerance has been used, or if iterations were terminated before optimality, this key might be helpful in deciding whether or not to restart the run.
Activity | is the value of xj at the final iterate.
Obj Gradient | is the value of gj at the final iterate. For FP problems, gj is set to zero.
Lower Limit | is the lower bound specified for the variable. None indicates that BL j≤-infbnd.
Upper Limit | is the upper bound specified for the variable. None indicates that BU j≥infbnd.
Reduced Gradnt | is the value of dj at the final iterate (see Section 11.3). For FP problems, dj is set to zero.
m + j | is the value of m+j.
Note: if two problems are the same except that one minimizes f x and the other maximizes -f x , their solutions will be the same but the signs of the dual variables πi and the reduced gradients dj will be reversed.

13.5 The Solution File

If a positive Solution File is specified, the information contained in a printed solution may also be output to the relevant file (which may be the Print file if so desired). Infinite Upper and Lower limits appear as ±1020 rather than None. Other real values are output with format 1pe16.6. The maximum line length is 111 characters, including what would be the carriage-control character if the file were printed.
A Solution file is intended to be read from disk by a self-contained program that extracts and saves certain values as required for possible further computation. Typically the first 14 lines would be ignored. Each subsequent line may be read using
FORMAT (i8, 2x, 2a4, 1x, a1, 1x, a3, 5e16.6, i7)
adapted to suit the occasion. The end of the ROWS section is marked by a line that starts with a 1 and is otherwise blank. If this and the next 4 lines are skipped, the COLUMNS section (see Section 13.4.2) can then be read under the same format. (There should be no need to use any BACKSPACE statements.)

13.6 The Summary File

If Summary File f is specified with f>0, certain brief information will be output to unit f. When E04NQF is run interactively, unit f will usually be the terminal. For batch jobs a disk file should be used, to retain a concise log of each run if desired. (A Summary File is more easily perused than the associated Print file).
A Summary file (like the Print file) is not rewound after a problem has been processed. The maximum line length is 72 characters, including a carriage-control character in column 1.
The following information is included:
1. | The optional parameters supplied via the option setting routines, if any;
2. | The Basis file loaded, if any;
3. | The status of the solution after each basis factorization (whether feasible; the objective value; the number of function calls so far);
4. | The same information every k th iteration, where k is the specified Summary Frequency;
5. | Warnings and error messages;
6. | The exit condition and a summary of the final solution.
Item 4 is preceded by a blank line, but item 5 is not.
The meaning of the printout for linear constraints is the same as that given above for variables, with ‘variable’ replaced by ‘constraint’, n replaced by m, NAMES j replaced by NAMES n+j, BL j and BU j are replaced by BL n+j and BU n+j respectively, and with the following change in the heading:
Constrnt gives the name of the linear constraint.
Note that movement off a constraint (as opposed to a variable moving away from its bound) can be interpreted as allowing the entry in the Residual column to become positive.
Numerical values are output with a fixed number of digits; they are not guaranteed to be accurate to this precision.
E04 Chapter Contents
E04 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


E04NRF : NAG Library, Mark 26

E04 Chapter Contents
E04 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

E04NRF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

E04NRF may be used to supply optional parameters to E04NQF from an external file. The initialization routine E04NPF must have been called before calling E04NRF.

2 Specification

SUBROUTINE E04NRF ( ISPECS, CW, IW, RW, IFAIL)
INTEGER | ISPECS, IW(*), IFAIL
REAL (KIND=nag_wp) | RW(*)
CHARACTER(8) | CW(*)

3 Description

E04NRF may be used to supply values for optional parameters to E04NQF. E04NRF reads an external file and each line of the file defines a single optional parameter. It is only necessary to supply values for those arguments whose values are to be different from their default values.
Each optional parameter is defined by a single character string, of up to 72 characters, consisting of one or more items. The items associated with a given option must be separated by spaces, or equals signs =. Alphabetic characters may be upper or lower case. The string
Print Level = 1
is an example of a string used to set an optional parameter. For each option the string contains one or more of the following items:
– | a mandatory keyword;
– | a phrase that qualifies the keyword;
– | a number that specifies an integer or real value. Such numbers may be up to 40 contiguous characters in Fortran's I, F, E or D formats, terminated by a space if this is not the last item on the line.
Blank strings and comments are ignored. A comment begins with an asterisk (*) and all subsequent characters in the string are regarded as part of the comment.
The file containing the options must start with Begin and must finish with End. An example of a valid options file is:
Begin * Example options file
   Print level = 5
End
Optional parameter settings are preserved following a call to E04NQF and so the keyword Defaults is provided to allow you to reset all the optional parameters to their default values before a subsequent call to E04NQF.
A complete list of optional parameters, their abbreviations, synonyms and default values is given in Section 12 in E04NQF.

4 References

None.

5 Arguments

1:   ISPECS – INTEGERInput
On entry: the unit number of the option file to be read.
Constraint: ISPECS is a valid unit open for reading.
2:   CW* – CHARACTER(8) arrayCommunication Array
Note: the dimension of the array CW must be at least LENCW (see E04NPF).
3:   IW* – INTEGER arrayCommunication Array
Note: the dimension of the array IW must be at least LENIW (see E04NPF).
4:   RW* – REAL (KIND=nag_wp) arrayCommunication Array
Note: the dimension of the array RW must be at least LENRW (see E04NPF).
5:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
The initialization routine E04NPF has not been called.
IFAIL=2
At least one line of the options file is invalid.
Could not read options file on unit ISPECS =value.
Could not read options file on unit ISPECS. This may be due to:
(a) | ISPECS is not a valid unit number;
(b) | a file is not associated with unit ISPECS, or if it is, is unavailable for read access;
(c) | one or more lines of the options file is invalid. Check that all keywords are neither ambiguous nor misspelt;
(d) | Begin was found, but end-of-file was found before End was found;
(e) | end-of-file was found before Begin was found.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

Not applicable.

8 Parallelism and Performance

E04NRF is not threaded in any implementation.

9 Further Comments

E04NSF, E04NTF or E04NUF may also be used to supply optional parameters to E04NQF.

10 Example

This example minimizes the quadratic function f x=cT x+12 xT Hx, where
c = -200.0,-2000.0,-2000.0,-2000.0,-2000.0,400.0,400.0 T
and
H= 2 0 0 0 0 0 0 0 2 0 0 0 0 0 0 0 2 2 0 0 0 0 0 2 2 0 0 0 0 0 0 0 2 0 0 0 0 0 0 0 2 2 0 0 0 0 0 2 2
subject to the bounds
00 0≤x 1≤0 200 00 0≤x 2≤2500 400≤x 3≤0 800 100≤x 4≤0 700 00 0≤x 5≤1500 00 0≤x 6≤1500 00 0≤x 7≤1500
and to the linear constraints
x 1 + x 2 + x 3 + x 4 + x 5 + x 6 + x 7 = 2000 0.15 x 1 + 0.04 x 2 + 0.02 x 3 + 0.04 x 4 + 0.02 x 5 + 0.01 x 6 + 0.03 x 7 ≤ 60 0.03 x 1 + 0.05 x 2 + 0.08 x 3 + 0.02 x 4 + 0.06 x 5 + 0.01 x 6 ≤ 100 0.02 x 1 + 0.04 x 2 + 0.01 x 3 + 0.02 x 4 + 0.02 x 5 ≤ 40 0.02 x 1 + 0.03 x 2 + 0.01 x 5 ≤ 30 1500 ≤ 0.70 x 1 + 0.75 x 2 + 0.80 x 3 + 0.75 x 4 + 0.80 x 5 + 0.97 x 6 250 ≤ 0.02 x 1 + 0.06 x 2 + 0.08 x 3 + 0.12 x 4 + 0.02 x 5 + 0.01 x 6 + 0.97 x 7 ≤ 300
The initial point, which is infeasible, is
x 0=0.0,0.0,0.0,0.0,0.0,0.0,0.0 T.
The optimal solution (to five figures) is
x*=0.0,349.40,648.85,172.85,407.52,271.36,150.02 T.
One bound constraint and four linear constraints are active at the solution. Note that the Hessian matrix H is positive semidefinite.

10.1 Program Text

Program Text (e04nrfe.f90)

10.2 Program Data

Program Options (e04nrfe.opt)

Program Data (e04nrfe.d)

10.3 Program Results

Program Results (e04nrfe.r)

E04 Chapter Contents
E04 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


E04NSF : NAG Library, Mark 26

E04 Chapter Contents
E04 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

E04NSF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
10 Example

1 Purpose

E04NSF may be used to supply individual optional parameters to E04NQF. The initialization routine E04NPF must have been called before calling E04NSF.

2 Specification

SUBROUTINE E04NSF ( STRING, CW, IW, RW, IFAIL)
INTEGER | IW(*), IFAIL
REAL (KIND=nag_wp) | RW(*)
CHARACTER(*) | STRING
CHARACTER(8) | CW(*)

3 Description

E04NSF may be used to supply values for optional parameters to E04NQF. It is only necessary to call E04NSF for those arguments whose values are to be different from their default values. One call to E04NSF sets one argument value.
Each optional parameter is defined by a single character string, of up to 72 characters, consisting of one or more items. The items associated with a given option must be separated by spaces, or equals signs =. Alphabetic characters may be upper or lower case. The string
Print Level = 1
is an example of a string used to set an optional parameter. For each option the string contains one or more of the following items:
– | a mandatory keyword;
– | a phrase that qualifies the keyword;
– | a number that specifies an integer or real value. Such numbers may be up to 40 contiguous characters in Fortran's I, F, E or D formats, terminated by a space if this is not the last item on the line.
For E04NSF, each user-specified option is not normally printed as it is defined, but this printing may be turned on using the keyword List. Thus the statement
CALL E04NSF ('List', CW, IW, RW, IFAIL)
turns on printing of this and subsequent options. Printing may be turned off again using the keyword Nolist.
Optional parameter settings are preserved following a call to E04NQF and so the keyword Defaults is provided to allow you to reset all the optional parameters to their default values before a subsequent call to E04NQF.
A complete list of optional parameters, their abbreviations, synonyms and default values is given in Section 12 in E04NQF.

4 References

None.

5 Arguments

1:   STRING – CHARACTER(*)Input
On entry: a single valid option string (see Section 3 in E04NSF and Section 12 in E04NQF).
2:   CW* – CHARACTER(8) arrayCommunication Array
Note: the dimension of the array CW must be at least LENCW (see E04NPF).
3:   IW* – INTEGER arrayCommunication Array
Note: the dimension of the array IW must be at least LENIW (see E04NPF).
4:   RW* – REAL (KIND=nag_wp) arrayCommunication Array
Note: the dimension of the array RW must be at least LENRW (see E04NPF).
5:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
The initialization routine E04NPF has not been called.
IFAIL=2
The supplied option is invalid. Check that the keywords are neither ambiguous nor misspelt.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

Not applicable.

8 Parallelism and Performance

E04NSF is not threaded in any implementation.

9 Further Comments

E04NRF, E04NTF or E04NUF may also be used to supply optional parameters to E04NQF.

10 Example

See Section 10 in E04NRF.
E04 Chapter Contents
E04 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


E04NTF : NAG Library, Mark 26

E04 Chapter Contents
E04 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

E04NTF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
10 Example

1 Purpose

E04NTF may be used to supply individual integer optional parameters to E04NQF. The initialization routine E04NPF must have been called before calling E04NTF.

2 Specification

SUBROUTINE E04NTF ( STRING, IVALUE, CW, IW, RW, IFAIL)
INTEGER | IVALUE, IW(*), IFAIL
REAL (KIND=nag_wp) | RW(*)
CHARACTER(*) | STRING
CHARACTER(8) | CW(*)

3 Description

E04NTF may be used to supply values for integer optional parameters to E04NQF. It is only necessary to call E04NTF for those arguments whose values are to be different from their default values. One call to E04NTF sets one argument value.
Each integer optional parameter is defined by a single character string in STRING and the corresponding value in IVALUE. For example, the following allows the iteration limit to be defined:
ITNLIM = 1000
IF (M > 500) ITNLIM = 500
CALL E04NTF ('Iterations', ITNLIM, CW, IW, RW, IFAIL)
Optional parameter settings are preserved following a call to E04NQF and so the keyword Defaults is provided to allow you to reset all the optional parameters to their default values before a subsequent call to E04NQF.
A complete list of optional parameters, their abbreviations, synonyms and default values is given in Section 12 in E04NQF.

4 References

None.

5 Arguments

1:   STRING – CHARACTER(*)Input
On entry: a single valid keyword of an integer optional parameter (as described in Section 12 in E04NQF).
2:   IVALUE – INTEGERInput
On entry: an integer value associated with the keyword in STRING.
3:   CW* – CHARACTER(8) arrayCommunication Array
Note: the dimension of the array CW must be at least LENCW (see E04NPF).
4:   IW* – INTEGER arrayCommunication Array
Note: the dimension of the array IW must be at least LENIW (see E04NPF).
5:   RW* – REAL (KIND=nag_wp) arrayCommunication Array
Note: the dimension of the array RW must be at least LENRW (see E04NPF).
6:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
The initialization routine E04NPF has not been called.
IFAIL=2
The supplied option is invalid. Check that the keywords are neither ambiguous nor misspelt.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

Not applicable.

8 Parallelism and Performance

E04NTF is not threaded in any implementation.

9 Further Comments

E04NRF or E04NSF may also be used to supply integer optional parameters to E04NQF.

10 Example

See Section 10 in E04NQF and E04NRF.
E04 Chapter Contents
E04 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


E04NUF : NAG Library, Mark 26

E04 Chapter Contents
E04 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

E04NUF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
10 Example

1 Purpose

E04NUF may be used to supply individual real optional parameters to E04NQF. The initialization routine E04NPF must have been called before calling E04NUF.

2 Specification

SUBROUTINE E04NUF ( STRING, RVALUE, CW, IW, RW, IFAIL)
INTEGER | IW(*), IFAIL
REAL (KIND=nag_wp) | RVALUE, RW(*)
CHARACTER(*) | STRING
CHARACTER(8) | CW(*)

3 Description

E04NUF may be used to supply values for real optional parameters to E04NQF. It is only necessary to call E04NUF for those arguments whose values are to be different from their default values. One call to E04NUF sets one argument value.
Each real optional parameter is defined by a single character string in STRING and the corresponding value in RVALUE. For example the following illustrates how the LU stability tolerance could be defined:
FACTOL = 100.0E0
IF (ILLCON) FACTOL = 5.0E0
CALL E04NUF ('LU Factor Tolerance', FACTOL, CW, IW, RW, IFAIL)
Optional parameter settings are preserved following a call to E04NQF and so the keyword Defaults is provided to allow you to reset all the optional parameters to their default values before a subsequent call to E04NQF.
A complete list of optional parameters, their abbreviations, synonyms and default values is given in Section 12 in E04NQF.

4 References

None.

5 Arguments

1:   STRING – CHARACTER(*)Input
On entry: a single valid keyword of a real optional parameter (as described in Section 12 in E04NQF).
2:   RVALUE – REAL (KIND=nag_wp)Input
On entry: the value associated with the keyword in STRING.
3:   CW* – CHARACTER(8) arrayCommunication Array
Note: the dimension of the array CW must be at least LENCW (see E04NPF).
4:   IW* – INTEGER arrayCommunication Array
Note: the dimension of the array IW must be at least LENIW (see E04NPF).
5:   RW* – REAL (KIND=nag_wp) arrayCommunication Array
Note: the dimension of the array RW must be at least LENRW (see E04NPF).
6:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
The initialization routine E04NPF has not been called.
IFAIL=2
The supplied option is invalid. Check that the keywords are neither ambiguous nor misspelt.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

Not applicable.

8 Parallelism and Performance

E04NUF is not threaded in any implementation.

9 Further Comments

E04NRF or E04NSF may also be used to supply real optional parameters to E04NQF.

10 Example

See Section 10 in E04NRF.
E04 Chapter Contents
E04 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


E04NXF : NAG Library, Mark 26

E04 Chapter Contents
E04 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

E04NXF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
10 Example

1 Purpose

E04NXF is used to get the value of an integer optional parameter. E04NXF can be used before or after calling E04NQF.

2 Specification

SUBROUTINE E04NXF ( STRING, IVALUE, CW, IW, RW, IFAIL)
INTEGER | IVALUE, IW(*), IFAIL
REAL (KIND=nag_wp) | RW(*)
CHARACTER(*) | STRING
CHARACTER(8) | CW(*)

3 Description

E04NXF obtains the current value of an integer option. For example:
CALL E04NXF ('Iterations', ITNLIM, CW, IW, RW, IFAIL)
will result in the value of the optional parameter Iterations Limit being output in ITNLIM.
A complete list of optional parameters, their abbreviations, synonyms and default values is given in Section 12 in E04NQF.

4 References

None.

5 Arguments

1:   STRING – CHARACTER(*)Input
On entry: a single valid keyword of an integer optional parameter (as described in Section 12 in E04NQF).
2:   IVALUE – INTEGEROutput
On exit: the integer value associated with the keyword in STRING.
3:   CW* – CHARACTER(8) arrayCommunication Array
Note: the dimension of the array CW must be at least LENCW (see E04NPF).
4:   IW* – INTEGER arrayCommunication Array
Note: the dimension of the array IW must be at least LENIW (see E04NPF).
5:   RW* – REAL (KIND=nag_wp) arrayCommunication Array
Note: the dimension of the array RW must be at least LENRW (see E04NPF).
6:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
The initialization routine E04NPF has not been called.
IFAIL=2
The supplied option is invalid. Check that the keywords are neither ambiguous nor misspelt.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

Not applicable.

8 Parallelism and Performance

E04NXF is not threaded in any implementation.

9 Further Comments

None.

10 Example

See Section 10 in E04NRF.
E04 Chapter Contents
E04 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


E04NYF : NAG Library, Mark 26

E04 Chapter Contents
E04 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

E04NYF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
10 Example

1 Purpose

E04NYF is used to get the value of a real optional parameter. E04NYF can be used before or after calling E04NQF.

2 Specification

SUBROUTINE E04NYF ( STRING, RVALUE, CW, IW, RW, IFAIL)
INTEGER | IW(*), IFAIL
REAL (KIND=nag_wp) | RVALUE, RW(*)
CHARACTER(*) | STRING
CHARACTER(8) | CW(*)

3 Description

E04NYF obtains the current value of a real option. For example
CALL E04NYF ('Feasibility Tolerance', FEATOL, CW, IW, RW, IFAIL)
will result in the value of the optional parameter Feasibility Tolerance being output in FEATOL.
A complete list of optional parameters, their abbreviations, synonyms and default values is given in Section 12 in E04NQF.

4 References

None.

5 Arguments

1:   STRING – CHARACTER(*)Input
On entry: a single valid keyword of a real optional parameter (as described in Section 12 in E04NQF).
2:   RVALUE – REAL (KIND=nag_wp)Output
On exit: the real value associated with the keyword in STRING.
3:   CW* – CHARACTER(8) arrayCommunication Array
Note: the dimension of the array CW must be at least LENCW (see E04NPF).
4:   IW* – INTEGER arrayCommunication Array
Note: the dimension of the array IW must be at least LENIW (see E04NPF).
5:   RW* – REAL (KIND=nag_wp) arrayCommunication Array
Note: the dimension of the array RW must be at least LENRW (see E04NPF).
6:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
The initialization routine E04NPF has not been called.
IFAIL=2
The supplied option is invalid. Check that the keywords are neither ambiguous nor misspelt.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

Not applicable.

8 Parallelism and Performance

E04NYF is not threaded in any implementation.

9 Further Comments

None.

10 Example

See Section 10 in E04NRF.
E04 Chapter Contents
E04 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


E04PCF : NAG Library, Mark 26

E04 Chapter Contents
E04 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

E04PCF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

E04PCF solves a linear least squares problem subject to fixed lower and upper bounds on the variables.

2 Specification

SUBROUTINE E04PCF ( ITYPE, M, N, A, LDA, B, BL, BU, TOL, X, RNORM, NFREE, W, INDX, IFAIL)
INTEGER | ITYPE, M, N, LDA, NFREE, INDX(N), IFAIL
REAL (KIND=nag_wp) | A(LDA,*), B(M), BL(N), BU(N), TOL, X(N), RNORM, W(N)

3 Description

Given an m by n matrix A, an n-vector l of lower bounds, an n-vector u of upper bounds, and an m-vector b, E04PCF computes an n-vector x that solves the least squares problem Ax=b subject to xi satisfying li ≤ xi ≤ ui .
A facility is provided to return a ‘regularized’ solution, which will closely approximate a minimal length solution whenever A is not of full rank. A minimal length solution is the solution to the problem which has the smallest Euclidean norm.
The algorithm works by applying orthogonal transformations to the matrix and to the right hand side to obtain within the matrix an upper triangular matrix R. In general the elements of x corresponding to the columns of R will be the candidate nonzero solutions. If a diagonal element of R is small compared to the other members of R then this is undesirable. R will be nearly singular and the equations for x thus ill-conditioned. You may specify the tolerance used to determine the relative linear dependence of a column vector for a variable moved from its initial value.

4 References

Lawson C L and Hanson R J (1974) Solving Least Squares Problems Prentice–Hall

5 Arguments

1:   ITYPE – INTEGERInput
On entry: provides the choice of returning a regularized solution if the matrix is not of full rank.
ITYPE=0
Specifies that a regularized solution is to be computed.
ITYPE=1
Specifies that no regularization is to take place.
Suggested value: unless there is a definite need for a minimal length solution we recommend that ITYPE=1 is used.
Constraint: ITYPE=0 or 1.
2:   M – INTEGERInput
On entry: m, the number of linear equations.
Constraint: M≥0.
3:   N – INTEGERInput
On entry: n, the number of variables.
Constraint: N≥0.
4:   A LDA* – REAL (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array A must be at least N.
On entry: the m by n matrix A.
On exit: if ITYPE=1, A contains the product matrix Q⁢A, where Q is an m by m orthogonal matrix generated by E04PCF; otherwise A is unchanged.
5:   LDA – INTEGERInput
On entry: the first dimension of the array A as declared in the (sub)program from which E04PCF is called.
Constraint: LDA≥M.
6:   B M – REAL (KIND=nag_wp) arrayInput/Output
On entry: the right-hand side vector b.
On exit: if ITYPE=1, the product of Q times the original vector b, where Q is as described in argument A; otherwise B is unchanged.
7:   BL N – REAL (KIND=nag_wp) arrayInput
8:   BU N – REAL (KIND=nag_wp) arrayInput
On entry: BL i and BU i must specify the lower and upper bounds, li and ui respectively, to be imposed on the solution vector xi.
Constraint: BL i ≤ BU i, for i=1,2,…,N.
9:   TOL – REAL (KIND=nag_wp)Input
On entry: TOL specifies a parameter used to determine the relative linear dependence of a column vector for a variable moved from its initial value. It determines the computational rank of the matrix. Increasing its value from machine precision will increase the likelihood of additional elements of x being set to zero. It may be worth experimenting with increasing values of TOL to determine whether the nature of the solution, x, changes significantly. In practice a value of machine precision is recommended (see X02AJF).
If on entry TOL<machine precision, then machine precision is used.
Suggested value: TOL=0.0
10:   X N – REAL (KIND=nag_wp) arrayOutput
On exit: the solution vector x.
11:   RNORM – REAL (KIND=nag_wp)Output
On exit: the Euclidean norm of the residual vector b-Ax.
12:   NFREE – INTEGEROutput
On exit: indicates the number of components of the solution vector that are not at one of the constraints.
13:   W N – REAL (KIND=nag_wp) arrayOutput
On exit: contains the dual solution vector. The magnitude of W i gives a measure of the improvement in the objective value if the corresponding bound were to be relaxed so that xi could take different values.
A value of W i equal to the special value -999.0 is indicative of the matrix A not having full rank. It is only likely to occur when ITYPE=1. However a matrix may have less than full rank without W i being set to -999.0. If ITYPE=1 then the values contained in W (other than those set to -999.0) may be unreliable; the corresponding values in INDX may likewise be unreliable. If you have any doubts set ITYPE=0. Otherwise the values of W i have the following meaning:
W i=0
if xi is unconstrained.
W i<0
if xi is constrained by its lower bound.
W i>0
if xi is constrained by its upper bound.
W i
may be any value if li=ui.
14:   INDX N – INTEGER arrayOutput
On exit: the contents of this array describe the components of the solution vector as follows:
INDX i, for i=1,2,…,NFREE
These elements of the solution have not hit a constraint; i.e., W i=0.
INDX i, for i=NFREE+1,…,k
These elements of the solution have been constrained by either the lower or upper bound.
INDX i, for i=k+1 ,…,N
These elements of the solution are fixed by the bounds; i.e., BL i=BU i.
Here k is determined from NFREE and the number of fixed components. (Often the latter will be 0, so k will be N-NFREE.)
15:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, because for this routine the values of the output arguments may be useful even if IFAIL≠0 on exit, the recommended value is -1. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Note: E04PCF may return useful information for one or more of the following detected errors or warnings.
Errors or warnings detected by the routine:
IFAIL=1
On entry, M=value.
Constraint: M≥0.
On entry, M=value and LDA=value.
Constraint: LDA≥M.
On entry, N=value.
Constraint: N≥0.
On entry, when i=value, BL i=value and BU i=value.
Constraint: BL i≤BU i.
IFAIL=2
The routine failed to converge in 3×n iterations. This is not expected. Please contact NAG.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

Orthogonal rotations are used.

8 Parallelism and Performance

E04PCF makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

If either M or N is zero on entry then E04PCF sets IFAIL=0 and simply returns without setting any other output arguments.

10 Example

The example minimizes Ax-b 2 where
A = 0.05 0.05 0.25 -0.25 0.25 0.25 0.05 -0.05 0.35 0.35 1.75 -1.75 1.75 1.75 0.35 -0.35 0.30 -0.30 0.30 0.30 0.40 -0.40 0.40 0.40
and
b = 1.0 2.0 3.0 4.0 5.0 6.0 T
subject to 1≤x≤5.

10.1 Program Text

Program Text (e04pcfe.f90)

10.2 Program Data

Program Data (e04pcfe.d)

10.3 Program Results

Program Results (e04pcfe.r)

E04 Chapter Contents
E04 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


E04RAF : NAG Library, Mark 26

E04 Chapter Contents
E04 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

E04RAF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
▸▿ 3 Description
3.1 Life Cycle of the Handle
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
10 Example

1 Purpose

E04RAF initializes a data structure for the NAG optimization modelling suite for problems such as, quadratic programming (QP), nonlinear programming (NLP), linear semidefinite programming (SDP) and semidefinite programming with bilinear matrix inequalities (BMI-SDP).

2 Specification

SUBROUTINE E04RAF ( HANDLE, NVAR, IFAIL)
INTEGER | NVAR, IFAIL
TYPE (C_PTR) | HANDLE

3 Description

E04RAF initializes an empty problem with n decision variables, x, and returns a handle to the data structure. This handle may then be passed to some of the routines E04REF, E04RFF, E04RGF, E04RHF, E04RJF, E04RKF, E04RLF, E04RNF and E04RPF to formulate the problem (define the objective function and constraints) and to a compatible solver, E04STF or E04SVF, to solve it. The handle must not be changed between calls. When the handle is no longer needed, E04RZF must be called to destroy it and deallocate all the allocated memory and data within. In addition, the suite comprises auxiliary routines for printing (E04RYF), for setting optional parameters (E04ZMF and E04ZPF), for retrieving them (E04ZNF) and for reading data files for linear semidefinite programming (E04RDF).
The handle can store various problem formulations, including quadratic programming (QP)
minimize x∈ℝ n 12 xT Hx + cT x   (a) subject to   lB≤Bx≤uB   (b) lx≤x≤ux ,   (c) (1)
nonlinear programming (NLP)
minimize x∈ℝ n f x   (a) subject to lg≤g x≤ug   (b) lB≤Bx≤uB   (c) lx≤x≤ux   (d) (2)
linear semidefinite programming (SDP)
minimize x∈ℝ n cT x   (a) subject to   ∑ i=1 n xi Aik - A 0 k ⪰ 0 ,  k=1,…,mA   (b) lB≤Bx≤uB   (c) lx≤x≤ux   (d) (3)
or semidefinite programming with bilinear matrix inequalities (BMI-SDP)
minimize x∈ℝ n 12 xT Hx + cT x   (a) subject to   ∑ i,j=1 n xi xj Q ij k + ∑ i=1 n xi Aik - A 0 k ⪰ 0 ,  k=1,…,mA   (b) lB≤Bx≤uB   (c) lx≤x≤ux ,   (d) (4)
where H, Aik and Q ij k denote symmetric matrices, B is a general rectangular matrix, mA is the number of semidefinite constraints (matrix inequalities) and c, l and u are vectors. The expression S⪰0 stands for a constraint on eigenvalues of a symmetric matrix S, namely, all the eigenvalues should be non-negative, i.e., the matrix S should be positive semidefinite.

3.1 Life Cycle of the Handle

Each handle should pass four stages in its life as depicted in the diagram below. These are initialization, problem formulation, problem solution and deallocation. The initialization by E04RAF and deallocation by E04RZF mark the beginning and the end of the life of the handle. During this time the handle must only be modified by the provided routines. Working with a handle which has not been properly initialized will result in IFAIL=1 (uniform across the suite) and is potentially very dangerous as it may cause unpredictable behaviour.
After the handle has been initialized, various routines are provided to add the following basic building blocks to the problem formulation: objective function, simple variable bounds, (standard) linear constraints and matrix constraints. Some of these can be defined at most once (e.g., objective function) and an attempt to redefine them will cause IFAIL=3. Others (matrix constraints) may be composed by several repetitive calls. The routines work in a tight cooperation, if the provided data is not compatible with the previous information, IFAIL=4 is returned.
The handle may be passed to E04REF to define the linear objective function (3)(a), to E04RFF for the quadratic objective function (1)(a), (4)(a), to E04RGF to declare the objective function as a nonlinear function (2)(a) or neither of them if the problem is just to find a feasible point satisfying the constraints. If present, the simple bounds on variables (box constraints, (1)(c), (2)(d), (3)(d), (4)(d)) may be defined by E04RHF. The linear constraints ((1)(b), (2)(c), (3)(c) and (4)(c)) are set by E04RJF. The nonlinear constraints (2)(b) may be declared by E04RKF. If the second derivatives of the nonlinear objective and constraints are available they may be supplied via E04RLF. The linear matrix inequalities (3)(b) or the linear part of (4)(b) are defined by E04RNF, and this call can be repeated several times if more matrix inequality constraints are required. Any existing (already defined) linear matrix inequalities can be extended by bilinear matrix terms in (4)(b) by one or more calls to E04RPF. The routines E04REF, E04RFF, E04RGF, E04RHF, E04RJF, E04RKF, E04RLF, E04RNF and E04RPF may be called in an arbitrary order, however, a call to E04RNF must precede a call to E04RPF for the matrix inequalities with bilinear terms and the nonlinear objective or constraints (E04RGF or E04RKF) must precede the definition of the second derivatives by E04RLF.
When the problem is fully formulated, the handle can be passed to a solver which is compatible with the defined problem. At Mark 26 the NAG optimization modelling suite comprises of E04STF and E04SVF. If the solver cannot deal with the given problem, IFAIL=2 is returned. Once the solver is called, no further modifications of the problem formulation are allowed and calling any of the routines defining the objective function or the constraints will result in IFAIL=2. The solver may be called repetitively, for example, with various optional parameters and/or starting points.
Any optional parameters may be set by a call to E04ZMF at any time between the initialization by E04RAF and the call to the solver or after the solver returns. Several optional parameters can be modified at once by E04ZPF when an option file is used. The current value of the optional parameters may be retrieved by E04ZNF.
For further details, see the documentation of the individual routines and the solvers which also contain a description of all the optional parameters.
Figure 1

4 References

None.

5 Arguments

1:   HANDLE – TYPE (C_PTR)Output
Note: HANDLE does not need to be set on input.
On exit: holds a handle to the internal data structure where an empty problem with NVAR variables is defined. You must not change the handle until the call to E04RZF (deallocation).
2:   NVAR – INTEGERInput
On entry: n, the number of decision variables in the problem.
Constraint: NVAR>0.
3:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=6
On entry, NVAR=value.
Constraint: NVAR>0.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

Not applicable.

8 Parallelism and Performance

E04RAF is not threaded in any implementation.

9 Further Comments

None.

10 Example

See examples associated with other routines of the suite:
– | the example in Section 10 in E04RDF demonstrates how to use the SDPA file reader and how to solve linear semidefinite programming problems, including printing of the matrix Lagrangian multipliers,
– | the example in Section 10 in E04RFF presents an alternative way to compute the nearest correlation matrix by means of nonlinear semidefinite programming,
– | a matrix completion problem (minimization of a rank of a partially unknown matrix) formulated as SDP is demonsrated in Section 10 in E04RHF, the example also demonstrates monitoring mode of the solver E04SVF,
– | the example in Section 10 in E04RJF solves LP/QP problems read in from an MPS file by E04MXF,
– | an application for statistics, E optimal design, solved as an SDP problem is shown in Section 10 in E04RNF,
– | the example in Section 10 in E04RPF reads BMI-SDP problem from a file which might be modified by users, in this case it solves Static Output Feedback (SOF) problem,
– | the example in Section 10 in E04RYF walks through the life cycle of the handle in which a BMI-SDP problem is formulated and solved,
– | an example in Section 10 in E04STF is a small test from Hock and Schittkowski set to show how to call the NLP solver,
– | the simple example in Section 10 in E04SVF demonstrates on the Lovász ϑ function eigenvalue optimization problem formulated as SDP.
E04 Chapter Contents
E04 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


E04RDF : NAG Library, Mark 26

E04 Chapter Contents
E04 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

E04RDF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
▸▿ 3 Description
3.1 Sparse SDPA file format
3.2 Recommendation on how best to use E04RDF
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

E04RDF reads in a linear semidefinite programming problem (SDP) from a file in sparse SDPA format and returns it in the form which is usable by routines E04RAF (initialization), E04REF (linear objective function), E04RNF (linear matrix constraints), E04SVF (solver) and E04RZF (deallocation) from the NAG optimization modelling suite.

2 Specification

SUBROUTINE E04RDF ( INFILE, MAXNVAR, MAXNBLK, MAXNNZ, FILELST, NVAR, NBLK, NNZ, CVEC, NNZA, IROWA, ICOLA, A, BLKSIZEA, IFAIL)
INTEGER | INFILE, MAXNVAR, MAXNBLK, MAXNNZ, FILELST, NVAR, NBLK, NNZ, NNZA(MAXNVAR+1), IROWA(MAXNNZ), ICOLA(MAXNNZ), BLKSIZEA(MAXNBLK), IFAIL
REAL (KIND=nag_wp) | CVEC(MAXNVAR), A(MAXNNZ)

3 Description

E04RDF is capable of reading linear semidefinite programming problems (SDP) from a text file in sparse SDPA format. The problem is captured and returned in the following form:
minimize x∈ℝ n cT x   (a) subject to   ∑ i=1 n xi Ai - A 0 ⪰ 0 ,   (b) (1)
where Ai denotes symmetric matrices and c is a vector. The expression S⪰0 stands for a constraint on the eigenvalues of a symmetric matrix S, namely, all the eigenvalues should be non-negative, i.e., the matrix S should be positive semidefinite.
Please note that this form covers even general linear SDP formulations with multiple linear matrix inequalities and a set of standard linear constraints. A set of mA linear matrix inequalities
∑ i=1 n xi Aik - A 0 k ⪰ 0 ,  k=1,…,mA (2)
can be equivalently expressed as one matrix inequality (1)(b) in the following block diagonal form where the matrices Ai 1 , Ai 2 , … , Ai mA create the diagonal blocks of Ai:
∑ i=1 n xi Ai 1 Ai 2 ⋱ Ai mA - A 01 A 02 ⋱ A 0 mA ⪰ 0 .
In addition, notice that if all matrices A i k belonging to the same block, say block k, are themselves diagonal matrices (or have dimension 1×1), the associated matrix inequality
∑ i=1 n xi Aik - A 0 k ⪰ 0 (3)
defines actually a standard linear constraint
Bx≥l
where l and columns of the matrix B are formed by the diagonals of matrices A 0 k and A 1 k,…,Ank, respectively. Precisely, li = A 0 k ii and b ij = Ajk ii . See Section 10.

3.1 Sparse SDPA file format

The problem data is written in an ASCII input file in a SDPA sparse format which was first introduced in Fujisawa et al. (1998). In the description below we follow closely the specification from Borchers (1999).
The format is line oriented. If more elements are required on the line they need to be separated by a space, a tab or any of the special characters ‘,’, ‘(’, ‘)’, ‘{’ or ‘}’. The file consists of six sections:
1. | Comments. The file can begin with arbitrarily many lines of comments. Each line of comments must begin with ‘"’ or ‘*’.
2. | The first line after the comments contains integer n, the number of variables. The rest of this line is ignored.
3. | The second line after the comments contains integer mA, the number of blocks in the block diagonal structure of the matrices. Additional text on this line after mA is ignored.
4. | The third line after the comments contains a vector of mA integers that give the sizes of the individual blocks. Negative numbers may be used to indicate that a block is actually a diagonal submatrix. Thus a block size of ‘-5’ indicates a 5 by 5 block in which only the diagonal elements are nonzero.
5. | The fourth line after the comments contains an n-dimensional real vector defining the objective function vector c.
6. The remaining lines of the file contain nonzero entries in the constraint matrices, with one entry per line. The format for each line is
matno   blkno   i   j   entry
where matno is the number 0,…,n of the matrix to which this entry belongs and blkno specifies the block number k=1,2,…,mA within this matrix. Together, they uniquely identify the block A matno blkno . Integers i and j are one-based indices which specify a location of the entry within the block. Note that since all matrices are assumed to be symmetric, only entries in the upper triangle of a matrix should be supplied. Finally, entry should give the real value of the entry in the matrix. Precisely, A matno blkno i j = A matno blkno j i = entry .
In the text below and in the file listing (FILELST) we use the word ‘token’ as a reference to a group of contiguous characters without a space or any other delimeters.

3.2 Recommendation on how best to use E04RDF

(a) | The input file with the problem needs to be opened for reading by X04ACF (MODE=0). In this way we avoid possible limitations of maximal lengths of lines inherited by Fortran I/O (X04ACF uses the formatted stream access mode to bypass the restriction). If the file is opened by other means or standard input is used instead, lines within the file might be truncated which would produce a file format error message. This would most likely happen on the line defining the objective function. Setting FILELST=1 might help with possible file formatting errors.
(b) | Unless the dimension of the problem (or its overestimate) is known in advance, call E04RDF initially with MAXNVAR=0, MAXNBLK=0 and MAXNNZ=0. In this case the exact size of the problem is computed and returned in NVAR, NBLK and NNZ. No other data will be stored and none of the arrays CVEC, NNZA, IROWA, ICOLA, A, BLKSIZEA will be referenced. Then the exact storage can be allocated and the file reopened. When E04RDF is called for the second time, the problem is read in and stored in appropriate arrays.
(c) | The example in Section 10 shows a typical sequence of calls to solve the problem read in by E04RDF. First an empty handle needs to be initialized by E04RAF with NVAR variables. This should be followed by calls to E04REF and E04RNF to formulate the objective function and the constraints, respectively. The arguments of both routines use the same naming and storage as in E04RDF so the variables can be passed unchanged; only DIMA in E04RNF is new and should equal to SUM BLKSIZEA 1:NBLK and NNZASUM in E04RNF is the same as NNZ in E04RDF. You may at this point want to modify option settings using E04ZMF. If dual variables (Lagrangian multipliers) are required from the solver, sufficient space needs to be allocated. The size is equal to the sum of the number of elements of dense triangular matrices for each block. For further details, see the argument UA of the solver E04SVF. The solver should be called and then followed, finally, by a call to E04RZF to deallocate memory associated with the problem.

4 References

Borchers B (1999) SDPLIB 1.2, A Library of semidefinite programming test problems. Optimization Methods and Software 11(1) 683–690 http://euler.nmt.edu/~brian/sdplib/
Fujisawa K, Kojima M and Nakata K (1998) SDPA (Semidefinite Programming Algorithm) User's Manual Technical Report B-308 Department of Mathematical and Computing Sciences, Tokyo Institute of Technology.

5 Arguments

1:   INFILE – INTEGERInput
On entry: the unit number associated with the sparse SDPA data file. Note: that the file needs to be opened in read mode by X04ACF with MODE=0.
Constraint: INFILE≥0.
2:   MAXNVAR – INTEGERInput
On entry: the upper limit for the number of variables in the problem. If it is set to zero, CVEC and NNZA will not be referenced.
Constraint: MAXNVAR≥0.
3:   MAXNBLK – INTEGERInput
On entry: the upper limit for the number of matrix constraints (i.e., the number of diagonal blocks within the matrix). If it is set to zero, BLKSIZEA will not be referenced.
Constraint: MAXNBLK≥0.
4:   MAXNNZ – INTEGERInput
On entry: the upper limit on the sum of nonzeros in all matrices Aik, for i=0,1,…,NVAR and k=1,2,…,NBLK. If it is set to zero, IROWA, ICOLA and A will not be referenced.
Constraint: MAXNNZ≥0.
5:   FILELST – INTEGERInput
On entry: if FILELST≠0, a listing of the input data is sent to the current advisory message unit (as defined by X04ABF). This can be useful for debugging the data file.
If FILELST=0, no listing is produced.
6:   NVAR – INTEGEROutput
7:   NBLK – INTEGEROutput
8:   NNZ – INTEGEROutput
On exit: the actual number of the variables n, matrix constraints mA and number of nonzeros of the problem in the file. This also indicates the exact memory needed in CVEC, NNZA, IROWA, ICOLA, A and BLKSIZEA.
9:   CVEC MAXNVAR – REAL (KIND=nag_wp) arrayOutput
On exit: CVEC i, for i=1,2,…,NVAR, stores the dense vector c of the linear objective function.
10:   NNZA MAXNVAR+1 – INTEGER arrayOutput
On exit: NNZA i+1, for i=0,1,…,NVAR, stores the number of nonzero elements in matrices Ai.
11:   IROWA MAXNNZ – INTEGER arrayOutput
12:   ICOLA MAXNNZ – INTEGER arrayOutput
13:   A MAXNNZ – REAL (KIND=nag_wp) arrayOutput
On exit: IROWA, ICOLA and A store the nonzeros in the upper triangle of matrices Ai, for i=0,1,…,NVAR, in the coordinate storage, i.e., IROWA j are one-based row indices, ICOLA j are one-based column indices and A j are the values of the nonzero elements, for j=1,2,…,NNZ. See Section 9.
14:   BLKSIZEA MAXNBLK – INTEGER arrayOutput
On exit: BLKSIZEA k, for k=1,2,…,NBLK, stores the sizes of the diagonal blocks in matrices Ai from the top to the bottom.
15:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, because for this routine the values of the output arguments may be useful even if IFAIL≠0 on exit, the recommended value is -1. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Note: E04RDF may return useful information for one or more of the following detected errors or warnings.
Errors or warnings detected by the routine:
IFAIL=1
At least one of MAXNVAR, MAXNBLK or MAXNNZ is too small. Suggested values are returned in NVAR, NBLK and NNZ, respectively.
IFAIL=2
The token on line value at position value to value was not recognized as a valid integer.
IFAIL=3
The token on line value at position value to value was not recognized as a valid real number.
IFAIL=4
The token on line value starting at position value was too long and was not recognized.
IFAIL=5
An invalid number of variables was given on line value.
The number stated there is value and needs to be at least 1.
IFAIL=6
An invalid number of blocks was given on line value.
The number stated there is value and needs to be at least 1.
IFAIL=7
An invalid size of the block number value was given on line value.
The number stated there is value and needs to be nonzero.
IFAIL=8
Not enough data was given on line value specifying block sizes.
Expected mA tokens but found only value.
IFAIL=9
Not enough data was given on line value specifying the objective function.
Expected n tokens but found only value.
IFAIL=10
Not enough data was given on line value specifying nonzero matrix elements.
Expected value tokens but found only value.
IFAIL=11
Invalid structural data found on line value.
The given matrix number is out of bounds. Its value value must be between 0 and n (inclusive).
IFAIL=12
Invalid structural data found on line value.
The given block number is out of bounds. Its value value must be between 1 and mA (inclusive).
IFAIL=13
Invalid structural data found on line value.
The given row index is out of bounds, it must respect the size of the block. Its value value must be between value and value (inclusive).
IFAIL=14
Invalid structural data found on line value.
The given column index is out of bounds, it must respect the size of the block. Its value value must be between value and value (inclusive).
IFAIL=15
Invalid structural data found on line value.
The specified nonzero element is not in the upper triangle.
The row index is value and column index is value.
IFAIL=16
Invalid structural data found on line value.
The specified element belongs to a diagonal block but is not diagonal.
The row index is value and column index is value.
IFAIL=17
An entry in the constraints with matno=value, blkno=value, row index value and column index value was defined more than once. All entries need to be unique.
IFAIL=18
A premature end of the input stream. The part defining the dimensions of the blocks was not found.
A premature end of the input stream. The part defining the nonzero entries was not found.
A premature end of the input stream. The part defining the number of blocks was not found.
A premature end of the input stream. The part defining the number of variables was not found.
A premature end of the input stream. The part defining the objective function was not found.
IFAIL=19
The input stream seems to be empty. No data was read. This might indicate a problem with opening the file, check that X04ACF was used correctly.
IFAIL=20
Reading from the stream caused an unknown error on line value.
IFAIL=21
On entry, INFILE=value.
Constraint: INFILE≥0.
On entry, MAXNBLK=value.
Constraint: MAXNBLK≥0.
On entry, MAXNNZ=value.
Constraint: MAXNNZ≥0.
On entry, MAXNVAR=value.
Constraint: MAXNVAR≥0.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

Not applicable.

8 Parallelism and Performance

E04RDF is not threaded in any implementation.

9 Further Comments

The following artificial example demonstrates how the elements of Ai matrices are organized within arrays NNZA, IROWA, ICOLA and A. For simplicity let us assume that NBLK=1, BLKSIZEA 1=3 and NVAR=4. Please note that the values of the elements were chosen to ease readability rather than to define a valid problem.
Let the matrix constraint (1)(b) be defined by
A 0 = 0 0.1 0 0.1 0 0.2 0 0.2 0.3 ,
A 1 = 1.1 0 0 0 1.2 1.3 0 1.3 1.4 ,
A 2 ​ empty,
A 3 = 0 0 0 0 3.1 0 0 0 3.2 ,
A 4 = 4.1 4.2 4.3 4.2 0 0 4.3 0 0 .
All matrices Ai have to be symmetric and therefore only the elements in the upper triangles are stored. The table below shows how the arrays would be populated.
IROWA | 0 1. 0 2. 0 3. | 0 1. 0 2. 0 2. 0 3. |  | 0 2. 0 3. | 0 1. 0 2. 0 3.
ICOLA | 0 2. 0 3. 0 3. | 0 1. 0 2. 0 3. 0 3. |  | 0 2. 0 3. | 0 1. 0 1. 0 1.
A | 0.1 0.2 0.3 ︸ | 1.1 1.2 1.3 1.4 ︸ | 000.0︸ | 3.1 3.2 ︸ | 4.1 4.2 4.3 ︸
 | A 0 | A 1 | A 2 | A 3 | A 4
NNZA | 3 | 4 | 0 | 2 | 3
See also Section 3 in E04RNF which accepts the same format.

10 Example

The following example comes from Fujisawa et al. (1998).
Imagine that we want to store the following problem in a file in the SDPA format.
minimize x∈ℝ 2 10 x 1 + 20 x 2 subject to 1 0 1 1 ⁢ x 1 x 2 ≥ 1 1.5 5 2 2 6 ⁢ x 2 - 3 0 0 4 ⪰ 0 .
There are two variables (n=2) in the problem. One linear matrix constraint and one block of linear constraints can be formed as (1) with two diagonal blocks (mA=2). Both blocks have dimension 2 but the first one (defining linear constraints) is only diagonal, thus the sizes will be stated as -2 2 .
The problem can be rewritten as
minimize x∈ℝ 2 cT x subject to A 1⁢x 1 + A 2⁢x 2 - A 0 ⪰ 0
where
  • c= 10 20 T ,
  • A 0 = 1 0 0 0 0 1.5 0 0 0 0 3 0 0 0 0 4 ,
  • A 1 = 1 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 ,
  • A 2 = 0 0 0 0 0 1 0 0 0 0 5 2 0 0 2 6 .
The optimal solution is x*= 1.0 1.0 T with the objective function value 30.0. The optimal Lagrangian multipliers (dual variables) are 10.0, 0.0 and 20/7, -20/7 -20/7, 20/7 .
See also Section 10 in E04RAF for links to further examples in the suite.

10.1 Program Text

Program Text (e04rdfe.f90)

10.2 Program Data

Program Options (e04rdfe.opt)

10.3 Program Results

Program Results (e04rdfe.r)

E04 Chapter Contents
E04 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


E04REF : NAG Library, Mark 26

E04 Chapter Contents
E04 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

E04REF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
10 Example

1 Purpose

E04REF is a part of the NAG optimization modelling suite and defines the linear objective function of the problem.

2 Specification

SUBROUTINE E04REF ( HANDLE, NVAR, CVEC, IFAIL)
INTEGER | NVAR, IFAIL
REAL (KIND=nag_wp) | CVEC(NVAR)
TYPE (C_PTR) | HANDLE

3 Description

After the initialization routine E04RAF has been called, E04REF may be used to define the objective function of the problem as a linear function cT x unless the objective function has already been defined by E04REF, E04RFF or by E04RGF. This will typically be used for linear semidefinite programming problems (SDP)
minimize x∈ℝ n cT x   (a) subject to   ∑ i=1 n xi Aik - A 0 k ⪰ 0 ,  k=1,…,mA   (b) lB≤Bx≤uB   (c) lx≤x≤ux   (d) (1)
or SDP with bilinear matrix inequalities (BMI-SDP) where the objective function has only linear terms. See E04RAF for more details.

4 References

None.

5 Arguments

1:   HANDLE – TYPE (C_PTR)Input
On entry: the handle to the problem. It needs to be initialized by E04RAF and must not be changed.
2:   NVAR – INTEGERInput
On entry: n, the number of decision variables x in the problem. It must be unchanged from the value set during the initialization of the handle by E04RAF.
3:   CVEC NVAR – REAL (KIND=nag_wp) arrayInput
On entry: the dense vector c of the objective function.
4:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, the recommended value is -1. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
The supplied HANDLE does not define a valid handle to the data structure for the NAG optimization modelling suite. It has not been initialized by E04RAF or it has been corrupted.
IFAIL=2
The problem cannot be modified in this phase any more, the solver has already been called.
IFAIL=3
The objective function has already been defined.
IFAIL=4
On entry, NVAR=value, expected value=value.
Constraint: NVAR must match the value given during initialization of HANDLE.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

Not applicable.

8 Parallelism and Performance

E04REF is not threaded in any implementation.

9 Further Comments

None.

10 Example

See Section 10 in E04RAF for links to all examples in the suite.
E04 Chapter Contents
E04 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


E04RFF : NAG Library, Mark 26

E04 Chapter Contents
E04 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

E04RFF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

E04RFF is a part of the NAG optimization modelling suite and defines the linear or the quadratic objective function of the problem.

2 Specification

SUBROUTINE E04RFF ( HANDLE, NNZC, IDXC, C, NNZH, IROWH, ICOLH, H, IFAIL)
INTEGER | NNZC, IDXC(NNZC), NNZH, IROWH(NNZH), ICOLH(NNZH), IFAIL
REAL (KIND=nag_wp) | C(NNZC), H(NNZH)
TYPE (C_PTR) | HANDLE

3 Description

After the initialization routine E04RAF has been called, E04RFF may be used to define the objective function of the problem as a quadratic function cT x+12 xT Hx or a sparse linear function cT x unless the objective function has been defined previously by E04REF, E04RFF or by E04RGF. This objective function will typically be used for quadratic programming problems (QP)
minimize x∈ℝ n 12 xT Hx + cT x   (a) subject to lB≤Bx≤uB   (b) lx≤x≤ux   (c) (1)
or for semidefinite programming problems with bilinear matrix inequalities (BMI-SDP)
minimize x∈ℝ n 12 xT Hx + cT x   (a) subject to   ∑ i,j=1 n xi xj Q ij k + ∑ i=1 n xi Aik - A 0 k ⪰ 0 ,  k=1,…,mA   (b) lB≤Bx≤uB   (c) lx≤x≤ux   (d) (2)
The matrix H is a sparse symmetric n by n matrix. It does not need to be positive definite. See E04RAF for more details.

4 References

None.

5 Arguments

1:   HANDLE – TYPE (C_PTR)Input
On entry: the handle to the problem. It needs to be initialized by E04RAF and must not be changed.
2:   NNZC – INTEGERInput
On entry: the number of nonzero elements in the sparse vector c.
If NNZC=0, c is considered to be zero and the arrays IDXC and C will not be referenced.
Constraint: NNZC≥0.
3:   IDXC NNZC – INTEGER arrayInput
4:   C NNZC – REAL (KIND=nag_wp) arrayInput
On entry: the nonzero elements of the sparse vector c. IDXC i must contain the index of C i in the vector, for i=1,2,…,NNZC. The elements are stored in ascending order. Note that n, the number of variables in the problem, was set in NVAR during the initialization of the handle by E04RAF.
Constraints:
  • 1≤IDXC i≤n, for i=1,2,…,NNZC;
  • IDXC i<IDXC i+1, for i=1,2,…,NNZC-1.
5:   NNZH – INTEGERInput
On entry: the number of nonzero elements in the upper triangle of the matrix H.
If NNZH=0, the matrix H is considered to be zero, the objective function is linear and IROWH, ICOLH and H will not be referenced.
Constraint: NNZH≥0.
6:   IROWH NNZH – INTEGER arrayInput
7:   ICOLH NNZH – INTEGER arrayInput
8:   H NNZH – REAL (KIND=nag_wp) arrayInput
On entry: arrays IROWH, ICOLH and H store the nonzeros of the upper triangle of the matrix H in coordinate storage (CS) format (see Section 2.1.1 in the F11 Chapter Introduction). IROWH specifies one-based row indices, ICOLH specifies one-based column indices and H specifies the values of the nonzero elements in such a way that h ij=H l where i=IROWH l, j=ICOLH l, for l=1,2,…,NNZH. No particular order is expected, but elements should not repeat.
Constraint: 1≤IROWH l≤ICOLH l≤n, for l=1,2,…,NNZH.
9:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, the recommended value is -1. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
The supplied HANDLE does not define a valid handle to the data structure for the NAG optimization modelling suite. It has not been initialized by E04RAF or it has been corrupted.
IFAIL=2
The problem cannot be modified in this phase any more, the solver has already been called.
IFAIL=3
The objective function has already been defined.
IFAIL=6
On entry, NNZC=value.
Constraint: NNZC≥0.
On entry, NNZH=value.
Constraint: NNZH≥0.
IFAIL=7
On entry, i=value, IDXC i=value and IDXC i+1=value.
Constraint: IDXC i<IDXC i+1 (ascending order).
On entry, i=value, IDXC i=value and n=value.
Constraint: 1≤IDXC i≤n.
IFAIL=8
On entry, i=value, ICOLH i=value and n=value.
Constraint: 1≤ICOLH i≤n.
On entry, i=value, IROWH i=value and ICOLH i=value.
Constraint: IROWH i≤ICOLH i (elements within the upper triangle).
On entry, i=value, IROWH i=value and n=value.
Constraint: 1≤IROWH i≤n.
On entry, more than one element of H has row index value and column index value.
Constraint: each element of H must have a unique row and column index.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

Not applicable.

8 Parallelism and Performance

E04RFF is not threaded in any implementation.

9 Further Comments

None.

10 Example

This example demonstrates how to use nonlinear semidefinite programming to find a nearest correlation matrix satisfying additional requirements. This is a viable alternative to routines G02AAF, G02ABF, G02AJF or G02ANF as it easily allows you to add further constraints on the correlation matrix. In this case a problem with a linear matrix inequality and a quadratic objective function is formulated to find the nearest correlation matrix in the Frobenius norm preserving the nonzero pattern of the original input matrix. However, additional box bounds (E04RHF) or linear constraints (E04RJF) can be readily added to further bind individual elements of the new correlation matrix or new matrix inequalities (E04RNF) to restrict its eigenvalues.
The problem is as follows (to simplify the notation only the upper triangular parts are shown). To a given m by m symmetric input matrix G
G = g 11 ⋯ g 1 m ⋱ ⋮ g mm
find correction terms x 1,…,xn which form symmetric matrix G-
G- = g-11 g-12 ⋯ g-1 m g-22 ⋯ g-2 m ⋱ ⋮ g-mm = 1 g 12+x 1 g 13+x 2 ⋯ g 1 m+xi 1 g 23+x 3 1 ⋮ ⋱ 1 g m-1 m+xn 1
so that the following requirements are met:
(a) It is a correlation matrix, i.e., symmetric positive semidefinite matrix with a unit diagonal. This is achieved by the way G- is assembled and by a linear matrix inequality
G- = x 1 0 1 0 ⋯ 0 0 0 ⋯ 0 0 ⋯ 0 ⋱ ⋮ 0 + x 2 0 0 1 ⋯ 0 0 0 ⋯ 0 0 ⋯ 0 ⋱ ⋮ 0 + x 3 0 0 0 ⋯ 0 0 1 ⋯ 0 0 ⋯ 0 ⋱ ⋮ 0 + ⋯ + xn 0 ⋯ 0 0 0 ⋱ ⋮ ⋮ ⋮ 0 0 0 0 1 0 - -1 -g 12 -g 13 ⋯ -g 1 m -1 -g 23 ⋯ -g 2 m -1 ⋯ -g 3 m ⋱ ⋮ -1 ⪰ 0 .
(b) G- is nearest to G in the Frobenius norm, i.e., it minimizes the Frobenius norm of the difference which is equivalent to:
minimize ​12 ∑i≠j g- ij - g ij 2 = ∑ i=1 n xi 2 .
(c) G- preserves the nonzero structure of G. This is met by defining xi only for nonzero elements g ij.
For the input matrix
G = 2 -1 0 0 -1 2 -1 0 0 -1 2 -1 0 0 -1 2
the result is
G- = 1.0000 -0.6823 0.0000 0.0000 -0.6823 1.0000 -0.5344 0.0000 0.0000 -0.5344 1.0000 -0.6823 0.0000 0.0000 -0.6823 1.0000 .
See also Section 10 in E04RAF for links to further examples in the suite.

10.1 Program Text

Program Text (e04rffe.f90)

10.2 Program Data

Program Data (e04rffe.d)

10.3 Program Results

Program Results (e04rffe.r)

E04 Chapter Contents
E04 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


E04RGF : NAG Library, Mark 26

E04 Chapter Contents
E04 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

E04RGF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
▸▿ 9 Further Comments
9.1 Additional Licensor
10 Example

1 Purpose

E04RGF is a part of the NAG optimization modelling suite and declares the objective function of the problem as a nonlinear function with a particular gradient sparsity structure.

2 Specification

SUBROUTINE E04RGF ( HANDLE, NNZFD, IDXFD, IFAIL)
INTEGER | NNZFD, IDXFD(NNZFD), IFAIL
TYPE (C_PTR) | HANDLE

3 Description

After the initialization routine E04RAF has been called (and unless the objective function has been defined previously by E04REF, E04RFF or by E04RGF), E04RGF may be used to declare the objective function of the problem as a nonlinear function and define the sparsity pattern (list of nonzero elements) of its gradient. This objective function will typically be used for nonlinear programming problems (NLP) of the kind:
minimize x∈ℝ n f x   (a) subject to lg≤g x≤ug   (b) lB≤Bx≤uB   (c) lx≤x≤ux   (d) (1)
The values of the nonlinear objective function f x and the nonzero values of its gradient ∂f ∂xi (matching the sparsity pattern) evaluated at particular points in the decision variable space will be communicated to the NLP solver by user-supplied functions (e.g., OBJFUN and OBJGRD). See E04RAF for more details.

4 References

None.

5 Arguments

1:   HANDLE – TYPE (C_PTR)Input
On entry: the handle to the problem. It needs to be initialized by E04RAF and must not be changed.
2:   NNZFD – INTEGERInput
On entry: the number of nonzero elements in the sparse gradient vector of the objective function.
Constraint: NNZFD≥0.
3:   IDXFD NNZFD – INTEGER arrayInput
On entry: the one-based indices of the nonzero elements of the sparse gradient vector. The indices must be stored in ascending order. Note that n, the number of decision variables in the problem, was set in NVAR during the initialization of the handle by E04RAF.
If NNZFD=0, the objective is assumed to be zero and the array IDXFD will not be referenced.
Constraints:
  • 1≤IDXFD i≤n, for i=1,2,…,NNZFD;
  • IDXFD i<IDXFD i+1, for i=1,2,…,NNZFD-1.
4:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, the recommended value is -1. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
The supplied HANDLE does not define a valid handle to the data structure for the NAG optimization modelling suite. It has not been initialized by E04RAF or it has been corrupted.
IFAIL=2
The Hessians of nonlinear functions have already been defined, a nonlinear objective cannot be added.
The problem cannot be modified in this phase any more, the solver has already been called.
IFAIL=3
The objective function has already been defined.
IFAIL=6
On entry, NNZFD=value.
Constraint: NNZFD≥0.
IFAIL=7
On entry, i=value, IDXFD i=value and IDXFD i+1=value.
Constraint: IDXFD i<IDXFD i+1 (ascending order).
On entry, i=value, IDXFD i=value and n=value.
Constraint: 1≤IDXFD i≤n.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

Not applicable.

8 Parallelism and Performance

E04RGF is not threaded in any implementation.

9 Further Comments

9.1 Additional Licensor

Parts of the code for E04STF are distributed according to terms imposed by another licensor. Please refer to Library Licensors for further details.

10 Example

See Section 10 in E04STF.
E04 Chapter Contents
E04 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


E04RHF : NAG Library, Mark 26

E04 Chapter Contents
E04 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

E04RHF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

E04RHF is a part of the NAG optimization modelling suite and defines bounds on the variables of the problem.

2 Specification

SUBROUTINE E04RHF ( HANDLE, NVAR, BL, BU, IFAIL)
INTEGER | NVAR, IFAIL
REAL (KIND=nag_wp) | BL(NVAR), BU(NVAR)
TYPE (C_PTR) | HANDLE

3 Description

After the initialization routine E04RAF has been called, E04RHF may be used to define the variable bounds lx≤x≤ux of the problem unless the bounds have already been defined. This will typically be used for problems, such as quadratic programming (QP)
minimize x∈ℝ n 12 xT Hx + cT x   (a) subject to lB≤Bx≤uB   (b) lx≤x≤ux   (c) (1)
nonlinear programming (NLP)
minimize x∈ℝ n f x   (a) subject to lg≤g x≤ug   (b) lB≤Bx≤uB   (c) lx≤x≤ux   (d) (2)
linear semidefinite programming (SDP)
minimize x∈ℝ n cT x   (a) subject to   ∑ i=1 n xi Aik - A 0 k ⪰ 0 ,  k=1,…,mA   (b) lB≤Bx≤uB   (c) lx≤x≤ux   (d) (3)
or semidefinite programming with bilinear matrix inequalities (BMI-SDP)
minimize x∈ℝ n 12 xT Hx + cT x   (a) subject to   ∑ i,j=1 n xi xj Q ij k + ∑ i=1 n xi Aik - A 0 k ⪰ 0 ,  k=1,…,mA   (b) lB≤Bx≤uB   (c) lx≤x≤ux   (d) (4)
where lx and ux are n-dimensional vectors. Note that upper and lower bounds are specified for all the variables. This form allows full generality in specifying various types of constraint. If certain bounds are not present, the associated elements of lx or ux may be set to special values that are treated as -∞ or +∞. See the description of the optional parameter Infinite Bound Size of the solvers in the suite, E04STF and E04SVF. Its value is denoted as bigbnd further in this text. Note that the bounds are interpreted based on its value at the time of calling this routine and any later alterations to Infinite Bound Size will not affect these constraints.
See E04RAF for more details.

4 References

Candes E and Recht B (2009) Exact matrix completion via convex optimization Foundations of Computation Mathematics (Volume 9) 717–772

5 Arguments

1:   HANDLE – TYPE (C_PTR)Input
On entry: the handle to the problem. It needs to be initialized by E04RAF and must not be changed.
2:   NVAR – INTEGERInput
On entry: n, the number of decision variables x in the problem. It must be unchanged from the value set during the initialization of the handle by E04RAF.
3:   BL NVAR – REAL (KIND=nag_wp) arrayInput
4:   BU NVAR – REAL (KIND=nag_wp) arrayInput
On entry: lx, BL and ux, BU define lower and upper bounds on the variables, respectively. To specify a nonexistent lower bound (i.e., lj=-∞), set BL j≤-bigbnd; to specify a nonexistent upper bound (i.e., uj=∞), set BU j≥bigbnd. Fixing of the variables is not allowed in this release, however, this limitation will be removed in a future release.
Constraints:
  • BL j<BU j, for j=1,2,…,NVAR;
  • BL j<bigbnd, for j=1,2,…,NVAR;
  • BU j>-bigbnd, for j=1,2,…,NVAR.
5:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, the recommended value is -1. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
The supplied HANDLE does not define a valid handle to the data structure for the NAG optimization modelling suite. It has not been initialized by E04RAF or it has been corrupted.
IFAIL=2
The problem cannot be modified in this phase any more, the solver has already been called.
IFAIL=3
Variable bounds have already been defined.
IFAIL=4
On entry, NVAR=value, expected value=value.
Constraint: NVAR must match the value given during initialization of HANDLE.
IFAIL=10
On entry, j=value, BL j=value, bigbnd=value.
Constraint: BL j<bigbnd.
On entry, j=value, BL j=value and BU j=value.
Constraint: BL j<BU j.
On entry, j=value, BU j=value, bigbnd=value.
Constraint: BU j>-bigbnd.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

Not applicable.

8 Parallelism and Performance

E04RHF is not threaded in any implementation.

9 Further Comments

None.

10 Example

There is a vast number of problems which can be reformulated as SDP. This example follows Candes and Recht (2009) to show how a rank minimization problem can be approximated by SDP. In addition, it demonstrates how to work with the monitor mode of E04SVF.
The problem can be stated as follows: Let's have m respondents answering k questions where they express their preferences as a number between 0 and 1 or the question can be left unanswered. The task is to fill in the missing entries, i.e., to guess the unexpressed preferences. This problem falls into the category of matrix completion. The idea is to choose the missing entries to minimize the rank of the matrix as it is commonly believed that only a few factors contribute to an individual's tastes or preferences.
Rank minimization is in general NP-hard but it can be approximated by a heuristic, minimizing the nuclear norm of the matrix. The nuclear norm of a matrix is the sum of its singular values. A rank deficient matrix must have (several) zero singular values. Given the fact that the singular values are always non-negative, a minimization of the nuclear norm has the same effect as ℓ 1 norm in compress sensing, i.e., it encourages many singular values to be zero and thus it can be considered as a heuristic for the original rank minimization problem.
Let Y^ denote the partially filled in m×k matrix with the valid responses on i,j∈Ω positions. We are looking for Y of the same size so that the valid responses are unchanged and the nuclear norm (denoted here as ·*) is minimal.
minimizeY Y* subject to   Y ij = Y^ij  for all  i,j∈Ω.
This is equivalent to
minimize W 1, W 2, Y trace W 1+ trace W 2 subject to   Y ij = Y^ij  for all  i,j∈Ω W 1 Y YT W 2 ⪰ 0
which is the linear semidefinite problem solved in this example, see Candes and Recht (2009) and the references therein for details.
This example has m=15 respondents and k=6 answers. The obtained answers are
Y^ = * * * * * 0.4 0.6 0.4 0.8 * * * * * 0.8 * 0.2 * 0.8 0.2 * * * * * 0.4 * 0.0 * 0.2 0.4 * * 0.2 * 0.2 * 0.8 0.2 0.6 * * * * 0.2 * * * * 0.4 * 0.6 0.0 * * * 0.4 * * * * * 0.2 0.2 0.4 0.4 * * * * 1.0 0.8 1.0 * 0.2 * * 0.6 * * * * * 0.2 0.6 * 0.2 0.4 * *
where * denotes missing entries (-1.0 is used instead in the data file). The obtained matrix has rank 4 and it is shown below printed to 1-digit accuracy:
Y = 0.5 0.3 0.2 0.2 0.4 0.4 0.6 0.4 0.8 0.2 0.3 0.4 0.4 0.3 0.8 0.0 0.2 0.2 0.8 0.2 0.3 0.4 0.3 0.4 0.0 0.4 0.2 0.0 0.2 0.2 0.4 0.1 0.2 0.2 0.1 0.2 0.6 0.8 0.2 0.6 0.2 0.4 0.1 0.1 0.2 0.0 0.0 0.1 0.6 0.4 0.1 0.6 0.0 0.3 0.2 0.1 0.4 0.0 0.1 0.1 0.5 0.3 0.2 0.2 0.4 0.4 0.7 0.4 0.3 0.0 1.0 0.8 1.0 0.3 0.2 0.5 0.5 0.6 0.2 0.1 0.1 0.1 0.2 0.2 0.6 0.3 0.2 0.4 0.2 0.3 .
The example also turns on monitor mode of E04SVF, there is a time limit introduced for the solver which is being checked at the end of every outer iteration. If the time limit is reached, the routine is stopped by setting INFORM=0 within the monitor step.
See also Section 10 in E04RAF for links to further examples in the suite.

10.1 Program Text

Program Text (e04rhfe.f90)

10.2 Program Data

Program Data (e04rhfe.d)

10.3 Program Results

Program Results (e04rhfe.r)

E04 Chapter Contents
E04 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


E04RJF : NAG Library, Mark 26

E04 Chapter Contents
E04 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

E04RJF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

E04RJF is a part of the NAG optimization modelling suite and defines the block of linear constraints of the problem.

2 Specification

SUBROUTINE E04RJF ( HANDLE, NCLIN, BL, BU, NNZB, IROWB, ICOLB, B, IDLC, IFAIL)
INTEGER | NCLIN, NNZB, IROWB(NNZB), ICOLB(NNZB), IDLC, IFAIL
REAL (KIND=nag_wp) | BL(NCLIN), BU(NCLIN), B(NNZB)
TYPE (C_PTR) | HANDLE

3 Description

After the initialization routine E04RAF has been called, E04RJF may be used to define the linear constraints lB≤Bx≤uB of the problem unless the linear constraints have already been defined. This will typically be used for problems, such as quadratic programming (QP)
minimize x∈ℝ n 12 xT Hx + cT x   (a) subject to   lB≤Bx≤uB   (b) lx≤x≤ux ,   (c) (1)
nonlinear programming (NLP)
minimize x∈ℝ n f x   (a) subject to lg≤g x≤ug   (b) lB≤Bx≤uB   (c) lx≤x≤ux   (d) (2)
linear semidefinite programming (SDP)
minimize x∈ℝ n cT x   (a) subject to   ∑ i=1 n xi Aik - A 0 k ⪰ 0 ,  k=1,…,mA   (b) lB≤Bx≤uB   (c) lx≤x≤ux   (d) (3)
or semidefinite programming with bilinear matrix inequalities (BMI-SDP)
minimize x∈ℝ n 12 xT Hx + cT x   (a) subject to   ∑ i,j=1 n xi xj Q ij k + ∑ i=1 n xi Aik - A 0 k ⪰ 0 ,  k=1,…,mA   (b) lB≤Bx≤uB   (c) lx≤x≤ux   (d) (4)
where n is the number of decision variables, B is a general mB×n rectangular matrix and lB and uB are mB-dimensional vectors. Note that upper and lower bounds are specified for all the constraints. This form allows full generality in specifying various types of constraint. In particular, the jth constraint may be defined as an equality by setting lj=uj. If certain bounds are not present, the associated elements of lB or uB may be set to special values that are treated as -∞ or +∞. See the description of the optional parameter Infinite Bound Size of the solvers in the suite, E04STF and E04SVF. Its value is denoted as bigbnd further in this text. Note that the bounds are interpreted based on its value at the time of calling this routine and any later alterations to Infinite Bound Size will not affect these constraints.
See E04RAF for more details.

4 References

None.

5 Arguments

1:   HANDLE – TYPE (C_PTR)Input
On entry: the handle to the problem. It needs to be initialized by E04RAF and must not be changed.
2:   NCLIN – INTEGERInput
On entry: mB, the number of linear constraints (number of rows of the matrix B).
If NCLIN=0, no linear constraints will be defined and BL, BU, NNZB, IROWB, ICOLB and B will not be referenced.
Constraint: NCLIN≥0.
3:   BL NCLIN – REAL (KIND=nag_wp) arrayInput
4:   BU NCLIN – REAL (KIND=nag_wp) arrayInput
On entry: BL and BU define lower and upper bounds of the linear constraints, lB and uB, respectively. To define the jth constraint as equality, set BL j=BU j=β, where β<bigbnd. To specify a nonexistent lower bound (i.e., lj=-∞), set BL j≤-bigbnd; to specify a nonexistent upper bound, set BU j≥bigbnd.
Constraints:
  • BL j≤BU j, for j=1,2,…,NCLIN;
  • BL j<bigbnd, for j=1,2,…,NCLIN;
  • BU j>-bigbnd, for j=1,2,…,NCLIN;
  • if BL j=BU j, BL j<bigbnd, for j=1,2,…,NCLIN.
5:   NNZB – INTEGERInput
On entry: NNZB gives the number of nonzeros in matrix B.
Constraint: if NCLIN>0, NNZB>0.
6:   IROWB NNZB – INTEGER arrayInput
7:   ICOLB NNZB – INTEGER arrayInput
8:   B NNZB – REAL (KIND=nag_wp) arrayInput
On entry: arrays IROWB, ICOLB and B store NNZB nonzeros of the sparse matrix B in coordinate storage (CS) format (see Section 2.1.1 in the F11 Chapter Introduction). The matrix B has dimensions mB×n, where n, the number of variables in the problem, was set in NVAR during the initialization of the handle by E04RAF. IROWB specifies one-based row indices, ICOLB specifies one-based column indices and B specifies the values of the nonzero elements in such a way that b ij=B l where i=IROWB l and j=ICOLB l, for l=1,2,…,NNZB. No particular order of elements is expected, but elements should not repeat.
Constraint: 1≤IROWB l≤NCLIN, 1≤ICOLB l≤n, for l=1,2,…,NNZB.
9:   IDLC – INTEGERInput/Output
Note: IDLC is reserved for future releases of the NAG Library.
On entry: if IDLC=0, new linear constraints are added to the problem definition. This is the only value allowed at the moment.
Constraint: IDLC=0.
On exit: the number of the last linear constraint added, thus NCLIN.
10:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, the recommended value is -1. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
The supplied HANDLE does not define a valid handle to the data structure for the NAG optimization modelling suite. It has not been initialized by E04RAF or it has been corrupted.
IFAIL=2
The problem cannot be modified in this phase any more, the solver has already been called.
IFAIL=3
A set of linear constraints has already been defined.
IFAIL=4
On entry, IDLC=value.
Constraint: IDLC=0.
IFAIL=6
On entry, NCLIN=value.
Constraint: NCLIN≥0.
On entry, NNZB=value.
Constraint: NNZB>0.
IFAIL=8
On entry, i=value, ICOLB i=value and n=value.
Constraint: 1≤ICOLB i≤n.
On entry, i=value, IROWB i=value and NCLIN=value.
Constraint: 1≤IROWB i≤NCLIN.
On entry, more than one element of B has row index value and column index value.
Constraint: each element of B must have a unique row and column index.
IFAIL=10
On entry, j=value, BL j=value, bigbnd=value.
Constraint: BL j<bigbnd.
On entry, j=value, BL j=value and BU j=value.
Constraint: BL j≤BU j.
On entry, j=value, BU j=value, bigbnd=value.
Constraint: BU j>-bigbnd.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

Not applicable.

8 Parallelism and Performance

E04RJF is not threaded in any implementation.

9 Further Comments

None.

10 Example

This example demonstrates how to use the MPS file reader E04MXF and this suite of routines to define and solve a QP problem. E04MXF uses a different output format to the one required by E04RJF, in particular, it uses the compressed column storage (CCS) (see Section 2.1.3 in the F11 Chapter Introduction) instead of the coordinate storage and the linear objective vector is included in the system matrix. Therefore a simple transformation is needed before calling E04RJF as demonstrated in the example program.
The data file stores the following problem:
minimize   cT x + 12 xT H x   subject to   lB ≤Bx ≤uB, -2 ≤A x ≤2,
where
c= -4.0 -1.0 -1.0 -1.0 -1.0 -1.0 -1.0 -0.1 -0.3 ,   H= 2 1 1 1 1 0 0 0 0 1 2 1 1 1 0 0 0 0 1 1 2 1 1 0 0 0 0 1 1 1 2 1 0 0 0 0 1 1 1 1 2 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 ,
B= 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 4.0 1.0 2.0 3.0 4.0 -2.0 1.0 1.0 1.0 1.0 1.0 -1.0 1.0 -1.0 1.0 1.0 1.0 1.0 1.0 ,
lB= -2.0 -2.0 -2.0   and   uB= 1.5 1.5 4.0 .
The optimal solution (to five figures) is
x*=2.0,-0.23333,-0.26667,-0.3,-0.1,2.0,2.0,-1.7777,-0.45555 T.
See also Section 10 in E04RAF for links to further examples in this suite.

10.1 Program Text

Program Text (e04rjfe.f90)

10.2 Program Data

Program Options (e04rjfe.opt)

10.3 Program Results

Program Results (e04rjfe.r)

E04 Chapter Contents
E04 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


E04RKF : NAG Library, Mark 26

E04 Chapter Contents
E04 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

E04RKF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
▸▿ 9 Further Comments
9.1 Additional Licensor
10 Example

1 Purpose

E04RKF is a part of the NAG optimization modelling suite and defines the number of nonlinear constraints of the problem as well as the sparsity structure of their first derivatives.

2 Specification

SUBROUTINE E04RKF ( HANDLE, NCNLN, BL, BU, NNZGD, IROWGD, ICOLGD, IFAIL)
INTEGER | NCNLN, NNZGD, IROWGD(NNZGD), ICOLGD(NNZGD), IFAIL
REAL (KIND=nag_wp) | BL(NCNLN), BU(NCNLN)
TYPE (C_PTR) | HANDLE

3 Description

After the initialization routine E04RAF has been called, E04RKF may be used to define the nonlinear constraints lg≤g x≤ug of the problem unless the nonlinear constraints have already been defined. This will typically be used for nonlinear programming problems (NLP) of the kind:
minimize x∈ℝ n f x   (a) subject to lg≤g x≤ug   (b) lB≤Bx≤uB   (c) lx≤x≤ux   (d) (1)
where n is the number of the decision variables x, mg is the number of the nonlinear constraints (in (1)(b)) and g x, lg and ug are mg-dimensional vectors. Linear constraints ((1)(c)), which require no separate gradient information, can be introduced by E04RJF and Box constraints ((1)(d)) can be introduced by E04RHF.
Note that upper and lower bounds are specified for all the constraints. This form allows full generality in specifying various types of constraint. In particular, the jth constraint may be defined as an equality by setting lj=uj. If certain bounds are not present, the associated elements lj or uj may be set to special values that are treated as -∞ or +∞. See the description of the optional parameter Infinite Bound Size of the solver E04STF. Its value is denoted as bigbnd further in this text. Note that the bounds are interpreted based on its value at the time of calling this routine and any later alterations to Infinite Bound Size will not affect these constraints.
Since each nonlinear constraint is most likely to involve a small subset of the decision variables, the partial derivatives of the constraint functions with respect to those variables are best expressed as a sparse Jacobian matrix of mg rows and n columns. The row and column positions of all the nonzero derivatives must be registered with the handle through E04RKF.
The values of the nonlinear constraint functions and their nonzero gradients at particular points in the decision variable space will be communicated to the NLP solver by user-supplied functions (e.g., CONFUN and CONGRD for E04STF).
See E04RAF for more details.

4 References

None.

5 Arguments

1:   HANDLE – TYPE (C_PTR)Input
On entry: the handle to the problem. It needs to be initialized by E04RAF and must not be changed.
2:   NCNLN – INTEGERInput
On entry: mg, the number of nonlinear constraints (number of rows of the Jacobian matrix).
If NCNLN=0, no nonlinear constraints will be defined and BL, BU, NNZGD, IROWGD and ICOLGD will not be referenced.
Constraint: NCNLN≥0.
3:   BL NCNLN – REAL (KIND=nag_wp) arrayInput
4:   BU NCNLN – REAL (KIND=nag_wp) arrayInput
On entry: BL and BU define lower and upper bounds of the nonlinear constraints, lg and ug, respectively. To define the jth constraint as equality, set BL j = BU j=β , where β<bigbnd . To specify a nonexistent lower bound (i.e., lj = -∞ ), set BL j ≤ -bigbnd ; to specify a nonexistent upper bound, set BU j ≥ bigbnd .
Constraints:
  • BL j≤BU j, for j=1,2,…,NCNLN;
  • BL j<bigbnd, for j=1,2,…,NCNLN;
  • BU j>-bigbnd, for j=1,2,…,NCNLN.
5:   NNZGD – INTEGERInput
On entry: NNZGD gives the number of nonzeros in the Jacobian matrix.
Constraint: if NCNLN>0, NNZGD>0.
6:   IROWGD NNZGD – INTEGER arrayInput
7:   ICOLGD NNZGD – INTEGER arrayInput
On entry: arrays IROWGD and ICOLGD store the sparsity structure (pattern) of the Jacobian matrix as NNZGD nonzeros in coordinate storage (CS) format (see Section 2.1.1 in the F11 Chapter Introduction). The matrix has dimensions NCNLN×n. IROWGD specifies one-based row indices and ICOLGD specifies one-based column indices. No particular order of elements is expected, but elements should not repeat and the same order should be used when the Jacobian is evaluated for the solver, e.g., the value of ∂gi ∂ xj where i=IROWGD l and j=ICOLGD l should be stored in GDX l, for l=1,2,…,NNZGD.
Constraints:
  • 1≤IROWGD l≤NCNLN, for l=1,2,…,NNZGD;
  • 1≤ICOLGD l≤n, for l=1,2,…,NNZGD.
8:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, the recommended value is -1. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
The supplied HANDLE does not define a valid handle to the data structure for the NAG optimization modelling suite. It has not been initialized by E04RAF or it has been corrupted.
IFAIL=2
The Hessian of the nonlinear objective has already been defined, nonlinear constraints cannot be added.
The problem cannot be modified in this phase any more, the solver has already been called.
IFAIL=3
A set of nonlinear constraints has already been defined.
IFAIL=6
On entry, NCNLN=value.
Constraint: NCNLN≥0.
On entry, NNZGD=value.
Constraint: NNZGD>0.
IFAIL=8
On entry, i=value, ICOLGD i=value and n=value.
Constraint: 1≤ICOLGD i≤n.
On entry, i=value, IROWGD i=value and NCNLN=value.
Constraint: 1≤IROWGD i≤NCNLN.
On entry, more than one element of structural Jacobian matrix has row index value and column index value.
Constraint: each element of structural Jacobian matrix must have a unique row and column index.
IFAIL=10
On entry, j=value, BL j=value, bigbnd=value.
Constraint: BL j<bigbnd.
On entry, j=value, BL j=value and BU j=value.
Constraint: BL j≤BU j.
On entry, j=value, BU j=value, bigbnd=value.
Constraint: BU j>-bigbnd.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

Not applicable.

8 Parallelism and Performance

E04RKF is not threaded in any implementation.

9 Further Comments

9.1 Additional Licensor

Parts of the code for E04STF are distributed according to terms imposed by another licensor. Please refer to Library Licensors for further details.

10 Example

See Section 10 in E04STF.
E04 Chapter Contents
E04 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


E04RLF : NAG Library, Mark 26

E04 Chapter Contents
E04 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

E04RLF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
▸▿ 9 Further Comments
9.1 Additional Licensor
10 Example

1 Purpose

E04RLF is a part of the NAG optimization modelling suite and defines the structure of the Hessians of the nonlinear objective and constraints, on assumption that they are present in the problem. Alternatively, it may be used to define the Hessian of the Lagrangian.

2 Specification

SUBROUTINE E04RLF ( HANDLE, IDF, NNZH, IROWH, ICOLH, IFAIL)
INTEGER | IDF, NNZH, IROWH(NNZH), ICOLH(NNZH), IFAIL
TYPE (C_PTR) | HANDLE

3 Description

After the initialization routine E04RAF has been called and an objective function f or nonlinear constraint function gi has been registered with E04RGF and E04RKF, E04RLF can be used to define the sparsity structure of the Hessians, H, of those functions (i.e., the second partial derivatives with respect to the decision variables) or a linear combination of them, called the Lagrangian.
  • Defining ∇2 f ≡ ∂2 f ∂2 x 1 ∂2 f ∂x 2∂x 1 … ∂2 f ∂xn∂x 1 ∂2 f ∂x 1∂x 2 ∂2 f ∂2 x 2 … ∂2 f ∂xn∂x 2 ⋮ ⋮ ⋱ ⋮ ∂2 f ∂x 1∂xn ∂2 f ∂x 2∂xn … ∂2 f ∂2 xn ;
  • the Hessian of the Lagrangian function ≡ σ ⁢ ∇ 2 f + ∑i=1 m λi ⁢ ∇2 gi ;
  • the Hessian of the objective function ≡∇2 f;
  • the Hessian of the constraint functions ≡∇2 gi .
Each of the symmetric n×n Hessian matrices will have its own sparsity structure, in general. These structures can be given in separate E04RLF calls, or merged together in the Lagrangian and given in one call.
The nonzero values of the Hessians at particular points in the decision variable space will be communicated to the NLP solver by user-supplied functions (e.g., HESS for E04STF).
Some NLP solvers (e.g., E04STF) expect either all of the Hessians (for objective and nonlinear constraints) to be supplied by the user or none and they will terminate with an error indicator if only some but not all of the Hessians have been introduced by E04RLF.
Some NLP solvers (e.g., E04STF, again) will automatically switch to using internal approximations for the Hessians if none have been introduced by E04RLF. This usually results in a slower convergence (more iterations to the solution) and might even result in no solution being attainable within the ordinary tolerances.

4 References

None.

5 Arguments

1:   HANDLE – TYPE (C_PTR)Input
On entry: the handle to the problem. It needs to be initialized by E04RAF and must not be changed.
2:   IDF – INTEGERInput
On entry: specifies the quantities for which a sparsity structure is provided in NNZH, IROWH and ICOLH.
IDF=-1
The sparsity structure of the Hessian of the Lagrangian is provided.
IDF=0
The sparsity structure of the Hessian of the objective function is provided.
IDF>0
The sparsity structure of the Hessian of the IDFth constraint function is provided.
The value of IDF will also determine how an NLP solver will call the user-supplied subroutines that evaluate these nonzeros at particular points of the decision variable space, i.e., whether the solver will expect the nonzero values of the objective and constraint Hessians in separate calls or merged in the Lagrangian Hessian, in one call. See, for example, HESS of E04STF.
Constraint: -1≤IDF≤ncnln.
Note: ncnln, the number of nonlinear constraints registered with the handle.
3:   NNZH – INTEGERInput
On entry: the number of nonzero elements in the upper triangle of the matrix H.
Constraint: NNZH>0.
4:   IROWH NNZH – INTEGER arrayInput
5:   ICOLH NNZH – INTEGER arrayInput
On entry: arrays IROWH and ICOLH store the nonzeros of the upper triangle of the matrix H in coordinate storage (CS) format (see Section 2.1.1 in the F11 Chapter Introduction). IROWH specifies one-based row indices, ICOLH specifies one-based column indices and specifies the values of the nonzero elements in such a way that h ij=H l where i=IROWH l and j=ICOLH l, for l=1,2,…,NNZH. No particular order is expected, but elements should not repeat.
Constraint: 1≤IROWH l≤ICOLH l≤n, for l=1,2,…,NNZH.
6:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, the recommended value is -1. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
The supplied HANDLE does not define a valid handle to the data structure for the NAG optimization modelling suite. It has not been initialized by E04RAF or it has been corrupted.
IFAIL=2
Neither nonlinear objective nor nonlinear constraints are present. The structure of the Hessian cannot be defined.
No nonlinear objective has been defined, its Hessian cannot be set.
The problem cannot be modified in this phase any more, the solver has already been called.
IFAIL=3
On entry, IDF=value.
The structure of the Hessian of nonlinear function linked to the given IDF has already been defined.
The structure of the Hessian of the Lagrangian has already been defined.
The structure of the individual Hessians has already been defined, the Hessian of the Lagrangian cannot be defined.
IFAIL=6
On entry, NNZH=value.
Constraint: NNZH>0.
IFAIL=7
On entry, IDF=value.
Constraint: value≤IDF≤value.
IFAIL=8
On entry, i=value, ICOLH i=value and n=value.
Constraint: 1≤ICOLH i≤n.
On entry, i=value, IROWH i=value and ICOLH i=value.
Constraint: IROWH i≤ICOLH i (elements within the upper triangle).
On entry, i=value, IROWH i=value and n=value.
Constraint: 1≤IROWH i≤n.
On entry, more than one element of structural matrix H has row index value and column index value.
Constraint: each element of structural matrix H must have a unique row and column index.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

Not applicable.

8 Parallelism and Performance

E04RLF is not threaded in any implementation.

9 Further Comments

9.1 Additional Licensor

Parts of the code for E04STF are distributed according to terms imposed by another licensor. Please refer to Library Licensors for further details.

10 Example

See Section 10 in E04STF.
E04 Chapter Contents
E04 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


E04RNF : NAG Library, Mark 26

E04 Chapter Contents
E04 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

E04RNF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
▸▿ 3 Description
3.1 Input data organization
3.2 Definition of Bilinear Matrix Inequalities (BMI)
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

E04RNF is a part of the NAG optimization modelling suite and defines one or more linear matrix constraints of the problem.

2 Specification

SUBROUTINE E04RNF ( HANDLE, NVAR, DIMA, NNZA, NNZASUM, IROWA, ICOLA, A, NBLK, BLKSIZEA, IDBLK, IFAIL)
INTEGER | NVAR, DIMA, NNZA(NVAR+1), NNZASUM, IROWA(NNZASUM), ICOLA(NNZASUM), NBLK, BLKSIZEA(NBLK), IDBLK, IFAIL
REAL (KIND=nag_wp) | A(NNZASUM)
TYPE (C_PTR) | HANDLE

3 Description

After the initialization routine E04RAF has been called, E04RNF may be used to add one or more linear matrix inequalities
∑ i=1 n xi Ai - A 0 ⪰ 0 (1)
to the problem definition. Here Ai are d by d symmetric matrices. The expression S⪰0 stands for a constraint on eigenvalues of a symmetric matrix S, namely, all the eigenvalues should be non-negative, i.e., the matrix S should be positive semidefinite.
Typically, this will be used in linear semidefinite programming problems (SDP)
minimize x∈ℝ n cT x   (a) subject to   ∑ i=1 n xi Aik - A 0 k ⪰ 0 ,  k=1,…,mA   (b) lB≤Bx≤uB   (c) lx≤x≤ux   (d) (2)
or to define the linear part of bilinear matrix inequalities (3)(b) in (BMI-SDP)
minimize x∈ℝ n 12 xT Hx + cT x   (a) subject to   ∑ i,j=1 n xi xj Q ij k + ∑ i=1 n xi Aik - A 0 k ⪰ 0 ,  k=1,…,mA   (b) lB≤Bx≤uB   (c) lx≤x≤ux   (d) (3)
E04RNF can be called repeatedly to accumulate more matrix inequalities. See E04RAF for more details.

3.1 Input data organization

All the matrices Ai, for i=0,1,…,n, are symmetric and thus only their upper triangles are passed to the routine. They are stored in sparse coordinate storage format (see Section 2.1.1 in the F11 Chapter Introduction), i.e., every nonzero from the upper triangles is coded as a triplet of row index, column index and the numeric value. These triplets of all (upper triangle) nonzeros from all Ai matrices are passed to the routine in three arrays: IROWA for row indices, ICOLA for column indices and A for the values. No particular order of nonzeros within one matrix is enforced but all nonzeros from A 0 must be stored first, followed by all nonzero from A 1, followed by A 2, etc.
The number of stored nonzeros from each Ai matrix is given in NNZA i+1, thus this array indicates which section of arrays IROWA, ICOLA and A belongs to which Ai matrix. See Table 1 and the example in Section 9. See also E04RDF which uses the same data organization.
IROWA | upper triangle | upper triangle |  | upper triangle
ICOLA | nonzeros | nonzeros | ⋯ | nonzeros
A | from ​ A 0 ︸ | from ​ A 1 ︸ |  | from ​ An ︸
 | NNZA 1 | NNZA 2 |  | NNZA n+1
Table 1
Coordinate storage format of matrices A 0, A 1,…, An in input arrays
There are two possibilities for defining more matrix inequality constraints
∑ i=1 n xi A i k - A 0 k ⪰ 0 ,  k=1,2,…,mA (4)
to the problem. The first is to call E04RNF mA times and define a single matrix inequality at a time. This might be more straightforward and therefore it is recommended. Alternatively, it is possible to merge all mA constraints into one inequality and pass them in a single call to E04RNF. It is easy to see that (4) can be equivalently expressed as one bigger matrix inequality with the following block diagonal structure
∑ i=1 n xi Ai 1 Ai 2 ⋱ Ai mA - A 01 A 02 ⋱ A 0 mA ⪰ 0 .
If dk denotes the dimension of inequality k, the new merged inequality has dimension d= ∑ k=1 mA dk and each of the Ai matrices is formed by A i 1 , A i 2 ,…, A i mA stored as mA diagonal blocks. In such a case, NBLK is set to mA and BLKSIZEA k to dk, the size of the kth diagonal blocks. This might be useful in connection with E04RDF.
On the other hand, if there is no block structure and just one matrix inequality is provided, NBLK should be set to 1 and BLKSIZEA is not referenced.

3.2 Definition of Bilinear Matrix Inequalities (BMI)

E04RNF is designed to be used together with E04RPF to define bilinear matrix inequalities (3)(b). E04RNF sets the linear part of the constraint and E04RPF expands it by higher order terms. To distinquish which linear matrix inequality (or more precisely, which block) is to be expanded, E04RPF needs the number of the block, IDBLK. The blocks are numbered as they are added, starting from 1.
Whenever a matrix inequality (or a set of them expressed as diagonal blocks) is stored, the routine returns IDBLK of the last inequality added. IDBLK is just the order of the inequality amongst all matrix inequalities accumulated through the calls. The first inequality has IDBLK=1, the second one IDBLK=2, etc. Therefore if you call E04RNF for the very first time with NBLK=42, it adds 42 inequalities with IDBLK from 1 to 42 and the routine returns IDBLK=42 (the number of the last one). A subsequent call with NBLK=1 would add only one inequality, this time with IDBLK=43 which would be returned.

4 References

None.

5 Arguments

1:   HANDLE – TYPE (C_PTR)Input
On entry: the handle to the problem. It needs to be initialized by E04RAF and must not be changed.
2:   NVAR – INTEGERInput
On entry: n, the number of decision variables x in the problem. It must be unchanged from the value set during the initialization of the handle by E04RAF.
3:   DIMA – INTEGERInput
On entry: d, the dimension of the matrices Ai, for i=0,1,…,NVAR.
Constraint: DIMA>0.
4:   NNZA NVAR+1 – INTEGER arrayInput
On entry: NNZA i+1, for i=0,1,…,NVAR, gives the number of nonzero elements in the upper triangle of matrix Ai. To define Ai as a zero matrix, set NNZA i+1=0. However, there must be at least one matrix with at least one nonzero.
Constraints:
  • NNZA i≥0;
  • ∑ i=1 n+1 NNZA i≥1.
5:   NNZASUM – INTEGERInput
On entry: the dimension of the arrays IROWA, ICOLA and A, at least the total number of all nonzeros in all matrices Ai.
Constraints:
  • NNZASUM>0;
  • ∑ i=1 n+1 NNZA i ≤ NNZASUM.
6:   IROWA NNZASUM – INTEGER arrayInput
7:   ICOLA NNZASUM – INTEGER arrayInput
8:   A NNZASUM – REAL (KIND=nag_wp) arrayInput
On entry: nonzero elements in upper triangle of matrices Ai stored in coordinate storage. The first NNZA 1 elements belong to A 0, the following NNZA 2 elements belong to A 1, etc. See explanation above.
Constraints:
  • 1≤IROWA i≤DIMA, IROWA i≤ICOLA i≤DIMA;
  • IROWA and ICOLA match the block diagonal pattern set by BLKSIZEA.
9:   NBLK – INTEGERInput
On entry: mA, number of diagonal blocks in Ai matrices. As explained above it is equivalent to the number of matrix inequalities supplied in this call.
Constraint: NBLK≥1.
10:   BLKSIZEA NBLK – INTEGER arrayInput
On entry: if NBLK>1, sizes dk of the diagonal blocks.
If NBLK=1, BLKSIZEA is not referenced.
Constraints:
  • BLKSIZEA i≥1;
  • ∑ i=1 mA BLKSIZEA i=DIMA.
11:   IDBLK – INTEGERInput/Output
On entry: if IDBLK=0, new matrix inequalities are created. This is the only value allowed at the moment; nonzero values are reserved for future releases of the NAG Library.
Constraint: IDBLK=0.
On exit: the number of the last matrix inequality added. By definition, it is the number of the matrix inequalities already defined plus NBLK.
12:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, the recommended value is -1. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
The supplied HANDLE does not define a valid handle to the data structure for the NAG optimization modelling suite. It has not been initialized by E04RAF or it has been corrupted.
IFAIL=2
The problem cannot be modified in this phase any more, the solver has already been called.
IFAIL=4
On entry, IDBLK=value.
Constraint: IDBLK=0.
On entry, NVAR=value, expected value=value.
Constraint: NVAR must match the value given during initialization of HANDLE.
IFAIL=6
On entry, DIMA=value.
Constraint: DIMA>0.
On entry, i=value and NNZA i=value.
Constraint: NNZA i≥0.
On entry, NNZASUM=value and sum NNZA=value.
Constraint: NNZASUM≥sum NNZA.
On entry, sum NNZA=value.
Constraint: sum NNZA≥1.
IFAIL=7
On entry, DIMA=value and sum BLKSIZEA=value.
Constraint: sum BLKSIZEA=DIMA.
On entry, i=value and BLKSIZEA i=value.
Constraint: BLKSIZEA i≥1.
On entry, NBLK=value.
Constraint: NBLK>0.
IFAIL=8
An error occurred in matrix Ai, i=value (counting indices 1…NVAR+1).
On entry, j=value, ICOLA j=value and DIMA=value.
Constraint: 1≤ICOLA j≤DIMA.
An error occurred in matrix Ai, i=value (counting indices 1…NVAR+1).
On entry, j=value, IROWA j=value and DIMA=value.
Constraint: 1≤IROWA j≤DIMA.
An error occurred in matrix Ai, i=value (counting indices 1…NVAR+1).
On entry, j=value, IROWA j=value and ICOLA j=value.
Constraint: IROWA j≤ICOLA j (elements within the upper triangle).
An error occurred in matrix Ai, i=value (counting indices 1…NVAR+1).
On entry, j=value, IROWA j=value and ICOLA j=value. Maximum column index in this row given by the block structure defined by BLKSIZEA is value.
Constraint: all elements of Ai must respect the block structure given by BLKSIZEA.
An error occurred in matrix Ai, i=value (counting indices 1…NVAR+1).
On entry, more than one element of Ai has row index value and column index value.
Constraint: each element of Ai must have a unique row and column index.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

Not applicable.

8 Parallelism and Performance

E04RNF is not threaded in any implementation.

9 Further Comments

The following example demonstrates how the elements of the A i k matrices are organized within the input arrays. Let us assume that there are two blocks defined (NBLK=2). The first has dimension 3 by 3 (BLKSIZEA 1=3) and the second 2 by 2 (BLKSIZEA 2=2). For simplicity, the number of variables is 2. Please note that the values were chosen to ease orientation rather than to define a valid problem.
A 0 1 = 0.1 0 0.3 0 0.2 0.4 0.3 0.4 0 , A 1 1 ​ empty ​ A 2 1 = 2.1 0 0 0 2.2 0 0 0 2.3 , A 0 2 = 0 -0.1 -0.1 0 , A 1 2 = -1.1 0 0 -1.2 , A 2 2 = -2.1 -2.2 -2.2 -2.3 .
Both inequalities will be passed in a single call to E04RNF, therefore the matrices are merged into the following block diagonal form:
A 0 = 0.1 0 0.3 0 0.2 0.4 0.3 0.4 0 0 -0.1 -0.1 0 ,
A 1 = 0 0 0 0 0 0 0 0 0 -1.1 0 0 -1.2 ,
A 2 = 2.1 0 0 0 2.2 0 0 0 2.3 -2.1 -2.2 -2.2 -2.3 .
All matrices are symmetric and therefore only the upper triangles are passed to the routine. The coordinate storage format is used. Note that elements within the same matrix do not need to be in any specific order. The table below shows one of the ways the arrays could be populated.
IROWA | 0.2 0.2 -0.4 0.1 0.1 | -0.4 -0.5 | 0.1 0.2 0.3 -0.4 -0.4 -0.5
ICOLA | 0.2 0.3 -0.5 0.1 0.3 | -0.4 -0.5 | 0.1 0.2 0.3 -0.4 -0.5 -0.5
A | 0.2 0.4 -0.1 0.1 0.3 ︸ | -1.1 -1.2 ︸ | 2.1 2.2 2.3 -2.1 -2.2 -2.3 ︸
 | A 0 | A 1 | A 2
NNZA | 5 | 2 | 6

10 Example

There are various problems which can be successfully reformulated and solved as an SDP problem. The following example shows how a maximization of the minimal eigenvalue of a matrix depending on certain parameters can be utilized in statistics.
For further examples, please refer to Section 10 in E04RAF.
Given a series of M vectors of length p, vi : i=1,2,…,M this example solves the SDP problem:
maximize λ 1,…,λM,t t subject to   ∑ i=1 M λi vi viT ⪰ t⁢I ∑ i=1 M λi =1 λi≥0 ,  k=1,…,M .
This formulation comes from an area of statistics called experimental design and corresponds to finding an approximate E optimal design for a linear regression.
A linear regression model has the form:
y=Xβ+ε
where y is a vector of observed values, X is a design matrix of (known) independent variables and ε is a vector of errors. In experimental design it is assumed that each row of X is chosen from a set of M possible vectors, vi : i=1,2,…,M . The goal of experimental design is to choose the rows of X so that the error covariance is ‘small’. For an E optimal design this is defined as the X that maximizes the minimum eigenvalue of XT X.
In this example we construct the E optimal design for a polynomial regression model of the form:
y = β 0+ β 1⁢ x+ β 2⁢ x 2+ β 3⁢ x 3+ β 4⁢ x 4+ε
where x∈ 1-j×0.05 : j=0,1,…,40 .

10.1 Program Text

Program Text (e04rnfe.f90)

10.2 Program Data

Program Data (e04rnfe.d)

10.3 Program Results

Program Results (e04rnfe.r)

E04 Chapter Contents
E04 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


E04RPF : NAG Library, Mark 26

E04 Chapter Contents
E04 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

E04RPF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
▸▿ 3 Description
3.1 Input data organization
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

E04RPF is a part of the NAG optimization modelling suite and defines bilinear matrix terms either in a new matrix constraint or adds them to an existing linear matrix inequality.

2 Specification

SUBROUTINE E04RPF ( HANDLE, NQ, QI, QJ, DIMQ, NNZQ, NNZQSUM, IROWQ, ICOLQ, Q, IDBLK, IFAIL)
INTEGER | NQ, QI(NQ), QJ(NQ), DIMQ, NNZQ(NQ), NNZQSUM, IROWQ(NNZQSUM), ICOLQ(NNZQSUM), IDBLK, IFAIL
REAL (KIND=nag_wp) | Q(NNZQSUM)
TYPE (C_PTR) | HANDLE

3 Description

After the initialization routine E04RAF has been called, E04RPF may be used to define bilinear matrix terms. It may be used in two ways, either to add to the problem formulation a new bilinear matrix inequality (BMI) which does not have linear terms:
∑ i,j=1 n xi xj Q ij ⪰0 (1)
or to extend an existing linear matrix inequality constraint by bilinear terms:
∑ i,j=1 n xi xj Q ij k . (2)
Here Q ij k are d by d (sparse) symmetric matrices and k, if present, is the number of the existing constraint. This routine will typically be used on semidefinite programming problems with bilinear matrix constraints (BMI-SDP)
minimize x∈ℝ n 12 xT Hx + cT x   (a) subject to   ∑ i,j=1 n xi xj Q ij k + ∑ i=1 n xi Aik - A 0 k ⪰ 0 ,  k=1,…,mA   (b) lB≤Bx≤uB   (c) lx≤x≤ux .   (d) (3)
The routine can be called multiple times to define an additional matrix inequality or to extend an existing one, but it cannot be called twice to extend the same matrix inequality. The argument IDBLK is used to distinguish whether a new matrix constraint should be added (IDBLK=0) or if an existing linear matrix inequality should be extended (IDBLK>0). In the latter case, IDBLK should be set to k, the number of the existing inequality. See E04RNF for details about formulation of linear matrix constraints and their numbering and a further description of IDBLK. For a generic description of the problem see E04RAF. In the further text, the index k will be omitted.

3.1 Input data organization

It is expected that only some of the matrices Q ij will be nonzero therefore only their index pairs i,j are listed in arrays QI and QJ. Note that a pair i,j should not repeat, i.e., a matrix Q ij should not be defined more than once. No particular ordering of pairs i,j is expected but other input arrays IROWQ, ICOLQ, Q and NNZQ need to respect the chosen order.
Note: the dimension of Q ij must respect the size of the linear matrix inequality if they are supposed to expand it (case IDBLK>0).
Matrices Q ij are symmetric and thus only their upper triangles are passed to the routine. They are stored in sparse coordinate storage format (see Section 2.1.1 in the F11 Chapter Introduction), i.e., every nonzero from the upper triangles is coded as a triplet of row index, column index and the numeric value. All these triplets from all Q ij matrices are passed to the routine in three arrays: IROWQ for row indices, ICOLQ for column indices and Q for the values. No particular order of nonzeros within one matrix is enforced but all nonzeros belonging to one Q ij matrix need to be stored next to each other. The first NNZQ 1 nonzeros belong to Q i 1j 1 where i 1=QI 1, j 1=QJ 1, the following NNZQ 2 nonzeros to the next one given by QI, QJ and so on. The array NNZQ thus splits arrays IROWQ, ICOLQ and Q into sections so that each section defines one Q ij matrix. See Table 1 below. Routines E04RDF and E04RNF use the same data organization so further examples can be found there.
IROWQ | upper triangle | upper triangle |  | upper triangle
ICOLQ | nonzeros | nonzeros | ⋯ | nonzeros
Q | from ​ Q i 1j 1 ︸ | from ​ Q i 2j 2 ︸ |  | from ​ Q iNQ jNQ ︸
 | NNZQ 1 | NNZQ 2 |  | NNZQ NQ
 | i 1 = QI 1 | i 2 = QI 2 |  | iNQ = QI NQ
 | j 1 = QJ 1 | j 2 = QJ 2 |  | jNQ = QJ NQ
Table 1
Coordinate storage format of Q ij matrices in input arrays

4 References

Syrmos V L, Abdallah C T, Dorato P and Grigoriadis K (1997) Static output feedback – a survey Journal Automatica (Journal of IFAC) (Volume 33) 2 125–137

5 Arguments

1:   HANDLE – TYPE (C_PTR)Input
On entry: the handle to the problem. It needs to be initialized by E04RAF and must not be changed.
2:   NQ – INTEGERInput
On entry: the number of index pairs i,j of the nonzero matrices Q ij.
Constraint: NQ>0.
3:   QI NQ – INTEGER arrayInput
4:   QJ NQ – INTEGER arrayInput
On entry: the index pairs i,j of the nonzero matrices Q ij in any order.
Constraint: 1≤i,j≤n where n is the number of decision variables in the problem set during the initialization of the handle by E04RAF. The pairs do not repeat.
5:   DIMQ – INTEGERInput
On entry: d, the dimension of matrices Q ij.
Constraints:
  • DIMQ>0;
  • if IDBLK>0, DIMQ needs to be identical to the dimension of matrices of the constraint k.
6:   NNZQ NQ – INTEGER arrayInput
On entry: the numbers of nonzero elements in the upper triangles of Q ij matrices.
Constraint: NNZQ i>0.
7:   NNZQSUM – INTEGERInput
On entry: the dimension of the arrays IROWQ, ICOLQ and Q, at least the total number of all nonzeros in all Q ij matrices.
Constraints:
  • NNZQSUM>0;
  • NNZQSUM≥∑ k=1 NQ NNZQ k.
8:   IROWQ NNZQSUM – INTEGER arrayInput
9:   ICOLQ NNZQSUM – INTEGER arrayInput
10:   Q NNZQSUM – REAL (KIND=nag_wp) arrayInput
On entry: the nonzero elements of the upper triangles of matrices Q ij stored in coordinate storage format. The first NNZQ 1 elements belong to the first Q i 1j 1, the following NNZQ 2 to Q i 2j 2, etc.
Constraint: 1≤IROWQ i≤DIMQ, IROWQ i≤ICOLQ i≤DIMQ.
11:   IDBLK – INTEGERInput/Output
On entry: if IDBLK=0, a new matrix constraint is created; otherwise IDBLK=k>0, the number of the existing linear matrix constraint to be expanded with the bilinear terms.
Constraint: IDBLK≥0.
On exit: if IDBLK=0 on entry, the number of the new matrix constraint is returned. By definition, it is the number of the matrix inequalities already defined plus one. Otherwise, IDBLK>0 stays unchanged.
12:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, the recommended value is -1. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
The supplied HANDLE does not define a valid handle to the data structure for the NAG optimization modelling suite. It has not been initialized by E04RAF or it has been corrupted.
IFAIL=2
The problem cannot be modified in this phase any more, the solver has already been called.
IFAIL=3
On entry, IDBLK=value.
Bilinear terms of the matrix inequality block with the given IDBLK have already been defined.
IFAIL=4
On entry, IDBLK=value.
The given IDBLK does not match with any existing matrix inequality block.
The maximum IDBLK is currently value.
On entry, IDBLK=value.
The given IDBLK refers to a nonexistent matrix inequality block.
No matrix inequalities have been added yet.
IFAIL=5
On entry, DIMQ=value, IDBLK=value.
The correct dimension of the given IDBLK is value.
Constraint: DIMQ must match the dimension of the block supplied earlier.
IFAIL=6
On entry, DIMQ=value.
Constraint: DIMQ>0.
On entry, i=value and NNZQ i=value.
Constraint: NNZQ i>0.
On entry, IDBLK=value.
Constraint: IDBLK≥0.
On entry, NNZQSUM=value and sum NNZQ=value.
Constraint: NNZQSUM≥sum NNZQ.
On entry, NQ=value.
Constraint: NQ>0.
IFAIL=8
On entry, an error occurred in matrix Q ij of index k=value, QI k=value, QJ k=value.
For j=value, ICOLQ j=value and DIMQ=value.
Constraint: 1≤ICOLQ j≤DIMQ.
On entry, an error occurred in matrix Q ij of index k=value, QI k=value, QJ k=value.
For j=value, IROWQ j=value and DIMQ=value.
Constraint: 1≤IROWQ j≤DIMQ.
On entry, an error occurred in matrix Q ij of index k=value, QI k=value, QJ k=value.
For j=value, IROWQ j=value and ICOLQ j=value.
Constraint: IROWQ j≤ICOLQ j (elements within the upper triangle).
On entry, an error occurred in matrix Q ij of index k=value, QI k=value, QJ k=value.
More than one element of Q ij has row index value and column index value.
Constraint: each element of Q ij must have a unique row and column index.
IFAIL=9
On entry, index pair with QI=value and QJ=value repeats.
Constraint: each index pair QI, QJ must be unique.
On entry, k=value, QI k=value and n=value.
Constraint: 1≤QI k≤n.
On entry, k=value, QJ k=value and n=value.
Constraint: 1≤QJ k≤n.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

Not applicable.

8 Parallelism and Performance

E04RPF is not threaded in any implementation.

9 Further Comments

None.

10 Example

This example demonstrates how semidefinite programming can be used in control theory. See also Section 10 in E04RAF for links to further examples in the suite.
The problem, from static output feedback (SOF) control Syrmos et al. (1997), solved here is the linear time-invariant (LTI) ‘test’ system
x.=Ax+Bu y=Cx (4)
subject to static output feedback
u=Ky . (5)
Here A∈ℝ n×n, B∈ℝ n×m and C∈ℝ p×n are given matrices, x∈ℝn is the vector of state variables, u∈ℝm is the vector of control inputs, y∈ℝp is the vector of system outputs, and K∈ℝ m×p is the unknown feedback gain matrix.
The problem is to find K such that (4) is time-stable when subject to (5), i.e., all eigenvalues of the closed-loop system matrix A+BKC belong to the left half-plane. From the Lyapunov stability theory, this holds if and only if there exists a symmetric positive definite matrix P such that
A+BKC T P+ P A+BKC ≺0 .
Hence, by introducing the new variable, the Lyapunov matrix P, we can formulate the SOF problem as a feasibility BMI-SDP problem in variables K and P. As we cannot formulate the problem with sharp matrix inequalities, we can solve the following system instead (note that the objective function is added to bound matrix P):
minimize K,P trace P subject to A+BKC T P+P A+BKC ⪯ -I P⪰I. (6)
For n=p=2, m=1,
A= -1 2 -3 -4 ,   B= -1 -1 ,  C=I
and the unknown matrices expressed as
P = x 1 x 2 x 2 x 3 ,  K = x 4 x 5 ,
the problem (6) can be rewritten in the form (3) as follows:
minimize x∈ℝ 5 x 1+x 3 subject to 2 x 1 ⁢ x 4 + 2 x 2 ⁢ x 4 x 1 ⁢ x 5 + x 2 ⁢ x 4 + x 2 ⁢ x 5 + x 3 ⁢ x 4 sym. 2 x 2 ⁢ x 5 + 2 x 3 ⁢ x 5 + 2 x 1 + 6 x 2 -2 x 1 + 5 x 2 + 3 x 3 sym. -4 x 2 + 8 x 3 - I ⪰ 0 x 1 x 2 sym. x 3 - I ⪰ 0 .
This formulation has been stored in a generic BMI-SDP data file which is processed and solved by the example program.

10.1 Program Text

Program Text (e04rpfe.f90)

10.2 Program Data

Program Data (e04rpfe.d)

10.3 Program Results

Program Results (e04rpfe.r)

E04 Chapter Contents
E04 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


E04RYF : NAG Library, Mark 26

E04 Chapter Contents
E04 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

E04RYF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

E04RYF is a part of the NAG optimization modelling suite. It allows you to print information about the problem, stored as a handle, such as which parts have already been defined or details of the matrix constraints.

2 Specification

SUBROUTINE E04RYF ( HANDLE, NOUT, CMDSTR, IFAIL)
INTEGER | NOUT, IFAIL
CHARACTER(*) | CMDSTR
TYPE (C_PTR) | HANDLE

3 Description

E04RYF prints information on a problem handle which has been previously initialized by E04RAF. Various pieces of information can be retrieved and printed to the given output unit. This can be helpful when the routine is interfaced from interactive environments, for debugging purposes or to help familiarize you with the NAG optimization modelling suite.
The printer is guided by a command string which contains one or more of the following keywords:
Overview
Gives a brief overview of the problem handle, particularly, which phase it is in, if the problem or optional parameters can be edited and which parts of the problem have already been set. This might be helpful to clarify situations when IFAIL=2 or 3 (the problem cannot be altered anymore, a certain part has already been defined) is obtained from routines, such as, E04REF, E04RFF, E04RHF and E04RJF.
Objective
Prints the objective function as it was defined by E04REF or E04RFF if it is linear or quadratic. Prints the sparsity structure of the objective function as it was defined by E04RGF if it is nonlinear.
Simple bounds
Prints the variable bounds as defined by E04RHF. This might help you understand the effect of the optional parameter Infinite Bound Size on the bounds.
Linear constraints bounds
Linear constraints detailed
Print bounds or linear constraint matrix as defined by E04RJF.
Matrix constraints
Gives a list of the matrix constraints as defined by E04RNF and E04RPF. For each matrix constraint its IDBLK, dimension and order (e.g., linear, bilinear) are printed.
Matrix constraints detailed
Prints all the matrix constraints including all nonzeros of all the matrices as formulated by E04RNF and E04RPF.
Nonlinear constraints bounds
Nonlinear constraints detailed
Print bounds or sparsity structure of the nonlinear constraints as defined by E04RKF.
Multipliers sizes
Prints the expected dimensions of array arguments U and UA of the solver E04SVF which store the Lagrangian multipliers for standard and matrix constraints, respectively. This might be helpful in particular in connection with Overview and Matrix constraints to check the way the sizes of the arrays are derived.
Options
Prints all the current optional parameters. It flags whether the argument is at its default choice, whether you have set it or whether it is chosen by the solver (for example, options left on ‘AUTO’ setting after the solver has been called).
Note that the output data might not match your input exactly. The sparse matrices are typically transposed, sorted and explicit zeros removed and in certain cases transformed as needed (for example, matrices Q ij and Q ji are merged by E04RPF).

4 References

None.

5 Arguments

1:   HANDLE – TYPE (C_PTR)Input
On entry: the handle to the problem. It needs to be initialized by E04RAF and must not be changed.
2:   NOUT – INTEGERInput
On entry: the Fortran unit number which identifies the file to be written to.
Constraint: NOUT≥0.
3:   CMDSTR – CHARACTER(*)Input
On entry: a command string which contains one or more keywords which identify the piece of information about the handle to be printed. Keywords are case-insensitive and space tolerant. Multiple keywords in CMDSTR must be separated by commas or semicolons.
Constraint: CMDSTR can only contain one or more of the following accepted keywords: overview, objective, simple bounds, linear constraints bounds, linear constraints detailed, matrix constraints, matrix constraints detailed, nonlinear constraints bounds, nonlinear constraints detailed, multipliers sizes, options.
4:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
The supplied HANDLE does not define a valid handle to the data structure for the NAG optimization modelling suite. It has not been initialized by E04RAF or it has been corrupted.
IFAIL=6
On entry, NOUT=value.
Constraint: NOUT≥0.
IFAIL=7
CMDSTR does not contain any keywords or is empty.
Keyword number value is not recognized, it is too long.
Keyword number value is not recognized.
IFAIL=199
An error occurred when writing to output.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

Not applicable.

8 Parallelism and Performance

E04RYF is not threaded in any implementation.

9 Further Comments

None.

10 Example

This example shows the life-cycle of a handle of a typical (BMI-SDP) problem by printing the overview of the handle in various stages of the problem formulation and after the solution is found. It is also helpful to notice how a linear matrix inequality is extended with the bilinear term, see E04RAF and E04RPF for further details.
The problem is as follows:
minimize x,y​ ​∈​ ​ℝ y subject to   1 x-1 y x-1 3/4 0 y 0 16 ⪰0 x -xy -xy 1 ⪰0 x≥0 -3≤y≤3
The solution is x=1/4, y=-2.
Note that the matrix constraints need to be supplied in the form of equation (3) in E04RPF, i.e.,
∑ i,j=1 n xi xj Q ij k + ∑ i=1 n xi Aik - A 0 k ⪰ 0 ,  k=1,…,mA .
Therefore the first constraint is defined by matrices
A 0 1 = -1 1 0 -3/4 0 -16 ,  A 1 1 = 0 1 0 0 0 0 ,  A 2 1 = 0 0 1 0 0 0
and the second one by
A 0 2 = 0 0 -1 ,  A 1 2 = 1 0 0 ,  A 2 2 ​ empty,  Q 12 2 = 0 -1 0 0 .
See also Section 10 in E04RAF for links to further examples in the suite.

10.1 Program Text

Program Text (e04ryfe.f90)

10.2 Program Data

None.

10.3 Program Results

Program Results (e04ryfe.r)

E04 Chapter Contents
E04 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


E04RZF : NAG Library, Mark 26

E04 Chapter Contents
E04 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

E04RZF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
10 Example

1 Purpose

E04RZF is a part of the NAG optimization modelling suite. It is used to deallocate the memory used within the problem handle and to destroy the handle itself.

2 Specification

SUBROUTINE E04RZF ( HANDLE, IFAIL)
INTEGER | IFAIL
TYPE (C_PTR) | HANDLE

3 Description

Each problem handle initialized by E04RAF should be deallocated to avoid memory leaks. Therefore E04RZF should be called on all the handles which are no longer needed, typically after obtaining results from the solver. Please note that passing a handle which has not been initialized by E04RAF might cause unpredictable behaviour, including a crash of your program. See E04RAF for a generic description of the suite.

4 References

None.

5 Arguments

1:   HANDLE – TYPE (C_PTR)Input/Output
On entry: the handle to the problem. It needs to be initialized by E04RAF and must not be changed before the call to E04RZF.
On exit: the handle is destroyed and set to 0.
2:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
The supplied HANDLE does not define a valid handle to the data structure for the NAG optimization modelling suite. It has not been initialized by E04RAF or it has been corrupted.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

Not applicable.

8 Parallelism and Performance

E04RZF is not threaded in any implementation.

9 Further Comments

None.

10 Example

See Section 10 in E04RAF for links to all examples in the suite.
E04 Chapter Contents
E04 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


E04STF : NAG Library, Mark 26

E04 Chapter Contents
E04 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

E04STF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.
Note: this routine uses optional parameters to define choices in the problem specification and in the details of the algorithm. If you wish to use default settings for all of the optional parameters, you need only read Sections 1 to 10 of this document. If, however, you wish to reset some or all of the settings please refer to Section 11 for a detailed description of the algorithm and to Section 12 for a detailed description of the specification of the optional parameters.

▸▿ Contents

1 Purpose
2 Specification
▸▿ 3 Description
3.1 Structure of the Lagrange Multipliers
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
▸▿ 9 Further Comments
9.1 Description of the Printed Output
9.2 Additional Licensor
▸▿ 10 Example
10.1 Program Text
10.2 Program Results
▸▿ 11 Algorithmic Details
11.1 Stopping Criteria
11.2 Scaling the NLP
▸▿ 12 Optional Parameters
12.1 Description of the Optional Parameters

1 Purpose

E04STF, an interior point method optimization solver, based on the IPOPT software package, is a solver for the NAG optimization modelling suite and is suitable for large scale nonlinear programming (NLP) problems.

2 Specification

SUBROUTINE E04STF ( HANDLE, OBJFUN, OBJGRD, CONFUN, CONGRD, HESS, MON, NVAR, X, NNZU, U, RINFO, STATS, IUSER, RUSER, CPUSER, IFAIL)
INTEGER | NVAR, NNZU, IUSER(*), IFAIL
REAL (KIND=nag_wp) | X(NVAR), U(NNZU), RINFO(32), STATS(32), RUSER(*)
EXTERNAL | OBJFUN, OBJGRD, CONFUN, CONGRD, HESS, MON
TYPE (C_PTR) | HANDLE, CPUSER

3 Description

E04STF will typically be used for nonlinear programming problems (NLP)
minimize x∈ℝ n f x   (a) subject to lg≤g x≤ug   (b) lB≤Bx≤uB   (c) lx≤x≤ux   (d) (1)
where
  • n is the number of the decision variables,
  • mg is the number of the nonlinear constraints and g x, lg and ug are mg-dimensional vectors,
  • mB is the number of the linear constraints and B is a mB by n matrix, lB and uB are mB-dimensional vectors,
  • there are n box constraints and lx and ux are n-dimensional vectors.
The objective f x can be specified in a number of ways: E04REF for a dense linear function, E04RFF for a sparse linear or quadratic function and E04RGF for a general nonlinear function. In the last case, OBJFUN and OBJGRD will be used to compute values and gradients of the objective function. Variable box bounds lx,ux can be specified with E04RHF. The special case of linear constraints lB,B,uB is handled by E04RJF while general nonlinear constraints lg,g x,ug are specified by E04RKF (both can be specified). Again, in the last case, CONFUN and CONGRD will be used to compute values and gradients of the nonlinear constraint functions.
Finally, if the user is willing to calculate second derivatives, the sparsity structure of the second partial derivatives of a nonlinear objective and/or of any nonlinear constraints is specified by E04RLF while the values of these derivatives themselves will be computed by user-supplied HESS. While there is an option (see Hessian Mode) that forces internal approximation of second derivatives, no such option exists for first derivatives which must be computed accurately. If E04RLF has been called and HESS is used to calculate values for second derivatives, both the objective and all the constraints must be included; it is not possible to provide a subset of these. If E04RLF is not called, then internal approximation of second derivatives will take place.

3.1 Structure of the Lagrange Multipliers

For a problem consisting of n variable bounds, mB linear constraints and mg nonlinear constraints (as specified in NVAR, NCLIN and NCNLN of E04RHF, E04RJF and E04RKF, respectively), the number of Lagrange multipliers, and consequently the correct value for NNZU, will be q=2*n+2*mB+2*mg. The order these will be found in the U array is
z 1 L, z 1 U, z 2 L, z 2 U… z nL, z nU, λ 1 L, λ 1 U, λ 2 L, λ 2 U… λ mB L, λ mB U, λ mB+1 L, λ mB+1 U, λ mB+2 L, λ mB+2 U… λ mB+mg L, λ mB+mg U
where the L and U subscripts refer to lower and upper bounds, respectively, and the variable bound constraint multipliers come first (if present, i.e., if E04RHF was called), followed by the linear constraint multipliers (if present, i.e., if E04RJF was called) and the nonlinear constraint multipliers (if present, i.e., if E04RKF was called).
Significantly nonzero values for any of these, after the solver has terminated, indicates that the corresponding constraint is active. Significance is judged in the first instance by the relative scale of any value compared to the smallest among them.

4 References

Byrd R H, Gilbert J Ch and Nocedal J (2000) A trust region method based on interior point techniques for nonlinear programming Mathematical Programming 89 149–185
Byrd R H, Liu G and Nocedal J (1997) On the local behavior of an interior point method for nonlinear programming Numerical Analysis (eds D F Griffiths and D J Higham) Addison–Wesley
Conn A R, Gould N I M, Orban D and Toint Ph L (2000) A primal-dual trust-region algorithm for non-convex nonlinear programming Mathematical Programming 87 (2) 215–249
Conn A R, Gould N I M and Toint Ph L (2000) Trust Region Methods SIAM, Philadephia
Fiacco A V and McCormick G P (1990) Nonlinear Programming: Sequential Unconstrained Minimization Techniques SIAM, Philadelphia
Gould N I M, Orban D, Sartenaer A and Toint Ph L (2001) Superlinear convergence of primal-dual interior point algorithms for nonlinear programming SIAM Journal on Optimization 11 (4) 974–1002
Hock W and Schittkowski K (1981) Test Examples for Nonlinear Programming Codes. Lecture Notes in Economics and Mathematical Systems 187 Springer–Verlag
Hogg J D and Scott J A (2011) HSL MA97: a bit-compatible multifrontal code for sparse symmetric systems RAL Technical Report. RAL-TR-2011-024
Wächter A and Biegler L T (2006) On the implementation of a primal-dual interior point filter line search algorithm for large-scale nonlinear programming Mathematical Programming 106(1) 25–57
Williams P and Lang B (2013) A framework for the M R 3 algorithm: theory and implementation SIAM J. Sci. Comput. 35 740–766
Yamashita H (1998) A globally convergent primal-dual interior-point method for constrained optimization Optimization Methods and Software 10 443–469

5 Arguments

1:   HANDLE – TYPE (C_PTR)Input
On entry: the handle to the problem. It needs to be initialized by E04RAF and the problem formulated by some of the routines E04REF, E04RFF, E04RGF, E04RHF, E04RJF, E04RKF and E04RLF. It must not be changed between calls to the NAG optimization modelling suite.
2:   OBJFUN – SUBROUTINE, supplied by the NAG Library or the user.External Procedure
OBJFUN must calculate the value of the nonlinear objective function f x at a specified value of the n-element vector of x variables. If there is no nonlinear objective (e.g., E04REF or E04RFF was called to define a linear or quadratic objective function), OBJFUN will never be called by E04STF and OBJFUN may be the dummy routine E04STV. (E04STV is included in the NAG Library.)
The specification of OBJFUN is:
SUBROUTINE OBJFUN ( NVAR, X, FX, INFORM, IUSER, RUSER, CPUSER)
INTEGER | NVAR, INFORM, IUSER(*)
REAL (KIND=nag_wp) | X(NVAR), FX, RUSER(*)
TYPE (C_PTR) | CPUSER
1:   NVAR – INTEGERInput
On entry: n, the number of variables in the problem. It must be unchanged from the value set during the initialization of the handle by E04RAF.
2:   X NVAR – REAL (KIND=nag_wp) arrayInput
On entry: the vector x of variable values at which the objective function is to be evaluated.
3:   FX – REAL (KIND=nag_wp)Output
On exit: the value of the objective function at x.
4:   INFORM – INTEGERInput/Output
On entry: a non-negative value.
On exit: must be set to a value describing the action to be taken by the solver on return from OBJFUN. Specifically, if the value is negative then the value of FX will be discarded and the solver will either attempt to find a different trial point or terminate immediately with IFAIL=25 (the same will happen if FX is Infinity or NaN); otherwise, the solver will proceed normally.
5:   IUSER* – INTEGER arrayUser Workspace
6:   RUSER* – REAL (KIND=nag_wp) arrayUser Workspace
7:   CPUSER – TYPE (C_PTR)User Workspace
OBJFUN is called with the arguments IUSER, RUSER and CPUSER as supplied to E04STF. You are free to use the arrays IUSER, RUSER and CPUSER to supply information to OBJFUN as an alternative to using COMMON global variables.
OBJFUN must either be a module subprogram USEd by, or declared as EXTERNAL in, the (sub)program from which E04STF is called. Arguments denoted as Input must not be changed by this procedure.
3:   OBJGRD – SUBROUTINE, supplied by the NAG Library or the user.External Procedure
OBJGRD must calculate the values of the nonlinear objective function gradients ∂f ∂x at a specified value of the n-element vector of x variables. If there is no nonlinear objective (e.g., E04REF or E04RFF was called to define a linear or quadratic objective function), OBJGRD will never be called by E04STF and OBJGRD may be the dummy subroutine E04STW. (E04STW is included in the NAG Library.)
The specification of OBJGRD is:
SUBROUTINE OBJGRD ( NVAR, X, NNZFD, FDX, INFORM, IUSER, RUSER, CPUSER)
INTEGER | NVAR, NNZFD, INFORM, IUSER(*)
REAL (KIND=nag_wp) | X(NVAR), FDX(NNZFD), RUSER(*)
TYPE (C_PTR) | CPUSER
1:   NVAR – INTEGERInput
On entry: n, the number of variables in the problem. It must be unchanged from the value set during the initialization of the handle by E04RAF.
2:   X NVAR – REAL (KIND=nag_wp) arrayInput
On entry: the vector x of variable values at which the objective function gradient is to be evaluated.
3:   NNZFD – INTEGERInput
On entry: the number of nonzero elements in the sparse gradient vector of the objective function, as was set in a previous call to E04RGF.
4:   FDX NNZFD – REAL (KIND=nag_wp) arrayOutput
On exit: the values of the nonzero elements in the sparse gradient vector of the objective function, in the order specified by IDXFD in a previous call to E04RGF. FDX i will be the gradient ∂f ∂x IDXFD i.
5:   INFORM – INTEGERInput/Output
On entry: a non-negative value.
On exit: must be set to a value describing the action to be taken by the solver on return from OBJGRD. Specifically, if the value is negative the solution of the current problem will terminate immediately with IFAIL=25 (the same will happen if FDX contains Infinity or NaN); otherwise, computations will continue.
6:   IUSER* – INTEGER arrayUser Workspace
7:   RUSER* – REAL (KIND=nag_wp) arrayUser Workspace
8:   CPUSER – TYPE (C_PTR)User Workspace
OBJGRD is called with the arguments IUSER, RUSER and CPUSER as supplied to E04STF. You are free to use the arrays IUSER, RUSER and CPUSER to supply information to OBJGRD as an alternative to using COMMON global variables.
OBJGRD must either be a module subprogram USEd by, or declared as EXTERNAL in, the (sub)program from which E04STF is called. Arguments denoted as Input must not be changed by this procedure.
4:   CONFUN – SUBROUTINE, supplied by the NAG Library or the user.External Procedure
CONFUN must calculate the values of the mg-element vector g i x of nonlinear constraint functions at a specified value of the n-element vector of x variables. If no nonlinear constraints were registered in this HANDLE, CONFUN will never be called by E04STF and CONFUN may be the dummy subroutine E04STX. (E04STX is included in the NAG Library.)
The specification of CONFUN is:
SUBROUTINE CONFUN ( NVAR, X, NCNLN, GX, INFORM, IUSER, RUSER, CPUSER)
INTEGER | NVAR, NCNLN, INFORM, IUSER(*)
REAL (KIND=nag_wp) | X(NVAR), GX(NCNLN), RUSER(*)
TYPE (C_PTR) | CPUSER
1:   NVAR – INTEGERInput
On entry: n, the number of variables in the problem. It must be unchanged from the value set during the initialization of the handle by E04RAF.
2:   X NVAR – REAL (KIND=nag_wp) arrayInput
On entry: the vector x of variable values at which the constraint functions are to be evaluated.
3:   NCNLN – INTEGERInput
On entry: mg, the number of nonlinear constraints, as specified in an earlier call to E04RKF.
4:   GX NCNLN – REAL (KIND=nag_wp) arrayOutput
On exit: the mg values of the nonlinear constraint functions at x.
5:   INFORM – INTEGERInput/Output
On entry: a non-negative value.
On exit: must be set to a value describing the action to be taken by the solver on return from CONFUN. Specifically, if the value is negative then the value of GX will be discarded and the solver will either attempt to find a different trial point or terminate immediately with IFAIL=25 (the same will happen if GX contains Infinity or NaN); otherwise, the solver will proceed normally.
6:   IUSER* – INTEGER arrayUser Workspace
7:   RUSER* – REAL (KIND=nag_wp) arrayUser Workspace
8:   CPUSER – TYPE (C_PTR)User Workspace
CONFUN is called with the arguments IUSER, RUSER and CPUSER as supplied to E04STF. You are free to use the arrays IUSER, RUSER and CPUSER to supply information to CONFUN as an alternative to using COMMON global variables.
CONFUN must either be a module subprogram USEd by, or declared as EXTERNAL in, the (sub)program from which E04STF is called. Arguments denoted as Input must not be changed by this procedure.
5:   CONGRD – SUBROUTINE, supplied by the NAG Library or the user.External Procedure
CONGRD must calculate the nonzero values of the sparse Jacobian of the nonlinear constraint functions ∂gi ∂x at a specified value of the n-element vector of x variables. If there are no nonlinear constraints (e.g., E04RKF was never called with the same HANDLE or it was called with NCNLN =0), CONGRD will never be called by E04STF and CONGRD may be the dummy subroutine E04STY. (E04STY is included in the NAG Library.)
The specification of CONGRD is:
SUBROUTINE CONGRD ( NVAR, X, NNZGD, GDX, INFORM, IUSER, RUSER, CPUSER)
INTEGER | NVAR, NNZGD, INFORM, IUSER(*)
REAL (KIND=nag_wp) | X(NVAR), GDX(NNZGD), RUSER(*)
TYPE (C_PTR) | CPUSER
1:   NVAR – INTEGERInput
On entry: n, the number of variables in the problem. It must be unchanged from the value set during the initialization of the handle by E04RAF.
2:   X NVAR – REAL (KIND=nag_wp) arrayInput
On entry: the vector x of variable values at which the Jacobian of the constraint functions is to be evaluated.
3:   NNZGD – INTEGERInput
On entry: is the number of nonzero elements in the sparse Jacobian of the constraint functions, as was set in a previous call to E04RKF.
4:   GDX NNZGD – REAL (KIND=nag_wp) arrayOutput
On exit: the nonzero values of the Jacobian of the nonlinear constraints, in the order specified by IROWGD and ICOLGD in an earlier call to E04RKF. GDX i will be the gradient ∂g IROWGD i ∂ x ICOLGD i .
5:   INFORM – INTEGERInput/Output
On entry: a non-negative value.
On exit: must be set to a value describing the action to be taken by the solver on return from CONGRD. Specifically, if the value is negative the solution of the current problem will terminate immediately with IFAIL=25 (the same will happen if GDX contains Infinity or NaN); otherwise, computations will continue.
6:   IUSER* – INTEGER arrayUser Workspace
7:   RUSER* – REAL (KIND=nag_wp) arrayUser Workspace
8:   CPUSER – TYPE (C_PTR)User Workspace
CONGRD is called with the arguments IUSER, RUSER and CPUSER as supplied to E04STF. You are free to use the arrays IUSER, RUSER and CPUSER to supply information to CONGRD as an alternative to using COMMON global variables.
CONGRD must either be a module subprogram USEd by, or declared as EXTERNAL in, the (sub)program from which E04STF is called. Arguments denoted as Input must not be changed by this procedure.
6:   HESS – SUBROUTINE, supplied by the NAG Library or the user.External Procedure
HESS must calculate the nonzero values of one of a set of second derivative quantities:
  • the Hessian of the Lagrangian function σ⁢∇ 2 f+∑i=1 mg λi⁢∇2 gi
  • the Hessian of the objective function ∇2 f
  • the Hessian of the constraint functions ∇2 gi
The value of argument IDF determines which one of these is to be computed and this, in turn, is determined by earlier calls to E04RLF, when the nonzero sparsity structure of these Hessians was registered. Please note that it is not possible to only supply a subset of the Hessians (see IFAIL=6). If there were no calls to E04RLF, HESS will never be called by E04STF and HESS may be the dummy subroutine E04STZ (E04STZ is included in the NAG Library). In this case, the Hessian of the Lagrangian will be approximated by a limited-memory quasi-Newton method (L-BFGS).
The specification of HESS is:
SUBROUTINE HESS ( NVAR, X, NCNLN, IDF, SIGMA, LAMBDA, NNZH, HX, INFORM, IUSER, RUSER, CPUSER)
INTEGER | NVAR, NCNLN, IDF, NNZH, INFORM, IUSER(*)
REAL (KIND=nag_wp) | X(NVAR), SIGMA, LAMBDA(NCNLN), HX(NNZH), RUSER(*)
TYPE (C_PTR) | CPUSER
1:   NVAR – INTEGERInput
On entry: n, the number of variables in the problem. It must be unchanged from the value set during the initialization of the handle by E04RAF.
2:   X NVAR – REAL (KIND=nag_wp) arrayInput
On entry: the vector x of variable values at which the Hessian functions are to be evaluated.
3:   NCNLN – INTEGERInput
On entry: mg, the number of nonlinear constraints, as specified in an earlier call to E04RKF.
4:   IDF – INTEGERInput
On entry: specifies the quantities to be computed in HX.
IDF=-1
The values of the Hessian of the Lagrangian will be computed in HX. This will be the case if E04RLF has been called with IDF of the same value.
IDF=0
The values of the Hessian of the objective function will be computed in HX. This will be the case if E04RLF has been called with IDF of the same value.
IDF>0
The values of the Hessian of the IDFth constraint function will be computed in HX. This will be the case if E04RLF has been called with IDF of the same value.
5:   SIGMA – REAL (KIND=nag_wp)Input
On entry: if IDF=-1, the value of the σ quantity in the definition of the Hessian of the Lagrangian. Otherwise, SIGMA should not be referenced.
6:   LAMBDA NCNLN – REAL (KIND=nag_wp) arrayInput
On entry: if IDF=-1, the values of the λi quantities in the definition of the Hessian of the Lagrangian. Otherwise, LAMBDA should not be referenced.
7:   NNZH – INTEGERInput
On entry: the number of nonzero elements in the Hessian to be computed.
8:   HX NNZH – REAL (KIND=nag_wp) arrayOutput
On exit: the nonzero values of the requested Hessian evaluated at x. For each value of IDF, the ordering of nonzeros must follow the sparsity structure registered in the HANDLE by earlier calls to E04RLF through the arguments IROWH and ICOLH.
9:   INFORM – INTEGERInput/Output
On entry: a non-negative value.
On exit: must be set to a value describing the action to be taken by the solver on return from HESS. Specifically, if the value is negative the solution of the current problem will terminate immediately with IFAIL=25 (the same will happen if HX contains Infinity or NaN); otherwise, computations will continue.
10:   IUSER* – INTEGER arrayUser Workspace
11:   RUSER* – REAL (KIND=nag_wp) arrayUser Workspace
12:   CPUSER – TYPE (C_PTR)User Workspace
HESS is called with the arguments IUSER, RUSER and CPUSER as supplied to E04STF. You are free to use the arrays IUSER, RUSER and CPUSER to supply information to HESS as an alternative to using COMMON global variables.
HESS must either be a module subprogram USEd by, or declared as EXTERNAL in, the (sub)program from which E04STF is called. Arguments denoted as Input must not be changed by this procedure.
7:   MON – SUBROUTINE, supplied by the NAG Library or the user.External Procedure
MON is provided to enable you to monitor the progress of the optimization. A facility is provided to halt the optimization process if necessary, using parameter INFORM.
MON may be the dummy subroutine E04STU (E04STU is included in the NAG Library).
The specification of MON is:
SUBROUTINE MON ( NVAR, X, NNZU, U, INFORM, RINFO, STATS, IUSER, RUSER, CPUSER)
INTEGER | NVAR, NNZU, INFORM, IUSER(*)
REAL (KIND=nag_wp) | X(NVAR), U(NNZU), RINFO(32), STATS(32), RUSER(*)
TYPE (C_PTR) | CPUSER
1:   NVAR – INTEGERInput
On entry: n, the number of variables in the problem.
2:   X NVAR – REAL (KIND=nag_wp) arrayInput
On entry: xi, the values of the decision variables x at the current iteration.
3:   NNZU – INTEGERInput
On entry: the dimension of array U.
4:   U NNZU – REAL (KIND=nag_wp) arrayInput
On entry: if NNZU>0, U holds the values at the current iteration of Lagrange multipliers (dual variables) for the constraints. See Section 3.1 for layout information.
5:   INFORM – INTEGERInput/Output
On entry: a non-negative value.
On exit: must be set to a value describing the action to be taken by the solver on return from MON. Specifically, if the value is negative the solution of the current problem will terminate immediately with IFAIL=20; otherwise, computations will continue.
6:   RINFO 32 – REAL (KIND=nag_wp) arrayInput
On entry: error measures and various indicators at the end of the current iteration as described in Section 9.1.
7:   STATS 32 – REAL (KIND=nag_wp) arrayInput
On entry: solver statistics at the end of the current iteration as described in Section 9.1.
8:   IUSER* – INTEGER arrayUser Workspace
9:   RUSER* – REAL (KIND=nag_wp) arrayUser Workspace
10:   CPUSER – TYPE (C_PTR)User Workspace
MON is called with the arguments IUSER, RUSER and CPUSER as supplied to E04STF. You are free to use the arrays IUSER, RUSER and CPUSER to supply information to MON as an alternative to using COMMON global variables.
MON must either be a module subprogram USEd by, or declared as EXTERNAL in, the (sub)program from which E04STF is called. Arguments denoted as Input must not be changed by this procedure.
8:   NVAR – INTEGERInput
On entry: n, the number of variables in the problem. It must be unchanged from the value set during the initialization of the handle by E04RAF.
9:   X NVAR – REAL (KIND=nag_wp) arrayInput/Output
On entry: x 0, the initial estimates of the variables x.
On exit: the final values of the variables x.
10:   NNZU – INTEGERInput
On entry: the number of Lagrange multipliers that are to be returned in array U.
If NNZU=0, U will not be referenced; otherwise it needs to match the dimension q as explained in Section 3.1.
Constraints:
  • NNZU≥0;
  • if NNZU>0, NNZU=q.
11:   U NNZU – REAL (KIND=nag_wp) arrayOutput
Note: if NNZU>0, U holds Lagrange multipliers (dual variables) for the constraints. See Section 3.1 for layout information. If NNZU=0, U will not be referenced.
On exit: the final value of Lagrange multipliers z,λ.
12:   RINFO 32 – REAL (KIND=nag_wp) arrayOutput
On exit: error measures and various indicators at the end of the final iteration as given in the table below:
1 | objective function value f x
2 | constraint violation (primal infeasibility) (8)
3 | dual infeasibility (7)
4 | complementarity
5 | Karush–Kuhn–Tucker error
13:   STATS 32 – REAL (KIND=nag_wp) arrayOutput
On exit: solver statistics at the end of the final iteration as given in the table below:
1 | number of the iterations
3 | number of backtracking trial steps
4 | number of Hessian evaluations
5 | number of objective gradient evaluations
8 | total wall clock time elapsed
19 | number of objective function evaluations
20 | number of constraint function evaluations
21 | number of constraint Jacobian evaluations
14:   IUSER* – INTEGER arrayUser Workspace
15:   RUSER* – REAL (KIND=nag_wp) arrayUser Workspace
16:   CPUSER – TYPE (C_PTR)User Workspace
IUSER, RUSER and CPUSER are not used by E04STF, but are passed directly to OBJFUN, OBJGRD, CONFUN, CONGRD, HESS and MON and may be used to pass information to these routines as an alternative to using COMMON global variables.
17:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, because for this routine the values of the output arguments may be useful even if IFAIL≠0 on exit, the recommended value is -1. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Note: E04STF may return useful information for one or more of the following detected errors or warnings.
Errors or warnings detected by the routine:
IFAIL=1
The supplied HANDLE does not define a valid handle to the data structure for the NAG optimization modelling suite. It has not been initialized by E04RAF or it has been corrupted.
IFAIL=2
The problem is already being solved.
This solver does not support matrix inequality constraints.
IFAIL=3
A different solver from the suite has already been used. Initialize a new HANDLE using E04RAF.
IFAIL=4
The information supplied does not match with that previously stored.
On entry, NVAR=value must match that given during initialization of the HANDLE, i.e., value.
IFAIL=5
On entry, NNZU=value.
Constraint: NNZU=value or 0.
On entry, NNZU=value.
Constraint: no constraints present, so NNZU must be 0.
IFAIL=6
Either all of the constraint and objective Hessian structures must be defined or none (in which case, the Hessians will be approximated by a limited-memory quasi-Newton L-BFGS method).
On entry, a nonlinear objective function has been defined but no objective Hessian sparsity structure has been defined through E04RLF.
On entry, a nonlinear constraint function has been defined but no constraint Hessian sparsity structure has been defined through E04RLF, for constraint number value.
IFAIL=7
The dummy CONFUN routine was called but the problem requires these values. Please provide a proper CONFUN routine.
The dummy CONGRD routine was called but the problem requires these derivatives. Please provide a proper CONGRD routine.
The dummy HESS routine was called but the problem requires these derivatives. Either change the option Hessian Mode or provide a proper HESS routine.
The dummy OBJFUN routine was called but the problem requires these values. Please provide a proper OBJFUN routine.
The dummy OBJGRD routine was called but the problem requires these derivatives. Please provide a proper OBJGRD routine.
IFAIL=20
User requested termination during a monitoring step. INFORM was set to a negative value in MON.
IFAIL=22
Maximum number of iterations exceeded.
IFAIL=23
The solver terminated after an error in the step computation. This message is printed if the solver is unable to compute a search direction, despite several attempts to modify the iteration matrix. Usually, the value of the regularization parameter then becomes too large. One situation where this can happen is when values in the Hessian are invalid (NaN or Infinity). You can check whether this is true by using the Verify Derivatives option.
The solver terminated after failure in the restoration phase. This indicates that the restoration phase failed to find a feasible point that was acceptable to the filter line search for the original problem. This could happen if the problem is highly degenerate, does not satisfy the constraint qualification, or if your NLP code provides incorrect derivative information.
The solver terminated after the maximum time allowed was exceeded. Maximum number of seconds exceeded. Use option Time Limit to reset the limit.
The solver terminated due to an invalid option. Please contact NAG with details of the call to E04STF.
The solver terminated due to an invalid problem definition. Please contact NAG with details of the call to E04STF.
The solver terminated with not enough degrees of freedom. This indicates that your problem, as specified, has too few degrees of freedom. This can happen if you have too many equality constraints, or if you fix too many variables.
IFAIL=24
The solver terminated after the search direction became too small. This indicates that the solver is calculating very small step sizes and is making very little progress. This could happen if the problem has been solved to the best numerical accuracy possible given the current NLP scaling.
IFAIL=25
Invalid number detected in user function. Either INFORM was set to a negative value within the user-supplied functions OBJFUN, OBJGRD, CONFUN, CONGRD or HESS, or an Infinity or NaN was detected in values returned from them.
IFAIL=50
The solver reports NLP solved to acceptable level. This indicates that the algorithm did not converge to the desired tolerances, but that it was able to obtain a point satisfying the acceptable tolerance level. This may happen if the desired tolerances are too small for the current problem.
IFAIL=51
The solver detected an infeasible problem. The restoration phase converged to a point that is a minimizer for the constraint violation (in the ℓ 1-norm), but is not feasible for the original problem. This indicates that the problem may be infeasible (or at least that the algorithm is stuck at a locally infeasible point). The returned point (the minimizer of the constraint violation) might help you to find which constraint is causing the problem. If you believe that the NLP is feasible, it might help to start the optimization from a different point.
IFAIL=54
The solver terminated due to diverging iterates. The max-norm of the iterates has become larger than a preset value. This can happen if the problem is unbounded below and the iterates are diverging.
IFAIL=-199
This routine is not available in this implementation.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

The accuracy of the solution is driven by optional parameter Stop Tolerance 1.
If IFAIL=0 on the final exit, the returned point satisfies Karush–Kuhn–Tucker (KKT) conditions to the requested accuracy (under the default settings close to ε where ε is the machine precision) and thus it is a good estimate of a local solution. If IFAIL=50, some of the convergence conditions were not fully satisfied but the point still seems to be a reasonable estimate and should be usable. Please refer to Section 11.1 and the description of the particular options.

8 Parallelism and Performance

E04STF is not threaded in any implementation.

9 Further Comments

9.1 Description of the Printed Output

The solver can print information to give an overview of the problem and of the progress of the computation. The output may be sent to two independent streams (files) which are set by optional parameters Print File and Monitoring File. Optional parameters Print Level and Monitoring Level determine the exposed level of detail. This allows, for example, the generation of a detailed log in a file while the condensed information is displayed on the screen. This section also describes what kind of information is made available to the monitoring routine MON via RINFO and STATS.
There are four sections printed to the primary output with the default settings (level 2): a derivative check, a header, an iteration log and a summary. At higher levels more information will be printed, including any internal IPOPT options that have been changed from their default values.
Derivative Check
If Verify Derivatives is set, then information will appear about any errors detected in the user-supplied derivative routines OBJGRD, CONGRD or HESS. It may look like this:
Starting derivative checker for first derivatives.

* grad_f[          1] = -2.000000E+00    ~  2.455000E+01  [ 1.081E+00]
* jac_g [    1,    4] =  4.700969E+01 v  ~  5.200968E+01  [ 9.614E-02]
Starting derivative checker for second derivatives.

*             obj_hess[    1,    1] =  1.881000E+03 v  ~  1.882000E+03  [ 5.314E-04]
*     1-th constr_hess[    1,    3] =  2.988964E+00 v  ~ -1.103543E-02  [ 3.000E+00]

Derivative checker detected 3 error(s).
The first line indicates that the value for the partial derivative of the objective with respect to the first variable as returned by OBJGRD (the first one printed) differs sufficiently from a finite difference estimation derived from OBJFUN (the second one printed). The number in square brackets is the relative difference between these two numbers.
The second line reports on a discrepancy for the partial derivative of the first constraint with respect to the fourth variable. If the indicator v is absent, the discrepancy refers to a component that had not been included in the sparsity structure, in which case the nonzero structure of the derivatives should be corrected. Mistakes in the first derivatives should be corrected before attempting to correct mistakes in the second derivatives.
The third line reports on a discrepancy in a second derivative of the objective function, differentiated with respect to the first variable, twice.
The fourth line reports on a discrepancy in a second derivative of the first constraint, differentiated with respect to the first and third variables.
Header
If Print Level≥1, the header will contain statistics about the size of the problem how the solver sees it, i.e., it reflects any changes imposed by preprocessing and problem transformations. The header may look like:
Number of nonzeros in equality constraint Jacobian...:        4
Number of nonzeros in inequality constraint Jacobian.:        8
Number of nonzeros in Lagrangian Hessian.............:       10

Total number of variables............................:        4
                     variables with only lower bounds:        4
                variables with lower and upper bounds:        0
                     variables with only upper bounds:        0
Total number of equality constraints.................:        1
Total number of inequality constraints...............:        2
        inequality constraints with only lower bounds:        2
   inequality constraints with lower and upper bounds:        0
        inequality constraints with only upper bounds:        0
It summarises what is known about the variables and the constraints. Simple bounds are set by E04RHF and standard equalities and inequalities by E04RJF.
Iteration log
If Print Level=2, the status of each iteration is condensed to one line. The line shows:
iter | The current iteration count. This includes regular iterations and iterations during the restoration phase. If the algorithm is in the restoration phase, the letter r will be appended to the iteration number. The iteration number 0 represents the starting point. This quantity is also available as STATS 1 of MON.
objective | The unscaled objective value at the current point (given the current NLP scaling). During the restoration phase, this value remains the unscaled objective value for the original problem. This quantity is also available as RINFO 1 of MON.
inf_pr | The unscaled constraint violation at the current point (given the current NLP scaling). This quantity is the infinity-norm (max) of the (unscaled) constraints gi. During the restoration phase, this value remains the constraint violation of the original problem at the current point. This quantity is also available as RINFO 2 of MON.
inf_du | The scaled dual infeasibility at the current point (given the current NLP scaling). This quantity measure the infinity-norm (max) of the internal dual infeasibility, λi of Eq. (4a) in the implementation paper Wächter and Biegler (2006), including inequality constraints reformulated using slack variables and NLP scaling. During the restoration phase, this is the value of the dual infeasibility for the restoration phase problem. This quantity is also available as RINFO 3 of MON.
lg(mu) | log10 of the value of the barrier parameter μ. μ itself is also available as RINFO 4 of MON.
||d|| The infinity norm (max) of the primal step (for the original variables x and the internal slack variables s). During the restoration phase, this value includes the values of additional variables, p- and n- (see Eq. (30) in Wächter and Biegler (2006)). This quantity is also available as RINFO 5 of MON.
lg(rg) | log10 of the value of the regularization term for the Hessian of the Lagrangian in the augmented system (δw of Eq. (26) and Section 3.1 in Wächter and Biegler (2006)). A dash (–) indicates that no regularization was done. The regularization term itself is also available as RINFO 6 of MON.
alpha_du | The stepsize for the dual variables (αkz of Eq. (14c) in Wächter and Biegler (2006)). This quantity is also available as RINFO 7 of MON.
alpha_pr The stepsize for the primal variables (αk of Eq. (14a) in Wächter and Biegler (2006)). This quantity is also available as RINFO 8 of MON. The number is usually followed by a character for additional diagnostic information regarding the step acceptance criterion.
f | f-type iteration in the filter method without second order correction
F | f-type iteration in the filter method with second order correction
h | h-type iteration in the filter method without second order correction
H | h-type iteration in the filter method with second order correction
k | penalty value unchanged in merit function method without second order correction
K | penalty value unchanged in merit function method with second order correction
n | penalty value updated in merit function method without second order correction
N | penalty value updated in merit function method with second order correction
R | Restoration phase just started
w | in watchdog procedure
s | step accepted in soft restoration phase
t/T | tiny step accepted without line search
r | some previous iterate restored
ls | The number of backtracking line search steps (does not include second order correction steps). This quantity is also available as STATS 2 of MON.
Note that the step acceptance mechanisms in IPOPT consider the barrier objective function (5) which is usually different from the value reported in the objective column. Similarly, for the purposes of the step acceptance, the constraint violation is measured for the internal problem formulation, which includes slack variables for inequality constraints and potentially NLP scaling of the constraint functions. This value, too, is usually different from the value reported in inf_pr. As a consequence, a new iterate might have worse values both for the objective function and the constraint violation as reported in the iteration output, seemingly contradicting globalization procedure.
Note that all these values are also available in RINFO 1,…,RINFO 8 and STATS 1,…,STATS 2of the monitoring routine MON.
The output might look as follows:
iter    objective    inf_pr   inf_du lg(mu)  ||d||  lg(rg) alpha_du alpha_pr  ls
   0  2.6603500E+05 1.55E+02 3.21E+01  -1.0 0.00E+00    -  0.00E+00 0.00E+00   0
   1  1.5053889E+05 7.95E+01 1.43E+01  -1.0 1.16E+00    -  4.55E-01 1.00E+00f  1
   2  8.9745785E+04 3.91E+01 6.45E+00  -1.0 3.07E+01    -  5.78E-03 1.00E+00f  1
   3  3.9878595E+04 1.63E+01 3.47E+00  -1.0 5.19E+00   0.0 2.43E-01 1.00E+00f  1
   4  2.7780042E+04 1.08E+01 1.64E+00  -1.0 3.66E+01    -  7.24E-01 8.39E-01f  1
   5  2.6194274E+04 1.01E+01 1.49E+00  -1.0 1.07E+01    -  1.00E+00 1.05E-01f  1
   6  1.5422960E+04 4.75E+00 6.82E-01  -1.0 1.74E+01    -  1.00E+00 1.00E+00f  1
   7  1.1975453E+04 3.14E+00 7.26E-01  -1.0 2.83E+01    -  1.00E+00 5.06E-01f  1
   8  8.3508421E+03 1.34E+00 2.04E-01  -1.0 3.96E+01    -  9.27E-01 1.00E+00f  1
   9  7.0657495E+03 4.85E-01 9.22E-02  -1.0 5.32E+01    -  1.00E+00 1.00E+00f  1
iter    objective    inf_pr   inf_du lg(mu)  ||d||  lg(rg) alpha_du alpha_pr  ls
  10  6.8359393E+03 1.17E-01 1.28E-01  -1.7 4.69E+01    -  8.21E-01 1.00E+00h  1
  11  6.6508917E+03 1.52E-02 1.52E-02  -2.5 1.87E+01    -  1.00E+00 1.00E+00h  1
  12  6.4123213E+03 8.77E-03 1.49E-01  -3.8 1.85E+01    -  7.49E-01 1.00E+00f  1
  13  6.3157361E+03 4.33E-03 1.90E-03  -3.8 2.07E+01    -  1.00E+00 1.00E+00f  1
  14  6.2989280E+03 1.12E-03 4.06E-04  -3.8 1.54E+01    -  1.00E+00 1.00E+00h  1
  15  6.2996264E+03 9.90E-05 2.05E-04  -5.7 5.35E+00    -  9.63E-01 1.00E+00h  1
  16  6.2998436E+03 0.00E+00 1.86E-07  -5.7 4.55E-01    -  1.00E+00 1.00E+00h  1
  17  6.2998424E+03 0.00E+00 6.18E-12  -8.2 2.62E-03    -  1.00E+00 1.00E+00h  1
If Print Level>2, each iteration produces significantly more detailed output comprising detailed error measures and output from internal operations. The output is reasonably self-explanatory so it is not featured here in detail.
Summary
Once the solver finishes, a detailed summary is produced if Print Level≥1. An example is shown below:
Number of Iterations....: 6

                                   (scaled)                 (unscaled)
Objective...............:   7.8692659500479623E-01    6.2324586324379867E+00
Dual infeasibility......:   7.9744615766675617E-10    6.3157735687207093E-09
Constraint violation....:   8.3555384833289281E-12    8.3555384833289281E-12
Complementarity.........:   0.0000000000000000E+00    0.0000000000000000E+00
Overall NLP error.......:   7.9744615766675617E-10    6.3157735687207093E-09

Number of objective function evaluations             = 7
Number of objective gradient evaluations             = 7
Number of equality constraint evaluations            = 7
Number of inequality constraint evaluations          = 0
Number of equality constraint Jacobian evaluations   = 7
Number of inequality constraint Jacobian evaluations = 0
Number of Lagrangian Hessian evaluations             = 6
Total CPU secs in IPOPT (w/o function evaluations)   =      0.724
Total CPU secs in NLP function evaluations           =      0.343

EXIT: Optimal Solution Found.
It starts with the total number of iterations the algorithm went through. Then, five quantities are printed, all evaluated at the termination point: the value of the objective function, the dual infeasibility, the constraint violation, the complementarity and the NLP error.
This is followed by some statistics on the number of calls to user-supplied functions and CPU time taken in user-supplied functions and the main algorithm. Lastly, status at exit is indicated by a short message. Detailed timings of the algorithm are displayed only if Stats Time is set.

9.2 Additional Licensor

Parts of the code for E04STF are distributed according to terms imposed by another licensor. Please refer to Library Licensors for further details.

10 Example

This example is based on Problem 73 in Hock and Schittkowski (1981) and involves the minimization of the linear function
f x= 24.55 x 1+ 26.75 x 2+ 39.00 x 3+ 40.50 x 4
subject to the bounds
0≤x 1, 0≤x 2, 0≤x 3, 0≤x 4,
to the nonlinear constraint
12 x 1+ 11.9 x 2+ 41.8 x 3+ 52.1 x 4-21- 1.645 0.28 x 12+ 0.19 x 22+ 20.5 x 32+ 0.62 x 42 ≥0
and the linear constraints
2.3 x 1+ 5.6 x 2+ 11.1 x 3+ 1.3 x 4≥5 , x 1+ x 2+ x 3+ x 4-1=0.
The initial point, which is infeasible, is
x 0 = 1, 1, 1, 1 T
and f x 0=130.8. The optimal solution (to five significant figures) is
x*=0.63552,0.0,0.31270,0.051777 T,

10.1 Program Text

Program Text (e04stfe.f90)

10.2 Program Results

Program Results (e04stfe.r)

11 Algorithmic Details

E04STF is an implementation of IPOPT (see Wächter and Biegler (2006)) that is fully supported and maintained by NAG. It uses Harwell packages MA97 for the underlying sparse linear algebra factorization and MC68 approximate minimum degree algorithm for the ordering. Any issues relating to E04STF should be directed to NAG who assume all responsibility for the E04STF routine and its implementation.
In the remainder of this section, we repeat part of Section 2.1 of Wächter and Biegler (2006).
To simplify notation, we describe the method for the problem formulation
minimize x∈ℝ n f x (2)
subject to g x=0 (3)
x≥0 . (4)
Range constraints of the form l≤c x≤u can be expressed in this formulation by introducing slack variables xs≥0, xt≥0 (increasing n by 2) and defining new equality constraints g x,xs≡c x-l-xs=0 and g x,xt≡u-c x-xt=0.
E04STF, like the methods discussed in Williams and Lang (2013), Byrd et al. (2000), Conn et al. (2000) and Fiacco and McCormick (1990), computes (approximate) solutions for a sequence of barrier problems
minimize x∈ℝ n φ μ x ≔ f x - μ ∑ i=1 n ln x i (5)
subject to g x=0 (6)
for a decreasing sequence of barrier parameters μ converging to zero.
The algorithm may be interpreted as a homotopy method to the primal-dual equations,
∇f x + ∇g x λ - z = 0 (7)
g x=0 (8)
XZe - μe = 0 (9)
with the homotopy parameter μ, which is driven to zero (see e.g., Byrd et al. (1997) and Gould et al. (2001)). Here, X≔diag x for a vector x (similarly z≔diag z, etc.), and e stands for the vector of all ones for appropriate dimension, while λ∈ℝ m and z∈ℝ n correspond to the Lagrange multipliers for the equality constraints (3) and the bound constraints (4), respectively.
Note, that the equations (7), (8) and (9) for μ=0 together with ‘x, z≥0’ are the Karush–Kuhn–Tucker (KKT) conditions for the original problem (2), (3) and (4). Those are the first order optimality conditions for (2), (3) and (4) if constraint qualifications are satisfied (Conn et al. (2000)).
Starting from an initial point supplied in X, E04STF computes an approximate solution to the barrier problem (5) and (6) for a fixed value of μ (by default, 0.1), then decreases the barrier parameter, and continues the solution of the next barrier problem from the approximate solution of the previous one.
A sophisticated overall termination criterion for the algorithm is used to overcome potential difficulties when the Lagrange multipliers become large. This can happen, for example, when the gradients of the active constraints are nearly linear dependent. The termination criterion is described in detail by Wächter and Biegler (2006) (also see below Section 11.1).

11.1 Stopping Criteria

Using the individual parts of the primal-dual equations (7), (8) and (9), we define the optimality error for the barrier problem as
Eμ x,λ,z ≔ max ∇f x + ∇g x λ - z ∞ s d ,g x∞, XZe - μe ∞ s c (10)
with scaling parameters sd, sc≥1 defined below (not to be confused with NLP scaling factors described in Section 11.2). By E 0 x,λ,z we denote (10) with μ=0; this measures the optimality error for the original problem (2), (3) and (4). The overall algorithm terminates if an approximate solution x~*,λ~*,z~* (including multiplier estimates) satisfying
E 0 x~*,λ~*,z~* ≤ εtol (11)
is found, where εtol>0 is the user provided error tolerance in optional parameter Stop Tolerance 1.
Even if the original problem is well scaled, the multipliers λ and z might become very large, for example, when the gradients of the active constraints are (nearly) linearly dependent at a solution of (2), (3) and (4). In this case, the algorithm might encounter numerical difficulties satisfying the unscaled primal-dual equations (7), (8) and (9) to a tight tolerance. In order to adapt the termination criteria to handle such circumstances, we choose the scaling factors
sd ≔ max smax, λ 1+z 1 m+n / smax    sc ≔ max s max , z 1 n / smax
in (10). In this way, a component of the optimality error is scaled, whenever the average value of the multipliers becomes larger than a fixed number smax≥1 (smax=100 in our implementation). Also note, in the case that the multipliers diverge, E 0 x,λ,z can only become small, if a Fritz John point for (2), (3) and (4) is approached, or if the primal variables diverge as well.

11.2 Scaling the NLP

Ideally, the formulated problem should be scaled so that, near the solution, all function gradients (objective and constraints), when nonzero, are of a similar order of a magnitude. E04STF will compute automatic NLP scaling factors for the objective and constraint functions (but not the decision variables) and apply them if large imbalances of scale are detected. This rescaling is only computed at the starting point. References to scaled or unscaled objective or constraints in Section 9.1 and Section 11 should be understood in this context.

12 Optional Parameters

Several optional parameters in E04STF define choices in the problem specification or the algorithm logic. In order to reduce the number of formal arguments of E04STF these optional parameters have associated default values that are appropriate for most problems. Therefore, you need only specify those optional parameters whose values are to be different from their default values.
The remainder of this section can be skipped if you wish to use the default values for all optional parameters.
The optional parameters can be changed by calling E04ZMF anytime between the initialization of the handle by E04RAF and the call to the solver. Modification of the arguments during intermediate monitoring stops is not allowed. Once the solver finishes, the optional parameters can be altered again for the next solve.
If any options are set by the solver (typically those with the choice of AUTO), their value can be retrieved by E04ZNF. If the solver is called again, any such arguments are reset to their default values and the decision is made again.
The following is a list of the optional parameters available. A full description of each optional parameter is provided in Section 12.1.
  • Defaults
  • Hessian Mode
  • Infinite Bound Size
  • Monitoring File
  • Monitoring Level
  • Outer Iteration Limit
  • Print File
  • Print Level
  • Stats Time
  • Stop Tolerance 1
  • Time Limit
  • Verify Derivatives

12.1 Description of the Optional Parameters

For each option, we give a summary line, a description of the optional parameter and details of constraints.
The summary line contains:
  • the keywords, where the minimum abbreviation of each keyword is underlined;
  • a parameter value, where the letters a, i and r denote options that take character, integer and real values respectively.
  • the default value, where the symbol ε is a generic notation for machine precision (see X02AJF).
All options accept the value DEFAULT to return single options to their default states.
Keywords and character values are case and white space insensitive.
Defaults
This special keyword may be used to reset all optional parameters to their default values. Any argument value given with this keyword will be ignored.
Hessian Mode a Default =AUTO
This argument specifies whether the Hessian will be supplied by the user (in HX) or approximated by E04STF using a limited-memory quasi-Newton L-BFGS method. In the AUTO setting, if no Hessian structure has been registered in the problem with a call to E04RLF, and there are explicitly nonlinear user-supplied functions, then the Hessian will be approximated. Otherwise HESS will be called if and only if any of E04RGF or E04RKF have been used to define the problem. Approximating the Hessian is likely to require more iterations to achieve convergence but will reduce the time spent in user-supplied functions.
Constraint: Hessian Mode=AUTO, EXACT or APPROXIMATE.
Infinite Bound Size r Default =1020
This defines the ‘infinite’ bound bigbnd in the definition of the problem constraints. Any upper bound greater than or equal to bigbnd will be regarded as +∞ (and similarly any lower bound less than or equal to -bigbnd will be regarded as -∞). Note that a modification of this optional parameter does not influence constraints which have already been defined; only the constraints formulated after the change will be affected.
It also serves as a limit for the objective function to be considered unbounded (IFAIL=54).
Constraint: Infinite Bound Size≥1000.
Monitoring File i Default =-1
If i≥0, the unit number for the secondary (monitoring) output. If set to -1, no secondary output is provided. The information output to this unit is controlled by Monitoring Level.
Constraint: Monitoring File≥-1.
Monitoring Level i Default =4
This argument sets the amount of information detail that will be printed by the solver to the secondary output. The meaning of the levels is the same as with Print Level.
Constraint: 0≤Monitoring Level≤5.
Outer Iteration Limit i Default =100
The maximum number of iterations to be performed by E04STF. Setting the option too low might lead to IFAIL=22.
Constraint: Outer Iteration Limit≥0.
Print File i Default =6
If i≥0, the unit number for the primary output of the solver. If Print File=-1, the primary output is completely turned off independently of other settings. The information output to this unit is controlled by Print Level.
Constraint: Print File≥-1.
Print Level i Default =2
This argument defines how detailed information should be printed by the solver to the primary output.
i | Output
0 | No output from the solver (except a one-time banner)
1 | Additionally, derivative check information, the Header and Summary.
2 | Additionally, the Iteration log.
3, 4 | Additionally, details of each iteration with scalar quantities printed.
5 | Additionally, individual components of arrays are printed resulting in large output.
Constraint: 0≤Print Level≤5.
Stats Time a Default =NO
This argument allows you to turn on timings of various parts of the algorithm to give a better overview of where most of the time is spent. This might be helpful for a choice of different solving approaches.
Constraint: Stats Time=YES or NO.
Stop Tolerance 1 r Default =max 10-6,ε
This option sets the value εtol which is used for optimality and complementarity tests from KKT conditions See Section 11.1.
Constraint: Stop Tolerance 1>ε.
Time Limit r Default =106
A limit on seconds that the solver can use to solve one problem. If during the convergence check this limit is exceeded, the solver will terminate with a corresponding error message.
Constraint: Time Limit>0.
Verify Derivatives a Default =AUTO
This argument specifies whether the routine should perform numerical checks on the consistency of the user-supplied functions. It is recommended that such checks are enabled when first developing the formulation of the problem. Option AUTO will perform the checks unless it is determined that there are no explicitly nonlinear user-supplied functions.
Constraint: Verify Derivatives=AUTO, YES or NO.
E04 Chapter Contents
E04 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


E04SVF : NAG Library, Mark 26

E04 Chapter Contents
E04 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

E04SVF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
▸▿ 3 Description
3.1 Structure of the Lagrangian Multipliers
3.2 Approximation of the Lagrangian Multipliers
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
▸▿ 9 Further Comments
9.1 Description of the Printed Output
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results
▸▿ 11 Algorithmic Details
11.1 Overview
11.2 Stopping Criteria
11.3 Choice of penalty functions φ_g and φ_A
11.4 Solution of the inner problem
▸▿ 12 Optional Parameters
12.1 Description of the Optional Parameters

1 Purpose

E04SVF is a solver from the NAG optimization modelling suite for problems such as, quadratic programming (QP), linear semidefinite programming (SDP) and semidefinite programming with bilinear matrix inequalities (BMI-SDP).

2 Specification

SUBROUTINE E04SVF ( HANDLE, NVAR, X, NNZU, U, NNZUC, UC, NNZUA, UA, RINFO, STATS, INFORM, IFAIL)
INTEGER | NVAR, NNZU, NNZUC, NNZUA, INFORM, IFAIL
REAL (KIND=nag_wp) | X(NVAR), U(NNZU), UC(NNZUC), UA(NNZUA), RINFO(32), STATS(32)
TYPE (C_PTR) | HANDLE

3 Description

E04SVF serves as a solver for compatible problems stored as a handle. The handle points to an internal data structure which defines the problem and serves as means of communication for routines in the suite. First, the problem handle is initialized by E04RAF. Then some of the routines E04REF, E04RFF, E04RHF, E04RJF, E04RNF or E04RPF may be used to formulate the objective function, (standard) constraints and matrix constraints of the problem. Once the problem is fully set, the handle may be passed to the solver. When the handle is not needed anymore, E04RZF should be called to destroy it and deallocate the memory held within. See E04RAF for more details.
Problems which can be defined this way are, for example, (generally nonconvex) quadratic programming (QP)
minimize x∈ℝ n 12 xT Hx + cT x   (a) subject to lB≤Bx≤uB   (b) lx≤x≤ux ,   (c) (1)
linear semidefinite programming problems (SDP)
minimize x∈ℝ n cT x   (a) subject to   ∑ i=1 n xi Aik - A 0 k ⪰ 0 ,  k=1,…,mA   (b) lB≤Bx≤uB   (c) lx≤x≤ux   (d) (2)
or semidefinite programming problems with bilinear matrix inequalities (BMI-SDP)
minimize x∈ℝ n 12 xT Hx + cT x   (a) subject to   ∑ i,j=1 n xi xj Q ij k + ∑ i=1 n xi Aik - A 0 k ⪰ 0 ,  k=1,…,mA   (b) lB≤Bx≤uB   (c) lx≤x≤ux .   (d) (3)
Here c, lx and ux are n-dimensional vectors, H is a symmetric n by n matrix, lB, uB are mB-dimensional vectors, B is a general mB by n rectangular matrix and Aik, Q ij k are symmetric matrices. The expression S⪰0 stands for a constraint on eigenvalues of a symmetric matrix S, namely, all the eigenvalues should be non-negative, i.e., the matrix should be positive semidefinite. See relevant routines of the suite for more details on the problem formulation.
The solver is based on a generalized Augmented Lagrangian method with a suitable choice of standard and matrix penalty functions. For a detailed description of the algorithm see Section 11. Under standard assumptions on the problem (Slater constraint qualification, boundedness of the objective function on the feasible set, see Stingl (2006) for details) the algorithm converges to a local solution. In case of convex problems such as linear SDP or convex QP, this is the global solution. The solver is suitable for both small dense and large-scale sparse problems.
The algorithm behaviour and solver strategy can be modified by various optional parameters (see Section 12) which can be set by E04ZMF and E04ZPF anytime between the initialization of the handle by E04RAF and a call to the solver. Once the solver has finished, options may be modified for the next solve. The solver may be called repeatedly with various starting points and/or optional parameters.
There are several optional parameters with a multiple choice where the default choice is AUTO (for example, Hessian Density). This value means that the decision over the option is left to the solver based on the structure of the problem. Option getter E04ZNF can be called to retrieve the choice of these options as well as on any other options.
Optional parameter Task may be used to switch the problem to maximization or to ignore the objective function and find only a feasible point.
Optional parameter Monitor Frequency may be used to turn on the monitor mode of the solver. The solver invoked in this mode pauses regularly even before the optimal point is found to allow monitoring the progress from the calling program. All the important error measures and statistics are available in the calling program which may terminate the solver early if desired (see argument INFORM).

3.1 Structure of the Lagrangian Multipliers

The algorithm works internally with estimates of both the decision variables, denoted by x, and the Lagrangian multipliers (dual variables) for standard and matrix constraints, denoted by u and U, respectively. You may provide initial estimates, request approximations during the run (the monitor mode turned on) and obtain the final values. The Lagrangian multipliers are split into two arrays, the multipliers u for (standard) constraints are stored in array U and multipliers U for matrix constraints in array UA. Both arrays need to conform to the structure of the constraints.
If the simple bounds were defined (E04RHF was successfully called), the first 2 n elements of U belong to the corresponding Lagrangian multipliers, interleaving a multiplier for the lower and for the upper bound for each xi. If any of the bounds were set to infinity, the corresponding Lagrangian multipliers are set to 0 and may be ignored.
Similarly, the following 2 mB elements of U belong to multipliers for the linear constraints, if formulated by E04RJF. The organization is the same, i.e., the multipliers for each constraint for the lower and upper bounds are alternated and zeroes are used for any missing (infinite bound) constraint.
A Lagrangian multiplier for a matrix constraint (one block) of dimension d by d is a dense symmetric matrix of the same dimension. All multipliers U are stored next to each other in array UA in the same order as the matrix constraints were defined by E04RNF and E04RPF. The lower triangle of each is stored in the packed column order (see Section 3.3.2 in the F07 Chapter Introduction). For example, if there are four matrix constraints of dimensions 7, 3, 1, 1, the dimension of array UA should be 36. The first 28 elements d 1 × d 1+1 /2 belong to the packed lower triangle of U 1, followed by six elements of U 2 and one element for each U 3 and U 4. See for example Section 10 in E04RDF.

3.2 Approximation of the Lagrangian Multipliers

By the nature of the algorithm, all inequality Lagrangian multiplier u,U are always kept positive during the computational process. This applies even to Lagrangian multipliers of inactive constraints at the solution. They will only be close to zero although they would normally be equal to zero exactly. This is one of the major differences between results from solvers based on the active set method (such as E04NQF) and others, such as, E04SVF or interior point methods. As a consequence, the initial estimate of the multipliers (if provided) might be adjusted by the solver to be sufficiently positive, also the estimates returned during the intermediate exits might only be a very crude approximation to their final values as they do not satisfy all the Karush–Kuhn–Tucker (KKT) conditions.
Another difference is that E04NQF merges multipliers for both lower and upper inequality into one element whose sign determines the inequality because there can be at most one active constraint and multiplier for the inactive is exact zero. Negative multipliers are associated with the upper bounds and positive with the lower bounds. On the other hand, E04SVF works with both multipliers at the same time so they are returned in two elements, one for the lower bound, the other for the upper bound (see Section 3.1). An equivalent result can be achieved by subtracting the upper bound multiplier from the lower one. This holds even when equalities are interpreted as two inequalities (see optional parameter Transform Constraints).

4 References

Ben–Tal A and Zibulevsky M (1997) Penalty/barrier multiplier methods for convex programming problems SIAM Journal on Optimization 7 347–366
Fujisawa K, Kojima M, Nakata K (1997) Exploiting sparsity in primal-dual interior-point method for semidefinite programming Math. Programming 79 235–253
Hogg J D and Scott J A (2011) HSL MA97: a bit-compatible multifrontal code for sparse symmetric systems RAL Technical Report. RAL-TR-2011-024
Kočvara M and Stingl M (2003) PENNON – a code for convex nonlinear and semidefinite programming Optimization Methods and Software 18(3) 317–333
Kočvara M and Stingl M (2007) On the solution of large-scale SDP problems by the modified barrier method using iterative solvers Math. Programming (Series B) 109(2–3) 413–444
Mittelmann H D (2003) An independent benchmarking of SDP and SOCP solvers Math. Programming 95 407–430
Stingl M (2006) On the Solution of Nonlinear Semidefinite Programs by Augmented Lagrangian Methods, PhD thesis Institute of Applied Mathematics II, Friedrich–Alexander University of Erlangen–Nuremberg

5 Arguments

1:   HANDLE – TYPE (C_PTR)Input
On entry: the handle to the problem. It needs to be initialized by E04RAF and the problem formulated by some of the routines E04REF, E04RFF, E04RHF, E04RJF, E04RNF and E04RPF. It must not be changed between the calls.
2:   NVAR – INTEGERInput
On entry: n, the number of decision variables x in the problem. It must be unchanged from the value set during the initialization of the handle by E04RAF.
3:   X NVAR – REAL (KIND=nag_wp) arrayInput/Output
Note: intermediate stops take place only if Monitor Frequency>0.
On entry: if Initial X=USER (the default), x 0, the initial estimate of the variables x, otherwise X need not be set.
On intermediate exit: the value of the variables x at the end of the current outer iteration.
On intermediate re-entry: the input is ignored.
On final exit: the final value of the variables x.
4:   NNZU – INTEGERInput
On entry: the dimension of array U.
If NNZU=0, U will not be referenced; otherwise it needs to match the dimension of constraints defined by E04RHF and E04RJF as explained in Section 3.1.
Constraint: NNZU≥0.
5:   U NNZU – REAL (KIND=nag_wp) arrayInput/Output
Note: intermediate stops take place only if Monitor Frequency>0.
If NNZU>0, U holds Lagrangian multipliers (dual variables) for (standard) constraints, i.e., simple bounds defined by E04RHF and a set of mB linear constraints defined by E04RJF. Either their initial estimates, intermediate approximations or final values, see Section 3.1.
If NNZU=0, U will not be referenced.
On entry: if Initial U=USER (the default is AUTOMATIC), u 0, the initial estimate of the Lagrangian multipliers u, otherwise U need not be set.
On intermediate exit: the estimate of the multipliers u at the end of the current outer iteration.
On intermediate re-entry: the input is ignored.
On exit: the final value of multipliers u.
6:   NNZUC – INTEGERInput
On entry: the dimension of array UC. If NNZUC=0, UC will not be referenced. This argument is reserved for future releases of the NAG Library which will allow definition of second order cone constraints. It needs to be set to 0 at the moment.
Constraint: NNZUC=0.
7:   UC NNZUC – REAL (KIND=nag_wp) arrayInput/Output
UC is reserved for future releases of the NAG Library which will allow definition of second order cone constraints. It is not referenced at the moment.
8:   NNZUA – INTEGERInput
On entry: the dimension of array UA. If NNZUA=0, UA will not be referenced; otherwise it needs to match the total number of nonzeros in all matrix Lagrangian multipliers (constraints defined by E04RNF and E04RPF) as explained in Section 3.1.
Constraint: NNZUA≥0.
9:   UA NNZUA – REAL (KIND=nag_wp) arrayInput/Output
Note: intermediate stops take place only if Monitor Frequency>0.
If NNZUA>0, UA holds the Lagrangian multipliers for matrix constraints defined by E04RNF and E04RPF, see Section 3.1.
If NNZUA=0, UA will not be referenced.
On entry: if Initial U=USER (the default is AUTOMATIC), U 0, the initial estimate of the matrix Lagrangian multipliers U, otherwise UA need not be set.
On intermediate exit: the estimate of the matrix multipliers U at the end of the outer iteration.
On intermediate re-entry: the input is ignored.
On final exit: the final estimate of the multipliers U.
10:   RINFO 32 – REAL (KIND=nag_wp) arrayOutput
On intermediate or final entry: error measures and various indicators (see Section 11 for details) at the end of the current (or final) outer iteration as given in the table below:
1 | objective function value f x
2 | optimality (12)
3 | feasibility (13)
4 | complementarity (14)
5 | minimum penalty
6 | relative precision (11)
7 | relative duality gap (10)
8 | precision f xℓ-f x ℓ+1
9 | duality gap
10 | minimum penalty for (standard) inequalities p
11 | minimum penalty for matrix inequalities P
12 | feasibility of equality constraints
13 | feasibility of (standard) inequalities
14 | feasibility of matrix inequalities
15 | complementarity of equality constraints
16 | complementarity of (standard) inequalities
17 | complementarity of matrix inequalities
18–23 | DIMACS error measures (16) (only if turned on by DIMACS Measures)
24–32 | reserved for future use
11:   STATS 32 – REAL (KIND=nag_wp) arrayOutput
On intermediate or final exit: solver statistics at the end of the current (or final) outer iteration as given in the table below. Note that time statistics is provided only if Stats Time is set (the default is NO), the measured time is returned in seconds.
1 | number of the outer iterations
2 | total number of the inner iterations
3 | total number of the linesearch steps
4 | number of evaluations of the augmented Lagrangian F, (see (8))
5 | number of evaluations of ∇F
6 | number of evaluations of ∇2 F
7 | reserved for future use
8 | total running time of the solver
9 | total running time of the solver without evaluations of the user's functions and monitoring stops
10 | time spent in the inner iterations
11 | time spent in Lagrangian multipliers updates
12 | time spent in penalty parameters updates
13 | time spent in matrix feasibility computation
14 | time of evaluations of F
15 | time of evaluations of ∇F
16 | time of evaluations of ∇2 F
17 | time of factorizations of the Newton system
18 | time of factorizations of the matrix constraints
19–32 | reserved for future use
12:   INFORM – INTEGERInput/Output
Note: intermediate stops take place only if Monitor Frequency>0.
On initial entry: no effect.
On intermediate exit: INFORM=1.
On intermediate re-entry: if set to 0, solving the current problem is terminated and the routine returns IFAIL=20; otherwise the routine continues.
On final exit: INFORM=0.
13:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, because for this routine the values of the output arguments may be useful even if IFAIL≠0 on exit, the recommended value is -1. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Note: E04SVF may return useful information for one or more of the following detected errors or warnings.
Errors or warnings detected by the routine:
IFAIL=1
The supplied HANDLE does not define a valid handle to the data structure for the NAG optimization modelling suite. It has not been initialized by E04RAF or it has been corrupted.
IFAIL=2
This solver does not support general nonlinear objective and constraints.
IFAIL=3
A different solver from the suite has already been used.
IFAIL=4
On entry, NVAR=value, expected value=value.
Constraint: NVAR must match the value given during initialization of HANDLE.
IFAIL=5
On entry, NNZU=value.
NNZU does not match the size of the Lagrangian multipliers for (standard) constraints.
The correct value is 0 for no (standard) constraints.
On entry, NNZU=value.
NNZU does not match the size of the Lagrangian multipliers for (standard) constraints.
The correct value is either 0 or value.
On entry, NNZUA=value.
NNZUA does not match the size of the Lagrangian multipliers for matrix constraints.
The correct value is 0 for no matrix constraints.
On entry, NNZUA=value.
NNZUA does not match the size of the Lagrangian multipliers for matrix constraints.
The correct value is either 0 or value.
On entry, NNZUC=value.
NNZUC does not match the size of the Lagrangian multipliers for second order cone constraints.
The correct value is 0 for no such constraints.
IFAIL=20
User requested termination during a monitoring step.
IFAIL=21
The current starting point is unusable.
The starting point x 0, either provided by the user (if Initial X=USER, the default) or the automatic estimate (if Initial X=AUTOMATIC), must not be extremely infeasible in the matrix constraints (infeasibility of order 106 and higher) and all the functions used in the problem formulation must be evaluatable.
In the unlikely case this error is triggered, it is necessary to provide a better estimate of the initial values.
IFAIL=22
Outer iteration limit has been reached.
The requested accuracy is not achieved.
If Outer Iteration Limit is left to the default, this error indicates numerical difficulties. Consider whether the stopping tolerances (Stop Tolerance 1, Stop Tolerance 2, Stop Tolerance Feasibility) are set too low or optional parameters affecting the behaviour of the penalty updates (P Update Speed, P Min or Pmat Min) have been modified inadvisedly. The iteration log should reveal more about the misbehaviour. Providing a different starting point might be of help in certain situations.
IFAIL=23
The inner subproblem could not be solved to the required accuracy.
Inner iteration limit has been reached.
The inner subproblem could not be solved to the required accuracy.
Limited progress in the inner subproblem triggered a stop (heuristic inner stop criteria).
The inner subproblem could not be solved to the required accuracy.
Line search or another internal component failed.
A problem with the convergence of the inner subproblem is typically a sign of numerical difficulties of the whole algorithm. The inner subproblem might be stopped before reaching the required accuracy because of the Inner Iteration Limit, a heuristic detected no progress in the inner iterations (if Inner Stop Criteria=HEURISTIC, default) or if an internal component failed (for example, line search was unable to find a suitable step). The algorithm tries to recover, however, it might give up after several attempts with one of these error messages. If it occurs in the very early iterations, consider increasing Inner Stop Tolerance and possibly Init Value P or Init Value Pmat which should ease the first iterations. An occurrence in later iterations indicates numerical difficulties typically due to scaling and/or ill-conditioning or the problem is close to infeasible. Reducing the tolerance on the stopping criteria or increasing P Update Speed might be of limited help.
IFAIL=24
Unable to make progress, the algorithm was stopped.
This error is returned if the solver cannot decrease the duality gap over a range of iterations. This can be due to the scaling of the problem or the problem might be close to primal or dual infeasibility.
IFAIL=50
The algorithm converged to a suboptimal solution.
The full accuracy was not achieved. The solution should still be usable.
This error may be reported only if Stop Criteria=SOFT (default). The solver predicted that it is unable to reach a better estimate of the solution. However, the error measures indicate that the point is a reasonable approximation. Typically, only the norm of the gradient of the Lagrangian (optimality) does not fully satisfy the requested tolerance whereas the others are well below the tolerance.
Setting Stop Criteria=STRICT will disallow this error but it is unlikely that the algorithm would reach a better solution.
IFAIL=51
The problem was found to be infeasible during preprocessing.
One or more of the constraints (or its part after preprocessing) violates the constraints by more than εfeas (Stop Tolerance Feasibility).
IFAIL=52
The problem was found unbounded during preprocessing.
The objective function consists of an unrestricted ray and thus the problem does not have a solution.
IFAIL=53
The problem seems to be infeasible, the algorithm was stopped.
Whilst the algorithm cannot definitively detect that the problem is infeasible, several indirect indicators suggest that it might be the case.
IFAIL=54
The problem seems to be unbounded, the algorithm was stopped.
Whilst the algorithm cannot definitively detect that the problem is unbounded, several indirect indicators (such as a rapid decrease in the objective function and a lack of convergence in the inner subproblem) suggest that this might be the case. A good scaling of the objective function is always highly recommended to avoid situations when unusual behavior triggers falsely this error exit.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

The accuracy of the solution is driven by optional parameters Stop Tolerance 1, Stop Tolerance 2, Stop Tolerance Feasibility and Stop Criteria and in certain cases DIMACS Measures.
If IFAIL=0 on the final exit, the returned point satisfies Karush–Kuhn–Tucker (KKT) conditions to the requested accuracy (under the default settings close to ε) and thus it is a good estimate of a local solution. If IFAIL=50, some of the convergence conditions were not fully satisfied but the point still seems to be a reasonable estimate and should be usable. Please refer to Section 11.2 and the description of the particular options.

8 Parallelism and Performance

E04SVF is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
E04SVF makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

9.1 Description of the Printed Output

The solver can print information to give an overview of the problem and of the progress of the computation. The output may be send to two independent unit numbers which are set by optional parameters Print File and Monitoring File. Optional parameters Print Level, Print Options and Monitoring Level determine the exposed level of detail. This allows, for example, to generate a detailed log in a file while the condensed information is displayed on the screen.
By default (Print File=6, Print Level=2), four sections are printed to the standard output: a header, a list of options, an iteration log and a summary.
Header
The header contains statistics about the size of the problem as represented internally, i.e., it reflects any changes imposed by preprocessing and problem transformations (see, for example, Presolve Block Detect and Transform Constraints). The header may look like:
E04SV, NLP-SDP Solver (Pennon)
---------------------------------------------------------------------------
Number of variables             2                 [eliminated            0]
                           simple  linear  nonlin
(Standard) inequalities         3       0       0
(Standard) equalities                   0       0
Matrix inequalities                     1       1 [dense    2, sparse    0]
                                                  [max dimension         3]
It shows the total number of variables and how many of them were eliminated (e.g., fixed by a simple equality). A constraint with both a lower and an upper bound counts as 2 inequalities. Simple bounds are set by E04RHF, matrix inequalities by E04RNF and E04RPF and standard equalities and inequalities by E04RJF. Note that matrix constraints of dimension 1 are extracted and treated as (standard) inequalities as well. The header report concludes with the number of matrix constraints factorized as dense and sparse matrices, together with the largest dimension of the matrix inequalities.
Optional parameters list
The list shows all options of the solver, each displayed on one line. The line contains the option name, its current value and an indicator for how it was set. The options left at their defaults are noted by (d), the ones set by the user are noted by (U) and the options reset by the solver by (S). The solver will automatically set options which are set to AUTO or options which are not possible to satisfy in the given context (e.g., requesting DIMACS Measures for a nonlinear problem). Note that the output format is compatible with the file format expected by E04ZPF. The output might look as follows:
Outer Iteration Limit         =                  20 * U
Stop Tolerance 1              =         1.00000E-06 * d
Stop Tolerance 2              =         1.00000E-07 * d
Hessian Density               =               Dense * S
Iteration log
If Print Level=2, the status of each major iteration is condensed to one line. The line shows the major iteration number (0 represents the starting point), the current objective value, KKT measures (optimality, feasibility and complementarity), minimal penalty and the number of inner iterations performed. Note that all these values are also available in RINFO 1,…,RINFO 5 and STATS 1. The output might look as follows:
-----------------------------------------------------------------
 it |  objective |  optim  |   feas  |  compl  | pen min  | inner
-----------------------------------------------------------------
  0   0.00000E+00  7.34E+00  1.23E-01  4.41E+01  1.00E+00   0
  1  -3.01998E-01  2.54E-03  0.00E+00  1.89E+00  1.00E+00   6
  2  -2.53008E+00  1.06E-03  1.30E-01  3.22E-01  3.17E-01   8
  3  -2.08172E+00  6.52E-03  1.85E-02  4.54E-02  1.01E-01   7
  4  -2.01060E+00  6.47E-03  4.10E-03  1.02E-02  3.19E-02   3
Occasionally, a one letter flag is printed at the end of the line indicating that the inner subproblem was not solved to the required accuracy. The possibilities are M for maximum number of inner iterations, L for difficulties in the line search and ! when a heuristic stop took place. Repeated troubles in the subproblems may lead to IFAIL=23. The output below had Inner Iteration Limit=5 which was not enough in the first subproblem (first outer iteration).
 ----------------------------------------------------------------
  it |  objective |  optim  |   feas  |  compl  | pen min | inner
 ----------------------------------------------------------------
   0  0.00000E+00  1.46E+03  5.01E+01  1.46E+03  6.40E+01   0
   1  3.78981E+02  3.86E+01  0.00E+00  1.21E+04  6.40E+01   5 M
   2  9.11724E+02  1.46E-02  0.00E+00  9.24E+02  4.45E+01   5
All KKT measures should normally converge to zero as the algorithm progresses and once the requested accuracy (Stop Tolerance 2) is achieved, the solver stops. However, the convergence is not necessarilly monotonic. The penalty parameters are decreased each major iteration which should improve overall the feasibility of the problem. This also increases the ill-conditioning which might lead to a higher number of inner iterations. A very high number of inner iterations usually signals numerical difficulties. See Section 11 for the algorithmic details.
If Print Level>2, each major iteration produces significantly more detailed output comprising detailed error measures and output from every inner iteration. The output is self-explanatory so is not featured here in detail.
Summary
Once the solver finishes, a detailed summary is produced. An example is shown below:
--------------------------------------------------------------
Status: converged, an optimal solution found
--------------------------------------------------------------
Final objective value                2.300000E+01
Relative precision                   5.873755E-09
Optimality                           1.756062E-10
Feasibility                          9.048738E-08
Complementarity                      1.855566E-08
DIMACS error 1                       8.780308E-11
DIMACS error 2                       0.000000E+00
DIMACS error 3                       0.000000E+00
DIMACS error 4                       4.524369E-08
DIMACS error 5                       4.065998E-10
DIMACS error 6                       3.948012E-10
Iteration counts
  Outer iterations                             13
  Inner iterations                             82
  Linesearch steps                             95
Evaluation counts
  Augm. Lagr. values                           96
  Augm. Lagr. gradient                         96
  Augm. Lagr. hessian                          82
Timing
  Total time                    0 h  0 min  3 sec
    Evaluations + monitoring             0.04 sec
    Solver itself                        3.09 sec
  Inner minimization step                2.72 sec   ( 87.1%)
    Augm. Lagr. value                    0.28 sec   (  9.0%)
    Augm. Lagr. gradient                 0.67 sec   ( 21.6%)
    Augm. Lagr. hessian                  1.11 sec   ( 35.4%)
    system matr. factor.                 0.64 sec   ( 20.5%)
    const. matr. factor.                 0.40 sec   ( 12.8%)
  Multiplier update                      0.01 sec   (  0.3%)
  Penalty update                         0.02 sec   (  0.5%)
  Feasibility check                      0.15 sec   (  4.7%)
--------------------------------------------------------------
It starts with the status line of the overall result which matches the IFAIL value. It is followed by the final objective value and the error measures (including DIMACS Measures if turned on). Iteration counters, numbers of evaluations of the Augmented Lagrangian function and timing of the routine conclude the section. The timing of the algorithm is displayed only if Stats Time is set.

10 Example

Semidefinite Programming has many applications in several fields of mathematics, such as, combinatorial optimization, finance, statistics, control theory or structural optimization. However, these applications seldom come in the form of (2) or (3). Usually a reformulation is needed or even a relaxation is employed to achieve the desired formulation. This is also the case of the Lovász ϑ function computed in this example. See also Section 10 in E04RAF for links to further examples in the suite.
The Lovász ϑ function (or also called ϑ number) of an undirected graph G=V,E is an important quantity in combinatorial optimization. It gives an upper bound to Shannon capacity of the graph G and is also related to the clique number and the chromatic number of the complement of G which are NP-hard problems.
The ϑ function can be expressed in various ways, here we use the following:
ϑ G = minimize λ max H ∣ H ∈ 𝕊n ,  s ij = 1 ​ if ​ i=j ​ or if ​ ij ∉ E
where n=V and 𝕊n denotes the space of real symmetric n by n matrices. This eigenvalue optimization problem is easy to reformulate as an SDP problem by introducing an artificial variable t as follows:
minimize t,H t subject to H⪯tI H∈𝕊n ,  s ij = 1 ​ if ​ i=j ​ or if ​ ij∉E .
Finally, this can be written as (2)) which is formulated in the example:
minimize t,x t subject to tI + ∑ ij∈E x ij E ij - J ⪰ 0
where J is a matrix of all ones and E ij is a matrix of all zeros except i,j and j,i.
The example also demonstrates how to set the optional parameters and how to retrieve them.
The data file stores the Petersen graph whose ϑ is 4.

10.1 Program Text

Program Text (e04svfe.f90)

10.2 Program Data

Program Data (e04svfe.d)

10.3 Program Results

Program Results (e04svfe.r)

11 Algorithmic Details

This section contains a description of the algorithm used in E04SVF which is based on the implementation of the code called Pennon. For further details, see Kočvara and Stingl (2003), Stingl (2006) and Kočvara and Stingl (2007).
For simplicity, we will use the following problem formulation; its connection to (SDP) and (BMI-SDP) is easy to see:
minimize x∈ℝn f x subject to gk x≥0, k=1,2,…,mg hk x=0, k=1,2,…,mh Ak x⪰0, k=1,2,…,mA, (4)
where f, gk, hk are C 2 functions from ℝn to ℝ and Ak is a C 2 matrix function from ℝn to 𝕊 mk. Here 𝕊m denotes the space of real symmetric matrices m×m and S∈ 𝕊m, S⪰0 stands for a constraint on eigenvalues of S, namely the matrix S should be positive semidefinite. Furthermore, we define the inner product on 𝕊m by A,B 𝕊m=trace AB. The index 𝕊m will be omitted whenever the dimension is clear from the context. Finally, for Φ:𝕊m→𝕊m and X,Y∈𝕊m, DΦ X;Y denotes the directional derivative of Φ with respect to X in direction Y.

11.1 Overview

The algorithm is based on a (generalized) augmented Lagrangian approach and on a suitable choice of smooth penalty/barrier functions φ g:ℝ→ℝ for (standard) inequality constraints and φ A:ℝ→ℝ for constraints on matrix eigenvalues. By means of φ A we define a penalty/barrier function for matrix inequalities as follows.
Let A∈𝕊m have an eigenvalue decomposition A=ST ΛS where Λ=diag⁡λ 1,λ 2,…,λm T. We define matrix function ΦP:𝕊m→𝕊m for P>0 as
ΦP:A↦ST P φA λ 1 P 0 ⋯ 0 0 P φA λ 2 P ⋯ 0 ⋮ ⋮ ⋱ ⋮ 0 0 ⋯ P φA λm P S . (5)
Both φ g and φ A satisfy a number of assumptions (see Kočvara and Stingl (2003)) guaranteeing, in particular, that for any p, P>0
gk x ≥ 0 ⇔ p φ g gk x/p ≥ 0 , k=1,2,…,mg, Ak x ⪰0 ⇔ ΦP Ak x ⪰ 0 , k=1,2,…,mA. (6)
Further in the text, we use simplified notation φ p(·)=p φ g·/p.
Thus for any p, P>0, problem (4) has the same solution as the following augmented problem
minimize x∈ℝn f x subject to φ p gk x≥0, k=1,2,…,mg hk x=0, k=1,2,…,mh ΦP Ak x⪰0, k=1,2,…,mA. (7)
The Lagrangian of (7) can be viewed as a (generalized) augmented Lagrangian of (4):
F x,u,v,U,p,P = f x - ∑ k=1 mg uk φ p gk x + ∑ k=1 mh vk hk x - ∑ k=1 mA Uk, ΦP Ak x ; (8)
where u∈ℝ mg, v∈ℝ mh and U=U 1,…,U mA, Uk∈𝕊 pk, k=1,…,mA are Lagrange multipliers associated with the (standard) inequalities and equalities and the matrix inequality constraints, respectively.
The algorithm combines ideas of the (exterior) penalty and (interior) barrier methods with the augmented Lagrangian method, it can be defined as follows:
  • Algorithm 1 (Outer Loop)
  • Let x 0, u 0, v 0 and U 0 be given. Let p 0>0, P 0>0, α 0>0. For ℓ=0,1,… repeat until a stopping criteria or maximum number of iterations is reached:
    (i) Find x ℓ+1, v ℓ+1 satisfying
    ∇x F x ℓ+1,uℓ,v ℓ+1,Uℓ,pℓ,Pℓ ≤ αℓ h x ℓ+1 ≤ αℓ (9)
    (ii) Update Lagrangian multipliers
    U k ℓ+1 = D ΦP Ak x ℓ+1 ; U k ℓ ,   k=1,2,…,mA u k ℓ+1 = u k ℓ φ g ' gk x ℓ+1 / pℓ ,   k=1,2,…,mg
    (iii) Update penalty parameters and inner problem stopping criteria
    p ℓ+1 < pℓ ,   P ℓ+1 < Pℓ ,   α ℓ+1 ≤ αℓ .
Step (i) of Algorithm 1, further referred as the inner problem, is the most time-consuming and thus the choice of the solver for (9) is critical for the overall efficiency of the method. See Section 11.4 below.
The inequality Lagrangian multipliers update in step (ii) is motivated by the fact that if x ℓ+1, v ℓ+1 solve (9) exactly in iteration ℓ, we obtain
∇x F x ℓ+1,u ℓ+1,v ℓ+1,U ℓ+1,pℓ,Pℓ =0 .
Details can be found, for example, in Stingl (2006).
In practise, numerical studies showed that it is not advantageous to do the full updates of multipliers u, U. Firstly, big changes in the multipliers may lead to a large number of iterations in subsequent solution of (9) and, secondly, the multipliers might become ill-conditioned after a few steps and the algorithm suffers from numerical instabilities. To overcome these difficulties, a restricted update is performed instead.
New Lagrangian multipliers for (standard) inequalities uk ℓ+1, for k=1,2,…,mg are limited not to violate the following bound
μg < u k ℓ+1 u k ℓ < 1 μg
for a given 0<μg <1 (see U Update Restriction).
A similar strategy is applied to the matrix multipliers Uk ℓ+1 as well. For 0<μA<1 (see Umat Update Restriction) set
U k new = U k ℓ+1 + μA U k ℓ - U k ℓ+1 .
The penalty parameters p,P in step (iii) are updated by some constant factor dependent on the initial penalty parameters p 0,P 0 and P Update Speed. The update process is stopped when pmin and Pmin are reached (see P Min, Pmat Min).
Additional details about the multiplier and penalty update strategies, as well as local and global convergence properties under standard assumptions can be found in an extensive study Stingl (2006).

11.2 Stopping Criteria

Algorithm 1 is stopped when all the stopping criteria are satisfied to the requested accuracy, these are:
f xℓ - F xℓ,uℓ,vℓ,Uℓ,pℓ,Pℓ 1+f xℓ ≤ε 1 , ​   relative duality gap (10)
f xℓ - f x ℓ-1 1+f xℓ ≤ε 1 ,        relative precision (11)
and these based on Karush–Kuhn–Tucker (KKT) error measures, to keep the notation simple, formulation (4) is assumed and iteration index ℓ is dropped:
∇ f x - ∑ k=1 mg uk ∇ gk x + ∑ k=1 mh vk ∇ hk x - ∑ k=1 mA Uk, ∂ ∂xi Ak x i=1,…,n ≤ ε 2 ,     optimality (12)
gk x ≥ -εfeas ,  hk x ≤ εfeas ,   Ak x ⪰ -εfeas I   for all ​ k ,       feasibility (13)
gk x uk ≤ ε 2 ,   hk x vk ≤ ε 2 ,   Ak x ,Uk ≤ ε 2 .          complementarity (14)
Here ε 1, ε 2, εfeas may be set in the option settings as Stop Tolerance 1, Stop Tolerance 2 and Stop Tolerance Feasibility, respectively.
Note that if Task=FEASIBLE POINT, only the feasibility is taken into account.
There is an option for linear SDP problems to switch from stopping criteria based on the KKT conditions to DIMACS Measures, see Mittelmann (2003). This is the default choice. To keep the notation readable, these are defined here only for the following simpler formulation of linear SDP rather than (2):
minimize x∈ℝ n cT x subject to   A x = ∑ i=1 n xi Ai - A 0 ⪰ 0 . (15)
In this case the algorithm stops when:
Derr 1 = A*U - c 1+c Derr 2 = max 0, - λmin U 1+c Derr 4 = max 0, - λmin ∑ i=1 n xi Ai - A 0 1+A 0 Derr 5 = A 0,U - cT x 1+ A 0,U + cT x Derr 6 = ∑ i=1 n xiAi - A 0 ,U 1 + A 0,U + cT x (16)
where A*(·) denote the adjoint operator to A(·), A*U i=Ai,U.
They can be viewed as a scaled version of the KKT conditions. Derr 1 represents the (scaled) norm of the gradient of the Lagrangian, Derr 2 and Derr 4 the dual and primal infeasibility, respectively, and Derr 5 and Derr 6 measure the duality gap and the complementary slackness. Note that in this solver Derr 2=0 by definition and Derr 3 is automaticaly zero because the formulation involves slack variables which are not used here.

11.3 Choice of penalty functions φ g and φ A

To treat the (standard) inequality constraints gk x≥0, we use the penalty/barrier function proposed by Ben–Tal and Zibulevsky (1997):
φ g τ = -τ + 12 τ 2 if ​ τ≤ τ- - 1- τ- 2 log 1-2 τ-+τ 1-τ- -τ- + 12 τ-2 if ​τ>τ-;
with default τ-=12.
The choice of φ A (and thus of ΦP) is motivated by the complexity of the evaluation of ΦP and its derivatives. If φ A is defined as
φ A τ = 1 1+τ - 1 ,
it is possible to avoid the explicit eigenvalue decomposition in (5) as it can be seen in the formulae below (note that index k is omitted):
ΦP A x = P 2 Z x -PI ∂ ∂xi ΦP A x = - P 2 Z x ∂A x ∂ xi Z x ∂2 ∂xi ∂xj ΦP A x = P 2 Z x ∂A x ∂ xi Z x ∂A x ∂ xj - ∂2 A x ∂xi ∂ xj + ∂A x ∂ xj Z x ∂A x ∂ xi Z x (17)
where
Z x = A x + P I-1 . (18)
For details follow Kočvara and Stingl (2003). Note that, in particular, formula (17) requires nontrivial computational resources even if careful handling of the sparsity of partial derivatives of A x is implemented. E04SVF uses a set of strategies described in Fujisawa et al. (1997) adapted for parallel computation.

11.4 Solution of the inner problem

This section describes solving of the inner problem (step (i) of Algorithm 1). We attempt to find an approximate solution of the following system (in x and v) up to the given precision α:
∇x F x,u,v,U,p,P = 0 h x = 0 (19)
where the penalty parameters p,P, as well as the Lagrangian multipliers u and U are fixed.
A linesearch SQP framework is used due to its desirable convergence properties. It can be stated as follows.
  • Algorithm 2 (Inner Loop)
  • Let x 0, v 0 be given (typically as the solution from the previous outer iteration), p, P, u, U and α>0 fixed. For ℓ=0,1,…
    (i) Find a descent direction d by solving
    ∇2 F xℓ ∇ h x ℓ ∇ h xℓ T 0 d dv = - ∇ F xℓ h xℓ (20)
    (ii) Find a suitable step length δ and set
    x ℓ+1 = xℓ + δ d v ℓ+1 = vℓ + δ dv
    (iii) Stop if Inner Iteration Limit is reached or if
    ∇x F x ℓ+1,u,v ℓ+1,U,p,P ≤ α h x ℓ+1 ≤ α .
System (20) is solved by the factorization routine MA97 (see Hogg and Scott (2011), in combination with an inertia correction strategy described in Stingl (2006). The step length selection is guided by Linesearch Mode.
If there are no equality constraints in the problem, the unconstrained minimization in Step (i) of Algorithm 1 simplifies to the modified Newton method with line-search (for details, see Kočvara and Stingl (2003)). Alternatively, the equality constraints hk x = 0 can be converted to two inequalities which would be treated with the remaining constraints (see Transform Constraints).

12 Optional Parameters

Several optional parameters in E04SVF define choices in the problem specification or the algorithm logic. In order to reduce the number of formal arguments of E04SVF these optional parameters have associated default values that are appropriate for most problems. Therefore, you need only specify those optional parameters whose values are to be different from their default values.
The remainder of this section can be skipped if you wish to use the default values for all optional parameters.
The optional parameters can be changed by calling E04ZMF anytime between the initialization of the handle by E04RAF and the call to the solver. Modification of the arguments during intermediate monitoring stops is not allowed. Once the solver finishes, the optional parameters can be altered again for the next solve.
If any options are set by the solver (typically those with the choice of AUTO), their value can be retrieved by E04ZNF. If the solver is called again, any such arguments are reset to their default values and the decision is made again.
The following is a list of the optional parameters available. A full description of each optional parameter is provided in Section 12.1.
  • Defaults
  • DIMACS Measures
  • Hessian Density
  • Infinite Bound Size
  • Initial P
  • Initial U
  • Initial X
  • Init Value P
  • Init Value Pmat
  • Inner Iteration Limit
  • Inner Stop Criteria
  • Inner Stop Tolerance
  • Linesearch Mode
  • List
  • Monitor Frequency
  • Monitoring File
  • Monitoring Level
  • Outer Iteration Limit
  • Pmat Min
  • P Min
  • Preference
  • Presolve Block Detect
  • Print File
  • Print Level
  • Print Options
  • P Update Speed
  • Stats Time
  • Stop Criteria
  • Stop Tolerance 1
  • Stop Tolerance 2
  • Stop Tolerance Feasibility
  • Task
  • Transform Constraints
  • Umat Update Restriction
  • U Update Restriction

12.1 Description of the Optional Parameters

For each option, we give a summary line, a description of the optional parameter and details of constraints.
The summary line contains:
  • the keywords, where the minimum abbreviation of each keyword is underlined;
  • a parameter value, where the letters a, i and r denote options that take character, integer and real values respectively;
  • the default value, where the symbol ε is a generic notation for machine precision (see X02AJF).
All options accept the value DEFAULT to return single options to their default states.
Keywords and character values are case and white space insensitive.
Defaults
This special keyword may be used to reset all optional parameters to their default values. Any argument value given with this keyword will be ignored.
DIMACS Measures a Default =CHECK
If the problem is a linear semidefinite programming problem, this argument specifies if DIMACS error measures (see Section 11.2) should be computed and/or checked. In other cases, this option reverts to NO automatically.
Constraint: DIMACS Measures=COMPUTE, CHECK or NO.
Hessian Density a Default =AUTO
This optional parameter guides the solver on how the Hessian matrix of augmented Lagrangian F x,u,v,U,p,P should be built. Option AUTO leaves the decision to the solver and it is the recommended option. Setting it to DENSE bypasses the autodetection and the Hessian is always built as a dense matrix. Option SPARSE instructs the solver to use a sparse storage and factorization of the matrix if possible.
Constraint: Hessian Density=AUTO, DENSE or SPARSE
Infinite Bound Size r Default =1020
This defines the ‘infinite’ bound bigbnd in the definition of the problem constraints. Any upper bound greater than or equal to bigbnd will be regarded as +∞ (and similarly any lower bound less than or equal to -bigbnd will be regarded as -∞). Note that a modification of this optional parameter does not influence constraints which have already been defined; only the constraints formulated after the change will be affected.
Constraint: Infinite Bound Size≥1000.
Initial P a Default =AUTOMATIC
This optional parameter defines the choice of the penalty optional parameters p 0, P 0, see Algorithm 1.
Initial P=AUTOMATIC
The penalty optional parameters are chosen automatically as set by optional parameter Init Value P, Init Value Pmat and subject to automatic scaling. Note that P 0 might be increased so that the penalty function ΦP is defined for all matrix constraints at the starting point.
Initial P=KEEP PREVIOUS
The penalty optional parameters are kept from the previous run of the solver if possible. If not, this options reverts to AUTOMATIC. Note that even if the matrix penalty optional parameters are the same as in the previous run, they are still subject to a possible increase so that the penalty function ΦP is well defined at the starting point.
Constraint: Initial P=AUTOMATIC or KEEP PREVIOUS.
Initial U a Default =AUTOMATIC
This argument guides the solver on which initial Lagrangian multipliers are to be used.
Initial U=AUTOMATIC
The Lagrangian multipliers are chosen automatically as set by automatic scaling.
Initial U=USER
The values of arrays U and UA (if provided) are used as the initial Lagrangian multipliers subject to automatic adjustments. If one or the other array is not provided, the choice for missing data is as in AUTOMATIC.
Initial U=KEEP PREVIOUS
The Lagrangian multipliers are kept from the previous run of the solver. If this option is set for the first run or optional parameters change the approach of the solver, the choice automatically reverts to AUTOMATIC. This might be useful if the solver is hot started, for example, to achieve higher precision of the solution.
Constraint: Initial U=AUTOMATIC, USER or KEEP PREVIOUS.
Initial X a Default =USER
This argument guides which starting point x 0 is to be used.
Initial X=AUTOMATIC
The starting point is chosen automatically so that it satisfies simple bounds on the variables or as a zero vector. Input of argument X is ignored.
Initial X=USER
Initial values of argument X are used as a starting point.
Constraint: Initial X=AUTOMATIC or USER.
Init Value P r Default =1.0
This argument defines the value p 0, the initial penalty optional parameter for (standard) inequalities. A low value of the penalty causes the solution of the inner problem to be closer to the feasible region and thus to the desirable result. However, it also increases ill-conditioning of the system. It is not advisable to set the penalty too low unless a good starting point is provided.
Constraint: ε 4≤Init Value P≤104.
Init Value Pmat r Default =1.0
The value of this option suggests P 0, the initial penalty optional parameter for matrix inequalities. It is similar to Init Value P (and the same advice applies), however, P 0 gets increased automatically if the matrix constraints are more infeasible than the actual penalty optional parameter.
Constraint: ε 4≤Init Value Pmat≤104.
Inner Iteration Limit i Default =100
The maximum number of the inner iterations (Newton steps) to be performed by Algorithm 2 in each outer iteration. Setting the option too low might lead to IFAIL=23. Values higher than 100 are unlikely to improve convergence.
Constraint: Inner Iteration Limit>0.
Inner Stop Criteria a Default =HEURISTIC
The precision α for the solution of the inner subproblem is determined in Algorithm 1 and under typical circumstances Algorithm 2 is expected to reach this precision within the given Inner Iteration Limit. If any problems are detected and Inner Stop Criteria=HEURISTIC, Algorithm 2 is allowed to stop before reaching the requested precision or the Inner Iteration Limit. This usually saves many unfruitful iterations and the solver may recover in the following iterations. If you suspect that the heuristic problem detection is not suitable for your problem, setting Inner Stop Criteria=STRICT disallows such behaviour.
Constraint: Inner Stop Criteria=HEURISTIC or STRICT.
Inner Stop Tolerance r Default =10-2
This option sets the required precision α 0 for the first inner problem solved by Algorithm 2. The precison of the solution of the inner problem does not need to be very high in the first outer iterations and it is automatically adjusted through the outer iterations to reach the optimality limit ε 2 in the last one.
Setting α 0 too restrictive (too low) causes an increase of the number of inner iterations needed in the first outer iterations and might lead to IFAIL=23. In certain cases it might be helpful to use a more relaxed (higher) α 0 and increase P Update Speed which should reduce the number of inner iterations needed at the beginning of the computation in exchange for a possibly higher number of the outer iterations.
Constraint: ε<Inner Stop Tolerance≤103.
Linesearch Mode a Default =AUTO
This controls the step size selection in Algorithm 2. If Linesearch Mode=FULLSTEP (the default for linear problems), unit steps are taken where possible and the step shortening takes place only to avoid undefined regions for the matrix penalty function ΦP (see (17)). This may be used for linear problems but it is not recommended for any nonlinear ones. If Linesearch Mode=ARMIJO, Armijo backtracking linesearch is used instead which is a fairly basic linesearch. If Linesearch Mode=GOLDSTEIN, a cubic safe guarded linesearch based on Goldstein condition is employed, this is the recommended (and default) choice for nonlinear problems.
Constraint: Linesearch Mode=AUTO, FULLSTEP, ARMIJO or GOLDSTEIN.
List a Default =NO
This argument may be set to YES if you wish to turn on printing of each optional parameter specification as it is supplied.
Constraint: List=YES or NO
Monitor Frequency i Default =0
If Monitor Frequency>0, the solver returns to you at the end of every ith outer iteration. During these intermediate exits, the current point X and Lagrangian multipliers U, UA (if requested) are provided as well as the statistics and error measures (RINFO, STATS). Argument INFORM helps to distinguish between intermediate and final exits and also allows immediate termination.
If Monitor Frequency=0, the solver stops only once on the final point and no intermediate exits are made.
Constraint: Monitor Frequency≥0.
Monitoring File i Default =-1
If i≥0, the unit number for the secondary (monitoring) output. If set to -1, no secondary output is provided. The following information is output to the unit:
  • – a listing of the optional parameters;
  • – problem statistics, the iteration log and the final status as set by Monitoring Level.
Constraint: Monitoring File≥-1.
Monitoring Level i Default =4
This argument sets the amount of information detail that will be printed by the solver to the secondary output. The meaning of the levels is the same as with Print Level.
Constraint: 0≤Monitoring Level≤5.
Outer Iteration Limit i Default =100
The maximum number of the outer iterations to be performed by Algorithm 1. If Outer Iteration Limit=0, no iteration is performed, only quantities needed in the stopping criteria are computed and returned in RINFO. This might be useful in connection with Initial X=USER and Initial U=USER to check optimality of the given point. However, note that the rules for possible modifications of the starting point still apply, see U and UA. Setting the option too low might lead to IFAIL=22.
Constraint: Outer Iteration Limit≥0.
P Min r Default =ε
This controls pmin, the lowest possible penalty value p used for (standard) inequalities. In general, very small values of the penalty optional parameters cause ill-conditioning which might lead to numerical difficulties. On the other hand, very high pmin prevents the algorithm from reaching the requested accuracy on the feasibility. Under normal circumstances, the default value is recommended.
Constraint: ε≤P Min≤10-2.
Pmat Min r Default =ε
This is an equivalent of P Min for the minimal matrix penalty optional parameter Pmin. The same advice applies.
Constraint: ε≤Pmat Min≤10-2.
Preference a Default =SPEED
This option affects how contributions from the matrix constraints (17) to the system Hessian matrix are computed. The default option of Preference=SPEED should be suitable in most cases. However, dealing with matrix constraints of a very high dimension may cause noticable memory overhead and switching to Preference=MEMORY may be required.
Constraint: Preference=SPEED or MEMORY.
Presolve Block Detect a Default =YES
If Presolve Block Detect=YES, the matrix constraints are checked during preprocessoring to determine if they can be split into smaller independent ones, thus speeding up the solver.
Constraint: Presolve Block Detect=YES or NO.
Print File i Default =6
If i≥0, the unit number for the primary output of the solver. If Print File=-1, the primary output is completely turned off independently of other settings. The following information is output to the unit:
  • – a listing of optional parameters if set by Print Options;
  • – problem statistics, the iteration log and the final status from the solver as set by Print Level.
Constraint: Print File≥-1.
Print Level i Default =2
This argument defines how detailed information should be printed by the solver to the primary output.
i | Output
0 | No output from the solver
1 | Only the final status and the objective value
2 | Problem statistics, one line per outer iteration showing the progress of the solution, final status and statistics
3 | As level 2 but detailed output of the outer iterations is provided and brief overview of the inner iterations
4, 5 | As level 3 but details of the inner iterations are printed as well
Constraint: 0≤Print Level≤5.
Print Options a Default =YES
If Print Options=YES, a listing of optional parameters will be printed to the primary output.
Constraint: Print Options=YES or NO.
P Update Speed i Default =12
This option affects the rate at which the penalty optional parameters p,P are updated (Algorithm 1, step (iii)) and thus indirectly influences the overall number of outer iterations. Its value can be interpretted as the typical number of outer iterations needed to get from the initial penalty values p 0, P 0 half-way to the pmin and Pmin. Values smaller than 3 causes a very agressive penalty update strategy which might lead to the increased number of inner iterations and possibly to numerical difficulties. On the other hand, values higher than 15 produce a relatively conservative approach which leads to a higher number of the outer iterations.
If the solver encounters difficulties on your problem, a higher value might help. If your problem is working fine, setting a lower value might increase the speed.
Constraint: 1≤P Update Speed≤100.
Stats Time a Default =NO
This argument turns on timings of various parts of the algorithm to give a better overview of where most of the time is spent. This might be helpful for a choice of different solving approaches. It is possible to choose between CPU and wall clock time. Choice YES is equivalent to wall clock.
Constraint: Stats Time=YES, NO, CPU or WALL CLOCK.
Stop Criteria a Default =SOFT
If Stop Criteria=SOFT, the solver is allowed to stop prematurely with a suboptimal solution, IFAIL=50, if it predicts that a better estimate of the solution cannot be reached. This is the recommended option.
Constraint: Stop Criteria=SOFT or STRICT.
Stop Tolerance 1 r Default =max 10-6,ε
This option defines ε 1 used as a tolerance for the relative duality gap (10) and the relative precision (11), see Section 11.2.
Constraint: Stop Tolerance 1>ε.
Stop Tolerance 2 r Default =max 10-7,ε
This option sets the value ε 2 which is used for optimality (12) and complementarity (14) tests from KKT conditions or if DIMACS Measures=Check for all DIMACS error measures instead. See Section 11.2.
Constraint: Stop Tolerance 2>ε.
Stop Tolerance Feasibility r Default =max 10-7,ε
This argument places an acceptance limit on the feasibility of the solution (13), εfeas. See Section 11.2.
Constraint: Stop Tolerance Feasibility>ε.
Task a Default =MINIMIZE
This argument specifies the required direction of the optimization. If Task=FEASIBLE POINT, the objective function (if set) is ignored and the algorithm stops as soon as a feasible point is found with respect to the given tolerance. If no objective function was set, Task reverts to FEASIBLE POINT automatically.
Constraint: Task=MINIMIZE, MAXIMIZE or FEASIBLE POINT.
Transform Constraints a Default =AUTO
This argument controls how equality constraints are treated by the solver. If Transform Constraints=EQUALITIES, all equality constraints hk x=0 from (4) are treated as two inequalities hk x≤0 and hk x≥0, see Section 11.4. This is the default and the only option in this release for equality constrained problems.
Constraint: Transform Constraints=AUTO, NO or EQUALITIES.
U Update Restriction r Default =0.5
This defines the value μg giving the bounds on the updates of Lagrangian multipliers for (standard) inequalities between the outer iterations. Values close to 1 limit the changes of the multipliers and serve as a kind of smoothing, lower values allow more significant changes.
Based on numerical experience, big variation in the multipliers may lead to a large number of iterations in the subsequent step and might disturb the convergence due to ill-conditioning.
It might be worth experimenting with the value on your particular problem. Mid range values are recommended over the more extremal ones.
Constraint: ε<U Update Restriction<1.
Umat Update Restriction r Default =0.3
This is an equivalent of U Update Restriction for matrix constraints, denoted as μA in Section 11.1. The advice above applies equally.
Constraint: ε<Umat Update Restriction<1.
E04 Chapter Contents
E04 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


E04UCF/E04UCA : NAG Library, Mark 26

E04 Chapter Contents
E04 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

E04UCF/E04UCA

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.
Note: this routine uses optional parameters to define choices in the problem specification and in the details of the algorithm. If you wish to use default settings for all of the optional parameters, you need only read Sections 1 to 10 of this document. If, however, you wish to reset some or all of the settings please refer to Section 11 for a detailed description of the algorithm, to Section 12 for a detailed description of the specification of the optional parameters and to Section 13 for a detailed description of the monitoring information produced by the routine.

▸▿ Contents

1 Purpose
▸▿ 2 Specification
2.1 Specification for E04UCF
2.2 Specification for E04UCA
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
▸▿ 9 Further Comments
9.1 Description of the Printed Output
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results
▸▿ 11 Algorithmic Details
11.1 Overview
11.2 Solution of the Quadratic Programming Subproblem
11.3 The Merit Function
11.4 The Quasi-Newton Update
▸▿ 12 Optional Parameters
12.1 Description of the Optional Parameters
13 Description of Monitoring Information

1 Purpose

E04UCF/E04UCA is designed to minimize an arbitrary smooth function subject to constraints (which may include simple bounds on the variables, linear constraints and smooth nonlinear constraints) using a sequential quadratic programming (SQP) method. As many first derivatives as possible should be supplied by you; any unspecified derivatives are approximated by finite differences. It is not intended for large sparse problems.
E04UCF/E04UCA may also be used for unconstrained, bound-constrained and linearly constrained optimization.
E04UCF/E04UCA uses forward communication for evaluating the objective function, the nonlinear constraint functions, and any of their derivatives.
E04UCA is a version of E04UCF that has additional arguments in order to make it safe for use in multithreaded applications (see Section 5). The initialization routine E04WBF must have been called before calling E04UCA.

2 Specification

2.1 Specification for E04UCF

SUBROUTINE E04UCF ( N, NCLIN, NCNLN, LDA, LDCJ, LDR, A, BL, BU, CONFUN, OBJFUN, ITER, ISTATE, C, CJAC, CLAMDA, OBJF, OBJGRD, R, X, IWORK, LIWORK, WORK, LWORK, IUSER, RUSER, IFAIL)
INTEGER | N, NCLIN, NCNLN, LDA, LDCJ, LDR, ITER, ISTATE(N+NCLIN+NCNLN), IWORK(LIWORK), LIWORK, LWORK, IUSER(*), IFAIL
REAL (KIND=nag_wp) | A(LDA,*), BL(N+NCLIN+NCNLN), BU(N+NCLIN+NCNLN), C(max(1,NCNLN)), CJAC(LDCJ,*), CLAMDA(N+NCLIN+NCNLN), OBJF, OBJGRD(N), R(LDR,N), X(N), WORK(LWORK), RUSER(*)
EXTERNAL | CONFUN, OBJFUN

2.2 Specification for E04UCA

SUBROUTINE E04UCA ( N, NCLIN, NCNLN, LDA, LDCJ, LDR, A, BL, BU, CONFUN, OBJFUN, ITER, ISTATE, C, CJAC, CLAMDA, OBJF, OBJGRD, R, X, IWORK, LIWORK, WORK, LWORK, IUSER, RUSER, LWSAV, IWSAV, RWSAV, IFAIL)
INTEGER | N, NCLIN, NCNLN, LDA, LDCJ, LDR, ITER, ISTATE(N+NCLIN+NCNLN), IWORK(LIWORK), LIWORK, LWORK, IUSER(*), IWSAV(610), IFAIL
REAL (KIND=nag_wp) | A(LDA,*), BL(N+NCLIN+NCNLN), BU(N+NCLIN+NCNLN), C(max(1,NCNLN)), CJAC(LDCJ,*), CLAMDA(N+NCLIN+NCNLN), OBJF, OBJGRD(N), R(LDR,N), X(N), WORK(LWORK), RUSER(*), RWSAV(475)
LOGICAL | LWSAV(120)
EXTERNAL | CONFUN, OBJFUN
Before calling E04UCA, or either of the option setting routines E04UDA or E04UEA, E04WBF must be called. The specification for E04WBF is:
SUBROUTINE E04WBF ( RNAME, CWSAV, LCWSAV, LWSAV, LLWSAV, IWSAV, LIWSAV, RWSAV, LRWSAV, IFAIL)
INTEGER | LCWSAV, LLWSAV, IWSAV(LIWSAV), LIWSAV, LRWSAV, IFAIL
REAL (KIND=nag_wp) | RWSAV(LRWSAV)
LOGICAL | LWSAV(LLWSAV)
CHARACTER(*) | RNAME
CHARACTER(80) | CWSAV(LCWSAV)
E04WBF should be called with RNAME='E04UCA'. LCWSAV, LLWSAV, LIWSAV and LRWSAV, the declared lengths of CWSAV, LWSAV, IWSAV and RWSAV respectively, must satisfy:
  • LCWSAV≥1;
  • LLWSAV≥120;
  • LIWSAV≥610;
  • LRWSAV≥475.
The contents of the arrays CWSAV, LWSAV, IWSAV and RWSAV must not be altered between calling routines E04UCA, E04UDA, E04UEA and E04WBF.

3 Description

E04UCF/E04UCA is designed to solve the nonlinear programming problem – the minimization of a smooth nonlinear function subject to a set of constraints on the variables. The problem is assumed to be stated in the following form:
minimize x∈Rn F x  subject to  l≤ x AL x c x ≤u, (1)
where F x (the objective function) is a nonlinear function, AL is an nL by n constant matrix, and c x is an nN element vector of nonlinear constraint functions. (The matrix AL and the vector c x may be empty.) The objective function and the constraint functions are assumed to be smooth, i.e., at least twice-continuously differentiable. (The method of E04UCF/E04UCA will usually solve (1) if there are only isolated discontinuities away from the solution.)
Note that although the bounds on the variables could be included in the definition of the linear constraints, we prefer to distinguish between them for reasons of computational efficiency. For the same reason, the linear constraints should not be included in the definition of the nonlinear constraints. Upper and lower bounds are specified for all the variables and for all the constraints. An equality constraint can be specified by setting li=ui. If certain bounds are not present, the associated elements of l or u can be set to special values that will be treated as -∞ or +∞. (See the description of the optional parameter Infinite Bound Size.)
If there are no nonlinear constraints in (1) and F is linear or quadratic, then it will generally be more efficient to use one of E04MFF/E04MFA, E04NCF/E04NCA or E04NFF/E04NFA, or E04NKF/E04NKA if the problem is large and sparse. If the problem is large and sparse and does have nonlinear constraints, then E04UGF/E04UGA should be used, since E04UCF/E04UCA treats all matrices as dense.
You must supply an initial estimate of the solution to (1), together with subroutines that define F x, c x and as many first partial derivatives as possible; unspecified derivatives are approximated by finite differences.
The objective function is defined by OBJFUN, and the nonlinear constraints are defined by CONFUN. On every call, these subroutines must return appropriate values of the objective and nonlinear constraints. You should also provide the available partial derivatives. Any unspecified derivatives are approximated by finite differences; see Section 12.1 for a discussion of the optional parameter Derivative Level. Note that if there are any nonlinear constraints then the first call to CONFUN will precede the first call to OBJFUN.
For maximum reliability, it is preferable for you to provide all partial derivatives (see Chapter 8 of Gill et al. (1981), for a detailed discussion). If all gradients cannot be provided, it is similarly advisable to provide as many as possible. While developing OBJFUN and CONFUN, the optional parameter Verify should be used to check the calculation of any known gradients.
The method used by E04UCF/E04UCA is described in detail in Section 11.
E04UFF/E04UFA is an alternative routine which uses exactly the same method, but uses reverse communication for evaluating the objective and constraint functions.

4 References

Dennis J E Jr and Moré J J (1977) Quasi-Newton methods, motivation and theory SIAM Rev. 19 46–89
Dennis J E Jr and Schnabel R B (1981) A new derivation of symmetric positive-definite secant updates nonlinear programming (eds O L Mangasarian, R R Meyer and S M Robinson) 4 167–199 Academic Press
Dennis J E Jr and Schnabel R B (1983) Numerical Methods for Unconstrained Optimization and Nonlinear Equations Prentice–Hall
Fletcher R (1987) Practical Methods of Optimization (2nd Edition) Wiley
Gill P E, Hammarling S, Murray W, Saunders M A and Wright M H (1986) Users' guide for LSSOL (Version 1.0) Report SOL 86-1 Department of Operations Research, Stanford University
Gill P E, Murray W, Saunders M A and Wright M H (1984a) Procedures for optimization problems with a mixture of bounds and general linear constraints ACM Trans. Math. Software 10 282–298
Gill P E, Murray W, Saunders M A and Wright M H (1984b) Users' guide for SOL/QPSOL version 3.2 Report SOL 84–5 Department of Operations Research, Stanford University
Gill P E, Murray W, Saunders M A and Wright M H (1986a) Some theoretical properties of an augmented Lagrangian merit function Report SOL 86–6R Department of Operations Research, Stanford University
Gill P E, Murray W, Saunders M A and Wright M H (1986b) Users' guide for NPSOL (Version 4.0): a Fortran package for nonlinear programming Report SOL 86-2 Department of Operations Research, Stanford University
Gill P E, Murray W and Wright M H (1981) Practical Optimization Academic Press
Hock W and Schittkowski K (1981) Test Examples for Nonlinear Programming Codes. Lecture Notes in Economics and Mathematical Systems 187 Springer–Verlag
Powell M J D (1974) Introduction to constrained optimization Numerical Methods for Constrained Optimization (eds P E Gill and W Murray) 1–28 Academic Press
Powell M J D (1983) Variable metric methods in constrained optimization Mathematical Programming: the State of the Art (eds A Bachem, M Grötschel and B Korte) 288–311 Springer–Verlag

5 Arguments

1:   N – INTEGERInput
On entry: n, the number of variables.
Constraint: N>0.
2:   NCLIN – INTEGERInput
On entry: nL, the number of general linear constraints.
Constraint: NCLIN≥0.
3:   NCNLN – INTEGERInput
On entry: nN, the number of nonlinear constraints.
Constraint: NCNLN≥0.
4:   LDA – INTEGERInput
On entry: the first dimension of the array A as declared in the (sub)program from which E04UCF/E04UCA is called.
Constraint: LDA≥max 1,NCLIN.
5:   LDCJ – INTEGERInput
On entry: the first dimension of the array CJAC as declared in the (sub)program from which E04UCF/E04UCA is called.
Constraint: LDCJ≥max 1,NCNLN.
6:   LDR – INTEGERInput
On entry: the first dimension of the array R as declared in the (sub)program from which E04UCF/E04UCA is called.
Constraint: LDR≥N.
7:   A LDA* – REAL (KIND=nag_wp) arrayInput
Note: the second dimension of the array A must be at least N if NCLIN>0, and at least 1 otherwise.
On entry: the ith row of A contains the ith row of the matrix AL of general linear constraints in (1). That is, the ith row contains the coefficients of the ith general linear constraint, for i=1,2,…,NCLIN.
If NCLIN=0, the array A is not referenced.
8:   BL N+NCLIN+NCNLN – REAL (KIND=nag_wp) arrayInput
9:   BU N+NCLIN+NCNLN – REAL (KIND=nag_wp) arrayInput
On entry: BL must contain the lower bounds and BU the upper bounds for all the constraints in the following order. The first n elements of each array must contain the bounds on the variables, the next nL elements the bounds for the general linear constraints (if any) and the next nN elements the bounds for the general nonlinear constraints (if any). To specify a nonexistent lower bound (i.e., lj=-∞), set BL j≤-bigbnd, and to specify a nonexistent upper bound (i.e., uj=+∞), set BU j≥bigbnd; the default value of bigbnd is 1020, but this may be changed by the optional parameter Infinite Bound Size. To specify the jth constraint as an equality, set BL j=BU j=β, say, where β<bigbnd.
Constraints:
  • BL j≤BU j, for j=1,2,…,N+NCLIN+NCNLN;
  • if BL j=BU j=β, β<bigbnd.
10:   CONFUN – SUBROUTINE, supplied by the NAG Library or the user.External Procedure
CONFUN must calculate the vector c x of nonlinear constraint functions and (optionally) its Jacobian (= ∂c ∂x ) for a specified n-element vector x. If there are no nonlinear constraints (i.e., NCNLN=0), CONFUN will never be called by E04UCF/E04UCA and CONFUN may be the dummy routine E04UDM. (E04UDM is included in the NAG Library.) If there are nonlinear constraints, the first call to CONFUN will occur before the first call to OBJFUN.
The specification of CONFUN is:
SUBROUTINE CONFUN ( MODE, NCNLN, N, LDCJ, NEEDC, X, C, CJAC, NSTATE, IUSER, RUSER)
INTEGER | MODE, NCNLN, N, LDCJ, NEEDC(NCNLN), NSTATE, IUSER(*)
REAL (KIND=nag_wp) | X(N), C(NCNLN), CJAC(LDCJ,N), RUSER(*)
1:   MODE – INTEGERInput/Output
On entry: indicates which values must be assigned during each call of CONFUN. Only the following values need be assigned, for each value of i such that NEEDC i>0:
MODE=0
C i.
MODE=1
All available elements in the ith row of CJAC.
MODE=2
C i and all available elements in the ith row of CJAC.
On exit: may be set to a negative value if you wish to terminate the solution to the current problem. In this case E04UCF/E04UCA will terminate with IFAIL set to MODE.
2:   NCNLN – INTEGERInput
On entry: nN, the number of nonlinear constraints.
3:   N – INTEGERInput
On entry: n, the number of variables.
4:   LDCJ – INTEGERInput
On entry: the first dimension of the array CJAC as declared in the (sub)program from which E04UCF/E04UCA is called.
5:   NEEDC NCNLN – INTEGER arrayInput
On entry: the indices of the elements of C and/or CJAC that must be evaluated by CONFUN. If NEEDC i>0, the ith element of C and/or the available elements of the ith row of CJAC (see argument MODE) must be evaluated at x.
6:   X N – REAL (KIND=nag_wp) arrayInput
On entry: x, the vector of variables at which the constraint functions and/or the available elements of the constraint Jacobian are to be evaluated.
7:   C NCNLN – REAL (KIND=nag_wp) arrayOutput
On exit: if NEEDC i>0 and MODE=0 or 2, C i must contain the value of the ith constraint at x. The remaining elements of C, corresponding to the non-positive elements of NEEDC, are ignored.
8:   CJAC LDCJN – REAL (KIND=nag_wp) arrayInput/Output
On entry: unless Derivative Level=2 or 3, the elements of CJAC are set to special values which enable E04UCF/E04UCA to detect whether they are changed by CONFUN.
On exit: if NEEDC i>0 and MODE=1 or 2, the ith row of CJAC must contain the available elements of the vector ∇ci given by
∇ci= ∂ci ∂x 1 , ∂ci ∂x 2 ,…, ∂ci ∂xn T,
where ∂ci ∂xj is the partial derivative of the ith constraint with respect to the jth variable, evaluated at the point x. See also the argument NSTATE. The remaining rows of CJAC, corresponding to non-positive elements of NEEDC, are ignored.
If all elements of the constraint Jacobian are known (i.e., Derivative Level=2 or 3), any constant elements may be assigned to CJAC one time only at the start of the optimization. An element of CJAC that is not subsequently assigned in CONFUN will retain its initial value throughout. Constant elements may be loaded into CJAC either before the call to E04UCF/E04UCA or during the first call to CONFUN (signalled by the value NSTATE=1). The ability to preload constants is useful when many Jacobian elements are identically zero, in which case CJAC may be initialized to zero and nonzero elements may be reset by CONFUN.
Note that constant nonzero elements do affect the values of the constraints. Thus, if CJAC ij is set to a constant value, it need not be reset in subsequent calls to CONFUN, but the value CJAC ij×X j must nonetheless be added to C i. For example, if CJAC 11=2 and CJAC 12=-5 then the term 2×X 1-5×X 2 must be included in the definition of C 1.
It must be emphasized that, if Derivative Level=0 or 1, unassigned elements of CJAC are not treated as constant; they are estimated by finite differences, at nontrivial expense. If you do not supply a value for the optional parameter Difference Interval, an interval for each element of x is computed automatically at the start of the optimization. The automatic procedure can usually identify constant elements of CJAC, which are then computed once only by finite differences.
9:   NSTATE – INTEGERInput
On entry: if NSTATE=1 then E04UCF/E04UCA is calling CONFUN for the first time. This argument setting allows you to save computation time if certain data must be read or calculated only once.
10:   IUSER* – INTEGER arrayUser Workspace
11:   RUSER* – REAL (KIND=nag_wp) arrayUser Workspace
CONFUN is called with the arguments IUSER and RUSER as supplied to E04UCF/E04UCA. You are free to use the arrays IUSER and RUSER to supply information to CONFUN as an alternative to using COMMON global variables.
CONFUN must either be a module subprogram USEd by, or declared as EXTERNAL in, the (sub)program from which E04UCF/E04UCA is called. Arguments denoted as Input must not be changed by this procedure.
CONFUN should be tested separately before being used in conjunction with E04UCF/E04UCA. See also the description of the optional parameter Verify.
11:   OBJFUN – SUBROUTINE, supplied by the user.External Procedure
OBJFUN must calculate the objective function F x and (optionally) its gradient g x = ∂F ∂x for a specified n-vector x.
The specification of OBJFUN is:
SUBROUTINE OBJFUN ( MODE, N, X, OBJF, OBJGRD, NSTATE, IUSER, RUSER)
INTEGER | MODE, N, NSTATE, IUSER(*)
REAL (KIND=nag_wp) | X(N), OBJF, OBJGRD(N), RUSER(*)
1:   MODE – INTEGERInput/Output
On entry: indicates which values must be assigned during each call of OBJFUN. Only the following values need be assigned:
MODE=0
OBJF.
MODE=1
All available elements of OBJGRD.
MODE=2
OBJF and all available elements of OBJGRD.
On exit: may be set to a negative value if you wish to terminate the solution to the current problem. In this case E04UCF/E04UCA will terminate with IFAIL set to MODE.
2:   N – INTEGERInput
On entry: n, the number of variables.
3:   X N – REAL (KIND=nag_wp) arrayInput
On entry: x, the vector of variables at which the objective function and/or all available elements of its gradient are to be evaluated.
4:   OBJF – REAL (KIND=nag_wp)Output
On exit: if MODE=0 or 2, OBJF must be set to the value of the objective function at x.
5:   OBJGRD N – REAL (KIND=nag_wp) arrayInput/Output
On entry: the elements of OBJGRD are set to special values which enable E04UCF/E04UCA to detect whether they are changed by OBJFUN.
On exit: if MODE=1 or 2, OBJGRD must return the available elements of the gradient evaluated at x.
6:   NSTATE – INTEGERInput
On entry: if NSTATE=1 then E04UCF/E04UCA is calling OBJFUN for the first time. This argument setting allows you to save computation time if certain data must be read or calculated only once.
7:   IUSER* – INTEGER arrayUser Workspace
8:   RUSER* – REAL (KIND=nag_wp) arrayUser Workspace
OBJFUN is called with the arguments IUSER and RUSER as supplied to E04UCF/E04UCA. You are free to use the arrays IUSER and RUSER to supply information to OBJFUN as an alternative to using COMMON global variables.
OBJFUN must either be a module subprogram USEd by, or declared as EXTERNAL in, the (sub)program from which E04UCF/E04UCA is called. Arguments denoted as Input must not be changed by this procedure.
OBJFUN should be tested separately before being used in conjunction with E04UCF/E04UCA. See also the description of the optional parameter Verify.
12:   ITER – INTEGEROutput
On exit: the number of major iterations performed.
13:   ISTATE N+NCLIN+NCNLN – INTEGER arrayInput/Output
On entry: need not be set if the (default) optional parameter Cold Start is used.
If the optional parameter Warm Start has been chosen, the elements of ISTATE corresponding to the bounds and linear constraints define the initial working set for the procedure that finds a feasible point for the linear constraints and bounds. The active set at the conclusion of this procedure and the elements of ISTATE corresponding to nonlinear constraints then define the initial working set for the first QP subproblem. More precisely, the first n elements of ISTATE refer to the upper and lower bounds on the variables, the next nL elements refer to the upper and lower bounds on AL x, and the next nN elements refer to the upper and lower bounds on c x. Possible values for ISTATE j are as follows:
ISTATE j | Meaning
0 | The corresponding constraint is not in the initial QP working set.
1 | This inequality constraint should be in the working set at its lower bound.
2 | This inequality constraint should be in the working set at its upper bound.
3 | This equality constraint should be in the initial working set. This value must not be specified unless BL j=BU j.
The values -2, -1 and 4 are also acceptable but will be modified by the routine. If E04UCF/E04UCA has been called previously with the same values of N, NCLIN and NCNLN, ISTATE already contains satisfactory information. The routine also adjusts (if necessary) the values supplied in X to be consistent with ISTATE.
Constraint: -2≤ISTATE j≤4, for j=1,2,…,N+NCLIN+NCNLN.
On exit: the status of the constraints in the QP working set at the point returned in X. The significance of each possible value of ISTATE j is as follows:
ISTATE j | Meaning
-2 | This constraint violates its lower bound by more than the appropriate feasibility tolerance (see the optional parameters Linear Feasibility Tolerance and Nonlinear Feasibility Tolerance). This value can occur only when no feasible point can be found for a QP subproblem.
-1 | This constraint violates its upper bound by more than the appropriate feasibility tolerance (see the optional parameters Linear Feasibility Tolerance and Nonlinear Feasibility Tolerance). This value can occur only when no feasible point can be found for a QP subproblem.
-0 | The constraint is satisfied to within the feasibility tolerance, but is not in the QP working set.
-1 | This inequality constraint is included in the QP working set at its lower bound.
-2 | This inequality constraint is included in the QP working set at its upper bound.
-3 | This constraint is included in the QP working set as an equality. This value of ISTATE can occur only when BL j=BU j.
14:   C max 1,NCNLN – REAL (KIND=nag_wp) arrayOutput
On exit: if NCNLN>0, C i contains the value of the ith nonlinear constraint function ci at the final iterate, for i=1,2,…,NCNLN.
If NCNLN=0, the array C is not referenced.
15:   CJAC LDCJ* – REAL (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array CJAC must be at least N if NCNLN>0, and at least 1 otherwise.
On entry: in general, CJAC need not be initialized before the call to E04UCF/E04UCA. However, if Derivative Level=2 or 3, you may optionally set the constant elements of CJAC (see argument NSTATE in the description of CONFUN). Such constant elements need not be re-assigned on subsequent calls to CONFUN.
On exit: if NCNLN>0, CJAC contains the Jacobian matrix of the nonlinear constraint functions at the final iterate, i.e., CJAC ij contains the partial derivative of the ith constraint function with respect to the jth variable, for i=1,2,…,NCNLN and j=1,2,…,N. (See the discussion of argument CJAC under CONFUN.)
If NCNLN=0, the array CJAC is not referenced.
16:   CLAMDA N+NCLIN+NCNLN – REAL (KIND=nag_wp) arrayInput/Output
On entry: need not be set if the (default) optional parameter Cold Start is used.
If the optional parameter Warm Start has been chosen, CLAMDA j must contain a multiplier estimate for each nonlinear constraint with a sign that matches the status of the constraint specified by the ISTATE array, for j=N+NCLIN+1,…,N+NCLIN+NCNLN. The remaining elements need not be set. Note that if the jth constraint is defined as ‘inactive’ by the initial value of ISTATE array (i.e., ISTATE j=0), CLAMDA j should be zero; if the jth constraint is an inequality active at its lower bound (i.e., ISTATE j=1), CLAMDA j should be non-negative; if the jth constraint is an inequality active at its upper bound (i.e., ISTATE j=2), CLAMDA j should be non-positive. If necessary, the routine will modify CLAMDA to match these rules.
On exit: the values of the QP multipliers from the last QP subproblem. CLAMDA j should be non-negative if ISTATE j=1 and non-positive if ISTATE j=2.
17:   OBJF – REAL (KIND=nag_wp)Output
On exit: the value of the objective function at the final iterate.
18:   OBJGRD N – REAL (KIND=nag_wp) arrayOutput
On exit: the gradient of the objective function at the final iterate (or its finite difference approximation).
19:   R LDRN – REAL (KIND=nag_wp) arrayInput/Output
On entry: need not be initialized if the (default) optional parameter Cold Start is used.
If the optional parameter Warm Start has been chosen, R must contain the upper triangular Cholesky factor R of the initial approximation of the Hessian of the Lagrangian function, with the variables in the natural order. Elements not in the upper triangular part of R are assumed to be zero and need not be assigned.
On exit: if Hessian=NO, R contains the upper triangular Cholesky factor R of QT H~Q, an estimate of the transformed and reordered Hessian of the Lagrangian at x (see (6) in Section 11.1). If Hessian=YES, R contains the upper triangular Cholesky factor R of H, the approximate (untransformed) Hessian of the Lagrangian, with the variables in the natural order.
20:   X N – REAL (KIND=nag_wp) arrayInput/Output
On entry: an initial estimate of the solution.
On exit: the final estimate of the solution.
21:   IWORK LIWORK – INTEGER arrayWorkspace
22:   LIWORK – INTEGERInput
On entry: the dimension of the array IWORK as declared in the (sub)program from which E04UCF/E04UCA is called.
Constraint: LIWORK≥3×N+NCLIN+2×NCNLN.
23:   WORK LWORK – REAL (KIND=nag_wp) arrayWorkspace
24:   LWORK – INTEGERInput
On entry: the dimension of the array WORK as declared in the (sub)program from which E04UCF/E04UCA is called.
Constraints:
  • if NCNLN=0 and NCLIN=0, LWORK≥20×N;
  • if NCNLN=0 and NCLIN>0, LWORK≥2×N 2+20×N+11×NCLIN;
  • if NCNLN>0 and NCLIN≥0, LWORK≥2×N 2+N×NCLIN+2×N× NCNLN+20×N+11×NCLIN+21×NCNLN.
The amounts of workspace provided and required are (by default) output on the current advisory message unit (as defined by X04ABF). As an alternative to computing LIWORK and LWORK from the formulas given above, you may prefer to obtain appropriate values from the output of a preliminary run with LIWORK and LWORK set to 1. (E04UCF/E04UCA will then terminate with IFAIL=9.)
25:   IUSER* – INTEGER arrayUser Workspace
26:   RUSER* – REAL (KIND=nag_wp) arrayUser Workspace
IUSER and RUSER are not used by E04UCF/E04UCA, but are passed directly to CONFUN and OBJFUN and may be used to pass information to these routines as an alternative to using COMMON global variables.
27:   IFAIL – INTEGERInput/Output
Note: for E04UCA, IFAIL does not occur in this position in the argument list. See the additional arguments described below.
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, because for this routine the values of the output arguments may be useful even if IFAIL≠0 on exit, the recommended value is -1. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).
E04UCF/E04UCA returns with IFAIL=0 if the iterates have converged to a point x that satisfies the first-order Kuhn–Tucker (see Section 11.1) conditions to the accuracy requested by the optional parameter Optimality Tolerance (default value=εR 0.8, where εr is the value of the optional parameter Function Precision (default value=ε 0.9, where ε is the machine precision)), i.e., the projected gradient and active constraint residuals are negligible at x.
You should check whether the following four conditions are satisfied:
(i) | the final value of Norm Gz (see Section 9.1) is significantly less than that at the starting point;
(ii) | during the final major iterations, the values of Step and Mnr (see Section 9.1) are both one;
(iii) | the last few values of both Norm Gz and Violtn (see Section 9.1) become small at a fast linear rate; and
(iv) | Cond Hz (see Section 9.1) is small.
If all these conditions hold, x is almost certainly a local minimum of (1).
Note: the following are additional arguments for specific use with E04UCA. Users of E04UCF therefore need not read the remainder of this description.
27:   LWSAV 120 – LOGICAL arrayCommunication Array
28:   IWSAV 610 – INTEGER arrayCommunication Array
29:   RWSAV 475 – REAL (KIND=nag_wp) arrayCommunication Array
The arrays LWSAV, IWSAV and RWSAV must not be altered between calls to any of the routines E04UCA, E04UDA or E04UEA.
30:   IFAIL – INTEGERInput/Output
Note: see the argument description for IFAIL above.

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Note: E04UCF/E04UCA may return useful information for one or more of the following detected errors or warnings.
Errors or warnings detected by the routine:
IFAIL<0
A negative value of IFAIL indicates an exit from E04UCF/E04UCA because you set MODE<0 in OBJFUN or CONFUN. The value of IFAIL will be the same as your setting of MODE.
IFAIL=1
The final iterate x satisfies the first-order Kuhn–Tucker conditions (see Section 11.1) to the accuracy requested, but the sequence of iterates has not yet converged. E04UCF/E04UCA was terminated because no further improvement could be made in the merit function (see Section 9.1).
This value of IFAIL may occur in several circumstances. The most common situation is that you ask for a solution with accuracy that is not attainable with the given precision of the problem (as specified by the optional parameter Function Precision (default value=ε 0.9, where ε is the machine precision)). This condition will also occur if, by chance, an iterate is an ‘exact’ Kuhn–Tucker point, but the change in the variables was significant at the previous iteration. (This situation often happens when minimizing very simple functions, such as quadratics.)
If the four conditions listed in Section 5 for IFAIL=0 are satisfied, x is likely to be a solution of (1) even if IFAIL=1.
IFAIL=2
E04UCF/E04UCA has terminated without finding a feasible point for the linear constraints and bounds, which means that either no feasible point exists for the given value of the optional parameter Linear Feasibility Tolerance (default value=ε, where ε is the machine precision), or no feasible point could be found in the number of iterations specified by the optional parameter Minor Iteration Limit (default value=max 50,3 n+nL+nN). You should check that there are no constraint redundancies. If the data for the constraints are accurate only to an absolute precision σ, you should ensure that the value of the optional parameter Linear Feasibility Tolerance is greater than σ. For example, if all elements of AL are of order unity and are accurate to only three decimal places, Linear Feasibility Tolerance should be at least 10-3.
IFAIL=3
No feasible point could be found for the nonlinear constraints. The problem may have no feasible solution. This means that there has been a sequence of QP subproblems for which no feasible point could be found (indicated by I at the end of each line of intermediate printout produced by the major iterations; see Section 9.1). This behaviour will occur if there is no feasible point for the nonlinear constraints. (However, there is no general test that can determine whether a feasible point exists for a set of nonlinear constraints.) If the infeasible subproblems occur from the very first major iteration, it is highly likely that no feasible point exists. If infeasibilities occur when earlier subproblems have been feasible, small constraint inconsistencies may be present. You should check the validity of constraints with negative values of ISTATE. If you are convinced that a feasible point does exist, E04UCF/E04UCA should be restarted at a different starting point.
IFAIL=4
The limiting number of iterations (as determined by the optional parameter Major Iteration Limit (default value=max 50,3 n+nL+10 nN)) has been reached.
If the algorithm appears to be making satisfactory progress, then Major Iteration Limit may be too small. If so, either increase its value and rerun E04UCF/E04UCA or, alternatively, rerun E04UCF/E04UCA using the optional parameter Warm Start. If the algorithm seems to be making little or no progress however, then you should check for incorrect gradients or ill-conditioning as described under IFAIL=6.
Note that ill-conditioning in the working set is sometimes resolved automatically by the algorithm, in which case performing additional iterations may be helpful. However, ill-conditioning in the Hessian approximation tends to persist once it has begun, so that allowing additional iterations without altering R is usually inadvisable. If the quasi-Newton update of the Hessian approximation was reset during the latter major iterations (i.e., an R occurs at the end of each line of intermediate printout; see Section 9.1), it may be worthwhile to try a Warm Start at the final point as suggested above.
IFAIL=5
Not used by this routine.
IFAIL=6
x does not satisfy the first-order Kuhn–Tucker conditions (see Section 11.1) and no improved point for the merit function (see Section 9.1) could be found during the final linesearch.
This sometimes occurs because an overly stringent accuracy has been requested, i.e., the value of the optional parameter Optimality Tolerance (default value=εR 0.8, where εr is the value of the optional parameter Function Precision (default value=ε 0.9, where ε is the machine precision)) is too small. In this case you should apply the four tests outlined in the description of the argument IFAIL to determine whether or not the final solution is acceptable (see Gill et al. (1981), for a discussion of the attainable accuracy).
If many iterations have occurred in which essentially no progress has been made and E04UCF/E04UCA has failed completely to move from the initial point then user-supplied subroutines OBJFUN and/or CONFUN may be incorrect. You should refer to comments under IFAIL=7 and check the gradients using the optional parameter Verify (default value=0). Unfortunately, there may be small errors in the objective and constraint gradients that cannot be detected by the verification process. Finite difference approximations to first derivatives are catastrophically affected by even small inaccuracies. An indication of this situation is a dramatic alteration in the iterates if the finite difference interval is altered. One might also suspect this type of error if a switch is made to central differences even when Norm Gz and Violtn (see Section 9.1) are large.
Another possibility is that the search direction has become inaccurate because of ill-conditioning in the Hessian approximation or the matrix of constraints in the working set; either form of ill-conditioning tends to be reflected in large values of Mnr (the number of iterations required to solve each QP subproblem; see Section 9.1).
If the condition estimate of the projected Hessian (Cond Hz; see Section 9.1) is extremely large, it may be worthwhile rerunning E04UCF/E04UCA from the final point with the optional parameter Warm Start. In this situation, ISTATE and CLAMDA should be left unaltered and R should be reset to the identity matrix.
If the matrix of constraints in the working set is ill-conditioned (i.e., Cond T is extremely large; see Section 13), it may be helpful to run E04UCF/E04UCA with a relaxed value of the Feasibility Tolerance (default value=ε, where ε is the machine precision). (Constraint dependencies are often indicated by wide variations in size in the diagonal elements of the matrix T, whose diagonals will be printed if Major Print Level≥30).
IFAIL=7
The user-supplied derivatives of the objective function and/or nonlinear constraints appear to be incorrect.
Large errors were found in the derivatives of the objective function and/or nonlinear constraints. This value of IFAIL will occur if the verification process indicated that at least one gradient or Jacobian element had no correct figures. You should refer to the printed output to determine which elements are suspected to be in error.
As a first-step, you should check that the code for the objective and constraint values is correct – for example, by computing the function at a point where the correct value is known. However, care should be taken that the chosen point fully tests the evaluation of the function. It is remarkable how often the values x=0 or x=1 are used to test function evaluation procedures, and how often the special properties of these numbers make the test meaningless.
Special care should be used in this test if computation of the objective function involves subsidiary data communicated in COMMON storage. Although the first evaluation of the function may be correct, subsequent calculations may be in error because some of the subsidiary data has accidentally been overwritten.
Gradient checking will be ineffective if the objective function uses information computed by the constraints, since they are not necessarily computed before each function evaluation.
Errors in programming the function may be quite subtle in that the function value is ‘almost’ correct. For example, the function may not be accurate to full precision because of the inaccurate calculation of a subsidiary quantity, or the limited accuracy of data upon which the function depends. A common error on machines where numerical calculations are usually performed in double precision is to include even one single precision constant in the calculation of the function; since some compilers do not convert such constants to double precision, half the correct figures may be lost by such a seemingly trivial error.
IFAIL=8
Not used by this routine.
IFAIL=9
An input argument is invalid.
Overflow
If the printed output before the overflow error contains a warning about serious ill-conditioning in the working set when adding the jth constraint, it may be possible to avoid the difficulty by increasing the magnitude of the optional parameter Linear Feasibility Tolerance and/or the optional parameter Nonlinear Feasibility Tolerance and rerunning the program. If the message recurs even after this change then the offending linearly dependent constraint (with index ‘j’) must be removed from the problem. If overflow occurs in one of the user-supplied subroutines (e.g., if the nonlinear functions involve exponentials or singularities), it may help to specify tighter bounds for some of the variables (i.e., reduce the gap between the appropriate lj and uj).
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

If IFAIL=0 on exit, then the vector returned in the array X is an estimate of the solution to an accuracy of approximately Optimality Tolerance (default value=ε 0.8, where ε is the machine precision).

8 Parallelism and Performance

E04UCF/E04UCA is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
E04UCF/E04UCA makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

9.1 Description of the Printed Output

This section describes the intermediate printout and final printout produced by E04UCF/E04UCA. The intermediate printout is a subset of the monitoring information produced by the routine at every iteration (see Section 13). You can control the level of printed output (see the description of the optional parameter Major Print Level). Note that the intermediate printout and final printout are produced only if Major Print Level≥10 (the default for E04UCF, by default no output is produced by E04UCA).
The following line of summary output (<80 characters) is produced at every major iteration. In all cases, the values of the quantities printed are those in effect on completion of the given iteration.
Maj | is the major iteration count.
Mnr is the number of minor iterations required by the feasibility and optimality phases of the QP subproblem. Generally, Mnr will be 1 in the later iterations, since theoretical analysis predicts that the correct active set will be identified near the solution (see Section 11).
Note that Mnr may be greater than the optional parameter Minor Iteration Limit if some iterations are required for the feasibility phase.
Step | is the step αk taken along the computed search direction. On reasonably well-behaved problems, the unit step (i.e., αk=1) will be taken as the solution is approached.
Merit Function is the value of the augmented Lagrangian merit function (12) at the current iterate. This function will decrease at each iteration unless it was necessary to increase the penalty parameters (see Section 11.3). As the solution is approached, Merit Function will converge to the value of the objective function at the solution.
If the QP subproblem does not have a feasible point (signified by I at the end of the current output line) then the merit function is a large multiple of the constraint violations, weighted by the penalty parameters. During a sequence of major iterations with infeasible subproblems, the sequence of Merit Function values will decrease monotonically until either a feasible subproblem is obtained or E04UCF/E04UCA terminates with IFAIL=3 (no feasible point could be found for the nonlinear constraints).
If there are no nonlinear constraints present (i.e., NCNLN=0) then this entry contains Objective, the value of the objective function F x. The objective function will decrease monotonically to its optimal value when there are no nonlinear constraints.
Norm Gz | is ZT gFR, the Euclidean norm of the projected gradient (see Section 11.2). Norm Gz will be approximately zero in the neighbourhood of a solution.
Violtn | is the Euclidean norm of the residuals of constraints that are violated or in the predicted active set (not printed if NCNLN is zero). Violtn will be approximately zero in the neighbourhood of a solution.
Cond Hz | is a lower bound on the condition number of the projected Hessian approximation HZ ( HZ = ZT HFR Z = RZT RZ ; see (6)). The larger this number, the more difficult the problem.
M | is printed if the quasi-Newton update has been modified to ensure that the Hessian approximation is positive definite (see Section 11.4).
I | is printed if the QP subproblem has no feasible point.
C | is printed if central differences have been used to compute the unspecified objective and constraint gradients. If the value of Step is zero then the switch to central differences was made because no lower point could be found in the linesearch. (In this case, the QP subproblem is resolved with the central difference gradient and Jacobian.) If the value of Step is nonzero then central differences were computed because Norm Gz and Violtn imply that x is close to a Kuhn–Tucker point (see Section 11.1 in E04UFF/E04UFA).
L | is printed if the linesearch has produced a relative change in x greater than the value defined by the optional parameter Step Limit. If this output occurs frequently during later iterations of the run, optional parameter Step Limit should be set to a larger value.
R | is printed if the approximate Hessian has been refactorized. If the diagonal condition estimator of R indicates that the approximate Hessian is badly conditioned then the approximate Hessian is refactorized using column interchanges. If necessary, R is modified so that its diagonal condition estimator is bounded.
The final printout includes a listing of the status of every variable and constraint. The following describes the printout for each variable. A full stop (.) is printed for any numerical value that is zero.
Varbl | gives the name (V) and index j, for j=1,2,…,n, of the variable.
State gives the state of the variable (FR if neither bound is in the working set, EQ if a fixed variable, LL if on its lower bound, UL if on its upper bound, TF if temporarily fixed at its current value). If Value lies outside the upper or lower bounds by more than the Feasibility Tolerance, State will be ++ or -- respectively. (The latter situation can occur only when there is no feasible point for the bounds and linear constraints.)
A key is sometimes printed before State.
A | Alternative optimum possible. The variable is active at one of its bounds, but its Lagrange multiplier is essentially zero. This means that if the variable were allowed to start moving away from its bound then there would be no change to the objective function. The values of the other free variables might change, giving a genuine alternative solution. However, if there are any degenerate variables (labelled D), the actual change might prove to be zero, since one of them could encounter a bound immediately. In either case the values of the Lagrange multipliers might also change.
D | Degenerate. The variable is free, but it is equal to (or very close to) one of its bounds.
I | Infeasible. The variable is currently violating one of its bounds by more than the Feasibility Tolerance.
Value | is the value of the variable at the final iteration.
Lower Bound | is the lower bound specified for the variable. None indicates that BL j≤-bigbnd.
Upper Bound | is the upper bound specified for the variable. None indicates that BU j≥bigbnd.
Lagr Mult | is the Lagrange multiplier for the associated bound. This will be zero if State is FR unless BL j≤-bigbnd and BU j≥bigbnd, in which case the entry will be blank. If x is optimal, the multiplier should be non-negative if State is LL and non-positive if State is UL.
Slack | is the difference between the variable Value and the nearer of its (finite) bounds BL j and BU j. A blank entry indicates that the associated variable is not bounded (i.e., BL j≤-bigbnd and BU j≥bigbnd).
The meaning of the printout for linear and nonlinear constraints is the same as that given above for variables, with ‘variable’ replaced by ‘constraint’, BL j and BU j are replaced by BL n+j and BU n+j respectively, and with the following changes in the heading:
L Con | gives the name (L) and index j, for j=1,2,…,nL, of the linear constraint.
N Con | gives the name (N) and index (j-nL), for j=nL+1,…,nL+nN, of the nonlinear constraint.
Note that movement off a constraint (as opposed to a variable moving away from its bound) can be interpreted as allowing the entry in the Slack column to become positive.
Numerical values are output with a fixed number of digits; they are not guaranteed to be accurate to this precision.

10 Example

This is based on Problem 71 in Hock and Schittkowski (1981) and involves the minimization of the nonlinear function
F x=x 1x 4 x 1+x 2+x 3+x 3
subject to the bounds
1≤x 1≤ 5 1≤x 2≤ 5 1≤x 3≤ 5 1≤x 4≤ 5
to the general linear constraint
x 1+x 2+x 3+x 4≤20,
and to the nonlinear constraints
x 12+x 22+x 32+x 42≤ 40, x 1x 2x 3x 4≥ 25.
The initial point, which is infeasible, is
x 0=1,5,5,1 T,
and F x 0=16.
The optimal solution (to five figures) is
x*=1.0,4.7430,3.8211,1.3794 T,
and F x*=17.014. One bound constraint and both nonlinear constraints are active at the solution.
The document for E04UDF/E04UDA includes an example program to solve the same problem using some of the optional parameters described in Section 12.

10.1 Program Text

Note: the following programs illustrate the use of E04UCF and E04UCA.

Program Text (e04ucfe.f90)

Program Text (e04ucae.f90)

10.2 Program Data

Program Data (e04ucfe.d)

Program Data (e04ucae.d)

10.3 Program Results

Program Results (e04ucfe.r)

Program Results (e04ucae.r)

Note: the remainder of this document is intended for more advanced users. Section 11 contains a detailed description of the algorithm which may be needed in order to understand Sections 12 and 13. Section 12 describes the optional parameters which may be set by calls to E04UDF/E04UDA and/or E04UEF/E04UEA. Section 13 describes the quantities which can be requested to monitor the course of the computation.

11 Algorithmic Details

This section contains a detailed description of the method used by E04UCF/E04UCA.

11.1 Overview

E04UCF/E04UCA is essentially identical to the subroutine NPSOL described in Gill et al. (1986b).
At a solution of (1), some of the constraints will be active, i.e., satisfied exactly. An active simple bound constraint implies that the corresponding variable is fixed at its bound, and hence the variables are partitioned into fixed and free variables. Let C denote the m by n matrix of gradients of the active general linear and nonlinear constraints. The number of fixed variables will be denoted by nFX, with nFR nFR=n-nFX the number of free variables. The subscripts ‘FX’ and ‘FR’ on a vector or matrix will denote the vector or matrix composed of the elements corresponding to fixed or free variables.
A point x is a first-order Kuhn–Tucker point for (1) (see Powell (1974)) if the following conditions hold:
(i) | x is feasible;
(ii) there exist vectors ξ and λ (the Lagrange multiplier vectors for the bound and general constraints) such that
g=CT λ+ξ (2)
where g is the gradient of F evaluated at x, and ξj=0 if the jth variable is free.
(iii) | The Lagrange multiplier corresponding to an inequality constraint active at its lower bound must be non-negative, and non-positive for an inequality constraint active at its upper bound.
Let Z denote a matrix whose columns form a basis for the set of vectors orthogonal to the rows of CFR; i.e., CFR Z=0. An equivalent statement of the condition (2) in terms of Z is
ZT gFR=0.
The vector ZT gFR is termed the projected gradient of F at x. Certain additional conditions must be satisfied in order for a first-order Kuhn–Tucker point to be a solution of (1) (see Powell (1974)).
E04UCF/E04UCA implements a sequential quadratic programming (SQP) method. For an overview of SQP methods, see, for example, Fletcher (1987), Gill et al. (1981) and Powell (1983).
The basic structure of E04UCF/E04UCA involves major and minor iterations. The major iterations generate a sequence of iterates xk that converge to x*, a first-order Kuhn–Tucker point of (1). At a typical major iteration, the new iterate x- is defined by
x-=x+αp (3)
where x is the current iterate, the non-negative scalar α is the step length, and p is the search direction. (For simplicity, we shall always consider a typical iteration and avoid reference to the index of the iteration.) Also associated with each major iteration are estimates of the Lagrange multipliers and a prediction of the active set.
The search direction p in (3) is the solution of a quadratic programming subproblem of the form
minimizep gT p+ 12 pT Hp   subject to   l-≤ p AL p AN p ≤u-, (4)
where g is the gradient of F at x, the matrix H is a positive definite quasi-Newton approximation to the Hessian of the Lagrangian function (see Section 11.4), and AN is the Jacobian matrix of c evaluated at x. (Finite difference estimates may be used for g and AN; see the optional parameter Derivative Level.) Let l in (1) be partitioned into three sections: lB, lL and lN, corresponding to the bound, linear and nonlinear constraints. The vector l- in (4) is similarly partitioned, and is defined as
l-B=lB-x,  l-L=lL-AL x,   and  l-N=lN-c,
where c is the vector of nonlinear constraints evaluated at x. The vector u- is defined in an analogous fashion.
The estimated Lagrange multipliers at each major iteration are the Lagrange multipliers from the subproblem (4) (and similarly for the predicted active set). (The numbers of bounds, general linear and nonlinear constraints in the QP active set are the quantities Bnd, Lin and Nln in the monitoring file output of E04UCF/E04UCA; see Section 13.) In E04UCF/E04UCA, (4) is solved using E04NCF/E04NCA. Since solving a quadratic program is itself an iterative procedure, the minor iterations of E04UCF/E04UCA are the iterations of E04NCF/E04NCA. (More details about solving the subproblem are given in Section 11.2.)
Certain matrices associated with the QP subproblem are relevant in the major iterations. Let the subscripts ‘FX’ and ‘FR’ refer to the predicted fixed and free variables, and let C denote the m by n matrix of gradients of the general linear and nonlinear constraints in the predicted active set. First, we have available the TQ factorization of CFR:
CFRQFR= 0 T , (5)
where T is a nonsingular m by m reverse-triangular matrix (i.e., t ij=0 if i+j<m), and the nonsingular nFR by nFR matrix QFR is the product of orthogonal transformations (see Gill et al. (1984b)). Second, we have the upper triangular Cholesky factor R of the transformed and reordered Hessian matrix
RT R=HQ≡QT H~Q, (6)
where H~ is the Hessian H with rows and columns permuted so that the free variables are first, and Q is the n by n matrix
Q= QFR IFX (7)
with IFX the identity matrix of order nFX. If the columns of QFR are partitioned so that
QFR= Z Y ,
the nZ (nZ≡nFR-m) columns of Z form a basis for the null space of CFR. The matrix Z is used to compute the projected gradient ZT gFR at the current iterate. (The values Nz and Norm Gz printed by E04UCF/E04UCA give nZ and ZT gFR; see Section 13.)
A theoretical characteristic of SQP methods is that the predicted active set from the QP subproblem (4) is identical to the correct active set in a neighbourhood of x*. In E04UCF/E04UCA, this feature is exploited by using the QP active set from the previous iteration as a prediction of the active set for the next QP subproblem, which leads in practice to optimality of the subproblems in only one iteration as the solution is approached. Separate treatment of bound and linear constraints in E04UCF/E04UCA also saves computation in factorizing CFR and HQ.
Once p has been computed, the major iteration proceeds by determining a step length α that produces a ‘sufficient decrease’ in an augmented Lagrangian merit function (see Section 11.3). Finally, the approximation to the transformed Hessian matrix HQ is updated using a modified BFGS quasi-Newton update (see Section 11.4) to incorporate new curvature information obtained in the move from x to x-.
On entry to E04UCF/E04UCA, an iterative procedure from E04NCF/E04NCA is executed, starting with the user-supplied initial point, to find a point that is feasible with respect to the bounds and linear constraints (using the tolerance specified by optional parameter Linear Feasibility Tolerance). If no feasible point exists for the bound and linear constraints, (1) has no solution and E04UCF/E04UCA terminates. Otherwise, the problem functions will thereafter be evaluated only at points that are feasible with respect to the bounds and linear constraints. The only exception involves variables whose bounds differ by an amount comparable to the finite difference interval (see the discussion of optional parameter Difference Interval). In contrast to the bounds and linear constraints, it must be emphasized that the nonlinear constraints will not generally be satisfied until an optimal point is reached.
Facilities are provided to check whether the user-supplied gradients appear to be correct (see the description of the optional parameter Verify). In general, the check is provided at the first point that is feasible with respect to the linear constraints and bounds. However, you may request that the check be performed at the initial point.
In summary, the method of E04UCF/E04UCA first determines a point that satisfies the bound and linear constraints. Thereafter, each iteration includes:
(a) | the solution of a quadratic programming subproblem;
(b) | a linesearch with an augmented Lagrangian merit function; and
(c) | a quasi-Newton update of the approximate Hessian of the Lagrangian function.
These three procedures are described in more detail in Sections 11.2 to 11.4.

11.2 Solution of the Quadratic Programming Subproblem

The search direction p is obtained by solving (4) using E04NCF/E04NCA (see Gill et al. (1986)), which was specifically designed to be used within an SQP algorithm for nonlinear programming.
E04NCF/E04NCA is based on a two-phase (primal) quadratic programming method. The two phases of the method are: finding an initial feasible point by minimizing the sum of infeasibilities (the feasibility phase), and minimizing the quadratic objective function within the feasible region (the optimality phase). The computations in both phases are performed by the same subroutines. The two-phase nature of the algorithm is reflected by changing the function being minimized from the sum of infeasibilities to the quadratic objective function.
In general, a quadratic program must be solved by iteration. Let p denote the current estimate of the solution of (4); the new iterate p- is defined by
p-=p+σd (8)
where, as in (3), σ is a non-negative step length and d is a search direction.
At the beginning of each iteration of E04NCF/E04NCA, a working set is defined of constraints (general and bound) that are satisfied exactly. The vector d is then constructed so that the values of constraints in the working set remain unaltered for any move along d. For a bound constraint in the working set, this property is achieved by setting the corresponding element of d to zero, i.e., by fixing the variable at its bound. As before, the subscripts ‘FX’ and ‘FR’ denote selection of the elements associated with the fixed and free variables.
Let C denote the sub-matrix of rows of
AL AN
corresponding to general constraints in the working set. The general constraints in the working set will remain unaltered if
CFRdFR=0, (9)
which is equivalent to defining dFR as
dFR=Z dZ (10)
for some vector dZ, where Z is the matrix associated with the TQ factorization (5) of CFR.
The definition of dZ in (10) depends on whether the current p is feasible. If not, dZ is zero except for an element γ in the jth position, where j and γ are chosen so that the sum of infeasibilities is decreasing along d. (For further details, see Gill et al. (1986).) In the feasible case, dZ satisfies the equations
RZT RZ dZ = - ZT qFR , (11)
where RZ is the Cholesky factor of ZT HFR Z and q is the gradient of the quadratic objective function q=g+Hp. (The vector ZT qFR is the projected gradient of the QP.) With (11), p+d is the minimizer of the quadratic objective function subject to treating the constraints in the working set as equalities.
If the QP projected gradient is zero, the current point is a constrained stationary point in the subspace defined by the working set. During the feasibility phase, the projected gradient will usually be zero only at a vertex (although it may vanish at non-vertices in the presence of constraint dependencies). During the optimality phase, a zero projected gradient implies that p minimizes the quadratic objective function when the constraints in the working set are treated as equalities. In either case, Lagrange multipliers are computed. Given a positive constant δ of the order of the machine precision, the Lagrange multiplier μj corresponding to an inequality constraint in the working set is said to be optimal if μj≤δ when the jth constraint is at its upper bound, or if μj≥-δ when the associated constraint is at its lower bound. If any multiplier is nonoptimal, the current objective function (either the true objective or the sum of infeasibilities) can be reduced by deleting the corresponding constraint from the working set.
If optimal multipliers occur during the feasibility phase and the sum of infeasibilities is nonzero, no feasible point exists. The QP algorithm will then continue iterating to determine the minimum sum of infeasibilities. At this point, the Lagrange multiplier μj will satisfy -1+δ≤μj≤δ for an inequality constraint at its upper bound, and -δ≤μj≤1+δ for an inequality at its lower bound. The Lagrange multiplier for an equality constraint will satisfy μj≤1+δ.
The choice of step length σ in the QP iteration (8) is based on remaining feasible with respect to the satisfied constraints. During the optimality phase, if p+d is feasible, σ will be taken as unity. (In this case, the projected gradient at p- will be zero.) Otherwise, σ is set to σM, the step to the ‘nearest’ constraint, which is added to the working set at the next iteration.
Each change in the working set leads to a simple change to CFR: if the status of a general constraint changes, a row of CFR is altered; if a bound constraint enters or leaves the working set, a column of CFR changes. Explicit representations are recurred of the matrices T, QFR and R, and of the vectors QT q and QT g.

11.3 The Merit Function

After computing the search direction as described in Section 11.2, each major iteration proceeds by determining a step length α in (3) that produces a ‘sufficient decrease’ in the augmented Lagrangian merit function
L x,λ,s = F x - ∑i λi ci x - si + 12 ∑i ρi ci x - si 2 , (12)
where x, λ and s vary during the linesearch. The summation terms in (12) involve only the nonlinear constraints. The vector λ is an estimate of the Lagrange multipliers for the nonlinear constraints of (1). The non-negative slack variables si allow nonlinear inequality constraints to be treated without introducing discontinuities. The solution of the QP subproblem (4) provides a vector triple that serves as a direction of search for the three sets of variables. The non-negative vector ρ of penalty parameters is initialized to zero at the beginning of the first major iteration. Thereafter, selected elements are increased whenever necessary to ensure descent for the merit function. Thus, the sequence of norms of ρ (the printed quantity Penalty; see Section 13) is generally nondecreasing, although each ρi may be reduced a limited number of times.
The merit function (12) and its global convergence properties are described in Gill et al. (1986a).

11.4 The Quasi-Newton Update

The matrix H in (4) is a positive definite quasi-Newton approximation to the Hessian of the Lagrangian function. (For a review of quasi-Newton methods, see Dennis and Schnabel (1983).) At the end of each major iteration, a new Hessian approximation H- is defined as a rank-two modification of H. In E04UCF/E04UCA, the BFGS (Broyden–Fletcher–Goldfarb–Shanno) quasi-Newton update is used:
H-=H-1 sT Hs Hs sT H+1 yT s y yT, (13)
where s=x--x (the change in x).
In E04UCF/E04UCA, H is required to be positive definite. If H is positive definite, H- defined by (13) will be positive definite if and only if yT s is positive (see Dennis and Moré (1977)). Ideally, y in (13) would be taken as yL, the change in gradient of the Lagrangian function
yL = g- - A-NT μN - g + ANT μN , (14)
where μN denotes the QP multipliers associated with the nonlinear constraints of the original problem. If yLT s is not sufficiently positive, an attempt is made to perform the update with a vector y of the form
y=yL+∑i=1 mN ωi ai x^ci x^-ai x ci x,
where ωi≥0. If no such vector can be found, the update is performed with a scaled yL; in this case, M is printed to indicate that the update was modified.
Rather than modifying H itself, the Cholesky factor of the transformed Hessian HQ (6) is updated, where Q is the matrix from (5) associated with the active set of the QP subproblem. The update (13) is equivalent to the following update to HQ:
H-Q = HQ - 1 sQT HQ sQ HQ sQ sQT HQ + 1 yQT sQ yQ yQT , (15)
where yQ=QT y, and sQ=QT s. This update may be expressed as a rank-one update to R (see Dennis and Schnabel (1981)).

12 Optional Parameters

Several optional parameters in E04UCF/E04UCA define choices in the problem specification or the algorithm logic. In order to reduce the number of formal arguments of E04UCF/E04UCA these optional parameters have associated default values that are appropriate for most problems. Therefore you need only specify those optional parameters whose values are to be different from their default values.
The remainder of this section can be skipped if you wish to use the default values for all optional parameters.
The following is a list of the optional parameters available. A full description of each optional parameter is provided in Section 12.1.
  • Central Difference Interval
  • Cold Start
  • Crash Tolerance
  • Defaults
  • Derivative Level
  • Difference Interval
  • Feasibility Tolerance
  • Function Precision
  • Hessian
  • Infinite Bound Size
  • Infinite Step Size
  • Iteration Limit
  • Iters
  • Itns
  • Linear Feasibility Tolerance
  • Line Search Tolerance
  • List
  • Major Iteration Limit
  • Major Print Level
  • Minor Iteration Limit
  • Minor Print Level
  • Monitoring File
  • Nolist
  • Nonlinear Feasibility Tolerance
  • Optimality Tolerance
  • Print Level
  • Start Constraint Check At Variable
  • Start Objective Check At Variable
  • Step Limit
  • Stop Constraint Check At Variable
  • Stop Objective Check At Variable
  • Verify
  • Verify Constraint Gradients
  • Verify Gradients
  • Verify Level
  • Verify Objective Gradients
  • Warm Start
Optional parameters may be specified by calling one, or both, of E04UDF/E04UDA and E04UEF/E04UEA before a call to E04UCF/E04UCA.
E04UDF/E04UDA reads options from an external options file, with Begin and End as the first and last lines respectively and each intermediate line defining a single optional parameter. For example,
Begin
  Print level = 1
End
The call can then be used to read the file on unit IOPTNS. INFORM will be zero on successful exit. E04UDF/E04UDA should be consulted for a full description of this method of supplying optional parameters.
E04UEF/E04UEA can be called to supply options directly, one call being necessary for each optional parameter. For example,
 CALL E04UEF ('Print Level = 1')
E04UEF/E04UEA should be consulted for a full description of this method of supplying optional parameters.
All optional parameters not specified by you are set to their default values. Optional parameters specified by you are unaltered by E04UCF/E04UCA (unless they define invalid values) and so remain in effect for subsequent calls to E04UCF/E04UCA, unless altered by you.

12.1 Description of the Optional Parameters

For each option, we give a summary line, a description of the optional parameter and details of constraints.
The summary line contains:
  • the keywords, where the minimum abbreviation of each keyword is underlined (if no characters of an optional qualifier are underlined, the qualifier may be omitted);
  • a parameter value, where the letters a, i and r denote options that take character, integer and real values respectively;
  • the default value, where the symbol ε is a generic notation for machine precision (see X02AJF), and εr denotes the relative precision of the objective function Function Precision, and bigbnd signifies the value of Infinite Bound Size.
Keywords and character values are case and white space insensitive.
Central Difference Interval r Default values are computed
If the algorithm switches to central differences because the forward-difference approximation is not sufficiently accurate, the value of r is used as the difference interval for every element of x. The switch to central differences is indicated by C at the end of each line of intermediate printout produced by the major iterations (see Section 9.1). The use of finite differences is discussed further under the optional parameter Difference Interval.
If you supply a value for this optional parameter, a small value between 0.0 and 1.0 is appropriate.
Cold Start Default
Warm Start
This option controls the specification of the initial working set in both the procedure for finding a feasible point for the linear constraints and bounds and in the first QP subproblem thereafter. With a Cold Start, the first working set is chosen by E04UCF/E04UCA based on the values of the variables and constraints at the initial point. Broadly speaking, the initial working set will include equality constraints and bounds or inequality constraints that violate or ‘nearly’ satisfy their bounds (to within Crash Tolerance).
With a Warm Start, you must set the ISTATE array and define CLAMDA and R as discussed in Section 5. ISTATE values associated with bounds and linear constraints determine the initial working set of the procedure to find a feasible point with respect to the bounds and linear constraints. ISTATE values associated with nonlinear constraints determine the initial working set of the first QP subproblem after such a feasible point has been found. E04UCF/E04UCA will override your specification of ISTATE if necessary, so that a poor choice of the working set will not cause a fatal error. For instance, any elements of ISTATE which are set to -2, -1​ or ​4 will be reset to zero, as will any elements which are set to 3 when the corresponding elements of BL and BU are not equal. A warm start will be advantageous if a good estimate of the initial working set is available – for example, when E04UCF/E04UCA is called repeatedly to solve related problems.
Crash Tolerance r Default =0.01
This value is used in conjunction with the optional parameter Cold Start (the default value) when E04UCF/E04UCA selects an initial working set. If 0≤r≤1, the initial working set will include (if possible) bounds or general inequality constraints that lie within r of their bounds. In particular, a constraint of the form ajT x≥l will be included in the initial working set if ajT x-l ≤ r 1+l . If r<0 or r>1, the default value is used.
Defaults
This special keyword may be used to reset all optional parameters to their default values.
Derivative Level i Default =3
This parameter indicates which derivatives are provided in user-supplied subroutines OBJFUN and CONFUN. The possible choices for i are the following.
i | Meaning
3 | All elements of the objective gradient and the constraint Jacobian are provided.
2 | All elements of the constraint Jacobian are provided, but some elements of the objective gradient are not specified.
1 | All elements of the objective gradient are provided, but some elements of the constraint Jacobian are not specified.
0 | Some elements of both the objective gradient and the constraint Jacobian are not specified.
The value i=3 should be used whenever possible, since E04UCF/E04UCA is more reliable (and will usually be more efficient) when all derivatives are exact.
If i=0​ or ​2, E04UCF/E04UCA will estimate the unspecified elements of the objective gradient, using finite differences. The computation of finite difference approximations usually increases the total run-time, since a call to OBJFUN is required for each unspecified element. Furthermore, less accuracy can be attained in the solution (see Chapter 8 of Gill et al. (1981), for a discussion of limiting accuracy).
If i=0​ or ​1, E04UCF/E04UCA will approximate unspecified elements of the constraint Jacobian. One call to CONFUN is needed for each variable for which partial derivatives are not available. For example, if the Jacobian has the form
* * * * * ? ? * * * ? * * * * *
where ‘*’ indicates an element provided by you and ‘?’ indicates an unspecified element, E04UCF/E04UCA will call CONFUN twice: once to estimate the missing element in column 2, and again to estimate the two missing elements in column 3. (Since columns 1 and 4 are known, they require no calls to CONFUN.)
At times, central differences are used rather than forward differences, in which case twice as many calls to OBJFUN and CONFUN are needed. (The switch to central differences is not under your control.)
If i<0 or i>3, the default value is used.
Difference Interval r Default values are computed
This option defines an interval used to estimate derivatives by finite differences in the following circumstances:
(a) | For verifying the objective and/or constraint gradients (see the description of the optional parameter Verify).
(b) | For estimating unspecified elements of the objective gradient or the constraint Jacobian.
In general, a derivative with respect to the jth variable is approximated using the interval δj, where δj=r 1+x^j, with x^ the first point feasible with respect to the bounds and linear constraints. If the functions are well scaled, the resulting derivative approximation should be accurate to O r. See Gill et al. (1981) for a discussion of the accuracy in finite difference approximations.
If a difference interval is not specified by you, a finite difference interval will be computed automatically for each variable by a procedure that requires up to six calls of CONFUN and OBJFUN for each element. This option is recommended if the function is badly scaled or you wish to have E04UCF/E04UCA determine constant elements in the objective and constraint gradients (see the descriptions of CONFUN and OBJFUN in Section 5).
If you supply a value for this optional parameter, a small value between 0.0 and 1.0 is appropriate.
Feasibility Tolerance r Default =ε
The scalar r defines the maximum acceptable absolute violations in linear and nonlinear constraints at a ‘feasible’ point; i.e., a constraint is considered satisfied if its violation does not exceed r. If r<ε or r≥1, the default value is used. Using this keyword sets both optional parameters Linear Feasibility Tolerance and Nonlinear Feasibility Tolerance to r, if ε≤r<1. (Additional details are given under the descriptions of these optional parameters.)
Function Precision r Default =ε 0.9
This parameter defines εr, which is intended to be a measure of the accuracy with which the problem functions F x and c x can be computed. If r<ε or r≥1, the default value is used.
The value of εr should reflect the relative precision of 1+F x; i.e., εr acts as a relative precision when F is large and as an absolute precision when F is small. For example, if F x is typically of order 1000 and the first six significant digits are known to be correct, an appropriate value for εr would be 10-6. In contrast, if F x is typically of order 10-4 and the first six significant digits are known to be correct, an appropriate value for εr would be 10-10. The choice of εr can be quite complicated for badly scaled problems; see Chapter 8 of Gill et al. (1981) for a discussion of scaling techniques. The default value is appropriate for most simple functions that are computed with full accuracy. However, when the accuracy of the computed function values is known to be significantly worse than full precision, the value of εr should be large enough so that E04UCF/E04UCA will not attempt to distinguish between function values that differ by less than the error inherent in the calculation.
Hessian N o Default =NO
This option controls the contents of the upper triangular matrix R (see Section 5). E04UCF/E04UCA works exclusively with the transformed and reordered Hessian HQ (6), and hence extra computation is required to form the Hessian itself. If Hessian=NO, R contains the Cholesky factor of the transformed and reordered Hessian. If Hessian=YES, the Cholesky factor of the approximate Hessian itself is formed and stored in R. You should select Hessian=YES if a Warm Start will be used for the next call to E04UCF/E04UCA.
Infinite Bound Size r Default =1020
If r>0, r defines the ‘infinite’ bound bigbnd in the definition of the problem constraints. Any upper bound greater than or equal to bigbnd will be regarded as +∞ (and similarly any lower bound less than or equal to -bigbnd will be regarded as -∞). If r<0, the default value is used.
Infinite Step Size r Default =max bigbnd,1020
If r>0, r specifies the magnitude of the change in variables that is treated as a step to an unbounded solution. If the change in x during an iteration would exceed the value of r, the objective function is considered to be unbounded below in the feasible region. If r≤0, the default value is used.
Line Search Tolerance r Default =0.9
The value r (0≤r<1) controls the accuracy with which the step α taken during each iteration approximates a minimum of the merit function along the search direction (the smaller the value of r, the more accurate the linesearch). The default value r=0.9 requests an inaccurate search and is appropriate for most problems, particularly those with any nonlinear constraints.
If there are no nonlinear constraints, a more accurate search may be appropriate when it is desirable to reduce the number of major iterations – for example, if the objective function is cheap to evaluate, or if a substantial number of derivatives are unspecified. If r<0 or r≥1, the default value is used.
Linear Feasibility Tolerance r 1 Default =ε
Nonlinear Feasibility Tolerance r 2 Default =ε 0.33 or ε
The default value of r 2 is ε 0.33 if Derivative Level=0 or 1, and ε otherwise.
The scalars r 1 and r 2 define the maximum acceptable absolute violations in linear and nonlinear constraints at a ‘feasible’ point; i.e., a linear constraint is considered satisfied if its violation does not exceed r 1, and similarly for a nonlinear constraint and r 2. If rm<ε or rm≥1, the default value is used, for m=1,2.
On entry to E04UCF/E04UCA, an iterative procedure is executed in order to find a point that satisfies the linear constraints and bounds on the variables to within the tolerance r 1. All subsequent iterates will satisfy the linear constraints to within the same tolerance (unless r 1 is comparable to the finite difference interval).
For nonlinear constraints, the feasibility tolerance r 2 defines the largest constraint violation that is acceptable at an optimal point. Since nonlinear constraints are generally not satisfied until the final iterate, the value of optional parameter Nonlinear Feasibility Tolerance acts as a partial termination criterion for the iterative sequence generated by E04UCF/E04UCA (see the discussion of optional parameter Optimality Tolerance).
These tolerances should reflect the precision of the corresponding constraints. For example, if the variables and the coefficients in the linear constraints are of order unity, and the latter are correct to about 6 decimal digits, it would be appropriate to specify r 1 as 10-6.
List Default for E04UCF
Nolist Default for E04UCA
For E04UCF, normally each optional parameter specification is printed as it is supplied. Optional parameter Nolist may be used to suppress the printing and optional parameter List may be used to turn on printing.
Major Iteration Limit i Default =max 50,3 n+nL+10 nN
Iteration Limit
Iters
Itns
The value of i specifies the maximum number of major iterations allowed before termination. Setting i=0 and Major Print Level>0 means that the workspace needed will be computed and printed, but no iterations will be performed. If i<0, the default value is used.
Major Print Level i Default for E04UCF =10
Print Level i Default for E04UCA =0
The value of i controls the amount of printout produced by the major iterations of E04UCF/E04UCA, as indicated below. A detailed description of the printed output is given in Section 9.1 (summary output at each major iteration and the final solution) and Section 13 (monitoring information at each major iteration). (See also the description of the optional parameter Minor Print Level.)
The following printout is sent to the current advisory message unit (as defined by X04ABF):
i | Output
≥0 0 | No output.
≥0 1 | The final solution only.
≥0 5 | One line of summary output (<80 characters; see Section 9.1) for each major iteration (no printout of the final solution).
≥10 | The final solution and one line of summary output for each major iteration.
The following printout is sent to the logical unit number by the optional parameter Monitoring File:
i | Output
<5 | No output.
≥5 | One long line of output (>80 characters; see Section 13) for each major iteration (no printout of the final solution).
≥20 | At each major iteration, the objective function, the Euclidean norm of the nonlinear constraint violations, the values of the nonlinear constraints (the vector c), the values of the linear constraints (the vector AL x), and the current values of the variables (the vector x).
≥30 | At each major iteration, the diagonal elements of the matrix T associated with the TQ factorization (5) (see Section 11.1) of the QP working set, and the diagonal elements of R, the triangular factor of the transformed and reordered Hessian (6) (see Section 11.1).
If Major Print Level≥5 and the unit number defined by the optional parameter Monitoring File is the same as that defined by X04ABF, then the summary output for each major iteration is suppressed.
Minor Iteration Limit i Default =max 50,3 n+nL+nN
The value of i specifies the maximum number of iterations for finding a feasible point with respect to the bounds and linear constraints (if any). The value of i also specifies the maximum number of minor iterations for the optimality phase of each QP subproblem. If i≤0, the default value is used.
Minor Print Level i Default =0
The value of i controls the amount of printout produced by the minor iterations of E04UCF/E04UCA (i.e., the iterations of the quadratic programming algorithm), as indicated below. A detailed description of the printed output is given in Section 9.1 (summary output at each minor iteration and the final QP solution) and Section 13 in E04NCF/E04NCA (monitoring information at each minor iteration). (See also the description of the optional parameter Major Print Level.)
The following printout is sent to the current advisory message unit (as defined by X04ABF):
i | Output
≥0 0 | No output.
≥0 1 | The final QP solution only.
≥0 5 | One line of summary output (<80 characters; see Section 9.2 in E04NCF/E04NCA) for each minor iteration (no printout of the final QP solution).
≥10 | The final QP solution and one line of summary output for each minor iteration.
The following printout is sent to the logical unit number by the optional parameter Monitoring File:
i | Output
<5 | No output.
≥5 | One long line of output (>80 characters; see Section 9.2 in E04NCF/E04NCA) for each minor iteration (no printout of the final QP solution).
≥20 | At each minor iteration, the current estimates of the QP multipliers, the current estimate of the QP search direction, the QP constraint values, and the status of each QP constraint.
≥30 | At each minor iteration, the diagonal elements of the matrix T associated with the TQ factorization (5) (see Section 11.1) of the QP working set, and the diagonal elements of the Cholesky factor R of the transformed Hessian (6) (see Section 11.1).
If Major Print Level≥5 and the unit number defined by the optional parameter Monitoring File is the same as that defined by X04ABF, then the summary output for each major iteration is suppressed.
Monitoring File i Default =-1
If i≥0 and Major Print Level≥5 or i≥0 and Minor Print Level≥5, monitoring information produced by E04UCF/E04UCA at every iteration is sent to a file with logical unit number i. If i<0 and/or Major Print Level<5 and Minor Print Level<5, no monitoring information is produced.
Optimality Tolerance r Default =εR 0.8
The parameter r (εr≤r<1) specifies the accuracy to which you wish the final iterate to approximate a solution of the problem. Broadly speaking, r indicates the number of correct figures desired in the objective function at the solution. For example, if r is 10-6 and E04UCF/E04UCA terminates successfully, the final value of F should have approximately six correct figures. If r<εr or r≥1, the default value is used.
E04UCF/E04UCA will terminate successfully if the iterative sequence of x values is judged to have converged and the final point satisfies the first-order Kuhn–Tucker conditions (see Section 11.1). The sequence of iterates is considered to have converged at x if
α p≤r 1+x, (16)
where p is the search direction and α the step length from (3). An iterate is considered to satisfy the first-order conditions for a minimum if
ZT g FR ≤ r 1 + max 1 + F x , g FR (17)
and
resj≤ftol  for all  j, (18)
where ZT gFR is the projected gradient (see Section 11.1), gFR is the gradient of F x with respect to the free variables, resj is the violation of the jth active nonlinear constraint, and ftol is the Nonlinear Feasibility Tolerance.
Start Objective Check At Variable i 1 Default =1
Stop Objective Check At Variable i 2 Default =n
Start Constraint Check At Variable i 3 Default =1
Stop Constraint Check At Variable i 4 Default =n
These keywords take effect only if Verify Level>0. They may be used to control the verification of gradient elements computed by OBJFUN and/or Jacobian elements computed by CONFUN. For example, if the first 30 elements of the objective gradient appeared to be correct in an earlier run, so that only element 31 remains questionable, it is reasonable to specify Start Objective Check At Variable=31. If the first 30 variables appear linearly in the objective, so that the corresponding gradient elements are constant, the above choice would also be appropriate.
If i 2 m-1≤0 or i 2 m-1>min n,i 2 m, the default value is used, for m=1,2. If i 2 m≤0 or i 2 m>n, the default value is used, for m=1,2.
Step Limit r Default =2.0
If r>0,r specifies the maximum change in variables at the first step of the linesearch. In some cases, such as F x=a e bx or F x=a xb, even a moderate change in the elements of x can lead to floating-point overflow. The parameter r is therefore used to encourage evaluation of the problem functions at meaningful points. Given any major iterate x, the first point x~ at which F and c are evaluated during the linesearch is restricted so that
x~-x 2≤r 1+x 2.
The linesearch may go on and evaluate F and c at points further from x if this will result in a lower value of the merit function (indicated by L at the end of each line of output produced by the major iterations; see Section 9.1). If L is printed for most of the iterations, r should be set to a larger value.
Wherever possible, upper and lower bounds on x should be used to prevent evaluation of nonlinear functions at wild values. The default value Step Limit=2.0 should not affect progress on well-behaved functions, but values such as 0.1 ​ or ​ 0.01 may be helpful when rapidly varying functions are present. If a small value of Step Limit is selected, a good starting point may be required. An important application is to the class of nonlinear least squares problems. If r≤0, the default value is used.
Verify Level i Default =0
Verify i
Verify Constraint Gradients i
Verify Gradients i
Verify Objective Gradients i
These keywords refer to finite difference checks on the gradient elements computed by OBJFUN and CONFUN. The possible choices for i are as follows:
i | Meaning
-1 | No checks are performed.
-0 | Only a ‘cheap’ test will be performed.
≥1 | Individual gradient elements will also be checked using a reliable (but more expensive) test.
It is possible to specify Verify Level=0 to 3 in several ways. For example, the nonlinear objective gradient (if any) will be verified if either Verify Objective Gradients or Verify Level=1 is specified. The constraint gradients will be verified if Verify=YES or Verify Level=2 or Verify is specified. Similarly, the objective and the constraint gradients will be verified if Verify=YES or Verify Level=3 or Verify is specified.
If 0≤i≤3, gradients will be verified at the first point that satisfies the linear constraints and bounds.
If i=0, only a ‘cheap’ test will be performed, requiring one call to OBJFUN and (if appropriate) one call to CONFUN.
If 1≤i≤3, a more reliable (but more expensive) check will be made on individual gradient elements, within the ranges specified by the Start Constraint Check At Variable and Stop Constraint Check At Variable keywords. A result of the form OK or BAD? is printed by E04UCF/E04UCA to indicate whether or not each element appears to be correct.
If 10≤i≤13, the action is the same as for i-10, except that it will take place at the user-specified initial value of x.
If i<-1 or 4≤i≤9 or i>13, the default value is used.
We suggest that Verify Level=3 be used whenever a new function routine is being developed.

13 Description of Monitoring Information

This section describes the long line of output (>80 characters) which forms part of the monitoring information produced by E04UCF/E04UCA. (See also the description of the optional parameters Major Print Level, Minor Print Level and Monitoring File.) You can control the level of printed output.
When Major Print Level≥5 and Monitoring File≥0, the following line of output is produced at every major iteration of E04UCF/E04UCA on the unit number specified by Monitoring File. In all cases, the values of the quantities printed are those in effect on completion of the given iteration.
Maj | is the major iteration count.
Mnr is the number of minor iterations required by the feasibility and optimality phases of the QP subproblem. Generally, Mnr will be 1 in the later iterations, since theoretical analysis predicts that the correct active set will be identified near the solution (see Section 11).
Note that Mnr may be greater than the optional parameter Minor Iteration Limit if some iterations are required for the feasibility phase.
Step | is the step αk taken along the computed search direction. On reasonably well-behaved problems, the unit step (i.e., αk=1) will be taken as the solution is approached.
Nfun | is the cumulative number of evaluations of the objective function needed for the linesearch. Evaluations needed for the estimation of the gradients by finite differences are not included. Nfun is printed as a guide to the amount of work required for the linesearch.
Merit Function is the value of the augmented Lagrangian merit function (12) at the current iterate. This function will decrease at each iteration unless it was necessary to increase the penalty parameters (see Section 11.3). As the solution is approached, Merit Function will converge to the value of the objective function at the solution.
If the QP subproblem does not have a feasible point (signified by I at the end of the current output line) then the merit function is a large multiple of the constraint violations, weighted by the penalty parameters. During a sequence of major iterations with infeasible subproblems, the sequence of Merit Function values will decrease monotonically until either a feasible subproblem is obtained or E04UCF/E04UCA terminates with IFAIL=3 (no feasible point could be found for the nonlinear constraints).
If there are no nonlinear constraints present (i.e., NCNLN=0) then this entry contains Objective, the value of the objective function F x. The objective function will decrease monotonically to its optimal value when there are no nonlinear constraints.
Norm Gz | is ZT gFR, the Euclidean norm of the projected gradient (see Section 11.2). Norm Gz will be approximately zero in the neighbourhood of a solution.
Violtn | is the Euclidean norm of the residuals of constraints that are violated or in the predicted active set (not printed if NCNLN is zero). Violtn will be approximately zero in the neighbourhood of a solution.
Nz | is the number of columns of Z (see Section 11.2). The value of Nz is the number of variables minus the number of constraints in the predicted active set; i.e., Nz=n-Bnd+Lin+Nln.
Bnd | is the number of simple bound constraints in the predicted active set.
Lin | is the number of general linear constraints in the predicted working set.
Nln | is the number of nonlinear constraints in the predicted active set (not printed if NCNLN is zero).
Penalty | is the Euclidean norm of the vector of penalty parameters used in the augmented Lagrangian merit function (not printed if NCNLN is zero).
Cond H | is a lower bound on the condition number of the Hessian approximation H.
Cond Hz | is a lower bound on the condition number of the projected Hessian approximation HZ ( HZ = ZT HFR Z = RZT RZ ; see (6)). The larger this number, the more difficult the problem.
Cond T | is a lower bound on the condition number of the matrix of predicted active constraints.
Conv is a three-letter indication of the status of the three convergence tests (16)–(18) defined in the description of the optional parameter Optimality Tolerance. Each letter is T if the test is satisfied and F otherwise. The three tests indicate whether:
(i) | the sequence of iterates has converged;
(ii) | the projected gradient (Norm Gz) is sufficiently small; and
(iii) | the norm of the residuals of constraints in the predicted active set (Violtn) is small enough.
If any of these indicators is F when E04UCF/E04UCA terminates with IFAIL=0, you should check the solution carefully.
M | is printed if the quasi-Newton update has been modified to ensure that the Hessian approximation is positive definite (see Section 11.4).
I | is printed if the QP subproblem has no feasible point.
C | is printed if central differences have been used to compute the unspecified objective and constraint gradients. If the value of Step is zero then the switch to central differences was made because no lower point could be found in the linesearch. (In this case, the QP subproblem is resolved with the central difference gradient and Jacobian.) If the value of Step is nonzero then central differences were computed because Norm Gz and Violtn imply that x is close to a Kuhn–Tucker point (see Section 11.1 in E04UFF/E04UFA).
L | is printed if the linesearch has produced a relative change in x greater than the value defined by the optional parameter Step Limit. If this output occurs frequently during later iterations of the run, optional parameter Step Limit should be set to a larger value.
R | is printed if the approximate Hessian has been refactorized. If the diagonal condition estimator of R indicates that the approximate Hessian is badly conditioned then the approximate Hessian is refactorized using column interchanges. If necessary, R is modified so that its diagonal condition estimator is bounded.
E04 Chapter Contents
E04 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


E04UDF/E04UDA : NAG Library, Mark 26

E04 Chapter Contents
E04 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

E04UDF/E04UDA

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
▸▿ 2 Specification
2.1 Specification for E04UDF
2.2 Specification for E04UDA
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

To supply optional parameters to E04UCF/E04UCA from an external file. More precisely, E04UDF must be used to supply optional parameters to E04UCF and E04UDA must be used to supply optional parameters to E04UCA.
E04UDA is a version of E04UDF that has additional arguments in order to make it safe for use in multithreaded applications (see Section 5). The initialization routine E04WBF must have been called before calling E04UDA.
E04UDF/E04UDA can also be used to supply optional parameters to E04UFF/E04UFA.

2 Specification

2.1 Specification for E04UDF

SUBROUTINE E04UDF ( IOPTNS, INFORM)
INTEGER IOPTNS, INFORM

2.2 Specification for E04UDA

SUBROUTINE E04UDA ( IOPTNS, LWSAV, IWSAV, RWSAV, INFORM)
INTEGER | IOPTNS, IWSAV(610), INFORM
REAL (KIND=nag_wp) | RWSAV(475)
LOGICAL | LWSAV(120)

3 Description

E04UDF/E04UDA may be used to supply values for optional parameters to E04UCF/E04UCA. E04UDF/E04UDA reads an external file and each line of the file defines a single optional parameter. It is only necessary to supply values for those arguments whose values are to be different from their default values.
Each optional parameter is defined by a single character string, of up to 72 characters, consisting of one or more items. The items associated with a given option must be separated by spaces, or equals signs =. Alphabetic characters may be upper or lower case. The string
Print Level = 1
is an example of a string used to set an optional parameter. For each option the string contains one or more of the following items:
– | a mandatory keyword;
– | a phrase that qualifies the keyword;
– | a number that specifies an integer or real value. Such numbers may be up to 40 contiguous characters in Fortran's I, F, E or D formats, terminated by a space if this is not the last item on the line.
Blank strings and comments are ignored. A comment begins with an asterisk (*) and all subsequent characters in the string are regarded as part of the comment.
The file containing the options must start with Begin and must finish with End. An example of a valid options file is:
Begin * Example options file
   Print level = 5
End
For E04UDF each line of the file is normally printed as it is read, on the current advisory message unit (see X04ABF), but printing may be suppressed using the keyword Nolist. To suppress printing of Begin, Nolist must be the first option supplied as in the file:
Begin
   Nolist
   Print level = 5
End
Printing will automatically be turned on again after a call to E04UCF or E04UDF and may be turned on again at any time using the keyword List.
For E04UDA printing is turned off by default, but may be turned on at any time using the keyword List.
Optional parameter settings are preserved following a call to E04UCF/E04UCA and so the keyword Defaults is provided to allow you to reset all the optional parameters to their default values before a subsequent call to E04UCF/E04UCA.
A complete list of optional parameters, their abbreviations, synonyms and default values is given in Section 12 in E04UCF/E04UCA.

4 References

None.

5 Arguments

1:   IOPTNS – INTEGERInput
On entry: the unit number of the options file to be read.
Constraint: 0≤IOPTNS≤99.
2:   INFORM – INTEGEROutput
Note: for E04UDA, INFORM does not occur in this position in the argument list. See the additional arguments described below.
On exit: contains zero if the options file has been successfully read and a value>0 otherwise (see Section 6).
Note: the following are additional arguments for specific use with E04UDA. Users of E04UDF therefore need not read the remainder of this description.
2:   LWSAV 120 – LOGICAL arrayCommunication Array
3:   IWSAV 610 – INTEGER arrayCommunication Array
4:   RWSAV 475 – REAL (KIND=nag_wp) arrayCommunication Array
The arrays LWSAV, IWSAV and RWSAV must not be altered between calls to any of the routines E04UDA, E04UCA, E04UEA and E04WBF.
5:   INFORM – INTEGEROutput
Note: see the argument description for INFORM above.

6 Error Indicators and Warnings

INFORM=1
IOPTNS is not in the range 0,99.
INFORM=2
Begin was found, but end-of-file was found before End was found.
INFORM=3
end-of-file was found before Begin was found.
INFORM=4
Not used.
INFORM=5
One or more lines of the options file is invalid. Check that all keywords are neither ambiguous nor misspelt.

7 Accuracy

Not applicable.

8 Parallelism and Performance

E04UDF/E04UDA is not threaded in any implementation.

9 Further Comments

E04UEF/E04UEA may also be used to supply optional parameters to E04UCF/E04UCA.

10 Example

This example solves the same problem as the example for E04UCF/E04UCA, but in addition illustrates the use of E04UDF/E04UDA and E04UEF/E04UEA to set optional parameters for E04UCF/E04UCA.
In this example the options file read by E04UDF/E04UDA is appended to the data file for the program (see Section 10.2). It would usually be more convenient in practice to keep the data file and the options file separate.

10.1 Program Text

Note: the following programs illustrate the use of E04UDF and E04UDA.

Program Text (e04udfe.f90)

Program Text (e04udae.f90)

10.2 Program Data

Program Options (e04udfe.opt)

Program Options (e04udae.opt)

Program Data (e04udfe.d)

Program Data (e04udae.d)

10.3 Program Results

Program Results (e04udfe.r)

Program Results (e04udae.r)

E04 Chapter Contents
E04 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


E04UEF/E04UEA : NAG Library, Mark 26

E04 Chapter Contents
E04 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

E04UEF/E04UEA

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
▸▿ 2 Specification
2.1 Specification for E04UEF
2.2 Specification for E04UEA
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
10 Example

1 Purpose

To supply individual optional parameters to E04UCF/E04UCA. More precisely, E04UEF must be used to supply optional parameters to E04UCF and E04UEA must be used to supply optional parameters to E04UCA.
E04UEA is a version of E04UEF that has additional arguments in order to make it safe for use in multithreaded applications (see Section 5). The initialization routine E04WBF must have been called before calling E04UEA.
E04UEF/E04UEA can also be used to supply individual optional parameters to E04UFF/E04UFA.

2 Specification

2.1 Specification for E04UEF

SUBROUTINE E04UEF ( STR)
CHARACTER(*) STR

2.2 Specification for E04UEA

SUBROUTINE E04UEA ( STR, LWSAV, IWSAV, RWSAV, INFORM)
INTEGER | IWSAV(610), INFORM
REAL (KIND=nag_wp) | RWSAV(475)
LOGICAL | LWSAV(120)
CHARACTER(*) | STR

3 Description

E04UEF/E04UEA may be used to supply values for optional parameters to E04UCF/E04UCA. It is only necessary to call E04UEF/E04UEA for those arguments whose values are to be different from their default values. One call to E04UEF/E04UEA sets one argument value.
Each optional parameter is defined by a single character string, of up to 72 characters, consisting of one or more items. The items associated with a given option must be separated by spaces, or equals signs =. Alphabetic characters may be upper or lower case. The string
Print Level = 1
is an example of a string used to set an optional parameter. For each option the string contains one or more of the following items:
– | a mandatory keyword;
– | a phrase that qualifies the keyword;
– | a number that specifies an integer or real value. Such numbers may be up to 40 contiguous characters in Fortran's I, F, E or D formats, terminated by a space if this is not the last item on the line.
Blank strings and comments are ignored. A comment begins with an asterisk (*) and all subsequent characters in the string are regarded as part of the comment.
For E04UEF, each user-specified option is normally printed as it is defined, on the current advisory message unit (see X04ABF), but this printing may be suppressed using the keyword Nolist. Thus the statement
 CALL E04EUF ('Nolist')
suppresses printing of this and subsequent options. Printing will automatically be turned on again after a call to E04UCF and may be turned on again at any time using the keyword List.
For E04UEA printing is turned off by default, but may be turned on at any time using the keyword List.
Optional parameter settings are preserved following a call to E04UCF/E04UCA and so the keyword Defaults is provided to allow you to reset all the optional parameters to their default values before a subsequent call to E04UCF/E04UCA.
A complete list of optional parameters, their abbreviations, synonyms and default values is given in Section 12 in E04UCF/E04UCA.

4 References

None.

5 Arguments

1:   STR – CHARACTER(*)Input
On entry: a single valid option string (as described in Section 3 and in Section 12 in E04UCF/E04UCA).
Note: the following are additional arguments for specific use with E04UEA. Users of E04UEF therefore need not read the remainder of this description.
2:   LWSAV 120 – LOGICAL arrayCommunication Array
3:   IWSAV 610 – INTEGER arrayCommunication Array
4:   RWSAV 475 – REAL (KIND=nag_wp) arrayCommunication Array
The arrays LWSAV, IWSAV and RWSAV must not be altered between calls to any of the routines E04UEA, E04UCA, E04UDA and E04WBF.
5:   INFORM – INTEGEROutput
On exit: contains zero if a valid option string has been supplied and a value>0 otherwise (see Section 6).

6 Error Indicators and Warnings

INFORM=5
The supplied option is invalid. Check that the keywords are neither ambiguous nor misspelt.

7 Accuracy

Not applicable.

8 Parallelism and Performance

E04UEF/E04UEA is not threaded in any implementation.

9 Further Comments

E04UDF/E04UDA may also be used to supply optional parameters to E04UCF/E04UCA.

10 Example

See Section 10 in E04UDF/E04UDA.
E04 Chapter Contents
E04 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


E04UFF/E04UFA : NAG Library, Mark 26

E04 Chapter Contents
E04 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

E04UFF/E04UFA

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.
Note: this routine uses optional parameters to define choices in the problem specification and in the details of the algorithm. If you wish to use default settings for all of the optional parameters, you need only read Sections 1 to 10 of this document. If, however, you wish to reset some or all of the settings please refer to Section 11 for a detailed description of the algorithm, to Section 12 for a detailed description of the specification of the optional parameters and to Section 13 for a detailed description of the monitoring information produced by the routine.

▸▿ Contents

1 Purpose
▸▿ 2 Specification
2.1 Specification for E04UFF
2.2 Specification for E04UFA
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
▸▿ 9 Further Comments
9.1 Description of the Printed Output
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results
▸▿ 11 Algorithmic Details
11.1 Overview
11.2 Solution of the Quadratic Programming Subproblem
11.3 The Merit Function
11.4 The Quasi-Newton Update
▸▿ 12 Optional Parameters
12.1 Description of the Optional Parameters
13 Description of Monitoring Information

1 Purpose

E04UFF/E04UFA is designed to minimize an arbitrary smooth function subject to constraints (which may include simple bounds on the variables, linear constraints and smooth nonlinear constraints) using a sequential quadratic programming (SQP) method. You should supply as many first derivatives as possible; any unspecified derivatives are approximated by finite differences. It is not intended for large sparse problems.
E04UFF/E04UFA may also be used for unconstrained, bound-constrained and linearly constrained optimization.
E04UFF/E04UFA uses reverse communication for evaluating the objective function, the nonlinear constraint functions and any of their derivatives.
E04UFA is a version of E04UFF that has additional arguments in order to make it safe for use in multithreaded applications (see Section 5). The initialization routine E04WBF must have been called before calling E04UFA.

2 Specification

2.1 Specification for E04UFF

SUBROUTINE E04UFF ( IREVCM, N, NCLIN, NCNLN, LDA, LDCJ, LDR, A, BL, BU, ITER, ISTATE, C, CJAC, CLAMDA, OBJF, OBJGRD, R, X, NEEDC, IWORK, LIWORK, WORK, LWORK, IFAIL)
INTEGER | IREVCM, N, NCLIN, NCNLN, LDA, LDCJ, LDR, ITER, ISTATE(N+NCLIN+NCNLN), NEEDC(max(1,NCNLN)), IWORK(LIWORK), LIWORK, LWORK, IFAIL
REAL (KIND=nag_wp) | A(LDA,*), BL(N+NCLIN+NCNLN), BU(N+NCLIN+NCNLN), C(*), CJAC(LDCJ,*), CLAMDA(N+NCLIN+NCNLN), OBJF, OBJGRD(N), R(LDR,N), X(N), WORK(LWORK)

2.2 Specification for E04UFA

SUBROUTINE E04UFA ( IREVCM, N, NCLIN, NCNLN, LDA, LDCJ, LDR, A, BL, BU, ITER, ISTATE, C, CJAC, CLAMDA, OBJF, OBJGRD, R, X, NEEDC, IWORK, LIWORK, WORK, LWORK, CWSAV, LWSAV, IWSAV, RWSAV, IFAIL)
INTEGER | IREVCM, N, NCLIN, NCNLN, LDA, LDCJ, LDR, ITER, ISTATE(N+NCLIN+NCNLN), NEEDC(max(1,NCNLN)), IWORK(LIWORK), LIWORK, LWORK, IWSAV(610), IFAIL
REAL (KIND=nag_wp) | A(LDA,*), BL(N+NCLIN+NCNLN), BU(N+NCLIN+NCNLN), C(*), CJAC(LDCJ,*), CLAMDA(N+NCLIN+NCNLN), OBJF, OBJGRD(N), R(LDR,N), X(N), WORK(LWORK), RWSAV(475)
LOGICAL | LWSAV(120)
CHARACTER(80) | CWSAV(5)
Before calling E04UFA, or either of the option setting routines E04UDA or E04UEA, E04WBF must be called. The specification for E04WBF is:
SUBROUTINE E04WBF ( RNAME, CWSAV, LCWSAV, LWSAV, LLWSAV, IWSAV, LIWSAV, RWSAV, LRWSAV, IFAIL)
INTEGER | LCWSAV, LLWSAV, IWSAV(LIWSAV), LIWSAV, LRWSAV, IFAIL
REAL (KIND=nag_wp) | RWSAV(LRWSAV)
LOGICAL | LWSAV(LLWSAV)
CHARACTER(*) | RNAME
CHARACTER(80) | CWSAV(LCWSAV)
E04WBF should be called with RNAME='E04UFA'. CWSAV must have a length of LCWSAV while the lengths of LWSAV, IWSAV and RWSAV should be LLWSAV, LIWSAV and LRWSAV, respectively. These arguments must satisfy the following constraints:
  • LCWSAV≥5
  • LLWSAV≥120
  • LIWSAV≥610
  • LRWSAV≥475
The contents of the arrays CWSAV, LWSAV, IWSAV and RWSAV must not be altered between calling routines E04UDA, E04UEA, E04UFA or E04WBF.

3 Description

E04UFF/E04UFA is designed to solve the nonlinear programming problem – the minimization of a smooth nonlinear function subject to a set of constraints on the variables. The problem is assumed to be stated in the following form:
minimize x∈Rn ​ ​ F x   subject to   l ≤ x AL x c x ≤u, (1)
where F x (the objective function) is a nonlinear function, AL is an nL by n constant matrix, and c x is an nN element vector of nonlinear constraint functions. (The matrix AL and the vector c x may be empty.) The objective function and the constraint functions are assumed to be smooth, i.e., at least twice-continuously differentiable. (The method of E04UFF/E04UFA will usually solve (1) if there are only isolated discontinuities away from the solution.)
Note that although the bounds on the variables could be included in the definition of the linear constraints, we prefer to distinguish between them for reasons of computational efficiency. For the same reason, the linear constraints should not be included in the definition of the nonlinear constraints. Upper and lower bounds are specified for all the variables and for all the constraints. An equality constraint can be specified by setting li=ui. If certain bounds are not present, the associated elements of l or u can be set to special values that will be treated as -∞ or +∞. (See the description of the optional parameter Infinite Bound Size.)
If there are no nonlinear constraints in (1) and F is linear or quadratic then it will generally be more efficient to use one of E04MFF/E04MFA, E04NCF/E04NCA or E04NFF/E04NFA, or E04NQF if the problem is large and sparse. If the problem is large and sparse and does have nonlinear constraints, E04UGF/E04UGA should be used, since E04UFF/E04UFA treats all matrices as dense.
E04UFF/E04UFA uses reverse communication for evaluating F x, c x and as many of their first partial derivatives as possible; any remaining derivatives are approximated by finite differences. See the description of the optional parameter Derivative Level.
On initial entry, you must supply an initial estimate of the solution to (1).
On intermediate exits, the calling program must compute appropriate values for the objective function, the nonlinear constraints or their derivatives, as specified by the argument IREVCM, and then re-enter the routine.
For maximum reliability, it is preferable to provide all partial derivatives (see Chapter 8 of Gill et al. (1981), for a detailed discussion). If they cannot all be provided, it is advisable to provide as many as possible. While developing code to evaluate the objective function and the constraints, the optional parameter Verify should be used to check the calculation of any known derivatives.
The method used by E04UFF/E04UFA is described in detail in Section 11.
E04WDF is an alternative routine which uses a similar method, but with direct communication: that is, the objective and constraint functions are evaluated by subroutines, supplied as arguments to the routine.

4 References

Dennis J E Jr and Moré J J (1977) Quasi-Newton methods, motivation and theory SIAM Rev. 19 46–89
Dennis J E Jr and Schnabel R B (1981) A new derivation of symmetric positive-definite secant updates nonlinear programming (eds O L Mangasarian, R R Meyer and S M Robinson) 4 167–199 Academic Press
Dennis J E Jr and Schnabel R B (1983) Numerical Methods for Unconstrained Optimization and Nonlinear Equations Prentice–Hall
Fletcher R (1987) Practical Methods of Optimization (2nd Edition) Wiley
Gill P E, Hammarling S, Murray W, Saunders M A and Wright M H (1986) Users' guide for LSSOL (Version 1.0) Report SOL 86-1 Department of Operations Research, Stanford University
Gill P E, Murray W, Saunders M A and Wright M H (1984a) Procedures for optimization problems with a mixture of bounds and general linear constraints ACM Trans. Math. Software 10 282–298
Gill P E, Murray W, Saunders M A and Wright M H (1984b) Users' guide for SOL/QPSOL version 3.2 Report SOL 84–5 Department of Operations Research, Stanford University
Gill P E, Murray W, Saunders M A and Wright M H (1986a) Some theoretical properties of an augmented Lagrangian merit function Report SOL 86–6R Department of Operations Research, Stanford University
Gill P E, Murray W, Saunders M A and Wright M H (1986b) Users' guide for NPSOL (Version 4.0): a Fortran package for nonlinear programming Report SOL 86-2 Department of Operations Research, Stanford University
Gill P E, Murray W and Wright M H (1981) Practical Optimization Academic Press
Hock W and Schittkowski K (1981) Test Examples for Nonlinear Programming Codes. Lecture Notes in Economics and Mathematical Systems 187 Springer–Verlag
Murtagh B A and Saunders M A (1983) MINOS 5.0 user's guide Report SOL 83-20 Department of Operations Research, Stanford University
Powell M J D (1974) Introduction to constrained optimization Numerical Methods for Constrained Optimization (eds P E Gill and W Murray) 1–28 Academic Press
Powell M J D (1983) Variable metric methods in constrained optimization Mathematical Programming: the State of the Art (eds A Bachem, M Grötschel and B Korte) 288–311 Springer–Verlag

5 Arguments

Note: this routine uses reverse communication. Its use involves an initial entry, intermediate exits and re-entries, and a final exit, as indicated by the argument IREVCM. Between intermediate exits and re-entries, all arguments other than those specified by the value of IREVCM must remain unchanged.
1:   IREVCM – INTEGERInput/Output
On initial entry: must be set to 0.
On intermediate exit: specifies what values the calling program must assign to arguments of E04UFF/E04UFA before re-entering the routine.
IREVCM=1
Set OBJF to the value of the objective function F x.
IREVCM=2
Set OBJGRD j to the value ∂F ∂xj if available, for j=1,2,…,n.
IREVCM=3
Set OBJF and OBJGRD j as for IREVCM=1 and IREVCM=2.
IREVCM=4
Set C i to the value of the constraint function ci x, for each i such that NEEDC i>0.
IREVCM=5
Set CJAC ij to the value ∂ci ∂xj if available, for each i such that NEEDC i>0 and j=1,2,…,n.
IREVCM=6
Set C i and CJAC ij as for IREVCM=4 and IREVCM=5.
On intermediate re-entry: must remain unchanged, unless you wish to terminate the solution to the current problem. In this case IREVCM may be set to a negative value and then E04UFF/E04UFA will take a final exit with IFAIL set to this value of IREVCM.
On final exit: IREVCM=0.
Constraint: IREVCM≤6.
2:   N – INTEGERInput
On initial entry: n, the number of variables.
Constraint: N>0.
3:   NCLIN – INTEGERInput
On initial entry: nL, the number of general linear constraints.
Constraint: NCLIN≥0.
4:   NCNLN – INTEGERInput
On initial entry: nN, the number of nonlinear constraints.
Constraint: NCNLN≥0.
5:   LDA – INTEGERInput
On initial entry: the first dimension of the array A as declared in the (sub)program from which E04UFF/E04UFA is called.
Constraint: LDA≥max 1,NCLIN.
6:   LDCJ – INTEGERInput
On initial entry: the first dimension of the array CJAC as declared in the (sub)program from which E04UFF/E04UFA is called.
Constraint: LDCJ≥max 1,NCNLN.
7:   LDR – INTEGERInput
On initial entry: the first dimension of the array R as declared in the (sub)program from which E04UFF/E04UFA is called.
Constraint: LDR≥N.
8:   A LDA* – REAL (KIND=nag_wp) arrayInput
Note: the second dimension of the array A must be at least N if NCLIN>0, and at least 1 otherwise.
On initial entry: the ith row of the matrix AL of general linear constraints in (1) must be stored in A ij, for i=1,2,…,NCLIN and j=1,2,…,N. That is, the ith row contains the coefficients of the ith general linear constraint, for i=1,2,…,NCLIN.
If NCLIN=0, the array A is not referenced.
9:   BL N+NCLIN+NCNLN – REAL (KIND=nag_wp) arrayInput
10:   BU N+NCLIN+NCNLN – REAL (KIND=nag_wp) arrayInput
On initial entry: BL must contain the lower bounds and BU the upper bounds, for all the constraints in the following order. The first n elements of each array must contain the bounds on the variables, the next nL elements the bounds for the general linear constraints (if any) and the next nN elements the bounds for the general nonlinear constraints (if any). To specify a nonexistent lower bound (i.e., lj=-∞), set BL j≤-bigbnd, and to specify a nonexistent upper bound (i.e., uj=+∞), set BU j≥bigbnd; the default value of bigbnd is 1020, but this may be changed by the optional parameter Infinite Bound Size. To specify the jth constraint as an equality, set BL j=BU j=β, say, where β<bigbnd.
Constraints:
  • BL j≤BU j, for j=1,2,…,N+NCLIN+NCNLN;
  • if BL j=BU j=β, β<bigbnd.
11:   ITER – INTEGERInput/Output
On intermediate re-entry: must remain unchanged from a previous call to E04UFF/E04UFA.
On final exit: the number of major iterations performed.
12:   ISTATE N+NCLIN+NCNLN – INTEGER arrayInput/Output
On initial entry: need not be set if the (default) optional parameter Cold Start is used.
If the optional parameter Warm Start has been chosen, the elements of ISTATE corresponding to the bounds and linear constraints define the initial working set for the procedure that finds a feasible point for the linear constraints and bounds. The active set at the conclusion of this procedure and the elements of ISTATE corresponding to nonlinear constraints then define the initial working set for the first QP subproblem. More precisely, the first n elements of ISTATE refer to the upper and lower bounds on the variables, the next nL elements refer to the upper and lower bounds on AL x, and the next nN elements refer to the upper and lower bounds on c x. Possible values for ISTATE j are as follows:
ISTATE j | Meaning
0 | The corresponding constraint is not in the initial QP working set.
1 | This inequality constraint should be in the working set at its lower bound.
2 | This inequality constraint should be in the working set at its upper bound.
3 | This equality constraint should be in the initial working set. This value must not be specified unless BL j=BU j.
The values -2, -1 and 4 are also acceptable but will be modified by the routine. If E04UFF/E04UFA has been called previously with the same values of N, NCLIN and NCNLN, ISTATE already contains satisfactory information. (See also the description of the optional parameter Warm Start.) The routine also adjusts (if necessary) the values supplied in X to be consistent with ISTATE.
Constraint: -2≤ISTATE j≤4, for j=1,2,…,N+NCLIN+NCNLN.
On final exit: the status of the constraints in the QP working set at the point returned in X. The significance of each possible value of ISTATE j is as follows:
ISTATE j | Meaning
-2 | This constraint violates its lower bound by more than the appropriate feasibility tolerance (see the optional parameters Linear Feasibility Tolerance and Nonlinear Feasibility Tolerance). This value can occur only when no feasible point can be found for a QP subproblem.
-1 | This constraint violates its upper bound by more than the appropriate feasibility tolerance (see the optional parameters Linear Feasibility Tolerance and Nonlinear Feasibility Tolerance). This value can occur only when no feasible point can be found for a QP subproblem.
-0 | The constraint is satisfied to within the feasibility tolerance, but is not in the QP working set.
-1 | This inequality constraint is included in the QP working set at its lower bound.
-2 | This inequality constraint is included in the QP working set at its upper bound.
-3 | This constraint is included in the QP working set as an equality. This value of ISTATE can occur only when BL j=BU j.
13:   C* – REAL (KIND=nag_wp) arrayInput/Output
Note: the dimension of the array C must be at least max 1,NCNLN.
On initial entry: need not be set.
On intermediate re-entry: if IREVCM=4 or 6 and NEEDC i>0, C i must contain the value of the ith constraint at x. The remaining elements of C, corresponding to the non-positive elements of NEEDC, are ignored.
On final exit: if NCNLN>0, C i contains the value of the ith nonlinear constraint function ci at the final iterate, for i=1,2,…,NCNLN.
If NCNLN=0, the array C is not referenced.
14:   CJAC LDCJ* – REAL (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array CJAC must be at least N if NCNLN>0, and at least 1 otherwise.
On initial entry: in general, CJAC need not be initialized before the call to E04UFF/E04UFA. However, if the optional parameter Derivative Level=2 or 3, you may optionally set the constant elements of CJAC. Such constant elements need not be re-assigned on subsequent intermediate exits.
If all elements of the constraint Jacobian are known (i.e., Derivative Level=2 or 3), any constant elements may be assigned to CJAC one time only at the start of the optimization. An element of CJAC that is not subsequently assigned during an intermediate exit will retain its initial value throughout. Constant elements may be loaded into CJAC either before the call to E04UFF/E04UFA or during the first intermediate exit. The ability to preload constants is useful when many Jacobian elements are identically zero, in which case CJAC may be initialized to zero and nonzero elements may be reset during intermediate exits.
On intermediate re-entry: if IREVCM=5 or 6 and NEEDC i>0, the ith row of CJAC must contain the available elements of the vector ∇ci given by
∇ci= ∂ci ∂x 1 , ∂ci ∂x 2 ,…, ∂ci ∂xn T,
where ∂ci ∂xj is the partial derivative of the ith constraint with respect to the jth variable, evaluated at the point x. The remaining rows of CJAC, corresponding to non-positive elements of NEEDC, are ignored. The ith row of the Jacobian should be stored in elements CJAC ij, for i=1,2,…,NCNLN and j=1,2,…,N.
Note that constant nonzero elements do affect the values of the constraints. Thus, if CJAC ij is set to a constant value, it need not be reset during subsequent intermediate exits, but the value CJAC ij×X j must nonetheless be added to C i. For example, if CJAC 11=2 and CJAC 12=-5, then the term 2×X 1-5×X 2 must be included in the definition of C 1.
It must be emphasized that, if Derivative Level=0 or 1, unassigned elements of CJAC are not treated as constant; they are estimated by finite differences, at nontrivial expense. If you do not supply a value for the optional parameter Difference Interval, an interval for each element of x is computed automatically at the start of the optimization. The automatic procedure can usually identify constant elements of CJAC, which are then computed once only by finite differences.
See also the description of the optional parameter Verify.
On final exit: if NCNLN>0, CJAC contains the Jacobian matrix of the nonlinear constraint functions at the final iterate, i.e., CJAC ij contains the partial derivative of the ith constraint function with respect to the jth variable, for i=1,2,…,NCNLN and j=1,2,…,N.
If NCNLN=0, the array CJAC is not referenced.
15:   CLAMDA N+NCLIN+NCNLN – REAL (KIND=nag_wp) arrayInput/Output
On initial entry: need not be set if the (default) optional parameter Cold Start is used.
If the optional parameter Warm Start has been chosen, CLAMDA j must contain a multiplier estimate for each nonlinear constraint with a sign that matches the status of the constraint specified by the ISTATE array, for j=N+NCLIN+1,…,N+NCLIN+NCNLN. The remaining elements need not be set. Note that if the jth constraint is defined as ‘inactive’ by the initial value of the ISTATE array (i.e. ISTATE j=0), CLAMDA j should be zero; if the jth constraint is an inequality active at its lower bound (i.e. ISTATE j=1), CLAMDA j should be non-negative; if the jth constraint is an inequality active at its upper bound (i.e. ISTATE j=2), CLAMDA j should be non-positive. If necessary, the routine will modify CLAMDA to match these rules.
On final exit: the values of the QP multipliers from the last QP subproblem. CLAMDA j should be non-negative if ISTATE j=1 and non-positive if ISTATE j=2.
16:   OBJF – REAL (KIND=nag_wp)Input/Output
On initial entry: need not be set.
On intermediate re-entry: if IREVCM=1 or 3, OBJF must be set to the value of the objective function at x.
On final exit: the value of the objective function at the final iterate.
17:   OBJGRD N – REAL (KIND=nag_wp) arrayInput/Output
On initial entry: need not be set.
On intermediate re-entry: if IREVCM=2 or 3, OBJGRD must contain the available elements of the gradient evaluated at x.
See also the description of the optional parameter Verify.
On final exit: the gradient of the objective function at the final iterate (or its finite difference approximation).
18:   R LDRN – REAL (KIND=nag_wp) arrayInput/Output
On initial entry: need not be initialized if the (default) optional parameter Cold Start is used.
If the optional parameter Warm Start has been chosen, R must contain the upper triangular Cholesky factor R of the initial approximation of the Hessian of the Lagrangian function, with the variables in the natural order. Elements not in the upper triangular part of R are assumed to be zero and need not be assigned.
On final exit: if Hessian=NO, R contains the upper triangular Cholesky factor R of QT H~Q, an estimate of the transformed and reordered Hessian of the Lagrangian at x (see (6) in Section 11.1).
If Hessian=YES, R contains the upper triangular Cholesky factor R of H, the approximate (untransformed) Hessian of the Lagrangian, with the variables in the natural order.
19:   X N – REAL (KIND=nag_wp) arrayInput/Output
On initial entry: an initial estimate of the solution.
On intermediate exit: the point x at which the objective function, constraint functions or their derivatives are to be evaluated.
On final exit: the final estimate of the solution.
20:   NEEDC max 1,NCNLN – INTEGER arrayOutput
On intermediate exit: if IREVCM≥4, NEEDC specifies the indices of the elements of C and/or CJAC that must be assigned. If NEEDC i>0, then the ith element of C and/or the available elements of the ith row of CJAC must be evaluated at x.
21:   IWORK LIWORK – INTEGER arrayCommunication Array
22:   LIWORK – INTEGERInput
On initial entry: the dimension of the array IWORK as declared in the (sub)program from which E04UFF/E04UFA is called.
Constraint: LIWORK≥3×N+NCLIN+2×NCNLN.
23:   WORK LWORK – REAL (KIND=nag_wp) arrayCommunication Array
24:   LWORK – INTEGERInput
On initial entry: the dimension of the array WORK as declared in the (sub)program from which E04UFF/E04UFA is called.
Constraints:
  • if NCNLN=0 and NCLIN=0, LWORK≥21×N+2;
  • if NCNLN=0 and NCLIN>0, LWORK≥2×N 2+21×N+11×NCLIN+2;
  • if NCNLN>0 and NCLIN≥0, LWORK≥2×N 2+N×NCLIN+2×N×NCNLN+21×N+11×NCLIN+22×NCNLN+1.
The amounts of workspace provided and required may be (by default for E04UFF) output on the current advisory message unit (as defined by X04ABF). As an alternative to computing LIWORK and LWORK from the formulae given above, you may prefer to obtain appropriate values from the output of a preliminary run with LIWORK and LWORK set to 1. (E04UFF/E04UFA will then terminate with IFAIL=9.)
25:   IFAIL – INTEGERInput/Output
Note: for E04UFA, IFAIL does not occur in this position in the argument list. See the additional arguments described below.
On initial entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, because for this routine the values of the output arguments may be useful even if IFAIL≠0 on exit, the recommended value is -1. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On final exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).
E04UFF/E04UFA returns with IFAIL=0 if the iterates have converged to a point x that satisfies the first-order Kuhn–Tucker conditions (see Section 11.1) to the accuracy requested by the optional parameter Optimality Tolerance. This has default value=εr 0.8, where εr is the value of the optional parameter Function Precision (default value=ε 0.9, where ε is the machine precision). That is IFAIL=0 when the projected gradient and active constraint residuals are negligible at x.
You should check whether the following four conditions are satisfied:
(i) | the final value of Norm Gz (see Section 9.1) is significantly less than that at the starting point;
(ii) | during the final major iterations, the values of Step and Mnr (see Section 9.1) are both one;
(iii) | the last few values of both Norm Gz and Violtn (see Section 9.1) become small at a fast linear rate; and
(iv) | Cond Hz (see Section 9.1) is small.
If all these conditions hold, x is almost certainly a local minimum of (1).
Note: the following are additional arguments for specific use with E04UFA. Users of E04UFF therefore need not read the remainder of this description.
25:   CWSAV 5 – CHARACTER(80) arrayCommunication Array
26:   LWSAV 120 – LOGICAL arrayCommunication Array
27:   IWSAV 610 – INTEGER arrayCommunication Array
28:   RWSAV 475 – REAL (KIND=nag_wp) arrayCommunication Array
The arrays LWSAV, IWSAV, RWSAV and CWSAV must not be altered between calls to any of the routines E04WBF, E04UFA, E04UDA or E04UEA.
29:   IFAIL – INTEGERInput/Output
Note: see the argument description for IFAIL above.

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Note: E04UFF/E04UFA may return useful information for one or more of the following detected errors or warnings.
Errors or warnings detected by the routine:
IFAIL<0
A negative value of IFAIL indicates an exit from E04UFF/E04UFA because you set IREVCM<0 during an intermediate exit. The value of IFAIL will be the same as your setting of IREVCM.
IFAIL=1
The final iterate x satisfies the first-order Kuhn–Tucker conditions (see Section 11.1) to the accuracy requested, but the sequence of iterates has not yet converged. E04UFF/E04UFA was terminated because no further improvement could be made in the merit function (see Section 9.1).
This value of IFAIL may occur in several circumstances. The most common situation is that you ask for a solution with accuracy that is not attainable with the given precision of the problem (as specified by the optional parameter Function Precision). This condition will also occur if, by chance, an iterate is an ‘exact’ Kuhn–Tucker point, but the change in the variables was significant at the previous iteration. (This situation often happens when minimizing very simple functions, such as quadratics.)
If the four conditions listed in Section 5 for IFAIL=0 are satisfied, x is likely to be a solution of (1) even if IFAIL=1.
IFAIL=2
E04UFF/E04UFA has terminated without finding a feasible point for the linear constraints and bounds, which means that either no feasible point exists for the given value of the optional parameter Linear Feasibility Tolerance, or no feasible point could be found in the number of iterations specified by the optional parameter Minor Iteration Limit. You should check that there are no constraint redundancies. If the data for the constraints are accurate only to an absolute precision σ, you should ensure that the value of the optional parameter Linear Feasibility Tolerance is greater than σ. For example, if all elements of AL are of order unity and are accurate to only three decimal places, Linear Feasibility Tolerance should be at least 10-3.
IFAIL=3
No feasible point could be found for the nonlinear constraints. The problem may have no feasible solution. This means that there has been a sequence of QP subproblems for which no feasible point could be found (indicated by I at the end of each line of intermediate printout produced by the major iterations; see Section 9.1). This behaviour will occur if there is no feasible point for the nonlinear constraints. (However, there is no general test that can determine whether a feasible point exists for a set of nonlinear constraints.) If the infeasible subproblems occur from the very first major iteration, it is highly likely that no feasible point exists. If infeasibilities occur when earlier subproblems have been feasible, small constraint inconsistencies may be present. You should check the validity of constraints with negative values of ISTATE. If you are convinced that a feasible point does exist, E04UFF/E04UFA should be restarted at a different starting point.
IFAIL=4
The limiting number of iterations (as determined by the optional parameter Major Iteration Limit) has been reached.
If the algorithm appears to be making satisfactory progress, then optional parameter Major Iteration Limit may be too small. If so, either increase its value and rerun E04UFF/E04UFA or, alternatively, rerun E04UFF/E04UFA using the optional parameter Warm Start. If the algorithm seems to be making little or no progress however, then you should check for incorrect gradients or ill-conditioning as described under IFAIL=6.
Note that ill-conditioning in the working set is sometimes resolved automatically by the algorithm, in which case performing additional iterations may be helpful. However, ill-conditioning in the Hessian approximation tends to persist once it has begun, so that allowing additional iterations without altering R is usually inadvisable. If the quasi-Newton update of the Hessian approximation was reset during the latter major iterations (i.e., an R occurs at the end of each line of intermediate printout; see Section 9.1), it may be worthwhile to try a Warm Start at the final point as suggested above.
IFAIL=5
Not used by this routine.
IFAIL=6
x does not satisfy the first-order Kuhn–Tucker conditions (see Section 11.1), and no improved point for the merit function (see Section 9.1) could be found during the final linesearch.
This sometimes occurs because an overly stringent accuracy has been requested, i.e., the value of the optional parameter Optimality Tolerance (default value=εr 0.8, where εr is the value of the optional parameter Function Precision) is too small. In this case you should apply the four tests described under IFAIL=0 to determine whether or not the final solution is acceptable (see Gill et al. (1981), for a discussion of the attainable accuracy).
If many iterations have occurred in which essentially no progress has been made and E04UFF/E04UFA has failed completely to move from the initial point, then values set by the calling program for the objective or constraint functions or their derivatives during intermediate exits may be incorrect. You should refer to comments under IFAIL=7 and check the gradients using the optional parameter Verify. Unfortunately, there may be small errors in the objective and constraint gradients that cannot be detected by the verification process. Finite difference approximations to first derivatives are catastrophically affected by even small inaccuracies. An indication of this situation is a dramatic alteration in the iterates if the finite difference interval is altered. One might also suspect this type of error if a switch is made to central differences even when Norm Gz and Violtn (see Section 9.1) are large.
Another possibility is that the search direction has become inaccurate because of ill-conditioning in the Hessian approximation or the matrix of constraints in the working set; either form of ill-conditioning tends to be reflected in large values of Mnr (the number of iterations required to solve each QP subproblem; see Section 9.1).
If the condition estimate of the projected Hessian (Cond Hz; see Section 9.1) is extremely large, it may be worthwhile rerunning E04UFF/E04UFA from the final point with the optional parameter Warm Start. In this situation, ISTATE and CLAMDA should be left unaltered and R should be reset to the identity matrix.
If the matrix of constraints in the working set is ill-conditioned (i.e., Cond T is extremely large; see Section 13), it may be helpful to run E04UFF/E04UFA with a relaxed value of the optional parameter Feasibility Tolerance. (Constraint dependencies are often indicated by wide variations in size in the diagonal elements of the matrix T, whose diagonals will be printed if Major Print Level≥30.)
IFAIL=7
The user-supplied derivatives of the objective function and/or nonlinear constraints appear to be incorrect.
Large errors were found in the derivatives of the objective function and/or nonlinear constraints. This value of IFAIL will occur if the verification process indicated that at least one gradient or Jacobian element had no correct figures. You should refer to the printed output to determine which elements are suspected to be in error.
As a first-step, you should check that the code for the objective and constraint values is correct – for example, by computing the function at a point where the correct value is known. However, care should be taken that the chosen point fully tests the evaluation of the function. It is remarkable how often the values x=0 or x=1 are used in such a test, and how often the special properties of these numbers make the test meaningless.
Special care should be used in the test if computation of the objective function involves subsidiary data communicated in COMMON storage. Although the first evaluation of the function may be correct, subsequent calculations may be in error because some of the subsidiary data has accidentally been overwritten.
Gradient checking will be ineffective if the objective function uses information computed by the constraints, since they are not necessarily computed before each function evaluation.
Errors in programming the function may be quite subtle in that the function value is ‘almost’ correct. For example, the function may not be accurate to full precision because of the inaccurate calculation of a subsidiary quantity, or the limited accuracy of data upon which the function depends. A common error on machines where numerical calculations are usually performed in double precision is to include even one single precision constant in the calculation of the function; since some compilers do not convert such constants to double precision, half the correct figures may be lost by such a seemingly trivial error.
IFAIL=8
Not used by this routine.
IFAIL=9
An input argument is invalid.
Overflow
If the printed output before the overflow error contains a warning about serious ill-conditioning in the working set when adding the jth constraint, it may be possible to avoid the difficulty by increasing the magnitude of the Linear Feasibility Tolerance and/or the optional parameter Nonlinear Feasibility Tolerance and rerunning the program. If the message recurs even after this change, the offending linearly dependent constraint (with index ‘j’) must be removed from the problem. If overflow occurs in one of the user-supplied subroutines (e.g., if the nonlinear functions involve exponentials or singularities), it may help to specify tighter bounds for some of the variables (i.e., reduce the gap between the appropriate lj and uj).
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

If IFAIL=0 on final exit then the vector returned in the array X is an estimate of the solution to an accuracy of approximately Optimality Tolerance (default value=ε 0.8, where ε is the machine precision).

8 Parallelism and Performance

E04UFF/E04UFA is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
E04UFF/E04UFA makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

9.1 Description of the Printed Output

This section describes the intermediate printout and final printout produced by E04UFF/E04UFA. The intermediate printout is a subset of the monitoring information produced by E04UFF/E04UFA at every iteration (see Section 13). You can control the level of printed output (see the description of the optional parameter Major Print Level). Note that the intermediate printout and final printout are produced only if Major Print Level≥10 (the default for E04UFF, by default no output is produced by E04UFA).
The following line of summary output (<80 characters) is produced at every major iteration. In all cases, the values of the quantities printed are those in effect on completion of the given iteration.
Maj | is the major iteration count.
Mnr is the number of minor iterations required by the feasibility and optimality phases of the QP subproblem. Generally, Mnr will be 1 in the later iterations, since theoretical analysis predicts that the correct active set will be identified near the solution (see Section 11).
Note that Mnr may be greater than the optional parameter Minor Iteration Limit if some iterations are required for the feasibility phase.
Step | is the step αk taken along the computed search direction. On reasonably well-behaved problems, the unit step (i.e., αk=1) will be taken as the solution is approached.
Merit Function is the value of the augmented Lagrangian merit function (12) at the current iterate. This function will decrease at each iteration unless it was necessary to increase the penalty parameters (see Section 11.3). As the solution is approached, Merit Function will converge to the value of the objective function at the solution.
If the QP subproblem does not have a feasible point (signified by I at the end of the current output line) then the merit function is a large multiple of the constraint violations, weighted by the penalty parameters. During a sequence of major iterations with infeasible subproblems, the sequence of Merit Function values will decrease monotonically until either a feasible subproblem is obtained or E04UFF/E04UFA terminates with IFAIL=3 (no feasible point could be found for the nonlinear constraints).
If there are no nonlinear constraints present (i.e., NCNLN=0) then this entry contains Objective, the value of the objective function F x. The objective function will decrease monotonically to its optimal value when there are no nonlinear constraints.
Norm Gz | is ZT gFR, the Euclidean norm of the projected gradient (see Section 11.2). Norm Gz will be approximately zero in the neighbourhood of a solution.
Violtn | is the Euclidean norm of the residuals of constraints that are violated or in the predicted active set (not printed if NCNLN is zero). Violtn will be approximately zero in the neighbourhood of a solution.
Cond Hz | is a lower bound on the condition number of the projected Hessian approximation HZ ( HZ = ZT HFR Z = RZT RZ ; see (6)). The larger this number, the more difficult the problem.
M | is printed if the quasi-Newton update has been modified to ensure that the Hessian approximation is positive definite (see Section 11.4).
I | is printed if the QP subproblem has no feasible point.
C | is printed if central differences have been used to compute the unspecified objective and constraint gradients. If the value of Step is zero then the switch to central differences was made because no lower point could be found in the linesearch. (In this case, the QP subproblem is resolved with the central difference gradient and Jacobian.) If the value of Step is nonzero then central differences were computed because Norm Gz and Violtn imply that x is close to a Kuhn–Tucker point (see Section 11.1).
L | is printed if the linesearch has produced a relative change in x greater than the value defined by the optional parameter Step Limit. If this output occurs frequently during later iterations of the run, optional parameter Step Limit should be set to a larger value.
R | is printed if the approximate Hessian has been refactorized. If the diagonal condition estimator of R indicates that the approximate Hessian is badly conditioned then the approximate Hessian is refactorized using column interchanges. If necessary, R is modified so that its diagonal condition estimator is bounded.
The final printout includes a listing of the status of every variable and constraint.
The following describes the printout for each variable. A full stop (.) is printed for any numerical value that is zero.
Varbl | gives the name (V) and index j, for j=1,2,…,n, of the variable.
State gives the state of the variable (FR if neither bound is in the working set, EQ if a fixed variable, LL if on its lower bound, UL if on its upper bound, TF if temporarily fixed at its current value). If Value lies outside the upper or lower bounds by more than the Feasibility Tolerance, State will be ++ or -- respectively.
A key is sometimes printed before State.
A | Alternative optimum possible. The variable is active at one of its bounds, but its Lagrange multiplier is essentially zero. This means that if the variable were allowed to start moving away from its bound then there would be no change to the objective function. The values of the other free variables might change, giving a genuine alternative solution. However, if there are any degenerate variables (labelled D), the actual change might prove to be zero, since one of them could encounter a bound immediately. In either case the values of the Lagrange multipliers might also change.
D | Degenerate. The variable is free, but it is equal to (or very close to) one of its bounds.
I | Infeasible. The variable is currently violating one of its bounds by more than the Feasibility Tolerance.
Value | is the value of the variable at the final iteration.
Lower Bound | is the lower bound specified for the variable. None indicates that BL j≤-bigbnd.
Upper Bound | is the upper bound specified for the variable. None indicates that BU j≥bigbnd.
Lagr Mult | is the Lagrange multiplier for the associated bound. This will be zero if State is FR unless BL j≤-bigbnd and BU j≥bigbnd, in which case the entry will be blank. If x is optimal, the multiplier should be non-negative if State is LL and non-positive if State is UL.
Slack | is the difference between the variable Value and the nearer of its (finite) bounds BL j and BU j. A blank entry indicates that the associated variable is not bounded (i.e., BL j≤-bigbnd and BU j≥bigbnd).
The meaning of the printout for linear and nonlinear constraints is the same as that given above for variables, with ‘variable’ replaced by ‘constraint’, BL j and BU j replaced by BL n+j and BU n+j respectively and with the following changes in the heading:
L Con | gives the name (L) and index j, for j=1,2,…,nL, of the linear constraint.
N Con | gives the name (N) and index (j-nL), for j=nL+1,…,nL+nN, of the nonlinear constraint.
Note that movement off a constraint (as opposed to a variable moving away from its bound) can be interpreted as allowing the entry in the Slack column to become positive.
Numerical values are output with a fixed number of digits; they are not guaranteed to be accurate to this precision.

10 Example

This is based on Problem 71 in Murtagh and Saunders (1983) and involves the minimization of the nonlinear function
F x=x 1x 4 x 1+x 2+x 3+x 3
subject to the bounds
1≤x 1≤ 5 1≤x 2≤ 5 1≤x 3≤ 5 1≤x 4≤ 5
to the general linear constraint
x 1+x 2+x 3+x 4≤20,
and to the nonlinear constraints
x 12+x 22+x 32+x 42≤ 40, x 1x 2x 3x 4≥ 25.
The initial point, which is infeasible, is
x 0=1,5,5,1 T,
and F x 0=16.
The optimal solution (to five figures) is
x*=1.0,4.7430,3.8211,1.3794 T,
and F x*=17.014. One bound constraint and both nonlinear constraints are active at the solution.

10.1 Program Text

Note: the following programs illustrate the use of E04UFF and E04UFA.

Program Text (e04uffe.f90)

Program Text (e04ufae.f90)

10.2 Program Data

Program Data (e04uffe.d)

Program Data (e04ufae.d)

10.3 Program Results

Program Results (e04uffe.r)

Program Results (e04ufae.r)

Note: the remainder of this document is intended for more advanced users. Section 11 contains a detailed description of the algorithm which may be needed in order to understand Sections 12 and 13. Section 12 describes the optional parameters which may be set by calls to E04UDF/E04UDA and/or E04UEF/E04UEA. Section 13 describes the quantities which can be requested to monitor the course of the computation.

11 Algorithmic Details

This section contains a detailed description of the method used by E04UFF/E04UFA.

11.1 Overview

E04UFF/E04UFA is essentially identical to the subroutine NPSOL described in Gill et al. (1986b).
At a solution of (1), some of the constraints will be active, i.e., satisfied exactly. An active simple bound constraint implies that the corresponding variable is fixed at its bound, and hence the variables are partitioned into fixed and free variables. Let C denote the m by n matrix of gradients of the active general linear and nonlinear constraints. The number of fixed variables will be denoted by nFX , with nFR ( nFR = n-nFX ) the number of free variables. The subscripts ‘FX’ and ‘FR’ on a vector or matrix will denote the vector or matrix composed of the elements corresponding to fixed or free variables.
A point x is a first-order Kuhn–Tucker point for (1) (see Powell (1974)) if the following conditions hold:
(i) | x is feasible;
(ii) there exist vectors ξ and λ (the Lagrange multiplier vectors for the bound and general constraints) such that
g=CT λ+ξ (2)
where g is the gradient of F evaluated at x and ξj=0 if the jth variable is free.
(iii) | the Lagrange multiplier corresponding to an inequality constraint active at its lower bound must be non-negative. It is non-positive for an inequality constraint active at its upper bound.
Let Z denote a matrix whose columns form a basis for the set of vectors orthogonal to the rows of CFR; i.e., CFR Z=0. An equivalent statement of the condition (2) in terms of Z is
ZT gFR=0.
The vector ZT gFR is termed the projected gradient of F at x. Certain additional conditions must be satisfied in order for a first-order Kuhn–Tucker point to be a solution of (1) (see Powell (1974)).
E04UFF/E04UFA implements a sequential quadratic programming (SQP) method. For an overview of SQP methods, see Fletcher (1987), Gill et al. (1981) and Powell (1983).
The basic structure of E04UFF/E04UFA involves major and minor iterations. The major iterations generate a sequence of iterates xk that converge to x*, a first-order Kuhn–Tucker point of (1). At a typical major iteration, the new iterate x- is defined by
x-=x+αp (3)
where x is the current iterate, the non-negative scalar α is the step length, and p is the search direction. (For simplicity, we shall always consider a typical iteration and avoid reference to the index of the iteration.) Also associated with each major iteration are estimates of the Lagrange multipliers and a prediction of the active set.
The search direction p in (3) is the solution of a quadratic programming subproblem of the form
minimizep gT p+ 12 pT H p   subject to   l- ≤ p AL p AN p ≤ u- , (4)
where g is the gradient of F at x, the matrix H is a positive definite quasi-Newton approximation to the Hessian of the Lagrangian function (see Section 11.4), and AN is the Jacobian matrix of c evaluated at x. (Finite difference estimates may be used for g and AN; see the optional parameter Derivative Level.) Let l in (1) be partitioned into three sections: lB, lL and lN, corresponding to the bound, linear and nonlinear constraints. The vector l- in (4) is similarly partitioned and is defined as
l-B=lB-x,  l-L=lL-AL x,   and  l-N=lN-c,
where c is the vector of nonlinear constraints evaluated at x. The vector u- is defined in an analogous fashion.
The estimated Lagrange multipliers at each major iteration are the Lagrange multipliers from the subproblem (4) (and similarly for the predicted active set). (The numbers of bounds, general linear and nonlinear constraints in the QP active set are the quantities Bnd, Lin and Nln in the monitoring file output of E04UFF/E04UFA; see Section 13.) In E04UFF/E04UFA, (4) is solved using E04NCF/E04NCA. Since solving a quadratic program is itself an iterative procedure, the minor iterations of E04UFF/E04UFA are the iterations of E04NCF/E04NCA. (More details about solving the subproblem are given in Section 11.2.)
Certain matrices associated with the QP subproblem are relevant in the major iterations. Let the subscripts ‘FX’ and ‘FR’ refer to the predicted fixed and free variables, and let C denote the m by n matrix of gradients of the general linear and nonlinear constraints in the predicted active set. Firstly, we have available the TQ factorization of CFR:
CFRQFR=0 T, (5)
where T is a nonsingular m by m reverse-triangular matrix (i.e., t ij=0 if i+j<m), and the nonsingular nFR by nFR matrix QFR is the product of orthogonal transformations (see Gill et al. (1984b)). Secondly, we have the upper triangular Cholesky factor R of the transformed and reordered Hessian matrix
RT R=HQ≡QT H~Q, (6)
where H~ is the Hessian H with rows and columns permuted so that the free variables are first and Q is the n by n matrix
Q= QFR IFX (7)
with IFX the identity matrix of order nFX. If the columns of QFR are partitioned so that
QFR= Z Y ,
then the nZ (nZ≡nFR-m) columns of Z form a basis for the null space of CFR. The matrix Z is used to compute the projected gradient ZT gFR at the current iterate. (The values Nz and Norm Gz printed by E04UFF/E04UFA give nZ and ZT gFR, see Section 13.)
A theoretical characteristic of SQP methods is that the predicted active set from the QP subproblem (4) is identical to the correct active set in a neighbourhood of x*. In E04UFF/E04UFA, this feature is exploited by using the QP active set from the previous iteration as a prediction of the active set for the next QP subproblem, which leads in practice to optimality of the subproblems in only one iteration as the solution is approached. Separate treatment of bound and linear constraints in E04UFF/E04UFA also saves computation in factorizing CFR and HQ.
Once p has been computed, the major iteration proceeds by determining a step length α that produces a ‘sufficient decrease’ in an augmented Lagrangian merit function (see Section 11.3). Finally, the approximation to the transformed Hessian matrix HQ is updated using a modified BFGS quasi-Newton update (see Section 11.4) to incorporate new curvature information obtained in the move from x to x-.
On entry to E04UFF/E04UFA, an iterative procedure from E04NCF/E04NCA is executed, starting with the user-supplied initial point, to find a point that is feasible with respect to the bounds and linear constraints (using the tolerance specified by the optional parameter Linear Feasibility Tolerance). If no feasible point exists for the bound and linear constraints, (1) has no solution and E04UFF/E04UFA terminates. Otherwise, the problem functions will thereafter be evaluated only at points that are feasible with respect to the bounds and linear constraints. The only exception involves variables whose bounds differ by an amount comparable to the finite difference interval (see the discussion of the optional parameter Difference Interval). In contrast to the bounds and linear constraints, it must be emphasized that the nonlinear constraints will not generally be satisfied until an optimal point is reached.
Facilities are provided to check whether the user-supplied gradients appear to be correct (see the description of the optional parameter Verify). In general, the check is provided at the first point that is feasible with respect to the linear constraints and bounds. However, you may request that the check be performed at the initial point.
In summary, the method of E04UFF/E04UFA first determines a point that satisfies the bound and linear constraints. Thereafter, each iteration includes:
(a) | the solution of a quadratic programming subproblem;
(b) | a linesearch with an augmented Lagrangian merit function; and
(c) | a quasi-Newton update of the approximate Hessian of the Lagrangian function.
These three procedures are described in more detail in Sections 11.2 to 11.4.

11.2 Solution of the Quadratic Programming Subproblem

The search direction p is obtained by solving (4) using E04NCF/E04NCA (see Gill et al. (1986)), which was specifically designed to be used within an SQP algorithm for nonlinear programming.
E04NCF/E04NCA is based on a two-phase (primal) quadratic programming method. The two phases of the method are: finding an initial feasible point by minimizing the sum of infeasibilities (the feasibility phase) and minimizing the quadratic objective function within the feasible region (the optimality phase). The computations in both phases are performed by the same subroutines. The two-phase nature of the algorithm is reflected by changing the function being minimized from the sum of infeasibilities to the quadratic objective function.
In general, a quadratic program must be solved by iteration. Let p denote the current estimate of the solution of (4); the new iterate p- is defined by
p-=p+σd (8)
where, as in (3), σ is a non-negative step length and d is a search direction.
At the beginning of each iteration of E04NCF/E04NCA, a working set is defined of constraints (general and bound) that are satisfied exactly. The vector d is then constructed so that the values of constraints in the working set remain unaltered for any move along d. For a bound constraint in the working set, this property is achieved by setting the corresponding element of d to zero, i.e., by fixing the variable at its bound. As before, the subscripts ‘FX’ and ‘FR’ denote selection of the elements associated with the fixed and free variables.
Let C denote the sub-matrix of rows of
AL AN
corresponding to general constraints in the working set. The general constraints in the working set will remain unaltered if
CFRdFR=0, (9)
which is equivalent to defining dFR as
dFR=Z dZ (10)
for some vector dZ, where Z is the matrix associated with the TQ factorization (5) of CFR.
The definition of dZ in (10) depends on whether the current p is feasible. If not, dZ is zero except for an element γ in the jth position, where j and γ are chosen so that the sum of infeasibilities is decreasing along d. (For further details, see Gill et al. (1986).) In the feasible case, dZ satisfies the equations
RZT RZ dZ = - ZT qFR , (11)
where RZ is the Cholesky factor of ZT HFR Z and q is the gradient of the quadratic objective function q=g+Hp. (The vector ZT qFR is the projected gradient of the QP.) With (11), p+d is the minimizer of the quadratic objective function subject to treating the constraints in the working set as equalities.
If the QP projected gradient is zero, the current point is a constrained stationary point in the subspace defined by the working set. During the feasibility phase, the projected gradient will usually be zero only at a vertex (although it may vanish at non-vertices in the presence of constraint dependencies). During the optimality phase, a zero projected gradient implies that p minimizes the quadratic objective function when the constraints in the working set are treated as equalities. In either case, Lagrange multipliers are computed. Given a positive constant δ of the order of the machine precision, the Lagrange multiplier μj corresponding to an inequality constraint in the working set is said to be optimal if μj≤δ when the jth constraint is at its upper bound, or if μj≥-δ when the associated constraint is at its lower bound. If any multiplier is nonoptimal, the current objective function (either the true objective or the sum of infeasibilities) can be reduced by deleting the corresponding constraint from the working set.
If optimal multipliers occur during the feasibility phase and the sum of infeasibilities is nonzero, no feasible point exists. The QP algorithm will then continue iterating to determine the minimum sum of infeasibilities. At this point, the Lagrange multiplier μj will satisfy -1+δ≤μj≤δ for an inequality constraint at its upper bound, and -δ≤μj≤1+δ for an inequality at its lower bound. The Lagrange multiplier for an equality constraint will satisfy μj≤1+δ.
The choice of step length σ in the QP iteration (8) is based on remaining feasible with respect to the satisfied constraints. During the optimality phase, if p+d is feasible, σ will be taken as unity. (In this case, the projected gradient at p- will be zero.) Otherwise, σ is set to σM, the step to the ‘nearest’ constraint, which is added to the working set at the next iteration.
Each change in the working set leads to a simple change to CFR: if the status of a general constraint changes, a row of CFR is altered; if a bound constraint enters or leaves the working set, a column of CFR changes. Explicit representations are recurred of the matrices T, QFR and R, and of the vectors QT q and QT g.

11.3 The Merit Function

After computing the search direction as described in Section 11.2, each major iteration proceeds by determining a step length α in (3) that produces a ‘sufficient decrease’ in the augmented Lagrangian merit function
L x,λ,s = F x - ∑i λi ci x - si + 12 ∑i ρi ci x - si 2 , (12)
where x, λ and s vary during the linesearch. The summation terms in (12) involve only the nonlinear constraints. The vector λ is an estimate of the Lagrange multipliers for the nonlinear constraints of (1). The non-negative slack variables si allow nonlinear inequality constraints to be treated without introducing discontinuities. The solution of the QP subproblem (4) provides a vector triple that serves as a direction of search for the three sets of variables. The non-negative vector ρ of penalty parameters is initialized to zero at the beginning of the first major iteration. Thereafter, selected elements are increased whenever necessary to ensure descent for the merit function. Thus, the sequence of norms of ρ (the printed quantity Penalty; see Section 13) is generally nondecreasing, although each ρi may be reduced a limited number of times.
The merit function (12) and its global convergence properties are described in Gill et al. (1986a).

11.4 The Quasi-Newton Update

The matrix H in (4) is a positive definite quasi-Newton approximation to the Hessian of the Lagrangian function. (For a review of quasi-Newton methods, see Dennis and Schnabel (1983).) At the end of each major iteration, a new Hessian approximation H- is defined as a rank-two modification of H. In E04UFF/E04UFA, the BFGS (Broyden–Fletcher–Goldfarb–Shanno) quasi-Newton update is used:
H-=H-1 sT Hs Hs sT H+1 yT s y yT, (13)
where s=x--x (the change in x).
In E04UFF/E04UFA, H is required to be positive definite. If H is positive definite, H- defined by (13) will be positive definite if and only if yT s is positive (see Dennis and Moré (1977)). Ideally, y in (13) would be taken as yL, the change in gradient of the Lagrangian function
yL = g- - A-NT μN - g + ANT μN , (14)
where μN denotes the QP multipliers associated with the nonlinear constraints of the original problem. If yLT s is not sufficiently positive, an attempt is made to perform the update with a vector y of the form
y=yL+∑i=1 mN ωi ai x^ci x^-ai x ci x,
where ωi≥0. If no such vector can be found, the update is performed with a scaled yL. In this case, M is printed to indicate that the update was modified.
Rather than modifying H itself, the Cholesky factor of the transformed Hessian HQ (6) is updated, where Q is the matrix from (5) associated with the active set of the QP subproblem. The update (13) is equivalent to the following update to HQ:
H-Q = HQ - 1 sQT HQ sQ HQ sQ sQT HQ + 1 yQT sQ yQ yQT , (15)
where yQ=QT y, and sQ=QT s. This update may be expressed as a rank-one update to R (see Dennis and Schnabel (1981)).

12 Optional Parameters

Several optional parameters in E04UFF/E04UFA define choices in the problem specification or the algorithm logic. In order to reduce the complexity of using E04UFF/E04UFA these optional parameters have associated default values that are appropriate for most problems. Therefore you need only specify those optional parameters whose values are to be different from their default values.
The remainder of this section can be skipped if you wish to use the default values for all optional parameters.
The following is a list of the optional parameters available. A full description of each optional parameter is provided in Section 12.1.
  • Central Difference Interval
  • Cold Start
  • Crash Tolerance
  • Defaults
  • Derivative Level
  • Difference Interval
  • Feasibility Tolerance
  • Function Precision
  • Hessian
  • Infinite Bound Size
  • Infinite Step Size
  • Iteration Limit
  • Iters
  • Itns
  • Linear Feasibility Tolerance
  • Line Search Tolerance
  • List
  • Major Iteration Limit
  • Major Print Level
  • Minor Iteration Limit
  • Minor Print Level
  • Monitoring File
  • Nolist
  • Nonlinear Feasibility Tolerance
  • Optimality Tolerance
  • Print Level
  • Start Constraint Check At Variable
  • Start Objective Check At Variable
  • Step Limit
  • Stop Constraint Check At Variable
  • Stop Objective Check At Variable
  • Verify
  • Verify Constraint Gradients
  • Verify Gradients
  • Verify Level
  • Verify Objective Gradients
  • Warm Start
Optional parameters may be specified by calling one, or both, of E04UDF/E04UDA and E04UEF/E04UEA before a call to E04UFF/E04UFA.
E04UDF/E04UDA reads options from an external options file, with Begin and End as the first and last lines respectively and each intermediate line defining a single optional parameter. For example,
Begin * Example options file
   Print level = 5
End
The call
 CALL E04UDF (IOPTNS, INFORM)
can then be used to read the file on unit IOPTNS. INFORM=0 on successful exit. E04UDF/E04UDA should be consulted for a full description of this method of supplying optional parameters.
E04UEF/E04UEA can be called to supply options directly, one call being necessary for each optional parameter. For example,
 CALL E04UEF ('Print Level = 1')
E04UEF/E04UEA should be consulted for a full description of this method of supplying optional parameters.
All optional parameters not specified are set to their default values. Optional parameters specified are unaltered by E04UFF/E04UFA (unless they define invalid values) and so remain in effect for subsequent calls to E04UFF/E04UFA.

12.1 Description of the Optional Parameters

For each option, we give a summary line, a description of the optional parameter and details of constraints.
The summary line contains:
  • the keywords, where the minimum abbreviation of each keyword is underlined (if no characters of an optional qualifier are underlined, the qualifier may be omitted);
  • a parameter value, where the letters a, i and r denote options that take character, integer and real values respectively;
  • the default value, where the symbol ε is a generic notation for machine precision (see X02AJF), and εr denotes the relative precision of the objective function Function Precision.
Keywords and character values are case and white space insensitive.
Central Difference Interval r Default values are computed
If the algorithm switches to central differences because the forward-difference approximation is not sufficiently accurate, the value of r is used as the difference interval for every element of x. The switch to central differences is indicated by C at the end of each line of intermediate printout produced by the major iterations (see Section 9.1). The use of finite differences is discussed further under the optional parameter Difference Interval.
If you supply a value for this optional parameter, a small value between 0.0 and 1.0 is appropriate.
Cold Start Default
Warm Start
This option controls the specification of the initial working set in both the procedure for finding a feasible point for the linear constraints and bounds and in the first QP subproblem thereafter. With a Cold Start, the first working set is chosen by E04UFF/E04UFA based on the values of the variables and constraints at the initial point. Broadly speaking, the initial working set will include equality constraints and bounds or inequality constraints that violate or ‘nearly’ satisfy their bounds (to within Crash Tolerance).
With a Warm Start, you must set the ISTATE array and define CLAMDA and R as discussed in Section 5. ISTATE values associated with bounds and linear constraints determine the initial working set of the procedure to find a feasible point with respect to the bounds and linear constraints. ISTATE values associated with nonlinear constraints determine the initial working set of the first QP subproblem after such a feasible point has been found. E04UFF/E04UFA will override your specification of ISTATE if necessary, so that a poor choice of the working set will not cause a fatal error. For instance, any elements of ISTATE which are set to -2, -1​ or ​4 will be reset to zero, as will any elements which are set to 3 when the corresponding elements of BL and BU are not equal. A warm start will be advantageous if a good estimate of the initial working set is available – for example, when E04UFF/E04UFA is called repeatedly to solve related problems.
Crash Tolerance r Default =0.01
This value is used in conjunction with the optional parameter Cold Start (the default value) when E04UFF/E04UFA selects an initial working set. If 0≤r≤1, the initial working set will include (if possible) bounds or general inequality constraints that lie within r of their bounds. In particular, a constraint of the form ajT x≥l will be included in the initial working set if ajT x-l ≤ r 1+l . If r<0 or r>1, the default value is used.
Defaults
This special keyword may be used to reset all optional parameters to their default values.
Derivative Level i Default =3
This parameter indicates which derivatives are provided during intermediate exits. The possible choices for i are the following.
i | Meaning
3 | All elements of the objective gradient and the constraint Jacobian are provided.
2 | All elements of the constraint Jacobian are provided, but some elements of the objective gradient are not specified.
1 | All elements of the objective gradient are provided, but some elements of the constraint Jacobian are not specified.
0 | Some elements of both the objective gradient and the constraint Jacobian are not specified.
The value i=3 should be used whenever possible, since E04UFF/E04UFA is more reliable (and will usually be more efficient) when all derivatives are exact.
If i=0​ or ​2, E04UFF/E04UFA will estimate the unspecified elements of the objective gradient, using finite differences. The computation of finite difference approximations usually increases the total run-time, since an intermediate exit to the calling program is required for each unspecified element. Furthermore, less accuracy can be attained in the solution (see Chapter 8 of Gill et al. (1981), for a discussion of limiting accuracy).
If i=0​ or ​1, E04UFF/E04UFA will approximate unspecified elements of the constraint Jacobian. One intermediate exit is needed for each variable for which partial derivatives are not available. For example, if the Jacobian has the form
* * * * * ? ? * * * ? * * * * *
where ‘*’ indicates an element provided and ‘?’ indicates an unspecified element, E04UFF/E04UFA will make an intermediate exit to the calling program twice: once to estimate the missing element in column 2, and again to estimate the two missing elements in column 3. (Since columns 1 and 4 are known, they require no intermediate exits for information.)
At times, central differences are used rather than forward differences, in which case twice as many intermediate exits are needed. (The switch to central differences is not under your control.)
If i<0 or i>3, the default value is used.
Difference Interval r Default values are computed
This option defines an interval used to estimate derivatives by finite differences in the following circumstances:
(a) | For verifying the objective and/or constraint gradients (see the description of the optional parameter Verify).
(b) | For estimating unspecified elements of the objective gradient or the constraint Jacobian.
In general, a derivative with respect to the jth variable is approximated using the interval δj, where δj=r 1+x^j, with x^ the first point feasible with respect to the bounds and linear constraints. If the functions are well scaled then the resulting derivative approximation should be accurate to O r. See Gill et al. (1981) for a discussion of the accuracy in finite difference approximations.
If a difference interval is not specified then a finite difference interval will be computed automatically for each variable by a procedure that requires up to six intermediate exits for each element. This option is recommended if the function is badly scaled or you wish to have E04UFF/E04UFA determine constant elements in the objective and constraint gradients.
If you supply a value for this optional parameter, a small value between 0.0 and 1.0 is appropriate.
Feasibility Tolerance r Default =ε
The scalar r defines the maximum acceptable absolute violations in linear and nonlinear constraints at a ‘feasible’ point; i.e., a constraint is considered satisfied if its violation does not exceed r. If r<ε or r≥1, the default value is used. Using this keyword sets both optional parameters Linear Feasibility Tolerance and Nonlinear Feasibility Tolerance to r, if ε≤r<1. (Additional details are given under the descriptions of these optional parameters.)
Function Precision r Default =ε 0.9
This parameter defines εr, which is intended to be a measure of the accuracy with which the problem functions F x and c x can be computed. If r<ε or r≥1, the default value is used.
The value of εr should reflect the relative precision of 1+F x; i.e., εr acts as a relative precision when F is large and as an absolute precision when F is small. For example, if F x is typically of order 1000 and the first six significant digits are known to be correct, an appropriate value for εr would be 10-6. In contrast, if F x is typically of order 10-4 and the first six significant digits are known to be correct, an appropriate value for εr would be 10-10. The choice of εr can be quite complicated for badly scaled problems; see Chapter 8 of Gill et al. (1981) for a discussion of scaling techniques. The default value is appropriate for most simple functions that are computed with full accuracy. However, when the accuracy of the computed function values is known to be significantly worse than full precision, the value of εr should be large enough so that E04UFF/E04UFA will not attempt to distinguish between function values that differ by less than the error inherent in the calculation.
Hessian Default =NO
This option controls the contents of the upper triangular matrix R (see Section 5). E04UFF/E04UFA works exclusively with the transformed and reordered Hessian HQ (6), and hence extra computation is required to form the Hessian itself. If Hessian=NO, R contains the Cholesky factor of the transformed and reordered Hessian. If Hessian=YES, the Cholesky factor of the approximate Hessian itself is formed and stored in R. You should select Hessian=YES if a Warm Start will be used for the next call to E04UFF/E04UFA.
Infinite Bound Size r Default =1020
If r>0, r defines the ‘infinite’ bound bigbnd in the definition of the problem constraints. Any upper bound greater than or equal to bigbnd will be regarded as +∞ (and similarly any lower bound less than or equal to -bigbnd will be regarded as -∞). If r<0, the default value is used.
Infinite Step Size r Default =max bigbnd,1020
If r>0, r specifies the magnitude of the change in variables that is treated as a step to an unbounded solution. If the change in x during an iteration would exceed the value of r, the objective function is considered to be unbounded below in the feasible region. If r≤0, the default value is used.
Line Search Tolerance r Default =0.9
The value r (0≤r<1) controls the accuracy with which the step α taken during each iteration approximates a minimum of the merit function along the search direction (the smaller the value of r, the more accurate the linesearch). The default value r=0.9 requests an inaccurate search and is appropriate for most problems, particularly those with any nonlinear constraints.
If there are no nonlinear constraints, a more accurate search may be appropriate when it is desirable to reduce the number of major iterations – for example, if the objective function is cheap to evaluate, or if a substantial number of derivatives are unspecified. If r<0 or r≥1, the default value is used.
Linear Feasibility Tolerance r 1 Default =ε
Nonlinear Feasibility Tolerance r 2 Default =ε 0.33 or ε
The default value of r 2 is ε 0.33 if Derivative Level=0 or 1, and ε otherwise.
The scalars r 1 and r 2 define the maximum acceptable absolute violations in linear and nonlinear constraints at a ‘feasible’ point; i.e., a linear constraint is considered satisfied if its violation does not exceed r 1. Similarly a nonlinear constraint is considered satisfied if its violation does not exceed r 2. If rm<ε or rm≥1, the default value is used, for m=1,2.
On entry to E04UFF/E04UFA, an iterative procedure is executed in order to find a point that satisfies the linear constraints and bounds on the variables to within the tolerance r 1. All subsequent iterates will satisfy the linear constraints to within the same tolerance (unless r 1 is comparable to the finite difference interval).
For nonlinear constraints, the feasibility tolerance r 2 defines the largest constraint violation that is acceptable at an optimal point. Since nonlinear constraints are generally not satisfied until the final iterate, the value of optional parameter Nonlinear Feasibility Tolerance acts as a partial termination criterion for the iterative sequence generated by E04UFF/E04UFA (see the discussion of optional parameter Optimality Tolerance).
These tolerances should reflect the precision of the corresponding constraints. For example, if the variables and the coefficients in the linear constraints are of order unity, and the latter are correct to about 6 decimal digits, it would be appropriate to specify r 1 as 10-6.
List Default for E04UFF
Nolist Default for E04UFA
Optional parameter List may be used to turn on printing of each optional parameter specification as it is supplied. Nolist may then be used to suppress this printing again.
Major Iteration Limit i Default =max 50,3 n+nL+10 nN
Iteration Limit
Iters
Itns
The value of i specifies the maximum number of major iterations allowed before termination. Setting i=0 and Major Print Level>0 means that the workspace needed will be computed and printed, but no iterations will be performed. If i<0, the default value is used.
Major Print Level i Default for E04UFF =10
Print Level Default for E04UFA =0
The value of i controls the amount of printout produced by the major iterations of E04UFF/E04UFA, as indicated below. A detailed description of the printed output is given in Section 9.1 (summary output at each major iteration and the final solution) and Section 13 (monitoring information at each major iteration). (See also the description of the optional parameter Minor Print Level.)
The following printout is sent to the current advisory message unit (as defined by X04ABF):
i | Output
≥0 0 | No output.
≥0 1 | The final solution only.
≥0 5 | One line of summary output (<80 characters; see Section 9.1) for each major iteration (no printout of the final solution).
≥10 | The final solution and one line of summary output for each major iteration.
The following printout is sent to the logical unit number by the optional parameter Monitoring File:
i | Output
<5 | No output.
≥5 | One long line of output (>80 characters; see Section 13) for each major iteration (no printout of the final solution).
≥20 | At each major iteration, the objective function, the Euclidean norm of the nonlinear constraint violations, the values of the nonlinear constraints (the vector c), the values of the linear constraints (the vector AL x), and the current values of the variables (the vector x).
≥30 | At each major iteration, the diagonal elements of the matrix T associated with the TQ factorization (5) (see Section 11.1) of the QP working set, and the diagonal elements of R, the triangular factor of the transformed and reordered Hessian (6) (see Section 11.1).
If Major Print Level≥5 and the unit number defined by the optional parameter Monitoring File is the same as that defined by X04ABF, then the summary output for each major iteration is suppressed.
Minor Iteration Limit i Default =max 50,3 n+nL+nN
The value of i specifies the maximum number of iterations for finding a feasible point with respect to the bounds and linear constraints (if any). The value of i also specifies the maximum number of minor iterations for the optimality phase of each QP subproblem. If i≤0, the default value is used.
Minor Print Level i Default =0
The value of i controls the amount of printout produced by the minor iterations of E04UFF/E04UFA (i.e., the iterations of the quadratic programming algorithm), as indicated below. A detailed description of the printed output is given in Section 9.2 in E04NCF/E04NCA (summary output at each minor iteration and the final QP solution) and Section 13 in E04NCF/E04NCA) (monitoring information at each minor iteration). (See also the description of the optional parameter Major Print Level.)
The following printout is sent to the current advisory message unit (as defined by X04ABF):
i | Output
≥0 0 | No output.
≥0 1 | The final QP solution only.
≥0 5 | One line of summary output (<80 characters; see Section 9.2 in E04NCF/E04NCA) for each minor iteration (no printout of the final QP solution).
≥10 | The final QP solution and one line of summary output for each minor iteration.
The following printout is sent to the logical unit number by the optional parameter Monitoring File:
i | Output
<5 | No output.
≥5 | One long line of output (>80 characters; see Section 9.2 in E04NCF/E04NCA) for each minor iteration (no printout of the final QP solution).
≥20 | At each minor iteration, the current estimates of the QP multipliers, the current estimate of the QP search direction, the QP constraint values and the status of each QP constraint.
≥30 | At each minor iteration, the diagonal elements of the matrix T associated with the TQ factorization (5) (see Section 11.1) of the QP working set and the diagonal elements of the Cholesky factor R of the transformed Hessian (6) (see Section 11.1).
If Major Print Level≥5 and the unit number defined by the optional parameter Monitoring File is the same as that defined by X04ABF, then the summary output for each major iteration is suppressed.
Monitoring File i Default =-1
If i≥0 and Major Print Level≥5 or i≥0 and Minor Print Level≥5, monitoring information produced by E04UFF/E04UFA at every iteration is sent to a file with logical unit number i. If i<0 and/or Major Print Level<5 and Minor Print Level<5, no monitoring information is produced.
Optimality Tolerance r Default =εr 0.8
The parameter r (εr≤r<1) specifies the accuracy to which you wish the final iterate to approximate a solution of the problem. Broadly speaking, r indicates the number of correct figures desired in the objective function at the solution. For example, if r is 10-6 and E04UFF/E04UFA terminates successfully, the final value of F should have approximately six correct figures. If r<εr or r≥1, the default value is used.
E04UFF/E04UFA will terminate successfully if the iterative sequence of x values is judged to have converged and the final point satisfies the first-order Kuhn–Tucker conditions (see Section 11.1). The sequence of iterates is considered to have converged at x if
α p≤r 1+x, (16)
where p is the search direction and α the step length from (3). An iterate is considered to satisfy the first-order conditions for a minimum if
ZT g FR ≤ r 1 + max 1 + F x , g FR (17)
and
resj≤ftol  for all  j, (18)
where ZT gFR is the projected gradient (see Section 11.1), gFR is the gradient of F x with respect to the free variables, resj is the violation of the jth active nonlinear constraint, and ftol is the Nonlinear Feasibility Tolerance.
Start Objective Check At Variable i 1 Default =1
Stop Objective Check At Variable i 2 Default =n
Start Constraint Check At Variable i 3 Default =1
Stop Constraint Check At Variable i 4 Default =n
These keywords take effect only if Verify Level>0. They may be used to control the verification of gradient elements and/or Jacobian elements computed by the calling program during intermediate exits. For example, if the first 30 elements of the objective gradient appeared to be correct in an earlier run, so that only element 31 remains questionable, it is reasonable to specify Start Objective Check At Variable=31. If the first 30 variables appear linearly in the objective, so that the corresponding gradient elements are constant, the above choice would also be appropriate.
If i 2 m-1≤0 or i 2 m-1>min n,i 2 m, the default value is used, for m=1,2. If i 2 m≤0 or i 2 m>n, the default value is used, for m=1,2.
Step Limit r Default =2.0
If r>0,r specifies the maximum change in variables at the first step of the linesearch. In some cases, such as F x=a e bx or F x=a xb, even a moderate change in the elements of x can lead to floating-point overflow. The parameter r is therefore used to encourage evaluation of the problem functions at meaningful points. Given any major iterate x, the first point x~ at which F and c are evaluated during the linesearch is restricted so that
x~-x 2≤r 1+x 2.
The linesearch may go on and evaluate F and c at points further from x if this will result in a lower value of the merit function (indicated by L at the end of each line of output produced by the major iterations; see Section 9.1). If L is printed for most of the iterations, r should be set to a larger value.
Wherever possible, upper and lower bounds on x should be used to prevent evaluation of nonlinear functions at wild values. The default value Step Limit=2.0 should not affect progress on well-behaved functions, but values such as 0.1 ​ or ​ 0.01 may be helpful when rapidly varying functions are present. If a small value of Step Limit is selected then a good starting point may be required. An important application is to the class of nonlinear least squares problems. If r≤0, the default value is used.
Verify Level i Default =0
Verify
Verify Constraint Gradients
Verify Gradients
Verify Objective Gradients
These keywords refer to finite difference checks on the gradient elements computed by the calling program during intermediate exits. (Unspecified gradient elements are not checked.) The possible choices for i are as follows:
i | Meaning
-1 | No checks are performed.
-0 | Only a ‘cheap’ test will be performed.
≥1 | In addition to the ‘cheap’ test, individual gradient elements will also be checked using a reliable (but more expensive) test.
It is possible to specify Verify Level=0 to 3 in several ways. For example, the objective gradient will be verified if Verify, Verify=YES, Verify Gradients, Verify Objective Gradients or Verify Level=1 is specified. The constraint gradients will be verified if Verify=YES or Verify Level=2 or Verify is specified. Similarly, the objective and the constraint gradients will be verified if Verify=YES or Verify Level=3 or Verify is specified.
If 0≤i≤3, gradients will be verified at the first point that satisfies the linear constraints and bounds.
If i=0, only a ‘cheap’ test will be performed, requiring one intermediate exit for the objective function gradients and (if appropriate) one intermediate exit for the partial derivatives of the constraints.
If 1≤i≤3, a more reliable (but more expensive) check will be made on individual gradient elements, within the ranges specified by the Start Objective Check At Variable and Stop Objective Check At Variable keywords. A result of the form OK or BAD? is printed by E04UFF/E04UFA to indicate whether or not each element appears to be correct.
If 10≤i≤13, the action is the same as for i<10, except that it will take place at the user-specified initial value of x.
If i<-1 or 4≤i≤9 or i>13, the default value is used.
We suggest that Verify Level=3 be used whenever a new calling program is being developed.

13 Description of Monitoring Information

This section describes the long line of output (>80 characters) which forms part of the monitoring information produced by E04UFF/E04UFA. (See also the description of the optional parameters Major Print Level, Minor Print Level and Monitoring File.) You can control the level of printed output (see the description of the optional parameter Major Print Level).
When Major Print Level≥5 and Monitoring File≥0, the following line of output is produced at every major iteration of E04UFF/E04UFA on the unit number specified by Monitoring File. In all cases, the values of the quantities printed are those in effect on completion of the given iteration.
Maj | is the major iteration count.
Mnr is the number of minor iterations required by the feasibility and optimality phases of the QP subproblem. Generally, Mnr will be 1 in the later iterations, since theoretical analysis predicts that the correct active set will be identified near the solution (see Section 11).
Note that Mnr may be greater than the optional parameter Minor Iteration Limit if some iterations are required for the feasibility phase.
Step | is the step αk taken along the computed search direction. On reasonably well-behaved problems, the unit step (i.e., αk=1) will be taken as the solution is approached.
Nfun | is the cumulative number of evaluations of the objective function needed for the linesearch. Evaluations needed for the estimation of the gradients by finite differences are not included. Nfun is printed as a guide to the amount of work required for the linesearch.
Merit Function is the value of the augmented Lagrangian merit function (12) at the current iterate. This function will decrease at each iteration unless it was necessary to increase the penalty parameters (see Section 11.3). As the solution is approached, Merit Function will converge to the value of the objective function at the solution.
If the QP subproblem does not have a feasible point (signified by I at the end of the current output line) then the merit function is a large multiple of the constraint violations, weighted by the penalty parameters. During a sequence of major iterations with infeasible subproblems, the sequence of Merit Function values will decrease monotonically until either a feasible subproblem is obtained or E04UFF/E04UFA terminates with IFAIL=3 (no feasible point could be found for the nonlinear constraints).
If there are no nonlinear constraints present (i.e., NCNLN=0) then this entry contains Objective, the value of the objective function F x. The objective function will decrease monotonically to its optimal value when there are no nonlinear constraints.
Norm Gz | is ZT gFR, the Euclidean norm of the projected gradient (see Section 11.2). Norm Gz will be approximately zero in the neighbourhood of a solution.
Violtn | is the Euclidean norm of the residuals of constraints that are violated or in the predicted active set (not printed if NCNLN is zero). Violtn will be approximately zero in the neighbourhood of a solution.
Nz | is the number of columns of Z (see Section 11.2). The value of Nz is the number of variables minus the number of constraints in the predicted active set; i.e., Nz=n-Bnd+Lin+Nln.
Bnd | is the number of simple bound constraints in the predicted active set.
Lin | is the number of general linear constraints in the predicted working set.
Nln | is the number of nonlinear constraints in the predicted active set (not printed if NCNLN is zero).
Penalty | is the Euclidean norm of the vector of penalty parameters used in the augmented Lagrangian merit function (not printed if NCNLN is zero).
Cond H | is a lower bound on the condition number of the Hessian approximation H.
Cond Hz | is a lower bound on the condition number of the projected Hessian approximation HZ ( HZ = ZT HFR Z = RZT RZ ; see (6)). The larger this number, the more difficult the problem.
Cond T | is a lower bound on the condition number of the matrix of predicted active constraints.
Conv is a three-letter indication of the status of the three convergence tests (16)–(18) defined in the description of the optional parameter Optimality Tolerance. Each letter is T if the test is satisfied and F otherwise. The three tests indicate whether:
(i) | the sequence of iterates has converged;
(ii) | the projected gradient (Norm Gz) is sufficiently small; and
(iii) | the norm of the residuals of constraints in the predicted active set (Violtn) is small enough.
If any of these indicators is F when E04UFF/E04UFA terminates with IFAIL=0, you should check the solution carefully.
M | is printed if the quasi-Newton update has been modified to ensure that the Hessian approximation is positive definite (see Section 11.4).
I | is printed if the QP subproblem has no feasible point.
C | is printed if central differences have been used to compute the unspecified objective and constraint gradients. If the value of Step is zero then the switch to central differences was made because no lower point could be found in the linesearch. (In this case, the QP subproblem is resolved with the central difference gradient and Jacobian.) If the value of Step is nonzero then central differences were computed because Norm Gz and Violtn imply that x is close to a Kuhn–Tucker point (see Section 11.1).
L | is printed if the linesearch has produced a relative change in x greater than the value defined by the optional parameter Step Limit. If this output occurs frequently during later iterations of the run, optional parameter Step Limit should be set to a larger value.
On entry: need not be initialized if the (default) optional parameter Cold Start is used.
If the optional parameter Warm Start has been chosen, R must contain the upper triangular Cholesky factor R of the initial approximation of the Hessian of the Lagrangian function, with the variables in the natural order. Elements not in the upper triangular part of R are assumed to be zero and need not be assigned.
On exit: if Hessian=NO, R contains the upper triangular Cholesky factor R of QT H~Q, an estimate of the transformed and reordered Hessian of the Lagrangian at x (see (6) in Section 11.1). If Hessian=YES, R contains the upper triangular Cholesky factor R of H, the approximate (untransformed) Hessian of the Lagrangian, with the variables in the natural order.
E04 Chapter Contents
E04 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


E04UGF/E04UGA : NAG Library, Mark 26

E04 Chapter Contents
E04 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

E04UGF/E04UGA

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.
Note: this routine uses optional parameters to define choices in the problem specification and in the details of the algorithm. If you wish to use default settings for all of the optional parameters, you need only read Sections 1 to 10 of this document. If, however, you wish to reset some or all of the settings please refer to Section 11 for a detailed description of the algorithm, to Section 12 for a detailed description of the specification of the optional parameters and to Section 13 for a detailed description of the monitoring information produced by the routine.

▸▿ Contents

1 Purpose
▸▿ 2 Specification
2.1 Specification for E04UGF
2.2 Specification for E04UGA
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
▸▿ 9 Further Comments
9.1 Major Iteration Printout
9.2 Minor Iteration Printout
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results
▸▿ 11 Algorithmic Details
11.1 Overview
11.2 Treatment of Constraint Infeasibilities
▸▿ 12 Optional Parameters
12.1 Description of the Optional Parameters
13 Description of Monitoring Information

1 Purpose

E04UGF/E04UGA solves sparse nonlinear programming problems.
E04UGA is a version of E04UGF that has additional arguments in order to make it safe for use in multithreaded applications (see Section 5). The initialization routine E04WBF must have been called before calling E04UGA.

2 Specification

2.1 Specification for E04UGF

SUBROUTINE E04UGF ( CONFUN, OBJFUN, N, M, NCNLN, NONLN, NJNLN, IOBJ, NNZ, A, HA, KA, BL, BU, START, NNAME, NAMES, NS, XS, ISTATE, CLAMDA, MINIZ, MINZ, NINF, SINF, OBJ, IZ, LENIZ, Z, LENZ, IUSER, RUSER, IFAIL)
INTEGER | N, M, NCNLN, NONLN, NJNLN, IOBJ, NNZ, HA(NNZ), KA(N+1), NNAME, NS, ISTATE(N+M), MINIZ, MINZ, NINF, IZ(LENIZ), LENIZ, LENZ, IUSER(*), IFAIL
REAL (KIND=nag_wp) | A(NNZ), BL(N+M), BU(N+M), XS(N+M), CLAMDA(N+M), SINF, OBJ, Z(LENZ), RUSER(*)
CHARACTER(1) | START
CHARACTER(8) | NAMES(NNAME)
EXTERNAL | CONFUN, OBJFUN

2.2 Specification for E04UGA

SUBROUTINE E04UGA ( CONFUN, OBJFUN, N, M, NCNLN, NONLN, NJNLN, IOBJ, NNZ, A, HA, KA, BL, BU, START, NNAME, NAMES, NS, XS, ISTATE, CLAMDA, MINIZ, MINZ, NINF, SINF, OBJ, IZ, LENIZ, Z, LENZ, IUSER, RUSER, LWSAV, IWSAV, RWSAV, IFAIL)
INTEGER | N, M, NCNLN, NONLN, NJNLN, IOBJ, NNZ, HA(NNZ), KA(N+1), NNAME, NS, ISTATE(N+M), MINIZ, MINZ, NINF, IZ(LENIZ), LENIZ, LENZ, IUSER(*), IWSAV(550), IFAIL
REAL (KIND=nag_wp) | A(NNZ), BL(N+M), BU(N+M), XS(N+M), CLAMDA(N+M), SINF, OBJ, Z(LENZ), RUSER(*), RWSAV(550)
LOGICAL | LWSAV(20)
CHARACTER(1) | START
CHARACTER(8) | NAMES(NNAME)
EXTERNAL | CONFUN, OBJFUN
Before calling E04UGA, or either of the option setting routines E04UHA or E04UJA, E04WBF must be called. The specification for E04WBF is:
SUBROUTINE E04WBF ( RNAME, CWSAV, LCWSAV, LWSAV, LLWSAV, IWSAV, LIWSAV, RWSAV, LRWSAV, IFAIL)
INTEGER | LCWSAV, LLWSAV, IWSAV(LIWSAV), LIWSAV, LRWSAV, IFAIL
REAL (KIND=nag_wp) | RWSAV(LRWSAV)
LOGICAL | LWSAV(LLWSAV)
CHARACTER(*) | RNAME
CHARACTER(80) | CWSAV(LCWSAV)
E04WBF should be called with RNAME='E04UGA'. LCWSAV, LLWSAV, LIWSAV and LRWSAV, the declared lengths of CWSAV, LWSAV, IWSAV and RWSAV respectively, must satisfy:
  • LCWSAV≥1
  • LLWSAV≥20
  • LIWSAV≥550
  • LRWSAV≥550
The contents of the arrays CWSAV, LWSAV, IWSAV and RWSAV must not be altered between calling routines E04UGA, E04UHA, E04UJA and E04WBF.

3 Description

E04UGF/E04UGA is designed to solve a class of nonlinear programming problems that are assumed to be stated in the following general form:
minimize x∈Rn f x  subject to  l≤ x F x Gx ≤u, (1)
where x=x 1,x 2,…,xn T is a set of variables, f x is a smooth scalar objective function, l and u are constant lower and upper bounds, F x is a vector of smooth nonlinear constraint functions Fi x and G is a sparse matrix.
The constraints involving F and Gx are called the general constraints. Note that upper and lower bounds are specified for all variables and constraints. This form allows full generality in specifying various types of constraint. In particular, the jth constraint can be defined as an equality by setting lj=uj. If certain bounds are not present, the associated elements of l or u can be set to special values that will be treated as -∞ or +∞. (See the description of the optional parameter Infinite Bound Size.)
E04UGF/E04UGA converts the upper and lower bounds on the m elements of F and Gx to equalities by introducing a set of slack variables s, where s=s 1,s 2,…,sm T. For example, the linear constraint 5≤2 x 1+3 x 2≤+∞ is replaced by 2 x 1+3 x 2-s 1=0, together with the bounded slack 5≤s 1≤+∞. The problem defined by (1) can therefore be re-written in the following equivalent form:
minimize x∈Rn,s∈Rm f x  subject to   Gx -s=0,  l≤ x s ≤u. (2)
Since the slack variables s are subject to the same upper and lower bounds as the elements of F and Gx, the bounds on F and Gx can simply be thought of as bounds on the combined vector x,s. The elements of x and s are partitioned into basic, nonbasic and superbasic variables defined as follows:
– | a basic variable (xj say) is the jth variable associated with the jth column of the basis matrix B;
– | a nonbasic variable is a variable that is temporarily fixed at its current value (usually its upper or lower bound);
– | a superbasic variable is a nonbasic variable which is not at one of its bounds that is free to move in any desired direction (namely one that will improve the value of the objective function or reduce the sum of infeasibilities).
For example, in the simplex method (see Gill et al. (1981)) the elements of x can be partitioned at each vertex into a set of m basic variables (all non-negative) and a set of n-m nonbasic variables (all zero). This is equivalent to partitioning the columns of the constraint matrix as BN , where B contains the m columns that correspond to the basic variables and N contains the n-m columns that correspond to the nonbasic variables. Note that B is square and nonsingular.
The optional parameter Maximize may be used to specify an alternative problem in which f x is maximized. If the objective function is nonlinear and all the constraints are linear, F is absent and the problem is said to be linearly constrained. In general, the objective and constraint functions are structured in the sense that they are formed from sums of linear and nonlinear functions. This structure can be exploited by the routine during the solution process as follows.
Consider the following nonlinear optimization problem with four variables (u,v,z,w):
minimize u,v,z,w  u+v+z 2+3 z+5 w
subject to the constraints
u 2+v 2+z +w= 2 u 4+v 4 +z+w= 4 2 u+ 4 v +z+w≥ 0
and to the bounds
z≥0. w≥0.
This problem has several characteristics that can be exploited by the routine:
– | the objective function is nonlinear. It is the sum of a nonlinear function of the variables (u,v,z) and a linear function of the variables (z,w);
– | the first two constraints are nonlinear. The third is linear;
– | each nonlinear constraint function is the sum of a nonlinear function of the variables (u,v) and a linear function of the variables (z,w).
The nonlinear terms are defined by OBJFUN and CONFUN (see Section 5), which involve only the appropriate subset of variables.
For the objective, we define the function f u,v,z= u+v+z 2 to include only the nonlinear part of the objective. The three variables (u,v,z) associated with this function are known as the nonlinear objective variables. The number of them is given by NONLN (see Section 5) and they are the only variables needed in OBJFUN. The linear part 3 z+5 w of the objective is stored in row IOBJ (see Section 5) of the (constraint) Jacobian matrix A (see below).
Thus, if x′ and y′ denote the nonlinear and linear objective variables, respectively, the objective may be re-written in the form
f x′+cTx′+dTy′,
where f x′ is the nonlinear part of the objective and c and d are constant vectors that form a row of A. In this example, x′=u,v,z and y′=w.
Similarly for the constraints, we define a vector function F u,v to include just the nonlinear terms. In this example, F 1 u,v=u 2+v 2 and F 2 u,v=u 4+v 4, where the two variables (u,v) are known as the nonlinear Jacobian variables. The number of them is given by NJNLN (see Section 5) and they are the only variables needed in CONFUN. Thus, if x′′ and y′′ denote the nonlinear and linear Jacobian variables, respectively, the constraint functions and the linear part of the objective have the form
F x′′+A 2 y′′ A 3 x′′+A 4 y′′ , (3)
where x′′=u,v and y′′=z,w in this example. This ensures that the Jacobian is of the form
A= J x′′ A 2 A 3 A 4 ,
where J x′′= ∂F x′′ ∂x . Note that J x′′ always appears in the top left-hand corner of A.
The inequalities l 1≤F x′′+A 2 y′′≤u 1 and l 2≤A 3 x′′+A 4 y′′≤u 2 implied by the constraint functions in (3) are known as the nonlinear and linear constraints, respectively. The nonlinear constraint vector F x′′ in (3) and (optionally) its partial derivative matrix J x′′ are set in CONFUN. The matrices A 2, A 3 and A 4 contain any (constant) linear terms. Along with the sparsity pattern of J x′′ they are stored in the arrays A, HA and KA (see Section 5).
In general, the vectors x′ and x′′ have different dimensions, but they always overlap, in the sense that the shorter vector is always the beginning of the other. In the above example, the nonlinear Jacobian variables u,v are an ordered subset of the nonlinear objective variables u,v,z. In other cases it could be the other way round (whichever is the most convenient), but the first way keeps J x′′ as small as possible.
Note that the nonlinear objective function f x′ may involve either a subset or superset of the variables appearing in the nonlinear constraint functions F x′′. Thus, NONLN≤NJNLN (or vice-versa). Sometimes the objective and constraints really involve disjoint sets of nonlinear variables. In such cases the variables should be ordered so that NONLN>NJNLN and x′=x′′,x′′′, where the objective is nonlinear in just the last vector x′′′. The first NJNLN elements of the gradient array OBJGRD should also be set to zero in OBJFUN. This is illustrated in Section 10.
If all elements of the constraint Jacobian are known (i.e., the optional parameter Derivative Level=2 or 3), any constant elements may be assigned their correct values in A, HA and KA. The corresponding elements of the constraint Jacobian array FJAC need not be reset in CONFUN. This includes values that are identically zero as constraint Jacobian elements are assumed to be zero unless specified otherwise. It must be emphasized that, if Derivative Level=0 or 1, unassigned elements of FJAC are not treated as constant; they are estimated by finite differences, at nontrivial expense.
If there are no nonlinear constraints in (1) and f x is linear or quadratic, then it may be more efficient to use E04NQF to solve the resulting linear or quadratic programming problem, or one of E04MFF/E04MFA, E04NCF/E04NCA or E04NFF/E04NFA if G is a dense matrix. If the problem is dense and does have nonlinear constraints then one of E04UFF/E04UFA, E04USF/E04USA or E04WDF (as appropriate) should be used instead.
You must supply an initial estimate of the solution to (1), together with versions of OBJFUN and CONFUN that define f x′ and F x′′, respectively, and as many first partial derivatives as possible. Note that if there are any nonlinear constraints, then the first call to CONFUN will precede the first call to OBJFUN.
E04UGF/E04UGA is based on the SNOPT package described in Gill et al. (2002), which in turn utilizes routines from the MINOS package (see Murtagh and Saunders (1995)). It incorporates a sequential quadratic programming (SQP) method that obtains search directions from a sequence of quadratic programming (QP) subproblems. Each QP subproblem minimizes a quadratic model of a certain Lagrangian function subject to a linearization of the constraints. An augmented Lagrangian merit function is reduced along each search direction to ensure convergence from any starting point. Further details can be found in Section 11.
Throughout this document the symbol ε is used to represent the machine precision (see X02AJF).

4 References

Conn A R (1973) Constrained optimization using a nondifferentiable penalty function SIAM J. Numer. Anal. 10 760–779
Eldersveld S K (1991) Large-scale sequential quadratic programming algorithms PhD Thesis Department of Operations Research, Stanford University, Stanford
Fletcher R (1984) An l 1 penalty method for nonlinear constraints Numerical Optimization 1984 (eds P T Boggs, R H Byrd and R B Schnabel) 26–40 SIAM Philadelphia
Fourer R (1982) Solving staircase linear programs by the simplex method Math. Programming 23 274–313
Gill P E, Murray W and Saunders M A (2002) SNOPT: An SQP Algorithm for Large-scale Constrained Optimization 12 979–1006 SIAM J. Optim.
Gill P E, Murray W, Saunders M A and Wright M H (1986) Users' guide for NPSOL (Version 4.0): a Fortran package for nonlinear programming Report SOL 86-2 Department of Operations Research, Stanford University
Gill P E, Murray W, Saunders M A and Wright M H (1989) A practical anti-cycling procedure for linearly constrained optimization Math. Programming 45 437–474
Gill P E, Murray W, Saunders M A and Wright M H (1992) Some theoretical properties of an augmented Lagrangian merit function Advances in Optimization and Parallel Computing (ed P M Pardalos) 101–128 North Holland
Gill P E, Murray W and Wright M H (1981) Practical Optimization Academic Press
Hock W and Schittkowski K (1981) Test Examples for Nonlinear Programming Codes. Lecture Notes in Economics and Mathematical Systems 187 Springer–Verlag
Murtagh B A and Saunders M A (1995) MINOS 5.4 users' guide Report SOL 83-20R Department of Operations Research, Stanford University
Ortega J M and Rheinboldt W C (1970) Iterative Solution of Nonlinear Equations in Several Variables Academic Press
Powell M J D (1974) Introduction to constrained optimization Numerical Methods for Constrained Optimization (eds P E Gill and W Murray) 1–28 Academic Press

5 Arguments

1:   CONFUN – SUBROUTINE, supplied by the NAG Library or the user.External Procedure
CONFUN must calculate the vector F x of nonlinear constraint functions and (optionally) its Jacobian = ∂F ∂x for a specified n 1′′ (≤n) element vector x. If there are no nonlinear constraints (i.e., NCNLN=0), CONFUN will never be called by E04UGF/E04UGA and CONFUN may be the dummy routine E04UGM. (E04UGM is included in the NAG Library.) If there are nonlinear constraints, the first call to CONFUN will occur before the first call to OBJFUN.
The specification of CONFUN is:
SUBROUTINE CONFUN ( MODE, NCNLN, NJNLN, NNZJAC, X, F, FJAC, NSTATE, IUSER, RUSER)
INTEGER | MODE, NCNLN, NJNLN, NNZJAC, NSTATE, IUSER(*)
REAL (KIND=nag_wp) | X(NJNLN), F(NCNLN), FJAC(NNZJAC), RUSER(*)
1:   MODE – INTEGERInput/Output
On entry: indicates which values must be assigned during each call of CONFUN. Only the following values need be assigned:
MODE=0
F.
MODE=1
All available elements of FJAC.
MODE=2
F and all available elements of FJAC.
On exit: you may set to a negative value as follows:
MODE≤-2
The solution to the current problem is terminated and in this case E04UGF/E04UGA will terminate with IFAIL set to MODE.
MODE=-1
The nonlinear constraint functions cannot be calculated at the current x. E04UGF/E04UGA will then terminate with IFAIL=-1 unless this occurs during the linesearch; in this case, the linesearch will shorten the step and try again.
2:   NCNLN – INTEGERInput
On entry: nN, the number of nonlinear constraints. These must be the first NCNLN constraints in the problem.
3:   NJNLN – INTEGERInput
On entry: n 1′′, the number of nonlinear variables. These must be the first NJNLN variables in the problem.
4:   NNZJAC – INTEGERInput
On entry: the number of nonzero elements in the constraint Jacobian. Note that NNZJAC will usually be less than NCNLN×NJNLN.
5:   X NJNLN – REAL (KIND=nag_wp) arrayInput
On entry: x, the vector of nonlinear Jacobian variables at which the nonlinear constraint functions and/or the available elements of the constraint Jacobian are to be evaluated.
6:   F NCNLN – REAL (KIND=nag_wp) arrayOutput
On exit: if MODE=0 or 2, F i must contain the value of the ith nonlinear constraint function at x.
7:   FJAC NNZJAC – REAL (KIND=nag_wp) arrayInput/Output
On entry: the elements of FJAC are set to special values which enable E04UGF/E04UGA to detect whether they are changed by CONFUN.
On exit: if MODE=1 or 2, FJAC must return the available elements of the constraint Jacobian evaluated at x. These elements must be stored in exactly the same positions as implied by the definitions of the arrays A, HA and KA. If optional parameter Derivative Level=2 or 3, the value of any constant Jacobian element not defined by CONFUN will be obtained directly from A. Note that the routine does not perform any internal checks for consistency (except indirectly via the optional parameter Verify Level), so great care is essential.
8:   NSTATE – INTEGERInput
On entry: if NSTATE=1, then E04UGF/E04UGA is calling CONFUN for the first time. This argument setting allows you to save computation time if certain data must be read or calculated only once.
If NSTATE≥2, then E04UGF/E04UGA is calling CONFUN for the last time. This argument setting allows you to perform some additional computation on the final solution. In general, the last call to CONFUN is made with NSTATE=2+IFAIL (see Section 6).
Otherwise, NSTATE=0.
9:   IUSER* – INTEGER arrayUser Workspace
10:   RUSER* – REAL (KIND=nag_wp) arrayUser Workspace
CONFUN is called with the arguments IUSER and RUSER as supplied to E04UGF/E04UGA. You are free to use the arrays IUSER and RUSER to supply information to CONFUN as an alternative to using COMMON global variables.
CONFUN must either be a module subprogram USEd by, or declared as EXTERNAL in, the (sub)program from which E04UGF/E04UGA is called. Arguments denoted as Input must not be changed by this procedure.
2:   OBJFUN – SUBROUTINE, supplied by the NAG Library or the user.External Procedure
OBJFUN must calculate the nonlinear part of the objective function f x and (optionally) its gradient = ∂f ∂x for a specified n 1′ (≤n) element vector x. If there are no nonlinear objective variables (i.e., NONLN=0), OBJFUN will never be called by E04UGF/E04UGA and OBJFUN may be the dummy routine E04UGN. (E04UGN is included in the NAG Library.)
The specification of OBJFUN is:
SUBROUTINE OBJFUN ( MODE, NONLN, X, OBJF, OBJGRD, NSTATE, IUSER, RUSER)
INTEGER | MODE, NONLN, NSTATE, IUSER(*)
REAL (KIND=nag_wp) | X(NONLN), OBJF, OBJGRD(NONLN), RUSER(*)
1:   MODE – INTEGERInput/Output
On entry: indicates which values must be assigned during each call of OBJFUN. Only the following values need be assigned:
MODE=0
OBJF.
MODE=1
All available elements of OBJGRD.
MODE=2
OBJF and all available elements of OBJGRD.
On exit: you may set to a negative value as follows:
MODE≤-2
The solution to the current problem is terminated and in this case E04UGF/E04UGA will terminate with IFAIL set to MODE.
MODE=-1
The nonlinear part of the objective function cannot be calculated at the current x. E04UGF/E04UGA will then terminate with IFAIL=-1 unless this occurs during the linesearch; in this case, the linesearch will shorten the step and try again.
2:   NONLN – INTEGERInput
On entry: n 1′, the number of nonlinear objective variables. These must be the first NONLN variables in the problem.
3:   X NONLN – REAL (KIND=nag_wp) arrayInput
On entry: x, the vector of nonlinear variables at which the nonlinear part of the objective function and/or all available elements of its gradient are to be evaluated.
4:   OBJF – REAL (KIND=nag_wp)Output
On exit: if MODE=0 or 2, OBJF must be set to the value of the objective function at x.
5:   OBJGRD NONLN – REAL (KIND=nag_wp) arrayInput/Output
On entry: the elements of OBJGRD are set to special values which enable E04UGF/E04UGA to detect whether they are changed by OBJFUN.
On exit: if MODE=1 or 2, OBJGRD must return the available elements of the gradient evaluated at x.
6:   NSTATE – INTEGERInput
On entry: if NSTATE=1, E04UGF/E04UGA is calling OBJFUN for the first time. This argument setting allows you to save computation time if certain data must be read or calculated only once.
If NSTATE≥2, E04UGF/E04UGA is calling OBJFUN for the last time. This argument setting allows you to perform some additional computation on the final solution. In general, the last call to OBJFUN is made with NSTATE=2+IFAIL (see Section 6).
Otherwise, NSTATE=0.
7:   IUSER* – INTEGER arrayUser Workspace
8:   RUSER* – REAL (KIND=nag_wp) arrayUser Workspace
OBJFUN is called with the arguments IUSER and RUSER as supplied to E04UGF/E04UGA. You are free to use the arrays IUSER and RUSER to supply information to OBJFUN as an alternative to using COMMON global variables.
OBJFUN must either be a module subprogram USEd by, or declared as EXTERNAL in, the (sub)program from which E04UGF/E04UGA is called. Arguments denoted as Input must not be changed by this procedure.
3:   N – INTEGERInput
On entry: n, the number of variables (excluding slacks). This is the number of columns in the full Jacobian matrix A.
Constraint: N≥1.
4:   M – INTEGERInput
On entry: m, the number of general constraints (or slacks). This is the number of rows in A, including the free row (if any; see IOBJ). Note that A must contain at least one row. If your problem has no constraints, or only upper and lower bounds on the variables, then you must include a dummy ‘free’ row consisting of a single (zero) element subject to ‘infinite’ upper and lower bounds. Further details can be found under the descriptions for IOBJ, NNZ, A, HA, KA, BL and BU.
Constraint: M≥1.
5:   NCNLN – INTEGERInput
On entry: nN, the number of nonlinear constraints.
Constraint: 0≤NCNLN≤M.
6:   NONLN – INTEGERInput
On entry: n 1′, the number of nonlinear objective variables. If the objective function is nonlinear, the leading n 1′ columns of A belong to the nonlinear objective variables. (See also the description for NJNLN.)
Constraint: 0≤NONLN≤N.
7:   NJNLN – INTEGERInput
On entry: n 1′′, the number of nonlinear Jacobian variables. If there are any nonlinear constraints, the leading n 1′′ columns of A belong to the nonlinear Jacobian variables. If n 1′>0 and n 1′′>0, the nonlinear objective and Jacobian variables overlap. The total number of nonlinear variables is given by n-=max n 1′,n 1′′.
Constraints:
  • if NCNLN=0, NJNLN=0;
  • if NCNLN>0, 1≤NJNLN≤N.
8:   IOBJ – INTEGERInput
On entry: if IOBJ>NCNLN, row IOBJ of A is a free row containing the nonzero elements of the linear part of the objective function.
IOBJ=0
There is no free row.
IOBJ=-1
There is a dummy ‘free’ row.
Constraints:
  • if IOBJ>0, NCNLN<IOBJ≤M;
  • otherwise IOBJ≥-1.
9:   NNZ – INTEGERInput
On entry: the number of nonzero elements in A (including the Jacobian for any nonlinear constraints). If IOBJ=-1, set NNZ=1.
Constraint: 1≤NNZ≤N×M.
10:   A NNZ – REAL (KIND=nag_wp) arrayInput/Output
On entry: the nonzero elements of the Jacobian matrix A, ordered by increasing column index. Since the constraint Jacobian matrix J x′′ must always appear in the top left-hand corner of A, those elements in a column associated with any nonlinear constraints must come before any elements belonging to the linear constraint matrix G and the free row (if any; see IOBJ).
In general, A is partitioned into a nonlinear part and a linear part corresponding to the nonlinear variables and linear variables in the problem. Elements in the nonlinear part may be set to any value (e.g., zero) because they are initialized at the first point that satisfies the linear constraints and the upper and lower bounds.
If Derivative Level=2 or 3, the nonlinear part may also be used to store any constant Jacobian elements. Note that if CONFUN does not define the constant Jacobian element FJAC i then the missing value will be obtained directly from A j for some j≥i.
If Derivative Level=0 or 1, unassigned elements of FJAC are not treated as constant; they are estimated by finite differences, at nontrivial expense.
The linear part must contain the nonzero elements of G and the free row (if any). If IOBJ=-1, set A 1=0. Elements with the same row and column indices are not allowed. (See also the descriptions for HA and KA.)
On exit: elements in the nonlinear part corresponding to nonlinear Jacobian variables are overwritten.
11:   HA NNZ – INTEGER arrayInput
On entry: HA i must contain the row index of the nonzero element stored in A i, for i=1,2,…,NNZ. The row indices for a column may be supplied in any order subject to the condition that those elements in a column associated with any nonlinear constraints must appear before those elements associated with any linear constraints (including the free row, if any). Note that CONFUN must define the Jacobian elements in the same order. If IOBJ=-1, set HA 1=1.
Constraint: 1≤HA i≤M, for i=1,2,…,NNZ.
12:   KA N+1 – INTEGER arrayInput
On entry: KA j must contain the index in A of the start of the jth column, for j=1,2,…,N. To specify the jth column as empty, set KA j=KA j+1. Note that the first and last elements of KA must be such that KA 1=1 and KA N+1=NNZ+1. If IOBJ=-1, set KA j=2, for j=2,3,…,N.
Constraints:
  • KA 1=1;
  • KA j≥1, for j=2,3,…,N;
  • KA N+1=NNZ+1;
  • 0≤KA j+1-KA j≤M, for j=1,2,…,N.
13:   BL N+M – REAL (KIND=nag_wp) arrayInput
On entry: l, the lower bounds for all the variables and general constraints, in the following order. The first N elements of BL must contain the bounds on the variables x, the next NCNLN elements the bounds for the nonlinear constraints F x (if any) and the next (M-NCNLN) elements the bounds for the linear constraints Gx and the free row (if any). To specify a nonexistent lower bound (i.e., lj=-∞), set BL j≤-bigbnd. To specify the jth constraint as an equality, set BL j=BU j=β, say, where β<bigbnd. If IOBJ=-1, set BL N+abs IOBJ≤-bigbnd.
Constraint: if NCNLN<IOBJ≤M or IOBJ=-1, BL N+abs IOBJ≤-bigbnd
(See also the description for BU.)
14:   BU N+M – REAL (KIND=nag_wp) arrayInput
On entry: u, the upper bounds for all the variables and general constraints, in the following order. The first N elements of BU must contain the bounds on the variables x, the next NCNLN elements the bounds for the nonlinear constraints F x (if any) and the next (M-NCNLN) elements the bounds for the linear constraints Gx and the free row (if any). To specify a nonexistent upper bound (i.e., uj=+∞), set BU j≥bigbnd. To specify the jth constraint as an equality, set BU j=BL j=β, say, where β<bigbnd. If IOBJ=-1, set BU N+abs IOBJ≥bigbnd.
Constraints:
  • if NCNLN<IOBJ≤M or IOBJ=-1, BU N+abs IOBJ≥bigbnd;
  • BL j≤BU j, for j=1,2,…,N+M;
  • if BL j=BU j=β, β<bigbnd.
15:   START – CHARACTER(1)Input
On entry: indicates how a starting basis is to be obtained.
START='C'
An internal Crash procedure will be used to choose an initial basis.
START='W'
A basis is already defined in ISTATE and NS (probably from a previous call).
Constraint: START='C' or 'W'.
16:   NNAME – INTEGERInput
On entry: the number of column (i.e., variable) and row (i.e., constraint) names supplied in NAMES.
NNAME=1
There are no names. Default names will be used in the printed output.
NNAME=N+M
All names must be supplied.
Constraint: NNAME=1 or N+M.
17:   NAMES NNAME – CHARACTER(8) arrayInput
On entry: specifies the column and row names to be used in the printed output.
If NNAME=1, NAMES is not referenced and the printed output will use default names for the columns and rows.
If NNAME=N+M, the first N elements must contain the names for the columns, the next NCNLN elements must contain the names for the nonlinear rows (if any) and the next M-NCNLN elements must contain the names for the linear rows (if any) to be used in the printed output. Note that the name for the free row or dummy ‘free’ row must be stored in NAMES N+abs IOBJ.
18:   NS – INTEGERInput/Output
On entry: nS, the number of superbasics. It need not be specified if START='C', but must retain its value from a previous call when START='W'.
On exit: the final number of superbasics.
19:   XS N+M – REAL (KIND=nag_wp) arrayInput/Output
On entry: the initial values of the variables and slacks x,s. (See the description for ISTATE.)
On exit: the final values of the variables and slacks x,s.
20:   ISTATE N+M – INTEGER arrayInput/Output
On entry: if START='C', the first N elements of ISTATE and XS must specify the initial states and values, respectively, of the variables x. (The slacks s need not be initialized.) An internal Crash procedure is then used to select an initial basis matrix B. The initial basis matrix will be triangular (neglecting certain small elements in each column). It is chosen from various rows and columns of A -I . Possible values for ISTATE j are as follows:
ISTATE j | State of XS j during Crash procedure
0 or 1 | Eligible for the basis
2 | Ignored
3 | Eligible for the basis (given preference over 0 or 1)
4 or 5 | Ignored
If nothing special is known about the problem, or there is no wish to provide special information, you may set ISTATE j=0 and XS j=0.0, for j=1,2,…,N. All variables will then be eligible for the initial basis. Less trivially, to say that the jth variable will probably be equal to one of its bounds, set ISTATE j=4 and XS j=BL j or ISTATE j=5 and XS j=BU j as appropriate.
Following the Crash procedure, variables for which ISTATE j=2 are made superbasic. Other variables not selected for the basis are then made nonbasic at the value XS j if BL j≤XS j≤BU j, or at the value BL j or BU j closest to XS j.
If START='W', ISTATE and XS must specify the initial states and values, respectively, of the variables and slacks x,s. If the routine has been called previously with the same values of N and M, ISTATE already contains satisfactory information.
Constraints:
  • if START='C', 0≤ISTATE j≤5, for j=1,2,…,N;
  • if START='W', 0≤ISTATE j≤3, for j=1,2,…,N+M.
On exit: the final states of the variables and slacks x,s. The significance of each possible value of ISTATE j is as follows:
ISTATE j | State of variable j | Normal value of XS j
0 | Nonbasic | BL j
1 | Nonbasic | BU j
2 | Superbasic | Between BL j and BU j
3 | Basic | Between BL j and BU j
If NINF=0, basic and superbasic variables may be outside their bounds by as much as the value of the optional parameter Minor Feasibility Tolerance. Note that if scaling is specified, the optional parameter Minor Feasibility Tolerance applies to the variables of the scaled problem. In this case, the variables of the original problem may be as much as 0.1 outside their bounds, but this is unlikely unless the problem is very badly scaled.
Very occasionally some nonbasic variables may be outside their bounds by as much as the optional parameter Minor Feasibility Tolerance and there may be some nonbasic variables for which XS j lies strictly between its bounds.
If NINF>0, some basic and superbasic variables may be outside their bounds by an arbitrary amount (bounded by SINF if scaling was not used).
21:   CLAMDA N+M – REAL (KIND=nag_wp) arrayInput/Output
On entry: if NCNLN>0, CLAMDA j must contain a Lagrange multiplier estimate for the jth nonlinear constraint Fj x, for j=N+1,…,N+NCNLN. If nothing special is known about the problem, or there is no wish to provide special information, you may set CLAMDA j=0.0. The remaining elements need not be set.
On exit: a set of Lagrange multipliers for the bounds on the variables (reduced costs) and the general constraints (shadow costs). More precisely, the first N elements contain the multipliers for the bounds on the variables, the next NCNLN elements contain the multipliers for the nonlinear constraints F x (if any) and the next (M-NCNLN) elements contain the multipliers for the linear constraints Gx and the free row (if any).
22:   MINIZ – INTEGEROutput
On exit: the minimum value of LENIZ required to start solving the problem. If IFAIL=12, E04UGF/E04UGA may be called again with LENIZ suitably larger than MINIZ. (The bigger the better, since it is not certain how much workspace the basis factors need.)
23:   MINZ – INTEGEROutput
On exit: the minimum value of LENZ required to start solving the problem. If IFAIL=13, E04UGF/E04UGA may be called again with LENZ suitably larger than MINZ. (The bigger the better, since it is not certain how much workspace the basis factors need.)
24:   NINF – INTEGEROutput
On exit: the number of constraints that lie outside their bounds by more than the value of the optional parameter Minor Feasibility Tolerance.
If the linear constraints are infeasible, the sum of the infeasibilities of the linear constraints is minimized subject to the upper and lower bounds being satisfied. In this case, NINF contains the number of elements of Gx that lie outside their upper or lower bounds. Note that the nonlinear constraints are not evaluated.
Otherwise, the sum of the infeasibilities of the nonlinear constraints is minimized subject to the linear constraints and the upper and lower bounds being satisfied. In this case, NINF contains the number of elements of F x that lie outside their upper or lower bounds.
25:   SINF – REAL (KIND=nag_wp)Output
On exit: the sum of the infeasibilities of constraints that lie outside their bounds by more than the value of the optional parameter Minor Feasibility Tolerance.
26:   OBJ – REAL (KIND=nag_wp)Output
On exit: the value of the objective function.
27:   IZ LENIZ – INTEGER arrayWorkspace
28:   LENIZ – INTEGERInput
On entry: the dimension of the array IZ as declared in the (sub)program from which E04UGF/E04UGA is called.
Constraint: LENIZ≥max 500,N+M.
29:   Z LENZ – REAL (KIND=nag_wp) arrayWorkspace
30:   LENZ – INTEGERInput
On entry: the dimension of the array Z as declared in the (sub)program from which E04UGF/E04UGA is called.
Constraint: LENZ≥500.
The amounts of workspace provided (i.e., LENIZ and LENZ) and required (i.e., MINIZ and MINZ) are (by default) output on the current advisory message unit (as defined by X04ABF). Since the minimum values of LENIZ and LENZ required to start solving the problem are returned in MINIZ and MINZ respectively, you may prefer to obtain appropriate values from the output of a preliminary run with LENIZ set to max 500,N+M and/or LENZ set to 500. (E04UGF/E04UGA will then terminate with IFAIL=15 or 16.)
31:   IUSER* – INTEGER arrayUser Workspace
32:   RUSER* – REAL (KIND=nag_wp) arrayUser Workspace
IUSER and RUSER are not used by E04UGF/E04UGA, but are passed directly to CONFUN and OBJFUN and may be used to pass information to these routines as an alternative to using COMMON global variables.
33:   IFAIL – INTEGERInput/Output
Note: for E04UGA, IFAIL does not occur in this position in the argument list. See the additional arguments described below.
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, because for this routine the values of the output arguments may be useful even if IFAIL≠0 on exit, the recommended value is -1. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).
E04UGF/E04UGA returns with IFAIL=0 if the iterates have converged to a point x that satisfies the first-order Kuhn–Karesh–Tucker conditions (see Section 9.1) to the accuracy requested by the optional parameters Major Feasibility Tolerance (default value=ε) and Major Optimality Tolerance (default value=ε).
Note: the following are additional arguments for specific use with E04UGA. Users of E04UGF therefore need not read the remainder of this description.
33:   LWSAV 20 – LOGICAL arrayCommunication Array
34:   IWSAV 550 – INTEGER arrayCommunication Array
35:   RWSAV 550 – REAL (KIND=nag_wp) arrayCommunication Array
The arrays LWSAV, IWSAV and RWSAV must not be altered between calls to any of the routines E04UGA, E04UHA or E04UJA.
36:   IFAIL – INTEGERInput/Output
Note: see the argument description for IFAIL above.

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Note: E04UGF/E04UGA may return useful information for one or more of the following detected errors or warnings.
Errors or warnings detected by the routine:
IFAIL<0
A negative value of IFAIL indicates an exit from E04UGF/E04UGA because you set MODE<0 in OBJFUN or CONFUN. The value of IFAIL will be the same as your setting of MODE.
IFAIL=1
The problem is infeasible. The general constraints cannot all be satisfied simultaneously to within the values of the optional parameters Major Feasibility Tolerance (default value=ε) and Minor Feasibility Tolerance (default value=ε).
IFAIL=2
The problem is unbounded (or badly scaled). The objective function is not bounded below (or above in the case of maximization) in the feasible region because a nonbasic variable can apparently be increased or decreased by an arbitrary amount without causing a basic variable to violate a bound. Add an upper or lower bound to the variable (whose index is printed by default by E04UGF) and rerun E04UGF/E04UGA.
IFAIL=3
The problem may be unbounded. Check that the values of the optional parameters Unbounded Objective (default value=1015) and Unbounded Step Size (default value=max bigbnd,1020) are not too small. This exit also implies that the objective function is not bounded below (or above in the case of maximization) in the feasible region defined by expanding the bounds by the value of the optional parameter Violation Limit (default value=10.0).
IFAIL=4
Too many iterations. The values of the optional parameters Major Iteration Limit (default value=1000) and/or Iteration Limit (default value=10000) are too small.
IFAIL=5
Feasible solution found, but requested accuracy could not be achieved. Check that the value of the optional parameter Major Optimality Tolerance (default value=ε) is not too small (say, <ε).
IFAIL=6
The value of the optional parameter Superbasics Limit (default value=min 500,n-+1) is too small.
IFAIL=7
An input argument is invalid.
IFAIL=8
The user-supplied derivatives of the objective function computed by OBJFUN appear to be incorrect. Check that OBJFUN has been coded correctly and that all relevant elements of the objective gradient have been assigned their correct values.
IFAIL=9
The user-supplied derivatives of the nonlinear constraint functions computed by CONFUN appear to be incorrect. Check that CONFUN has been coded correctly and that all relevant elements of the nonlinear constraint Jacobian have been assigned their correct values.
IFAIL=10
The current point cannot be improved upon. Check that OBJFUN and CONFUN have been coded correctly and that they are consistent with the value of the optional parameter Derivative Level (default value=3).
IFAIL=11
Numerical error in trying to satisfy the linear constraints (or the linearized nonlinear constraints). The basis is very ill-conditioned.
IFAIL=12
Not enough integer workspace for the basis factors. Increase LENIZ and rerun E04UGF/E04UGA.
IFAIL=13
Not enough real workspace for the basis factors. Increase LENZ and rerun E04UGF/E04UGA.
IFAIL=14
The basis is singular after 15 attempts to factorize it (and adding slacks where necessary). Either the problem is badly scaled or the value of the optional parameter LU Factor Tolerance (default value=5.0 or 100.0) is too large.
IFAIL=15
Not enough integer workspace to start solving the problem. Increase LENIZ to at least MINIZ and rerun E04UGF/E04UGA.
IFAIL=16
Not enough real workspace to start solving the problem. Increase LENZ to at least MINZ and rerun E04UGF/E04UGA.
IFAIL=17
An unexpected error has occurred. Please contact NAG.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

If the value of the optional parameter Major Optimality Tolerance is set to 10-d (default value=ε) and IFAIL=0 on exit, then the final value of f x should have approximately d correct significant digits.

8 Parallelism and Performance

E04UGF/E04UGA is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
E04UGF/E04UGA makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

This section contains a description of the printed output.

9.1 Major Iteration Printout

This section describes the intermediate printout and final printout produced by the major iterations of E04UGF/E04UGA. The intermediate printout is a subset of the monitoring information produced by the routine at every iteration (see Section 13). You can control the level of printed output (see the description of the optional parameter Major Print Level). Note that the intermediate printout and final printout are produced only if Major Print Level≥10 (the default for E04UGF, by default no output is produced by E04UGA).
The following line of summary output (<80 characters) is produced at every major iteration. In all cases, the values of the quantities printed are those in effect on completion of the given iteration.
Maj | is the major iteration count.
Mnr is the number of minor iterations required by the feasibility and optimality phases of the QP subproblem. Generally, Mnr will be 1 in the later iterations, since theoretical analysis predicts that the correct active set will be identified near the solution (see Section 11).
Note that Mnr may be greater than the optional parameter Minor Iteration Limit if some iterations are required for the feasibility phase.
Step | is the step αk taken along the computed search direction. On reasonably well-behaved problems, the unit step (i.e., αk=1) will be taken as the solution is approached.
Merit Function is the value of the augmented Lagrangian merit function (6) at the current iterate. This function will decrease at each iteration unless it was necessary to increase the penalty parameters (see Section 9.1). As the solution is approached, Merit Function will converge to the value of the objective function at the solution.
In elastic mode (see Section 11.2) then the merit function is a composite function involving the constraint violations weighted by the value of the optional parameter Elastic Weight.
If there are no nonlinear constraints present then this entry contains Objective, the value of the objective function f x. In this case, f x will decrease monotonically to its optimal value.
Feasibl is the value of rowerr, the largest element of the scaled nonlinear constraint residual vector defined in the description of the optional parameter Major Feasibility Tolerance. The solution is regarded as ‘feasible’ if Feasibl is less than (or equal to) the optional parameter Major Feasibility Tolerance. Feasibl will be approximately zero in the neighbourhood of a solution.
If there are no nonlinear constraints present, all iterates are feasible and this entry is not printed.
Optimal | is the value of maxgap, the largest element of the maximum complementarity gap vector defined in the description of the optional parameter Major Optimality Tolerance. The Lagrange multipliers are regarded as ‘optimal’ if Optimal is less than (or equal to) the optional parameter Major Optimality Tolerance. Optimal will be approximately zero in the neighbourhood of a solution.
Cond Hz | is an estimate of the condition number of the reduced Hessian of the Lagrangian (not printed if NCNLN and NONLN are both zero). It is the square of the ratio between the largest and smallest diagonal elements of the upper triangular matrix R. This constitutes a lower bound on the condition number of the matrix RT R that approximates the reduced Hessian. The larger this number, the more difficult the problem.
PD | is a two-letter indication of the status of the convergence tests involving the feasibility and optimality of the iterates defined in the descriptions of the optional parameters Major Feasibility Tolerance and Major Optimality Tolerance. Each letter is T if the test is satisfied and F otherwise. The tests indicate whether the values of Feasibl and Optimal are sufficiently small. For example, TF or TT is printed if there are no nonlinear constraints present (since all iterates are feasible). If either indicator is F when E04UGF/E04UGA terminates with IFAIL=0, you should check the solution carefully.
M | is printed if an extra evaluation of user-supplied subroutines OBJFUN and CONFUN was needed in order to define an acceptable positive definite quasi-Newton update to the Hessian of the Lagrangian. This modification is only performed when there are nonlinear constraints present.
m | is printed if, in addition, it was also necessary to modify the update to include an augmented Lagrangian term.
s | is printed if a self-scaled BFGS (Broyden–Fletcher–Goldfarb–Shanno) update was performed. This update is always used when the Hessian approximation is diagonal and hence always follows a Hessian reset.
S | is printed if, in addition, it was also necessary to modify the self-scaled update in order to maintain positive-definiteness.
n | is printed if no positive definite BFGS update could be found, in which case the approximate Hessian is unchanged from the previous iteration.
r | is printed if the approximate Hessian was reset after 10 consecutive major iterations in which no BFGS update could be made. The diagonal elements of the approximate Hessian are retained if at least one update has been performed since the last reset. Otherwise, the approximate Hessian is reset to the identity matrix.
R | is printed if the approximate Hessian has been reset by discarding all but its diagonal elements. This reset will be forced periodically by the values of the optional parameters Hessian Frequency and Hessian Updates. However, it may also be necessary to reset an ill-conditioned Hessian from time to time.
l | is printed if the change in the norm of the variables was greater than the value defined by the optional parameter Major Step Limit. If this output occurs frequently during later iterations, it may be worthwhile increasing the value of Major Step Limit.
c | is printed if central differences have been used to compute the unknown elements of the objective and constraint gradients. A switch to central differences is made if either the linesearch gives a small step, or x is close to being optimal. In some cases, it may be necessary to re-solve the QP subproblem with the central difference gradient and Jacobian.
u | is printed if the QP subproblem was unbounded.
t | is printed if the minor iterations were terminated after the number of iterations specified by the value of the optional parameter Minor Iteration Limit was reached.
i | is printed if the QP subproblem was infeasible when the routine was not in elastic mode. This event triggers the start of nonlinear elastic mode, which remains in effect for all subsequent iterations. Once in elastic mode, the QP subproblems are associated with the elastic problem (8) (see Section 11.2). It is also printed if the minimizer of the elastic subproblem does not satisfy the linearized constraints when the routine is already in elastic mode. (In this case, a feasible point for the usual QP subproblem may or may not exist.)
w | is printed if a weak solution of the QP subproblem was found.
The final printout includes a listing of the status of every variable and constraint.
The following describes the printout for each variable. A full stop (.) is printed for any numerical value that is zero.
Variable | gives the name of the variable. If NNAME=1, a default name is assigned to the jth variable, for j=1,2,…,n. If NNAME=N+M, the name supplied in NAMES j is assigned to the jth variable.
State gives the state of the variable (LL if nonbasic on its lower bound, UL if nonbasic on its upper bound, EQ if nonbasic and fixed, FR if nonbasic and strictly between its bounds, BS if basic and SBS if superbasic).
A key is sometimes printed before State. Note that unless the optional parameter Scale Option=0 is specified, the tests for assigning a key are applied to the variables of the scaled problem.
A | Alternative optimum possible. The variable is nonbasic, but its reduced gradient is essentially zero. This means that if the variable were allowed to start moving away from its current value, there would be no change in the value of the objective function. The values of the basic and superbasic variables might change, giving a genuine alternative solution. The values of the Lagrange multipliers might also change.
D | Degenerate. The variable is basic, but it is equal to (or very close to) one of its bounds.
I | Infeasible. The variable is basic and is currently violating one of its bounds by more than the value of the optional parameter Minor Feasibility Tolerance.
N | Not precisely optimal. The variable is nonbasic. Its reduced gradient is larger than the value of the optional parameter Major Feasibility Tolerance.
Value | is the value of the variable at the final iteration.
Lower Bound | is the lower bound specified for the variable. None indicates that BL j≤-bigbnd.
Upper Bound | is the upper bound specified for the variable. None indicates that BU j≥bigbnd.
Lagr Mult | is the Lagrange multiplier for the associated bound. This will be zero if State is FR. If x is optimal, the multiplier should be non-negative if State is LL, non-positive if State is UL and zero if State is BS or SBS.
Residual | is the difference between the variable Value and the nearer of its (finite) bounds BL j and BU j. A blank entry indicates that the associated variable is not bounded (i.e., BL j≤-bigbnd and BU j≥bigbnd).
The meaning of the printout for general constraints is the same as that given above for variables, with ‘variable’ replaced by ‘constraint’, n replaced by m, NAMES j replaced by NAMES n+j, BL j and BU j are replaced by BL n+j and BU n+j respectively. The heading is changed as follows:
Constrnt gives the name of the general constraint.
Numerical values are output with a fixed number of digits; they are not guaranteed to be accurate to this precision.

9.2 Minor Iteration Printout

This section describes the printout produced by the minor iterations of E04UGF/E04UGA, which involve solving a QP subproblem at every major iteration. (Further details can be found in Section 9.1.) The printout is a subset of the monitoring information produced by the routine at every iteration (see Section 13). You can control the level of printed output (see the description of the optional parameter Minor Print Level). Note that the printout is produced only if Minor Print Level≥1 (default value=0, which produces no output).
The following line of summary output (<80 characters) is produced at every minor iteration. In all cases, the values of the quantities printed are those in effect on completion of the given iteration of the QP subproblem.
Itn | is the iteration count.
Step | is the step taken along the computed search direction.
Ninf | is the number of infeasibilities. This will not increase unless the iterations are in elastic mode. Ninf will be zero during the optimality phase.
Sinf | is the value of the sum of infeasibilities if Ninf is nonzero. This will be zero during the optimality phase.
Objective | is the value of the current QP objective function when Ninf is zero and the iterations are not in elastic mode. The switch to elastic mode is indicated by a change in the heading to Composite Obj.
Composite Obj | is the value of the composite objective function (9) when the iterations are in elastic mode. This function will decrease monotonically at each iteration.
Norm rg | is the Euclidean norm of the reduced gradient of the QP objective function. During the optimality phase, this norm will be approximately zero after a unit step.
Numerical values are output with a fixed number of digits; they are not guaranteed to be accurate to this precision.

10 Example

This is a reformulation of Problem 74 in Hock and Schittkowski (1981) and involves the minimization of the nonlinear function
f x=10-6 x 33+23×10-6 x 43+3 x 3+2 x 4
subject to the bounds
-0.55≤x 1≤ 0.55, -0.55≤x 2≤ 0.55, - 0.0 0≤x 3≤ 1200, - 0.0 0≤x 4≤ 1200,
to the nonlinear constraints
1000 sin-x 1-0.25 + 1000 sin-x 2-0.25-x 3 = -894.8, 1000 sin x 1-0.25 + 1000 sin x 1-x 2-0.25-x 4 = -894.8, 1000 sin x 2-0.25 + 1000 sin x 2-x 1-0.25 = -1294.8,
and to the linear constraints
-x 1+x 2≥-0.55, -x 1-x 2≥-0.55.
The initial point, which is infeasible, is
x 0 = 0, 0, 0, 0 T ,
and f x 0=0.
The optimal solution (to five figures) is
x*=0.11887,-0.39623,679.94,1026.0 T,
and f x*=5126.4. All the nonlinear constraints are active at the solution.
The document for E04UHF/E04UHA includes an example program to solve Problem 45 from Hock and Schittkowski (1981) using some of the optional parameters described in Section 12.

10.1 Program Text

Note: the following programs illustrate the use of E04UGF and E04UGA.

Program Text (e04ugfe.f90)

Program Text (e04ugae.f90)

10.2 Program Data

Program Data (e04ugfe.d)

Program Data (e04ugae.d)

10.3 Program Results

Program Results (e04ugfe.r)

Program Results (e04ugae.r)

Note: the remainder of this document is intended for more advanced users. Section 11 contains a detailed description of the algorithm which may be needed in order to understand Sections 12 and 13. Section 12 describes the optional parameters which may be set by calls to E04UHF/E04UHA and/or E04UJF/E04UJA. Section 13 describes the quantities which can be requested to monitor the course of the computation.

11 Algorithmic Details

This section contains a detailed description of the method used by E04UGF/E04UGA.

11.1 Overview

Here we briefly summarise the main features of the method and introduce some terminology. Where possible, explicit reference is made to the names of variables that are arguments of the routine or appear in the printed output. Further details can be found in Gill et al. (2002).
At a solution of (1), some of the constraints will be active, i.e., satisfied exactly. Let
r x= x F x Gx
and G denote the set of indices of r x corresponding to active constraints at an arbitrary point x. Let rj′x denote the usual derivative of rj x, which is the row vector of first partial derivatives of rj x (see Ortega and Rheinboldt (1970)). The vector rj′x comprises the jth row of r′x so that
r′x= I J x G ,
where J x is the Jacobian of F x.
A point x is a first-order Kuhn–Karesh–Tucker (KKT) point for (1) (see Powell (1974)) if the following conditions hold:
(a) | x is feasible;
(b) there exists a vector λ (the Lagrange multiplier vector for the bound and general constraints) such that
g x=r′x T λ=I J x T GT λ, (4)
where g is the gradient of f evaluated at x;
(c) | the Lagrange multiplier λj associated with the jth constraint satisfies λj=0 if lj<rj x<uj; λj≥0 if lj=rj x; λj≤0 if rj x=uj; and λj can have any value if lj=uj.
An equivalent statement of the condition (4) is
ZT g x=0,
where Z is a matrix defined as follows. Consider the set N of vectors orthogonal to the gradients of the active constraints, i.e.,
N = z   ∣   rj′ x z=0   for all   j∈G .
The columns of Z may then be taken as any basis for the vector space N. The vector ZT g is termed the reduced gradient of f at x. Certain additional conditions must be satisfied in order for a first-order KKT point to be a solution of (1) (see Powell (1974)).
The basic structure of E04UGF/E04UGA involves major and minor iterations. The major iterations generate a sequence of iterates xk that satisfy the linear constraints and converge to a point x* that satisfies the first-order KKT optimality conditions. At each iterate a QP subproblem is used to generate a search direction towards the next iterate (x k+1). The constraints of the subproblem are formed from the linear constraints Gx-sL=0 and the nonlinear constraint linearization
F xk+F′xkx-xk-sN=0,
where F′xk denotes the Jacobian matrix, whose rows are the first partial derivatives of F x evaluated at the point xk. The QP constraints therefore comprise the m linear constraints
F′xk x-sN-sL=-F xk+F′xk xk, 'xk Gx-sN-sL=0,F xk+F′xk xk
where x and s=sN,sL T are bounded above and below by u and l as before. If the m by n matrix A and m element vector b are defined as
A= F′xk G   and  b= -F xk+F′xk xk 0 ,
then the QP subproblem can be written as
minimize x,s q x  subject to  Ax-s=b,  l≤ x s ≤u, (5)
where q x is a quadratic approximation to a modified Lagrangian function (see Gill et al. (2002)).
The linear constraint matrix A is stored in the arrays A, HA and KA (see Section 5). This allows you to specify the sparsity pattern of nonzero elements in F′x and G and to identify any nonzero elements that remain constant throughout the minimization.
Solving the QP subproblem is itself an iterative procedure, with the minor iterations of an SQP method being the iterations of the QP method. At each minor iteration, the constraints Ax-s=b are (conceptually) partitioned into the form
B xB+S xS+N xN=b,
where the basis matrix B is square and nonsingular. The elements of xB, xS and xN are called the basic, superbasic and nonbasic variables respectively; they are a permutation of the elements of x and s. At a QP solution, the basic and superbasic variables will lie somewhere between their bounds, while the nonbasic variables will be equal to one of their upper or lower bounds. At each minor iteration, xS is regarded as a set of independent variables that are free to move in any desired direction, namely one that will improve the value of the QP objective function q x or sum of infeasibilities (as appropriate). The basic variables are then adjusted in order to ensure that (x,s) continues to satisfy Ax-s=b. The number of superbasic variables (nS say) therefore indicates the number of degrees of freedom remaining after the constraints have been satisfied. In broad terms, nS is a measure of how nonlinear the problem is. In particular, nS will always be zero if there are no nonlinear constraints in (1) and f x is linear.
If it appears that no improvement can be made with the current definition of B, S and N, a nonbasic variable is selected to be added to S and the process is repeated with the value of nS increased by one. At all stages, if a basic or superbasic variable encounters one of its bounds, the variable is made nonbasic and the value of nS decreased by one.
Associated with each of the m equality constraints Ax-s=b is a dual variable πi. Similarly, each variable in x,s has an associated reduced gradient dj (also known as a reduced cost). The reduced gradients for the variables x are the quantities g-AT π, where g is the gradient of the QP objective function q x; the reduced gradients for the slack variables s are the dual variables π. The QP subproblem (5) is optimal if dj≥0 for all nonbasic variables at their lower bounds, dj≤0 for all nonbasic variables at their upper bounds and dj=0 for other variables (including superbasics). In practice, an approximate QP solution is found by slightly relaxing these conditions on dj (see the description of the optional parameter Minor Optimality Tolerance).
After a QP subproblem has been solved, new estimates of the solution to (1) are computed using a linesearch on the augmented Lagrangian merit function
M x,s,π = f x - πT F x - sN + 12 F x - sN T D F x - sN , (6)
where D is a diagonal matrix of penalty parameters. If (xk,sk,πk) denotes the current estimate of the solution and (x^,s^,π^) denotes the optimal QP solution, the linesearch determines a step αk (where 0<αk≤1) such that the new point
x k+1 s k+1 π k+1 = xk sk πk +αk x^k-xk s^k-sk π^k-πk
produces a sufficient decrease in the merit function (6). When necessary, the penalties in D are increased by the minimum-norm perturbation that ensures descent for M (see Gill et al. (1992)). As in E04WDF, sN is adjusted to minimize the merit function as a function of s before the solution of the QP subproblem. Further details can be found in Eldersveld (1991) and Gill et al. (1986).

11.2 Treatment of Constraint Infeasibilities

E04UGF/E04UGA makes explicit allowance for infeasible constraints. Infeasible linear constraints are detected first by solving a problem of the form
minimize x,v,w eT v+w  subject to  l≤ x Gx-v+w ≤u,  v≥0,  w≥0, (7)
where e=1,1,…,1 T. This is equivalent to minimizing the sum of the general linear constraint violations subject to the simple bounds. (In the linear programming literature, the approach is often called elastic programming.)
If the linear constraints are infeasible (i.e., v≠0 or w≠0), the routine terminates without computing the nonlinear functions.
If the linear constraints are feasible, all subsequent iterates will satisfy the linear constraints. (Such a strategy allows linear constraints to be used to define a region in which f x and F x can be safely evaluated.) The routine then proceeds to solve (1) as given, using search directions obtained from a sequence of QP subproblems (5). Each QP subproblem minimizes a quadratic model of a certain Lagrangian function subject to linearized constraints. An augmented Lagrangian merit function (6) is reduced along each search direction to ensure convergence from any starting point.
The routine enters ‘elastic’ mode if the QP subproblem proves to be infeasible or unbounded (or if the dual variables π for the nonlinear constraints become ‘large’) by solving a problem of the form
minimize x,v,w f-x,v,w  subject to  l≤ x F x-v+w Gx ≤u,  v≥0,  w≥0, (8)
where
f-x,v,w=f x+γ eT v+w (9)
is called a composite objective and γ is a non-negative argument (the elastic weight). If γ is sufficiently large, this is equivalent to minimizing the sum of the nonlinear constraint violations subject to the linear constraints and bounds. A similar l 1 formulation of (1) is fundamental to the Sl 1QP algorithm of Fletcher (1984). See also Conn (1973).

12 Optional Parameters

Several optional parameters in E04UGF/E04UGA define choices in the problem specification or the algorithm logic. In order to reduce the number of formal arguments of E04UGF/E04UGA these optional parameters have associated default values that are appropriate for most problems. Therefore, you need only specify those optional parameters whose values are to be different from their default values.
The remainder of this section can be skipped if you wish to use the default values for all optional parameters.
The following is a list of the optional parameters available. A full description of each optional parameter is provided in Section 12.1.
  • Central Difference Interval
  • Check Frequency
  • Crash Option
  • Crash Tolerance
  • Defaults
  • Derivative Level
  • Derivative Linesearch
  • Elastic Weight
  • Expand Frequency
  • Factorization Frequency
  • Feasibility Tolerance
  • Feasible Exit
  • Feasible Point
  • Forward Difference Interval
  • Function Precision
  • Hessian Frequency
  • Hessian Full Memory
  • Hessian Limited Memory
  • Hessian Updates
  • Infeasible Exit
  • Infinite Bound Size
  • Iteration Limit
  • Linesearch Tolerance
  • List
  • LU Density Tolerance
  • LU Factor Tolerance
  • LU Singularity Tolerance
  • LU Update Tolerance
  • Major Feasibility Tolerance
  • Major Iteration Limit
  • Major Optimality Tolerance
  • Major Print Level
  • Major Step Limit
  • Maximize
  • Minimize
  • Minor Feasibility Tolerance
  • Minor Iteration Limit
  • Minor Optimality Tolerance
  • Minor Print Level
  • Monitoring File
  • Nolist
  • Nonderivative Linesearch
  • Optimality Tolerance
  • Partial Price
  • Pivot Tolerance
  • Print Level
  • Scale Option
  • Scale Tolerance
  • Start Constraint Check At Column
  • Start Objective Check At Column
  • Stop Constraint Check At Column
  • Stop Objective Check At Column
  • Superbasics Limit
  • Unbounded Objective
  • Unbounded Step Size
  • Verify Level
  • Violation Limit
Optional parameters may be specified by calling one, or both, of the routines E04UHF/E04UHA and E04UJF/E04UJA before a call to E04UGF/E04UGA.
E04UHF/E04UHA reads options from an external options file, with Begin and End as the first and last lines respectively and each intermediate line defining a single optional parameter. For example,
Begin
  Print Level = 5
End
The call

 Call E04UHF (IOPTNS, INFORM)
can then be used to read the file on unit IOPTNS. INFORM will be zero on successful exit. E04UHF/E04UHA should be consulted for a full description of this method of supplying optional parameters.
E04UJF/E04UJA can be called to supply options directly, one call being necessary for each optional parameter. For example,
 CALL E04UJF ('Print Level = 5')
E04UJF/E04UJA should be consulted for a full description of this method of supplying optional parameters.
All optional parameters not specified by you are set to their default values. Optional parameters specified by you are unaltered by E04UGF/E04UGA (unless they define invalid values) and so remain in effect for subsequent calls to E04UGF/E04UGA from the calling program (unless altered by you).

12.1 Description of the Optional Parameters

For each option, we give a summary line, a description of the optional parameter and details of constraints.
The summary line contains:
  • the keywords, where the minimum abbreviation of each keyword is underlined (if no characters of an optional qualifier are underlined, the qualifier may be omitted);
  • a parameter value, where the letters a, i and r denote options that take character, integer and real values respectively;
  • the default value is used whenever the condition i≥100000000 is satisfied and where the symbol ε is a generic notation for machine precision (see X02AJF).
Keywords and character values are case and white space insensitive.
Central Difference Interval r Default =Function Precision 3
Note that this option does not apply when Derivative Level=3.
The value of r is used near an optimal solution in order to obtain more accurate (but more expensive) estimates of gradients. This requires twice as many function evaluations as compared to using forward differences (see optional parameter Forward Difference Interval). The interval used for the jth variable is hj=r 1+xj. The resulting gradient estimates should be accurate to O r 2, unless the functions are badly scaled. The switch to central differences is indicated by c at the end of each line of intermediate printout produced by the major iterations (see Section 9.1). See Gill et al. (1981) for a discussion of the accuracy in finite difference approximations.
If r≤0, the default value is used.
Check Frequency i Default =60
Every ith minor iteration after the most recent basis factorization, a numerical test is made to see if the current solution x,s satisfies the general linear constraints (including any linearized nonlinear constraints). The constraints are of the form Ax-s=b, where s is the set of slack variables. If the largest element of the residual vector r=b-Ax+s is judged to be too large, the current basis is refactorized and the basic variables recomputed to satisfy the general constraints more accurately.
If i<0, the default value is used. If i=0, the value i=99999999 is used and effectively no checks are made.
Crash Option i Default =0​ or ​3
The default value of i is 0 if there are any nonlinear constraints and 3 otherwise. Note that this option does not apply when START='W' (see Section 5).
If START='C', an internal Crash procedure is used to select an initial basis from various rows and columns of the constraint matrix A -I . The value of i determines which rows and columns of A are initially eligible for the basis and how many times the Crash procedure is called. Columns of -I are used to pad the basis where necessary. The possible choices for i are the following.
i | Meaning
0 | The initial basis contains only slack variables: B=I.
1 | The Crash procedure is called once (looking for a triangular basis in all rows and columns of A).
2 | The Crash procedure is called twice (if there are any nonlinear constraints). The first call looks for a triangular basis in linear rows and the iteration proceeds with simplex iterations until the linear constraints are satisfied. The Jacobian is then evaluated for the first major iteration and the Crash procedure is called again to find a triangular basis in the nonlinear rows (whilst retaining the current basis for linear rows).
3 | The Crash procedure is called up to three times (if there are any nonlinear constraints). The first two calls treat linear equality constraints and linear inequality constraints separately. The Jacobian is then evaluated for the first major iteration and the Crash procedure is called again to find a triangular basis in the nonlinear rows (whilst retaining the current basis for linear rows).
If i<0 or i>3, the default value is used.
If i≥1, certain slacks on inequality rows are selected for the basis first. (If i≥2, numerical values are used to exclude slacks that are close to a bound.) The Crash procedure then makes several passes through the columns of A, searching for a basis matrix that is essentially triangular. A column is assigned to ‘pivot’ on a particular row if the column contains a suitably large element in a row that has not yet been assigned. (The pivot elements ultimately form the diagonals of the triangular basis.) For remaining unassigned rows, slack variables are inserted to complete the basis.
Crash Tolerance r Default =0.1
The value r (0≤r<1) allows the Crash procedure to ignore certain ‘small’ nonzero elements in the columns of A while searching for a triangular basis. If amax is the largest element in the jth column, other nonzeros a ij in the column are ignored if a ij≤amax×r.
When r>0, the basis obtained by the Crash procedure may not be strictly triangular, but it is likely to be nonsingular and almost triangular. The intention is to obtain a starting basis containing more columns of A and fewer (arbitrary) slacks. A feasible solution may be reached earlier on some problems.
If r<0 or r≥1, the default value is used.
Defaults
This special keyword may be used to reset all optional parameters to their default values.
Derivative Level i Default =3
This parameter indicates which nonlinear function gradients are provided in user-supplied subroutines OBJFUN and CONFUN. The possible choices for i are the following.
i | Meaning
3 | All elements of the objective gradient and the constraint Jacobian are provided.
2 | All elements of the constraint Jacobian are provided, but some (or all) elements of the objective gradient are not specified.
1 | All elements of the objective gradient are provided, but some (or all) elements of the constraint Jacobian are not specified.
0 | Some (or all) elements of both the objective gradient and the constraint Jacobian are not specified.
The default value i=3 should be used whenever possible. It is the most reliable and will usually be the most efficient.
If i=0​ or ​2, E04UGF/E04UGA will estimate the unspecified elements of the objective gradient, using finite differences. This may simplify the coding of OBJFUN. However, the computation of finite difference approximations usually increases the total run-time substantially (since a call to OBJFUN is required for each unspecified element) and there is less assurance that an acceptable solution will be found.
If i=0​ or ​1, E04UGF/E04UGA will approximate unspecified elements of the constraint Jacobian. For each column of the Jacobian, one call to CONFUN is needed to estimate all unspecified elements in that column (if any). For example, if the sparsity pattern of the Jacobian has the form
* * * * * ? ? * * * ? * * * * *
where ‘*’ indicates an element provided and ‘?’ indicates an unspecified element, E04UGF/E04UGA will call CONFUN twice: once to estimate the missing element in column 2 and again to estimate the two missing elements in column 3. (Since columns 1 and 4 are known, they require no calls to CONFUN.)
At times, central differences are used rather than forward differences, in which case twice as many calls to OBJFUN and CONFUN are needed. (The switch to central differences is not under your control.)
If i<0 or i>3, the default value is used.
Derivative Linesearch Default
Nonderivative Linesearch
At each major iteration, a linesearch is used to improve the value of the Lagrangian merit function (6). The default linesearch uses safeguarded cubic interpolation and requires both function and gradient values in order to compute estimates of the step αk. If some analytic derivatives are not provided or optional parameter Nonderivative Linesearch is specified, a linesearch based upon safeguarded quadratic interpolation (which does not require the evaluation or approximation of any gradients) is used instead.
A nonderivative linesearch can be slightly less robust on difficult problems and it is recommended that the default be used if the functions and their derivatives can be computed at approximately the same cost. If the gradients are very expensive to compute relative to the functions however, a nonderivative linesearch may result in a significant decrease in the total run-time.
If optional parameter Nonderivative Linesearch is selected, E04UGF/E04UGA signals the evaluation of the linesearch by calling OBJFUN and CONFUN with MODE=0. Once the linesearch is complete, the nonlinear functions are re-evaluated with MODE=2. If the potential savings offered by a nonderivative linesearch are to be fully realised, it is essential that OBJFUN and CONFUN be coded so that no derivatives are computed when MODE=0.
Elastic Weight r Default =1.0 or 100.0
The default value of r is 100.0 if there are any nonlinear constraints and 1.0 otherwise.
This option defines the initial weight γ associated with problem (8).
At any given major iteration k, elastic mode is entered if the QP subproblem is infeasible or the QP dual variables (Lagrange multipliers) are larger in magnitude than r×1+g xk 2, where g is the objective gradient. In either case, the QP subproblem is resolved in elastic mode with γ=r×1+g xk 2.
Thereafter, γ is increased (subject to a maximum allowable value) at any point that is optimal for problem (8), but not feasible for problem (1). After the pth increase, γ=r×10 p×1+g x k 1 2, where x k 1 is the iterate at which γ was first needed.
If r<0, the default value is used.
Expand Frequency i Default =10000
This option is part of the EXPAND anti-cycling procedure due to Gill et al. (1989), which is designed to make progress even on highly degenerate problems.
For linear models, the strategy is to force a positive step at every iteration, at the expense of violating the constraints by a small amount. Suppose that the value of optional parameter Minor Feasibility Tolerance is δ. Over a period of i iterations, the feasibility tolerance actually used by E04UGF/E04UGA (i.e., the working feasibility tolerance) increases from 0.5 δ to δ (in steps of 0.5 δ/i).
For nonlinear models, the same procedure is used for iterations in which there is only one superbasic variable. (Cycling can only occur when the current solution is at a vertex of the feasible region.) Thus, zero steps are allowed if there is more than one superbasic variable, but otherwise positive steps are enforced.
Increasing the value of i helps reduce the number of slightly infeasible nonbasic basic variables (most of which are eliminated during the resetting procedure). However, it also diminishes the freedom to choose a large pivot element (see optional parameter Pivot Tolerance).
If i<0, the default value is used. If i=0, the value i=99999999 is used and effectively no anti-cycling procedure is invoked.
Factorization Frequency i Default =50​ or ​100
The default value of i is 50 if there are any nonlinear constraints and 100 otherwise.
If i>0, at most i basis changes will occur between factorizations of the basis matrix.
For linear problems, the basis factors are usually updated at every iteration. The default value i=100 is reasonable for typical problems, particularly those that are extremely sparse and well-scaled.
When the objective function is nonlinear, fewer basis updates will occur as the solution is approached. The number of iterations between basis factorizations will therefore increase. During these iterations a test is made regularly according to the value of optional parameter Check Frequency to ensure that the general constraints are satisfied. If necessary, the basis will be refactorized before the limit of i updates is reached.
If i≤0, the default value is used.
Infeasible Exit Default
Feasible Exit
Note that this option is ignored if the value of optional parameter Major Iteration Limit is exceeded, or the linear constraints are infeasible.
If termination is about to occur at a point that does not satisfy the nonlinear constraints and optional parameter Feasible Exit is selected, this option requests that additional iterations be performed in order to find a feasible point (if any) for the nonlinear constraints. This involves solving a feasible point problem in which the objective function is omitted.
Otherwise, this option requests no additional iterations be performed.
Minimize Default
Maximize
Feasible Point
If optional parameter Feasible Point is selected, this option attempts to find a feasible point (if any) for the nonlinear constraints by omitting the objective function. It can also be used to check whether the nonlinear constraints are feasible.
Otherwise, this option specifies the required direction of the optimization. It applies to both linear and nonlinear terms (if any) in the objective function. Note that if two problems are the same except that one minimizes f x and the other maximizes -f x, their solutions will be the same but the signs of the dual variables πi and the reduced gradients dj will be reversed.
Forward Difference Interval r Default =Function Precision
This option defines an interval used to estimate derivatives by forward differences in the following circumstances:
(a) | For verifying the objective and/or constraint gradients (see the description of the optional parameter Verify Level).
(b) | For estimating unspecified elements of the objective gradient and/or the constraint Jacobian.
A derivative with respect to xj is estimated by perturbing that element of x to the value xj+r 1+xj and then evaluating f x and/or F x (as appropriate) at the perturbed point. The resulting gradient estimates should be accurate to O r, unless the functions are badly scaled. Judicious alteration of r may sometimes lead to greater accuracy. See Gill et al. (1981) for a discussion of the accuracy in finite difference approximations.
If r≤0, the default value is used.
Function Precision r Default =ε 0.8
This parameter defines the relative function precision εr, which is intended to be a measure of the relative accuracy with which the nonlinear functions can be computed. For example, if f x (or Fi x) is computed as 1000.56789 for some relevant x and the first 6 significant digits are known to be correct then the appropriate value for εr would be 10-6.
Ideally the functions f x or Fi x should have magnitude of order 1. If all functions are substantially less than 1 in magnitude, εr should be the absolute precision. For example, if f x (or Fi x) is computed as 1.23456789×10-4 for some relevant x and the first 6 significant digits are known to be correct then the appropriate value for εr would be 10-10.
The choice of εr can be quite complicated for badly scaled problems; see Chapter 8 of Gill et al. (1981) for a discussion of scaling techniques. The default value is appropriate for most simple functions that are computed with full accuracy.
In some cases the function values will be the result of extensive computation, possibly involving an iterative procedure that can provide few digits of precision at reasonable cost. Specifying an appropriate value of r may therefore lead to savings, by allowing the linesearch procedure to terminate when the difference between function values along the search direction becomes as small as the absolute error in the values.
If r<ε or r≥1, the default value is used.
Hessian Frequency i Default =99999999
This option forces the approximate Hessian formed from i BFGS updates to be reset to the identity matrix upon completion of a major iteration. It is intended to be used in conjunction with optional parameter Hessian Full Memory.
If i≤0, the default value is used and effectively no resets occur.
Hessian Full Memory Default when n-<75
Hessian Limited Memory Default when n-≥75
These options specify the method for storing and updating the quasi-Newton approximation to the Hessian of the Lagrangian function.
If Hessian Full Memory is specified, the approximate Hessian is treated as a dense matrix and BFGS quasi-Newton updates are applied explicitly. This is most efficient when the total number of nonlinear variables is not too large (say, n-<75). In this case, the storage requirement is fixed and you can expect 1-step Q-superlinear convergence to the solution.
Hessian Limited Memory should only be specified when n- is very large. In this case a limited memory procedure is used to update a diagonal Hessian approximation Hr a limited number of times. (Updates are accumulated as a list of vector pairs. They are discarded at regular intervals after Hr has been reset to their diagonal.)
Note that if Hessian Frequency=20 is used in conjunction with Hessian Full Memory, the effect will be similar to using Hessian Limited Memory in conjunction with Hessian Updates=20, except that the latter will retain the current diagonal during resets.
Hessian Updates i Default =20​ or ​99999999
The default value of i is 20 when Hessian Limited Memory is in effect and 99999999 when Hessian Full Memory is in effect, in which case no updates are performed.
If Hessian Limited Memory is in effect, this option defines the maximum number of pairs of Hessian update vectors that are to be used to define the quasi-Newton approximate Hessian. Once the limit of i updates is reached, all but the diagonal elements of the accumulated updates are discarded and the process starts again. Broadly speaking, the more updates that are stored, the better the quality of the approximate Hessian. On the other hand, the more vectors that are stored, the greater the cost of each QP iteration.
The default value of i is likely to give a robust algorithm without significant expense, but faster convergence may be obtained with far fewer updates (e.g., i=5).
If i<0, the default value is used.
Infinite Bound Size r Default =1020
If r>0, r defines the ‘infinite’ bound bigbnd in the definition of the problem constraints. Any upper bound greater than or equal to bigbnd will be regarded as +∞ (and similarly any lower bound less than or equal to -bigbnd will be regarded as -∞).
If r≤0, the default value is used.
Iteration Limit i Default =10000
The value of i specifies the maximum number of minor iterations allowed (i.e., iterations of the simplex method or the QP algorithm), summed over all major iterations. (See also the description of the optional parameters Major Iteration Limit and Minor Iteration Limit.)
If i<0, the default value is used.
Linesearch Tolerance r Default =0.9
This option controls the accuracy with which a step length will be located along the direction of search at each iteration. At the start of each linesearch a target directional derivative for the Lagrangian merit function is identified. The value of r therefore determines the accuracy to which this target value is approximated.
The default value r=0.9 requests an inaccurate search and is appropriate for most problems, particularly those with any nonlinear constraints.
If the nonlinear functions are cheap to evaluate, a more accurate search may be appropriate; try r=0.1,0.01 ​ or ​ 0.001. The number of major iterations required to solve the problem might decrease.
If the nonlinear functions are expensive to evaluate, a less accurate search may be appropriate. If Derivative Level=3, try r=0.99. (The number of major iterations required to solve the problem might increase, but the total number of function evaluations may decrease enough to compensate.)
If Derivative Level<3, a moderately accurate search may be appropriate; try r=0.5. Each search will (typically) require only 1-5 function values, but many function calls will then be needed to estimate the missing gradients for the next iteration.
If r<0 or r≥1, the default value is used.
List Default for E04UGF =List
Nolist Default for E04UGA =Nolist
Normally each optional parameter specification is printed as it is supplied. Optional parameter Nolist may be used to suppress the printing and optional parameter List may be used to restore printing.
LU Density Tolerance r 1 Default =0.6
LU Singularity Tolerance r 2 Default =ε 0.67
If r 1>0, r 1 defines the density tolerance used during the LU factorization of the basis matrix. Columns of L and rows of U are formed one at a time and the remaining rows and columns of the basis are altered appropriately. At any stage, if the density of the remaining matrix exceeds r 1, the Markowitz strategy for choosing pivots is terminated. The remaining matrix is then factorized using a dense LU procedure. Increasing the value of r 1 towards unity may give slightly sparser LU factors, with a slight increase in factorization time. If r 1≤0, the default value is used.
If r 2>0, r 2 defines the singularity tolerance used to guard against ill-conditioned basis matrices. Whenever the basis is refactorized, the diagonal elements of U are tested as follows. If u jj≤r 2 or u jj<r 2×maxi u ij, the jth column of the basis is replaced by the corresponding slack variable. This is most likely to occur when START='W' (see Section 5), or at the start of a major iteration. If r 2≤0, the default value is used.
In some cases, the Jacobian matrix may converge to values that make the basis exactly singular (e.g., a whole row of the Jacobian matrix could be zero at an optimal solution). Before exact singularity occurs, the basis could become very ill-conditioned and the optimization could progress very slowly (if at all). Setting r 2=0.00001 (say) may therefore help cause a judicious change of basis in such situations.
LU Factor Tolerance r 1 Default =5.0 or 100.0
LU Update Tolerance r 2 Default =5.0 or 10.0
The default value of r 1 is 5.0 if there are any nonlinear constraints and 100.0 otherwise. The default value of r 2 is 5.0 if there are any nonlinear constraints and 10.0 otherwise.
If r 1≥1 and r 2≥1, the values of r 1 and r 2 affect the stability and sparsity of the basis factorization B=LU, during refactorization and updating, respectively. The lower triangular matrix L is a product of matrices of the form
1 0 μ 1 ,
where the multipliers μ satisfy μ≤ri. Smaller values of ri favour stability, while larger values favour sparsity. The default values of r 1 and r 2 usually strike a good compromise. For large and relatively dense problems, setting r 1=10.0 ​ or ​ 5.0 (say) may give a marked improvement in sparsity without impairing stability to a serious degree. Note that for problems involving band matrices, it may be necessary to reduce r 1 and/or r 2 in order to achieve stability.
If r 1<1 or r 2<1, the appropriate default value is used.
Major Feasibility Tolerance r Default =ε
This option specifies how accurately the nonlinear constraints should be satisfied. The default value is appropriate when the linear and nonlinear constraints contain data to approximately that accuracy. A larger value may be appropriate if some of the problem functions are known to be of low accuracy.
Let rowerr be defined as the maximum nonlinear constraint violation normalized by the size of the solution. It is required to satisfy
rowerr=maxi violi x,s ≤r,
where violi is the violation of the ith nonlinear constraint.
If r≤ε, the default value is used.
Major Iteration Limit i Default =1000
The value of i specifies the maximum number of major iterations allowed before termination. It is intended to guard against an excessive number of linearizations of the nonlinear constraints. Setting i=0 and Major Print Level>0 means that the objective and constraint gradients will be checked if Verify Level>0 and the workspace needed to start solving the problem will be computed and printed, but no iterations will be performed.
If i<0, the default value is used.
Major Optimality Tolerance r Default =ε
Optimality Tolerance r
This option specifies the final accuracy of the dual variables. If E04UGF/E04UGA terminates with IFAIL=0, a primal and dual solution (x,s,π) will have been computed such that
maxgap=maxj gapj π≤r,
where gapj is an estimate of the complementarity gap for the jth variable and π is a measure of the size of the QP dual variables (or Lagrange multipliers) given by
π=max σ m,1,   where  σ=∑i=1 m πi.
It is included to make the tests independent of a scale factor on the objective function. Specifically, gapj is computed from the final QP solution using the reduced gradients dj=gj-πT aj, where gj is the jth element of the objective gradient and aj is the associated column of the constraint matrix A -I :
gapj = -dj min xj-lj,1 if ​dj≥0; -dj min uj-xj,1 if ​dj<0.
If r≤0, the default value is used.
Major Print Level i Default for E04UGF =10
Default for E04UGA =0
Print Level
The value of i controls the amount of printout produced by the major iterations of E04UGF/E04UGA, as indicated below. A detailed description of the printed output is given in Section 9.1 (summary output at each major iteration and the final solution) and Section 13 (monitoring information at each major iteration). (See also the description of the optional parameter Minor Print Level.)
The following printout is sent to the current advisory message unit (as defined by X04ABF):
i | Output
≥0 0 | No output.
≥0 1 | The final solution only.
≥0 5 | One line of summary output (<80 characters; see Section 9.1) for each major iteration (no printout of the final solution).
≥10 | The final solution and one line of summary output for each major iteration.
The following printout is sent to the logical unit number by the optional parameter Monitoring File:
i | Output
≥0 0 | No output.
≥0 1 | The final solution only.
≥0 5 | One long line of output (<120 characters; see Section 13) for each major iteration (no printout of the final solution).
≥10 | The final solution and one long line of output for each major iteration.
≥20 | The final solution, one long line of output for each major iteration, matrix statistics (initial status of rows and columns, number of elements, density, biggest and smallest elements, etc.), details of the scale factors resulting from the scaling procedure (if Scale Option=1 or 2), basis factorization statistics and details of the initial basis resulting from the Crash procedure (if START='C'; see Section 5).
If Major Print Level≥5 and the unit number defined by the optional parameter Monitoring File is the same as that defined by X04ABF, then the summary output for each major iteration is suppressed.
Major Step Limit r Default =2.0
If r>0,r limits the change in x during a linesearch. It applies to all nonlinear problems once a ‘feasible solution’ or ‘feasible subproblem’ has been found.
A linesearch determines a step α in the interval 0<α≤β, where β=1 if there are any nonlinear constraints, or the step to the nearest upper or lower bound on x if all the constraints are linear. Normally, the first step attempted is α 1=min 1,β.
In some cases, such as f x=a e bx or f x=a xb, even a moderate change in the elements of x can lead to floating-point overflow. The parameter r is therefore used to define a step limit β- given by
β-=r 1+x 2 p 2 ,
where p is the search direction and the first evaluation of f x is made at the (potentially) smaller step length α 1=min 1,β-,β.
Wherever possible, upper and lower bounds on x should be used to prevent evaluation of nonlinear functions at meaningless points. The default value r=2.0 should not affect progress on well-behaved functions, but values such as r=0.1 ​ or ​ 0.01 may be helpful when rapidly varying functions are present. If a small value of r is selected, a ‘good’ starting point may be required. An important application is to the class of nonlinear least squares problems.
If r≤0, the default value is used.
Minor Feasibility Tolerance r Default =ε
Feasibility Tolerance r
This option attempts to ensure that all variables eventually satisfy their upper and lower bounds to within the tolerance r. Since this includes slack variables, general linear constraints should also be satisfied to within r. Note that feasibility with respect to nonlinear constraints is judged by the value of optional parameter Major Feasibility Tolerance and not by r.
If the bounds and linear constraints cannot be satisfied to within r, the problem is declared infeasible. Let Sinf be the corresponding sum of infeasibilities. If Sinf is quite small, it may be appropriate to raise r by a factor of 10 or 100. Otherwise, some error in the data should be suspected.
If Scale Option≥1, feasibility is defined in terms of the scaled problem (since it is more likely to be meaningful).
Nonlinear functions will only be evaluated at points that satisfy the bounds and linear constraints. If there are regions where a function is undefined, every effort should be made to eliminate these regions from the problem. For example, if f x 1,x 2=x 1+log x 2, it is essential to place lower bounds on both x 1 and x 2. If the value r=10-6 is used, the bounds x 1≥10-5 and x 2≥10-4 might be appropriate. (The log singularity is more serious; in general, you should attempt to keep x as far away from singularities as possible.)
In reality, r is used as a feasibility tolerance for satisfying the bounds on x and s in each QP subproblem. If the sum of infeasibilities cannot be reduced to zero, the QP subproblem is declared infeasible and the routine is then in elastic mode thereafter (with only the linearized nonlinear constraints defined to be elastic). (See also the description of Elastic Weight.)
If r≤ε, the default value is used.
Minor Iteration Limit i Default =500
The value of i specifies the maximum number of iterations allowed between successive linearizations of the nonlinear constraints. A value in the range 10≤i≤50 prevents excessive effort being expended on early major iterations, but allows later QP subproblems to be solved to completion. Note that an extra m minor iterations are allowed if the first QP subproblem to be solved starts with the all-slack basis B=I. (See the description of the optional parameter Crash Option.)
In general, it is unsafe to specify values as small as i=1​ or ​2 (because even when an optimal solution has been reached, a few minor iterations may be needed for the corresponding QP subproblem to be recognized as optimal).
If i≤0, the default value is used.
Minor Optimality Tolerance r Default =ε
This option is used to judge optimality for each QP subproblem. Let the QP reduced gradients be dj=gj-πT aj, where gj is the jth element of the QP gradient, aj is the associated column of the QP constraint matrix and π is the set of QP dual variables.
By construction, the reduced gradients for basic variables are always zero. The QP subproblem will be declared optimal if the reduced gradients for nonbasic variables at their upper or lower bounds satisfy
dj π≥-r  or  dj π≤r
respectively, and if djπ≤r for superbasic variables.
Note that π is a measure of the size of the dual variables. It is included to make the tests independent of a scale factor on the objective function. (The value of π actually used is defined in the description for optional parameter Major Optimality Tolerance.)
If the objective is scaled down to be very small, the optimality test reduces to comparing dj against r.
If r≤0, the default value is used.
Minor Print Level i Default =0
The value of i controls the amount of printout produced by the minor iterations of E04UGF/E04UGA (i.e., the iterations of the quadratic programming algorithm), as indicated below. A detailed description of the printed output is given in Section 9.2 (summary output at each minor iteration) and Section 13 (monitoring information at each minor iteration). (See also the description of the optional parameter Major Print Level.)
The following printout is sent to the current advisory message unit (as defined by X04ABF):
i | Output
≥0 | No output.
≥1 | One line of summary output (<80 characters; see Section 9.2) for each minor iteration.
The following printout is sent to the logical unit number by the optional parameter Monitoring File:
i | Output
≥0 | No output.
≥1 | One long line of output (<120 characters; see Section 13) for each minor iteration.
If Major Print Level≥5 and the unit number defined by the optional parameter Monitoring File is the same as that defined by X04ABF, then the summary output for each major iteration is suppressed.
Monitoring File i Default =-1
If i≥0 and Major Print Level≥5 or i≥0 and Minor Print Level≥1 then monitoring information is produced by E04UGF/E04UGA at every iteration is sent to a file with logical unit number i. If i<0 and/or Major Print Level<5 and Minor Print Level<1 then no monitoring information is produced.
Partial Price i Default =1​ or ​10
The default value of i is 1 if there are any nonlinear constraints and 10 otherwise.
This option is recommended for large problems that have significantly more variables than constraints (i.e., n≫m). It reduces the work required for each ‘pricing’ operation (i.e., when a nonbasic variable is selected to become superbasic). The possible choices for i are the following.
i | Meaning
≥1 | All columns of the constraint matrix A -I are searched.
≥2 | Both A and I are partitioned to give i roughly equal segments Aj,Ij, for j=1,2,…,p (modulo p). If the previous pricing search was successful on Aj,Ij, the next search begins on the segments A j+1,I j+1. If a reduced gradient is found that is larger than some dynamic tolerance, the variable with the largest such reduced gradient (of appropriate sign) is selected to enter the basis. If nothing is found, the search continues on the next segments A j+2,I j+2 and so on.
If i≤0, the default value is used.
Pivot Tolerance r Default =ε 0.67
If r>0, r is used during the solution of QP subproblems to prevent columns entering the basis if they would cause the basis to become almost singular.
When x changes to x+αp for some specified search direction p, a ‘ratio test’ is used to determine which element of x reaches an upper or lower bound first. The corresponding element of p is called the pivot element. Elements of p are ignored (and therefore cannot be pivot elements) if they are smaller than r.
It is common in practice for two (or more) variables to reach a bound at essentially the same time. In such cases, the Minor Feasibility Tolerance provides some freedom to maximize the pivot element and thereby improve numerical stability. Excessively small values of Minor Feasibility Tolerance should therefore not be specified. To a lesser extent, the Expand Frequency also provides some freedom to maximize the pivot element. Excessively large values of Expand Frequency should therefore not be specified.
If r≤0, the default value is used.
Scale Option i Default =1​ or ​2
The default value of i is 1 if there are any nonlinear constraints and 2 otherwise.
This option enables you to scale the variables and constraints using an iterative procedure due to Fourer (1982), which attempts to compute row scales ri and column scales cj such that the scaled matrix coefficients a-ij=a ij×cj/ri are as close as possible to unity. (The lower and upper bounds on the variables and slacks for the scaled problem are redefined as l-j=lj/cj and u-j=uj/cj respectively, where cj≡r j-n if j>n.) The possible choices for i are the following.
i | Meaning
0 | No scaling is performed. This is recommended if it is known that the elements of x and the constraint matrix A (along with its Jacobian) never become large (say, >1000).
1 | All linear constraints and variables are scaled. This may improve the overall efficiency of the routine on some problems.
2 | All constraints and variables are scaled. Also, an additional scaling is performed that takes into account columns of A -I that are fixed or have positive lower bounds or negative upper bounds.
If there are any nonlinear constraints present, the scale factors depend on the Jacobian at the first point that satisfies the linear constraints and the upper and lower bounds. The setting i=2 should therefore be used only if a ‘good’ starting point is available and the problem is not highly nonlinear.
If i<0 or i>2, the default value is used.
Scale Tolerance r Default =0.9
Note that this option does not apply when Scale Option=0.
The value r (0<r<1) is used to control the number of scaling passes to be made through the constraint matrix A. At least 3 (and at most 10) passes will be made. More precisely, let ap denote the largest column ratio (i.e., 'biggest'​ element 'smallest'​ element in some sense) after the pth scaling pass through A. The scaling procedure is terminated if ap≥a p-1×r for some p≥3. Thus, increasing the value of r from 0.9 to 0.99 (say) will probably increase the number of passes through A.
If r≤0 or r≥1, the default value is used.
Start Objective Check At Column i 1 Default =1
Stop Objective Check At Column i 2 Default =n 1′
Start Constraint Check At Column i 3 Default =1
Stop Constraint Check At Column i 4 Default =n 1′′
These keywords take effect only if Verify Level>0. They may be used to control the verification of gradient elements computed by OBJFUN and/or Jacobian elements computed by CONFUN. For example, if the first 30 elements of the objective gradient appeared to be correct in an earlier run, so that only element 31 remains questionable then it is reasonable to specify Start Objective Check At Column=31. Similarly for columns of the Jacobian. If the first 30 variables occur nonlinearly in the constraints but the remaining variables are nonlinear only in the objective, then OBJFUN must set the first 30 elements of the array OBJGRD to zero, but these hardly need to be verified. Again it is reasonable to specify Start Objective Check At Column=31.
If i 2≤0 or i 2>n 1′, the default value is used.
If i 1≤0 or i 1>min n 1′,i 2, the default value is used.
If i 4≤0 or i 4>n 1′′, the default value is used.
If i 3≤0 or i 3>min n 1′′,i 4, the default value is used.
Superbasics Limit i Default =min 500,n-+1
Note that this option does not apply to linear problems.
It places a limit on the storage allocated for superbasic variables. Ideally, the value of i should be set slightly larger than the ‘number of degrees of freedom’ expected at the solution.
For nonlinear problems, the number of degrees of freedom is often called the ‘number of independent variables’. Normally, the value of i need not be greater than n-+1, but for many problems it may be considerably smaller. (This will save storage if n- is very large.)
If i≤0, the default value is used.
Unbounded Objective r 1 Default =1015
Unbounded Step Size r 2 Default =max bigbnd,1020
These options are intended to detect unboundedness in nonlinear problems. During the linesearch, the objective function f is evaluated at points of the form x+αp, where x and p are fixed and α varies. If f exceeds r 1 or α exceeds r 2, the iterations are terminated and the routine returns with IFAIL=3.
If singularities are present, unboundedness in f x may manifest itself by a floating-point overflow during the evaluation of f x+αp, before the test against r 1 can be made.
Unboundedness in x is best avoided by placing finite upper and lower bounds on the variables.
If r 1≤0 or r 2≤0, the appropriate default value is used.
Verify Level i Default =0
This option refers to finite difference checks on the gradient elements computed by OBJFUN and CONFUN. Gradients are verified at the first point that satisfies the linear constraints and the upper and lower bounds. Unspecified gradient elements are not checked and hence they result in no overhead. The possible choices for i are the following.
i | Meaning
-1 | No checks are performed.
-0 | Only a ‘cheap’ test will be performed, requiring three calls to OBJFUN and two calls to CONFUN. Note that no checks are carried out if every column of the constraint gradients (Jacobian) contains a missing element.
-1 | Individual objective gradient elements will be checked using a reliable (but more expensive) test. If Major Print Level>0, a key of the form OK or BAD? indicates whether or not each element appears to be correct.
-2 | Individual columns of the constraint gradients (Jacobian) will be checked using a reliable (but more expensive) test. If Major Print Level>0, a key of the form OK or BAD? indicates whether or not each element appears to be correct.
-3 | Check both constraint and objective gradients (in that order) as described above for i=2 and i=1 respectively.
The value i=3 should be used whenever a new function routine is being developed. The Start Objective Check At Column and Stop Objective Check At Column keywords may be used to limit the number of nonlinear variables to be checked.
If i<-1 or i>3, the default value is used.
Violation Limit r Default =10.0
This option defines an absolute limit on the magnitude of the maximum constraint violation after the linesearch. Upon completion of the linesearch, the new iterate x k+1 satisfies the condition
vi x k+1≤r×max 1,vi x 0,
where x 0 is the point at which the nonlinear constraints are first evaluated and vi x is the ith nonlinear constraint violation vi x= max 0,li-Fi x,Fi x-ui.
The effect of the violation limit is to restrict the iterates to lie in an expanded feasible region whose size depends on the magnitude of r. This makes it possible to keep the iterates within a region where the objective function is expected to be well-defined and bounded below (or above in the case of maximization). If the objective function is bounded below (or above in the case of maximization) for all values of the variables, then r may be any large positive value.
If r≤0, the default value is used.

13 Description of Monitoring Information

This section describes the intermediate printout and final printout which constitutes the monitoring information produced by E04UGF/E04UGA. (See also the description of the optional parameters Monitoring File, Major Print Level and Minor Print Level.) You can control the level of printed output.
When Major Print Level≥20 and Monitoring File≥0, the following line of intermediate printout (<120 characters) is produced at every major iteration on the unit number specified by optional parameter Monitoring File. Unless stated otherwise, the values of the quantities printed are those in effect on completion of the given iteration.
Major | is the major iteration count.
Minor | is the number of minor iterations required by the feasibility and optimality phases of the QP subproblem. Generally, Minor will be 1 in the later iterations, since theoretical analysis predicts that the correct active set will be identified near the solution (see Section 11).
Step | is the step αk taken along the computed search direction. On reasonably well-behaved problems, the unit step (i.e., αk=1) will be taken as the solution is approached.
nObj | is the number of times OBJFUN has been called to evaluate the nonlinear part of the objective function. Evaluations needed for the estimation of the gradients by finite differences are not included. nObj is printed as a guide to the amount of work required for the linesearch.
nCon | is the number of times CONFUN has been called to evaluate the nonlinear constraint functions (not printed if NCNLN is zero).
Merit is the value of the augmented Lagrangian merit function (6) at the current iterate. This function will decrease at each iteration unless it was necessary to increase the penalty parameters (see Section 9.1). As the solution is approached, Merit will converge to the value of the objective function at the solution.
In elastic mode (see Section 11.2), the merit function is a composite function involving the constraint violations weighted by the value of the optional parameter Elastic Weight.
If there are no nonlinear constraints present, this entry contains Objective, the value of the objective function f x. In this case, f x will decrease monotonically to its optimal value.
Feasibl is the value of rowerr, the largest element of the scaled nonlinear constraint residual vector defined in the description of the optional parameter Major Feasibility Tolerance. The solution is regarded as ‘feasible’ if Feasibl is less than (or equal to) the optional parameter Major Feasibility Tolerance. Feasibl will be approximately zero in the neighbourhood of a solution.
If there are no nonlinear constraints present, all iterates are feasible and this entry is not printed.
Optimal | is the value of maxgap, the largest element of the maximum complementarity gap vector defined in the description of the optional parameter Major Optimality Tolerance. The Lagrange multipliers are regarded as ‘optimal’ if Optimal is less than (or equal to) the optional parameter Major Optimality Tolerance. Optimal will be approximately zero in the neighbourhood of a solution.
nS | is the current number of superbasic variables.
Penalty | is the Euclidean norm of the vector of penalty parameters used in the augmented Lagrangian merit function (not printed if NCNLN is zero).
LU is the number of nonzeros representing the basis factors L and U on completion of the QP subproblem.
If there are nonlinear constraints present, the basis factorization B=LU is computed at the start of the first minor iteration. At this stage, LU=lenL+lenU, where lenL is the number of subdiagonal elements in the columns of a lower triangular matrix and lenU is the number of diagonal and superdiagonal elements in the rows of an upper triangular matrix. As columns of B are replaced during the minor iterations, the value of LU may fluctuate up or down (but in general will tend to increase). As the solution is approached and the number of minor iterations required to solve each QP subproblem decreases towards zero, LU will reflect the number of nonzeros in the LU factors at the start of each QP subproblem.
If there are no nonlinear constraints present, refactorization is subject only to the value of the optional parameter Factorization Frequency and hence LU will tend to increase between factorizations.
Swp | is the number of columns of the basis matrix B that were swapped with columns of S in order to improve the condition number of B (not printed if NCNLN is zero). The swaps are determined by an LU factorization of the rectangular matrix BS = B S T , with stability being favoured more than sparsity.
Cond Hz | is an estimate of the condition number of the reduced Hessian of the Lagrangian (not printed if NCNLN and NONLN are both zero). It is the square of the ratio between the largest and smallest diagonal elements of the upper triangular matrix R. This constitutes a lower bound on the condition number of the matrix RT R that approximates the reduced Hessian. The larger this number, the more difficult the problem.
PD | is a two-letter indication of the status of the convergence tests involving the feasibility and optimality of the iterates defined in the descriptions of the optional parameters Major Feasibility Tolerance and Major Optimality Tolerance. Each letter is T if the test is satisfied and F otherwise. The tests indicate whether the values of Feasibl and Optimal are sufficiently small. For example, TF or TT is printed if there are no nonlinear constraints present (since all iterates are feasible). If either indicator is F when E04UGF/E04UGA terminates with IFAIL=0, you should check the solution carefully.
M | is printed if an extra evaluation of user-supplied subroutines OBJFUN and CONFUN was needed in order to define an acceptable positive definite quasi-Newton update to the Hessian of the Lagrangian. This modification is only performed when there are nonlinear constraints present.
m | is printed if, in addition, it was also necessary to modify the update to include an augmented Lagrangian term.
s | is printed if a self-scaled BFGS (Broyden–Fletcher–Goldfarb–Shanno) update was performed. This update is always used when the Hessian approximation is diagonal and hence always follows a Hessian reset.
S | is printed if, in addition, it was also necessary to modify the self-scaled update in order to maintain positive-definiteness.
n | is printed if no positive definite BFGS update could be found, in which case the approximate Hessian is unchanged from the previous iteration.
r | is printed if the approximate Hessian was reset after 10 consecutive major iterations in which no BFGS update could be made. The diagonal elements of the approximate Hessian are retained if at least one update has been performed since the last reset. Otherwise, the approximate Hessian is reset to the identity matrix.
R | is printed if the approximate Hessian has been reset by discarding all but its diagonal elements. This reset will be forced periodically by the values of the optional parameters Hessian Frequency and Hessian Updates. However, it may also be necessary to reset an ill-conditioned Hessian from time to time.
l | is printed if the change in the norm of the variables was greater than the value defined by the optional parameter Major Step Limit. If this output occurs frequently during later iterations, it may be worthwhile increasing the value of Major Step Limit.
c | is printed if central differences have been used to compute the unknown elements of the objective and constraint gradients. A switch to central differences is made if either the linesearch gives a small step, or x is close to being optimal. In some cases, it may be necessary to re-solve the QP subproblem with the central difference gradient and Jacobian.
u | is printed if the QP subproblem was unbounded.
t | is printed if the minor iterations were terminated after the number of iterations specified by the value of the optional parameter Minor Iteration Limit was reached.
i | is printed if the QP subproblem was infeasible when the routine was not in elastic mode. This event triggers the start of nonlinear elastic mode, which remains in effect for all subsequent iterations. Once in elastic mode, the QP subproblems are associated with the elastic problem (8) (see Section 11.2). It is also printed if the minimizer of the elastic subproblem does not satisfy the linearized constraints when the routine is already in elastic mode. (In this case, a feasible point for the usual QP subproblem may or may not exist.)
w | is printed if a weak solution of the QP subproblem was found.
When Minor Print Level≥1 and Monitoring File≥0, the following line of intermediate printout (<120 characters) is produced at every minor iteration on the unit number specified by optional parameter Monitoring File. Unless stated otherwise, the values of the quantities printed are those in effect on completion of the given iteration.
In the description below, a ‘pricing’ operation is defined to be the process by which a nonbasic variable is selected to become superbasic (in addition to those already in the superbasic set). If the problem is purely linear, the variable selected will usually become basic immediately (unless it happens to reach its opposite bound and return to the nonbasic set).
Itn | is the iteration count.
pp | is the partial price indicator. The variable selected by the last pricing operation came from the ppth partition of A and -I. Note that pp is reset to zero whenever the basis is refactorized.
dj | is the value of the reduced gradient (or reduced cost) for the variable selected by the pricing operation at the start of the current iteration.
+SBS | is the variable selected by the pricing operation to be added to the superbasic set.
-SBS | is the variable chosen to leave the superbasic set. It has become basic if the entry under -B is nonzero; otherwise it has become nonbasic.
-BS | is the variable removed from the basis (if any) to become nonbasic.
-B | is the variable removed from the basis (if any) to swap with a slack variable made superbasic by the latest pricing operation. The swap is done to ensure that there are no superbasic slacks.
Step | is the value of the step length α taken along the current search direction p. The variables x have just been changed to x+αp. If a variable is made superbasic during the current iteration (i.e., +SBS is positive), Step will be the step to the nearest bound. During the optimality phase, the step can be greater than unity only if the reduced Hessian is not positive definite.
Pivot | is the rth element of a vector y satisfying By=aq whenever aq (the qth column of the constraint matrix A-I ) replaces the rth column of the basis matrix B. Wherever possible, Step is chosen so as to avoid extremely small values of Pivot (since they may cause the basis to be nearly singular). In extreme cases, it may be necessary to increase the value of the optional parameter Pivot Tolerance to exclude very small elements of y from consideration during the computation of Step.
Ninf | is the number of infeasibilities. This will not increase unless the iterations are in elastic mode. Ninf will be zero during the optimality phase.
Sinf/Objective | is the value of the current objective function. If x is infeasible, Sinf gives the value of the sum of infeasibilities at the start of the current iteration. It will usually decrease at each nonzero value of Step, but may occasionally increase if the value of Ninf decreases by a factor of 2 or more. However, in elastic mode this entry gives the value of the composite objective function (9), which will decrease monotonically at each iteration. If x is feasible, Objective is the value of the current QP objective function.
L | is the number of nonzeros in the basis factor L. Immediately after a basis factorization B=LU, this entry contains lenL. Further nonzeros are added to L when various columns of B are later replaced. (Thus, L increases monotonically.)
U | is the number of nonzeros in the basis factor U. Immediately after a basis factorization B=LU, this entry contains lenU. As columns of B are replaced, the matrix U is maintained explicitly (in sparse form). The value of U may fluctuate up or down; in general, it will tend to increase.
Ncp | is the number of compressions required to recover workspace in the data structure for U. This includes the number of compressions needed during the previous basis factorization. Normally, Ncp should increase very slowly. If it does not, increase LENIZ and LENZ by at least L+U and rerun E04UGF/E04UGA (possibly using START='W'; see Section 5).
The following items are printed only if the problem is nonlinear or the superbasic set is non-empty (i.e., if the current solution is nonbasic).
Norm rg | is the Euclidean norm of the reduced gradient of the QP objective function. During the optimality phase, this norm will be approximately zero after a unit step.
nS | is the current number of superbasic variables.
Cond Hz | is an estimate of the condition number of the reduced Hessian of the Lagrangian (not printed if NCNLN and NONLN are both zero). It is the square of the ratio between the largest and smallest diagonal elements of the upper triangular matrix R. This constitutes a lower bound on the condition number of the matrix RT R that approximates the reduced Hessian. The larger this number, the more difficult the problem.
When Major Print Level≥20 and Monitoring File≥0, the following lines of intermediate printout (<120 characters) are produced on the unit number specified by optional parameter Monitoring File whenever the matrix B or BS=B S T is factorized before solving the next QP subproblem. Gaussian elimination is used to compute a sparse LU factorization of B or BS, where PL PT is a lower triangular matrix and PUQ is an upper triangular matrix for some permutation matrices P and Q. The factorization is stabilized in the manner described under the optional parameter LU Factor Tolerance (default value=5.0 or 100.0).
Note that BS may be factorized at the beginning of just some of the major iterations. It is immediately followed by a factorization of B itself.
Factorize | is the factorization count.
Iteration | is the iteration count.
Nonlinear | is the number of nonlinear variables in the current basis B (not printed if BS is factorized).
Linear | is the number of linear variables in B (not printed if BS is factorized).
Slacks | is the number of slack variables in B (not printed if BS is factorized).
Elems | is the number of nonzeros in B (not printed if BS is factorized).
Density | is the percentage nonzero density of B (not printed if BS is factorized). More precisely, Density=100×Elems/Nonlinear+Linear+Slacks 2.
Compressns | is the number of times the data structure holding the partially factorized matrix needed to be compressed, in order to recover unused workspace. Ideally, it should be zero. If it is more than 3 or 4, increase LENIZ and LENZ and rerun E04UGF/E04UGA (possibly using START='W'; see Section 5).
Merit | is the average Markowitz merit count for the elements chosen to be the diagonals of PUQ. Each merit count is defined to be c-1r-1, where c and r are the number of nonzeros in the column and row containing the element at the time it is selected to be the next diagonal. Merit is the average of m such quantities. It gives an indication of how much work was required to preserve sparsity during the factorization.
lenL | is the number of nonzeros in L.
lenU | is the number of nonzeros in U.
Increase | is the percentage increase in the number of nonzeros in L and U relative to the number of nonzeros in B. More precisely, Increase=100×lenL+lenU-Elems/Elems.
m | is the number of rows in the problem. Note that m=Ut+Lt+bp.
Ut | is the number of triangular rows of B at the top of U.
d1 | is the number of columns remaining when the density of the basis matrix being factorized reached 0.3.
Lmax | is the maximum subdiagonal element in the columns of L. This will not exceed the value of the optional parameter LU Factor Tolerance.
Bmax | is the maximum nonzero element in B (not printed if BS is factorized).
BSmax | is the maximum nonzero element in BS (not printed if B is factorized).
Umax | is the maximum nonzero element in U, excluding elements of B that remain in U unchanged. (For example, if a slack variable is in the basis, the corresponding row of B will become a row of U without modification. Elements in such rows will not contribute to Umax. If the basis is strictly triangular then none of the elements of B will contribute and Umax will be zero.) Ideally, Umax should not be significantly larger than Bmax. If it is several orders of magnitude larger, it may be advisable to reset the optional parameter LU Factor Tolerance to some value nearer unity. Umax is not printed if BS is factorized.
Umin | is the magnitude of the smallest diagonal element of PUQ.
Growth | is the value of the ratio Umax/Bmax, which should not be too large. Providing Lmax is not large (say, <10.0), the ratio max Bmax,Umax/Umin is an estimate of the condition number of B. If this number is extremely large, the basis is nearly singular and some numerical difficulties might occur. (However, an effort is made to avoid near-singularity by using slacks to replace columns of B that would have made Umin extremely small and the modified basis is refactorized.)
Lt | is the number of triangular columns of B at the left of L.
bp | is the size of the ‘bump’ or block to be factorized nontrivially after the triangular rows and columns of B have been removed.
d2 | is the number of columns remaining when the density of the basis matrix being factorized has reached 0.6.
When Major Print Level≥20, Monitoring File≥0 and Crash Option>0 (default value=0​ or ​3), the following lines of intermediate printout (<80 characters) are produced on the unit number specified by optional parameter Monitoring File whenever START='C' (see Section 5). They refer to the number of columns selected by the Crash procedure during each of several passes through A while searching for a triangular basis matrix.
Slacks | is the number of slacks selected initially.
Free cols | is the number of free columns in the basis, including those whose bounds are rather far apart.
Preferred | is the number of ‘preferred’ columns in the basis (i.e., ISTATE j=3 for some j≤n). It will be a subset of the columns for which ISTATE j=3 was specified.
Unit | is the number of unit columns in the basis.
Double | is the number of columns in the basis containing two nonzeros.
Triangle | is the number of triangular columns in the basis with three (or more) nonzeros.
Pad | is the number of slacks used to pad the basis (to make it a nonsingular triangle).
When Major Print Level=1 or ≥10 and Monitoring File≥0, the following lines of final printout (<120 characters) are produced on the unit number specified by optional parameter Monitoring File.
Let xj denote the jth ‘column variable’, for j=1,2,…,n. We assume that a typical variable xj has bounds α≤xj≤β.
The following describes the printout for each column (or variable). A full stop (.) is printed for any numerical value that is zero.
Number | is the column number j. (This is used internally to refer to xj in the intermediate output.)
Column | gives the name of xj.
State gives the state of xj relative to the bounds α and β.
The various possible states are as follows:
LL | xj is nonbasic at its lower limit, α.
UL | xj is nonbasic at its upper limit, β.
EQ | xj is nonbasic and fixed at the value α=β.
FR | xj is nonbasic at some value strictly between its bounds: α<xj<β.
BS | xj is basic. Usually α<xj<β.
A key is sometimes printed before State. Note that unless the optional parameter Scale Option=0 is specified, the tests for assigning a key are applied to the variables of the scaled problem.
A | Alternative optimum possible. The variable is nonbasic, but its reduced gradient is essentially zero. This means that if the variable were allowed to start moving away from its current value, there would be no change in the value of the objective function. The values of the basic and superbasic variables might change, giving a genuine alternative solution. The values of the Lagrange multipliers might also change.
D | Degenerate. The variable is basic, but it is equal to (or very close to) one of its bounds.
I | Infeasible. The variable is basic and is currently violating one of its bounds by more than the value of the optional parameter Minor Feasibility Tolerance.
N | Not precisely optimal. The variable is nonbasic. Its reduced gradient is larger than the value of the optional parameter Major Feasibility Tolerance.
Activity | is the value of xj at the final iterate.
Obj Gradient | is the value of gj at the final iterate. (If any xj is infeasible, gj is the gradient of the sum of infeasibilities.)
Lower Bound | is the lower bound specified for the variable. None indicates that BL j≤-bigbnd.
Upper Bound | is the upper bound specified for the variable. None indicates that BU j≥bigbnd.
Reduced Gradnt | is the value of dj at the final iterate.
m + j | is the value of m+j.
General linear constraints take the form l≤Ax≤u. The ith constraint is therefore of the form α≤aiT x≤β and the value of aiT x is called the row activity. Internally, the linear constraints take the form Ax-s=0, where the slack variables s should satisfy the bounds l≤s≤u. For the ith ‘row’, it is the slack variable si that is directly available and it is sometimes convenient to refer to its state. Slacks may be basic or nonbasic (but not superbasic).
Nonlinear constraints α≤Fi x+aiT x≤β are treated similarly, except that the row activity and degree of infeasibility are computed directly from Fi x+aiT x rather than from si.
The following describes the printout for each row (or constraint). A full stop (.) is printed for any numerical value that is zero.
Number | is the value of n+i. (This is used internally to refer to si in the intermediate output.)
Row | gives the name of the ith row.
State gives the state of the ith row relative to the bounds α and β.
The various possible states are as follows:
LL | The row is at its lower limit, α.
UL | The row is at its upper limit, β.
EQ | The limits are the same α=β.
BS | The constraint is not binding. si is basic.
A key is sometimes printed before State. Note that unless the optional parameter Scale Option=0 is specified, the tests for assigning a key are applied to the variables of the scaled problem.
A | Alternative optimum possible. The variable is nonbasic, but its reduced gradient is essentially zero. This means that if the variable were allowed to start moving away from its current value, there would be no change in the value of the objective function. The values of the basic and superbasic variables might change, giving a genuine alternative solution. The values of the Lagrange multipliers might also change.
D | Degenerate. The variable is basic, but it is equal to (or very close to) one of its bounds.
I | Infeasible. The variable is basic and is currently violating one of its bounds by more than the value of the optional parameter Minor Feasibility Tolerance.
N | Not precisely optimal. The variable is nonbasic. Its reduced gradient is larger than the value of the optional parameter Major Feasibility Tolerance.
Activity | is the value of aiT x (or Fi x+aiT x for nonlinear rows) at the final iterate.
Slack Activity | is the value by which the row differs from its nearest bound. (For the free row (if any), it is set to Activity.)
Lower Bound | is α, the lower bound specified for the ith row. None indicates that BL n+i≤-bigbnd.
Upper Bound | is β, the upper bound specified for the ith row. None indicates that BU n+i≥bigbnd.
Dual Activity | is the value of the dual variable πi.
i | gives the index i of the ith row.
Numerical values are output with a fixed number of digits; they are not guaranteed to be accurate to this precision.
E04 Chapter Contents
E04 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


E04UHF/E04UHA : NAG Library, Mark 26

E04 Chapter Contents
E04 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

E04UHF/E04UHA

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
▸▿ 2 Specification
2.1 Specification for E04UHF
2.2 Specification for E04UHA
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

To supply optional parameters to E04UGF/E04UGA from an external file. More precisely, E04UHF must be used to supply optional parameters to E04UGF and E04UHA must be used to supply optional parameters to E04UGA.
E04UHA is a version of E04UHF that has additional arguments in order to make it safe for use in multithreaded applications (see Section 5). The initialization routine E04WBF must have been called before calling E04UHA.

2 Specification

2.1 Specification for E04UHF

SUBROUTINE E04UHF ( IOPTNS, INFORM)
INTEGER IOPTNS, INFORM

2.2 Specification for E04UHA

SUBROUTINE E04UHA ( IOPTNS, LWSAV, IWSAV, RWSAV, INFORM)
INTEGER | IOPTNS, IWSAV(550), INFORM
REAL (KIND=nag_wp) | RWSAV(550)
LOGICAL | LWSAV(20)

3 Description

E04UHF/E04UHA may be used to supply values for optional parameters to E04UGF/E04UGA. E04UHF/E04UHA reads an external file and each line of the file defines a single optional parameter. It is only necessary to supply values for those arguments whose values are to be different from their default values.
Each optional parameter is defined by a single character string, of up to 72 characters, consisting of one or more items. The items associated with a given option must be separated by spaces, or equals signs =. Alphabetic characters may be upper or lower case. The string
Print Level = 1
is an example of a string used to set an optional parameter. For each option the string contains one or more of the following items:
– | a mandatory keyword;
– | a phrase that qualifies the keyword;
– | a number that specifies an integer or real value. Such numbers may be up to 40 contiguous characters in Fortran's I, F, E or D formats, terminated by a space if this is not the last item on the line.
Blank strings and comments are ignored. A comment begins with an asterisk (*) and all subsequent characters in the string are regarded as part of the comment.
The file containing the options must start with Begin and must finish with End. An example of a valid options file is:
Begin * Example options file
   Print level = 5
End
For E04UHF each line of the file is normally printed as it is read, on the current advisory message unit (see X04ABF), but printing may be suppressed using the keyword Nolist. To suppress printing of Begin, Nolist must be the first option supplied as in the file:
Begin
   Nolist
   Print level = 5
End
Printing will automatically be turned on again after a call to E04UGF or E04UHF and may be turned on again at any time using the keyword List.
For E04UHA printing is turned off by default, but may be turned on at any time using the keyword List.
Optional parameter settings are preserved following a call to E04UGF/E04UGA and so the keyword Defaults is provided to allow you to reset all the optional parameters to their default values before a subsequent call to E04UGF/E04UGA.
A complete list of optional parameters, their abbreviations, synonyms and default values is given in Section 12 in E04UGF/E04UGA.

4 References

Hock W and Schittkowski K (1981) Test Examples for Nonlinear Programming Codes. Lecture Notes in Economics and Mathematical Systems 187 Springer–Verlag

5 Arguments

1:   IOPTNS – INTEGERInput
On entry: the unit number of the options file to be read.
Constraint: 0≤IOPTNS≤99.
2:   INFORM – INTEGEROutput
Note: for E04UHA, INFORM does not occur in this position in the argument list. See the additional arguments described below.
On exit: contains zero if the options file has been successfully read and a value>0 otherwise (see Section 6).
Note: the following are additional arguments for specific use with E04UHA. Users of E04UHF therefore need not read the remainder of this description.
2:   LWSAV 20 – LOGICAL arrayCommunication Array
3:   IWSAV 550 – INTEGER arrayCommunication Array
4:   RWSAV 550 – REAL (KIND=nag_wp) arrayCommunication Array
The arrays LWSAV, IWSAV and RWSAV must not be altered between calls to any of the routines E04UHA, E04UGA, E04UJA or E04WBF.
5:   INFORM – INTEGEROutput
Note: see the argument description for INFORM above.

6 Error Indicators and Warnings

INFORM=1
IOPTNS is not in the range 0,99.
INFORM=2
Begin was found, but end-of-file was found before End was found.
INFORM=3
end-of-file was found before Begin was found.
INFORM=4
Not used.
INFORM=5
One or more lines of the options file is invalid. Check that all keywords are neither ambiguous nor misspelt.

7 Accuracy

Not applicable.

8 Parallelism and Performance

E04UHF/E04UHA is not threaded in any implementation.

9 Further Comments

E04UJF/E04UJA may also be used to supply optional parameters to E04UGF/E04UGA.

10 Example

This is Problem 45 from Hock and Schittkowski (1981) and involves the minimization of the nonlinear function
f x=2-1120×x 1x 2x 3x 4x 5
subject to the bounds
0≤x 1≤ 1, 0≤x 2≤ 2, 0≤x 3≤ 3, 0≤x 4≤ 4, 0≤x 5≤ 5.
The initial point, which is infeasible, is
x 0=2,2,2,2,2 T,
and f x 0=1.7333 (to five figures).
The optimal solution is
x*=1,2,3,4,5 T,
and f x*=1. All the bounds are active at the solution.
In this example the options file read by E04UHF/E04UHA is appended to the data file for the program (see Section 10.2). It would usually be more convenient in practice to keep the data file and the options file separate.

10.1 Program Text

Note: the following programs illustrate the use of E04UHF and E04UHA.

Program Text (e04uhfe.f90)

Program Text (e04uhae.f90)

10.2 Program Data

Program Options (e04uhfe.opt)

Program Options (e04uhae.opt)

Program Data (e04uhfe.d)

Program Data (e04uhae.d)

10.3 Program Results

Program Results (e04uhfe.r)

Program Results (e04uhae.r)

E04 Chapter Contents
E04 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


E04UJF/E04UJA : NAG Library, Mark 26

E04 Chapter Contents
E04 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

E04UJF/E04UJA

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
▸▿ 2 Specification
2.1 Specification for E04UJF
2.2 Specification for E04UJA
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
10 Example

1 Purpose

To supply individual optional parameters to E04UGF/E04UGA. More precisely, E04UJF must be used to supply optional parameters to E04UGF and E04UJA must be used to supply optional parameters to E04UGA.
E04UJA is a version of E04UJF that has additional arguments in order to make it safe for use in multithreaded applications (see Section 5). The initialization routine E04WBF must have been called before calling E04UJA.

2 Specification

2.1 Specification for E04UJF

SUBROUTINE E04UJF ( STR)
CHARACTER(*) STR

2.2 Specification for E04UJA

SUBROUTINE E04UJA ( STR, LWSAV, IWSAV, RWSAV, INFORM)
INTEGER | IWSAV(550), INFORM
REAL (KIND=nag_wp) | RWSAV(550)
LOGICAL | LWSAV(20)
CHARACTER(*) | STR

3 Description

E04UJF/E04UJA may be used to supply values for optional parameters to E04UGF/E04UGA. It is only necessary to call E04UJF/E04UJA for those arguments whose values are to be different from their default values. One call to E04UJF/E04UJA sets one argument value.
Each optional parameter is defined by a single character string, of up to 72 characters, consisting of one or more items. The items associated with a given option must be separated by spaces, or equals signs =. Alphabetic characters may be upper or lower case. The string
Print Level = 1
is an example of a string used to set an optional parameter. For each option the string contains one or more of the following items:
– | a mandatory keyword;
– | a phrase that qualifies the keyword;
– | a number that specifies an integer or real value. Such numbers may be up to 40 contiguous characters in Fortran's I, F, E or D formats, terminated by a space if this is not the last item on the line.
Blank strings and comments are ignored. A comment begins with an asterisk (*) and all subsequent characters in the string are regarded as part of the comment.
For E04UJF, each user-specified option is normally printed as it is defined, on the current advisory message unit (see X04ABF), but this printing may be suppressed using the keyword Nolist. Thus the statement

 CALL E04UJF ('Nolist')
suppresses printing of this and subsequent options. Printing will automatically be turned on again after a call to E04UGF and may be turned on again at any time using the keyword List.
For E04UJA printing is turned off by default, but may be turned on at any time using the keyword List.
Optional parameter settings are preserved following a call to E04UGF/E04UGA and so the keyword Defaults is provided to allow you to reset all the optional parameters to their default values before a subsequent call to E04UGF/E04UGA.
A complete list of optional parameters, their abbreviations, synonyms and default values is given in Section 12 in E04UGF/E04UGA.

4 References

None.

5 Arguments

1:   STR – CHARACTER(*)Input
On entry: a single valid option string (as described in Section 3 and in Section 12 in E04UGF/E04UGA).
Note: the following are additional arguments for specific use with E04UJA. Users of E04UJF therefore need not read the remainder of this description.
2:   LWSAV 20 – LOGICAL arrayCommunication Array
3:   IWSAV 550 – INTEGER arrayCommunication Array
4:   RWSAV 550 – REAL (KIND=nag_wp) arrayCommunication Array
The arrays LWSAV, IWSAV and RWSAV must not be altered between calls to any of the routines E04UJA, E04UGA, E04UHA or E04WBF.
5:   INFORM – INTEGEROutput
On exit: contains zero if a valid option string has been supplied and a value>0 otherwise (see Section 6).

6 Error Indicators and Warnings

INFORM=5
The supplied option is invalid. Check that the keywords are neither ambiguous nor misspelt.

7 Accuracy

Not applicable.

8 Parallelism and Performance

E04UJF/E04UJA is not threaded in any implementation.

9 Further Comments

E04UHF/E04UHA may also be used to supply optional parameters to E04UGF/E04UGA.

10 Example

See Section 10 in E04UHF/E04UHA.
E04 Chapter Contents
E04 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


E04UQF/E04UQA : NAG Library, Mark 26

E04 Chapter Contents
E04 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

E04UQF/E04UQA

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
▸▿ 2 Specification
2.1 Specification for E04UQF
2.2 Specification for E04UQA
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

To supply optional parameters to E04USF/E04USA from an external file. More precisely, E04UQF must be used to supply optional parameters to E04USF and E04UQA must be used to supply optional parameters to E04USA.
E04UQA is a version of E04UQF that has additional arguments in order to make it safe for use in multithreaded applications (see Section 5). The initialization routine E04WBF must have been called before calling E04UQA.

2 Specification

2.1 Specification for E04UQF

SUBROUTINE E04UQF ( IOPTNS, INFORM)
INTEGER IOPTNS, INFORM

2.2 Specification for E04UQA

SUBROUTINE E04UQA ( IOPTNS, LWSAV, IWSAV, RWSAV, INFORM)
INTEGER | IOPTNS, IWSAV(610), INFORM
REAL (KIND=nag_wp) | RWSAV(475)
LOGICAL | LWSAV(120)

3 Description

E04UQF/E04UQA may be used to supply values for optional parameters to the corresponding routines E04USF/E04USA. E04UQF/E04UQA reads an external file and each line of the file defines a single optional parameter. It is only necessary to supply values for those arguments whose values are to be different from their default values.
Each optional parameter is defined by a single character string, of up to 72 characters, consisting of one or more items. The items associated with a given option must be separated by spaces, or equals signs =. Alphabetic characters may be upper or lower case. The string
Print Level = 1
is an example of a string used to set an optional parameter. For each option the string contains one or more of the following items:
– | a mandatory keyword;
– | a phrase that qualifies the keyword;
– | a number that specifies an integer or real value. Such numbers may be up to 40 contiguous characters in Fortran's I, F, E or D formats, terminated by a space if this is not the last item on the line.
Blank strings and comments are ignored. A comment begins with an asterisk (*) and all subsequent characters in the string are regarded as part of the comment.
The file containing the options must start with Begin and must finish with End. An example of a valid options file is:
Begin * Example options file
   Print level = 5
End
For E04UQF each line of the file is normally printed as it is read, on the current advisory message unit (see X04ABF), but printing may be suppressed using the keyword Nolist. To suppress printing of Begin, Nolist must be the first option supplied as in the file:
Begin
   Nolist
   Print level = 5
End
Printing will automatically be turned on again after a call to E04USF/E04USA or E04UQF and may be turned on again at any time using the keyword List.
For E04UQA printing is turned off by default, but may be turned on at any time using the keyword List.
Optional parameter settings are preserved following a call to E04USF/E04USA and so the keyword Defaults is provided to allow you to reset all the optional parameters to their default values before a subsequent call to E04USF/E04USA.
A complete list of optional parameters, their abbreviations, synonyms and default values is given in Section 12 in E04USF/E04USA.

4 References

None.

5 Arguments

1:   IOPTNS – INTEGERInput
On entry: the unit number of the options file to be read.
Constraint: 0≤IOPTNS≤99.
2:   INFORM – INTEGEROutput
Note: for E04UQA, INFORM does not occur in this position in the argument list. See the additional arguments described below.
On exit: contains zero if the options file has been successfully read and a value>0 otherwise (see Section 6).
Note: the following are additional arguments for specific use with E04UQA. Users of E04UQF therefore need not read the remainder of this description.
2:   LWSAV 120 – LOGICAL arrayCommunication Array
3:   IWSAV 610 – INTEGER arrayCommunication Array
4:   RWSAV 475 – REAL (KIND=nag_wp) arrayCommunication Array
The arrays LWSAV, IWSAV and RWSAV must not be altered between calls to any of the routines E04UQA, E04URA, E04USA or E04WBF.
5:   INFORM – INTEGEROutput
Note: see the argument description for INFORM above.

6 Error Indicators and Warnings

INFORM=1
IOPTNS is not in the range 0,99.
INFORM=2
Begin was found, but end-of-file was found before End was found.
INFORM=3
end-of-file was found before Begin was found.
INFORM=4
Not used.
INFORM=5
One or more lines of the options file is invalid. Check that all keywords are neither ambiguous nor misspelt.

7 Accuracy

Not applicable.

8 Parallelism and Performance

E04UQF/E04UQA is not threaded in any implementation.

9 Further Comments

E04URF/E04URA may also be used to supply optional parameters to E04USF/E04USA.

10 Example

This example solves the same problem as the example for E04USF/E04USA, but in addition illustrates the use of E04UQF/E04UQA and E04URF/E04URA to set optional parameters for E04USF/E04USA.
In this example the options file read by E04UQF/E04UQA is appended to the data file for the program (see Section 10.2). It would usually be more convenient in practice to keep the data file and the options file separate.

10.1 Program Text

Note: the following programs illustrate the use of E04UQF and E04UQA.

Program Text (e04uqfe.f90)

Program Text (e04uqae.f90)

10.2 Program Data

Program Options (e04uqfe.opt)

Program Options (e04uqae.opt)

Program Data (e04uqfe.d)

Program Data (e04uqae.d)

10.3 Program Results

Program Results (e04uqfe.r)

Program Results (e04uqae.r)

E04 Chapter Contents
E04 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


E04URF/E04URA : NAG Library, Mark 26

E04 Chapter Contents
E04 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

E04URF/E04URA

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
▸▿ 2 Specification
2.1 Specification for E04URF
2.2 Specification for E04URA
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
10 Example

1 Purpose

To supply individual optional parameters to E04USF/E04USA. More precisely, E04URF must be used to supply optional parameters to E04USF and E04URA must be used to supply optional parameters to E04USA.
E04URA is a version of E04URF that has additional arguments in order to make it safe for use in multithreaded applications (see Section 5). The initialization routine E04WBF must have been called before calling E04URA.

2 Specification

2.1 Specification for E04URF

SUBROUTINE E04URF ( STR)
CHARACTER(*) STR

2.2 Specification for E04URA

SUBROUTINE E04URA ( STR, LWSAV, IWSAV, RWSAV, INFORM)
INTEGER | IWSAV(610), INFORM
REAL (KIND=nag_wp) | RWSAV(475)
LOGICAL | LWSAV(120)
CHARACTER(*) | STR

3 Description

E04URF/E04URA may be used to supply values for optional parameters to E04USF/E04USA. It is only necessary to call E04URF/E04URA for those arguments whose values are to be different from their default values. One call to E04URF/E04URA sets one argument value.
Each optional parameter is defined by a single character string, of up to 72 characters, consisting of one or more items. The items associated with a given option must be separated by spaces, or equals signs =. Alphabetic characters may be upper or lower case. The string
Print Level = 1
is an example of a string used to set an optional parameter. For each option the string contains one or more of the following items:
– | a mandatory keyword;
– | a phrase that qualifies the keyword;
– | a number that specifies an integer or real value. Such numbers may be up to 40 contiguous characters in Fortran's I, F, E or D formats, terminated by a space if this is not the last item on the line.
Blank strings and comments are ignored. A comment begins with an asterisk (*) and all subsequent characters in the string are regarded as part of the comment.
For E04URF, each user-specified option is normally printed as it is defined, on the current advisory message unit (see X04ABF), but this printing may be suppressed using the keyword Nolist. Thus the statement
 CALL E04URF ('Nolist')
suppresses printing of this and subsequent options. Printing will automatically be turned on again after a call to E04USF and may be turned on again at any time using the keyword List.
For E04URA printing is turned off by default, but may be turned on at any time using the keyword List.
Optional parameter settings are preserved following a call to E04USF/E04USA and so the keyword Defaults is provided to allow you to reset all the optional parameters to their default values before a subsequent call to E04USF/E04USA.
A complete list of optional parameters, their abbreviations, synonyms and default values is given in Section 12 in E04USF/E04USA.

4 References

None.

5 Arguments

1:   STR – CHARACTER(*)Input
On entry: a single valid option string (as described in Section 3 and in Section 12 in E04USF/E04USA.
Note: the following are additional arguments for specific use with E04URA. Users of E04URF therefore need not read the remainder of this description.
2:   LWSAV 120 – LOGICAL arrayCommunication Array
3:   IWSAV 610 – INTEGER arrayCommunication Array
4:   RWSAV 475 – REAL (KIND=nag_wp) arrayCommunication Array
The arrays LWSAV, IWSAV and RWSAV must not be altered between calls to any of the routines E04URA, E04UQA or E04URA.
5:   INFORM – INTEGEROutput
On exit: contains zero if a valid option string has been supplied and a value>0 otherwise (see Section 6).

6 Error Indicators and Warnings

INFORM=5
The supplied option is invalid. Check that the keywords are neither ambiguous nor misspelt.

7 Accuracy

Not applicable.

8 Parallelism and Performance

E04URF/E04URA is not threaded in any implementation.

9 Further Comments

E04UQF/E04UQA may also be used to supply optional parameters to E04USF/E04USA.

10 Example

See Section 10 in E04UQF/E04UQA.
E04 Chapter Contents
E04 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


E04USF/E04USA : NAG Library, Mark 26

E04 Chapter Contents
E04 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

E04USF/E04USA

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.
Note: this routine uses optional parameters to define choices in the problem specification and in the details of the algorithm. If you wish to use default settings for all of the optional parameters, you need only read Sections 1 to 10 of this document. If, however, you wish to reset some or all of the settings please refer to Section 11 for a detailed description of the algorithm, to Section 12 for a detailed description of the specification of the optional parameters and to Section 13 for a detailed description of the monitoring information produced by the routine.

▸▿ Contents

1 Purpose
▸▿ 2 Specification
2.1 Specification for E04USF
2.2 Specification for E04USA
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
▸▿ 9 Further Comments
9.1 Description of the Printed Output
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results
11 Algorithmic Details
▸▿ 12 Optional Parameters
12.1 Description of the Optional Parameters
13 Description of Monitoring Information

1 Purpose

E04USF/E04USA is designed to minimize an arbitrary smooth sum of squares function subject to constraints (which may include simple bounds on the variables, linear constraints and smooth nonlinear constraints) using a sequential quadratic programming (SQP) method. As many first derivatives as possible should be supplied by you; any unspecified derivatives are approximated by finite differences. See the description of the optional parameter Derivative Level, in Section 12.1. It is not intended for large sparse problems.
E04USF/E04USA may also be used for unconstrained, bound-constrained and linearly constrained optimization.
E04USA is a version of E04USF that has additional arguments in order to make it safe for use in multithreaded applications (see Section 5). The initialization routine E04WBF must have been called before calling E04USA.

2 Specification

2.1 Specification for E04USF

SUBROUTINE E04USF ( M, N, NCLIN, NCNLN, LDA, LDCJ, LDFJ, LDR, A, BL, BU, Y, CONFUN, OBJFUN, ITER, ISTATE, C, CJAC, F, FJAC, CLAMDA, OBJF, R, X, IWORK, LIWORK, WORK, LWORK, IUSER, RUSER, IFAIL)
INTEGER | M, N, NCLIN, NCNLN, LDA, LDCJ, LDFJ, LDR, ITER, ISTATE(N+NCLIN+NCNLN), IWORK(LIWORK), LIWORK, LWORK, IUSER(*), IFAIL
REAL (KIND=nag_wp) | A(LDA,*), BL(N+NCLIN+NCNLN), BU(N+NCLIN+NCNLN), Y(M), C(max(1,NCNLN)), CJAC(LDCJ,*), F(M), FJAC(LDFJ,N), CLAMDA(N+NCLIN+NCNLN), OBJF, R(LDR,N), X(N), WORK(LWORK), RUSER(*)
EXTERNAL | CONFUN, OBJFUN

2.2 Specification for E04USA

SUBROUTINE E04USA ( M, N, NCLIN, NCNLN, LDA, LDCJ, LDFJ, LDR, A, BL, BU, Y, CONFUN, OBJFUN, ITER, ISTATE, C, CJAC, F, FJAC, CLAMDA, OBJF, R, X, IWORK, LIWORK, WORK, LWORK, IUSER, RUSER, LWSAV, IWSAV, RWSAV, IFAIL)
INTEGER | M, N, NCLIN, NCNLN, LDA, LDCJ, LDFJ, LDR, ITER, ISTATE(N+NCLIN+NCNLN), IWORK(LIWORK), LIWORK, LWORK, IUSER(*), IWSAV(610), IFAIL
REAL (KIND=nag_wp) | A(LDA,*), BL(N+NCLIN+NCNLN), BU(N+NCLIN+NCNLN), Y(M), C(max(1,NCNLN)), CJAC(LDCJ,*), F(M), FJAC(LDFJ,N), CLAMDA(N+NCLIN+NCNLN), OBJF, R(LDR,N), X(N), WORK(LWORK), RUSER(*), RWSAV(475)
LOGICAL | LWSAV(120)
EXTERNAL | CONFUN, OBJFUN
Before calling E04USA, or either of the option setting routines E04UQA or E04URA, E04WBF must be called. The specification for E04WBF is:
SUBROUTINE E04WBF ( RNAME, CWSAV, LCWSAV, LWSAV, LLWSAV, IWSAV, LIWSAV, RWSAV, LRWSAV, IFAIL)
INTEGER | LCWSAV, LLWSAV, IWSAV(LIWSAV), LIWSAV, LRWSAV, IFAIL
REAL (KIND=nag_wp) | RWSAV(LRWSAV)
LOGICAL | LWSAV(LLWSAV)
CHARACTER(*) | RNAME
CHARACTER(80) | CWSAV(LCWSAV)
E04WBF should be called with RNAME='E04USA'. LCWSAV, LLWSAV, LIWSAV and LRWSAV, the declared lengths of CWSAV, LWSAV, IWSAV and RWSAV respectively, must satisfy:
  • LCWSAV≥1
  • LLWSAV≥120
  • LIWSAV≥610
  • LRWSAV≥475
The contents of the arrays CWSAV, LWSAV, IWSAV and RWSAV must not be altered between calling routines E04UQA, E04URA, E04USA and E04WBF.

3 Description

E04USF/E04USA is designed to solve the nonlinear least squares programming problem – the minimization of a smooth nonlinear sum of squares function subject to a set of constraints on the variables. The problem is assumed to be stated in the following form:
minimize x∈Rn F x = 12 ∑ i=1 m yi- fi x 2   subject to   l≤ x AL x c x ≤u, (1)
where F x (the objective function) is a nonlinear function which can be represented as the sum of squares of m subfunctions y 1-f 1 x,y 2-f 2 x,…,ym-fm x, the yi are constant, AL is an nL by n constant matrix, and c x is an nN element vector of nonlinear constraint functions. (The matrix AL and the vector c x may be empty.) The objective function and the constraint functions are assumed to be smooth, i.e., at least twice-continuously differentiable. (The method of E04USF/E04USA will usually solve (1) if any isolated discontinuities are away from the solution.)
Note that although the bounds on the variables could be included in the definition of the linear constraints, we prefer to distinguish between them for reasons of computational efficiency. For the same reason, the linear constraints should not be included in the definition of the nonlinear constraints. Upper and lower bounds are specified for all the variables and for all the constraints. An equality constraint can be specified by setting li=ui. If certain bounds are not present, the associated elements of l or u can be set to special values that will be treated as -∞ or +∞. (See the description of the optional parameter Infinite Bound Size.)
You must supply an initial estimate of the solution to (1), together with subroutines that define f x = f 1 x,f 2 x,…,fm x T , c x and as many first partial derivatives as possible; unspecified derivatives are approximated by finite differences.
The subfunctions are defined by the array Y and OBJFUN, and the nonlinear constraints are defined by CONFUN. On every call, these subroutines must return appropriate values of f x and c x. You should also provide the available partial derivatives. Any unspecified derivatives are approximated by finite differences for a discussion of the optional parameter Derivative Level. Note that if there are any nonlinear constraints, then the first call to CONFUN will precede the first call to OBJFUN.
For maximum reliability, it is preferable for you to provide all partial derivatives (see Chapter 8 of Gill et al. (1981) for a detailed discussion). If all gradients cannot be provided, it is similarly advisable to provide as many as possible. While developing OBJFUN and CONFUN, the optional parameter Verify should be used to check the calculation of any known gradients.

4 References

Gill P E, Murray W and Wright M H (1981) Practical Optimization Academic Press
Hock W and Schittkowski K (1981) Test Examples for Nonlinear Programming Codes. Lecture Notes in Economics and Mathematical Systems 187 Springer–Verlag

5 Arguments

1:   M – INTEGERInput
On entry: m, the number of subfunctions associated with F x.
Constraint: M>0.
2:   N – INTEGERInput
On entry: n, the number of variables.
Constraint: N>0.
3:   NCLIN – INTEGERInput
On entry: nL, the number of general linear constraints.
Constraint: NCLIN≥0.
4:   NCNLN – INTEGERInput
On entry: nN, the number of nonlinear constraints.
Constraint: NCNLN≥0.
5:   LDA – INTEGERInput
On entry: the first dimension of the array A as declared in the (sub)program from which E04USF/E04USA is called.
Constraint: LDA≥max 1,NCLIN.
6:   LDCJ – INTEGERInput
On entry: the first dimension of the array CJAC as declared in the (sub)program from which E04USF/E04USA is called.
Constraint: LDCJ≥max 1,NCNLN.
7:   LDFJ – INTEGERInput
On entry: the first dimension of the array FJAC as declared in the (sub)program from which E04USF/E04USA is called.
Constraint: LDFJ≥M.
8:   LDR – INTEGERInput
On entry: the first dimension of the array R as declared in the (sub)program from which E04USF/E04USA is called.
Constraint: LDR≥N.
9:   A LDA* – REAL (KIND=nag_wp) arrayInput
Note: the second dimension of the array A must be at least N if NCLIN>0, and at least 1 otherwise.
On entry: the ith row of A contains the ith row of the matrix AL of general linear constraints in (1). That is, the ith row contains the coefficients of the ith general linear constraint, for i=1,2,…,NCLIN.
If NCLIN=0, the array A is not referenced.
10:   BL N+NCLIN+NCNLN – REAL (KIND=nag_wp) arrayInput
11:   BU N+NCLIN+NCNLN – REAL (KIND=nag_wp) arrayInput
On entry: must contain the lower bounds and BU the upper bounds, for all the constraints in the following order. The first n elements of each array must contain the bounds on the variables, the next nL elements the bounds for the general linear constraints (if any) and the next nN elements the bounds for the general nonlinear constraints (if any). To specify a nonexistent lower bound (i.e., lj=-∞), set BL j≤-bigbnd, and to specify a nonexistent upper bound (i.e., uj=+∞), set BU j≥bigbnd; the default value of bigbnd is 1020, but this may be changed by the optional parameter Infinite Bound Size. To specify the jth constraint as an equality, set BL j=BU j=β, say, where β<bigbnd.
Constraints:
  • BL j≤BU j, for j=1,2,…,N+NCLIN+NCNLN;
  • if BL j=BU j=β, β<bigbnd.
12:   Y M – REAL (KIND=nag_wp) arrayInput
On entry: the coefficients of the constant vector y of the objective function.
13:   CONFUN – SUBROUTINE, supplied by the NAG Library or the user.External Procedure
CONFUN must calculate the vector c x of nonlinear constraint functions and (optionally) its Jacobian (= ∂c ∂x ) for a specified n-element vector x. If there are no nonlinear constraints (i.e., NCNLN=0), CONFUN will never be called by E04USF/E04USA and CONFUN may be the dummy routine E04UDM. (E04UDM is included in the NAG Library.) If there are nonlinear constraints, the first call to CONFUN will occur before the first call to OBJFUN.
The specification of CONFUN is:
SUBROUTINE CONFUN ( MODE, NCNLN, N, LDCJ, NEEDC, X, C, CJAC, NSTATE, IUSER, RUSER)
INTEGER | MODE, NCNLN, N, LDCJ, NEEDC(NCNLN), NSTATE, IUSER(*)
REAL (KIND=nag_wp) | X(N), C(NCNLN), CJAC(LDCJ,N), RUSER(*)
1:   MODE – INTEGERInput/Output
On entry: indicates which values must be assigned during each call of CONFUN. Only the following values need be assigned, for each value of i such that NEEDC i>0:
MODE=0
C i.
MODE=1
All available elements in the ith row of CJAC.
MODE=2
C i and all available elements in the ith row of CJAC.
On exit: may be set to a negative value if you wish to terminate the solution to the current problem, and in this case E04USF/E04USA will terminate with IFAIL set to MODE.
2:   NCNLN – INTEGERInput
On entry: nN, the number of nonlinear constraints.
3:   N – INTEGERInput
On entry: n, the number of variables.
4:   LDCJ – INTEGERInput
On entry: the first dimension of the array CJAC as declared in the (sub)program from which E04USF/E04USA is called.
5:   NEEDC NCNLN – INTEGER arrayInput
On entry: the indices of the elements of C and/or CJAC that must be evaluated by CONFUN. If NEEDC i>0, then the ith element of C and/or the available elements of the ith row of CJAC (see argument MODE) must be evaluated at x.
6:   X N – REAL (KIND=nag_wp) arrayInput
On entry: x, the vector of variables at which the constraint functions and/or all available elements of the constraint Jacobian are to be evaluated.
7:   C NCNLN – REAL (KIND=nag_wp) arrayOutput
On exit: if NEEDC i>0 and MODE=0 or 2, C i must contain the value of the ith constraint at x. The remaining elements of C, corresponding to the non-positive elements of NEEDC, are ignored.
8:   CJAC LDCJN – REAL (KIND=nag_wp) arrayInput/Output
On entry: is set to a special value.
On exit: if NEEDC i>0 and MODE=1 or 2, the ith row of CJAC must contain the available elements of the vector ∇ci given by
∇ci= ∂ci ∂x 1 , ∂ci ∂x 2 ,…, ∂ci ∂xn T,
where ∂ci ∂xj is the partial derivative of the ith constraint with respect to the jth variable, evaluated at the point x. See also the argument NSTATE. The remaining rows of CJAC, corresponding to non-positive elements of NEEDC, are ignored.
If all elements of the constraint Jacobian are known (i.e., Derivative Level=2 or 3), any constant elements may be assigned to CJAC one time only at the start of the optimization. An element of CJAC that is not subsequently assigned in CONFUN will retain its initial value throughout. Constant elements may be loaded into CJAC either before the call to E04USF/E04USA or during the first call to CONFUN (signalled by the value NSTATE=1). The ability to preload constants is useful when many Jacobian elements are identically zero, in which case CJAC may be initialized to zero and nonzero elements may be reset by CONFUN.
Note that constant nonzero elements do affect the values of the constraints. Thus, if CJAC ij is set to a constant value, it need not be reset in subsequent calls to CONFUN, but the value CJAC ij×X j must nonetheless be added to C i. For example, if CJAC 11=2 and CJAC 12=-5, then the term 2×X 1-5×X 2 must be included in the definition of C 1.
It must be emphasized that, if Derivative Level=0 or 1, unassigned elements of CJAC are not treated as constant; they are estimated by finite differences, at nontrivial expense. If you do not supply a value for the optional parameter Difference Interval, an interval for each element of x is computed automatically at the start of the optimization. The automatic procedure can usually identify constant elements of CJAC, which are then computed once only by finite differences.
9:   NSTATE – INTEGERInput
On entry: if NSTATE=1 then E04USF/E04USA is calling CONFUN for the first time. This argument setting allows you to save computation time if certain data must be read or calculated only once.
10:   IUSER* – INTEGER arrayUser Workspace
11:   RUSER* – REAL (KIND=nag_wp) arrayUser Workspace
CONFUN is called with the arguments IUSER and RUSER as supplied to E04USF/E04USA. You are free to use the arrays IUSER and RUSER to supply information to CONFUN as an alternative to using COMMON global variables.
CONFUN must either be a module subprogram USEd by, or declared as EXTERNAL in, the (sub)program from which E04USF/E04USA is called. Arguments denoted as Input must not be changed by this procedure.
Note: CONFUN should be tested separately before being used in conjunction with E04USF/E04USA. See also the description of the optional parameter Verify.
14:   OBJFUN – SUBROUTINE, supplied by the user.External Procedure
OBJFUN must calculate either the ith element of the vector f x = f 1 x,f 2 x,…,fm x T or all m elements of f x and (optionally) its Jacobian (= ∂f ∂x ) for a specified n-element vector x.
The specification of OBJFUN is:
SUBROUTINE OBJFUN ( MODE, M, N, LDFJ, NEEDFI, X, F, FJAC, NSTATE, IUSER, RUSER)
INTEGER | MODE, M, N, LDFJ, NEEDFI, NSTATE, IUSER(*)
REAL (KIND=nag_wp) | X(N), F(M), FJAC(LDFJ,N), RUSER(*)
1:   MODE – INTEGERInput/Output
On entry: indicates which values must be assigned during each call of OBJFUN. Only the following values need be assigned:
MODE=0 and NEEDFI=i, where i>0
F i.
MODE=0 and NEEDFI<0
F.
MODE=1 and NEEDFI<0
All available elements of FJAC.
MODE=2 and NEEDFI<0
F and all available elements of FJAC.
On exit: may be set to a negative value if you wish to terminate the solution to the current problem, and in this case E04USF/E04USA will terminate with IFAIL set to MODE.
2:   M – INTEGERInput
On entry: m, the number of subfunctions.
3:   N – INTEGERInput
On entry: n, the number of variables.
4:   LDFJ – INTEGERInput
On entry: the first dimension of the array FJAC as declared in the (sub)program from which E04USF/E04USA is called.
5:   NEEDFI – INTEGERInput
On entry: if NEEDFI=i>0, only the ith element of f x needs to be evaluated at x; the remaining elements need not be set. This can result in significant computational savings when m≫n.
6:   X N – REAL (KIND=nag_wp) arrayInput
On entry: x, the vector of variables at which f x and/or all available elements of its Jacobian are to be evaluated.
7:   F M – REAL (KIND=nag_wp) arrayOutput
On exit: if MODE=0 and NEEDFI=i>0, F i must contain the value of fi at x.
If MODE=0 or 2 and NEEDFI<0, F i must contain the value of fi at x, for i=1,2,…,m.
8:   FJAC LDFJN – REAL (KIND=nag_wp) arrayInput/Output
On entry: is set to a special value.
On exit: if MODE=1 or 2 and NEEDFI<0, the ith row of FJAC must contain the available elements of the vector ∇fi given by
∇fi= ∂fi ∂x 1 , ∂fi ∂x 2 ,…, ∂fi ∂xn T,
evaluated at the point x. See also the argument NSTATE.
9:   NSTATE – INTEGERInput
On entry: if NSTATE=1 then E04USF/E04USA is calling OBJFUN for the first time. This argument setting allows you to save computation time if certain data must be read or calculated only once.
10:   IUSER* – INTEGER arrayUser Workspace
11:   RUSER* – REAL (KIND=nag_wp) arrayUser Workspace
OBJFUN is called with the arguments IUSER and RUSER as supplied to E04USF/E04USA. You are free to use the arrays IUSER and RUSER to supply information to OBJFUN as an alternative to using COMMON global variables.
OBJFUN must either be a module subprogram USEd by, or declared as EXTERNAL in, the (sub)program from which E04USF/E04USA is called. Arguments denoted as Input must not be changed by this procedure.
Note: OBJFUN should be tested separately before being used in conjunction with E04USF/E04USA. See also the description of the optional parameter Verify.
15:   ITER – INTEGEROutput
On exit: the number of major iterations performed.
16:   ISTATE N+NCLIN+NCNLN – INTEGER arrayInput/Output
On entry: need not be set if the (default) optional parameter Cold Start is used.
If the optional parameter Warm Start has been chosen, the elements of ISTATE corresponding to the bounds and linear constraints define the initial working set for the procedure that finds a feasible point for the linear constraints and bounds. The active set at the conclusion of this procedure and the elements of ISTATE corresponding to nonlinear constraints then define the initial working set for the first QP subproblem. More precisely, the first n elements of ISTATE refer to the upper and lower bounds on the variables, the next nL elements refer to the upper and lower bounds on AL x, and the next nN elements refer to the upper and lower bounds on c x. Possible values for ISTATE j are as follows:
ISTATE j | Meaning
0 | The corresponding constraint is not in the initial QP working set.
1 | This inequality constraint should be in the working set at its lower bound.
2 | This inequality constraint should be in the working set at its upper bound.
3 | This equality constraint should be in the initial working set. This value must not be specified unless BL j=BU j.
The values -2, -1 and 4 are also acceptable but will be modified by the routine. If E04USF/E04USA has been called previously with the same values of N, NCLIN and NCNLN, ISTATE already contains satisfactory information. (See also the description of the optional parameter Warm Start.) The routine also adjusts (if necessary) the values supplied in X to be consistent with ISTATE.
Constraint: -2≤ISTATE j≤4, for j=1,2,…,N+NCLIN+NCNLN.
On exit: the status of the constraints in the QP working set at the point returned in X. The significance of each possible value of ISTATE j is as follows:
ISTATE j | Meaning
-2 | This constraint violates its lower bound by more than the appropriate feasibility tolerance (see the optional parameters Linear Feasibility Tolerance and Nonlinear Feasibility Tolerance). This value can occur only when no feasible point can be found for a QP subproblem.
-1 | This constraint violates its upper bound by more than the appropriate feasibility tolerance (see the optional parameters Linear Feasibility Tolerance and Nonlinear Feasibility Tolerance). This value can occur only when no feasible point can be found for a QP subproblem.
-0 | The constraint is satisfied to within the feasibility tolerance, but is not in the QP working set.
-1 | This inequality constraint is included in the QP working set at its lower bound.
-2 | This inequality constraint is included in the QP working set at its upper bound.
-3 | This constraint is included in the QP working set as an equality. This value of ISTATE can occur only when BL j=BU j.
17:   C max 1,NCNLN – REAL (KIND=nag_wp) arrayOutput
On exit: if NCNLN>0, C i contains the value of the ith nonlinear constraint function ci at the final iterate, for i=1,2,…,NCNLN.
If NCNLN=0, the array C is not referenced.
18:   CJAC LDCJ* – REAL (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array CJAC must be at least N if NCNLN>0, and at least 1 otherwise.
On entry: in general, CJAC need not be initialized before the call to E04USF/E04USA. However, if Derivative Level=3, you may optionally set the constant elements of CJAC (see argument NSTATE in the description of CONFUN). Such constant elements need not be re-assigned on subsequent calls to CONFUN.
On exit: if NCNLN>0, CJAC contains the Jacobian matrix of the nonlinear constraint functions at the final iterate, i.e., CJAC ij contains the partial derivative of the ith constraint function with respect to the jth variable, for i=1,2,…,NCNLN and j=1,2,…,N. (See the discussion of argument CJAC under CONFUN.)
If NCNLN=0, the array CJAC is not referenced.
19:   F M – REAL (KIND=nag_wp) arrayOutput
On exit: F i contains the value of the ith function fi at the final iterate, for i=1,2,…,M.
20:   FJAC LDFJN – REAL (KIND=nag_wp) arrayInput/Output
On entry: in general, FJAC need not be initialized before the call to E04USF/E04USA. However, if Derivative Level=3, you may optionally set the constant elements of FJAC (see argument NSTATE in the description of OBJFUN). Such constant elements need not be re-assigned on subsequent calls to OBJFUN.
On exit: the Jacobian matrix of the functions f 1,f 2,…,fm at the final iterate, i.e., FJAC ij contains the partial derivative of the ith function with respect to the jth variable, for i=1,2,…,M and j=1,2,…,N. (See also the discussion of argument FJAC under OBJFUN.)
21:   CLAMDA N+NCLIN+NCNLN – REAL (KIND=nag_wp) arrayInput/Output
On entry: need not be set if the (default) optional parameter Cold Start is used.
If the optional parameter Warm Start has been chosen, CLAMDA j must contain a multiplier estimate for each nonlinear constraint with a sign that matches the status of the constraint specified by the ISTATE array, for j=N+NCLIN+1,…,N+NCLIN+NCNLN. The remaining elements need not be set. Note that if the jth constraint is defined as ‘inactive’ by the initial value of the ISTATE array (i.e., ISTATE j=0), CLAMDA j should be zero; if the jth constraint is an inequality active at its lower bound (i.e., ISTATE j=1), CLAMDA j should be non-negative; if the jth constraint is an inequality active at its upper bound (i.e., ISTATE j=2, CLAMDA j should be non-positive. If necessary, the routine will modify CLAMDA to match these rules.
On exit: the values of the QP multipliers from the last QP subproblem. CLAMDA j should be non-negative if ISTATE j=1 and non-positive if ISTATE j=2.
22:   OBJF – REAL (KIND=nag_wp)Output
On exit: the value of the objective function at the final iterate.
23:   R LDRN – REAL (KIND=nag_wp) arrayInput/Output
On entry: need not be initialized if the (default) optional parameter Cold Start is used.
If the optional parameter Warm Start has been chosen, R must contain the upper triangular Cholesky factor R of the initial approximation of the Hessian of the Lagrangian function, with the variables in the natural order. Elements not in the upper triangular part of R are assumed to be zero and need not be assigned.
On exit: if Hessian=NO, R contains the upper triangular Cholesky factor R of QT H~Q, an estimate of the transformed and reordered Hessian of the Lagrangian at x (see (6) in E04UFF/E04UFA). If Hessian=YES, R contains the upper triangular Cholesky factor R of H, the approximate (untransformed) Hessian of the Lagrangian, with the variables in the natural order.
24:   X N – REAL (KIND=nag_wp) arrayInput/Output
On entry: an initial estimate of the solution.
On exit: the final estimate of the solution.
25:   IWORK LIWORK – INTEGER arrayWorkspace
26:   LIWORK – INTEGERInput
On entry: the dimension of the array IWORK as declared in the (sub)program from which E04USF/E04USA is called.
Constraint: LIWORK≥3×N+NCLIN+2×NCNLN.
27:   WORK LWORK – REAL (KIND=nag_wp) arrayWorkspace
28:   LWORK – INTEGERInput
On entry: the dimension of the array WORK as declared in the (sub)program from which E04USF/E04USA is called.
Constraints:
  • if NCNLN=0 and NCLIN=0, LWORK≥20×N+M×N+3;
  • if NCNLN=0 and NCLIN>0, LWORK≥2×N 2+20×N+11×NCLIN+ M×N+3;
  • if NCNLN>0 and NCLIN≥0, LWORK≥2×N 2+N×NCLIN+2×N× NCNLN+20×N+11×NCLIN+21×NCNLN+M×N+3.
The amounts of workspace provided and required are (by default) output on the current advisory message unit (as defined by X04ABF). As an alternative to computing LIWORK and LWORK from the formulas given above, you may prefer to obtain appropriate values from the output of a preliminary run with LIWORK and LWORK set to 1. (E04USF/E04USA will then terminate with IFAIL=9.)
29:   IUSER* – INTEGER arrayUser Workspace
30:   RUSER* – REAL (KIND=nag_wp) arrayUser Workspace
IUSER and RUSER are not used by E04USF/E04USA, but are passed directly to CONFUN and OBJFUN and may be used to pass information to these routines as an alternative to using COMMON global variables.
31:   IFAIL – INTEGERInput/Output
Note: for E04USA, IFAIL does not occur in this position in the argument list. See the additional arguments described below.
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, because for this routine the values of the output arguments may be useful even if IFAIL≠0 on exit, the recommended value is -1. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).
E04USF/E04USA returns with IFAIL=0 if the iterates have converged to a point x that satisfies the first-order Kuhn–Tucker conditions (see Section 11.1 in E04UFF/E04UFA) to the accuracy requested by the optional parameter Optimality Tolerance (default value=εr 0.8, where εr is the value of the optional parameter Function Precision (default value=ε 0.9, where ε is the machine precision)), i.e., the projected gradient and active constraint residuals are negligible at x.
You should check whether the following four conditions are satisfied:
(i) | the final value of Norm Gz (see Section 9.1) is significantly less than that at the starting point;
(ii) | during the final major iterations, the values of Step and Mnr (see Section 9.1) are both one;
(iii) | the last few values of both Norm Gz and Violtn (see Section 9.1) become small at a fast linear rate; and
(iv) | Cond Hz (see Section 9.1) is small.
If all these conditions hold, x is almost certainly a local minimum of (1).
Note: the following are additional arguments for specific use with E04USA. Users of E04USF therefore need not read the remainder of this description.
31:   LWSAV 120 – LOGICAL arrayCommunication Array
32:   IWSAV 610 – INTEGER arrayCommunication Array
33:   RWSAV 475 – REAL (KIND=nag_wp) arrayCommunication Array
The arrays LWSAV, IWSAV and RWSAV must not be altered between calls to any of the routines E04USA, E04UQA or E04URA.
34:   IFAIL – INTEGERInput/Output
Note: see the argument description for IFAIL above.

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Note: E04USF/E04USA may return useful information for one or more of the following detected errors or warnings.
Errors or warnings detected by the routine:
IFAIL<0
A negative value of IFAIL indicates an exit from E04USF/E04USA because you set MODE<0 in OBJFUN or CONFUN. The value of IFAIL will be the same as your setting of MODE.
IFAIL=1
The final iterate x satisfies the first-order Kuhn–Tucker conditions (see Section 11.1 in E04UFF/E04UFA) to the accuracy requested, but the sequence of iterates has not yet converged. E04USF/E04USA was terminated because no further improvement could be made in the merit function (see Section 9.1).
This value of IFAIL may occur in several circumstances. The most common situation is that you ask for a solution with accuracy that is not attainable with the given precision of the problem (as specified by the optional parameter Function Precision (default value=ε 0.9, where ε is the machine precision)). This condition will also occur if, by chance, an iterate is an ‘exact’ Kuhn–Tucker point, but the change in the variables was significant at the previous iteration. (This situation often happens when minimizing very simple functions, such as quadratics.)
If the four conditions listed in Section 5 for IFAIL=0 are satisfied, x is likely to be a solution of (1) even if IFAIL=1.
IFAIL=2
E04USF/E04USA has terminated without finding a feasible point for the linear constraints and bounds, which means that either no feasible point exists for the given value of the optional parameter Linear Feasibility Tolerance (default value=ε, where ε is the machine precision), or no feasible point could be found in the number of iterations specified by the optional parameter Minor Iteration Limit (default value=max 50,3 n+nL+nN). You should check that there are no constraint redundancies. If the data for the constraints are accurate only to an absolute precision σ, you should ensure that the value of the optional parameter Linear Feasibility Tolerance is greater than σ. For example, if all elements of AL are of order unity and are accurate to only three decimal places, Linear Feasibility Tolerance should be at least 10-3.
IFAIL=3
No feasible point could be found for the nonlinear constraints. The problem may have no feasible solution. This means that there has been a sequence of QP subproblems for which no feasible point could be found (indicated by I at the end of each line of intermediate printout produced by the major iterations; see Section 9.1). This behaviour will occur if there is no feasible point for the nonlinear constraints. (However, there is no general test that can determine whether a feasible point exists for a set of nonlinear constraints.) If the infeasible subproblems occur from the very first major iteration, it is highly likely that no feasible point exists. If infeasibilities occur when earlier subproblems have been feasible, small constraint inconsistencies may be present. You should check the validity of constraints with negative values of ISTATE. If you are convinced that a feasible point does exist, E04USF/E04USA should be restarted at a different starting point.
IFAIL=4
The limiting number of iterations (as determined by the optional parameter Major Iteration Limit (default value=max 50,3 n+nL+10 nN) has been reached.
If the algorithm appears to be making satisfactory progress, then Major Iteration Limit may be too small. If so, either increase its value and rerun E04USF/E04USA or, alternatively, rerun E04USF/E04USA using the optional parameter Warm Start. If the algorithm seems to be making little or no progress however, then you should check for incorrect gradients or ill-conditioning as described under IFAIL=6.
Note that ill-conditioning in the working set is sometimes resolved automatically by the algorithm, in which case performing additional iterations may be helpful. However, ill-conditioning in the Hessian approximation tends to persist once it has begun, so that allowing additional iterations without altering R is usually inadvisable. If the quasi-Newton update of the Hessian approximation was reset during the latter major iterations (i.e., an R occurs at the end of each line of intermediate printout; see Section 9.1), it may be worthwhile to try a Warm Start at the final point as suggested above.
IFAIL=5
Not used by this routine.
IFAIL=6
x does not satisfy the first-order Kuhn–Tucker conditions (see Section 11.1 in E04UFF/E04UFA), and no improved point for the merit function (see Section 9.1) could be found during the final linesearch.
This sometimes occurs because an overly stringent accuracy has been requested, i.e., the value of the optional parameter Optimality Tolerance (default value=εr 0.8, where εr is the value of the optional parameter Function Precision (default value=ε 0.9, where ε is the machine precision)) is too small. In this case you should apply the four tests described under IFAIL=0 to determine whether or not the final solution is acceptable (see Gill et al. (1981), for a discussion of the attainable accuracy).
If many iterations have occurred in which essentially no progress has been made and E04USF/E04USA has failed completely to move from the initial point then user-supplied subroutines OBJFUN and/or CONFUN may be incorrect. You should refer to comments under IFAIL=7 and check the gradients using the optional parameter Verify (default value=0). Unfortunately, there may be small errors in the objective and constraint gradients that cannot be detected by the verification process. Finite difference approximations to first derivatives are catastrophically affected by even small inaccuracies. An indication of this situation is a dramatic alteration in the iterates if the finite difference interval is altered. One might also suspect this type of error if a switch is made to central differences even when Norm Gz and Violtn (see Section 9.1) are large.
Another possibility is that the search direction has become inaccurate because of ill-conditioning in the Hessian approximation or the matrix of constraints in the working set; either form of ill-conditioning tends to be reflected in large values of Mnr (the number of iterations required to solve each QP subproblem; see Section 9.1).
If the condition estimate of the projected Hessian (Cond Hz; see Section 13) is extremely large, it may be worthwhile rerunning E04USF/E04USA from the final point with the optional parameter Warm Start. In this situation, ISTATE and CLAMDA should be left unaltered and R should be reset to the identity matrix.
If the matrix of constraints in the working set is ill-conditioned (i.e., Cond T is extremely large; see Section 13), it may be helpful to run E04USF/E04USA with a relaxed value of the optional parameter Feasibility Tolerance (default value=ε, where ε is the machine precision). (Constraint dependencies are often indicated by wide variations in size in the diagonal elements of the matrix T, whose diagonals will be printed if Major Print Level≥30).
IFAIL=7
The user-supplied derivatives of the subfunctions and/or nonlinear constraints appear to be incorrect.
Large errors were found in the derivatives of the subfunctions and/or nonlinear constraints. This value of IFAIL will occur if the verification process indicated that at least one Jacobian element had no correct figures. You should refer to the printed output to determine which elements are suspected to be in error.
As a first-step, you should check that the code for the subfunction and constraint values is correct – for example, by computing the subfunctions at a point where the correct value of F x is known. However, care should be taken that the chosen point fully tests the evaluation of the subfunctions. It is remarkable how often the values x=0 or x=1 are used to test function evaluation procedures, and how often the special properties of these numbers make the test meaningless.
Special care should be used in this test if computation of the subfunctions involves subsidiary data communicated in COMMON storage. Although the first evaluation of the subfunctions may be correct, subsequent calculations may be in error because some of the subsidiary data has accidentally been overwritten.
Gradient checking will be ineffective if the objective function uses information computed by the constraints, since they are not necessarily computed before each function evaluation.
Errors in programming the subfunctions may be quite subtle in that the subfunction values are ‘almost’ correct. For example, a subfunction may not be accurate to full precision because of the inaccurate calculation of a subsidiary quantity, or the limited accuracy of data upon which the subfunction depends. A common error on machines where numerical calculations are usually performed in double precision is to include even one single precision constant in the calculation of the subfunction; since some compilers do not convert such constants to double precision, half the correct figures may be lost by such a seemingly trivial error.
IFAIL=8
Not used by this routine.
IFAIL=9
An input argument is invalid.
overflow
If overflow occurs then either an element of C is very large, or the singular values or singular vectors have been incorrectly supplied.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

If IFAIL=0 on exit, then the vector returned in the array X is an estimate of the solution to an accuracy of approximately Optimality Tolerance (default value=ε 0.8, where ε is the machine precision).

8 Parallelism and Performance

E04USF/E04USA is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
E04USF/E04USA makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

9.1 Description of the Printed Output

This section describes the intermediate printout and final printout produced by E04USF/E04USA. The intermediate printout is a subset of the monitoring information produced by the routine at every iteration (see Section 13). You can control the level of printed output (see the description of the optional parameter Major Print Level). Note that the intermediate printout and final printout are produced only if Major Print Level≥10 (the default for E04USF, by default no output is produced by E04USA). (by default no output is produced by E04USF).
The following line of summary output (<80 characters) is produced at every major iteration. In all cases, the values of the quantities printed are those in effect on completion of the given iteration.
Maj | is the major iteration count.
Mnr is the number of minor iterations required by the feasibility and optimality phases of the QP subproblem. Generally, Mnr will be 1 in the later iterations, since theoretical analysis predicts that the correct active set will be identified near the solution (see Section 11 in E04UFF/E04UFA).
Note that Mnr may be greater than the optional parameter Minor Iteration Limit if some iterations are required for the feasibility phase.
Step | is the step αk taken along the computed search direction. On reasonably well-behaved problems, the unit step (i.e., αk=1) will be taken as the solution is approached.
Merit Function is the value of the augmented Lagrangian merit function (see (12) in E04UFF/E04UFA) at the current iterate. This function will decrease at each iteration unless it was necessary to increase the penalty parameters (see Section 11.3 in E04UFF/E04UFA). As the solution is approached, Merit Function will converge to the value of the objective function at the solution.
If the QP subproblem does not have a feasible point (signified by I at the end of the current output line) then the merit function is a large multiple of the constraint violations, weighted by the penalty parameters. During a sequence of major iterations with infeasible subproblems, the sequence of Merit Function values will decrease monotonically until either a feasible subproblem is obtained or E04USF/E04USA terminates with IFAIL=3 (no feasible point could be found for the nonlinear constraints).
If there are no nonlinear constraints present (i.e., NCNLN=0) then this entry contains Objective, the value of the objective function F x. The objective function will decrease monotonically to its optimal value when there are no nonlinear constraints.
Norm Gz | is ZT gFR, the Euclidean norm of the projected gradient (see Section 11.2 in E04UFF/E04UFA). Norm Gz will be approximately zero in the neighbourhood of a solution.
Violtn | is the Euclidean norm of the residuals of constraints that are violated or in the predicted active set (not printed if NCNLN is zero). Violtn will be approximately zero in the neighbourhood of a solution.
Cond Hz | is a lower bound on the condition number of the projected Hessian approximation HZ ( HZ = ZT HFR Z = RZT RZ ; see (6) and (11) in E04UFF/E04UFA). The larger this number, the more difficult the problem.
M | is printed if the quasi-Newton update has been modified to ensure that the Hessian approximation is positive definite (see Section 11.4 in E04UFF/E04UFA).
I | is printed if the QP subproblem has no feasible point.
C | is printed if central differences have been used to compute the unspecified objective and constraint gradients. If the value of Step is zero then the switch to central differences was made because no lower point could be found in the linesearch. (In this case, the QP subproblem is resolved with the central difference gradient and Jacobian.) If the value of Step is nonzero then central differences were computed because Norm Gz and Violtn imply that x is close to a Kuhn–Tucker point (see Section 11.1 in E04UFF/E04UFA).
L | is printed if the linesearch has produced a relative change in x greater than the value defined by the optional parameter Step Limit. If this output occurs frequently during later iterations of the run, optional parameter Step Limit should be set to a larger value.
R | is printed if the approximate Hessian has been refactorized. If the diagonal condition estimator of R indicates that the approximate Hessian is badly conditioned then the approximate Hessian is refactorized using column interchanges. If necessary, R is modified so that its diagonal condition estimator is bounded.
The final printout includes a listing of the status of every variable and constraint.
The following describes the printout for each variable. A full stop (.) is printed for any numerical value that is zero.
Varbl | gives the name (V) and index j, for j=1,2,…,n, of the variable.
State gives the state of the variable (FR if neither bound is in the working set, EQ if a fixed variable, LL if on its lower bound, UL if on its upper bound, TF if temporarily fixed at its current value). If Value lies outside the upper or lower bounds by more than the Feasibility Tolerance, State will be ++ or -- respectively.
A key is sometimes printed before State.
A | Alternative optimum possible. The variable is active at one of its bounds, but its Lagrange multiplier is essentially zero. This means that if the variable were allowed to start moving away from its bound then there would be no change to the objective function. The values of the other free variables might change, giving a genuine alternative solution. However, if there are any degenerate variables (labelled D), the actual change might prove to be zero, since one of them could encounter a bound immediately. In either case the values of the Lagrange multipliers might also change.
D | Degenerate. The variable is free, but it is equal to (or very close to) one of its bounds.
I | Infeasible. The variable is currently violating one of its bounds by more than the Feasibility Tolerance.
Value | is the value of the variable at the final iteration.
Lower Bound | is the lower bound specified for the variable. None indicates that BL j≤-bigbnd.
Upper Bound | is the upper bound specified for the variable. None indicates that BU j≥bigbnd.
Lagr Mult | is the Lagrange multiplier for the associated bound. This will be zero if State is FR unless BL j≤-bigbnd and BU j≥bigbnd, in which case the entry will be blank. If x is optimal, the multiplier should be non-negative if State is LL and non-positive if State is UL.
Slack | is the difference between the variable Value and the nearer of its (finite) bounds BL j and BU j. A blank entry indicates that the associated variable is not bounded (i.e., BL j≤-bigbnd and BU j≥bigbnd).
The meaning of the printout for linear and nonlinear constraints is the same as that given above for variables, with ‘variable’ replaced by ‘constraint’, BL j and BU j are replaced by BL n+j and BU n+j respectively, and with the following changes in the heading:
L Con | gives the name (L) and index j, for j=1,2,…,nL, of the linear constraint.
N Con | gives the name (N) and index (j-nL), for j=nL+1,…,nL+nN, of the nonlinear constraint.
Note that movement off a constraint (as opposed to a variable moving away from its bound) can be interpreted as allowing the entry in the Slack column to become positive.
Numerical values are output with a fixed number of digits; they are not guaranteed to be accurate to this precision.

10 Example

This example is based on Problem 57 in Hock and Schittkowski (1981) and involves the minimization of the sum of squares function
F x = 12 ∑ i=1 44 yi - fi x 2 ,
where
fi x = x 1 + 0.49-x 1 e -x 2 ai- 8
and
i yi ai i yi ai 1 0.49 8 23 0.41 22 2 0.49 8 24 0.40 22 3 0.48 10 25 0.42 24 4 0.47 10 26 0.40 24 5 0.48 10 27 0.40 24 6 0.47 10 28 0.41 26 7 0.46 12 29 0.40 26 8 0.46 12 30 0.41 26 9 0.45 12 31 0.41 28 10 0.43 12 32 0.40 28 11 0.45 14 33 0.40 30 12 0.43 14 34 0.40 30 13 0.43 14 35 0.38 30 14 0.44 16 36 0.41 32 15 0.43 16 37 0.40 32 16 0.43 16 38 0.40 34 17 0.46 18 39 0.41 36 18 0.45 18 40 0.38 36 19 0.42 20 41 0.40 38 20 0.42 20 42 0.40 38 21 0.43 20 43 0.39 40 22 0.41 22 44 0.39 42
subject to the bounds
x 1≥-0.4 x 2≥-4.0
to the general linear constraint
x 1+x 2≥1.0
and to the nonlinear constraint
0.49 x 2-x 1 x 2≥ 0.09 .
The initial point, which is infeasible, is
x 0=0.4,0.0 T
and F x 0=0.002241.
The optimal solution (to five figures) is
x*=0.41995,1.28484 T,
and F x*=0.01423. The nonlinear constraint is active at the solution.
The document for E04UQF/E04UQA includes an example program to solve the same problem using some of the optional parameters described in Section 12.

10.1 Program Text

Note: the following programs illustrate the use of E04USF and E04USA.

Program Text (e04usfe.f90)

Program Text (e04usae.f90)

10.2 Program Data

Program Data (e04usfe.d)

Program Data (e04usae.d)

10.3 Program Results

Program Results (e04usfe.r)

Program Results (e04usae.r)

Note: the remainder of this document is intended for more advanced users. Section 12 describes the optional parameters which may be set by calls to E04UQF/E04UQA and/or E04URF/E04URA. Section 13 describes the quantities which can be requested to monitor the course of the computation.

11 Algorithmic Details

E04USF/E04USA implements a sequential quadratic programming (SQP) method incorporating an augmented Lagrangian merit function and a BFGS (Broyden–Fletcher–Goldfarb–Shanno) quasi-Newton approximation to the Hessian of the Lagrangian, and is based on E04WDF. The documents for E04NCF/E04NCA, E04UFF/E04UFA and E04WDF should be consulted for details of the method.

12 Optional Parameters

Several optional parameters in E04USF/E04USA define choices in the problem specification or the algorithm logic. In order to reduce the number of formal arguments of E04USF/E04USA these optional parameters have associated default values that are appropriate for most problems. Therefore you need only specify those optional parameters whose values are to be different from their default values.
The remainder of this section can be skipped if you wish to use the default values for all optional parameters.
The following is a list of the optional parameters available. A full description of each optional parameter is provided in Section 12.1.
  • Central Difference Interval
  • Cold Start
  • Crash Tolerance
  • Defaults
  • Derivative Level
  • Difference Interval
  • Feasibility Tolerance
  • Function Precision
  • Hessian
  • Infinite Bound Size
  • Infinite Step Size
  • Iteration Limit
  • Iters
  • Itns
  • JTJ Initial Hessian
  • Linear Feasibility Tolerance
  • Line Search Tolerance
  • List
  • Major Iteration Limit
  • Major Print Level
  • Minor Iteration Limit
  • Minor Print Level
  • Monitoring File
  • Nolist
  • Nonlinear Feasibility Tolerance
  • Optimality Tolerance
  • Print Level
  • Reset Frequency
  • Start Constraint Check At Variable
  • Start Objective Check At Variable
  • Step Limit
  • Stop Constraint Check At Variable
  • Stop Objective Check At Variable
  • Unit Initial Hessian
  • Verify
  • Verify Constraint Gradients
  • Verify Gradients
  • Verify Level
  • Verify Objective Gradients
  • Warm Start
Optional parameters may be specified by calling one, or both, of E04UQF/E04UQA and E04URF/E04URA before a call to E04USF/E04USA.
E04UQF/E04UQA reads options from an external options file, with Begin and End as the first and last lines respectively and each intermediate line defining a single optional parameter. For example,
Begin
  Print level = 1
End
The call
 CALL E04UQF (IOPTNS, INFORM)
can then be used to read the file on unit IOPTNS. INFORM will be zero on successful exit. E04UQF/E04UQA should be consulted for a full description of this method of supplying optional parameters.
E04URF/E04URA can be called to supply options directly, one call being necessary for each optional parameter. For example,
 CALL E04URF ('Print Level = 1')
E04URF/E04URA should be consulted for a full description of this method of supplying optional parameters.
All optional parameters not specified by you are set to their default values. Optional parameters specified by you are unaltered by E04USF/E04USA (unless they define invalid values) and so remain in effect for subsequent calls to E04USF/E04USA, unless altered by you.

12.1 Description of the Optional Parameters

For each option, we give a summary line, a description of the optional parameter and details of constraints.
The summary line contains:
  • the keywords, where the minimum abbreviation of each keyword is underlined (if no characters of an optional qualifier are underlined, the qualifier may be omitted);
  • a parameter value, where the letters a, i and r denote options that take character, integer and real values respectively;
  • the default value, where the symbol ε is a generic notation for machine precision (see X02AJF), and εr denotes the relative precision of the objective function Function Precision.
Keywords and character values are case and white space insensitive.
Further details of other quantities not explicitly defined in this section may be found by consulting the document for E04UFF/E04UFA.
Central Difference Interval r Default values are computed
If the algorithm switches to central differences because the forward-difference approximation is not sufficiently accurate, the value of r is used as the difference interval for every element of x. The switch to central differences is indicated by C at the end of each line of intermediate printout produced by the major iterations (see Section 9.1). The use of finite differences is discussed further under the optional parameter Difference Interval.
If you supply a value for this optional parameter, a small value between 0.0 and 1.0 is appropriate.
Cold Start Default
Warm Start
This option controls the specification of the initial working set in both the procedure for finding a feasible point for the linear constraints and bounds, and in the first QP subproblem thereafter. With a Cold Start, the first working set is chosen by E04USF/E04USA based on the values of the variables and constraints at the initial point. Broadly speaking, the initial working set will include equality constraints and bounds or inequality constraints that violate or ‘nearly’ satisfy their bounds (to within Crash Tolerance).
With a Warm Start, you must set the ISTATE array and define CLAMDA and R as discussed in Section 5. ISTATE values associated with bounds and linear constraints determine the initial working set of the procedure to find a feasible point with respect to the bounds and linear constraints. ISTATE values associated with nonlinear constraints determine the initial working set of the first QP subproblem after such a feasible point has been found. E04USF/E04USA will override your specification of ISTATE if necessary, so that a poor choice of the working set will not cause a fatal error. For instance, any elements of ISTATE which are set to -2, -1​ or ​4 will be reset to zero, as will any elements which are set to 3 when the corresponding elements of BL and BU are not equal. A Warm Start will be advantageous if a good estimate of the initial working set is available – for example, when E04USF/E04USA is called repeatedly to solve related problems.
Crash Tolerance r Default =0.01
This value is used in conjunction with the optional parameter Cold Start (the default value) when E04USF/E04USA selects an initial working set. If 0≤r≤1, the initial working set will include (if possible) bounds or general inequality constraints that lie within r of their bounds. In particular, a constraint of the form ajT x≥l will be included in the initial working set if ajT x-l ≤ r 1+l . If r<0 or r>1, the default value is used.
Defaults
This special keyword may be used to reset all optional parameters to their default values.
Derivative Level i Default =3
This parameter indicates which derivatives are provided in user-supplied subroutines OBJFUN and CONFUN. The possible choices for i are the following.
i | Meaning
3 | All elements of the objective Jacobian and the constraint Jacobian are provided by you.
2 | All elements of the constraint Jacobian are provided, but some elements of the objective Jacobian are not specified by you.
1 | All elements of the objective Jacobian are provided, but some elements of the constraint Jacobian are not specified by you.
0 | Some elements of both the objective Jacobian and the constraint Jacobian are not specified by you.
The value i=3 should be used whenever possible, since E04USF/E04USA is more reliable (and will usually be more efficient) when all derivatives are exact.
If i=0​ or ​2, E04USF/E04USA will approximate unspecified elements of the objective Jacobian, using finite differences. The computation of finite difference approximations usually increases the total run-time, since a call to OBJFUN is required for each unspecified element. Furthermore, less accuracy can be attained in the solution (see Chapter 8 of Gill et al. (1981), for a discussion of limiting accuracy).
If i=0​ or ​1, E04USF/E04USA will approximate unspecified elements of the constraint Jacobian. One call to CONFUN is needed for each variable for which partial derivatives are not available. For example, if the constraint Jacobian has the form
* * * * * ? ? * * * ? * * * * *
where ‘*’ indicates an element provided by you and ‘?’ indicates an unspecified element, E04USF/E04USA will call CONFUN twice: once to estimate the missing element in column 2, and again to estimate the two missing elements in column 3. (Since columns 1 and 4 are known, they require no calls to CONFUN.)
At times, central differences are used rather than forward differences, in which case twice as many calls to OBJFUN and CONFUN are needed. (The switch to central differences is not under your control.)
If i<0 or i>3, the default value is used.
Difference Interval r Default values are computed
This option defines an interval used to estimate derivatives by finite differences in the following circumstances:
(a) | For verifying the objective and/or constraint gradients (see the description of the optional parameter Verify).
(b) | For estimating unspecified elements of the objective and/or constraint Jacobian matrix.
In general, a derivative with respect to the jth variable is approximated using the interval δj, where δj=r 1+x^j, with x^ the first point feasible with respect to the bounds and linear constraints. If the functions are well scaled, the resulting derivative approximation should be accurate to O r. See Gill et al. (1981) for a discussion of the accuracy in finite difference approximations.
If a difference interval is not specified, a finite difference interval will be computed automatically for each variable by a procedure that requires up to six calls of CONFUN and OBJFUN for each element. This option is recommended if the function is badly scaled or you wish to have E04USF/E04USA determine constant elements in the objective and constraint gradients (see the descriptions of CONFUN and OBJFUN in Section 5).
If you supply a value for this optional parameter, a small value between 0.0 and 1.0 is appropriate.
Feasibility Tolerance r Default =ε
The scalar r defines the maximum acceptable absolute violations in linear and nonlinear constraints at a ‘feasible’ point; i.e., a constraint is considered satisfied if its violation does not exceed r. If r<ε or r≥1, the default value is used. Using this keyword sets both optional parameters Linear Feasibility Tolerance and Nonlinear Feasibility Tolerance to r, if ε≤r<1. (Additional details are given under the descriptions of these optional parameters.)
Function Precision r Default =ε 0.9
This parameter defines εr, which is intended to be a measure of the accuracy with which the problem functions F x and c x can be computed. If r<ε or r≥1, the default value is used.
The value of εr should reflect the relative precision of 1+F x; i.e., εr acts as a relative precision when F is large and as an absolute precision when F is small. For example, if F x is typically of order 1000 and the first six significant digits are known to be correct, an appropriate value for εr would be 10-6. In contrast, if F x is typically of order 10-4 and the first six significant digits are known to be correct, an appropriate value for εr would be 10-10. The choice of εr can be quite complicated for badly scaled problems; see Chapter 8 of Gill et al. (1981) for a discussion of scaling techniques. The default value is appropriate for most simple functions that are computed with full accuracy. However, when the accuracy of the computed function values is known to be significantly worse than full precision, the value of εr should be large enough so that E04USF/E04USA will not attempt to distinguish between function values that differ by less than the error inherent in the calculation.
Hessian N o Default =NO
This option controls the contents of the upper triangular matrix R (see Section 5). E04USF/E04USA works exclusively with the transformed and reordered Hessian HQ, and hence extra computation is required to form the Hessian itself. If Hessian=NO, R contains the Cholesky factor of the transformed and reordered Hessian. If Hessian=YES, the Cholesky factor of the approximate Hessian itself is formed and stored in R. You should select Hessian=YES if a Warm Start will be used for the next call to E04USF/E04USA.
Infinite Bound Size r Default =1020
If r>0, r defines the ‘infinite’ bound bigbnd in the definition of the problem constraints. Any upper bound greater than or equal to bigbnd will be regarded as +∞ (and similarly any lower bound less than or equal to -bigbnd will be regarded as -∞). If r<0, the default value is used.
Infinite Step Size r Default =max bigbnd,1020
If r>0, r specifies the magnitude of the change in variables that is treated as a step to an unbounded solution. If the change in x during an iteration would exceed the value of r, the objective function is considered to be unbounded below in the feasible region. If r≤0, the default value is used.
JTJ Initial Hessian Default
Unit Initial Hessian
This option controls the initial value of the upper triangular matrix R. If J denotes the objective Jacobian matrix ∇f x, then JT J is often a good approximation to the objective Hessian matrix ∇2 F x (see also optional parameter Reset Frequency).
Line Search Tolerance r Default =0.9
The value r (0≤r<1) controls the accuracy with which the step α taken during each iteration approximates a minimum of the merit function along the search direction (the smaller the value of r, the more accurate the linesearch). The default value r=0.9 requests an inaccurate search and is appropriate for most problems, particularly those with any nonlinear constraints.
If there are no nonlinear constraints, a more accurate search may be appropriate when it is desirable to reduce the number of major iterations – for example, if the objective function is cheap to evaluate, or if a substantial number of derivatives are unspecified. If r<0 or r≥1, the default value is used.
Linear Feasibility Tolerance r 1 Default =ε
Nonlinear Feasibility Tolerance r 2 Default =ε 0.33 or ε
The default value of r 2 is ε 0.33 if Derivative Level=0 or 1, and ε otherwise.
The scalars r 1 and r 2 define the maximum acceptable absolute violations in linear and nonlinear constraints at a ‘feasible’ point; i.e., a linear constraint is considered satisfied if its violation does not exceed r 1, and similarly for a nonlinear constraint and r 2. If rm<ε or rm≥1, the default value is used, for m=1,2.
On entry to E04USF/E04USA, an iterative procedure is executed in order to find a point that satisfies the linear constraints and bounds on the variables to within the tolerance r 1. All subsequent iterates will satisfy the linear constraints to within the same tolerance (unless r 1 is comparable to the finite difference interval).
For nonlinear constraints, the feasibility tolerance r 2 defines the largest constraint violation that is acceptable at an optimal point. Since nonlinear constraints are generally not satisfied until the final iterate, the value of optional parameter Nonlinear Feasibility Tolerance acts as a partial termination criterion for the iterative sequence generated by E04USF/E04USA (see also optional parameter Optimality Tolerance).
These tolerances should reflect the precision of the corresponding constraints. For example, if the variables and the coefficients in the linear constraints are of order unity, and the latter are correct to about 6 decimal digits, it would be appropriate to specify r 1 as 10-6.
List Default for E04USF =List
Nolist Default for E04USA =Nolist
Normally each optional parameter specification is printed as it is supplied. Optional parameter Nolist may be used to suppress the printing and optional parameter List may be used to restore printing.
Major Iteration Limit i Default =max 50,3 n+nL+10 nN
Iteration Limit
Iters
Itns
The value of i specifies the maximum number of major iterations allowed before termination. Setting i=0 and Major Print Level>0 means that the workspace needed will be computed and printed, but no iterations will be performed. If i<0, the default value is used.
Major Print Level i Default for E04USF =10
Print Level Default for E04USA =0
The value of i controls the amount of printout produced by the major iterations of E04USF/E04USA, as indicated below. A detailed description of the printed output is given in Section 9.1 (summary output at each major iteration and the final solution) and Section 13 (monitoring information at each major iteration). (See also the description of the optional parameter Minor Print Level.)
The following printout is sent to the current advisory message unit (as defined by X04ABF):
i | Output
≥0 0 | No output.
≥0 1 | The final solution only.
≥0 5 | One line of summary output (<80 characters; see Section 9.1) for each major iteration (no printout of the final solution).
≥10 | The final solution and one line of summary output for each major iteration.
The following printout is sent to the logical unit number by the optional parameter Monitoring File:
i | Output
<5 | No output.
≥5 | One long line of output (>80 characters; see Section 13) for each major iteration (no printout of the final solution).
≥20 | At each major iteration, the objective function, the Euclidean norm of the nonlinear constraint violations, the values of the nonlinear constraints (the vector c), the values of the linear constraints (the vector AL x), and the current values of the variables (the vector x).
≥30 | At each major iteration, the diagonal elements of the matrix T associated with the TQ factorization (see (5) in E04UFF/E04UFA) of the QP working set, and the diagonal elements of R, the triangular factor of the transformed and reordered Hessian (see (6) in E04UFF/E04UFA).
If Major Print Level≥5 and the unit number defined by the optional parameter Monitoring File is the same as that defined by X04ABF, then the summary output for each major iteration is suppressed.
Minor Iteration Limit i Default =max 50,3 n+nL+nN
The value of i specifies the maximum number of iterations for finding a feasible point with respect to the bounds and linear constraints (if any). The value of i also specifies the maximum number of minor iterations for the optimality phase of each QP subproblem. If i≤0, the default value is used.
Minor Print Level i Default =0
The value of i controls the amount of printout produced by the minor iterations of E04USF/E04USA (i.e., the iterations of the quadratic programming algorithm), as indicated below. A detailed description of the printed output is given in Section 9.1 (summary output at each minor iteration and the final QP solution) and Section 13 (monitoring information at each minor iteration). (See also the description of the optional parameter Major Print Level.)
The following printout is sent to the current advisory message unit (as defined by X04ABF):
i | Output
≥0 0 | No output.
≥0 1 | The final QP solution only.
≥0 5 | One line of summary output (<80 characters; see Section 9.1) for each minor iteration (no printout of the final QP solution).
≥10 | The final QP solution and one line of summary output for each minor iteration.
The following printout is sent to the logical unit number by the optional parameter Monitoring File:
i | Output
<5 | No output.
≥5 | One long line of output (>80 characters; see Section 13) for each minor iteration (no printout of the final QP solution).
≥20 | At each minor iteration, the current estimates of the QP multipliers, the current estimate of the QP search direction, the QP constraint values, and the status of each QP constraint.
≥30 | At each minor iteration, the diagonal elements of the matrix T associated with the TQ factorization (see (5) in E04UFF/E04UFA) of the QP working set, and the diagonal elements of the Cholesky factor R of the transformed Hessian (see (6) in E04UFF/E04UFA).
If Major Print Level≥5 and the unit number defined by the optional parameter Monitoring File is the same as that defined by X04ABF, then the summary output for each major iteration is suppressed.
Monitoring File i Default =-1
If i≥0 and Major Print Level≥5 or i≥0 and Minor Print Level≥5, monitoring information produced by E04USF/E04USA at every iteration is sent to a file with logical unit number i. If i<0 and/or Major Print Level<5 and Minor Print Level<5, no monitoring information is produced.
Optimality Tolerance r Default =εR 0.8
The parameter r (εR≤r<1) specifies the accuracy to which you wish the final iterate to approximate a solution of the problem. Broadly speaking, r indicates the number of correct figures desired in the objective function at the solution. For example, if r is 10-6 and E04USF/E04USA terminates successfully, the final value of F should have approximately six correct figures. If r<εR or r≥1, the default value is used.
E04USF/E04USA will terminate successfully if the iterative sequence of x values is judged to have converged and the final point satisfies the first-order Kuhn–Tucker conditions (see Section 11.1 in E04UFF/E04UFA). The sequence of iterates is considered to have converged at x if
α p≤r 1+x, (2)
where p is the search direction and α the step length. An iterate is considered to satisfy the first-order conditions for a minimum if
ZT g FR ≤ r 1 + max 1 + F x , g FR (3)
and
resj≤ftol  for all  j, (4)
where ZT gFR is the projected gradient, gFR is the gradient of F x with respect to the free variables, resj is the violation of the jth active nonlinear constraint, and ftol is the Nonlinear Feasibility Tolerance.
Reset Frequency i Default =2
If i>0, this parameter allows you to reset the approximate Hessian matrix to JT J every i iterations, where J is the objective Jacobian matrix ∇f x (see also the description of the optional parameter JTJ Initial Hessian).
At any point where there are no nonlinear constraints active and the values of f are small in magnitude compared to the norm of J, JT J will be a good approximation to the objective Hessian ∇2 F x. Under these circumstances, frequent resetting can significantly improve the convergence rate of E04USF/E04USA.
Resetting is suppressed at any iteration during which there are nonlinear constraints active.
If i≤0, the default value is used.
Start Objective Check At Variable i 1 Default =1
Stop Objective Check At Variable i 2 Default =n
Start Constraint Check At Variable i 3 Default =1
Stop Constraint Check At Variable i 4 Default =n
These keywords take effect only if Verify Level>0. They may be used to control the verification of Jacobian elements computed by user-supplied subroutines OBJFUN and CONFUN. For example, if the first 30 columns of the objective Jacobian appeared to be correct in an earlier run, so that only column 31 remains questionable, it is reasonable to specify Start Objective Check At Variable=31. If the first 30 variables appear linearly in the subfunctions, so that the corresponding Jacobian elements are constant, the above choice would also be appropriate.
If i 2 m-1≤0 or i 2 m-1>min n,i 2 m, the default value is used, for m=1,2. If i 2 m≤0 or i 2 m>n, the default value is used, for m=1,2.
Step Limit r Default =2.0
If r>0,r specifies the maximum change in variables at the first step of the linesearch. In some cases, such as F x=a e bx or F x=a xb, even a moderate change in the elements of x can lead to floating-point overflow. The parameter r is therefore used to encourage evaluation of the problem functions at meaningful points. Given any major iterate x, the first point x~ at which F and c are evaluated during the linesearch is restricted so that
x~-x 2≤r 1+x 2.
The linesearch may go on and evaluate F and c at points further from x if this will result in a lower value of the merit function (indicated by L at the end of each line of output produced by the major iterations; see Section 9.1). If L is printed for most of the iterations, r should be set to a larger value.
Wherever possible, upper and lower bounds on x should be used to prevent evaluation of nonlinear functions at wild values. The default value Step Limit=2.0 should not affect progress on well-behaved functions, but values such as 0.1 ​ or ​ 0.01 may be helpful when rapidly varying functions are present. If a small value of Step Limit is selected, a good starting point may be required. An important application is to the class of nonlinear least squares problems. If r≤0, the default value is used.
Verify Level i Default =0
Verify
Verify Constraint Gradients
Verify Gradients
Verify Objective Gradients
These keywords refer to finite difference checks on the gradient elements computed by OBJFUN and CONFUN. (Unspecified gradient elements are not checked.) The possible choices for i are the following:
i | Meaning
-1 | No checks are performed.
-0 | Only a ‘cheap’ test will be performed, requiring one call to OBJFUN.
-1 | Individual gradient elements will also be checked using a reliable (but more expensive) test.
For example, the nonlinear objective gradient (if any) will be verified if either Verify Objective Gradients or Verify Level=1 is specified. Similarly, the objective and the constraint gradients will be verified if Verify=YES or Verify Level=3 or Verify is specified.
If i=-1, no checking will be performed.
If 0≤i≤3, gradients will be verified at the first point that satisfies the linear constraints and bounds. If i=0, only a ‘cheap’ test will be performed, requiring one call to OBJFUN and (if appropriate) one call to CONFUN. If 1≤i≤3, a more reliable (but more expensive) check will be made on individual gradient elements, within the ranges specified by the Start Objective Check At Variable and Stop Objective Check At Variable keywords. A result of the form OK or BAD? is printed by E04USF/E04USA to indicate whether or not each element appears to be correct.
If 10≤i≤13, the action is the same as for i-10, except that it will take place at the user-specified initial value of x.
If i<-1 or 4≤i≤9 or i>13, the default value is used.
We suggest that Verify Level=3 be used whenever a new function routine is being developed.

13 Description of Monitoring Information

This section describes the long line of output (>80 characters) which forms part of the monitoring information produced by E04USF/E04USA. (See also the description of the optional parameters Major Print Level, Minor Print Level and Monitoring File.) You can control the level of printed output.
When Major Print Level≥5 and Monitoring File≥0, the following line of output is produced at every major iteration of E04USF/E04USA on the unit number specified by optional parameter Monitoring File. In all cases, the values of the quantities printed are those in effect on completion of the given iteration.
Maj | is the major iteration count.
Mnr is the number of minor iterations required by the feasibility and optimality phases of the QP subproblem. Generally, Mnr will be 1 in the later iterations, since theoretical analysis predicts that the correct active set will be identified near the solution (see Section 11 in E04UFF/E04UFA).
Note that Mnr may be greater than the optional parameter Minor Iteration Limit if some iterations are required for the feasibility phase.
Step | is the step αk taken along the computed search direction. On reasonably well-behaved problems, the unit step (i.e., αk=1) will be taken as the solution is approached.
Nfun | is the cumulative number of evaluations of the objective function needed for the linesearch. Evaluations needed for the estimation of the gradients by finite differences are not included. Nfun is printed as a guide to the amount of work required for the linesearch.
Merit Function is the value of the augmented Lagrangian merit function (see (12) in E04UFF/E04UFA) at the current iterate. This function will decrease at each iteration unless it was necessary to increase the penalty parameters (see Section 11.3 in E04UFF/E04UFA). As the solution is approached, Merit Function will converge to the value of the objective function at the solution.
If the QP subproblem does not have a feasible point (signified by I at the end of the current output line) then the merit function is a large multiple of the constraint violations, weighted by the penalty parameters. During a sequence of major iterations with infeasible subproblems, the sequence of Merit Function values will decrease monotonically until either a feasible subproblem is obtained or E04USF/E04USA terminates with IFAIL=3 (no feasible point could be found for the nonlinear constraints).
If there are no nonlinear constraints present (i.e., NCNLN=0) then this entry contains Objective, the value of the objective function F x. The objective function will decrease monotonically to its optimal value when there are no nonlinear constraints.
Norm Gz | is ZT gFR, the Euclidean norm of the projected gradient (see Section 11.2 in E04UFF/E04UFA). Norm Gz will be approximately zero in the neighbourhood of a solution.
Violtn | is the Euclidean norm of the residuals of constraints that are violated or in the predicted active set (not printed if NCNLN is zero). Violtn will be approximately zero in the neighbourhood of a solution.
Nz | is the number of columns of Z (see Section 11.2 in E04UFF/E04UFA). The value of Nz is the number of variables minus the number of constraints in the predicted active set; i.e., Nz=n-Bnd+Lin+Nln.
Bnd | is the number of simple bound constraints in the current working set.
Lin | is the number of general linear constraints in the current working set.
Nln | is the number of nonlinear constraints in the predicted active set (not printed if NCNLN is zero).
Penalty | is the Euclidean norm of the vector of penalty parameters used in the augmented Lagrangian merit function (not printed if NCNLN is zero).
Cond H | is a lower bound on the condition number of the Hessian approximation H.
Cond Hz | is a lower bound on the condition number of the projected Hessian approximation HZ ( HZ = ZT HFR Z = RZT RZ ; see (6) and (11) in E04UFF/E04UFA). The larger this number, the more difficult the problem.
Cond T | is a lower bound on the condition number of the matrix of predicted active constraints.
Conv is a three-letter indication of the status of the three convergence tests (2)–(4) defined in the description of the optional parameter Optimality Tolerance. Each letter is T if the test is satisfied and F otherwise. The three tests indicate whether:
(i) | the sequence of iterates has converged;
(ii) | the projected gradient (Norm Gz) is sufficiently small; and
(iii) | the norm of the residuals of constraints in the predicted active set (Violtn) is small enough.
If any of these indicators is F when E04USF/E04USA terminates with IFAIL=0, you should check the solution carefully.
M | is printed if the quasi-Newton update has been modified to ensure that the Hessian approximation is positive definite (see Section 11.4 in E04UFF/E04UFA).
I | is printed if the QP subproblem has no feasible point.
C | is printed if central differences have been used to compute the unspecified objective and constraint gradients. If the value of Step is zero then the switch to central differences was made because no lower point could be found in the linesearch. (In this case, the QP subproblem is resolved with the central difference gradient and Jacobian.) If the value of Step is nonzero then central differences were computed because Norm Gz and Violtn imply that x is close to a Kuhn–Tucker point (see Section 11.1 in E04UFF/E04UFA).
L | is printed if the linesearch has produced a relative change in x greater than the value defined by the optional parameter Step Limit. If this output occurs frequently during later iterations of the run, optional parameter Step Limit should be set to a larger value.
R | is printed if the approximate Hessian has been refactorized. If the diagonal condition estimator of R indicates that the approximate Hessian is badly conditioned then the approximate Hessian is refactorized using column interchanges. If necessary, R is modified so that its diagonal condition estimator is bounded.
E04 Chapter Contents
E04 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


E04VGF : NAG Library, Mark 26

E04 Chapter Contents
E04 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

E04VGF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
10 Example

1 Purpose

E04VGF is used to initialize the routine E04VHF.

2 Specification

SUBROUTINE E04VGF ( CW, LENCW, IW, LENIW, RW, LENRW, IFAIL)
INTEGER | LENCW, IW(LENIW), LENIW, LENRW, IFAIL
REAL (KIND=nag_wp) | RW(LENRW)
CHARACTER(8) | CW(LENCW)

3 Description

E04VGF initializes the arrays CW, IW and RW for the routine E04VHF.

4 References

None.

5 Arguments

1:   CW LENCW – CHARACTER(8) arrayCommunication Array
2:   LENCW – INTEGERInput
On entry: the dimension of the array CW as declared in the (sub)program from which E04VGF is called.
Constraint: LENCW≥600, see routine E04VHF.
3:   IW LENIW – INTEGER arrayCommunication Array
4:   LENIW – INTEGERInput
On entry: the dimension of the array IW as declared in the (sub)program from which E04VGF is called.
Constraint: LENIW≥600, see routine E04VHF.
5:   RW LENRW – REAL (KIND=nag_wp) arrayCommunication Array
6:   LENRW – INTEGERInput
On entry: the dimension of the array RW as declared in the (sub)program from which E04VGF is called.
Constraint: LENRW≥600, see routine E04VHF.
7:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
One or more of the communication array lengths LENCW, LENIW or LENRW is less than 600.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

Not applicable.

8 Parallelism and Performance

E04VGF is not threaded in any implementation.

9 Further Comments

The time taken by E04VGF is negligible.

10 Example

See Section 10 in E04VHF and E04VKF.
E04 Chapter Contents
E04 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


E04VHF : NAG Library, Mark 26

E04 Chapter Contents
E04 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

E04VHF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.
Note: this routine uses optional parameters to define choices in the problem specification and in the details of the algorithm. If you wish to use default settings for all of the optional parameters, you need only read Sections 1 to 10 of this document. If, however, you wish to reset some or all of the settings please refer to Section 11 for a detailed description of the algorithm, to Section 12 for a detailed description of the specification of the optional parameters and to Section 13 for a detailed description of the monitoring information produced by the routine.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
▸▿ 9 Further Comments
▸▿ 9.1 The Final Output
9.1.1 The ROWS section
9.1.2 The COLUMNS section
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results
▸▿ 11 Algorithmic Details
11.1 Constraints and Slack Variables
11.2 Major Iterations
11.3 Minor Iterations
11.4 The Merit Function
11.5 Treatment of Constraint Infeasibilities
▸▿ 12 Optional Parameters
12.1 Description of the Optional Parameters
▸▿ 13 Description of Monitoring Information
13.1 Major Iteration Log
13.2 Minor Iteration Log
13.3 Crash Statistics
13.4 Basis Factorization Statistics
13.5 The Solution File
13.6 The Summary File

1 Purpose

E04VHF solves sparse linear and nonlinear programming problems.

2 Specification

SUBROUTINE E04VHF ( START, NF, N, NXNAME, NFNAME, OBJADD, OBJROW, PROB, USRFUN, IAFUN, JAVAR, A, LENA, NEA, IGFUN, JGVAR, LENG, NEG, XLOW, XUPP, XNAMES, FLOW, FUPP, FNAMES, X, XSTATE, XMUL, F, FSTATE, FMUL, NS, NINF, SINF, CW, LENCW, IW, LENIW, RW, LENRW, CUSER, IUSER, RUSER, IFAIL)
INTEGER | START, NF, N, NXNAME, NFNAME, OBJROW, IAFUN(LENA), JAVAR(LENA), LENA, NEA, IGFUN(LENG), JGVAR(LENG), LENG, NEG, XSTATE(N), FSTATE(NF), NS, NINF, LENCW, IW(LENIW), LENIW, LENRW, IUSER(*), IFAIL
REAL (KIND=nag_wp) | OBJADD, A(LENA), XLOW(N), XUPP(N), FLOW(NF), FUPP(NF), X(N), XMUL(N), F(NF), FMUL(NF), SINF, RW(LENRW), RUSER(*)
CHARACTER(8) | PROB, XNAMES(NXNAME), FNAMES(NFNAME), CW(LENCW), CUSER(*)
EXTERNAL | USRFUN
Before calling E04VHF, or one of the option setting routines E04VKF, E04VLF, E04VMF or E04VNF, routine E04VGF must be called. The specification for E04VGF is:
SUBROUTINE E04VGF ( CW, LENCW, IW, LENIW, RW, LENRW, IFAIL)
INTEGER | LENCW, IW(LENIW), LENIW, LENRW, IFAIL
REAL (KIND=nag_wp) | RW(LENRW)
CHARACTER(8) | CW(LENCW)
E04VGF should be called with LENCW, LENIW and LENRW, the declared lengths of CW, IW and RW respectively, must satisfy:
  • LENCW≥600
  • LENIW≥600
  • LENRW≥600
The contents of the arrays CW, IW and RW must not be altered between calling routines E04VGF, E04VHF, E04VJF, E04VKF, E04VLF, E04VMF and E04VNF.

3 Description

E04VHF is designed to minimize a linear or nonlinear function subject to bounds on the variables and sparse linear or nonlinear constraints. It is suitable for large-scale linear and quadratic programming and for linearly constrained optimization, as well as for general nonlinear programs of the form
minimizex f 0 x   subject to ​ l ≤ x f x AL x ≤ u , (1)
where x is an n -vector of variables, l and u are constant lower and upper bounds, f 0 x is a smooth scalar objective function, AL is a sparse matrix, and f x is a vector of smooth nonlinear constraint functions fi x . The optional parameter Maximize specifies that f 0 x should be maximized instead of minimized.
Ideally, the first derivatives (gradients) of f 0 x and fi x should be known and coded by you. If only some of the gradients are known, E04VHF estimates the missing ones by finite differences.
If f 0 x is linear and f x is absent, (1) is a linear program (LP) and E04VHF applies the primal simplex method (see Dantzig (1963)). Sparse basis factors are maintained by LUSOL (see Gill et al. (1987)) as in MINOS (see Murtagh and Saunders (1995)).
If only the objective is nonlinear, the problem is linearly constrained (LC) and tends to solve more easily than the general case with nonlinear constraints (NC). For both nonlinear cases, E04VHF applies a sparse sequential quadratic programming (SQP) method (see Gill et al. (2002)), using limited-memory quasi-Newton approximations to the Hessian of the Lagrangian. The merit function for step-length control is an augmented Lagrangian, as in the dense SQP solver E04WDF (see Gill et al. (1986) and Gill et al. (1992)).
E04VHF is suitable for nonlinear problems with thousands of constraints and variables, and is most efficient if only some of the variables enter nonlinearly, or there are relatively few degrees of freedom at a solution (i.e., many constraints are active). However, there is no limit on the number of degrees of freedom.
E04VHF allows linear and nonlinear constraints and variables to be entered in an arbitrary order, and uses one subroutine to define all the nonlinear functions.
The optimization problem is assumed to be in the form
minimizex Fobj x   subject to ​ lx ≤ x ≤ ux ,   lF ≤ F x ≤ uF , (2)
where the upper and lower bounds are constant, F x is a vector of smooth linear and nonlinear constraint functions Fi x , and Fobj x is one of the components of F to be minimized, as specified by the input argument OBJROW. E04VHF reorders the variables and constraints so that the problem is in the form (1).
Upper and lower bounds are specified for all variables and functions. The j th constraint may be defined as an equality by setting lj = uj . If certain bounds are not present, the associated elements of l or u should be set to special values that are treated as -∞ or +∞. Free variables and free constraints (‘free rows’) have both bounds infinite.
In general, the components of F are structured in the sense that they are formed from sums of linear and nonlinear functions of just some of the variables. This structure can be exploited by E04VHF.
In many cases, the vector F x is a sum of linear and nonlinear functions. E04VHF allows these terms to be specified separately, so that the linear part is defined just once by the input arguments IAFUN, JAVAR and A. Only the nonlinear part is recomputed at each x .
Suppose that each component of F x is of the form
Fi x = fi x + ∑ j=1 n A ij xj ,
where fi x is a nonlinear function (possibly zero) and the elements A ij are constant. The nf by n Jacobian of F x is the sum of two sparse matrices of the same size: F′x = G x + A , where G x = f′x and A is the matrix with elements A ij . The two matrices must be non-overlapping in the sense that each element of the Jacobian F′x = G x + A comes from G x or A , but not both. The element cannot be split between G x and A .
For example, the function
F x = 3 x 1 + e x 2 x 4 + x 22 + 4 x 4 - x 3 + x 5 x 2 + x 32 + sin⁡x 4 - 3 x 5 x 1 - x 3
can be written as
F x = f x + Ax = e x 2 x 4 + x 22 + 4 x 4 x 32 + sin⁡x 4 0 + 3 x 1 - x 3 + x 5 x 2 - 3 x 5 x 1 - x 3 ,
in which case
F′x = 3 e x 2 x 4 + 2 x 2 -1 e x 2 + 4 -1 0 1 2 x 3 cos⁡x 4 -3 1 0 -1 0 -0
can be written as F′x = f′x + A = G x + A , where
G x = 0 e x 2 x 4 + 2 x 2 0 e x 2 + 4 0 0 0 2 x 3 cos⁡x 4 0 0 0 0 0 0 ,   A = 3 0 -1 0 -1 0 1 -0 0 -3 1 0 -1 0 -0 .
Note: the element e x 2+4 of F′x appears in G x and is not split between G x and A although it contains a linear term.
The nonzero elements of A and G are provided to E04VHF in coordinate form. The elements of A are entered as triples i,j,A ij in the arrays IAFUN, JAVAR and A. The sparsity pattern G is entered as pairs i,j in the arrays IGFUN and JGVAR. The corresponding entries G ij (any that are known) are assigned to appropriate array elements G k in USRFUN.
The elements of A and G may be stored in any order. Duplicate entries are ignored. IGFUN and JGVAR may be defined automatically by subroutine E04VJF when Derivative Option=0 is specified and USRFUN does not provide any gradients.
Throughout this document the symbol ε is used to represent the machine precision (see X02AJF).
E04VHF is based on SNOPTA, which is part of the SNOPT package described in Gill et al. (2005b).

4 References

Dantzig G B (1963) Linear Programming and Extensions Princeton University Press
Eldersveld S K (1991) Large-scale sequential quadratic programming algorithms PhD Thesis Department of Operations Research, Stanford University, Stanford
Fourer R (1982) Solving staircase linear programs by the simplex method Math. Programming 23 274–313
Gill P E, Murray W and Saunders M A (2002) SNOPT: An SQP Algorithm for Large-scale Constrained Optimization 12 979–1006 SIAM J. Optim.
Gill P E, Murray W and Saunders M A (2005a) Users' guide for SQOPT 7: a Fortran package for large-scale linear and quadratic programming Report NA 05-1 Department of Mathematics, University of California, San Diego http://www.ccom.ucsd.edu/~peg/papers/sqdoc7.pdf
Gill P E, Murray W and Saunders M A (2005b) Users' guide for SNOPT 7.1: a Fortran package for large-scale linear nonlinear programming Report NA 05-2 Department of Mathematics, University of California, San Diego http://www.ccom.ucsd.edu/~peg/papers/sndoc7.pdf
Gill P E, Murray W, Saunders M A and Wright M H (1986) Users' guide for NPSOL (Version 4.0): a Fortran package for nonlinear programming Report SOL 86-2 Department of Operations Research, Stanford University
Gill P E, Murray W, Saunders M A and Wright M H (1987) Maintaining LU factors of a general sparse matrix Linear Algebra and its Applics. 88/89 239–270
Gill P E, Murray W, Saunders M A and Wright M H (1992) Some theoretical properties of an augmented Lagrangian merit function Advances in Optimization and Parallel Computing (ed P M Pardalos) 101–128 North Holland
Hock W and Schittkowski K (1981) Test Examples for Nonlinear Programming Codes. Lecture Notes in Economics and Mathematical Systems 187 Springer–Verlag
Murtagh B A and Saunders M A (1978) Large-scale linearly constrained optimization 14 41–72 Math. Programming
Murtagh B A and Saunders M A (1982) A projected Lagrangian algorithm and its implementation for sparse nonlinear constraints Math. Program. Stud. 16 84–118
Murtagh B A and Saunders M A (1995) MINOS 5.4 users' guide Report SOL 83-20R Department of Operations Research, Stanford University

5 Arguments

1:   START – INTEGERInput
On entry: indicates how a starting point is to be obtained.
START=0
Requests that the Crash procedure be used, unless a Basis file is provided via optional parameters Old Basis File, Insert File or Load File.
START=1
Is the same as START=0 but is more meaningful when a Basis file is given.
START=2
Means that XSTATE and FSTATE define a valid starting point (probably from an earlier call, though not necessarily).
Constraint: START=0, 1 or 2.
2:   NF – INTEGERInput
On entry: nf, the number of problem functions in F x , including the objective function (if any) and the linear and nonlinear constraints. Upper and lower bounds on x can be defined using the arguments XLOW and XUPP and should not be included in F .
Constraint: NF>0.
3:   N – INTEGERInput
On entry: n, the number of variables.
Constraint: N>0.
4:   NXNAME – INTEGERInput
On entry: the number of names provided in the array XNAMES.
NXNAME=1
There are no names provided and generic names will be used in the output.
NXNAME=N
Names for all variables must be provided and will be used in the output.
Constraint: NXNAME=1​ or ​N.
5:   NFNAME – INTEGERInput
On entry: the number of names provided in the array FNAMES.
NFNAME=1
There are no names provided and generic names will be used in the output.
NFNAME=NF
Names for all functions must be provided and will be used in the output.
Constraint: NFNAME=1​ or ​NF.
Note: if NXNAME=1 then NFNAME must also be 1 (and vice versa). Similarly, if NXNAME=N then NFNAME must be NF (and vice versa).
6:   OBJADD – REAL (KIND=nag_wp)Input
On entry: is a constant that will be added to the objective row Fobj for printing purposes. Typically, OBJADD=0.0E+0.
7:   OBJROW – INTEGERInput
On entry: says which row of F x is to act as the objective function. If there is no such row, set OBJROW=0 . Then E04VHF will seek a feasible point such that lF ≤ F x ≤ uF and lx ≤ x ≤ ux .
Constraint: 1≤OBJROW≤NF​ or ​OBJROW=0 (or a feasible point problem).
8:   PROB – CHARACTER(8)Input
On entry: is an 8-character name for the problem. PROB is used in the printed solution and in some routines that output Basis files. A blank name may be used.
9:   USRFUN – SUBROUTINE, supplied by the user.External Procedure
USRFUN must define the nonlinear portion f x of the problem functions F x=f x + Ax , along with its gradient elements G ij x= ∂ fi x ∂ xj . (A dummy subroutine is needed even if f≡0 and all functions are linear.)
In general, USRFUN should return all function and gradient values on every entry except perhaps the last. This provides maximum reliability and corresponds to the default option setting, Derivative Option=1.
The elements of G x are stored in the array G 1:LENG in the order specified by the input arrays IGFUN and JGVAR.
In practice it is often convenient not to code gradients. E04VHF is able to estimate them by finite differences, using a call to USRFUN for each variable xj for which some ∂ fi x ∂ xj needs to be estimated. However, this reduces the reliability of the optimization algorithm, and it can be very expensive if there are many such variables xj .
As a compromise, E04VHF allows you to code as many gradients as you like. This option is implemented as follows. Just before USRFUN is called, each element of the derivative array G is initialized to a specific value. On exit, any element retaining that value must be estimated by finite differences.
Some rules of thumb follow:
(i) | for maximum reliability, compute all gradients;
(ii) | if the gradients are expensive to compute, specify optional parameter Nonderivative Linesearch and use the value of the input argument NEEDG to avoid computing them on certain entries. (There is no need to compute gradients if NEEDG=0 on entry to USRFUN.);
(iii) | if not all gradients are known, you must specify Derivative Option=0. You should still compute as many gradients as you can. (It often happens that some of them are constant or zero.);
(iv) | again, if the known gradients are expensive, don't compute them if NEEDG=0 on entry to USRFUN;
(v) | use the input argument STATUS to test for special actions on the first or last entries;
(vi) | while USRFUN is being developed, use the optional parameter Verify Level to check the computation of gradients that are supposedly known;
(vii) | USRFUN is not called until the linear constraints and bounds on x are satisfied. This helps confine x to regions where the functions fi x are likely to be defined. However, be aware of the optional parameter Minor Feasibility Tolerance if the functions have singularities on the constraint boundaries;
(viii) | set STATUS=-1 if some of the functions are undefined. The linesearch will shorten the step and try again;
(ix) | set STATUS≤-2 if you want E04VHF to stop.
The specification of USRFUN is:
SUBROUTINE USRFUN ( STATUS, N, X, NEEDF, NF, F, NEEDG, LENG, G, CUSER, IUSER, RUSER)
INTEGER | STATUS, N, NEEDF, NF, NEEDG, LENG, IUSER(*)
REAL (KIND=nag_wp) | X(N), F(NF), G(LENG), RUSER(*)
CHARACTER(8) | CUSER(*)
1:   STATUS – INTEGERInput/Output
On entry: indicates the first and last calls to USRFUN.
STATUS=0
There is nothing special about the current call to USRFUN.
STATUS=1
E04VHF is calling your subroutine for the first time. You may wish to do something special such as read data from a file.
STATUS≥2
E04VHF is calling your subroutine for the last time. This argument setting allows you to perform some additional computation on the final solution.
STATUS=2
The current X is optimal.
STATUS=3
The problem appears to be infeasible.
STATUS=4
The problem appears to be unbounded.
STATUS=5
An iterations limit was reached.
If the functions are expensive to evaluate, it may be desirable to do nothing on the last call. The first executable statement could be
 IF (STATUS .GE. 2) RETURN.
On exit: may be used to indicate that you are unable to evaluate f or its gradients at the current x . (For example, the problem functions may not be defined there.)
During the linesearch, f x is evaluated at points x=xk + α pk for various step lengths α , where f xk has already been evaluated satisfactorily. For any such x , if you set STATUS=-1 , E04VHF will reduce α and evaluate f again (closer to xk , where f xk is more likely to be defined).
If for some reason you wish to terminate the current problem, set STATUS≤-2 .
2:   N – INTEGERInput
On entry: n , the number of variables, as defined in the call to E04VHF.
3:   X N – REAL (KIND=nag_wp) arrayInput
On entry: the variables x at which the problem functions are to be calculated. The array x must not be altered.
4:   NEEDF – INTEGERInput
On entry: indicates whether F must be assigned during this call of USRFUN.
NEEDF=0
F is not required and is ignored.
NEEDF>0
The components of f x corresponding to the nonlinear part of F x must be calculated and assigned to F.
If Fi x is linear and completely defined by the i th row of A , Ai′ , then the associated value fi x is ignored and need not be assigned. However, if Fi x has a nonlinear portion fi x that happens to be zero at x , then it is still necessary to set fi x=0 . If the linear part Ai′ of a nonlinear Fi x is provided using the arrays IAFUN, JAVAR and A, then it must not be computed again as part of fi x .
To simplify the code, you may ignore the value of NEEDF and compute f x on every entry to USRFUN.
NEEDF may also be ignored with Derivative Linesearch and Derivative Option=1. In this case, NEEDF is always 1, and F must always be assigned.
5:   NF – INTEGERInput
On entry: is the length of the full vector F x=f x + Ax as defined in the call to E04VHF.
6:   F NF – REAL (KIND=nag_wp) arrayInput/Output
On entry: concerns the calculation of f x .
On exit: F contains the computed functions f x (except perhaps if NEEDF=0).
7:   NEEDG – INTEGERInput
On entry: indicates whether G must be assigned during this call of USRFUN.
NEEDG=0
G is not required and is ignored.
NEEDG>0
The partial derivatives of f x must be calculated and assigned to G. The value of G k should be ∂fi x ∂xj, where i=IGFUN k, j=JGVAR k and k=1,2,…,LENG.
8:   LENG – INTEGERInput
On entry: is the length of the coordinate arrays JGVAR and IGFUN in the call to E04VHF.
9:   G LENG – REAL (KIND=nag_wp) arrayInput/Output
On entry: concerns the calculations of the derivatives of the function f x .
On exit: contains the computed derivatives G x (unless NEEDG=0).
These derivative elements must be stored in G in exactly the same positions as implied by the definitions of arrays IGFUN and JGVAR. There is no internal check for consistency (except indirectly via the optional parameter Verify Level), so great care is essential.
10:   CUSER* – CHARACTER(8) arrayUser Workspace
USRFUN is called with the argument CUSER as supplied to E04VHF. You are free to use the array CUSER to supply information to USRFUN as an alternative to using COMMON global variables.
11:   IUSER* – INTEGER arrayUser Workspace
USRFUN is called with the argument IUSER as supplied to E04VHF. You are free to use the array IUSER to supply information to USRFUN as an alternative to using COMMON global variables.
12:   RUSER* – REAL (KIND=nag_wp) arrayUser Workspace
USRFUN is called with the argument RUSER as supplied to E04VHF. You are free to use the array RUSER to supply information to USRFUN as an alternative to using COMMON global variables.
USRFUN must either be a module subprogram USEd by, or declared as EXTERNAL in, the (sub)program from which E04VHF is called. Arguments denoted as Input must not be changed by this procedure.
10:   IAFUN LENA – INTEGER arrayInput
11:   JAVAR LENA – INTEGER arrayInput
12:   A LENA – REAL (KIND=nag_wp) arrayInput
On entry: define the coordinates i,j and values A ij of the nonzero elements of the linear part A of the function F x=f x + Ax .
In particular, NEA triples IAFUN k,JAVAR k,A k define the row and column indices i=IAFUN k and j=JAVAR k of the element A ij=A k.
The coordinates may define the elements of A in any order.
13:   LENA – INTEGERInput
On entry: the dimension of the arrays IAFUN, JAVAR and A that hold i,j,A ij as declared in the (sub)program from which E04VHF is called.
Constraint: LENA≥1.
14:   NEA – INTEGERInput
On entry: is the number of nonzero entries in A such that F x=f x + Ax .
Constraint: 0≤NEA≤LENA.
15:   IGFUN LENG – INTEGER arrayInput
16:   JGVAR LENG – INTEGER arrayInput
On entry: define the coordinates i,j of the nonzero elements of G , the nonlinear part of the derivative J x=G x + A of the function F x=f x + Ax . E04VJF may be used to define these two arrays.
The coordinates can define the elements of G in any order. However, USRFUN must define the actual elements of G in exactly the same order as defined by the coordinates IGFUN,JGVAR .
17:   LENG – INTEGERInput
On entry: the dimension of the arrays IGFUN and JGVAR that define the varying Jacobian elements i,j,G ij as declared in the (sub)program from which E04VHF is called.
Constraint: LENG≥1.
18:   NEG – INTEGERInput
On entry: the number of nonzero entries in G .
Constraint: 0≤NEG≤LENG.
19:   XLOW N – REAL (KIND=nag_wp) arrayInput
20:   XUPP N – REAL (KIND=nag_wp) arrayInput
On entry: contain the lower and upper bounds lx and ux on the variables x .
To specify a nonexistent lower bound lx j = -∞ , set XLOW j≤-bigbnd , where bigbnd is the optional parameter Infinite Bound Size. To specify a nonexistent upper bound ux j = ∞ , set XUPP j≥bigbnd.
To fix the jth variable at xj=β , where β<bigbnd, set XLOW j=XUPP j=β .
Constraint: XLOW i≤XUPP i, for i=1,2,…,N.
21:   XNAMES NXNAME – CHARACTER(8) arrayInput
On entry: the optional names for the variables.
If NXNAME=1 , XNAMES is not referenced and default names will be used for output.
If NXNAME=N , XNAMES j should contain the 8-character name of the j th variable.
22:   FLOW NF – REAL (KIND=nag_wp) arrayInput
23:   FUPP NF – REAL (KIND=nag_wp) arrayInput
On entry: contain the lower and upper bounds lF and uF on F x .
To specify a nonexistent lower bound lF i =-∞ , set FLOW i≤-bigbnd. For a nonexistent upper bound uF i =∞ , set FUPP i≥bigbnd .
To make the i th constraint an equality at Fi=β , where β < bigbnd , set FLOW i=FUPP i=β.
Constraint: FLOW i≤FUPP i, for i=1,2,…,N.
24:   FNAMES NFNAME – CHARACTER(8) arrayInput
On entry: the optional names for the problem functions.
If NFNAME=1 , FNAMES is not referenced and default names will be used for output.
If NFNAME=NF , FNAMES i should contain the 8-character name of the i th row of F .
25:   X N – REAL (KIND=nag_wp) arrayInput/Output
On entry: an initial estimate of the variables x . See the following description of XSTATE.
On exit: the final values of the variable x .
26:   XSTATE N – INTEGER arrayInput/Output
On entry: the initial state for each variable x .
If START=0 or 1 and no basis information is provided (the optional parameters Old Basis File, Insert File and Load File are all set to 0; the default) X and XSTATE must be defined.
If nothing special is known about the problem, or if there is no wish to provide special information, you may set X j=0.0, XSTATE j=0, for all j=1,2,…,N . If you set X j=XLOW j set XSTATE j=4 ; if you set X j=XUPP j then set XSTATE j=5 . In this case a Crash procedure is used to select an initial basis.
If START=0 or 1 and basis information is provided (at least one of the optional parameters Old Basis File, Insert File and Load File is nonzero) X and XSTATE need not be set.
If START=2 (Warm Start), X and XSTATE must be set (probably from a previous call). In this case XSTATE j must be 0, 1, 2 ​ or ​ 3, for j=1,2,…,N.
On exit: the final state of the variables.
XSTATE j | State of variable j | Usual value of X j
0 | nonbasic | XLOW j
1 | nonbasic | XUPP j
2 | superbasic | Between XLOW j and XUPP j
3 | basic | Between XLOW j and XUPP j
Basic and superbasic variables may be outside their bounds by as much as the optional parameter Minor Feasibility Tolerance. Note that if scaling is specified, the feasibility tolerance applies to the variables of the scaled problem. In this case, the variables of the original problem may be as much as 0.1 outside their bounds, but this is unlikely unless the problem is very badly scaled. Check the value of Primal infeasibility output to the unit number associated with the optional parameter Print File.
Very occasionally some nonbasic variables may be outside their bounds by as much as the optional parameter Minor Feasibility Tolerance, and there may be some nonbasics for which X j lies strictly between its bounds.
If NINF>0 , some basic and superbasic variables may be outside their bounds by an arbitrary amount (bounded by SINF if scaling was not used).
Constraint: 0≤XSTATE j≤5, for ​j=1,2,…,N.
27:   XMUL N – REAL (KIND=nag_wp) arrayOutput
On exit: the vector of the dual variables (Lagrange multipliers) for the simple bounds lx ≤ x ≤ ux .
28:   F NF – REAL (KIND=nag_wp) arrayInput/Output
On entry: an initial value for the problem functions F . See the following description of FSTATE.
On exit: the final values for the problem functions F (the values F at the final point X).
29:   FSTATE NF – INTEGER arrayInput/Output
On entry: the initial state for the problem functions F.
If START=0 or 1 and no basis information is provided (the optional parameters Old Basis File, Insert File and Load File are all set to 0; the default, F and FSTATE must be defined.
If nothing special is known about the problem, or if there is no wish to provide special information, you may set F i=0.0, FSTATE i=0, for all i=1,2,…,NF. Less trivially, to say that the optimal value of function F i will probably be equal to one of its bounds, set F i=FLOW i and FSTATE i=4 or F i=FUPP i and FSTATE i=5 as appropriate. In this case a Crash procedure is used to select an initial basis.
If START=0 or 1 and basis information is provided (at least one of the optional parameters Old Basis File, Insert File and Load File is nonzero), F and FSTATE need not be set.
If START=2 (Warm Start), F and FSTATE must be set (probably from a previous call). In this case FSTATE i must be 0, 1, 2 or 3, for i=1,2,…,NF.
On exit: the final state of the variables. The elements of FSTATE have the following meaning:
FSTATE i State of the corresponding
slack variable 		Usual value of F i
0 | nonbasic | FLOW i
1 | nonbasic | FUPP i
2 | superbasic | Between FLOW i and FUPP i
3 | basic | Between FLOW i and FUPP i
Basic and superbasic slack variables may lead to the corresponding functions being outside their bounds by as much as the optional parameter Minor Feasibility Tolerance.
Very occasionally some functions may be outside their bounds by as much as the optional parameter Minor Feasibility Tolerance, and there may be some nonbasics for which F i lies strictly between its bounds.
If NINF>0 , some basic and superbasic variables may be outside their bounds by an arbitrary amount (bounded by SINF if scaling was not used).
Constraint: 0≤FSTATE i≤5, for ​i=1,2,…,NF.
30:   FMUL NF – REAL (KIND=nag_wp) arrayInput/Output
On entry: an estimate of γ , the vector of Lagrange multipliers (shadow prices) for the constraints lF ≤ F x ≤ uF . All NF components must be defined. If nothing is known about γ , set FMUL i=0.0 , for i=1,2,…,NF. For warm start use the values from a previous call.
On exit: the vector of the dual variables (Lagrange multipliers) for the general constraints lF ≤ F x ≤ uF
31:   NS – INTEGERInput/Output
On entry: the number of superbasic variables. NS need not be specified for cold starts, but should retain its value from a previous call when warm start is used.
On exit: the final number of superbasic variables.
32:   NINF – INTEGEROutput
33:   SINF – REAL (KIND=nag_wp)Output
On exit: are the number and the sum of the infeasibilities of constraints that lie outside one of their bounds by more than the optional parameter Minor Feasibility Tolerance before the solution is unscaled.
If any linear constraints are infeasible, x minimizes the sum of the infeasibilities of the linear constraints subject to the upper and lower bounds being satisfied. In this case NINF gives the number of variables and linear constraints lying outside their upper or lower bounds. The nonlinear constraints are not evaluated.
Otherwise, x minimizes the sum of infeasibilities of the nonlinear constraints subject to the linear constraints and upper and lower bounds being satisfied. In this case NINF gives the number of components of F x lying outside their bounds by more than the optional parameter Minor Feasibility Tolerance. Again this is before the solution is unscaled.
34:   CW LENCW – CHARACTER(8) arrayCommunication Array
35:   LENCW – INTEGERInput
On entry: the dimension of the array CW as declared in the (sub)program from which E04VHF is called.
Constraint: LENCW≥600.
36:   IW LENIW – INTEGER arrayCommunication Array
37:   LENIW – INTEGERInput
On entry: the dimension of the array IW as declared in the (sub)program from which E04VHF is called.
Constraint: LENIW≥600.
38:   RW LENRW – REAL (KIND=nag_wp) arrayCommunication Array
39:   LENRW – INTEGERInput
On entry: the dimension of the array RW as declared in the (sub)program from which E04VHF is called.
Constraint: LENRW≥600.
40:   CUSER* – CHARACTER(8) arrayUser Workspace
41:   IUSER* – INTEGER arrayUser Workspace
42:   RUSER* – REAL (KIND=nag_wp) arrayUser Workspace
CUSER, IUSER and RUSER are not used by E04VHF, but are passed directly to USRFUN and may be used to pass information to this routine as an alternative to using COMMON global variables.
43:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, because for this routine the values of the output arguments may be useful even if IFAIL≠0 on exit, the recommended value is -1. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).
E04VHF returns with IFAIL=0 if the iterates have converged to a point x that satisfies the first-order Kuhn–Tucker (see Section 13.2) conditions to the accuracy requested by the optional parameter Major Optimality Tolerance, i.e., the projected gradient and active constraint residuals are negligible at x.
You should check whether the following four conditions are satisfied:
(i) | the final value of rgNorm (see Section 13.2) is significantly less than that at the starting point;
(ii) | during the final major iterations, the values of Step and Minors (see Section 13.1) are both one;
(iii) | the last few values of both rgNorm and SumInf (see Section 13.2) become small at a fast linear rate; and
(iv) | condHz (see Section 13.1) is small.
If all these conditions hold, x is almost certainly a local minimum of (1).
One caution about ‘Optimal solutions’. Some of the variables or slacks may lie outside their bounds more than desired, especially if scaling was requested. Max Primal infeas in the Print file (see Section 13) refers to the largest bound infeasibility and which variable is involved. If it is too large, consider restarting with a smaller Minor Feasibility Tolerance (say 10 times smaller) and perhaps Scale Option=0.
Similarly, Max Dual infeas in the Print file indicates which variable is most likely to be at a nonoptimal value. Broadly speaking, if
Max Dual infeas / Max pi = 10-d ,
then the objective function would probably change in the d th significant digit if optimization could be continued. If d seems too large, consider restarting with a smaller Major Optimality Tolerance.
Finally, Nonlinear constraint violn in the Print file shows the maximum infeasibility for nonlinear rows. If it seems too large, consider restarting with a smaller Major Feasibility Tolerance.

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Note: E04VHF may return useful information for one or more of the following detected errors or warnings.
Errors or warnings detected by the routine:
IFAIL=1
On entry, LENCW=value.
Constraint: LENCW≥600.
On entry, LENIW=value.
Constraint: LENIW≥600.
On entry, LENRW=value.
Constraint: LENRW≥600.
The initialization routine E04VGF has not been called.
IFAIL=2
Array element IGFUN value=value is out of range 1 to NF=value, or array element JGVAR value=value is out of range 1 to N=value.
Basis file dimensions do not match this problem.
On entry, bounds FLOW and FUPP for value are equal and infinite. FLOW=FUPP=value and infbnd= value.
On entry, bounds FLOW and FUPP for variable value are equal and infinite. FLOW=FUPP=value and infbnd=value.
On entry, bounds for value are inconsistent. FLOW=value and FUPP=value.
On entry, bounds for value are inconsistent. XLOW=value and XUPP=value.
On entry, bounds for variable value are inconsistent. FLOW=value and FUPP=value.
On entry, bounds for variable value are inconsistent. XLOW=value and XUPP=value.
On entry, bounds XLOW and XUPP for value are equal and infinite. XLOW=XUPP=value and infbnd=value.
On entry, bounds XLOW and XUPP for variable value are equal and infinite. XLOW=XUPP=value and infbnd=value.
On entry, LENA=value.
Constraint: LENA≥1.
On entry, LENG=value.
Constraint: LENG≥1.
On entry, N=value.
Constraint: N≥1.
On entry, NEA=value, N=value and NF=value.
Constraint: NEA≤N×NF.
On entry, NEA=value.
Constraint: NEA≥0.
On entry, NEG=value, N=value and NF=value.
Constraint: NEG≤N×NF.
On entry, NEG=value.
Constraint: NEG≥0.
On entry, NF=value.
Constraint: NF≥1.
On entry, NFNAME=value and NF=value.
Constraint: NFNAME=1 or NF.
On entry, NXNAME=value and N=value.
Constraint: NXNAME=1 or N.
On entry, OBJROW=value and NF=value.
Constraint: 0≤OBJROW≤NF.
On entry, one but not both of NXNAME and NFNAME is equal to 1. NXNAME=value and NFNAME=value.
On entry, START=value.
Constraint: START=0, 1 or 2.
IFAIL=3
The requested accuracy could not be achieved.
A feasible solution has been found, but the requested accuracy in the dual infeasibilities could not be achieved. An abnormal termination has occurred, but E04VHF is within 10-2 of satisfying the Major Optimality Tolerance. Check that the Major Optimality Tolerance is not too small.
IFAIL=4
The linear constraints appear to be infeasible.
The problem appears to be infeasible. Infeasibilites have been minimized.
The problem appears to be infeasible. Nonlinear infeasibilites have been minimized.
The problem appears to be infeasible. The linear equality constraints could not be satisfied.
When the constraints are linear, this message is based on a relatively reliable indicator of infeasibility. Feasibility is measured with respect to the upper and lower bounds on the variables and slacks. Among all the points satisfying the general constraints Ax-s=0 (see (6) and (7) in Section 11.2), there is apparently no point that satisfies the bounds on x and s . Violations as small as the Minor Feasibility Tolerance are ignored, but at least one component of x or s violates a bound by more than the tolerance.
When nonlinear constraints are present, infeasibility is much harder to recognize correctly. Even if a feasible solution exists, the current linearization of the constraints may not contain a feasible point. In an attempt to deal with this situation, when solving each QP subproblem, E04VHF is prepared to relax the bounds on the slacks associated with nonlinear rows.
If a QP subproblem proves to be infeasible or unbounded (or if the Lagrange multiplier estimates for the nonlinear constraints become large), E04VHF enters so-called ‘nonlinear elastic’ mode. The subproblem includes the original QP objective and the sum of the infeasibilities – suitably weighted using the optional parameter Elastic Weight. In elastic mode, some of the bounds on the nonlinear rows are ‘elastic’ – i.e., they are allowed to violate their specific bounds. Variables subject to elastic bounds are known as elastic variables. An elastic variable is free to violate one or both of its original upper or lower bounds. If the original problem has a feasible solution and the elastic weight is sufficiently large, a feasible point eventually will be obtained for the perturbed constraints, and optimization can continue on the subproblem. If the nonlinear problem has no feasible solution, E04VHF will tend to determine a ‘good’ infeasible point if the elastic weight is sufficiently large. (If the elastic weight were infinite, E04VHF would locally minimize the nonlinear constraint violations subject to the linear constraints and bounds.)
Unfortunately, even though E04VHF locally minimizes the nonlinear constraint violations, there may still exist other regions in which the nonlinear constraints are satisfied. Wherever possible, nonlinear constraints should be defined in such a way that feasible points are known to exist when the constraints are linearized.
IFAIL=5
The problem appears to be unbounded. The constraint violation limit has been reached.
The problem appears to be unbounded. The objective function is unbounded.
The problem appears to be unbounded (or badly scaled).
For linear problems, unboundedness is detected by the simplex method when a nonbasic variable can be increased or decreased by an arbitrary amount without causing a basic variable to violate a bound. Consider adding an upper or lower bound to the variable. Also, examine the constraints that have nonzeros in the associated column, to see if they have been formulated as intended.
Very rarely, the scaling of the problem could be so poor that numerical error will give an erroneous indication of unboundedness. Consider using the optional parameter Scale Option.
For nonlinear problems, E04VHF monitors both the size of the current objective function and the size of the change in the variables at each step. If either of these is very large (as judged by the ‘Unbounded’ optional parameters (see Section 12)), the problem is terminated and declared unbounded. To avoid large function values, it may be necessary to impose bounds on some of the variables in order to keep them away from singularities in the nonlinear functions.
The message may indicate an abnormal termination while enforcing the limit on the constraint violations. This exit implies that the objective is not bounded below in the feasible region defined by expanding the bounds by the value of the Violation Limit.
IFAIL=6
Iteration limit reached.
Major iteration limit reached.
The value of the optional parameter Superbasics Limit is too small.
Either the Iterations Limit or the Major Iterations Limit was exceeded before the required solution could be found. Check the iteration log to be sure that progress was being made. If so, and if you caused a basis file to be saved by using the optional parameter New Basis File, consider restarting the run using the optional parameter Old Basis File to see whether further progress can be made. If you have no basis file available, you might rerun the problem after increasing the optional parameters Minor Iterations Limit and/or Major Iterations Limit.
If none of the above limits have been reached, this error may mean that the problem appears to be more nonlinear than anticipated. The current set of basic and superbasic variables have been optimized as much as possible and a pricing operation (where a nonbasic variable is selected to become superbasic) is necessary to continue, but it can't continue as the number of superbasic variables has already reached the limit specified by the optional parameter Superbasics Limit. In general, raise the Superbasics Limit s by a reasonable amount, bearing in mind the storage needed for the reduced Hessian.
IFAIL=7
Numerical difficulties have been encountered and no further progress can be made.
Several circumstances could lead to this exit.
1. | USRFUN could be returning accurate function values but inaccurate gradients (or vice versa). This is the most likely cause. Study the comments given for IFAIL=8, and do your best to ensure that the coding is correct.
2. | The function and gradient values could be consistent, but their precision could be too low. For example, accidental use of a low precision data type when a higher precision was intended would lead to a relative function precision of about 10-6 instead of something like 10-15 . The default Major Optimality Tolerance of 2×10-6 would need to be raised to about 10-3 for optimality to be declared (at a rather suboptimal point). Of course, it is better to revise the function coding to obtain as much precision as economically possible.
3. If function values are obtained from an expensive iterative process, they may be accurate to rather few significant figures, and gradients will probably not be available. One should specify
  • Function Precision t
  • Major Optimality Tolerance t
but even then, if t is as large as 10-5 or 10-6 (only 5 or 6 significant figures), the same exit condition may occur. At present the only remedy is to increase the accuracy of the function calculation.
4. An LU factorization of the basis has just been obtained and used to recompute the basic variables xB , given the present values of the superbasic and nonbasic variables. A step of ‘iterative refinement’ has also been applied to increase the accuracy of xB . However, a row check has revealed that the resulting solution does not satisfy the current constraints Ax-s=0 sufficiently well.
This probably means that the current basis is very ill-conditioned. If there are some linear constraints and variables, try Scale Option=1 if scaling has not yet been used.
For certain highly structured basis matrices (notably those with band structure), a systematic growth may occur in the factor U . Consult the description of Umax and Growth in Section 13.4 and set the LU Factor Tolerance to 2.0 (or possibly even smaller, but not less than 1.0).
5. | The first factorization attempt will have found the basis to be structurally or numerically singular. (Some diagonals of the triangular matrix U were respectively zero or smaller than a certain tolerance.) The associated variables are replaced by slacks and the modified basis is refactorized, but singularity persists. This must mean that the problem is badly scaled, or the LU Factor Tolerance is too much larger than 1.0. This is highly unlikely to occur.
IFAIL=8
User-supplied function computes incorrect constraint derivatives.
User-supplied function computes incorrect objective derivatives.
A check has been made on some elements of the Jacobian as returned in the argument G of USRFUN. At least one value disagrees remarkably with its associated forward difference estimate (the relative difference between the computed and estimated values is 1.0 or more). This exit is a safeguard, since E04VHF will usually fail to make progress when the computed gradients are seriously inaccurate. In the process it may expend considerable effort before terminating with IFAIL=7.
Check the function and Jacobian computation very carefully in USRFUN. A simple omission could explain everything. If a component is very large, then give serious thought to scaling the function or the nonlinear variables.
If you feel certain that the computed Jacobian is correct (and that the forward-difference estimate is therefore wrong), you can specify Verify Level=0 to prevent individual elements from being checked. However, the optimization procedure may have difficulty.
IFAIL=9
Unable to proceed into undefined region of user-supplied function.
User-supplied function is undefined at the first feasible point.
User-supplied function is undefined at the initial point.
You have indicated that the problem functions are undefined by assigning the value STATUS=-1 on exit from USRFUN. E04VHF attempts to evaluate the problem functions closer to a point at which the functions are already known to be defined. This exit occurs if E04VHF is unable to find a point at which the functions are defined. This will occur in the case of:
– undefined functions with no recovery possible;
– undefined functions at the first point;
– undefined functions at the first feasible point; or
– undefined functions when checking derivatives.
IFAIL=10
User-supplied function requested termination.
User requested termination.
You have indicated the wish to terminate solution of the current problem by setting STATUS to a value < -1 on exit from USRFUN.
IFAIL=11
Internal error: memory allocation failed when attempting to allocate workspace sizes value, value and value. Please contact NAG.
IFAIL=12
Internal memory allocation was insufficient. Please contact NAG.
IFAIL=13
An error has occurred in the basis package. Check that arrays IAFUN, JAVAR, IGFUN and JGVAR contain values in the appropriate ranges and do not define duplicate elements of A or G. Set the optional parameter Print File and examine the output carefully for further information.
IFAIL=14
An unexpected error has occurred. Set the optional parameter Print File and examine the output carefully for further information.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

If the value of the optional parameter Major Optimality Tolerance is set to 10-d (default value=ε) and IFAIL=0 on exit, then the final value of f x should have approximately d correct significant digits.

8 Parallelism and Performance

E04VHF makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

This section describes the final output produced by E04VHF. Intermediate and other output are given in Section 13.

9.1 The Final Output

If Print File > 0 , the final output, including a listing of the status of every variable and constraint will be sent to the Print File. The following describes the output for each constraint (row) and variable (column).

9.1.1 The ROWS section

General linear constraints take the form l≤AL x≤u . The i th constraint is therefore of the form
α≤ νi x≤ β ,
where νi is the ith row of AL .
Internally, the constraints take the form AL x-s=0 , where s is the set of slack variables (which satisfy the bounds l≤s≤u ). For the ith row it is the slack variable si that is directly available and it is sometimes convenient to refer to its state. Nonlinear constraints α≤fi x+νi x≤β are treated similarly, except that the row activity and degree of infeasibility are computed directly from fi x + νi x , rather than si .
A full stop (.) is printed for any numerical value that is exactly zero.
Label | Description
Number | is the value of n+i. (This is used internally to refer to si in the intermediate output.)
Row | gives the name of the ith row.
State the state of the ith row relative to the bounds α and β . The various states possible are as follows:
LL | the row is at its lower limit, α .
UL | the row is at its upper limit, β .
EQ | the limits are the same ( α=β ).
FR | si is nonbasic and currently zero, even though it is free to take any value between its bounds α and β .
BS | si is basic.
SBS | si is superbasic.
A key is sometimes printed before State. Note that unless the optional parameter Scale Option=0 is specified, the tests for assigning a key are applied to the variables of the scaled problem.
A | Alternative optimum possible. The variable is nonbasic, but its reduced gradient is essentially zero. This means that if the variable were allowed to start moving away from its bound, there would be no change in the value of the objective function. The values of the other free variables might change, giving a genuine alternative solution. However, if there are any degenerate variables (labelled D), the actual change might prove to be zero, since one of them could encounter a bound immediately. In either case, the values of the Lagrange multipliers might also change.
D | Degenerate. The variable is basic or superbasic, but it is equal (or very close) to one of its bounds.
I | Infeasible. The variable is basic or superbasic and is currently violating one of its bounds by more than the value of the Feasibility Tolerance.
N | Not precisely optimal. The variable is nonbasic or superbasic. If the value of the reduced gradient for the variable exceeds the value of the optional parameter Major Optimality Tolerance, the solution would not be declared optimal because the reduced gradient for the variable would not be considered negligible.
Activity | is the value of νi x (or fi x + νi x for nonlinear rows) at the final iterate.
Slack Activity | is the value by which the row differs from its nearest bound. (For the free row (if any), it is set to Activity.)
Lower Limit | is α, the lower bound on the row.
Upper Limit | is β, the upper bound on the row.
Dual Activity | is the value of the dual variable πi (the Lagrange multiplier for the i th constraint). The full vector π always satisfies BT π = gB , where B is the current basis matrix and gB contains the associated gradients for the current objective function. For FP problems, πi is set to zero.
i | gives the index i of the ith row.

9.1.2 The COLUMNS section

Let the j th component of x be the variable xj and assume that it satisfies the bounds α ≤ xj ≤ β . A fullstop (.) is printed for any numerical value that is exactly zero.
Label | Description
Number | is the column number j. (This is used internally to refer to xj in the intermediate output.)
Column | gives the name of xj.
State the state of xj relative to the bounds α and β . The various states possible are as follows:
LL | xj is nonbasic at its lower limit, α .
UL | xj is nonbasic at its upper limit, β .
EQ | xj is nonbasic and fixed at the value α = β .
FR | xj is nonbasic at some value strictly between its bounds: α< xj< β .
BS | xj is basic. Usually α< xj< β .
SBS | xj is superbasic. Usually α< xj< β .
A key is sometimes printed before State. Note that unless the optional parameter Scale Option=0 is specified, the tests for assigning a key are applied to the variables of the scaled problem.
A | Alternative optimum possible. The variable is nonbasic, but its reduced gradient is essentially zero. This means that if the variable were allowed to start moving away from its bound, there would be no change in the value of the objective function. The values of the other free variables might change, giving a genuine alternative solution. However, if there are any degenerate variables (labelled D), the actual change might prove to be zero, since one of them could encounter a bound immediately. In either case, the values of the Lagrange multipliers might also change.
D | Degenerate. The variable is basic or superbasic, but it is equal (or very close) to one of its bounds.
I | Infeasible. The variable is basic or superbasic and is currently violating one of its bounds by more than the value of the Feasibility Tolerance.
N | Not precisely optimal. The variable is nonbasic or superbasic. If the value of the reduced gradient for the variable exceeds the value of the optional parameter Major Optimality Tolerance, the solution would not be declared optimal because the reduced gradient for the variable would not be considered negligible.
Activity | is the value of xj at the final iterate.
Obj Gradient | is the value of gj at the final iterate. For FP problems, gj is set to zero.
Lower Limit | is the lower bound specified for the variable. None indicates that XLOW j≤-infbnd.
Upper Limit | is the upper bound specified for the variable. None indicates that XUPP j≥infbnd.
Reduced Gradnt | is the value of the reduced gradient dj = gj - πT aj where aj is the j th column of the constraint matrix. For FP problems, dj is set to zero.
m + j | is the value of m+j.
Note that movement off a constraint (as opposed to a variable moving away from its bound) can be interpreted as allowing the entry in the Slack Activity column to become positive.
Numerical values are output with a fixed number of digits; they are not guaranteed to be accurate to this precision.

10 Example

This example is a reformulation of Problem 74 from Hock and Schittkowski (1981) and involves the minimization of the nonlinear function
f x=10-6 x 33+23×10-6 x 43+3 x 3+2 x 4
subject to the bounds
-0.55≤x 1≤ 0.55, -0.55≤x 2≤ 0.55, - 0.0 0≤x 3≤ 1200, - 0.0 0≤x 4≤ 1200,
to the nonlinear constraints
1000 sin -x 1 -0.25 + 1000 sin -x 2 -0.25 - x 3 = -894.8, 1000 sin x 1-0.25+1000 sin x 1-x 2-0.25-x 4 = -894.8, 1000 sin x 2-0.25+1000 sin x 2-x 1-0.25 = -1294.8,
and to the linear constraints
-x 1+x 2≥-0.55, -x 1-x 2≥-0.55.
The initial point, which is infeasible, is
x 0 = 0, 0, 0, 0 T ,
and f x 0=0.
The optimal solution (to five figures) is
x*=0.11887,-0.39623,679.94,1026.0 T,
and f x*=5126.4. All the nonlinear constraints are active at the solution.
The example in the document for E04VJF solves the above problem. It first calls E04VJF to determine the sparsity pattern before calling E04VHF.
The example in the document for E04VKF solves the above problem using some of the optional parameters described in Section 12.
The formulation of the problem combines the constraints and the objective into a single vector ( F ) which is split into linear part ( AL x ) and a nonlinear part ( f ). For example we could write
F = 1000 sin -x 1 - 0.25 + 1000 sin -x 2 - 0.25 - x 3 1000 sin x 1 - 0.25 + 1000 sin x 1 - x 2 - 0.25 - x 4 1000 sin x 2 - 0.25 + 1000 sin x 2 - x 1 - 0.25 -x 1 + x 2 -x 1 - x 2 10-6 x 33 + 23 × 10-6 x 43 + 3 x 3 + 2 x 4 = f + AL x
where
f = 1000 sin -x 1 - 0.25 + 1000 sin -x 2 - 0.25 1000 sin x 1 - 0.25 + 1000 sin x 1 - x 2 - 0.25 1000 sin x 2 - 0.25 + 1000 sin x 2 - x 1 - 0.25 0 0 10-6 x 33 + 23 × 10-6 x 43
and
AL = 0 0 -1 0 0 0 0 -1 0 0 0 0 -1 1 0 0 1 -1 0 0 0 0 3 2 .
The nonzero elements of AL need to be stored in the triples IAFUN k,JAVAR k,A k in any order. For example
k | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8
IAFUN k | 1 | 2 | 4 | 4 | 5 | 5 | 6 | 6
JAVAR k | 3 | 4 | 1 | 2 | 1 | 2 | 3 | 4
A k | -1 | -1 | -1 | 1 | 1 | -1 | 3 | 2
The nonlinear functions f and the Jacobian need to be supplied in USRFUN. Please note that there is no need to assign any value to f 4 or f 5 as there is no nonlinear part in F 4 or F 5 .
The nonzero entries of the Jacobian of f are
∂f 1 ∂x 1 = -1000 cos -x 1 - 0.25 ∂f 1 ∂x 2 = -1000 cos -x 2 - 0.25 ∂f 2 ∂x 1 = 1000 cos x 1 - 0.25 + 1000 cos x 1 - x 2 - 0.25 ∂f 2 ∂x 2 = -1000 cos x 1 - x 2 - 0.25 ∂f 3 ∂x 1 = -1000 cos x 2 - x 1 - 0.25 ∂f 3 ∂x 2 = 1000 cos x 2 - 0.25 + 1000 cos x 2 - x 1 - 0.25 ∂f 6 ∂x 3 = 3×10 -6 x 32 ∂f 6 ∂x 4 = 2×10 -6 x 42
So the arrays IGFUN and JGVAR must contain:
k | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8
IGFUN k | 1 | 1 | 2 | 2 | 3 | 3 | 6 | 6
JGVAR k | 1 | 2 | 1 | 2 | 1 | 2 | 3 | 4
and USRFUN must return in G k the value of ∂fi ∂xj , where i=IGFUN k and j=JGVAR k .

10.1 Program Text

Program Text (e04vhfe.f90)

10.2 Program Data

Program Data (e04vhfe.d)

10.3 Program Results

Program Results (e04vhfe.r)

Note: the remainder of this document is intended for more advanced users. Section 11 contains a detailed description of the algorithm which may be needed in order to understand Sections 12 and 13. Section 12 describes the optional parameters which may be set by calls to E04VKF, E04VLF, E04VMF and/or E04VNF. Section 13 describes the quantities which can be requested to monitor the course of the computation.

11 Algorithmic Details

Here we summarise the main features of the SQP algorithm used in E04VHF and introduce some terminology used in the description of the subroutine and its arguments. The SQP algorithm is fully described in Gill et al. (2002).

11.1 Constraints and Slack Variables

Problem (1) contains n variables in x . Let m be the number of components of f x and AL x combined. The upper and lower bounds on those terms define the general constraints of the problem. E04VHF converts the general constraints to equalities by introducing a set of slack variables s = s 1,s 2,…,sm T . For example, the linear constraint 5 ≤ 2 x 1 + 3 x 2 ≤ ∞ is replaced by 2 x 1 + 3 x 2 - s 1 = 0 together with the bounded slack 5 ≤ s 1 ≤ ∞ . The minimization problem (1) can therefore be written in the equivalent form
minimize x,s f 0 x  subject to ​ f x AL x - s = 0 ,  l ≤ x s ≤ u . (3)
The general constraints become the equalities f x - sN = 0 and AL x - sL = 0 , where sL and sN are the linear and nonlinear slacks.

11.2 Major Iterations

The basic structure of the SQP algorithm involves major and minor iterations. The major iterations generate a sequence of iterates xk that satisfy the linear constraints and converge to a point that satisfies the nonlinear constraints and the first-order conditions for optimality. At each iterate xk a QP subproblem is used to generate a search direction towards the next iterate x k+1 . The constraints of the subproblem are formed from the linear constraints AL x - sL = 0 and the linearized constraint
f xk + f′ xk x-xk - sN = 0 , (4)
where f′ xk denotes the Jacobian matrix, whose elements are the first derivatives of f x evaluated at xk . The QP constraints therefore comprise the m linear constraints
f′ xk x - sN = -f xk + f′ xk xk , AL x -sN - sL = 0 , (5)
where x and s are bounded above and below by u and l as before. If the m by n matrix A and m -vector b are defined as
A = f′ xk AL  and  b = -f xk + f′ xk xk 0 , (6)
then the QP subproblem can be written as
minimize x,s q x,xk = gkT x-xk + 12 x-xk T Hk x-xk  subject to ​ Ax - s = b ,  l ≤ x s ≤ u , (7)
where q x,xk is a quadratic approximation to a modified Lagrangian function (see Gill et al. (2002)). The matrix Hk is a quasi-Newton approximation to the Hessian of the Lagrangian. A BFGS update is applied after each major iteration. If some of the variables enter the Lagrangian linearly the Hessian will have some zero rows and columns. If the nonlinear variables appear first, then only the n 1 rows and columns of the Hessian need to be approximated, where n 1 is the number of nonlinear variables. This quantity is determined by the implicit values of the number of nonlinear objective and Jacobian variables determined after the constraints and variables are reordered.

11.3 Minor Iterations

Solving the QP subproblem is itself an iterative procedure. Here, the iterations of the QP solver E04NQF form the minor iterations of the SQP method. E04NQF uses a reduced-Hessian active-set method implemented as a reduced-gradient method. At each minor iteration, the constraints Ax-s=b are partitioned into the form
B xB + S xS + N xN = b , (8)
where the basis matrix B is square and nonsingular, and the matrices S and N are the remaining columns of A -I . The vectors xB , xS and xN are the associated basic, superbasic and nonbasic variables respectively; they are a permutation of the elements of x and s . At a QP subproblem, the basic and superbasic variables will lie somewhere between their bounds, while the nonbasic variables will normally be equal to one of their bounds. At each iteration, xS is regarded as a set of independent variables that are free to move in any desired direction, namely one that will improve the value of the QP objective (or the sum of infeasibilities). The basic variables are then adjusted in order to ensure that x,s continues to satisfy Ax-s=b . The number of superbasic variables ( nS , say) therefore indicates the number of degrees of freedom remaining after the constraints have been satisfied. In broad terms, nS is a measure of how nonlinear the problem is. In particular, nS will always be zero for LP problems.
If it appears that no improvement can be made with the current definition of B , S and N , a nonbasic variable is selected to be added to S , and the process is repeated with the value of nS increased by one. At all stages, if a basic or superbasic variable encounters one of its bounds, the variable is made nonbasic and the value of nS is decreased by one.
Associated with each of the m equality constraints Ax-s=b are the dual variables π . Similarly, each variable in x,s has an associated reduced gradient dj . The reduced gradients for the variables x are the quantities g-AT π , where g is the gradient of the QP objective, and the reduced gradients for the slacks are the dual variables π . The QP subproblem is optimal if dj≥0 for all nonbasic variables at their lower bounds, dj≤0 for all nonbasic variables at their upper bounds, and dj=0 for other variables, including superbasics. In practice, an approximate QP solution x^k,s^k,π^k is found by relaxing these conditions.

11.4 The Merit Function

After a QP subproblem has been solved, new estimates of the solution are computed using a linesearch on the augmented Lagrangian merit function
M x,s,π = f 0 x - πT f x - sN + 12 f x - sN T D f x - sN , (9)
where D is a diagonal matrix of penalty parameters D ii ≥ 0 , and π now refers to dual variables for the nonlinear constraints in (1). If xk,sk,πk denotes the current solution estimate and x^k,s^k,π^k denotes the QP solution, the linesearch determines a step αk 0<αk≤1 such that the new point
x k+1 s k+1 π k+1 = xk sk πk + αk x^k - xk s^k - sk π^k - πk (10)
gives a sufficient decrease in the merit function M. When necessary, the penalties in D are increased by the minimum-norm perturbation that ensures descent for M (see Gill et al. (1992)). The value of sN is adjusted to minimize the merit function as a function of s before the solution of the QP subproblem (see Gill et al. (1986) and Eldersveld (1991)).

11.5 Treatment of Constraint Infeasibilities

E04VHF makes explicit allowance for infeasible constraints. First, infeasible linear constraints are detected by solving the linear program
minimize x,v,w eT v+w  subject to ​ l ≤ x AL x - v + w ≤ u ,  v≥0 ,  w≥0 , (11)
where e is a vector of ones, and the nonlinear constraint bounds are temporarily excluded from l and u . This is equivalent to minimizing the sum of the general linear constraint violations subject to the bounds on x . (The sum is the ℓ 1 -norm of the linear constraint violations. In the linear programming literature, the approach is called elastic programming.)
The linear constraints are infeasible if the optimal solution of (11) has v≠0 or w≠0 . E04VHF then terminates without computing the nonlinear functions.
Otherwise, all subsequent iterates satisfy the linear constraints. (Such a strategy allows linear constraints to be used to define a region in which the functions can be safely evaluated.) E04VHF proceeds to solve nonlinear problems as given, using search directions obtained from the sequence of QP subproblems (see (7)).
If a QP subproblem proves to be infeasible or unbounded (or if the dual variables π for the nonlinear constraints become large), E04VHF enters ‘elastic’ mode and thereafter solves the problem
minimize x,v,w f 0 x + γ eT v+w  subject to ​ l ≤ x f x - v + w AL x ≤ u ,  v≥0 ,  w≥0 , (12)
where γ is a non-negative argument (the elastic weight), and f 0 x + γ eT v+w is called a composite objective (the ℓ 1 penalty function for the nonlinear constraints).
The value of γ may increase automatically by multiples of 10 if the optimal v and w continue to be nonzero. If γ is sufficiently large, this is equivalent to minimizing the sum of the nonlinear constraint violations subject to the linear constraints and bounds.
The initial value of γ is controlled by the optional parameter Elastic Weight.

12 Optional Parameters

Several optional parameters in E04VHF define choices in the problem specification or the algorithm logic. In order to reduce the number of formal arguments of E04VHF these optional parameters have associated default values that are appropriate for most problems. Therefore, you need only specify those optional parameters whose values are to be different from their default values.
The remainder of this section can be skipped if you wish to use the default values for all optional parameters.
The following is a list of the optional parameters available. A full description of each optional parameter is provided in Section 12.1.
  • Backup Basis File
  • Central Difference Interval
  • Check Frequency
  • Crash Option
  • Crash Tolerance
  • Defaults
  • Derivative Linesearch
  • Derivative Option
  • Difference Interval
  • Dump File
  • Elastic Weight
  • Expand Frequency
  • Factorization Frequency
  • Feasibility Tolerance
  • Feasible Point
  • Function Precision
  • Hessian Frequency
  • Hessian Full Memory
  • Hessian Limited Memory
  • Hessian Updates
  • Infinite Bound Size
  • Insert File
  • Iterations Limit
  • Linesearch Tolerance
  • List
  • Load File
  • LU Complete Pivoting
  • LU Density Tolerance
  • LU Factor Tolerance
  • LU Partial Pivoting
  • LU Rook Pivoting
  • LU Singularity Tolerance
  • LU Update Tolerance
  • Major Feasibility Tolerance
  • Major Iterations Limit
  • Major Optimality Tolerance
  • Major Print Level
  • Major Step Limit
  • Maximize
  • Minimize
  • Minor Feasibility Tolerance
  • Minor Iterations Limit
  • Minor Print Level
  • New Basis File
  • New Superbasics Limit
  • Nolist
  • Nonderivative Linesearch
  • Old Basis File
  • Partial Price
  • Pivot Tolerance
  • Print File
  • Print Frequency
  • Proximal Point Method
  • Punch File
  • Save Frequency
  • Scale Option
  • Scale Print
  • Scale Tolerance
  • Solution File
  • Summary File
  • Summary Frequency
  • Superbasics Limit
  • Suppress Parameters
  • System Information No
  • System Information Yes
  • Timing Level
  • Unbounded Objective
  • Unbounded Step Size
  • Verify Level
  • Violation Limit
Optional parameters may be specified by calling one, or more, of the routines E04VKF, E04VLF, E04VMF and E04VNF before a call to E04VHF.
E04VKF reads options from an external options file, with Begin and End as the first and last lines respectively and each intermediate line defining a single optional parameter. For example,
Begin
   Print Level = 5
End
The call
CALL E04VKF (ISPECS, CW, IW, RW, IFAIL)
can then be used to read the file on unit ISPECS. IFAIL=0 on successful exit. E04VKF should be consulted for a full description of this method of supplying optional parameters.
E04VLF, E04VMF and E04VNF can be called to supply options directly, one call being necessary for each optional parameter. For example,
CALL E04VLF ('Print Level = 5', CW, IW, RW, IFAIL)
E04VLF, E04VMF and E04VNF should be consulted for a full description of this method of supplying optional parameters.
All optional parameters you do not specify are set to their default values. Optional parameters you specify are unaltered by E04VHF (unless they define invalid values) and so remain in effect for subsequent calls to E04VHF, unless you alter them.

12.1 Description of the Optional Parameters

For each option, we give a summary line, a description of the optional parameter and details of constraints.
The summary line contains:
  • the keywords, where the minimum abbreviation of each keyword is underlined (if no characters of an optional qualifier are underlined, the qualifier may be omitted);
  • a parameter value, where the letters a, i and r denote options that take character, integer and real values respectively;
  • the default value, where the symbol ε is a generic notation for machine precision (see X02AJF), and εr denotes the relative precision of the objective function Function Precision, and bigbnd signifies the value of Infinite Bound Size.
Keywords and character values are case and white space insensitive.
Central Difference Interval r Default =εr 13
When Derivative Option=0, the central-difference interval r is used near an optimal solution to obtain more accurate (but more expensive) estimates of gradients. Twice as many function evaluations are required compared to forward differencing. The interval used for the j th variable is hj=r 1+ xj . The resulting derivative estimates should be accurate to O r 2 , unless the functions are badly scaled.
If you supply a value for this optional parameter, a small value between 0.0 and 1.0 is appropriate.
Check Frequency i Default =60
Every i th minor iteration after the most recent basis factorization, a numerical test is made to see if the current solution x satisfies the general linear constraints (the linear constraints and the linearized nonlinear constraints, if any). The constraints are of the form Ax-s=b , where s is the set of slack variables. To perform the numerical test, the residual vector r=b-Ax+s is computed. If the largest component of r is judged to be too large, the current basis is refactorized and the basic variables are recomputed to satisfy the general constraints more accurately. If i≤0, the value of i=99999999 is used and effectively no checks are made.
Check Frequency=1 is useful for debugging purposes, but otherwise this option should not be needed.
Crash Option i Default =3
Crash Tolerance r Default =0.1
Except on restarts, an internal Crash procedure is used to select an initial basis from certain rows and columns of the constraint matrix A -I . The Crash Option i determines which rows and columns of A are eligible initially, and how many times the Crash procedure is called. Columns of -I are used to pad the basis where necessary.
i | Meaning
0 | The initial basis contains only slack variables: B=I.
1 | The Crash procedure is called once, looking for a triangular basis in all rows and columns of A.
2 | The Crash procedure is called twice (if there are nonlinear constraints). The first call looks for a triangular basis in linear rows, and the iteration proceeds with simplex iterations until the linear constraints are satisfied. The Jacobian is then evaluated for the first major iteration and the Crash procedure is called again to find a triangular basis in the nonlinear rows (retaining the current basis for linear rows).
3 | The Crash procedure is called up to three times (if there are nonlinear constraints). The first two calls treat linear equalities and linear inequalities separately. As before, the last call treats nonlinear rows before the first major iteration.
If i≥1 , certain slacks on inequality rows are selected for the basis first. (If i≥2 , numerical values are used to exclude slacks that are close to a bound). The Crash procedure then makes several passes through the columns of A , searching for a basis matrix that is essentially triangular. A column is assigned to ‘pivot’ on a particular row if the column contains a suitably large element in a row that has not yet been assigned. (The pivot elements ultimately form the diagonals of the triangular basis.) For remaining unassigned rows, slack variables are inserted to complete the basis.
The Crash Tolerance r allows the starting Crash procedure to ignore certain ‘small’ nonzeros in each column of A . If amax is the largest element in column j , other nonzeros of a ij in the columns are ignored if a ij ≤ amax × r . (To be meaningful, r should be in the range 0≤r<1 .)
When r>0.0 , the basis obtained by the Crash procedure may not be strictly triangular, but it is likely to be nonsingular and almost triangular. The intention is to obtain a starting basis containing more columns of A and fewer (arbitrary) slacks. A feasible solution may be reached sooner on some problems.
For example, suppose the first m columns of A form the matrix shown under LU Factor Tolerance; i.e., a tridiagonal matrix with entries -1, 4, -1. To help the Crash procedure choose all m columns for the initial basis, we would specify a Crash Tolerance of r for some value of r>0.5.
Defaults
This special keyword may be used to reset all optional parameters to their default values.
Derivative Option i Default =1
Optional parameter Derivative Option specifies which nonlinear function gradients are known analytically and will be supplied to E04VHF by USRFUN.
i | Meaning
0 | Some problem derivatives are unknown.
1 | All problem derivatives are known.
The value i=1 should be used whenever possible. It is the most reliable and will usually be the most efficient.
If i=0 , E04VHF will estimate the missing components of G x using finite differences. This may simplify the coding of USRFUN. However, it could increase the total run-time substantially (since a special call to USRFUN is required for each column of the Jacobian that has a missing element), and there is less assurance that an acceptable solution will be located. If the nonlinear variables are not well scaled, it may be necessary to specify a nonstandard optional parameter Difference Interval.
For each column of the Jacobian, one call to USRFUN is needed to estimate all missing elements in that column, if any.
At times, central differences are used rather than forward differences. Twice as many calls to USRFUN are needed. (This is not under your control.)
Derivative Linesearch Default
Nonderivative Linesearch
At each major iteration a linesearch is used to improve the merit function. Optional parameter Derivative Linesearch uses safeguarded cubic interpolation and requires both function and gradient values to compute estimates of the step αk . If some analytic derivatives are not provided, or optional parameter Nonderivative Linesearch is specified, E04VHF employs a linesearch based upon safeguarded quadratic interpolation, which does not require gradient evaluations.
A nonderivative linesearch can be slightly less robust on difficult problems, and it is recommended that the default be used if the functions and derivatives can be computed at approximately the same cost. If the gradients are very expensive relative to the functions, a nonderivative linesearch may give a significant decrease in computation time.
If Nonderivative Linesearch is selected, E04VHF signals the evaluation of the linesearch by calling USRFUN with NEEDG=0. Once the linesearch is completed, the problem functions are called again with NEEDF=0 and NEEDG=0. If the potential saving provided by a nonderivative linesearch is to be realised, it is essential that USRFUN be coded so that derivatives are not computed when NEEDG=0.
Difference Interval r Default =εr
This alters the interval r used to estimate gradients by forward differences. It does so in the following circumstances:
– | in the interval (‘cheap’) phase of verifying the problem derivatives;
– | for verifying the problem derivatives;
– | for estimating missing derivatives.
In all cases, a derivative with respect to xj is estimated by perturbing that component of x to the value xj + r 1 + xj , and then evaluating Fobj x or f x at the perturbed point. The resulting gradient estimates should be accurate to O r unless the functions are badly scaled. Judicious alteration of r may sometimes lead to greater accuracy.
If you supply a value for this optional parameter, a small value between 0.0 and 1.0 is appropriate.
Dump File i 1 Default =0
Load File i 2 Default =0
Optional parameters Dump File and Load File are similar to optional parameters Punch File and Insert File, but they record solution information in a manner that is more direct and more easily modified. A full description of information recorded in optional parameters Dump File and Load File is given in Gill et al. (2005a).
If i 1>0 , the last solution obtained will be output to the file with unit number i 1 .
If i 2>0 , the Load File, containing basis information, will be read. The file will usually have been output previously as a Dump File. The file will not be accessed if optional parameters Old Basis File or Insert File are specified.
Elastic Weight r Default =104
This keyword determines the initial weight γ associated with the problem (12) (see Section 11.5).
At major iteration k , if elastic mode has not yet started, a scale factor σk=1 + g xk∞ is defined from the current objective gradient. Elastic mode is then started if the QP subproblem is infeasible, or the QP dual variables are larger in magnitude than σk r . The QP is resolved in elastic mode with γ=σk r .
Thereafter, major iterations continue in elastic mode until they converge to a point that is optimal for (12) (see Section 11.5). If the point is feasible for equation (1) v=w=0 , it is declared locally optimal. Otherwise, γ is increased by a factor of 10 and major iterations continue. If γ has already reached a maximum allowable value, equation (1) is declared locally infeasible.
Expand Frequency i Default =10000
This option is part of the anti-cycling procedure designed to make progress even on highly degenerate problems.
For linear models, the strategy is to force a positive step at every iteration, at the expense of violating the bounds on the variables by a small amount. Suppose that the optional parameter Minor Feasibility Tolerance is δ . Over a period of i iterations, the tolerance actually used by E04VHF increases from 0.5 δ to δ (in steps of 0.5 δ/i ).
For nonlinear models, the same procedure is used for iterations in which there is only one superbasic variable. (Cycling can occur only when the current solution is at a vertex of the feasible region.) Thus, zero steps are allowed if there is more than one superbasic variable, but otherwise positive steps are enforced.
Increasing i helps reduce the number of slightly infeasible nonbasic variables (most of which are eliminated during a resetting procedure). However, it also diminishes the freedom to choose a large pivot element (see optional parameter Pivot Tolerance).
Factorization Frequency i Default =50
At most i basis changes will occur between factorizations of the basis matrix.
With linear programs, the basis factors are usually updated every iteration. The default i is reasonable for typical problems. Higher values up to i=100 (say) may be more efficient on well-scaled problems.
When the objective function is nonlinear, fewer basis updates will occur as an optimum is approached. The number of iterations between basis factorizations will therefore increase. During these iterations a test is made regularly (according to the optional parameter Check Frequency) to ensure that the general constraints are satisfied. If necessary the basis will be refactorized before the limit of i updates is reached.
Function Precision r Default =ε 0.8
The relative function precision εr is intended to be a measure of the relative accuracy with which the nonlinear functions can be computed. For example, if f x is computed as 1000.56789 for some relevant x and if the first 6 significant digits are known to be correct, the appropriate value for εr would be 1.0E−6 .
Ideally the functions fi x should have magnitude of order 1. If all functions are substantially less than 1 in magnitude, εr should be the absolute precision. For example, if f x=1.23456789E−4 at some point and if the first 6 significant digits are known to be correct, the appropriate value for εr would be 1.0E−10 .)
The default value of εr is appropriate for simple analytic functions.
In some cases the function values will be the result of extensive computation, possibly involving a costly iterative procedure that can provide few digits of precision. Specifying an appropriate Function Precision may lead to savings, by allowing the linesearch procedure to terminate when the difference between function values along the search direction becomes as small as the absolute error in the values.
Hessian Full Memory Default if n 1≤75
Hessian Limited Memory Default if n 1>75
These options select the method for storing and updating the approximate Hessian. (E04VHF uses a quasi-Newton approximation to the Hessian of the Lagrangian. A BFGS update is applied after each major iteration.)
If Hessian Full Memory is specified, the approximate Hessian is treated as a dense matrix and the BFGS updates are applied explicitly. This option is most efficient when the number of variables n is not too large (say, less than 75). In this case, the storage requirement is fixed and one can expect 1-step Q-superlinear convergence to the solution.
Hessian Limited Memory should be used on problems where n is very large. In this case a limited-memory procedure is used to update a diagonal Hessian approximation Hr a limited number of times. (Updates are accumulated as a list of vector pairs. They are discarded at regular intervals after Hr has been reset to their diagonal.)
Hessian Frequency i Default =99999999
If optional parameter Hessian Full Memory is in effect and i BFGS updates have already been carried out, the Hessian approximation is reset to the identity matrix. (For certain problems, occasional resets may improve convergence, but in general they should not be necessary.)
Hessian Full Memory and Hessian Frequency=10 have a similar effect to Hessian Limited Memory and Hessian Updates=10 (except that the latter retains the current diagonal during resets).
Hessian Updates i Default =Hessian Frequency if Hessian Full Memory, 10 otherwise
If optional parameter Hessian Limited Memory is in effect and i BFGS updates have already been carried out, all but the diagonal elements of the accumulated updates are discarded and the updating process starts again.
Broadly speaking, the more updates stored, the better the quality of the approximate Hessian. However, the more vectors stored, the greater the cost of each QP iteration. The default value is likely to give a robust algorithm without significant expense, but faster convergence can sometimes be obtained with significantly fewer updates (e.g., i=5 ).
Infinite Bound Size r Default =1020
If r≥0, r defines the ‘infinite’ bound bigbnd in the definition of the problem constraints. Any upper bound greater than or equal to bigbnd will be regarded as +∞ (and similarly any lower bound less than or equal to -bigbnd will be regarded as -∞). If r<0, the default value is used.
Iterations Limit i Default = max 10000, 10 max N,NF
The value of i specifies the maximum number of minor iterations allowed (i.e., iterations of the simplex method or the QP algorithm), summed over all major iterations. (See also the description of the optional parameter Minor Iterations Limit.)
Linesearch Tolerance r Default =0.9
This tolerance, r , controls the accuracy with which a step length will be located along the direction of search each iteration. At the start of each linesearch a target directional derivative for the merit function is identified. This parameter determines the accuracy to which this target value is approximated, and it must be a value in the range 0.0≤r≤1.0 .
The default value r=0.9 requests just moderate accuracy in the linesearch.
If the nonlinear functions are cheap to evaluate, a more accurate search may be appropriate; try r=0.1 , ​ 0.01 ​ or ​ 0.001 .
If the nonlinear functions are expensive to evaluate, a less accurate search may be appropriate. If all gradients are known, try r=0.99 . (The number of major iterations might increase, but the total number of function evaluations may decrease enough to compensate.)
If not all gradients are known, a moderately accurate search remains appropriate. Each search will require only 1–5 function values (typically), but many function calls will then be needed to estimate missing gradients for the next iteration.
LU Density Tolerance r 1 Default =0.6
LU Singularity Tolerance r 2 Default =ε 23
The density tolerance, r 1 , is used during LU factorization of the basis matrix B. Columns of L and rows of U are formed one at a time, and the remaining rows and columns of the basis are altered appropriately. At any stage, if the density of the remaining matrix exceeds r 1 , the Markowitz strategy for choosing pivots is terminated, and the remaining matrix is factored by a dense LU procedure. Raising the density tolerance towards 1.0 may give slightly sparser LU factors, with a slight increase in factorization time.
The singularity tolerance, r 2 , helps guard against ill-conditioned basis matrices. After B is refactorized, the diagonal elements of U are tested as follows: if u jj ≤ r 2 or u jj < r 2 maxi u ij , the j th column of the basis is replaced by the corresponding slack variable. (This is most likely to occur after a restart.)
LU Factor Tolerance r 1 Default =3.99
LU Update Tolerance r 2 Default =3.99
The values of r 1 and r 2 affect the stability of the basis factorization B=LU, during refactorization and updates respectively. The lower triangular matrix L is a product of matrices of the form
1 0 μ 1
where the multipliers μ will satisfy μ≤ri. The default values of r 1 and r 2 usually strike a good compromise between stability and sparsity. They must satisfy r 1, r 2≥1.0.
For large and relatively dense problems, r 1=10.0​ or ​5.0 (say) may give a useful improvement in stability without impairing sparsity to a serious degree.
For certain very regular structures (e.g., band matrices) it may be necessary to reduce r 1​ and/or ​r 2 in order to achieve stability. For example, if the columns of A include a sub-matrix of the form
4 -1 -1 4 -1 -1 4 -1 … … … -1 4 -1 -1 4 ,
one should set both r 1 and r 2 to values in the range 1.0≤ri<4.0.
LU Partial Pivoting Default
LU Complete Pivoting
LU Rook Pivoting
The LU factorization implements a Markowitz-type search for pivots that locally minimize the fill-in subject to a threshold pivoting stability criterion. The default option is to use threshhold partial pivoting. The optional parameters LU Rook Pivoting and LU Complete Pivoting are more expensive than partial pivoting but are more stable and better at revealing rank, as long as LU Factor Tolerance is not too large (say <2.0). When numerical difficulties are encountered, E04VHF automatically reduces the LU tolerance towards 1.0 and switches (if necessary) to rook or complete pivoting, before reverting to the default or specified options at the next refactorization (with System Information Yes, relevant messages are output to the Print File).
Major Feasibility Tolerance r Default = max 10-6,ε
This tolerance, r , specifies how accurately the nonlinear constraints should be satisfied. The default value is appropriate when the linear and nonlinear constraints contain data to about that accuracy.
Let vmax be the maximum nonlinear constraint violation, normalized by the size of the solution, which is required to satisfy
vmax=maxi vi ​ ​/​ ​ x ≤ r , (13)
where vi is the violation of the i th nonlinear constraint, for i=1,2,…,NF.
In the major iteration log (see Section 13.2), vmax appears as the quantity labelled ‘Feasible’. If some of the problem functions are known to be of low accuracy, a larger Major Feasibility Tolerance may be appropriate.
Major Optimality Tolerance r Default =2 max 10-6,ε
This tolerance, r , specifies the final accuracy of the dual variables. On successful termination, E04VHF will have computed a solution x,s,π such that
cmax=maxj cj ​ ​/​ ​ π ≤ r , (14)
where cj is an estimate of the complementarity slackness for variable j , for j=1,2,…,n+nf. The values ci are computed from the final QP solution using the reduced gradients dj=gj - πT aj (where gj is the j th component of the objective gradient, aj is the associated column of the constraint matrix A -I , and π is the set of QP dual variables):
cj = - dj min xj - lj ,1 if ​ dj≥0 ; -dj min uj - xj ,1 if ​ dj<0 . (15)
In the Print File, cmax appears as the quantity labelled ‘Optimal’.
Major Iterations Limit i Default = max 1000, 3 max n,nf
This is the maximum number of major iterations allowed. It is intended to guard against an excessive number of linearizations of the constraints. If i=0, optimality and feasibility are checked.
Major Print Level i Default =1
This controls the amount of output to the optional parameters Print File and Summary File at each major iteration. Major Print Level=0 suppresses most output, except for error messages. Major Print Level=1 gives normal output for linear and nonlinear problems, and Major Print Level=11 gives additional details of the Jacobian factorization that commences each major iteration.
In general, the value being specified may be thought of as a binary number of the form
Major Print Level JFDXbs
where each letter stands for a digit that is either 0 or 1 as follows:
s | a single line that gives a summary of each major iteration. (This entry in JFDXbs is not strictly binary since the summary line is printed whenever JFDXbs ≥ 1 );
b | basis statistics, i.e., information relating to the basis matrix whenever it is refactorized. (This output is always provided if JFDXbs ≥ 10 );
X | xk , the nonlinear variables involved in the objective function or the constraints. These appear under the heading ‘Jacobian variables’;
D | πk , the dual variables for the nonlinear constraints. These appear under the heading ‘Multiplier estimates’;
F | f xk , the values of the nonlinear constraint functions;
J | J xk , the Jacobian matrix. This appears under the heading ‘x and Jacobian’.
To obtain output of any items JFDXbs , set the corresponding digit to 1, otherwise to 0.
If J=1 , the Jacobian matrix will be output column-wise at the start of each major iteration. Column j will be preceded by the value of the corresponding variable xj and a key to indicate whether the variable is basic, superbasic or nonbasic. (Hence if J=1 , there is no reason to specify X=1 unless the objective contains more nonlinear variables than the Jacobian.) A typical line of output is
 3 1.250000E+01 BS 1 1.00000E+00 4 2.00000E+00
which would mean that x 3 is basic at value 12.5, and the third column of the Jacobian has elements of 1.0 and 2.0 in rows 1 and 4.
Major Step Limit r Default =2.0
This parameter limits the change in x during a linesearch. It applies to all nonlinear problems, once a ‘feasible solution’ or ‘feasible subproblem’ has been found.
1. | A linesearch determines a step α over the range 0<α≤β , where β is 1 if there are nonlinear constraints or is the step to the nearest upper or lower bound on x if all the constraints are linear. Normally, the first step length tried is α 1 = min 1,β .
2. | In some cases, such as f x=a e bx or f x=a xb , even a moderate change in the components of x can lead to floating-point overflow. The parameter r is therefore used to define a limit β-=r 1+x / p (where p is the search direction), and the first evaluation of f x is at the potentially smaller step length α 1 = min 1,β-,β .
3. | Wherever possible, upper and lower bounds on x should be used to prevent evaluation of nonlinear functions at meaningless points. The optional parameter Major Step Limit provides an additional safeguard. The default value r=2.0 should not affect progress on well behaved problems, but setting r=0.1​ or ​0.01 may be helpful when rapidly varying functions are present. A ‘good’ starting point may be required. An important application is to the class of nonlinear least squares problems.
4. | In cases where several local optima exist, specifying a small value for r may help locate an optimum near the starting point.
Minimize Default
Maximize
Feasible Point
The keywords Minimize and Maximize specify the required direction of optimization. It applies to both linear and nonlinear terms in the objective.
The keyword Feasible Point means ‘Ignore the objective function, while finding a feasible point for the linear and nonlinear constraints’. It can be used to check that the nonlinear constraints are feasible without altering the call to E04VHF.
Minor Feasibility Tolerance r Default = max 10-6,ε
Feasibility Tolerance r Default = max 10-6,ε
E04VHF tries to ensure that all variables eventually satisfy their upper and lower bounds to within this tolerance, r . This includes slack variables. Hence, general linear constraints should also be satisfied to within r .
Feasibility with respect to nonlinear constraints is judged by the optional parameter Major Feasibility Tolerance (not by r ).
If the bounds and linear constraints cannot be satisfied to within r , the problem is declared infeasible. If SINF is quite small, it may be appropriate to raise r by a factor of 10 or 100. Otherwise, some error in the data should be suspected.
Nonlinear functions will be evaluated only at points that satisfy the bounds and linear constraints. If there are regions where a function is undefined, every attempt should be made to eliminate these regions from the problem.
For example, if f x=x 1 + log x 2 , it is essential to place lower bounds on both variables. If r=1.0E−6 , the bounds x 1 ≥ 10-5 and x 2 ≥ 10-4 might be appropriate. (The log singularity is more serious. In general, keep x as far away from singularities as possible.)
If Scale Option ≥ 1 , feasibility is defined in terms of the scaled problem (since it is then more likely to be meaningful).
In reality, E04VHF uses r as a feasibility tolerance for satisfying the bounds on x and s in each QP subproblem. If the sum of infeasibilities cannot be reduced to zero, the QP subproblem is declared infeasible. E04VHF is then in elastic mode thereafter (with only the linearized nonlinear constraints defined to be elastic). See the description of the optional parameter Elastic Weight.
Minor Iterations Limit i Default =500
If the number of minor iterations for the optimality phase of the QP subproblem exceeds i , then all nonbasic QP variables that have not yet moved are frozen at their current values and the reduced QP is solved to optimality.
Note that more than i minor iterations may be necessary to solve the reduced QP to optimality. These extra iterations are necessary to ensure that the terminated point gives a suitable direction for the linesearch.
In the major iteration log (see Section 13.2) a t at the end of a line indicates that the corresponding QP was artificially terminated using the limit i .
Compare with the optional parameter Iterations Limit, which defines an independent absolute limit on the total number of minor iterations (summed over all QP subproblems).
Minor Print Level i Default =1
This controls the amount of output to the Print File and Summary File during solution of the QP subproblems. The value of i has the following effect:
i | Meaning
0 | No minor iteration output except error messages.
≥1 | A single line of output at each minor iteration (controlled by optional parameters Print Frequency and Summary Frequency.
≥10 | Basis factorization statistics generated during the periodic refactorization of the basis (see the optional parameter Factorization Frequency). Statistics for the first factorization each major iteration are controlled by the optional parameter Major Print Level.
New Basis File i 1 Default =0
Backup Basis File i 2 Default =0
Save Frequency i 3 Default =100
New Basis File and Backup Basis File are sometimes referred to as basis maps. They contain the most compact representation of the state of each variable. They are intended for restarting the solution of a problem at a point that was reached by an earlier run. For nontrivial problems, it is advisable to save basis maps at the end of a run, in order to restart the run if necessary.
If i 1>0 , a basis map will be saved in the file associated with unit i 1 every i 3 th iteration. The first record of the file will contain the word PROCEEDING if the run is still in progress. A basis map will also be saved at the end of a run, with some other word indicating the final solution status.
Use of i 2>0 is intended as a safeguard against losing the results of a long run. Suppose that a New Basis File is being saved every 100 (Save Frequency) iterations, and that E04VHF is about to save such a basis at iteration 2000. It is conceivable that the run may be interrupted during the next few milliseconds (in the middle of the save). In this case the Basis file will be corrupted and the run will have been essentially wasted.
To eliminate this risk, both a New Basis File and a Backup Basis File may be specified. The following would be suitable for the above example:
Backup Basis File 11
New Basis File 12
The current basis will then be saved every 100 iterations, first in the file associated with unit 12 and then immediately in the file associated with unit 11. If the run is interrupted at iteration 2000 during the save in the file associated with unit 12, there will still be a usable basis in the file associated with unit 11 (corresponding to iteration 1900).
Note that a new basis will be saved in New Basis File at the end of a run if it terminates normally, but it will not be saved in Backup Basis File. In the above example, if an optimum solution is found at iteration 2050 (or if the iteration limit is 2050), the final basis in the file associated with unit 12 will correspond to iteration 2050, but the last basis saved in the file associated with unit 11 will be the one for iteration 2000.
A full description of information recorded in New Basis File and Backup Basis File is given in Gill et al. (2005a).
New Superbasics Limit i Default =99
This option causes early termination of the QP subproblems if the number of free variables has increased significantly since the first feasible point. If the number of new superbasics is greater than i , the nonbasic variables that have not yet moved are frozen and the resulting smaller QP is solved to optimality.
In the major iteration log (see Section 13.1), a t at the end of a line indicates that the QP was terminated early in this way.
Nolist Default
List
For E04VHF, normally each optional parameter specification is printed as it is supplied. Optional parameter Nolist may be used to suppress the printing and optional parameter List may be used to turn on printing.
Old Basis File i Default =0
If i>0 , the basis maps information will be obtained from this file. The file will usually have been output previously as a New Basis File or Backup Basis File. A full description of information recorded in New Basis File and Backup Basis File is given in Gill et al. (2005a).
The file will not be acceptable if the number of rows or columns in the problem has been altered.
Partial Price i Default =1
This parameter is recommended for large problems that have significantly more variables than constraints. It reduces the work required for each ‘pricing’ operation (where a nonbasic variable is selected to become superbasic). When i=1 , all columns of the constraint matrix A -I are searched. Otherwise, A and I are partitioned to give i roughly equal segments Aj and Ij , for j=1,2,…,i. If the previous pricing search was successful on A j-1 and I j-1 , the next search begins on the segments Aj and Ij . (All subscripts here are modulo i .) If a reduced gradient is found that is larger than some dynamic tolerance, the variable with the largest such reduced gradient (of appropriate sign) is selected to become superbasic. If nothing is found, the search continues on the next segments A j+1 and I j+1 , and so on.
For time-stage models having t time periods, Partial Price t (or t/2 or t/3 ) may be appropriate.
Pivot Tolerance r Default =ε 23
During the solution of QP subproblems, the pivot tolerance is used to prevent columns entering the basis if they would cause the basis to become almost singular.
When x changes to x+αp for some search direction p , a ‘ratio test’ determines which component of x reaches an upper or lower bound first. The corresponding element of p is called the pivot element. Elements of p are ignored (and therefore cannot be pivot elements) if they are smaller than the pivot tolerance r .
It is common for two or more variables to reach a bound at essentially the same time. In such cases, the Minor Feasibility Tolerance (say, t ) provides some freedom to maximize the pivot element and thereby improve numerical stability. Excessively small values of t should therefore not be specified. To a lesser extent, the Expand Frequency (say, f ) also provides some freedom to maximize the pivot element. Excessively large values of f should therefore not be specified.
Print File i Default =0
If i>0 , the following information is output to a file associated with unit i during the solution of each problem:
– | a listing of the optional parameters;
– | some statistics about the problem;
– | the amount of storage available for the LU factorization of the basis matrix;
– | notes about the initial basis resulting from a Crash procedure or a Basis file;
– | the iteration log;
– | basis factorization statistics;
– | the exit IFAIL condition and some statistics about the solution obtained;
– | the printed solution, if requested.
These items are described in Sections 9 and 13. Further brief output may be directed to the Summary File.
Print Frequency i Default =100
If i>0 , one line of the iteration log will be printed every i th iteration. A value such as i=10 is suggested for those interested only in the final solution. If i≤0, the value of i=99999999 is used and effectively no checks are made.
Proximal Point Method i Default =1
i=1​ or ​2 specifies minimization of x-x 0 1 or 12 x-x 0 22 when the starting point x 0 is changed to satisfy the linear constraints (where x 0 refers to nonlinear variables).
Punch File i 1 Default =0
Insert File i 2 Default =0
The Punch File from a previous run may be used as an Insert File for a later run on the same problem. A full description of information recorded in Insert File and Punch File is given in Gill et al. (2005a).
If i 1>0 , the final solution obtained will be output to the file. For linear programs, this format is compatible with various commercial systems.
If i 2>0 the Insert File containing basis information will be read from unit i 2 . The file will usually have been output previously as a Punch File. The file will not be accessed if Old Basis File is specified.
Scale Option i Default =0
Scale Tolerance r Default =0.9
Scale Print
Three scale options are available as follows:
i | Meaning
0 | No scaling. This is recommended if it is known that x and the constraint matrix never have very large elements (say, larger than 100).
1 | The constraints and variables are scaled by an iterative procedure that attempts to make the matrix coefficients as close as possible to 1.0 (see Fourer (1982)). This will sometimes improve the performance of the solution procedures.
2 | The constraints and variables are scaled by the iterative procedure. Also, a certain additional scaling is performed that may be helpful if the right-hand side b or the solution x is large. This takes into account columns of A -I that are fixed or have positive lower bounds or negative upper bounds.
Optional parameter Scale Tolerance affects how many passes might be needed through the constraint matrix. On each pass, the scaling procedure computes the ratio of the largest and smallest nonzero coefficients in each column:
ρj=maxj a ij / mini a ij   a ij ≠ 0 .
If maxj ρj is less than r times its previous value, another scaling pass is performed to adjust the row and column scales. Raising r from 0.9 to 0.99 (say) usually increases the number of scaling passes through A . At most 10 passes are made. The value of r should lie in the range 0<r<1.
Scale Print causes the row scales r i and column scales c j to be printed to Print File, if System Information Yes has been specified. The scaled matrix coefficients are a- ij = a ij c j / r i, and the scaled bounds on the variables and slacks are l-j = lj / c j , u-j = uj / c j , where c j = r j-n if j>n.
Solution File i Default =0
If i>0 , the final solution will be output to file i (whether optimal or not). All numbers are printed in 1pe16.6 format.
To see more significant digits in the printed solution, it will sometimes be useful to make i refer to Print File.
Summary File i 1 Default =0
Summary Frequency i 2 Default =100
If i 1>0 , a brief log will be output to the file associated with unit i 1 , including one line of information every i 2 th iteration. In an interactive environment, it is useful to direct this output to the terminal, to allow a run to be monitored online. (If something looks wrong, the run can be manually terminated.) Further details are given in Section 13.6.
Superbasics Limit i Default = n 1
This option places a limit on the storage allocated for superbasic variables. Ideally, i should be set slightly larger than the ‘number of degrees of freedom’ expected at an optimal solution.
For nonlinear problems, the number of degrees of freedom is often called the ‘number of independent variables’. Normally, i need not be greater than n+1 , where n 1 is the number of nonlinear variables. For many problems, i may be considerably smaller than n. This will save storage if n is very large.
Suppress Parameters
Normally E04VHF prints the options file as it is being read, and then prints a complete list of the available keywords and their final values. The optional parameter Suppress Parameters tells E04VHF not to print the full list.
System Information No Default
System Information Yes
This option prints additional information on the progress of major and minor iterations, and Crash statistics. See Section 13.
Timing Level i Default =0
If i>0 , some timing information will be output to the Print file, if Print File>0.
Unbounded Objective r 1 Default =1.0E+15
Unbounded Step Size r 2 Default =infbnd
These parameters are intended to detect unboundedness in nonlinear problems. During a linesearch, Fobj is evaluated at points of the form x+αp , where x and p are fixed and α varies. If Fobj exceeds r 1 or α exceeds r 2 , iterations are terminated with the exit message IFAIL=5.
If singularities are present, unboundedness in Fobj x may be manifested by a floating-point overflow (during the evaluation of Fobj x+αp ), before the test against r 1 can be made.
Unboundedness in x is best avoided by placing finite upper and lower bounds on the variables.
Verify Level i Default =0
This option refers to finite difference checks on the derivatives computed by the user-supplied routines. Derivatives are checked at the first point that satisfies all bounds and linear constraints.
i | Meaning
0 | Only a ‘cheap’ test will be performed, requiring two calls to USRFUN.
1 | Individual gradients will be checked (with a more reliable test). A key of the form OK or Bad? indicates whether or not each component appears to be correct.
2 | Individual columns of the problem Jacobian will be checked.
3 | Options 2 and 1 will both occur (in that order).
-1 | Derivative checking is disabled.
Verify Level=3 should be specified whenever a new USRFUN is being developed.
Violation Limit r Default =1.0E+6
This keyword defines an absolute limit on the magnitude of the maximum constraint violation, r , after the linesearch. On completion of the linesearch, the new iterate x k+1 satisfies the condition
vi x k+1 ≤ r ​ ​ max 1, vi x 0 ,
where x 0 is the point at which the nonlinear constraints are first evaluated and vi x is the i th nonlinear constraint violation vi x = max 0, li - fi x , fi x - ui .
The effect of this violation limit is to restrict the iterates to lie in an expanded feasible region whose size depends on the magnitude of r . This makes it possible to keep the iterates within a region where the objective is expected to be well-defined and bounded below. If the objective is bounded below for all values of the variables, then r may be any large positive value.

13 Description of Monitoring Information

E04VHF produces monitoring information, statistical information and information about the solution. Section 9.1 contains details of the final output information sent to the unit specified by the optional parameter Print File. This section contains other details of output information.

13.1 Major Iteration Log

This section describes the output to unit Print File if Major Print Level > 0 . One line of information is output every k th major iteration, where k is Print Frequency.
Label | Description
Itns | is the cumulative number of minor iterations.
Major | is the current major iteration number.
Minors | is the number of iterations required by both the feasibility and optimality phases of the QP subproblem. Generally, Minors will be 1 in the later iterations, since theoretical analysis predicts that the correct active set will be identified near the solution (see Section 11).
Step | is the step length α taken along the current search direction p . The variables x have just been changed to x + α p . On reasonably well-behaved problems, the unit step will be taken as the solution is approached.
nCon | the number of times USRFUN has been called to evaluate the nonlinear problem functions. Evaluations needed for the estimation of the derivatives by finite differences are not included. nCon is printed as a guide to the amount of work required for the linesearch.
Feasible is the value of vmax (see (13)), the maximum component of the scaled nonlinear constraint residual (see optional parameter Major Feasibility Tolerance). The solution is regarded as acceptably feasible if Feasible is less than the Major Feasibility Tolerance. In this case, the entry is contained in parentheses.
If the constraints are linear, all iterates are feasible and this entry is not printed.
Optimal | is the value of cmax (see (14)), the maximum complementary gap (see optional parameter Major Optimality Tolerance). It is an estimate of the degree of nonoptimality of the reduced costs. Both Feasible and Optimal are small in the neighbourhood of a solution.
MeritFunction is the value of the augmented Lagrangian merit function (see (8)). This function will decrease at each iteration unless it was necessary to increase the penalty parameters (see Section 11.4). As the solution is approached, MeritFunction will converge to the value of the objective at the solution.
In elastic mode, the merit function is a composite function involving the constraint violations weighted by the elastic weight.
If the constraints are linear, this item is labelled Objective, the value of the objective function. It will decrease monotonically to its optimal value.
L+U is the number of nonzeros representing the basis factors L and U on completion of the QP subproblem.
If nonlinear constraints are present, the basis factorization B = LU is computed at the start of the first minor iteration. At this stage, L+U = lenL+lenU , where lenL (see Section 13.4) is the number of subdiagonal elements in the columns of a lower triangular matrix and lenU (see Section 13.4) is the number of diagonal and superdiagonal elements in the rows of an upper-triangular matrix.
As columns of B are replaced during the minor iterations, L+U may fluctuate up or down but, in general, will tend to increase. As the solution is approached and the minor iterations decrease towards zero, L+U will reflect the number of nonzeros in the LU factors at the start of the QP subproblem.
If the constraints are linear, refactorization is subject only to the Factorization Frequency, and L+U will tend to increase between factorizations.
BSwap | is the number of columns of the basis matrix B that were swapped with columns of S to improve the condition of B . The swaps are determined by an LU factorization of the rectangular matrix BS = B S T with stability being favoured more than sparsity.
nS | is the current number of superbasic variables.
condHz is an estimate of the condition number of RT R , itself an estimate of ZT HZ , the reduced Hessian of the Lagrangian. The condition number is the square of the ratio of the largest and smallest diagonals of the upper triangular matrix R , this being a lower bound on the condition number of RT R . condHz gives a rough indication of whether or not the optimization procedure is having difficulty. If ε is the relative machine precision being used, the SQP algorithm will make slow progress if condHz becomes as large as ε-1/2 ≈ 108 , and will probably fail to find a better solution if condHz reaches ε-3/4 ≈ 1012 .
To guard against high values of condHz, attention should be given to the scaling of the variables and the constraints. In some cases it may be necessary to add upper or lower bounds to certain variables to keep them a reasonable distance from singularities in the nonlinear functions or their derivatives.
Penalty | is the Euclidean norm of the vector of penalty parameters used in the augmented Lagrangian merit function (not printed if there are no nonlinear constraints).
The summary line may include additional code characters that indicate what happened during the course of the major iteration. These will follow the separator ‘_’ in the output
Label | Description
c | central differences have been used to compute the unknown components of the objective and constraint gradients. A switch to central differences is made if either the linesearch gives a small step, or x is close to being optimal. In some cases, it may be necessary to re-solve the QP subproblem with the central difference gradient and Jacobian.
d | during the linesearch it was necessary to decrease the step in order to obtain a maximum constraint violation conforming to the value of the optional parameter Violation Limit.
D | you set STATUS=-1 on exit from USRFUN, indicating that the linesearch needed to be done with a smaller value of the step length α.
l | the norm wise change in the variables was limited by the value of the optional parameter Major Step Limit. If this output occurs repeatedly during later iterations, it may be worthwhile increasing the value of the optional parameter Major Step Limit.
i | if E04VHF is not in elastic mode, an i signifies that the QP subproblem is infeasible. This event triggers the start of nonlinear elastic mode, which remains in effect for all subsequent iterations. Once in elastic mode, the QP subproblems are associated with the elastic problem (12) (see Section 11.5). If E04VHF is already in elastic mode, an i indicates that the minimizer of the elastic subproblem does not satisfy the linearized constraints. (In this case, a feasible point for the usual QP subproblem may or may not exist.)
M | an extra evaluation of the problem functions was needed to define an acceptable positive definite quasi-Newton update to the Lagrangian Hessian. This modification is only done when there are nonlinear constraints.
m | this is the same as M except that it was also necessary to modify the update to include an augmented Lagrangian term.
n | no positive definite BFGS update could be found. The approximate Hessian is unchanged from the previous iteration.
R | the approximate Hessian has been reset by discarding all but the diagonal elements. This reset will be forced periodically by the Hessian Frequency and Hessian Updates keywords. However, it may also be necessary to reset an ill-conditioned Hessian from time to time.
r | the approximate Hessian was reset after ten consecutive major iterations in which no BFGS update could be made. The diagonals of the approximate Hessian are retained if at least one update has been done since the last reset. Otherwise, the approximate Hessian is reset to the identity matrix.
s | a self-scaled BFGS update was performed. This update is used when the Hessian approximation is diagonal, and hence always follows a Hessian reset.
t | the minor iterations were terminated because of the Minor Iterations Limit.
T | the minor iterations were terminated because of the New Superbasics Limit.
u | the QP subproblem was unbounded.
w | a weak solution of the QP subproblem was found.
z | the Superbasics Limit was reached.

13.2 Minor Iteration Log

If Minor Print Level > 0 , one line of information is output to the Print file every k th minor iteration, where k is the specified Print Frequency. A heading is printed before the first such line following a basis factorization. The heading contains the items described below. In this description, a pricing operation is the process by which a nonbasic variable is selected to become superbasic (in addition to those already in the superbasic set). The selected variable is denoted by jq. Variable jq often becomes basic immediately. Otherwise it remains superbasic, unless it reaches its opposite bound and returns to the nonbasic set.
If Partial Price is in effect, variable jq is selected from App or Ipp , the pp th segments of the constraint matrix A -I .
Label | Description
Itn | the current iteration number.
LPmult or QPmult | is the reduced cost (or reduced gradient) of the variable jq selected by the pricing procedure at the start of the present iteration. Algebraically, the reduced gradient is dj = gj - πT aj for j = jq , where gj is the gradient of the current objective function, π is the vector of dual variables for the QP subproblem, and aj is the j th column of A -I . Note that the reduced cost is the 1-norm of the reduced-gradient vector at the start of the iteration, just after the pricing procedure.
LPstep or QPstep | is the step length α taken along the current search direction p . The variables x have just been changed to x + α p . Write Step to stand for LPStep or QPStep, depending on the problem. If a variable is made superbasic during the current iteration ( +SBS>0 ), Step will be the step to the nearest bound. During Phase 2, the step can be greater than one only if the reduced Hessian is not positive definite.
nInf | is the number of infeasibilities after the present iteration. This number will not increase unless the iterations are in elastic mode.
SumInf | is the sum of infeasibilities after the present iteration, if nInf>0. The value usually decreases at each nonzero Step, but if it decreases by 2 or more, SumInf may occasionally increase.
rgNorm | is the norm of the reduced-gradient vector at the start of the iteration. (It is the norm of the vector with elements dj for variables j in the superbasic set.) During Phase 2 this norm will be approximately zero after a unit step. (The heading is not printed if the problem is linear.)
LPobjective or QPobjective | the QP objective function after the present iteration. In elastic mode, the heading is changed to Elastic QPobj. In either case, the value printed decreases monotonically.
+SBS | is the variable jq selected by the pricing operation to be added to the superbasic set.
-SBS | is the superbasic variable chosen to become nonbasic.
-BS | is the basis variable removed (if any) to become nonbasic.
Pivot | if column aq replaces the r th column of the basis B , Pivot is the r th element of a vector y satisfying By=aq . Wherever possible, Step is chosen to avoid extremely small values of Pivot (since they cause the basis to be nearly singular). In rare cases, it may be necessary to increase the Pivot Tolerance to exclude very small elements of y from consideration during the computation of Step.
L+U | is the number of nonzeros representing the basis factors L and U . Immediately after a basis factorization B=LU , L+U is lenL+lenU, the number of subdiagonal elements in the columns of a lower triangular matrix and the number of diagonal and superdiagonal elements in the rows of an upper-triangular matrix. Further nonzeros are added to L when various columns of B are later replaced. As columns of B are replaced, the matrix U is maintained explicitly (in sparse form). The value of L will steadily increase, whereas the value of U may fluctuate up or down. Thus the value of L+U may fluctuate up or down (in general, it will tend to increase).
ncp | is the number of compressions required to recover storage in the data structure for U . This includes the number of compressions needed during the previous basis factorization.
nS | is the current number of superbasic variables. (The heading is not printed if the problem is linear.)
condHz | see Section 13.1. (The heading is not printed if the problem is linear.)

13.3 Crash Statistics

If Major Print Level ≥ 10 and System Information Yes has been specified, the following items are output to the Print file when START=0 and no Basis file is loaded. They refer to the number of columns that the Crash procedure selects during selected passes through A while searching for a triangular basis matrix.
Label | Description
Slacks | is the number of slacks selected initially.
Free cols | is the number of free columns in the basis.
Preferred | is the number of ‘preferred’ columns in the basis (i.e., XSTATE j=3 for some j≤n ).
Unit | is the number of unit columns in the basis.
Double | is the number of columns in the basis containing 2 nonzeros.
Triangle | is the number of triangular columns in the basis.
Pad | is the number of slacks used to pad the basis (to make it a nonsingular triangle).

13.4 Basis Factorization Statistics

If Major Print Level ≥ 10 , the first seven items listed below are output to the Print file whenever the basis B or the rectangular matrix BS = B S T is factorized before solution of the next QP subproblem (see Section 12.1).
Note that BS may be factorized at the start of just some of the major iterations. It is immediately followed by a factorization of B itself.
Gaussian elimination is used to compute a sparse LU factorization of B or BS , where PL PT and PUQ are lower and upper triangular matrices, for some permutation matrices P and Q . Stability is ensured as described under optional parameter LU Factor Tolerance.
If Minor Print Level ≥ 10 , the same items are printed during the QP solution whenever the current B is factorized. In addition, if System Information Yes has been specified, the entries from Elems onwards are also printed.
Label | Description
Factor | the number of factorizations since the start of the run.
Demand a code giving the reason for the present factorization, as follows:
Code | Meaning
0 | First LU factorization.
1 | The number of updates reached the Factorization Frequency.
2 | The nonzeros in the updated factors have increased significantly.
7 | Not enough storage to update factors.
10 | Row residuals are too large (see the description of the optional parameter Check Frequency).
11 | Ill-conditioning has caused inconsistent results.
Itn | is the current minor iteration number.
Nonlin | is the number of nonlinear variables in the current basis B .
Linear | is the number of linear variables in B .
Slacks | is the number of slack variables in B .
B, BR, BS or BT factorize is the type of LU factorization.
B | periodic factorization of the basis B .
BR | more careful rank-revealing factorization of B using threshold rook pivoting. This occurs mainly at the start, if the first basis factors seem singular or ill-conditioned. Followed by a normal B factorize.
BS | BS is factorized to choose a well-conditioned B from the current B S . Followed by a normal B factorize.
BT | same as BS except the current B is tried first and accepted if it appears to be not much more ill-conditioned than after the previous BS factorize.
m | is the number of rows in B or BS .
n | is the number of columns in B or BS . Preceded by ‘=’ or ‘>’ respectively.
Elems | is the number of nonzero elements in B or BS .
Amax | is the largest nonzero in B or BS .
Density | is the percentage nonzero density of B or BS .
Merit/MerRP/MerCP | Merit is the average Markowitz merit count for the elements chosen to be the diagonals of PUQ . Each merit count is defined to be c-1 r-1 where c and r are the number of nonzeros in the column and row containing the element at the time it is selected to be the next diagonal. Merit is the average of n such quantities. It gives an indication of how much work was required to preserve sparsity during the factorization. If LU Complete Pivoting or LU Rook Pivoting has been selected, this heading is changed to MerCP, respectively MerRP.
lenL | is the number of nonzeros in L .
L+U | is the number of nonzeros representing the basis factors L and U . Immediately after a basis factorization B=LU , this is lenL+lenU, the number of subdiagonal elements in the columns of a lower triangular matrix and the number of diagonal and superdiagonal elements in the rows of an upper-triangular matrix. Further nonzeros are added to L when various columns of B are later replaced. As columns of B are replaced, the matrix U is maintained explicitly (in sparse form). The value of L will steadily increase, whereas the value of U may fluctuate up or down. Thus the value of L+U may fluctuate up or down (in general, it will tend to increase).
Cmpressns | is the number of times the data structure holding the partially factored matrix needed to be compressed to recover unused storage. Ideally this number should be zero. If it is more than 3 or 4, the amount of workspace available to E04VHF should be increased for efficiency.
Incres | is the percentage increase in the number of nonzeros in L and U relative to the number of nonzeros in B or BS .
Utri | is the number of triangular rows of B or BS at the top of U .
lenU | the number of nonzeros in U , including its diagonals.
Ltol | is the largest subdiagonal element allowed in L . This is the specified LU Factor Tolerance or a smaller value that is currently being used for greater stability.
Umax | the maximum nonzero element in U .
Ugrwth is the ratio Umax/Amax , which ideally should not be substantially larger than 10.0 or 100.0. If it is orders of magnitude larger, it may be advisable to reduce the LU Factor Tolerance to 5.0, 4.0, 3.0 or 2.0, say (but bigger than 1.0).
As long as Lmax is not large (say 5.0 or less), max Amax,Umax / DUmin gives an estimate of the condition number B . If this is extremely large, the basis is nearly singular. Slacks are used to replace suspect columns of B and the modified basis is refactored.
Ltri | is the number of triangular columns of B or BS at the left of L .
dense1 | is the number of columns remaining when the density of the basis matrix being factorized reached 0.3.
Lmax | is the actual maximum subdiagonal element in L (bounded by Ltol).
Akmax | is the largest nonzero generated at any stage of the LU factorization. (Values much larger than Amax indicate instability.) Akmax is not printed if LU Partial Pivoting is selected.
Agrwth | is the ratio Akmax/Amax . Values much larger than 100 (say) indicate instability. Agrwth is not printed if LU Partial Pivoting is selected.
bump | is the size of the block to be factorized nontrivially after the triangular rows and columns of B or BS have been removed.
dense2 | is the number of columns remaining when the density of the basis matrix being factorized reached 0.6. (The Markowitz pivot strategy searches fewer columns at that stage.)
DUmax | is the largest diagonal of PUQ .
DUmin | is the smallest diagonal of PUQ .
condU | the ratio DUmax/DUmin , which estimates the condition number of U (and of B if Ltol is less than 5.0, say).

13.5 The Solution File

At the end of a run, the final solution may be output as a Solution file, according to Solution File. Some header information appears first to identify the problem and the final state of the optimization procedure. A ROWS section and a COLUMNS section then follow, giving one line of information for each row and column. The format used is similar to certain commercial systems, though there is no industry standard.
In general, numerical values are output with format f16.5. The maximum record length is 111 characters, including the first (carriage-control) character.
To reduce clutter, a full stop (.) is printed for any numerical value that is exactly zero. The values ±1 are also printed specially as 1.0 and -1.0 . Infinite bounds ( ± 1020 or larger) are printed as None.
A Solution file is intended to be read from disk by a self-contained program that extracts and saves certain values as required for possible further computation. Typically, the first 14 records would be ignored. Each subsequent record may be read using
format(i8, 2x, 2a4, 1x, a1, 1x, a3, 5e16.6, i7)
adapted to suit the occasion. The end of the ROWS section is marked by a record that starts with a 1 and is otherwise blank. If this and the next 4 records are skipped, the COLUMNS section can then be read under the same format. (There should be no need for backspace statements.)
A full description of the ROWS section and the COLUMNS section is given in Sections 9.1.1 and 9.1.2.

13.6 The Summary File

If Summary File > 0 , the following information is output to the unit number associated with Summary File. (It is a brief summary of the output directed to unit Print File):
– | the optional parameters supplied via the option setting routines, if any;
– | the Basis file loaded, if any;
– | a brief major iteration log (see Section 13.1);
– | a brief minor iteration log (see Section 13.2);
– | the exit condition, IFAIL;
– | a summary of the final iterate.
E04 Chapter Contents
E04 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


E04VJF : NAG Library, Mark 26

E04 Chapter Contents
E04 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

E04VJF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

E04VJF may be used before E04VHF to determine the sparsity pattern for the Jacobian.

2 Specification

SUBROUTINE E04VJF ( NF, N, USRFUN, IAFUN, JAVAR, A, LENA, NEA, IGFUN, JGVAR, LENG, NEG, X, XLOW, XUPP, CW, LENCW, IW, LENIW, RW, LENRW, CUSER, IUSER, RUSER, IFAIL)
INTEGER | NF, N, IAFUN(LENA), JAVAR(LENA), LENA, NEA, IGFUN(LENG), JGVAR(LENG), LENG, NEG, LENCW, IW(LENIW), LENIW, LENRW, IUSER(*), IFAIL
REAL (KIND=nag_wp) | A(LENA), X(N), XLOW(N), XUPP(N), RW(LENRW), RUSER(*)
CHARACTER(8) | CW(LENCW), CUSER(*)
EXTERNAL | USRFUN

3 Description

When using E04VHF, if you set the optional parameter Derivative Option=0 and USRFUN provides none of the derivatives, you may need to call E04VJF to determine the input arrays IAFUN, JAVAR, A, IGFUN and JGVAR. These arrays define the pattern of nonzeros in the Jacobian matrix. A typical sequence of calls could be
CALL E04VGF (CW, LENCW, ... )
CALL E04VJF (NF, N, ... )
CALL E04VLF ('Derivative Option = 0', CW, ... )
CALL E04VHF (START, NF, ... )
E04VJF determines the sparsity pattern for the Jacobian and identifies the constant elements automatically. To do so, E04VJF approximates the problem functions, F x , at three random perturbations of the given initial point x . If an element of the approximate Jacobian is the same at all three points, then it is taken to be constant. If it is zero, it is taken to be identically zero. Since the random points are not chosen close together, the heuristic will correctly classify the Jacobian elements in the vast majority of cases. In general, E04VJF finds that the Jacobian can be permuted to the form:
G x A 3 A 2 A 4 ,
where A 2 , A 3 and A 4 are constant. Note that G x might contain elements that are also constant, but E04VJF must classify them as nonlinear. This is because E04VHF ‘removes’ linear variables from the calculation of F by setting them to zero before calling USRFUN. A knowledgeable user would be able to move such elements from F x in USRFUN and enter them as part of IAFUN, JAVAR and A for E04VHF.

4 References

Hock W and Schittkowski K (1981) Test Examples for Nonlinear Programming Codes. Lecture Notes in Economics and Mathematical Systems 187 Springer–Verlag

5 Arguments

Note: all optional parameters are described in detail in Section 12.1 in E04VHF.
1:   NF – INTEGERInput
On entry: nf, the number of problem functions in F x , including the objective function (if any) and the linear and nonlinear constraints. Simple upper and lower bounds on x can be defined using the arguments XLOW and XUPP and should not be included in F .
Constraint: NF>0.
2:   N – INTEGERInput
On entry: n, the number of variables.
Constraint: N>0.
3:   USRFUN – SUBROUTINE, supplied by the user.External Procedure
USRFUN must define the problem functions F x . This subroutine is passed to E04VJF as the external argument USRFUN.
The specification of USRFUN is:
SUBROUTINE USRFUN ( STATUS, N, X, NEEDF, NF, F, NEEDG, LENG, G, CUSER, IUSER, RUSER)
INTEGER | STATUS, N, NEEDF, NF, NEEDG, LENG, IUSER(*)
REAL (KIND=nag_wp) | X(N), F(NF), G(LENG), RUSER(*)
CHARACTER(8) | CUSER(*)
1:   STATUS – INTEGERInput/Output
On entry: indicates the first call to USRFUN.
STATUS=0
There is nothing special about the current call to USRFUN.
STATUS=1
E04VJF is calling your subroutine for the first time. Some data may need to be input or computed and saved.
On exit: may be used to indicate that you are unable to evaluate F at the current x . (For example, the problem functions may not be defined there).
E04VJF evaluates F x at random perturbation of the initial point x , say xp . If the functions cannot be evaluated at xp , you can set STATUS=-1 , E04VJF will use another random perturbation.
If for some reason you wish to terminate the current problem, set STATUS≤-2 .
2:   N – INTEGERInput
On entry: n , the number of variables, as defined in the call to E04VJF.
3:   X N – REAL (KIND=nag_wp) arrayInput
On entry: the variables x at which the problem functions are to be calculated. The array x must not be altered.
4:   NEEDF – INTEGERInput
On entry: indicates if F must be assigned during the call to USRFUN (see F).
5:   NF – INTEGERInput
On entry: nf, the number of problem functions.
6:   F NF – REAL (KIND=nag_wp) arrayInput/Output
On entry: this will be set by E04VJF.
On exit: the computed F x according to the setting of NEEDF.
If NEEDF=0 , F is not required and is ignored.
If NEEDF > 0 , the components of F x must be calculated and assigned to F. E04VJF will always call USRFUN with NEEDF>0 .
To simplify the code, you may ignore the value of NEEDF and compute F x on every entry to USRFUN.
7:   NEEDG – INTEGERInput
On entry: E04VJF will call USRFUN with NEEDG=0 to indicate that G is not required.
8:   LENG – INTEGERInput
On entry: the dimension of the array G as declared in the (sub)program from which E04VJF is called.
9:   G LENG – REAL (KIND=nag_wp) arrayInput/Output
On entry: concerns the calculations of the derivatives of the function f x .
On exit: E04VJF will always call USRFUN with NEEDG=0 : G is not required to be set on exit but must be declared correctly.
10:   CUSER* – CHARACTER(8) arrayUser Workspace
11:   IUSER* – INTEGER arrayUser Workspace
12:   RUSER* – REAL (KIND=nag_wp) arrayUser Workspace
USRFUN is called with the arguments CUSER, IUSER and RUSER as supplied to E04VJF. You are free to use the arrays CUSER, IUSER and RUSER to supply information to USRFUN as an alternative to using COMMON global variables.
USRFUN must either be a module subprogram USEd by, or declared as EXTERNAL in, the (sub)program from which E04VJF is called. Arguments denoted as Input must not be changed by this procedure.
4:   IAFUN LENA – INTEGER arrayOutput
5:   JAVAR LENA – INTEGER arrayOutput
6:   A LENA – REAL (KIND=nag_wp) arrayOutput
On exit: define the coordinates i,j and values A ij of the nonzero elements of the linear part A of the function F x=f x + Ax .
In particular, NEA triples IAFUN k,JAVAR k,A k define the row and column indices i=IAFUN k and j=JAVAR k of the element A ij=A k .
7:   LENA – INTEGERInput
On entry: the dimension of the arrays IAFUN, JAVAR and A that hold i,j,A ij as declared in the (sub)program from which E04VJF is called. LENA should be an overestimate of the number of elements in the linear part of the Jacobian.
Constraint: LENA≥1.
8:   NEA – INTEGEROutput
On exit: is the number of nonzero entries in A such that F x=f x + Ax .
9:   IGFUN LENG – INTEGER arrayOutput
10:   JGVAR LENG – INTEGER arrayOutput
On exit: define the coordinates i,j of the nonzero elements of G , the nonlinear part of the derivatives J x=G x + A of the function F x=f x + Ax .
11:   LENG – INTEGERInput
On entry: the dimension of the arrays IGFUN and JGVAR that define the varying Jacobian elements i,j,G ij as declared in the (sub)program from which E04VJF is called. LENG should be an overestimate of the number of elements in the nonlinear part of the Jacobian.
Constraint: LENG≥1.
12:   NEG – INTEGEROutput
On exit: the number of nonzero entries in G .
13:   X N – REAL (KIND=nag_wp) arrayInput
On entry: an initial estimate of the variables x . The contents of x will be used by E04VJF in the call of USRFUN, and so each element of X should be within the bounds given by XLOW and XUPP.
14:   XLOW N – REAL (KIND=nag_wp) arrayInput
15:   XUPP N – REAL (KIND=nag_wp) arrayInput
On entry: contain the lower and upper bounds lx and ux on the variables x .
To specify a nonexistent lower bound lx j =-∞ , set XLOW j ≤ -bigbnd , where bigbnd is the optional parameter Infinite Bound Size. To specify a nonexistent upper bound XUPP j ≥ bigbnd .
To fix the j th variable (say, xj=β , where β < bigbnd ), set XLOW j=XUPP j=β .
16:   CW LENCW – CHARACTER(8) arrayCommunication Array
17:   LENCW – INTEGERInput
On entry: the dimension of the array CW as declared in the (sub)program from which E04VJF is called.
Constraint: LENCW≥600.
18:   IW LENIW – INTEGER arrayCommunication Array
19:   LENIW – INTEGERInput
On entry: the dimension of the array IW as declared in the (sub)program from which E04VJF is called.
Constraint: LENIW≥600.
20:   RW LENRW – REAL (KIND=nag_wp) arrayCommunication Array
21:   LENRW – INTEGERInput
On entry: the dimension of the array RW as declared in the (sub)program from which E04VJF is called.
Constraint: LENRW≥600.
22:   CUSER* – CHARACTER(8) arrayUser Workspace
23:   IUSER* – INTEGER arrayUser Workspace
24:   RUSER* – REAL (KIND=nag_wp) arrayUser Workspace
CUSER, IUSER and RUSER are not used by E04VJF, but are passed directly to USRFUN and may be used to pass information to this routine as an alternative to using COMMON global variables.
25:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, LENCW=value.
Constraint: LENCW≥600.
On entry, LENIW=value.
Constraint: LENIW≥600.
On entry, LENRW=value.
Constraint: LENRW≥600.
The initialization routine E04VGF has not been called.
IFAIL=2
On entry, LENA=value.
Constraint: LENA≥1.
On entry, LENG=value.
Constraint: LENG≥1.
IFAIL=3
User-supplied routine USRFUN indicates that functions are undefined near given point X.
You have indicated that the problem functions are undefined by setting STATUS=-1 on exit from USRFUN. This exit occurs if E04VJF is unable to find a point at which the functions are defined.
IFAIL=4
User-supplied routine USRFUN requested termination.
You have indicated the wish to terminate the call to E04VJF by setting STATUS to a value <-1 on exit from USRFUN.
IFAIL=5
Either LENA or LENG is too small. Increase both of them and corresponding array sizes. LENA=value and LENG=value.
IFAIL=6
Cannot estimate Jacobian structure at given point X.
IFAIL=7
Internal error: memory allocation failed when attempting to allocate workspace sizes value, value and value. Please contact NAG.
IFAIL=8
Internal memory allocation was insufficient. Please contact NAG.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

Not applicable.

8 Parallelism and Performance

E04VJF makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

None.

10 Example

This example shows how to call E04VJF to determine the sparsity pattern of the Jacobian before calling E04VHF to solve a sparse nonlinear programming problem without providing the Jacobian information in USRFUN.
It is a reformulation of Problem 74 from Hock and Schittkowski (1981) and involves the minimization of the nonlinear function
f x = 10-6 x 33 + 23 × 10-6 x 43+3 x 3+2 x 4
subject to the bounds
-0.55≤x 1≤ 0.55, -0.55≤x 2≤ 0.55, 0≤x 3≤ 1200, 0≤x 4≤ 1200,
to the nonlinear constraints
1000 sin-x 1-0.25+1000 sin-x 2-0.25-x 3 = -894.8, 1000 sin x 1-0.25+1000 sin x 1-x 2-0.25-x 4 = -894.8, 1000 sin x 2-0.25+1000 sin x 2-x 1-0.25 = -1294.8,
and to the linear constraints
-x 1+x 2≥-0.55, -x 1-x 2≥-0.55.
The initial point, which is infeasible, is
x 0 = 0, 0, 0, 0 T ,
and f x 0=0.
The optimal solution (to five figures) is
x*=0.11887,-0.39623,679.94,1026.0 T,
and f x*=5126.4. All the nonlinear constraints are active at the solution.
The formulation of the problem combines the constraints and the objective into a single vector ( F ).
F = 1000 sin -x 1 - 0.25 + 1000 sin -x 2 - 0.25 - x 3 1000 sin x 1 - 0.25 + 1000 sin x 1 - x 2 - 0.25 - x 4 1000 sin x 2 - 0.25 + 1000 sin x 2 - x 1 - 0.25 -x 1 + x 2 x 1 - x 2 10-6 x 33 + 23 × 10-6 x 43 + 3 x 3 + 2 x 4

10.1 Program Text

Program Text (e04vjfe.f90)

10.2 Program Data

Program Data (e04vjfe.d)

10.3 Program Results

Program Results (e04vjfe.r)

E04 Chapter Contents
E04 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


E04VKF : NAG Library, Mark 26

E04 Chapter Contents
E04 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

E04VKF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

E04VKF may be used to supply optional parameters to E04VHF from an external file. The initialization routine E04VGF must have been called before calling E04VKF.

2 Specification

SUBROUTINE E04VKF ( ISPECS, CW, IW, RW, IFAIL)
INTEGER | ISPECS, IW(*), IFAIL
REAL (KIND=nag_wp) | RW(*)
CHARACTER(8) | CW(*)

3 Description

E04VKF may be used to supply values for optional parameters to E04VHF. E04VKF reads an external file and each line of the file defines a single optional parameter. It is only necessary to supply values for those arguments whose values are to be different from their default values.
Each optional parameter is defined by a single character string consisting of one or more items. The items associated with a given option must be separated by spaces, or equals signs =. Alphabetic characters may be upper or lower case. The string
Print Level = 1
is an example of a string used to set an optional parameter. For each option the string contains one or more of the following items:
– | a mandatory keyword.
– | a phrase that qualifies the keyword.
– | a number that specifies an integer or real value. Such numbers may be up to 16 contiguous characters in Fortran's I, F, E or D formats, terminated by a space if this is not the last item on the line.
Blank strings and comments are ignored. A comment begins with an asterisk (*) and all subsequent characters in the string are regarded as part of the comment.
The file containing the options must start with Begin and must finish with End. An example of a valid options file is:
Begin * Example options file
   Print level = 5
End
Optional parameter settings are preserved following a call to E04VHF and so the keyword Defaults is provided to allow you to reset all the optional parameters to their default values before a subsequent call to E04VHF.
A complete list of optional parameters, their abbreviations, synonyms and default values is given in Section 12 in E04VHF.

4 References

None.

5 Arguments

1:   ISPECS – INTEGERInput
On entry: the unit number of the option file to be read.
Constraint: ISPECS is a valid unit open for reading.
2:   CW* – CHARACTER(8) arrayCommunication Array
Note: the dimension of the array CW must be at least LENCW (see E04VGF).
3:   IW* – INTEGER arrayCommunication Array
Note: the dimension of the array IW must be at least LENIW (see E04VGF).
4:   RW* – REAL (KIND=nag_wp) arrayCommunication Array
Note: the dimension of the array RW must be at least LENRW (see E04VGF).
5:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
The initialization routine E04VGF has not been called.
IFAIL=2
At least one line of the options file is invalid.
Could not read options file on unit ISPECS =value.
Could not read options file on unit ISPECS. This may be due to:
(a) | ISPECS is not a valid unit number;
(b) | a file is not associated with unit ISPECS, or if it is, is unavailable for read access;
(c) | one or more lines of the options file is invalid. Check that all keywords are neither ambiguous nor misspelt;
(d) | Begin was found, but end-of-file was found before End was found;
(e) | end-of-file was found before Begin was found.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

Not applicable.

8 Parallelism and Performance

E04VKF is not threaded in any implementation.

9 Further Comments

E04VLF, E04VMF or E04VNF may also be used to supply optional parameters to E04VHF.

10 Example

This example solves the same problem as the example in the document for E04VHF, but sets and reads some optional parameters first. See Section 10 in E04VHF for further details.
The example in the document for E04VJF also solves the same problem (see Section 10 in E04VJF), but it first calls E04VJF to determine the sparsity pattern before calling E04VKF.

10.1 Program Text

Program Text (e04vkfe.f90)

10.2 Program Data

Program Options (e04vkfe.opt)

Program Data (e04vkfe.d)

10.3 Program Results

Program Results (e04vkfe.r)

E04 Chapter Contents
E04 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


E04VLF : NAG Library, Mark 26

E04 Chapter Contents
E04 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

E04VLF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
10 Example

1 Purpose

E04VLF may be used to supply individual optional parameters to E04VHF. The initialization routine E04VGF must have been called before calling E04VLF.

2 Specification

SUBROUTINE E04VLF ( STRING, CW, IW, RW, IFAIL)
INTEGER | IW(*), IFAIL
REAL (KIND=nag_wp) | RW(*)
CHARACTER(*) | STRING
CHARACTER(8) | CW(*)

3 Description

E04VLF may be used to supply values for optional parameters to E04VHF. It is only necessary to call E04VLF for those arguments whose values are to be different from their default values. One call to E04VLF sets one argument value.
Each optional parameter is defined by a single character string, of up to 72 characters, consisting of one or more items. The items associated with a given option must be separated by spaces, or equals signs =. Alphabetic characters may be upper or lower case. The string
Print Level = 1
is an example of a string used to set an optional parameter. For each option the string contains one or more of the following items:
– | a mandatory keyword;
– | a phrase that qualifies the keyword;
– | a number that specifies an integer or real value. Such numbers may be up to 40 contiguous characters in Fortran's I, F, E or D formats, terminated by a space if this is not the last item on the line.
For E04VLF, each user-specified option is not normally printed as it is defined, but this printing may be turned on using the keyword List. Thus the statement
CALL E04VLF ('List', CW, IW, RW, IFAIL)
turns on printing of this and subsequent options. Printing may be turned off again using the keyword Nolist.
Optional parameter settings are preserved following a call to E04VHF and so the keyword Defaults is provided to allow you to reset all the optional parameters to their default values before a subsequent call to E04VHF.
A complete list of optional parameters, their abbreviations, synonyms and default values is given in Section 12 in E04VHF.

4 References

None.

5 Arguments

1:   STRING – CHARACTER(*)Input
On entry: a single valid option string (see Section 3 in E04VLF and Section 12 in E04VHF).
2:   CW* – CHARACTER(8) arrayCommunication Array
Note: the dimension of the array CW must be at least LENCW (see E04VGF).
3:   IW* – INTEGER arrayCommunication Array
Note: the dimension of the array IW must be at least LENIW (see E04VGF).
4:   RW* – REAL (KIND=nag_wp) arrayCommunication Array
Note: the dimension of the array RW must be at least LENRW (see E04VGF).
5:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
The initialization routine E04VGF has not been called.
IFAIL=2
The supplied option is invalid. Check that the keywords are neither ambiguous nor misspelt.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

Not applicable.

8 Parallelism and Performance

E04VLF is not threaded in any implementation.

9 Further Comments

E04VKF, E04VMF or E04VNF may also be used to supply optional parameters to E04VHF.

10 Example

See Section 10 in E04VKF.
E04 Chapter Contents
E04 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


E04VMF : NAG Library, Mark 26

E04 Chapter Contents
E04 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

E04VMF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
10 Example

1 Purpose

E04VMF may be used to supply individual integer optional parameters to E04VHF. The initialization routine E04VGF must have been called before calling E04VMF.

2 Specification

SUBROUTINE E04VMF ( STRING, IVALUE, CW, IW, RW, IFAIL)
INTEGER | IVALUE, IW(*), IFAIL
REAL (KIND=nag_wp) | RW(*)
CHARACTER(*) | STRING
CHARACTER(8) | CW(*)

3 Description

E04VMF may be used to supply values for integer optional parameters to E04VHF. It is only necessary to call E04VMF for those arguments whose values are to be different from their default values. One call to E04VMF sets one argument value.
Each integer optional parameter is defined by a single character string in STRING and the corresponding value in IVALUE. For example, the following allows the iteration limit to be defined:
ITNLIM = 1000
IF (M > 500) ITNLIM = 500
CALL E04VMF ('Major Iterations', ITNLIM, CW, IW, RW, IFAIL)
Optional parameter settings are preserved following a call to E04VHF and so the keyword Defaults is provided to allow you to reset all the optional parameters to their default values before a subsequent call to E04VHF.
A complete list of optional parameters, their abbreviations, synonyms and default values is given in Section 12 in E04VHF.

4 References

None.

5 Arguments

1:   STRING – CHARACTER(*)Input
On entry: a single valid keyword of an integer optional parameter (as described in Section 12 in E04VHF).
2:   IVALUE – INTEGERInput
On entry: an integer value associated with the keyword in STRING.
3:   CW* – CHARACTER(8) arrayCommunication Array
Note: the dimension of the array CW must be at least LENCW (see E04VGF).
4:   IW* – INTEGER arrayCommunication Array
Note: the dimension of the array IW must be at least LENIW (see E04VGF).
5:   RW* – REAL (KIND=nag_wp) arrayCommunication Array
Note: the dimension of the array RW must be at least LENRW (see E04VGF).
6:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
The initialization routine E04VGF has not been called.
IFAIL=2
The supplied option is invalid. Check that the keywords are neither ambiguous nor misspelt.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

Not applicable.

8 Parallelism and Performance

E04VMF is not threaded in any implementation.

9 Further Comments

E04VKF or E04VLF may also be used to supply integer optional parameters to E04VHF.

10 Example

See Section 10 in E04VHF and E04VKF.
E04 Chapter Contents
E04 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


E04VNF : NAG Library, Mark 26

E04 Chapter Contents
E04 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

E04VNF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
10 Example

1 Purpose

E04VNF may be used to supply individual real optional parameters to E04VHF. The initialization routine E04VGF must have been called before calling E04VNF.

2 Specification

SUBROUTINE E04VNF ( STRING, RVALUE, CW, IW, RW, IFAIL)
INTEGER | IW(*), IFAIL
REAL (KIND=nag_wp) | RVALUE, RW(*)
CHARACTER(*) | STRING
CHARACTER(8) | CW(*)

3 Description

E04VNF may be used to supply values for real optional parameters to E04VHF. It is only necessary to call E04VNF for those arguments whose values are to be different from their default values. One call to E04VNF sets one argument value.
Each real optional parameter is defined by a single character string in STRING and the corresponding value in RVALUE. For example the following illustrates how the LU stability tolerance could be defined:
FACTOL = 100.0E0
IF (ILLCON) FACTOL = 5.0E0
CALL E04VNF ('LU Factor Tolerance', FACTOL, CW, IW, RW, IFAIL)
Optional parameter settings are preserved following a call to E04VHF and so the keyword Defaults is provided to allow you to reset all the optional parameters to their default values before a subsequent call to E04VHF.
A complete list of optional parameters, their abbreviations, synonyms and default values is given in Section 12 in E04VHF.

4 References

None.

5 Arguments

1:   STRING – CHARACTER(*)Input
On entry: a single valid keyword of a real optional parameter (as described in Section 12 in E04VHF).
2:   RVALUE – REAL (KIND=nag_wp)Input
On entry: the value associated with the keyword in STRING.
3:   CW* – CHARACTER(8) arrayCommunication Array
Note: the dimension of the array CW must be at least LENCW (see E04VGF).
4:   IW* – INTEGER arrayCommunication Array
Note: the dimension of the array IW must be at least LENIW (see E04VGF).
5:   RW* – REAL (KIND=nag_wp) arrayCommunication Array
Note: the dimension of the array RW must be at least LENRW (see E04VGF).
6:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
The initialization routine E04VGF has not been called.
IFAIL=2
The supplied option is invalid. Check that the keywords are neither ambiguous nor misspelt.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

Not applicable.

8 Parallelism and Performance

E04VNF is not threaded in any implementation.

9 Further Comments

E04VKF or E04VLF may also be used to supply real optional parameters to E04VHF.

10 Example

See Section 10 in E04VKF.
E04 Chapter Contents
E04 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


E04VRF : NAG Library, Mark 26

E04 Chapter Contents
E04 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

E04VRF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
10 Example

1 Purpose

E04VRF is used to get the value of an integer optional parameter. E04VRF can be used before or after calling E04VHF.

2 Specification

SUBROUTINE E04VRF ( STRING, IVALUE, CW, IW, RW, IFAIL)
INTEGER | IVALUE, IW(*), IFAIL
REAL (KIND=nag_wp) | RW(*)
CHARACTER(*) | STRING
CHARACTER(8) | CW(*)

3 Description

E04VRF obtains the current value of an integer option. For example
CALL E04VRF ('Major Iterations', ITNLIM, CW, IW, RW, IFAIL)
will result in the value of the optional parameter Major Iterations Limit being output in ITNLIM.
A complete list of optional parameters, their abbreviations, synonyms and default values is given in Section 12 in E04VHF.

4 References

None.

5 Arguments

1:   STRING – CHARACTER(*)Input
On entry: a single valid keyword of an integer optional parameter (as described in Section 12 in E04VHF).
2:   IVALUE – INTEGEROutput
On exit: the integer value associated with the keyword in STRING.
3:   CW* – CHARACTER(8) arrayCommunication Array
Note: the dimension of the array CW must be at least LENCW (see E04VGF).
4:   IW* – INTEGER arrayCommunication Array
Note: the dimension of the array IW must be at least LENIW (see E04VGF).
5:   RW* – REAL (KIND=nag_wp) arrayCommunication Array
Note: the dimension of the array RW must be at least LENRW (see E04VGF).
6:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
The initialization routine E04VGF has not been called.
IFAIL=2
The supplied option is invalid. Check that the keywords are neither ambiguous nor misspelt.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

Not applicable.

8 Parallelism and Performance

E04VRF is not threaded in any implementation.

9 Further Comments

None.

10 Example

See Section 10 in E04VKF.
E04 Chapter Contents
E04 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


E04VSF : NAG Library, Mark 26

E04 Chapter Contents
E04 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

E04VSF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
10 Example

1 Purpose

E04VSF is used to get the value of a real optional parameter. E04VSF can be used before or after calling E04VHF.

2 Specification

SUBROUTINE E04VSF ( STRING, RVALUE, CW, IW, RW, IFAIL)
INTEGER | IW(*), IFAIL
REAL (KIND=nag_wp) | RVALUE, RW(*)
CHARACTER(*) | STRING
CHARACTER(8) | CW(*)

3 Description

E04VSF obtains the current value of a real option. For example
CALL E04VSF ('Feasibility Tolerance', FEATOL, CW, IW, RW, IFAIL)
will result in the value of the optional parameter Feasibility Tolerance being output in FEATOL.
A complete list of optional parameters, their abbreviations, synonyms and default values is given in Section 12 in E04VHF.

4 References

None.

5 Arguments

1:   STRING – CHARACTER(*)Input
On entry: a single valid keyword of a real optional parameter (as described in Section 12 in E04VHF).
2:   RVALUE – REAL (KIND=nag_wp)Output
On exit: the real value associated with the keyword in STRING.
3:   CW* – CHARACTER(8) arrayCommunication Array
Note: the dimension of the array CW must be at least LENCW (see E04VGF).
4:   IW* – INTEGER arrayCommunication Array
Note: the dimension of the array IW must be at least LENIW (see E04VGF).
5:   RW* – REAL (KIND=nag_wp) arrayCommunication Array
Note: the dimension of the array RW must be at least LENRW (see E04VGF).
6:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
The initialization routine E04VGF has not been called.
IFAIL=2
The supplied option is invalid. Check that the keywords are neither ambiguous nor misspelt.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

Not applicable.

8 Parallelism and Performance

E04VSF is not threaded in any implementation.

9 Further Comments

None.

10 Example

See Section 10 in E04VKF.
E04 Chapter Contents
E04 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


E04WBF : NAG Library, Mark 26

E04 Chapter Contents
E04 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

E04WBF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
10 Example

1 Purpose

E04WBF is used to initialize routines E04DGA, E04MFA, E04NCA, E04NFA, E04NKA, E04UCA, E04UFA, E04UGA and E04USA.

2 Specification

SUBROUTINE E04WBF ( RNAME, CWSAV, LCWSAV, LWSAV, LLWSAV, IWSAV, LIWSAV, RWSAV, LRWSAV, IFAIL)
INTEGER | LCWSAV, LLWSAV, IWSAV(LIWSAV), LIWSAV, LRWSAV, IFAIL
REAL (KIND=nag_wp) | RWSAV(LRWSAV)
LOGICAL | LWSAV(LLWSAV)
CHARACTER(*) | RNAME
CHARACTER(80) | CWSAV(LCWSAV)

3 Description

E04WBF initializes some or all of the arrays CWSAV, LWSAV, IWSAV and RWSAV for the routine specified by RNAME, and any associated option setting routines.

4 References

None.

5 Arguments

1:   RNAME – CHARACTER(*)Input
On entry: the name of the routine to be initialized.
Constraint: RNAME must be the name of one of the routines initialized by E04WBF.
2:   CWSAV LCWSAV – CHARACTER(80) arrayCommunication Array
3:   LCWSAV – INTEGERInput
On entry: the dimension of the array CWSAV as declared in the (sub)program from which E04WBF is called.
Constraints:
  • if RNAME='E04UFF' or 'E04UFA', LCWSAV≥5;
  • otherwise LCWSAV≥1.
4:   LWSAV LLWSAV – LOGICAL arrayCommunication Array
5:   LLWSAV – INTEGERInput
On entry: the dimension of the array LWSAV as declared in the (sub)program from which E04WBF is called.
Constraints:
  • if RNAME='E04NKF' or 'E04NKA', LLWSAV≥20;
  • if RNAME='E04UGF' or 'E04UGA', LLWSAV≥20;
  • otherwise LLWSAV≥120.
6:   IWSAV LIWSAV – INTEGER arrayCommunication Array
7:   LIWSAV – INTEGERInput
On entry: the dimension of the array IWSAV as declared in the (sub)program from which E04WBF is called.
Constraints:
  • if RNAME='E04NKF' or 'E04NKA', LIWSAV≥380;
  • if RNAME='E04UGF' or 'E04UGA', LIWSAV≥550;
  • otherwise LIWSAV≥610.
8:   RWSAV LRWSAV – REAL (KIND=nag_wp) arrayCommunication Array
9:   LRWSAV – INTEGERInput
On entry: the dimension of the array RWSAV as declared in the (sub)program from which E04WBF is called.
Constraints:
  • if RNAME='E04NKF' or 'E04NKA', LRWSAV≥285;
  • if RNAME='E04UGF' or 'E04UGA', LRWSAV≥550;
  • otherwise LRWSAV≥475.
10:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
The routine name supplied in RNAME is invalid
IFAIL=2
One or more of the workspace array lengths LCWSAV, LLWSAV, LIWSAV or LRWSAV is too small.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

Not applicable.

8 Parallelism and Performance

E04WBF is not threaded in any implementation.

9 Further Comments

The time taken by E04WBF is negligible.

10 Example

The use of E04WBF is illustrated by the example programs of the routines listed in Section 1.
E04 Chapter Contents
E04 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


E04WCF : NAG Library, Mark 26

E04 Chapter Contents
E04 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

E04WCF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
10 Example

1 Purpose

E04WCF is used to initialize the routine E04WDF.

2 Specification

SUBROUTINE E04WCF ( IW, LENIW, RW, LENRW, IFAIL)
INTEGER | IW(LENIW), LENIW, LENRW, IFAIL
REAL (KIND=nag_wp) | RW(LENRW)

3 Description

E04WCF initializes the arrays IW and RW for the routine E04WDF.

4 References

None.

5 Arguments

1:   IW LENIW – INTEGER arrayCommunication Array
2:   LENIW – INTEGERInput
On entry: the dimension of the array IW as declared in the (sub)program from which E04WCF is called.
Constraint: LENIW≥600, see routine E04WDF.
3:   RW LENRW – REAL (KIND=nag_wp) arrayCommunication Array
4:   LENRW – INTEGERInput
On entry: the dimension of the array RW as declared in the (sub)program from which E04WCF is called.
Constraint: LENRW≥600, see routine E04WDF.
5:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
One or more of the communication array lengths LENIW or LENRW is less than 600.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

Not applicable.

8 Parallelism and Performance

E04WCF is not threaded in any implementation.

9 Further Comments

The time taken by E04WCF is negligible.

10 Example

See Section 10 in E04WDF and E04WEF.
E04 Chapter Contents
E04 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


E04WDF : NAG Library, Mark 26

E04 Chapter Contents
E04 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

E04WDF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.
Note: this routine uses optional parameters to define choices in the problem specification and in the details of the algorithm. If you wish to use default settings for all of the optional parameters, you need only read Sections 1 to 10 of this document. If, however, you wish to reset some or all of the settings please refer to Section 11 for a detailed description of the algorithm, to Section 12 for a detailed description of the specification of the optional parameters and to Section 13 for a detailed description of the monitoring information produced by the routine.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
▸▿ 9 Further Comments
9.1 The Final Output
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results
▸▿ 11 Algorithmic Details
11.1 Constraints and Slack Variables
11.2 Major Iterations
11.3 Minor Iterations
11.4 The Merit Function
11.5 Treatment of Constraint Infeasibilities
▸▿ 12 Optional Parameters
12.1 Description of the Optional Parameters
▸▿ 13 Description of Monitoring Information
13.1 Major Iteration Log
13.2 Minor Iteration Log
13.3 Crash Statistics
13.4 Basis Factorization Statistics
▸▿ 13.5 The Solution File
13.5.1 The ROWS section
13.5.2 The COLUMNS section
13.6 The Summary File

1 Purpose

E04WDF is designed to minimize an arbitrary smooth function subject to constraints (which may include simple bounds on the variables, linear constraints and smooth nonlinear constraints) using a sequential quadratic programming (SQP) method. As many first derivatives as possible should be supplied by you; any unspecified derivatives are approximated by finite differences. It is not intended for large sparse problems.
E04WDF may also be used for unconstrained, bound-constrained and linearly constrained optimization.
E04WDF uses forward communication for evaluating the objective function, the nonlinear constraint functions, and any of their derivatives.
The initialization routine E04WCF must have been called before to calling E04WDF.

2 Specification

SUBROUTINE E04WDF ( N, NCLIN, NCNLN, LDA, LDCJ, LDH, A, BL, BU, CONFUN, OBJFUN, MAJITS, ISTATE, CCON, CJAC, CLAMDA, OBJF, GRAD, H, X, IW, LENIW, RW, LENRW, IUSER, RUSER, IFAIL)
INTEGER | N, NCLIN, NCNLN, LDA, LDCJ, LDH, MAJITS, ISTATE(N+NCLIN+NCNLN), IW(LENIW), LENIW, LENRW, IUSER(*), IFAIL
REAL (KIND=nag_wp) | A(LDA,*), BL(N+NCLIN+NCNLN), BU(N+NCLIN+NCNLN), CCON(max(1,NCNLN)), CJAC(LDCJ,*), CLAMDA(N+NCLIN+NCNLN), OBJF, GRAD(N), H(LDH,*), X(N), RW(LENRW), RUSER(*)
EXTERNAL | CONFUN, OBJFUN
Before calling E04WDF, or any of the option setting routines E04WEF, E04WFF, E04WGF or E04WHF, E04WCF must be called. The specification for E04WCF is:
SUBROUTINE E04WCF ( IW, LENIW, RW, LENRW, IFAIL)
INTEGER | IW(LENIW), LENIW, LENRW, IFAIL
REAL (KIND=nag_wp) | RW(LENRW)
E04WCF must be called with LENIW and LENRW, the declared lengths of IW and RW respectively, satisfying:
  • LENIW≥600;
  • LENRW≥600.
The contents of the arrays IW and RW must not be altered between calls of the routines E04WCF, E04WDF, E04WEF, E04WGF or E04WHF.

3 Description

E04WDF is designed to solve nonlinear programming problems – the minimization of a smooth nonlinear function subject to a set of constraints on the variables. E04WDF is suitable for small dense problems. The problem is assumed to be stated in the following form:
minimize x∈Rn F x   subject to   l ≤ x AL x c x ≤u, (1)
where F x (the objective function) is a nonlinear scalar function, AL is an nL by n constant matrix, and c x is an nN -vector of nonlinear constraint functions. (The matrix AL and the vector c x may be empty.) The objective function and the constraint functions are assumed to be smooth, here meaning at least twice-continuously differentiable. (The method of E04WDF will usually solve (1) if there are only isolated discontinuities away from the solution.) We also write r x for the vector of combined functions:
r x = x AL x c x T .
Note that although the bounds on the variables could be included in the definition of the linear constraints, we prefer to distinguish between them for reasons of computational efficiency. For the same reason, the linear constraints should not be included in the definition of the nonlinear constraints. Upper and lower bounds are specified for all the variables and for all the constraints. An equality constraint on ri can be specified by setting li = ui . If certain bounds are not present, the associated elements of l or u can be set to special values that will be treated as -∞ or +∞ . (See the description of the optional parameter Infinite Bound Size.)
A typical invocation of E04WDF is:
CALL E04WCF (IW, LENIW, ...)
CALL E04WEF (ISPECS, IW, ...)
CALL E04WDF (N, NCLIN, NCNLN, ...)
where E04WEF reads a set of optional parameter definitions from the file with unit number ISPECS.
Figure 1 illustrates the feasible region for the j th pair of constraints lj ≤ rj x ≤ uj . The quantity of δ is the Feasibility Tolerance, which can be set by you (see Section 12). The constraints lj ≤ rj ≤ uj are considered ‘satisfied’ if rj lies in Regions 2, 3 or 4, and ‘inactive’ if rj lies in Region 3. The constraint rj ≥ lj is considered ‘active’ in Region 2, and ‘violated’ in Region 1. Similarly, rj ≤ uj is active in Region 4, and violated in Region 5. For equality constraints ( lj = uj ), Regions 2 and 4 are the same and Region 3 is empty.
Illustration of the constraints lj ≤ rj x ≤ uj
Figure 1: Illustration of the constraints lj ≤ rj x ≤ uj
If there are no nonlinear constraints in (1) and F is linear or quadratic, then it will generally be more efficient to use one of E04MFF/E04MFA, E04NCF/E04NCA or E04NFF/E04NFA. If the problem is large and sparse and does have nonlinear constraints, then E04VHF should be used, since E04WDF treats all matrices as dense.
You must supply an initial estimate of the solution to (1), together with subroutines that define F x and c x with as many first partial derivatives as possible; unspecified derivatives are approximated by finite differences; see Section 12.1 for a discussion of the optional parameter Derivative Level.
The objective function is defined by OBJFUN, and the nonlinear constraints are defined by CONFUN. Note that if there are any nonlinear constraints then the first call to CONFUN will precede the first call to OBJFUN.
For maximum reliability, it is preferable for you to provide all partial derivatives (see Chapter 8 of Gill et al. (1981), for a detailed discussion). If all gradients cannot be provided, it is similarly advisable to provide as many as possible. While developing OBJFUN and CONFUN, the optional parameter Verify Level should be used to check the calculation of any known gradients.
The method used by E04WDF is based on NPOPT, which is part of the SNOPT package described in Gill et al. (2005b), and the algorithm it uses is described in detail in Section 11.

4 References

Eldersveld S K (1991) Large-scale sequential quadratic programming algorithms PhD Thesis Department of Operations Research, Stanford University, Stanford
Fourer R (1982) Solving staircase linear programs by the simplex method Math. Programming 23 274–313
Gill P E, Murray W and Saunders M A (2002) SNOPT: An SQP Algorithm for Large-scale Constrained Optimization 12 979–1006 SIAM J. Optim.
Gill P E, Murray W and Saunders M A (2005a) Users' guide for SQOPT 7: a Fortran package for large-scale linear and quadratic programming Report NA 05-1 Department of Mathematics, University of California, San Diego http://www.ccom.ucsd.edu/~peg/papers/sqdoc7.pdf
Gill P E, Murray W and Saunders M A (2005b) Users' guide for SNOPT 7.1: a Fortran package for large-scale linear nonlinear programming Report NA 05-2 Department of Mathematics, University of California, San Diego http://www.ccom.ucsd.edu/~peg/papers/sndoc7.pdf
Gill P E, Murray W, Saunders M A and Wright M H (1986) Users' guide for NPSOL (Version 4.0): a Fortran package for nonlinear programming Report SOL 86-2 Department of Operations Research, Stanford University
Gill P E, Murray W, Saunders M A and Wright M H (1992) Some theoretical properties of an augmented Lagrangian merit function Advances in Optimization and Parallel Computing (ed P M Pardalos) 101–128 North Holland
Gill P E, Murray W and Wright M H (1981) Practical Optimization Academic Press
Hock W and Schittkowski K (1981) Test Examples for Nonlinear Programming Codes. Lecture Notes in Economics and Mathematical Systems 187 Springer–Verlag

5 Arguments

1:   N – INTEGERInput
On entry: n, the number of variables.
Constraint: N>0.
2:   NCLIN – INTEGERInput
On entry: nL, the number of general linear constraints.
Constraint: NCLIN≥0.
3:   NCNLN – INTEGERInput
On entry: nN, the number of nonlinear constraints.
Constraint: NCNLN≥0.
4:   LDA – INTEGERInput
On entry: the first dimension of the array A as declared in the (sub)program from which E04WDF is called.
Constraint: LDA≥max 1,NCLIN.
5:   LDCJ – INTEGERInput
On entry: the first dimension of the array CJAC as declared in the (sub)program from which E04WDF is called.
Constraint: LDCJ≥max 1,NCNLN.
6:   LDH – INTEGERInput
On entry: the first dimension of the array H as declared in the (sub)program from which E04WDF is called.
Constraint: LDH≥N unless optional parameter Hessian Limited Memory is in effect.
7:   A LDA* – REAL (KIND=nag_wp) arrayInput
Note: the second dimension of the array A must be at least N if NCLIN>0, and at least 1 otherwise.
On entry: the ith row of A contains the ith row of the matrix AL of general linear constraints in (1). That is, the ith row contains the coefficients of the ith general linear constraint, for i=1,2,…,NCLIN.
If NCLIN=0, the array A is not referenced.
8:   BL N+NCLIN+NCNLN – REAL (KIND=nag_wp) arrayInput
9:   BU N+NCLIN+NCNLN – REAL (KIND=nag_wp) arrayInput
On entry: BL must contain the lower bounds and BU the upper bounds for all the constraints, in the following order. The first n elements of each array must contain the bounds on the variables, the next nL elements the bounds for the general linear constraints (if any) and the next nN elements the bounds for the general nonlinear constraints (if any). To specify a nonexistent lower bound (i.e., lj=-∞ ), set BL j ≤ -bigbnd , and to specify a nonexistent upper bound (i.e., uj=+∞ ), set BU j ≥ bigbnd ; where bigbnd is the optional parameter Infinite Bound Size. To specify the j th constraint as an equality, set BL j=BU j=β , say, where β < bigbnd .
Constraints:
  • BL j≤BU j, for j=1,2,…,N+NCLIN+NCNLN;
  • if BL j=BU j=β, β<bigbnd.
10:   CONFUN – SUBROUTINE, supplied by the NAG Library or the user.External Procedure
CONFUN must calculate the vector c x of nonlinear constraint functions and (optionally) its Jacobian, ∂c ∂x , for a specified n-vector x. If there are no nonlinear constraints (i.e., NCNLN=0), E04WDF will never call CONFUN, so it may be the dummy routine E04WDP. (E04WDP is included in the NAG Library). If there are nonlinear constraints, the first call to CONFUN will occur before the first call to OBJFUN.
If all constraint gradients (Jacobian elements) are known (i.e., Derivative Level=2 or 3), any constant elements may be assigned to CJAC once only at the start of the optimization. An element of CJAC that is not subsequently assigned in CONFUN will retain its initial value throughout. Constant elements may be loaded in CJAC during the first call to CONFUN (signalled by the value of NSTATE=1). The ability to preload constants is useful when many Jacobian elements are identically zero, in which case CJAC may be initialized to zero and nonzero elements may be reset by CONFUN.
It must be emphasized that, if Derivative Level<2, unassigned elements of CJAC are not treated as constant; they are estimated by finite differences, at nontrivial expense.
The specification of CONFUN is:
SUBROUTINE CONFUN ( MODE, NCNLN, N, LDCJ, NEEDC, X, CCON, CJAC, NSTATE, IUSER, RUSER)
INTEGER | MODE, NCNLN, N, LDCJ, NEEDC(NCNLN), NSTATE, IUSER(*)
REAL (KIND=nag_wp) | X(N), CCON(max(1,NCNLN)), CJAC(LDCJ,N), RUSER(*)
1:   MODE – INTEGERInput/Output
On entry: is set by E04WDF to indicate which values must be assigned during each call of CONFUN. Only the following values need be assigned, for each value of i such that NEEDC i>0:
MODE=0
The components of CCON corresponding to positive values in NEEDC must be set. Other components and the array CJAC are ignored.
MODE=1
The known components of the rows of CJAC corresponding to positive values in NEEDC must be set. Other rows of CJAC and the array CCON will be ignored.
MODE=2
Only the elements of CCON corresponding to positive values of NEEDC need to be set (and similarly for the known components of the rows of CJAC).
On exit: may be used to indicate that you are unable or unwilling to evaluate the constraint functions at the current x .
During the linesearch, the constraint functions are evaluated at points of the form x=xk + α pk after they have already been evaluated satisfactorily at xk . At any such α , if you set MODE=-1 , E04WDF will evaluate the functions at some point closer to xk (where they are more likely to be defined).
If for some reason you wish to terminate the current problem, set MODE<-1 .
2:   NCNLN – INTEGERInput
On entry: nN, the number of nonlinear constraints.
3:   N – INTEGERInput
On entry: n, the number of variables.
4:   LDCJ – INTEGERInput
On entry: the first dimension of the array CJAC as declared in the (sub)program from which E04WDF is called.
5:   NEEDC NCNLN – INTEGER arrayInput
On entry: the indices of the elements of CCON and/or CJAC that must be evaluated by CONFUN. If NEEDC i>0, the ith element of CCON and/or the available elements of the ith row of CJAC (see argument MODE) must be evaluated at x.
6:   X N – REAL (KIND=nag_wp) arrayInput
On entry: x, the vector of variables at which the constraint functions and/or the available elements of the constraint Jacobian are to be evaluated.
7:   CCON max 1,NCNLN – REAL (KIND=nag_wp) arrayOutput
On exit: if NEEDC i > 0 and MODE=0 or 2, CCON i must contain the value of the ith constraint at x. The remaining elements of CCON, corresponding to the non-positive elements of NEEDC, are ignored.
8:   CJAC LDCJN – REAL (KIND=nag_wp) arrayInput/Output
On entry: the elements of CJAC are set to special values that enable E04WDF to detect whether they are reset by CONFUN.
On exit: if NEEDC i > 0 and MODE=1 or 2, the i th row of CJAC must contain the available elements of the vector ∇ ci given by
∇ ci= ∂ci ∂x 1 , ∂ci ∂x 2 , … , ∂ci ∂xn T ,
where ∂ci ∂xj is the partial derivative of the ith constraint with respect to the jth variable, evaluated at the point x. See also the argument NSTATE. The remaining rows of CJAC, corresponding to non-positive elements of NEEDC, are ignored.
If all elements of the constraint Jacobian are known (i.e., Derivative Level=2 or 3), any constant elements may be assigned to CJAC one time only at the start of the optimization. An element of CJAC that is not subsequently assigned in CONFUN will retain its initial value throughout. Constant elements may be loaded into CJAC during the first call to CONFUN (signalled by the value NSTATE=1). The ability to preload constants is useful when many Jacobian elements are identically zero, in which case CJAC may be initialized to zero and nonzero elements may be reset by CONFUN.
Note that constant nonzero elements do affect the values of the constraints. Thus, if CJAC ij is set to a constant value, it need not be reset in subsequent calls to CONFUN, but the value CJAC ij × X j must nonetheless be added to CCON i . For example, if CJAC 11=2 and CJAC 12=-5 then the term 2 × X 1 - 5 × X 2 must be included in the definition of CCON 1 .
It must be emphasized that, if Derivative Level=0 or 1, unassigned elements of CJAC are not treated as constant; they are estimated by finite differences, at nontrivial expense. If you do not supply a value for the optional parameter Difference Interval, an interval for each element of x is computed automatically at the start of the optimization. The automatic procedure can usually identify constant elements of CJAC, which are then computed once only by finite differences.
9:   NSTATE – INTEGERInput
On entry: if NSTATE=1 then E04WDF is calling CONFUN for the first time. This argument setting allows you to save computation time if certain data must be read or calculated only once.
10:   IUSER* – INTEGER arrayUser Workspace
11:   RUSER* – REAL (KIND=nag_wp) arrayUser Workspace
CONFUN is called with the arguments IUSER and RUSER as supplied to E04WDF. You are free to use the arrays IUSER and RUSER to supply information to CONFUN as an alternative to using COMMON global variables.
CONFUN must either be a module subprogram USEd by, or declared as EXTERNAL in, the (sub)program from which E04WDF is called. Arguments denoted as Input must not be changed by this procedure.
CONFUN should be tested separately before being used in conjunction with E04WDF. See also the description of the optional parameter Verify Level.
11:   OBJFUN – SUBROUTINE, supplied by the user.External Procedure
OBJFUN must calculate the objective function F x and (optionally) its gradient g x = ∂F ∂x for a specified n-vector x.
The specification of OBJFUN is:
SUBROUTINE OBJFUN ( MODE, N, X, OBJF, GRAD, NSTATE, IUSER, RUSER)
INTEGER | MODE, N, NSTATE, IUSER(*)
REAL (KIND=nag_wp) | X(N), OBJF, GRAD(N), RUSER(*)
1:   MODE – INTEGERInput/Output
On entry: is set by E04WDF to indicate which values must be assigned during each call of OBJFUN. Only the following values need be assigned:
MODE=0
OBJF.
MODE=1
All available elements of GRAD.
MODE=2
OBJF and all available elements of GRAD.
On exit: may be used to indicate that you are unable or unwilling to evaluate the objective function at the current x .
During the linesearch, the function is evaluated at points of the form x=xk + α pk after they have already been evaluated satisfactorily at xk . For any such x , if you set MODE=-1 , E04WDF will reduce α and evaluate the functions again (closer to xk , where they are more likely to be defined).
If for some reason you wish to terminate the current problem, set MODE<-1 .
2:   N – INTEGERInput
On entry: n, the number of variables.
3:   X N – REAL (KIND=nag_wp) arrayInput
On entry: x, the vector of variables at which the objective function and/or all available elements of its gradient are to be evaluated.
4:   OBJF – REAL (KIND=nag_wp)Output
On exit: if MODE=0 or 2, OBJF must be set to the value of the objective function at x.
5:   GRAD N – REAL (KIND=nag_wp) arrayInput/Output
On entry: the elements of GRAD are set to special values.
On exit: if MODE=1 or 2, GRAD must return the available elements of the gradient evaluated at x, i.e., GRAD i contains the partial derivative ∂F ∂xi .
6:   NSTATE – INTEGERInput
On entry: if NSTATE=1 then E04WDF is calling OBJFUN for the first time. This argument setting allows you to save computation time if certain data must be read or calculated only once.
7:   IUSER* – INTEGER arrayUser Workspace
8:   RUSER* – REAL (KIND=nag_wp) arrayUser Workspace
OBJFUN is called with the arguments IUSER and RUSER as supplied to E04WDF. You are free to use the arrays IUSER and RUSER to supply information to OBJFUN as an alternative to using COMMON global variables.
OBJFUN must either be a module subprogram USEd by, or declared as EXTERNAL in, the (sub)program from which E04WDF is called. Arguments denoted as Input must not be changed by this procedure.
OBJFUN should be tested separately before being used in conjunction with E04WDF. See also the description of the optional parameter Verify Level.
12:   MAJITS – INTEGEROutput
On exit: the number of major iterations performed.
13:   ISTATE N+NCLIN+NCNLN – INTEGER arrayInput/Output
On entry: is an integer array that need not be initialized if E04WDF is called with the Cold Start option (the default).
If optional parameter Warm Start has been chosen, every element of ISTATE must be set. If E04WDF has just been called on a problem with the same dimensions, ISTATE already contains valid values. Otherwise, ISTATE j should indicate whether either of the constraints rj x ≥ lj or rj x ≤ uj is expected to be active at a solution of (1).
The ordering of ISTATE is the same as for BL, BU and r x, i.e., the first N components of ISTATE refer to the upper and lower bounds on the variables, the next NCLIN refer to the bounds on AL x , and the last NCNLN refer to the bounds on c x . Possible values of ISTATE i follow:
0 | Neither rj x ≥ lj nor rj x ≤ uj is expected to be active.
1 | rj x ≥ lj is expected to be active.
2 | rj x ≤ uj is expected to be active.
3 | This may be used if lj=uj . Normally an equality constraint rj x=lj=uj is active at a solution.
The values 1, 2 or 3 all have the same effect when BL j=BU j . If necessary, E04WDF will override your specification of ISTATE, so that a poor choice will not cause the algorithm to fail.
On exit: describes the status of the constraints l≤r x≤u . For the jth lower or upper bound, j=1,2,…,N+NCLIN+NCNLN, the possible values of ISTATE j are as follows (see Figure 1). δ is the appropriate feasibility tolerance.
-2 | (Region 1) The lower bound is violated by more than δ .
-1 | (Region 5) The upper bound is violated by more than δ .
-0 | (Region 3) Both bounds are satisfied by more than δ .
-1 | (Region 2) The lower bound is active (to within δ ).
-2 | (Region 4) The upper bound is active (to within δ ).
-3 | (Region 2=Region 4) The bounds are equal and the equality constraint is satisfied (to within δ ).
These values of ISTATE are labelled in the printed solution according to Table 1.
Region | 1 | 2 | 3 | 4 | 5 | 2≡4
ISTATE j | -2 | 1 | 0 | 2 | -1 | 3
Printed solution -- LL FR UL ++ EQ
Table 1
Labels used in the printed solution for the regions in Figure 1
14:   CCON max 1,NCNLN – REAL (KIND=nag_wp) arrayInput/Output
On entry: CCON need not be initialized if the (default) optional parameter Cold Start is used.
For a Warm Start, and if NCNLN>0, CCON contains values of the nonlinear constraint functions ci, for i=1,2,…,NCNLN, calculated in a previous call to E04WDF.
On exit: if NCNLN>0, CCON i contains the value of the ith nonlinear constraint function ci at the final iterate, for i=1,2,…,NCNLN.
If NCNLN=0, the array CCON is not referenced.
15:   CJAC LDCJ* – REAL (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array CJAC must be at least N if NCNLN>0, and at least 1 otherwise.
On entry: in general, CJAC need not be initialized before the call to E04WDF. However, if Derivative Level=2 or 3, any constant elements of CJAC may be initialized. Such elements need not be reassigned on subsequent calls to CONFUN.
On exit: if NCNLN>0, CJAC contains the Jacobian matrix of the nonlinear constraint functions at the final iterate, i.e., CJAC ij contains the partial derivative of the ith constraint function with respect to the jth variable, for i=1,2,…,NCNLN and j=1,2,…,N. (See the discussion of argument CJAC under CONFUN.)
If NCNLN=0, the array CJAC is not referenced.
16:   CLAMDA N+NCLIN+NCNLN – REAL (KIND=nag_wp) arrayInput/Output
On entry: need not be set if the (default) optional parameter Cold Start is used.
If the optional parameter Warm Start has been chosen, CLAMDA j must contain a multiplier estimate for each nonlinear constraint, with a sign that matches the status of the constraint specified by the ISTATE array, for j=N+NCLIN+1,…,N+NCLIN+NCNLN. The remaining elements need not be set. If the jth constraint is defined as ‘inactive’ by the initial value of the ISTATE array (i.e., ISTATE j=0), CLAMDA j should be zero; if the jth constraint is an inequality active at its lower bound (i.e., ISTATE j=1), CLAMDA j should be non-negative; if the jth constraint is an inequality active at its upper bound (i.e., ISTATE j=2), CLAMDA j should be non-positive. If necessary, the routine will modify CLAMDA to match these rules.
On exit: the values of the QP multipliers from the last QP subproblem. CLAMDA j should be non-negative if ISTATE j=1 and non-positive if ISTATE j=2.
17:   OBJF – REAL (KIND=nag_wp)Output
On exit: the value of the objective function at the final iterate.
18:   GRAD N – REAL (KIND=nag_wp) arrayOutput
On exit: the gradient of the objective function (or its finite difference approximation) at the final iterate.
19:   H LDH* – REAL (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array H must be at least N unless the optional parameter Hessian Limited Memory is in effect. If Hessian Limited Memory is in effect, array H is not referenced.
On entry: H need not be initialized if the (default) optional parameter Cold Start is used, and will be set to the identity.
If the optional parameter Warm Start has been chosen, H provides the initial approximation of the Hessian of the Lagrangian, i.e., H ij ≈ ∂2 L x,λ ∂xi ∂xj , where L x,λ=F x - c x T λ and λ is an estimate of the Lagrange multipliers. H must be a positive definite matrix.
On exit: contains the Hessian of the Lagrangian at the final estimate x .
20:   X N – REAL (KIND=nag_wp) arrayInput/Output
On entry: an initial estimate of the solution.
On exit: the final estimate of the solution.
21:   IW LENIW – INTEGER arrayCommunication Array
22:   LENIW – INTEGERInput
On entry: the dimension of the array IW as declared in the (sub)program from which E04WDF is called.
Constraint: LENIW≥600.
23:   RW LENRW – REAL (KIND=nag_wp) arrayCommunication Array
24:   LENRW – INTEGERInput
On entry: the dimension of the array RW as declared in the (sub)program from which E04WDF is called.
Constraint: LENRW≥600.
25:   IUSER* – INTEGER arrayUser Workspace
26:   RUSER* – REAL (KIND=nag_wp) arrayUser Workspace
IUSER and RUSER are not used by E04WDF, but are passed directly to CONFUN and OBJFUN and may be used to pass information to these routines as an alternative to using COMMON global variables.
27:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, because for this routine the values of the output arguments may be useful even if IFAIL≠0 on exit, the recommended value is -1. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).
E04WDF returns with IFAIL=0 if the iterates have converged to a point x that satisfies the first-order Kuhn–Tucker (see Section 13.2) conditions to the accuracy requested by the Major Optimality Tolerance, i.e., the projected gradient and active constraint residuals are negligible at x.
You should check whether the following four conditions are satisfied:
(i) | the final value of rgNorm (see Section 13.2) is significantly less than that at the starting point;
(ii) | during the final major iterations, the values of Step and Minors (see Section 13.1) are both one;
(iii) | the last few values of both rgNorm and SumInf (see Section 13.2) become small at a fast linear rate; and
(iv) | condHz (see Section 13.1) is small.
If all these conditions hold, x is almost certainly a local minimum of (1).
One caution about ‘Optimal solutions’. Some of the variables or slacks may lie outside their bounds more than desired, especially if scaling was requested. Max Primal infeas in the Print file refers to the largest bound infeasibility and which variable is involved. If it is too large, consider restarting with a smaller Minor Feasibility Tolerance (say 10 times smaller) and perhaps Scale Option=0.
Similarly, Max Dual infeas in the Print file indicates which variable is most likely to be at a nonoptimal value. Broadly speaking, if
Max Dual infeas / Max pi = 10-d ,
then the objective function would probably change in the d th significant digit if optimization could be continued. If d seems too large, consider restarting with a smaller Major Optimality Tolerance.
Finally, Nonlinear constraint violn in the Print file shows the maximum infeasibility for nonlinear rows. If it seems too large, consider restarting with a smaller Major Feasibility Tolerance.

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Note: E04WDF may return useful information for one or more of the following detected errors or warnings.
Errors or warnings detected by the routine:
IFAIL=1
On entry, LENIW=value.
Constraint: LENIW≥600.
On entry, LENRW=value.
Constraint: LENRW≥600.
The initialization routine E04WCF has not been called.
IFAIL=2
Basis file dimensions do not match this problem.
On entry, bounds BL and BU for value are equal and infinite. BL=BU=value and bigbnd=value.
On entry, bounds for value are inconsistent. BL=value and BU=value.
On entry, LDA=value and NCLIN=value.
Constraint: LDA≥NCLIN.
On entry, LDCJ=value and NCNLN=value.
Constraint: LDCJ≥NCNLN.
On entry, LDH=value and N=value.
Constraint: LDH≥N.
On entry, N=value.
Constraint: N≥value.
On entry, NCLIN=value.
Constraint: NCLIN≥value.
On entry, NCNLN=value.
Constraint: NCNLN≥value.
IFAIL=3
The requested accuracy could not be achieved.
A feasible solution has been found, but the requested accuracy in the dual infeasibilities could not be achieved. An abnormal termination has occurred, but E04WDF is within 10-2 of satisfying the Major Optimality Tolerance. Check that the Major Optimality Tolerance is not too small.
IFAIL=4
The linear constraints appear to be infeasible.
The problem appears to be infeasible. Infeasibilites have been minimized.
The problem appears to be infeasible. Nonlinear infeasibilites have been minimized.
The problem appears to be infeasible. The linear equality constraints could not be satisfied.
When the constraints are linear, this message is based on a relatively reliable indicator of infeasibility. Feasibility is measured with respect to the upper and lower bounds on the variables and slacks. Among all the points satisfying the general constraints Ax-s=0 (see (5) and (6) in Section 11.2), there is apparently no point that satisfies the bounds on x and s . Violations as small as the Minor Feasibility Tolerance are ignored, but at least one component of x or s violates a bound by more than the tolerance.
When nonlinear constraints are present, infeasibility is much harder to recognize correctly. Even if a feasible solution exists, the current linearization of the constraints may not contain a feasible point. In an attempt to deal with this situation, when solving each QP subproblem, E04WDF is prepared to relax the bounds on the slacks associated with nonlinear rows.
If a QP subproblem proves to be infeasible or unbounded (or if the Lagrange multiplier estimates for the nonlinear constraints become large), E04WDF enters so-called ‘nonlinear elastic’ mode. The subproblem includes the original QP objective and the sum of the infeasibilities – suitably weighted using the optional parameter Elastic Weight. In elastic mode, some of the bounds on the nonlinear rows are ‘elastic’ – i.e., they are allowed to violate their specific bounds. Variables subject to elastic bounds are known as elastic variables. An elastic variable is free to violate one or both of its original upper or lower bounds. If the original problem has a feasible solution and the elastic weight is sufficiently large, a feasible point eventually will be obtained for the perturbed constraints, and optimization can continue on the subproblem. If the nonlinear problem has no feasible solution, E04WDF will tend to determine a ‘good’ infeasible point if the elastic weight is sufficiently large. (If the elastic weight were infinite, E04WDF would locally minimize the nonlinear constraint violations subject to the linear constraints and bounds.)
Unfortunately, even though E04WDF locally minimizes the nonlinear constraint violations, there may still exist other regions in which the nonlinear constraints are satisfied. Wherever possible, nonlinear constraints should be defined in such a way that feasible points are known to exist when the constraints are linearized.
IFAIL=5
The problem appears to be unbounded. The constraint violation limit has been reached.
The problem appears to be unbounded. The objective function is unbounded.
The problem appears to be unbounded (or badly scaled).
For linear problems, unboundedness is detected by the simplex method when a nonbasic variable can be increased or decreased by an arbitrary amount without causing a basic variable to violate a bound. Consider adding an upper or lower bound to the variable. Also, examine the constraints that have nonzeros in the associated column, to see if they have been formulated as intended.
Very rarely, the scaling of the problem could be so poor that numerical error will give an erroneous indication of unboundedness. Consider using the optional parameter Scale Option.
For nonlinear problems, E04WDF monitors both the size of the current objective function and the size of the change in the variables at each step. If either of these is very large (as judged by the ‘Unbounded’ parameters (see Section 12)), the problem is terminated and declared unbounded. To avoid large function values, it may be necessary to impose bounds on some of the variables in order to keep them away from singularities in the nonlinear functions.
The message may indicate an abnormal termination while enforcing the limit on the constraint violations. This exit implies that the objective is not bounded below in the feasible region defined by expanding the bounds by the value of the Violation Limit.
IFAIL=6
Iteration limit reached.
Major iteration limit reached.
The value of the optional parameter Superbasics Limit is too small.
Either the Iterations Limit or the Major Iterations Limit was exceeded before the required solution could be found. Check the iteration log to be sure that progress was being made. If so, and if you caused a basis file to be saved by using the optional parameter New Basis File, consider restarting the run using the optional parameter Old Basis File to see whether further progress can be made. If you have no basis file available, you might rerun the problem after increasing the optional parameters Minor Iterations Limit and/or Major Iterations Limit.
If none of the above limits have been reached, this error may mean that the problem appears to be more nonlinear than anticipated. The current set of basic and superbasic variables have been optimized as much as possible and a pricing operation (where a nonbasic variable is selected to become superbasic) is necessary to continue, but it can't continue as the number of superbasic variables has already reached the limit specified by the optional parameter Superbasics Limit. In general, raise the Superbasics Limit s by a reasonable amount, bearing in mind the storage needed for the reduced Hessian. (The Reduced Hessian Dimension h will also increase to s unless specified otherwise, and the associated storage will be about 12 s 2 words.) In some cases you may have to set h<s to conserve storage, but beware that the rate of convergence will probably fall off severely.
IFAIL=7
Numerical difficulties have been encountered and no further progress can be made.
Numerical difficulties have been encountered and no further progress can be made.
Several circumstances could lead to this exit.
1. | The user-supplied subroutines OBJFUN or CONFUN could be returning accurate function values but inaccurate gradients (or vice versa). This is the most likely cause. Study the comments given for IFAIL=8, and do your best to ensure that the coding is correct.
2. | The function and gradient values could be consistent, but their precision could be too low. For example, accidental use of a real data type when double precision was intended would lead to a relative function precision of about 10-6 instead of something like 10-15 . The default Major Optimality Tolerance of 2×10-6 would need to be raised to about 10-3 for optimality to be declared (at a rather suboptimal point). Of course, it is better to revise the function coding to obtain as much precision as economically possible.
3. If function values are obtained from an expensive iterative process, they may be accurate to rather few significant figures, and gradients will probably not be available. One should specify
  • Function Precision t
  • Major Optimality Tolerance t
but even then, if t is as large as 10-5 or 10-6 (only 5 or 6 significant figures), the same exit condition may occur. At present the only remedy is to increase the accuracy of the function calculation.
4. An LU factorization of the basis has just been obtained and used to recompute the basic variables xB , given the present values of the superbasic and nonbasic variables. A step of ‘iterative refinement’ has also been applied to increase the accuracy of xB . However, a row check has revealed that the resulting solution does not satisfy the current constraints Ax-s=0 sufficiently well.
This probably means that the current basis is very ill-conditioned. If there are some linear constraints and variables, try Scale Option=1 if scaling has not yet been used.
For certain highly structured basis matrices (notably those with band structure), a systematic growth may occur in the factor U . Consult the description of Umax and Growth in Section 13.4 and set the LU Factor Tolerance to 2.0 (or possibly even smaller, but not less than 1.0).
5. | The first factorization attempt will have found the basis to be structurally or numerically singular. (Some diagonals of the triangular matrix U were respectively zero or smaller than a certain tolerance.) The associated variables are replaced by slacks and the modified basis is refactorized, but singularity persists. This must mean that the problem is badly scaled, or the LU Factor Tolerance is too much larger than 1.0. This is highly unlikely to occur.
IFAIL=8
User-supplied function computes incorrect constraint derivatives.
User-supplied function computes incorrect objective derivatives.
If the message refers to the derivatives of the objective function, then a check has been made on some individual elements of the objective gradient array at the first point that satisfies the linear constraints. At least one component GRADj is being set to a value that disagrees markedly with its associated forward-difference estimate ∂F ∂xj . (The relative difference between the computed and estimated values is 1.0 or more.) This exit is a safeguard, since E04WDF will usually fail to make progress when the computed gradients are seriously inaccurate. In the process it may expend considerable effort before terminating with IFAIL=7.
Check the function and gradient computation very carefully in OBJFUN. A simple omission could explain everything. If F or a component ∂F ∂xj is very large, then give serious thought to scaling the function or the nonlinear variables.
If you feel certain that the computed GRAD j is correct (and that the forward-difference estimate is therefore wrong), you can specify Verify Level=0 to prevent individual elements from being checked. However, the optimization procedure may have difficulty.
If the message refers to derivatives of the constraints, then at least one of the computed constraint derivatives is significantly different from an estimate obtained by forward-differencing the vector c x . Follow the advice given above, trying to ensure that the arrays CCON and CJAC are being set correctly in CONFUN.
IFAIL=9
Unable to proceed into undefined region of user-supplied function.
User-supplied function is undefined at the first feasible point.
User-supplied function is undefined at the initial point.
You have indicated that the problem functions are undefined by assigning the value MODE=-1 on exit from OBJFUN or CONFUN. E04WDF attempts to evaluate the problem functions closer to a point at which the functions are already known to be defined. This exit occurs if E04WDF is unable to find a point at which the functions are defined. This will occur in the case of:
– undefined functions with no recovery possible;
– undefined functions at the first point;
– undefined functions at the first feasible point; or
– undefined functions when checking derivatives.
IFAIL=10
User-supplied constraint function requested termination.
User-supplied objective function requested termination.
You have indicated the wish to terminate solution of the current problem by setting MODE to a value < -1 on exit from OBJFUN or CONFUN.
IFAIL=11
Internal error: memory allocation failed when attempting to allocate workspace sizes value and value. Please contact NAG.
IFAIL=12
Internal memory allocation was insufficient. Please contact NAG.
IFAIL=13
An error has occurred in the basis package, perhaps indicating incorrect setup of arrays. Set the optional parameter Print File and examine the output carefully for further information.
IFAIL=14
An unexpected error has occurred. Set the optional parameter Print File and examine the output carefully for further information.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

If IFAIL=0 on exit, then the vector returned in the array X is an estimate of the solution to an accuracy of approximately Major Optimality Tolerance.

8 Parallelism and Performance

E04WDF makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

This section describes the final output produced by E04WDF. Intermediate and other output are given in Section 13.

9.1 The Final Output

If Print File > 0 , the final output, including a listing of the status of every variable and constraint will be sent to the Print File. The following describes the output for each variable. A full stop (.) is printed for any numerical value that is zero.
Variable | gives the name (Variable) and index j, for j=1,2,…,n, of the variable.
State gives the state of the variable (FR if neither bound is in the working set, EQ if a fixed variable, LL if on its lower bound, UL if on its upper bound, TF if temporarily fixed at its current value). If Value lies outside the upper or lower bounds by more than the Feasibility Tolerance, State will be ++ or -- respectively. (The latter situation can occur only when there is no feasible point for the bounds and linear constraints.)
A key is sometimes printed before State.
A | Alternative optimum possible. The variable is active at one of its bounds, but its Lagrange multiplier is essentially zero. This means that if the variable were allowed to start moving away from its bound then there would be no change to the objective function. The values of the other free variables might change, giving a genuine alternative solution. However, if there are any degenerate variables (labelled D), the actual change might prove to be zero, since one of them could encounter a bound immediately. In either case the values of the Lagrange multipliers might also change.
D | Degenerate. The variable is free, but it is equal to (or very close to) one of its bounds.
I | Infeasible. The variable is currently violating one of its bounds by more than the Feasibility Tolerance.
Value | is the value of the variable at the final iteration.
Lower bound | is the lower bound specified for the variable. None indicates that BL j≤-bigbnd.
Upper bound | is the upper bound specified for the variable. None indicates that BU j≥bigbnd.
Lagr multiplier | is the Lagrange multiplier for the associated bound. This will be zero if State is FR unless BL j≤-bigbnd and BU j≥bigbnd, in which case the entry will be blank. If x is optimal, the multiplier should be non-negative if State is LL and non-positive if State is UL.
Slack | is the difference between the variable Value and the nearer of its (finite) bounds BL j and BU j. A blank entry indicates that the associated variable is not bounded (i.e., BL j≤-bigbnd and BU j≥bigbnd).
The meaning of the output for linear and nonlinear constraints is the same as that given above for variables, with BL j and BU j replaced by BL n+j and BU n+j respectively, and with the following changes in the heading:
Linear constrnt | gives the name (lincon) and index j, for j=1,2,…,nL, of the linear constraint.
Nonlin constrnt | gives the name (nlncon) and index (j-nL), for j=nL+1,…,nL+nN, of the nonlinear constraint.
Note that movement off a constraint (as opposed to a variable moving away from its bound) can be interpreted as allowing the entry in the Slack column to become positive.
Numerical values are output with a fixed number of digits; they are not guaranteed to be accurate to this precision.

10 Example

This example is based on Problem 71 in Hock and Schittkowski (1981) and involves the minimization of the nonlinear function
F x=x 1x 4 x 1+x 2+x 3+x 3
subject to the bounds
1≤x 1≤ 5 1≤x 2≤ 5 1≤x 3≤ 5 1≤x 4≤ 5,
to the general linear constraint
x 1+x 2+x 3+x 4≤20,
and to the nonlinear constraints
x 12+x 22+x 32+x 42≤ 40, x 1x 2x 3x 4≥ 25.
The initial point, which is infeasible, is
x 0 = 1,5,5,1 T ,
with F x 0=16.
The optimal solution (to five figures) is
x*=1.0,4.7430,3.8211,1.3794 T,
and F x*=17.014. One bound constraint and both nonlinear constraints are active at the solution.

10.1 Program Text

Program Text (e04wdfe.f90)

10.2 Program Data

Program Data (e04wdfe.d)

10.3 Program Results

Program Results (e04wdfe.r)

Note: the remainder of this document is intended for more advanced users. Section 11 contains a detailed description of the algorithm which may be needed in order to understand Sections 12 and 13. Section 12 describes the optional parameters which may be set by calls to E04WFF, E04WGF and/or E04WHF. Section 13 describes the quantities which can be requested to monitor the course of the computation.

11 Algorithmic Details

Here we summarise the main features of the SQP algorithm used in E04WDF and introduce some terminology used in the description of the subroutine and its arguments. The SQP algorithm is fully described in Gill et al. (2002).

11.1 Constraints and Slack Variables

The upper and lower bounds on the nL + nN components of AL x c x are said to define the general constraints of the problem. E04WDF converts the general constraints to equalities by introducing a set of slack variables s = s 1,s 2,…, s nL + nN T . For example, the linear constraint 5 ≤ 2 x 1 + 3 x 2 ≤ ∞ is replaced by 2 x 1 + 3 x 2 - s 1 = 0 together with the bounded slack 5 ≤ s 1 ≤ ∞ . The minimization problem (1) can therefore be written in the equivalent form
minimize x,s F x  subject to ​ AL x c x - s = 0 ,  l ≤ x s ≤ u . (2)
The general constraints become the equalities AL x - sL = 0 and c x - sN = 0 , where sL and sN are the linear and nonlinear slacks.

11.2 Major Iterations

The basic structure of the SQP algorithm involves major and minor iterations. The major iterations generate a sequence of iterates xk that satisfy the linear constraints and converge to a point that satisfies the nonlinear constraints and the first-order conditions for optimality. At each iterate xk a QP subproblem is used to generate a search direction towards the next iterate x k+1 . The constraints of the subproblem are formed from the linear constraints AL x - sL = 0 and the linearized constraint
c xk + c′ xk x-xk - sN = 0 , (3)
where c′ xk denotes the Jacobian matrix, whose elements are the first derivatives of c x evaluated at xk . The QP constraints therefore comprise the nL + nN linear constraints
AL x - sL = 0 , c′ xk x - sN = -c xk + c′ xk xk , (4)
where x and s are bounded above and below by u and l as before. If the nL + nN × n matrix A and nL + nN -vector b are defined as
A = AL c′ xk  and  b = 0 -c xk + c′ xk xk , (5)
then the QP subproblem can be written as
minimize x,s q x,xk = gkT x-xk + 12 x-xk Hk x-xk  subject to ​ Ax - s = b ,  l ≤ x s ≤ u , (6)
where q x,xk is a quadratic approximation to a modified Lagrangian function (see Gill et al. (2002)). The matrix Hk is a quasi-Newton approximation to the Hessian of the Lagrangian. A BGFS update is applied after each major iteration. If some of the variables enter the Lagrangian linearly the Hessian will have some zero rows and columns. If the nonlinear variables appear first, then only the leading nN rows and columns of the Hessian need to be approximated.

11.3 Minor Iterations

Solving the QP subproblem is itself an iterative procedure. Here, the iterations of the QP solver E04NQF form the minor iterations of the SQP method. E04NQF uses a reduced-Hessian active-set method implemented as a reduced-gradient method. At each minor iteration, the constraints Ax-s=b are partitioned into the form
B xB + S xS + N xN = b , (7)
where the basis matrix B is square and nonsingular, and the matrices S and N are the remaining columns of A -I . The vectors xB , xS and xN are the associated basic, superbasic and nonbasic variables respectively; they are a permutation of the elements of x and s . At a QP subproblem, the basic and superbasic variables will lie somewhere between their bounds, while the nonbasic variables will normally be equal to one of their bounds. At each iteration, xS is regarded as a set of independent variables that are free to move in any desired direction, namely one that will improve the value of the QP objective (or the sum of infeasibilities). The basic variables are then adjusted in order to ensure that x,s continues to satisfy Ax-s=b . The number of superbasic variables ( nS , say) therefore indicates the number of degrees of freedom remaining after the constraints have been satisfied. In broad terms, nS is a measure of how nonlinear the problem is. In particular, nS will always be zero for LP problems.
If it appears that no improvement can be made with the current definition of B , S and N , a nonbasic variable is selected to be added to S , and the process is repeated with the value of nS increased by one. At all stages, if a basic or superbasic variable encounters one of its bounds, the variable is made nonbasic and the value of nS is decreased by one.
Associated with each of the nL + nN equality constraints Ax-s=b are the dual variables π . Similarly, each variable in x,s has an associated reduced gradient dj . The reduced gradients for the variables x are the quantities g-AT π , where g is the gradient of the QP objective, and the reduced gradients for the slacks are the dual variables π . The QP subproblem is optimal if dj≥0 for all nonbasic variables at their lower bounds, dj≤0 for all nonbasic variables at their upper bounds, and dj=0 for other variables, including superbasics. In practice, an approximate QP solution x^k,s^k,π^k is found by relaxing these conditions.

11.4 The Merit Function

After a QP subproblem has been solved, new estimates of the solution are computed using a linesearch on the augmented Lagrangian merit function
M x,s,π = F x - πT c x - sN + 12 c x - sN T D c x - sN , (8)
where D is a diagonal matrix of penalty parameters D ii ≥ 0 , and π now refers to dual variables for the nonlinear constraints in (1). If xk,sk,πk denotes the current solution estimate and x^k,s^k,π^k denotes the QP solution, the linesearch determines a step αk 0<αk≤1 such that the new point
x k+1 s k+1 π k+1 = xk sk πk + αk x^k - xk s^k - sk π^k - πk (9)
gives a sufficient decrease in the merit function M . When necessary, the penalties in D are increased by the minimum-norm perturbation that ensures descent for M (see Gill et al. (1992)). The value of sN is adjusted to minimize the merit function as a function of s before the solution of the QP subproblem (see Gill et al. (1986) and Eldersveld (1991)).

11.5 Treatment of Constraint Infeasibilities

E04WDF makes explicit allowance for infeasible constraints. First, infeasible linear constraints are detected by solving the linear program
minimize x,v,w eT v+w  subject to ​ l ≤ x AL x - v + w ≤ u ,  v≥0 ,  w≥0 , (10)
where e is a vector of ones, and the nonlinear constraint bounds are temporarily excluded from l and u . This is equivalent to minimizing the sum of the general linear constraint violations subject to the bounds on x . (The sum is the ℓ 1 -norm of the linear constraint violations. In the linear programming literature, the approach is called elastic programming.)
The linear constraints are infeasible if the optimal solution of (10) has v≠0 or w≠0 . E04WDF then terminates without computing the nonlinear functions.
Otherwise, all subsequent iterates satisfy the linear constraints. (Such a strategy allows linear constraints to be used to define a region in which the functions can be safely evaluated.) E04WDF proceeds to solve nonlinear problems as given, using search directions obtained from the sequence of QP subproblems (see (6)).
If a QP subproblem proves to be infeasible or unbounded (or if the dual variables π for the nonlinear constraints become large), E04WDF enters ‘elastic’ mode and thereafter solves the problem
minimize x,v,w F x + γ eT v+w  subject to ​ l ≤ x AL x c x -v+w ≤ u ,  v≥0 ,  w≥0 , (11)
where γ is a non-negative argument (the elastic weight), and F x + γ eT v+w is called a composite objective (the ℓ 1 penalty function for the nonlinear constraints).
The value of γ may increase automatically by multiples of 10 if the optimal v and w continue to be nonzero. If γ is sufficiently large, this is equivalent to minimizing the sum of the nonlinear constraint violations subject to the linear constraints and bounds.
The initial value of γ is controlled by the optional parameter Elastic Weight.

12 Optional Parameters

Several optional parameters in E04WDF define choices in the problem specification or the algorithm logic. In order to reduce the number of formal arguments of E04WDF these optional parameters have associated default values that are appropriate for most problems. Therefore, you need only specify those optional parameters whose values are to be different from their default values.
The remainder of this section can be skipped if you wish to use the default values for all optional parameters.
The following is a list of the optional parameters available. A full description of each optional parameter is provided in Section 12.1.
  • Backup Basis File
  • Central Difference Interval
  • Check Frequency
  • Cold Start
  • Crash Option
  • Crash Tolerance
  • Defaults
  • Derivative Level
  • Derivative Linesearch
  • Difference Interval
  • Dump File
  • Elastic Weight
  • Expand Frequency
  • Factorization Frequency
  • Feasibility Tolerance
  • Feasible Point
  • Function Precision
  • Hessian Frequency
  • Hessian Full Memory
  • Hessian Limited Memory
  • Hessian Updates
  • Infinite Bound Size
  • Insert File
  • Iterations Limit
  • Linesearch Tolerance
  • List
  • Load File
  • LU Complete Pivoting
  • LU Density Tolerance
  • LU Factor Tolerance
  • LU Partial Pivoting
  • LU Rook Pivoting
  • LU Singularity Tolerance
  • LU Update Tolerance
  • Major Feasibility Tolerance
  • Major Iterations Limit
  • Major Optimality Tolerance
  • Major Print Level
  • Major Step Limit
  • Maximize
  • Minimize
  • Minor Feasibility Tolerance
  • Minor Iterations Limit
  • Minor Print Level
  • New Basis File
  • New Superbasics Limit
  • Nolist
  • Nonderivative Linesearch
  • Old Basis File
  • Partial Price
  • Pivot Tolerance
  • Print File
  • Print Frequency
  • Proximal Point Method
  • Punch File
  • QPSolver CG
  • QPSolver Cholesky
  • QPSolver QN
  • Reduced Hessian Dimension
  • Save Frequency
  • Scale Option
  • Scale Print
  • Scale Tolerance
  • Solution File
  • Start Constraint Check At Variable
  • Start Objective Check At Variable
  • Stop Constraint Check At Variable
  • Stop Objective Check At Variable
  • Summary File
  • Summary Frequency
  • Superbasics Limit
  • Suppress Parameters
  • System Information No
  • System Information Yes
  • Timing Level
  • Unbounded Objective
  • Unbounded Step Size
  • Verify Level
  • Violation Limit
  • Warm Start
Optional parameters may be specified by calling one, or more, of the routines E04WEF, E04WFF and E04WGF before a call to E04WDF.
E04WEF reads options from an external options file, with Begin and End as the first and last lines respectively and each intermediate line defining a single optional parameter. For example,
Begin
   Print Level = 5
End
The call
 CALL E04WEF (ISPECS, IW, RW, IFAIL)
can then be used to read the file on unit ISPECS. IFAIL will be zero on successful exit. E04WEF should be consulted for a full description of this method of supplying optional parameters.
E04WFF, E04WGF or E04WHF can be called to supply options directly, one call being necessary for each optional parameter. E04WFF, E04WGF or E04WHF should be consulted for a full description of this method of supplying optional parameters.
All optional parameters not specified by you are set to their default values. Optional parameters specified by you are unaltered by E04WDF (unless they define invalid values) and so remain in effect for subsequent calls to E04WDF, unless altered by you.

12.1 Description of the Optional Parameters

For each option, we give a summary line, a description of the optional parameter and details of constraints.
The summary line contains:
  • the keywords, where the minimum abbreviation of each keyword is underlined (if no characters of an optional qualifier are underlined, the qualifier may be omitted);
  • a parameter value, where the letters a, i and r denote options that take character, integer and real values respectively;
  • the default value, where the symbol ε is a generic notation for machine precision (see X02AJF), and εr denotes the relative precision of the objective function Function Precision, and bigbnd signifies the value of Infinite Bound Size.
Keywords and character values are case and white space insensitive.
Central Difference Interval r Default =εr 13
When Derivative Level < 3 , the central-difference interval r is used near an optimal solution to obtain more accurate (but more expensive) estimates of gradients. Twice as many function evaluations are required compared to forward differencing. The interval used for the j th variable is hj=r 1+ xj . The resulting derivative estimates should be accurate to O r 2 , unless the functions are badly scaled.
If you supply a value for this optional parameter, a small value between 0.0 and 1.0 is appropriate.
Check Frequency i Default =60
Every i th minor iteration after the most recent basis factorization, a numerical test is made to see if the current solution x satisfies the general linear constraints (the linear constraints and the linearized nonlinear constraints, if any). The constraints are of the form Ax-s=b , where s is the set of slack variables. To perform the numerical test, the residual vector r=b-Ax+s is computed. If the largest component of r is judged to be too large, the current basis is refactorized and the basic variables are recomputed to satisfy the general constraints more accurately. If i≤0, the value of i=99999999 is used and effectively no checks are made.
Check Frequency=1 is useful for debugging purposes, but otherwise this option should not be needed.
Cold Start Default
Warm Start
This option controls the specification of the initial working set in the procedure for finding a feasible point for the linear constraints and bounds and in the first QP subproblem thereafter. With a Cold Start, the first working set is chosen by E04WDF based on the values of the variables and constraints at the initial point. Broadly speaking, the initial working set will include equality constraints and bounds or inequality constraints that violate or ‘nearly’ satisfy their bounds (to within Crash Tolerance).
With a Warm Start, you must set the ISTATE array and define CLAMDA and H as discussed in Section 5. ISTATE values associated with bounds and linear constraints determine the initial working set of the procedure to find a feasible point with respect to the bounds and linear constraints. ISTATE values associated with nonlinear constraints determine the initial working set of the first QP subproblem after such a feasible point has been found. E04WDF will override your specification of ISTATE if necessary, so that a poor choice of the working set will not cause a fatal error. For instance, any elements of ISTATE which are set to -2, -1​ or ​4 will be reset to zero, as will any elements which are set to 3 when the corresponding elements of BL and BU are not equal. A warm start will be advantageous if a good estimate of the initial working set is available – for example, when E04WDF is called repeatedly to solve related problems.
Crash Option i Default =3
Crash Tolerance r Default =0.1
If a Cold Start is specified, an internal Crash procedure is used to select an initial basis from certain rows and columns of the constraint matrix A -I . The optional parameter Crash Option i determines which rows and columns of A are eligible initially, and how many times the Crash procedure is called. Columns of -I are used to pad the basis where necessary.
i | Meaning
0 | The initial basis contains only slack variables: B=I.
1 | The Crash procedure is called once, looking for a triangular basis in all rows and columns of A.
2 | The Crash procedure is called twice (if there are nonlinear constraints). The first call looks for a triangular basis in linear rows, and the iteration proceeds with simplex iterations until the linear constraints are satisfied. The Jacobian is then evaluated for the first major iteration and the Crash procedure is called again to find a triangular basis in the nonlinear rows (retaining the current basis for linear rows).
3 | The Crash procedure is called up to three times (if there are nonlinear constraints). The first two calls treat linear equalities and linear inequalities separately. As before, the last call treats nonlinear rows before the first major iteration.
If i≥1 , certain slacks on inequality rows are selected for the basis first. (If i≥2 , numerical values are used to exclude slacks that are close to a bound). The Crash procedure then makes several passes through the columns of A , searching for a basis matrix that is essentially triangular. A column is assigned to ‘pivot’ on a particular row if the column contains a suitably large element in a row that has not yet been assigned. (The pivot elements ultimately form the diagonals of the triangular basis.) For remaining unassigned rows, slack variables are inserted to complete the basis.
The Crash Tolerance r allows the starting Crash procedure to ignore certain ‘small’ nonzeros in each column of A . If amax is the largest element in column j , other nonzeros of a ij in the columns are ignored if a ij ≤ amax × r . (To be meaningful, r must be in the range 0≤r<1 .)
When r>0.0 , the basis obtained by the Crash procedure may not be strictly triangular, but it is likely to be nonsingular and almost triangular. The intention is to obtain a starting basis containing more columns of A and fewer (arbitrary) slacks. A feasible solution may be reached sooner on some problems.
For example, suppose the first m columns of A form the matrix shown under LU Factor Tolerance; i.e., a tridiagonal matrix with entries -1, 4, -1. To help the Crash procedure choose all m columns for the initial basis, we would specify a Crash Tolerance of r for some value of r>0.5.
Defaults
This special keyword may be used to reset all optional parameters to their default values.
Derivative Level i Default =3
Optional parameter Derivative Level specifies which nonlinear function gradients are known analytically and will be supplied to E04WDF by user-supplied subroutines OBJFUN and CONFUN.
i | Meaning
3 | All objective and constraint gradients are known.
2 | All constraint gradients are known, but some or all components of the objective gradient are unknown.
1 | The objective gradient is known, but some or all of the constraint gradients are unknown.
0 | Some components of the objective gradient are unknown and some of the constraint gradients are unknown.
The value i=3 should be used whenever possible. It is the most reliable and will usually be the most efficient.
If i=0 or 2 , E04WDF will estimate the missing components of the objective gradient, using finite differences. This may simplify the coding of OBJFUN. However, it could increase the total run-time substantially (since a special call to OBJFUN is required for each missing element), and there is less assurance that an acceptable solution will be located. If the nonlinear variables are not well scaled, it may be necessary to specify a non-default optional parameter Difference Interval.
If i=0 or 1 , E04WDF will estimate missing elements of the Jacobian. For each column of the Jacobian, one call to CONFUN is needed to estimate all missing elements in that column, if any.
At times, central differences are used rather than forward differences. (This is not under your control.)
Derivative Linesearch Default
Nonderivative Linesearch
At each major iteration a linesearch is used to improve the merit function. Optional parameter Derivative Linesearch uses safeguarded cubic interpolation and requires both function and gradient values to compute estimates of the step αk . If some analytic derivatives are not provided, or optional parameter Nonderivative Linesearch is specified, E04WDF employs a linesearch based upon safeguarded quadratic interpolation, which does not require gradient evaluations.
A nonderivative linesearch can be slightly less robust on difficult problems, and it is recommended that the default be used if the functions and derivatives can be computed at approximately the same cost. If the gradients are very expensive relative to the functions, a nonderivative linesearch may give a significant decrease in computation time.
If Nonderivative Linesearch is selected, E04WDF signals the evaluation of the linesearch by calling OBJFUN with MODE=0. If the potential saving provided by a nonderivative linesearch is to be realised, it is essential that OBJFUN be coded so that derivatives are not computed when MODE=0.
Difference Interval r Default =εr
This alters the interval r used to estimate gradients by forward differences. It does so in the following circumstances:
– | in the interval (‘cheap’) phase of verifying the problem derivatives;
– | for verifying the problem derivatives;
– | for estimating missing derivatives.
In all cases, a derivative with respect to xj is estimated by perturbing that component of x to the value xj + r 1 + xj , and then evaluating F x or c x at the perturbed point. The resulting gradient estimates should be accurate to O r unless the functions are badly scaled. Judicious alteration of r may sometimes lead to greater accuracy.
If you supply a value for this optional parameter, a small value between 0.0 and 1.0 is appropriate.
Dump File i 1 Default =0
Load File i 2 Default =0
Optional parameters Dump File and Load File are similar to optional parameters Punch File and Insert File, but they record solution information in a manner that is more direct and more easily modified. A full description of information recorded in optional parameters Dump File and Load File is given in Gill et al. (2005a).
If i 1>0 , the last solution obtained will be output to the file with unit number i 1 .
If i 2>0 , the Load File, containing basis information, will be read. The file will usually have been output previously as a Dump File. The file will not be accessed if optional parameters Old Basis File or Insert File are specified.
Elastic Weight r Default =104
This keyword determines the initial weight γ associated with the problem (11) (see Section 11.5).
At major iteration k , if elastic mode has not yet started, a scale factor σk=1 + g xk∞ is defined from the current objective gradient. Elastic mode is then started if the QP subproblem is infeasible, or the QP dual variables are larger in magnitude than σk r . The QP is resolved in elastic mode with γ=σk r .
Thereafter, major iterations continue in elastic mode until they converge to a point that is optimal for (11) (see Section 11.5). If the point is feasible for equation (1) v=w=0 , it is declared locally optimal. Otherwise, γ is increased by a factor of 10 and major iterations continue. If γ has already reached a maximum allowable value, equation (1) is declared locally infeasible.
Expand Frequency i Default =10000
This option is part of the anti-cycling procedure designed to make progress even on highly degenerate problems.
For linear models, the strategy is to force a positive step at every iteration, at the expense of violating the bounds on the variables by a small amount. Suppose that the optional parameter Minor Feasibility Tolerance is δ . Over a period of i iterations, the tolerance actually used by E04WDF increases from 0.5 δ to δ (in steps of 0.5 δ/i ).
For nonlinear models, the same procedure is used for iterations in which there is only one superbasic variable. (Cycling can occur only when the current solution is at a vertex of the feasible region.) Thus, zero steps are allowed if there is more than one superbasic variable, but otherwise positive steps are enforced.
Increasing i helps reduce the number of slightly infeasible nonbasic variables (most of which are eliminated during a resetting procedure). However, it also diminishes the freedom to choose a large pivot element (see optional parameter Pivot Tolerance).
Factorization Frequency i Default =50
At most i basis changes will occur between factorizations of the basis matrix.
With linear programs, the basis factors are usually updated every iteration. The default i is reasonable for typical problems. Higher values up to i=100 (say) may be more efficient on well-scaled problems.
When the objective function is nonlinear, fewer basis updates will occur as an optimum is approached. The number of iterations between basis factorizations will therefore increase. During these iterations a test is made regularly (according to the optional parameter Check Frequency) to ensure that the general constraints are satisfied. If necessary the basis will be refactorized before the limit of i updates is reached.
Function Precision r Default =ε 0.8
The relative function precision εr is intended to be a measure of the relative accuracy with which the functions can be computed. For example, if F x is computed as 1000.56789 for some relevant x and if the first 6 significant digits are known to be correct, the appropriate value for εr would be 1.0E−6 .
(Ideally the functions F x or ci x should have magnitude of order 1. If all functions are substantially less than 1 in magnitude, εr should be the absolute precision. For example, if F x=1.23456789E−4 at some point and if the first 6 significant digits are known to be correct, the appropriate value for εr would be 1.0E−10 .)
The default value of εr is appropriate for simple analytic functions.
In some cases the function values will be the result of extensive computation, possibly involving a costly iterative procedure that can provide few digits of precision. Specifying an appropriate Function Precision may lead to savings, by allowing the linesearch procedure to terminate when the difference between function values along the search direction becomes as small as the absolute error in the values.
Hessian Full Memory Default if n≤75
Hessian Limited Memory Default if n>75
These options select the method for storing and updating the approximate Hessian. (E04WDF uses a quasi-Newton approximation to the Hessian of the Lagrangian. A BFGS update is applied after each major iteration.)
If Hessian Full Memory is specified, the approximate Hessian is treated as a dense matrix and the BFGS updates are applied explicitly. This option is most efficient when the number of variables n is not too large (say, less than 75). In this case, the storage requirement is fixed and one can expect 1-step Q-superlinear convergence to the solution.
Hessian Limited Memory should be used on problems where n is very large. In this case a limited-memory procedure is used to update a diagonal Hessian approximation Hr a limited number of times. (Updates are accumulated as a list of vector pairs. They are discarded at regular intervals after Hr has been reset to their diagonal.)
Hessian Frequency i Default =99999999
If optional parameter Hessian Full Memory is in effect and i BFGS updates have already been carried out, the Hessian approximation is reset to the identity matrix. (For certain problems, occasional resets may improve convergence, but in general they should not be necessary.)
Hessian Full Memory and Hessian Frequency=10 have a similar effect to Hessian Limited Memory and Hessian Updates=10 (except that the latter retains the current diagonal during resets).
Hessian Updates i Default =Hessian Frequency if Hessian Full Memory, 10 otherwise
If optional parameter Hessian Limited Memory is in effect and i BFGS updates have already been carried out, all but the diagonal elements of the accumulated updates are discarded and the updating process starts again.
Broadly speaking, the more updates stored, the better the quality of the approximate Hessian. However, the more vectors stored, the greater the cost of each QP iteration. The default value is likely to give a robust algorithm without significant expense, but faster convergence can sometimes be obtained with significantly fewer updates (e.g., i=5 ).
Infinite Bound Size r Default =1020
If r>0, r defines the ‘infinite’ bound bigbnd in the definition of the problem constraints. Any upper bound greater than or equal to bigbnd will be regarded as +∞ (and similarly any lower bound less than or equal to -bigbnd will be regarded as -∞). If r<0, the default value is used.
Iterations Limit i Default = max 10000, 10 max n,nL+nN
The value of i specifies the maximum number of minor iterations allowed (i.e., iterations of the simplex method or the QP algorithm), summed over all major iterations. (See also the description of the optional parameter Minor Iterations Limit.)
Linesearch Tolerance r Default =0.9
This tolerance, r , controls the accuracy with which a step length will be located along the direction of search each iteration. At the start of each linesearch a target directional derivative for the merit function is identified. This parameter determines the accuracy to which this target value is approximated, and it must be a value in the range 0.0≤r≤1.0 .
The default value r=0.9 requests just moderate accuracy in the linesearch.
If the nonlinear functions are cheap to evaluate, a more accurate search may be appropriate; try r=0.1 , ​ 0.01 ​ or ​ 0.001 .
If the nonlinear functions are expensive to evaluate, a less accurate search may be appropriate. If all gradients are known, try r=0.99 . (The number of major iterations might increase, but the total number of function evaluations may decrease enough to compensate.)
If not all gradients are known, a moderately accurate search remains appropriate. Each search will require only 1–5 function values (typically), but many function calls will then be needed to estimate missing gradients for the next iteration.
Nolist Default
List
For E04WDF, normally each optional parameter specification is printed as it is supplied. Optional parameter Nolist may be used to suppress the printing and optional parameter List may be used to turn on printing.
LU Density Tolerance r 1 Default =0.6
LU Singularity Tolerance r 2 Default =ε 23
The density tolerance, r 1 , is used during LU factorization of the basis matrix B. Columns of L and rows of U are formed one at a time, and the remaining rows and columns of the basis are altered appropriately. At any stage, if the density of the remaining matrix exceeds r 1 , the Markowitz strategy for choosing pivots is terminated, and the remaining matrix is factored by a dense LU procedure. Raising the density tolerance towards 1.0 may give slightly sparser LU factors, with a slight increase in factorization time.
The singularity tolerance, r 2 , helps guard against ill-conditioned basis matrices. After B is refactorized, the diagonal elements of U are tested as follows: if u jj ≤ r 2 or u jj < r 2 maxi u ij , the j th column of the basis is replaced by the corresponding slack variable. (This is most likely to occur after a restart.)
LU Factor Tolerance r 1 Default =1.10
LU Update Tolerance r 2 Default =1.10
The values of r 1 and r 2 affect the stability of the basis factorization B=LU, during refactorization and updates respectively. The lower triangular matrix L is a product of matrices of the form
1 0 μ 1
where the multipliers μ will satisfy μ≤ri. The default values of r 1 and r 2 usually strike a good compromise between stability and sparsity. They must satisfy r 1, r 2≥1.0.
For large and relatively dense problems, r 1=10.0​ or ​5.0 (say) may give a useful improvement in stability without impairing sparsity to a serious degree.
For certain very regular structures (e.g., band matrices) it may be necessary to reduce r 1​ and/or ​r 2 in order to achieve stability. For example, if the columns of A include a sub-matrix of the form
4 -1 -1 4 -1 -1 4 -1 … … … -1 4 -1 -1 4 ,
one should set both r 1 and r 2 to values in the range 1.0≤ri<4.0.
LU Partial Pivoting Default
LU Complete Pivoting
LU Rook Pivoting
The LU factorization implements a Markowitz-type search for pivots that locally minimize the fill-in subject to a threshold pivoting stability criterion. The default option is to use threshhold partial pivoting. The optional parameters LU Rook Pivoting and LU Complete Pivoting are more expensive than partial pivoting but are more stable and better at revealing rank, as long as LU Factor Tolerance is not too large (say <2.0). When numerical difficulties are encountered, E04WDF automatically reduces the LU tolerance towards 1.0 and switches (if necessary) to rook or complete pivoting, before reverting to the default or specified options at the next refactorization (with System Information Yes, relevant messages are output to the Print File).
Major Feasibility Tolerance r Default = max 10-6,ε
This tolerance, r , specifies how accurately the nonlinear constraints should be satisfied. The default value is appropriate when the linear and nonlinear constraints contain data to about that accuracy.
Let vmax be the maximum nonlinear constraint violation, normalized by the size of the solution, which is required to satisfy
vmax/=maxi vi / x ≤ r , (12)
where vi is the violation of the i th nonlinear constraint i=1:nL .
In the major iteration log (see Section 13.2, vmax appears as the quantity labelled ‘Feasible’. If some of the problem functions are known to be of low accuracy, a larger Major Feasibility Tolerance may be appropriate.
Major Optimality Tolerance r Default = 2 max 10-6,ε
This tolerance, r , specifies the final accuracy of the dual variables. On successful termination, E04WDF will have computed a solution x,s,π such that
cmax=maxj cj / π ≤ r , (13)
where cj is an estimate of the complementarity slackness for variable j where j=1:n+nL+nN. The values ci are computed from the final QP solution using the reduced gradients dj=gj - πT aj (where gj is the j th component of the objective gradient, aj is the associated column of the constraint matrix A -I , and π is the set of QP dual variables):
cj = - dj min xj - lj ,1 if ​ dj≥0 ; -dj min uj - xj ,1 if ​ dj<0 . (14)
In the Print File, cmax appears as the quantity labelled ‘Optimal’.
Major Iterations Limit i Default = max 1000, 3 max n, nL + nN
This is the maximum number of major iterations allowed. It is intended to guard against an excessive number of linearizations of the constraints. If i=0, optimality and feasibility are checked.
Major Print Level i Default =000001
This controls the amount of output to the optional parameters Print File and Summary File at each major iteration. Major Print Level=0 suppresses most output, except for error messages. Major Print Level=1 gives normal output for linear and nonlinear problems, and Major Print Level=11 gives additional details of the Jacobian factorization that commences each major iteration.
In general, the value being specified may be thought of as a binary number of the form
Major Print Level JFDXbs
where each letter stands for a digit that is either 0 or 1 as follows:
s | a single line that gives a summary of each major iteration. (This entry in JFDXbs is not strictly binary since the summary line is printed whenever JFDXbs ≥ 1 );
b | basis statistics, i.e., information relating to the basis matrix whenever it is refactorized. (This output is always provided if JFDXbs ≥ 10 );
X | xk , the nonlinear variables involved in the objective function or the constraints. These appear under the heading ‘Jacobian variables’;
D | πk , the dual variables for the nonlinear constraints. These appear under the heading ‘Multiplier estimates’;
F | c xk , the values of the nonlinear constraint functions;
J | J xk , the Jacobian matrix. This appears under the heading ‘x and Jacobian’.
To obtain output of any items JFDXbs , set the corresponding digit to 1, otherwise to 0.
If J=1 , the Jacobian matrix will be output column-wise at the start of each major iteration. Column j will be preceded by the value of the corresponding variable xj and a key to indicate whether the variable is basic, superbasic or nonbasic. (Hence if J=1 , there is no reason to specify X=1 unless the objective contains more nonlinear variables than the Jacobian.) A typical line of output is
 3 1.250000E+01 BS 1 1.00000E+00 4 2.00000E+00
which would mean that x 3 is basic at value 12.5, and the third column of the Jacobian has elements of 1.0 and 2.0 in rows 1 and 4.
Major Step Limit r Default =2.0
This parameter limits the change in x during a linesearch. It applies to all nonlinear problems, once a ‘feasible solution’ or ‘feasible subproblem’ has been found. A linesearch determines a step α over the range 0<α≤β , where β is 1 if there are nonlinear constraints, or is the step to the nearest upper or lower bound on x if all the constraints are linear. Normally, the first step length tried is α 1 = min 1,β .
1. | In some cases, such as f x=a e bx or f x=a xb , even a moderate change in the components of x can lead to floating-point overflow. The parameter r is therefore used to define a limit β-=r 1+x / p (where p is the search direction), and the first evaluation of f x is at the potentially smaller step length α 1 = min 1,β-,β .
2. | Wherever possible, upper and lower bounds on x should be used to prevent evaluation of nonlinear functions at meaningless points. The optional parameter Major Step Limit provides an additional safeguard. The default value r=2.0 should not affect progress on well behaved problems, but setting r=0.1​ or ​0.01 may be helpful when rapidly varying functions are present. A ‘good’ starting point may be required. An important application is to the class of nonlinear least squares problems.
3. | In cases where several local optima exist, specifying a small value for r may help locate an optimum near the starting point.
Minimize Default
Maximize
Feasible Point
The keywords Minimize and Maximize specify the required direction of optimization. It applies to both linear and nonlinear terms in the objective.
The keyword Feasible Point means ‘Ignore the objective function, while finding a feasible point for the linear and nonlinear constraints’. It can be used to check that the nonlinear constraints are feasible without altering the call to E04WDF.
Minor Feasibility Tolerance
Feasibility Tolerance r Default = max 10-6,ε
E04WDF tries to ensure that all variables eventually satisfy their upper and lower bounds to within this tolerance, r . This includes slack variables. Hence, general linear constraints should also be satisfied to within r .
Feasibility with respect to nonlinear constraints is judged by the optional parameter Major Feasibility Tolerance (not by r ).
If the bounds and linear constraints cannot be satisfied to within r , the problem is declared infeasible. If the corresponding sum of infeasibilities is quite small, it may be appropriate to raise r by a factor of 10 or 100. Otherwise, some error in the data should be suspected.
Nonlinear functions will be evaluated only at points that satisfy the bounds and linear constraints. If there are regions where a function is undefined, every attempt should be made to eliminate these regions from the problem.
For example, if f x=x 1 + log x 2 , it is essential to place lower bounds on both variables. If r=1.0E−6 , the bounds x 1 ≥ 10-5 and x 2 ≥ 10-4 might be appropriate. (The log singularity is more serious. In general, keep x as far away from singularities as possible.)
If Scale Option ≥ 1 , feasibility is defined in terms of the scaled problem (since it is then more likely to be meaningful).
In reality, E04WDF uses r as a feasibility tolerance for satisfying the bounds on x and s in each QP subproblem. If the sum of infeasibilities cannot be reduced to zero, the QP subproblem is declared infeasible. E04WDF is then in elastic mode thereafter (with only the linearized nonlinear constraints defined to be elastic). See the description of the optional parameter Elastic Weight.
Minor Iterations Limit i Default =500
If the number of minor iterations for the optimality phase of the QP subproblem exceeds i , then all nonbasic QP variables that have not yet moved are frozen at their current values and the reduced QP is solved to optimality.
Note that more than i minor iterations may be necessary to solve the reduced QP to optimality. These extra iterations are necessary to ensure that the terminated point gives a suitable direction for the linesearch.
In the major iteration log (see Section 13.2) a t at the end of a line indicates that the corresponding QP was artificially terminated using the limit i .
Compare with the optional parameter Iterations Limit, which defines an independent absolute limit on the total number of minor iterations (summed over all QP subproblems).
Minor Print Level i Default =1
This controls the amount of output to the Print File and the Summary File during solution of the QP subproblems. The value of i has the following effect:
i | Output
0 | No minor iteration output except error messages.
≥1 | A single line of output at each minor iteration (controlled by optional parameters Print Frequency and Summary Frequency.
≥10 | Basis factorization statistics generated during the periodic refactorization of the basis (see the optional parameter Factorization Frequency). Statistics for the first factorization each major iteration are controlled by the optional parameter Major Print Level.
New Basis File i 1 Default =0
Backup Basis File i 2 Default =0
Save Frequency i 3 Default =100
New Basis File and Backup Basis File are sometimes referred to as basis maps. They contain the most compact representation of the state of each variable. They are intended for restarting the solution of a problem at a point that was reached by an earlier run. For nontrivial problems, it is advisable to save basis maps at the end of a run, in order to restart the run if necessary.
If i 1>0 , a basis map will be saved on the file associated with unit i 1 every i 3 th iteration. The first record of the file will contain the word PROCEEDING if the run is still in progress. A basis map will also be saved at the end of a run, with some other word indicating the final solution status.
Use of i 2>0 is intended as a safeguard against losing the results of a long run. Suppose that a New Basis File is being saved every 100 (Save Frequency) iterations, and that E04WDF is about to save such a basis at iteration 2000. It is conceivable that the run may be interrupted during the next few milliseconds (in the middle of the save). In this case the Basis file will be corrupted and the run will have been essentially wasted.
To eliminate this risk, both a New Basis File and a Backup Basis File may be specified. The following would be suitable for the above example:
 Backup Basis File 11
 New Basis File 12
The current basis will then be saved every 100 iterations, first on the file associated with unit 12 and then immediately on the file associated with unit 11. If the run is interrupted at iteration 2000 during the save on the file associated with unit 12, there will still be a usable basis on the file associated with unit 11 (corresponding to iteration 1900).
Note that a new basis will be saved in New Basis File at the end of a run if it terminates normally, but it will not be saved in Backup Basis File. In the above example, if an optimum solution is found at iteration 2050 (or if the iteration limit is 2050), the final basis in the file associated with unit 12 will correspond to iteration 2050, but the last basis saved in the file associated with unit 11 will be the one for iteration 2000.
A full description of information recorded in New Basis File and Backup Basis File is given in Gill et al. (2005a).
New Superbasics Limit i Default =99
This option causes early termination of the QP subproblems if the number of free variables has increased significantly since the first feasible point. If the number of new superbasics is greater than i , the nonbasic variables that have not yet moved are frozen and the resulting smaller QP is solved to optimality.
In the major iteration log (see Section 13.1), a t at the end of a line indicates that the QP was terminated early in this way.
Old Basis File i Default =0
If i>0 , the basis maps information will be obtained from this file. The file will usually have been output previously as a New Basis File or Backup Basis File. A full description of information recorded in New Basis File and Backup Basis File is given in Gill et al. (2005a).
The file will not be acceptable if the number of rows or columns in the problem has been altered.
Partial Price i Default =1
This parameter is recommended for large problems that have significantly more variables than constraints. It reduces the work required for each ‘pricing’ operation (where a nonbasic variable is selected to become superbasic). When i=1 , all columns of the constraint matrix A -I are searched. Otherwise, A and I are partitioned to give i roughly equal segments Aj and Ij , for j=1,2,…,i. If the previous pricing search was successful on A j-1 and I j-1 , the next search begins on the segments Aj and Ij . (All subscripts here are modulo i .) If a reduced gradient is found that is larger than some dynamic tolerance, the variable with the largest such reduced gradient (of appropriate sign) is selected to become superbasic. If nothing is found, the search continues on the next segments A j+1 and I j+1 , and so on.
For time-stage models having t time periods, Partial Price t (or t/2 or t/3 ) may be appropriate.
Pivot Tolerance r Default =ε 23
During the solution of QP subproblems, the pivot tolerance is used to prevent columns entering the basis if they would cause the basis to become almost singular.
When x changes to x+αp for some search direction p , a ‘ratio test’ determines which component of x reaches an upper or lower bound first. The corresponding element of p is called the pivot element. Elements of p are ignored (and therefore cannot be pivot elements) if they are smaller than the pivot tolerance r .
It is common for two or more variables to reach a bound at essentially the same time. In such cases, the Minor Feasibility Tolerance (say, t ) provides some freedom to maximize the pivot element and thereby improve numerical stability. Excessively small values of t should therefore not be specified. To a lesser extent, the Expand Frequency (say, f ) also provides some freedom to maximize the pivot element. Excessively large values of f should therefore not be specified.
Print File i Default =0
If i>0 , the following information is output to a file associated with unit i during the solution of each problem:
– | a listing of the optional parameters;
– | some statistics about the problem;
– | the amount of storage available for the LU factorization of the basis matrix;
– | notes about the initial basis resulting from a Crash procedure or a Basis file;
– | the iteration log;
– | basis factorization statistics;
– | the exit IFAIL condition and some statistics about the solution obtained;
– | the printed solution, if requested.
These items are described in Sections 9 and 13. Further brief output may be directed to the Summary File.
Print Frequency i Default =100
If i>0 , one line of the iteration log will be printed every i th iteration. A value such as i=10 is suggested for those interested only in the final solution. If i≤0, the value of i=99999999 is used and effectively no checks are made.
Proximal Point Method i Default =1
i=1​ or ​2 specifies minimization of x-x 0 1 or 12 x-x 0 22 when the starting point x 0 is changed to satisfy the linear constraints (where x 0 refers to nonlinear variables).
Punch File i 1 Default =0
Insert File i 2 Default =0
The Punch File from a previous run may be used as an Insert File for a later run on the same problem. A full description of information recorded in Insert File and Punch File is given in Gill et al. (2005a).
If i 1>0 , the final solution obtained will be output to the file. For linear programs, this format is compatible with various commercial systems.
If i 2>0 the Insert File containing basis information will be read from unit i 2 . The file will usually have been output previously as a Punch File. The file will not be accessed if Old Basis File is specified.
QPSolver Cholesky Default
QPSolver CG
QPSolver QN
Specifies the active-set algorithm used to solve subproblem (11) (see Section 11.5). QPSolver Cholesky holds the full Cholesky factor R of the reduced Hessian ZT HZ. As the QP iterations proceed, the dimension of R changes with the number of superbasic variables. If the number of superbasic variables needs to increase beyond the value of Reduced Hessian Dimension, the reduced Hessian cannot be stored and the solver switches to QPSolver CG. The Cholesky solver is reactivated if the number of superbasics stabilizes at a value less than Reduced Hessian Dimension.
QPSolver QN solves the QP using a quasi-Newton method. In this case, R is the factor of a quasi-Newton approximate Hessian.
QPSolver CG uses an active-set method similar to QPSolver QN, but uses the conjugate-gradient method to solve all systems involving the reduced Hessian.
The Cholesky QP solver is the most robust, but may require a significant amount of computation if there are many superbasics.
The quasi-Newton QP solver does not require computation of the exact R at the start of the subproblem in (11). It may be appropriate when the number of superbasics is large but relatively few iterations are needed to reach a solution (e.g., if E04WDF is called with a Warm Start).
The conjugate-gradient QP solver is appropriate for problems with many degrees of freedom (say, more than 2000 superbasics).
Reduced Hessian Dimension i Default = min 2000,n
This specifies that an i by i triangular matrix R (to define the reduced Hessian according to RT R = ZT HZ ) is to be available for use by the Cholesky QP solver.
Scale Option i Default =0
Scale Tolerance r Default =0.9
Scale Print
Three scale options are available as follows:
i | Meaning
0 | No scaling. This is recommended if it is known that x and the constraint matrix never have very large elements (say, larger than 100).
1 | The constraints and variables are scaled by an iterative procedure that attempts to make the matrix coefficients as close as possible to 1.0 (see Fourer (1982)). This will sometimes improve the performance of the solution procedures.
2 | The constraints and variables are scaled by the iterative procedure. Also, a certain additional scaling is performed that may be helpful if the right-hand side b or the solution x is large. This takes into account columns of A -I that are fixed or have positive lower bounds or negative upper bounds.
Optional parameter Scale Tolerance affects how many passes might be needed through the constraint matrix. On each pass, the scaling procedure computes the ratio of the largest and smallest nonzero coefficients in each column:
ρj=maxj a ij / mini a ij   a ij ≠ 0 .
If maxj ρj is less than r times its previous value, another scaling pass is performed to adjust the row and column scales. Raising r from 0.9 to 0.99 (say) usually increases the number of scaling passes through A . At most 10 passes are made. The value of r should lie in the range 0<r<1.
Scale Print causes the row scales r i and column scales c j to be printed to Print File, if System Information Yes has been specified. The scaled matrix coefficients are a- ij = a ij c j / r i, and the scaled bounds on the variables and slacks are l-j = lj / c j , u-j = uj / c j , where c j = r j-n if j>n.
Solution File i Default =0
If i>0 , the final solution will be output to file i (whether optimal or not). All numbers are printed in 1pe16.6 format.
To see more significant digits in the printed solution, it will sometimes be useful to make i refer to Print File.
Start Objective Check At Variable i Default =1
Stop Objective Check At Variable i Default =n
Start Constraint Check At Variable i Default =1
Stop Constraint Check At Variable i Default =n
These keywords take effect only if Verify Level>0. They may be used to contol the verification of gradient elements computed by function OBJFUN and/or Jacobian elements computed by function CONFUN. For eample, if the first 30 elements of the objective gradient appeared to be correct in an earlier run, so that only element 31 remains questionable, it is reasonable to specify Start Objective Check At Variable=31. If the first 30 variables appear linearly in the objective, so that the corresponding gradient elements are constant, the above choice would also be appropriate.
Summary File i 1 Default =0
Summary Frequency i 2 Default =100
If i 1>0 , a brief log will be output to the file associated with unit i 1 , including one line of information every i 2 th iteration. In an interactive environment, it is useful to direct this output to the terminal, to allow a run to be monitored online. (If something looks wrong, the run can be manually terminated.) Further details are given in Section 13.6.
Superbasics Limit i Default = n
This option places a limit on the storage allocated for superbasic variables. Ideally, i should be set slightly larger than the ‘number of degrees of freedom’ expected at an optimal solution.
For nonlinear problems, the number of degrees of freedom is often called the ‘number of independent variables’. Normally, i need not be greater than nN+1 , where nN is the number of nonlinear variables. For many problems, i may be considerably smaller than nN. This will save storage if nN is very large.
Suppress Parameters
Normally E04WDF prints the options file as it is being read, and then prints a complete list of the available keywords and their final values. The optional parameter Suppress Parameters tells E04WDF not to print the full list.
System Information No Default
System Information Yes
This option prints additional information on the progress of major and minor iterations, and Crash statistics. See Section 13.
Timing Level i Default =0
If i>0 , some timing information will be output to the Print file, if Print File>0.
Unbounded Objective r 1 Default =1.0E+15
Unbounded Step Size r 2 Default =bigbnd
These parameters are intended to detect unboundedness in nonlinear problems. During a linesearch, F is evaluated at points of the form x+αp , where x and p are fixed and α varies. If F exceeds r 1 or α exceeds r 2 , iterations are terminated with the exit message IFAIL=5.
If singularities are present, unboundedness in F x may be manifested by a floating-point overflow (during the evaluation of F x+αp ), before the test against r 1 can be made.
Unboundedness in x is best avoided by placing finite upper and lower bounds on the variables.
Verify Level i Default =0
This option refers to finite difference checks on the derivatives computed by the user-supplied routines. Derivatives are checked at the first point that satisfies all bounds and linear constraints.
i | Meaning
0 | Only a ‘cheap’ test will be performed, requiring two calls to CONFUN.
1 | Individual gradients will be checked (with a more reliable test). A key of the form OK or Bad? indicates whether or not each component appears to be correct.
2 | Individual columns of the problem Jacobian will be checked.
3 | Options 2 and 1 will both occur (in that order).
-1 | Derivative checking is disabled.
Verify Level=3 should be specified whenever a new function routine is being developed. Missing derivatives are not checked, so they result in no overhead.
Violation Limit r Default =1.0E+6
This keyword defines an absolute limit on the magnitude of the maximum constraint violation, r , after the linesearch. On completion of the linesearch, the new iterate x k+1 satisfies the condition
vi x k+1 ≤ r ​ ​ max 1, vi x 0 ,
where x 0 is the point at which the nonlinear constraints are first evaluated and vi x is the i th nonlinear constraint violation vi x = max 0, li - ci x , ci x - ui .
The effect of this violation limit is to restrict the iterates to lie in an expanded feasible region whose size depends on the magnitude of r . This makes it possible to keep the iterates within a region where the objective is expected to be well defined and bounded below. If the obective is bounded below for all values of the variables, then r may be any large positive value.

13 Description of Monitoring Information

E04WDF produces monitoring information, statistical information and information about the solution. Section 9.1 contains the final output information sent to unit Print File. This section contains other output information.

13.1 Major Iteration Log

This section describes the output to unit Print File if Major Print Level > 0 . One line of information is output every k th major iteration, where k is Print Frequency.
Label | Description
Itns | is the cumulative number of minor iterations.
Major | is the current major iteration number.
Minors | is the number of iterations required by both the feasibility and optimality phases of the QP subproblem. Generally, Minors will be 1 in the later iterations, since theoretical analysis predicts that the correct active set will be identified near the solution (see Section 11).
Step | is the step length α taken along the current search direction p . The variables x have just been changed to x + α p . On reasonably well-behaved problems, the unit step will be taken as the solution is approached.
nCon or nObj | nCon is the number of times CONFUN has been called to evaluate the nonlinear problem functions. Evaluations needed for the estimation of the derivatives by finite differences are not included. nCon is printed as a guide to the amount of work required for the linesearch. If nN , the number of nonlinear constraints, is zero, nCon does not appear, but is replaced by nObj. This quantity is the number of calls made to OBJFUN.
Feasible is the value of vmax (see (12)), the maximum component of the scaled nonlinear constraint residual (see the description of the optional parameter Major Feasibility Tolerance). The solution is regarded as acceptably feasible if Feasible is less than the Major Feasibility Tolerance. In this case, the entry is contained in parentheses.
If the constraints are linear, all iterates are feasible and this entry is not printed.
Optimal | is the value of cmax (see (13)), the maximum complementary gap (see the description of the optional parameter Major Optimality Tolerance). It is an estimate of the degree of nonoptimality of the reduced costs. Both Feasible and Optimal are small in the neighbourhood of a solution.
MeritFunction or Objective is the value of the augmented Lagrangian merit function (see (8)). This function will decrease at each iteration unless it was necessary to increase the penalty parameters (see Section 11.4). As the solution is approached, MeritFunction will converge to the value of the objective at the solution.
In elastic mode, the merit function is a composite function involving the constraint violations weighted by the elastic weight.
If the constraints are linear, this item is labelled Objective, the value of the objective function. It will decrease monotonically to its optimal value.
L+U is the number of nonzeros representing the basis factors L and U on completion of the QP subproblem.
If nonlinear constraints are present, the basis factorization B = LU is computed at the start of the first minor iteration. At this stage, L+U = lenL + lenU , where lenL (see Section 13.4) is the number of subdiagonal elements in the columns of a lower triangular matrix and lenU (see Section 13.4) is the number of diagonal and superdiagonal elements in the rows of an upper-triangular matrix.
As columns of B are replaced during the minor iterations, L+U may fluctuate up or down but, in general, will tend to increase. As the solution is approached and the minor iterations decrease towards zero, L+U will reflect the number of nonzeros in the LU factors at the start of the QP subproblem.
If the constraints are linear, refactorization is subject only to the Factorization Frequency, and L+U will tend to increase between factorizations.
BSwap | is the number of columns of the basis matrix B that were swapped with columns of S to improve the condition of B . The swaps are determined by an LU factorization of the rectangular matrix BS = B S T with stability being favoured more than sparsity.
nS | is the current number of superbasic variables.
condHz is an estimate of the condition number of RT R , itself an estimate of ZT HZ , the reduced Hessian of the Lagrangian. The condition number is the square of the ratio of the largest and smallest diagonals of the upper triangular matrix R , this being a lower bound on the condition number of RT R . condHz gives a rough indication of whether or not the optimization procedure is having difficulty. If ε is the relative machine precision being used, the SQP algorithm will make slow progress if condHz becomes as large as ε-1/2 ≈ 108 , and will probably fail to find a better solution if condHz reaches ε-3/4 ≈ 1012 .
To guard against high values of condHz, attention should be given to the scaling of the variables and the constraints. In some cases it may be necessary to add upper or lower bounds to certain variables to keep them a reasonable distance from singularities in the nonlinear functions or their derivatives.
Penalty | is the Euclidean norm of the vector of penalty parameters used in the augmented Lagrangian merit function (not printed if there are no nonlinear constraints).
The summary line may include additional code characters that indicate what happened during the course of the major iteration. These will follow the separator ‘_’ in the output.
Label | Description
c | central differences have been used to compute the unknown components of the objective and constraint gradients. A switch to central differences is made if either the linesearch gives a small step, or x is close to being optimal. In some cases, it may be necessary to re-solve the QP subproblem with the central difference gradient and Jacobian.
d | during the linesearch it was necessary to decrease the step in order to obtain a maximum constraint violation conforming to the value of Violation Limit.
D | you set MODE=-1 on exit from OBJFUN, indicating that the linesearch needed to be done with a smaller value of the step length α.
l | the norm wise change in the variables was limited by the value of the Major Step Limit. If this output occurs repeatedly during later iterations, it may be worthwhile increasing the value of Major Step Limit.
i | if E04WDF is not in elastic mode, an i signifies that the QP subproblem is infeasible. This event triggers the start of nonlinear elastic mode, which remains in effect for all subsequent iterations. Once in elastic mode, the QP subproblems are associated with the elastic problem (11) (see Section 11.5). If E04WDF is already in elastic mode, an i indicates that the minimizer of the elastic subproblem does not satisfy the linearized constraints. (In this case, a feasible point for the usual QP subproblem may or may not exist.)
M | an extra evaluation of the problem functions was needed to define an acceptable positive definite quasi-Newton update to the Lagrangian Hessian. This modification is only done when there are nonlinear constraints.
m | this is the same as M except that it was also necessary to modify the update to include an augmented Lagrangian term.
n | no positive definite BFGS update could be found. The approximate Hessian is unchanged from the previous iteration.
R | the approximate Hessian has been reset by discarding all but the diagonal elements. This reset will be forced periodically by the Hessian Frequency and Hessian Updates keywords. However, it may also be necessary to reset an ill-conditioned Hessian from time to time.
r | the approximate Hessian was reset after ten consecutive major iterations in which no BFGS update could be made. The diagonals of the approximate Hessian are retained if at least one update has been done since the last reset. Otherwise, the approximate Hessian is reset to the identity matrix.
s | a self-scaled BFGS update was performed. This update is used when the Hessian approximation is diagonal, and hence always follows a Hessian reset.
t | the minor iterations were terminated because of the Minor Iterations Limit.
T | the minor iterations were terminated because of the New Superbasics Limit.
u | the QP subproblem was unbounded.
w | a weak solution of the QP subproblem was found.
z | the Superbasics Limit was reached.

13.2 Minor Iteration Log

If Minor Print Level > 0 , one line of information is output to the Print file every k th minor iteration, where k is the specified Print Frequency. A heading is printed before the first such line following a basis factorization. The heading contains the items described below. In this description, a pricing operation is the process by which a nonbasic variable is selected to become superbasic (in addition to those already in the superbasic set). The selected variable is denoted by jq. Variable jq often becomes basic immediately. Otherwise it remains superbasic, unless it reaches its opposite bound and returns to the nonbasic set.
If Partial Price is in effect, variable jq is selected from App or Ipp , the pp th segments of the constraint matrix A -I .
Label | Description
Itn | the current iteration number.
LPmult or QPmult | is the reduced cost (or reduced gradient) of the variable jq selected by the pricing procedure at the start of the present iteration. Algebraically, the reduced gradient is dj = gj - πT aj for j = jq , where gj is the gradient of the current objective function, π is the vector of dual variables for the QP subproblem, and aj is the j th column of A -I . Note that the reduced cost is the 1-norm of the reduced-gradient vector at the start of the iteration, just after the pricing procedure.
LPstep or QPstep | is the step length α taken along the current search direction p . The variables x have just been changed to x + α p . Write Step to stand for LPStep or QPStep, depending on the problem. If a variable is made superbasic during the current iteration ( +SBS>0 ), Step will be the step to the nearest bound. During the solution of (11), the step can be greater than one only if the reduced Hessian is not positive definite.
nInf | is the number of infeasibilities after the present iteration. This number will not increase unless the iterations are in elastic mode.
SumInf | is the sum of infeasibilities after the present iteration, if nInf>0 . The value usually decreases at each nonzero Step, but if it decreases by 2 or more, SumInf may occasionally increase.
rgNorm | is the norm of the reduced-gradient vector at the start of the iteration. (It is the norm of the vector with elements dj for variables j in the superbasic set.) During the solution of subproblem (11) this norm will be approximately zero after a unit step. (The heading is not printed if the problem is linear.)
LPobjective, QPobjective or Elastic QPobj | the QP objective function after the present iteration. In elastic mode, the heading is changed to Elastic QPobj. In either case, the value printed decreases monotonically.
+SBS | is the variable jq selected by the pricing operation to be added to the superbasic set.
-SBS | is the superbasic variable chosen to become nonbasic.
-BS | is the basis variable removed (if any) to become nonbasic.
Pivot | if column aq replaces the r th column of the basis B , Pivot is the r th element of a vector y satisfying By=aq . Wherever possible, Step is chosen to avoid extremely small values of Pivot (since they cause the basis to be nearly singular). In rare cases, it may be necessary to increase the Pivot Tolerance to exclude very small elements of y from consideration during the computation of Step.
L+U | is the number of nonzeros representing the basis factors L and U . Immediately after a basis factorization B=LU , L+U is lenL+lenU, the number of subdiagonal elements in the columns of a lower triangular matrix and the number of diagonal and superdiagonal elements in the rows of an upper-triangular matrix. Further nonzeros are added to L when various columns of B are later replaced. As columns of B are replaced, the matrix U is maintained explicitly (in sparse form). The value of L will steadily increase, whereas the value of U may fluctuate up or down. Thus the value of L+U may fluctuate up or down (in general, it will tend to increase).
ncp | is the number of compressions required to recover storage in the data structure for U . This includes the number of compressions needed during the previous basis factorization.
nS | is the current number of superbasic variables. (The heading is not printed if the problem is linear.)
condHz | see Section 13.1. (The heading is not printed if the problem is linear.)

13.3 Crash Statistics

If Major Print Level ≥ 10 and System Information Yes has been specified, the following items are output to the Print file when Cold Start and no Backup Basis file is loaded. They refer to the number of columns that the Crash procedure selects during selected passes through A while searching for a triangular basis matrix.
Label | Description
Slacks | is the number of slacks selected initially.
Free cols | is the number of free columns in the basis.
Preferred | is the number of ‘preferred’ columns in the basis (i.e., ISTATE j=3 for some j≤n ).
Unit | is the number of unit columns in the basis.
Double | is the number of columns in the basis containing 2 nonzeros.
Triangle | is the number of triangular columns in the basis.
Pad | is the number of slacks used to pad the basis (to make it a nonsingular triangle).

13.4 Basis Factorization Statistics

If Major Print Level ≥ 10 , the first seven items in the list below are output to the Print file whenever the basis B or the rectangular matrix BS = B S T is factorized before solution of the next QP subproblem. See Section 12.1 for a full description of an optional parameter.
Gaussian elimination is used to compute a sparse LU factorization of B or BS , where PL PT and PUQ are lower and upper triangular matrices for some permutation matrices P and Q . Stability is ensured as described under the optional parameter LU Factor Tolerance.
If Minor Print Level ≥ 10 , the same items are printed during the QP solution whenever the current B is factorized. In addition, if System Information Yes has been specified, the entries from Elems onwards are also printed.
Label | Description
Factor | the number of factorizations since the start of the run.
Demand a code giving the reason for the present factorization, as follows:
Code | Meaning
0 | First LU factorization.
1 | The number of updates reached the Factorization Frequency.
2 | The nonzeros in the updated factors have increased significantly.
7 | Not enough storage to update factors.
10 | Row residuals too large (see the description of the optional parameter Check Frequency).
11 | Ill-conditioning has caused inconsistent results.
Itn | is the current minor iteration number.
Nonlin | is the number of nonlinear variables in the current basis B .
Linear | is the number of linear variables in B .
Slacks | is the number of slack variables in B .
B BR BS or BT factorize is the type of LU factorization.
B | periodic factorization of the basis B .
BR | more careful rank-revealing factorization of B using threshold rook pivoting. This occurs mainly at the start, if the first basis factors seem singular or ill-conditioned. Followed by a normal B factorize.
BS | BS is factorized to choose a well-conditioned B from the current B S . Followed by a normal B factorize.
BT | same as BS except the current B is tried first and accepted if it appears to be not much more ill-conditioned than after the previous BS factorize.
m | is the number of rows in B or BS .
n | is the number of columns in B or BS . Preceded by ‘=’ or ‘>’ respectively.
Elems | is the number of nonzero elements in B or BS .
Amax | is the largest nonzero in B or BS .
Density | is the percentage nonzero density of B or BS .
Merit/MerRP/MerCP | is the average Markowitz merit count for the elements chosen to be the diagonals of PUQ . Each merit count is defined to be c-1 r-1 where c and r are the number of nonzeros in the column and row containing the element at the time it is selected to be the next diagonal. Merit is the average of n such quantities. It gives an indication of how much work was required to preserve sparsity during the factorization. If LU Complete Pivoting or LU Rook Pivoting has been selected, this heading is changed to MerCP, respectively MerRP.
lenL | is the number of nonzeros in L .
L+U | is the number of nonzeros representing the basis factors L and U . Immediately after a basis factorization B=LU , L+U is lenL+lenU, the number of subdiagonal elements in the columns of a lower triangular matrix and the number of diagonal and superdiagonal elements in the rows of an upper-triangular matrix. Further nonzeros are added to L when various columns of B are later replaced. As columns of B are replaced, the matrix U is maintained explicitly (in sparse form). The value of L will steadily increase, whereas the value of U may fluctuate up or down. Thus the value of L+U may fluctuate up or down (in general, it will tend to increase).
Cmpressns | is the number of times the data structure holding the partially factored matrix needed to be compressed to recover unused storage. Ideally this number should be zero. If it is more than 3 or 4, the amount of workspace available to E04WDF should be increased for efficiency.
Incres | is the percentage increase in the number of nonzeros in L and U relative to the number of nonzeros in B or BS .
Utri | is the number of triangular rows of B or BS at the top of U .
lenU | the number of nonzeros in U , including its diagonals.
Ltol | is the largest subdiagonal element allowed in L . This is the specified LU Factor Tolerance or a smaller value that is currently being used for greater stability.
Umax | the maximum nonzero element in U .
Ugrwth is the ratio Umax/Amax , which ideally should not be substantially larger than 10.0 or 100.0. If it is orders of magnitude larger, it may be advisable to reduce the LU Factor Tolerance to 5.0, 4.0, 3.0 or 2.0, say (but bigger than 1.0).
As long as Lmax is not large (say 5.0 or less), max Amax,Umax / DUmin gives an estimate of the condition number B . If this is extremely large, the basis is nearly singular. Slacks are used to replace suspect columns of B and the modified basis is refactored.
Ltri | is the number of triangular columns of B or BS at the left of L .
dense1 | is the number of columns remaining when the density of the basis matrix being factorized reached 0.3.
Lmax | is the actual maximum subdiagonal element in L (bounded by Ltol).
Akmax | is the largest nonzero generated at any stage of the LU factorization. (Values much larger than Amax indicate instability.) Akmax is not printed if LU Partial Pivoting is selected.
Agrwth | is the ratio Akmax/Amax . Values much larger than 100 (say) indicate instability. Growth is not printed if LU Partial Pivoting is selected.
bump | is the size of the block to be factorized nontrivially after the triangular rows and columns of B or BS have been removed.
dense2 | is the number of columns remaining when the density of the basis matrix being factorized reached 0.6. (The Markowitz pivot strategy searches fewer columns at that stage.)
DUmax | is the largest diagonal of PUQ .
DUmin | is the smallest diagonal of PUQ .
condU | the ratio DUmax/DUmin , which estimates the condition number of U (and of B if Ltol is less than 5.0, say).

13.5 The Solution File

At the end of a run, the final solution may be output as a Solution file, according to Solution File. Some header information appears first to identify the problem and the final state of the optimization procedure. A ROWS section and a COLUMNS section then follow, giving one line of information for each row and column. The format used is similar to certain commercial systems, though there is no industry standard.
In general, numerical values are output with format f16.5. The maximum record length is 111 characters, including the first (carriage-control) character.
To reduce clutter, a full stop (.) is printed for any numerical value that is exactly zero. The values ±1 are also printed specially as 1.0 and -1.0 . Infinite bounds ( ± 1020 or larger) are printed as None.
A Solution file is intended to be read from disk by a self-contained program that extracts and saves certain values as required for possible further computation. Typically, the first 14 records would be ignored. Each subsequent record may be read using
format(i8, 2x, 2a4, 1x, a1, 1x, a3, 5e16.6, i7)
adapted to suit the occasion. The end of the ROWS section is marked by a record that starts with a 1 and is otherwise blank. If this and the next 4 records are skipped, the COLUMNS section can then be read under the same format. (There should be no need for backspace statements.)

13.5.1 The ROWS section

General linear constraints take the form l ≤ Ax ≤ u . The i th constraint is therefore of the form
α ≤ νi x ≤ β ,
where νi is the i th row of A .
Internally, the constraints take the form Ax - s = 0 , where s is the set of slack variables (which happen to satisfy the bounds l ≤ s ≤ u ). For the i th constraint it is the slack variable si that is directly available, and it is sometimes convenient to refer to its state. Nonlinear constraints α≤ ci x+ vi x≤ β are treated similarly, except that the row activity and degree of infeasibility are computed directly from ci x + vi x rather than si . A fullstop (.) is printed for any numerical value that is exactly zero.
Label | Description
Number | is the value of n+i. (This is used internally to refer to si in the intermediate output.)
Row | gives the name of the ith row.
State the state of the ith row relative to the bounds α and β . The various states possible are as follows:
LL | the row is at its lower limit, α .
UL | the row is at its upper limit, β .
EQ | the limits are the same ( α=β ).
FR | si is nonbasic and currently zero, even though it is free to take any value between its bounds α and β .
BS | si is basic.
SBS | si is superbasic.
A key is sometimes printed before State. Note that unless the optional parameter Scale Option=0 is specified, the tests for assigning a key are applied to the variables of the scaled problem.
A | Alternative optimum possible. The variable is nonbasic, but its reduced gradient is essentially zero. This means that if the variable were allowed to start moving away from its bound, there would be no change in the value of the objective function. The values of the other free variables might change, giving a genuine alternative solution. However, if there are any degenerate variables (labelled D), the actual change might prove to be zero, since one of them could encounter a bound immediately. In either case, the values of the Lagrange multipliers might also change.
D | Degenerate. The variable is basic or superbasic, but it is equal (or very close) to one of its bounds.
I | Infeasible. The variable is basic or superbasic and is currently violating one of its bounds by more than the value of the Feasibility Tolerance.
N | Not precisely optimal. The variable is nonbasic or superbasic. If the value of the reduced gradient for the variable exceeds the value of the optional parameter Major Optimality Tolerance, the solution would not be declared optimal because the reduced gradient for the variable would not be considered negligible.
Activity | is the value of vi x (or ci x + vi x for nonlinear rows) at the final iterate.
Slack Activity | is the value by which the row differs from its nearest bound. (For the free row (if any), it is set to Activity.)
Lower Limit | is α, the lower bound on the row.
Upper Limit | is β, the upper bound on the row.
Dual Activity | is the value of the dual variable πi (the Lagrange multiplier for the i th constraint). The full vector π always satisfies BT π = gB , where B is the current basis matrix and gB contains the associated gradients for the current objective function. For FP problems, πi is set to zero.
i | gives the index i of the ith row.

13.5.2 The COLUMNS section

Let the j th component of x be the variable xj and assume that it satisfies the bounds α ≤ xj ≤ β . A fullstop (.) is printed for any numerical value that is exactly zero.
Label | Description
Number | is the column number j. (This is used internally to refer to xj in the intermediate output.)
Column | gives the name of xj.
State the state of xj relative to the bounds α and β . The various states possible are as follows:
LL | xj is nonbasic at its lower limit, α .
UL | xj is nonbasic at its upper limit, β .
EQ | xj is nonbasic and fixed at the value α = β .
FR | xj is nonbasic at some value strictly between its bounds: α<xj<β .
BS | xj is basic. Usually α<xj<β .
SBS | xj is superbasic. Usually α<xj<β .
A key is sometimes printed before State. Note that unless the optional parameter Scale Option=0 is specified, the tests for assigning a key are applied to the variables of the scaled problem.
A | Alternative optimum possible. The variable is nonbasic, but its reduced gradient is essentially zero. This means that if the variable were allowed to start moving away from its bound, there would be no change in the value of the objective function. The values of the other free variables might change, giving a genuine alternative solution. However, if there are any degenerate variables (labelled D), the actual change might prove to be zero, since one of them could encounter a bound immediately. In either case, the values of the Lagrange multipliers might also change.
D | Degenerate. The variable is basic or superbasic, but it is equal (or very close) to one of its bounds.
I | Infeasible. The variable is basic or superbasic and is currently violating one of its bounds by more than the value of the Feasibility Tolerance.
N | Not precisely optimal. The variable is nonbasic or superbasic. If the value of the reduced gradient for the variable exceeds the value of the optional parameter Major Optimality Tolerance, the solution would not be declared optimal because the reduced gradient for the variable would not be considered negligible.
Activity | is the value of xj at the final iterate.
Obj Gradient | is the value of gj at the final iterate. For FP problems, gj is set to zero.
Lower Limit | is the lower bound specified for the variable. None indicates that BL j≤-bigbnd.
Upper Limit | is the upper bound specified for the variable. None indicates that BU j≥bigbnd.
Reduced Gradnt | is the value of the reduced gradient dj = gj - πT aj where aj is the j th column of the constraint matrix. For FP problems, dj is set to zero.
m + j | is the value of m+j.
Note that movement off a constraint (as opposed to a variable moving away from its bound) can be interpreted as allowing the entry in the Slack Activity column to become positive.
Numerical values are output with a fixed number of digits; they are not guaranteed to be accurate to this precision.

13.6 The Summary File

If Summary File > 0 , the following information is output to the unit number associated with Summary File. (It is a brief summary of the output directed to unit Print File):
– | the optional parameters supplied via the option setting routines, if any;
– | the Basis file loaded, if any;
– | a brief major iteration log (see Section 13.1);
– | a brief minor iteration log (see Section 13.2);
– | the exit condition, IFAIL;
– | a summary of the final iterate.
E04 Chapter Contents
E04 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


E04WEF : NAG Library, Mark 26

E04 Chapter Contents
E04 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

E04WEF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

E04WEF may be used to supply optional parameters to E04WDF from an external file. The initialization routine E04WCF must have been called before calling E04WEF.

2 Specification

SUBROUTINE E04WEF ( ISPECS, IW, RW, IFAIL)
INTEGER | ISPECS, IW(*), IFAIL
REAL (KIND=nag_wp) | RW(*)

3 Description

E04WEF may be used to supply values for optional parameters to E04WDF. E04WEF reads an external file and each line of the file defines a single optional parameter. It is only necessary to supply values for those arguments whose values are to be different from their default values.
Each optional parameter is defined by a single character string, of up to 72 characters, consisting of one or more items. The items associated with a given option must be separated by spaces, or equals signs =. Alphabetic characters may be upper or lower case. The string
Print Level = 1
is an example of a string used to set an optional parameter. For each option the string contains one or more of the following items:
– | a mandatory keyword;
– | a phrase that qualifies the keyword;
– | a number that specifies an integer or real value. Such numbers may be up to 40 contiguous characters in Fortran's I, F, E or D formats, terminated by a space if this is not the last item on the line.
Blank strings and comments are ignored. A comment begins with an asterisk (*) and all subsequent characters in the string are regarded as part of the comment.
The file containing the options must start with Begin and must finish with End. An example of a valid options file is:
Begin * Example options file
   Print level = 5
End
Optional parameter settings are preserved following a call to E04WDF and so the keyword Defaults is provided to allow you to reset all the optional parameters to their default values before a subsequent call to E04WDF.
A complete list of optional parameters, their abbreviations, synonyms and default values is given in Section 12 in E04WDF.

4 References

Hock W and Schittkowski K (1981) Test Examples for Nonlinear Programming Codes. Lecture Notes in Economics and Mathematical Systems 187 Springer–Verlag

5 Arguments

1:   ISPECS – INTEGERInput
On entry: the unit number of the option file to be read.
Constraint: ISPECS is a valid unit open for reading.
2:   IW* – INTEGER arrayCommunication Array
Note: the dimension of the array IW must be at least LENIW (see E04WCF).
3:   RW* – REAL (KIND=nag_wp) arrayCommunication Array
Note: the dimension of the array RW must be at least LENRW (see E04WCF).
4:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
The initialization routine E04WCF has not been called.
IFAIL=2
At least one line of the options file is invalid.
Could not read options file on unit ISPECS =value.
Could not read options file on unit ISPECS. This may be due to:
(a) | ISPECS is not a valid unit number;
(b) | a file is not associated with unit ISPECS, or if it is, is unavailable for read access;
(c) | one or more lines of the options file is invalid. Check that all keywords are neither ambiguous nor misspelt;
(d) | Begin was found, but end-of-file was found before End was found;
(e) | end-of-file was found before Begin was found.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

Not applicable.

8 Parallelism and Performance

E04WEF is not threaded in any implementation.

9 Further Comments

E04WFF, E04WGF or E04WHF may also be used to supply optional parameters to E04WDF.

10 Example

This example is based on Problem 71 in Hock and Schittkowski (1981) and involves the minimization of the nonlinear function
F x=x 1x 4 x 1+x 2+x 3+x 3
subject to the bounds
1≤x 1≤ 5 1≤x 2≤ 5 1≤x 3≤ 5 1≤x 4≤ 5
to the general linear constraint
x 1+x 2+x 3+x 4≤20,
and to the nonlinear constraints
x 12+x 22+x 32+x 42≤ 40, x 1x 2x 3x 4≥ 25.
The initial point, which is infeasible, is
x 0=1,5,5,1 T,
and F x 0=16.
The optimal solution (to five figures) is
x*=1.0,4.7430,3.8211,1.3794 T,
and F x*=17.014. One bound constraint and both nonlinear constraints are active at the solution.
The document for E04WEF includes an example program to solve the same problem using some of the optional parameters described in Section 12 in E04WDF.

10.1 Program Text

Program Text (e04wefe.f90)

10.2 Program Data

Program Options (e04wefe.opt)

Program Data (e04wefe.d)

10.3 Program Results

Program Results (e04wefe.r)

E04 Chapter Contents
E04 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


E04WFF : NAG Library, Mark 26

E04 Chapter Contents
E04 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

E04WFF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
10 Example

1 Purpose

E04WFF may be used to supply individual optional parameters to E04WDF. The initialization routine E04WCF must have been called before calling E04WFF.

2 Specification

SUBROUTINE E04WFF ( STRING, IW, RW, IFAIL)
INTEGER | IW(*), IFAIL
REAL (KIND=nag_wp) | RW(*)
CHARACTER(*) | STRING

3 Description

E04WFF may be used to supply values for optional parameters to E04WDF. It is only necessary to call E04WFF for those arguments whose values are to be different from their default values. One call to E04WFF sets one argument value.
Each optional parameter is defined by a single character string, of up to 72 characters, consisting of one or more items. The items associated with a given option must be separated by spaces, or equals signs =. Alphabetic characters may be upper or lower case. The string
Print Level = 1
is an example of a string used to set an optional parameter. For each option the string contains one or more of the following items:
– | a mandatory keyword;
– | a phrase that qualifies the keyword;
– | a number that specifies an integer or real value. Such numbers may be up to 40 contiguous characters in Fortran's I, F, E or D formats, terminated by a space if this is not the last item on the line.
For E04WFF, each user-specified option is not normally printed as it is defined, but this printing may be turned on using the keyword List. Thus the statement
CALL E04WFF ('List', IW, RW, IFAIL)
turns on printing of this and subsequent options. Printing may be turned off again using the keyword Nolist.
Optional parameter settings are preserved following a call to E04WDF and so the keyword Defaults is provided to allow you to reset all the optional parameters to their default values before a subsequent call to E04WDF.
A complete list of optional parameters, their abbreviations, synonyms and default values is given in Section 12 in E04WDF.

4 References

None.

5 Arguments

1:   STRING – CHARACTER(*)Input
On entry: a single valid option string (see Section 3 in E04WFF and Section 12 in E04WDF).
2:   IW* – INTEGER arrayCommunication Array
Note: the dimension of the array IW must be at least LENIW (see E04WCF).
3:   RW* – REAL (KIND=nag_wp) arrayCommunication Array
Note: the dimension of the array RW must be at least LENRW (see E04WCF).
4:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
The initialization routine E04WCF has not been called.
IFAIL=2
The supplied option is invalid. Check that the keywords are neither ambiguous nor misspelt.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

Not applicable.

8 Parallelism and Performance

E04WFF is not threaded in any implementation.

9 Further Comments

E04WEF, E04WGF or E04WHF may also be used to supply optional parameters to E04WDF.

10 Example

See Section 10 in E04WEF.
E04 Chapter Contents
E04 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


E04WGF : NAG Library, Mark 26

E04 Chapter Contents
E04 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

E04WGF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
10 Example

1 Purpose

E04WGF may be used to supply individual integer optional parameters to E04WDF. The initialization routine E04WCF must have been called before calling E04WGF.

2 Specification

SUBROUTINE E04WGF ( STRING, IVALUE, IW, RW, IFAIL)
INTEGER | IVALUE, IW(*), IFAIL
REAL (KIND=nag_wp) | RW(*)
CHARACTER(*) | STRING

3 Description

E04WGF may be used to supply values for integer optional parameters to E04WDF. It is only necessary to call E04WGF for those arguments whose values are to be different from their default values. One call to E04WGF sets one argument value.
Each integer optional parameter is defined by a single character string in STRING and the corresponding value in IVALUE. For example, the following allows the iteration limit to be defined:
ITNLIM = 1000
IF (M > 500) ITNLIM = 500
CALL E04WGF ('Iterations', ITNLIM, IW, RW, IFAIL)
Optional parameter settings are preserved following a call to E04WDF and so the keyword Defaults is provided to allow you to reset all the optional parameters to their default values before a subsequent call to E04WDF.
A complete list of optional parameters, their abbreviations, synonyms and default values is given in Section 12 in E04WDF.

4 References

None.

5 Arguments

1:   STRING – CHARACTER(*)Input
On entry: a single valid keyword of an integer optional parameter (as described in Section 12 in E04WDF).
2:   IVALUE – INTEGERInput
On entry: an integer value associated with the keyword in STRING.
3:   IW* – INTEGER arrayCommunication Array
Note: the dimension of the array IW must be at least LENIW (see E04WCF).
4:   RW* – REAL (KIND=nag_wp) arrayCommunication Array
Note: the dimension of the array RW must be at least LENRW (see E04WCF).
5:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
The initialization routine E04WCF has not been called.
IFAIL=2
The supplied option is invalid. Check that the keywords are neither ambiguous nor misspelt.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

Not applicable.

8 Parallelism and Performance

E04WGF is not threaded in any implementation.

9 Further Comments

E04WEF or E04WFF may also be used to supply integer optional parameters to E04WDF.

10 Example

See Section 10 in E04WDF and E04WEF.
E04 Chapter Contents
E04 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


E04WHF : NAG Library, Mark 26

E04 Chapter Contents
E04 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

E04WHF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
10 Example

1 Purpose

E04WHF may be used to supply individual real optional parameters to E04WDF. The initialization routine E04WCF must have been called before calling E04WHF.

2 Specification

SUBROUTINE E04WHF ( STRING, RVALUE, IW, RW, IFAIL)
INTEGER | IW(*), IFAIL
REAL (KIND=nag_wp) | RVALUE, RW(*)
CHARACTER(*) | STRING

3 Description

E04WHF may be used to supply values for real optional parameters to E04WDF. It is only necessary to call E04WHF for those arguments whose values are to be different from their default values. One call to E04WHF sets one argument value.
Each real optional parameter is defined by a single character string in STRING and the corresponding value in RVALUE. For example the following illustrates how the LU stability tolerance could be defined:
FACTOL = 100.0E0
IF (ILLCON) FACTOL = 5.0E0
CALL E04WHF ('LU Factor Tolerance', FACTOL, IW, RW, IFAIL)
Optional parameter settings are preserved following a call to E04WDF and so the keyword Defaults is provided to allow you to reset all the optional parameters to their default values before a subsequent call to E04WDF.
A complete list of optional parameters, their abbreviations, synonyms and default values is given in Section 12 in E04WDF.

4 References

None.

5 Arguments

1:   STRING – CHARACTER(*)Input
On entry: a single valid keyword of a real optional parameter (as described in Section 12 in E04WDF).
2:   RVALUE – REAL (KIND=nag_wp)Input
On entry: the value associated with the keyword in STRING.
3:   IW* – INTEGER arrayCommunication Array
Note: the dimension of the array IW must be at least LENIW (see E04WCF).
4:   RW* – REAL (KIND=nag_wp) arrayCommunication Array
Note: the dimension of the array RW must be at least LENRW (see E04WCF).
5:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
The initialization routine E04WCF has not been called.
IFAIL=2
The supplied option is invalid. Check that the keywords are neither ambiguous nor misspelt.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

Not applicable.

8 Parallelism and Performance

E04WHF is not threaded in any implementation.

9 Further Comments

E04WEF or E04WFF may also be used to supply real optional parameters to E04WDF.

10 Example

See Section 10 in E04WEF.
E04 Chapter Contents
E04 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


E04WKF : NAG Library, Mark 26

E04 Chapter Contents
E04 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

E04WKF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
10 Example

1 Purpose

E04WKF is used to get the value of an integer optional parameter. E04WKF can be used before or after calling E04WDF.

2 Specification

SUBROUTINE E04WKF ( STRING, IVALUE, IW, RW, IFAIL)
INTEGER | IVALUE, IW(*), IFAIL
REAL (KIND=nag_wp) | RW(*)
CHARACTER(*) | STRING

3 Description

E04WKF obtains the current value of an integer option. For example
CALL E04WKF ('Iterations', ITNLIM, IW, RW, IFAIL)
will result in the value of the optional parameter Major Iterations Limit being output in ITNLIM.
A complete list of optional parameters, their abbreviations, synonyms and default values is given in Section 12 in E04WDF.

4 References

None.

5 Arguments

1:   STRING – CHARACTER(*)Input
On entry: a single valid keyword of an integer optional parameter (as described in Section 12 in E04WDF).
2:   IVALUE – INTEGEROutput
On exit: the integer value associated with the keyword in STRING.
3:   IW* – INTEGER arrayCommunication Array
Note: the dimension of the array IW must be at least LENIW (see E04WCF).
4:   RW* – REAL (KIND=nag_wp) arrayCommunication Array
Note: the dimension of the array RW must be at least LENRW (see E04WCF).
5:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
The initialization routine E04WCF has not been called.
IFAIL=2
The supplied option is invalid. Check that the keywords are neither ambiguous nor misspelt.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

Not applicable.

8 Parallelism and Performance

E04WKF is not threaded in any implementation.

9 Further Comments

None.

10 Example

See Section 10 in E04WEF.
E04 Chapter Contents
E04 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


E04WLF : NAG Library, Mark 26

E04 Chapter Contents
E04 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

E04WLF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
10 Example

1 Purpose

E04WLF is used to get the value of a real optional parameter. E04WLF can be used before or after calling E04WDF.

2 Specification

SUBROUTINE E04WLF ( STRING, RVALUE, IW, RW, IFAIL)
INTEGER | IW(*), IFAIL
REAL (KIND=nag_wp) | RVALUE, RW(*)
CHARACTER(*) | STRING

3 Description

E04WLF obtains the current value of a real option. For example
CALL E04WLF ('LU Factor Tolerance', FACTOL, IW, RW, IFAIL)
will result in the value of the optional parameter LU Factor Tolerance being output in FACTOL.
A complete list of optional parameters, their abbreviations, synonyms and default values is given in Section 12 in E04WDF.

4 References

None.

5 Arguments

1:   STRING – CHARACTER(*)Input
On entry: a single valid keyword of a real optional parameter (as described in Section 12 in E04WDF).
2:   RVALUE – REAL (KIND=nag_wp)Output
On exit: the real value associated with the keyword in STRING.
3:   IW* – INTEGER arrayCommunication Array
Note: the dimension of the array IW must be at least LENIW (see E04WCF).
4:   RW* – REAL (KIND=nag_wp) arrayCommunication Array
Note: the dimension of the array RW must be at least LENRW (see E04WCF).
5:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
The initialization routine E04WCF has not been called.
IFAIL=2
The supplied option is invalid. Check that the keywords are neither ambiguous nor misspelt.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

Not applicable.

8 Parallelism and Performance

E04WLF is not threaded in any implementation.

9 Further Comments

None.

10 Example

See Section 10 in E04WEF.
E04 Chapter Contents
E04 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


E04XAF/E04XAA : NAG Library, Mark 26

E04 Chapter Contents
E04 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

E04XAF/E04XAA

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
▸▿ 2 Specification
2.1 Specification for E04XAF
2.2 Specification for E04XAA
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
▸▿ 9 Further Comments
9.1 Description of the Printed Output
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

E04XAF/E04XAA computes an approximation to the gradient vector and/or the Hessian matrix for use in conjunction with, or following the use of an optimization routine (such as E04UFF/E04UFA).
E04XAA is a version of E04XAF that has additional arguments in order to make it safe for use in multithreaded applications (see Section 5).

2 Specification

2.1 Specification for E04XAF

SUBROUTINE E04XAF ( MSGLVL, N, EPSRF, X, MODE, OBJFUN, LDH, HFORW, OBJF, OBJGRD, HCNTRL, H, IWARN, WORK, IUSER, RUSER, INFO, IFAIL)
INTEGER | MSGLVL, N, MODE, LDH, IWARN, IUSER(*), INFO(N), IFAIL
REAL (KIND=nag_wp) | EPSRF, X(N), HFORW(N), OBJF, OBJGRD(N), HCNTRL(N), H(LDH,*), WORK(*), RUSER(*)
EXTERNAL | OBJFUN

2.2 Specification for E04XAA

SUBROUTINE E04XAA ( MSGLVL, N, EPSRF, X, MODE, OBJFUN, LDH, HFORW, OBJF, OBJGRD, HCNTRL, H, IWARN, WORK, IUSER, RUSER, INFO, LWSAV, IWSAV, RWSAV, IFAIL)
INTEGER | MSGLVL, N, MODE, LDH, IWARN, IUSER(*), INFO(N), IWSAV(1), IFAIL
REAL (KIND=nag_wp) | EPSRF, X(N), HFORW(N), OBJF, OBJGRD(N), HCNTRL(N), H(LDH,*), WORK(*), RUSER(*), RWSAV(1)
LOGICAL | LWSAV(1)
EXTERNAL | OBJFUN

3 Description

E04XAF/E04XAA is similar to routine FDCALC described in Gill et al. (1983a). It should be noted that this routine aims to compute sufficiently accurate estimates of the derivatives for use with an optimization algorithm. If you require more accurate estimates you should refer to Chapter D04.
E04XAF/E04XAA computes finite difference approximations to the gradient vector and the Hessian matrix for a given function. The simplest approximation involves the forward-difference formula, in which the derivative f′x of a univariate function f x is approximated by the quantity
ρF f,h=f x+h-f x h
for some interval h>0, where the subscript 'F' denotes ‘forward-difference’ (see Gill et al. (1983b)).
To summarise the procedure used by E04XAF/E04XAA (for the case when the objective function is available and you require estimates of gradient values and Hessian matrix diagonal values, i.e., MODE=0) consider a univariate function f at the point x. (In order to obtain the gradient of a multivariate function F x, where x is an n-vector, the procedure is applied to each component of x, keeping the other components fixed.) Roughly speaking, the method is based on the fact that the bound on the relative truncation error in the forward-difference approximation tends to be an increasing function of h, while the relative condition error bound is generally a decreasing function of h, hence changes in h will tend to have opposite effects on these errors (see Gill et al. (1983b)).
The ‘best’ interval h is given by
hF=2 1+f x eR Φ (1)
where Φ is an estimate of f′′x, and eR is an estimate of the relative error associated with computing the function (see Chapter 8 of Gill et al. (1981)). Given an interval h, Φ is defined by the second-order approximation
Φ=f x+h-2 f x+f x-h h 2.
The decision as to whether a given value of Φ is acceptable involves c^Φ, the following bound on the relative condition error in Φ:
c^Φ=4 eR 1+f h 2 Φ
(When Φ is zero, c^Φ is taken as an arbitrary large number.)
The procedure selects the interval hϕ (to be used in computing Φ) from a sequence of trial intervals hk. The initial trial interval is taken as 10 h-, where
h-=2 1+x eR
unless you specify the initial value to be used.
The value of c^Φ for a trial value hk is defined as ‘acceptable’ if it lies in the interval 0.001,0.1. In this case hϕ is taken as hk, and the current value of Φ is used to compute hF from (1). If c^Φ is unacceptable, the next trial interval is chosen so that the relative condition error bound will either decrease or increase, as required. If the bound on the relative condition error is too large, a larger interval is used as the next trial value in an attempt to reduce the condition error bound. On the other hand, if the relative condition error bound is too small, hk is reduced.
The procedure will fail to produce an acceptable value of c^Φ in two situations. Firstly, if f′′x is extremely small, then c^Φ may never become small, even for a very large value of the interval. Alternatively, c^Φ may never exceed 0.001, even for a very small value of the interval. This usually implies that f′′x is extremely large, and occurs most often near a singularity.
As a check on the validity of the estimated first derivative, the procedure provides a comparison of the forward-difference approximation computed with hF (as above) and the central-difference approximation computed with hϕ. Using the central-difference formula the first derivative can be approximated by
ρc f,h=f x+h-f x-h 2 h
where h>0. If the values hF and hϕ do not display some agreement, neither can be considered reliable.
When both function and gradients are available and you require the Hessian matrix (i.e., MODE=1) E04XAF/E04XAA follows a similar procedure to the case above with the exception that the gradient function g x is substituted for the objective function and so the forward-difference interval for the first derivative of g x with respect to variable xj is computed. The jth column of the approximate Hessian matrix is then defined as in Chapter 2 of Gill et al. (1981), by
g x+hjej-g x hj
where hj is the best forward-difference interval associated with the jth component of g and ej is the vector with unity in the jth position and zeros elsewhere.
When only the objective function is available and you require the gradients and Hessian matrix (i.e., MODE=2) E04XAF/E04XAA again follows the same procedure as the case for MODE=0 except that this time the value of c^Φ for a trial value hk is defined as acceptable if it lies in the interval 0.0001,0.01 and the initial trial interval is taken as
h-=2 1+x eR 4.
The approximate Hessian matrix G is then defined as in Chapter 2 of Gill et al. (1981), by
G ij x=1 hihj f x+hiei+hjej-f x+hiei-f x+hjej+f x.

4 References

Gill P E, Murray W, Saunders M A and Wright M H (1983a) Documentation for FDCALC and FDCORE Technical Report SOL 83–6 Stanford University
Gill P E, Murray W, Saunders M A and Wright M H (1983b) Computing forward-difference intervals for numerical optimization SIAM J. Sci. Statist. Comput. 4 310–321
Gill P E, Murray W and Wright M H (1981) Practical Optimization Academic Press

5 Arguments

1:   MSGLVL – INTEGERInput
On entry: must indicate the amount of intermediate output desired (see Section 9.1 for a description of the printed output). All output is written on the current advisory message unit (see X04ABF).
Value | Definition
0 | No printout
1 | A summary is printed out for each variable plus any warning messages.
Other | Values other than 0 and 1 should normally be used only at the direction of NAG.
2:   N – INTEGERInput
On entry: the number n of independent variables.
Constraint: N≥1.
3:   EPSRF – REAL (KIND=nag_wp)Input
On entry: must define eR, which is intended to be a measure of the accuracy with which the problem function F can be computed. The value of eR should reflect the relative precision of 1+F x, i.e., acts as a relative precision when F is large, and as an absolute precision when F is small. For example, if F x is typically of order 1000 and the first six significant digits are known to be correct, an appropriate value for eR would be 1.0E−6.
A discussion of EPSRF is given in Chapter 8 of Gill et al. (1981). If EPSRF is either too small or too large on entry a warning will be printed if MSGLVL=1, the argument IWARN set to the appropriate value on exit and E04XAF/E04XAA will use a default value of eM 0.9, where eM is the machine precision.
If EPSRF≤0.0 on entry then E04XAF/E04XAA will use the default value internally. The default value will be appropriate for most simple functions that are computed with full accuracy.
4:   X N – REAL (KIND=nag_wp) arrayInput
On entry: the point x at which the derivatives are to be computed.
5:   MODE – INTEGERInput/Output
On entry: indicates which derivatives are required.
MODE=0
The gradient and Hessian diagonal values having supplied the objective function via OBJFUN.
MODE=1
The Hessian matrix having supplied both the objective function and gradients via OBJFUN.
MODE=2
The gradient values and Hessian matrix having supplied the objective function via OBJFUN.
On exit: is changed only if you set MODE negative in OBJFUN, i.e., you have requested termination of E04XAF/E04XAA.
6:   OBJFUN – SUBROUTINE, supplied by the user.External Procedure
If MODE=0 or 2, OBJFUN must calculate the objective function; otherwise if MODE=1, OBJFUN must calculate the objective function and the gradients.
The specification of OBJFUN is:
SUBROUTINE OBJFUN ( MODE, N, X, OBJF, OBJGRD, NSTATE, IUSER, RUSER)
INTEGER | MODE, N, NSTATE, IUSER(*)
REAL (KIND=nag_wp) | X(N), OBJF, OBJGRD(N), RUSER(*)
1:   MODE – INTEGERInput/Output
MODE indicates which argument values within OBJFUN need to be set.
On entry: to OBJFUN, MODE is always set to the value that you set it to before the call to E04XAF/E04XAA.
On exit: its value must not be altered unless you wish to indicate a failure within OBJFUN, in which case it should be set to a negative value. If MODE is negative on exit from OBJFUN, the execution of E04XAF/E04XAA is terminated with IFAIL set to MODE.
2:   N – INTEGERInput
On entry: the number n of variables as input to E04XAF/E04XAA.
3:   X N – REAL (KIND=nag_wp) arrayInput
On entry: the point x at which the objective function (and gradients if MODE=1) is to be evaluated.
4:   OBJF – REAL (KIND=nag_wp)Output
On exit: must be set to the value of the objective function.
5:   OBJGRD N – REAL (KIND=nag_wp) arrayOutput
On exit: if MODE=1, OBJGRD j must contain the value of the first derivative with respect to x.
If MODE≠1, OBJGRD need not be set.
6:   NSTATE – INTEGERInput
On entry: will be set to 1 on the first call of OBJFUN by E04XAF/E04XAA, and is 0 for all subsequent calls. Thus, if you wish, NSTATE may be tested within OBJFUN in order to perform certain calculations once only. For example you may read data.
7:   IUSER* – INTEGER arrayUser Workspace
8:   RUSER* – REAL (KIND=nag_wp) arrayUser Workspace
OBJFUN is called with the arguments IUSER and RUSER as supplied to E04XAF/E04XAA. You are free to use the arrays IUSER and RUSER to supply information to OBJFUN as an alternative to using COMMON global variables.
OBJFUN must either be a module subprogram USEd by, or declared as EXTERNAL in, the (sub)program from which E04XAF/E04XAA is called. Arguments denoted as Input must not be changed by this procedure.
7:   LDH – INTEGERInput
On entry: the first dimension of the array H as declared in the (sub)program from which E04XAF/E04XAA is called.
Constraint: LDH≥N.
8:   HFORW N – REAL (KIND=nag_wp) arrayInput/Output
On entry: the initial trial interval for computing the appropriate partial derivative to the jth variable.
If HFORW j≤0.0, then the initial trial interval is computed by E04XAF/E04XAA (see Section 3).
On exit: HFORW j is the best interval found for computing a forward-difference approximation to the appropriate partial derivative for the jth variable.
9:   OBJF – REAL (KIND=nag_wp)Output
On exit: the value of the objective function evaluated at the input vector in X.
10:   OBJGRD N – REAL (KIND=nag_wp) arrayOutput
On exit: if MODE=0 or 2, OBJGRD j contains the best estimate of the first partial derivative for the jth variable.
If MODE=1, OBJGRD j contains the first partial derivative for the jth variable evaluated at the input vector in X.
11:   HCNTRL N – REAL (KIND=nag_wp) arrayOutput
On exit: HCNTRL j is the best interval found for computing a central-difference approximation to the appropriate partial derivative for the jth variable.
12:   H LDH* – REAL (KIND=nag_wp) arrayOutput
Note: the second dimension of the array H must be at least 1 if MODE=0 and at least N if MODE=1 or 2.
On exit: if MODE=0, the estimated Hessian diagonal elements are contained in the first column of this array.
If MODE=1 or 2, the estimated Hessian matrix is contained in the leading n by n part of this array.
13:   IWARN – INTEGEROutput
On exit: IWARN=0 on successful exit.
If the value of EPSRF on entry is too small or too large then IWARN is set to 1 or 2 respectively on exit and the default value for EPSRF is used within E04XAF/E04XAA.
If MSGLVL>0 then warnings will be printed if EPSRF is too small or too large.
14:   WORK* – REAL (KIND=nag_wp) arrayWorkspace
Note: the dimension of the array WORK must be at least N if MODE=0 and at least N×N+1 if MODE=1 or 2.
15:   IUSER* – INTEGER arrayUser Workspace
16:   RUSER* – REAL (KIND=nag_wp) arrayUser Workspace
IUSER and RUSER are not used by E04XAF/E04XAA, but are passed directly to OBJFUN and may be used to pass information to this routine as an alternative to using COMMON global variables.
17:   INFO N – INTEGER arrayOutput
On exit: INFO j represents diagnostic information on variable j. (See Section 6 for more details.)
18:   IFAIL – INTEGERInput/Output
Note: for E04XAA, IFAIL does not occur in this position in the argument list. See the additional arguments described below.
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).
Note: the following are additional arguments for specific use with E04XAA. Users of E04XAF therefore need not read the remainder of this description.
18:   LWSAV 1 – LOGICAL arrayCommunication Array
19:   IWSAV 1 – INTEGER arrayCommunication Array
20:   RWSAV 1 – REAL (KIND=nag_wp) arrayCommunication Array
These arguments are no longer required by E04XAF/E04XAA.
21:   IFAIL – INTEGERInput/Output
Note: see the argument description for IFAIL above.

6 Error Indicators and Warnings

On exit from E04XAF/E04XAA both diagnostic arguments INFO and IFAIL should be tested. IFAIL represents an overall diagnostic indicator, whereas the integer array INFO represents diagnostic information on each variable.
If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL<0
A negative value of IFAIL indicates an exit from E04XAF/E04XAA because you set MODE negative in OBJFUN. The value of IFAIL will be the same as your setting of MODE.
IFAIL=1
On entry, one or more of the following conditions are satisfied: N<1, LDH<N​ or ​MODE is invalid.
IFAIL=2
One or more variables have a nonzero INFO value. This may not necessarily represent an unsuccessful exit – see diagnostic information on INFO.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.
Diagnostic information returned via INFO is as follows:
INFO=1
The appropriate function appears to be constant. HFORW i is set to the initial trial interval value (see Section 3) corresponding to a well-scaled problem and Error est. in the printed output is set to zero. This value occurs when the estimated relative condition error in the first derivative approximation is unacceptably large for every value of the finite difference interval. If this happens when the function is not constant the initial interval may be too small; in this case, it may be worthwhile to rerun E04XAF/E04XAA with larger initial trial interval values supplied in HFORW (see Section 3). This error may also occur if the function evaluation includes an inordinately large constant term or if EPSRF is too large.
INFO=2
The appropriate function appears to be linear or odd. HFORW i is set to the smallest interval with acceptable bounds on the relative condition error in the forward- and backward-difference estimates. In this case, the estimated relative condition error in the second derivative approximation remained large for every trial interval, but the estimated error in the first derivative approximation was acceptable for at least one interval. If the function is not linear or odd the relative condition error in the second derivative may be decreasing very slowly, it may be worthwhile to rerun E04XAF/E04XAA with larger initial trial interval values supplied in HFORW (see Section 3).
INFO=3
The second derivative of the appropriate function appears to be so large that it cannot be reliably estimated (i.e., near a singularity). HFORW i is set to the smallest trial interval.
This value occurs when the relative condition error estimate in the second derivative remained very small for every trial interval.
If the second derivative is not large the relative condition error in the second derivative may be increasing very slowly. It may be worthwhile to rerun E04XAF/E04XAA with smaller initial trial interval values supplied in HFORW (see Section 3). This error may also occur when the given value of EPSRF is not a good estimate of a bound on the absolute error in the appropriate function (i.e., EPSRF is too small).
INFO=4
The algorithm terminated with an apparently acceptable estimate of the second derivative. However the forward-difference estimates of the appropriate first derivatives (computed with the final estimate of the ‘optimal’ forward-difference interval) and the central difference estimates (computed with the interval used to compute the final estimate of the second derivative) do not agree to half a decimal place. The usual reason that the forward- and central-difference estimates fail to agree is that the first derivative is small.
If the first derivative is not small, it may be helpful to execute the procedure at a different point.

7 Accuracy

If IFAIL=0 on exit the algorithm terminated successfully, i.e., the forward-difference estimates of the appropriate first derivatives (computed with the final estimate of the ‘optimal’ forward-difference interval hF) and the central-difference estimates (computed with the interval hϕ used to compute the final estimate of the second derivative) agree to at least half a decimal place.
In short word length implementations when computing the full Hessian matrix given function values only (i.e., MODE=2) the elements of the computed Hessian will have at best 1 to 2 figures of accuracy.

8 Parallelism and Performance

E04XAF/E04XAA is not threaded in any implementation.

9 Further Comments

To evaluate an acceptable set of finite difference intervals for a well-scaled problem, the routine will require around two function evaluations per variable; in a badly scaled problem however, as many as six function evaluations per variable may be needed.
If you request the full Hessian matrix supplying both function and gradients (i.e., MODE=1) or function only (i.e., MODE=2) then a further N or 3×N×N+1/2 function evaluations respectively are required.

9.1 Description of the Printed Output

The following is a description of the printed output from E04XAF/E04XAA as controlled by the argument MSGLVL.
Output when MSGLVL=1 is as follows:
J | number of variable for which the difference interval has been computed.
X j | jth variable of x as set by you.
F. dif. int. | the best interval found for computing a forward-difference approximation to the appropriate partial derivative with respect to the jth variable.
C. dif. int. | the best interval found for computing a central-difference approximation to the appropriate partial derivative with respect to the jth variable.
Error est. | a bound on the estimated error in the final forward-difference approximation. When INFO j=1, Error est. is set to zero.
Grad. est. | best estimate of the first partial derivative with respect to the jth variable.
Hess diag est. | best estimate of the second partial derivative with respect to the jth variable.
fun evals. | the number of function evaluations used to compute the final difference intervals for the jth variable.
info j | the value of INFO for the jth variable.

10 Example

This example computes the gradient vector and the Hessian matrix of the following function:
F x= x 1+10 x 2 2+5⁢ x 3-x 4 2+ x 2-2 x 3 4+10⁢ x 1-x 4 4
at the point 2,-1,1,1.

10.1 Program Text

Note: the following programs illustrate the use of E04XAF and E04XAA.

Program Text (e04xafe.f90)

Program Text (e04xaae.f90)

10.2 Program Data

None.

10.3 Program Results

Program Results (e04xafe.r)

Program Results (e04xaae.r)

E04 Chapter Contents
E04 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


E04YAF : NAG Library, Mark 26

E04 Chapter Contents
E04 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

E04YAF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

E04YAF checks that a user-supplied subroutine for evaluating a vector of functions and the matrix of their first derivatives produces derivative values which are consistent with the function values calculated.

2 Specification

SUBROUTINE E04YAF ( M, N, LSQFUN, X, FVEC, FJAC, LDFJAC, IW, LIW, W, LW, IFAIL)
INTEGER | M, N, LDFJAC, IW(LIW), LIW, LW, IFAIL
REAL (KIND=nag_wp) | X(N), FVEC(M), FJAC(LDFJAC,N), W(LW)
EXTERNAL | LSQFUN

3 Description

Routines for minimizing a sum of squares of m nonlinear functions (or ‘residuals’), fi x 1,x 2,…,xn, for i=1,2,…,m and m≥n, may require you to supply a subroutine to evaluate the fi and their first derivatives. E04YAF checks the derivatives calculated by such user-supplied subroutines, e.g., routines of the form required for E04GBF, E04GDF and E04HEF. As well as the routine to be checked (LSQFUN), you must supply a point x = x 1,x 2,…,xn T at which the check will be made. E04YAF is essentially identical to CHKLSJ in the NPL Algorithms Library.
E04YAF first calls LSQFUN to evaluate the fi x and their first derivatives, and uses these to calculate the sum of squares F x=∑i=1 m fi x 2, and its first derivatives gj = ∂ F ∂ x j x , for j=1,2,…,n. The components of g along two orthogonal directions (defined by unit vectors p 1 and p 2, say) are then calculated; these will be gT p 1 and gT p 2 respectively. The same components are also estimated by finite differences, giving quantities
vk=F x+h pk-F x h,  k=1,2
where h is a small positive scalar. If the relative difference between v 1 and gT p 1 or between v 2 and gT p 2 is judged too large, an error indicator is set.

4 References

None.

5 Arguments

1:   M – INTEGERInput
2:   N – INTEGERInput
On entry: the number m of residuals, fi x, and the number n of variables, xj.
Constraint: 1≤N≤M.
3:   LSQFUN – SUBROUTINE, supplied by the user.External Procedure
LSQFUN must calculate the vector of values fi x and their first derivatives ∂fi ∂xj at any point x. (The minimization routines mentioned in Section 3 give you the option of resetting an argument to terminate immediately. E04YAF will also terminate immediately, without finishing the checking process, if the argument in question is reset.)
The specification of LSQFUN is:
SUBROUTINE LSQFUN ( IFLAG, M, N, XC, FVEC, FJAC, LDFJAC, IW, LIW, W, LW)
INTEGER | IFLAG, M, N, LDFJAC, IW(LIW), LIW, LW
REAL (KIND=nag_wp) | XC(N), FVEC(M), FJAC(LDFJAC,N), W(LW)
1:   IFLAG – INTEGERInput/Output
On entry: to LSQFUN, IFLAG will be set to 2.
On exit: if you reset IFLAG to some negative number in LSQFUN and return control to E04YAF, the routine will terminate immediately with IFAIL set to your setting of IFLAG.
2:   M – INTEGERInput
On entry: the numbers m of residuals.
3:   N – INTEGERInput
On entry: the numbers n of variables.
4:   XC N – REAL (KIND=nag_wp) arrayInput
On entry: x, the point at which the values of the fi and the ∂fi ∂xj are required.
5:   FVEC M – REAL (KIND=nag_wp) arrayOutput
On exit: unless IFLAG is reset to a negative number, FVEC i must contain the value of fi at the point x, for i=1,2,…,m.
6:   FJAC LDFJACN – REAL (KIND=nag_wp) arrayOutput
On exit: unless IFLAG is reset to a negative number, FJAC ij must contain the value of ∂fi ∂xj at the point x, for i=1,2,…,m and j=1,2,…,n.
7:   LDFJAC – INTEGERInput
On entry: the first dimension of the array FJAC as declared in the (sub)program from which E04YAF is called.
8:   IW LIW – INTEGER arrayWorkspace
9:   LIW – INTEGERInput
10:   W LW – REAL (KIND=nag_wp) arrayWorkspace
11:   LW – INTEGERInput
These arguments are present so that LSQFUN will be of the form required by the minimization routines mentioned in Section 3. LSQFUN is called with the same arguments IW, LIW, W, LW as in the call to E04YAF. If the recommendation in the minimization routine document is followed, you will have no reason to examine or change the elements of IW or W. In any case, LSQFUN must not change the first 3×N+M+M×N elements of W.
LSQFUN must either be a module subprogram USEd by, or declared as EXTERNAL in, the (sub)program from which E04YAF is called. Arguments denoted as Input must not be changed by this procedure.
4:   X N – REAL (KIND=nag_wp) arrayInput
On entry: X j, for j=1,2,…,n, must be set to the coordinates of a suitable point at which to check the derivatives calculated by LSQFUN. ‘Obvious’ settings, such as 0 or 1, should not be used since, at such particular points, incorrect terms may take correct values (particularly zero), so that errors can go undetected. For a similar reason, it is preferable that no two elements of X should have the same value.
5:   FVEC M – REAL (KIND=nag_wp) arrayOutput
On exit: unless you set IFLAG negative in the first call of LSQFUN, FVEC i contains the value of fi at the point supplied by you in X, for i=1,2,…,m.
6:   FJAC LDFJACN – REAL (KIND=nag_wp) arrayOutput
On exit: unless you set IFLAG negative in the first call of LSQFUN, FJAC ij contains the value of the first derivative ∂fi ∂xj at the point given in X, as calculated by LSQFUN, for i=1,2,…,m and j=1,2,…,n.
7:   LDFJAC – INTEGERInput
On entry: the first dimension of the array FJAC as declared in the (sub)program from which E04YAF is called.
Constraint: LDFJAC≥M.
8:   IW LIW – INTEGER arrayCommunication Array
This array appears in the argument list purely so that, if E04YAF is called by another library routine, the library routine can pass quantities to LSQFUN via IW. IW is not examined or changed by E04YAF. In general you must provide an array IW, but are advised not to use it.
9:   LIW – INTEGERInput
On entry: the dimension of the array IW as declared in the (sub)program from which E04YAF is called.
Constraint: LIW≥1.
10:   W LW – REAL (KIND=nag_wp) arrayCommunication Array
11:   LW – INTEGERInput
On entry: the dimension of the array W as declared in the (sub)program from which E04YAF is called.
Constraint: LW≥3×N+M+M×N.
12:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, because for this routine the values of the output arguments may be useful even if IFAIL≠0 on exit, the recommended value is -1. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Note: E04YAF may return useful information for one or more of the following detected errors or warnings.
Errors or warnings detected by the routine:
IFAIL<0
A negative value of IFAIL indicates an exit from E04YAF because you have set IFLAG negative in LSQFUN. The setting of IFAIL will be the same as your setting of IFLAG. The check on LSQFUN will not have been completed.
IFAIL=1
On entry, | M<N,
or | N<1,
or | LDFJAC<M,
or | LIW<1,
or | LW<3×N+M+M×N.
IFAIL=2
You should check carefully the derivation and programming of expressions for the ∂fi ∂xj , because it is very unlikely that LSQFUN is calculating them correctly.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

IFAIL is set to 2 if
vk - gT pk 2 ≥ h× gT pk 2 +1
for k=1​ or ​2. (See Section 3 for definitions of the quantities involved.) The scalar h is set equal to ε, where ε is the machine precision as given by X02AJF.

8 Parallelism and Performance

E04YAF is not threaded in any implementation.

9 Further Comments

E04YAF calls LSQFUN three times.
Before using E04YAF to check the calculation of the first derivatives, you should be confident that LSQFUN is calculating the residuals correctly.
E04YAF only checks the derivatives calculated by a user-supplied routine when IFLAG=2. So, if LSQFUN is intended for use in conjunction with a minimization routine which may set IFLAG to 1, you must check that, for given settings of the XC j, LSQFUN produces the same values for the ∂fi ∂xj when IFLAG is set to 1 as when IFLAG is set to 2.

10 Example

Suppose that it is intended to use E04GBF or E04GDF to find least squares estimates of x 1,x 2 and x 3 in the model
y=x 1+t 1 x 2t 2+x 3t 3
using the 15 sets of data given in the following table.
y t 1 t 2 t 3 0.14 1.0 15.0 1.0 0.18 2.0 14.0 2.0 0.22 3.0 13.0 3.0 0.25 4.0 12.0 4.0 0.29 5.0 11.0 5.0 0.32 6.0 10.0 6.0 0.35 7.0 9.0 7.0 0.39 8.0 8.0 8.0 0.37 9.0 7.0 7.0 0.58 10.0 6.0 6.0 0.73 11.0 5.0 5.0 0.96 12.0 4.0 4.0 1.34 13.0 3.0 3.0 2.10 14.0 2.0 2.0 4.39 15.0 1.0 1.0
The following program could be used to check the first derivatives calculated by LSQFUN. (The tests of whether IFLAG=0 or 1 in LSQFUN are present ready for when LSQFUN is called by E04GBF or E04GDF. E04YAF will always call LSQFUN with IFLAG set to 2.)

10.1 Program Text

Program Text (e04yafe.f90)

10.2 Program Data

Program Data (e04yafe.d)

10.3 Program Results

Program Results (e04yafe.r)

E04 Chapter Contents
E04 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


E04YBF : NAG Library, Mark 26

E04 Chapter Contents
E04 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

E04YBF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

E04YBF checks that a user-supplied subroutine for evaluating the second derivative term of the Hessian matrix of a sum of squares is consistent with a user-supplied subroutine for calculating the corresponding first derivatives.

2 Specification

SUBROUTINE E04YBF ( M, N, LSQFUN, LSQHES, X, FVEC, FJAC, LDFJAC, B, LB, IW, LIW, W, LW, IFAIL)
INTEGER | M, N, LDFJAC, LB, IW(LIW), LIW, LW, IFAIL
REAL (KIND=nag_wp) | X(N), FVEC(M), FJAC(LDFJAC,N), B(LB), W(LW)
EXTERNAL | LSQFUN, LSQHES

3 Description

Routines for minimizing a sum of squares of m nonlinear functions (or ‘residuals’), fi x 1,x 2,…,xn, for i=1,2,…,m and m≥n, may require you to supply a subroutine to evaluate the quantities
b jk=∑i=1 m fi ∂2 fi ∂xj∂xk
for j=1,2,…,n and k=1,2,…,j. E04YBF is designed to check the b jk calculated by such user-supplied subroutines. As well as the routine to be checked (LSQHES), you must supply a subroutine (LSQFUN) to evaluate the fi and their first derivatives, and a point x=x 1,x 2,…,xn T at which the checks will be made. Note that E04YBF checks routines of the form required by E04HEF. E04YBF is essentially identical to CHKLSH in the NPL Algorithms Library.
E04YBF first calls user-supplied subroutines LSQFUN and LSQHES to evaluate the first derivatives and the b jk at x. Let J denote the m by n matrix of first derivatives of the residuals. The Hessian matrix of the sum of squares,
G=JT J+B,
is calculated and projected onto two orthogonal vectors y and z to give the scalars yT Gy and zT Gz respectively. The same projections of the Hessian matrix are also estimated by finite differences, giving
p=yT g x+hy-yT g x/h  and q=zT g x+hz-zT g x/h
respectively, where g denotes the gradient vector of the sum of squares at the point in brackets and h is a small positive scalar. If the relative difference between p and yT Gy or between q and zT Gz is judged too large, an error indicator is set.

4 References

None.

5 Arguments

1:   M – INTEGERInput
2:   N – INTEGERInput
On entry: the number m of residuals, fi x, and the number n of variables, xj.
Constraint: 1≤N≤M.
3:   LSQFUN – SUBROUTINE, supplied by the user.External Procedure
LSQFUN must calculate the vector of values fi x and their first derivatives ∂fi ∂xj at any point x. (E04HEF gives you the option of resetting arguments of LSQFUN to cause the minimization process to terminate immediately. E04YBF will also terminate immediately, without finishing the checking process, if the argument in question is reset.)
The specification of LSQFUN is:
SUBROUTINE LSQFUN ( IFLAG, M, N, XC, FVEC, FJAC, LDFJAC, IW, LIW, W, LW)
INTEGER | IFLAG, M, N, LDFJAC, IW(LIW), LIW, LW
REAL (KIND=nag_wp) | XC(N), FVEC(M), FJAC(LDFJAC,N), W(LW)
1:   IFLAG – INTEGERInput/Output
On entry: to LSQFUN, IFLAG will be set to 2.
On exit: if you reset IFLAG to some negative number in LSQFUN and return control to E04YBF, the routine will terminate immediately with IFAIL set to your setting of IFLAG.
2:   M – INTEGERInput
On entry: the numbers m of residuals.
3:   N – INTEGERInput
On entry: the numbers n of variables.
4:   XC N – REAL (KIND=nag_wp) arrayInput
On entry: the point x at which the values of the fi and the ∂fi ∂xj are required.
5:   FVEC M – REAL (KIND=nag_wp) arrayOutput
On exit: unless IFLAG is reset to a negative number, FVEC i must contain the value of fi at the point x, for i=1,2,…,m.
6:   FJAC LDFJACN – REAL (KIND=nag_wp) arrayOutput
On exit: unless IFLAG is reset to a negative number, FJAC ij must contain the value of ∂fi ∂xj at the point x, for i=1,2,…,m and j=1,2,…,n.
7:   LDFJAC – INTEGERInput
On entry: the first dimension of the array FJAC as declared in the (sub)program from which E04YBF is called.
8:   IW LIW – INTEGER arrayWorkspace
9:   LIW – INTEGERInput
10:   W LW – REAL (KIND=nag_wp) arrayWorkspace
11:   LW – INTEGERInput
These arguments are present so that LSQFUN will be of the form required by E04HEF. LSQFUN is called with E04YBF's arguments IW, LIW, W, LW as these arguments. If the recommendation in E04HEF is followed, you will have no reason to examine or change the elements of IW or W. In any case, LSQFUN must not change the first 5×N+M+M×N+N×N-1/2 (or 6+2×M if N=1) elements of W.
LSQFUN must either be a module subprogram USEd by, or declared as EXTERNAL in, the (sub)program from which E04YBF is called. Arguments denoted as Input must not be changed by this procedure.
Note: E04YAF should be used to check the first derivatives calculated by LSQFUN before E04YBF is used to check the b jk since E04YBF assumes that the first derivatives are correct.
4:   LSQHES – SUBROUTINE, supplied by the user.External Procedure
LSQHES must calculate the elements of the symmetric matrix
B x=∑i=1 m fi x Gi x,
at any point x, where Gi x is the Hessian matrix of fi x. (As with LSQFUN, an argument can be set to cause immediate termination.)
The specification of LSQHES is:
SUBROUTINE LSQHES ( IFLAG, M, N, FVEC, XC, B, LB, IW, LIW, W, LW)
INTEGER | IFLAG, M, N, LB, IW(LIW), LIW, LW
REAL (KIND=nag_wp) | FVEC(M), XC(N), B(LB), W(LW)
1:   IFLAG – INTEGERInput/Output
On entry: is set to a non-negative number.
On exit: if LSQHES resets IFLAG to some negative number, E04YBF will terminate immediately, with IFAIL set to your setting of IFLAG.
2:   M – INTEGERInput
On entry: the numbers m of residuals.
3:   N – INTEGERInput
On entry: the numbers n of variables.
4:   FVEC M – REAL (KIND=nag_wp) arrayInput
On entry: the value of the residual fi at the point x, for i=1,2,…,m, so that the values of the fi can be used in the calculation of the elements of B.
5:   XC N – REAL (KIND=nag_wp) arrayInput
On entry: the point x at which the elements of B are to be evaluated.
6:   B LB – REAL (KIND=nag_wp) arrayOutput
On exit: unless IFLAG is reset to a negative number B must contain the lower triangle of the matrix B x, evaluated at the point in XC, stored by rows. (The upper triangle is not needed because the matrix is symmetric.) More precisely, B j j-1/2+k must contain ∑i=1 m fi ∂2 fi ∂xj∂xk evaluated at the point x, for j=1,2,…,n and k=1,2,…,j.
7:   LB – INTEGERInput
On entry: gives the length of the array B.
8:   IW LIW – INTEGER arrayWorkspace
9:   LIW – INTEGERInput
10:   W LW – REAL (KIND=nag_wp) arrayWorkspace
11:   LW – INTEGERInput
As in LSQFUN, these arguments correspond to the arguments IW, LIW, W, LW of E04YBF. LSQHES must not change the first 5×N+M×N+N×N-1/2 (or 6+2×M if N=1) elements of W.
LSQHES must either be a module subprogram USEd by, or declared as EXTERNAL in, the (sub)program from which E04YBF is called. Arguments denoted as Input must not be changed by this procedure.
5:   X N – REAL (KIND=nag_wp) arrayInput
On entry: X j, for j=1,2,…,n, must be set to the coordinates of a suitable point at which to check the b jk calculated by LSQHES. ‘Obvious’ settings, such as 0 or 1, should not be used since, at such particular points, incorrect terms may take correct values (particularly zero), so that errors could go undetected. For a similar reason, it is preferable that no two elements of X should have the same value.
6:   FVEC M – REAL (KIND=nag_wp) arrayOutput
On exit: unless you set IFLAG negative in the first call of LSQFUN, FVEC i contains the value of fi at the point supplied by you in X, for i=1,2,…,m.
7:   FJAC LDFJACN – REAL (KIND=nag_wp) arrayOutput
On exit: unless you set IFLAG negative in the first call of LSQFUN, FJAC ij contains the value of the first derivative ∂fi ∂xj at the point given in X, as calculated by LSQFUN, for i=1,2,…,m and j=1,2,…,n.
8:   LDFJAC – INTEGERInput
On entry: the first dimension of the array FJAC as declared in the (sub)program from which E04YBF is called.
Constraint: LDFJAC≥M.
9:   B LB – REAL (KIND=nag_wp) arrayOutput
On exit: unless you set IFLAG negative in LSQHES, B j×j-1/2+k contains the value of b jk at the point given in X as calculated by LSQHES, for j=1,2,…,n and k=1,2,…,j.
10:   LB – INTEGERInput
On entry: the dimension of the array B as declared in the (sub)program from which E04YBF is called.
Constraint: LB≥N+1×N/2.
11:   IW LIW – INTEGER arrayWorkspace
This array appears in the argument list purely so that, if E04YBF is called by another library routine, the library routine can pass quantities to user-supplied subroutines LSQFUN and LSQHES via IW. IW is not examined or changed by E04YBF. In general you must provide an array IW, but are advised not to use it.
12:   LIW – INTEGERInput
On entry: the actual length of IW as declared in the subroutine from which E04YBF is called.
Constraint: LIW≥1.
13:   W LW – REAL (KIND=nag_wp) arrayWorkspace
14:   LW – INTEGERInput
On entry: the actual length of W as declared in the subroutine from which E04YBF is called.
Constraints:
  • if N>1, LW≥5×N+M+M×N+N×N-1/2;
  • if N=1, LW≥6+2×M.
15:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, because for this routine the values of the output arguments may be useful even if IFAIL≠0 on exit, the recommended value is -1. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Note: E04YBF may return useful information for one or more of the following detected errors or warnings.
Errors or warnings detected by the routine:
IFAIL<0
A negative value of IFAIL indicates an exit from E04YBF because you have set IFLAG negative in user-supplied subroutines LSQFUN or LSQHES. The setting of IFAIL will be the same as your setting of IFLAG. The check on LSQHES will not have been completed.
IFAIL=1
On entry, | M<N,
or | N<1,
or | LDFJAC<M,
or | LB<N+1×N/2,
or | LIW<1,
or | LW<5×N+M+M×N+N×N-1/2, if N>1,
or | LW<6+2×M, if N=1.
IFAIL=2
You should check carefully the derivation and programming of expressions for the b jk, because it is very unlikely that LSQHES is calculating them correctly.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

IFAIL is set to 2 if
yT Gy-p≥h yT Gy+1.0 or zT Gz-q≥h zT Gz+1.0
where h is set equal to ε (ε being the machine precision as given by X02AJF) and other quantities are defined as in Section 3.

8 Parallelism and Performance

E04YBF is not threaded in any implementation.

9 Further Comments

E04YBF calls LSQHES once and LSQFUN three times.

10 Example

Suppose that it is intended to use E04HEF to find least squares estimates of x 1,x 2 and x 3 in the model
y = x 1 + t 1 x 2 t 2+ x 3 t 3
using the 15 sets of data given in the following table.
y t 1 t 2 t 3 0.14 1.0 15.0 1.0 0.18 2.0 14.0 2.0 0.22 3.0 13.0 3.0 0.25 4.0 12.0 4.0 0.29 5.0 11.0 5.0 0.32 6.0 10.0 6.0 0.35 7.0 9.0 7.0 0.39 8.0 8.0 8.0 0.37 9.0 7.0 7.0 0.58 10.0 6.0 6.0 0.73 11.0 5.0 5.0 0.96 12.0 4.0 4.0 1.34 13.0 3.0 3.0 2.10 14.0 2.0 2.0 4.39 15.0 1.0 1.0
This example program could be used to check the b jk calculated by LSQHES required. (The call of E04YBF is preceded by a call of E04YAF to check LSQFUN which calculates the first derivatives.)

10.1 Program Text

Program Text (e04ybfe.f90)

10.2 Program Data

Program Data (e04ybfe.d)

10.3 Program Results

Program Results (e04ybfe.r)

E04 Chapter Contents
E04 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


E04YCF : NAG Library, Mark 26

E04 Chapter Contents
E04 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

E04YCF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

E04YCF returns estimates of elements of the variance-covariance matrix of the estimated regression coefficients for a nonlinear least squares problem. The estimates are derived from the Jacobian of the function f x at the solution.
This routine may be used following any one of the nonlinear least squares routines E04FCF, E04FYF, E04GBF, E04GDF, E04GYF, E04GZF, E04HEF or E04HYF.

2 Specification

SUBROUTINE E04YCF ( JOB, M, N, FSUMSQ, S, V, LDV, CJ, WORK, IFAIL)
INTEGER | JOB, M, N, LDV, IFAIL
REAL (KIND=nag_wp) | FSUMSQ, S(N), V(LDV,N), CJ(N), WORK(N)

3 Description

E04YCF is intended for use when the nonlinear least squares function, F x=fT x f x, represents the goodness-of-fit of a nonlinear model to observed data. The routine assumes that the Hessian of F x, at the solution, can be adequately approximated by 2 JT J, where J is the Jacobian of f x at the solution. The estimated variance-covariance matrix C is then given by
C=σ 2JT J-1,  JT J  nonsingular,
where σ 2 is the estimated variance of the residual at the solution, x-, given by
σ 2=F x- m-n ,
m being the number of observations and n the number of variables.
The diagonal elements of C are estimates of the variances of the estimated regression coefficients. See the E04 Chapter Introduction, Bard (1974) and Wolberg (1967) for further information on the use of C.
When JT J is singular then C is taken to be
C=σ 2 JT J †,
where JT J † is the pseudo-inverse of JT J, and
σ 2 = F x- m-k ,   k=rank ​J
but in this case the argument IFAIL is returned as nonzero as a warning to you that J has linear dependencies in its columns. The assumed rank of J can be obtained from IFAIL.
The routine can be used to find either the diagonal elements of C, or the elements of the jth column of C, or the whole of C.
E04YCF must be preceded by one of the nonlinear least squares routines mentioned in Section 1, and requires the arguments FSUMSQ, S and V to be supplied by those routines (e.g., see E04FCF). FSUMSQ is the residual sum of squares F x- and S and V contain the singular values and right singular vectors respectively in the singular value decomposition of J. S and V are returned directly by the comprehensive routines E04FCF, E04GBF, E04GDF and E04HEF, but are returned as part of the workspace argument W (from one of the easy-to-use routines). In the case of E04FYF, S starts at W NS, where
NS=6× N+2× M+M× N+1+ max 1, N × N-1 / 2
and in the cases of the remaining easy-to-use routines, S starts at W NS, where
NS=7× N+2× M+M× N+N× N+1 / 2+1+ max 1, N × N-1 / 2 .
The argument V starts immediately following the elements of S, so that V starts at W NV, where
NV=NS+N .
For all the easy-to-use routines the argument LDV must be supplied as N. Thus a call to E04YCF following E04FYF can be illustrated as
 .
 .
 .
 CALL E04FYF (M, N, LFUN1, X, FSUMSQ, W, LW, IUSER, RUSER, IFAIL)
 .
 .
 .
 NS = 6*N _ 2*M + M*N + 1 MAX((1,(N*(N-1))/2)
 NV = NS + N;
 CALL E04YCF (JOB, M, N, FSUMSQ, W(NS), W(NV), N, CJ, WORK, IFAIL)
where the arguments M, N, FSUMSQ and the n+n 2 elements W NS , W NS+1 , … , W NV+ N 2 -1 must not be altered between the calls to E04FYF and E04YCF. The above illustration also holds for a call to E04YCF following a call to one of E04GYF, E04GZF or E04HYF, except that NS must be computed as
NS=7× N+2× M+M× N+ N× N+1 /2+1+ max 1, N × N-1 / 2 .

4 References

Bard Y (1974) Nonlinear Parameter Estimation Academic Press
Wolberg J R (1967) Prediction Analysis Van Nostrand

5 Arguments

1:   JOB – INTEGERInput
On entry: which elements of C are returned as follows:
JOB=-1
The n by n symmetric matrix C is returned.
JOB=0
The diagonal elements of C are returned.
JOB>0
The elements of column JOB of C are returned.
Constraint: -1≤JOB≤N.
2:   M – INTEGERInput
On entry: the number m of observations (residuals fi x).
Constraint: M≥N.
3:   N – INTEGERInput
On entry: the number n of variables xj.
Constraint: 1≤N≤M.
4:   FSUMSQ – REAL (KIND=nag_wp)Input
On entry: the sum of squares of the residuals, F x-, at the solution x-, as returned by the nonlinear least squares routine.
Constraint: FSUMSQ≥0.0.
5:   S N – REAL (KIND=nag_wp) arrayInput
On entry: the n singular values of the Jacobian as returned by the nonlinear least squares routine. See Section 3 for information on supplying S following one of the easy-to-use routines.
6:   V LDVN – REAL (KIND=nag_wp) arrayInput/Output
On entry: the n by n right-hand orthogonal matrix (the right singular vectors) of J as returned by the nonlinear least squares routine. See Section 3 for information on supplying V following one of the easy-to-use routines.
On exit: if JOB≥0, V is unchanged.
If JOB=-1, the leading n by n part of V is overwritten by the n by n matrix C. When E04YCF is called with JOB=-1 following an easy-to-use routine this means that C is returned, column by column, in the n 2 elements of W given by W NV,W NV+1,…,W NV+N 2-1. (See Section 3 for the definition of NV.)
7:   LDV – INTEGERInput
On entry: the first dimension of the array V as declared in the (sub)program from which E04YCF is called. When V is passed in the workspace argument W (following one of the easy-to-use least square routines), LDV must be the value N.
Constraint: if JOB=-1, LDV≥N.
8:   CJ N – REAL (KIND=nag_wp) arrayOutput
On exit: if JOB=0, CJ returns the n diagonal elements of C.
If JOB=j>0, CJ returns the n elements of the jth column of C.
If JOB=-1, CJ is not referenced.
9:   WORK N – REAL (KIND=nag_wp) arrayWorkspace
If JOB=-1 or 0, WORK is used as internal workspace.
If JOB>0, WORK is not referenced.
10:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, because for this routine the values of the output arguments may be useful even if IFAIL≠0 on exit, the recommended value is -1. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Note: E04YCF may return useful information for one or more of the following detected errors or warnings.
Errors or warnings detected by the routine:
IFAIL=1
On entry, | JOB<-1,
or | JOB>N,
or | N<1,
or | M<N,
or | FSUMSQ<0.0,
or | LDV<N.
IFAIL=2
The singular values are all zero, so that at the solution the Jacobian matrix J has rank 0.
IFAIL>2
At the solution the Jacobian matrix contains linear, or near linear, dependencies amongst its columns. In this case the required elements of C have still been computed based upon J having an assumed rank given by IFAIL-2. The rank is computed by regarding singular values SV j that are not larger than 10 ε×SV 1 as zero, where ε is the machine precision (see X02AJF). If you expect near linear dependencies at the solution and are happy with this tolerance in determining rank you should call E04YCF with IFAIL=1 in order to prevent termination (see the description of IFAIL). It is then essential to test the value of IFAIL on exit from E04YCF.
Overflow
If overflow occurs then either an element of C is very large, or the singular values or singular vectors have been incorrectly supplied.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

The computed elements of C will be the exact covariances corresponding to a closely neighbouring Jacobian matrix J.

8 Parallelism and Performance

E04YCF is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
E04YCF makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

When JOB=-1 the time taken by E04YCF is approximately proportional to n 3. When JOB≥0 the time taken by the routine is approximately proportional to n 2.

10 Example

This example estimates the variance-covariance matrix C for the least squares estimates of x 1, x 2 and x 3 in the model
y=x 1+t 1 x 2t 2+x 3t 3
using the 15 sets of data given in the following table:
y t 1 t 2 t 3 0.14 1.0 15.0 1.0 0.18 2.0 14.0 2.0 0.22 3.0 13.0 3.0 0.25 4.0 12.0 4.0 0.29 5.0 11.0 5.0 0.32 6.0 10.0 6.0 0.35 7.0 9.0 7.0 0.39 8.0 8.0 8.0 0.37 9.0 7.0 7.0 0.58 10.0 6.0 6.0 0.73 11.0 5.0 5.0 0.96 12.0 4.0 4.0 1.34 13.0 3.0 3.0 2.10 14.0 2.0 2.0 4.39 15.0 1.0 1.0
The program uses 0.5,1.0,1.5 as the initial guess at the position of the minimum and computes the least squares solution using E04FYF. See the routine document E04FYF for further information.

10.1 Program Text

Program Text (e04ycfe.f90)

10.2 Program Data

Program Data (e04ycfe.d)

10.3 Program Results

Program Results (e04ycfe.r)

E04 Chapter Contents
E04 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


E04ZMF : NAG Library, Mark 26

E04 Chapter Contents
E04 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

E04ZMF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
10 Example

1 Purpose

E04ZMF is an option setting routine for solvers from the NAG optimization modelling suite, namely E04STF and E04SVF. It can set a single optional parameter or reset all of them to their default.

2 Specification

SUBROUTINE E04ZMF ( HANDLE, OPTSTR, IFAIL)
INTEGER | IFAIL
CHARACTER(*) | OPTSTR
TYPE (C_PTR) | HANDLE

3 Description

E04ZMF can only be called on handles which have been initialized by E04RAF and not during the call to the solver. It has two purposes: to reset all optional parameters to their default values; or to set a single optional parameter to a user-supplied value.
Optional parameters and their values are, in general, presented as a character string, OPTSTR, of the form ‘option=optval’; alphabetic characters can be supplied in either upper or lower case. Both option and optval may consist of one or more tokens separated by white space. The tokens that comprise optval will normally be either an integer, real or character value as defined in the description of the specific optional argument. In addition all optional parameters can take an optval DEFAULT which resets the optional parameter to its default value.
Information relating to available option names and their corresponding valid values is given in the documentation of the particular solver. See also E04RAF for a generic description of the suite.

4 References

None.

5 Arguments

1:   HANDLE – TYPE (C_PTR)Input
On entry: the handle to the problem. It needs to be initialized by E04RAF and must not be changed.
2:   OPTSTR – CHARACTER(*)Input
On entry: a string identifying the option and its value to be set.
Defaults
Resets all options to their default values.
Option=optval
See the documentation of the particular solver for details of valid values for option and optval. The equals sign (=) delimiter must be used to separate the option from its optval value.
Option=Default
Resets the given option back to its default value.
OPTSTR is case insensitive. Each token in the option and optval component must be separated by at least one space.
3:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
The supplied HANDLE does not define a valid handle to the data structure for the NAG optimization modelling suite. It has not been initialized by E04RAF or it has been corrupted.
IFAIL=2
The options cannot be modified in this phase.
IFAIL=11
On entry, the option supplied in OPTSTR was not recognized: OPTSTR=value.
IFAIL=12
On entry, the expected delimiter ‘=’ was not found in OPTSTR: OPTSTR=value.
IFAIL=13
On entry, could not convert the specified optval to an integer: optval=value.
On entry, could not convert the specified optval to a real: optval=value.
IFAIL=15
On entry, the optval supplied for the integer optional parameter is not valid.
option=value, optval=value.
Constraint: optval<value.
On entry, the optval supplied for the integer optional parameter is not valid.
option=value, optval=value.
Constraint: optval>value.
On entry, the optval supplied for the integer optional parameter is not valid.
option=value, optval=value.
Constraint: optval≤value.
On entry, the optval supplied for the integer optional parameter is not valid.
option=value, optval=value.
Constraint: optval≥value.
IFAIL=16
On entry, the optval supplied for the real optional parameter is not valid.
option=value, optval=value.
Constraint: optval<value.
On entry, the optval supplied for the real optional parameter is not valid.
option=value, optval=value.
Constraint: optval>value.
On entry, the optval supplied for the real optional parameter is not valid.
option=value, optval=value.
Constraint: optval≤value.
On entry, the optval supplied for the real optional parameter is not valid.
option=value, optval=value.
Constraint: optval≥value.
IFAIL=17
On entry, the optval supplied for the character optional parameter is not valid.
option=value, optval=value.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

Not applicable.

8 Parallelism and Performance

E04ZMF is not threaded in any implementation.

9 Further Comments

None.

10 Example

See the example programs associated with the solvers E04STF and E04SVF for a demonstration of how to use E04ZMF. See also Section 10 in E04RAF for links to all examples in this suite.
E04 Chapter Contents
E04 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


E04ZNF : NAG Library, Mark 26

E04 Chapter Contents
E04 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

E04ZNF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
10 Example

1 Purpose

E04ZNF is an option getting routine for solvers from the NAG optimization modelling suite, namely E04STF and E04SVF. It is used to query the value of optional parameters.

2 Specification

SUBROUTINE E04ZNF ( HANDLE, OPTSTR, IVALUE, RVALUE, CVALUE, OPTYPE, IFAIL)
INTEGER | IVALUE, OPTYPE, IFAIL
REAL (KIND=nag_wp) | RVALUE
CHARACTER(*) | OPTSTR, CVALUE
TYPE (C_PTR) | HANDLE

3 Description

E04ZNF is used to query the current values of options. It can be especially useful to retrieve the optional parameters left for automatic choice by the solver.
This routine will normally return either an integer, real or character value dependent upon the type associated with the optional parameter being queried. This is indicated by the returned value of OPTYPE.
Information relating to available option names is given in the documentation of the particular solver. See also E04RAF for a generic description of the suite.

4 References

None.

5 Arguments

1:   HANDLE – TYPE (C_PTR)Input
On entry: the handle to the problem. It needs to be initialized by E04RAF and must not be changed.
2:   OPTSTR – CHARACTER(*)Input
On entry: a string identifying the option whose current value is required. See the documentation of the particular solver for information on valid options.
3:   IVALUE – INTEGEROutput
On exit: if the optional parameter supplied in OPTSTR is an integer-valued argument, IVALUE will hold its current value.
4:   RVALUE – REAL (KIND=nag_wp)Output
On exit: if the optional parameter supplied in OPTSTR is a real-valued argument, RVALUE will hold its current value.
5:   CVALUE – CHARACTER(*)Output
Note: the string returned in CVALUE will never exceed 40 characters in length.
On exit: if the optional parameter supplied in OPTSTR is a character-valued argument, CVALUE will hold its current value.
6:   OPTYPE – INTEGEROutput
On exit: indicates whether the optional parameter supplied in OPTSTR is an integer, real or character-valued argument and hence which of IVALUE, RVALUE or CVALUE holds the current value.
OPTYPE=1
OPTSTR is an integer-valued optional parameter; its current value has been returned in IVALUE.
OPTYPE=2
OPTSTR is a real-valued optional parameter; its current value has been returned in RVALUE.
OPTYPE=3
OPTSTR is a character-valued optional parameter; its current value has been returned in CVALUE.
7:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
The supplied HANDLE does not define a valid handle to the data structure for the NAG optimization modelling suite. It has not been initialized by E04RAF or it has been corrupted.
IFAIL=11
On entry, the option supplied in OPTSTR was not recognized: OPTSTR=value.
IFAIL=41
On entry, OPTSTR indicates a character optional parameter, but CVALUE is too short to hold the stored value. The returned value will be truncated.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

Not applicable.

8 Parallelism and Performance

E04ZNF is not threaded in any implementation.

9 Further Comments

None.

10 Example

See the example program associated with the solver E04SVF for a demonstration of how to use E04ZNF to query options. See also Section 10 in E04RAF for links to all examples in the suite.
E04 Chapter Contents
E04 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


E04ZPF : NAG Library, Mark 26

E04 Chapter Contents
E04 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

E04ZPF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
10 Example

1 Purpose

E04ZPF is an option setting routine for solvers from the NAG optimization modelling suite, namely E04STF and E04SVF. It can set one or more optional parameters from an external file.

2 Specification

SUBROUTINE E04ZPF ( HANDLE, INFILE, IFAIL)
INTEGER | INFILE, IFAIL
TYPE (C_PTR) | HANDLE

3 Description

E04ZPF may be used to supply values for optional parameters to the solver from an external file. It can only be called on handles which have been initialized by E04RAF and before the call to the solver. E04ZPF looks in the file for a specific section containing the optional parameters. The section must start with a line Begin and must finish with a line End. Anything outside the section is ignored. If there is more than one section like this, only the first one is processed. Any line within the section is either blank or a comment which is ignored or defines a single optional parameter as if it had been set by E04ZMF. The implied data type (character, integer or real) of each value to be set must match that expected by the corresponding optional parameter. It is only necessary to supply values for those arguments whose values are to be different from their default values. A comment begins with an asterisk (*) and all subsequent characters to the end of the line are ignored. Comments can also be placed after the optional parameter. The file is case insensitive.
Note that the optional parameters printed by the solver or by E04RYF are in the compatible format. An example of a valid options file is:
Begin * Example options file
   Print Level = 3
   Monitoring Level = 5 * output all details
   Monitoring File = 42 * to this file
End

4 References

None.

5 Arguments

1:   HANDLE – TYPE (C_PTR)Input
On entry: the handle to the problem. It needs to be initialized by E04RAF and must not be changed.
2:   INFILE – INTEGERInput
On entry: the file identifier associated with the argument data file. Note: that the file needs to be opened in read mode by X04ACF with MODE=0.
Constraint: INFILE≥0.
3:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
The supplied HANDLE does not define a valid handle to the data structure for the NAG optimization modelling suite. It has not been initialized by E04RAF or it has been corrupted.
IFAIL=2
The options cannot be modified in this phase.
IFAIL=3
On entry, INFILE=value.
Constraint: INFILE≥0.
IFAIL=4
BEGIN found, but end-of-file found before END. All optional parameters that were set from the file before this error was encountered will remain set on exit.
End-of-file or read error detected before BEGIN was found.
IFAIL=11
The option provided on line value was not recognized.
IFAIL=12
The expected delimiter ‘=’ was not found on line value.
IFAIL=13
The optval provided on line value could not be converted to the expected numerical type.
IFAIL=15
The optval provided on line value for the integer optional parameter is out of bounds.
IFAIL=16
The optval provided on line value for the real optional parameter is out of bounds.
IFAIL=17
The optval provided on line value for the character optional parameter is not valid.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

Not applicable.

8 Parallelism and Performance

E04ZPF is not threaded in any implementation.

9 Further Comments

None.

10 Example

See Section 10 in E04RAF for links to all examples in the suite.
E04 Chapter Contents
E04 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


E05 Chapter Contents : NAG Library Manual, Mark 26

E05 Chapter Introduction
NAG Library Manual

NAG Library Chapter Contents

E05 – Global Optimization of a Function

E05 Chapter Introduction – a description of the Chapter and an overview of the algorithms available

Routine Name | Mark of Introduction | Purpose
E05JAF | 22 | nagf_glopt_bnd_mcs_init Initialization routine for E05JBF
E05JBF Example Text Example Data Example Plot | 22 | nagf_glopt_bnd_mcs_solve Global optimization by multi-level coordinate search, simple bounds, using function values only
E05JCF Example Text Example Options Example Data Example Plot | 22 | nagf_glopt_bnd_mcs_optset_file Supply optional parameter values for E05JBF from external file
E05JDF | 22 | nagf_glopt_bnd_mcs_optset_string Set a single optional parameter for E05JBF from a character string
E05JEF | 22 | nagf_glopt_bnd_mcs_optset_char Set a single optional parameter for E05JBF from an ‘ON’/‘OFF’-valued character argument
E05JFF | 22 | nagf_glopt_bnd_mcs_optset_int Set a single optional parameter for E05JBF from an integer argument
E05JGF | 22 | nagf_glopt_bnd_mcs_optset_real Set a single optional parameter for E05JBF from a real argument
E05JHF | 22 | nagf_glopt_bnd_mcs_option_check Determine whether an optional parameter for E05JBF has been set by you or not
E05JJF | 22 | nagf_glopt_bnd_mcs_optget_char Get the setting of an ‘ON’/‘OFF’-valued character optional parameter of E05JBF
E05JKF | 22 | nagf_glopt_bnd_mcs_optget_int Get the setting of an integer valued optional parameter of E05JBF
E05JLF | 22 | nagf_glopt_bnd_mcs_optget_real Get the setting of a real valued optional parameter of E05JBF
E05SAF Example Text Example Text | 23 | nagf_glopt_bnd_pso Global optimization using particle swarm algorithm (PSO), bound constraints only
E05SBF Example Text | 23 | nagf_glopt_nlp_pso Global optimization using particle swarm algorithm (PSO), comprehensive
E05UCF Example Text Example Data | 24 | nagf_glopt_nlp_multistart_sqp Global optimization using multi-start, nonlinear constraints
E05USF Example Text Example Data | 24 | nagf_glopt_nlp_multistart_sqp_lsq Global optimization of a sum of squares problem using multi-start, nonlinear constraints
E05ZKF | 23 | nagf_glopt_optset Option setting routine for E05SAF, E05SBF, E05UCF and E05USF
E05ZLF | 23 | nagf_glopt_optget Option getting routine for E05SAF, E05SBF, E05UCF and E05USF
E05 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


E05 Chapter Introduction : NAG Library, Mark 26

E05 Chapter Contents
NAG Library Manual

NAG Library Chapter Introduction

E05 – Global Optimization of a Function

▸▿ Contents

1 Scope of the Chapter
▸▿ 2 Background to the Problems
2.1 Problem Formulation
▸▿ 2.2 Terminology
2.2.1 Complete Methods
2.2.2 Branching
▸▿ 2.3 Methods of Global Optimization
2.3.1 Multi-level Coordinate Search (MCS)
2.3.2 Particle Swarm Optimization
2.3.3 Multiple Start
3 Recommendations on Choice and Use of Available Routines
4 Functionality Index
5 Auxiliary Routines Associated with Library Routine Arguments
6 Routines Withdrawn or Scheduled for Withdrawal
7 References

1 Scope of the Chapter

Global optimization involves finding the absolute maximum or minimum value of a function (the objective function) of several variables, possibly subject to restrictions (defined by a set of bounds or constraint functions) on the values of the variables. Such problems can be much harder to solve than local optimization problems (which are discussed in Chapter E04) because it is difficult to determine whether a potential optimum found is global, and because of the nonlocal methods required to avoid becoming trapped near local optima. Most optimization routines in the NAG Library are concerned with function minimization only, since the problem of maximizing a given objective function F is equivalent to minimizing -F. In E05JBF, E05SAF and E05SBF, you may specify whether you are solving a minimization or maximization problem; in the latter case, the required transformation of the objective function will be carried out automatically. In what follows we refer exclusively to minimization problems.
This introduction is a brief guide to the subject of global optimization, designed for the casual user. For further details you may find it beneficial to consult a more detailed text, see Neumaier (2004). Furthermore, much of the material in the E04 Chapter Introduction is also relevant in this context and it is strongly recommended that you read Section 2.6 in the E04 Chapter Introduction.

2 Background to the Problems

2.1 Problem Formulation

For the purposes of this Library, the global optimization problem is
minimize x∈Rn F x   subject to   lx ≤ x ≤ ux   and   lc ≤ c x ≤ uc , (1)
where F x (the objective function) is a real function; the vectors lx and ux are elements of R-n, where R- denotes the extended reals R∪-∞,∞; and where c is a vector of m constraint functions c 1,…,cm, with lc and uc defining the constraints on c x. If m=0 the problem is said to be bound constrained. Relational operators between vectors are interpreted elementwise. The feasible region Φ is the set of all points (feasible points) that satisfy all of the constraints. A solution of (1) is a feasible point x^∈Φ satisfying
F x^ = min x∈Φ F x.
A local minimum minimizes F only on some neighbourhood of x^. If a local minimum has the smallest objective value over all the local minima, then it is a global minimum.

2.2 Terminology

2.2.1 Complete Methods

A global optimization algorithm is called asymptotically complete if
(i) | assuming indefinitely long run-time and exact computations, a global minimum will be found with certainty (probability one), but
(ii) | the algorithm has no way of knowing when a global minimum has been found.
In comparison, a complete method satisfies (i) as well as the algorithm being able to recognize a global minimum (to prescribed tolerances) within a finite amount of time.
It is important to appreciate that, for finding a solution exactly, bounds on the amount of work may be very pessimistic. What complete methods guarantee is the absence of any deficiency that would prevent a global minimum from eventually being found. To achieve termination with certainty in a finite amount of time, the algorithm requires access to global information about the problem. In the case where only function values are available, as in E05JBF, stopping criteria based on heuristics are present. This is because such a class of method can only terminate with certainty by performing an expensive dense search.
In contrast, incomplete methods have intuitive heuristics for searching but no guarantee of not getting stuck near nonglobal, local, minima. Often, to make incomplete methods efficient, expert knowledge on the particular problem class to be solved is required. Examples of incomplete methods include Particle Swarm Optimization (PSO), Genetic Algorithms (GA), Simulated Annealing (SA), Ant Colony Optimization (ACO) and Covariance Matrix Adaptation Evolutionary Strategies (CMA-ES). PSO has been implemented in the routines E05SAF and E05SBF. Such routines must also use heuristics to stop the algorithm as again an expensive, dense search would be required to guarantee that no superior optima are present.
The heuristic nature of incomplete algorithms can make them very efficiently parallelizable. This is the case for E05SAF and E05SBF, which use a heavily asynchronous implementation of the particle swarm heuristic to be efficient in achieving a good solution in multi-threaded implementations of NAG Library.

2.2.2 Branching

Most complete methods recursively split the original problem into smaller, more manageable subproblems. This technique is called branching. Branching is usually accompanied by a selection process that splits favourable branches more frequently than others. For example, with branch and bound methods, bounds on the objective function for each subproblem are computed in an attempt to eliminate those subregions where no improvement will occur.
Branching methods use a branching scheme to generate sequences of sub-boxes that eventually cover the feasible region. At least one function evaluation is made for every sub-box, and new sub-boxes are generated by splitting existing ones. Using appropriate splitting rules, convergence to zero of the diameters of sub-boxes is assured. For example, always splitting the oldest box along the oldest side, provided the children do not have too small a volume compared with the parent, guarantees convergence of the method, in the sense described in Neumaier (2004).
Efficiency can be enhanced by carefully balancing global and local searches. While the global part of the search splits sub-boxes with large unexplored territory, the local part usually entails splitting boxes with good function values. For example, the sub-box with the best function value should always be split. A method may also be improved by launching local searches from appropriate candidate local minima.

2.3 Methods of Global Optimization

2.3.1 Multi-level Coordinate Search (MCS)

The routine E05JBF searches for a global minimizer using branching to recursively split the search space in a nonuniform manner. It divides, or splits, the root box of the search into smaller sub-boxes. Each sub-box contains a distinguished basepoint at which the objective function is sampled. We shall sometimes say ‘the function value of the (sub)box’ as shorthand for ‘the function value of the basepoint of the (sub)box’. The splitting procedure biases the search in favour of those sub-boxes where low function values are expected.
The global part of the algorithm entails splitting sub-boxes that enclose large unexplored territory, while the local part of the algorithm entails splitting sub-boxes that have good function values. A balance between the global and local part is achieved using a multi-level approach, where every sub-box is assigned a level s∈0,1,…,smax. You can control the value of smax using the optional parameter Splits Limit. Whenever a sub-box of intermediate level 0<s<smax is split each descendant will be given a new level, and the original sub-box's level is set to 0: a sub-box with level 0 has already been split; a sub-box with level smax will be split no further. This entire process is described in more detail in Section 11.1 in E05JBF, where the initialization procedure used to produce an initial set of sub-boxes is outlined, and the method by which the algorithm sweeps through levels is discussed. Each sweep starts with the sub-boxes at the lowest level, a process thus forming the global part of the algorithm. At each level the sub-box with the best function value is selected for splitting; this forms the local part of the algorithm.
The process by which sub-boxes are split is explained in Section 11.2 in E05JBF. It is a variant of the standard coordinate search method: the solver splits along a single coordinate at a time, at adaptively chosen points. In most cases one new function evaluation is needed to split a sub-box into two or three children. Each child is given a basepoint chosen to differ from the basepoint of the parent in at most one coordinate, and safeguards are present to ensure a degree of symmetry in the splits.
If you set the optional parameter Local Searches to be OFF, then the basepoints and function values of sub-boxes of maximum level smax are put into a ‘shopping basket’ of candidate minima. Turning Local Searches ON (the default setting) will enable local searches to be started from these basepoints before they go into the shopping basket. The local search will go ahead providing the basepoint is not likely to be in the basin of attraction of a previously-found local minimum. The search itself uses a trust region approach, and is explained in Section 11.3 in E05JBF: local quadratic models are built by a triple search, then a linesearch is made along the direction obtained by minimizing the quadratic on a region where it is a good approximation to the objective function. The quadratic need not be positive definite, so the general nonlinear optimizer E04VHF is used to minimize the model.

2.3.2 Particle Swarm Optimization

The routines E05SAF and E05SBF search for a global optimum using a variant of the Particle Swarm Optimization (PSO) algorithm. PSO is an heuristic algorithm similar in its behaviour to GA, ACO, SA and others. A set of particles (the swarm) is generated in the search space, and advances at each iteration following an heuristic velocity based upon the best candidate found by an individual particle (cognitive memory), the best candidate found by all the particles (global memory) and inertia. The inertia is provided by a decreasingly weighted contribution from a particle's current velocity. This mix allows for a global search of the domain in question.
The rate at which the swarm contracts and expands about potential optima is user controllable, allowing expert knowledge to be used when available. Furthermore, the algorithm may be coupled with a selection of local optimizers. These may be called during the iterations of the heuristic algorithm (the interior phase) to hasten the discovery of locally optimal points. They may also be called following the heuristic iterations (the exterior phase) to attempt to refine the final solution. Different options may be set for the local optimizer in each phase. For further details see Section 11 in E05SAF and E05SBF.
These routines are most effectively used when multiple cores are available for computation, since very many function evaluations are required for a typical problem. In multi-threaded implementations of the NAG Library the algorithm has been parallelized to allow for high levels of asynchronicity between threads. This allows individual threads to continue searching without the requirement for all threads to have returned solutions, and leads to excellent parallel speedup.

2.3.3 Multiple Start

Routine E05UCF attempts to find the global minimum of an arbitrary smooth function subject to constraints (which may include simple bounds on the variables, linear constraints and smooth nonlinear constraints) by generating a number of different starting points and using the local minimizer E04UCA. Routine E05USF takes the same approach in attempting to find the global minimum of an arbitrary smooth sum of squares function using the local minimizer E04USA.
The more starting points chosen, the greater the degree of confidence that you might have in the returned results. Facilities are provided to allow you to specify the starting points and to provide for subsequent runs with different starting points as an additional means of gaining confidence in the results.
You may also request that a number of solutions be provided, ordered in increasing value of the local optima. This may be useful if a local solution has a desirable property not exhibited by the best local optimum computed, the putative global optimum.

3 Recommendations on Choice and Use of Available Routines

The suite of multi-level coordinate search routines consists of:
  • an initialization routine:
    • E05JAF;
  • optional parameter setting routines:
    • E05JCF,
    • E05JDF,
    • E05JEF,
    • E05JFF,
    • E05JGF;
  • an optional parameter checking routine:
    • E05JHF;
  • optional parameter getting routines:
    • E05JKF,
    • E05JLF;
  • and the solver:
    • E05JBF.
E05JBF is based on the multi-level coordinate search method of Huyer and Neumaier (1999). It is an asymptotically complete method for bound constrained problems based on local information (function values) only, employing branching and local searches to accelerate convergence.
If the problem has nonlinear constraints and is sufficiently smooth then you are advised to consider a multiple start technique. E05UCF and E05USF are provided for this purpose. Both E05UCF and E05USF use the routines E05ZKF and E05ZLF for initialization and option setting.
The suite of particle swarm optimization (PSO) routines are to be considered as experimental and are not recommended for production or mission-critical applications. They are only recommended as a last resort (should other methods fail) or for comparitive purposes.
The suite consists of the solver routines:
  • E05SAF;
  • E05SBF.
Both E05SAF and E05SBF use the routines E05ZKF and E05ZLF for initialization and option setting. These routines predominantly use function values only, although derivatives can be provided for coupled local minimization routines. They are designed for use primarily with multi-threaded implementations of the NAG Library (although they may also be used in serial implementations). In such implementations, a minimal knowledge of OpenMP parallel programming is required, specifically the use of basic OpenMP commands and operators such as OMP_GET_THREAD_NUM and CRITICAL sections to ensure the thread safety of provided callback routines. Additional example programs are provided to demonstrate how this may be done (see Section 10 in E05SAF and E05SBF).
E05SAF is a simplified version of E05SBF with less functionality. In particular, E05SAF does not support general constraint handling whereas E05SBF does support general nonlinear, non-equality constraints.
If the objective function is smooth and the problem has only simple bound constraints then both algorithms are applicable. For low dimensional problems (up to 20) E05JBF is preferred. With increasing dimension the multi-start methods may be better, especially when parallelism can be exploited by using multi-threaded implementations of the NAG Library.
The particle swarm methods are potentially useful when there is no smoothness in the objective function (e.g., due to noise) and, for the simple-bound constrained problem, E05SAF may be appropriate.
Currently there is no routine in this chapter using a complete method that can handle constraints that are not bound constraints.

4 Functionality Index

Global optimization, function of several real variables, general constraints,
multi-start E05UCF
using function values predominantly, and optional derivative information, PSO E05SBF
Global optimization, function of several real variables, sum of squares, general constraints,
multi-start E05USF
Global optimum, function of several variables, bound constraints,
using function values only E05JBF
using function values predominantly, and optional derivative information, PSO E05SAF
Service routines,
check whether optional parameter has been set for E05JBF E05JHF
initialization routine for E05JBF E05JAF
optional parameter getting routine for use with E05SAF, E05SBF, E05UCF and E05USF E05ZLF
optional parameter setting routine for use with E05SAF, E05SBF, E05UCF and E05USF E05ZKF
retrieve integer optional parameter values used by E05JBF E05JKF
retrieve real optional parameter values used by E05JBF E05JLF
retrieve value of ‘ON’/‘OFF’-valued character optional parameter used by E05JBF E05JJF
supply integer optional parameter values to E05JBF E05JFF
supply ‘ON’/‘OFF’-valued character optional parameter values to E05JBF E05JEF
supply optional parameter values from character string to E05JBF E05JDF
supply optional parameter values from external file for E05JBF E05JCF
supply real optional parameter values to E05JBF E05JGF

5 Auxiliary Routines Associated with Library Routine Arguments

E05JBK | nagf_glopt_bnd_mcs_dummy_monit See the description of the argument MONIT in E05JBF.
E05SXM | nagf_glopt_bnd_pso_dummy_monmod See the description of the argument MONMOD in E05SAF.
E05SYM | nagf_glopt_nlp_pso_dummy_monmod See the description of the argument MONMOD in E05SBF.
E05SZM | nagf_glopt_nlp_pso_dummy_confun See the description of the argument CONFUN in E05SBF.
E05UCZ | nagf_glopt_multistart_start_points See the description of the argument START in E05UCF.

6 Routines Withdrawn or Scheduled for Withdrawal

None.

7 References

Gill P E, Murray W and Wright M H (1981) Practical Optimization Academic Press
Huyer W and Neumaier A (1999) Global optimization by multi-level coordinate search Journal of Global Optimization 14 331–355
Kennedy J and Eberhart R C (1995) Particle Swarm Optimization Proceedings of the 1995 IEEE International Conference on Neural Networks 1942–1948
Koh B, George A D, Haftka R T and Fregly B J (2006) Parallel Asynchronous Particle Swarm Optimization International Journal for Numerical Methods in Engineering 67(4) 578–595
Neumaier A (2004) Complete search in constrained global optimization Acta Numerica 13 271–369
Vaz A I and Vicente L N (2007) A Particle Swarm Pattern Search Method for Bound Constrained Global Optimization Journal of Global Optimization 39(2) 197–219 Kluwer Academic Publishers
E05 Chapter Contents
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


E05JAF : NAG Library, Mark 26

E05 Chapter Contents
E05 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

E05JAF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
10 Example

1 Purpose

E05JAF is used to initialize communication data for the suite of multi-level coordinate search routines: E05JBF, E05JCF, E05JDF, E05JEF, E05JFF, E05JGF, E05JHF, E05JJF, E05JKF and E05JLF.

2 Specification

SUBROUTINE E05JAF ( N_R, COMM, LCOMM, IFAIL)
INTEGER | N_R, LCOMM, IFAIL
REAL (KIND=nag_wp) | COMM(LCOMM)

3 Description

E05JAF initializes the communication array COMM for the solver E05JBF and the optional-argument handlers E05JCF, E05JDF, E05JEF, E05JFF, E05JGF, E05JHF, E05JJF, E05JKF and E05JLF.

4 References

None.

5 Arguments

1:   N_R – INTEGERDummy
This argument is no longer accessed by E05JAF.
2:   COMM LCOMM – REAL (KIND=nag_wp) arrayCommunication Array
On exit: COMM must not be altered between calls to any of the routines E05JBF, E05JCF, E05JDF, E05JEF, E05JFF, E05JGF, E05JHF, E05JJF, E05JKF and E05JLF.
3:   LCOMM – INTEGERInput
On entry: the dimension of the array COMM as declared in the (sub)program from which E05JAF is called.
Constraint: LCOMM≥100.
4:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, LCOMM=value.
Constraint: LCOMM≥100.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

Not applicable.

8 Parallelism and Performance

E05JAF is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The time taken by E05JAF is negligible.

10 Example

See Section 10 in E05JBF and E05JCF.
E05 Chapter Contents
E05 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


E05JBF : NAG Library, Mark 26

E05 Chapter Contents
E05 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

E05JBF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.
Note: this routine uses optional parameters to define choices in the problem specification and in the details of the algorithm. If you wish to use default settings for all of the optional parameters, you need only read Sections 1 to 10 of this document. If, however, you wish to reset some or all of the settings please refer to Section 11 for a detailed description of the algorithm, and to Section 12 for a detailed description of the specification of the optional parameters.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results
▸▿ 11 Algorithmic Details
11.1 Initialization and Sweeps
▸▿ 11.2 Splitting
11.2.1 Splitting by rank
11.2.2 Splitting by expected gain
11.3 Local Search
▸▿ 12 Optional Parameters
12.1 Description of the Optional Parameters

1 Purpose

E05JBF is designed to find the global minimum or maximum of an arbitrary function, subject to simple bound-constraints using a multi-level coordinate search method. Derivatives are not required, but convergence is only guaranteed if the objective function is continuous in a neighbourhood of a global optimum. It is not intended for large problems.
The initialization routine E05JAF must have been called before calling E05JBF.

2 Specification

SUBROUTINE E05JBF ( N, OBJFUN, IBOUND, IINIT, BL, BU, SDLIST, LIST, NUMPTS, INITPT, MONIT, X, OBJ, COMM, LCOMM, IUSER, RUSER, IFAIL)
INTEGER | N, IBOUND, IINIT, SDLIST, NUMPTS(N), INITPT(N), LCOMM, IUSER(*), IFAIL
REAL (KIND=nag_wp) | BL(N), BU(N), LIST(N,SDLIST), X(N), OBJ, COMM(LCOMM), RUSER(*)
EXTERNAL | OBJFUN, MONIT
E05JAF must be called before calling E05JBF, or any of the option-setting or option-getting routines E05JCF, E05JDF, E05JEF, E05JFF, E05JGF, E05JHF, E05JJF, E05JKF or E05JLF.
You must not alter the number of non-fixed variables in your problem or the contents of the array COMM between calls of the routines E05JAF, E05JBF, E05JCF, E05JDF, E05JEF, E05JFF, E05JGF, E05JHF, E05JJF, E05JKF or E05JLF.

3 Description

E05JBF is designed to solve modestly sized global optimization problems having simple bound-constraints only; it finds the global optimum of a nonlinear function subject to a set of bound constraints on the variables. Without loss of generality, the problem is assumed to be stated in the following form:
minimize x∈Rn F x   subject to   ℓ ≤ x ≤ u   and   ℓ≤u ,
where F x (the objective function) is a nonlinear scalar function (assumed to be continuous in a neighbourhood of a global minimum), and the bound vectors are elements of R-n, where R- denotes the extended reals R∪-∞,∞. Relational operators between vectors are interpreted elementwise.
The optional parameter Maximize should be set if you wish to solve maximization, rather than minimization, problems.
If certain bounds are not present, the associated elements of ℓ or u can be set to special values that will be treated as -∞ or +∞. See the description of the optional parameter Infinite Bound Size. Phrases in this document containing terms like ‘unbounded values’ should be understood to be taken relative to this optional parameter.
Fixing variables (that is, setting li=ui for some i) is allowed in E05JBF.
A typical excerpt from a routine calling E05JBF is:
CALL E05JAF (N_R, COMM, LCOMM, ...)
CALL E05JDF (OPTSTR, COMM, LCOMM, ...)
CALL E05JBF (N, OBJFUN, ...)
where E05JDF sets the optional parameter and value specified in OPTSTR.
The initialization routine E05JAF does not need to be called before each invocation of E05JBF. You should be aware that a call to the initialization routine will reset each optional parameter to its default value, and, if you are using repeatable randomized initialization lists (see the description of the argument IINIT), the random state stored in the array COMM will be destroyed.
You must supply a subroutine that evaluates F x; derivatives are not required.
The method used by E05JBF is based on MCS, the Multi-level Coordinate Search method described in Huyer and Neumaier (1999), and the algorithm it uses is described in detail in Section 11.

4 References

Huyer W and Neumaier A (1999) Global optimization by multi-level coordinate search Journal of Global Optimization 14 331–355

5 Arguments

1:   N – INTEGERInput
On entry: n, the number of variables.
Constraint: N>0.
2:   OBJFUN – SUBROUTINE, supplied by the user.External Procedure
OBJFUN must evaluate the objective function F x for a specified n-vector x.
The specification of OBJFUN is:
SUBROUTINE OBJFUN ( N, X, F, NSTATE, IUSER, RUSER, INFORM)
INTEGER | N, NSTATE, IUSER(*), INFORM
REAL (KIND=nag_wp) | X(N), F, RUSER(*)
1:   N – INTEGERInput
On entry: n, the number of variables.
2:   X N – REAL (KIND=nag_wp) arrayInput
On entry: x, the vector at which the objective function is to be evaluated.
3:   F – REAL (KIND=nag_wp)Output
On exit: must be set to the value of the objective function at x, unless you have specified termination of the current problem using INFORM.
4:   NSTATE – INTEGERInput
On entry: if NSTATE=1 then E05JBF is calling OBJFUN for the first time. This argument setting allows you to save computation time if certain data must be read or calculated only once.
5:   IUSER* – INTEGER arrayUser Workspace
6:   RUSER* – REAL (KIND=nag_wp) arrayUser Workspace
OBJFUN is called with the arguments IUSER and RUSER as supplied to E05JBF. You are free to use the arrays IUSER and RUSER to supply information to OBJFUN as an alternative to using COMMON global variables.
7:   INFORM – INTEGEROutput
On exit: must be set to a value describing the action to be taken by the solver on return from OBJFUN. Specifically, if the value is negative the solution of the current problem will terminate immediately; otherwise, computations will continue.
OBJFUN must either be a module subprogram USEd by, or declared as EXTERNAL in, the (sub)program from which E05JBF is called. Arguments denoted as Input must not be changed by this procedure.
3:   IBOUND – INTEGERInput
On entry: indicates whether the facility for dealing with bounds of special forms is to be used. IBOUND must be set to one of the following values.
IBOUND=0
You will supply ℓ and u individually.
IBOUND=1
There are no bounds on x.
IBOUND=2
There are semi-infinite bounds 0≤x.
IBOUND=3
There are constant bounds ℓ=ℓ 1 and u=u 1.
Note that it only makes sense to fix any components of x when IBOUND=0.
Constraint: IBOUND=0, 1, 2 or 3.
4:   IINIT – INTEGERInput
On entry: selects which initialization method to use.
IINIT=0
Simple initialization (boundary and midpoint), with
NUMPTS i=3 , INITPT i=2 and
LIST ij = BL i, BL i + BU i / 2 ,BU i ,
for i=1,2,…,N and j=1,2,3.
IINIT=1
Simple initialization (off-boundary and midpoint), with
NUMPTS i=3 , INITPT i=2 and
LIST ij = 5 BL i+ BU i / 6 , BL i + BU i / 2 , BL i + 5 BU i / 6 ,
for i=1,2,…,N and j=1,2,3.
IINIT=2
Initialization using linesearches.
IINIT=3
You are providing your own initialization list.
IINIT=4
Generate a random initialization list.
For more information on methods IINIT=2, 3 or 4 see Section 11.1.
If ‘infinite’ values (as determined by the value of the optional parameter Infinite Bound Size) are detected by E05JBF when you are using a simple initialization method (IINIT=0 or 1), a safeguarded initialization procedure will be attempted, to avoid overflow.
Suggested value: IINIT=0.
Constraint: IINIT=0, 1, 2, 3 or 4.
5:   BL N – REAL (KIND=nag_wp) arrayInput/Output
6:   BU N – REAL (KIND=nag_wp) arrayInput/Output
On entry: BL is ℓ, the array of lower bounds. BU is u, the array of upper bounds.
If IBOUND=0, you must set BL i to ℓi and BU i to ui, for i=1,2,…,N. If a particular xi is to be unbounded below, the corresponding BL i should be set to -infbnd, where infbnd is the value of the optional parameter Infinite Bound Size. Similarly, if a particular xi is to be unbounded above, the corresponding BU i should be set to infbnd.
If IBOUND=1 or 2, arrays BL and BU need not be set on input.
If IBOUND=3, you must set BL 1 to ℓ1 and BU 1 to u1. The remaining elements of BL and BU will then be populated by these initial values.
On exit: unless IFAIL=1 or 2 on exit, BL and BU are the actual arrays of bounds used by E05JBF.
Constraints:
  • if IBOUND=0, BL i≤BU i, for i=1,2,…,N;
  • if IBOUND=3, BL 1<BU 1.
7:   SDLIST – INTEGERInput
On entry: the second dimension of the array LIST as declared in the (sub)program from which E05JBF is called. SDLIST is, at least, the maximum over i of the number of points in coordinate i at which to split according to the initialization list LIST; that is, SDLIST≥maxi NUMPTS i.
Internally, E05JBF uses LIST to determine sets of points along each coordinate direction to which it fits quadratic interpolants. Since fitting a quadratic requires at least three distinct points, this puts a lower bound on SDLIST. Furthermore, in the case of initialization by linesearches (IINIT=2) internal storage considerations require that SDLIST be at least 192, but not all of this space may be used.
Constraints:
  • if IINIT≠2, SDLIST≥3;
  • if IINIT=2, SDLIST≥192;
  • if IINIT=3, SDLIST≥ maxi NUMPTS i.
8:   LIST NSDLIST – REAL (KIND=nag_wp) arrayInput/Output
On entry: this argument need not be set on entry if you wish to use one of the preset initialization methods (IINIT≠3).
LIST is the ‘initialization list’: whenever a sub-box in the algorithm is split for the first time (either during the initialization procedure or later), for each non-fixed coordinate i the split is done at the values LIST i 1:NUMPTS i, as well as at some adaptively chosen intermediate points. The array sections LIST i 1:NUMPTS i , for i=1,2,…,N, must be in ascending order with each entry being distinct. In this context, ‘distinct’ should be taken to mean relative to the safe-range argument (see X02AMF).
On exit: unless IFAIL=1, 2 or -999 on exit, the actual initialization data used by E05JBF. If you wish to monitor the contents of LIST you are advised to do so solely through MONIT, not through the output value here.
Constraint: if X i is not fixed, LIST i 1:NUMPTS i is in ascending order with each entry being distinct, for i=1,2,…,NBL i≤LIST ij≤BU i, for i=1,2,…,N and j=1,2,…,NUMPTS i.
9:   NUMPTS N – INTEGER arrayInput/Output
On entry: this argument need not be set on entry if you wish to use one of the preset initialization methods (IINIT≠3).
NUMPTS encodes the number of splitting points in each non-fixed dimension.
On exit: unless IFAIL=1, 2 or -999 on exit, the actual initialization data used by E05JBF.
Constraints:
  • if X i is not fixed, NUMPTS i ≤ SDLIST ;
  • NUMPTS i ≥ 3 , for i=1,2,…,N.
10:   INITPT N – INTEGER arrayInput/Output
On entry: this argument need not be set on entry if you wish to use one of the preset initialization methods (IINIT≠3).
You must designate a point stored in LIST that you wish E05JBF to consider as an ‘initial point’ for the purposes of the splitting procedure. Call this initial point x*. The coordinates of x* correspond to a set of indices Ji, for i=1,2,…,n, such that xi* is stored in LIST i Ji , for i=1,2,…,n. You must set INITPT i = Ji , for i=1,2,…,n.
On exit: unless IFAIL=1, 2 or -999 on exit, the actual initialization data used by E05JBF.
Constraint: if X i is not fixed, 1 ≤ INITPT i ≤ SDLIST , for i=1,2,…,N.
11:   MONIT – SUBROUTINE, supplied by the NAG Library or the user.External Procedure
MONIT may be used to monitor the optimization process. It is invoked upon every successful completion of the procedure in which a sub-box is considered for splitting. It will also be called just before E05JBF exits if that splitting procedure was not successful.
If no monitoring is required, MONIT may be the dummy monitoring routine E05JBK supplied by the NAG Library.
The specification of MONIT is:
SUBROUTINE MONIT ( N, NCALL, XBEST, ICOUNT, NINIT, LIST, NUMPTS, INITPT, NBASKT, XBASKT, BOXL, BOXU, NSTATE, IUSER, RUSER, INFORM)
INTEGER | N, NCALL, ICOUNT(6), NINIT, NUMPTS(N), INITPT(N), NBASKT, NSTATE, IUSER(*), INFORM
REAL (KIND=nag_wp) | XBEST(N), LIST(N,NINIT), XBASKT(N,NBASKT), BOXL(N), BOXU(N), RUSER(*)
1:   N – INTEGERInput
On entry: n, the number of variables.
2:   NCALL – INTEGERInput
On entry: the cumulative number of calls to OBJFUN.
3:   XBEST N – REAL (KIND=nag_wp) arrayInput
On entry: the current best point.
4:   ICOUNT 6 – INTEGER arrayInput
On entry: an array of counters.
ICOUNT 1
nboxes, the current number of sub-boxes.
ICOUNT 2
ncloc, the cumulative number of calls to OBJFUN made in local searches.
ICOUNT 3
nloc, the cumulative number of points used as start points for local searches.
ICOUNT 4
nsweep, the cumulative number of sweeps through levels.
ICOUNT 5
m, the cumulative number of splits by initialization list.
ICOUNT 6
s, the current lowest level containing non-split boxes.
5:   NINIT – INTEGERInput
On entry: the maximum over i of the number of points in coordinate i at which to split according to the initialization list LIST. See also the description of the argument NUMPTS.
6:   LIST NNINIT – REAL (KIND=nag_wp) arrayInput
On entry: the initialization list.
7:   NUMPTS N – INTEGER arrayInput
On entry: the number of points in each coordinate at which to split according to the initialization list LIST.
8:   INITPT N – INTEGER arrayInput
On entry: a pointer to the ‘initial point’ in LIST. Element INITPT i is the column index in LIST of the ith coordinate of the initial point.
9:   NBASKT – INTEGERInput
On entry: the number of points in the ‘shopping basket’ XBASKT.
10:   XBASKT NNBASKT – REAL (KIND=nag_wp) arrayInput
Note: the jth candidate minimum has its ith coordinate stored in XBASKT ji, for i=1,2,…,N and j=1,2,…,NBASKT.
On entry: the ‘shopping basket’ of candidate minima.
11:   BOXL N – REAL (KIND=nag_wp) arrayInput
On entry: the array of lower bounds of the current search box.
12:   BOXU N – REAL (KIND=nag_wp) arrayInput
On entry: the array of upper bounds of the current search box.
13:   NSTATE – INTEGERInput
On entry: is set by E05JBF to indicate at what stage of the minimization MONIT was called.
NSTATE=1
This is the first time that MONIT has been called.
NSTATE=-1
This is the last time MONIT will be called.
NSTATE=0
This is the first and last time MONIT will be called.
14:   IUSER* – INTEGER arrayUser Workspace
15:   RUSER* – REAL (KIND=nag_wp) arrayUser Workspace
MONIT is called with the arguments IUSER and RUSER as supplied to E05JBF. You are free to use the arrays IUSER and RUSER to supply information to MONIT as an alternative to using COMMON global variables.
16:   INFORM – INTEGEROutput
On exit: must be set to a value describing the action to be taken by the solver on return from MONIT. Specifically, if the value is negative the solution of the current problem will terminate immediately; otherwise, computations will continue.
MONIT must either be a module subprogram USEd by, or declared as EXTERNAL in, the (sub)program from which E05JBF is called. Arguments denoted as Input must not be changed by this procedure.
12:   X N – REAL (KIND=nag_wp) arrayOutput
On exit: if IFAIL=0, contains an estimate of the global optimum (see also Section 7).
13:   OBJ – REAL (KIND=nag_wp)Output
On exit: if IFAIL=0, contains the function value at X.
If you request early termination of E05JBF using INFORM in OBJFUN or the analogous INFORM in MONIT, there is no guarantee that the function value at X equals OBJ.
14:   COMM LCOMM – REAL (KIND=nag_wp) arrayCommunication Array
On exit: COMM must not be altered between calls to any of the routines E05JBF, E05JCF, E05JDF, E05JEF, E05JFF, E05JGF, E05JHF, E05JJF, E05JKF and E05JLF.
15:   LCOMM – INTEGERInput
On entry: the dimension of the array COMM as declared in the (sub)program from which E05JBF is called.
Constraint: LCOMM≥100.
16:   IUSER* – INTEGER arrayUser Workspace
17:   RUSER* – REAL (KIND=nag_wp) arrayUser Workspace
IUSER and RUSER are not used by E05JBF, but are passed directly to OBJFUN and MONIT and may be used to pass information to these routines as an alternative to using COMMON global variables.
18:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).
E05JBF returns with IFAIL=0 if your termination criterion has been met: either a target value has been found to the required relative error (as determined by the values of the optional parameters Target Objective Value, Target Objective Error and Target Objective Safeguard), or the best function value was static for the number of sweeps through levels given by the optional parameter Static Limit. The latter criterion is the default.

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
Initialization routine E05JAF has not been called.
On entry, LCOMM=value.
Constraint: LCOMM≥100.
IFAIL=2
A value of Splits Limit (smax) smaller than nr+3 was set: smax=value, nr=value.
On entry, IBOUND=value.
Constraint: IBOUND=0, 1, 2 or 3.
On entry, IBOUND=0 or 3 and BL i=value, BU i=value and i=value.
Constraint: if IBOUND=0 then BL i ≤ BU i , for i=1,2,…,N; if IBOUND=3 then BL 1<BU 1.
On entry, IBOUND=3 and BL 1=BU 1=value.
Constraint: if IBOUND=3 then BL 1<BU 1.
On entry, IINIT=value.
Constraint: IINIT=0, 1, 2, 3 or 4.
On entry, IINIT=2 and SDLIST=value.
Constraint: if IINIT=2 then SDLIST≥192.
On entry, IINIT=value and SDLIST=value.
Constraint: if IINIT≠2 then SDLIST≥3.
On entry, N=value.
Constraint: N>0.
On entry, user-supplied INITPT i=value, i=value.
Constraint: if X i is not fixed then INITPT i≥1, for i=1,2,…,N.
On entry, user-supplied INITPT i=value, i=value and SDLIST=value.
Constraint: if X i is not fixed then INITPT i ≤ SDLIST , for i=1,2,…,N.
On entry, user-supplied LIST ij=value, i=value, j=value, and BL i=value.
Constraint: if X i is not fixed then LIST ij ≥ BL i , for i=1,2,…,N and j=1,2,…,NUMPTS i.
On entry, user-supplied LIST ij=value, i=value, j=value, and BU i=value.
Constraint: if X i is not fixed then LIST ij ≤ BU i , for i=1,2,…,N and j=1,2,…,NUMPTS i.
On entry, user-supplied NUMPTS i=value, i=value.
Constraint: if X i is not fixed then NUMPTS i≥3, for i=1,2,…,N.
On entry, user-supplied NUMPTS i=value, i=value and SDLIST=value.
Constraint: if X i is not fixed then NUMPTS i≤SDLIST, for i=1,2,…,N.
On entry, user-supplied section LIST i 1:NUMPTS i contained ndist distinct elements, and ndist<NUMPTS i: ndist=value, NUMPTS i=value, i=value.
On entry, user-supplied section LIST i 1:NUMPTS i was not in ascending order: NUMPTS i=value, i=value.
The number of non-fixed variables nr=0.
Constraint: nr>0.
IFAIL=3
A finite initialization list could not be computed internally. Consider reformulating the bounds on the problem, try providing your own initialization list, use the randomization option (IINIT=4) or vary the value of Infinite Bound Size.
The user-supplied initialization list contained infinite values, as determined by the optional parameter Infinite Bound Size.
IFAIL=4
The division procedure completed but your target value could not be reached.
Despite every sub-box being processed Splits Limit times, the target value you provided in Target Objective Value could not be found to the tolerances given in Target Objective Error and Target Objective Safeguard. You could try reducing Splits Limit or the objective tolerances.
IFAIL=5
The function evaluations limit was exceeded.
Approximately Function Evaluations Limit function calls have been made without your chosen termination criterion being satisfied.
IFAIL=6
User-supplied monitoring routine requested termination.
User-supplied objective function requested termination.
IFAIL=7
An error occurred during initialization. It is likely that points from the initialization list are very close together. Try relaxing the bounds on the variables or use a different initialization method.
An error occurred during linesearching. It is likely that your objective function is badly scaled: try rescaling it. Also, try relaxing the bounds or use a different initialization method. If the problem persists, please contact NAG quoting error code value.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

If IFAIL=0 on exit, then the vector returned in the array X is an estimate of the solution x whose function value satisfies your termination criterion: the function value was static for Static Limit sweeps through levels, or
F x - objval ≤ max objerr × objval ,objsfg ,
where objval is the value of the optional parameter Target Objective Value, objerr is the value of the optional parameter Target Objective Error, and objsfg is the value of the optional parameter Target Objective Safeguard.

8 Parallelism and Performance

E05JBF is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
E05JBF makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

For each invocation of E05JBF, local workspace arrays of fixed length are allocated internally. The total size of these arrays amounts to 13 nr+smax-1 integer elements, where smax is the value of the optional parameter Splits Limit and nr is the number of non-fixed variables, and 2+nr SDLIST+2 N+22 nr+3 nr 2+1 real elements. In addition, if you are using randomized initialization lists (see the description of the argument IINIT), a further 21 integer elements are allocated internally.
In order to keep track of the regions of the search space that have been visited while looking for a global optimum, E05JBF internally allocates arrays of increasing sizes depending on the difficulty of the problem. Two of the main factors that govern the amount allocated are the number of sub-boxes (call this quantity nboxes) and the number of points in the ‘shopping basket’ (the argument NBASKT on entry to MONIT). Safe, pessimistic upper bounds on these two quantities are so large as to be impractical. In fact, the worst-case number of sub-boxes for even the most simple initialization list (when NINIT=3 on entry to MONIT) grows like nr nr. Thus E05JBF does not attempt to estimate in advance the final values of nboxes or NBASKT for a given problem. There are a total of 5 integer arrays and 4+nr+NINIT real arrays whose lengths depend on nboxes, and there are a total of 2 integer arrays and 3+N+nr real arrays whose lengths depend on NBASKT. E05JBF makes a fixed initial guess that the maximum number of sub-boxes required will be 10000 and that the maximum number of points in the ‘shopping basket’ will be 1000. If ever a greater amount of sub-boxes or more room in the ‘shopping basket’ is required, E05JBF performs reallocation, usually doubling the size of the inadequately-sized arrays. Clearly this process requires periods where the original array and its extension exist in memory simultaneously, so that the data within can be copied, which compounds the complexity of E05JBF's memory usage. It is possible (although not likely) that if your problem is particularly difficult to solve, or of a large size (hundreds of variables), you may run out of memory.
One array that could be dynamically resized by E05JBF is the ‘shopping basket’ (XBASKT on entry to MONIT). If the initial attempt to allocate 1000 nr reals for this array fails, MONIT will not be called on exit from E05JBF.
E05JBF performs better if your problem is well-scaled. It is worth trying (by guesswork perhaps) to rescale the problem if necessary, as sensible scaling will reduce the difficulty of the optimization problem, so that E05JBF will take less computer time.

10 Example

This example finds the global minimum of the ‘peaks’ function in two dimensions
F x,y = 3 1-x 2 exp - x 2 - y+1 2 -10 x 5 - x 3 - y 5 exp - x 2 - y 2 - 1 3 exp - x+1 2 - y 2
on the box -3,3 × -3,3 .
The function F has several local minima and one global minimum in the given box. The global minimum is approximately located at 0.23,-1.63 , where the function value is approximately -6.55.
We use default values for all the optional parameters, and we instruct E05JBF to use the simple initialization list corresponding to IINIT=0. In particular, this will set for us the initial point 0,0 (see Section 10.3).

10.1 Program Text

Program Text (e05jbfe.f90)

10.2 Program Data

Program Data (e05jbfe.d)

10.3 Program Results

Program Results (e05jbfe.r)

GnuplotProduced by GNUPLOT 4.6 patchlevel 3 −3 −2 −1 0 1 2 3 −3 −2 −1 0 1 2 3 Example Program The Peaks Function F and Search Boxes The global minimum is denoted by GM, while our start point is labelled with X GM X gnuplot_plot_1 gnuplot_plot_2 gnuplot_plot_3 gnuplot_plot_4 gnuplot_plot_5 gnuplot_plot_6 gnuplot_plot_7 gnuplot_plot_8 gnuplot_plot_9 gnuplot_plot_10 gnuplot_plot_11 gnuplot_plot_12 gnuplot_plot_13 gnuplot_plot_14
Note: the remainder of this document is intended for more advanced users. Section 11 contains a detailed description of the algorithm. This information may be needed in order to understand Section 12, which describes the optional parameters that can be set by calls to E05JCF, E05JDF, E05JEF, E05JFF and/or E05JGF.

11 Algorithmic Details

Here we summarise the main features of the MCS algorithm used in E05JBF, and we introduce some terminology used in the description of the subroutine and its arguments. We assume throughout that we will only do any work in coordinates i in which xi is free to vary. The MCS algorithm is fully described in Huyer and Neumaier (1999).

11.1 Initialization and Sweeps

Each sub-box is determined by a basepoint x and an opposite point y. We denote such a sub-box by B x,y. The basepoint is allowed to belong to more than one sub-box, is usually a boundary point, and is often a vertex.
An initialization procedure produces an initial set of sub-boxes. Whenever a sub-box is split along a coordinate i for the first time (in the initialization procedure or later), the splitting is done at three or more user-defined values xij j at which the objective function is sampled, and at some adaptively chosen intermediate points. At least four children are generated. More precisely, we assume that we are given
ℓi ≤ xi 1 < xi 2 < ⋯ < xi Li ≤ ui ,  Li ≥ 3 ,  for ​ i=1,2,…,n
and a vector p that, for each i, locates within xij j the ith coordinate of an initial point x 0; that is, if xi 0=xij for some j=1,2,…,Li, then pi=j. A good guess for the global optimum can be used as x 0.
The initialization points and the vectors ℓ and p are collectively called the initialization list (and sometimes we will refer to just the initialization points as ‘the initialization list’, whenever this causes no confusion). The initialization data may be input by you, or they can be set to sensible default values by E05JBF: if you provide them yourself, LIST ij should contain xij, NUMPTS i should contain Li, and INITPT i should contain pi, for i=1,2,…,n and j=1,2,…,Li; if you wish E05JBF to use one of its preset initialization methods, you could choose one of two simple, three-point methods (see Figure 1). If the list generated by one of these methods contains infinite values, attempts are made to generate a safeguarded list using the function subint x,y (which is also used during the splitting procedure, and is described in Section 11.2). If infinite values persist, E05JBF exits with IFAIL=3. There is also the option to generate an initialization list with the aid of linesearches (by setting IINIT=2). Starting with the absolutely smallest point in the root box, linesearches are made along each coordinate. For each coordinate, the local minimizers found by the linesearches are put into the initialization list. If there were fewer than three minimizers, they are augmented by close-by values. The final preset initialization option (IINIT=4) generates a randomized list, so that independent multiple runs may be made if you suspect a global optimum has not been found. Each call to the initialization routine E05JAF resets the initial-state vector for the Wichmann–Hill base-generator that is used. Depending on whether you set the optional parameter Repeatability to ON or OFF, the random state is initialized to give a repeatable or non-repeatable sequence. Then, a random integer between 3 and SDLIST is selected, which is then used to determine the number of points to be generated in each coordinate; that is, NUMPTS becomes a constant vector, set to this value. The components of LIST are then generated, from a uniform distribution on the root box if the box is finite, or else in a safeguarded fashion if any bound is infinite. The array INITPT is set to point to the best point in LIST.
Given an initialization list (preset or otherwise), E05JBF evaluates F at x 0, and sets the initial estimate of the global minimum, x*, to x 0. Then, for i=1,2,…,n, the objective function F is evaluated at Li-1 points that agree with x* in all but the ith coordinate. We obtain pairs x^ j , f i j , for j=1,2,…,Li, with: x*=x^j 1, say; with, for j≠j 1,
x^kj = xk* if ​k≠i; xkj otherwise;
and with
fij = F x^ j .
The point having the smallest function value is renamed x* and the procedure is repeated with the next coordinate.
Once E05JBF has a full set of initialization points and function values, it can generate an initial set of sub-boxes. Recall that the root box is B x,y=ℓ,u, having basepoint x=x 0. The opposite point y is a corner of ℓ,u farthest away from x, in some sense. The point x need not be a vertex of ℓ,u, and y is entitled to have infinite coordinates. We loop over each coordinate i, splitting the current box along coordinate i into 2 Li-2, 2 Li-1 or 2 Li sub-intervals with exactly one of the x^ij as endpoints, depending on whether two, one or none of the x^ij are on the boundary. Thus, as well as splitting at x^ i j , for j=1,2,…,Li, we split at additional points z i j , for j=2,3,…,Li. These additional zij are such that
zij = x^ i j-1 + qm x^ i j - x^ i j-1 ,   j=2,…,Li ,
where q is the golden-section ratio 5-1/2, and the exponent m takes the value 1 or 2, chosen so that the sub-box with the smaller function value gets the larger fraction of the interval. Each child sub-box gets as basepoint the point obtained from x* by changing xi* to the xij that is a boundary point of the corresponding ith coordinate interval; this new basepoint therefore has function value fij. The opposite point is derived from y by changing yi to the other end of that interval.
E05JBF can now rank the coordinates based on an estimated variability of F. For each i we compute the union of the ranges of the quadratic interpolant through any three consecutive x^ij, taking the difference between the upper and lower bounds obtained as a measure of the variability of F in coordinate i. A vector π is populated in such a way that coordinate i has the πith highest estimated variability. For tiebreaks, when the x* obtained after splitting coordinate i belongs to two sub-boxes, the one that contains the minimizer of the quadratic models is designated the current sub-box for coordinate i+1.
Boxes are assigned levels in the following manner. The root box is given level 1. When a sub-box of level s is split, the child with the smaller fraction of the golden-section split receives level s+2; all other children receive level s+1. The box with the better function value is given the larger fraction of the splitting interval and the smaller level because then it is more likely to be split again more quickly. We see that after the initialization procedure the first level is empty and the non-split boxes have levels 2,…,nr+2, so it is meaningful to choose smax much larger than nr. Note that the internal structure of E05JBF demands that smax be at least nr+3.
Examples of initializations in two dimensions are given in Figure 1. In both cases the initial point is x 0=ℓ+u/2; on the left the initialization points are
x 1 = ℓ ,  x 2 = ℓ+u / 2 ,  x 3 = u ,
while on the right the points are
x 1 = 5 ℓ + u / 6 ,  x 2 = ℓ + u / 2 ,  x 3 = ℓ + 5 u / 6 .
In Figure 1, basepoints and levels after initialization are displayed. Note that these initialization lists correspond to IINIT=0 and IINIT=1, respectively.
Examples of the initialization procedure
Figure 1: Examples of the initialization procedure
After initialization, a series of sweeps through levels is begun. A sweep is defined by three steps:
(i) | scan the list of non-split sub-boxes. Fill a record list b according to bs=0 if there is no box at level s, and with bs pointing to a sub-box with the lowest function value among all sub-boxes with level s otherwise, for 0<s<smax;
(ii) | the sub-box with label bs is a candidate for splitting. If the sub-box is not to be split, according to the rules described in Section 11.2, increase its level by 1 and update b s+1 if necessary. If the sub-box is split, mark it so, insert its children into the list of sub-boxes, and update b if any child with level s′ yields a strict improvement of F over those sub-boxes at level s′;
(iii) | increment s by 1. If s=smax then displaying monitoring information and start a new sweep; else if bs=0 then repeat this step; else display monitoring information and go to the previous step.
Clearly, each sweep ends after at most smax-1 visits of the third step.

11.2 Splitting

Each sub-box is stored by E05JBF as a set of information about the history of the sub-box: the label of its parent, a label identifying which child of the parent it is, etc. Whenever a sub-box B x,y of level s<smax is a candidate for splitting, as described in Section 11.1, we recover x, y, and the number, nj, of times coordinate j has been split in the history of B. Sub-box B could be split in one of two ways.
(i) | Splitting by rank If s > 2 nr min⁡nj+1 , the box is always split. The splitting index is set to a coordinate i such that ni=min⁡nj.
(ii) | Splitting by expected gain If s ≤ 2 nr min⁡nj+1 , the sub-box could be split along a coordinate where a maximal gain in function value is expected. This gain is estimated according to a local separable quadratic model obtained by fitting to 2 nr+1 function values. If the expected gain is too small the sub-box is not split at all, and its level is increased by 1.
Eventually, a sub-box that is not eligible for splitting by expected gain will reach level 2 nr min⁡nj+1 +1 and then be split by rank, as long as smax is large enough. As smax→∞, the rule for splitting by rank ensures that each coordinate is split arbitrarily often.
Before describing the details of each splitting method, we introduce the procedure for correctly handling splitting at adaptive points and for dealing with unbounded intervals. Suppose we want to split the ith coordinate interval ▯xi,yi, where we define ▯xi,yi=min xi,yi,max xi,yi, for xi∈R and yi∈R-, and where x is the basepoint of the sub-box being considered. The descendants of the sub-box should shrink sufficiently fast, so we should not split too close to xi. Moreover, if yi is large we want the new splitting value to not be too large, so we force it to belong to some smaller interval ▯ξ′,ξ′′, determined by
ξ′′ = subint xi,yi ,  ξ′ = xi + ξ′′ - xi / 10 ,
where the function subint is defined by
subint x,y = sign y if ​ 1000 x<1 ​ and ​ y>1000 ; 10 sign yx if ​ 1000 x≥1 ​ and ​ y>1000 x ; y otherwise.

11.2.1 Splitting by rank

Consider a sub-box B with level s > 2 nr min⁡nj+1 . Although the sub-box has reached a high level, there is at least one coordinate along which it has not been split very often. Among the i such that ni = min⁡nj for B, select the splitting index to be the coordinate with the lowest πi (and hence highest variability rank). ‘Splitting by rank’ refers to the ranking of the coordinates by ni and πi.
If ni=0, so that B has never been split along coordinate i, the splitting is done according to the initialization list and the adaptively chosen golden-section split points, as described in Section 11.1. Also as covered there, new basepoints and opposite points are generated. The children having the smaller fraction of the golden-section split (that is, those with larger function values) are given level min s+2,smax. All other children are given level s+1.
Otherwise, B ranges between xi and yi in the ith coordinate direction. The splitting value is selected to be zi=xi+2 subint xi,yi-xi/3; we are not attempting to split based on a large reduction in function value, merely in order to reduce the size of a large interval, so zi may not be optimal. Sub-box B is split at zi and the golden-section split point, producing three parts and requiring only one additional function evaluation, at the point x′ obtained from x by changing the ith coordinate to zi. The child with the smaller fraction of the golden-section split is given level min s+2,smax, while the other two parts are given level s+1. Basepoints are assigned as follows: the basepoint of the first child is taken to be x, and the basepoint of the second and third children is the point x′. Opposite points are obtained by changing yi to the other end of the ith coordinate-interval of the corresponding child.

11.2.2 Splitting by expected gain

When a sub-box B has level s ≤ 2 nr min⁡nj+1 , we compute the optimal splitting index and splitting value from a local separable quadratic used as a simple local approximation of the objective function. To fit this curve, for each coordinate we need two additional points and their function values. Such data may be recoverable from the history of B: whenever the ith coordinate was split in the history of B, we obtained values that can be used for the current quadratic interpolation in coordinate i.
We loop over i; for each coordinate we pursue the history of B back to the root box, and we take the first two points and function values we find, since these are expected to be closest to the current basepoint x. If the current coordinate has not yet been split we use the initialization list. Then we generate a local separable model e ξ for F ξ by interpolation at x and the 2 nr additional points just collected:
e ξ = F x + ∑ i=1 n ei ξi .
We define the expected gain e^i in function value when we evaluate at a new point obtained by changing coordinate i in the basepoint, for each i, based on two cases:
(i) ni=0. We compute the expected gain as
e^i = min 1≤j≤ Li fij - f i pi .
Again, we split according to the initialization list, with the new basepoints and opposite points being as before.
(ii) ni>0. Now, the ith component of our sub-box ranges from xi to yi. Using the quadratic partial correction function
ei ξi = αi ξi - xi + βi ξi - xi 2
we can approximate the maximal gain expected when changing xi only. We will choose the splitting value from ▯ξ′,ξ′′. We compute
e^i = min ξi ∈ ▯ ξ′,ξ′′ ei ξi
and call zi the minimizer in ▯ξ′,ξ′′.
If the expected best function value fexp satisfies
fexp = F x + min 1≤i≤n e^i < fbest , (1)
where fbest is the current best function value (including those function values obtained by local optimization), we expect the sub-box to contain a better point and so we split it, using as splitting index the component with minimal e^i. Equation (1) prevents wasting function calls by avoiding splitting sub-boxes whose basepoints have bad function values. These sub-boxes will eventually be split by rank anyway.
We now have a splitting index and a splitting value zi. The sub-box is split at zi as long as zi≠yi, and at the golden-section split point; two or three children are produced. The larger fraction of the golden-section split receives level s+1, while the smaller fraction receives level min s+2,smax. If it is the case that zi≠yi and the third child is larger than the smaller of the two children from the golden-section split, the third child receives level s+1. Otherwise it is given the level min s+2,smax. The basepoint of the first child is set to x, and the basepoint of the second (and third if it exists) is obtained by changing the ith coordinate of x to zi. The opposite points are again derived by changing yi to the other end of the ith coordinate interval of B.
If equation (1) does not hold, we expect no improvement. We do not split, and we increase the level of B by 1.

11.3 Local Search

The local optimization algorithm used by E05JBF uses linesearches along directions that are determined by minimizing quadratic models, all subject to bound constraints. Triples of vectors are computed using coordinate searches based on linesearches. These triples are used in triple search procedures to build local quadratic models for F. A trust-region-type approach to minimize these models is then carried out, and more information about the coordinate search and the triple search can be found in Huyer and Neumaier (1999).
The local search starts by looking for better points without being too local, by making a triple search using points found by a coordinate search. This yields a new point and function value, an approximation of the gradient of the objective, and an approximation of the Hessian of the objective. Then the quadratic model for F is minimized over a small box, with the solution to that minimization problem then being used as a linesearch direction to minimize the objective. A measure r is computed to quantify the predictive quality of the quadratic model.
The third stage is the checking of termination criteria. The local search will stop if more than loclim visits to this part of the local search have occurred, where loclim is the value of the optional parameter Local Searches Limit. If that is not the case, it will stop if the limit on function calls has been exceeded (see the description of the optional parameter Function Evaluations Limit). The final criterion checks if no improvement can be made to the function value, or whether the approximated gradient g is small, in the sense that
g T max x, x old < loctol f 0-f .
The vector xold is the best point at the start of the current loop in this iterative local-search procedure, the constant loctol is the value of the optional parameter Local Searches Tolerance, f is the objective value at x, and f 0 is the smallest function value found by the initialization procedure.
Next, E05JBF attempts to move away from the boundary, if any components of the current point lie there, using linesearches along the offending coordinates. Local searches are terminated if no improvement could be made.
The fifth stage carries out another triple search, but this time it does not use points from a coordinate search, rather points lying within the trust-region box are taken.
The final stage modifies the trust-region box to be bigger or smaller, depending on the quality of the quadratic model, minimizes the new quadratic model on that box, and does a linesearch in the direction of the minimizer. The value of r is updated using the new data, and then we go back to the third stage (checking of termination criteria).
The Hessians of the quadratic models generated by the local search may not be positive definite, so E05JBF uses the general nonlinear optimizer E04VHF to minimize the models.

12 Optional Parameters

Several optional parameters in E05JBF define choices in the problem specification or the algorithm logic. In order to reduce the number of formal arguments of E05JBF these optional parameters have associated default values that are appropriate for most problems. Therefore, you need only specify those optional parameters whose values are to be different from their default values.
The remainder of this section can be skipped if you wish to use the default values for all optional parameters.
The following is a list of the optional parameters available. A full description of each optional parameter is provided in Section 12.1.
  • Defaults
  • Function Evaluations Limit
  • Infinite Bound Size
  • List
  • Local Searches
  • Local Searches Limit
  • Local Searches Tolerance
  • Maximize
  • Minimize
  • Nolist
  • Repeatability
  • Splits Limit
  • Static Limit
  • Target Objective Error
  • Target Objective Safeguard
  • Target Objective Value
Optional parameters may be specified by calling one, or more, of the routines E05JCF, E05JDF, E05JEF, E05JFF and E05JGF before a call to E05JBF.
E05JCF reads options from an external options file, with Begin and End as the first and last lines respectively, and with each intermediate line defining a single optional parameter. For example,
 Begin
   Static Limit = 50
 End
The call
 CALL E05JCF (IOPTS, COMM, LCOMM, IFAIL)
can then be used to read the file on unit IOPTS. IFAIL will be zero on successful exit. E05JCF should be consulted for a full description of this method of supplying optional parameters.
E05JDF, E05JEF, E05JFF or E05JGF can be called to supply options directly, one call being necessary for each optional parameter. E05JDF, E05JEF, E05JFF or E05JGF should be consulted for a full description of this method of supplying optional parameters.
All optional parameters not specified by you are set to their default values. Valid values of optional parameters specified by you are unaltered by E05JBF and so remain in effect for subsequent calls to E05JBF, unless you explicitly change them.

12.1 Description of the Optional Parameters

For each option, we give a summary line, a description of the optional parameter and details of constraints.
The summary line contains:
  • a parameter value, where the letters a, i and r denote options that take character, integer and real values respectively, and where the letter a denotes an option that takes an ON or OFF value;
  • the default value, where the symbol ε is a generic notation for machine precision (see X02AJF), the symbol rmax stands for the largest positive model number (see X02ALF), nr represents the number of non-fixed variables, and the symbol d stands for the maximum number of decimal digits that can be represented (see X02BEF).
Option names are case-insensitive and must be provided in full; abbreviations are not recognized.
Defaults
This special keyword is used to reset all optional parameters to their default values, and any random state stored in the array COMM will be destroyed.
Any option value given with this keyword will be ignored. This optional parameter cannot be queried or got.
Function Evaluations Limit i Default =100 nr 2
This puts an approximate limit on the number of function calls allowed. The total number of calls made is checked at the top of an internal iteration loop, so it is possible that a few calls more than nf may be made.
Constraint: nf>0.
Infinite Bound Size r Default =rmax 14
This defines the ‘infinite’ bound infbnd in the definition of the problem constraints. Any upper bound greater than or equal to infbnd will be regarded as ∞ (and similarly any lower bound less than or equal to -infbnd will be regarded as -∞).
Constraint: rmax 14≤infbnd≤rmax 12.
Local Searches a Default =ON
If you want to try to accelerate convergence of E05JBF by starting local searches from candidate minima, you will require lcsrch to be ON.
Constraint: lcsrch=ON​ or ​OFF.
Local Searches Limit i Default =50
This defines the maximal number of iterations to be used in the trust-region loop of the local-search procedure.
Constraint: loclim>0.
Local Searches Tolerance r Default =2 ε
The value of loctol is the multiplier used during local searches as a stopping criterion for when the approximated gradient is small, in the sense described in Section 11.3.
Constraint: loctol≥2 ε.
Minimize Default
Maximize
These keywords specify the required direction of optimization. Any option value given with these keywords will be ignored.
Nolist Default
List
These options control the echoing of each optional parameter specification as it is supplied. List turns printing on, Nolist turns printing off. The output is sent to the current advisory message unit (as defined by X04ABF).
Any option value given with these keywords will be ignored. This optional parameter cannot be queried or got.
Repeatability a Default =OFF
For use with random initialization lists (IINIT=4). When set to ON, an internally-initialized random state is stored in the array COMM for use in subsequent calls to E05JBF.
Constraint: repeat=ON​ or ​OFF.
Splits Limit i Default =d nr+2/3
Along with the initialization list LIST, this defines a limit on the number of times the root box will be split along any single coordinate direction. If Local Searches is OFF you may find the default value to be too small.
Constraint: smax>nr+2.
Static Limit i Default =3 nr
As the default termination criterion, computation stops when the best function value is static for stclim sweeps through levels. This parameter is ignored if you have specified a target value to reach in Target Objective Value.
Constraint: stclim>0.
Target Objective Error r Default =ε 14
If you have given a target objective value to reach in objval (the value of the optional parameter Target Objective Value), objerr sets your desired relative error (from above if Minimize is set, from below if Maximize is set) between OBJ and objval, as described in Section 7. See also the description of the optional parameter Target Objective Safeguard.
Constraint: objerr≥2 ε.
Target Objective Safeguard r Default =ε 12
If you have given a target objective value to reach in objval (the value of the optional parameter Target Objective Value), objsfg sets your desired safeguarded termination tolerance, for when objval is close to zero.
Constraint: objsfg≥2 ε.
Target Objective Value r
This parameter may be set if you wish E05JBF to use a specific value as the target function value to reach during the optimization. Setting objval overrides the default termination criterion determined by the optional parameter Static Limit.
E05 Chapter Contents
E05 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


E05JDF : NAG Library, Mark 26

E05 Chapter Contents
E05 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

E05JDF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
10 Example

1 Purpose

E05JDF may be used to supply individual optional parameters to E05JBF. The initialization routine E05JAF must have been called before calling E05JDF.

2 Specification

SUBROUTINE E05JDF ( OPTSTR, COMM, LCOMM, IFAIL)
INTEGER | LCOMM, IFAIL
REAL (KIND=nag_wp) | COMM(LCOMM)
CHARACTER(*) | OPTSTR

3 Description

E05JDF may be used to supply values for optional parameters to E05JBF. It is only necessary to call E05JDF for those arguments whose values are to be different from their default values. One call to E05JDF sets one argument value.
Each optional parameter is defined by a single character string, of up to 72 characters, consisting of one or more items. The items associated with a given optional parameter must be separated by spaces, or equals signs =. Alphabetic characters may be upper or lower case. The string
Static Limit = 100
is an example of a string used to set an optional parameter. For each optional parameter the string contains one or more of the following items:
– | a mandatory keyword;
– | a phrase that qualifies the keyword;
– | a number that specifies an integer or real value. Such numbers may be up to 40 contiguous characters.
For E05JDF, each user-specified optional parameter is not normally printed as it is defined, but this printing may be turned on using the keyword List. Thus the statement
CALL E05JDF ('List', COMM, LCOMM, IFAIL)
turns on printing of this and subsequent options. Printing may be turned off again using the keyword Nolist.
Optional parameter settings are preserved following a call to E05JBF and so the keyword Defaults is provided to allow you to reset all the optional parameters to their default values before a subsequent call to E05JBF.
A complete list of optional parameters, their symbolic names and default values is given in Section 12 in E05JBF.

4 References

None.

5 Arguments

1:   OPTSTR – CHARACTER(*)Input
On entry: a string defining a single optional parameter (as described in Section 3 and in Section 12 in E05JBF). The implied data type (character, integer or real) of each value to set must match that expected by the optional parameter.
2:   COMM LCOMM – REAL (KIND=nag_wp) arrayCommunication Array
On exit: COMM must not be altered between calls to any of the routines E05JBF, E05JCF, E05JDF, E05JEF, E05JFF, E05JGF, E05JHF, E05JJF, E05JKF and E05JLF.
3:   LCOMM – INTEGERInput
On entry: the dimension of the array COMM as declared in the (sub)program from which E05JDF is called.
Constraint: LCOMM≥100.
4:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
Initialization routine E05JAF has not been called.
On entry, LCOMM=value.
Constraint: LCOMM≥100.
IFAIL=2
The supplied optional parameter is invalid. A keyword or keyword combination was not recognized.
IFAIL=3
Attempt to assign an illegal value of Local Searches (lcsrch): lcsrch=value.
Attempt to assign an illegal value of Repeatability (repeat): repeat=value.
Attempt to assign a non-positive value of Function Evaluations Limit (nf): nf=value.
Attempt to assign a non-positive value of Local Searches Limit (loclim): loclim=value.
Attempt to assign a non-positive value of Static Limit (stclim): stclim=value.
Attempt to assign an out-of-bounds value of Infinite Bound Size (infbnd): infbnd=value.
Attempt to assign too small a value of Local Searches Tolerance (loctol): loctol=value.
Attempt to assign too small a value of Target Objective Error (objerr): objerr=value.
Attempt to assign too small a value of Target Objective Safeguard (objsfg): objsfg=value.
IFAIL=5
The value to be set could not be parsed. Check that it specifies a valid integer or real value.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

Not applicable.

8 Parallelism and Performance

E05JDF is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

E05JCF, E05JEF, E05JFF or E05JGF may also be used to supply optional parameters to E05JBF.

10 Example

See Section 10 in E05JCF.
E05 Chapter Contents
E05 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


E05JEF : NAG Library, Mark 26

E05 Chapter Contents
E05 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

E05JEF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
10 Example

1 Purpose

E05JEF may be used to supply individual ‘ON’/‘OFF’-valued character optional parameters to E05JBF. The initialization routine E05JAF must have been called before calling E05JEF.

2 Specification

SUBROUTINE E05JEF ( OPTSTR, CVALUE, COMM, LCOMM, IFAIL)
INTEGER | LCOMM, IFAIL
REAL (KIND=nag_wp) | COMM(LCOMM)
CHARACTER(*) | OPTSTR, CVALUE

3 Description

E05JEF may be used to supply values for ‘ON’/‘OFF’-valued character optional parameters to E05JBF. It is only necessary to call E05JEF for those arguments whose values are to be different from their default values. One call to E05JEF sets one argument value.
Each ‘ON’/‘OFF’-valued character optional parameter is defined by a single character string in OPTSTR and the corresponding value in CVALUE. For example, the following allows local searches to be turned off:
LCSRCH = 'off'
CALL E05JEF ('Local Searches', LCSRCH, COMM, LCOMM, IFAIL)
A complete list of optional parameters, their symbolic names and default values is given in Section 12 in E05JBF.

4 References

None.

5 Arguments

1:   OPTSTR – CHARACTER(*)Input
On entry: a string defining a single ‘ON’/‘OFF’-valued character optional parameter (as described in Section 12 in E05JBF).
2:   CVALUE – CHARACTER(*)Input
On entry: the ‘ON’/‘OFF’ value associated with the keyword in OPTSTR.
3:   COMM LCOMM – REAL (KIND=nag_wp) arrayCommunication Array
On exit: COMM must not be altered between calls to any of the routines E05JBF, E05JCF, E05JDF, E05JEF, E05JFF, E05JGF, E05JHF, E05JJF, E05JKF and E05JLF.
4:   LCOMM – INTEGERInput
On entry: the dimension of the array COMM as declared in the (sub)program from which E05JEF is called.
Constraint: LCOMM≥100.
5:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
Initialization routine E05JAF has not been called.
On entry, LCOMM=value.
Constraint: LCOMM≥100.
IFAIL=2
The supplied optional parameter is invalid. A keyword or keyword combination was not recognized.
IFAIL=3
Attempt to assign an illegal value of Local Searches (lcsrch): lcsrch=value.
Attempt to assign an illegal value of Repeatability (repeat): repeat=value.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

Not applicable.

8 Parallelism and Performance

E05JEF is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

E05JCF or E05JDF may also be used to supply ‘ON’/‘OFF’-valued character optional parameters to E05JBF.

10 Example

See Section 10 in E05JCF.
E05 Chapter Contents
E05 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


E05JFF : NAG Library, Mark 26

E05 Chapter Contents
E05 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

E05JFF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
10 Example

1 Purpose

E05JFF may be used to supply individual integer optional parameters to E05JBF. The initialization routine E05JAF must have been called before calling E05JFF.

2 Specification

SUBROUTINE E05JFF ( OPTSTR, IVALUE, COMM, LCOMM, IFAIL)
INTEGER | IVALUE, LCOMM, IFAIL
REAL (KIND=nag_wp) | COMM(LCOMM)
CHARACTER(*) | OPTSTR

3 Description

E05JFF may be used to supply values for integer optional parameters to E05JBF. It is only necessary to call E05JFF for those arguments whose values are to be different from their default values. One call to E05JFF sets one argument value.
Each integer optional parameter is defined by a single character string in OPTSTR and the corresponding value in IVALUE. For example, the following allows the function evaluations limit to be defined:
NF = 1000
CALL E05JFF ('Function Evaluations Limit', NF, COMM, LCOMM, IFAIL)
A complete list of optional parameters, their symbolic names and default values is given in Section 12 in E05JBF.

4 References

None.

5 Arguments

1:   OPTSTR – CHARACTER(*)Input
On entry: a string identifying an integer-valued optional parameter (as described in Section 12 in E05JBF).
2:   IVALUE – INTEGERInput
On entry: an integer value associated with the optional parameter in OPTSTR.
3:   COMM LCOMM – REAL (KIND=nag_wp) arrayCommunication Array
On exit: COMM must not be altered between calls to any of the routines E05JBF, E05JCF, E05JDF, E05JEF, E05JFF, E05JGF, E05JHF, E05JJF, E05JKF and E05JLF.
4:   LCOMM – INTEGERInput
On entry: the dimension of the array COMM as declared in the (sub)program from which E05JFF is called.
Constraint: LCOMM≥100.
5:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
Initialization routine E05JAF has not been called.
On entry, LCOMM=value.
Constraint: LCOMM≥100.
IFAIL=2
The supplied optional parameter is invalid. A keyword or keyword combination was not recognized.
IFAIL=3
Attempt to assign a non-positive value of Function Evaluations Limit (nf): nf=value.
Attempt to assign a non-positive value of Local Searches Limit (loclim): loclim=value.
Attempt to assign a non-positive value of Static Limit (stclim): stclim=value.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

Not applicable.

8 Parallelism and Performance

E05JFF is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

E05JCF or E05JDF may also be used to supply integer optional parameters to E05JBF.

10 Example

See Section 10 in E05JCF.
E05 Chapter Contents
E05 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


E05JGF : NAG Library, Mark 26

E05 Chapter Contents
E05 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

E05JGF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
10 Example

1 Purpose

E05JGF may be used to supply individual real optional parameters to E05JBF. The initialization routine E05JAF must have been called before calling E05JGF.

2 Specification

SUBROUTINE E05JGF ( OPTSTR, RVALUE, COMM, LCOMM, IFAIL)
INTEGER | LCOMM, IFAIL
REAL (KIND=nag_wp) | RVALUE, COMM(LCOMM)
CHARACTER(*) | OPTSTR

3 Description

E05JGF may be used to supply values for real optional parameters to E05JBF. It is only necessary to call E05JGF for those arguments whose values are to be different from their default values. One call to E05JGF sets one argument value.
Each real optional parameter is defined by a single character string in OPTSTR and the corresponding value in RVALUE. For example the following illustrates how the local searches tolerance could be defined:
LOCTOL = 1.0E-10
CALL E05JGF ('Local Searches Tolerance', LOCTOL, COMM, LCOMM, IFAIL)
A complete list of optional parameters, their symbolic names and default values is given in Section 12 in E05JBF.

4 References

None.

5 Arguments

1:   OPTSTR – CHARACTER(*)Input
On entry: a string identifying a real-valued optional parameter (as described in Section 12 in E05JBF).
2:   RVALUE – REAL (KIND=nag_wp)Input
On entry: the value associated with the optional parameter in OPTSTR.
3:   COMM LCOMM – REAL (KIND=nag_wp) arrayCommunication Array
On exit: COMM must not be altered between calls to any of the routines E05JBF, E05JCF, E05JDF, E05JEF, E05JFF, E05JGF, E05JHF, E05JJF, E05JKF and E05JLF.
4:   LCOMM – INTEGERInput
On entry: the dimension of the array COMM as declared in the (sub)program from which E05JGF is called.
Constraint: LCOMM≥100.
5:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
Initialization routine E05JAF has not been called.
On entry, LCOMM=value.
Constraint: LCOMM≥100.
IFAIL=2
The supplied optional parameter is invalid. A keyword or keyword combination was not recognized.
IFAIL=3
Attempt to assign an out-of-bounds value of Infinite Bound Size (infbnd): infbnd=value.
Attempt to assign too small a value of Local Searches Tolerance (loctol): loctol=value.
Attempt to assign too small a value of Target Objective Error (objerr): objerr=value.
Attempt to assign too small a value of Target Objective Safeguard (objsfg): objsfg=value.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

Not applicable.

8 Parallelism and Performance

E05JGF is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

E05JCF or E05JDF may also be used to supply real optional parameters to E05JBF.

10 Example

See Section 10 in E05JCF.
E05 Chapter Contents
E05 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


E05JHF : NAG Library, Mark 26

E05 Chapter Contents
E05 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

E05JHF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
10 Example

1 Purpose

E05JHF is used to check if you have set an optional parameter of E05JBF. The initialization routine E05JAF must have been called before calling E05JHF.

2 Specification

FUNCTION E05JHF ( OPTSTR, COMM, LCOMM, IFAIL)
INTEGER E05JHF
INTEGER | LCOMM, IFAIL
REAL (KIND=nag_wp) | COMM(LCOMM)
CHARACTER(*) | OPTSTR

3 Description

E05JHF returns 1 if you have previously set the optional parameter contained in OPTSTR, otherwise it returns 0.
A complete list of optional parameters, their symbolic names and default values is given in Section 12 in E05JBF.

4 References

None.

5 Arguments

1:   OPTSTR – CHARACTER(*)Input
On entry: a string identifying an optional parameter (as described in Section 12 in E05JBF).
2:   COMM LCOMM – REAL (KIND=nag_wp) arrayCommunication Array
On entry: communication data as initialized by E05JAF.
3:   LCOMM – INTEGERInput
On entry: the dimension of the array COMM as declared in the (sub)program from which E05JHF is called.
Constraint: LCOMM≥100.
4:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
Initialization routine E05JAF has not been called.
On entry, LCOMM=value.
Constraint: LCOMM≥100.
IFAIL=2
The supplied optional parameter is invalid. A keyword or keyword combination was not recognized.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

Not applicable.

8 Parallelism and Performance

E05JHF is not threaded in any implementation.

9 Further Comments

None.

10 Example

See Section 10 in E05JCF.
E05 Chapter Contents
E05 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


E05JJF : NAG Library, Mark 26

E05 Chapter Contents
E05 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

E05JJF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
10 Example

1 Purpose

E05JJF is used to get the value of an ‘ON’/‘OFF’-valued character E05JBF optional parameter. E05JJF can be used before or after calling E05JBF, but the initialization routine E05JAF must have been called before calling E05JJF.

2 Specification

SUBROUTINE E05JJF ( OPTSTR, CVALUE, COMM, LCOMM, IFAIL)
INTEGER | LCOMM, IFAIL
REAL (KIND=nag_wp) | COMM(LCOMM)
CHARACTER(*) | OPTSTR, CVALUE

3 Description

E05JJF obtains the current value of an ‘ON’/‘OFF’-valued character optional parameter. For example
CALL E05JJF ('Local Searches', LCSRCH, COMM, LCOMM, IFAIL)
will result in the ‘ON’/‘OFF’ value of the optional parameter Local Searches being output in LCSRCH.
A complete list of optional parameters, their symbolic names and default values is given in Section 12 in E05JBF.

4 References

None.

5 Arguments

1:   OPTSTR – CHARACTER(*)Input
On entry: a string defining a single ‘ON’/‘OFF’-valued character optional parameter (as described in Section 12 in E05JBF).
2:   CVALUE – CHARACTER(*)Output
On exit: if IFAIL=0 on exit, CVALUE contains the ‘ON’/‘OFF’ value associated with the keyword in OPTSTR.
3:   COMM LCOMM – REAL (KIND=nag_wp) arrayCommunication Array
On entry: communication data as initialized by E05JAF.
4:   LCOMM – INTEGERInput
On entry: the dimension of the array COMM as declared in the (sub)program from which E05JJF is called.
Constraint: LCOMM≥100.
5:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
Initialization routine E05JAF has not been called.
On entry, LCOMM=value.
Constraint: LCOMM≥100.
IFAIL=2
The supplied optional parameter is invalid. A keyword or keyword combination was not recognized.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

Not applicable.

8 Parallelism and Performance

E05JJF is not threaded in any implementation.

9 Further Comments

None.

10 Example

See Section 10 in E05JCF.
E05 Chapter Contents
E05 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


E05JKF : NAG Library, Mark 26

E05 Chapter Contents
E05 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

E05JKF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
10 Example

1 Purpose

E05JKF is used to get the value of an integer E05JBF optional parameter. E05JKF can be used before or after calling E05JBF, but the initialization routine E05JAF must have been called before calling E05JKF.

2 Specification

SUBROUTINE E05JKF ( OPTSTR, IVALUE, COMM, LCOMM, IFAIL)
INTEGER | IVALUE, LCOMM, IFAIL
REAL (KIND=nag_wp) | COMM(LCOMM)
CHARACTER(*) | OPTSTR

3 Description

E05JKF obtains the current value of an integer-valued optional parameter. For example
CALL E05JKF ('Local Searches Limit', LOCLIM, COMM, LCOMM, IFAIL)
will result in the value of the optional parameter Local Searches Limit being output in LOCLIM.
The default values of the optional parameters Function Evaluations Limit, Splits Limit and Static Limit depend on the problem parameter nr (the number of non-fixed variables). A default value for each of these optional parameters will be set in the first call to the solver E05JBF: before that time, getting the value of any of these optional parameters using E05JKF will not return a meaningful result.
A complete list of optional parameters, their symbolic names and default values is given in Section 12 in E05JBF.

4 References

None.

5 Arguments

1:   OPTSTR – CHARACTER(*)Input
On entry: a string identifying an integer-valued optional parameter (as described in Section 12 in E05JBF).
2:   IVALUE – INTEGEROutput
On exit: if IFAIL=0 on exit, IVALUE contains the integer value associated with the optional parameter in OPTSTR.
3:   COMM LCOMM – REAL (KIND=nag_wp) arrayCommunication Array
On entry: communication data as initialized by E05JAF.
4:   LCOMM – INTEGERInput
On entry: the dimension of the array COMM as declared in the (sub)program from which E05JKF is called.
Constraint: LCOMM≥100.
5:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
Initialization routine E05JAF has not been called.
On entry, LCOMM=value.
Constraint: LCOMM≥100.
IFAIL=2
The supplied optional parameter is invalid. A keyword or keyword combination was not recognized.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

Not applicable.

8 Parallelism and Performance

E05JKF is not threaded in any implementation.

9 Further Comments

None.

10 Example

See Section 10 in E05JCF.
E05 Chapter Contents
E05 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


E05JLF : NAG Library, Mark 26

E05 Chapter Contents
E05 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

E05JLF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
10 Example

1 Purpose

E05JLF is used to get the value of a real E05JBF optional parameter. E05JLF can be used before or after calling E05JBF, but the initialization routine E05JAF must have been called before calling E05JLF.

2 Specification

SUBROUTINE E05JLF ( OPTSTR, RVALUE, COMM, LCOMM, IFAIL)
INTEGER | LCOMM, IFAIL
REAL (KIND=nag_wp) | RVALUE, COMM(LCOMM)
CHARACTER(*) | OPTSTR

3 Description

E05JLF obtains the current value of a real-valued optional parameter. For example
CALL E05JLF ('Local Searches Tolerance', LOCTOL, COMM, LCOMM, IFAIL)
will result in the value of the optional parameter Local Searches Tolerance being output in LOCTOL.
A complete list of optional parameters, their symbolic names and default values is given in Section 12 in E05JBF.

4 References

None.

5 Arguments

1:   OPTSTR – CHARACTER(*)Input
On entry: a string identifying a real-valued optional parameter (as described in Section 12 in E05JBF).
2:   RVALUE – REAL (KIND=nag_wp)Output
On exit: if IFAIL=0 on exit, RVALUE contains the real value associated with the optional parameter in OPTSTR.
3:   COMM LCOMM – REAL (KIND=nag_wp) arrayCommunication Array
On entry: communication data as initialized by E05JAF.
4:   LCOMM – INTEGERInput
On entry: the dimension of the array COMM as declared in the (sub)program from which E05JLF is called.
Constraint: LCOMM≥100.
5:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
Initialization routine E05JAF has not been called.
On entry, LCOMM=value.
Constraint: LCOMM≥100.
IFAIL=2
The supplied optional parameter is invalid. A keyword or keyword combination was not recognized.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

Not applicable.

8 Parallelism and Performance

E05JLF is not threaded in any implementation.

9 Further Comments

None.

10 Example

See Section 10 in E05JCF.
E05 Chapter Contents
E05 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


E05SAF : NAG Library, Mark 26

E05 Chapter Contents
E05 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

E05SAF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.
Note: this routine uses optional parameters to define choices in the problem specification and in the details of the algorithm. If you wish to use default settings for all of the optional parameters, you need only read Sections 1 to 10 of this document. If, however, you wish to reset some or all of the settings please refer to Section 11 for a detailed description of the algorithm and to Section 12 for a detailed description of the specification of the optional parameters.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results
11 Algorithmic Details
▸▿ 12 Optional Parameters
12.1 Description of the Optional Parameters
12.2 Description of the SMP optional parameters

1 Purpose

E05SAF is designed to search for the global minimum or maximum of an arbitrary function, using Particle Swarm Optimization (PSO). Derivatives are not required, although these may be used by an accompanying local minimization routine if desired. E05SAF is essentially identical to E05SBF, but with a simpler interface and with various optional parameters removed; otherwise most arguments are identical. In particular, E05SAF does not handle general constraints.

2 Specification

SUBROUTINE E05SAF ( NDIM, NPAR, XB, FB, BL, BU, OBJFUN, MONMOD, IOPTS, OPTS, IUSER, RUSER, ITT, INFORM, IFAIL)
INTEGER | NDIM, NPAR, IOPTS(*), IUSER(*), ITT(6), INFORM, IFAIL
REAL (KIND=nag_wp) | XB(NDIM), FB, BL(NDIM), BU(NDIM), OPTS(*), RUSER(*)
EXTERNAL | OBJFUN, MONMOD
Before calling E05SAF, E05ZKF must be called with OPTSTR set to ‘Initialize = e05saf’. Optional parameters may also be specified by calling E05ZKF before the call to E05SAF.

3 Description

E05SAF uses a stochastic method based on Particle Swarm Optimization (PSO) to search for the global optimum of a nonlinear function F, subject to a set of bound constraints on the variables. In the PSO algorithm (see Section 11), a set of particles is generated in the search space, and advances each iteration to (hopefully) better positions using a heuristic velocity based upon inertia, cognitive memory and global memory. The inertia is provided by a decreasingly weighted contribution from a particles current velocity, the cognitive memory refers to the best candidate found by an individual particle and the global memory refers to the best candidate found by all the particles. This allows for a global search of the domain in question.
Further, this may be coupled with a selection of local minimization routines, which may be called during the iterations of the heuristic algorithm, the interior phase, to hasten the discovery of locally optimal points, and after the heuristic phase has completed to attempt to refine the final solution, the exterior phase. Different options may be set for the local optimizer in each phase.
Without loss of generality, the problem is assumed to be stated in the following form:
minimize x∈Rndim   F x   subject to   ℓ ≤ x ≤ u ,
where the objective F x is a scalar function, x is a vector in Rndim and the vectors ℓ≤u are lower and upper bounds respectively for the ndim variables. The objective function may be nonlinear. Continuity of F is not essential. For functions which are smooth and primarily unimodal, faster solutions will almost certainly be achieved by using Chapter E04 routines directly.
For functions which are smooth and multi-modal, gradient dependent local minimization routines may be coupled with E05SAF.
For multi-modal functions for which derivatives cannot be provided, particularly functions with a significant level of noise in their evaluation, E05SAF should be used either alone, or coupled with E04CBF.
The ndim lower and upper box bounds on the variable x are included to initialize the particle swarm into a finite hypervolume, although their subsequent influence on the algorithm is user determinable (see the option Boundary in Section 12). It is strongly recommended that sensible bounds are provided for all variables.
E05SAF may also be used to maximize the objective function (see the option Optimize).
Due to the nature of global optimization, unless a predefined target is provided, there is no definitive way of knowing when to end a computation. As such several stopping heuristics have been implemented into the algorithm. If any of these is achieved, E05SAF will exit with IFAIL=1, and the parameter INFORM will indicate which criteria was reached. See INFORM for more information.
In addition, you may provide your own stopping criteria through MONMOD and OBJFUN.
E05SBF provides a comprehensive interface, allowing for the inclusion of general nonlinear constraints.

4 References

Gill P E, Murray W and Wright M H (1981) Practical Optimization Academic Press
Kennedy J and Eberhart R C (1995) Particle Swarm Optimization Proceedings of the 1995 IEEE International Conference on Neural Networks 1942–1948
Koh B, George A D, Haftka R T and Fregly B J (2006) Parallel Asynchronous Particle Swarm Optimization International Journal for Numerical Methods in Engineering 67(4) 578–595
Vaz A I and Vicente L N (2007) A Particle Swarm Pattern Search Method for Bound Constrained Global Optimization Journal of Global Optimization 39(2) 197–219 Kluwer Academic Publishers

5 Arguments

Note: for descriptions of the symbolic variables, see Section 11.
1:   NDIM – INTEGERInput
On entry: ndim, the number of dimensions.
Constraint: NDIM≥1.
2:   NPAR – INTEGERInput
On entry: npar, the number of particles to be used in the swarm. Assuming all particles remain within bounds, each complete iteration will perform at least NPAR function evaluations. Otherwise, significantly fewer objective function evaluations may be performed.
Suggested value: NPAR=10×NDIM.
Constraint: NPAR≥5×num_threads, where num_threads is the value returned by the OpenMP environment variable OMP_NUM_THREADS, or num_threads is 1 for a serial version of this routine.
3:   XB NDIM – REAL (KIND=nag_wp) arrayOutput
On exit: the location of the best solution found, x~, in Rndim.
4:   FB – REAL (KIND=nag_wp)Output
On exit: the objective value of the best solution, f~=F x~.
5:   BL NDIM – REAL (KIND=nag_wp) arrayInput
6:   BU NDIM – REAL (KIND=nag_wp) arrayInput
On entry: BL is ℓ, the array of lower bounds, BU is u, the array of upper bounds. The NDIM entries in BL and BU must contain the lower and upper simple (box) bounds of the variables respectively. These must be provided to initialize the sample population into a finite hypervolume, although their subsequent influence on the algorithm is user determinable (see the option Boundary in Section 12).
If BL i=BU i for any i∈1,…,NDIM, variable i will remain locked to BL i regardless of the Boundary option selected.
It is strongly advised that you place sensible lower and upper bounds on all variables, even if your model allows for variables to be unbounded (using the option Boundary=ignore) since these define the initial search space.
Constraints:
  • BL i≤BU i, for i=1,2,…,NDIM;
  • BL i≠BU i for at least one i∈1,…,NDIM.
7:   OBJFUN – SUBROUTINE, supplied by the user.External Procedure
OBJFUN must, depending on the value of MODE, calculate the objective function and/or calculate the gradient of the objective function for a ndim-variable vector x. Gradients are only required if a local minimizer has been chosen which requires gradients. See the option Local Minimizer for more information.
The specification of OBJFUN is:
SUBROUTINE OBJFUN ( MODE, NDIM, X, OBJF, VECOUT, NSTATE, IUSER, RUSER)
INTEGER | MODE, NDIM, NSTATE, IUSER(*)
REAL (KIND=nag_wp) | X(NDIM), OBJF, VECOUT(NDIM), RUSER(*)
1:   MODE – INTEGERInput/Output
On entry: indicates which functionality is required.
MODE=0
F x should be returned in OBJF. The value of OBJF on entry may be used as an upper bound for the calculation. Any expected value of F x that is greater than OBJF may be approximated by this upper bound; that is OBJF can remain unaltered.
MODE=1
Local Minimizer=E04UCF only
First derivatives can be evaluated and returned in VECOUT. Any unaltered elements of VECOUT will be approximated using finite differences.
MODE=2
Local Minimizer=E04UCF only
F x must be calculated and returned in OBJF, and available first derivatives can be evaluated and returned in VECOUT. Any unaltered elements of VECOUT will be approximated using finite differences.
MODE=5
F x must be calculated and returned in OBJF. The value of OBJF on entry may not be used as an upper bound.
MODE=6
Local Minimizer=E04DGF or E04KZF only
All first derivatives must be evaluated and returned in VECOUT.
MODE=7
Local Minimizer=E04DGF or E04KZF only
F x must be calculated and returned in OBJF, and all first derivatives must be evaluated and returned in VECOUT.
On exit: if the value of MODE is set to be negative, then E05SAF will exit as soon as possible with IFAIL=3 and INFORM=MODE.
2:   NDIM – INTEGERInput
On entry: the number of dimensions.
3:   X NDIM – REAL (KIND=nag_wp) arrayInput
On entry: x, the point at which the objective function and/or its gradient are to be evaluated.
4:   OBJF – REAL (KIND=nag_wp)Input/Output
On entry: the value of OBJF passed to OBJFUN varies with the argument MODE.
MODE=0
OBJF is an upper bound for the value of F x, often equal to the best value of F x found so far by a given particle. Only objective function values less than the value of OBJF on entry will be used further. As such this upper bound may be used to stop further evaluation when this will only increase the objective function value above the upper bound.
MODE=1, 2, 5, 6 or 7
OBJF is meaningless on entry.
On exit: the value of OBJF returned varies with the argument MODE.
MODE=0
OBJF must be the value of F x. Only values of F x strictly less than OBJF on entry need be accurate.
MODE=1 or 6
Need not be set.
MODE=2, 5 or 7
F x must be calculated and returned in OBJF. The entry value of OBJF may not be used as an upper bound.
5:   VECOUT NDIM – REAL (KIND=nag_wp) arrayInput/Output
On entry: if Local Minimizer=E04UCF or E04UCA, the values of VECOUT are used internally to indicate whether a finite difference approximation is required. See E04UCF/E04UCA.
On exit: the required values of VECOUT returned to the calling routine depend on the value of MODE.
MODE=0 or 5
The value of VECOUT need not be set.
MODE=1 or 2
VECOUT can contain components of the gradient of the objective function ∂F ∂xi for some i=1,2,…NDIM, or acceptable approximations. Any unaltered elements of VECOUT will be approximated using finite differences.
MODE=6 or 7
VECOUT must contain the gradient of the objective function ∂F ∂xi for all i=1,2,…NDIM. Approximation of the gradient is strongly discouraged, and no finite difference approximations will be performed internally (see E04DGF/E04DGA and E04KZF).
6:   NSTATE – INTEGERInput
On entry: NSTATE indicates various stages of initialization throughout the routine. This allows for permanent global arguments to be initialized the least number of times. For example, you may initialize a random number generator seed.
NSTATE=3
SMP users only. OBJFUN is called for the first time in a parallel region on a new thread other than the master thread. You may use this opportunity to set up any thread-dependent information in IUSER and RUSER.
NSTATE=2
OBJFUN is called for the very first time. You may save computational time if certain data must be read or calculated only once.
NSTATE=1
OBJFUN is called for the first time by a NAG local minimization routine. You may save computational time if certain data required for the local minimizer need only be calculated at the initial point of the local minimization.
NSTATE=0
Used in all other cases.
7:   IUSER* – INTEGER arrayUser Workspace
8:   RUSER* – REAL (KIND=nag_wp) arrayUser Workspace
OBJFUN is called with the arguments IUSER and RUSER as supplied to E05SAF. You are free to use the arrays IUSER and RUSER to supply information to OBJFUN as an alternative to using COMMON global variables.
OBJFUN must either be a module subprogram USEd by, or declared as EXTERNAL in, the (sub)program from which E05SAF is called. Arguments denoted as Input must not be changed by this procedure.
8:   MONMOD – SUBROUTINE, supplied by the NAG Library or the user.External Procedure
A user-specified monitoring and modification function. MONMOD is called once every complete iteration after a finalization check. It may be used to modify the particle locations that will be evaluated at the next iteration. This permits the incorporation of algorithmic modifications such as including additional advection heuristics and genetic mutations. MONMOD is only called during the main loop of the algorithm, and as such will be unaware of any further improvement from the final local minimization. If no monitoring and/or modification is required, MONMOD may be the dummy monitoring routine E05SXM. (E05SXM is included in the NAG Library) .
The specification of MONMOD is:
SUBROUTINE MONMOD ( NDIM, NPAR, X, XB, FB, XBEST, FBEST, ITT, IUSER, RUSER, INFORM)
INTEGER | NDIM, NPAR, ITT(6), IUSER(*), INFORM
REAL (KIND=nag_wp) | X(NDIM,NPAR), XB(NDIM), FB, XBEST(NDIM,NPAR), FBEST(NPAR), RUSER(*)
1:   NDIM – INTEGERInput
On entry: the number of dimensions.
2:   NPAR – INTEGERInput
On entry: the number of particles.
3:   X NDIMNPAR – REAL (KIND=nag_wp) arrayInput/Output
Note: the ith component of the jth particle, xj i, is stored in X ij.
On entry: the NPAR particle locations, xj, which will currently be used during the next iteration unless altered in MONMOD.
On exit: the particle locations to be used during the next iteration.
4:   XB NDIM – REAL (KIND=nag_wp) arrayInput
On entry: the location, x~, of the best solution yet found.
5:   FB – REAL (KIND=nag_wp)Input
On entry: the objective value, f~=F x~, of the best solution yet found.
6:   XBEST NDIMNPAR – REAL (KIND=nag_wp) arrayInput
Note: the ith component of the position of the jth particle's cognitive memory, x^j i, is stored in XBEST ij.
On entry: the locations currently in the cognitive memory, x^j, for j=1,2,…,NPAR (see Section 11).
7:   FBEST NPAR – REAL (KIND=nag_wp) arrayInput
On entry: the objective values currently in the cognitive memory, F x^j, for j=1,2,…,NPAR.
8:   ITT 6 – INTEGER arrayInput
On entry: iteration and function evaluation counters (see description of ITT below).
9:   IUSER* – INTEGER arrayUser Workspace
10:   RUSER* – REAL (KIND=nag_wp) arrayUser Workspace
MONMOD is called with the arguments IUSER and RUSER as supplied to E05SAF. You are free to use the arrays IUSER and RUSER to supply information to MONMOD as an alternative to using COMMON global variables.
11:   INFORM – INTEGERInput/Output
On entry: INFORM=thread_num, where thread_num is the value returned by a call of the OpenMP function OMP_GET_THREAD_NUM(). If running in serial this will always be zero.
On exit: setting INFORM<0 will cause near immediate exit from E05SAF. This value will be returned as INFORM with IFAIL=3. You need not set INFORM unless you wish to force an exit.
MONMOD must either be a module subprogram USEd by, or declared as EXTERNAL in, the (sub)program from which E05SAF is called. Arguments denoted as Input must not be changed by this procedure.
9:   IOPTS* – INTEGER arrayCommunication Array
Note: the dimension of this array is dictated by the requirements of associated functions that must have been previously called. This array must be the same array passed as argument IOPTS in the previous call to E05ZKF.
On entry: optional parameter array as generated and possibly modified by calls to E05ZKF. The contents of IOPTS must not be modified directly between calls to E05SAF, E05ZKF or E05ZLF.
10:   OPTS* – REAL (KIND=nag_wp) arrayCommunication Array
Note: the dimension of this array is dictated by the requirements of associated functions that must have been previously called. This array must be the same array passed as argument OPTS in the previous call to E05ZKF.
On entry: optional parameter array as generated and possibly modified by calls to E05ZKF. The contents of OPTS must not be modified directly between calls to E05SAF, E05ZKF or E05ZLF.
11:   IUSER* – INTEGER arrayUser Workspace
IUSER is not used by E05SAF, but is passed directly to OBJFUN and MONMOD and may be used to pass information to these routines as an alternative to using COMMON global variables.
With care, you may also write information back into IUSER. This might be useful, for example, should there be a need to preserve the state of a random number generator.
With SMP-enabled versions of E05SAF the array IUSER provided are classified as OpenMP shared memory. Use of IUSER has to take account of this in order to preserve thread safety whenever information is written back to either of these arrays.
12:   RUSER* – REAL (KIND=nag_wp) arrayUser Workspace
RUSER is not used by E05SAF, but is passed directly to OBJFUN and MONMOD and may be used to pass information to these routines as an alternative to using COMMON global variables.
With care, you may also write information back into RUSER. This might be useful, for example, should there be a need to preserve the state of a random number generator.
With SMP-enabled versions of E05SAF the array RUSER provided are classified as OpenMP shared memory. Use of RUSER has to take account of this in order to preserve thread safety whenever information is written back to either of these arrays.
13:   ITT 6 – INTEGER arrayOutput
On exit: integer iteration counters for E05SAF.
ITT 1
Number of complete iterations.
ITT 2
Number of complete iterations without improvement to the current optimum.
ITT 3
Number of particles converged to the current optimum.
ITT 4
Number of improvements to the optimum.
ITT 5
Number of function evaluations performed.
ITT 6
Number of particles reset.
14:   INFORM – INTEGEROutput
On exit: indicates which finalization criterion was reached. The possible values of INFORM are:
INFORM | Meaning
<0 | Exit from a user-supplied subroutine.
0 | E05SAF has detected an error and terminated.
1 | The provided objective target has been achieved. (Target Objective Value).
2 | The standard deviation of the location of all the particles is below the set threshold (Swarm Standard Deviation). If the solution returned is not satisfactory, you may try setting a smaller value of Swarm Standard Deviation, or try adjusting the options governing the repulsive phase (Repulsion Initialize, Repulsion Finalize).
3 | The total number of particles converged (Maximum Particles Converged) to the current global optimum has reached the set limit. This is the number of particles which have moved to a distance less than Distance Tolerance from the optimum with regard to the L 2 norm. If the solution is not satisfactory, you may consider lowering the Distance Tolerance. However, this may hinder the global search capability of the algorithm.
4 | The maximum number of iterations without improvement (Maximum Iterations Static) has been reached, and the required number of particles (Maximum Iterations Static Particles) have converged to the current optimum. Increasing either of these options will allow the algorithm to continue searching for longer. Alternatively if the solution is not satisfactory, re-starting the application several times with Repeatability=OFF may lead to an improved solution.
5 | The maximum number of iterations (Maximum Iterations Completed) has been reached. If the number of iterations since improvement is small, then a better solution may be found by increasing this limit, or by using the option Local Minimizer with corresponding exterior options. Otherwise if the solution is not satisfactory, you may try re-running the application several times with Repeatability=OFF and a lower iteration limit, or adjusting the options governing the repulsive phase (Repulsion Initialize, Repulsion Finalize).
6 | The maximum allowed number of function evaluations (Maximum Function Evaluations) has been reached. As with INFORM=5, increasing this limit if the number of iterations without improvement is small, or decreasing this limit and running the algorithm multiple times with Repeatability=OFF, may provide a superior result.
15:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
On exit: the most common exit will be IFAIL=1.
For this reason, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended; otherwise, the recommended value is -1. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
E05SAF will return IFAIL=0 if and only if a finalization criterion has been reached which can guarantee success. This may only happen if the option Target Objective Value has been set and reached at a point within the search domain. The finalization criterion Target Objective Value is not activated using default option settings, and must be explicitly set using E05ZKF if required.
E05SAF will return IFAIL=1 if no error has been detected, and a finalization criterion has been achieved which cannot guarantee success. This does not indicate that the routine has failed, merely that the returned solution cannot be guaranteed to be the true global optimum.
The value of INFORM should be examined to determine which finalization criterion was reached.
Other positive values of IFAIL indicate that either an error or a warning has been triggered. See Sections 6, 7 and 11 for more information.

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
A finalization criterion was reached that cannot guarantee success.
On exit, INFORM=value.
IFAIL=2
If the option Target Warning has been activated, this indicates that the Target Objective Value has been achieved to specified tolerances at a sufficiently constrained point, either during the initialization phase, or during the first two iterations of the algorithm. While this is not necessarily an error, it may occur if:
(i) | The target was achieved at the first point sampled by the routine. This will be the mean of the lower and upper bounds.
(ii) | The target may have been achieved at a randomly generated sample point. This will always be a possibility provided that the domain under investigation contains a point with a target objective value.
(iii) | If the Local Minimizer has been set, then a sample point may have been inside the basin of attraction of a satisfactory point. If this occurs repeatedly when the routine is called, it may imply that the objective is largely unimodal, and that it may be more efficient to use the routine selected as the Local Minimizer directly.
Assuming that OBJFUN is correct, you may wish to set a better Target Objective Value, or a stricter Target Objective Tolerance.
IFAIL=3
User requested exit value during call to MONMOD.
User requested exit value during call to OBJFUN.
IFAIL=11
On entry, NDIM=value.
Constraint: NDIM≥1.
IFAIL=12
On entry, NPAR=value.
Constraint: NPAR≥5×num_threads, where num_threads is the value returned by the OpenMP environment variable OMP_NUM_THREADS, or num_threads is 1 for a serial version of this routine.
IFAIL=14
On entry, BL value=value and BU value=value.
Constraint: BU i≥BL i for all i.
On entry, BL i=BU i for all i.
Constraint: BU i>BL i for at least one i.
IFAIL=19
Error value occurred whilst adjusting to exterior local minimizer options.
Error value occurred whilst adjusting to interior local minimizer options.
IFAIL=21
Either the option arrays have not been initialized for E05SAF, or they have become corrupted.
IFAIL=32
Derivative checks indicate possible errors in the supplied derivatives. Gradient checks may be disabled by setting Verify Gradients=OFF.
IFAIL=51
Multiple SMP threads have been detected; however, the option SMP Callback Thread Safe has not been set.
Set SMP Callback Thread Safe=YES if the provided callbacks are thread safe.
Set SMP Callback Thread Safe=NO if the provided callbacks are not thread safe, to force serial execution.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

If IFAIL=0 (or IFAIL=2) or IFAIL=1 on exit, either a Target Objective Value or finalization criterion has been reached, depending on user selected options. As with all global optimization software, the solution achieved may not be the true global optimum. Various options allow for either greater search diversity or faster convergence to a (local) optimum (See Sections 11 and 12).
Provided the objective function and constraints are sufficiently well behaved, if a local minimizer is used in conjunction with E05SAF, then it is more likely that the final result will at least be in the near vicinity of a local optimum, and due to the global search characteristics of the particle swarm, this solution should be superior to many other local optima.
Caution should be used in accelerating the rate of convergence, as with faster convergence, less of the domain will remain searchable by the swarm, making it increasingly difficult for the algorithm to detect the basin of attraction of superior local optima. Using the options Repulsion Initialize and Repulsion Finalize described in Section 12 will help to overcome this, by causing the swarm to diverge away from the current optimum once no more local improvement is likely.
On successful exit with guaranteed success, IFAIL=0. This may only happen if a Target Objective Value is assigned and is reached by the algorithm.
On successful exit without guaranteed success, IFAIL=1 is returned. This will happen if another finalization criterion is achieved without the detection of an error.
In both cases, the value of INFORM provides further information as to the cause of the exit.

8 Parallelism and Performance

E05SAF is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
E05SAF makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.
The algorithm has been parallelized to allow for a high degree of asynchronicity between threads. Each thread is assigned a static number of the NPAR particles requested, and performs a sub-iteration using these particles and a private copy of x~. The thread only updates this private copy if a superior solution is found. In these implementations, this routine may make calls to the user-supplied functions from within an OpenMP parallel region. Thus OpenMP directives within the user functions can only be used if you are compiling the user-supplied function and linking the executable in accordance with the instructions in the Users' Note for your implementation.
Once a thread has completed a sub-iteration, it enters a brief critical section where it compares this private x~ to a globally accessible version. If either is superior, the inferior version is updated and the thread continues into a new sub-iteration.
Parallelizing the algorithm in this way allows for individual threads to continue searching even if other threads are completing sub-iterations in inferior times. The optional argument SMP Thread Overrun allows you to force a synchronization across the team of threads once one thread completes sufficiently more sub-iterations than the slowest thread. In particular, this may be used to force synchronization after every sub-iteration if so desired.
When using an SMP parallel version of this routine, you must indicate that the callback routines are thread safe by setting the optional argument SMP Callback Thread Safe before calling E05SAF in a multi-threaded environment. See Section 12.2 for more information on this and other SMP options.
Note: the stochastic method used in E05SAF will not produce repeatable answers when run on multiple threads.

9 Further Comments

The memory used by E05SAF is relatively static throughout. As such, E05SAF may be used in problems with high dimension number (NDIM>100) without the concern of computational resource exhaustion, although the probability of successfully locating the global optimum will decrease dramatically with the increase in dimensionality.
Due to the stochastic nature of the algorithm, the result will vary over multiple runs. This is particularly true if arguments and options are chosen to accelerate convergence at the expense of the global search. However, the option Repeatability=ON may be set to initialize the internal random number generator using a preset seed, which will result in identical solutions being obtained.
(For SMP users only) The option Repeatability=ON will use preset seeds to initialize the random number generator on each thread, however due to the unpredictable nature of parallel communication, this cannot ensure repeatable results when running on multiple threads, even with SMP Thread Overrun set to force synchronization every iteration.

10 Example

This example uses a particle swarm to find the global minimum of the Schwefel function:
minimize x∈Rndim f = ∑ i=1 ndim xi sin xi
xi ∈ -500,500 ,  for ​ i=1,2,…,NDIM .
In two dimensions the optimum is fmin=-837.966, located at x=-420.97,-420.97.
The example demonstrates how to initialize and set the options arrays using E05ZKF, how to query options using E05ZLF, and finally how to search for the global optimum using E05SAF. The function is minimized several times to demonstrate using E05SAF alone, and coupled with local minimizers. This program uses the non-default option Repeatability=ON to produce repeatable solutions.
Note: for users of multi-threaded implementations of the NAG Library example program does not include the setting of the optional parameter SMP Callback Thread Safe, and as such if run on multiple threads it will issue an error message. An additional example program, e05safe_smp.f90, is included with the distribution material of all implementations of multi-threaded implementations of the NAG Library to illustrate how to safely access independent subsections of the provided IUSER and RUSER arrays from multiple threads and how to use E05ZKF to set additional SMP threading related options.

10.1 Program Text

Program Text (e05safe.f90)

Program Text (e05safe_smp.f90)

10.2 Program Data

None.

10.3 Program Results

Program Results (e05safe.r)

Program Results (e05safe_smp.r)

11 Algorithmic Details

The following pseudo-code describes the algorithm used with the repulsion mechanism.
INITIALIZE for ​ j=1, ​ np xj = R ∈ U ℓbox,ubox x^ j = R∈ U ℓbox,ubox vj = R ∈ U -V max ,Vmax f^j = F x^ j initialize ​wj wj = Wmax Weight Initialize=MAXIMUM Wini Weight Initialize=INITIAL R ∈ U W min , W max Weight Initialize=RANDOMIZED end for x~ = 12 ℓbox + ubox f~ = F x~ Ic = Is = 0 SWARM while (not finalized), Ic = Ic + 1 for ​ j = 1 , np xj = BOUNDARY xj,ℓbox,ubox fj = F xj if ​ fj < f^j f^j = fj , ​ x^j = xj if ​ fj < f~ f~ = fj , ​ x~ = xj end for if ​ new f~ LOCMIN x~,f~,Oi , ​ Is=0 [see note on repulsion below for code insertion] else Is = Is + 1 for ​ j = 1 , np vj = wj vj + Cs D 1 x^j - xj + Cg D 2 x~ - xj xj = xj + vj if ​ xj - x~ < dtol reset ​ xj, ​ vj, ​ wj; ​ x^j = xj else update ​wj end for if (target achieved or termination criterion satisfied) finalized=true MONMOD xj end LOCMIN x~,f~,Oe
The definition of terms used in the above pseudo-code are as follows.
np | the number of particles, NPAR
ℓbox | array of NDIM lower box bounds
ubox | array of NDIM upper box bounds
xj | position of particle j
x^j | best position found by particle j
x~ | best position found by any particle
fj | F xj
f^j | F x^j, best value found by particle j
f~ | F x~, best value found by any particle
vj | velocity of particle j
wj | weight on vj for velocity update, decreasing according to Weight Decrease
Vmax | maximum absolute velocity, dependent upon Maximum Variable Velocity
Ic | swarm iteration counter
Is | iterations since x~ was updated
D 1,D 2 | diagonal matrices with random elements in range 0,1
Cs | the cognitive advance coefficient which weights velocity towards x^j, adjusted using Advance Cognitive
Cg | the global advance coefficient which weights velocity towards x~, adjusted using Advance Global
dtol | the Distance Tolerance for resetting a converged particle
R∈U ℓbox,ubox | an array of random numbers whose ith element is drawn from a uniform distribution in the range ℓbox i,ubox i, for i=1,2,…,NDIM
Oi | local optimizer interior options
Oe | local optimizer exterior options
LOCMIN x,f,O | apply local optimizer using the set of options O using the solution x,f as the starting point, if used (not default)
MONMOD | monitor progress and possibly modify xj
BOUNDARY | apply required behaviour for xj outside bounding box, (see Boundary)
new (f~) | true if x~, c~, f~ were updated at this iteration
Additionally a repulsion phase can be introduced by changing from the default values of options Repulsion Finalize (rf), Repulsion Initialize (ri) and Repulsion Particles (rp). If the number of static particles is denoted ns then the following can be inserted after the new(f~) check in the pseudo-code above.
else ​ if ​ ( ns ≥ rp ​ and ​ ri ≤ Is ≤ ri + rf ) LOCMIN x~,f~,Oi use ​ -C g ​ instead of ​ Cg ​ in velocity updates if ​ Is = ri + rf Is = 0

12 Optional Parameters

This section can be skipped if you wish to use the default values for all optional parameters, otherwise, the following is a list of the optional parameters available and a full description of each optional parameter is provided in Section 12.1.
  • Advance Cognitive
  • Advance Global
  • Boundary
  • Distance Scaling
  • Distance Tolerance
  • Function Precision
  • Local Boundary Restriction
  • Local Exterior Iterations
  • Local Exterior Major Iterations
  • Local Exterior Minor Iterations
  • Local Exterior Tolerance
  • Local Interior Iterations
  • Local Interior Major Iterations
  • Local Interior Minor Iterations
  • Local Interior Tolerance
  • Local Minimizer
  • Maximum Function Evaluations
  • Maximum Iterations Completed
  • Maximum Iterations Static
  • Maximum Iterations Static Particles
  • Maximum Particles Converged
  • Maximum Particles Reset
  • Maximum Variable Velocity
  • Optimize
  • Repeatability
  • Repulsion Finalize
  • Repulsion Initialize
  • Repulsion Particles
  • SMP Callback Thread Safe
  • SMP Local Minimizer External
  • SMP Monitor
  • SMP Monmod
  • SMP Subswarm
  • SMP Thread Overrun
  • Swarm Standard Deviation
  • Target Objective
  • Target Objective Safeguard
  • Target Objective Tolerance
  • Target Objective Value
  • Target Warning
  • Verify Gradients
  • Weight Decrease
  • Weight Initial
  • Weight Initialize
  • Weight Maximum
  • Weight Minimum
  • Weight Reset
  • Weight Value

12.1 Description of the Optional Parameters

For each option, we give a summary line, a description of the optional parameter and details of constraints.
The summary line contains:
  • the keywords;
  • a parameter value, where the letters a, i and r denote options that take character, integer and real values respectively;
  • the default value, where the symbol ε is a generic notation for machine precision (see X02AJF), and Imax represents the largest representable integer value (see X02BBF).
All options accept the value ‘DEFAULT’ in order to return single options to their default states.
Keywords and character values are case insensitive, however they must be separated by at least one space.
For E05SAF the maximum length of the argument CVALUE used by E05ZLF is 15.
Advance Cognitive r Default=2.0
The cognitive advance coefficient, Cs. When larger than the global advance coefficient, this will cause particles to be attracted toward their previous best positions. Setting r=0.0 will cause E05SAF to act predominantly as a local optimizer. Setting r>2.0 may cause the swarm to diverge, and is generally inadvisable. At least one of the global and cognitive coefficients must be nonzero.
Advance Global r Default=2.0
The global advance coefficient, Cg. When larger than the cognitive coefficient this will encourage convergence toward the best solution yet found. Values r∈0,1 will inhibit particles overshooting the optimum. Values r∈1,2 cause particles to fly over the optimum some of the time. Larger values can prohibit convergence. Setting r=0.0 will remove any attraction to the current optimum, effectively generating a Monte–Carlo multi-start optimization algorithm. At least one of the global and cognitive coefficients must be nonzero.
Boundary a Default=FLOATING
Determines the behaviour if particles leave the domain described by the box bounds. This only affects the general PSO algorithm, and will not pass down to any NAG local minimizers chosen.
This option is only effective in those dimensions for which BL i≠BU i, i=1,2,…,NDIM.
IGNORE
The box bounds are ignored. The objective function is still evaluated at the new particle position.
RESET
The particle is re-initialized inside the domain. x^j and f^j are not affected.
FLOATING
The particle position remains the same, however the objective function will not be evaluated at the next iteration. The particle will probably be advected back into the domain at the next advance due to attraction by the cognitive and global memory.
HYPERSPHERICAL
The box bounds are wrapped around an ndim-dimensional hypersphere. As such a particle leaving through a lower bound will immediately re-enter through the corresponding upper bound and vice versa. The standard distance between particles is also modified accordingly.
FIXED
The particle rests on the boundary, with the corresponding dimensional velocity set to 0.0.
Distance Scaling a Default=ON
Determines whether distances should be scaled by box widths.
ON
When a distance is calculated between x and y, a scaled L 2 norm is used.
L 2 x,y = ∑ i | ui ≠ ℓi , i≤ndim xi - yi ui - ℓi 2 1 2 .
OFF
Distances are calculated as the standard L 2 norm without any rescaling.
L 2 x,y = ∑ i=1 ndim xi - yi 2 1 2 .
Distance Tolerance r Default=10-4
This is the distance, dtol between particles and the global optimum which must be reached for the particle to be considered converged, i.e., that any subsequent movement of such a particle cannot significantly alter the global optimum. Once achieved the particle is reset into the box bounds to continue searching.
Constraint: r>0.0.
Function Precision r Default=ε 0.9
The parameter defines εr, which is intended to be a measure of the accuracy with which the problem function F x can be computed. If r<ε or r≥1, the default value is used.
The value of εr should reflect the relative precision of 1+F x; i.e., εr acts as a relative precision when F is large, and as an absolute precision when F is small. For example, if F x is typically of order 1000 and the first six significant digits are known to be correct, an appropriate value for εr would be 10-6. In contrast, if F x is typically of order 10-4 and the first six significant digits are known to be correct, an appropriate value for εr would be 10-10. The choice of εr can be quite complicated for badly scaled problems; see Chapter 8 of Gill et al. (1981) for a discussion of scaling techniques. The default value is appropriate for most simple functions that are computed with full accuracy. However when the accuracy of the computed function values is known to be significantly worse than full precision, the value of εr should be large enough so that no attempt will be made to distinguish between function values that differ by less than the error inherent in the calculation.
Local Boundary Restriction r Default=0.5
Contracts the box boundaries used by a box constrained local minimizer to, βl,βu, containing the start point x, where
∂i = r × ui - ℓi βli = max ℓi, xi - ∂i 2 βui = min ui, xi + ∂i 2 ,  i=1,…,NDIM .
Smaller values of r thereby restrict the size of the domain exposed to the local minimizer, possibly reducing the amount of work done by the local minimizer.
Constraint: 0.0≤r≤1.0.
Local Interior Iterations i 1
Local Interior Major Iterations i 1
Local Exterior Iterations i 2
Local Exterior Major Iterations i 2
The maximum number of iterations or function evaluations the chosen local minimizer will perform inside (outside) the main loop if applicable. For the NAG minimizers these correspond to:
Minimizer | Parameter/option | Default Interior | Default Exterior
E04CBF | MAXCAL | NDIM+10 | 2×NDIM+15
E04DGF/E04DGA | Iteration Limit | max 30,3×NDIM | max 50,5×NDIM
E04UCF/E04UCA | Major Iteration Limit | max 10,2×NDIM | max 30,3×NDIM
Unless set, these are functions of the parameters passed to E05SAF.
Setting i=0 will disable the local minimizer in the corresponding algorithmic region. For example, setting Local Interior Iterations=0 and Local Exterior Iterations=30 will cause the algorithm to perform no local minimizations inside the main loop of the algorithm, and a local minimization with upto 30 iterations after the main loop has been exited.
Note: currently E04JYF or E04KZF are restricted to using 400×NDIM and 50×NDIM as function evaluation limits respectively. This applies to both local minimizations inside and outside the main loop. They may still be deactivated in either phase by setting i=0, and may subsequently be reactivated in either phase by setting i>0.
Constraint: i 1≥0, i 2≥0.
Local Interior Tolerance r 1 Default=10-4
Local Exterior Tolerance r 2 Default=10-4
This is the tolerance provided to a local minimizer in the interior (exterior) of the main loop of the algorithm.
Constraint: r 1>0.0, r 2>0.0.
Local Interior Minor Iterations i 1
Local Exterior Minor Iterations i 2
Where applicable, the secondary number of iterations the chosen local minimizer will use inside (outside) the main loop. Currently the relevant default values are:
Minimizer | Parameter/option | Default Interior | Default Exterior
E04UCF/E04UCA | Minor Iteration Limit | max 10,2×NDIM | max 30,3×NDIM
Constraint: i 1≥0, i 2≥0.
Local Minimizer a Default=OFF
Allows for a choice of Chapter E04 routines to be used as a coupled, dedicated local minimizer.
OFF
No local minimization will be performed in either the INTERIOR or EXTERIOR sections of the algorithm.
E04CBF
Use E04CBF as the local minimizer. This does not require the calculation of derivatives.
On a call to OBJFUN during a local minimization, MODE=5.
E04KZF
Use E04KZF as the local minimizer. This requires the calculation of derivatives in OBJFUN, as indicated by MODE.
The box bounds forwarded to this routine from E05SAF will have been acted upon by Local Boundary Restriction. As such, the domain exposed may be greatly smaller than that provided to E05SAF.
Accurate derivatives must be provided to this routine, and will not be approximated internally. Each iteration of this local minimizer also requires the calculation of both the objective function and its derivative. Hence on a call to OBJFUN during a local minimization, MODE=7.
E04JYF
Use E04JYF as the local minimizer. This does not require the calculation of derivatives.
On a call to OBJFUN during a local minimization, MODE=5.
The box bounds forwarded to this routine from E05SAF will have been acted upon by Local Boundary Restriction. As such, the domain exposed may be greatly smaller than that provided to E05SAF.
E04DGF
E04DGA
Use E04DGA as the local minimizer.
Accurate derivatives must be provided, and will not be approximated internally. Additionally, each call to OBJFUN during a local minimization will require either the objective to be evaluated alone, or both the objective and its gradient to be evaluated. Hence on a call to OBJFUN, MODE=5 or 7.
E04UCF
E04UCA
Use E04UCA as the local minimizer. This operates such that any derivatives of the objective function that you cannot supply, will be approximated internally using finite differences.
Either, the objective, objective gradient, or both may be requested during a local minimization, and as such on a call to OBJFUN, MODE=1, 2 or 5.
The box bounds forwarded to this routine from E05SAF will have been acted upon by Local Boundary Restriction. As such, the domain exposed may be greatly smaller than that provided to E05SAF.
Maximum Function Evaluations i Default =Imax
The maximum number of evaluations of the objective function. When reached this will return IFAIL=1 and INFORM=6.
Constraint: i>0.
Maximum Iterations Completed i Default=1000×NDIM
The maximum number of complete iterations that may be performed. Once exceeded E05SAF will exit with IFAIL=1 and INFORM=5.
Unless set, this adapts to the parameters passed to E05SAF.
Constraint: i≥1.
Maximum Iterations Static i Default=100
The maximum number of iterations without any improvement to the current global optimum. If exceeded E05SAF will exit with IFAIL=1 and INFORM=4. This exit will be hindered by setting Maximum Iterations Static Particles to larger values.
Constraint: i≥1.
Maximum Iterations Static Particles i Default=0
The minimum number of particles that must have converged to the current optimum before the routine may exit due to Maximum Iterations Static with IFAIL=1 and INFORM=4.
Constraint: i≥0.
Maximum Particles Converged i Default =Imax
The maximum number of particles that may converge to the current optimum. When achieved, E05SAF will exit with IFAIL=1 and INFORM=3. This exit will be hindered by setting ‘Repulsion’ options, as these cause the swarm to re-expand.
Constraint: i>0.
Maximum Particles Reset i Default =Imax
The maximum number of particles that may be reset after converging to the current optimum. Once achieved no further particles will be reset, and any particles within Distance Tolerance of the global optimum will continue to evolve as normal.
Constraint: i>0.
Maximum Variable Velocity r Default=0.25
Along any dimension j, the absolute velocity is bounded above by vj≤r×uj-ℓj=Vmax. Very low values will greatly increase convergence time. There is no upper limit, although larger values will allow more particles to be advected out of the box bounds, and values greater than 4.0 may cause significant and potentially unrecoverable swarm divergence.
Constraint: r>0.0.
Optimize a Default=MINIMIZE
Determines whether to maximize or minimize the objective function.
MINIMIZE
The objective function will be minimized.
MAXIMIZE
The objective function will be maximized. This is accomplished by minimizing the negative of the objective.
Repeatability a Default=OFF
Allows for the same random number generator seed to be used for every call to E05SAF. Repeatability=OFF is recommended in general.
OFF
The internal generation of random numbers will be nonrepeatable.
ON
The same seed will be used.
Repulsion Finalize i Default =Imax
The number of iterations performed in a repulsive phase before re-contraction. This allows a re-diversified swarm to contract back toward the current optimum, allowing for a finer search of the near optimum space.
Constraint: i≥2.
Repulsion Initialize i Default =Imax
The number of iterations without any improvement to the global optimum before the algorithm begins a repulsive phase. This phase allows the particle swarm to re-expand away from the current optimum, allowing more of the domain to be investigated. The repulsive phase is automatically ended if a superior optimum is found.
Constraint: i≥2.
Repulsion Particles i Default=0
The number of particles required to have converged to the current optimum before any repulsive phase may be initialized. This will prevent repulsion before a satisfactory search of the near optimum area has been performed, which may happen for large dimensional problems.
Constraint: i≥0.
Swarm Standard Deviation r Default=0.1
The target standard deviation of the particle distances from the current optimum. Once the standard deviation is below this level, E05SAF will exit with IFAIL=1 and INFORM=2. This criterion will be penalized by the use of ‘Repulsion’ options, as these cause the swarm to re-expand, increasing the standard deviation of the particle distances from the best point.
In SMP parallel implementations of E05SAF, the standard deviation will be calculated based only on the particles local to the particular thread that checks for finalization. Considerably fewer particles may be used in this calculation than when the algorithm is run in serial. It is therefore recommended that you provide a smaller value of Swarm Standard Deviation when running in parallel than when running in serial.
Constraint: r≥0.0.
Target Objective a Default=OFF
Target Objective Value r Default=0.0
Activate or deactivate the use of a target value as a finalization criterion. If active, then once the supplied target value for the objective function is found (beyond the first iteration if Target Warning is active) E05SAF will exit with IFAIL=0 and INFORM=1. Other than checking for feasibility only (Optimize=CONSTRAINTS), this is the only finalization criterion that guarantees that the algorithm has been successful. If the target value was achieved at the initialization phase or first iteration and Target Warning is active, E05SAF will exit with IFAIL=2. This option may take any real value r, or the character ON/OFF as well as DEFAULT. If this option is queried using E05ZLF, the current value of r will be returned in RVALUE, and CVALUE will indicate whether this option is ON or OFF. The behaviour of the option is as follows:
r
Once a point is found with an objective value within the Target Objective Tolerance of r, E05SAF will exit successfully with IFAIL=0 and INFORM=1.
OFF
The current value of r will remain stored, however it will not be used as a finalization criterion.
ON
The current value of r stored will be used as a finalization criterion.
DEFAULT
The stored value of r will be reset to its default value (0.0), and this finalization criterion will be deactivated.
Target Objective Safeguard r Default=100.0 ε
If you have given a target objective value to reach in objval (the value of the optional parameter Target Objective Value), objsfg sets your desired safeguarded termination tolerance, for when objval is close to zero.
Constraint: objsfg≥2 ε.
Target Objective Tolerance r Default=0.0
The optional tolerance to a user-specified target value.
Constraint: r≥0.0.
Target Warning a Default=OFF
Activates or deactivates the error exit associated with the target value being achieved before entry into the main loop of the algorithm, IFAIL=2.
OFF
No error will be returned, and the routine will exit normally.
ON
An error will be returned if the target objective is reached prematurely, and the routine will exit with IFAIL=2.
Verify Gradients a Default=ON
Adjusts the level of gradient checking performed when gradients are required. Gradient checks are only performed on the first call to the chosen local minimizer if it requires gradients. There is no guarantee that the gradient check will be correct, as the finite differences used in the gradient check are themselves subject to inaccuracies.
OFF
No gradient checking will be performed.
ON
A cheap gradient check will be performed on both the gradients corresponding to the objective through OBJFUN.
OBJECTIVE
FULL
A more expensive gradient check will be performed on the gradients corresponding to the objective OBJFUN.
Weight Decrease a Default=INTEREST
Determines how particle weights decrease.
OFF
Weights do not decrease.
INTEREST
Weights decrease through compound interest as w IT+1=wIT 1-Wval, where Wval is the Weight Value and IT is the current number of iterations.
LINEAR
Weights decrease linearly following w IT+1=wIT-IT×Wmax-Wmin/ITmax, where IT is the iteration number and ITmax is the maximum number of iterations as set by Maximum Iterations Completed.
Weight Initial r Default=Wmax
The initial value of any particle's inertial weight, Wini, or the minimum possible initial value if initial weights are randomized. When set, this will override Weight Initialize=RANDOMIZED or MAXIMUM, and as such these must be set afterwards if so desired.
Constraint: Wmin≤r≤Wmax.
Weight Initialize a Default=MAXIMUM
Determines how the initial weights are distributed.
INITIAL
All weights are initialized at the initial weight, Wini, if set. If Weight Initial has not been set, this will be the maximum weight, Wmax.
MAXIMUM
All weights are initialized at the maximum weight, Wmax.
RANDOMIZED
Weights are uniformly distributed in Wmin,Wmax or Wini,Wmax if Weight Initial has been set.
Weight Maximum r Default=1.0
The maximum particle weight, Wmax.
Constraint: 1.0≥r≥Wmin (If Wini has been set then 1.0≥r≥Wini.)
Weight Minimum r Default=0.1
The minimum achievable weight of any particle, Wmin. Once achieved, no further weight reduction is possible.
Constraint: 0.0≤r≤Wmax (If Wini has been set then 0.0≤r≤Wini.)
Weight Reset a Default=MAXIMUM
Determines how particle weights are re-initialized.
INITIAL
Weights are re-initialized at the initial weight if set. If Weight Initial has not been set, this will be the maximum weight.
MAXIMUM
Weights are re-initialized at the maximum weight.
RANDOMIZED
Weights are uniformly distributed in Wmin,Wmax or Wini,Wmax if Weight Initial has been set.
Weight Value r Default=0.01
The constant Wval used with Weight Decrease=INTEREST.
Constraint: 0.0≤r≤13.

12.2 Description of the SMP optional parameters

This section details additional options available to users of multi-threaded implementations of the NAG Library. In particular it includes the option SMP Callback Thread Safe, which must be set before calling E05SAF with multiple threads.
SMP Callback Thread Safe a Default=WARNING
Declare that the callback routines you provide are or are not thread safe. In particular, this indicates that access to the shared memory arrays IUSER and RUSER from within your provided callbacks is done in a thread safe manner. If these arrays are just used to pass constant data, then you may assume they are thread safe. If these are also used for workspace, or passing variable data such as random number generator seeds, then you must ensure these are accessed and updated safely. Whilst this can be done using OpenMP critical sections, we suggest their use is minimized to prevent unnecessary bottlenecks, and that instead individual threads have access to independent subsections of the provided arrays where possible.
YES
The callback routines have been programmed in a thread safe way. The algorithm will use OMP_NUM_THREADS threads.
NO
The callback routines are not thread safe. Setting this option will force the algorithm to run on a single thread only, and is advisable only for debugging purposes, or if you wish to parallelize your callback functions.
WARNING
This will cause an immediate exit from E05SAF with IFAIL=51 if multiple threads are detected. This is to inform you that you have not declared the callback functions either to be thread safe, or that they are thread unsafe and you wish the algorithm to run in serial.
An additional example program, e05safe_smp.f90, is included with the distribution material of multi-threaded implementations of the NAG Library to illustrate how to safely access independent subsections of the provided IUSER and RUSER arrays from multiple threads.
SMP Local Minimizer External a Default=ALL
Determines how many threads will attempt to locally minimize the best found solution after the routine has exited the main loop.
MASTER
Only the master thread will attempt to find any improvement. The local minimization will be launched from the best known solution. All other threads will remain effectively idle.
ALL
The master thread will perform a local minimization from the best known solution, while all other threads will perform a local minimization from randomly generated perturbations of the best known solution, increasing the chance of an improvement. Assuming all local minimizations will take approximately the same amount of computation, this will be effectively free in terms of real time. It will however increase the number of function evaluations performed.
SMP Monitor a Default=SINGLE
SMP Monmod a
Determines whether the user-supplied function MONMOD is invoked once every sub-iteration each thread performs, or only once by a single thread after all threads have completed at least one sub-iteration.
SINGLE
Only one thread will invoke MONMOD, after all threads have performed at least one sub-iteration.
ALL
Each thread will invoke MONMOD each time it completes a sub-iteration. If you wish to alter X using MONMOD you should use this option, as MONMOD will only receive the arrays X, XBEST and FBEST private to the calling thread.
SMP Subswarm i Default=1
Determines how many threads support a particle subswarm. This is an extra collection of particles constrained to search only within a hypercube of edge length 10.0×Distance Tolerance of the best point known to an individual thread. This may improve the number of iterations required to find a provided target, particularly if no local minimizer is in use.
If i≤0, then this will be disabled on all the threads.
If i≥OMP_NUM_THREADS, then all the threads will support a particle subswarm.
SMP Thread Overrun i Default=Imax
This option provides control over the level of asynchronicity present in a simulation. In particular, a barrier synchronization between all threads is performed if any thread completes i sub-iterations more than the slowest thread, causing all threads to be exposed to the current best solution. Allowing asynchronous behaviour does however allow individual threads to focus on different global optimum candidates some of the time, which can inhibit convergence to unwanted sub-optima. It also allows for threads to continue searching when other threads are completing sub-iterations at a slower rate.
If i<1, then the algorithm will force a synchronization between threads at the end of each iteration.
E05 Chapter Contents
E05 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


E05SBF : NAG Library, Mark 26

E05 Chapter Contents
E05 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

E05SBF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.
Note: this routine uses optional parameters to define choices in the problem specification and in the details of the algorithm. If you wish to use default settings for all of the optional parameters, you need only read Sections 1 to 10 of this document. If, however, you wish to reset some or all of the settings please refer to Section 11 for a detailed description of the algorithm and to Section 12 for a detailed description of the specification of the optional parameters.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results
11 Algorithmic Details
▸▿ 12 Optional Parameters
12.1 Description of the Optional Parameters
12.2 Description of the SMP optional parameters

1 Purpose

E05SBF is designed to search for the global minimum or maximum of an arbitrary function, subject to general nonlinear constraints, using Particle Swarm Optimization (PSO). Derivatives are not required, although these may be used by an accompanying local minimization routine if desired. E05SBF is essentially identical to E05SAF, with an expert interface and various additional arguments added; otherwise most arguments are identical. In particular, E05SAF does not handle general constraints.

2 Specification

SUBROUTINE E05SBF ( NDIM, NCON, NPAR, XB, FB, CB, BL, BU, XBEST, FBEST, CBEST, OBJFUN, CONFUN, MONMOD, IOPTS, OPTS, IUSER, RUSER, ITT, INFORM, IFAIL)
INTEGER | NDIM, NCON, NPAR, IOPTS(*), IUSER(*), ITT(7), INFORM, IFAIL
REAL (KIND=nag_wp) | XB(NDIM), FB, CB(NCON), BL(NDIM+NCON), BU(NDIM+NCON), XBEST(NDIM,NPAR), FBEST(NPAR), CBEST(NCON,NPAR), OPTS(*), RUSER(*)
EXTERNAL | OBJFUN, CONFUN, MONMOD
Before calling E05SBF, E05ZKF must be called with OPTSTR set to ‘Initialize = e05sbf’. Optional parameters may also be specified by calling E05ZKF before the call to E05SBF.

3 Description

E05SBF uses a stochastic method based on Particle Swarm Optimization (PSO) to search for the global optimum of a nonlinear function F, subject to a set of bound constraints on the variables, and optionally a set of general nonlinear constraints. In the PSO algorithm (see Section 11), a set of particles is generated in the search space, and advances each iteration to (hopefully) better positions using a heuristic velocity based upon inertia, cognitive memory and global memory. The inertia is provided by a decreasingly weighted contribution from a particles current velocity, the cognitive memory refers to the best candidate found by an individual particle and the global memory refers to the best candidate found by all the particles. This allows for a global search of the domain in question.
Further, this may be coupled with a selection of local minimization routines, which may be called during the iterations of the heuristic algorithm, the interior phase, to hasten the discovery of locally optimal points, and after the heuristic phase has completed to attempt to refine the final solution, the exterior phase. Different options may be set for the local optimizer in each phase.
Without loss of generality, the problem is assumed to be stated in the following form:
minimize x∈Rndim   F x   subject to   ℓ ≤ x c x ≤ u ,
where the objective F x is a scalar function, c x is a vector of scalar constraint functions, x is a vector in Rndim and the vectors ℓ≤u are lower and upper bounds respectively for the ndim variables and ncon constraints. Both the objective function and the ncon constraints may be nonlinear. Continuity of F, and the functions c x, is not essential. For functions which are smooth and primarily unimodal, faster solutions will almost certainly be achieved by using Chapter E04 routines directly.
For functions which are smooth and multi-modal, gradient dependent local minimization routines may be coupled with E05SBF.
For multi-modal functions for which derivatives cannot be provided, particularly functions with a significant level of noise in their evaluation, E05SBF should be used either alone, or coupled with E04CBF.
For heavily constrained problems, E05SBF should either be used alone, or coupled with E04UCF/E04UCA provided the function and the constraints are sufficiently smooth.
The ndim lower and upper box bounds on the variable x are included to initialize the particle swarm into a finite hypervolume, although their subsequent influence on the algorithm is user determinable (see the option Boundary in Section 12). It is strongly recommended that sensible bounds are provided for all variables and constraints.
E05SBF may also be used to maximize the objective function, or to search for a feasible point satisfying the simple bounds and general constraints (see the option Optimize).
Due to the nature of global optimization, unless a predefined target is provided, there is no definitive way of knowing when to end a computation. As such several stopping heuristics have been implemented into the algorithm. If any of these is achieved, E05SBF will exit with IFAIL=1, and the parameter INFORM will indicate which criteria was reached. See INFORM for more information.
In addition, you may provide your own stopping criteria through MONMOD, OBJFUN and CONFUN.
E05SAF provides a simpler interface, without the inclusion of general nonlinear constraints.

4 References

Gill P E, Murray W and Wright M H (1981) Practical Optimization Academic Press
Kennedy J and Eberhart R C (1995) Particle Swarm Optimization Proceedings of the 1995 IEEE International Conference on Neural Networks 1942–1948
Koh B, George A D, Haftka R T and Fregly B J (2006) Parallel Asynchronous Particle Swarm Optimization International Journal for Numerical Methods in Engineering 67(4) 578–595
Vaz A I and Vicente L N (2007) A Particle Swarm Pattern Search Method for Bound Constrained Global Optimization Journal of Global Optimization 39(2) 197–219 Kluwer Academic Publishers

5 Arguments

Note: for descriptions of the symbolic variables, see Section 11.
1:   NDIM – INTEGERInput
On entry: ndim, the number of dimensions.
Constraint: NDIM≥1.
2:   NCON – INTEGERInput
On entry: ncon, the number of constraints, not including box constraints.
Constraint: NCON≥0.
3:   NPAR – INTEGERInput
On entry: npar, the number of particles to be used in the swarm. Assuming all particles remain within constraints, each complete iteration will perform at least NPAR function evaluations. Otherwise, significantly fewer objective function evaluations may be performed.
Suggested value: NPAR=10×NDIM.
Constraint: NPAR≥5×num_threads, where num_threads is the value returned by the OpenMP environment variable OMP_NUM_THREADS, or num_threads is 1 for a serial version of this routine.
4:   XB NDIM – REAL (KIND=nag_wp) arrayOutput
On exit: the location of the best solution found, x~, in Rndim.
5:   FB – REAL (KIND=nag_wp)Output
On exit: the objective value of the best solution, f~=F x~.
6:   CB NCON – REAL (KIND=nag_wp) arrayOutput
On exit: the constraint violations of the best solution found, e~=e x~. These may have been deemed to be acceptable given the tolerance and scaling of the constraints. See Sections 11 and 12.
7:   BL NDIM+NCON – REAL (KIND=nag_wp) arrayInput
8:   BU NDIM+NCON – REAL (KIND=nag_wp) arrayInput
On entry: BL is ℓ, the array of lower bounds, BU is u, the array of upper bounds. The first NDIM entries in BL and BU must contain the lower and upper simple (box) bounds of the variables respectively. These must be provided to initialize the sample population into a finite hypervolume, although their subsequent influence on the algorithm is user determinable (see the option Boundary in Section 12).
The next NCON entries must contain the lower and upper bounds for any general constraints respectively.
If BL i=BU i for any i∈1,…,NDIM, variable i will remain locked to BL i regardless of the Boundary option selected.
It is strongly advised that you place sensible lower and upper bounds on all variables and constraints, even if your model allows for unbounded variables or constraints.
Constraints:
  • BL i≤BU i, for i=1,2,…,NDIM+NCON;
  • BL i≠BU i for at least one i∈1,…,NDIM.
9:   XBEST NDIMNPAR – REAL (KIND=nag_wp) arrayInput/Output
Note: the ith component of the best position of the jth particle, x^j i, is stored in XBEST ij.
On entry: if using Start=WARM, the initial particle positions, x^j 0.
On exit: the best positions found, x^j, by the NPAR particles in the swarm.
10:   FBEST NPAR – REAL (KIND=nag_wp) arrayInput/Output
On entry: if using Start=WARM, objective function values, f^j 0=F x^j 0, corresponding to the NPAR particle locations stored in XBEST.
On exit: objective function values, f^j=F x^j, corresponding to the locations returned in XBEST.
11:   CBEST NCONNPAR – REAL (KIND=nag_wp) arrayInput/Output
Note: the kth constraint violation of the jth particle is stored in CBEST kj.
On entry: if using Start=WARM, the initial constraint violations, e^j 0=e x^j 0, corresponding to the NPAR particle locations.
On exit: the final constraint violations, e^j, corresponding to the locations returned in XBEST.
12:   OBJFUN – SUBROUTINE, supplied by the user.External Procedure
OBJFUN must, depending on the value of MODE, calculate the objective function and/or calculate the gradient of the objective function for a ndim-variable vector x. Gradients are only required if a local minimizer has been chosen which requires gradients. See the option Local Minimizer for more information.
The specification of OBJFUN is:
SUBROUTINE OBJFUN ( MODE, NDIM, X, OBJF, VECOUT, NSTATE, IUSER, RUSER)
INTEGER | MODE, NDIM, NSTATE, IUSER(*)
REAL (KIND=nag_wp) | X(NDIM), OBJF, VECOUT(NDIM), RUSER(*)
1:   MODE – INTEGERInput/Output
On entry: indicates which functionality is required.
MODE=0
F x should be returned in OBJF. The value of OBJF on entry may be used as an upper bound for the calculation. Any expected value of F x that is greater than OBJF may be approximated by this upper bound; that is OBJF can remain unaltered.
MODE=1
Local Minimizer=E04UCF only
First derivatives can be evaluated and returned in VECOUT. Any unaltered elements of VECOUT will be approximated using finite differences.
MODE=2
Local Minimizer=E04UCF only
F x must be calculated and returned in OBJF, and available first derivatives can be evaluated and returned in VECOUT. Any unaltered elements of VECOUT will be approximated using finite differences.
MODE=5
F x must be calculated and returned in OBJF. The value of OBJF on entry may not be used as an upper bound.
MODE=6
Local Minimizer=E04DGF or E04KZF only
All first derivatives must be evaluated and returned in VECOUT.
MODE=7
Local Minimizer=E04DGF or E04KZF only
F x must be calculated and returned in OBJF, and all first derivatives must be evaluated and returned in VECOUT.
On exit: if the value of MODE is set to be negative, then E05SBF will exit as soon as possible with IFAIL=3 and INFORM=MODE.
2:   NDIM – INTEGERInput
On entry: the number of dimensions.
3:   X NDIM – REAL (KIND=nag_wp) arrayInput
On entry: x, the point at which the objective function and/or its gradient are to be evaluated.
4:   OBJF – REAL (KIND=nag_wp)Input/Output
On entry: the value of OBJF passed to OBJFUN varies with the argument MODE.
MODE=0
OBJF is an upper bound for the value of F x, often equal to the best constraint penalised value of F x found so far by a given particle if the objective function is strictly positive (see Section 11). Only objective function values less than the value of OBJF on entry will be used further. As such this upper bound may be used to stop further evaluation when this will only increase the objective function value above the upper bound.
MODE=1, 2, 5, 6 or 7
OBJF is meaningless on entry.
On exit: the value of OBJF returned varies with the argument MODE.
MODE=0
OBJF must be the value of F x. Only values of F x strictly less than OBJF on entry need be accurate.
MODE=1 or 6
Need not be set.
MODE=2, 5 or 7
F x must be calculated and returned in OBJF. The entry value of OBJF may not be used as an upper bound.
5:   VECOUT NDIM – REAL (KIND=nag_wp) arrayInput/Output
On entry: if Local Minimizer=E04UCF or E04UCA, the values of VECOUT are used internally to indicate whether a finite difference approximation is required. See E04UCF/E04UCA.
On exit: the required values of VECOUT returned to the calling routine depend on the value of MODE.
MODE=0 or 5
The value of VECOUT need not be set.
MODE=1 or 2
VECOUT can contain components of the gradient of the objective function ∂F ∂xi for some i=1,2,…NDIM, or acceptable approximations. Any unaltered elements of VECOUT will be approximated using finite differences.
MODE=6 or 7
VECOUT must contain the gradient of the objective function ∂F ∂xi for all i=1,2,…NDIM. Approximation of the gradient is strongly discouraged, and no finite difference approximations will be performed internally (see E04DGF/E04DGA and E04KZF).
6:   NSTATE – INTEGERInput
On entry: NSTATE indicates various stages of initialization throughout the routine. This allows for permanent global arguments to be initialized the least number of times. For example, you may initialize a random number generator seed.
NSTATE=3
SMP users only. OBJFUN is called for the first time in a parallel region on a new thread other than the master thread. You may use this opportunity to set up any thread-dependent information in IUSER and RUSER.
NSTATE=2
OBJFUN is called for the very first time. You may save computational time if certain data must be read or calculated only once.
NSTATE=1
OBJFUN is called for the first time by a NAG local minimization routine. You may save computational time if certain data required for the local minimizer need only be calculated at the initial point of the local minimization.
NSTATE=0
Used in all other cases.
7:   IUSER* – INTEGER arrayUser Workspace
8:   RUSER* – REAL (KIND=nag_wp) arrayUser Workspace
OBJFUN is called with the arguments IUSER and RUSER as supplied to E05SBF. You are free to use the arrays IUSER and RUSER to supply information to OBJFUN as an alternative to using COMMON global variables.
OBJFUN must either be a module subprogram USEd by, or declared as EXTERNAL in, the (sub)program from which E05SBF is called. Arguments denoted as Input must not be changed by this procedure.
13:   CONFUN – SUBROUTINE, supplied by the NAG Library or the user.External Procedure
CONFUN must calculate any constraints other than the box constraints. If no constraints are required, CONFUN may be the dummy constraint routine E05SZM. (E05SZM is included in the NAG Library). For information on how a NAG local minimizer will use CONFUN see the documentation for E04UCA.
The specification of CONFUN is:
SUBROUTINE CONFUN ( MODE, NCON, NDIM, LDCJ, NEEDC, X, C, CJAC, NSTATE, IUSER, RUSER)
INTEGER | MODE, NCON, NDIM, LDCJ, NEEDC(NCON), NSTATE, IUSER(*)
REAL (KIND=nag_wp) | X(NDIM), C(NCON), CJAC(LDCJ,NDIM), RUSER(*)
1:   MODE – INTEGERInput/Output
On entry: indicates which values must be assigned during each call of CONFUN. Only the following values need be assigned, for each value of k∈1,…,NCON such that NEEDC k>0:
MODE=0
the constraint values ck x.
MODE=1
rows of the constraint Jacobian, ∂ck∂xi x, for i=1,2,…,NDIM.
MODE=2
the constraint values ck x and the corresponding rows of the constraint Jacobian, ∂ck∂xi x, for i=1,2,…,NDIM.
On exit: may be set to a negative value if you wish to terminate the solution to the current problem. In this case E05SBF will terminate with IFAIL=3 and INFORM=MODE as soon as possible.
2:   NCON – INTEGERInput
On entry: the number of constraints, not including box bounds.
3:   NDIM – INTEGERInput
On entry: the number of variables.
4:   LDCJ – INTEGERInput
On entry: the first dimension of the array CJAC as declared in the (sub)program from which E05SBF is called.
5:   NEEDC NCON – INTEGER arrayInput
On entry: the indices of the elements of C and/or CJAC that must be evaluated by CONFUN. If NEEDC k>0, the kth element of C, corresponding to the values of the kth constraint, and/or the available elements of the kth row of CJAC, corresponding to the derivatives of the kth constraint, must be evaluated at x (see argument MODE).
6:   X NDIM – REAL (KIND=nag_wp) arrayInput
On entry: x, the vector of variables at which the constraint functions and/or the available elements of the constraint Jacobian are to be evaluated.
7:   C NCON – REAL (KIND=nag_wp) arrayOutput
On exit: if NEEDC k>0 and MODE=0 or 2, C k must contain the value of ck x. The remaining elements of C, corresponding to the non-positive elements of NEEDC, need not be set.
8:   CJAC LDCJNDIM – REAL (KIND=nag_wp) arrayInput/Output
Note: the derivative of the kth constraint with respect to the ith component, ∂ck ∂x i , is stored in CJAC ki.
On entry: the elements of CJAC are set to special values which enable E05SBF to detect whether they are changed by CONFUN.
On exit: if NEEDC k>0 and MODE=1 or 2, the elements of CJAC corresponding to the kth row of the constraint Jacobian should contain the available elements of the vector ∇ck given by
∇ck= ∂ck ∂x 1 , ∂ck ∂x 2 ,…, ∂ck ∂xn ,
where ∂ck ∂xi is the partial derivative of the kth constraint with respect to the ith variable, evaluated at the point x; elements of CJAC that remain unaltered will be approximated internally using finite differences. The remaining rows of CJAC, corresponding to non-positive elements of NEEDC, need not be set.
It must be emphasized that unassigned elements of CJAC are not treated as constant; they are estimated by finite differences, at nontrivial expense. An interval for each element of x is computed automatically at the start of the optimization. The automatic procedure can usually identify constant elements of CJAC, which are then computed once only by finite differences.
9:   NSTATE – INTEGERInput
On entry: NSTATE indicates various stages of initialization throughout the routine. This allows for permanent global arguments to be initialized a minimum number of times. For example, you may initialize a random number generator seed. Note that unless the option Optimize=CONSTRAINTS has been set, OBJFUN will be called before CONFUN.
NSTATE=3
SMP users only. OBJFUN is called for the first time in a parallel region on a new thread other than the master thread. You may use this opportunity to set up any thread-dependent information in IUSER and RUSER.
NSTATE=2
CONFUN is called for the very first time. This argument setting allows you to save computational time if certain data must be read or calculated only once.
NSTATE=1
CONFUN is called for the first time during a NAG local minimization routine. This argument setting allows you to save computational time if certain data required for the local minimizer need only be calculated at the initial point of the local minimization.
NSTATE=0
Used in all other cases.
10:   IUSER* – INTEGER arrayUser Workspace
11:   RUSER* – REAL (KIND=nag_wp) arrayUser Workspace
CONFUN is called with the arguments IUSER and RUSER as supplied to E05SBF. You are free to use the arrays IUSER and RUSER to supply information to CONFUN as an alternative to using COMMON global variables.
CONFUN must either be a module subprogram USEd by, or declared as EXTERNAL in, the (sub)program from which E05SBF is called. Arguments denoted as Input must not be changed by this procedure.
CONFUN should be tested separately before being used in conjunction with E05SBF.
14:   MONMOD – SUBROUTINE, supplied by the NAG Library or the user.External Procedure
A user-specified monitoring and modification function. MONMOD is called once every complete iteration after a finalization check. It may be used to modify the particle locations that will be evaluated at the next iteration. This permits the incorporation of algorithmic modifications such as including additional advection heuristics and genetic mutations. MONMOD is only called during the main loop of the algorithm, and as such will be unaware of any further improvement from the final local minimization. If no monitoring and/or modification is required, MONMOD may be the dummy monitoring routine E05SYM. (E05SYM is included in the NAG Library) .
The specification of MONMOD is:
SUBROUTINE MONMOD ( NDIM, NCON, NPAR, X, XB, FB, CB, XBEST, FBEST, CBEST, ITT, IUSER, RUSER, INFORM)
INTEGER | NDIM, NCON, NPAR, ITT(7), IUSER(*), INFORM
REAL (KIND=nag_wp) | X(NDIM,NPAR), XB(NDIM), FB, CB(NCON), XBEST(NDIM,NPAR), FBEST(NPAR), CBEST(NCON,NPAR), RUSER(*)
1:   NDIM – INTEGERInput
On entry: the number of dimensions.
2:   NCON – INTEGERInput
On entry: the number of constraints.
3:   NPAR – INTEGERInput
On entry: the number of particles.
4:   X NDIMNPAR – REAL (KIND=nag_wp) arrayInput/Output
Note: the ith component of the jth particle, xj i, is stored in X ij.
On entry: the NPAR particle locations, xj, which will currently be used during the next iteration unless altered in MONMOD.
On exit: the particle locations to be used during the next iteration.
5:   XB NDIM – REAL (KIND=nag_wp) arrayInput
On entry: the location, x~, of the best solution yet found.
6:   FB – REAL (KIND=nag_wp)Input
On entry: the objective value, f~=F x~, of the best solution yet found.
7:   CB NCON – REAL (KIND=nag_wp) arrayInput
On entry: the constraint violations, e~=e x~, of the best solution yet found.
8:   XBEST NDIMNPAR – REAL (KIND=nag_wp) arrayInput
Note: the ith component of the position of the jth particle's cognitive memory, x^j i, is stored in XBEST ij.
On entry: the locations currently in the cognitive memory, x^j, for j=1,2,…,NPAR (see Section 11).
9:   FBEST NPAR – REAL (KIND=nag_wp) arrayInput
On entry: the objective values currently in the cognitive memory, F x^j, for j=1,2,…,NPAR.
10:   CBEST NCONNPAR – REAL (KIND=nag_wp) arrayInput
Note: the kth constraint violation of the jth particle's cognitive memory is stored in CBEST kj.
On entry: the constraint violations currently in the cognitive memory, e^=e x^j, for j=1,2,…,NPAR, evaluated at x^j.
11:   ITT 7 – INTEGER arrayInput
On entry: iteration and function evaluation counters (see description of ITT below).
12:   IUSER* – INTEGER arrayUser Workspace
13:   RUSER* – REAL (KIND=nag_wp) arrayUser Workspace
MONMOD is called with the arguments IUSER and RUSER as supplied to E05SBF. You are free to use the arrays IUSER and RUSER to supply information to MONMOD as an alternative to using COMMON global variables.
14:   INFORM – INTEGERInput/Output
On entry: INFORM=thread_num, where thread_num is the value returned by a call of the OpenMP function OMP_GET_THREAD_NUM(). If running in serial this will always be zero.
On exit: setting INFORM<0 will cause near immediate exit from E05SBF. This value will be returned as INFORM with IFAIL=3. You need not set INFORM unless you wish to force an exit.
MONMOD must either be a module subprogram USEd by, or declared as EXTERNAL in, the (sub)program from which E05SBF is called. Arguments denoted as Input must not be changed by this procedure.
15:   IOPTS* – INTEGER arrayCommunication Array
Note: the dimension of this array is dictated by the requirements of associated functions that must have been previously called. This array must be the same array passed as argument IOPTS in the previous call to E05ZKF.
On entry: optional parameter array as generated and possibly modified by calls to E05ZKF. The contents of IOPTS must not be modified directly between calls to E05SBF, E05ZKF or E05ZLF.
16:   OPTS* – REAL (KIND=nag_wp) arrayCommunication Array
Note: the dimension of this array is dictated by the requirements of associated functions that must have been previously called. This array must be the same array passed as argument OPTS in the previous call to E05ZKF.
On entry: optional parameter array as generated and possibly modified by calls to E05ZKF. The contents of OPTS must not be modified directly between calls to E05SBF, E05ZKF or E05ZLF.
17:   IUSER* – INTEGER arrayUser Workspace
IUSER is not used by E05SBF, but is passed directly to OBJFUN, CONFUN and MONMOD and may be used to pass information to these routines as an alternative to using COMMON global variables.
With care, you may also write information back into IUSER. This might be useful, for example, should there be a need to preserve the state of a random number generator.
With SMP-enabled versions of E05SBF the array IUSER provided are classified as OpenMP shared memory. Use of IUSER has to take account of this in order to preserve thread safety whenever information is written back to either of these arrays.
18:   RUSER* – REAL (KIND=nag_wp) arrayUser Workspace
RUSER is not used by E05SBF, but is passed directly to OBJFUN, CONFUN and MONMOD and may be used to pass information to these routines as an alternative to using COMMON global variables.
With care, you may also write information back into RUSER. This might be useful, for example, should there be a need to preserve the state of a random number generator.
With SMP-enabled versions of E05SBF the array RUSER provided are classified as OpenMP shared memory. Use of RUSER has to take account of this in order to preserve thread safety whenever information is written back to either of these arrays.
19:   ITT 7 – INTEGER arrayOutput
On exit: integer iteration counters for E05SBF.
ITT 1
Number of complete iterations.
ITT 2
Number of complete iterations without improvement to the current optimum.
ITT 3
Number of particles converged to the current optimum.
ITT 4
Number of improvements to the optimum.
ITT 5
Number of function evaluations performed.
ITT 6
Number of particles reset.
ITT 7
Number of violated constraints at completion. Note this is always calculated using the L 1 norm and a nonzero result does not necessarily mean that the algorithm did not find a suitably constrained point with respect to the single norm used.
20:   INFORM – INTEGEROutput
On exit: indicates which finalization criterion was reached. The possible values of INFORM are:
INFORM | Meaning
<0 | Exit from a user-supplied subroutine.
0 | E05SBF has detected an error and terminated.
1 | The provided objective target has been achieved. (Target Objective Value).
2 | The standard deviation of the location of all the particles is below the set threshold (Swarm Standard Deviation). If the solution returned is not satisfactory, you may try setting a smaller value of Swarm Standard Deviation, or try adjusting the options governing the repulsive phase (Repulsion Initialize, Repulsion Finalize).
3 | The total number of particles converged (Maximum Particles Converged) to the current global optimum has reached the set limit. This is the number of particles which have moved to a distance less than Distance Tolerance from the optimum with regard to the L 2 norm. If the solution is not satisfactory, you may consider lowering the Distance Tolerance. However, this may hinder the global search capability of the algorithm.
4 | The maximum number of iterations without improvement (Maximum Iterations Static) has been reached, and the required number of particles (Maximum Iterations Static Particles) have converged to the current optimum. Increasing either of these options will allow the algorithm to continue searching for longer. Alternatively if the solution is not satisfactory, re-starting the application several times with Repeatability=OFF may lead to an improved solution.
5 | The maximum number of iterations (Maximum Iterations Completed) has been reached. If the number of iterations since improvement is small, then a better solution may be found by increasing this limit, or by using the option Local Minimizer with corresponding exterior options. Otherwise if the solution is not satisfactory, you may try re-running the application several times with Repeatability=OFF and a lower iteration limit, or adjusting the options governing the repulsive phase (Repulsion Initialize, Repulsion Finalize).
6 | The maximum allowed number of function evaluations (Maximum Function Evaluations) has been reached. As with INFORM=5, increasing this limit if the number of iterations without improvement is small, or decreasing this limit and running the algorithm multiple times with Repeatability=OFF, may provide a superior result.
7 | A feasible point has been found. The objective has not been minimized, although it has been evaluated at the final solutions given in XB and XBEST (Optimize=CONSTRAINTS).
If you wish to continue from the final position gained from a previous simulation with adjusted options, you may set the option Start=WARM, and pass back in the returned arrays XBEST, FBEST, and CBEST. You should either record the returned values of XB, FB and CB for comparison, as these will not be re-used by the algorithm, or include them in XBEST, FBEST and CBEST respectively by overwriting the entries corresponding to one particle with the relevant information.
21:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
On exit: the most common exit will be IFAIL=1.
For this reason, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended; otherwise, the recommended value is -1. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
E05SBF returns IFAIL=0 if and only if a finalization criterion has been reached which can guarantee success. This may only happen if:
(i) | The option Target Objective Value has been set and has been reached at a sufficiently constrained point within the search domain.
(ii) | The option Optimize=CONSTRAINTS has been set, and a sufficiently constrained point has been found within the search domain.
These finalization criteria are not active using default option settings, and must be explicitly set using E05ZKF if required.
E05SBF will return IFAIL=1 if no error has been detected, and a finalization criterion has been achieved which cannot guarantee success. This does not indicate that the routine has failed, merely that the returned solution cannot be guaranteed to be the true global optimum.
The value of INFORM should be examined to determine which finalization criterion was reached.
Other positive values of IFAIL indicate that either an error or a warning has been triggered. See Sections 6, 7 and 11 for more information.

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
A finalization criterion was reached that cannot guarantee success.
On exit, INFORM=value.
IFAIL=2
If the option Target Warning has been activated, this indicates that the Target Objective Value has been achieved to specified tolerances at a sufficiently constrained point, either during the initialization phase, or during the first two iterations of the algorithm. While this is not necessarily an error, it may occur if:
(i) | The target was achieved at the first point sampled by the routine. This will be the mean of the lower and upper bounds.
(ii) | The target may have been achieved at a randomly generated sample point. This will always be a possibility provided that the domain under investigation contains a point with a target objective value.
(iii) | If the Local Minimizer has been set, then a sample point may have been inside the basin of attraction of a satisfactory point. If this occurs repeatedly when the routine is called, it may imply that the objective is largely unimodal, and that it may be more efficient to use the routine selected as the Local Minimizer directly.
Assuming that OBJFUN is correct, you may wish to set a better Target Objective Value, or a stricter Target Objective Tolerance.
IFAIL=3
User requested exit value during call to CONFUN.
User requested exit value during call to MONMOD.
User requested exit value during call to OBJFUN.
IFAIL=4
Unable to locate strictly feasible point. value constraints remain violated. This exit may be suppressed using the option Constraint Warning.
IFAIL=11
On entry, NDIM=value.
Constraint: NDIM≥1.
IFAIL=12
On entry, NPAR=value.
Constraint: NPAR≥5×num_threads, where num_threads is the value returned by the OpenMP environment variable OMP_NUM_THREADS, or num_threads is 1 for a serial version of this routine.
IFAIL=13
On entry, NCON=value.
Constraint: NCON≥0.
IFAIL=14
On entry, BL value=value and BU value=value.
Constraint: BU i≥BL i for all i.
On entry, BL i=BU i for all box bounds i.
Constraint: BU i>BL i for at least one box bound i.
IFAIL=17
E05SBF has been called with NCON>0 and the dummy constraint function E05SZM. Only use E05SZM with NCON=0.
IFAIL=18
The option Optimize=CONSTRAINTS is active, however NCON=0.
IFAIL=19
Error value occurred whilst adjusting to exterior local minimizer options.
Error value occurred whilst adjusting to interior local minimizer options.
IFAIL=21
Either the option arrays have not been initialized for E05SBF, or they have become corrupted.
IFAIL=32
Derivative checks indicate possible errors in the supplied derivatives. Gradient checks may be disabled by setting Verify Gradients=OFF.
IFAIL=51
Multiple SMP threads have been detected; however, the option SMP Callback Thread Safe has not been set.
Set SMP Callback Thread Safe=YES if the provided callbacks are thread safe.
Set SMP Callback Thread Safe=NO if the provided callbacks are not thread safe, to force serial execution.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

If IFAIL=0 (or IFAIL=2) or IFAIL=1 on exit, a criterion will have been reached depending on user selected options. As with all global optimization software, the solution achieved may not be the true global optimum. Various options allow for either greater search diversity or faster convergence to a (local) optimum (See Sections 11 and 12).
Provided the objective function and constraints are sufficiently well behaved, if a local minimizer is used in conjunction with E05SBF, then it is more likely that the final result will at least be in the near vicinity of a local optimum, and due to the global search characteristics of the particle swarm, this solution should be superior to many other local optima.
Caution should be used in accelerating the rate of convergence, as with faster convergence, less of the domain will remain searchable by the swarm, making it increasingly difficult for the algorithm to detect the basins of attraction of superior local optima. Using the options Repulsion Initialize and Repulsion Finalize described in Section 12 will help to overcome this, by causing the swarm to diverge away from the current optimum once no more local improvement is likely.
On successful exit with guaranteed success, IFAIL=0 (or IFAIL=2). This may happen if a Target Objective Value is assigned and is reached by the algorithm at a satisfactorily constrained point. It will also occur if a constrained point is found when Optimize=CONSTRAINTS is set.
On successful exit without guaranteed success, IFAIL=1 is returned. This will happen if another finalization criterion is achieved without the detection of an error.
In both cases, the value of INFORM provides further information as to the cause of the exit.

8 Parallelism and Performance

E05SBF is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
E05SBF makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.
The algorithm has been parallelized to allow for a high degree of asynchronicity between threads. Each thread is assigned a static number of the NPAR particles requested, and performs a sub-iteration using these particles and a private copy of x~. The thread only updates this private copy if a superior solution is found. In these implementations, this routine may make calls to the user-supplied functions from within an OpenMP parallel region. Thus OpenMP directives within the user functions can only be used if you are compiling the user-supplied function and linking the executable in accordance with the instructions in the Users' Note for your implementation.
Once a thread has completed a sub-iteration, it enters a brief critical section where it compares this private x~ to a globally accessible version. If either is superior, the inferior version is updated and the thread continues into a new sub-iteration.
Parallelizing the algorithm in this way allows for individual threads to continue searching even if other threads are completing sub-iterations in inferior times. The optional argument SMP Thread Overrun allows you to force a synchronization across the team of threads once one thread completes sufficiently more sub-iterations than the slowest thread. In particular, this may be used to force synchronization after every sub-iteration if so desired.
When using an SMP parallel version of this routine, you must indicate that the callback routines are thread safe by setting the optional argument SMP Callback Thread Safe before calling E05SBF in a multi-threaded environment. See Section 12.2 for more information on this and other SMP options.
Note: the stochastic method used in E05SBF will not produce repeatable answers when run on multiple threads.

9 Further Comments

The memory used by E05SBF is relatively static throughout. Indeed, most of the memory required is used to store the current particle locations, the cognitive particle memories, the particle velocities and the particle weights. As such, E05SBF may be used in problems with high dimension number (NDIM>100) without the concern of computational resource exhaustion, although the probability of successfully locating the global optimum will decrease dramatically with the increase in dimensionality.
Due to the stochastic nature of the algorithm, the result will vary over multiple runs. This is particularly true if arguments and options are chosen to accelerate convergence at the expense of the global search. However, the option Repeatability=ON may be set to initialize the internal random number generator using a preset seed, which will result in identical solutions being obtained.
(For SMP users only) The option Repeatability=ON will use preset seeds to initialize the random number generator on each thread, however due to the unpredictable nature of parallel communication, this cannot ensure repeatable results when running on multiple threads, even with SMP Thread Overrun set to force synchronization every iteration.

10 Example

This example uses a particle swarm to find the global minimum of the two-dimensional Schwefel function:
minimize x∈R 2 f = ∑ j=1 2 xj sin xj
subject to the constraints:
3.0 x 1 - 2.0 x 2 <10.0 , -1.0 < x 12 - x 22 + 3.0 x 1 x 2 < 50000.0 , -0.9 < cos x 1 / 200 2 + x 2 / 100 < 0.9 , -500 ≤ x 1 ≤ 500 , -500 ≤ x 2 ≤ 500 .
The global optimum has an objective value of fmin=-731.707, located at x=-394.15,-433.48. Only the third constraint is active at this point.
The example demonstrates how to initialize and set the options arrays using E05ZKF, how to query options using E05ZLF, and finally how to search for the global optimum using E05SBF. The problem is solved twice, first using E05SBF alone, and secondly by coupling E05SBF with E04UCF/E04UCA as a dedicated local minimizer. In both cases the default option Repeatability=ON is used to produce repeatable solutions.
Note: for users of multi-threaded implementations of the NAG Library the following example program does not include the setting of the optional parameter SMP Callback Thread Safe, and as such if run on multiple threads it will issue an error message. See the additional example program provided for E05SAF for more information on how to safely access independent subsections of the provided IUSER and RUSER arrays from multiple threads and how to use E05ZKF to set additional SMP threading related options.

10.1 Program Text

Program Text (e05sbfe.f90)

10.2 Program Data

None.

10.3 Program Results

Program Results (e05sbfe.r)

11 Algorithmic Details

The following pseudo-code describes the algorithm used with the repulsion mechanism.
INITIALIZE for ​ j=1, ​ np xj = R ∈ U ℓbox,ubox x^ j = R ∈ U ℓbox,ubox Start=COLD x^ j 0 Start=WARM vj = R ∈ U -V max ,Vmax f^j = F x^ j Start=COLD f^ j 0 Start=WARM e^ j = e x^ j Start=COLD e^ j 0 Start=WARM wj = Wmax Weight Initialize=MAXIMUM Wini Weight Initialize=INITIAL R ∈ U W min , W max Weight Initialize=RANDOMIZED end for x~ = 12 ℓbox + ubox f~ = F x~ e~ = e x~ Ic = Is = 0 SWARM while (not finalized), Ic = Ic + 1 for ​ j = 1 , np xj = BOUNDARY xj,ℓbox,ubox fj = F xj ej = e xj if ​ fj / fscale + ϕ wj ej < f^j / fscale + ϕ wj e^j f^j = fj , ​ x^ j = xj if ​ e j < e~ ​ or ​ e j ≈ e~ ​ and ​ fj < f~ f~ = fj , ​ x~ = xj end for if ​ new f~ LOCMIN x~,f~,e~,Oi , ​ Is=0 [see note on repulsion below for code insertion] else Is = Is + 1 for ​ j = 1 , np vj = wj vj + Cs D 1 x^j - xj + Cg D 2 x~ - xj xj = xj + vj if ​ xj - x~ < dtol reset ​ xj, ​ vj, ​ wj; ​ x^j = xj else update ​wj end for if (target achieved or termination criterion satisfied) finalized=true MONMOD xj end LOCMIN x~,f~,e~,Oe
The definition of terms used in the above pseudo-code are as follows.
np | the number of particles, NPAR
ℓbox | array of NDIM lower box bounds
ubox | array of NDIM upper box bounds
xj | position of particle j
x^j | best position found by particle j
x~ | best position found by any particle
fj | F xj
f^j | F x^j, best value found by particle j
f~ | F x~, best value found by any particle
ek x | kth (scaled) constraint violation at x, evaluated as min ck x-l NDIM+k,0.0+max ck x-u NDIM+k,0.0; this may be scaled by the maximum kth constraint found thus far
e x | the array of NCON constraint violations, ek x, for k=1,2,…,NCON, at a point x
ej | e xj, the array of constraint violations evaluated at xj
e^j | e x^j, the array of constraint violations evaluated at x^j
e~ | e x~, the array of constraint violations evaluated at x~
vj | velocity of particle j
wj | weight on vj for velocity update, decreasing according to Weight Decrease
Vmax | maximum absolute velocity, dependent upon Maximum Variable Velocity
Ic | swarm iteration counter
Is | iterations since x~ was updated
fscale | objective function scaling defined by the options Constraint Scaling, Objective Scaling and Objective Scale.
D 1,D 2 | diagonal matrices with random elements in range 0,1
Cs | the cognitive advance coefficient which weights velocity towards x^j, adjusted using Advance Cognitive
Cg | the global advance coefficient which weights velocity towards x~, adjusted using Advance Global
dtol | the Distance Tolerance for resetting a converged particle
R∈U ℓbox,ubox | an array of random numbers whose ith element is drawn from a uniform distribution in the range ℓbox i,ubox i, for i=1,2,…,NDIM
Oi | local optimizer interior options
Oe | local optimizer exterior options
ϕ wj | a function of wj designed to increasingly weight towards minimizing constraint violations as wj decreases
LOCMIN x,f,e,O | apply local optimizer using the set of options O using the solution x,f,e as the starting point, if used (not default)
MONMOD | monitor progress and possibly modify xj
BOUNDARY | apply required behaviour for xj outside bounding box, (see Boundary)
new (f~) | true if x~, c~, f~ were updated at this iteration
Additionally a repulsion phase can be introduced by changing from the default values of options Repulsion Finalize (rf), Repulsion Initialize (ri) and Repulsion Particles (rp). If the number of static particles is denoted ns then the following can be inserted after the new(f~) check in the pseudo-code above.
else ​ if ​ ( ns ≥ rp ​ and ​ ri ≤ Is ≤ ri + rf ) LOCMIN x~,f~,e~,Oi use ​ -C g ​ instead of ​ Cg ​ in velocity updates if ​ Is = ri + rf Is = 0

12 Optional Parameters

This section can be skipped if you wish to use the default values for all optional parameters, otherwise, the following is a list of the optional parameters available and a full description of each optional parameter is provided in Section 12.1.
  • Advance Cognitive
  • Advance Global
  • Boundary
  • Constraint Norm
  • Constraint Scale Maximum
  • Constraint Scaling
  • Constraint Superiority
  • Constraint Tolerance
  • Constraint Warning
  • Distance Scaling
  • Distance Tolerance
  • Function Precision
  • Local Boundary Restriction
  • Local Exterior Iterations
  • Local Exterior Major Iterations
  • Local Exterior Minor Iterations
  • Local Exterior Tolerance
  • Local Interior Iterations
  • Local Interior Major Iterations
  • Local Interior Minor Iterations
  • Local Interior Tolerance
  • Local Minimizer
  • Maximum Function Evaluations
  • Maximum Iterations Completed
  • Maximum Iterations Static
  • Maximum Iterations Static Particles
  • Maximum Particles Converged
  • Maximum Particles Reset
  • Maximum Variable Velocity
  • Objective Scale
  • Objective Scaling
  • Optimize
  • Repeatability
  • Repulsion Finalize
  • Repulsion Initialize
  • Repulsion Particles
  • SMP Callback Thread Safe
  • SMP Local Minimizer External
  • SMP Monitor
  • SMP Monmod
  • SMP Subswarm
  • SMP Thread Overrun
  • Start
  • Swarm Standard Deviation
  • Target Objective
  • Target Objective Safeguard
  • Target Objective Tolerance
  • Target Objective Value
  • Target Warning
  • Verify Gradients
  • Weight Decrease
  • Weight Initial
  • Weight Initialize
  • Weight Maximum
  • Weight Minimum
  • Weight Reset
  • Weight Value

12.1 Description of the Optional Parameters

For each option, we give a summary line, a description of the optional parameter and details of constraints.
The summary line contains:
  • the keywords;
  • a parameter value, where the letters a, i and r denote options that take character, integer and real values respectively;
  • the default value, where the symbol ε is a generic notation for machine precision (see X02AJF), and Imax represents the largest representable integer value (see X02BBF).
All options accept the value ‘DEFAULT’ in order to return single options to their default states.
Keywords and character values are case insensitive, however they must be separated by at least one space.
For E05SBF the maximum length of the argument CVALUE used by E05ZLF is 15.
Advance Cognitive r Default=2.0
The cognitive advance coefficient, Cs. When larger than the global advance coefficient, this will cause particles to be attracted toward their previous best positions. Setting r=0.0 will cause E05SBF to act predominantly as a local optimizer. Setting r>2.0 may cause the swarm to diverge, and is generally inadvisable. At least one of the global and cognitive coefficients must be nonzero.
Advance Global r Default=2.0
The global advance coefficient, Cg. When larger than the cognitive coefficient this will encourage convergence toward the best solution yet found. Values r∈0,1 will inhibit particles overshooting the optimum. Values r∈1,2 cause particles to fly over the optimum some of the time. Larger values can prohibit convergence. Setting r=0.0 will remove any attraction to the current optimum, effectively generating a Monte–Carlo multi-start optimization algorithm. At least one of the global and cognitive coefficients must be nonzero.
Boundary a Default=FLOATING
Determines the behaviour if particles leave the domain described by the box bounds. This only affects the general PSO algorithm, and will not pass down to any NAG local minimizers chosen.
This option is only effective in those dimensions for which BL i≠BU i, i=1,2,…,NDIM.
IGNORE
The box bounds are ignored. The objective function is still evaluated at the new particle position.
RESET
The particle is re-initialized inside the domain. x^j, f^j and e^j are not affected.
FLOATING
The particle position remains the same, however the objective function will not be evaluated at the next iteration. The particle will probably be advected back into the domain at the next advance due to attraction by the cognitive and global memory.
HYPERSPHERICAL
The box bounds are wrapped around an ndim-dimensional hypersphere. As such a particle leaving through a lower bound will immediately re-enter through the corresponding upper bound and vice versa. The standard distance between particles is also modified accordingly.
FIXED
The particle rests on the boundary, with the corresponding dimensional velocity set to 0.0.
Constraint Norm a Default=L1
Determines with respect to which norm the constraint residuals should be constructed. These are automatically scaled with respect to NCON as stated. For the set of (scaled) violations e, these may be,
L1
The L 1 norm will be used, e 1=1 NCON∑1 NCON ek
L2
The L 2 norm will be used, e 2=1 NCON∑1 NCON ek 2
L2SQ
The square of the L 2 norm will be used, e 22=1 NCON∑1 NCON ek 2
LMAX
The L∞ norm will be used, e∞=max 0<k≤NCON ek
Constraint Scale Maximum r Default=1.0E6
Internally, each constraint violation is scaled with respect to the maximum violation yet achieved for that constraint. This option acts as a ceiling for this scale.
Constraint: r>1.0.
Constraint Scaling a Default=INITIAL
Determines whether to scale the constraints and objective function when constructing the penalty function.
OFF
Neither the constraint violations nor the objective will be scaled automatically. This should only be used if the constraints and objective are similarly scaled everywhere throughout the domain.
INITIAL
The maximum of the initial cognitive memories, f^j and e^j, will be used to scale the objective function and constraint violations respectively.
ADAPTIVE
Initially, the maximum of the initial cognitive memories, f^j and e^j, will be used to scale the objective function and constraint violations respectively. If a significant change is detected in the behaviour of the constraints or the objective, these will be rescaled with respect to the current state of the cognitive memory.
Constraint Superiority r Default=0.01
The minimum scaled improvement in the constraint violation for a location to be immediately superior to that in memory, regardless of the objective value.
Constraint: r>0.0.
Constraint Tolerance r Default=10-4
The maximum scaled violation of the constraints for which a sample particle is considered comparable to the current global optimum. Should this not be exceeded, then the current global optimum will be updated if the value of the objective function of the sample particle is superior.
Constraint Warning a Default=ON
Activates or deactivates the error exit associated with the inability to completely satisfy all constraints, IFAIL=4. It is advisable to deactivate this option if IFAIL=0 on entry and the satisfaction of all constraints is not program critical.
OFF
No error will be returned.
ON
An error will be returned if any constraints are sufficiently violated at the end of the simulation.
Distance Scaling a Default=ON
Determines whether distances should be scaled by box widths.
ON
When a distance is calculated between x and y, a scaled L 2 norm is used.
L 2 x,y = ∑ i | ui ≠ ℓi , i≤ndim xi - yi ui - ℓi 2 1 2 .
OFF
Distances are calculated as the standard L 2 norm without any rescaling.
L 2 x,y = ∑ i=1 ndim xi - yi 2 1 2 .
Distance Tolerance r Default=10-4
This is the distance, dtol between particles and the global optimum which must be reached for the particle to be considered converged, i.e., that any subsequent movement of such a particle cannot significantly alter the global optimum. Once achieved the particle is reset into the box bounds to continue searching.
Constraint: r>0.0.
Function Precision r Default=ε 0.9
The parameter defines εr, which is intended to be a measure of the accuracy with which the problem function F x can be computed. If r<ε or r≥1, the default value is used.
The value of εr should reflect the relative precision of 1+F x; i.e., εr acts as a relative precision when F is large, and as an absolute precision when F is small. For example, if F x is typically of order 1000 and the first six significant digits are known to be correct, an appropriate value for εr would be 10-6. In contrast, if F x is typically of order 10-4 and the first six significant digits are known to be correct, an appropriate value for εr would be 10-10. The choice of εr can be quite complicated for badly scaled problems; see Chapter 8 of Gill et al. (1981) for a discussion of scaling techniques. The default value is appropriate for most simple functions that are computed with full accuracy. However when the accuracy of the computed function values is known to be significantly worse than full precision, the value of εr should be large enough so that no attempt will be made to distinguish between function values that differ by less than the error inherent in the calculation.
Local Boundary Restriction r Default=0.5
Contracts the box boundaries used by a box constrained local minimizer to, βl,βu, containing the start point x, where
∂i = r × ui - ℓi βli = max ℓi, xi - ∂i 2 βui = min ui, xi + ∂i 2 ,  i=1,…,NDIM .
Smaller values of r thereby restrict the size of the domain exposed to the local minimizer, possibly reducing the amount of work done by the local minimizer.
Constraint: 0.0≤r≤1.0.
Local Interior Iterations i 1
Local Interior Major Iterations i 1
Local Exterior Iterations i 2
Local Exterior Major Iterations i 2
The maximum number of iterations or function evaluations the chosen local minimizer will perform inside (outside) the main loop if applicable. For the NAG minimizers these correspond to:
Minimizer | Parameter/option | Default Interior | Default Exterior
E04CBF | MAXCAL | NDIM+10 | 2×NDIM+15
E04DGF/E04DGA | Iteration Limit | max 30,3×NDIM | max 50,5×NDIM
E04UCF/E04UCA | Major Iteration Limit | max 10,2×NDIM | max 30,3×NDIM
Unless set, these are functions of the parameters passed to E05SBF.
Setting i=0 will disable the local minimizer in the corresponding algorithmic region. For example, setting Local Interior Iterations=0 and Local Exterior Iterations=30 will cause the algorithm to perform no local minimizations inside the main loop of the algorithm, and a local minimization with upto 30 iterations after the main loop has been exited.
Note: currently E04JYF or E04KZF are restricted to using 400×NDIM and 50×NDIM as function evaluation limits respectively. This applies to both local minimizations inside and outside the main loop. They may still be deactivated in either phase by setting i=0, and may subsequently be reactivated in either phase by setting i>0.
Constraint: i 1≥0, i 2≥0.
Local Interior Tolerance r 1 Default=10-4
Local Exterior Tolerance r 2 Default=10-4
This is the tolerance provided to a local minimizer in the interior (exterior) of the main loop of the algorithm.
Constraint: r 1>0.0, r 2>0.0.
Local Interior Minor Iterations i 1
Local Exterior Minor Iterations i 2
Where applicable, the secondary number of iterations the chosen local minimizer will use inside (outside) the main loop. Currently the relevant default values are:
Minimizer | Parameter/option | Default Interior | Default Exterior
E04UCF/E04UCA | Minor Iteration Limit | max 10,2×NDIM | max 30,3×NDIM
Constraint: i 1≥0, i 2≥0.
Local Minimizer a Default=OFF
Allows for a choice of Chapter E04 routines to be used as a coupled, dedicated local minimizer.
OFF
No local minimization will be performed in either the INTERIOR or EXTERIOR sections of the algorithm.
E04CBF
Use E04CBF as the local minimizer. This does not require the calculation of derivatives.
On a call to OBJFUN during a local minimization, MODE=5.
E04KZF
Use E04KZF as the local minimizer. This requires the calculation of derivatives in OBJFUN, as indicated by MODE.
The box bounds forwarded to this routine from E05SBF will have been acted upon by Local Boundary Restriction. As such, the domain exposed may be greatly smaller than that provided to E05SBF.
Accurate derivatives must be provided to this routine, and will not be approximated internally. Each iteration of this local minimizer also requires the calculation of both the objective function and its derivative. Hence on a call to OBJFUN during a local minimization, MODE=7.
E04JYF
Use E04JYF as the local minimizer. This does not require the calculation of derivatives.
On a call to OBJFUN during a local minimization, MODE=5.
The box bounds forwarded to this routine from E05SBF will have been acted upon by Local Boundary Restriction. As such, the domain exposed may be greatly smaller than that provided to E05SBF.
E04DGF
E04DGA
Use E04DGA as the local minimizer.
Accurate derivatives must be provided, and will not be approximated internally. Additionally, each call to OBJFUN during a local minimization will require either the objective to be evaluated alone, or both the objective and its gradient to be evaluated. Hence on a call to OBJFUN, MODE=5 or 7.
E04UCF
E04UCA
Use E04UCA as the local minimizer. This operates such that any derivatives of either the objective function or the constraint Jacobian, which you cannot supply, will be approximated internally using finite differences.
Either, the objective, objective gradient, or both may be requested during a local minimization, and as such on a call to OBJFUN, MODE=1, 2 or 5.
The box bounds forwarded to this routine from E05SBF will have been acted upon by Local Boundary Restriction. As such, the domain exposed may be greatly smaller than that provided to E05SBF.
Maximum Function Evaluations i Default =Imax
The maximum number of evaluations of the objective function. When reached this will return IFAIL=1 and INFORM=6.
Constraint: i>0.
Maximum Iterations Completed i Default=1000×NDIM
The maximum number of complete iterations that may be performed. Once exceeded E05SBF will exit with IFAIL=1 and INFORM=5.
Unless set, this adapts to the parameters passed to E05SBF.
Constraint: i≥1.
Maximum Iterations Static i Default=100
The maximum number of iterations without any improvement to the current global optimum. If exceeded E05SBF will exit with IFAIL=1 and INFORM=4. This exit will be hindered by setting Maximum Iterations Static Particles to larger values.
Constraint: i≥1.
Maximum Iterations Static Particles i Default=0
The minimum number of particles that must have converged to the current optimum before the routine may exit due to Maximum Iterations Static with IFAIL=1 and INFORM=4.
Constraint: i≥0.
Maximum Particles Converged i Default =Imax
The maximum number of particles that may converge to the current optimum. When achieved, E05SBF will exit with IFAIL=1 and INFORM=3. This exit will be hindered by setting ‘Repulsion’ options, as these cause the swarm to re-expand.
Constraint: i>0.
Maximum Particles Reset i Default =Imax
The maximum number of particles that may be reset after converging to the current optimum. Once achieved no further particles will be reset, and any particles within Distance Tolerance of the global optimum will continue to evolve as normal.
Constraint: i>0.
Maximum Variable Velocity r Default=0.25
Along any dimension j, the absolute velocity is bounded above by vj≤r×uj-ℓj=Vmax. Very low values will greatly increase convergence time. There is no upper limit, although larger values will allow more particles to be advected out of the box bounds, and values greater than 4.0 may cause significant and potentially unrecoverable swarm divergence.
Constraint: r>0.0.
Objective Scale r Default=1.0
The initial scale for the objective function. This will remain fixed if Objective Scaling=USER is selected.
Objective Scaling a Default=MAXIMUM
The method of (re)scaling applied to the objective function when the routine detects a significant difference between the scale and the global and cognitive memory (f~ and f^j). This only has an effect when NCON>0 and Constraint Scaling is active.
MAXIMUM
The objective is rescaled with respect to the maximum absolute value of the objective in the cognitive and global memory.
MEAN
The objective is rescaled with respect to the mean absolute value of the objective in the cognitive and global memory.
USER
The scale remains fixed at the value set using Objective Scale.
Optimize a Default=MINIMIZE
Determines whether to maximize or minimize the objective function, or ignore the objective and search for a constrained point.
MINIMIZE
The objective function will be minimized.
MAXIMIZE
The objective function will be maximized. This is accomplished by minimizing the negative of the objective.
CONSTRAINTS
The objective function will be ignored, and the algorithm will attempt to find a feasible point given the provided constraints. The objective function will be evaluated at the best point found with regards to constraint violations, and the final positions returned in XBEST. The objective will be calculated at the best point found in terms of constraints only. Should a constrained point be found, E05SBF will exit with IFAIL=0 and INFORM=6.
Constraint: if Optimize=CONSTRAINTS, NCON>0 is required.
Repeatability a Default=OFF
Allows for the same random number generator seed to be used for every call to E05SBF. Repeatability=OFF is recommended in general.
OFF
The internal generation of random numbers will be nonrepeatable.
ON
The same seed will be used.
Repulsion Finalize i Default =Imax
The number of iterations performed in a repulsive phase before re-contraction. This allows a re-diversified swarm to contract back toward the current optimum, allowing for a finer search of the near optimum space.
Constraint: i≥2.
Repulsion Initialize i Default =Imax
The number of iterations without any improvement to the global optimum before the algorithm begins a repulsive phase. This phase allows the particle swarm to re-expand away from the current optimum, allowing more of the domain to be investigated. The repulsive phase is automatically ended if a superior optimum is found.
Constraint: i≥2.
Repulsion Particles i Default=0
The number of particles required to have converged to the current optimum before any repulsive phase may be initialized. This will prevent repulsion before a satisfactory search of the near optimum area has been performed, which may happen for large dimensional problems.
Constraint: i≥0.
Start a Default=COLD
Used to affect the initialization of the routine.
COLD
The random number generators and all initialization data will be generated internally. The variables XBEST, FBEST and CBEST need not be set.
WARM
You must supply the initial best location, function and constraint violation values XBEST, FBEST and CBEST. This option is recommended if you already have a data set you wish to improve upon.
Swarm Standard Deviation r Default=0.1
The target standard deviation of the particle distances from the current optimum. Once the standard deviation is below this level, E05SBF will exit with IFAIL=1 and INFORM=2. This criterion will be penalized by the use of ‘Repulsion’ options, as these cause the swarm to re-expand, increasing the standard deviation of the particle distances from the best point.
In SMP parallel implementations of E05SBF, the standard deviation will be calculated based only on the particles local to the particular thread that checks for finalization. Considerably fewer particles may be used in this calculation than when the algorithm is run in serial. It is therefore recommended that you provide a smaller value of Swarm Standard Deviation when running in parallel than when running in serial.
Constraint: r≥0.0.
Target Objective a Default=OFF
Target Objective Value r Default=0.0
Activate or deactivate the use of a target value as a finalization criterion. If active, then once the supplied target value for the objective function is found (beyond the first iteration if Target Warning is active) E05SBF will exit with IFAIL=0 and INFORM=1. Other than checking for feasibility only (Optimize=CONSTRAINTS), this is the only finalization criterion that guarantees that the algorithm has been successful. If the target value was achieved at the initialization phase or first iteration and Target Warning is active, E05SBF will exit with IFAIL=2. This option may take any real value r, or the character ON/OFF as well as DEFAULT. If this option is queried using E05ZLF, the current value of r will be returned in RVALUE, and CVALUE will indicate whether this option is ON or OFF. The behaviour of the option is as follows:
r
Once a point is found with an objective value within the Target Objective Tolerance of r, E05SBF will exit successfully with IFAIL=0 and INFORM=1.
OFF
The current value of r will remain stored, however it will not be used as a finalization criterion.
ON
The current value of r stored will be used as a finalization criterion.
DEFAULT
The stored value of r will be reset to its default value (0.0), and this finalization criterion will be deactivated.
Target Objective Safeguard r Default=10.0 ε
If you have given a target objective value to reach in objval (the value of the optional parameter Target Objective Value), objsfg sets your desired safeguarded termination tolerance, for when objval is close to zero.
Constraint: objsfg≥2 ε.
Target Objective Tolerance r Default=0.0
The optional tolerance to a user-specified target value.
Constraint: r≥0.0.
Target Warning a Default=OFF
Activates or deactivates the error exit associated with the target value being achieved before entry into the main loop of the algorithm, IFAIL=2.
OFF
No error will be returned, and the routine will exit normally.
ON
An error will be returned if the target objective is reached prematurely, and the routine will exit with IFAIL=2.
Verify Gradients a Default=ON
Adjusts the level of gradient checking performed when gradients are required. Gradient checks are only performed on the first call to the chosen local minimizer if it requires gradients. There is no guarantee that the gradient check will be correct, as the finite differences used in the gradient check are themselves subject to inaccuracies.
OFF
No gradient checking will be performed.
ON
A cheap gradient check will be performed on both the gradients corresponding to the objective through OBJFUN and those provided via the constraint Jacobian through CONFUN.
OBJECTIVE
A more expensive gradient check will be performed on the gradients corresponding to the objective OBJFUN. The gradients of the constraints will not be checked.
CONSTRAINTS
A more expensive check will be performed on the elements of CJAC provided via CONFUN. The objective gradient will not be checked.
FULL
A more expensive check will be performed on both the gradient of the objective and the constraint Jacobian.
Weight Decrease a Default=INTEREST
Determines how particle weights decrease.
OFF
Weights do not decrease.
INTEREST
Weights decrease through compound interest as w IT+1=wIT 1-Wval, where Wval is the Weight Value and IT is the current number of iterations.
LINEAR
Weights decrease linearly following w IT+1=wIT-IT×Wmax-Wmin/ITmax, where IT is the iteration number and ITmax is the maximum number of iterations as set by Maximum Iterations Completed.
Weight Initial r Default=Wmax
The initial value of any particle's inertial weight, Wini, or the minimum possible initial value if initial weights are randomized. When set, this will override Weight Initialize=RANDOMIZED or MAXIMUM, and as such these must be set afterwards if so desired.
Constraint: Wmin≤r≤Wmax.
Weight Initialize a Default=MAXIMUM
Determines how the initial weights are distributed.
INITIAL
All weights are initialized at the initial weight, Wini, if set. If Weight Initial has not been set, this will be the maximum weight, Wmax.
MAXIMUM
All weights are initialized at the maximum weight, Wmax.
RANDOMIZED
Weights are uniformly distributed in Wmin,Wmax or Wini,Wmax if Weight Initial has been set.
Weight Maximum r Default=1.0
The maximum particle weight, Wmax.
Constraint: 1.0≥r≥Wmin (If Wini has been set then 1.0≥r≥Wini.)
Weight Minimum r Default=0.1
The minimum achievable weight of any particle, Wmin. Once achieved, no further weight reduction is possible.
Constraint: 0.0≤r≤Wmax (If Wini has been set then 0.0≤r≤Wini.)
Weight Reset a Default=MAXIMUM
Determines how particle weights are re-initialized.
INITIAL
Weights are re-initialized at the initial weight if set. If Weight Initial has not been set, this will be the maximum weight.
MAXIMUM
Weights are re-initialized at the maximum weight.
RANDOMIZED
Weights are uniformly distributed in Wmin,Wmax or Wini,Wmax if Weight Initial has been set.
Weight Value r Default=0.01
The constant Wval used with Weight Decrease=INTEREST.
Constraint: 0.0≤r≤13.

12.2 Description of the SMP optional parameters

This section details additional options available to users of multi-threaded implementations of the NAG Library. In particular it includes the option SMP Callback Thread Safe, which must be set before calling E05SBF with multiple threads.
SMP Callback Thread Safe a Default=WARNING
Declare that the callback routines you provide are or are not thread safe. In particular, this indicates that access to the shared memory arrays IUSER and RUSER from within your provided callbacks is done in a thread safe manner. If these arrays are just used to pass constant data, then you may assume they are thread safe. If these are also used for workspace, or passing variable data such as random number generator seeds, then you must ensure these are accessed and updated safely. Whilst this can be done using OpenMP critical sections, we suggest their use is minimized to prevent unnecessary bottlenecks, and that instead individual threads have access to independent subsections of the provided arrays where possible.
YES
The callback routines have been programmed in a thread safe way. The algorithm will use OMP_NUM_THREADS threads.
NO
The callback routines are not thread safe. Setting this option will force the algorithm to run on a single thread only, and is advisable only for debugging purposes, or if you wish to parallelize your callback functions.
WARNING
This will cause an immediate exit from E05SBF with IFAIL=51 if multiple threads are detected. This is to inform you that you have not declared the callback functions either to be thread safe, or that they are thread unsafe and you wish the algorithm to run in serial.
SMP Local Minimizer External a Default=ALL
Determines how many threads will attempt to locally minimize the best found solution after the routine has exited the main loop.
MASTER
Only the master thread will attempt to find any improvement. The local minimization will be launched from the best known solution. All other threads will remain effectively idle.
ALL
The master thread will perform a local minimization from the best known solution, while all other threads will perform a local minimization from randomly generated perturbations of the best known solution, increasing the chance of an improvement. Assuming all local minimizations will take approximately the same amount of computation, this will be effectively free in terms of real time. It will however increase the number of function evaluations performed.
SMP Monitor a Default=SINGLE
SMP Monmod a
Determines whether the user-supplied function MONMOD is invoked once every sub-iteration each thread performs, or only once by a single thread after all threads have completed at least one sub-iteration.
SINGLE
Only one thread will invoke MONMOD, after all threads have performed at least one sub-iteration.
ALL
Each thread will invoke MONMOD each time it completes a sub-iteration. If you wish to alter X using MONMOD you should use this option, as MONMOD will only receive the arrays X, XBEST, FBEST and CBEST private to the calling thread.
SMP Subswarm i Default=1
Determines how many threads support a particle subswarm. This is an extra collection of particles constrained to search only within a hypercube of edge length 10.0×Distance Tolerance of the best point known to an individual thread. This may improve the number of iterations required to find a provided target, particularly if no local minimizer is in use.
If i≤0, then this will be disabled on all the threads.
If i≥OMP_NUM_THREADS, then all the threads will support a particle subswarm.
SMP Thread Overrun i Default=Imax
This option provides control over the level of asynchronicity present in a simulation. In particular, a barrier synchronization between all threads is performed if any thread completes i sub-iterations more than the slowest thread, causing all threads to be exposed to the current best solution. Allowing asynchronous behaviour does however allow individual threads to focus on different global optimum candidates some of the time, which can inhibit convergence to unwanted sub-optima. It also allows for threads to continue searching when other threads are completing sub-iterations at a slower rate.
If i<1, then the algorithm will force a synchronization between threads at the end of each iteration.
E05 Chapter Contents
E05 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


E05UCF : NAG Library, Mark 26

E05 Chapter Contents
E05 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

E05UCF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
▸▿ 9 Further Comments
9.1 Description of the Printed Output
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results
11 Algorithmic Details
▸▿ 12 Optional Parameters
12.1 Description of the Optional Parameters
13 Description of Monitoring Information

1 Purpose

E05UCF is designed to find the global minimum of an arbitrary smooth function subject to constraints (which may include simple bounds on the variables, linear constraints and smooth nonlinear constraints) by generating a number of different starting points and performing a local search from each using sequential quadratic programming.

2 Specification

SUBROUTINE E05UCF ( N, NCLIN, NCNLN, A, LDA, BL, BU, CONFUN, OBJFUN, NPTS, X, LDX, START, REPEAT, NB, OBJF, OBJGRD, LDOBJD, ITER, C, LDC, CJAC, LDCJAC, SDCJAC, R, LDR, SDR, CLAMDA, LDCLDA, ISTATE, LISTAT, IOPTS, OPTS, IUSER, RUSER, INFO, IFAIL)
INTEGER | N, NCLIN, NCNLN, LDA, NPTS, LDX, NB, LDOBJD, ITER(NB), LDC, LDCJAC, SDCJAC, LDR, SDR, LDCLDA, ISTATE(LISTAT,NB), LISTAT, IOPTS(740), IUSER(*), INFO(NB), IFAIL
REAL (KIND=nag_wp) | A(LDA,*), BL(N+NCLIN+NCNLN), BU(N+NCLIN+NCNLN), X(LDX,NB), OBJF(NB), OBJGRD(LDOBJD,NB), C(LDC,NB), CJAC(LDCJAC,SDCJAC,NB), R(LDR,SDR,NB), CLAMDA(LDCLDA,NB), OPTS(485), RUSER(*)
LOGICAL | REPEAT
EXTERNAL | CONFUN, OBJFUN, START
Before calling E05UCF, the optional parameter arrays IOPTS and OPTS must be initialized for use with E05UCF by calling E05ZKF with OPTSTR set to ‘Initialize = e05ucf’. Optional parameters may be specified by calling E05ZKF before the call to E05UCF.

3 Description

The problem is assumed to be stated in the following form:
minimize x∈Rn ​ ​ F x  subject to  l≤ x AL x c x ≤u, (1)
where F x (the objective function) is a nonlinear function, AL is an nL by n linear constraint matrix, and c x is an nN element vector of nonlinear constraint functions. (The matrix AL and the vector c x may be empty.) The objective function and the constraint functions are assumed to be smooth, i.e., at least twice-continuously differentiable. (This routine will usually solve (1) if there are only isolated discontinuities away from the solution.)
E05UCF solves a user-specified number of local optimization problems with different starting points. You may specify the starting points via the subroutine START. If a random number generator is used to generate the starting points then the argument REPEAT allows you to specify whether a repeatable set of points are generated or whether different starting points are generated on different calls. The resulting local minima are ordered and the best NB results returned in order of ascending values of the resulting objective function values at the minima. Thus the value returned in position 1 will be the best result obtained. If a sufficient number of different points are chosen then this is likely to be be the global minimum. Please note that the default version of START uses a random number generator to generate the starting points.

4 References

Dennis J E Jr and Moré J J (1977) Quasi-Newton methods, motivation and theory SIAM Rev. 19 46–89
Dennis J E Jr and Schnabel R B (1981) A new derivation of symmetric positive-definite secant updates nonlinear programming (eds O L Mangasarian, R R Meyer and S M Robinson) 4 167–199 Academic Press
Dennis J E Jr and Schnabel R B (1983) Numerical Methods for Unconstrained Optimization and Nonlinear Equations Prentice–Hall
Fletcher R (1987) Practical Methods of Optimization (2nd Edition) Wiley
Gill P E, Hammarling S, Murray W, Saunders M A and Wright M H (1986) Users' guide for LSSOL (Version 1.0) Report SOL 86-1 Department of Operations Research, Stanford University
Gill P E, Murray W, Saunders M A and Wright M H (1984) Users' guide for SOL/QPSOL version 3.2 Report SOL 84–5 Department of Operations Research, Stanford University
Gill P E, Murray W, Saunders M A and Wright M H (1986a) Some theoretical properties of an augmented Lagrangian merit function Report SOL 86–6R Department of Operations Research, Stanford University
Gill P E, Murray W, Saunders M A and Wright M H (1986b) Users' guide for NPSOL (Version 4.0): a Fortran package for nonlinear programming Report SOL 86-2 Department of Operations Research, Stanford University
Gill P E, Murray W and Wright M H (1981) Practical Optimization Academic Press
Powell M J D (1974) Introduction to constrained optimization Numerical Methods for Constrained Optimization (eds P E Gill and W Murray) 1–28 Academic Press
Powell M J D (1983) Variable metric methods in constrained optimization Mathematical Programming: the State of the Art (eds A Bachem, M Grötschel and B Korte) 288–311 Springer–Verlag

5 Arguments

1:   N – INTEGERInput
On entry: n, the number of variables.
Constraint: N>0.
2:   NCLIN – INTEGERInput
On entry: nL, the number of general linear constraints.
Constraint: NCLIN≥0.
3:   NCNLN – INTEGERInput
On entry: nN, the number of nonlinear constraints.
Constraint: NCNLN≥0.
4:   A LDA* – REAL (KIND=nag_wp) arrayInput
Note: the second dimension of the array A must be at least N if NCLIN>0, and at least 1 otherwise.
On entry: the matrix AL of general linear constraints in (1). That is, the ith row contains the coefficients of the ith general linear constraint, for i=1,2,…,NCLIN.
If NCLIN=0, the array A is not referenced.
5:   LDA – INTEGERInput
On entry: the first dimension of the array A as declared in the (sub)program from which E05UCF is called.
Constraint: LDA≥NCLIN.
6:   BL N+NCLIN+NCNLN – REAL (KIND=nag_wp) arrayInput
7:   BU N+NCLIN+NCNLN – REAL (KIND=nag_wp) arrayInput
On entry: BL must contain the lower bounds and BU the upper bounds for all the constraints in the following order. The first n elements of each array must contain the bounds on the variables, the next nL elements the bounds for the general linear constraints (if any) and the next nN elements the bounds for the general nonlinear constraints (if any). To specify a nonexistent lower bound (i.e., lj=-∞), set BL j≤-bigbnd, and to specify a nonexistent upper bound (i.e., uj=+∞), set BU j≥bigbnd; the default value of bigbnd is 1020, but this may be changed by the optional parameter Infinite Bound Size. To specify the jth constraint as an equality, set BL j=BU j=β, say, where β<bigbnd.
Constraints:
  • BL j≤BU j, for j=1,2,…,N+NCLIN+NCNLN;
  • if BL j=BU j=β, β<bigbnd.
8:   CONFUN – SUBROUTINE, supplied by the NAG Library or the user.External Procedure
CONFUN must calculate the vector c x of nonlinear constraint functions and (optionally) its Jacobian (= ∂c ∂x ) for a specified n-element vector x. If there are no nonlinear constraints (i.e., NCNLN=0), CONFUN will never be called by E05UCF and CONFUN may be the dummy routine E04UDM. (E04UDM is included in the NAG Library.) If there are nonlinear constraints, the first call to CONFUN will occur before the first call to OBJFUN.
The specification of CONFUN is:
SUBROUTINE CONFUN ( MODE, NCNLN, N, LDCJSL, NEEDC, X, C, CJSL, NSTATE, IUSER, RUSER)
INTEGER | MODE, NCNLN, N, LDCJSL, NEEDC(NCNLN), NSTATE, IUSER(*)
REAL (KIND=nag_wp) | X(N), C(NCNLN), CJSL(LDCJSL,N), RUSER(*)
1:   MODE – INTEGERInput/Output
On entry: indicates which values must be assigned during each call of CONFUN. Only the following values need be assigned, for each value of i such that NEEDC i>0:
MODE=0
C i.
MODE=1
All available elements in the ith row of CJSL.
MODE=2
C i and all available elements in the ith row of CJSL.
On exit: may be set to a negative value if you wish to abandon the solution to the current local minimization problem. In this case E05UCF will move to the next local minimization problem.
2:   NCNLN – INTEGERInput
On entry: nN, the number of nonlinear constraints.
3:   N – INTEGERInput
On entry: n, the number of variables.
4:   LDCJSL – INTEGERInput
On entry: LDCJSL is the same value as LDCJAC in the call to E05UCF.
5:   NEEDC NCNLN – INTEGER arrayInput
On entry: the indices of the elements of C and/or CJSL that must be evaluated by CONFUN. If NEEDC i>0, C i and/or the available elements of the ith row of CJSL (see argument MODE) must be evaluated at x.
6:   X N – REAL (KIND=nag_wp) arrayInput
On entry: x, the vector of variables at which the constraint functions and/or the available elements of the constraint Jacobian are to be evaluated.
7:   C NCNLN – REAL (KIND=nag_wp) arrayOutput
On exit: if NEEDC k>0 and MODE=0 or 2, C k must contain the value of ck x. The remaining elements of C, corresponding to the non-positive elements of NEEDC, need not be set.
8:   CJSL LDCJSLN – REAL (KIND=nag_wp) arrayInput/Output
CJSL may be regarded as a two-dimensional ‘slice’ of the three-dimensional array CJAC of E05UCF.
On entry: unless Derivative Level=2 or 3 (the default setting is Derivative Level=3, the elements of CJSL are set to special values which enable E05UCF to detect whether they are changed by CONFUN.
On exit: if NEEDC k>0 and MODE=1 or 2, the kth row of CJSL must contain the available elements of the vector ∇ck given by
∇ck= ∂ck ∂x 1 , ∂ck ∂x 2 ,…, ∂ck ∂xn T,
where ∂ck ∂xj is the partial derivative of the kth constraint with respect to the jth variable, evaluated at the point x. See also the argument NSTATE. The remaining rows of CJSL, corresponding to non-positive elements of NEEDC, need not be set.
If all elements of the constraint Jacobian are known (i.e., Derivative Level=2 or 3), any constant elements may be assigned to CJSL one time only at the start of each local optimization. An element of CJSL that is not subsequently assigned in CONFUN will retain its initial value throughout the local optimization. Constant elements may be loaded into CJSL during the first call to CONFUN for the local optimization (signalled by the value NSTATE=1). The ability to preload constants is useful when many Jacobian elements are identically zero, in which case CJSL may be initialized to zero and nonzero elements may be reset by CONFUN.
Note that constant nonzero elements do affect the values of the constraints. Thus, if CJSL kj is set to a constant value, it need not be reset in subsequent calls to CONFUN, but the value CJSL kj×X j must nonetheless be added to C k. For example, if CJSL 11=2 and CJSL 12=-5 then the term 2×X 1-5×X 2 must be included in the definition of C 1.
It must be emphasized that, if Derivative Level=0 or 1, unassigned elements of CJSL are not treated as constant; they are estimated by finite differences, at nontrivial expense. If you do not supply a value for the optional parameter Difference Interval, an interval for each element of x is computed automatically at the start of each local optimization. The automatic procedure can usually identify constant elements of CJSL, which are then computed once only by finite differences.
9:   NSTATE – INTEGERInput
On entry: if NSTATE=1 then E05UCF is calling CONFUN for the first time on the current local optimization problem. This argument setting allows you to save computation time if certain data must be calculated only once.
10:   IUSER* – INTEGER arrayUser Workspace
11:   RUSER* – REAL (KIND=nag_wp) arrayUser Workspace
CONFUN is called with the arguments IUSER and RUSER as supplied to E05UCF. You are free to use the arrays IUSER and RUSER to supply information to CONFUN as an alternative to using COMMON global variables.
CONFUN must either be a module subprogram USEd by, or declared as EXTERNAL in, the (sub)program from which E05UCF is called. Arguments denoted as Input must not be changed by this procedure.
CONFUN should be tested separately before being used in conjunction with E05UCF. See also the description of the optional parameter Verify.
9:   OBJFUN – SUBROUTINE, supplied by the user.External Procedure
OBJFUN must calculate the objective function F x and (optionally) its gradient g x = ∂F ∂x for a specified n-vector x.
The specification of OBJFUN is:
SUBROUTINE OBJFUN ( MODE, N, X, OBJF, OBJGRD, NSTATE, IUSER, RUSER)
INTEGER | MODE, N, NSTATE, IUSER(*)
REAL (KIND=nag_wp) | X(N), OBJF, OBJGRD(N), RUSER(*)
1:   MODE – INTEGERInput/Output
On entry: indicates which values must be assigned during each call of OBJFUN. Only the following values need be assigned:
MODE=0
OBJF.
MODE=1
All available elements of OBJGRD.
MODE=2
OBJF and all available elements of OBJGRD.
On exit: may be set to a negative value if you wish to abandon the solution to the current local minimization problem. In this case E05UCF will move to the next local minimization problem.
2:   N – INTEGERInput
On entry: n, the number of variables.
3:   X N – REAL (KIND=nag_wp) arrayInput
On entry: x, the vector of variables at which the objective function and/or all available elements of its gradient are to be evaluated.
4:   OBJF – REAL (KIND=nag_wp)Output
On exit: if MODE=0 or 2, OBJF must be set to the value of the objective function at x.
5:   OBJGRD N – REAL (KIND=nag_wp) arrayInput/Output
On entry: the elements of OBJGRD are set to special values which enable E05UCF to detect whether they are changed by OBJFUN.
On exit: if MODE=1 or 2, OBJGRD must return the available elements of the gradient evaluated at x.
6:   NSTATE – INTEGERInput
On entry: if NSTATE=1 then E05UCF is calling OBJFUN for the first time on the current local optimization problem. This argument setting allows you to save computation time if certain data must be calculated only once.
7:   IUSER* – INTEGER arrayUser Workspace
8:   RUSER* – REAL (KIND=nag_wp) arrayUser Workspace
OBJFUN is called with the arguments IUSER and RUSER as supplied to E05UCF. You are free to use the arrays IUSER and RUSER to supply information to OBJFUN as an alternative to using COMMON global variables.
OBJFUN must either be a module subprogram USEd by, or declared as EXTERNAL in, the (sub)program from which E05UCF is called. Arguments denoted as Input must not be changed by this procedure.
OBJFUN should be tested separately before being used in conjunction with E05UCF. See also the description of the optional parameter Verify.
10:   NPTS – INTEGERInput
On entry: the number of different starting points to be generated and used. The more points used, the more likely that the best returned solution will be a global minimum.
Constraint: 1≤NB≤NPTS.
11:   X LDXNB – REAL (KIND=nag_wp) arrayOutput
On exit: X ji contains the final estimate of the ith solution, for j=1,2,…,N.
12:   LDX – INTEGERInput
On entry: the first dimension of the array X as declared in the (sub)program from which E05UCF is called.
Constraint: LDX≥N.
13:   START – SUBROUTINE, supplied by the NAG Library or the user.External Procedure
START must calculate the NPTS starting points to be used by the local optimizer. If you do not wish to write a routine specific to your problem then E05UCZ may be used as the actual argument. E05UCZ is supplied in the NAG Library and uses the NAG quasi-random number generators to distribute starting points uniformly across the domain. It is affected by the value of REPEAT.
The specification of START is:
SUBROUTINE START ( NPTS, QUAS, N, REPEAT, BL, BU, IUSER, RUSER, MODE)
INTEGER | NPTS, N, IUSER(*), MODE
REAL (KIND=nag_wp) | QUAS(N,NPTS), BL(N), BU(N), RUSER(*)
LOGICAL | REPEAT
1:   NPTS – INTEGERInput
On entry: indicates the number of starting points.
2:   QUAS NNPTS – REAL (KIND=nag_wp) arrayInput/Output
On entry: all elements of QUAS will have been set to zero, so only nonzero values need be set subsequently.
On exit: must contain the starting points for the NPTS local minimizations, i.e., QUAS ji must contain the jth component of the ith starting point.
3:   N – INTEGERInput
On entry: the number of variables.
4:   REPEAT – LOGICALInput
On entry: specifies whether a repeatable or non-repeatable sequence of points are to be generated.
5:   BL N – REAL (KIND=nag_wp) arrayInput
On entry: the lower bounds on the variables. These may be used to ensure that the starting points generated in some sense ‘cover’ the region, but there is no requirement that a starting point be feasible.
6:   BU N – REAL (KIND=nag_wp) arrayInput
On entry: the upper bounds on the variables. (See BL.)
7:   IUSER* – INTEGER arrayUser Workspace
8:   RUSER* – REAL (KIND=nag_wp) arrayUser Workspace
START is called with the arguments IUSER and RUSER as supplied to E05UCF. You are free to use the arrays IUSER and RUSER to supply information to START as an alternative to using COMMON global variables.
9:   MODE – INTEGERInput/Output
On entry: MODE will contain 0.
On exit: if you set MODE to a negative value then E05UCF will terminate immediately with IFAIL=9.
START must either be a module subprogram USEd by, or declared as EXTERNAL in, the (sub)program from which E05UCF is called. Arguments denoted as Input must not be changed by this procedure.
14:   REPEAT – LOGICALInput
On entry: is passed as an argument to START and may be used to initialize a random number generator to a repeatable, or non-repeatable, sequence.
15:   NB – INTEGERInput
On entry: the number of solutions to be returned. The routine saves up to NB local minima ordered by increasing value of the final objective function. If the defining criterion for ‘best solution’ is only that the value of the objective function is as small as possible then NB should be set to 1. However, if you want to look at other solutions that may have desirable properties then setting NB>1 will produce NB local minima, ordered by increasing value of their objective functions at the minima.
Constraint: 1≤NB≤NPTS.
16:   OBJF NB – REAL (KIND=nag_wp) arrayOutput
On exit: OBJF i contains the value of the objective function at the final iterate for the ith solution.
17:   OBJGRD LDOBJDNB – REAL (KIND=nag_wp) arrayOutput
On exit: OBJGRD ji contains the gradient of the objective function for the ith solution at the final iterate (or its finite difference approximation), for j=1,2,…,N.
18:   LDOBJD – INTEGERInput
On entry: the first dimension of the array OBJGRD as declared in the (sub)program from which E05UCF is called.
Constraint: LDOBJD≥N.
19:   ITER NB – INTEGER arrayOutput
On exit: ITER i contains the number of major iterations performed to obtain the ith solution. If less than NB solutions are returned then ITER NB contains the number of starting points that have resulted in a converged solution. If this is close to NPTS then this might be indicative that fewer than NB local minima exist.
20:   C LDCNB – REAL (KIND=nag_wp) arrayOutput
On exit: if NCNLN>0, C ji contains the value of the jth nonlinear constraint function cj at the final iterate, for the ith solution, for j=1,2,…,NCNLN.
If NCNLN=0, the array C is not referenced.
21:   LDC – INTEGERInput
On entry: the first dimension of the array C as declared in the (sub)program from which E05UCF is called.
Constraint: LDC≥NCNLN.
22:   CJAC LDCJACSDCJACNB – REAL (KIND=nag_wp) arrayOutput
On exit: if NCNLN>0, CJAC contains the Jacobian matrices of the nonlinear constraint functions at the final iterate for each of the returned solutions, i.e., CJAC kji contains the partial derivative of the kth constraint function with respect to the jth variable, for k=1,2,…,NCNLN and j=1,2,…,N, for the ith solution. (See the discussion of argument CJSL under CONFUN.)
If NCNLN=0, the array CJAC is not referenced.
23:   LDCJAC – INTEGERInput
On entry: the first dimension of the array CJAC as declared in the (sub)program from which E05UCF is called.
Constraint: LDCJAC≥NCNLN.
24:   SDCJAC – INTEGERInput
On entry: the second dimension of the array CJAC as declared in the (sub)program from which E05UCF is called.
Constraint: if NCNLN>0, SDCJAC≥N.
25:   R LDRSDRNB – REAL (KIND=nag_wp) arrayOutput
On exit: for each of the NB solutions R will contain a form of the Hessian; for the ith returned solution R LDRSDRi contains the Hessian that would be returned from the local minimizer. If Hessian=NO, the default, each R LDRSDRi contains the upper triangular Cholesky factor R of QT HQ, an estimate of the transformed and reordered Hessian of the Lagrangian at x. If Hessian=YES, R LDRSDRi contains the upper triangular Cholesky factor R of H, the approximate (untransformed) Hessian of the Lagrangian, with the variables in the natural order.
26:   LDR – INTEGERInput
On entry: the first dimension of the array R as declared in the (sub)program from which E05UCF is called.
Constraint: LDR≥N.
27:   SDR – INTEGERInput
On entry: the second dimension of the array R as declared in the (sub)program from which E05UCF is called.
Constraint: SDR≥N.
28:   CLAMDA LDCLDANB – REAL (KIND=nag_wp) arrayOutput
On exit: the values of the QP multipliers from the last QP subproblem solved for the ith solution. CLAMDA ji should be non-negative if ISTATE ji=1 and non-positive if ISTATE ji=2.
29:   LDCLDA – INTEGERInput
On entry: the first dimension of the array CLAMDA as declared in the (sub)program from which E05UCF is called.
Constraint: LDCLDA≥N+NCLIN+NCNLN.
30:   ISTATE LISTATNB – INTEGER arrayOutput
On exit: ISTATE ji contains the status of the constraints in the QP working set for the ith solution. The significance of each possible value of ISTATE ji is as follows:
ISTATE ji | Meaning
-0 | The constraint is satisfied to within the feasibility tolerance, but is not in the QP working set.
-1 | This inequality constraint is included in the QP working set at its lower bound.
-2 | This inequality constraint is included in the QP working set at its upper bound.
-3 | This constraint is included in the QP working set as an equality. This value of ISTATE can occur only when BL j=BU j.
31:   LISTAT – INTEGERInput
On entry: the first dimension of the array ISTATE as declared in the (sub)program from which E05UCF is called.
Constraint: LISTAT≥N+NCLIN+NCNLN.
32:   IOPTS 740 – INTEGER arrayCommunication Array
33:   OPTS 485 – REAL (KIND=nag_wp) arrayCommunication Array
The arrays IOPTS and OPTS must not be altered between calls to any of the routines E05UCF and E05ZKF.
34:   IUSER* – INTEGER arrayUser Workspace
35:   RUSER* – REAL (KIND=nag_wp) arrayUser Workspace
IUSER and RUSER are not used by E05UCF, but are passed directly to CONFUN, OBJFUN and START and may be used to pass information to these routines as an alternative to using COMMON global variables.
With care, you may also write information back into IUSER and RUSER. This might be useful, for example, should there be a need to preserve the state of a random number generator.
With SMP-enabled versions of E05UCF the arrays IUSER and RUSER provided are classified as OpenMP shared memory. Use of IUSER and RUSER has to take account of this in order to preserve thread safety whenever information is written back to either of these arrays.
36:   INFO NB – INTEGER arrayOutput
On exit: INFO i contains one of 0, 1 or 6. Please see the description of each corresponding value of IFAIL on exit from E04UCF/E04UCA for detailed explanations of these exit values. As usual 0 denotes success.
If IFAIL=8 on exit, then not all NB solutions have been found, and INFO NB contains the number of solutions actually found.
37:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, because for this routine the values of the output arguments may be useful even if IFAIL≠0 on exit, the recommended value is -1. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Note: E05UCF may return useful information for one or more of the following detected errors or warnings.
Errors or warnings detected by the routine:
IFAIL=1
An input value is incorrect. One or more of the following constraints are violated.
  • On entry, BL i>BU i: i=value.
    Constraint: BL i≤BU i, for all i.
  • On entry, LDA=value and NCLIN=value.
    Constraint: LDA≥NCLIN.
  • On entry, LDC=value and NCNLN=value.
    Constraint: LDC≥NCNLN.
  • On entry, LDCJAC=value and NCNLN=value.
    Constraint: LDCJAC≥NCNLN.
  • On entry, LDCLDA=value, N=value, NCLIN=value and NCNLN=value.
    Constraint: LDCLDA≥N+NCLIN+NCNLN.
  • On entry, LDOBJD=value and N=value.
    Constraint: LDOBJD≥N.
  • On entry, LDR=value and N=value.
    Constraint: LDR≥N.
  • On entry, LDX=value and N=value.
    Constraint: LDX≥N.
  • On entry, LISTAT=value, N=value, NCLIN=value and NCNLN=value.
    Constraint: LISTAT≥N+NCLIN+NCNLN.
  • On entry, N=value.
    Constraint: N>0.
  • On entry, NB=value and NPTS=value.
    Constraint: 1≤NB≤NPTS.
  • On entry, NCLIN=value.
    Constraint: NCLIN≥0.
  • On entry, NCNLN=value.
    Constraint: NCNLN≥0.
  • On entry, NCNLN>0, SDCJAC=value and N=value.
    Constraint: if NCNLN>0, SDCJAC≥N.
  • On entry, SDR=value and N=value.
    Constraint: SDR≥N.
IFAIL=2
No solution obtained. Linear constraints may be infeasible.
E05UCF has terminated without finding any solutions. The majority of calls to the local optimizer have failed to find a feasible point for the linear constraints and bounds, which means that either no feasible point exists for the given value of the optional parameter Linear Feasibility Tolerance (default value ε, where ε is the machine precision), or no feasible point could be found in the number of iterations specified by the optional parameter Minor Iteration Limit. You should check that there are no constraint redundancies. If the data for the constraints are accurate only to an absolute precision σ, you should ensure that the value of the optional parameter Linear Feasibility Tolerance is greater than σ. For example, if all elements of AL are of order unity and are accurate to only three decimal places, Linear Feasibility Tolerance should be at least 10-3.
IFAIL=3
E05UCF has failed to find any solutions. The majority of local optimizations could not find a feasible point for the nonlinear constraints. The problem may have no feasible solution. This behaviour will occur if there is no feasible point for the nonlinear constraints. (However, there is no general test that can determine whether a feasible point exists for a set of nonlinear constraints.)
No solution obtained. Nonlinear constraints may be infeasible.
IFAIL=4
No solution obtained. Many potential solutions reach iteration limit.
The Iteration Limit may be changed using E05ZKF.
IFAIL=7
User-supplied derivatives probably wrong.
The user-supplied derivatives of the objective function and/or nonlinear constraints appear to be incorrect.
Large errors were found in the derivatives of the objective function and/or nonlinear constraints. This value of IFAIL will occur if the verification process indicated that at least one gradient or Jacobian element had no correct figures. You should refer to or enable the printed output to determine which elements are suspected to be in error.
As a first-step, you should check that the code for the objective and constraint values is correct – for example, by computing the function at a point where the correct value is known. However, care should be taken that the chosen point fully tests the evaluation of the function. It is remarkable how often the values x=0 or x=1 are used to test function evaluation procedures, and how often the special properties of these numbers make the test meaningless.
Gradient checking will be ineffective if the objective function uses information computed by the constraints, since they are not necessarily computed before each function evaluation.
Errors in programming the function may be quite subtle in that the function value is ‘almost’ correct. For example, the function may not be accurate to full precision because of the inaccurate calculation of a subsidiary quantity, or the limited accuracy of data upon which the function depends. A common error on machines where numerical calculations are usually performed in double precision is to include even one single precision constant in the calculation of the function; since some compilers do not convert such constants to double precision, half the correct figures may be lost by such a seemingly trivial error.
IFAIL=8
Only value solutions obtained.
Not all NB solutions have been found. INFO NB contains the number actually found.
IFAIL=9
User terminated computation from START procedure: MODE=value.
If E05UCZ has been used as an actual argument for START then the message displayed, when IFAIL=0 or -1 on entry to E05UCF, will have the following meaning:
998 | failure to allocate space, a smaller value of NPTS should be tried.
997 | an internal error has occurred. Please contact NAG for assistance.
IFAIL=10
Failed to initialize optional parameter arrays.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

If IFAIL=0 on exit and the value of INFO i=0, then the vector returned in the array X for solution i is an estimate of the solution to an accuracy of approximately Optimality Tolerance.

8 Parallelism and Performance

E05UCF is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library. In these implementations, this routine may make calls to the user-supplied functions from within an OpenMP parallel region. Thus OpenMP directives within the user functions can only be used if you are compiling the user-supplied function and linking the executable in accordance with the instructions in the Users' Note for your implementation. The user workspace arrays IUSER and RUSER are classified as OpenMP shared memory and use of IUSER and RUSER has to take account of this in order to preserve thread safety whenever information is written back to either of these arrays. If at all possible, it is recommended that these arrays are only used to supply read-only data to the user functions when a multithreaded implementation is being used.
E05UCF makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

You should be wary of requesting much intermediate output from the local optimizer, since large volumes may be produced if NPTS is large.
The auxiliary routine E05UCZ makes use of the NAG quasi-random Sobol generator (G05YLF and G05YMF). If E05UCZ is used as an argument for START (see the description of START) and REPEAT=.FALSE. then a randomly chosen value for ISKIP is used, otherwise ISKIP is set to 100. If REPEAT is set to .FALSE. and the program is executed several times, each time producing the same best answer, then there is increased probability that this answer is a global minimum. However, if it is important that identical results be obtained on successive runs, then REPEAT should be set to .TRUE..

9.1 Description of the Printed Output

See Section 9.1 in E04UCF/E04UCA.

10 Example

This example finds the global minimum of the two-dimensional Schwefel function:
minimize x∈R 2 f = ∑ j=1 2 xj sin xj
subject to the constraints:
-10000<3.0 x 1 - 2.0 x 2 <10.0 , -1.0 < x 12 - x 22 + 3.0 x 1 x 2 < 500000.0 , -0.9 < cos x 1 / 200 2 + x 2 / 100 < 0.9 , -500 ≤ x 1 ≤ 500 , -500 ≤ x 2 ≤ 500 .

10.1 Program Text

Program Text (e05ucfe.f90)

10.2 Program Data

Program Data (e05ucfe.d)

10.3 Program Results

Program Results (e05ucfe.r)

11 Algorithmic Details

See Section 11 in E04UCF/E04UCA.

12 Optional Parameters

Several optional parameters in E05UCF define choices in the problem specification or the algorithm logic. In order to reduce the number of formal arguments of E05UCF these optional parameters have associated default values that are appropriate for most problems. Therefore you need only specify those optional parameters whose values are to be different from their default values.
Optional parameters may be specified by calling E05ZKF before a call to E05UCF. Before calling E05UCF, the optional parameter arrays IOPTS and OPTS must be initialized for use with E05UCF by calling E05ZKF with OPTSTR set to ‘Initialize = e05ucf’.
All optional parameters not specified are set to their default values. Optional parameters specified are unaltered by E05UCF (unless they define invalid values) and so remain in effect for subsequent calls to E05UCF.

12.1 Description of the Optional Parameters

E05UCF supports two options that are distinct from those of E04UCF/E04UCA:
Punch Unit i Default =6
This option allows you to send information arising from an appropriate setting of Out_Level to be sent to the Fortran unit number defined by Punch Unit. If you wish this file to be different to the standard output unit (6) where other output is displayed then this file should be attached by calling X04ACF prior to calling E05UCF.
Out_Level i Default =0
This option defines the amount of extra information to be sent to the Fortran unit number defined by Punch Unit. The possible choices for i are the following:
i | Meaning
0 | No extra output.
1 | Updated solutions only. This is useful during long runs to observe progress.
2 | Successful start points only. This is useful to save the starting points that gave rise to the final solution.
3 | Both updated solutions and successful start points.
See Section 12 in E04UCF/E04UCA for details of the other options.
The Warm Start option of E04UCF/E04UCA is not a valid option for use with E05UCF.

13 Description of Monitoring Information

See Section 13 in E04UCF/E04UCA.
E05 Chapter Contents
E05 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


E05USF : NAG Library, Mark 26

E05 Chapter Contents
E05 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

E05USF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
▸▿ 9 Further Comments
9.1 Description of the Printed Output
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results
11 Algorithmic Details
12 Optional Parameters
13 Description of Monitoring Information

1 Purpose

E05USF is designed to find the global minimum of an arbitrary smooth sum of squares function subject to constraints (which may include simple bounds on the variables, linear constraints and smooth nonlinear constraints) by generating a number of different starting points and performing a local search from each using sequential quadratic programming.

2 Specification

SUBROUTINE E05USF ( M, N, NCLIN, NCNLN, A, LDA, BL, BU, Y, CONFUN, OBJFUN, NPTS, X, LDX, START, REPEAT1, NB, OBJF, F, FJAC, LDFJAC, SDFJAC, ITER, C, LDC, CJAC, LDCJAC, SDCJAC, CLAMDA, LDCLDA, ISTATE, LISTAT, IOPTS, OPTS, IUSER, RUSER, INFO, IFAIL)
INTEGER | M, N, NCLIN, NCNLN, LDA, NPTS, LDX, NB, LDFJAC, SDFJAC, ITER(NB), LDC, LDCJAC, SDCJAC, LDCLDA, ISTATE(LISTAT,*), LISTAT, IOPTS(740), IUSER(*), INFO(NB), IFAIL
REAL (KIND=nag_wp) | A(LDA,*), BL(N+NCLIN+NCNLN), BU(N+NCLIN+NCNLN), Y(M), X(LDX,*), OBJF(NB), F(M,*), FJAC(LDFJAC,SDFJAC,*), C(LDC,*), CJAC(LDCJAC,SDCJAC,*), CLAMDA(LDCLDA,*), OPTS(485), RUSER(*)
LOGICAL | REPEAT1
EXTERNAL | CONFUN, OBJFUN, START
Before calling E05USF, the optional parameter arrays IOPTS and OPTS must be initialized for use with E05USF by calling E05ZKF with OPTSTR set to ‘Initialize = e05usf’. Optional parameters may subsequently be specified by calling E05ZKF before the call to E05USF.

3 Description

The local minimization method is E04USA. The problem is assumed to be stated in the following form:
minimize x∈Rn ​ ​ F x = 12 ∑ i=1 m yi- fi x 2   subject to  l≤ x AL x c x ≤u, (1)
where F x (the objective function) is a nonlinear function which can be represented as the sum of squares of m subfunctions y 1-f 1 x,y 2-f 2 x,…,ym-fm x, the yi are constant, AL is an nL by n constant linear constraint matrix, and c x is an nN element vector of nonlinear constraint functions. (The matrix AL and the vector c x may be empty.) The objective function and the constraint functions are assumed to be smooth, i.e., at least twice-continuously differentiable. (This routine will usually solve (1) if any isolated discontinuities are away from the solution.)
E05USF solves a user-specified number of local optimization problems with different starting points. You may specify the starting points via the subroutine START. If a random number generator is used to generate the starting points then the argument REPEAT1 allows you to specify whether a repeatable set of points are generated or whether different starting points are generated on different calls. The resulting local minima are ordered and the best NB results returned in order of ascending values of the resulting objective function values at the minima. Thus the value returned in position 1 will be the best result obtained. If a sufficiently high number of different points are chosen then this is likely to be the global minimum.

4 References

Gill P E, Murray W and Wright M H (1981) Practical Optimization Academic Press
Hock W and Schittkowski K (1981) Test Examples for Nonlinear Programming Codes. Lecture Notes in Economics and Mathematical Systems 187 Springer–Verlag

5 Arguments

1:   M – INTEGERInput
On entry: m, the number of subfunctions associated with F x.
Constraint: M>0.
2:   N – INTEGERInput
On entry: n, the number of variables.
Constraint: N>0.
3:   NCLIN – INTEGERInput
On entry: nL, the number of general linear constraints.
Constraint: NCLIN≥0.
4:   NCNLN – INTEGERInput
On entry: nN, the number of nonlinear constraints.
Constraint: NCNLN≥0.
5:   A LDA* – REAL (KIND=nag_wp) arrayInput
Note: the second dimension of the array A must be at least N if NCLIN>0, and at least 1 otherwise.
On entry: the matrix AL of general linear constraints in (1). That is, the ith row contains the coefficients of the ith general linear constraint, for i=1,2,…,NCLIN.
If NCLIN=0, the array A is not referenced.
6:   LDA – INTEGERInput
On entry: the first dimension of the array A as declared in the (sub)program from which E05USF is called.
Constraint: LDA≥NCLIN.
7:   BL N+NCLIN+NCNLN – REAL (KIND=nag_wp) arrayInput
8:   BU N+NCLIN+NCNLN – REAL (KIND=nag_wp) arrayInput
On entry: BL must contain the lower bounds and BU the upper bounds for all the constraints in the following order. The first n elements of each array must contain the bounds on the variables, the next nL elements the bounds for the general linear constraints (if any) and the next nN elements the bounds for the general nonlinear constraints (if any). To specify a nonexistent lower bound (i.e., lj=-∞), set BL j≤-bigbnd, and to specify a nonexistent upper bound (i.e., uj=+∞), set BU j≥bigbnd; the default value of bigbnd is 1020, but this may be changed by the optional parameter Infinite Bound Size. To specify the jth constraint as an equality, set BL j=BU j=β, say, where β<bigbnd.
Constraints:
  • BL j≤BU j, for j=1,2,…,N+NCLIN+NCNLN;
  • if BL j=BU j=β, β<bigbnd.
9:   Y M – REAL (KIND=nag_wp) arrayInput
On entry: the coefficients of the constant vector y of the objective function.
10:   CONFUN – SUBROUTINE, supplied by the NAG Library or the user.External Procedure
CONFUN must calculate the vector c x of nonlinear constraint functions and (optionally) its Jacobian (= ∂c ∂x ) for a specified n-element vector x. If there are no nonlinear constraints (i.e., NCNLN=0), CONFUN will never be called by E05USF and CONFUN may be the dummy routine E04UDM. (E04UDM is included in the NAG Library.) If there are nonlinear constraints, the first call to CONFUN will occur before the first call to OBJFUN.
The specification of CONFUN is:
SUBROUTINE CONFUN ( MODE, NCNLN, N, LDCJSL, NEEDC, X, C, CJSL, NSTATE, IUSER, RUSER)
INTEGER | MODE, NCNLN, N, LDCJSL, NEEDC(NCNLN), NSTATE, IUSER(*)
REAL (KIND=nag_wp) | X(N), C(NCNLN), CJSL(LDCJSL,*), RUSER(*)
1:   MODE – INTEGERInput/Output
On entry: indicates which values must be assigned during each call of CONFUN. Only the following values need be assigned, for each value of i such that NEEDC i>0:
MODE=0
C i, the ith nonlinear constraint.
MODE=1
All available elements in the ith row of CJSL.
MODE=2
C i and all available elements in the ith row of CJSL.
On exit: may be set to a negative value if you wish to abandon the solution to the current local minimization problem. In this case E05USF will move to the next local minimization problem.
2:   NCNLN – INTEGERInput
On entry: nN, the number of nonlinear constraints.
3:   N – INTEGERInput
On entry: n, the number of variables.
4:   LDCJSL – INTEGERInput
On entry: LDCJSL is the first dimension of the array CJSL.
5:   NEEDC NCNLN – INTEGER arrayInput
On entry: the indices of the elements of C and/or CJSL that must be evaluated by CONFUN. If NEEDC i>0, C i and/or the available elements of the ith row of CJSL (see argument MODE) must be evaluated at x.
6:   X N – REAL (KIND=nag_wp) arrayInput
On entry: x, the vector of variables at which the constraint functions and/or the available elements of the constraint Jacobian are to be evaluated.
7:   C NCNLN – REAL (KIND=nag_wp) arrayOutput
On exit: if NEEDC i>0 and MODE=0 or 2, C i must contain the value of ci x. The remaining elements of C, corresponding to the non-positive elements of NEEDC, need not be set.
8:   CJSL LDCJSL* – REAL (KIND=nag_wp) arrayInput/Output
CJSL may be regarded as a two-dimensional ‘slice’ of the three-dimensional array CJAC of E05USF.
On entry: unless Derivative Level=2 or 3, the elements of CJSL are set to special values which enable E05USF to detect whether they are changed by CONFUN.
On exit: if NEEDC i>0 and MODE=1 or 2, the ith row of CJSL must contain the available elements of the vector ∇ci given by
∇ci= ∂ci ∂x 1 , ∂ci ∂x 2 ,…, ∂ci ∂xn T,
where ∂ci ∂xj is the partial derivative of the ith constraint with respect to the jth variable, evaluated at the point x. See also the argument NSTATE. The remaining rows of CJSL, corresponding to non-positive elements of NEEDC, need not be set.
If all elements of the constraint Jacobian are known (i.e., Derivative Level=2 or 3; note the default is Derivative Level=3), any constant elements may be assigned to CJSL one time only at the start of each local optimization. An element of CJSL that is not subsequently assigned in CONFUN will retain its initial value throughout the local optimization. Constant elements may be loaded into CJSL during the first call to CONFUN for the local optimization (signalled by the value NSTATE=1). The ability to preload constants is useful when many Jacobian elements are identically zero, in which case CJSL may be initialized to zero and nonzero elements may be reset by CONFUN.
Note that constant nonzero elements do affect the values of the constraints. Thus, if CJSL ij is set to a constant value, it need not be reset in subsequent calls to CONFUN, but the value CJSL ij×X j must nonetheless be added to C i. For example, if CJSL 11=2 and CJSL 12=-5 then the term 2×X 1-5×X 2 must be included in the definition of C 1.
It must be emphasized that, if Derivative Level=0 or 1, unassigned elements of CJSL are not treated as constant; they are estimated by finite differences, at nontrivial expense. If you do not supply a value for the optional parameter Difference Interval, an interval for each element of x is computed automatically at the start of each local optimization. The automatic procedure can usually identify constant elements of CJSL, which are then computed once only by finite differences.
9:   NSTATE – INTEGERInput
On entry: if NSTATE=1 then E05USF is calling CONFUN for the first time on the current local optimization problem. This argument setting allows you to save computation time if certain data must be read or calculated only once.
10:   IUSER* – INTEGER arrayUser Workspace
11:   RUSER* – REAL (KIND=nag_wp) arrayUser Workspace
CONFUN is called with the arguments IUSER and RUSER as supplied to E05USF. You are free to use the arrays IUSER and RUSER to supply information to CONFUN as an alternative to using COMMON global variables.
CONFUN must either be a module subprogram USEd by, or declared as EXTERNAL in, the (sub)program from which E05USF is called. Arguments denoted as Input must not be changed by this procedure.
CONFUN should be tested separately before being used in conjunction with E05USF. See also the description of the optional parameter Verify.
11:   OBJFUN – SUBROUTINE, supplied by the user.External Procedure
OBJFUN must calculate either the ith element of the vector f x = f 1 x,f 2 x,…,fm x T or all m elements of f x and (optionally) its Jacobian (= ∂f ∂x ) for a specified n-element vector x.
The specification of OBJFUN is:
SUBROUTINE OBJFUN ( MODE, M, N, LDFJSL, NEEDFI, X, F, FJSL, NSTATE, IUSER, RUSER)
INTEGER | MODE, M, N, LDFJSL, NEEDFI, NSTATE, IUSER(*)
REAL (KIND=nag_wp) | X(N), F(M), FJSL(LDFJSL,*), RUSER(*)
1:   MODE – INTEGERInput/Output
On entry: indicates which values must be assigned during each call of OBJFUN. Only the following values need be assigned:
MODE=0 and NEEDFI=i, where i>0
F i.
MODE=0 and NEEDFI<0
F.
MODE=1 and NEEDFI<0
All available elements of FJSL.
MODE=2 and NEEDFI<0
F and all available elements of FJSL.
On exit: may be set to a negative value if you wish to abandon the solution to the current local minimization problem. In this case E05USF will move to the next local minimization problem.
2:   M – INTEGERInput
On entry: m, the number of subfunctions.
3:   N – INTEGERInput
On entry: n, the number of variables.
4:   LDFJSL – INTEGERInput
On entry: LDFJSL is the first dimension of the array FJSL.
5:   NEEDFI – INTEGERInput
On entry: if NEEDFI=i>0, only the ith element of f x needs to be evaluated at x; the remaining elements need not be set. This can result in significant computational savings when m≫n.
6:   X N – REAL (KIND=nag_wp) arrayInput
On entry: x, the vector of variables at which the objective function and/or all available elements of its gradient are to be evaluated.
7:   F M – REAL (KIND=nag_wp) arrayOutput
On exit: if MODE=0 and NEEDFI=i>0, F i must contain the value of fi at x.
If MODE=0 or 2 and NEEDFI<0, F i must contain the value of fi at x, for i=1,2,…,m.
8:   FJSL LDFJSL* – REAL (KIND=nag_wp) arrayInput/Output
FJSL may be regarded as a two-dimensional ‘slice’ of the three-dimensional array FJAC of E05USF.
On entry: is set to a special value.
On exit: if MODE=1 or 2 and NEEDFI<0, the ith row of FJSL must contain the available elements of the vector ∇fi given by
∇fi = ∂fi/ ∂x 1, ∂fi/ ∂x 2 ,…, ∂fi/ ∂xn T ,
evaluated at the point x. See also the argument NSTATE.
9:   NSTATE – INTEGERInput
On entry: if NSTATE=1 then E05USF is calling OBJFUN for the first time on the current local optimization problem. This argument setting allows you to save computation time if certain data must be read or calculated only once.
10:   IUSER* – INTEGER arrayUser Workspace
11:   RUSER* – REAL (KIND=nag_wp) arrayUser Workspace
OBJFUN is called with the arguments IUSER and RUSER as supplied to E05USF. You are free to use the arrays IUSER and RUSER to supply information to OBJFUN as an alternative to using COMMON global variables.
OBJFUN must either be a module subprogram USEd by, or declared as EXTERNAL in, the (sub)program from which E05USF is called. Arguments denoted as Input must not be changed by this procedure.
OBJFUN should be tested separately before being used in conjunction with E05USF. See also the description of the optional parameter Verify.
12:   NPTS – INTEGERInput
On entry: the number of different starting points to be generated and used. The more points used, the more likely that the best returned solution will be a global minimum.
Constraint: 1≤NB≤NPTS.
13:   X LDX* – REAL (KIND=nag_wp) arrayOutput
Note: the second dimension of the array X must be at least NB.
On exit: X ji contains the final estimate of the ith solution, for j=1,2,…,N.
14:   LDX – INTEGERInput
On entry: the first dimension of the array X as declared in the (sub)program from which E05USF is called.
Constraint: LDX≥N.
15:   START – SUBROUTINE, supplied by the NAG Library or the user.External Procedure
START must calculate the NPTS starting points to be used by the local optimizer. If you do not wish to write a routine specific to your problem then E05UCZ may be used as the actual argument. E05UCZ is supplied in the NAG Library and uses the NAG quasi-random number generators to distribute starting points uniformly across the domain. It is affected by the value of REPEAT1.
The specification of START is:
SUBROUTINE START ( NPTS, QUAS, N, REPEAT1, BL, BU, IUSER, RUSER, MODE)
INTEGER | NPTS, N, IUSER(*), MODE
REAL (KIND=nag_wp) | QUAS(N,NPTS), BL(N), BU(N), RUSER(*)
LOGICAL | REPEAT1
1:   NPTS – INTEGERInput
On entry: indicates the number of starting points.
2:   QUAS NNPTS – REAL (KIND=nag_wp) arrayInput/Output
On entry: all elements of QUAS will have been set to zero, so only nonzero values need be set subsequently.
On exit: must contain the starting points for the NPTS local minimizations, i.e., QUAS ji must contain the jth component of the ith starting point.
3:   N – INTEGERInput
On entry: the number of variables.
4:   REPEAT1 – LOGICALInput
On entry: specifies whether a repeatable or non-repeatable sequence of points are to be generated.
5:   BL N – REAL (KIND=nag_wp) arrayInput
On entry: the lower bounds on the variables. These may be used to ensure that the starting points generated in some sense ‘cover’ the region, but there is no requirement that a starting point be feasible.
6:   BU N – REAL (KIND=nag_wp) arrayInput
On entry: the upper bounds on the variables. (See BL.)
7:   IUSER* – INTEGER arrayUser Workspace
8:   RUSER* – REAL (KIND=nag_wp) arrayUser Workspace
START is called with the arguments IUSER and RUSER as supplied to E05USF. You are free to use the arrays IUSER and RUSER to supply information to START as an alternative to using COMMON global variables.
9:   MODE – INTEGERInput/Output
On entry: MODE will contain 0.
On exit: if you set MODE to a negative value then E05USF will terminate immediately with IFAIL=9.
START must either be a module subprogram USEd by, or declared as EXTERNAL in, the (sub)program from which E05USF is called. Arguments denoted as Input must not be changed by this procedure.
16:   REPEAT1 – LOGICALInput
On entry: is passed as an argument to START and may be used to initialize a random number generator to a repeatable, or non-repeatable, sequence. See Section 9 for more detail.
17:   NB – INTEGERInput
On entry: the number of solutions to be returned. The routine saves up to NB local minima ordered by increasing value of the final objective function. If the defining criterion for ‘best solution’ is only that the value of the objective function is as small as possible then NB should be set to 1. However, if you want to look at other solutions that may have desirable properties then setting NB>1 will produce NB local minima, ordered by increasing value of their objective functions at the minima.
Constraint: 1≤NB≤NPTS.
18:   OBJF NB – REAL (KIND=nag_wp) arrayOutput
On exit: OBJF i contains the value of the objective function at the final iterate for the ith solution.
19:   F M* – REAL (KIND=nag_wp) arrayOutput
Note: the second dimension of the array F must be at least NB.
On exit: F ji contains the value of the jth function fj at the final iterate, for j=1,2,…,M, for the ith solution, for i=1,2,…,NB.
20:   FJAC LDFJACSDFJAC* – REAL (KIND=nag_wp) arrayOutput
Note: the last dimension of the array FJAC must be at least NB.
On exit: for the ith returned solution, the Jacobian matrix of the functions f 1 , f 2 ,…, fm at the final iterate, i.e., FJAC kji contains the partial derivative of the kth function with respect to the jth variable, for k=1,2,…,M, j=1,2,…,N and i=1,2,…,NB. (See also the discussion of argument FJSL under OBJFUN.)
21:   LDFJAC – INTEGERInput
On entry: the first dimension of the array FJAC as declared in the (sub)program from which E05USF is called.
Constraint: LDFJAC≥M.
22:   SDFJAC – INTEGERInput
On entry: the second dimension of the array FJAC as declared in the (sub)program from which E05USF is called.
Constraint: SDFJAC≥N.
23:   ITER NB – INTEGER arrayOutput
On exit: ITER i contains the number of major iterations performed to obtain the ith solution. If less than NB solutions are returned then ITER NB contains the number of starting points that have resulted in a converged solution. If this is close to NPTS then this might be indicative that fewer than NB local minima exist.
24:   C LDC* – REAL (KIND=nag_wp) arrayOutput
Note: the second dimension of the array C must be at least NB.
On exit: if NCNLN>0, C ji contains the value of the jth nonlinear constraint function cj at the final iterate, for the ith solution, for j=1,2,…,NCNLN.
If NCNLN=0, the array C is not referenced.
25:   LDC – INTEGERInput
On entry: the first dimension of the array C as declared in the (sub)program from which E05USF is called.
Constraint: LDC≥NCNLN.
26:   CJAC LDCJACSDCJAC* – REAL (KIND=nag_wp) arrayOutput
Note: the last dimension of the array CJAC must be at least NB.
On exit: if NCNLN>0, CJAC contains the Jacobian matrices of the nonlinear constraint functions at the final iterate for each of the returned solutions, i.e., CJAC kji contains the partial derivative of the kth constraint function with respect to the jth variable, for k=1,2,…,NCNLN and j=1,2,…,N, for the ith solution. (See the discussion of argument CJSL under CONFUN.)
If NCNLN=0, the array CJAC is not referenced.
27:   LDCJAC – INTEGERInput
On entry: the first dimension of the array CJAC as declared in the (sub)program from which E05USF is called.
Constraint: LDCJAC≥NCNLN.
28:   SDCJAC – INTEGERInput
On entry: the second dimension of the array CJAC as declared in the (sub)program from which E05USF is called.
Constraint: if NCNLN>0, SDCJAC≥N.
29:   CLAMDA LDCLDA* – REAL (KIND=nag_wp) arrayOutput
Note: the second dimension of the array CLAMDA must be at least NB.
On exit: the values of the QP multipliers from the last QP subproblem solved for the ith solution. CLAMDA ji should be non-negative if ISTATE ji=1 and non-positive if ISTATE ji=2.
30:   LDCLDA – INTEGERInput
On entry: the first dimension of the array CLAMDA as declared in the (sub)program from which E05USF is called.
Constraint: LDCLDA≥N+NCLIN+NCNLN.
31:   ISTATE LISTAT* – INTEGER arrayOutput
Note: the second dimension of the array ISTATE must be at least NB.
On exit: ISTATE ji contains the status of the constraints in the QP working set for the ith solution. The significance of each possible value of ISTATE ji is as follows:
ISTATE ji | Meaning
-0 | The constraint is satisfied to within the feasibility tolerance, but is not in the QP working set.
-1 | This inequality constraint is included in the QP working set at its lower bound.
-2 | This inequality constraint is included in the QP working set at its upper bound.
-3 | This constraint is included in the QP working set as an equality. This value of ISTATE can occur only when BL j=BU j.
32:   LISTAT – INTEGERInput
On entry: the first dimension of the array ISTATE as declared in the (sub)program from which E05USF is called.
Constraint: LISTAT≥N+NCLIN+NCNLN.
33:   IOPTS 740 – INTEGER arrayCommunication Array
34:   OPTS 485 – REAL (KIND=nag_wp) arrayCommunication Array
The arrays IOPTS and OPTS must not be altered between calls to any of the routines E05USF and E05ZKF.
35:   IUSER* – INTEGER arrayUser Workspace
36:   RUSER* – REAL (KIND=nag_wp) arrayUser Workspace
IUSER and RUSER are not used by E05USF, but are passed directly to CONFUN, OBJFUN and START and may be used to pass information to these routines as an alternative to using COMMON global variables.
With SMP-enabled versions of E05USF the arrays IUSER and RUSER provided are classified as OpenMP shared memory. Use of IUSER and RUSER has to take account of this in order to preserve thread safety whenever information is written back to either of these arrays.
37:   INFO NB – INTEGER arrayOutput
On exit: if IFAIL=0, INFO i does not contain an error value returned by E04USF/E04USA .
If IFAIL=8 on exit, then not all NB solutions have been found, and INFO NB contains the number of solutions actually found.
38:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, because for this routine the values of the output arguments may be useful even if IFAIL≠0 on exit, the recommended value is -1. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Note: E05USF may return useful information for one or more of the following detected errors or warnings.
Errors or warnings detected by the routine:
IFAIL=1
An input value is incorrect. One or more of the following requirements are violated:
  • On entry, BL i>BU i: i=value.
    Constraint: BL i≤BU i, for all i.
  • On entry, LDA=value and NCLIN=value.
    Constraint: LDA≥NCLIN.
  • On entry, LDC=value and NCNLN=value.
    Constraint: LDC≥NCNLN.
  • On entry, LDCJAC=value and NCNLN=value.
    Constraint: LDCJAC≥NCNLN.
  • On entry, LDCLDA=value, N=value, NCLIN=value and NCNLN=value.
    Constraint: LDCLDA≥N+NCLIN+NCNLN.
  • On entry, LDFJAC=value and M=value.
    Constraint: LDFJAC≥M.
  • On entry, LDX=value and N=value.
    Constraint: LDX≥N.
  • On entry, LISTAT=value, N=value, NCLIN=value and NCNLN=value.
    Constraint: LISTAT≥N+NCLIN+NCNLN.
  • On entry, M=value.
    Constraint: M>0.
  • On entry, N=value.
    Constraint: N>0.
  • On entry, NB=value and NPTS=value.
    Constraint: 1≤NB≤NPTS.
  • On entry, NCLIN=value.
    Constraint: NCLIN≥0.
  • On entry, NCNLN=value.
    Constraint: NCNLN≥0.
  • On entry, NCNLN>0, SDCJAC=value and N=value.
    Constraint: if NCNLN>0, SDCJAC≥N.
  • On entry, SDFJAC=value and N=value.
    Constraint: SDFJAC≥N.
IFAIL=2
E05USF has terminated without finding any solutions. The majority of calls to the local optimizer have failed to find a feasible point for the linear constraints and bounds, which means that either no feasible point exists for the given value of the optional parameter Linear Feasibility Tolerance (default value macheps, where macheps is the machine precision), or no feasible point could be found in the number of iterations specified by the optional parameter Minor Iteration Limit. You should check that there are no constraint redundancies. If the data for the constraints are accurate only to an absolute precision σ, you should ensure that the value of the optional parameter Linear Feasibility Tolerance is greater than σ. For example, if all elements of AL are of order unity and are accurate to only three decimal places, Linear Feasibility Tolerance should be at least 10-3.
No solution obtained. Linear constraints may be infeasible.
IFAIL=3
E05USF has failed to find any solutions. The majority of local optimizations could not find a feasible point for the nonlinear constraints. The problem may have no feasible solution. This behaviour will occur if there is no feasible point for the nonlinear constraints. (However, there is no general test that can determine whether a feasible point exists for a set of nonlinear constraints.)
No solution obtained. Nonlinear constraints may be infeasible.
IFAIL=4
E05USF has failed to find any solutions. The majority of local optimizations have failed because the limiting number of iterations have been reached.
No solution obtained. Many potential solutions reach iteration limit.
IFAIL=7
The user-supplied derivatives of the objective function and/or nonlinear constraints appear to be incorrect.
Large errors were found in the derivatives of the objective function and/or nonlinear constraints. This value of IFAIL will occur if the verification process indicated that at least one gradient or Jacobian element had no correct figures. You should refer to or enable the printed output to determine which elements are suspected to be in error.
As a first-step, you should check that the code for the objective and constraint values is correct – for example, by computing the function at a point where the correct value is known. However, care should be taken that the chosen point fully tests the evaluation of the function. It is remarkable how often the values x=0 or x=1 are used to test function evaluation procedures, and how often the special properties of these numbers make the test meaningless.
Gradient checking will be ineffective if the objective function uses information computed by the constraints, since they are not necessarily computed before each function evaluation.
Errors in programming the function may be quite subtle in that the function value is ‘almost’ correct. For example, the function may not be accurate to full precision because of the inaccurate calculation of a subsidiary quantity, or the limited accuracy of data upon which the function depends. A common error on machines where numerical calculations are usually performed in double precision is to include even one single precision constant in the calculation of the function; since some compilers do not convert such constants to double precision, half the correct figures may be lost by such a seemingly trivial error.
IFAIL=8
Only value solutions obtained.
Not all NB solutions have been found. INFO NB contains the number actually found.
IFAIL=9
User terminated computation from START procedure: MODE=value.
If E05UCZ has been used as an actual argument for START then the message displayed, when IFAIL=0 or -1 on entry to E05USF, will have the following meaning:
998 | failure to allocate space, a smaller value of NPTS should be tried.
997 | an internal error has occurred. Please contact NAG for assistance.
IFAIL=10
Failed to initialize optional parameter arrays.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

If IFAIL=0 on exit and the value of INFO i=0, then the vector returned in the array X for solution i is an estimate of the solution to an accuracy of approximately Optimality Tolerance.

8 Parallelism and Performance

E05USF is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library. In these implementations, this routine may make calls to the user-supplied functions from within an OpenMP parallel region. Thus OpenMP directives within the user functions can only be used if you are compiling the user-supplied function and linking the executable in accordance with the instructions in the Users' Note for your implementation. The user workspace arrays IUSER and RUSER are classified as OpenMP shared memory and use of IUSER and RUSER has to take account of this in order to preserve thread safety whenever information is written back to either of these arrays. If at all possible, it is recommended that these arrays are only used to supply read-only data to the user functions when a multithreaded implementation is being used.
E05USF makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

You should be wary of requesting much intermediate output from the local optimizer, since large volumes may be produced if NPTS is large.
The auxiliary routine E05UCZ makes use of the NAG quasi-random Sobol generator (G05YLF and G05YMF). If E05UCZ is used as the actual argument for START and REPEAT1=.FALSE. then a randomly chosen value for ISKIP is used, otherwise ISKIP is set to 100. If REPEAT1 is set to .FALSE. and the program is executed several times, each time producing the same best answer, then there is increased probability that this answer is a global minimum. However, if it is important that identical results be obtained on successive runs, then REPEAT1 should be set to .TRUE..

9.1 Description of the Printed Output

See Section 9.1 in E04USF/E04USA.

10 Example

This example is based on Problem 57 in Hock and Schittkowski (1981) and involves the minimization of the sum of squares function
F x = 12 ∑ i=1 44 yi - fi x 2 ,
where
fi x = x 1 + 0.49-x 1 e -x 2 ai- 8
and
i yi ai i yi ai 1 0.49 8 23 0.41 22 2 0.49 8 24 0.40 22 3 0.48 10 25 0.42 24 4 0.47 10 26 0.40 24 5 0.48 10 27 0.40 24 6 0.47 10 28 0.41 26 7 0.46 12 29 0.40 26 8 0.46 12 30 0.41 26 9 0.45 12 31 0.41 28 10 0.43 12 32 0.40 28 11 0.45 14 33 0.40 30 12 0.43 14 34 0.40 30 13 0.43 14 35 0.38 30 14 0.44 16 36 0.41 32 15 0.43 16 37 0.40 32 16 0.43 16 38 0.40 34 17 0.46 18 39 0.41 36 18 0.45 18 40 0.38 36 19 0.42 20 41 0.40 38 20 0.42 20 42 0.40 38 21 0.43 20 43 0.39 40 22 0.41 22 44 0.39 42
subject to the bounds
x 1≥-0.4 x 2≥-4.0
to the general linear constraint
x 1+x 2≥1.0
and to the nonlinear constraint
0.49 x 2-x 1 x 2≥ 0.09 .
The optimal solution (to five figures) is
x*=0.41995,1.28484 T,
and F x*=0.01423. The nonlinear constraint is active at the solution.
The document for E04UQF/E04UQA includes an example program to solve the same problem using some of the optional parameters described in Section 12.

10.1 Program Text

Program Text (e05usfe.f90)

10.2 Program Data

Program Data (e05usfe.d)

10.3 Program Results

Program Results (e05usfe.r)

11 Algorithmic Details

See Section 11 in E04USF/E04USA.

12 Optional Parameters

Several optional parameters in E05USF define choices in the problem specification or the algorithm logic. In order to reduce the number of formal arguments of E05USF these optional parameters have associated default values that are appropriate for most problems. Therefore you need only specify those optional parameters whose values are to be different from their default values.
Optional parameters may be specified by calling E05ZKF before a call to E05USF. Before calling E05USF, the optional parameter arrays IOPTS and OPTS must be initialized for use with E05USF by calling E05ZKF with OPTSTR set to ‘Initialize = e05usf’.
All optional parameters not specified are set to their default values. Optional parameters specified are unaltered by E05USF (unless they define invalid values) and so remain in effect for subsequent calls to E05USF.
See Section 12 in E04USF/E04USA for full details.
The Warm Start option of E04USF/E04USA is not a valid option for use with E05USF.
E05USF supports two options that are distinct from those of E04USF/E04USA:
Punch Unit i Default =6
This option allows you to send information arising from an appropriate setting of Out_Level to be sent to the Fortran unit number defined by Punch Unit. If you wish this file to be different to the standard output unit (6) where other output is displayed then this file should be attached by calling X04ACF prior to calling E05USF.
Out_Level i Default =0
This option defines the amount of extra information to be sent to the Fortran unit number defined by Punch Unit. The possible choices for i are the following:
i | Meaning
0 | No extra output.
1 | Updated solutions only. This is useful during long runs to observe progress.
2 | Successful start points only. This is useful to save the starting points that gave rise to the final solution.
3 | Both updated solutions and successful start points.

13 Description of Monitoring Information

See Section 13 in E04USF/E04USA.
E05 Chapter Contents
E05 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


E05ZKF : NAG Library, Mark 26

E05 Chapter Contents
E05 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

E05ZKF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
10 Example

1 Purpose

E05ZKF either initializes or resets the optional parameter arrays or sets a single optional parameter for supported problem solving routines in Chapter E05. The following routines are supported:
  • E05SAF,
  • E05SBF,
  • E05UCF,
  • E05USF.

2 Specification

SUBROUTINE E05ZKF ( OPTSTR, IOPTS, LIOPTS, OPTS, LOPTS, IFAIL)
INTEGER | IOPTS(LIOPTS), LIOPTS, LOPTS, IFAIL
REAL (KIND=nag_wp) | OPTS(LOPTS)
CHARACTER(*) | OPTSTR

3 Description

E05ZKF has three purposes: to initialize optional parameter arrays; to reset all optional parameters to their default values; or to set a single optional parameter to a user-supplied value.
Optional parameters and their values are, in general, presented as a character string, OPTSTR, of the form ‘option =optval’; alphabetic characters can be supplied in either upper or lower case. Both option and optval may consist of one or more tokens separated by white space. The tokens that comprise optval will normally be either an integer, real or character value as defined in the description of the specific optional argument. In addition all optional parameters can take an optval DEFAULT which resets the optional parameter to its default value.
It is imperative that optional parameter arrays are initialized before any options are set, before the relevant problem solving routine is called and before any options are queried using E05ZLF. To initialize the optional parameter arrays IOPTS and OPTS for a specific problem solving routine, the option Initialize is used with optval identifying the problem solving routine to be called, via its short name. For example, to initialize optional parameter arrays to be passed to E05SAF, E05ZKF is called as follows:
call E05ZKF('Initialize = e05saf', IOPTS, LIOPTS, OPTS, LOPTS, IFAIL)
Information relating to available option names and their corresponding valid values is given in Section 12 in E05SAF, E05SBF, E05UCF and E05USF.

4 References

None.

5 Arguments

1:   OPTSTR – CHARACTER(*)Input
On entry: a string identifying the option to be set.
Initialize=routine name
Initialize the optional parameter arrays IOPTS and OPTS for use with routine routine name, where routine name is the short name associated with the routine of interest.
Defaults
Resets all options to their default values.
option=optval
See Section 12 in E05SAF, E05SBF, E05UCF and E05USF for details of valid values for option and optval. The equals sign (=) delimiter must be used to separate the option from its optval value.
OPTSTR is case insensitive. Each token in the option and optval component must be separated by at least one space.
2:   IOPTS LIOPTS – INTEGER arrayCommunication Array
On entry: optional parameter array.
If OPTSTR has the form Initialize=routine name, the contents of IOPTS need not be set.
Otherwise, IOPTS must not have been altered since the last call to E05ZKF, E05ZLF or the selected problem solving routine.
On exit: dependent on the contents of OPTSTR, either an initialized, reset or updated version of the optional parameter array.
3:   LIOPTS – INTEGERInput
On entry: the length of the array IOPTS.
Constraint: unless otherwise stated in the documentation for a specific, supported, problem solving routine, LIOPTS≥100.
4:   OPTS LOPTS – REAL (KIND=nag_wp) arrayCommunication Array
On entry: optional parameter array.
If OPTSTR has the form Initialize=routine name, the contents of OPTS need not be set.
Otherwise, OPTS must not have been altered since the last call to E05ZKF, E05ZLF or the selected problem solving routine.
On exit: dependent on the contents of OPTSTR, either an initialized, reset or updated version of the optional parameter array.
5:   LOPTS – INTEGERInput
On entry: the length of the array OPTS.
Constraint: unless otherwise stated in the documentation for a specific, supported, problem solving routine, LOPTS≥100.
6:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=11
On entry, the optional parameter in OPTSTR was not recognized: OPTSTR=value.
IFAIL=12
On entry, the expected delimiter ‘=’ was not found in OPTSTR: OPTSTR=value.
IFAIL=13
On entry, could not convert the specified optval to an integer: OPTSTR=value.
On entry, could not convert the specified optval to a real: OPTSTR=value.
The option in OPTSTR is associated with a numerical value. However, the optval, value, present in OPTSTR could not be fully interpreted.
IFAIL=14
On entry, the option in OPTSTR has been detected as Initialize, however the optval, value, associated with OPTSTR has not been recognized as a valid routine name.
IFAIL=15
On entry, the optval supplied for the integer optional parameter is not valid.
OPTSTR=value.
IFAIL=16
On entry, the optval supplied for the real optional parameter is not valid.
OPTSTR=value.
IFAIL=17
On entry, the optional parameter in OPTSTR was not recognized: OPTSTR=value.
On entry, the optval supplied for the character optional parameter is not valid.
OPTSTR=value.
IFAIL=21
On entry, either the option arrays have not been initialized or they have been corrupted.
On entry, the optional parameter in OPTSTR was not recognized: OPTSTR=value.
IFAIL=31
On entry, LIOPTS=value.
Constraint: LIOPTS≥value.
IFAIL=51
On entry, LOPTS=value.
Constraint: LOPTS≥value.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

Not applicable.

8 Parallelism and Performance

E05ZKF is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

Some options have default values which are problem dependent. For example the option Maximum Iterations Completed for E05SAF has the default value 1000×NDIM. If options such as this are set, they may only be set to constant values. If such an option is reset to its DEFAULT value its dependence on the specific problem will be restored.

10 Example

See the example programs associated with the problem solving routine you wish to use for a demonstration of how to use E05ZKF to initialize option arrays and set options.
E05 Chapter Contents
E05 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


E05ZLF : NAG Library, Mark 26

E05 Chapter Contents
E05 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

E05ZLF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
10 Example

1 Purpose

E05ZLF is used to query the value of optional parameters available to supported problem solving routines in Chapter E05. Currently the following routines are supported:
  • E05SAF,
  • E05SBF,
  • E05UCF,
  • E05USF.

2 Specification

SUBROUTINE E05ZLF ( OPTSTR, IVALUE, RVALUE, CVALUE, OPTYPE, IOPTS, OPTS, IFAIL)
INTEGER | IVALUE, OPTYPE, IOPTS(*), IFAIL
REAL (KIND=nag_wp) | RVALUE, OPTS(*)
CHARACTER(*) | OPTSTR, CVALUE

3 Description

E05ZLF is used to query the current values of options. It is necessary to initialize optional parameter arrays using E05ZKF before any options are queried.
E05ZLF will normally return either an integer, real or character value dependent upon the type associated with the optional parameter being queried. Some real and integer options also return additional information in CVALUE. Whether the option queried is of integer, real or character type, and whether additional information is returned in CVALUE, is indicated by the returned value of OPTYPE.
Information on optional parameter names and whether these options are real, integer or character can be found in Section 12 in E05SAF, E05SBF, E05UCF and E05USF.

4 References

None.

5 Arguments

1:   OPTSTR – CHARACTER(*)Input
On entry: a string identifying the option whose current value is required. See Section 12 in E05SAF and E05SBF for information on valid options. In addition, the following is a valid option:
Identify
E05ZLF returns in CVALUE the routine name supplied to E05ZKF when the optional parameter arrays IOPTS and OPTS were initialized.
2:   IVALUE – INTEGEROutput
On exit: if the optional parameter supplied in OPTSTR is an integer valued argument, IVALUE will hold its current value.
3:   RVALUE – REAL (KIND=nag_wp)Output
On exit: if the optional parameter supplied in OPTSTR is a real valued argument, RVALUE will hold its current value.
4:   CVALUE – CHARACTER(*)Output
Note: the string returned in CVALUE will never exceed 40 characters in length.
On exit: if the optional parameter supplied in OPTSTR is a character valued argument, CVALUE will hold its current value. CVALUE will also contain additional information for some integer and real valued arguments, as indicated by OPTYPE.
5:   OPTYPE – INTEGEROutput
On exit: indicates whether the optional parameter supplied in OPTSTR is an integer, real or character valued argument and hence which of IVALUE, RVALUE or CVALUE holds the current value.
OPTYPE=1
OPTSTR is an integer valued optional parameter, its current value has been returned in IVALUE.
OPTYPE=2
OPTSTR is a real valued optional parameter, its current value has been returned in RVALUE.
OPTYPE=3
OPTSTR is a character valued optional parameter, its current value has been returned in CVALUE.
OPTYPE=4
OPTSTR is an integer valued optional parameter, its current value has been returned in IVALUE. Additional information has been returned in CVALUE.
OPTYPE=5
OPTSTR is a real valued optional parameter, its current value has been returned in RVALUE. Additional information has been returned in CVALUE.
6:   IOPTS* – INTEGER arrayCommunication Array
Note: the dimension of this array is dictated by the requirements of associated functions that must have been previously called. This array must be the same array passed as argument IOPTS in the previous call to E05ZKF.
7:   OPTS* – REAL (KIND=nag_wp) arrayCommunication Array
Note: the dimension of this array is dictated by the requirements of associated functions that must have been previously called. This array must be the same array passed as argument OPTS in the previous call to E05ZKF.
8:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=11
On entry, the option in OPTSTR has not been recognized.
IFAIL=41
On entry, OPTSTR indicates a character optional parameter, but CVALUE is too short to hold the stored value. The returned value will be truncated.
IFAIL=61
The arrays IOPTS and OPTS have either not been initialized, have become corrupted, or are not compatible with this option setting routine.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

Not applicable.

8 Parallelism and Performance

E05ZLF is not threaded in any implementation.

9 Further Comments

Some options have default values which are problem dependent. For example the option Maximum Iterations Completed for E05SAF has the default value 1000×NDIM. If options such as this are queried before being set, or before the problem solving routine has been called, they will return misleading information in IVALUE or RVALUE. In some cases, the value of CVALUE will be set to DEFAULT to indicate that the real or integer valued optional parameter supplied in OPTSTR is at its default value.

10 Example

See the example programs associated with the problem solving routine you wish to use for a demonstration of how to use E05ZLF to query options.
E05 Chapter Contents
E05 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F Chapter Contents : NAG Library Manual, Mark 26

F Chapter Introduction
NAG Library Manual

NAG Library Chapter Contents

F – Linear Algebra

F Chapter Introduction – a description of the Chapter and an overview of the algorithms available

  • F01 – Matrix Operations, Including Inversion
  • F02 – Eigenvalues and Eigenvectors
  • F03 – Determinants
  • F04 – Simultaneous Linear Equations
  • F05 – Orthogonalization
  • F06 – Linear Algebra Support Routines
  • F07 – Linear Equations (LAPACK)
  • F08 – Least Squares and Eigenvalue Problems (LAPACK)
  • F11 – Large Scale Linear Systems
  • F12 – Large Scale Eigenproblems
  • F16 – Further Linear Algebra Support Routines
F Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F Chapter Introduction : NAG Library, Mark 26

F Chapter Contents
NAG Library Manual

NAG Library Chapter Introduction

F – Linear Algebra

▸▿ Contents

1 Introduction
2 Linear Equations
3 Linear Least Squares
4 Eigenvalue Problems and Singular Value Problems
5 Inversion and Determinants
6 Matrix Operations
7 Support Routines
8 References

1 Introduction

The F Chapters of the Library are concerned with linear algebra and cover a large area. This general introduction is intended to help you decide which particular F Chapter is relevant to your problem. The following Chapters are currently available:
  • Chapter F01 – Matrix Operations, Including Inversion
  • Chapter F02 – Eigenvalues and Eigenvectors
  • Chapter F03 – Determinants
  • Chapter F04 – Simultaneous Linear Equations
  • Chapter F05 – Orthogonalization
  • Chapter F06 – Linear Algebra Support Routines
  • Chapter F07 – Linear Equations (LAPACK)
  • Chapter F08 – Least Squares and Eigenvalue Problems (LAPACK)
  • Chapter F11 – Large Scale Linear Systems
  • Chapter F12 – Large Scale Eigenproblems
  • Chapter F16 – Further Linear Algebra Support Routines
The principal problem areas addressed by the above Chapters are
  • Systems of linear equations
  • Linear least squares problems
  • Eigenvalue and singular value problems
The solution of these problems usually involves several matrix operations, such as a matrix factorization followed by the solution of the factorized form, and the routines for these operations themselves utilize lower level support routines, typically from Chapters F06 and F16. You will not normally need to be concerned with these support routines.
NAG has been involved in a project, called LAPACK (see Anderson et al. (1999)), to develop a linear algebra package for modern high-performance computers, and the routines developed within that project are incorporated into the Library as Chapters F07 and F08. It should be emphasized that, while the LAPACK project has been concerned with high-performance computers, the routines do not compromise efficiency on conventional machines.
Chapters F11 and F12 contain routines for solving large scale problems, but a few earlier routines are still located in Chapters F01, F02 and F04.
For background information on numerical algorithms for the solution of linear algebra problems see Golub and Van Loan (1996). For the three main problem areas listed above you generally have the choice of selecting a single routine to solve the problem, a so-called Black Box routine, or selecting more than one routine to solve the problem, such as a factorization routine followed by a solve routine, so-called General Purpose routines. The following sections indicate which chapters are relevant to particular problem areas.

2 Linear Equations

The Black Box routines for solving linear equations of the form
Ax=b  and  AX=B,
where A is an n by n real or complex nonsingular matrix, are to be found in Chapters F04 and F07. Such equations can also be solved by selecting a general purpose factorization routine from Chapter F01 or Chapter F03 and combining them with a solve routine in Chapter F04, or by selecting a factorization and a solve routine from Chapter F07. For large sparse problems, routines from Chapter F11 should be used. In addition there are routines to estimate condition numbers in Chapters F04 and F07, and routines to give error estimates in Chapters F02, F04 and F07.
There are routines to cater for a variety of types of matrix, including general, symmetric or Hermitian, symmetric or Hermitian positive definite, banded, skyline and sparse matrices.
In order to select the appropriate routine, you are recommended to consult the F04 Chapter Introduction in the first instance, although the decision trees will often in fact point to a routine in Chapters F07 or F11.

3 Linear Least Squares

The Black Box routines for solving linear least squares problems of the form
minimize x rT r,   where ​r=b-Ax,
and A is an m by n, possibly rank deficient, matrix, are to be found in Chapters F04 and F08. Such problems can also be solved by selecting one or more general purpose factorization routines from Chapters F02 or F08 and combining them with a solve routine in Chapter F04, which also contains a routine to compute covariance matrices, or Chapter F08. Linear least squares problems can also be solved by routines in the statistical Chapter G02.
In order to select the appropriate routine, you are recommended to consult the F04 Chapter Introduction in the first instance, but if you have additional statistical requirements you may prefer to consult Section 2.2 in the G02 Chapter Introduction.
Chapter F08 also contains routines for solving linear equality constrained least squares problems, and the general Gauss–Markov linear model problem. Chapter E04 contains a routine to solve general linearly constrained linear least squares problems.

4 Eigenvalue Problems and Singular Value Problems

The Black Box routines for solving standard matrix eigenvalue problems of the form
Ax=λx,
where A is an n by n real or complex matrix, and generalized matrix eigenvalue problems of the form
Ax=λBx and ABx=λx,
where B is also an n by n matrix, are to be found in Chapters F02, F08 and F12. These eigenvalue problems can also be solved by a combination of General Purpose routines (which are mostly in Chapter F08, but a few are in Chapter F02).
There are routines to cater for various types of matrices, including general, symmetric or Hermitian, and banded and sparse matrices.
Similarly, the Black Box routines for finding singular values and/or singular vectors of an m by n real or complex matrix A are to be found in Chapters F02 and F08, and such problems may also be solved by routines from Chapter F12, and by combining routines from Chapter F08.
In order to select the appropriate routine, you are recommended to consult Chapters F02 and F08 in the first instance.

5 Inversion and Determinants

Routines for matrix inversion are to be found in Chapters F01 and F07. You are recommended to consult Chapter F01 in the first instance, although the decision tree will often in fact point to a routine in Chapter F07. It should be noted that you are strongly encouraged not to use matrix inversion routines for the solution of linear equations, since these can be solved more efficiently and accurately using routines directed specifically at such problems. Indeed many problems, which superficially appear to be matrix inversion, can be posed as the solution of a system of linear equations and this is almost invariably preferable.
Routines to compute determinants of matrices are to be found in Chapter F03. You are recommended to consult Chapter F03 in the first instance.

6 Matrix Operations

Routines for various sorts of matrix operation are to be found in Chapter F01, including matrix transposition, addition and multiplication, and conversion between different matrix representation storage formats. Facilities for matrix manipulation can also be found in Chapter F06 (see next section).

7 Support Routines

Chapters F06 and F16 contain contain a variety of routines to perform elementary algebraic operations involving scalars, vectors and matrices, such as setting up a plane rotation, performing a dot product and computing a matrix norm. Chapters F06 and F16 contain routines that meet the specification of the BLAS (Basic Linear Algebra Subprograms) (see Lawson et al. (1979), Dodson et al. (1991), Dongarra et al. (1988), Dongarra et al. (1990) and Blackford et al. (2002)). The routines in these chapters will not normally be required by the general user, but are intended for use by those who require to build specialist linear algebra modules. These routines, especially the BLAS, are extensively used by other NAG Library routines.

8 References

Anderson E, Bai Z, Bischof C, Blackford S, Demmel J, Dongarra J J, Du Croz J J, Greenbaum A, Hammarling S, McKenney A and Sorensen D (1999) LAPACK Users' Guide (3rd Edition) SIAM, Philadelphia
Blackford L S, Demmel J, Dongarra J J, Duff I S, Hammarling S, Henry G, Heroux M, Kaufman L, Lumsdaine A, Petitet A, Pozo R, Remington K and Whaley R C (2002) An updated set of Basic Linear Algebra Subprograms (BLAS) ACM Trans. Math. Software 28 135–151
Dodson D S, Grimes R G and Lewis J G (1991) Sparse extensions to the Fortran basic linear algebra subprograms ACM Trans. Math. Software 17 253–263
Dongarra J J, Du Croz J J, Duff I S and Hammarling S (1990) A set of Level 3 basic linear algebra subprograms ACM Trans. Math. Software 16 1–28
Dongarra J J, Du Croz J J, Hammarling S and Hanson R J (1988) An extended set of FORTRAN basic linear algebra subprograms ACM Trans. Math. Software 14 1–32
Golub G H and Van Loan C F (1996) Matrix Computations (3rd Edition) Johns Hopkins University Press, Baltimore
Lawson C L, Hanson R J, Kincaid D R and Krogh F T (1979) Basic linear algebra supbrograms for Fortran usage ACM Trans. Math. Software 5 308–325
F Chapter Contents
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F01ABF : NAG Library, Mark 26

F01 Chapter Contents
F01 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F01ABF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F01ABF calculates the accurate inverse of a real symmetric positive definite matrix, using a Cholesky factorization and iterative refinement.

2 Specification

SUBROUTINE F01ABF ( A, LDA, N, B, LDB, Z, IFAIL)
INTEGER | LDA, N, LDB, IFAIL
REAL (KIND=nag_wp) | A(LDA,N), B(LDB,N), Z(N)

3 Description

To compute the inverse X of a real symmetric positive definite matrix A, F01ABF first computes a Cholesky factorization of A as A=L LT, where L is lower triangular. An approximation to X is found by computing L-1 and then the product L-TL-1. The residual matrix R=I-AX is calculated using additional precision, and a correction D to X is found by solving L LT D=R. X is replaced by X+D, and this iterative refinement of the inverse is repeated until full machine accuracy has been obtained.

4 References

Wilkinson J H and Reinsch C (1971) Handbook for Automatic Computation II, Linear Algebra Springer–Verlag

5 Arguments

1:   A LDAN – REAL (KIND=nag_wp) arrayInput/Output
On entry: the upper triangle of the n by n positive definite symmetric matrix A. The elements of the array below the diagonal need not be set.
On exit: the lower triangle of the inverse matrix X is stored in the elements of the array below the diagonal, in rows 2 to n+1; x ij is stored in A i+1 j for i≥j. The upper triangle of the original matrix is unchanged.
2:   LDA – INTEGERInput
On entry: the first dimension of the array A as declared in the (sub)program from which F01ABF is called.
Constraint: LDA≥N+1.
3:   N – INTEGERInput
On entry: n, the order of the matrix A.
Constraint: N≥1.
4:   B LDBN – REAL (KIND=nag_wp) arrayOutput
On exit: the lower triangle of the inverse matrix X, with x ij stored in B ij, for i≥j.
5:   LDB – INTEGERInput
On entry: the first dimension of the array B as declared in the (sub)program from which F01ABF is called.
Constraint: LDB≥N.
6:   Z N – REAL (KIND=nag_wp) arrayWorkspace
7:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
The matrix A is not positive definite, possibly due to rounding errors.
IFAIL=2
The refinement process fails to converge, i.e., the matrix A is ill-conditioned.
IFAIL=3
N<1 , or LDA<N+1 , or LDB<N .
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

The computed inverse should be correct to full machine accuracy. For a detailed error analysis see page 40 of Wilkinson and Reinsch (1971).

8 Parallelism and Performance

F01ABF is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
F01ABF makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The time taken by F01ABF is approximately proportional to n 3.

10 Example

This example finds the inverse of the 4 by 4 matrix:
5 7 6 5 7 10 8 7 6 8 10 9 5 7 9 10 .

10.1 Program Text

Program Text (f01abfe.f90)

10.2 Program Data

Program Data (f01abfe.d)

10.3 Program Results

Program Results (f01abfe.r)

F01 Chapter Contents
F01 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F01ADF : NAG Library, Mark 26

F01 Chapter Contents
F01 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F01ADF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F01ADF calculates the approximate inverse of a real symmetric positive definite matrix, using a Cholesky factorization.

2 Specification

SUBROUTINE F01ADF ( N, A, LDA, IFAIL)
INTEGER | N, LDA, IFAIL
REAL (KIND=nag_wp) | A(LDA,*)

3 Description

To compute the inverse X of a real symmetric positive definite matrix A, F01ADF first computes a Cholesky factorization of A as A=L LT, where L is lower triangular. It then computes L-1 and finally forms X as the product L-TL-1.

4 References

Wilkinson J H and Reinsch C (1971) Handbook for Automatic Computation II, Linear Algebra Springer–Verlag

5 Arguments

1:   N – INTEGERInput
On entry: n, the order of the matrix A.
Constraint: N≥0.
2:   A LDA* – REAL (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array A must be at least max 1,N.
On entry: the upper triangle of the n by n positive definite symmetric matrix A. The elements of the array below the diagonal need not be set.
On exit: the lower triangle of the inverse matrix X is stored in the elements of the array below the diagonal, in rows 2 to n+1; x ij is stored in A i+1 j for i≥j. The upper triangle of the original matrix is unchanged.
3:   LDA – INTEGERInput
On entry: the first dimension of the array A as declared in the (sub)program from which F01ADF is called.
Constraint: LDA≥N+1.
4:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
The matrix A is not positive definite, possibly due to rounding errors.
IFAIL=2
On entry, | N<0,
or | LDA<N+1.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

The accuracy of the computed inverse depends on the conditioning of the original matrix. For a detailed error analysis see page 39 of Wilkinson and Reinsch (1971).

8 Parallelism and Performance

F01ADF is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
F01ADF makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The time taken by F01ADF is approximately proportional to n 3. F01ADF calls routines F07FDF (DPOTRF) and F07FJF (DPOTRI) from LAPACK.

10 Example

This example finds the inverse of the 4 by 4 matrix:
5 7 6 5 7 10 8 7 6 8 10 9 5 7 9 10 .

10.1 Program Text

Program Text (f01adfe.f90)

10.2 Program Data

Program Data (f01adfe.d)

10.3 Program Results

Program Results (f01adfe.r)

F01 Chapter Contents
F01 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F01BLF : NAG Library, Mark 26

F01 Chapter Contents
F01 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F01BLF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F01BLF calculates the rank and pseudo-inverse of an m by n real matrix, m≥n, using a QR factorization with column interchanges.

2 Specification

SUBROUTINE F01BLF ( M, N, T, A, LDA, AIJMAX, IRANK, INC, D, U, LDU, DU, IFAIL)
INTEGER | M, N, LDA, IRANK, INC(N), LDU, IFAIL
REAL (KIND=nag_wp) | T, A(LDA,N), AIJMAX(N), D(M), U(LDU,N), DU(N)

3 Description

Householder's factorization with column interchanges is used in the decomposition F=QU, where F is A with its columns permuted, Q is the first r columns of an m by m orthogonal matrix and U is an r by n upper-trapezoidal matrix of rank r. The pseudo-inverse of F is given by X where
X=UTU UT-1QT.
If the matrix is found to be of maximum rank, r=n, U is a nonsingular n by n upper-triangular matrix and the pseudo-inverse of F simplifies to X=U-1QT. The transpose of the pseudo-inverse of A is overwritten on A.

4 References

Peters G and Wilkinson J H (1970) The least squares problem and pseudo-inverses Comput. J. 13 309–316
Wilkinson J H and Reinsch C (1971) Handbook for Automatic Computation II, Linear Algebra Springer–Verlag

5 Arguments

1:   M – INTEGERInput
2:   N – INTEGERInput
On entry: m and n, the number of rows and columns in the matrix A.
Constraint: M≥N.
3:   T – REAL (KIND=nag_wp)Input
On entry: the tolerance used to decide when elements can be regarded as zero (see Section 9).
4:   A LDAN – REAL (KIND=nag_wp) arrayInput/Output
On entry: the m by n rectangular matrix A.
On exit: the transpose of the pseudo-inverse of A.
5:   LDA – INTEGERInput
On entry: the first dimension of the array A as declared in the (sub)program from which F01BLF is called.
Constraint: LDA≥M.
6:   AIJMAX N – REAL (KIND=nag_wp) arrayOutput
On exit: AIJMAX i contains the element of largest modulus in the reduced matrix at the ith stage. If r<n, then only the first r+1 elements of AIJMAX have values assigned to them; the remaining elements are unused. The ratio AIJMAX 1/AIJMAX r usually gives an indication of the condition number of the original matrix (see Section 9).
7:   IRANK – INTEGEROutput
On exit: r, the rank of A as determined using the tolerance T.
8:   INC N – INTEGER arrayOutput
On exit: the record of the column interchanges in the Householder factorization.
9:   D M – REAL (KIND=nag_wp) arrayWorkspace
10:   U LDUN – REAL (KIND=nag_wp) arrayWorkspace
11:   LDU – INTEGERInput
On entry: the first dimension of the array U as declared in the (sub)program from which F01BLF is called.
Constraint: LDU≥N.
12:   DU N – REAL (KIND=nag_wp) arrayWorkspace
13:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
Inverse not found, due to an incorrect determination of IRANK (see Section 9).
IFAIL=2
Invalid tolerance, due to
(i) | T is negative, IRANK=-1;
(ii) | T too large, IRANK=0;
(iii) | T too small, IRANK>0.
IFAIL=3
On entry, M<N.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

For most matrices the pseudo-inverse is the best possible having regard to the condition of A and the choice of T. Note that only the singular value decomposition method can be relied upon to give maximum accuracy for the precision of computation used and correct determination of the condition of a matrix (see Wilkinson and Reinsch (1971)).
The computed factors Q and U satisfy the relation QU=F+E where
E 2<cε A 2+η⁢m-rn-r
in which c is a modest function of m and n, η is the value of T, and ε is the machine precision.

8 Parallelism and Performance

F01BLF is not threaded in any implementation.

9 Further Comments

The time taken by F01BLF is approximately proportional to mnr.
The most difficult practical problem is the determination of the rank of the matrix (see pages 314–315 of Peters and Wilkinson (1970)); only the singular value decomposition method gives a reliable indication of rank deficiency (see pages 134–151 of Wilkinson and Reinsch (1971) and F08KBF (DGESVD)). In F01BLF a tolerance, T, is used to recognize ‘zero’ elements in the remaining matrix at each step in the factorization. The value of T should be set at n times the bound on possible errors in individual elements of the original matrix. If the elements of A vary widely in their orders of magnitude, of course this presents severe difficulties. Sound decisions can only be made by somebody who appreciates the underlying physical problem.
If the condition number of A is 10 p we expect to get p figures wrong in the pseudo-inverse. An estimate of the condition number is usually given by AIJMAX 1/AIJMAX r.

10 Example

A complete program follows which outputs the maximum of the moduli of the ‘remaining’ elements at each step in the factorization, the rank, as determined by the given value of T, and the transposed pseudo-inverse. Data and results are given for an example which is a 6 by 5 matrix of deficient rank in which the last column is a linear combination of the other four. Setting T to ε times the norm of the matrix, the rank is correctly determined as 4 and the pseudo-inverse is computed to full implementation accuracy.

10.1 Program Text

Program Text (f01blfe.f90)

10.2 Program Data

Program Data (f01blfe.d)

10.3 Program Results

Program Results (f01blfe.r)

F01 Chapter Contents
F01 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F01BRF : NAG Library, Mark 26

F01 Chapter Contents
F01 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F01BRF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
▸▿ 9 Further Comments
9.1 Timing
9.2 Scaling
9.3 Singular and Rectangular Systems
9.4 Duplicated Nonzeros
9.5 Determinant
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F01BRF factorizes a real sparse matrix. The routine either forms the LU factorization of a permutation of the entire matrix, or, optionally, first permutes the matrix to block lower triangular form and then only factorizes the diagonal blocks.

2 Specification

SUBROUTINE F01BRF ( N, NZ, A, LICN, IRN, LIRN, ICN, PIVOT, IKEEP, IW, W, LBLOCK, GROW, ABORT, IDISP, IFAIL)
INTEGER | N, NZ, LICN, IRN(LIRN), LIRN, ICN(LICN), IKEEP(5*N), IW(8*N), IDISP(10), IFAIL
REAL (KIND=nag_wp) | A(LICN), PIVOT, W(N)
LOGICAL | LBLOCK, GROW, ABORT(4)

3 Description

Given a real sparse matrix A, F01BRF may be used to obtain the LU factorization of a permutation of A,
PAQ=LU
where P and Q are permutation matrices, L is unit lower triangular and U is upper triangular. The routine uses a sparse variant of Gaussian elimination, and the pivotal strategy is designed to compromise between maintaining sparsity and controlling loss of accuracy through round-off.
Optionally the routine first permutes the matrix into block lower triangular form and then only factorizes the diagonal blocks. For some matrices this gives a considerable saving in storage and execution time.
Extensive data checks are made; duplicated nonzeros can be accumulated.
The factorization is intended to be used by F04AXF to solve sparse systems of linear equations Ax=b or AT x=b. If several matrices of the same sparsity pattern are to be factorized, F01BSF should be used for the second and subsequent matrices.
The method is fully described in Duff (1977).
A more recent algorithm for the same calculation is provided by F11MEF.

4 References

Duff I S (1977) MA28 – a set of Fortran subroutines for sparse unsymmetric linear equations AERE Report R8730 HMSO

5 Arguments

1:   N – INTEGERInput
On entry: n, the order of the matrix A.
Constraint: N>0.
2:   NZ – INTEGERInput
On entry: the number of nonzero elements in the matrix A.
Constraint: NZ>0.
3:   A LICN – REAL (KIND=nag_wp) arrayInput/Output
On entry: A i, for i=1,2,…,NZ, must contain the nonzero elements of the sparse matrix A. They can be in any order since F01BRF will reorder them.
On exit: the nonzero elements in the LU factorization. The array must not be changed by you between a call of F01BRF and a call of F04AXF.
4:   LICN – INTEGERInput
On entry: the dimension of the arrays A and ICN as declared in the (sub)program from which F01BRF is called. Since the factorization is returned in A and ICN, LICN should be large enough to accommodate this and should ordinarily be 2 to 4 times as large as NZ.
Constraint: LICN≥NZ.
5:   IRN LIRN – INTEGER arrayInput/Output
On entry: IRN i, for i=1,2,…,NZ, must contain the row index of the nonzero element stored in A i.
On exit: IRN is overwritten and is not needed for subsequent calls of F01BSF or F04AXF.
6:   LIRN – INTEGERInput
On entry: the dimension of the array IRN as declared in the (sub)program from which F01BRF is called. It need not be as large as LICN; normally it will not need to be very much greater than NZ.
Constraint: LIRN≥NZ.
7:   ICN LICN – INTEGER arrayCommunication Array
ICN i, for i=1,2,…,NZ, must contain, on entry, the column index of the nonzero element stored in A i. ICN contains, on exit, the column indices of the nonzero elements in the factorization. The array must not be changed by you between a call of F01BRF and subsequent calls of F01BSF or F04AXF.
8:   PIVOT – REAL (KIND=nag_wp)Input
On entry: should have a value in the range 0.0≤PIVOT≤0.9999 and is used to control the choice of pivots. If PIVOT<0.0, the value 0.0 is assumed, and if PIVOT>0.9999, the value 0.9999 is assumed. When searching a row for a pivot, any element is excluded which is less than PIVOT times the largest of those elements in the row available as pivots. Thus decreasing PIVOT biases the algorithm to maintaining sparsity at the expense of stability.
Suggested value: PIVOT=0.1 has been found to work well on test examples.
9:   IKEEP 5×N – INTEGER arrayCommunication Array
On exit: indexing information about the factorization.
You must not change IKEEP between a call of F01BRF and subsequent calls to F01BSF or F04AXF.
10:   IW 8×N – INTEGER arrayWorkspace
11:   W N – REAL (KIND=nag_wp) arrayOutput
On exit: if GROW=.TRUE., W 1 contains an estimate (an upper bound) of the increase in size of elements encountered during the factorization (see GROW); the rest of the array is used as workspace.
If GROW=.FALSE., the array is not used.
12:   LBLOCK – LOGICALInput
On entry: if LBLOCK=.TRUE., the matrix is preordered into block lower triangular form before the LU factorization is performed; otherwise the entire matrix is factorized.
Suggested value: LBLOCK=.TRUE. unless the matrix is known to be irreducible, or is singular and an upper bound on the rank is required.
13:   GROW – LOGICALInput
On entry: if GROW=.TRUE., then on exit W 1 contains an estimate (an upper bound) of the increase in size of elements encountered during the factorization. If the matrix is well-scaled (see Section 9.2), then a high value for W 1 indicates that the LU factorization may be inaccurate and you should be wary of the results and perhaps increase the argument PIVOT for subsequent runs (see Section 7).
Suggested value: GROW=.TRUE..
14:   ABORT 4 – LOGICAL arrayInput
On entry: if ABORT 1=.TRUE., F01BRF will exit immediately on detecting a structural singularity (one that depends on the pattern of nonzeros) and return IFAIL=1; otherwise it will complete the factorization (see Section 9.3).
If ABORT 2=.TRUE., F01BRF will exit immediately on detecting a numerical singularity (one that depends on the numerical values) and return IFAIL=2; otherwise it will complete the factorization (see Section 9.3).
If ABORT 3=.TRUE., F01BRF will exit immediately (with IFAIL=5) when the arrays A and ICN are filled up by the previously factorized, active and unfactorized parts of the matrix; otherwise it continues so that better guidance on necessary array sizes can be given in IDISP 6 and IDISP 7, and will exit with IFAIL in the range 4 to 6. Note that there is always an immediate error exit if the array IRN is too small.
If ABORT 4=.TRUE., F01BRF exits immediately (with IFAIL=13) if it finds duplicate elements in the input matrix.
If ABORT 4=.FALSE., F01BRF proceeds using a value equal to the sum of the duplicate elements. In either case details of each duplicate element are output on the current advisory message unit (see X04ABF), unless suppressed by the value of IFAIL on entry.
Suggested values:
  • ABORT 1=.TRUE.;
  • ABORT 2=.TRUE.;
  • ABORT 3=.FALSE.;
  • ABORT 4=.TRUE..
15:   IDISP 10 – INTEGER arrayCommunication Array
On exit: contains information about the factorization.
IDISP 1 and IDISP 2 indicate the position in arrays A and ICN of the first and last elements in the LU factorization of the diagonal blocks. (IDISP 2 gives the number of nonzeros in the factorization.) IDISP 1 and IDISP 2 must not be changed by you between a call of F01BRF and subsequent calls to F01BSF or F04AXF.
IDISP 3 and IDISP 4 monitor the adequacy of ‘elbow room’ in the arrays IRN and A (and ICN) respectively, by giving the number of times that the data in these arrays has been compressed during the factorization to release more storage. If either IDISP 3 or IDISP 4 is quite large (say greater than 10), it will probably pay you to increase the size of the corresponding array(s) for subsequent runs. If either is very low or zero, then you can perhaps save storage by reducing the size of the corresponding array(s).
IDISP 5, when LBLOCK=.FALSE., gives an upper bound on the rank of the matrix; when LBLOCK=.TRUE., gives an upper bound on the sum of the ranks of the lower triangular blocks.
IDISP 6 and IDISP 7 give the minimum size of arrays IRN and A (and ICN) respectively which would enable a successful run on an identical matrix (but some ‘elbow-room’ should be allowed – see Section 9).
IDISP 8 to 10 are only used if LBLOCK=.TRUE..
  • IDISP 8 gives the structural rank of the matrix.
  • IDISP 9 gives the number of diagonal blocks.
  • IDISP 10 gives the size of the largest diagonal block.
You must not change IDISP between a call of F01BRF and subsequent calls to F01BSF or F04AXF.
16:   IFAIL – INTEGERInput/Output
For this routine, the normal use of IFAIL is extended to control the printing of error and warning messages as well as specifying hard or soft failure (see Section 3.4 in How to Use the NAG Library and its Documentation).
On entry: IFAIL must be set to a value with the decimal expansion cba, where each of the decimal digits c, b and a must have a value of 0 or 1.
a=0 | specifies hard failure, otherwise soft failure;
b=0 | suppresses error messages, otherwise error messages will be printed (see Section 6);
c=0 | suppresses warning messages, otherwise warning messages will be printed (see Section 6).
The recommended value for inexperienced users is 110 (i.e., hard failure with all messages printed).
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=-2
Successful factorization of a numerically singular matrix (which may also be structurally singular) (see Section 9.3).
IFAIL=-1
Successful factorization of a structurally singular matrix (see Section 9.3).
IFAIL=1
The matrix is structurally singular and the factorization has been abandoned (ABORT 1 was .TRUE. on entry).
IFAIL=2
The matrix is numerically singular and the factorization has been abandoned (ABORT 2 was .TRUE. on entry).
IFAIL=3
LIRN is too small: there is not enough space in the array IRN to continue the factorization. You are recommended to try again with LIRN (and the length of IRN) equal to at least IDISP 6+N/2.
IFAIL=4
LICN is much too small: there is much too little space in the arrays A and ICN to continue the factorization.
IFAIL=5
LICN is too small: there is not enough space in the arrays A and ICN to store the factorization. If ABORT 3 was .FALSE. on entry, the factorization has been completed but some of the LU factors have been discarded to create space; IDISP 7 then gives the minimum value of LICN (i.e., the minimum length of A and ICN) required for a successful factorization of the same matrix.
IFAIL=6
LICN and LIRN are both too small: effectively this is a combination of IFAIL=3 and 5 (with ABORT 3=.FALSE.).
IFAIL=7
LICN is too small: there is not enough space in the arrays A and ICN for the permutation to block triangular form.
IFAIL=8
On entry, N≤0.
IFAIL=9
On entry, NZ≤0.
IFAIL=10
On entry, LICN<NZ.
IFAIL=11
On entry, LIRN<NZ.
IFAIL=12
On entry, an element of the input matrix has a row or column index (i.e., an element of IRN or ICN) outside the range 1 to N.
IFAIL=13
Duplicate elements have been found in the input matrix and the factorization has been abandoned (ABORT 4=.TRUE. on entry).
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

The factorization obtained is exact for a perturbed matrix whose i,jth element differs from a ij by less than 3 ερ m ij where ε is the machine precision, ρ is the growth value returned in W 1 if GROW=.TRUE., and m ij the number of Gaussian elimination operations applied to element i,j. The value of m ij is not greater than n and is usually much less. Small ρ values therefore guarantee accurate results, but unfortunately large ρ values may give a very pessimistic indication of accuracy.

8 Parallelism and Performance

F01BRF is not threaded in any implementation.

9 Further Comments

9.1 Timing

The time required may be estimated very roughly from the number τ of nonzeros in the factorized form (output as IDISP 2) and for F01BRF and its associates is
F01BRF: | 5⁢τ 2/n units
F01BSF: | τ 2/n units
F04AXF: | 2 τ units
where our unit is the time for the inner loop of a full matrix code (e.g., solving a full set of equations takes about 13 n 3 units). Note that the faster F01BSF time makes it well worthwhile to use this for a sequence of problems with the same pattern.
It should be appreciated that τ varies widely from problem to problem. For network problems it may be little greater than NZ, the number of nonzeros in A; for discretization of two-dimensional and three-dimensional partial differential equations it may be about 3 n log 2⁡n and 12 n 5/3, respectively.
The time taken by F01BRF to find the block lower triangular form (LBLOCK=.TRUE.) is typically 5–15% of the time taken by the routine when it is not found (LBLOCK=.FALSE.). If the matrix is irreducible (IDISP 9=1 after a call with LBLOCK=.TRUE.) then this time is wasted. Otherwise, particularly if the largest block is small (IDISP 10≪n), the consequent savings are likely to be greater.
The time taken to estimate growth (GROW=.TRUE.) is typically under 20% of the overall time.
The overall time may be substantially increased if there is inadequate ‘elbow-room’ in the arrays A, IRN and ICN. When the sizes of the arrays are minimal (IDISP 6 and IDISP 7) it can execute as much as three times slower. Values of IDISP 3 and IDISP 4 greater than about 10 indicate that it may be worthwhile to increase array sizes.

9.2 Scaling

The use of a relative pivot tolerance PIVOT essentially presupposes that the matrix is well-scaled, i.e., that the matrix elements are broadly comparable in size. Practical problems are often naturally well-scaled but particular care is needed for problems containing mixed types of variables (for example millimetres and neutron fluxes).

9.3 Singular and Rectangular Systems

It is envisaged that F01BRF will almost always be called for square nonsingular matrices and that singularity indicates an error condition. However, even if the matrix is singular it is possible to complete the factorization. It is even possible for F04AXF to solve a set of equations whose matrix is singular provided the set is consistent.
Two forms of singularity are possible. If the matrix would be singular for any values of the nonzeros (e.g., if it has a whole row of zeros), then we say it is structurally singular, and continue only if ABORT 1=.FALSE.. If the matrix is nonsingular by virtue of the particular values of the nonzeros, then we say that it is numerically singular and continue only if ABORT 2=.FALSE., in which case an upper bound on the rank of the matrix is returned in IDISP 5 when LBLOCK=.FALSE..
Rectangular matrices may be treated by setting N to the larger of the number of rows and numbers of columns and setting ABORT 1=.FALSE..
Note: the soft failure option should be used (last digit of IFAIL=1) if you wish to factorize singular matrices with ABORT 1 or ABORT 2 set to .FALSE..

9.4 Duplicated Nonzeros

The matrix A may consist of a sum of contributions from different sub-systems (for example finite elements). In such cases you may rely on F01BRF to perform assembly, since duplicated elements are summed.

9.5 Determinant

The following code may be used to compute the determinant of A (as the real variable DET) after a call of F01BRF:
   DET = 1.0
   ID = IDISP(1)
   DO 10 I = 1, N
      IDG = ID + IKEEP(3*N+I)
      DET = DET*A(IDG)
      IF (IKEEP(N+I).NE.I)DET = -DET
      IF (IKEEP(2*N+I).NE.I)DET = -DET
      ID = ID + IKEEP(I)
10 CONTINUE

10 Example

This example factorizes the real sparse matrix:
5 0 0 0 0 0 0 2 -1 2 0 0 0 0 3 0 0 0 -2 0 0 1 1 0 -1 0 0 -1 2 -3 -1 -1 0 0 0 6 .
This example program simply prints out some information about the factorization as returned by F01BRF in W 1 and IDISP. Normally the call of F01BRF would be followed by a call of F04AXF (see Section 10 in F04AXF).

10.1 Program Text

Program Text (f01brfe.f90)

10.2 Program Data

Program Data (f01brfe.d)

10.3 Program Results

Program Results (f01brfe.r)

F01 Chapter Contents
F01 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F01BSF : NAG Library, Mark 26

F01 Chapter Contents
F01 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F01BSF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F01BSF factorizes a real sparse matrix using the pivotal sequence previously obtained by F01BRF when a matrix of the same sparsity pattern was factorized.

2 Specification

SUBROUTINE F01BSF ( N, NZ, A, LICN, IVECT, JVECT, ICN, IKEEP, IW, W, GROW, ETA, RPMIN, ABORT, IDISP, IFAIL)
INTEGER | N, NZ, LICN, IVECT(NZ), JVECT(NZ), ICN(LICN), IKEEP(5*N), IW(5*N), IDISP(2), IFAIL
REAL (KIND=nag_wp) | A(LICN), W(N), ETA, RPMIN
LOGICAL | GROW, ABORT

3 Description

F01BSF accepts as input a real sparse matrix of the same sparsity pattern as a matrix previously factorized by a call of F01BRF. It first applies to the matrix the same permutations as were used by F01BRF, both for permutation to block triangular form and for pivoting, and then performs Gaussian elimination to obtain the LU factorization of the diagonal blocks.
Extensive data checks are made; duplicated nonzeros can be accumulated.
The factorization is intended to be used by F04AXF to solve sparse systems of linear equations Ax=b or AT x=b.
F01BSF is much faster than F01BRF and in some applications it is expected that there will be many calls of F01BSF for each call of F01BRF.
The method is fully described in Duff (1977).
A more recent algorithm for the same calculation is provided by F11MEF.

4 References

Duff I S (1977) MA28 – a set of Fortran subroutines for sparse unsymmetric linear equations AERE Report R8730 HMSO

5 Arguments

1:   N – INTEGERInput
On entry: n, the order of the matrix A.
Constraint: N>0.
2:   NZ – INTEGERInput
On entry: the number of nonzero elements in the matrix A.
Constraint: NZ>0.
3:   A LICN – REAL (KIND=nag_wp) arrayInput/Output
On entry: A i, for i=1,2,…,NZ, must contain the nonzero elements of the sparse matrix A. They can be in any order since F01BSF will reorder them.
On exit: the nonzero elements in the LU factorization. The array must not be changed by you between a call of F01BSF and a call of F04AXF.
4:   LICN – INTEGERInput
On entry: the dimension of the arrays A and ICN as declared in the (sub)program from which F01BSF is called. It should have the same value as it had for F01BRF.
Constraint: LICN≥NZ.
5:   IVECT NZ – INTEGER arrayInput
6:   JVECT NZ – INTEGER arrayInput
On entry: IVECT i and JVECT i, for i=1,2,…,NZ, must contain the row index and the column index respectively of the nonzero element stored in A i.
7:   ICN LICN – INTEGER arrayInput
ICN contains, on entry, the same information as output by F01BRF. It must not be changed by you between a call of F01BSF and a call of F04AXF.
ICN is used as internal workspace prior to being restored on exit and hence is unchanged.
8:   IKEEP 5×N – INTEGER arrayCommunication Array
On entry: the same indexing information about the factorization as output in IKEEP by F01BRF.
You must not change IKEEP between a call of F01BSF and subsequent calls to F04AXF.
9:   IW 5×N – INTEGER arrayWorkspace
10:   W N – REAL (KIND=nag_wp) arrayOutput
On exit: if GROW=.TRUE., W 1 contains an estimate (an upper bound) of the increase in size of elements encountered during the factorization (see GROW); the rest of the array is used as workspace.
If GROW=.FALSE., the array is not used.
11:   GROW – LOGICALInput
On entry: if GROW=.TRUE., then on exit W 1 contains an estimate (an upper bound) of the increase in size of elements encountered during the factorization. If the matrix is well-scaled (see Section 9), then a high value for W 1 indicates that the LU factorization may be inaccurate and you should be wary of the results and perhaps increase the argument PIVOT for subsequent runs (see Section 7).
12:   ETA – REAL (KIND=nag_wp)Input
On entry: the relative pivot threshold below which an error diagnostic is provoked and IFAIL is set to IFAIL=7. If ETA is greater than 1.0, then no check on pivot size is made.
Suggested value: ETA=10-4.
13:   RPMIN – REAL (KIND=nag_wp)Output
On exit: if ETA is less than 1.0, then RPMIN gives the smallest ratio of the pivot to the largest element in the row of the corresponding upper triangular factor thus monitoring the stability of the factorization. If RPMIN is very small it may be advisable to perform a new factorization using F01BRF.
14:   ABORT – LOGICALInput
On entry: if ABORT=.TRUE., F01BSF exits immediately (with IFAIL=8) if it finds duplicate elements in the input matrix.
If ABORT=.FALSE., F01BSF proceeds using a value equal to the sum of the duplicate elements.
In either case details of each duplicate element are output on the current advisory message unit (see X04ABF), unless suppressed by the value of IFAIL on entry.
Suggested value: ABORT=.TRUE..
15:   IDISP 2 – INTEGER arrayCommunication Array
On entry: IDISP 1 and IDISP 2 must be as output in IDISP by the previous call of F01BRF.
16:   IFAIL – INTEGERInput/Output
For this routine, the normal use of IFAIL is extended to control the printing of error and warning messages as well as specifying hard or soft failure (see Section 3.4 in How to Use the NAG Library and its Documentation).
On entry: IFAIL must be set to a value with the decimal expansion cba, where each of the decimal digits c, b and a must have a value of 0 or 1.
a=0 | specifies hard failure, otherwise soft failure;
b=0 | suppresses error messages, otherwise error messages will be printed (see Section 6);
c=0 | suppresses warning messages, otherwise warning messages will be printed (see Section 6).
The recommended value for inexperienced users is 110 (i.e., hard failure with all messages printed).
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, N≤0.
IFAIL=2
On entry, NZ≤0.
IFAIL=3
On entry, LICN<NZ.
IFAIL=4
On entry, an element of the input matrix has a row or column index (i.e., an element of IVECT or JVECT) outside the range 1 to N.
IFAIL=5
The input matrix is incompatible with the matrix factorized by the previous call of F01BRF (see Section 9).
IFAIL=6
The input matrix is numerically singular.
IFAIL=7
A very small pivot has been detected (see Section 5, ETA). The factorization has been completed but is potentially unstable.
IFAIL=8
Duplicate elements have been found in the input matrix and the factorization has been abandoned (ABORT=.TRUE. on entry).
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

The factorization obtained is exact for a perturbed matrix whose i,jth element differs from a ij by less than 3 ερ m ij where ε is the machine precision, ρ is the growth value returned in W 1 if GROW=.TRUE., and m ij the number of Gaussian elimination operations applied to element i,j.
If ρ=W 1 is very large or RPMIN is very small, then a fresh call of F01BRF is recommended.

8 Parallelism and Performance

F01BSF is not threaded in any implementation.

9 Further Comments

If you have a sequence of problems with the same sparsity pattern then F01BSF is recommended after F01BRF has been called for one such problem. It is typically 4 to 7 times faster but is potentially unstable since the previous pivotal sequence is used. Further details on timing are given in the document for F01BRF.
If growth estimation is performed (GROW=.TRUE.), then the time increases by between 5% and 10%. Pivot size monitoring (ETA≤1.0) involves a similar overhead.
We normally expect this routine to be entered with a matrix having the same pattern of nonzeros as was earlier presented to F01BRF. However there is no record of this pattern, but rather a record of the pattern including all fill-ins. Therefore we permit additional nonzeros in positions corresponding to fill-ins.
If singular matrices are being treated then it is also required that the present matrix be sufficiently like the previous one for the same permutations to be suitable for factorization with the same set of zero pivots.

10 Example

This example factorizes the real sparse matrices
5 0 0 0 0 0 0 2 -1 2 0 0 0 0 3 0 0 0 -2 0 0 1 1 0 -1 0 0 -1 2 -3 -1 -1 0 0 0 6
and
10 0 0 0 0 0 0 12 -3 -1 0 0 0 0 15 0 0 0 -2 0 0 10 -1 0 -1 0 0 -5 1 -1 -1 -2 0 0 0 6 .
This example program simply prints the values of W 1 and RPMIN returned by F01BSF. Normally the calls of F01BRF and F01BSF would be followed by calls of F04AXF.

10.1 Program Text

Program Text (f01bsfe.f90)

10.2 Program Data

Program Data (f01bsfe.d)

10.3 Program Results

Program Results (f01bsfe.r)

F01 Chapter Contents
F01 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F01BUF : NAG Library, Mark 26

F01 Chapter Contents
F01 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F01BUF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F01BUF performs a ULD LTUT decomposition of a real symmetric positive definite band matrix.

2 Specification

SUBROUTINE F01BUF ( N, M1, K, A, LDA, W, IFAIL)
INTEGER | N, M1, K, LDA, IFAIL
REAL (KIND=nag_wp) | A(LDA,N), W(M1)

3 Description

The symmetric positive definite matrix A, of order n and bandwidth 2 m+1, is divided into the leading principal sub-matrix of order k and its complement, where m≤k≤n. A UD UT decomposition of the latter and an LD LT decomposition of the former are obtained by means of a sequence of elementary transformations, where U is unit upper triangular, L is unit lower triangular and D is diagonal. Thus if k=n, an LD LT decomposition of A is obtained.
This routine is specifically designed to precede F01BVF for the transformation of the symmetric-definite eigenproblem Ax=λBx by the method of Crawford where A and B are of band form. In this context, k is chosen to be close to n/2 and the decomposition is applied to the matrix B.

4 References

Wilkinson J H (1965) The Algebraic Eigenvalue Problem Oxford University Press, Oxford
Wilkinson J H and Reinsch C (1971) Handbook for Automatic Computation II, Linear Algebra Springer–Verlag

5 Arguments

1:   N – INTEGERInput
On entry: n, the order of the matrix A.
2:   M1 – INTEGERInput
On entry: m+1, where m is the number of nonzero superdiagonals in A. Normally M1≪N.
3:   K – INTEGERInput
On entry: k, the change-over point in the decomposition.
Constraint: M1-1≤K≤N.
4:   A LDAN – REAL (KIND=nag_wp) arrayInput/Output
On entry: the upper triangle of the n by n symmetric band matrix A, with the diagonal of the matrix stored in the m+1th row of the array, and the m superdiagonals within the band stored in the first m rows of the array. Each column of the matrix is stored in the corresponding column of the array. For example, if n=6 and m=2, the storage scheme is
* * a 13 a 24 a 35 a 46 * a 12 a 23 a 34 a 45 a 56 a 11 a 22 a 33 a 44 a 55 a 66
Elements in the top left corner of the array are not used. The following code assigns the matrix elements within the band to the correct elements of the array:
    DO 20 J = 1, N
       DO 10 I = MAX(1,J-M1+1), J
          A(I-J+M1,J) = matrix(I,J)
 10    CONTINUE
 20 CONTINUE
On exit: A is overwritten by the corresponding elements of L, D and U.
5:   LDA – INTEGERInput
On entry: the first dimension of the array A as declared in the (sub)program from which F01BUF is called.
Constraint: LDA≥M1.
6:   W M1 – REAL (KIND=nag_wp) arrayWorkspace
7:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, K<M1-1 or K>N.
IFAIL=2
IFAIL=3
The matrix A is not positive definite, perhaps as a result of rounding errors, giving an element of D which is zero or negative. IFAIL=3 when the failure occurs in the leading principal sub-matrix of order K and IFAIL=2 when it occurs in the complement.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

The Cholesky decomposition of a positive definite matrix is known for its remarkable numerical stability (see Wilkinson (1965)). The computed U, L and D satisfy the relation ULD LTUT=A+E where the 2-norms of A and E are related by E≤c m+1 2 ε A where c is a constant of order unity and ε is the machine precision. In practice, the error is usually appreciably smaller than this.

8 Parallelism and Performance

F01BUF is not threaded in any implementation.

9 Further Comments

The time taken by F01BUF is approximately proportional to n m 2+3 nm.
This routine is specifically designed for use as the first stage in the solution of the generalized symmetric eigenproblem Ax=λBx by Crawford's method which preserves band form in the transformation to a similar standard problem. In this context, for maximum efficiency, k should be chosen as the multiple of m nearest to n/2.
The matrix U is such that U-1 A U-T is diagonal in its last n-k rows and columns, L is such that L-1U-1 A U-TL-T=D and D is diagonal. To find U, L and D where A=ULD LTUT requires nm m+3/2-m m+1m+2/3 multiplications and divisions which, is independent of k.

10 Example

This example finds a ULD LTUT decomposition of the real symmetric positive definite matrix
3 -9 6 -9 31 -2 -4 6 -2 123 -66 15 -4 -66 145 -24 4 15 -24 61 -74 -18 4 -74 98 24 -18 24 6 .

10.1 Program Text

Program Text (f01bufe.f90)

10.2 Program Data

Program Data (f01bufe.d)

10.3 Program Results

Program Results (f01bufe.r)

F01 Chapter Contents
F01 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F01BVF : NAG Library, Mark 26

F01 Chapter Contents
F01 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F01BVF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F01BVF transforms the generalized symmetric-definite eigenproblem Ax=λBx to the equivalent standard eigenproblem Cy=λy, where A, B and C are symmetric band matrices and B is positive definite. B must have been decomposed by F01BUF.

2 Specification

SUBROUTINE F01BVF ( N, MA1, MB1, M3, K, A, LDA, B, LDB, V, LDV, W, IFAIL)
INTEGER | N, MA1, MB1, M3, K, LDA, LDB, LDV, IFAIL
REAL (KIND=nag_wp) | A(LDA,N), B(LDB,N), V(LDV,M3), W(M3)

3 Description

A is a symmetric band matrix of order n and bandwidth 2 mA+1. The positive definite symmetric band matrix B, of order n and bandwidth 2 mB+1, must have been previously decomposed by F01BUF as ULD LTUT. F01BVF applies U, L and D to A, mA rows at a time, restoring the band form of A at each stage by plane rotations. The argument k defines the change-over point in the decomposition of B as used by F01BUF and is also used as a change-over point in the transformations applied by this routine. For maximum efficiency, k should be chosen to be the multiple of mA nearest to n/2. The resulting symmetric band matrix C is overwritten on A. The eigenvalues of C, and thus of the original problem, may be found using F08HEF (DSBTRD) and F08JFF (DSTERF). For selected eigenvalues, use F08HEF (DSBTRD) and F08JJF (DSTEBZ).

4 References

Crawford C R (1973) Reduction of a band-symmetric generalized eigenvalue problem Comm. ACM 16 41–44

5 Arguments

1:   N – INTEGERInput
On entry: n, the order of the matrices A, B and C.
2:   MA1 – INTEGERInput
On entry: mA+1, where mA is the number of nonzero superdiagonals in A. Normally MA1≪N.
3:   MB1 – INTEGERInput
On entry: mB+1, where mB is the number of nonzero superdiagonals in B.
Constraint: MB1≤MA1.
4:   M3 – INTEGERInput
On entry: the value of 3 mA+mB.
5:   K – INTEGERInput
On entry: k, the change-over point in the transformations. It must be the same as the value used by F01BUF in the decomposition of B.
Suggested value: the optimum value is the multiple of mA nearest to n/2.
Constraint: MB1-1≤K≤N.
6:   A LDAN – REAL (KIND=nag_wp) arrayInput/Output
On entry: the upper triangle of the n by n symmetric band matrix A, with the diagonal of the matrix stored in the mA+1th row of the array, and the mA superdiagonals within the band stored in the first mA rows of the array. Each column of the matrix is stored in the corresponding column of the array. For example, if n=6 and mA=2, the storage scheme is
* * a 13 a 24 a 35 a 46 * a 12 a 23 a 34 a 45 a 56 a 11 a 22 a 33 a 44 a 55 a 66
Elements in the top left corner of the array need not be set. The following code assigns the matrix elements within the band to the correct elements of the array:
    DO 20 J = 1, N
       DO 10 I = MAX(1,J-MA1+1), J
          A(I-J+MA1,J) = matrix (I,J)
 10    CONTINUE
 20 CONTINUE
On exit: is overwritten by the corresponding elements of C.
7:   LDA – INTEGERInput
On entry: the first dimension of the array A as declared in the (sub)program from which F01BVF is called.
Constraint: LDA≥MA1.
8:   B LDBN – REAL (KIND=nag_wp) arrayInput/Output
On entry: the elements of the decomposition of matrix B as returned by F01BUF.
On exit: the elements of B will have been permuted.
9:   LDB – INTEGERInput
On entry: the first dimension of the array B as declared in the (sub)program from which F01BVF is called.
Constraint: LDB≥MB1.
10:   V LDVM3 – REAL (KIND=nag_wp) arrayWorkspace
11:   LDV – INTEGERInput
On entry: the first dimension of the array V as declared in the (sub)program from which F01BVF is called.
Constraint: LDV≥mA+mB.
12:   W M3 – REAL (KIND=nag_wp) arrayWorkspace
13:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, MB1>MA1.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

In general the computed system is exactly congruent to a problem A+E x=λ B+F x, where E and F are of the order of εκ BA and εκ BB respectively, where κ B is the condition number of B with respect to inversion and ε is the machine precision. This means that when B is positive definite but not well-conditioned with respect to inversion, the method, which effectively involves the inversion of B, may lead to a severe loss of accuracy in well-conditioned eigenvalues.

8 Parallelism and Performance

F01BVF is not threaded in any implementation.

9 Further Comments

The time taken by F01BVF is approximately proportional to n 2 mB 2 and the distance of k from n/2, e.g., k=n/4 and k=3 n/4 take 502% longer.
When B is positive definite and well-conditioned with respect to inversion, the generalized symmetric eigenproblem can be reduced to the standard symmetric problem Py=λy where P=L-1 A L-T and B=L LT, the Cholesky factorization.
When A and B are of band form, especially if the bandwidth is small compared with the order of the matrices, storage considerations may rule out the possibility of working with P since it will be a full matrix in general. However, for any factorization of the form B=S ST, the generalized symmetric problem reduces to the standard form
S-1 A S-T ST x=λ ST x
and there does exist a factorization such that S-1 A S-T is still of band form (see Crawford (1973)). Writing
C=S-1 A S-T  and  y=ST x
the standard form is Cy=λy and the bandwidth of C is the maximum bandwidth of A and B.
Each stage in the transformation consists of two phases. The first reduces a leading principal sub-matrix of B to the identity matrix and this introduces nonzero elements outside the band of A. In the second, further transformations are applied which leave the reduced part of B unaltered and drive the extra elements upwards and off the top left corner of A. Alternatively, B may be reduced to the identity matrix starting at the bottom right-hand corner and the extra elements introduced in A can be driven downwards.
The advantage of the ULD LTUT decomposition of B is that no extra elements have to be pushed over the whole length of A. If k is taken as approximately n/2, the shifting is limited to halfway. At each stage the size of the triangular bumps produced in A depends on the number of rows and columns of B which are eliminated in the first phase and on the bandwidth of B. The number of rows and columns over which these triangles are moved at each step in the second phase is equal to the bandwidth of A.
In this routine, A is defined as being at least as wide as B and must be filled out with zeros if necessary as it is overwritten with C. The number of rows and columns of B which are effectively eliminated at each stage is mA.

10 Example

This example finds the three smallest eigenvalues of Ax=λBx, where
A= 11 12 12 12 13 13 13 14 14 14 15 15 15 16 16 16 17 17 17 18 18 18 19 19 19
B= 101 22 22 102 23 23 103 24 24 104 25 25 105 26 26 106 27 27 107 28 28 108 29 29 109 .

10.1 Program Text

Program Text (f01bvfe.f90)

10.2 Program Data

Program Data (f01bvfe.d)

10.3 Program Results

Program Results (f01bvfe.r)

F01 Chapter Contents
F01 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F01CKF : NAG Library, Mark 26

F01 Chapter Contents
F01 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F01CKF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F01CKF returns with the result of the multiplication of two matrices B and C in the matrix A, with the option to overwrite B or C.

2 Specification

SUBROUTINE F01CKF ( A, B, C, N, P, M, Z, IZ, OPT, IFAIL)
INTEGER | N, P, M, IZ, OPT, IFAIL
REAL (KIND=nag_wp) | A(N,P), B(N,M), C(M,P), Z(IZ)

3 Description

The n by m matrix B is post-multiplied by the m by p matrix C. If OPT=1 the result is formed in the n by p matrix A. If OPT=2, m must equal p, and the result is written back to B. If OPT=3, n must equal m, and the result is written back to C.

4 References

None.

5 Arguments

1:   A NP – REAL (KIND=nag_wp) arrayOutput
On exit: if OPT=1, A contains the result of the matrix multiplication.
2:   B NM – REAL (KIND=nag_wp) arrayInput/Output
On entry: the n by m matrix B.
On exit: if OPT=2, B contains the result of the multiplication.
3:   C MP – REAL (KIND=nag_wp) arrayInput/Output
On entry: the m by p matrix C.
On exit: if OPT=3, C contains the result of the multiplication.
4:   N – INTEGERInput
On entry: n, the number of rows of the array A and of the array B.
Constraints:
  • if OPT=3, N=M;
  • otherwise N≥1.
5:   P – INTEGERInput
On entry: p, the number of columns of the array A and of the array C.
Constraints:
  • if OPT=2, P=M;
  • otherwise P≥1.
6:   M – INTEGERInput
On entry: m, the number of columns of the array B and rows of the array C.
Constraints:
  • if OPT=2, M=P;
  • if OPT=3, M=N;
  • if OPT≠1, M≤IZ;
  • otherwise M≥1.
7:   Z IZ – REAL (KIND=nag_wp) arrayWorkspace
8:   IZ – INTEGERInput
On entry: the dimension of the array Z as declared in the (sub)program from which F01CKF is called.
Constraints:
  • if OPT=1, IZ≥1;
  • if OPT≠1, IZ≥M.
9:   OPT – INTEGERInput
On entry: the value of OPT determines which array is to contain the final result.
OPT=1
A must be distinct from B and C and, on exit, contains the result. B and C need not be distinct in this case.
OPT=2
B must be distinct from C and on exit, contains the result. A is not used in this case and need not be distinct from B or C.
OPT=3
C must be distinct from B and on exit, contains the result. A is not used in this case and need not be distinct from B or C.
Constraint: 1≤OPT≤3.
10:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, M or P or N≤0.
IFAIL=2
OPT=2 and M≠P.
IFAIL=3
OPT=3 and N≠M.
IFAIL=4
OPT≠1 and IZ<M.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

Each element of the result is effectively computed as an inner product using basic precision.

8 Parallelism and Performance

F01CKF makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The time taken by F01CKF is approximately proportional to mnp.

10 Example

This example multiplies the 2 by 3 matrix B and the 3 by 2 matrix C together and places the result in the 2 by 2 matrix A.

10.1 Program Text

Program Text (f01ckfe.f90)

10.2 Program Data

Program Data (f01ckfe.d)

10.3 Program Results

Program Results (f01ckfe.r)

F01 Chapter Contents
F01 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F01 Chapter Contents : NAG Library Manual, Mark 26

F01 Chapter Introduction
NAG Library Manual

NAG Library Chapter Contents

F01 – Matrix Operations, Including Inversion

F01 Chapter Introduction – a description of the Chapter and an overview of the algorithms available

Routine Name | Mark of Introduction | Purpose
F01ABF Example Text Example Data | 1 | nagf_matop_real_symm_posdef_inv Inverse of real symmetric positive definite matrix using iterative refinement
F01ADF Example Text Example Data | 2 | nagf_matop_real_symm_posdef_inv_noref Inverse of real symmetric positive definite matrix
F01BLF Example Text Example Data | 5 | nagf_matop_real_gen_pseudinv Pseudo-inverse and rank of real m by n matrix m≥n
F01BRF Example Text Example Data | 7 | nagf_matop_real_gen_sparse_lu LU factorization of real sparse matrix
F01BSF Example Text Example Data | 7 | nagf_matop_real_gen_sparse_lu_reuse LU factorization of real sparse matrix with known sparsity pattern
F01BUF Example Text Example Data | 7 | nagf_matop_real_symm_posdef_fac ULD LTUT factorization of real symmetric positive definite band matrix
F01BVF Example Text Example Data | 7 | nagf_matop_real_symm_posdef_geneig Reduction to standard form, generalized real symmetric-definite banded eigenproblem
F01CKF Example Text Example Data | 2 | nagf_matop_real_gen_matmul Multiplication of real matrices
F01CRF Example Text Example Data | 7 | nagf_matop_real_gen_trans_inplace Transposition of a real matrix
F01CTF Example Text Example Data | 14 | nagf_matop_real_addsub Sum or difference of two real matrices, optional scaling and transposition
F01CWF Example Text Example Data | 14 | nagf_matop_complex_addsub Sum or difference of two complex matrices, optional scaling and transposition
F01ECF Example Text Example Data | 22 | nagf_matop_real_gen_matrix_exp Real matrix exponential
F01EDF Example Text Example Data | 23 | nagf_matop_real_symm_matrix_exp Real symmetric matrix exponential
F01EFF Example Text Example Data | 23 | nagf_matop_real_symm_matrix_fun Function of a real symmetric matrix
F01EJF Example Text Example Data | 24 | nagf_matop_real_gen_matrix_log Real matrix logarithm
F01EKF Example Text Example Data | 24 | nagf_matop_real_gen_matrix_fun_std Exponential, sine, cosine, sinh or cosh of a real matrix (Schur–Parlett algorithm)
F01ELF Example Text Example Data | 24 | nagf_matop_real_gen_matrix_fun_num Function of a real matrix (using numerical differentiation)
F01EMF Example Text Example Data | 24 | nagf_matop_real_gen_matrix_fun_usd Function of a real matrix (using user-supplied derivatives)
F01ENF Example Text Example Data | 25 | nagf_matop_real_gen_matrix_sqrt Real matrix square root
F01EPF Example Text Example Data | 25 | nagf_matop_real_tri_matrix_sqrt Real upper quasi-triangular matrix square root
F01EQF Example Text Example Data | 25 | nagf_matop_real_gen_matrix_pow General power of a real matrix
F01FCF Example Text Example Data | 23 | nagf_matop_complex_gen_matrix_exp Complex matrix exponential
F01FDF Example Text Example Data | 23 | nagf_matop_complex_herm_matrix_exp Complex Hermitian matrix exponential
F01FFF Example Text Example Data | 23 | nagf_matop_complex_herm_matrix_fun Function of a complex Hermitian matrix
F01FJF Example Text Example Data | 24 | nagf_matop_complex_gen_matrix_log Complex matrix logarithm
F01FKF Example Text Example Data | 24 | nagf_matop_complex_gen_matrix_fun_std Exponential, sine, cosine, sinh or cosh of a complex matrix (Schur–Parlett algorithm)
F01FLF Example Text Example Data | 24 | nagf_matop_complex_gen_matrix_fun_num Function of a complex matrix (using numerical differentiation)
F01FMF Example Text Example Data | 24 | nagf_matop_complex_gen_matrix_fun_usd Function of a complex matrix (using user-supplied derivatives)
F01FNF Example Text Example Data | 25 | nagf_matop_complex_gen_matrix_sqrt Complex matrix square root
F01FPF Example Text Example Data | 25 | nagf_matop_complex_tri_matrix_sqrt Complex upper triangular matrix square root
F01FQF Example Text Example Data | 25 | nagf_matop_complex_gen_matrix_pow General power of a complex matrix
F01GAF Example Text Example Data | 24 | nagf_matop_real_gen_matrix_actexp Action of a real matrix exponential on a real matrix
F01GBF Example Text Example Data | 24 | nagf_matop_real_gen_matrix_actexp_rcomm Action of a real matrix exponential on a real matrix (reverse communication)
F01HAF Example Text Example Data | 24 | nagf_matop_complex_gen_matrix_actexp Action of a complex matrix exponential on a complex matrix
F01HBF Example Text Example Data | 24 | nagf_matop_complex_gen_matrix_actexp_rcomm Action of a complex matrix exponential on a complex matrix (reverse communication)
F01JAF Example Text Example Data | 24 | nagf_matop_real_gen_matrix_cond_std Condition number for the exponential, logarithm, sine, cosine, sinh or cosh of a real matrix
F01JBF Example Text Example Data | 24 | nagf_matop_real_gen_matrix_cond_num Condition number for a function of a real matrix (using numerical differentiation)
F01JCF Example Text Example Data | 24 | nagf_matop_real_gen_matrix_cond_usd Condition number for a function of a real matrix (using user-supplied derivatives)
F01JDF Example Text Example Data | 25 | nagf_matop_real_gen_matrix_cond_sqrt Condition number for square root of real matrix
F01JEF Example Text Example Data | 25 | nagf_matop_real_gen_matrix_cond_pow Condition number for real matrix power
F01JFF Example Text Example Data | 25 | nagf_matop_real_gen_matrix_frcht_pow Fréchet derivative of real matrix power
F01JGF Example Text Example Data | 25 | nagf_matop_real_gen_matrix_cond_exp Condition number for real matrix exponential
F01JHF Example Text Example Data | 25 | nagf_matop_real_gen_matrix_frcht_exp Fréchet derivative of real matrix exponential
F01JJF Example Text Example Data | 25 | nagf_matop_real_gen_matrix_cond_log Condition number for real matrix logarithm
F01JKF Example Text Example Data | 25 | nagf_matop_real_gen_matrix_frcht_log Fréchet derivative of real matrix logarithm
F01KAF Example Text Example Data | 24 | nagf_matop_complex_gen_matrix_cond_std Condition number for the exponential, logarithm, sine, cosine, sinh or cosh of a complex matrix
F01KBF Example Text Example Data | 24 | nagf_matop_complex_gen_matrix_cond_num Condition number for a function of a complex matrix (using numerical differentiation)
F01KCF Example Text Example Data | 24 | nagf_matop_complex_gen_matrix_cond_usd Condition number for a function of a complex matrix (using user-supplied derivatives)
F01KDF Example Text Example Data | 25 | nagf_matop_complex_gen_matrix_cond_sqrt Condition number for square root of complex matrix
F01KEF Example Text Example Data | 25 | nagf_matop_complex_gen_matrix_cond_pow Condition number for complex matrix power
F01KFF Example Text Example Data | 25 | nagf_matop_complex_gen_matrix_frcht_pow Fréchet derivative of complex matrix power
F01KGF Example Text Example Data | 25 | nagf_matop_complex_gen_matrix_cond_exp Condition number for complex matrix exponential
F01KHF Example Text Example Data | 25 | nagf_matop_complex_gen_matrix_frcht_exp Fréchet derivative of complex matrix exponential
F01KJF Example Text Example Data | 25 | nagf_matop_complex_gen_matrix_cond_log Condition number for complex matrix logarithm
F01KKF Example Text Example Data | 25 | nagf_matop_complex_gen_matrix_frcht_log Fréchet derivative of complex matrix logarithm
F01LEF Example Text Example Data | 11 | nagf_matop_real_gen_tridiag_lu LU factorization of real tridiagonal matrix
F01LHF Example Text Example Data | 13 | nagf_matop_real_gen_blkdiag_lu LU factorization of real almost block diagonal matrix
F01MCF Example Text Example Data | 8 | nagf_matop_real_vband_posdef_fac LD LT factorization of real symmetric positive definite variable-bandwidth matrix
F01QGF Example Text Example Data | 14 | nagf_matop_real_trapez_rq RQ factorization of real m by n upper trapezoidal matrix m≤n
F01QJF Example Text Example Data | 14 | nagf_matop_real_gen_rq RQ factorization of real m by n matrix m≤n
F01QKF Example Text Example Data | 14 | nagf_matop_real_gen_rq_formq Operations with orthogonal matrices, form rows of Q, after RQ factorization by F01QJF
F01RGF Example Text Example Data | 14 | nagf_matop_complex_trapez_rq RQ factorization of complex m by n upper trapezoidal matrix m≤n
F01RJF Example Text Example Data | 14 | nagf_matop_complex_gen_rq RQ factorization of complex m by n matrix m≤n
F01RKF Example Text Example Data | 14 | nagf_matop_complex_gen_rq_formq Operations with unitary matrices, form rows of Q, after RQ factorization by F01RJF
F01VAF (DTRTTP) Example Text Example Data | 23 | DTRTTP nagf_matop_dtrttp Copies a real triangular matrix from full format to packed format
F01VBF (ZTRTTP) Example Text Example Data | 23 | ZTRTTP nagf_matop_ztrttp Copies a complex triangular matrix from full format to packed format
F01VCF (DTPTTR) Example Text Example Data | 23 | DTPTTR nagf_matop_dtpttr Copies a real triangular matrix from packed format to full format
F01VDF (ZTPTTR) Example Text Example Data | 23 | ZTPTTR nagf_matop_ztpttr Copies a complex triangular matrix from packed format to full format
F01VEF (DTRTTF) Example Text Example Data | 23 | DTRTTF nagf_matop_dtrttf Copies a real triangular matrix from full format to Rectangular Full Packed format
F01VFF (ZTRTTF) Example Text Example Data | 23 | ZTRTTF nagf_matop_ztrttf Copies a complex triangular matrix from full format to Rectangular Full Packed format
F01VGF (DTFTTR) Example Text Example Data | 23 | DTFTTR nagf_matop_dtfttr Copies a real triangular matrix from Rectangular Full Packed format to full format
F01VHF (ZTFTTR) Example Text Example Data | 23 | ZTFTTR nagf_matop_ztfttr Copies a complex triangular matrix from Rectangular Full Packed format to full format
F01VJF (DTPTTF) Example Text Example Data | 23 | DTPTTF nagf_matop_dtpttf Copies a real triangular matrix from packed format to Rectangular Full Packed format
F01VKF (ZTPTTF) Example Text Example Data | 23 | ZTPTTF nagf_matop_ztpttf Copies a complex triangular matrix from packed format to Rectangular Full Packed format
F01VLF (DTFTTP) Example Text Example Data | 23 | DTFTTP nagf_matop_dtfttp Copies a real triangular matrix from Rectangular Full Packed format to packed format
F01VMF (ZTFTTP) Example Text Example Data | 23 | ZTFTTP nagf_matop_ztfttp Copies a complex triangular matrix from Rectangular Full Packed format to packed format
F01ZAF Example Text Example Data | 14 | nagf_matop_real_tri_pack Convert real matrix between packed triangular and square storage formats
F01ZBF Example Text Example Data | 14 | nagf_matop_complex_tri_pack Convert complex matrix between packed triangular and square storage formats
F01ZCF Example Text Example Data | 14 | nagf_matop_real_band_pack Convert real matrix between packed banded and rectangular storage formats
F01ZDF Example Text Example Data | 14 | nagf_matop_complex_band_pack Convert complex matrix between packed banded and rectangular storage formats
F01 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F01CRF : NAG Library, Mark 26

F01 Chapter Contents
F01 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F01CRF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F01CRF transposes a rectangular matrix in-situ.

2 Specification

SUBROUTINE F01CRF ( A, M, N, MN, MOVE, LMOVE, IFAIL)
INTEGER | M, N, MN, MOVE(LMOVE), LMOVE, IFAIL
REAL (KIND=nag_wp) | A(MN)

3 Description

F01CRF requires that the elements of an m by n matrix A are stored consecutively by columns in a one-dimensional array. It reorders the elements so that on exit the array holds the transpose of A stored in the same way. For example, if m=4 and n=3, on entry the array must hold:
a 11 a 21 a 31 a 41 a 12 a 22 a 32 a 42 a 13 a 23 a 33 a 43
and on exit it holds
a 11   a 12   a 13   a 21   a 22   a 23   a 31   a 32   a 33   a 41   a 42   a 43.

4 References

Cate E G and Twigg D W (1977) Algorithm 513: Analysis of in-situ transposition ACM Trans. Math. Software 3 104–110

5 Arguments

1:   A MN – REAL (KIND=nag_wp) arrayInput/Output
On entry: the elements of the m by n matrix A, stored by columns.
On exit: the elements of the transpose matrix, also stored by columns.
2:   M – INTEGERInput
On entry: m, the number of rows of the matrix A.
3:   N – INTEGERInput
On entry: n, the number of columns of the matrix A.
4:   MN – INTEGERInput
On entry: n, the value m×n.
5:   MOVE LMOVE – INTEGER arrayWorkspace
6:   LMOVE – INTEGERInput
On entry: the dimension of the array MOVE as declared in the (sub)program from which F01CRF is called.
Suggested value: LMOVE=m+n/2.
Constraint: LMOVE≥1.
7:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, MN≠M×N.
IFAIL=2
On entry, LMOVE≤0.
IFAIL<0
A serious error has occurred. Check all subroutine calls and array sizes. Seek expert help.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

Exact results are produced.

8 Parallelism and Performance

F01CRF is not threaded in any implementation.

9 Further Comments

The time taken by F01CRF is approximately proportional to mn.

10 Example

This example transposes a 7 by 3 matrix and prints out, for convenience, its transpose.

10.1 Program Text

Program Text (f01crfe.f90)

10.2 Program Data

Program Data (f01crfe.d)

10.3 Program Results

Program Results (f01crfe.r)

F01 Chapter Contents
F01 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F01CTF : NAG Library, Mark 26

F01 Chapter Contents
F01 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F01CTF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F01CTF adds two real matrices, each one optionally transposed and multiplied by a scalar.

2 Specification

SUBROUTINE F01CTF ( TRANSA, TRANSB, M, N, ALPHA, A, LDA, BETA, B, LDB, C, LDC, IFAIL)
INTEGER | M, N, LDA, LDB, LDC, IFAIL
REAL (KIND=nag_wp) | ALPHA, A(LDA,*), BETA, B(LDB,*), C(LDC,*)
CHARACTER(1) | TRANSA, TRANSB

3 Description

F01CTF performs one of the operations
  • C≔αA+βB,
  • C≔α AT+βB,
  • C≔αA+β BT or
  • C≔α AT+β BT,
where A, B and C are matrices, and α and β are scalars. For efficiency, the routine contains special code for the cases when one or both of α, β is equal to zero, unity or minus unity. The matrices, or their transposes, must be compatible for addition. A and B are either m by n or n by m matrices, depending on whether they are to be transposed before addition. C is an m by n matrix.

4 References

None.

5 Arguments

1:   TRANSA – CHARACTER(1)Input
2:   TRANSB – CHARACTER(1)Input
On entry: TRANSA and TRANSB must specify whether or not the matrix A and the matrix B, respectively, are to be transposed before addition.
TRANSA or TRANSB='N'
The matrix will not be transposed.
TRANSA or TRANSB='T' or 'C'
The matrix will be transposed.
Constraint: TRANSA​ or ​TRANSB='N', 'T' or 'C'.
3:   M – INTEGERInput
On entry: m, the number of rows of the matrices A and B or their transposes. Also the number of rows of the matrix C.
Constraint: M≥0.
4:   N – INTEGERInput
On entry: n, the number of columns of the matrices A and B or their transposes. Also the number of columns of the matrix C.
Constraint: N≥0.
5:   ALPHA – REAL (KIND=nag_wp)Input
On entry: the scalar α, by which matrix A is multiplied before addition.
6:   A LDA* – REAL (KIND=nag_wp) arrayInput
Note: the second dimension of the array A must be at least max 1,N if TRANSA='N', and at least max 1,M otherwise.
On entry: if α=0.0, the elements of array A need not be assigned. If α≠0.0, then if TRANSA='N', the leading m by n part of A must contain the matrix A, otherwise the leading n by m part of A must contain the matrix A.
7:   LDA – INTEGERInput
On entry: the first dimension of the array A as declared in the (sub)program from which F01CTF is called.
Constraints:
  • if TRANSA='N', LDA≥max 1,M;
  • otherwise LDA≥max 1,N.
8:   BETA – REAL (KIND=nag_wp)Input
On entry: the scalar β, by which matrix B is multiplied before addition.
9:   B LDB* – REAL (KIND=nag_wp) arrayInput
Note: the second dimension of the array B must be at least max 1,N if TRANSB='N', and at least max 1,M otherwise.
On entry: if β=0.0, the elements of array B need not be assigned. If β≠0.0, then if TRANSA='N', the leading m by n part of B must contain the matrix B, otherwise the leading n by m part of B must contain the matrix B.
10:   LDB – INTEGERInput
On entry: the first dimension of the array B as declared in the (sub)program from which F01CTF is called.
Constraints:
  • if TRANSB='N', LDB≥max 1,M;
  • otherwise LDB≥max 1,N.
11:   C LDC* – REAL (KIND=nag_wp) arrayOutput
Note: the second dimension of the array C must be at least max 1,N.
On exit: the elements of the m by n matrix C.
12:   LDC – INTEGERInput
On entry: the first dimension of the array C as declared in the (sub)program from which F01CTF is called.
Constraint: LDC≥max 1,M.
13:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, one or both of TRANSA or TRANSB is not equal to 'N', 'T' or 'C'.
IFAIL=2
On entry, one or both of M or N is less than 0.
IFAIL=3
On entry, LDA<max 1,P, where P=M if TRANSA='N', and P=N otherwise.
IFAIL=4
On entry, LDB<max 1,P, where P=M if TRANSB='N', and P=N otherwise.
IFAIL=5
On entry, LDC<max 1,M.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

The results returned by F01CTF are accurate to machine precision.

8 Parallelism and Performance

F01CTF is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The time taken for a call of F01CTF varies with M, N and the values of α and β. The routine is quickest if either or both of α and β are equal to zero, or plus or minus unity.

10 Example

The following program reads in a pair of matrices A and B, along with values for TRANSA, TRANSB, ALPHA and BETA, and adds them together, printing the result matrix C. The process is continued until the end of the input stream is reached.

10.1 Program Text

Program Text (f01ctfe.f90)

10.2 Program Data

Program Data (f01ctfe.d)

10.3 Program Results

Program Results (f01ctfe.r)

F01 Chapter Contents
F01 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F01CWF : NAG Library, Mark 26

F01 Chapter Contents
F01 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F01CWF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F01CWF adds two complex matrices, each one optionally transposed and multiplied by a scalar.

2 Specification

SUBROUTINE F01CWF ( TRANSA, TRANSB, M, N, ALPHA, A, LDA, BETA, B, LDB, C, LDC, IFAIL)
INTEGER | M, N, LDA, LDB, LDC, IFAIL
COMPLEX (KIND=nag_wp) | ALPHA, A(LDA,*), BETA, B(LDB,*), C(LDC,*)
CHARACTER(1) | TRANSA, TRANSB

3 Description

F01CWF performs one of the operations
  • C≔αA+βB,
  • C≔α AT+βB,
  • C≔α AH+βB,
  • C≔αA+β BT,
  • C≔α AT+β BT,
  • C≔α AH+β BT,
  • C≔αA+β BH,
  • C≔α AT+β BH or
  • C≔α AH+β BH,
where A, B and C are matrices, α and β are scalars, T denotes transposition and H denotes conjugate transposition. For efficiency, the routine contains special code for the cases when one or both of α, β is equal to zero, unity or minus unity. The matrices, or their transposes, must be compatible for addition. A and B are either m by n or n by m matrices, depending on whether they are to be transposed before addition. C is an m by n matrix.

4 References

None.

5 Arguments

1:   TRANSA – CHARACTER(1)Input
2:   TRANSB – CHARACTER(1)Input
On entry: TRANSA and TRANSB must specify whether or not the matrix A and the matrix B, respectively, are to be transposed before addition.
TRANSA or TRANSB='N'
The matrix will not be transposed.
TRANSA or TRANSB='T'
The matrix will be transposed.
TRANSA or TRANSB='C'
The matrix will be transposed and conjugated.
Constraint: TRANSA​ or ​TRANSB='N', 'T' or 'C'.
3:   M – INTEGERInput
On entry: m, the number of rows of the matrices A and B or their transposes. Also the number of rows of the matrix C.
Constraint: M≥0.
4:   N – INTEGERInput
On entry: n, the number of columns of the matrices A and B or their transposes. Also the number of columns of the matrix C.
Constraint: N≥0.
5:   ALPHA – COMPLEX (KIND=nag_wp)Input
On entry: the scalar α, by which matrix A is multiplied before addition.
6:   A LDA* – COMPLEX (KIND=nag_wp) arrayInput
Note: the second dimension of the array A must be at least max 1,N if ALPHA≠0 and TRANSA='N', max 1,M if ALPHA≠0 and TRANSA='T' or 'C' and at least 1 if ALPHA=0.
On entry: the matrix A. If α=0, the array A is not referenced.
7:   LDA – INTEGERInput
On entry: the first dimension of the array A as declared in the (sub)program from which F01CWF is called.
Constraints:
  • if TRANSA='N', LDA≥max 1,M;
  • otherwise LDA≥max 1,N.
8:   BETA – COMPLEX (KIND=nag_wp)Input
On entry: the scalar β, by which matrix B is multiplied before addition.
9:   B LDB* – COMPLEX (KIND=nag_wp) arrayInput
Note: the second dimension of the array B must be at least max 1,N if BETA≠0 and TRANSB='N', max 1,M if BETA≠0 and TRANSB='T' or 'C' and at least 1 if BETA=0.
On entry: the matrix B. If β=0, the array B is not referenced.
10:   LDB – INTEGERInput
On entry: the first dimension of the array B as declared in the (sub)program from which F01CWF is called.
Constraints:
  • if TRANSB='N', LDB≥max 1,M;
  • otherwise LDB≥max 1,N.
11:   C LDC* – COMPLEX (KIND=nag_wp) arrayOutput
Note: the second dimension of the array C must be at least max 1,N.
On exit: the elements of the m by n matrix C.
12:   LDC – INTEGERInput
On entry: the first dimension of the array C as declared in the (sub)program from which F01CWF is called.
Constraint: LDC≥max 1,M.
13:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, one or both of TRANSA or TRANSB is not equal to 'N', 'T' or 'C'.
IFAIL=2
On entry, one or both of M or N is less than 0.
IFAIL=3
On entry, LDA<max 1,P, where P=M if TRANSA='N', and P=N otherwise.
IFAIL=4
On entry, LDB<max 1,P, where P=M if TRANSB='N', and P=N otherwise.
IFAIL=5
On entry, LDC<max 1,M.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

The results returned by F01CWF are accurate to machine precision.

8 Parallelism and Performance

F01CWF is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The time taken for a call of F01CWF varies with M, N and the values of α and β. The routine is quickest if either or both of α and β are equal to zero, or plus or minus unity.

10 Example

The following program reads in a pair of matrices A and B, along with values for TRANSA, TRANSB, ALPHA and BETA, and adds them together, printing the result matrix C. The process is continued until the end of the input stream is reached.

10.1 Program Text

Program Text (f01cwfe.f90)

10.2 Program Data

Program Data (f01cwfe.d)

10.3 Program Results

Program Results (f01cwfe.r)

F01 Chapter Contents
F01 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F01ECF : NAG Library, Mark 26

F01 Chapter Contents
F01 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F01ECF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F01ECF computes the matrix exponential, eA, of a real n by n matrix A.

2 Specification

SUBROUTINE F01ECF ( N, A, LDA, IFAIL)
INTEGER | N, LDA, IFAIL
REAL (KIND=nag_wp) | A(LDA,*)

3 Description

eA is computed using a Padé approximant and the scaling and squaring method described in Al–Mohy and Higham (2009).

4 References

Al–Mohy A H and Higham N J (2009) A new scaling and squaring algorithm for the matrix exponential SIAM J. Matrix Anal. 31(3) 970–989
Higham N J (2005) The scaling and squaring method for the matrix exponential revisited SIAM J. Matrix Anal. Appl. 26(4) 1179–1193
Higham N J (2008) Functions of Matrices: Theory and Computation SIAM, Philadelphia, PA, USA
Moler C B and Van Loan C F (2003) Nineteen dubious ways to compute the exponential of a matrix, twenty-five years later SIAM Rev. 45 3–49

5 Arguments

1:   N – INTEGERInput
On entry: n, the order of the matrix A.
Constraint: N≥0.
2:   A LDA* – REAL (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array A must be at least N.
On entry: the n by n matrix A.
On exit: the n by n matrix exponential eA.
3:   LDA – INTEGERInput
On entry: the first dimension of the array A as declared in the (sub)program from which F01ECF is called.
Constraint: LDA≥N.
4:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
The linear equations to be solved for the Padé approximant are singular; it is likely that this routine has been called incorrectly.
IFAIL=2
The linear equations to be solved are nearly singular and the Padé approximant probably has no correct figures; it is likely that this routine has been called incorrectly.
IFAIL=3
eA has been computed using an IEEE double precision Padé approximant, although the arithmetic precision is higher than IEEE double precision.
IFAIL=4
An unexpected internal error has occurred. Please contact NAG.
IFAIL=-1
On entry, N=value.
Constraint: N≥0.
IFAIL=-3
On entry, LDA=value and N=value.
Constraint: LDA≥N.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

For a normal matrix A (for which AT A=A AT) the computed matrix, eA, is guaranteed to be close to the exact matrix, that is, the method is forward stable. No such guarantee can be given for non-normal matrices. See Al–Mohy and Higham (2009) and Section 10.3 of Higham (2008) for details and further discussion.
If estimates of the condition number of the matrix exponential are required then F01JGF should be used.

8 Parallelism and Performance

F01ECF is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
F01ECF makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The integer allocatable memory required is N, and the real allocatable memory required is approximately 6×N 2.
The cost of the algorithm is O n 3; see Section 5 of of Al–Mohy and Higham (2009). The real allocatable memory required is approximately 6×n 2.
If the Fréchet derivative of the matrix exponential is required then F01JHF should be used.
As well as the excellent book cited above, the classic reference for the computation of the matrix exponential is Moler and Van Loan (2003).

10 Example

This example finds the matrix exponential of the matrix
A = 1 2 2 2 3 1 1 2 3 2 1 2 3 3 3 1 .

10.1 Program Text

Program Text (f01ecfe.f90)

10.2 Program Data

Program Data (f01ecfe.d)

10.3 Program Results

Program Results (f01ecfe.r)

F01 Chapter Contents
F01 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F01EDF : NAG Library, Mark 26

F01 Chapter Contents
F01 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F01EDF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F01EDF computes the matrix exponential, eA, of a real symmetric n by n matrix A.

2 Specification

SUBROUTINE F01EDF ( UPLO, N, A, LDA, IFAIL)
INTEGER | N, LDA, IFAIL
REAL (KIND=nag_wp) | A(LDA,*)
CHARACTER(1) | UPLO

3 Description

eA is computed using a spectral factorization of A
A = Q D QT ,
where D is the diagonal matrix whose diagonal elements, di, are the eigenvalues of A, and Q is an orthogonal matrix whose columns are the eigenvectors of A. eA is then given by
eA = Q eD QT ,
where eD is the diagonal matrix whose ith diagonal element is e di. See for example Section 4.5 of Higham (2008).

4 References

Higham N J (2008) Functions of Matrices: Theory and Computation SIAM, Philadelphia, PA, USA
Moler C B and Van Loan C F (2003) Nineteen dubious ways to compute the exponential of a matrix, twenty-five years later SIAM Rev. 45 3–49

5 Arguments

1:   UPLO – CHARACTER(1)Input
On entry: indicates whether the upper or lower triangular part of A is stored.
UPLO='U'
The upper triangular part of A is stored.
UPLO='L'
The lower triangular part of A is stored.
Constraint: UPLO='U' or 'L'.
2:   N – INTEGERInput
On entry: n, the order of the matrix A.
Constraint: N≥0.
3:   A LDA* – REAL (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array A must be at least N.
On entry: the n by n symmetric matrix A.
  • If UPLO='U', the upper triangular part of A must be stored and the elements of the array below the diagonal are not referenced.
  • If UPLO='L', the lower triangular part of A must be stored and the elements of the array above the diagonal are not referenced.
On exit: if IFAIL=0, the upper or lower triangular part of the n by n matrix exponential, eA.
4:   LDA – INTEGERInput
On entry: the first dimension of the array A as declared in the (sub)program from which F01EDF is called.
Constraint: LDA≥max 1,N.
5:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL>0
The computation of the spectral factorization failed to converge.
IFAIL=-1
On entry, UPLO=value.
Constraint: UPLO='L' or 'U'.
IFAIL=-2
On entry, N=value.
Constraint: N≥0.
IFAIL=-3
An internal error occurred when computing the spectral factorization. Please contact NAG.
IFAIL=-4
On entry, LDA=value and N=value.
Constraint: LDA≥N.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

For a symmetric matrix A, the matrix eA, has the relative condition number
κ A = A 2 ,
which is the minimum possible for the matrix exponential and so the computed matrix exponential is guaranteed to be close to the exact matrix. See Section 10.2 of Higham (2008) for details and further discussion.

8 Parallelism and Performance

F01EDF is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
F01EDF makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The integer allocatable memory required is N, and the real allocatable memory required is approximately N+nb+4×N, where nb is the block size required by F08FAF (DSYEV).
The cost of the algorithm is O n 3.
As well as the excellent book cited above, the classic reference for the computation of the matrix exponential is Moler and Van Loan (2003).

10 Example

This example finds the matrix exponential of the symmetric matrix
A = 1 2 3 4 2 1 2 3 3 2 1 2 4 3 2 1

10.1 Program Text

Program Text (f01edfe.f90)

10.2 Program Data

Program Data (f01edfe.d)

10.3 Program Results

Program Results (f01edfe.r)

F01 Chapter Contents
F01 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F01EFF : NAG Library, Mark 26

F01 Chapter Contents
F01 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F01EFF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F01EFF computes the matrix function, f A, of a real symmetric n by n matrix A. f A must also be a real symmetric matrix.

2 Specification

SUBROUTINE F01EFF ( UPLO, N, A, LDA, F, IUSER, RUSER, IFLAG, IFAIL)
INTEGER | N, LDA, IUSER(*), IFLAG, IFAIL
REAL (KIND=nag_wp) | A(LDA,*), RUSER(*)
CHARACTER(1) | UPLO
EXTERNAL | F

3 Description

f A is computed using a spectral factorization of A
A = Q D QT ,
where D is the diagonal matrix whose diagonal elements, di, are the eigenvalues of A, and Q is an orthogonal matrix whose columns are the eigenvectors of A. f A is then given by
f A = Q f D QT ,
where f D is the diagonal matrix whose ith diagonal element is f di. See for example Section 4.5 of Higham (2008). f di is assumed to be real.

4 References

Higham N J (2008) Functions of Matrices: Theory and Computation SIAM, Philadelphia, PA, USA

5 Arguments

1:   UPLO – CHARACTER(1)Input
On entry: if UPLO='U', the upper triangle of the matrix A is stored.
If UPLO='L', the lower triangle of the matrix A is stored.
Constraint: UPLO='U' or 'L'.
2:   N – INTEGERInput
On entry: n, the order of the matrix A.
Constraint: N≥0.
3:   A LDA* – REAL (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array A must be at least N.
On entry: the n by n symmetric matrix A.
  • If UPLO='U', the upper triangular part of A must be stored and the elements of the array below the diagonal are not referenced.
  • If UPLO='L', the lower triangular part of A must be stored and the elements of the array above the diagonal are not referenced.
On exit: if IFAIL=0, the upper or lower triangular part of the n by n matrix function, f A.
4:   LDA – INTEGERInput
On entry: the first dimension of the array A as declared in the (sub)program from which F01EFF is called.
Constraint: LDA≥max 1,N.
5:   F – SUBROUTINE, supplied by the user.External Procedure
The subroutine F evaluates f zi at a number of points zi.
The specification of F is:
SUBROUTINE F ( IFLAG, N, X, FX, IUSER, RUSER)
INTEGER | IFLAG, N, IUSER(*)
REAL (KIND=nag_wp) | X(N), FX(N), RUSER(*)
1:   IFLAG – INTEGERInput/Output
On entry: IFLAG will be zero.
On exit: IFLAG should either be unchanged from its entry value of zero, or may be set nonzero to indicate that there is a problem in evaluating the function f x; for instance f x may not be defined, or may be complex. If IFLAG is returned as nonzero then F01EFF will terminate the computation, with IFAIL=-6.
2:   N – INTEGERInput
On entry: n, the number of function values required.
3:   X N – REAL (KIND=nag_wp) arrayInput
On entry: the n points x 1,x 2,…,xn at which the function f is to be evaluated.
4:   FX N – REAL (KIND=nag_wp) arrayOutput
On exit: the n function values. FX i should return the value f xi, for i=1,2,…,n.
5:   IUSER* – INTEGER arrayUser Workspace
6:   RUSER* – REAL (KIND=nag_wp) arrayUser Workspace
F is called with the arguments IUSER and RUSER as supplied to F01EFF. You are free to use the arrays IUSER and RUSER to supply information to F as an alternative to using COMMON global variables.
F must either be a module subprogram USEd by, or declared as EXTERNAL in, the (sub)program from which F01EFF is called. Arguments denoted as Input must not be changed by this procedure.
6:   IUSER* – INTEGER arrayUser Workspace
7:   RUSER* – REAL (KIND=nag_wp) arrayUser Workspace
IUSER and RUSER are not used by F01EFF, but are passed directly to F and may be used to pass information to this routine as an alternative to using COMMON global variables.
8:   IFLAG – INTEGEROutput
On exit: IFLAG=0, unless you have set IFLAG nonzero inside F, in which case IFLAG will be the value you set and IFAIL will be set to IFAIL=-6.
9:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL>0
The computation of the spectral factorization failed to converge.
IFAIL=-1
On entry, UPLO=value.
Constraint: UPLO='L' or 'U'.
IFAIL=-2
On entry, N=value.
Constraint: N≥0.
IFAIL=-3
An internal error occurred when computing the spectral factorization. Please contact NAG.
IFAIL=-4
On entry, LDA=value and N=value.
Constraint: LDA≥N.
IFAIL=-6
IFLAG was set to a nonzero value in F.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

Provided that f D can be computed accurately then the computed matrix function will be close to the exact matrix function. See Section 10.2 of Higham (2008) for details and further discussion.

8 Parallelism and Performance

F01EFF is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
F01EFF makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The integer allocatable memory required is N, and the real allocatable memory required is approximately N+nb+4×N, where nb is the block size required by F08FAF (DSYEV).
The cost of the algorithm is O n 3 plus the cost of evaluating f D. If λ^i is the ith computed eigenvalue of A, then the user-supplied subroutine F will be asked to evaluate the function f at f λ^i, i=1,2,…,n.
For further information on matrix functions, see Higham (2008).
F01FFF can be used to find the matrix function f A for a complex Hermitian matrix A.

10 Example

This example finds the matrix cosine, cos A, of the symmetric matrix
A= 1 2 3 4 2 1 2 3 3 2 1 2 4 3 2 1 .

10.1 Program Text

Program Text (f01effe.f90)

10.2 Program Data

Program Data (f01effe.d)

10.3 Program Results

Program Results (f01effe.r)

F01 Chapter Contents
F01 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F01EJF : NAG Library, Mark 26

F01 Chapter Contents
F01 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F01EJF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F01EJF computes the principal matrix logarithm, log A, of a real n by n matrix A, with no eigenvalues on the closed negative real line.

2 Specification

SUBROUTINE F01EJF ( N, A, LDA, IMNORM, IFAIL)
INTEGER | N, LDA, IFAIL
REAL (KIND=nag_wp) | A(LDA,*), IMNORM

3 Description

Any nonsingular matrix A has infinitely many logarithms. For a matrix with no eigenvalues on the closed negative real line, the principal logarithm is the unique logarithm whose spectrum lies in the strip z:-π<Im⁡z<π.
log A is computed using the inverse scaling and squaring algorithm for the matrix logarithm described in Al–Mohy and Higham (2011), adapted to real matrices by Al–Mohy et al. (2012).

4 References

Al–Mohy A H and Higham N J (2011) Improved inverse scaling and squaring algorithms for the matrix logarithm SIAM J. Sci. Comput. 34(4) C152–C169
Al–Mohy A H, Higham N J and Relton S D (2012) Computing the Fréchet derivative of the matrix logarithm and estimating the condition number SIAM J. Sci. Comput. 35(4) C394–C410
Higham N J (2008) Functions of Matrices: Theory and Computation SIAM, Philadelphia, PA, USA

5 Arguments

1:   N – INTEGERInput
On entry: n, the order of the matrix A.
Constraint: N≥0.
2:   A LDA* – REAL (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array A must be at least N.
On entry: the n by n matrix A.
On exit: the n by n principal matrix logarithm, log A.
3:   LDA – INTEGERInput
On entry: the first dimension of the array A as declared in the (sub)program from which F01EJF is called.
Constraint: LDA≥N.
4:   IMNORM – REAL (KIND=nag_wp)Output
On exit: if the routine has given a reliable answer then IMNORM=0.0. If IMNORM differs from 0.0 by more than unit roundoff (as returned by X02AJF) then the computed matrix logarithm is unreliable.
5:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
A is singular so the logarithm cannot be computed.
IFAIL=2
A was found to have eigenvalues on the negative real line. The principal logarithm is not defined in this case. F01FJF can be used to find a complex non-principal logarithm.
IFAIL=3
log A has been computed using an IEEE double precision Padé approximant, although the arithmetic precision is higher than IEEE double precision.
IFAIL=4
An unexpected internal error occurred. Please contact NAG.
IFAIL=-1
On entry, N=value.
Constraint: N≥0.
IFAIL=-3
On entry, LDA=value and N=value.
Constraint: LDA≥N.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

For a normal matrix A (for which AT A=A AT), the Schur decomposition is diagonal and the algorithm reduces to evaluating the logarithm of the eigenvalues of A and then constructing log A using the Schur vectors. This should give a very accurate result. In general, however, no error bounds are available for the algorithm. See Al–Mohy and Higham (2011) and Section 9.4 of Higham (2008) for details and further discussion.
The sensitivity of the computation of log A is worst when A has an eigenvalue of very small modulus or has a complex conjugate pair of eigenvalues lying close to the negative real axis.
If estimates of the condition number of the matrix logarithm are required then F01JJF should be used.

8 Parallelism and Performance

F01EJF is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
F01EJF makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The cost of the algorithm is O n 3 floating-point operations (see Al–Mohy and Higham (2011)). The real allocatable memory required is approximately 3×n 2.
If the Fréchet derivative of the matrix logarithm is required then F01JKF should be used.
F01FJF can be used to find the principal logarithm of a complex matrix. It can also be used to return a complex, non-principal logarithm if a real matrix has no principal logarithm due to the presence of negative eigenvalues.

10 Example

This example finds the principal matrix logarithm of the matrix
A = 3 -3 1 1 2 1 -2 1 1 1 3 -1 2 0 2 0 .

10.1 Program Text

Program Text (f01ejfe.f90)

10.2 Program Data

Program Data (f01ejfe.d)

10.3 Program Results

Program Results (f01ejfe.r)

F01 Chapter Contents
F01 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F01EKF : NAG Library, Mark 26

F01 Chapter Contents
F01 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F01EKF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F01EKF computes the matrix exponential, sine, cosine, sinh or cosh, of a real n by n matrix A using the Schur–Parlett algorithm.

2 Specification

SUBROUTINE F01EKF ( FUN, N, A, LDA, IMNORM, IFAIL)
INTEGER | N, LDA, IFAIL
REAL (KIND=nag_wp) | A(LDA,*), IMNORM
CHARACTER(*) | FUN

3 Description

f A, where f is either the exponential, sine, cosine, sinh or cosh, is computed using the Schur–Parlett algorithm described in Higham (2008) and Davies and Higham (2003).

4 References

Davies P I and Higham N J (2003) A Schur–Parlett algorithm for computing matrix functions. SIAM J. Matrix Anal. Appl. 25(2) 464–485
Higham N J (2008) Functions of Matrices: Theory and Computation SIAM, Philadelphia, PA, USA

5 Arguments

1:   FUN – CHARACTER(*)Input
On entry: indicates which matrix function will be computed.
FUN='EXP'
The matrix exponential, eA, will be computed.
FUN='SIN'
The matrix sine, sin A, will be computed.
FUN='COS'
The matrix cosine, cos A, will be computed.
FUN='SINH'
The hyperbolic matrix sine, sinh A, will be computed.
FUN='COSH'
The hyperbolic matrix cosine, cosh A, will be computed.
Constraint: FUN='EXP', 'SIN', 'COS', 'SINH' or 'COSH'.
2:   N – INTEGERInput
On entry: n, the order of the matrix A.
Constraint: N≥0.
3:   A LDA* – REAL (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array A must be at least N.
On entry: the n by n matrix A.
On exit: the n by n matrix, f A.
4:   LDA – INTEGERInput
On entry: the first dimension of the array A as declared in the (sub)program from which F01EKF is called.
Constraint: LDA≥N.
5:   IMNORM – REAL (KIND=nag_wp)Output
On exit: if A has complex eigenvalues, F01EKF will use complex arithmetic to compute the matrix function. The imaginary part is discarded at the end of the computation, because it will theoretically vanish. IMNORM contains the 1-norm of the imaginary part, which should be used to check that the routine has given a reliable answer.
If A has real eigenvalues, F01EKF uses real arithmetic and IMNORM=0.
6:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
A Taylor series failed to converge.
IFAIL=2
An unexpected internal error occurred when evaluating the function at a point. Please contact NAG.
IFAIL=3
There was an error whilst reordering the Schur form of A.
Note: this failure should not occur and suggests that the routine has been called incorrectly.
IFAIL=4
The routine was unable to compute the Schur decomposition of A.
Note: this failure should not occur and suggests that the routine has been called incorrectly.
IFAIL=5
An unexpected internal error occurred. Please contact NAG.
IFAIL=6
The linear equations to be solved are nearly singular and the Padé approximant used to compute the exponential may have no correct figures.
Note: this failure should not occur and suggests that the routine has been called incorrectly.
IFAIL=-1
On entry, FUN=value was an illegal value.
IFAIL=-2
Input argument number value is invalid.
IFAIL=-4
On entry, argument LDA is invalid.
Constraint: LDA≥N.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

For a normal matrix A (for which AT A=A AT), the Schur decomposition is diagonal and the algorithm reduces to evaluating f at the eigenvalues of A and then constructing f A using the Schur vectors. This should give a very accurate result. In general, however, no error bounds are available for the algorithm.
For further discussion of the Schur–Parlett algorithm see Section 9.4 of Higham (2008).

8 Parallelism and Performance

F01EKF is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library. In these implementations, this routine may make calls to the user-supplied functions from within an OpenMP parallel region. Thus OpenMP directives within the user functions can only be used if you are compiling the user-supplied function and linking the executable in accordance with the instructions in the Users' Note for your implementation.
F01EKF makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The integer allocatable memory required is n. If A has real eigenvalues then up to 9 n 2 of real allocatable memory may be required. If A has complex eigenvalues then up to 9 n 2 of complex allocatable memory may be required.
The cost of the Schur–Parlett algorithm depends on the spectrum of A, but is roughly between 28 n 3 and n 4/3 floating-point operations; see Algorithm 9.6 of Higham (2008).
If the matrix exponential is required then it is recommended that F01ECF be used. F01ECF uses an algorithm which is, in general, more accurate than the Schur–Parlett algorithm used by F01EKF.
If estimates of the condition number of the matrix function are required then F01JAF should be used.
F01FKF can be used to find the matrix exponential, sin, cos, sinh or cosh of a complex matrix.

10 Example

This example finds the matrix cosine of the matrix
A = 2 0 1 0 0 2 -2 1 0 2 3 1 1 4 0 0 .

10.1 Program Text

Program Text (f01ekfe.f90)

10.2 Program Data

Program Data (f01ekfe.d)

10.3 Program Results

Program Results (f01ekfe.r)

F01 Chapter Contents
F01 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F01ELF : NAG Library, Mark 26

F01 Chapter Contents
F01 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F01ELF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F01ELF computes the matrix function, f A, of a real n by n matrix A. Numerical differentiation is used to evaluate the derivatives of f when they are required.

2 Specification

SUBROUTINE F01ELF ( N, A, LDA, F, IUSER, RUSER, IFLAG, IMNORM, IFAIL)
INTEGER | N, LDA, IUSER(*), IFLAG, IFAIL
REAL (KIND=nag_wp) | A(LDA,*), RUSER(*), IMNORM
EXTERNAL | F

3 Description

f A is computed using the Schur–Parlett algorithm described in Higham (2008) and Davies and Higham (2003). The coefficients of the Taylor series used in the algorithm are evaluated using the numerical differentiation algorithm of Lyness and Moler (1967).
The scalar function f is supplied via subroutine F which evaluates f zi at a number of points zi.

4 References

Davies P I and Higham N J (2003) A Schur–Parlett algorithm for computing matrix functions. SIAM J. Matrix Anal. Appl. 25(2) 464–485
Higham N J (2008) Functions of Matrices: Theory and Computation SIAM, Philadelphia, PA, USA
Lyness J N and Moler C B (1967) Numerical differentiation of analytic functions SIAM J. Numer. Anal. 4(2) 202–210

5 Arguments

1:   N – INTEGERInput
On entry: n, the order of the matrix A.
Constraint: N≥0.
2:   A LDA* – REAL (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array A must be at least N.
On entry: the n by n matrix A.
On exit: the n by n matrix, f A.
3:   LDA – INTEGERInput
On entry: the first dimension of the array A as declared in the (sub)program from which F01ELF is called.
Constraint: LDA≥N.
4:   F – SUBROUTINE, supplied by the user.External Procedure
The subroutine F evaluates f zi at a number of points zi.
The specification of F is:
SUBROUTINE F ( IFLAG, NZ, Z, FZ, IUSER, RUSER)
INTEGER | IFLAG, NZ, IUSER(*)
REAL (KIND=nag_wp) | RUSER(*)
COMPLEX (KIND=nag_wp) | Z(NZ), FZ(NZ)
1:   IFLAG – INTEGERInput/Output
On entry: IFLAG will be zero.
On exit: IFLAG should either be unchanged from its entry value of zero, or may be set nonzero to indicate that there is a problem in evaluating the function f zi; for instance f zi may not be defined. If IFLAG is returned as nonzero then F01ELF will terminate the computation, with IFAIL=2.
2:   NZ – INTEGERInput
On entry: nz, the number of function values required.
3:   Z NZ – COMPLEX (KIND=nag_wp) arrayInput
On entry: the nz points z 1,z 2,…,z nz at which the function f is to be evaluated.
4:   FZ NZ – COMPLEX (KIND=nag_wp) arrayOutput
On exit: the nz function values. FZ i should return the value f zi, for i=1,2,…,nz. If zi lies on the real line, then so must f zi.
5:   IUSER* – INTEGER arrayUser Workspace
6:   RUSER* – REAL (KIND=nag_wp) arrayUser Workspace
F is called with the arguments IUSER and RUSER as supplied to F01ELF. You are free to use the arrays IUSER and RUSER to supply information to F as an alternative to using COMMON global variables.
F must either be a module subprogram USEd by, or declared as EXTERNAL in, the (sub)program from which F01ELF is called. Arguments denoted as Input must not be changed by this procedure.
5:   IUSER* – INTEGER arrayUser Workspace
6:   RUSER* – REAL (KIND=nag_wp) arrayUser Workspace
IUSER and RUSER are not used by F01ELF, but are passed directly to F and may be used to pass information to this routine as an alternative to using COMMON global variables.
7:   IFLAG – INTEGEROutput
On exit: IFLAG=0, unless IFLAG has been set nonzero inside F, in which case IFLAG will be the value set and IFAIL will be set to IFAIL=2.
8:   IMNORM – REAL (KIND=nag_wp)Output
On exit: if A has complex eigenvalues, F01ELF will use complex arithmetic to compute f A. The imaginary part is discarded at the end of the computation, because it will theoretically vanish. IMNORM contains the 1-norm of the imaginary part, which should be used to check that the routine has given a reliable answer.
If A has real eigenvalues, F01ELF uses real arithmetic and IMNORM=0.
9:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
A Taylor series failed to converge after 40 terms. Further Taylor series coefficients can no longer reliably be obtained by numerical differentiation.
IFAIL=2
IFLAG has been set nonzero by the user.
IFAIL=3
There was an error whilst reordering the Schur form of A.
Note: this failure should not occur and suggests that the routine has been called incorrectly.
IFAIL=4
The routine was unable to compute the Schur decomposition of A.
Note: this failure should not occur and suggests that the routine has been called incorrectly.
IFAIL=5
An unexpected internal error occurred. Please contact NAG.
IFAIL=-1
Input argument number value is invalid.
IFAIL=-3
On entry, argument LDA is invalid.
Constraint: LDA≥N.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

For a normal matrix A (for which AT A=A AT) the Schur decomposition is diagonal and the algorithm reduces to evaluating f at the eigenvalues of A and then constructing f A using the Schur vectors. See Section 9.4 of Higham (2008) for further discussion of the Schur–Parlett algorithm, and Lyness and Moler (1967) for a discussion of numerical differentiation.

8 Parallelism and Performance

F01ELF is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library. In these implementations, this routine may make calls to the user-supplied functions from within an OpenMP parallel region. Thus OpenMP directives within the user functions can only be used if you are compiling the user-supplied function and linking the executable in accordance with the instructions in the Users' Note for your implementation. The user workspace arrays IUSER and RUSER are classified as OpenMP shared memory and use of IUSER and RUSER has to take account of this in order to preserve thread safety whenever information is written back to either of these arrays. If at all possible, it is recommended that these arrays are only used to supply read-only data to the user functions when a multithreaded implementation is being used.
F01ELF makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The integer allocatable memory required is n. If A has real eigenvalues then up to 6 n 2 of real allocatable memory may be required. If A has complex eigenvalues then up to 6 n 2 of complex allocatable memory may be required.
The cost of the Schur–Parlett algorithm depends on the spectrum of A, but is roughly between 28 n 3 and n 4/3 floating-point operations. There is an additional cost in numerically differentiating f, in order to obtain the Taylor series coefficients. If the derivatives of f are known analytically, then F01EMF can be used to evaluate f A more accurately. If A is real symmetric then it is recommended that F01EFF be used as it is more efficient and, in general, more accurate than F01ELF.
For any z on the real line, f z must be real. f must also be complex analytic on the spectrum of A. These conditions ensure that f A is real for real A.
For further information on matrix functions, see Higham (2008).
If estimates of the condition number of the matrix function are required then F01JBF should be used.
F01FLF can be used to find the matrix function f A for a complex matrix A.

10 Example

This example finds cos⁡2 A where
A= 3 0 1 2 -1 1 3 1 0 2 2 1 2 1 -1 1 .

10.1 Program Text

Program Text (f01elfe.f90)

10.2 Program Data

Program Data (f01elfe.d)

10.3 Program Results

Program Results (f01elfe.r)

F01 Chapter Contents
F01 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F01EMF : NAG Library, Mark 26

F01 Chapter Contents
F01 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F01EMF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F01EMF computes the matrix function, f A, of a real n by n matrix A, using analytical derivatives of f you have supplied.

2 Specification

SUBROUTINE F01EMF ( N, A, LDA, F, IUSER, RUSER, IFLAG, IMNORM, IFAIL)
INTEGER | N, LDA, IUSER(*), IFLAG, IFAIL
REAL (KIND=nag_wp) | A(LDA,*), RUSER(*), IMNORM
EXTERNAL | F

3 Description

f A is computed using the Schur–Parlett algorithm described in Higham (2008) and Davies and Higham (2003).
The scalar function f, and the derivatives of f, are returned by the subroutine F which, given an integer m, should evaluate f m zi at a number of (generally complex) points zi, for i=1,2,…,nz. For any z on the real line, f z must also be real. F01EMF is therefore appropriate for functions that can be evaluated on the complex plane and whose derivatives, of arbitrary order, can also be evaluated on the complex plane.

4 References

Davies P I and Higham N J (2003) A Schur–Parlett algorithm for computing matrix functions. SIAM J. Matrix Anal. Appl. 25(2) 464–485
Higham N J (2008) Functions of Matrices: Theory and Computation SIAM, Philadelphia, PA, USA

5 Arguments

1:   N – INTEGERInput
On entry: n, the order of the matrix A.
Constraint: N≥0.
2:   A LDA* – REAL (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array A must be at least N.
On entry: the n by n matrix A.
On exit: the n by n matrix, f A.
3:   LDA – INTEGERInput
On entry: the first dimension of the array A as declared in the (sub)program from which F01EMF is called.
Constraint: LDA≥N.
4:   F – SUBROUTINE, supplied by the user.External Procedure
Given an integer m, the subroutine F evaluates f m zi at a number of points zi.
The specification of F is:
SUBROUTINE F ( M, IFLAG, NZ, Z, FZ, IUSER, RUSER)
INTEGER | M, IFLAG, NZ, IUSER(*)
REAL (KIND=nag_wp) | RUSER(*)
COMPLEX (KIND=nag_wp) | Z(NZ), FZ(NZ)
1:   M – INTEGERInput
On entry: the order, m, of the derivative required.
If M=0, f zi should be returned. For M>0, f m zi should be returned.
2:   IFLAG – INTEGERInput/Output
On entry: IFLAG will be zero.
On exit: IFLAG should either be unchanged from its entry value of zero, or may be set nonzero to indicate that there is a problem in evaluating the function f z; for instance f zi may not be defined for a particular zi. If IFLAG is returned as nonzero then F01EMF will terminate the computation, with IFAIL=2.
3:   NZ – INTEGERInput
On entry: nz, the number of function or derivative values required.
4:   Z NZ – COMPLEX (KIND=nag_wp) arrayInput
On entry: the nz points z 1,z 2,…,z nz at which the function f is to be evaluated.
5:   FZ NZ – COMPLEX (KIND=nag_wp) arrayOutput
On exit: the nz function or derivative values. FZ i should return the value f m zi, for i=1,2,…,nz. If zi lies on the real line, then so must f m zi.
6:   IUSER* – INTEGER arrayUser Workspace
7:   RUSER* – REAL (KIND=nag_wp) arrayUser Workspace
F is called with the arguments IUSER and RUSER as supplied to F01EMF. You are free to use the arrays IUSER and RUSER to supply information to F as an alternative to using COMMON global variables.
F must either be a module subprogram USEd by, or declared as EXTERNAL in, the (sub)program from which F01EMF is called. Arguments denoted as Input must not be changed by this procedure.
5:   IUSER* – INTEGER arrayUser Workspace
6:   RUSER* – REAL (KIND=nag_wp) arrayUser Workspace
IUSER and RUSER are not used by F01EMF, but are passed directly to F and may be used to pass information to this routine as an alternative to using COMMON global variables.
7:   IFLAG – INTEGEROutput
On exit: IFLAG=0, unless IFLAG has been set nonzero inside F, in which case IFLAG will be the value set and IFAIL will be set to IFAIL=2.
8:   IMNORM – REAL (KIND=nag_wp)Output
On exit: if A has complex eigenvalues, F01EMF will use complex arithmetic to compute f A. The imaginary part is discarded at the end of the computation, because it will theoretically vanish. IMNORM contains the 1-norm of the imaginary part, which should be used to check that the routine has given a reliable answer.
If A has real eigenvalues, F01EMF uses real arithmetic and IMNORM=0.
9:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
A Taylor series failed to converge.
IFAIL=2
IFLAG has been set nonzero by the user.
IFAIL=3
There was an error whilst reordering the Schur form of A.
Note: this failure should not occur and suggests that the routine has been called incorrectly.
IFAIL=4
The routine was unable to compute the Schur decomposition of A.
Note: this failure should not occur and suggests that the routine has been called incorrectly.
IFAIL=5
An unexpected internal error occurred. Please contact NAG.
IFAIL=-1
Input argument number value is invalid.
IFAIL=-3
On entry, argument LDA is invalid.
Constraint: LDA≥N.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

For a normal matrix A (for which AT A=A AT), the Schur decomposition is diagonal and the algorithm reduces to evaluating f at the eigenvalues of A and then constructing f A using the Schur vectors. This should give a very accurate result. In general, however, no error bounds are available for the algorithm. See Section 9.4 of Higham (2008) for further discussion of the Schur–Parlett algorithm.

8 Parallelism and Performance

F01EMF is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library. In these implementations, this routine may make calls to the user-supplied functions from within an OpenMP parallel region. Thus OpenMP directives within the user functions can only be used if you are compiling the user-supplied function and linking the executable in accordance with the instructions in the Users' Note for your implementation. The user workspace arrays IUSER and RUSER are classified as OpenMP shared memory and use of IUSER and RUSER has to take account of this in order to preserve thread safety whenever information is written back to either of these arrays. If at all possible, it is recommended that these arrays are only used to supply read-only data to the user functions when a multithreaded implementation is being used.
F01EMF makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

If A has real eigenvalues then up to 6 n 2 of real allocatable memory may be required. If A has complex eigenvalues then up to 6 n 2 of complex allocatable memory may be required.
The cost of the Schur–Parlett algorithm depends on the spectrum of A, but is roughly between 28 n 3 and n 4/3 floating-point operations. There is an additional cost in evaluating f and its derivatives. If the derivatives of f are not known analytically, then F01ELF can be used to evaluate f A using numerical differentiation. If A is real symmetric then it is recommended that F01EFF be used as it is more efficient and, in general, more accurate than F01EMF.
For any z on the real line, f z must be real. f must also be complex analytic on the spectrum of A. These conditions ensure that f A is real for real A.
For further information on matrix functions, see Higham (2008).
If estimates of the condition number of the matrix function are required then F01JCF should be used.
F01FMF can be used to find the matrix function f A for a complex matrix A.

10 Example

This example finds the e 2 A where
A= 1 0 -2 1 -1 2 0 1 2 0 1 0 1 0 -1 2 .

10.1 Program Text

Program Text (f01emfe.f90)

10.2 Program Data

Program Data (f01emfe.d)

10.3 Program Results

Program Results (f01emfe.r)

F01 Chapter Contents
F01 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F01ENF : NAG Library, Mark 26

F01 Chapter Contents
F01 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F01ENF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F01ENF computes the principal matrix square root, A 1/2, of a real n by n matrix A.

2 Specification

SUBROUTINE F01ENF ( N, A, LDA, IFAIL)
INTEGER | N, LDA, IFAIL
REAL (KIND=nag_wp) | A(LDA,*)

3 Description

A square root of a matrix A is a solution X to the equation X 2=A. A nonsingular matrix has multiple square roots. For a matrix with no eigenvalues on the closed negative real line, the principal square root, denoted by A 1/2, is the unique square root whose eigenvalues lie in the open right half-plane.
A 1/2 is computed using the algorithm described in Higham (1987). This is a real arithmetic version of the algorithm of Björck and Hammarling (1983). In addition a blocking scheme described in Deadman et al. (2013) is used.

4 References

Björck Å and Hammarling S (1983) A Schur method for the square root of a matrix Linear Algebra Appl. 52/53 127–140
Deadman E, Higham N J and Ralha R (2013) Blocked Schur Algorithms for Computing the Matrix Square Root Applied Parallel and Scientific Computing: 11th International Conference, (PARA 2012, Helsinki, Finland) P. Manninen and P. Öster, Eds Lecture Notes in Computer Science 7782 171–181 Springer–Verlag
Higham N J (1987) Computing real square roots of a real matrix Linear Algebra Appl. 88/89 405–430
Higham N J (2008) Functions of Matrices: Theory and Computation SIAM, Philadelphia, PA, USA

5 Arguments

1:   N – INTEGERInput
On entry: n, the order of the matrix A.
Constraint: N≥0.
2:   A LDA* – REAL (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array A must be at least N.
On entry: the n by n matrix A.
On exit: contains, if IFAIL=0, the n by n principal matrix square root, A 1/2. Alternatively, if IFAIL=1, contains an n by n non-principal square root of A.
3:   LDA – INTEGERInput
On entry: the first dimension of the array A as declared in the (sub)program from which F01ENF is called.
Constraint: LDA≥N.
4:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
A has a semisimple vanishing eigenvalue. A non-principal square root is returned.
IFAIL=2
A has a defective vanishing eigenvalue. The square root cannot be found in this case.
IFAIL=3
A has a negative real eigenvalue. The principal square root is not defined. F01FNF can be used to return a complex, non-principal square root.
IFAIL=4
An internal error occurred. It is likely that the routine was called incorrectly.
IFAIL=-1
On entry, N=value.
Constraint: N≥0.
IFAIL=-3
On entry, LDA=value and N=value.
Constraint: LDA≥N.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

The computed square root X^ satisfies X^2=A+ΔA, where ΔA F≈O ε n 3 X^F 2, where ε is machine precision.
For further discussion of the condition of the matrix square root see Section 6.1 of Higham (2008).

8 Parallelism and Performance

F01ENF is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
F01ENF makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The cost of the algorithm is 85 n 3/3 floating-point operations; see Algorithm 6.7 of Higham (2008). O 2×n 2 of real allocatable memory is required by the routine.
If condition number and residual bound estimates are required, then F01JDF should be used.

10 Example

This example finds the principal matrix square root of the matrix
A = 507 622 300 -202 237 352 126 -60 751 950 440 -286 -286 -326 -192 150 .

10.1 Program Text

Program Text (f01enfe.f90)

10.2 Program Data

Program Data (f01enfe.d)

10.3 Program Results

Program Results (f01enfe.r)

F01 Chapter Contents
F01 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F01EPF : NAG Library, Mark 26

F01 Chapter Contents
F01 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F01EPF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F01EPF computes the principal matrix square root, A 1/2, of a real upper quasi-triangular n by n matrix A.

2 Specification

SUBROUTINE F01EPF ( N, A, LDA, IFAIL)
INTEGER | N, LDA, IFAIL
REAL (KIND=nag_wp) | A(LDA,*)

3 Description

A square root of a matrix A is a solution X to the equation X 2=A. A nonsingular matrix has multiple square roots. For a matrix with no eigenvalues on the closed negative real line, the principal square root, denoted by A 1/2, is the unique square root whose eigenvalues lie in the open right half-plane.
F01EPF computes A 1/2, where A is an upper quasi-triangular matrix, with 1×1 and 2×2 blocks on the diagonal. Such matrices arise from the Schur factorization of a real general matrix, as computed by F08PEF (DHSEQR), for example. F01EPF does not require A to be in the canonical Schur form described in F08PEF (DHSEQR), it merely requires A to be upper quasi-triangular. A 1/2 then has the same block triangular structure as A.
The algorithm used by F01EPF is described in Higham (1987). In addition a blocking scheme described in Deadman et al. (2013) is used.

4 References

Björck Å and Hammarling S (1983) A Schur method for the square root of a matrix Linear Algebra Appl. 52/53 127–140
Deadman E, Higham N J and Ralha R (2013) Blocked Schur Algorithms for Computing the Matrix Square Root Applied Parallel and Scientific Computing: 11th International Conference, (PARA 2012, Helsinki, Finland) P. Manninen and P. Öster, Eds Lecture Notes in Computer Science 7782 171–181 Springer–Verlag
Higham N J (1987) Computing real square roots of a real matrix Linear Algebra Appl. 88/89 405–430
Higham N J (2008) Functions of Matrices: Theory and Computation SIAM, Philadelphia, PA, USA

5 Arguments

1:   N – INTEGERInput
On entry: n, the order of the matrix A.
Constraint: N≥0.
2:   A LDA* – REAL (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array A must be at least N.
On entry: the n by n upper quasi-triangular matrix A.
On exit: the n by n principal matrix square root A 1/2.
3:   LDA – INTEGERInput
On entry: the first dimension of the array A as declared in the (sub)program from which F01EPF is called.
Constraint: LDA≥N.
4:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
A has negative or vanishing eigenvalues. The principal square root is not defined in this case. F01ENF or F01FNF may be able to provide further information.
IFAIL=2
An internal error occurred. It is likely that the routine was called incorrectly.
IFAIL=-1
On entry, N=value.
Constraint: N≥0.
IFAIL=-3
On entry, LDA=value and N=value.
Constraint: LDA≥N.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

The computed square root X^ satisfies X^2=A+ΔA, where ΔA F≈O ε n X^F 2, where ε is machine precision.

8 Parallelism and Performance

F01EPF is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
F01EPF makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The cost of the algorithm is n 3/3 floating-point operations; see Algorithm 6.7 of Higham (2008). O n of integer allocatable memory is required by the routine.
If A is a full matrix, then F01ENF should be used to compute the square root. If A has negative real eigenvalues then F01FNF can be used to return a complex, non-principal square root.
If condition number and residual bound estimates are required, then F01JDF should be used. For further discussion of the condition of the matrix square root see Section 6.1 of Higham (2008).

10 Example

This example finds the principal matrix square root of the matrix
A = 6 4 -5 15 8 6 -3 10 0 0 3 -4 0 0 4 3 .

10.1 Program Text

Program Text (f01epfe.f90)

10.2 Program Data

Program Data (f01epfe.d)

10.3 Program Results

Program Results (f01epfe.r)

F01 Chapter Contents
F01 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F01EQF : NAG Library, Mark 26

F01 Chapter Contents
F01 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F01EQF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F01EQF computes the principal real power Ap, for arbitrary p, of a real n by n matrix A.

2 Specification

SUBROUTINE F01EQF ( N, A, LDA, P, IFAIL)
INTEGER | N, LDA, IFAIL
REAL (KIND=nag_wp) | A(LDA,*), P

3 Description

For a matrix A with no eigenvalues on the closed negative real line, Ap (p∈ℝ) can be defined as
Ap= exp p log A
where log A is the principal logarithm of A (the unique logarithm whose spectrum lies in the strip z:-π<Im z<π).
Ap is computed using the real version of the Schur–Padé algorithm described in Higham and Lin (2011) and Higham and Lin (2013).
The real number p is expressed as p=q+r where q∈-1,1 and r∈ℤ. Then Ap=AqAr. The integer power Ar is found using a combination of binary powering and, if necessary, matrix inversion. The fractional power Aq is computed, entirely in real arithmetic, using a real Schur decomposition and a Padé approximant.

4 References

Higham N J (2008) Functions of Matrices: Theory and Computation SIAM, Philadelphia, PA, USA
Higham N J and Lin L (2011) A Schur–Padé algorithm for fractional powers of a matrix SIAM J. Matrix Anal. Appl. 32(3) 1056–1078
Higham N J and Lin L (2013) An improved Schur–Padé algorithm for fractional powers of a matrix and their Fréchet derivatives SIAM J. Matrix Anal. Appl. 34(3) 1341–1360

5 Arguments

1:   N – INTEGERInput
On entry: n, the order of the matrix A.
Constraint: N≥0.
2:   A LDA* – REAL (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array A must be at least N.
On entry: the n by n matrix A.
On exit: the n by n matrix pth power, Ap.
3:   LDA – INTEGERInput
On entry: the first dimension of the array A as declared in the (sub)program from which F01EQF is called.
Constraint: LDA≥N.
4:   P – REAL (KIND=nag_wp)Input
On entry: the required power of A.
5:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
A has eigenvalues on the negative real line. The principal pth power is not defined. F01FQF can be used to find a complex, non-principal pth power.
IFAIL=2
A is singular so the pth power cannot be computed.
IFAIL=3
Ap has been computed using an IEEE double precision Padé approximant, although the arithmetic precision is higher than IEEE double precision.
IFAIL=4
An unexpected internal error occurred. This failure should not occur and suggests that the routine has been called incorrectly.
IFAIL=-1
On entry, N=value.
Constraint: N≥0.
IFAIL=-3
On entry, LDA=value and N=value.
Constraint: LDA≥N.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

For positive integer p, the algorithm reduces to a sequence of matrix multiplications. For negative integer p, the algorithm consists of a combination of matrix inversion and matrix multiplications.
For a normal matrix A (for which AT A=A AT) and non-integer p, the Schur decomposition is diagonal and the algorithm reduces to evaluating powers of the eigenvalues of A and then constructing Ap using the Schur vectors. This should give a very accurate result. In general however, no error bounds are available for the algorithm.

8 Parallelism and Performance

F01EQF is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
F01EQF makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The cost of the algorithm is O n 3. The exact cost depends on the matrix A but if p∈-1,1 then the cost is independent of p. O 4×n 2 of real allocatable memory is required by the routine.
If estimates of the condition number of Ap are required then F01JEF should be used.

10 Example

This example finds Ap where p=0.2 and
A = 3 3 2 1 3 1 0 2 1 1 4 3 3 0 3 1 .

10.1 Program Text

Program Text (f01eqfe.f90)

10.2 Program Data

Program Data (f01eqfe.d)

10.3 Program Results

Program Results (f01eqfe.r)

F01 Chapter Contents
F01 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F01FCF : NAG Library, Mark 26

F01 Chapter Contents
F01 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F01FCF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F01FCF computes the matrix exponential, eA, of a complex n by n matrix A.

2 Specification

SUBROUTINE F01FCF ( N, A, LDA, IFAIL)
INTEGER | N, LDA, IFAIL
COMPLEX (KIND=nag_wp) | A(LDA,*)

3 Description

eA is computed using a Padé approximant and the scaling and squaring method described in Al–Mohy and Higham (2009).

4 References

Al–Mohy A H and Higham N J (2009) A new scaling and squaring algorithm for the matrix exponential SIAM J. Matrix Anal. 31(3) 970–989
Higham N J (2005) The scaling and squaring method for the matrix exponential revisited SIAM J. Matrix Anal. Appl. 26(4) 1179–1193
Higham N J (2008) Functions of Matrices: Theory and Computation SIAM, Philadelphia, PA, USA
Moler C B and Van Loan C F (2003) Nineteen dubious ways to compute the exponential of a matrix, twenty-five years later SIAM Rev. 45 3–49

5 Arguments

1:   N – INTEGERInput
On entry: n, the order of the matrix A.
Constraint: N≥0.
2:   A LDA* – COMPLEX (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array A must be at least N.
On entry: the n by n matrix A.
On exit: with IFAIL=0, the n by n matrix exponential eA.
3:   LDA – INTEGERInput
On entry: the first dimension of the array A as declared in the (sub)program from which F01FCF is called.
Constraint: LDA≥N.
4:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
The linear equations to be solved for the Padé approximant are singular; it is likely that this routine has been called incorrectly.
IFAIL=2
The linear equations to be solved are nearly singular and the Padé approximant probably has no correct figures; it is likely that this routine has been called incorrectly.
IFAIL=3
eA has been computed using an IEEE double precision Padé approximant, although the arithmetic precision is higher than IEEE double precision.
IFAIL=4
An unexpected internal error has occurred. Please contact NAG.
IFAIL=-1
On entry, N=value.
Constraint: N≥0.
IFAIL=-3
On entry, LDA=value and N=value.
Constraint: LDA≥N.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

For a normal matrix A (for which AH A=A AH) the computed matrix, eA, is guaranteed to be close to the exact matrix, that is, the method is forward stable. No such guarantee can be given for non-normal matrices. See Al–Mohy and Higham (2009) and Section 10.3 of Higham (2008) for details and further discussion.
If estimates of the condition number of the matrix exponential are required then F01KGF should be used.

8 Parallelism and Performance

F01FCF is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
F01FCF makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The integer allocatable memory required is N, and the complex allocatable memory required is approximately 6×N 2.
The cost of the algorithm is O n 3; see Section 5 of Al–Mohy and Higham (2009). The complex allocatable memory required is approximately 6×n 2.
If the Fréchet derivative of the matrix exponential is required then F01KHF should be used.
As well as the excellent book cited above, the classic reference for the computation of the matrix exponential is Moler and Van Loan (2003).

10 Example

This example finds the matrix exponential of the matrix
A = 1+2 i 2+2 i 2+2 i 2+i 3+2 i 1 1 2+i 3+2 i 2+2 i 1 2+i 3+2 i 3+2 i 3+2 i 1+i .

10.1 Program Text

Program Text (f01fcfe.f90)

10.2 Program Data

Program Data (f01fcfe.d)

10.3 Program Results

Program Results (f01fcfe.r)

F01 Chapter Contents
F01 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F01FDF : NAG Library, Mark 26

F01 Chapter Contents
F01 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F01FDF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F01FDF computes the matrix exponential, eA, of a complex Hermitian n by n matrix A.

2 Specification

SUBROUTINE F01FDF ( UPLO, N, A, LDA, IFAIL)
INTEGER | N, LDA, IFAIL
COMPLEX (KIND=nag_wp) | A(LDA,*)
CHARACTER(1) | UPLO

3 Description

eA is computed using a spectral factorization of A
A = Q D QH ,
where D is the diagonal matrix whose diagonal elements, di, are the eigenvalues of A, and Q is a unitary matrix whose columns are the eigenvectors of A. eA is then given by
eA = Q eD QH ,
where eD is the diagonal matrix whose ith diagonal element is e di. See for example Section 4.5 of Higham (2008).

4 References

Higham N J (2005) The scaling and squaring method for the matrix exponential revisited SIAM J. Matrix Anal. Appl. 26(4) 1179–1193
Higham N J (2008) Functions of Matrices: Theory and Computation SIAM, Philadelphia, PA, USA
Moler C B and Van Loan C F (2003) Nineteen dubious ways to compute the exponential of a matrix, twenty-five years later SIAM Rev. 45 3–49

5 Arguments

1:   UPLO – CHARACTER(1)Input
On entry: if UPLO='U', the upper triangle of the matrix A is stored.
If UPLO='L', the lower triangle of the matrix A is stored.
Constraint: UPLO='U' or 'L'.
2:   N – INTEGERInput
On entry: n, the order of the matrix A.
Constraint: N≥0.
3:   A LDA* – COMPLEX (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array A must be at least N.
On entry: the n by n Hermitian matrix A.
  • If UPLO='U', the upper triangular part of A must be stored and the elements of the array below the diagonal are not referenced.
  • If UPLO='L', the lower triangular part of A must be stored and the elements of the array above the diagonal are not referenced.
On exit: if IFAIL=0, the upper or lower triangular part of the n by n matrix exponential, eA.
4:   LDA – INTEGERInput
On entry: the first dimension of the array A as declared in the (sub)program from which F01FDF is called.
Constraint: LDA≥N.
5:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL>0
The computation of the spectral factorization failed to converge.
IFAIL=-1
On entry, UPLO was invalid.
IFAIL=-2
On entry, N=value.
Constraint: N≥0.
IFAIL=-3
An internal error occurred when computing the spectral factorization. Please contact NAG.
IFAIL=-4
On entry, LDA=value and N=value.
Constraint: LDA≥N.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

For an Hermitian matrix A, the matrix eA, has the relative condition number
κ A = A 2 ,
which is the minimal possible for the matrix exponential and so the computed matrix exponential is guaranteed to be close to the exact matrix. See Section 10.2 of Higham (2008) for details and further discussion.

8 Parallelism and Performance

F01FDF is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
F01FDF makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The integer allocatable memory required is N, the real allocatable memory required is N and the complex allocatable memory required is approximately N+nb+1×N, where nb is the block size required by F08FNF (ZHEEV).
The cost of the algorithm is O n 3.
As well as the excellent book cited above, the classic reference for the computation of the matrix exponential is Moler and Van Loan (2003).

10 Example

This example finds the matrix exponential of the Hermitian matrix
A = 1 2+2 i 3+2 i 4+3 i 2-2 i 1 2+2 i 3+2 i 3-2 i 2-2 i 1 2+2 i 4-3 i 3-2 i 2-2 i 1 .

10.1 Program Text

Program Text (f01fdfe.f90)

10.2 Program Data

Program Data (f01fdfe.d)

10.3 Program Results

Program Results (f01fdfe.r)

F01 Chapter Contents
F01 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F01FFF : NAG Library, Mark 26

F01 Chapter Contents
F01 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F01FFF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F01FFF computes the matrix function, f A, of a complex Hermitian n by n matrix A. f A must also be a complex Hermitian matrix.

2 Specification

SUBROUTINE F01FFF ( UPLO, N, A, LDA, F, IUSER, RUSER, IFLAG, IFAIL)
INTEGER | N, LDA, IUSER(*), IFLAG, IFAIL
REAL (KIND=nag_wp) | RUSER(*)
COMPLEX (KIND=nag_wp) | A(LDA,*)
CHARACTER(1) | UPLO
EXTERNAL | F

3 Description

f A is computed using a spectral factorization of A
A = Q D QH ,
where D is the real diagonal matrix whose diagonal elements, di, are the eigenvalues of A, Q is a unitary matrix whose columns are the eigenvectors of A and QH is the conjugate transpose of Q. f A is then given by
f A = Q f D QH ,
where f D is the diagonal matrix whose ith diagonal element is f di. See for example Section 4.5 of Higham (2008). f di is assumed to be real.

4 References

Higham N J (2008) Functions of Matrices: Theory and Computation SIAM, Philadelphia, PA, USA

5 Arguments

1:   UPLO – CHARACTER(1)Input
On entry: if UPLO='U', the upper triangle of the matrix A is stored.
If UPLO='L', the lower triangle of the matrix A is stored.
Constraint: UPLO='U' or 'L'.
2:   N – INTEGERInput
On entry: n, the order of the matrix A.
Constraint: N≥0.
3:   A LDA* – COMPLEX (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array A must be at least N.
On entry: the n by n Hermitian matrix A.
  • If UPLO='U', the upper triangular part of A must be stored and the elements of the array below the diagonal are not referenced.
  • If UPLO='L', the lower triangular part of A must be stored and the elements of the array above the diagonal are not referenced.
On exit: if IFAIL=0, the upper or lower triangular part of the n by n matrix function, f A.
4:   LDA – INTEGERInput
On entry: the first dimension of the array A as declared in the (sub)program from which F01FFF is called.
Constraint: LDA≥max 1,N.
5:   F – SUBROUTINE, supplied by the user.External Procedure
The subroutine F evaluates f zi at a number of points zi.
The specification of F is:
SUBROUTINE F ( IFLAG, N, X, FX, IUSER, RUSER)
INTEGER | IFLAG, N, IUSER(*)
REAL (KIND=nag_wp) | X(N), FX(N), RUSER(*)
1:   IFLAG – INTEGERInput/Output
On entry: IFLAG will be zero.
On exit: IFLAG should either be unchanged from its entry value of zero, or may be set nonzero to indicate that there is a problem in evaluating the function f x; for instance f x may not be defined, or may be complex. If IFLAG is returned as nonzero then F01FFF will terminate the computation, with IFAIL=-6.
2:   N – INTEGERInput
On entry: n, the number of function values required.
3:   X N – REAL (KIND=nag_wp) arrayInput
On entry: the n points x 1,x 2,…,xn at which the function f is to be evaluated.
4:   FX N – REAL (KIND=nag_wp) arrayOutput
On exit: the n function values. FX i should return the value f xi, for i=1,2,…,n.
5:   IUSER* – INTEGER arrayUser Workspace
6:   RUSER* – REAL (KIND=nag_wp) arrayUser Workspace
F is called with the arguments IUSER and RUSER as supplied to F01FFF. You are free to use the arrays IUSER and RUSER to supply information to F as an alternative to using COMMON global variables.
F must either be a module subprogram USEd by, or declared as EXTERNAL in, the (sub)program from which F01FFF is called. Arguments denoted as Input must not be changed by this procedure.
6:   IUSER* – INTEGER arrayUser Workspace
7:   RUSER* – REAL (KIND=nag_wp) arrayUser Workspace
IUSER and RUSER are not used by F01FFF, but are passed directly to F and may be used to pass information to this routine as an alternative to using COMMON global variables.
8:   IFLAG – INTEGEROutput
On exit: IFLAG=0, unless you have set IFLAG nonzero inside F, in which case IFLAG will be the value you set and IFAIL will be set to IFAIL=-6.
9:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL>0
The computation of the spectral factorization failed to converge.
IFAIL=-1
On entry, UPLO=value.
Constraint: UPLO='L' or 'U'.
IFAIL=-2
On entry, N=value.
Constraint: N≥0.
IFAIL=-3
An internal error occurred when computing the spectral factorization. Please contact NAG.
IFAIL=-4
On entry, LDA=value and N=value.
Constraint: LDA≥N.
IFAIL=-6
IFLAG was set to a nonzero value in F.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

Provided that f D can be computed accurately then the computed matrix function will be close to the exact matrix function. See Section 10.2 of Higham (2008) for details and further discussion.

8 Parallelism and Performance

F01FFF is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
F01FFF makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The integer allocatable memory required is N, the real allocatable memory required is 4×N-2 and the complex allocatable memory required is approximately N+nb+1×N, where nb is the block size required by F08FNF (ZHEEV).
The cost of the algorithm is O n 3 plus the cost of evaluating f D. If λ^i is the ith computed eigenvalue of A, then the user-supplied subroutine F will be asked to evaluate the function f at f λ^i, for i=1,2,…,n.
For further information on matrix functions, see Higham (2008).
F01EFF can be used to find the matrix function f A for a real symmetric matrix A.

10 Example

This example finds the matrix cosine, cos A, of the Hermitian matrix
A= 1 2+i 3+2 i 4+3 i 2-i 1 2+i 3+2 i 3-2 i 2-i 1 2+i 4-3 i 3-2 i 2-i 1 .

10.1 Program Text

Program Text (f01fffe.f90)

10.2 Program Data

Program Data (f01fffe.d)

10.3 Program Results

Program Results (f01fffe.r)

F01 Chapter Contents
F01 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F01FJF : NAG Library, Mark 26

F01 Chapter Contents
F01 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F01FJF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F01FJF computes the principal matrix logarithm, log A, of a complex n by n matrix A, with no eigenvalues on the closed negative real line.

2 Specification

SUBROUTINE F01FJF ( N, A, LDA, IFAIL)
INTEGER | N, LDA, IFAIL
COMPLEX (KIND=nag_wp) | A(LDA,*)

3 Description

Any nonsingular matrix A has infinitely many logarithms. For a matrix with no eigenvalues on the closed negative real line, the principal logarithm is the unique logarithm whose spectrum lies in the strip z:-π<Im⁡z<π. If A is nonsingular but has eigenvalues on the negative real line, the principal logarithm is not defined, but F01FJF will return a non-principal logarithm.
log A is computed using the inverse scaling and squaring algorithm for the matrix logarithm described in Al–Mohy and Higham (2011).

4 References

Al–Mohy A H and Higham N J (2011) Improved inverse scaling and squaring algorithms for the matrix logarithm SIAM J. Sci. Comput. 34(4) C152–C169
Higham N J (2008) Functions of Matrices: Theory and Computation SIAM, Philadelphia, PA, USA

5 Arguments

1:   N – INTEGERInput
On entry: n, the order of the matrix A.
Constraint: N≥0.
2:   A LDA* – COMPLEX (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array A must be at least N.
On entry: the n by n matrix A.
On exit: the n by n principal matrix logarithm, log A, unless IFAIL=2, in which case a non-principal logarithm is returned.
3:   LDA – INTEGERInput
On entry: the first dimension of the array A as declared in the (sub)program from which F01FJF is called.
Constraint: LDA≥N.
4:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
A is singular so the logarithm cannot be computed.
IFAIL=2
A was found to have eigenvalues on the negative real line. The principal logarithm is not defined in this case, so a non-principal logarithm was returned.
IFAIL=3
log A has been computed using an IEEE double precision Padé approximant, although the arithmetic precision is higher than IEEE double precision.
IFAIL=4
An unexpected internal error has occurred. Please contact NAG.
IFAIL=-1
On entry, N=value.
Constraint: N≥0.
IFAIL=-3
On entry, LDA=value and N=value.
Constraint: LDA≥N.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

For a normal matrix A (for which AH A=A AH), the Schur decomposition is diagonal and the algorithm reduces to evaluating the logarithm of the eigenvalues of A and then constructing log A using the Schur vectors. This should give a very accurate result. In general, however, no error bounds are available for the algorithm. See Al–Mohy and Higham (2011) and Section 9.4 of Higham (2008) for details and further discussion.
The sensitivity of the computation of log A is worst when A has an eigenvalue of very small modulus or has a complex conjugate pair of eigenvalues lying close to the negative real axis.
If estimates of the condition number of the matrix logarithm are required then F01KJF should be used.

8 Parallelism and Performance

F01FJF is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
F01FJF makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The cost of the algorithm is O n 3 floating-point operations (see Al–Mohy and Higham (2011)). The complex allocatable memory required is approximately 3×n 2.
If the Fréchet derivative of the matrix logarithm is required then F01KKF should be used.
F01EJF can be used to find the principal logarithm of a real matrix.

10 Example

This example finds the principal matrix logarithm of the matrix
A = 1.0+2.0 i 0.0+1.0 i 1.0+0.0 i 3.0+2.0 i 0.0+3.0 i -2.0+0.0 i 0.0+0.0 i 1.0+0.0 i 1.0+0.0 i -2.0+0.0 i 3.0+2.0 i 0.0+3.0 i 2.0+0.0 i 0.0+1.0 i 0.0+1.0 i 2.0+3.0 i .

10.1 Program Text

Program Text (f01fjfe.f90)

10.2 Program Data

Program Data (f01fjfe.d)

10.3 Program Results

Program Results (f01fjfe.r)

F01 Chapter Contents
F01 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F01FKF : NAG Library, Mark 26

F01 Chapter Contents
F01 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F01FKF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F01FKF computes the matrix exponential, sine, cosine, sinh or cosh, of a complex n by n matrix A using the Schur–Parlett algorithm.

2 Specification

SUBROUTINE F01FKF ( FUN, N, A, LDA, IFAIL)
INTEGER | N, LDA, IFAIL
COMPLEX (KIND=nag_wp) | A(LDA,*)
CHARACTER(*) | FUN

3 Description

f A, where f is either the exponential, sine, cosine, sinh or cosh, is computed using the Schur–Parlett algorithm described in Higham (2008) and Davies and Higham (2003).

4 References

Davies P I and Higham N J (2003) A Schur–Parlett algorithm for computing matrix functions. SIAM J. Matrix Anal. Appl. 25(2) 464–485
Higham N J (2008) Functions of Matrices: Theory and Computation SIAM, Philadelphia, PA, USA

5 Arguments

1:   FUN – CHARACTER(*)Input
On entry: indicates which matrix function will be computed.
FUN='EXP'
The matrix exponential, eA, will be computed.
FUN='SIN'
The matrix sine, sin A, will be computed.
FUN='COS'
The matrix cosine, cos A, will be computed.
FUN='SINH'
The hyperbolic matrix sine, sinh A, will be computed.
FUN='COSH'
The hyperbolic matrix cosine, cosh A, will be computed.
Constraint: FUN='EXP', 'SIN', 'COS', 'SINH' or 'COSH'.
2:   N – INTEGERInput
On entry: n, the order of the matrix A.
Constraint: N≥0.
3:   A LDA* – COMPLEX (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array A must be at least N.
On entry: the n by n matrix A.
On exit: the n by n matrix, f A.
4:   LDA – INTEGERInput
On entry: the first dimension of the array A as declared in the (sub)program from which F01FKF is called.
Constraint: LDA≥N.
5:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
A Taylor series failed to converge.
IFAIL=2
An unexpected internal error occurred when evaluating the function at a point. Please contact NAG.
IFAIL=3
There was an error whilst reordering the Schur form of A.
Note: this failure should not occur and suggests that the routine has been called incorrectly.
IFAIL=4
The routine was unable to compute the Schur decomposition of A.
Note: this failure should not occur and suggests that the routine has been called incorrectly.
IFAIL=5
An unexpected internal error occurred. Please contact NAG.
IFAIL=6
The linear equations to be solved are nearly singular and the Padé approximant used to compute the exponential may have no correct figures.
Note: this failure should not occur and suggests that the routine has been called incorrectly.
IFAIL=-1
On entry, FUN=value was an illegal value.
IFAIL=-2
Input argument number value is invalid.
IFAIL=-4
On entry, argument LDA is invalid.
Constraint: LDA≥N.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

For a normal matrix A (for which AH A=A AH), the Schur decomposition is diagonal and the algorithm reduces to evaluating f at the eigenvalues of A and then constructing f A using the Schur vectors. This should give a very accurate result. In general, however, no error bounds are available for the algorithm.
For further discussion of the Schur–Parlett algorithm see Section 9.4 of Higham (2008).

8 Parallelism and Performance

F01FKF is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library. In these implementations, this routine may make calls to the user-supplied functions from within an OpenMP parallel region. Thus OpenMP directives within the user functions can only be used if you are compiling the user-supplied function and linking the executable in accordance with the instructions in the Users' Note for your implementation.
F01FKF makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The integer allocatable memory required is n, and the complex allocatable memory required is approximately 9 n 2.
The cost of the Schur–Parlett algorithm depends on the spectrum of A, but is roughly between 28 n 3 and n 4/3 floating-point operations; see Algorithm 9.6 of Higham (2008).
If the matrix exponential is required then it is recommended that F01FCF be used. F01FCF uses an algorithm which is, in general, more accurate than the Schur–Parlett algorithm used by F01FKF.
If estimates of the condition number of the matrix function are required then F01KAF should be used.
F01EKF can be used to find the matrix exponential, sin, cos, sinh or cosh of a real matrix A.

10 Example

This example finds the matrix sinh of the matrix
A = 1.0+1.0 i 0.0+0.0 i 1.0+3.0 i 0.0+0.0 i 0.0+0.0 i 2.0+0.0 i 0.0+0.0 i 1.0+2.0 i 3.0+1.0 i 0.0+4.0 i 1.0+1.0 i 0.0+0.0 i 1.0+1.0 i 0.0+2.0 i 0.0+0.0 i 1.0+0.0 i .

10.1 Program Text

Program Text (f01fkfe.f90)

10.2 Program Data

Program Data (f01fkfe.d)

10.3 Program Results

Program Results (f01fkfe.r)

F01 Chapter Contents
F01 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F01FLF : NAG Library, Mark 26

F01 Chapter Contents
F01 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F01FLF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F01FLF computes the matrix function, f A, of a complex n by n matrix A. Numerical differentiation is used to evaluate the derivatives of f when they are required.

2 Specification

SUBROUTINE F01FLF ( N, A, LDA, F, IUSER, RUSER, IFLAG, IFAIL)
INTEGER | N, LDA, IUSER(*), IFLAG, IFAIL
REAL (KIND=nag_wp) | RUSER(*)
COMPLEX (KIND=nag_wp) | A(LDA,*)
EXTERNAL | F

3 Description

f A is computed using the Schur–Parlett algorithm described in Higham (2008) and Davies and Higham (2003). The coefficients of the Taylor series used in the algorithm are evaluated using the numerical differentiation algorithm of Lyness and Moler (1967).
The scalar function f is supplied via subroutine F which evaluates f zi at a number of points zi.

4 References

Davies P I and Higham N J (2003) A Schur–Parlett algorithm for computing matrix functions. SIAM J. Matrix Anal. Appl. 25(2) 464–485
Higham N J (2008) Functions of Matrices: Theory and Computation SIAM, Philadelphia, PA, USA
Lyness J N and Moler C B (1967) Numerical differentiation of analytic functions SIAM J. Numer. Anal. 4(2) 202–210

5 Arguments

1:   N – INTEGERInput
On entry: n, the order of the matrix A.
Constraint: N≥0.
2:   A LDA* – COMPLEX (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array A must be at least N.
On entry: the n by n matrix A.
On exit: the n by n matrix, f A.
3:   LDA – INTEGERInput
On entry: the first dimension of the array A as declared in the (sub)program from which F01FLF is called.
Constraint: LDA≥N.
4:   F – SUBROUTINE, supplied by the user.External Procedure
The subroutine F evaluates f zi at a number of points zi.
The specification of F is:
SUBROUTINE F ( IFLAG, NZ, Z, FZ, IUSER, RUSER)
INTEGER | IFLAG, NZ, IUSER(*)
REAL (KIND=nag_wp) | RUSER(*)
COMPLEX (KIND=nag_wp) | Z(NZ), FZ(NZ)
1:   IFLAG – INTEGERInput/Output
On entry: IFLAG will be zero.
On exit: IFLAG should either be unchanged from its entry value of zero, or may be set nonzero to indicate that there is a problem in evaluating the function f zi; for instance f zi may not be defined. If IFLAG is returned as nonzero then F01FLF will terminate the computation, with IFAIL=2.
2:   NZ – INTEGERInput
On entry: nz, the number of function values required.
3:   Z NZ – COMPLEX (KIND=nag_wp) arrayInput
On entry: the nz points z 1,z 2,…,z nz at which the function f is to be evaluated.
4:   FZ NZ – COMPLEX (KIND=nag_wp) arrayOutput
On exit: the nz function values. FZ i should return the value f zi, for i=1,2,…,nz.
5:   IUSER* – INTEGER arrayUser Workspace
6:   RUSER* – REAL (KIND=nag_wp) arrayUser Workspace
F is called with the arguments IUSER and RUSER as supplied to F01FLF. You are free to use the arrays IUSER and RUSER to supply information to F as an alternative to using COMMON global variables.
F must either be a module subprogram USEd by, or declared as EXTERNAL in, the (sub)program from which F01FLF is called. Arguments denoted as Input must not be changed by this procedure.
5:   IUSER* – INTEGER arrayUser Workspace
6:   RUSER* – REAL (KIND=nag_wp) arrayUser Workspace
IUSER and RUSER are not used by F01FLF, but are passed directly to F and may be used to pass information to this routine as an alternative to using COMMON global variables.
7:   IFLAG – INTEGEROutput
On exit: IFLAG=0, unless IFLAG has been set nonzero inside F, in which case IFLAG will be the value set and IFAIL will be set to IFAIL=2.
8:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
A Taylor series failed to converge after 40 terms. Further Taylor series coefficients can no longer reliably be obtained by numerical differentiation.
IFAIL=2
IFLAG has been set nonzero by the user.
IFAIL=3
The function was unable to compute the Schur decomposition of A.
Note: this failure should not occur and suggests that the routine has been called incorrectly.
There was an error whilst reordering the Schur form of A.
Note: this failure should not occur and suggests that the routine has been called incorrectly.
IFAIL=5
An unexpected internal error occurred. Please contact NAG.
IFAIL=-1
Input argument number value is invalid.
IFAIL=-3
On entry, argument LDA is invalid.
Constraint: LDA≥N.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

For a normal matrix A (for which AH A=A AH) Schur decomposition is diagonal and the algorithm reduces to evaluating f at the eigenvalues of A and then constructing f A using the Schur vectors. See Section 9.4 of Higham (2008) for further discussion of the Schur–Parlett algorithm, and Lyness and Moler (1967) for a discussion of numerical differentiation.

8 Parallelism and Performance

F01FLF is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library. In these implementations, this routine may make calls to the user-supplied functions from within an OpenMP parallel region. Thus OpenMP directives within the user functions can only be used if you are compiling the user-supplied function and linking the executable in accordance with the instructions in the Users' Note for your implementation. The user workspace arrays IUSER and RUSER are classified as OpenMP shared memory and use of IUSER and RUSER has to take account of this in order to preserve thread safety whenever information is written back to either of these arrays. If at all possible, it is recommended that these arrays are only used to supply read-only data to the user functions when a multithreaded implementation is being used.
F01FLF makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The integer allocatable memory required is n, and up to 6 n 2 of complex allocatable memory is required.
The cost of the Schur–Parlett algorithm depends on the spectrum of A, but is roughly between 28 n 3 and n 4/3 floating-point operations. There is an additional cost in numerically differentiating f, in order to obtain the Taylor series coefficients. If the derivatives of f are known analytically, then F01FMF can be used to evaluate f A more accurately. If A is complex Hermitian then it is recommended that F01FFF be used as it is more efficient and, in general, more accurate than F01FLF.
Note that f must be analytic in the region of the complex plane containing the spectrum of A.
For further information on matrix functions, see Higham (2008).
If estimates of the condition number of the matrix function are required then F01KBF should be used.
F01ELF can be used to find the matrix function f A for a real matrix A.

10 Example

This example finds sin⁡2 A where
A= 1.0+0.0 i 0.0+1.0 i 1.0+0.0 i 0.0+1.0 i -1.0+0.0 i 0.0+0.0 i 2.0+1.0 i 0.0+0.0 i 0.0+0.0 i 2.0+1.0 i 0.0+2.0 i 0.0+1.0 i 1.0+0.0 i 1.0+1.0 i -1.0+0.0 i 2.0+1.0 i .

10.1 Program Text

Program Text (f01flfe.f90)

10.2 Program Data

Program Data (f01flfe.d)

10.3 Program Results

Program Results (f01flfe.r)

F01 Chapter Contents
F01 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F01FMF : NAG Library, Mark 26

F01 Chapter Contents
F01 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F01FMF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F01FMF computes the matrix function, f A, of a complex n by n matrix A, using analytical derivatives of f you have supplied.

2 Specification

SUBROUTINE F01FMF ( N, A, LDA, F, IUSER, RUSER, IFLAG, IFAIL)
INTEGER | N, LDA, IUSER(*), IFLAG, IFAIL
REAL (KIND=nag_wp) | RUSER(*)
COMPLEX (KIND=nag_wp) | A(LDA,*)
EXTERNAL | F

3 Description

f A is computed using the Schur–Parlett algorithm described in Higham (2008) and Davies and Higham (2003).
The scalar function f, and the derivatives of f, are returned by the subroutine F which, given an integer m, should evaluate f m zi at a number of points zi, for i=1,2,…,nz, on the complex plane. F01FMF is therefore appropriate for functions that can be evaluated on the complex plane and whose derivatives, of arbitrary order, can also be evaluated on the complex plane.

4 References

Davies P I and Higham N J (2003) A Schur–Parlett algorithm for computing matrix functions. SIAM J. Matrix Anal. Appl. 25(2) 464–485
Higham N J (2008) Functions of Matrices: Theory and Computation SIAM, Philadelphia, PA, USA

5 Arguments

1:   N – INTEGERInput
On entry: n, the order of the matrix A.
Constraint: N≥0.
2:   A LDA* – COMPLEX (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array A must be at least N.
On entry: the n by n matrix A.
On exit: the n by n matrix, f A.
3:   LDA – INTEGERInput
On entry: the first dimension of the array A as declared in the (sub)program from which F01FMF is called.
Constraint: LDA≥N.
4:   F – SUBROUTINE, supplied by the user.External Procedure
Given an integer m, the subroutine F evaluates f m zi at a number of points zi.
The specification of F is:
SUBROUTINE F ( M, IFLAG, NZ, Z, FZ, IUSER, RUSER)
INTEGER | M, IFLAG, NZ, IUSER(*)
REAL (KIND=nag_wp) | RUSER(*)
COMPLEX (KIND=nag_wp) | Z(NZ), FZ(NZ)
1:   M – INTEGERInput
On entry: the order, m, of the derivative required.
If M=0, f zi should be returned. For M>0, f m zi should be returned.
2:   IFLAG – INTEGERInput/Output
On entry: IFLAG will be zero.
On exit: IFLAG should either be unchanged from its entry value of zero, or may be set nonzero to indicate that there is a problem in evaluating the function f z; for instance f zi may not be defined for a particular zi. If IFLAG is returned as nonzero then F01FMF will terminate the computation, with IFAIL=2.
3:   NZ – INTEGERInput
On entry: nz, the number of function or derivative values required.
4:   Z NZ – COMPLEX (KIND=nag_wp) arrayInput
On entry: the nz points z 1,z 2,…,z nz at which the function f is to be evaluated.
5:   FZ NZ – COMPLEX (KIND=nag_wp) arrayOutput
On exit: the nz function or derivative values. FZ i should return the value f m zi, for i=1,2,…,nz.
6:   IUSER* – INTEGER arrayUser Workspace
7:   RUSER* – REAL (KIND=nag_wp) arrayUser Workspace
F is called with the arguments IUSER and RUSER as supplied to F01FMF. You are free to use the arrays IUSER and RUSER to supply information to F as an alternative to using COMMON global variables.
F must either be a module subprogram USEd by, or declared as EXTERNAL in, the (sub)program from which F01FMF is called. Arguments denoted as Input must not be changed by this procedure.
5:   IUSER* – INTEGER arrayUser Workspace
6:   RUSER* – REAL (KIND=nag_wp) arrayUser Workspace
IUSER and RUSER are not used by F01FMF, but are passed directly to F and may be used to pass information to this routine as an alternative to using COMMON global variables.
7:   IFLAG – INTEGEROutput
On exit: IFLAG=0, unless IFLAG has been set nonzero inside F, in which case IFLAG will be the value set and IFAIL will be set to IFAIL=2.
8:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
A Taylor series failed to converge.
IFAIL=2
IFLAG has been set nonzero by the user.
IFAIL=3
There was an error whilst reordering the Schur form of A.
Note: this failure should not occur and suggests that the routine has been called incorrectly.
IFAIL=4
The routine was unable to compute the Schur decomposition of A.
Note: this failure should not occur and suggests that the routine has been called incorrectly.
IFAIL=5
An unexpected internal error occurred. Please contact NAG.
IFAIL=-1
Input argument number value is invalid.
IFAIL=-3
On entry, argument LDA is invalid.
Constraint: LDA≥N.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

For a normal matrix A (for which AH A=A AH), the Schur decomposition is diagonal and the algorithm reduces to evaluating f at the eigenvalues of A and then constructing f A using the Schur vectors. This should give a very accurate result. In general, however, no error bounds are available for the algorithm. See Section 9.4 of Higham (2008) for further discussion of the Schur–Parlett algorithm.

8 Parallelism and Performance

F01FMF is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library. In these implementations, this routine may make calls to the user-supplied functions from within an OpenMP parallel region. Thus OpenMP directives within the user functions can only be used if you are compiling the user-supplied function and linking the executable in accordance with the instructions in the Users' Note for your implementation. The user workspace arrays IUSER and RUSER are classified as OpenMP shared memory and use of IUSER and RUSER has to take account of this in order to preserve thread safety whenever information is written back to either of these arrays. If at all possible, it is recommended that these arrays are only used to supply read-only data to the user functions when a multithreaded implementation is being used.
F01FMF makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

Up to 6 n 2 of complex allocatable memory is required.
The cost of the Schur–Parlett algorithm depends on the spectrum of A, but is roughly between 28 n 3 and n 4/3 floating-point operations. There is an additional cost in evaluating f and its derivatives. If the derivatives of f are not known analytically, then F01FLF can be used to evaluate f A using numerical differentiation. If A is complex Hermitian then it is recommended that F01FFF be used as it is more efficient and, in general, more accurate than F01FMF.
Note that f must be analytic in the region of the complex plane containing the spectrum of A.
For further information on matrix functions, see Higham (2008).
If estimates of the condition number of the matrix function are required then F01KCF should be used.
F01EMF can be used to find the matrix function f A for a real matrix A.

10 Example

This example finds the e 3 A where
A= 1.0+0.0 i 0.0+0.0 i 1.0+0.0 i 0.0+2.0 i 0.0+1.0 i 1.0+0.0 i -1.0+0.0 i 1.0+0.0 i -1.0+0.0 i 0.0+1.0 i 0.0+1.0 i 0.0+1.0 i 1.0+1.0 i 0.0+2.0 i -1.0+0.0 i 0.0+1.0 i .

10.1 Program Text

Program Text (f01fmfe.f90)

10.2 Program Data

Program Data (f01fmfe.d)

10.3 Program Results

Program Results (f01fmfe.r)

F01 Chapter Contents
F01 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F01FNF : NAG Library, Mark 26

F01 Chapter Contents
F01 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F01FNF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F01FNF computes the principal matrix square root, A 1/2, of a complex n by n matrix A.

2 Specification

SUBROUTINE F01FNF ( N, A, LDA, IFAIL)
INTEGER | N, LDA, IFAIL
COMPLEX (KIND=nag_wp) | A(LDA,*)

3 Description

A square root of a matrix A is a solution X to the equation X 2=A. A nonsingular matrix has multiple square roots. For a matrix with no eigenvalues on the closed negative real line, the principal square root, denoted by A 1/2, is the unique square root whose eigenvalues lie in the open right half-plane.
A 1/2 is computed using the algorithm described in Björck and Hammarling (1983). In addition a blocking scheme described in Deadman et al. (2013) is used.

4 References

Björck Å and Hammarling S (1983) A Schur method for the square root of a matrix Linear Algebra Appl. 52/53 127–140
Deadman E, Higham N J and Ralha R (2013) Blocked Schur Algorithms for Computing the Matrix Square Root Applied Parallel and Scientific Computing: 11th International Conference, (PARA 2012, Helsinki, Finland) P. Manninen and P. Öster, Eds Lecture Notes in Computer Science 7782 171–181 Springer–Verlag
Higham N J (2008) Functions of Matrices: Theory and Computation SIAM, Philadelphia, PA, USA

5 Arguments

1:   N – INTEGERInput
On entry: n, the order of the matrix A.
Constraint: N≥0.
2:   A LDA* – COMPLEX (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array A must be at least N.
On entry: the n by n matrix A.
On exit: contains, if IFAIL=0, the n by n principal matrix square root, A 1/2. Alternatively, if IFAIL=1, contains an n by n non-principal square root of A.
3:   LDA – INTEGERInput
On entry: the first dimension of the array A as declared in the (sub)program from which F01FNF is called.
Constraint: LDA≥N.
4:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
A has a negative or semisimple vanishing eigenvalue. A non-principal square root is returned.
IFAIL=2
A has a defective vanishing eigenvalue. The square root cannot be found in this case.
IFAIL=3
An internal error occurred. It is likely that the routine was called incorrectly.
IFAIL=-1
On entry, N=value.
Constraint: N≥0.
IFAIL=-3
On entry, LDA=value and N=value.
Constraint: LDA≥N.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

The computed square root X^ satisfies X^2=A+ΔA, where ΔA F≈O ε n 3 X^F 2, where ε is machine precision.

8 Parallelism and Performance

F01FNF is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
F01FNF makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The cost of the algorithm is 85 n 3/3 complex floating-point operations; see Algorithm 6.3 in Higham (2008). O 2×n 2 of complex allocatable memory is required by the routine.
If condition number and residual bound estimates are required, then F01KDF should be used. For further discussion of the condition of the matrix square root see Section 6.1 of Higham (2008).

10 Example

This example finds the principal matrix square root of the matrix
A = 105+121 i -21+157 i 42+18 i -4-0 2 i 174+0 72 i 28+236 i 51+31 i 16-0 6 i 176+0 52 i 37+177 i 23+27 i 25+13 i -9+125 i -111+0 67 i -8+30 i 0 8 i .

10.1 Program Text

Program Text (f01fnfe.f90)

10.2 Program Data

Program Data (f01fnfe.d)

10.3 Program Results

Program Results (f01fnfe.r)

F01 Chapter Contents
F01 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F01FPF : NAG Library, Mark 26

F01 Chapter Contents
F01 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F01FPF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F01FPF computes the principal matrix square root, A 1/2, of a complex upper triangular n by n matrix A.

2 Specification

SUBROUTINE F01FPF ( N, A, LDA, IFAIL)
INTEGER | N, LDA, IFAIL
COMPLEX (KIND=nag_wp) | A(LDA,*)

3 Description

A square root of a matrix A is a solution X to the equation X 2=A. A nonsingular matrix has multiple square roots. For a matrix with no eigenvalues on the closed negative real line, the principal square root, denoted by A 1/2, is the unique square root whose eigenvalues lie in the open right half-plane.
F01FPF computes A 1/2, where A is an upper triangular matrix. A 1/2 is also upper triangular.
The algorithm used by F01FPF is described in Björck and Hammarling (1983). In addition a blocking scheme described in Deadman et al. (2013) is used.

4 References

Björck Å and Hammarling S (1983) A Schur method for the square root of a matrix Linear Algebra Appl. 52/53 127–140
Deadman E, Higham N J and Ralha R (2013) Blocked Schur Algorithms for Computing the Matrix Square Root Applied Parallel and Scientific Computing: 11th International Conference, (PARA 2012, Helsinki, Finland) P. Manninen and P. Öster, Eds Lecture Notes in Computer Science 7782 171–181 Springer–Verlag
Higham N J (2008) Functions of Matrices: Theory and Computation SIAM, Philadelphia, PA, USA

5 Arguments

1:   N – INTEGERInput
On entry: n, the order of the matrix A.
Constraint: N≥0.
2:   A LDA* – COMPLEX (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array A must be at least N.
On entry: the n by n upper triangular matrix A.
On exit: contains, if IFAIL=0, the n by n principal matrix square root, A 1/2. Alternatively, if IFAIL=1, contains an n by n non-principal square root of A.
3:   LDA – INTEGERInput
On entry: the first dimension of the array A as declared in the (sub)program from which F01FPF is called.
Constraint: LDA≥N.
4:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
A has negative or semisimple, vanishing eigenvalues. The principal square root is not defined in this case; a non-principal square root is returned.
IFAIL=2
A has a defective vanishing eigenvalue. The square root cannot be found in this case.
IFAIL=3
An internal error occurred. It is likely that the routine was called incorrectly.
IFAIL=-1
On entry, N=value.
Constraint: N≥0.
IFAIL=-3
On entry, LDA=value and N=value.
Constraint: LDA≥N.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

The computed square root X^ satisfies X^2=A+ΔA, where ΔA≈O ε n X^2, where ε is machine precision. The order of the change in A is to be interpreted elementwise.

8 Parallelism and Performance

F01FPF is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
F01FPF makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The cost of the algorithm is n 3/3 complex floating-point operations; see Algorithm 6.3 in Higham (2008). O 2×n 2 of complex allocatable memory is required by the routine.
If A is a full matrix, then F01FNF should be used to compute the principal square root.
If condition number and residual bound estimates are required, then F01KDF should be used. For further discussion of the condition of the matrix square root see Section 6.1 of Higham (2008).

10 Example

This example finds the principal matrix square root of the matrix
A = 2 i 14+0 2 i 12+0 3 i 6+0 4 i 0 i+0 -5+12 i 6+18 i 9+16 i 0 i+0 0 i+00 3-0 4 i 16-0 4 i 0 i+0 0 i+00 0 i+00 4 i+00 .

10.1 Program Text

Program Text (f01fpfe.f90)

10.2 Program Data

Program Data (f01fpfe.d)

10.3 Program Results

Program Results (f01fpfe.r)

F01 Chapter Contents
F01 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F01FQF : NAG Library, Mark 26

F01 Chapter Contents
F01 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F01FQF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F01FQF computes an abitrary real power Ap of a complex n by n matrix A.

2 Specification

SUBROUTINE F01FQF ( N, A, LDA, P, IFAIL)
INTEGER | N, LDA, IFAIL
REAL (KIND=nag_wp) | P
COMPLEX (KIND=nag_wp) | A(LDA,*)

3 Description

For a matrix A with no eigenvalues on the closed negative real line, Ap (p∈ℝ) can be defined as
Ap= exp p log A
where log A is the principal logarithm of A (the unique logarithm whose spectrum lies in the strip z:-π<Im z<π).
Ap is computed using the Schur–Padé algorithm described in Higham and Lin (2011) and Higham and Lin (2013).
The real number p is expressed as p=q+r where q∈-1,1 and r∈ℤ. Then Ap=AqAr. The integer power Ar is found using a combination of binary powering and, if necessary, matrix inversion. The fractional power Aq is computed using a Schur decomposition and a Padé approximant.

4 References

Higham N J (2008) Functions of Matrices: Theory and Computation SIAM, Philadelphia, PA, USA
Higham N J and Lin L (2011) A Schur–Padé algorithm for fractional powers of a matrix SIAM J. Matrix Anal. Appl. 32(3) 1056–1078
Higham N J and Lin L (2013) An improved Schur–Padé algorithm for fractional powers of a matrix and their Fréchet derivatives SIAM J. Matrix Anal. Appl. 34(3) 1341–1360

5 Arguments

1:   N – INTEGERInput
On entry: n, the order of the matrix A.
Constraint: N≥0.
2:   A LDA* – COMPLEX (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array A must be at least N.
On entry: the n by n matrix A.
On exit: if IFAIL=0, the n by n matrix pth power, Ap. Alternatively, if IFAIL=1, contains an n by n non-principal power of A.
3:   LDA – INTEGERInput
On entry: the first dimension of the array A as declared in the (sub)program from which F01FQF is called.
Constraint: LDA≥N.
4:   P – REAL (KIND=nag_wp)Input
On entry: the required power of A.
5:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
A has eigenvalues on the negative real line. The principal pth power is not defined so a non-principal power is returned.
IFAIL=2
A is singular so the pth power cannot be computed.
IFAIL=3
Ap has been computed using an IEEE double precision Padé approximant, although the arithmetic precision is higher than IEEE double precision.
IFAIL=4
An unexpected internal error occurred. This failure should not occur and suggests that the routine has been called incorrectly.
IFAIL=-1
On entry, N=value.
Constraint: N≥0.
IFAIL=-3
On entry, LDA=value and N=value.
Constraint: LDA≥N.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

For positive integer p, the algorithm reduces to a sequence of matrix multiplications. For negative integer p, the algorithm consists of a combination of matrix inversion and matrix multiplications.
For a normal matrix A (for which AH A=A AH) and non-integer p, the Schur decomposition is diagonal and the algorithm reduces to evaluating powers of the eigenvalues of A and then constructing Ap using the Schur vectors. This should give a very accurate result. In general however, no error bounds are available for the algorithm.

8 Parallelism and Performance

F01FQF is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
F01FQF makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The cost of the algorithm is O n 3. The exact cost depends on the matrix A but if p∈-1,1 then the cost is independent of p. O 4×n 2 complex allocatable memory is required by the routine.
If estimates of the condition number of Ap are required then F01KEF should be used.

10 Example

This example finds Ap where p=0.2 and
A = 2 i+ 3 i+0 2 i+0 1+3 i 2+i 1 i+0 1 i+0 2+2 i 2+i 2+2 i 2 i 2+4 i 3 i+ 2+2 i 3 i+0 1 i+0 .

10.1 Program Text

Program Text (f01fqfe.f90)

10.2 Program Data

Program Data (f01fqfe.d)

10.3 Program Results

Program Results (f01fqfe.r)

F01 Chapter Contents
F01 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F01GAF : NAG Library, Mark 26

F01 Chapter Contents
F01 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F01GAF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F01GAF computes the action of the matrix exponential e tA, on the matrix B, where A is a real n by n matrix, B is a real n by m matrix and t is a real scalar.

2 Specification

SUBROUTINE F01GAF ( N, M, A, LDA, B, LDB, T, IFAIL)
INTEGER | N, M, LDA, LDB, IFAIL
REAL (KIND=nag_wp) | A(LDA,*), B(LDB,*), T

3 Description

e tA B is computed using the algorithm described in Al–Mohy and Higham (2011) which uses a truncated Taylor series to compute the product e tA B without explicitly forming e tA.

4 References

Al–Mohy A H and Higham N J (2011) Computing the action of the matrix exponential, with an application to exponential integrators SIAM J. Sci. Statist. Comput. 33(2) 488-511
Higham N J (2008) Functions of Matrices: Theory and Computation SIAM, Philadelphia, PA, USA

5 Arguments

1:   N – INTEGERInput
On entry: n, the order of the matrix A.
Constraint: N≥0.
2:   M – INTEGERInput
On entry: m, the number of columns of the matrix B.
Constraint: M≥0.
3:   A LDA* – REAL (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array A must be at least N.
On entry: the n by n matrix A.
On exit: A is overwritten during the computation.
4:   LDA – INTEGERInput
On entry: the first dimension of the array A as declared in the (sub)program from which F01GAF is called.
Constraint: LDA≥N.
5:   B LDB* – REAL (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array B must be at least M.
On entry: the n by m matrix B.
On exit: the n by m matrix e tA B.
6:   LDB – INTEGERInput
On entry: the first dimension of the array B as declared in the (sub)program from which F01GAF is called.
Constraint: LDB≥N.
7:   T – REAL (KIND=nag_wp)Input
On entry: the scalar t.
8:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=2
e tA B has been computed using an IEEE double precision Taylor series, although the arithmetic precision is higher than IEEE double precision.
IFAIL=-1
On entry, N=value.
Constraint: N≥0.
IFAIL=-2
On entry, M=value.
Constraint: M≥0.
IFAIL=-4
On entry, LDA=value and N=value.
Constraint: LDA≥N.
IFAIL=-6
On entry, LDB=value and N=value.
Constraint: LDB≥N.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

For a symmetric matrix A (for which AT=A) the computed matrix e tA B is guaranteed to be close to the exact matrix, that is, the method is forward stable. No such guarantee can be given for non-symmetric matrices. See Section 4 of Al–Mohy and Higham (2011) for details and further discussion.

8 Parallelism and Performance

F01GAF is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
F01GAF makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The matrix e tA B could be computed by explicitly forming e tA using F01ECF and multiplying B by the result. However, experiments show that it is usually both more accurate and quicker to use F01GAF.
The cost of the algorithm is O n 2 m. The precise cost depends on A since a combination of balancing, shifting and scaling is used prior to the Taylor series evaluation.
Approximately n 2+ 2 m+8 n of real allocatable memory is required by F01GAF.
F01HAF can be used to compute e tA B for complex A, B, and t. F01GBF provides an implementation of the algorithm with a reverse communication interface, which returns control to the user when matrix multiplications are required. This should be used if A is large and sparse.

10 Example

This example computes e tA B, where
A = 0.7 -0.2 1.0 0.3 0.3 0.7 1.2 1.0 0.9 0.0 0.2 0.7 2.4 0.1 0.0 0.2 ,
B = 0.1 1.2 1.3 0.2 0.0 1.0 0.4 -0.9
and
t=1.2 .

10.1 Program Text

Program Text (f01gafe.f90)

10.2 Program Data

Program Data (f01gafe.d)

10.3 Program Results

Program Results (f01gafe.r)

F01 Chapter Contents
F01 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F01GBF : NAG Library, Mark 26

F01 Chapter Contents
F01 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F01GBF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
▸▿ 9 Further Comments
9.1 Use of Tr(A)
9.2 When to use F01GBF
9.3 Use in Conjunction with NAG Library Routines
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F01GBF computes the action of the matrix exponential e tA, on the matrix B, where A is a real n by n matrix, B is a real n by m matrix and t is a real scalar. It uses reverse communication for evaluating matrix products, so that the matrix A is not accessed explicitly.

2 Specification

SUBROUTINE F01GBF ( IREVCM, N, M, B, LDB, T, TR, B2, LDB2, X, LDX, Y, LDY, P, R, Z, COMM, ICOMM, IFAIL)
INTEGER | IREVCM, N, M, LDB, LDB2, LDX, LDY, ICOMM(2*N+40), IFAIL
REAL (KIND=nag_wp) | B(LDB,*), T, TR, B2(LDB2,*), X(LDX,*), Y(LDY,*), P(N), R(N), Z(N), COMM(N*M+3*N+12)

3 Description

e tA B is computed using the algorithm described in Al–Mohy and Higham (2011) which uses a truncated Taylor series to compute the e tA B without explicitly forming e tA.
The algorithm does not explicity need to access the elements of A; it only requires the result of matrix multiplications of the form AX or AT Y. A reverse communication interface is used, in which control is returned to the calling program whenever a matrix product is required.

4 References

Al–Mohy A H and Higham N J (2011) Computing the action of the matrix exponential, with an application to exponential integrators SIAM J. Sci. Statist. Comput. 33(2) 488-511
Higham N J (2008) Functions of Matrices: Theory and Computation SIAM, Philadelphia, PA, USA

5 Arguments

Note: this routine uses reverse communication. Its use involves an initial entry, intermediate exits and re-entries, and a final exit, as indicated by the argument IREVCM. Between intermediate exits and re-entries, all arguments other than B2, X, Y, P and R must remain unchanged.
1:   IREVCM – INTEGERInput/Output
On initial entry: must be set to 0.
On intermediate exit: IREVCM=1, 2, 3, 4 or 5. The calling program must:
(a) if IREVCM=1: evaluate B 2=AB, where B 2 is an n by m matrix, and store the result in B2;
if IREVCM=2: evaluate Y=AX, where X and Y are n by 2 matrices, and store the result in Y;
if IREVCM=3: evaluate X=AT Y and store the result in X;
if IREVCM=4: evaluate p=Az and store the result in P;
if IREVCM=5: evaluate r=AT z and store the result in R.
(b) call F01GBF again with all other parameters unchanged.
On final exit: IREVCM=0.
2:   N – INTEGERInput
On entry: n, the order of the matrix A.
Constraint: N≥0.
3:   M – INTEGERInput
On entry: the number of columns of the matrix B.
Constraint: M≥0.
4:   B LDB* – REAL (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array B must be at least M.
On initial entry: the n by m matrix B.
On intermediate exit: if IREVCM=1, contains the n by m matrix B.
On intermediate re-entry: must not be changed.
On final exit: the n by m matrix e tA B.
5:   LDB – INTEGERInput
On entry: the first dimension of the array B as declared in the (sub)program from which F01GBF is called.
Constraint: LDB≥N.
6:   T – REAL (KIND=nag_wp)Input
On entry: the scalar t.
7:   TR – REAL (KIND=nag_wp)Input
On entry: the trace of A. If this is not available then any number can be supplied (0 is a reasonable default); however, in the trivial case, n=1, the result e TRt B is immediately returned in the first row of B. See Section 9.
8:   B2 LDB2* – REAL (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array B2 must be at least M.
On initial entry: need not be set.
On intermediate re-entry: if IREVCM=1, must contain AB.
On final exit: the array is undefined.
9:   LDB2 – INTEGERInput
On initial entry: the first dimension of the array B2 as declared in the (sub)program from which F01GBF is called.
Constraint: LDB2≥N.
10:   X LDX* – REAL (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array X must be at least 2.
On initial entry: need not be set.
On intermediate exit: if IREVCM=2, contains the current n by 2 matrix X.
On intermediate re-entry: if IREVCM=3, must contain AT Y.
On final exit: the array is undefined.
11:   LDX – INTEGERInput
On entry: the first dimension of the array X as declared in the (sub)program from which F01GBF is called.
Constraint: LDX≥N.
12:   Y LDY* – REAL (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array Y must be at least 2.
On initial entry: need not be set.
On intermediate exit: if IREVCM=3, contains the current n by 2 matrix Y.
On intermediate re-entry: if IREVCM=2, must contain AX.
On final exit: the array is undefined.
13:   LDY – INTEGERInput
On entry: the first dimension of the array Y as declared in the (sub)program from which F01GBF is called.
Constraint: LDY≥N.
14:   P N – REAL (KIND=nag_wp) arrayInput/Output
On initial entry: need not be set.
On intermediate re-entry: if IREVCM=4, must contain Az.
On final exit: the array is undefined.
15:   R N – REAL (KIND=nag_wp) arrayInput/Output
On initial entry: need not be set.
On intermediate re-entry: if IREVCM=5, must contain AT z.
On final exit: the array is undefined.
16:   Z N – REAL (KIND=nag_wp) arrayInput/Output
On initial entry: need not be set.
On intermediate exit: if IREVCM=4 or 5, contains the vector z.
On intermediate re-entry: must not be changed.
On final exit: the array is undefined.
17:   COMM N×M+3×N+12 – REAL (KIND=nag_wp) arrayCommunication Array
18:   ICOMM 2×N+40 – INTEGER arrayCommunication Array
19:   IFAIL – INTEGERInput/Output
On initial entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, because for this routine the values of the output arguments may be useful even if IFAIL≠0 on exit, the recommended value is -1. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On final exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=2
e tA B has been computed using an IEEE double precision Taylor series, although the arithmetic precision is higher than IEEE double precision.
IFAIL=-1
On initial entry, IREVCM=value.
Constraint: IREVCM=0.
On intermediate re-entry, IREVCM=value.
Constraint: IREVCM=1, 2, 3, 4 or 5.
IFAIL=-2
On initial entry, N=value.
Constraint: N≥0.
IFAIL=-3
On initial entry, M=value.
Constraint: M≥0.
IFAIL=-5
On initial entry, LDB=value and N=value.
Constraint: LDB≥N.
IFAIL=-9
On initial entry, LDB2=value and N=value.
Constraint: LDB2≥N.
IFAIL=-11
On initial entry, LDX=value and N=value.
Constraint: LDX≥N.
IFAIL=-13
On initial entry, LDY=value and N=value.
Constraint: LDY≥N.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

For a symmetric matrix A (for which AT=A) the computed matrix e tA B is guaranteed to be close to the exact matrix, that is, the method is forward stable. No such guarantee can be given for non-symmetric matrices. See Section 4 of Al–Mohy and Higham (2011) for details and further discussion.

8 Parallelism and Performance

F01GBF is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

9.1 Use of Tr A

The elements of A are not explicitly required by F01GBF. However, the trace of A is used in the preprocessing phase of the algorithm. If Tr A is not available to the calling subroutine then any number can be supplied (0 is recommended). This will not affect the stability of the algorithm, but it may reduce its efficiency.

9.2 When to use F01GBF

F01GBF is designed to be used when A is large and sparse. Whenever a matrix multiplication is required, the routine will return control to the calling program so that the multiplication can be done in the most efficient way possible. Note that e tA B will not, in general, be sparse even if A is sparse.
If A is small and dense then F01GAF can be used to compute e tA B without the use of a reverse communication interface.
The complex analog of F01GBF is F01HBF.

9.3 Use in Conjunction with NAG Library Routines

To compute e tA B, the following skeleton code can normally be used:
revcm: Do
  Call F01GBF(IREVCM,N,M,B,LDB,T,TR,B2,LDB2,X,LDX,Y,LDY,P,R,Z, &
              COMM,ICOMM,IFAIL)
  If (IREVCM == 0) Then
      Exit revcm
  Else If (IREVCM == 1) Then
      .. Code to compute B2=AB ..
  Else If (IREVCM == 2) Then
      .. Code to compute Y=AX ..
  Else If (IREVCM == 3) Then
      .. Code to compute X=A^T Y ..
  Else If (IREVCM == 4) Then
      .. Code to compute P=AZ ..
  Else If (IREVCM == 5) Then
      .. Code to compute R=A^T Z ..
  End If
End Do revcm
The code used to compute the matrix products will vary depending on the way A is stored. If all the elements of A are stored explicitly, then F06YAF (DGEMM)) can be used. If A is triangular then F06YFF (DTRMM) should be used. If A is symmetric, then F06YCF (DSYMM) should be used. For sparse A stored in coordinate storage format F11XAF and F11XEF can be used. Alternatively if A is stored in compressed column format F11MKF can be used.

10 Example

This example computes e tA B, where
A = 0.4 -0.2 1.3 0.6 0.3 0.8 1.0 1.0 3.0 4.8 0.2 0.7 0.5 0.0 -5.0 0.7 ,
B = 0.1 1.1 1.7 -0.2 0.5 1.0 0.4 -0.2 ,
and
t=-0.2 .

10.1 Program Text

Program Text (f01gbfe.f90)

10.2 Program Data

Program Data (f01gbfe.d)

10.3 Program Results

Program Results (f01gbfe.r)

F01 Chapter Contents
F01 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F01HAF : NAG Library, Mark 26

F01 Chapter Contents
F01 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F01HAF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F01HAF computes the action of the matrix exponential e tA, on the matrix B, where A is a complex n by n matrix, B is a complex n by m matrix and t is a complex scalar.

2 Specification

SUBROUTINE F01HAF ( N, M, A, LDA, B, LDB, T, IFAIL)
INTEGER | N, M, LDA, LDB, IFAIL
COMPLEX (KIND=nag_wp) | A(LDA,*), B(LDB,*), T

3 Description

e tA B is computed using the algorithm described in Al–Mohy and Higham (2011) which uses a truncated Taylor series to compute the product e tA B without explicitly forming e tA.

4 References

Al–Mohy A H and Higham N J (2011) Computing the action of the matrix exponential, with an application to exponential integrators SIAM J. Sci. Statist. Comput. 33(2) 488-511
Higham N J (2008) Functions of Matrices: Theory and Computation SIAM, Philadelphia, PA, USA

5 Arguments

1:   N – INTEGERInput
On entry: n, the order of the matrix A.
Constraint: N≥0.
2:   M – INTEGERInput
On entry: m, the number of columns of the matrix B.
Constraint: M≥0.
3:   A LDA* – COMPLEX (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array A must be at least N.
On entry: the n by n matrix A.
On exit: A is overwritten during the computation.
4:   LDA – INTEGERInput
On entry: the first dimension of the array A as declared in the (sub)program from which F01HAF is called.
Constraint: LDA≥N.
5:   B LDB* – COMPLEX (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array B must be at least M.
On entry: the n by m matrix B.
On exit: the n by m matrix e tA B.
6:   LDB – INTEGERInput
On entry: the first dimension of the array B as declared in the (sub)program from which F01HAF is called.
Constraint: LDB≥N.
7:   T – COMPLEX (KIND=nag_wp)Input
On entry: the scalar t.
8:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=2
e tA B has been computed using an IEEE double precision Taylor series, although the arithmetic precision is higher than IEEE double precision.
IFAIL=-1
On entry, N=value.
Constraint: N≥0.
IFAIL=-2
On entry, M=value.
Constraint: M≥0.
IFAIL=-4
On entry, LDA=value and N=value.
Constraint: LDA≥N.
IFAIL=-6
On entry, LDB=value and N=value.
Constraint: LDB≥N.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

For a Hermitian matrix A (for which AH=A) the computed matrix e tA B is guaranteed to be close to the exact matrix, that is, the method is forward stable. No such guarantee can be given for non-Hermitian matrices. See Section 4 of Al–Mohy and Higham (2011) for details and further discussion.

8 Parallelism and Performance

F01HAF is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
F01HAF makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The matrix e tA B could be computed by explicitly forming e tA using F01FCF and multiplying B by the result. However, experiments show that it is usually both more accurate and quicker to use F01HAF.
The cost of the algorithm is O n 2 m. The precise cost depends on A since a combination of balancing, shifting and scaling is used prior to the Taylor series evaluation.
Approximately n 2+ 2 m+8 n of complex allocatable memory is required by F01HAF.
F01GAF can be used to compute e tA B for real A, B, and t. F01HBF provides an implementation of the algorithm with a reverse communication interface, which returns control to the user when matrix multiplications are required. This should be used if A is large and sparse.

10 Example

This example computes e tA B, where
A = 0.5+0.0 i -0.2+0.0 i 1.0+0.1 i 0.0+0.4 i 0.3+0.0 i 0.5+1.2 i 3.1+0.0 i 1.0+0.2 i 0.0+2.0 i 0.1+0.0 i 1.2+0.2 i 0.5+0.0 i 1.0+0.3 i 0.0+0.2 i 0.0+0.9 i 0.5+0.0 i ,
B = 0.4+0.0 i 1.2+0.0 i 1.3+0.0 i -0.2+0.1 i 0.0+0.3 i 2.1+0.0 i 0.4+0.0 i -0.9+0.0 i
and
t=-0.5+0.0 i .

10.1 Program Text

Program Text (f01hafe.f90)

10.2 Program Data

Program Data (f01hafe.d)

10.3 Program Results

Program Results (f01hafe.r)

F01 Chapter Contents
F01 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F01HBF : NAG Library, Mark 26

F01 Chapter Contents
F01 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F01HBF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
▸▿ 9 Further Comments
9.1 Use of Tr(A)
9.2 When to use F01HBF
9.3 Use in Conjunction with NAG Library Routines
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F01HBF computes the action of the matrix exponential e tA, on the matrix B, where A is a complex n by n matrix, B is a complex n by m matrix and t is a complex scalar. It uses reverse communication for evaluating matrix products, so that the matrix A is not accessed explicitly.

2 Specification

SUBROUTINE F01HBF ( IREVCM, N, M, B, LDB, T, TR, B2, LDB2, X, LDX, Y, LDY, P, R, Z, CCOMM, COMM, ICOMM, IFAIL)
INTEGER | IREVCM, N, M, LDB, LDB2, LDX, LDY, ICOMM(2*N+40), IFAIL
REAL (KIND=nag_wp) | COMM(3*N+14)
COMPLEX (KIND=nag_wp) | B(LDB,*), T, TR, B2(LDB2,*), X(LDX,*), Y(LDY,*), P(N), R(N), Z(N), CCOMM(N*(M+2))

3 Description

e tA B is computed using the algorithm described in Al–Mohy and Higham (2011) which uses a truncated Taylor series to compute the e tA B without explicitly forming e tA.
The algorithm does not explicity need to access the elements of A; it only requires the result of matrix multiplications of the form AX or AH Y. A reverse communication interface is used, in which control is returned to the calling program whenever a matrix product is required.

4 References

Al–Mohy A H and Higham N J (2011) Computing the action of the matrix exponential, with an application to exponential integrators SIAM J. Sci. Statist. Comput. 33(2) 488-511
Higham N J (2008) Functions of Matrices: Theory and Computation SIAM, Philadelphia, PA, USA

5 Arguments

Note: this routine uses reverse communication. Its use involves an initial entry, intermediate exits and re-entries, and a final exit, as indicated by the argument IREVCM. Between intermediate exits and re-entries, all arguments other than B2, X, Y, P and R must remain unchanged.
1:   IREVCM – INTEGERInput/Output
On initial entry: must be set to 0.
On intermediate exit: IREVCM=1, 2, 3, 4 or 5. The calling program must:
(a) if IREVCM=1: evaluate B 2=AB, where B 2 is an n by m matrix, and store the result in B2;
if IREVCM=2: evaluate Y=AX, where X and Y are n by 2 matrices, and store the result in Y;
if IREVCM=3: evaluate X=AH Y and store the result in X;
if IREVCM=4: evaluate p=Az and store the result in P;
if IREVCM=5: evaluate r=AH z and store the result in R.
(b) call F01HBF again with all other parameters unchanged.
On final exit: IREVCM=0.
2:   N – INTEGERInput
On entry: n, the order of the matrix A.
Constraint: N≥0.
3:   M – INTEGERInput
On entry: the number of columns of the matrix B.
Constraint: M≥0.
4:   B LDB* – COMPLEX (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array B must be at least M.
On initial entry: the n by m matrix B.
On intermediate exit: if IREVCM=1, contains the n by m matrix B.
On intermediate re-entry: must not be changed.
On final exit: the n by m matrix e tA B.
5:   LDB – INTEGERInput
On entry: the first dimension of the array B as declared in the (sub)program from which F01HBF is called.
Constraint: LDB≥N.
6:   T – COMPLEX (KIND=nag_wp)Input
On entry: the scalar t.
7:   TR – COMPLEX (KIND=nag_wp)Input
On entry: the trace of A. If this is not available then any number can be supplied (0 is a reasonable default); however, in the trivial case, n=1, the result e TRt B is immediately returned in the first row of B. See Section 9.
8:   B2 LDB2* – COMPLEX (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array B2 must be at least M.
On initial entry: need not be set.
On intermediate re-entry: if IREVCM=1, must contain AB.
On final exit: the array is undefined.
9:   LDB2 – INTEGERInput
On initial entry: the first dimension of the array B2 as declared in the (sub)program from which F01HBF is called.
Constraint: LDB2≥N.
10:   X LDX* – COMPLEX (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array X must be at least 2.
On initial entry: need not be set.
On intermediate exit: if IREVCM=2, contains the current n by 2 matrix X.
On intermediate re-entry: if IREVCM=3, must contain AH Y.
On final exit: the array is undefined.
11:   LDX – INTEGERInput
On entry: the first dimension of the array X as declared in the (sub)program from which F01HBF is called.
Constraint: LDX≥N.
12:   Y LDY* – COMPLEX (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array Y must be at least 2.
On initial entry: need not be set.
On intermediate exit: if IREVCM=3, contains the current n by 2 matrix Y.
On intermediate re-entry: if IREVCM=2, must contain AX.
On final exit: the array is undefined.
13:   LDY – INTEGERInput
On entry: the first dimension of the array Y as declared in the (sub)program from which F01HBF is called.
Constraint: LDY≥N.
14:   P N – COMPLEX (KIND=nag_wp) arrayInput/Output
On initial entry: need not be set.
On intermediate re-entry: if IREVCM=4, must contain Az.
On final exit: the array is undefined.
15:   R N – COMPLEX (KIND=nag_wp) arrayInput/Output
On initial entry: need not be set.
On intermediate re-entry: if IREVCM=5, must contain AH z.
On final exit: the array is undefined.
16:   Z N – COMPLEX (KIND=nag_wp) arrayInput/Output
On initial entry: need not be set.
On intermediate exit: if IREVCM=4 or 5, contains the vector z.
On intermediate re-entry: must not be changed.
On final exit: the array is undefined.
17:   CCOMM N×M+2 – COMPLEX (KIND=nag_wp) arrayCommunication Array
18:   COMM 3×N+14 – REAL (KIND=nag_wp) arrayCommunication Array
19:   ICOMM 2×N+40 – INTEGER arrayCommunication Array
20:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=2
e tA B has been computed using an IEEE double precision Taylor series, although the arithmetic precision is higher than IEEE double precision.
IFAIL=-1
On initial entry, IREVCM=value.
Constraint: IREVCM=0.
On intermediate re-entry, IREVCM=value.
Constraint: IREVCM=1, 2, 3, 4 or 5.
IFAIL=-2
On initial entry, N=value.
Constraint: N≥0.
IFAIL=-3
On initial entry, M=value.
Constraint: M≥0.
IFAIL=-5
On initial entry, LDB=value and N=value.
Constraint: LDB≥N.
IFAIL=-9
On initial entry, LDB2=value and N=value.
Constraint: LDB2≥N.
IFAIL=-11
On initial entry, LDX=value and N=value.
Constraint: LDX≥N.
IFAIL=-13
On initial entry, LDY=value and N=value.
Constraint: LDY≥N.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

For an Hermitian matrix A (for which AH=A) the computed matrix e tA B is guaranteed to be close to the exact matrix, that is, the method is forward stable. No such guarantee can be given for non-Hermitian matrices. See Section 4 of Al–Mohy and Higham (2011) for details and further discussion.

8 Parallelism and Performance

F01HBF is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

9.1 Use of Tr A

The elements of A are not explicitly required by F01HBF. However, the trace of A is used in the preprocessing phase of the algorithm. If Tr A is not available to the calling subroutine then any number can be supplied (0 is recommended). This will not affect the stability of the algorithm, but it may reduce its efficiency.

9.2 When to use F01HBF

F01HBF is designed to be used when A is large and sparse. Whenever a matrix multiplication is required, the routine will return control to the calling program so that the multiplication can be done in the most efficient way possible. Note that e tA B will not, in general, be sparse even if A is sparse.
If A is small and dense then F01HAF can be used to compute e tA B without the use of a reverse communication interface.
The real analog of F01HBF is F01GBF.

9.3 Use in Conjunction with NAG Library Routines

To compute e tA B, the following skeleton code can normally be used:
revcm: Do
  Call F01HBF(IREVCM,N,M,B,LDB,T,TR,B2,LDB2,X,LDX,Y,LDX,P,R,Z, &
             CCOMM,COMM,ICOMM,IFAIL)
  If (IREVCM == 0) Then
      Exit revcm
  Else If (IREVCM == 1) Then
      .. Code to compute B2=AB ..
  Else If (IREVCM == 2) Then
      .. Code to compute Y=AX ..
  Else If (IREVCM == 3) Then
      .. Code to compute X=A^H Y ..
  Else If (IREVCM == 4) Then
      .. Code to compute P=AZ ..
  Else If (IREVCM == 5) Then
      .. Code to compute R=A^H Z ..
  End If
End Do revcm
The code used to compute the matrix products will vary depending on the way A is stored. If all the elements of A are stored explicitly, then F06ZAF (ZGEMM) can be used. If A is triangular then F06ZFF (ZTRMM) should be used. If A is Hermitian, then F06ZCF (ZHEMM) should be used. If A is symmetric, then F06ZTF (ZSYMM) should be used. For sparse A stored in coordinate storage format F11XNF and F11XSF can be used. For sparse A stored in compressed column storage format (CCS) the program text of Section 10 contains the routine matmul to perform matrix products.

10 Example

This example computes e tA B where
A = 0.7+0.8 i -0.2+0.0 i 1.0+0.0 i 0.6+0.5 i 0.3+0.7 i 0.7+0.0 i 0.9+3.0 i 1.0+0.8 i 0.3+3.0 i -0.7+0.0 i 0.2+0.6 i 0.7+0.5 i 0.0+0.9 i 4.0+0.0 i 0.0+0.0 i 0.2+0.0 i ,
B = 0.1+0.0 i 1.2+0.1 i 1.3+0.9 i -0.2+2.0 i 4.0+0.6 i -1.0+0.8 i 0.4+0.0 i -0.9+0.0 i
and
t=1.1+0.0 i .
A is stored in compressed column storage format (CCS) and matrix multiplications are performed using the routine matmul.

10.1 Program Text

Program Text (f01hbfe.f90)

10.2 Program Data

Program Data (f01hbfe.d)

10.3 Program Results

Program Results (f01hbfe.r)

F01 Chapter Contents
F01 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F01 Chapter Introduction : NAG Library, Mark 26

F01 Chapter Contents
NAG Library Manual

NAG Library Chapter Introduction

F01 – Matrix Operations, Including Inversion

▸▿ Contents

1 Scope of the Chapter
▸▿ 2 Background to the Problems
2.1 Matrix Inversion
2.2 Matrix Factorizations
2.3 Matrix Arithmetic and Manipulation
2.4 Matrix Functions
▸▿ 3 Recommendations on Choice and Use of Available Routines
3.1 Matrix Inversion
3.2 Matrix Factorizations
▸▿ 3.3 Matrix Arithmetic and Manipulation
3.3.1 NAG Names and LAPACK Names
3.4 Matrix Functions
4 Decision Trees
5 Functionality Index
6 Auxiliary Routines Associated with Library Routine Arguments
7 Routines Withdrawn or Scheduled for Withdrawal
8 References

1 Scope of the Chapter

This chapter provides facilities for four types of problem:
(i) | Matrix Inversion
(ii) | Matrix Factorizations
(iii) | Matrix Arithmetic and Manipulation
(iv) | Matrix Functions
See Sections 2.1, 2.2, 2.3 and 2.4 where these problems are discussed.

2 Background to the Problems

2.1 Matrix Inversion

(i) Nonsingular square matrices of order n.
If A, a square matrix of order n, is nonsingular (has rank n), then its inverse X exists and satisfies the equations AX=XA=I (the identity or unit matrix).
It is worth noting that if AX-I=R, so that R is the ‘residual’ matrix, then a bound on the relative error is given by R, i.e.,
X-A-1 A-1 ≤R.
(ii) General real rectangular matrices.
A real matrix A has no inverse if it is square (n by n) and singular (has rank <n), or if it is of shape (m by n) with m≠n, but there is a Generalized or Pseudo-inverse A+ which satisfies the equations
A A+A=A,  A+A A+=A+,  A A+T=A A+,  A+A T=A+A
(which of course are also satisfied by the inverse X of A if A is square and nonsingular).
(a) if m≥n and rank A=n then A can be factorized using a QR factorization, given by
A=Q R 0 ,
where Q is an m by m orthogonal matrix and R is an n by n, nonsingular, upper triangular matrix. The pseudo-inverse of A is then given by
A+=R-1Q~T,
where Q~ consists of the first n columns of Q.
(b) if m≤n and rank A=m then A can be factorized using an RQ factorization, given by
A=R 0 QT
where Q is an n by n orthogonal matrix and R is an m by m, nonsingular, upper triangular matrix. The pseudo-inverse of A is then given by
A+ = Q~R-1 ,
where Q~ consists of the first m columns of Q.
(c) if m≥n and rank A=r≤n then A can be factorized using a QR factorization, with column interchanges, as
A=Q R 0 PT,
where Q is an m by m orthogonal matrix, R is an r by n upper trapezoidal matrix and P is an n by n permutation matrix. The pseudo-inverse of A is then given by
A+=P RTR RT-1Q~T,
where Q~ consists of the first r columns of Q.
(d) if rank A=r≤k=min m,n, then A can be factorized as the singular value decomposition
A=UΣ VT,
where U is an m by m orthogonal matrix, V is an n by n orthogonal matrix and Σ is an m by n diagonal matrix with non-negative diagonal elements σ. The first k columns of U and V are the left- and right-hand singular vectors of A respectively and the k diagonal elements of Σ are the singular values of A. Σ may be chosen so that
σ 1≥σ 2≥⋯≥σk≥0
and in this case if rank A=r then
σ 1≥σ 2≥⋯≥σr>0,  σ r+1=⋯=σk=0.
If U~ and V~ consist of the first r columns of U and V respectively and Σ~ is an r by r diagonal matrix with diagonal elements σ 1,σ 2,…,σr then A is given by
A=U~Σ~V~T
and the pseudo-inverse of A is given by
A+=V~Σ~-1U~T.
Notice that
AT A=V ΣT Σ VT
which is the classical eigenvalue (spectral) factorization of AT A.
(e) if A is complex then the above relationships are still true if we use ‘unitary’ in place of ‘orthogonal’ and conjugate transpose in place of transpose. For example, the singular value decomposition of A is
A=UΣ VH,
where U and V are unitary, VH the conjugate transpose of V and Σ is as in (d) above.

2.2 Matrix Factorizations

The routines in this section perform matrix factorizations which are required for the solution of systems of linear equations with various special structures. A few routines which perform associated computations are also included.
Other routines for matrix factorizations are to be found in Chapters F07, F08 and F11.
This section also contains a few routines associated with eigenvalue problems (see Chapter F02). (Historical note: this section used to contain many more such routines, but they have now been superseded by routines in Chapter F08.)

2.3 Matrix Arithmetic and Manipulation

The intention of routines in this section (sub-chapters F01C, F01V and F01Z) is to cater for some of the commonly occurring operations in matrix manipulation, i.e., transposing a matrix or adding part of one matrix to another, and for conversion between different storage formats,such as conversion between rectangular band matrix storage and packed band matrix storage. For vector or matrix-vector or matrix-matrix operations refer to Chapters F06 and F16.

2.4 Matrix Functions

Given a square matrix A, the matrix function f A is a matrix with the same dimensions as A which provides a generalization of the scalar function f.
If A has a full set of eigenvectors V then A can be factorized as
A = V D V-1 ,
where D is the diagonal matrix whose diagonal elements, di, are the eigenvalues of A. f A is given by
f A = V f D V-1 ,
where f D is the diagonal matrix whose ith diagonal element is f di.
In general, A may not have a full set of eigenvectors. The matrix function can then be defined via a Cauchy integral. For A∈ℂ n×n,
f A = 1 2 π i ∫ Γ f z zI-A-1 dz ,
where Γ is a closed contour surrounding the eigenvalues of A, and f is analytic within Γ.
Some matrix functions are defined implicitly. A matrix logarithm is a solution X to the equation
eX=A .
In general X is not unique, but if A has no eigenvalues on the closed negative real line then a unique principal logarithm exists whose eigenvalues have imaginary part between π and -π. Similarly, a matrix square root is a solution X to the equation
X 2=A .
If A has no eigenvalues on the closed negative real line then a unique principal square root exists with eigenvalues in the right half-plane. If A has a vanishing eigenvalue then log A cannot be computed. If the vanishing eigenvalue is defective (its algebraic multiplicity exceeds its geometric multiplicity, or equivalently it occurs in a Jordan block of size greater than 1) then the square root cannot be computed. If the vanishing eigenvalue is semisimple (its algebraic and geometric multiplicities are equal, or equivalently it occurs only in Jordan blocks of size 1) then a square root can be computed.
Algorithms for computing matrix functions are usually tailored to a specific function. Currently Chapter F01 contains routines for calculating the exponential, logarithm, sine, cosine, sinh, cosh, square root and general real power of both real and complex matrices. In addition there are routines to compute a general function of real symmetric and complex Hermitian matrices and a general function of general real and complex matrices.
The Fréchet derivative of a matrix function f A in the direction of the matrix E is the linear function mapping E to Lf A,E such that
f A+E - f A - Lf A,E = O E .
The Fréchet derivative measures the first-order effect on f A of perturbations in A. Chapter F01 contains routines for calculating the Fréchet derivative of the exponential, logarithm and real powers of both real and complex matrices.
The condition number of a matrix function is a measure of its sensitivity to perturbations in the data. The absolute condition number measures these perturbations in an absolute sense, and is defined by
condabs f,A ≔ lim ε→0 sup E→0 f A+E - f A ε .
The relative condition number, which is usually of more interest, measures these perturbations in a relative sense, and is defined by
condrel f,A = condabs f,A A f A .
The absolute and relative condition numbers can be expressed in terms of the norm of the Fréchet derivative by
condabs f,A = max E≠0 L A,E E ,
condrel f,A = A f A max E≠0 L A,E E .
Chapter F01 contains routines for calculating the condition number of the matrix exponential, logarithm, sine, cosine, sinh, cosh, square root and general real power of both real and complex matrices. It also contains routines for estimating the condition number of a general function of a real or complex matrix.

3 Recommendations on Choice and Use of Available Routines

3.1 Matrix Inversion

Note: before using any routine for matrix inversion, consider carefully whether it is really needed.
Although the solution of a set of linear equations Ax=b can be written as x=A-1 b, the solution should never be computed by first inverting A and then computing A-1 b; the routines in Chapters F04 or F07 should always be used to solve such sets of equations directly; they are faster in execution, and numerically more stable and accurate. Similar remarks apply to the solution of least squares problems which again should be solved by using the routines in Chapters F04 and F08 rather than by computing a pseudo-inverse.
(a) Nonsingular square matrices of order n
This chapter describes techniques for inverting a general real matrix A and matrices which are positive definite (have all eigenvalues positive) and are either real and symmetric or complex and Hermitian. It is wasteful and uneconomical not to use the appropriate routine when a matrix is known to have one of these special forms. A general routine must be used when the matrix is not known to be positive definite. In most routines the inverse is computed by solving the linear equations A xi=ei, for i=1,2,…,n, where ei is the ith column of the identity matrix.
Routines are given for calculating the approximate inverse, that is solving the linear equations just once, and also for obtaining the accurate inverse by successive iterative corrections of this first approximation. The latter, of course, are more costly in terms of time and storage, since each correction involves the solution of n sets of linear equations and since the original A and its LU decomposition must be stored together with the first and successively corrected approximations to the inverse. In practice the storage requirements for the ‘corrected’ inverse routines are about double those of the ‘approximate’ inverse routines, though the extra computer time is not prohibitive since the same matrix and the same LU decomposition is used in every linear equation solution.
Despite the extra work of the ‘corrected’ inverse routines they are superior to the ‘approximate’ inverse routines. A correction provides a means of estimating the number of accurate figures in the inverse or the number of ‘meaningful’ figures relating to the degree of uncertainty in the coefficients of the matrix.
The residual matrix R=AX-I, where X is a computed inverse of A, conveys useful information. Firstly R is a bound on the relative error in X and secondly R<12 guarantees the convergence of the iterative process in the ‘corrected’ inverse routines.
The decision trees for inversion show which routines in Chapter F04 and Chapter F07 should be used for the inversion of other special types of matrices not treated in the chapter.
(b) General real rectangular matrices
For real matrices F08AEF (DGEQRF) and F01QJF return QR and RQ factorizations of A respectively and F08BFF (DGEQP3) returns the QR factorization with column interchanges. The corresponding complex routines are F08ASF (ZGEQRF), F01RJF and F08BTF (ZGEQP3) respectively. Routines are also provided to form the orthogonal matrices and transform by the orthogonal matrices following the use of the above routines. F01QGF and F01RGF form the RQ factorization of an upper trapezoidal matrix for the real and complex cases respectively.
F01BLF uses the QR factorization as described in Section 2.1(ii)(a) and is the only routine that explicitly returns a pseudo-inverse. If m≥n, then the routine will calculate the pseudo-inverse A+ of the matrix A. If m<n, then the n by m matrix AT should be used. The routine will calculate the pseudo-inverse Z=AT+=A+T of AT and the required pseudo-inverse will be ZT. The routine also attempts to calculate the rank, r, of the matrix given a tolerance to decide when elements can be regarded as zero. However, should this routine fail due to an incorrect determination of the rank, the singular value decomposition method (described below) should be used.
F08KBF (DGESVD) and F08KPF (ZGESVD) compute the singular value decomposition as described in Section 2 for real and complex matrices respectively. If A has rank r≤k=min m,n then the k-r smallest singular values will be negligible and the pseudo-inverse of A can be obtained as A+=V Σ-1UT as described in Section 2. If the rank of A is not known in advance it can be estimated from the singular values (see Section 2.4 in the F04 Chapter Introduction). In the real case with m≥n, F08AEF (DGEQRF) followed by F02WUF provide details of the QR factorization or the singular value decomposition depending on whether or not A is of full rank and for some problems provides an attractive alternative to F08KBF (DGESVD). For large sparse matrices, leading terms in the singular value decomposition can be computed using routines from Chapter F12.

3.2 Matrix Factorizations

Each of these routines serves a special purpose required for the solution of sets of simultaneous linear equations or the eigenvalue problem. For further details you should consult Sections 3 or 4 in the F02 Chapter Introduction or Sections 3 or 4 in the F04 Chapter Introduction.
F01BRF and F01BSF are provided for factorizing general real sparse matrices. A more recent algorithm for the same problem is available through F11MEF. For factorizing real symmetric positive definite sparse matrices, see F11JAF. These routines should be used only when A is not banded and when the total number of nonzero elements is less than 10% of the total number of elements. In all other cases either the band routines or the general routines should be used.

3.3 Matrix Arithmetic and Manipulation

The routines in the F01C section are designed for the general handling of m by n matrices. Emphasis has been placed on flexibility in the argument specifications and on avoiding, where possible, the use of internally declared arrays. They are therefore suited for use with large matrices of variable row and column dimensions. Routines are included for the addition and subtraction of sub-matrices of larger matrices, as well as the standard manipulations of full matrices. Those routines involving matrix multiplication may use additional-precision arithmetic for the accumulation of inner products. See also Chapter F06.
The routines in the F01V (LAPACK) and F01Z section are designed to allow conversion between full storage format and one of the packed storage schemes required by some of the routines in Chapters F02, F04, F06, F07 and F08.

3.3.1 NAG Names and LAPACK Names

Routines with NAG name beginning F01V may be called either by their NAG names or by their LAPACK names. When using the NAG Library, the double precision form of the LAPACK name must be used (beginning with D- or Z-).
References to Chapter F01 routines in the manual normally include the LAPACK double precision names, for example, F01VEF (DTRTTF).
The LAPACK routine names follow a simple scheme (which is similar to that used for the BLAS in Chapter F06). Most names have the structure XYYTZZ, where the components have the following meanings:
– the initial letter, X, indicates the data type (real or complex) and precision:
  • S – real, single precision (in Fortran, 4 byte length REAL)
  • D – real, double precision (in Fortran, 8 byte length REAL)
  • C – complex, single precision (in Fortran, 8 byte length COMPLEX)
  • Z – complex, double precision (in Fortran, 16 byte length COMPLEX)
– the fourth letter, T, indicates that the routine is performing a storage scheme transformation (conversion)
– the letters YY indicate the original storage scheme used to store a triangular part of the matrix A, while the letters ZZ indicate the target storage scheme of the conversion (YY cannot equal ZZ since this would do nothing):
  • TF – Rectangular Full Packed Format (RFP)
  • TP – Packed Format
  • TR – Full Format

3.4 Matrix Functions

F01ECF and F01FCF compute the matrix exponential, eA, of a real and complex square matrix A respectively. If estimates of the condition number of the matrix exponential are required then F01JGF and F01KGF should be used. If Fréchet derivatives are required then F01JHF and F01KHF should be used.
F01EDF and F01FDF compute the matrix exponential, eA, of a real symmetric and complex Hermitian matrix respectively. If the matrix is real symmetric, or complex Hermitian then it is recommended that F01EDF, or F01FDF be used as they are more efficient and, in general, more accurate than F01ECF and F01FCF.
F01EJF and F01FJF compute the principal matrix logarithm, log A, of a real and complex square matrix A respectively. If estimates of the condition number of the matrix logarithm are required then F01JJF and F01KJF should be used. If Fréchet derivatives are required then F01JKF and F01KKF should be used.
F01EKF and F01FKF compute the matrix exponential, sine, cosine, sinh or cosh of a real and complex square matrix A respectively. If the matrix exponential is required then it is recommended that F01ECF or F01FCF be used as they are, in general, more accurate than F01EKF and F01FKF. If estimates of the condition number of the matrix function are required then F01JAF and F01KAF should be used.
F01ELF and F01EMF compute the matrix function, f A, of a real square matrix. F01FLF and F01FMF compute the matrix function of a complex square matrix. The derivatives of f are required for these computations. F01ELF and F01FLF use numerical differentiation to obtain the derivatives of f. F01EMF and F01FMF use derivatives you have supplied. If estimates of the condition number are required but you are not supplying derivatives then F01JBF and F01KBF should be used. If estimates of the condition number of the matrix function are required and you are supplying derivatives of f, then F01JCF and F01KCF should be used.
If the matrix A is real symmetric or complex Hermitian then it is recommended that to compute the matrix function, f A, F01EFF and F01FFF are used respectively as they are more efficient and, in general, more accurate than F01ELF, F01EMF, F01FLF and F01FMF.
F01GAF and F01HAF compute the matrix function e tA B for explicitly stored dense real and complex matrices A and B respectively while F01GBF and F01HBF compute the same using reverse communication. In the latter case, control is returned to you. You should calculate any required matrix-matrix products and then call the routine again. See Section 3.3.3 in How to Use the NAG Library and its Documentation for further information.
F01ENF and F01FNF compute the principal square root A 1/2 of a real and complex square matrix A respectively. If A is complex and upper triangular then F01FPF should be used. If A is real and upper quasi-triangular then F01EPF should be used. If estimates of the condition number of the matrix square root are required then F01JDF and F01KDF should be used.
F01EQF and F01FQF compute the matrix power Ap, where p∈ℝ, of real and complex matrices respectively. If estimates of the condition number of the matrix power are required then F01JEF and F01KEF should be used. If Fréchet derivatives are required then F01JFF and F01KFF should be used.

4 Decision Trees

The decision trees show the routines in this chapter and in Chapter F04, Chapter F07 and Chapter F08 that should be used for inverting matrices of various types. They also show which routine should be used to calculate various matrix functions.
(i) Matrix Inversion:

Tree 1

Is A an n by n matrix of rank n? |  |  | Is A a real matrix? |  |  | see Tree 2
 |  | yes |  |  | yes
 | no |  |  | no |
 |  |  | see Tree 3
see Tree 4

Tree 2: Inverse of a real n by n matrix of full rank

Is A a band matrix? |  |  | See Note 1.
 |  | yes
 | no |
Is A symmetric? |  |  | Is A positive definite? |  |  | Do you want guaranteed accuracy? (See Note 2) |  |  | F01ABF
 |  | yes |  |  | yes |  |  | yes
 | no |  |  | no |  |  | no |
 |  |  |  |  |  | Is one triangle of A stored as a linear array? |  |  | F07GDF and F07GJF
 |  |  |  |  |  |  |  | yes
 |  |  |  |  |  |  | no |
 |  |  |  |  |  | F01ADF or F07FDF and F07FJF
 |  |  | Is one triangle of A stored as a linear array? |  |  | F07PDF and F07PJF
 |  |  |  |  | yes
 |  |  |  | no |
 |  |  | F07MDF and F07MJF
Is A triangular? |  |  | Is A stored as a linear array? |  |  | F07UJF
 |  | yes |  |  | yes
 | no |  |  | no |
 |  |  | F07TJF
Do you want guaranteed accuracy? (See Note 2) |  |  | F07ABF
 |  | yes
 | no |
F07ADF and F07AJF

Tree 3: Inverse of a complex n by n matrix of full rank

Is A a band matrix? |  |  | See Note 1.
 |  | yes
 | no |
Is A Hermitian? |  |  | Is A positive definite? |  |  | Is one triangle of A stored as a linear array? |  |  | F07GRF and F07GWF
 |  | yes |  |  | yes |  |  | yes
 | no |  |  | no |  |  | no |
 |  |  |  |  |  | F07FRF and F07FWF
 |  |  | Is one triangle A stored as a linear array? |  |  | F07PRF and F07PWF
 |  |  |  |  | yes
 |  |  |  | no |
 |  |  | F07MRF and F07MWF
Is A symmetric? |  |  | Is one triangle of A stored as a linear array? |  |  | F07QRF and F07QWF
 |  | yes |  |  | yes
 | no |  |  | no |
 |  |  | F07NRF and F07NWF
Is A triangular? |  |  | Is A stored as a linear array? |  |  | F07UWF
 |  | yes |  |  | yes
 | no |  |  | no |
 |  |  | F07TWF
F07ANF or F07ARF and F07AWF

Tree 4: Pseudo-inverses

Is A a complex matrix? |  |  | Is A of full rank? |  |  | Is A an m by n matrix with m<n? |  |  | F01RJF and F01RKF
 |  | yes |  |  | yes |  |  | yes
 | no |  |  | no |  |  | no |
 |  |  |  |  |  | F08ASF and F08AUF or F08ATF
 |  |  | F08KPF
Is A of full rank? |  |  | Is A an m by n matrix with m<n? |  |  | F01QJF and F01QKF
 |  | yes |  |  | yes
 | no |  |  | no |
 |  |  | F08AEF and F08AGF or F08AFF
Is A an m by n matrix with m<n? |  |  | F08KBF
 |  | yes
 | no |
Is reliability more important than efficiency? |  |  | F08KBF
 |  | yes
 | no |
F01BLF
Note 1: the inverse of a band matrix A does not in general have the same shape as A, and no routines are provided specifically for finding such an inverse. The matrix must either be treated as a full matrix, or the equations AX=B must be solved, where B has been initialized to the identity matrix I. In the latter case, see the decision trees in Section 4 in the F04 Chapter Introduction.
Note 2: by ‘guaranteed accuracy’ we mean that the accuracy of the inverse is improved by use of the iterative refinement technique using additional precision.
(ii) Matrix Factorizations: see the decision trees in Section 4 in the F02 and F04 Chapter Introductions.
(iii) Matrix Arithmetic and Manipulation: not appropriate.
(iv) Matrix Functions:

Tree 5: Matrix functions f A of an n by n real matrix A

Is e tA B required? |  |  | Is A stored in dense format? |  |  | F01GAF
 |  | yes |  |  | yes
 | no |  |  | no |
 |  |  | F01GBF
Is A real symmetric? |  |  | Is eA required? |  |  | F01EDF
 |  | yes |  |  | yes
 | no |  |  | no |
 |  |  | F01EFF
Is cos A or cosh A or sin A or sinh A required? |  |  | Is the condition number of the matrix function required? |  |  | F01JAF
 |  | yes |  |  | yes
 | no |  |  | no |
 |  |  | F01EKF
Is log A required? |  |  | Is the condition number of the matrix logarithm required? |  |  | F01JJF
 |  | yes |  |  | yes
 | no |  |  | no |
 |  |  | Is the Fréchet derivative of the matrix logarithm required? |  |  | F01JKF
 |  |  |  |  | yes
 |  |  |  | no |
 |  |  | F01EJF
Is exp A required? |  |  | Is the condition number of the matrix exponential required? |  |  | F01JGF
 |  | yes |  |  | yes
 | no |  |  | no |
 |  |  | Is the Fréchet derivative of the matrix exponential required? |  |  | F01JHF
 |  |  |  |  | yes
 |  |  |  | no |
 |  |  | F01ECF
Is A 1/2 required? |  |  | Is the condition number of the matrix square root required? |  |  | F01JDF
 |  | yes |  |  | yes
 | no |  |  | no |
 |  |  | Is the matrix upper quasi-triangular? |  |  | F01EPF
 |  |  |  |  | yes
 |  |  |  | no |
 |  |  | F01ENF
Is Ap required? |  |  | Is the condition number of the matrix power required? |  |  | F01JEF
 |  | yes |  |  | yes
 | no |  |  | no |
 |  |  | Is the Fréchet derivative of the matrix power required? |  |  | F01JFF
 |  |  |  |  | yes
 |  |  |  | no |
 |  |  | F01EQF
f A will be computed. Will derivatives of f be supplied by the user? |  |  | Is the condition number of the matrix function required? |  |  | F01JCF
 |  | yes |  |  | yes
 | no |  |  | no |
 |  |  | F01EMF
Is the condition number of the matrix function required? |  |  | F01JBF
 |  | yes
 | no |
F01ELF

Tree 6: Matrix functions f A of an n by n complex matrix A

Is e tA B required? |  |  | Is A stored in dense format? |  |  | F01HAF
 |  | yes |  |  | yes
 | no |  |  | no |
 |  |  | F01HBF
Is A complex Hermitian? |  |  | Is eA required? |  |  | F01FDF
 |  | yes |  |  | yes
 | no |  |  | no |
 |  |  | F01FFF
Is cos A or cosh A or sin A or sinh A required? |  |  | Is the condition number of the matrix function required? |  |  | F01KAF
 |  | yes |  |  | yes
 | no |  |  | no |
 |  |  | F01FKF
Is log A required? |  |  | Is the condition number of the matrix logarithm required? |  |  | F01KJF
 |  | yes |  |  | yes
 | no |  |  | no |
 |  |  | Is the Fréchet derivative of the matrix logarithm required? |  |  | F01KKF
 |  |  |  |  | yes
 |  |  |  | no |
 |  |  | F01FJF
Is exp A required? |  |  | Is the condition number of the matrix exponential required? |  |  | F01KGF
 |  | yes |  |  | yes
 | no |  |  | no |
 |  |  | Is the Fréchet derivative of the matrix exponential required? |  |  | F01KHF
 |  |  |  |  | yes
 |  |  |  | no |
 |  |  | F01FCF
Is A 1/2 required? |  |  | Is the condition number of the matrix square root required? |  |  | F01KDF
 |  | yes |  |  | yes
 | no |  |  | no |
 |  |  | Is the matrix upper triangular? |  |  | F01FPF
 |  |  |  |  | yes
 |  |  |  | no |
 |  |  | F01FNF
Is Ap required? |  |  | Is the condition number of the matrix power required? |  |  | F01KEF
 |  | yes |  |  | yes
 | no |  |  | no |
 |  |  | Is the Fréchet derivative of the matrix power required? |  |  | F01KFF
 |  |  |  |  | yes
 |  |  |  | no |
 |  |  | F01FQF
f A will be computed. Will derivatives of f be supplied by the user? |  |  | Is the condition number of the matrix function required? |  |  | F01KCF
 |  | yes |  |  | yes
 | no |  |  | no |
 |  |  | F01FMF
Is the condition number of the matrix function required? |  |  | F01KBF
 |  | yes
 | no |
F01FLF

5 Functionality Index

Action of the matrix exponential on a complex matrix F01HAF
Action of the matrix exponential on a complex matrix (reverse communication) F01HBF
Action of the matrix exponential on a real matrix F01GAF
Action of the matrix exponential on a real matrix (reverse communication) F01GBF
Inversion (also see Chapter F07),
real m by n matrix,
pseudo-inverse F01BLF
real symmetric positive definite matrix,
accurate inverse F01ABF
approximate inverse F01ADF
Matrix Arithmetic and Manipulation,
matrix addition,
complex matrices F01CWF
real matrices F01CTF
matrix multiplication F01CKF
matrix storage conversion,
full to packed triangular storage,
complex matrices F01VBF (ZTRTTP)
real matrices F01VAF (DTRTTP)
full to Rectangular Full Packed storage,
complex matrix F01VFF (ZTRTTF)
real matrix F01VEF (DTRTTF)
packed band ↔ rectangular storage, special provision for diagonal
complex matrices F01ZDF
real matrices F01ZCF
packed triangular to full storage,
complex matrices F01VDF (ZTPTTR)
real matrices F01VCF (DTPTTR)
packed triangular to Rectangular Full Packed storage,
complex matrices F01VKF (ZTPTTF)
real matrices F01VJF (DTPTTF)
packed triangular ↔ square storage, special provision for diagonal
complex matrices F01ZBF
real matrices F01ZAF
Rectangular Full Packed to full storage,
complex matrices F01VHF (ZTFTTR)
real matrices F01VGF (DTFTTR)
Rectangular Full Packed to packed triangular storage,
complex matrices F01VMF (ZTFTTP)
real matrices F01VLF (DTFTTP)
matrix subtraction,
complex matrices F01CWF
real matrices F01CTF
matrix transpose F01CRF
Matrix function,
complex Hermitian n by n matrix,
matrix exponential F01FDF
matrix function F01FFF
complex n by n matrix,
condition number for a matrix exponential F01KGF
condition number for a matrix exponential, logarithm, sine, cosine, sinh or cosh F01KAF
condition number for a matrix function, using numerical differentiation F01KBF
condition number for a matrix function, using user-supplied derivatives F01KCF
condition number for a matrix logarithm F01KJF
condition number for a matrix power F01KEF
condition number for the matrix square root, logarithm, sine, cosine, sinh or cosh F01KDF
Fréchet derivative
matrix exponential F01KHF
matrix logarithm F01KKF
matrix power F01KFF
general power
matrix F01FQF
matrix exponential F01FCF
matrix exponential, sine, cosine, sinh or cosh F01FKF
matrix function, using numerical differentiation F01FLF
matrix function, using user-supplied derivatives F01FMF
matrix logarithm F01FJF
matrix square root F01FNF
upper triangular
matrix square root F01FPF
real n by n matrix,
condition number for a matrix exponential F01JGF
condition number for a matrix function, using numerical differentiation F01JBF
condition number for a matrix function, using user-supplied derivatives F01JCF
condition number for a matrix logarithm F01JJF
condition number for a matrix power F01JEF
condition number for the matrix exponential, logarithm, sine, cosine, sinh or cosh F01JAF
condition number for the matrix square root, logarithm, sine, cosine, sinh or cosh F01JDF
Fréchet derivative
matrix exponential F01JHF
matrix logarithm F01JKF
matrix power F01JFF
general power
matrix exponential F01EQF
matrix exponential F01ECF
matrix exponential, sine, cosine, sinh or cosh F01EKF
matrix function, using numerical differentiation F01ELF
matrix function, using user-supplied derivatives F01EMF
matrix logarithm F01EJF
matrix square root F01ENF
upper quasi-triangular
matrix square root F01EPF
real symmetric n by n matrix,
matrix exponential F01EDF
matrix function F01EFF
Matrix Transformations,
complex matrix, form unitary matrix F01RKF
complex m by n(m ≤ n) matrix,
RQ factorization F01RJF
complex upper trapezoidal matrix,
RQ factorization F01RGF
eigenproblem Ax = λBx, A, B banded,
reduction to standard symmetric problem F01BVF
real almost block-diagonal matrix,
LU factorization F01LHF
real band symmetric positive definite matrix,
ULD LTUT factorization F01BUF
variable bandwidth, LD LT factorization F01MCF
real matrix,
form orthogonal matrix F01QKF
real m by n(m ≤ n) matrix,
RQ factorization F01QJF
real sparse matrix,
factorization F01BRF
factorization, known sparsity pattern F01BSF
real upper trapezoidal matrix,
RQ factorization F01QGF
tridiagonal matrix,
LU factorization F01LEF

6 Auxiliary Routines Associated with Library Routine Arguments

None.

7 Routines Withdrawn or Scheduled for Withdrawal

The following lists all those routines that have been withdrawn since Mark 19 of the Library or are scheduled for withdrawal at one of the next two marks.
Withdrawn Routine | Mark of Withdrawal | Replacement Routine(s)
F01MAF | 19 | F11JAF

8 References

Golub G H and Van Loan C F (1996) Matrix Computations (3rd Edition) Johns Hopkins University Press, Baltimore
Higham N J (2008) Functions of Matrices: Theory and Computation SIAM, Philadelphia, PA, USA
Wilkinson J H (1965) The Algebraic Eigenvalue Problem Oxford University Press, Oxford
Wilkinson J H (1977) Some recent advances in numerical linear algebra The State of the Art in Numerical Analysis (ed D A H Jacobs) Academic Press
Wilkinson J H and Reinsch C (1971) Handbook for Automatic Computation II, Linear Algebra Springer–Verlag
F01 Chapter Contents
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F01JAF : NAG Library, Mark 26

F01 Chapter Contents
F01 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F01JAF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F01JAF computes an estimate of the absolute condition number of a matrix function f at a real n by n matrix A in the 1-norm, where f is either the exponential, logarithm, sine, cosine, hyperbolic sine (sinh) or hyperbolic cosine (cosh). The evaluation of the matrix function, f A, is also returned.

2 Specification

SUBROUTINE F01JAF ( FUN, N, A, LDA, CONDA, NORMA, NORMFA, IFAIL)
INTEGER | N, LDA, IFAIL
REAL (KIND=nag_wp) | A(LDA,*), CONDA, NORMA, NORMFA
CHARACTER(*) | FUN

3 Description

The absolute condition number of f at A, condabs f,A is given by the norm of the Fréchet derivative of f, L A, which is defined by
L X := max E≠0 L X,E E ,
where L X,E is the Fréchet derivative in the direction E. L X,E is linear in E and can therefore be written as
vec L X,E = K X vec E ,
where the vec operator stacks the columns of a matrix into one vector, so that K X is n 2×n 2. F01JAF computes an estimate γ such that γ ≤ K X 1 , where K X 1 ∈ n-1 L X 1 , n L X 1 . The relative condition number can then be computed via
cond rel f,A = cond abs f,A A 1 f A 1 .
The algorithm used to find γ is detailed in Section 3.4 of Higham (2008).

4 References

Higham N J (2008) Functions of Matrices: Theory and Computation SIAM, Philadelphia, PA, USA

5 Arguments

1:   FUN – CHARACTER(*)Input
On entry: indicates which matrix function will be used.
FUN='EXP'
The matrix exponential, eA, will be used.
FUN='SIN'
The matrix sine, sin A, will be used.
FUN='COS'
The matrix cosine, cos A, will be used.
FUN='SINH'
The hyperbolic matrix sine, sinh A, will be used.
FUN='COSH'
The hyperbolic matrix cosine, cosh A, will be used.
FUN='LOG'
The matrix logarithm, log A, will be used.
Constraint: FUN='EXP', 'SIN', 'COS', 'SINH', 'COSH' or 'LOG'.
2:   N – INTEGERInput
On entry: n, the order of the matrix A.
Constraint: N≥0.
3:   A LDA* – REAL (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array A must be at least N.
On entry: the n by n matrix A.
On exit: the n by n matrix, f A.
4:   LDA – INTEGERInput
On entry: the first dimension of the array A as declared in the (sub)program from which F01JAF is called.
Constraint: LDA≥N.
5:   CONDA – REAL (KIND=nag_wp)Output
On exit: an estimate of the absolute condition number of f at A.
6:   NORMA – REAL (KIND=nag_wp)Output
On exit: the 1-norm of A.
7:   NORMFA – REAL (KIND=nag_wp)Output
On exit: the 1-norm of f A.
8:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
An internal error occurred when evaluating the matrix function f A. Please contact NAG.
IFAIL=2
An internal error occurred when estimating the norm of the Fréchet derivative of f at A. Please contact NAG.
IFAIL=-1
On entry, FUN=value was an illegal value.
IFAIL=-2
On entry, N<0.
Input argument number value is invalid.
IFAIL=-4
On entry, argument LDA is invalid.
Constraint: LDA≥N.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

F01JAF uses the norm estimation routine F04YDF to estimate a quantity γ, where γ ≤ K X 1 and K X 1 ∈ n-1 L X 1 , n L X 1 . For further details on the accuracy of norm estimation, see the documentation for F04YDF.

8 Parallelism and Performance

F01JAF is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library. In these implementations, this routine may make calls to the user-supplied functions from within an OpenMP parallel region. Thus OpenMP directives within the user functions can only be used if you are compiling the user-supplied function and linking the executable in accordance with the instructions in the Users' Note for your implementation.
F01JAF makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The matrix function is computed using one of three underlying matrix function routines:
  • if FUN='EXP', F01ECF is used;
  • if FUN='LOG', F01EJF is used;
  • else, F01EKF is used.
Approximately 6 n 2 of real allocatable memory is required by the routine, in addition to the memory used by these underlying matrix function routines.
If only f A is required, without an estimate of the condition number, then it is far more efficient to use the appropriate matrix function routine listed above.
F01KAF can be used to find the condition number of the exponential, logarithm, sine, cosine, sinh or cosh matrix functions at a complex matrix.

10 Example

This example estimates the absolute and relative condition numbers of the matrix sinh function where
A = 2 1 3 1 3 -1 0 2 1 0 3 1 1 2 0 3 .

10.1 Program Text

Program Text (f01jafe.f90)

10.2 Program Data

Program Data (f01jafe.d)

10.3 Program Results

Program Results (f01jafe.r)

F01 Chapter Contents
F01 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F01JBF : NAG Library, Mark 26

F01 Chapter Contents
F01 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F01JBF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F01JBF computes an estimate of the absolute condition number of a matrix function f at a real n by n matrix A in the 1-norm. Numerical differentiation is used to evaluate the derivatives of f when they are required.

2 Specification

SUBROUTINE F01JBF ( N, A, LDA, F, IUSER, RUSER, IFLAG, CONDA, NORMA, NORMFA, IFAIL)
INTEGER | N, LDA, IUSER(*), IFLAG, IFAIL
REAL (KIND=nag_wp) | A(LDA,*), RUSER(*), CONDA, NORMA, NORMFA
EXTERNAL | F

3 Description

The absolute condition number of f at A, condabs f,A is given by the norm of the Fréchet derivative of f, L A, which is defined by
L X := max E≠0 L X,E E ,
where L X,E is the Fréchet derivative in the direction E. L X,E is linear in E and can therefore be written as
vec L X,E = K X vec E ,
where the vec operator stacks the columns of a matrix into one vector, so that K X is n 2×n 2. F01JBF computes an estimate γ such that γ ≤ K X 1 , where K X 1 ∈ n-1 L X 1 , n L X 1 . The relative condition number can then be computed via
cond rel f,A = cond abs f,A A 1 f A 1 .
The algorithm used to find γ is detailed in Section 3.4 of Higham (2008).
The function f is supplied via subroutine F which evaluates f zi at a number of points zi.

4 References

Higham N J (2008) Functions of Matrices: Theory and Computation SIAM, Philadelphia, PA, USA

5 Arguments

1:   N – INTEGERInput
On entry: n, the order of the matrix A.
Constraint: N≥0.
2:   A LDA* – REAL (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array A must be at least N.
On entry: the n by n matrix A.
On exit: the n by n matrix, f A.
3:   LDA – INTEGERInput
On entry: the first dimension of the array A as declared in the (sub)program from which F01JBF is called.
Constraint: LDA≥N.
4:   F – SUBROUTINE, supplied by the user.External Procedure
The subroutine F evaluates f zi at a number of points zi.
The specification of F is:
SUBROUTINE F ( IFLAG, NZ, Z, FZ, IUSER, RUSER)
INTEGER | IFLAG, NZ, IUSER(*)
REAL (KIND=nag_wp) | RUSER(*)
COMPLEX (KIND=nag_wp) | Z(NZ), FZ(NZ)
1:   IFLAG – INTEGERInput/Output
On entry: IFLAG will be zero.
On exit: IFLAG should either be unchanged from its entry value of zero, or may be set nonzero to indicate that there is a problem in evaluating the function f z; for instance f z may not be defined. If IFLAG is returned as nonzero then F01JBF will terminate the computation, with IFAIL=3.
2:   NZ – INTEGERInput
On entry: nz, the number of function values required.
3:   Z NZ – COMPLEX (KIND=nag_wp) arrayInput
On entry: the nz points z 1,z 2,…,z nz at which the function f is to be evaluated.
4:   FZ NZ – COMPLEX (KIND=nag_wp) arrayOutput
On exit: the nz function values. FZ i should return the value f zi, for i=1,2,…,nz. If zi lies on the real line, then so must f zi.
5:   IUSER* – INTEGER arrayUser Workspace
6:   RUSER* – REAL (KIND=nag_wp) arrayUser Workspace
F is called with the arguments IUSER and RUSER as supplied to F01JBF. You are free to use the arrays IUSER and RUSER to supply information to F as an alternative to using COMMON global variables.
F must either be a module subprogram USEd by, or declared as EXTERNAL in, the (sub)program from which F01JBF is called. Arguments denoted as Input must not be changed by this procedure.
5:   IUSER* – INTEGER arrayUser Workspace
6:   RUSER* – REAL (KIND=nag_wp) arrayUser Workspace
IUSER and RUSER are not used by F01JBF, but are passed directly to F and may be used to pass information to this routine as an alternative to using COMMON global variables.
7:   IFLAG – INTEGEROutput
On exit: IFLAG=0, unless IFLAG has been set nonzero inside F, in which case IFLAG will be the value set and IFAIL will be set to IFAIL=3.
8:   CONDA – REAL (KIND=nag_wp)Output
On exit: an estimate of the absolute condition number of f at A.
9:   NORMA – REAL (KIND=nag_wp)Output
On exit: the 1-norm of A.
10:   NORMFA – REAL (KIND=nag_wp)Output
On exit: the 1-norm of f A.
11:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
An internal error occurred when estimating the norm of the Fréchet derivative of f at A. Please contact NAG.
IFAIL=2
An internal error occurred when evaluating the matrix function f A. You can investigate further by calling F01ELF with the matrix A and the function f.
IFAIL=3
IFLAG has been set nonzero by the user-supplied subroutine.
IFAIL=-1
On entry, N<0.
Input argument number value is invalid.
IFAIL=-3
On entry, argument LDA is invalid.
Constraint: LDA≥N.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

F01JBF uses the norm estimation routine F04YDF to estimate a quantity γ, where γ ≤ K X 1 and K X 1 ∈ n-1 L X 1 , n L X 1 . For further details on the accuracy of norm estimation, see the documentation for F04YDF.

8 Parallelism and Performance

F01JBF is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library. In these implementations, this routine may make calls to the user-supplied functions from within an OpenMP parallel region. Thus OpenMP directives within the user functions can only be used if you are compiling the user-supplied function and linking the executable in accordance with the instructions in the Users' Note for your implementation. The user workspace arrays IUSER and RUSER are classified as OpenMP shared memory and use of IUSER and RUSER has to take account of this in order to preserve thread safety whenever information is written back to either of these arrays. If at all possible, it is recommended that these arrays are only used to supply read-only data to the user functions when a multithreaded implementation is being used.
F01JBF makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The matrix function is computed using the underlying matrix function routine F01ELF. Approximately 6 n 2 of real allocatable memory is required by the routine, in addition to the memory used by the underlying matrix function routine.
If only f A is required, without an estimate of the condition number, then it is far more efficient to use the underlying matrix function routine.
The complex analogue of this routine is F01KBF.

10 Example

This example estimates the absolute and relative condition numbers of the matrix function cos⁡2 A where
A= -1 -1 -2 1 0 1 -1 0 -1 -2 1 -1 0 -1 0 -1 .

10.1 Program Text

Program Text (f01jbfe.f90)

10.2 Program Data

Program Data (f01jbfe.d)

10.3 Program Results

Program Results (f01jbfe.r)

F01 Chapter Contents
F01 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F01JCF : NAG Library, Mark 26

F01 Chapter Contents
F01 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F01JCF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F01JCF computes an estimate of the absolute condition number of a matrix function f at a real n by n matrix A in the 1-norm, using analytical derivatives of f you have supplied.

2 Specification

SUBROUTINE F01JCF ( N, A, LDA, F, IUSER, RUSER, IFLAG, CONDA, NORMA, NORMFA, IFAIL)
INTEGER | N, LDA, IUSER(*), IFLAG, IFAIL
REAL (KIND=nag_wp) | A(LDA,*), RUSER(*), CONDA, NORMA, NORMFA
EXTERNAL | F

3 Description

The absolute condition number of f at A, condabs f,A is given by the norm of the Fréchet derivative of f, L A, which is defined by
L X := max E≠0 L X,E E ,
where L X,E is the Fréchet derivative in the direction E. L X,E is linear in E and can therefore be written as
vec L X,E = K X vec E ,
where the vec operator stacks the columns of a matrix into one vector, so that K X is n 2×n 2. F01JCF computes an estimate γ such that γ ≤ K X 1 , where K X 1 ∈ n-1 L X 1 , n L X 1 . The relative condition number can then be computed via
cond rel f,A = cond abs f,A A 1 f A 1 .
The algorithm used to find γ is detailed in Section 3.4 of Higham (2008).
The function f, and the derivatives of f, are returned by subroutine F which, given an integer m, evaluates f m zi at a number of (generally complex) points zi, for i=1,2,…,nz. For any z on the real line, f z must also be real. F01JCF is therefore appropriate for routines that can be evaluated on the complex plane and whose derivatives, of arbitrary order, can also be evaluated on the complex plane.

4 References

Higham N J (2008) Functions of Matrices: Theory and Computation SIAM, Philadelphia, PA, USA

5 Arguments

1:   N – INTEGERInput
On entry: n, the order of the matrix A.
Constraint: N≥0.
2:   A LDA* – REAL (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array A must be at least N.
On entry: the n by n matrix A.
On exit: the n by n matrix, f A.
3:   LDA – INTEGERInput
On entry: the first dimension of the array A as declared in the (sub)program from which F01JCF is called.
Constraint: LDA≥N.
4:   F – SUBROUTINE, supplied by the user.External Procedure
Given an integer m, the subroutine F evaluates f m zi at a number of points zi.
The specification of F is:
SUBROUTINE F ( M, IFLAG, NZ, Z, FZ, IUSER, RUSER)
INTEGER | M, IFLAG, NZ, IUSER(*)
REAL (KIND=nag_wp) | RUSER(*)
COMPLEX (KIND=nag_wp) | Z(NZ), FZ(NZ)
1:   M – INTEGERInput
On entry: the order, m, of the derivative required.
If M=0, f zi should be returned. For M>0, f m zi should be returned.
2:   IFLAG – INTEGERInput/Output
On entry: IFLAG will be zero.
On exit: IFLAG should either be unchanged from its entry value of zero, or may be set nonzero to indicate that there is a problem in evaluating the function f z; for instance f z may not be defined. If IFLAG is returned as nonzero then F01JCF will terminate the computation, with IFAIL=3.
3:   NZ – INTEGERInput
On entry: nz, the number of function or derivative values required.
4:   Z NZ – COMPLEX (KIND=nag_wp) arrayInput
On entry: the nz points z 1,z 2,…,z nz at which the function f is to be evaluated.
5:   FZ NZ – COMPLEX (KIND=nag_wp) arrayOutput
On exit: the nz function or derivative values. FZ i should return the value f m zi, for i=1,2,…,nz. If zi lies on the real line, then so must f m zi.
6:   IUSER* – INTEGER arrayUser Workspace
7:   RUSER* – REAL (KIND=nag_wp) arrayUser Workspace
F is called with the arguments IUSER and RUSER as supplied to F01JCF. You are free to use the arrays IUSER and RUSER to supply information to F as an alternative to using COMMON global variables.
F must either be a module subprogram USEd by, or declared as EXTERNAL in, the (sub)program from which F01JCF is called. Arguments denoted as Input must not be changed by this procedure.
5:   IUSER* – INTEGER arrayUser Workspace
6:   RUSER* – REAL (KIND=nag_wp) arrayUser Workspace
IUSER and RUSER are not used by F01JCF, but are passed directly to F and may be used to pass information to this routine as an alternative to using COMMON global variables.
7:   IFLAG – INTEGEROutput
On exit: IFLAG=0, unless IFLAG has been set nonzero inside F, in which case IFLAG will be the value set and IFAIL will be set to IFAIL=3.
8:   CONDA – REAL (KIND=nag_wp)Output
On exit: an estimate of the absolute condition number of f at A.
9:   NORMA – REAL (KIND=nag_wp)Output
On exit: the 1-norm of A.
10:   NORMFA – REAL (KIND=nag_wp)Output
On exit: the 1-norm of f A.
11:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
An internal error occurred when estimating the norm of the Fréchet derivative of f at A. Please contact NAG.
IFAIL=2
An internal error occurred when evaluating the matrix function f A. You can investigate further by calling F01EMF with the matrix A and the function f.
IFAIL=3
IFLAG has been set nonzero by the user-supplied subroutine.
IFAIL=-1
On entry, N<0.
Input argument number value is invalid.
IFAIL=-3
On entry, argument LDA is invalid.
Constraint: LDA≥N.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

F01JCF uses the norm estimation routine F04YDF to estimate a quantity γ, where γ ≤ K X 1 and K X 1 ∈ n-1 L X 1 , n L X 1 . For further details on the accuracy of norm estimation, see the documentation for F04YDF.

8 Parallelism and Performance

F01JCF is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library. In these implementations, this routine may make calls to the user-supplied functions from within an OpenMP parallel region. Thus OpenMP directives within the user functions can only be used if you are compiling the user-supplied function and linking the executable in accordance with the instructions in the Users' Note for your implementation. The user workspace arrays IUSER and RUSER are classified as OpenMP shared memory and use of IUSER and RUSER has to take account of this in order to preserve thread safety whenever information is written back to either of these arrays. If at all possible, it is recommended that these arrays are only used to supply read-only data to the user functions when a multithreaded implementation is being used.
F01JCF makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The matrix function is computed using the underlying matrix function routine F01EMF. Approximately 6 n 2 of real allocatable memory is required by the routine, in addition to the memory used by the underlying matrix function routine.
If only f A is required, without an estimate of the condition number, then it is far more efficient to use the underlying matrix function routine directly.
The complex analogue of this routine is F01KCF.

10 Example

This example estimates the absolute and relative condition numbers of the matrix function e 2 A where
A= 0 -1 -1 1 -2 0 1 -1 2 -1 2 -2 -1 -2 0 -1 .

10.1 Program Text

Program Text (f01jcfe.f90)

10.2 Program Data

Program Data (f01jcfe.d)

10.3 Program Results

Program Results (f01jcfe.r)

F01 Chapter Contents
F01 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F01JDF : NAG Library, Mark 26

F01 Chapter Contents
F01 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F01JDF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F01JDF computes an estimate of the relative condition number κ A 1/2 and a bound on the relative residual, in the Frobenius norm, for the square root of a real n by n matrix A. The principal square root, A 1/2, of A is also returned.

2 Specification

SUBROUTINE F01JDF ( N, A, LDA, ALPHA, CONDSA, IFAIL)
INTEGER | N, LDA, IFAIL
REAL (KIND=nag_wp) | A(LDA,*), ALPHA, CONDSA

3 Description

For a matrix with no eigenvalues on the closed negative real line, the principal matrix square root, A 1/2, of A is the unique square root with eigenvalues in the right half-plane.
The Fréchet derivative of a matrix function A 1/2 in the direction of the matrix E is the linear function mapping E to L A,E such that
A+E 1/2 - A 1/2 - L A,E = o A .
The absolute condition number is given by the norm of the Fréchet derivative which is defined by
L A := max E≠0 L A,E E .
The Fréchet derivative is linear in E and can therefore be written as
vec L A,E = K A vec E ,
where the vec operator stacks the columns of a matrix into one vector, so that K A is n 2×n 2.
F01JDF uses Algorithm 3.20 from Higham (2008) to compute an estimate γ such that γ ≤ K X F . The quantity of γ provides a good approximation to L A F. The relative condition number, κ A 1/2, is then computed via
κ A 1/2 = L A F A F A 1/2 F .
κ A 1/2 is returned in the argument CONDSA.
A 1/2 is computed using the algorithm described in Higham (1987). This is a real arithmetic version of the algorithm of Björck and Hammarling (1983). In addition, a blocking scheme described in Deadman et al. (2013) is used.
The computed quantity α is a measure of the stability of the relative residual (see Section 7). It is computed via
α= A 1/2 F 2 A F .

4 References

Björck Å and Hammarling S (1983) A Schur method for the square root of a matrix Linear Algebra Appl. 52/53 127–140
Deadman E, Higham N J and Ralha R (2013) Blocked Schur Algorithms for Computing the Matrix Square Root Applied Parallel and Scientific Computing: 11th International Conference, (PARA 2012, Helsinki, Finland) P. Manninen and P. Öster, Eds Lecture Notes in Computer Science 7782 171–181 Springer–Verlag
Higham N J (1987) Computing real square roots of a real matrix Linear Algebra Appl. 88/89 405–430
Higham N J (2008) Functions of Matrices: Theory and Computation SIAM, Philadelphia, PA, USA

5 Arguments

1:   N – INTEGERInput
On entry: n, the order of the matrix A.
Constraint: N≥0.
2:   A LDA* – REAL (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array A must be at least N.
On entry: the n by n matrix A.
On exit: contains, if IFAIL=0, the n by n principal matrix square root, A 1/2. Alternatively, if IFAIL=1, contains an n by n non-principal square root of A.
3:   LDA – INTEGERInput
On entry: the first dimension of the array A as declared in the (sub)program from which F01JDF is called.
Constraint: LDA≥N.
4:   ALPHA – REAL (KIND=nag_wp)Output
On exit: an estimate of the stability of the relative residual for the computed principal (if IFAIL=0) or non-principal (if IFAIL=1) matrix square root, α.
5:   CONDSA – REAL (KIND=nag_wp)Output
On exit: an estimate of the relative condition number, in the Frobenius norm, of the principal (if IFAIL=0) or non-principal (if IFAIL=1) matrix square root at A, κ A 1/2.
6:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
A has a semisimple vanishing eigenvalue. A non-principal square root was returned.
IFAIL=2
A has a defective vanishing eigenvalue. The square root and condition number cannot be found in this case.
IFAIL=3
A has a negative real eigenvalue. The principal square root is not defined. F01KDF can be used to return a complex, non-principal square root.
IFAIL=4
An error occurred when computing the matrix square root. Consequently, ALPHA and CONDSA could not be computed. It is likely that the routine was called incorrectly.
IFAIL=5
An error occurred when computing the condition number. The matrix square root was still returned but you should use F01ENF to check if it is the principal matrix square root.
IFAIL=-1
On entry, N=value.
Constraint: N≥0.
IFAIL=-3
On entry, LDA=value and N=value.
Constraint: LDA≥N.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

If the computed square root is X~, then the relative residual
A - X~2 F A F ,
is bounded approximately by nαε, where ε is machine precision. The relative error in X~ is bounded approximately by nα κ A 1/2 ε.

8 Parallelism and Performance

F01JDF is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
F01JDF makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

Approximately 3×n 2 of real allocatable memory is required by the routine.
The cost of computing the matrix square root is 85 n 3/3 floating-point operations. The cost of computing the condition number depends on how fast the algorithm converges. It typically takes over twice as long as computing the matrix square root.
If condition estimates are not required then it is more efficient to use F01ENF to obtain the matrix square root alone. Condition estimates for the square root of a complex matrix can be obtained via F01KDF.

10 Example

This example estimates the matrix square root and condition number of the matrix
A = -5 2 -1 1 -2 -3 19 27 -9 0 15 24 7 8 11 16 .

10.1 Program Text

Program Text (f01jdfe.f90)

10.2 Program Data

Program Data (f01jdfe.d)

10.3 Program Results

Program Results (f01jdfe.r)

F01 Chapter Contents
F01 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F01JEF : NAG Library, Mark 26

F01 Chapter Contents
F01 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F01JEF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F01JEF computes an estimate of the relative condition number κ Ap of the pth power (where p is real) of a real n by n matrix A, in the 1-norm. The principal matrix power Ap is also returned.

2 Specification

SUBROUTINE F01JEF ( N, A, LDA, P, CONDPA, IFAIL)
INTEGER | N, LDA, IFAIL
REAL (KIND=nag_wp) | A(LDA,*), P, CONDPA

3 Description

For a matrix A with no eigenvalues on the closed negative real line, Ap (p∈ℝ) can be defined as
Ap= exp p log A
where log A is the principal logarithm of A (the unique logarithm whose spectrum lies in the strip z:-π<Im z<π).
The Fréchet derivative of the matrix pth power of A is the unique linear mapping E⟼L A,E such that for any matrix E
A+E p - Ap - L A,E = o E .
The derivative describes the first-order effect of perturbations in A on the matrix power Ap.
The relative condition number of the matrix pth power can be defined by
κ Ap = L A A Ap ,
where L A is the norm of the Fréchet derivative of the matrix power at A.
F01JEF uses the algorithms of Higham and Lin (2011) and Higham and Lin (2013) to compute κ Ap and Ap. The real number p is expressed as p=q+r where q∈-1,1 and r∈ℤ. Then Ap=AqAr. The integer power Ar is found using a combination of binary powering and, if necessary, matrix inversion. The fractional power Aq is computed using a Schur decomposition, a Padé approximant and the scaling and squaring method.
To obtain an estimate of κ Ap, F01JEF first estimates L A by computing an estimate γ of a quantity K∈n-1 L A 1,n L A 1, such that γ≤K. This requires multiple Fréchet derivatives to be computed. Fréchet derivatives of Aq are obtained by differentiating the Padé approximant. Fréchet derivatives of Ap are then computed using a combination of the chain rule and the product rule for Fréchet derivatives.

4 References

Higham N J (2008) Functions of Matrices: Theory and Computation SIAM, Philadelphia, PA, USA
Higham N J and Lin L (2011) A Schur–Padé algorithm for fractional powers of a matrix SIAM J. Matrix Anal. Appl. 32(3) 1056–1078
Higham N J and Lin L (2013) An improved Schur–Padé algorithm for fractional powers of a matrix and their Fréchet derivatives SIAM J. Matrix Anal. Appl. 34(3) 1341–1360

5 Arguments

1:   N – INTEGERInput
On entry: n, the order of the matrix A.
Constraint: N≥0.
2:   A LDA* – REAL (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array A must be at least N.
On entry: the n by n matrix A.
On exit: the n by n principal matrix pth power, Ap.
3:   LDA – INTEGERInput
On entry: the first dimension of the array A as declared in the (sub)program from which F01JEF is called.
Constraint: LDA≥N.
4:   P – REAL (KIND=nag_wp)Input
On entry: the required power of A.
5:   CONDPA – REAL (KIND=nag_wp)Output
On exit: if IFAIL=0 or 3, an estimate of the relative condition number of the matrix pth power, κ Ap. Alternatively, if IFAIL=4, the absolute condition number of the matrix pth power.
6:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
A has eigenvalues on the negative real line. The principal pth power is not defined in this case; F01KEF can be used to find a complex, non-principal pth power.
IFAIL=2
A is singular so the pth power cannot be computed.
IFAIL=3
Ap has been computed using an IEEE double precision Padé approximant, although the arithmetic precision is higher than IEEE double precision.
IFAIL=4
The relative condition number is infinite. The absolute condition number was returned instead.
IFAIL=5
An unexpected internal error occurred. This failure should not occur and suggests that the routine has been called incorrectly.
IFAIL=-1
On entry, N=value.
Constraint: N≥0.
IFAIL=-3
On entry, LDA=value and N=value.
Constraint: LDA≥N.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

F01JEF uses the norm estimation routine F04YDF to produce an estimate γ of a quantity K∈n-1 L A 1,n L A 1, such that γ≤K. For further details on the accuracy of norm estimation, see the documentation for F04YDF.
For a normal matrix A (for which AT A=A AT), the Schur decomposition is diagonal and the computation of the fractional part of the matrix power reduces to evaluating powers of the eigenvalues of A and then constructing Ap using the Schur vectors. This should give a very accurate result. In general, however, no error bounds are available for the algorithm. See Higham and Lin (2011) and Higham and Lin (2013) for details and further discussion.

8 Parallelism and Performance

F01JEF is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
F01JEF makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The amount of real allocatable memory required by the algorithm is typically of the order 10×n 2.
The cost of the algorithm is O n 3 floating-point operations; see Higham and Lin (2013).
If the matrix pth power alone is required, without an estimate of the condition number, then F01EQF should be used. If the Fréchet derivative of the matrix power is required then F01JFF should be used. If A has negative real eigenvalues then F01KEF can be used to return a complex, non-principal pth power and its condition number.

10 Example

This example estimates the relative condition number of the matrix power Ap, where p=0.2 and
A = 3 3 2 1 1 1 0 2 1 4 4 2 3 1 3 1 .

10.1 Program Text

Program Text (f01jefe.f90)

10.2 Program Data

Program Data (f01jefe.d)

10.3 Program Results

Program Results (f01jefe.r)

F01 Chapter Contents
F01 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F01JFF : NAG Library, Mark 26

F01 Chapter Contents
F01 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F01JFF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F01JFF computes the Fréchet derivative L A,E of the pth power (where p is real) of the real n by n matrix A applied to the real n by n matrix E. The principal matrix power Ap is also returned.

2 Specification

SUBROUTINE F01JFF ( N, A, LDA, E, LDE, P, IFAIL)
INTEGER | N, LDA, LDE, IFAIL
REAL (KIND=nag_wp) | A(LDA,*), E(LDE,*), P

3 Description

For a matrix A with no eigenvalues on the closed negative real line, Ap (p∈ℝ) can be defined as
Ap= exp p log A
where log A is the principal logarithm of A (the unique logarithm whose spectrum lies in the strip z:-π<Im z<π).
The Fréchet derivative of the matrix pth power of A is the unique linear mapping E⟼L A,E such that for any matrix E
A+E p - Ap - L A,E = o E .
The derivative describes the first-order effect of perturbations in A on the matrix power Ap.
F01JFF uses the algorithms of Higham and Lin (2011) and Higham and Lin (2013) to compute Ap and L A,E. The real number p is expressed as p=q+r where q∈-1,1 and r∈ℤ. Then Ap=AqAr. The integer power Ar is found using a combination of binary powering and, if necessary, matrix inversion. The fractional power Aq is computed using a Schur decomposition, a Padé approximant and the scaling and squaring method. The Padé approximant is differentiated in order to obtain the Fréchet derivative of Aq and L A,E is then computed using a combination of the chain rule and the product rule for Fréchet derivatives.

4 References

Higham N J (2008) Functions of Matrices: Theory and Computation SIAM, Philadelphia, PA, USA
Higham N J and Lin L (2011) A Schur–Padé algorithm for fractional powers of a matrix SIAM J. Matrix Anal. Appl. 32(3) 1056–1078
Higham N J and Lin L (2013) An improved Schur–Padé algorithm for fractional powers of a matrix and their Fréchet derivatives SIAM J. Matrix Anal. Appl. 34(3) 1341–1360

5 Arguments

1:   N – INTEGERInput
On entry: n, the order of the matrix A.
Constraint: N≥0.
2:   A LDA* – REAL (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array A must be at least N.
On entry: the n by n matrix A.
On exit: the n by n principal matrix pth power, Ap.
3:   LDA – INTEGERInput
On entry: the first dimension of the array A as declared in the (sub)program from which F01JFF is called.
Constraint: LDA≥N.
4:   E LDE* – REAL (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array E must be at least N.
On entry: the n by n matrix E.
On exit: the Fréchet derivative L A,E.
5:   LDE – INTEGERInput
On entry: the first dimension of the array E as declared in the (sub)program from which F01JFF is called.
Constraint: LDE≥N.
6:   P – REAL (KIND=nag_wp)Input
On entry: the required power of A.
7:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
A has eigenvalues on the negative real line. The principal pth power is not defined in this case; F01KFF can be used to find a complex, non-principal pth power.
IFAIL=2
A is singular so the pth power cannot be computed.
IFAIL=3
Ap has been computed using an IEEE double precision Padé approximant, although the arithmetic precision is higher than IEEE double precision.
IFAIL=4
An unexpected internal error occurred. This failure should not occur and suggests that the routine has been called incorrectly.
IFAIL=-1
On entry, N=value.
Constraint: N≥0.
IFAIL=-3
On entry, LDA=value and N=value.
Constraint: LDA≥N.
IFAIL=-5
On entry, LDE=value and N=value.
Constraint: LDE≥N.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

For a normal matrix A (for which AT A=A AT), the Schur decomposition is diagonal and the computation of the fractional part of the matrix power reduces to evaluating powers of the eigenvalues of A and then constructing Ap using the Schur vectors. This should give a very accurate result. In general, however, no error bounds are available for the algorithm. See Higham and Lin (2011) and Higham and Lin (2013) for details and further discussion.
If the condition number of the matrix power is required then F01JEF should be used.

8 Parallelism and Performance

F01JFF is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
F01JFF makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The real allocatable memory required by the algorithm is approximately 6×n 2.
The cost of the algorithm is O n 3 floating-point operations; see Higham and Lin (2011) and Higham and Lin (2013).
If the matrix pth power alone is required, without the Fréchet derivative, then F01EQF should be used. If the condition number of the matrix power is required then F01JEF should be used. If A has negative real eigenvalues then F01KFF can be used to return a complex, non-principal pth power and its Fréchet derivative L A,E.

10 Example

This example finds Ap and the Fréchet derivative of the matrix power L A,E, where p=0.2,
A = 3 3 2 1 3 1 0 2 1 1 4 3 3 0 3 1   and   E = 1 0 2 1 0 4 5 2 1 0 0 0 2 3 3 0 .

10.1 Program Text

Program Text (f01jffe.f90)

10.2 Program Data

Program Data (f01jffe.d)

10.3 Program Results

Program Results (f01jffe.r)

F01 Chapter Contents
F01 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F01JGF : NAG Library, Mark 26

F01 Chapter Contents
F01 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F01JGF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F01JGF computes an estimate of the relative condition number κexp A of the exponential of a real n by n matrix A, in the 1-norm. The matrix exponential eA is also returned.

2 Specification

SUBROUTINE F01JGF ( N, A, LDA, CONDEA, IFAIL)
INTEGER | N, LDA, IFAIL
REAL (KIND=nag_wp) | A(LDA,*), CONDEA

3 Description

The Fréchet derivative of the matrix exponential of A is the unique linear mapping E⟼L A,E such that for any matrix E
e A+E - e A - L A,E = o E .
The derivative describes the first-order effect of perturbations in A on the exponential eA.
The relative condition number of the matrix exponential can be defined by
κexp A = L A A exp A ,
where L A is the norm of the Fréchet derivative of the matrix exponential at A.
To obtain the estimate of κexp A, F01JGF first estimates L A by computing an estimate γ of a quantity K∈n-1 L A 1,n L A 1, such that γ≤K.
The algorithms used to compute κexp A are detailed in the Al–Mohy and Higham (2009a) and Al–Mohy and Higham (2009b).
The matrix exponential eA is computed using a Padé approximant and the scaling and squaring method. The Padé approximant is differentiated to obtain the Fréchet derivatives L A,E which are used to estimate the condition number.

4 References

Al–Mohy A H and Higham N J (2009a) A new scaling and squaring algorithm for the matrix exponential SIAM J. Matrix Anal. 31(3) 970–989
Al–Mohy A H and Higham N J (2009b) Computing the Fréchet derivative of the matrix exponential, with an application to condition number estimation SIAM J. Matrix Anal. Appl. 30(4) 1639–1657
Higham N J (2008) Functions of Matrices: Theory and Computation SIAM, Philadelphia, PA, USA
Moler C B and Van Loan C F (2003) Nineteen dubious ways to compute the exponential of a matrix, twenty-five years later SIAM Rev. 45 3–49

5 Arguments

1:   N – INTEGERInput
On entry: n, the order of the matrix A.
Constraint: N≥0.
2:   A LDA* – REAL (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array A must be at least N.
On entry: the n by n matrix A.
On exit: the n by n matrix exponential eA.
3:   LDA – INTEGERInput
On entry: the first dimension of the array A as declared in the (sub)program from which F01JGF is called.
Constraint: LDA≥N.
4:   CONDEA – REAL (KIND=nag_wp)Output
On exit: an estimate of the relative condition number of the matrix exponential κexp A.
5:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
The linear equations to be solved for the Padé approximant are singular; it is likely that this routine has been called incorrectly.
IFAIL=2
eA has been computed using an IEEE double precision Padé approximant, although the arithmetic precision is higher than IEEE double precision.
IFAIL=3
An unexpected internal error has occurred. Please contact NAG.
IFAIL=-1
On entry, N=value.
Constraint: N≥0.
IFAIL=-3
On entry, LDA=value and N=value.
Constraint: LDA≥N.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

F01JGF uses the norm estimation routine F04YDF to produce an estimate γ of a quantity K∈n-1 L A 1,n L A 1, such that γ≤K. For further details on the accuracy of norm estimation, see the documentation for F04YDF.
For a normal matrix A (for which AT A=A AT) the computed matrix, eA, is guaranteed to be close to the exact matrix, that is, the method is forward stable. No such guarantee can be given for non-normal matrices. See Section 10.3 of Higham (2008) for details and further discussion.
For further discussion of the condition of the matrix exponential see Section 10.2 of Higham (2008).

8 Parallelism and Performance

F01JGF is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
F01JGF makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

F01JAF uses a similar algorithm to F01JGF to compute an estimate of the absolute condition number (which is related to the relative condition number by a factor of A/exp A). However, the required Fréchet derivatives are computed in a more efficient and stable manner by F01JGF and so its use is recommended over F01JAF.
The cost of the algorithm is O n 3 and the real allocatable memory required is approximately 15 n 2; see Al–Mohy and Higham (2009a) and Al–Mohy and Higham (2009b) for further details.
If the matrix exponential alone is required, without an estimate of the condition number, then F01ECF should be used. If the Fréchet derivative of the matrix exponential is required then F01JHF should be used.
As well as the excellent book Higham (2008), the classic reference for the computation of the matrix exponential is Moler and Van Loan (2003).

10 Example

This example estimates the relative condition number of the matrix exponential eA, where
A = 2 2 1 2 3 1 4 0 2 3 1 2 0 1 3 3 .

10.1 Program Text

Program Text (f01jgfe.f90)

10.2 Program Data

Program Data (f01jgfe.d)

10.3 Program Results

Program Results (f01jgfe.r)

F01 Chapter Contents
F01 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F01JHF : NAG Library, Mark 26

F01 Chapter Contents
F01 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F01JHF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F01JHF computes the Fréchet derivative L A,E of the matrix exponential of a real n by n matrix A applied to the real n by n matrix E. The matrix exponential eA is also returned.

2 Specification

SUBROUTINE F01JHF ( N, A, LDA, E, LDE, IFAIL)
INTEGER | N, LDA, LDE, IFAIL
REAL (KIND=nag_wp) | A(LDA,*), E(LDE,*)

3 Description

The Fréchet derivative of the matrix exponential of A is the unique linear mapping E⟼L A,E such that for any matrix E
e A+E - e A - L A,E = o E .
The derivative describes the first-order effect of perturbations in A on the exponential eA.
F01JHF uses the algorithms of Al–Mohy and Higham (2009a) and Al–Mohy and Higham (2009b) to compute eA and L A,E. The matrix exponential eA is computed using a Padé approximant and the scaling and squaring method. The Padé approximant is then differentiated in order to obtain the Fréchet derivative L A,E.

4 References

Al–Mohy A H and Higham N J (2009a) A new scaling and squaring algorithm for the matrix exponential SIAM J. Matrix Anal. 31(3) 970–989
Al–Mohy A H and Higham N J (2009b) Computing the Fréchet derivative of the matrix exponential, with an application to condition number estimation SIAM J. Matrix Anal. Appl. 30(4) 1639–1657
Higham N J (2008) Functions of Matrices: Theory and Computation SIAM, Philadelphia, PA, USA
Moler C B and Van Loan C F (2003) Nineteen dubious ways to compute the exponential of a matrix, twenty-five years later SIAM Rev. 45 3–49

5 Arguments

1:   N – INTEGERInput
On entry: n, the order of the matrix A.
Constraint: N≥0.
2:   A LDA* – REAL (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array A must be at least N.
On entry: the n by n matrix A.
On exit: the n by n matrix exponential eA.
3:   LDA – INTEGERInput
On entry: the first dimension of the array A as declared in the (sub)program from which F01JHF is called.
Constraint: LDA≥N.
4:   E LDE* – REAL (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array E must be at least N.
On entry: the n by n matrix E
On exit: the Fréchet derivative L A,E
5:   LDE – INTEGERInput
On entry: the first dimension of the array E as declared in the (sub)program from which F01JHF is called.
Constraint: LDE≥N.
6:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
The linear equations to be solved for the Padé approximant are singular; it is likely that this routine has been called incorrectly.
IFAIL=2
eA has been computed using an IEEE double precision Padé approximant, although the arithmetic precision is higher than IEEE double precision.
IFAIL=3
An unexpected internal error has occurred. Please contact NAG.
IFAIL=-1
On entry, N=value.
Constraint: N≥0.
IFAIL=-3
On entry, LDA=value and N=value.
Constraint: LDA≥N.
IFAIL=-5
On entry, LDE=value and N=value.
Constraint: LDE≥N.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

For a normal matrix A (for which AT A=A AT) the computed matrix, eA, is guaranteed to be close to the exact matrix, that is, the method is forward stable. No such guarantee can be given for non-normal matrices. See Section 10.3 of Higham (2008), Al–Mohy and Higham (2009a) and Al–Mohy and Higham (2009b) for details and further discussion.

8 Parallelism and Performance

F01JHF is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
F01JHF makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The cost of the algorithm is O n 3 and the real allocatable memory required is approximately 9 n 2; see Al–Mohy and Higham (2009a) and Al–Mohy and Higham (2009b).
If the matrix exponential alone is required, without the Fréchet derivative, then F01ECF should be used.
If the condition number of the matrix exponential is required then F01JGF should be used.
As well as the excellent book Higham (2008), the classic reference for the computation of the matrix exponential is Moler and Van Loan (2003).

10 Example

This example finds the matrix exponential eA and the Fréchet derivative L A,E, where
A = 1 2 2 2 3 1 1 2 3 2 1 2 3 3 3 1   and   E = 1 0 1 2 0 0 0 1 4 2 1 2 0 3 2 1 .

10.1 Program Text

Program Text (f01jhfe.f90)

10.2 Program Data

Program Data (f01jhfe.d)

10.3 Program Results

Program Results (f01jhfe.r)

F01 Chapter Contents
F01 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F01JJF : NAG Library, Mark 26

F01 Chapter Contents
F01 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F01JJF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F01JJF computes an estimate of the relative condition number κlog A of the logarithm of a real n by n matrix A, in the 1-norm. The principal matrix logarithm log A is also returned.

2 Specification

SUBROUTINE F01JJF ( N, A, LDA, CONDLA, IFAIL)
INTEGER | N, LDA, IFAIL
REAL (KIND=nag_wp) | A(LDA,*), CONDLA

3 Description

For a matrix with no eigenvalues on the closed negative real line, the principal matrix logarithm log A is the unique logarithm whose spectrum lies in the strip z:-π<Im⁡z<π.
The Fréchet derivative of the matrix logarithm of A is the unique linear mapping E⟼L A,E such that for any matrix E
log A+E - log A - L A,E = o E .
The derivative describes the first order effect of perturbations in A on the logarithm log A.
The relative condition number of the matrix logarithm can be defined by
κlog A = L A A log A ,
where L A is the norm of the Fréchet derivative of the matrix logarithm at A.
To obtain the estimate of κlog A, F01JJF first estimates L A by computing an estimate γ of a quantity K∈n-1 L A 1,n L A 1, such that γ≤K.
The algorithms used to compute κlog A and log A are based on a Schur decomposition, the inverse scaling and squaring method and Padé approximants. Further details can be found in Al–Mohy and Higham (2011) and Al–Mohy et al. (2012).

4 References

Al–Mohy A H and Higham N J (2011) Improved inverse scaling and squaring algorithms for the matrix logarithm SIAM J. Sci. Comput. 34(4) C152–C169
Al–Mohy A H, Higham N J and Relton S D (2012) Computing the Fréchet derivative of the matrix logarithm and estimating the condition number SIAM J. Sci. Comput. 35(4) C394–C410
Higham N J (2008) Functions of Matrices: Theory and Computation SIAM, Philadelphia, PA, USA

5 Arguments

1:   N – INTEGERInput
On entry: n, the order of the matrix A.
Constraint: N≥0.
2:   A LDA* – REAL (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array A must be at least N.
On entry: the n by n matrix A.
On exit: the n by n principal matrix logarithm, log A.
3:   LDA – INTEGERInput
On entry: the first dimension of the array A as declared in the (sub)program from which F01JJF is called.
Constraint: LDA≥N.
4:   CONDLA – REAL (KIND=nag_wp)Output
On exit: with IFAIL=0 or 3, an estimate of the relative condition number of the matrix logarithm, κlog A. Alternatively, if IFAIL=4, contains the absolute condition number of the matrix logarithm.
5:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
A is singular so the logarithm cannot be computed.
IFAIL=2
A has eigenvalues on the negative real line. The principal logarithm is not defined in this case; F01KJF can be used to return a complex, non-principal log.
IFAIL=3
log A has been computed using an IEEE double precision Padé approximant, although the arithmetic precision is higher than IEEE double precision.
IFAIL=4
The relative condition number is infinite. The absolute condition number was returned instead.
IFAIL=5
An unexpected internal error occurred. This failure should not occur and suggests that the routine has been called incorrectly.
IFAIL=-1
On entry, N=value.
Constraint: N≥0.
IFAIL=-3
On entry, LDA=value and N=value.
Constraint: LDA≥N.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

F01JJF uses the norm estimation routine F04YDF to produce an estimate γ of a quantity K∈n-1 L A 1,n L A 1, such that γ≤K. For further details on the accuracy of norm estimation, see the documentation for F04YDF.
For a normal matrix A (for which AT A=A AT), the Schur decomposition is diagonal and the computation of the matrix logarithm reduces to evaluating the logarithm of the eigenvalues of A and then constructing log A using the Schur vectors. This should give a very accurate result. In general, however, no error bounds are available for the algorithm. The sensitivity of the computation of log A is worst when A has an eigenvalue of very small modulus or has a complex conjugate pair of eigenvalues lying close to the negative real axis. See Al–Mohy and Higham (2011) and Section 11.2 of Higham (2008) for details and further discussion.

8 Parallelism and Performance

F01JJF is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
F01JJF makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

F01JAF uses a similar algorithm to F01JJF to compute an estimate of the absolute condition number (which is related to the relative condition number by a factor of A/log A). However, the required Fréchet derivatives are computed in a more efficient and stable manner by F01JJF and so its use is recommended over F01JAF.
The amount of real allocatable memory required by the algorithm is typically of the order 10 n 2.
The cost of the algorithm is O n 3 floating-point operations; see Al–Mohy et al. (2012).
If the matrix logarithm alone is required, without an estimate of the condition number, then F01EJF should be used. If the Fréchet derivative of the matrix logarithm is required then F01JKF should be used. If A has negative real eigenvalues then F01KJF can be used to return a complex, non-principal matrix logarithm and its condition number.

10 Example

This example estimates the relative condition number of the matrix logarithm log A, where
A = 4 -1 0 1 2 5 -2 2 1 1 3 -1 2 0 2 8 .

10.1 Program Text

Program Text (f01jjfe.f90)

10.2 Program Data

Program Data (f01jjfe.d)

10.3 Program Results

Program Results (f01jjfe.r)

F01 Chapter Contents
F01 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F01JKF : NAG Library, Mark 26

F01 Chapter Contents
F01 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F01JKF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F01JKF computes the Fréchet derivative L A,E of the matrix logarithm of the real n by n matrix A applied to the real n by n matrix E. The principal matrix logarithm log A is also returned.

2 Specification

SUBROUTINE F01JKF ( N, A, LDA, E, LDE, IFAIL)
INTEGER | N, LDA, LDE, IFAIL
REAL (KIND=nag_wp) | A(LDA,*), E(LDE,*)

3 Description

For a matrix with no eigenvalues on the closed negative real line, the principal matrix logarithm log A is the unique logarithm whose spectrum lies in the strip z:-π<Im⁡z<π.
The Fréchet derivative of the matrix logarithm of A is the unique linear mapping E⟼L A,E such that for any matrix E
log A+E - log A - L A,E = o E .
The derivative describes the first order effect of perturbations in A on the logarithm log A.
F01JKF uses the algorithm of Al–Mohy et al. (2012) to compute log A and L A,E. The principal matrix logarithm log A is computed using a Schur decomposition, a Padé approximant and the inverse scaling and squaring method. The Padé approximant is then differentiated in order to obtain the Fréchet derivative L A,E.

4 References

Al–Mohy A H and Higham N J (2011) Improved inverse scaling and squaring algorithms for the matrix logarithm SIAM J. Sci. Comput. 34(4) C152–C169
Al–Mohy A H, Higham N J and Relton S D (2012) Computing the Fréchet derivative of the matrix logarithm and estimating the condition number SIAM J. Sci. Comput. 35(4) C394–C410
Higham N J (2008) Functions of Matrices: Theory and Computation SIAM, Philadelphia, PA, USA

5 Arguments

1:   N – INTEGERInput
On entry: n, the order of the matrix A.
Constraint: N≥0.
2:   A LDA* – REAL (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array A must be at least N.
On entry: the n by n matrix A.
On exit: the n by n principal matrix logarithm, log A.
3:   LDA – INTEGERInput
On entry: the first dimension of the array A as declared in the (sub)program from which F01JKF is called.
Constraint: LDA≥N.
4:   E LDE* – REAL (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array E must be at least N.
On entry: the n by n matrix E
On exit: the Fréchet derivative L A,E
5:   LDE – INTEGERInput
On entry: the first dimension of the array E as declared in the (sub)program from which F01JKF is called.
Constraint: LDE≥N.
6:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
A is singular so the logarithm cannot be computed.
IFAIL=2
A has eigenvalues on the negative real line. The principal logarithm is not defined in this case; F01KKF can be used to return a complex, non-principal log.
IFAIL=3
log A has been computed using an IEEE double precision Padé approximant, although the arithmetic precision is higher than IEEE double precision.
IFAIL=4
An unexpected internal error occurred. This failure should not occur and suggests that the routine has been called incorrectly.
IFAIL=-1
On entry, N=value.
Constraint: N≥0.
IFAIL=-3
On entry, LDA=value and N=value.
Constraint: LDA≥N.
IFAIL=-5
On entry, LDE=value and N=value.
Constraint: LDE≥N.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

For a normal matrix A (for which AT A=A AT), the Schur decomposition is diagonal and the computation of the matrix logarithm reduces to evaluating the logarithm of the eigenvalues of A and then constructing log A using the Schur vectors. This should give a very accurate result. In general, however, no error bounds are available for the algorithm. The sensitivity of the computation of log A and L A,E is worst when A has an eigenvalue of very small modulus or has a complex conjugate pair of eigenvalues lying close to the negative real axis. See Al–Mohy and Higham (2011), Al–Mohy et al. (2012) and Section 11.2 of Higham (2008) for details and further discussion.

8 Parallelism and Performance

F01JKF is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
F01JKF makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The cost of the algorithm is O n 3 floating-point operations. The real allocatable memory required is approximately 5 n 2; see Al–Mohy et al. (2012) for further details.
If the matrix logarithm alone is required, without the Fréchet derivative, then F01EJF should be used. If the condition number of the matrix logarithm is required then F01JJF should be used. If A has negative real eigenvalues then F01KKF can be used to return a complex, non-principal matrix logarithm and its Fréchet derivative L A,E.

10 Example

This example finds the principal matrix logarithm log A and the Fréchet derivative L A,E, where
A = 4 2 0 2 3 3 1 1 3 2 1 0 3 3 1 2   and   ​ E = 1 2 2 2 0 0 3 1 1 2 1 2 1 3 1 1 .

10.1 Program Text

Program Text (f01jkfe.f90)

10.2 Program Data

Program Data (f01jkfe.d)

10.3 Program Results

Program Results (f01jkfe.r)

F01 Chapter Contents
F01 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F01KAF : NAG Library, Mark 26

F01 Chapter Contents
F01 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F01KAF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F01KAF computes an estimate of the absolute condition number of a matrix function f of a complex n by n matrix A in the 1-norm, where f is either the exponential, logarithm, sine, cosine, hyperbolic sine (sinh) or hyperbolic cosine (cosh). The evaluation of the matrix function, f A, is also returned.

2 Specification

SUBROUTINE F01KAF ( FUN, N, A, LDA, CONDA, NORMA, NORMFA, IFAIL)
INTEGER | N, LDA, IFAIL
REAL (KIND=nag_wp) | CONDA, NORMA, NORMFA
COMPLEX (KIND=nag_wp) | A(LDA,*)
CHARACTER(*) | FUN

3 Description

The absolute condition number of f at A, condabs f,A is given by the norm of the Fréchet derivative of f, L A, which is defined by
L X := max E≠0 L X,E E ,
where L X,E is the Fréchet derivative in the direction E. L X,E is linear in E and can therefore be written as
vec L X,E = K X vec E ,
where the vec operator stacks the columns of a matrix into one vector, so that K X is n 2×n 2. F01KAF computes an estimate γ such that γ ≤ K X 1 , where K X 1 ∈ n-1 L X 1 , n L X 1 . The relative condition number can then be computed via
cond rel f,A = cond abs f,A A 1 f A 1 .
The algorithm used to find γ is detailed in Section 3.4 of Higham (2008).

4 References

Higham N J (2008) Functions of Matrices: Theory and Computation SIAM, Philadelphia, PA, USA

5 Arguments

1:   FUN – CHARACTER(*)Input
On entry: indicates which matrix function will be used.
FUN='EXP'
The matrix exponential, eA, will be used.
FUN='SIN'
The matrix sine, sin A, will be used.
FUN='COS'
The matrix cosine, cos A, will be used.
FUN='SINH'
The hyperbolic matrix sine, sinh A, will be used.
FUN='COSH'
The hyperbolic matrix cosine, cosh A, will be used.
FUN='LOG'
The matrix logarithm, log A, will be used.
Constraint: FUN='EXP', 'SIN', 'COS', 'SINH', 'COSH' or 'LOG'.
2:   N – INTEGERInput
On entry: n, the order of the matrix A.
Constraint: N≥0.
3:   A LDA* – COMPLEX (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array A must be at least N.
On entry: the n by n matrix A.
On exit: the n by n matrix, f A.
4:   LDA – INTEGERInput
On entry: the first dimension of the array A as declared in the (sub)program from which F01KAF is called.
Constraint: LDA≥N.
5:   CONDA – REAL (KIND=nag_wp)Output
On exit: an estimate of the absolute condition number of f at A.
6:   NORMA – REAL (KIND=nag_wp)Output
On exit: the 1-norm of A.
7:   NORMFA – REAL (KIND=nag_wp)Output
On exit: the 1-norm of f A.
8:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
An internal error occurred when estimating the norm of the Fréchet derivative of f at A. Please contact NAG.
IFAIL=2
An internal error occurred when evaluating the matrix function f A. You can investigate further by calling F01FCF, F01FJF or F01FKF with the matrix A.
IFAIL=-1
On entry, FUN=value was an illegal value.
IFAIL=-2
On entry, N<0.
Input argument number value is invalid.
IFAIL=-4
On entry, argument LDA is invalid.
Constraint: LDA≥N.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

F01KAF uses the norm estimation routine F04ZDF to estimate a quantity γ, where γ ≤ K X 1 and K X 1 ∈ n-1 L X 1 , n L X 1 . For further details on the accuracy of norm estimation, see the documentation for F04ZDF.

8 Parallelism and Performance

F01KAF is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library. In these implementations, this routine may make calls to the user-supplied functions from within an OpenMP parallel region. Thus OpenMP directives within the user functions can only be used if you are compiling the user-supplied function and linking the executable in accordance with the instructions in the Users' Note for your implementation.
F01KAF makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

Approximately 6 n 2 of complex allocatable memory is required by the routine, in addition to the memory used by the underlying matrix function routines F01FCF, F01FJF or F01FKF.
F01KAF returns the matrix function f A. This is computed using F01FCF if FUN='EXP', F01FJF if FUN='LOG' and F01FKF otherwise. If only f A is required, without an estimate of the condition number, then it is far more efficient to use F01FCF, F01FJF or F01FKF directly.
F01JAF can be used to find the condition number of the exponential, logarithm, sine, cosine, sinh or cosh at a real matrix.

10 Example

This example estimates the absolute and relative condition numbers of the matrix sinh function for
A = 0.0+1.0 i -1.0+0.0 i 1.0+0.0 i 2.0+0.0 i 2.0+1.0 i 0.0-1.0 i 0.0+0.0 i 1.0+0.0 i 0.0+1.0 i 0.0+0.0 i 1.0+1.0 i 0.0+2.0 i 1.0+0.0 i 2.0+0.0 i -2.0+3.0 i 0.0+1.0 i .

10.1 Program Text

Program Text (f01kafe.f90)

10.2 Program Data

Program Data (f01kafe.d)

10.3 Program Results

Program Results (f01kafe.r)

F01 Chapter Contents
F01 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F01KBF : NAG Library, Mark 26

F01 Chapter Contents
F01 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F01KBF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F01KBF computes an estimate of the absolute condition number of a matrix function f of a complex n by n matrix A in the 1-norm. Numerical differentiation is used to evaluate the derivatives of f when they are required.

2 Specification

SUBROUTINE F01KBF ( N, A, LDA, F, IUSER, RUSER, IFLAG, CONDA, NORMA, NORMFA, IFAIL)
INTEGER | N, LDA, IUSER(*), IFLAG, IFAIL
REAL (KIND=nag_wp) | RUSER(*), CONDA, NORMA, NORMFA
COMPLEX (KIND=nag_wp) | A(LDA,*)
EXTERNAL | F

3 Description

The absolute condition number of f at A, condabs f,A is given by the norm of the Fréchet derivative of f, L A, which is defined by
L X := max E≠0 L X,E E ,
where L X,E is the Fréchet derivative in the direction E. L X,E is linear in E and can therefore be written as
vec L X,E = K X vec E ,
where the vec operator stacks the columns of a matrix into one vector, so that K X is n 2×n 2. F01KBF computes an estimate γ such that γ ≤ K X 1 , where K X 1 ∈ n-1 L X 1 , n L X 1 . The relative condition number can then be computed via
cond rel f,A = cond abs f,A A 1 f A 1 .
The algorithm used to find γ is detailed in Section 3.4 of Higham (2008).

4 References

Higham N J (2008) Functions of Matrices: Theory and Computation SIAM, Philadelphia, PA, USA

5 Arguments

1:   N – INTEGERInput
On entry: n, the order of the matrix A.
Constraint: N≥0.
2:   A LDA* – COMPLEX (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array A must be at least N.
On entry: the n by n matrix A.
On exit: the n by n matrix, f A.
3:   LDA – INTEGERInput
On entry: the first dimension of the array A as declared in the (sub)program from which F01KBF is called.
Constraint: LDA≥N.
4:   F – SUBROUTINE, supplied by the user.External Procedure
The subroutine F evaluates f zi at a number of points zi.
The specification of F is:
SUBROUTINE F ( IFLAG, NZ, Z, FZ, IUSER, RUSER)
INTEGER | IFLAG, NZ, IUSER(*)
REAL (KIND=nag_wp) | RUSER(*)
COMPLEX (KIND=nag_wp) | Z(NZ), FZ(NZ)
1:   IFLAG – INTEGERInput/Output
On entry: IFLAG will be zero.
On exit: IFLAG should either be unchanged from its entry value of zero, or may be set nonzero to indicate that there is a problem in evaluating the function f z; for instance f z may not be defined. If IFLAG is returned as nonzero then F01KBF will terminate the computation, with IFAIL=3.
2:   NZ – INTEGERInput
On entry: nz, the number of function values required.
3:   Z NZ – COMPLEX (KIND=nag_wp) arrayInput
On entry: the nz points z 1,z 2,…,z nz at which the function f is to be evaluated.
4:   FZ NZ – COMPLEX (KIND=nag_wp) arrayOutput
On exit: the nz function values. FZ i should return the value f zi, for i=1,2,…,nz.
5:   IUSER* – INTEGER arrayUser Workspace
6:   RUSER* – REAL (KIND=nag_wp) arrayUser Workspace
F is called with the arguments IUSER and RUSER as supplied to F01KBF. You are free to use the arrays IUSER and RUSER to supply information to F as an alternative to using COMMON global variables.
F must either be a module subprogram USEd by, or declared as EXTERNAL in, the (sub)program from which F01KBF is called. Arguments denoted as Input must not be changed by this procedure.
5:   IUSER* – INTEGER arrayUser Workspace
6:   RUSER* – REAL (KIND=nag_wp) arrayUser Workspace
IUSER and RUSER are not used by F01KBF, but are passed directly to F and may be used to pass information to this routine as an alternative to using COMMON global variables.
7:   IFLAG – INTEGEROutput
On exit: IFLAG=0, unless IFLAG has been set nonzero inside F, in which case IFLAG will be the value set and IFAIL will be set to IFAIL=3.
8:   CONDA – REAL (KIND=nag_wp)Output
On exit: an estimate of the absolute condition number of f at A.
9:   NORMA – REAL (KIND=nag_wp)Output
On exit: the 1-norm of A.
10:   NORMFA – REAL (KIND=nag_wp)Output
On exit: the 1-norm of f A.
11:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
An internal error occurred when estimating the norm of the Fréchet derivative of f at A. Please contact NAG.
IFAIL=2
An internal error occurred while evaluating the matrix function f A. You can investigate further by calling F01FLF with the matrix A and the function f.
IFAIL=3
IFLAG has been set nonzero by the user-supplied subroutine.
IFAIL=-1
On entry, N<0.
IFAIL=-3
On entry, argument LDA is invalid.
Constraint: LDA≥N.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

F01KBF uses the norm estimation routine F04ZDF to estimate a quantity γ, where γ ≤ K X 1 and K X 1 ∈ n-1 L X 1 , n L X 1 . For further details on the accuracy of norm estimation, see the documentation for F04ZDF.

8 Parallelism and Performance

F01KBF is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library. In these implementations, this routine may make calls to the user-supplied functions from within an OpenMP parallel region. Thus OpenMP directives within the user functions can only be used if you are compiling the user-supplied function and linking the executable in accordance with the instructions in the Users' Note for your implementation. The user workspace arrays IUSER and RUSER are classified as OpenMP shared memory and use of IUSER and RUSER has to take account of this in order to preserve thread safety whenever information is written back to either of these arrays. If at all possible, it is recommended that these arrays are only used to supply read-only data to the user functions when a multithreaded implementation is being used.
F01KBF makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

Approximately 6 n 2 of complex allocatable memory is required by the routine, in addition to the memory used by the underlying matrix function routine F01FLF.
F01KBF returns the matrix function f A. This is computed using F01FLF. If only f A is required, without an estimate of the condition number, then it is far more efficient to use F01FLF directly.
The real analogue of this routine is F01JBF.

10 Example

This example estimates the absolute and relative condition numbers of the matrix function sin⁡2 A where
A = 2.0+0.0 i 0.0+1.0 i 1.0+1.0 i 0.0+3.0 i 1.0+1.0 i 0.0+2.0 i 2.0+2.0 i 0.0+0.0 i 0.0+0.0 i 2.0+0.0 i 1.0+2.0 i 1.0+0.0 i 1.0+1.0 i 3.0+0.0 i 0.0+0.0 i 1.0+2.0 i .

10.1 Program Text

Program Text (f01kbfe.f90)

10.2 Program Data

Program Data (f01kbfe.d)

10.3 Program Results

Program Results (f01kbfe.r)

F01 Chapter Contents
F01 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F01KCF : NAG Library, Mark 26

F01 Chapter Contents
F01 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F01KCF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F01KCF computes an estimate of the absolute condition number of a matrix function f of a complex n by n matrix A in the 1-norm, using analytical derivatives of f you have supplied.

2 Specification

SUBROUTINE F01KCF ( N, A, LDA, F, IUSER, RUSER, IFLAG, CONDA, NORMA, NORMFA, IFAIL)
INTEGER | N, LDA, IUSER(*), IFLAG, IFAIL
REAL (KIND=nag_wp) | RUSER(*), CONDA, NORMA, NORMFA
COMPLEX (KIND=nag_wp) | A(LDA,*)
EXTERNAL | F

3 Description

The absolute condition number of f at A, condabs f,A is given by the norm of the Fréchet derivative of f, L A, which is defined by
L X := max E≠0 L X,E E ,
where L X,E is the Fréchet derivative in the direction E. L X,E is linear in E and can therefore be written as
vec L X,E = K X vec E ,
where the vec operator stacks the columns of a matrix into one vector, so that K X is n 2×n 2. F01KCF computes an estimate γ such that γ ≤ K X 1 , where K X 1 ∈ n-1 L X 1 , n L X 1 . The relative condition number can then be computed via
cond rel f,A = cond abs f,A A 1 f A 1 .
The algorithm used to find γ is detailed in Section 3.4 of Higham (2008).

4 References

Higham N J (2008) Functions of Matrices: Theory and Computation SIAM, Philadelphia, PA, USA

5 Arguments

1:   N – INTEGERInput
On entry: n, the order of the matrix A.
Constraint: N≥0.
2:   A LDA* – COMPLEX (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array A must be at least N.
On entry: the n by n matrix A.
On exit: the n by n matrix, f A.
3:   LDA – INTEGERInput
On entry: the first dimension of the array A as declared in the (sub)program from which F01KCF is called.
Constraint: LDA≥N.
4:   F – SUBROUTINE, supplied by the user.External Procedure
Given an integer m, the subroutine F evaluates f m zi at a number of points zi.
The specification of F is:
SUBROUTINE F ( M, IFLAG, NZ, Z, FZ, IUSER, RUSER)
INTEGER | M, IFLAG, NZ, IUSER(*)
REAL (KIND=nag_wp) | RUSER(*)
COMPLEX (KIND=nag_wp) | Z(NZ), FZ(NZ)
1:   M – INTEGERInput
On entry: the order, m, of the derivative required.
If M=0, f zi should be returned. For M>0, f m zi should be returned.
2:   IFLAG – INTEGERInput/Output
On entry: IFLAG will be zero.
On exit: IFLAG should either be unchanged from its entry value of zero, or may be set nonzero to indicate that there is a problem in evaluating the function f z; for instance f z may not be defined. If IFLAG is returned as nonzero then F01KCF will terminate the computation, with IFAIL=3.
3:   NZ – INTEGERInput
On entry: nz, the number of function or derivative values required.
4:   Z NZ – COMPLEX (KIND=nag_wp) arrayInput
On entry: the nz points z 1,z 2,…,z nz at which the function f is to be evaluated.
5:   FZ NZ – COMPLEX (KIND=nag_wp) arrayOutput
On exit: the nz function or derivative values. FZ i should return the value f m zi, for i=1,2,…,nz.
6:   IUSER* – INTEGER arrayUser Workspace
7:   RUSER* – REAL (KIND=nag_wp) arrayUser Workspace
F is called with the arguments IUSER and RUSER as supplied to F01KCF. You are free to use the arrays IUSER and RUSER to supply information to F as an alternative to using COMMON global variables.
F must either be a module subprogram USEd by, or declared as EXTERNAL in, the (sub)program from which F01KCF is called. Arguments denoted as Input must not be changed by this procedure.
5:   IUSER* – INTEGER arrayUser Workspace
6:   RUSER* – REAL (KIND=nag_wp) arrayUser Workspace
IUSER and RUSER are not used by F01KCF, but are passed directly to F and may be used to pass information to this routine as an alternative to using COMMON global variables.
7:   IFLAG – INTEGEROutput
On exit: IFLAG=0, unless IFLAG has been set nonzero inside F, in which case IFLAG will be the value set and IFAIL will be set to IFAIL=3.
8:   CONDA – REAL (KIND=nag_wp)Output
On exit: an estimate of the absolute condition number of f at A.
9:   NORMA – REAL (KIND=nag_wp)Output
On exit: the 1-norm of A.
10:   NORMFA – REAL (KIND=nag_wp)Output
On exit: the 1-norm of f A.
11:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
An internal error occurred when estimating the norm of the Fréchet derivative of f at A. Please contact NAG.
IFAIL=2
An internal error occurred when evaluating the matrix function f A. You can investigate further by calling F01FMF with the matrix A and the function f.
IFAIL=3
IFLAG has been set nonzero by the user-supplied subroutine.
IFAIL=-1
On entry, N<0.
IFAIL=-3
On entry, argument LDA is invalid.
Constraint: LDA≥N.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

F01KCF uses the norm estimation routine F04ZDF to estimate a quantity γ, where γ ≤ K X 1 and K X 1 ∈ n-1 L X 1 , n L X 1 . For further details on the accuracy of norm estimation, see the documentation for F04ZDF.

8 Parallelism and Performance

F01KCF is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library. In these implementations, this routine may make calls to the user-supplied functions from within an OpenMP parallel region. Thus OpenMP directives within the user functions can only be used if you are compiling the user-supplied function and linking the executable in accordance with the instructions in the Users' Note for your implementation. The user workspace arrays IUSER and RUSER are classified as OpenMP shared memory and use of IUSER and RUSER has to take account of this in order to preserve thread safety whenever information is written back to either of these arrays. If at all possible, it is recommended that these arrays are only used to supply read-only data to the user functions when a multithreaded implementation is being used.
F01KCF makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

Approximately 6 n 2 of complex allocatable memory is required by the routine, in addition to the memory used by the underlying matrix function routine F01FMF.
F01KCF returns the matrix function f A. This is computed using F01FMF. If only f A is required, without an estimate of the condition number, then it is far more efficient to use F01FMF directly.
The real analogue of this routine is F01JCF.

10 Example

This example estimates the absolute and relative condition numbers of the matrix function e 3 A where
A= 1.0+1.0 i 0.0+1.0 i 1.0+0.0 i 2.0+0.0 i 0.0+0.0 i 2.0+0.0 i 0.0+2.0 i 1.0+0.0 i 0.0+1.0 i 0.0+1.0 i 0.0+0.0 i 2.0+0.0 i 1.0+0.0 i 0.0+1.0 i 1.0+0.0 i 0.0+1.0 i .

10.1 Program Text

Program Text (f01kcfe.f90)

10.2 Program Data

Program Data (f01kcfe.d)

10.3 Program Results

Program Results (f01kcfe.r)

F01 Chapter Contents
F01 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F01KDF : NAG Library, Mark 26

F01 Chapter Contents
F01 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F01KDF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F01KDF computes an estimate of the relative condition number, κ A 1/2, and a bound on the relative residual, in the Frobenius norm, for the square root of a complex n by n matrix A. The principal square root, A 1/2, of A is also returned.

2 Specification

SUBROUTINE F01KDF ( N, A, LDA, ALPHA, CONDSA, IFAIL)
INTEGER | N, LDA, IFAIL
REAL (KIND=nag_wp) | ALPHA, CONDSA
COMPLEX (KIND=nag_wp) | A(LDA,*)

3 Description

For a matrix with no eigenvalues on the closed negative real line, the principal matrix square root, A 1/2, of A is the unique square root with eigenvalues in the right half-plane.
The Fréchet derivative of a matrix function A 1/2 in the direction of the matrix E is the linear function mapping E to L A,E such that
A+E 1/2 - A 1/2 - L A,E = o A .
The absolute condition number is given by the norm of the Fréchet derivative which is defined by
L A := max E≠0 L A,E E .
The Fréchet derivative is linear in E and can therefore be written as
vec L A,E = K A vec E ,
where the vec operator stacks the columns of a matrix into one vector, so that K A is n 2×n 2.
F01KDF uses Algorithm 3.20 from Higham (2008) to compute an estimate γ such that γ ≤ K X F . The quantity of γ provides a good approximation to L A F. The relative condition number, κ A 1/2, is then computed via
κ A 1/2 = L A F A F A 1/2 F .
κ A 1/2 is returned in the argument CONDSA.
A 1/2 is computed using the algorithm described in Higham (1987). This is a version of the algorithm of Björck and Hammarling (1983). In addition, a blocking scheme described in Deadman et al. (2013) is used.
The computed quantity α is a measure of the stability of the relative residual (see Section 7). It is computed via
α= A 1/2 F 2 A F .

4 References

Björck Å and Hammarling S (1983) A Schur method for the square root of a matrix Linear Algebra Appl. 52/53 127–140
Deadman E, Higham N J and Ralha R (2013) Blocked Schur Algorithms for Computing the Matrix Square Root Applied Parallel and Scientific Computing: 11th International Conference, (PARA 2012, Helsinki, Finland) P. Manninen and P. Öster, Eds Lecture Notes in Computer Science 7782 171–181 Springer–Verlag
Higham N J (1987) Computing real square roots of a real matrix Linear Algebra Appl. 88/89 405–430
Higham N J (2008) Functions of Matrices: Theory and Computation SIAM, Philadelphia, PA, USA

5 Arguments

1:   N – INTEGERInput
On entry: n, the order of the matrix A.
Constraint: N≥0.
2:   A LDA* – COMPLEX (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array A must be at least N.
On entry: the n by n matrix A.
On exit: the n by n principal matrix square root A 1/2. Alternatively, if IFAIL=1, contains an n by n non-principal square root of A.
3:   LDA – INTEGERInput
On entry: the first dimension of the array A as declared in the (sub)program from which F01KDF is called.
Constraint: LDA≥N.
4:   ALPHA – REAL (KIND=nag_wp)Output
On exit: an estimate of the stability of the relative residual for the computed principal (if IFAIL=0) or non-principal (if IFAIL=1) matrix square root, α.
5:   CONDSA – REAL (KIND=nag_wp)Output
On exit: an estimate of the relative condition number, in the Frobenius norm, of the principal (if IFAIL=0) or non-principal (if IFAIL=1) matrix square root at A, κ A 1/2.
6:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
A has a negative or semisimple vanishing eigenvalue. A non-principal square root was returned.
IFAIL=2
A has a defective vanishing eigenvalue. The square root and condition number cannot be found in this case.
IFAIL=3
An error occurred when computing the matrix square root. Consequently, ALPHA and CONDSA could not be computed. It is likely that the routine was called incorrectly.
IFAIL=4
An error occurred when computing the condition number. The matrix square root was still returned but you should use F01FNF to check if it is the principal matrix square root.
IFAIL=-1
On entry, N=value.
Constraint: N≥0.
IFAIL=-3
On entry, LDA=value and N=value.
Constraint: LDA≥N.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

If the computed square root is X~, then the relative residual
A - X~2 F A F ,
is bounded approximately by nαε, where ε is machine precision. The relative error in X~ is bounded approximately by nα κ A 1/2 ε.

8 Parallelism and Performance

F01KDF is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
F01KDF makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

Approximately 3×n 2 of complex allocatable memory is required by the routine.
The cost of computing the matrix square root is 85 n 3/3 floating-point operations. The cost of computing the condition number depends on how fast the algorithm converges. It typically takes over twice as long as computing the matrix square root.
If condition estimates are not required then it is more efficient to use F01FNF to obtain the matrix square root alone. Condition estimates for the square root of a real matrix can be obtained via F01JDF.

10 Example

This example estimates the matrix square root and condition number of the matrix
A = 29+35 i 31+61 i -38+49 i -17-0 6 i 52-59 i 58-29 i 97+39 i -32+15 i 20-31 i 44-00 i 37+19 i -26+19 i -70+72 i -90+0 8 i -87-43 i 47-0 5 i .

10.1 Program Text

Program Text (f01kdfe.f90)

10.2 Program Data

Program Data (f01kdfe.d)

10.3 Program Results

Program Results (f01kdfe.r)

F01 Chapter Contents
F01 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F01KEF : NAG Library, Mark 26

F01 Chapter Contents
F01 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F01KEF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F01KEF computes an estimate of the relative condition number κ Ap of the pth power (where p is real) of a complex n by n matrix A, in the 1-norm. The principal matrix power Ap is also returned.

2 Specification

SUBROUTINE F01KEF ( N, A, LDA, P, CONDPA, IFAIL)
INTEGER | N, LDA, IFAIL
REAL (KIND=nag_wp) | P, CONDPA
COMPLEX (KIND=nag_wp) | A(LDA,*)

3 Description

For a matrix A with no eigenvalues on the closed negative real line, Ap (p∈ℝ) can be defined as
Ap= exp p log A
where log A is the principal logarithm of A (the unique logarithm whose spectrum lies in the strip z:-π<Im z<π).
The Fréchet derivative of the matrix pth power of A is the unique linear mapping E⟼L A,E such that for any matrix E
A+E p - Ap - L A,E = o E .
The derivative describes the first-order effect of perturbations in A on the matrix power Ap.
The relative condition number of the matrix pth power can be defined by
κ Ap = L A A Ap ,
where L A is the norm of the Fréchet derivative of the matrix power at A.
F01KEF uses the algorithms of Higham and Lin (2011) and Higham and Lin (2013) to compute κ Ap and Ap. The real number p is expressed as p=q+r where q∈-1,1 and r∈ℤ. Then Ap=AqAr. The integer power Ar is found using a combination of binary powering and, if necessary, matrix inversion. The fractional power Aq is computed using a Schur decomposition, a Padé approximant and the scaling and squaring method.
To obtain the estimate of κ Ap, F01KEF first estimates L A by computing an estimate γ of a quantity K∈n-1 L A 1,n L A 1, such that γ≤K. This requires multiple Fréchet derivatives to be computed. Fréchet derivatives of Aq are obtained by differentiating the Padé approximant. Fréchet derivatives of Ap are then computed using a combination of the chain rule and the product rule for Fréchet derivatives.
If A is nonsingular but has negative real eigenvalues F01KEF will return a non-principal matrix pth power and its condition number.

4 References

Higham N J (2008) Functions of Matrices: Theory and Computation SIAM, Philadelphia, PA, USA
Higham N J and Lin L (2011) A Schur–Padé algorithm for fractional powers of a matrix SIAM J. Matrix Anal. Appl. 32(3) 1056–1078
Higham N J and Lin L (2013) An improved Schur–Padé algorithm for fractional powers of a matrix and their Fréchet derivatives SIAM J. Matrix Anal. Appl. 34(3) 1341–1360

5 Arguments

1:   N – INTEGERInput
On entry: n, the order of the matrix A.
Constraint: N≥0.
2:   A LDA* – COMPLEX (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array A must be at least N.
On entry: the n by n matrix A.
On exit: the n by n principal matrix pth power, Ap, unless IFAIL=1, in which case a non-principal pth power is returned.
3:   LDA – INTEGERInput
On entry: the first dimension of the array A as declared in the (sub)program from which F01KEF is called.
Constraint: LDA≥N.
4:   P – REAL (KIND=nag_wp)Input
On entry: the required power of A.
5:   CONDPA – REAL (KIND=nag_wp)Output
On exit: if IFAIL=0 or 3, an estimate of the relative condition number of the matrix pth power, κ Ap. Alternatively, if IFAIL=4, the absolute condition number of the matrix pth power.
6:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
A has eigenvalues on the negative real line. The principal pth power is not defined in this case, so a non-principal power was returned.
IFAIL=2
A is singular so the pth power cannot be computed.
IFAIL=3
Ap has been computed using an IEEE double precision Padé approximant, although the arithmetic precision is higher than IEEE double precision.
IFAIL=4
The relative condition number is infinite. The absolute condition number was returned instead.
IFAIL=5
An unexpected internal error occurred. This failure should not occur and suggests that the routine has been called incorrectly.
IFAIL=-1
On entry, N=value.
Constraint: N≥0.
IFAIL=-3
On entry, LDA=value and N=value.
Constraint: LDA≥N.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

F01KEF uses the norm estimation routine F04ZDF to produce an estimate γ of a quantity K∈n-1 L A 1,n L A 1, such that γ≤K. For further details on the accuracy of norm estimation, see the documentation for F04ZDF.
For a normal matrix A (for which AH A=A AH), the Schur decomposition is diagonal and the computation of the fractional part of the matrix power reduces to evaluating powers of the eigenvalues of A and then constructing Ap using the Schur vectors. This should give a very accurate result. In general, however, no error bounds are available for the algorithm. See Higham and Lin (2011) and Higham and Lin (2013) for details and further discussion.

8 Parallelism and Performance

F01KEF is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
F01KEF makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The amount of complex allocatable memory required by the algorithm is typically of the order 10×n 2.
The cost of the algorithm is O n 3 floating-point operations; see Higham and Lin (2013).
If the matrix pth power alone is required, without an estimate of the condition number, then F01FQF should be used. If the Fréchet derivative of the matrix power is required then F01KFF should be used. The real analogue of this routine is F01JEF.

10 Example

This example estimates the relative condition number of the matrix power Ap, where p=0.4 and
A = 1+2 i 3 2 1+3 i 1+i 1 1 2+i 1 2 1 2 i 3 i 2+i 1 .

10.1 Program Text

Program Text (f01kefe.f90)

10.2 Program Data

Program Data (f01kefe.d)

10.3 Program Results

Program Results (f01kefe.r)

F01 Chapter Contents
F01 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F01KFF : NAG Library, Mark 26

F01 Chapter Contents
F01 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F01KFF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F01KFF computes the Fréchet derivative L A,E of the pth power (where p is real) of the complex n by n matrix A applied to the complex n by n matrix E. The principal matrix power Ap is also returned.

2 Specification

SUBROUTINE F01KFF ( N, A, LDA, E, LDE, P, IFAIL)
INTEGER | N, LDA, LDE, IFAIL
REAL (KIND=nag_wp) | P
COMPLEX (KIND=nag_wp) | A(LDA,*), E(LDE,*)

3 Description

For a matrix A with no eigenvalues on the closed negative real line, Ap (p∈ℝ) can be defined as
Ap= exp p log A
where log A is the principal logarithm of A (the unique logarithm whose spectrum lies in the strip z:-π<Im z<π). If A is nonsingular but has negative real eigenvalues, the principal logarithm is not defined, but a non-principal pth power can be defined by using a non-principal logarithm.
The Fréchet derivative of the matrix pth power of A is the unique linear mapping E⟼L A,E such that for any matrix E
A+E p - Ap - L A,E = o E .
The derivative describes the first-order effect of perturbations in A on the matrix power Ap.
F01KFF uses the algorithms of Higham and Lin (2011) and Higham and Lin (2013) to compute Ap and L A,E. The real number p is expressed as p=q+r where q∈-1,1 and r∈ℤ. Then Ap=AqAr. The integer power Ar is found using a combination of binary powering and, if necessary, matrix inversion. The fractional power Aq is computed using a Schur decomposition, a Padé approximant and the scaling and squaring method. The Padé approximant is differentiated in order to obtain the Fréchet derivative of Aq and L A,E is then computed using a combination of the chain rule and the product rule for Fréchet derivatives.

4 References

Higham N J (2008) Functions of Matrices: Theory and Computation SIAM, Philadelphia, PA, USA
Higham N J and Lin L (2011) A Schur–Padé algorithm for fractional powers of a matrix SIAM J. Matrix Anal. Appl. 32(3) 1056–1078
Higham N J and Lin L (2013) An improved Schur–Padé algorithm for fractional powers of a matrix and their Fréchet derivatives SIAM J. Matrix Anal. Appl. 34(3) 1341–1360

5 Arguments

1:   N – INTEGERInput
On entry: n, the order of the matrix A.
Constraint: N≥0.
2:   A LDA* – COMPLEX (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array A must be at least N.
On entry: the n by n matrix A.
On exit: the n by n principal matrix pth power, Ap. Alternatively if IFAIL=1, a non-principal pth power is returned.
3:   LDA – INTEGERInput
On entry: the first dimension of the array A as declared in the (sub)program from which F01KFF is called.
Constraint: LDA≥N.
4:   E LDE* – COMPLEX (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array E must be at least N.
On entry: the n by n matrix E.
On exit: the Fréchet derivative L A,E.
5:   LDE – INTEGERInput
On entry: the first dimension of the array E as declared in the (sub)program from which F01KFF is called.
Constraint: LDE≥N.
6:   P – REAL (KIND=nag_wp)Input
On entry: the required power of A.
7:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
A has eigenvalues on the negative real line. The principal pth power is not defined in this case, so a non-principal power was returned.
IFAIL=2
A is singular so the pth power cannot be computed.
IFAIL=3
Ap has been computed using an IEEE double precision Padé approximant, although the arithmetic precision is higher than IEEE double precision.
IFAIL=4
An unexpected internal error occurred. This failure should not occur and suggests that the routine has been called incorrectly.
IFAIL=-1
On entry, N=value.
Constraint: N≥0.
IFAIL=-3
On entry, LDA=value and N=value.
Constraint: LDA≥N.
IFAIL=-5
On entry, LDE=value and N=value.
Constraint: LDE≥N.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

For a normal matrix A (for which AH A=A AH), the Schur decomposition is diagonal and the computation of the fractional part of the matrix power reduces to evaluating powers of the eigenvalues of A and then constructing Ap using the Schur vectors. This should give a very accurate result. In general, however, no error bounds are available for the algorithm. See Higham and Lin (2011) and Higham and Lin (2013) for details and further discussion.
If the condition number of the matrix power is required then F01KEF should be used.

8 Parallelism and Performance

F01KFF is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
F01KFF makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The complex allocatable memory required by the algorithm is approximately 6×n 2.
The cost of the algorithm is O n 3 floating-point operations; see Higham and Lin (2011) and Higham and Lin (2013).
If the matrix pth power alone is required, without the Fréchet derivative, then F01FQF should be used. If the condition number of the matrix power is required then F01KEF should be used. The real analogue of this routine is F01JFF.

10 Example

This example finds Ap and the Fréchet derivative of the matrix power L A,E, where p=0.2,
A = 2 i+ 3 i+0 2 i+0 1+3 i 2+i 1 i+0 1 i+0 2+0 i 0+i 2+2 i 0+2 i 0+4 i 3 i+ 0+0 i 3 i+0 1 i+0   and   E = 0+i 3 i+0 2 i+0 1+3 i 0+i 1 i+0 3+3 i 0+0 i 0+i 2+2 i 0+2 i 0 i+0 2 i+ 0+0 i 1 i+0 1 i+0 .

10.1 Program Text

Program Text (f01kffe.f90)

10.2 Program Data

Program Data (f01kffe.d)

10.3 Program Results

Program Results (f01kffe.r)

F01 Chapter Contents
F01 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F01KGF : NAG Library, Mark 26

F01 Chapter Contents
F01 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F01KGF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F01KGF computes an estimate of the relative condition number κexp A of the exponential of a complex n by n matrix A, in the 1-norm. The matrix exponential eA is also returned.

2 Specification

SUBROUTINE F01KGF ( N, A, LDA, CONDEA, IFAIL)
INTEGER | N, LDA, IFAIL
REAL (KIND=nag_wp) | CONDEA
COMPLEX (KIND=nag_wp) | A(LDA,*)

3 Description

The Fréchet derivative of the matrix exponential of A is the unique linear mapping E⟼L A,E such that for any matrix E
e A+E - e A - L A,E = o E .
The derivative describes the first-order effect of perturbations in A on the exponential eA.
The relative condition number of the matrix exponential can be defined by
κexp A = L A A exp A ,
where L A is the norm of the Fréchet derivative of the matrix exponential at A.
To obtain the estimate of κexp A, F01KGF first estimates L A by computing an estimate γ of a quantity K∈n-1 L A 1,n L A 1, such that γ≤K.
The algorithms used to compute κexp A are detailed in the Al–Mohy and Higham (2009a) and Al–Mohy and Higham (2009b).
The matrix exponential eA is computed using a Padé approximant and the scaling and squaring method. The Padé approximant is differentiated to obtain the Fréchet derivatives L A,E which are used to estimate the condition number.

4 References

Al–Mohy A H and Higham N J (2009a) A new scaling and squaring algorithm for the matrix exponential SIAM J. Matrix Anal. 31(3) 970–989
Al–Mohy A H and Higham N J (2009b) Computing the Fréchet derivative of the matrix exponential, with an application to condition number estimation SIAM J. Matrix Anal. Appl. 30(4) 1639–1657
Higham N J (2008) Functions of Matrices: Theory and Computation SIAM, Philadelphia, PA, USA
Moler C B and Van Loan C F (2003) Nineteen dubious ways to compute the exponential of a matrix, twenty-five years later SIAM Rev. 45 3–49

5 Arguments

1:   N – INTEGERInput
On entry: n, the order of the matrix A.
Constraint: N≥0.
2:   A LDA* – COMPLEX (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array A must be at least N.
On entry: the n by n matrix A.
On exit: the n by n matrix exponential eA.
3:   LDA – INTEGERInput
On entry: the first dimension of the array A as declared in the (sub)program from which F01KGF is called.
Constraint: LDA≥N.
4:   CONDEA – REAL (KIND=nag_wp)Output
On exit: an estimate of the relative condition number of the matrix exponential κexp A.
5:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
The linear equations to be solved for the Padé approximant are singular; it is likely that this routine has been called incorrectly.
IFAIL=2
eA has been computed using an IEEE double precision Padé approximant, although the arithmetic precision is higher than IEEE double precision.
IFAIL=3
An unexpected internal error has occurred. Please contact NAG.
IFAIL=-1
On entry, N=value.
Constraint: N≥0.
IFAIL=-3
On entry, LDA=value and N=value.
Constraint: LDA≥N.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

F01KGF uses the norm estimation routine F04ZDF to produce an estimate γ of a quantity K∈n-1 L A 1,n L A 1, such that γ≤K. For further details on the accuracy of norm estimation, see the documentation for F04ZDF.
For a normal matrix A (for which AH A=A AH) the computed matrix, eA, is guaranteed to be close to the exact matrix, that is, the method is forward stable. No such guarantee can be given for non-normal matrices. See Section 10.3 of Higham (2008) for details and further discussion.
For further discussion of the condition of the matrix exponential see Section 10.2 of Higham (2008).

8 Parallelism and Performance

F01KGF is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
F01KGF makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

F01KAF uses a similar algorithm to F01KGF to compute an estimate of the absolute condition number (which is related to the relative condition number by a factor of A/exp A). However, the required Fréchet derivatives are computed in a more efficient and stable manner by F01KGF and so its use is recommended over F01KAF.
The cost of the algorithm is O n 3 and the complex allocatable memory required is approximately 15 n 2; see Al–Mohy and Higham (2009a) and Al–Mohy and Higham (2009b) for further details.
If the matrix exponential alone is required, without an estimate of the condition number, then F01FCF should be used. If the Fréchet derivative of the matrix exponential is required then F01KHF should be used.
As well as the excellent book Higham (2008), the classic reference for the computation of the matrix exponential is Moler and Van Loan (2003).

10 Example

This example estimates the relative condition number of the matrix exponential eA, where
A = 1+0 i 2+0 i 2+0 i 2+i 3+2 i 1 i+0 1 i+0 2+i 3+2 i 2+0 i 1 i+0 2+i 3+2 i 3+2 i 3+2 i 1+i .

10.1 Program Text

Program Text (f01kgfe.f90)

10.2 Program Data

Program Data (f01kgfe.d)

10.3 Program Results

Program Results (f01kgfe.r)

F01 Chapter Contents
F01 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F01KHF : NAG Library, Mark 26

F01 Chapter Contents
F01 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F01KHF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F01KHF computes the Fréchet derivative L A,E of the matrix exponential of a complex n by n matrix A applied to the complex n by n matrix E. The matrix exponential eA is also returned.

2 Specification

SUBROUTINE F01KHF ( N, A, LDA, E, LDE, IFAIL)
INTEGER | N, LDA, LDE, IFAIL
COMPLEX (KIND=nag_wp) | A(LDA,*), E(LDE,*)

3 Description

The Fréchet derivative of the matrix exponential of A is the unique linear mapping E⟼L A,E such that for any matrix E
e A+E - e A - L A,E = o E .
The derivative describes the first-order effect of perturbations in A on the exponential eA.
F01KHF uses the algorithms of Al–Mohy and Higham (2009a) and Al–Mohy and Higham (2009b) to compute eA and L A,E. The matrix exponential eA is computed using a Padé approximant and the scaling and squaring method. The Padé approximant is then differentiated in order to obtain the Fréchet derivative L A,E.

4 References

Al–Mohy A H and Higham N J (2009a) A new scaling and squaring algorithm for the matrix exponential SIAM J. Matrix Anal. 31(3) 970–989
Al–Mohy A H and Higham N J (2009b) Computing the Fréchet derivative of the matrix exponential, with an application to condition number estimation SIAM J. Matrix Anal. Appl. 30(4) 1639–1657
Higham N J (2008) Functions of Matrices: Theory and Computation SIAM, Philadelphia, PA, USA
Moler C B and Van Loan C F (2003) Nineteen dubious ways to compute the exponential of a matrix, twenty-five years later SIAM Rev. 45 3–49

5 Arguments

1:   N – INTEGERInput
On entry: n, the order of the matrix A.
Constraint: N≥0.
2:   A LDA* – COMPLEX (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array A must be at least N.
On entry: the n by n matrix A.
On exit: the n by n matrix exponential eA.
3:   LDA – INTEGERInput
On entry: the first dimension of the array A as declared in the (sub)program from which F01KHF is called.
Constraint: LDA≥N.
4:   E LDE* – COMPLEX (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array E must be at least N.
On entry: the n by n matrix E
On exit: the Fréchet derivative L A,E
5:   LDE – INTEGERInput
On entry: the first dimension of the array E as declared in the (sub)program from which F01KHF is called.
Constraint: LDE≥N.
6:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
The linear equations to be solved for the Padé approximant are singular; it is likely that this routine has been called incorrectly.
IFAIL=2
eA has been computed using an IEEE double precision Padé approximant, although the arithmetic precision is higher than IEEE double precision.
IFAIL=3
An unexpected internal error has occurred. Please contact NAG.
IFAIL=-1
On entry, N=value.
Constraint: N≥0.
IFAIL=-3
On entry, LDA=value and N=value.
Constraint: LDA≥N.
IFAIL=-5
On entry, LDE=value and N=value.
Constraint: LDE≥N.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

For a normal matrix A (for which AH A=A AH) the computed matrix, eA, is guaranteed to be close to the exact matrix, that is, the method is forward stable. No such guarantee can be given for non-normal matrices. See Section 10.3 of Higham (2008), Al–Mohy and Higham (2009a) and Al–Mohy and Higham (2009b) for details and further discussion.

8 Parallelism and Performance

F01KHF is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
F01KHF makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The cost of the algorithm is O n 3 and the complex allocatable memory required is approximately 9 n 2; see Al–Mohy and Higham (2009a) and Al–Mohy and Higham (2009b).
If the matrix exponential alone is required, without the Fréchet derivative, then F01FCF should be used.
If the condition number of the matrix exponential is required then F01KGF should be used.
As well as the excellent book Higham (2008), the classic reference for the computation of the matrix exponential is Moler and Van Loan (2003).

10 Example

This example finds the matrix exponential eA and the Fréchet derivative L A,E, where
A = 1+0 i 2+0 i 2+0 i 2+i 3+2 i 1 i+0 1 i+0 2+i 3+2 i 2+0 i 1 i+0 2+i 3+2 i 3+2 i 3+2 i 1+i   and   E = 1 i+0 2+0 i 2 i+0 4+i 3+2 i 0 i+0 1 i+0 0+i 0+2 i 0+0 i 1 i+0 0 i+ 1+0 i 2+2 i 0+3 i 1 i+ .

10.1 Program Text

Program Text (f01khfe.f90)

10.2 Program Data

Program Data (f01khfe.d)

10.3 Program Results

Program Results (f01khfe.r)

F01 Chapter Contents
F01 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F01KJF : NAG Library, Mark 26

F01 Chapter Contents
F01 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F01KJF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F01KJF computes an estimate of the relative condition number κlog A of the logarithm of a complex n by n matrix A, in the 1-norm. The principal matrix logarithm log A is also returned.

2 Specification

SUBROUTINE F01KJF ( N, A, LDA, CONDLA, IFAIL)
INTEGER | N, LDA, IFAIL
REAL (KIND=nag_wp) | CONDLA
COMPLEX (KIND=nag_wp) | A(LDA,*)

3 Description

For a matrix with no eigenvalues on the closed negative real line, the principal matrix logarithm log A is the unique logarithm whose spectrum lies in the strip z:-π<Im⁡z<π.
The Fréchet derivative of the matrix logarithm of A is the unique linear mapping E⟼L A,E such that for any matrix E
log A+E - log A - L A,E = o E .
The derivative describes the first order effect of perturbations in A on the logarithm log A.
The relative condition number of the matrix logarithm can be defined by
κlog A = L A A log A ,
where L A is the norm of the Fréchet derivative of the matrix logarithm at A.
To obtain the estimate of κlog A, F01KJF first estimates L A by computing an estimate γ of a quantity K∈n-1 L A 1,n L A 1, such that γ≤K.
The algorithms used to compute κlog A and log A are based on a Schur decomposition, the inverse scaling and squaring method and Padé approximants. Further details can be found in Al–Mohy and Higham (2011) and Al–Mohy et al. (2012).
If A is nonsingular but has negative real eigenvalues, the principal logarithm is not defined, but F01KJF will return a non-principal logarithm and its condition number.

4 References

Al–Mohy A H and Higham N J (2011) Improved inverse scaling and squaring algorithms for the matrix logarithm SIAM J. Sci. Comput. 34(4) C152–C169
Al–Mohy A H, Higham N J and Relton S D (2012) Computing the Fréchet derivative of the matrix logarithm and estimating the condition number SIAM J. Sci. Comput. 35(4) C394–C410
Higham N J (2008) Functions of Matrices: Theory and Computation SIAM, Philadelphia, PA, USA

5 Arguments

1:   N – INTEGERInput
On entry: n, the order of the matrix A.
Constraint: N≥0.
2:   A LDA* – COMPLEX (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array A must be at least N.
On entry: the n by n matrix A.
On exit: the n by n principal matrix logarithm, log A. Alternatively, if IFAIL=2, a non-principal logarithm is returned.
3:   LDA – INTEGERInput
On entry: the first dimension of the array A as declared in the (sub)program from which F01KJF is called.
Constraint: LDA≥N.
4:   CONDLA – REAL (KIND=nag_wp)Output
On exit: with IFAIL=0, 2 or 3, an estimate of the relative condition number of the matrix logarithm, κlog A. Alternatively, if IFAIL=4, contains the absolute condition number of the matrix logarithm.
5:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
A is singular so the logarithm cannot be computed.
IFAIL=2
A has eigenvalues on the negative real line. The principal logarithm is not defined in this case, so a non-principal logarithm was returned.
IFAIL=3
log A has been computed using an IEEE double precision Padé approximant, although the arithmetic precision is higher than IEEE double precision.
IFAIL=4
The relative condition number is infinite. The absolute condition number was returned instead.
IFAIL=5
An unexpected internal error occurred. This failure should not occur and suggests that the routine has been called incorrectly.
IFAIL=-1
On entry, N=value.
Constraint: N≥0.
IFAIL=-3
On entry, LDA=value and N=value.
Constraint: LDA≥N.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

F01KJF uses the norm estimation routine F04ZDF to produce an estimate γ of a quantity K∈n-1 L A 1,n L A 1, such that γ≤K. For further details on the accuracy of norm estimation, see the documentation for F04ZDF.
For a normal matrix A (for which AH A=A AH), the Schur decomposition is diagonal and the computation of the matrix logarithm reduces to evaluating the logarithm of the eigenvalues of A and then constructing log A using the Schur vectors. This should give a very accurate result. In general, however, no error bounds are available for the algorithm. The sensitivity of the computation of log A is worst when A has an eigenvalue of very small modulus or has a complex conjugate pair of eigenvalues lying close to the negative real axis. See Al–Mohy and Higham (2011) and Section 11.2 of Higham (2008) for details and further discussion.

8 Parallelism and Performance

F01KJF is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
F01KJF makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

F01KAF uses a similar algorithm to F01KJF to compute an estimate of the absolute condition number (which is related to the relative condition number by a factor of A/log A). However, the required Fréchet derivatives are computed in a more efficient and stable manner by F01KJF and so its use is recommended over F01KAF.
The amount of complex allocatable memory required by the algorithm is typically of the order 10 n 2.
The cost of the algorithm is O n 3 floating-point operations; see Al–Mohy et al. (2012).
If the matrix logarithm alone is required, without an estimate of the condition number, then F01FJF should be used. If the Fréchet derivative of the matrix logarithm is required then F01KKF should be used. The real analogue of this routine is F01JJF.

10 Example

This example estimates the relative condition number of the matrix logarithm log A, where
A = 3+2 i 1 1 1+2 i 0+2 i -4 0 0 1 -2 3+2 i 0+i 1 i 1 2+3 i .

10.1 Program Text

Program Text (f01kjfe.f90)

10.2 Program Data

Program Data (f01kjfe.d)

10.3 Program Results

Program Results (f01kjfe.r)

F01 Chapter Contents
F01 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F01KKF : NAG Library, Mark 26

F01 Chapter Contents
F01 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F01KKF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F01KKF computes the Fréchet derivative L A,E of the matrix logarithm of the complex n by n matrix A applied to the complex n by n matrix E. The principal matrix logarithm log A is also returned.

2 Specification

SUBROUTINE F01KKF ( N, A, LDA, E, LDE, IFAIL)
INTEGER | N, LDA, LDE, IFAIL
COMPLEX (KIND=nag_wp) | A(LDA,*), E(LDE,*)

3 Description

For a matrix with no eigenvalues on the closed negative real line, the principal matrix logarithm log A is the unique logarithm whose spectrum lies in the strip z:-π<Im⁡z<π.
The Fréchet derivative of the matrix logarithm of A is the unique linear mapping E⟼L A,E such that for any matrix E
log A+E - log A - L A,E = o E .
The derivative describes the first order effect of perturbations in A on the logarithm log A.
F01KKF uses the algorithm of Al–Mohy et al. (2012) to compute log A and L A,E. The principal matrix logarithm log A is computed using a Schur decomposition, a Padé approximant and the inverse scaling and squaring method. The Padé approximant is then differentiated in order to obtain the Fréchet derivative L A,E. If A is nonsingular but has negative real eigenvalues, the principal logarithm is not defined, but F01KKF will return a non-principal logarithm and Fréchet derivative.

4 References

Al–Mohy A H and Higham N J (2011) Improved inverse scaling and squaring algorithms for the matrix logarithm SIAM J. Sci. Comput. 34(4) C152–C169
Al–Mohy A H, Higham N J and Relton S D (2012) Computing the Fréchet derivative of the matrix logarithm and estimating the condition number SIAM J. Sci. Comput. 35(4) C394–C410
Higham N J (2008) Functions of Matrices: Theory and Computation SIAM, Philadelphia, PA, USA

5 Arguments

1:   N – INTEGERInput
On entry: n, the order of the matrix A.
Constraint: N≥0.
2:   A LDA* – COMPLEX (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array A must be at least N.
On entry: the n by n matrix A.
On exit: the n by n principal matrix logarithm, log A. Alterntively, if IFAIL=2, a non-principal logarithm is returned.
3:   LDA – INTEGERInput
On entry: the first dimension of the array A as declared in the (sub)program from which F01KKF is called.
Constraint: LDA≥N.
4:   E LDE* – COMPLEX (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array E must be at least N.
On entry: the n by n matrix E
On exit: with IFAIL=0, 2 or 3, the Fréchet derivative L A,E
5:   LDE – INTEGERInput
On entry: the first dimension of the array E as declared in the (sub)program from which F01KKF is called.
Constraint: LDE≥N.
6:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
A is singular so the logarithm cannot be computed.
IFAIL=2
A has eigenvalues on the negative real line. The principal logarithm is not defined in this case, so a non-principal logarithm was returned.
IFAIL=3
log A has been computed using an IEEE double precision Padé approximant, although the arithmetic precision is higher than IEEE double precision.
IFAIL=4
An unexpected internal error occurred. This failure should not occur and suggests that the routine has been called incorrectly.
IFAIL=-1
On entry, N=value.
Constraint: N≥0.
IFAIL=-3
On entry, LDA=value and N=value.
Constraint: LDA≥N.
IFAIL=-5
On entry, LDE=value and N=value.
Constraint: LDE≥N.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

For a normal matrix A (for which AH A=A AH), the Schur decomposition is diagonal and the computation of the matrix logarithm reduces to evaluating the logarithm of the eigenvalues of A and then constructing log A using the Schur vectors. This should give a very accurate result. In general, however, no error bounds are available for the algorithm. The sensitivity of the computation of log A and L A,E is worst when A has an eigenvalue of very small modulus or has a complex conjugate pair of eigenvalues lying close to the negative real axis. See Al–Mohy and Higham (2011), Al–Mohy et al. (2012) and Section 11.2 of Higham (2008) for details and further discussion.

8 Parallelism and Performance

F01KKF is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
F01KKF makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The cost of the algorithm is O n 3 floating-point operations. The complex allocatable memory required is approximately 5 n 2; see Al–Mohy et al. (2012) for further details.
If the matrix logarithm alone is required, without the Fréchet derivative, then F01FJF should be used. If the condition number of the matrix logarithm is required then F01KJF should be used. The real analogue of this routine is F01JKF.

10 Example

This example finds the principal matrix logarithm log A and the Fréchet derivative L A,E, where
A = 1+4 i 3 i 0 i 2 i+ 2 i 3 i+0 1 i+0 1+i 0 i 2+0 i 2 i+0 i 1+2 i 3+2 i 1+2 i 3+i   and   E = 1 i+0 1+2 i 2 i+0 2+i 1+3 i 0 i 1 i+0 0 i+ 2 i 4+0 i 1 i+0 1 i+ 1 i+0 2+2 i 3 i 1 i+ .

10.1 Program Text

Program Text (f01kkfe.f90)

10.2 Program Data

Program Data (f01kkfe.d)

10.3 Program Results

Program Results (f01kkfe.r)

F01 Chapter Contents
F01 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F01LEF : NAG Library, Mark 26

F01 Chapter Contents
F01 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F01LEF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F01LEF computes an LU factorization of a real tridiagonal matrix, using Gaussian elimination with partial pivoting.

2 Specification

SUBROUTINE F01LEF ( N, A, LAMBDA, B, C, TOL, D, IPIV, IFAIL)
INTEGER | N, IPIV(N), IFAIL
REAL (KIND=nag_wp) | A(N), LAMBDA, B(N), C(N), TOL, D(N)

3 Description

The matrix T-λI, where T is a real n by n tridiagonal matrix, is factorized as
T-λI=PLU,
where P is a permutation matrix, L is a unit lower triangular matrix with at most one nonzero subdiagonal element per column, and U is an upper triangular matrix with at most two nonzero superdiagonal elements per column.
The factorization is obtained by Gaussian elimination with partial pivoting and implicit row scaling.
An indication of whether or not the matrix T-λI is nearly singular is returned in the nth element of the array IPIV. If it is important that T-λI is nonsingular, as is usually the case when solving a system of tridiagonal equations, then it is strongly recommended that IPIV n is inspected on return from F01LEF. (See the argument IPIV and Section 9 for further details.)
The argument λ is included in the routine so that F01LEF may be used, in conjunction with F04LEF, to obtain eigenvectors of T by inverse iteration.

4 References

Wilkinson J H (1965) The Algebraic Eigenvalue Problem Oxford University Press, Oxford
Wilkinson J H and Reinsch C (1971) Handbook for Automatic Computation II, Linear Algebra Springer–Verlag

5 Arguments

1:   N – INTEGERInput
On entry: n, the order of the matrix T.
Constraint: N≥1.
2:   A N – REAL (KIND=nag_wp) arrayInput/Output
On entry: the diagonal elements of T.
On exit: the diagonal elements of the upper triangular matrix U.
3:   LAMBDA – REAL (KIND=nag_wp)Input
On entry: the scalar λ. F01LEF factorizes T-λI.
4:   B N – REAL (KIND=nag_wp) arrayInput/Output
On entry: the superdiagonal elements of T, stored in B 2 to B n; B 1 is not used.
On exit: the elements of the first superdiagonal of U, stored in B 2 to B n.
5:   C N – REAL (KIND=nag_wp) arrayInput/Output
On entry: the subdiagonal elements of T, stored in C 2 to C n; C 1 is not used.
On exit: the subdiagonal elements of L, stored in C 2 to C n.
6:   TOL – REAL (KIND=nag_wp)Input
On entry: a relative tolerance used to indicate whether or not the matrix (T-λI) is nearly singular. TOL should normally be chosen as approximately the largest relative error in the elements of T. For example, if the elements of T are correct to about 4 significant figures, then TOL should be set to about 5×10-4. See Section 9 for further details on how TOL is used. If TOL is supplied as less than ε, where ε is the machine precision, then the value ε is used in place of TOL.
7:   D N – REAL (KIND=nag_wp) arrayOutput
On exit: the elements of the second superdiagonal of U, stored in D 3 to D n; D 1 and D 2 are not used.
8:   IPIV N – INTEGER arrayOutput
On exit: details of the permutation matrix P. If an interchange occurred at the kth step of the elimination, then IPIV k=1, otherwise IPIV k=0. If a diagonal element of U is small, indicating that T-λI is nearly singular, then the element IPIV n is returned as positive. Otherwise IPIV n is returned as 0. See Section 9 for further details. If the application is such that it is important that T-λI is not nearly singular, then it is strongly recommended that IPIV n is inspected on return.
9:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, N<1.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

The computed factorization will satisfy the equation
PLU=T-λI+E,
where
E 1≤ 9×max i≥j l ij,l ij 2 ε T-λ I 1
where ε is the machine precision.

8 Parallelism and Performance

F01LEF makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The time taken by F01LEF is approximately proportional to n.
The factorization of a tridiagonal matrix proceeds in n-1 steps, each step eliminating one subdiagonal element of the tridiagonal matrix. In order to avoid small pivot elements and to prevent growth in the size of the elements of L, rows k and (k+1) will, if necessary, be interchanged at the kth step prior to the elimination.
The element IPIV n returns the smallest integer, j, for which
u jj≤T-λI j 1×TOL,
where T-λI j 1 denotes the sum of the absolute values of the jth row of the matrix (T-λI). If no such j exists, then IPIV n is returned as zero. If such a j exists, then u jj is small and hence (T-λI) is singular or nearly singular.
This routine may be followed by F04LEF to solve systems of tridiagonal equations. If you wish to solve single systems of tridiagonal equations you should be aware of F07CAF (DGTSV), which solves tridiagonal systems with a single call. F07CAF (DGTSV) requires less storage and will generally be faster than the combination of F01LEF and F04LEF, but no test for near singularity is included in F07CAF (DGTSV) and so it should only be used when the equations are known to be nonsingular.

10 Example

This example factorizes the tridiagonal matrix T where
T= 3.0 2.1 0 0 0 3.4 2.3 -1.0 0 0 0 3.6 -5.0 1.9 0 0 0 7.0 -0.9 8.0 0 0 0 -6.0 7.1
and then to solve the equations Tx=y, where
y= 2.7 -0.5 2.6 0.6 2.7
by a call to F04LEF. The example program sets TOL=5×10-5 and, of course, sets LAMBDA=0.

10.1 Program Text

Program Text (f01lefe.f90)

10.2 Program Data

Program Data (f01lefe.d)

10.3 Program Results

Program Results (f01lefe.r)

F01 Chapter Contents
F01 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F01LHF : NAG Library, Mark 26

F01 Chapter Contents
F01 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F01LHF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F01LHF factorizes a real almost block diagonal matrix.

2 Specification

SUBROUTINE F01LHF ( N, NBLOKS, BLKSTR, A, LENA, PIVOT, TOL, KPIVOT, IFAIL)
INTEGER | N, NBLOKS, BLKSTR(3,NBLOKS), LENA, PIVOT(N), KPIVOT, IFAIL
REAL (KIND=nag_wp) | A(LENA), TOL

3 Description

F01LHF factorizes a real almost block diagonal matrix, A, by row elimination with alternate row and column pivoting such that no ‘fill-in’ is produced. The code, which is derived from ARCECO described in Diaz et al. (1983), uses Level 1 and Level 2 BLAS. No three successive diagonal blocks may have columns in common and therefore the almost block diagonal matrix must have the form shown in the following diagram:
Figure 1
This routine may be followed by F04LHF, which is designed to solve sets of linear equations AX=B or AT X=B.

4 References

Diaz J C, Fairweather G and Keast P (1983) Fortran packages for solving certain almost block diagonal linear systems by modified alternate row and column elimination ACM Trans. Math. Software 9 358–375

5 Arguments

1:   N – INTEGERInput
On entry: n, the order of the matrix A.
Constraint: N>0.
2:   NBLOKS – INTEGERInput
On entry: n, the total number of blocks of the matrix A.
Constraint: 0<NBLOKS≤N.
3:   BLKSTR 3 NBLOKS – INTEGER arrayInput
On entry: information which describes the block structure of A as follows:
  • BLKSTR 1 k must contain the number of rows in the kth block, k=1,2,…,NBLOKS;
  • BLKSTR 2 k must contain the number of columns in the kth block, k=1,2,…,NBLOKS;
  • BLKSTR 3 k must contain the number of columns of overlap between the kth and k+1th blocks, k=1,2,…,NBLOKS-1. BLKSTR 3 NBLOKS need not be set.
The following conditions delimit the structure of A:
  • BLKSTR 1 k,BLKSTR 2 k>0,  k=1,2,…,NBLOKS,
  • BLKSTR 3 k≥0,   k=1,2,…,NBLOKS-1,
(there must be at least one column and one row in each block and a non-negative number of columns of overlap);
  • BLKSTR 3 k-1+BLKSTR 3 k≤BLKSTR 2 k,  k=2,3,…,NBLOKS-1,
(the total number of columns in overlaps in each block must not exceed the number of columns in that block);
  • BLKSTR 21≥BLKSTR 11,
  • BLKSTR 21 + ∑ k =2 j BLKSTR 2 k -BLKSTR 3 k -1 ≥ ∑ k =1 j BLKSTR 1 k , j=2,3,…,NBLOKS-1 ,
  • ∑k=1 j BLKSTR 2 k-BLKSTR 3 k≤∑k=1 j BLKSTR 1 k,  j=1,2,…,NBLOKS-1,
(the index of the first column of the overlap between the jth and j+1th blocks must be ≤ the index of the last row of the jth block, and the index of the last column of overlap must be ≥ the index of the last row of the jth block);
  • ∑ k =1 NBLOKS BLKSTR 1 k =n ,
  • BLKSTR 21 + ∑ k =2 NBLOKS BLKSTR 2 k -BLKSTR 3 k -1 =nk ,
(both the number of rows and the number of columns of A must equal n).
4:   A LENA – REAL (KIND=nag_wp) arrayInput/Output
On entry: the elements of the almost block diagonal matrix stored block by block, with each block stored column by column. The sizes of the blocks and the overlaps are defined by the argument BLKSTR.
If a rs is the first element in the kth block, then an arbitrary element a ij in the kth block must be stored in the array element:
A pk+ j-r mk+ i-s+1
where
pk=∑l= 1 k- 1 BLKSTR 1 l×BLKSTR 2 l
is the base address of the kth block, and
mk=BLKSTR 1 k
is the number of rows of the kth block.
See Section 9 for comments on scaling.
On exit: the factorized form of the matrix.
5:   LENA – INTEGERInput
On entry: the dimension of the array A as declared in the (sub)program from which F01LHF is called.
Constraint: LENA ≥ ∑ k =1 NBLOKS BLKSTR 1 k × BLKSTR 2 k .
6:   PIVOT N – INTEGER arrayOutput
On exit: details of the interchanges.
7:   TOL – REAL (KIND=nag_wp)Input/Output
On entry: a relative tolerance to be used to indicate whether or not the matrix is singular. For a discussion on how TOL is used see Section 9. If TOL is non-positive, then TOL is reset to 10 ε, where ε is the machine precision.
On exit: unchanged unless TOL≤0.0 on entry, in which case it is set to 10 ε.
8:   KPIVOT – INTEGEROutput
On exit: if IFAIL=2, KPIVOT contains the value k, where k is the first position on the diagonal of the matrix A where too small a pivot was detected. Otherwise KPIVOT is set to 0.
9:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, | N<1,
or | NBLOKS<1,
or | N<NBLOKS,
or | LENA is too small,
or | illegal values detected in BLKSTR.
IFAIL=2
The factorization has been completed, but a small pivot has been detected.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

The accuracy of F01LHF depends on the conditioning of the matrix A.

8 Parallelism and Performance

F01LHF makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

Singularity or near singularity in A is determined by the argument TOL. If the absolute value of any pivot is less than TOL×amax, where amax is the maximum absolute value of an element of A, then A is said to be singular. The position on the diagonal of A of the first of any such pivots is indicated by the argument KPIVOT. The factorization, and the test for near singularity, will be more accurate if before entry A is scaled so that the ∞-norms of the rows and columns of A are all of approximately the same order of magnitude. (The ∞-norm is the maximum absolute value of any element in the row or column.)

10 Example

This example solves the set of linear equations Ax=b where
A= -1.00 -0.98 -0.79 -0.15 -1.00 -0.25 -0.87 0.35 0.78 0.31 -0.85 0.89 -0.69 -0.98 -0.76 -0.82 0.12 -0.01 0.75 0.32 -1.00 -0.53 -0.83 -0.98 -0.58 0.04 0.87 0.38 -1.00 -0.21 -0.93 -0.84 0.37 -0.94 -0.96 -1.00 -0.99 -0.91 -0.28 -0.90 0.78 -0.93 -0.76 0.48 -0.87 -0.14 -1.00 -0.59 -0.99 0.21 -0.73 -0.48 -0.93 -0.91 0.10 -0.89 -0.68 -0.09 -0.58 -0.21 0.85 -0.39 0.79 -0.71 0.39 -0.99 -0.12 -0.75 0.17 -1.37 1.29 -1.59 1.10 -1.63 -1.01 -0.27 0.08 0.61 0.54 -0.41 0.16 -0.46 -0.67 0.56 -0.99 0.16 -0.16 0.98 -0.24 -0.41 0.40 -0.93 0.70 0.43 0.71 -0.97 -0.60 -0.30 0.18 -0.47 -0.98 -0.73 0.07 0.04 -0.25 -0.92 -0.52 -0.46 -0.58 -0.89 -0.94 -0.54 -1.00 -0.36
and
b= -2.92 -1.17 -1.30 -1.17 -2.10 -4.51 -1.71 -4.59 -4.19 -0.93 -3.31 0.52 -0.12 -0.05 -0.98 -2.07 -2.73 -1.95
The exact solution is
x=1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1 T.

10.1 Program Text

Program Text (f01lhfe.f90)

10.2 Program Data

Program Data (f01lhfe.d)

10.3 Program Results

Program Results (f01lhfe.r)

F01 Chapter Contents
F01 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F01MCF : NAG Library, Mark 26

F01 Chapter Contents
F01 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F01MCF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F01MCF computes the Cholesky factorization of a real symmetric positive definite variable-bandwidth matrix.

2 Specification

SUBROUTINE F01MCF ( N, A, LAL, NROW, AL, D, IFAIL)
INTEGER | N, LAL, NROW(N), IFAIL
REAL (KIND=nag_wp) | A(LAL), AL(LAL), D(N)

3 Description

F01MCF determines the unit lower triangular matrix L and the diagonal matrix D in the Cholesky factorization A=LD LT of a symmetric positive definite variable-bandwidth matrix A of order n. (Such a matrix is sometimes called a ‘sky-line’ matrix.)
The matrix A is represented by the elements lying within the envelope of its lower triangular part, that is, between the first nonzero of each row and the diagonal (see Section 10 for an example). The width NROW i of the ith row is the number of elements between the first nonzero element and the element on the diagonal, inclusive. Although, of course, any matrix possesses an envelope as defined, this routine is primarily intended for the factorization of symmetric positive definite matrices with an average bandwidth which is small compared with n (also see Section 9).
The method is based on the property that during Cholesky factorization there is no fill-in outside the envelope.
The determination of L and D is normally the first of two steps in the solution of the system of equations Ax=b. The remaining step, viz. the solution of LD LT x=b, may be carried out using F04MCF.

4 References

Jennings A (1966) A compact storage scheme for the solution of symmetric linear simultaneous equations Comput. J. 9 281–285
Wilkinson J H and Reinsch C (1971) Handbook for Automatic Computation II, Linear Algebra Springer–Verlag

5 Arguments

1:   N – INTEGERInput
On entry: n, the order of the matrix A.
Constraint: N≥1.
2:   A LAL – REAL (KIND=nag_wp) arrayInput
On entry: the elements within the envelope of the lower triangle of the positive definite symmetric matrix A, taken in row by row order. The following code assigns the matrix elements within the envelope to the correct elements of the array:
    K = 0
    DO 20 I = 1, N
       DO 10 J = I-NROW(I)+1, I
          K = K + 1
          A(K) = matrix (I,J)
 10    CONTINUE
 20 CONTINUE
See also Section 9.
3:   LAL – INTEGERInput
On entry: the dimension of the arrays A and AL as declared in the (sub)program from which F01MCF is called.
Constraint: LAL≥NROW 1+NROW 2+…+NROW n.
4:   NROW N – INTEGER arrayInput
On entry: NROW i must contain the width of row i of the matrix A, i.e., the number of elements between the first (leftmost) nonzero element and the element on the diagonal, inclusive.
Constraint: 1≤NROW i≤i, for i=1,2,…,n.
5:   AL LAL – REAL (KIND=nag_wp) arrayOutput
On exit: the elements within the envelope of the lower triangular matrix L, taken in row by row order. The envelope of L is identical to that of the lower triangle of A. The unit diagonal elements of L are stored explicitly. See also Section 9.
6:   D N – REAL (KIND=nag_wp) arrayOutput
On exit: the diagonal elements of the diagonal matrix D. Note that the determinant of A is equal to the product of these diagonal elements. If the value of the determinant is required it should not be determined by forming the product explicitly, because of the possibility of overflow or underflow. The logarithm of the determinant may safely be formed from the sum of the logarithms of the diagonal elements.
7:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, | N<1,
or | for some i, NROW i<1 or NROW i>i,
or | LAL<NROW 1+NROW 2+…+NROW N.
IFAIL=2
A is not positive definite, or this property has been destroyed by rounding errors. The factorization has not been completed.
IFAIL=3
A is not positive definite, or this property has been destroyed by rounding errors. The factorization has not been completed.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

If IFAIL=0 on exit, then the computed L and D satisfy the relation LD LT=A+F, where
F 2 ≤ k m 2 ε × maxi a ii
and
F 2 ≤ k m 2 ε × A 2 ,
where k is a constant of order unity, m is the largest value of NROW i, and ε is the machine precision. See pages 25–27 and 54–55 of Wilkinson and Reinsch (1971).

8 Parallelism and Performance

F01MCF is not threaded in any implementation.

9 Further Comments

The time taken by F01MCF is approximately proportional to the sum of squares of the values of NROW i.
The distribution of row widths may be very non-uniform without undue loss of efficiency. Moreover, the routine has been designed to be as competitive as possible in speed with routines designed for full or uniformly banded matrices, when applied to such matrices.
Unless otherwise stated in the Users' Note for your implementation, the routine may be called with the same actual array supplied for arguments A and AL, in which case L overwrites the lower triangle of A. However this is not standard Fortran and may not work in all implementations.

10 Example

This example obtains the Cholesky factorization of the symmetric matrix, whose lower triangle is:
1 2 5 0 3 13 0 0 0 16 5 14 18 8 55 0 0 0 24 17 77 .
For this matrix, the elements of NROW must be set to 1, 2, 2, 1, 5, 3, and the elements within the envelope must be supplied in row order as:
1, 2, 5, 3, 13, 16, 5, 14, 18, 8, 55, 24, 17, 77 .

10.1 Program Text

Program Text (f01mcfe.f90)

10.2 Program Data

Program Data (f01mcfe.d)

10.3 Program Results

Program Results (f01mcfe.r)

F01 Chapter Contents
F01 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F01QGF : NAG Library, Mark 26

F01 Chapter Contents
F01 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F01QGF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F01QGF reduces the m by n (m≤n) real upper trapezoidal matrix A to upper triangular form by means of orthogonal transformations.

2 Specification

SUBROUTINE F01QGF ( M, N, A, LDA, ZETA, IFAIL)
INTEGER | M, N, LDA, IFAIL
REAL (KIND=nag_wp) | A(LDA,*), ZETA(M)

3 Description

The m by n (m≤n) real upper trapezoidal matrix A given by
A= U X ,
where U is an m by m upper triangular matrix, is factorized as
A= R 0 PT,
where P is an n by n orthogonal matrix and R is an m by m upper triangular matrix.
P is given as a sequence of Householder transformation matrices
P=Pm⋯P 2P 1,
the m-k+1th transformation matrix, Pk, being used to introduce zeros into the kth row of A. Pk has the form
Pk= I 0 0 Tk ,
where
Tk=I-uk ukT, uk= ζk 0 zk ,
ζk is a scalar and zk is an (n-m) element vector. ζk and zk are chosen to annihilate the elements of the kth row of X.
The vector uk is returned in the kth element of the array ZETA and in the kth row of A, such that ζk is in ZETA k and the elements of zk are in A k m+1,…,A kn. The elements of R are returned in the upper triangular part of A.
For further information on this factorization and its use see Section 6.5 of Golub and Van Loan (1996).

4 References

Golub G H and Van Loan C F (1996) Matrix Computations (3rd Edition) Johns Hopkins University Press, Baltimore
Wilkinson J H (1965) The Algebraic Eigenvalue Problem Oxford University Press, Oxford

5 Arguments

1:   M – INTEGERInput
On entry: m, the number of rows of the matrix A.
When M=0 then an immediate return is effected.
Constraint: M≥0.
2:   N – INTEGERInput
On entry: n, the number of columns of the matrix A.
Constraint: N≥M.
3:   A LDA* – REAL (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array A must be at least max 1,N.
On entry: the leading m by n upper trapezoidal part of the array A must contain the matrix to be factorized.
On exit: the m by m upper triangular part of A will contain the upper triangular matrix R, and the m by n-m upper trapezoidal part of A will contain details of the factorization as described in Section 3.
4:   LDA – INTEGERInput
On entry: the first dimension of the array A as declared in the (sub)program from which F01QGF is called.
Constraint: LDA≥max 1,M.
5:   ZETA M – REAL (KIND=nag_wp) arrayOutput
On exit: ZETA k contains the scalar ζk for the m-k+1th transformation. If Tk=I then ZETA k=0.0, otherwise ZETA k contains ζk as described in Section 3 and ζk is always in the range 1.0,2.0.
6:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=-1
On entry, | M<0,
or | N<M,
or | LDA<M.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

The computed factors R and P satisfy the relation
R 0 PT=A+E,
where
E≤cε A,
ε is the machine precision (see X02AJF), c is a modest function of m and n and . denotes the spectral (two) norm.

8 Parallelism and Performance

F01QGF makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The approximate number of floating-point operations is given by 2×m 2 n-m.

10 Example

This example reduces the 3 by 5 matrix
A= 2.4 0.8 -1.4 3.0 -0.8 0.0 1.6 0.8 0.4 -0.8 0.0 0.0 1.0 2.0 2.0
to upper triangular form.

10.1 Program Text

Program Text (f01qgfe.f90)

10.2 Program Data

Program Data (f01qgfe.d)

10.3 Program Results

Program Results (f01qgfe.r)

F01 Chapter Contents
F01 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F01QJF : NAG Library, Mark 26

F01 Chapter Contents
F01 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F01QJF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F01QJF finds the RQ factorization of the real m by n (m≤n) matrix A, so that A is reduced to upper triangular form by means of orthogonal transformations from the right.

2 Specification

SUBROUTINE F01QJF ( M, N, A, LDA, ZETA, IFAIL)
INTEGER | M, N, LDA, IFAIL
REAL (KIND=nag_wp) | A(LDA,*), ZETA(M)

3 Description

The m by n matrix A is factorized as
A= R 0 PT when m<n, A=R PT when m=n,
where P is an n by n orthogonal matrix and R is an m by m upper triangular matrix.
P is given as a sequence of Householder transformation matrices
P=Pm…P 2P 1,
the (m-k+1)th transformation matrix, Pk, being used to introduce zeros into the kth row of A. Pk has the form
Pk=I-uk ukT,
where
uk= wk ζk 0 zk ,
ζk is a scalar, wk is an k-1 element vector and zk is an n-m element vector. uk is chosen to annihilate the elements in the kth row of A.
The vector uk is returned in the kth element of ZETA and in the kth row of A, such that ζk is in ZETA k, the elements of wk are in A k 1,…,A k k-1 and the elements of zk are in A k m+1,…,A kn. The elements of R are returned in the upper triangular part of A.

4 References

Golub G H and Van Loan C F (1996) Matrix Computations (3rd Edition) Johns Hopkins University Press, Baltimore
Wilkinson J H (1965) The Algebraic Eigenvalue Problem Oxford University Press, Oxford

5 Arguments

1:   M – INTEGERInput
On entry: m, the number of rows of the matrix A.
When M=0 then an immediate return is effected.
Constraint: M≥0.
2:   N – INTEGERInput
On entry: n, the number of columns of the matrix A.
Constraint: N≥M.
3:   A LDA* – REAL (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array A must be at least max 1,N.
On entry: the leading m by n part of the array A must contain the matrix to be factorized.
On exit: the m by m upper triangular part of A will contain the upper triangular matrix R, and the m by m strictly lower triangular part of A and the m by n-m rectangular part of A to the right of the upper triangular part will contain details of the factorization as described in Section 3.
4:   LDA – INTEGERInput
On entry: the first dimension of the array A as declared in the (sub)program from which F01QJF is called.
Constraint: LDA≥max 1,M.
5:   ZETA M – REAL (KIND=nag_wp) arrayOutput
On exit: ZETA k contains the scalar ζk for the m-k+1th transformation. If Pk=I then ZETA k=0.0, otherwise ZETA k contains ζk as described in Section 3 and ζk is always in the range 1.0,2.0.
6:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=-1
On entry, | M<0,
or | N<M,
or | LDA<M.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

The computed factors R and P satisfy the relation
R 0 PT=A+E,
where
E≤cε A,
ε is the machine precision (see X02AJF), c is a modest function of m and n, and . denotes the spectral (two) norm.

8 Parallelism and Performance

F01QJF makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The approximate number of floating-point operations is given by 2×m 2 3 n-m/3.
The first k rows of the orthogonal matrix PT can be obtained by calling F01QKF, which overwrites the k rows of PT on the first k rows of the array A. PT is obtained by the call:

IFAIL = 0
CALL F01QKF('Separate',M,N,K,A,LDA,ZETA,WORK,IFAIL)
WORK must be a max m-1,k-m,1 element array. If K is larger than M, then A must have been declared to have at least K rows.
Operations involving the matrix R can readily be performed by the Level 2 BLAS routines F06PFF (DTRMV) and F06PJF (DTRSV) (see Chapter F06), but note that no test for near singularity of R is incorporated into F06PJF (DTRSV). If R is singular, or nearly singular then F02WUF can be used to determine the singular value decomposition of R.

10 Example

This example obtains the RQ factorization of the 3 by 5 matrix
A= 2.0 2.0 1.6 2.0 1.2 2.5 2.5 -0.4 -0.5 -0.3 2.5 2.5 2.8 0.5 -2.9 .

10.1 Program Text

Program Text (f01qjfe.f90)

10.2 Program Data

Program Data (f01qjfe.d)

10.3 Program Results

Program Results (f01qjfe.r)

F01 Chapter Contents
F01 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F01QKF : NAG Library, Mark 26

F01 Chapter Contents
F01 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F01QKF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F01QKF returns the first ℓ rows of the real n by n orthogonal matrix PT, where P is given as the product of Householder transformation matrices.
This routine is intended for use following F01QJF.

2 Specification

SUBROUTINE F01QKF ( WHERET, M, N, NROWP, A, LDA, ZETA, WORK, IFAIL)
INTEGER | M, N, NROWP, LDA, IFAIL
REAL (KIND=nag_wp) | A(LDA,*), ZETA(*), WORK(max(M-1,NROWP-M,1))
CHARACTER(1) | WHERET

3 Description

P is assumed to be given by
P=PmP m-1⋯P 1
where
Pk = I - uk ukT , uk= wk ζk 0 zk ,
ζk is a scalar, wk is a (k-1) element vector and zk is an (n-m) element vector. wk must be supplied in the kth row of A in elements A k 1,…,A k k-1. zk must be supplied in the kth row of A in elements A k m+1,…,A kn and ζk must be supplied either in A kk or in ZETA k, depending upon the argument WHERET.

4 References

Golub G H and Van Loan C F (1996) Matrix Computations (3rd Edition) Johns Hopkins University Press, Baltimore
Wilkinson J H (1965) The Algebraic Eigenvalue Problem Oxford University Press, Oxford

5 Arguments

1:   WHERET – CHARACTER(1)Input
On entry: indicates where the elements of ζ are to be found.
WHERET='I' (In A)
The elements of ζ are in A.
WHERET='S' (Separate)
The elements of ζ are separate from A, in ZETA.
Constraint: WHERET='I' or 'S'.
2:   M – INTEGERInput
On entry: m, the number of rows of the matrix A.
Constraint: M≥0.
3:   N – INTEGERInput
On entry: n, the number of columns of the matrix A.
Constraint: N≥M.
4:   NROWP – INTEGERInput
On entry: ℓ, the required number of rows of P.
If NROWP=0, an immediate return is effected.
Constraint: 0≤NROWP≤N.
5:   A LDA* – REAL (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array A must be at least max 1,N.
On entry: the leading m by m strictly lower triangular part of the array A, and the m by n-m rectangular part of A with top left-hand corner at element A 1 M+1 must contain details of the matrix P. In addition, if WHERET='I', the diagonal elements of A must contain the elements of ζ.
On exit: the first NROWP rows of the array A are overwritten by the first NROWP rows of the n by n orthogonal matrix PT.
6:   LDA – INTEGERInput
On entry: the first dimension of the array A as declared in the (sub)program from which F01QKF is called.
Constraint: LDA≥max 1,M,NROWP.
7:   ZETA* – REAL (KIND=nag_wp) arrayInput
Note: the dimension of the array ZETA must be at least max 1,M if WHERET='S', and at least 1 otherwise.
On entry: with WHERET='S', the array ZETA must contain the elements of ζ. If ZETA k=0.0 then Pk is assumed to be I, otherwise ZETA k is assumed to contain ζk.
When WHERET='I', the array ZETA is not referenced.
8:   WORK max M-1,NROWP-M,1 – REAL (KIND=nag_wp) arrayWorkspace
Note: the dimension of the array WORK must be at least max M-1,NROWP-M,1.
9:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=-1
On entry, | WHERET≠'I' or 'S',
or | M<0,
or | N<M,
or | NROWP<0 or NROWP>N,
or | LDA<max M,NROWP.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

The computed matrix P satisfies the relation
P=Q+E,
where Q is an exactly orthogonal matrix and
E≤cε,
ε is the machine precision (see X02AJF), c is a modest function of n, and . denotes the spectral (two) norm. See also Section 7 in F01QJF.

8 Parallelism and Performance

F01QKF makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The approximate number of floating-point operations is given by
23 m 3 n-m2 ℓ-m-m ℓ-m, if ​ℓ≥m, and ​ 23 ℓ 2 3 n-ℓ, if ​ℓ<m.

10 Example

This example obtains the 5 by 5 orthogonal matrix P following the RQ factorization of the 3 by 5 matrix A given by
A= 2.0 2.0 1.6 2.0 1.2 2.5 2.5 -0.4 -0.5 -0.3 2.5 2.5 2.8 0.5 -2.9 .

10.1 Program Text

Program Text (f01qkfe.f90)

10.2 Program Data

Program Data (f01qkfe.d)

10.3 Program Results

Program Results (f01qkfe.r)

F01 Chapter Contents
F01 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F01RGF : NAG Library, Mark 26

F01 Chapter Contents
F01 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F01RGF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F01RGF reduces the complex m by n (m≤n) upper trapezoidal matrix A to upper triangular form by means of unitary transformations.

2 Specification

SUBROUTINE F01RGF ( M, N, A, LDA, THETA, IFAIL)
INTEGER | M, N, LDA, IFAIL
COMPLEX (KIND=nag_wp) | A(LDA,*), THETA(M)

3 Description

The m by n m≤n upper trapezoidal matrix A given by
A= U X ,
where U is an m by m upper triangular matrix, is factorized as
A= R 0 PH,
where P is an n by n unitary matrix and R is an m by m upper triangular matrix.
P is given as a sequence of Householder transformation matrices
P=Pm⋯P 2P 1,
the m-k+1th transformation matrix, Pk, being used to introduce zeros into the kth row of A. Pk has the form
Pk= I 0 0 Tk ,
where
Tk=I-γkuk ukH, uk= ζk 0 zk cr ,
γk is a scalar for which Re γk=1.0, ζk is a real scalar and zk is an n-m element vector. γk, ζk and zk are chosen to annihilate the elements of the kth row of X and to make the diagonal elements of R real.
The scalar γk and the vector uk are returned in the kth element of the array THETA and in the kth row of A, such that θk, given by
θk=ζk,Im γk,
is in THETA k and the elements of zk are in A k m+1,…,A kn. The elements of R are returned in the upper triangular part of A.
For further information on this factorization and its use see Section 6.5 of Golub and Van Loan (1996).

4 References

Golub G H and Van Loan C F (1996) Matrix Computations (3rd Edition) Johns Hopkins University Press, Baltimore
Wilkinson J H (1965) The Algebraic Eigenvalue Problem Oxford University Press, Oxford

5 Arguments

1:   M – INTEGERInput
On entry: m, the number of rows of the matrix A.
When M=0 then an immediate return is effected.
Constraint: M≥0.
2:   N – INTEGERInput
On entry: n, the number of columns of the matrix A.
Constraint: N≥M.
3:   A LDA* – COMPLEX (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array A must be at least max 1,N.
On entry: the leading m by n upper trapezoidal part of the array A must contain the matrix to be factorized.
On exit: the m by m upper triangular part of A will contain the upper triangular matrix R, and the m by n-m upper trapezoidal part of A will contain details of the factorization as described in Section 3.
4:   LDA – INTEGERInput
On entry: the first dimension of the array A as declared in the (sub)program from which F01RGF is called.
Constraint: LDA≥max 1,M.
5:   THETA M – COMPLEX (KIND=nag_wp) arrayOutput
On exit: THETA k contains the scalar θk for the m-k+1th transformation. If Tk=I then THETA k=0.0; if
Tk= α 0 0 I ,  Re α<0.0
then THETA k=α, otherwise THETA k contains θk as described in Section 3 and Re θk is always in the range 1.0,2.0.
6:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=-1
On entry, | M<0,
or | N<M,
or | LDA<M.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

The computed factors R and P satisfy the relation
R 0 PH=A+E,
where
E≤cε A,
ε is the machine precision (see X02AJF), c is a modest function of m and n, and . denotes the spectral (two) norm.

8 Parallelism and Performance

F01RGF makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The approximate number of floating-point operations is given by 8×m 2 n-m.

10 Example

This example reduces the 3 by 4 matrix
2.4 0.8+0.8 i -1.4+0.6 i 3.0-1.0 i 0.0 1.6 i+0.0 0.8+0.3 i 0.4+0.5 i 0.0 0.0i+0.0 1.0 i+0.0 2.0-1.0 i
to upper triangular form.

10.1 Program Text

Program Text (f01rgfe.f90)

10.2 Program Data

Program Data (f01rgfe.d)

10.3 Program Results

Program Results (f01rgfe.r)

F01 Chapter Contents
F01 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F01RJF : NAG Library, Mark 26

F01 Chapter Contents
F01 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F01RJF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F01RJF finds the RQ factorization of the complex m by n (m≤n), matrix A, so that A is reduced to upper triangular form by means of unitary transformations from the right.

2 Specification

SUBROUTINE F01RJF ( M, N, A, LDA, THETA, IFAIL)
INTEGER | M, N, LDA, IFAIL
COMPLEX (KIND=nag_wp) | A(LDA,*), THETA(M)

3 Description

The m by n matrix A is factorized as
A= R 0 PH when ​m<n, A=R PH when ​m=n,
where P is an n by n unitary matrix and R is an m by m upper triangular matrix.
P is given as a sequence of Householder transformation matrices
P=Pm⋯P 2P 1,
the m-k+1th transformation matrix, Pk, being used to introduce zeros into the kth row of A. Pk has the form
Pk=I-γkuk ukH,
where
uk= wk ζk 0 zk .
γk is a scalar for which Re γk=1.0, ζk is a real scalar, wk is a k-1 element vector and zk is an n-m element vector. γk and uk are chosen to annihilate the elements in the kth row of A.
The scalar γk and the vector uk are returned in the kth element of THETA and in the kth row of A, such that θk, given by
θk=ζk,Im γk.
is in THETA k, the elements of wk are in A k 1,…,A k k-1 and the elements of zk are in A k m+1,…,A kn. The elements of R are returned in the upper triangular part of A.

4 References

Golub G H and Van Loan C F (1996) Matrix Computations (3rd Edition) Johns Hopkins University Press, Baltimore
Wilkinson J H (1965) The Algebraic Eigenvalue Problem Oxford University Press, Oxford

5 Arguments

1:   M – INTEGERInput
On entry: m, the number of rows of the matrix A.
When M=0 then an immediate return is effected.
Constraint: M≥0.
2:   N – INTEGERInput
On entry: n, the number of columns of the matrix A.
Constraint: N≥M.
3:   A LDA* – COMPLEX (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array A must be at least max 1,N.
On entry: the leading m by n part of the array A must contain the matrix to be factorized.
On exit: the m by m upper triangular part of A will contain the upper triangular matrix R, and the m by m strictly lower triangular part of A and the m by n-m rectangular part of A to the right of the upper triangular part will contain details of the factorization as described in Section 3.
4:   LDA – INTEGERInput
On entry: the first dimension of the array A as declared in the (sub)program from which F01RJF is called.
Constraint: LDA≥max 1,M.
5:   THETA M – COMPLEX (KIND=nag_wp) arrayOutput
On exit: THETA k contains the scalar θk for the m-k+1th transformation. If Pk=I then THETA k=0.0; if
Tk= I 0 0 0 α 0 0 0 I ,  Re α<0.0
then THETA k=α, otherwise THETA k contains θk as described in Section 3 and θk is always in the range 1.0,2.0.
6:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=-1
On entry, | M<0,
or | N<M,
or | LDA<M.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

The computed factors R and P satisfy the relation
R 0 PH=A+E,
where
E≤cε A,
ε is the machine precision (see X02AJF), c is a modest function of m and n, and . denotes the spectral (two) norm.

8 Parallelism and Performance

F01RJF makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The approximate number of floating-point operations is given by 8×m 2 3 n-m/3.
The first k rows of the unitary matrix PH can be obtained by calling F01RKF, which overwrites the k rows of PH on the first k rows of the array A. PH is obtained by the call:
IFAIL = 0
CALL F01RKF('Separate',M,N,K,A,LDA,THETA,WORK,IFAIL)
WORK must be a max m-1,k-m,1 element array. If K is larger than M, then A must have been declared to have at least K rows.
Operations involving the matrix R can readily be performed by the Level 2 BLAS routines F06SFF (ZTRMV) and F06SJF (ZTRSV), (see Chapter F06), but note that no test for near singularity of R is incorporated into F06SFF (ZTRMV). If R is singular, or nearly singular then F02XUF can be used to determine the singular value decomposition of R.

10 Example

This example obtains the RQ factorization of the 3 by 5 matrix
A= -0.5 i 0.4-0.3 i 0.4 i+0.0 0.3-0.4 i 0.3 i -0.5-1.5 i 0.9-1.3 i -0.4-0.4 i 0.1-0.7 i 0.3-0.3 i -1.0-1.0 i 0.2-1.4 i 1.8 i+0.0 0.0 i+0.0 -2.4 i .

10.1 Program Text

Program Text (f01rjfe.f90)

10.2 Program Data

Program Data (f01rjfe.d)

10.3 Program Results

Program Results (f01rjfe.r)

F01 Chapter Contents
F01 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F01RKF : NAG Library, Mark 26

F01 Chapter Contents
F01 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F01RKF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F01RKF returns the first ℓ rows of the n by n unitary matrix PH, where P is given as the product of Householder transformation matrices.
This routine is intended for use following F01RJF.

2 Specification

SUBROUTINE F01RKF ( WHERET, M, N, NROWP, A, LDA, THETA, WORK, IFAIL)
INTEGER | M, N, NROWP, LDA, IFAIL
COMPLEX (KIND=nag_wp) | A(LDA,*), THETA(*), WORK(max(M-1,NROWP-M,1))
CHARACTER(1) | WHERET

3 Description

P is assumed to be given by
P = Pm P m-1 ⋯ P 1 ,
where
Pk=I-γkuk ukH, uk= wk ζk 0 zk
γk is a scalar for which Re γk=1.0, ζk is a real scalar, wk is a k-1 element vector and zk is an n-m element vector. wk must be supplied in the kth row of A in elements A k 1,…,A k k-1. zk must be supplied in the kth row of A in elements A k m+1,…,A kn and θk, given by
θk=ζk,Im γk,
must be supplied either in A kk or in THETA k, depending upon the argument WHERET.

4 References

Golub G H and Van Loan C F (1996) Matrix Computations (3rd Edition) Johns Hopkins University Press, Baltimore
Wilkinson J H (1965) The Algebraic Eigenvalue Problem Oxford University Press, Oxford

5 Arguments

1:   WHERET – CHARACTER(1)Input
On entry: indicates where the elements of θ are to be found.
WHERET='I' (In A)
The elements of θ are in A.
WHERET='S' (Separate)
The elements of θ are separate from A, in THETA.
Constraint: WHERET='I' or 'S'.
2:   M – INTEGERInput
On entry: m, the number of rows of the matrix A.
Constraint: M≥0.
3:   N – INTEGERInput
On entry: n, the number of columns of the matrix A.
Constraint: N≥M.
4:   NROWP – INTEGERInput
On entry: ℓ, the required number of rows of P.
If NROWP=0, an immediate return is effected.
Constraint: 0≤NROWP≤N.
5:   A LDA* – COMPLEX (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array A must be at least max 1,N.
On entry: the leading m by m strictly lower triangular part of the array A, and the m by n-m rectangular part of A with top left-hand corner at element A 1 M+1 must contain details of the matrix P. In addition, if WHERET='I', the diagonal elements of A must contain the elements of θ.
On exit: the first NROWP rows of the array A are overwritten by the first NROWP rows of the n by n unitary matrix PH.
6:   LDA – INTEGERInput
On entry: the first dimension of the array A as declared in the (sub)program from which F01RKF is called.
Constraint: LDA≥max 1,M,NROWP.
7:   THETA* – COMPLEX (KIND=nag_wp) arrayInput
Note: the dimension of the array THETA must be at least max 1,M if WHERET='S', and at least 1 otherwise.
On entry: if WHERET='S', the array THETA must contain the elements of θ. If THETA k=0.0, Pk is assumed to be I, if THETA k=α and Re α<0.0, Pk is assumed to be of the form
Pk= I 0 0 0 α 0 0 0 I ,
otherwise THETA k is assumed to contain θk given by
θk=ζk,Im γk.
If WHERET='I', the array THETA is not referenced.
8:   WORK max M-1,NROWP-M,1 – COMPLEX (KIND=nag_wp) arrayWorkspace
9:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=-1
On entry, | WHERET≠'I' or 'S',
or | M<0,
or | N<M,
or | NROWP<0 or NROWP>N,
or | LDA<max 1,M,NROWP.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

The computed matrix P satisfies the relation
P=Q+E,
where Q is an exactly unitary matrix and
E≤cε,
where ε the machine precision (see X02AJF), c is a modest function of n, and . denotes the spectral (two) norm. See also Section 7 in F01RJF.

8 Parallelism and Performance

F01RKF makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The approximate number of floating-point operations is given by
83 n 3 n-m2 ℓ-m-m ℓ-m, if ​ℓ≥m, and ​ 83 ℓ 2 3 n-ℓ, if ​ℓ<m.

10 Example

This example obtains the 5 by 5 unitary matrix P following the RQ factorization of the 3 by 5 matrix A given by
A = -0.5 i 0.4-0.3 i 0.4 i+0.0 0.3-0.4 i 0.3 i -0.5-1.5 i 0.9-1.3 i -0.4-0.4 i 0.1-0.7 i 0.3-0.3 i -1.0-1.0 i 0.2-1.4 i 1.8 i+0.0 0.0 i+0.0 -2.4 i .

10.1 Program Text

Program Text (f01rkfe.f90)

10.2 Program Data

Program Data (f01rkfe.d)

10.3 Program Results

Program Results (f01rkfe.r)

F01 Chapter Contents
F01 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F01VAF (DTRTTP) : NAG Library, Mark 26

F01 Chapter Contents
F01 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F01VAF (DTRTTP)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F01VAF (DTRTTP) copies a real triangular matrix, stored in a full format array, to a standard packed format array.

2 Specification

SUBROUTINE F01VAF ( UPLO, N, A, LDA, AP, INFO)
INTEGER | N, LDA, INFO
REAL (KIND=nag_wp) | A(LDA,*), AP(N*(N+1)/2)
CHARACTER(1) | UPLO
The routine may be called by its LAPACK name dtrttp.

3 Description

F01VAF (DTRTTP) packs a real n by n triangular matrix A, stored conventionally in a full format array, into an array of length n n+1/2. The matrix is packed by columns. This routine is intended for possible use in conjunction with routines from Chapters F06, F07, F08 and F16 where some routines use triangular matrices stored in the packed form. Packed storage format is described in Section 3.3.2 in the F07 Chapter Introduction.

4 References

None.

5 Arguments

1:   UPLO – CHARACTER(1)Input
On entry: specifies whether A is upper or lower triangular.
UPLO='U'
A is upper triangular.
UPLO='L'
A is lower triangular.
Constraint: UPLO='U' or 'L'.
2:   N – INTEGERInput
On entry: n, the order of the matrix A.
Constraint: N≥0.
3:   A LDA* – REAL (KIND=nag_wp) arrayInput
Note: the second dimension of the array A must be at least N.
On entry: the triangular matrix A.
  • If UPLO='U', A is upper triangular and the elements of the array below the diagonal are not referenced.
  • If UPLO='L', A is lower triangular and the elements of the array above the diagonal are not referenced.
4:   LDA – INTEGERInput
On entry: the first dimension of the array A as declared in the (sub)program from which F01VAF (DTRTTP) is called.
Constraint: LDA≥max 1,N.
5:   AP N×N+1/2 – REAL (KIND=nag_wp) arrayOutput
On exit: the n by n triangular matrix A, packed by columns.
More precisely,
  • if UPLO='U', the upper triangle of A is stored with element A ij in AP i+j j-1/2 for i≤j;
  • if UPLO='L', the lower triangle of A is stored with element A ij in AP i+2 n-jj-1/2 for i≥j.
6:   INFO – INTEGEROutput
On exit: INFO=0 unless the routine detects an error (see Section 6).

6 Error Indicators and Warnings

INFO<0
If INFO=-i, argument i had an illegal value. An explanatory message is output, and execution of the program is terminated.

7 Accuracy

Not applicable.

8 Parallelism and Performance

F01VAF (DTRTTP) is not threaded in any implementation.

9 Further Comments

None.

10 Example

This example reads in a triangular matrix and copies it to packed format.

10.1 Program Text

Program Text (f01vafe.f90)

10.2 Program Data

Program Data (f01vafe.d)

10.3 Program Results

Program Results (f01vafe.r)

F01 Chapter Contents
F01 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F01VBF (ZTRTTP) : NAG Library, Mark 26

F01 Chapter Contents
F01 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F01VBF (ZTRTTP)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F01VBF (ZTRTTP) copies a complex triangular matrix, stored in a full format array, to a packed format array.

2 Specification

SUBROUTINE F01VBF ( UPLO, N, A, LDA, AP, INFO)
INTEGER | N, LDA, INFO
COMPLEX (KIND=nag_wp) | A(LDA,*), AP(N*(N+1)/2)
CHARACTER(1) | UPLO
The routine may be called by its LAPACK name ztrttp.

3 Description

F01VBF (ZTRTTP) packs a complex n by n triangular matrix A, stored conventionally in a full format array, into an array of length n n+1/2. The matrix is packed by columns. This routine is intended for possible use in conjunction with routines from Chapters F06, F07, F08 and F16 where some routines use triangular matrices stored in the packed form. Packed storage format is described in Section 3.3.2 in the F07 Chapter Introduction.

4 References

None.

5 Arguments

1:   UPLO – CHARACTER(1)Input
On entry: specifies whether A is upper or lower triangular.
UPLO='U'
A is upper triangular.
UPLO='L'
A is lower triangular.
Constraint: UPLO='U' or 'L'.
2:   N – INTEGERInput
On entry: n, the order of the matrix A.
Constraint: N≥0.
3:   A LDA* – COMPLEX (KIND=nag_wp) arrayInput
Note: the second dimension of the array A must be at least N.
On entry: the triangular matrix A.
  • If UPLO='U', A is upper triangular and the elements of the array below the diagonal are not referenced.
  • If UPLO='L', A is lower triangular and the elements of the array above the diagonal are not referenced.
4:   LDA – INTEGERInput
On entry: the first dimension of the array A as declared in the (sub)program from which F01VBF (ZTRTTP) is called.
Constraint: LDA≥max 1,N.
5:   AP N×N+1/2 – COMPLEX (KIND=nag_wp) arrayOutput
On exit: the n by n triangular matrix A, packed by columns.
More precisely,
  • if UPLO='U', the upper triangle of A is stored with element A ij in AP i+j j-1/2 for i≤j;
  • if UPLO='L', the lower triangle of A is stored with element A ij in AP i+2 n-jj-1/2 for i≥j.
6:   INFO – INTEGEROutput
On exit: INFO=0 unless the routine detects an error (see Section 6).

6 Error Indicators and Warnings

INFO<0
If INFO=-i, argument i had an illegal value. An explanatory message is output, and execution of the program is terminated.

7 Accuracy

Not applicable.

8 Parallelism and Performance

F01VBF (ZTRTTP) is not threaded in any implementation.

9 Further Comments

None.

10 Example

This example reads in a triangular matrix and copies it to packed format.

10.1 Program Text

Program Text (f01vbfe.f90)

10.2 Program Data

Program Data (f01vbfe.d)

10.3 Program Results

Program Results (f01vbfe.r)

F01 Chapter Contents
F01 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F01VCF (DTPTTR) : NAG Library, Mark 26

F01 Chapter Contents
F01 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F01VCF (DTPTTR)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F01VCF (DTPTTR) unpacks a real triangular matrix, stored in a standard packed format array, to a full format array.

2 Specification

SUBROUTINE F01VCF ( UPLO, N, AP, A, LDA, INFO)
INTEGER | N, LDA, INFO
REAL (KIND=nag_wp) | AP(N*(N+1)/2), A(LDA,*)
CHARACTER(1) | UPLO
The routine may be called by its LAPACK name dtpttr.

3 Description

F01VCF (DTPTTR) unpacks a real n by n triangular matrix A, stored in an array of length n n+1/2, to conventional storage in a full format array. This routine is intended for possible use in conjunction with routines from Chapters F06, F07, F08 and F16 where some routines use triangular matrices stored in the packed form. Packed storage format is described in Section 3.3.2 in the F07 Chapter Introduction.

4 References

None.

5 Arguments

1:   UPLO – CHARACTER(1)Input
On entry: specifies whether A is upper or lower triangular.
UPLO='U'
A is upper triangular.
UPLO='L'
A is lower triangular.
Constraint: UPLO='U' or 'L'.
2:   N – INTEGERInput
On entry: n, the order of the matrix A.
Constraint: N≥0.
3:   AP N×N+1/2 – REAL (KIND=nag_wp) arrayInput
On entry: the n by n triangular matrix A, packed by columns.
More precisely,
  • if UPLO='U', the upper triangle of A must be stored with element A ij in AP i+j j-1/2 for i≤j;
  • if UPLO='L', the lower triangle of A must be stored with element A ij in AP i+2 n-jj-1/2 for i≥j.
4:   A LDA* – REAL (KIND=nag_wp) arrayOutput
Note: the second dimension of the array A must be at least N.
On exit: the triangular matrix A.
  • If UPLO='U', A is upper triangular and the elements of the array below the diagonal are not referenced.
  • If UPLO='L', A is lower triangular and the elements of the array above the diagonal are not referenced.
5:   LDA – INTEGERInput
On entry: the first dimension of the array A as declared in the (sub)program from which F01VCF (DTPTTR) is called.
Constraint: LDA≥max 1,N.
6:   INFO – INTEGEROutput
On exit: INFO=0 unless the routine detects an error (see Section 6).

6 Error Indicators and Warnings

INFO<0
If INFO=-i, argument i had an illegal value. An explanatory message is output, and execution of the program is terminated.

7 Accuracy

Not applicable.

8 Parallelism and Performance

F01VCF (DTPTTR) is not threaded in any implementation.

9 Further Comments

None.

10 Example

This example reads in a triangular matrix packed by columns and unpacks it to full format.

10.1 Program Text

Program Text (f01vcfe.f90)

10.2 Program Data

Program Data (f01vcfe.d)

10.3 Program Results

Program Results (f01vcfe.r)

F01 Chapter Contents
F01 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F01VDF (ZTPTTR) : NAG Library, Mark 26

F01 Chapter Contents
F01 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F01VDF (ZTPTTR)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F01VDF (ZTPTTR) unpacks a complex triangular matrix, stored in a standard packed format array, to a full format array.

2 Specification

SUBROUTINE F01VDF ( UPLO, N, AP, A, LDA, INFO)
INTEGER | N, LDA, INFO
COMPLEX (KIND=nag_wp) | AP(N*(N+1)/2), A(LDA,*)
CHARACTER(1) | UPLO
The routine may be called by its LAPACK name ztpttr.

3 Description

F01VDF (ZTPTTR) unpacks a complex n by n triangular matrix A, stored in an array of length n n+1/2, to conventional storage in a full format array. This routine is intended for possible use in conjunction with routines from Chapters F06, F07, F08 and F16 where some routines use triangular matrices stored in the packed form. Packed storage format is described in Section 3.3.2 in the F07 Chapter Introduction.

4 References

None.

5 Arguments

1:   UPLO – CHARACTER(1)Input
On entry: specifies whether A is upper or lower triangular.
UPLO='U'
A is upper triangular.
UPLO='L'
A is lower triangular.
Constraint: UPLO='U' or 'L'.
2:   N – INTEGERInput
On entry: n, the order of the matrix A.
Constraint: N≥0.
3:   AP N×N+1/2 – COMPLEX (KIND=nag_wp) arrayInput
On entry: the n by n triangular matrix A, packed by columns.
More precisely,
  • if UPLO='U', the upper triangle of A must be stored with element A ij in AP i+j j-1/2 for i≤j;
  • if UPLO='L', the lower triangle of A must be stored with element A ij in AP i+2 n-jj-1/2 for i≥j.
4:   A LDA* – COMPLEX (KIND=nag_wp) arrayOutput
Note: the second dimension of the array A must be at least N.
On exit: the triangular matrix A.
  • If UPLO='U', A is upper triangular and the elements of the array below the diagonal are not referenced.
  • If UPLO='L', A is lower triangular and the elements of the array above the diagonal are not referenced.
5:   LDA – INTEGERInput
On entry: the first dimension of the array A as declared in the (sub)program from which F01VDF (ZTPTTR) is called.
Constraint: LDA≥max 1,N.
6:   INFO – INTEGEROutput
On exit: INFO=0 unless the routine detects an error (see Section 6).

6 Error Indicators and Warnings

INFO<0
If INFO=-i, argument i had an illegal value. An explanatory message is output, and execution of the program is terminated.

7 Accuracy

Not applicable.

8 Parallelism and Performance

F01VDF (ZTPTTR) is not threaded in any implementation.

9 Further Comments

None.

10 Example

This example reads in a triangular matrix packed by columns and unpacks it to full format.

10.1 Program Text

Program Text (f01vdfe.f90)

10.2 Program Data

Program Data (f01vdfe.d)

10.3 Program Results

Program Results (f01vdfe.r)

F01 Chapter Contents
F01 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F01VEF (DTRTTF) : NAG Library, Mark 26

F01 Chapter Contents
F01 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F01VEF (DTRTTF)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F01VEF (DTRTTF) copies a real triangular matrix, stored in a full format array, to a Rectangular Full Packed (RFP) format array.

2 Specification

SUBROUTINE F01VEF ( TRANSR, UPLO, N, A, LDA, AR, INFO)
INTEGER | N, LDA, INFO
REAL (KIND=nag_wp) | A(LDA,*), AR(N*(N+1)/2)
CHARACTER(1) | TRANSR, UPLO
The routine may be called by its LAPACK name dtrttf.

3 Description

F01VEF (DTRTTF) packs a real n by n triangular matrix A, stored conventionally in a full format array, into RFP format. This routine is intended for possible use in conjunction with routines from Chapters F06, F07 and F16 where some routines that use triangular matrices store them in RFP format. The RFP storage format is described in Section 3.3.3 in the F07 Chapter Introduction.

4 References

Gustavson F G, Waśniewski J, Dongarra J J and Langou J (2010) Rectangular full packed format for Cholesky's algorithm: factorization, solution, and inversion ACM Trans. Math. Software 37, 2

5 Arguments

1:   TRANSR – CHARACTER(1)Input
On entry: specifies whether the normal RFP representation of A or its transpose is stored.
TRANSR='N'
The RFP representation of the matrix A is stored.
TRANSR='T'
The transpose of the RFP representation of the matrix A is stored.
Constraint: TRANSR='N' or 'T'.
2:   UPLO – CHARACTER(1)Input
On entry: specifies whether A is upper or lower triangular.
UPLO='U'
A is upper triangular.
UPLO='L'
A is lower triangular.
Constraint: UPLO='U' or 'L'.
3:   N – INTEGERInput
On entry: n, the order of the matrix A.
Constraint: N≥0.
4:   A LDA* – REAL (KIND=nag_wp) arrayInput
Note: the second dimension of the array A must be at least N.
On entry: the triangular matrix A.
  • If UPLO='U', A is upper triangular and the elements of the array below the diagonal are not referenced.
  • If UPLO='L', A is lower triangular and the elements of the array above the diagonal are not referenced.
5:   LDA – INTEGERInput
On entry: the first dimension of the array A as declared in the (sub)program from which F01VEF (DTRTTF) is called.
Constraint: LDA≥max 1,N.
6:   AR N×N+1/2 – REAL (KIND=nag_wp) arrayOutput
On exit: the upper or lower n by n triangular matrix A (as specified by UPLO) in either normal or transposed RFP format (as specified by TRANSR). The storage format is described in Section 3.3.3 in the F07 Chapter Introduction.
7:   INFO – INTEGEROutput
On exit: INFO=0 unless the routine detects an error (see Section 6).

6 Error Indicators and Warnings

INFO<0
If INFO=-i, argument i had an illegal value. An explanatory message is output, and execution of the program is terminated.

7 Accuracy

Not applicable.

8 Parallelism and Performance

F01VEF (DTRTTF) is not threaded in any implementation.

9 Further Comments

None.

10 Example

This example reads in a triangular matrix and copies it to RFP format.

10.1 Program Text

Program Text (f01vefe.f90)

10.2 Program Data

Program Data (f01vefe.d)

10.3 Program Results

Program Results (f01vefe.r)

F01 Chapter Contents
F01 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F01VFF (ZTRTTF) : NAG Library, Mark 26

F01 Chapter Contents
F01 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F01VFF (ZTRTTF)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F01VFF (ZTRTTF) copies a complex triangular matrix, stored in a full format array, to a Rectangular Full Packed (RFP) format array.

2 Specification

SUBROUTINE F01VFF ( TRANSR, UPLO, N, A, LDA, AR, INFO)
INTEGER | N, LDA, INFO
COMPLEX (KIND=nag_wp) | A(LDA,*), AR(N*(N+1)/2)
CHARACTER(1) | TRANSR, UPLO
The routine may be called by its LAPACK name ztrttf.

3 Description

F01VFF (ZTRTTF) packs a complex n by n triangular matrix A, stored conventionally in a full format array, into RFP format. This routine is intended for possible use in conjunction with routines from Chapters F06, F07 and F16 where some routines that use triangular matrices store them in RFP format. The RFP storage format is described in Section 3.3.3 in the F07 Chapter Introduction.

4 References

Gustavson F G, Waśniewski J, Dongarra J J and Langou J (2010) Rectangular full packed format for Cholesky's algorithm: factorization, solution, and inversion ACM Trans. Math. Software 37, 2

5 Arguments

1:   TRANSR – CHARACTER(1)Input
On entry: specifies whether the normal RFP representation of A or its conjugate transpose is stored.
TRANSR='N'
The RFP representation of the matrix A is stored.
TRANSR='C'
The conjugate transpose of the RFP representation of the matrix A is stored.
Constraint: TRANSR='N' or 'C'.
2:   UPLO – CHARACTER(1)Input
On entry: specifies whether A is upper or lower triangular.
UPLO='U'
A is upper triangular.
UPLO='L'
A is lower triangular.
Constraint: UPLO='U' or 'L'.
3:   N – INTEGERInput
On entry: n, the order of the matrix A.
Constraint: N≥0.
4:   A LDA* – COMPLEX (KIND=nag_wp) arrayInput
Note: the second dimension of the array A must be at least N.
On entry: the triangular matrix A.
  • If UPLO='U', A is upper triangular and the elements of the array below the diagonal are not referenced.
  • If UPLO='L', A is lower triangular and the elements of the array above the diagonal are not referenced.
5:   LDA – INTEGERInput
On entry: the first dimension of the array A as declared in the (sub)program from which F01VFF (ZTRTTF) is called.
Constraint: LDA≥max 1,N.
6:   AR N×N+1/2 – COMPLEX (KIND=nag_wp) arrayOutput
On exit: the upper or lower n by n triangular matrix A (as specified by UPLO) in either normal or transposed RFP format (as specified by TRANSR). The storage format is described in Section 3.3.3 in the F07 Chapter Introduction.
7:   INFO – INTEGEROutput
On exit: INFO=0 unless the routine detects an error (see Section 6).

6 Error Indicators and Warnings

INFO<0
If INFO=-i, argument i had an illegal value. An explanatory message is output, and execution of the program is terminated.

7 Accuracy

Not applicable.

8 Parallelism and Performance

F01VFF (ZTRTTF) is not threaded in any implementation.

9 Further Comments

None.

10 Example

This example reads in a triangular matrix and copies it to RFP format.

10.1 Program Text

Program Text (f01vffe.f90)

10.2 Program Data

Program Data (f01vffe.d)

10.3 Program Results

Program Results (f01vffe.r)

F01 Chapter Contents
F01 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F01VGF (DTFTTR) : NAG Library, Mark 26

F01 Chapter Contents
F01 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F01VGF (DTFTTR)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F01VGF (DTFTTR) unpacks a real triangular matrix, stored in a Rectangular Full Packed (RFP) format array, to a full format array.

2 Specification

SUBROUTINE F01VGF ( TRANSR, UPLO, N, AR, A, LDA, INFO)
INTEGER | N, LDA, INFO
REAL (KIND=nag_wp) | AR(N*(N+1)/2), A(LDA,*)
CHARACTER(1) | TRANSR, UPLO
The routine may be called by its LAPACK name dtfttr.

3 Description

F01VGF (DTFTTR) unpacks a real n by n triangular matrix A, stored in RFP format to conventional storage in a full format array. This routine is intended for possible use in conjunction with routines from Chapters F06, F07 and F16 where some routines that use triangular matrices store them in RFP format. The RFP storage format is described in Section 3.3.3 in the F07 Chapter Introduction.

4 References

Gustavson F G, Waśniewski J, Dongarra J J and Langou J (2010) Rectangular full packed format for Cholesky's algorithm: factorization, solution, and inversion ACM Trans. Math. Software 37, 2

5 Arguments

1:   TRANSR – CHARACTER(1)Input
On entry: specifies whether the normal RFP representation of A or its transpose is stored.
TRANSR='N'
The RFP representation of the matrix A is stored.
TRANSR='T'
The transpose of the RFP representation of the matrix A is stored.
Constraint: TRANSR='N' or 'T'.
2:   UPLO – CHARACTER(1)Input
On entry: specifies whether A is upper or lower triangular.
UPLO='U'
A is upper triangular.
UPLO='L'
A is lower triangular.
Constraint: UPLO='U' or 'L'.
3:   N – INTEGERInput
On entry: n, the order of the matrix A.
Constraint: N≥0.
4:   AR N×N+1/2 – REAL (KIND=nag_wp) arrayInput
On entry: the upper or lower n by n triangular matrix A (as specified by UPLO) in either normal or transposed RFP format (as specified by TRANSR). The storage format is described in Section 3.3.3 in the F07 Chapter Introduction.
5:   A LDA* – REAL (KIND=nag_wp) arrayOutput
Note: the second dimension of the array A must be at least N.
On exit: the triangular matrix A.
  • If UPLO='U', A is upper triangular and the elements of the array below the diagonal are not referenced.
  • If UPLO='L', A is lower triangular and the elements of the array above the diagonal are not referenced.
6:   LDA – INTEGERInput
On entry: the first dimension of the array A as declared in the (sub)program from which F01VGF (DTFTTR) is called.
Constraint: LDA≥max 1,N.
7:   INFO – INTEGEROutput
On exit: INFO=0 unless the routine detects an error (see Section 6).

6 Error Indicators and Warnings

INFO<0
If INFO=-i, argument i had an illegal value. An explanatory message is output, and execution of the program is terminated.

7 Accuracy

Not applicable.

8 Parallelism and Performance

F01VGF (DTFTTR) is not threaded in any implementation.

9 Further Comments

None.

10 Example

This example reads in a triangular matrix in RFP format and unpacks it to full format.

10.1 Program Text

Program Text (f01vgfe.f90)

10.2 Program Data

Program Data (f01vgfe.d)

10.3 Program Results

Program Results (f01vgfe.r)

F01 Chapter Contents
F01 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F01VHF (ZTFTTR) : NAG Library, Mark 26

F01 Chapter Contents
F01 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F01VHF (ZTFTTR)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F01VHF (ZTFTTR) unpacks a complex triangular matrix, stored in a Rectangular Full Packed (RFP) format array, to a full format array.

2 Specification

SUBROUTINE F01VHF ( TRANSR, UPLO, N, AR, A, LDA, INFO)
INTEGER | N, LDA, INFO
COMPLEX (KIND=nag_wp) | AR(N*(N+1)/2), A(LDA,*)
CHARACTER(1) | TRANSR, UPLO
The routine may be called by its LAPACK name ztfttr.

3 Description

F01VHF (ZTFTTR) unpacks a complex n by n triangular matrix A, stored in RFP format to conventional storage in a full format array. This routine is intended for possible use in conjunction with routines from Chapters F06, F07 and F16 where some routines that use triangular matrices store them in RFP format. The RFP storage format is described in Section 3.3.3 in the F07 Chapter Introduction.

4 References

Gustavson F G, Waśniewski J, Dongarra J J and Langou J (2010) Rectangular full packed format for Cholesky's algorithm: factorization, solution, and inversion ACM Trans. Math. Software 37, 2

5 Arguments

1:   TRANSR – CHARACTER(1)Input
On entry: specifies whether the normal RFP representation of A or its conjugate transpose is stored.
TRANSR='N'
The RFP representation of the matrix A is stored.
TRANSR='C'
The conjugate transpose of the RFP representation of the matrix A is stored.
Constraint: TRANSR='N' or 'C'.
2:   UPLO – CHARACTER(1)Input
On entry: specifies whether A is upper or lower triangular.
UPLO='U'
A is upper triangular.
UPLO='L'
A is lower triangular.
Constraint: UPLO='U' or 'L'.
3:   N – INTEGERInput
On entry: n, the order of the matrix A.
Constraint: N≥0.
4:   AR N×N+1/2 – COMPLEX (KIND=nag_wp) arrayInput
On entry: the upper or lower n by n triangular matrix A (as specified by UPLO) in either normal or transposed RFP format (as specified by TRANSR). The storage format is described in Section 3.3.3 in the F07 Chapter Introduction.
5:   A LDA* – COMPLEX (KIND=nag_wp) arrayOutput
Note: the second dimension of the array A must be at least N.
On exit: the triangular matrix A.
  • If UPLO='U', A is upper triangular and the elements of the array below the diagonal are not referenced.
  • If UPLO='L', A is lower triangular and the elements of the array above the diagonal are not referenced.
6:   LDA – INTEGERInput
On entry: the first dimension of the array A as declared in the (sub)program from which F01VHF (ZTFTTR) is called.
Constraint: LDA≥max 1,N.
7:   INFO – INTEGEROutput
On exit: INFO=0 unless the routine detects an error (see Section 6).

6 Error Indicators and Warnings

INFO<0
If INFO=-i, argument i had an illegal value. An explanatory message is output, and execution of the program is terminated.

7 Accuracy

Not applicable.

8 Parallelism and Performance

F01VHF (ZTFTTR) is not threaded in any implementation.

9 Further Comments

None.

10 Example

This example reads in a triangular matrix in RFP format and unpacks it to full format.

10.1 Program Text

Program Text (f01vhfe.f90)

10.2 Program Data

Program Data (f01vhfe.d)

10.3 Program Results

Program Results (f01vhfe.r)

F01 Chapter Contents
F01 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F01VJF (DTPTTF) : NAG Library, Mark 26

F01 Chapter Contents
F01 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F01VJF (DTPTTF)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F01VJF (DTPTTF) copies a real triangular matrix, stored in a standard packed format array, to a Rectangular Full Packed (RFP) format array.

2 Specification

SUBROUTINE F01VJF ( TRANSR, UPLO, N, AP, AR, INFO)
INTEGER | N, INFO
REAL (KIND=nag_wp) | AP(N*(N+1)/2), AR(N*(N+1)/2)
CHARACTER(1) | TRANSR, UPLO
The routine may be called by its LAPACK name dtpttf.

3 Description

F01VJF (DTPTTF) copies a real n by n triangular matrix, A, stored in packed format, to RFP format. This routine is intended for possible use in conjunction with routines from Chapters F06, F07 and F16 where some routines that use triangular matrices store them in RFP format. The RFP storage format is described in Section 3.3.3 in the F07 Chapter Introduction and the packed storage format is described in Section 3.3.2 in the F07 Chapter Introduction.

4 References

Gustavson F G, Waśniewski J, Dongarra J J and Langou J (2010) Rectangular full packed format for Cholesky's algorithm: factorization, solution, and inversion ACM Trans. Math. Software 37, 2

5 Arguments

1:   TRANSR – CHARACTER(1)Input
On entry: specifies whether the normal RFP representation of A or its transpose is stored.
TRANSR='N'
The RFP representation of the matrix A is stored.
TRANSR='T'
The transpose of the RFP representation of the matrix A is stored.
Constraint: TRANSR='N' or 'T'.
2:   UPLO – CHARACTER(1)Input
On entry: specifies whether A is upper or lower triangular.
UPLO='U'
A is upper triangular.
UPLO='L'
A is lower triangular.
Constraint: UPLO='U' or 'L'.
3:   N – INTEGERInput
On entry: n, the order of the matrix A.
Constraint: N≥0.
4:   AP N×N+1/2 – REAL (KIND=nag_wp) arrayInput
On entry: the n by n triangular matrix A, packed by columns.
More precisely,
  • if UPLO='U', the upper triangle of A must be stored with element A ij in AP i+j j-1/2 for i≤j;
  • if UPLO='L', the lower triangle of A must be stored with element A ij in AP i+2 n-jj-1/2 for i≥j.
5:   AR N×N+1/2 – REAL (KIND=nag_wp) arrayOutput
On exit: the upper or lower n by n triangular matrix A (as specified by UPLO) in either normal or transposed RFP format (as specified by TRANSR). The storage format is described in Section 3.3.3 in the F07 Chapter Introduction.
6:   INFO – INTEGEROutput
On exit: INFO=0 unless the routine detects an error (see Section 6).

6 Error Indicators and Warnings

-999<INFO<0
If INFO=-i, argument i had an illegal value. An explanatory message is output, and execution of the program is terminated.
INFO=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

Not applicable.

8 Parallelism and Performance

F01VJF (DTPTTF) is not threaded in any implementation.

9 Further Comments

None.

10 Example

This example reads in a triangular matrix in packed format and copies it to RFP format.

10.1 Program Text

Program Text (f01vjfe.f90)

10.2 Program Data

Program Data (f01vjfe.d)

10.3 Program Results

Program Results (f01vjfe.r)

F01 Chapter Contents
F01 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F01VKF (ZTPTTF) : NAG Library, Mark 26

F01 Chapter Contents
F01 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F01VKF (ZTPTTF)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F01VKF (ZTPTTF) copies a complex triangular matrix, stored in a standard packed format array, to a Rectangular Full Packed (RFP) format array.

2 Specification

SUBROUTINE F01VKF ( TRANSR, UPLO, N, AP, AR, INFO)
INTEGER | N, INFO
COMPLEX (KIND=nag_wp) | AP(N*(N+1)/2), AR(N*(N+1)/2)
CHARACTER(1) | TRANSR, UPLO
The routine may be called by its LAPACK name ztpttf.

3 Description

F01VKF (ZTPTTF) copies a complex n by n triangular matrix, A, stored in packed format, to RFP format. This routine is intended for possible use in conjunction with routines from Chapters F06, F07 and F16 where some routines that use triangular matrices store them in RFP format. The RFP storage format is described in Section 3.3.3 in the F07 Chapter Introduction and the packed storage format is described in Section 3.3.2 in the F07 Chapter Introduction.

4 References

Gustavson F G, Waśniewski J, Dongarra J J and Langou J (2010) Rectangular full packed format for Cholesky's algorithm: factorization, solution, and inversion ACM Trans. Math. Software 37, 2

5 Arguments

1:   TRANSR – CHARACTER(1)Input
On entry: specifies whether the normal RFP representation of A or its conjugate transpose is stored.
TRANSR='N'
The RFP representation of the matrix A is stored.
TRANSR='C'
The conjugate transpose of the RFP representation of the matrix A is stored.
Constraint: TRANSR='N' or 'C'.
2:   UPLO – CHARACTER(1)Input
On entry: specifies whether A is upper or lower triangular.
UPLO='U'
A is upper triangular.
UPLO='L'
A is lower triangular.
Constraint: UPLO='U' or 'L'.
3:   N – INTEGERInput
On entry: n, the order of the matrix A.
Constraint: N≥0.
4:   AP N×N+1/2 – COMPLEX (KIND=nag_wp) arrayInput
On entry: the n by n triangular matrix A, packed by columns.
More precisely,
  • if UPLO='U', the upper triangle of A must be stored with element A ij in AP i+j j-1/2 for i≤j;
  • if UPLO='L', the lower triangle of A must be stored with element A ij in AP i+2 n-jj-1/2 for i≥j.
5:   AR N×N+1/2 – COMPLEX (KIND=nag_wp) arrayOutput
On exit: the upper or lower n by n triangular matrix A (as specified by UPLO) in either normal or transposed RFP format (as specified by TRANSR). The storage format is described in Section 3.3.3 in the F07 Chapter Introduction.
6:   INFO – INTEGEROutput
On exit: INFO=0 unless the routine detects an error (see Section 6).

6 Error Indicators and Warnings

-999<INFO<0
If INFO=-i, argument i had an illegal value. An explanatory message is output, and execution of the program is terminated.
INFO=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

Not applicable.

8 Parallelism and Performance

F01VKF (ZTPTTF) is not threaded in any implementation.

9 Further Comments

None.

10 Example

This example reads in a triangular matrix in packed format and copies it to RFP format.

10.1 Program Text

Program Text (f01vkfe.f90)

10.2 Program Data

Program Data (f01vkfe.d)

10.3 Program Results

Program Results (f01vkfe.r)

F01 Chapter Contents
F01 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F01VLF (DTFTTP) : NAG Library, Mark 26

F01 Chapter Contents
F01 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F01VLF (DTFTTP)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F01VLF (DTFTTP) copies a real triangular matrix, stored in a Rectangular Full Packed (RFP) format array, to a standard packed format array.

2 Specification

SUBROUTINE F01VLF ( TRANSR, UPLO, N, AR, AP, INFO)
INTEGER | N, INFO
REAL (KIND=nag_wp) | AR(N*(N+1)/2), AP(N*(N+1)/2)
CHARACTER(1) | TRANSR, UPLO
The routine may be called by its LAPACK name dtfttp.

3 Description

F01VLF (DTFTTP) packs a real n by n triangular matrix A, stored in RFP format, to packed format. This routine is intended for possible use in conjunction with routines from Chapters F06, F07 and F16 where some routines that use triangular matrices store them in RFP format. The RFP storage format is described in Section 3.3.3 in the F07 Chapter Introduction and the packed storage format is described in Section 3.3.2 in the F07 Chapter Introduction.

4 References

Gustavson F G, Waśniewski J, Dongarra J J and Langou J (2010) Rectangular full packed format for Cholesky's algorithm: factorization, solution, and inversion ACM Trans. Math. Software 37, 2

5 Arguments

1:   TRANSR – CHARACTER(1)Input
On entry: specifies whether the normal RFP representation of A or its transpose is stored.
TRANSR='N'
The RFP representation of the matrix A is stored.
TRANSR='T'
The transpose of the RFP representation of the matrix A is stored.
Constraint: TRANSR='N' or 'T'.
2:   UPLO – CHARACTER(1)Input
On entry: specifies whether A is upper or lower triangular.
UPLO='U'
A is upper triangular.
UPLO='L'
A is lower triangular.
Constraint: UPLO='U' or 'L'.
3:   N – INTEGERInput
On entry: n, the order of the matrix A.
Constraint: N≥0.
4:   AR N×N+1/2 – REAL (KIND=nag_wp) arrayInput
On entry: the upper or lower n by n triangular matrix A (as specified by UPLO) in either normal or transposed RFP format (as specified by TRANSR). The storage format is described in Section 3.3.3 in the F07 Chapter Introduction.
5:   AP N×N+1/2 – REAL (KIND=nag_wp) arrayOutput
On exit: the n by n triangular matrix A, packed by columns.
More precisely,
  • if UPLO='U', the upper triangle of A is stored with element A ij in AP i+j j-1/2 for i≤j;
  • if UPLO='L', the lower triangle of A is stored with element A ij in AP i+2 n-jj-1/2 for i≥j.
6:   INFO – INTEGEROutput
On exit: INFO=0 unless the routine detects an error (see Section 6).

6 Error Indicators and Warnings

-999<INFO<0
If INFO=-i, argument i had an illegal value. An explanatory message is output, and execution of the program is terminated.
INFO=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

Not applicable.

8 Parallelism and Performance

F01VLF (DTFTTP) is not threaded in any implementation.

9 Further Comments

None.

10 Example

This example reads in a triangular matrix in RFP format and copies it to packed format.

10.1 Program Text

Program Text (f01vlfe.f90)

10.2 Program Data

Program Data (f01vlfe.d)

10.3 Program Results

Program Results (f01vlfe.r)

F01 Chapter Contents
F01 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F01VMF (ZTFTTP) : NAG Library, Mark 26

F01 Chapter Contents
F01 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F01VMF (ZTFTTP)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F01VMF (ZTFTTP) copies a complex triangular matrix, stored in a Rectangular Full Packed (RFP) format array, to a standard packed format array.

2 Specification

SUBROUTINE F01VMF ( TRANSR, UPLO, N, AR, AP, INFO)
INTEGER | N, INFO
COMPLEX (KIND=nag_wp) | AR(N*(N+1)/2), AP(N*(N+1)/2)
CHARACTER(1) | TRANSR, UPLO
The routine may be called by its LAPACK name ztfttp.

3 Description

F01VMF (ZTFTTP) packs a complex n by n triangular matrix A, stored in RFP format, to packed format. This routine is intended for possible use in conjunction with routines from Chapters F06, F07 and F16 where some routines that use triangular matrices store them in RFP format. The RFP storage format is described in Section 3.3.3 in the F07 Chapter Introduction and the packed storage format is described in Section 3.3.2 in the F07 Chapter Introduction.

4 References

Gustavson F G, Waśniewski J, Dongarra J J and Langou J (2010) Rectangular full packed format for Cholesky's algorithm: factorization, solution, and inversion ACM Trans. Math. Software 37, 2

5 Arguments

1:   TRANSR – CHARACTER(1)Input
On entry: specifies whether the normal RFP representation of A or its conjugate transpose is stored.
TRANSR='N'
The RFP representation of the matrix A is stored.
TRANSR='C'
The conjugate transpose of the RFP representation of the matrix A is stored.
Constraint: TRANSR='N' or 'C'.
2:   UPLO – CHARACTER(1)Input
On entry: specifies whether A is upper or lower triangular.
UPLO='U'
A is upper triangular.
UPLO='L'
A is lower triangular.
Constraint: UPLO='U' or 'L'.
3:   N – INTEGERInput
On entry: n, the order of the matrix A.
Constraint: N≥0.
4:   AR N×N+1/2 – COMPLEX (KIND=nag_wp) arrayInput
On entry: the upper or lower n by n triangular matrix A (as specified by UPLO) in either normal or transposed RFP format (as specified by TRANSR). The storage format is described in Section 3.3.3 in the F07 Chapter Introduction.
5:   AP N×N+1/2 – COMPLEX (KIND=nag_wp) arrayOutput
On exit: the n by n triangular matrix A, packed by columns.
More precisely,
  • if UPLO='U', the upper triangle of A is stored with element A ij in AP i+j j-1/2 for i≤j;
  • if UPLO='L', the lower triangle of A is stored with element A ij in AP i+2 n-jj-1/2 for i≥j.
6:   INFO – INTEGEROutput
On exit: INFO=0 unless the routine detects an error (see Section 6).

6 Error Indicators and Warnings

-999<INFO<0
If INFO=-i, argument i had an illegal value. An explanatory message is output, and execution of the program is terminated.
INFO=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

Not applicable.

8 Parallelism and Performance

F01VMF (ZTFTTP) is not threaded in any implementation.

9 Further Comments

None.

10 Example

This example reads in a triangular matrix in RFP format and copies it to packed format.

10.1 Program Text

Program Text (f01vmfe.f90)

10.2 Program Data

Program Data (f01vmfe.d)

10.3 Program Results

Program Results (f01vmfe.r)

F01 Chapter Contents
F01 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F01ZAF : NAG Library, Mark 26

F01 Chapter Contents
F01 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F01ZAF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F01ZAF copies a real triangular matrix stored in a packed one-dimensional array into an unpacked two-dimensional array, or vice versa.

2 Specification

SUBROUTINE F01ZAF ( JOB, UPLO, DIAG, N, A, LDA, B, IFAIL)
INTEGER | N, LDA, IFAIL
REAL (KIND=nag_wp) | A(LDA,N), B((N*(N+1))/2)
CHARACTER(1) | JOB, UPLO, DIAG

3 Description

F01ZAF unpacks a triangular matrix stored in a vector into a two-dimensional array, or packs a triangular matrix stored in a two-dimensional array into a vector. The matrix is packed by column. This routine is intended for possible use in conjunction with routines from Chapters F06, F07 and F08 where some routines that use triangular matrices store them in the packed form described below.

4 References

None.

5 Arguments

1:   JOB – CHARACTER(1)Input
On entry: specifies whether the triangular matrix is to be packed or unpacked.
JOB='P' (Pack)
The matrix is to be packed into array B.
JOB='U' (Unpack)
The matrix is to be unpacked into array A.
Constraint: JOB='P' or 'U'.
2:   UPLO – CHARACTER(1)Input
On entry: specifies the type of the matrix to be copied
UPLO='L' (Lower)
The matrix is lower triangular. In this case the packed vector holds, or will hold on exit, the matrix elements in the following order: 1,1,2,1,…,N,1, 2,2,3,2,…,N,2, etc..
UPLO='U' (Upper)
The matrix is upper triangular. In this case the packed vector holds, or will hold on exit, the matrix elements in the following order: 1,1, 1,2, 2,2, 1,3, 2,3, 3,3, 1,4, etc..
Constraint: UPLO='L' or 'U'.
3:   DIAG – CHARACTER(1)Input
On entry: must specify whether the diagonal elements of the matrix are to be copied.
DIAG='B' (Blank)
The diagonal elements of the matrix are not referenced and not copied.
DIAG='U' (Unit diagonal)
The diagonal elements of the matrix are not referenced, but are assumed all to be unity, and are copied as such.
DIAG='N' (Non-unit diagonal)
The diagonal elements of the matrix are referenced and copied.
Constraint: DIAG='B', 'U' or 'N'.
4:   N – INTEGERInput
On entry: n, the number of rows and columns of the triangular matrix.
Constraint: N>0.
5:   A LDAN – REAL (KIND=nag_wp) arrayInput/Output
On entry: if JOB='P', then the leading N by N part of A must contain the matrix to be copied, stored in unpacked form, in the upper or lower triangle depending on argument UPLO. The opposite triangle of A is not referenced and need not be assigned.
On exit: if JOB='U', then the leading N by N part of array A contains the copied matrix, stored in unpacked form, in the upper or lower triangle depending on argument UPLO. The opposite triangle of A is not referenced.
6:   LDA – INTEGERInput
On entry: the first dimension of the array A as declared in the (sub)program from which F01ZAF is called.
Constraint: LDA≥N.
7:   B N×N+1/2 – REAL (KIND=nag_wp) arrayInput/Output
On entry: if JOB='U', then B must contain the triangular matrix packed by column.
On exit: if JOB='P', then B contains the triangular matrix packed by column.
Note that B must have space for the diagonal elements of the matrix, even if these are not stored.
8:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, JOB≠'P' or 'U'.
IFAIL=2
On entry, UPLO≠'L' or 'U'.
IFAIL=3
On entry, DIAG≠'N', 'U' or 'B'.
IFAIL=4
On entry, N<1.
IFAIL=5
On entry, LDA<N.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

Not applicable.

8 Parallelism and Performance

F01ZAF is not threaded in any implementation.

9 Further Comments

None.

10 Example

This example reads in a triangular matrix A, and copies it to the packed matrix B.

10.1 Program Text

Program Text (f01zafe.f90)

10.2 Program Data

Program Data (f01zafe.d)

10.3 Program Results

Program Results (f01zafe.r)

F01 Chapter Contents
F01 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F01ZBF : NAG Library, Mark 26

F01 Chapter Contents
F01 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F01ZBF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F01ZBF copies a complex triangular matrix stored in a packed one-dimensional array into an unpacked two-dimensional array, or vice versa.

2 Specification

SUBROUTINE F01ZBF ( JOB, UPLO, DIAG, N, A, LDA, B, IFAIL)
INTEGER | N, LDA, IFAIL
COMPLEX (KIND=nag_wp) | A(LDA,N), B((N*(N+1))/2)
CHARACTER(1) | JOB, UPLO, DIAG

3 Description

F01ZBF unpacks a triangular matrix stored in a vector into a two-dimensional array, or packs a triangular matrix stored in a two-dimensional array into a vector. The matrix is packed by column. This routine is intended for possible use in conjunction with routines from Chapters F06, F07 and F08, where some routines that use triangular matrices store them in the packed form described below.

4 References

None.

5 Arguments

1:   JOB – CHARACTER(1)Input
On entry: specifies whether the triangular matrix is to be packed or unpacked.
JOB='P' (Pack)
The matrix is to be packed into array B.
JOB='U' (Unpack)
The matrix is to be unpacked into array A.
Constraint: JOB='P' or 'U'.
2:   UPLO – CHARACTER(1)Input
On entry: specifies the type of the matrix to be copied
UPLO='L' (Lower)
The matrix is lower triangular. In this case the packed vector holds, or will hold on exit, the matrix elements in the following order: 1,1,2,1,…,N,1, 2,2,3,2,…,N,2, etc..
UPLO='U' (Upper)
The matrix is upper triangular. In this case the packed vector holds, or will hold on exit, the matrix elements in the following order: 1,1, 1,2, 2,2, 1,3, 2,3, 3,3, 1,4, etc..
Constraint: UPLO='L' or 'U'.
3:   DIAG – CHARACTER(1)Input
On entry: must specify whether the diagonal elements of the matrix are to be copied.
DIAG='B' (Blank)
The diagonal elements of the matrix are not referenced and not copied.
DIAG='U' (Unit diagonal)
The diagonal elements of the matrix are not referenced, but are assumed all to be unity, and are copied as such.
DIAG='N' (Non-unit diagonal)
The diagonal elements of the matrix are referenced and copied.
Constraint: DIAG='B', 'U' or 'N'.
4:   N – INTEGERInput
On entry: N must specify the number of rows and columns of the triangular matrix.
Constraint: N>0.
5:   A LDAN – COMPLEX (KIND=nag_wp) arrayInput/Output
On entry: if JOB='P', then the leading N by N part of A must contain the matrix to be copied, stored in unpacked form, in the upper or lower triangle depending on argument UPLO. The opposite triangle of A is not referenced and need not be assigned.
On exit: if JOB='U', then the leading N by N part of array A contains the copied matrix, stored in unpacked form, in the upper or lower triangle depending on argument UPLO. The opposite triangle of A is not referenced.
6:   LDA – INTEGERInput
On entry: the first dimension of the array A as declared in the (sub)program from which F01ZBF is called.
Constraint: LDA≥N.
7:   B N×N+1/2 – COMPLEX (KIND=nag_wp) arrayInput/Output
On entry: if JOB='U', then B must contain the triangular matrix packed by column.
On exit: if JOB='P', then B contains the triangular matrix packed by column.
Note that B must have space for the diagonal elements of the matrix, even if these are not stored.
8:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, JOB≠'P' or 'U'.
IFAIL=2
On entry, UPLO≠'L' or 'U'.
IFAIL=3
On entry, DIAG≠'N', 'U' or 'B'.
IFAIL=4
On entry, N<1.
IFAIL=5
On entry, LDA<N.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

Not applicable.

8 Parallelism and Performance

F01ZBF is not threaded in any implementation.

9 Further Comments

None.

10 Example

This example reads in a triangular matrix A, and copies it to the packed matrix B.

10.1 Program Text

Program Text (f01zbfe.f90)

10.2 Program Data

Program Data (f01zbfe.d)

10.3 Program Results

Program Results (f01zbfe.r)

F01 Chapter Contents
F01 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F01ZCF : NAG Library, Mark 26

F01 Chapter Contents
F01 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F01ZCF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F01ZCF copies a real band matrix stored in a packed array into an unpacked array, or vice versa.

2 Specification

SUBROUTINE F01ZCF ( JOB, M, N, KL, KU, A, LDA, B, LDB, IFAIL)
INTEGER | M, N, KL, KU, LDA, LDB, IFAIL
REAL (KIND=nag_wp) | A(LDA,N), B(LDB,*)
CHARACTER(1) | JOB

3 Description

F01ZCF unpacks a band matrix that is stored in a packed array, or packs a band matrix that is stored in an unpacked array. The band matrix has m rows, n columns, kl nonzero subdiagonals, and ku nonzero superdiagonals. This routine is intended for possible use in conjunction with routines from Chapters F06, F07 and F08, where routines that use band matrices store them in the packed form described below.

4 References

None.

5 Arguments

1:   JOB – CHARACTER(1)Input
On entry: specifies whether the band matrix is to be packed or unpacked.
JOB='P' (Pack)
The band matrix is to be packed into array B.
JOB='U' (Unpack)
The band matrix is to be unpacked into array A.
Constraint: JOB='P' or 'U'.
2:   M – INTEGERInput
3:   N – INTEGERInput
On entry: m and n, the number of rows and columns of the band matrix, respectively.
Constraints:
  • M>0;
  • N>0.
4:   KL – INTEGERInput
On entry: kl, the number of subdiagonals of the band matrix.
Constraint: KL≥0.
5:   KU – INTEGERInput
On entry: ku, the number of superdiagonals of the band matrix.
Constraint: KU≥0.
6:   A LDAN – REAL (KIND=nag_wp) arrayInput/Output
On entry: if JOB='P', then the leading m by n part of A must contain the band matrix stored in unpacked form. Elements of the array that lie outside the banded part of the matrix are not referenced and need not be assigned.
On exit: if JOB='U', then the leading m by n part of A contains the band matrix stored in unpacked form. Elements of the leading m by n part of A that are not within the banded part of the matrix are assigned the value zero.
7:   LDA – INTEGERInput
On entry: the first dimension of the array A as declared in the (sub)program from which F01ZCF is called.
Constraint: LDA≥M.
8:   B LDB* – REAL (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array B must be at least min M+KU,N.
On entry: if JOB='U', then B must contain the band matrix in packed form, in the leading kl+ku+1 by min m+ku,n part of the array. The matrix is packed column by column, with the leading diagonal of the matrix in row ku+1 of B, the first superdiagonal starting at position 2 in row ku, the first subdiagonal starting at position 1 in row ku+2, and so on. Elements of B that are not needed to store the band matrix, for instance the leading ku by ku triangle, are not referenced and need not be assigned.
On exit: if JOB='P', then B contains the band matrix stored in packed form. Elements of B that are not needed to store the band matrix are not referenced.
9:   LDB – INTEGERInput
On entry: the first dimension of the array B as declared in the (sub)program from which F01ZCF is called.
Constraint: LDB≥KL+KU+1.
10:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, JOB≠'P' or 'U'.
IFAIL=2
On entry, KL<0.
IFAIL=3
On entry, KU<0.
IFAIL=4
On entry, LDA<M.
IFAIL=5
On entry, LDB<KL+KU+1.
IFAIL=6
On entry, | M<1,
or | N<1.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

Not applicable.

8 Parallelism and Performance

F01ZCF is not threaded in any implementation.

9 Further Comments

None.

10 Example

This example reads a matrix A in unpacked form, and copies it to the packed matrix B.

10.1 Program Text

Program Text (f01zcfe.f90)

10.2 Program Data

Program Data (f01zcfe.d)

10.3 Program Results

Program Results (f01zcfe.r)

F01 Chapter Contents
F01 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F01ZDF : NAG Library, Mark 26

F01 Chapter Contents
F01 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F01ZDF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F01ZDF copies a complex band matrix stored in a packed array into an unpacked array, or vice versa.

2 Specification

SUBROUTINE F01ZDF ( JOB, M, N, KL, KU, A, LDA, B, LDB, IFAIL)
INTEGER | M, N, KL, KU, LDA, LDB, IFAIL
COMPLEX (KIND=nag_wp) | A(LDA,N), B(LDB,*)
CHARACTER(1) | JOB

3 Description

F01ZDF unpacks a band matrix that is stored in a packed array, or packs a band matrix that is stored in an unpacked array. The band matrix has m rows, n columns, kl nonzero subdiagonals, and ku nonzero superdiagonals. This routine is intended for possible use in conjunction with routines from Chapters F06, F07 and F08, where routines that use band matrices store them in the packed form described below.

4 References

None.

5 Arguments

1:   JOB – CHARACTER(1)Input
On entry: specifies whether the band matrix is to be packed or unpacked.
JOB='P' (Pack)
The band matrix is to be packed into array B.
JOB='U' (Unpack)
The band matrix is to be unpacked into array A.
Constraint: JOB='P' or 'U'.
2:   M – INTEGERInput
3:   N – INTEGERInput
On entry: m and n, the number of rows and columns of the band matrix, respectively.
Constraints:
  • M>0;
  • N>0.
4:   KL – INTEGERInput
On entry: kl, the number of subdiagonals of the band matrix.
Constraint: KL≥0.
5:   KU – INTEGERInput
On entry: ku, the number of superdiagonals of the band matrix.
Constraint: KU≥0.
6:   A LDAN – COMPLEX (KIND=nag_wp) arrayInput/Output
On entry: if JOB='P', then the leading m by n part of A must contain the band matrix stored in unpacked form. Elements of the array that lie outside the banded part of the matrix are not referenced and need not be assigned.
On exit: if JOB='U', then the leading m by n part of A contains the band matrix stored in unpacked form. Elements of the leading m by n part of A that are not within the banded part of the matrix are assigned the value zero.
7:   LDA – INTEGERInput
On entry: the first dimension of the array A as declared in the (sub)program from which F01ZDF is called.
Constraint: LDA≥M.
8:   B LDB* – COMPLEX (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array B must be at least min M+KU,N.
On entry: if JOB='U', then B must contain the band matrix in packed form, in the leading kl+ku+1 by min m+ku,n part of the array. The matrix is packed column by column, with the leading diagonal of the matrix in row ku+1 of B, the first superdiagonal starting at position 2 in row ku, the first subdiagonal starting at position 1 in row ku+2, and so on. Elements of B that are not needed to store the band matrix, for instance the leading ku by ku triangle, are not referenced and need not be assigned.
On exit: if JOB='P', then B contains the band matrix stored in packed form. Elements of B that are not needed to store the band matrix are not referenced.
9:   LDB – INTEGERInput
On entry: the first dimension of the array B as declared in the (sub)program from which F01ZDF is called.
Constraint: LDB≥KL+KU+1.
10:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, JOB≠'P' or 'U'.
IFAIL=2
On entry, KL<0.
IFAIL=3
On entry, KU<0.
IFAIL=4
On entry, LDA<M.
IFAIL=5
On entry, LDB<KL+KU+1.
IFAIL=6
On entry, | M<1,
or | N<1.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

Not applicable.

8 Parallelism and Performance

F01ZDF is not threaded in any implementation.

9 Further Comments

None.

10 Example

This example reads a matrix A in unpacked form, and copies it to the packed matrix B.

10.1 Program Text

Program Text (f01zdfe.f90)

10.2 Program Data

Program Data (f01zdfe.d)

10.3 Program Results

Program Results (f01zdfe.r)

F01 Chapter Contents
F01 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F02 Chapter Contents : NAG Library Manual, Mark 26

F02 Chapter Introduction
NAG Library Manual

NAG Library Chapter Contents

F02 – Eigenvalues and Eigenvectors

F02 Chapter Introduction – a description of the Chapter and an overview of the algorithms available

Routine Name | Mark of Introduction | Purpose
F02ECF Example Text Example Data | 17 | nagf_eigen_real_gen_eigsys Selected eigenvalues and eigenvectors of real nonsymmetric matrix (Black Box)
F02EKF Example Text Example Data | 24 | nagf_eigen_real_gen_sparse_arnoldi Selected eigenvalues and eigenvectors of a real sparse general matrix
F02FJF Example Text Example Data | 11 | nagf_eigen_real_symm_sparse_eigsys Selected eigenvalues and eigenvectors of sparse symmetric eigenproblem (Black Box)
F02FKF Example Text Example Data | 25 | nagf_eigen_real_symm_sparse_arnoldi Selected eigenvalues and eigenvectors of a real symmetric sparse matrix
F02GCF Example Text Example Data | 17 | nagf_eigen_complex_gen_eigsys Selected eigenvalues and eigenvectors of complex nonsymmetric matrix (Black Box)
F02JCF Example Text Example Data | 25 | nagf_eigen_real_gen_quad Solves the quadratic eigenvalue problem for real matrices
F02JQF Example Text Example Data | 25 | nagf_eigen_complex_gen_quad Solves the quadratic eigenvalue problem for complex matrices
F02SDF Example Text Example Data | 8 | nagf_eigen_withdraw_real_band_geneig Eigenvector of generalized real banded eigenproblem by inverse iteration Note: this routine is scheduled for withdrawal at Mark 27, see Advice on Replacement Calls for Withdrawn/Superseded Routines for further information.
F02WDF Example Text Example Data | 8 | nagf_eigen_withdraw_real_gen_qu_svd Returns the Householder factorization of a real rectangular m by n matrix. Part or all of the singular value decomposition may also be returned Note: this routine is scheduled for withdrawal at Mark 27, see Advice on Replacement Calls for Withdrawn/Superseded Routines for further information.
F02WGF Example Text Example Data | 22 | nagf_eigen_real_gen_partialsvd Computes leading terms in the singular value decomposition of a real general matrix; also computes corresponding left and right singular vectors
F02WUF Example Text Example Data | 14 | nagf_eigen_real_triang_svd SVD of real upper triangular matrix (Black Box)
F02XUF Example Text Example Data | 13 | nagf_eigen_complex_triang_svd SVD of complex upper triangular matrix (Black Box)
F02 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F02ECF : NAG Library, Mark 26

F02 Chapter Contents
F02 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F02ECF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F02ECF computes selected eigenvalues and eigenvectors of a real general matrix.

2 Specification

SUBROUTINE F02ECF ( CRIT, N, A, LDA, WL, WU, MEST, M, WR, WI, VR, LDVR, VI, LDVI, WORK, LWORK, IWORK, BWORK, IFAIL)
INTEGER | N, LDA, MEST, M, LDVR, LDVI, LWORK, IWORK(N), IFAIL
REAL (KIND=nag_wp) | A(LDA,N), WL, WU, WR(N), WI(N), VR(LDVR,MEST), VI(LDVI,MEST), WORK(LWORK)
LOGICAL | BWORK(N)
CHARACTER(1) | CRIT

3 Description

F02ECF computes selected eigenvalues and the corresponding right eigenvectors of a real general matrix A:
A xi = λi xi .
Eigenvalues λi may be selected either by modulus, satisfying:
wl ≤ λi ≤ wu ,
or by real part, satisfying:
wl ≤ Re λi ≤ wu .
Note that even though A is real, λi and xi may be complex. If xi is an eigenvector corresponding to a complex eigenvalue λi, then the complex conjugate vector x-i is the eigenvector corresponding to the complex conjugate eigenvalue λ-i. The eigenvalues in a complex conjugate pair λi and λ-i are either both selected or both not selected.

4 References

Golub G H and Van Loan C F (1996) Matrix Computations (3rd Edition) Johns Hopkins University Press, Baltimore

5 Arguments

1:   CRIT – CHARACTER(1)Input
On entry: indicates the criterion for selecting eigenvalues.
CRIT='M'
Eigenvalues are selected according to their moduli: wl≤λi≤wu.
CRIT='R'
Eigenvalues are selected according to their real parts: wl≤Re λi≤wu.
Constraint: CRIT='M' or 'R'.
2:   N – INTEGERInput
On entry: n, the order of the matrix A.
Constraint: N≥0.
3:   A LDAN – REAL (KIND=nag_wp) arrayInput/Output
On entry: the n by n general matrix A.
On exit: contains the Hessenberg form of the balanced input matrix A′ (see Section 9).
4:   LDA – INTEGERInput
On entry: the first dimension of the array A as declared in the (sub)program from which F02ECF is called.
Constraint: LDA≥max 1,N.
5:   WL – REAL (KIND=nag_wp)Input
6:   WU – REAL (KIND=nag_wp)Input
On entry: wl and wu, the lower and upper bounds on the criterion for the selected eigenvalues (see CRIT).
Constraint: WU>WL.
7:   MEST – INTEGERInput
On entry: the second dimension of the arrays VR and VI as declared in the (sub)program from which F02ECF is called. MEST must be an upper bound on m, the number of eigenvalues and eigenvectors selected. No eigenvectors are computed if MEST<m.
Constraint: MEST≥max 1,m.
8:   M – INTEGEROutput
On exit: m, the number of eigenvalues actually selected.
9:   WR N – REAL (KIND=nag_wp) arrayOutput
10:   WI N – REAL (KIND=nag_wp) arrayOutput
On exit: the first M elements of WR and WI hold the real and imaginary parts, respectively, of the selected eigenvalues; elements M+1 to N contain the other eigenvalues. Complex conjugate pairs of eigenvalues are stored in consecutive elements of the arrays, with the eigenvalue having positive imaginary part first. See also Section 9.
11:   VR LDVRMEST – REAL (KIND=nag_wp) arrayOutput
On exit: contains the real parts of the selected eigenvectors, with the ith column holding the real part of the eigenvector associated with the eigenvalue λi (stored in WR i and WI i).
12:   LDVR – INTEGERInput
On entry: the first dimension of the array VR as declared in the (sub)program from which F02ECF is called.
Constraint: LDVR≥max 1,N.
13:   VI LDVIMEST – REAL (KIND=nag_wp) arrayOutput
On exit: contains the imaginary parts of the selected eigenvectors, with the ith column holding the imaginary part of the eigenvector associated with the eigenvalue λi (stored in WR i and WI i).
14:   LDVI – INTEGERInput
On entry: the first dimension of the array VI as declared in the (sub)program from which F02ECF is called.
Constraint: LDVI≥max 1,N.
15:   WORK LWORK – REAL (KIND=nag_wp) arrayWorkspace
16:   LWORK – INTEGERInput
On entry: the dimension of the array WORK as declared in the (sub)program from which F02ECF is called.
Constraint: LWORK≥max 1,N×N+4.
17:   IWORK N – INTEGER arrayWorkspace
18:   BWORK N – LOGICAL arrayWorkspace
19:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, | CRIT≠'M' or 'R',
or | N<0,
or | LDA<max 1,N,
or | WU≤WL,
or | MEST<1,
or | LDVR<max 1,N,
or | LDVI<max 1,N,
or | LWORK<max 1,N×N+4.
IFAIL=2
The QR algorithm failed to compute all the eigenvalues. No eigenvectors have been computed.
IFAIL=3
There are more than MEST eigenvalues in the specified range. The actual number of eigenvalues in the range is returned in M. No eigenvectors have been computed. Rerun with the second dimension of VR and VI=MEST≥M.
IFAIL=4
Inverse iteration failed to compute all the specified eigenvectors. If an eigenvector failed to converge, the corresponding column of VR and VI is set to zero.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

If λi is an exact eigenvalue, and λ~i is the corresponding computed value, then
λ~i-λi≤c n ε A′2 si,
where c n is a modestly increasing function of n, ε is the machine precision, and si is the reciprocal condition number of λi; A′ is the balanced form of the original matrix A (see Section 9), and A′≤A.
If xi is the corresponding exact eigenvector, and x~i is the corresponding computed eigenvector, then the angle θ x~i,xi between them is bounded as follows:
θ x~i,xi≤c n ε A′2 sepi,
where sepi is the reciprocal condition number of xi.
The condition numbers si and sepi may be computed from the Hessenberg form of the balanced matrix A′ which is returned in the array A. This requires calling F08PEF (DHSEQR) with JOB='S' to compute the Schur form of A′, followed by F08QLF (DTRSNA).

8 Parallelism and Performance

F02ECF is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
F02ECF makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

F02ECF calls routines from LAPACK in Chapter F08. It first balances the matrix, using a diagonal similarity transformation to reduce its norm; and then reduces the balanced matrix A′ to upper Hessenberg form H, using an orthogonal similarity transformation: A′=QH QT. The routine uses the Hessenberg QR algorithm to compute all the eigenvalues of H, which are the same as the eigenvalues of A. It computes the eigenvectors of H which correspond to the selected eigenvalues, using inverse iteration. It premultiplies the eigenvectors by Q to form the eigenvectors of A′; and finally transforms the eigenvectors to those of the original matrix A.
Each eigenvector x (real or complex) is normalized so that x 2=1, and the element of largest absolute value is real and positive.
The inverse iteration routine may make a small perturbation to the real parts of close eigenvalues, and this may shift their moduli just outside the specified bounds. If you are relying on eigenvalues being within the bounds, you should test them on return from F02ECF.
The time taken by the routine is approximately proportional to n 3.
The routine can be used to compute all eigenvalues and eigenvectors, by setting WL large and negative, and WU large and positive.

10 Example

This example computes those eigenvalues of the matrix A whose moduli lie in the range 0.2,0.5, and their corresponding eigenvectors, where
A= 0.35 0.45 -0.14 -0.17 0.09 0.07 -0.54 0.35 -0.44 -0.33 -0.03 0.17 0.25 -0.32 -0.13 0.11 .

10.1 Program Text

Program Text (f02ecfe.f90)

10.2 Program Data

Program Data (f02ecfe.d)

10.3 Program Results

Program Results (f02ecfe.r)

F02 Chapter Contents
F02 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F02EKF : NAG Library, Mark 26

F02 Chapter Contents
F02 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F02EKF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.
Note: this routine uses optional parameters to define choices in the problem specification. If you wish to use default settings for all of the optional parameters, you need only read Sections 1 to 10 of this document. If, however, you wish to reset some or all of the settings this must be done by calling the option setting routine F12ADF from the user-supplied subroutine OPTION. Please refer to Section 11 for a detailed description of the specification of the optional parameters.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results
▸▿ 11 Optional Parameters
11.1 Description of the Optional Parameters

1 Purpose

F02EKF computes selected eigenvalues and eigenvectors of a real sparse general matrix.

2 Specification

SUBROUTINE F02EKF ( N, NNZ, A, ICOLZP, IROWIX, NEV, NCV, SIGMA, MONIT, OPTION, NCONV, W, V, LDV, RESID, IUSER, RUSER, IFAIL)
INTEGER | N, NNZ, ICOLZP(N+1), IROWIX(NNZ), NEV, NCV, NCONV, LDV, IUSER(*), IFAIL
REAL (KIND=nag_wp) | A(NNZ), SIGMA, V(LDV,*), RESID(NEV+1), RUSER(*)
COMPLEX (KIND=nag_wp) | W(NCV)
EXTERNAL | MONIT, OPTION

3 Description

F02EKF computes selected eigenvalues and the corresponding right eigenvectors of a real sparse general matrix A:
A wi = λi wi .
A specified number, n ev, of eigenvalues λi, or the shifted inverses μi=1/λi-σ, may be selected either by largest or smallest modulus, largest or smallest real part, or, largest or smallest imaginary part. Convergence is generally faster when selecting larger eigenvalues, smaller eigenvalues can always be selected by choosing a zero inverse shift (σ=0.0). When eigenvalues closest to a given real value are required then the shifted inverses of largest magnitude should be selected with shift equal to the required real value.
Note that even though A is real, λi and wi may be complex. If wi is an eigenvector corresponding to a complex eigenvalue λi, then the complex conjugate vector w-i is the eigenvector corresponding to the complex conjugate eigenvalue λ-i. The eigenvalues in a complex conjugate pair λi and λ-i are either both selected or both not selected.
The sparse matrix A is stored in compressed column storage (CCS) format. See Section 2.1.3 in the F11 Chapter Introduction.
F02EKF uses an implicitly restarted Arnoldi iterative method to converge approximations to a set of required eigenvalues and corresponding eigenvectors. Further algorithmic information is given in Section 9 while a fuller discussion is provided in the F12 Chapter Introduction. If shifts are to be performed then operations using shifted inverse matrices are performed using a direct sparse solver; further information on the solver used is provided in the F11 Chapter Introduction.

4 References

Golub G H and Van Loan C F (1996) Matrix Computations (3rd Edition) Johns Hopkins University Press, Baltimore
Lehoucq R B, Sorensen D C and Yang C (1998) ARPACK Users' Guide: Solution of Large-scale Eigenvalue Problems with Implicitly Restarted Arnoldi Methods SIAM, Philidelphia

5 Arguments

1:   N – INTEGERInput
On entry: n, the order of the matrix A.
Constraint: N≥0.
2:   NNZ – INTEGERInput
On entry: the dimension of the array A and The number of nonzero elements of the matrix A and, if a nonzero shifted inverse is to be applied, all diagonal elements. Each nonzero is counted once in the latter case.
Constraint: 0≤NNZ≤N 2.
3:   A NNZ – REAL (KIND=nag_wp) arrayInput/Output
On entry: the array of nonzero elements (and diagonal elements if a nonzero inverse shift is to be applied) of the n by n general matrix A.
On exit: if a nonzero shifted inverse is to be applied then the diagonal elements of A have the shift value, as supplied in SIGMA, subtracted.
4:   ICOLZP N+1 – INTEGER arrayInput
On entry: ICOLZP i contains the index in A of the start of column i, for i=1,2,…,n; ICOLZP N+1 must contain the value NNZ+1. Thus the number of nonzero elements in column i of A is ICOLZP i+1-ICOLZP i; when shifts are applied this includes diagonal elements irrespective of value. See Section 2.1.3 in the F11 Chapter Introduction.
5:   IROWIX NNZ – INTEGER arrayInput
On entry: IROWIX i contains the row index for each entry in A. See Section 2.1.3 in the F11 Chapter Introduction.
6:   NEV – INTEGERInput
On entry: the number of eigenvalues to be computed.
Constraint: 0<NEV<N-1.
7:   NCV – INTEGERInput
On entry: the dimension of the array W as declared in the (sub)program from which F02EKF is called. The number of Arnoldi basis vectors to use during the computation.
At present there is no a priori analysis to guide the selection of NCV relative to NEV. However, it is recommended that NCV≥2×NEV+1. If many problems of the same type are to be solved, you should experiment with increasing NCV while keeping NEV fixed for a given test problem. This will usually decrease the required number of matrix-vector operations but it also increases the work and storage required to maintain the orthogonal basis vectors. The optimal ‘cross-over’ with respect to CPU time is problem dependent and must be determined empirically.
Constraint: NEV+1<NCV≤N.
8:   SIGMA – REAL (KIND=nag_wp)Input
On entry: if the Shifted Inverse Real mode has been selected then SIGMA contains the real shift used; otherwise SIGMA is not referenced. This mode can be selected by setting the appropriate options in the user-supplied subroutine OPTION.
9:   MONIT – SUBROUTINE, supplied by the NAG Library or the user.External Procedure
MONIT is used to monitor the progress of F02EKF. MONIT may be the dummy subroutine F02EKZ if no monitoring is actually required. (F02EKZ is included in the NAG Library.) MONIT is called after the solution of each eigenvalue sub-problem and also just prior to return from F02EKF.
The specification of MONIT is:
SUBROUTINE MONIT ( NCV, NITER, NCONV, W, RZEST, ISTAT, IUSER, RUSER)
INTEGER | NCV, NITER, NCONV, ISTAT, IUSER(*)
REAL (KIND=nag_wp) | RZEST(NCV), RUSER(*)
COMPLEX (KIND=nag_wp) | W(NCV)
1:   NCV – INTEGERInput
On entry: the dimension of the arrays W and RZEST. The number of Arnoldi basis vectors used during the computation.
2:   NITER – INTEGERInput
On entry: the number of the current Arnoldi iteration.
3:   NCONV – INTEGERInput
On entry: the number of converged eigenvalues so far.
4:   W NCV – COMPLEX (KIND=nag_wp) arrayInput
On entry: the first NCONV elements of W contain the converged approximate eigenvalues.
5:   RZEST NCV – REAL (KIND=nag_wp) arrayInput
On entry: the first NCONV elements of RZEST contain the Ritz estimates (error bounds) on the converged approximate eigenvalues.
6:   ISTAT – INTEGERInput/Output
On entry: set to zero.
On exit: if set to a nonzero value F02EKF returns immediately with IFAIL=9.
7:   IUSER* – INTEGER arrayUser Workspace
8:   RUSER* – REAL (KIND=nag_wp) arrayUser Workspace
MONIT is called with the arguments IUSER and RUSER as supplied to F02EKF. You are free to use the arrays IUSER and RUSER to supply information to MONIT as an alternative to using COMMON global variables.
MONIT must either be a module subprogram USEd by, or declared as EXTERNAL in, the (sub)program from which F02EKF is called. Arguments denoted as Input must not be changed by this procedure.
10:   OPTION – SUBROUTINE, supplied by the NAG Library or the user.External Procedure
You can supply non-default options to the Arnoldi eigensolver by repeated calls to F12ADF from within OPTION. (Please note that it is only necessary to call F12ADF; no call to F12AAF is required from within OPTION.) For example, you can set the mode to Shifted Inverse Real, you can increase the Iteration Limit beyond its default and you can print varying levels of detail on the iterative process using Print Level.
If only the default options (including that the eigenvalues of largest magnitude are sought) are to be used then OPTION may be the dummy subroutine F02EKY (F02EKY is included in the NAG Library). See Section 10 for an example of using OPTION to set some non-default options.
The specification of OPTION is:
SUBROUTINE OPTION ( ICOMM, COMM, ISTAT, IUSER, RUSER)
INTEGER | ICOMM(*), ISTAT, IUSER(*)
REAL (KIND=nag_wp) | COMM(*), RUSER(*)
1:   ICOMM* – INTEGER arrayCommunication Array
On entry: contains details of the default option set. This array must be passed as argument ICOMM in any call to F12ADF.
On exit: contains data on the current options set which may be altered from the default set via calls to F12ADF.
2:   COMM* – REAL (KIND=nag_wp) arrayCommunication Array
On entry: contains details of the default option set. This array must be passed as argument COMM in any call to F12ADF.
On exit: contains data on the current options set which may be altered from the default set via calls to F12ADF.
3:   ISTAT – INTEGERInput/Output
On entry: set to zero.
On exit: if set to a nonzero value F02EKF returns immediately with IFAIL=10.
4:   IUSER* – INTEGER arrayUser Workspace
5:   RUSER* – REAL (KIND=nag_wp) arrayUser Workspace
OPTION is called with the arguments IUSER and RUSER as supplied to F02EKF. You are free to use the arrays IUSER and RUSER to supply information to OPTION as an alternative to using COMMON global variables.
OPTION must either be a module subprogram USEd by, or declared as EXTERNAL in, the (sub)program from which F02EKF is called.
11:   NCONV – INTEGEROutput
On exit: the number of converged approximations to the selected eigenvalues. On successful exit, this will normally be either NEV or NEV+1 depending on the number of complex conjugate pairs of eigenvalues returned.
12:   W NCV – COMPLEX (KIND=nag_wp) arrayOutput
On exit: the first NCONV elements contain the converged approximations to the selected eigenvalues. Since complex conjugate pairs of eigenvalues appear together, it is possible (given an odd number of converged real eigenvalues) for F02EKF to return one more eigenvalue than requested.
13:   V LDV* – REAL (KIND=nag_wp) arrayOutput
Note: the second dimension of the array V must be at least NCV.
On exit: contains the eigenvectors associated with the eigenvalue λi, for i=1,2,…,NCONV (stored in W). For a real eigenvalue, λj, the corresponding eigenvector is real and is stored in V ij, for i=1,2,…,n. For complex conjugate pairs of eigenvalues, w j+1=wj-, the real and imaginary parts of the corresponding eigenvectors are stored, respectively, in V ij and V ij, for i=1,2,…,n. The imaginary parts stored are for the first of the conjugate pair of eigenvectors; the other eigenvector in the pair is obtained by negating these imaginary parts.
14:   LDV – INTEGERInput
On entry: the first dimension of the array V as declared in the (sub)program from which F02EKF is called.
Constraint: LDV≥N.
15:   RESID NEV+1 – REAL (KIND=nag_wp) arrayOutput
On exit: the residual A wi - λi wi 2 for the estimates to the eigenpair λi and wi is returned in RESID i, for i=1,2,…,NCONV.
16:   IUSER* – INTEGER arrayUser Workspace
IUSER is not used by F02EKF, but is passed directly to MONIT and OPTION and may be used to pass information to these routines as an alternative to using COMMON global variables.
17:   RUSER* – REAL (KIND=nag_wp) arrayUser Workspace
RUSER is not used by F02EKF, but is passed directly to MONIT and OPTION and may be used to pass information to these routines as an alternative to using COMMON global variables.
18:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, N=value.
Constraint: N>0.
IFAIL=2
On entry, NNZ=value.
Constraint: NNZ>0.
On entry, NNZ=value and N=value.
Constraint: NNZ≤N×N.
IFAIL=3
On entry, in shifted inverse mode, the jth diagonal element of A is not defined, for j=value.
IFAIL=4
On entry, for i=value, ICOLZP i=value and ICOLZP i+1=value.
Constraint: ICOLZP i<ICOLZP i+1.
On entry, ICOLZP 1=value.
Constraint: ICOLZP 1=1.
On entry, ICOLZP N+1=value and NNZ=value.
Constraint: ICOLZP N+1=NNZ+1.
IFAIL=5
On entry, in specification of column value, and for j=value, IROWIX j=value and IROWIX j+1=value.
Constraint: IROWIX j<IROWIX j+1.
IFAIL=6
On entry, NEV=value.
Constraint: NEV>0.
IFAIL=7
On entry, NCV=value and N=value.
Constraint: NCV≤N.
On entry, NCV=value and NEV=value.
Constraint: NCV>NEV+1.
IFAIL=8
On entry, the matrix A-σ×I is nearly numerically singular and could not be inverted. Try perturbing the value of σ. Norm of matrix =value, Reciprocal condition number =value.
On entry, the matrix A-σ×I is numerically singular and could not be inverted. Try perturbing the value of σ.
IFAIL=9
User requested termination in MONIT, ISTAT=value.
IFAIL=10
User requested termination in OPTION, ISTAT=value.
IFAIL=14
On entry, LDV=value and N=value.
Constraint: LDV≥N.
IFAIL=21
The maximum number of iterations ≤0, the optional parameter Iteration Limit has been set to value.
IFAIL=22
An internal call to F12ABF returned with IFAIL=2.
This error should not occur. Please contact NAG.
IFAIL=23
An internal call to F12ABF returned with IFAIL=3.
IFAIL=24
The maximum number of iterations has been reached.
The maximum number of iterations =value.
The number of converged eigenvalues =value.
See the routine document for further details.
IFAIL=25
No shifts could be applied during a cycle of the implicitly restarted Arnoldi iteration.
IFAIL=26
Could not build an Arnoldi factorization. The size of the current Arnoldi factorization =value.
IFAIL=27
Error in internal call to compute eigenvalues and corresponding error bounds of the current upper Hessenberg matrix.
Please contact NAG.
IFAIL=32
An internal call to F12ACF returned with IFAIL=2.
IFAIL=33
The number of eigenvalues found to sufficient accuracy is zero.
IFAIL=34
Internal inconsistency in the number of converged Ritz values. Number counted =value, number expected =value.
IFAIL=35
During calculation of a real Schur form, there was a failure to compute value eigenvalues in a total of value iterations.
IFAIL=36
The computed Schur form could not be reordered by an internal call.
This routine returned with IFAIL=value.
Please contact NAG.
IFAIL=37
In calculating eigenvectors, an internal call returned with an error.
Please contact NAG.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

The relative accuracy of a Ritz value (eigenvalue approximation), λ, is considered acceptable if its Ritz estimate ≤Tolerance×λ. The default value for Tolerance is the machine precision given by X02AJF. The Ritz estimates are available via the MONIT subroutine at each iteration in the Arnoldi process, or can be printed by setting option Print Level to a positive value.

8 Parallelism and Performance

F02EKF is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
F02EKF makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

F02EKF calls routines based on the ARPACK suite in Chapter F12. These routines use an implicitly restarted Arnoldi iterative method to converge to approximations to a set of required eigenvalues (see the F12 Chapter Introduction).
In the default Regular mode, only matrix-vector multiplications are performed using the sparse matrix A during the Arnoldi process. Each iteration is therefore cheap computationally, relative to the alternative, Shifted Inverse Real, mode described below. It is most efficient (i.e., the total number of iterations required is small) when the eigenvalues of largest magnitude are sought and these are distinct.
Although there is an option for returning the smallest eigenvalues using this mode (see Smallest Magnitude option), the number of iterations required for convergence will be far greater or the method may not converge at all. However, where convergence is achieved, Regular mode may still prove to be the most efficient since no inversions are required. Where smallest eigenvalues are sought and Regular mode is not suitable, or eigenvalues close to a given real value are sought, the Shifted Inverse Real mode should be used.
If the Shifted Inverse Real mode is used (via a call to F12ADF in OPTION) then the matrix A-σI is used in linear system solves by the Arnoldi process. This is first factorized internally using the direct LU factorization routine F11MEF. The condition number of A-σI is then calculated by a call to F11MGF. If the condition number is too big then the matrix is considered to be nearly singular, i.e., σ is an approximate eigenvalue of A, and the routine exits with an error. In this situation it is normally sufficient to perturb σ by a small amount and call F02EKF again. After successful factorization, subsequent solves are performed by calls to F11MFF.
Finally, F02EKF transforms the eigenvectors. Each eigenvector w (real or complex) is normalized so that w 2=1, and the element of largest absolute value is real.
The monitoring routine MONIT provides some basic information on the convergence of the Arnoldi iterations. Much greater levels of detail on the Arnoldi process are available via option Print Level. If this is set to a positive value then information will be printed, by default, to standard output. The Monitoring option may be used to select a monitoring file by setting the option to a file identification (unit) number associated with Monitoring (see X04ACF).

10 Example

This example computes the four eigenvalues of the matrix A which lie closest to the value σ=5.5 on the real line, and their corresponding eigenvectors, where A is the tridiagonal matrix with elements
a ij = 2+i, j=i 3, j = i-1 -1 + ρ / 2 n+2, j = i+1 ​ with ​ ρ = 10.0.

10.1 Program Text

Program Text (f02ekfe.f90)

10.2 Program Data

Program Data (f02ekfe.d)

10.3 Program Results

Program Results (f02ekfe.r)

11 Optional Parameters

Internally F02EKF calls routines from the suite F12AAF, F12ABF, F12ACF, F12ADF and F12AEF. Several optional parameters for these computational routines define choices in the problem specification or the algorithm logic. In order to reduce the number of formal arguments of F02EKF these optional parameters are also used here and have associated default values that are usually appropriate. Therefore, you need only specify those optional parameters whose values are to be different from their default values.
Optional parameters may be specified via the user-supplied subroutine OPTION in the call to F02EKF. OPTION must be coded such that one call to F12ADF is necessary to set each optional parameter. All optional parameters you do not specify are set to their default values.
The remainder of this section can be skipped if you wish to use the default values for all optional parameters.
The following is a list of the optional parameters available. A full description of each optional parameter is provided in Section 11.1.
  • Advisory
  • Defaults
  • Iteration Limit
  • Largest Imaginary
  • Largest Magnitude
  • Largest Real
  • List
  • Monitoring
  • Nolist
  • Print Level
  • Regular
  • Shifted Inverse Real
  • Smallest Imaginary
  • Smallest Magnitude
  • Smallest Real
  • Tolerance

11.1 Description of the Optional Parameters

For each option, we give a summary line, a description of the optional parameter and details of constraints.
The summary line contains:
  • the keywords, where the minimum abbreviation of each keyword is underlined;
  • a parameter value, where the letters a, i and r denote options that take character, integer and real values respectively;
  • the default value, where the symbol ε is a generic notation for machine precision (see X02AJF).
Keywords and character values are case and white space insensitive.
Advisory i Default =0
If the optional parameter List is set then optional parameter specifications are listed in a List file by setting the option to a file identification (unit) number associated with Advisory messages (see X04ABF and X04ACF).
Defaults
This special keyword may be used to reset all optional parameters to their default values.
Iteration Limit i Default = 300
The limit on the number of Arnoldi iterations that can be performed before F02EKF exits with IFAIL≠0.
Largest Magnitude Default
Largest Imaginary
Largest Real
Smallest Imaginary
Smallest Magnitude
Smallest Real
The Arnoldi iterative method converges on a number of eigenvalues with given properties. The default is to compute the eigenvalues of largest magnitude using Largest Magnitude. Alternatively, eigenvalues may be chosen which have Largest Real part, Largest Imaginary part, Smallest Magnitude, Smallest Real part or Smallest Imaginary part.
Note that these options select the eigenvalue properties for eigenvalues of OP the linear operator determined by the computational mode and problem type.
Nolist Default
List
Normally each optional parameter specification is not printed to the advisory channel as it is supplied. Optional parameter List may be used to enable printing and optional parameter Nolist may be used to suppress the printing.
Monitoring i Default = -1
If i>0, monitoring information is output to channel number i during the solution of each problem; this may be the same as the Advisory channel number. The type of information produced is dependent on the value of Print Level, see the description of the optional parameter Print Level for details of the information produced. Please see X04ACF to associate a file with a given channel number.
Print Level i Default = 0
This controls the amount of printing produced by F02EKF as follows.
=0 | No output except error messages.
>0 | The set of selected options.
=2 | Problem and timing statistics when all calls to F12ABF have been completed.
≥5 | A single line of summary output at each Arnoldi iteration.
≥10 | If Monitoring>0, then at each iteration, the length and additional steps of the current Arnoldi factorization and the number of converged Ritz values; during re-orthogonalization, the norm of initial/restarted starting vector.
≥20 | Problem and timing statistics on final exit from F12ABF. If Monitoring>0, then at each iteration, the number of shifts being applied, the eigenvalues and estimates of the Hessenberg matrix H, the size of the Arnoldi basis, the wanted Ritz values and associated Ritz estimates and the shifts applied; vector norms prior to and following re-orthogonalization.
≥30 | If Monitoring>0, then on final iteration, the norm of the residual; when computing the Schur form, the eigenvalues and Ritz estimates both before and after sorting; for each iteration, the norm of residual for compressed factorization and the compressed upper Hessenberg matrix H; during re-orthogonalization, the initial/restarted starting vector; during the Arnoldi iteration loop, a restart is flagged and the number of the residual requiring iterative refinement; while applying shifts, the indices of the shifts being applied.
≥40 | If Monitoring>0, then during the Arnoldi iteration loop, the Arnoldi vector number and norm of the current residual; while applying shifts, key measures of progress and the order of H; while computing eigenvalues of H, the last rows of the Schur and eigenvector matrices; when computing implicit shifts, the eigenvalues and Ritz estimates of H.
≥50 | If Monitoring>0, then during Arnoldi iteration loop: norms of key components and the active column of H, norms of residuals during iterative refinement, the final upper Hessenberg matrix H; while applying shifts: number of shifts, shift values, block indices, updated matrix H; while computing eigenvalues of H: the matrix H, the computed eigenvalues and Ritz estimates.
Regular Default
Shifted Inverse Real
These options define the computational mode which in turn defines the form of operation OP x to be performed.
Given a standard eigenvalue problem in the form Ax=λx then the following modes are available with the appropriate operator OP x.
Regular | OP=A
Shifted Inverse Real | OP=A-σI-1 where σ is real
Tolerance r Default = ε
An approximate eigenvalue has deemed to have converged when the corresponding Ritz estimate is within Tolerance relative to the magnitude of the eigenvalue.
F02 Chapter Contents
F02 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F02FJF : NAG Library, Mark 26

F02 Chapter Contents
F02 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F02FJF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F02FJF finds eigenvalues and eigenvectors of a real sparse symmetric or generalized symmetric eigenvalue problem.

2 Specification

SUBROUTINE F02FJF ( N, M, K, NOITS, TOL, DOT, IMAGE, MONIT, NOVECS, X, LDX, D, WORK, LWORK, RUSER, LRUSER, IUSER, LIUSER, IFAIL)
INTEGER | N, M, K, NOITS, NOVECS, LDX, LWORK, LRUSER, IUSER(LIUSER), LIUSER, IFAIL
REAL (KIND=nag_wp) | TOL, DOT, X(LDX,K), D(K), WORK(LWORK), RUSER(LRUSER)
EXTERNAL | DOT, IMAGE, MONIT

3 Description

F02FJF finds the m eigenvalues of largest absolute value and the corresponding eigenvectors for the real eigenvalue problem
Cx=λ x (1)
where C is an n by n matrix such that
BC=CT B (2)
for a given positive definite matrix B. C is said to be B-symmetric. Different specifications of C allow for the solution of a variety of eigenvalue problems. For example, when
C=A  and  B=I  where  A=AT
the routine finds the m eigenvalues of largest absolute magnitude for the standard symmetric eigenvalue problem
Ax=λx. (3)
The routine is intended for the case where A is sparse.
As a second example, when
C=B-1 A
where
A=AT
the routine finds the m eigenvalues of largest absolute magnitude for the generalized symmetric eigenvalue problem
Ax=λBx. (4)
The routine is intended for the case where A and B are sparse.
The routine does not require C explicitly, but C is specified via IMAGE which, given an n-element vector z, computes the image w given by
w=Cz.
For instance, in the above example, where C=B-1 A, IMAGE will need to solve the positive definite system of equations Bw=Az for w.
To find the m eigenvalues of smallest absolute magnitude of (3) we can choose C=A-1 and hence find the reciprocals of the required eigenvalues, so that IMAGE will need to solve Aw=z for w, and correspondingly for (4) we can choose C=A-1 B and solve Aw=Bz for w.
A table of examples of choice of IMAGE is given in Table 1. It should be remembered that the routine also returns the corresponding eigenvectors and that B is positive definite. Throughout A is assumed to be symmetric and, where necessary, nonsingularity is also assumed.
Eigenvalues Required | Problem
 | Ax=λx B=I | Ax=λBx | ABx=λx
Largest | Compute w=Az | Solve Bw=Az | Compute w=ABz
Smallest (Find 1/λ) | Solve Aw=z | Solve Aw=Bz | Solve Av=z, Bw=v
Furthest from σ (Find λ-σ) | Compute w=A-σI z | Solve Bw=A-σB z | Compute w=AB-σI z
Closest to σ (Find 1/λ-σ) | Solve A-σI w=z | Solve A-σB w=Bz | Solve AB-σI w=z
Table 1
The Requirement of IMAGE for Various Problems.
The matrix B also need not be supplied explicitly, but is specified via DOT which, given n-element vectors z and w, computes the generalized dot product wT Bz.
F02FJF is based upon routine SIMITZ (see Nikolai (1979)), which is itself a derivative of the Algol procedure ritzit (see Rutishauser (1970)), and uses the method of simultaneous (subspace) iteration. (See Parlett (1998) for a description, analysis and advice on the use of the method.)
The routine performs simultaneous iteration on k>m vectors. Initial estimates to p≤k eigenvectors, corresponding to the p eigenvalues of C of largest absolute value, may be supplied to F02FJF. When possible k should be chosen so that the kth eigenvalue is not too close to the m required eigenvalues, but if k is initially chosen too small then F02FJF may be re-entered, supplying approximations to the k eigenvectors found so far and with k then increased.
At each major iteration F02FJF solves an r by r (r≤k) eigenvalue sub-problem in order to obtain an approximation to the eigenvalues for which convergence has not yet occurred. This approximation is refined by Chebyshev acceleration.

4 References

Nikolai P J (1979) Algorithm 538: Eigenvectors and eigenvalues of real generalized symmetric matrices by simultaneous iteration ACM Trans. Math. Software 5 118–125
Parlett B N (1998) The Symmetric Eigenvalue Problem SIAM, Philadelphia
Rutishauser H (1969) Computational aspects of F L Bauer's simultaneous iteration method Numer. Math. 13 4–13
Rutishauser H (1970) Simultaneous iteration method for symmetric matrices Numer. Math. 16 205–223

5 Arguments

1:   N – INTEGERInput
On entry: n, the order of the matrix C.
Constraint: N≥1.
2:   M – INTEGERInput/Output
On entry: m, the number of eigenvalues required.
Constraint: M≥1.
On exit: m′, the number of eigenvalues actually found. It is equal to m if IFAIL=0 on exit, and is less than m if IFAIL=2, 3 or 4. See Sections 6 and 9 for further information.
3:   K – INTEGERInput
On entry: the number of simultaneous iteration vectors to be used. Too small a value of K may inhibit convergence, while a larger value of K incurs additional storage and additional work per iteration.
Suggested value: K=M+4 will often be a reasonable choice in the absence of better information.
Constraint: M<K≤N.
4:   NOITS – INTEGERInput/Output
On entry: the maximum number of major iterations (eigenvalue sub-problems) to be performed. If NOITS≤0, the value 100 is used in place of NOITS.
On exit: the number of iterations actually performed.
5:   TOL – REAL (KIND=nag_wp)Input
On entry: a relative tolerance to be used in accepting eigenvalues and eigenvectors. If the eigenvalues are required to about t significant figures, TOL should be set to about 10-t. di is accepted as an eigenvalue as soon as two successive approximations to di differ by less than d~i×TOL/10, where d~i is the latest approximation to di. Once an eigenvalue has been accepted, an eigenvector is accepted as soon as difi/di-dk<TOL, where fi is the normalized residual of the current approximation to the eigenvector (see Section 9 for further information). The values of the fi and di can be printed from MONIT. If TOL is supplied outside the range (ε,1.0), where ε is the machine precision, the value ε is used in place of TOL.
6:   DOT – REAL (KIND=nag_wp) FUNCTION, supplied by the user.External Procedure
DOT must return the value wT Bz for given vectors w and z. For the standard eigenvalue problem, where B=I, DOT must return the dot product wT z.
The specification of DOT is:
FUNCTION DOT ( IFLAG, N, Z, W, RUSER, LRUSER, IUSER, LIUSER)
REAL (KIND=nag_wp) DOT
INTEGER | IFLAG, N, LRUSER, IUSER(LIUSER), LIUSER
REAL (KIND=nag_wp) | Z(N), W(N), RUSER(LRUSER)
1:   IFLAG – INTEGERInput/Output
On entry: is always non-negative.
On exit: may be used as a flag to indicate a failure in the computation of wT Bz. If IFLAG is negative on exit from DOT, F02FJF will exit immediately with IFAIL set to IFLAG. Note that in this case DOT must still be assigned a value.
2:   N – INTEGERInput
On entry: the number of elements in the vectors z and w and the order of the matrix B.
3:   Z N – REAL (KIND=nag_wp) arrayInput
On entry: the vector z for which wT Bz is required.
4:   W N – REAL (KIND=nag_wp) arrayInput
On entry: the vector w for which wT Bz is required.
5:   RUSER LRUSER – REAL (KIND=nag_wp) arrayUser Workspace
DOT is called with the argument RUSER as supplied to F02FJF. You are free to use the array RUSER to supply information to DOT as an alternative to using COMMON global variables.
6:   LRUSER – INTEGERInput
On entry: the dimension of the array RUSER as declared in the (sub)program from which F02FJF is called.
7:   IUSER LIUSER – INTEGER arrayUser Workspace
DOT is called with the argument IUSER as supplied to F02FJF. You are free to use the array IUSER to supply information to DOT as an alternative to using COMMON global variables.
8:   LIUSER – INTEGERInput
On entry: the dimension of the array IUSER as declared in the (sub)program from which F02FJF is called.
DOT must either be a module subprogram USEd by, or declared as EXTERNAL in, the (sub)program from which F02FJF is called. Arguments denoted as Input must not be changed by this procedure.
7:   IMAGE – SUBROUTINE, supplied by the user.External Procedure
IMAGE must return the vector w=Cz for a given vector z.
The specification of IMAGE is:
SUBROUTINE IMAGE ( IFLAG, N, Z, W, RUSER, LRUSER, IUSER, LIUSER)
INTEGER | IFLAG, N, LRUSER, IUSER(LIUSER), LIUSER
REAL (KIND=nag_wp) | Z(N), W(N), RUSER(LRUSER)
1:   IFLAG – INTEGERInput/Output
On entry: is always non-negative.
On exit: may be used as a flag to indicate a failure in the computation of w. If IFLAG is negative on exit from IMAGE, F02FJF will exit immediately with IFAIL set to IFLAG.
2:   N – INTEGERInput
On entry: n, the number of elements in the vectors w and z, and the order of the matrix C.
3:   Z N – REAL (KIND=nag_wp) arrayInput
On entry: the vector z for which Cz is required.
4:   W N – REAL (KIND=nag_wp) arrayOutput
On exit: the vector w=Cz.
5:   RUSER LRUSER – REAL (KIND=nag_wp) arrayUser Workspace
IMAGE is called with the argument RUSER as supplied to F02FJF. You are free to use the array RUSER to supply information to IMAGE as an alternative to using COMMON global variables.
6:   LRUSER – INTEGERInput
On entry: the dimension of the array RUSER as declared in the (sub)program from which F02FJF is called.
7:   IUSER LIUSER – INTEGER arrayUser Workspace
IMAGE is called with the argument IUSER as supplied to F02FJF. You are free to use the array IUSER to supply information to IMAGE as an alternative to using COMMON global variables.
8:   LIUSER – INTEGERInput
On entry: the dimension of the array IUSER as declared in the (sub)program from which F02FJF is called.
IMAGE must either be a module subprogram USEd by, or declared as EXTERNAL in, the (sub)program from which F02FJF is called. Arguments denoted as Input must not be changed by this procedure.
8:   MONIT – SUBROUTINE, supplied by the NAG Library or the user.External Procedure
MONIT is used to monitor the progress of F02FJF. MONIT may be the dummy subroutine F02FJZ if no monitoring is actually required. (F02FJZ is included in the NAG Library.) MONIT is called after the solution of each eigenvalue sub-problem and also just prior to return from F02FJF. The arguments ISTATE and NEXTIT allow selective printing by MONIT.
The specification of MONIT is:
SUBROUTINE MONIT ( ISTATE, NEXTIT, NEVALS, NEVECS, K, F, D)
INTEGER | ISTATE, NEXTIT, NEVALS, NEVECS, K
REAL (KIND=nag_wp) | F(K), D(K)
1:   ISTATE – INTEGERInput
On entry: specifies the state of F02FJF.
ISTATE=0
No eigenvalue or eigenvector has just been accepted.
ISTATE=1
One or more eigenvalues have been accepted since the last call to MONIT.
ISTATE=2
One or more eigenvectors have been accepted since the last call to MONIT.
ISTATE=3
One or more eigenvalues and eigenvectors have been accepted since the last call to MONIT.
ISTATE=4
Return from F02FJF is about to occur.
2:   NEXTIT – INTEGERInput
On entry: the number of the next iteration.
3:   NEVALS – INTEGERInput
On entry: the number of eigenvalues accepted so far.
4:   NEVECS – INTEGERInput
On entry: the number of eigenvectors accepted so far.
5:   K – INTEGERInput
On entry: k, the number of simultaneous iteration vectors.
6:   F K – REAL (KIND=nag_wp) arrayInput
On entry: a vector of error quantities measuring the state of convergence of the simultaneous iteration vectors. See TOL and Section 9 for further details. Each element of F is initially set to the value 4.0 and an element remains at 4.0 until the corresponding vector is tested.
7:   D K – REAL (KIND=nag_wp) arrayInput
On entry: D i contains the latest approximation to the absolute value of the ith eigenvalue of C.
MONIT must either be a module subprogram USEd by, or declared as EXTERNAL in, the (sub)program from which F02FJF is called. Arguments denoted as Input must not be changed by this procedure.
9:   NOVECS – INTEGERInput
On entry: the number of approximate vectors that are being supplied in X. If NOVECS is outside the range 0,K, the value 0 is used in place of NOVECS.
10:   X LDXK – REAL (KIND=nag_wp) arrayInput/Output
On entry: if 0<NOVECS≤K, the first NOVECS columns of X must contain approximations to the eigenvectors corresponding to the NOVECS eigenvalues of largest absolute value of C. Supplying approximate eigenvectors can be useful when reasonable approximations are known, or when F02FJF is being restarted with a larger value of K. Otherwise it is not necessary to supply approximate vectors, as simultaneous iteration vectors will be generated randomly by F02FJF.
On exit: if IFAIL=0, 2, 3 or 4, the first m′ columns contain the eigenvectors corresponding to the eigenvalues returned in the first m′ elements of D; and the next k-m′-1 columns contain approximations to the eigenvectors corresponding to the approximate eigenvalues returned in the next k-m′-1 elements of D. Here m′ is the value returned in M, the number of eigenvalues actually found. The kth column is used as workspace.
11:   LDX – INTEGERInput
On entry: the first dimension of the array X as declared in the (sub)program from which F02FJF is called.
Constraint: LDX≥N.
12:   D K – REAL (KIND=nag_wp) arrayOutput
On exit: if IFAIL=0, 2, 3 or 4, the first m′ elements contain the first m′ eigenvalues in decreasing order of magnitude; and the next k-m′-1 elements contain approximations to the next k-m′-1 eigenvalues. Here m′ is the value returned in M, the number of eigenvalues actually found. D k contains the value e where -e,e is the latest interval over which Chebyshev acceleration is performed.
13:   WORK LWORK – REAL (KIND=nag_wp) arrayWorkspace
14:   LWORK – INTEGERInput
On entry: the dimension of the array WORK as declared in the (sub)program from which F02FJF is called.
Constraint: LWORK≥3×K+max K×K,2×N.
15:   RUSER LRUSER – REAL (KIND=nag_wp) arrayUser Workspace
RUSER is not used by F02FJF, but is passed directly to DOT and IMAGE and may be used to pass information to these routines as an alternative to using COMMON global variables.
16:   LRUSER – INTEGERInput
On entry: the dimension of the array RUSER as declared in the (sub)program from which F02FJF is called.
Constraint: LRUSER≥1.
17:   IUSER LIUSER – INTEGER arrayUser Workspace
IUSER is not used by F02FJF, but is passed directly to DOT and IMAGE and may be used to pass information to these routines as an alternative to using COMMON global variables.
18:   LIUSER – INTEGERInput
On entry: the dimension of the array IUSER as declared in the (sub)program from which F02FJF is called.
Constraint: LIUSER≥1.
19:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, because for this routine the values of the output arguments may be useful even if IFAIL≠0 on exit, the recommended value is -1. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL<0
A negative value of IFAIL indicates an exit from F02FJF because you have set IFLAG negative in DOT or IMAGE. The value of IFAIL will be the same as your setting of IFLAG.
IFAIL=1
On entry, | N<1,
or | M<1,
or | M≥K,
or | K>N,
or | LDX<N,
or | LWORK<3×K+max K×K,2×N,
or | LRUSER<1,
or | LIUSER<1.
IFAIL=2
Not all the requested eigenvalues and vectors have been obtained. Approximations to the rth eigenvalue are oscillating rapidly indicating that severe cancellation is occurring in the rth eigenvector and so M is returned as r-1. A restart with a larger value of K may permit convergence.
IFAIL=3
Not all the requested eigenvalues and vectors have been obtained. The rate of convergence of the remaining eigenvectors suggests that more than NOITS iterations would be required and so the input value of M has been reduced. A restart with a larger value of K may permit convergence.
IFAIL=4
Not all the requested eigenvalues and vectors have been obtained. NOITS iterations have been performed. A restart, possibly with a larger value of K, may permit convergence.
IFAIL=5
This error is very unlikely to occur, but indicates that convergence of the eigenvalue sub-problem has not taken place. Restarting with a different set of approximate vectors may allow convergence. If this error occurs you should check carefully that F02FJF is being called correctly.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

Eigenvalues and eigenvectors will normally be computed to the accuracy requested by the argument TOL, but eigenvectors corresponding to small or to close eigenvalues may not always be computed to the accuracy requested by the argument TOL. Use of the MONIT to monitor acceptance of eigenvalues and eigenvectors is recommended.

8 Parallelism and Performance

F02FJF is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
F02FJF makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The time taken by F02FJF will be principally determined by the time taken to solve the eigenvalue sub-problem and the time taken by DOT and IMAGE. The time taken to solve an eigenvalue sub-problem is approximately proportional to n k 2. It is important to be aware that several calls to DOT and IMAGE may occur on each major iteration.
As can be seen from Table 1, many applications of F02FJF will require the IMAGE to solve a system of linear equations. For example, to find the smallest eigenvalues of Ax=λ Bx, IMAGE needs to solve equations of the form Aw=Bz for w and routines from Chapters F01 and F04 will frequently be useful in this context. In particular, if A is a positive definite variable band matrix, F04MCF may be used after A has been factorized by F01MCF. Thus factorization need be performed only once prior to calling F02FJF. An illustration of this type of use is given in the example program.
An approximation d~h, to the ith eigenvalue, is accepted as soon as d~h and the previous approximation differ by less than d~h×TOL/ 10. Eigenvectors are accepted in groups corresponding to clusters of eigenvalues that are equal, or nearly equal, in absolute value and that have already been accepted. If dr is the last eigenvalue in such a group and we define the residual rj as
rj=C xj-yr
where yr is the projection of C xj, with respect to B, onto the space spanned by x 1,x 2,…, xr, and xj is the current approximation to the jth eigenvector, then the value fi returned in MONIT is given by
fi = max rj B / C xj B   x B 2 = xT Bx
and each vector in the group is accepted as an eigenvector if
dr fr/dr-e<TOL,
where e is the current approximation to d~k. The values of the fi are systematically increased if the convergence criteria appear to be too strict. See Rutishauser (1970) for further details.
The algorithm implemented by F02FJF differs slightly from SIMITZ (see Nikolai (1979)) in that the eigenvalue sub-problem is solved using the singular value decomposition of the upper triangular matrix R of the Gram–Schmidt factorization of C xr, rather than forming RT R.

10 Example

This example finds the four eigenvalues of smallest absolute value and corresponding eigenvectors for the generalized symmetric eigenvalue problem Ax=λBx, where A and B are the 16 by 16 matrices
A=-14 -4 1 1 1 -4 1 1 1 -4 1 1 1 -4 1 1 1 1 -4 1 1 1 1 -4 1 1 1 1 -4 1 1 1 1 -4 1 1 1 1 -4 1 1 1 1 -4 1 1 1 1 -4 1 1 1 1 -4 1 1 1 1 -4 1 1 1 -4 1 1 1 -4 1 1 1 -4
B=-12 -2 1 1 -2 1 1 -2 1 1 -2 1 1 -2 1 1 -2 1 1 -2 1 1 -2 1 1 -2 1 1 -2 1 1 -2 1 1 -2 1 1 -2 1 1 -2 1 1 -2 1 1 -2
TOL is taken as 0.0001 and 6 iteration vectors are used. F11JAF is used to factorize the matrix A, prior to calling F02FJF, and F11JCF is used within IMAGE to solve the equations Aw=Bz for w.
Output from MONIT occurs each time ISTATE is nonzero. Note that the required eigenvalues are the reciprocals of the eigenvalues returned by F02FJF.

10.1 Program Text

Program Text (f02fjfe.f90)

10.2 Program Data

Program Data (f02fjfe.d)

10.3 Program Results

Program Results (f02fjfe.r)

F02 Chapter Contents
F02 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F02FKF : NAG Library, Mark 26

F02 Chapter Contents
F02 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F02FKF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.
Note: this routine uses optional parameters to define choices in the problem specification. If you wish to use default settings for all of the optional parameters, you need only read Sections 1 to 10 of this document. If, however, you wish to reset some or all of the settings this must be done by calling the option setting routine F12FDF from the user-supplied subroutine OPTION. Please refer to Section 11 for a detailed description of the specification of the optional parameters.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
▸▿ 9 Further Comments
9.1 Additional Licensor
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results
▸▿ 11 Optional Parameters
11.1 Description of the Optional Parameters

1 Purpose

F02FKF computes selected eigenvalues and eigenvectors of a real sparse symmetric matrix.

2 Specification

SUBROUTINE F02FKF ( N, NNZ, A, IROW, ICOL, NEV, NCV, SIGMA, MONIT, OPTION, NCONV, W, V, LDV, RESID, IUSER, RUSER, IFAIL)
INTEGER | N, NNZ, IROW(NNZ), ICOL(NNZ), NEV, NCV, NCONV, LDV, IUSER(*), IFAIL
REAL (KIND=nag_wp) | A(NNZ), SIGMA, W(NCV), V(LDV,*), RESID(NEV), RUSER(*)
EXTERNAL | MONIT, OPTION

3 Description

F02FKF computes selected eigenvalues and the corresponding right eigenvectors of a real sparse symmetric matrix A:
A vi = λi vi .
A specified number, n ev, of eigenvalues λi, or the shifted inverses μi=1/λi-σ, may be selected either by largest or smallest modulus, largest or smallest value, or, largest and smallest values (both ends). Convergence is generally faster when selecting larger eigenvalues, smaller eigenvalues can always be selected by choosing a zero inverse shift (σ=0.0). When eigenvalues closest to a given value are required then the shifted inverses of largest magnitude should be selected with shift equal to the required value.
The sparse matrix A is stored in symmetric coordinate storage (SCS) format. See Section 2.1.2 in the F11 Chapter Introduction.
F02FKF uses an implicitly restarted Arnoldi (Lanczos) iterative method to converge approximations to a set of required eigenvalues and corresponding eigenvectors. Further algorithmic information is given in Section 9 while a fuller discussion is provided in the F12 Chapter Introduction. If shifts are to be performed then operations using shifted inverse matrices are performed using a direct sparse solver.

4 References

Golub G H and Van Loan C F (1996) Matrix Computations (3rd Edition) Johns Hopkins University Press, Baltimore
HSL (2011) A collection of Fortran codes for large-scale scientific computation http://www.hsl.rl.ac.uk/
Lehoucq R B, Sorensen D C and Yang C (1998) ARPACK Users' Guide: Solution of Large-scale Eigenvalue Problems with Implicitly Restarted Arnoldi Methods SIAM, Philidelphia

5 Arguments

1:   N – INTEGERInput
On entry: n, the order of the matrix A.
Constraint: N>0.
2:   NNZ – INTEGERInput
On entry: the dimension of the array A as declared in the (sub)program from which F02FKF is called.The number of nonzero elements in the lower triangular part of the matrix A.
Constraint: 1≤NNZ≤N×N+1/2.
3:   A NNZ – REAL (KIND=nag_wp) arrayInput
On entry: the array of nonzero elements of the lower triangular part of the n by n symmetric matrix A.
4:   IROW NNZ – INTEGER arrayInput
5:   ICOL NNZ – INTEGER arrayInput
On entry: the row and column indices of the elements supplied in array A.
If IROW k=i and ICOL k=j then A ij is stored in A k. IROW does not need to be ordered, an internal call to F11ZBF forces the correct ordering.
Constraint:
IROW and ICOL must satisfy these constraints:
1≤IROW i≤N and 1≤ICOL i≤IROW i, for i=1,2,…,NNZ.
6:   NEV – INTEGERInput
On entry: the number of eigenvalues to be computed.
Constraint: 0<NEV<N-1.
7:   NCV – INTEGERInput
On entry: the dimension of the array W as declared in the (sub)program from which F02FKF is called. The number of Arnoldi basis vectors to use during the computation.
At present there is no a priori analysis to guide the selection of NCV relative to NEV. However, it is recommended that NCV≥2×NEV+1. If many problems of the same type are to be solved, you should experiment with increasing NCV while keeping NEV fixed for a given test problem. This will usually decrease the required number of matrix-vector operations but it also increases the work and storage required to maintain the orthogonal basis vectors. The optimal ‘cross-over’ with respect to computation time is problem dependent and must be determined empirically.
Constraint: NEV<NCV≤N.
8:   SIGMA – REAL (KIND=nag_wp)Input
On entry: if the Shifted Inverse mode has been selected then SIGMA contains the real shift used; otherwise SIGMA is not referenced. This mode can be selected by setting the appropriate options in the user-supplied subroutine OPTION.
9:   MONIT – SUBROUTINE, supplied by the NAG Library or the user.External Procedure
MONIT is used to monitor the progress of F02FKF. MONIT may be the dummy subroutine F02FKZ if no monitoring is actually required. (F02FKZ is included in the NAG Library.) MONIT is called after the solution of each eigenvalue sub-problem and also just prior to return from F02FKF.
The specification of MONIT is:
SUBROUTINE MONIT ( NCV, NITER, NCONV, W, RZEST, ISTAT, IUSER, RUSER)
INTEGER | NCV, NITER, NCONV, ISTAT, IUSER(*)
REAL (KIND=nag_wp) | W(NCV), RZEST(NCV), RUSER(*)
1:   NCV – INTEGERInput
On entry: the dimension of the arrays W and RZEST. The number of Arnoldi basis vectors used during the computation.
2:   NITER – INTEGERInput
On entry: the number of the current Arnoldi iteration.
3:   NCONV – INTEGERInput
On entry: the number of converged eigenvalues so far.
4:   W NCV – REAL (KIND=nag_wp) arrayInput
On entry: the first NCONV elements of W contain the converged approximate eigenvalues.
5:   RZEST NCV – REAL (KIND=nag_wp) arrayInput
On entry: the first NCONV elements of RZEST contain the Ritz estimates (error bounds) on the converged approximate eigenvalues.
6:   ISTAT – INTEGERInput/Output
On entry: set to zero.
On exit: if set to a nonzero value F02FKF returns immediately with IFAIL=9.
7:   IUSER* – INTEGER arrayUser Workspace
8:   RUSER* – REAL (KIND=nag_wp) arrayUser Workspace
MONIT is called with the arguments IUSER and RUSER as supplied to F02FKF. You are free to use the arrays IUSER and RUSER to supply information to MONIT as an alternative to using COMMON global variables.
MONIT must either be a module subprogram USEd by, or declared as EXTERNAL in, the (sub)program from which F02FKF is called. Arguments denoted as Input must not be changed by this procedure.
10:   OPTION – SUBROUTINE, supplied by the NAG Library or the user.External Procedure
You can supply non-default options to the Arnoldi eigensolver by repeated calls to F12FDF from within OPTION. (Please note that it is only necessary to call F12FDF; no call to F12FAF is required from within OPTION.) For example, you can set the mode to Shifted Inverse, you can increase the Iteration Limit beyond its default and you can print varying levels of detail on the iterative process using Print Level.
If only the default options (including that the eigenvalues of largest magnitude are sought) are to be used then OPTION may be the dummy subroutine F02EKY (F02EKY is included in the NAG Library). See Section 10 for an example of using OPTION to set some non-default options.
The specification of OPTION is:
SUBROUTINE OPTION ( ICOMM, COMM, ISTAT, IUSER, RUSER)
INTEGER | ICOMM(*), ISTAT, IUSER(*)
REAL (KIND=nag_wp) | COMM(*), RUSER(*)
1:   ICOMM* – INTEGER arrayCommunication Array
On entry: contains details of the default option set. This array must be passed as argument ICOMM in any call to F12FDF.
On exit: contains data on the current options set which may be altered from the default set via calls to F12FDF.
2:   COMM* – REAL (KIND=nag_wp) arrayCommunication Array
On entry: contains details of the default option set. This array must be passed as argument COMM in any call to F12FDF.
On exit: contains data on the current options set which may be altered from the default set via calls to F12FDF.
3:   ISTAT – INTEGERInput/Output
On entry: set to zero.
On exit: if set to a nonzero value F02FKF returns immediately with IFAIL=10.
4:   IUSER* – INTEGER arrayUser Workspace
5:   RUSER* – REAL (KIND=nag_wp) arrayUser Workspace
OPTION is called with the arguments IUSER and RUSER as supplied to F02FKF. You are free to use the arrays IUSER and RUSER to supply information to OPTION as an alternative to using COMMON global variables.
OPTION must either be a module subprogram USEd by, or declared as EXTERNAL in, the (sub)program from which F02FKF is called.
11:   NCONV – INTEGEROutput
On exit: the number of converged approximations to the selected eigenvalues. On successful exit, this will normally be NEV.
12:   W NCV – REAL (KIND=nag_wp) arrayOutput
On exit: the first NCONV elements contain the converged approximations to the selected eigenvalues.
13:   V LDV* – REAL (KIND=nag_wp) arrayOutput
Note: the second dimension of the array V must be at least NCV.
On exit: contains the eigenvectors associated with the eigenvalue λi, for i=1,2,…,NCONV (stored in W). For eigenvalue, λj, the corresponding eigenvector is stored in V ij, for i=1,2,…,n.
14:   LDV – INTEGERInput
On entry: the first dimension of the array V as declared in the (sub)program from which F02FKF is called.
Constraint: LDV≥N.
15:   RESID NEV – REAL (KIND=nag_wp) arrayOutput
On exit: the residual A wi - λi wi 2 for the estimates to the eigenpair λi and wi is returned in RESID i, for i=1,2,…,NCONV.
16:   IUSER* – INTEGER arrayUser Workspace
IUSER is not used by F02FKF, but is passed directly to MONIT and OPTION and may be used to pass information to these routines as an alternative to using COMMON global variables.
17:   RUSER* – REAL (KIND=nag_wp) arrayUser Workspace
RUSER is not used by F02FKF, but is passed directly to MONIT and OPTION and may be used to pass information to these routines as an alternative to using COMMON global variables.
18:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, N=value.
Constraint: N>0.
IFAIL=2
On entry, NNZ=value.
Constraint: NNZ>0.
On entry, NNZ=value and N=value.
Constraint: NNZ≤N×N+1/2.
IFAIL=4
On entry, for i=value, IROW i=value.
Constraint: 1≤IROW i≤N.
IFAIL=5
On entry, for i=value, ICOL i=value, IROW i=value.
Constraint: 1≤ICOL i≤IROW i.
IFAIL=6
On entry, NEV=value.
Constraint: NEV>0.
On entry, NEV=value and N=value.
Constraint: NEV<N-1.
IFAIL=7
On entry, NCV=value and N=value.
Constraint: NCV≤N.
On entry, NCV=value and NEV=value.
Constraint: NCV>NEV.
IFAIL=8
On entry, the matrix A-σ⁢I is numerically singular and could not be inverted. Try perturbing the value of σ.
IFAIL=9
User requested termination in MONIT, ISTAT=value.
IFAIL=10
User requested termination in OPTION, ISTAT=value.
IFAIL=14
On entry, LDV=value and N=value.
Constraint: LDV≥N.
IFAIL=20
The maximum number of iterations, through the optional parameter Iteration Limit, has been set to a non-positive value.
IFAIL=21
The option Both Ends has been set but only 1 eigenvalue is requested.
IFAIL=22
The maximum number of iterations has been reached.
The maximum number of iterations =value.
The number of converged eigenvalues =value.
See the routine document for further details.
IFAIL=30
A serious error, code value, has occurred in an internal call to value. Check all subroutine calls and array sizes. If the call is correct then please contact NAG for assistance.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

The relative accuracy of a Ritz value (eigenvalue approximation), λ, is considered acceptable if its Ritz estimate ≤Tolerance×λ. The default value for Tolerance is the machine precision given by X02AJF. The Ritz estimates are available via the MONIT subroutine at each iteration in the Arnoldi process, or can be printed by setting option Print Level to a positive value.

8 Parallelism and Performance

F02FKF is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
F02FKF makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

F02FKF calls routines based on the ARPACK suite in Chapter F12. These routines use an implicitly restarted Lanczos iterative method to converge to approximations to a set of required eigenvalues (see the F12 Chapter Introduction).
In the default Regular mode, only matrix-vector multiplications are performed using the sparse matrix A during the Lanczos process; F11XEF can be used to perform this task. Each iteration is therefore cheap computationally, relative to the alternative, Shifted Inverse, mode described below. It is most efficient (i.e., the total number of iterations required is small) when the eigenvalues of largest magnitude are sought and these are distinct.
Although there is an option for returning the smallest eigenvalues using this mode (see Smallest Magnitude option), the number of iterations required for convergence will be far greater or the method may not converge at all. However, where convergence is achieved, Regular mode may still prove to be the most efficient since no inversions are required. Where smallest eigenvalues are sought and Regular mode is not suitable, or eigenvalues close to a given real value are sought, the Shifted Inverse mode should be used.
If the Shifted Inverse mode is used (via a call to F12FDF in OPTION) then the matrix A-σI is used in linear system solves by the Lanczos process. This is first factorized internally using a direct sparse LD LT factorization under the assumption that the matrix is indefinite. If the factorization determines that the matrix is numerically singular then the routine exits with an error. In this situation it is normally sufficient to perturb σ by a small amount and call F02FKF again. After successful factorization, subsequent solves are performed by backsubstitution using the sparse factorization.
Finally, F02FKF transforms the eigenvectors. Each eigenvector w is normalized so that w 2=1.
The monitoring routine MONIT provides some basic information on the convergence of the Lanczos iterations. Much greater levels of detail on the Lanczos process are available via option Print Level. If this is set to a positive value then information will be printed, by default, to standard output. The destination of monitoring information can be changed using the Monitoring option.

9.1 Additional Licensor

The direct sparse LDL T factorization performed in Shifted Inverse mode is performed by an implementation of HSL_MA97 (see HSL (2011)).

10 Example

This example solves Ax = λx in Shifted Inverse mode, where A is obtained from the standard central difference discretization of the one-dimensional Laplacian operator ∂2 u ∂x 2 on 0,1 , with zero Dirichlet boundary conditions.

10.1 Program Text

Program Text (f02fkfe.f90)

10.2 Program Data

Program Data (f02fkfe.d)

10.3 Program Results

Program Results (f02fkfe.r)

11 Optional Parameters

Internally F02FKF calls routines from the suite F12FAF, F12FBF, F12FCF, F12FDF and F12FEF. Several optional parameters for these computational routines define choices in the problem specification or the algorithm logic. In order to reduce the number of formal arguments of F02FKF these optional parameters are also used here and have associated default values that are usually appropriate. Therefore, you need only specify those optional parameters whose values are to be different from their default values.
Optional parameters may be specified via the user-supplied subroutine OPTION in the call to F02FKF. OPTION must be coded such that one call to F12FDF is necessary to set each optional parameter. All optional parameters you do not specify are set to their default values.
The remainder of this section can be skipped if you wish to use the default values for all optional parameters.
The following is a list of the optional parameters available. A full description of each optional parameter is provided in Section 11.1.
  • Advisory
  • Both Ends
  • Defaults
  • Iteration Limit
  • Largest Algebraic
  • Largest Magnitude
  • List
  • Monitoring
  • Nolist
  • Print Level
  • Regular
  • Regular Inverse
  • Shifted Inverse
  • Smallest Algebraic
  • Smallest Magnitude
  • Tolerance

11.1 Description of the Optional Parameters

For each option, we give a summary line, a description of the optional parameter and details of constraints.
The summary line contains:
  • the keywords, where the minimum abbreviation of each keyword is underlined;
  • a parameter value, where the letters a, i and r denote options that take character, integer and real values respectively;
  • the default value, where the symbol ε is a generic notation for machine precision (see X02AJF).
Keywords and character values are case and white space insensitive.
Advisory i Default = the value returned by X04ABF
If the optional parameter List is set then optional parameter specifications are listed in a List file by setting the option to a file identification (unit) number associated with Advisory messages (see X04ABF and X04ACF).
Defaults
This special keyword may be used to reset all optional parameters to their default values.
Iteration Limit i Default = 300
The limit on the number of Lanczos iterations that can be performed before F12FBF exits. If not all requested eigenvalues have converged to within Tolerance and the number of Lanczos iterations has reached this limit then F12FBF exits with an error; F12FCF can still be called subsequently to return the number of converged eigenvalues, the converged eigenvalues and, if requested, the corresponding eigenvectors.
Largest Magnitude Default
Both Ends
Largest Algebraic
Smallest Algebraic
Smallest Magnitude
The Lanczos iterative method converges on a number of eigenvalues with given properties. The default is for F12FBF to compute the eigenvalues of largest magnitude using Largest Magnitude. Alternatively, eigenvalues may be chosen which have Largest Algebraic part, Smallest Magnitude, or Smallest Algebraic part; or eigenvalues which are from Both Ends of the algebraic spectrum.
Nolist Default
List
Normally each optional parameter specification is not listed as it is supplied. This behaviour can be changed using the List and Nolist options.
Monitoring i Default = -1
If i>0, monitoring information is output to channel number i during the solution of each problem; this may be the same as the Advisory channel number. The type of information produced is dependent on the value of Print Level, see the description of the optional parameter Print Level for details of the information produced. Please see X04ACF to associate a file with a given channel number.
Print Level i Default = 0
This controls the amount of printing produced by F02FKF as follows.
=0 | No output except error messages. If you want to suppress all output, set Print Level=0.
>0 | The set of selected options.
=2 | Problem and timing statistics on final exit from F12FBF.
≥5 | A single line of summary output at each Lanczos iteration.
≥10 | If Monitoring is set, then at each iteration, the length and additional steps of the current Lanczos factorization and the number of converged Ritz values; during re-orthogonalization, the norm of initial/restarted starting vector; on a final Lanczos iteration, the number of update iterations taken, the number of converged eigenvalues, the converged eigenvalues and their Ritz estimates.
≥20 | Problem and timing statistics on final exit from F12FBF. If Monitoring>0, Monitoring is set, then at each iteration, the number of shifts being applied, the eigenvalues and estimates of the symmetric tridiagonal matrix H, the size of the Lanczos basis, the wanted Ritz values and associated Ritz estimates and the shifts applied; vector norms prior to and following re-orthogonalization.
≥30 | If Monitoring>0, Monitoring is set, then on final iteration, the norm of the residual; when computing the Schur form, the eigenvalues and Ritz estimates both before and after sorting; for each iteration, the norm of residual for compressed factorization and the symmetric tridiagonal matrix H; during re-orthogonalization, the initial/restarted starting vector; during the Lanczos iteration loop, a restart is flagged and the number of the residual requiring iterative refinement; while applying shifts, some indices.
≥40 | If Monitoring>0, Monitoring is set, then during the Lanczos iteration loop, the Lanczos vector number and norm of the current residual; while applying shifts, key measures of progress and the order of H; while computing eigenvalues of H, the last rows of the Schur and eigenvector matrices; when computing implicit shifts, the eigenvalues and Ritz estimates of H.
≥50 | If Monitoring is set, then during Lanczos iteration loop: norms of key components and the active column of H, norms of residuals during iterative refinement, the final symmetric tridiagonal matrix H; while applying shifts: number of shifts, shift values, block indices, updated tridiagonal matrix H; while computing eigenvalues of H: the diagonals of H, the computed eigenvalues and Ritz estimates.
Note that setting Print Level≥30 can result in very lengthy Monitoring output.
Regular Default
Regular Inverse
Shifted Inverse
These options define the computational mode which in turn defines the form of operation OP x to be performed.
Regular | OP=A
Shifted Inverse | OP=A-σI-1 where σ is real
Regular Inverse | OP=A-1
Tolerance r Default = ε
An approximate eigenvalue has deemed to have converged when the corresponding Ritz estimate is within Tolerance relative to the magnitude of the eigenvalue.
F02 Chapter Contents
F02 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F02GCF : NAG Library, Mark 26

F02 Chapter Contents
F02 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F02GCF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F02GCF computes selected eigenvalues and eigenvectors of a complex general matrix.

2 Specification

SUBROUTINE F02GCF ( CRIT, N, A, LDA, WL, WU, MEST, M, W, V, LDV, WORK, LWORK, RWORK, IWORK, BWORK, IFAIL)
INTEGER | N, LDA, MEST, M, LDV, LWORK, IWORK(N), IFAIL
REAL (KIND=nag_wp) | WL, WU, RWORK(2*N)
COMPLEX (KIND=nag_wp) | A(LDA,*), W(N), V(LDV,MEST), WORK(LWORK)
LOGICAL | BWORK(N)
CHARACTER(1) | CRIT

3 Description

F02GCF computes selected eigenvalues and the corresponding right eigenvectors of a complex general matrix A:
A xi=λixi.
Eigenvalues λi may be selected either by modulus, satisfying
wl≤λi≤wu,
or by real part, satisfying
wl≤Re λi≤wu.

4 References

Golub G H and Van Loan C F (1996) Matrix Computations (3rd Edition) Johns Hopkins University Press, Baltimore

5 Arguments

1:   CRIT – CHARACTER(1)Input
On entry: indicates the criterion for selecting eigenvalues.
CRIT='M'
Eigenvalues are selected according to their moduli: wl≤λi≤wu.
CRIT='R'
Eigenvalues are selected according to their real parts: wl≤Re λi≤wu.
Constraint: CRIT='M' or 'R'.
2:   N – INTEGERInput
On entry: n, the order of the matrix A.
Constraint: N≥0.
3:   A LDA* – COMPLEX (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array A must be at least max 1,N.
On entry: the n by n general matrix A.
On exit: contains the Hessenberg form of the balanced input matrix A′ (see Section 9).
4:   LDA – INTEGERInput
On entry: the first dimension of the array A as declared in the (sub)program from which F02GCF is called.
Constraint: LDA≥max 1,N.
5:   WL – REAL (KIND=nag_wp)Input
6:   WU – REAL (KIND=nag_wp)Input
On entry: wl and wu, the lower and upper bounds on the criterion for the selected eigenvalues (see CRIT).
Constraint: WU>WL.
7:   MEST – INTEGERInput
On entry: the second dimension of the array V as declared in the (sub)program from which F02GCF is called. MEST must be an upper bound on m, the number of eigenvalues and eigenvectors selected. No eigenvectors are computed if MEST<m.
Constraint: MEST≥max 1,m.
8:   M – INTEGEROutput
On exit: m, the number of eigenvalues actually selected.
9:   W N – COMPLEX (KIND=nag_wp) arrayOutput
On exit: the first M elements of W hold the selected eigenvalues; elements M+1 to N contain the other eigenvalues.
10:   V LDVMEST – COMPLEX (KIND=nag_wp) arrayOutput
On exit: contains the selected eigenvectors, with the ith column holding the eigenvector associated with the eigenvalue λi (stored in W i).
11:   LDV – INTEGERInput
On entry: the first dimension of the array V as declared in the (sub)program from which F02GCF is called.
Constraint: LDV≥max 1,N.
12:   WORK LWORK – COMPLEX (KIND=nag_wp) arrayWorkspace
13:   LWORK – INTEGERInput
On entry: the dimension of the array WORK as declared in the (sub)program from which F02GCF is called.
Constraint: LWORK≥max 1,N×N+2.
14:   RWORK 2×N – REAL (KIND=nag_wp) arrayWorkspace
15:   IWORK N – INTEGER arrayWorkspace
16:   BWORK N – LOGICAL arrayWorkspace
17:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, | CRIT≠'M' or 'R',
or | N<0,
or | LDA<max 1,N,
or | WU≤WL,
or | MEST<1,
or | LDV<max 1,N,
or | LWORK<max 1,N×N+2.
IFAIL=2
The QR algorithm failed to compute all the eigenvalues. No eigenvectors have been computed.
IFAIL=3
There are more than MEST eigenvalues in the specified range. The actual number of eigenvalues in the range is returned in M. No eigenvectors have been computed. Rerun with the second dimension of V=MEST≥M.
IFAIL=4
Inverse iteration failed to compute all the specified eigenvectors. If an eigenvector failed to converge, the corresponding column of V is set to zero.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

If λi is an exact eigenvalue, and λ~i is the corresponding computed value, then
λ~i - λi ≤ c n ε A′2 si,
where c n is a modestly increasing function of n, ε is the machine precision, and si is the reciprocal condition number of λi; A′ is the balanced form of the original matrix A (see Section 9), and A′≤A.
If xi is the corresponding exact eigenvector, and x~i is the corresponding computed eigenvector, then the angle θ x~i,xi between them is bounded as follows:
θ x~i,xi≤c n ε A′2 sepi
where sepi is the reciprocal condition number of xi.
The condition numbers si and sepi may be computed from the Hessenberg form of the balanced matrix A′ which is returned in the array A. This requires calling F08PSF (ZHSEQR) with JOB='S' to compute the Schur form of A′, followed by F08QYF (ZTRSNA).

8 Parallelism and Performance

F02GCF is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
F02GCF makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

F02GCF calls routines from LAPACK in Chapter F08. It first balances the matrix, using a diagonal similarity transformation to reduce its norm; and then reduces the balanced matrix A′ to upper Hessenberg form H, using a unitary similarity transformation: A′=QH QH. The routine uses the Hessenberg QR algorithm to compute all the eigenvalues of H, which are the same as the eigenvalues of A. It computes the eigenvectors of H which correspond to the selected eigenvalues, using inverse iteration. It premultiplies the eigenvectors by Q to form the eigenvectors of A′; and finally transforms the eigenvectors to those of the original matrix A.
Each eigenvector x is normalized so that x 2=1, and the element of largest absolute value is real.
The inverse iteration routine may make a small perturbation to the real parts of close eigenvalues, and this may shift their moduli just outside the specified bounds. If you are relying on eigenvalues being within the bounds, you should test them on return from F02GCF.
The time taken by the routine is approximately proportional to n 3.
The routine can be used to compute all eigenvalues and eigenvectors, by setting WL large and negative, and WU large and positive.

10 Example

This example computes those eigenvalues of the matrix A which lie in the range -5.5,+5.5 , and their corresponding eigenvectors, where
A = -3.97-5.04 i -4.11+3.70 i -0.34+1.01 i 1.29-0.86 i 0.34-1.50 i 1.52-0.43 i 1.88-5.38 i 3.36+0.65 i 3.31-3.85 i 2.50+3.45 i 0.88-1.08 i 0.64-1.48 i -1.10+0.82 i 1.81-1.59 i 3.25+1.33 i 1.57-3.44 i .

10.1 Program Text

Program Text (f02gcfe.f90)

10.2 Program Data

Program Data (f02gcfe.d)

10.3 Program Results

Program Results (f02gcfe.r)

F02 Chapter Contents
F02 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F02 Chapter Introduction : NAG Library, Mark 26

F02 Chapter Contents
NAG Library Manual

NAG Library Chapter Introduction

F02 – Eigenvalues and Eigenvectors

▸▿ Contents

1 Scope of the Chapter
▸▿ 2 Background to the Problems
▸▿ 2.1 Standard Eigenvalue Problems
2.1.1 Standard symmetric eigenvalue problems
2.1.2 Standard nonsymmetric eigenvalue problems
2.2 The Singular Value Decomposition
▸▿ 2.3 Generalized Eigenvalue Problems
2.3.1 Generalized symmetric-definite eigenvalue problems
2.3.2 Generalized nonsymmetric eigenvalue problems
2.4 Quadratic eigenvalue problems
▸▿ 3 Recommendations on Choice and Use of Available Routines
3.1 Black Box Routines and General Purpose Routines
3.2 Computing Selected Eigenvalues and Eigenvectors
3.3 Storage Schemes for Symmetric Matrices
3.4 Balancing for Nonsymmmetric Eigenproblems
3.5 Non-uniqueness of Eigenvectors and Singular Vectors
▸▿ 4 Decision Trees
4.1 Black Box Routines
4.2 General Purpose Routines (Eigenvalues and Eigenvectors)
4.3 General Purpose Routines (Singular Value Decomposition)
5 Functionality Index
6 Auxiliary Routines Associated with Library Routine Arguments
7 Routines Withdrawn or Scheduled for Withdrawal
8 References

1 Scope of the Chapter

This chapter provides routines for various types of matrix eigenvalue problem:
  • standard eigenvalue problems (finding eigenvalues and eigenvectors of a square matrix A);
  • singular value problems (finding singular values and singular vectors of a rectangular matrix A);
  • generalized eigenvalue problems (finding eigenvalues and eigenvectors of a matrix pencil A-λB).
  • quadratic eigenvalue problems (finding eigenvalues and eigenvectors of the quadratic λ 2 A+λB+C).
Routines are provided for both real and complex data.
The majority of routines for these problems can be found in Chapter F08 which contains software derived from LAPACK (see Anderson et al. (1999)). However, you should read the the F02 Chapter Introduction before turning to Chapter F08, especially if you are a new user. Chapter F12 contains routines for large sparse eigenvalue problems, although one such routine is also available in this chapter.
Chapters F02 and F08 contain Black Box (or Driver) routines that enable many problems to be solved by a call to a single routine, and the decision trees in Section 4 direct you to the most appropriate routines in Chapters F02 and F08. The Chapter F02 routines call routines in Chapters F07 and F08 wherever possible to perform the computations, and there are pointers in Section 4 to the relevant decision trees in Chapter F08.

2 Background to the Problems

Here we describe the different types of problem which can be tackled by the routines in this chapter, and give a brief outline of the methods used to solve them. If you have one specific type of problem to solve, you need only read the relevant sub-section and then turn to Section 3. Consult a standard textbook for a more thorough discussion, for example Golub and Van Loan (1996) or Parlett (1998).
In each sub-section, we first describe the problem in terms of real matrices. The changes needed to adapt the discussion to complex matrices are usually simple and obvious: a matrix transpose such as QT must be replaced by its conjugate transpose QH; symmetric matrices must be replaced by Hermitian matrices, and orthogonal matrices by unitary matrices. Any additional changes are noted at the end of the sub-section.

2.1 Standard Eigenvalue Problems

Let A be a square matrix of order n. The standard eigenvalue problem is to find eigenvalues, λ, and corresponding eigenvectors, x≠0, such that
Ax=λx. (1)
(The phrase ‘eigenvalue problem’ is sometimes abbreviated to eigenproblem.)

2.1.1 Standard symmetric eigenvalue problems

If A is real symmetric, the eigenvalue problem has many desirable features, and it is advisable to take advantage of symmetry whenever possible.
The eigenvalues λ are all real, and the eigenvectors can be chosen to be mutually orthogonal. That is, we can write
A zi=λizi  for ​i=1,2,…,n
or equivalently:
AZ=ZΛ (2)
where Λ is a real diagonal matrix whose diagonal elements λi are the eigenvalues, and Z is a real orthogonal matrix whose columns zi are the eigenvectors. This implies that ziT zj = 0 if i≠j, and zi 2=1.
Equation (2) can be rewritten
A=ZΛ ZT. (3)
This is known as the eigen-decomposition or spectral factorization of A.
Eigenvalues of a real symmetric matrix are well-conditioned, that is, they are not unduly sensitive to perturbations in the original matrix A. The sensitivity of an eigenvector depends on how small the gap is between its eigenvalue and any other eigenvalue: the smaller the gap, the more sensitive the eigenvector. More details on the accuracy of computed eigenvalues and eigenvectors are given in the routine documents, and in the F08 Chapter Introduction.
For dense or band matrices, the computation of eigenvalues and eigenvectors proceeds in the following stages:
1. | A is reduced to a symmetric tridiagonal matrix T by an orthogonal similarity transformation: A=QT QT, where Q is orthogonal. (A tridiagonal matrix is zero except for the main diagonal and the first subdiagonal and superdiagonal on either side.) T has the same eigenvalues as A and is easier to handle.
2. | Eigenvalues and eigenvectors of T are computed as required. If all eigenvalues (and optionally eigenvectors) are required, they are computed by the QR algorithm, which effectively factorizes T as T=SΛ ST, where S is orthogonal, or by the divide-and-conquer method. If only selected eigenvalues are required, they are computed by bisection, and if selected eigenvectors are required, they are computed by inverse iteration. If s is an eigenvector of T, then Qs is an eigenvector of A.
All the above remarks also apply – with the obvious changes – to the case when A is a complex Hermitian matrix. The eigenvectors are complex, but the eigenvalues are all real, and so is the tridiagonal matrix T.
If A is large and sparse, the methods just described would be very wasteful in both storage and computing time, and therefore an alternative algorithm, known as subspace iteration, is provided (for real problems only) to find a (usually small) subset of the eigenvalues and their corresponding eigenvectors. Chapter F12 contains routines based on the Lanczos method for real symmetric large sparse eigenvalue problems, and these routines are usually more efficient than subspace iteration.

2.1.2 Standard nonsymmetric eigenvalue problems

A real nonsymmetric matrix A may have complex eigenvalues, occurring as complex conjugate pairs. If x is an eigenvector corresponding to a complex eigenvalue λ, then the complex conjugate vector x- is the eigenvector corresponding to the complex conjugate eigenvalue λ-. Note that the vector x defined in equation (1) is sometimes called a right eigenvector; a left eigenvector y is defined by
yH A=λ yH  or  AT y=λ-y.
Routines in this chapter only compute right eigenvectors (the usual requirement), but routines in Chapter F08 can compute left or right eigenvectors or both.
The eigenvalue problem can be solved via the Schur factorization of A, defined as
A=ZT ZT,
where Z is an orthogonal matrix and T is a real upper quasi-triangular matrix, with the same eigenvalues as A. T is called the Schur form of A. If all the eigenvalues of A are real, then T is upper triangular, and its diagonal elements are the eigenvalues of A. If A has complex conjugate pairs of eigenvalues, then T has 2 by 2 diagonal blocks, whose eigenvalues are the complex conjugate pairs of eigenvalues of A. (The structure of T is simpler if the matrices are complex – see below.)
For example, the following matrix is in quasi-triangular form
1 * * * 0 2 -1 * 0 1 2 * 0 0 0 3
and has eigenvalues 1, 2±i, and 3. (The elements indicated by ‘*’ may take any values.)
The columns of Z are called the Schur vectors. For each k 1≤k≤n, the first k columns of Z form an orthonormal basis for the invariant subspace corresponding to the first k eigenvalues on the diagonal of T. (An invariant subspace (for A) is a subspace S such that for any vector v in S, Av is also in S.) Because this basis is orthonormal, it is preferable in many applications to compute Schur vectors rather than eigenvectors. It is possible to order the Schur factorization so that any desired set of k eigenvalues occupy the k leading positions on the diagonal of T, and routines for this purpose are provided in Chapter F08.
Note that if A is symmetric, the Schur vectors are the same as the eigenvectors, but if A is nonsymmetric, they are distinct, and the Schur vectors, being orthonormal, are often more satisfactory to work with in numerical computation.
Eigenvalues and eigenvectors of a nonsymmetric matrix may be ill-conditioned, that is, sensitive to perturbations in A. Chapter F08 contains routines which compute or estimate the condition numbers of eigenvalues and eigenvectors, and the F08 Chapter Introduction gives more details about the error analysis of nonsymmetric eigenproblems. The accuracy with which eigenvalues and eigenvectors can be obtained is often improved by balancing a matrix. This is discussed further in Section 3.4.
Computation of eigenvalues, eigenvectors or the Schur factorization proceeds in the following stages:
1. | A is reduced to an upper Hessenberg matrix H by an orthogonal similarity transformation: A=QH QT, where Q is orthogonal. (An upper Hessenberg matrix is zero below the first subdiagonal.) H has the same eigenvalues as A, and is easier to handle.
2. | The upper Hessenberg matrix H is reduced to Schur form T by the QR algorithm, giving the Schur factorization H=ST ST. The eigenvalues of A are obtained from the diagonal blocks of T. The matrix Z of Schur vectors (if required) is computed as Z=QS.
3. | After the eigenvalues have been found, eigenvectors may be computed, if required, in two different ways. Eigenvectors of H can be computed by inverse iteration, and then pre-multiplied by Q to give eigenvectors of A; this approach is usually preferred if only a few eigenvectors are required. Alternatively, eigenvectors of T can be computed by back-substitution, and pre-multiplied by Z to give eigenvectors of A.
All the above remarks also apply – with the obvious changes – to the case when A is a complex matrix. The eigenvalues are in general complex, so there is no need for special treatment of complex conjugate pairs, and the Schur form T is simply a complex upper triangular matrix.
As for the symmetric eigenvalue problem, if A and is large and sparse then it is generally preferable to use an alternative method. Chapter F12 provides routines based on Arnoldi's method for both real and complex matrices, intended to find a subset of the eigenvalues and vectors.

2.2 The Singular Value Decomposition

The singular value decomposition (SVD) of a real m by n matrix A is given by
A=UΣ VT,
where U and V are orthogonal and Σ is an m by n diagonal matrix with real diagonal elements, σi, such that
σ 1≥σ 2≥⋯≥σ min m,n≥0.
The σi are the singular values of A and the first min m,n columns of U and V are, respectively, the left and right singular vectors of A. The singular values and singular vectors satisfy
A vi=σiui  and  AT ui=σivi
where ui and vi are the ith columns of U and V respectively.
The singular value decomposition of A is closely related to the eigen-decompositions of the symmetric matrices AT A or A AT, because:
AT A vi=σi 2 vi  and  A AT ui=σi 2 ui.
However, these relationships are not recommended as a means of computing singular values or vectors unless A is sparse and routines from Chapter F12 are to be used.
If Uk, Vk denote the leading k columns of U and V respectively, and if Σ k denotes the leading principal submatrix of Σ, then
Ak ≡ Uk Σ k VT k
is the best rank-k approximation to A in both the 2-norm and the Frobenius norm.
Singular values are well-conditioned; that is, they are not unduly sensitive to perturbations in A. The sensitivity of a singular vector depends on how small the gap is between its singular value and any other singular value: the smaller the gap, the more sensitive the singular vector. More details on the accuracy of computed singular values and vectors are given in the routine documents and in the F08 Chapter Introduction.
The singular value decomposition is useful for the numerical determination of the rank of a matrix, and for solving linear least squares problems, especially when they are rank-deficient (or nearly so). See Chapter F04.
Computation of singular values and vectors proceeds in the following stages:
1. | A is reduced to an upper bidiagonal matrix B by an orthogonal transformation A=U 1 B V 1 T, where U 1 and V 1 are orthogonal. (An upper bidiagonal matrix is zero except for the main diagonal and the first superdiagonal.) B has the same singular values as A, and is easier to handle.
2. | The SVD of the bidiagonal matrix B is computed as B = U 2 Σ V 2 T , where U 2 and V 2 are orthogonal and Σ is diagonal as described above. Then in the SVD of A, U=U 1U 2 and V=V 1V 2.
All the above remarks also apply – with the obvious changes – to the case when A is a complex matrix. The singular vectors are complex, but the singular values are real and non-negative, and the bidiagonal matrix B is also real.
By formulating the problems appropriately, real large sparse singular value problems may be solved using the symmetric eigenvalue routines in Chapter F12.

2.3 Generalized Eigenvalue Problems

Let A and B be square matrices of order n. The generalized eigenvalue problem is to find eigenvalues, λ, and corresponding eigenvectors, x≠0, such that
Ax=λBx. (4)
For given A and B, the set of all matrices of the form A-λB is called a pencil, and λ and x are said to be an eigenvalue and eigenvector of the pencil A-λB.
When B is nonsingular, equation (4) is mathematically equivalent to B-1 A x=λx, and when A is nonsingular, it is equivalent to A-1 B x=1/λ x. Thus, in theory, if one of the matrices A or B is known to be nonsingular, the problem could be reduced to a standard eigenvalue problem.
However, for this reduction to be satisfactory from the point of view of numerical stability, it is necessary not only that B (or A) should be nonsingular, but that it should be well-conditioned with respect to inversion. The nearer B is to singularity, the more unsatisfactory B-1 A will be as a vehicle for determining the required eigenvalues. Well-determined eigenvalues of the original problem (4) may be poorly determined even by the correctly rounded version of B-1 A.
We consider first a special class of problems in which B is known to be nonsingular, and then return to the general case in the following sub-section.

2.3.1 Generalized symmetric-definite eigenvalue problems

If A and B are symmetric and B is positive definite, then the generalized eigenvalue problem has desirable properties similar to those of the standard symmetric eigenvalue problem. The eigenvalues are all real, and the eigenvectors, while not orthogonal in the usual sense, satisfy the relations ziT B zj = 0 for i≠j and can be normalized so that ziT B zi = 1 .
Note that it is not enough for A and B to be symmetric; B must also be positive definite, which implies nonsingularity. Eigenproblems with these properties are referred to as symmetric-definite problems.
If Λ is the diagonal matrix whose diagonal elements are the eigenvalues, and Z is the matrix whose columns are the eigenvectors, then
ZT AZ=Λ  and  ZT BZ=I.
To compute eigenvalues and eigenvectors, the problem can be reduced to a standard symmetric eigenvalue problem, using the Cholesky factorization of B as L LT or UT U (see Chapter F07). Note, however, that this reduction does implicitly involve the inversion of B, and hence this approach should not be used if B is ill-conditioned with respect to inversion.
For example, with B=L LT, we have
Az=λBz ⇔ L-1 A L-T LT z = λ LT z .
Hence the eigenvalues of Az=λBz are those of Cy=λy, where C is the symmetric matrix C = L-1 A L-T and y=LT z. The standard symmetric eigenproblem Cy=λy may be solved by the methods described in Section 2.1.1. The eigenvectors z of the original problem may be recovered by computing z = L-T y .
Most of the routines which solve this class of problems can also solve the closely related problems
ABx=λx  or  BAx=λx
where again A and B are symmetric and B is positive definite. See the routine documents for details.
All the above remarks also apply – with the obvious changes – to the case when A and B are complex Hermitian matrices. Such problems are called Hermitian-definite. The eigenvectors are complex, but the eigenvalues are all real.
If A and B are large and sparse, reduction to an equivalent standard eigenproblem as described above would almost certainly result in a large dense matrix C, and hence would be very wasteful in both storage and computing time. The methods of subspace iteration and Lanczos type methods, mentioned in Section 2.1.1, can also be used for large sparse generalized symmetric-definite problems.

2.3.2 Generalized nonsymmetric eigenvalue problems

Any generalized eigenproblem which is not symmetric-definite with well-conditioned B must be handled as if it were a general nonsymmetric problem.
If B is singular, the problem has infinite eigenvalues. These are not a problem; they are equivalent to zero eigenvalues of the problem Bx=μAx. Computationally they appear as very large values.
If A and B are both singular and have a common null space, then A-λB is singular for all λ; in other words, any value λ can be regarded as an eigenvalue. Pencils with this property are called singular.
As with standard nonsymmetric problems, a real problem may have complex eigenvalues, occurring as complex conjugate pairs.
The generalized eigenvalue problem can be solved via the generalized Schur factorization of A and B:
A=QU ZT,  B=QV ZT
where Q and Z are orthogonal, V is upper triangular, and U is upper quasi-triangular (defined just as in Section 2.1.2).
If all the eigenvalues are real, then U is upper triangular; the eigenvalues are given by λi=u ii/v ii. If there are complex conjugate pairs of eigenvalues, then U has 2 by 2 diagonal blocks.
Eigenvalues and eigenvectors of a generalized nonsymmetric problem may be ill-conditioned; that is, sensitive to perturbations in A or B.
Particular care must be taken if, for some i, u ii=v ii=0, or in practical terms if u ii and v ii are both small; this means that the pencil is singular, or approximately so. Not only is the particular value λi undetermined, but also no reliance can be placed on any of the computed eigenvalues. See also the routine documents.
Computation of eigenvalues and eigenvectors proceeds in the following stages.
1. | The pencil A-λB is reduced by an orthogonal transformation to a pencil H-λK in which H is upper Hessenberg and K is upper triangular: A = Q 1 H Z 1 T and B = Q 1 K Z 1 T . The pencil H-λK has the same eigenvalues as A-λB, and is easier to handle.
2. | The upper Hessenberg matrix H is reduced to upper quasi-triangular form, while K is maintained in upper triangular form, using the QZ algorithm. This gives the generalized Schur factorization: H=Q 2 U Z 2 and K=Q 2 V Z 2.
3. | Eigenvectors of the pencil U-λV are computed (if required) by back-substitution, and pre-multiplied by Z 1Z 2 to give eigenvectors of A.
All the above remarks also apply – with the obvious changes – to the case when A and B are complex matrices. The eigenvalues are in general complex, so there is no need for special treatment of complex conjugate pairs, and the matrix U in the generalized Schur factorization is simply a complex upper triangular matrix.
As for the generalized symmetric-definite eigenvalue problem, if A and B are large and sparse then it is generally preferable to use an alternative method. Chapter F12 provides routines based on Arnoldi's method for both real and complex matrices, intended to find a subset of the eigenvalues and vectors.

2.4 Quadratic eigenvalue problems

Let A, B and C be square matrices of order n. The quadratic eigenvalue problem (QEP) is to find eigenvalues, λ, and corresponding eigenvectors, x≠0, such that
λ 2 A+λB+C x=0 .
More specifically, x is a right eigenvector and a left eigenvector, y, is such that
yH λ 2 A+λB+C =0 ,
where yH is the conjugate transpose of y (transpose when y is real).
In general the QEP has 2 n eigenvalues and corresponding eigenvectors.
QEPs are generally solved by linearizing the problem to produce a 2 n by 2 n generalized eigenvalue problem. For example,
C 1 λ = B C -I 0 - λ -A 0 0 -I ,
which is called the first companion form and has the same 2 n eigenvalues as the QEP.
If
det λ 2 A+λB+C ≢ 0 ,
then the QEP is said to be regular, or non-singular. For a regular QEP, when C is singular the QEP has one or more zero eigenvalues and when A is singular the QEP has one or more infinite eigenvalues. As with the generalized problem particular care must be taken when the problem is singular (see Section 2.3.2).
As with generalized nonsymmetric problems, a real QEP may have complex eigenvalues, occurring as complex conjugate pairs.
For further information on QEPs, see the survey article by Tisseur and Meerbergen (2001), and for details on solving the dense QEP see Hammarling et al. (2013).

3 Recommendations on Choice and Use of Available Routines

3.1 Black Box Routines and General Purpose Routines

Routines in the NAG Library for solving eigenvalue problems fall into two categories.
1. | Black Box Routines: these are designed to solve a standard type of problem in a single call – for example, to compute all the eigenvalues and eigenvectors of a real symmetric matrix. You are recommended to use a black box routine if there is one to meet your needs; refer to the decision tree in Section 4.1 or the index in Section 5.
2. | General Purpose Routines: these perform the computational subtasks which make up the separate stages of the overall task, as described in Section 2 – for example, reducing a real symmetric matrix to tridiagonal form. General purpose routines are to be found, for historical reasons, some in this chapter, a few in Chapter F01, but most in Chapter F08. If there is no black box routine that meets your needs, you will need to use one or more general purpose routines.
The decision trees in Section 4.2 list the combinations of general purpose routines which are needed to solve many common types of problem.
Sometimes a combination of a black box routine and one or more general purpose routines will be the most convenient way to solve your problem: the black box routine can be used to compute most of the results, and a general purpose routine can be used to perform a subsidiary computation, such as computing condition numbers of eigenvalues and eigenvectors.

3.2 Computing Selected Eigenvalues and Eigenvectors

The decision trees and the routine documents make a distinction between routines which compute all eigenvalues or eigenvectors, and routines which compute selected eigenvalues or eigenvectors; the two classes of routine use different algorithms.
It is difficult to give clear guidance on which of these two classes of routine to use in a particular case, especially with regard to computing eigenvectors. If you only wish to compute a very few eigenvectors, then a routine for selected eigenvectors will be more economical, but if you want to compute a substantial subset (an old rule of thumb suggested more than 25%), then it may be more economical to compute all of them. Conversely, if you wish to compute all the eigenvectors of a sufficiently large symmetric tridiagonal matrix, the routine for selected eigenvectors may be faster.
The choice depends on the properties of the matrix and on the computing environment; if it is critical, you should perform your own timing tests.
For dense nonsymmetric eigenproblems, there are no algorithms provided for computing selected eigenvalues; it is always necessary to compute all the eigenvalues, but you can then select specific eigenvectors for computation by inverse iteration.

3.3 Storage Schemes for Symmetric Matrices

Routines which handle symmetric matrices are usually designed to use either the upper or lower triangle of the matrix; it is not necessary to store the whole matrix. If either the upper or lower triangle is stored conventionally in the upper or lower triangle of a two-dimensional array, the remaining elements of the array can be used to store other useful data. However, that is not always convenient, and if it is important to economize on storage, the upper or lower triangle can be stored in a one-dimensional array of length n n+1/2; in other words, the storage is almost halved. This storage format is referred to as packed storage.
Routines designed for packed storage are usually less efficient, especially on high-performance computers, so there is a trade-off between storage and efficiency.
A band matrix is one whose nonzero elements are confined to a relatively small number of subdiagonals or superdiagonals on either side of the main diagonal. Algorithms can take advantage of bandedness to reduce the amount of work and storage required.
Routines which take advantage of packed storage or bandedness are provided for both standard symmetric eigenproblems and generalized symmetric-definite eigenproblems.

3.4 Balancing for Nonsymmmetric Eigenproblems

There are two preprocessing steps which one may perform on a nonsymmetric matrix A in order to make its eigenproblem easier. Together they are referred to as balancing.
1. | Permutation: this involves reordering the rows and columns to make A more nearly upper triangular (and thus closer to Schur form): A′=PA PT, where P is a permutation matrix. If A has a significant number of zero elements, this preliminary permutation can reduce the amount of work required, and also improve the accuracy of the computed eigenvalues. In the extreme case, if A is permutable to upper triangular form, then no floating-point operations are needed to reduce it to Schur form.
2. | Scaling: a diagonal matrix D is used to make the rows and columns of A′ more nearly equal in norm: A′′=D A′D-1. Scaling can make the matrix norm smaller with respect to the eigenvalues, and so possibly reduce the inaccuracy contributed by roundoff (see Chapter II/11 of Wilkinson and Reinsch (1971)).
Routines are provided in Chapter F08 for performing either or both of these preprocessing steps, and also for transforming computed eigenvectors or Schur vectors back to those of the original matrix.
The black box routines in this chapter which compute eigenvectors perform both forms of balancing.

3.5 Non-uniqueness of Eigenvectors and Singular Vectors

Eigenvectors, as defined by equations (1) or (4), are not uniquely defined. If x is an eigenvector, then so is kx where k is any nonzero scalar. Eigenvectors computed by different algorithms, or on different computers, may appear to disagree completely, though in fact they differ only by a scalar factor (which may be complex). These differences should not be significant in any application in which the eigenvectors will be used, but they can arouse uncertainty about the correctness of computed results.
Even if eigenvectors x are normalized so that x 2=1, this is not sufficient to fix them uniquely, since they can still be multiplied by a scalar factor k such that k=1. To counteract this inconvenience, most of the routines in this chapter, and in Chapter F08, normalize eigenvectors (and Schur vectors) so that x 2=1 and the component of x with largest absolute value is real and positive. (There is still a possible indeterminacy if there are two components of equal largest absolute value – or in practice if they are very close – but this is rare.)
In symmetric problems the computed eigenvalues are sorted into ascending order, but in nonsymmetric problems the order in which the computed eigenvalues are returned is dependent on the detailed working of the algorithm and may be sensitive to rounding errors. The Schur form and Schur vectors depend on the ordering of the eigenvalues and this is another possible cause of non-uniqueness when they are computed. However, it must be stressed again that variations in the results from this cause should not be significant. (Routines in Chapter F08 can be used to transform the Schur form and Schur vectors so that the eigenvalues appear in any given order if this is important.)
In singular value problems, the left and right singular vectors u and v which correspond to a singular value σ cannot be normalized independently: if u is multiplied by a factor k such that k=1, then v must also be multiplied by k.
Non-uniqueness also occurs among eigenvectors which correspond to a multiple eigenvalue, or among singular vectors which correspond to a multiple singular value. In practice, this is more likely to be apparent as the extreme sensitivity of eigenvectors which correspond to a cluster of close eigenvalues (or of singular vectors which correspond to a cluster of close singular values).

4 Decision Trees

4.1 Black Box Routines

The decision tree for this section is divided into three sub-trees.
  • Tree 1 Eigenvalues and Eigenvectors of Real Matrices
  • Tree 2 Eigenvalues and Eigenvectors of Complex Matrices
  • Tree 3 Singular Values and Singular Vectors
Note: for the Chapter F08 routines there is generally a choice of simple and comprehensive routine. The comprehensive routines return additional information such as condition and/or error estimates.

Tree 1: Eigenvalues and Eigenvectors of Real Matrices

Is this a sparse eigenproblem Ax=λx or Ax=λBx? |  |  | Is the problem symmetric? |  |  | F02FJF or F02FKF
 |  | yes |  |  | yes
 | no |  |  | no |
 |  |  | F02EKF
Is the eigenproblem λ 2 A+λB+C x=0? |  |  | F02JCF
 |  | yes
 | no |
Is the eigenproblem Ax=λBx? |  |  | Are A and B symmetric with B positive definite and well-conditioned w.r.t inversion? |  |  | Are A and B band matrices? |  |  | F08UAF, F08UBF or F12FFF and F12AGF
 |  | yes |  |  | yes |  |  | yes
 | no |  |  | no |  |  | no |
 |  |  |  |  |  | F08SAF or F08SBF
 |  |  | Are A and B band matrices? |  |  | F12AFF and F12AGF
 |  |  |  |  | yes
 |  |  |  | no |
 |  |  | Is the generalized Schur factorization required? |  |  | F08XAF
 |  |  |  |  | yes
 |  |  |  | no |
 |  |  | F08WAF or F08WBF
The eigenproblem is Ax=λx. Is A symmetric? |  |  | Are all eigenvalues or all eigenvectors required? |  |  | F08FAF
 |  | yes |  |  | yes
 | no |  |  | no |
 |  |  | F08FBF
Are eigenvalues only required? |  |  | F08NAF or F08NBF
 |  | yes
 | no |
Is the Schur factorization required? |  |  | F08PAF or F08PBF
 |  | yes
 | no |
Are all eigenvectors required? |  |  | F08NAF or F08NBF
 |  | yes
 | no |
F02ECF

Tree 2: Eigenvalues and Eigenvectors of Complex Matrices

Is this a sparse eigenproblem Ax=λx or Ax=λBx? |  |  | Are A and B banded matrices? |  |  | F12ATF and F12AUF
 |  | yes |  |  | yes
 | no |  |  | no |
 |  |  | See Chapter F12
Is the eigenproblem λ 2 A+λB+C x=0? |  |  | F02JQF
 |  | yes
 | no |
Is the eigenproblem Ax=λBx? |  |  | Are A and B Hermitian with B positive definite and well-conditioned w.r.t. inversion? |  |  | F08UNF or F08UPF
 |  | yes |  |  | yes
 | no |  |  | no |
 |  |  | Is the generalized Schur factorization required? |  |  | F08XNF
 |  |  |  |  | yes
 |  |  |  | no |
 |  |  | F08WNF
The eigenproblem is Ax=λx. Is A Hermitian? |  |  | Are all eigenvalues and eigenvectors required? |  |  | F08FNF or F08FPF
 |  | yes |  |  | yes
 | no |  |  | no |
 |  |  | F08FPF
Are eigenvalues only required? |  |  | F08NNF or F08NPF
 |  | yes
 | no |
Is the Schur factorization required? |  |  | F08PNF or F08PPF
 |  | yes
 | no |
Are all eigenvectors required? |  |  | F08NNF or F08NPF
 |  | yes
 | no |
F02GCF

Tree 3: Singular Values and Singular Vectors

Is A a complex matrix? |  |  | Is A upper triangular? |  |  | F02XUF
 |  | yes |  |  | yes
 | no |  |  | no |
 |  |  | F08KPF
Is A upper triangular? |  |  | F02WUF
 |  | yes
 | no |
Are only the leading terms required? |  |  | F02WGF
 |  | yes
 | no |
F08KBF

4.2 General Purpose Routines (Eigenvalues and Eigenvectors)

Routines for large sparse eigenvalue problems are to be found in Chapter F12, see the F12 Chapter Introduction.
The decision tree for this section addressing dense problems, is divided into eight sub-trees:
  • Tree 1 Real Symmetric Eigenvalue Problems in the F08 Chapter Introduction
  • Tree 2 Real Generalized Symmetric-definite Eigenvalue Problems in the F08 Chapter Introduction
  • Tree 3 Real Nonsymmetric Eigenvalue Problems in the F08 Chapter Introduction
  • Tree 4 Real Generalized Nonsymmetric Eigenvalue Problems in the F08 Chapter Introduction
  • Tree 5 Complex Hermitian Eigenvalue Problems in the F08 Chapter Introduction
  • Tree 6 Complex Generalized Hermitian-definite Eigenvalue Problems in the F08 Chapter Introduction
  • Tree 7 Complex non-Hermitian Eigenvalue Problems in the F08 Chapter Introduction
  • Tree 8 Complex Generalized non-Hermitian Eigenvalue Problems in the F08 Chapter Introduction
As it is very unlikely that one of the routines in this section will be called on its own, the other routines required to solve a given problem are listed in the order in which they should be called.

4.3 General Purpose Routines (Singular Value Decomposition)

See Section 4.2 in the F08 Chapter Introduction. For real sparse matrices where only selected singular values are required (possibly with their singular vectors), routines from Chapter F12 may be applied to the symmetric matrix AT A; see Section 10 in F12FBF.

5 Functionality Index

Black Box routines,
complex eigenproblem,
selected eigenvalues and eigenvectors F02GCF
complex quadratic eigenproblem,
all eigenvalues and optionally eigenvectors, backward,
errors and eigenvalue condition numbers F02JQF
complex upper triangular matrix,
singular values and, optionally, left and/or right singular vectors F02XUF
generalized real sparse symmetric-definite eigenproblem,
selected eigenvalues and eigenvectors F02FJF
real eigenproblem,
selected eigenvalues and eigenvectors F02ECF
real quadratic eigenproblem,
all eigenvalues and optionally eigenvectors, backward,
errors and eigenvalue condition numbers F02JCF
real sparse eigenproblem,
selected eigenvalues and eigenvectors F02EKF
real sparse symmetric matrix,
driver,
selected eigenvalues and eigenvectors F02FKF
selected eigenvalues and eigenvectors F02FJF
real upper triangular matrix,
singular values and, optionally, left and/or right singular vectors F02WUF
General Purpose routines (see also Chapter F12),
real m by n matrix, leading terms SVD F02WGF

6 Auxiliary Routines Associated with Library Routine Arguments

F02EKY | nagf_eigen_arnoldi_option See the description of the argument OPTION in F02EKF.
F02EKZ | nagf_eigen_arnoldi_monit_gen See the description of the argument MONIT in F02EKF.
F02FJZ | nagf_eigen_monit See the description of the argument MONIT in F02FJF.
F02FKZ | nagf_eigen_arnoldi_monit_symm See the description of the argument MONIT in F02FKF.

7 Routines Withdrawn or Scheduled for Withdrawal

The following lists all those routines that have been withdrawn since Mark 19 of the Library or are scheduled for withdrawal at one of the next two marks.
Withdrawn Routine | Mark of Withdrawal | Replacement Routine(s)
F02BBF | 19 | F08FBF (DSYEVX)
F02BCF | 19 | F02ECF
F02BDF | 19 | F02GCF
F02BJF | 23 | F08WAF (DGGEV)
F02EAF | 23 | F08PAF (DGEES)
F02EBF | 23 | F08NAF (DGEEV)
F02FAF | 23 | F08FAF (DSYEV)
F02FCF | 23 | F08FBF (DSYEVX)
F02FDF | 23 | F08SAF (DSYGV)
F02FHF | 23 | F08UAF (DSBGV)
F02GAF | 23 | F08PNF (ZGEES)
F02GBF | 23 | F08NNF (ZGEEV)
F02GJF | 23 | F08WNF (ZGGEV)
F02HAF | 23 | F08FNF (ZHEEV)
F02HCF | 23 | F08FPF (ZHEEVX)
F02HDF | 23 | F08SNF (ZHEGV)
F02SDF | 27 | F12AGF and F12FGF
F02WDF | 27 | F02WUF and F08AEF (DGEQRF)
F02WEF | 23 | F08KBF (DGESVD)
F02XEF | 23 | F08KPF (ZGESVD)

8 References

Anderson E, Bai Z, Bischof C, Blackford S, Demmel J, Dongarra J J, Du Croz J J, Greenbaum A, Hammarling S, McKenney A and Sorensen D (1999) LAPACK Users' Guide (3rd Edition) SIAM, Philadelphia
Golub G H and Van Loan C F (1996) Matrix Computations (3rd Edition) Johns Hopkins University Press, Baltimore
Hammarling S, Munro C J and Tisseur F (2013) An algorithm for the complete solution of quadratic eigenvalue problems. ACM Trans. Math. Software. 39(3):18:1–18:119 http://eprints.ma.man.ac.uk/1815/
Parlett B N (1998) The Symmetric Eigenvalue Problem SIAM, Philadelphia
Tisseur F and Meerbergen K (2001) The quadratic eigenvalue problem SIAM Review 43:235–286
Wilkinson J H and Reinsch C (1971) Handbook for Automatic Computation II, Linear Algebra Springer–Verlag
F02 Chapter Contents
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F02JCF : NAG Library, Mark 26

F02 Chapter Contents
F02 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F02JCF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F02JCF solves the quadratic eigenvalue problem
λ 2 ⁢ A + λ ⁢ B + C ⁢ x = 0 ,
where A, B and C are real n by n matrices.
The routine returns the 2⁢n eigenvalues, λj, for j=1,2,…,2 n, and can optionally return the corresponding right eigenvectors, xj and/or left eigenvectors, yj as well as estimates of the condition numbers of the computed eigenvalues and backward errors of the computed right and left eigenvectors. A left eigenvector satisfies the equation
yH ⁢ λ 2⁢A+ λ⁢B+ C = 0 ,
where yH is the complex conjugate transpose of y.
λ is represented as the pair α,β , such that λ = α/β. Note that the computation of α/β may overflow and indeed β may be zero.

2 Specification

SUBROUTINE F02JCF ( SCAL, JOBVL, JOBVR, SENSE, TOL, N, A, LDA, B, LDB, C, LDC, ALPHAR, ALPHAI, BETA, VL, LDVL, VR, LDVR, S, BEVL, BEVR, IWARN, IFAIL)
INTEGER | SCAL, SENSE, N, LDA, LDB, LDC, LDVL, LDVR, IWARN, IFAIL
REAL (KIND=nag_wp) | TOL, A(LDA,*), B(LDB,*), C(LDC,*), ALPHAR(2*N), ALPHAI(2*N), BETA(2*N), VL(LDVL,*), VR(LDVR,*), S(*), BEVL(*), BEVR(*)
CHARACTER(1) | JOBVL, JOBVR

3 Description

The quadratic eigenvalue problem is solved by linearizing the problem and solving the resulting 2 n by 2 n generalized eigenvalue problem. The linearization is chosen to have favourable conditioning and backward stability properties. An initial preprocessing step is performed that reveals and deflates the zero and infinite eigenvalues contributed by singular leading and trailing matrices.
The algorithm is backward stable for problems that are not too heavily damped, that is B≤10 A·C.
Further details on the algorithm are given in Hammarling et al. (2013).

4 References

Fan H -Y, Lin W.-W and Van Dooren P. (2004) Normwise scaling of second order polynomial matrices. SIAM J. Matrix Anal. Appl. 26, 1 252–256
Gaubert S and Sharify M (2009) Tropical scaling of polynomial matrices Lecture Notes in Control and Information Sciences Series 389 291–303 Springer–Verlag
Hammarling S, Munro C J and Tisseur F (2013) An algorithm for the complete solution of quadratic eigenvalue problems. ACM Trans. Math. Software. 39(3):18:1–18:119 http://eprints.ma.man.ac.uk/1815/

5 Arguments

1:   SCAL – INTEGERInput
On entry: determines the form of scaling to be performed on A, B and C.
SCAL=0
No scaling.
SCAL=1 (the recommended value)
Fan, Lin and Van Dooren scaling if B A×C <10 and no scaling otherwise where Z is the Frobenius norm of Z.
SCAL=2
Fan, Lin and Van Dooren scaling.
SCAL=3
Tropical scaling with largest root.
SCAL=4
Tropical scaling with smallest root.
Constraint: SCAL=0, 1, 2, 3 or 4.
2:   JOBVL – CHARACTER(1)Input
On entry: if JOBVL='N', do not compute left eigenvectors.
If JOBVL='V', compute the left eigenvectors.
If SENSE=1, 2, 4, 5, 6 or 7, JOBVL must be set to 'V'.
Constraint: JOBVL='N' or 'V'.
3:   JOBVR – CHARACTER(1)Input
On entry: if JOBVR='N', do not compute right eigenvectors.
If JOBVR='V', compute the right eigenvectors.
If SENSE=1, 3, 4, 5, 6 or 7, JOBVR must be set to 'V'.
Constraint: JOBVR='N' or 'V'.
4:   SENSE – INTEGERInput
On entry: determines whether, or not, condition numbers and backward errors are computed.
SENSE=0
Do not compute condition numbers, or backward errors.
SENSE=1
Just compute condition numbers for the eigenvalues.
SENSE=2
Just compute backward errors for the left eigenpairs.
SENSE=3
Just compute backward errors for the right eigenpairs.
SENSE=4
Compute backward errors for the left and right eigenpairs.
SENSE=5
Compute condition numbers for the eigenvalues and backward errors for the left eigenpairs.
SENSE=6
Compute condition numbers for the eigenvalues and backward errors for the right eigenpairs.
SENSE=7
Compute condition numbers for the eigenvalues and backward errors for the left and right eigenpairs.
Constraint: SENSE=0, 1, 2, 3, 4, 5, 6 or 7.
5:   TOL – REAL (KIND=nag_wp)Input
On entry: TOL is used as the tolerance for making decisions on rank in the deflation procedure. If TOL is zero on entry then n × machine precision is used in place of TOL, where machine precision is as returned by routine X02AJF. A diagonal element of a triangular matrix, R, is regarded as zero if r jj ≤TOL×size X, or n×machine precision×size X when TOL is zero, where size X is based on the size of the absolute values of the elements of the matrix X containing the matrix R. See Hammarling et al. (2013) for the motivation. If TOL is -1.0 on entry then no deflation is attempted. The recommended value for TOL is zero.
6:   N – INTEGERInput
On entry: the order of the matrices A, B and C.
Constraint: N≥0.
7:   A LDA* – REAL (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array A must be at least N.
On entry: the n by n matrix A.
On exit: A is used as internal workspace, but if JOBVL='V' or JOBVR='V', then A is restored on exit.
8:   LDA – INTEGERInput
On entry: the first dimension of the array A as declared in the (sub)program from which F02JCF is called.
Constraint: LDA≥N.
9:   B LDB* – REAL (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array B must be at least N.
On entry: the n by n matrix B.
On exit: B is used as internal workspace, but is restored on exit.
10:   LDB – INTEGERInput
On entry: the first dimension of the array B as declared in the (sub)program from which F02JCF is called.
Constraint: LDB≥N.
11:   C LDC* – REAL (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array C must be at least N.
On entry: the n by n matrix C.
On exit: C is used as internal workspace, but if JOBVL='V' or JOBVR='V', C is restored on exit.
12:   LDC – INTEGERInput
On entry: the first dimension of the array C as declared in the (sub)program from which F02JCF is called.
Constraint: LDC≥N.
13:   ALPHAR 2×N – REAL (KIND=nag_wp) arrayOutput
On exit: ALPHAR j, for j=1,2,…,2 n, contains the real part of αj for the jth eigenvalue pair αj,βj of the quadratic eigenvalue problem.
14:   ALPHAI 2×N – REAL (KIND=nag_wp) arrayOutput
On exit: ALPHAI j, for j=1,2,…,2 n, contains the imaginary part of αj for the jth eigenvalue pair αj,βj of the quadratic eigenvalue problem. If ALPHAI j is zero then the jth eigenvalue is real; if ALPHAI j is positive then the jth and j+1th eigenvalues are a complex conjugate pair, with ALPHAI j+1 negative.
15:   BETA 2×N – REAL (KIND=nag_wp) arrayOutput
On exit: BETA j, for j=1,2,…,2⁢n, contains the second part of the jth eigenvalue pair αj,βj of the quadratic eigenvalue problem, with βj≥0. Infinite eigenvalues have βj set to zero.
16:   VL LDVL* – REAL (KIND=nag_wp) arrayOutput
Note: the second dimension of the array VL must be at least 2×N if JOBVL='V'.
On exit: if JOBVL='V', the left eigenvectors yj are stored one after another in the columns of VL, in the same order as the corresponding eigenvalues. If the jth eigenvalue is real, then yj=VL:j, the jth column of VL. If the jth and j+1th eigenvalues form a complex conjugate pair, then yj= VL:j + i× VL:j+1 and y j+1 = VL:j -i × VL:j+1 . Each eigenvector will be normalized with length unity and with the element of largest modulus real and positive.
If JOBVL='N', VL is not referenced.
17:   LDVL – INTEGERInput
On entry: the first dimension of the array VL as declared in the (sub)program from which F02JCF is called.
Constraint: LDVL≥N.
18:   VR LDVR* – REAL (KIND=nag_wp) arrayOutput
Note: the second dimension of the array VR must be at least 2×N if JOBVR='V'.
On exit: if JOBVR='V', the right eigenvectors xj are stored one after another in the columns of VR, in the same order as the corresponding eigenvalues. If the jth eigenvalue is real, then xj = VR:j , the jth column of VR. If the jth and j+1th eigenvalues form a complex conjugate pair, then xj = VR:j +i× VR:j+1 and x j+1= VR:j -i× VR:j+1 . Each eigenvector will be normalized with length unity and with the element of largest modulus real and positive.
If JOBVR='N', VR is not referenced.
19:   LDVR – INTEGERInput
On entry: the first dimension of the array VR as declared in the (sub)program from which F02JCF is called.
Constraint: LDVR≥N.
20:   S* – REAL (KIND=nag_wp) arrayOutput
Note: the dimension of the array S must be at least 2×N if SENSE=1, 5, 6 or 7.
Also: computing the condition numbers of the eigenvalues requires that both the left and right eigenvectors be computed.
On exit: if SENSE=1, 5, 6 or 7, S j contains the condition number estimate for the jth eigenvalue (large condition numbers imply that the problem is near one with multiple eigenvalues). Infinite condition numbers are returned as the largest model real number (X02ALF).
If SENSE=0, 2, 3 or 4, S is not referenced.
21:   BEVL* – REAL (KIND=nag_wp) arrayOutput
Note: the dimension of the array BEVL must be at least 2×N if SENSE=2, 4, 5 or 7.
On exit: if SENSE=2, 4, 5 or 7, BEVL j contains the backward error estimate for the computed left eigenpair λj,yj .
If SENSE=0, 1, 3 or 6, BEVL is not referenced.
22:   BEVR* – REAL (KIND=nag_wp) arrayOutput
Note: the dimension of the array BEVR must be at least 2×N if SENSE=3, 4, 6 or 7.
On exit: if SENSE=3, 4, 6 or 7, BEVR j contains the backward error estimate for the computed right eigenpair λj,xj .
If SENSE=0, 1, 2 or 5, BEVR is not referenced.
23:   IWARN – INTEGEROutput
On exit: IWARN will be positive if there are warnings, otherwise IWARN will be 0.
If IFAIL=0 then:
  • if IWARN=1 then one, or both, of the matrices A and C is zero. In this case no scaling is performed, even if SCAL>0;
  • if IWARN=2 then the matrices A and C are singular, or nearly singular, so the problem is potentially ill-posed;
  • if IWARN=3 then both the conditions for IWARN=1 and IWARN=2 above, apply. If IWARN=4, B≥10 A·C and backward stability cannot be guaranteed.
If IFAIL=2, IWARN returns the value of INFO from F08XAF (DGGES).
If IFAIL=3, IWARN returns the value of INFO from F08WAF (DGGEV).
24:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
The quadratic matrix polynomial is nonregular (singular).
IFAIL=2
The QZ iteration failed in F08XAF (DGGES).
IWARN returns the value of INFO returned by F08XAF (DGGES). This failure is unlikely to happen, but if it does, please contact NAG.
IFAIL=3
The QZ iteration failed in F08WAF (DGGEV).
IWARN returns the value of INFO returned by F08WAF (DGGEV). This failure is unlikely to happen, but if it does, please contact NAG.
IFAIL=-1
On entry, SCAL=value.
Constraint: SCAL=0, 1, 2, 3 or 4.
IFAIL=-2
On entry, JOBVL=value.
Constraint: JOBVL='N' or 'V'.
On entry, SENSE=value and JOBVL=value.
Constraint: when JOBVL='N', SENSE=0 or 3,
when JOBVL='V', SENSE=1, 2, 4, 5, 6 or 7.
IFAIL=-3
On entry, JOBVR=value.
Constraint: JOBVR='N' or 'V'.
On entry, SENSE=value and JOBVR=value.
Constraint: when JOBVR='N', SENSE=0 or 2,
when JOBVR='V', SENSE=1, 3, 4, 5, 6 or 7.
IFAIL=-4
On entry, SENSE=value.
Constraint: SENSE=0, 1, 2, 3, 4, 5, 6 or 7.
IFAIL=-6
On entry, N=value.
Constraint: N≥0.
IFAIL=-8
On entry, LDA=value and N=value.
Constraint: LDA≥N.
IFAIL=-10
On entry, LDB=value and N=value.
Constraint: LDB≥N.
IFAIL=-12
On entry, LDC=value and N=value.
Constraint: LDC≥N.
IFAIL=-17
On entry, LDVL=value, N=value and JOBVL=value.
Constraint: when JOBVL='V', LDVL≥N.
IFAIL=-19
On entry, LDVR=value, N=value and JOBVR=value.
Constraint: when JOBVR='V', LDVR≥N.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

The algorithm is backward stable for problems that are not too heavily damped, that is B≤10 A·C .

8 Parallelism and Performance

F02JCF is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
F02JCF makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

None.

10 Example

To solve the quadratic eigenvalue problem
λ 2 A + λB + C x = 0
where
A = 1 2 2 3 1 1 3 2 1 ,  B = 3 2 1 2 1 3 1 3 2  and  C = 1 1 2 2 3 1 3 1 2 .
The example also returns the left eigenvectors, condition numbers for the computed eigenvalues and backward errors of the computed right and left eigenpairs.

10.1 Program Text

Program Text (f02jcfe.f90)

10.2 Program Data

Program Data (f02jcfe.d)

10.3 Program Results

Program Results (f02jcfe.r)

F02 Chapter Contents
F02 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F02JQF : NAG Library, Mark 26

F02 Chapter Contents
F02 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F02JQF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F02JQF solves the quadratic eigenvalue problem
λ 2 ⁢ A + λ ⁢ B + C ⁢ x = 0 ,
where A, B and C are complex n by n matrices.
The routine returns the 2⁢n eigenvalues, λj, for j=1,2,…,2 n, and can optionally return the corresponding right eigenvectors, xj and/or left eigenvectors, yj as well as estimates of the condition numbers of the computed eigenvalues and backward errors of the computed right and left eigenvectors. A left eigenvector satisfies the equation
yH ⁢ λ 2⁢A+ λ⁢B+ C = 0 ,
where yH is the complex conjugate transpose of y.
λ is represented as the pair α,β , such that λ = α/β. Note that the computation of α/β may overflow and indeed β may be zero.

2 Specification

SUBROUTINE F02JQF ( SCAL, JOBVL, JOBVR, SENSE, TOL, N, A, LDA, B, LDB, C, LDC, ALPHA, BETA, VL, LDVL, VR, LDVR, S, BEVL, BEVR, IWARN, IFAIL)
INTEGER | SCAL, SENSE, N, LDA, LDB, LDC, LDVL, LDVR, IWARN, IFAIL
REAL (KIND=nag_wp) | TOL, S(*), BEVL(*), BEVR(*)
COMPLEX (KIND=nag_wp) | A(LDA,*), B(LDB,*), C(LDC,*), ALPHA(2*N), BETA(2*N), VL(LDVL,*), VR(LDVR,*)
CHARACTER(1) | JOBVL, JOBVR

3 Description

The quadratic eigenvalue problem is solved by linearizing the problem and solving the resulting 2 n by 2 n generalized eigenvalue problem. The linearization is chosen to have favourable conditioning and backward stability properties. An initial preprocessing step is performed that reveals and deflates the zero and infinite eigenvalues contributed by singular leading and trailing matrices.
The algorithm is backward stable for problems that are not too heavily damped, that is B≤10 A·C.
Further details on the algorithm are given in Hammarling et al. (2013).

4 References

Fan H -Y, Lin W.-W and Van Dooren P. (2004) Normwise scaling of second order polynomial matrices. SIAM J. Matrix Anal. Appl. 26, 1 252–256
Gaubert S and Sharify M (2009) Tropical scaling of polynomial matrices Lecture Notes in Control and Information Sciences Series 389 291–303 Springer–Verlag
Hammarling S, Munro C J and Tisseur F (2013) An algorithm for the complete solution of quadratic eigenvalue problems. ACM Trans. Math. Software. 39(3):18:1–18:119 http://eprints.ma.man.ac.uk/1815/

5 Arguments

1:   SCAL – INTEGERInput
On entry: determines the form of scaling to be performed on A, B and C.
SCAL=0
No scaling.
SCAL=1 (the recommended value)
Fan, Lin and Van Dooren scaling if B A×C <10 and no scaling otherwise where Z is the Frobenius norm of Z.
SCAL=2
Fan, Lin and Van Dooren scaling.
SCAL=3
Tropical scaling with largest root.
SCAL=4
Tropical scaling with smallest root.
Constraint: SCAL=0, 1, 2, 3 or 4.
2:   JOBVL – CHARACTER(1)Input
On entry: if JOBVL='N', do not compute left eigenvectors.
If JOBVL='V', compute the left eigenvectors.
If SENSE=1, 2, 4, 5, 6 or 7, JOBVL must be set to 'V'.
Constraint: JOBVL='N' or 'V'.
3:   JOBVR – CHARACTER(1)Input
On entry: if JOBVR='N', do not compute right eigenvectors.
If JOBVR='V', compute the right eigenvectors.
If SENSE=1, 3, 4, 5, 6 or 7, JOBVR must be set to 'V'.
Constraint: JOBVR='N' or 'V'.
4:   SENSE – INTEGERInput
On entry: determines whether, or not, condition numbers and backward errors are computed.
SENSE=0
Do not compute condition numbers, or backward errors.
SENSE=1
Just compute condition numbers for the eigenvalues.
SENSE=2
Just compute backward errors for the left eigenpairs.
SENSE=3
Just compute backward errors for the right eigenpairs.
SENSE=4
Compute backward errors for the left and right eigenpairs.
SENSE=5
Compute condition numbers for the eigenvalues and backward errors for the left eigenpairs.
SENSE=6
Compute condition numbers for the eigenvalues and backward errors for the right eigenpairs.
SENSE=7
Compute condition numbers for the eigenvalues and backward errors for the left and right eigenpairs.
Constraint: SENSE=0, 1, 2, 3, 4, 5, 6 or 7.
5:   TOL – REAL (KIND=nag_wp)Input
On entry: TOL is used as the tolerance for making decisions on rank in the deflation procedure. If TOL is zero on entry then n× machine precision is used in place of TOL, where machine precision is as returned by routine X02AJF. A diagonal element of a triangular matrix, R, is regarded as zero if r jj ≤TOL×size X, or n×machine precision×size X when TOL is zero, where size X is based on the size of the absolute values of the elements of the matrix X containing the matrix R. See Hammarling et al. (2013) for the motivation. If TOL is -1.0 on entry then no deflation is attempted. The recommended value for TOL is zero.
6:   N – INTEGERInput
On entry: the order of the matrices A, B and C.
Constraint: N≥0.
7:   A LDA* – COMPLEX (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array A must be at least N.
On entry: the n by n matrix A.
On exit: A is used as internal workspace, but if JOBVL='V' or JOBVR='V', then A is restored on exit.
8:   LDA – INTEGERInput
On entry: the first dimension of the array A as declared in the (sub)program from which F02JQF is called.
Constraint: LDA≥N.
9:   B LDB* – COMPLEX (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array B must be at least N.
On entry: the n by n matrix B.
On exit: B is used as internal workspace, but is restored on exit.
10:   LDB – INTEGERInput
On entry: the first dimension of the array B as declared in the (sub)program from which F02JQF is called.
Constraint: LDB≥N.
11:   C LDC* – COMPLEX (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array C must be at least N.
On entry: the n by n matrix C.
On exit: C is used as internal workspace, but if JOBVL='V' or JOBVR='V', C is restored on exit.
12:   LDC – INTEGERInput
On entry: the first dimension of the array C as declared in the (sub)program from which F02JQF is called.
Constraint: LDC≥N.
13:   ALPHA 2×N – COMPLEX (KIND=nag_wp) arrayOutput
On exit: ALPHA j, for j=1,2,…,2 n, contains the first part of the the jth eigenvalue pair αj,βj of the quadratic eigenvalue problem.
14:   BETA 2×N – COMPLEX (KIND=nag_wp) arrayOutput
On exit: BETA j, for j=1,2,…,2⁢n, contains the second part of the jth eigenvalue pair αj,βj of the quadratic eigenvalue problem. Although BETA is declared complex, it is actually real and non-negative. Infinite eigenvalues have βj set to zero.
15:   VL LDVL* – COMPLEX (KIND=nag_wp) arrayOutput
Note: the second dimension of the array VL must be at least 2×N if JOBVL='V'.
On exit: if JOBVL='V', the left eigenvectors yj are stored one after another in the columns of VL, in the same order as the corresponding eigenvalues. Each eigenvector will be normalized with length unity and with the element of largest modulus real and positive.
If JOBVL='N', VL is not referenced.
16:   LDVL – INTEGERInput
On entry: the first dimension of the array VL as declared in the (sub)program from which F02JQF is called.
Constraint: LDVL≥N.
17:   VR LDVR* – COMPLEX (KIND=nag_wp) arrayOutput
Note: the second dimension of the array VR must be at least 2×N if JOBVR='V'.
On exit: if JOBVR='V', the right eigenvectors xj are stored one after another in the columns of VR, in the same order as the corresponding eigenvalues. Each eigenvector will be normalized with length unity and with the element of largest modulus real and positive.
If JOBVR='N', VR is not referenced.
18:   LDVR – INTEGERInput
On entry: the first dimension of the array VR as declared in the (sub)program from which F02JQF is called.
Constraint: LDVR≥N.
19:   S* – REAL (KIND=nag_wp) arrayOutput
Note: the dimension of the array S must be at least 2×N if SENSE=1, 5, 6 or 7.
Also: computing the condition numbers of the eigenvalues requires that both the left and right eigenvectors be computed.
On exit: if SENSE=1, 5, 6 or 7, S j contains the condition number estimate for the jth eigenvalue (large condition numbers imply that the problem is near one with multiple eigenvalues). Infinite condition numbers are returned as the largest model real number (X02ALF).
If SENSE=0, 2, 3 or 4, S is not referenced.
20:   BEVL* – REAL (KIND=nag_wp) arrayOutput
Note: the dimension of the array BEVL must be at least 2×N if SENSE=2, 4, 5 or 7.
On exit: if SENSE=2, 4, 5 or 7, BEVL j contains the backward error estimate for the computed left eigenpair λj,yj .
If SENSE=0, 1, 3 or 6, BEVL is not referenced.
21:   BEVR* – REAL (KIND=nag_wp) arrayOutput
Note: the dimension of the array BEVR must be at least 2×N if SENSE=3, 4, 6 or 7.
On exit: if SENSE=3, 4, 6 or 7, BEVR j contains the backward error estimate for the computed right eigenpair λj,xj .
If SENSE=0, 1, 2 or 5, BEVR is not referenced.
22:   IWARN – INTEGEROutput
On exit: IWARN will be positive if there are warnings, otherwise IWARN will be 0.
If IFAIL=0 then:
  • if IWARN=1 then one, or both, of the matrices A and C is zero. In this case no scaling is performed, even if SCAL>0;
  • if IWARN=2 then the matrices A and C are singular, or nearly singular, so the problem is potentially ill-posed;
  • if IWARN=3 then both the conditions for IWARN=1 and IWARN=2 above, apply. If IWARN=4, B≥10 A·C and backward stability cannot be guaranteed.
If IFAIL=2, IWARN returns the value of INFO from F08XNF (ZGGES).
If IFAIL=3, IWARN returns the value of INFO from F08WNF (ZGGEV).
23:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
The quadratic matrix polynomial is nonregular (singular).
IFAIL=2
The QZ iteration failed in F08XNF (ZGGES).
IWARN returns the value of INFO returned by F08XNF (ZGGES). This failure is unlikely to happen, but if it does, please contact NAG.
IFAIL=3
The QZ iteration failed in F08WNF (ZGGEV).
IWARN returns the value of INFO returned by F08WNF (ZGGEV). This failure is unlikely to happen, but if it does, please contact NAG.
IFAIL=-1
On entry, SCAL=value.
Constraint: SCAL=0, 1, 2, 3 or 4.
IFAIL=-2
On entry, JOBVL=value.
Constraint: JOBVL='N' or 'V'.
On entry, SENSE=value and JOBVL=value.
Constraint: when JOBVL='N', SENSE=0 or 3,
when JOBVL='V', SENSE=1, 2, 4, 5, 6 or 7.
IFAIL=-3
On entry, JOBVR=value.
Constraint: JOBVR='N' or 'V'.
On entry, SENSE=value and JOBVR=value.
Constraint: when JOBVR='N', SENSE=0 or 2,
when JOBVR='V', SENSE=1, 3, 4, 5, 6 or 7.
IFAIL=-4
On entry, SENSE=value.
Constraint: SENSE=0, 1, 2, 3, 4, 5, 6 or 7.
IFAIL=-6
On entry, N=value.
Constraint: N≥0.
IFAIL=-8
On entry, LDA=value and N=value.
Constraint: LDA≥N.
IFAIL=-10
On entry, LDB=value and N=value.
Constraint: LDB≥N.
IFAIL=-12
On entry, LDC=value and N=value.
Constraint: LDC≥N.
IFAIL=-16
On entry, LDVL=value, N=value and JOBVL=value.
Constraint: when JOBVL='V', LDVL≥N.
IFAIL=-18
On entry, LDVR=value, N=value and JOBVR=value.
Constraint: when JOBVR='V', LDVR≥N.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

The algorithm is backward stable for problems that are not too heavily damped, that is B≤ A·C .

8 Parallelism and Performance

F02JQF is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
F02JQF makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

None.

10 Example

To solve the quadratic eigenvalue problem
λ 2 A + λB + C x = 0
where
A = 2 i 4 i 4 i 6 i 2 i 2 i 6 i 4 i 2 i ,  B = 3+3 i 2+2 i 1+1 i 2+2 i 1+1 i 3+3 i 1+1 i 3+3 i 2+2 i  and  C = 1 1 2 2 3 1 3 1 2 .
The example also returns the left eigenvectors, condition numbers for the computed eigenvalues and the maximum backward errors of the computed right and left eigenpairs.

10.1 Program Text

Program Text (f02jqfe.f90)

10.2 Program Data

Program Data (f02jqfe.d)

10.3 Program Results

Program Results (f02jqfe.r)

F02 Chapter Contents
F02 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F02SDF : NAG Library, Mark 26

F02 Chapter Contents
F02 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F02SDF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
▸▿ 9 Further Comments
9.1 Timing
9.2 Storage
9.3 Algorithmic Details
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F02SDF finds the eigenvector corresponding to a given real eigenvalue for the generalized problem Ax=λBx, or for the standard problem Ax=λx, where A and B are real band matrices.

2 Specification

SUBROUTINE F02SDF ( N, MA1, MB1, A, LDA, B, LDB, SYM, RELEP, RMU, VEC, D, IWORK, WORK, LWORK, IFAIL)
INTEGER | N, MA1, MB1, LDA, LDB, IWORK(N), LWORK, IFAIL
REAL (KIND=nag_wp) | A(LDA,N), B(LDB,N), RELEP, RMU, VEC(N), D(30), WORK(LWORK)
LOGICAL | SYM

3 Description

Given an approximation μ to a real eigenvalue λ of the generalized eigenproblem Ax=λBx, F02SDF attempts to compute the corresponding eigenvector by inverse iteration.
F02SDF first computes lower and upper triangular factors, L and U, of A-μB, using Gaussian elimination with interchanges, and then solves the equation Ux=e, where e=1,1,1,…,1 T – this is the first half iteration.
There are then three possible courses of action depending on the input value of D 1.
1. | D 1=0. This setting should be used if λ is an ill-conditioned eigenvalue (provided the matrix elements do not vary widely in order of magnitude). In this case it is essential to accept only a vector found after one half iteration, and μ must be a very good approximation to λ. If acceptable growth is achieved in the solution of Ux=e, then the normalized x is accepted as the eigenvector. If not, columns of an orthogonal matrix are tried in turn in place of e. If none of these give acceptable growth, the routine fails, indicating that μ was not a sufficiently good approximation to λ.
2. | D 1>0. This setting should be used if μ is moderately close to an eigenvalue which is not ill-conditioned (provided the matrix elements do not differ widely in order of magnitude). If acceptable growth is achieved in the solution of Ux=e, the normalized x is accepted as the eigenvector. If not, inverse iteration is performed. Up to 30 iterations are allowed to achieve a vector and a correction to μ which together give acceptably small residuals.
3. | D 1<0. This setting should be used if the elements of A and B vary widely in order of magnitude. Inverse iteration is performed, but a different convergence criterion is used.
See Section 9.3 for further details.
Note that the bandwidth of the matrix A must not be less than the bandwidth of B. If this is not so, either A must be filled out with zeros, or matrices A and B may be reversed and 1/μ supplied as an approximation to the eigenvalue 1/λ. Also it is assumed that A and B each have the same number of subdiagonals as superdiagonals. If this is not so, they must be filled out with zeros. If A and B are both symmetric, only the upper triangles need be supplied.

4 References

Peters G and Wilkinson J H (1979) Inverse iteration, ill-conditioned equations and Newton's method SIAM Rev. 21 339–360
Wilkinson J H (1965) The Algebraic Eigenvalue Problem Oxford University Press, Oxford
Wilkinson J H (1972) Inverse iteration in theory and practice Symposia Mathematica Volume X 361–379 Istituto Nazionale di Alta Matematica, Monograf, Bologna
Wilkinson J H (1974) Notes on inverse iteration and ill-conditioned eigensystems Acta Univ. Carolin. Math. Phys. 1–2 173–177
Wilkinson J H (1979) Kronecker's canonical form and the QZ algorithm Linear Algebra Appl. 28 285–303

5 Arguments

1:   N – INTEGERInput
On entry: n, the order of the matrices A and B.
Constraint: N≥1.
2:   MA1 – INTEGERInput
On entry: the value mA+1, where mA is the number of nonzero lines on each side of the diagonal of A. Thus the total bandwidth of A is 2 mA+1.
Constraint: 1≤MA1≤N.
3:   MB1 – INTEGERInput
On entry: if MB1≤0, B is assumed to be the unit matrix. Otherwise MB1 must specify the value mB+1, where mB is the number of nonzero lines on each side of the diagonal of B. Thus the total bandwidth of B is 2 mB+1.
Constraint: MB1≤MA1.
4:   A LDAN – REAL (KIND=nag_wp) arrayInput/Output
On entry: the n by n band matrix A. The mA subdiagonals must be stored in the first mA rows of the array; the diagonal in the (mA+1)th row; and the mA superdiagonals in rows mA+2 to 2 mA+1. Each row of the matrix must be stored in the corresponding column of the array. For example, if n=6 and mA=2 the storage scheme is:
* * a 31 a 42 a 53 a 64 * a 21 a 32 a 43 a 54 a 65 a 11 a 22 a 33 a 44 a 55 a 66 a 12 a 23 a 34 a 45 a 56 * a 13 a 24 a 35 a 46 * * .
Elements of the array marked * need not be set. The following code assigns the matrix elements within the band to the correct elements of the array:
 DO 20 J = 1, N
 DO 10 I = MAX(1,J-MA1+1), MIN(N,J+MA1-1)
 A(I-J+MA1,J) = matrix(J,I)
 10 CONTINUE
 20 CONTINUE
If SYM=.TRUE. (i.e., both A and B are symmetric), only the lower triangle of A need be stored in the first MA1 rows of the array.
On exit: details of the factorization of A-λ-B, where λ- is an estimate of the eigenvalue.
5:   LDA – INTEGERInput
On entry: the first dimension of the array A as declared in the (sub)program from which F02SDF is called.
Constraint: LDA≥2×MA1-1.
6:   B LDBN – REAL (KIND=nag_wp) arrayInput/Output
On entry: if MB1>0, B must contain the n by n band matrix B, stored in the same way as A. If SYM=.TRUE., only the lower triangle of B need be stored in the first MB1 rows of the array.
If MB1≤0, the array is not used.
On exit: elements in the top-left corner, and in the bottom right corner if SYM=.FALSE., are set to zero; otherwise the array is unchanged.
7:   LDB – INTEGERInput
On entry: the first dimension of the array B as declared in the (sub)program from which F02SDF is called.
Constraints:
  • if SYM=.FALSE., LDB≥2×MB1-1;
  • if SYM=.TRUE., LDB≥MB1.
8:   SYM – LOGICALInput
On entry: if SYM=.TRUE., both A and B are assumed to be symmetric and only their upper triangles need be stored. Otherwise SYM must be set to .FALSE..
9:   RELEP – REAL (KIND=nag_wp)Input
On entry: the relative error of the coefficients of the given matrices A and B. If the value of RELEP is less than the machine precision, the machine precision is used instead.
10:   RMU – REAL (KIND=nag_wp)Input
On entry: μ, an approximation to the eigenvalue for which the corresponding eigenvector is required.
11:   VEC N – REAL (KIND=nag_wp) arrayOutput
On exit: the eigenvector, normalized so that the largest element is unity, corresponding to the improved eigenvalue RMU+D 30.
12:   D 30 – REAL (KIND=nag_wp) arrayInput/Output
On entry: D 1 must be set to indicate the type of problem (see Section 3):
D 1>0.0
Indicates a well-conditioned eigenvalue.
D 1=0.0
Indicates an ill-conditioned eigenvalue.
D 1<0.0
Indicates that the matrices have elements varying widely in order of magnitude.
On exit: if D 1≠0.0 on entry, the successive corrections to μ are given in D i, for i=1,2,…,k, where k+1 is the total number of iterations performed. The final correction is also given in the last position, D 30, of the array. The remaining elements of D are set to zero.
If D 1=0.0 on entry, no corrections to μ are computed and D i is set to 0.0, for i=1,2,…,30. Thus in all three cases the best available approximation to the eigenvalue is RMU+D 30.
13:   IWORK N – INTEGER arrayWorkspace
14:   WORK LWORK – REAL (KIND=nag_wp) arrayWorkspace
15:   LWORK – INTEGERInput
On entry: the dimension of the array WORK as declared in the (sub)program from which F02SDF is called.
Constraints:
  • if D 1≠0.0, LWORK≥N×MA1+1;
  • if D 1=0.0, LWORK≥2×N.
16:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, | N<1,
or | MA1<1,
or | MA1>N,
or | LDA<2×MA1-1,
or | LDB<MB1 when SYM=.TRUE.,
or | LDB<2×MB1-1 when SYM=.FALSE. (LDB is not checked if MB1≤0).
IFAIL=2
On entry, MA1<MB1. Either fill out A with zeros, or reverse the roles of A and B, and replace RMU by its reciprocal, i.e., solve Bx=λ-1 Ax.
IFAIL=3
On entry, | LWORK<2×N when D 1=0.0,
or | LWORK<N×MA1+1 when D 1≠0.0.
IFAIL=4
A is null. If B is nonsingular, all the eigenvalues are zero and any set of N orthogonal vectors forms the eigensolution.
IFAIL=5
B is null. If A is nonsingular, all the eigenvalues are infinite, and the columns of the unit matrix are eigenvectors.
IFAIL=6
On entry, A and B are both null. The eigensolution is arbitrary.
IFAIL=7
D 1≠0.0 on entry and convergence is not achieved in 30 iterations. Either the eigenvalue is ill-conditioned or RMU is a poor approximation to the eigenvalue. See Section 9.3.
IFAIL=8
D 1=0.0 on entry and no eigenvector has been found after min N,5 back-substitutions. RMU is not a sufficiently good approximation to the eigenvalue.
IFAIL=9
D 1<0.0 on entry and RMU is too inaccurate for the solution to converge.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

The eigensolution is exact for some problem
A+E x=μ B+F x,
where E,F are of the order of η A+μ B, where η is the value used for RELEP.

8 Parallelism and Performance

F02SDF is not threaded in any implementation.

9 Further Comments

9.1 Timing

The time taken by F02SDF is approximately proportional to n 2 mA+1 2 for factorization, and to n 2 mA+1 for each iteration.

9.2 Storage

The storage of the matrices A and B is designed for efficiency on a paged machine.
F02SDF will work with full matrices but it will do so inefficiently, particularly in respect of storage requirements.

9.3 Algorithmic Details

Inverse iteration is performed according to the rule
A-μB y r+1=B xr
x r+ 1=1 α r+ 1 y r+ 1
where α r+1 is the element of y r+1 of largest magnitude.
Thus:
A-μB x r+1=1 α r+1 B xr.
Hence the residual corresponding to x r+1 is very small if α r+1 is very large (see Peters and Wilkinson (1979)). The first half iteration, U y 1=e, corresponds to taking L-1 PB x 0=e.
If μ is a very accurate eigenvalue, then there should always be an initial vector x 0 such that one half iteration gives a small residual and thus a good eigenvector. If the eigenvalue is ill-conditioned, then second and subsequent iterated vectors may not be even remotely close to an eigenvector of a neighbouring problem (see pages 374–376 of Wilkinson (1972) and Wilkinson (1974)). In this case it is essential to accept only a vector obtained after one half iteration.
However, for well-conditioned eigenvalues, there is no loss in performing more than one iteration (see page 376 of Wilkinson (1972)), and indeed it will be necessary to iterate if μ is not such a good approximation to the eigenvalue. When the iteration has converged, y r+1 will be some multiple of xr, y r+1=β r+1xr, say.
Therefore
A-μB β r+1xr=B xr,
giving
A-μ+1 β r+ 1 B xr=0.
Thus μ+ 1 β r+1 is a better approximation to the eigenvalue. β r+1 is obtained as the element of y r+1 which corresponds to the element of largest magnitude, +1, in xr. The routine terminates when A-μ+ 1 βr B xr is of the order of the machine precision relative to A+μB.
If the elements of A and B vary widely in order of magnitude, then A and B are excessively large and a different convergence test is required. The routine terminates when the difference between successive corrections to μ is small relative to μ.
In practice one does not necessarily know if the given problem is well-conditioned or ill-conditioned. In order to provide some information on the condition of the eigenvalue or the accuracy of μ in the event of failure, successive values of 1 βr are stored in the vector D when D 1 is nonzero on input. If these values appear to be converging steadily, then it is likely that μ was a poor approximation to the eigenvalue and it is worth trying again with RMU+D 30 as the initial approximation. If the values in D vary considerably in magnitude, then the eigenvalue is ill-conditioned.
A discussion of the significance of the singularity of A and/or B is given in relation to the QZ algorithm in Wilkinson (1979).

10 Example

Given the generalized eigenproblem Ax=λBx where
A= 1 1 2 -1 2 1 2 -1 3 1 2 -1 4 1 -1 5   and  B= 5 1 1 4 2 2 3 2 2 2 1 1 1
find the eigenvector corresponding to the approximate eigenvalue -12.33.
Although B is symmetric, A is not, so SYM must be set to .FALSE. and all the elements of B in the band must be supplied to the routine. A (as written above) has 1 subdiagonal and 2 superdiagonals, so MA1 must be set to 3 and A filled out with an additional subdiagonal of zeros. Each row of the matrices is read in as data in turn.

10.1 Program Text

Program Text (f02sdfe.f90)

10.2 Program Data

Program Data (f02sdfe.d)

10.3 Program Results

Program Results (f02sdfe.r)

F02 Chapter Contents
F02 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F02WDF : NAG Library, Mark 26

F02 Chapter Contents
F02 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F02WDF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
▸▿ 9 Further Comments
9.1 Timing
9.2 General Remarks
9.3 Determining the Rank of A
9.4 Storage Details of the QU Factorization
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F02WDF returns the Householder QU factorization of a real rectangular m by n m≥n matrix A. Further, on request or if A is not of full rank, part or all of the singular value decomposition of A is returned.

2 Specification

SUBROUTINE F02WDF ( M, N, A, LDA, WANTB, B, TOL, SVD, IRANK, Z, SV, WANTR, R, LDR, WANTPT, PT, LDPT, WORK, LWORK, IFAIL)
INTEGER | M, N, LDA, IRANK, LDR, LDPT, LWORK, IFAIL
REAL (KIND=nag_wp) | A(LDA,N), B(M), TOL, Z(N), SV(N), R(LDR,N), PT(LDPT,N), WORK(LWORK)
LOGICAL | WANTB, SVD, WANTR, WANTPT

3 Description

The real m by n m≥n matrix A is first factorized as
A=Q U 0 ,
where Q is an m by m orthogonal matrix and U is an n by n upper triangular matrix.
If either U is singular or SVD is supplied as .TRUE., then the singular value decomposition (SVD) of U is obtained so that U is factorized as
U=RD PT,
where R and P are n by n orthogonal matrices and D is the n by n diagonal matrix
D=diag s v 1,s v 2,…,s vn,
with s v 1≥s v 2≥⋯≥s vn≥0.
Note that the SVD of A is then given by
A=Q 1 D 0 PT  where  Q 1=Q R 0 0 I ,
the diagonal elements of D being the singular values of A.
The option to form a vector QT b, or if appropriate Q 1 T b, is also provided.
The rank of the matrix A, based upon a user-supplied argument TOL, is also returned.
The QU factorization of A is obtained by Householder transformations. To obtain the SVD of U the matrix is first reduced to bidiagonal form by means of plane rotations and then the QR algorithm is used to obtain the SVD of the bidiagonal form.

4 References

Wilkinson J H (1978) Singular Value Decomposition – Basic Aspects Numerical Software – Needs and Availability (ed D A H Jacobs) Academic Press

5 Arguments

1:   M – INTEGERInput
On entry: m, the number of rows of the matrix A.
Constraint: M≥N.
2:   N – INTEGERInput
On entry: n, the number of columns of the matrix A.
Constraint: 1≤N≤M.
3:   A LDAN – REAL (KIND=nag_wp) arrayInput/Output
On entry: the leading m by n part of A must contain the matrix to be factorized.
On exit: the leading m by n part of A, together with the n-element vector Z, contains details of the Householder QU factorization.
Details of the storage of the QU factorization are given in Section 9.4.
4:   LDA – INTEGERInput
On entry: the first dimension of the array A as declared in the (sub)program from which F02WDF is called.
Constraint: LDA≥M.
5:   WANTB – LOGICALInput
On entry: must be .TRUE. if QT b or Q 1 T b is required.
If on entry WANTB=.FALSE., B is not referenced.
6:   B M – REAL (KIND=nag_wp) arrayInput/Output
On entry: if WANTB is supplied as .TRUE., B must contain the m element vector b. Otherwise, B is not referenced.
On exit: contains Q 1 T b if SVD is returned as .TRUE. and QT b if SVD is returned as .FALSE..
7:   TOL – REAL (KIND=nag_wp)Input
On entry: must specify a relative tolerance to be used to determine the rank of A. TOL should be chosen as approximately the largest relative error in the elements of A. For example, if the elements of A are correct to about 4 significant figures, TOL should be set to about 5×10-4. See Section 9.3 for a description of how TOL is used to determine rank.
If TOL is outside the range ε,1.0, where ε is the machine precision, the value ε is used in place of TOL. For most problems this is unreasonably small.
8:   SVD – LOGICALInput/Output
On entry: must be .TRUE. if the singular values are to be found even if A is of full rank.
If before entry, SVD=.FALSE. and A is determined to be of full rank, only the QU factorization of A is computed.
On exit: is returned as .FALSE. if only the QU factorization of A has been obtained and is returned as .TRUE. if the singular values of A have been obtained.
9:   IRANK – INTEGEROutput
On exit: returns the rank of the matrix A. (It should be noted that it is possible for IRANK to be returned as n and SVD to be returned as .TRUE., even if SVD was supplied as .FALSE.. This means that the matrix U only just failed the test for nonsingularity.)
10:   Z N – REAL (KIND=nag_wp) arrayOutput
On exit: the n-element vector Z contains some details of the Householder transformations. See Section 9.4 for further information.
11:   SV N – REAL (KIND=nag_wp) arrayOutput
On exit: if SVD is returned as .TRUE., SV contains the n singular values of A arranged in descending order.
12:   WANTR – LOGICALInput
On entry: must be .TRUE. if the orthogonal matrix R is required when the singular values are computed.
If on entry WANTR=.FALSE., R is not referenced.
13:   R LDRN – REAL (KIND=nag_wp) arrayOutput
Note: the second dimension of the array R must be at least N if WANTR=.TRUE., and at least 1 otherwise.
On exit: if SVD is returned as .TRUE. and WANTR was supplied as .TRUE., the leading n by n part of R will contain the left-hand orthogonal matrix of the SVD of U.
14:   LDR – INTEGERInput
On entry: the first dimension of the array R as declared in the (sub)program from which F02WDF is called.
Constraints:
  • if WANTR=.TRUE., LDR≥N;
  • otherwise LDR≥1.
15:   WANTPT – LOGICALInput
On entry: must be .TRUE. if the orthogonal matrix PT is required when the singular values are computed.
Note that if SVD is returned as .TRUE., PT is referenced even if WANTPT is supplied as .FALSE., but see argument PT.
16:   PT LDPTN – REAL (KIND=nag_wp) arrayOutput
On exit: if SVD is returned as .TRUE. and WANTPT was supplied as .TRUE., the leading n by n part of PT contains the orthogonal matrix PT.
If SVD is returned as .TRUE., but WANTPT was supplied as .FALSE., the leading n by n part of PT is used for internal workspace.
17:   LDPT – INTEGERInput
On entry: the first dimension of the array PT as declared in the (sub)program from which F02WDF is called.
Constraint: LDPT≥N.
18:   WORK LWORK – REAL (KIND=nag_wp) arrayOutput
On exit: if SVD is returned as .FALSE., WORK 1 contains the condition number U EU-1 E of the upper triangular matrix U.
If SVD is returned as .TRUE., WORK 1 will contain the total number of iterations taken by the QR algorithm.
The rest of the array is used as workspace and so contains no meaningful information.
19:   LWORK – INTEGERInput
On entry: the dimension of the array WORK as declared in the (sub)program from which F02WDF is called.
Constraint: LWORK≥3×N.
20:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, | N<1,
or | M<N,
or | LDA<M,
or | LDR<N when WANTR=.TRUE.,
or | LDPT<N
or | LWORK<3×N.
(The routine only checks LDR if WANTR is supplied as .TRUE..)
IFAIL>1
The QR algorithm has failed to converge to the singular values in 50×N iterations. In this case SV 1,SV 2,…,SV IFAIL-1 may not have been correctly found and the remaining singular values may not be the smallest singular values. The matrix A has nevertheless been factorized as A=Q 1 C PT, where C is an upper bidiagonal matrix with SV 1,SV 2,…,SV n as its diagonal elements and WORK 2,WORK 3,…,WORK n as its superdiagonal elements.
This failure cannot occur if SVD is returned as .FALSE. and in any case is extremely rare.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

The computed factors Q, U, R, D and PT satisfy the relations
Q U 0 =A+E,
Q R 0 0 I D 0 PT=A+F
where E 2≤c 1 ε A 2, F 2≤c 2 ε A 2,
ε being the machine precision and c 1 and c 2 are modest functions of m and n. Note that A 2=s v 1.

8 Parallelism and Performance

F02WDF is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
F02WDF makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

9.1 Timing

The time taken by F02WDF to obtain the Householder QU factorization is approximately proportional to n 2 3 m-n.
The additional time taken to obtain the singular value decomposition is approximately proportional to n 3, where the constant of proportionality depends upon whether or not the orthogonal matrices R and PT are required.

9.2 General Remarks

Singular vectors associated with a zero or multiple singular value, are not uniquely determined, even in exact arithmetic, and very different results may be obtained if they are computed on different machines.
Unless otherwise stated in the Users' Note for your implementation, the routine may be called with the same array for arguments Z and SV, in which case, if SVD is returned as .TRUE., the singular values will overwrite the original contents of Z; also, if WANTPT=.FALSE., it may be called with the same array for arguments R and PT. However this is not standard Fortran, and may not work on all systems.
This routine is called by the least squares routine F04JGF.

9.3 Determining the Rank of A

Following the QU factorization of A, if SVD is supplied as .FALSE., then the condition number of U given by
C U=U F U-1 F
is found, where .F denotes the Frobenius norm, and if C U is such that
C U×TOL>1.0
then U is regarded as singular and the singular values of A are computed. If this test is not satisfied, then the rank of A is set to n. Note that if SVD is supplied as .TRUE. then this test is omitted.
When the singular values are computed, then the rank of A, r, is returned as the largest integer such that
s vr>TOL×s v 1,
unless s v 1=0 in which case r is returned as zero. That is, singular values which satisfy s vi≤TOL×s v 1 are regarded as negligible because relative perturbations of order TOL can make such singular values zero.

9.4 Storage Details of the QU Factorization

The kth Householder transformation matrix, Tk, used in the QU factorization is chosen to introduce the zeros into the kth column and has the form
Tk=I-2 0 u 0 uT ,  uT u=1,
where u is an m-k+1 element vector.
In place of u the routine actually computes the vector z given by
z=2 u 1 u.
The first element of z is stored in Z k and the remaining elements of z are overwritten on the subdiagonal elements of the kth column of A. The upper triangular matrix U is overwritten on the n by n upper triangular part of A.

10 Example

This example obtains the rank and the singular value decomposition of the 6 by 4 matrix A given by
A= 22.25 31.75 -38.25 65.50 20.00 26.75 28.50 -26.50 -15.25 24.25 27.75 18.50 27.25 10.00 3.00 2.00 -17.25 -30.75 11.25 7.50 17.25 30.75 -11.25 -7.50
the value TOL to be taken as 5×10-4.

10.1 Program Text

Program Text (f02wdfe.f90)

10.2 Program Data

Program Data (f02wdfe.d)

10.3 Program Results

Program Results (f02wdfe.r)

F02 Chapter Contents
F02 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F02WGF : NAG Library, Mark 26

F02 Chapter Contents
F02 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F02WGF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F02WGF returns leading terms in the singular value decomposition (SVD) of a real general matrix and computes the corresponding left and right singular vectors.

2 Specification

SUBROUTINE F02WGF ( M, N, K, NCV, AV, NCONV, SIGMA, U, LDU, V, LDV, RESID, IUSER, RUSER, IFAIL)
INTEGER | M, N, K, NCV, NCONV, LDU, LDV, IUSER(*), IFAIL
REAL (KIND=nag_wp) | SIGMA(NCV), U(LDU,NCV), V(LDV,NCV), RESID(NCV), RUSER(*)
EXTERNAL | AV

3 Description

F02WGF computes a few, k, of the largest singular values and corresponding vectors of an m by n matrix A. The value of k should be small relative to m and n, for example k∼O min m,n. The full singular value decomposition (SVD) of an m by n matrix A is given by
A=UΣ VT ,
where U and V are orthogonal and Σ is an m by n diagonal matrix with real diagonal elements, σi, such that
σ 1 ≥ σ 2 ≥⋯≥ σ min m,n ≥ 0 .
The σi are the singular values of A and the first min m,n columns of U and V are the left and right singular vectors of A.
If Uk, Vk denote the leading k columns of U and V respectively, and if Σ k denotes the leading principal submatrix of Σ, then
Ak ≡ Uk Σ k VT k
is the best rank-k approximation to A in both the 2-norm and the Frobenius norm.
The singular values and singular vectors satisfy
A vi = σi ui   and   AT ui = σi vi   so that   AT A νi = σi 2 νi ​ and ​ A AT ui = σ i 2 u i ,
where ui and vi are the ith columns of Uk and Vk respectively.
Thus, for m≥n, the largest singular values and corresponding right singular vectors are computed by finding eigenvalues and eigenvectors for the symmetric matrix AT A. For m<n, the largest singular values and corresponding left singular vectors are computed by finding eigenvalues and eigenvectors for the symmetric matrix A AT. These eigenvalues and eigenvectors are found using routines from Chapter F12. You should read the F12 Chapter Introduction for full details of the method used here.
The real matrix A is not explicitly supplied to F02WGF. Instead, you are required to supply a routine, AV, that must calculate one of the requested matrix-vector products Ax or AT x for a given real vector x (of length n or m respectively).

4 References

Wilkinson J H (1978) Singular Value Decomposition – Basic Aspects Numerical Software – Needs and Availability (ed D A H Jacobs) Academic Press

5 Arguments

1:   M – INTEGERInput
On entry: m, the number of rows of the matrix A.
Constraint: M≥0.
If M=0, an immediate return is effected.
2:   N – INTEGERInput
On entry: n, the number of columns of the matrix A.
Constraint: N≥0.
If N=0, an immediate return is effected.
3:   K – INTEGERInput
On entry: k, the number of singular values to be computed.
Constraint: 0<K<min M,N-1.
4:   NCV – INTEGERInput
On entry: the dimension of the arrays SIGMA and RESID and the second dimension of the arrays U and V as declared in the (sub)program from which F02WGF is called. This is the number of Lanczos basis vectors to use during the computation of the largest eigenvalues of AT A (m≥n) or A AT (m<n).
At present there is no a priori analysis to guide the selection of NCV relative to K. However, it is recommended that NCV≥2×K+1. If many problems of the same type are to be solved, you should experiment with varying NCV while keeping K fixed for a given test problem. This will usually decrease the required number of matrix-vector operations but it also increases the internal storage required to maintain the orthogonal basis vectors. The optimal ‘cross-over’ with respect to CPU time is problem dependent and must be determined empirically.
Constraint: K<NCV≤min M,N.
5:   AV – SUBROUTINE, supplied by the user.External Procedure
AV must return the vector result of the matrix-vector product Ax or AT x, as indicated by the input value of IFLAG, for the given vector x.
AV is called from F02WGF with the argument IUSER and RUSER as supplied to F02WGF. You are free to use these arrays to supply information to AV.
The specification of AV is:
SUBROUTINE AV ( IFLAG, M, N, X, AX, IUSER, RUSER)
INTEGER | IFLAG, M, N, IUSER(*)
REAL (KIND=nag_wp) | X(*), AX(*), RUSER(*)
1:   IFLAG – INTEGERInput/Output
On entry: if IFLAG=1, AX must return the m-vector result of the matrix-vector product Ax.
If IFLAG=2, AX must return the n-vector result of the matrix-vector product AT x.
On exit: may be used as a flag to indicate a failure in the computation of Ax or AT x. If IFLAG is negative on exit from AV, F02WGF will exit immediately with IFAIL set to IFLAG.
2:   M – INTEGERInput
On entry: the number of rows of the matrix A.
3:   N – INTEGERInput
On entry: the number of columns of the matrix A.
4:   X* – REAL (KIND=nag_wp) arrayInput
On entry: the vector to be pre-multiplied by the matrix A or AT.
5:   AX* – REAL (KIND=nag_wp) arrayOutput
On exit: if IFLAG=1, contains the m-vector result of the matrix-vector product Ax.
If IFLAG=2, contains the n-vector result of the matrix-vector product AT x.
6:   IUSER* – INTEGER arrayUser Workspace
7:   RUSER* – REAL (KIND=nag_wp) arrayUser Workspace
AV is called with the arguments IUSER and RUSER as supplied to F02WGF. You are free to use the arrays IUSER and RUSER to supply information to AV as an alternative to using COMMON global variables.
AV must either be a module subprogram USEd by, or declared as EXTERNAL in, the (sub)program from which F02WGF is called. Arguments denoted as Input must not be changed by this procedure.
6:   NCONV – INTEGEROutput
On exit: the number of converged singular values found.
7:   SIGMA NCV – REAL (KIND=nag_wp) arrayOutput
On exit: the NCONV converged singular values are stored in the first NCONV elements of SIGMA.
8:   U LDUNCV – REAL (KIND=nag_wp) arrayOutput
On exit: the left singular vectors corresponding to the singular values stored in SIGMA.
The ith element of the jth left singular vector uj is stored in U ij, for i=1,2,…,m and j=1,2,…,NCONV.
9:   LDU – INTEGERInput
On entry: the first dimension of the array U as declared in the (sub)program from which F02WGF is called.
Constraint: LDU≥max 1,M.
10:   V LDVNCV – REAL (KIND=nag_wp) arrayOutput
On exit: the right singular vectors corresponding to the singular values stored in SIGMA.
The ith element of the jth right singular vector vj is stored in V ij, for i=1,2,…,n and j=1,2,…,NCONV.
11:   LDV – INTEGERInput
On entry: the first dimension of the array V as declared in the (sub)program from which F02WGF is called.
Constraint: LDV≥max 1,N.
12:   RESID NCV – REAL (KIND=nag_wp) arrayOutput
On exit: the residual A vj - σj uj , for m≥n, or AT uj - σj vj , for m<n, for each of the converged singular values σj and corresponding left and right singular vectors uj and vj.
13:   IUSER* – INTEGER arrayUser Workspace
14:   RUSER* – REAL (KIND=nag_wp) arrayUser Workspace
IUSER and RUSER are not used by F02WGF, but are passed directly to AV and may be used to pass information to this routine as an alternative to using COMMON global variables.
15:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).
F02WGF returns with IFAIL=0 if at least k singular values have converged and the corresponding left and right singular vectors have been computed.

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, M=value.
Constraint: M≥0.
IFAIL=2
On entry, N=value.
Constraint: N≥0.
IFAIL=3
On entry, K=value.
Constraint: K>0.
IFAIL=4
On entry, K=value, NCV=value, M=value and N=value.
Constraint: K<NCV≤min M,N.
IFAIL=5
On entry, LDU=value and M=value.
Constraint: LDU≥M.
IFAIL=6
On entry, LDV=value and N=value.
Constraint: LDV≥N.
IFAIL=8
The maximum number of iterations has been reached. The maximum number of iterations =value. The number of converged eigenvalues =value.
IFAIL=9
No shifts could be applied during a cycle of the implicitly restarted Lanczos iteration.
IFAIL=10
Could not build a full Lanczos factorization.
IFAIL=11
The number of eigenvalues found to sufficient accuracy is zero.
IFAIL=20
An error occurred during an internal call. Consider increasing the size of NCV relative to K.
IFAIL<0
On output from user-defined routine AV, IFLAG was set to a negative value, IFLAG=value.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

See Section 2.14.2 in the F08 Chapter Introduction.

8 Parallelism and Performance

F02WGF is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
F02WGF makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

None.

10 Example

This example finds the four largest singular values (σ) and corresponding right and left singular vectors for the matrix A, where A is the m by n real matrix derived from the simplest finite difference discretization of the two-dimensional kernel k s,t dt where
k s,t = s t-1 if ​0≤s≤t≤ 1 t s-1 if ​0≤t<s≤1 .

10.1 Program Text

Program Text (f02wgfe.f90)

10.2 Program Data

Program Data (f02wgfe.d)

10.3 Program Results

Program Results (f02wgfe.r)

F02 Chapter Contents
F02 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F02WUF : NAG Library, Mark 26

F02 Chapter Contents
F02 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F02WUF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F02WUF returns all, or part, of the singular value decomposition of a real upper triangular matrix.

2 Specification

SUBROUTINE F02WUF ( N, A, LDA, NCOLB, B, LDB, WANTQ, Q, LDQ, SV, WANTP, WORK, IFAIL)
INTEGER | N, LDA, NCOLB, LDB, LDQ, IFAIL
REAL (KIND=nag_wp) | A(LDA,*), B(LDB,*), Q(LDQ,*), SV(N), WORK(*)
LOGICAL | WANTQ, WANTP

3 Description

The n by n upper triangular matrix R is factorized as
R=QS PT,
where Q and P are n by n orthogonal matrices and S is an n by n diagonal matrix with non-negative diagonal elements, σ 1,σ 2,…,σn, ordered such that
σ 1≥σ 2≥…≥σn≥0.
The columns of Q are the left-hand singular vectors of R, the diagonal elements of S are the singular values of R and the columns of P are the right-hand singular vectors of R.
Either or both of Q and PT may be requested and the matrix C given by
C=QT B,
where B is an n by ncolb given matrix, may also be requested.
The routine obtains the singular value decomposition by first reducing R to bidiagonal form by means of Givens plane rotations and then using the QR algorithm to obtain the singular value decomposition of the bidiagonal form.
Good background descriptions to the singular value decomposition are given in Chan (1982), Dongarra et al. (1979), Golub and Van Loan (1996), Hammarling (1985) and Wilkinson (1978).
Note that if K is any orthogonal diagonal matrix so that
K KT=I
(that is the diagonal elements of K are +1 or -1) then
A=QK S PK T
is also a singular value decomposition of A.

4 References

Chan T F (1982) An improved algorithm for computing the singular value decomposition ACM Trans. Math. Software 8 72–83
Dongarra J J, Moler C B, Bunch J R and Stewart G W (1979) LINPACK Users' Guide SIAM, Philadelphia
Golub G H and Van Loan C F (1996) Matrix Computations (3rd Edition) Johns Hopkins University Press, Baltimore
Hammarling S (1985) The singular value decomposition in multivariate statistics SIGNUM Newsl. 20(3) 2–25
Wilkinson J H (1978) Singular Value Decomposition – Basic Aspects Numerical Software – Needs and Availability (ed D A H Jacobs) Academic Press

5 Arguments

1:   N – INTEGERInput
On entry: n, the order of the matrix R.
If N=0, an immediate return is effected.
Constraint: N≥0.
2:   A LDA* – REAL (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array A must be at least max 1,N.
On entry: the leading n by n upper triangular part of the array A must contain the upper triangular matrix R.
On exit: if WANTP=.TRUE., the n by n part of A will contain the n by n orthogonal matrix PT, otherwise the n by n upper triangular part of A is used as internal workspace, but the strictly lower triangular part of A is not referenced.
3:   LDA – INTEGERInput
On entry: the first dimension of the array A as declared in the (sub)program from which F02WUF is called.
Constraint: LDA≥max 1,N.
4:   NCOLB – INTEGERInput
On entry: ncolb, the number of columns of the matrix B.
If NCOLB=0, the array B is not referenced.
Constraint: NCOLB≥0.
5:   B LDB* – REAL (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array B must be at least max 1,NCOLB.
On entry: with NCOLB>0, the leading n by ncolb part of the array B must contain the matrix to be transformed.
On exit: the leading n by ncolb part of the array B is overwritten by the matrix QT B.
6:   LDB – INTEGERInput
On entry: the first dimension of the array B as declared in the (sub)program from which F02WUF is called.
Constraints:
  • if NCOLB>0, LDB≥max 1,N;
  • otherwise LDB≥1.
7:   WANTQ – LOGICALInput
On entry: must be .TRUE. if the matrix Q is required.
If WANTQ=.FALSE., the array Q is not referenced.
8:   Q LDQ* – REAL (KIND=nag_wp) arrayOutput
Note: the second dimension of the array Q must be at least max 1,N if WANTQ=.TRUE., and at least 1 otherwise.
On exit: with WANTQ=.TRUE., the leading n by n part of the array Q will contain the orthogonal matrix Q. Otherwise the array Q is not referenced.
9:   LDQ – INTEGERInput
On entry: the first dimension of the array Q as declared in the (sub)program from which F02WUF is called.
Constraints:
  • if WANTQ=.TRUE., LDQ≥max 1,N;
  • otherwise LDQ≥1.
10:   SV N – REAL (KIND=nag_wp) arrayOutput
On exit: the array SV will contain the n diagonal elements of the matrix S.
11:   WANTP – LOGICALInput
On entry: must be .TRUE. if the matrix PT is required, in which case PT is overwritten on the array A, otherwise WANTP must be .FALSE..
12:   WORK* – REAL (KIND=nag_wp) arrayOutput
Note: the dimension of the array WORK must be at least max 1,2×N-1 if NCOLB=0 and WANTQ=.FALSE. and WANTP=.FALSE., max 1,3×N-1 if (NCOLB=0 and WANTQ=.FALSE. and WANTP=.TRUE.) or (WANTP=.FALSE. and (NCOLB>0 or WANTQ=.TRUE.)), and at least max 1,5×N-1 otherwise.
On exit: WORK N contains the total number of iterations taken by the QR algorithm.
The rest of the array is used as internal workspace.
13:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=-1
On entry, | N<0,
or | LDA<N,
or | NCOLB<0,
or | LDB<N and NCOLB>0,
or | LDQ<N and WANTQ=.TRUE..
IFAIL>0
The QR algorithm has failed to converge in 50×N iterations. In this case SV 1,SV 2,…,SV IFAIL may not have been found correctly and the remaining singular values may not be the smallest. The matrix R will nevertheless have been factorized as R=QE PT, where E is a bidiagonal matrix with SV 1,SV 2,…,SV n as the diagonal elements and WORK 1,WORK 2,…,WORK n-1 as the superdiagonal elements.
This failure is not likely to occur.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

The computed factors Q, S and P satisfy the relation
QS PT=R+E,
where
E≤cε A ,
ε is the machine precision, c is a modest function of n and . denotes the spectral (two) norm. Note that A=SV 1.
A similar result holds for the computed matrix QT B.
The computed matrix Q satisfies the relation
Q=T+F,
where T is exactly orthogonal and
F≤dε,
where d is a modest function of n. A similar result holds for P.

8 Parallelism and Performance

F02WUF is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
F02WUF makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

For given values of NCOLB, WANTQ and WANTP, the number of floating-point operations required is approximately proportional to n 3.
Following the use of this routine the rank of R may be estimated by a call to the INTEGER FUNCTION F06KLF. The statement
IRANK = F06KLF(N,SV,1,TOL)
returns the value k-1 in IRANK, where k is the smallest integer for which SV k<tol×SV 1, and tol is the tolerance supplied in TOL, so that IRANK is an estimate of the rank of S and thus also of R. If TOL is supplied as negative then the machine precision is used in place of TOL.

10 Example

This example finds the singular value decomposition of the 3 by 3 upper triangular matrix
A= -4 -2 -3 0 -3 -2 0 0 -4 ,
together with the vector QT b for the vector
b= -1 -1 -1 .

10.1 Program Text

Program Text (f02wufe.f90)

10.2 Program Data

Program Data (f02wufe.d)

10.3 Program Results

Program Results (f02wufe.r)

F02 Chapter Contents
F02 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F02XUF : NAG Library, Mark 26

F02 Chapter Contents
F02 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F02XUF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F02XUF returns all, or part, of the singular value decomposition of a complex upper triangular matrix.

2 Specification

SUBROUTINE F02XUF ( N, A, LDA, NCOLB, B, LDB, WANTQ, Q, LDQ, SV, WANTP, RWORK, CWORK, IFAIL)
INTEGER | N, LDA, NCOLB, LDB, LDQ, IFAIL
REAL (KIND=nag_wp) | SV(N), RWORK(*)
COMPLEX (KIND=nag_wp) | A(LDA,*), B(LDB,*), Q(LDQ,*), CWORK(max(1,N-1))
LOGICAL | WANTQ, WANTP

3 Description

The n by n upper triangular matrix R is factorized as
R=QS PH,
where Q and P are n by n unitary matrices and S is an n by n diagonal matrix with real non-negative diagonal elements, s v 1,s v 2,…,s vn, ordered such that
s v 1≥s v 2≥⋯≥s vn≥0.
The columns of Q are the left-hand singular vectors of R, the diagonal elements of S are the singular values of R and the columns of P are the right-hand singular vectors of R.
Either or both of Q and PH may be requested and the matrix C given by
C=QH B,
where B is an n by ncolb given matrix, may also be requested.
F02XUF obtains the singular value decomposition by first reducing R to bidiagonal form by means of Givens plane rotations and then using the QR algorithm to obtain the singular value decomposition of the bidiagonal form.
Good background descriptions to the singular value decomposition are given in Dongarra et al. (1979), Hammarling (1985) and Wilkinson (1978).
Note that if K is any unitary diagonal matrix so that
K KH=I,
then
A=QK S PK H
is also a singular value decomposition of A.

4 References

Dongarra J J, Moler C B, Bunch J R and Stewart G W (1979) LINPACK Users' Guide SIAM, Philadelphia
Hammarling S (1985) The singular value decomposition in multivariate statistics SIGNUM Newsl. 20(3) 2–25
Wilkinson J H (1978) Singular Value Decomposition – Basic Aspects Numerical Software – Needs and Availability (ed D A H Jacobs) Academic Press

5 Arguments

1:   N – INTEGERInput
On entry: n, the order of the matrix R.
If N=0, an immediate return is effected.
Constraint: N≥0.
2:   A LDA* – COMPLEX (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array A must be at least max 1,N.
On entry: the leading n by n upper triangular part of the array A must contain the upper triangular matrix R.
On exit: if WANTP=.TRUE., the n by n part of A will contain the n by n unitary matrix PH, otherwise the n by n upper triangular part of A is used as internal workspace, but the strictly lower triangular part of A is not referenced.
3:   LDA – INTEGERInput
On entry: the first dimension of the array A as declared in the (sub)program from which F02XUF is called.
Constraint: LDA≥max 1,N.
4:   NCOLB – INTEGERInput
On entry: ncolb, the number of columns of the matrix B.
If NCOLB=0, the array B is not referenced.
Constraint: NCOLB≥0.
5:   B LDB* – COMPLEX (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array B must be at least max 1,NCOLB.
On entry: if NCOLB>0, the leading n by ncolb part of the array B must contain the matrix to be transformed.
On exit: is overwritten by the n by ncolb matrix QH B.
6:   LDB – INTEGERInput
On entry: the first dimension of the array B as declared in the (sub)program from which F02XUF is called.
Constraints:
  • if NCOLB>0, LDB≥max 1,N;
  • otherwise LDB≥1.
7:   WANTQ – LOGICALInput
On entry: must be .TRUE. if the matrix Q is required.
If WANTQ=.FALSE. then the array Q is not referenced.
8:   Q LDQ* – COMPLEX (KIND=nag_wp) arrayOutput
Note: the second dimension of the array Q must be at least max 1,N if WANTQ=.TRUE., and at least 1 otherwise.
On exit: if WANTQ=.TRUE., the leading n by n part of the array Q will contain the unitary matrix Q. Otherwise the array Q is not referenced.
9:   LDQ – INTEGERInput
On entry: the first dimension of the array Q as declared in the (sub)program from which F02XUF is called.
Constraints:
  • if WANTQ=.TRUE., LDQ≥max 1,N;
  • otherwise LDQ≥1.
10:   SV N – REAL (KIND=nag_wp) arrayOutput
On exit: the n diagonal elements of the matrix S.
11:   WANTP – LOGICALInput
On entry: must be .TRUE. if the matrix PH is required, in which case PH is returned in the array A, otherwise WANTP must be .FALSE..
12:   RWORK* – REAL (KIND=nag_wp) arrayOutput
Note: the dimension of the array RWORK must be at least max 1,2×N-1 if NCOLB=0 and WANTQ=.FALSE. and WANTP=.FALSE., max 1,3×N-1 if NCOLB=0 and WANTQ=.FALSE. and WANTP=.TRUE. or NCOLB>0 and WANTP=.FALSE. or WANTQ=.TRUE. and WANTP=.FALSE., and at least max 1,5×N-1 otherwise.
On exit: RWORK(N) contains the total number of iterations taken by the QR algorithm.
The rest of the array is used as workspace.
13:   CWORK max 1,N-1 – COMPLEX (KIND=nag_wp) arrayWorkspace
14:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=-1
On entry, | N<0,
or | LDA<N,
or | NCOLB<0,
or | LDB<N and NCOLB>0,
or | LDQ<N and WANTQ=.TRUE.
IFAIL>0
The QR algorithm has failed to converge in 50×N iterations. In this case SV 1,SV 2,…,SV IFAIL may not have been found correctly and the remaining singular values may not be the smallest. The matrix R will nevertheless have been factorized as R=QE PH, where E is a bidiagonal matrix with SV 1,SV 2,…,SV n as the diagonal elements and RWORK 1,RWORK 2,…,RWORK n-1 as the superdiagonal elements.
This failure is not likely to occur.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

The computed factors Q, S and P satisfy the relation
QS PH=A+E,
where
E≤cε A,
ε is the machine precision, c is a modest function of n and . denotes the spectral (two) norm. Note that A=s v 1.

8 Parallelism and Performance

F02XUF is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
F02XUF makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

For given values of NCOLB, WANTQ and WANTP, the number of floating-point operations required is approximately proportional to n 3.
Following the use of this routine the rank of R may be estimated by a call to the INTEGER FUNCTION F06KLF. The statement
IRANK = F06KLF(N,SV,1,TOL)
returns the value k-1 in IRANK, where k is the smallest integer for which sv k<tol×sv 1, where tol is the tolerance supplied in TOL, so that IRANK is an estimate of the rank of S and thus also of R. If TOL is supplied as negative then the machine precision is used in place of TOL.

10 Example

This example finds the singular value decomposition of the 3 by 3 upper triangular matrix
A = 1 1+i 1+i 0 -2 i+ -1-i 0 0 i+ -3 i+
together with the vector QH b for the vector
b= 1+1 i -1 i+0 -1+1 i .

10.1 Program Text

Program Text (f02xufe.f90)

10.2 Program Data

Program Data (f02xufe.d)

10.3 Program Results

Program Results (f02xufe.r)

F02 Chapter Contents
F02 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F03BAF : NAG Library, Mark 26

F03 Chapter Contents
F03 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F03BAF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F03BAF computes the determinant of a real n by n matrix A. F07ADF (DGETRF) must be called first to supply the matrix A in factorized form.

2 Specification

SUBROUTINE F03BAF ( N, A, LDA, IPIV, D, ID, IFAIL)
INTEGER | N, LDA, IPIV(N), ID, IFAIL
REAL (KIND=nag_wp) | A(LDA,*), D

3 Description

F03BAF computes the determinant of a real n by n matrix A that has been factorized by a call to F07ADF (DGETRF). The determinant of A is the product of the diagonal elements of U with the correct sign determined by the row interchanges.

4 References

Wilkinson J H and Reinsch C (1971) Handbook for Automatic Computation II, Linear Algebra Springer–Verlag

5 Arguments

1:   N – INTEGERInput
On entry: n, the order of the matrix A.
Constraint: N>0.
2:   A LDA* – REAL (KIND=nag_wp) arrayInput
Note: the second dimension of the array A must be at least N.
On entry: the n by n matrix A in factorized form as returned by F07ADF (DGETRF).
3:   LDA – INTEGERInput
On entry: the first dimension of the array A as declared in the (sub)program from which F03BAF is called.
Constraint: LDA≥N.
4:   IPIV N – INTEGER arrayInput
On entry: the row interchanges used to factorize matrix A as returned by F07ADF (DGETRF).
5:   D – REAL (KIND=nag_wp)Output
6:   ID – INTEGEROutput
On exit: the determinant of A is given by D×2.0 ID. It is given in this form to avoid overflow or underflow.
7:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, N=value.
Constraint: N≥1.
IFAIL=3
On entry, LDA=value and N=value.
Constraint: LDA≥N.
IFAIL=4
The matrix A is approximately singular.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

The accuracy of the determinant depends on the conditioning of the original matrix. For a detailed error analysis, see page 107 of Wilkinson and Reinsch (1971).

8 Parallelism and Performance

F03BAF is not threaded in any implementation.

9 Further Comments

The time taken by F03BAF is approximately proportional to n.

10 Example

This example computes the LU factorization with partial pivoting, and calculates the determinant, of the real matrix
33 16 72 -24 -10 -57 -8 -4 -17 .

10.1 Program Text

Program Text (f03bafe.f90)

10.2 Program Data

Program Data (f03bafe.d)

10.3 Program Results

Program Results (f03bafe.r)

F03 Chapter Contents
F03 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F03BFF : NAG Library, Mark 26

F03 Chapter Contents
F03 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F03BFF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F03BFF computes the determinant of a real n by n symmetric positive definite matrix A. F07FDF (DPOTRF) must be called first to supply the symmetric matrix A in Cholesky factorized form. The storage (upper or lower triangular) used by F07FDF (DPOTRF) is not relevant to F03BFF since only the diagonal elements of the factorized A are referenced.

2 Specification

SUBROUTINE F03BFF ( N, A, LDA, D, ID, IFAIL)
INTEGER | N, LDA, ID, IFAIL
REAL (KIND=nag_wp) | A(LDA,*), D

3 Description

F03BFF computes the determinant of a real n by n symmetric positive definite matrix A that has been factorized as A=UT U, where U is upper triangular, or A=L LT, where L is lower triangular. The determinant is the product of the squares of the diagonal elements of U or L. The Cholesky factorized form of the matrix must be supplied; this is returned by a call to F07FDF (DPOTRF).

4 References

Wilkinson J H and Reinsch C (1971) Handbook for Automatic Computation II, Linear Algebra Springer–Verlag

5 Arguments

1:   N – INTEGERInput
On entry: n, the order of the matrix A.
Constraint: N>0.
2:   A LDA* – REAL (KIND=nag_wp) arrayInput
Note: the second dimension of the array A must be at least N.
On entry: the lower or upper triangle of the Cholesky factorized form of the n by n positive definite symmetric matrix A. Only the diagonal elements are referenced.
3:   LDA – INTEGERInput
On entry: the first dimension of the array A as declared in the (sub)program from which F03BFF is called.
Constraint: LDA≥N.
4:   D – REAL (KIND=nag_wp)Output
5:   ID – INTEGEROutput
On exit: the determinant of A is given by D×2.0 ID. It is given in this form to avoid overflow or underflow.
6:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, N=value.
Constraint: N>0.
IFAIL=3
On entry, LDA=value and N=value.
Constraint: LDA≥N.
IFAIL=4
The matrix A is not positive definite.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

The accuracy of the determinant depends on the conditioning of the original matrix. For a detailed error analysis see page 25 of Wilkinson and Reinsch (1971).

8 Parallelism and Performance

F03BFF is not threaded in any implementation.

9 Further Comments

The time taken by F03BFF is approximately proportional to n.

10 Example

This example computes a Cholesky factorization and calculates the determinant of the real symmetric positive definite matrix
6 7 6 5 7 11 8 7 6 8 11 9 5 7 9 11 .

10.1 Program Text

Program Text (f03bffe.f90)

10.2 Program Data

Program Data (f03bffe.d)

10.3 Program Results

Program Results (f03bffe.r)

F03 Chapter Contents
F03 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F03BHF : NAG Library, Mark 26

F03 Chapter Contents
F03 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F03BHF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F03BHF computes the determinant of a n by n symmetric positive definite banded matrix A that has been stored in band-symmetric storage. F07HDF (DPBTRF) must be called first to supply the Cholesky factorized form. The storage (upper or lower triangular) used by F07HDF (DPBTRF) is relevant as this determines which elements of the stored factorized form are referenced.

2 Specification

SUBROUTINE F03BHF ( UPLO, N, KD, AB, LDAB, D, ID, IFAIL)
INTEGER | N, KD, LDAB, ID, IFAIL
REAL (KIND=nag_wp) | AB(LDAB,*), D
CHARACTER(1) | UPLO

3 Description

The determinant of A is calculated using the Cholesky factorization A=UT U, where U is an upper triangular band matrix, or A=L LT, where L is a lower triangular band matrix. The determinant of A is the product of the squares of the diagonal elements of U or L.

4 References

Wilkinson J H and Reinsch C (1971) Handbook for Automatic Computation II, Linear Algebra Springer–Verlag

5 Arguments

1:   UPLO – CHARACTER(1)Input
On entry: indicates whether the upper or lower triangular part of A was stored and how it was factorized. This should not be altered following a call to F07HDF (DPBTRF).
UPLO='U'
The upper triangular part of A was originally stored and A was factorized as UT U where U is upper triangular.
UPLO='L'
The lower triangular part of A was originally stored and A was factorized as L LT where L is lower triangular.
Constraint: UPLO='U' or 'L'.
2:   N – INTEGERInput
On entry: n, the order of the matrix A.
Constraint: N>0.
3:   KD – INTEGERInput
On entry: kd, the number of superdiagonals or subdiagonals of the matrix A.
Constraint: KD≥0.
4:   AB LDAB* – REAL (KIND=nag_wp) arrayInput
Note: the second dimension of the array AB must be at least max 1,N.
On entry: the Cholesky factor of A, as returned by F07HDF (DPBTRF).
5:   LDAB – INTEGERInput
On entry: the first dimension of the array AB as declared in the subprogram from which F03BHF is called.
Constraint: LDAB≥KD+1.
6:   D – REAL (KIND=nag_wp)Output
7:   ID – INTEGEROutput
On exit: the determinant of A is given by D×2.0 ID. It is given in this form to avoid overflow or underflow.
8:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, UPLO=value.
Constraint: UPLO='L' or 'U'.
IFAIL=2
On entry, N=value.
Constraint: N>0.
IFAIL=3
On entry, KD=value.
Constraint: KD≥0.
IFAIL=5
On entry, LDAB=value and KD=value.
Constraint: LDAB≥KD+1.
IFAIL=6
The matrix A is not positive definite.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

The accuracy of the determinant depends on the conditioning of the original matrix. For a detailed error analysis see page 54 of Wilkinson and Reinsch (1971).

8 Parallelism and Performance

F03BHF is not threaded in any implementation.

9 Further Comments

The time taken by F03BHF is approximately proportional to n.
This routine should only be used when m≪n since as m approaches n, it becomes less efficient to take advantage of the band form.

10 Example

This example calculates the determinant of the real symmetric positive definite band matrix
5 -4 1 -4 6 -4 1 1 -4 6 -4 1 1 -4 6 -4 1 1 -4 6 -4 1 1 -4 6 -4 1 -4 5 .

10.1 Program Text

Program Text (f03bhfe.f90)

10.2 Program Data

Program Data (f03bhfe.d)

10.3 Program Results

Program Results (f03bhfe.r)

F03 Chapter Contents
F03 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F03BNF : NAG Library, Mark 26

F03 Chapter Contents
F03 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F03BNF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F03BNF computes the determinant of a complex n by n matrix A. F07ARF (ZGETRF) must be called first to supply the matrix A in factorized form.

2 Specification

SUBROUTINE F03BNF ( N, A, LDA, IPIV, D, ID, IFAIL)
INTEGER | N, LDA, IPIV(N), ID(2), IFAIL
COMPLEX (KIND=nag_wp) | A(LDA,*), D

3 Description

F03BNF computes the determinant of a complex n by n matrix A that has been factorized by a call to F07ARF (ZGETRF). The determinant of A is the product of the diagonal elements of U with the correct sign determined by the row interchanges.

4 References

Wilkinson J H and Reinsch C (1971) Handbook for Automatic Computation II, Linear Algebra Springer–Verlag

5 Arguments

1:   N – INTEGERInput
On entry: n, the order of the matrix A.
Constraint: N>0.
2:   A LDA* – COMPLEX (KIND=nag_wp) arrayInput
Note: the second dimension of the array A must be at least N.
On entry: the n by n matrix A in factorized form as returned by F07ARF (ZGETRF).
3:   LDA – INTEGERInput
On entry: the first dimension of the array A as declared in the (sub)program from which F03BNF is called.
Constraint: LDA≥N.
4:   IPIV N – INTEGER arrayInput
On entry: the row interchanges used to factorize matrix A as returned by F07ARF (ZGETRF).
5:   D – COMPLEX (KIND=nag_wp)Output
On exit: the mantissa of the real and imaginary parts of the determinant.
6:   ID 2 – INTEGER arrayOutput
On exit: the exponents for the real and imaginary parts of the determinant. The determinant, d=dr,di, is returned as dr=Dr×2 j and di=Di×2 k, where D=Dr,Di and j and k are stored in the first and second elements respectively of the array ID on successful exit.
7:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, N=value.
Constraint: N≥1.
IFAIL=3
On entry, LDA=value and N=value.
Constraint: LDA≥N.
IFAIL=4
The matrix A is approximately singular.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

The accuracy of the determinant depends on the conditioning of the original matrix. For a detailed error analysis, see page 107 of Wilkinson and Reinsch (1971).

8 Parallelism and Performance

F03BNF is not threaded in any implementation.

9 Further Comments

The time taken by F03BNF is approximately proportional to n.

10 Example

This example calculates the determinant of the complex matrix
1 1+2 i 2+10 i 1+i 3 i -5+14 i 1+i 5 i -8+20 i .

10.1 Program Text

Program Text (f03bnfe.f90)

10.2 Program Data

Program Data (f03bnfe.d)

10.3 Program Results

Program Results (f03bnfe.r)

F03 Chapter Contents
F03 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F03 Chapter Contents : NAG Library Manual, Mark 26

F03 Chapter Introduction
NAG Library Manual

NAG Library Chapter Contents

F03 – Determinants

F03 Chapter Introduction – a description of the Chapter and an overview of the algorithms available

Routine Name | Mark of Introduction | Purpose
F03BAF Example Text Example Data | 23 | nagf_det_real_gen Determinant of real matrix, matrix already factorized by F07ADF (DGETRF)
F03BFF Example Text Example Data | 23 | nagf_det_real_sym Determinant of real symmetric positive definite matrix
F03BHF Example Text Example Data | 23 | nagf_det_real_band_sym Determinant of real symmetric positive definite banded matrix previously factorized by F07HDF (DPBTRF)
F03BNF Example Text Example Data | 23 | nagf_det_complex_gen Determinant of complex matrix previously LU factorized
F03 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F03 Chapter Introduction : NAG Library, Mark 26

F03 Chapter Contents
NAG Library Manual

NAG Library Chapter Introduction

F03 – Determinants

▸▿ Contents

1 Scope of the Chapter
2 Background to the Problems
3 Recommendations on Choice and Use of Available Routines
4 Decision Trees
5 Functionality Index
6 Auxiliary Routines Associated with Library Routine Arguments
7 Routines Withdrawn or Scheduled for Withdrawal
8 References

1 Scope of the Chapter

This chapter is concerned with the calculation of determinants of square matrices.

2 Background to the Problems

The routines in this chapter compute the determinant of a square matrix A. The matrix is assumed to have first been decomposed into triangular factors
A=LU ,
using routines from Chapter F07.
If A is positive definite, then U=LT, and the determinant is the product of the squares of the diagonal elements of L. Otherwise, the routines in this chapter use the Dolittle form of the LU decomposition, where L has unit elements on its diagonal. The determinant is then the product of the diagonal elements of U, taking account of possible sign changes due to row interchanges.
To avoid overflow or underflow in the computation of the determinant, some scaling is associated with each multiplication in the product of the relevant diagonal elements. The final value is represented by
det⁡A=d×2 id
where id is an integer and
116≤d<1 .
For complex valued determinants the real and imaginary parts are scaled separately.

3 Recommendations on Choice and Use of Available Routines

It is extremely wasteful of computer time and storage to use an inappropriate routine, for example to use a routine requiring a complex matrix when A is real. Most programmers will know whether their matrix is real or complex, but may be less certain whether or not a real symmetric matrix A is positive definite, i.e., all eigenvalues of A>0. A real symmetric matrix A not known to be positive definite must be treated as a general real matrix. In all other cases either the band routine or the general routines must be used.
The routines in this chapter are general purpose routines. These give the value of the determinant in its scaled form, d and id, given the triangular decomposition of the matrix from a suitable routine from Chapter F07.

4 Decision Trees

Tree 1

Is A a real matrix? |  |  | Is A a symmetric positive definite matrix? |  |  | Is A a band matrix? |  |  | F07HDF and F03BHF
 |  | yes |  |  | yes |  |  | yes
 | no |  |  | no |  |  | no |
 |  |  |  |  |  | F07FDF and F03BFF
 |  |  | F07ADF and F03BAF
F07ARF and F03BNF

5 Functionality Index

Determinants of factorized matrices,
complex matrix F03BNF
real matrix F03BAF
real symmetric band positive definite matrix F03BHF
real symmetric positive definite matrix F03BFF

6 Auxiliary Routines Associated with Library Routine Arguments

None.

7 Routines Withdrawn or Scheduled for Withdrawal

The following lists all those routines that have been withdrawn since Mark 19 of the Library or are scheduled for withdrawal at one of the next two marks.
Withdrawn Routine | Mark of Withdrawal | Replacement Routine(s)
F03AAF | 25 | F07ADF (DGETRF) and F03BAF
F03ABF | 25 | F07FDF (DPOTRF) and F03BFF
F03ACF | 25 | F07HDF (DPBTRF) and F03BHF
F03ADF | 25 | F07ARF (ZGETRF) and F03BNF
F03AEF | 25 | F07FDF (DPOTRF) and F03BFF
F03AFF | 25 | F07ADF (DGETRF) and F03BAF

8 References

Fox L (1964) An Introduction to Numerical Linear Algebra Oxford University Press
Wilkinson J H and Reinsch C (1971) Handbook for Automatic Computation II, Linear Algebra Springer–Verlag
F03 Chapter Contents
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F04ABF : NAG Library, Mark 26

F04 Chapter Contents
F04 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F04ABF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F04ABF calculates the accurate solution of a set of real symmetric positive definite linear equations with multiple right-hand sides, using a Cholesky factorization and iterative refinement.

2 Specification

SUBROUTINE F04ABF ( A, LDA, B, LDB, N, M, C, LDC, WKSPCE, BB, LDBB, IFAIL)
INTEGER | LDA, LDB, N, M, LDC, LDBB, IFAIL
REAL (KIND=nag_wp) | A(LDA,*), B(LDB,*), C(LDC,M), WKSPCE(N), BB(LDBB,M)

3 Description

Given a set of real linear equations AX=B, where A is symmetric positive definite, F04ABF first computes a Cholesky factorization of A as A=L LT, where L is lower triangular. An approximation to X is found by forward and backward substitution. The residual matrix R=B-AX is then calculated using additional precision, and a correction D to X is found by solving L LT D=R. X is replaced by X+D, and this iterative refinement of the solution is repeated until full machine accuracy has been obtained.

4 References

Wilkinson J H and Reinsch C (1971) Handbook for Automatic Computation II, Linear Algebra Springer–Verlag

5 Arguments

1:   A LDA* – REAL (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array A must be at least max 1,N.
On entry: the upper triangle of the n by n positive definite symmetric matrix A. The elements of the array below the diagonal need not be set.
On exit: the elements of the array below the diagonal are overwritten; the upper triangle of A is unchanged.
2:   LDA – INTEGERInput
On entry: the first dimension of the array A as declared in the (sub)program from which F04ABF is called.
Constraint: LDA≥max 1,N.
3:   B LDB* – REAL (KIND=nag_wp) arrayInput
Note: the second dimension of the array B must be at least max 1,M.
On entry: the n by m right-hand side matrix B.
4:   LDB – INTEGERInput
On entry: the first dimension of the array B as declared in the (sub)program from which F04ABF is called.
Constraint: LDB≥max 1,N.
5:   N – INTEGERInput
On entry: n, the order of the matrix A.
Constraint: N≥0.
6:   M – INTEGERInput
On entry: m, the number of right-hand sides.
Constraint: M≥0.
7:   C LDCM – REAL (KIND=nag_wp) arrayOutput
Note: the second dimension of the array C must be at least max 1,M.
On exit: the n by m solution matrix X.
8:   LDC – INTEGERInput
On entry: the first dimension of the array C as declared in the (sub)program from which F04ABF is called.
Constraint: LDC≥max 1,N.
9:   WKSPCE N – REAL (KIND=nag_wp) arrayWorkspace
10:   BB LDBBM – REAL (KIND=nag_wp) arrayOutput
Note: the second dimension of the array BB must be at least max 1,M.
On exit: the final n by m residual matrix R=B-AX.
11:   LDBB – INTEGERInput
On entry: the first dimension of the array BB as declared in the (sub)program from which F04ABF is called.
Constraint: LDBB≥max 1,N.
12:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
The matrix A is not positive definite, possibly due to rounding errors.
IFAIL=2
Iterative refinement fails to improve the solution, i.e., the matrix A is too ill-conditioned.
IFAIL=3
On entry, | N<0,
or | M<0,
or | LDA<max 1,N,
or | LDB<max 1,N,
or | LDC<max 1,N,
or | LDBB<max 1,N.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

The computed solutions should be correct to full machine accuracy. For a detailed error analysis see page 39 of Wilkinson and Reinsch (1971).

8 Parallelism and Performance

F04ABF is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
F04ABF makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The time taken by F04ABF is approximately proportional to n 3.
If there is only one right-hand side, it is simpler to use F04ASF.

10 Example

This example solves the set of linear equations AX=B where
A= 5 7 6 5 7 10 8 7 6 8 10 9 5 7 9 10   and  B= 23 32 33 31 .

10.1 Program Text

Program Text (f04abfe.f90)

10.2 Program Data

Program Data (f04abfe.d)

10.3 Program Results

Program Results (f04abfe.r)

F04 Chapter Contents
F04 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F04AEF : NAG Library, Mark 26

F04 Chapter Contents
F04 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F04AEF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F04AEF calculates the accurate solution of a set of real linear equations with multiple right-hand sides using an LU factorization with partial pivoting, and iterative refinement.

2 Specification

SUBROUTINE F04AEF ( A, LDA, B, LDB, N, M, C, LDC, WKSPCE, AA, LDAA, BB, LDBB, IFAIL)
INTEGER | LDA, LDB, N, M, LDC, LDAA, LDBB, IFAIL
REAL (KIND=nag_wp) | A(LDA,*), B(LDB,*), C(LDC,*), WKSPCE(max(1,N)), AA(LDAA,*), BB(LDBB,*)

3 Description

Given a set of real linear equations AX=B, the routine first computes an LU factorization of A with partial pivoting, PA=LU, where P is a permutation matrix, L is lower triangular and U is unit upper triangular. An approximation to X is found by forward and backward substitution. The residual matrix R=B-AX is then calculated using additional precision, and a correction D to X is found by solving LUD=PR. X is replaced by X+D and this iterative refinement of the solution is repeated until full machine accuracy has been obtained.

4 References

Wilkinson J H and Reinsch C (1971) Handbook for Automatic Computation II, Linear Algebra Springer–Verlag

5 Arguments

1:   A LDA* – REAL (KIND=nag_wp) arrayInput
Note: the second dimension of the array A must be at least max 1,N.
On entry: the n by n matrix A.
2:   LDA – INTEGERInput
On entry: the first dimension of the array A as declared in the (sub)program from which F04AEF is called.
Constraint: LDA≥max 1,N.
3:   B LDB* – REAL (KIND=nag_wp) arrayInput
Note: the second dimension of the array B must be at least max 1,M.
On entry: the n by m right-hand side matrix B.
4:   LDB – INTEGERInput
On entry: the first dimension of the array B as declared in the (sub)program from which F04AEF is called.
Constraint: LDB≥max 1,N.
5:   N – INTEGERInput
On entry: n, the order of the matrix A.
Constraint: N≥0.
6:   M – INTEGERInput
On entry: m, the number of right-hand sides.
Constraint: M≥0.
7:   C LDC* – REAL (KIND=nag_wp) arrayOutput
Note: the second dimension of the array C must be at least max 1,M.
On exit: the n by m solution matrix X.
8:   LDC – INTEGERInput
On entry: the first dimension of the array C as declared in the (sub)program from which F04AEF is called.
Constraint: LDC≥max 1,N.
9:   WKSPCE max 1,N – REAL (KIND=nag_wp) arrayWorkspace
10:   AA LDAA* – REAL (KIND=nag_wp) arrayOutput
Note: the second dimension of the array AA must be at least max 1,N.
On exit: the triangular factors L and U, except that the unit diagonal elements of U are not stored.
11:   LDAA – INTEGERInput
On entry: the first dimension of the array AA as declared in the (sub)program from which F04AEF is called.
Constraint: LDAA≥max 1,N.
12:   BB LDBB* – REAL (KIND=nag_wp) arrayOutput
Note: the second dimension of the array BB must be at least max 1,M.
On exit: the final n by m residual matrix R=B-AX.
13:   LDBB – INTEGERInput
On entry: the first dimension of the array BB as declared in the (sub)program from which F04AEF is called.
Constraint: LDBB≥max 1,N.
14:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
The matrix A is singular, possibly due to rounding errors.
IFAIL=2
Iterative refinement fails to improve the solution, i.e., the matrix A is too ill-conditioned.
IFAIL=3
On entry, | N<0,
or | M<0,
or | LDA<max 1,N,
or | LDB<max 1,N,
or | LDC<max 1,N,
or | LDAA<max 1,N,
or | LDBB<max 1,N.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

The computed solutions should be correct to full machine accuracy. For a detailed error analysis see page 107 of Wilkinson and Reinsch (1971).

8 Parallelism and Performance

F04AEF is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
F04AEF makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The time taken by F04AEF is approximately proportional to n 3.
If there is only one right-hand side, it is simpler to use F04ATF.

10 Example

This example solves the set of linear equations AX=B where
A= 33 16 72 -24 -10 -57 -8 -4 -17   and  B= -359 281 85 .

10.1 Program Text

Program Text (f04aefe.f90)

10.2 Program Data

Program Data (f04aefe.d)

10.3 Program Results

Program Results (f04aefe.r)

F04 Chapter Contents
F04 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F04AMF : NAG Library, Mark 26

F04 Chapter Contents
F04 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F04AMF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F04AMF calculates the accurate least squares solution of a set of m linear equations in n unknowns, m≥n and rank =n, with multiple right-hand sides, AX=B, using a QR factorization and iterative refinement.

2 Specification

SUBROUTINE F04AMF ( A, LDA, X, LDX, B, LDB, M, N, IR, EPS, QR, LDQR, ALPHA, E, Y, Z, R, IPIV, IFAIL)
INTEGER | LDA, LDX, LDB, M, N, IR, LDQR, IPIV(N), IFAIL
REAL (KIND=nag_wp) | A(LDA,N), X(LDX,IR), B(LDB,IR), EPS, QR(LDQR,N), ALPHA(N), E(N), Y(N), Z(N), R(M)

3 Description

To compute the least squares solution to a set of m linear equations in n unknowns m≥n AX=B, F04AMF first computes a QR factorization of A with column pivoting, AP=QR, where R is upper triangular, Q is an m by m orthogonal matrix, and P is a permutation matrix. QT is applied to the m by r right-hand side matrix B to give C=QT B, and the n by r solution matrix X is calculated, to a first approximation, by back-substitution in RX=C. The residual matrix S=B-AX is calculated using additional precision, and a correction D to X is computed as the least squares solution to AD=S. X is replaced by X+D and this iterative refinement of the solution is repeated until full machine accuracy has been obtained.

4 References

Wilkinson J H and Reinsch C (1971) Handbook for Automatic Computation II, Linear Algebra Springer–Verlag

5 Arguments

1:   A LDAN – REAL (KIND=nag_wp) arrayInput
On entry: the m by n matrix A.
2:   LDA – INTEGERInput
On entry: the first dimension of the array A as declared in the (sub)program from which F04AMF is called.
Constraint: LDA≥M.
3:   X LDXIR – REAL (KIND=nag_wp) arrayOutput
On exit: the n by r solution matrix X.
4:   LDX – INTEGERInput
On entry: the first dimension of the array X as declared in the (sub)program from which F04AMF is called.
Constraint: LDX≥N.
5:   B LDBIR – REAL (KIND=nag_wp) arrayInput
On entry: the m by r right-hand side matrix B.
6:   LDB – INTEGERInput
On entry: the first dimension of the array B as declared in the (sub)program from which F04AMF is called.
Constraint: LDB≥M.
7:   M – INTEGERInput
On entry: m, the number of rows of the matrix A, i.e., the number of equations.
Constraint: M≥1.
8:   N – INTEGERInput
On entry: n, the number of columns of the matrix A, i.e., the number of unknowns.
Constraint: 0≤N≤M.
9:   IR – INTEGERInput
On entry: r, the number of right-hand sides.
10:   EPS – REAL (KIND=nag_wp)Input
On entry: must be set to the value of the machine precision.
11:   QR LDQRN – REAL (KIND=nag_wp) arrayOutput
On exit: details of the QR factorization.
12:   LDQR – INTEGERInput
On entry: the first dimension of the array QR as declared in the (sub)program from which F04AMF is called.
Constraint: LDQR≥M.
13:   ALPHA N – REAL (KIND=nag_wp) arrayOutput
On exit: the diagonal elements of the upper triangular matrix R.
14:   E N – REAL (KIND=nag_wp) arrayWorkspace
15:   Y N – REAL (KIND=nag_wp) arrayWorkspace
16:   Z N – REAL (KIND=nag_wp) arrayWorkspace
17:   R M – REAL (KIND=nag_wp) arrayWorkspace
18:   IPIV N – INTEGER arrayOutput
On exit: details of the column interchanges.
19:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
The rank of A is less than n; the problem does not have a unique solution.
IFAIL=2
The iterative refinement fails to converge, i.e., the matrix A is too ill-conditioned.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

Although the correction process is continued until the solution has converged to full machine accuracy, all the figures in the final solution may not be correct since the correction D to X is itself the solution to a linear least squares problem. For a detailed error analysis see page 116 of Wilkinson and Reinsch (1971).

8 Parallelism and Performance

F04AMF makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The time taken by F04AMF is approximately proportional to n 2 3 m-n, provided r is small compared with n.

10 Example

This example calculates the accurate least squares solution of the equations
1.1 x 1+0.9 x 2=2.2 1.2 x 1+1.0 x 2=2.3 1.0 x 1+1.0 x 2=2.1

10.1 Program Text

Program Text (f04amfe.f90)

10.2 Program Data

Program Data (f04amfe.d)

10.3 Program Results

Program Results (f04amfe.r)

F04 Chapter Contents
F04 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F04ASF : NAG Library, Mark 26

F04 Chapter Contents
F04 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F04ASF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F04ASF calculates the accurate solution of a set of real symmetric positive definite linear equations with a single right-hand side, Ax=b, using a Cholesky factorization and iterative refinement.

2 Specification

SUBROUTINE F04ASF ( A, LDA, B, N, C, WK1, WK2, IFAIL)
INTEGER | LDA, N, IFAIL
REAL (KIND=nag_wp) | A(LDA,*), B(max(1,N)), C(max(1,N)), WK1(max(1,N)), WK2(max(1,N))

3 Description

Given a set of real linear equations Ax=b, where A is a symmetric positive definite matrix, F04ASF first computes a Cholesky factorization of A as A=L LT where L is lower triangular. An approximation to x is found by forward and backward substitution. The residual vector r=b-Ax is then calculated using additional precision and a correction d to x is found by solving L LT d=r. x is then replaced by x+d, and this iterative refinement of the solution is repeated until machine accuracy is obtained.

4 References

Wilkinson J H and Reinsch C (1971) Handbook for Automatic Computation II, Linear Algebra Springer–Verlag

5 Arguments

1:   A LDA* – REAL (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array A must be at least max 1,N.
On entry: the upper triangle of the n by n positive definite symmetric matrix A. The elements of the array below the diagonal need not be set.
On exit: the elements of the array below the diagonal are overwritten; the upper triangle of A is unchanged.
2:   LDA – INTEGERInput
On entry: the first dimension of the array A as declared in the (sub)program from which F04ASF is called.
Constraint: LDA≥max 1,N.
3:   B max 1,N – REAL (KIND=nag_wp) arrayInput
Note: the dimension of the array B must be at least max 1,N.
On entry: the right-hand side vector b.
4:   N – INTEGERInput
On entry: n, the order of the matrix A.
Constraint: N≥0.
5:   C max 1,N – REAL (KIND=nag_wp) arrayOutput
On exit: the solution vector x.
6:   WK1 max 1,N – REAL (KIND=nag_wp) arrayWorkspace
7:   WK2 max 1,N – REAL (KIND=nag_wp) arrayWorkspace
8:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
The matrix A is not positive definite, possibly due to rounding errors.
IFAIL=2
Iterative refinement fails to improve the solution, i.e., the matrix A is too ill-conditioned.
IFAIL=3
On entry, | N<0,
or | LDA<max 1,N.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

The computed solutions should be correct to full machine accuracy. For a detailed error analysis see page 39 of Wilkinson and Reinsch (1971).

8 Parallelism and Performance

F04ASF is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
F04ASF makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The time taken by F04ASF is approximately proportional to n 3.
The routine must not be called with the same name for arguments B and C.

10 Example

This example solves the set of linear equations Ax=b where
A= 5 7 6 5 7 10 8 7 6 8 10 9 5 7 9 10   and  b= 23 32 33 31 .

10.1 Program Text

Program Text (f04asfe.f90)

10.2 Program Data

Program Data (f04asfe.d)

10.3 Program Results

Program Results (f04asfe.r)

F04 Chapter Contents
F04 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F04ATF : NAG Library, Mark 26

F04 Chapter Contents
F04 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F04ATF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F04ATF calculates the accurate solution of a set of real linear equations with a single right-hand side, using an LU factorization with partial pivoting, and iterative refinement.

2 Specification

SUBROUTINE F04ATF ( A, LDA, B, N, C, AA, LDAA, WKS1, WKS2, IFAIL)
INTEGER | LDA, N, LDAA, IFAIL
REAL (KIND=nag_wp) | A(LDA,*), B(*), C(N), AA(LDAA,N), WKS1(N), WKS2(N)

3 Description

Given a set of real linear equations, Ax=b, the routine first computes an LU factorization of A with partial pivoting, PA=LU, where P is a permutation matrix, L is lower triangular and U is unit upper triangular. An approximation to x is found by forward and backward substitution in Ly=Pb and Ux=y. The residual vector r=b-Ax is then calculated using additional precision, and a correction d to x is found by solving LUd=r. x is replaced by x+d, and this iterative refinement of the solution is repeated until full machine accuracy is obtained.

4 References

Wilkinson J H and Reinsch C (1971) Handbook for Automatic Computation II, Linear Algebra Springer–Verlag

5 Arguments

1:   A LDA* – REAL (KIND=nag_wp) arrayInput
Note: the second dimension of the array A must be at least max 1,N.
On entry: the n by n matrix A.
2:   LDA – INTEGERInput
On entry: the first dimension of the array A as declared in the (sub)program from which F04ATF is called.
Constraint: LDA≥max 1,N.
3:   B* – REAL (KIND=nag_wp) arrayInput
Note: the dimension of the array B must be at least max 1,N.
On entry: the right-hand side vector b.
4:   N – INTEGERInput
On entry: n, the order of the matrix A.
Constraint: N≥0.
5:   C N – REAL (KIND=nag_wp) arrayOutput
On exit: the solution vector x.
6:   AA LDAAN – REAL (KIND=nag_wp) arrayOutput
Note: the second dimension of the array AA must be at least max 1,N.
On exit: the triangular factors L and U, except that the unit diagonal elements of U are not stored.
7:   LDAA – INTEGERInput
On entry: the first dimension of the array AA as declared in the (sub)program from which F04ATF is called.
Constraint: LDAA≥max 1,N.
8:   WKS1 N – REAL (KIND=nag_wp) arrayWorkspace
9:   WKS2 N – REAL (KIND=nag_wp) arrayWorkspace
10:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
The matrix A is singular, possibly due to rounding errors.
IFAIL=2
Iterative refinement fails to improve the solution, i.e., the matrix A is too ill-conditioned.
IFAIL=3
On entry, | N<0,
or | LDA<max 1,N,
or | LDAA<max 1,N.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

The computed solutions should be correct to full machine accuracy. For a detailed error analysis see page 107 of Wilkinson and Reinsch (1971).

8 Parallelism and Performance

F04ATF is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
F04ATF makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The time taken by F04ATF is approximately proportional to n 3.
The routine must not be called with the same name for arguments B and C.

10 Example

This example solves the set of linear equations Ax=b where
A= 33 16 72 -24 -10 -57 -8 -4 -17   and  b= -359 281 85 .

10.1 Program Text

Program Text (f04atfe.f90)

10.2 Program Data

Program Data (f04atfe.d)

10.3 Program Results

Program Results (f04atfe.r)

F04 Chapter Contents
F04 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F04AXF : NAG Library, Mark 26

F04 Chapter Contents
F04 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F04AXF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F04AXF calculates the approximate solution of a set of real sparse linear equations with a single right-hand side, Ax=b or AT x=b, where A has been factorized by F01BRF or F01BSF.

2 Specification

SUBROUTINE F04AXF ( N, A, LICN, ICN, IKEEP, RHS, W, MTYPE, IDISP, RESID)
INTEGER | N, LICN, ICN(LICN), IKEEP(5*N), MTYPE, IDISP(2)
REAL (KIND=nag_wp) | A(LICN), RHS(N), W(N), RESID

3 Description

To solve a system of real linear equations Ax=b or AT x=b, where A is a general sparse matrix, A must first be factorized by F01BRF or F01BSF. F04AXF then computes x by block forward or backward substitution using simple forward and backward substitution within each diagonal block.
The method is fully described in Duff (1977).
A more recent method is available through solver routine F11MFF and factorization routine F11MEF.

4 References

Duff I S (1977) MA28 – a set of Fortran subroutines for sparse unsymmetric linear equations AERE Report R8730 HMSO

5 Arguments

1:   N – INTEGERInput
On entry: n, the order of the matrix A.
Constraint: N≥0.
2:   A LICN – REAL (KIND=nag_wp) arrayInput
On entry: the nonzero elements in the factorization of the matrix A, as returned by F01BRF or F01BSF.
3:   LICN – INTEGERInput
On entry: the dimension of the arrays A and ICN as declared in the (sub)program from which F04AXF is called.
4:   ICN LICN – INTEGER arrayCommunication Array
On entry: the column indices of the nonzero elements of the factorization, as returned by F01BRF or F01BSF.
5:   IKEEP 5×N – INTEGER arrayInput
IKEEP provides, on entry, indexing information about the factorization, as returned by F01BRF or F01BSF. Used as internal workspace prior to being restored and hence is unchanged.
6:   RHS N – REAL (KIND=nag_wp) arrayInput/Output
On entry: the right-hand side vector b.
On exit: RHS is overwritten by the solution vector x.
7:   W N – REAL (KIND=nag_wp) arrayWorkspace
8:   MTYPE – INTEGERInput
On entry: MTYPE specifies the task to be performed.
MTYPE=1
Solve Ax=b.
MTYPE≠1
Solve AT x=b.
9:   IDISP 2 – INTEGER arrayCommunication Array
On entry: the values returned in IDISP by F01BRF.
10:   RESID – REAL (KIND=nag_wp)Output
On exit: the value of the maximum residual, max bi-∑j a ijxj, over all the unsatisfied equations, in case F01BRF or F01BSF has been used to factorize a singular or rectangular matrix.

6 Error Indicators and Warnings

If an error is detected in an input argument F04AXF will act as if a soft noisy exit has been requested (see Section 3.4.4 in How to Use the NAG Library and its Documentation).

7 Accuracy

The accuracy of the computed solution depends on the conditioning of the original matrix. Since F04AXF is always used with either F01BRF or F01BSF, you are recommended to set GROW=.TRUE. on entry to these routines and to examine the value of W 1 on exit (see F01BRF and F01BSF). For a detailed error analysis see page 17 of Duff (1977).
If storage for the original matrix is available then the error can be estimated by calculating the residual
r=b-Ax or ​b-AT x
and calling F04AXF again to find a correction δ for x by solving
Aδ=r or ​AT δ=r.

8 Parallelism and Performance

F04AXF is not threaded in any implementation.

9 Further Comments

If the factorized form contains τ nonzeros (IDISP 2=τ) then the time taken is very approximately 2 τ times longer than the inner loop of full matrix code. Some advantage is taken of zeros in the right-hand side when solving AT x=b (MTYPE≠1).

10 Example

This example solves the set of linear equations Ax=b where
A= 5 0 0 0 0 0 0 2 -1 2 0 0 0 0 3 0 0 0 -2 0 0 1 1 0 -1 0 0 -1 2 -3 -1 -1 0 0 0 6   and  b= 15 12 18 3 -6 0 .
The nonzero elements of A and indexing information are read in by the program, as described in the document for F01BRF.

10.1 Program Text

Program Text (f04axfe.f90)

10.2 Program Data

Program Data (f04axfe.d)

10.3 Program Results

Program Results (f04axfe.r)

F04 Chapter Contents
F04 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F04BAF : NAG Library, Mark 26

F04 Chapter Contents
F04 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F04BAF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F04BAF computes the solution to a real system of linear equations AX=B, where A is an n by n matrix and X and B are n by r matrices. An estimate of the condition number of A and an error bound for the computed solution are also returned.

2 Specification

SUBROUTINE F04BAF ( N, NRHS, A, LDA, IPIV, B, LDB, RCOND, ERRBND, IFAIL)
INTEGER | N, NRHS, LDA, IPIV(N), LDB, IFAIL
REAL (KIND=nag_wp) | A(LDA,*), B(LDB,*), RCOND, ERRBND

3 Description

The LU decomposition with partial pivoting and row interchanges is used to factor A as A=PLU, where P is a permutation matrix, L is unit lower triangular, and U is upper triangular. The factored form of A is then used to solve the system of equations AX=B.

4 References

Anderson E, Bai Z, Bischof C, Blackford S, Demmel J, Dongarra J J, Du Croz J J, Greenbaum A, Hammarling S, McKenney A and Sorensen D (1999) LAPACK Users' Guide (3rd Edition) SIAM, Philadelphia http://www.netlib.org/lapack/lug
Higham N J (2002) Accuracy and Stability of Numerical Algorithms (2nd Edition) SIAM, Philadelphia

5 Arguments

1:   N – INTEGERInput
On entry: the number of linear equations n, i.e., the order of the matrix A.
Constraint: N≥0.
2:   NRHS – INTEGERInput
On entry: the number of right-hand sides r, i.e., the number of columns of the matrix B.
Constraint: NRHS≥0.
3:   A LDA* – REAL (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array A must be at least max 1,N.
On entry: the n by n coefficient matrix A.
On exit: if IFAIL≥0, the factors L and U from the factorization A=PLU. The unit diagonal elements of L are not stored.
4:   LDA – INTEGERInput
On entry: the first dimension of the array A as declared in the (sub)program from which F04BAF is called.
Constraint: LDA≥max 1,N.
5:   IPIV N – INTEGER arrayOutput
On exit: if IFAIL≥0, the pivot indices that define the permutation matrix P; at the ith step row i of the matrix was interchanged with row IPIV i. IPIV i=i indicates a row interchange was not required.
6:   B LDB* – REAL (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array B must be at least max 1,NRHS.
On entry: the n by r matrix of right-hand sides B.
On exit: if IFAIL=0 or N+1, the n by r solution matrix X.
7:   LDB – INTEGERInput
On entry: the first dimension of the array B as declared in the (sub)program from which F04BAF is called.
Constraint: LDB≥max 1,N.
8:   RCOND – REAL (KIND=nag_wp)Output
On exit: if no constraints are violated, an estimate of the reciprocal of the condition number of the matrix A, computed as RCOND=1/A 1A-1 1.
9:   ERRBND – REAL (KIND=nag_wp)Output
On exit: if IFAIL=0 or N+1, an estimate of the forward error bound for a computed solution x^, such that x^-x 1/x 1≤ERRBND, where x^ is a column of the computed solution returned in the array B and x is the corresponding column of the exact solution X. If RCOND is less than machine precision, then ERRBND is returned as unity.
10:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL>0 and IFAIL≤N
Diagonal element value of the upper triangular factor is zero. The factorization has been completed, but the solution could not be computed.
IFAIL=N+1
A solution has been computed, but RCOND is less than machine precision so that the matrix A is numerically singular.
IFAIL=-1
On entry, N=value.
Constraint: N≥0.
IFAIL=-2
On entry, NRHS=value.
Constraint: NRHS≥0.
IFAIL=-4
On entry, LDA=value and N=value.
Constraint: LDA≥max 1,N.
IFAIL=-7
On entry, LDB=value and N=value.
Constraint: LDB≥max 1,N.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
The integer allocatable memory required is N, and the real allocatable memory required is 4×N. In this case the factorization and the solution X have been computed, but RCOND and ERRBND have not been computed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

The computed solution for a single right-hand side, x^, satisfies an equation of the form
A+E x^=b,
where
E 1 = O ε A 1
and ε is the machine precision. An approximate error bound for the computed solution is given by
x^-x 1 x 1 ≤ κ A E 1 A 1 ,
where κ A = A-1 1 A 1 , the condition number of A with respect to the solution of the linear equations. F04BAF uses the approximation E 1=ε A 1 to estimate ERRBND. See Section 4.4 of Anderson et al. (1999) for further details.

8 Parallelism and Performance

F04BAF is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
F04BAF makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The total number of floating-point operations required to solve the equations AX=B is proportional to 23 n 3+n 2 r. The condition number estimation typically requires between four and five solves and never more than eleven solves, following the factorization.
In practice the condition number estimator is very reliable, but it can underestimate the true condition number; see Section 15.3 of Higham (2002) for further details.
The complex analogue of F04BAF is F04CAF.

10 Example

This example solves the equations
AX=B,
where
A= 1.80 2.88 2.05 -0.89 5.25 -2.95 -0.95 -3.80 1.58 -2.69 -2.90 -1.04 -1.11 -0.66 -0.59 0.80   and   B= 9.52 18.47 24.35 2.25 0.77 -13.28 -6.22 -6.21 .
An estimate of the condition number of A and an approximate error bound for the computed solutions are also printed.

10.1 Program Text

Program Text (f04bafe.f90)

10.2 Program Data

Program Data (f04bafe.d)

10.3 Program Results

Program Results (f04bafe.r)

F04 Chapter Contents
F04 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F04BBF : NAG Library, Mark 26

F04 Chapter Contents
F04 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F04BBF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F04BBF computes the solution to a real system of linear equations AX=B, where A is an n by n band matrix, with kl subdiagonals and ku superdiagonals, and X and B are n by r matrices. An estimate of the condition number of A and an error bound for the computed solution are also returned.

2 Specification

SUBROUTINE F04BBF ( N, KL, KU, NRHS, AB, LDAB, IPIV, B, LDB, RCOND, ERRBND, IFAIL)
INTEGER | N, KL, KU, NRHS, LDAB, IPIV(N), LDB, IFAIL
REAL (KIND=nag_wp) | AB(LDAB,*), B(LDB,*), RCOND, ERRBND

3 Description

The LU decomposition with partial pivoting and row interchanges is used to factor A as A=PLU, where P is a permutation matrix, L is the product of permutation matrices and unit lower triangular matrices with kl subdiagonals, and U is upper triangular with kl+ku superdiagonals. The factored form of A is then used to solve the system of equations AX=B.

4 References

Anderson E, Bai Z, Bischof C, Blackford S, Demmel J, Dongarra J J, Du Croz J J, Greenbaum A, Hammarling S, McKenney A and Sorensen D (1999) LAPACK Users' Guide (3rd Edition) SIAM, Philadelphia http://www.netlib.org/lapack/lug
Higham N J (2002) Accuracy and Stability of Numerical Algorithms (2nd Edition) SIAM, Philadelphia

5 Arguments

1:   N – INTEGERInput
On entry: the number of linear equations n, i.e., the order of the matrix A.
Constraint: N≥0.
2:   KL – INTEGERInput
On entry: the number of subdiagonals kl, within the band of A.
Constraint: KL≥0.
3:   KU – INTEGERInput
On entry: the number of superdiagonals ku, within the band of A.
Constraint: KU≥0.
4:   NRHS – INTEGERInput
On entry: the number of right-hand sides r, i.e., the number of columns of the matrix B.
Constraint: NRHS≥0.
5:   AB LDAB* – REAL (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array AB must be at least max 1,N.
On entry: the n by n matrix A.
The matrix is stored in rows kl+1 to 2 kl+ku+1; the first kl rows need not be set, more precisely, the element A ij must be stored in
AB kl+ku+1+i-j j=A ij  for ​max 1,j-ku≤i≤min n,j+kl.
See Section 9 for further details.
On exit: if IFAIL≥0, AB is overwritten by details of the factorization.
The upper triangular band matrix U, with kl+ku superdiagonals, is stored in rows 1 to kl+ku+1 of the array, and the multipliers used to form the matrix L are stored in rows kl+ku+2 to 2 kl+ku+1.
6:   LDAB – INTEGERInput
On entry: the first dimension of the array AB as declared in the (sub)program from which F04BBF is called.
Constraint: LDAB≥2×KL+KU+1.
7:   IPIV N – INTEGER arrayOutput
On exit: if IFAIL≥0, the pivot indices that define the permutation matrix P; at the ith step row i of the matrix was interchanged with row IPIV i. IPIV i=i indicates a row interchange was not required.
8:   B LDB* – REAL (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array B must be at least max 1,NRHS.
On entry: the n by r matrix of right-hand sides B.
On exit: if IFAIL=0 or N+1, the n by r solution matrix X.
9:   LDB – INTEGERInput
On entry: the first dimension of the array B as declared in the (sub)program from which F04BBF is called.
Constraint: LDB≥max 1,N.
10:   RCOND – REAL (KIND=nag_wp)Output
On exit: if no constraints are violated, an estimate of the reciprocal of the condition number of the matrix A, computed as RCOND=1/A 1A-1 1.
11:   ERRBND – REAL (KIND=nag_wp)Output
On exit: if IFAIL=0 or N+1, an estimate of the forward error bound for a computed solution x^, such that x^-x 1/x 1≤ERRBND, where x^ is a column of the computed solution returned in the array B and x is the corresponding column of the exact solution X. If RCOND is less than machine precision, then ERRBND is returned as unity.
12:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL>0 and IFAIL≤N
Diagonal element value of the upper triangular factor is zero. The factorization has been completed, but the solution could not be computed.
IFAIL=N+1
A solution has been computed, but RCOND is less than machine precision so that the matrix A is numerically singular.
IFAIL=-1
On entry, N=value.
Constraint: N≥0.
IFAIL=-2
On entry, KL=value.
Constraint: KL≥0.
IFAIL=-3
On entry, KU=value.
Constraint: KU≥0.
IFAIL=-4
On entry, NRHS=value.
Constraint: NRHS≥0.
IFAIL=-6
On entry, LDAB =value, KL =value and KU=value.
Constraint: LDAB≥2×KL+KU+1.
IFAIL=-9
On entry, LDB=value and N=value.
Constraint: LDB≥max 1,N.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
The integer allocatable memory required is N, and the real allocatable memory required is 3×N. In this case the factorization and the solution X have been computed, but RCOND and ERRBND have not been computed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

The computed solution for a single right-hand side, x^, satisfies an equation of the form
A+E x^=b,
where
E 1 = O ε A 1
and ε is the machine precision. An approximate error bound for the computed solution is given by
x^-x 1 x 1 ≤ κ A E 1 A 1 ,
where κ A = A-1 1 A 1 , the condition number of A with respect to the solution of the linear equations. F04BBF uses the approximation E 1=ε A 1 to estimate ERRBND. See Section 4.4 of Anderson et al. (1999) for further details.

8 Parallelism and Performance

F04BBF is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
F04BBF makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The band storage scheme for the array AB is illustrated by the following example, when n=6, kl=1, and ku=2. Storage of the band matrix A in the array AB:
* * * + + + * * a 13 a 24 a 35 a 46 * a 12 a 23 a 34 a 45 a 56 a 11 a 22 a 33 a 44 a 55 a 66 a 21 a 32 a 43 a 54 a 65 *
Array elements marked * need not be set and are not referenced by the routine. Array elements marked + need not be set, but are defined on exit from the routine and contain the elements u 14, u 25 and u 36.
The total number of floating-point operations required to solve the equations AX=B depends upon the pivoting required, but if n≫kl+ku then it is approximately bounded by O n kl kl + ku for the factorization and O n 2 kl + ku r for the solution following the factorization. The condition number estimation typically requires between four and five solves and never more than eleven solves, following the factorization.
In practice the condition number estimator is very reliable, but it can underestimate the true condition number; see Section 15.3 of Higham (2002) for further details.
The complex analogue of F04BBF is F04CBF.

10 Example

This example solves the equations
AX=B,
where A is the band matrix
A= -0.23 2.54 -3.66 0 -6.98 2.46 -2.73 -2.13 0 2.56 2.46 4.07 0 0 -4.78 -3.82   and   B= 4.42 -36.01 27.13 -31.67 -6.14 -1.16 10.50 -25.82 .
An estimate of the condition number of A and an approximate error bound for the computed solutions are also printed.

10.1 Program Text

Program Text (f04bbfe.f90)

10.2 Program Data

Program Data (f04bbfe.d)

10.3 Program Results

Program Results (f04bbfe.r)

F04 Chapter Contents
F04 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F04BCF : NAG Library, Mark 26

F04 Chapter Contents
F04 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F04BCF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F04BCF computes the solution to a real system of linear equations AX=B, where A is an n by n tridiagonal matrix and X and B are n by r matrices. An estimate of the condition number of A and an error bound for the computed solution are also returned.

2 Specification

SUBROUTINE F04BCF ( N, NRHS, DL, D, DU, DU2, IPIV, B, LDB, RCOND, ERRBND, IFAIL)
INTEGER | N, NRHS, IPIV(N), LDB, IFAIL
REAL (KIND=nag_wp) | DL(*), D(*), DU(*), DU2(N-2), B(LDB,*), RCOND, ERRBND

3 Description

The LU decomposition with partial pivoting and row interchanges is used to factor A as A=PLU, where P is a permutation matrix, L is unit lower triangular with at most one nonzero subdiagonal element, and U is an upper triangular band matrix with two superdiagonals. The factored form of A is then used to solve the system of equations AX=B.
Note that the equations AT X=B may be solved by interchanging the order of the arguments DU and DL.

4 References

Anderson E, Bai Z, Bischof C, Blackford S, Demmel J, Dongarra J J, Du Croz J J, Greenbaum A, Hammarling S, McKenney A and Sorensen D (1999) LAPACK Users' Guide (3rd Edition) SIAM, Philadelphia http://www.netlib.org/lapack/lug
Higham N J (2002) Accuracy and Stability of Numerical Algorithms (2nd Edition) SIAM, Philadelphia

5 Arguments

1:   N – INTEGERInput
On entry: the number of linear equations n, i.e., the order of the matrix A.
Constraint: N≥0.
2:   NRHS – INTEGERInput
On entry: the number of right-hand sides r, i.e., the number of columns of the matrix B.
Constraint: NRHS≥0.
3:   DL* – REAL (KIND=nag_wp) arrayInput/Output
Note: the dimension of the array DL must be at least max 1,N-1.
On entry: must contain the n-1 subdiagonal elements of the matrix A.
On exit: if IFAIL≥0, DL is overwritten by the n-1 multipliers that define the matrix L from the LU factorization of A.
4:   D* – REAL (KIND=nag_wp) arrayInput/Output
Note: the dimension of the array D must be at least max 1,N.
On entry: must contain the n diagonal elements of the matrix A.
On exit: if IFAIL≥0, D is overwritten by the n diagonal elements of the upper triangular matrix U from the LU factorization of A.
5:   DU* – REAL (KIND=nag_wp) arrayInput/Output
Note: the dimension of the array DU must be at least max 1,N-1.
On entry: must contain the n-1 superdiagonal elements of the matrix A
On exit: if IFAIL≥0, DU is overwritten by the n-1 elements of the first superdiagonal of U.
6:   DU2 N-2 – REAL (KIND=nag_wp) arrayOutput
On exit: if IFAIL≥0, DU2 returns the n-2 elements of the second superdiagonal of U.
7:   IPIV N – INTEGER arrayOutput
On exit: if IFAIL≥0, the pivot indices that define the permutation matrix P; at the ith step row i of the matrix was interchanged with row IPIV i. IPIV i will always be either i or i+1; IPIV i=i indicates a row interchange was not required.
8:   B LDB* – REAL (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array B must be at least max 1,NRHS.
On entry: the n by r matrix of right-hand sides B.
On exit: if IFAIL=0 or N+1, the n by r solution matrix X.
9:   LDB – INTEGERInput
On entry: the first dimension of the array B as declared in the (sub)program from which F04BCF is called.
Constraint: LDB≥max 1,N.
10:   RCOND – REAL (KIND=nag_wp)Output
On exit: if no constraints are violated, an estimate of the reciprocal of the condition number of the matrix A, computed as RCOND=1/A 1A-1 1.
11:   ERRBND – REAL (KIND=nag_wp)Output
On exit: if IFAIL=0 or N+1, an estimate of the forward error bound for a computed solution x^, such that x^-x 1/x 1≤ERRBND, where x^ is a column of the computed solution returned in the array B and x is the corresponding column of the exact solution X. If RCOND is less than machine precision, then ERRBND is returned as unity.
12:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL>0 and IFAIL=N
Diagonal element value of the upper triangular factor is zero. The factorization has been completed, but the solution could not be computed.
IFAIL=N+1
A solution has been computed, but RCOND is less than machine precision so that the matrix A is numerically singular.
IFAIL=-1
On entry, N=value.
Constraint: N≥0.
IFAIL=-2
On entry, NRHS=value.
Constraint: NRHS≥0.
IFAIL=-9
On entry, LDB=value and N=value.
Constraint: LDB≥max 1,N.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
The integer allocatable memory required is N, and the real allocatable memory required is 2×N. In this case the factorization and the solution X have been computed, but RCOND and ERRBND have not been computed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

The computed solution for a single right-hand side, x^, satisfies an equation of the form
A+E x^=b,
where
E 1 = O ε A 1
and ε is the machine precision. An approximate error bound for the computed solution is given by
x^-x 1 x 1 ≤ κ A E 1 A 1 ,
where κ A = A-1 1 A 1 , the condition number of A with respect to the solution of the linear equations. F04BCF uses the approximation E 1=ε A 1 to estimate ERRBND. See Section 4.4 of Anderson et al. (1999) for further details.

8 Parallelism and Performance

F04BCF makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The total number of floating-point operations required to solve the equations AX=B is proportional to nr. The condition number estimation typically requires between four and five solves and never more than eleven solves, following the factorization.
In practice the condition number estimator is very reliable, but it can underestimate the true condition number; see Section 15.3 of Higham (2002) for further details.
The complex analogue of F04BCF is F04CCF.

10 Example

This example solves the equations
AX=B,
where A is the tridiagonal matrix
A= 3.0 2.1 0 0 0 3.4 2.3 -1.0 0 0 0 3.6 -5.0 1.9 0 0 0 7.0 -0.9 8.0 0 0 0 -6.0 7.1   and   B= 2.7 6.6 -0.5 10.8 2.6 -3.2 0.6 -11.2 2.7 19.1 .
An estimate of the condition number of A and an approximate error bound for the computed solutions are also printed.

10.1 Program Text

Program Text (f04bcfe.f90)

10.2 Program Data

Program Data (f04bcfe.d)

10.3 Program Results

Program Results (f04bcfe.r)

F04 Chapter Contents
F04 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F04BDF : NAG Library, Mark 26

F04 Chapter Contents
F04 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F04BDF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F04BDF computes the solution to a real system of linear equations AX=B, where A is an n by n symmetric positive definite matrix and X and B are n by r matrices. An estimate of the condition number of A and an error bound for the computed solution are also returned.

2 Specification

SUBROUTINE F04BDF ( UPLO, N, NRHS, A, LDA, B, LDB, RCOND, ERRBND, IFAIL)
INTEGER | N, NRHS, LDA, LDB, IFAIL
REAL (KIND=nag_wp) | A(LDA,*), B(LDB,*), RCOND, ERRBND
CHARACTER(1) | UPLO

3 Description

The Cholesky factorization is used to factor A as A=UT U, if UPLO='U', or A=L LT, if UPLO='L', where U is an upper triangular matrix and L is a lower triangular matrix. The factored form of A is then used to solve the system of equations AX=B.

4 References

Anderson E, Bai Z, Bischof C, Blackford S, Demmel J, Dongarra J J, Du Croz J J, Greenbaum A, Hammarling S, McKenney A and Sorensen D (1999) LAPACK Users' Guide (3rd Edition) SIAM, Philadelphia http://www.netlib.org/lapack/lug
Higham N J (2002) Accuracy and Stability of Numerical Algorithms (2nd Edition) SIAM, Philadelphia

5 Arguments

1:   UPLO – CHARACTER(1)Input
On entry: if UPLO='U', the upper triangle of the matrix A is stored.
If UPLO='L', the lower triangle of the matrix A is stored.
Constraint: UPLO='U' or 'L'.
2:   N – INTEGERInput
On entry: the number of linear equations n, i.e., the order of the matrix A.
Constraint: N≥0.
3:   NRHS – INTEGERInput
On entry: the number of right-hand sides r, i.e., the number of columns of the matrix B.
Constraint: NRHS≥0.
4:   A LDA* – REAL (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array A must be at least max 1,N.
On entry: the n by n symmetric matrix A.
If UPLO='U', the leading N by N upper triangular part of A contains the upper triangular part of the matrix A, and the strictly lower triangular part of A is not referenced.
If UPLO='L', the leading N by N lower triangular part of A contains the lower triangular part of the matrix A, and the strictly upper triangular part of A is not referenced.
On exit: if IFAIL=0 or N+1, the factor U or L from the Cholesky factorization A=UT U or A=L LT.
5:   LDA – INTEGERInput
On entry: the first dimension of the array A as declared in the (sub)program from which F04BDF is called.
Constraint: LDA≥max 1,N.
6:   B LDB* – REAL (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array B must be at least max 1,NRHS.
On entry: the n by r matrix of right-hand sides B.
On exit: if IFAIL=0 or N+1, the n by r solution matrix X.
7:   LDB – INTEGERInput
On entry: the first dimension of the array B as declared in the (sub)program from which F04BDF is called.
Constraint: LDB≥max 1,N.
8:   RCOND – REAL (KIND=nag_wp)Output
On exit: if IFAIL=0 or N+1, an estimate of the reciprocal of the condition number of the matrix A, computed as RCOND=1/A 1A-1 1.
9:   ERRBND – REAL (KIND=nag_wp)Output
On exit: if IFAIL=0 or N+1, an estimate of the forward error bound for a computed solution x^, such that x^-x 1/x 1≤ERRBND, where x^ is a column of the computed solution returned in the array B and x is the corresponding column of the exact solution X. If RCOND is less than machine precision, then ERRBND is returned as unity.
10:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL>0 and IFAIL≤N
The principal minor of order value of the matrix A is not positive definite. The factorization has not been completed and the solution could not be computed.
IFAIL=N+1
A solution has been computed, but RCOND is less than machine precision so that the matrix A is numerically singular.
IFAIL=-1
On entry, UPLO≠'U' or 'L': UPLO=value.
IFAIL=-2
On entry, N=value.
Constraint: N≥0.
IFAIL=-3
On entry, NRHS=value.
Constraint: NRHS≥0.
IFAIL=-5
On entry, LDA=value and N=value.
Constraint: LDA≥max 1,N.
IFAIL=-7
On entry, LDB=value and N=value.
Constraint: LDB≥max 1,N.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
The integer allocatable memory required is N, and the real allocatable memory required is 3×N. Allocation failed before the solution could be computed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

The computed solution for a single right-hand side, x^, satisfies an equation of the form
A+E x^=b,
where
E 1 = O ε A 1
and ε is the machine precision. An approximate error bound for the computed solution is given by
x^-x 1 x 1 ≤ κ A E 1 A 1 ,
where κ A = A-1 1 A 1 , the condition number of A with respect to the solution of the linear equations. F04BDF uses the approximation E 1=ε A 1 to estimate ERRBND. See Section 4.4 of Anderson et al. (1999) for further details.

8 Parallelism and Performance

F04BDF is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
F04BDF makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The total number of floating-point operations required to solve the equations AX=B is proportional to 13 n 3+n 2 r. The condition number estimation typically requires between four and five solves and never more than eleven solves, following the factorization.
In practice the condition number estimator is very reliable, but it can underestimate the true condition number; see Section 15.3 of Higham (2002) for further details.
The complex analogue of F04BDF is F04CDF.

10 Example

This example solves the equations
AX=B,
where A is the symmetric positive definite matrix
A= 4.16 -3.12 0.56 -0.10 -3.12 5.03 -0.83 1.18 0.56 -0.83 0.76 0.34 -0.10 1.18 0.34 1.18   and   B= 8.70 8.30 -13.35 2.13 1.89 1.61 -4.14 5.00 .
An estimate of the condition number of A and an approximate error bound for the computed solutions are also printed.

10.1 Program Text

Program Text (f04bdfe.f90)

10.2 Program Data

Program Data (f04bdfe.d)

10.3 Program Results

Program Results (f04bdfe.r)

F04 Chapter Contents
F04 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F04BEF : NAG Library, Mark 26

F04 Chapter Contents
F04 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F04BEF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F04BEF computes the solution to a real system of linear equations AX=B, where A is an n by n symmetric positive definite matrix, stored in packed format, and X and B are n by r matrices. An estimate of the condition number of A and an error bound for the computed solution are also returned.

2 Specification

SUBROUTINE F04BEF ( UPLO, N, NRHS, AP, B, LDB, RCOND, ERRBND, IFAIL)
INTEGER | N, NRHS, LDB, IFAIL
REAL (KIND=nag_wp) | AP(*), B(LDB,*), RCOND, ERRBND
CHARACTER(1) | UPLO

3 Description

The Cholesky factorization is used to factor A as A=UT U, if UPLO='U', or A=L LT, if UPLO='L', where U is an upper triangular matrix and L is a lower triangular matrix. The factored form of A is then used to solve the system of equations AX=B.

4 References

Anderson E, Bai Z, Bischof C, Blackford S, Demmel J, Dongarra J J, Du Croz J J, Greenbaum A, Hammarling S, McKenney A and Sorensen D (1999) LAPACK Users' Guide (3rd Edition) SIAM, Philadelphia http://www.netlib.org/lapack/lug
Higham N J (2002) Accuracy and Stability of Numerical Algorithms (2nd Edition) SIAM, Philadelphia

5 Arguments

1:   UPLO – CHARACTER(1)Input
On entry: if UPLO='U', the upper triangle of the matrix A is stored.
If UPLO='L', the lower triangle of the matrix A is stored.
Constraint: UPLO='U' or 'L'.
2:   N – INTEGERInput
On entry: the number of linear equations n, i.e., the order of the matrix A.
Constraint: N≥0.
3:   NRHS – INTEGERInput
On entry: the number of right-hand sides r, i.e., the number of columns of the matrix B.
Constraint: NRHS≥0.
4:   AP* – REAL (KIND=nag_wp) arrayInput/Output
Note: the dimension of the array AP must be at least max 1,N×N+1/2.
On entry: the n by n symmetric matrix A. The upper or lower triangular part of the symmetric matrix is packed column-wise in a linear array. The jth column of A is stored in the array AP as follows:
More precisely,
  • if UPLO='U', the upper triangle of A must be stored with element A ij in AP i+j j-1/2 for i≤j;
  • if UPLO='L', the lower triangle of A must be stored with element A ij in AP i+2 n-jj-1/2 for i≥j.
On exit: if IFAIL=0 or N+1, the factor U or L from the Cholesky factorization A=UT U or A=L LT, in the same storage format as A.
5:   B LDB* – REAL (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array B must be at least max 1,NRHS.
On entry: the n by r matrix of right-hand sides B.
On exit: if IFAIL=0 or N+1, the n by r solution matrix X.
6:   LDB – INTEGERInput
On entry: the first dimension of the array B as declared in the (sub)program from which F04BEF is called.
Constraint: LDB≥max 1,N.
7:   RCOND – REAL (KIND=nag_wp)Output
On exit: if IFAIL=0 or N+1, an estimate of the reciprocal of the condition number of the matrix A, computed as RCOND=1/A 1A-1 1.
8:   ERRBND – REAL (KIND=nag_wp)Output
On exit: if IFAIL=0 or N+1, an estimate of the forward error bound for a computed solution x^, such that x^-x 1/x 1≤ERRBND, where x^ is a column of the computed solution returned in the array B and x is the corresponding column of the exact solution X. If RCOND is less than machine precision, then ERRBND is returned as unity.
9:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL>0 and IFAIL≤N
The principal minor of order value of the matrix A is not positive definite. The factorization has not been completed and the solution could not be computed.
IFAIL=N+1
A solution has been computed, but RCOND is less than machine precision so that the matrix A is numerically singular.
IFAIL=-1
On entry, UPLO not one of 'U' or 'u' or 'L' or 'l': UPLO=value.
IFAIL=-2
On entry, N=value.
Constraint: N≥0.
IFAIL=-3
On entry, NRHS=value.
Constraint: NRHS≥0.
IFAIL=-6
On entry, LDB=value and N=value.
Constraint: LDB≥max 1,N.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
The integer allocatable memory required is N, and the real allocatable memory required is 3×N. Allocation failed before the solution could be computed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

The computed solution for a single right-hand side, x^, satisfies an equation of the form
A+E x^=b,
where
E 1=O ε A 1
and ε is the machine precision. An approximate error bound for the computed solution is given by
x^-x 1 x 1 ≤ κ A E 1 A 1 ,
where κ A=A-1 1A 1, the condition number of A with respect to the solution of the linear equations. F04BEF uses the approximation E 1=ε A 1 to estimate ERRBND. See Section 4.4 of Anderson et al. (1999) for further details.

8 Parallelism and Performance

F04BEF is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
F04BEF makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The packed storage scheme is illustrated by the following example when n=4 and UPLO='U'. Two-dimensional storage of the symmetric matrix A:
a 11 a 12 a 13 a 14 a 22 a 23 a 24 a 33 a 34 a 44   a ij = a ji
Packed storage of the upper triangle of A:
AP= a 11, a 12, a 22, a 13, a 23, a 33, a 14, a 24, a 34, a 44
The total number of floating-point operations required to solve the equations AX=B is proportional to 13 n 3+n 2 r. The condition number estimation typically requires between four and five solves and never more than eleven solves, following the factorization.
In practice the condition number estimator is very reliable, but it can underestimate the true condition number; see Section 15.3 of Higham (2002) for further details.
The complex analogue of F04BEF is F04CEF.

10 Example

This example solves the equations
AX=B,
where A is the symmetric positive definite matrix
A= 4.16 -3.12 0.56 -0.10 -3.12 5.03 -0.83 1.18 0.56 -0.83 0.76 0.34 -0.10 1.18 0.34 1.18   and   B= 8.70 8.30 -13.35 2.13 1.89 1.61 -4.14 5.00 .
An estimate of the condition number of A and an approximate error bound for the computed solutions are also printed.

10.1 Program Text

Program Text (f04befe.f90)

10.2 Program Data

Program Data (f04befe.d)

10.3 Program Results

Program Results (f04befe.r)

F04 Chapter Contents
F04 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F04BFF : NAG Library, Mark 26

F04 Chapter Contents
F04 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F04BFF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F04BFF computes the solution to a real system of linear equations AX=B, where A is an n by n symmetric positive definite band matrix of band width 2 k+1, and X and B are n by r matrices. An estimate of the condition number of A and an error bound for the computed solution are also returned.

2 Specification

SUBROUTINE F04BFF ( UPLO, N, KD, NRHS, AB, LDAB, B, LDB, RCOND, ERRBND, IFAIL)
INTEGER | N, KD, NRHS, LDAB, LDB, IFAIL
REAL (KIND=nag_wp) | AB(LDAB,*), B(LDB,*), RCOND, ERRBND
CHARACTER(1) | UPLO

3 Description

The Cholesky factorization is used to factor A as A=UT U, if UPLO='U', or A=L LT, if UPLO='L', where U is an upper triangular band matrix with k superdiagonals, and L is a lower triangular band matrix with k subdiagonals. The factored form of A is then used to solve the system of equations AX=B.

4 References

Anderson E, Bai Z, Bischof C, Blackford S, Demmel J, Dongarra J J, Du Croz J J, Greenbaum A, Hammarling S, McKenney A and Sorensen D (1999) LAPACK Users' Guide (3rd Edition) SIAM, Philadelphia http://www.netlib.org/lapack/lug
Higham N J (2002) Accuracy and Stability of Numerical Algorithms (2nd Edition) SIAM, Philadelphia

5 Arguments

1:   UPLO – CHARACTER(1)Input
On entry: if UPLO='U', the upper triangle of the matrix A is stored.
If UPLO='L', the lower triangle of the matrix A is stored.
Constraint: UPLO='U' or 'L'.
2:   N – INTEGERInput
On entry: the number of linear equations n, i.e., the order of the matrix A.
Constraint: N≥0.
3:   KD – INTEGERInput
On entry: the number of superdiagonals k (and the number of subdiagonals) of the band matrix A.
Constraint: KD≥0.
4:   NRHS – INTEGERInput
On entry: the number of right-hand sides r, i.e., the number of columns of the matrix B.
Constraint: NRHS≥0.
5:   AB LDAB* – REAL (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array AB must be at least max 1,N.
On entry: the n by n symmetric band matrix A. The upper or lower triangular part of the symmetric matrix is stored in the first KD+1 rows of the array. The jth column of A is stored in the jth column of the array AB as follows:
The matrix is stored in rows 1 to k+1, more precisely,
  • if UPLO='U', the elements of the upper triangle of A within the band must be stored with element A ij in AB k+1+i-j j​ for ​max 1,j-k≤i≤j;
  • if UPLO='L', the elements of the lower triangle of A within the band must be stored with element A ij in AB 1+i-j j​ for ​j≤i≤min n,j+k.
See Section 9 below for further details.
On exit: if IFAIL=0 or N+1, the factor U or L from the Cholesky factorization A=UT U or A=L LT, in the same storage format as A.
6:   LDAB – INTEGERInput
On entry: the first dimension of the array AB as declared in the (sub)program from which F04BFF is called.
Constraint: LDAB≥KD+1.
7:   B LDB* – REAL (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array B must be at least max 1,NRHS.
On entry: the n by r matrix of right-hand sides B.
On exit: if IFAIL=0 or N+1, the n by r solution matrix X.
8:   LDB – INTEGERInput
On entry: the first dimension of the array B as declared in the (sub)program from which F04BFF is called.
Constraint: LDB≥max 1,N.
9:   RCOND – REAL (KIND=nag_wp)Output
On exit: if IFAIL=0 or N+1, an estimate of the reciprocal of the condition number of the matrix A, computed as RCOND=1/A 1A-1 1.
10:   ERRBND – REAL (KIND=nag_wp)Output
On exit: if IFAIL=0 or N+1, an estimate of the forward error bound for a computed solution x^, such that x^-x 1/x 1≤ERRBND, where x^ is a column of the computed solution returned in the array B and x is the corresponding column of the exact solution X. If RCOND is less than machine precision, then ERRBND is returned as unity.
11:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL>0 and IFAIL≤N
The principal minor of order value of the matrix A is not positive definite. The factorization has not been completed and the solution could not be computed.
IFAIL=N+1
A solution has been computed, but RCOND is less than machine precision so that the matrix A is numerically singular.
IFAIL=-1
On entry, UPLO not one of 'U' or 'u' or 'L' or 'l': UPLO=value.
IFAIL=-2
On entry, N=value.
Constraint: N≥0.
IFAIL=-3
On entry, KD=value.
Constraint: KD≥0.
IFAIL=-4
On entry, NRHS=value.
Constraint: NRHS≥0.
IFAIL=-6
On entry, LDAB =value and KD =value.
Constraint: LDAB≥KD+1.
IFAIL=-8
On entry, LDB=value and N=value.
Constraint: LDB≥max 1,N.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
The integer allocatable memory required is N, and the real allocatable memory required is 3×N. Allocation failed before the solution could be computed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

The computed solution for a single right-hand side, x^, satisfies an equation of the form
A+E x^=b,
where
E 1=O ε A 1
and ε is the machine precision. An approximate error bound for the computed solution is given by
x^-x 1 x 1 ≤ κ A E 1 A 1 ,
where κ A=A-1 1A 1, the condition number of A with respect to the solution of the linear equations. F04BFF uses the approximation E 1=ε A 1 to estimate ERRBND. See Section 4.4 of Anderson et al. (1999) for further details.

8 Parallelism and Performance

F04BFF is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
F04BFF makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The band storage scheme for the array AB is illustrated by the following example, when n=6, k=2, and UPLO='U':
On entry:
* * a 13 a 24 a 35 a 46 * a 12 a 23 a 34 a 45 a 56 a 11 a 22 a 33 a 44 a 55 a 66
On exit:
* * u 13 u 24 u 35 u 46 * u 12 u 23 u 34 u 45 u 56 u 11 u 22 u 33 u 44 u 55 u 66
Similarly, if UPLO='L' the format of AB is as follows:
On entry:
a 11 a 22 a 33 a 44 a 55 a 66 a 21 a 32 a 43 a 54 a 65 * a 31 a 42 a 53 a 64 * *
On exit:
l 11 l 22 l 33 l 44 l 55 l 66 l 21 l 32 l 43 l 54 l 65 * l 31 l 42 l 53 l 64 * *
Array elements marked * need not be set and are not referenced by the routine.
Assuming that n≫k, the total number of floating-point operations required to solve the equations AX=B is approximately n k+1 2 for the factorization and 4 nkr for the solution following the factorization. The condition number estimation typically requires between four and five solves and never more than eleven solves, following the factorization.
In practice the condition number estimator is very reliable, but it can underestimate the true condition number; see Section 15.3 of Higham (2002) for further details.
The complex analogue of F04BFF is F04CFF.

10 Example

This example solves the equations
AX=B,
where A is the symmetric positive definite band matrix
A= 5.49 2.68 0 0 2.68 5.63 -2.39 0 0 -2.39 2.60 -2.22 0 0 -2.22 5.17   and   B= 22.09 5.10 9.31 30.81 -5.24 -25.82 11.83 22.90 .
An estimate of the condition number of A and an approximate error bound for the computed solutions are also printed.

10.1 Program Text

Program Text (f04bffe.f90)

10.2 Program Data

Program Data (f04bffe.d)

10.3 Program Results

Program Results (f04bffe.r)

F04 Chapter Contents
F04 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F04BGF : NAG Library, Mark 26

F04 Chapter Contents
F04 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F04BGF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F04BGF computes the solution to a real system of linear equations AX=B, where A is an n by n symmetric positive definite tridiagonal matrix and X and B are n by r matrices. An estimate of the condition number of A and an error bound for the computed solution are also returned.

2 Specification

SUBROUTINE F04BGF ( N, NRHS, D, E, B, LDB, RCOND, ERRBND, IFAIL)
INTEGER | N, NRHS, LDB, IFAIL
REAL (KIND=nag_wp) | D(*), E(*), B(LDB,*), RCOND, ERRBND

3 Description

A is factorized as A=LD LT, where L is a unit lower bidiagonal matrix and D is diagonal, and the factored form of A is then used to solve the system of equations.

4 References

Anderson E, Bai Z, Bischof C, Blackford S, Demmel J, Dongarra J J, Du Croz J J, Greenbaum A, Hammarling S, McKenney A and Sorensen D (1999) LAPACK Users' Guide (3rd Edition) SIAM, Philadelphia http://www.netlib.org/lapack/lug
Higham N J (2002) Accuracy and Stability of Numerical Algorithms (2nd Edition) SIAM, Philadelphia

5 Arguments

1:   N – INTEGERInput
On entry: the number of linear equations n, i.e., the order of the matrix A.
Constraint: N≥0.
2:   NRHS – INTEGERInput
On entry: the number of right-hand sides r, i.e., the number of columns of the matrix B.
Constraint: NRHS≥0.
3:   D* – REAL (KIND=nag_wp) arrayInput/Output
Note: the dimension of the array D must be at least max 1,N.
On entry: must contain the n diagonal elements of the tridiagonal matrix A.
On exit: if IFAIL=0 or N+1, D is overwritten by the n diagonal elements of the diagonal matrix D from the LD LT factorization of A.
4:   E* – REAL (KIND=nag_wp) arrayInput/Output
Note: the dimension of the array E must be at least max 1,N-1.
On entry: must contain the n-1 subdiagonal elements of the tridiagonal matrix A.
On exit: if IFAIL=0 or N+1, E is overwritten by the n-1 subdiagonal elements of the unit lower bidiagonal matrix L from the LD LT factorization of A. (E can also be regarded as the superdiagonal of the unit upper bidiagonal factor U from the UT DU factorization of A.)
5:   B LDB* – REAL (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array B must be at least max 1,NRHS.
On entry: the n by r matrix of right-hand sides B.
On exit: if IFAIL=0 or N+1, the n by r solution matrix X.
6:   LDB – INTEGERInput
On entry: the first dimension of the array B as declared in the (sub)program from which F04BGF is called.
Constraint: LDB≥max 1,N.
7:   RCOND – REAL (KIND=nag_wp)Output
On exit: if IFAIL=0 or N+1, an estimate of the reciprocal of the condition number of the matrix A, computed as RCOND=1/A 1A-1 1.
8:   ERRBND – REAL (KIND=nag_wp)Output
On exit: if IFAIL=0 or N+1, an estimate of the forward error bound for a computed solution x^, such that x^-x 1/x 1≤ERRBND, where x^ is a column of the computed solution returned in the array B and x is the corresponding column of the exact solution X. If RCOND is less than machine precision, then ERRBND is returned as unity.
9:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL>0 and IFAIL≤N
The principal minor of order value of the matrix A is not positive definite. The factorization has not been completed and the solution could not be computed.
IFAIL=N+1
A solution has been computed, but RCOND is less than machine precision so that the matrix A is numerically singular.
IFAIL=-1
On entry, N=value.
Constraint: N≥0.
IFAIL=-2
On entry, NRHS=value.
Constraint: NRHS≥0.
IFAIL=-6
On entry, LDB=value and N=value.
Constraint: LDB≥max 1,N.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
The real allocatable memory required is N. In this case the factorization and the solution X have been computed, but RCOND and ERRBND have not been computed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

The computed solution for a single right-hand side, x^, satisfies an equation of the form
A+E x^=b,
where
E 1=O ε A 1
and ε is the machine precision. An approximate error bound for the computed solution is given by
x^-x 1 x 1 ≤ κ A E 1 A 1 ,
where κ A=A-1 1A 1, the condition number of A with respect to the solution of the linear equations. F04BGF uses the approximation E 1=ε A 1 to estimate ERRBND. See Section 4.4 of Anderson et al. (1999) for further details.

8 Parallelism and Performance

F04BGF makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The total number of floating-point operations required to solve the equations AX=B is proportional to nr. The condition number estimation requires O n floating-point operations.
See Section 15.3 of Higham (2002) for further details on computing the condition number of tridiagonal matrices.
The complex analogue of F04BGF is F04CGF.

10 Example

This example solves the equations
AX=B,
where A is the symmetric positive definite tridiagonal matrix
A= 4.0 -2.0 0 0 0 -2.0 10.0 -6.0 0 0 0 -6.0 29.0 15.0 0 0 0 15.0 25.0 8.0 0 0 0 8.0 5.0   and   B= 6.0 10.0 9.0 4.0 2.0 9.0 14.0 65.0 7.0 23.0 .
An estimate of the condition number of A and an approximate error bound for the computed solutions are also printed.

10.1 Program Text

Program Text (f04bgfe.f90)

10.2 Program Data

Program Data (f04bgfe.d)

10.3 Program Results

Program Results (f04bgfe.r)

F04 Chapter Contents
F04 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F04BHF : NAG Library, Mark 26

F04 Chapter Contents
F04 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F04BHF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F04BHF computes the solution to a real system of linear equations AX=B, where A is an n by n symmetric matrix and X and B are n by r matrices. An estimate of the condition number of A and an error bound for the computed solution are also returned.

2 Specification

SUBROUTINE F04BHF ( UPLO, N, NRHS, A, LDA, IPIV, B, LDB, RCOND, ERRBND, IFAIL)
INTEGER | N, NRHS, LDA, IPIV(N), LDB, IFAIL
REAL (KIND=nag_wp) | A(LDA,*), B(LDB,*), RCOND, ERRBND
CHARACTER(1) | UPLO

3 Description

The diagonal pivoting method is used to factor A as A=UD UT, if UPLO='U', or A=LD LT, if UPLO='L', where U (or L) is a product of permutation and unit upper (lower) triangular matrices, and D is symmetric and block diagonal with 1 by 1 and 2 by 2 diagonal blocks. The factored form of A is then used to solve the system of equations AX=B.

4 References

Anderson E, Bai Z, Bischof C, Blackford S, Demmel J, Dongarra J J, Du Croz J J, Greenbaum A, Hammarling S, McKenney A and Sorensen D (1999) LAPACK Users' Guide (3rd Edition) SIAM, Philadelphia http://www.netlib.org/lapack/lug
Higham N J (2002) Accuracy and Stability of Numerical Algorithms (2nd Edition) SIAM, Philadelphia

5 Arguments

1:   UPLO – CHARACTER(1)Input
On entry: if UPLO='U', the upper triangle of the matrix A is stored.
If UPLO='L', the lower triangle of the matrix A is stored.
Constraint: UPLO='U' or 'L'.
2:   N – INTEGERInput
On entry: the number of linear equations n, i.e., the order of the matrix A.
Constraint: N≥0.
3:   NRHS – INTEGERInput
On entry: the number of right-hand sides r, i.e., the number of columns of the matrix B.
Constraint: NRHS≥0.
4:   A LDA* – REAL (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array A must be at least max 1,N.
On entry: the n by n symmetric matrix A.
If UPLO='U', the leading N by N upper triangular part of the array A contains the upper triangular part of the matrix A, and the strictly lower triangular part of A is not referenced.
If UPLO='L', the leading N by N lower triangular part of the array A contains the lower triangular part of the matrix A, and the strictly upper triangular part of A is not referenced.
On exit: if IFAIL≥0, the block diagonal matrix D and the multipliers used to obtain the factor U or L from the factorization A=UD UT or A=LD LT as computed by F07MDF (DSYTRF).
5:   LDA – INTEGERInput
On entry: the first dimension of the array A as declared in the (sub)program from which F04BHF is called.
Constraint: LDA≥max 1,N.
6:   IPIV N – INTEGER arrayOutput
On exit: if IFAIL≥0, details of the interchanges and the block structure of D, as determined by F07MDF (DSYTRF).
IPIV k>0
Rows and columns k and IPIV k were interchanged, and d kk is a 1 by 1 diagonal block.
UPLO='U' and IPIV k=IPIV k-1<0
Rows and columns k-1 and -IPIV k were interchanged and d k-1:k,k-1:k is a 2 by 2 diagonal block.
UPLO='L' and IPIV k=IPIV k+1<0
Rows and columns k+1 and -IPIV k were interchanged and d k:k+1,k:k+1 is a 2 by 2 diagonal block.
7:   B LDB* – REAL (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array B must be at least max 1,NRHS.
On entry: the n by r matrix of right-hand sides B.
On exit: if IFAIL=0 or N+1, the n by r solution matrix X.
8:   LDB – INTEGERInput
On entry: the first dimension of the array B as declared in the (sub)program from which F04BHF is called.
Constraint: LDB≥max 1,N.
9:   RCOND – REAL (KIND=nag_wp)Output
On exit: if no constraints are violated, an estimate of the reciprocal of the condition number of the matrix A, computed as RCOND=1/A 1A-1 1.
10:   ERRBND – REAL (KIND=nag_wp)Output
On exit: if IFAIL=0 or N+1, an estimate of the forward error bound for a computed solution x^, such that x^-x 1/x 1≤ERRBND, where x^ is a column of the computed solution returned in the array B and x is the corresponding column of the exact solution X. If RCOND is less than machine precision, then ERRBND is returned as unity.
11:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL>0 and IFAIL≤N
Diagonal block value of the block diagonal matrix is zero. The factorization has been completed, but the solution could not be computed.
IFAIL=N+1
A solution has been computed, but RCOND is less than machine precision so that the matrix A is numerically singular.
IFAIL=-1
On entry, UPLO not one of 'U' or 'u' or 'L' or 'l': UPLO=value.
IFAIL=-2
On entry, N=value.
Constraint: N≥0.
IFAIL=-3
On entry, NRHS=value.
Constraint: NRHS≥0.
IFAIL=-5
On entry, LDA=value and N=value.
Constraint: LDA≥max 1,N.
IFAIL=-8
On entry, LDB=value and N=value.
Constraint: LDB≥max 1,N.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
The integer allocatable memory required is N, and the real allocatable memory required is max 2×N,LWORK, where LWORK is the optimum workspace required by F07MAF (DSYSV). If this failure occurs it may be possible to solve the equations by calling the packed storage version of F04BHF, F04BJF, or by calling F07MAF (DSYSV) directly with less than the optimum workspace (see Chapter F07).
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

The computed solution for a single right-hand side, x^, satisfies an equation of the form
A+E x^ = b ,
where
E 1 = O ε A 1
and ε is the machine precision. An approximate error bound for the computed solution is given by
x^-x 1 x 1 ≤ κ A E 1 A 1 ,
where κ A = A-1 1 A 1 , the condition number of A with respect to the solution of the linear equations. F04BHF uses the approximation E 1=ε A 1 to estimate ERRBND. See Section 4.4 of Anderson et al. (1999) for further details.

8 Parallelism and Performance

F04BHF makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The total number of floating-point operations required to solve the equations AX=B is proportional to 13 n 3+2⁢n 2 r. The condition number estimation typically requires between four and five solves and never more than eleven solves, following the factorization.
In practice the condition number estimator is very reliable, but it can underestimate the true condition number; see Section 15.3 of Higham (2002) for further details.
The complex analogues of F04BHF are F04CHF for complex Hermitian matrices, and F04DHF for complex symmetric matrices.

10 Example

This example solves the equations
AX=B,
where A is the symmetric indefinite matrix
A= -1.81 2.06 0.63 -1.15 2.06 1.15 1.87 4.20 0.63 1.87 -0.21 3.87 -1.15 4.20 3.87 2.07   and   B= 0.96 3.93 6.07 19.25 8.38 9.90 9.50 27.85 .
An estimate of the condition number of A and an approximate error bound for the computed solutions are also printed.

10.1 Program Text

Program Text (f04bhfe.f90)

10.2 Program Data

Program Data (f04bhfe.d)

10.3 Program Results

Program Results (f04bhfe.r)

F04 Chapter Contents
F04 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F04BJF : NAG Library, Mark 26

F04 Chapter Contents
F04 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F04BJF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F04BJF computes the solution to a real system of linear equations AX=B, where A is an n by n symmetric matrix, stored in packed format and X and B are n by r matrices. An estimate of the condition number of A and an error bound for the computed solution are also returned.

2 Specification

SUBROUTINE F04BJF ( UPLO, N, NRHS, AP, IPIV, B, LDB, RCOND, ERRBND, IFAIL)
INTEGER | N, NRHS, IPIV(N), LDB, IFAIL
REAL (KIND=nag_wp) | AP(*), B(LDB,*), RCOND, ERRBND
CHARACTER(1) | UPLO

3 Description

The diagonal pivoting method is used to factor A as A=UD UT, if UPLO='U', or A=LD LT, if UPLO='L', where U (or L) is a product of permutation and unit upper (lower) triangular matrices, and D is symmetric and block diagonal with 1 by 1 and 2 by 2 diagonal blocks. The factored form of A is then used to solve the system of equations AX=B.

4 References

Anderson E, Bai Z, Bischof C, Blackford S, Demmel J, Dongarra J J, Du Croz J J, Greenbaum A, Hammarling S, McKenney A and Sorensen D (1999) LAPACK Users' Guide (3rd Edition) SIAM, Philadelphia http://www.netlib.org/lapack/lug
Higham N J (2002) Accuracy and Stability of Numerical Algorithms (2nd Edition) SIAM, Philadelphia

5 Arguments

1:   UPLO – CHARACTER(1)Input
On entry: if UPLO='U', the upper triangle of the matrix A is stored.
If UPLO='L', the lower triangle of the matrix A is stored.
Constraint: UPLO='U' or 'L'.
2:   N – INTEGERInput
On entry: the number of linear equations n, i.e., the order of the matrix A.
Constraint: N≥0.
3:   NRHS – INTEGERInput
On entry: the number of right-hand sides r, i.e., the number of columns of the matrix B.
Constraint: NRHS≥0.
4:   AP* – REAL (KIND=nag_wp) arrayInput/Output
Note: the dimension of the array AP must be at least max 1,N×N+1/2.
On entry: the n by n symmetric matrix A, packed column-wise in a linear array. The jth column of the matrix A is stored in the array AP as follows:
More precisely,
  • if UPLO='U', the upper triangle of A must be stored with element A ij in AP i+j j-1/2 for i≤j;
  • if UPLO='L', the lower triangle of A must be stored with element A ij in AP i+2 n-jj-1/2 for i≥j.
On exit: if IFAIL≥0, the block diagonal matrix D and the multipliers used to obtain the factor U or L from the factorization A=UD UT or A=LD LT as computed by F07PDF (DSPTRF), stored as a packed triangular matrix in the same storage format as A.
5:   IPIV N – INTEGER arrayOutput
On exit: if IFAIL≥0, details of the interchanges and the block structure of D, as determined by F07PDF (DSPTRF).
  • If IPIV k>0, then rows and columns k and IPIV k were interchanged, and d kk is a 1 by 1 diagonal block;
  • if UPLO='U' and IPIV k=IPIV k-1<0, then rows and columns k-1 and -IPIV k were interchanged and d k-1:k,k-1:k is a 2 by 2 diagonal block;
  • if UPLO='L' and IPIV k=IPIV k+1<0, then rows and columns k+1 and -IPIV k were interchanged and d k:k+1,k:k+1 is a 2 by 2 diagonal block.
6:   B LDB* – REAL (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array B must be at least max 1,NRHS.
On entry: the n by r matrix of right-hand sides B.
On exit: if IFAIL=0 or N+1, the n by r solution matrix X.
7:   LDB – INTEGERInput
On entry: the first dimension of the array B as declared in the (sub)program from which F04BJF is called.
Constraint: LDB≥max 1,N.
8:   RCOND – REAL (KIND=nag_wp)Output
On exit: if no constraints are violated, an estimate of the reciprocal of the condition number of the matrix A, computed as RCOND=1/A 1A-1 1.
9:   ERRBND – REAL (KIND=nag_wp)Output
On exit: if IFAIL=0 or N+1, an estimate of the forward error bound for a computed solution x^, such that x^-x 1/x 1≤ERRBND, where x^ is a column of the computed solution returned in the array B and x is the corresponding column of the exact solution X. If RCOND is less than machine precision, then ERRBND is returned as unity.
10:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL>0 and IFAIL≤N
Diagonal block value of the block diagonal matrix is zero. The factorization has been completed, but the solution could not be computed.
IFAIL=N+1
A solution has been computed, but RCOND is less than machine precision so that the matrix A is numerically singular.
IFAIL=-1
On entry, UPLO not one of 'U' or 'u' or 'L' or 'l': UPLO=value.
IFAIL=-2
On entry, N=value.
Constraint: N≥0.
IFAIL=-3
On entry, NRHS=value.
Constraint: NRHS≥0.
IFAIL=-7
On entry, LDB=value and N=value.
Constraint: LDB≥max 1,N.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
The integer allocatable memory required is N, and the real allocatable memory required is 2×N. Allocation failed before the solution could be computed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

The computed solution for a single right-hand side, x^, satisfies an equation of the form
A+E x^=b,
where
E 1 = O ε A 1
and ε is the machine precision. An approximate error bound for the computed solution is given by
x^-x 1 x 1 ≤ κ A E 1 A 1 ,
where κ A = A-1 1 A 1 , the condition number of A with respect to the solution of the linear equations. F04BJF uses the approximation E 1=ε A 1 to estimate ERRBND. See Section 4.4 of Anderson et al. (1999) for further details.

8 Parallelism and Performance

F04BJF makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The packed storage scheme is illustrated by the following example when n=4 and UPLO='U'. Two-dimensional storage of the symmetric matrix A:
a 11 a 12 a 13 a 14 a 22 a 23 a 24 a 33 a 34 a 44   a ij = a ji
Packed storage of the upper triangle of A:
AP= a 11, a 12, a 22, a 13, a 23, a 33, a 14, a 24, a 34, a 44
The total number of floating-point operations required to solve the equations AX=B is proportional to 13 n 3+2⁢n 2 r. The condition number estimation typically requires between four and five solves and never more than eleven solves, following the factorization.
In practice the condition number estimator is very reliable, but it can underestimate the true condition number; see Section 15.3 of Higham (2002) for further details.
The complex analogues of F04BJF are F04CJF for complex Hermitian matrices, and F04DJF for complex symmetric matrices.

10 Example

This example solves the equations
AX=B,
where A is the symmetric indefinite matrix
A= -1.81 2.06 0.63 -1.15 2.06 1.15 1.87 4.20 0.63 1.87 -0.21 3.87 -1.15 4.20 3.87 2.07   and   B= 0.96 3.93 6.07 19.25 8.38 9.90 9.50 27.85 .
An estimate of the condition number of A and an approximate error bound for the computed solutions are also printed.

10.1 Program Text

Program Text (f04bjfe.f90)

10.2 Program Data

Program Data (f04bjfe.d)

10.3 Program Results

Program Results (f04bjfe.r)

F04 Chapter Contents
F04 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F04CAF : NAG Library, Mark 26

F04 Chapter Contents
F04 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F04CAF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F04CAF computes the solution to a complex system of linear equations AX=B, where A is an n by n matrix and X and B are n by r matrices. An estimate of the condition number of A and an error bound for the computed solution are also returned.

2 Specification

SUBROUTINE F04CAF ( N, NRHS, A, LDA, IPIV, B, LDB, RCOND, ERRBND, IFAIL)
INTEGER | N, NRHS, LDA, IPIV(N), LDB, IFAIL
REAL (KIND=nag_wp) | RCOND, ERRBND
COMPLEX (KIND=nag_wp) | A(LDA,*), B(LDB,*)

3 Description

The LU decomposition with partial pivoting and row interchanges is used to factor A as A=PLU, where P is a permutation matrix, L is unit lower triangular, and U is upper triangular. The factored form of A is then used to solve the system of equations AX=B.

4 References

Anderson E, Bai Z, Bischof C, Blackford S, Demmel J, Dongarra J J, Du Croz J J, Greenbaum A, Hammarling S, McKenney A and Sorensen D (1999) LAPACK Users' Guide (3rd Edition) SIAM, Philadelphia http://www.netlib.org/lapack/lug
Higham N J (2002) Accuracy and Stability of Numerical Algorithms (2nd Edition) SIAM, Philadelphia

5 Arguments

1:   N – INTEGERInput
On entry: the number of linear equations n, i.e., the order of the matrix A.
Constraint: N≥0.
2:   NRHS – INTEGERInput
On entry: the number of right-hand sides r, i.e., the number of columns of the matrix B.
Constraint: NRHS≥0.
3:   A LDA* – COMPLEX (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array A must be at least max 1,N.
On entry: the n by n coefficient matrix A.
On exit: if IFAIL≥0, the factors L and U from the factorization A=PLU. The unit diagonal elements of L are not stored.
4:   LDA – INTEGERInput
On entry: the first dimension of the array A as declared in the (sub)program from which F04CAF is called.
Constraint: LDA≥max 1,N.
5:   IPIV N – INTEGER arrayOutput
On exit: if IFAIL≥0, the pivot indices that define the permutation matrix P; at the ith step row i of the matrix was interchanged with row IPIV i. IPIV i=i indicates a row interchange was not required.
6:   B LDB* – COMPLEX (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array B must be at least max 1,NRHS.
On entry: the n by r matrix of right-hand sides B.
On exit: if IFAIL=0 or N+1, the n by r solution matrix X.
7:   LDB – INTEGERInput
On entry: the first dimension of the array B as declared in the (sub)program from which F04CAF is called.
Constraint: LDB≥max 1,N.
8:   RCOND – REAL (KIND=nag_wp)Output
On exit: if no constraints are violated, an estimate of the reciprocal of the condition number of the matrix A, computed as RCOND=1/A 1A-1 1.
9:   ERRBND – REAL (KIND=nag_wp)Output
On exit: if IFAIL=0 or N+1, an estimate of the forward error bound for a computed solution x^, such that x^-x 1/x 1≤ERRBND, where x^ is a column of the computed solution returned in the array B and x is the corresponding column of the exact solution X. If RCOND is less than machine precision, then ERRBND is returned as unity.
10:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL>0 and IFAIL≤N
Diagonal element value of the upper triangular factor is zero. The factorization has been completed, but the solution could not be computed.
IFAIL=N+1
A solution has been computed, but RCOND is less than machine precision so that the matrix A is numerically singular.
IFAIL=-1
On entry, N=value.
Constraint: N≥0.
IFAIL=-2
On entry, NRHS=value.
Constraint: NRHS≥0.
IFAIL=-4
On entry, LDA=value and N=value.
Constraint: LDA≥max 1,N.
IFAIL=-7
On entry, LDB=value and N=value.
Constraint: LDB≥max 1,N.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
The complex allocatable memory required is 2×N, and the real allocatable memory required is 2×N. In this case the factorization and the solution X have been computed, but RCOND and ERRBND have not been computed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

The computed solution for a single right-hand side, x^, satisfies an equation of the form
A+E x^=b,
where
E 1 = O ε A 1
and ε is the machine precision. An approximate error bound for the computed solution is given by
x^-x 1 x 1 ≤ κ A E 1 A 1 ,
where κ A = A-1 1 A 1 , the condition number of A with respect to the solution of the linear equations. F04CAF uses the approximation E 1=ε A 1 to estimate ERRBND. See Section 4.4 of Anderson et al. (1999) for further details.

8 Parallelism and Performance

F04CAF is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
F04CAF makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The total number of floating-point operations required to solve the equations AX=B is proportional to 23 n 3+n 2 r. The condition number estimation typically requires between four and five solves and never more than eleven solves, following the factorization.
In practice the condition number estimator is very reliable, but it can underestimate the true condition number; see Section 15.3 of Higham (2002) for further details.
The real analogue of F04CAF is F04BAF.

10 Example

This example solves the equations
AX=B,
where
A = -1.34+2.55 i 0.28+3.17 i -6.39-2.20 i 0.72-0.92 i -0.17-1.41 i 3.31-0.15 i -0.15+1.34 i 1.29+1.38 i -3.29-2.39 i -1.91+4.42 i -0.14-1.35 i 1.72+1.35 i 2.41+0.39 i -0.56+1.47 i -0.83-0.69 i -1.96+0.67 i
and
B= 26.26+51.78 i 31.32-0 6.70 i 6.43-0 8.68 i 15.86-0 1.42 i -5.75+25.31 i -2.15+30.19 i 1.16+0 2.57 i -2.56+0 7.55 i .
An estimate of the condition number of A and an approximate error bound for the computed solutions are also printed.

10.1 Program Text

Program Text (f04cafe.f90)

10.2 Program Data

Program Data (f04cafe.d)

10.3 Program Results

Program Results (f04cafe.r)

F04 Chapter Contents
F04 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F04CBF : NAG Library, Mark 26

F04 Chapter Contents
F04 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F04CBF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F04CBF computes the solution to a complex system of linear equations AX=B, where A is an n by n band matrix, with kl subdiagonals and ku superdiagonals, and X and B are n by r matrices. An estimate of the condition number of A and an error bound for the computed solution are also returned.

2 Specification

SUBROUTINE F04CBF ( N, KL, KU, NRHS, AB, LDAB, IPIV, B, LDB, RCOND, ERRBND, IFAIL)
INTEGER | N, KL, KU, NRHS, LDAB, IPIV(N), LDB, IFAIL
REAL (KIND=nag_wp) | RCOND, ERRBND
COMPLEX (KIND=nag_wp) | AB(LDAB,*), B(LDB,*)

3 Description

The LU decomposition with partial pivoting and row interchanges is used to factor A as A=PLU, where P is a permutation matrix, L is the product of permutation matrices and unit lower triangular matrices with kl subdiagonals, and U is upper triangular with kl+ku superdiagonals. The factored form of A is then used to solve the system of equations AX=B.

4 References

Anderson E, Bai Z, Bischof C, Blackford S, Demmel J, Dongarra J J, Du Croz J J, Greenbaum A, Hammarling S, McKenney A and Sorensen D (1999) LAPACK Users' Guide (3rd Edition) SIAM, Philadelphia http://www.netlib.org/lapack/lug
Higham N J (2002) Accuracy and Stability of Numerical Algorithms (2nd Edition) SIAM, Philadelphia

5 Arguments

1:   N – INTEGERInput
On entry: the number of linear equations n, i.e., the order of the matrix A.
Constraint: N≥0.
2:   KL – INTEGERInput
On entry: the number of subdiagonals kl, within the band of A.
Constraint: KL≥0.
3:   KU – INTEGERInput
On entry: the number of superdiagonals ku, within the band of A.
Constraint: KU≥0.
4:   NRHS – INTEGERInput
On entry: the number of right-hand sides r, i.e., the number of columns of the matrix B.
Constraint: NRHS≥0.
5:   AB LDAB* – COMPLEX (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array AB must be at least max 1,N.
On entry: the n by n matrix A.
The matrix is stored in rows kl+1 to 2 kl+ku+1; the first kl rows need not be set, more precisely, the element A ij must be stored in
AB kl+ku+1+i-j j=A ij  for ​max 1,j-ku≤i≤min n,j+kl.
See Section 9 for further details.
On exit: if IFAIL≥0, AB is overwritten by details of the factorization.
The upper triangular band matrix U, with kl+ku superdiagonals, is stored in rows 1 to kl+ku+1 of the array, and the multipliers used to form the matrix L are stored in rows kl+ku+2 to 2 kl+ku+1.
6:   LDAB – INTEGERInput
On entry: the first dimension of the array AB as declared in the (sub)program from which F04CBF is called.
Constraint: LDAB≥2×KL+KU+1.
7:   IPIV N – INTEGER arrayOutput
On exit: if IFAIL≥0, the pivot indices that define the permutation matrix P; at the ith step row i of the matrix was interchanged with row IPIV i. IPIV i=i indicates a row interchange was not required.
8:   B LDB* – COMPLEX (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array B must be at least max 1,NRHS.
On entry: the n by r matrix of right-hand sides B.
On exit: if IFAIL=0 or N+1, the n by r solution matrix X.
9:   LDB – INTEGERInput
On entry: the first dimension of the array B as declared in the (sub)program from which F04CBF is called.
Constraint: LDB≥max 1,N.
10:   RCOND – REAL (KIND=nag_wp)Output
On exit: if IFAIL≥0, an estimate of the reciprocal of the condition number of the matrix A, computed as RCOND=A 1A-1 1.
11:   ERRBND – REAL (KIND=nag_wp)Output
On exit: if IFAIL=0 or N+1, an estimate of the forward error bound for a computed solution x^, such that x^-x 1/x 1≤ERRBND, where x^ is a column of the computed solution returned in the array B and x is the corresponding column of the exact solution X. If RCOND is less than machine precision, then ERRBND is returned as unity.
12:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL>0 and IFAIL≤N
Diagonal element value of the upper triangular factor is zero. The factorization has been completed, but the solution could not be computed.
IFAIL=N+1
A solution has been computed, but RCOND is less than machine precision so that the matrix A is numerically singular.
IFAIL=-1
On entry, N=value.
Constraint: N≥0.
IFAIL=-2
On entry, KL=value.
Constraint: KL≥0.
IFAIL=-3
On entry, KU=value.
Constraint: KU≥0.
IFAIL=-4
On entry, NRHS=value.
Constraint: NRHS≥0.
IFAIL=-6
On entry, LDAB =value, KL =value and KU=value.
Constraint: LDAB≥2×KL+KU+1.
IFAIL=-9
On entry, LDB=value and N=value.
Constraint: LDB≥max 1,N.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
The real allocatable memory required is N, and the complex allocatable memory required is 2×N. In this case the factorization and the solution X have been computed, but RCOND and ERRBND have not been computed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

The computed solution for a single right-hand side, x^, satisfies an equation of the form
A+E x^=b,
where
E 1=O ε A 1
and ε is the machine precision. An approximate error bound for the computed solution is given by
x^-x 1 x 1 ≤ κ A E 1 A 1 ,
where κ A=A-1 1A 1, the condition number of A with respect to the solution of the linear equations. F04CBF uses the approximation E 1=ε A 1 to estimate ERRBND. See Section 4.4 of Anderson et al. (1999) for further details.

8 Parallelism and Performance

F04CBF is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
F04CBF makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The band storage scheme for the array AB is illustrated by the following example, when n=6, kl=1, and ku=2. Storage of the band matrix A in the array AB:
* * * + + + * * a 13 a 24 a 35 a 46 * a 12 a 23 a 34 a 45 a 56 a 11 a 22 a 33 a 44 a 55 a 66 a 21 a 32 a 43 a 54 a 65 *
Array elements marked * need not be set and are not referenced by the routine. Array elements marked + need not be set, but are defined on exit from the routine and contain the elements u 14, u 25 and u 36.
The total number of floating-point operations required to solve the equations AX=B depends upon the pivoting required, but if n≫kl+ku then it is approximately bounded by O n kl kl + ku for the factorization and O n 2 kl + ku ,r for the solution following the factorization. The condition number estimation typically requires between four and five solves and never more than eleven solves, following the factorization.
In practice the condition number estimator is very reliable, but it can underestimate the true condition number; see Section 15.3 of Higham (2002) for further details.
The real analogue of F04CBF is F04BBF.

10 Example

This example solves the equations
AX=B,
where A is the band matrix
A= -1.65+2.26 i -2.05-0.85 i 0.97-2.84 i 0.00i+0.00 0.00+6.30 i -1.48-1.75 i -3.99+4.01 i 0.59-0.48 i 0.00i+0.00 -0.77+2.83 i -1.06+1.94 i 3.33-1.04 i 0.00i+0.00 0.00i+0.00 4.48-1.09 i -0.46-1.72 i
and
B= -1.06+21.50 i 12.85+0 2.84 i -22.72-53.90 i -70.22+21.57 i 28.24-38.60 i -20.73-0 1.23 i -34.56+16.73 i 26.01+31.97 i .
An estimate of the condition number of A and an approximate error bound for the computed solutions are also printed.

10.1 Program Text

Program Text (f04cbfe.f90)

10.2 Program Data

Program Data (f04cbfe.d)

10.3 Program Results

Program Results (f04cbfe.r)

F04 Chapter Contents
F04 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F04CCF : NAG Library, Mark 26

F04 Chapter Contents
F04 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F04CCF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F04CCF computes the solution to a complex system of linear equations AX=B, where A is an n by n tridiagonal matrix and X and B are n by r matrices. An estimate of the condition number of A and an error bound for the computed solution are also returned.

2 Specification

SUBROUTINE F04CCF ( N, NRHS, DL, D, DU, DU2, IPIV, B, LDB, RCOND, ERRBND, IFAIL)
INTEGER | N, NRHS, IPIV(N), LDB, IFAIL
REAL (KIND=nag_wp) | RCOND, ERRBND
COMPLEX (KIND=nag_wp) | DL(*), D(*), DU(*), DU2(N-2), B(LDB,*)

3 Description

The LU decomposition with partial pivoting and row interchanges is used to factor A as A=PLU, where P is a permutation matrix, L is unit lower triangular with at most one nonzero subdiagonal element, and U is an upper triangular band matrix with two superdiagonals. The factored form of A is then used to solve the system of equations AX=B.
Note that the equations AT X=B may be solved by interchanging the order of the arguments DU and DL.

4 References

Anderson E, Bai Z, Bischof C, Blackford S, Demmel J, Dongarra J J, Du Croz J J, Greenbaum A, Hammarling S, McKenney A and Sorensen D (1999) LAPACK Users' Guide (3rd Edition) SIAM, Philadelphia http://www.netlib.org/lapack/lug
Higham N J (2002) Accuracy and Stability of Numerical Algorithms (2nd Edition) SIAM, Philadelphia

5 Arguments

1:   N – INTEGERInput
On entry: the number of linear equations n, i.e., the order of the matrix A.
Constraint: N≥0.
2:   NRHS – INTEGERInput
On entry: the number of right-hand sides r, i.e., the number of columns of the matrix B.
Constraint: NRHS≥0.
3:   DL* – COMPLEX (KIND=nag_wp) arrayInput/Output
Note: the dimension of the array DL must be at least max 1,N-1.
On entry: must contain the n-1 subdiagonal elements of the matrix A.
On exit: if IFAIL≥0, DL is overwritten by the n-1 multipliers that define the matrix L from the LU factorization of A.
4:   D* – COMPLEX (KIND=nag_wp) arrayInput/Output
Note: the dimension of the array D must be at least max 1,N.
On entry: must contain the n diagonal elements of the matrix A.
On exit: if IFAIL≥0, D is overwritten by the n diagonal elements of the upper triangular matrix U from the LU factorization of A.
5:   DU* – COMPLEX (KIND=nag_wp) arrayInput/Output
Note: the dimension of the array DU must be at least max 1,N-1.
On entry: must contain the n-1 superdiagonal elements of the matrix A
On exit: if IFAIL≥0, DU is overwritten by the n-1 elements of the first superdiagonal of U.
6:   DU2 N-2 – COMPLEX (KIND=nag_wp) arrayOutput
On exit: if IFAIL≥0, DU2 returns the n-2 elements of the second superdiagonal of U.
7:   IPIV N – INTEGER arrayOutput
On exit: if IFAIL≥0, the pivot indices that define the permutation matrix P; at the ith step row i of the matrix was interchanged with row IPIV i. IPIV i will always be either i or i+1; IPIV i=i indicates a row interchange was not required.
8:   B LDB* – COMPLEX (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array B must be at least max 1,NRHS.
On entry: the n by r matrix of right-hand sides B.
On exit: if IFAIL=0 or N+1, the n by r solution matrix X.
9:   LDB – INTEGERInput
On entry: the first dimension of the array B as declared in the (sub)program from which F04CCF is called.
Constraint: LDB≥max 1,N.
10:   RCOND – REAL (KIND=nag_wp)Output
On exit: if no constraints are violated, an estimate of the reciprocal of the condition number of the matrix A, computed as RCOND=1/A 1A-1 1.
11:   ERRBND – REAL (KIND=nag_wp)Output
On exit: if IFAIL=0 or N+1, an estimate of the forward error bound for a computed solution x^, such that x^-x 1/x 1≤ERRBND, where x^ is a column of the computed solution returned in the array B and x is the corresponding column of the exact solution X. If RCOND is less than machine precision, then ERRBND is returned as unity.
12:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL>0 and IFAIL≤N
Diagonal element value of the upper triangular factor is zero. The factorization has been completed, but the solution could not be computed.
IFAIL=N+1
A solution has been computed, but RCOND is less than machine precision so that the matrix A is numerically singular.
IFAIL=-1
On entry, N=value.
Constraint: N≥0.
IFAIL=-2
On entry, NRHS=value.
Constraint: NRHS≥0.
IFAIL=-9
On entry, LDB=value and N=value.
Constraint: LDB≥max 1,N.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
The complex allocatable memory required is 2×N. In this case the factorization and the solution X have been computed, but RCOND and ERRBND have not been computed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

The computed solution for a single right-hand side, x^, satisfies an equation of the form
A+E x^=b,
where
E 1 = O ε A 1
and ε is the machine precision. An approximate error bound for the computed solution is given by
x^-x 1 x 1 ≤ κ A E 1 A 1 ,
where κ A = A-1 1 A 1 , the condition number of A with respect to the solution of the linear equations. F04CCF uses the approximation E 1=ε A 1 to estimate ERRBND. See Section 4.4 of Anderson et al. (1999) for further details.

8 Parallelism and Performance

F04CCF makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The total number of floating-point operations required to solve the equations AX=B is proportional to nr. The condition number estimation typically requires between four and five solves and never more than eleven solves, following the factorization.
In practice the condition number estimator is very reliable, but it can underestimate the true condition number; see Section 15.3 of Higham (2002) for further details.
The real analogue of F04CCF is F04BCF.

10 Example

This example solves the equations
AX=B,
where A is the tridiagonal matrix
A= -1.3+1.3 i 2.0-1.0 i 0.0i+0.0 0.0i+0.0 0.0i+0.0 1.0-2.0 i -1.3+1.3 i 2.0+1.0 i 0.0i+0.0 0.0i+0.0 0.0i+0.0 1.0+1.0 i -1.3+3.3 i -1.0+1.0 i 0.0i+0.0 0.0i+0.0 0.0i+0.0 2.0-3.0 i -0.3+4.3 i 1.0-1.0 i 0.0i+0.0 0.0i+0.0 0.0i+0.0 1.0+1.0 i -3.3+1.3 i
and
B = 2.4-0 5.0 i 2.7+0 6.9 i 3.4+18.2 i -6.9-0 5.3 i -14.7+0 9.7 i -6.0-0 0.6 i 31.9-0 7.7 i -3.9+0 9.3 i -1.0+0 1.6 i -3.0+12.2 i .
An estimate of the condition number of A and an approximate error bound for the computed solutions are also printed.

10.1 Program Text

Program Text (f04ccfe.f90)

10.2 Program Data

Program Data (f04ccfe.d)

10.3 Program Results

Program Results (f04ccfe.r)

F04 Chapter Contents
F04 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F04CDF : NAG Library, Mark 26

F04 Chapter Contents
F04 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F04CDF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F04CDF computes the solution to a complex system of linear equations AX=B, where A is an n by n Hermitian positive definite matrix and X and B are n by r matrices. An estimate of the condition number of A and an error bound for the computed solution are also returned.

2 Specification

SUBROUTINE F04CDF ( UPLO, N, NRHS, A, LDA, B, LDB, RCOND, ERRBND, IFAIL)
INTEGER | N, NRHS, LDA, LDB, IFAIL
REAL (KIND=nag_wp) | RCOND, ERRBND
COMPLEX (KIND=nag_wp) | A(LDA,*), B(LDB,*)
CHARACTER(1) | UPLO

3 Description

The Cholesky factorization is used to factor A as A=UH U, if UPLO='U', or A=L LH, if UPLO='L', where U is an upper triangular matrix and L is a lower triangular matrix. The factored form of A is then used to solve the system of equations AX=B.

4 References

Anderson E, Bai Z, Bischof C, Blackford S, Demmel J, Dongarra J J, Du Croz J J, Greenbaum A, Hammarling S, McKenney A and Sorensen D (1999) LAPACK Users' Guide (3rd Edition) SIAM, Philadelphia http://www.netlib.org/lapack/lug
Higham N J (2002) Accuracy and Stability of Numerical Algorithms (2nd Edition) SIAM, Philadelphia

5 Arguments

1:   UPLO – CHARACTER(1)Input
On entry: if UPLO='U', the upper triangle of the matrix A is stored.
If UPLO='L', the lower triangle of the matrix A is stored.
Constraint: UPLO='U' or 'L'.
2:   N – INTEGERInput
On entry: the number of linear equations n, i.e., the order of the matrix A.
Constraint: N≥0.
3:   NRHS – INTEGERInput
On entry: the number of right-hand sides r, i.e., the number of columns of the matrix B.
Constraint: NRHS≥0.
4:   A LDA* – COMPLEX (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array A must be at least max 1,N.
On entry: the n by n Hermitian matrix A.
If UPLO='U', the leading N by N upper triangular part of A contains the upper triangular part of the matrix A, and the strictly lower triangular part of A is not referenced.
If UPLO='L', the leading N by N lower triangular part of A contains the lower triangular part of the matrix A, and the strictly upper triangular part of A is not referenced.
On exit: if IFAIL=0 or N+1, the factor U or L from the Cholesky factorization A=UH U or A=L LH.
5:   LDA – INTEGERInput
On entry: the first dimension of the array A as declared in the (sub)program from which F04CDF is called.
Constraint: LDA≥max 1,N.
6:   B LDB* – COMPLEX (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array B must be at least max 1,NRHS.
On entry: the n by r matrix of right-hand sides B.
On exit: if IFAIL=0 or N+1, the n by r solution matrix X.
7:   LDB – INTEGERInput
On entry: the first dimension of the array B as declared in the (sub)program from which F04CDF is called.
Constraint: LDB≥max 1,N.
8:   RCOND – REAL (KIND=nag_wp)Output
On exit: if IFAIL=0 or N+1, an estimate of the reciprocal of the condition number of the matrix A, computed as RCOND=1/A 1A-1 1.
9:   ERRBND – REAL (KIND=nag_wp)Output
On exit: if IFAIL=0 or N+1, an estimate of the forward error bound for a computed solution x^, such that x^-x 1/x 1≤ERRBND, where x^ is a column of the computed solution returned in the array B and x is the corresponding column of the exact solution X. If RCOND is less than machine precision, then ERRBND is returned as unity.
10:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL>0 and IFAIL≤N
The principal minor of order value of the matrix A is not positive definite. The factorization has not been completed and the solution could not be computed.
IFAIL=N+1
A solution has been computed, but RCOND is less than machine precision so that the matrix A is numerically singular.
IFAIL=-1
On entry, UPLO not one of 'U' or 'u' or 'L' or 'l': UPLO=value.
IFAIL=-2
On entry, N=value.
Constraint: N≥0.
IFAIL=-3
On entry, NRHS=value.
Constraint: NRHS≥0.
IFAIL=-5
On entry, LDA=value and N=value.
Constraint: LDA≥max 1,N.
IFAIL=-7
On entry, LDB=value and N=value.
Constraint: LDB≥max 1,N.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
The real allocatable memory required is N, and the complex allocatable memory required is 2×N. Allocation failed before the solution could be computed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

The computed solution for a single right-hand side, x^, satisfies an equation of the form
A+E x^=b,
where
E 1 = O ε A 1
and ε is the machine precision. An approximate error bound for the computed solution is given by
x^-x 1 x 1 ≤ κ A E 1 A 1 ,
where κ A = A-1 1 A 1 , the condition number of A with respect to the solution of the linear equations. F04CDF uses the approximation E 1=ε A 1 to estimate ERRBND. See Section 4.4 of Anderson et al. (1999) for further details.

8 Parallelism and Performance

F04CDF is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
F04CDF makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The total number of floating-point operations required to solve the equations AX=B is proportional to 13 n 3+n 2 r. The condition number estimation typically requires between four and five solves and never more than eleven solves, following the factorization.
In practice the condition number estimator is very reliable, but it can underestimate the true condition number; see Section 15.3 of Higham (2002) for further details.
The real analogue of F04CDF is F04BDF.

10 Example

This example solves the equations
AX=B,
where A is the Hermitian positive definite matrix
A= 3.23 i+0.00 1.51-1.92 i 1.90+0.84 i 0.42+2.50 i 1.51+1.92 i 3.58 i+0.00 -0.23+1.11 i -1.18+1.37 i 1.90-0.84 i -0.23-1.11 i 4.09 i+0.00 2.33-0.14 i 0.42-2.50 i -1.18-1.37 i 2.33+0.14 i 4.29 i+0.00
and
B= 3.93-0 6.14 i 1.48+0 6.58 i 6.17+0 9.42 i 4.65-0 4.75 i -7.17-21.83 i -4.91+0 2.29 i 1.99-14.38 i 7.64-10.79 i .
An estimate of the condition number of A and an approximate error bound for the computed solutions are also printed.

10.1 Program Text

Program Text (f04cdfe.f90)

10.2 Program Data

Program Data (f04cdfe.d)

10.3 Program Results

Program Results (f04cdfe.r)

F04 Chapter Contents
F04 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F04CEF : NAG Library, Mark 26

F04 Chapter Contents
F04 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F04CEF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F04CEF computes the solution to a complex system of linear equations AX=B, where A is an n by n Hermitian positive definite matrix, stored in packed format, and X and B are n by r matrices. An estimate of the condition number of A and an error bound for the computed solution are also returned.

2 Specification

SUBROUTINE F04CEF ( UPLO, N, NRHS, AP, B, LDB, RCOND, ERRBND, IFAIL)
INTEGER | N, NRHS, LDB, IFAIL
REAL (KIND=nag_wp) | RCOND, ERRBND
COMPLEX (KIND=nag_wp) | AP(*), B(LDB,*)
CHARACTER(1) | UPLO

3 Description

The Cholesky factorization is used to factor A as A=UH U, if UPLO='U', or A=L LH, if UPLO='L', where U is an upper triangular matrix and L is a lower triangular matrix. The factored form of A is then used to solve the system of equations AX=B.

4 References

Anderson E, Bai Z, Bischof C, Blackford S, Demmel J, Dongarra J J, Du Croz J J, Greenbaum A, Hammarling S, McKenney A and Sorensen D (1999) LAPACK Users' Guide (3rd Edition) SIAM, Philadelphia http://www.netlib.org/lapack/lug
Higham N J (2002) Accuracy and Stability of Numerical Algorithms (2nd Edition) SIAM, Philadelphia

5 Arguments

1:   UPLO – CHARACTER(1)Input
On entry: if UPLO='U', the upper triangle of the matrix A is stored.
If UPLO='L', the lower triangle of the matrix A is stored.
Constraint: UPLO='U' or 'L'.
2:   N – INTEGERInput
On entry: the number of linear equations n, i.e., the order of the matrix A.
Constraint: N≥0.
3:   NRHS – INTEGERInput
On entry: the number of right-hand sides r, i.e., the number of columns of the matrix B.
Constraint: NRHS≥0.
4:   AP* – COMPLEX (KIND=nag_wp) arrayInput/Output
Note: the dimension of the array AP must be at least max 1,N×N+1/2.
On entry: the n by n Hermitian matrix A. The upper or lower triangular part of the Hermitian matrix is packed column-wise in a linear array. The jth column of A is stored in the array AP as follows:
More precisely,
  • if UPLO='U', the upper triangle of A must be stored with element A ij in AP i+j j-1/2 for i≤j;
  • if UPLO='L', the lower triangle of A must be stored with element A ij in AP i+2 n-jj-1/2 for i≥j.
On exit: if IFAIL=0 or N+1, the factor U or L from the Cholesky factorization A=UH U or A=L LH, in the same storage format as A.
5:   B LDB* – COMPLEX (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array B must be at least max 1,NRHS.
On entry: the n by r matrix of right-hand sides B.
On exit: if IFAIL=0 or N+1, the n by r solution matrix X.
6:   LDB – INTEGERInput
On entry: the first dimension of the array B as declared in the (sub)program from which F04CEF is called.
Constraint: LDB≥max 1,N.
7:   RCOND – REAL (KIND=nag_wp)Output
On exit: if IFAIL=0 or N+1, an estimate of the reciprocal of the condition number of the matrix A, computed as RCOND=1/A 1A-1 1.
8:   ERRBND – REAL (KIND=nag_wp)Output
On exit: if IFAIL=0 or N+1, an estimate of the forward error bound for a computed solution x^, such that x^-x 1/x 1≤ERRBND, where x^ is a column of the computed solution returned in the array B and x is the corresponding column of the exact solution X. If RCOND is less than machine precision, then ERRBND is returned as unity.
9:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL<0 and IFAIL≠-999
If IFAIL=-i, the ith argument had an illegal value.
IFAIL>0 and IFAIL≤N
If IFAIL=i, the leading minor of order i of A is not positive definite. The factorization could not be completed, and the solution has not been computed.
IFAIL=N+1
RCOND is less than machine precision, so that the matrix A is numerically singular. A solution to the equations AX=B has nevertheless been computed.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

The computed solution for a single right-hand side, x^, satisfies an equation of the form
A+E x^=b,
where
E 1=O ε A 1
and ε is the machine precision. An approximate error bound for the computed solution is given by
x^-x 1 x 1 ≤ κ A E 1 A 1 ,
where κ A=A-1 1A 1, the condition number of A with respect to the solution of the linear equations. F04CEF uses the approximation E 1=ε A 1 to estimate ERRBND. See Section 4.4 of Anderson et al. (1999) for further details.

8 Parallelism and Performance

F04CEF is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
F04CEF makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The packed storage scheme is illustrated by the following example when n=4 and UPLO='U'. Two-dimensional storage of the Hermitian matrix A:
a 11 a 12 a 13 a 14 a 22 a 23 a 24 a 33 a 34 a 44   a ij = a- ji
Packed storage of the upper triangle of A:
AP= a 11, a 12, a 22, a 13, a 23, a 33, a 14, a 24, a 34, a 44
The total number of floating-point operations required to solve the equations AX=B is proportional to 13 n 3+n 2 r. The condition number estimation typically requires between four and five solves and never more than eleven solves, following the factorization.
In practice the condition number estimator is very reliable, but it can underestimate the true condition number; see Section 15.3 of Higham (2002) for further details.
The real analogue of F04CEF is F04BEF.

10 Example

This example solves the equations
AX=B,
where A is the Hermitian positive definite matrix
A= 3.23 i+0.00 1.51-1.92 i 1.90+0.84 i 0.42+2.50 i 1.51+1.92 i 3.58 i+0.00 -0.23+1.11 i -1.18+1.37 i 1.90-0.84 i -0.23-1.11 i 4.09 i+0.00 2.33-0.14 i 0.42-2.50 i -1.18-1.37 i 2.33+0.14 i 4.29 i+0.00
and
B= 3.93-0 6.14 i 1.48+0 6.58 i 6.17+0 9.42 i 4.65-0 4.75 i -7.17-21.83 i -4.91+0 2.29 i 1.99-14.38 i 7.64-10.79 i .
An estimate of the condition number of A and an approximate error bound for the computed solutions are also printed.

10.1 Program Text

Program Text (f04cefe.f90)

10.2 Program Data

Program Data (f04cefe.d)

10.3 Program Results

Program Results (f04cefe.r)

F04 Chapter Contents
F04 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F04CFF : NAG Library, Mark 26

F04 Chapter Contents
F04 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F04CFF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F04CFF computes the solution to a complex system of linear equations AX=B, where A is an n by n Hermitian positive definite band matrix of band width 2 k+1, and X and B are n by r matrices. An estimate of the condition number of A and an error bound for the computed solution are also returned.

2 Specification

SUBROUTINE F04CFF ( UPLO, N, KD, NRHS, AB, LDAB, B, LDB, RCOND, ERRBND, IFAIL)
INTEGER | N, KD, NRHS, LDAB, LDB, IFAIL
REAL (KIND=nag_wp) | RCOND, ERRBND
COMPLEX (KIND=nag_wp) | AB(LDAB,*), B(LDB,*)
CHARACTER(1) | UPLO

3 Description

The Cholesky factorization is used to factor A as A=UH U, if UPLO='U', or A=L LH, if UPLO='L', where U is an upper triangular band matrix with k superdiagonals, and L is a lower triangular band matrix with k subdiagonals. The factored form of A is then used to solve the system of equations AX=B.

4 References

Anderson E, Bai Z, Bischof C, Blackford S, Demmel J, Dongarra J J, Du Croz J J, Greenbaum A, Hammarling S, McKenney A and Sorensen D (1999) LAPACK Users' Guide (3rd Edition) SIAM, Philadelphia http://www.netlib.org/lapack/lug
Higham N J (2002) Accuracy and Stability of Numerical Algorithms (2nd Edition) SIAM, Philadelphia

5 Arguments

1:   UPLO – CHARACTER(1)Input
On entry: if UPLO='U', the upper triangle of the matrix A is stored.
If UPLO='L', the lower triangle of the matrix A is stored.
Constraint: UPLO='U' or 'L'.
2:   N – INTEGERInput
On entry: the number of linear equations n, i.e., the order of the matrix A.
Constraint: N≥0.
3:   KD – INTEGERInput
On entry: the number of superdiagonals k (and the number of subdiagonals) of the band matrix A.
Constraint: KD≥0.
4:   NRHS – INTEGERInput
On entry: the number of right-hand sides r, i.e., the number of columns of the matrix B.
Constraint: NRHS≥0.
5:   AB LDAB* – COMPLEX (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array AB must be at least max 1,N.
On entry: the n by n Hermitian band matrix A. The upper or lower triangular part of the Hermitian matrix is stored in the first KD+1 rows of the array. The jth column of A is stored in the jth column of the array AB as follows:
The matrix is stored in rows 1 to k+1, more precisely,
  • if UPLO='U', the elements of the upper triangle of A within the band must be stored with element A ij in AB k+1+i-j j​ for ​max 1,j-k≤i≤j;
  • if UPLO='L', the elements of the lower triangle of A within the band must be stored with element A ij in AB 1+i-j j​ for ​j≤i≤min n,j+k.
See Section 9 below for further details.
On exit: if IFAIL=0 or N+1, the factor U or L from the Cholesky factorization A=UH U or A=L LH, in the same storage format as A.
6:   LDAB – INTEGERInput
On entry: the first dimension of the array AB as declared in the (sub)program from which F04CFF is called.
Constraint: LDAB≥KD+1.
7:   B LDB* – COMPLEX (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array B must be at least max 1,NRHS.
On entry: the n by r matrix of right-hand sides B.
On exit: if IFAIL=0 or N+1, the n by r solution matrix X.
8:   LDB – INTEGERInput
On entry: the first dimension of the array B as declared in the (sub)program from which F04CFF is called.
Constraint: LDB≥max 1,N.
9:   RCOND – REAL (KIND=nag_wp)Output
On exit: if IFAIL=0 or N+1, an estimate of the reciprocal of the condition number of the matrix A, computed as RCOND=1/A 1A-1 1.
10:   ERRBND – REAL (KIND=nag_wp)Output
On exit: if IFAIL=0 or N+1, an estimate of the forward error bound for a computed solution x^, such that x^-x 1/x 1≤ERRBND, where x^ is a column of the computed solution returned in the array B and x is the corresponding column of the exact solution X. If RCOND is less than machine precision, then ERRBND is returned as unity.
11:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL<0 and IFAIL≠-999
If IFAIL=-i, the ith argument had an illegal value.
IFAIL>0 and IFAIL≤N
If IFAIL=i, the leading minor of order i of A is not positive definite. The factorization could not be completed, and the solution has not been computed.
IFAIL=N+1
RCOND is less than machine precision, so that the matrix A is numerically singular. A solution to the equations AX=B has nevertheless been computed.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

The computed solution for a single right-hand side, x^, satisfies an equation of the form
A+E x^=b,
where
E 1=O ε A 1
and ε is the machine precision. An approximate error bound for the computed solution is given by
x^-x 1 x 1 ≤ κ A E 1 A 1 ,
where κ A=A-1 1A 1, the condition number of A with respect to the solution of the linear equations. F04CFF uses the approximation E 1=ε A 1 to estimate ERRBND. See Section 4.4 of Anderson et al. (1999) for further details.

8 Parallelism and Performance

F04CFF is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
F04CFF makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The band storage scheme for the array AB is illustrated by the following example, when n=6, k=2, and UPLO='U':
On entry:
* * a 13 a 24 a 35 a 46 * a 12 a 23 a 34 a 45 a 56 a 11 a 22 a 33 a 44 a 55 a 66
On exit:
* * u 13 u 24 u 35 u 46 * u 12 u 23 u 34 u 45 u 56 u 11 u 22 u 33 u 44 u 55 u 66
Similarly, if UPLO='L' the format of AB is as follows:
On entry:
a 11 a 22 a 33 a 44 a 55 a 66 a 21 a 32 a 43 a 54 a 65 * a 31 a 42 a 53 a 64 * *
On exit:
l 11 l 22 l 33 l 44 l 55 l 66 l 21 l 32 l 43 l 54 l 65 * l 31 l 42 l 53 l 64 * *
Array elements marked * need not be set and are not referenced by the routine.
Assuming that n≫k, the total number of floating-point operations required to solve the equations AX=B is approximately n k+1 2 for the factorization and 4 nkr for the solution following the factorization. The condition number estimation typically requires between four and five solves and never more than eleven solves, following the factorization.
In practice the condition number estimator is very reliable, but it can underestimate the true condition number; see Section 15.3 of Higham (2002) for further details.
The real analogue of F04CFF is F04BFF.

10 Example

This example solves the equations
AX=B,
where A is the Hermitian positive definite band matrix
A= 9.39 i+0.00 1.08-1.73 i 0.00i+0.00 0.00i+0.00 1.08+1.73 i 1.69 i+0.00 -0.04+0.29 i 0.00i+0.00 0.00i+0.00 -0.04-0.29 i 2.65 i+0.00 -0.33+2.24 i 0.00i+0.00 0.00i+0.00 -0.33-2.24 i 2.17 i+0.00
and
B= -12.42+68.42 i 54.30-56.56 i -9.93+0 0.88 i 18.32+0 4.76 i -27.30-0 0.01 i -4.40+0 9.97 i 5.31+23.63 i 9.43+0 1.41 i .
An estimate of the condition number of A and an approximate error bound for the computed solutions are also printed.

10.1 Program Text

Program Text (f04cffe.f90)

10.2 Program Data

Program Data (f04cffe.d)

10.3 Program Results

Program Results (f04cffe.r)

F04 Chapter Contents
F04 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F04CGF : NAG Library, Mark 26

F04 Chapter Contents
F04 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F04CGF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F04CGF computes the solution to a complex system of linear equations AX=B, where A is an n by n Hermitian positive definite tridiagonal matrix and X and B are n by r matrices. An estimate of the condition number of A and an error bound for the computed solution are also returned.

2 Specification

SUBROUTINE F04CGF ( N, NRHS, D, E, B, LDB, RCOND, ERRBND, IFAIL)
INTEGER | N, NRHS, LDB, IFAIL
REAL (KIND=nag_wp) | D(*), RCOND, ERRBND
COMPLEX (KIND=nag_wp) | E(*), B(LDB,*)

3 Description

A is factorized as A=LD LH, where L is a unit lower bidiagonal matrix and D is a real diagonal matrix, and the factored form of A is then used to solve the system of equations.

4 References

Anderson E, Bai Z, Bischof C, Blackford S, Demmel J, Dongarra J J, Du Croz J J, Greenbaum A, Hammarling S, McKenney A and Sorensen D (1999) LAPACK Users' Guide (3rd Edition) SIAM, Philadelphia http://www.netlib.org/lapack/lug
Higham N J (2002) Accuracy and Stability of Numerical Algorithms (2nd Edition) SIAM, Philadelphia

5 Arguments

1:   N – INTEGERInput
On entry: the number of linear equations n, i.e., the order of the matrix A.
Constraint: N≥0.
2:   NRHS – INTEGERInput
On entry: the number of right-hand sides r, i.e., the number of columns of the matrix B.
Constraint: NRHS≥0.
3:   D* – REAL (KIND=nag_wp) arrayInput/Output
Note: the dimension of the array D must be at least max 1,N.
On entry: must contain the n diagonal elements of the tridiagonal matrix A.
On exit: if IFAIL=0 or N+1, D is overwritten by the n diagonal elements of the diagonal matrix D from the LD LH factorization of A.
4:   E* – COMPLEX (KIND=nag_wp) arrayInput/Output
Note: the dimension of the array E must be at least max 1,N-1.
On entry: must contain the n-1 subdiagonal elements of the tridiagonal matrix A.
On exit: if IFAIL=0 or N+1, E is overwritten by the n-1 subdiagonal elements of the unit lower bidiagonal matrix L from the LD LH factorization of A. (E can also be regarded as the conjugate of the superdiagonal of the unit upper bidiagonal factor U from the UH DU factorization of A.)
5:   B LDB* – COMPLEX (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array B must be at least max 1,NRHS.
On entry: the n by r matrix of right-hand sides B.
On exit: if IFAIL=0 or N+1, the n by r solution matrix X.
6:   LDB – INTEGERInput
On entry: the first dimension of the array B as declared in the (sub)program from which F04CGF is called.
Constraint: LDB≥max 1,N.
7:   RCOND – REAL (KIND=nag_wp)Output
On exit: if IFAIL=0 or N+1, an estimate of the reciprocal of the condition number of the matrix A, computed as RCOND=1/A 1,A-1 1.
8:   ERRBND – REAL (KIND=nag_wp)Output
On exit: if IFAIL=0 or N+1, an estimate of the forward error bound for a computed solution x^, such that x^-x 1/x 1≤ERRBND, where x^ is a column of the computed solution returned in the array B and x is the corresponding column of the exact solution X. If RCOND is less than machine precision, then ERRBND is returned as unity.
9:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL>0 and IFAIL≤N
The principal minor of order value of the matrix A is not positive definite. The factorization has not been completed and the solution could not be computed.
IFAIL=N+1
A solution has been computed, but RCOND is less than machine precision so that the matrix A is numerically singular.
IFAIL=-1
On entry, N=value.
Constraint: N≥0.
IFAIL=-2
On entry, NRHS=value.
Constraint: NRHS≥0.
IFAIL=-6
On entry, LDB=value and N=value.
Constraint: LDB≥max 1,N.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
The real allocatable memory required is N. In this case the factorization and the solution X have been computed, but RCOND and ERRBND have not been computed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

The computed solution for a single right-hand side, x^, satisfies an equation of the form
A+E x^=b,
where
E 1=O ε A 1
and ε is the machine precision. An approximate error bound for the computed solution is given by
x^-x 1 x 1 ≤ κ A E 1 A 1 ,
where κ A=A-1 1A 1, the condition number of A with respect to the solution of the linear equations. F04CGF uses the approximation E 1=ε A 1 to estimate ERRBND. See Section 4.4 of Anderson et al. (1999) for further details.

8 Parallelism and Performance

F04CGF makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The total number of floating-point operations required to solve the equations AX=B is proportional to nr. The condition number estimation requires O n floating-point operations.
See Section 15.3 of Higham (2002) for further details on computing the condition number of tridiagonal matrices.
The real analogue of F04CGF is F04BGF.

10 Example

This example solves the equations
AX=B,
where A is the Hermitian positive definite tridiagonal matrix
A= 16.0 i+00.0 16.0+16.0 i 0.0i+0.0 0.0i+0.0 16.0-16.0 i 41.0 i+00.0 18.0-9.0 i 0.0i+0.0 0.0i+00.0 18.0+0 9.0 i 46.0 i+0.0 1.0-4.0 i 0.0i+00.0 0.0i+00.0 1.0+4.0 i 21.0 i+0.0
and
B= 64.0+16.0 i -16.0-32.0 i 93.0+62.0 i 61.0-66.0 i 78.0-80.0 i 71.0-74.0 i 14.0-27.0 i 35.0+15.0 i .
An estimate of the condition number of A and an approximate error bound for the computed solutions are also printed.

10.1 Program Text

Program Text (f04cgfe.f90)

10.2 Program Data

Program Data (f04cgfe.d)

10.3 Program Results

Program Results (f04cgfe.r)

F04 Chapter Contents
F04 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F04CHF : NAG Library, Mark 26

F04 Chapter Contents
F04 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F04CHF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F04CHF computes the solution to a complex system of linear equations AX=B, where A is an n by n Hermitian matrix and X and B are n by r matrices. An estimate of the condition number of A and an error bound for the computed solution are also returned.

2 Specification

SUBROUTINE F04CHF ( UPLO, N, NRHS, A, LDA, IPIV, B, LDB, RCOND, ERRBND, IFAIL)
INTEGER | N, NRHS, LDA, IPIV(N), LDB, IFAIL
REAL (KIND=nag_wp) | RCOND, ERRBND
COMPLEX (KIND=nag_wp) | A(LDA,*), B(LDB,*)
CHARACTER(1) | UPLO

3 Description

The diagonal pivoting method is used to factor A as A=UD UH, if UPLO='U', or A=LD LH, if UPLO='L', where U (or L) is a product of permutation and unit upper (lower) triangular matrices, and D is Hermitian and block diagonal with 1 by 1 and 2 by 2 diagonal blocks. The factored form of A is then used to solve the system of equations AX=B.

4 References

Anderson E, Bai Z, Bischof C, Blackford S, Demmel J, Dongarra J J, Du Croz J J, Greenbaum A, Hammarling S, McKenney A and Sorensen D (1999) LAPACK Users' Guide (3rd Edition) SIAM, Philadelphia http://www.netlib.org/lapack/lug
Higham N J (2002) Accuracy and Stability of Numerical Algorithms (2nd Edition) SIAM, Philadelphia

5 Arguments

1:   UPLO – CHARACTER(1)Input
On entry: if UPLO='U', the upper triangle of the matrix A is stored.
If UPLO='L', the lower triangle of the matrix A is stored.
Constraint: UPLO='U' or 'L'.
2:   N – INTEGERInput
On entry: the number of linear equations n, i.e., the order of the matrix A.
Constraint: N≥0.
3:   NRHS – INTEGERInput
On entry: the number of right-hand sides r, i.e., the number of columns of the matrix B.
Constraint: NRHS≥0.
4:   A LDA* – COMPLEX (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array A must be at least max 1,N.
On entry: the n by n Hermitian matrix A.
If UPLO='U', the leading N by N upper triangular part of the array A contains the upper triangular part of the matrix A, and the strictly lower triangular part of A is not referenced.
If UPLO='L', the leading N by N lower triangular part of the array A contains the lower triangular part of the matrix A, and the strictly upper triangular part of A is not referenced.
On exit: if IFAIL≥0, the block diagonal matrix D and the multipliers used to obtain the factor U or L from the factorization A=UD UH or A=LD LH as computed by F07MRF (ZHETRF).
5:   LDA – INTEGERInput
On entry: the first dimension of the array A as declared in the (sub)program from which F04CHF is called.
Constraint: LDA≥max 1,N.
6:   IPIV N – INTEGER arrayOutput
On exit: if IFAIL≥0, details of the interchanges and the block structure of D, as determined by F07MRF (ZHETRF).
  • If IPIV k>0, then rows and columns k and IPIV k were interchanged, and d kk is a 1 by 1 diagonal block;
  • if UPLO='U' and IPIV k=IPIV k-1<0, then rows and columns k-1 and -IPIV k were interchanged and d k-1:k,k-1:k is a 2 by 2 diagonal block;
  • if UPLO='L' and IPIV k=IPIV k+1<0, then rows and columns k+1 and -IPIV k were interchanged and d k:k+1,k:k+1 is a 2 by 2 diagonal block.
7:   B LDB* – COMPLEX (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array B must be at least max 1,NRHS.
On entry: the n by r matrix of right-hand sides B.
On exit: if IFAIL=0 or N+1, the n by r solution matrix X.
8:   LDB – INTEGERInput
On entry: the first dimension of the array B as declared in the (sub)program from which F04CHF is called.
Constraint: LDB≥max 1,N.
9:   RCOND – REAL (KIND=nag_wp)Output
On exit: if no constraints are violated, an estimate of the reciprocal of the condition number of the matrix A, computed as RCOND=1/A 1A-1 1.
10:   ERRBND – REAL (KIND=nag_wp)Output
On exit: if IFAIL=0 or N+1, an estimate of the forward error bound for a computed solution x^, such that x^-x 1/x 1≤ERRBND, where x^ is a column of the computed solution returned in the array B and x is the corresponding column of the exact solution X. If RCOND is less than machine precision, then ERRBND is returned as unity.
11:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL>0 and IFAIL≤N
Diagonal block value of the block diagonal matrix is zero. The factorization has been completed, but the solution could not be computed.
IFAIL=N+1
A solution has been computed, but RCOND is less than machine precision so that the matrix A is numerically singular.
IFAIL=-1
On entry, UPLO not one of 'U' or 'u' or 'L' or 'l': UPLO=value.
IFAIL=-2
On entry, N=value.
Constraint: N≥0.
IFAIL=-3
On entry, NRHS=value.
Constraint: NRHS≥0.
IFAIL=-5
On entry, LDA=value and N=value.
Constraint: LDA≥max 1,N.
IFAIL=-8
On entry, LDB=value and N=value.
Constraint: LDB≥max 1,N.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
The real allocatable memory required is N, and the complex allocatable memory required is max 2×N,LWORK, where LWORK is the optimum workspace required by F07MNF (ZHESV). If this failure occurs it may be possible to solve the equations by calling the packed storage version of F04CHF, F04CJF, or by calling F07MNF (ZHESV) directly with less than the optimum workspace (see Chapter F07).
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

The computed solution for a single right-hand side, x^, satisfies an equation of the form
A+E x^ = b ,
where
E 1 = O ε A 1
and ε is the machine precision. An approximate error bound for the computed solution is given by
x^-x 1 x 1 ≤ κ A E 1 A 1 ,
where κ A = A-1 1 A 1 , the condition number of A with respect to the solution of the linear equations. F04CHF uses the approximation E 1=ε A 1 to estimate ERRBND. See Section 4.4 of Anderson et al. (1999) for further details.

8 Parallelism and Performance

F04CHF makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The total number of floating-point operations required to solve the equations AX=B is proportional to 13 n 3+2⁢n 2 r. The condition number estimation typically requires between four and five solves and never more than eleven solves, following the factorization.
In practice the condition number estimator is very reliable, but it can underestimate the true condition number; see Section 15.3 of Higham (2002) for further details.
Routine F04DHF is for complex symmetric matrices, and the real analogue of F04CHF is F04BHF.

10 Example

This example solves the equations
AX=B,
where A is the Hermitian indefinite matrix
A= -1.84 i+0.00 0.11-0.11 i -1.78-1.18 i 3.91-1.50 i 0.11+0.11 i -4.63 i+0.00 -1.84+0.03 i 2.21+0.21 i -1.78+1.18 i -1.84-0.03 i -8.87 i+0.00 1.58-0.90 i 3.91+1.50 i 2.21-0.21 i 1.58+0.90 i -1.36 i+0.00
and
B= 2.98-10.18 i 28.68-39.89 i -9.58+0 3.88 i -24.79-0 8.40 i -0.77-16.05 i 4.23-70.02 i 7.79+0 5.48 i -35.39+18.01 i .
An estimate of the condition number of A and an approximate error bound for the computed solutions are also printed.

10.1 Program Text

Program Text (f04chfe.f90)

10.2 Program Data

Program Data (f04chfe.d)

10.3 Program Results

Program Results (f04chfe.r)

F04 Chapter Contents
F04 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F04CJF : NAG Library, Mark 26

F04 Chapter Contents
F04 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F04CJF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F04CJF computes the solution to a complex system of linear equations AX=B, where A is an n by n complex Hermitian matrix, stored in packed format and X and B are n by r matrices. An estimate of the condition number of A and an error bound for the computed solution are also returned.

2 Specification

SUBROUTINE F04CJF ( UPLO, N, NRHS, AP, IPIV, B, LDB, RCOND, ERRBND, IFAIL)
INTEGER | N, NRHS, IPIV(N), LDB, IFAIL
REAL (KIND=nag_wp) | RCOND, ERRBND
COMPLEX (KIND=nag_wp) | AP(*), B(LDB,*)
CHARACTER(1) | UPLO

3 Description

The diagonal pivoting method is used to factor A as A=UD UH, if UPLO='U', or A=LD LH, if UPLO='L', where U (or L) is a product of permutation and unit upper (lower) triangular matrices, and D is Hermitian and block diagonal with 1 by 1 and 2 by 2 diagonal blocks. The factored form of A is then used to solve the system of equations AX=B.

4 References

Anderson E, Bai Z, Bischof C, Blackford S, Demmel J, Dongarra J J, Du Croz J J, Greenbaum A, Hammarling S, McKenney A and Sorensen D (1999) LAPACK Users' Guide (3rd Edition) SIAM, Philadelphia http://www.netlib.org/lapack/lug
Higham N J (2002) Accuracy and Stability of Numerical Algorithms (2nd Edition) SIAM, Philadelphia

5 Arguments

1:   UPLO – CHARACTER(1)Input
On entry: if UPLO='U', the upper triangle of the matrix A is stored.
If UPLO='L', the lower triangle of the matrix A is stored.
Constraint: UPLO='U' or 'L'.
2:   N – INTEGERInput
On entry: the number of linear equations n, i.e., the order of the matrix A.
Constraint: N≥0.
3:   NRHS – INTEGERInput
On entry: the number of right-hand sides r, i.e., the number of columns of the matrix B.
Constraint: NRHS≥0.
4:   AP* – COMPLEX (KIND=nag_wp) arrayInput/Output
Note: the dimension of the array AP must be at least max 1,N×N+1/2.
On entry: the n by n Hermitian matrix A, packed column-wise in a linear array. The jth column of the matrix A is stored in the array AP as follows:
More precisely,
  • if UPLO='U', the upper triangle of A must be stored with element A ij in AP i+j j-1/2 for i≤j;
  • if UPLO='L', the lower triangle of A must be stored with element A ij in AP i+2 n-jj-1/2 for i≥j.
On exit: if IFAIL≥0, the block diagonal matrix D and the multipliers used to obtain the factor U or L from the factorization A=UD UH or A=LD LH as computed by F07PRF (ZHPTRF), stored as a packed triangular matrix in the same storage format as A.
5:   IPIV N – INTEGER arrayOutput
On exit: if IFAIL≥0, details of the interchanges and the block structure of D, as determined by F07PRF (ZHPTRF).
  • If IPIV k>0, then rows and columns k and IPIV k were interchanged, and d kk is a 1 by 1 diagonal block;
  • if UPLO='U' and IPIV k=IPIV k-1<0, then rows and columns k-1 and -IPIV k were interchanged and d k-1:k,k-1:k is a 2 by 2 diagonal block;
  • if UPLO='L' and IPIV k=IPIV k+1<0, then rows and columns k+1 and -IPIV k were interchanged and d k:k+1,k:k+1 is a 2 by 2 diagonal block.
6:   B LDB* – COMPLEX (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array B must be at least max 1,NRHS.
On entry: the n by r matrix of right-hand sides B.
On exit: if IFAIL=0 or N+1, the n by r solution matrix X.
7:   LDB – INTEGERInput
On entry: the first dimension of the array B as declared in the (sub)program from which F04CJF is called.
Constraint: LDB≥max 1,N.
8:   RCOND – REAL (KIND=nag_wp)Output
On exit: if no constraints are violated, an estimate of the reciprocal of the condition number of the matrix A, computed as RCOND=1/A 1A-1 1.
9:   ERRBND – REAL (KIND=nag_wp)Output
On exit: if IFAIL=0 or N+1, an estimate of the forward error bound for a computed solution x^, such that x^-x 1/x 1≤ERRBND, where x^ is a column of the computed solution returned in the array B and x is the corresponding column of the exact solution X. If RCOND is less than machine precision, then ERRBND is returned as unity.
10:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL>0 and IFAIL≤N
Diagonal block value of the block diagonal matrix is zero. The factorization has been completed, but the solution could not be computed.
IFAIL=N+1
A solution has been computed, but RCOND is less than machine precision so that the matrix A is numerically singular.
IFAIL=-1
On entry, UPLO≠'U' or 'L': UPLO=value.
IFAIL=-2
On entry, N=value.
Constraint: N≥0.
IFAIL=-3
On entry, NRHS=value.
Constraint: NRHS≥0.
IFAIL=-7
On entry, LDB=value and N=value.
Constraint: LDB≥max 1,N.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
The real allocatable memory required is N, and the complex allocatable memory required is 2×N. Allocation failed before the solution could be computed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

The computed solution for a single right-hand side, x^, satisfies an equation of the form
A+E x^=b,
where
E 1 = O ε A 1
and ε is the machine precision. An approximate error bound for the computed solution is given by
x^-x 1 x 1 ≤ κ A E 1 A 1 ,
where κ A = A-1 1 A 1 , the condition number of A with respect to the solution of the linear equations. F04CJF uses the approximation E 1=ε A 1 to estimate ERRBND. See Section 4.4 of Anderson et al. (1999) for further details.

8 Parallelism and Performance

F04CJF makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The packed storage scheme is illustrated by the following example when n=4 and UPLO='U'. Two-dimensional storage of the Hermitian matrix A:
a 11 a 12 a 13 a 14 a 22 a 23 a 24 a 33 a 34 a 44   a ij = a-ji .
Packed storage of the upper triangle of A:
AP= a 11, a 12, a 22, a 13, a 23, a 33, a 14, a 24, a 34, a 44 .
The total number of floating-point operations required to solve the equations AX=B is proportional to 13 n 3+2⁢n 2 r. The condition number estimation typically requires between four and five solves and never more than eleven solves, following the factorization.
In practice the condition number estimator is very reliable, but it can underestimate the true condition number; see Section 15.3 of Higham (2002) for further details.
Routine F04DJF is for complex symmetric matrices, and the real analogue of F04CJF is F04BJF.

10 Example

This example solves the equations
AX=B,
where A is the Hermitian indefinite matrix
A= -1.84 i+0.00 0.11-0.11 i -1.78-1.18 i 3.91-1.50 i 0.11+0.11 i -4.63 i+0.00 -1.84+0.03 i 2.21+0.21 i -1.78+1.18 i -1.84-0.03 i -8.87 i+0.00 1.58-0.90 i 3.91+1.50 i 2.21-0.21 i 1.58+0.90 i -1.36 i+0.00
and
B= 2.98-10.18 i 28.68-39.89 i -9.58+0 3.88 i -24.79-0 8.40 i -0.77-16.05 i 4.23-70.02 i 7.79+0 5.48 i -35.39+18.01 i .
An estimate of the condition number of A and an approximate error bound for the computed solutions are also printed.

10.1 Program Text

Program Text (f04cjfe.f90)

10.2 Program Data

Program Data (f04cjfe.d)

10.3 Program Results

Program Results (f04cjfe.r)

F04 Chapter Contents
F04 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F04 Chapter Contents : NAG Library Manual, Mark 26

F04 Chapter Introduction
NAG Library Manual

NAG Library Chapter Contents

F04 – Simultaneous Linear Equations

F04 Chapter Introduction – a description of the Chapter and an overview of the algorithms available

Routine Name | Mark of Introduction | Purpose
F04ABF Example Text Example Data | 2 | nagf_linsys_withdraw_real_posdef_solve_ref Solution of real symmetric positive definite simultaneous linear equations with multiple right-hand sides using iterative refinement (Black Box) Note: this routine is scheduled for withdrawal at Mark 28, see Advice on Replacement Calls for Withdrawn/Superseded Routines for further information.
F04AEF Example Text Example Data | 2 | nagf_linsys_withdraw_real_square_solve_ref Solution of real simultaneous linear equations with multiple right-hand sides using iterative refinement (Black Box) Note: this routine is scheduled for withdrawal at Mark 28, see Advice on Replacement Calls for Withdrawn/Superseded Routines for further information.
F04AMF Example Text Example Data | 2 | nagf_linsys_real_gen_lsqsol Least squares solution of m real equations in n unknowns, rank =n, m≥n using iterative refinement (Black Box)
F04ASF Example Text Example Data | 4 | nagf_linsys_withdraw_real_posdef_solve_1rhs Solution of real symmetric positive definite simultaneous linear equations, one right-hand side using iterative refinement (Black Box) Note: this routine is scheduled for withdrawal at Mark 28, see Advice on Replacement Calls for Withdrawn/Superseded Routines for further information.
F04ATF Example Text Example Data | 4 | nagf_linsys_withdraw_real_square_solve_1rhs Solution of real simultaneous linear equations, one right-hand side using iterative refinement (Black Box) Note: this routine is scheduled for withdrawal at Mark 28, see Advice on Replacement Calls for Withdrawn/Superseded Routines for further information.
F04AXF Example Text Example Data | 7 | nagf_linsys_real_sparse_fac_solve Solution of real sparse simultaneous linear equations (coefficient matrix already factorized)
F04BAF Example Text Example Data | 21 | nagf_linsys_real_square_solve Computes the solution, estimated condition number and error-bound to a real system of linear equations
F04BBF Example Text Example Data | 21 | nagf_linsys_real_band_solve Computes the solution, estimated condition number and error-bound to a real banded system of linear equations
F04BCF Example Text Example Data | 21 | nagf_linsys_real_tridiag_solve Computes the solution, estimated condition number and error-bound to a real tridiagonal system of linear equations
F04BDF Example Text Example Data | 21 | nagf_linsys_real_posdef_solve Computes the solution, estimated condition number and error-bound to a real symmetric positive definite system of linear equations
F04BEF Example Text Example Data | 21 | nagf_linsys_real_posdef_packed_solve Computes the solution, estimated condition number and error-bound to a real symmetric positive definite system of linear equations, packed storage
F04BFF Example Text Example Data | 21 | nagf_linsys_real_posdef_band_solve Computes the solution, estimated condition number and error-bound to a real symmetric positive definite banded system of linear equations
F04BGF Example Text Example Data | 21 | nagf_linsys_real_posdef_tridiag_solve Computes the solution, estimated condition number and error-bound to a real symmetric positive definite tridiagonal system of linear equations
F04BHF Example Text Example Data | 21 | nagf_linsys_real_symm_solve Computes the solution, estimated condition number and error-bound to a real symmetric system of linear equations
F04BJF Example Text Example Data | 21 | nagf_linsys_real_symm_packed_solve Computes the solution, estimated condition number and error-bound to a real symmetric system of linear equations, packed storage
F04CAF Example Text Example Data | 21 | nagf_linsys_complex_square_solve Computes the solution, estimated condition number and error-bound to a complex system of linear equations
F04CBF Example Text Example Data | 21 | nagf_linsys_complex_band_solve Computes the solution, estimated condition number and error-bound to a complex banded system of linear equations
F04CCF Example Text Example Data | 21 | nagf_linsys_complex_tridiag_solve Computes the solution, estimated condition number and error-bound to a complex tridiagonal system of linear equations
F04CDF Example Text Example Data | 21 | nagf_linsys_complex_posdef_solve Computes the solution, estimated condition number and error-bound to a complex Hermitian positive definite system of linear equations
F04CEF Example Text Example Data | 21 | nagf_linsys_complex_posdef_packed_solve Computes the solution, estimated condition number and error-bound to a complex Hermitian positive definite system of linear equations, packed storage
F04CFF Example Text Example Data | 21 | nagf_linsys_complex_posdef_band_solve Computes the solution, estimated condition number and error-bound to a complex Hermitian positive definite banded system of linear equations
F04CGF Example Text Example Data | 21 | nagf_linsys_complex_posdef_tridiag_solve Computes the solution, estimated condition number and error-bound to a complex Hermitian positive definite tridiagonal system of linear equations
F04CHF Example Text Example Data | 21 | nagf_linsys_complex_herm_solve Computes the solution and error-bound to a complex Hermitian system of linear equations
F04CJF Example Text Example Data | 21 | nagf_linsys_complex_herm_packed_solve Computes the solution, estimated condition number and error-bound to a complex Hermitian system of linear equations, packed storage
F04DHF Example Text Example Data | 21 | nagf_linsys_complex_symm_solve Computes the solution, estimated condition number and error-bound to a complex symmetric system of linear equations
F04DJF Example Text Example Data | 21 | nagf_linsys_complex_symm_packed_solve Computes the solution, estimated condition number and error-bound to a complex symmetric system of linear equations, packed storage
F04FEF Example Text Example Data | 15 | nagf_linsys_real_toeplitz_yule Solution of the Yule–Walker equations for real symmetric positive definite Toeplitz matrix, one right-hand side
F04FFF Example Text Example Data | 15 | nagf_linsys_real_toeplitz_solve Solution of real symmetric positive definite Toeplitz system, one right-hand side
F04JGF Example Text Example Data | 8 | nagf_linsys_real_gen_solve Least squares (if rank =n) or minimal least squares (if rank <n) solution of m real equations in n unknowns, m≥n
F04LEF Example Text Example Data | 11 | nagf_linsys_real_tridiag_fac_solve Solution of real tridiagonal simultaneous linear equations (coefficient matrix already factorized by F01LEF)
F04LHF Example Text Example Data | 13 | nagf_linsys_real_blkdiag_fac_solve Solution of real almost block diagonal simultaneous linear equations (coefficient matrix already factorized by F01LHF)
F04MCF Example Text Example Data | 8 | nagf_linsys_real_posdef_vband_solve Solution of real symmetric positive definite variable-bandwidth simultaneous linear equations (coefficient matrix already factorized by F01MCF)
F04MEF Example Text Example Data | 15 | nagf_linsys_real_toeplitz_yule_update Update solution of the Yule–Walker equations for real symmetric positive definite Toeplitz matrix
F04MFF Example Text Example Data | 15 | nagf_linsys_real_toeplitz_update Update solution of real symmetric positive definite Toeplitz system
F04QAF Example Text Example Data | 11 | nagf_linsys_real_gen_sparse_lsqsol Sparse linear least squares problem, m real equations in n unknowns
F04YAF Example Text Example Data | 11 | nagf_linsys_real_gen_lsq_covmat Covariance matrix for linear least squares problems, m real equations in n unknowns
F04YDF Example Text Example Data | 24 | nagf_linsys_real_gen_norm_rcomm Norm estimation (for use in condition estimation), real rectangular matrix
F04ZDF Example Text Example Data | 24 | nagf_linsys_complex_gen_norm_rcomm Norm estimation (for use in condition estimation), complex rectangular matrix
F04 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F04DHF : NAG Library, Mark 26

F04 Chapter Contents
F04 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F04DHF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F04DHF computes the solution to a complex system of linear equations AX=B, where A is an n by n complex symmetric matrix and X and B are n by r matrices. An estimate of the condition number of A and an error bound for the computed solution are also returned.

2 Specification

SUBROUTINE F04DHF ( UPLO, N, NRHS, A, LDA, IPIV, B, LDB, RCOND, ERRBND, IFAIL)
INTEGER | N, NRHS, LDA, IPIV(N), LDB, IFAIL
REAL (KIND=nag_wp) | RCOND, ERRBND
COMPLEX (KIND=nag_wp) | A(LDA,*), B(LDB,*)
CHARACTER(1) | UPLO

3 Description

The diagonal pivoting method is used to factor A as A=UD UT, if UPLO='U', or A=LD LT, if UPLO='L', where U (or L) is a product of permutation and unit upper (lower) triangular matrices, and D is symmetric and block diagonal with 1 by 1 and 2 by 2 diagonal blocks. The factored form of A is then used to solve the system of equations AX=B.

4 References

Anderson E, Bai Z, Bischof C, Blackford S, Demmel J, Dongarra J J, Du Croz J J, Greenbaum A, Hammarling S, McKenney A and Sorensen D (1999) LAPACK Users' Guide (3rd Edition) SIAM, Philadelphia http://www.netlib.org/lapack/lug
Higham N J (2002) Accuracy and Stability of Numerical Algorithms (2nd Edition) SIAM, Philadelphia

5 Arguments

1:   UPLO – CHARACTER(1)Input
On entry: if UPLO='U', the upper triangle of the matrix A is stored.
If UPLO='L', the lower triangle of the matrix A is stored.
Constraint: UPLO='U' or 'L'.
2:   N – INTEGERInput
On entry: the number of linear equations n, i.e., the order of the matrix A.
Constraint: N≥0.
3:   NRHS – INTEGERInput
On entry: the number of right-hand sides r, i.e., the number of columns of the matrix B.
Constraint: NRHS≥0.
4:   A LDA* – COMPLEX (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array A must be at least max 1,N.
On entry: the n by n complex symmetric matrix A.
If UPLO='U', the leading N by N upper triangular part of the array A contains the upper triangular part of the matrix A, and the strictly lower triangular part of A is not referenced.
If UPLO='L', the leading N by N lower triangular part of the array A contains the lower triangular part of the matrix A, and the strictly upper triangular part of A is not referenced.
On exit: if IFAIL≥0, the block diagonal matrix D and the multipliers used to obtain the factor U or L from the factorization A=UD UT or A=LD LT as computed by F07NRF (ZSYTRF).
5:   LDA – INTEGERInput
On entry: the first dimension of the array A as declared in the (sub)program from which F04DHF is called.
Constraint: LDA≥max 1,N.
6:   IPIV N – INTEGER arrayOutput
On exit: if IFAIL≥0, details of the interchanges and the block structure of D, as determined by F07NRF (ZSYTRF).
  • If IPIV k>0, then rows and columns k and IPIV k were interchanged, and d kk is a 1 by 1 diagonal block;
  • if UPLO='U' and IPIV k=IPIV k-1<0, then rows and columns k-1 and -IPIV k were interchanged and d k-1:k,k-1:k is a 2 by 2 diagonal block;
  • if UPLO='L' and IPIV k=IPIV k+1<0, then rows and columns k+1 and -IPIV k were interchanged and d k:k+1,k:k+1 is a 2 by 2 diagonal block.
7:   B LDB* – COMPLEX (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array B must be at least max 1,NRHS.
On entry: the n by r matrix of right-hand sides B.
On exit: if IFAIL=0 or N+1, the n by r solution matrix X.
8:   LDB – INTEGERInput
On entry: the first dimension of the array B as declared in the (sub)program from which F04DHF is called.
Constraint: LDB≥max 1,N.
9:   RCOND – REAL (KIND=nag_wp)Output
On exit: if no constraints are violated, an estimate of the reciprocal of the condition number of the matrix A, computed as RCOND=1/A 1A-1 1.
10:   ERRBND – REAL (KIND=nag_wp)Output
On exit: if IFAIL=0 or N+1, an estimate of the forward error bound for a computed solution x^, such that x^-x 1/x 1≤ERRBND, where x^ is a column of the computed solution returned in the array B and x is the corresponding column of the exact solution X. If RCOND is less than machine precision, then ERRBND is returned as unity.
11:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL>0 and IFAIL≤N
Diagonal block value of the block diagonal matrix is zero. The factorization has been completed, but the solution could not be computed.
IFAIL=N+1
A solution has been computed, but RCOND is less than machine precision so that the matrix A is numerically singular.
IFAIL=-1
On entry, UPLO not one of 'U' or 'u' or 'L' or 'l': UPLO=value.
IFAIL=-2
On entry, N=value.
Constraint: N≥0.
IFAIL=-3
On entry, NRHS=value.
Constraint: NRHS≥0.
IFAIL=-5
On entry, LDA=value and N=value.
Constraint: LDA≥max 1,N.
IFAIL=-8
On entry, LDB=value and N=value.
Constraint: LDB≥max 1,N.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
The real allocatable memory required is N, and the complex allocatable memory required is max 2×N,LWORK, where LWORK is the optimum workspace required by F07NNF (ZSYSV). If this failure occurs it may be possible to solve the equations by calling the packed storage version of F04DHF, F04DJF, or by calling F07NNF (ZSYSV) directly with less than the optimum workspace (see Chapter F07).
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

The computed solution for a single right-hand side, x^, satisfies an equation of the form
A+E x^ = b ,
where
E 1 = O ε A 1
and ε is the machine precision. An approximate error bound for the computed solution is given by
x^-x 1 x 1 ≤ κ A E 1 A 1 ,
where κ A = A-1 1 A 1 , the condition number of A with respect to the solution of the linear equations. F04DHF uses the approximation E 1=ε A 1 to estimate ERRBND. See Section 4.4 of Anderson et al. (1999) for further details.

8 Parallelism and Performance

F04DHF makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The total number of floating-point operations required to solve the equations AX=B is proportional to 13 n 3+2⁢n 2 r. The condition number estimation typically requires between four and five solves and never more than eleven solves, following the factorization.
In practice the condition number estimator is very reliable, but it can underestimate the true condition number; see Section 15.3 of Higham (2002) for further details.
Routine F04CHF is for complex Hermitian matrices, and the real analogue of F04DHF is F04BHF.

10 Example

This example solves the equations
AX=B,
where A is the symmetric indefinite matrix
A= -0.56+0.12 i -1.54-2.86 i 5.32-1.59 i 3.80+0.92 i -1.54-2.86 i -2.83-0.03 i -3.52+0.58 i -7.86-2.96 i 5.32-1.59 i -3.52+0.58 i 8.86+1.81 i 5.14-0.64 i 3.80+0.92 i -7.86-2.96 i 5.14-0.64 i -0.39-0.71 i
and
B= -6.43+19.24 i -4.59-35.53 i -0.49-0 1.47 i 6.95+20.49 i -48.18+66.00 i -12.08-27.02 i -55.64+41.22 i -19.09-35.97 i .
An estimate of the condition number of A and an approximate error bound for the computed solutions are also printed.

10.1 Program Text

Program Text (f04dhfe.f90)

10.2 Program Data

Program Data (f04dhfe.d)

10.3 Program Results

Program Results (f04dhfe.r)

F04 Chapter Contents
F04 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F04DJF : NAG Library, Mark 26

F04 Chapter Contents
F04 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F04DJF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F04DJF computes the solution to a complex system of linear equations AX=B, where A is an n by n complex symmetric matrix, stored in packed format and X and B are n by r matrices. An estimate of the condition number of A and an error bound for the computed solution are also returned.

2 Specification

SUBROUTINE F04DJF ( UPLO, N, NRHS, AP, IPIV, B, LDB, RCOND, ERRBND, IFAIL)
INTEGER | N, NRHS, IPIV(N), LDB, IFAIL
REAL (KIND=nag_wp) | RCOND, ERRBND
COMPLEX (KIND=nag_wp) | AP(*), B(LDB,*)
CHARACTER(1) | UPLO

3 Description

The diagonal pivoting method is used to factor A as A=UD UT, if UPLO='U', or A=LD LT, if UPLO='L', where U (or L) is a product of permutation and unit upper (lower) triangular matrices, and D is symmetric and block diagonal with 1 by 1 and 2 by 2 diagonal blocks. The factored form of A is then used to solve the system of equations AX=B.

4 References

Anderson E, Bai Z, Bischof C, Blackford S, Demmel J, Dongarra J J, Du Croz J J, Greenbaum A, Hammarling S, McKenney A and Sorensen D (1999) LAPACK Users' Guide (3rd Edition) SIAM, Philadelphia http://www.netlib.org/lapack/lug
Higham N J (2002) Accuracy and Stability of Numerical Algorithms (2nd Edition) SIAM, Philadelphia

5 Arguments

1:   UPLO – CHARACTER(1)Input
On entry: if UPLO='U', the upper triangle of the matrix A is stored.
If UPLO='L', the lower triangle of the matrix A is stored.
Constraint: UPLO='U' or 'L'.
2:   N – INTEGERInput
On entry: the number of linear equations n, i.e., the order of the matrix A.
Constraint: N≥0.
3:   NRHS – INTEGERInput
On entry: the number of right-hand sides r, i.e., the number of columns of the matrix B.
Constraint: NRHS≥0.
4:   AP* – COMPLEX (KIND=nag_wp) arrayInput/Output
Note: the dimension of the array AP must be at least max 1,N×N+1/2.
On entry: the n by n symmetric matrix A, packed column-wise in a linear array. The jth column of the matrix A is stored in the array AP as follows:
More precisely,
  • if UPLO='U', the upper triangle of A must be stored with element A ij in AP i+j j-1/2 for i≤j;
  • if UPLO='L', the lower triangle of A must be stored with element A ij in AP i+2 n-jj-1/2 for i≥j.
On exit: if IFAIL≥0, the block diagonal matrix D and the multipliers used to obtain the factor U or L from the factorization A=UD UT or A=LD LT as computed by F07QRF (ZSPTRF), stored as a packed triangular matrix in the same storage format as A.
5:   IPIV N – INTEGER arrayOutput
On exit: if no constraints are violated, details of the interchanges and the block structure of D, as determined by F07QRF (ZSPTRF).
  • If IPIV k>0, then rows and columns k and IPIV k were interchanged, and d kk is a 1 by 1 diagonal block;
  • if UPLO='U' and IPIV k=IPIV k-1<0, then rows and columns k-1 and -IPIV k were interchanged and d k-1:k,k-1:k is a 2 by 2 diagonal block;
  • if UPLO='L' and IPIV k=IPIV k+1<0, then rows and columns k+1 and -IPIV k were interchanged and d k:k+1,k:k+1 is a 2 by 2 diagonal block.
6:   B LDB* – COMPLEX (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array B must be at least max 1,NRHS.
On entry: the n by r matrix of right-hand sides B.
On exit: if IFAIL=0 or N+1, the n by r solution matrix X.
7:   LDB – INTEGERInput
On entry: the first dimension of the array B as declared in the (sub)program from which F04DJF is called.
Constraint: LDB≥max 1,N.
8:   RCOND – REAL (KIND=nag_wp)Output
On exit: if no constraints are violated, an estimate of the reciprocal of the condition number of the matrix A, computed as RCOND=1/A 1A-1 1.
9:   ERRBND – REAL (KIND=nag_wp)Output
On exit: if IFAIL=0 or N+1, an estimate of the forward error bound for a computed solution x^, such that x^-x 1/x 1≤ERRBND, where x^ is a column of the computed solution returned in the array B and x is the corresponding column of the exact solution X. If RCOND is less than machine precision, then ERRBND is returned as unity.
10:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL>0 and IFAIL≤N
Diagonal block value of the block diagonal matrix is zero. The factorization has been completed, but the solution could not be computed.
IFAIL=N+1
A solution has been computed, but RCOND is less than machine precision so that the matrix A is numerically singular.
IFAIL=-1
On entry, UPLO≠'U' or 'L': UPLO=value.
IFAIL=-2
On entry, N=value.
Constraint: N≥0.
IFAIL=-3
On entry, NRHS=value.
Constraint: NRHS≥0.
IFAIL=-7
On entry, LDB=value and N=value.
Constraint: LDB≥max 1,N.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
The real allocatable memory required is N, and the complex allocatable memory required is 2×N. Allocation failed before the solution could be computed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

The computed solution for a single right-hand side, x^, satisfies an equation of the form
A+E x^=b,
where
E 1 = O ε A 1
and ε is the machine precision. An approximate error bound for the computed solution is given by
x^-x 1 x 1 ≤ κ A E 1 A 1 ,
where κ A = A-1 1 A 1 , the condition number of A with respect to the solution of the linear equations. F04DJF uses the approximation E 1=ε A 1 to estimate ERRBND. See Section 4.4 of Anderson et al. (1999) for further details.

8 Parallelism and Performance

F04DJF makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The packed storage scheme is illustrated by the following example when n=4 and UPLO='U'. Two-dimensional storage of the symmetric matrix A:
a 11 a 12 a 13 a 14 a 22 a 23 a 24 a 33 a 34 a 44   a ij = a ji
Packed storage of the upper triangle of A:
AP= a 11, a 12, a 22, a 13, a 23, a 33, a 14, a 24, a 34, a 44
The total number of floating-point operations required to solve the equations AX=B is proportional to 13 n 3+2⁢n 2 r. The condition number estimation typically requires between four and five solves and never more than eleven solves, following the factorization.
In practice the condition number estimator is very reliable, but it can underestimate the true condition number; see Section 15.3 of Higham (2002) for further details.
Routine F04CJF is for complex Hermitian matrices, and the real analogue of F04DJF is F04BJF.

10 Example

This example solves the equations
AX=B,
where A is the symmetric indefinite matrix
A= -0.56+0.12 i -1.54-2.86 i 5.32-1.59 i 3.80+0.92 i -1.54-2.86 i -2.83-0.03 i -3.52+0.58 i -7.86-2.96 i 5.32-1.59 i -3.52+0.58 i 8.86+1.81 i 5.14-0.64 i 3.80+0.92 i -7.86-2.96 i 5.14-0.64 i -0.39-0.71 i
and
B= -6.43+19.24 i -4.59-35.53 i -0.49-0 1.47 i 6.95+20.49 i -48.18+66.00 i -12.08-27.02 i -55.64+41.22 i -19.09-35.97 i .
An estimate of the condition number of A and an approximate error bound for the computed solutions are also printed.

10.1 Program Text

Program Text (f04djfe.f90)

10.2 Program Data

Program Data (f04djfe.d)

10.3 Program Results

Program Results (f04djfe.r)

F04 Chapter Contents
F04 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F04FEF : NAG Library, Mark 26

F04 Chapter Contents
F04 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F04FEF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F04FEF solves the Yule–Walker equations for a real symmetric positive definite Toeplitz system.

2 Specification

SUBROUTINE F04FEF ( N, T, X, WANTP, P, WANTV, V, VLAST, WORK, IFAIL)
INTEGER | N, IFAIL
REAL (KIND=nag_wp) | T(0:N), X(N), P(*), V(*), VLAST, WORK(N-1)
LOGICAL | WANTP, WANTV

3 Description

F04FEF solves the equations
Tx=-t,
where T is the n by n symmetric positive definite Toeplitz matrix
T= τ 0 τ 1 τ 2 … τ n-1 τ 1 τ 0 τ 1 … τ n-2 τ 2 τ 1 τ 0 … τ n-3 . . . . τ n-1 τ n-2 τ n-3 … τ 0
and t is the vector
tT=τ 1,τ 2…τn.
The routine uses the method of Durbin (see Durbin (1960) and Golub and Van Loan (1996)). Optionally the mean square prediction errors and/or the partial correlation coefficients for each step can be returned.

4 References

Bunch J R (1985) Stability of methods for solving Toeplitz systems of equations SIAM J. Sci. Statist. Comput. 6 349–364
Bunch J R (1987) The weak and strong stability of algorithms in numerical linear algebra Linear Algebra Appl. 88/89 49–66
Cybenko G (1980) The numerical stability of the Levinson–Durbin algorithm for Toeplitz systems of equations SIAM J. Sci. Statist. Comput. 1 303–319
Durbin J (1960) The fitting of time series models Rev. Inst. Internat. Stat. 28 233
Golub G H and Van Loan C F (1996) Matrix Computations (3rd Edition) Johns Hopkins University Press, Baltimore

5 Arguments

1:   N – INTEGERInput
On entry: the order of the Toeplitz matrix T.
Constraint: N≥0. When N=0, then an immediate return is effected.
2:   T 0:N – REAL (KIND=nag_wp) arrayInput
On entry: T 0 must contain the value τ 0 of the diagonal elements of T, and the remaining N elements of T must contain the elements of the vector t.
Constraint: T 0>0.0. Note that if this is not true, then the Toeplitz matrix cannot be positive definite.
3:   X N – REAL (KIND=nag_wp) arrayOutput
On exit: the solution vector x.
4:   WANTP – LOGICALInput
On entry: must be set to .TRUE. if the partial (auto)correlation coefficients are required, and must be set to .FALSE. otherwise.
5:   P* – REAL (KIND=nag_wp) arrayOutput
Note: the dimension of the array P must be at least max 1,N if WANTP=.TRUE., and at least 1 otherwise.
On exit: with WANTP as .TRUE., the ith element of P contains the partial (auto)correlation coefficient, or reflection coefficient, pi for the ith step. (See Section 9 and Chapter G13.) If WANTP is .FALSE., then P is not referenced. Note that in any case, xn=pn.
6:   WANTV – LOGICALInput
On entry: must be set to .TRUE. if the mean square prediction errors are required, and must be set to .FALSE. otherwise.
7:   V* – REAL (KIND=nag_wp) arrayOutput
Note: the dimension of the array V must be at least max 1,N if WANTV=.TRUE., and at least 1 otherwise.
On exit: with WANTV as .TRUE., the ith element of V contains the mean square prediction error, or predictor error variance ratio, vi, for the ith step. (See Section 9 and Chapter G13.) If WANTV is .FALSE., then V is not referenced.
8:   VLAST – REAL (KIND=nag_wp)Output
On exit: the value of vn, the mean square prediction error for the final step.
9:   WORK N-1 – REAL (KIND=nag_wp) arrayWorkspace
10:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, because for this routine the values of the output arguments may be useful even if IFAIL≠0 on exit, the recommended value is -1. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Note: F04FEF may return useful information for one or more of the following detected errors or warnings.
Errors or warnings detected by the routine:
IFAIL=-1
On entry, | N<0,
or | T 0≤0.0.
IFAIL>0
The principal minor of order (IFAIL+1) of the Toeplitz matrix is not positive definite to working accuracy. If, on exit, xIFAIL is close to unity, then the principal minor was close to being singular, and the sequence τ 0,τ 1,…,τIFAIL may be a valid sequence nevertheless. The first IFAIL elements of X return the solution of the equations
TIFAIL x=-τ 1,τ 2,…,τIFAIL T,
where TIFAIL is the IFAILth principal minor of T. Similarly, if WANTP and/or WANTV are true, then P and/or V return the first IFAIL elements of P and V respectively and VLAST returns vIFAIL. In particular if IFAIL=N, then the solution of the equations Tx=-t is returned in X, but τN is such that T N+1 would not be positive definite to working accuracy.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

The computed solution of the equations certainly satisfies
r=Tx+t,
where r 1 is approximately bounded by
r 1≤cε ∏i=1 n 1+pi-1 ,
c being a modest function of n and ε being the machine precision. This bound is almost certainly pessimistic, but it has not yet been established whether or not the method of Durbin is backward stable. If pn is close to one, then the Toeplitz matrix is probably ill-conditioned and hence only just positive definite. For further information on stability issues see Bunch (1985), Bunch (1987), Cybenko (1980) and Golub and Van Loan (1996). The following bounds on T-1 1 hold:
max 1 v n-1 , 1 ∏ i=1 n-1 1-pi ≤ T-1 1 ≤ ∏ i=1 n-1 1+pi 1-pi .
Note: vn<v n-1. The norm of T-1 may also be estimated using routine F04YDF.

8 Parallelism and Performance

F04FEF makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The number of floating-point operations used by F04FEF is approximately 2⁢n 2, independent of the values of WANTP and WANTV.
The mean square prediction error, vi, is defined as
vi=τ 0+τ 1τ 2…τ i-1 y i-1/τ 0,
where yi is the solution of the equations
Tiyi=-τ 1τ 2…τi T
and the partial correlation coefficient, pi, is defined as the ith element of yi. Note that vi=1-pi 2 v i-1.

10 Example

This example finds the solution of the Yule–Walker equations Tx=-t, where
T= 4 3 2 1 3 4 3 2 2 3 4 3 1 2 3 4   and  t= 3 2 1 0 .

10.1 Program Text

Program Text (f04fefe.f90)

10.2 Program Data

Program Data (f04fefe.d)

10.3 Program Results

Program Results (f04fefe.r)

F04 Chapter Contents
F04 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F04FFF : NAG Library, Mark 26

F04 Chapter Contents
F04 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F04FFF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F04FFF solves the equations Tx=b, where T is a real symmetric positive definite Toeplitz matrix.

2 Specification

SUBROUTINE F04FFF ( N, T, B, X, WANTP, P, WORK, IFAIL)
INTEGER | N, IFAIL
REAL (KIND=nag_wp) | T(0:*), B(*), X(N), P(*), WORK(2*(N-1))
LOGICAL | WANTP

3 Description

F04FFF solves the equations
Tx=b,
where T is the n by n symmetric positive definite Toeplitz matrix
T= τ 0 τ 1 τ 2 … τ n-1 τ 1 τ 0 τ 1 … τ n-2 τ 2 τ 1 τ 0 … τ n-3 . . . . τ n-1 τ n-2 τ n-3 … τ 0
and b is an n-element vector.
The routine uses the method of Levinson (see Levinson (1947) and Golub and Van Loan (1996)). Optionally, the reflection coefficients for each step may also be returned.

4 References

Bunch J R (1985) Stability of methods for solving Toeplitz systems of equations SIAM J. Sci. Statist. Comput. 6 349–364
Bunch J R (1987) The weak and strong stability of algorithms in numerical linear algebra Linear Algebra Appl. 88/89 49–66
Cybenko G (1980) The numerical stability of the Levinson–Durbin algorithm for Toeplitz systems of equations SIAM J. Sci. Statist. Comput. 1 303–319
Golub G H and Van Loan C F (1996) Matrix Computations (3rd Edition) Johns Hopkins University Press, Baltimore
Levinson N (1947) The Weiner RMS error criterion in filter design and prediction J. Math. Phys. 25 261–278

5 Arguments

1:   N – INTEGERInput
On entry: the order of the Toeplitz matrix T.
Constraint: N≥0. When N=0, then an immediate return is effected.
2:   T 0:* – REAL (KIND=nag_wp) arrayInput
Note: the dimension of the array T must be at least max 1,N.
On entry: T i must contain the value τi, for i=0,1,…,N-1.
Constraint: T 0>0.0. Note that if this is not true, then the Toeplitz matrix cannot be positive definite.
3:   B* – REAL (KIND=nag_wp) arrayInput
Note: the dimension of the array B must be at least max 1,N.
On entry: the right-hand side vector b.
4:   X N – REAL (KIND=nag_wp) arrayOutput
On exit: the solution vector x.
5:   WANTP – LOGICALInput
On entry: must be set to .TRUE. if the reflection coefficients are required, and must be set to .FALSE. otherwise.
6:   P* – REAL (KIND=nag_wp) arrayOutput
Note: the dimension of the array P must be at least max 1,N-1 if WANTP=.TRUE., and at least 1 otherwise.
On exit: with WANTP as .TRUE., the ith element of P contains the reflection coefficient, pi, for the ith step, for i=1,2,…,N-1. (See Section 9.) If WANTP is .FALSE., then P is not referenced.
7:   WORK 2×N-1 – REAL (KIND=nag_wp) arrayWorkspace
8:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, because for this routine the values of the output arguments may be useful even if IFAIL≠0 on exit, the recommended value is -1. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Note: F04FFF may return useful information for one or more of the following detected errors or warnings.
Errors or warnings detected by the routine:
IFAIL=-1
On entry, | N<0,
or | T 0≤0.0.
IFAIL>0
The principal minor of order IFAIL of the Toeplitz matrix is not positive definite to working accuracy. The first (IFAIL-1) elements of X return the solution of the equations
T IFAIL-1 x=b 1,b 2,…,b IFAIL-1 T,
where Tk is the kth principal minor of T.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

The computed solution of the equations certainly satisfies
r = Tx-b ,
where r is approximately bounded by
r ≤ cεC T ,
c being a modest function of n, ε being the machine precision and C T being the condition number of T with respect to inversion. This bound is almost certainly pessimistic, but it seems unlikely that the method of Levinson is backward stable, so caution should be exercised when T is ill-conditioned. The following bound on T-1 holds:
max 1 ∏ i=1 n-1 1 - pi 2 , 1 ∏ i=1 n-1 1-pi ≤ T-1 1 ≤ ∏ i=1 n-1 1+pi 1-pi .
(See Golub and Van Loan (1996).) The norm of T-1 may also be estimated using routine F04YDF. For further information on stability issues see Bunch (1985), Bunch (1987), Cybenko (1980) and Golub and Van Loan (1996).

8 Parallelism and Performance

F04FFF makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The number of floating-point operations used by F04FFF is approximately 4⁢n 2.
If yi is the solution of the equations
Tiyi=-τ 1τ 2…τi T,
then the partial correlation coefficient pi is defined as the ith element of yi.

10 Example

This example finds the solution of the equations Tx=b, where
T= 4 3 2 1 3 4 3 2 2 3 4 3 1 2 3 4   and  b= 1 1 1 1 .

10.1 Program Text

Program Text (f04fffe.f90)

10.2 Program Data

Program Data (f04fffe.d)

10.3 Program Results

Program Results (f04fffe.r)

F04 Chapter Contents
F04 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F04 Chapter Introduction : NAG Library, Mark 26

F04 Chapter Contents
NAG Library Manual

NAG Library Chapter Introduction

F04 – Simultaneous Linear Equations

▸▿ Contents

1 Scope of the Chapter
▸▿ 2 Background to the Problems
2.1 Unique Solution of Ax=b
2.2 The Least Squares Solution of Ax≃b, m>n, rank(A)=n
2.3 Rank-deficient Cases
2.4 The Rank of a Matrix
2.5 Generalized Linear Least Squares Problems
2.6 Calculating the Inverse of a Matrix
2.7 Estimating the 1-norm of a Matrix
▸▿ 3 Recommendations on Choice and Use of Available Routines
3.1 Black Box and General Purpose Routines
3.2 Systems of Linear Equations
3.3 Linear Least Squares Problems
3.4 Sparse Matrix Routines
4 Decision Trees
5 Functionality Index
6 Auxiliary Routines Associated with Library Routine Arguments
7 Routines Withdrawn or Scheduled for Withdrawal
8 References

1 Scope of the Chapter

This chapter is concerned with the solution of the matrix equation AX=B, where B may be a single vector or a matrix of multiple right-hand sides. The matrix A may be real, complex, symmetric, Hermitian, positive definite, positive definite Toeplitz or banded. It may also be rectangular, in which case a least squares solution is obtained.
Much of the functionality of this chapter has been superseded by routines from Chapters F07 and F08 (LAPACK routines) as those chapters have grown and have included driver and expert driver routines.
For a general introduction to sparse systems of equations, see the F11 Chapter Introduction, which provides routines for large sparse systems. Some routines for sparse problems are also included in this chapter; they are described in Section 3.4.

2 Background to the Problems

A set of linear equations may be written in the form
Ax=b
where the known matrix A, with real or complex coefficients, is of size m by n (m rows and n columns), the known right-hand vector b has m components (m rows and one column), and the required solution vector x has n components (n rows and one column). There may also be p vectors bi, for i=1,2,…,p, on the right-hand side and the equations may then be written as
AX=B,
the required matrix X having as its p columns the solutions of A xi=bi, for i=1,2,…,p. Some routines deal with the latter case, but for clarity only the case p=1 is discussed here.
The most common problem, the determination of the unique solution of Ax=b, occurs when m=n and A is not singular, that is rank A=n. This is discussed in Section 2.1 below. The next most common problem, discussed in Section 2.2 below, is the determination of the least squares solution of Ax≃b required when m>n and rank A=n, i.e., the determination of the vector x which minimizes the norm of the residual vector r=b-Ax. All other cases are rank deficient, and they are treated in Section 2.3.

2.1 Unique Solution of Ax=b

Most routines in this chapter solve this particular problem. The computation starts with the triangular decomposition A=PLU, where L and U are respectively lower and upper triangular matrices and P is a permutation matrix, chosen so as to ensure that the decomposition is numerically stable. The solution is then obtained by solving in succession the simpler equations
Ly = PT b Ux = y
the first by forward-substitution and the second by back-substitution.
If A is real symmetric and positive definite, U=LT, while if A is complex Hermitian and positive definite, U=LH; in both these cases P is the identity matrix (i.e., no permutations are necessary). In all other cases either U or L has unit diagonal elements.
Due to rounding errors the computed ‘solution’ x 0, say, is only an approximation to the true solution x. This approximation will sometimes be satisfactory, agreeing with x to several figures, but if the problem is ill-conditioned then x and x 0 may have few or even no figures in common, and at this stage there is no means of estimating the ‘accuracy’ of x 0.
There are three possible approaches to estimating the accuracy of a computed solution.
One way to do so, and to ‘correct’ x 0 when this is meaningful (see next paragraph), involves computing the residual vector r=b-A x 0 in extended precision arithmetic, and obtaining a correction vector d by solving PLUd=r. The new approximate solution x 0+d is usually more accurate and the correcting process is repeated until (a) further corrections are negligible or (b) they show no further decrease.
It must be emphasized that the ‘true’ solution x may not be meaningful, that is correct to all figures quoted, if the elements of A and b are known with certainty only to say p figures, where p is less than full precision. The first correction vector d will then give some useful information about the number of figures in the ‘solution’ which probably remain unchanged with respect to maximum possible uncertainties in the coefficients.
An alternative approach to assessing the accuracy of the solution is to compute or estimate the condition number of A, defined as
κ A = A . A-1 .
Roughly speaking, errors or uncertainties in A or b may be amplified in the solution by a factor κ A. Thus, for example, if the data in A and b are only accurate to 5 digits and κ A≈103, then the solution cannot be guaranteed to have more than 2 correct digits. If κ A≥105, the solution may have no meaningful digits.
To be more precise, suppose that
Ax=b  and  A+δAx+δx=b+δb.
Here δA and δb represent perturbations to the matrices A and b which cause a perturbation δx in the solution. We can define measures of the relative sizes of the perturbations in A, b and x as
ρA=δA A ,  ρb=δb b   and  ρx=δx x   respectively.
Then
ρx≤κ A 1-κ A ρA ρA+ρb
provided that κ A ρA<1. Often κ A ρA≪1 and then the bound effectively simplifies to
ρx≤κ AρA+ρb.
Hence, if we know κ A, ρA and ρb, we can compute a bound on the relative errors in the solution. Note that ρA, ρb and ρx are defined in terms of the norms of A, b and x. If A, b or x contains elements of widely differing magnitude, then ρA, ρb and ρx will be dominated by the errors in the larger elements, and ρx will give no information about the relative accuracy of smaller elements of x.
A third way to obtain useful information about the accuracy of a solution is to solve two sets of equations, one with the given coefficients, which are assumed to be known with certainty to p figures, and one with the coefficients rounded to (p-1) figures, and to count the number of figures to which the two solutions agree. In ill-conditioned problems this can be surprisingly small and even zero.

2.2 The Least Squares Solution of Ax≃b, m>n, rank A=n

The least squares solution is the vector x^ which minimizes the sum of the squares of the residuals,
S=b-A x^T b-A x^=b-A x^2 2.
The solution is obtained in two steps.
(a) Householder transformations are used to reduce A to ‘simpler form’ via the equation QA=R, where R has the appearance
R^0
with R^ a nonsingular upper triangular n by n matrix and 0 a zero matrix of shape m-n by n. Similar operations convert b to Qb=c, where
c=c 1c 2
with c 1 having n rows and c 2 having (m-n) rows.
(b) The required least squares solution is obtained by back-substitution in the equation
R^x^=c 1.
Again due to rounding errors the computed x^0 is only an approximation to the required x^, but as in Section 2.1, this can be improved by ‘iterative refinement’. The first correction d is the solution of the least squares problem
Ad=b-A x^0=r
and since the matrix A is unchanged, this computation takes less time than that of the original x^0. The process can be repeated until further corrections are (a) negligible or (b) show no further decrease.

2.3 Rank-deficient Cases

If, in the least squares problem just discussed, rank A<n, then a least squares solution exists but it is not unique. In this situation it is usual to ask for the least squares solution ‘of minimal length’, i.e., the vector x which minimizes x 2, among all those x for which b-Ax 2 is a minimum.
This can be computed from the Singular Value Decomposition (SVD) of A, in which A is factorized as
A=QD PT
where Q is an m by n matrix with orthonormal columns, P is an n by n orthogonal matrix and D is an n by n diagonal matrix. The diagonal elements of D are called the ‘singular values’ of A; they are non-negative and can be arranged in decreasing order of magnitude:
d 1≥d 2≥⋯≥dn≥0.
The columns of Q and P are called respectively the left and right singular vectors of A. If the singular values d r+1,…,dn are zero or negligible, but dr is not negligible, then the rank of A is taken to be r (see also Section 2.4) and the minimal length least squares solution of Ax≃b is given by
x^=D†QT b
where D† is the diagonal matrix with diagonal elements d 1-1,d 2-1,…,dr-1,0,…,0.
The SVD may also be used to find solutions to the homogeneous system of equations Ax=0, where A is m by n. Such solutions exist if and only if rank A<n, and are given by
x=∑i=r+1 n αipi
where the αi are arbitrary numbers and the pi are the columns of P which correspond to negligible elements of D.
The general solution to the rank-deficient least squares problem is given by x^+x, where x^ is the minimal length least squares solution and x is any solution of the homogeneous system of equations Ax=0.

2.4 The Rank of a Matrix

In theory the rank is r if n-r elements of the diagonal matrix D of the singular value decomposition are exactly zero. In practice, due to rounding and/or experimental errors, some of these elements have very small values which usually can and should be treated as zero.
For example, the following 5 by 8 matrix has rank 3 in exact arithmetic:
22 14 -1 -3 9 9 2 4 10 7 13 -2 8 1 -6 5 2 10 -1 13 1 -7 6 0 3 0 -11 -2 -2 5 5 -2 7 8 3 4 4 -1 1 2 .
On a computer with 7 decimal digits of precision the computed singular values were
3.5×101,   2.0×101,   2.0×101,   1.3×10-6,   5.5×10-7
and the rank would be correctly taken to be 3.
It is not, however, always certain that small computed singular values are really zero. With the 7 by 7 Hilbert matrix, for example, where a ij=1/i+j-1, the singular values are
1.7,  2.7×10-1,  2.1×10-2,  1.0×10-3,  2.9×10-5,  4.9×10-7,  3.5×10-9.
Here there is no clear cut-off between small (i.e., negligible) singular values and larger ones. In fact, in exact arithmetic, the matrix is known to have full rank and none of its singular values is zero. On a computer with 7 decimal digits of precision, the matrix is effectively singular, but should its rank be taken to be 6, or 5, or 4?
It is therefore impossible to give an infallible rule, but generally the rank can be taken to be the number of singular values which are neither zero nor very small compared with other singular values. For example, if there is a sharp decrease in singular values from numbers of order unity to numbers of order 10-7, then the latter will almost certainly be zero in a machine in which 7 significant decimal figures is the maximum accuracy. Similarly for a least squares problem in which the data is known to about four significant figures and the largest singular value is of order unity then a singular value of order 10-4 or less should almost certainly be regarded as zero.
It should be emphasized that rank determination and least squares solutions can be sensitive to the scaling of the matrix. If at all possible the units of measurement should be chosen so that the elements of the matrix have data errors of approximately equal magnitude.

2.5 Generalized Linear Least Squares Problems

The simple type of linear least squares problem described in Section 2.2 can be generalized in various ways.
1. Linear least squares problems with equality constraints:
find ​x​ to minimize ​S=c-Ax 2 2  subject to  Bx=d,
where A is m by n and B is p by n, with p≤n≤m+p. The equations Bx=d may be regarded as a set of equality constraints on the problem of minimizing S. Alternatively the problem may be regarded as solving an overdetermined system of equations
A B x= c d ,
where some of the equations (those involving B) are to be solved exactly, and the others (those involving A) are to be solved in a least squares sense. The problem has a unique solution on the assumptions that B has full row rank p and the matrix A B has full column rank n. (For linear least squares problems with inequality constraints, refer to Chapter E04.)
2. General Gauss–Markov linear model problems:
minimize ​y 2  subject to  d=Ax+By,
where A is m by n and B is m by p, with n≤m≤n+p. When B=I, the problem reduces to an ordinary linear least squares problem. When B is square and nonsingular, it is equivalent to a weighted linear least squares problem:
find ​x​ to minimize ​B-1 d-Ax 2.
The problem has a unique solution on the assumptions that A has full column rank n, and the matrix A,B has full row rank m.

2.6 Calculating the Inverse of a Matrix

The routines in this chapter can also be used to calculate the inverse of a square matrix A by solving the equation
AX=I
where I is the identity matrix. However, solving the equations AX=B by calculation of the inverse of the coefficient matrix A, i.e., by X=A-1 B, is definitely not recommended.
Similar remarks apply to the calculation of the pseudo-inverse of a singular or rectangular matrix.

2.7 Estimating the 1-norm of a Matrix

The 1-norm of a matrix A is defined to be:
A 1 = max 1≤j≤n ∑ i=1 m a ij (1)
Typically it is useful to calculate the condition number of a matrix with respect to the solution of linear equations, or inversion. The higher the condition number the less accuracy might be expected from a numerical computation. A condition number for the solution of linear equations is A.A-1. Since this might be a relatively expensive computation it often suffices to estimate the norm of each matrix.

3 Recommendations on Choice and Use of Available Routines

See also Section 3 in the F07 Chapter Introduction for recommendations on the choice of available routines from that chapter.

3.1 Black Box and General Purpose Routines

Most of the routines in this chapter are categorised either as Black Box routines or general purpose routines.
Black Box routines solve the equations A xi=bi, for i=1,2,…,p, in a single call with the matrix A and the right-hand sides, bi, being supplied as data. These are the simplest routines to use and are suitable when all the right-hand sides are known in advance and do not occupy too much storage.
General purpose routines, in general, require a previous call to a routine in Chapters F01 or F07 to factorize the matrix A. This factorization can then be used repeatedly to solve the equations for one or more right-hand sides which may be generated in the course of the computation. The Black Box routines simply call a factorization routine and then a general purpose routine to solve the equations.
The routine F04QAF which uses an iterative method for sparse systems of equations does not fit easily into this categorization, but is classified as a general purpose routine in the decision trees and indexes.

3.2 Systems of Linear Equations

Most of the routines in this chapter solve linear equations Ax=b when A is n by n and a unique solution is expected (see Section 2.1). The matrix A may be ‘general’ real or complex, or may have special structure or properties, e.g., it may be banded, tridiagonal, almost block-diagonal, sparse, symmetric, Hermitian, positive definite (or various combinations of these).
It must be emphasized that it is a waste of computer time and space to use an inappropriate routine, for example one for the complex case when the equations are real. It is also unsatisfactory to use the special routines for a positive definite matrix if this property is not known in advance.
Routines are given for calculating the approximate solution, that is solving the linear equations just once, and also for obtaining the accurate solution by successive iterative corrections of this first approximation using additional precision arithmetic, as described in Section 2.1. The latter, of course, are more costly in terms of time and storage, since each correction involves the solution of n sets of linear equations and since the original A and its LU decomposition must be stored together with the first and successively corrected approximations to the solution. In practice the storage requirements for the ‘corrected’ routines are about double those of the ‘approximate’ routines, though the extra computer time may not be prohibitive since the same matrix and the same LU decomposition is used in every linear equation solution.
A number of the Black Box routines in this chapter return estimates of the condition number and the forward error, along with the solution of the equations. But for those routines that do not return a condition estimate two routines are provided – F04YDF for real matrices, F04ZDF for complex matrices – which can return a cheap but reliable estimate of A-1, and hence an estimate of the condition number κ A (see Section 2.1). These routines can also be used in conjunction with most of the linear equation solving routines in Chapter F11: further advice is given in the routine documents.
Other routines for solving linear equation systems, computing inverse matrices, and estimating condition numbers can be found in Chapter F07, which contains LAPACK software.

3.3 Linear Least Squares Problems

The majority of the routines for solving linear least squares problems are to be found in Chapter F08.
For the case described in Section 2.2, when m≥n and a unique least squares solution is expected, there are two routines for a general real A, one of which (F04JGF) computes a first approximation and the other (F04AMF) computes iterative corrections. If it transpires that rank A<n, so that the least squares solution is not unique, then F04AMF takes a failure exit, but F04JGF proceeds to compute the minimal length solution by using the SVD (see below).
If A is expected to be of less than full rank then one of the routines for calculating the minimal length solution may be used.
For m≫n the use of the SVD is not significantly more expensive than the use of routines based upon the QR factorization.
Problems with linear equality constraints can be solved by F08ZAF (DGGLSE) (for real data) or by F08ZNF (ZGGLSE) (for complex data), provided that the problems are of full rank. Problems with linear inequality constraints can be solved by E04NCF/E04NCA in Chapter E04.
General Gauss–Markov linear model problems, as formulated in Section 2.5, can be solved by F08ZBF (DGGGLM) (for real data) or by F08ZPF (ZGGGLM) (for complex data).

3.4 Sparse Matrix Routines

Routines specifically for sparse matrices are appropriate only when the number of nonzero elements is very small, less than, say, 10% of the n 2 elements of A, and the matrix does not have a relatively small band width.
Chapter F11 contains routines for both the direct and iterative solution of sparse linear systems. There are two routines in Chapter F04 for solving sparse linear equations (F04AXF and F04QAF). F04AXF utilizes a factorization of the matrix A obtained from F01BRF or F01BSF, while F04QAF uses an iterative technique and requires a user-supplied function to compute matrix-vector products Ac and AT c for any given vector c.
F04QAF solves sparse least squares problems by an iterative technique, and also allows the solution of damped (regularized) least squares problems (see the routine document for details).

4 Decision Trees

The name of the routine (if any) that should be used to factorize the matrix A is given in brackets after the name of the routine for solving the equations.

Tree 1: Black Box routines for unique solution of Ax=b (Real matrix)

Is A symmetric? |  |  | Is A positive definite? |  |  | Is A a band matrix? |  |  | Is A tridiagonal? |  |  | F04BGF (see Note 1) or F07JAF or F07JBF (see Note 2)
 |  | yes |  |  | yes |  |  | yes |  |  | yes
 | no |  |  | no |  |  | no |  |  | no |
 |  |  |  |  |  |  |  |  | F04BFF (see Note 1) or F07HAF or F07HBF (see Note 2)
 |  |  |  |  |  | Is A a Toeplitz matrix? |  |  | Are the equations the Yule–Walker equations? |  |  | F04FEF
 |  |  |  |  |  |  |  | yes |  |  | yes
 |  |  |  |  |  |  | no |  |  | no |
 |  |  |  |  |  |  |  |  | F04FFF
 |  |  |  |  |  | Do you require an accurate solution using iterative refinement? |  |  | F07FBF
 |  |  |  |  |  |  |  | yes
 |  |  |  |  |  |  | no |
 |  |  |  |  |  | Is one triangle of A stored as a linear array? |  |  | F04BEF (see Note 1) or F07GAF or F07GBF (see Note 2)
 |  |  |  |  |  |  |  | yes
 |  |  |  |  |  |  | no |
 |  |  |  |  |  | F04BDF (see Note 1) or F07FAF or F07FBF (see Note 2)
 |  |  | Is one triangle of A stored as a linear array? |  |  | F04BJF (see Note 1) or F07PAF or F07PBF (see Note 2)
 |  |  |  |  | yes
 |  |  |  | no |
 |  |  | F04BHF (see Note 1) or F07MAF or F07MBF (see Note 2)
Is A a band matrix? |  |  | Is A tridiagonal? |  |  | F04BCF (see Note 1) or F07CAF or F07CBF (see Note 2)
 |  | yes |  |  | yes
 | no |  |  | no |
 |  |  | F04BBF (see Note 1) or F07BAF or F07BBF (see Note 2)
Do you require an accurate solution using iterative refinement? |  |  | F07ABF
 |  | yes
 | no |
F04BAF (see Note 1) or F07AAF or F07ABF (see Note 2)

Tree 2: Black Box routines for unique solution of Ax=b (Complex matrix)

Is A Hermitian? |  |  | Is A positive definite? |  |  | Is A a band matrix? |  |  | Is A tridiagonal? |  |  | F04CGF (see Note 1) or F07JNF or F07JPF (see Note 2)
 |  | yes |  |  | yes |  |  | yes |  |  | yes
 | no |  |  | no |  |  | no |  |  | no |
 |  |  |  |  |  |  |  |  | F04CFF (see Note 1) or F07HNF or F07HPF (see Note 2)
 |  |  |  |  |  | Is one triangle of A stored as a linear array? |  |  | F04CEF (see Note 1) or F07GNF or F07GPF (see Note 2)
 |  |  |  |  |  |  |  | yes
 |  |  |  |  |  |  | no |
 |  |  |  |  |  | F04CDF (see Note 1) or F07FNF or F07FPF (see Note 2)
 |  |  | Is one triangle of A stored as a linear array? |  |  | F04CJF (see Note 1) or F07PNF or F07PPF (see Note 2)
 |  |  |  |  | yes
 |  |  |  | no |
 |  |  | F04CHF (see Note 1) or F07MNF or F07MPF (see Note 2)
Is A symmetric? |  |  | Is one triangle of A stored as a linear array? |  |  | F04DJF (see Note 1) or F07QNF or F07QPF (see Note 2)
 |  | yes |  |  | yes
 | no |  |  | no |
 |  |  | F04DHF (see Note 1) or F07NNF or F07NPF (see Note 2)
Is A a band matrix? |  |  | Is A tridiagonal? |  |  | F04CCF (see Note 1) or F07CNF or F07CPF (see Note 2)
 |  | yes |  |  | yes
 | no |  |  | no |
 |  |  | F04CBF (see Note 1) or F07BNF or F07BPF (see Note 2)
F04CAF (see Note 1) or F07ANF or F07APF (see Note 2)

Tree 3: General purpose routines for unique solution of Ax=b (Real matrix)

Is A a sparse matrix and not banded? |  |  | Chapter F11 or F04AXF (F01BRF or F01BSF) or F04QAF
 |  | yes
 | no |
Is A symmetric? |  |  | Is A positive definite? |  |  | Is A band matrix? |  |  | Is A tridiagonal? |  |  | F07JEF (F07JDF)
 |  | yes |  |  | yes |  |  | yes |  |  | yes
 | no |  |  | no |  |  | no |  |  | no |
 |  |  |  |  |  |  |  |  | Is A variable band width? |  |  | F04MCF (F01MCF)
 |  |  |  |  |  |  |  |  |  |  | yes
 |  |  |  |  |  |  |  |  |  | no |
 |  |  |  |  |  |  |  |  | F07HEF (F07HDF)
 |  |  |  |  |  | Is A a Toeplitz matrix? |  |  | Are the equations the Yule–Walker equations? |  |  | F04MEF
 |  |  |  |  |  |  |  | yes |  |  | yes
 |  |  |  |  |  |  | no |  |  | no |
 |  |  |  |  |  |  |  |  | F04MFF
 |  |  |  |  |  | Is one triangle of A stored as a linear array? |  |  | F07GEF (F07GDF)
 |  |  |  |  |  |  |  | yes
 |  |  |  |  |  |  | no |
 |  |  |  |  |  | F07FEF (F07FDF)
 |  |  | Is one triangle of A stored as a linear array? |  |  | F07PEF (F07PDF)
 |  |  |  |  | yes
 |  |  |  | no |
 |  |  | F07MEF (F07MDF)
Is A triangular? |  |  | Is A a band matrix? |  |  | F07VEF
 |  | yes |  |  | yes
 | no |  |  | no |
 |  |  | Is A stored as a linear array? |  |  | F07UEF
 |  |  |  |  | yes
 |  |  |  | no |
 |  |  | F07TEF
Is A a band matrix? |  |  | Is A tridiagonal? |  |  | F04LEF (F01LEF) or F07CEF (F07CDF)
 |  | yes |  |  | yes
 | no |  |  | no |
 |  |  | Is A almost block diagonal? |  |  | F04LHF (F01LHF)
 |  |  |  |  | yes
 |  |  |  | no |
 |  |  | F07BEF (F07BDF)
F07AEF (F07ADF)

Tree 4: General purpose routines for unique solution of Ax=b (Complex matrix)

Is A a sparse matrix and not banded? |  |  | Chapter F11
 |  | yes
 | no |
Is A Hermitian? |  |  | Is A positive definite? |  |  | Is A a band matrix? |  |  | Is A tridiagonal? |  |  | F07JSF (F07JRF)
 |  | yes |  |  | yes |  |  | yes |  |  | yes
 | no |  |  | no |  |  | no |  |  | no |
 |  |  |  |  |  |  |  |  | F07HSF (F07HRF)
 |  |  |  |  |  | Is one triangle of A stored as a linear array? |  |  | F07GSF (F07GRF)
 |  |  |  |  |  |  |  | yes
 |  |  |  |  |  |  | no |
 |  |  |  |  |  | F07FSF (F07FRF)
 |  |  | Is one triangle of A stored as a linear array? |  |  | F07PSF (F07PRF)
 |  |  |  |  | yes
 |  |  |  | no |
 |  |  | F07MSF (F07MRF)
Is A symmetric? |  |  | Is one triangle of A stored as a linear array? |  |  | F07QSF (F07QRF)
 |  | yes |  |  | yes
 | no |  |  | no |
 |  |  | F07NSF (F07NRF)
Is A triangular? |  |  | Is A a band matrix? |  |  | F07VSF
 |  | yes |  |  | yes
 | no |  |  | no |
 |  |  | Is A stored as a linear array? |  |  | F07USF
 |  |  |  |  | yes
 |  |  |  | no |
 |  |  | F07TSF
Is A a band matrix? |  |  | Is A tridiagonal? |  |  | F07CSF (F07CRF)
 |  | yes |  |  | yes
 | no |  |  | no |
 |  |  | F07BSF (F07BRF)
F07ASF (F07ARF)

Tree 5: General purpose routines for least squares and homogeneous equations (without constraints)

Is the problem Ax=0? |  |  | F08KAF
 |  | yes
 | no |
Is A sparse? |  |  | F04QAF
 |  | yes
 | no |
Is rank A=n? |  |  | Are storage and time more important than accuracy? |  |  | F04JGF
 |  | yes |  |  | yes
 | no |  |  | no |
 |  |  | F04AMF
Is m>n? |  |  | F04JGF or F08KAF
 |  | yes
 | no |
F08KAF
Note: there are also routines in Chapter F08 for solving least squares problems.
Note 1: also returns an estimate of the condition number and the forward error.
Note 2: also returns an estimate of the condition number, the forward error and the backward error. Requires additional workspace.

5 Functionality Index

Black Box routines, Ax = b,
complex general band matrix F04CBF
complex general matrix F04CAF
complex general tridiagonal matrix F04CCF
complex Hermitian matrix,
packed matrix format F04CJF
standard matrix format F04CHF
complex Hermitian positive definite band matrix F04CFF
complex Hermitian positive definite matrix,
packed matrix format F04CEF
standard matrix format F04CDF
complex Hermitian positive definite tridiagonal matrix F04CGF
complex symmetric matrix,
packed matrix format F04DJF
standard matrix format F04DHF
real general band matrix F04BBF
real general matrix,
multiple right-hand sides, standard precision F04BAF
real general tridiagonal matrix F04BCF
real symmetric matrix,
packed matrix format F04BJF
standard matrix format F04BHF
real symmetric positive definite band matrix F04BFF
real symmetric positive definite matrix,
multiple right-hand sides, standard precision F04BDF
packed matrix format F04BEF
real symmetric positive definite Toeplitz matrix,
general right-hand side F04FFF
Yule–Walker equations F04FEF
real symmetric positive definite tridiagonal matrix F04BGF
General Purpose routines, Ax = b,
real almost block-diagonal matrix F04LHF
real band symmetric positive definite matrix, variable bandwidth F04MCF
real sparse matrix,
direct method F04AXF
iterative method F04QAF
real symmetric positive definite Toeplitz matrix,
general right-hand side, update solution F04MFF
Yule–Walker equations, update solution F04MEF
real tridiagonal matrix F04LEF
Least squares and Homogeneous Equations,
real m by n matrix,
m ≥ n, rank = n or minimal solution F04JGF
rank = n, iterative refinement F04AMF
real sparse matrix F04QAF
Service Routines,
complex rectangular matrix,
norm and condition number estimation F04ZDF
real matrix,
covariance matrix for linear least squares problems F04YAF
real rectangular matrix,
norm and condition number estimation F04YDF

6 Auxiliary Routines Associated with Library Routine Arguments

None.

7 Routines Withdrawn or Scheduled for Withdrawal

The following lists all those routines that have been withdrawn since Mark 19 of the Library or are scheduled for withdrawal at one of the next two marks.
Withdrawn Routine | Mark of Withdrawal | Replacement Routine(s)
F04AAF | 23 | F07AAF (DGESV)
F04ABF | 28 | F07FBF (DPOSVX)
F04ACF | 23 | F07HAF (DPBSV)
F04ADF | 23 | F07ANF (ZGESV)
F04AEF | 28 | F07ABF (DGESVX)
F04AFF | 25 | No replacement routine required
F04AGF | 25 | No replacement routine required
F04AHF | 25 | No replacement routine required
F04AJF | 25 | No replacement routine required
F04ARF | 23 | F07AAF (DGESV)
F04ASF | 28 | F07FBF (DPOSVX)
F04ATF | 28 | F07ABF (DGESVX)
F04EAF | 23 | F07CAF (DGTSV)
F04FAF | 23 | F07JAF (DPTSV), or F07JDF (DPTTRF) and F07JEF (DPTTRS)
F04JAF | 23 | F08KAF (DGELSS)
F04JDF | 23 | F08KAF (DGELSS)
F04JLF | 23 | F08ZBF (DGGGLM)
F04JMF | 23 | F08ZAF (DGGLSE)
F04KLF | 23 | F08ZPF (ZGGGLM)
F04KMF | 23 | F08ZNF (ZGGLSE)
F04MAF | 19 | F11JCF
F04MBF | 19 | F11GDF, F11GEF and F11GFF (or F11JCF or F11JEF)
F04YCF | 26 | F04YDF
F04ZCF | 26 | F04ZDF

8 References

Golub G H and Van Loan C F (1996) Matrix Computations (3rd Edition) Johns Hopkins University Press, Baltimore
Lawson C L and Hanson R J (1974) Solving Least Squares Problems Prentice–Hall
Wilkinson J H and Reinsch C (1971) Handbook for Automatic Computation II, Linear Algebra Springer–Verlag
F04 Chapter Contents
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F04JGF : NAG Library, Mark 26

F04 Chapter Contents
F04 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F04JGF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F04JGF finds the solution of a linear least squares problem, Ax=b, where A is a real m by n m≥n matrix and b is an m element vector. If the matrix of observations is not of full rank, then the minimal least squares solution is returned.

2 Specification

SUBROUTINE F04JGF ( M, N, A, LDA, B, TOL, SVD, SIGMA, IRANK, WORK, LWORK, IFAIL)
INTEGER | M, N, LDA, IRANK, LWORK, IFAIL
REAL (KIND=nag_wp) | A(LDA,N), B(M), TOL, SIGMA, WORK(LWORK)
LOGICAL | SVD

3 Description

The minimal least squares solution of the problem Ax=b is the vector x of minimum (Euclidean) length which minimizes the length of the residual vector r=b-Ax.
The real m by n m≥n matrix A is factorized as
A=Q R 0
where Q is an m by m orthogonal matrix and R is an n by n upper triangular matrix. If R is of full rank, then the least squares solution is given by
x= R-1 0 QT b.
If R is not of full rank, then the singular value decomposition of R is obtained so that R is factorized as
R=UD VT,
where U and V are n by n orthogonal matrices and D is the n by n diagonal matrix
D=diag σ 1,σ 2,…,σn,
with σ 1≥σ 2≥…≥σn≥0, these being the singular values of A. If the singular values σ k+1,…,σn are negligible, but σk is not negligible, relative to the data errors in A, then the rank of A is taken to be k and the minimal least squares solution is given by
x=V S-1 0 0 0 UT 0 0 I QT b,
where S=diag σ 1,σ 2,…,σk.
The routine also returns the value of the standard error
σ = rT r m-k , if ​m>k, = 0, if ​m=k,
rT r being the residual sum of squares and k the rank of A.

4 References

Lawson C L and Hanson R J (1974) Solving Least Squares Problems Prentice–Hall

5 Arguments

1:   M – INTEGERInput
On entry: m, the number of rows of A.
Constraint: M≥N.
2:   N – INTEGERInput
On entry: n, the number of columns of A.
Constraint: 1≤N≤M.
3:   A LDAN – REAL (KIND=nag_wp) arrayInput/Output
On entry: the m by n matrix A.
On exit: if SVD is returned as .FALSE., A is overwritten by details of the QR factorization of A.
If SVD is returned as .TRUE., the first n rows of A are overwritten by the right-hand singular vectors, stored by rows; and the remaining rows of the array are used as workspace.
4:   LDA – INTEGERInput
On entry: the first dimension of the array A as declared in the (sub)program from which F04JGF is called.
Constraint: LDA≥M.
5:   B M – REAL (KIND=nag_wp) arrayInput/Output
On entry: the right-hand side vector b.
On exit: the first n elements of B contain the minimal least squares solution vector x. The remaining m-n elements are used for workspace.
6:   TOL – REAL (KIND=nag_wp)Input
On entry: a relative tolerance to be used to determine the rank of A. TOL should be chosen as approximately the largest relative error in the elements of A. For example, if the elements of A are correct to about 4 significant figures then TOL should be set to about 5×10-4. See Section 9 for a description of how TOL is used to determine rank. If TOL is outside the range ε,1.0, where ε is the machine precision, then the value ε is used in place of TOL. For most problems this is unreasonably small.
7:   SVD – LOGICALOutput
On exit: is returned as .FALSE. if the least squares solution has been obtained from the QR factorization of A. In this case A is of full rank. SVD is returned as .TRUE. if the least squares solution has been obtained from the singular value decomposition of A.
8:   SIGMA – REAL (KIND=nag_wp)Output
On exit: the standard error, i.e., the value rT r/m-k when m>k, and the value zero when m=k. Here r is the residual vector b-Ax and k is the rank of A.
9:   IRANK – INTEGEROutput
On exit: k, the rank of the matrix A. It should be noted that it is possible for IRANK to be returned as n and SVD to be returned as .TRUE.. This means that the matrix R only just failed the test for nonsingularity.
10:   WORK LWORK – REAL (KIND=nag_wp) arrayOutput
On exit: if SVD is returned as .FALSE., then the first n elements of WORK contain information on the QR factorization of A (see argument A above), and WORK n+1 contains the condition number R ER-1 E of the upper triangular matrix R.
If SVD is returned as .TRUE., then the first n elements of WORK contain the singular values of A arranged in descending order and WORK n+1 contains the total number of iterations taken by the QR algorithm. The rest of WORK is used as workspace.
11:   LWORK – INTEGERInput
On entry: the dimension of the array WORK as declared in the (sub)program from which F04JGF is called.
Constraint: LWORK≥4×N.
12:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, LDA=value and M=value.
Constraint: LDA≥M.
On entry, LWORK is too small. Minimum size required: value.
On entry, M=value and N=value.
Constraint: M≥N.
On entry, N=value.
Constraint: N≥1.
IFAIL=2
The QR algorithm has failed to converge to the singular values in 50×N iterations. This failure can only happen when the singular value decomposition is employed, but even then it is not likely to occur.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

The computed factors Q, R, U, D and VT satisfy the relations
Q R 0 =A+E,
Q U 0 0 I D 0 VT=A+F,
where
E 2≤c 1 ε A 2,
F 2≤c 2 ε A 2,
ε being the machine precision, and c 1 and c 2 being modest functions of m and n. Note that A 2=σ 1.
For a fuller discussion, covering the accuracy of the solution x see Lawson and Hanson (1974), especially pages 50 and 95.

8 Parallelism and Performance

F04JGF is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
F04JGF makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

If the least squares solution is obtained from the QR factorization then the time taken by the routine is approximately proportional to n 2 3 m-n. If the least squares solution is obtained from the singular value decomposition then the time taken is approximately proportional to n 2 3 m+19 n. The approximate proportionality factor is the same in each case.
This routine is column biased and so is suitable for use in paged environments.
Following the QR factorization of A the condition number
c R=R E R-1 E
is determined and if c R is such that
c R×TOL>1.0
then R is regarded as singular and the singular values of A are computed. If this test is not satisfied, R is regarded as nonsingular and the rank of A is set to n. When the singular values are computed the rank of A, say k, is returned as the largest integer such that
σk>TOL×σ 1,
unless σ 1=0 in which case k is returned as zero. That is, singular values which satisfy σi≤TOL×σ 1 are regarded as negligible because relative perturbations of order TOL can make such singular values zero.

10 Example

This example obtains a least squares solution for r=b-Ax, where
A= 0.05 0.05 0.25 -0.25 0.25 0.25 0.05 -0.05 0.35 0.35 1.75 -1.75 1.75 1.75 0.35 -0.35 0.30 -0.30 0.30 0.30 0.40 -0.40 0.40 0.40 ,  b= 1 2 3 4 5 6
and the value TOL is to be taken as 5×10-4.

10.1 Program Text

Program Text (f04jgfe.f90)

10.2 Program Data

Program Data (f04jgfe.d)

10.3 Program Results

Program Results (f04jgfe.r)

F04 Chapter Contents
F04 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F04LEF : NAG Library, Mark 26

F04 Chapter Contents
F04 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F04LEF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F04LEF solves a system of tridiagonal equations following the factorization by F01LEF. This routine is intended for applications such as inverse iteration as well as straightforward linear equation applications.

2 Specification

SUBROUTINE F04LEF ( JOB, N, A, B, C, D, IPIV, Y, TOL, IFAIL)
INTEGER | JOB, N, IPIV(N), IFAIL
REAL (KIND=nag_wp) | A(N), B(N), C(N), D(N), Y(N), TOL

3 Description

Following the factorization of the n by n tridiagonal matrix T-λI as
T-λI=PLU
by F01LEF, F04LEF may be used to solve any of the equations
T-λ I x=y,   T-λ I T x=y,   Ux=y
for x, the choice of equation being controlled by the argument JOB. In each case there is an option to perturb zero or very small diagonal elements of U, this option being intended for use in applications such as inverse iteration.

4 References

Wilkinson J H (1965) The Algebraic Eigenvalue Problem Oxford University Press, Oxford
Wilkinson J H and Reinsch C (1971) Handbook for Automatic Computation II, Linear Algebra Springer–Verlag

5 Arguments

1:   JOB – INTEGERInput
On entry: must specify the equations to be solved.
JOB=1
The equations T-λI x=y are to be solved, but diagonal elements of U are not to be perturbed.
JOB=-1
The equations T-λI x=y are to be solved and, if overflow would otherwise occur, diagonal elements of U are to be perturbed. See argument TOL.
JOB=2
The equations T-λI T x=y are to be solved, but diagonal elements of U are not to be perturbed.
JOB=-2
The equations T-λI T x=y are to be solved and, if overflow would otherwise occur, diagonal elements of U are to be perturbed. See argument TOL.
JOB=3
The equations Ux=y are to be solved, but diagonal elements of U are not to be perturbed.
JOB=-3
The equations Ux=y are to be solved and, if overflow would otherwise occur, diagonal elements of U are to be perturbed. See argument TOL.
2:   N – INTEGERInput
On entry: n, the order of the matrix T.
Constraint: N≥1.
3:   A N – REAL (KIND=nag_wp) arrayInput
On entry: the diagonal elements of U as returned by F04LEF.
4:   B N – REAL (KIND=nag_wp) arrayInput
On entry: the elements of the first superdiagonal of U as returned by F04LEF.
5:   C N – REAL (KIND=nag_wp) arrayInput
On entry: the subdiagonal elements of L as returned by F04LEF.
6:   D N – REAL (KIND=nag_wp) arrayInput
On entry: the elements of the second superdiagonal of U as returned by F04LEF.
7:   IPIV N – INTEGER arrayInput
On entry: details of the matrix P as returned by F01LEF.
8:   Y N – REAL (KIND=nag_wp) arrayInput/Output
On entry: the right-hand side vector y.
On exit: Y is overwritten by the solution vector x.
9:   TOL – REAL (KIND=nag_wp)Input/Output
On entry: the minimum perturbation to be made to very small diagonal elements of U. TOL is only referenced when JOB is negative. TOL should normally be chosen as about ε U, where ε is the machine precision, but if TOL is supplied as non-positive, then it is reset to ε max u ij.
On exit: if on entry TOL is non-positive, it is reset as just described. Otherwise TOL is unchanged.
10:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, | N<1,
or | JOB=0,
or | JOB<-3 or JOB>3.
IFAIL>1
Overflow would occur when computing the (IFAIL-1)th element of the solution vector x. This can only occur when JOB is supplied as positive and either means that a diagonal element of U is very small or that elements of the right-hand side vector y are very large.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

The computed solution of the equations T-λI x=y, say x-, will satisfy an equation of the form
T-λI+E x-=y,
where E can be expected to satisfy a bound of the form
E≤αε T-λI,
α being a modest constant and ε being the machine precision. The computed solution of the equations T-λI T x=y and Ux=y will satisfy similar results. The above result implies that the relative error in x- satisfies
x--x x- ≤c T-λI αε,
where c T-λI is the condition number of T-λI with respect to inversion. Thus if T-λI is nearly singular, x- can be expected to have a large relative error. Note that F01LEF incorporates a test for near singularity.

8 Parallelism and Performance

F04LEF is not threaded in any implementation.

9 Further Comments

The time taken by F04LEF is approximately proportional to n.
If you have single systems of tridiagonal equations to solve you are advised that F07CAF (DGTSV) requires less storage and will normally be faster than the combination of F01LEF and F04LEF, but F07CAF (DGTSV) does not incorporate a test for near singularity.

10 Example

This example solves the two sets of tridiagonal equations
Tx=y  and  TT x=y
where
T= 3.0 2.1 0 0 0 3.4 2.3 -1.0 0 0 0 3.6 -5.0 1.9 0 0 0 7.0 -0.9 8.0 0 0 0 -6.0 7.1   and   y = 2.7 -0.5 2.6 0.6 2.7 .
The example program first calls F01LEF to factorize T and then two calls are made to F04LEF, one to solve Tx=y and the second to solve TT x=y.

10.1 Program Text

Program Text (f04lefe.f90)

10.2 Program Data

Program Data (f04lefe.d)

10.3 Program Results

Program Results (f04lefe.r)

F04 Chapter Contents
F04 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F04LHF : NAG Library, Mark 26

F04 Chapter Contents
F04 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F04LHF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F04LHF calculates the approximate solution of a set of real linear equations with multiple right-hand sides, AX=B or AT X=B, where A is an almost block-diagonal matrix which has been factorized by F01LHF.

2 Specification

SUBROUTINE F04LHF ( TRANS, N, NBLOKS, BLKSTR, A, LENA, PIVOT, B, LDB, IR, IFAIL)
INTEGER | N, NBLOKS, BLKSTR(3,NBLOKS), LENA, PIVOT(N), LDB, IR, IFAIL
REAL (KIND=nag_wp) | A(LENA), B(LDB,IR)
CHARACTER(1) | TRANS

3 Description

F04LHF solves a set of real linear equations AX=B or AT X=B, where A is almost block-diagonal. A must first be factorized by F01LHF. F04LHF then computes X by forward and backward substitution over the blocks.

4 References

Diaz J C, Fairweather G and Keast P (1983) Fortran packages for solving certain almost block diagonal linear systems by modified alternate row and column elimination ACM Trans. Math. Software 9 358–375

5 Arguments

1:   TRANS – CHARACTER(1)Input
On entry: specifies the equations to be solved.
TRANS='N'
Solve AX=B.
TRANS='T'
Solve AT X=B.
Constraint: TRANS='N' or 'T'.
2:   N – INTEGERInput
On entry: n, the order of the matrix A.
Constraint: N>0.
3:   NBLOKS – INTEGERInput
On entry: the total number of blocks of the matrix A, as supplied to F04LHF.
Constraint: 0<NBLOKS≤N.
4:   BLKSTR 3 NBLOKS – INTEGER arrayInput
On entry: information which describes the block structure of A, as supplied to F04LHF.
5:   A LENA – REAL (KIND=nag_wp) arrayInput
On entry: the elements in the factorization of A, as returned by F04LHF.
6:   LENA – INTEGERInput
On entry: the dimension of the array A as declared in the (sub)program from which F04LHF is called.
Constraint: LENA≥∑k=1 NBLOKS BLKSTR 1 k × BLKSTR 2 k .
7:   PIVOT N – INTEGER arrayInput
On entry: details of the interchanges in the factorization, as returned by F04LHF.
8:   B LDBIR – REAL (KIND=nag_wp) arrayInput/Output
On entry: the n by r right-hand side matrix B.
On exit: B is overwritten by the n by r solution matrix X.
9:   LDB – INTEGERInput
On entry: the first dimension of the array B as declared in the (sub)program from which F04LHF is called.
Constraint: LDB≥N.
10:   IR – INTEGERInput
On entry: r, the number of right-hand sides.
Constraint: IR>0.
11:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, | N<1,
or | NBLOKS<1,
or | IR<1,
or | LDB<N,
or | N<NBLOKS,
or | LENA is too small,
or | illegal values detected in BLKSTR,
or | TRANS≠'N' or 'T'.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

The accuracy of the computed solution depends on the conditioning of the original matrix A.

8 Parallelism and Performance

F04LHF makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

None.

10 Example

This example solves the set of linear equations Ax=b where
A= -1.00 -0.98 -0.79 -0.15 -1.00 -0.25 -0.87 0.35 0.78 0.31 -0.85 0.89 -0.69 -0.98 -0.76 -0.82 0.12 -0.01 0.75 0.32 -1.00 -0.53 -0.83 -0.98 -0.58 0.04 0.87 0.38 -1.00 -0.21 -0.93 -0.84 0.37 -0.94 -0.96 -1.00 -0.99 -0.91 -0.28 0.90 0.78 -0.93 -0.76 0.48 -0.87 -0.14 -1.00 -0.59 -0.99 0.21 -0.73 -0.48 -0.93 -0.91 0.10 -0.89 -0.68 -0.09 -0.58 -0.21 0.85 -0.39 0.79 -0.71 0.39 -0.99 -0.12 -0.75 0.17 -1.37 1.29 -1.59 1.10 -1.63 -1.01 -0.27 0.08 0.61 0.54 -0.41 0.16 -0.46 -0.67 0.56 -0.99 0.16 -0.16 0.98 -0.24 -0.41 0.40 -0.93 0.70 0.43 0.71 -0.97 -0.60 -0.30 0.18 -0.47 -0.98 -0.73 0.07 0.04 -0.25 -0.92 -0.52 -0.46 -0.58 0.89 -0.94 -0.54 -1.00 -0.36
and
b= -2.92 -1.17 -1.30 -1.17 -2.10 -4.51 -1.71 -4.59 -4.19 -0.93 -3.31 0.52 -0.12 -0.05 -0.98 -2.07 -2.73 -1.95
The exact solution is
x=1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1 T.

10.1 Program Text

Program Text (f04lhfe.f90)

10.2 Program Data

Program Data (f04lhfe.d)

10.3 Program Results

Program Results (f04lhfe.r)

F04 Chapter Contents
F04 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F04MCF : NAG Library, Mark 26

F04 Chapter Contents
F04 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F04MCF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F04MCF computes the approximate solution of a system of real linear equations with multiple right-hand sides, AX=B, where A is a symmetric positive definite variable-bandwidth matrix, which has previously been factorized by F01MCF. Related systems may also be solved.

2 Specification

SUBROUTINE F04MCF ( N, AL, LAL, D, NROW, IR, B, LDB, ISELCT, X, LDX, IFAIL)
INTEGER | N, LAL, NROW(N), IR, LDB, ISELCT, LDX, IFAIL
REAL (KIND=nag_wp) | AL(LAL), D(*), B(LDB,IR), X(LDX,IR)

3 Description

The normal use of this routine is the solution of the systems AX=B, following a call of F01MCF to determine the Cholesky factorization A=LD LT of the symmetric positive definite variable-bandwidth matrix A.
However, the routine may be used to solve any one of the following systems of linear algebraic equations:
1. | LD LT X=B (usual system),
2. | LDX=B (lower triangular system),
3. | D LT X=B (upper triangular system),
4. | L LT X=B
5. | LX=B (unit lower triangular system),
6. | LT X=B (unit upper triangular system).
L denotes a unit lower triangular variable-bandwidth matrix of order n, D a diagonal matrix of order n, and B a set of right-hand sides.
The matrix L is represented by the elements lying within its envelope, i.e., between the first nonzero of each row and the diagonal (see Section 10 for an example). The width NROW i of the ith row is the number of elements between the first nonzero element and the element on the diagonal inclusive.

4 References

Wilkinson J H and Reinsch C (1971) Handbook for Automatic Computation II, Linear Algebra Springer–Verlag

5 Arguments

1:   N – INTEGERInput
On entry: n, the order of the matrix L.
Constraint: N≥1.
2:   AL LAL – REAL (KIND=nag_wp) arrayInput
On entry: the elements within the envelope of the lower triangular matrix L, taken in row by row order, as returned by F01MCF. The unit diagonal elements of L must be stored explicitly.
3:   LAL – INTEGERInput
On entry: the dimension of the array AL as declared in the (sub)program from which F04MCF is called.
Constraint: LAL≥NROW 1+NROW 2+…+NROW n.
4:   D* – REAL (KIND=nag_wp) arrayInput
Note: the dimension of the array D must be at least 1 if ISELCT≥4, and at least N otherwise.
On entry: the diagonal elements of the diagonal matrix D. D is not referenced if ISELCT≥4.
5:   NROW N – INTEGER arrayInput
On entry: NROW i must contain the width of row i of L, i.e., the number of elements between the first (leftmost) nonzero element and the element on the diagonal, inclusive.
Constraint: 1≤NROW i≤i.
6:   IR – INTEGERInput
On entry: r, the number of right-hand sides.
Constraint: IR≥1.
7:   B LDBIR – REAL (KIND=nag_wp) arrayInput
On entry: the n by r right-hand side matrix B. See also Section 9.
8:   LDB – INTEGERInput
On entry: the first dimension of the array B as declared in the (sub)program from which F04MCF is called.
Constraint: LDB≥N.
9:   ISELCT – INTEGERInput
On entry: must specify the type of system to be solved, as follows:
ISELCT=1
Solve LD LT X=B.
ISELCT=2
Solve LDX=B.
ISELCT=3
Solve D LT X=B.
ISELCT=4
Solve L LT X=B.
ISELCT=5
Solve LX=B.
ISELCT=6
Solve LT X=B.
Constraint: ISELCT=1, 2, 3, 4, 5 or 6.
10:   X LDXIR – REAL (KIND=nag_wp) arrayOutput
On exit: the n by r solution matrix X. See also Section 9.
11:   LDX – INTEGERInput
On entry: the first dimension of the array X as declared in the (sub)program from which F04MCF is called.
Constraint: LDX≥N.
12:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, | N<1,
or | for some i, NROW i<1 or NROW i>i,
or | LAL<NROW 1+NROW 2+⋯+ NROW N .
IFAIL=2
On entry, | IR<1,
or | LDB<N,
or | LDX<N.
IFAIL=3
On entry, | ISELCT<1,
or | ISELCT>6.
IFAIL=4
The diagonal matrix D is singular, i.e., at least one of the elements of D is zero. This can only occur if ISELCT≤3.
IFAIL=5
At least one of the diagonal elements of L is not equal to unity.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

The usual backward error analysis of the solution of triangular system applies: each computed solution vector is exact for slightly perturbed matrices L and D, as appropriate (see pages 25–27 and 54–55 of Wilkinson and Reinsch (1971)).

8 Parallelism and Performance

F04MCF is not threaded in any implementation.

9 Further Comments

The time taken by F04MCF is approximately proportional to pr, where p=NROW 1+NROW 2+⋯+NROW n.
Unless otherwise stated in the Users' Note for your implementation, the routine may be called with the same actual array supplied for the arguments B and X, in which case the solution matrix will overwrite the right-hand side matrix. However this is not standard Fortran and may not work in all implementations.

10 Example

This example solves the system of equations AX=B, where
A= 1 2 0 0 5 0 2 5 3 0 14 0 0 3 13 0 18 0 0 0 0 16 8 24 5 14 18 8 55 17 0 0 0 24 17 77   and  B= 6 -10 15 -21 11 -3 0 24 51 -39 46 67
Here A is symmetric and positive definite and must first be factorized by F01MCF.

10.1 Program Text

Program Text (f04mcfe.f90)

10.2 Program Data

Program Data (f04mcfe.d)

10.3 Program Results

Program Results (f04mcfe.r)

F04 Chapter Contents
F04 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F04MEF : NAG Library, Mark 26

F04 Chapter Contents
F04 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F04MEF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F04MEF updates the solution to the Yule–Walker equations for a real symmetric positive definite Toeplitz system.

2 Specification

SUBROUTINE F04MEF ( N, T, X, V, WORK, IFAIL)
INTEGER | N, IFAIL
REAL (KIND=nag_wp) | T(0:N), X(*), V, WORK(N-1)

3 Description

F04MEF solves the equations
Tnxn=-tn,
where Tn is the n by n symmetric positive definite Toeplitz matrix
Tn= τ 0 τ 1 τ 2 … τ n-1 τ 1 τ 0 τ 1 … τ n-2 τ 2 τ 1 τ 0 … τ n-3 . . . . τ n-1 τ n-2 τ n-3 … τ 0
and tn is the vector
tnT =τ 1τ 2…τn,
given the solution of the equations
T n- 1x n- 1=-t n- 1.
The routine will normally be used to successively solve the equations
Tkxk=-tk,  k=1,2,…,n.
If it is desired to solve the equations for a single value of n, then routine F04FEF may be called. This routine uses the method of Durbin (see Durbin (1960) and Golub and Van Loan (1996)).

4 References

Bunch J R (1985) Stability of methods for solving Toeplitz systems of equations SIAM J. Sci. Statist. Comput. 6 349–364
Bunch J R (1987) The weak and strong stability of algorithms in numerical linear algebra Linear Algebra Appl. 88/89 49–66
Cybenko G (1980) The numerical stability of the Levinson–Durbin algorithm for Toeplitz systems of equations SIAM J. Sci. Statist. Comput. 1 303–319
Durbin J (1960) The fitting of time series models Rev. Inst. Internat. Stat. 28 233
Golub G H and Van Loan C F (1996) Matrix Computations (3rd Edition) Johns Hopkins University Press, Baltimore

5 Arguments

1:   N – INTEGERInput
On entry: the order of the Toeplitz matrix T.
Constraint: N≥0. When N=0, then an immediate return is effected.
2:   T 0:N – REAL (KIND=nag_wp) arrayInput
On entry: T 0 must contain the value τ 0 of the diagonal elements of T, and the remaining N elements of T must contain the elements of the vector tn.
Constraint: T 0>0.0. Note that if this is not true, then the Toeplitz matrix cannot be positive definite.
3:   X* – REAL (KIND=nag_wp) arrayInput/Output
Note: the dimension of the array X must be at least max 1,N.
On entry: with N>1 the (n-1) elements of the solution vector x n-1 as returned by a previous call to F04MEF. The element X N need not be specified.
Constraint: X N-1<1.0. Note that this is the partial (auto)correlation coefficient, or reflection coefficient, for the n-1th step. If the constraint does not hold, then Tn cannot be positive definite.
On exit: the solution vector xn. The element X N returns the partial (auto)correlation coefficient, or reflection coefficient, for the nth step. If X N≥1.0, then the matrix T n+1 will not be positive definite to working accuracy.
4:   V – REAL (KIND=nag_wp)Input/Output
On entry: with N>1 the mean square prediction error for the (n-1)th step, as returned by a previous call to F04MEF.
On exit: the mean square prediction error, or predictor error variance ratio, νn, for the nth step. (See Section 9 and the Introduction to Chapter G13.)
5:   WORK N-1 – REAL (KIND=nag_wp) arrayWorkspace
6:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=-1
On entry, | N<0,
or | T 0≤0.0,
or | N>1 and X N-1≥1.0.
IFAIL=1
The Toeplitz matrix T n+1 is not positive definite to working accuracy. If, on exit, X N is close to unity, then the principal minor was probably close to being singular, and the sequence τ 0,τ 1,…,τN may be a valid sequence nevertheless. X returns the solution of the equations
Tnxn=-tn,
and V returns vn, but it may not be positive.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

The computed solution of the equations certainly satisfies
r=Tnxn+tn,
where r 1 is approximately bounded by
r 1≤cε ∏i=1 n 1+pi-1 ,
c being a modest function of n, ε being the machine precision and pk being the kth element of xk. This bound is almost certainly pessimistic, but it has not yet been established whether or not the method of Durbin is backward stable. For further information on stability issues see Bunch (1985), Bunch (1987), Cybenko (1980) and Golub and Van Loan (1996). The following bounds on Tn-1 1 hold:
max 1 v n-1,1∏i=1 n-1 1-pi ≤Tn-1 1≤∏i=1 n-1 1+pi 1-pi ,
where vn is the mean square prediction error for the nth step. (See Cybenko (1980).) Note that vn<v n-1. The norm of Tn-1 may also be estimated using routine F04YDF.

8 Parallelism and Performance

F04MEF makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The number of floating-point operations used by this routine is approximately 4 n.
The mean square prediction errors, vi, is defined as
vi=τ 0+ t i-1 T x i-1/τ 0.
Note that vi=1-pi 2 v i-1.

10 Example

This example finds the solution of the Yule–Walker equations Tkxk=-tk, k=1,2,3,4 where
T 4= 4 3 2 1 3 4 3 2 2 3 4 3 1 2 3 4   and  t 4= 3 2 1 0 .

10.1 Program Text

Program Text (f04mefe.f90)

10.2 Program Data

Program Data (f04mefe.d)

10.3 Program Results

Program Results (f04mefe.r)

F04 Chapter Contents
F04 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F04MFF : NAG Library, Mark 26

F04 Chapter Contents
F04 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F04MFF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F04MFF updates the solution of the equations Tx=b, where T is a real symmetric positive definite Toeplitz matrix.

2 Specification

SUBROUTINE F04MFF ( N, T, B, X, P, WORK, IFAIL)
INTEGER | N, IFAIL
REAL (KIND=nag_wp) | T(0:*), B(*), X(*), P, WORK(*)

3 Description

F04MFF solves the equations
Tnxn=bn,
where Tn is the n by n symmetric positive definite Toeplitz matrix
Tn= τ 0 τ 1 τ 2 … τ n-1 τ 1 τ 0 τ 1 … τ n-2 τ 2 τ 1 τ 0 … τ n-3 . . . . τ n-1 τ n-2 τ n-3 … τ 0
and bn is the n-element vector bn=β 1β 2…βn T, given the solution of the equations
T n-1x n-1=b n-1.
This routine will normally be used to successively solve the equations
Tkxk=bk,   k= 1,2,…,n.
If it is desired to solve the equations for a single value of n, then routine F04FFF may be called. This routine uses the method of Levinson (see Levinson (1947) and Golub and Van Loan (1996)).

4 References

Bunch J R (1985) Stability of methods for solving Toeplitz systems of equations SIAM J. Sci. Statist. Comput. 6 349–364
Bunch J R (1987) The weak and strong stability of algorithms in numerical linear algebra Linear Algebra Appl. 88/89 49–66
Cybenko G (1980) The numerical stability of the Levinson–Durbin algorithm for Toeplitz systems of equations SIAM J. Sci. Statist. Comput. 1 303–319
Golub G H and Van Loan C F (1996) Matrix Computations (3rd Edition) Johns Hopkins University Press, Baltimore
Levinson N (1947) The Weiner RMS error criterion in filter design and prediction J. Math. Phys. 25 261–278

5 Arguments

1:   N – INTEGERInput
On entry: the order of the Toeplitz matrix T.
Constraint: N≥0. When N=0, then an immediate return is effected.
2:   T 0:* – REAL (KIND=nag_wp) arrayInput
Note: the dimension of the array T must be at least max 1,N.
On entry: T i must contain the value τi, for i=0,1,…,N-1.
Constraint: T 0>0.0. Note that if this is not true, then the Toeplitz matrix cannot be positive definite.
3:   B* – REAL (KIND=nag_wp) arrayInput
Note: the dimension of the array B must be at least max 1,N.
On entry: the right-hand side vector bn.
4:   X* – REAL (KIND=nag_wp) arrayInput/Output
Note: the dimension of the array X must be at least max 1,N.
On entry: with N>1 the (n-1) elements of the solution vector x n-1 as returned by a previous call to F04MFF. The element X N need not be specified.
On exit: the solution vector xn.
5:   P – REAL (KIND=nag_wp)Output
On exit: the reflection coefficient p n-1. (See Section 9.)
6:   WORK* – REAL (KIND=nag_wp) arrayInput/Output
Note: the dimension of the array WORK must be at least max 1,2×N-1.
On entry: with N>2 the elements of WORK should be as returned from a previous call to F04MFF with (N-1) as the argument N.
On exit: the first (N-1) elements of WORK contain the solution to the Yule–Walker equations
T n-1y n-1=-t n-1,
where t n-1=τ 1τ 2…τ n-1 T.
7:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=-1
On entry, | N<0,
or | T 0≤0.0.
IFAIL=1
The Toeplitz matrix Tn is not positive definite to working accuracy. If, on exit, P is close to unity, then Tn was probably close to being singular.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

The computed solution of the equations certainly satisfies
r=Tnxn-bn,
where r 1 is approximately bounded by
r 1≤cεC Tn,
c being a modest function of n, ε being the machine precision and C T being the condition number of T with respect to inversion. This bound is almost certainly pessimistic, but it seems unlikely that the method of Levinson is backward stable, so caution should be exercised when Tn is ill-conditioned. The following bound on Tn-1 holds:
max 1∏i=1 n-1 1-pi 2 , 1∏i=1 n-1 1-pi ≤Tn-1 1≤∏i=1 n-1 1+pi 1-pi .
(See Golub and Van Loan (1996).) The norm of Tn-1 may also be estimated using routine F04YDF. For further information on stability issues see Bunch (1985), Bunch (1987), Cybenko (1980) and Golub and Van Loan (1996).

8 Parallelism and Performance

F04MFF makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The number of floating-point operations used by this routine is approximately 8 n.
If yi is the solution of the equations
Tiyi=-τ 1τ 2…τi T,
then the reflection coefficient pi is defined as the ith element of yi.

10 Example

This example finds the solution of the equations Tkxk=bk, k=1,2,3,4, where
T 4= 4 3 2 1 3 4 3 2 2 3 4 3 1 2 3 4   and  b 4= 1 1 1 1 .

10.1 Program Text

Program Text (f04mffe.f90)

10.2 Program Data

Program Data (f04mffe.d)

10.3 Program Results

Program Results (f04mffe.r)

F04 Chapter Contents
F04 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F04QAF : NAG Library, Mark 26

F04 Chapter Contents
F04 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F04QAF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
▸▿ 9 Further Comments
9.1 Description of the Printed Output
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F04QAF solves sparse nonsymmetric equations, sparse linear least squares problems and sparse damped linear least squares problems, using a Lanczos algorithm.

2 Specification

SUBROUTINE F04QAF ( M, N, B, X, SE, APROD, DAMP, ATOL, BTOL, CONLIM, ITNLIM, MSGLVL, ITN, ANORM, ACOND, RNORM, ARNORM, XNORM, WORK, RUSER, LRUSER, IUSER, LIUSER, INFORM, IFAIL)
INTEGER | M, N, ITNLIM, MSGLVL, ITN, LRUSER, IUSER(LIUSER), LIUSER, INFORM, IFAIL
REAL (KIND=nag_wp) | B(M), X(N), SE(N), DAMP, ATOL, BTOL, CONLIM, ANORM, ACOND, RNORM, ARNORM, XNORM, WORK(N,2), RUSER(LRUSER)
EXTERNAL | APROD

3 Description

F04QAF can be used to solve a system of linear equations
Ax=b (1)
where A is an n by n sparse nonsymmetric matrix, or can be used to solve linear least squares problems, so that F04QAF minimizes the value ρ given by
ρ=r,  r=b-Ax (2)
where A is an m by n sparse matrix and r denotes the Euclidean length of r so that r 2=rT r. A damping argument, λ, may be included in the least squares problem in which case F04QAF minimizes the value ρ given by
ρ 2=r 2+λ 2x 2. (3)
λ is supplied as the argument DAMP and should of course be zero if the solution to problems (1) or (2) is required. Minimizing ρ in (3) is often called ridge regression.
F04QAF is based upon algorithm LSQR (see Paige and Saunders (1982a) and Paige and Saunders (1982b)) and solves the problems by an algorithm based upon the Lanczos process. The routine does not require A explicitly, but A is specified via APROD which must perform the operations y+Ax and x+AT y for a given n-element vector x and m element vector y. A argument to APROD specifies which of the two operations is required on a given entry.
The routine also returns estimates of the standard errors of the sample regression coefficients (xi, for i=1,2,…,n) given by the diagonal elements of the estimated variance-covariance matrix V. When problem (2) is being solved and A is of full rank, then V is given by
V=s 2AT A-1,  s 2=ρ 2/m-n,  m>n
and when problem (3) is being solved then V is given by
V=s 2AT A+λ 2 I -1,  s 2=ρ 2/m,  λ≠0.
Let A- denote the matrix
A-=A,  λ=0;  A-= A λI ,  λ≠0, (4)
let r- denote the residual vector
r-=r,  λ=0;  r-= b 0 -A-x,  λ≠0 (5)
corresponding to an iterate x, so that ρ=r- is the function being minimized, and let A denote the Frobenius (Euclidean) norm of A. Then the routine accepts x as a solution if it is estimated that one of the following two conditions is satisfied:
ρ≤tol 1 A-.x+tol 2 b (6)
A-T r- ≤ tol 1 A- ρ (7)
where tol 1 and tol 2 are user-supplied tolerances which estimate the relative errors in A and b respectively. Condition (6) is appropriate for compatible problems where, in theory, we expect the residual to be zero and will be satisfied by an acceptable solution x to a compatible problem. Condition (7) is appropriate for incompatible systems where we do not expect the residual to be zero and is based on the observation that, in theory,
A-T r- = 0
when x is a solution to the least squares problem, and so (7) will be satisfied by an acceptable solution x to a linear least squares problem.
The routine also includes a test to prevent convergence to solutions, x, with unacceptably large elements. This can happen if A is nearly singular or is nearly rank deficient. If we let the singular values of A- be
σ 1≥σ 2≥⋯≥σn≥0
then the condition number of A- is defined as
cond A-=σ 1/σk
where σk is the smallest nonzero singular value of A- and hence k is the rank of A-. When k<n, then A- is rank deficient, the least squares solution is not unique and F04QAF will normally converge to the minimal length solution. In practice A- will not have exactly zero singular values, but may instead have small singular values that we wish to regard as zero.
The routine provides for this possibility by terminating if
cond A-≥clim (8)
where clim is a user-supplied limit on the condition number of A-. For problem (1) termination with this condition indicates that A is nearly singular and for problem (2) indicates that A is nearly rank deficient and so has near linear dependencies in its columns. In this case inspection of r, AT r and x, which are all returned by the routine, will indicate whether or not an acceptable solution has been found. Condition (8), perhaps in conjunction with λ≠0, can be used to try and ‘regularize’ least squares solutions. A full discussion of the stopping criteria is given in Section 6 of Paige and Saunders (1982a).
Introduction of a nonzero damping argument λ tends to reduce the size of the computed solution and to make its components less sensitive to changes in the data, and F04QAF is applicable when a value of λ is known a priori. To have an effect, λ should normally be at least ε A where ε is the machine precision. For further discussion see Paige and Saunders (1982b) and the references given there.
Whenever possible the matrix A should be scaled so that the relative errors in the elements of A are all of comparable size. Such a scaling helps to prevent the least squares problem from being unnecessarily sensitive to data errors and will normally reduce the number of iterations required. At the very least, in the absence of better information, the columns of A should be scaled to have roughly equal column length.

4 References

Paige C C and Saunders M A (1982a) LSQR: An algorithm for sparse linear equations and sparse least squares ACM Trans. Math. Software 8 43–71
Paige C C and Saunders M A (1982b) Algorithm 583 LSQR: Sparse linear equations and least squares problems ACM Trans. Math. Software 8 195–209

5 Arguments

1:   M – INTEGERInput
On entry: m, the number of rows of the matrix A.
Constraint: M≥1.
2:   N – INTEGERInput
On entry: n, the number of columns of the matrix A.
Constraint: N≥1.
3:   B M – REAL (KIND=nag_wp) arrayInput/Output
On entry: the right-hand side vector b.
On exit: B is overwritten.
4:   X N – REAL (KIND=nag_wp) arrayOutput
On exit: the solution vector x.
5:   SE N – REAL (KIND=nag_wp) arrayOutput
On exit: the estimates of the standard errors of the components of x. Thus SE i contains an estimate of ν ii, where ν ii is the ith diagonal element of the estimated variance-covariance matrix V. The estimates returned in SE will be the lower bounds on the actual estimated standard errors, but will usually be correct to at least one significant figure.
6:   APROD – SUBROUTINE, supplied by the user.External Procedure
APROD must perform the operations y:=y+Ax and x:=x+AT y for given vectors x and y.
The specification of APROD is:
SUBROUTINE APROD ( MODE, M, N, X, Y, RUSER, LRUSER, IUSER, LIUSER)
INTEGER | MODE, M, N, LRUSER, IUSER(LIUSER), LIUSER
REAL (KIND=nag_wp) | X(N), Y(M), RUSER(LRUSER)
1:   MODE – INTEGERInput/Output
On entry: specifies which operation is to be performed.
MODE=1
APROD must compute y+Ax.
MODE=2
APROD must compute x+AT y.
On exit: may be used as a flag to indicate a failure in the computation of y+Ax or x+AT y. If MODE is negative on exit from APROD, F04QAF will exit immediately with IFAIL set to MODE.
2:   M – INTEGERInput
On entry: m, the number of rows of A.
3:   N – INTEGERInput
On entry: n, the number of columns of A.
4:   X N – REAL (KIND=nag_wp) arrayInput/Output
On entry: the vector x.
On exit: if MODE=1, X must be unchanged.
If MODE=2, X must contain x+AT y.
5:   Y M – REAL (KIND=nag_wp) arrayInput/Output
On entry: the vector y.
On exit: if MODE=1, Y must contain y+Ax.
If MODE=2, Y must be unchanged.
6:   RUSER LRUSER – REAL (KIND=nag_wp) arrayUser Workspace
7:   LRUSER – INTEGERInput
8:   IUSER LIUSER – INTEGER arrayUser Workspace
9:   LIUSER – INTEGERInput
APROD is called with the arguments RUSER, LRUSER, IUSER and LIUSER as supplied to F04QAF. You are free to use the arrays RUSER, LRUSER, IUSER and LIUSER to supply information to APROD as an alternative to using COMMON global variables.
APROD must either be a module subprogram USEd by, or declared as EXTERNAL in, the (sub)program from which F04QAF is called. Arguments denoted as Input must not be changed by this procedure.
7:   DAMP – REAL (KIND=nag_wp)Input
On entry: the value λ. If either problem (1) or problem (2) is to be solved, then DAMP must be supplied as zero.
8:   ATOL – REAL (KIND=nag_wp)Input
On entry: the tolerance, tol 1, of the convergence criteria (6) and (7); it should be an estimate of the largest relative error in the elements of A. For example, if the elements of A are correct to about 4 significant figures, then ATOL should be set to about 5×10-4. If ATOL is supplied as less than ε, where ε is the machine precision, then the value ε is used instead of ATOL.
9:   BTOL – REAL (KIND=nag_wp)Input
On entry: the tolerance, tol 2, of the convergence criterion (6); it should be an estimate of the largest relative error in the elements of B. For example, if the elements of B are correct to about 4 significant figures, then BTOL should be set to about 5×10-4. If BTOL is supplied as less than ε, then the value ε is used instead of BTOL.
10:   CONLIM – REAL (KIND=nag_wp)Input
On entry: the value clim of equation (8); it should be an upper limit on the condition number of A-. CONLIM should not normally be chosen much larger than 1.0/ATOL. If CONLIM is supplied as zero, then the value 1.0/ε is used instead of CONLIM.
11:   ITNLIM – INTEGERInput/Output
On entry: an upper limit on the number of iterations. If ITNLIM≤0, then the value N is used in place of ITNLIM, but for ill-conditioned problems a higher value of ITNLIM is likely to be necessary.
On exit: unchanged unless ITNLIM≤0 on entry, in which case it is set to N.
12:   MSGLVL – INTEGERInput
On entry: the level of printing from F04QAF. If MSGLVL≤0, then no printing occurs, but otherwise messages will be output on the advisory message channel (see X04ABF). A description of the printed output is given in Section 9.1. The level of printing is determined as follows:
MSGLVL≤0
No printing.
MSGLVL=1
A brief summary is printed just prior to return from F04QAF.
MSGLVL≥2
A summary line is printed periodically to monitor the progress of F04QAF, together with a brief summary just prior to return from F04QAF.
13:   ITN – INTEGEROutput
On exit: the number of iterations performed.
14:   ANORM – REAL (KIND=nag_wp)Output
On exit: an estimate of A- for the matrix A- of (4).
15:   ACOND – REAL (KIND=nag_wp)Output
On exit: an estimate of cond A- which is a lower bound.
16:   RNORM – REAL (KIND=nag_wp)Output
On exit: an estimate of r- for the residual, r-, of (5) corresponding to the solution x returned in X. Note that r- is the function being minimized.
17:   ARNORM – REAL (KIND=nag_wp)Output
On exit: an estimate of the A-T r- corresponding to the solution x returned in X.
18:   XNORM – REAL (KIND=nag_wp)Output
On exit: an estimate of x for the solution x returned in X.
19:   WORK N 2 – REAL (KIND=nag_wp) arrayWorkspace
20:   RUSER LRUSER – REAL (KIND=nag_wp) arrayUser Workspace
RUSER is not used by F04QAF, but is passed directly to APROD and may be used to pass information to this routine as an alternative to using COMMON global variables.
21:   LRUSER – INTEGERInput
On entry: the dimension of the array RUSER as declared in the (sub)program from which F04QAF is called.
Constraint: LRUSER≥1.
22:   IUSER LIUSER – INTEGER arrayUser Workspace
IUSER is not used by F04QAF, but is passed directly to APROD and may be used to pass information to this routine as an alternative to using COMMON global variables.
23:   LIUSER – INTEGERInput
On entry: the dimension of the array IUSER as declared in the (sub)program from which F04QAF is called.
Constraint: LIUSER≥1.
24:   INFORM – INTEGEROutput
On exit: the reason for termination of F04QAF.
INFORM=0
The exact solution is x=0. No iterations are performed in this case.
INFORM=1
The termination criterion of (6) has been satisfied with tol 1 and tol 2 as the values supplied in ATOL and BTOL respectively.
INFORM=2
The termination criterion of (7) has been satisfied with tol 1 as the value supplied in ATOL.
INFORM=3
The termination criterion of (6) has been satisfied with tol 1 and/or tol 2 as the value ε, where ε is the machine precision. One or both of the values supplied in ATOL and BTOL must have been less than ε and was too small for this machine.
INFORM=4
The termination criterion of (7) has been satisfied with tol 1 as the value ε. The value supplied in ATOL must have been less than ε and was too small for this machine.
The values INFORM=5, 6 and 7 correspond to failure with IFAIL=2, 3 and 4 respectively (see Section 6) and when IFAIL is negative INFORM will be set to the same negative value.
25:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL<0
A negative value of IFAIL indicates an exit from F04QAF because you have set MODE negative in APROD. The value of IFAIL will be the same as your setting of MODE.
IFAIL=1
On entry, | M<1,
or | N<1,
or | LRUSER<1,
or | LIUSER<1.
IFAIL=2
The condition of (8) has been satisfied for the value of clim supplied in CONLIM. If this failure is unexpected you should check that APROD is working correctly. Although conditions (6) or (7) have not been satisfied, the values returned in RNORM, ARNORM and XNORM may nevertheless indicate that an acceptable solution has been reached.
IFAIL=3
The condition of (8) has been satisfied for the value clim=1.0/ε, where ε is the machine precision. The matrix A- is nearly singular or rank deficient and the problem is too ill-conditioned for this machine. If this failure is unexpected, you should check that APROD is working correctly.
IFAIL=4
The limit on the number of iterations has been reached. The number of iterations required by F04QAF and the condition of the matrix A- can depend strongly on the scaling of the problem. Poor scaling of the rows and columns of A should be avoided whenever possible.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

When the problem is compatible, the computed solution x will satisfy the equation
r=b-Ax,
where an estimate of r is returned in the argument RNORM. When the problem is incompatible, the computed solution x will satisfy the equation
A-T r- = e ,
where an estimate of e is returned in the argument ARNORM. See also Section 6.2 of Paige and Saunders (1982b).

8 Parallelism and Performance

F04QAF makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The time taken by F04QAF is likely to be principally determined by the time taken in APROD, which is called twice on each iteration, once with MODE=1 and once with MODE=2. The time taken per iteration by the remaining operations in F04QAF is approximately proportional to max m,n.
The Lanczos process will usually converge more quickly if A is pre-conditioned by a nonsingular matrix M that approximates A in some sense and is also chosen so that equations of the form My=c can efficiently be solved for y. For a discussion of preconditioning, see the F11 Chapter Introduction. In the context of F04QAF, problem (1) is equivalent to
A M-1 y=b,  Mx=y
and problem (2) is equivalent to minimizing
ρ=r,   r=b-A M-1 y,   Mx=y.
Note that the normal matrix A M-1 T A M-1=M-T AT A M-1 so that the preconditioning A M-1 is equivalent to the preconditioning M-T AT A M-1 of the normal matrix AT A.
Pre-conditioning can be incorporated into F04QAF simply by coding APROD to compute y+A M-1 x and x+M-TAT y in place of y+Ax and x+AT y respectively, and then solving the equations Mx=y for x on return from F04QAF. The quantity y+A M-1 x should be computed by solving Mz=x for z and then computing y+Az, and x+M-TAT y should be computed by solving MT z=AT y for z and then forming x+z.

9.1 Description of the Printed Output

When MSGLVL>0, then F04QAF will produce output (except in the case where the routine fails with IFAIL=1) on the advisory message channel (see X04ABF).
When MSGLVL≥2 then a summary line is printed periodically giving the following information:
Output | Meaning
ITN | Iteration number, k.
X(1) | The first element of the current iterate xk.
FUNCTION | The current value of the function, ρ, being minimized.
COMPAT | An estimate of r-k/b, where r-k is the residual corresponding to xk. This value should converge to zero (in theory) if and only if the problem is compatible. COMPAT decreases monotonically.
INCOMPAT | An estimate of A-T r-k / A-r-k which should converge to zero if and only if at the solution ρ is nonzero. INCOMPAT is not usually monotonic.
NRM(ABAR) | A monotonically increasing estimate of A-.
COND(ABAR) | A monotonically increasing estimate of the condition number cond A-.

10 Example

This example solves the linear least squares problem
min⁡ρ =r,  r=b-Ax
where A is the 13 by 12 matrix and b is the 13 element vector given by
A= 1 0 0 -1 0 0 0 0 0 0 0 0 0 1 0 0 -1 0 0 0 0 0 0 0 0 0 1 -1 0 0 0 0 0 0 0 0 -1 0 -1 4 -1 0 0 -1 0 0 0 0 0 -1 0 -1 4 -1 0 0 -1 0 0 0 0 0 0 0 -1 1 0 0 0 0 0 0 0 0 0 0 0 0 1 -1 0 0 0 0 0 0 0 -1 0 0 -1 4 -1 0 -1 0 0 0 0 0 -1 0 0 -1 4 -1 0 -1 0 0 0 0 0 0 0 0 -1 1 0 0 0 0 0 0 0 0 0 -1 0 0 1 0 0 0 0 0 0 0 0 0 -1 0 0 1 1 1 1 0 0 1 1 0 0 1 1 1 ,  b=-h 2 0 0 0 1 1 0 0 1 1 0 0 0 -h-3
with h=0.1.
Such a problem can arise by considering the Neumann problem on a rectangle
δu δn =0 δu δn =0 ∇ 2 u=g x,y δu δn =0 ∫ c u=1 δu δn =0
where C is the boundary of the rectangle, and discretizing as illustrated below with the square mesh
Figure 1
The 12 by 12 symmetric part of A represents the difference equations and the final row comes from the normalizing condition. The example program has g x,y=1 at all the internal mesh points, but apart from this is written in a general manner so that the number of rows (NROWS) and columns (NCOLS) in the grid can readily be altered.

10.1 Program Text

Program Text (f04qafe.f90)

10.2 Program Data

Program Data (f04qafe.d)

10.3 Program Results

Program Results (f04qafe.r)

F04 Chapter Contents
F04 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F04YAF : NAG Library, Mark 26

F04 Chapter Contents
F04 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F04YAF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F04YAF returns elements of the estimated variance-covariance matrix of the sample regression coefficients for the solution of a linear least squares problem.
The routine can be used to find the estimated variances of the sample regression coefficients.

2 Specification

SUBROUTINE F04YAF ( JOB, P, SIGMA, A, LDA, SVD, IRANK, SV, CJ, WORK, IFAIL)
INTEGER | JOB, P, LDA, IRANK, IFAIL
REAL (KIND=nag_wp) | SIGMA, A(LDA,P), SV(P), CJ(P), WORK(P)
LOGICAL | SVD

3 Description

The estimated variance-covariance matrix C of the sample regression coefficients is given by
C = σ 2 XT X - 1 ,   XT X   nonsingular,
where XT X is the normal matrix for the linear least squares regression problem
min:y-Xb 2, (1)
σ 2 is the estimated variance of the residual vector r=y-Xb, and X is an n by p observation matrix.
When XT X is singular, C is taken to be
C=σ 2 XT X †,
where XT X † is the pseudo-inverse of XT X; this assumes that the minimal least squares solution of (1) has been found.
The diagonal elements of C are the estimated variances of the sample regression coefficients, b.
The routine can be used to find either the diagonal elements of C, or the elements of the jth column of C, or the upper triangular part of C.
This routine must be preceded by a routine that returns either the upper triangular matrix U of the QU factorization of X or of the Cholesky factorization of XT X, or the singular values and right singular vectors of X. In particular this routine can be preceded by one of the routines F04JGF or F08KAF (DGELSS), which return the arguments IRANK, SIGMA, A and SV in the required form. F04JGF returns the argument SVD, but when this routine is used following routine F08KAF (DGELSS) the argument SVD should be set to .TRUE.. The argument P of this routine corresponds to the argument N in routines F04JGF and F08KAF (DGELSS).

4 References

Anderson T W (1958) An Introduction to Multivariate Statistical Analysis Wiley
Lawson C L and Hanson R J (1974) Solving Least Squares Problems Prentice–Hall

5 Arguments

1:   JOB – INTEGERInput
On entry: specifies which elements of C are required.
JOB=-1
The upper triangular part of C is required.
JOB=0
The diagonal elements of C are required.
JOB>0
The elements of column JOB of C are required.
Constraint: -1≤JOB≤P.
2:   P – INTEGERInput
On entry: p, the order of the variance-covariance matrix C.
Constraint: P≥1.
3:   SIGMA – REAL (KIND=nag_wp)Input
On entry: σ, the standard error of the residual vector given by
σ=rT r/n-k,n>kσ=0,n=k,
where k is the rank of X.
Constraint: SIGMA≥0.0.
4:   A LDAP – REAL (KIND=nag_wp) arrayInput/Output
On entry: if SVD=.FALSE., A must contain the upper triangular matrix U of the QU factorization of X, or of the Cholesky factorization of XT X; elements of the array below the diagonal need not be set.
If SVD=.TRUE., A must contain the first k rows of the matrix VT, where k is the rank of X and V is the right-hand orthogonal matrix of the singular value decomposition of X. Thus the ith row must contain the ith right-hand singular vector of X.
On exit: if JOB≥0, A is unchanged.
If JOB=-1, A contains the upper triangle of the symmetric matrix C.
If SVD=.TRUE., elements of the array below the diagonal are used as workspace.
If SVD=.FALSE., they are unchanged.
5:   LDA – INTEGERInput
On entry: the first dimension of the array A as declared in the (sub)program from which F04YAF is called.
Constraints:
  • if SVD=.FALSE. or JOB=-1, LDA≥P;
  • if SVD=.TRUE. and JOB≥0, LDA≥max 1,IRANK.
6:   SVD – LOGICALInput
On entry: must be .TRUE. if the least squares solution was obtained from a singular value decomposition of X. SVD must be .FALSE. if the least squares solution was obtained from either a QU factorization of X or a Cholesky factorization of XT X. In the latter case the rank of X is assumed to be p and so is applicable only to full rank problems with n≥p.
7:   IRANK – INTEGERInput
On entry: if SVD=.TRUE., IRANK must specify the rank k of the matrix X.
If SVD=.FALSE., IRANK is not referenced and the rank of X is assumed to be p.
Constraint: 0<IRANK≤min n,P.
8:   SV P – REAL (KIND=nag_wp) arrayInput
On entry: if SVD=.TRUE., SV must contain the first IRANK singular values of X.
If SVD=.FALSE., SV is not referenced.
9:   CJ P – REAL (KIND=nag_wp) arrayOutput
On exit: if JOB=0, CJ returns the diagonal elements of C.
If JOB=j>0, CJ returns the jth column of C.
If JOB=-1, CJ is not referenced.
10:   WORK P – REAL (KIND=nag_wp) arrayWorkspace
If JOB>0, WORK is not referenced.
11:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, | P<1,
or | SIGMA<0.0,
or | JOB<-1,
or | JOB>P,
or SVD=.TRUE. and (IRANK<0 or IRANK>P)
or (JOB≥0 and LDA<max 1,IRANK)
or (JOB=-1 and LDA<P)),
or | SVD=.FALSE. and LDA<P.
IFAIL=2
On entry, SVD=.TRUE. and IRANK=0.
IFAIL=3
On entry, SVD=.FALSE. and overflow would occur in computing an element of C. The upper triangular matrix U must be very nearly singular.
IFAIL=4
On entry, SVD=.TRUE. and one of the first IRANK singular values is zero. Either the first IRANK singular values or IRANK must be incorrect.
overflow
If overflow occurs then either an element of C is very large, or more likely, either the rank, or the upper triangular matrix, or the singular values or vectors have been incorrectly supplied.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

The computed elements of C will be the exact covariances of a closely neighbouring least squares problem, so long as a numerically stable method has been used in the solution of the least squares problem.

8 Parallelism and Performance

F04YAF makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

When JOB=-1 the time taken by F04YAF is approximately proportional to p k 2, where k is the rank of X. When JOB=0 and SVD=.FALSE., the time taken by the routine is approximately proportional to p k 2, otherwise the time taken is approximately proportional to pk.

10 Example

This example finds the estimated variances of the sample regression coefficients (the diagonal elements of C) for the linear least squares problem
min⁡rT r ,   where ​ r=y-Xb  and
X= 0.6 1.2 3.9 5.0 4.0 2.5 1.0 -4.0 -5.5 -1.0 -2.0 -6.5 -4.2 -8.4 -4.8 ,   b= 3.0 4.0 -1.0 -5.0 -1.0 ,
following a solution obtained by F04JGF. See the routine document for F04JGF for further information.

10.1 Program Text

Program Text (f04yafe.f90)

10.2 Program Data

Program Data (f04yafe.d)

10.3 Program Results

Program Results (f04yafe.r)

F04 Chapter Contents
F04 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F04YDF : NAG Library, Mark 26

F04 Chapter Contents
F04 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F04YDF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
▸▿ 9 Further Comments
9.1 Timing
9.2 Overflow
9.3 Choice of t
9.4 Use in Conjunction with NAG Library Routines
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F04YDF estimates the 1-norm of a real rectangular matrix without accessing the matrix explicitly. It uses reverse communication for evaluating matrix products. The routine may be used for estimating condition numbers of square matrices.

2 Specification

SUBROUTINE F04YDF ( IREVCM, M, N, X, LDX, Y, LDY, ESTNRM, T, SEED, WORK, IWORK, IFAIL)
INTEGER | IREVCM, M, N, LDX, LDY, T, SEED, IWORK(2*N+5*T+20), IFAIL
REAL (KIND=nag_wp) | X(LDX,*), Y(LDY,*), ESTNRM, WORK(M*T)

3 Description

F04YDF computes an estimate (a lower bound) for the 1-norm
A 1 = max 1≤j≤n ∑ i=1 m a ij (1)
of an m by n real matrix A=a ij. The routine regards the matrix A as being defined by a user-supplied ‘Black Box’ which, given an n×t matrix X (with t≪n) or an m×t matrix Y, can return AX or AT Y. A reverse communication interface is used; thus control is returned to the calling program whenever a matrix product is required.
Note: this routine is not recommended for use when the elements of A are known explicitly; it is then more efficient to compute the 1-norm directly from formula (1) above.
The main use of the routine is for estimating B-1 1 for a square matrix, B, and hence the condition number κ 1 B=B 1B-1 1, without forming B-1 explicitly (A=B-1 above).
If, for example, an LU factorization of B is available, the matrix products B-1 X and B-T Y required by F04YDF may be computed by back- and forward-substitutions, without computing B-1.
The routine can also be used to estimate 1-norms of matrix products such as A-1 B and ABC, without forming the products explicitly. Further applications are described by Higham (1988).
Since A∞=AT 1, F04YDF can be used to estimate the ∞-norm of A by working with AT instead of A.
The algorithm used is described in Higham and Tisseur (2000).

4 References

Higham N J (1988) FORTRAN codes for estimating the one-norm of a real or complex matrix, with applications to condition estimation ACM Trans. Math. Software 14 381–396
Higham N J and Tisseur F (2000) A block algorithm for matrix 1-norm estimation, with an application to 1-norm pseudospectra SIAM J. Matrix. Anal. Appl. 21 1185–1201

5 Arguments

Note: this routine uses reverse communication. Its use involves an initial entry, intermediate exits and re-entries, and a final exit, as indicated by the argument IREVCM. Between intermediate exits and re-entries, all arguments other than X and Y must remain unchanged.
1:   IREVCM – INTEGERInput/Output
On initial entry: must be set to 0.
On intermediate exit: IREVCM=1 or 2, and X contains the n×t matrix X and Y contains the m×t matrix Y. The calling program must
(a) if IREVCM=1, evaluate AX and store the result in Y
or
if IREVCM=2, evaluate AT Y and store the result in X,
(b) call F04YDF once again, with all the other arguments unchanged.
On intermediate re-entry: IREVCM must be unchanged.
On final exit: IREVCM=0.
2:   M – INTEGERInput
On entry: the number of rows of the matrix A.
Constraint: M≥0.
3:   N – INTEGERInput
On entry: n, the number of columns of the matrix A.
Constraint: N≥0.
4:   X LDX* – REAL (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array X must be at least max 1,T.
On initial entry: need not be set.
On intermediate exit: if IREVCM=1, contains the current matrix X.
On intermediate re-entry: if IREVCM=2, must contain AT Y.
On final exit: the array is undefined.
5:   LDX – INTEGERInput
On initial entry: the leading dimension of the array X as declared in the (sub)program from which F04YDF is called.
Constraint: LDX≥N.
6:   Y LDY* – REAL (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array Y must be at least max 1,T.
On initial entry: need not be set.
On intermediate exit: if IREVCM=2, contains the current matrix Y.
On intermediate re-entry: if IREVCM=1, must contain AX.
On final exit: the array is undefined.
7:   LDY – INTEGERInput
On initial entry: the leading dimension of the array Y as declared in the (sub)program from which F04YDF is called.
Constraint: LDY≥M.
8:   ESTNRM – REAL (KIND=nag_wp)Input/Output
On initial entry: need not be set.
On intermediate re-entry: must not be changed.
On final exit: an estimate (a lower bound) for A 1.
9:   T – INTEGERInput
On entry: the number of columns t of the matrices X and Y. This is an argument that can be used to control the accuracy and reliability of the estimate and corresponds roughly to the number of columns of A that are visited during each iteration of the algorithm.
If T≥2 then a partly random starting matrix is used in the algorithm.
Suggested value: T=2.
Constraint: 1≤T≤M.
10:   SEED – INTEGERInput
On entry: the seed used for random number generation.
If T=1, SEED is not used.
Constraint: if T>1, SEED≥1.
11:   WORK M×T – REAL (KIND=nag_wp) arrayCommunication Array
12:   IWORK 2×N+5×T+20 – INTEGER arrayCommunication Array
On initial entry: need not be set.
On intermediate re-entry: must not be changed.
13:   IFAIL – INTEGERInput/Output
On initial entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, because for this routine the values of the output arguments may be useful even if IFAIL≠0 on exit, the recommended value is -1. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On final exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
Internal error; please contact NAG.
IFAIL=-1
On entry, IREVCM=value.
Constraint: IREVCM=0, 1 or 2.
On initial entry, IREVCM=value.
Constraint: IREVCM=0.
IFAIL=-2
On entry, M=value.
Constraint: M≥0.
IFAIL=-3
On entry, N=value.
Constraint: N≥0.
IFAIL=-5
On entry, LDX=value and N=value.
Constraint: LDX≥N.
IFAIL=-7
On entry, LDY=value and M=value.
Constraint: LDY≥M.
IFAIL=-9
On entry, M=value and T=value.
Constraint: 1≤T≤M.
IFAIL=-10
On entry, T=value and SEED=value.
Constraint: if T>1, SEED≥1.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

In extensive tests on random matrices of size up to m=n=450 the estimate ESTNRM has been found always to be within a factor two of A 1; often the estimate has many correct figures. However, matrices exist for which the estimate is smaller than A 1 by an arbitrary factor; such matrices are very unlikely to arise in practice. See Higham and Tisseur (2000) for further details.

8 Parallelism and Performance

F04YDF is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

9.1 Timing

For most problems the time taken during calls to F04YDF will be negligible compared with the time spent evaluating matrix products between calls to F04YDF.
The number of matrix products required depends on the matrix A. At most six products of the form Y=AX and five products of the form X=AT Y will be required. The number of iterations is independent of the choice of t.

9.2 Overflow

It is your responsibility to guard against potential overflows during evaluation of the matrix products. In particular, when estimating B-1 1 using a triangular factorization of B, F04YDF should not be called if one of the factors is exactly singular – otherwise division by zero may occur in the substitutions.

9.3 Choice of t

The argument t controls the accuracy and reliability of the estimate. For t=1, the algorithm behaves similarly to the LAPACK estimator xLACON. Increasing t typically improves the estimate, without increasing the number of iterations required.
For t≥2, random matrices are used in the algorithm, so for repeatable results the same value of SEED should be used each time.
A value of t=2 is recommended for new users.

9.4 Use in Conjunction with NAG Library Routines

To estimate the 1-norm of the inverse of a matrix A, the following skeleton code can normally be used:
      ...  code to factorize A ...
      IF (A is not singular) THEN
         IREVCM = 0
10       CALL F04YDF (IREVCM,M,N,X,LDX,Y,LDY,ESTNRM,T,SEED,WORK,   &
                      IWORK,IFAIL)
         IF (IREVCM.NE.0) THEN
            IF (IREVCM.EQ.1) THEN
               ...  code to compute Y=inv(A)X ...
            ELSE
               ...  code to compute X=inv(transpose(A))Y ...
            END IF
            GO TO 10
         END IF
      END IF
To compute A-1 X or A-T Y, solve the equation AY=X or AT X=Y, storing the result in Y or X respectively. The code will vary, depending on the type of the matrix A, and the NAG routine used to factorize A.
The factorization will normally have been performed by a suitable routine from Chapters F01, F03 or F07. Note also that many of the ‘Black Box’ routines in Chapter F04 for solving systems of equations also return a factorization of the matrix. The example program in Section 10 illustrates how F04YDF can be used in conjunction with NAG Library routines for LU factorization of a real matrix F07ADF (DGETRF).
It is straightforward to use F04YDF for the following other types of matrix, using the named routines for factorization and solution:
  • nonsymmetric tridiagonal (F01LEF and F04LEF);
  • nonsymmetric almost block-diagonal (F01LHF and F04LHF);
  • nonsymmetric band (F07BDF (DGBTRF) and F07BEF (DGBTRS));
  • symmetric positive definite (F07FDF (DPOTRF) and F07FEF (DPOTRS));
  • symmetric positive definite band (F07HDF (DPBTRF) and F07HEF (DPBTRS));
  • symmetric positive definite tridiagonal (F07JAF (DPTSV), F07JDF (DPTTRF) and F07JEF (DPTTRS));
  • symmetric positive definite variable bandwidth (F01MCF and F04MCF);
  • symmetric positive definite sparse (F11JAF and F11JBF);
  • symmetric indefinite (F07PDF (DSPTRF) and F07PEF (DSPTRS));
  • nonsymmetric sparse (F11MEF and F11MFF; note that F11MGF can also be used here).
For upper or lower triangular matrices, no factorization routine is needed: Y=A-1 X and X=A-T Y may be computed by calls to F06PJF (DTRSV) (or F06PKF (DTBSV) if the matrix is banded, or F06PLF (DTPSV) if the matrix is stored in packed form).

10 Example

For this routine two examples are provided. There is a single example program for F04YDF, with a main program and the code to solve the two example problems is given in Example 1 (EX1) and Example 2 (EX2).
Example 1 (EX1)
This example estimates the condition number A 1A-1 1 of the matrix A given by
A= 0.7 -0.2 1.0 0.0 2.0 0.1 0.3 0.7 0.0 1.0 0.9 0.2 0.0 0.0 0.2 0.7 0.0 -1.1 0.0 3.4 -0.7 0.2 0.1 0.1 0.0 -4.0 0.0 1.0 9.0 0.0 0.4 1.2 4.3 0.0 6.2 5.9 .
Example 2 (EX2)
This example estimates the condition number of the sparse matrix A (stored in symmetric coordinate storage format) given by
A = 0.0 0.0 0.0 1.0 0.0 3.0 1.0 0.0 0.0 0.0 0.0 2.0 0.0 2.0 0.0 2.0 0.0 4.0 0.0 5.0 0.0 1.0 2.0 0.0 0.0 .

10.1 Program Text

Program Text (f04ydfe.f90)

10.2 Program Data

Program Data (f04ydfe.d)

10.3 Program Results

Program Results (f04ydfe.r)

F04 Chapter Contents
F04 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F04ZDF : NAG Library, Mark 26

F04 Chapter Contents
F04 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F04ZDF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
▸▿ 9 Further Comments
9.1 Timing
9.2 Overflow
9.3 Choice of t
9.4 Use in Conjunction with NAG Library Routines
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F04ZDF estimates the 1-norm of a complex rectangular matrix without accessing the matrix explicitly. It uses reverse communication for evaluating matrix products. The routine may be used for estimating condition numbers of square matrices.

2 Specification

SUBROUTINE F04ZDF ( IREVCM, M, N, X, LDX, Y, LDY, ESTNRM, T, SEED, WORK, RWORK, IWORK, IFAIL)
INTEGER | IREVCM, M, N, LDX, LDY, T, SEED, IWORK(2*N+5*T+20), IFAIL
REAL (KIND=nag_wp) | ESTNRM, RWORK(2*N)
COMPLEX (KIND=nag_wp) | X(LDX,*), Y(LDY,*), WORK(M*T)

3 Description

F04ZDF computes an estimate (a lower bound) for the 1-norm
A 1 = max 1≤j≤n ∑ i=1 m a ij (1)
of an m by n complex matrix A=a ij. The routine regards the matrix A as being defined by a user-supplied ‘Black Box’ which, given an n×t matrix X (with t≪n) or an m×t matrix Y, can return AX or AH Y, where AH is the complex conjugate transpose. A reverse communication interface is used; thus control is returned to the calling program whenever a matrix product is required.
Note: this routine is not recommended for use when the elements of A are known explicitly; it is then more efficient to compute the 1-norm directly from the formula (1) above.
The main use of the routine is for estimating B-1 1 for a square matrix B, and hence the condition number κ 1 B=B 1B-1 1, without forming B-1 explicitly (A=B-1 above).
If, for example, an LU factorization of B is available, the matrix products B-1 X and B-H Y required by F04ZDF may be computed by back- and forward-substitutions, without computing B-1.
The routine can also be used to estimate 1-norms of matrix products such as A-1 B and ABC, without forming the products explicitly. Further applications are described in Higham (1988).
Since A∞=AH 1, F04ZDF can be used to estimate the ∞-norm of A by working with AH instead of A.
The algorithm used is described in Higham and Tisseur (2000).

4 References

Higham N J (1988) FORTRAN codes for estimating the one-norm of a real or complex matrix, with applications to condition estimation ACM Trans. Math. Software 14 381–396
Higham N J and Tisseur F (2000) A block algorithm for matrix 1-norm estimation, with an application to 1-norm pseudospectra SIAM J. Matrix. Anal. Appl. 21 1185–1201

5 Arguments

Note: this routine uses reverse communication. Its use involves an initial entry, intermediate exits and re-entries, and a final exit, as indicated by the argument IREVCM. Between intermediate exits and re-entries, all arguments other than X and Y must remain unchanged.
1:   IREVCM – INTEGERInput/Output
On initial entry: must be set to 0.
On intermediate exit: IREVCM=1 or 2, and X contains the n×t matrix X and Y contains the m×t matrix Y. The calling program must
(a) if IREVCM=1, evaluate AX and store the result in Y
or
if IREVCM=2, evaluate AH Y and store the result in X, where AH is the complex conjugate transpose;
(b) call F04ZDF once again, with all the arguments unchanged.
On intermediate re-entry: IREVCM must be unchanged.
On final exit: IREVCM=0.
2:   M – INTEGERInput
On entry: the number of rows of the matrix A.
Constraint: M≥0.
3:   N – INTEGERInput
On initial entry: n, the number of columns of the matrix A.
Constraint: N≥0.
4:   X LDX* – COMPLEX (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array X must be at least max 1,T.
On initial entry: need not be set.
On intermediate exit: if IREVCM=1, contains the current matrix X.
On intermediate re-entry: if IREVCM=2, must contain AH Y.
On final exit: the array is undefined.
5:   LDX – INTEGERInput
On initial entry: the leading dimension of the array X as declared in the (sub)program from which F04ZDF is called.
Constraint: LDX≥N.
6:   Y LDY* – COMPLEX (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array Y must be at least max 1,T.
On initial entry: need not be set.
On intermediate exit: if IREVCM=2, contains the current matrix Y.
On intermediate re-entry: if IREVCM=1, must contain AX.
On final exit: the array is undefined.
7:   LDY – INTEGERInput
On initial entry: the leading dimension of the array Y as declared in the (sub)program from which F04ZDF is called.
Constraint: LDY≥M.
8:   ESTNRM – REAL (KIND=nag_wp)Input/Output
On initial entry: need not be set.
On intermediate re-entry: must not be changed.
On final exit: an estimate (a lower bound) for A 1.
9:   T – INTEGERInput
On entry: the number of columns t of the matrices X and Y. This is an argument that can be used to control the accuracy and reliability of the estimate and corresponds roughly to the number of columns of A that are visited during each iteration of the algorithm.
If T≥2 then a partly random starting matrix is used in the algorithm.
Suggested value: T=2.
Constraint: 1≤T≤M.
10:   SEED – INTEGERInput
On entry: the seed used for random number generation.
If T=1, SEED is not used.
Constraint: if T>1, SEED≥1.
11:   WORK M×T – COMPLEX (KIND=nag_wp) arrayCommunication Array
12:   RWORK 2×N – REAL (KIND=nag_wp) arrayCommunication Array
13:   IWORK 2×N+5×T+20 – INTEGER arrayCommunication Array
On initial entry: need not be set.
On intermediate re-entry: must not be changed.
14:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
Internal error; please contact NAG.
IFAIL=-1
On entry, IREVCM=value.
Constraint: IREVCM=0, 1 or 2.
On initial entry, IREVCM=value.
Constraint: IREVCM=0.
IFAIL=-2
On entry, M=value.
Constraint: M≥0.
IFAIL=-3
On entry, N=value.
Constraint: N≥0.
IFAIL=-5
On entry, LDX=value and N=value.
Constraint: LDX≥N.
IFAIL=-7
On entry, LDY=value and M=value.
Constraint: LDY≥M.
IFAIL=-9
On entry, M=value and T=value.
Constraint: 1≤T≤M.
IFAIL=-10
On entry, T=value and SEED=value.
Constraint: if T>1, SEED≥1.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

In extensive tests on random matrices of size up to m=n=450 the estimate ESTNRM has been found always to be within a factor two of A 1; often the estimate has many correct figures. However, matrices exist for which the estimate is smaller than A 1 by an arbitrary factor; such matrices are very unlikely to arise in practice. See Higham and Tisseur (2000) for further details.

8 Parallelism and Performance

F04ZDF is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

9.1 Timing

For most problems the time taken during calls to F04ZDF will be negligible compared with the time spent evaluating matrix products between calls to F04ZDF.
The number of matrix products required depends on the matrix A. At most six products of the form Y=AX and five products of the form X=AH Y will be required. The number of iterations is independent of the choice of t.

9.2 Overflow

It is your responsibility to guard against potential overflows during evaluation of the matrix products. In particular, when estimating B-1 1 using a triangular factorization of B, F04ZDF should not be called if one of the factors is exactly singular – otherwise division by zero may occur in the substitutions.

9.3 Choice of t

The argument t controls the accuracy and reliability of the estimate. For t=1, the algorithm behaves similarly to the LAPACK estimator xLACON. Increasing t typically improves the estimate, without increasing the number of iterations required.
For t≥2, random matrices are used in the algorithm, so for repeatable results the same value of SEED should be used each time.
A value of t=2 is recommended for new users.

9.4 Use in Conjunction with NAG Library Routines

To estimate the 1-norm of the inverse of a matrix A, the following skeleton code can normally be used:
      ...  code to factorize A ...
      IF (A is not singular) THEN
         IREVCM = 0
10       CALL F04ZDF (IREVCM,M,N,X,LDX,Y,LDY,ESTNRM,T,SEED,WORK,  &
                      RWORK,IWORK,IFAIL)
         IF (IREVCM.NE.0) THEN
            IF (IREVCM.EQ.1) THEN
               ...  code to compute Y=inv(A)X ...
            ELSE
               ...  code to compute X=inv(herm(A))Y ...
            END IF
            GO TO 10
         END IF
      END IF
To compute A-1 X or A-H Y, solve the equation AY=X or AH X=Y storing the result in Y or X respectively. The code will vary, depending on the type of the matrix A, and the NAG routine used to factorize A.
The example program in Section 10 illustrates how F04ZDF can be used in conjunction with NAG Library routine for LU factorization of complex matrices F07ARF (ZGETRF)).
It is also straightforward to use F04ZDF for Hermitian positive definite matrices, using F06TFF, F07FRF (ZPOTRF) and F07FSF (ZPOTRS) for factorization and solution.
For upper or lower triangular square matrices, no factorization routine is needed: Y=A-1 X and X=A-H Y may be computed by calls to F06SJF (ZTRSV) (or F06SKF (ZTBSV) if the matrix is banded, or F06SLF (ZTPSV) if the matrix is stored in packed form).

10 Example

This example estimates the condition number A 1A-1 1 of the matrix A given by
A = 0.7+0.1 i -0.2+0.0 i 1.0+0.0 i 0.0+0.0 i 0.0+0.0 i 0.1+0.0 i 0.3+0.0 i 0.7+0.0 i 0.0+0.0 i 1.0+0.2 i 0.9+0.0 i 0.2+0.0 i 0.0+5.9 i 0.0+0.0 i 0.2+0.0 i 0.7+0.0 i 0.4+6.1 i 1.1+0.4 i 0.0+0.1 i 0.0+0.1 i -0.7+0.0 i 0.2+0.0 i 0.1+0.0 i 0.1+0.0 i 0.0+0.0 i 4.0+0.0 i 0.0+0.0 i 1.0+0.0 i 9.0+0.0 i 0.0+0.1 i 4.5+6.7 i 0.1+0.4 i 0.0+3.2 i 1.2+0.0 i 0.0+0.0 i 7.8+0.2 i .

10.1 Program Text

Program Text (f04zdfe.f90)

10.2 Program Data

Program Data (f04zdfe.d)

10.3 Program Results

Program Results (f04zdfe.r)

F04 Chapter Contents
F04 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F05AAF : NAG Library, Mark 26

F05 Chapter Contents
F05 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F05AAF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F05AAF applies the Schmidt orthogonalization process to n vectors in m-dimensional space, n≤m.

2 Specification

SUBROUTINE F05AAF ( A, LDA, M, N1, N2, S, CC, ICOL, IFAIL)
INTEGER | LDA, M, N1, N2, ICOL, IFAIL
REAL (KIND=nag_wp) | A(LDA,N2), S(N2), CC

3 Description

F05AAF applies the Schmidt orthogonalization process to n linearly independent vectors in m-dimensional space, n≤m. The effect of this process is to replace the original n vectors by n orthonormal vectors which have the property that the rth vector is linearly dependent on the first r of the original vectors, and that the sum of squares of the elements of the rth vector is equal to 1, for r=1,2,…,n. Inner-products are accumulated using additional precision.

4 References

None.

5 Arguments

1:   A LDAN2 – REAL (KIND=nag_wp) arrayInput/Output
On entry: columns N1 to N2 contain the vectors to be orthogonalized. The vectors are stored by columns in elements 1 to m.
On exit: these vectors are overwritten by the orthonormal vectors.
2:   LDA – INTEGERInput
On entry: the first dimension of the array A as declared in the (sub)program from which F05AAF is called.
Constraint: LDA≥M.
3:   M – INTEGERInput
On entry: m, the number of elements in each vector.
4:   N1 – INTEGERInput
5:   N2 – INTEGERInput
On entry: the indices of the first and last columns of A to be orthogonalized.
Constraint: N1≤N2.
6:   S N2 – REAL (KIND=nag_wp) arrayWorkspace
7:   CC – REAL (KIND=nag_wp)Output
On exit: is used to indicate linear dependence of the original vectors. The nearer CC is to 1.0, the more likely vector ICOL is dependent on vectors N1 to ICOL-1. See Section 9.
8:   ICOL – INTEGEROutput
On exit: the column number corresponding to CC. See Section 9.
9:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, N1>N2.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

Innerproducts are accumulated using additional precision arithmetic and full machine accuracy should be obtained except when CC>0.99999. (See Section 9.)

8 Parallelism and Performance

F05AAF is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The time taken by F05AAF is approximately proportional to n m 2, where n=N2-N1+1.
Arguments CC and ICOL have been included to give some indication of whether or not the vectors are nearly linearly independent, and their values should always be tested on exit from the routine. CC will be in the range 0.0,1.0 and the closer CC is to 1.0, the more likely the vector ICOL is to be linearly dependent on vectors N1 to ICOL-1. Theoretically, when the vectors are linearly dependent, CC should be exactly 1.0. In practice, because of rounding errors, it may be difficult to decide whether or not a value of CC close to 1.0 indicates linear dependence. As a general guide a value of CC>0.99999 usually indicates linear dependence, but examples exist which give CC>0.99999 for linearly independent vectors. If one of the original vectors is zero or if, possibly due to rounding errors, an exactly zero vector is produced by the Gram–Schmidt process, then CC is set exactly to 1.0 and the vector is not, of course, normalized. If more than one such vector occurs then ICOL references the last of these vectors.
If you are concerned about testing for near linear dependence in a set of vectors you may wish to consider using routine F08KBF (DGESVD).

10 Example

This example orthonormalizes columns 2, 3 and 4 of the matrix:
1 -2 3 1 -2 1 -2 -1 3 -2 1 5 4 1 5 3 .

10.1 Program Text

Program Text (f05aafe.f90)

10.2 Program Data

Program Data (f05aafe.d)

10.3 Program Results

Program Results (f05aafe.r)

F05 Chapter Contents
F05 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F05 Chapter Contents : NAG Library Manual, Mark 26

F05 Chapter Introduction
NAG Library Manual

NAG Library Chapter Contents

F05 – Orthogonalization

F05 Chapter Introduction – a description of the Chapter and an overview of the algorithms available

Routine Name | Mark of Introduction | Purpose
F05AAF Example Text Example Data | 5 | nagf_orthog_real_gram_schmidt Gram–Schmidt orthogonalization of n vectors of order m
F05 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F05 Chapter Introduction : NAG Library, Mark 26

F05 Chapter Contents
NAG Library Manual

NAG Library Chapter Introduction

F05 – Orthogonalization

▸▿ Contents

1 Scope of the Chapter
▸▿ 2 Background to the Problems
2.1 Gram–Schmidt Orthogonalization
2.2 Householder Orthogonalization
3 Recommendations on Choice and Use of Available Routines
4 Routines Withdrawn or Scheduled for Withdrawal
5 References

1 Scope of the Chapter

This chapter is concerned with the orthogonalization of vectors in a finite dimensional space.

2 Background to the Problems

Let a 1,a 2,…,an be a set of n linearly independent vectors in m-dimensional space; m≥n.
We wish to construct a set of n vectors q 1,q 2,…,qn such that:
  • – the vectors qi form an orthonormal set; that is, qiT qj=0 for i≠j, and qi 2=1;
  • – each ai is linearly dependent on the set qi.

2.1 Gram–Schmidt Orthogonalization

The classical Gram–Schmidt orthogonalization process is described in many textbooks; see for example Chapter 5 of Golub and Van Loan (1996).
It constructs the orthonormal set progressively. Suppose it has computed orthonormal vectors q 1,q 2,…,qk which orthogonalise the first k vectors a 1,a 2,…,ak. It then uses a k+1 to compute q k+1 as follows:
z k+1 = a k+1-∑i=1 k qiT a k+1 qi q k+1 = z k+1 /z k+1 2.
In finite precision computation, this process can result in a set of vectors qi which are far from being orthogonal. This is caused by z k+1 being small compared with a k+1. If this situation is detected, it can be remedied by reorthogonalising the computed q k+1 against q 1,q 2,…,qk, that is, repeating the process with the computed q k+1 instead of a k+1. See Danial et al. (1976).

2.2 Householder Orthogonalization

An alternative approach to orthogonalising a set of vectors is based on the QR factorization (see the F08 Chapter Introduction), which is usually performed by Householder's method. See Chapter 5 of Golub and Van Loan (1996).
Let A be the m by n matrix whose columns are the n vectors to be orthogonalised. The QR factorization gives
A=QR
where R is an n by n upper triangular matrix and Q is an m by n matrix, whose columns are the required orthonormal set.
Moreover, for any k such that 1≤k≤n, the first k columns of Q are an orthonormal basis for the first k columns of A.
Householder's method requires twice as much work as the Gram–Schmidt method, provided that no re-orthogonalization is required in the latter. However, it has satisfactory numerical properties and yields vectors which are close to orthogonality even when the original vectors ai are close to being linearly dependent.

3 Recommendations on Choice and Use of Available Routines

The single routine in this chapter, F05AAF, uses the Gram–Schmidt method, with re-orthogonalization to ensure that the computed vectors are close to being exactly orthogonal. This method is only available for real vectors.
To apply Householder's method, you must use routines in Chapter F08:
for real vectors: | F08AEF (DGEQRF), followed by F08AFF (DORGQR)
for complex vectors: | F08ASF (ZGEQRF), followed by F08ATF (ZUNGQR)
The example programs for F08AEF (DGEQRF) or F08ASF (ZGEQRF) illustrate the necessary calls to these routines.

4 Routines Withdrawn or Scheduled for Withdrawal

None.

5 References

Danial J W, Gragg W B, Kaufman L and Stewart G W (1976) Reorthogonalization and stable algorithms for updating the Gram–Schmidt QR factorization Math. Comput. 30 772–795
Golub G H and Van Loan C F (1996) Matrix Computations (3rd Edition) Johns Hopkins University Press, Baltimore
F05 Chapter Contents
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F06AAF (DROTG) : NAG Library, Mark 26

F06 Chapter Contents
F06 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F06AAF (DROTG)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
10 Example

1 Purpose

F06AAF (DROTG) generates a real Givens plane rotation.

2 Specification

SUBROUTINE F06AAF ( A, B, C, S)
REAL (KIND=nag_wp) A, B, C, S
The routine may be called by its BLAS name drotg.

3 Description

F06AAF (DROTG) generates a real Givens plane rotation with parameters c and s, such that, given real a and b:
c s -s c a b = d 0 .
The routine computes c, s and d as follows:
d = σ⁢a 2+b 2 ;
c = a/d, if ​ d≠ 0, 1, if ​ d= 0,   s = b/d, if ​ d≠ 0, 0, if ​ d= 0,
where   σ = sign⁡a, if ​a>b, sign⁡b, if ​a≤b.
The routine also computes the value z defined as
z= s, if ​s<c​ or ​c=0, 1/c, if ​0<c≤s.
This enables c and s to be reconstructed from the single value z as
c= 1-z 2, if ​z≤1, 1/z, if ​z>1,  s= z, if ​z≤1, 1-c 2, if ​z>1.
To apply the plane rotation to a pair of real vectors, call F06EPF (DROT); to apply it to a pair of complex vectors, call F06KPF (ZDROT).

4 References

None.

5 Arguments

1:   A – REAL (KIND=nag_wp)Input/Output
On entry: the value a, the first element of the vector which determines the rotation.
On exit: the value d.
2:   B – REAL (KIND=nag_wp)Input/Output
On entry: the value b, the second element of the vector which determines the rotation.
On exit: the value z, from which c and s can be reconstructed.
3:   C – REAL (KIND=nag_wp)Output
On exit: the value c, the cosine of the rotation.
4:   S – REAL (KIND=nag_wp)Output
On exit: the value s, the sine of the rotation.

6 Error Indicators and Warnings

None.

7 Accuracy

Not applicable.

8 Parallelism and Performance

F06AAF (DROTG) is not threaded in any implementation.

9 Further Comments

None.

10 Example

None.
F06 Chapter Contents
F06 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F06BAF : NAG Library, Mark 26

F06 Chapter Contents
F06 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F06BAF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
10 Example

1 Purpose

F06BAF generates a real Givens plane rotation and the tangent of that rotation.

2 Specification

SUBROUTINE F06BAF ( A, B, C, S)
REAL (KIND=nag_wp) A, B, C, S

3 Description

F06BAF generates a real Givens plane rotation with parameters c (≥0) and s, such that, given real a and b:
c s -s c a b = d 0 .
On exit, b is overwritten by t, the tangent of the rotation; c and s can be reconstructed from the single stored value t, by a subsequent call to F06BCF.
If b<ε a, where ε is the machine precision, the routine sets c=1 and s=0; if a<ε b, the routine sets c=0 and s=sign⁡b/a.
Note that t is always set to b/a, unless this would overflow, in which case the value flmax×sign⁡b/a is returned, where flmax is the value given by 1/X02AMF.
To apply the plane rotation to a pair of real vectors, call F06EPF (DROT); to apply it to a pair of complex vectors, call F06KPF (ZDROT).

4 References

None.

5 Arguments

1:   A – REAL (KIND=nag_wp)Input/Output
On entry: the value a, the first element of the vector which determines the rotation.
On exit: the value d.
2:   B – REAL (KIND=nag_wp)Input/Output
On entry: the value b, the second element of the vector which determines the rotation.
On exit: the value t, the tangent of the rotation.
3:   C – REAL (KIND=nag_wp)Output
On exit: the value c, the cosine of the rotation.
4:   S – REAL (KIND=nag_wp)Output
On exit: the value s, the sine of the rotation.

6 Error Indicators and Warnings

None.

7 Accuracy

Not applicable.

8 Parallelism and Performance

F06BAF is not threaded in any implementation.

9 Further Comments

None.

10 Example

None.
F06 Chapter Contents
F06 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F06BCF : NAG Library, Mark 26

F06 Chapter Contents
F06 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F06BCF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
10 Example

1 Purpose

F06BCF reconstructs the parameters c and s of a real plane rotation from the tangent of that rotation.

2 Specification

SUBROUTINE F06BCF ( T, C, S)
REAL (KIND=nag_wp) T, C, S

3 Description

F06BCF reconstructs the parameters c and s of a real plane rotation from the value of the tangent t, as returned by F06BAF:
c=1 1+t 2 ,  s=ct,
so that c≥0 and s has the same sign as t.
If t<ε, where ε is the machine precision, the routine sets c=1 and s=t; if t>1/ε, the routine sets c= 1 t and s=sign⁡t.

4 References

None.

5 Arguments

1:   T – REAL (KIND=nag_wp)Input
On entry: the value t, the tangent of the rotation.
2:   C – REAL (KIND=nag_wp)Output
On exit: the value c, the cosine of the rotation.
3:   S – REAL (KIND=nag_wp)Output
On exit: the value s, the sine of the rotation.

6 Error Indicators and Warnings

None.

7 Accuracy

Not applicable.

8 Parallelism and Performance

F06BCF is not threaded in any implementation.

9 Further Comments

None.

10 Example

None.
F06 Chapter Contents
F06 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F06BEF : NAG Library, Mark 26

F06 Chapter Contents
F06 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F06BEF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
10 Example

1 Purpose

F06BEF generates a real Jacobi plane rotation.

2 Specification

SUBROUTINE F06BEF ( JOB, X, Y, Z, C, S)
REAL (KIND=nag_wp) | X, Y, Z, C, S
CHARACTER(1) | JOB

3 Description

F06BEF generates a real Jacobi plane rotation with parameters c and s, which diagonalizes a given 2 by 2 real symmetric matrix:
c s -s c x y y z c -s s c = a 0 0 b .

4 References

None.

5 Arguments

1:   JOB – CHARACTER(1)Input
On entry: specifies the property which determines the precise form of the rotation.
JOB='B'
c≥1/2.
JOB='S'
0≤c≤1/2.
JOB='M'
a≥b.
Constraint: JOB='B', 'S' or 'M'.
2:   X – REAL (KIND=nag_wp)Input/Output
On entry: the value x, the 1,1 element of the input matrix.
On exit: the value a.
3:   Y – REAL (KIND=nag_wp)Input/Output
On entry: the value y, the 1,2 or 2,1 element of the input matrix.
On exit: the value t, the tangent of the rotation.
4:   Z – REAL (KIND=nag_wp)Input/Output
On entry: the value z. the 2,2 element of the input matrix.
On exit: the value b.
5:   C – REAL (KIND=nag_wp)Output
On exit: the value c, the cosine of the rotation.
6:   S – REAL (KIND=nag_wp)Output
On exit: the value s, the sine of the rotation.

6 Error Indicators and Warnings

None.

7 Accuracy

Not applicable.

8 Parallelism and Performance

F06BEF is not threaded in any implementation.

9 Further Comments

None.

10 Example

None.
F06 Chapter Contents
F06 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F06BHF : NAG Library, Mark 26

F06 Chapter Contents
F06 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F06BHF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
10 Example

1 Purpose

F06BHF applies a real similarity rotation to a 2 by 2 real symmetric matrix.

2 Specification

SUBROUTINE F06BHF ( X, Y, Z, C, S)
REAL (KIND=nag_wp) X, Y, Z, C, S

3 Description

F06BHF applies a real similarity rotation, with parameters c and s, to a given 2 by 2 real symmetric matrix; that is, it performs the operation:
x y y z ← c s -s c x y y z c -s s c .

4 References

None.

5 Arguments

1:   X – REAL (KIND=nag_wp)Input/Output
On entry: the value x, the 1,1 element of the input matrix.
On exit: the transformed value x.
2:   Y – REAL (KIND=nag_wp)Input/Output
On entry: the value y, the 1,2 or 2,1 element of the input matrix.
On exit: the transformed value y.
3:   Z – REAL (KIND=nag_wp)Input/Output
On entry: the value z, the 2,2 element of the input matrix.
On exit: the transformed value z.
4:   C – REAL (KIND=nag_wp)Input
On entry: the value c, the cosine of the rotation.
5:   S – REAL (KIND=nag_wp)Input
On entry: the value s, the sine of the rotation.

6 Error Indicators and Warnings

None.

7 Accuracy

Not applicable.

8 Parallelism and Performance

F06BHF is not threaded in any implementation.

9 Further Comments

None.

10 Example

None.
F06 Chapter Contents
F06 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F06BLF : NAG Library, Mark 26

F06 Chapter Contents
F06 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F06BLF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
10 Example

1 Purpose

F06BLF computes the quotient of two real scalars.

2 Specification

FUNCTION F06BLF ( A, B, FAIL)
REAL (KIND=nag_wp) F06BLF
REAL (KIND=nag_wp) | A, B
LOGICAL | FAIL

3 Description

F06BLF returns the value q via the function name, where
q= a/b, if ​a/b​ does not overflow, 0, if ​a=0, flmax×sign a/b, if ​a≠0​ and ​a/b​ would overflow.
Here flmax is the large value given by 1/X02AMF, and sign a/0 is taken as sign⁡a.

4 References

None.

5 Arguments

1:   A – REAL (KIND=nag_wp)Input
On entry: the value a.
2:   B – REAL (KIND=nag_wp)Input
On entry: the value b.
3:   FAIL – LOGICALOutput
On exit: .TRUE. if a/b would overflow (in which case q=flmax) or a=b=0 (in which case q=0); otherwise .FALSE..

6 Error Indicators and Warnings

None.

7 Accuracy

Not applicable.

8 Parallelism and Performance

F06BLF is not threaded in any implementation.

9 Further Comments

None.

10 Example

None.
F06 Chapter Contents
F06 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F06BMF : NAG Library, Mark 26

F06 Chapter Contents
F06 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F06BMF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
10 Example

1 Purpose

F06BMF completes the safe computation of the Euclidean length of a vector, following a call to F06FJF or F06KJF.

2 Specification

FUNCTION F06BMF ( SCAL, SSQ)
REAL (KIND=nag_wp) F06BMF
REAL (KIND=nag_wp) SCAL, SSQ

3 Description

F06BMF completes the safe computation of the Euclidean length of a vector, following a call to F06FJF or F06KJF which return values α and ξ such that
x 2 2=α 2 ξ.
F06BMF returns, via the function name, the value
min α⁢ξ,flmax,
where flmax is the value given by 1/X02AMF.

4 References

None.

5 Arguments

1:   SCAL – REAL (KIND=nag_wp)Input
On entry: the scaling factor α, returned by F06FJF or F06KJF.
Constraint: SCAL≥0.0.
2:   SSQ – REAL (KIND=nag_wp)Input
On entry: the scaled sum of squares ξ, returned by F06FJF or F06KJF.
Constraint: SSQ≥1.0.

6 Error Indicators and Warnings

None.

7 Accuracy

Not applicable.

8 Parallelism and Performance

F06BMF is not threaded in any implementation.

9 Further Comments

None.

10 Example

None.
F06 Chapter Contents
F06 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F06BNF : NAG Library, Mark 26

F06 Chapter Contents
F06 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F06BNF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
10 Example

1 Purpose

F06BNF returns the value a 2+b 2 via the function name.

2 Specification

FUNCTION F06BNF ( A, B)
REAL (KIND=nag_wp) F06BNF
REAL (KIND=nag_wp) A, B

3 Description

None.

4 References

None.

5 Arguments

1:   A – REAL (KIND=nag_wp)Input
On entry: the value a.
2:   B – REAL (KIND=nag_wp)Input
On entry: the value b.

6 Error Indicators and Warnings

None.

7 Accuracy

Not applicable.

8 Parallelism and Performance

F06BNF is not threaded in any implementation.

9 Further Comments

None.

10 Example

None.
F06 Chapter Contents
F06 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F06BPF : NAG Library, Mark 26

F06 Chapter Contents
F06 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F06BPF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
10 Example

1 Purpose

F06BPF returns an eigenvalue of a 2 by 2 real symmetric matrix.

2 Specification

FUNCTION F06BPF ( A, B, C)
REAL (KIND=nag_wp) F06BPF
REAL (KIND=nag_wp) A, B, C

3 Description

F06BPF returns an eigenvalue of the 2 by 2 real symmetric matrix
a b b c ,
via the function name. The result is intended for use as a shift in symmetric eigenvalue routines.
The eigenvalue is computed as
c - b f + sign⁡f × 1+f 2 ,
where f = a-c 2 b .
This is the eigenvalue nearer to c if a≠c, and is equal to c-b if a=c.

4 References

None.

5 Arguments

1:   A – REAL (KIND=nag_wp)Input
On entry: the value a, the 1,1 element of the input matrix.
2:   B – REAL (KIND=nag_wp)Input
On entry: the value b, the 1,2 or 2,1 element of the input matrix.
3:   C – REAL (KIND=nag_wp)Input
On entry: the value c, the 2,2 element of the input matrix.

6 Error Indicators and Warnings

None.

7 Accuracy

Not applicable.

8 Parallelism and Performance

F06BPF is not threaded in any implementation.

9 Further Comments

None.

10 Example

None.
F06 Chapter Contents
F06 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F06CAF : NAG Library, Mark 26

F06 Chapter Contents
F06 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F06CAF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
10 Example

1 Purpose

F06CAF generates a complex Givens plane rotation having real cosine.

2 Specification

SUBROUTINE F06CAF ( A, B, C, S)
REAL (KIND=nag_wp) | C
COMPLEX (KIND=nag_wp) | A, B, S

3 Description

F06CAF generates a complex Givens plane rotation with parameters c (real ≥0) and s (complex), such that, given complex a and b:
c s- -s c a b = d 0 .
If a is real, then d is also real. On exit, b is overwritten by t, the tangent of the rotation; c and s can be reconstructed from the single stored value t, by a subsequent call to F06CCF.
If b<ε a, where ε is the machine precision, the routine sets c=1 and s=t.
Note that t is always set to b/a, unless overflow would occur, in which case the routine returns the value of the expression
CMPLX flmax × sign Re b /a , flmax × sign Im b / a ;
flmax is the real value given by 1/X02AMF.

4 References

None.

5 Arguments

1:   A – COMPLEX (KIND=nag_wp)Input/Output
On entry: the value a, the first element of the vector which determines the rotation.
On exit: the value d.
2:   B – COMPLEX (KIND=nag_wp)Input/Output
On entry: the value b, the second element of the vector which determines the rotation.
On exit: the value t, the tangent of the rotation.
3:   C – REAL (KIND=nag_wp)Output
On exit: the value c, the cosine of the rotation.
4:   S – COMPLEX (KIND=nag_wp)Output
On exit: the value s, the sine of the rotation.

6 Error Indicators and Warnings

None.

7 Accuracy

Not applicable.

8 Parallelism and Performance

F06CAF is not threaded in any implementation.

9 Further Comments

None.

10 Example

None.
F06 Chapter Contents
F06 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F06CBF : NAG Library, Mark 26

F06 Chapter Contents
F06 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F06CBF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
10 Example

1 Purpose

F06CBF generates a complex Givens plane rotation having real sine.

2 Specification

SUBROUTINE F06CBF ( A, B, C, S)
REAL (KIND=nag_wp) | S
COMPLEX (KIND=nag_wp) | A, B, C

3 Description

F06CBF generates a complex Givens plane rotation with parameters c (complex) and s (real), such that, given complex a and b:
c- s -s c a b = d 0 ,
If b is real, then d is also real. On exit, b is overwritten by t, the tangent of the rotation; c and s can be reconstructed from the single stored value t, by a subsequent call to F06CDF.
If b<ε a and Im a=0, where ε is the machine precision, the routine sets c=1 and s=t.
If b<ε a and Im a≠0, the routine sets
c=sign Re a a a   and  s=t
Note that t is always set to b/a, unless overflow would occur, in which case the routine returns the value of the expression
CMPLX flmax × sign Re b /a , flmax × sign Im b / a ;
flmax is the real value given by 1/X02AMF.

4 References

None.

5 Arguments

1:   A – COMPLEX (KIND=nag_wp)Input/Output
On entry: the value a, the first element of the vector which determines the rotation.
On exit: the value d.
2:   B – COMPLEX (KIND=nag_wp)Input/Output
On entry: the value b, the second element of the vector which determines the rotation.
On exit: the value t, the tangent of the rotation.
3:   C – COMPLEX (KIND=nag_wp)Output
On exit: the value c, the cosine of the rotation.
4:   S – REAL (KIND=nag_wp)Output
On exit: the value s, the sine of the rotation.

6 Error Indicators and Warnings

None.

7 Accuracy

Not applicable.

8 Parallelism and Performance

F06CBF is not threaded in any implementation.

9 Further Comments

None.

10 Example

None.
F06 Chapter Contents
F06 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F06CCF : NAG Library, Mark 26

F06 Chapter Contents
F06 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F06CCF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
10 Example

1 Purpose

F06CCF reconstructs the parameters c (real) and s (complex) of a complex plane rotation from the tangent of that rotation.

2 Specification

SUBROUTINE F06CCF ( T, C, S)
REAL (KIND=nag_wp) | C
COMPLEX (KIND=nag_wp) | T, S

3 Description

F06CCF reconstructs the parameters c (real) and s (complex) of a complex plane rotation, from the value of the tangent t, as returned by F06CAF:
c=1 1+t 2 ,  s=ct,
so that c is always real and non-negative.
If t<ε, where ε is the machine precision, the routine sets c=1 and s=t.

4 References

None.

5 Arguments

1:   T – COMPLEX (KIND=nag_wp)Input
On entry: the value t, the tangent of the rotation.
2:   C – REAL (KIND=nag_wp)Output
On exit: the value c, the cosine of the rotation.
3:   S – COMPLEX (KIND=nag_wp)Output
On exit: the value s, the sine of the rotation.

6 Error Indicators and Warnings

None.

7 Accuracy

Not applicable.

8 Parallelism and Performance

F06CCF is not threaded in any implementation.

9 Further Comments

None.

10 Example

None.
F06 Chapter Contents
F06 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F06CDF : NAG Library, Mark 26

F06 Chapter Contents
F06 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F06CDF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
10 Example

1 Purpose

F06CDF reconstructs the parameters c (complex) and s (real) of a complex plane rotation from the tangent of that rotation.

2 Specification

SUBROUTINE F06CDF ( T, C, S)
REAL (KIND=nag_wp) | S
COMPLEX (KIND=nag_wp) | T, C

3 Description

F06CDF reconstructs the parameters c (complex) and s (real) of a complex plane rotation, from the value of the tangent t, as returned by F06CBF:
c=sign Re t t t⁢1+t 2 ,  s=ct.
If t<ε, where ε is the machine precision, the routine sets:
c=sign Re t t t,  s=sign Re t t.

4 References

None.

5 Arguments

1:   T – COMPLEX (KIND=nag_wp)Input
On entry: the value t, the tangent of the rotation.
2:   C – COMPLEX (KIND=nag_wp)Output
On exit: the value c, the cosine of the rotation.
3:   S – REAL (KIND=nag_wp)Output
On exit: the value s, the sine of the rotation.

6 Error Indicators and Warnings

None.

7 Accuracy

Not applicable.

8 Parallelism and Performance

F06CDF is not threaded in any implementation.

9 Further Comments

None.

10 Example

None.
F06 Chapter Contents
F06 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F06CHF : NAG Library, Mark 26

F06 Chapter Contents
F06 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F06CHF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
10 Example

1 Purpose

F06CHF applies a complex similarity rotation having real cosine and complex sine to a 2 by 2 complex Hermitian matrix.

2 Specification

SUBROUTINE F06CHF ( X, Y, Z, C, S)
REAL (KIND=nag_wp) | C
COMPLEX (KIND=nag_wp) | X, Y, Z, S

3 Description

F06CHF applies a complex similarity rotation, with parameters c (real) and s (complex), to a given 2 by 2 complex Hermitian matrix; that is, it performs the operation:
x y y- z ← c s- -s c x y y- z c -s- s c ,
where x and z are real.
The argument X and Z which hold x and z are declared complex for convenience when using the routine to operate on submatrices of larger Hermitian matrices.
Note that:
z y- y x ← c w- -w c z y- y x c -w- w c ,
where w=-s-, so to use F06CHF when y is the 2,1 element of the matrix, you can make the call
CALL F06CHF(Z, Y, X, C, -CONJG(S))

4 References

None.

5 Arguments

1:   X – COMPLEX (KIND=nag_wp)Input/Output
On entry: the value x, the 1,1 element of the input matrix.
On exit: the transformed value x.
2:   Y – COMPLEX (KIND=nag_wp)Input/Output
On entry: the value y, the 1,2 element of the input matrix.
On exit: the transformed value y.
3:   Z – COMPLEX (KIND=nag_wp)Input/Output
On entry: the value z, the 2,2 element of the input matrix.
On exit: the transformed value z.
4:   C – REAL (KIND=nag_wp)Input
On entry: the value c, the cosine of the rotation.
5:   S – COMPLEX (KIND=nag_wp)Input
On entry: the value s, the sine of the rotation.

6 Error Indicators and Warnings

None.

7 Accuracy

Not applicable.

8 Parallelism and Performance

F06CHF is not threaded in any implementation.

9 Further Comments

None.

10 Example

None.
F06 Chapter Contents
F06 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F06CLF : NAG Library, Mark 26

F06 Chapter Contents
F06 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F06CLF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
10 Example

1 Purpose

F06CLF computes the quotient of two complex scalars.

2 Specification

FUNCTION F06CLF ( A, B, FAIL)
COMPLEX (KIND=nag_wp) F06CLF
COMPLEX (KIND=nag_wp) | A, B
LOGICAL | FAIL

3 Description

F06CLF returns the value q via the function name, where
q= a/b, if ​a/b​ does not overflow, 0, if ​a=0, cflmax, if ​a≠0​ and ​a/b​ would overflow.
Here cflmax is a large complex value, given by
cflmax=flmax×sign Re a/b,flmax×sign Im a/b;
flmax is the real value given by 1/X02AMF, and for real x, sign x/0 is taken as sign⁡x.

4 References

None.

5 Arguments

1:   A – COMPLEX (KIND=nag_wp)Input
On entry: the value a.
2:   B – COMPLEX (KIND=nag_wp)Input
On entry: the value b.
3:   FAIL – LOGICALOutput
On exit: .TRUE. if a/b would overflow (in which case Re q=Im q=flmax) or a=b=0 (in which case q=0); otherwise .FALSE..

6 Error Indicators and Warnings

None.

7 Accuracy

Not applicable.

8 Parallelism and Performance

F06CLF is not threaded in any implementation.

9 Further Comments

None.

10 Example

None.
F06 Chapter Contents
F06 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F06 Chapter Contents : NAG Library Manual, Mark 26

F06 Chapter Introduction
NAG Library Manual

NAG Library Chapter Contents

F06 – Linear Algebra Support Routines

F06 Chapter Introduction – a description of the Chapter and an overview of the algorithms available

Routine Name | Mark of Introduction | Purpose
F06AAF (DROTG) | 12 | DROTG nagf_blas_drotg Generate real plane rotation
F06BAF | 12 | nagf_blas_drotgc Generate real plane rotation, storing tangent
F06BCF | 12 | nagf_blas_dcsg Recover cosine and sine from given real tangent
F06BEF | 12 | nagf_blas_drotj Generate real Jacobi plane rotation
F06BHF | 12 | nagf_blas_drot2 Apply real similarity rotation to 2 by 2 symmetric matrix
F06BLF | 12 | nagf_blas_ddiv Compute quotient of two real scalars, with overflow flag
F06BMF | 12 | nagf_blas_dnorm Compute Euclidean norm from scaled form
F06BNF | 12 | nagf_blas_dpyth Compute square root of a 2+b 2, real a and b
F06BPF | 12 | nagf_blas_deig2 Compute eigenvalue of 2 by 2 real symmetric matrix
F06CAF | 12 | nagf_blas_zrotgc Generate complex plane rotation, storing tangent, real cosine
F06CBF | 12 | nagf_blas_zrotgs Generate complex plane rotation, storing tangent, real sine
F06CCF | 12 | nagf_blas_zcsg Recover cosine and sine from given complex tangent, real cosine
F06CDF | 12 | nagf_blas_zcsgs Recover cosine and sine from given complex tangent, real sine
F06CHF | 12 | nagf_blas_zrot2 Apply complex similarity rotation to 2 by 2 Hermitian matrix
F06CLF | 12 | nagf_blas_zdiv Compute quotient of two complex scalars, with overflow flag
F06DBF | 12 | nagf_blas_iload Broadcast scalar into integer vector
F06DFF | 12 | nagf_blas_icopy Copy integer vector
F06EAF (DDOT) | 12 | DDOT nagf_blas_ddot Dot product of two real vectors
F06ECF (DAXPY) | 12 | DAXPY nagf_blas_daxpy Add scalar times real vector to real vector
F06EDF (DSCAL) | 12 | DSCAL nagf_blas_dscal Multiply real vector by scalar
F06EFF (DCOPY) | 12 | DCOPY nagf_blas_dcopy Copy real vector
F06EGF (DSWAP) | 12 | DSWAP nagf_blas_dswap Swap two real vectors
F06EJF (DNRM2) | 12 | DNRM2 nagf_blas_dnrm2 Compute Euclidean norm of real vector
F06EKF (DASUM) | 12 | DASUM nagf_blas_dasum Sum absolute values of real vector elements
F06EPF (DROT) | 12 | DROT nagf_blas_drot Apply real plane rotation
F06ERF (DDOTI) | 14 | DDOTI nagf_blas_ddoti Dot product of a real sparse and a full vector
F06ETF (DAXPYI) | 14 | DAXPYI nagf_blas_daxpyi Add scalar times real sparse vector to a full vector
F06EUF (DGTHR) | 14 | DGTHR nagf_blas_dgthr Gather real sparse vector
F06EVF (DGTHRZ) | 14 | DGTHRZ nagf_blas_dgthrz Gather and set to zero real sparse vector
F06EWF (DSCTR) | 14 | DSCTR nagf_blas_dsctr Scatter real sparse vector
F06EXF (DROTI) | 14 | DROTI nagf_blas_droti Apply plane rotation to a real sparse and a full vector
F06FAF | 12 | nagf_blas_dvcos Compute cosine of angle between two real vectors
F06FBF | 12 | nagf_blas_dload Broadcast scalar into real vector
F06FCF | 12 | nagf_blas_ddscl Multiply real vector by diagonal matrix
F06FDF | 12 | nagf_blas_axpzy Multiply real vector by scalar, preserving input vector
F06FEF | 21 | nagf_blas_drscl Multiply real vector by reciprocal of scalar
F06FGF | 12 | nagf_blas_dnegv Negate real vector
F06FJF | 12 | nagf_blas_dssq Update Euclidean norm of real vector in scaled form
F06FKF | 12 | nagf_blas_dnrm2w Compute weighted Euclidean norm of real vector
F06FLF | 12 | nagf_blas_darang Elements of real vector with largest and smallest absolute value
F06FPF | 12 | nagf_blas_drots Apply real symmetric plane rotation to two vectors
F06FQF | 12 | nagf_blas_dsrotg Generate sequence of real plane rotations
F06FRF | 12 | nagf_blas_dnhousg Generate real elementary reflection, NAG style
F06FSF | 12 | nagf_blas_dlhousg Generate real elementary reflection, LINPACK style
F06FTF | 12 | nagf_blas_dnhous Apply real elementary reflection, NAG style
F06FUF | 12 | nagf_blas_dlhous Apply real elementary reflection, LINPACK style
F06GAF (ZDOTU) | 12 | ZDOTU nagf_blas_zdotu Dot product of two complex vectors, unconjugated
F06GBF (ZDOTC) | 12 | ZDOTC nagf_blas_zdotc Dot product of two complex vectors, conjugated
F06GCF (ZAXPY) | 12 | ZAXPY nagf_blas_zaxpy Add scalar times complex vector to complex vector
F06GDF (ZSCAL) | 12 | ZSCAL nagf_blas_zscal Multiply complex vector by complex scalar
F06GFF (ZCOPY) | 12 | ZCOPY nagf_blas_zcopy Copy complex vector
F06GGF (ZSWAP) | 12 | ZSWAP nagf_blas_zswap Swap two complex vectors
F06GRF (ZDOTUI) | 14 | ZDOTUI nagf_blas_zdotui Dot product of a complex sparse and a full vector, unconjugated
F06GSF (ZDOTCI) | 14 | ZDOTCI nagf_blas_zdotci Dot product of a complex sparse and a full vector, conjugated
F06GTF (ZAXPYI) | 14 | ZAXPYI nagf_blas_zaxpyi Add scalar times complex sparse vector to a full vector
F06GUF (ZGTHR) | 14 | ZGTHR nagf_blas_zgthr Gather complex sparse vector
F06GVF (ZGTHRZ) | 14 | ZGTHRZ nagf_blas_zgthrz Gather and set to zero complex sparse vector
F06GWF (ZSCTR) | 14 | ZSCTR nagf_blas_zsctr Scatter complex sparse vector
F06HBF | 12 | nagf_blas_zload Broadcast scalar into complex vector
F06HCF | 12 | nagf_blas_zdscl Multiply complex vector by complex diagonal matrix
F06HDF | 12 | nagf_blas_zaxpzy Multiply complex vector by complex scalar, preserving input vector
F06HGF | 12 | nagf_blas_znegv Negate complex vector
F06HMF (ZROT) | 21 | ZROT nagf_blas_zrot Apply plane rotation with real cosine and complex sine
F06HPF | 12 | nagf_blas_zcrot Apply complex plane rotation
F06HQF | 12 | nagf_blas_zsrotg Generate sequence of complex plane rotations
F06HRF | 12 | nagf_blas_zhousg Generate complex elementary reflection
F06HTF | 12 | nagf_blas_zhous Apply complex elementary reflection
F06JDF (ZDSCAL) | 12 | ZDSCAL nagf_blas_zdscal Multiply complex vector by real scalar
F06JJF (DZNRM2) | 12 | DZNRM2 nagf_blas_dznrm2 Compute Euclidean norm of complex vector
F06JKF (DZASUM) | 12 | DZASUM nagf_blas_dzasum Sum absolute values of complex vector elements
F06JLF (IDAMAX) | 12 | IDAMAX nagf_blas_idamax Index, real vector element with largest absolute value
F06JMF (IZAMAX) | 12 | IZAMAX nagf_blas_izamax Index, complex vector element with largest absolute value
F06KCF | 12 | nagf_blas_zddscl Multiply complex vector by real diagonal matrix
F06KDF | 12 | nagf_blas_zdaxpzy Multiply complex vector by real scalar, preserving input vector
F06KEF | 21 | nagf_blas_zdrscl Multiply complex vector by reciprocal of real scalar
F06KFF | 12 | nagf_blas_zdcopy Copy real vector to complex vector
F06KJF | 12 | nagf_blas_dzssq Update Euclidean norm of complex vector in scaled form
F06KLF | 12 | nagf_blas_idrank Last non-negligible element of real vector
F06KPF (ZDROT) | 12 | ZDROT nagf_blas_zdrot Apply real plane rotation to two complex vectors
F06PAF (DGEMV) | 12 | DGEMV nagf_blas_dgemv Matrix-vector product, real rectangular matrix
F06PBF (DGBMV) | 12 | DGBMV nagf_blas_dgbmv Matrix-vector product, real rectangular band matrix
F06PCF (DSYMV) | 12 | DSYMV nagf_blas_dsymv Matrix-vector product, real symmetric matrix
F06PDF (DSBMV) | 12 | DSBMV nagf_blas_dsbmv Matrix-vector product, real symmetric band matrix
F06PEF (DSPMV) | 12 | DSPMV nagf_blas_dspmv Matrix-vector product, real symmetric packed matrix
F06PFF (DTRMV) | 12 | DTRMV nagf_blas_dtrmv Matrix-vector product, real triangular matrix
F06PGF (DTBMV) | 12 | DTBMV nagf_blas_dtbmv Matrix-vector product, real triangular band matrix
F06PHF (DTPMV) | 12 | DTPMV nagf_blas_dtpmv Matrix-vector product, real triangular packed matrix
F06PJF (DTRSV) | 12 | DTRSV nagf_blas_dtrsv System of equations, real triangular matrix
F06PKF (DTBSV) | 12 | DTBSV nagf_blas_dtbsv System of equations, real triangular band matrix
F06PLF (DTPSV) | 12 | DTPSV nagf_blas_dtpsv System of equations, real triangular packed matrix
F06PMF (DGER) | 12 | DGER nagf_blas_dger Rank-1 update, real rectangular matrix
F06PPF (DSYR) | 12 | DSYR nagf_blas_dsyr Rank-1 update, real symmetric matrix
F06PQF (DSPR) | 12 | DSPR nagf_blas_dspr Rank-1 update, real symmetric packed matrix
F06PRF (DSYR2) | 12 | DSYR2 nagf_blas_dsyr2 Rank-2 update, real symmetric matrix
F06PSF (DSPR2) | 12 | DSPR2 nagf_blas_dspr2 Rank-2 update, real symmetric packed matrix
F06QFF | 13 | nagf_blas_dmcopy Matrix copy, real rectangular or trapezoidal matrix
F06QHF | 13 | nagf_blas_dmload Matrix initialization, real rectangular matrix
F06QJF | 13 | nagf_blas_dgeap Permute rows or columns, real rectangular matrix, permutations represented by an integer array
F06QKF | 13 | nagf_blas_dgeapr Permute rows or columns, real rectangular matrix, permutations represented by a real array
F06QMF | 13 | nagf_blas_dsysrc Orthogonal similarity transformation of real symmetric matrix as a sequence of plane rotations
F06QPF | 13 | nagf_blas_dutr1 QR factorization by sequence of plane rotations, rank-1 update of real upper triangular matrix
F06QQF | 13 | nagf_blas_dutupd QR factorization by sequence of plane rotations, real upper triangular matrix augmented by a full row
F06QRF | 13 | nagf_blas_duhqr QR or RQ factorization by sequence of plane rotations, real upper Hessenberg matrix
F06QSF | 13 | nagf_blas_dusqr QR or RQ factorization by sequence of plane rotations, real upper spiked matrix
F06QTF | 13 | nagf_blas_dutsqr QR factorization of UP or RQ factorization of PU, U real upper triangular, P a sequence of plane rotations
F06QVF | 13 | nagf_blas_dutsrh Compute upper Hessenberg matrix by sequence of plane rotations, real upper triangular matrix
F06QWF | 13 | nagf_blas_dutsrs Compute upper spiked matrix by sequence of plane rotations, real upper triangular matrix
F06QXF | 13 | nagf_blas_dgesrc Apply sequence of plane rotations, real rectangular matrix
F06RAF | 15 | nagf_blas_dlange 1-norm, ∞-norm, Frobenius norm, largest absolute element, real general matrix
F06RBF | 15 | nagf_blas_dlangb 1-norm, ∞-norm, Frobenius norm, largest absolute element, real band matrix
F06RCF | 15 | nagf_blas_dlansy 1-norm, ∞-norm, Frobenius norm, largest absolute element, real symmetric matrix
F06RDF | 15 | nagf_blas_dlansp 1-norm, ∞-norm, Frobenius norm, largest absolute element, real symmetric matrix, packed storage
F06REF | 15 | nagf_blas_dlansb 1-norm, ∞-norm, Frobenius norm, largest absolute element, real symmetric band matrix
F06RJF | 15 | nagf_blas_dlantr 1-norm, ∞-norm, Frobenius norm, largest absolute element, real trapezoidal/triangular matrix
F06RKF | 15 | nagf_blas_dlantp 1-norm, ∞-norm, Frobenius norm, largest absolute element, real triangular matrix, packed storage
F06RLF | 15 | nagf_blas_dlantb 1-norm, ∞-norm, Frobenius norm, largest absolute element, real triangular band matrix
F06RMF | 15 | nagf_blas_dlanhs 1-norm, ∞-norm, Frobenius norm, largest absolute element, real upper Hessenberg matrix
F06RNF | 21 | nagf_blas_dlangt 1-norm, ∞-norm, Frobenius norm, largest absolute element, real tridiagonal matrix
F06RPF | 21 | nagf_blas_dlanst 1-norm, ∞-norm, Frobenius norm, largest absolute element, real symmetric tridiagonal matrix
F06SAF (ZGEMV) | 12 | ZGEMV nagf_blas_zgemv Matrix-vector product, complex rectangular matrix
F06SBF (ZGBMV) | 12 | ZGBMV nagf_blas_zgbmv Matrix-vector product, complex rectangular band matrix
F06SCF (ZHEMV) | 12 | ZHEMV nagf_blas_zhemv Matrix-vector product, complex Hermitian matrix
F06SDF (ZHBMV) | 12 | ZHBMV nagf_blas_zhbmv Matrix-vector product, complex Hermitian band matrix
F06SEF (ZHPMV) | 12 | ZHPMV nagf_blas_zhpmv Matrix-vector product, complex Hermitian packed matrix
F06SFF (ZTRMV) | 12 | ZTRMV nagf_blas_ztrmv Matrix-vector product, complex triangular matrix
F06SGF (ZTBMV) | 12 | ZTBMV nagf_blas_ztbmv Matrix-vector product, complex triangular band matrix
F06SHF (ZTPMV) | 12 | ZTPMV nagf_blas_ztpmv Matrix-vector product, complex triangular packed matrix
F06SJF (ZTRSV) | 12 | ZTRSV nagf_blas_ztrsv System of equations, complex triangular matrix
F06SKF (ZTBSV) | 12 | ZTBSV nagf_blas_ztbsv System of equations, complex triangular band matrix
F06SLF (ZTPSV) | 12 | ZTPSV nagf_blas_ztpsv System of equations, complex triangular packed matrix
F06SMF (ZGERU) | 12 | ZGERU nagf_blas_zgeru Rank-1 update, complex rectangular matrix, unconjugated vector
F06SNF (ZGERC) | 12 | ZGERC nagf_blas_zgerc Rank-1 update, complex rectangular matrix, conjugated vector
F06SPF (ZHER) | 12 | ZHER nagf_blas_zher Rank-1 update, complex Hermitian matrix
F06SQF (ZHPR) | 12 | ZHPR nagf_blas_zhpr Rank-1 update, complex Hermitian packed matrix
F06SRF (ZHER2) | 12 | ZHER2 nagf_blas_zher2 Rank-2 update, complex Hermitian matrix
F06SSF (ZHPR2) | 12 | ZHPR2 nagf_blas_zhpr2 Rank-2 update, complex Hermitian packed matrix
F06TAF | 21 | nagf_blas_zsymv Matrix-vector product, complex symmetric matrix
F06TBF | 21 | nagf_blas_zsyr Rank-1 update, complex symmetric matrix
F06TCF | 21 | nagf_blas_zspmv Matrix-vector product, complex symmetric packed matrix
F06TDF | 21 | nagf_blas_zspr Rank-1 update, complex symmetric packed matrix
F06TFF | 13 | nagf_blas_zmcopy Matrix copy, complex rectangular or trapezoidal matrix
F06THF | 13 | nagf_blas_zmload Matrix initialization, complex rectangular matrix
F06TMF | 13 | nagf_blas_zhesrc Unitary similarity transformation of Hermitian matrix as a sequence of plane rotations
F06TPF | 13 | nagf_blas_zutr1 QR factorization by sequence of plane rotations, rank-1 update of complex upper triangular matrix
F06TQF | 13 | nagf_blas_zutupd QR factorization by sequence of plane rotations, complex upper triangular matrix augmented by a full row
F06TRF | 13 | nagf_blas_zuhqr QR or RQ factorization by sequence of plane rotations, complex upper Hessenberg matrix
F06TSF | 13 | nagf_blas_zusqr QR or RQ factorization by sequence of plane rotations, complex upper spiked matrix
F06TTF | 13 | nagf_blas_zutsqr QR factorization of UP or RQ factorization of PU, U complex upper triangular, P a sequence of plane rotations
F06TVF | 13 | nagf_blas_zutsrh Compute upper Hessenberg matrix by sequence of plane rotations, complex upper triangular matrix
F06TWF | 13 | nagf_blas_zutsrs Compute upper spiked matrix by sequence of plane rotations, complex upper triangular matrix
F06TXF | 13 | nagf_blas_zgesrc Apply sequence of plane rotations, complex rectangular matrix, real cosine and complex sine
F06TYF | 13 | nagf_blas_zgesrs Apply sequence of plane rotations, complex rectangular matrix, complex cosine and real sine
F06UAF | 15 | nagf_blas_zlange 1-norm, ∞-norm, Frobenius norm, largest absolute element, complex general matrix
F06UBF | 15 | nagf_blas_zlangb 1-norm, ∞-norm, Frobenius norm, largest absolute element, complex band matrix
F06UCF | 15 | nagf_blas_zlanhe 1-norm, ∞-norm, Frobenius norm, largest absolute element, complex Hermitian matrix
F06UDF | 15 | nagf_blas_zlanhp 1-norm, ∞-norm, Frobenius norm, largest absolute element, complex Hermitian matrix, packed storage
F06UEF | 15 | nagf_blas_zlanhb 1-norm, ∞-norm, Frobenius norm, largest absolute element, complex Hermitian band matrix
F06UFF | 15 | nagf_blas_zlansy 1-norm, ∞-norm, Frobenius norm, largest absolute element, complex symmetric matrix
F06UGF | 15 | nagf_blas_zlansp 1-norm, ∞-norm, Frobenius norm, largest absolute element, complex symmetric matrix, packed storage
F06UHF | 15 | nagf_blas_zlansb 1-norm, ∞-norm, Frobenius norm, largest absolute element, complex symmetric band matrix
F06UJF | 15 | nagf_blas_zlantr 1-norm, ∞-norm, Frobenius norm, largest absolute element, complex trapezoidal/triangular matrix
F06UKF | 15 | nagf_blas_zlantp 1-norm, ∞-norm, Frobenius norm, largest absolute element, complex triangular matrix, packed storage
F06ULF | 15 | nagf_blas_zlantb 1-norm, ∞-norm, Frobenius norm, largest absolute element, complex triangular band matrix
F06UMF | 15 | nagf_blas_zlanhs 1-norm, ∞-norm, Frobenius norm, largest absolute element, complex Hessenberg matrix
F06UNF | 21 | nagf_blas_zlangt 1-norm, ∞-norm, Frobenius norm, largest absolute element, complex tridiagonal matrix
F06UPF | 21 | nagf_blas_zlanht 1-norm, ∞-norm, Frobenius norm, largest absolute element, complex Hermitian tridiagonal matrix
F06VJF | 13 | nagf_blas_zgeap Permute rows or columns, complex rectangular matrix, permutations represented by an integer array
F06VKF | 13 | nagf_blas_zgeapr Permute rows or columns, complex rectangular matrix, permutations represented by a real array
F06VXF | 13 | nagf_blas_zsgesr Apply sequence of plane rotations, complex rectangular matrix, real cosine and sine
F06WAF (DLANSF) Example Text Example Data | 23 | DLANSF nagf_blas_dlansf 1-norm, ∞-norm, Frobenius norm, largest absolute element, real symmetric matrix, Rectangular Full Packed format
F06WBF (DTFSM) Example Text Example Data | 23 | DTFSM nagf_blas_dtfsm Solves a system of equations with multiple right-hand sides, real triangular coefficient matrix, Rectangular Full Packed format
F06WCF (DSFRK) Example Text Example Data | 23 | DSFRK nagf_blas_dsfrk Rank-k update of a real symmetric matrix, Rectangular Full Packed format
F06WNF (ZLANHF) Example Text Example Data | 23 | ZLANHF nagf_blas_zlanhf 1-norm, ∞-norm, Frobenius norm, largest absolute element, complex Hermitian matrix, Rectangular Full Packed format
F06WPF (ZTFSM) Example Text Example Data | 23 | ZTFSM nagf_blas_ztfsm Solves system of equations with multiple right-hand sides, complex triangular coefficient matrix, Rectangular Full Packed format
F06WQF (ZHFRK) Example Text Example Data | 23 | ZHFRK nagf_blas_zhfrk Rank-k update of a complex Hermitian matrix, Rectangular Full Packed format
F06YAF (DGEMM) | 14 | DGEMM nagf_blas_dgemm Matrix-matrix product, two real rectangular matrices
F06YCF (DSYMM) | 14 | DSYMM nagf_blas_dsymm Matrix-matrix product, one real symmetric matrix, one real rectangular matrix
F06YFF (DTRMM) | 14 | DTRMM nagf_blas_dtrmm Matrix-matrix product, one real triangular matrix, one real rectangular matrix
F06YJF (DTRSM) | 14 | DTRSM nagf_blas_dtrsm Solves a system of equations with multiple right-hand sides, real triangular coefficient matrix
F06YPF (DSYRK) | 14 | DSYRK nagf_blas_dsyrk Rank-k update of a real symmetric matrix
F06YRF (DSYR2K) | 14 | DSYR2K nagf_blas_dsyr2k Rank-2 k update of a real symmetric matrix
F06ZAF (ZGEMM) | 14 | ZGEMM nagf_blas_zgemm Matrix-matrix product, two complex rectangular matrices
F06ZCF (ZHEMM) | 14 | ZHEMM nagf_blas_zhemm Matrix-matrix product, one complex Hermitian matrix, one complex rectangular matrix
F06ZFF (ZTRMM) | 14 | ZTRMM nagf_blas_ztrmm Matrix-matrix product, one complex triangular matrix, one complex rectangular matrix
F06ZJF (ZTRSM) | 14 | ZTRSM nagf_blas_ztrsm Solves system of equations with multiple right-hand sides, complex triangular coefficient matrix
F06ZPF (ZHERK) | 14 | ZHERK nagf_blas_zherk Rank-k update of a complex Hermitian matrix
F06ZRF (ZHER2K) | 14 | ZHER2K nagf_blas_zher2k Rank-2 k update of a complex Hermitian matrix
F06ZTF (ZSYMM) | 14 | ZSYMM nagf_blas_zsymm Matrix-matrix product, one complex symmetric matrix, one complex rectangular matrix
F06ZUF (ZSYRK) | 14 | ZSYRK nagf_blas_zsyrk Rank-k update of a complex symmetric matrix
F06ZWF (ZSYR2K) | 14 | ZSYR2K nagf_blas_zsyr2k Rank-2 k update of a complex symmetric matrix
F06 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F06DBF : NAG Library, Mark 26

F06 Chapter Contents
F06 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F06DBF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
10 Example

1 Purpose

F06DBF broadcasts an integer scalar into an integer vector.

2 Specification

SUBROUTINE F06DBF ( N, CON, X, INCX)
INTEGER N, CON, X(*), INCX

3 Description

F06DBF performs the operation
x←α,α,…,α T,
where x is an n-element integer vector scattered with stride INCX.

4 References

None.

5 Arguments

1:   N – INTEGERInput
On entry: n, the number of elements in x.
2:   CON – INTEGERInput
On entry: the scalar α.
3:   X* – INTEGER arrayOutput
Note: the dimension of the array X must be at least max 1, 1+N-1 ×INCX .
On exit: the vector x. xi will be stored in X 1+i-1×INCX, for i=1,2,…,N.
Intermediate elements of X are unchanged.
4:   INCX – INTEGERInput
On entry: the increment in the subscripts of X between successive elements of x.
Constraint: INCX>0.

6 Error Indicators and Warnings

None.

7 Accuracy

Not applicable.

8 Parallelism and Performance

F06DBF is not threaded in any implementation.

9 Further Comments

None.

10 Example

None.
F06 Chapter Contents
F06 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F06DFF : NAG Library, Mark 26

F06 Chapter Contents
F06 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F06DFF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
10 Example

1 Purpose

F06DFF copies an integer vector.

2 Specification

SUBROUTINE F06DFF ( N, X, INCX, Y, INCY)
INTEGER N, X(*), INCX, Y(*), INCY

3 Description

F06DFF performs the operation
y←x
where x and y are n-element integer vectors scattered with stride INCX and INCY respectively.

4 References

None.

5 Arguments

1:   N – INTEGERInput
On entry: n, the number of elements in x and y.
2:   X* – INTEGER arrayInput
Note: the dimension of the array X must be at least max 1, 1+N-1 ×INCX .
On entry: the n-element vector x.
If INCX>0, xi must be stored in X 1+i-1×INCX, for i=1,2,…,N.
If INCX<0, xi must be stored in X 1-N-i×INCX, for i=1,2,…,N.
Intermediate elements of X are not referenced.
3:   INCX – INTEGERInput
On entry: the increment in the subscripts of X between successive elements of x.
4:   Y* – INTEGER arrayOutput
Note: the dimension of the array Y must be at least max 1, 1+N-1 ×INCY .
On exit: the vector y.
If INCY>0, yi will be stored in Y 1+i-1×INCY, for i=1,2,…,N.
If INCY<0, yi will be stored in Y 1-N-i×INCY, for i=1,2,…,N.
Intermediate elements of Y are unchanged.
5:   INCY – INTEGERInput
On entry: the increment in the subscripts of Y between successive elements of y.

6 Error Indicators and Warnings

None.

7 Accuracy

Not applicable.

8 Parallelism and Performance

F06DFF is not threaded in any implementation.

9 Further Comments

None.

10 Example

None.
F06 Chapter Contents
F06 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F06EAF (DDOT) : NAG Library, Mark 26

F06 Chapter Contents
F06 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F06EAF (DDOT)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
10 Example

1 Purpose

F06EAF (DDOT) computes the scalar product of two real vectors.

2 Specification

FUNCTION F06EAF ( N, X, INCX, Y, INCY)
REAL (KIND=nag_wp) F06EAF
INTEGER | N, INCX, INCY
REAL (KIND=nag_wp) | X(*), Y(*)
The routine may be called by its BLAS name ddot.

3 Description

F06EAF (DDOT) returns, via the function name, the value of the scalar product
xT y
where x and y are n-element real vectors scattered with stride INCX and INCY respectively.

4 References

Lawson C L, Hanson R J, Kincaid D R and Krogh F T (1979) Basic linear algebra supbrograms for Fortran usage ACM Trans. Math. Software 5 308–325

5 Arguments

1:   N – INTEGERInput
On entry: n, the number of elements in x and y.
2:   X* – REAL (KIND=nag_wp) arrayInput
Note: the dimension of the array X must be at least max 1, 1+N-1 ×INCX .
On entry: the n-element vector x.
If INCX>0, xi must be stored in X 1+i-1×INCX, for i=1,2,…,N.
If INCX<0, xi must be stored in X 1-N-i×INCX, for i=1,2,…,N.
Intermediate elements of X are not referenced.
3:   INCX – INTEGERInput
On entry: the increment in the subscripts of X between successive elements of x.
4:   Y* – REAL (KIND=nag_wp) arrayInput
Note: the dimension of the array Y must be at least max 1, 1+N-1 ×INCY .
On entry: the n-element vector y.
If INCY>0, yi must be stored in Y 1+i-1×INCY, for i=1,2,…,N.
If INCY<0, yi must be stored in Y 1-N-i×INCY, for i=1,2,…,N.
Intermediate elements of Y are not referenced.
5:   INCY – INTEGERInput
On entry: the increment in the subscripts of Y between successive elements of y.

6 Error Indicators and Warnings

None.

7 Accuracy

Not applicable.

8 Parallelism and Performance

F06EAF (DDOT) is not threaded in any implementation.

9 Further Comments

None.

10 Example

None.
F06 Chapter Contents
F06 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F06ECF (DAXPY) : NAG Library, Mark 26

F06 Chapter Contents
F06 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F06ECF (DAXPY)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
10 Example

1 Purpose

F06ECF (DAXPY) adds a scaled real vector to an unscaled real vector.

2 Specification

SUBROUTINE F06ECF ( N, ALPHA, X, INCX, Y, INCY)
INTEGER | N, INCX, INCY
REAL (KIND=nag_wp) | ALPHA, X(*), Y(*)
The routine may be called by its BLAS name daxpy.

3 Description

F06ECF (DAXPY) performs the operation
y←αx+y
where x and y are n-element real vectors scattered with stride INCX and INCY respectively, and α is a real scalar.

4 References

Lawson C L, Hanson R J, Kincaid D R and Krogh F T (1979) Basic linear algebra supbrograms for Fortran usage ACM Trans. Math. Software 5 308–325

5 Arguments

1:   N – INTEGERInput
On entry: n, the number of elements in x and y.
2:   ALPHA – REAL (KIND=nag_wp)Input
On entry: the scalar α.
3:   X* – REAL (KIND=nag_wp) arrayInput
Note: the dimension of the array X must be at least max 1, 1+N-1 ×INCX .
On entry: the n-element vector x.
If INCX>0, xi must be stored in X 1+i-1×INCX, for i=1,2,…,N.
If INCX<0, xi must be stored in X 1-N-i×INCX, for i=1,2,…,N.
Intermediate elements of X are not referenced.
4:   INCX – INTEGERInput
On entry: the increment in the subscripts of X between successive elements of x.
5:   Y* – REAL (KIND=nag_wp) arrayInput/Output
Note: the dimension of the array Y must be at least max 1, 1+N-1 ×INCY .
On entry: the n-element vector y.
If INCY>0, yi must be stored in Y 1+i-1×INCY, for i=1,2,…,N.
If INCY<0, yi must be stored in Y 1-N-i×INCY, for i=1,2,…,N.
Intermediate elements of Y are not referenced.
On exit: the updated vector y stored in the array elements used to supply the original vector y.
Intermediate elements of Y are unchanged.
6:   INCY – INTEGERInput
On entry: the increment in the subscripts of Y between successive elements of y.

6 Error Indicators and Warnings

None.

7 Accuracy

Not applicable.

8 Parallelism and Performance

F06ECF (DAXPY) is not threaded in any implementation.

9 Further Comments

None.

10 Example

None.
F06 Chapter Contents
F06 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F06EDF (DSCAL) : NAG Library, Mark 26

F06 Chapter Contents
F06 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F06EDF (DSCAL)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
10 Example

1 Purpose

F06EDF (DSCAL) multiplies a real vector by a real scalar.

2 Specification

SUBROUTINE F06EDF ( N, ALPHA, X, INCX)
INTEGER | N, INCX
REAL (KIND=nag_wp) | ALPHA, X(*)
The routine may be called by its BLAS name dscal.

3 Description

F06EDF (DSCAL) performs the operation
x←αx
where x is an n-element real vector scattered with stride INCX, and α is a real scalar.

4 References

Lawson C L, Hanson R J, Kincaid D R and Krogh F T (1979) Basic linear algebra supbrograms for Fortran usage ACM Trans. Math. Software 5 308–325

5 Arguments

1:   N – INTEGERInput
On entry: n, the number of elements in x.
2:   ALPHA – REAL (KIND=nag_wp)Input
On entry: the scalar α.
3:   X* – REAL (KIND=nag_wp) arrayInput/Output
Note: the dimension of the array X must be at least max 1, 1+N-1 ×INCX .
On entry: the n-element vector x. xi must be stored in X 1+i-1×INCX, for i=1,2,…,N.
Intermediate elements of X are not referenced.
On exit: the vector αx stored in the array elements used to supply the original vector x.
Intermediate elements of X are unchanged.
4:   INCX – INTEGERInput
On entry: the increment in the subscripts of X between successive elements of x.
Constraint: INCX>0.

6 Error Indicators and Warnings

None.

7 Accuracy

Not applicable.

8 Parallelism and Performance

F06EDF (DSCAL) is not threaded in any implementation.

9 Further Comments

None.

10 Example

None.
F06 Chapter Contents
F06 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F06EFF (DCOPY) : NAG Library, Mark 26

F06 Chapter Contents
F06 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F06EFF (DCOPY)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
10 Example

1 Purpose

F06EFF (DCOPY) makes a copy of a real vector.

2 Specification

SUBROUTINE F06EFF ( N, X, INCX, Y, INCY)
INTEGER | N, INCX, INCY
REAL (KIND=nag_wp) | X(*), Y(*)
The routine may be called by its BLAS name dcopy.

3 Description

F06EFF (DCOPY) performs the operation
y←x
where x and y are n-element real vectors scattered with stride INCX and INCY respectively.

4 References

Lawson C L, Hanson R J, Kincaid D R and Krogh F T (1979) Basic linear algebra supbrograms for Fortran usage ACM Trans. Math. Software 5 308–325

5 Arguments

1:   N – INTEGERInput
On entry: n, the number of elements in x and y.
2:   X* – REAL (KIND=nag_wp) arrayInput
Note: the dimension of the array X must be at least max 1, 1+N-1 ×INCX .
On entry: the n-element vector x.
If INCX>0, xi must be stored in X 1+i-1×INCX, for i=1,2,…,N.
If INCX<0, xi must be stored in X 1-N-i×INCX, for i=1,2,…,N.
Intermediate elements of X are not referenced.
3:   INCX – INTEGERInput
On entry: the increment in the subscripts of X between successive elements of x.
4:   Y* – REAL (KIND=nag_wp) arrayOutput
Note: the dimension of the array Y must be at least max 1, 1+N-1 ×INCY .
On exit: the vector y.
If INCY>0, yi will be stored in Y 1+i-1×INCY, for i=1,2,…,N.
If INCY<0, yi will be stored in Y 1-N-i×INCY, for i=1,2,…,N.
Intermediate elements of Y are unchanged.
5:   INCY – INTEGERInput
On entry: the increment in the subscripts of Y between successive elements of y.

6 Error Indicators and Warnings

None.

7 Accuracy

Not applicable.

8 Parallelism and Performance

F06EFF (DCOPY) is not threaded in any implementation.

9 Further Comments

None.

10 Example

None.
F06 Chapter Contents
F06 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F06EGF (DSWAP) : NAG Library, Mark 26

F06 Chapter Contents
F06 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F06EGF (DSWAP)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
10 Example

1 Purpose

F06EGF (DSWAP) interchanges two n-element real vectors x and y.

2 Specification

SUBROUTINE F06EGF ( N, X, INCX, Y, INCY)
INTEGER | N, INCX, INCY
REAL (KIND=nag_wp) | X(*), Y(*)
The routine may be called by its BLAS name dswap.

3 Description

F06EGF (DSWAP) interchanges the elements of real vectors x and y scattered with stride INCX and INCY respectively.

4 References

Lawson C L, Hanson R J, Kincaid D R and Krogh F T (1979) Basic linear algebra supbrograms for Fortran usage ACM Trans. Math. Software 5 308–325

5 Arguments

1:   N – INTEGERInput
On entry: n, the number of elements in x and y.
2:   X* – REAL (KIND=nag_wp) arrayInput/Output
Note: the dimension of the array X must be at least max 1, 1+N-1 ×INCX .
On entry: the n-element vector x.
If INCX>0, xi must be stored in X 1+i-1×INCX, for i=1,2,…,N.
If INCX<0, xi must be stored in X 1-N-i×INCX, for i=1,2,…,N.
Intermediate elements of X are not referenced.
On exit: the original vector y stored in the array elements used to supply the original vector x.
Intermediate elements of X are unchanged.
3:   INCX – INTEGERInput
On entry: the increment in the subscripts of X between successive elements of x.
4:   Y* – REAL (KIND=nag_wp) arrayInput/Output
Note: the dimension of the array Y must be at least max 1, 1+N-1 ×INCY .
On entry: the n-element vector y.
If INCY>0, yi must be stored in Y 1+i-1×INCY, for i=1,2,…,N.
If INCY<0, yi must be stored in Y 1-N-i×INCY, for i=1,2,…,N.
Intermediate elements of Y are not referenced.
On exit: the original vector x stored in the array elements used to supply the original vector y.
Intermediate elements of Y are unchanged.
5:   INCY – INTEGERInput
On entry: the increment in the subscripts of Y between successive elements of y.

6 Error Indicators and Warnings

None.

7 Accuracy

Not applicable.

8 Parallelism and Performance

F06EGF (DSWAP) is not threaded in any implementation.

9 Further Comments

None.

10 Example

None.
F06 Chapter Contents
F06 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F06EJF (DNRM2) : NAG Library, Mark 26

F06 Chapter Contents
F06 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F06EJF (DNRM2)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
10 Example

1 Purpose

F06EJF (DNRM2) returns the Euclidean norm of the n-element real vector x.

2 Specification

FUNCTION F06EJF ( N, X, INCX)
REAL (KIND=nag_wp) F06EJF
INTEGER | N, INCX
REAL (KIND=nag_wp) | X(*)
The routine may be called by its BLAS name dnrm2.

3 Description

F06EJF (DNRM2) returns, via the function name, the Euclidean norm
x 2=xT x
of the n-element real vector x scattered with stride INCX.

4 References

Lawson C L, Hanson R J, Kincaid D R and Krogh F T (1979) Basic linear algebra supbrograms for Fortran usage ACM Trans. Math. Software 5 308–325

5 Arguments

1:   N – INTEGERInput
On entry: n, the number of elements in x.
2:   X* – REAL (KIND=nag_wp) arrayInput
Note: the dimension of the array X must be at least max 1, 1+N-1 ×INCX .
On entry: the n-element vector x. xi must be stored in X 1+i-1×INCX, for i=1,2,…,N.
Intermediate elements of X are not referenced.
3:   INCX – INTEGERInput
On entry: the increment in the subscripts of X between successive elements of x.
Constraint: INCX>0.

6 Error Indicators and Warnings

None.

7 Accuracy

Not applicable.

8 Parallelism and Performance

F06EJF (DNRM2) is not threaded in any implementation.

9 Further Comments

None.

10 Example

None.
F06 Chapter Contents
F06 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F06EKF (DASUM) : NAG Library, Mark 26

F06 Chapter Contents
F06 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F06EKF (DASUM)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
10 Example

1 Purpose

F06EKF (DASUM) returns the 1-norm of the n-element real vector x.

2 Specification

FUNCTION F06EKF ( N, X, INCX)
REAL (KIND=nag_wp) F06EKF
INTEGER | N, INCX
REAL (KIND=nag_wp) | X(*)
The routine may be called by its BLAS name dasum.

3 Description

F06EKF (DASUM), returns via the function name, the 1-norm
x 1+x 2+⋯+xn
of the n-element real vector x scattered with stride INCX.

4 References

Lawson C L, Hanson R J, Kincaid D R and Krogh F T (1979) Basic linear algebra supbrograms for Fortran usage ACM Trans. Math. Software 5 308–325

5 Arguments

1:   N – INTEGERInput
On entry: n, the number of elements in x.
2:   X* – REAL (KIND=nag_wp) arrayInput
Note: the dimension of the array X must be at least max 1, 1+N-1 ×INCX .
On entry: the n-element vector x. xi must be stored in X 1+i-1×INCX, for i=1,2,…,N.
Intermediate elements of X are not referenced.
3:   INCX – INTEGERInput
On entry: the increment in the subscripts of X between successive elements of x.
Constraint: INCX>0.

6 Error Indicators and Warnings

None.

7 Accuracy

Not applicable.

8 Parallelism and Performance

F06EKF (DASUM) is not threaded in any implementation.

9 Further Comments

None.

10 Example

None.
F06 Chapter Contents
F06 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F06EPF (DROT) : NAG Library, Mark 26

F06 Chapter Contents
F06 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F06EPF (DROT)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
10 Example

1 Purpose

F06EPF (DROT) applies a real plane rotation to two real vectors.

2 Specification

SUBROUTINE F06EPF ( N, X, INCX, Y, INCY, C, S)
INTEGER | N, INCX, INCY
REAL (KIND=nag_wp) | X(*), Y(*), C, S
The routine may be called by its BLAS name drot.

3 Description

F06EPF (DROT) applies a real plane rotation to two n-element real vectors x and y:
xT yT ← c s -s c xT yT .
with stride INCX and INCY respectively. The plane rotation has the form generated by F06AAF (DROTG) or F06BAF.

4 References

Lawson C L, Hanson R J, Kincaid D R and Krogh F T (1979) Basic linear algebra supbrograms for Fortran usage ACM Trans. Math. Software 5 308–325

5 Arguments

1:   N – INTEGERInput
On entry: n, the number of elements in x and y.
2:   X* – REAL (KIND=nag_wp) arrayInput/Output
Note: the dimension of the array X must be at least max 1, 1+N-1 ×INCX .
On entry: the n-element vector x.
If INCX>0, xi must be stored in X 1+i-1×INCX, for i=1,2,…,N.
If INCX<0, xi must be stored in X 1-N-i×INCX, for i=1,2,…,N.
Intermediate elements of X are not referenced.
On exit: the transformed vector x stored in the array elements used to supply the original vector x.
Intermediate elements of X are unchanged.
3:   INCX – INTEGERInput
On entry: the increment in the subscripts of X between successive elements of x.
4:   Y* – REAL (KIND=nag_wp) arrayInput/Output
Note: the dimension of the array Y must be at least max 1, 1+N-1 ×INCY .
On entry: the n-element vector y.
If INCY>0, yi must be stored in Y 1+i-1×INCY, for i=1,2,…,N.
If INCY<0, yi must be stored in Y 1-N-i×INCY, for i=1,2,…,N.
Intermediate elements of Y are not referenced.
On exit: the transformed vector y stored in the array elements used to supply the original vector y.
Intermediate elements of Y are unchanged.
5:   INCY – INTEGERInput
On entry: the increment in the subscripts of Y between successive elements of y.
6:   C – REAL (KIND=nag_wp)Input
On entry: the value c, the cosine of the rotation.
7:   S – REAL (KIND=nag_wp)Input
On entry: the value s, the sine of the rotation.

6 Error Indicators and Warnings

None.

7 Accuracy

Not applicable.

8 Parallelism and Performance

F06EPF (DROT) is not threaded in any implementation.

9 Further Comments

None.

10 Example

None.
F06 Chapter Contents
F06 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F06ERF (DDOTI) : NAG Library, Mark 26

F06 Chapter Contents
F06 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F06ERF (DDOTI)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
10 Example

1 Purpose

F06ERF (DDOTI) computes the scalar product of a sparse real vector, stored in compressed form, with a real vector.

2 Specification

FUNCTION F06ERF ( NZ, X, INDX, Y)
REAL (KIND=nag_wp) F06ERF
INTEGER | NZ, INDX(*)
REAL (KIND=nag_wp) | X(*), Y(*)
The routine may be called by its BLAS name ddoti.

3 Description

F06ERF (DDOTI) returns, via the function name, the value of the scalar product
xT y = x 1 × y indx 1 + x 2 × y indy 2 + ⋯ + x nz × y indx nz
where x is a sparse real vector, stored in compressed form and y is a real vector in full storage format.

4 References

Dodson D S, Grimes R G and Lewis J G (1991) Sparse extensions to the Fortran basic linear algebra subprograms ACM Trans. Math. Software 17 253–263

5 Arguments

1:   NZ – INTEGERInput
On entry: the number of nonzeros in the sparse vector x.
2:   X* – REAL (KIND=nag_wp) arrayInput
Note: the dimension of the array X must be at least max 1,NZ .
On entry: the nonzero elements of the sparse vector x.
3:   INDX* – INTEGER arrayInput
Note: the dimension of the array INDX must be at least max 1,NZ .
On entry: INDX i must contain the index of X i in the sparse vector x, for i=1,2,…,NZ.
4:   Y* – REAL (KIND=nag_wp) arrayInput
Note: the dimension of the array Y must be at least maxk INDX k .
On entry: the vector y. Only elements corresponding to indices in INDX are accessed.

6 Error Indicators and Warnings

None.

7 Accuracy

Not applicable.

8 Parallelism and Performance

F06ERF (DDOTI) is not threaded in any implementation.

9 Further Comments

None.

10 Example

None.
F06 Chapter Contents
F06 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F06ETF (DAXPYI) : NAG Library, Mark 26

F06 Chapter Contents
F06 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F06ETF (DAXPYI)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
10 Example

1 Purpose

F06ETF (DAXPYI) adds a scaled sparse real vector, stored in compressed form, to an unscaled real vector.

2 Specification

SUBROUTINE F06ETF ( NZ, A, X, INDX, Y)
INTEGER | NZ, INDX(*)
REAL (KIND=nag_wp) | A, X(*), Y(*)
The routine may be called by its BLAS name daxpyi.

3 Description

F06ETF (DAXPYI) performs the operation
y←αx+y
where x is a sparse real vector, stored in compressed form, and y is a real vector in full storage form.

4 References

Dodson D S, Grimes R G and Lewis J G (1991) Sparse extensions to the Fortran basic linear algebra subprograms ACM Trans. Math. Software 17 253–263

5 Arguments

1:   NZ – INTEGERInput
On entry: the number of nonzeros in the sparse vector x.
2:   A – REAL (KIND=nag_wp)Input
On entry: the scalar α.
3:   X* – REAL (KIND=nag_wp) arrayInput
Note: the dimension of the array X must be at least max 1,NZ .
On entry: the nonzero elements of the sparse vector x.
4:   INDX* – INTEGER arrayInput
Note: the dimension of the array INDX must be at least max 1,NZ .
On entry: INDX i must contain the index of X i in the sparse vector x, for i=1,2,…,NZ.
Constraint: the indices must be distinct.
5:   Y* – REAL (KIND=nag_wp) arrayInput/Output
Note: the dimension of the array Y must be at least maxk INDX k .
On entry: the vector y. Only elements corresponding to indices in INDX are accessed.
On exit: the updated vector y.

6 Error Indicators and Warnings

None.

7 Accuracy

Not applicable.

8 Parallelism and Performance

F06ETF (DAXPYI) is not threaded in any implementation.

9 Further Comments

None.

10 Example

None.
F06 Chapter Contents
F06 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F06EUF (DGTHR) : NAG Library, Mark 26

F06 Chapter Contents
F06 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F06EUF (DGTHR)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
10 Example

1 Purpose

F06EUF (DGTHR) gathers specified (usually nonzero) elements of a real vector y in full storage form into a sparse real vector x in compressed form.

2 Specification

SUBROUTINE F06EUF ( NZ, Y, X, INDX)
INTEGER | NZ, INDX(*)
REAL (KIND=nag_wp) | Y(*), X(*)
The routine may be called by its BLAS name dgthr.

3 Description

F06EUF (DGTHR) gathers the specified elements of a vector, y, in full storage form, into x, the equivalent sparse vector compressed form.

4 References

Dodson D S, Grimes R G and Lewis J G (1991) Sparse extensions to the Fortran basic linear algebra subprograms ACM Trans. Math. Software 17 253–263

5 Arguments

1:   NZ – INTEGERInput
On entry: the number of nonzeros in the compressed sparse vector x.
2:   Y* – REAL (KIND=nag_wp) arrayInput
Note: the dimension of the array Y must be at least maxk INDX k .
On entry: the vector y. Only elements corresponding to indices in INDX are accessed.
3:   X* – REAL (KIND=nag_wp) arrayOutput
Note: the dimension of the array X must be at least max 1,NZ.
On exit: the compressed vector x.
4:   INDX* – INTEGER arrayInput
Note: the dimension of the array INDX must be at least max 1,NZ .
On entry: INDX i must contain the index Y i, for i=1,2,…,NZ, which is to be gathered into x.

6 Error Indicators and Warnings

None.

7 Accuracy

Not applicable.

8 Parallelism and Performance

F06EUF (DGTHR) is not threaded in any implementation.

9 Further Comments

None.

10 Example

None.
F06 Chapter Contents
F06 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F06EVF (DGTHRZ) : NAG Library, Mark 26

F06 Chapter Contents
F06 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F06EVF (DGTHRZ)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
10 Example

1 Purpose

F06EVF (DGTHRZ) gathers specified (usually nonzero) elements of a real vector y in full storage form into a sparse real vector x in compressed form. The specified elements of y are set to zero.

2 Specification

SUBROUTINE F06EVF ( NZ, Y, X, INDX)
INTEGER | NZ, INDX(*)
REAL (KIND=nag_wp) | Y(*), X(*)
The routine may be called by its BLAS name dgthrz.

3 Description

F06EVF (DGTHRZ) gathers the specified elements of a vector, y, in full storage form, into the equivalent sparse vector compressed form. The gathered elements of y are set to zero.

4 References

Dodson D S, Grimes R G and Lewis J G (1991) Sparse extensions to the Fortran basic linear algebra subprograms ACM Trans. Math. Software 17 253–263

5 Arguments

1:   NZ – INTEGERInput
On entry: the number of nonzeros in the compressed sparse vector x.
2:   Y* – REAL (KIND=nag_wp) arrayInput/Output
Note: the dimension of the array Y must be at least maxk INDX k .
On entry: the vector y. Only elements corresponding to indices in INDX are accessed.
On exit: the elements of y corresponding to indices in INDX are set to zero.
3:   X* – REAL (KIND=nag_wp) arrayOutput
Note: the dimension of the array X must be at least max 1,NZ.
On exit: the compressed vector x.
4:   INDX* – INTEGER arrayInput
Note: the dimension of the array INDX must be at least max 1,NZ .
On entry: INDX i must contain the index Y i, for i=1,2,…,NZ, which is to be gathered into x.
Constraint: the indices must be distinct.

6 Error Indicators and Warnings

None.

7 Accuracy

Not applicable.

8 Parallelism and Performance

F06EVF (DGTHRZ) is not threaded in any implementation.

9 Further Comments

None.

10 Example

None.
F06 Chapter Contents
F06 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F06EWF (DSCTR) : NAG Library, Mark 26

F06 Chapter Contents
F06 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F06EWF (DSCTR)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
10 Example

1 Purpose

F06EWF (DSCTR) scatters the elements of a sparse real vector x stored in compressed form, into a real vector y in full storage form.

2 Specification

SUBROUTINE F06EWF ( NZ, X, INDX, Y)
INTEGER | NZ, INDX(*)
REAL (KIND=nag_wp) | X(*), Y(*)
The routine may be called by its BLAS name dsctr.

3 Description

F06EWF (DSCTR) scatters the elements of a vector x, stored in compressed form, into a vector, y, in full storage form.

4 References

Dodson D S, Grimes R G and Lewis J G (1991) Sparse extensions to the Fortran basic linear algebra subprograms ACM Trans. Math. Software 17 253–263

5 Arguments

1:   NZ – INTEGERInput
On entry: the number of nonzeros in the sparse vector x.
2:   X* – REAL (KIND=nag_wp) arrayInput
Note: the dimension of the array X must be at least max 1,NZ .
On entry: the nonzero elements of the sparse vector x.
3:   INDX* – INTEGER arrayInput
Note: the dimension of the array INDX must be at least max 1,NZ .
On entry: INDX i must contain the index of X i in the sparse vector x, for i=1,2,…,NZ.
Constraint: the indices must be distinct.
4:   Y* – REAL (KIND=nag_wp) arrayOutput
Note: the dimension of the array Y must be at least maxk INDX k .
On exit: the vector y. Only elements corresponding to indices in INDX are altered.

6 Error Indicators and Warnings

None.

7 Accuracy

Not applicable.

8 Parallelism and Performance

F06EWF (DSCTR) is not threaded in any implementation.

9 Further Comments

None.

10 Example

None.
F06 Chapter Contents
F06 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F06EXF (DROTI) : NAG Library, Mark 26

F06 Chapter Contents
F06 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F06EXF (DROTI)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
10 Example

1 Purpose

F06EXF (DROTI) applies a real plane rotation to a sparse real vector and a real vector.

2 Specification

SUBROUTINE F06EXF ( NZ, X, INDX, Y, C, S)
INTEGER | NZ, INDX(*)
REAL (KIND=nag_wp) | X(*), Y(*), C, S
The routine may be called by its BLAS name droti.

3 Description

F06EXF (DROTI) applies a real plane rotation to a sparse real vector x stored in compressed form and a real vector y in full storage form:
xT yT ← c s -s c xT yT .
The plane rotation has the form generated by F06AAF (DROTG) or F06BAF.

4 References

Dodson D S, Grimes R G and Lewis J G (1991) Sparse extensions to the Fortran basic linear algebra subprograms ACM Trans. Math. Software 17 253–263

5 Arguments

1:   NZ – INTEGERInput
On entry: the number of nonzeros in the sparse vector x.
2:   X* – REAL (KIND=nag_wp) arrayInput/Output
Note: the dimension of the array X must be at least max 1,NZ .
On entry: the nonzero elements of the sparse vector x.
On exit: the transformed vector x.
3:   INDX* – INTEGER arrayInput
Note: the dimension of the array INDX must be at least max 1,NZ .
On entry: INDX i must contain the index of X i in the sparse vector x, for i=1,2,…,NZ.
Constraint: the indices must be distinct.
4:   Y* – REAL (KIND=nag_wp) arrayInput/Output
Note: the dimension of the array Y must be at least maxk INDX k .
On entry: the vector y. Only the elements corresponding to indices in INDX are referenced.
On exit: the transformed vector y. Only elements corresponding to indices in INDX are altered.
5:   C – REAL (KIND=nag_wp)Input
On entry: the value c, the cosine of the rotation.
6:   S – REAL (KIND=nag_wp)Input
On entry: the value s, the sine of the rotation.

6 Error Indicators and Warnings

None.

7 Accuracy

Not applicable.

8 Parallelism and Performance

F06EXF (DROTI) is not threaded in any implementation.

9 Further Comments

None.

10 Example

None.
F06 Chapter Contents
F06 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F06FAF : NAG Library, Mark 26

F06 Chapter Contents
F06 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F06FAF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
10 Example

1 Purpose

F06FAF computes the cosine of the angle between two real vectors.

2 Specification

FUNCTION F06FAF ( N, J, TOLX, X, INCX, TOLY, Y, INCY)
REAL (KIND=nag_wp) F06FAF
INTEGER | N, J, INCX, INCY
REAL (KIND=nag_wp) | TOLX, X(*), TOLY, Y(*)

3 Description

F06FAF returns, via the function name, the cosine of the angle between two n-element real vectors x and y, given by the expression
xT y x 2y 2 .
If 1≤j≤n, y is taken to be the unit vector ej, in which case the array Y is not referenced.
If x 2≤tolx, the routine returns 2.0; if x 2>tolx but y 2≤toly, the routine returns -2.0; otherwise the value returned is in the range -1.0,1.0.

4 References

None.

5 Arguments

1:   N – INTEGERInput
On entry: n, the number of elements in x and y.
2:   J – INTEGERInput
On entry: if the vector y is supplied in Y, J should be set to 0. Otherwise, J specifies the index j of the unit vector ej to be used as y.
3:   TOLX – REAL (KIND=nag_wp)Input
On entry: the value tolx, used to determine whether x 2 is effectively zero.
If TOLX is negative, the value zero is used.
4:   X* – REAL (KIND=nag_wp) arrayInput
Note: the dimension of the array X must be at least max 1, 1+N-1 ×INCX .
On entry: the n-element vector x.
If INCX>0, xi must be stored in X 1+i-1×INCX, for i=1,2,…,N.
If INCX<0, xi must be stored in X 1-N-i×INCX, for i=1,2,…,N.
Intermediate elements of X are not referenced.
5:   INCX – INTEGERInput
On entry: the increment in the subscripts of X between successive elements of x.
6:   TOLY – REAL (KIND=nag_wp)Input
On entry: the value toly, used to determine whether y 2 is effectively zero.
If TOLY is negative, the value zero is used.
7:   Y* – REAL (KIND=nag_wp) arrayInput
Note: the dimension of the array Y must be at least max 1, 1+N-1 ×INCY .
On entry: if 1≤J≤N, Y is not referenced. Otherwise, Y holds the vector y.
If INCY>0, yi must be stored in Y 1+i-1×INCY, for i=1,2,…,N.
If INCY<0, yi must be stored in Y 1-N-i×INCY, for i=1,2,…,N.
Intermediate elements of Y are not referenced.
8:   INCY – INTEGERInput
On entry: the increment in the subscripts of Y between successive elements of y.

6 Error Indicators and Warnings

None.

7 Accuracy

Not applicable.

8 Parallelism and Performance

F06FAF is not threaded in any implementation.

9 Further Comments

None.

10 Example

None.
F06 Chapter Contents
F06 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F06FBF : NAG Library, Mark 26

F06 Chapter Contents
F06 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F06FBF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
10 Example

1 Purpose

F06FBF broadcasts a real scalar into a real vector.

2 Specification

SUBROUTINE F06FBF ( N, CON, X, INCX)
INTEGER | N, INCX
REAL (KIND=nag_wp) | CON, X(*)

3 Description

F06FBF performs the operation
x←α,α,…,α T,
where x is an n-element real vector.

4 References

None.

5 Arguments

1:   N – INTEGERInput
On entry: n, the number of elements in x.
2:   CON – REAL (KIND=nag_wp)Input
On entry: the scalar α.
3:   X* – REAL (KIND=nag_wp) arrayOutput
Note: the dimension of the array X must be at least max 1, 1+N-1 ×INCX .
On exit: the vector x. xi will be stored in X 1+i-1×INCX, for i=1,2,…,N.
Intermediate elements of X are unchanged.
4:   INCX – INTEGERInput
On entry: the increment in the subscripts of X between successive elements of x.
Constraint: INCX>0.

6 Error Indicators and Warnings

None.

7 Accuracy

Not applicable.

8 Parallelism and Performance

F06FBF is not threaded in any implementation.

9 Further Comments

None.

10 Example

None.
F06 Chapter Contents
F06 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F06FCF : NAG Library, Mark 26

F06 Chapter Contents
F06 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F06FCF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
10 Example

1 Purpose

F06FCF multiplies a real vector by a real diagonal matrix.

2 Specification

SUBROUTINE F06FCF ( N, D, INCD, X, INCX)
INTEGER | N, INCD, INCX
REAL (KIND=nag_wp) | D(*), X(*)

3 Description

F06FCF performs the operation
x←Dx
where x is an n-element real vector and D=diag d is a real diagonal matrix.
Equivalently, the routine performs the element-by-element product of the vectors x and d
xi=dixi,   i=1,2,…,n.

4 References

None.

5 Arguments

1:   N – INTEGERInput
On entry: n, the number of elements in d and x.
2:   D* – REAL (KIND=nag_wp) arrayInput
Note: the dimension of the array D must be at least max 1, 1+N-1 ×INCD .
On entry: the vector d.
If INCD>0, di must be stored in D i-1×INCD+1 , for i=1,2,…,N.
If INCD<0, di must be stored in D 1-N-i×INCD , for i=1,2,…,N.
3:   INCD – INTEGERInput
On entry: the increment in the subscripts of D between successive elements of d.
4:   X* – REAL (KIND=nag_wp) arrayInput/Output
Note: the dimension of the array X must be at least max 1, 1+N-1 ×INCX .
On entry: the array X must contain the n-element vector x.
If INCX>0, xi must be stored in X 1+i-1×INCX , for i=1,2,…,N.
If INCX<0, xi must be stored in X 1-N-i×INCX , for i=1,2,…,N.
On exit: the updated vector x stored in the array elements used to supply the original vector x.
Intermediate elements of X are unchanged.
5:   INCX – INTEGERInput
On entry: the increment in the subscripts of X between successive elements of x.

6 Error Indicators and Warnings

None.

7 Accuracy

Not applicable.

8 Parallelism and Performance

F06FCF makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

None.

10 Example

None.
F06 Chapter Contents
F06 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F06FDF : NAG Library, Mark 26

F06 Chapter Contents
F06 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F06FDF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
10 Example

1 Purpose

F06FDF multiplies a real vector by a scalar, preserving the input vector.

2 Specification

SUBROUTINE F06FDF ( N, ALPHA, X, INCX, Y, INCY)
INTEGER | N, INCX, INCY
REAL (KIND=nag_wp) | ALPHA, X(*), Y(*)

3 Description

F06FDF performs the operation
y←αx
where x and y are n-element real vectors scattered with stride INCX and INCY respectively, and α is a real scalar.

4 References

None.

5 Arguments

1:   N – INTEGERInput
On entry: n, the number of elements in x and y.
2:   ALPHA – REAL (KIND=nag_wp)Input
On entry: the scalar α.
3:   X* – REAL (KIND=nag_wp) arrayInput
Note: the dimension of the array X must be at least max 1, 1+N-1 ×INCX .
On entry: the n-element vector x.
If INCX>0, xi must be stored in X 1+i-1×INCX, for i=1,2,…,N.
If INCX<0, xi must be stored in X 1-N-i×INCX, for i=1,2,…,N.
Intermediate elements of X are not referenced.
4:   INCX – INTEGERInput
On entry: the increment in the subscripts of X between successive elements of x.
5:   Y* – REAL (KIND=nag_wp) arrayOutput
Note: the dimension of the array Y must be at least max 1, 1+N-1 ×INCY .
On exit: the vector y.
If INCY>0, yi will be stored in Y 1+i-1×INCY, for i=1,2,…,N.
If INCY<0, yi will be stored in Y 1-N-i×INCY, for i=1,2,…,N.
Intermediate elements of Y are unchanged.
6:   INCY – INTEGERInput
On entry: the increment in the subscripts of Y between successive elements of y.

6 Error Indicators and Warnings

None.

7 Accuracy

Not applicable.

8 Parallelism and Performance

F06FDF is not threaded in any implementation.

9 Further Comments

None.

10 Example

None.
F06 Chapter Contents
F06 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F06FEF : NAG Library, Mark 26

F06 Chapter Contents
F06 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F06FEF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
10 Example

1 Purpose

F06FEF multiplies a real vector by the reciprocal of a scalar.

2 Specification

SUBROUTINE F06FEF ( N, ALPHA, X, INCX)
INTEGER | N, INCX
REAL (KIND=nag_wp) | ALPHA, X(*)

3 Description

F06FEF performs the operation
x←1 α x
where x is an n-element real vector scattered with stride INCX and α is a real nonzero scalar.

4 References

None.

5 Arguments

1:   N – INTEGERInput
On entry: n, the number of elements in x.
2:   ALPHA – REAL (KIND=nag_wp)Input
On entry: the scalar α.
Constraint: ALPHA≠0.0.
3:   X* – REAL (KIND=nag_wp) arrayInput/Output
Note: the dimension of the array X must be at least max 1, 1+N-1 ×INCX .
On entry: the n-element vector x. xi must be stored in X 1+i-1×INCX, for i=1,2,…,N.
Intermediate elements of X are not referenced.
On exit: the updated vector x, stored in the same array elements used to supply the original vector.
4:   INCX – INTEGERInput
On entry: the increment in the subscripts of X between successive elements of x.
Constraint: INCX>0.

6 Error Indicators and Warnings

None.

7 Accuracy

Not applicable.

8 Parallelism and Performance

F06FEF makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

None.

10 Example

None.
F06 Chapter Contents
F06 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F06FGF : NAG Library, Mark 26

F06 Chapter Contents
F06 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F06FGF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
10 Example

1 Purpose

F06FGF negates a real vector.

2 Specification

SUBROUTINE F06FGF ( N, X, INCX)
INTEGER | N, INCX
REAL (KIND=nag_wp) | X(*)

3 Description

F06FGF performs the operation
x←-x
where x is an n-element real vector scattered with stride INCX.

4 References

None.

5 Arguments

1:   N – INTEGERInput
On entry: n, the number of elements in x.
2:   X* – REAL (KIND=nag_wp) arrayInput/Output
Note: the dimension of the array X must be at least max 1, 1+N-1 ×INCX .
On entry: the n-element vector x. xi must be stored in X 1+i-1×INCX, for i=1,2,…,N.
Intermediate elements of X are not referenced.
On exit: the vector -x stored in the array elements used to supply the original vector x.
Intermediate elements of X are unchanged.
3:   INCX – INTEGERInput
On entry: the increment in the subscripts of X between successive elements of x.
Constraint: INCX>0.

6 Error Indicators and Warnings

None.

7 Accuracy

Not applicable.

8 Parallelism and Performance

F06FGF is not threaded in any implementation.

9 Further Comments

None.

10 Example

None.
F06 Chapter Contents
F06 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F06FJF : NAG Library, Mark 26

F06 Chapter Contents
F06 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F06FJF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
10 Example

1 Purpose

F06FJF updates the Euclidean norm of real vector in scaled form.

2 Specification

SUBROUTINE F06FJF ( N, X, INCX, SCAL, SUMSQ)
INTEGER | N, INCX
REAL (KIND=nag_wp) | X(*), SCAL, SUMSQ

3 Description

Given an n-element real vector x, and real scalars α and ξ, F06FJF returns updated values α~ and ξ~ such that
α~2 ξ~=x 12+x 22+⋯+xn 2+α 2 ξ.
F06FJF is designed for use in the safe computation of the Euclidean norm of a real vector, without unnecessary overflow or destructive underflow. An initial call to F06FJF (with ξ=1 and α=0) may be followed by further calls to F06FJF and finally a call to F06BMF to complete the computation. Multiple calls of F06FJF may be needed if the elements of the vector cannot all be accessed in a single array X.

4 References

None.

5 Arguments

1:   N – INTEGERInput
On entry: n, the number of elements in x.
2:   X* – REAL (KIND=nag_wp) arrayInput
Note: the dimension of the array X must be at least max 1, 1+N-1 ×INCX .
On entry: the n-element vector x. xi must be stored in X 1+i-1×INCX, for i=1,2,…,N.
Intermediate elements of X are not referenced.
3:   INCX – INTEGERInput
On entry: the increment in the subscripts of X between successive elements of x.
Constraint: INCX>0.
4:   SCAL – REAL (KIND=nag_wp)Input/Output
On entry: the scaling factor α. On the first call to F06FJF SCAL=0.0.
Constraint: SCAL≥0.0.
On exit: the updated scaling factor α~=maxi α,xi .
5:   SUMSQ – REAL (KIND=nag_wp)Input/Output
On entry: the scaled sum of squares ξ. On the first call to F06FJF SUMSQ=1.0.
Constraint: SUMSQ≥1.0.
On exit: the updated scaled sum of squares ξ~, satisfying: 1≤ξ~≤ξ+n.

6 Error Indicators and Warnings

None.

7 Accuracy

Not applicable.

8 Parallelism and Performance

F06FJF is not threaded in any implementation.

9 Further Comments

None.

10 Example

None.
F06 Chapter Contents
F06 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F06FKF : NAG Library, Mark 26

F06 Chapter Contents
F06 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F06FKF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
10 Example

1 Purpose

F06FKF computes the weighted Euclidean norm of a real vector.

2 Specification

FUNCTION F06FKF ( N, W, INCW, X, INCX)
REAL (KIND=nag_wp) F06FKF
INTEGER | N, INCW, INCX
REAL (KIND=nag_wp) | W(*), X(*)

3 Description

F06FKF returns, via the function name, the weighted Euclidean norm
xT Wx
of the n-element real vector x scattered with stride INCW and INCX respectively, where W=diag w and w is a vector of weights scattered with stride INCW.

4 References

None.

5 Arguments

1:   N – INTEGERInput
On entry: n, the number of elements in x.
2:   W* – REAL (KIND=nag_wp) arrayInput
Note: the dimension of the array W must be at least max 1, 1+N-1 ×INCW .
On entry: w, the vector of weights.
If INCW>0, wi must be stored in W 1+i-1×INCX , for i=1,2,…,N.
If INCW<0, wi must be stored in W 1-N-i×INCW , for i=1,2,…,N.
Constraint: All weights must be non-negative.
3:   INCW – INTEGERInput
On entry: the increment in the subscripts of W between successive elements of w.
4:   X* – REAL (KIND=nag_wp) arrayInput
Note: the dimension of the array X must be at least max 1, 1+N-1 ×INCX .
On entry: the n-element vector x.
If INCX>0, xi must be stored in X 1+i-1×INCX, for i=1,2,…,N.
If INCX<0, xi must be stored in X 1-N-i×INCX, for i=1,2,…,N.
Intermediate elements of X are not referenced.
5:   INCX – INTEGERInput
On entry: the increment in the subscripts of X between successive elements of x.

6 Error Indicators and Warnings

None.

7 Accuracy

Not applicable.

8 Parallelism and Performance

F06FKF is not threaded in any implementation.

9 Further Comments

None.

10 Example

None.
F06 Chapter Contents
F06 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F06FLF : NAG Library, Mark 26

F06 Chapter Contents
F06 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F06FLF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
10 Example

1 Purpose

F06FLF returns the absolutely largest and absolutely smallest values from a real vector.

2 Specification

SUBROUTINE F06FLF ( N, X, INCX, XMAX, XMIN)
INTEGER | N, INCX
REAL (KIND=nag_wp) | X(*), XMAX, XMIN

3 Description

F06FLF returns the values xmax and xmin given by
xmax=maxi xi,  xmin=mini xi,
where x is an n-element real vector scattered with stride INCX. If n<1, then xmax and xmin are returned as zero.

4 References

None.

5 Arguments

1:   N – INTEGERInput
On entry: n, the number of elements in x.
2:   X* – REAL (KIND=nag_wp) arrayInput
Note: the dimension of the array X must be at least max 1, 1+N-1 ×INCX .
On entry: the n-element vector x. xi must be stored in X 1+i-1×INCX, for i=1,2,…,N.
Intermediate elements of X are not referenced.
3:   INCX – INTEGERInput
On entry: the increment in the subscripts of X between successive elements of x.
Constraint: INCX>0.
4:   XMAX – REAL (KIND=nag_wp)Output
On exit: the value xmax=maxi xi.
5:   XMIN – REAL (KIND=nag_wp)Output
On exit: the value xmin=mini xi.

6 Error Indicators and Warnings

None.

7 Accuracy

Not applicable.

8 Parallelism and Performance

F06FLF is not threaded in any implementation.

9 Further Comments

None.

10 Example

None.
F06 Chapter Contents
F06 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F06FPF : NAG Library, Mark 26

F06 Chapter Contents
F06 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F06FPF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
10 Example

1 Purpose

F06FPF applies a real symmetric plane rotation to two real vectors.

2 Specification

SUBROUTINE F06FPF ( N, X, INCX, Y, INCY, C, S)
INTEGER | N, INCX, INCY
REAL (KIND=nag_wp) | X(*), Y(*), C, S

3 Description

F06FPF applies a symmetric real plane rotation to two n-element real vectors x and y scattered with stride INCX and INCY respectively:
xT yT ← c s s -c xT yT .

4 References

None.

5 Arguments

1:   N – INTEGERInput
On entry: n, the number of elements in x and y.
2:   X* – REAL (KIND=nag_wp) arrayInput/Output
Note: the dimension of the array X must be at least max 1, 1+N-1 ×INCX .
On entry: the original vector x.
If INCX>0, xi must be stored in X 1+i-1×INCX , for i=1,2,…,N.
If INCX<0, xi must be stored in X 1-N-i×INCX , for i=1,2,…,N.
Intermediate elements of X are not referenced.
On exit: the transformed vector x stored in the same elements used to supply the original vector x.
Intermediate elements of X are unchanged.
3:   INCX – INTEGERInput
On entry: the increment in the subscripts of X between successive elements of x.
4:   Y* – REAL (KIND=nag_wp) arrayInput/Output
Note: the dimension of the array Y must be at least max 1, 1+N-1 ×INCY .
On entry: the original vector y.
If INCY>0, yi must be stored in Y 1+i-1×INCY , for i=1,2,…,N.
If INCY<0, yi must be stored in Y 1-N-i×INCY , for i=1,2,…,N.
Intermediate elements of Y are not referenced.
On exit: the transformed vector y stored in the same elements used to supply the original vector y.
Intermediate elements of Y are unchanged.
5:   INCY – INTEGERInput
On entry: the increment in the subscripts of Y between successive elements of y.
6:   C – REAL (KIND=nag_wp)Input
On entry: the value c, the cosine of the rotation.
7:   S – REAL (KIND=nag_wp)Input
On entry: the value s, the sine of the rotation.

6 Error Indicators and Warnings

None.

7 Accuracy

Not applicable.

8 Parallelism and Performance

F06FPF is not threaded in any implementation.

9 Further Comments

None.

10 Example

None.
F06 Chapter Contents
F06 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F06FQF : NAG Library, Mark 26

F06 Chapter Contents
F06 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F06FQF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
10 Example

1 Purpose

F06FQF generates a sequence of real plane rotations.

2 Specification

SUBROUTINE F06FQF ( PIVOT, DIRECT, N, ALPHA, X, INCX, C, S)
INTEGER | N, INCX
REAL (KIND=nag_wp) | ALPHA, X(*), C(N), S(N)
CHARACTER(1) | PIVOT, DIRECT

3 Description

F06FQF generates the parameters of a real orthogonal matrix P, of order n+1, chosen so as to set to zero the elements of a supplied n-element real vector x.
If PIVOT='F' and DIRECT='F', or if PIVOT='V' and DIRECT='B',
P α x = β 0 ;
If PIVOT='F' and DIRECT='B', or if PIVOT='V' and DIRECT='F',
P x α = 0 β .
Here α and β are real scalars.
P is represented as a sequence of n plane rotations Pk, as specified by PIVOT and DIRECT; Pk is chosen to annihilate xk, and its 2 by 2 plane rotation part has the form
ck sk -sk ck .
The tangent of the rotation, tk, is overwritten on xk.

4 References

None.

5 Arguments

1:   PIVOT – CHARACTER(1)Input
On entry: specifies the plane rotated by Pk.
PIVOT='V' (variable pivot)
Pk rotates the k,k+1 plane.
PIVOT='F' (fixed pivot)
Pk rotates the 1,k+1 plane if DIRECT='F', or the k,n+1 plane if DIRECT='B'.
Constraint: PIVOT='V' or 'F'.
2:   DIRECT – CHARACTER(1)Input
On entry: specifies the sequence direction.
DIRECT='F' (forward sequence)
P=Pn⋯P 2P 1.
DIRECT='B' (backward sequence)
P=P 1P 2⋯Pn.
Constraint: DIRECT='F' or 'B'.
3:   N – INTEGERInput
On entry: n, the number of elements in x.
4:   ALPHA – REAL (KIND=nag_wp)Input/Output
On entry: the scalar α.
On exit: the scalar β.
5:   X* – REAL (KIND=nag_wp) arrayInput/Output
Note: the dimension of the array X must be at least max 1, 1+N-1 ×INCX .
On entry: the n-element vector x. xi must be stored in X 1+i-1×INCX, for i=1,2,…,N.
Intermediate elements of X are not referenced.
On exit: the referenced elements are overwritten by details of the sequence of plane rotations.
6:   INCX – INTEGERInput
On entry: the increment in the subscripts of X between successive elements of x.
Constraint: INCX>0.
7:   C N – REAL (KIND=nag_wp) arrayOutput
On exit: the values ck, the cosines of the rotations.
8:   S N – REAL (KIND=nag_wp) arrayOutput
On exit: the values sk, the sines of the rotations.

6 Error Indicators and Warnings

None.

7 Accuracy

Not applicable.

8 Parallelism and Performance

F06FQF is not threaded in any implementation.

9 Further Comments

None.

10 Example

None.
F06 Chapter Contents
F06 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F06FRF : NAG Library, Mark 26

F06 Chapter Contents
F06 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F06FRF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
10 Example

1 Purpose

F06FRF generates a real elementary reflection in the NAG (as opposed to LINPACK) style.

2 Specification

SUBROUTINE F06FRF ( N, ALPHA, X, INCX, TOL, ZETA)
INTEGER | N, INCX
REAL (KIND=nag_wp) | ALPHA, X(*), TOL, ZETA

3 Description

F06FRF generates details of a real elementary reflection (Householder matrix), P, such that
P α x = β 0
where P is orthogonal, α and β are real scalars, and x is an n-element real vector.
P is given in the form
P=I- ζ z ζ zT ,
where z is an n-element real vector and ζ is a real scalar.
If x is such that
max xi≤max tol,ε α
where ε is the machine precision and tol is a user-supplied tolerance, then ζ is set to 0, and P can be taken to be the unit matrix. Otherwise 1≤ζ≤2.

4 References

None.

5 Arguments

1:   N – INTEGERInput
On entry: n, the number of elements in x and z.
2:   ALPHA – REAL (KIND=nag_wp)Input/Output
On entry: the scalar α.
On exit: the scalar β.
3:   X* – REAL (KIND=nag_wp) arrayInput/Output
Note: the dimension of the array X must be at least max 1, 1+N-1 ×INCX .
On entry: the n-element vector x. xi must be stored in X 1+i-1×INCX, for i=1,2,…,N.
Intermediate elements of X are not referenced.
On exit: the referenced elements are overwritten by details of the real elementary reflection.
4:   INCX – INTEGERInput
On entry: the increment in the subscripts of X between successive elements of x.
Constraint: INCX>0.
5:   TOL – REAL (KIND=nag_wp)Input
On entry: the value tol.
6:   ZETA – REAL (KIND=nag_wp)Output
On exit: the scalar ζ.

6 Error Indicators and Warnings

None.

7 Accuracy

Not applicable.

8 Parallelism and Performance

F06FRF makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

None.

10 Example

None.
F06 Chapter Contents
F06 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F06FSF : NAG Library, Mark 26

F06 Chapter Contents
F06 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F06FSF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
10 Example

1 Purpose

F06FSF generates a real elementary reflection in the LINPACK (as opposed to NAG) style.

2 Specification

SUBROUTINE F06FSF ( N, ALPHA, X, INCX, TOL, Z1)
INTEGER | N, INCX
REAL (KIND=nag_wp) | ALPHA, X(*), TOL, Z1

3 Description

F06FSF generates details of a real elementary reflection (Householder matrix), P, such that
P α x = β 0
where P is orthogonal, α and β are real scalars, and x is an n-element real vector.
P is given in the form
P=I-1 ζ ζ z ζ zT ,
where z is an n-element real vector and ζ is a real scalar. (This form is compatible with that used by LINPACK.)
If the elements of x are all zero, or if the elements of x are all less than tol×α in absolute value, then ζ is set to 0 and P can be taken to be the unit matrix. Otherwise ζ always lies in the range 1,2.

4 References

None.

5 Arguments

1:   N – INTEGERInput
On entry: n, the number of elements in x and z.
2:   ALPHA – REAL (KIND=nag_wp)Input/Output
On entry: the scalar α.
On exit: the scalar β.
3:   X* – REAL (KIND=nag_wp) arrayInput/Output
Note: the dimension of the array X must be at least max 1, 1+N-1 ×INCX .
On entry: the n-element vector x. xi must be stored in X 1+i-1×INCX, for i=1,2,…,N.
Intermediate elements of X are not referenced.
On exit: the referenced elements are overwritten by details of the real elementary reflection.
4:   INCX – INTEGERInput
On entry: the increment in the subscripts of X between successive elements of x.
Constraint: INCX>0.
5:   TOL – REAL (KIND=nag_wp)Input
On entry: the value tol.
If TOL is not in the range 0,1 , then the value 0 is used for tol.
6:   Z1 – REAL (KIND=nag_wp)Output
On exit: the scalar ζ.

6 Error Indicators and Warnings

None.

7 Accuracy

Not applicable.

8 Parallelism and Performance

F06FSF makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

None.

10 Example

None.
F06 Chapter Contents
F06 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F06FTF : NAG Library, Mark 26

F06 Chapter Contents
F06 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F06FTF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
10 Example

1 Purpose

F06FTF applies a NAG (as opposed to LINPACK) style real elementary reflection to a real vector.

2 Specification

SUBROUTINE F06FTF ( N, DELTA, Y, INCY, ZETA, Z, INCZ)
INTEGER | N, INCY, INCZ
REAL (KIND=nag_wp) | DELTA, Y(*), ZETA, Z(*)

3 Description

F06FTF applies a real elementary reflection (Householder matrix) P, as generated by F06FRF, to a given real vector:
δ y ←P δ y ,
where y is an n-element real vector and δ a real scalar.

4 References

None.

5 Arguments

1:   N – INTEGERInput
On entry: n, the number of elements in y and z.
2:   DELTA – REAL (KIND=nag_wp)Input/Output
On entry: the original scalar δ.
On exit: the transformed scalar δ.
3:   Y* – REAL (KIND=nag_wp) arrayInput/Output
Note: the dimension of the array Y must be at least max 1, 1+N-1 ×INCY .
On entry: the original vector y.
If INCY>0, yi must be stored in Y 1+i-1 ×INCY , for i=1,2,…,N.
If INCY<0, yi must be stored in Y 1-N-i ×INCY , for i=1,2,…,N.
On exit: the transformed stored in the same array elements used to supply the original vector y.
4:   INCY – INTEGERInput
On entry: the increment in the subscripts of Y between successive elements of y.
5:   ZETA – REAL (KIND=nag_wp)Input
On entry: the scalar ζ, as returned by F06FRF.
If ζ=0, P is assumed to be the unit matrix and the transformation is skipped.
Constraint: if ZETA=0.0, N=0.
6:   Z* – REAL (KIND=nag_wp) arrayInput
Note: the dimension of the array Z must be at least max 1, 1+N-1 ×INCZ .
On entry: the vector z, as returned by F06FRF.
If INCZ>0, zi must be stored in Z 1+i-1×INCZ , for i=1,2,…,N.
If INCZ<0, zi must be stored in Z 1-N-i×INCZ , for i=1,2,…,N.
7:   INCZ – INTEGERInput
On entry: the increment in the subscripts of Z between successive elements of z.

6 Error Indicators and Warnings

None.

7 Accuracy

Not applicable.

8 Parallelism and Performance

F06FTF makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

None.

10 Example

None.
F06 Chapter Contents
F06 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F06FUF : NAG Library, Mark 26

F06 Chapter Contents
F06 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F06FUF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
10 Example

1 Purpose

F06FUF applies a LINPACK (as opposed to NAG) style real elementary reflection to a real vector.

2 Specification

SUBROUTINE F06FUF ( N, Z, INCZ, Z1, ALPHA, X, INCX)
INTEGER | N, INCZ, INCX
REAL (KIND=nag_wp) | Z(*), Z1, ALPHA, X(*)

3 Description

F06FUF applies a real elementary reflection (Householder matrix) P, as generated by F06FSF, to a given real vector:
α x ←P α x
where x is an n-element real vector and α a real scalar.

4 References

None.

5 Arguments

1:   N – INTEGERInput
On entry: n, the number of elements in x and z.
2:   Z* – REAL (KIND=nag_wp) arrayInput
Note: the dimension of the array Z must be at least max 1, 1+N-1 ×INCZ .
On entry: the vector z, as returned by F06FSF.
If INCZ>0, zi must be stored in Z 1+i-1×INCZ , for i=1,2,…,N.
If INCZ<0, zi must be stored in Z 1-N-i×INCZ , for i=1,2,…,N.
3:   INCZ – INTEGERInput
On entry: the increment in the subscripts of Z between successive elements of z.
4:   Z1 – REAL (KIND=nag_wp)Input
On entry: the scalar ζ, as returned by F06FSF.
If ζ=0, P is assumed to be the unit matrix and the transformation is skipped.
5:   ALPHA – REAL (KIND=nag_wp)Input/Output
On entry: the original scalar α.
On exit: the transformed scalar α.
6:   X* – REAL (KIND=nag_wp) arrayInput/Output
Note: the dimension of the array X must be at least max 1, 1+N-1 ×INCX .
On entry: the original vector x.
If INCX>0, xi must be stored in X 1+i-1×INCX , for i=1,2,…,N.
If INCX<0, xi must be stored in X 1-N-i×INCX , for i=1,2,…,N.
On exit: the transformed vector x stored in the same array elements used to supply the original vector x.
7:   INCX – INTEGERInput
On entry: the increment in the subscripts of X between successive elements of x.

6 Error Indicators and Warnings

None.

7 Accuracy

Not applicable.

8 Parallelism and Performance

F06FUF makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

None.

10 Example

None.
F06 Chapter Contents
F06 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F06GAF (ZDOTU) : NAG Library, Mark 26

F06 Chapter Contents
F06 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F06GAF (ZDOTU)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
10 Example

1 Purpose

F06GAF (ZDOTU) computes the scalar product of two complex vectors.

2 Specification

FUNCTION F06GAF ( N, X, INCX, Y, INCY)
COMPLEX (KIND=nag_wp) F06GAF
INTEGER | N, INCX, INCY
COMPLEX (KIND=nag_wp) | X(*), Y(*)
The routine may be called by its BLAS name zdotu.

3 Description

F06GAF (ZDOTU) returns, via the function name, the value of the scalar product
xT y
where x and y are n-element complex vectors scattered with stride INCX and INCY respectively.

4 References

Lawson C L, Hanson R J, Kincaid D R and Krogh F T (1979) Basic linear algebra supbrograms for Fortran usage ACM Trans. Math. Software 5 308–325

5 Arguments

1:   N – INTEGERInput
On entry: n, the number of elements in x and y.
2:   X* – COMPLEX (KIND=nag_wp) arrayInput
Note: the dimension of the array X must be at least max 1, 1+N-1 ×INCX .
On entry: the n-element vector x.
If INCX>0, xi must be stored in X 1+i-1×INCX, for i=1,2,…,N.
If INCX<0, xi must be stored in X 1-N-i×INCX, for i=1,2,…,N.
Intermediate elements of X are not referenced.
3:   INCX – INTEGERInput
On entry: the increment in the subscripts of X between successive elements of x.
4:   Y* – COMPLEX (KIND=nag_wp) arrayInput
Note: the dimension of the array Y must be at least max 1, 1+N-1 ×INCY .
On entry: the n-element vector y.
If INCY>0, yi must be stored in Y 1+i-1×INCY, for i=1,2,…,N.
If INCY<0, yi must be stored in Y 1-N-i×INCY, for i=1,2,…,N.
Intermediate elements of Y are not referenced.
5:   INCY – INTEGERInput
On entry: the increment in the subscripts of Y between successive elements of y.

6 Error Indicators and Warnings

None.

7 Accuracy

Not applicable.

8 Parallelism and Performance

F06GAF (ZDOTU) is not threaded in any implementation.

9 Further Comments

None.

10 Example

None.
F06 Chapter Contents
F06 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F06GBF (ZDOTC) : NAG Library, Mark 26

F06 Chapter Contents
F06 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F06GBF (ZDOTC)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
10 Example

1 Purpose

F06GBF (ZDOTC) computes the scalar product of two complex vectors.

2 Specification

FUNCTION F06GBF ( N, X, INCX, Y, INCY)
COMPLEX (KIND=nag_wp) F06GBF
INTEGER | N, INCX, INCY
COMPLEX (KIND=nag_wp) | X(*), Y(*)
The routine may be called by its BLAS name zdotc.

3 Description

F06GBF (ZDOTC) returns, via the function name, the value of the scalar product
xH y
where x and y are n-element complex vectors scattered with stride INCX and INCY respectively.

4 References

Lawson C L, Hanson R J, Kincaid D R and Krogh F T (1979) Basic linear algebra supbrograms for Fortran usage ACM Trans. Math. Software 5 308–325

5 Arguments

1:   N – INTEGERInput
On entry: n, the number of elements in x and y.
2:   X* – COMPLEX (KIND=nag_wp) arrayInput
Note: the dimension of the array X must be at least max 1, 1+N-1 ×INCX .
On entry: the n-element vector x.
If INCX>0, xi must be stored in X 1+i-1×INCX, for i=1,2,…,N.
If INCX<0, xi must be stored in X 1-N-i×INCX, for i=1,2,…,N.
Intermediate elements of X are not referenced.
3:   INCX – INTEGERInput
On entry: the increment in the subscripts of X between successive elements of x.
4:   Y* – COMPLEX (KIND=nag_wp) arrayInput
Note: the dimension of the array Y must be at least max 1, 1+N-1 ×INCY .
On entry: the n-element vector y.
If INCY>0, yi must be stored in Y 1+i-1×INCY, for i=1,2,…,N.
If INCY<0, yi must be stored in Y 1-N-i×INCY, for i=1,2,…,N.
Intermediate elements of Y are not referenced.
5:   INCY – INTEGERInput
On entry: the increment in the subscripts of Y between successive elements of y.

6 Error Indicators and Warnings

None.

7 Accuracy

Not applicable.

8 Parallelism and Performance

F06GBF (ZDOTC) is not threaded in any implementation.

9 Further Comments

None.

10 Example

None.
F06 Chapter Contents
F06 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F06GCF (ZAXPY) : NAG Library, Mark 26

F06 Chapter Contents
F06 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F06GCF (ZAXPY)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
10 Example

1 Purpose

F06GCF (ZAXPY) adds a scaled complex vector to an unscaled complex vector.

2 Specification

SUBROUTINE F06GCF ( N, ALPHA, X, INCX, Y, INCY)
INTEGER | N, INCX, INCY
COMPLEX (KIND=nag_wp) | ALPHA, X(*), Y(*)
The routine may be called by its BLAS name zaxpy.

3 Description

F06GCF (ZAXPY) performs the operation
y←αx+y
where x and y are n-element complex vectors scattered with stride INCX and INCY respectively, and α is a complex scalar.

4 References

Lawson C L, Hanson R J, Kincaid D R and Krogh F T (1979) Basic linear algebra supbrograms for Fortran usage ACM Trans. Math. Software 5 308–325

5 Arguments

1:   N – INTEGERInput
On entry: n, the number of elements in x and y.
2:   ALPHA – COMPLEX (KIND=nag_wp)Input
On entry: the scalar α.
3:   X* – COMPLEX (KIND=nag_wp) arrayInput
Note: the dimension of the array X must be at least max 1, 1+N-1 ×INCX .
On entry: the n-element vector x.
If INCX>0, xi must be stored in X 1+i-1×INCX, for i=1,2,…,N.
If INCX<0, xi must be stored in X 1-N-i×INCX, for i=1,2,…,N.
Intermediate elements of X are not referenced.
4:   INCX – INTEGERInput
On entry: the increment in the subscripts of X between successive elements of x.
5:   Y* – COMPLEX (KIND=nag_wp) arrayInput/Output
Note: the dimension of the array Y must be at least max 1, 1+N-1 ×INCY .
On entry: the n-element vector y.
If INCY>0, yi must be stored in Y 1+i-1×INCY, for i=1,2,…,N.
If INCY<0, yi must be stored in Y 1-N-i×INCY, for i=1,2,…,N.
Intermediate elements of Y are not referenced.
On exit: the updated vector y.
6:   INCY – INTEGERInput
On entry: the increment in the subscripts of Y between successive elements of y.

6 Error Indicators and Warnings

None.

7 Accuracy

Not applicable.

8 Parallelism and Performance

F06GCF (ZAXPY) is not threaded in any implementation.

9 Further Comments

None.

10 Example

None.
F06 Chapter Contents
F06 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F06GDF (ZSCAL) : NAG Library, Mark 26

F06 Chapter Contents
F06 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F06GDF (ZSCAL)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
10 Example

1 Purpose

F06GDF (ZSCAL) scales a complex vector by a complex scalar.

2 Specification

SUBROUTINE F06GDF ( N, ALPHA, X, INCX)
INTEGER | N, INCX
COMPLEX (KIND=nag_wp) | ALPHA, X(*)
The routine may be called by its BLAS name zscal.

3 Description

F06GDF (ZSCAL) performs the operation
x←αx
where x is an n-element complex vector scattered with stride INCX, and α is a complex scalar.

4 References

Lawson C L, Hanson R J, Kincaid D R and Krogh F T (1979) Basic linear algebra supbrograms for Fortran usage ACM Trans. Math. Software 5 308–325

5 Arguments

1:   N – INTEGERInput
On entry: n, the number of elements in x.
2:   ALPHA – COMPLEX (KIND=nag_wp)Input
On entry: the scalar α.
3:   X* – COMPLEX (KIND=nag_wp) arrayInput/Output
Note: the dimension of the array X must be at least max 1, 1+N-1 ×INCX .
On entry: the n-element vector x. xi must be stored in X 1+i-1×INCX, for i=1,2,…,N.
Intermediate elements of X are not referenced.
On exit: the vector αx stored in the array elements used to supply the original vector x y.
Intermediate elements of X are unchanged.
4:   INCX – INTEGERInput
On entry: the increment in the subscripts of X between successive elements of x.
Constraint: INCX>0.

6 Error Indicators and Warnings

None.

7 Accuracy

Not applicable.

8 Parallelism and Performance

F06GDF (ZSCAL) is not threaded in any implementation.

9 Further Comments

None.

10 Example

None.
F06 Chapter Contents
F06 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F06GFF (ZCOPY) : NAG Library, Mark 26

F06 Chapter Contents
F06 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F06GFF (ZCOPY)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
10 Example

1 Purpose

F06GFF (ZCOPY) copies a complex vector to a complex vector.

2 Specification

SUBROUTINE F06GFF ( N, X, INCX, Y, INCY)
INTEGER | N, INCX, INCY
COMPLEX (KIND=nag_wp) | X(*), Y(*)
The routine may be called by its BLAS name zcopy.

3 Description

F06GFF (ZCOPY) performs the operation
y←x
where x and y are n-element complex vectors scattered with stride INCX and INCY respectively.

4 References

Lawson C L, Hanson R J, Kincaid D R and Krogh F T (1979) Basic linear algebra supbrograms for Fortran usage ACM Trans. Math. Software 5 308–325

5 Arguments

1:   N – INTEGERInput
On entry: n, the number of elements in x and y.
2:   X* – COMPLEX (KIND=nag_wp) arrayInput
Note: the dimension of the array X must be at least max 1, 1+N-1 ×INCX .
On entry: the n-element vector x.
If INCX>0, xi must be stored in X 1+i-1×INCX, for i=1,2,…,N.
If INCX<0, xi must be stored in X 1-N-i×INCX, for i=1,2,…,N.
Intermediate elements of X are not referenced.
3:   INCX – INTEGERInput
On entry: the increment in the subscripts of X between successive elements of x.
4:   Y* – COMPLEX (KIND=nag_wp) arrayOutput
Note: the dimension of the array Y must be at least max 1, 1+N-1 ×INCY .
On exit: the vector y.
If INCY>0, yi will be stored in Y 1+i-1×INCY, for i=1,2,…,N.
If INCY<0, yi will be stored in Y 1-N-i×INCY, for i=1,2,…,N.
Intermediate elements of Y are unchanged.
5:   INCY – INTEGERInput
On entry: the increment in the subscripts of Y between successive elements of y.

6 Error Indicators and Warnings

None.

7 Accuracy

Not applicable.

8 Parallelism and Performance

F06GFF (ZCOPY) is not threaded in any implementation.

9 Further Comments

None.

10 Example

None.
F06 Chapter Contents
F06 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F06GGF (ZSWAP) : NAG Library, Mark 26

F06 Chapter Contents
F06 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F06GGF (ZSWAP)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
10 Example

1 Purpose

F06GGF (ZSWAP) interchanges two n-element complex vectors x and y.

2 Specification

SUBROUTINE F06GGF ( N, X, INCX, Y, INCY)
INTEGER | N, INCX, INCY
COMPLEX (KIND=nag_wp) | X(*), Y(*)
The routine may be called by its BLAS name zswap.

3 Description

F06GGF (ZSWAP) interchanges the elements of complex vectors x and y scattered with stride INCX and INCY respectively.

4 References

Lawson C L, Hanson R J, Kincaid D R and Krogh F T (1979) Basic linear algebra supbrograms for Fortran usage ACM Trans. Math. Software 5 308–325

5 Arguments

1:   N – INTEGERInput
On entry: n, the number of elements in x and y.
2:   X* – COMPLEX (KIND=nag_wp) arrayInput/Output
Note: the dimension of the array X must be at least max 1, 1+N-1 ×INCX .
On entry: the original vector x.
If INCX>0, xi must be stored in X 1+i-1×INCX, for i=1,2,…,N.
If INCX≤0, xi must be stored in X 1+N-i×INCX, for i=1,2,…,N.
On exit: the original vector y stored in the array elements used to store the original vector x. Intermediate elements of X are unchanged.
3:   INCX – INTEGERInput
On entry: the increment in the subscripts of X between successive elements of x.
4:   Y* – COMPLEX (KIND=nag_wp) arrayInput/Output
Note: the dimension of the array Y must be at least max 1, 1+N-1 ×INCY .
On entry: the original vector y.
If INCY>0, yi must be stored in Y 1+i-1×INCY, for i=1,2,…,N.
If INCY≤0, yi must be stored in Y 1+N-i×INCY, for i=1,2,…,N.
On exit: the original vector x stored in the array elements used to store the original vector y. Intermediate elements of Y are unchanged.
5:   INCY – INTEGERInput
On entry: the increment in the subscripts of Y between successive elements of y.

6 Error Indicators and Warnings

None.

7 Accuracy

Not applicable.

8 Parallelism and Performance

F06GGF (ZSWAP) is not threaded in any implementation.

9 Further Comments

None.

10 Example

None.
F06 Chapter Contents
F06 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F06GRF (ZDOTUI) : NAG Library, Mark 26

F06 Chapter Contents
F06 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F06GRF (ZDOTUI)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
10 Example

1 Purpose

F06GRF (ZDOTUI) computes the scalar product of an unconjugated sparse complex vector with a complex vector.

2 Specification

FUNCTION F06GRF ( NZ, X, INDX, Y)
COMPLEX (KIND=nag_wp) F06GRF
INTEGER | NZ, INDX(*)
COMPLEX (KIND=nag_wp) | X(*), Y(*)
The routine may be called by its BLAS name zdotui.

3 Description

F06GRF (ZDOTUI) returns, via the function name, the value of the scalar product
xT y
where x is a sparse complex vector stored in compressed form, and y is a complex vector in full storage form.

4 References

Dodson D S, Grimes R G and Lewis J G (1991) Sparse extensions to the Fortran basic linear algebra subprograms ACM Trans. Math. Software 17 253–263

5 Arguments

1:   NZ – INTEGERInput
On entry: the number of nonzeros in the sparse vector x.
2:   X* – COMPLEX (KIND=nag_wp) arrayInput
Note: the dimension of the array X must be at least max 1,NZ .
On entry: the compressed vector x. X contains xi for i∈J.
3:   INDX* – INTEGER arrayInput
Note: the dimension of the array INDX must be at least max 1,NZ .
On entry: INDX must contain the set of indices J.
4:   Y* – COMPLEX (KIND=nag_wp) arrayInput
Note: the dimension of the array Y must be at least maxk INDX k .
On entry: the vector y. Only elements corresponding to indices in INDX are accessed.

6 Error Indicators and Warnings

None.

7 Accuracy

Not applicable.

8 Parallelism and Performance

F06GRF (ZDOTUI) is not threaded in any implementation.

9 Further Comments

None.

10 Example

None.
F06 Chapter Contents
F06 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F06GSF (ZDOTCI) : NAG Library, Mark 26

F06 Chapter Contents
F06 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F06GSF (ZDOTCI)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
10 Example

1 Purpose

F06GSF (ZDOTCI) computes the scalar product of a conjugated sparse complex vector with a complex vector.

2 Specification

FUNCTION F06GSF ( NZ, X, INDX, Y)
COMPLEX (KIND=nag_wp) F06GSF
INTEGER | NZ, INDX(*)
COMPLEX (KIND=nag_wp) | X(*), Y(*)
The routine may be called by its BLAS name zdotci.

3 Description

F06GSF (ZDOTCI) returns, via the function name, the value of the scalar product
xH y
where x is a sparse complex vector stored in compressed form, and y is a complex vector in full storage form.

4 References

Dodson D S, Grimes R G and Lewis J G (1991) Sparse extensions to the Fortran basic linear algebra subprograms ACM Trans. Math. Software 17 253–263

5 Arguments

1:   NZ – INTEGERInput
On entry: the number of nonzeros in the sparse vector x.
2:   X* – COMPLEX (KIND=nag_wp) arrayInput
Note: the dimension of the array X must be at least max 1,NZ .
On entry: the compressed vector x. X contains xi for i∈J.
3:   INDX* – INTEGER arrayInput
Note: the dimension of the array INDX must be at least max 1,NZ .
On entry: INDX must contain the set of indices J.
4:   Y* – COMPLEX (KIND=nag_wp) arrayInput
Note: the dimension of the array Y must be at least maxk INDX k .
On entry: the vector y. Only elements corresponding to indices in INDX are accessed.

6 Error Indicators and Warnings

None.

7 Accuracy

Not applicable.

8 Parallelism and Performance

F06GSF (ZDOTCI) is not threaded in any implementation.

9 Further Comments

None.

10 Example

None.
F06 Chapter Contents
F06 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F06GTF (ZAXPYI) : NAG Library, Mark 26

F06 Chapter Contents
F06 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F06GTF (ZAXPYI)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
10 Example

1 Purpose

F06GTF (ZAXPYI) adds a scaled sparse complex vector to an unscaled complex vector.

2 Specification

SUBROUTINE F06GTF ( NZ, A, X, INDX, Y)
INTEGER | NZ, INDX(*)
COMPLEX (KIND=nag_wp) | A, X(*), Y(*)
The routine may be called by its BLAS name zaxpyi.

3 Description

F06GTF (ZAXPYI) performs the operation
y←αx+y
where x is a sparse complex vector stored in compressed form, and y is a complex vector in full storage form.

4 References

Dodson D S, Grimes R G and Lewis J G (1991) Sparse extensions to the Fortran basic linear algebra subprograms ACM Trans. Math. Software 17 253–263

5 Arguments

1:   NZ – INTEGERInput
On entry: the number of nonzeros in the sparse vector x.
2:   A – COMPLEX (KIND=nag_wp)Input
On entry: the scalar α.
3:   X* – COMPLEX (KIND=nag_wp) arrayInput
Note: the dimension of the array X must be at least max 1,NZ .
On entry: the compressed vector x. X contains xi for i∈J.
4:   INDX* – INTEGER arrayInput
Note: the dimension of the array INDX must be at least max 1,NZ .
On entry: the indices of the elements in the compressed vector x.
Constraint: the indices must be distinct.
5:   Y* – COMPLEX (KIND=nag_wp) arrayInput/Output
Note: the dimension of the array Y must be at least maxk INDX k .
On entry: the vector y. Only elements corresponding to indices in INDX are accessed.
On exit: the updated vector y.

6 Error Indicators and Warnings

None.

7 Accuracy

Not applicable.

8 Parallelism and Performance

F06GTF (ZAXPYI) is not threaded in any implementation.

9 Further Comments

None.

10 Example

None.
F06 Chapter Contents
F06 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F06GUF (ZGTHR) : NAG Library, Mark 26

F06 Chapter Contents
F06 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F06GUF (ZGTHR)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
10 Example

1 Purpose

F06GUF (ZGTHR) gathers specified (usually nonzero) elements of a complex vector y in full storage form into a sparse complex vector x in compressed form.

2 Specification

SUBROUTINE F06GUF ( NZ, Y, X, INDX)
INTEGER | NZ, INDX(*)
COMPLEX (KIND=nag_wp) | Y(*), X(*)
The routine may be called by its BLAS name zgthr.

3 Description

None.

4 References

Dodson D S, Grimes R G and Lewis J G (1991) Sparse extensions to the Fortran basic linear algebra subprograms ACM Trans. Math. Software 17 253–263

5 Arguments

1:   NZ – INTEGERInput
On entry: the number of nonzeros in the sparse vector x.
2:   Y* – COMPLEX (KIND=nag_wp) arrayInput
Note: the dimension of the array Y must be at least maxk INDX k .
On entry: the vector y. Only elements corresponding to indices in INDX are accessed.
3:   X* – COMPLEX (KIND=nag_wp) arrayOutput
Note: the dimension of the array X must be at least max 1,NZ.
On exit: the compressed vector x.
4:   INDX* – INTEGER arrayInput
Note: the dimension of the array INDX must be at least max 1,NZ .
On entry: INDX must contain the set of indices J.

6 Error Indicators and Warnings

None.

7 Accuracy

Not applicable.

8 Parallelism and Performance

F06GUF (ZGTHR) is not threaded in any implementation.

9 Further Comments

None.

10 Example

None.
F06 Chapter Contents
F06 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F06GVF (ZGTHRZ) : NAG Library, Mark 26

F06 Chapter Contents
F06 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F06GVF (ZGTHRZ)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
10 Example

1 Purpose

F06GVF (ZGTHRZ) gathers specified (usually nonzero) elements of a complex vector y in full storage form into a sparse complex vector x in compressed form. The specified elements of y are set to zero.

2 Specification

SUBROUTINE F06GVF ( NZ, Y, X, INDX)
INTEGER | NZ, INDX(*)
COMPLEX (KIND=nag_wp) | Y(*), X(*)
The routine may be called by its BLAS name zgthrz.

3 Description

None.

4 References

Dodson D S, Grimes R G and Lewis J G (1991) Sparse extensions to the Fortran basic linear algebra subprograms ACM Trans. Math. Software 17 253–263

5 Arguments

1:   NZ – INTEGERInput
On entry: the number of nonzeros in the sparse vector x.
2:   Y* – COMPLEX (KIND=nag_wp) arrayInput/Output
Note: the dimension of the array Y must be at least maxk INDX k .
On entry: the vector y. Only elements corresponding to indices in INDX are accessed.
On exit: the elements of y corresponding to indices in INDX are set to zero.
3:   X* – COMPLEX (KIND=nag_wp) arrayOutput
Note: the dimension of the array X must be at least max 1,NZ.
On exit: the compressed vector x.
4:   INDX* – INTEGER arrayInput
Note: the dimension of the array INDX must be at least max 1,NZ .
On entry: INDX must contain the set of indices J.

6 Error Indicators and Warnings

None.

7 Accuracy

Not applicable.

8 Parallelism and Performance

F06GVF (ZGTHRZ) is not threaded in any implementation.

9 Further Comments

None.

10 Example

None.
F06 Chapter Contents
F06 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F06GWF (ZSCTR) : NAG Library, Mark 26

F06 Chapter Contents
F06 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F06GWF (ZSCTR)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
10 Example

1 Purpose

F06GWF (ZSCTR) scatters the elements of a sparse complex vector x stored in compressed form, into a complex vector y in full storage form.

2 Specification

SUBROUTINE F06GWF ( NZ, X, INDX, Y)
INTEGER | NZ, INDX(*)
COMPLEX (KIND=nag_wp) | X(*), Y(*)
The routine may be called by its BLAS name zsctr.

3 Description

None.

4 References

Dodson D S, Grimes R G and Lewis J G (1991) Sparse extensions to the Fortran basic linear algebra subprograms ACM Trans. Math. Software 17 253–263

5 Arguments

1:   NZ – INTEGERInput
On entry: the number of nonzeros in the sparse vector x.
2:   X* – COMPLEX (KIND=nag_wp) arrayInput
Note: the dimension of the array X must be at least max 1,NZ .
On entry: the compressed vector x. X contains xi for i∈J.
3:   INDX* – INTEGER arrayInput
Note: the dimension of the array INDX must be at least max 1,NZ .
On entry: the indices of the elements in the compressed vector x.
Constraint: the indices must be distinct.
4:   Y* – COMPLEX (KIND=nag_wp) arrayOutput
Note: the dimension of the array Y must be at least maxk INDX k .
On exit: the vector y. Only elements corresponding to indices in INDX are altered.

6 Error Indicators and Warnings

None.

7 Accuracy

Not applicable.

8 Parallelism and Performance

F06GWF (ZSCTR) is not threaded in any implementation.

9 Further Comments

None.

10 Example

None.
F06 Chapter Contents
F06 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F06HBF : NAG Library, Mark 26

F06 Chapter Contents
F06 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F06HBF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
10 Example

1 Purpose

F06HBF broadcasts a complex scalar into a complex vector.

2 Specification

SUBROUTINE F06HBF ( N, CON, X, INCX)
INTEGER | N, INCX
COMPLEX (KIND=nag_wp) | CON, X(*)

3 Description

F06HBF performs the operation
x←α,α,…,α T,
where x is an n-element complex vector scattered with stride INCX.

4 References

None.

5 Arguments

1:   N – INTEGERInput
On entry: n, the number of elements in x.
2:   CON – COMPLEX (KIND=nag_wp)Input
On entry: the scalar α.
3:   X* – COMPLEX (KIND=nag_wp) arrayOutput
Note: the dimension of the array X must be at least max 1, 1+N-1 ×INCX .
On exit: the vector x, xi is stored in X 1+i-1×INCX , for i=1,2,…,N.
Intermediate elements of X are unchanged.
4:   INCX – INTEGERInput
On entry: the increment in the subscripts of X between successive elements of x.
Constraint: INCX>0.

6 Error Indicators and Warnings

None.

7 Accuracy

Not applicable.

8 Parallelism and Performance

F06HBF is not threaded in any implementation.

9 Further Comments

None.

10 Example

None.
F06 Chapter Contents
F06 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F06HCF : NAG Library, Mark 26

F06 Chapter Contents
F06 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F06HCF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
10 Example

1 Purpose

F06HCF multiplies a complex vector by a complex diagonal matrix.

2 Specification

SUBROUTINE F06HCF ( N, D, INCD, X, INCX)
INTEGER | N, INCD, INCX
COMPLEX (KIND=nag_wp) | D(*), X(*)

3 Description

F06HCF performs the operation
x←Dx
where x is an n-element complex vector and D=diag d is a complex diagonal matrix.
Equivalently, the routine performs the element-by-element product of the vectors x and d
xi=dixi,   i=1,2,…,n.

4 References

None.

5 Arguments

1:   N – INTEGERInput
On entry: n, the number of elements in d and x.
2:   D* – COMPLEX (KIND=nag_wp) arrayInput
Note: the dimension of the array D must be at least max 1, 1+N-1 ×INCD .
On entry: the vector d.
If INCD>0, di must be stored in D i-1×INCD+1 , for i=1,2,…,N.
If INCD<0, di must be stored in D 1-N-i×INCD , for i=1,2,…,N.
3:   INCD – INTEGERInput
On entry: the increment in the subscripts of D between successive elements of d.
4:   X* – COMPLEX (KIND=nag_wp) arrayInput/Output
Note: the dimension of the array X must be at least max 1, 1+N-1 ×INCX .
On entry: the array X must contain the n-element vector x.
If INCX>0, xi must be stored in X 1+i-1×INCX , for i=1,2,…,N.
If INCX<0, xi must be stored in X 1-N-i×INCX , for i=1,2,…,N.
On exit: the updated vector x stored in the array elements used to supply the original vector x.
Intermediate elements of X are unchanged.
5:   INCX – INTEGERInput
On entry: the increment in the subscripts of X between successive elements of x.

6 Error Indicators and Warnings

None.

7 Accuracy

Not applicable.

8 Parallelism and Performance

F06HCF makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

None.

10 Example

None.
F06 Chapter Contents
F06 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F06HDF : NAG Library, Mark 26

F06 Chapter Contents
F06 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F06HDF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
10 Example

1 Purpose

F06HDF multiplies a complex vector by a scalar, preserving the input vector.

2 Specification

SUBROUTINE F06HDF ( N, ALPHA, X, INCX, Y, INCY)
INTEGER | N, INCX, INCY
COMPLEX (KIND=nag_wp) | ALPHA, X(*), Y(*)

3 Description

F06HDF performs the operation
y←αx
where x and y are n-element complex vectors scattered with stride INCX and INCY respectively, and α is a complex scalar.

4 References

None.

5 Arguments

1:   N – INTEGERInput
On entry: n, the number of elements in x and y.
2:   ALPHA – COMPLEX (KIND=nag_wp)Input
On entry: the scalar α.
3:   X* – COMPLEX (KIND=nag_wp) arrayInput
Note: the dimension of the array X must be at least max 1, 1+N-1 ×INCX .
On entry: the n-element vector x.
If INCX>0, xi must be stored in X 1+i-1×INCX, for i=1,2,…,N.
If INCX<0, xi must be stored in X 1-N-i×INCX, for i=1,2,…,N.
Intermediate elements of X are not referenced.
4:   INCX – INTEGERInput
On entry: the increment in the subscripts of X between successive elements of x.
5:   Y* – COMPLEX (KIND=nag_wp) arrayOutput
Note: the dimension of the array Y must be at least max 1, 1+N-1 ×INCY .
On exit: the vector y.
If INCY>0, yi will be stored in Y 1+i-1×INCY, for i=1,2,…,N.
If INCY<0, yi will be stored in Y 1-N-i×INCY, for i=1,2,…,N.
Intermediate elements of Y are unchanged.
6:   INCY – INTEGERInput
On entry: the increment in the subscripts of Y between successive elements of y.

6 Error Indicators and Warnings

None.

7 Accuracy

Not applicable.

8 Parallelism and Performance

F06HDF is not threaded in any implementation.

9 Further Comments

None.

10 Example

None.
F06 Chapter Contents
F06 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F06HGF : NAG Library, Mark 26

F06 Chapter Contents
F06 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F06HGF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
10 Example

1 Purpose

F06HGF negates a complex vector.

2 Specification

SUBROUTINE F06HGF ( N, X, INCX)
INTEGER | N, INCX
COMPLEX (KIND=nag_wp) | X(*)

3 Description

F06HGF performs the operation
x←-x
where x is an n-element complex vector scattered with stride INCX.

4 References

None.

5 Arguments

1:   N – INTEGERInput
On entry: n, the number of elements in x.
2:   X* – COMPLEX (KIND=nag_wp) arrayInput/Output
Note: the dimension of the array X must be at least max 1, 1+N-1 ×INCX .
On entry: the n-element vector x. xi must be stored in X 1+i-1×INCX, for i=1,2,…,N.
Intermediate elements of X are not referenced.
On exit: the vector -x stored in the array elements used to supply the original vector x.
Intermediate elements of X are unchanged.
3:   INCX – INTEGERInput
On entry: the increment in the subscripts of X between successive elements of x.
Constraint: INCX>0.

6 Error Indicators and Warnings

None.

7 Accuracy

Not applicable.

8 Parallelism and Performance

F06HGF is not threaded in any implementation.

9 Further Comments

None.

10 Example

None.
F06 Chapter Contents
F06 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F06HMF (ZROT) : NAG Library, Mark 26

F06 Chapter Contents
F06 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F06HMF (ZROT)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
10 Example

1 Purpose

F06HMF (ZROT) applies a plane rotation with a real cosine and complex sine to two complex vectors.

2 Specification

SUBROUTINE F06HMF ( N, CX, INCX, CY, INCY, C, S)
INTEGER | N, INCX, INCY
REAL (KIND=nag_wp) | C
COMPLEX (KIND=nag_wp) | CX(*), CY(*), S
The routine may be called by its LAPACK name zrot.

3 Description

F06HMF (ZROT) applies a plane rotation, where the cosine is real and the sine is complex, to two n-element complex vectors x and y:
xT yT ← c s -s- c xT yT .

4 References

None.

5 Arguments

1:   N – INTEGERInput
On entry: n, the number of elements in x and y.
2:   CX* – COMPLEX (KIND=nag_wp) arrayInput/Output
Note: the dimension of the array CX must be at least max 1, 1+N-1 ×INCX .
On entry: the n-element vector x.
If INCX>0, xi must be stored in CX 1+i-1×INCX, for i=1,2,…,N.
If INCX<0, xi must be stored in CX 1-N-i×INCX, for i=1,2,…,N.
Intermediate elements of CX are not referenced.
On exit: the transformed vector x stored in the array elements used to supply the original vector x.
Intermediate elements of CX are unchanged.
3:   INCX – INTEGERInput
On entry: the increment in the subscripts of CX between successive elements of x.
4:   CY* – COMPLEX (KIND=nag_wp) arrayInput/Output
Note: the dimension of the array CY must be at least max 1, 1+N-1 ×INCY .
On entry: the n-element vector y.
If INCY>0, yi must be stored in CY 1+i-1×INCY, for i=1,2,…,N.
If INCY<0, yi must be stored in CY 1-N-i×INCY, for i=1,2,…,N.
Intermediate elements of CY are not referenced.
On exit: the transformed vector y.
Intermediate elements of CY are unchanged.
5:   INCY – INTEGERInput
On entry: the increment in the subscripts of CY between successive elements of y.
6:   C – REAL (KIND=nag_wp)Input
On entry: the value c, the cosine of the rotation.
7:   S – COMPLEX (KIND=nag_wp)Input
On entry: the value s, the sine of the rotation.

6 Error Indicators and Warnings

None.

7 Accuracy

Not applicable.

8 Parallelism and Performance

F06HMF (ZROT) is not threaded in any implementation.

9 Further Comments

None.

10 Example

None.
F06 Chapter Contents
F06 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F06HPF : NAG Library, Mark 26

F06 Chapter Contents
F06 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F06HPF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
10 Example

1 Purpose

F06HPF applies a complex plane rotation to two complex vectors.

2 Specification

SUBROUTINE F06HPF ( N, X, INCX, Y, INCY, C, S)
INTEGER | N, INCX, INCY
COMPLEX (KIND=nag_wp) | X(*), Y(*), C, S

3 Description

F06HPF applies a complex plane rotation to two n-element complex vectors x and y:
xT yT ← c s -s- c- xT yT .

4 References

None.

5 Arguments

1:   N – INTEGERInput
On entry: n, the number of elements in x and y.
2:   X* – COMPLEX (KIND=nag_wp) arrayInput/Output
Note: the dimension of the array X must be at least max 1, 1+N-1 ×INCX .
On entry: the n-element vector x.
If INCX>0, xi must be stored in X 1+i-1×INCX, for i=1,2,…,N.
If INCX<0, xi must be stored in X 1-N-i×INCX, for i=1,2,…,N.
Intermediate elements of X are not referenced.
On exit: the transformed vector x stored in the array elements used to supply the original vector x.
Intermediate elements of X are unchanged.
3:   INCX – INTEGERInput
On entry: the increment in the subscripts of X between successive elements of x.
4:   Y* – COMPLEX (KIND=nag_wp) arrayInput/Output
Note: the dimension of the array Y must be at least max 1, 1+N-1 ×INCY .
On entry: the n-element vector y.
If INCY>0, yi must be stored in Y 1+i-1×INCY, for i=1,2,…,N.
If INCY<0, yi must be stored in Y 1-N-i×INCY, for i=1,2,…,N.
Intermediate elements of Y are not referenced.
On exit: the transformed vector y.
Intermediate elements of Y are unchanged.
5:   INCY – INTEGERInput
On entry: the increment in the subscripts of Y between successive elements of y.
6:   C – COMPLEX (KIND=nag_wp)Input
On entry: the value c, the cosine of the rotation.
7:   S – COMPLEX (KIND=nag_wp)Input
On entry: the value s, the sine of the rotation.

6 Error Indicators and Warnings

None.

7 Accuracy

Not applicable.

8 Parallelism and Performance

F06HPF is not threaded in any implementation.

9 Further Comments

None.

10 Example

None.
F06 Chapter Contents
F06 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F06HQF : NAG Library, Mark 26

F06 Chapter Contents
F06 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F06HQF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
10 Example

1 Purpose

F06HQF generates a sequence of complex plane rotations.

2 Specification

SUBROUTINE F06HQF ( PIVOT, DIRECT, N, ALPHA, X, INCX, C, S)
INTEGER | N, INCX
REAL (KIND=nag_wp) | C(N)
COMPLEX (KIND=nag_wp) | ALPHA, X(*), S(N)
CHARACTER(1) | PIVOT, DIRECT

3 Description

F06HQF generates the parameters of a complex unitary matrix P, of order n+1, chosen so as to set to zero the elements of a supplied n-element complex vector x.
If PIVOT='F' and DIRECT='F', or if PIVOT='V' and DIRECT='B',
P α x = β 0 ;
If PIVOT='F' and DIRECT='B', or if PIVOT='V' and DIRECT='F',
P x α = 0 β .
Here α and β are complex scalars.
P is represented as a sequence of n plane rotations Pk, as specified by PIVOT and DIRECT; Pk is chosen to annihilate xk, and its 2 by 2 plane rotation part has the form
ck s-k -sk ck ,
with ck real. The tangent of the rotation, tk, is overwritten on xk.

4 References

None.

5 Arguments

1:   PIVOT – CHARACTER(1)Input
On entry: specifies the plane rotated by Pk.
PIVOT='V' (variable pivot)
Pk rotates the k,k+1 plane.
PIVOT='F' (fixed pivot)
Pk rotates the 1,k+1 plane if DIRECT='F', or the k,n+1 plane if DIRECT='B'.
Constraint: PIVOT='V' or 'F'.
2:   DIRECT – CHARACTER(1)Input
On entry: specifies the sequence direction.
DIRECT='F' (forward sequence)
P=Pn⋯P 2P 1.
DIRECT='B' (backward sequence)
P=P 1P 2⋯Pn.
Constraint: DIRECT='F' or 'B'.
3:   N – INTEGERInput
On entry: n, the number of elements in x.
4:   ALPHA – COMPLEX (KIND=nag_wp)Input/Output
On entry: the scalar α.
On exit: the scalar β.
5:   X* – COMPLEX (KIND=nag_wp) arrayInput/Output
Note: the dimension of the array X must be at least max 1, 1+N-1 ×INCX .
On entry: the n-element vector x. xi must be stored in X 1+i-1×INCX, for i=1,2,…,N.
Intermediate elements of X are not referenced.
On exit: the referenced elements are overwritten by details of the plane rotations.
6:   INCX – INTEGERInput
On entry: the increment in the subscripts of X between successive elements of x.
Constraint: INCX>0.
7:   C N – REAL (KIND=nag_wp) arrayOutput
On exit: the values ck, the cosines of the rotations.
8:   S N – COMPLEX (KIND=nag_wp) arrayOutput
On exit: the values sk, the sines of the rotations.

6 Error Indicators and Warnings

None.

7 Accuracy

Not applicable.

8 Parallelism and Performance

F06HQF is not threaded in any implementation.

9 Further Comments

None.

10 Example

None.
F06 Chapter Contents
F06 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F06HRF : NAG Library, Mark 26

F06 Chapter Contents
F06 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F06HRF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
10 Example

1 Purpose

F06HRF generates a complex elementary reflection.

2 Specification

SUBROUTINE F06HRF ( N, ALPHA, X, INCX, TOL, THETA)
INTEGER | N, INCX
REAL (KIND=nag_wp) | TOL
COMPLEX (KIND=nag_wp) | ALPHA, X(*), THETA

3 Description

F06HRF generates details of a complex elementary reflection (Householder matrix), P, such that
P α x = β 0
where P is unitary, α is a complex scalar, β is a real scalar, and x is an n-element complex vector.
P is given in the form
P=I-γ ζ z ζ zH ,
where z is an n-element complex vector, γ is a complex scalar such that Re γ=1, and ζ is a real scalar. γ and ζ are returned in a single complex value θ=ζ,Im γ. Thus ζ=Re θ and γ=1,Im θ.
If x is such that
max Re xi,Im xi≤max tol,ε max Re α,Im α,
where ε is the machine precision and tol is a user-supplied tolerance, then:
  • either θ is set to 0, in which case P can be taken to be the unit matrix;
  • or θ is set so that Re θ≤0 and θ≠0, in which case
    P= θ 0 0 I .
Otherwise 1≤Re θ≤2.

4 References

None.

5 Arguments

1:   N – INTEGERInput
On entry: n, the number of elements in x and z.
2:   ALPHA – COMPLEX (KIND=nag_wp)Input/Output
On entry: the scalar α.
On exit: the scalar β.
3:   X* – COMPLEX (KIND=nag_wp) arrayInput/Output
Note: the dimension of the array X must be at least max 1, 1+N-1 ×INCX .
On entry: the n-element vector x. xi must be stored in X 1+i-1×INCX, for i=1,2,…,N.
Intermediate elements of X are not referenced.
On exit: the referenced elements are overwritten by details of the complex elementary reflection.
4:   INCX – INTEGERInput
On entry: the increment in the subscripts of X between successive elements of x.
Constraint: INCX>0.
5:   TOL – REAL (KIND=nag_wp)Input
On entry: the value tol.
6:   THETA – COMPLEX (KIND=nag_wp)Output
On exit: the scalar θ.

6 Error Indicators and Warnings

None.

7 Accuracy

Not applicable.

8 Parallelism and Performance

F06HRF makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

None.

10 Example

None.
F06 Chapter Contents
F06 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F06HTF : NAG Library, Mark 26

F06 Chapter Contents
F06 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F06HTF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
10 Example

1 Purpose

F06HTF applies a complex elementary reflection to a complex vector.

2 Specification

SUBROUTINE F06HTF ( N, DELTA, Y, INCY, THETA, Z, INCZ)
INTEGER | N, INCY, INCZ
COMPLEX (KIND=nag_wp) | DELTA, Y(*), THETA, Z(*)

3 Description

F06HTF applies a complex elementary reflection (Householder matrix) P, as generated by F06HRF, to a given complex vector:
δ y ←P δ y
where y is an n-element complex vector and δ is a complex scalar.
To apply the conjugate transpose matrix PH, call F06HTF with θ- in place of θ.

4 References

None.

5 Arguments

1:   N – INTEGERInput
On entry: n, the number of elements in y and z.
2:   DELTA – COMPLEX (KIND=nag_wp)Input/Output
On entry: the original scalar δ.
On exit: the transformed scalar δ.
3:   Y* – COMPLEX (KIND=nag_wp) arrayInput/Output
Note: the dimension of the array Y must be at least max 1, 1+N-1 ×INCY .
On entry: the original vector y.
If INCY>0, yi must be stored in Y 1+i-1 ×INCY , for i=1,2,…,N.
If INCY<0, yi must be stored in Y 1-N-i ×INCY , for i=1,2,…,N.
On exit: the transformed stored in the same array elements used to supply the original vector y.
4:   INCY – INTEGERInput
On entry: the increment in the subscripts of Y between successive elements of y.
5:   THETA – COMPLEX (KIND=nag_wp)Input
On entry: the value θ, as returned by F06HRF.
If θ=0, P is assumed to be the unit matrix and the transformation is skipped.
Constraint: if THETA≤0, n=0.
6:   Z* – COMPLEX (KIND=nag_wp) arrayInput
Note: the dimension of the array Z must be at least max 1, 1+N-1 ×INCZ .
On entry: the vector z, as returned by F06HRF.
If INCZ>0, zi must be stored in Z 1+i-1×INCZ , for i=1,2,…,N.
If INCZ<0, zi must be stored in Z 1-N-i×INCZ , for i=1,2,…,N.
7:   INCZ – INTEGERInput
On entry: the increment in the subscripts of Z between successive elements of z.

6 Error Indicators and Warnings

None.

7 Accuracy

Not applicable.

8 Parallelism and Performance

F06HTF makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

None.

10 Example

None.
F06 Chapter Contents
F06 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F06 Chapter Introduction : NAG Library, Mark 26

F06 Chapter Contents
NAG Library Manual

NAG Library Chapter Introduction

F06 – Linear Algebra Support Routines

▸▿ Contents

1 Scope of the Chapter
▸▿ 2 Background to the Problems
2.1 The Use of BLAS Names
▸▿ 2.2 Background Information
2.2.1 Real plane rotations
2.2.2 Complex plane rotations
2.2.3 Elementary real (Householder) reflections
2.2.4 Elementary complex (Householder) reflections
▸▿ 3 Recommendations on Choice and Use of Available Routines
▸▿ 3.1 Naming Scheme
3.1.1 NAG names
3.1.2 BLAS names
3.1.3 LAPACK names
3.2 The Level-0 Scalar Routines
3.3 The Level-1 Vector Routines
3.4 The Level-2 Matrix-vector and Matrix Routines
3.5 The Level-3 Matrix-matrix Routines
3.6 Vector Arguments
▸▿ 3.7 Matrix Arguments and Storage Schemes
3.7.1 Conventional storage
3.7.2 Packed storage
3.7.3 Rectangular Full Packed (RFP) storage
3.7.4 Band storage
3.7.5 Unit triangular matrices
3.7.6 Real diagonal elements of complex Hermitian matrices
3.7.7 Spiked matrices
▸▿ 3.8 Option Parameters
3.8.1 Matrix norms
3.9 Error Handling
4 Functionality Index
5 Auxiliary Routines Associated with Library Routine Arguments
6 Routines Withdrawn or Scheduled for Withdrawal
7 References

1 Scope of the Chapter

This chapter is concerned with basic linear algebra routines which perform elementary algebraic operations involving scalars, vectors and matrices. It includes routines which conform to the specifications of the BLAS (Basic Linear Algebra Subprograms).

2 Background to the Problems

A number of the routines in this chapter meet the specification of the Basic Linear Algebra Subprograms (BLAS) as described in Lawson et al. (1979), Dodson et al. (1991), Dongarra et al. (1988) and Dongarra et al. (1990). The first reference describes a set of routines concerned with operations on scalars and vectors: these will be referred to here as the Level-0 and the Level-1 BLAS; the second reference describes a set of routines concerned with operations on sparse vectors: these will be referred to here as the Level-1 Sparse BLAS; the third reference describes a set of routines concerned with matrix-vector operations: these will be referred to here as the Level-2 BLAS; and the fourth reference describes a set of routines concerned with matrix-matrix operations: these will be referred to here as the Level-3 BLAS.
More generally we refer to the scalar routines in the chapter as Level-0 routines, to the vector routines as Level-1 routines, to the matrix-vector and matrix routines as Level-2 routines, and to the matrix-matrix routines as Level-3 routines. The terminology reflects the number of operations involved. For example, a Level-2 routine involves O n 2 operations for an n×n matrix.

2.1 The Use of BLAS Names

Many of the routines in other chapters of the Library call the routines in this chapter, and in particular a number of the BLAS are called. These routines are usually called by the BLAS name and so, for correct operation of the Library, it is essential that you do not attempt to link your own versions of these routines. If you are in any doubt about how to avoid this, please consult your computer centre or the NAG Response Centre.
The BLAS names are used in order to make use of efficient implementations of the routines when these exist. Such implementations are stringently tested before being used, to ensure that they correctly meet the specification of the BLAS, and that they return the desired accuracy (see, for example, Dodson et al. (1991), Dongarra et al. (1988) and Dongarra et al. (1990)).

2.2 Background Information

Most of the routines in this chapter implement straightforward scalar, vector and matrix operations that need no further explanation beyond a statement of the purpose of the routine. In this section we give some additional background information to those few cases where additional explanation may be necessary. A sub-section is devoted to each topic.

2.2.1 Real plane rotations

There are a number of routines in the chapter concerned with setting up and applying plane rotations. This section discusses the real case and the next section looks at the complex case. For further background information see Golub and Van Loan (1996).
A plane rotation matrix for the i,j plane, R ij, is an orthogonal matrix that is different from the unit matrix only in the elements r ii, r jj, r ij and r ji. If we put
R= r ii r ij r ji r jj , (1)
then, in the real case, it is usual to choose R ij so that
R= -c s -s c ,   c=cos⁡θ,   s=sin⁡θ.
An exception is routine F06FPF which applies the so-called symmetric rotation for which
R= c -s s -c . (2)
The application of plane rotations is straightforward and needs no further elaboration, so further comment is made only on the construction of plane rotations.
The most common use of plane rotations is to choose c and s so that for given a and b,
-c s -s c   a b = d 0 . (3)
In such an application the matrix R is often termed a Givens rotation matrix. There are two approaches to the construction of real Givens rotations in Chapter F06.
The BLAS routine F06AAF (DROTG), see Lawson et al. (1979) and Dodson and Grimes (1982), computes c, s and d as
d=σ a 2+b 2 1/2,
c= a/d, d≠0, 1, d=0,     s= b/d, d≠0, 0, d=0, (4)
where σ= sign⁡a, a>b sign⁡b, a≤b .
The value z defined as
z= s, s<c  or  c=0 1/c, 0<c≤s (5)
is also computed and this enables c and s to be reconstructed from the single value z as
c= 0, z=1 1-z 2 1/2, z<1 1/z, z>1     s= 1, z=1 z, z<1 1-c 2 1/2, z>1 .
The other Chapter F06 routines for constructing Givens rotations are based on the computation of the tangent, t=tan⁡θ. t is computed as
t= 0, b=0 b/a, b≤a.flmax,b≠0 sign b/a.flmax, b>a.flmax sign b.flmax, b≠0,a=0 (6)
where flmax=1/flmin and flmin is the small positive value returned by X02AMF. The values of c and s are then computed or reconstructed via t as
c= 1/1+t 2 1/2, eps≤t≤1/eps 1, t<eps 1/t, t>1/eps     s= c.t, eps≤t≤1/eps t, t<eps sign⁡t, t>1/eps (7)
where eps is the machine precision. Note that c is always non-negative in this scheme and that the same expressions are used in the initial computation of c and s from a and b as in any subsequent recovery of c and s via t. This is the approach used by many of the NAG Library routines that require plane rotations. d is computed simply as
d=c.a+s.b.
You need not be too concerned with the above detail, since routines are provided for setting up, recovering and applying such rotations.
Another use of plane rotations is to choose c and s so that for given x, y and z
-c s -s c   x y y z   c -s s -c = a 0 0 b . (8)
In such an application the matrix R is often termed a Jacobi rotation matrix. The routine that generates a Jacobi rotation (F06BEF) first computes the tangent t and then computes c and s via t as described above for the Givens rotation.

2.2.2 Complex plane rotations

In the complex case a plane rotation matrix for the i,j plane, R ij is a unitary matrix and, analogously to the real case, it is usual to choose R ij so that
R= -c- s- -s c ,   c 2+s 2=1, (9)
where a- denotes the complex conjugate of a.
The BLAS (see Lawson et al. (1979)) do not contain a routine for the generation of complex rotations, and so the routines in Chapter F06 are all based upon computing c and s via t=b/a in an analogous manner to the real case. R can be chosen to have either c real, or s real and there are routines for both cases.
When c is real then it is non-negative and the transformation
-c s- -s c   a b = d 0 (10)
is such that if a is real then d is also real.
When s is real then the transformation
-c- s -s c   a b = d 0 (11)
is such that if b is real then d is also real.

2.2.3 Elementary real (Householder) reflections

There are a number of routines in the chapter concerned with setting up and applying Householder transformations. This section discusses the real case and the next section looks at the complex case. For further background information see Golub and Van Loan (1996).
A real elementary reflector, P, is a matrix of the form
P=I-μu uT,   μ uT u=2, (12)
where μ is a scalar and u is a vector, and P is both symmetric and orthogonal. In the routines in Chapter F06, u is expressed in the form
u= ζ z ,   ζ​ a scalar (13)
because in many applications ζ and z are not contiguous elements. The usual use of elementary reflectors is to choose μ and u so that for given α and x
P α x = β 0 ,   α​ and ​β​ scalars. (14)
Such a transformation is often termed a Householder transformation. There are two choices of μ and u available in Chapter F06.
The first form of the Householder transformation is compatible with that used by LINPACK (see Dongarra et al. (1979)) and has
μ=1/ζ. (15)
This choice makes ζ satisfy
1≤ζ≤2.
The second form, and the form used by many of the NAG Library routines, has
μ=1 (16)
which makes
1≤ζ≤2.
In both cases the special setting
ζ=0 (17)
is used by the routines to flag the case where P=I.
Note that while there are routines to apply an elementary reflector to a vector, there are no routines available in Chapter F06 to apply an elementary reflector to a matrix. This is because such transformations can readily and efficiently be achieved by calls to the matrix-vector Level 2 BLAS routines. For example, to form PA for a given matrix
PA = I-μu uT A=A-μu uT A = A-μu bT,  b=AT u, (18)
and so we can call a matrix-vector product routine to form b=AT u and then call a rank-one update routine to form A-μu bT. Of course, we must skip the transformation when ζ has been set to zero.

2.2.4 Elementary complex (Householder) reflections

A complex elementary reflector, P, is a matrix of the form
P=I-μu uH,   μ uH u=2,   μ​ real,
where uH denotes the complex conjugate of uT, and P is both Hermitian and unitary. For convenience in a number of applications this definition can be generalized slightly by allowing μ to be complex and so defining the generalized elementary reflector as
P=I-μu uH,   μ 2uH u=μ+μ- (19)
for which P is still unitary, but is no longer Hermitian.
The Chapter F06 routines choose μ and ζ so that
Re μ=1,   Im ζ=0 (20)
and this reduces to (12) with the choice (16) when μ and u are real. This choice is used because μ and u can now be chosen so that in the Householder transformation (14) we can make
Im β=0
and, as in the real case,
1≤ζ≤2.
Rather than returning μ and ζ as separate arguments the Chapter F06 routines return the single complex value θ defined as
θ=ζ+i.Im μ,  i=-1.
Obviously ζ and μ can be recovered as
ζ=Re θ,  μ=1+i.Im θ.
The special setting
θ=0
is used to flag the case where P=I, and
Re θ≤0,  Im θ≠0
is used to flag the case where
P= γ 0 0 I ,   γ​ a scalar (21)
and in this case θ actually contains the value of γ. Notice that with both (18) and (21) we merely have to supply θ- rather than θ in order to represent PH.

3 Recommendations on Choice and Use of Available Routines

3.1 Naming Scheme

3.1.1 NAG names

Table 1 shows the naming scheme for the routines in this chapter.
 |  | Level-0 | Level-1 | Level-2 | Level-3
integer | Chapter F06 routine | – | F06D_F | – | –
‘real’ | BLAS routine | F06A_F | F06E_F | F06P_F | F06Y_F
‘real’ | Chapter F06 routine | F06B_F | F06F_F | F06Q_F | –
 |  |  |  | F06R_F |
‘complex’ | BLAS routine | – | F06G_F | F06S_F | F06Z_F
‘complex’ | Chapter F06 routine | F06C_F | F06H_F | F06T_F | –
 |  |  |  | F06U_F |
‘mixed type’ | BLAS routine | – | F06J_F | – | –
‘mixed type’ | Chapter F06 routine | – | F06K_F | F06V_F | –
‘real’ and ‘complex’ | LAPACK routines | – | – | F06W_F | F06W_F
Table 1
The heading ‘mixed type’ is for routines where a mixture of data types is involved, such as a routine that returns the real Euclidean length of a complex vector. In future marks of the Library, routines may be included in categories that are currently empty and further categories may be introduced.

3.1.2 BLAS names

Those routines which conform to the specifications of the BLAS may be called either by their NAG names or by their BLAS names.
In many implementations of the NAG Library, references to BLAS names may be linked to an efficient machine-specific implementation of the BLAS, usually provided by the vendor of the machine. Such implementations are stringently tested before being used with the NAG Library, to ensure that they correctly meet the specifications of the BLAS, and that they return the desired accuracy. Use of BLAS names is recommended for efficiency.
References to NAG routine names (beginning F06-) are always linked to the code provided in the NAG Library and may be significantly slower than the equivalent BLAS routine.
The names of the Level-2 and Level-3 BLAS follow a simple scheme (which is similar to that used for LAPACK routines in Chapters F07 and F08). Each name has the structure XYYZZZ, where the components have the following meanings:
– the initial letter X indicates the data type (real or complex) and precision:
S | real, single precision (in Fortran, REAL)
D | real, double precision (in Fortran, DOUBLE PRECISION)
C | complex, single precision (in Fortran, COMPLEX)
Z | complex, double precision (in Fortran, COMPLEX*16 or DOUBLE COMPLEX)
– the second and third letters YY indicate the type of the matrix A (and in some cases its storage scheme):
GE | general
GB | general band
SY | symmetric
SP | symmetric (packed storage)
SB | symmetric band
HE | (complex) Hermitian
HP | (complex) Hermitian (packed storage)
HB | (complex) Hermitian band
TR | triangular
TP | triangular (packed storage)
TB | triangular band
– the remaining 1, 2 or 3 letters ZZZ indicate the computation performed:
MV | matrix-vector product
MM | matrix-matrix product
R | rank-1 update
R2 | rank-2 update
RK | rank-k update
R2K | rank-2 k update
SV | solve a system of linear equations
SM | solve a system of linear equations with a matrix of right-hand sides
Thus the routine DGEMV performs a matrix-vector product involving a real general matrix in double precision; the corresponding routine for a complex general matrix is ZGEMV.
The names of the Level-1 BLAS mostly follow the same convention for the initial letter (S-, C-, D- or Z-), except for a few involving data of mixed type, where the first two characters are precision-dependent.

3.1.3 LAPACK names

There are some LAPACK routines in this chapter that have BLAS-like functionalty. Four are equivalent to BLAS routines but for matrices stored in Rectangular Full Packed (RFP) format. The naming convention for these is as above with the addition of the matrix types:
HF | (complex) Hermitian (RFP storage)
TF | triangular (RFP storage)
SF | symmetric (RFP storage)
There are an additonal two that compute norms of RFP matrices. These have second and third letters LA (signifying LAPACK), fourth letter N (signifying norm), and fifth and sixth letter signifying matrix type as above. For example ZLANHF computes the norm of a Hermitian matrix in RFP format.

3.2 The Level-0 Scalar Routines

The Level-0 routines perform operations on scalars or on vectors or matrices of order 2.

3.3 The Level-1 Vector Routines

The Level-1 routines perform operations either on a single vector or on a pair of vectors.

3.4 The Level-2 Matrix-vector and Matrix Routines

The Level-2 routines perform operations involving either a matrix on its own, or a matrix and one or more vectors.

3.5 The Level-3 Matrix-matrix Routines

The Level-3 routines perform operations involving matrix-matrix products.

3.6 Vector Arguments

Vector arguments (except in the Level-1 Sparse BLAS) are represented by a one-dimensional array, immediately followed by an increment argument whose name consists of the three characters INC followed by the name of the array. For example, a vector x is represented by the two arguments X and INCX. The length of the vector, n say, is passed as a separate argument, N.
The increment argument is the spacing (stride) in the array between the elements of the vector. For instance, if INCX=2, then the elements of x are in locations x 1,x 3,…,x 2 n-1 of the array X and the intermediate locations x 2,x 4,…,x 2 n-2 are not referenced.
When INCX>0, the vector element xi is in the array element X 1+i-1×INCX. When INCX≤0, the elements are stored in the reverse order so that the vector element xi is in the array element X 1-n-i×INCX and hence, in particular, the element xn is in X 1. The declared length of the array X in the calling subroutine must be at least 1+N-1×INCX.
Negative increments are permitted only for:
  • Level-1 routines which have more than one vector argument;
  • Level-2 BLAS routines (but not for other Level-2 routines)
Zero increments are formally permitted for Level-1 routines with more than one argument (in which case the element X 1 is accessed repeatedly), but their use is strongly discouraged since the effect may be implementation-dependent. There is usually an alternative routine in this chapter, with a simplified argument list, to achieve the required purpose. Zero increments are not permitted in the Level-2 BLAS.
In the Level-1 Sparse BLAS, each routine operates on two vectors x and y. The vector x is stored as a compressed sparse vector, and is represented by the three arguments NZ, X and INDX; NZ is the number of ‘interesting’ (usually nonzero) elements of x, and INDX is a one-dimensional index array such that
x INDX k=X k,  k=1,2,…,NZ.
The (mathematical) length of the vector, n say, does not need to be supplied; it is assumed that 1≤INDX k≤n. For example, the vector
x=0,4,0,0,1,0,0,0,6,0
could be represented with NZ=3, X=4,1,6, INDX=2,5,9. The second vector y is stored conventionally, and is represented simply by the one-dimensional array Y, with yi in Y i; the increment is assumed to be 1. Only the elements Y INDX k are referenced.
Non-positive values of NZ are permitted, in which case the routines return immediately — except that functions set their value to zero before returning. For those routines where Y is an output argument the values in the array INDX must be distinct; violating this condition may yield incorrect results.

3.7 Matrix Arguments and Storage Schemes

In this chapter the following different storage schemes are used for matrices:
  • – conventional storage in a two-dimensional array;
  • – packed and RFP storage for symmetric, Hermitian or triangular matrices;
  • – band storage for band matrices;
  • – storage for spiked matrices.
These storage schemes are compatible with those used in Chapters F07 and F08. (Different schemes for packed or band storage are used in a few older routines in Chapters F01, F02, F03 and F04.)
Chapter F01 provides some utility routines for conversion between storage schemes.
In the examples, * indicates an array element which need not be set and is not referenced by the routines. The examples illustrate only the relevant leading rows and columns of the arrays; array arguments may of course have additional rows or columns, according to the usual rules for passing array arguments in Fortran.

3.7.1 Conventional storage

Please see Section 3.3.1 in the F07 Chapter Introduction for full details.

3.7.2 Packed storage

Please see Section 3.3.2 in the F07 Chapter Introduction for full details.

3.7.3 Rectangular Full Packed (RFP) storage

Please see Section 3.3.3 in the F07 Chapter Introduction for full details.

3.7.4 Band storage

Please see Section 3.3.4 in the F07 Chapter Introduction for full details.

3.7.5 Unit triangular matrices

Please see Section 3.3.5 in the F07 Chapter Introduction for full details.

3.7.6 Real diagonal elements of complex Hermitian matrices

Please see Section 3.3.6 in the F07 Chapter Introduction for full details.

3.7.7 Spiked matrices

A few routines in this chapter (F06QSF, F06QWF, F06TSF and F06TWF) deal with upper spiked matrices. These are upper triangular matrices with an additional nonzero row or column below the diagonal.
The position of the spike is defined by indices k 1 and k 2; it is assumed that k 1<k 2. A row spike has nonzero elements in the k 2th row, a k 2,k for k=k 1,k 1+1,…,k 2-1; a column spike has nonzero elements in the k 1th column, a k+1,k 1 for k=k 1,k 1+1,…,k 2-1. For example, when n=6, k 1=2 and k 2=5:
Row spike | Column spike
a 11 a 12 a 13 a 14 a 15 a 16 a 22 a 23 a 24 a 25 a 26 a 33 a 34 a 35 a 36 a 44 a 45 a 46 a 52 a 53 a 54 a 55 a 56 a 66 | a 11 a 12 a 13 a 14 a 15 a 16 a 22 a 23 a 24 a 25 a 26 a 32 a 33 a 34 a 35 a 36 a 42 a 44 a 45 a 46 a 52 a 55 a 56 a 66
The storage scheme adopted by the routines in this chapter is for the upper triangular part of the spiked matrix to be stored conventionally in a two-dimensional array A, with the subdiagonal elements of the spike stored in a separate vector.

3.8 Option Parameters

Many of the routines in this chapter have one or more option arguments, of type CHARACTER. The descriptions in the routine documents refer only to upper-case values (for example UPLO='U' or UPLO='L'); however, in every case, the corresponding lower-case characters may be supplied (with the same meaning). Any other value is illegal.
A longer character string can be passed as the actual argument, making the calling program more readable, but only the first character is significant. (This is a feature of Fortran.) For example:
 CALL DTRSV('Upper','Transpose','Non-unit',...)
The following option arguments are used in this chapter:
  • If TRANS='N', operate with the matrix (Not transposed);
  • if TRANS='T', operate with the Transpose of the matrix;
  • if TRANS='C', operate with the Conjugate transpose of the matrix.
  • If UPLO='U', upper triangle or trapezoid of matrix;
  • if UPLO='L', lower triangle or trapezoid of matrix.
  • If DIAG='U', unit triangular;
  • if DIAG='N', nonunit triangular.
  • If SIDE='L', operate from the left-hand side;
  • if SIDE='R', operate from the right-hand side.
  • If PIVOT='V', variable pivot (in applying a sequence of plane rotations);
  • if PIVOT='B', bottom pivot;
  • if PIVOT='T', top pivot;
  • if PIVOT='F', fixed pivot.
  • If DIRECT='B', backward sequence of plane rotations;
  • if DIRECT='F', forward sequence of plane rotations.
  • If NORM='1' or 'O', 1-norm of a matrix;
  • if NORM='I', ∞-norm of a matrix;
  • if NORM='F' or 'E', Frobenius or Euclidean norm of a matrix;
  • if NORM='M', maximum absolute value of the elements of a matrix (not strictly a norm).
  • If MATRIX='G', general (rectangular or square) matrix;
  • if MATRIX='U', upper trapezoidal or triangular matrix;
  • if MATRIX='L', lower trapezoidal or triangular matrix.
  • if TRANSR='N', matrix stored in normal RFP format (Not transposed).
  • if TRANSR='T', transpose of the matrix stored in RFP format.
  • if TRANSR='C', conjugate transpose of the matrix stored in RFP format.

3.8.1 Matrix norms

The option argument NORM specifies different matrix norms whose definitions are given here for reference (for a general m by n matrix A):
  • One-norm (NORM='O' or '1'):
    A 1=maxj∑i=1 m a ij;
  • Infinity-norm (NORM='I'):
    A∞=maxi∑j=1 n a ij;
  • Frobenius or Euclidean norm (NORM='F' or 'E'):
    A F= ∑i=1 m∑j=1 n a ij 2 1/2.
If A is symmetric or Hermitian, A 1=A∞.
The argument NORM can also be used to specify the maximum absolute value max i,j a ij (if NORM='M'), but this is not a norm in the strict mathematical sense.

3.9 Error Handling

Routines in this chapter do not use the usual NAG Library error-handling mechanism, involving the argument IFAIL.
If one of the Level-2 or Level-3 BLAS routines is called with an invalid value of one of its arguments, then an error message is output on the error message unit (see X04AAF), giving the name of the routine and the number of the first invalid argument, and execution of the program is terminated. The following values of arguments are invalid:
  • – any value of the character arguments TRANS, TRANSA, TRANSB, UPLO, SIDE or DIAG, whose meaning is not specified;
  • – a negative value of any of the arguments M, N, K, KL or KU;
  • – too small a value for any of the leading dimension arguments;
  • – a zero value for the increment arguments INCX and INCY.
Zero values for the matrix dimensions M, N or K are considered valid.
The other routines in this chapter do not report any errors in their arguments. Normally, if called, for example, with an unspecified value for one of the option arguments, or with a negative value of one of the problem dimensions M or N, they simply do nothing and return immediately.

4 Functionality Index

Level 0 (Scalar) operations,
complex numbers,
apply similarity rotation to 2 by 2 Hermitian matrix F06CHF
generate a plane rotation, storing the tangent, real cosine F06CAF
generate a plane rotation, storing the tangent, real sine F06CBF
quotient of two numbers, with overflow flag F06CLF
recover cosine and sine from given tangent, real cosine F06CCF
recover cosine and sine from given tangent, real sine F06CDF
real numbers,
apply similarity rotation to 2 by 2 symmetric matrix F06BHF
compute (a 2 + b 2)1 / 2 F06BNF
compute Euclidean norm from scaled form F06BMF
eigenvalue of 2 by 2 symmetric matrix F06BPF
generate a Jacobi plane rotation F06BEF
generate a plane rotation F06AAF (DROTG)
generate a plane rotation storing the tangent F06BAF
quotient of two numbers, with overflow flag F06BLF
recover cosine and sine from given tangent F06BCF
Level 1 (Vector) operations,
complex vector(s),
add scalar times a vector to another vector F06GCF (ZAXPY)
apply a complex plane rotation F06HPF
apply an elementary reflection to a vector F06HTF
apply a real plane rotation F06KPF (ZDROT)
broadcast a scalar into a vector F06HBF
copy a real vector to a complex vector F06KFF
copy a vector F06GFF (ZCOPY)
dot product of two vectors, conjugated F06GBF (ZDOTC)
dot product of two vectors, unconjugated F06GAF (ZDOTU)
Euclidean norm of a vector F06JJF (DZNRM2)
generate an elementary reflection F06HRF
generate a sequence of plane rotations F06HQF
index of element of largest absolute value F06JMF (IZAMAX)
multiply vector by a complex scalar F06GDF (ZSCAL)
multiply vector by a complex scalar, preserving input vector F06HDF
multiply vector by a real scalar F06JDF (ZDSCAL)
multiply vector by a real scalar, preserving input vector F06KDF
multiply vector by complex diagonal matrix F06HCF
multiply vector by real diagonal matrix F06KCF
multiply vector by reciprocal of a real scalar F06KEF
negate a vector F06HGF
sum of absolute values of vector-elements F06JKF (DZASUM)
swap two vectors F06GGF (ZSWAP)
update Euclidean norm in scaled form F06KJF
Complex vector(s),
apply plane rotation,
real cosine, complex sine F06HMF (ZROT)
integer vector(s),
broadcast a scalar into a vector F06DBF
copy a vector F06DFF
real vector(s),
add scalar times a vector to another vector F06ECF (DAXPY)
apply an elementary reflection to a vector (Linpack style) F06FUF
apply an elementary reflection to a vector (NAG style) F06FTF
apply a symmetric plane rotation to two vectors F06FPF
apply plane rotation F06EPF (DROT)
broadcast a scalar into a vector F06FBF
copy a vector F06EFF (DCOPY)
cosine of angle between two vectors F06FAF
dot product of two vectors F06EAF (DDOT)
elements of largest and smallest absolute value F06FLF
Euclidean norm of a vector F06EJF (DNRM2)
generate an elementary reflection (Linpack style) F06FSF
generate an elementary reflection (NAG style) F06FRF
generate a sequence of plane rotations F06FQF
index of element of largest absolute value F06JLF (IDAMAX)
index of last non-negligible element F06KLF
multiply vector by a scalar F06EDF (DSCAL)
multiply vector by a scalar, preserving input vector F06FDF
multiply vector by diagonal matrix F06FCF
multiply vector by reciprocal of a scalar F06FEF
negate a vector F06FGF
sum of absolute values of vector-elements F06EKF (DASUM)
swap two vectors F06EGF (DSWAP)
update Euclidean norm in scaled form F06FJF
weighted Euclidean norm of a vector F06FKF
Level 2 (Matrix-vector and matrix) operations,
complex matrix and vector(s),
apply sequence of plane rotations to a rectangular matrix,
complex cosine, real sine F06TYF
real cosine, complex sine F06TXF
real cosine and sine F06VXF
compute a norm or the element of largest absolute value,
band matrix F06UBF
general matrix F06UAF
Hermitian band matrix F06UEF
Hermitian matrix F06UCF
Hermitian matrix, packed form F06UDF
Hermitian matrix, RFP format F06WNF (ZLANHF)
Hermitian tridiagonal matrix F06UPF
Hessenberg matrix F06UMF
symmetric band matrix F06UHF
symmetric matrix F06UFF
symmetric matrix, packed form F06UGF
trapezoidal matrix F06UJF
triangular band matrix F06ULF
triangular matrix, packed form F06UKF
tridiagonal matrix F06UNF
compute upper Hessenberg matrix by applying sequence of plane rotations to an upper triangular matrix F06TVF
compute upper spiked matrix by applying sequence of plane rotations to an upper triangular matrix F06TWF
matrix initialization F06THF
matrix-vector product,
Hermitian band matrix F06SDF (ZHBMV)
Hermitian matrix F06SCF (ZHEMV)
Hermitian packed matrix F06SEF (ZHPMV)
rectangular band matrix F06SBF (ZGBMV)
rectangular matrix F06SAF (ZGEMV)
symmetric matrix F06TAF
symmetric packed matrix F06TCF
triangular band matrix F06SGF (ZTBMV)
triangular matrix F06SFF (ZTRMV)
triangular packed matrix F06SHF (ZTPMV)
permute rows or columns of a matrix,
permutations represented by an integer array F06VJF
permutations represented by a real array F06VKF
QR factorization by sequence of plane rotations,
of rank-1 update of upper triangular matrix F06TPF
of upper triangular matrix augmented by a full row F06TQF
QR factorization of UZ or RQ factorization of ZU, where U is upper triangular and Z is a sequence of plane rotations F06TTF
QR or RQ factorization by sequence of plane rotations,
of upper Hessenberg matrix F06TRF
of upper spiked matrix F06TSF
rank-1 update,
Hermitian matrix F06SPF (ZHER)
Hermitian packed matrix F06SQF (ZHPR)
rectangular matrix, conjugated vector F06SNF (ZGERC)
rectangular matrix, unconjugated vector F06SMF (ZGERU)
symmetric matrix F06TBF
symmetric packed matrix F06TDF
rank-2 update,
Hermitian matrix F06SRF (ZHER2)
Hermitian packed matrix F06SSF (ZHPR2)
matrix copy, rectangular or trapezoidal F06TFF
solution of a system of equations,
triangular band matrix F06SKF (ZTBSV)
triangular matrix F06SJF (ZTRSV)
triangular packed matrix F06SLF (ZTPSV)
unitary similarity transformation of a Hermitian matrix,
as sequence of plane rotations F06TMF
real matrix and vector(s),
apply sequence of plane rotations to a rectangular matrix F06QXF
compute a norm or the element of largest absolute value,
band matrix F06RBF
general matrix F06RAF
Hessenberg matrix F06RMF
matrix initialization F06QHF
symmetric band matrix F06REF
symmetric matrix F06RCF
symmetric matrix, packed form F06RDF
symmetric matrix, RFP format F06WAF (DLANSF)
symmetric tridiagonal matrix F06RPF
trapezoidal matrix F06RJF
triangular band matrix F06RLF
triangular matrix, packed form F06RKF
tridiagonal matrix F06RNF
compute upper Hessenberg matrix by applying sequence of plane rotations to an upper triangular matrix F06QVF
compute upper spiked matrix by applying sequence of plane rotations to an upper triangular matrix F06QWF
matrix-vector product,
rectangular band matrix F06PBF (DGBMV)
rectangular matrix F06PAF (DGEMV)
symmetric band matrix F06PDF (DSBMV)
symmetric matrix F06PCF (DSYMV)
symmetric packed matrix F06PEF (DSPMV)
triangular band matrix F06PGF (DTBMV)
triangular matrix F06PFF (DTRMV)
triangular packed matrix F06PHF (DTPMV)
orthogonal similarity transformation of a symmetric matrix,
as sequence of plane rotations F06QMF
permute rows or columns of a matrix,
permutations represented by an integer array F06QJF
permutations represented by a real array F06QKF
QR factorization by sequence of plane rotations,
of rank-1 update of upper triangular matrix F06QPF
of upper triangular matrix augmented by a full row F06QQF
QR factorization of UZ or RQ factorization of ZU, where U is upper triangular and Z is a sequence of plane rotations F06QTF
QR or RQ factorization by sequence of plane rotations,
of upper Hessenberg matrix F06QRF
of upper spiked matrix F06QSF
rank-1 update,
rectangular matrix F06PMF (DGER)
symmetric matrix F06PPF (DSYR)
symmetric packed matrix F06PQF (DSPR)
rank-2 update,
matrix copy, rectangular or trapezoidal F06QFF
symmetric matrix F06PRF (DSYR2)
symmetric packed matrix F06PSF (DSPR2)
solution of a system of equations,
triangular band matrix F06PKF (DTBSV)
triangular matrix F06PJF (DTRSV)
triangular packed matrix F06PLF (DTPSV)
Level 3 (Matrix-matrix) operations,
complex matrices,
matrix-matrix product,
one matrix Hermitian F06ZCF (ZHEMM)
one matrix symmetric F06ZTF (ZSYMM)
one matrix triangular F06ZFF (ZTRMM)
two rectangular matrices F06ZAF (ZGEMM)
rank-2 k update,
of a Hermitian matrix F06ZRF (ZHER2K)
of a symmetric matrix F06ZWF (ZSYR2K)
rank-k update,
of a Hermitian matrix F06ZPF (ZHERK)
of a Hermitian matrix, RFP format F06WQF (ZHFRK)
of a symmetric matrix F06ZUF (ZSYRK)
solution of triangular systems of equations F06ZJF (ZTRSM)
solution of triangular systems of equations, RFP format F06WPF (ZTFSM)
real matrices,
matrix-matrix product,
one matrix symmetric F06YCF (DSYMM)
one matrix triangular F06YFF (DTRMM)
rectangular matrices F06YAF (DGEMM)
rank-2 k update of a symmetric matrix F06YRF (DSYR2K)
rank-k update,
of a symmetric matrix F06YPF (DSYRK)
of a symmetric matrix, RFP format F06WCF (DSFRK)
solution of triangular systems of equations F06YJF (DTRSM)
solution of triangular systems of equations, RFP format F06WBF (DTFSM)
Sparse level 1 (vector) operations,
complex vector(s),
add scalar times sparse vector to a full vector F06GTF (ZAXPYI)
dot product of a sparse and a full vector (conjugated) F06GSF (ZDOTCI)
dot product of a sparse and a full vector (unconjugated) F06GRF (ZDOTUI)
gather and set to zero a sparse vector F06GVF (ZGTHRZ)
gather sparse vector F06GUF (ZGTHR)
scatter sparse vector F06GWF (ZSCTR)
real vector(s),
add scalar times sparse vector to a full vector F06ETF (DAXPYI)
apply plane rotation to a sparse and a full vector F06EXF (DROTI)
dot product of a sparse and a full vector F06ERF (DDOTI)
gather and set to zero a sparse vector F06EVF (DGTHRZ)
gather sparse vector F06EUF (DGTHR)
scatter sparse vector F06EWF (DSCTR)
BLAS Routines
Real Matrices
single precision | double precision | NAG
ISAMAX | IDAMAX | F06JLF (IDAMAX)
SASUM | DASUM | F06EKF (DASUM)
SAXPY | DAXPY | F06ECF (DAXPY)
SAXPYI | DAXPYI | F06ETF (DAXPYI)
SCASUM | DZASUM | F06JKF (DZASUM)
SCNRM2 | DZNRM2 | F06JJF (DZNRM2)
SCOPY | DCOPY | F06EFF (DCOPY)
SDOT | DDOT | F06EAF (DDOT)
SDOTI | DDOTI | F06ERF (DDOTI)
SGBMV | DGBMV | F06PBF (DGBMV)
SGEMM | DGEMM | F06YAF (DGEMM)
SGEMV | DGEMV | F06PAF (DGEMV)
SGER | DGER | F06PMF (DGER)
SGTHR | DGTHR | F06EUF (DGTHR)
SGTHRZ | DGTHRZ | F06EVF (DGTHRZ)
SNRM2 | DNRM2 | F06EJF (DNRM2)
SROT | DROT | F06EPF (DROT)
SROTG | DROTG | F06AAF (DROTG)
SROTI | DROTI | F06EXF (DROTI)
SSBMV | DSBMV | F06PDF (DSBMV)
SSCAL | DSCAL | F06EDF (DSCAL)
SSCTR | DSCTR | F06EWF (DSCTR)
SSPMV | DSPMV | F06PEF (DSPMV)
SSPR | DSPR | F06PQF (DSPR)
SSPR2 | DSPR2 | F06PSF (DSPR2)
SSWAP | DSWAP | F06EGF (DSWAP)
SSYMM | DSYMM | F06YCF (DSYMM)
SSYMV | DSYMV | F06PCF (DSYMV)
SSYR | DSYR | F06PPF (DSYR)
SSYR2 | DSYR2 | F06PRF (DSYR2)
SSYR2K | DSYR2K | F06YRF (DSYR2K)
SSYRK | DSYRK | F06YPF (DSYRK)
STBMV | DTBMV | F06PGF (DTBMV)
STBSV | DTBSV | F06PKF (DTBSV)
STPMV | DTPMV | F06PHF (DTPMV)
STPSV | DTPSV | F06PLF (DTPSV)
STRMM | DTRMM | F06YFF (DTRMM)
STRMV | DTRMV | F06PFF (DTRMV)
STRSM | DTRSM | F06YJF (DTRSM)
STRSV | DTRSV | F06PJF (DTRSV)
SLANSF | DLANSF | F06WAF (DLANSF)
STFSM | DTFSM | F06WBF (DTFSM)
SSFRK | DSFRK | F06WCF (DSFRK)

Complex Matrices
single precision | double precision | NAG
ICAMAX | IZAMAX | F06JMF (IZAMAX)
CAXPY | ZAXPY | F06GCF (ZAXPY)
CAXPYI | ZAXPYI | F06GTF (ZAXPYI)
CCOPY | ZCOPY | F06GFF (ZCOPY)
CDOTC | ZDOTC | F06GBF (ZDOTC)
CDOTCI | ZDOTCI | F06GSF (ZDOTCI)
CDOTU | ZDOTU | F06GAF (ZDOTU)
CDOTUI | ZDOTUI | F06GRF (ZDOTUI)
CGBMV | ZGBMV | F06SBF (ZGBMV)
CGEMM | ZGEMM | F06ZAF (ZGEMM)
CGEMV | ZGEMV | F06SAF (ZGEMV)
CGERC | ZGERC | F06SNF (ZGERC)
CGERU | ZGERU | F06SMF (ZGERU)
CGTHR | ZGTHR | F06GUF (ZGTHR)
CGTHRZ | ZGTHRZ | F06GVF (ZGTHRZ)
CHBMV | ZHBMV | F06SDF (ZHBMV)
CHEMM | ZHEMM | F06ZCF (ZHEMM)
CHEMV | ZHEMV | F06SCF (ZHEMV)
CHER | ZHER | F06SPF (ZHER)
CHER2 | ZHER2 | F06SRF (ZHER2)
CHER2K | ZHER2K | F06ZRF (ZHER2K)
CHERK | ZHERK | F06ZPF (ZHERK)
CHPMV | ZHPMV | F06SEF (ZHPMV)
CHPR | ZHPR | F06SQF (ZHPR)
CHPR2 | ZHPR2 | F06SSF (ZHPR2)
CSCAL | ZSCAL | F06GDF (ZSCAL)
CSCTR | ZSCTR | F06GWF (ZSCTR)
CSSCAL | ZDSCAL | F06JDF (ZDSCAL)
CSWAP | ZSWAP | F06GGF (ZSWAP)
CSYMM | ZSYMM | F06ZTF (ZSYMM)
CSYR2K | ZSYR2K | F06ZWF (ZSYR2K)
CSYRK | ZSYRK | F06ZUF (ZSYRK)
CTBMV | ZTBMV | F06SGF (ZTBMV)
CTBSV | ZTBSV | F06SKF (ZTBSV)
CTPMV | ZTPMV | F06SHF (ZTPMV)
CTPSV | ZTPSV | F06SLF (ZTPSV)
CTRMM | ZTRMM | F06ZFF (ZTRMM)
CTRMV | ZTRMV | F06SFF (ZTRMV)
CTRSM | ZTRSM | F06ZJF (ZTRSM)
CTRSV | ZTRSV | F06SJF (ZTRSV)
CLANHF | ZLANHF | F06WNF (ZLANHF)
CHFRK | ZHFRK | F06WQF (ZHFRK)
CTFSM | ZTFSM | F06WPF (ZTFSM)

5 Auxiliary Routines Associated with Library Routine Arguments

None.

6 Routines Withdrawn or Scheduled for Withdrawal

None.

7 References

Dodson D S and Grimes R G (1982) Remark on Algorithm 539 ACM Trans. Math. Software 8 403–404
Dodson D S, Grimes R G and Lewis J G (1991) Sparse extensions to the Fortran basic linear algebra subprograms ACM Trans. Math. Software 17 253–263
Dongarra J J, Du Croz J J, Duff I S and Hammarling S (1990) A set of Level 3 basic linear algebra subprograms ACM Trans. Math. Software 16 1–28
Dongarra J J, Du Croz J J, Hammarling S and Hanson R J (1988) An extended set of FORTRAN basic linear algebra subprograms ACM Trans. Math. Software 14 1–32
Dongarra J J, Moler C B, Bunch J R and Stewart G W (1979) LINPACK Users' Guide SIAM, Philadelphia
Golub G H and Van Loan C F (1996) Matrix Computations (3rd Edition) Johns Hopkins University Press, Baltimore
Lawson C L, Hanson R J, Kincaid D R and Krogh F T (1979) Basic linear algebra supbrograms for Fortran usage ACM Trans. Math. Software 5 308–325
F06 Chapter Contents
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F06JDF (ZDSCAL) : NAG Library, Mark 26

F06 Chapter Contents
F06 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F06JDF (ZDSCAL)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
10 Example

1 Purpose

F06JDF (ZDSCAL) scales a complex vector by a real scalar.

2 Specification

SUBROUTINE F06JDF ( N, ALPHA, X, INCX)
INTEGER | N, INCX
REAL (KIND=nag_wp) | ALPHA
COMPLEX (KIND=nag_wp) | X(*)
The routine may be called by its BLAS name zdscal.

3 Description

F06JDF (ZDSCAL) performs the operation
x←αx
where x is an n-element complex vector scattered with stride INCX, and α is a real scalar.

4 References

Lawson C L, Hanson R J, Kincaid D R and Krogh F T (1979) Basic linear algebra supbrograms for Fortran usage ACM Trans. Math. Software 5 308–325

5 Arguments

1:   N – INTEGERInput
On entry: n, the number of elements in x.
2:   ALPHA – REAL (KIND=nag_wp)Input
On entry: the scalar α.
3:   X* – COMPLEX (KIND=nag_wp) arrayInput/Output
Note: the dimension of the array X must be at least max 1, 1+N-1 ×INCX .
On entry: the n-element vector x. xi must be stored in X 1+i-1×INCX, for i=1,2,…,N.
Intermediate elements of X are not referenced.
On exit: the vector αx stored in the array elements used to supply the original vector x.
Intermediate elements of X are unchanged.
4:   INCX – INTEGERInput
On entry: the increment in the subscripts of X between successive elements of x.
Constraint: INCX>0.

6 Error Indicators and Warnings

None.

7 Accuracy

Not applicable.

8 Parallelism and Performance

F06JDF (ZDSCAL) is not threaded in any implementation.

9 Further Comments

None.

10 Example

None.
F06 Chapter Contents
F06 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F06JJF (DZNRM2) : NAG Library, Mark 26

F06 Chapter Contents
F06 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F06JJF (DZNRM2)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
10 Example

1 Purpose

F06JJF (DZNRM2) computes the Euclidean norm of a complex vector.

2 Specification

FUNCTION F06JJF ( N, X, INCX)
REAL (KIND=nag_wp) F06JJF
INTEGER | N, INCX
COMPLEX (KIND=nag_wp) | X(*)
The routine may be called by its BLAS name dznrm2.

3 Description

F06JJF (DZNRM2) returns the Euclidean norm
x 2=xH x
of the n-element complex vector x scattered with stride INCX, via the function name.

4 References

Lawson C L, Hanson R J, Kincaid D R and Krogh F T (1979) Basic linear algebra supbrograms for Fortran usage ACM Trans. Math. Software 5 308–325

5 Arguments

1:   N – INTEGERInput
On entry: n, the number of elements in x.
2:   X* – COMPLEX (KIND=nag_wp) arrayInput
Note: the dimension of the array X must be at least max 1, 1+N-1 ×INCX .
On entry: the n-element vector x. xi must be stored in X 1+i-1×INCX, for i=1,2,…,N.
Intermediate elements of X are not referenced.
3:   INCX – INTEGERInput
On entry: the increment in the subscripts of X between successive elements of x.
Constraint: INCX>0.

6 Error Indicators and Warnings

None.

7 Accuracy

Not applicable.

8 Parallelism and Performance

F06JJF (DZNRM2) is not threaded in any implementation.

9 Further Comments

None.

10 Example

None.
F06 Chapter Contents
F06 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F06JKF (DZASUM) : NAG Library, Mark 26

F06 Chapter Contents
F06 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F06JKF (DZASUM)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
10 Example

1 Purpose

F06JKF (DZASUM) returns the sum of the absolute values of the real and imaginary parts of the elements in a complex vector.

2 Specification

FUNCTION F06JKF ( N, X, INCX)
REAL (KIND=nag_wp) F06JKF
INTEGER | N, INCX
COMPLEX (KIND=nag_wp) | X(*)
The routine may be called by its BLAS name dzasum.

3 Description

F06JKF (DZASUM) returns the norm
Re x 1+Im x 1+⋯+Re xn+Im xn
of the n-element complex vector x scattered with stride INCX, via the function name.

4 References

Lawson C L, Hanson R J, Kincaid D R and Krogh F T (1979) Basic linear algebra supbrograms for Fortran usage ACM Trans. Math. Software 5 308–325

5 Arguments

1:   N – INTEGERInput
On entry: n, the number of elements in x.
2:   X* – COMPLEX (KIND=nag_wp) arrayInput
Note: the dimension of the array X must be at least max 1, 1+N-1 ×INCX .
On entry: the n-element vector x. xi must be stored in X 1+i-1×INCX, for i=1,2,…,N.
Intermediate elements of X are not referenced.
3:   INCX – INTEGERInput
On entry: the increment in the subscripts of X between successive elements of x.
Constraint: INCX>0.

6 Error Indicators and Warnings

None.

7 Accuracy

Not applicable.

8 Parallelism and Performance

F06JKF (DZASUM) is not threaded in any implementation.

9 Further Comments

None.

10 Example

None.
F06 Chapter Contents
F06 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F06JLF (IDAMAX) : NAG Library, Mark 26

F06 Chapter Contents
F06 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F06JLF (IDAMAX)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
10 Example

1 Purpose

F06JLF (IDAMAX) computes the index of the absolutely largest component of a real vector.

2 Specification

FUNCTION F06JLF ( N, X, INCX)
INTEGER F06JLF
INTEGER | N, INCX
REAL (KIND=nag_wp) | X(*)
The routine may be called by its BLAS name idamax.

3 Description

F06JLF (IDAMAX) returns, via the function name, the smallest index i such that
xi=maxj xj
where x is an n-element real vector scattered with stride INCX.

4 References

Lawson C L, Hanson R J, Kincaid D R and Krogh F T (1979) Basic linear algebra supbrograms for Fortran usage ACM Trans. Math. Software 5 308–325

5 Arguments

1:   N – INTEGERInput
On entry: n, the number of elements in x.
2:   X* – REAL (KIND=nag_wp) arrayInput
Note: the dimension of the array X must be at least max 1, 1+N-1 ×INCX .
On entry: the n-element vector x. xi must be stored in X 1+i-1×INCX, for i=1,2,…,N.
Intermediate elements of X are not referenced.
3:   INCX – INTEGERInput
On entry: the increment in the subscripts of X between successive elements of x.
Constraint: INCX>0.

6 Error Indicators and Warnings

None.

7 Accuracy

Not applicable.

8 Parallelism and Performance

F06JLF (IDAMAX) is not threaded in any implementation.

9 Further Comments

None.

10 Example

None.
F06 Chapter Contents
F06 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F06JMF (IZAMAX) : NAG Library, Mark 26

F06 Chapter Contents
F06 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F06JMF (IZAMAX)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
10 Example

1 Purpose

F06JMF (IZAMAX) computes the index of the absolutely largest component of a complex vector.

2 Specification

FUNCTION F06JMF ( N, X, INCX)
INTEGER F06JMF
INTEGER | N, INCX
COMPLEX (KIND=nag_wp) | X(*)
The routine may be called by its BLAS name izamax.

3 Description

F06JMF (IZAMAX) returns, via the function name, the smallest index i such that
Re xi+Im xi=maxj Re xj+Im xj
where x is an n-element complex vector scattered with stride INCX.

4 References

Lawson C L, Hanson R J, Kincaid D R and Krogh F T (1979) Basic linear algebra supbrograms for Fortran usage ACM Trans. Math. Software 5 308–325

5 Arguments

1:   N – INTEGERInput
On entry: n, the number of elements in x.
2:   X* – COMPLEX (KIND=nag_wp) arrayInput
Note: the dimension of the array X must be at least max 1, 1+N-1 ×INCX .
On entry: the n-element vector x. xi must be stored in X 1+i-1×INCX, for i=1,2,…,N.
Intermediate elements of X are not referenced.
3:   INCX – INTEGERInput
On entry: the increment in the subscripts of X between successive elements of x.
Constraint: INCX>0.

6 Error Indicators and Warnings

None.

7 Accuracy

Not applicable.

8 Parallelism and Performance

F06JMF (IZAMAX) is not threaded in any implementation.

9 Further Comments

None.

10 Example

None.
F06 Chapter Contents
F06 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F06KCF : NAG Library, Mark 26

F06 Chapter Contents
F06 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F06KCF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
10 Example

1 Purpose

F06KCF multiplies a complex vector by a real diagonal matrix.

2 Specification

SUBROUTINE F06KCF ( N, D, INCD, X, INCX)
INTEGER | N, INCD, INCX
REAL (KIND=nag_wp) | D(*)
COMPLEX (KIND=nag_wp) | X(*)

3 Description

F06KCF performs the operation
x←Dx
where x is an n-element complex vector and D=diag d is a real diagonal matrix.
Equivalently, the routine performs the element-by-element product of the vectors x and d
xi=dixi,  i=1,2,…,n.

4 References

None.

5 Arguments

1:   N – INTEGERInput
On entry: n, the number of elements in d and x.
2:   D* – REAL (KIND=nag_wp) arrayInput
Note: the dimension of the array D must be at least max 1, 1+N-1 ×INCD .
On entry: the vector d.
If INCD>0, di must be stored in D i-1×INCD+1 , for i=1,2,…,N.
If INCD<0, di must be stored in D 1-N-i×INCD , for i=1,2,…,N.
3:   INCD – INTEGERInput
On entry: the increment in the subscripts of D between successive elements of d.
4:   X* – COMPLEX (KIND=nag_wp) arrayInput/Output
Note: the dimension of the array X must be at least max 1, 1+N-1 ×INCX .
On entry: the array X must contain the n-element vector x.
If INCX>0, xi must be stored in X 1+i-1×INCX , for i=1,2,…,N.
If INCX<0, xi must be stored in X 1-N-i×INCX , for i=1,2,…,N.
On exit: the updated vector x stored in the array elements used to supply the original vector x.
Intermediate elements of X are unchanged.
5:   INCX – INTEGERInput
On entry: the increment in the subscripts of X between successive elements of x.

6 Error Indicators and Warnings

None.

7 Accuracy

Not applicable.

8 Parallelism and Performance

F06KCF makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

None.

10 Example

None.
F06 Chapter Contents
F06 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F06KDF : NAG Library, Mark 26

F06 Chapter Contents
F06 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F06KDF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
10 Example

1 Purpose

F06KDF multiplies a complex vector by a real scalar, preserving the input vector.

2 Specification

SUBROUTINE F06KDF ( N, ALPHA, X, INCX, Y, INCY)
INTEGER | N, INCX, INCY
REAL (KIND=nag_wp) | ALPHA
COMPLEX (KIND=nag_wp) | X(*), Y(*)

3 Description

F06KDF performs the operation
y←αx
where x and y are n-element complex vectors, and α is a real scalar scattered with stride INCX and INCY respectively.

4 References

None.

5 Arguments

1:   N – INTEGERInput
On entry: n, the number of elements in x and y.
2:   ALPHA – REAL (KIND=nag_wp)Input
On entry: the scalar α.
3:   X* – COMPLEX (KIND=nag_wp) arrayInput
Note: the dimension of the array X must be at least max 1, 1+N-1 ×INCX .
On entry: the n-element vector x.
If INCX>0, xi must be stored in X 1+i-1×INCX, for i=1,2,…,N.
If INCX<0, xi must be stored in X 1-N-i×INCX, for i=1,2,…,N.
Intermediate elements of X are not referenced.
4:   INCX – INTEGERInput
On entry: the increment in the subscripts of X between successive elements of x.
5:   Y* – COMPLEX (KIND=nag_wp) arrayOutput
Note: the dimension of the array Y must be at least max 1, 1+N-1 ×INCY .
On exit: the vector y.
If INCY>0, yi will be stored in Y 1+i-1×INCY, for i=1,2,…,N.
If INCY<0, yi will be stored in Y 1-N-i×INCY, for i=1,2,…,N.
Intermediate elements of Y are unchanged.
6:   INCY – INTEGERInput
On entry: the increment in the subscripts of Y between successive elements of y.

6 Error Indicators and Warnings

None.

7 Accuracy

Not applicable.

8 Parallelism and Performance

F06KDF is not threaded in any implementation.

9 Further Comments

None.

10 Example

None.
F06 Chapter Contents
F06 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F06KEF : NAG Library, Mark 26

F06 Chapter Contents
F06 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F06KEF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
10 Example

1 Purpose

F06KEF multiplies a complex vector by the reciprocal of a real scalar.

2 Specification

SUBROUTINE F06KEF ( N, ALPHA, X, INCX)
INTEGER | N, INCX
REAL (KIND=nag_wp) | ALPHA
COMPLEX (KIND=nag_wp) | X(*)

3 Description

F06KEF performs the operation
x←1 α x
where x is an n-element complex vector and α is a real nonzero scalar scattered with stride INCX.

4 References

None.

5 Arguments

1:   N – INTEGERInput
On entry: n, the number of elements in x.
2:   ALPHA – REAL (KIND=nag_wp)Input
On entry: the scalar α.
Constraint: ALPHA≠0.0.
3:   X* – COMPLEX (KIND=nag_wp) arrayInput/Output
Note: the dimension of the array X must be at least max 1, 1+N-1 ×INCX .
On entry: the n-element vector x. xi must be stored in X 1+i-1×INCX, for i=1,2,…,N.
Intermediate elements of X are not referenced.
On exit: the updated vector x, stored in the same array elements used to supply the original vector.
4:   INCX – INTEGERInput
On entry: the increment in the subscripts of X between successive elements of x.
Constraint: INCX>0.

6 Error Indicators and Warnings

None.

7 Accuracy

Not applicable.

8 Parallelism and Performance

F06KEF makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

None.

10 Example

None.
F06 Chapter Contents
F06 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F06KFF : NAG Library, Mark 26

F06 Chapter Contents
F06 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F06KFF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
10 Example

1 Purpose

F06KFF copies a real vector to a complex vector.

2 Specification

SUBROUTINE F06KFF ( N, X, INCX, Y, INCY)
INTEGER | N, INCX, INCY
REAL (KIND=nag_wp) | X(*)
COMPLEX (KIND=nag_wp) | Y(*)

3 Description

F06KFF performs the operation
y←x
where x is an n-element real vector, and y is an n-element complex vector scattered with stride INCX and INCY respectively.

4 References

None.

5 Arguments

1:   N – INTEGERInput
On entry: n, the number of elements in x and y.
2:   X* – REAL (KIND=nag_wp) arrayInput
Note: the dimension of the array X must be at least max 1, 1+N-1 ×INCX .
On entry: the n-element vector x.
If INCX>0, xi must be stored in X 1+i-1×INCX, for i=1,2,…,N.
If INCX<0, xi must be stored in X 1-N-i×INCX, for i=1,2,…,N.
Intermediate elements of X are not referenced.
3:   INCX – INTEGERInput
On entry: the increment in the subscripts of X between successive elements of x.
4:   Y* – COMPLEX (KIND=nag_wp) arrayOutput
Note: the dimension of the array Y must be at least max 1, 1+N-1 ×INCY .
On exit: the vector y.
If INCY>0, yi will be stored in Y 1+i-1×INCY, for i=1,2,…,N.
If INCY<0, yi will be stored in Y 1-N-i×INCY, for i=1,2,…,N.
Intermediate elements of Y are unchanged.
5:   INCY – INTEGERInput
On entry: the increment in the subscripts of Y between successive elements of y.

6 Error Indicators and Warnings

None.

7 Accuracy

Not applicable.

8 Parallelism and Performance

F06KFF is not threaded in any implementation.

9 Further Comments

None.

10 Example

None.
F06 Chapter Contents
F06 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F06KJF : NAG Library, Mark 26

F06 Chapter Contents
F06 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F06KJF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
10 Example

1 Purpose

F06KJF updates the Euclidean norm of complex vector in scaled form.

2 Specification

SUBROUTINE F06KJF ( N, X, INCX, SCAL, SUMSQ)
INTEGER | N, INCX
REAL (KIND=nag_wp) | SCAL, SUMSQ
COMPLEX (KIND=nag_wp) | X(*)

3 Description

Given an n-element complex vector x, and real scalars α and ξ, F06KJF returns updated values α~ and ξ~ such that
α~2 ξ~=x 1 2+x 2 2+⋯+xn 2+α 2 ξ.
F06KJF is designed for use in the safe computation of the Euclidean norm of a complex vector, without unnecessary overflow or destructive underflow. An initial call to F06KJF (with ξ=1 and α=0) may be followed by further calls to F06KJF and finally a call to F06BMF to complete the computation. Multiple calls of F06KJF may be needed if the elements of the vector cannot all be accessed in a single array X.

4 References

None.

5 Arguments

1:   N – INTEGERInput
On entry: n, the number of elements in x.
2:   X* – COMPLEX (KIND=nag_wp) arrayInput
Note: the dimension of the array X must be at least max 1, 1+N-1 ×INCX .
On entry: the n-element vector x. xi must be stored in X 1+i-1×INCX, for i=1,2,…,N.
Intermediate elements of X are not referenced.
3:   INCX – INTEGERInput
On entry: the increment in the subscripts of X between successive elements of x.
Constraint: INCX>0.
4:   SCAL – REAL (KIND=nag_wp)Input/Output
On entry: the scaling factor α. On the first call to F06KJF SCAL=0.0.
Constraint: SCAL≥0.
On exit: the updated scaling factor α~=maxi α,Re xi,Im xi .
5:   SUMSQ – REAL (KIND=nag_wp)Input/Output
On entry: the scaled sum of squares ξ. On the first call to F06KJF SUMSQ=1.0.
Constraint: SUMSQ≥1.
On exit: the updated scaled sum of squares ξ~, satisfying: 1≤ξ~≤ξ+2 n.

6 Error Indicators and Warnings

None.

7 Accuracy

Not applicable.

8 Parallelism and Performance

F06KJF is not threaded in any implementation.

9 Further Comments

None.

10 Example

None.
F06 Chapter Contents
F06 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F06KLF : NAG Library, Mark 26

F06 Chapter Contents
F06 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F06KLF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
10 Example

1 Purpose

F06KLF determines the index of the first negligible element of a real vector.

2 Specification

FUNCTION F06KLF ( N, X, INCX, TOL)
INTEGER F06KLF
INTEGER | N, INCX
REAL (KIND=nag_wp) | X(*), TOL

3 Description

F06KLF finds the first element of the n-element real vector x for which
x k+1≤tol max x 1,…,xk
and returns the index k via the function name. If no such k exists, then the value n is returned. If a negative value of tol is supplied, the value of machine precision is used in place of tol.

4 References

None.

5 Arguments

1:   N – INTEGERInput
On entry: n, the number of elements in x.
2:   X* – REAL (KIND=nag_wp) arrayInput
Note: the dimension of the array X must be at least max 1, 1+N-1 ×INCX .
On entry: the n-element vector x. xi must be stored in X 1+i-1×INCX, for i=1,2,…,N.
Intermediate elements of X are not referenced.
3:   INCX – INTEGERInput
On entry: the increment in the subscripts of X between successive elements of x.
Constraint: INCX>0.
4:   TOL – REAL (KIND=nag_wp)Input
On entry: the value tol.

6 Error Indicators and Warnings

None.

7 Accuracy

Not applicable.

8 Parallelism and Performance

F06KLF is not threaded in any implementation.

9 Further Comments

None.

10 Example

None.
F06 Chapter Contents
F06 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F06KPF (ZDROT) : NAG Library, Mark 26

F06 Chapter Contents
F06 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F06KPF (ZDROT)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
10 Example

1 Purpose

F06KPF (ZDROT) applies a real plane rotation to two complex vectors.

2 Specification

SUBROUTINE F06KPF ( N, X, INCX, Y, INCY, C, S)
INTEGER | N, INCX, INCY
REAL (KIND=nag_wp) | C, S
COMPLEX (KIND=nag_wp) | X(*), Y(*)
The routine may be called by its BLAS name zdrot.

3 Description

F06KPF (ZDROT) applies a real plane rotation to two n-element complex vectors x and y scattered with stride INCX and INCY respectively:
xT yT ← c s -s c xT yT .
The plane rotation has the form generated by F06AAF (DROTG) or F06BAF.

4 References

None.

5 Arguments

1:   N – INTEGERInput
On entry: n, the number of elements in x and y.
2:   X* – COMPLEX (KIND=nag_wp) arrayInput/Output
Note: the dimension of the array X must be at least max 1, 1+N-1 ×INCX .
On entry: the n-element vector x.
If INCX>0, xi must be stored in X 1+i-1×INCX, for i=1,2,…,N.
If INCX<0, xi must be stored in X 1-N-i×INCX, for i=1,2,…,N.
Intermediate elements of X are not referenced.
On exit: the transformed vector x stored in the array elements used to supply the original vector x.
Intermediate elements of X are unchanged.
3:   INCX – INTEGERInput
On entry: the increment in the subscripts of X between successive elements of x.
4:   Y* – COMPLEX (KIND=nag_wp) arrayInput/Output
Note: the dimension of the array Y must be at least max 1, 1+N-1 ×INCY .
On entry: the n-element vector y.
If INCY>0, yi must be stored in Y 1+i-1×INCY, for i=1,2,…,N.
If INCY<0, yi must be stored in Y 1-N-i×INCY, for i=1,2,…,N.
Intermediate elements of Y are not referenced.
On exit: the transformed vector y.
Intermediate elements of Y are unchanged.
5:   INCY – INTEGERInput
On entry: the increment in the subscripts of Y between successive elements of y.
6:   C – REAL (KIND=nag_wp)Input
On entry: the value c, the cosine of the rotation.
7:   S – REAL (KIND=nag_wp)Input
On entry: the value s, the sine of the rotation.

6 Error Indicators and Warnings

None.

7 Accuracy

Not applicable.

8 Parallelism and Performance

F06KPF (ZDROT) is not threaded in any implementation.

9 Further Comments

None.

10 Example

None.
F06 Chapter Contents
F06 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F06PAF (DGEMV) : NAG Library, Mark 26

F06 Chapter Contents
F06 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F06PAF (DGEMV)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
10 Example

1 Purpose

F06PAF (DGEMV) computes the matrix-vector product for a real general matrix or its transpose.

2 Specification

SUBROUTINE F06PAF ( TRANS, M, N, ALPHA, A, LDA, X, INCX, BETA, Y, INCY)
INTEGER | M, N, LDA, INCX, INCY
REAL (KIND=nag_wp) | ALPHA, A(LDA,*), X(*), BETA, Y(*)
CHARACTER(1) | TRANS
The routine may be called by its BLAS name dgemv.

3 Description

F06PAF (DGEMV) performs one of the matrix-vector operations
y←αAx + βy ,   or   y←α AT x + βy ,
where A is an m by n real matrix, x and y are real vectors, and α and β are real scalars.
If m=0 or n=0, no operation is performed.

4 References

None.

5 Arguments

1:   TRANS – CHARACTER(1)Input
On entry: specifies the operation to be performed.
TRANS='N'
y←αAx+βy.
TRANS='T' or 'C'
y←α AT x+βy.
Constraint: TRANS='N', 'T' or 'C'.
2:   M – INTEGERInput
On entry: m, the number of rows of the matrix A.
Constraint: M≥0.
3:   N – INTEGERInput
On entry: n, the number of columns of the matrix A.
Constraint: N≥0.
4:   ALPHA – REAL (KIND=nag_wp)Input
On entry: the scalar α.
5:   A LDA* – REAL (KIND=nag_wp) arrayInput
Note: the second dimension of the array A must be at least N.
On entry: the m by n matrix A.
6:   LDA – INTEGERInput
On entry: the first dimension of the array A as declared in the (sub)program from which F06PAF (DGEMV) is called.
Constraint: LDA≥ max 1,M .
7:   X* – REAL (KIND=nag_wp) arrayInput
Note: the dimension of the array X must be at least max 1, 1+ N-1 ×INCX if TRANS='N' and at least max 1, 1+ M-1 ×INCX if TRANS='T' or 'C'.
On entry: the vector x.
If TRANS='N',
  • if INCX>0, xi must be stored in X 1+i-1×INCX , for i=1,2,…,N;
  • if INCX<0, xi must be stored in X 1-N-i×INCX , for i=1,2,…,N.
If TRANS='T' or 'C',
  • if INCX>0, xi must be stored in X 1+i-1×INCX , for i=1,2,…,M;
  • if INCX<0, xi must be stored in X 1-M-i×INCX , for i=1,2,…,M.
8:   INCX – INTEGERInput
On entry: the increment in the subscripts of X between successive elements of x.
Constraint: INCX≠0.
9:   BETA – REAL (KIND=nag_wp)Input
On entry: the scalar β.
10:   Y* – REAL (KIND=nag_wp) arrayInput/Output
Note: the dimension of the array Y must be at least max 1,1+M-1 ×INCY if TRANS='N' and at least max 1,1+N-1 ×INCY if TRANS='T' or 'C'.
On entry: the vector y, if BETA=0.0, Y need not be set.
If TRANS='N',
  • if INCY>0, yi must be stored in Y 1+i-1×INCY , for i=1,2,…,M;
  • if INCY<0, yi must be stored in Y 1-M-i×INCY , for i=1,2,…,M.
If TRANS='T' or 'C',
  • if INCY>0, yi must be stored in Y 1+i-1×INCY , for i=1,2,…,N;
  • if INCY<0, yi must be stored in Y 1-N-i×INCY , for i=1,2,…,N.
On exit: the updated vector y stored in the array elements used to supply the original vector y.
11:   INCY – INTEGERInput
On entry: the increment in the subscripts of Y between successive elements of y.
Constraint: INCY≠0.

6 Error Indicators and Warnings

None.

7 Accuracy

Not applicable.

8 Parallelism and Performance

F06PAF (DGEMV) is not threaded in any implementation.

9 Further Comments

None.

10 Example

None.
F06 Chapter Contents
F06 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F06PBF (DGBMV) : NAG Library, Mark 26

F06 Chapter Contents
F06 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F06PBF (DGBMV)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
10 Example

1 Purpose

F06PBF (DGBMV) computes the matrix-vector product for a real general band matrix or its transpose.

2 Specification

SUBROUTINE F06PBF ( TRANS, M, N, KL, KU, ALPHA, A, LDA, X, INCX, BETA, Y, INCY)
INTEGER | M, N, KL, KU, LDA, INCX, INCY
REAL (KIND=nag_wp) | ALPHA, A(LDA,*), X(*), BETA, Y(*)
CHARACTER(1) | TRANS
The routine may be called by its BLAS name dgbmv.

3 Description

F06PBF (DGBMV) performs one of the matrix-vector operations
y←αAx+βy   or   y←α AT x+βy ,
where A is an m by n real band matrix with kl subdiagonals and ku superdiagonals, x and y are real vectors, and α and β are real scalars.
If m=0 or n=0, no operation is performed.

4 References

None.

5 Arguments

1:   TRANS – CHARACTER(1)Input
On entry: specifies the operation to be performed.
TRANS='N'
y←αAx+βy.
TRANS='T' or 'C'
y←α AT x+βy.
Constraint: TRANS='N', 'T' or 'C'.
2:   M – INTEGERInput
On entry: m, the number of rows of the matrix A.
Constraint: M≥0.
3:   N – INTEGERInput
On entry: n, the number of columns of the matrix A.
Constraint: N≥0.
4:   KL – INTEGERInput
On entry: kl, the number of subdiagonals within the band of A.
Constraint: KL≥0.
5:   KU – INTEGERInput
On entry: ku, the number of superdiagonals within the band of A.
Constraint: KU≥0.
6:   ALPHA – REAL (KIND=nag_wp)Input
On entry: the scalar α.
7:   A LDA* – REAL (KIND=nag_wp) arrayInput
Note: the second dimension of the array A must be at least N.
On entry: the m by n band matrix A.
The matrix is stored in rows 1 to kl+ku+1, more precisely, the element A ij must be stored in
A ku+1+i-j j  for ​max 1,j-ku≤i≤min m,j+kl.
8:   LDA – INTEGERInput
On entry: the first dimension of the array A as declared in the (sub)program from which F06PBF (DGBMV) is called.
Constraint: LDA≥KL+KU+1.
9:   X* – REAL (KIND=nag_wp) arrayInput
Note: the dimension of the array X must be at least max 1, 1+ N-1 ×INCX if TRANS='N' and at least max 1, 1+ M-1 ×INCX if TRANS='T' or 'C'.
On entry: the vector x.
If TRANS='N',
  • if INCX>0, xi must be stored in X 1+i-1×INCX , for i=1,2,…,N;
  • if INCX<0, xi must be stored in X 1-N-i×INCX , for i=1,2,…,N.
If TRANS='T' or 'C',
  • if INCX>0, xi must be stored in X 1+i-1×INCX , for i=1,2,…,M;
  • if INCX<0, xi must be stored in X 1-M-i×INCX , for i=1,2,…,M.
10:   INCX – INTEGERInput
On entry: the increment in the subscripts of X between successive elements of x.
Constraint: INCX≠0.
11:   BETA – REAL (KIND=nag_wp)Input
On entry: the scalar β.
12:   Y* – REAL (KIND=nag_wp) arrayInput/Output
Note: the dimension of the array Y must be at least max 1,1+M-1 ×INCY if TRANS='N' and at least max 1,1+N-1 ×INCY if TRANS='T' or 'C'.
On entry: the vector y, if BETA=0.0, Y need not be set.
If TRANS='N',
  • if INCY>0, yi must be stored in Y 1+i-1×INCY , for i=1,2,…,M;
  • if INCY<0, yi must be stored in Y 1-M-i×INCY , for i=1,2,…,M.
If TRANS='T' or 'C',
  • if INCY>0, yi must be stored in Y 1+i-1×INCY , for i=1,2,…,N;
  • if INCY<0, yi must be stored in Y 1-N-i×INCY , for i=1,2,…,N.
On exit: the updated vector y stored in the array elements used to supply the original vector y.
13:   INCY – INTEGERInput
On entry: the increment in the subscripts of Y between successive elements of y.
Constraint: INCY≠0.

6 Error Indicators and Warnings

None.

7 Accuracy

Not applicable.

8 Parallelism and Performance

F06PBF (DGBMV) is not threaded in any implementation.

9 Further Comments

None.

10 Example

None.
F06 Chapter Contents
F06 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F06PCF (DSYMV) : NAG Library, Mark 26

F06 Chapter Contents
F06 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F06PCF (DSYMV)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
10 Example

1 Purpose

F06PCF (DSYMV) the matrix-vector product for a real symmetric matrix.

2 Specification

SUBROUTINE F06PCF ( UPLO, N, ALPHA, A, LDA, X, INCX, BETA, Y, INCY)
INTEGER | N, LDA, INCX, INCY
REAL (KIND=nag_wp) | ALPHA, A(LDA,*), X(*), BETA, Y(*)
CHARACTER(1) | UPLO
The routine may be called by its BLAS name dsymv.

3 Description

F06PCF (DSYMV) performs the matrix-vector operation
y←αAx+βy ,
where A is an n by n real symmetric matrix, x and y are n-element real vectors, and α and β are real scalars.

4 References

None.

5 Arguments

1:   UPLO – CHARACTER(1)Input
On entry: specifies whether the upper or lower triangular part of A is stored.
UPLO='U'
The upper triangular part of A is stored.
UPLO='L'
The lower triangular part of A is stored.
Constraint: UPLO='U' or 'L'.
2:   N – INTEGERInput
On entry: n, the order of the matrix A.
Constraint: N≥0.
3:   ALPHA – REAL (KIND=nag_wp)Input
On entry: the scalar α.
4:   A LDA* – REAL (KIND=nag_wp) arrayInput
Note: the second dimension of the array A must be at least max 1,N.
On entry: the n by n symmetric matrix A.
  • If UPLO='U', the upper triangular part of A must be stored and the elements of the array below the diagonal are not referenced.
  • If UPLO='L', the lower triangular part of A must be stored and the elements of the array above the diagonal are not referenced.
5:   LDA – INTEGERInput
On entry: the first dimension of the array A as declared in the (sub)program from which F06PCF (DSYMV) is called.
Constraint: LDA≥ max 1,N .
6:   X* – REAL (KIND=nag_wp) arrayInput
Note: the dimension of the array X must be at least max 1, 1+N-1 ×INCX .
On entry: the n-element vector x.
If INCX>0, xi must be stored in X 1+i-1×INCX, for i=1,2,…,N.
If INCX<0, xi must be stored in X 1-N-i×INCX, for i=1,2,…,N.
Intermediate elements of X are not referenced.
7:   INCX – INTEGERInput
On entry: the increment in the subscripts of X between successive elements of x.
Constraint: INCX≠0.
8:   BETA – REAL (KIND=nag_wp)Input
On entry: the scalar β.
9:   Y* – REAL (KIND=nag_wp) arrayInput/Output
Note: the dimension of the array Y must be at least max 1, 1+N-1 ×INCY .
On entry: the n-element vector y, if BETA=0.0 Y need not be set.
If INCY>0, yi must be stored in Y 1+i–1×INCY , for i=1,2,…,N.
If INCY<0, yi must be stored in Y 1–N–i×INCY , for i=1,2,…,N.
On exit: the updated vector y stored in the array elements used to supply the original vector y.
10:   INCY – INTEGERInput
On entry: the increment in the subscripts of Y between successive elements of y.
Constraint: INCY≠0.

6 Error Indicators and Warnings

None.

7 Accuracy

Not applicable.

8 Parallelism and Performance

F06PCF (DSYMV) is not threaded in any implementation.

9 Further Comments

None.

10 Example

None.
F06 Chapter Contents
F06 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F06PDF (DSBMV) : NAG Library, Mark 26

F06 Chapter Contents
F06 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F06PDF (DSBMV)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
10 Example

1 Purpose

F06PDF (DSBMV) computes the matrix-vector product for a real symmetric band matrix.

2 Specification

SUBROUTINE F06PDF ( UPLO, N, K, ALPHA, A, LDA, X, INCX, BETA, Y, INCY)
INTEGER | N, K, LDA, INCX, INCY
REAL (KIND=nag_wp) | ALPHA, A(LDA,*), X(*), BETA, Y(*)
CHARACTER(1) | UPLO
The routine may be called by its BLAS name dsbmv.

3 Description

F06PDF (DSBMV) performs the matrix-vector operation
y←αAx+βy ,
where A is an n by n real symmetric band matrix with k subdiagonals and k superdiagonals, x and y are n-element real vectors, and α and β are real scalars.

4 References

None.

5 Arguments

1:   UPLO – CHARACTER(1)Input
On entry: specifies whether the upper or lower triangular part of A is stored.
UPLO='U'
The upper triangular part of A is stored.
UPLO='L'
The lower triangular part of A is stored.
Constraint: UPLO='U' or 'L'.
2:   N – INTEGERInput
On entry: n, the order of the matrix A.
Constraint: N≥0.
3:   K – INTEGERInput
On entry: k, the number of subdiagonals or superdiagonals of the matrix A.
Constraint: K≥0.
4:   ALPHA – REAL (KIND=nag_wp)Input
On entry: the scalar α.
5:   A LDA* – REAL (KIND=nag_wp) arrayInput
Note: the second dimension of the array A must be at least N.
On entry: the n by n symmetric band matrix A.
The matrix is stored in rows 1 to k+1, more precisely,
  • if UPLO='U', the elements of the upper triangle of A within the band must be stored with element A ij in A k+1+i-j j​ for ​max 1,j-k≤i≤j;
  • if UPLO='L', the elements of the lower triangle of A within the band must be stored with element A ij in A 1+i-j j​ for ​j≤i≤min n,j+k.
6:   LDA – INTEGERInput
On entry: the first dimension of the array A as declared in the (sub)program from which F06PDF (DSBMV) is called.
Constraint: LDA≥K+1.
7:   X* – REAL (KIND=nag_wp) arrayInput
Note: the dimension of the array X must be at least max 1, 1+N-1 ×INCX .
On entry: the n-element vector x.
If INCX>0, xi must be stored in X 1+i-1×INCX, for i=1,2,…,N.
If INCX<0, xi must be stored in X 1-N-i×INCX, for i=1,2,…,N.
Intermediate elements of X are not referenced.
8:   INCX – INTEGERInput
On entry: the increment in the subscripts of X between successive elements of x.
Constraint: INCX≠0.
9:   BETA – REAL (KIND=nag_wp)Input
On entry: the scalar β.
10:   Y* – REAL (KIND=nag_wp) arrayInput/Output
Note: the dimension of the array Y must be at least max 1, 1+N-1 ×INCY .
On entry: the n-element vector y, if BETA=0.0 Y need not be set.
If INCY>0, yi must be stored in Y 1+i–1×INCY , for i=1,2,…,N.
If INCY<0, yi must be stored in Y 1–N–i×INCY , for i=1,2,…,N.
On exit: the updated vector y stored in the array elements used to supply the original vector y.
11:   INCY – INTEGERInput
On entry: the increment in the subscripts of Y between successive elements of y.
Constraint: INCY≠0.

6 Error Indicators and Warnings

None.

7 Accuracy

Not applicable.

8 Parallelism and Performance

F06PDF (DSBMV) is not threaded in any implementation.

9 Further Comments

None.

10 Example

None.
F06 Chapter Contents
F06 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F06PEF (DSPMV) : NAG Library, Mark 26

F06 Chapter Contents
F06 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F06PEF (DSPMV)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
10 Example

1 Purpose

F06PEF (DSPMV) computes the matrix-vector product for a real symmetric matrix stored in packed form.

2 Specification

SUBROUTINE F06PEF ( UPLO, N, ALPHA, AP, X, INCX, BETA, Y, INCY)
INTEGER | N, INCX, INCY
REAL (KIND=nag_wp) | ALPHA, AP(*), X(*), BETA, Y(*)
CHARACTER(1) | UPLO
The routine may be called by its BLAS name dspmv.

3 Description

F06PEF (DSPMV) performs the matrix-vector operation
y←αAx + βy ,
where A is an n by n real symmetric matrix stored in packed form, x and y are n-element real vectors, and α and β are real scalars.

4 References

None.

5 Arguments

1:   UPLO – CHARACTER(1)Input
On entry: specifies whether the upper or lower triangular part of A is stored.
UPLO='U'
The upper triangular part of A is stored.
UPLO='L'
The lower triangular part of A is stored.
Constraint: UPLO='U' or 'L'.
2:   N – INTEGERInput
On entry: n, the order of the matrix A.
Constraint: N≥0.
3:   ALPHA – REAL (KIND=nag_wp)Input
On entry: the scalar α.
4:   AP* – REAL (KIND=nag_wp) arrayInput
Note: the dimension of the array AP must be at least N× N+1/2 .
On entry: the n by n symmetric matrix A, packed by columns.
More precisely,
  • if UPLO='U', the upper triangle of A must be stored with element A ij in AP i+j j-1/2 for i≤j;
  • if UPLO='L', the lower triangle of A must be stored with element A ij in AP i+2 n-jj-1/2 for i≥j.
5:   X* – REAL (KIND=nag_wp) arrayInput
Note: the dimension of the array X must be at least max 1, 1+N-1 ×INCX .
On entry: the n-element vector x.
If INCX>0, xi must be stored in X 1+i-1×INCX, for i=1,2,…,N.
If INCX<0, xi must be stored in X 1-N-i×INCX, for i=1,2,…,N.
Intermediate elements of X are not referenced.
6:   INCX – INTEGERInput
On entry: the increment in the subscripts of X between successive elements of x.
Constraint: INCX≠0.
7:   BETA – REAL (KIND=nag_wp)Input
On entry: the scalar β.
8:   Y* – REAL (KIND=nag_wp) arrayInput/Output
Note: the dimension of the array Y must be at least max 1, 1+N-1 ×INCY .
On entry: the n-element vector y, if BETA=0.0 Y need not be set.
If INCY>0, yi must be stored in Y 1+i–1×INCY , for i=1,2,…,N.
If INCY<0, yi must be stored in Y 1–N–i×INCY , for i=1,2,…,N.
On exit: the updated vector y stored in the array elements used to supply the original vector y.
9:   INCY – INTEGERInput
On entry: the increment in the subscripts of Y between successive elements of y.
Constraint: INCY≠0.

6 Error Indicators and Warnings

None.

7 Accuracy

Not applicable.

8 Parallelism and Performance

F06PEF (DSPMV) is not threaded in any implementation.

9 Further Comments

None.

10 Example

None.
F06 Chapter Contents
F06 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F06PFF (DTRMV) : NAG Library, Mark 26

F06 Chapter Contents
F06 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F06PFF (DTRMV)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
10 Example

1 Purpose

F06PFF (DTRMV) computes the matrix-vector product for a real triangular matrix or its transpose.

2 Specification

SUBROUTINE F06PFF ( UPLO, TRANS, DIAG, N, A, LDA, X, INCX)
INTEGER | N, LDA, INCX
REAL (KIND=nag_wp) | A(LDA,*), X(*)
CHARACTER(1) | UPLO, TRANS, DIAG
The routine may be called by its BLAS name dtrmv.

3 Description

F06PFF (DTRMV) performs one of the matrix-vector operations
x←Ax   or   x←AT x ,
where A is an n by n real triangular matrix, and x is an n-element real vector.

4 References

None.

5 Arguments

1:   UPLO – CHARACTER(1)Input
On entry: specifies whether A is upper or lower triangular.
UPLO='U'
A is upper triangular.
UPLO='L'
A is lower triangular.
Constraint: UPLO='U' or 'L'.
2:   TRANS – CHARACTER(1)Input
On entry: specifies the operation to be performed.
TRANS='N'
x←Ax.
TRANS='T' or 'C'
x←AT x.
Constraint: TRANS='N', 'T' or 'C'.
3:   DIAG – CHARACTER(1)Input
On entry: specifies whether A has nonunit or unit diagonal elements.
DIAG='N'
The diagonal elements are stored explicitly.
DIAG='U'
The diagonal elements are assumed to be 1, and are not referenced.
Constraint: DIAG='N' or 'U'.
4:   N – INTEGERInput
On entry: n, the order of the matrix A.
Constraint: N≥0.
5:   A LDA* – REAL (KIND=nag_wp) arrayInput
Note: the second dimension of the array A must be at least N.
On entry: the n by n triangular matrix A.
  • If UPLO='U', A is upper triangular and the elements of the array below the diagonal are not referenced.
  • If UPLO='L', A is lower triangular and the elements of the array above the diagonal are not referenced.
  • If DIAG='U', the diagonal elements of A are assumed to be 1, and are not referenced.
6:   LDA – INTEGERInput
On entry: the first dimension of the array A as declared in the (sub)program from which F06PFF (DTRMV) is called.
Constraint: LDA≥ max 1,N .
7:   X* – REAL (KIND=nag_wp) arrayInput/Output
Note: the dimension of the array X must be at least max 1, 1+N-1 ×INCX .
On entry: the n-element vector x.
If INCX>0, xi must be stored in X 1+i–1×INCX , for i=1,2,…,N.
If INCX<0, xi must be stored in X 1–N–i×INCX , for i=1,2,…,N.
On exit: the updated vector x stored in the array elements used to supply the original vector x.
8:   INCX – INTEGERInput
On entry: the increment in the subscripts of X between successive elements of x.
Constraint: INCX≠0.

6 Error Indicators and Warnings

None.

7 Accuracy

Not applicable.

8 Parallelism and Performance

F06PFF (DTRMV) is not threaded in any implementation.

9 Further Comments

None.

10 Example

None.
F06 Chapter Contents
F06 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F06PGF (DTBMV) : NAG Library, Mark 26

F06 Chapter Contents
F06 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F06PGF (DTBMV)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
10 Example

1 Purpose

F06PGF (DTBMV) computes the matrix-vector product for a real triangular band matrix or its transpose.

2 Specification

SUBROUTINE F06PGF ( UPLO, TRANS, DIAG, N, K, A, LDA, X, INCX)
INTEGER | N, K, LDA, INCX
REAL (KIND=nag_wp) | A(LDA,*), X(*)
CHARACTER(1) | UPLO, TRANS, DIAG
The routine may be called by its BLAS name dtbmv.

3 Description

F06PGF (DTBMV) performs one of the matrix-vector operations
x←Ax   or   x←AT x ,
where A is an n by n real triangular band matrix with k subdiagonals or superdiagonals, and x is an n-element real vector.

4 References

None.

5 Arguments

1:   UPLO – CHARACTER(1)Input
On entry: specifies whether A is upper or lower triangular.
UPLO='U'
A is upper triangular.
UPLO='L'
A is lower triangular.
Constraint: UPLO='U' or 'L'.
2:   TRANS – CHARACTER(1)Input
On entry: specifies the operation to be performed.
TRANS='N'
x←Ax.
TRANS='T' or 'C'
x←AT x.
Constraint: TRANS='N', 'T' or 'C'.
3:   DIAG – CHARACTER(1)Input
On entry: specifies whether A has nonunit or unit diagonal elements.
DIAG='N'
The diagonal elements are stored explicitly.
DIAG='U'
The diagonal elements are assumed to be 1, and are not referenced.
Constraint: DIAG='N' or 'U'.
4:   N – INTEGERInput
On entry: n, the order of the matrix A.
Constraint: N≥0.
5:   K – INTEGERInput
On entry: k, the number of subdiagonals or superdiagonals of the matrix A.
Constraint: K≥0.
6:   A LDA* – REAL (KIND=nag_wp) arrayInput
Note: the second dimension of the array A must be at least N.
On entry: the n by n triangular band matrix A
The matrix is stored in rows 1 to k+1, more precisely,
  • if UPLO='U', the elements of the upper triangle of A within the band must be stored with element A ij in A k+1+i-j j​ for ​max 1,j-k≤i≤j;
  • if UPLO='L', the elements of the lower triangle of A within the band must be stored with element A ij in A 1+i-j j​ for ​j≤i≤min n,j+k.
If DIAG='U', the diagonal elements of A are assumed to be 1, and are not referenced.
7:   LDA – INTEGERInput
On entry: the first dimension of the array A as declared in the (sub)program from which F06PGF (DTBMV) is called.
Constraint: LDA≥K+1.
8:   X* – REAL (KIND=nag_wp) arrayInput/Output
Note: the dimension of the array X must be at least max 1, 1+N-1 ×INCX .
On entry: the n-element vector x.
If INCX>0, xi must be stored in X 1+i–1×INCX , for i=1,2,…,N.
If INCX<0, xi must be stored in X 1–N–i×INCX , for i=1,2,…,N.
On exit: the updated vector x stored in the array elements used to supply the original vector x.
9:   INCX – INTEGERInput
On entry: the increment in the subscripts of X between successive elements of x.
Constraint: INCX≠0.

6 Error Indicators and Warnings

None.

7 Accuracy

Not applicable.

8 Parallelism and Performance

F06PGF (DTBMV) is not threaded in any implementation.

9 Further Comments

None.

10 Example

None.
F06 Chapter Contents
F06 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F06PHF (DTPMV) : NAG Library, Mark 26

F06 Chapter Contents
F06 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F06PHF (DTPMV)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
10 Example

1 Purpose

F06PHF (DTPMV) computes the matrix-vector product for a real triangular matrix, or its transpose, stored in packed form.

2 Specification

SUBROUTINE F06PHF ( UPLO, TRANS, DIAG, N, AP, X, INCX)
INTEGER | N, INCX
REAL (KIND=nag_wp) | AP(*), X(*)
CHARACTER(1) | UPLO, TRANS, DIAG
The routine may be called by its BLAS name dtpmv.

3 Description

F06PHF (DTPMV) performs one of the matrix-vector operations
x←Ax   or   x←AT x ,
where A is an n by n real triangular matrix, stored in packed form, and x is an n-element real vector.

4 References

None.

5 Arguments

1:   UPLO – CHARACTER(1)Input
On entry: specifies whether A is upper or lower triangular.
UPLO='U'
A is upper triangular.
UPLO='L'
A is lower triangular.
Constraint: UPLO='U' or 'L'.
2:   TRANS – CHARACTER(1)Input
On entry: specifies the operation to be performed.
TRANS='N'
x←Ax.
TRANS='T' or 'C'
x←AT x.
Constraint: TRANS='N', 'T' or 'C'.
3:   DIAG – CHARACTER(1)Input
On entry: specifies whether A has nonunit or unit diagonal elements.
DIAG='N'
The diagonal elements are stored explicitly.
DIAG='U'
The diagonal elements are assumed to be 1, and are not referenced.
Constraint: DIAG='N' or 'U'.
4:   N – INTEGERInput
On entry: n, the order of the matrix A.
Constraint: N≥0.
5:   AP* – REAL (KIND=nag_wp) arrayInput
Note: the dimension of the array AP must be at least N× N+1/2 .
On entry: the n by n triangular matrix A, packed by columns.
More precisely,
  • if UPLO='U', the upper triangle of A must be stored with element A ij in AP i+j j-1/2 for i≤j;
  • if UPLO='L', the lower triangle of A must be stored with element A ij in AP i+2 n-jj-1/2 for i≥j.
If DIAG='U', the diagonal elements of A are assumed to be 1, and are not referenced; the same storage scheme is used whether DIAG='N' or ‘U’.
6:   X* – REAL (KIND=nag_wp) arrayInput/Output
Note: the dimension of the array X must be at least max 1, 1+N-1 ×INCX .
On entry: the n-element vector x.
If INCX>0, xi must be stored in X 1+i–1×INCX , for i=1,2,…,N.
If INCX<0, xi must be stored in X 1–N–i×INCX , for i=1,2,…,N.
On exit: the updated vector x stored in the array elements used to supply the original vector x.
7:   INCX – INTEGERInput
On entry: the increment in the subscripts of X between successive elements of x.
Constraint: INCX≠0.

6 Error Indicators and Warnings

None.

7 Accuracy

Not applicable.

8 Parallelism and Performance

F06PHF (DTPMV) is not threaded in any implementation.

9 Further Comments

None.

10 Example

None.
F06 Chapter Contents
F06 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F06PJF (DTRSV) : NAG Library, Mark 26

F06 Chapter Contents
F06 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F06PJF (DTRSV)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
10 Example

1 Purpose

F06PJF (DTRSV) solves a real triangular system of equations with a single right hand side.

2 Specification

SUBROUTINE F06PJF ( UPLO, TRANS, DIAG, N, A, LDA, X, INCX)
INTEGER | N, LDA, INCX
REAL (KIND=nag_wp) | A(LDA,*), X(*)
CHARACTER(1) | UPLO, TRANS, DIAG
The routine may be called by its BLAS name dtrsv.

3 Description

F06PJF (DTRSV) performs one of the matrix-vector operations
x←A-1 x   or   x←A-T x ,
where A is an n by n real triangular matrix, and x is an n-element real vector. A-T denotes AT-1 or equivalently A-1 T .
No test for singularity or near-singularity of A is included in this routine. Such tests must be performed before calling this routine.

4 References

None.

5 Arguments

1:   UPLO – CHARACTER(1)Input
On entry: specifies whether A is upper or lower triangular.
UPLO='U'
A is upper triangular.
UPLO='L'
A is lower triangular.
Constraint: UPLO='U' or 'L'.
2:   TRANS – CHARACTER(1)Input
On entry: specifies the operation to be performed.
TRANS='N'
x←A-1 x.
TRANS='T' or 'C'
x←A-T x.
Constraint: TRANS='N', 'T' or 'C'.
3:   DIAG – CHARACTER(1)Input
On entry: specifies whether A has nonunit or unit diagonal elements.
DIAG='N'
The diagonal elements are stored explicitly.
DIAG='U'
The diagonal elements are assumed to be 1, and are not referenced.
Constraint: DIAG='N' or 'U'.
4:   N – INTEGERInput
On entry: n, the order of the matrix A.
Constraint: N≥0.
5:   A LDA* – REAL (KIND=nag_wp) arrayInput
Note: the second dimension of the array A must be at least N.
On entry: the n by n triangular matrix A.
  • If UPLO='U', A is upper triangular and the elements of the array below the diagonal are not referenced.
  • If UPLO='L', A is lower triangular and the elements of the array above the diagonal are not referenced.
  • If DIAG='U', the diagonal elements of A are assumed to be 1, and are not referenced.
6:   LDA – INTEGERInput
On entry: the first dimension of the array A as declared in the (sub)program from which F06PJF (DTRSV) is called.
Constraint: LDA≥ max 1,N .
7:   X* – REAL (KIND=nag_wp) arrayInput/Output
Note: the dimension of the array X must be at least max 1, 1+N-1 ×INCX .
On entry: the n-element vector x.
If INCX>0, xi must be stored in X 1+i–1×INCX , for i=1,2,…,N.
If INCX<0, xi must be stored in X 1–N–i×INCX , for i=1,2,…,N.
On exit: the updated vector x stored in the array elements used to supply the original vector x.
8:   INCX – INTEGERInput
On entry: the increment in the subscripts of X between successive elements of x.
Constraint: INCX≠0.

6 Error Indicators and Warnings

None.

7 Accuracy

Not applicable.

8 Parallelism and Performance

F06PJF (DTRSV) is not threaded in any implementation.

9 Further Comments

None.

10 Example

None.
F06 Chapter Contents
F06 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F06PKF (DTBSV) : NAG Library, Mark 26

F06 Chapter Contents
F06 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F06PKF (DTBSV)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
10 Example

1 Purpose

F06PKF (DTBSV) solves a real triangular banded system of equations with a single right hand side.

2 Specification

SUBROUTINE F06PKF ( UPLO, TRANS, DIAG, N, K, A, LDA, X, INCX)
INTEGER | N, K, LDA, INCX
REAL (KIND=nag_wp) | A(LDA,*), X(*)
CHARACTER(1) | UPLO, TRANS, DIAG
The routine may be called by its BLAS name dtbsv.

3 Description

F06PKF (DTBSV) performs one of the matrix-vector operations
x←A-1 x   or   x←A-T x ,
where A is an n by n real triangular band matrix with k subdiagonals or superdiagonals, and x is an n-element real vector. A-T denotes AT-1 or equivalently A-1 T .
No test for singularity or near-singularity of A is included in this routine. Such tests must be performed before calling this routine.

4 References

None.

5 Arguments

1:   UPLO – CHARACTER(1)Input
On entry: specifies whether A is upper or lower triangular.
UPLO='U'
A is upper triangular.
UPLO='L'
A is lower triangular.
Constraint: UPLO='U' or 'L'.
2:   TRANS – CHARACTER(1)Input
On entry: specifies the operation to be performed.
TRANS='N'
x←A-1 x.
TRANS='T' or 'C'
x←A-T x.
Constraint: TRANS='N', 'T' or 'C'.
3:   DIAG – CHARACTER(1)Input
On entry: specifies whether A has nonunit or unit diagonal elements.
DIAG='N'
The diagonal elements are stored explicitly.
DIAG='U'
The diagonal elements are assumed to be 1, and are not referenced.
Constraint: DIAG='N' or 'U'.
4:   N – INTEGERInput
On entry: n, the order of the matrix A.
Constraint: N≥0.
5:   K – INTEGERInput
On entry: k, the number of subdiagonals or superdiagonals of the matrix A.
Constraint: K≥0.
6:   A LDA* – REAL (KIND=nag_wp) arrayInput
Note: the second dimension of the array A must be at least N.
On entry: the n by n triangular band matrix A
The matrix is stored in rows 1 to k+1, more precisely,
  • if UPLO='U', the elements of the upper triangle of A within the band must be stored with element A ij in A k+1+i-j j​ for ​max 1,j-k≤i≤j;
  • if UPLO='L', the elements of the lower triangle of A within the band must be stored with element A ij in A 1+i-j j​ for ​j≤i≤min n,j+k.
If DIAG='U', the diagonal elements of A are assumed to be 1, and are not referenced.
7:   LDA – INTEGERInput
On entry: the first dimension of the array A as declared in the (sub)program from which F06PKF (DTBSV) is called.
Constraint: LDA≥K+1.
8:   X* – REAL (KIND=nag_wp) arrayInput/Output
Note: the dimension of the array X must be at least max 1, 1+N-1 ×INCX .
On entry: the n-element vector x.
If INCX>0, xi must be stored in X 1+i–1×INCX , for i=1,2,…,N.
If INCX<0, xi must be stored in X 1–N–i×INCX , for i=1,2,…,N.
On exit: the updated vector x stored in the array elements used to supply the original vector x.
9:   INCX – INTEGERInput
On entry: the increment in the subscripts of X between successive elements of x.
Constraint: INCX≠0.

6 Error Indicators and Warnings

None.

7 Accuracy

Not applicable.

8 Parallelism and Performance

F06PKF (DTBSV) is not threaded in any implementation.

9 Further Comments

None.

10 Example

None.
F06 Chapter Contents
F06 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F06PLF (DTPSV) : NAG Library, Mark 26

F06 Chapter Contents
F06 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F06PLF (DTPSV)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
10 Example

1 Purpose

F06PLF (DTPSV) solves a real triangular system of equations, stored in packed form, with a single right hand side.

2 Specification

SUBROUTINE F06PLF ( UPLO, TRANS, DIAG, N, AP, X, INCX)
INTEGER | N, INCX
REAL (KIND=nag_wp) | AP(*), X(*)
CHARACTER(1) | UPLO, TRANS, DIAG
The routine may be called by its BLAS name dtpsv.

3 Description

F06PLF (DTPSV) performs one of the matrix-vector operations
x←A-1 x   or   x←A-T x ,
where A is an n by n real triangular matrix, stored in packed form, and x is an n-element real vector. A-T denotes A-T or equivalently A-T.
No test for singularity or near-singularity of A is included in this routine. Such tests must be performed before calling this routine.

4 References

None.

5 Arguments

1:   UPLO – CHARACTER(1)Input
On entry: specifies whether A is upper or lower triangular.
UPLO='U'
A is upper triangular.
UPLO='L'
A is lower triangular.
Constraint: UPLO='U' or 'L'.
2:   TRANS – CHARACTER(1)Input
On entry: specifies the operation to be performed.
TRANS='N'
x←A-1 x.
TRANS='T' or 'C'
x←A-T x.
Constraint: TRANS='N', 'T' or 'C'.
3:   DIAG – CHARACTER(1)Input
On entry: specifies whether A has nonunit or unit diagonal elements.
DIAG='N'
The diagonal elements are stored explicitly.
DIAG='U'
The diagonal elements are assumed to be 1, and are not referenced.
Constraint: DIAG='N' or 'U'.
4:   N – INTEGERInput
On entry: n, the order of the matrix A.
Constraint: N≥0.
5:   AP* – REAL (KIND=nag_wp) arrayInput
Note: the dimension of the array AP must be at least N× N+1/2 .
On entry: the n by n triangular matrix A, packed by columns.
More precisely,
  • if UPLO='U', the upper triangle of A must be stored with element A ij in AP i+j j-1/2 for i≤j;
  • if UPLO='L', the lower triangle of A must be stored with element A ij in AP i+2 n-jj-1/2 for i≥j.
If DIAG='U', the diagonal elements of A are assumed to be 1, and are not referenced; the same storage scheme is used whether DIAG='N' or ‘U’.
6:   X* – REAL (KIND=nag_wp) arrayInput/Output
Note: the dimension of the array X must be at least max 1, 1+N-1 ×INCX .
On entry: the n-element vector x.
If INCX>0, xi must be stored in X 1+i–1×INCX , for i=1,2,…,N.
If INCX<0, xi must be stored in X 1–N–i×INCX , for i=1,2,…,N.
On exit: the updated vector x stored in the array elements used to supply the original vector x.
7:   INCX – INTEGERInput
On entry: the increment in the subscripts of X between successive elements of x.
Constraint: INCX≠0.

6 Error Indicators and Warnings

None.

7 Accuracy

Not applicable.

8 Parallelism and Performance

F06PLF (DTPSV) is not threaded in any implementation.

9 Further Comments

None.

10 Example

None.
F06 Chapter Contents
F06 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F06PMF (DGER) : NAG Library, Mark 26

F06 Chapter Contents
F06 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F06PMF (DGER)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
10 Example

1 Purpose

F06PMF (DGER) computes the rank-1 update of a real general matrix.

2 Specification

SUBROUTINE F06PMF ( M, N, ALPHA, X, INCX, Y, INCY, A, LDA)
INTEGER | M, N, INCX, INCY, LDA
REAL (KIND=nag_wp) | ALPHA, X(*), Y(*), A(LDA,*)
The routine may be called by its BLAS name dger.

3 Description

F06PMF (DGER) performs the rank-1 update operation
A←αx yT + A ,
where A is an m by n real matrix, x is an m element real vector, y is an n-element real vector, and α is a real scalar.

4 References

None.

5 Arguments

1:   M – INTEGERInput
On entry: m, the number of rows of the matrix A.
Constraint: M≥0.
2:   N – INTEGERInput
On entry: n, the number of columns of the matrix A.
Constraint: N≥0.
3:   ALPHA – REAL (KIND=nag_wp)Input
On entry: the scalar α.
4:   X* – REAL (KIND=nag_wp) arrayInput
Note: the dimension of the array X must be at least max 1, 1+M-1 ×INCX .
On entry: the m element vector x.
If INCX>0, xi must be stored in X 1+i-1×INCX, for i=1,2,…,M.
If INCX<0, xi must be stored in X 1-M-i×INCX, for i=1,2,…,M.
Intermediate elements of X are not referenced.
5:   INCX – INTEGERInput
On entry: the increment in the subscripts of X between successive elements of x.
Constraint: INCX≠0.
6:   Y* – REAL (KIND=nag_wp) arrayInput
Note: the dimension of the array Y must be at least max 1, 1+N-1 ×INCY .
On entry: the n-element vector y.
If INCY>0, yi must be stored in Y 1+i-1×INCY, for i=1,2,…,N.
If INCY<0, yi must be stored in Y 1-N-i×INCY, for i=1,2,…,N.
Intermediate elements of Y are not referenced.
7:   INCY – INTEGERInput
On entry: the increment in the subscripts of Y between successive elements of y.
Constraint: INCY≠0.
8:   A LDA* – REAL (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array A must be at least N.
On entry: the m by n matrix A.
On exit: the updated matrix A.
9:   LDA – INTEGERInput
On entry: the first dimension of the array A as declared in the (sub)program from which F06PMF (DGER) is called.
Constraint: LDA≥ max 1,M .

6 Error Indicators and Warnings

None.

7 Accuracy

Not applicable.

8 Parallelism and Performance

F06PMF (DGER) is not threaded in any implementation.

9 Further Comments

None.

10 Example

None.
F06 Chapter Contents
F06 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F06PPF (DSYR) : NAG Library, Mark 26

F06 Chapter Contents
F06 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F06PPF (DSYR)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
10 Example

1 Purpose

F06PPF (DSYR) computes the rank-1 update of a real symmetric matrix.

2 Specification

SUBROUTINE F06PPF ( UPLO, N, ALPHA, X, INCX, A, LDA)
INTEGER | N, INCX, LDA
REAL (KIND=nag_wp) | ALPHA, X(*), A(LDA,*)
CHARACTER(1) | UPLO
The routine may be called by its BLAS name dsyr.

3 Description

F06PPF (DSYR) performs the symmetric rank-1 update operation
A←αx xT+A ,
where A is an n by n real symmetric matrix, x is an n-element real vector, and α is a real scalar.

4 References

None.

5 Arguments

1:   UPLO – CHARACTER(1)Input
On entry: specifies whether the upper or lower triangular part of A is stored.
UPLO='U'
The upper triangular part of A is stored.
UPLO='L'
The lower triangular part of A is stored.
Constraint: UPLO='U' or 'L'.
2:   N – INTEGERInput
On entry: n, the order of the matrix A.
Constraint: N≥0.
3:   ALPHA – REAL (KIND=nag_wp)Input
On entry: the scalar α.
4:   X* – REAL (KIND=nag_wp) arrayInput
Note: the dimension of the array X must be at least max 1, 1+N-1 ×INCX .
On entry: the n-element vector x.
If INCX>0, xi must be stored in X 1+i-1×INCX, for i=1,2,…,N.
If INCX<0, xi must be stored in X 1-N-i×INCX, for i=1,2,…,N.
Intermediate elements of X are not referenced.
5:   INCX – INTEGERInput
On entry: the increment in the subscripts of X between successive elements of x.
Constraint: INCX≠0.
6:   A LDA* – REAL (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array A must be at least max 1,N.
On entry: the n by n symmetric matrix A.
  • If UPLO='U', the upper triangular part of A must be stored and the elements of the array below the diagonal are not referenced.
  • If UPLO='L', the lower triangular part of A must be stored and the elements of the array above the diagonal are not referenced.
On exit: the updated matrix A.
7:   LDA – INTEGERInput
On entry: the first dimension of the array A as declared in the (sub)program from which F06PPF (DSYR) is called.
Constraint: LDA≥ max 1,N .

6 Error Indicators and Warnings

None.

7 Accuracy

Not applicable.

8 Parallelism and Performance

F06PPF (DSYR) is not threaded in any implementation.

9 Further Comments

None.

10 Example

None.
F06 Chapter Contents
F06 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F06PQF (DSPR) : NAG Library, Mark 26

F06 Chapter Contents
F06 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F06PQF (DSPR)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
10 Example

1 Purpose

F06PQF (DSPR) computes the rank-1 update of a real symmetric matrix stored in packed form.

2 Specification

SUBROUTINE F06PQF ( UPLO, N, ALPHA, X, INCX, AP)
INTEGER | N, INCX
REAL (KIND=nag_wp) | ALPHA, X(*), AP(*)
CHARACTER(1) | UPLO
The routine may be called by its BLAS name dspr.

3 Description

F06PQF (DSPR) performs the symmetric rank-1 update operation
A←αx xT + A ,
where A is an n by n real symmetric matrix, stored in packed form, x is an n-element real vector, and α is a real scalar.

4 References

None.

5 Arguments

1:   UPLO – CHARACTER(1)Input
On entry: specifies whether the upper or lower triangular part of A is stored.
UPLO='U'
The upper triangular part of A is stored.
UPLO='L'
The lower triangular part of A is stored.
Constraint: UPLO='U' or 'L'.
2:   N – INTEGERInput
On entry: n, the order of the matrix A.
Constraint: N≥0.
3:   ALPHA – REAL (KIND=nag_wp)Input
On entry: the scalar α.
4:   X* – REAL (KIND=nag_wp) arrayInput
Note: the dimension of the array X must be at least max 1, 1+N-1 ×INCX .
On entry: the n-element vector x.
If INCX>0, xi must be stored in X 1+i-1×INCX, for i=1,2,…,N.
If INCX<0, xi must be stored in X 1-N-i×INCX, for i=1,2,…,N.
Intermediate elements of X are not referenced.
5:   INCX – INTEGERInput
On entry: the increment in the subscripts of X between successive elements of x.
Constraint: INCX≠0.
6:   AP* – REAL (KIND=nag_wp) arrayInput/Output
Note: the dimension of the array AP must be at least N× N+1/2 .
On entry: the n by n symmetric matrix A, packed by columns.
More precisely,
  • if UPLO='U', the upper triangle of A must be stored with element A ij in AP i+j j-1/2 for i≤j;
  • if UPLO='L', the lower triangle of A must be stored with element A ij in AP i+2 n-jj-1/2 for i≥j.
On exit: the updated matrix A.

6 Error Indicators and Warnings

None.

7 Accuracy

Not applicable.

8 Parallelism and Performance

F06PQF (DSPR) is not threaded in any implementation.

9 Further Comments

None.

10 Example

None.
F06 Chapter Contents
F06 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F06PRF (DSYR2) : NAG Library, Mark 26

F06 Chapter Contents
F06 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F06PRF (DSYR2)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
10 Example

1 Purpose

F06PRF (DSYR2) computes the rank-2 update of a real symmetric matrix.

2 Specification

SUBROUTINE F06PRF ( UPLO, N, ALPHA, X, INCX, Y, INCY, A, LDA)
INTEGER | N, INCX, INCY, LDA
REAL (KIND=nag_wp) | ALPHA, X(*), Y(*), A(LDA,*)
CHARACTER(1) | UPLO
The routine may be called by its BLAS name dsyr2.

3 Description

F06PRF (DSYR2) performs the symmetric rank-2 update operation
A←αx yT + αy xT + A ,
where A is an n by n real symmetric matrix, x and y are n-element real vectors, and α is a real scalar.

4 References

None.

5 Arguments

1:   UPLO – CHARACTER(1)Input
On entry: specifies whether the upper or lower triangular part of A is stored.
UPLO='U'
The upper triangular part of A is stored.
UPLO='L'
The lower triangular part of A is stored.
Constraint: UPLO='U' or 'L'.
2:   N – INTEGERInput
On entry: n, the order of the matrix A.
Constraint: N≥0.
3:   ALPHA – REAL (KIND=nag_wp)Input
On entry: the scalar α.
4:   X* – REAL (KIND=nag_wp) arrayInput
Note: the dimension of the array X must be at least max 1, 1+N-1 ×INCX .
On entry: the n-element vector x.
If INCX>0, xi must be stored in X 1+i-1×INCX, for i=1,2,…,N.
If INCX<0, xi must be stored in X 1-N-i×INCX, for i=1,2,…,N.
Intermediate elements of X are not referenced.
5:   INCX – INTEGERInput
On entry: the increment in the subscripts of X between successive elements of x.
Constraint: INCX≠0.
6:   Y* – REAL (KIND=nag_wp) arrayInput
Note: the dimension of the array Y must be at least max 1, 1+N-1 ×INCY .
On entry: the n-element vector y.
If INCY>0, yi must be stored in Y 1+i-1×INCY, for i=1,2,…,N.
If INCY<0, yi must be stored in Y 1-N-i×INCY, for i=1,2,…,N.
Intermediate elements of Y are not referenced.
7:   INCY – INTEGERInput
On entry: the increment in the subscripts of Y between successive elements of y.
Constraint: INCY≠0.
8:   A LDA* – REAL (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array A must be at least max 1,N.
On entry: the n by n symmetric matrix A.
  • If UPLO='U', the upper triangular part of A must be stored and the elements of the array below the diagonal are not referenced.
  • If UPLO='L', the lower triangular part of A must be stored and the elements of the array above the diagonal are not referenced.
On exit: the updated matrix A.
9:   LDA – INTEGERInput
On entry: the first dimension of the array A as declared in the (sub)program from which F06PRF (DSYR2) is called.
Constraint: LDA≥ max 1,N .

6 Error Indicators and Warnings

None.

7 Accuracy

Not applicable.

8 Parallelism and Performance

F06PRF (DSYR2) is not threaded in any implementation.

9 Further Comments

None.

10 Example

None.
F06 Chapter Contents
F06 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F06PSF (DSPR2) : NAG Library, Mark 26

F06 Chapter Contents
F06 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F06PSF (DSPR2)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
10 Example

1 Purpose

F06PSF (DSPR2) computes the rank-2 update of a real symmetric matrix stored in packed form.

2 Specification

SUBROUTINE F06PSF ( UPLO, N, ALPHA, X, INCX, Y, INCY, AP)
INTEGER | N, INCX, INCY
REAL (KIND=nag_wp) | ALPHA, X(*), Y(*), AP(*)
CHARACTER(1) | UPLO
The routine may be called by its BLAS name dspr2.

3 Description

F06PSF (DSPR2) performs the symmetric rank-2 update operation
A←αx yT + αy xT + A ,
where A is an n by n real symmetric matrix, stored in packed form, x and y are n-element real vectors, and α is a real scalar.

4 References

None.

5 Arguments

1:   UPLO – CHARACTER(1)Input
On entry: specifies whether the upper or lower triangular part of A is stored.
UPLO='U'
The upper triangular part of A is stored.
UPLO='L'
The lower triangular part of A is stored.
Constraint: UPLO='U' or 'L'.
2:   N – INTEGERInput
On entry: n, the order of the matrix A.
Constraint: N≥0.
3:   ALPHA – REAL (KIND=nag_wp)Input
On entry: the scalar α.
4:   X* – REAL (KIND=nag_wp) arrayInput
Note: the dimension of the array X must be at least max 1, 1+N-1 ×INCX .
On entry: the n-element vector x.
If INCX>0, xi must be stored in X 1+i-1×INCX, for i=1,2,…,N.
If INCX<0, xi must be stored in X 1-N-i×INCX, for i=1,2,…,N.
Intermediate elements of X are not referenced.
5:   INCX – INTEGERInput
On entry: the increment in the subscripts of X between successive elements of x.
Constraint: INCX≠0.
6:   Y* – REAL (KIND=nag_wp) arrayInput
Note: the dimension of the array Y must be at least max 1, 1+N-1 ×INCY .
On entry: the n-element vector y.
If INCY>0, yi must be stored in Y 1+i-1×INCY, for i=1,2,…,N.
If INCY<0, yi must be stored in Y 1-N-i×INCY, for i=1,2,…,N.
Intermediate elements of Y are not referenced.
7:   INCY – INTEGERInput
On entry: the increment in the subscripts of Y between successive elements of y.
Constraint: INCY≠0.
8:   AP* – REAL (KIND=nag_wp) arrayInput/Output
Note: the dimension of the array AP must be at least N× N+1/2 .
On entry: the n by n symmetric matrix A, packed by columns.
More precisely,
  • if UPLO='U', the upper triangle of A must be stored with element A ij in AP i+j j-1/2 for i≤j;
  • if UPLO='L', the lower triangle of A must be stored with element A ij in AP i+2 n-jj-1/2 for i≥j.
On exit: the updated matrix A.

6 Error Indicators and Warnings

None.

7 Accuracy

Not applicable.

8 Parallelism and Performance

F06PSF (DSPR2) is not threaded in any implementation.

9 Further Comments

None.

10 Example

None.
F06 Chapter Contents
F06 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F06QFF : NAG Library, Mark 26

F06 Chapter Contents
F06 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F06QFF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
10 Example

1 Purpose

F06QFF performs the matrix-copy operation
B←A
where A and B are m by n real general or trapezoidal matrices.

2 Specification

SUBROUTINE F06QFF ( MATRIX, M, N, A, LDA, B, LDB)
INTEGER | M, N, LDA, LDB
REAL (KIND=nag_wp) | A(LDA,*), B(LDB,*)
CHARACTER(1) | MATRIX

3 Description

None.

4 References

None.

5 Arguments

1:   MATRIX – CHARACTER(1)Input
On entry: the matrix type.
MATRIX='G'
General matrix.
MATRIX='U'
Upper trapezoidal matrix (upper triangular if m=n).
MATRIX='L'
Lower trapezoidal matrix (lower triangular if m=n).
Constraint: MATRIX='G', 'U' or 'L'.
2:   M – INTEGERInput
On entry: m, the number of rows of the matrices A and B.
Constraint: M≥0.
3:   N – INTEGERInput
On entry: n, the number of columns of the matrices A and B.
Constraint: N≥0.
4:   A LDA* – REAL (KIND=nag_wp) arrayInput
Note: the second dimension of the array A must be at least N.
On entry: the m by n general or trapezoidal matrix A.
  • If MATRIX='U', A is upper trapezoidal and the elements of the array below the diagonal are not referenced.
  • If MATRIX='L', A is lower trapezoidal and the elements of the array above the diagonal are not referenced.
5:   LDA – INTEGERInput
On entry: the first dimension of the array A as declared in the (sub)program from which F06QFF is called.
Constraint: LDA≥ max 1,M .
6:   B LDB* – REAL (KIND=nag_wp) arrayOutput
Note: the second dimension of the array B must be at least N.
On exit: the m by n general or trapezoidal matrix B.
  • If MATRIX='U', B is upper trapezoidal and the elements of the array below the diagonal are not referenced.
  • If MATRIX='L', B is lower trapezoidal and the elements of the array above the diagonal are not referenced.
7:   LDB – INTEGERInput
On entry: the first dimension of the array B as declared in the (sub)program from which F06QFF is called.
Constraint: LDB≥ max 1,M .

6 Error Indicators and Warnings

None.

7 Accuracy

Not applicable.

8 Parallelism and Performance

F06QFF is not threaded in any implementation.

9 Further Comments

None.

10 Example

None.
F06 Chapter Contents
F06 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F06QHF : NAG Library, Mark 26

F06 Chapter Contents
F06 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F06QHF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
10 Example

1 Purpose

F06QHF forms the real m by n rectangular or trapezoidal matrix A given by
a ij = diag if i=j const if i≠j .

2 Specification

SUBROUTINE F06QHF ( MATRIX, M, N, CON, DIAG, A, LDA)
INTEGER | M, N, LDA
REAL (KIND=nag_wp) | CON, DIAG, A(LDA,*)
CHARACTER(1) | MATRIX

3 Description

None.

4 References

None.

5 Arguments

1:   MATRIX – CHARACTER(1)Input
On entry: the matrix type.
MATRIX='G'
General matrix.
MATRIX='U'
Upper trapezoidal matrix (upper triangular if m=n).
MATRIX='L'
Lower trapezoidal matrix (lower triangular if m=n).
Constraint: MATRIX='G', 'U' or 'L'.
2:   M – INTEGERInput
On entry: m, the number of rows of the matrix A.
Constraint: M≥0.
3:   N – INTEGERInput
On entry: n, the number of columns of the matrix A.
Constraint: N≥0.
4:   CON – REAL (KIND=nag_wp)Input
On entry: the value to be assigned to the off-diagonal elements of A.
5:   DIAG – REAL (KIND=nag_wp)Input
On entry: the value to be assigned to the diagonal elements of A.
6:   A LDA* – REAL (KIND=nag_wp) arrayOutput
Note: the second dimension of the array A must be at least N.
On exit: the m by n general or trapezoidal matrix A.
  • If MATRIX='U', A is upper trapezoidal and the elements of the array below the diagonal are not referenced.
  • If MATRIX='L', A is lower trapezoidal and the elements of the array above the diagonal are not referenced.
7:   LDA – INTEGERInput
On entry: the first dimension of the array A as declared in the (sub)program from which F06QHF is called.
Constraint: LDA≥ max 1,M .

6 Error Indicators and Warnings

None.

7 Accuracy

Not applicable.

8 Parallelism and Performance

F06QHF is not threaded in any implementation.

9 Further Comments

None.

10 Example

None.
F06 Chapter Contents
F06 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F06QJF : NAG Library, Mark 26

F06 Chapter Contents
F06 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F06QJF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
10 Example

1 Purpose

F06QJF permutes the rows or columns of a real rectangular matrix using an integer array of permutations.

2 Specification

SUBROUTINE F06QJF ( SIDE, TRANS, N, PERM, K, B, LDB)
INTEGER | N, PERM(*), K, LDB
REAL (KIND=nag_wp) | B(LDB,*)
CHARACTER(1) | SIDE, TRANS

3 Description

F06QJF performs one of the permutation operations
B←PT B, B←PB, B←B PT  or B←BP,
where B is a real matrix, and P is a permutation matrix.
P is represented in the form
P=P 1,p 1P 2,p 2⋯P n,pn,
where P i,j is the permutation matrix that interchanges items i and j; that is, P i,j is the unit matrix with rows and columns i and j interchanged. If i=j, P i,j=I.
Let m denote the number of rows of B if SIDE='L', or the number of columns of B if SIDE='R': the routine does not require m to be passed as an argument, but assumes that m≥pi, for i=1,2,…,n.
This routine requires the indices pi to be supplied in an integer array; F06QKF performs the same operation with the indices supplied in a real array.

4 References

None.

5 Arguments

1:   SIDE – CHARACTER(1)Input
2:   TRANS – CHARACTER(1)Input
On entry: specifies the operation to be performed.
SIDE='L' and TRANS='T'
B←PT B.
SIDE='L' and TRANS='N'
B←PB.
SIDE='R' and TRANS='T'
B←B PT.
SIDE='R' and TRANS='N'
B←BP.
Constraints:
  • SIDE='L' or 'R';
  • TRANS='N' or 'T'.
3:   N – INTEGERInput
On entry: n, the number of interchanges in the representation of P.
Constraint: N≥0.
4:   PERM* – INTEGER arrayInput
Note: the dimension of the array PERM must be at least max 1,N .
On entry: the n indices pi which define the interchanges in the representation of P. It is usual to have pi≥i, but this is not necessary.
Constraint: 1≤PERM i≤m.
5:   K – INTEGERInput
On entry: k, the number of columns of B if SIDE='L', or the number of rows of B if SIDE='R'.
Constraint: K≥0.
6:   B LDB* – REAL (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array B must be at least max 1,K if SIDE='L' and at least max 1,maxk PERM k if SIDE='R'.
On entry: the original matrix B; B is m by k if SIDE='L', or k by m if SIDE='R'.
On exit: the permuted matrix B.
7:   LDB – INTEGERInput
On entry: the first dimension of the array B as declared in the (sub)program from which F06QJF is called.
Constraints:
  • if SIDE='L', LDB≥ max 1,m ;
  • if SIDE='R', LDB≥ max 1,K .

6 Error Indicators and Warnings

None.

7 Accuracy

Not applicable.

8 Parallelism and Performance

F06QJF is not threaded in any implementation.

9 Further Comments

None.

10 Example

None.
F06 Chapter Contents
F06 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F06QKF : NAG Library, Mark 26

F06 Chapter Contents
F06 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F06QKF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
10 Example

1 Purpose

F06QKF permutes the rows or columns of a real rectangular matrix using a real array of permutations.

2 Specification

SUBROUTINE F06QKF ( SIDE, TRANS, N, PERM, K, B, LDB)
INTEGER | N, K, LDB
REAL (KIND=nag_wp) | PERM(*), B(LDB,*)
CHARACTER(1) | SIDE, TRANS

3 Description

F06QKF performs one of the permutation operations
B←PT B, B←PB, B←B PT  or B←BP,
where B is a real matrix, and P is a permutation matrix.
P is represented in the form
P=P 1,p 1P 2,p 2⋯P n,pn,
where P i,j is the permutation matrix that interchanges items i and j; that is, P i,j is the unit matrix with rows and columns i and j interchanged. If i=j, P i,j=I.
Let m denote the number of rows of B if SIDE='L', or the number of columns of B if SIDE='R': the routine does not require m to be passed as an argument, but assumes that m≥pi, for i=1,2,…,n.
This routine requires the indices pi to be supplied in a real array (the routine takes the integer part of the array elements); F06QJF performs the same operation with the indices supplied in an integer array.

4 References

None.

5 Arguments

1:   SIDE – CHARACTER(1)Input
2:   TRANS – CHARACTER(1)Input
On entry: specifies the operation to be performed.
SIDE='L' and TRANS='T'
B←PT B.
SIDE='L' and TRANS='N'
B←PB.
SIDE='R' and TRANS='T'
B←B PT.
SIDE='R' and TRANS='N'
B←BP.
Constraints:
  • SIDE='L' or 'R';
  • TRANS='N' or 'T'.
3:   N – INTEGERInput
On entry: n, the number of interchanges in the representation of P.
Constraint: N≥0.
4:   PERM* – REAL (KIND=nag_wp) arrayInput
Note: the dimension of the array PERM must be at least max 1,N .
On entry: the n indices pi which define the interchanges in the representation of P. It is usual to have pi≥i, but this is not necessary.
Constraint: 1≤PERM i≤m.
5:   K – INTEGERInput
On entry: k, the number of columns of B if SIDE='L', or the number of rows of B if SIDE='R'.
Constraint: K≥0.
6:   B LDB* – REAL (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array B must be at least max 1,K if SIDE='L' and at least max 1,maxk int⁡PERM k if SIDE='R'.
On entry: the original matrix B; B is m by k if SIDE='L', or k by m if SIDE='R'.
On exit: the permuted matrix B.
7:   LDB – INTEGERInput
On entry: the first dimension of the array B as declared in the (sub)program from which F06QKF is called.
Constraints:
  • if SIDE='L', LDB≥ max 1,m ;
  • if SIDE='R', LDB≥ max 1,K .

6 Error Indicators and Warnings

None.

7 Accuracy

Not applicable.

8 Parallelism and Performance

F06QKF is not threaded in any implementation.

9 Further Comments

None.

10 Example

None.
F06 Chapter Contents
F06 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F06QMF : NAG Library, Mark 26

F06 Chapter Contents
F06 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F06QMF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
10 Example

1 Purpose

F06QMF performs an orthogonal similarity transformation (as a sequence of plane rotations) of a real symmetric matrix.

2 Specification

SUBROUTINE F06QMF ( UPLO, PIVOT, DIRECT, N, K1, K2, C, S, A, LDA)
INTEGER | N, K1, K2, LDA
REAL (KIND=nag_wp) | C(*), S(*), A(LDA,*)
CHARACTER(1) | UPLO, PIVOT, DIRECT

3 Description

F06QMF performs the transformation
A←PA PT
where A is an n by n real symmetric matrix, and P is a real orthogonal matrix defined as a sequence of plane rotations, Pk, applied in planes k 1 to k 2.
The 2 by 2 plane rotation part of Pk is assumed to have the form
ck sk -sk ck .

4 References

None.

5 Arguments

1:   UPLO – CHARACTER(1)Input
On entry: specifies whether the upper or lower triangular part of A is stored.
UPLO='U'
The upper triangular part of A is stored.
UPLO='L'
The lower triangular part of A is stored.
Constraint: UPLO='U' or 'L'.
2:   PIVOT – CHARACTER(1)Input
On entry: specifies the plane rotated by Pk.
PIVOT='V' (variable pivot)
Pk rotates the k,k+1 plane.
PIVOT='T' (top pivot)
Pk rotates the k 1,k+1 plane.
PIVOT='B' (bottom pivot)
Pk rotates the k,k 2 plane.
Constraint: PIVOT='V', 'T' or 'B'.
3:   DIRECT – CHARACTER(1)Input
On entry: specifies the sequence direction.
DIRECT='F' (forward sequence)
P=P k 2-1⋯P k 1+1P k 1.
DIRECT='B' (backward sequence)
P=P k 1P k 1+1⋯P k 2-1.
Constraint: DIRECT='F' or 'B'.
4:   N – INTEGERInput
On entry: n, the order of the matrix A.
Constraint: N≥0.
5:   K1 – INTEGERInput
6:   K2 – INTEGERInput
On entry: the values k 1 and k 2.
If K1<1 or K2≤K1 or K2>N, an immediate return is effected.
7:   C* – REAL (KIND=nag_wp) arrayInput
Note: the dimension of the array C must be at least K2-K1.
On entry: C k must hold ck, the cosine of the rotation Pk, for k=k 1,…,k 2-1.
8:   S* – REAL (KIND=nag_wp) arrayInput
Note: the dimension of the array S must be at least K2-K1.
On entry: S k must hold sk, the sine of the rotation Pk, for k=k 1,…,k 2-1.
9:   A LDA* – REAL (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array A must be at least max 1,N.
On entry: the n by n symmetric matrix A.
  • If UPLO='U', the upper triangular part of A must be stored and the elements of the array below the diagonal are not referenced.
  • If UPLO='L', the lower triangular part of A must be stored and the elements of the array above the diagonal are not referenced.
On exit: the transformed matrix A.
10:   LDA – INTEGERInput
On entry: the first dimension of the array A as declared in the (sub)program from which F06QMF is called.
Constraint: LDA≥ max 1,N .

6 Error Indicators and Warnings

None.

7 Accuracy

Not applicable.

8 Parallelism and Performance

F06QMF is not threaded in any implementation.

9 Further Comments

None.

10 Example

None.
F06 Chapter Contents
F06 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F06QPF : NAG Library, Mark 26

F06 Chapter Contents
F06 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F06QPF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
10 Example

1 Purpose

F06QPF performs a QR factorization (as a sequence of plane rotations) of a real upper triangular matrix that has been modified by a rank-1 update.

2 Specification

SUBROUTINE F06QPF ( N, ALPHA, X, INCX, Y, INCY, A, LDA, C, S)
INTEGER | N, INCX, INCY, LDA
REAL (KIND=nag_wp) | ALPHA, X(*), Y(*), A(LDA,*), C(N-1), S(N-1)

3 Description

F06QPF performs a QR factorization of an upper triangular matrix which has been modified by a rank-1 update:
αx yT + U=QR
where U and R are n by n real upper triangular matrices, x and y are n-element real vectors, α is a real scalar, and Q is an n by n real orthogonal matrix.
Q is formed as the product of two sequences of plane rotations:
QT = Q n-1 ⋯ Q 2 Q 1 P 1 P 2 ⋯ P n-1
where
  • Pk is a rotation in the k,n plane, chosen to annihilate xk: thus Px=β en, where P=P 1P 2⋯P n-1 and en is the last column of the unit matrix;
  • Qk is a rotation in the k,n plane, chosen to annihilate the n,k element of αβ en yT+PU, and thus restore it to upper triangular form.
The 2 by 2 plane rotation part of Pk or Qk has the form
ck sk -sk ck .
The tangents of the rotations Pk are returned in the array X; the cosines and sines of these rotations can be recovered by calling F06BCF. The cosines and sines of the rotations Qk are returned directly in the arrays C and S.

4 References

None.

5 Arguments

1:   N – INTEGERInput
On entry: n, the order of the matrices U and R.
Constraint: N≥0.
2:   ALPHA – REAL (KIND=nag_wp)Input
On entry: the scalar α.
3:   X* – REAL (KIND=nag_wp) arrayInput/Output
Note: the dimension of the array X must be at least max 1, 1+N-1 ×INCX .
On entry: the n-element vector x. xi must be stored in X 1+i-1×INCX, for i=1,2,…,N.
Intermediate elements of X are not referenced.
On exit: the referenced elements are overwritten by details of the sequence of plane rotations.
4:   INCX – INTEGERInput
On entry: the increment in the subscripts of X between successive elements of x.
Constraint: INCX>0.
5:   Y* – REAL (KIND=nag_wp) arrayInput
Note: the dimension of the array Y must be at least max 1, 1+N-1 ×INCY .
On entry: the n-element vector y. yi must be stored in Y 1+i-1×INCY, for i=1,2,…,N.
Intermediate elements of Y are not referenced.
6:   INCY – INTEGERInput
On entry: the increment in the subscripts of Y between successive elements of y.
Constraint: INCY>0.
7:   A LDA* – REAL (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array A must be at least N.
On entry: the n by n upper triangular matrix U.
On exit: the upper triangular matrix R.
8:   LDA – INTEGERInput
On entry: the first dimension of the array A as declared in the (sub)program from which F06QPF is called.
Constraint: LDA≥ max 1,N .
9:   C N-1 – REAL (KIND=nag_wp) arrayOutput
On exit: the cosines of the rotations Qk, for k=1,2,…,n-1.
10:   S N-1 – REAL (KIND=nag_wp) arrayOutput
On exit: the sines of the rotations Qk, for k=1,2,…,n-1.

6 Error Indicators and Warnings

None.

7 Accuracy

Not applicable.

8 Parallelism and Performance

F06QPF makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

None.

10 Example

None.
F06 Chapter Contents
F06 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F06QQF : NAG Library, Mark 26

F06 Chapter Contents
F06 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F06QQF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
10 Example

1 Purpose

F06QQF performs a QR factorization (as a sequence of plane rotations) of a real upper triangular matrix that has been augmented by a full row.

2 Specification

SUBROUTINE F06QQF ( N, ALPHA, X, INCX, A, LDA, C, S)
INTEGER | N, INCX, LDA
REAL (KIND=nag_wp) | ALPHA, X(*), A(LDA,*), C(N), S(N)

3 Description

F06QQF performs the factorization
U α xT =Q R 0
where U and R are n by n real upper triangular matrices, x is an n-element real vector, α is a real scalar, and Q is a real orthogonal matrix.
Q is formed as a sequence of plane rotations
QT = Qn ⋯ Q 2 Q 1
where Qk is a rotation in the k,n+1 plane, chosen to annihilate xk.
The 2 by 2 plane rotation part of Qk has the form
ck sk -sk ck .

4 References

None.

5 Arguments

1:   N – INTEGERInput
On entry: n, the order of the matrices U and R.
Constraint: N≥0.
2:   ALPHA – REAL (KIND=nag_wp)Input
On entry: the scalar α.
3:   X* – REAL (KIND=nag_wp) arrayInput/Output
Note: the dimension of the array X must be at least max 1, 1+N-1 ×INCX .
On entry: the vector x. xi must be stored in X 1+i–1×INCX , for i=1,2,…,N.
On exit: the referenced elements are overwritten by the tangents of the rotations Qk, for k=1,2,…,n.
4:   INCX – INTEGERInput
On entry: the increment in the subscripts of X between successive elements of x.
Constraint: INCX>0.
5:   A LDA* – REAL (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array A must be at least N.
On entry: the n by n upper triangular matrix U.
On exit: the upper triangular matrix R.
6:   LDA – INTEGERInput
On entry: the first dimension of the array A as declared in the (sub)program from which F06QQF is called.
Constraint: LDA≥ max 1,N .
7:   C N – REAL (KIND=nag_wp) arrayOutput
On exit: the values ck, the cosines of the rotations Qk, for k=1,2,…,n.
8:   S N – REAL (KIND=nag_wp) arrayOutput
On exit: the values sk, the sines of the rotations Qk, for k=1,2,…,n.

6 Error Indicators and Warnings

None.

7 Accuracy

Not applicable.

8 Parallelism and Performance

F06QQF is not threaded in any implementation.

9 Further Comments

None.

10 Example

None.
F06 Chapter Contents
F06 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F06QRF : NAG Library, Mark 26

F06 Chapter Contents
F06 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F06QRF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
10 Example

1 Purpose

F06QRF performs a QR or RQ factorization (as a sequence of plane rotations) of a real upper Hessenberg matrix.

2 Specification

SUBROUTINE F06QRF ( SIDE, N, K1, K2, C, S, A, LDA)
INTEGER | N, K1, K2, LDA
REAL (KIND=nag_wp) | C(K2-1), S(K2-1), A(LDA,*)
CHARACTER(1) | SIDE

3 Description

F06QRF transforms an n by n real upper Hessenberg matrix H to upper triangular form R by applying an orthogonal matrix P from the left or the right. H is assumed to have nonzero subdiagonal elements h k+1,k, for k=k 1,…,k 2-1, only. P is formed as a sequence of plane rotations in planes k 1 to k 2.
If SIDE='L', the rotations are applied from the left:
PH=R ,
where P = P k 2-1 ⋯ P k 1+1 P k 1 .
If SIDE='R', the rotations are applied from the right:
H PT=R ,
where P = P k 1 P k 1+1 ⋯ P k 2-1 .
In either case, Pk is a rotation in the k,k+1 plane, chosen to annihilate h k+1,k.
The 2 by 2 plane rotation part of Pk has the form
ck sk -sk ck .

4 References

None.

5 Arguments

1:   SIDE – CHARACTER(1)Input
On entry: specifies whether H is operated on from the left or the right.
SIDE='L'
H is pre-multiplied from the left.
SIDE='R'
H is post-multiplied from the right.
Constraint: SIDE='L' or 'R'.
2:   N – INTEGERInput
On entry: n, the order of the matrix H.
Constraint: N≥0.
3:   K1 – INTEGERInput
4:   K2 – INTEGERInput
On entry: the values k 1 and k 2.
If K1<1 or K2≤K1 or K2>N, an immediate return is effected.
5:   C K2-1 – REAL (KIND=nag_wp) arrayOutput
On exit: C k holds ck, the cosine of the rotation Pk, for k=k 1,…,k 2-1.
6:   S K2-1 – REAL (KIND=nag_wp) arrayInput/Output
On entry: the nonzero subdiagonal elements of H: S k must hold h k+1,k, for k=k 1,…,k 2-1.
On exit: S k holds sk, the sine of the rotation Pk, for k=k 1,…,k 2-1.
7:   A LDA* – REAL (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array A must be at least N.
On entry: the upper triangular part of the n by n upper Hessenberg matrix H.
On exit: the upper triangular matrix R.
8:   LDA – INTEGERInput
On entry: the first dimension of the array A as declared in the (sub)program from which F06QRF is called.
Constraint: LDA≥ max 1,N .

6 Error Indicators and Warnings

None.

7 Accuracy

Not applicable.

8 Parallelism and Performance

F06QRF is not threaded in any implementation.

9 Further Comments

None.

10 Example

None.
F06 Chapter Contents
F06 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F06QSF : NAG Library, Mark 26

F06 Chapter Contents
F06 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F06QSF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
10 Example

1 Purpose

F06QSF performs a QR or RQ factorization (as a sequence of plane rotations) of a real upper spiked matrix.

2 Specification

SUBROUTINE F06QSF ( SIDE, N, K1, K2, C, S, A, LDA)
INTEGER | N, K1, K2, LDA
REAL (KIND=nag_wp) | C(K2-1), S(*), A(LDA,*)
CHARACTER(1) | SIDE

3 Description

F06QSF transforms an n by n real upper spiked matrix H to upper triangular form R by applying a real orthogonal matrix P from the left or the right. P is formed as a sequence of plane rotations in planes k 1 to k 2.
If SIDE='L', H is assumed to have a row spike, with nonzero elements h k 2,k, for k=k 1,…,k 2-1. The rotations are applied from the left:
PH=R ,
where P = P k 2-1 ⋯ P k 1+1 P k 1 and Pk is a rotation in the k,k 2 plane.
If SIDE='R', H is assumed to have a column spike, with nonzero elements h k+1,k 1, for k=k 1,…,k 2-1. The rotations are applied from the right:
H PT=R ,
where P = P k 1 P k 1+1 ⋯ P k 2-1 and Pk is a rotation in the k 1,k+1 plane.
The 2 by 2 plane rotation part of Pk has the form
ck sk -sk ck .

4 References

None.

5 Arguments

1:   SIDE – CHARACTER(1)Input
On entry: specifies whether H is operated on from the left or the right.
SIDE='L'
H is pre-multiplied from the left.
SIDE='R'
H is post-multiplied from the right.
Constraint: SIDE='L' or 'R'.
2:   N – INTEGERInput
On entry: n, the order of the matrix H.
Constraint: N≥0.
3:   K1 – INTEGERInput
4:   K2 – INTEGERInput
On entry: the values k 1 and k 2.
If K1<1 or K2≤K1 or K2>N, an immediate return is effected.
5:   C K2-1 – REAL (KIND=nag_wp) arrayOutput
On exit: C k holds ck, the cosine of the rotation Pk, for k=k 1,…,k 2-1.
6:   S* – REAL (KIND=nag_wp) arrayInput/Output
Note: the dimension of the array S must be at least K2-K1.
On entry: the nonzero elements of the spike of H: S k must hold h k 2,k if SIDE='L', and h k+1,k 1 if SIDE='R', for k=k 1,…,k 2-1.
On exit: S k holds sk, the sine of the rotation Pk, for k=k 1,…,k 2-1.
7:   A LDA* – REAL (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array A must be at least N.
On entry: the upper triangular part of the n by n upper spiked matrix H.
On exit: the upper triangular matrix R.
8:   LDA – INTEGERInput
On entry: the first dimension of the array A as declared in the (sub)program from which F06QSF is called.
Constraint: LDA≥ max 1,N .

6 Error Indicators and Warnings

None.

7 Accuracy

Not applicable.

8 Parallelism and Performance

F06QSF is not threaded in any implementation.

9 Further Comments

None.

10 Example

None.
F06 Chapter Contents
F06 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F06QTF : NAG Library, Mark 26

F06 Chapter Contents
F06 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F06QTF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
10 Example

1 Purpose

F06QTF performs a QR or RQ factorization of the product of a real upper triangular matrix and a real matrix of plane rotations.

2 Specification

SUBROUTINE F06QTF ( SIDE, N, K1, K2, C, S, A, LDA)
INTEGER | N, K1, K2, LDA
REAL (KIND=nag_wp) | C(*), S(*), A(LDA,*)
CHARACTER(1) | SIDE

3 Description

F06QTF performs one of the transformations
R←PU QT   or   R←QU PT ,
where U is a given n by n real upper triangular matrix, P is a given real orthogonal matrix, and Q is a real orthogonal matrix chosen to make R upper triangular. Both P and Q are represented as sequences of plane rotations in planes k 1 to k 2.
If SIDE='L',
R←PU QT ,
where P= P k 2-1 … P k 1+1 P k 1 and Q= Q k 2-1 … Q k 1+1 Q k 1 .
If SIDE='R',
R←QU PT ,
where P=P k 1 P k 1+1 … P k 2-1 and Q= Q k 1 Q k 1+1 … Q k 2-1 .
In either case Pk and Qk are rotations in the k,k+1 plane.
The 2 by 2 rotation part of Pk or Qk has the form
ck sk -sk ck .

4 References

None.

5 Arguments

1:   SIDE – CHARACTER(1)Input
On entry: specifies whether P is applied from the left or the right in the transformation.
SIDE='L'
P is applied from the left.
SIDE='R'
P is applied from the right.
Constraint: SIDE='L' or 'R'.
2:   N – INTEGERInput
On entry: n, the order of the matrices U and R.
Constraint: N≥0.
3:   K1 – INTEGERInput
4:   K2 – INTEGERInput
On entry: the values k 1 and k 2.
If K1<1 or K2≤K1 or K2>N, an immediate return is effected.
5:   C* – REAL (KIND=nag_wp) arrayInput/Output
Note: the dimension of the array C must be at least K2-K1.
On entry: C k must hold the cosine of the rotation Pk, for k=k 1,…,k 2-1.
On exit: C k holds the cosine of the rotation Qk, for k=k 1,…,k 2-1.
6:   S* – REAL (KIND=nag_wp) arrayInput/Output
Note: the dimension of the array S must be at least K2-K1.
On entry: S k must hold the sine of the rotation Pk, for k=k 1,…,k 2-1.
On exit: S k holds the sine of the rotation Qk, for k=k 1,…,k 2-1.
7:   A LDA* – REAL (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array A must be at least N.
On entry: the n by n upper triangular matrix U.
On exit: the upper triangular matrix R.
8:   LDA – INTEGERInput
On entry: the first dimension of the array A as declared in the (sub)program from which F06QTF is called.
Constraint: LDA≥ max 1,N .

6 Error Indicators and Warnings

None.

7 Accuracy

Not applicable.

8 Parallelism and Performance

F06QTF is not threaded in any implementation.

9 Further Comments

None.

10 Example

None.
F06 Chapter Contents
F06 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F06QVF : NAG Library, Mark 26

F06 Chapter Contents
F06 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F06QVF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
10 Example

1 Purpose

F06QVF transforms a real upper triangular matrix to an upper Hessenberg matrix by applying a given sequence of plane rotations.

2 Specification

SUBROUTINE F06QVF ( SIDE, N, K1, K2, C, S, A, LDA)
INTEGER | N, K1, K2, LDA
REAL (KIND=nag_wp) | C(*), S(*), A(LDA,*)
CHARACTER(1) | SIDE

3 Description

F06QVF transforms an n by n real upper triangular matrix U to an upper Hessenberg matrix H, by applying a given sequence of plane rotations from either the left or the right, in planes k 1 to k 2; H has nonzero subdiagonal elements h k+1,k, for k=k 1,…,k 2-1 only.
If SIDE='L', the rotations are applied from the left:
H=PU ,
where P = P k 1 P k 1+1 ⋯ P k 2-1 .
If SIDE='R', the rotations are applied from the right:
H = U PT ,
where P = P k 2-1 ⋯ P k 1+1 P k 1 .
In either case, Pk is a rotation in the k,k+1 plane.
The 2 by 2 plane rotation part of Pk has the form
ck sk -sk ck .

4 References

None.

5 Arguments

1:   SIDE – CHARACTER(1)Input
On entry: specifies whether U is operated on from the left or the right.
SIDE='L'
U is pre-multiplied from the left.
SIDE='R'
U is post-multiplied from the right.
Constraint: SIDE='L' or 'R'.
2:   N – INTEGERInput
On entry: n, the order of the matrices U and H.
Constraint: N≥0.
3:   K1 – INTEGERInput
4:   K2 – INTEGERInput
On entry: the values k 1 and k 2.
If K1<1 or K2≤K1 or K2>N, an immediate return is effected.
5:   C* – REAL (KIND=nag_wp) arrayInput
Note: the dimension of the array C must be at least K2-K1.
On entry: C k must hold ck, the cosine of the rotation Pk, for k=k 1,…,k 2-1.
6:   S* – REAL (KIND=nag_wp) arrayInput/Output
Note: the dimension of the array S must be at least K2-K1.
On entry: S k must hold sk, the sine of the rotation Pk, for k=k 1,…,k 2-1.
On exit: S k holds h k+1,k, the subdiagonal element of H, for k=k 1,…,k 2-1.
7:   A LDA* – REAL (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array A must be at least N.
On entry: the n by n upper triangular matrix U.
On exit: the upper triangular part of the upper Hessenberg matrix H.
8:   LDA – INTEGERInput
On entry: the first dimension of the array A as declared in the (sub)program from which F06QVF is called.
Constraint: LDA≥ max 1,N .

6 Error Indicators and Warnings

None.

7 Accuracy

Not applicable.

8 Parallelism and Performance

F06QVF is not threaded in any implementation.

9 Further Comments

None.

10 Example

None.
F06 Chapter Contents
F06 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F06QWF : NAG Library, Mark 26

F06 Chapter Contents
F06 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F06QWF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
10 Example

1 Purpose

F06QWF transforms a real upper triangular matrix to an upper spiked matrix by applying a given sequence of plane rotations.

2 Specification

SUBROUTINE F06QWF ( SIDE, N, K1, K2, C, S, A, LDA)
INTEGER | N, K1, K2, LDA
REAL (KIND=nag_wp) | C(*), S(*), A(LDA,*)
CHARACTER(1) | SIDE

3 Description

F06QWF transforms an n by n real upper triangular matrix U to an upper spiked matrix H, by applying a given sequence of plane rotations from either the left or the right, in planes k 1 to k 2.
If SIDE='L', H has a row spike, with nonzero elements h k 2,k , for k = k 1 , k 1+1, …, k 2-1 . The rotations are applied from the left:
H=PU ,
where P = P k 1 P k 1+1 ⋯ P k 2-1 and Pk is a rotation in the k,k 2 plane.
If SIDE='R', H has a column spike, with nonzero elements h k+1, k 1 , for k= k 1, k 1+1, …, k 2-1 . The rotations are applied from the right:
H PT = R ,
where P = P k 2-1 ⋯ P k 1+1 P k 1 and Pk is a rotation in the k 1,k+1 plane.
The 2 by 2 plane rotation part of Pk has the form
ck sk -sk ck .

4 References

None.

5 Arguments

1:   SIDE – CHARACTER(1)Input
On entry: specifies whether U is operated on from the left or the right.
SIDE='L'
U is pre-multiplied from the left.
SIDE='R'
U is post-multiplied from the right.
Constraint: SIDE='L' or 'R'.
2:   N – INTEGERInput
On entry: n, the order of the matrices U and H.
Constraint: N≥0.
3:   K1 – INTEGERInput
4:   K2 – INTEGERInput
On entry: the values k 1 and k 2.
If K1<1 or K2≤K1 or K2>N, an immediate return is effected.
5:   C* – REAL (KIND=nag_wp) arrayInput
Note: the dimension of the array C must be at least K2-K1.
On entry: C k must hold ck, the cosine of the rotation Pk, for k=k 1,…,k 2-1.
6:   S* – REAL (KIND=nag_wp) arrayInput/Output
Note: the dimension of the array S must be at least K2-K1.
On entry: S k must hold sk, the sine of the rotation Pk, for k=k 1,…,k 2-1.
On exit: S k holds a nonzero element of the spike of H: h k 2,k if SIDE='L', or h k+1,k 1 if SIDE='R', for k=k 1,…,k 2-1.
7:   A LDA* – REAL (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array A must be at least N.
On entry: the n by n upper triangular matrix U.
On exit: the upper triangular part of the upper spiked matrix H.
8:   LDA – INTEGERInput
On entry: the first dimension of the array A as declared in the (sub)program from which F06QWF is called.
Constraint: LDA≥ max 1,N .

6 Error Indicators and Warnings

None.

7 Accuracy

Not applicable.

8 Parallelism and Performance

F06QWF is not threaded in any implementation.

9 Further Comments

None.

10 Example

None.
F06 Chapter Contents
F06 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F06QXF : NAG Library, Mark 26

F06 Chapter Contents
F06 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F06QXF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
10 Example

1 Purpose

F06QXF applies a sequence of plane rotations to a real rectangular matrix.

2 Specification

SUBROUTINE F06QXF ( SIDE, PIVOT, DIRECT, M, N, K1, K2, C, S, A, LDA)
INTEGER | M, N, K1, K2, LDA
REAL (KIND=nag_wp) | C(K2-1), S(K2-1), A(LDA,*)
CHARACTER(1) | SIDE, PIVOT, DIRECT

3 Description

F06QXF performs the transformation
A←PA   or   A←A PT ,
where A is an m by n real matrix and P is a real orthogonal matrix, defined as a sequence of plane rotations, Pk, applied in planes k 1 to k 2.
The 2 by 2 plane rotation part of Pk is assumed to have the form
ck sk -sk ck .

4 References

None.

5 Arguments

1:   SIDE – CHARACTER(1)Input
On entry: specifies whether A is operated on from the left or the right.
SIDE='L'
A is pre-multiplied from the left.
SIDE='R'
A is post-multiplied from the right.
Constraint: SIDE='L' or 'R'.
2:   PIVOT – CHARACTER(1)Input
On entry: specifies the plane rotated by Pk.
PIVOT='V' (variable pivot)
Pk rotates the k,k+1 plane.
PIVOT='T' (top pivot)
Pk rotates the k 1,k+1 plane.
PIVOT='B' (bottom pivot)
Pk rotates the k,k 2 plane.
Constraint: PIVOT='V', 'T' or 'B'.
3:   DIRECT – CHARACTER(1)Input
On entry: specifies the sequence direction.
DIRECT='F' (forward sequence)
P=P k 2-1⋯P k 1+1P k 1.
DIRECT='B' (backward sequence)
P=P k 1P k 1+1⋯P k 2-1.
Constraint: DIRECT='F' or 'B'.
4:   M – INTEGERInput
On entry: m, the number of rows of the matrix A.
If M<1, an immediate return is effected.
Constraint: M≥0.
5:   N – INTEGERInput
On entry: n, the number of columns of the matrix A.
If N<1, an immediate return is effected.
Constraint: N≥0.
6:   K1 – INTEGERInput
7:   K2 – INTEGERInput
On entry: the values k 1 and k 2.
If K1<1 or K2≤K1, or SIDE='L' and K2>M, or SIDE='R' and K2>N, an immediate return is effected.
8:   C K2-1 – REAL (KIND=nag_wp) arrayInput
On entry: C k must hold ck, the cosine of the rotation Pk, for k=k 1,…,k 2-1.
9:   S K2-1 – REAL (KIND=nag_wp) arrayInput
On entry: S k must hold sk, the sine of the rotation Pk, for k=k 1,…,k 2-1.
10:   A LDA* – REAL (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array A must be at least N.
On entry: the m by n matrix A.
On exit: the transformed matrix A.
11:   LDA – INTEGERInput
On entry: the first dimension of the array A as declared in the (sub)program from which F06QXF is called.
Constraint: LDA≥ max 1,M .

6 Error Indicators and Warnings

None.

7 Accuracy

Not applicable.

8 Parallelism and Performance

F06QXF is not threaded in any implementation.

9 Further Comments

None.

10 Example

None.
F06 Chapter Contents
F06 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F06RAF : NAG Library, Mark 26

F06 Chapter Contents
F06 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F06RAF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
10 Example

1 Purpose

F06RAF returns, via the function name, the value of the 1-norm, the ∞-norm, the Frobenius norm, or the maximum absolute value of the elements of a real m by n matrix.

2 Specification

FUNCTION F06RAF ( NORM, M, N, A, LDA, WORK)
REAL (KIND=nag_wp) F06RAF
INTEGER | M, N, LDA
REAL (KIND=nag_wp) | A(LDA,*), WORK(*)
CHARACTER(1) | NORM

3 Description

None.

4 References

None.

5 Arguments

1:   NORM – CHARACTER(1)Input
On entry: specifies the value to be returned.
NORM='1' or 'O'
The 1-norm.
NORM='I'
The ∞-norm.
NORM='F' or 'E'
The Frobenius (or Euclidean) norm.
NORM='M'
The value max i,j a ij (not a norm).
Constraint: NORM='1', 'O', 'I', 'F', 'E' or 'M'.
2:   M – INTEGERInput
On entry: m, the number of rows of the matrix A.
When M=0, F06RAF is set to zero.
Constraint: M≥0.
3:   N – INTEGERInput
On entry: n, the number of columns of the matrix A.
When N=0, F06RAF is set to zero.
Constraint: N≥0.
4:   A LDA* – REAL (KIND=nag_wp) arrayInput
Note: the second dimension of the array A must be at least N.
On entry: the m by n matrix A.
5:   LDA – INTEGERInput
On entry: the first dimension of the array A as declared in the (sub)program from which F06RAF is called.
Constraint: LDA≥ max 1,M .
6:   WORK* – REAL (KIND=nag_wp) arrayWorkspace
Note: the dimension of the array WORK must be at least max 1,M if NORM='I', and at least 1 otherwise.

6 Error Indicators and Warnings

None.

7 Accuracy

Not applicable.

8 Parallelism and Performance

F06RAF is not threaded in any implementation.

9 Further Comments

None.

10 Example

None.
F06 Chapter Contents
F06 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F06RBF : NAG Library, Mark 26

F06 Chapter Contents
F06 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F06RBF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
10 Example

1 Purpose

F06RBF returns, via the function name, the value of the 1-norm, the ∞-norm, the Frobenius norm, or the maximum absolute value of the elements of a real n by n band matrix.

2 Specification

FUNCTION F06RBF ( NORM, N, KL, KU, AB, LDAB, WORK)
REAL (KIND=nag_wp) F06RBF
INTEGER | N, KL, KU, LDAB
REAL (KIND=nag_wp) | AB(LDAB,*), WORK(*)
CHARACTER(1) | NORM

3 Description

None.

4 References

None.

5 Arguments

1:   NORM – CHARACTER(1)Input
On entry: specifies the value to be returned.
NORM='1' or 'O'
The 1-norm.
NORM='I'
The ∞-norm.
NORM='F' or 'E'
The Frobenius (or Euclidean) norm.
NORM='M'
The value max i,j a ij (not a norm).
Constraint: NORM='1', 'O', 'I', 'F', 'E' or 'M'.
2:   N – INTEGERInput
On entry: n, the order of the matrix A.
When N=0, F06RBF returns zero.
Constraint: N≥0.
3:   KL – INTEGERInput
On entry: kl, the number of subdiagonals within the band of A.
Constraint: KL≥0.
4:   KU – INTEGERInput
On entry: ku, the number of superdiagonals within the band of A.
Constraint: KU≥0.
5:   AB LDAB* – REAL (KIND=nag_wp) arrayInput
Note: the second dimension of the array AB must be at least N.
On entry: the n by n band matrix A.
The matrix is stored in rows 1 to kl+ku+1, more precisely, the element A ij must be stored in
AB ku+1+i-j j  for ​max 1,j-ku≤i≤min n,j+kl.
6:   LDAB – INTEGERInput
On entry: the first dimension of the array AB as declared in the (sub)program from which F06RBF is called.
Constraint: LDAB≥KL+KU+1.
7:   WORK* – REAL (KIND=nag_wp) arrayWorkspace
Note: the dimension of the array WORK must be at least max 1,N if NORM='I', and at least 1 otherwise.

6 Error Indicators and Warnings

None.

7 Accuracy

Not applicable.

8 Parallelism and Performance

F06RBF is not threaded in any implementation.

9 Further Comments

None.

10 Example

None.
F06 Chapter Contents
F06 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F06RCF : NAG Library, Mark 26

F06 Chapter Contents
F06 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F06RCF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
10 Example

1 Purpose

F06RCF returns, via the function name, the value of the 1-norm, the ∞-norm, the Frobenius norm, or the maximum absolute value of the elements of a real n by n symmetric matrix.

2 Specification

FUNCTION F06RCF ( NORM, UPLO, N, A, LDA, WORK)
REAL (KIND=nag_wp) F06RCF
INTEGER | N, LDA
REAL (KIND=nag_wp) | A(LDA,*), WORK(*)
CHARACTER(1) | NORM, UPLO

3 Description

None.

4 References

None.

5 Arguments

1:   NORM – CHARACTER(1)Input
On entry: specifies the value to be returned.
NORM='1' or 'O'
The 1-norm.
NORM='I'
The ∞-norm (= the 1-norm for a symmetric matrix).
NORM='F' or 'E'
The Frobenius (or Euclidean) norm.
NORM='M'
The value max i,j a ij (not a norm).
Constraint: NORM='1', 'O', 'I', 'F', 'E' or 'M'.
2:   UPLO – CHARACTER(1)Input
On entry: specifies whether the upper or lower triangular part of A is stored.
UPLO='U'
The upper triangular part of A is stored.
UPLO='L'
The lower triangular part of A is stored.
Constraint: UPLO='U' or 'L'.
3:   N – INTEGERInput
On entry: n, the order of the matrix A.
When N=0, F06RCF returns zero.
Constraint: N≥0.
4:   A LDA* – REAL (KIND=nag_wp) arrayInput
Note: the second dimension of the array A must be at least max 1,N.
On entry: the n by n symmetric matrix A.
  • If UPLO='U', the upper triangular part of A must be stored and the elements of the array below the diagonal are not referenced.
  • If UPLO='L', the lower triangular part of A must be stored and the elements of the array above the diagonal are not referenced.
5:   LDA – INTEGERInput
On entry: the first dimension of the array A as declared in the (sub)program from which F06RCF is called.
Constraint: LDA≥ max 1,N .
6:   WORK* – REAL (KIND=nag_wp) arrayWorkspace
Note: the dimension of the array WORK must be at least max 1,N if NORM='1', 'O' or 'I', and at least 1 otherwise.

6 Error Indicators and Warnings

None.

7 Accuracy

Not applicable.

8 Parallelism and Performance

F06RCF is not threaded in any implementation.

9 Further Comments

None.

10 Example

None.
F06 Chapter Contents
F06 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F06RDF : NAG Library, Mark 26

F06 Chapter Contents
F06 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F06RDF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
10 Example

1 Purpose

F06RDF returns, via the function name, the value of the 1-norm, the ∞-norm, the Frobenius norm, or the maximum absolute value of the elements of a real n by n symmetric matrix, stored in packed form.

2 Specification

FUNCTION F06RDF ( NORM, UPLO, N, AP, WORK)
REAL (KIND=nag_wp) F06RDF
INTEGER | N
REAL (KIND=nag_wp) | AP(*), WORK(*)
CHARACTER(1) | NORM, UPLO

3 Description

None.

4 References

None.

5 Arguments

1:   NORM – CHARACTER(1)Input
On entry: specifies the value to be returned.
NORM='1' or 'O'
The 1-norm.
NORM='I'
The ∞-norm (= the 1-norm for a symmetric matrix).
NORM='F' or 'E'
The Frobenius (or Euclidean) norm.
NORM='M'
The value max i,j a ij (not a norm).
Constraint: NORM='1', 'O', 'I', 'F', 'E' or 'M'.
2:   UPLO – CHARACTER(1)Input
On entry: specifies whether the upper or lower triangular part of A is stored.
UPLO='U'
The upper triangular part of A is stored.
UPLO='L'
The lower triangular part of A is stored.
Constraint: UPLO='U' or 'L'.
3:   N – INTEGERInput
On entry: n, the order of the matrix A.
When N=0, F06RDF returns zero.
Constraint: N≥0.
4:   AP* – REAL (KIND=nag_wp) arrayInput
Note: the dimension of the array AP must be at least N× N+1/2 .
On entry: the n by n symmetric matrix A, packed by columns.
More precisely,
  • if UPLO='U', the upper triangle of A must be stored with element A ij in AP i+j j-1/2 for i≤j;
  • if UPLO='L', the lower triangle of A must be stored with element A ij in AP i+2 n-jj-1/2 for i≥j.
5:   WORK* – REAL (KIND=nag_wp) arrayWorkspace
Note: the dimension of the array WORK must be at least max 1,N if NORM='1', 'O' or 'I', and at least 1 otherwise.

6 Error Indicators and Warnings

None.

7 Accuracy

Not applicable.

8 Parallelism and Performance

F06RDF is not threaded in any implementation.

9 Further Comments

None.

10 Example

None.
F06 Chapter Contents
F06 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F06REF : NAG Library, Mark 26

F06 Chapter Contents
F06 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F06REF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
10 Example

1 Purpose

F06REF returns, via the function name, the value of the 1-norm, the ∞-norm, the Frobenius norm, or the maximum absolute value of the elements of a real n by n symmetric band matrix.

2 Specification

FUNCTION F06REF ( NORM, UPLO, N, K, AB, LDAB, WORK)
REAL (KIND=nag_wp) F06REF
INTEGER | N, K, LDAB
REAL (KIND=nag_wp) | AB(LDAB,*), WORK(*)
CHARACTER(1) | NORM, UPLO

3 Description

None.

4 References

None.

5 Arguments

1:   NORM – CHARACTER(1)Input
On entry: specifies the value to be returned.
NORM='1' or 'O'
The 1-norm.
NORM='I'
The ∞-norm (= the 1-norm for a symmetric matrix).
NORM='F' or 'E'
The Frobenius (or Euclidean) norm.
NORM='M'
The value max i,j a ij (not a norm).
Constraint: NORM='1', 'O', 'I', 'F', 'E' or 'M'.
2:   UPLO – CHARACTER(1)Input
On entry: specifies whether the upper or lower triangular part of A is stored.
UPLO='U'
The upper triangular part of A is stored.
UPLO='L'
The lower triangular part of A is stored.
Constraint: UPLO='U' or 'L'.
3:   N – INTEGERInput
On entry: n, the order of the matrix A.
When N=0, F06REF returns zero.
Constraint: N≥0.
4:   K – INTEGERInput
On entry: k, the number of subdiagonals or superdiagonals of the matrix A.
Constraint: K≥0.
5:   AB LDAB* – REAL (KIND=nag_wp) arrayInput
Note: the second dimension of the array AB must be at least N.
On entry: the n by n symmetric band matrix A.
The matrix is stored in rows 1 to k+1, more precisely,
  • if UPLO='U', the elements of the upper triangle of A within the band must be stored with element A ij in AB k+1+i-j j​ for ​max 1,j-k≤i≤j;
  • if UPLO='L', the elements of the lower triangle of A within the band must be stored with element A ij in AB 1+i-j j​ for ​j≤i≤min n,j+k.
6:   LDAB – INTEGERInput
On entry: the first dimension of the array AB as declared in the (sub)program from which F06REF is called.
Constraint: LDAB≥K+1.
7:   WORK* – REAL (KIND=nag_wp) arrayWorkspace
Note: the dimension of the array WORK must be at least max 1,N if NORM='1', 'O' or 'I', and at least 1 otherwise.

6 Error Indicators and Warnings

None.

7 Accuracy

Not applicable.

8 Parallelism and Performance

F06REF is not threaded in any implementation.

9 Further Comments

None.

10 Example

None.
F06 Chapter Contents
F06 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F06RJF : NAG Library, Mark 26

F06 Chapter Contents
F06 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F06RJF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
10 Example

1 Purpose

F06RJF returns, via the function name, the value of the 1-norm, the ∞-norm, the Frobenius norm, or the maximum absolute value of the elements of a real m by n trapezoidal matrix (triangular if m=n).

2 Specification

FUNCTION F06RJF ( NORM, UPLO, DIAG, M, N, A, LDA, WORK)
REAL (KIND=nag_wp) F06RJF
INTEGER | M, N, LDA
REAL (KIND=nag_wp) | A(LDA,*), WORK(*)
CHARACTER(1) | NORM, UPLO, DIAG

3 Description

None.

4 References

None.

5 Arguments

1:   NORM – CHARACTER(1)Input
On entry: specifies the value to be returned.
NORM='1' or 'O'
The 1-norm.
NORM='I'
The ∞-norm.
NORM='F' or 'E'
The Frobenius (or Euclidean) norm.
NORM='M'
The value max i,j a ij (not a norm).
Constraint: NORM='1', 'O', 'I', 'F', 'E' or 'M'.
2:   UPLO – CHARACTER(1)Input
On entry: specifies whether A is upper or lower trapezoidal.
UPLO='U'
A is upper trapezoidal.
UPLO='L'
A is lower trapezoidal.
Constraint: UPLO='U' or 'L'.
3:   DIAG – CHARACTER(1)Input
On entry: specifies whether A has nonunit or unit diagonal elements.
DIAG='N'
The diagonal elements are stored explicitly.
DIAG='U'
The diagonal elements are assumed to be 1, and are not referenced.
Constraint: DIAG='N' or 'U'.
4:   M – INTEGERInput
On entry: m, the number of rows of the matrix A.
When M=0, F06RJF is set to zero.
Constraint: M≥0.
5:   N – INTEGERInput
On entry: n, the number of columns of the matrix A.
When N=0, F06RJF is set to zero.
Constraint: N≥0.
6:   A LDA* – REAL (KIND=nag_wp) arrayInput
Note: the second dimension of the array A must be at least N.
On entry: the m by n trapezoidal matrix A.
  • If UPLO='U', A is upper trapezoidal and the elements of the array below the diagonal are not referenced.
  • If UPLO='L', A is lower trapezoidal and the elements of the array above the diagonal are not referenced.
  • If DIAG='U', the diagonal elements of A are assumed to be 1, and are not referenced.
7:   LDA – INTEGERInput
On entry: the first dimension of the array A as declared in the (sub)program from which F06RJF is called.
Constraint: LDA≥ max 1,M .
8:   WORK* – REAL (KIND=nag_wp) arrayWorkspace
Note: the dimension of the array WORK must be at least max 1,M if NORM='I', and at least 1 otherwise.

6 Error Indicators and Warnings

None.

7 Accuracy

Not applicable.

8 Parallelism and Performance

F06RJF is not threaded in any implementation.

9 Further Comments

None.

10 Example

None.
F06 Chapter Contents
F06 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F06RKF : NAG Library, Mark 26

F06 Chapter Contents
F06 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F06RKF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
10 Example

1 Purpose

F06RKF returns, via the function name, the value of the 1-norm, the ∞-norm, the Frobenius norm, or the maximum absolute value of the elements of a real n by n triangular matrix, stored in packed form.

2 Specification

FUNCTION F06RKF ( NORM, UPLO, DIAG, N, AP, WORK)
REAL (KIND=nag_wp) F06RKF
INTEGER | N
REAL (KIND=nag_wp) | AP(*), WORK(*)
CHARACTER(1) | NORM, UPLO, DIAG

3 Description

None.

4 References

None.

5 Arguments

1:   NORM – CHARACTER(1)Input
On entry: specifies the value to be returned.
NORM='1' or 'O'
The 1-norm.
NORM='I'
The ∞-norm.
NORM='F' or 'E'
The Frobenius (or Euclidean) norm.
NORM='M'
The value max i,j a ij (not a norm).
Constraint: NORM='1', 'O', 'I', 'F', 'E' or 'M'.
2:   UPLO – CHARACTER(1)Input
On entry: specifies whether A is upper or lower triangular.
UPLO='U'
A is upper triangular.
UPLO='L'
A is lower triangular.
Constraint: UPLO='U' or 'L'.
3:   DIAG – CHARACTER(1)Input
On entry: specifies whether A has nonunit or unit diagonal elements.
DIAG='N'
The diagonal elements are stored explicitly.
DIAG='U'
The diagonal elements are assumed to be 1, and are not referenced.
Constraint: DIAG='N' or 'U'.
4:   N – INTEGERInput
On entry: n, the order of the matrix A.
When N=0, F06RKF returns zero.
Constraint: N≥0.
5:   AP* – REAL (KIND=nag_wp) arrayInput
Note: the dimension of the array AP must be at least N× N+1/2 .
On entry: the n by n triangular matrix A, packed by columns.
More precisely,
  • if UPLO='U', the upper triangle of A must be stored with element A ij in AP i+j j-1/2 for i≤j;
  • if UPLO='L', the lower triangle of A must be stored with element A ij in AP i+2 n-jj-1/2 for i≥j.
If DIAG='U', the diagonal elements of A are assumed to be 1, and are not referenced; the same storage scheme is used whether DIAG='N' or ‘U’.
6:   WORK* – REAL (KIND=nag_wp) arrayWorkspace
Note: the dimension of the array WORK must be at least max 1,N if NORM='I', and at least 1 otherwise.

6 Error Indicators and Warnings

None.

7 Accuracy

Not applicable.

8 Parallelism and Performance

F06RKF is not threaded in any implementation.

9 Further Comments

None.

10 Example

None.
F06 Chapter Contents
F06 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F06RLF : NAG Library, Mark 26

F06 Chapter Contents
F06 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F06RLF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
10 Example

1 Purpose

F06RLF returns, via the function name, the value of the 1-norm, the ∞-norm, the Frobenius norm, or the maximum absolute value of the elements of a real n by n triangular band matrix.

2 Specification

FUNCTION F06RLF ( NORM, UPLO, DIAG, N, K, AB, LDAB, WORK)
REAL (KIND=nag_wp) F06RLF
INTEGER | N, K, LDAB
REAL (KIND=nag_wp) | AB(LDAB,*), WORK(*)
CHARACTER(1) | NORM, UPLO, DIAG

3 Description

None.

4 References

None.

5 Arguments

1:   NORM – CHARACTER(1)Input
On entry: specifies the value to be returned.
NORM='1' or 'O'
The 1-norm.
NORM='I'
The ∞-norm.
NORM='F' or 'E'
The Frobenius (or Euclidean) norm.
NORM='M'
The value max i,j a ij (not a norm).
Constraint: NORM='1', 'O', 'I', 'F', 'E' or 'M'.
2:   UPLO – CHARACTER(1)Input
On entry: specifies whether A is upper or lower triangular.
UPLO='U'
A is upper triangular.
UPLO='L'
A is lower triangular.
Constraint: UPLO='U' or 'L'.
3:   DIAG – CHARACTER(1)Input
On entry: specifies whether A has nonunit or unit diagonal elements.
DIAG='N'
The diagonal elements are stored explicitly.
DIAG='U'
The diagonal elements are assumed to be 1, and are not referenced.
Constraint: DIAG='N' or 'U'.
4:   N – INTEGERInput
On entry: n, the order of the matrix A.
When N=0, F06RLF returns zero.
Constraint: N≥0.
5:   K – INTEGERInput
On entry: k, the number of subdiagonals or superdiagonals of the matrix A.
Constraint: K≥0.
6:   AB LDAB* – REAL (KIND=nag_wp) arrayInput
Note: the second dimension of the array AB must be at least N.
On entry: the n by n triangular band matrix A
The matrix is stored in rows 1 to k+1, more precisely,
  • if UPLO='U', the elements of the upper triangle of A within the band must be stored with element A ij in AB k+1+i-j j​ for ​max 1,j-k≤i≤j;
  • if UPLO='L', the elements of the lower triangle of A within the band must be stored with element A ij in AB 1+i-j j​ for ​j≤i≤min n,j+k.
If DIAG='U', the diagonal elements of A are assumed to be 1, and are not referenced.
7:   LDAB – INTEGERInput
On entry: the first dimension of the array AB as declared in the (sub)program from which F06RLF is called.
Constraint: LDAB≥K+1.
8:   WORK* – REAL (KIND=nag_wp) arrayWorkspace
Note: the dimension of the array WORK must be at least max 1,N if NORM='I', and at least 1 otherwise.

6 Error Indicators and Warnings

None.

7 Accuracy

Not applicable.

8 Parallelism and Performance

F06RLF is not threaded in any implementation.

9 Further Comments

None.

10 Example

None.
F06 Chapter Contents
F06 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F06RMF : NAG Library, Mark 26

F06 Chapter Contents
F06 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F06RMF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
10 Example

1 Purpose

F06RMF returns, via the function name, the value of the 1-norm, the ∞-norm, the Frobenius norm, or the maximum absolute value of the elements of a real n by n upper Hessenberg matrix.

2 Specification

FUNCTION F06RMF ( NORM, N, A, LDA, WORK)
REAL (KIND=nag_wp) F06RMF
INTEGER | N, LDA
REAL (KIND=nag_wp) | A(LDA,*), WORK(*)
CHARACTER(1) | NORM

3 Description

None.

4 References

None.

5 Arguments

1:   NORM – CHARACTER(1)Input
On entry: specifies the value to be returned.
NORM='1' or 'O'
The 1-norm.
NORM='I'
The ∞-norm.
NORM='F' or 'E'
The Frobenius (or Euclidean) norm.
NORM='M'
The value max i,j a ij (not a norm).
Constraint: NORM='1', 'O', 'I', 'F', 'E' or 'M'.
2:   N – INTEGERInput
On entry: n, the order of the matrix A.
When N=0, F06RMF returns zero.
Constraint: N≥0.
3:   A LDA* – REAL (KIND=nag_wp) arrayInput
Note: the second dimension of the array A must be at least N.
On entry: the n by n upper Hessenberg matrix A; elements of the array below the first subdiagonal are not referenced.
4:   LDA – INTEGERInput
On entry: the first dimension of the array A as declared in the (sub)program from which F06RMF is called.
Constraint: LDA≥ max 1,N .
5:   WORK* – REAL (KIND=nag_wp) arrayWorkspace
Note: the dimension of the array WORK must be at least max 1,N if NORM='I', and at least 1 otherwise.

6 Error Indicators and Warnings

None.

7 Accuracy

Not applicable.

8 Parallelism and Performance

F06RMF is not threaded in any implementation.

9 Further Comments

None.

10 Example

None.
F06 Chapter Contents
F06 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F06RNF : NAG Library, Mark 26

F06 Chapter Contents
F06 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F06RNF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
10 Example

1 Purpose

F06RNF returns, via the function name, the value of the 1-norm, the ∞-norm, the Frobenius norm, or the maximum absolute value of the elements of a real n by n tridiagonal matrix A.

2 Specification

FUNCTION F06RNF ( NORM, N, DL, D, DU)
REAL (KIND=nag_wp) F06RNF
INTEGER | N
REAL (KIND=nag_wp) | DL(*), D(*), DU(*)
CHARACTER(1) | NORM

3 Description

None.

4 References

None.

5 Arguments

1:   NORM – CHARACTER(1)Input
On entry: specifies the value to be returned.
NORM='1' or 'O'
The 1-norm.
NORM='I'
The ∞-norm.
NORM='F' or 'E'
The Frobenius (or Euclidean) norm.
NORM='M'
The value max i,j a ij (not a norm).
Constraint: NORM='1', 'O', 'I', 'F', 'E' or 'M'.
2:   N – INTEGERInput
On entry: n, the order of the matrix A.
When N=0, F06RNF returns zero.
Constraint: N≥0.
3:   DL* – REAL (KIND=nag_wp) arrayInput
Note: the dimension of the array DL must be at least max 1,N-1 .
On entry: the (n-1) subdiagonal elements of A.
4:   D* – REAL (KIND=nag_wp) arrayInput
Note: the dimension of the array D must be at least max 1,N.
On entry: the n diagonal elements of A.
5:   DU* – REAL (KIND=nag_wp) arrayInput
Note: the dimension of the array DU must be at least max 1,N-1 .
On entry: the (n-1) superdiagonal elements of A.

6 Error Indicators and Warnings

None.

7 Accuracy

Not applicable.

8 Parallelism and Performance

F06RNF is not threaded in any implementation.

9 Further Comments

None.

10 Example

None.
F06 Chapter Contents
F06 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F06RPF : NAG Library, Mark 26

F06 Chapter Contents
F06 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F06RPF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
10 Example

1 Purpose

F06RPF returns, via the function name, the value of the 1-norm, the ∞-norm, the Frobenius norm, or the maximum absolute value of the elements of a real n by n symmetric tridiagonal matrix A.

2 Specification

FUNCTION F06RPF ( NORM, N, D, E)
REAL (KIND=nag_wp) F06RPF
INTEGER | N
REAL (KIND=nag_wp) | D(*), E(*)
CHARACTER(1) | NORM

3 Description

None.

4 References

None.

5 Arguments

1:   NORM – CHARACTER(1)Input
On entry: specifies the value to be returned.
NORM='1' or 'O'
The 1-norm.
NORM='I'
The ∞-norm.
NORM='F' or 'E'
The Frobenius (or Euclidean) norm.
NORM='M'
The value max i,j a ij (not a norm).
Constraint: NORM='1', 'O', 'I', 'F', 'E' or 'M'.
2:   N – INTEGERInput
On entry: n, the order of the matrix A.
When N=0, F06RPF returns zero.
Constraint: N≥0.
3:   D* – REAL (KIND=nag_wp) arrayInput
Note: the dimension of the array D must be at least max 1,N .
On entry: the n diagonal elements of the tridiagonal matrix A.
4:   E* – REAL (KIND=nag_wp) arrayInput
Note: the dimension of the array E must be at least max 1,N-1 .
On entry: the (n-1) subdiagonal or superdiagonal elements of the tridiagonal matrix A.

6 Error Indicators and Warnings

None.

7 Accuracy

Not applicable.

8 Parallelism and Performance

F06RPF is not threaded in any implementation.

9 Further Comments

None.

10 Example

None.
F06 Chapter Contents
F06 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F06SAF (ZGEMV) : NAG Library, Mark 26

F06 Chapter Contents
F06 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F06SAF (ZGEMV)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
10 Example

1 Purpose

F06SAF (ZGEMV) computes the matrix-vector product for a complex general matrix, its transpose or its conjugate transpose.

2 Specification

SUBROUTINE F06SAF ( TRANS, M, N, ALPHA, A, LDA, X, INCX, BETA, Y, INCY)
INTEGER | M, N, LDA, INCX, INCY
COMPLEX (KIND=nag_wp) | ALPHA, A(LDA,*), X(*), BETA, Y(*)
CHARACTER(1) | TRANS
The routine may be called by its BLAS name zgemv.

3 Description

F06SAF (ZGEMV) performs one of the matrix-vector operations
y←αAx + βy ,   y←α AT x + βy   or   y←α AH x + βy ,
where A is an m by n complex matrix, x and y are complex vectors, and α and β are complex scalars.
If m=0 or n=0, no operation is performed.

4 References

None.

5 Arguments

1:   TRANS – CHARACTER(1)Input
On entry: specifies the operation to be performed.
TRANS='N'
y←αAx+βy.
TRANS='T'
y←α AT x+βy.
TRANS='C'
y←α AH x+βy.
Constraint: TRANS='N', 'T' or 'C'.
2:   M – INTEGERInput
On entry: m, the number of rows of the matrix A.
Constraint: M≥0.
3:   N – INTEGERInput
On entry: n, the number of columns of the matrix A.
Constraint: N≥0.
4:   ALPHA – COMPLEX (KIND=nag_wp)Input
On entry: the scalar α.
5:   A LDA* – COMPLEX (KIND=nag_wp) arrayInput
Note: the second dimension of the array A must be at least N.
On entry: the m by n matrix A.
6:   LDA – INTEGERInput
On entry: the first dimension of the array A as declared in the (sub)program from which F06SAF (ZGEMV) is called.
Constraint: LDA≥ max 1,M .
7:   X* – COMPLEX (KIND=nag_wp) arrayInput
Note: the dimension of the array X must be at least max 1, 1+ N-1 ×INCX if TRANS='N' and at least max 1, 1+ M-1 ×INCX if TRANS='T' or 'C'.
On entry: the vector x.
If TRANS='N',
  • if INCX>0, xi must be stored in X 1+i-1×INCX , for i=1,2,…,N;
  • if INCX<0, xi must be stored in X 1-N-i×INCX , for i=1,2,…,N.
If TRANS='T' or 'C',
  • if INCX>0, xi must be stored in X 1+i-1×INCX , for i=1,2,…,M;
  • if INCX<0, xi must be stored in X 1-M-i×INCX , for i=1,2,…,M.
8:   INCX – INTEGERInput
On entry: the increment in the subscripts of X between successive elements of x.
Constraint: INCX≠0.
9:   BETA – COMPLEX (KIND=nag_wp)Input
On entry: the scalar β.
10:   Y* – COMPLEX (KIND=nag_wp) arrayInput/Output
Note: the dimension of the array Y must be at least max 1,1+M-1 ×INCY if TRANS='N' and at least max 1,1+N-1 ×INCY if TRANS='T' or 'C'.
On entry: the vector y, if BETA=0.0, Y need not be set.
If TRANS='N',
  • if INCY>0, yi must be stored in Y 1+i-1×INCY , for i=1,2,…,M;
  • if INCY<0, yi must be stored in Y 1-M-i×INCY , for i=1,2,…,M.
If TRANS='T' or 'C',
  • if INCY>0, yi must be stored in Y 1+i-1×INCY , for i=1,2,…,N;
  • if INCY<0, yi must be stored in Y 1-N-i×INCY , for i=1,2,…,N.
On exit: the updated vector y stored in the array elements used to supply the original vector y.
11:   INCY – INTEGERInput
On entry: the increment in the subscripts of Y between successive elements of y.
Constraint: INCY≠0.

6 Error Indicators and Warnings

None.

7 Accuracy

Not applicable.

8 Parallelism and Performance

F06SAF (ZGEMV) is not threaded in any implementation.

9 Further Comments

None.

10 Example

None.
F06 Chapter Contents
F06 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F06SBF (ZGBMV) : NAG Library, Mark 26

F06 Chapter Contents
F06 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F06SBF (ZGBMV)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
10 Example

1 Purpose

F06SBF (ZGBMV) computes the matrix-vector product for a complex general band matrix, its transpose or its conjugate transpose.

2 Specification

SUBROUTINE F06SBF ( TRANS, M, N, KL, KU, ALPHA, A, LDA, X, INCX, BETA, Y, INCY)
INTEGER | M, N, KL, KU, LDA, INCX, INCY
COMPLEX (KIND=nag_wp) | ALPHA, A(LDA,*), X(*), BETA, Y(*)
CHARACTER(1) | TRANS
The routine may be called by its BLAS name zgbmv.

3 Description

F06SBF (ZGBMV) performs one of the matrix-vector operations
y←αAx+βy ,   y←α AT x+βy   or   y←α AH x+βy ,
where A is an m by n complex band matrix with kl subdiagonals and ku superdiagonals, x and y are complex vectors, and α and β are complex scalars.
If m=0 or n=0, no operation is performed.

4 References

None.

5 Arguments

1:   TRANS – CHARACTER(1)Input
On entry: specifies the operation to be performed.
TRANS='N'
y←αAx+βy.
TRANS='T'
y←α AT x+βy.
TRANS='C'
y←α AH x+βy.
Constraint: TRANS='N', 'T' or 'C'.
2:   M – INTEGERInput
On entry: m, the number of rows of the matrix A.
Constraint: M≥0.
3:   N – INTEGERInput
On entry: n, the number of columns of the matrix A.
Constraint: N≥0.
4:   KL – INTEGERInput
On entry: kl, the number of subdiagonals within the band of A.
Constraint: KL≥0.
5:   KU – INTEGERInput
On entry: ku, the number of superdiagonals within the band of A.
Constraint: KU≥0.
6:   ALPHA – COMPLEX (KIND=nag_wp)Input
On entry: the scalar α.
7:   A LDA* – COMPLEX (KIND=nag_wp) arrayInput
Note: the second dimension of the array A must be at least N.
On entry: the m by n band matrix A.
The matrix is stored in rows 1 to kl+ku+1, more precisely, the element A ij must be stored in
A ku+1+i-j j  for ​max 1,j-ku≤i≤min m,j+kl.
8:   LDA – INTEGERInput
On entry: the first dimension of the array A as declared in the (sub)program from which F06SBF (ZGBMV) is called.
Constraint: LDA≥KL+KU+1.
9:   X* – COMPLEX (KIND=nag_wp) arrayInput
Note: the dimension of the array X must be at least max 1, 1+ N-1 ×INCX if TRANS='N' and at least max 1, 1+ M-1 ×INCX if TRANS='T' or 'C'.
On entry: the vector x.
If TRANS='N',
  • if INCX>0, xi must be stored in X 1+i-1×INCX , for i=1,2,…,N;
  • if INCX<0, xi must be stored in X 1-N-i×INCX , for i=1,2,…,N.
If TRANS='T' or 'C',
  • if INCX>0, xi must be stored in X 1+i-1×INCX , for i=1,2,…,M;
  • if INCX<0, xi must be stored in X 1-M-i×INCX , for i=1,2,…,M.
10:   INCX – INTEGERInput
On entry: the increment in the subscripts of X between successive elements of x.
Constraint: INCX≠0.
11:   BETA – COMPLEX (KIND=nag_wp)Input
On entry: the scalar β.
12:   Y* – COMPLEX (KIND=nag_wp) arrayInput/Output
Note: the dimension of the array Y must be at least max 1,1+M-1 ×INCY if TRANS='N' and at least max 1,1+N-1 ×INCY if TRANS='T' or 'C'.
On entry: the vector y, if BETA=0.0, Y need not be set.
If TRANS='N',
  • if INCY>0, yi must be stored in Y 1+i-1×INCY , for i=1,2,…,M;
  • if INCY<0, yi must be stored in Y 1-M-i×INCY , for i=1,2,…,M.
If TRANS='T' or 'C',
  • if INCY>0, yi must be stored in Y 1+i-1×INCY , for i=1,2,…,N;
  • if INCY<0, yi must be stored in Y 1-N-i×INCY , for i=1,2,…,N.
On exit: the updated vector y stored in the array elements used to supply the original vector y.
13:   INCY – INTEGERInput
On entry: the increment in the subscripts of Y between successive elements of y.
Constraint: INCY≠0.

6 Error Indicators and Warnings

None.

7 Accuracy

Not applicable.

8 Parallelism and Performance

F06SBF (ZGBMV) is not threaded in any implementation.

9 Further Comments

None.

10 Example

None.
F06 Chapter Contents
F06 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F06SCF (ZHEMV) : NAG Library, Mark 26

F06 Chapter Contents
F06 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F06SCF (ZHEMV)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
10 Example

1 Purpose

F06SCF (ZHEMV) computes the matrix-vector product for a complex Hermitian matrix.

2 Specification

SUBROUTINE F06SCF ( UPLO, N, ALPHA, A, LDA, X, INCX, BETA, Y, INCY)
INTEGER | N, LDA, INCX, INCY
COMPLEX (KIND=nag_wp) | ALPHA, A(LDA,*), X(*), BETA, Y(*)
CHARACTER(1) | UPLO
The routine may be called by its BLAS name zhemv.

3 Description

F06SCF (ZHEMV) performs the matrix-vector operation
y←αAx+βy ,
where A is an n by n complex Hermitian matrix, x and y are n-element complex vectors, and α and β are complex scalars.

4 References

None.

5 Arguments

1:   UPLO – CHARACTER(1)Input
On entry: specifies whether the upper or lower triangular part of A is stored.
UPLO='U'
The upper triangular part of A is stored.
UPLO='L'
The lower triangular part of A is stored.
Constraint: UPLO='U' or 'L'.
2:   N – INTEGERInput
On entry: n, the order of the matrix A.
Constraint: N≥0.
3:   ALPHA – COMPLEX (KIND=nag_wp)Input
On entry: the scalar α.
4:   A LDA* – COMPLEX (KIND=nag_wp) arrayInput
Note: the second dimension of the array A must be at least max 1,N.
On entry: the n by n Hermitian matrix A.
  • If UPLO='U', the upper triangular part of A must be stored and the elements of the array below the diagonal are not referenced.
  • If UPLO='L', the lower triangular part of A must be stored and the elements of the array above the diagonal are not referenced.
5:   LDA – INTEGERInput
On entry: the first dimension of the array A as declared in the (sub)program from which F06SCF (ZHEMV) is called.
Constraint: LDA≥ max 1,N .
6:   X* – COMPLEX (KIND=nag_wp) arrayInput
Note: the dimension of the array X must be at least max 1, 1+N-1 ×INCX .
On entry: the n-element vector x.
If INCX>0, xi must be stored in X 1+i-1×INCX, for i=1,2,…,N.
If INCX<0, xi must be stored in X 1-N-i×INCX, for i=1,2,…,N.
Intermediate elements of X are not referenced.
7:   INCX – INTEGERInput
On entry: the increment in the subscripts of X between successive elements of x.
Constraint: INCX≠0.
8:   BETA – COMPLEX (KIND=nag_wp)Input
On entry: the scalar β.
9:   Y* – COMPLEX (KIND=nag_wp) arrayInput/Output
Note: the dimension of the array Y must be at least max 1, 1+N-1 ×INCY .
On entry: the n-element vector y, if BETA=0, Y need not be set.
If INCY>0, yi must be stored in Y 1+i–1×INCY , for i=1,2,…,N.
If INCY<0, yi must be stored in Y 1–N–i×INCY , for i=1,2,…,N.
On exit: the updated vector y stored in the array elements used to supply the original vector y.
10:   INCY – INTEGERInput
On entry: the increment in the subscripts of Y between successive elements of y.
Constraint: INCY≠0.

6 Error Indicators and Warnings

None.

7 Accuracy

Not applicable.

8 Parallelism and Performance

F06SCF (ZHEMV) is not threaded in any implementation.

9 Further Comments

None.

10 Example

None.
F06 Chapter Contents
F06 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F06SDF (ZHBMV) : NAG Library, Mark 26

F06 Chapter Contents
F06 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F06SDF (ZHBMV)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
10 Example

1 Purpose

F06SDF (ZHBMV) computes the matrix-vector product for a complex Hermitian band matrix.

2 Specification

SUBROUTINE F06SDF ( UPLO, N, K, ALPHA, A, LDA, X, INCX, BETA, Y, INCY)
INTEGER | N, K, LDA, INCX, INCY
COMPLEX (KIND=nag_wp) | ALPHA, A(LDA,*), X(*), BETA, Y(*)
CHARACTER(1) | UPLO
The routine may be called by its BLAS name zhbmv.

3 Description

F06SDF (ZHBMV) performs the matrix-vector operation
y←αAx+βy ,
where A is an n by n complex Hermitian band matrix with k subdiagonals and k superdiagonals, x and y are n-element complex vectors, and α and β are complex scalars.

4 References

None.

5 Arguments

1:   UPLO – CHARACTER(1)Input
On entry: specifies whether the upper or lower triangular part of A is stored.
UPLO='U'
The upper triangular part of A is stored.
UPLO='L'
The lower triangular part of A is stored.
Constraint: UPLO='U' or 'L'.
2:   N – INTEGERInput
On entry: n, the order of the matrix A.
Constraint: N≥0.
3:   K – INTEGERInput
On entry: k, the number of subdiagonals or superdiagonals of the matrix A.
Constraint: K≥0.
4:   ALPHA – COMPLEX (KIND=nag_wp)Input
On entry: the scalar α.
5:   A LDA* – COMPLEX (KIND=nag_wp) arrayInput
Note: the second dimension of the array A must be at least N.
On entry: the n by n Hermitian band matrix A.
The matrix is stored in rows 1 to k+1, more precisely,
  • if UPLO='U', the elements of the upper triangle of A within the band must be stored with element A ij in A k+1+i-j j​ for ​max 1,j-k≤i≤j;
  • if UPLO='L', the elements of the lower triangle of A within the band must be stored with element A ij in A 1+i-j j​ for ​j≤i≤min n,j+k.
6:   LDA – INTEGERInput
On entry: the first dimension of the array A as declared in the (sub)program from which F06SDF (ZHBMV) is called.
Constraint: LDA≥K+1.
7:   X* – COMPLEX (KIND=nag_wp) arrayInput
Note: the dimension of the array X must be at least max 1, 1+N-1 ×INCX .
On entry: the n-element vector x.
If INCX>0, xi must be stored in X 1+i-1×INCX, for i=1,2,…,N.
If INCX<0, xi must be stored in X 1-N-i×INCX, for i=1,2,…,N.
Intermediate elements of X are not referenced.
8:   INCX – INTEGERInput
On entry: the increment in the subscripts of X between successive elements of x.
Constraint: INCX≠0.
9:   BETA – COMPLEX (KIND=nag_wp)Input
On entry: the scalar β.
10:   Y* – COMPLEX (KIND=nag_wp) arrayInput/Output
Note: the dimension of the array Y must be at least max 1, 1+N-1 ×INCY .
On entry: the n-element vector y, if BETA=0, Y need not be set.
If INCY>0, yi must be stored in Y 1+i–1×INCY , for i=1,2,…,N.
If INCY<0, yi must be stored in Y 1–N–i×INCY , for i=1,2,…,N.
On exit: the updated vector y stored in the array elements used to supply the original vector y.
11:   INCY – INTEGERInput
On entry: the increment in the subscripts of Y between successive elements of y.
Constraint: INCY≠0.

6 Error Indicators and Warnings

None.

7 Accuracy

Not applicable.

8 Parallelism and Performance

F06SDF (ZHBMV) is not threaded in any implementation.

9 Further Comments

None.

10 Example

None.
F06 Chapter Contents
F06 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F06SEF (ZHPMV) : NAG Library, Mark 26

F06 Chapter Contents
F06 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F06SEF (ZHPMV)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
10 Example

1 Purpose

F06SEF (ZHPMV) computes the matrix-vector product for a complex Hermitian matrix stored in packed form.

2 Specification

SUBROUTINE F06SEF ( UPLO, N, ALPHA, AP, X, INCX, BETA, Y, INCY)
INTEGER | N, INCX, INCY
COMPLEX (KIND=nag_wp) | ALPHA, AP(*), X(*), BETA, Y(*)
CHARACTER(1) | UPLO
The routine may be called by its BLAS name zhpmv.

3 Description

F06SEF (ZHPMV) performs the matrix-vector operation
y←αAx + βy ,
where A is an n by n complex Hermitian matrix stored in packed form, x and y are n-element complex vectors, and α and β are complex scalars.

4 References

None.

5 Arguments

1:   UPLO – CHARACTER(1)Input
On entry: specifies whether the upper or lower triangular part of A is stored.
UPLO='U'
The upper triangular part of A is stored.
UPLO='L'
The lower triangular part of A is stored.
Constraint: UPLO='U' or 'L'.
2:   N – INTEGERInput
On entry: n, the order of the matrix A.
Constraint: N≥0.
3:   ALPHA – COMPLEX (KIND=nag_wp)Input
On entry: the scalar α.
4:   AP* – COMPLEX (KIND=nag_wp) arrayInput
Note: the dimension of the array AP must be at least N× N+1/2 .
On entry: the n by n Hermitian matrix A, packed by columns.
More precisely,
  • if UPLO='U', the upper triangle of A must be stored with element A ij in AP i+j j-1/2 for i≤j;
  • if UPLO='L', the lower triangle of A must be stored with element A ij in AP i+2 n-jj-1/2 for i≥j.
5:   X* – COMPLEX (KIND=nag_wp) arrayInput
Note: the dimension of the array X must be at least max 1, 1+N-1 ×INCX .
On entry: the n-element vector x.
If INCX>0, xi must be stored in X 1+i-1×INCX, for i=1,2,…,N.
If INCX<0, xi must be stored in X 1-N-i×INCX, for i=1,2,…,N.
Intermediate elements of X are not referenced.
6:   INCX – INTEGERInput
On entry: the increment in the subscripts of X between successive elements of x.
Constraint: INCX≠0.
7:   BETA – COMPLEX (KIND=nag_wp)Input
On entry: the scalar β.
8:   Y* – COMPLEX (KIND=nag_wp) arrayInput/Output
Note: the dimension of the array Y must be at least max 1, 1+N-1 ×INCY .
On entry: the n-element vector y, if BETA=0, Y need not be set.
If INCY>0, yi must be stored in Y 1+i–1×INCY , for i=1,2,…,N.
If INCY<0, yi must be stored in Y 1–N–i×INCY , for i=1,2,…,N.
On exit: the updated vector y stored in the array elements used to supply the original vector y.
9:   INCY – INTEGERInput
On entry: the increment in the subscripts of Y between successive elements of y.
Constraint: INCY≠0.

6 Error Indicators and Warnings

None.

7 Accuracy

Not applicable.

8 Parallelism and Performance

F06SEF (ZHPMV) is not threaded in any implementation.

9 Further Comments

None.

10 Example

None.
F06 Chapter Contents
F06 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F06SFF (ZTRMV) : NAG Library, Mark 26

F06 Chapter Contents
F06 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F06SFF (ZTRMV)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
10 Example

1 Purpose

F06SFF (ZTRMV) computes the matrix-vector product for a complex triangular matrix, its transpose or its conjugate transpose.

2 Specification

SUBROUTINE F06SFF ( UPLO, TRANS, DIAG, N, A, LDA, X, INCX)
INTEGER | N, LDA, INCX
COMPLEX (KIND=nag_wp) | A(LDA,*), X(*)
CHARACTER(1) | UPLO, TRANS, DIAG
The routine may be called by its BLAS name ztrmv.

3 Description

F06SFF (ZTRMV) performs one of the matrix-vector operations
x←Ax ,   x←AT x   or   x←AH x ,
where A is an n by n complex triangular matrix, and x is an n-element complex vector.

4 References

None.

5 Arguments

1:   UPLO – CHARACTER(1)Input
On entry: specifies whether A is upper or lower triangular.
UPLO='U'
A is upper triangular.
UPLO='L'
A is lower triangular.
Constraint: UPLO='U' or 'L'.
2:   TRANS – CHARACTER(1)Input
On entry: specifies the operation to be performed.
TRANS='N'
x←Ax.
TRANS='T'
x←AT x.
TRANS='C'
x←AH x.
Constraint: TRANS='N', 'T' or 'C'.
3:   DIAG – CHARACTER(1)Input
On entry: specifies whether A has nonunit or unit diagonal elements.
DIAG='N'
The diagonal elements are stored explicitly.
DIAG='U'
The diagonal elements are assumed to be 1, and are not referenced.
Constraint: DIAG='N' or 'U'.
4:   N – INTEGERInput
On entry: n, the order of the matrix A.
Constraint: N≥0.
5:   A LDA* – COMPLEX (KIND=nag_wp) arrayInput
Note: the second dimension of the array A must be at least N.
On entry: the n by n triangular matrix A.
  • If UPLO='U', A is upper triangular and the elements of the array below the diagonal are not referenced.
  • If UPLO='L', A is lower triangular and the elements of the array above the diagonal are not referenced.
  • If DIAG='U', the diagonal elements of A are assumed to be 1, and are not referenced.
6:   LDA – INTEGERInput
On entry: the first dimension of the array A as declared in the (sub)program from which F06SFF (ZTRMV) is called.
Constraint: LDA≥ max 1,N .
7:   X* – COMPLEX (KIND=nag_wp) arrayInput/Output
Note: the dimension of the array X must be at least max 1, 1+N-1 ×INCX .
On entry: the vector x.
If INCX>0, xi must be stored in X 1+i–1×INCX , for i=1,2,…,N.
If INCX<0, xi must be stored in X 1–N–i×INCX , for i=1,2,…,N.
On exit: the updated vector x stored in the array elements used to supply the original vector x.
8:   INCX – INTEGERInput
On entry: the increment in the subscripts of X between successive elements of x.
Constraint: INCX≠0.

6 Error Indicators and Warnings

None.

7 Accuracy

Not applicable.

8 Parallelism and Performance

F06SFF (ZTRMV) is not threaded in any implementation.

9 Further Comments

None.

10 Example

None.
F06 Chapter Contents
F06 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F06SGF (ZTBMV) : NAG Library, Mark 26

F06 Chapter Contents
F06 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F06SGF (ZTBMV)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
10 Example

1 Purpose

F06SGF (ZTBMV) computes the matrix-vector product for a complex triangular band matrix, its transpose or its conjugate transpose.

2 Specification

SUBROUTINE F06SGF ( UPLO, TRANS, DIAG, N, K, A, LDA, X, INCX)
INTEGER | N, K, LDA, INCX
COMPLEX (KIND=nag_wp) | A(LDA,*), X(*)
CHARACTER(1) | UPLO, TRANS, DIAG
The routine may be called by its BLAS name ztbmv.

3 Description

F06SGF (ZTBMV) performs one of the matrix-vector operations
x←Ax ,   x←AT x   or   x←AH x ,
where A is an n by n complex triangular band matrix with k subdiagonals or superdiagonals, and x is an n-element complex vector.

4 References

None.

5 Arguments

1:   UPLO – CHARACTER(1)Input
On entry: specifies whether A is upper or lower triangular.
UPLO='U'
A is upper triangular.
UPLO='L'
A is lower triangular.
Constraint: UPLO='U' or 'L'.
2:   TRANS – CHARACTER(1)Input
On entry: specifies the operation to be performed.
TRANS='N'
x←Ax.
TRANS='T'
x←AT x.
TRANS='C'
x←AH x.
Constraint: TRANS='N', 'T' or 'C'.
3:   DIAG – CHARACTER(1)Input
On entry: specifies whether A has nonunit or unit diagonal elements.
DIAG='N'
The diagonal elements are stored explicitly.
DIAG='U'
The diagonal elements are assumed to be 1, and are not referenced.
Constraint: DIAG='N' or 'U'.
4:   N – INTEGERInput
On entry: n, the order of the matrix A.
Constraint: N≥0.
5:   K – INTEGERInput
On entry: k, the number of subdiagonals or superdiagonals of the matrix A.
Constraint: K≥0.
6:   A LDA* – COMPLEX (KIND=nag_wp) arrayInput
Note: the second dimension of the array A must be at least N.
On entry: the n by n triangular band matrix A
The matrix is stored in rows 1 to k+1, more precisely,
  • if UPLO='U', the elements of the upper triangle of A within the band must be stored with element A ij in A k+1+i-j j​ for ​max 1,j-k≤i≤j;
  • if UPLO='L', the elements of the lower triangle of A within the band must be stored with element A ij in A 1+i-j j​ for ​j≤i≤min n,j+k.
If DIAG='U', the diagonal elements of A are assumed to be 1, and are not referenced.
7:   LDA – INTEGERInput
On entry: the first dimension of the array A as declared in the (sub)program from which F06SGF (ZTBMV) is called.
Constraint: LDA≥K+1.
8:   X* – COMPLEX (KIND=nag_wp) arrayInput/Output
Note: the dimension of the array X must be at least max 1, 1+N-1 ×INCX .
On entry: the vector x.
If INCX>0, xi must be stored in X 1+i–1×INCX , for i=1,2,…,N.
If INCX<0, xi must be stored in X 1–N–i×INCX , for i=1,2,…,N.
On exit: the updated vector x stored in the array elements used to supply the original vector x.
9:   INCX – INTEGERInput
On entry: the increment in the subscripts of X between successive elements of x.
Constraint: INCX≠0.

6 Error Indicators and Warnings

None.

7 Accuracy

Not applicable.

8 Parallelism and Performance

F06SGF (ZTBMV) is not threaded in any implementation.

9 Further Comments

None.

10 Example

None.
F06 Chapter Contents
F06 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F06SHF (ZTPMV) : NAG Library, Mark 26

F06 Chapter Contents
F06 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F06SHF (ZTPMV)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
10 Example

1 Purpose

F06SHF (ZTPMV) computes the matrix-vector product for a complex triangular matrix, its transpose or its conjugate transpose, stored in packed form.

2 Specification

SUBROUTINE F06SHF ( UPLO, TRANS, DIAG, N, AP, X, INCX)
INTEGER | N, INCX
COMPLEX (KIND=nag_wp) | AP(*), X(*)
CHARACTER(1) | UPLO, TRANS, DIAG
The routine may be called by its BLAS name ztpmv.

3 Description

F06SHF (ZTPMV) performs one of the matrix-vector operations
x←Ax ,   x←AT x   or   x←AH x ,
where A is an n by n complex triangular matrix, stored in packed form, and x is an n-element complex vector.

4 References

None.

5 Arguments

1:   UPLO – CHARACTER(1)Input
On entry: specifies whether A is upper or lower triangular.
UPLO='U'
A is upper triangular.
UPLO='L'
A is lower triangular.
Constraint: UPLO='U' or 'L'.
2:   TRANS – CHARACTER(1)Input
On entry: specifies the operation to be performed.
TRANS='N'
x←Ax.
TRANS='T'
x←AT x.
TRANS='C'
x←AH x.
Constraint: TRANS='N', 'T' or 'C'.
3:   DIAG – CHARACTER(1)Input
On entry: specifies whether A has nonunit or unit diagonal elements.
DIAG='N'
The diagonal elements are stored explicitly.
DIAG='U'
The diagonal elements are assumed to be 1, and are not referenced.
Constraint: DIAG='N' or 'U'.
4:   N – INTEGERInput
On entry: n, the order of the matrix A.
Constraint: N≥0.
5:   AP* – COMPLEX (KIND=nag_wp) arrayInput
Note: the dimension of the array AP must be at least N× N+1/2 .
On entry: the n by n triangular matrix A, packed by columns.
More precisely,
  • if UPLO='U', the upper triangle of A must be stored with element A ij in AP i+j j-1/2 for i≤j;
  • if UPLO='L', the lower triangle of A must be stored with element A ij in AP i+2 n-jj-1/2 for i≥j.
If DIAG='U', the diagonal elements of A are assumed to be 1, and are not referenced; the same storage scheme is used whether DIAG='N' or ‘U’.
6:   X* – COMPLEX (KIND=nag_wp) arrayInput/Output
Note: the dimension of the array X must be at least max 1, 1+N-1 ×INCX .
On entry: the vector x.
If INCX>0, xi must be stored in X 1+i–1×INCX , for i=1,2,…,N.
If INCX<0, xi must be stored in X 1–N–i×INCX , for i=1,2,…,N.
On exit: the updated vector x stored in the array elements used to supply the original vector x.
7:   INCX – INTEGERInput
On entry: the increment in the subscripts of X between successive elements of x.
Constraint: INCX≠0.

6 Error Indicators and Warnings

None.

7 Accuracy

Not applicable.

8 Parallelism and Performance

F06SHF (ZTPMV) is not threaded in any implementation.

9 Further Comments

None.

10 Example

None.
F06 Chapter Contents
F06 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F06SJF (ZTRSV) : NAG Library, Mark 26

F06 Chapter Contents
F06 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F06SJF (ZTRSV)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
10 Example

1 Purpose

F06SJF (ZTRSV) solves a complex triangular system of equations with a single right hand side.

2 Specification

SUBROUTINE F06SJF ( UPLO, TRANS, DIAG, N, A, LDA, X, INCX)
INTEGER | N, LDA, INCX
COMPLEX (KIND=nag_wp) | A(LDA,*), X(*)
CHARACTER(1) | UPLO, TRANS, DIAG
The routine may be called by its BLAS name ztrsv.

3 Description

F06SJF (ZTRSV) performs one of the matrix-vector operations
x←A-1 x ,   x←A-T x   or   x←A-H x ,
where A is an n by n complex triangular matrix, and x is an n-element complex vector. A-T denotes AT-1 or equivalently A-1 T ; A-H denotes AH-1 or equivalently A-1 H .
No test for singularity or near-singularity of A is included in this routine. Such tests must be performed before calling this routine.

4 References

None.

5 Arguments

1:   UPLO – CHARACTER(1)Input
On entry: specifies whether A is upper or lower triangular.
UPLO='U'
A is upper triangular.
UPLO='L'
A is lower triangular.
Constraint: UPLO='U' or 'L'.
2:   TRANS – CHARACTER(1)Input
On entry: specifies the operation to be performed.
TRANS='N'
x←A-1 x.
TRANS='T'
x←A-T x.
TRANS='C'
x←A-H x.
Constraint: TRANS='N', 'T' or 'C'.
3:   DIAG – CHARACTER(1)Input
On entry: specifies whether A has nonunit or unit diagonal elements.
DIAG='N'
The diagonal elements are stored explicitly.
DIAG='U'
The diagonal elements are assumed to be 1, and are not referenced.
Constraint: DIAG='N' or 'U'.
4:   N – INTEGERInput
On entry: n, the order of the matrix A.
Constraint: N≥0.
5:   A LDA* – COMPLEX (KIND=nag_wp) arrayInput
Note: the second dimension of the array A must be at least N.
On entry: the n by n triangular matrix A.
  • If UPLO='U', A is upper triangular and the elements of the array below the diagonal are not referenced.
  • If UPLO='L', A is lower triangular and the elements of the array above the diagonal are not referenced.
  • If DIAG='U', the diagonal elements of A are assumed to be 1, and are not referenced.
6:   LDA – INTEGERInput
On entry: the first dimension of the array A as declared in the (sub)program from which F06SJF (ZTRSV) is called.
Constraint: LDA≥ max 1,N .
7:   X* – COMPLEX (KIND=nag_wp) arrayInput/Output
Note: the dimension of the array X must be at least max 1, 1+N-1 ×INCX .
On entry: the vector x.
If INCX>0, xi must be stored in X 1+i–1×INCX , for i=1,2,…,N.
If INCX<0, xi must be stored in X 1–N–i×INCX , for i=1,2,…,N.
On exit: the updated vector x stored in the array elements used to supply the original vector x.
8:   INCX – INTEGERInput
On entry: the increment in the subscripts of X between successive elements of x.
Constraint: INCX≠0.

6 Error Indicators and Warnings

None.

7 Accuracy

Not applicable.

8 Parallelism and Performance

F06SJF (ZTRSV) is not threaded in any implementation.

9 Further Comments

None.

10 Example

None.
F06 Chapter Contents
F06 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F06SKF (ZTBSV) : NAG Library, Mark 26

F06 Chapter Contents
F06 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F06SKF (ZTBSV)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
10 Example

1 Purpose

F06SKF (ZTBSV) solves a complex triangular banded system of equations with a single right hand side.

2 Specification

SUBROUTINE F06SKF ( UPLO, TRANS, DIAG, N, K, A, LDA, X, INCX)
INTEGER | N, K, LDA, INCX
COMPLEX (KIND=nag_wp) | A(LDA,*), X(*)
CHARACTER(1) | UPLO, TRANS, DIAG
The routine may be called by its BLAS name ztbsv.

3 Description

F06SKF (ZTBSV) performs one of the matrix-vector operations
x←A-1 x ,   x←A-T x   or   x←A-H x ,
where A is an n by n complex triangular band matrix with k subdiagonals or superdiagonals, and x is an n-element complex vector. A-T denotes AT-1 or equivalently A-1 T ; A-H denotes AH-1 or equivalently A-1 H .
No test for singularity or near-singularity of A is included in this routine. Such tests must be performed before calling this routine.

4 References

None.

5 Arguments

1:   UPLO – CHARACTER(1)Input
On entry: specifies whether A is upper or lower triangular.
UPLO='U'
A is upper triangular.
UPLO='L'
A is lower triangular.
Constraint: UPLO='U' or 'L'.
2:   TRANS – CHARACTER(1)Input
On entry: specifies the operation to be performed.
TRANS='N'
x←A-1 x.
TRANS='T'
x←A-T x.
TRANS='C'
x←A-H x.
Constraint: TRANS='N', 'T' or 'C'.
3:   DIAG – CHARACTER(1)Input
On entry: specifies whether A has nonunit or unit diagonal elements.
DIAG='N'
The diagonal elements are stored explicitly.
DIAG='U'
The diagonal elements are assumed to be 1, and are not referenced.
Constraint: DIAG='N' or 'U'.
4:   N – INTEGERInput
On entry: n, the order of the matrix A.
Constraint: N≥0.
5:   K – INTEGERInput
On entry: k, the number of subdiagonals or superdiagonals of the matrix A.
Constraint: K≥0.
6:   A LDA* – COMPLEX (KIND=nag_wp) arrayInput
Note: the second dimension of the array A must be at least N.
On entry: the n by n triangular band matrix A
The matrix is stored in rows 1 to k+1, more precisely,
  • if UPLO='U', the elements of the upper triangle of A within the band must be stored with element A ij in A k+1+i-j j​ for ​max 1,j-k≤i≤j;
  • if UPLO='L', the elements of the lower triangle of A within the band must be stored with element A ij in A 1+i-j j​ for ​j≤i≤min n,j+k.
If DIAG='U', the diagonal elements of A are assumed to be 1, and are not referenced.
7:   LDA – INTEGERInput
On entry: the first dimension of the array A as declared in the (sub)program from which F06SKF (ZTBSV) is called.
Constraint: LDA≥K+1.
8:   X* – COMPLEX (KIND=nag_wp) arrayInput/Output
Note: the dimension of the array X must be at least max 1, 1+N-1 ×INCX .
On entry: the vector x.
If INCX>0, xi must be stored in X 1+i–1×INCX , for i=1,2,…,N.
If INCX<0, xi must be stored in X 1–N–i×INCX , for i=1,2,…,N.
On exit: the updated vector x stored in the array elements used to supply the original vector x.
9:   INCX – INTEGERInput
On entry: the increment in the subscripts of X between successive elements of x.
Constraint: INCX≠0.

6 Error Indicators and Warnings

None.

7 Accuracy

Not applicable.

8 Parallelism and Performance

F06SKF (ZTBSV) is not threaded in any implementation.

9 Further Comments

None.

10 Example

None.
F06 Chapter Contents
F06 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F06SLF (ZTPSV) : NAG Library, Mark 26

F06 Chapter Contents
F06 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F06SLF (ZTPSV)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
10 Example

1 Purpose

F06SLF (ZTPSV) solves a complex triangular system of equations, stored in packed form, with a single right hand side.

2 Specification

SUBROUTINE F06SLF ( UPLO, TRANS, DIAG, N, AP, X, INCX)
INTEGER | N, INCX
COMPLEX (KIND=nag_wp) | AP(*), X(*)
CHARACTER(1) | UPLO, TRANS, DIAG
The routine may be called by its BLAS name ztpsv.

3 Description

F06SLF (ZTPSV) performs one of the matrix-vector operations
x←A-1 x ,   x←A-T x   or   x←A-H x ,
where A is an n by n complex triangular matrix, stored in packed form, and x is an n-element complex vector. A-T denotes AT-1 or equivalently A-1 T ; A-H denotes AH-1 or equivalently A-1 H .
No test for singularity or near-singularity of A is included in this routine. Such tests must be performed before calling this routine.

4 References

None.

5 Arguments

1:   UPLO – CHARACTER(1)Input
On entry: specifies whether A is upper or lower triangular.
UPLO='U'
A is upper triangular.
UPLO='L'
A is lower triangular.
Constraint: UPLO='U' or 'L'.
2:   TRANS – CHARACTER(1)Input
On entry: specifies the operation to be performed.
TRANS='N'
x←A-1 x.
TRANS='T'
x←A-T x.
TRANS='C'
x←A-H x.
Constraint: TRANS='N', 'T' or 'C'.
3:   DIAG – CHARACTER(1)Input
On entry: specifies whether A has nonunit or unit diagonal elements.
DIAG='N'
The diagonal elements are stored explicitly.
DIAG='U'
The diagonal elements are assumed to be 1, and are not referenced.
Constraint: DIAG='N' or 'U'.
4:   N – INTEGERInput
On entry: n, the order of the matrix A.
Constraint: N≥0.
5:   AP* – COMPLEX (KIND=nag_wp) arrayInput
Note: the dimension of the array AP must be at least N× N+1/2 .
On entry: the n by n triangular matrix A, packed by columns.
More precisely,
  • if UPLO='U', the upper triangle of A must be stored with element A ij in AP i+j j-1/2 for i≤j;
  • if UPLO='L', the lower triangle of A must be stored with element A ij in AP i+2 n-jj-1/2 for i≥j.
If DIAG='U', the diagonal elements of A are assumed to be 1, and are not referenced; the same storage scheme is used whether DIAG='N' or ‘U’.
6:   X* – COMPLEX (KIND=nag_wp) arrayInput/Output
Note: the dimension of the array X must be at least max 1, 1+N-1 ×INCX .
On entry: the vector x.
If INCX>0, xi must be stored in X 1+i–1×INCX , for i=1,2,…,N.
If INCX<0, xi must be stored in X 1–N–i×INCX , for i=1,2,…,N.
On exit: the updated vector x stored in the array elements used to supply the original vector x.
7:   INCX – INTEGERInput
On entry: the increment in the subscripts of X between successive elements of x.
Constraint: INCX≠0.

6 Error Indicators and Warnings

None.

7 Accuracy

Not applicable.

8 Parallelism and Performance

F06SLF (ZTPSV) is not threaded in any implementation.

9 Further Comments

None.

10 Example

None.
F06 Chapter Contents
F06 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F06SMF (ZGERU) : NAG Library, Mark 26

F06 Chapter Contents
F06 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F06SMF (ZGERU)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
10 Example

1 Purpose

F06SMF (ZGERU) computes the rank-1 update of a complex general matrix using an unconjugated vector.

2 Specification

SUBROUTINE F06SMF ( M, N, ALPHA, X, INCX, Y, INCY, A, LDA)
INTEGER | M, N, INCX, INCY, LDA
COMPLEX (KIND=nag_wp) | ALPHA, X(*), Y(*), A(LDA,*)
The routine may be called by its BLAS name zgeru.

3 Description

F06SMF (ZGERU) performs the rank-1 update operation
A←αx yT + A ,
where A is an m by n complex matrix, x is an m element complex vector, y is an n-element complex vector, and α is a complex scalar.

4 References

None.

5 Arguments

1:   M – INTEGERInput
On entry: m, the number of rows of the matrix A.
Constraint: M≥0.
2:   N – INTEGERInput
On entry: n, the number of columns of the matrix A.
Constraint: N≥0.
3:   ALPHA – COMPLEX (KIND=nag_wp)Input
On entry: the scalar α.
4:   X* – COMPLEX (KIND=nag_wp) arrayInput
Note: the dimension of the array X must be at least max 1,1+M-1 ×INCX .
On entry: the m element vector x.
If INCX>0, xi must be stored in X 1+i–1×INCX , for i=1,2,…,M.
If INCX<0, xi must be stored in X 1–M–i×INCX , for i=1,2,…,M.
Intermediate elements of X are not referenced.
5:   INCX – INTEGERInput
On entry: the increment in the subscripts of X between successive elements of x.
Constraint: INCX≠0.
6:   Y* – COMPLEX (KIND=nag_wp) arrayInput
Note: the dimension of the array Y must be at least max 1, 1+N-1 ×INCY .
On entry: the n-element vector y.
If INCY>0, yi must be stored in Y 1+i-1×INCY, for i=1,2,…,N.
If INCY<0, yi must be stored in Y 1-N-i×INCY, for i=1,2,…,N.
Intermediate elements of Y are not referenced.
7:   INCY – INTEGERInput
On entry: the increment in the subscripts of Y between successive elements of y.
Constraint: INCY≠0.
8:   A LDA* – COMPLEX (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array A must be at least N.
On entry: the m by n matrix A.
On exit: the updated matrix A.
9:   LDA – INTEGERInput
On entry: the first dimension of the array A as declared in the (sub)program from which F06SMF (ZGERU) is called.
Constraint: LDA≥ max 1,M .

6 Error Indicators and Warnings

None.

7 Accuracy

Not applicable.

8 Parallelism and Performance

F06SMF (ZGERU) is not threaded in any implementation.

9 Further Comments

None.

10 Example

None.
F06 Chapter Contents
F06 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F06SNF (ZGERC) : NAG Library, Mark 26

F06 Chapter Contents
F06 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F06SNF (ZGERC)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
10 Example

1 Purpose

F06SNF (ZGERC) computes the rank-1 update of a complex general matrix using a conjugated vector.

2 Specification

SUBROUTINE F06SNF ( M, N, ALPHA, X, INCX, Y, INCY, A, LDA)
INTEGER | M, N, INCX, INCY, LDA
COMPLEX (KIND=nag_wp) | ALPHA, X(*), Y(*), A(LDA,*)
The routine may be called by its BLAS name zgerc.

3 Description

F06SNF (ZGERC) performs the rank-1 update operation
A←αx yH + A ,
where A is an m by n complex matrix, x is an m element complex vector, y is an n-element complex vector, and α is a complex scalar.

4 References

None.

5 Arguments

1:   M – INTEGERInput
On entry: m, the number of rows of the matrix A.
Constraint: M≥0.
2:   N – INTEGERInput
On entry: n, the number of columns of the matrix A.
Constraint: N≥0.
3:   ALPHA – COMPLEX (KIND=nag_wp)Input
On entry: the scalar α.
4:   X* – COMPLEX (KIND=nag_wp) arrayInput
Note: the dimension of the array X must be at least max 1,1+M-1 ×INCX .
On entry: the m element vector x.
If INCX>0, xi must be stored in X 1+i–1×INCX , for i=1,2,…,M.
If INCX<0, xi must be stored in X 1–M–i×INCX , for i=1,2,…,M.
Intermediate elements of X are not referenced.
5:   INCX – INTEGERInput
On entry: the increment in the subscripts of X between successive elements of x.
Constraint: INCX≠0.
6:   Y* – COMPLEX (KIND=nag_wp) arrayInput
Note: the dimension of the array Y must be at least max 1, 1+N-1 ×INCY .
On entry: the n-element vector y.
If INCY>0, yi must be stored in Y 1+i-1×INCY, for i=1,2,…,N.
If INCY<0, yi must be stored in Y 1-N-i×INCY, for i=1,2,…,N.
Intermediate elements of Y are not referenced.
7:   INCY – INTEGERInput
On entry: the increment in the subscripts of Y between successive elements of y.
Constraint: INCY≠0.
8:   A LDA* – COMPLEX (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array A must be at least N.
On entry: the m by n matrix A.
On exit: the updated matrix A.
9:   LDA – INTEGERInput
On entry: the first dimension of the array A as declared in the (sub)program from which F06SNF (ZGERC) is called.
Constraint: LDA≥ max 1,M .

6 Error Indicators and Warnings

None.

7 Accuracy

Not applicable.

8 Parallelism and Performance

F06SNF (ZGERC) is not threaded in any implementation.

9 Further Comments

None.

10 Example

None.
F06 Chapter Contents
F06 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F06SPF (ZHER) : NAG Library, Mark 26

F06 Chapter Contents
F06 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F06SPF (ZHER)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
10 Example

1 Purpose

F06SPF (ZHER) computes the rank-1 update of a complex Hermitian matrix.

2 Specification

SUBROUTINE F06SPF ( UPLO, N, ALPHA, X, INCX, A, LDA)
INTEGER | N, INCX, LDA
REAL (KIND=nag_wp) | ALPHA
COMPLEX (KIND=nag_wp) | X(*), A(LDA,*)
CHARACTER(1) | UPLO
The routine may be called by its BLAS name zher.

3 Description

F06SPF (ZHER) performs the Hermitian rank-1 update operation
A←αx xH+A ,
where A is an n by n complex Hermitian matrix, x is an n-element complex vector, and α is a real scalar.

4 References

None.

5 Arguments

1:   UPLO – CHARACTER(1)Input
On entry: specifies whether the upper or lower triangular part of A is stored.
UPLO='U'
The upper triangular part of A is stored.
UPLO='L'
The lower triangular part of A is stored.
Constraint: UPLO='U' or 'L'.
2:   N – INTEGERInput
On entry: n, the order of the matrix A.
Constraint: N≥0.
3:   ALPHA – REAL (KIND=nag_wp)Input
On entry: the scalar α.
4:   X* – COMPLEX (KIND=nag_wp) arrayInput
Note: the dimension of the array X must be at least max 1, 1+N-1 ×INCX .
On entry: the n-element vector x.
If INCX>0, xi must be stored in X 1+i-1×INCX, for i=1,2,…,N.
If INCX<0, xi must be stored in X 1-N-i×INCX, for i=1,2,…,N.
Intermediate elements of X are not referenced.
5:   INCX – INTEGERInput
On entry: the increment in the subscripts of X between successive elements of x.
Constraint: INCX≠0.
6:   A LDA* – COMPLEX (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array A must be at least max 1,N.
On entry: the n by n Hermitian matrix A.
  • If UPLO='U', the upper triangular part of A must be stored and the elements of the array below the diagonal are not referenced.
  • If UPLO='L', the lower triangular part of A must be stored and the elements of the array above the diagonal are not referenced.
On exit: the updated matrix A. The imaginary parts of the diagonal elements are set to zero.
7:   LDA – INTEGERInput
On entry: the first dimension of the array A as declared in the (sub)program from which F06SPF (ZHER) is called.
Constraint: LDA≥ max 1,N .

6 Error Indicators and Warnings

None.

7 Accuracy

Not applicable.

8 Parallelism and Performance

F06SPF (ZHER) is not threaded in any implementation.

9 Further Comments

None.

10 Example

None.
F06 Chapter Contents
F06 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F06SQF (ZHPR) : NAG Library, Mark 26

F06 Chapter Contents
F06 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F06SQF (ZHPR)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
10 Example

1 Purpose

F06SQF (ZHPR) computes the rank-1 update of a complex Hermitian matrix stored in packed form.

2 Specification

SUBROUTINE F06SQF ( UPLO, N, ALPHA, X, INCX, AP)
INTEGER | N, INCX
REAL (KIND=nag_wp) | ALPHA
COMPLEX (KIND=nag_wp) | X(*), AP(*)
CHARACTER(1) | UPLO
The routine may be called by its BLAS name zhpr.

3 Description

F06SQF (ZHPR) performs the Hermitian rank-1 update operation
A←αx xH + A ,
where A is an n by n complex Hermitian matrix, stored in packed form, x is an n-element complex vector, and α is a real scalar.

4 References

None.

5 Arguments

1:   UPLO – CHARACTER(1)Input
On entry: specifies whether the upper or lower triangular part of A is stored.
UPLO='U'
The upper triangular part of A is stored.
UPLO='L'
The lower triangular part of A is stored.
Constraint: UPLO='U' or 'L'.
2:   N – INTEGERInput
On entry: n, the order of the matrix A.
Constraint: N≥0.
3:   ALPHA – REAL (KIND=nag_wp)Input
On entry: the scalar α.
4:   X* – COMPLEX (KIND=nag_wp) arrayInput
Note: the dimension of the array X must be at least max 1, 1+N-1 ×INCX .
On entry: the n-element vector x.
If INCX>0, xi must be stored in X 1+i-1×INCX, for i=1,2,…,N.
If INCX<0, xi must be stored in X 1-N-i×INCX, for i=1,2,…,N.
Intermediate elements of X are not referenced.
5:   INCX – INTEGERInput
On entry: the increment in the subscripts of X between successive elements of x.
Constraint: INCX≠0.
6:   AP* – COMPLEX (KIND=nag_wp) arrayInput/Output
Note: the dimension of the array AP must be at least N× N+1/2 .
On entry: the n by n Hermitian matrix A, packed by columns.
More precisely,
  • if UPLO='U', the upper triangle of A must be stored with element A ij in AP i+j j-1/2 for i≤j;
  • if UPLO='L', the lower triangle of A must be stored with element A ij in AP i+2 n-jj-1/2 for i≥j.
On exit: the updated matrix A. The imaginary parts of the diagonal elements are set to zero.

6 Error Indicators and Warnings

None.

7 Accuracy

Not applicable.

8 Parallelism and Performance

F06SQF (ZHPR) is not threaded in any implementation.

9 Further Comments

None.

10 Example

None.
F06 Chapter Contents
F06 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F06SRF (ZHER2) : NAG Library, Mark 26

F06 Chapter Contents
F06 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F06SRF (ZHER2)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
10 Example

1 Purpose

F06SRF (ZHER2) computes the rank-2 update of a complex Hermitian matrix.

2 Specification

SUBROUTINE F06SRF ( UPLO, N, ALPHA, X, INCX, Y, INCY, A, LDA)
INTEGER | N, INCX, INCY, LDA
COMPLEX (KIND=nag_wp) | ALPHA, X(*), Y(*), A(LDA,*)
CHARACTER(1) | UPLO
The routine may be called by its BLAS name zher2.

3 Description

F06SRF (ZHER2) performs the Hermitian rank-2 update operation
A←αx yH + α-y xH + A ,
where A is an n by n complex Hermitian matrix, x and y are n-element complex vectors, and α is a complex scalar.

4 References

None.

5 Arguments

1:   UPLO – CHARACTER(1)Input
On entry: specifies whether the upper or lower triangular part of A is stored.
UPLO='U'
The upper triangular part of A is stored.
UPLO='L'
The lower triangular part of A is stored.
Constraint: UPLO='U' or 'L'.
2:   N – INTEGERInput
On entry: n, the order of the matrix A.
Constraint: N≥0.
3:   ALPHA – COMPLEX (KIND=nag_wp)Input
On entry: the scalar α.
4:   X* – COMPLEX (KIND=nag_wp) arrayInput
Note: the dimension of the array X must be at least max 1, 1+N-1 ×INCX .
On entry: the n-element vector x.
If INCX>0, xi must be stored in X 1+i-1×INCX, for i=1,2,…,N.
If INCX<0, xi must be stored in X 1-N-i×INCX, for i=1,2,…,N.
Intermediate elements of X are not referenced.
5:   INCX – INTEGERInput
On entry: the increment in the subscripts of X between successive elements of x.
Constraint: INCX≠0.
6:   Y* – COMPLEX (KIND=nag_wp) arrayInput
Note: the dimension of the array Y must be at least max 1, 1+N-1 ×INCY .
On entry: the n-element vector y.
If INCY>0, yi must be stored in Y 1+i-1×INCY, for i=1,2,…,N.
If INCY<0, yi must be stored in Y 1-N-i×INCY, for i=1,2,…,N.
Intermediate elements of Y are not referenced.
7:   INCY – INTEGERInput
On entry: the increment in the subscripts of Y between successive elements of y.
Constraint: INCY≠0.
8:   A LDA* – COMPLEX (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array A must be at least max 1,N.
On entry: the n by n Hermitian matrix A.
  • If UPLO='U', the upper triangular part of A must be stored and the elements of the array below the diagonal are not referenced.
  • If UPLO='L', the lower triangular part of A must be stored and the elements of the array above the diagonal are not referenced.
On exit: the updated matrix A. The imaginary parts of the diagonal elements are set to zero.
9:   LDA – INTEGERInput
On entry: the first dimension of the array A as declared in the (sub)program from which F06SRF (ZHER2) is called.
Constraint: LDA≥ max 1,N .

6 Error Indicators and Warnings

None.

7 Accuracy

Not applicable.

8 Parallelism and Performance

F06SRF (ZHER2) is not threaded in any implementation.

9 Further Comments

None.

10 Example

None.
F06 Chapter Contents
F06 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F06SSF (ZHPR2) : NAG Library, Mark 26

F06 Chapter Contents
F06 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F06SSF (ZHPR2)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
10 Example

1 Purpose

F06SSF (ZHPR2) computes the rank-2 update of a complex Hermitian matrix stored in packed form.

2 Specification

SUBROUTINE F06SSF ( UPLO, N, ALPHA, X, INCX, Y, INCY, AP)
INTEGER | N, INCX, INCY
COMPLEX (KIND=nag_wp) | ALPHA, X(*), Y(*), AP(*)
CHARACTER(1) | UPLO
The routine may be called by its BLAS name zhpr2.

3 Description

F06SSF (ZHPR2) performs the Hermitian rank-2 update operation
A←αx yH + α-y xH + A ,
where A is an n by n complex Hermitian matrix, stored in packed form, x and y are n-element complex vectors, and α is a complex scalar.

4 References

None.

5 Arguments

1:   UPLO – CHARACTER(1)Input
On entry: specifies whether the upper or lower triangular part of A is stored.
UPLO='U'
The upper triangular part of A is stored.
UPLO='L'
The lower triangular part of A is stored.
Constraint: UPLO='U' or 'L'.
2:   N – INTEGERInput
On entry: n, the order of the matrix A.
Constraint: N≥0.
3:   ALPHA – COMPLEX (KIND=nag_wp)Input
On entry: the scalar α.
4:   X* – COMPLEX (KIND=nag_wp) arrayInput
Note: the dimension of the array X must be at least max 1, 1+N-1 ×INCX .
On entry: the n-element vector x.
If INCX>0, xi must be stored in X 1+i-1×INCX, for i=1,2,…,N.
If INCX<0, xi must be stored in X 1-N-i×INCX, for i=1,2,…,N.
Intermediate elements of X are not referenced.
5:   INCX – INTEGERInput
On entry: the increment in the subscripts of X between successive elements of x.
Constraint: INCX≠0.
6:   Y* – COMPLEX (KIND=nag_wp) arrayInput
Note: the dimension of the array Y must be at least max 1, 1+N-1 ×INCY .
On entry: the n-element vector y.
If INCY>0, yi must be stored in Y 1+i-1×INCY, for i=1,2,…,N.
If INCY<0, yi must be stored in Y 1-N-i×INCY, for i=1,2,…,N.
Intermediate elements of Y are not referenced.
7:   INCY – INTEGERInput
On entry: the increment in the subscripts of Y between successive elements of y.
Constraint: INCY≠0.
8:   AP* – COMPLEX (KIND=nag_wp) arrayInput/Output
Note: the dimension of the array AP must be at least N× N+1/2 .
On entry: the n by n Hermitian matrix A, packed by columns.
More precisely,
  • if UPLO='U', the upper triangle of A must be stored with element A ij in AP i+j j-1/2 for i≤j;
  • if UPLO='L', the lower triangle of A must be stored with element A ij in AP i+2 n-jj-1/2 for i≥j.
On exit: the updated matrix A. The imaginary parts of the diagonal elements are set to zero.

6 Error Indicators and Warnings

None.

7 Accuracy

Not applicable.

8 Parallelism and Performance

F06SSF (ZHPR2) is not threaded in any implementation.

9 Further Comments

None.

10 Example

None.
F06 Chapter Contents
F06 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F06TAF : NAG Library, Mark 26

F06 Chapter Contents
F06 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F06TAF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
10 Example

1 Purpose

F06TAF performs the matrix-vector operation
y←αAx + βy,
where A is an n by n complex symmetric matrix, x and y are n-element complex vectors, and α and β are complex scalars.

2 Specification

SUBROUTINE F06TAF ( UPLO, N, ALPHA, A, LDA, X, INCX, BETA, Y, INCY)
INTEGER | N, LDA, INCX, INCY
COMPLEX (KIND=nag_wp) | ALPHA, A(LDA,*), X(*), BETA, Y(*)
CHARACTER(1) | UPLO

3 Description

None.

4 References

None.

5 Arguments

1:   UPLO – CHARACTER(1)Input
On entry: specifies whether the upper or lower triangular part of A is stored.
UPLO='U'
The upper triangular part of A is stored.
UPLO='L'
The lower triangular part of A is stored.
Constraint: UPLO='U' or 'L'.
2:   N – INTEGERInput
On entry: n, the order of the matrix A.
Constraint: N≥0.
3:   ALPHA – COMPLEX (KIND=nag_wp)Input
On entry: the scalar α.
4:   A LDA* – COMPLEX (KIND=nag_wp) arrayInput
Note: the second dimension of the array A must be at least max 1,N.
On entry: the n by n symmetric matrix A.
  • If UPLO='U', the upper triangular part of A must be stored and the elements of the array below the diagonal are not referenced.
  • If UPLO='L', the lower triangular part of A must be stored and the elements of the array above the diagonal are not referenced.
5:   LDA – INTEGERInput
On entry: the first dimension of the array A as declared in the (sub)program from which F06TAF is called.
Constraint: LDA≥ max 1,N .
6:   X* – COMPLEX (KIND=nag_wp) arrayInput
Note: the dimension of the array X must be at least max 1, 1+N-1 ×INCX .
On entry: the n-element vector x.
If INCX>0, xi must be stored in X 1+i-1×INCX, for i=1,2,…,N.
If INCX<0, xi must be stored in X 1-N-i×INCX, for i=1,2,…,N.
Intermediate elements of X are not referenced.
7:   INCX – INTEGERInput
On entry: the increment in the subscripts of X between successive elements of x.
Constraint: INCX≠0.
8:   BETA – COMPLEX (KIND=nag_wp)Input
On entry: the scalar β.
9:   Y* – COMPLEX (KIND=nag_wp) arrayInput/Output
Note: the dimension of the array Y must be at least max 1, 1+N-1 ×INCY .
On entry: the n-element vector y.
If INCY>0, yi must be stored in Y 1+i–1×INCY , for i=1,2,…,N.
If INCY<0, yi must be stored in Y 1–N–i×INCY , for i=1,2,…,N.
On exit: the updated vector y stored in the array elements used to supply the original vector y.
10:   INCY – INTEGERInput
On entry: the increment in the subscripts of Y between successive elements of y.
Constraint: INCY≠0.

6 Error Indicators and Warnings

None.

7 Accuracy

Not applicable.

8 Parallelism and Performance

F06TAF is not threaded in any implementation.

9 Further Comments

None.

10 Example

None.
F06 Chapter Contents
F06 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F06TBF : NAG Library, Mark 26

F06 Chapter Contents
F06 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F06TBF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
10 Example

1 Purpose

F06TBF performs the symmetric rank-1 update operation
A←αx xT + A ,
where A is an n by n complex symmetric matrix, x is an n-element complex vector, and α is a complex scalar.

2 Specification

SUBROUTINE F06TBF ( UPLO, N, ALPHA, X, INCX, A, LDA)
INTEGER | N, INCX, LDA
COMPLEX (KIND=nag_wp) | ALPHA, X(*), A(LDA,*)
CHARACTER(1) | UPLO

3 Description

None.

4 References

None.

5 Arguments

1:   UPLO – CHARACTER(1)Input
On entry: specifies whether the upper or lower triangular part of A is stored.
UPLO='U'
The upper triangular part of A is stored.
UPLO='L'
The lower triangular part of A is stored.
Constraint: UPLO='U' or 'L'.
2:   N – INTEGERInput
On entry: n, the order of the matrix A.
Constraint: N≥0.
3:   ALPHA – COMPLEX (KIND=nag_wp)Input
On entry: the scalar α.
4:   X* – COMPLEX (KIND=nag_wp) arrayInput
Note: the dimension of the array X must be at least max 1, 1+N-1 ×INCX .
On entry: the n-element vector x.
If INCX>0, xi must be stored in X 1+i-1×INCX, for i=1,2,…,N.
If INCX<0, xi must be stored in X 1-N-i×INCX, for i=1,2,…,N.
Intermediate elements of X are not referenced.
5:   INCX – INTEGERInput
On entry: the increment in the subscripts of X between successive elements of x.
Constraint: INCX≠0.
6:   A LDA* – COMPLEX (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array A must be at least max 1,N.
On entry: the n by n symmetric matrix A.
  • If UPLO='U', the upper triangular part of A must be stored and the elements of the array below the diagonal are not referenced.
  • If UPLO='L', the lower triangular part of A must be stored and the elements of the array above the diagonal are not referenced.
On exit: the updated matrix A.
7:   LDA – INTEGERInput
On entry: the first dimension of the array A as declared in the (sub)program from which F06TBF is called.
Constraint: LDA≥ max 1,N .

6 Error Indicators and Warnings

None.

7 Accuracy

Not applicable.

8 Parallelism and Performance

F06TBF is not threaded in any implementation.

9 Further Comments

None.

10 Example

None.
F06 Chapter Contents
F06 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F06TCF : NAG Library, Mark 26

F06 Chapter Contents
F06 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F06TCF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
10 Example

1 Purpose

F06TCF performs the matrix-vector operation
y←αAx + βy
where A is an n by n complex symmetric matrix stored in packed form, x and y are n-element complex vectors, and α and β are complex scalars.

2 Specification

SUBROUTINE F06TCF ( UPLO, N, ALPHA, AP, X, INCX, BETA, Y, INCY)
INTEGER | N, INCX, INCY
COMPLEX (KIND=nag_wp) | ALPHA, AP(*), X(*), BETA, Y(*)
CHARACTER(1) | UPLO

3 Description

None.

4 References

None.

5 Arguments

1:   UPLO – CHARACTER(1)Input
On entry: specifies whether the upper or lower triangular part of A is stored.
UPLO='U'
The upper triangular part of A is stored.
UPLO='L'
The lower triangular part of A is stored.
Constraint: UPLO='U' or 'L'.
2:   N – INTEGERInput
On entry: n, the order of the matrix A.
Constraint: N≥0.
3:   ALPHA – COMPLEX (KIND=nag_wp)Input
On entry: the scalar α.
4:   AP* – COMPLEX (KIND=nag_wp) arrayInput
Note: the dimension of the array AP must be at least N× N+1/2 .
On entry: the n by n symmetric matrix A, packed by columns.
More precisely,
  • if UPLO='U', the upper triangle of A must be stored with element A ij in AP i+j j-1/2 for i≤j;
  • if UPLO='L', the lower triangle of A must be stored with element A ij in AP i+2 n-jj-1/2 for i≥j.
5:   X* – COMPLEX (KIND=nag_wp) arrayInput
Note: the dimension of the array X must be at least max 1, 1+N-1 ×INCX .
On entry: the n-element vector x.
If INCX>0, xi must be stored in X 1+i-1×INCX, for i=1,2,…,N.
If INCX<0, xi must be stored in X 1-N-i×INCX, for i=1,2,…,N.
Intermediate elements of X are not referenced.
6:   INCX – INTEGERInput
On entry: the increment in the subscripts of X between successive elements of x.
Constraint: INCX≠0.
7:   BETA – COMPLEX (KIND=nag_wp)Input
On entry: the scalar β.
8:   Y* – COMPLEX (KIND=nag_wp) arrayInput/Output
Note: the dimension of the array Y must be at least max 1, 1+N-1 ×INCY .
On entry: the n-element vector y.
If INCY>0, yi must be stored in Y 1+i–1×INCY , for i=1,2,…,N.
If INCY<0, yi must be stored in Y 1–N–i×INCY , for i=1,2,…,N.
On exit: the updated vector y stored in the array elements used to supply the original vector y.
9:   INCY – INTEGERInput
On entry: the increment in the subscripts of Y between successive elements of y.
Constraint: INCY≠0.

6 Error Indicators and Warnings

None.

7 Accuracy

Not applicable.

8 Parallelism and Performance

F06TCF is not threaded in any implementation.

9 Further Comments

None.

10 Example

None.
F06 Chapter Contents
F06 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F06TDF : NAG Library, Mark 26

F06 Chapter Contents
F06 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F06TDF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
10 Example

1 Purpose

F06TDF performs the symmetric rank-1 update operation
A←αx xT + A ,
where A is an n by n complex symmetric matrix, stored in packed form, x is an n-element complex vector, and α is a complex scalar.

2 Specification

SUBROUTINE F06TDF ( UPLO, N, ALPHA, X, INCX, AP)
INTEGER | N, INCX
COMPLEX (KIND=nag_wp) | ALPHA, X(*), AP(*)
CHARACTER(1) | UPLO

3 Description

None.

4 References

None.

5 Arguments

1:   UPLO – CHARACTER(1)Input
On entry: specifies whether the upper or lower triangular part of A is stored.
UPLO='U'
The upper triangular part of A is stored.
UPLO='L'
The lower triangular part of A is stored.
Constraint: UPLO='U' or 'L'.
2:   N – INTEGERInput
On entry: n, the order of the matrix A.
Constraint: N≥0.
3:   ALPHA – COMPLEX (KIND=nag_wp)Input
On entry: the scalar α.
4:   X* – COMPLEX (KIND=nag_wp) arrayInput
Note: the dimension of the array X must be at least max 1, 1+N-1 ×INCX .
On entry: the n-element vector x.
If INCX>0, xi must be stored in X 1+i-1×INCX, for i=1,2,…,N.
If INCX<0, xi must be stored in X 1-N-i×INCX, for i=1,2,…,N.
Intermediate elements of X are not referenced.
5:   INCX – INTEGERInput
On entry: the increment in the subscripts of X between successive elements of x.
Constraint: INCX≠0.
6:   AP* – COMPLEX (KIND=nag_wp) arrayInput/Output
Note: the dimension of the array AP must be at least N× N+1/2 .
On entry: the n by n symmetric matrix A, packed by columns.
More precisely,
  • if UPLO='U', the upper triangle of A must be stored with element A ij in AP i+j j-1/2 for i≤j;
  • if UPLO='L', the lower triangle of A must be stored with element A ij in AP i+2 n-jj-1/2 for i≥j.
On exit: the updated matrix A.

6 Error Indicators and Warnings

None.

7 Accuracy

Not applicable.

8 Parallelism and Performance

F06TDF is not threaded in any implementation.

9 Further Comments

None.

10 Example

None.
F06 Chapter Contents
F06 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F06TFF : NAG Library, Mark 26

F06 Chapter Contents
F06 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F06TFF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
10 Example

1 Purpose

F06TFF performs the matrix-copy operation
B←A
where A and B are m by n complex general or trapezoidal matrices.

2 Specification

SUBROUTINE F06TFF ( MATRIX, M, N, A, LDA, B, LDB)
INTEGER | M, N, LDA, LDB
COMPLEX (KIND=nag_wp) | A(LDA,*), B(LDB,*)
CHARACTER(1) | MATRIX

3 Description

None.

4 References

None.

5 Arguments

1:   MATRIX – CHARACTER(1)Input
On entry: the matrix type.
MATRIX='G'
General matrix.
MATRIX='U'
Upper trapezoidal matrix (upper triangular if m=n).
MATRIX='L'
Lower trapezoidal matrix (lower triangular if m=n).
Constraint: MATRIX='G', 'U' or 'L'.
2:   M – INTEGERInput
On entry: m, the number of rows of the matrices A and B.
Constraint: M≥0.
3:   N – INTEGERInput
On entry: n, the number of columns of the matrices A and B.
Constraint: N≥0.
4:   A LDA* – COMPLEX (KIND=nag_wp) arrayInput
Note: the second dimension of the array A must be at least N.
On entry: the m by n general or trapezoidal matrix A.
  • If MATRIX='U', A is upper trapezoidal and the elements of the array below the diagonal are not referenced.
  • If MATRIX='L', A is lower trapezoidal and the elements of the array above the diagonal are not referenced.
5:   LDA – INTEGERInput
On entry: the first dimension of the array A as declared in the (sub)program from which F06TFF is called.
Constraint: LDA≥ max 1,M .
6:   B LDB* – COMPLEX (KIND=nag_wp) arrayOutput
Note: the second dimension of the array B must be at least N.
On exit: the m by n general or trapezoidal matrix B.
  • If MATRIX='U', B is upper trapezoidal and the elements of the array below the diagonal are not referenced.
  • If MATRIX='L', B is lower trapezoidal and the elements of the array above the diagonal are not referenced.
7:   LDB – INTEGERInput
On entry: the first dimension of the array B as declared in the (sub)program from which F06TFF is called.
Constraint: LDB≥ max 1,M .

6 Error Indicators and Warnings

None.

7 Accuracy

Not applicable.

8 Parallelism and Performance

F06TFF is not threaded in any implementation.

9 Further Comments

None.

10 Example

None.
F06 Chapter Contents
F06 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F06THF : NAG Library, Mark 26

F06 Chapter Contents
F06 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F06THF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
10 Example

1 Purpose

F06THF forms the complex m by n rectangular or trapezoidal matrix A given by
a ij = diag if i=j const if i≠j .

2 Specification

SUBROUTINE F06THF ( MATRIX, M, N, CON, DIAG, A, LDA)
INTEGER | M, N, LDA
COMPLEX (KIND=nag_wp) | CON, DIAG, A(LDA,*)
CHARACTER(1) | MATRIX

3 Description

None.

4 References

None.

5 Arguments

1:   MATRIX – CHARACTER(1)Input
On entry: the matrix type.
MATRIX='G'
General matrix.
MATRIX='U'
Upper trapezoidal matrix (upper triangular if m=n).
MATRIX='L'
Lower trapezoidal matrix (lower triangular if m=n).
Constraint: MATRIX='G', 'U' or 'L'.
2:   M – INTEGERInput
On entry: m, the number of rows of the matrix A.
Constraint: M≥0.
3:   N – INTEGERInput
On entry: n, the number of columns of the matrix A.
Constraint: N≥0.
4:   CON – COMPLEX (KIND=nag_wp)Input
On entry: the value to be assigned to the off-diagonal elements of A.
5:   DIAG – COMPLEX (KIND=nag_wp)Input
On entry: the value to be assigned to the diagonal elements of A.
6:   A LDA* – COMPLEX (KIND=nag_wp) arrayOutput
Note: the second dimension of the array A must be at least N.
On exit: the m by n general or trapezoidal matrix A.
  • If MATRIX='U', A is upper trapezoidal and the elements of the array below the diagonal are not referenced.
  • If MATRIX='L', A is lower trapezoidal and the elements of the array above the diagonal are not referenced.
7:   LDA – INTEGERInput
On entry: the first dimension of the array A as declared in the (sub)program from which F06THF is called.
Constraint: LDA≥ max 1,M .

6 Error Indicators and Warnings

None.

7 Accuracy

Not applicable.

8 Parallelism and Performance

F06THF is not threaded in any implementation.

9 Further Comments

None.

10 Example

None.
F06 Chapter Contents
F06 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F06TMF : NAG Library, Mark 26

F06 Chapter Contents
F06 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F06TMF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
10 Example

1 Purpose

F06TMF performs a Unitary similarity transformation (as a sequence of plane rotations) of a complex Hermitian matrix.

2 Specification

SUBROUTINE F06TMF ( UPLO, PIVOT, DIRECT, N, K1, K2, C, S, A, LDA)
INTEGER | N, K1, K2, LDA
REAL (KIND=nag_wp) | C(*)
COMPLEX (KIND=nag_wp) | S(*), A(LDA,*)
CHARACTER(1) | UPLO, PIVOT, DIRECT

3 Description

F06TMF performs the transformation
A←PA PH
where A is an n by n complex Hermitian matrix, and P is a complex unitary matrix defined as a sequence of plane rotations, Pk, applied in planes k 1 to k 2.
The 2 by 2 plane rotation part of Pk is assumed to have the form
ck s-k -sk ck
with ck real.

4 References

None.

5 Arguments

1:   UPLO – CHARACTER(1)Input
On entry: specifies whether the upper or lower triangular part of A is stored.
UPLO='U'
The upper triangular part of A is stored.
UPLO='L'
The lower triangular part of A is stored.
Constraint: UPLO='U' or 'L'.
2:   PIVOT – CHARACTER(1)Input
On entry: specifies the plane rotated by Pk.
PIVOT='V' (variable pivot)
Pk rotates the k,k+1 plane.
PIVOT='T' (top pivot)
Pk rotates the k 1,k+1 plane.
PIVOT='B' (bottom pivot)
Pk rotates the k,k 2 plane.
Constraint: PIVOT='V', 'T' or 'B'.
3:   DIRECT – CHARACTER(1)Input
On entry: specifies the sequence direction.
DIRECT='F' (forward sequence)
P=P k 2-1⋯P k 1+1P k 1.
DIRECT='B' (backward sequence)
P=P k 1P k 1+1⋯P k 2-1.
Constraint: DIRECT='F' or 'B'.
4:   N – INTEGERInput
On entry: n, the order of the matrix A.
Constraint: N≥0.
5:   K1 – INTEGERInput
6:   K2 – INTEGERInput
On entry: the values k 1 and k 2.
If K1<1 or K2≤K1 or K2>N, an immediate return is effected.
7:   C* – REAL (KIND=nag_wp) arrayInput
Note: the dimension of the array C must be at least K2-K1.
On entry: C k must hold ck, the cosine of the rotation Pk, for k=k 1,…,k 2-1.
8:   S* – COMPLEX (KIND=nag_wp) arrayInput
Note: the dimension of the array S must be at least K2-K1.
On entry: S k must hold sk, the sine of the rotation Pk, for k=k 1,…,k 2-1.
9:   A LDA* – COMPLEX (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array A must be at least max 1,N.
On entry: the n by n Hermitian matrix A.
  • If UPLO='U', the upper triangular part of A must be stored and the elements of the array below the diagonal are not referenced.
  • If UPLO='L', the lower triangular part of A must be stored and the elements of the array above the diagonal are not referenced.
On exit: the transformed matrix A. The imaginary parts of the diagonal elements are set to zero.
10:   LDA – INTEGERInput
On entry: the first dimension of the array A as declared in the (sub)program from which F06TMF is called.
Constraint: LDA≥ max 1,N .

6 Error Indicators and Warnings

None.

7 Accuracy

Not applicable.

8 Parallelism and Performance

F06TMF is not threaded in any implementation.

9 Further Comments

None.

10 Example

None.
F06 Chapter Contents
F06 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F06TPF : NAG Library, Mark 26

F06 Chapter Contents
F06 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F06TPF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
10 Example

1 Purpose

F06TPF performs a QR factorization (as a sequence of plane rotations) of a complex upper triangular matrix that has been modified by a rank-1 update.

2 Specification

SUBROUTINE F06TPF ( N, ALPHA, X, INCX, Y, INCY, A, LDA, C, S)
INTEGER | N, INCX, INCY, LDA
REAL (KIND=nag_wp) | C(N-1)
COMPLEX (KIND=nag_wp) | ALPHA, X(*), Y(*), A(LDA,*), S(N)

3 Description

F06TPF performs a QR factorization of an upper triangular matrix which has been modified by a rank-1 update:
αx yT + U=QR
where U and R are n by n complex upper triangular matrices with real diagonal elements, x and y are n-element complex vectors, α is a complex scalar, and Q is an n by n complex unitary matrix.
Q is formed as the product of two sequences of plane rotations and a unitary diagonal matrix D:
QH = D Q n-1 ⋯ Q 2 Q 1 P 1 P 2 ⋯ P n-1
where
  • Pk is a rotation in the k,n plane, chosen to annihilate xk: thus Px=β en, where P=P 1P 2⋯P n-1 and en is the last column of the unit matrix;
  • Qk is a rotation in the k,n plane, chosen to annihilate the n,k element of αβ en yT+PU, and thus restore it to upper triangular form;
  • D=diag 1,…,1,dn, with dn chosen to make r nn real; dn=1.
The 2 by 2 plane rotation part of Pk or Qk has the form
ck s-k -sk ck
with ck real. The tangents of the rotations Pk are returned in the array X; the cosines and sines of these rotations can be recovered by calling F06BCF. The cosines and sines of the rotations Qk are returned directly in the arrays C and S.

4 References

None.

5 Arguments

1:   N – INTEGERInput
On entry: n, the order of the matrices U and R.
Constraint: N≥0.
2:   ALPHA – COMPLEX (KIND=nag_wp)Input
On entry: the scalar α.
3:   X* – COMPLEX (KIND=nag_wp) arrayInput/Output
Note: the dimension of the array X must be at least max 1, 1+N-1 ×INCX .
On entry: the n-element vector x. xi must be stored in X 1+i-1×INCX, for i=1,2,…,N.
Intermediate elements of X are not referenced.
On exit: the referenced elements are overwritten by details of the sequence of plane rotations.
4:   INCX – INTEGERInput
On entry: the increment in the subscripts of X between successive elements of x.
Constraint: INCX>0.
5:   Y* – COMPLEX (KIND=nag_wp) arrayInput
Note: the dimension of the array Y must be at least max 1, 1+N-1 ×INCY .
On entry: the n-element vector y. yi must be stored in Y 1+i-1×INCY, for i=1,2,…,N.
Intermediate elements of Y are not referenced.
6:   INCY – INTEGERInput
On entry: the increment in the subscripts of Y between successive elements of y.
Constraint: INCY>0.
7:   A LDA* – COMPLEX (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array A must be at least N.
On entry: the n by n upper triangular matrix U. The imaginary parts of the diagonal elements must be zero.
On exit: the upper triangular matrix R. The imaginary parts of the diagonal elements must be zero.
8:   LDA – INTEGERInput
On entry: the first dimension of the array A as declared in the (sub)program from which F06TPF is called.
Constraint: LDA≥ max 1,N .
9:   C N-1 – REAL (KIND=nag_wp) arrayOutput
On exit: the cosines of the rotations Qk, for k=1,2,…,n-1.
10:   S N – COMPLEX (KIND=nag_wp) arrayOutput
On exit: the sines of the rotations Qk, for k=1,2,…,n-1; S n holds dn, the nth diagonal element of D.

6 Error Indicators and Warnings

None.

7 Accuracy

Not applicable.

8 Parallelism and Performance

F06TPF makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

None.

10 Example

None.
F06 Chapter Contents
F06 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F06TQF : NAG Library, Mark 26

F06 Chapter Contents
F06 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F06TQF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
10 Example

1 Purpose

F06TQF performs a QR factorization (as a sequence of plane rotations) of a complex upper triangular matrix that has been augmented by a full row.

2 Specification

SUBROUTINE F06TQF ( N, ALPHA, X, INCX, A, LDA, C, S)
INTEGER | N, INCX, LDA
REAL (KIND=nag_wp) | C(N)
COMPLEX (KIND=nag_wp) | ALPHA, X(*), A(LDA,*), S(N)

3 Description

F06TQF performs the factorization
U α xT =Q R 0
where U and R are n by n complex upper triangular matrices, x is an n-element complex vector, α is a complex scalar, and Q is a complex unitary matrix. If U has real diagonal elements, then so does R.
Q is formed as a sequence of plane rotations
QH = Qn ⋯ Q 2 Q 1
where Qk is a rotation in the k,n+1 plane, chosen to annihilate xk.
The 2 by 2 plane rotation part of Qk has the form
ck s-k -sk ck
with ck real.

4 References

None.

5 Arguments

1:   N – INTEGERInput
On entry: n, the order of the matrices U and R.
Constraint: N≥0.
2:   ALPHA – COMPLEX (KIND=nag_wp)Input
On entry: the scalar α.
3:   X* – COMPLEX (KIND=nag_wp) arrayInput/Output
Note: the dimension of the array X must be at least max 1, 1+N-1 ×INCX .
On entry: the n-element vector x. xi must be stored in X 1+i-1×INCX, for i=1,2,…,N.
Intermediate elements of X are not referenced.
On exit: the referenced elements are overwritten by details of the sequence of plane rotations.
4:   INCX – INTEGERInput
On entry: the increment in the subscripts of X between successive elements of x.
Constraint: INCX>0.
5:   A LDA* – COMPLEX (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array A must be at least N.
On entry: the n by n upper triangular matrix U.
On exit: the upper triangular matrix R.
6:   LDA – INTEGERInput
On entry: the first dimension of the array A as declared in the (sub)program from which F06TQF is called.
Constraint: LDA≥ max 1,N .
7:   C N – REAL (KIND=nag_wp) arrayOutput
On exit: the values ck, the cosines of the rotations Qk, for k=1,2,…,n.
8:   S N – COMPLEX (KIND=nag_wp) arrayOutput
On exit: the values sk, the sines of the rotations Qk, for k=1,2,…,n.

6 Error Indicators and Warnings

None.

7 Accuracy

Not applicable.

8 Parallelism and Performance

F06TQF is not threaded in any implementation.

9 Further Comments

None.

10 Example

None.
F06 Chapter Contents
F06 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F06TRF : NAG Library, Mark 26

F06 Chapter Contents
F06 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F06TRF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
10 Example

1 Purpose

F06TRF performs a QR or RQ factorization (as a sequence of plane rotations) of a complex upper Hessenberg matrix.

2 Specification

SUBROUTINE F06TRF ( SIDE, N, K1, K2, C, S, A, LDA)
INTEGER | N, K1, K2, LDA
REAL (KIND=nag_wp) | S(*)
COMPLEX (KIND=nag_wp) | C(K2), A(LDA,*)
CHARACTER(1) | SIDE

3 Description

F06TRF transforms an n by n complex upper Hessenberg matrix H to upper triangular form R by applying a unitary matrix P from the left or the right. H is assumed to have real nonzero subdiagonal elements h k+1,k, for k=k 1,…,k 2-1, only; R has real diagonal elements. P is formed as a sequence of plane rotations in planes k 1 to k 2.
If SIDE='L', the rotations are applied from the left:
PH=R ,
where P = D P k 2-1 ⋯ P k 1+1 P k 1 and D = diag 1,…,1 , d k 2 , 1,…,1 with d k 2=1.
If SIDE='R', the rotations are applied from the right:
H PH=R ,
where P = D P k 1 P k 1+1 ⋯ P k 2-1 and D = diag 1,…,1,d k 1,1,…,1 with d k 1=1.
In either case, Pk is a rotation in the k,k+1 plane, chosen to annihilate h k+1,k.
The 2 by 2 plane rotation part of Pk has the form
c-k sk -sk ck
with sk real.

4 References

None.

5 Arguments

1:   SIDE – CHARACTER(1)Input
On entry: specifies whether H is operated on from the left or the right.
SIDE='L'
H is pre-multiplied from the left.
SIDE='R'
H is post-multiplied from the right.
Constraint: SIDE='L' or 'R'.
2:   N – INTEGERInput
On entry: n, the order of the matrix H.
Constraint: N≥0.
3:   K1 – INTEGERInput
4:   K2 – INTEGERInput
On entry: the dimension of the array C as declared in the (sub)program from which F06TRF is called. The values k 1 and k 2.
If K1<1 or K2≤K1 or K2>N, an immediate return is effected.
5:   C K2 – COMPLEX (KIND=nag_wp) arrayOutput
On exit: C k holds ck, the cosine of the rotation Pk, for k=k 1,…,k 2-1; C k 2 holds d k 2, the k 2th diagonal element of D, if SIDE='L', or d k 1, the k 1th diagonal element of D, if SIDE='R'.
6:   S* – REAL (KIND=nag_wp) arrayInput/Output
Note: the dimension of the array S must be at least K2-K1.
On entry: the nonzero subdiagonal elements of H: S k must hold h k+1,k, for k=k 1,…,k 2-1.
On exit: S k holds sk, the sine of the rotation Pk, for k=k 1,…,k 2-1.
7:   A LDA* – COMPLEX (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array A must be at least N.
On entry: the upper triangular part of the n by n upper Hessenberg matrix H.
On exit: the upper triangular matrix R. The imaginary parts of the diagonal elements are set to zero.
8:   LDA – INTEGERInput
On entry: the first dimension of the array A as declared in the (sub)program from which F06TRF is called.
Constraint: LDA≥ max 1,N .

6 Error Indicators and Warnings

None.

7 Accuracy

Not applicable.

8 Parallelism and Performance

F06TRF makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

None.

10 Example

None.
F06 Chapter Contents
F06 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F06TSF : NAG Library, Mark 26

F06 Chapter Contents
F06 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F06TSF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
10 Example

1 Purpose

F06TSF performs a QR or RQ factorization (as a sequence of plane rotations) of a complex upper spiked matrix.

2 Specification

SUBROUTINE F06TSF ( SIDE, N, K1, K2, C, S, A, LDA)
INTEGER | N, K1, K2, LDA
REAL (KIND=nag_wp) | C(K2-1)
COMPLEX (KIND=nag_wp) | S(*), A(LDA,*)
CHARACTER(1) | SIDE

3 Description

F06TSF transforms an n by n complex upper spiked matrix H to upper triangular form R by applying a complex unitary matrix P from the left or the right. H is assumed to have real diagonal elements except where the spike joins the diagonal; R has real diagonal elements. P is formed as a sequence of plane rotations in planes k 1 to k 2.
If SIDE='L', H is assumed to have a row spike, with nonzero elements h k 2,k, for k=k 1,…,k 2-1. The rotations are applied from the left:
PH=R ,
where P = D P k 2-1 ⋯ P k 1+1 P k 1 , Pk is a rotation in the k,k 2 plane and D=diag 1,…,1,d k 2,1,…,1 with d k 2=1.
If SIDE='R', H is assumed to have a column spike, with nonzero elements h k+1,k 1, for k=k 1,…,k 2-1. The rotations are applied from the right:
H PH=R ,
where P = D P k 1 P k 1+1 ⋯ P k 2-1 , Pk is a rotation in the k 1,k+1 plane and D=diag 1,…,1,d k 1,1,…,1 with d k 1=1.
The 2 by 2 plane rotation part of Pk has the form
ck s-k -sk ck
with ck real.

4 References

None.

5 Arguments

1:   SIDE – CHARACTER(1)Input
On entry: specifies whether H is operated on from the left or the right.
SIDE='L'
H is pre-multiplied from the left.
SIDE='R'
H is post-multiplied from the right.
Constraint: SIDE='L' or 'R'.
2:   N – INTEGERInput
On entry: n, the order of the matrix H.
Constraint: N≥0.
3:   K1 – INTEGERInput
4:   K2 – INTEGERInput
On entry: the values k 1 and k 2.
If K1<1 or K2≤K1 or K2>N, an immediate return is effected.
5:   C K2-1 – REAL (KIND=nag_wp) arrayOutput
On exit: C k holds ck, the cosine of the rotation Pk, for k=k 1,…,k 2-1.
6:   S* – COMPLEX (KIND=nag_wp) arrayInput/Output
Note: the dimension of the array S must be at least K2-K1.
On entry: the nonzero elements of the spike of H: S k must hold h k 2,k if SIDE='L', and h k+1,k 1 if SIDE='R', for k=k 1,…,k 2-1.
On exit: S k holds sk, the sine of the rotation Pk, for k=k 1,…,k 2-1; S k 2 holds d k 2, the k 2th diagonal element of D, if SIDE='L', or d k 1, the k 1th diagonal element of D, if SIDE='R'.
7:   A LDA* – COMPLEX (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array A must be at least N.
On entry: the upper triangular part of the n by n upper spiked matrix H. The imaginary parts of the diagonal elements must be zero, except for the k 2,k 2 element if SIDE='L', or the k 1,k 1 element if SIDE='R'.
On exit: the upper triangular matrix R. The imaginary parts of the diagonal elements are set to zero.
8:   LDA – INTEGERInput
On entry: the first dimension of the array A as declared in the (sub)program from which F06TSF is called.
Constraint: LDA≥ max 1,N .

6 Error Indicators and Warnings

None.

7 Accuracy

Not applicable.

8 Parallelism and Performance

F06TSF makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

None.

10 Example

None.
F06 Chapter Contents
F06 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F06TTF : NAG Library, Mark 26

F06 Chapter Contents
F06 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F06TTF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
10 Example

1 Purpose

F06TTF performs a QR or RQ factorization of the product of a complex upper triangular matrix and a complex matrix of plane rotations.

2 Specification

SUBROUTINE F06TTF ( SIDE, N, K1, K2, C, S, A, LDA)
INTEGER | N, K1, K2, LDA
REAL (KIND=nag_wp) | C(*)
COMPLEX (KIND=nag_wp) | S(*), A(LDA,*)
CHARACTER(1) | SIDE

3 Description

F06TTF performs one of the transformations
R←PU QH   or   R←QU PH ,
where U is a given n by n complex upper triangular matrix, P is a given complex unitary matrix, and Q is a complex unitary matrix chosen to make R upper triangular. Both P and Q are represented as sequences of plane rotations in planes k 1 to k 2.
If SIDE='L',
R←PU QH ,
where P= P k 2-1 … P k 1+1 P k 1 and Q= Q k 2-1 … Q k 1+1 Q k 1 .
If SIDE='R',
R←QU PH ,
where P=P k 1 P k 1+1 … P k 2-1 and Q= Q k 1 Q k 1+1 … Q k 2-1 .
In either case Pk and Qk are rotations in the k,k+1 plane.
The 2 by 2 rotation part of Pk or Qk has the form
ck s-k -sk ck
with ck real.

4 References

None.

5 Arguments

1:   SIDE – CHARACTER(1)Input
On entry: specifies whether P is applied from the left or the right in the transformation.
SIDE='L'
P is applied from the left.
SIDE='R'
P is applied from the right.
Constraint: SIDE='L' or 'R'.
2:   N – INTEGERInput
On entry: n, the order of the matrices U and R.
Constraint: N≥0.
3:   K1 – INTEGERInput
4:   K2 – INTEGERInput
On entry: the values k 1 and k 2.
If K1<1 or K2≤K1 or K2>N, an immediate return is effected.
5:   C* – REAL (KIND=nag_wp) arrayInput/Output
Note: the dimension of the array C must be at least K2-K1.
On entry: C k must hold the cosine of the rotation Pk, for k=k 1,…,k 2-1.
On exit: C k holds the cosine of the rotation Qk, for k=k 1,…,k 2-1.
6:   S* – COMPLEX (KIND=nag_wp) arrayInput/Output
Note: the dimension of the array S must be at least K2-K1.
On entry: S k must hold the sine of the rotation Pk, for k=k 1,…,k 2-1.
On exit: S k holds the sine of the rotation Qk, for k=k 1,…,k 2-1.
7:   A LDA* – COMPLEX (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array A must be at least N.
On entry: the n by n upper triangular matrix U.
On exit: the upper triangular matrix R.
8:   LDA – INTEGERInput
On entry: the first dimension of the array A as declared in the (sub)program from which F06TTF is called.
Constraint: LDA≥ max 1,N .

6 Error Indicators and Warnings

None.

7 Accuracy

Not applicable.

8 Parallelism and Performance

F06TTF is not threaded in any implementation.

9 Further Comments

None.

10 Example

None.
F06 Chapter Contents
F06 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F06TVF : NAG Library, Mark 26

F06 Chapter Contents
F06 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F06TVF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
10 Example

1 Purpose

F06TVF transforms a complex upper triangular matrix to an upper Hessenberg matrix by applying a given sequence of plane rotations.

2 Specification

SUBROUTINE F06TVF ( SIDE, N, K1, K2, C, S, A, LDA)
INTEGER | N, K1, K2, LDA
REAL (KIND=nag_wp) | S(*)
COMPLEX (KIND=nag_wp) | C(*), A(LDA,*)
CHARACTER(1) | SIDE

3 Description

F06TVF transforms an n by n complex upper triangular matrix U with real diagonal elements, to an upper Hessenberg matrix H, by applying a given sequence of plane rotations from either the left or the right, in planes k 1 to k 2; H has real nonzero subdiagonal elements h k+1,k, for k=k 1,…,k 2-1 only.
If SIDE='L', the rotations are applied from the left:
H=PU ,
where P = P k 1 P k 1+1 ⋯ P k 2-1 .
If SIDE='R', the rotations are applied from the right:
H = U PH ,
where P = P k 2-1 ⋯ P k 1+1 P k 1 .
In either case, Pk is a rotation in the k,k+1 plane.
The 2 by 2 plane rotation part of Pk has the form
c-k sk -sk ck
with sk real.

4 References

None.

5 Arguments

1:   SIDE – CHARACTER(1)Input
On entry: specifies whether U is operated on from the left or the right.
SIDE='L'
U is pre-multiplied from the left.
SIDE='R'
U is post-multiplied from the right.
Constraint: SIDE='L' or 'R'.
2:   N – INTEGERInput
On entry: n, the order of the matrices U and H.
Constraint: N≥0.
3:   K1 – INTEGERInput
4:   K2 – INTEGERInput
On entry: the values k 1 and k 2.
If K1<1 or K2≤K1 or K2>N, an immediate return is effected.
5:   C* – COMPLEX (KIND=nag_wp) arrayInput
Note: the dimension of the array C must be at least K2-K1.
On entry: C k must hold ck, the cosine of the rotation Pk, for k=k 1,…,k 2-1.
6:   S* – REAL (KIND=nag_wp) arrayInput/Output
Note: the dimension of the array S must be at least K2-K1.
On entry: S k must hold sk, the sine of the rotation Pk, for k=k 1,…,k 2-1.
On exit: S k holds h k+1,k, the subdiagonal element of H, for k=k 1,…,k 2-1.
7:   A LDA* – COMPLEX (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array A must be at least N.
On entry: the n by n upper triangular matrix U. The imaginary parts of the diagonal elements must be zero.
On exit: the upper triangular part of the upper Hessenberg matrix H.
8:   LDA – INTEGERInput
On entry: the first dimension of the array A as declared in the (sub)program from which F06TVF is called.
Constraint: LDA≥ max 1,N .

6 Error Indicators and Warnings

None.

7 Accuracy

Not applicable.

8 Parallelism and Performance

F06TVF is not threaded in any implementation.

9 Further Comments

None.

10 Example

None.
F06 Chapter Contents
F06 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F06TWF : NAG Library, Mark 26

F06 Chapter Contents
F06 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F06TWF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
10 Example

1 Purpose

F06TWF transforms a complex upper triangular matrix to an upper spiked matrix by applying a given sequence of plane rotations.

2 Specification

SUBROUTINE F06TWF ( SIDE, N, K1, K2, C, S, A, LDA)
INTEGER | N, K1, K2, LDA
REAL (KIND=nag_wp) | C(*)
COMPLEX (KIND=nag_wp) | S(*), A(LDA,*)
CHARACTER(1) | SIDE

3 Description

F06TWF transforms an n by n complex upper triangular matrix U with real diagonal elements, to an upper spiked matrix H, by applying a given sequence of plane rotations from either the left or the right, in planes k 1 to k 2. H has real diagonal elements except where the spike joins the diagonal.
If SIDE='L', H has a row spike, with nonzero elements h k 2,k , for k = k 1 , k 1+1, …, k 2-1 . The rotations are applied from the left:
H=PU ,
where P = P k 1 P k 1+1 ⋯ P k 2-1 and Pk is a rotation in the k,k 2 plane.
If SIDE='R', H has a column spike, with nonzero elements h k+1, k 1 , for k= k 1, k 1+1, …, k 2-1 . The rotations are applied from the right:
H PH = R ,
where P = P k 2-1 ⋯ P k 1+1 P k 1 and Pk is a rotation in the k 1,k+1 plane.
The 2 by 2 plane rotation part of Pk has the form
ck s-k -sk ck
with ck real.

4 References

None.

5 Arguments

1:   SIDE – CHARACTER(1)Input
On entry: specifies whether U is operated on from the left or the right.
SIDE='L'
U is pre-multiplied from the left.
SIDE='R'
U is post-multiplied from the right.
Constraint: SIDE='L' or 'R'.
2:   N – INTEGERInput
On entry: n, the order of the matrices U and H.
Constraint: N≥0.
3:   K1 – INTEGERInput
4:   K2 – INTEGERInput
On entry: the values k 1 and k 2.
If K1<1 or K2≤K1 or K2>N, an immediate return is effected.
5:   C* – REAL (KIND=nag_wp) arrayInput
Note: the dimension of the array C must be at least K2-K1.
On entry: C k must hold ck, the cosine of the rotation Pk, for k=k 1,…,k 2-1.
6:   S* – COMPLEX (KIND=nag_wp) arrayInput/Output
Note: the dimension of the array S must be at least K2-K1.
On entry: S k must hold sk, the sine of the rotation Pk, for k=k 1,…,k 2-1.
On exit: S k holds a nonzero element of the spike of H: h k 2,k if SIDE='L', or h k+1,k 1 if SIDE='R', for k=k 1,…,k 2-1.
7:   A LDA* – COMPLEX (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array A must be at least N.
On entry: the n by n upper triangular matrix U. The imaginary parts of the diagonal elements must be zero.
On exit: the upper triangular part of the upper spiked matrix H. The imaginary parts of the diagonal elements are set to zero except for the k 2,k 2 element if SIDE='L', or the k 1,k 1 element if SIDE='R'.
8:   LDA – INTEGERInput
On entry: the first dimension of the array A as declared in the (sub)program from which F06TWF is called.
Constraint: LDA≥ max 1,N .

6 Error Indicators and Warnings

None.

7 Accuracy

Not applicable.

8 Parallelism and Performance

F06TWF is not threaded in any implementation.

9 Further Comments

None.

10 Example

None.
F06 Chapter Contents
F06 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F06TXF : NAG Library, Mark 26

F06 Chapter Contents
F06 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F06TXF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
10 Example

1 Purpose

F06TXF applies to a complex rectangular matrix a sequence of plane rotations having real cosines and complex sines.

2 Specification

SUBROUTINE F06TXF ( SIDE, PIVOT, DIRECT, M, N, K1, K2, C, S, A, LDA)
INTEGER | M, N, K1, K2, LDA
REAL (KIND=nag_wp) | C(*)
COMPLEX (KIND=nag_wp) | S(*), A(LDA,*)
CHARACTER(1) | SIDE, PIVOT, DIRECT

3 Description

F06TXF performs the transformation
A←PA   or   A←A PH ,
where A is an m by n complex matrix and P is a complex unitary matrix, defined as a sequence of complex plane rotations, Pk, with real cosines, applied in planes k 1 to k 2.
The 2 by 2 plane rotation part of Pk is assumed to have the form
ck s-k -sk ck
with ck real.

4 References

None.

5 Arguments

1:   SIDE – CHARACTER(1)Input
On entry: specifies whether A is operated on from the left or the right.
SIDE='L'
A is pre-multiplied from the left.
SIDE='R'
A is post-multiplied from the right.
Constraint: SIDE='L' or 'R'.
2:   PIVOT – CHARACTER(1)Input
On entry: specifies the plane rotated by Pk.
PIVOT='V' (variable pivot)
Pk rotates the k,k+1 plane.
PIVOT='T' (top pivot)
Pk rotates the k 1,k+1 plane.
PIVOT='B' (bottom pivot)
Pk rotates the k,k 2 plane.
Constraint: PIVOT='V', 'T' or 'B'.
3:   DIRECT – CHARACTER(1)Input
On entry: specifies the sequence direction.
DIRECT='F' (forward sequence)
P=P k 2-1⋯P k 1+1P k 1.
DIRECT='B' (backward sequence)
P=P k 1P k 1+1⋯P k 2-1.
Constraint: DIRECT='F' or 'B'.
4:   M – INTEGERInput
On entry: m, the number of rows of the matrix A.
Constraint: M≥0.
5:   N – INTEGERInput
On entry: n, the number of columns of the matrix A.
Constraint: N≥0.
6:   K1 – INTEGERInput
7:   K2 – INTEGERInput
On entry: the values k 1 and k 2.
If K1<1 or K2≤K1, or SIDE='L' and K2>M, or SIDE='R' and K2>N, an immediate return is effected.
8:   C* – REAL (KIND=nag_wp) arrayInput
Note: the dimension of the array C must be at least K2-K1.
On entry: C k must hold ck, the cosine of the rotation Pk, for k=k 1,…,k 2-1.
9:   S* – COMPLEX (KIND=nag_wp) arrayInput
Note: the dimension of the array S must be at least K2-K1.
On entry: S k must hold sk, the sine of the rotation Pk, for k=k 1,…,k 2-1.
10:   A LDA* – COMPLEX (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array A must be at least N.
On entry: the m by n matrix A.
On exit: the transformed matrix A.
11:   LDA – INTEGERInput
On entry: the first dimension of the array A as declared in the (sub)program from which F06TXF is called.
Constraint: LDA≥ max 1,M .

6 Error Indicators and Warnings

None.

7 Accuracy

Not applicable.

8 Parallelism and Performance

F06TXF is not threaded in any implementation.

9 Further Comments

None.

10 Example

None.
F06 Chapter Contents
F06 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F06TYF : NAG Library, Mark 26

F06 Chapter Contents
F06 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F06TYF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
10 Example

1 Purpose

F06TYF applies to a complex rectangular matrix a sequence of plane rotations having real sines and complex cosines.

2 Specification

SUBROUTINE F06TYF ( SIDE, PIVOT, DIRECT, M, N, K1, K2, C, S, A, LDA)
INTEGER | M, N, K1, K2, LDA
REAL (KIND=nag_wp) | S(*)
COMPLEX (KIND=nag_wp) | C(*), A(LDA,*)
CHARACTER(1) | SIDE, PIVOT, DIRECT

3 Description

F06TYF performs the transformation
A←PA   or   A←A PH ,
where A is an m by n complex matrix and P is a complex unitary matrix, defined as a sequence of complex plane rotations, Pk, with real sines, applied in planes k 1 to k 2.
The 2 by 2 plane rotation part of Pk is assumed to have the form
c-k sk -sk ck
with sk real.

4 References

None.

5 Arguments

1:   SIDE – CHARACTER(1)Input
On entry: specifies whether A is operated on from the left or the right.
SIDE='L'
A is pre-multiplied from the left.
SIDE='R'
A is post-multiplied from the right.
Constraint: SIDE='L' or 'R'.
2:   PIVOT – CHARACTER(1)Input
On entry: specifies the plane rotated by Pk.
PIVOT='V' (variable pivot)
Pk rotates the k,k+1 plane.
PIVOT='T' (top pivot)
Pk rotates the k 1,k+1 plane.
PIVOT='B' (bottom pivot)
Pk rotates the k,k 2 plane.
Constraint: PIVOT='V', 'T' or 'B'.
3:   DIRECT – CHARACTER(1)Input
On entry: specifies the sequence direction.
DIRECT='F' (forward sequence)
P=P k 2-1⋯P k 1+1P k 1.
DIRECT='B' (backward sequence)
P=P k 1P k 1+1⋯P k 2-1.
Constraint: DIRECT='F' or 'B'.
4:   M – INTEGERInput
On entry: m, the number of rows of the matrix A.
Constraint: M≥0.
5:   N – INTEGERInput
On entry: n, the number of columns of the matrix A.
Constraint: N≥0.
6:   K1 – INTEGERInput
7:   K2 – INTEGERInput
On entry: the values k 1 and k 2.
If K1<1 or K2≤K1, or SIDE='L' and K2>M, or SIDE='R' and K2>N, an immediate return is effected.
8:   C* – COMPLEX (KIND=nag_wp) arrayInput
Note: the dimension of the array C must be at least K2-K1.
On entry: C k must hold ck, the cosine of the rotation Pk, for k=k 1,…,k 2-1.
9:   S* – REAL (KIND=nag_wp) arrayInput
Note: the dimension of the array S must be at least K2-K1.
On entry: S k must hold sk, the sine of the rotation Pk, for k=k 1,…,k 2-1.
10:   A LDA* – COMPLEX (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array A must be at least N.
On entry: the m by n matrix A.
On exit: the transformed matrix A.
11:   LDA – INTEGERInput
On entry: the first dimension of the array A as declared in the (sub)program from which F06TYF is called.
Constraint: LDA≥ max 1,M .

6 Error Indicators and Warnings

None.

7 Accuracy

Not applicable.

8 Parallelism and Performance

F06TYF is not threaded in any implementation.

9 Further Comments

None.

10 Example

None.
F06 Chapter Contents
F06 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F06UAF : NAG Library, Mark 26

F06 Chapter Contents
F06 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F06UAF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
10 Example

1 Purpose

F06UAF returns, via the function name, the value of the 1-norm, the ∞-norm, the Frobenius norm, or the maximum absolute value of the elements of a complex m by n matrix.

2 Specification

FUNCTION F06UAF ( NORM, M, N, A, LDA, WORK)
REAL (KIND=nag_wp) F06UAF
INTEGER | M, N, LDA
REAL (KIND=nag_wp) | WORK(*)
COMPLEX (KIND=nag_wp) | A(LDA,*)
CHARACTER(1) | NORM

3 Description

None.

4 References

None.

5 Arguments

1:   NORM – CHARACTER(1)Input
On entry: specifies the value to be returned.
NORM='1' or 'O'
The 1-norm.
NORM='I'
The ∞-norm.
NORM='F' or 'E'
The Frobenius (or Euclidean) norm.
NORM='M'
The value max i,j a ij (not a norm).
Constraint: NORM='1', 'O', 'I', 'F', 'E' or 'M'.
2:   M – INTEGERInput
On entry: m, the number of rows of the matrix A.
When M=0, F06UAF is set to zero.
Constraint: M≥0.
3:   N – INTEGERInput
On entry: n, the number of columns of the matrix A.
When N=0, F06UAF is set to zero.
Constraint: N≥0.
4:   A LDA* – COMPLEX (KIND=nag_wp) arrayInput
Note: the second dimension of the array A must be at least N.
On entry: the m by n matrix A.
5:   LDA – INTEGERInput
On entry: the first dimension of the array A as declared in the (sub)program from which F06UAF is called.
Constraint: LDA≥ max 1,M .
6:   WORK* – REAL (KIND=nag_wp) arrayWorkspace
Note: the dimension of the array WORK must be at least max 1,M if NORM='I', and at least 1 otherwise.

6 Error Indicators and Warnings

None.

7 Accuracy

Not applicable.

8 Parallelism and Performance

F06UAF is not threaded in any implementation.

9 Further Comments

None.

10 Example

None.
F06 Chapter Contents
F06 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F06UBF : NAG Library, Mark 26

F06 Chapter Contents
F06 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F06UBF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
10 Example

1 Purpose

F06UBF returns, via the function name, the value of the 1-norm, the ∞-norm, the Frobenius norm, or the maximum absolute value of the elements of a complex n by n band matrix.

2 Specification

FUNCTION F06UBF ( NORM, N, KL, KU, AB, LDAB, WORK)
REAL (KIND=nag_wp) F06UBF
INTEGER | N, KL, KU, LDAB
REAL (KIND=nag_wp) | WORK(*)
COMPLEX (KIND=nag_wp) | AB(LDAB,*)
CHARACTER(1) | NORM

3 Description

None.

4 References

None.

5 Arguments

1:   NORM – CHARACTER(1)Input
On entry: specifies the value to be returned.
NORM='1' or 'O'
The 1-norm.
NORM='I'
The ∞-norm.
NORM='F' or 'E'
The Frobenius (or Euclidean) norm.
NORM='M'
The value max i,j a ij (not a norm).
Constraint: NORM='1', 'O', 'I', 'F', 'E' or 'M'.
2:   N – INTEGERInput
On entry: n, the order of the matrix A.
When N=0, F06UBF returns zero.
Constraint: N≥0.
3:   KL – INTEGERInput
On entry: kl, the number of subdiagonals within the band of A.
Constraint: KL≥0.
4:   KU – INTEGERInput
On entry: ku, the number of superdiagonals within the band of A.
Constraint: KU≥0.
5:   AB LDAB* – COMPLEX (KIND=nag_wp) arrayInput
Note: the second dimension of the array AB must be at least N.
On entry: the n by n band matrix A.
The matrix is stored in rows 1 to kl+ku+1, more precisely, the element A ij must be stored in
AB ku+1+i-j j  for ​max 1,j-ku≤i≤min n,j+kl.
6:   LDAB – INTEGERInput
On entry: the first dimension of the array AB as declared in the (sub)program from which F06UBF is called.
Constraint: LDAB≥KL+KU+1.
7:   WORK* – REAL (KIND=nag_wp) arrayWorkspace
Note: the dimension of the array WORK must be at least max 1,N if NORM='I', and at least 1 otherwise.

6 Error Indicators and Warnings

None.

7 Accuracy

Not applicable.

8 Parallelism and Performance

F06UBF is not threaded in any implementation.

9 Further Comments

None.

10 Example

None.
F06 Chapter Contents
F06 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F06UCF : NAG Library, Mark 26

F06 Chapter Contents
F06 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F06UCF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
10 Example

1 Purpose

F06UCF returns, via the function name, the value of the 1-norm, the ∞-norm, the Frobenius norm, or the maximum absolute value of the elements of a complex n by n Hermitian matrix.

2 Specification

FUNCTION F06UCF ( NORM, UPLO, N, A, LDA, WORK)
REAL (KIND=nag_wp) F06UCF
INTEGER | N, LDA
REAL (KIND=nag_wp) | WORK(*)
COMPLEX (KIND=nag_wp) | A(LDA,*)
CHARACTER(1) | NORM, UPLO

3 Description

None.

4 References

None.

5 Arguments

1:   NORM – CHARACTER(1)Input
On entry: specifies the value to be returned.
NORM='1' or 'O'
The 1-norm.
NORM='I'
The ∞-norm (= the 1-norm for a Hermitian matrix).
NORM='F' or 'E'
The Frobenius (or Euclidean) norm.
NORM='M'
The value max i,j a ij (not a norm).
Constraint: NORM='1', 'O', 'I', 'F', 'E' or 'M'.
2:   UPLO – CHARACTER(1)Input
On entry: specifies whether the upper or lower triangular part of A is stored.
UPLO='U'
The upper triangular part of A is stored.
UPLO='L'
The lower triangular part of A is stored.
Constraint: UPLO='U' or 'L'.
3:   N – INTEGERInput
On entry: n, the order of the matrix A.
When N=0, F06UCF returns zero.
Constraint: N≥0.
4:   A LDA* – COMPLEX (KIND=nag_wp) arrayInput
Note: the second dimension of the array A must be at least max 1,N.
On entry: the n by n Hermitian matrix A.
  • If UPLO='U', the upper triangular part of A must be stored and the elements of the array below the diagonal are not referenced.
  • If UPLO='L', the lower triangular part of A must be stored and the elements of the array above the diagonal are not referenced.
5:   LDA – INTEGERInput
On entry: the first dimension of the array A as declared in the (sub)program from which F06UCF is called.
Constraint: LDA≥ max 1,N .
6:   WORK* – REAL (KIND=nag_wp) arrayWorkspace
Note: the dimension of the array WORK must be at least max 1,N if NORM='1', 'O' or 'I', and at least 1 otherwise.

6 Error Indicators and Warnings

None.

7 Accuracy

Not applicable.

8 Parallelism and Performance

F06UCF is not threaded in any implementation.

9 Further Comments

None.

10 Example

None.
F06 Chapter Contents
F06 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F06UDF : NAG Library, Mark 26

F06 Chapter Contents
F06 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F06UDF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
10 Example

1 Purpose

F06UDF returns, via the function name, the value of the 1-norm, the ∞-norm, the Frobenius norm, or the maximum absolute value of the elements of a complex n by n Hermitian matrix, stored in packed form.

2 Specification

FUNCTION F06UDF ( NORM, UPLO, N, AP, WORK)
REAL (KIND=nag_wp) F06UDF
INTEGER | N
REAL (KIND=nag_wp) | WORK(*)
COMPLEX (KIND=nag_wp) | AP(*)
CHARACTER(1) | NORM, UPLO

3 Description

None.

4 References

None.

5 Arguments

1:   NORM – CHARACTER(1)Input
On entry: specifies the value to be returned.
NORM='1' or 'O'
The 1-norm.
NORM='I'
The ∞-norm (= the 1-norm for a Hermitian matrix).
NORM='F' or 'E'
The Frobenius (or Euclidean) norm.
NORM='M'
The value max i,j a ij (not a norm).
Constraint: NORM='1', 'O', 'I', 'F', 'E' or 'M'.
2:   UPLO – CHARACTER(1)Input
On entry: specifies whether the upper or lower triangular part of A is stored.
UPLO='U'
The upper triangular part of A is stored.
UPLO='L'
The lower triangular part of A is stored.
Constraint: UPLO='U' or 'L'.
3:   N – INTEGERInput
On entry: n, the order of the matrix A.
When N=0, F06UDF returns zero.
Constraint: N≥0.
4:   AP* – COMPLEX (KIND=nag_wp) arrayInput
Note: the dimension of the array AP must be at least N× N+1/2 .
On entry: the n by n Hermitian matrix A, packed by columns.
More precisely,
  • if UPLO='U', the upper triangle of A must be stored with element A ij in AP i+j j-1/2 for i≤j;
  • if UPLO='L', the lower triangle of A must be stored with element A ij in AP i+2 n-jj-1/2 for i≥j.
5:   WORK* – REAL (KIND=nag_wp) arrayWorkspace
Note: the dimension of the array WORK must be at least max 1,N if NORM='1', 'O' or 'I', and at least 1 otherwise.

6 Error Indicators and Warnings

None.

7 Accuracy

Not applicable.

8 Parallelism and Performance

F06UDF is not threaded in any implementation.

9 Further Comments

None.

10 Example

None.
F06 Chapter Contents
F06 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F06UEF : NAG Library, Mark 26

F06 Chapter Contents
F06 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F06UEF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
10 Example

1 Purpose

F06UEF returns, via the function name, the value of the 1-norm, the ∞-norm, the Frobenius norm, or the maximum absolute value of the elements of a complex n by n Hermitian band matrix.

2 Specification

FUNCTION F06UEF ( NORM, UPLO, N, K, AB, LDAB, WORK)
REAL (KIND=nag_wp) F06UEF
INTEGER | N, K, LDAB
REAL (KIND=nag_wp) | WORK(*)
COMPLEX (KIND=nag_wp) | AB(LDAB,*)
CHARACTER(1) | NORM, UPLO

3 Description

None.

4 References

None.

5 Arguments

1:   NORM – CHARACTER(1)Input
On entry: specifies the value to be returned.
NORM='1' or 'O'
The 1-norm.
NORM='I'
The ∞-norm (= the 1-norm for a Hermitian matrix).
NORM='F' or 'E'
The Frobenius (or Euclidean) norm.
NORM='M'
The value max i,j a ij (not a norm).
Constraint: NORM='1', 'O', 'I', 'F', 'E' or 'M'.
2:   UPLO – CHARACTER(1)Input
On entry: specifies whether the upper or lower triangular part of A is stored.
UPLO='U'
The upper triangular part of A is stored.
UPLO='L'
The lower triangular part of A is stored.
Constraint: UPLO='U' or 'L'.
3:   N – INTEGERInput
On entry: n, the order of the matrix A.
When N=0, F06UEF returns zero.
Constraint: N≥0.
4:   K – INTEGERInput
On entry: k, the number of subdiagonals or superdiagonals of the matrix A.
Constraint: K≥0.
5:   AB LDAB* – COMPLEX (KIND=nag_wp) arrayInput
Note: the second dimension of the array AB must be at least N.
On entry: the n by n Hermitian band matrix A.
The matrix is stored in rows 1 to k+1, more precisely,
  • if UPLO='U', the elements of the upper triangle of A within the band must be stored with element A ij in AB k+1+i-j j​ for ​max 1,j-k≤i≤j;
  • if UPLO='L', the elements of the lower triangle of A within the band must be stored with element A ij in AB 1+i-j j​ for ​j≤i≤min n,j+k.
6:   LDAB – INTEGERInput
On entry: the first dimension of the array AB as declared in the (sub)program from which F06UEF is called.
Constraint: LDAB≥K+1.
7:   WORK* – REAL (KIND=nag_wp) arrayWorkspace
Note: the dimension of the array WORK must be at least max 1,N if NORM='1', 'O' or 'I', and at least 1 otherwise.

6 Error Indicators and Warnings

None.

7 Accuracy

Not applicable.

8 Parallelism and Performance

F06UEF is not threaded in any implementation.

9 Further Comments

None.

10 Example

None.
F06 Chapter Contents
F06 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F06UFF : NAG Library, Mark 26

F06 Chapter Contents
F06 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F06UFF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
10 Example

1 Purpose

F06UFF returns, via the function name, the value of the 1-norm, the ∞-norm, the Frobenius norm, or the maximum absolute value of the elements of a complex n by n symmetric matrix.

2 Specification

FUNCTION F06UFF ( NORM, UPLO, N, A, LDA, WORK)
REAL (KIND=nag_wp) F06UFF
INTEGER | N, LDA
REAL (KIND=nag_wp) | WORK(*)
COMPLEX (KIND=nag_wp) | A(LDA,*)
CHARACTER(1) | NORM, UPLO

3 Description

None.

4 References

None.

5 Arguments

1:   NORM – CHARACTER(1)Input
On entry: specifies the value to be returned.
NORM='1' or 'O'
The 1-norm.
NORM='I'
The ∞-norm (= the 1-norm for a symmetric matrix).
NORM='F' or 'E'
The Frobenius (or Euclidean) norm.
NORM='M'
The value max i,j a ij (not a norm).
Constraint: NORM='1', 'O', 'I', 'F', 'E' or 'M'.
2:   UPLO – CHARACTER(1)Input
On entry: specifies whether the upper or lower triangular part of A is stored.
UPLO='U'
The upper triangular part of A is stored.
UPLO='L'
The lower triangular part of A is stored.
Constraint: UPLO='U' or 'L'.
3:   N – INTEGERInput
On entry: n, the order of the matrix A.
When N=0, F06UFF returns zero.
Constraint: N≥0.
4:   A LDA* – COMPLEX (KIND=nag_wp) arrayInput
Note: the second dimension of the array A must be at least max 1,N.
On entry: the n by n symmetric matrix A.
  • If UPLO='U', the upper triangular part of A must be stored and the elements of the array below the diagonal are not referenced.
  • If UPLO='L', the lower triangular part of A must be stored and the elements of the array above the diagonal are not referenced.
5:   LDA – INTEGERInput
On entry: the first dimension of the array A as declared in the (sub)program from which F06UFF is called.
Constraint: LDA≥ max 1,N .
6:   WORK* – REAL (KIND=nag_wp) arrayWorkspace
Note: the dimension of the array WORK must be at least max 1,N if NORM='1', 'O' or 'I', and at least 1 otherwise.

6 Error Indicators and Warnings

None.

7 Accuracy

Not applicable.

8 Parallelism and Performance

F06UFF is not threaded in any implementation.

9 Further Comments

None.

10 Example

None.
F06 Chapter Contents
F06 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F06UGF : NAG Library, Mark 26

F06 Chapter Contents
F06 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F06UGF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
10 Example

1 Purpose

F06UGF returns, via the function name, the value of the 1-norm, the ∞-norm, the Frobenius norm, or the maximum absolute value of the elements of a complex n by n symmetric matrix, stored in packed form.

2 Specification

FUNCTION F06UGF ( NORM, UPLO, N, AP, WORK)
REAL (KIND=nag_wp) F06UGF
INTEGER | N
REAL (KIND=nag_wp) | WORK(*)
COMPLEX (KIND=nag_wp) | AP(*)
CHARACTER(1) | NORM, UPLO

3 Description

None.

4 References

None.

5 Arguments

1:   NORM – CHARACTER(1)Input
On entry: specifies the value to be returned.
NORM='1' or 'O'
The 1-norm.
NORM='I'
The ∞-norm (= the 1-norm for a symmetric matrix).
NORM='F' or 'E'
The Frobenius (or Euclidean) norm.
NORM='M'
The value max i,j a ij (not a norm).
Constraint: NORM='1', 'O', 'I', 'F', 'E' or 'M'.
2:   UPLO – CHARACTER(1)Input
On entry: specifies whether the upper or lower triangular part of A is stored.
UPLO='U'
The upper triangular part of A is stored.
UPLO='L'
The lower triangular part of A is stored.
Constraint: UPLO='U' or 'L'.
3:   N – INTEGERInput
On entry: n, the order of the matrix A.
When N=0, F06UGF returns zero.
Constraint: N≥0.
4:   AP* – COMPLEX (KIND=nag_wp) arrayInput
Note: the dimension of the array AP must be at least N× N+1/2 .
On entry: the n by n symmetric matrix A, packed by columns.
More precisely,
  • if UPLO='U', the upper triangle of A must be stored with element A ij in AP i+j j-1/2 for i≤j;
  • if UPLO='L', the lower triangle of A must be stored with element A ij in AP i+2 n-jj-1/2 for i≥j.
5:   WORK* – REAL (KIND=nag_wp) arrayWorkspace
Note: the dimension of the array WORK must be at least max 1,N if NORM='1', 'O' or 'I', and at least 1 otherwise.

6 Error Indicators and Warnings

None.

7 Accuracy

Not applicable.

8 Parallelism and Performance

F06UGF is not threaded in any implementation.

9 Further Comments

None.

10 Example

None.
F06 Chapter Contents
F06 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F06UHF : NAG Library, Mark 26

F06 Chapter Contents
F06 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F06UHF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
10 Example

1 Purpose

F06UHF returns, via the function name, the value of the 1-norm, the ∞-norm, the Frobenius norm, or the maximum absolute value of the elements of a complex n by n symmetric band matrix.

2 Specification

FUNCTION F06UHF ( NORM, UPLO, N, K, AB, LDAB, WORK)
REAL (KIND=nag_wp) F06UHF
INTEGER | N, K, LDAB
REAL (KIND=nag_wp) | WORK(*)
COMPLEX (KIND=nag_wp) | AB(LDAB,*)
CHARACTER(1) | NORM, UPLO

3 Description

None.

4 References

None.

5 Arguments

1:   NORM – CHARACTER(1)Input
On entry: specifies the value to be returned.
NORM='1' or 'O'
The 1-norm.
NORM='I'
The ∞-norm (= the 1-norm for a symmetric matrix).
NORM='F' or 'E'
The Frobenius (or Euclidean) norm.
NORM='M'
The value max i,j a ij (not a norm).
Constraint: NORM='1', 'O', 'I', 'F', 'E' or 'M'.
2:   UPLO – CHARACTER(1)Input
On entry: specifies whether the upper or lower triangular part of A is stored.
UPLO='U'
The upper triangular part of A is stored.
UPLO='L'
The lower triangular part of A is stored.
Constraint: UPLO='U' or 'L'.
3:   N – INTEGERInput
On entry: n, the order of the matrix A.
When N=0, F06UHF returns zero.
Constraint: N≥0.
4:   K – INTEGERInput
On entry: k, the number of subdiagonals or superdiagonals of the matrix A.
Constraint: K≥0.
5:   AB LDAB* – COMPLEX (KIND=nag_wp) arrayInput
Note: the second dimension of the array AB must be at least N.
On entry: the n by n symmetric band matrix A.
The matrix is stored in rows 1 to k+1, more precisely,
  • if UPLO='U', the elements of the upper triangle of A within the band must be stored with element A ij in AB k+1+i-j j​ for ​max 1,j-k≤i≤j;
  • if UPLO='L', the elements of the lower triangle of A within the band must be stored with element A ij in AB 1+i-j j​ for ​j≤i≤min n,j+k.
6:   LDAB – INTEGERInput
On entry: the first dimension of the array AB as declared in the (sub)program from which F06UHF is called.
Constraint: LDAB≥K+1.
7:   WORK* – REAL (KIND=nag_wp) arrayWorkspace
Note: the dimension of the array WORK must be at least max 1,N if NORM='1', 'O' or 'I', and at least 1 otherwise.

6 Error Indicators and Warnings

None.

7 Accuracy

Not applicable.

8 Parallelism and Performance

F06UHF is not threaded in any implementation.

9 Further Comments

None.

10 Example

None.
F06 Chapter Contents
F06 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F06UJF : NAG Library, Mark 26

F06 Chapter Contents
F06 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F06UJF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
10 Example

1 Purpose

F06UJF returns, via the function name, the value of the 1-norm, the ∞-norm, the Frobenius norm, or the maximum absolute value of the elements of a complex m by n trapezoidal matrix (triangular if m=n).

2 Specification

FUNCTION F06UJF ( NORM, UPLO, DIAG, M, N, A, LDA, WORK)
REAL (KIND=nag_wp) F06UJF
INTEGER | M, N, LDA
REAL (KIND=nag_wp) | WORK(*)
COMPLEX (KIND=nag_wp) | A(LDA,*)
CHARACTER(1) | NORM, UPLO, DIAG

3 Description

None.

4 References

None.

5 Arguments

1:   NORM – CHARACTER(1)Input
On entry: specifies the value to be returned.
NORM='1' or 'O'
The 1-norm.
NORM='I'
The ∞-norm.
NORM='F' or 'E'
The Frobenius (or Euclidean) norm.
NORM='M'
The value max i,j a ij (not a norm).
Constraint: NORM='1', 'O', 'I', 'F', 'E' or 'M'.
2:   UPLO – CHARACTER(1)Input
On entry: specifies whether A is upper or lower trapezoidal.
UPLO='U'
A is upper trapezoidal.
UPLO='L'
A is lower trapezoidal.
Constraint: UPLO='U' or 'L'.
3:   DIAG – CHARACTER(1)Input
On entry: specifies whether A has nonunit or unit diagonal elements.
DIAG='N'
The diagonal elements are stored explicitly.
DIAG='U'
The diagonal elements are assumed to be 1, and are not referenced.
Constraint: DIAG='N' or 'U'.
4:   M – INTEGERInput
On entry: m, the number of rows of the matrix A.
When M=0, F06UJF is set to zero.
Constraint: M≥0.
5:   N – INTEGERInput
On entry: n, the number of columns of the matrix A.
When N=0, F06UJF is set to zero.
Constraint: N≥0.
6:   A LDA* – COMPLEX (KIND=nag_wp) arrayInput
Note: the second dimension of the array A must be at least N.
On entry: the m by n trapezoidal matrix A.
  • If UPLO='U', A is upper trapezoidal and the elements of the array below the diagonal are not referenced.
  • If UPLO='L', A is lower trapezoidal and the elements of the array above the diagonal are not referenced.
  • If DIAG='U', the diagonal elements of A are assumed to be 1, and are not referenced.
7:   LDA – INTEGERInput
On entry: the first dimension of the array A as declared in the (sub)program from which F06UJF is called.
Constraint: LDA≥ max 1,M .
8:   WORK* – REAL (KIND=nag_wp) arrayWorkspace
Note: the dimension of the array WORK must be at least max 1,M if NORM='I', and at least 1 otherwise.

6 Error Indicators and Warnings

None.

7 Accuracy

Not applicable.

8 Parallelism and Performance

F06UJF is not threaded in any implementation.

9 Further Comments

None.

10 Example

None.
F06 Chapter Contents
F06 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F06UKF : NAG Library, Mark 26

F06 Chapter Contents
F06 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F06UKF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
10 Example

1 Purpose

F06UKF returns, via the function name, the value of the 1-norm, the ∞-norm, the Frobenius norm, or the maximum absolute value of the elements of a complex n by n triangular matrix, stored in packed form.

2 Specification

FUNCTION F06UKF ( NORM, UPLO, DIAG, N, AP, WORK)
REAL (KIND=nag_wp) F06UKF
INTEGER | N
REAL (KIND=nag_wp) | WORK(*)
COMPLEX (KIND=nag_wp) | AP(*)
CHARACTER(1) | NORM, UPLO, DIAG

3 Description

None.

4 References

None.

5 Arguments

1:   NORM – CHARACTER(1)Input
On entry: specifies the value to be returned.
NORM='1' or 'O'
The 1-norm.
NORM='I'
The ∞-norm.
NORM='F' or 'E'
The Frobenius (or Euclidean) norm.
NORM='M'
The value max i,j a ij (not a norm).
Constraint: NORM='1', 'O', 'I', 'F', 'E' or 'M'.
2:   UPLO – CHARACTER(1)Input
On entry: specifies whether A is upper or lower triangular.
UPLO='U'
A is upper triangular.
UPLO='L'
A is lower triangular.
Constraint: UPLO='U' or 'L'.
3:   DIAG – CHARACTER(1)Input
On entry: specifies whether A has nonunit or unit diagonal elements.
DIAG='N'
The diagonal elements are stored explicitly.
DIAG='U'
The diagonal elements are assumed to be 1, and are not referenced.
Constraint: DIAG='N' or 'U'.
4:   N – INTEGERInput
On entry: n, the order of the matrix A.
When N=0, F06UKF returns zero.
Constraint: N≥0.
5:   AP* – COMPLEX (KIND=nag_wp) arrayInput
Note: the dimension of the array AP must be at least N× N+1/2 .
On entry: the n by n triangular matrix A, packed by columns.
More precisely,
  • if UPLO='U', the upper triangle of A must be stored with element A ij in AP i+j j-1/2 for i≤j;
  • if UPLO='L', the lower triangle of A must be stored with element A ij in AP i+2 n-jj-1/2 for i≥j.
If DIAG='U', the diagonal elements of A are assumed to be 1, and are not referenced; the same storage scheme is used whether DIAG='N' or ‘U’.
6:   WORK* – REAL (KIND=nag_wp) arrayWorkspace
Note: the dimension of the array WORK must be at least max 1,N if NORM='I', and at least 1 otherwise.

6 Error Indicators and Warnings

None.

7 Accuracy

Not applicable.

8 Parallelism and Performance

F06UKF is not threaded in any implementation.

9 Further Comments

None.

10 Example

None.
F06 Chapter Contents
F06 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F06ULF : NAG Library, Mark 26

F06 Chapter Contents
F06 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F06ULF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
10 Example

1 Purpose

F06ULF returns, via the function name, the value of the 1-norm, the ∞-norm, the Frobenius norm, or the maximum absolute value of the elements of a complex n by n triangular band matrix.

2 Specification

FUNCTION F06ULF ( NORM, UPLO, DIAG, N, K, AB, LDAB, WORK)
REAL (KIND=nag_wp) F06ULF
INTEGER | N, K, LDAB
REAL (KIND=nag_wp) | WORK(*)
COMPLEX (KIND=nag_wp) | AB(LDAB,*)
CHARACTER(1) | NORM, UPLO, DIAG

3 Description

None.

4 References

None.

5 Arguments

1:   NORM – CHARACTER(1)Input
On entry: specifies the value to be returned.
NORM='1' or 'O'
The 1-norm.
NORM='I'
The ∞-norm.
NORM='F' or 'E'
The Frobenius (or Euclidean) norm.
NORM='M'
The value max i,j a ij (not a norm).
Constraint: NORM='1', 'O', 'I', 'F', 'E' or 'M'.
2:   UPLO – CHARACTER(1)Input
On entry: specifies whether A is upper or lower triangular.
UPLO='U'
A is upper triangular.
UPLO='L'
A is lower triangular.
Constraint: UPLO='U' or 'L'.
3:   DIAG – CHARACTER(1)Input
On entry: specifies whether A has nonunit or unit diagonal elements.
DIAG='N'
The diagonal elements are stored explicitly.
DIAG='U'
The diagonal elements are assumed to be 1, and are not referenced.
Constraint: DIAG='N' or 'U'.
4:   N – INTEGERInput
On entry: n, the order of the matrix A.
When N=0, F06ULF returns zero.
Constraint: N≥0.
5:   K – INTEGERInput
On entry: k, the number of subdiagonals or superdiagonals of the matrix A.
Constraint: K≥0.
6:   AB LDAB* – COMPLEX (KIND=nag_wp) arrayInput
Note: the second dimension of the array AB must be at least N.
On entry: the n by n triangular band matrix A
The matrix is stored in rows 1 to k+1, more precisely,
  • if UPLO='U', the elements of the upper triangle of A within the band must be stored with element A ij in AB k+1+i-j j​ for ​max 1,j-k≤i≤j;
  • if UPLO='L', the elements of the lower triangle of A within the band must be stored with element A ij in AB 1+i-j j​ for ​j≤i≤min n,j+k.
If DIAG='U', the diagonal elements of A are assumed to be 1, and are not referenced.
7:   LDAB – INTEGERInput
On entry: the first dimension of the array AB as declared in the (sub)program from which F06ULF is called.
Constraint: LDAB≥K+1.
8:   WORK* – REAL (KIND=nag_wp) arrayWorkspace
Note: the dimension of the array WORK must be at least max 1,N if NORM='I', and at least 1 otherwise.

6 Error Indicators and Warnings

None.

7 Accuracy

Not applicable.

8 Parallelism and Performance

F06ULF is not threaded in any implementation.

9 Further Comments

None.

10 Example

None.
F06 Chapter Contents
F06 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F06UMF : NAG Library, Mark 26

F06 Chapter Contents
F06 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F06UMF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
10 Example

1 Purpose

F06UMF returns, via the function name, the value of the 1-norm, the ∞-norm, the Frobenius norm, or the maximum absolute value of the elements of a complex n by n upper Hessenberg matrix.

2 Specification

FUNCTION F06UMF ( NORM, N, A, LDA, WORK)
REAL (KIND=nag_wp) F06UMF
INTEGER | N, LDA
REAL (KIND=nag_wp) | WORK(*)
COMPLEX (KIND=nag_wp) | A(LDA,*)
CHARACTER(1) | NORM

3 Description

None.

4 References

None.

5 Arguments

1:   NORM – CHARACTER(1)Input
On entry: specifies the value to be returned.
NORM='1' or 'O'
The 1-norm.
NORM='I'
The ∞-norm.
NORM='F' or 'E'
The Frobenius (or Euclidean) norm.
NORM='M'
The value max i,j a ij (not a norm).
Constraint: NORM='1', 'O', 'I', 'F', 'E' or 'M'.
2:   N – INTEGERInput
On entry: n, the order of the matrix A.
When N=0, F06UMF returns zero.
Constraint: N≥0.
3:   A LDA* – COMPLEX (KIND=nag_wp) arrayInput
Note: the second dimension of the array A must be at least N.
On entry: the n by n upper Hessenberg matrix A; elements of the array below the first subdiagonal are not referenced.
4:   LDA – INTEGERInput
On entry: the first dimension of the array A as declared in the (sub)program from which F06UMF is called.
Constraint: LDA≥ max 1,N .
5:   WORK* – REAL (KIND=nag_wp) arrayWorkspace
Note: the dimension of the array WORK must be at least max 1,N if NORM='I', and at least 1 otherwise.

6 Error Indicators and Warnings

None.

7 Accuracy

Not applicable.

8 Parallelism and Performance

F06UMF is not threaded in any implementation.

9 Further Comments

None.

10 Example

None.
F06 Chapter Contents
F06 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F06UNF : NAG Library, Mark 26

F06 Chapter Contents
F06 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F06UNF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
10 Example

1 Purpose

F06UNF returns, via the function name, the value of the 1-norm, the ∞-norm, the Frobenius norm, or the maximum absolute value of the elements of a complex n by n tridiagonal matrix A.

2 Specification

FUNCTION F06UNF ( NORM, N, DL, D, DU)
REAL (KIND=nag_wp) F06UNF
INTEGER | N
COMPLEX (KIND=nag_wp) | DL(*), D(*), DU(*)
CHARACTER(1) | NORM

3 Description

None.

4 References

None.

5 Arguments

1:   NORM – CHARACTER(1)Input
On entry: specifies the value to be returned.
NORM='1' or 'O'
The 1-norm.
NORM='I'
The ∞-norm.
NORM='F' or 'E'
The Frobenius (or Euclidean) norm.
NORM='M'
The value max i,j a ij (not a norm).
Constraint: NORM='1', 'O', 'I', 'F', 'E' or 'M'.
2:   N – INTEGERInput
On entry: n, the order of the matrix A.
When N=0, F06UNF returns zero.
Constraint: N≥0.
3:   DL* – COMPLEX (KIND=nag_wp) arrayInput
Note: the dimension of the array DL must be at least max 1,N-1 .
On entry: the (n-1) subdiagonal elements of A.
4:   D* – COMPLEX (KIND=nag_wp) arrayInput
Note: the dimension of the array D must be at least max 1,N.
On entry: the n diagonal elements of A.
5:   DU* – COMPLEX (KIND=nag_wp) arrayInput
Note: the dimension of the array DU must be at least max 1,N-1 .
On entry: the (n-1) superdiagonal elements of A.

6 Error Indicators and Warnings

None.

7 Accuracy

Not applicable.

8 Parallelism and Performance

F06UNF is not threaded in any implementation.

9 Further Comments

None.

10 Example

None.
F06 Chapter Contents
F06 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F06UPF : NAG Library, Mark 26

F06 Chapter Contents
F06 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F06UPF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
10 Example

1 Purpose

F06UPF returns, via the function name, the value of the 1-norm, the ∞-norm, the Frobenius norm, or the maximum absolute value of the elements of a complex n by n Hermitian tridiagonal matrix A.

2 Specification

FUNCTION F06UPF ( NORM, N, D, E)
REAL (KIND=nag_wp) F06UPF
INTEGER | N
REAL (KIND=nag_wp) | D(*)
COMPLEX (KIND=nag_wp) | E(*)
CHARACTER(1) | NORM

3 Description

None.

4 References

None.

5 Arguments

1:   NORM – CHARACTER(1)Input
On entry: specifies the value to be returned.
NORM='1' or 'O'
The 1-norm.
NORM='I'
The ∞-norm.
NORM='F' or 'E'
The Frobenius (or Euclidean) norm.
NORM='M'
The value max i,j a ij (not a norm).
Constraint: NORM='1', 'O', 'I', 'F', 'E' or 'M'.
2:   N – INTEGERInput
On entry: n, the order of the matrix A.
When N=0, F06UPF returns zero.
Constraint: N≥0.
3:   D* – REAL (KIND=nag_wp) arrayInput
Note: the dimension of the array D must be at least max 1,N .
On entry: the n diagonal elements of the tridiagonal matrix A.
4:   E* – COMPLEX (KIND=nag_wp) arrayInput
Note: the dimension of the array E must be at least max 1,N-1 .
On entry: the (n-1) subdiagonal or superdiagonal elements of the tridiagonal matrix A.

6 Error Indicators and Warnings

None.

7 Accuracy

Not applicable.

8 Parallelism and Performance

F06UPF is not threaded in any implementation.

9 Further Comments

None.

10 Example

None.
F06 Chapter Contents
F06 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F06VJF : NAG Library, Mark 26

F06 Chapter Contents
F06 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F06VJF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
10 Example

1 Purpose

F06VJF permutes the rows or columns of a complex rectangular matrix using an integer array of permutations.

2 Specification

SUBROUTINE F06VJF ( SIDE, TRANS, N, PERM, K, B, LDB)
INTEGER | N, PERM(*), K, LDB
COMPLEX (KIND=nag_wp) | B(LDB,*)
CHARACTER(1) | SIDE, TRANS

3 Description

F06VJF performs one of the permutation operations
B←PT B, B←PB, B←B PT  or B←BP,
where B is a complex matrix, and P is a permutation matrix.
P is represented in the form
P=P 1,p 1P 2,p 2⋯P n,pn,
where P i,j is the permutation matrix that interchanges items i and j; that is, P i,j is the unit matrix with rows and columns i and j interchanged. If i=j, P i,j=I.
Let m denote the number of rows of B if SIDE='L', or the number of columns of B if SIDE='R': the routine does not require m to be passed as an argument, but assumes that m≥pi, for i=1,2,…,n.
This routine requires the indices pi to be supplied in an integer array; F06VKF performs the same operation with the indices supplied in a real array.

4 References

None.

5 Arguments

1:   SIDE – CHARACTER(1)Input
2:   TRANS – CHARACTER(1)Input
On entry: specifies the operation to be performed.
SIDE='L' and TRANS='T'
B←PT B.
SIDE='L' and TRANS='N'
B←PB.
SIDE='R' and TRANS='T'
B←B PT.
SIDE='R' and TRANS='N'
B←BP.
Constraints:
  • SIDE='L' or 'R';
  • TRANS='N' or 'T'.
3:   N – INTEGERInput
On entry: n, the number of interchanges in the representation of P.
Constraint: N≥0.
4:   PERM* – INTEGER arrayInput
Note: the dimension of the array PERM must be at least max 1,N .
On entry: the n indices pi which define the interchanges in the representation of P. It is usual to have pi≥i, but this is not necessary.
Constraint: 1≤PERM i≤m.
5:   K – INTEGERInput
On entry: k, the number of columns of B if SIDE='L', or the number of rows of B if SIDE='R'.
Constraint: K≥0.
6:   B LDB* – COMPLEX (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array B must be at least max 1,K if SIDE='L' and at least max 1,maxk PERM k if SIDE='R'.
On entry: the original matrix B; B is m by k if SIDE='L', or k by m if SIDE='R'.
On exit: the permuted matrix B.
7:   LDB – INTEGERInput
On entry: the first dimension of the array B as declared in the (sub)program from which F06VJF is called.
Constraints:
  • if SIDE='L', LDB≥ max 1,m ;
  • if SIDE='R', LDB≥ max 1,K .

6 Error Indicators and Warnings

None.

7 Accuracy

Not applicable.

8 Parallelism and Performance

F06VJF is not threaded in any implementation.

9 Further Comments

None.

10 Example

None.
F06 Chapter Contents
F06 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F06VKF : NAG Library, Mark 26

F06 Chapter Contents
F06 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F06VKF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
10 Example

1 Purpose

F06VKF permutes the rows or columns of a complex rectangular matrix using a real array of permutations.

2 Specification

SUBROUTINE F06VKF ( SIDE, TRANS, N, PERM, K, B, LDB)
INTEGER | N, K, LDB
REAL (KIND=nag_wp) | PERM(*)
COMPLEX (KIND=nag_wp) | B(LDB,*)
CHARACTER(1) | SIDE, TRANS

3 Description

F06VKF performs one of the permutation operations
B←PT B, B←PB, B←B PT  or B←BP,
where B is a complex matrix, and P is a permutation matrix.
P is represented in the form
P=P 1,p 1P 2,p 2⋯P n,pn,
where P i,j is the permutation matrix that interchanges items i and j; that is, P i,j is the unit matrix with rows and columns i and j interchanged. If i=j, P i,j=I.
Let m denote the number of rows of B if SIDE='L', or the number of columns of B if SIDE='R': the routine does not require m to be passed as an argument, but assumes that m≥pi, for i=1,2,…,n.
This routine requires the indices pi to be supplied in a real array (the routine takes the integer part of the array elements); F06VJF performs the same operation with the indices supplied in an integer array.

4 References

None.

5 Arguments

1:   SIDE – CHARACTER(1)Input
2:   TRANS – CHARACTER(1)Input
On entry: specifies the operation to be performed.
SIDE='L' and TRANS='T'
B←PT B.
SIDE='L' and TRANS='N'
B←PB.
SIDE='R' and TRANS='T'
B←B PT.
SIDE='R' and TRANS='N'
B←BP.
Constraints:
  • SIDE='L' or 'R';
  • TRANS='N' or 'T'.
3:   N – INTEGERInput
On entry: n, the number of interchanges in the representation of P.
Constraint: N≥0.
4:   PERM* – REAL (KIND=nag_wp) arrayInput
Note: the dimension of the array PERM must be at least max 1,N .
On entry: the n indices pi which define the interchanges in the representation of P. It is usual to have pi≥i, but this is not necessary.
Constraint: 1≤PERM i≤m.
5:   K – INTEGERInput
On entry: k, the number of columns of B if SIDE='L', or the number of rows of B if SIDE='R'.
Constraint: K≥0.
6:   B LDB* – COMPLEX (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array B must be at least max 1,K if SIDE='L' and at least max 1,maxk int⁡PERM k if SIDE='R'.
On entry: the original matrix B; B is m by k if SIDE='L', or k by m if SIDE='R'.
On exit: the permuted matrix B.
7:   LDB – INTEGERInput
On entry: the first dimension of the array B as declared in the (sub)program from which F06VKF is called.
Constraints:
  • if SIDE='L', LDB≥ max 1,m ;
  • if SIDE='R', LDB≥ max 1,K .

6 Error Indicators and Warnings

None.

7 Accuracy

Not applicable.

8 Parallelism and Performance

F06VKF is not threaded in any implementation.

9 Further Comments

None.

10 Example

None.
F06 Chapter Contents
F06 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F06VXF : NAG Library, Mark 26

F06 Chapter Contents
F06 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F06VXF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
10 Example

1 Purpose

F06VXF applies to a complex rectangular matrix a sequence of plane rotations having real cosines and complex sines.

2 Specification

SUBROUTINE F06VXF ( SIDE, PIVOT, DIRECT, M, N, K1, K2, C, S, A, LDA)
INTEGER | M, N, K1, K2, LDA
REAL (KIND=nag_wp) | C(*), S(*)
COMPLEX (KIND=nag_wp) | A(LDA,*)
CHARACTER(1) | SIDE, PIVOT, DIRECT

3 Description

F06VXF performs the transformation
A←PA   or   A←A PH ,
where A is an m by n complex matrix and P is a real orthogonal matrix, defined as a sequence of real plane rotations, Pk, applied in planes k 1 to k 2.
The 2 by 2 plane rotation part of Pk is assumed to have the form
ck sk -sk ck
with ck and sk real.

4 References

None.

5 Arguments

1:   SIDE – CHARACTER(1)Input
On entry: specifies whether A is operated on from the left or the right.
SIDE='L'
A is pre-multiplied from the left.
SIDE='R'
A is post-multiplied from the right.
Constraint: SIDE='L' or 'R'.
2:   PIVOT – CHARACTER(1)Input
On entry: specifies the plane rotated by Pk.
PIVOT='V' (variable pivot)
Pk rotates the k,k+1 plane.
PIVOT='T' (top pivot)
Pk rotates the k 1,k+1 plane.
PIVOT='B' (bottom pivot)
Pk rotates the k,k 2 plane.
Constraint: PIVOT='V', 'T' or 'B'.
3:   DIRECT – CHARACTER(1)Input
On entry: specifies the sequence direction.
DIRECT='F' (forward sequence)
P=P k 2-1⋯P k 1+1P k 1.
DIRECT='B' (backward sequence)
P=P k 1P k 1+1⋯P k 2-1.
Constraint: DIRECT='F' or 'B'.
4:   M – INTEGERInput
On entry: m, the number of rows of the matrix A.
Constraint: M≥0.
5:   N – INTEGERInput
On entry: n, the number of columns of the matrix A.
Constraint: N≥0.
6:   K1 – INTEGERInput
7:   K2 – INTEGERInput
On entry: the values k 1 and k 2.
If K1<1 or K2≤K1, or SIDE='L' and K2>M, or SIDE='R' and K2>N, an immediate return is effected.
8:   C* – REAL (KIND=nag_wp) arrayInput
Note: the dimension of the array C must be at least K2-K1.
On entry: C k must hold ck, the cosine of the rotation Pk, for k=k 1,…,k 2-1.
9:   S* – REAL (KIND=nag_wp) arrayInput
Note: the dimension of the array S must be at least K2-K1.
On entry: S k must hold sk, the sine of the rotation Pk, for k=k 1,…,k 2-1.
10:   A LDA* – COMPLEX (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array A must be at least N.
On entry: the m by n matrix A.
On exit: the transformed matrix A.
11:   LDA – INTEGERInput
On entry: the first dimension of the array A as declared in the (sub)program from which F06VXF is called.
Constraint: LDA≥ max 1,M .

6 Error Indicators and Warnings

None.

7 Accuracy

Not applicable.

8 Parallelism and Performance

F06VXF is not threaded in any implementation.

9 Further Comments

None.

10 Example

None.
F06 Chapter Contents
F06 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F06WAF (DLANSF) : NAG Library, Mark 26

F06 Chapter Contents
F06 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F06WAF (DLANSF)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F06WAF (DLANSF) returns the value of the 1-norm, the ∞-norm, the Frobenius norm, or the maximum absolute value of the elements of a real symmetric matrix A stored in Rectangular Full Packed (RFP) format.

2 Specification

FUNCTION F06WAF ( NORM, TRANSR, UPLO, N, AR, WORK)
REAL (KIND=nag_wp) F06WAF
INTEGER | N
REAL (KIND=nag_wp) | AR(N*(N+1)/2), WORK(*)
CHARACTER(1) | NORM, TRANSR, UPLO
The routine may be called by its LAPACK name dlansf.

3 Description

Given a real n by n symmetric matrix, A, F06WAF (DLANSF) calculates one of the values given by
A 1=maxj⁡∑i=1 n a ij | (the 1-norm of A),
A∞=maxi⁡∑j= 1 n a ij | (the ∞-norm of A),
A F=∑i=1 n∑j=1 n a ij 2 1/2 | (the Frobenius norm of A), or
max i,j a ij | (the maximum absolute element value of A).
A is stored in compact form using the RFP format. The RFP storage format is described in Section 3.3.3 in the F07 Chapter Introduction.

4 References

Basic Linear Algebra Subprograms Technical (BLAST) Forum (2001) Basic Linear Algebra Subprograms Technical (BLAST) Forum Standard University of Tennessee, Knoxville, Tennessee http://www.netlib.org/blas/blast-forum/blas-report.pdf
Gustavson F G, Waśniewski J, Dongarra J J and Langou J (2010) Rectangular full packed format for Cholesky's algorithm: factorization, solution, and inversion ACM Trans. Math. Software 37, 2

5 Arguments

1:   NORM – CHARACTER(1)Input
On entry: specifies the value to be returned.
NORM='1' or 'O'
The 1-norm.
NORM='I'
The ∞-norm.
NORM='F' or 'E'
The Frobenius (or Euclidean) norm.
NORM='M'
The value max i,j a ij (not a norm).
Constraint: NORM='1', 'O', 'I', 'F', 'E' or 'M'.
2:   TRANSR – CHARACTER(1)Input
On entry: specifies whether the RFP representation of A is normal or transposed.
TRANSR='N'
The matrix A is stored in normal RFP format.
TRANSR='T'
The matrix A is stored in transposed RFP format.
Constraint: TRANSR='N' or 'T'.
3:   UPLO – CHARACTER(1)Input
On entry: specifies whether the upper or lower triangular part of A is stored.
UPLO='U'
The upper triangular part of A is stored.
UPLO='L'
The lower triangular part of A is stored.
Constraint: UPLO='U' or 'L'.
4:   N – INTEGERInput
On entry: n, the order of the matrix A.
When N=0, F06WAF (DLANSF) returns zero.
Constraint: N≥0.
5:   AR N×N+1/2 – REAL (KIND=nag_wp) arrayInput
On entry: the upper or lower triangular part (as specified by UPLO) of the n by n symmetric matrix A, in either normal or transposed RFP format (as specified by TRANSR). The storage format is described in detail in Section 3.3.3 in the F07 Chapter Introduction.
6:   WORK* – REAL (KIND=nag_wp) arrayWorkspace
Note: the dimension of the array WORK must be at least max 1,N if NORM='1', 'O' or 'I', and at least 1 otherwise.

6 Error Indicators and Warnings

None.

7 Accuracy

The BLAS standard requires accurate implementations which avoid unnecessary over/underflow (see Section 2.7 of Basic Linear Algebra Subprograms Technical (BLAST) Forum (2001)).

8 Parallelism and Performance

F06WAF (DLANSF) is not threaded in any implementation.

9 Further Comments

None.

10 Example

This example reads in the lower triangular part of a symmetric matrix, converts this to RFP format, then calculates the norm of the matrix for each of the available norm types.

10.1 Program Text

Program Text (f06wafe.f90)

10.2 Program Data

Program Data (f06wafe.d)

10.3 Program Results

Program Results (f06wafe.r)

F06 Chapter Contents
F06 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F06WBF (DTFSM) : NAG Library, Mark 26

F06 Chapter Contents
F06 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F06WBF (DTFSM)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F06WBF (DTFSM) performs one of the matrix-matrix operations
B←α A-1 B , B←α A-T B , B←αB A-1   or B←αB A-T ,
where A is a real triangular matrix stored in Rectangular Full Packed (RFP) format, B is an m by n real matrix, and α is a real scalar. A-T denotes AT-1 or equivalently A-1 T .
No test for singularity or near-singularity of A is included in this routine. Such tests must be performed before calling this routine.

2 Specification

SUBROUTINE F06WBF ( TRANSR, SIDE, UPLO, TRANS, DIAG, M, N, ALPHA, AR, B, LDB)
INTEGER | M, N, LDB
REAL (KIND=nag_wp) | ALPHA, AR(*), B(LDB,*)
CHARACTER(1) | TRANSR, SIDE, UPLO, TRANS, DIAG
The routine may be called by its LAPACK name dtfsm.

3 Description

F06WBF (DTFSM) solves (for X) a triangular linear system of one of the forms
AX=αB , AT X=αB , XA=αB   or X AT=αB ,
where A is a real triangular matrix stored in RFP format, B, X are m by n real matrices, and α is a real scalar. The RFP storage format is described in Section 3.3.3 in the F07 Chapter Introduction.

4 References

Gustavson F G, Waśniewski J, Dongarra J J and Langou J (2010) Rectangular full packed format for Cholesky's algorithm: factorization, solution, and inversion ACM Trans. Math. Software 37, 2

5 Arguments

1:   TRANSR – CHARACTER(1)Input
On entry: specifies whether the RFP representation of A is normal or transposed.
TRANSR='N'
The matrix A is stored in normal RFP format.
TRANSR='T'
The matrix A is stored in transposed RFP format.
Constraint: TRANSR='N' or 'T'.
2:   SIDE – CHARACTER(1)Input
On entry: specifies whether B is operated on from the left or the right, or similarly whether A (or its transpose) appears to the left or right of the solution matrix in the linear system to be solved.
SIDE='L'
B is pre-multiplied from the left. The system to be solved has the form AX=αB or AT X=αB.
SIDE='R'
B is post-multiplied from the right. The system to be solved has the form XA=αB or X AT=αB.
Constraint: SIDE='L' or 'R'.
3:   UPLO – CHARACTER(1)Input
On entry: specifies whether A is upper or lower triangular.
UPLO='U'
A is upper triangular.
UPLO='L'
A is lower triangular.
Constraint: UPLO='U' or 'L'.
4:   TRANS – CHARACTER(1)Input
On entry: specifies whether the operation involves A-1 or A-T, i.e., whether or not A is transposed in the linear system to be solved.
TRANS='N'
The operation involves A-1, i.e., A is not transposed.
TRANS='T'
The operation involves A-T, i.e., A is transposed.
Constraint: TRANS='N' or 'T'.
5:   DIAG – CHARACTER(1)Input
On entry: specifies whether A has nonunit or unit diagonal elements.
DIAG='N'
The diagonal elements of A are stored explicitly.
DIAG='U'
The diagonal elements of A are assumed to be 1, the corresponding elements of AR are not referenced.
Constraint: DIAG='N' or 'U'.
6:   M – INTEGERInput
On entry: m, the number of rows of the matrix B.
Constraint: M≥0.
7:   N – INTEGERInput
On entry: n, the number of columns of the matrix B.
Constraint: N≥0.
8:   ALPHA – REAL (KIND=nag_wp)Input
On entry: the scalar α.
9:   AR* – REAL (KIND=nag_wp) arrayInput
Note: the dimension of the array AR must be at least max 1,M×M+1/2 if SIDE='L' and at least max 1,N×N+1/2 if SIDE='R'.
On entry: A, the m by m triangular matrix A if SIDE='L' or the n by n triangular matrix A if SIDE='R', stored in RFP format (as specified by TRANSR). The storage format is described in detail in Section 3.3.3 in the F07 Chapter Introduction. If ALPHA=0.0, AR is not referenced.
10:   B LDB* – REAL (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array B must be at least max 1,N.
On entry: the m by n matrix B.
If ALPHA=0, B need not be set.
On exit: the updated matrix B, or similarly the solution matrix X.
11:   LDB – INTEGERInput
On entry: the first dimension of the array B as declared in the (sub)program from which F06WBF (DTFSM) is called.
Constraint: LDB≥ max 1,M .

6 Error Indicators and Warnings

None.

7 Accuracy

Not applicable.

8 Parallelism and Performance

F06WBF (DTFSM) makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

None.

10 Example

This example reads in the lower triangular part of a symmetric matrix A which it converts to RFP format. It also reads in α and a 6 by 4 matrix B and then performs the matrix-matrix operation B←α A-1 B.

10.1 Program Text

Program Text (f06wbfe.f90)

10.2 Program Data

Program Data (f06wbfe.d)

10.3 Program Results

Program Results (f06wbfe.r)

F06 Chapter Contents
F06 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F06WCF (DSFRK) : NAG Library, Mark 26

F06 Chapter Contents
F06 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F06WCF (DSFRK)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F06WCF (DSFRK) performs one of the symmetric rank-k update operations
C←αA AT + βC   or   C←α AT A + βC ,
where A is a real matrix, C is an n by n real symmetric matrix stored in Rectangular Full Packed (RFP) format, and α and β are real scalars.

2 Specification

SUBROUTINE F06WCF ( TRANSR, UPLO, TRANS, N, K, ALPHA, A, LDA, BETA, CR)
INTEGER | N, K, LDA
REAL (KIND=nag_wp) | ALPHA, A(LDA,*), BETA, CR(N*(N+1)/2)
CHARACTER(1) | TRANSR, UPLO, TRANS
The routine may be called by its LAPACK name dsfrk.

3 Description

F06WCF (DSFRK) performs one of the symmetric rank-k update operations
C←αA AT + βC   or   C←α AT A + βC ,
where A is a real matrix, C is an n by n real symmetric matrix stored in Rectangular Full Packed (RFP) format, and α and β are real scalars. The RFP storage format is described in Section 3.3.3 in the F07 Chapter Introduction.
If n=0 or if β=1.0 and either k=0 or α=0.0 then F06WCF (DSFRK) returns immediately. If β=0.0 and either k=0 or α=0.0 then C is set to the zero matrix.

4 References

Gustavson F G, Waśniewski J, Dongarra J J and Langou J (2010) Rectangular full packed format for Cholesky's algorithm: factorization, solution, and inversion ACM Trans. Math. Software 37, 2

5 Arguments

1:   TRANSR – CHARACTER(1)Input
On entry: specifies whether the RFP representation of C is normal or transposed.
TRANSR='N'
The matrix C is stored in normal RFP format.
TRANSR='T'
The matrix C is stored in transposed RFP format.
Constraint: TRANSR='N' or 'T'.
2:   UPLO – CHARACTER(1)Input
On entry: specifies whether the upper or lower triangular part of C is stored in RFP format.
UPLO='U'
The upper triangular part of C is stored in RFP format.
UPLO='L'
The lower triangular part of C is stored in RFP format.
Constraint: UPLO='U' or 'L'.
3:   TRANS – CHARACTER(1)Input
On entry: specifies the operation to be performed.
TRANS='N'
C←αA AT+βC.
TRANS='T'
C←α AT A+βC.
Constraint: TRANS='N' or 'T'.
4:   N – INTEGERInput
On entry: n, the order of the matrix C.
Constraint: N≥0.
5:   K – INTEGERInput
On entry: k, the number of columns of A if TRANS='N', or the number of rows of A if TRANS='T'.
Constraint: K≥0.
6:   ALPHA – REAL (KIND=nag_wp)Input
On entry: the scalar α.
7:   A LDA* – REAL (KIND=nag_wp) arrayInput
Note: the second dimension of the array A must be at least max 1,K if TRANS='N' and at least max 1,N if TRANS='T'.
On entry: the matrix A; A is n by k if TRANS='N', or k by n if TRANS='T'. If ALPHA=0.0, A is not referenced.
8:   LDA – INTEGERInput
On entry: the first dimension of the array A as declared in the (sub)program from which F06WCF (DSFRK) is called.
Constraints:
  • if TRANS='N', LDA≥ max 1,N ;
  • if TRANS='T', LDA≥ max 1,K .
9:   BETA – REAL (KIND=nag_wp)Input
On entry: the scalar β.
10:   CR N×N+1/2 – REAL (KIND=nag_wp) arrayInput/Output
On entry: the upper or lower triangular part (as specified by UPLO) of the n by n symmetric matrix C, stored in RFP format (as specified by TRANSR). The storage format is described in detail in Section 3.3.3 in the F07 Chapter Introduction.
On exit: the updated matrix C, that is its upper or lower triangular part stored in RFP format.

6 Error Indicators and Warnings

None.

7 Accuracy

Not applicable.

8 Parallelism and Performance

F06WCF (DSFRK) makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

None.

10 Example

This example reads in the lower triangular part of a symmetric matrix C which it converts to RFP format. It also reads in α, β and a 6 by 4 matrix A and then performs the symmetric rank-4 update C←αA AT+βC.

10.1 Program Text

Program Text (f06wcfe.f90)

10.2 Program Data

Program Data (f06wcfe.d)

10.3 Program Results

Program Results (f06wcfe.r)

F06 Chapter Contents
F06 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F06WNF (ZLANHF) : NAG Library, Mark 26

F06 Chapter Contents
F06 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F06WNF (ZLANHF)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F06WNF (ZLANHF) returns the value of the 1-norm, the ∞-norm, the Frobenius norm, or the maximum absolute value of the elements of a complex Hermitian matrix A stored in Rectangular Full Packed (RFP) format.

2 Specification

FUNCTION F06WNF ( NORM, TRANSR, UPLO, N, AR, WORK)
REAL (KIND=nag_wp) F06WNF
INTEGER | N
REAL (KIND=nag_wp) | WORK(*)
COMPLEX (KIND=nag_wp) | AR(N*(N+1)/2)
CHARACTER(1) | NORM, TRANSR, UPLO
The routine may be called by its LAPACK name zlanhf.

3 Description

Given a complex n by n symmetric matrix, A, F06WNF (ZLANHF) calculates one of the values given by
A 1=maxj⁡∑i=1 n a ij | (the 1-norm of A),
A∞=maxi⁡∑j= 1 n a ij | (the ∞-norm of A),
A F=∑i=1 n∑j=1 n a ij 2 1/2 | (the Frobenius norm of A), or
max i,j a ij | (the maximum absolute element value of A).
A is stored in compact form using the RFP format. The RFP storage format is described in Section 3.3.3 in the F07 Chapter Introduction.

4 References

Basic Linear Algebra Subprograms Technical (BLAST) Forum (2001) Basic Linear Algebra Subprograms Technical (BLAST) Forum Standard University of Tennessee, Knoxville, Tennessee http://www.netlib.org/blas/blast-forum/blas-report.pdf
Gustavson F G, Waśniewski J, Dongarra J J and Langou J (2010) Rectangular full packed format for Cholesky's algorithm: factorization, solution, and inversion ACM Trans. Math. Software 37, 2

5 Arguments

1:   NORM – CHARACTER(1)Input
On entry: specifies the value to be returned.
NORM='1' or 'O'
The 1-norm.
NORM='I'
The ∞-norm.
NORM='F' or 'E'
The Frobenius (or Euclidean) norm.
NORM='M'
The value max i,j a ij (not a norm).
Constraint: NORM='1', 'O', 'I', 'F', 'E' or 'M'.
2:   TRANSR – CHARACTER(1)Input
On entry: specifies whether the normal RFP representation of A or its conjugate transpose is stored.
TRANSR='N'
The matrix A is stored in normal RFP format.
TRANSR='C'
The conjugate transpose of the RFP representation of the matrix A is stored.
Constraint: TRANSR='N' or 'C'.
3:   UPLO – CHARACTER(1)Input
On entry: specifies whether the upper or lower triangular part of A is stored.
UPLO='U'
The upper triangular part of A is stored.
UPLO='L'
The lower triangular part of A is stored.
Constraint: UPLO='U' or 'L'.
4:   N – INTEGERInput
On entry: n, the order of the matrix A.
When N=0, F06WNF (ZLANHF) returns zero.
Constraint: N≥0.
5:   AR N×N+1/2 – COMPLEX (KIND=nag_wp) arrayInput
On entry: the upper or lower triangular part (as specified by UPLO) of the n by n Hermitian matrix A, in either normal or transposed RFP format (as specified by TRANSR). The storage format is described in detail in Section 3.3.3 in the F07 Chapter Introduction.
6:   WORK* – REAL (KIND=nag_wp) arrayWorkspace
Note: the dimension of the array WORK must be at least max 1,N if NORM='1', 'O' or 'I', and at least 1 otherwise.

6 Error Indicators and Warnings

None.

7 Accuracy

The BLAS standard requires accurate implementations which avoid unnecessary over/underflow (see Section 2.7 of Basic Linear Algebra Subprograms Technical (BLAST) Forum (2001)).

8 Parallelism and Performance

F06WNF (ZLANHF) is not threaded in any implementation.

9 Further Comments

None.

10 Example

This example reads in the lower triangular part of a symmetric matrix, converts this to RFP format, then calculates the norm of the matrix for each of the available norm types.

10.1 Program Text

Program Text (f06wnfe.f90)

10.2 Program Data

Program Data (f06wnfe.d)

10.3 Program Results

Program Results (f06wnfe.r)

F06 Chapter Contents
F06 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F06WPF (ZTFSM) : NAG Library, Mark 26

F06 Chapter Contents
F06 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F06WPF (ZTFSM)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F06WPF (ZTFSM) performs one of the matrix-matrix operations
B←α A-1 B , B←α A-H B , B←αB A-1   or B←αB A-H ,
where A is a complex triangular matrix stored in Rectangular Full Packed (RFP) format, B is an m by n complex matrix, and α is a complex scalar. A-H denotes AH-1 or equivalently A-1 H .
No test for singularity or near-singularity of A is included in this routine. Such tests must be performed before calling this routine.

2 Specification

SUBROUTINE F06WPF ( TRANSR, SIDE, UPLO, TRANS, DIAG, M, N, ALPHA, AR, B, LDB)
INTEGER | M, N, LDB
COMPLEX (KIND=nag_wp) | ALPHA, AR(*), B(LDB,*)
CHARACTER(1) | TRANSR, SIDE, UPLO, TRANS, DIAG
The routine may be called by its LAPACK name ztfsm.

3 Description

F06WPF (ZTFSM) solves (for X) a triangular linear system of one of the forms
AX=αB , AH X=αB , XA=αB   or X AH=αB ,
where A is a complex triangular matrix stored in RFP format, B, X are m by n complex matrices, and α is a complex scalar. The RFP storage format is described in Section 3.3.3 in the F07 Chapter Introduction.

4 References

Gustavson F G, Waśniewski J, Dongarra J J and Langou J (2010) Rectangular full packed format for Cholesky's algorithm: factorization, solution, and inversion ACM Trans. Math. Software 37, 2

5 Arguments

1:   TRANSR – CHARACTER(1)Input
On entry: specifies whether the normal RFP representation of A or its conjugate transpose is stored.
TRANSR='N'
The matrix A is stored in normal RFP format.
TRANSR='C'
The conjugate transpose of the RFP representation of the matrix A is stored.
Constraint: TRANSR='N' or 'C'.
2:   SIDE – CHARACTER(1)Input
On entry: specifies whether B is operated on from the left or the right, or similarly whether A (or its transpose) appears to the left or right of the solution matrix in the linear system to be solved.
SIDE='L'
B is pre-multiplied from the left. The system to be solved has the form AX=αB or AT X=αB.
SIDE='R'
B is post-multiplied from the right. The system to be solved has the form XA=αB or X AT=αB.
Constraint: SIDE='L' or 'R'.
3:   UPLO – CHARACTER(1)Input
On entry: specifies whether A is upper or lower triangular.
UPLO='U'
A is upper triangular.
UPLO='L'
A is lower triangular.
Constraint: UPLO='U' or 'L'.
4:   TRANS – CHARACTER(1)Input
On entry: specifies whether the operation involves A-1 or A-H, i.e., whether or not A is transpose conjugated in the linear system to be solved.
TRANS='N'
The operation involves A-1, i.e., A is not transpose conjugated.
TRANS='C'
The operation involves A-H, i.e., A is transpose conjugated.
Constraint: TRANS='N' or 'C'.
5:   DIAG – CHARACTER(1)Input
On entry: specifies whether A has nonunit or unit diagonal elements.
DIAG='N'
The diagonal elements of A are stored explicitly.
DIAG='U'
The diagonal elements of A are assumed to be 1, the corresponding elements of AR are not referenced.
Constraint: DIAG='N' or 'U'.
6:   M – INTEGERInput
On entry: m, the number of rows of the matrix B.
Constraint: M≥0.
7:   N – INTEGERInput
On entry: n, the number of columns of the matrix B.
Constraint: N≥0.
8:   ALPHA – COMPLEX (KIND=nag_wp)Input
On entry: the scalar α.
9:   AR* – COMPLEX (KIND=nag_wp) arrayInput
Note: the dimension of the array AR must be at least max 1,M×M+1/2 if SIDE='L' and at least max 1,N×N+1/2 if SIDE='R'.
On entry: A, the m by m triangular matrix A if SIDE='L' or the n by n triangular matrix A if SIDE='R', stored in RFP format (as specified by TRANSR). The storage format is described in detail in Section 3.3.3 in the F07 Chapter Introduction. If ALPHA=0.0, AR is not referenced.
10:   B LDB* – COMPLEX (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array B must be at least max 1,N.
On entry: the m by n matrix B.
If ALPHA=0, B need not be set.
On exit: the updated matrix B, or similarly the solution matrix X.
11:   LDB – INTEGERInput
On entry: the first dimension of the array B as declared in the (sub)program from which F06WPF (ZTFSM) is called.
Constraint: LDB≥ max 1,M .

6 Error Indicators and Warnings

None.

7 Accuracy

Not applicable.

8 Parallelism and Performance

F06WPF (ZTFSM) makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

None.

10 Example

This example reads in the upper triangular part of a symmetric matrix A which it converts to RFP format. It also reads in α and a 4 by 3 matrix B and then performs the matrix-matrix operation B←α A-1 B.

10.1 Program Text

Program Text (f06wpfe.f90)

10.2 Program Data

Program Data (f06wpfe.d)

10.3 Program Results

Program Results (f06wpfe.r)

F06 Chapter Contents
F06 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F06WQF (ZHFRK) : NAG Library, Mark 26

F06 Chapter Contents
F06 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F06WQF (ZHFRK)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F06WQF (ZHFRK) performs one of the Hermitian rank-k update operations
C←αA AH + βC   or   C←α AH A + βC ,
where A is a complex matrix, C is an n by n complex Hermitian matrix stored in Rectangular Full Packed (RFP) format, and α and β are real scalars.

2 Specification

SUBROUTINE F06WQF ( TRANSR, UPLO, TRANS, N, K, ALPHA, A, LDA, BETA, CR)
INTEGER | N, K, LDA
REAL (KIND=nag_wp) | ALPHA, BETA
COMPLEX (KIND=nag_wp) | A(LDA,*), CR(N*(N+1)/2)
CHARACTER(1) | TRANSR, UPLO, TRANS
The routine may be called by its LAPACK name zhfrk.

3 Description

F06WQF (ZHFRK) performs one of the Hermitian rank-k update operations
C←αA AH + βC   or   C←α AH A + βC ,
where A is a complex matrix, C is an n by n complex Hermitian matrix stored in Rectangular Full Packed (RFP) format, and α and β are real scalars. The RFP storage format is described in Section 3.3.3 in the F07 Chapter Introduction.
If n=0 or if β=1.0 and either k=0 or α=0.0 then F06WQF (ZHFRK) returns immediately. If β=0.0 and either k=0 or α=0.0 then C is set to the zero matrix.

4 References

Gustavson F G, Waśniewski J, Dongarra J J and Langou J (2010) Rectangular full packed format for Cholesky's algorithm: factorization, solution, and inversion ACM Trans. Math. Software 37, 2

5 Arguments

1:   TRANSR – CHARACTER(1)Input
On entry: specifies whether the normal RFP representation of C or its conjugate transpose is stored.
TRANSR='N'
The matrix C is stored in normal RFP format.
TRANSR='C'
The conjugate transpose of the RFP representation of the matrix C is stored.
Constraint: TRANSR='N' or 'C'.
2:   UPLO – CHARACTER(1)Input
On entry: specifies whether the upper or lower triangular part of C is stored in RFP format.
UPLO='U'
The upper triangular part of C is stored in RFP format.
UPLO='L'
The lower triangular part of C is stored in RFP format.
Constraint: UPLO='U' or 'L'.
3:   TRANS – CHARACTER(1)Input
On entry: specifies the operation to be performed.
TRANS='N'
C←αA AH+βC.
TRANS='C'
C←α AH A+βC.
Constraint: TRANS='N' or 'C'.
4:   N – INTEGERInput
On entry: n, the order of the matrix C.
Constraint: N≥0.
5:   K – INTEGERInput
On entry: k, the number of columns of A if TRANS='N', or the number of rows of A if TRANS='C'.
Constraint: K≥0.
6:   ALPHA – REAL (KIND=nag_wp)Input
On entry: the scalar α.
7:   A LDA* – COMPLEX (KIND=nag_wp) arrayInput
Note: the second dimension of the array A must be at least max 1,K if TRANS='N' and at least max 1,N if TRANS='C'.
On entry: the matrix A; A is n by k if TRANS='N', or k by n if TRANS='C'. If ALPHA=0.0, A is not referenced.
8:   LDA – INTEGERInput
On entry: the first dimension of the array A as declared in the (sub)program from which F06WQF (ZHFRK) is called.
Constraints:
  • if TRANS='N', LDA≥ max 1,N ;
  • if TRANS='C', LDA≥ max 1,K .
9:   BETA – REAL (KIND=nag_wp)Input
On entry: the scalar β.
10:   CR N×N+1/2 – COMPLEX (KIND=nag_wp) arrayInput/Output
On entry: the upper or lower triangular part (as specified by UPLO) of the n by n Hermitian matrix C, stored in RFP format (as specified by TRANSR). The storage format is described in detail in Section 3.3.3 in the F07 Chapter Introduction.
On exit: the updated matrix C, that is its upper or lower triangular part stored in RFP format.

6 Error Indicators and Warnings

None.

7 Accuracy

Not applicable.

8 Parallelism and Performance

F06WQF (ZHFRK) makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

None.

10 Example

This example reads in the lower triangular part of a symmetric matrix C which it converts to RFP format. It also reads in α, β and a 4 by 3 matrix A and then performs the Hermitian rank-3 update C←αA AH+βC.

10.1 Program Text

Program Text (f06wqfe.f90)

10.2 Program Data

Program Data (f06wqfe.d)

10.3 Program Results

Program Results (f06wqfe.r)

F06 Chapter Contents
F06 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F06YAF (DGEMM) : NAG Library, Mark 26

F06 Chapter Contents
F06 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F06YAF (DGEMM)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
10 Example

1 Purpose

F06YAF (DGEMM) performs one of the matrix-matrix operations
C←αAB+βC, C←α AT B+βC, C←αA BT+βC  or C←α ATBT+βC,
where A, B and C are real matrices, and α and β are real scalars; C is always m by n.

2 Specification

SUBROUTINE F06YAF ( TRANSA, TRANSB, M, N, K, ALPHA, A, LDA, B, LDB, BETA, C, LDC)
INTEGER | M, N, K, LDA, LDB, LDC
REAL (KIND=nag_wp) | ALPHA, A(LDA,*), B(LDB,*), BETA, C(LDC,*)
CHARACTER(1) | TRANSA, TRANSB
The routine may be called by its BLAS name dgemm.

3 Description

None.

4 References

None.

5 Arguments

1:   TRANSA – CHARACTER(1)Input
On entry: specifies whether the operation involves A or AT.
TRANSA='N'
The operation involves A.
TRANSA='T' or 'C'
The operation involves AT.
Constraint: TRANSA='N', 'T' or 'C'.
2:   TRANSB – CHARACTER(1)Input
On entry: specifies whether the operation involves B or BT.
TRANSB='N'
The operation involves B.
TRANSB='T' or 'C'
The operation involves BT.
Constraint: TRANSB='N', 'T' or 'C'.
3:   M – INTEGERInput
On entry: m, the number of rows of the matrix C; the number of rows of A if TRANSA='N', or the number of columns of A if TRANSA='T' or 'C'.
Constraint: M≥0.
4:   N – INTEGERInput
On entry: n, the number of columns of the matrix C; the number of columns of B if TRANSB='N', or the number of rows of B if TRANSB='T' or 'C'.
Constraint: N≥0.
5:   K – INTEGERInput
On entry: k, the number of columns of A if TRANSA='N', or the number of rows of A if TRANSA='T' or 'C'; the number of rows of B if TRANSB='N', or the number of columns of B if TRANSB='T' or 'C'.
Constraint: K≥0.
6:   ALPHA – REAL (KIND=nag_wp)Input
On entry: the scalar α.
7:   A LDA* – REAL (KIND=nag_wp) arrayInput
Note: the second dimension of the array A must be at least max 1,K if TRANSA='N' and at least max 1,M if TRANSA='T' or 'C'.
On entry: the matrix A; A is m by k if TRANSA='N', or k by m if TRANSA='T' or 'C'.
8:   LDA – INTEGERInput
On entry: the first dimension of the array A as declared in the (sub)program from which F06YAF (DGEMM) is called.
Constraints:
  • if TRANSA='N', LDA≥ max 1,M ;
  • if TRANSA='T' or 'C', LDA≥ max 1,K .
9:   B LDB* – REAL (KIND=nag_wp) arrayInput
Note: the second dimension of the array B must be at least max 1,N if TRANSB='N' and at least max 1,K if TRANSB='T' or 'C'.
On entry: the matrix B; B is k by n if TRANSB='N', or n by k if TRANSB='T' or 'C'.
10:   LDB – INTEGERInput
On entry: the first dimension of the array B as declared in the (sub)program from which F06YAF (DGEMM) is called.
Constraints:
  • if TRANSB='N', LDB≥ max 1,K ;
  • if TRANSB='T' or 'C', LDB≥ max 1,N .
11:   BETA – REAL (KIND=nag_wp)Input
On entry: the scalar β.
12:   C LDC* – REAL (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array C must be at least max 1,N.
On entry: the m by n matrix C.
If BETA=0, C need not be set.
On exit: the updated matrix C.
13:   LDC – INTEGERInput
On entry: the first dimension of the array C as declared in the (sub)program from which F06YAF (DGEMM) is called.
Constraint: LDC≥ max 1,M .

6 Error Indicators and Warnings

None.

7 Accuracy

Not applicable.

8 Parallelism and Performance

F06YAF (DGEMM) is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

None.

10 Example

None.
F06 Chapter Contents
F06 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F06YCF (DSYMM) : NAG Library, Mark 26

F06 Chapter Contents
F06 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F06YCF (DSYMM)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
10 Example

1 Purpose

F06YCF (DSYMM) performs one of the matrix-matrix operations
C←αAB + βC   or   C←αBA + βC ,
where A is a real symmetric matrix, B and C are m by n real matrices, and α and β are real scalars.

2 Specification

SUBROUTINE F06YCF ( SIDE, UPLO, M, N, ALPHA, A, LDA, B, LDB, BETA, C, LDC)
INTEGER | M, N, LDA, LDB, LDC
REAL (KIND=nag_wp) | ALPHA, A(LDA,*), B(LDB,*), BETA, C(LDC,*)
CHARACTER(1) | SIDE, UPLO
The routine may be called by its BLAS name dsymm.

3 Description

None.

4 References

None.

5 Arguments

1:   SIDE – CHARACTER(1)Input
On entry: specifies whether B is operated on from the left or the right.
SIDE='L'
B is pre-multiplied from the left.
SIDE='R'
B is post-multiplied from the right.
Constraint: SIDE='L' or 'R'.
2:   UPLO – CHARACTER(1)Input
On entry: specifies whether the upper or lower triangular part of A is stored.
UPLO='U'
The upper triangular part of A is stored.
UPLO='L'
The lower triangular part of A is stored.
Constraint: UPLO='U' or 'L'.
3:   M – INTEGERInput
On entry: m, the number of rows of the matrices B and C; the order of A if SIDE='L'.
Constraint: M≥0.
4:   N – INTEGERInput
On entry: n, the number of columns of the matrices B and C; the order of A if SIDE='R'.
Constraint: N≥0.
5:   ALPHA – REAL (KIND=nag_wp)Input
On entry: the scalar α.
6:   A LDA* – REAL (KIND=nag_wp) arrayInput
Note: the second dimension of the array A must be at least max 1,M if SIDE='L' and at least max 1,N if SIDE='R'.
On entry: the symmetric matrix A; A is m by m if SIDE='L', or n by n if SIDE='R'.
  • If UPLO='U', the upper triangular part of A must be stored and the elements of the array below the diagonal are not referenced.
  • If UPLO='L', the lower triangular part of A must be stored and the elements of the array above the diagonal are not referenced.
7:   LDA – INTEGERInput
On entry: the first dimension of the array A as declared in the (sub)program from which F06YCF (DSYMM) is called.
Constraints:
  • if SIDE='L', LDA≥ max 1,M ;
  • if SIDE='R', LDA≥ max 1,N .
8:   B LDB* – REAL (KIND=nag_wp) arrayInput
Note: the second dimension of the array B must be at least max 1,N.
On entry: the m by n matrix B.
9:   LDB – INTEGERInput
On entry: the first dimension of the array B as declared in the (sub)program from which F06YCF (DSYMM) is called.
Constraint: LDB≥ max 1,M .
10:   BETA – REAL (KIND=nag_wp)Input
On entry: the scalar β.
11:   C LDC* – REAL (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array C must be at least max 1,N.
On entry: the m by n matrix C.
If BETA=0, C need not be set.
On exit: the updated matrix C.
12:   LDC – INTEGERInput
On entry: the first dimension of the array C as declared in the (sub)program from which F06YCF (DSYMM) is called.
Constraint: LDC≥ max 1,M .

6 Error Indicators and Warnings

None.

7 Accuracy

Not applicable.

8 Parallelism and Performance

F06YCF (DSYMM) is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

None.

10 Example

None.
F06 Chapter Contents
F06 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F06YFF (DTRMM) : NAG Library, Mark 26

F06 Chapter Contents
F06 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F06YFF (DTRMM)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
10 Example

1 Purpose

F06YFF (DTRMM) performs one of the matrix-matrix operations
B←αAB, B←α AT B, B←αBA  or B←αB AT,
where B is an m by n real matrix, A is a real triangular matrix, and α is a real scalar.

2 Specification

SUBROUTINE F06YFF ( SIDE, UPLO, TRANSA, DIAG, M, N, ALPHA, A, LDA, B, LDB)
INTEGER | M, N, LDA, LDB
REAL (KIND=nag_wp) | ALPHA, A(LDA,*), B(LDB,*)
CHARACTER(1) | SIDE, UPLO, TRANSA, DIAG
The routine may be called by its BLAS name dtrmm.

3 Description

None.

4 References

None.

5 Arguments

1:   SIDE – CHARACTER(1)Input
On entry: specifies whether B is operated on from the left or the right.
SIDE='L'
B is pre-multiplied from the left.
SIDE='R'
B is post-multiplied from the right.
Constraint: SIDE='L' or 'R'.
2:   UPLO – CHARACTER(1)Input
On entry: specifies whether A is upper or lower triangular.
UPLO='U'
A is upper triangular.
UPLO='L'
A is lower triangular.
Constraint: UPLO='U' or 'L'.
3:   TRANSA – CHARACTER(1)Input
On entry: specifies whether the operation involves A or AT.
TRANSA='N'
The operation involves A.
TRANSA='T' or 'C'
The operation involves AT.
Constraint: TRANSA='N', 'T' or 'C'.
4:   DIAG – CHARACTER(1)Input
On entry: specifies whether A has nonunit or unit diagonal elements.
DIAG='N'
The diagonal elements are stored explicitly.
DIAG='U'
The diagonal elements are assumed to be 1, and are not referenced.
Constraint: DIAG='N' or 'U'.
5:   M – INTEGERInput
On entry: m, the number of rows of the matrix B; the order of A if SIDE='L'.
Constraint: M≥0.
6:   N – INTEGERInput
On entry: n, the number of columns of the matrix B; the order of A if SIDE='R'.
Constraint: N≥0.
7:   ALPHA – REAL (KIND=nag_wp)Input
On entry: the scalar α.
8:   A LDA* – REAL (KIND=nag_wp) arrayInput
Note: the second dimension of the array A must be at least max 1,M if SIDE='L' and at least max 1,N if SIDE='R'.
On entry: the triangular matrix A; A is m by m if SIDE='L', or n by n if SIDE='R'.
  • If UPLO='U', A is upper triangular and the elements of the array below the diagonal are not referenced.
  • If UPLO='L', A is lower triangular and the elements of the array above the diagonal are not referenced.
  • If DIAG='U', the diagonal elements of A are assumed to be 1, and are not referenced.
9:   LDA – INTEGERInput
On entry: the first dimension of the array A as declared in the (sub)program from which F06YFF (DTRMM) is called.
Constraints:
  • if SIDE='L', LDA≥ max 1,M ;
  • if SIDE='R', LDA≥ max 1,N .
10:   B LDB* – REAL (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array B must be at least max 1,N.
On entry: the m by n matrix B.
If ALPHA=0, B need not be set.
On exit: the updated matrix B.
11:   LDB – INTEGERInput
On entry: the first dimension of the array B as declared in the (sub)program from which F06YFF (DTRMM) is called.
Constraint: LDB≥ max 1,M .

6 Error Indicators and Warnings

None.

7 Accuracy

Not applicable.

8 Parallelism and Performance

F06YFF (DTRMM) is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

None.

10 Example

None.
F06 Chapter Contents
F06 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F06YJF (DTRSM) : NAG Library, Mark 26

F06 Chapter Contents
F06 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F06YJF (DTRSM)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
10 Example

1 Purpose

F06YJF (DTRSM) performs one of the matrix-matrix operations
B←α A-1 B, B←α A-T B, B←αB A-1  or B←αB A-T,
where A is a real triangular matrix, B is an m by n real matrix, and α is a real scalar. A-T denotes AT-1 or equivalently A-1 T .
No test for singularity or near-singularity of A is included in this routine. Such tests must be performed before calling this routine.

2 Specification

SUBROUTINE F06YJF ( SIDE, UPLO, TRANSA, DIAG, M, N, ALPHA, A, LDA, B, LDB)
INTEGER | M, N, LDA, LDB
REAL (KIND=nag_wp) | ALPHA, A(LDA,*), B(LDB,*)
CHARACTER(1) | SIDE, UPLO, TRANSA, DIAG
The routine may be called by its BLAS name dtrsm.

3 Description

None.

4 References

None.

5 Arguments

1:   SIDE – CHARACTER(1)Input
On entry: specifies whether B is operated on from the left or the right.
SIDE='L'
B is pre-multiplied from the left.
SIDE='R'
B is post-multiplied from the right.
Constraint: SIDE='L' or 'R'.
2:   UPLO – CHARACTER(1)Input
On entry: specifies whether A is upper or lower triangular.
UPLO='U'
A is upper triangular.
UPLO='L'
A is lower triangular.
Constraint: UPLO='U' or 'L'.
3:   TRANSA – CHARACTER(1)Input
On entry: specifies whether the operation involves A-1 or A-T.
TRANSA='N'
The operation involves A-1.
TRANSA='T' or 'C'
The operation involves A-T.
Constraint: TRANSA='N', 'T' or 'C'.
4:   DIAG – CHARACTER(1)Input
On entry: specifies whether A has nonunit or unit diagonal elements.
DIAG='N'
The diagonal elements are stored explicitly.
DIAG='U'
The diagonal elements are assumed to be 1, and are not referenced.
Constraint: DIAG='N' or 'U'.
5:   M – INTEGERInput
On entry: m, the number of rows of the matrix B; the order of A if SIDE='L'.
Constraint: M≥0.
6:   N – INTEGERInput
On entry: n, the number of columns of the matrix B; the order of A if SIDE='R'.
Constraint: N≥0.
7:   ALPHA – REAL (KIND=nag_wp)Input
On entry: the scalar α.
8:   A LDA* – REAL (KIND=nag_wp) arrayInput
Note: the second dimension of the array A must be at least max 1,M if SIDE='L' and at least max 1,N if SIDE='R'.
On entry: the triangular matrix A; A is m by m if SIDE='L', or n by n if SIDE='R'.
  • If UPLO='U', A is upper triangular and the elements of the array below the diagonal are not referenced.
  • If UPLO='L', A is lower triangular and the elements of the array above the diagonal are not referenced.
  • If DIAG='U', the diagonal elements of A are assumed to be 1, and are not referenced.
9:   LDA – INTEGERInput
On entry: the first dimension of the array A as declared in the (sub)program from which F06YJF (DTRSM) is called.
Constraints:
  • if SIDE='L', LDA≥ max 1,M ;
  • if SIDE='R', LDA≥ max 1,N .
10:   B LDB* – REAL (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array B must be at least max 1,N.
On entry: the m by n matrix B.
If ALPHA=0, B need not be set.
On exit: the updated matrix B.
11:   LDB – INTEGERInput
On entry: the first dimension of the array B as declared in the (sub)program from which F06YJF (DTRSM) is called.
Constraint: LDB≥ max 1,M .

6 Error Indicators and Warnings

None.

7 Accuracy

Not applicable.

8 Parallelism and Performance

F06YJF (DTRSM) is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

None.

10 Example

None.
F06 Chapter Contents
F06 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F06YPF (DSYRK) : NAG Library, Mark 26

F06 Chapter Contents
F06 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F06YPF (DSYRK)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
10 Example

1 Purpose

F06YPF (DSYRK) performs one of the symmetric rank-k update operations
C←αA AT + βC   or   C←α AT A + βC ,
where A is a real matrix, C is an n by n real symmetric matrix, and α and β are real scalars.

2 Specification

SUBROUTINE F06YPF ( UPLO, TRANS, N, K, ALPHA, A, LDA, BETA, C, LDC)
INTEGER | N, K, LDA, LDC
REAL (KIND=nag_wp) | ALPHA, A(LDA,*), BETA, C(LDC,*)
CHARACTER(1) | UPLO, TRANS
The routine may be called by its BLAS name dsyrk.

3 Description

None.

4 References

None.

5 Arguments

1:   UPLO – CHARACTER(1)Input
On entry: specifies whether the upper or lower triangular part of C is stored.
UPLO='U'
The upper triangular part of C is stored.
UPLO='L'
The lower triangular part of C is stored.
Constraint: UPLO='U' or 'L'.
2:   TRANS – CHARACTER(1)Input
On entry: specifies the operation to be performed.
TRANS='N'
C←αA AT+βC.
TRANS='T' or 'C'
C←α AT A+βC.
Constraint: TRANS='N', 'T' or 'C'.
3:   N – INTEGERInput
On entry: n, the order of the matrix C; the number of rows of A if TRANS='N', or the number of columns of A if TRANS='T' or 'C'.
Constraint: N≥0.
4:   K – INTEGERInput
On entry: k, the number of columns of A if TRANS='N', or the number of rows of A if TRANS='T' or 'C'.
Constraint: K≥0.
5:   ALPHA – REAL (KIND=nag_wp)Input
On entry: the scalar α.
6:   A LDA* – REAL (KIND=nag_wp) arrayInput
Note: the second dimension of the array A must be at least max 1,K if TRANS='N' and at least max 1,N if TRANS='T' or 'C'.
On entry: the matrix A; A is n by k if TRANS='N', or k by n if TRANS='T' or 'C'.
7:   LDA – INTEGERInput
On entry: the first dimension of the array A as declared in the (sub)program from which F06YPF (DSYRK) is called.
Constraints:
  • if TRANS='N', LDA≥ max 1,N ;
  • if TRANS='T' or 'C', LDA≥ max 1,K .
8:   BETA – REAL (KIND=nag_wp)Input
On entry: the scalar β.
9:   C LDC* – REAL (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array C must be at least max 1,N.
On entry: the n by n symmetric matrix C.
  • If UPLO='U', the upper triangular part of C must be stored and the elements of the array below the diagonal are not referenced.
  • If UPLO='L', the lower triangular part of C must be stored and the elements of the array above the diagonal are not referenced.
On exit: the updated matrix C.
10:   LDC – INTEGERInput
On entry: the first dimension of the array C as declared in the (sub)program from which F06YPF (DSYRK) is called.
Constraint: LDC≥max 1,N .

6 Error Indicators and Warnings

None.

7 Accuracy

Not applicable.

8 Parallelism and Performance

F06YPF (DSYRK) is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

None.

10 Example

None.
F06 Chapter Contents
F06 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F06YRF (DSYR2K) : NAG Library, Mark 26

F06 Chapter Contents
F06 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F06YRF (DSYR2K)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
10 Example

1 Purpose

F06YRF (DSYR2K) performs one of the symmetric rank-2 k update operations
C←αA BT + αB AT + βC   or   C←α AT B + α BT A+βC ,
where A and B are real matrices, C is an n by n real symmetric matrix, and α and β are real scalars.

2 Specification

SUBROUTINE F06YRF ( UPLO, TRANS, N, K, ALPHA, A, LDA, B, LDB, BETA, C, LDC)
INTEGER | N, K, LDA, LDB, LDC
REAL (KIND=nag_wp) | ALPHA, A(LDA,*), B(LDB,*), BETA, C(LDC,*)
CHARACTER(1) | UPLO, TRANS
The routine may be called by its BLAS name dsyr2k.

3 Description

None.

4 References

None.

5 Arguments

1:   UPLO – CHARACTER(1)Input
On entry: specifies whether the upper or lower triangular part of C is stored.
UPLO='U'
The upper triangular part of C is stored.
UPLO='L'
The lower triangular part of C is stored.
Constraint: UPLO='U' or 'L'.
2:   TRANS – CHARACTER(1)Input
On entry: specifies the operation to be performed.
TRANS='N'
C←αA BT+αB AT+βC.
TRANS='T' or 'C'
C←α AT B+α BT A+βC.
Constraint: TRANS='N', 'T' or 'C'.
3:   N – INTEGERInput
On entry: n, the order of the matrix C; the number of rows of A and B if TRANS='N', or the number of columns of A and B if TRANS='T' or 'C'.
Constraint: N≥0.
4:   K – INTEGERInput
On entry: k, the number of columns of A and B if TRANS='N', or the number of rows of A and B if TRANS='T' or 'C'.
Constraint: K≥0.
5:   ALPHA – REAL (KIND=nag_wp)Input
On entry: the scalar α.
6:   A LDA* – REAL (KIND=nag_wp) arrayInput
Note: the second dimension of the array A must be at least max 1,K if TRANS='N' and at least max 1,N if TRANS='T' or 'C'.
On entry: the matrix A; A is n by k if TRANS='N', or k by n if TRANS='T' or 'C'.
7:   LDA – INTEGERInput
On entry: the first dimension of the array A as declared in the (sub)program from which F06YRF (DSYR2K) is called.
Constraints:
  • if TRANS='N', LDA≥ max 1,N ;
  • if TRANS='T' or 'C', LDA≥ max 1,K .
8:   B LDB* – REAL (KIND=nag_wp) arrayInput
Note: the second dimension of the array B must be at least max 1,K if TRANS='N' and at least max 1,N if TRANS='T' or 'C'.
On entry: the matrix B; B is n by k if TRANS='N', or k by n if TRANS='T' or 'C'.
9:   LDB – INTEGERInput
On entry: the first dimension of the array B as declared in the (sub)program from which F06YRF (DSYR2K) is called.
Constraints:
  • if TRANS='N', LDB≥ max 1,N ;
  • if TRANS='T' or 'C', LDB≥ max 1,K .
10:   BETA – REAL (KIND=nag_wp)Input
On entry: the scalar β.
11:   C LDC* – REAL (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array C must be at least max 1,N.
On entry: the n by n symmetric matrix C.
  • If UPLO='U', the upper triangular part of C must be stored and the elements of the array below the diagonal are not referenced.
  • If UPLO='L', the lower triangular part of C must be stored and the elements of the array above the diagonal are not referenced.
On exit: the updated matrix C.
12:   LDC – INTEGERInput
On entry: the first dimension of the array C as declared in the (sub)program from which F06YRF (DSYR2K) is called.
Constraint: LDC≥max 1,N .

6 Error Indicators and Warnings

None.

7 Accuracy

Not applicable.

8 Parallelism and Performance

F06YRF (DSYR2K) is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
F06YRF (DSYR2K) makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

None.

10 Example

None.
F06 Chapter Contents
F06 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F06ZAF (ZGEMM) : NAG Library, Mark 26

F06 Chapter Contents
F06 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F06ZAF (ZGEMM)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
10 Example

1 Purpose

F06ZAF (ZGEMM) performs one of the matrix-matrix operations
C←αAB+βC, C←α AT B+βC, C←α AH B+βC, C←αA BT+βC, C←α ATBT+βC, C←α AHBT+βC, C←αA BH+βC, C←α ATBH+βC  or C←α AHBH+βC,
where A, B and C are complex matrices, and α and β are complex scalars; C is always m by n.

2 Specification

SUBROUTINE F06ZAF ( TRANSA, TRANSB, M, N, K, ALPHA, A, LDA, B, LDB, BETA, C, LDC)
INTEGER | M, N, K, LDA, LDB, LDC
COMPLEX (KIND=nag_wp) | ALPHA, A(LDA,*), B(LDB,*), BETA, C(LDC,*)
CHARACTER(1) | TRANSA, TRANSB
The routine may be called by its BLAS name zgemm.

3 Description

None.

4 References

None.

5 Arguments

1:   TRANSA – CHARACTER(1)Input
On entry: specifies whether the operation involves A, AT or AH.
TRANSA='N'
The operation involves A.
TRANSA='T'
The operation involves AT.
TRANSA='C'
The operation involves AH.
Constraint: TRANSA='N', 'T' or 'C'.
2:   TRANSB – CHARACTER(1)Input
On entry: specifies whether the operation involves B, BT or BH.
TRANSB='N'
The operation involves B.
TRANSB='T'
The operation involves BT.
TRANSB='C'
The operation involves BH.
Constraint: TRANSB='N', 'T' or 'C'.
3:   M – INTEGERInput
On entry: m, the number of rows of the matrix C; the number of rows of A if TRANSA='N', or the number of columns of A if TRANSA='T' or 'C'.
Constraint: M≥0.
4:   N – INTEGERInput
On entry: n, the number of columns of the matrix C; the number of columns of B if TRANSB='N', or the number of rows of B if TRANSB='T' or 'C'.
Constraint: N≥0.
5:   K – INTEGERInput
On entry: k, the number of columns of A if TRANSA='N', or the number of rows of A if TRANSA='T' or 'C'; the number of rows of B if TRANSB='N', or the number of columns of B if TRANSB='T' or 'C'.
Constraint: K≥0.
6:   ALPHA – COMPLEX (KIND=nag_wp)Input
On entry: the scalar α.
7:   A LDA* – COMPLEX (KIND=nag_wp) arrayInput
Note: the second dimension of the array A must be at least max 1,K if TRANSA='N' and at least max 1,M if TRANSA='T' or 'C'.
On entry: the matrix A; A is m by k if TRANSA='N', or k by m if TRANSA='T' or 'C'.
8:   LDA – INTEGERInput
On entry: the first dimension of the array A as declared in the (sub)program from which F06ZAF (ZGEMM) is called.
Constraints:
  • if TRANSA='N', LDA≥ max 1,M ;
  • if TRANSA='T' or 'C', LDA≥ max 1,K .
9:   B LDB* – COMPLEX (KIND=nag_wp) arrayInput
Note: the second dimension of the array B must be at least max 1,N if TRANSB='N' and at least max 1,K if TRANSB='T' or 'C'.
On entry: the matrix B; B is k by n if TRANSB='N', or n by k if TRANSB='T' or 'C'.
10:   LDB – INTEGERInput
On entry: the first dimension of the array B as declared in the (sub)program from which F06ZAF (ZGEMM) is called.
Constraints:
  • if TRANSB='N', LDB≥ max 1,K ;
  • if TRANSB='T' or 'C', LDB≥ max 1,N .
11:   BETA – COMPLEX (KIND=nag_wp)Input
On entry: the scalar β.
12:   C LDC* – COMPLEX (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array C must be at least max 1,N.
On entry: the m by n matrix C.
If BETA=0, C need not be set.
On exit: the updated matrix C.
13:   LDC – INTEGERInput
On entry: the first dimension of the array C as declared in the (sub)program from which F06ZAF (ZGEMM) is called.
Constraint: LDC≥ max 1,M .

6 Error Indicators and Warnings

None.

7 Accuracy

Not applicable.

8 Parallelism and Performance

F06ZAF (ZGEMM) is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

None.

10 Example

None.
F06 Chapter Contents
F06 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F06ZCF (ZHEMM) : NAG Library, Mark 26

F06 Chapter Contents
F06 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F06ZCF (ZHEMM)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
10 Example

1 Purpose

F06ZCF (ZHEMM) performs one of the matrix-matrix operations
C←αAB + βC   or   C←αBA + βC ,
where A is a complex Hermitian matrix, B and C are m by n complex matrices, and α and β are complex scalars.

2 Specification

SUBROUTINE F06ZCF ( SIDE, UPLO, M, N, ALPHA, A, LDA, B, LDB, BETA, C, LDC)
INTEGER | M, N, LDA, LDB, LDC
COMPLEX (KIND=nag_wp) | ALPHA, A(LDA,*), B(LDB,*), BETA, C(LDC,*)
CHARACTER(1) | SIDE, UPLO
The routine may be called by its BLAS name zhemm.

3 Description

None.

4 References

None.

5 Arguments

1:   SIDE – CHARACTER(1)Input
On entry: specifies whether B is operated on from the left or the right.
SIDE='L'
B is pre-multiplied from the left.
SIDE='R'
B is post-multiplied from the right.
Constraint: SIDE='L' or 'R'.
2:   UPLO – CHARACTER(1)Input
On entry: specifies whether the upper or lower triangular part of A is stored.
UPLO='U'
The upper triangular part of A is stored.
UPLO='L'
The lower triangular part of A is stored.
Constraint: UPLO='U' or 'L'.
3:   M – INTEGERInput
On entry: m, the number of rows of the matrices B and C; the order of A if SIDE='L'.
Constraint: M≥0.
4:   N – INTEGERInput
On entry: n, the number of columns of the matrices B and C; the order of A if SIDE='R'.
Constraint: N≥0.
5:   ALPHA – COMPLEX (KIND=nag_wp)Input
On entry: the scalar α.
6:   A LDA* – COMPLEX (KIND=nag_wp) arrayInput
Note: the second dimension of the array A must be at least max 1,M if SIDE='L' and at least max 1,N if SIDE='R'.
On entry: the Hermitian matrix A; A is m by m if SIDE='L', or n by n if SIDE='R'.
  • If UPLO='U', the upper triangular part of A must be stored and the elements of the array below the diagonal are not referenced.
  • If UPLO='L', the lower triangular part of A must be stored and the elements of the array above the diagonal are not referenced.
7:   LDA – INTEGERInput
On entry: the first dimension of the array A as declared in the (sub)program from which F06ZCF (ZHEMM) is called.
Constraints:
  • if SIDE='L', LDA≥ max 1,M ;
  • if SIDE='R', LDA≥ max 1,N .
8:   B LDB* – COMPLEX (KIND=nag_wp) arrayInput
Note: the second dimension of the array B must be at least max 1,N.
On entry: the m by n matrix B.
9:   LDB – INTEGERInput
On entry: the first dimension of the array B as declared in the (sub)program from which F06ZCF (ZHEMM) is called.
Constraint: LDB≥ max 1,M .
10:   BETA – COMPLEX (KIND=nag_wp)Input
On entry: the scalar β.
11:   C LDC* – COMPLEX (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array C must be at least max 1,N.
On entry: the m by n matrix C.
If BETA=0, C need not be set.
On exit: the updated matrix C.
12:   LDC – INTEGERInput
On entry: the first dimension of the array C as declared in the (sub)program from which F06ZCF (ZHEMM) is called.
Constraint: LDC≥ max 1,M .

6 Error Indicators and Warnings

None.

7 Accuracy

Not applicable.

8 Parallelism and Performance

F06ZCF (ZHEMM) is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

None.

10 Example

None.
F06 Chapter Contents
F06 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F06ZFF (ZTRMM) : NAG Library, Mark 26

F06 Chapter Contents
F06 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F06ZFF (ZTRMM)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
10 Example

1 Purpose

F06ZFF (ZTRMM) performs one of the matrix-matrix operations
B←αAB, B←α AT B, B←α AH B, B←αBA, B←αB AT  or B←αB AH,
where B is an m by n complex matrix, A is a complex triangular matrix, and α is a complex scalar.

2 Specification

SUBROUTINE F06ZFF ( SIDE, UPLO, TRANSA, DIAG, M, N, ALPHA, A, LDA, B, LDB)
INTEGER | M, N, LDA, LDB
COMPLEX (KIND=nag_wp) | ALPHA, A(LDA,*), B(LDB,*)
CHARACTER(1) | SIDE, UPLO, TRANSA, DIAG
The routine may be called by its BLAS name ztrmm.

3 Description

None.

4 References

None.

5 Arguments

1:   SIDE – CHARACTER(1)Input
On entry: specifies whether B is operated on from the left or the right.
SIDE='L'
B is pre-multiplied from the left.
SIDE='R'
B is post-multiplied from the right.
Constraint: SIDE='L' or 'R'.
2:   UPLO – CHARACTER(1)Input
On entry: specifies whether A is upper or lower triangular.
UPLO='U'
A is upper triangular.
UPLO='L'
A is lower triangular.
Constraint: UPLO='U' or 'L'.
3:   TRANSA – CHARACTER(1)Input
On entry: specifies whether the operation involves A, AT or AH.
TRANSA='N'
The operation involves A.
TRANSA='T'
The operation involves AT.
TRANSA='C'
The operation involves AH.
Constraint: TRANSA='N', 'T' or 'C'.
4:   DIAG – CHARACTER(1)Input
On entry: specifies whether A has nonunit or unit diagonal elements.
DIAG='N'
The diagonal elements are stored explicitly.
DIAG='U'
The diagonal elements are assumed to be 1, and are not referenced.
Constraint: DIAG='N' or 'U'.
5:   M – INTEGERInput
On entry: m, the number of rows of the matrix B; the order of A if SIDE='L'.
Constraint: M≥0.
6:   N – INTEGERInput
On entry: n, the number of columns of the matrix B; the order of A if SIDE='R'.
Constraint: N≥0.
7:   ALPHA – COMPLEX (KIND=nag_wp)Input
On entry: the scalar α.
8:   A LDA* – COMPLEX (KIND=nag_wp) arrayInput
Note: the second dimension of the array A must be at least max 1,M if SIDE='L' and at least max 1,N if SIDE='R'.
On entry: the triangular matrix A; A is m by m if SIDE='L', or n by n if SIDE='R'.
  • If UPLO='U', A is upper triangular and the elements of the array below the diagonal are not referenced.
  • If UPLO='L', A is lower triangular and the elements of the array above the diagonal are not referenced.
  • If DIAG='U', the diagonal elements of A are assumed to be 1, and are not referenced.
9:   LDA – INTEGERInput
On entry: the first dimension of the array A as declared in the (sub)program from which F06ZFF (ZTRMM) is called.
Constraints:
  • if SIDE='L', LDA≥ max 1,M ;
  • if SIDE='R', LDA≥ max 1,N .
10:   B LDB* – COMPLEX (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array B must be at least max 1,N.
On entry: the m by n matrix B.
If ALPHA=0, B need not be set.
On exit: the updated matrix B.
11:   LDB – INTEGERInput
On entry: the first dimension of the array B as declared in the (sub)program from which F06ZFF (ZTRMM) is called.
Constraint: LDB≥ max 1,M .

6 Error Indicators and Warnings

None.

7 Accuracy

Not applicable.

8 Parallelism and Performance

F06ZFF (ZTRMM) is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

None.

10 Example

None.
F06 Chapter Contents
F06 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F06ZJF (ZTRSM) : NAG Library, Mark 26

F06 Chapter Contents
F06 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F06ZJF (ZTRSM)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
10 Example

1 Purpose

F06ZJF (ZTRSM) performs one of the matrix-matrix operations
B←α A-1 B , B←α A-T B , B←α A-H B , B←αB A-1 , B←αB A-T   or B←αB A-H ,
where A is a complex triangular matrix, B is an m by n complex matrix, and α is a complex scalar. A-T denotes AT-1 or equivalently A-1 T ; A-H denotes AH-1 or equivalently A-1 H .
No test for singularity or near-singularity of A is included in this routine. Such tests must be performed before calling this routine.

2 Specification

SUBROUTINE F06ZJF ( SIDE, UPLO, TRANSA, DIAG, M, N, ALPHA, A, LDA, B, LDB)
INTEGER | M, N, LDA, LDB
COMPLEX (KIND=nag_wp) | ALPHA, A(LDA,*), B(LDB,*)
CHARACTER(1) | SIDE, UPLO, TRANSA, DIAG
The routine may be called by its BLAS name ztrsm.

3 Description

None.

4 References

None.

5 Arguments

1:   SIDE – CHARACTER(1)Input
On entry: specifies whether B is operated on from the left or the right.
SIDE='L'
B is pre-multiplied from the left.
SIDE='R'
B is post-multiplied from the right.
Constraint: SIDE='L' or 'R'.
2:   UPLO – CHARACTER(1)Input
On entry: specifies whether A is upper or lower triangular.
UPLO='U'
A is upper triangular.
UPLO='L'
A is lower triangular.
Constraint: UPLO='U' or 'L'.
3:   TRANSA – CHARACTER(1)Input
On entry: specifies whether the operation involves A-1, A-T or A-H.
TRANSA='N'
The operation involves A-1.
TRANSA='T'
The operation involves A-T.
TRANSA='C'
The operation involves A-H.
Constraint: TRANSA='N', 'T' or 'C'.
4:   DIAG – CHARACTER(1)Input
On entry: specifies whether A has nonunit or unit diagonal elements.
DIAG='N'
The diagonal elements are stored explicitly.
DIAG='U'
The diagonal elements are assumed to be 1, and are not referenced.
Constraint: DIAG='N' or 'U'.
5:   M – INTEGERInput
On entry: m, the number of rows of the matrix B; the order of A if SIDE='L'.
Constraint: M≥0.
6:   N – INTEGERInput
On entry: n, the number of columns of the matrix B; the order of A if SIDE='R'.
Constraint: N≥0.
7:   ALPHA – COMPLEX (KIND=nag_wp)Input
On entry: the scalar α.
8:   A LDA* – COMPLEX (KIND=nag_wp) arrayInput
Note: the second dimension of the array A must be at least max 1,M if SIDE='L' and at least max 1,N if SIDE='R'.
On entry: the triangular matrix A; A is m by m if SIDE='L', or n by n if SIDE='R'.
  • If UPLO='U', A is upper triangular and the elements of the array below the diagonal are not referenced.
  • If UPLO='L', A is lower triangular and the elements of the array above the diagonal are not referenced.
  • If DIAG='U', the diagonal elements of A are assumed to be 1, and are not referenced.
9:   LDA – INTEGERInput
On entry: the first dimension of the array A as declared in the (sub)program from which F06ZJF (ZTRSM) is called.
Constraints:
  • if SIDE='L', LDA≥ max 1,M ;
  • if SIDE='R', LDA≥ max 1,N .
10:   B LDB* – COMPLEX (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array B must be at least max 1,N.
On entry: the m by n matrix B.
If ALPHA=0, B need not be set.
On exit: the updated matrix B.
11:   LDB – INTEGERInput
On entry: the first dimension of the array B as declared in the (sub)program from which F06ZJF (ZTRSM) is called.
Constraint: LDB≥ max 1,M .

6 Error Indicators and Warnings

None.

7 Accuracy

Not applicable.

8 Parallelism and Performance

F06ZJF (ZTRSM) is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

None.

10 Example

None.
F06 Chapter Contents
F06 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F06ZPF (ZHERK) : NAG Library, Mark 26

F06 Chapter Contents
F06 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F06ZPF (ZHERK)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
10 Example

1 Purpose

F06ZPF (ZHERK) performs one of the Hermitian rank-k update operations
C←αA AH+βC  or  C←α AH A+βC
where A is a complex matrix, C is an n by n complex Hermitian matrix, and α and β are real scalars.

2 Specification

SUBROUTINE F06ZPF ( UPLO, TRANS, N, K, ALPHA, A, LDA, BETA, C, LDC)
INTEGER | N, K, LDA, LDC
REAL (KIND=nag_wp) | ALPHA, BETA
COMPLEX (KIND=nag_wp) | A(LDA,*), C(LDC,*)
CHARACTER(1) | UPLO, TRANS
The routine may be called by its BLAS name zherk.

3 Description

None.

4 References

None.

5 Arguments

1:   UPLO – CHARACTER(1)Input
On entry: specifies whether the upper or lower triangular part of C is stored.
UPLO='U'
The upper triangular part of C is stored.
UPLO='L'
The lower triangular part of C is stored.
Constraint: UPLO='U' or 'L'.
2:   TRANS – CHARACTER(1)Input
On entry: specifies the operation to be performed.
TRANS='N'
C←αA AH+βC.
TRANS='C'
C←α AH A+βC.
Constraint: TRANS='N' or 'C'.
3:   N – INTEGERInput
On entry: n, the order of the matrix C; the number of rows of A if TRANS='N', or the number of columns of A if TRANS='C'.
Constraint: N≥0.
4:   K – INTEGERInput
On entry: k, the number of columns of A if TRANS='N', or the number of rows of A if TRANS='C'.
Constraint: K≥0.
5:   ALPHA – REAL (KIND=nag_wp)Input
On entry: the scalar α.
6:   A LDA* – COMPLEX (KIND=nag_wp) arrayInput
Note: the second dimension of the array A must be at least max 1,K if TRANS='N' and at least max 1,N if TRANS='C'.
On entry: the matrix A; A is n by k if TRANS='N', or k by n if TRANS='C'.
7:   LDA – INTEGERInput
On entry: the first dimension of the array A as declared in the (sub)program from which F06ZPF (ZHERK) is called.
Constraints:
  • if TRANS='N', LDA≥ max 1,N ;
  • if TRANS='C', LDA≥ max 1,K .
8:   BETA – REAL (KIND=nag_wp)Input
On entry: the scalar β.
9:   C LDC* – COMPLEX (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array C must be at least max 1,N.
On entry: the n by n Hermitian matrix C.
  • If UPLO='U', the upper triangular part of C must be stored and the elements of the array below the diagonal are not referenced.
  • If UPLO='L', the lower triangular part of C must be stored and the elements of the array above the diagonal are not referenced.
On exit: the updated matrix C. The imaginary parts of the diagonal elements are set to zero.
10:   LDC – INTEGERInput
On entry: the first dimension of the array C as declared in the (sub)program from which F06ZPF (ZHERK) is called.
Constraint: LDC≥max 1,N .

6 Error Indicators and Warnings

None.

7 Accuracy

Not applicable.

8 Parallelism and Performance

F06ZPF (ZHERK) is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

None.

10 Example

None.
F06 Chapter Contents
F06 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F06ZRF (ZHER2K) : NAG Library, Mark 26

F06 Chapter Contents
F06 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F06ZRF (ZHER2K)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
10 Example

1 Purpose

F06ZRF (ZHER2K) performs one of the Hermitian rank-2 k update operations
C←αA BH + α-B AH + βC   or   C←α AH B + α-BH A+βC ,
where A and B are complex matrices, C is an n by n complex Hermitian matrix, α is a complex scalar, and β is a real scalar.

2 Specification

SUBROUTINE F06ZRF ( UPLO, TRANS, N, K, ALPHA, A, LDA, B, LDB, BETA, C, LDC)
INTEGER | N, K, LDA, LDB, LDC
REAL (KIND=nag_wp) | BETA
COMPLEX (KIND=nag_wp) | ALPHA, A(LDA,*), B(LDB,*), C(LDC,*)
CHARACTER(1) | UPLO, TRANS
The routine may be called by its BLAS name zher2k.

3 Description

None.

4 References

None.

5 Arguments

1:   UPLO – CHARACTER(1)Input
On entry: specifies whether the upper or lower triangular part of C is stored.
UPLO='U'
The upper triangular part of C is stored.
UPLO='L'
The lower triangular part of C is stored.
Constraint: UPLO='U' or 'L'.
2:   TRANS – CHARACTER(1)Input
On entry: specifies the operation to be performed.
TRANS='N'
C←αA BH+α-B AH+βC.
TRANS='C'
C←α AH B+α-BH A+βC.
Constraint: TRANS='N' or 'C'.
3:   N – INTEGERInput
On entry: n, the order of the matrix C; the number of rows of A if TRANS='N', or the number of columns of A if TRANS='C'.
Constraint: N≥0.
4:   K – INTEGERInput
On entry: k, the number of columns of A if TRANS='N', or the number of rows of A if TRANS='C'.
Constraint: K≥0.
5:   ALPHA – COMPLEX (KIND=nag_wp)Input
On entry: the scalar α.
6:   A LDA* – COMPLEX (KIND=nag_wp) arrayInput
Note: the second dimension of the array A must be at least max 1,K if TRANS='N' and at least max 1,N if TRANS='C'.
On entry: the matrix A; A is n by k if TRANS='N', or k by n if TRANS='C'.
7:   LDA – INTEGERInput
On entry: the first dimension of the array A as declared in the (sub)program from which F06ZRF (ZHER2K) is called.
Constraints:
  • if TRANS='N', LDA≥ max 1,N ;
  • if TRANS='C', LDA≥ max 1,K .
8:   B LDB* – COMPLEX (KIND=nag_wp) arrayInput
Note: the second dimension of the array B must be at least max 1,K if TRANS='N' and at least max 1,N if TRANS='C'.
On entry: the matrix B; B is n by k if TRANS='N', or k by n if TRANS='C'.
9:   LDB – INTEGERInput
On entry: the first dimension of the array B as declared in the (sub)program from which F06ZRF (ZHER2K) is called.
Constraints:
  • if TRANS='N', LDB≥ max 1,N ;
  • if TRANS='C', LDB≥ max 1,K .
10:   BETA – REAL (KIND=nag_wp)Input
On entry: the scalar β.
11:   C LDC* – COMPLEX (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array C must be at least max 1,N.
On entry: the n by n Hermitian matrix C.
  • If UPLO='U', the upper triangular part of C must be stored and the elements of the array below the diagonal are not referenced.
  • If UPLO='L', the lower triangular part of C must be stored and the elements of the array above the diagonal are not referenced.
On exit: the updated matrix C. The imaginary parts of the diagonal elements are set to zero.
12:   LDC – INTEGERInput
On entry: the first dimension of the array C as declared in the (sub)program from which F06ZRF (ZHER2K) is called.
Constraint: LDC≥max 1,N .

6 Error Indicators and Warnings

None.

7 Accuracy

Not applicable.

8 Parallelism and Performance

F06ZRF (ZHER2K) is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
F06ZRF (ZHER2K) makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

None.

10 Example

None.
F06 Chapter Contents
F06 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F06ZTF (ZSYMM) : NAG Library, Mark 26

F06 Chapter Contents
F06 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F06ZTF (ZSYMM)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
10 Example

1 Purpose

F06ZTF (ZSYMM) performs one of the matrix-matrix operations
C←αAB + βC   or   C←αBA + βC ,
where A is a complex symmetric matrix, B and C are m by n complex matrices, and α and β are complex scalars.

2 Specification

SUBROUTINE F06ZTF ( SIDE, UPLO, M, N, ALPHA, A, LDA, B, LDB, BETA, C, LDC)
INTEGER | M, N, LDA, LDB, LDC
COMPLEX (KIND=nag_wp) | ALPHA, A(LDA,*), B(LDB,*), BETA, C(LDC,*)
CHARACTER(1) | SIDE, UPLO
The routine may be called by its BLAS name zsymm.

3 Description

None.

4 References

None.

5 Arguments

1:   SIDE – CHARACTER(1)Input
On entry: specifies whether B is operated on from the left or the right.
SIDE='L'
B is pre-multiplied from the left.
SIDE='R'
B is post-multiplied from the right.
Constraint: SIDE='L' or 'R'.
2:   UPLO – CHARACTER(1)Input
On entry: specifies whether the upper or lower triangular part of A is stored.
UPLO='U'
The upper triangular part of A is stored.
UPLO='L'
The lower triangular part of A is stored.
Constraint: UPLO='U' or 'L'.
3:   M – INTEGERInput
On entry: m, the number of rows of the matrices B and C; the order of A if SIDE='L'.
Constraint: M≥0.
4:   N – INTEGERInput
On entry: n, the number of columns of the matrices B and C; the order of A if SIDE='R'.
Constraint: N≥0.
5:   ALPHA – COMPLEX (KIND=nag_wp)Input
On entry: the scalar α.
6:   A LDA* – COMPLEX (KIND=nag_wp) arrayInput
Note: the second dimension of the array A must be at least max 1,M if SIDE='L' and at least max 1,N if SIDE='R'.
On entry: the symmetric matrix A; A is m by m if SIDE='L', or n by n if SIDE='R'.
  • If UPLO='U', the upper triangular part of A must be stored and the elements of the array below the diagonal are not referenced.
  • If UPLO='L', the lower triangular part of A must be stored and the elements of the array above the diagonal are not referenced.
7:   LDA – INTEGERInput
On entry: the first dimension of the array A as declared in the (sub)program from which F06ZTF (ZSYMM) is called.
Constraints:
  • if SIDE='L', LDA≥ max 1,M ;
  • if SIDE='R', LDA≥ max 1,N .
8:   B LDB* – COMPLEX (KIND=nag_wp) arrayInput
Note: the second dimension of the array B must be at least max 1,N.
On entry: the m by n matrix B.
9:   LDB – INTEGERInput
On entry: the first dimension of the array B as declared in the (sub)program from which F06ZTF (ZSYMM) is called.
Constraint: LDB≥ max 1,M .
10:   BETA – COMPLEX (KIND=nag_wp)Input
On entry: the scalar β.
11:   C LDC* – COMPLEX (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array C must be at least max 1,N.
On entry: the m by n matrix C.
If BETA=0, C need not be set.
On exit: the updated matrix C.
12:   LDC – INTEGERInput
On entry: the first dimension of the array C as declared in the (sub)program from which F06ZTF (ZSYMM) is called.
Constraint: LDC≥ max 1,M .

6 Error Indicators and Warnings

None.

7 Accuracy

Not applicable.

8 Parallelism and Performance

F06ZTF (ZSYMM) is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

None.

10 Example

None.
F06 Chapter Contents
F06 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F06ZUF (ZSYRK) : NAG Library, Mark 26

F06 Chapter Contents
F06 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F06ZUF (ZSYRK)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
10 Example

1 Purpose

F06ZUF (ZSYRK) performs one of the symmetric rank-k update operations
C←αA AT + βC   or   C←α AT A + βC ,
where A is a complex matrix, C is an n by n complex symmetric matrix, and α and β are complex scalars.

2 Specification

SUBROUTINE F06ZUF ( UPLO, TRANS, N, K, ALPHA, A, LDA, BETA, C, LDC)
INTEGER | N, K, LDA, LDC
COMPLEX (KIND=nag_wp) | ALPHA, A(LDA,*), BETA, C(LDC,*)
CHARACTER(1) | UPLO, TRANS
The routine may be called by its BLAS name zsyrk.

3 Description

None.

4 References

None.

5 Arguments

1:   UPLO – CHARACTER(1)Input
On entry: specifies whether the upper or lower triangular part of C is stored.
UPLO='U'
The upper triangular part of C is stored.
UPLO='L'
The lower triangular part of C is stored.
Constraint: UPLO='U' or 'L'.
2:   TRANS – CHARACTER(1)Input
On entry: specifies the operation to be performed.
TRANS='N'
C←αA AT+βC.
TRANS='T'
C←α AT A+βC.
Constraint: TRANS='N' or 'T'.
3:   N – INTEGERInput
On entry: n, the order of the matrix C; the number of rows of A and B if TRANS='N', or the number of columns of A and B if TRANS='T'.
Constraint: N≥0.
4:   K – INTEGERInput
On entry: k, the number of columns of A and B if TRANS='N', or the number of rows of A and B if TRANS='T'.
Constraint: K≥0.
5:   ALPHA – COMPLEX (KIND=nag_wp)Input
On entry: the scalar α.
6:   A LDA* – COMPLEX (KIND=nag_wp) arrayInput
Note: the second dimension of the array A must be at least max 1,K if TRANS='N' and at least max 1,N if TRANS='T'.
On entry: the matrix A; A is n by k if TRANS='N', or k by n if TRANS='T'.
7:   LDA – INTEGERInput
On entry: the first dimension of the array A as declared in the (sub)program from which F06ZUF (ZSYRK) is called.
Constraints:
  • if TRANS='N', LDA≥ max 1,N ;
  • if TRANS='T', LDA≥ max 1,K .
8:   BETA – COMPLEX (KIND=nag_wp)Input
On entry: the scalar β.
9:   C LDC* – COMPLEX (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array C must be at least max 1,N.
On entry: the n by n symmetric matrix C.
  • If UPLO='U', the upper triangular part of C must be stored and the elements of the array below the diagonal are not referenced.
  • If UPLO='L', the lower triangular part of C must be stored and the elements of the array above the diagonal are not referenced.
On exit: the updated matrix C.
10:   LDC – INTEGERInput
On entry: the first dimension of the array C as declared in the (sub)program from which F06ZUF (ZSYRK) is called.
Constraint: LDC≥max 1,N .

6 Error Indicators and Warnings

None.

7 Accuracy

Not applicable.

8 Parallelism and Performance

F06ZUF (ZSYRK) is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

None.

10 Example

None.
F06 Chapter Contents
F06 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F06ZWF (ZSYR2K) : NAG Library, Mark 26

F06 Chapter Contents
F06 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F06ZWF (ZSYR2K)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
10 Example

1 Purpose

F06ZWF (ZSYR2K) performs one of the symmetric rank-2 k update operations
C←αA BT + αB AT + βC   or   C←α AT B + α BT A + βC ,
where A and B are complex matrices, C is an n by n complex symmetric matrix, and α and β are complex scalars.

2 Specification

SUBROUTINE F06ZWF ( UPLO, TRANS, N, K, ALPHA, A, LDA, B, LDB, BETA, C, LDC)
INTEGER | N, K, LDA, LDB, LDC
COMPLEX (KIND=nag_wp) | ALPHA, A(LDA,*), B(LDB,*), BETA, C(LDC,*)
CHARACTER(1) | UPLO, TRANS
The routine may be called by its BLAS name zsyr2k.

3 Description

None.

4 References

None.

5 Arguments

1:   UPLO – CHARACTER(1)Input
On entry: specifies whether the upper or lower triangular part of C is stored.
UPLO='U'
The upper triangular part of C is stored.
UPLO='L'
The lower triangular part of C is stored.
Constraint: UPLO='U' or 'L'.
2:   TRANS – CHARACTER(1)Input
On entry: specifies the operation to be performed.
TRANS='N'
C←αA BT+αB AT+βC.
TRANS='T'
C←α AT B+α BT A+βC.
Constraint: TRANS='N' or 'T'.
3:   N – INTEGERInput
On entry: n, the order of the matrix C; the number of rows of A and B if TRANS='N', or the number of columns of A and B if TRANS='T'.
Constraint: N≥0.
4:   K – INTEGERInput
On entry: k, the number of columns of A and B if TRANS='N', or the number of rows of A and B if TRANS='T'.
Constraint: K≥0.
5:   ALPHA – COMPLEX (KIND=nag_wp)Input
On entry: the scalar α.
6:   A LDA* – COMPLEX (KIND=nag_wp) arrayInput
Note: the second dimension of the array A must be at least max 1,K if TRANS='N' and at least max 1,N if TRANS='T'.
On entry: the matrix A; A is n by k if TRANS='N', or k by n if TRANS='T'.
7:   LDA – INTEGERInput
On entry: the first dimension of the array A as declared in the (sub)program from which F06ZWF (ZSYR2K) is called.
Constraints:
  • if TRANS='N', LDA≥ max 1,N ;
  • if TRANS='T', LDA≥ max 1,K .
8:   B LDB* – COMPLEX (KIND=nag_wp) arrayInput
Note: the second dimension of the array B must be at least max 1,K if TRANS='N' and at least max 1,N if TRANS='T'.
On entry: the matrix B; B is n by k if TRANS='N', or k by n if TRANS='T'.
9:   LDB – INTEGERInput
On entry: the first dimension of the array B as declared in the (sub)program from which F06ZWF (ZSYR2K) is called.
Constraints:
  • if TRANS='N', LDB≥ max 1,N ;
  • if TRANS='T', LDB≥ max 1,K .
10:   BETA – COMPLEX (KIND=nag_wp)Input
On entry: the scalar β.
11:   C LDC* – COMPLEX (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array C must be at least max 1,N.
On entry: the n by n symmetric matrix C.
  • If UPLO='U', the upper triangular part of C must be stored and the elements of the array below the diagonal are not referenced.
  • If UPLO='L', the lower triangular part of C must be stored and the elements of the array above the diagonal are not referenced.
On exit: the updated matrix C.
12:   LDC – INTEGERInput
On entry: the first dimension of the array C as declared in the (sub)program from which F06ZWF (ZSYR2K) is called.
Constraint: LDC≥max 1,N .

6 Error Indicators and Warnings

None.

7 Accuracy

Not applicable.

8 Parallelism and Performance

F06ZWF (ZSYR2K) is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
F06ZWF (ZSYR2K) makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

None.

10 Example

None.
F06 Chapter Contents
F06 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F07AAF (DGESV) : NAG Library, Mark 26

F07 Chapter Contents
F07 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F07AAF (DGESV)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F07AAF (DGESV) computes the solution to a real system of linear equations
AX=B ,
where A is an n by n matrix and X and B are n by r matrices.

2 Specification

SUBROUTINE F07AAF ( N, NRHS, A, LDA, IPIV, B, LDB, INFO)
INTEGER | N, NRHS, LDA, IPIV(N), LDB, INFO
REAL (KIND=nag_wp) | A(LDA,*), B(LDB,*)
The routine may be called by its LAPACK name dgesv.

3 Description

F07AAF (DGESV) uses the LU decomposition with partial pivoting and row interchanges to factor A as
A=PLU ,
where P is a permutation matrix, L is unit lower triangular, and U is upper triangular. The factored form of A is then used to solve the system of equations AX=B.

4 References

Anderson E, Bai Z, Bischof C, Blackford S, Demmel J, Dongarra J J, Du Croz J J, Greenbaum A, Hammarling S, McKenney A and Sorensen D (1999) LAPACK Users' Guide (3rd Edition) SIAM, Philadelphia http://www.netlib.org/lapack/lug
Golub G H and Van Loan C F (1996) Matrix Computations (3rd Edition) Johns Hopkins University Press, Baltimore

5 Arguments

1:   N – INTEGERInput
On entry: n, the number of linear equations, i.e., the order of the matrix A.
Constraint: N≥0.
2:   NRHS – INTEGERInput
On entry: r, the number of right-hand sides, i.e., the number of columns of the matrix B.
Constraint: NRHS≥0.
3:   A LDA* – REAL (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array A must be at least max 1,N.
On entry: the n by n coefficient matrix A.
On exit: the factors L and U from the factorization A=PLU; the unit diagonal elements of L are not stored.
4:   LDA – INTEGERInput
On entry: the first dimension of the array A as declared in the (sub)program from which F07AAF (DGESV) is called.
Constraint: LDA≥max 1,N.
5:   IPIV N – INTEGER arrayOutput
On exit: if no constraints are violated, the pivot indices that define the permutation matrix P; at the ith step row i of the matrix was interchanged with row IPIV i. IPIV i=i indicates a row interchange was not required.
6:   B LDB* – REAL (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array B must be at least max 1,NRHS.
On entry: the n by r right-hand side matrix B.
On exit: if INFO=0, the n by r solution matrix X.
7:   LDB – INTEGERInput
On entry: the first dimension of the array B as declared in the (sub)program from which F07AAF (DGESV) is called.
Constraint: LDB≥max 1,N.
8:   INFO – INTEGEROutput
On exit: INFO=0 unless the routine detects an error (see Section 6).

6 Error Indicators and Warnings

INFO<0
If INFO=-i, argument i had an illegal value. An explanatory message is output, and execution of the program is terminated.
INFO>0
Element value of the diagonal is exactly zero. The factorization has been completed, but the factor U is exactly singular, so the solution could not be computed.

7 Accuracy

The computed solution for a single right-hand side, x^ , satisfies the equation of the form
A+E x^=b ,
where
E 1 = O ε A 1
and ε is the machine precision. An approximate error bound for the computed solution is given by
x^ - x 1 x 1 ≤ κ A E 1 A 1
where κ A = A-1 1 A 1 , the condition number of A with respect to the solution of the linear equations. See Section 4.4 of Anderson et al. (1999) for further details.
Following the use of F07AAF (DGESV), F07AGF (DGECON) can be used to estimate the condition number of A and F07AHF (DGERFS) can be used to obtain approximate error bounds. Alternatives to F07AAF (DGESV), which return condition and error estimates directly are F04BAF and F07ABF (DGESVX).

8 Parallelism and Performance

F07AAF (DGESV) is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
F07AAF (DGESV) makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The total number of floating-point operations is approximately 23 n 3 + 2⁢n 2 r , where r is the number of right-hand sides.
The complex analogue of this routine is F07ANF (ZGESV).

10 Example

This example solves the equations
Ax = b ,
where A is the general matrix
A = 1.80 2.88 2.05 -0.89 5.25 -2.95 -0.95 -3.80 1.58 -2.69 -2.90 -1.04 -1.11 -0.66 -0.59 0.80   and   b = 9.52 24.35 0.77 -6.22 .
Details of the LU factorization of A are also output.

10.1 Program Text

Program Text (f07aafe.f90)

10.2 Program Data

Program Data (f07aafe.d)

10.3 Program Results

Program Results (f07aafe.r)

F07 Chapter Contents
F07 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F07ABF (DGESVX) : NAG Library, Mark 26

F07 Chapter Contents
F07 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F07ABF (DGESVX)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F07ABF (DGESVX) uses the LU factorization to compute the solution to a real system of linear equations
AX=B   or   AT X=B ,
where A is an n by n matrix and X and B are n by r matrices. Error bounds on the solution and a condition estimate are also provided.

2 Specification

SUBROUTINE F07ABF ( FACT, TRANS, N, NRHS, A, LDA, AF, LDAF, IPIV, EQUED, R, C, B, LDB, X, LDX, RCOND, FERR, BERR, WORK, IWORK, INFO)
INTEGER | N, NRHS, LDA, LDAF, IPIV(*), LDB, LDX, IWORK(N), INFO
REAL (KIND=nag_wp) | A(LDA,*), AF(LDAF,*), R(*), C(*), B(LDB,*), X(LDX,*), RCOND, FERR(NRHS), BERR(NRHS), WORK(max(1,4*N))
CHARACTER(1) | FACT, TRANS, EQUED
The routine may be called by its LAPACK name dgesvx.

3 Description

F07ABF (DGESVX) performs the following steps:
1. Equilibration
The linear system to be solved may be badly scaled. However, the system can be equilibrated as a first stage by setting FACT='E'. In this case, real scaling factors are computed and these factors then determine whether the system is to be equilibrated. Equilibrated forms of the systems AX=B and AT X=B are
DR A DC DC-1 X = DR B
and
DR A DC T DR-1 X = DC B ,
respectively, where DR and DC are diagonal matrices, with positive diagonal elements, formed from the computed scaling factors.
When equilibration is used, A will be overwritten by DR A DC and B will be overwritten by DR B (or DC B when the solution of AT X=B is sought).
2. Factorization
The matrix A, or its scaled form, is copied and factored using the LU decomposition
A=PLU ,
where P is a permutation matrix, L is a unit lower triangular matrix, and U is upper triangular.
This stage can be by-passed when a factored matrix (with scaled matrices and scaling factors) are supplied; for example, as provided by a previous call to F07ABF (DGESVX) with the same matrix A.
3. Condition Number Estimation
The LU factorization of A determines whether a solution to the linear system exists. If some diagonal element of U is zero, then U is exactly singular, no solution exists and the routine returns with a failure. Otherwise the factorized form of A is used to estimate the condition number of the matrix A. If the reciprocal of the condition number is less than machine precision then a warning code is returned on final exit.
4. Solution
The (equilibrated) system is solved for X ( DC-1 X or DR-1 X ) using the factored form of A ( DR A DC ).
5. Iterative Refinement
Iterative refinement is applied to improve the computed solution matrix and to calculate error bounds and backward error estimates for the computed solution.
6. Construct Solution Matrix X
If equilibration was used, the matrix X is premultiplied by DC (if TRANS='N') or DR (if TRANS='T' or 'C') so that it solves the original system before equilibration.

4 References

Anderson E, Bai Z, Bischof C, Blackford S, Demmel J, Dongarra J J, Du Croz J J, Greenbaum A, Hammarling S, McKenney A and Sorensen D (1999) LAPACK Users' Guide (3rd Edition) SIAM, Philadelphia http://www.netlib.org/lapack/lug
Golub G H and Van Loan C F (1996) Matrix Computations (3rd Edition) Johns Hopkins University Press, Baltimore
Higham N J (2002) Accuracy and Stability of Numerical Algorithms (2nd Edition) SIAM, Philadelphia

5 Arguments

1:   FACT – CHARACTER(1)Input
On entry: specifies whether or not the factorized form of the matrix A is supplied on entry, and if not, whether the matrix A should be equilibrated before it is factorized.
FACT='F'
AF and IPIV contain the factorized form of A. If EQUED≠'N', the matrix A has been equilibrated with scaling factors given by R and C. A, AF and IPIV are not modified.
FACT='N'
The matrix A will be copied to AF and factorized.
FACT='E'
The matrix A will be equilibrated if necessary, then copied to AF and factorized.
Constraint: FACT='F', 'N' or 'E'.
2:   TRANS – CHARACTER(1)Input
On entry: specifies the form of the system of equations.
TRANS='N'
AX=B (No transpose).
TRANS='T' or 'C'
AT X=B (Transpose).
Constraint: TRANS='N', 'T' or 'C'.
3:   N – INTEGERInput
On entry: n, the number of linear equations, i.e., the order of the matrix A.
Constraint: N≥0.
4:   NRHS – INTEGERInput
On entry: r, the number of right-hand sides, i.e., the number of columns of the matrix B.
Constraint: NRHS≥0.
5:   A LDA* – REAL (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array A must be at least max 1,N.
On entry: the n by n matrix A.
If FACT='F' and EQUED≠'N', A must have been equilibrated by the scaling factors in R and/or C.
On exit: if FACT='F' or 'N', or if FACT='E' and EQUED='N', A is not modified.
If FACT='E' or EQUED≠'N', A is scaled as follows:
  • if EQUED='R', A=DR A;
  • if EQUED='C', A=A DC;
  • if EQUED='B', A=DR A DC.
6:   LDA – INTEGERInput
On entry: the first dimension of the array A as declared in the (sub)program from which F07ABF (DGESVX) is called.
Constraint: LDA≥max 1,N.
7:   AF LDAF* – REAL (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array AF must be at least max 1,N.
On entry: if FACT='F', AF contains the factors L and U from the factorization A=PLU as computed by F07ADF (DGETRF). If EQUED≠'N', AF is the factorized form of the equilibrated matrix A.
If FACT='N' or 'E', AF need not be set.
On exit: if FACT='N', AF returns the factors L and U from the factorization A=PLU of the original matrix A.
If FACT='E', AF returns the factors L and U from the factorization A=PLU of the equilibrated matrix A (see the description of A for the form of the equilibrated matrix).
If FACT='F', AF is unchanged from entry.
8:   LDAF – INTEGERInput
On entry: the first dimension of the array AF as declared in the (sub)program from which F07ABF (DGESVX) is called.
Constraint: LDAF≥max 1,N.
9:   IPIV* – INTEGER arrayInput/Output
Note: the dimension of the array IPIV must be at least max 1,N.
On entry: if FACT='F', IPIV contains the pivot indices from the factorization A=PLU as computed by F07ADF (DGETRF); at the ith step row i of the matrix was interchanged with row IPIV i. IPIV i=i indicates a row interchange was not required.
If FACT='N' or 'E', IPIV need not be set.
On exit: if FACT='N', IPIV contains the pivot indices from the factorization A=PLU of the original matrix A.
If FACT='E', IPIV contains the pivot indices from the factorization A=PLU of the equilibrated matrix A.
If FACT='F', IPIV is unchanged from entry.
10:   EQUED – CHARACTER(1)Input/Output
On entry: if FACT='N' or 'E', EQUED need not be set.
If FACT='F', EQUED must specify the form of the equilibration that was performed as follows:
  • if EQUED='N', no equilibration;
  • if EQUED='R', row equilibration, i.e., A has been premultiplied by DR;
  • if EQUED='C', column equilibration, i.e., A has been postmultiplied by DC;
  • if EQUED='B', both row and column equilibration, i.e., A has been replaced by DR A DC.
On exit: if FACT='F', EQUED is unchanged from entry.
Otherwise, if no constraints are violated, EQUED specifies the form of equilibration that was performed as specified above.
Constraint: if FACT='F', EQUED='N', 'R', 'C' or 'B'.
11:   R* – REAL (KIND=nag_wp) arrayInput/Output
Note: the dimension of the array R must be at least max 1,N.
On entry: if FACT='N' or 'E', R need not be set.
If FACT='F' and EQUED='R' or 'B', R must contain the row scale factors for A, DR; each element of R must be positive.
On exit: if FACT='F', R is unchanged from entry.
Otherwise, if no constraints are violated and EQUED='R' or 'B', R contains the row scale factors for A, DR, such that A is multiplied on the left by DR; each element of R is positive.
12:   C* – REAL (KIND=nag_wp) arrayInput/Output
Note: the dimension of the array C must be at least max 1,N.
On entry: if FACT='N' or 'E', C need not be set.
If FACT='F' or EQUED='C' or 'B', C must contain the column scale factors for A, DC; each element of C must be positive.
On exit: if FACT='F', C is unchanged from entry.
Otherwise, if no constraints are violated and EQUED='C' or 'B', C contains the row scale factors for A, DC; each element of C is positive.
13:   B LDB* – REAL (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array B must be at least max 1,NRHS.
On entry: the n by r right-hand side matrix B.
On exit: if EQUED='N', B is not modified.
If TRANS='N' and EQUED='R' or 'B', B is overwritten by DR B.
If TRANS='T' or 'C' and EQUED='C' or 'B', B is overwritten by DC B.
14:   LDB – INTEGERInput
On entry: the first dimension of the array B as declared in the (sub)program from which F07ABF (DGESVX) is called.
Constraint: LDB≥max 1,N.
15:   X LDX* – REAL (KIND=nag_wp) arrayOutput
Note: the second dimension of the array X must be at least max 1,NRHS.
On exit: if INFO=0 or N+1, the n by r solution matrix X to the original system of equations. Note that the arrays A and B are modified on exit if EQUED≠'N', and the solution to the equilibrated system is DC-1 X if TRANS='N' and EQUED='C' or 'B', or DR-1 X if TRANS='T' or 'C' and EQUED='R' or 'B'.
16:   LDX – INTEGERInput
On entry: the first dimension of the array X as declared in the (sub)program from which F07ABF (DGESVX) is called.
Constraint: LDX≥max 1,N.
17:   RCOND – REAL (KIND=nag_wp)Output
On exit: if no constraints are violated, an estimate of the reciprocal condition number of the matrix A (after equilibration if that is performed), computed as RCOND=1.0/A 1 A-1 1 .
18:   FERR NRHS – REAL (KIND=nag_wp) arrayOutput
On exit: if INFO=0 or N+1, an estimate of the forward error bound for each computed solution vector, such that x^j-xj∞/xj∞≤FERR j where x^j is the jth column of the computed solution returned in the array X and xj is the corresponding column of the exact solution X. The estimate is as reliable as the estimate for RCOND, and is almost always a slight overestimate of the true error.
19:   BERR NRHS – REAL (KIND=nag_wp) arrayOutput
On exit: if INFO=0 or N+1, an estimate of the component-wise relative backward error of each computed solution vector x^j (i.e., the smallest relative change in any element of A or B that makes x^j an exact solution).
20:   WORK max 1,4×N – REAL (KIND=nag_wp) arrayOutput
On exit: WORK 1 contains the reciprocal pivot growth factor A/U. The ‘max absolute element’ norm is used. If WORK 1 is much less than 1, then the stability of the LU factorization of the (equilibrated) matrix A could be poor. This also means that the solution X, condition estimate RCOND, and forward error bound FERR could be unreliable. If the factorization fails with INFO>0 and INFO≤N, then WORK 1 contains the reciprocal pivot growth factor for the leading INFO columns of A.
21:   IWORK N – INTEGER arrayWorkspace
22:   INFO – INTEGEROutput
On exit: INFO=0 unless the routine detects an error (see Section 6).

6 Error Indicators and Warnings

INFO<0
If INFO=-i, argument i had an illegal value. An explanatory message is output, and execution of the program is terminated.
INFO>0 and INFO≤N
Element value of the diagonal is exactly zero. The factorization has been completed, but the factor U is exactly singular, so the solution and error bounds could not be computed. RCOND=0.0 is returned.
INFO=N+1
U is nonsingular, but RCOND is less than machine precision, meaning that the matrix is singular to working precision. Nevertheless, the solution and error bounds are computed because there are a number of situations where the computed solution can be more accurate than the value of RCOND would suggest.

7 Accuracy

For each right-hand side vector b, the computed solution x^ is the exact solution of a perturbed system of equations A+E x^=b, where
E≤c n εP LU ,
c n is a modest linear function of n, and ε is the machine precision. See Section 9.3 of Higham (2002) for further details.
If x is the true solution, then the computed solution x^ satisfies a forward error bound of the form
x-x^∞ x^∞ ≤ wc cond A,x^,b
where cond A,x^,b = A-1 A x^ + b ∞/ x^∞ ≤ cond A = A-1 A ∞≤κ∞ A. If x^ is the j th column of X , then wc is returned in BERR j and a bound on x - x^ ∞ / x^ ∞ is returned in FERR j . See Section 4.4 of Anderson et al. (1999) for further details.

8 Parallelism and Performance

F07ABF (DGESVX) is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
F07ABF (DGESVX) makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The factorization of A requires approximately 23 n 3 floating-point operations.
Estimating the forward error involves solving a number of systems of linear equations of the form Ax=b or AT x=b; the number is usually 4 or 5 and never more than 11. Each solution involves approximately 2⁢n 2 operations.
In practice the condition number estimator is very reliable, but it can underestimate the true condition number; see Section 15.3 of Higham (2002) for further details.
The complex analogue of this routine is F07APF (ZGESVX).

10 Example

This example solves the equations
AX=B ,
where A is the general matrix
A= 1.80 2.88 2.05 -0.89 525.00 -295.00 -95.00 -380.00 1.58 -2.69 -2.90 -1.04 -1.11 -0.66 -0.59 -0.80
and
B = 9.52 18.47 2435.00 225.00 0.77 -13.28 -6.22 -6.21 .
Error estimates for the solutions, information on scaling, an estimate of the reciprocal of the condition number of the scaled matrix A and an estimate of the reciprocal of the pivot growth factor for the factorization of A are also output.

10.1 Program Text

Program Text (f07abfe.f90)

10.2 Program Data

Program Data (f07abfe.d)

10.3 Program Results

Program Results (f07abfe.r)

F07 Chapter Contents
F07 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F07ACF (DSGESV) : NAG Library, Mark 26

F07 Chapter Contents
F07 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F07ACF (DSGESV)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F07ACF (DSGESV) computes the solution to a real system of linear equations
AX=B ,
where A is an n by n matrix and X and B are n by r matrices.

2 Specification

SUBROUTINE F07ACF ( N, NRHS, A, LDA, IPIV, B, LDB, X, LDX, WORK, SWORK, ITER, INFO)
INTEGER | N, NRHS, LDA, IPIV(N), LDB, LDX, ITER, INFO
REAL (KIND=nag_wp) | A(LDA,*), B(LDB,*), X(LDX,*), WORK(N*NRHS)
REAL (KIND=nag_rp) | SWORK(N*(N+NRHS))
The routine may be called by its LAPACK name dsgesv.

3 Description

F07ACF (DSGESV) first attempts to factorize the matrix in single precision and use this factorization within an iterative refinement procedure to produce a solution with full double precision accuracy. If the approach fails the method switches to a double precision factorization and solve.
The iterative refinement process is stopped if
ITER>itermax ,
where ITER is the number of iterations carried out thus far and itermax is the maximum number of iterations allowed, which is fixed at 30 iterations. The process is also stopped if for all right-hand sides we have
resid < N x A ε ,
where resid is the ∞-norm of the residual, x is the ∞-norm of the solution, A is the ∞-operator-norm of the matrix A and ε is the machine precision returned by X02AJF.
The iterative refinement strategy used by F07ACF (DSGESV) can be more efficient than the corresponding direct full precision algorithm. Since this strategy must perform iterative refinement on each right-hand side, any efficiency gains will reduce as the number of right-hand sides increases. Conversely, as the matrix size increases the cost of these iterative refinements become less significant relative to the cost of factorization. Thus, any efficiency gains will be greatest for a very small number of right-hand sides and for large matrix sizes. The cut-off values for the number of right-hand sides and matrix size, for which the iterative refinement strategy performs better, depends on the relative performance of the reduced and full precision factorization and back-substitution. For now, F07ACF (DSGESV) always attempts the iterative refinement strategy first; you are advised to compare the performance of F07ACF (DSGESV) with that of its full precision counterpart F07AAF (DGESV) to determine whether this strategy is worthwhile for your particular problem dimensions.

4 References

Anderson E, Bai Z, Bischof C, Blackford S, Demmel J, Dongarra J J, Du Croz J J, Greenbaum A, Hammarling S, McKenney A and Sorensen D (1999) LAPACK Users' Guide (3rd Edition) SIAM, Philadelphia http://www.netlib.org/lapack/lug
Buttari A, Dongarra J, Langou J, Langou J, Luszczek P and Kurzak J (2007) Mixed precision iterative refinement techniques for the solution of dense linear systems International Journal of High Performance Computing Applications
Golub G H and Van Loan C F (1996) Matrix Computations (3rd Edition) Johns Hopkins University Press, Baltimore

5 Arguments

1:   N – INTEGERInput
On entry: n, the number of linear equations, i.e., the order of the matrix A.
Constraint: N≥0.
2:   NRHS – INTEGERInput
On entry: r, the number of right-hand sides, i.e., the number of columns of the matrix B.
Constraint: NRHS≥0.
3:   A LDA* – REAL (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array A must be at least max 1,N.
On entry: the n by n coefficient matrix A.
On exit: if iterative refinement has been successfully used (i.e., if INFO=0 and ITER≥0), then A is unchanged. If double precision factorization has been used (when INFO=0 and ITER<0), A contains the factors L and U from the factorization A=PLU; the unit diagonal elements of L are not stored.
4:   LDA – INTEGERInput
On entry: the first dimension of the array A as declared in the (sub)program from which F07ACF (DSGESV) is called.
Constraint: LDA≥max 1,N.
5:   IPIV N – INTEGER arrayOutput
On exit: if no constraints are violated, the pivot indices that define the permutation matrix P; at the ith step row i of the matrix was interchanged with row IPIV i. IPIV i=i indicates a row interchange was not required. IPIV corresponds either to the single precision factorization (if INFO=0 and ITER≥0) or to the double precision factorization (if INFO=0 and ITER<0).
6:   B LDB* – REAL (KIND=nag_wp) arrayInput
Note: the second dimension of the array B must be at least max 1,NRHS.
On entry: the n by r right-hand side matrix B.
7:   LDB – INTEGERInput
On entry: the first dimension of the array B as declared in the (sub)program from which F07ACF (DSGESV) is called.
Constraint: LDB≥max 1,N.
8:   X LDX* – REAL (KIND=nag_wp) arrayOutput
Note: the second dimension of the array X must be at least max 1,NRHS.
On exit: if INFO=0, the n by r solution matrix X.
9:   LDX – INTEGERInput
On entry: the first dimension of the array X as declared in the (sub)program from which F07ACF (DSGESV) is called.
Constraint: LDX≥max 1,N.
10:   WORK N*NRHS – REAL (KIND=nag_wp) arrayWorkspace
11:   SWORK N×N+NRHS – REAL (KIND=nag_rp) arrayWorkspace
Note: this array is utilized in the reduced precision computation, consequently its type nag_rp reflects this usage.
12:   ITER – INTEGEROutput
On exit: if ITER>0, iterative refinement has been successfully used and ITER is the number of iterations carried out.
If ITER<0, iterative refinement has failed for one of the reasons given below and double precision factorization has been carried out instead.
ITER=-1
Taking into account machine parameters, and the values of N and NRHS, it is not worth working in single precision.
ITER=-2
Overflow of an entry occurred when moving from double to single precision.
ITER=-3
An intermediate single precision factorization failed.
ITER=-31
The maximum permitted number of iterations was exceeded.
13:   INFO – INTEGEROutput
On exit: INFO=0 unless the routine detects an error (see Section 6).

6 Error Indicators and Warnings

INFO<0
If INFO=-i, argument i had an illegal value. An explanatory message is output, and execution of the program is terminated.
INFO>0
Element value of the diagonal is exactly zero. The factorization has been completed, but the factor U is exactly singular, so the solution could not be computed.

7 Accuracy

The computed solution for a single right-hand side, x^ , satisfies the equation of the form
A+E x^=b ,
where
E 1 = O ε A 1
and ε is the machine precision. An approximate error bound for the computed solution is given by
x^ - x 1 x 1 ≤ κ A E 1 A 1
where κ A = A-1 1 A 1 , the condition number of A with respect to the solution of the linear equations. See Section 4.4 of Anderson et al. (1999) for further details.

8 Parallelism and Performance

F07ACF (DSGESV) is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
F07ACF (DSGESV) makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The complex analogue of this routine is F07AQF (ZCGESV).

10 Example

This example solves the equations
Ax = b ,
where A is the general matrix
A = 1.80 2.88 2.05 -0.89 5.25 -2.95 -0.95 -3.80 1.58 -2.69 -2.90 -1.04 -1.11 -0.66 -0.59 0.80   and   b = 9.52 24.35 0.77 -6.22 .

10.1 Program Text

Program Text (f07acfe.f90)

10.2 Program Data

Program Data (f07acfe.d)

10.3 Program Results

Program Results (f07acfe.r)

F07 Chapter Contents
F07 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F07ADF (DGETRF) : NAG Library, Mark 26

F07 Chapter Contents
F07 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F07ADF (DGETRF)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F07ADF (DGETRF) computes the LU factorization of a real m by n matrix.

2 Specification

SUBROUTINE F07ADF ( M, N, A, LDA, IPIV, INFO)
INTEGER | M, N, LDA, IPIV(min(M,N)), INFO
REAL (KIND=nag_wp) | A(LDA,*)
The routine may be called by its LAPACK name dgetrf.

3 Description

F07ADF (DGETRF) forms the LU factorization of a real m by n matrix A as A=PLU, where P is a permutation matrix, L is lower triangular with unit diagonal elements (lower trapezoidal if m>n) and U is upper triangular (upper trapezoidal if m<n). Usually A is square m=n, and both L and U are triangular. The routine uses partial pivoting, with row interchanges.

4 References

Golub G H and Van Loan C F (1996) Matrix Computations (3rd Edition) Johns Hopkins University Press, Baltimore

5 Arguments

1:   M – INTEGERInput
On entry: m, the number of rows of the matrix A.
Constraint: M≥0.
2:   N – INTEGERInput
On entry: n, the number of columns of the matrix A.
Constraint: N≥0.
3:   A LDA* – REAL (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array A must be at least max 1,N.
On entry: the m by n matrix A.
On exit: the factors L and U from the factorization A=PLU; the unit diagonal elements of L are not stored.
4:   LDA – INTEGERInput
On entry: the first dimension of the array A as declared in the (sub)program from which F07ADF (DGETRF) is called.
Constraint: LDA≥max 1,M.
5:   IPIV min M,N – INTEGER arrayOutput
On exit: the pivot indices that define the permutation matrix. At the ith step, if IPIV i>i then row i of the matrix A was interchanged with row IPIV i, for i=1,2,…,min m,n. IPIV i≤i indicates that, at the ith step, a row interchange was not required.
6:   INFO – INTEGEROutput
On exit: INFO=0 unless the routine detects an error (see Section 6).

6 Error Indicators and Warnings

INFO<0
If INFO=-i, argument i had an illegal value. An explanatory message is output, and execution of the program is terminated.
INFO>0
Element value of the diagonal is exactly zero. The factorization has been completed, but the factor U is exactly singular, and division by zero will occur if it is used to solve a system of equations.

7 Accuracy

The computed factors L and U are the exact factors of a perturbed matrix A+E, where
E ≤ c min m,n ε P L U ,
c n is a modest linear function of n, and ε is the machine precision.

8 Parallelism and Performance

F07ADF (DGETRF) is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
F07ADF (DGETRF) makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The total number of floating-point operations is approximately 23 n 3 if m=n (the usual case), 13 n 2 3 m-n if m>n and 13 m 2 3 n-m if m<n.
A call to this routine with m=n may be followed by calls to the routines:
  • F07AEF (DGETRS) to solve AX=B or AT X=B;
  • F07AGF (DGECON) to estimate the condition number of A;
  • F07AJF (DGETRI) to compute the inverse of A.
The complex analogue of this routine is F07ARF (ZGETRF).

10 Example

This example computes the LU factorization of the matrix A, where
A= 1.80 2.88 2.05 -0.89 5.25 -2.95 -0.95 -3.80 1.58 -2.69 -2.90 -1.04 -1.11 -0.66 -0.59 0.80 .

10.1 Program Text

Program Text (f07adfe.f90)

10.2 Program Data

Program Data (f07adfe.d)

10.3 Program Results

Program Results (f07adfe.r)

F07 Chapter Contents
F07 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F07AEF (DGETRS) : NAG Library, Mark 26

F07 Chapter Contents
F07 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F07AEF (DGETRS)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F07AEF (DGETRS) solves a real system of linear equations with multiple right-hand sides,
AX=B   or   AT X=B ,
where A has been factorized by F07ADF (DGETRF).

2 Specification

SUBROUTINE F07AEF ( TRANS, N, NRHS, A, LDA, IPIV, B, LDB, INFO)
INTEGER | N, NRHS, LDA, IPIV(*), LDB, INFO
REAL (KIND=nag_wp) | A(LDA,*), B(LDB,*)
CHARACTER(1) | TRANS
The routine may be called by its LAPACK name dgetrs.

3 Description

F07AEF (DGETRS) is used to solve a real system of linear equations AX=B or AT X=B, the routine must be preceded by a call to F07ADF (DGETRF) which computes the LU factorization of A as A=PLU. The solution is computed by forward and backward substitution.
If TRANS='N', the solution is computed by solving PLY=B and then UX=Y.
If TRANS='T' or 'C', the solution is computed by solving UT Y=B and then LTPT X=Y.

4 References

Golub G H and Van Loan C F (1996) Matrix Computations (3rd Edition) Johns Hopkins University Press, Baltimore

5 Arguments

1:   TRANS – CHARACTER(1)Input
On entry: indicates the form of the equations.
TRANS='N'
AX=B is solved for X.
TRANS='T' or 'C'
AT X=B is solved for X.
Constraint: TRANS='N', 'T' or 'C'.
2:   N – INTEGERInput
On entry: n, the order of the matrix A.
Constraint: N≥0.
3:   NRHS – INTEGERInput
On entry: r, the number of right-hand sides.
Constraint: NRHS≥0.
4:   A LDA* – REAL (KIND=nag_wp) arrayInput
Note: the second dimension of the array A must be at least max 1,N.
On entry: the LU factorization of A, as returned by F07ADF (DGETRF).
5:   LDA – INTEGERInput
On entry: the first dimension of the array A as declared in the (sub)program from which F07AEF (DGETRS) is called.
Constraint: LDA≥max 1,N.
6:   IPIV* – INTEGER arrayInput
Note: the dimension of the array IPIV must be at least max 1,N.
On entry: the pivot indices, as returned by F07ADF (DGETRF).
7:   B LDB* – REAL (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array B must be at least max 1,NRHS.
On entry: the n by r right-hand side matrix B.
On exit: the n by r solution matrix X.
8:   LDB – INTEGERInput
On entry: the first dimension of the array B as declared in the (sub)program from which F07AEF (DGETRS) is called.
Constraint: LDB≥max 1,N.
9:   INFO – INTEGEROutput
On exit: INFO=0 unless the routine detects an error (see Section 6).

6 Error Indicators and Warnings

INFO<0
If INFO=-i, argument i had an illegal value. An explanatory message is output, and execution of the program is terminated.

7 Accuracy

For each right-hand side vector b, the computed solution x is the exact solution of a perturbed system of equations A+E x=b, where
E≤c n εP LU ,
c n is a modest linear function of n, and ε is the machine precision.
If x^ is the true solution, then the computed solution x satisfies a forward error bound of the form
x-x^∞ x∞ ≤c n cond A,x ε
where cond A,x = A-1 A x ∞ / x∞ ≤ cond A = A-1 A ∞ ≤ κ∞ A .
Note that cond A,x can be much smaller than cond A, and cond AT can be much larger (or smaller) than cond A.
Forward and backward error bounds can be computed by calling F07AHF (DGERFS), and an estimate for κ∞A can be obtained by calling F07AGF (DGECON) with NORM='I'.

8 Parallelism and Performance

F07AEF (DGETRS) is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
F07AEF (DGETRS) makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The total number of floating-point operations is approximately 2⁢n 2 r.
This routine may be followed by a call to F07AHF (DGERFS) to refine the solution and return an error estimate.
The complex analogue of this routine is F07ASF (ZGETRS).

10 Example

This example solves the system of equations AX=B, where
A= 1.80 2.88 2.05 -0.89 5.25 -2.95 -0.95 -3.80 1.58 -2.69 -2.90 -1.04 -1.11 -0.66 -0.59 0.80   and   B= 9.52 18.47 24.35 2.25 0.77 -13.28 -6.22 -6.21 .
Here A is nonsymmetric and must first be factorized by F07ADF (DGETRF).

10.1 Program Text

Program Text (f07aefe.f90)

10.2 Program Data

Program Data (f07aefe.d)

10.3 Program Results

Program Results (f07aefe.r)

F07 Chapter Contents
F07 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F07AFF (DGEEQU) : NAG Library, Mark 26

F07 Chapter Contents
F07 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F07AFF (DGEEQU)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F07AFF (DGEEQU) computes diagonal scaling matrices DR and DC intended to equilibrate a real m by n matrix A and reduce its condition number.

2 Specification

SUBROUTINE F07AFF ( M, N, A, LDA, R, C, ROWCND, COLCND, AMAX, INFO)
INTEGER | M, N, LDA, INFO
REAL (KIND=nag_wp) | A(LDA,*), R(M), C(N), ROWCND, COLCND, AMAX
The routine may be called by its LAPACK name dgeequ.

3 Description

F07AFF (DGEEQU) computes the diagonal scaling matrices. The diagonal scaling matrices are chosen to try to make the elements of largest absolute value in each row and column of the matrix B given by
B=DR A DC
have absolute value 1. The diagonal elements of DR and DC are restricted to lie in the safe range δ,1/δ , where δ is the value returned by routine X02AMF. Use of these scaling factors is not guaranteed to reduce the condition number of A but works well in practice.

4 References

None.

5 Arguments

1:   M – INTEGERInput
On entry: m, the number of rows of the matrix A.
Constraint: M≥0.
2:   N – INTEGERInput
On entry: n, the number of columns of the matrix A.
Constraint: N≥0.
3:   A LDA* – REAL (KIND=nag_wp) arrayInput
Note: the second dimension of the array A must be at least max 1,N.
On entry: the matrix A whose scaling factors are to be computed.
4:   LDA – INTEGERInput
On entry: the first dimension of the array A as declared in the (sub)program from which F07AFF (DGEEQU) is called.
Constraint: LDA≥max 1,M.
5:   R M – REAL (KIND=nag_wp) arrayOutput
On exit: if INFO=0 or INFO>M, R contains the row scale factors, the diagonal elements of DR. The elements of R will be positive.
6:   C N – REAL (KIND=nag_wp) arrayOutput
On exit: if INFO=0, C contains the column scale factors, the diagonal elements of DC. The elements of C will be positive.
7:   ROWCND – REAL (KIND=nag_wp)Output
On exit: if INFO=0 or INFO>M, ROWCND contains the ratio of the smallest value of R i to the largest value of R i. If ROWCND≥0.1 and AMAX is neither too large nor too small, it is not worth scaling by DR.
8:   COLCND – REAL (KIND=nag_wp)Output
On exit: if INFO=0, COLCND contains the ratio of the smallest value of C i to the largest value of C i.
If COLCND≥0.1, it is not worth scaling by DC.
9:   AMAX – REAL (KIND=nag_wp)Output
On exit: max a ij. If AMAX is very close to overflow or underflow, the matrix A should be scaled.
10:   INFO – INTEGEROutput
On exit: INFO=0 unless the routine detects an error (see Section 6).

6 Error Indicators and Warnings

INFO<0
If INFO=-i, argument i had an illegal value. An explanatory message is output, and execution of the program is terminated.
INFO>0 and INFO≤M
Row value of A is exactly zero.
INFO>M
Column value of A is exactly zero.

7 Accuracy

The computed scale factors will be close to the exact scale factors.

8 Parallelism and Performance

F07AFF (DGEEQU) is not threaded in any implementation.

9 Further Comments

The complex analogue of this routine is F07ATF (ZGEEQU).

10 Example

This example equilibrates the general matrix A given by
A = -1.80×1010 -2.88×1010 -2.05 -8.90×109 -5.25 -2.95 -9.50×10-9 -3.80 -1.58 -2.69 -2.90×10-10 -1.04 -1.11 -0.66 -5.90×10-11 -0.80 .
Details of the scaling factors, and the scaled matrix are output.

10.1 Program Text

Program Text (f07affe.f90)

10.2 Program Data

Program Data (f07affe.d)

10.3 Program Results

Program Results (f07affe.r)

F07 Chapter Contents
F07 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F07AGF (DGECON) : NAG Library, Mark 26

F07 Chapter Contents
F07 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F07AGF (DGECON)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F07AGF (DGECON) estimates the condition number of a real matrix A, where A has been factorized by F07ADF (DGETRF).

2 Specification

SUBROUTINE F07AGF ( NORM, N, A, LDA, ANORM, RCOND, WORK, IWORK, INFO)
INTEGER | N, LDA, IWORK(N), INFO
REAL (KIND=nag_wp) | A(LDA,*), ANORM, RCOND, WORK(4*N)
CHARACTER(1) | NORM
The routine may be called by its LAPACK name dgecon.

3 Description

F07AGF (DGECON) estimates the condition number of a real matrix A, in either the 1-norm or the ∞-norm:
κ 1 A = A 1 A-1 1   or   κ∞ A = A∞ A-1∞ .
Note that κ∞A=κ 1 AT.
Because the condition number is infinite if A is singular, the routine actually returns an estimate of the reciprocal of the condition number.
The routine should be preceded by a call to F06RAF to compute A 1 or A∞, and a call to F07ADF (DGETRF) to compute the LU factorization of A. The routine then uses Higham's implementation of Hager's method (see Higham (1988)) to estimate A-1 1 or A-1∞.

4 References

Higham N J (1988) FORTRAN codes for estimating the one-norm of a real or complex matrix, with applications to condition estimation ACM Trans. Math. Software 14 381–396

5 Arguments

1:   NORM – CHARACTER(1)Input
On entry: indicates whether κ 1 A or κ∞A is estimated.
NORM='1' or 'O'
κ 1 A is estimated.
NORM='I'
κ∞A is estimated.
Constraint: NORM='1', 'O' or 'I'.
2:   N – INTEGERInput
On entry: n, the order of the matrix A.
Constraint: N≥0.
3:   A LDA* – REAL (KIND=nag_wp) arrayInput
Note: the second dimension of the array A must be at least max 1,N.
On entry: the LU factorization of A, as returned by F07ADF (DGETRF).
4:   LDA – INTEGERInput
On entry: the first dimension of the array A as declared in the (sub)program from which F07AGF (DGECON) is called.
Constraint: LDA≥max 1,N.
5:   ANORM – REAL (KIND=nag_wp)Input
On entry: if NORM='1' or 'O', the 1-norm of the original matrix A.
If NORM='I', the ∞-norm of the original matrix A.
ANORM may be computed by calling F06RAF with the same value for the argument NORM.
ANORM must be computed either before calling F07ADF (DGETRF) or else from a copy of the original matrix A (see Section 10).
Constraint: ANORM≥0.0.
6:   RCOND – REAL (KIND=nag_wp)Output
On exit: an estimate of the reciprocal of the condition number of A. RCOND is set to zero if exact singularity is detected or the estimate underflows. If RCOND is less than machine precision, A is singular to working precision.
7:   WORK 4×N – REAL (KIND=nag_wp) arrayWorkspace
8:   IWORK N – INTEGER arrayWorkspace
9:   INFO – INTEGEROutput
On exit: INFO=0 unless the routine detects an error (see Section 6).

6 Error Indicators and Warnings

INFO<0
If INFO=-i, argument i had an illegal value. An explanatory message is output, and execution of the program is terminated.

7 Accuracy

The computed estimate RCOND is never less than the true value ρ, and in practice is nearly always less than 10 ρ, although examples can be constructed where RCOND is much larger.

8 Parallelism and Performance

F07AGF (DGECON) makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

A call to F07AGF (DGECON) involves solving a number of systems of linear equations of the form Ax=b or AT x=b; the number is usually 4 or 5 and never more than 11. Each solution involves approximately 2⁢n 2 floating-point operations but takes considerably longer than a call to F07AEF (DGETRS) with one right-hand side, because extra care is taken to avoid overflow when A is approximately singular.
The complex analogue of this routine is F07AUF (ZGECON).

10 Example

This example estimates the condition number in the 1-norm of the matrix A, where
A= 1.80 2.88 2.05 -0.89 5.25 -2.95 -0.95 -3.80 1.58 -2.69 -2.90 -1.04 -1.11 -0.66 -0.59 0.80 .
Here A is nonsymmetric and must first be factorized by F07ADF (DGETRF). The true condition number in the 1-norm is 152.16.

10.1 Program Text

Program Text (f07agfe.f90)

10.2 Program Data

Program Data (f07agfe.d)

10.3 Program Results

Program Results (f07agfe.r)

F07 Chapter Contents
F07 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F07AHF (DGERFS) : NAG Library, Mark 26

F07 Chapter Contents
F07 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F07AHF (DGERFS)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F07AHF (DGERFS) returns error bounds for the solution of a real system of linear equations with multiple right-hand sides, AX=B or AT X=B. It improves the solution by iterative refinement, in order to reduce the backward error as much as possible.

2 Specification

SUBROUTINE F07AHF ( TRANS, N, NRHS, A, LDA, AF, LDAF, IPIV, B, LDB, X, LDX, FERR, BERR, WORK, IWORK, INFO)
INTEGER | N, NRHS, LDA, LDAF, IPIV(*), LDB, LDX, IWORK(N), INFO
REAL (KIND=nag_wp) | A(LDA,*), AF(LDAF,*), B(LDB,*), X(LDX,*), FERR(NRHS), BERR(NRHS), WORK(3*N)
CHARACTER(1) | TRANS
The routine may be called by its LAPACK name dgerfs.

3 Description

F07AHF (DGERFS) returns the backward errors and estimated bounds on the forward errors for the solution of a real system of linear equations with multiple right-hand sides AX=B or AT X=B. The routine handles each right-hand side vector (stored as a column of the matrix B) independently, so we describe the function of F07AHF (DGERFS) in terms of a single right-hand side b and solution x.
Given a computed solution x, the routine computes the component-wise backward error β. This is the size of the smallest relative perturbation in each element of A and b such that x is the exact solution of a perturbed system
A+δA x=b+δb δ a ij≤β a ij   and   δ bi≤β bi .
Then the routine estimates a bound for the component-wise forward error in the computed solution, defined by:
maxi xi - x^i / maxi xi
where x^ is the true solution.
For details of the method, see the F07 Chapter Introduction.

4 References

Golub G H and Van Loan C F (1996) Matrix Computations (3rd Edition) Johns Hopkins University Press, Baltimore

5 Arguments

1:   TRANS – CHARACTER(1)Input
On entry: indicates the form of the linear equations for which X is the computed solution.
TRANS='N'
The linear equations are of the form AX=B.
TRANS='T' or 'C'
The linear equations are of the form AT X=B.
Constraint: TRANS='N', 'T' or 'C'.
2:   N – INTEGERInput
On entry: n, the order of the matrix A.
Constraint: N≥0.
3:   NRHS – INTEGERInput
On entry: r, the number of right-hand sides.
Constraint: NRHS≥0.
4:   A LDA* – REAL (KIND=nag_wp) arrayInput
Note: the second dimension of the array A must be at least max 1,N.
On entry: the n by n original matrix A as supplied to F07ADF (DGETRF).
5:   LDA – INTEGERInput
On entry: the first dimension of the array A as declared in the (sub)program from which F07AHF (DGERFS) is called.
Constraint: LDA≥max 1,N.
6:   AF LDAF* – REAL (KIND=nag_wp) arrayInput
Note: the second dimension of the array AF must be at least max 1,N.
On entry: the LU factorization of A, as returned by F07ADF (DGETRF).
7:   LDAF – INTEGERInput
On entry: the first dimension of the array AF as declared in the (sub)program from which F07AHF (DGERFS) is called.
Constraint: LDAF≥max 1,N.
8:   IPIV* – INTEGER arrayInput
Note: the dimension of the array IPIV must be at least max 1,N.
On entry: the pivot indices, as returned by F07ADF (DGETRF).
9:   B LDB* – REAL (KIND=nag_wp) arrayInput
Note: the second dimension of the array B must be at least max 1,NRHS.
On entry: the n by r right-hand side matrix B.
10:   LDB – INTEGERInput
On entry: the first dimension of the array B as declared in the (sub)program from which F07AHF (DGERFS) is called.
Constraint: LDB≥max 1,N.
11:   X LDX* – REAL (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array X must be at least max 1,NRHS.
On entry: the n by r solution matrix X, as returned by F07AEF (DGETRS).
On exit: the improved solution matrix X.
12:   LDX – INTEGERInput
On entry: the first dimension of the array X as declared in the (sub)program from which F07AHF (DGERFS) is called.
Constraint: LDX≥max 1,N.
13:   FERR NRHS – REAL (KIND=nag_wp) arrayOutput
On exit: FERR j contains an estimated error bound for the jth solution vector, that is, the jth column of X, for j=1,2,…,r.
14:   BERR NRHS – REAL (KIND=nag_wp) arrayOutput
On exit: BERR j contains the component-wise backward error bound β for the jth solution vector, that is, the jth column of X, for j=1,2,…,r.
15:   WORK 3×N – REAL (KIND=nag_wp) arrayWorkspace
16:   IWORK N – INTEGER arrayWorkspace
17:   INFO – INTEGEROutput
On exit: INFO=0 unless the routine detects an error (see Section 6).

6 Error Indicators and Warnings

INFO<0
If INFO=-i, argument i had an illegal value. An explanatory message is output, and execution of the program is terminated.

7 Accuracy

The bounds returned in FERR are not rigorous, because they are estimated, not computed exactly; but in practice they almost always overestimate the actual error.

8 Parallelism and Performance

F07AHF (DGERFS) is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
F07AHF (DGERFS) makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

For each right-hand side, computation of the backward error involves a minimum of 4⁢n 2 floating-point operations. Each step of iterative refinement involves an additional 6⁢n 2 operations. At most five steps of iterative refinement are performed, but usually only one or two steps are required.
Estimating the forward error involves solving a number of systems of linear equations of the form Ax=b or AT x=b; the number is usually 4 or 5 and never more than 11. Each solution involves approximately 2⁢n 2 operations.
The complex analogue of this routine is F07AVF (ZGERFS).

10 Example

This example solves the system of equations AX=B using iterative refinement and to compute the forward and backward error bounds, where
A= 1.80 2.88 2.05 -0.89 5.25 -2.95 -0.95 -3.80 1.58 -2.69 -2.90 -1.04 -1.11 -0.66 -0.59 0.80   and   B= 9.52 18.47 24.35 2.25 0.77 -13.28 -6.22 -6.21 .
Here A is nonsymmetric and must first be factorized by F07ADF (DGETRF).

10.1 Program Text

Program Text (f07ahfe.f90)

10.2 Program Data

Program Data (f07ahfe.d)

10.3 Program Results

Program Results (f07ahfe.r)

F07 Chapter Contents
F07 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F07AJF (DGETRI) : NAG Library, Mark 26

F07 Chapter Contents
F07 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F07AJF (DGETRI)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F07AJF (DGETRI) computes the inverse of a real matrix A, where A has been factorized by F07ADF (DGETRF).

2 Specification

SUBROUTINE F07AJF ( N, A, LDA, IPIV, WORK, LWORK, INFO)
INTEGER | N, LDA, IPIV(*), LWORK, INFO
REAL (KIND=nag_wp) | A(LDA,*), WORK(max(1,LWORK))
The routine may be called by its LAPACK name dgetri.

3 Description

F07AJF (DGETRI) is used to compute the inverse of a real matrix A, the routine must be preceded by a call to F07ADF (DGETRF), which computes the LU factorization of A as A=PLU. The inverse of A is computed by forming U-1 and then solving the equation XPL=U-1 for X.

4 References

Du Croz J J and Higham N J (1992) Stability of methods for matrix inversion IMA J. Numer. Anal. 12 1–19

5 Arguments

1:   N – INTEGERInput
On entry: n, the order of the matrix A.
Constraint: N≥0.
2:   A LDA* – REAL (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array A must be at least max 1,N.
On entry: the LU factorization of A, as returned by F07ADF (DGETRF).
On exit: the factorization is overwritten by the n by n matrix A-1.
3:   LDA – INTEGERInput
On entry: the first dimension of the array A as declared in the (sub)program from which F07AJF (DGETRI) is called.
Constraint: LDA≥max 1,N.
4:   IPIV* – INTEGER arrayInput
Note: the dimension of the array IPIV must be at least max 1,N.
On entry: the pivot indices, as returned by F07ADF (DGETRF).
5:   WORK max 1,LWORK – REAL (KIND=nag_wp) arrayWorkspace
On exit: if INFO=0, WORK 1 contains the minimum value of LWORK required for optimum performance.
6:   LWORK – INTEGERInput
On entry: the dimension of the array WORK as declared in the (sub)program from which F07AJF (DGETRI) is called, unless LWORK=-1, in which case a workspace query is assumed and the routine only calculates the optimal dimension of WORK (using the formula given below).
Suggested value: for optimum performance LWORK should be at least N×nb, where nb is the block size.
Constraint: LWORK≥max 1,N or LWORK=-1.
7:   INFO – INTEGEROutput
On exit: INFO=0 unless the routine detects an error (see Section 6).

6 Error Indicators and Warnings

INFO<0
If INFO=-i, argument i had an illegal value. An explanatory message is output, and execution of the program is terminated.
INFO>0
Element value of the diagonal is zero. U is singular, and the inverse of A cannot be computed.

7 Accuracy

The computed inverse X satisfies a bound of the form:
XA-I≤c n ε X P LU ,
where c n is a modest linear function of n, and ε is the machine precision.
Note that a similar bound for AX-I cannot be guaranteed, although it is almost always satisfied. See Du Croz and Higham (1992).

8 Parallelism and Performance

F07AJF (DGETRI) makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The total number of floating-point operations is approximately 43 n 3.
The complex analogue of this routine is F07AWF (ZGETRI).

10 Example

This example computes the inverse of the matrix A, where
A= 1.80 2.88 2.05 -0.89 5.25 -2.95 -0.95 -3.80 1.58 -2.69 -2.90 -1.04 -1.11 -0.66 -0.59 0.80 .
Here A is nonsymmetric and must first be factorized by F07ADF (DGETRF).

10.1 Program Text

Program Text (f07ajfe.f90)

10.2 Program Data

Program Data (f07ajfe.d)

10.3 Program Results

Program Results (f07ajfe.r)

F07 Chapter Contents
F07 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F07ANF (ZGESV) : NAG Library, Mark 26

F07 Chapter Contents
F07 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F07ANF (ZGESV)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F07ANF (ZGESV) computes the solution to a complex system of linear equations
AX=B ,
where A is an n by n matrix and X and B are n by r matrices.

2 Specification

SUBROUTINE F07ANF ( N, NRHS, A, LDA, IPIV, B, LDB, INFO)
INTEGER | N, NRHS, LDA, IPIV(N), LDB, INFO
COMPLEX (KIND=nag_wp) | A(LDA,*), B(LDB,*)
The routine may be called by its LAPACK name zgesv.

3 Description

F07ANF (ZGESV) uses the LU decomposition with partial pivoting and row interchanges to factor A as
A=PLU ,
where P is a permutation matrix, L is unit lower triangular, and U is upper triangular. The factored form of A is then used to solve the system of equations AX=B.

4 References

Anderson E, Bai Z, Bischof C, Blackford S, Demmel J, Dongarra J J, Du Croz J J, Greenbaum A, Hammarling S, McKenney A and Sorensen D (1999) LAPACK Users' Guide (3rd Edition) SIAM, Philadelphia http://www.netlib.org/lapack/lug
Golub G H and Van Loan C F (1996) Matrix Computations (3rd Edition) Johns Hopkins University Press, Baltimore

5 Arguments

1:   N – INTEGERInput
On entry: n, the number of linear equations, i.e., the order of the matrix A.
Constraint: N≥0.
2:   NRHS – INTEGERInput
On entry: r, the number of right-hand sides, i.e., the number of columns of the matrix B.
Constraint: NRHS≥0.
3:   A LDA* – COMPLEX (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array A must be at least max 1,N.
On entry: the n by n coefficient matrix A.
On exit: the factors L and U from the factorization A=PLU; the unit diagonal elements of L are not stored.
4:   LDA – INTEGERInput
On entry: the first dimension of the array A as declared in the (sub)program from which F07ANF (ZGESV) is called.
Constraint: LDA≥max 1,N.
5:   IPIV N – INTEGER arrayOutput
On exit: if no constraints are violated, the pivot indices that define the permutation matrix P; at the ith step row i of the matrix was interchanged with row IPIV i. IPIV i=i indicates a row interchange was not required.
6:   B LDB* – COMPLEX (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array B must be at least max 1,NRHS.
On entry: the n by r right-hand side matrix B.
On exit: if INFO=0, the n by r solution matrix X.
7:   LDB – INTEGERInput
On entry: the first dimension of the array B as declared in the (sub)program from which F07ANF (ZGESV) is called.
Constraint: LDB≥max 1,N.
8:   INFO – INTEGEROutput
On exit: INFO=0 unless the routine detects an error (see Section 6).

6 Error Indicators and Warnings

INFO<0
If INFO=-i, argument i had an illegal value. An explanatory message is output, and execution of the program is terminated.
INFO>0
Element value of the diagonal is exactly zero. The factorization has been completed, but the factor U is exactly singular, so the solution could not be computed.

7 Accuracy

The computed solution for a single right-hand side, x^ , satisfies the equation of the form
A+E x^=b ,
where
E 1 = O ε A 1
and ε is the machine precision. An approximate error bound for the computed solution is given by
x^ - x 1 x 1 ≤ κ A E 1 A 1
where κ A = A-1 1 A 1 , the condition number of A with respect to the solution of the linear equations. See Section 4.4 of Anderson et al. (1999) for further details.
Following the use of F07ANF (ZGESV), F07AUF (ZGECON) can be used to estimate the condition number of A and F07AVF (ZGERFS) can be used to obtain approximate error bounds. Alternatives to F07ANF (ZGESV), which return condition and error estimates directly are F04CAF and F07APF (ZGESVX).

8 Parallelism and Performance

F07ANF (ZGESV) is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
F07ANF (ZGESV) makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The total number of floating-point operations is approximately 83 n 3 + 8⁢n 2 r , where r is the number of right-hand sides.
The real analogue of this routine is F07AAF (DGESV).

10 Example

This example solves the equations
Ax = b ,
where A is the general matrix
A = -1.34+2.55 i 0.28+3.17 i -6.39-2.20 i 0.72-0.92 i -0.17-1.41 i 3.31-0.15 i -0.15+1.34 i 1.29+1.38 i -3.29-2.39 i -1.91+4.42 i -0.14-1.35 i 1.72+1.35 i 2.41+0.39 i -0.56+1.47 i -0.83-0.69 i -1.96+0.67 i   and   b = 26.26+51.78 i 6.43-0 8.68 i -5.75+25.31 i 1.16+0 2.57 i .
Details of the LU factorization of A are also output.

10.1 Program Text

Program Text (f07anfe.f90)

10.2 Program Data

Program Data (f07anfe.d)

10.3 Program Results

Program Results (f07anfe.r)

F07 Chapter Contents
F07 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F07APF (ZGESVX) : NAG Library, Mark 26

F07 Chapter Contents
F07 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F07APF (ZGESVX)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F07APF (ZGESVX) uses the LU factorization to compute the solution to a complex system of linear equations
AX=B   or   AT X=B   or   AH X=B ,
where A is an n by n matrix and X and B are n by r matrices. Error bounds on the solution and a condition estimate are also provided.

2 Specification

SUBROUTINE F07APF ( FACT, TRANS, N, NRHS, A, LDA, AF, LDAF, IPIV, EQUED, R, C, B, LDB, X, LDX, RCOND, FERR, BERR, WORK, RWORK, INFO)
INTEGER | N, NRHS, LDA, LDAF, IPIV(*), LDB, LDX, INFO
REAL (KIND=nag_wp) | R(*), C(*), RCOND, FERR(NRHS), BERR(NRHS), RWORK(max(1,2*N))
COMPLEX (KIND=nag_wp) | A(LDA,*), AF(LDAF,*), B(LDB,*), X(LDX,*), WORK(2*N)
CHARACTER(1) | FACT, TRANS, EQUED
The routine may be called by its LAPACK name zgesvx.

3 Description

F07APF (ZGESVX) performs the following steps:
1. Equilibration
The linear system to be solved may be badly scaled. However, the system can be equilibrated as a first stage by setting FACT='E'. In this case, real scaling factors are computed and these factors then determine whether the system is to be equilibrated. Equilibrated forms of the systems AX=B , AT X=B and AH X=B are
DR A DC DC-1 X = DR B ,
DR A DC T DR-1 X = DC B ,
and
DR A DC H DR-1 X = DC B ,
respectively, where DR and DC are diagonal matrices, with positive diagonal elements, formed from the computed scaling factors.
When equilibration is used, A will be overwritten by DR A DC and B will be overwritten by DR B (or DC B when the solution of AT X=B or AH X=B is sought).
2. Factorization
The matrix A, or its scaled form, is copied and factored using the LU decomposition
A=PLU ,
where P is a permutation matrix, L is a unit lower triangular matrix, and U is upper triangular.
This stage can be by-passed when a factored matrix (with scaled matrices and scaling factors) are supplied; for example, as provided by a previous call to F07APF (ZGESVX) with the same matrix A.
3. Condition Number Estimation
The LU factorization of A determines whether a solution to the linear system exists. If some diagonal element of U is zero, then U is exactly singular, no solution exists and the routine returns with a failure. Otherwise the factorized form of A is used to estimate the condition number of the matrix A. If the reciprocal of the condition number is less than machine precision then a warning code is returned on final exit.
4. Solution
The (equilibrated) system is solved for X ( DC-1 X or DR-1 X ) using the factored form of A ( DR A DC ).
5. Iterative Refinement
Iterative refinement is applied to improve the computed solution matrix and to calculate error bounds and backward error estimates for the computed solution.
6. Construct Solution Matrix X
If equilibration was used, the matrix X is premultiplied by DC (if TRANS='N') or DR (if TRANS='T' or 'C') so that it solves the original system before equilibration.

4 References

Anderson E, Bai Z, Bischof C, Blackford S, Demmel J, Dongarra J J, Du Croz J J, Greenbaum A, Hammarling S, McKenney A and Sorensen D (1999) LAPACK Users' Guide (3rd Edition) SIAM, Philadelphia http://www.netlib.org/lapack/lug
Golub G H and Van Loan C F (1996) Matrix Computations (3rd Edition) Johns Hopkins University Press, Baltimore
Higham N J (2002) Accuracy and Stability of Numerical Algorithms (2nd Edition) SIAM, Philadelphia

5 Arguments

1:   FACT – CHARACTER(1)Input
On entry: specifies whether or not the factorized form of the matrix A is supplied on entry, and if not, whether the matrix A should be equilibrated before it is factorized.
FACT='F'
AF and IPIV contain the factorized form of A. If EQUED≠'N', the matrix A has been equilibrated with scaling factors given by R and C. A, AF and IPIV are not modified.
FACT='N'
The matrix A will be copied to AF and factorized.
FACT='E'
The matrix A will be equilibrated if necessary, then copied to AF and factorized.
Constraint: FACT='F', 'N' or 'E'.
2:   TRANS – CHARACTER(1)Input
On entry: specifies the form of the system of equations.
TRANS='N'
AX=B (No transpose).
TRANS='T'
AT X=B (Transpose).
TRANS='C'
AH X=B (Conjugate transpose).
Constraint: TRANS='N', 'T' or 'C'.
3:   N – INTEGERInput
On entry: n, the number of linear equations, i.e., the order of the matrix A.
Constraint: N≥0.
4:   NRHS – INTEGERInput
On entry: r, the number of right-hand sides, i.e., the number of columns of the matrix B.
Constraint: NRHS≥0.
5:   A LDA* – COMPLEX (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array A must be at least max 1,N.
On entry: the n by n matrix A.
If FACT='F' and EQUED≠'N', A must have been equilibrated by the scaling factors in R and/or C.
On exit: if FACT='F' or 'N', or if FACT='E' and EQUED='N', A is not modified.
If FACT='E' or EQUED≠'N', A is scaled as follows:
  • if EQUED='R', A=DR A;
  • if EQUED='C', A=A DC;
  • if EQUED='B', A=DR A DC.
6:   LDA – INTEGERInput
On entry: the first dimension of the array A as declared in the (sub)program from which F07APF (ZGESVX) is called.
Constraint: LDA≥max 1,N.
7:   AF LDAF* – COMPLEX (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array AF must be at least max 1,N.
On entry: if FACT='F', AF contains the factors L and U from the factorization A=PLU as computed by F07ARF (ZGETRF). If EQUED≠'N', AF is the factorized form of the equilibrated matrix A.
If FACT='N' or 'E', AF need not be set.
On exit: if FACT='N', AF returns the factors L and U from the factorization A=PLU of the original matrix A.
If FACT='E', AF returns the factors L and U from the factorization A=PLU of the equilibrated matrix A (see the description of A for the form of the equilibrated matrix).
If FACT='F', AF is unchanged from entry.
8:   LDAF – INTEGERInput
On entry: the first dimension of the array AF as declared in the (sub)program from which F07APF (ZGESVX) is called.
Constraint: LDAF≥max 1,N.
9:   IPIV* – INTEGER arrayInput/Output
Note: the dimension of the array IPIV must be at least max 1,N.
On entry: if FACT='F', IPIV contains the pivot indices from the factorization A=PLU as computed by F07ARF (ZGETRF); at the ith step row i of the matrix was interchanged with row IPIV i. IPIV i=i indicates a row interchange was not required.
If FACT='N' or 'E', IPIV need not be set.
On exit: if FACT='N', IPIV contains the pivot indices from the factorization A=PLU of the original matrix A.
If FACT='E', IPIV contains the pivot indices from the factorization A=PLU of the equilibrated matrix A.
If FACT='F', IPIV is unchanged from entry.
10:   EQUED – CHARACTER(1)Input/Output
On entry: if FACT='N' or 'E', EQUED need not be set.
If FACT='F', EQUED must specify the form of the equilibration that was performed as follows:
  • if EQUED='N', no equilibration;
  • if EQUED='R', row equilibration, i.e., A has been premultiplied by DR;
  • if EQUED='C', column equilibration, i.e., A has been postmultiplied by DC;
  • if EQUED='B', both row and column equilibration, i.e., A has been replaced by DR A DC.
On exit: if FACT='F', EQUED is unchanged from entry.
Otherwise, if no constraints are violated, EQUED specifies the form of equilibration that was performed as specified above.
Constraint: if FACT='F', EQUED='N', 'R', 'C' or 'B'.
11:   R* – REAL (KIND=nag_wp) arrayInput/Output
Note: the dimension of the array R must be at least max 1,N.
On entry: if FACT='N' or 'E', R need not be set.
If FACT='F' and EQUED='R' or 'B', R must contain the row scale factors for A, DR; each element of R must be positive.
On exit: if FACT='F', R is unchanged from entry.
Otherwise, if no constraints are violated and EQUED='R' or 'B', R contains the row scale factors for A, DR, such that A is multiplied on the left by DR; each element of R is positive.
12:   C* – REAL (KIND=nag_wp) arrayInput/Output
Note: the dimension of the array C must be at least max 1,N.
On entry: if FACT='N' or 'E', C need not be set.
If FACT='F' or EQUED='C' or 'B', C must contain the column scale factors for A, DC; each element of C must be positive.
On exit: if FACT='F', C is unchanged from entry.
Otherwise, if no constraints are violated and EQUED='C' or 'B', C contains the row scale factors for A, DC; each element of C is positive.
13:   B LDB* – COMPLEX (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array B must be at least max 1,NRHS.
On entry: the n by r right-hand side matrix B.
On exit: if EQUED='N', B is not modified.
If TRANS='N' and EQUED='R' or 'B', B is overwritten by DR B.
If TRANS='T' or 'C' and EQUED='C' or 'B', B is overwritten by DC B.
14:   LDB – INTEGERInput
On entry: the first dimension of the array B as declared in the (sub)program from which F07APF (ZGESVX) is called.
Constraint: LDB≥max 1,N.
15:   X LDX* – COMPLEX (KIND=nag_wp) arrayOutput
Note: the second dimension of the array X must be at least max 1,NRHS.
On exit: if INFO=0 or N+1, the n by r solution matrix X to the original system of equations. Note that the arrays A and B are modified on exit if EQUED≠'N', and the solution to the equilibrated system is DC-1 X if TRANS='N' and EQUED='C' or 'B', or DR-1 X if TRANS='T' or 'C' and EQUED='R' or 'B'.
16:   LDX – INTEGERInput
On entry: the first dimension of the array X as declared in the (sub)program from which F07APF (ZGESVX) is called.
Constraint: LDX≥max 1,N.
17:   RCOND – REAL (KIND=nag_wp)Output
On exit: if no constraints are violated, an estimate of the reciprocal condition number of the matrix A (after equilibration if that is performed), computed as RCOND=1.0/A 1 A-1 1 .
18:   FERR NRHS – REAL (KIND=nag_wp) arrayOutput
On exit: if INFO=0 or N+1, an estimate of the forward error bound for each computed solution vector, such that x^j-xj∞/xj∞≤FERR j where x^j is the jth column of the computed solution returned in the array X and xj is the corresponding column of the exact solution X. The estimate is as reliable as the estimate for RCOND, and is almost always a slight overestimate of the true error.
19:   BERR NRHS – REAL (KIND=nag_wp) arrayOutput
On exit: if INFO=0 or N+1, an estimate of the component-wise relative backward error of each computed solution vector x^j (i.e., the smallest relative change in any element of A or B that makes x^j an exact solution).
20:   WORK 2×N – COMPLEX (KIND=nag_wp) arrayWorkspace
21:   RWORK max 1,2×N – REAL (KIND=nag_wp) arrayOutput
On exit: RWORK 1 contains the reciprocal pivot growth factor A/U. The ‘max absolute element’ norm is used. If RWORK 1 is much less than 1, then the stability of the LU factorization of the (equilibrated) matrix A could be poor. This also means that the solution X, condition estimator RCOND, and forward error bound FERR could be unreliable. If factorization fails with INFO>0 and INFO≤N, then RWORK 1 contains the reciprocal pivot growth factor for the leading INFO columns of A.
22:   INFO – INTEGEROutput
On exit: INFO=0 unless the routine detects an error (see Section 6).

6 Error Indicators and Warnings

INFO<0
If INFO=-i, argument i had an illegal value. An explanatory message is output, and execution of the program is terminated.
INFO>0 and INFO≤N
Element value of the diagonal is exactly zero. The factorization has been completed, but the factor U is exactly singular, so the solution and error bounds could not be computed. RCOND=0.0 is returned.
INFO=N+1
U is nonsingular, but RCOND is less than machine precision, meaning that the matrix is singular to working precision. Nevertheless, the solution and error bounds are computed because there are a number of situations where the computed solution can be more accurate than the value of RCOND would suggest.

7 Accuracy

For each right-hand side vector b, the computed solution x^ is the exact solution of a perturbed system of equations A+E x^=b, where
E≤c n εP LU ,
c n is a modest linear function of n, and ε is the machine precision. See Section 9.3 of Higham (2002) for further details.
If x is the true solution, then the computed solution x^ satisfies a forward error bound of the form
x-x^∞ x^∞ ≤ wc cond A,x^,b
where cond A,x^,b = A-1 A x^ + b ∞/ x^∞ ≤ cond A = A-1 A ∞≤κ∞ A. If x^ is the j th column of X , then wc is returned in BERR j and a bound on x - x^ ∞ / x^ ∞ is returned in FERR j . See Section 4.4 of Anderson et al. (1999) for further details.

8 Parallelism and Performance

F07APF (ZGESVX) is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
F07APF (ZGESVX) makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The factorization of A requires approximately 83 n 3 floating-point operations.
Estimating the forward error involves solving a number of systems of linear equations of the form Ax=b or AT x=b; the number is usually 4 or 5 and never more than 11. Each solution involves approximately 8⁢n 2 operations.
In practice the condition number estimator is very reliable, but it can underestimate the true condition number; see Section 15.3 of Higham (2002) for further details.
The real analogue of this routine is F07ABF (DGESVX).

10 Example

This example solves the equations
AX=B ,
where A is the general matrix
A= -1.34+0 2.55 i 0.28+3.17 i -6.39-0 2.20 i 0.72-0 0.92 i -1.70-14.10 i 33.10-1.50 i -1.50+13.40 i 12.90+13.80 i -3.29-0 2.39 i -1.91+4.42 i -0.14-0 1.35 i 1.72+0 1.35 i 2.41+0 0.39 i -0.56+1.47 i -0.83-0 0.69 i -1.96+0 0.67 i
and
B= 26.26+51.78 i 31.32-0 6.70 i 64.30-86.80 i 158.60-14.20 i -5.75+25.31 i -2.15+30.19 i 1.16+0 2.57 i -2.56+0 7.55 i .
Error estimates for the solutions, information on scaling, an estimate of the reciprocal of the condition number of the scaled matrix A and an estimate of the reciprocal of the pivot growth factor for the factorization of A are also output.

10.1 Program Text

Program Text (f07apfe.f90)

10.2 Program Data

Program Data (f07apfe.d)

10.3 Program Results

Program Results (f07apfe.r)

F07 Chapter Contents
F07 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F07AQF (ZCGESV) : NAG Library, Mark 26

F07 Chapter Contents
F07 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F07AQF (ZCGESV)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F07AQF (ZCGESV) computes the solution to a complex system of linear equations
AX=B ,
where A is an n by n matrix and X and B are n by r matrices.

2 Specification

SUBROUTINE F07AQF ( N, NRHS, A, LDA, IPIV, B, LDB, X, LDX, WORK, SWORK, RWORK, ITER, INFO)
INTEGER | N, NRHS, LDA, IPIV(N), LDB, LDX, ITER, INFO
REAL (KIND=nag_wp) | RWORK(N)
COMPLEX (KIND=nag_wp) | A(LDA,*), B(LDB,*), X(LDX,*), WORK(N*NRHS)
COMPLEX (KIND=nag_rp) | SWORK(N*(N+NRHS))
The routine may be called by its LAPACK name zcgesv.

3 Description

F07AQF (ZCGESV) first attempts to factorize the matrix in single precision and use this factorization within an iterative refinement procedure to produce a solution with double precision accuracy. If the approach fails the method switches to a double precision factorization and solve.
The iterative refinement process is stopped if
ITER>itermax ,
where ITER is the number of iterations carried out thus far and itermax is the maximum number of iterations allowed, which is fixed at 30 iterations. The process is also stopped if for all right-hand sides we have
resid < N x A ε ,
where resid is the ∞-norm of the residual, x is the ∞-norm of the solution, A is the ∞-operator-norm of the matrix A and ε is the machine precision returned by X02AJF.
The iterative refinement strategy used by F07AQF (ZCGESV) can be more efficient than the corresponding direct full precision algorithm. Since this strategy must perform iterative refinement on each right-hand side, any efficiency gains will reduce as the number of right-hand sides increases. Conversely, as the matrix size increases the cost of these iterative refinements become less significant relative to the cost of factorization. Thus, any efficiency gains will be greatest for a very small number of right-hand sides and for large matrix sizes. The cut-off values for the number of right-hand sides and matrix size, for which the iterative refinement strategy performs better, depends on the relative performance of the reduced and full precision factorization and back-substitution. For now, F07AQF (ZCGESV) always attempts the iterative refinement strategy first; you are advised to compare the performance of F07AQF (ZCGESV) with that of its full precision counterpart F07ANF (ZGESV) to determine whether this strategy is worthwhile for your particular problem dimensions.

4 References

Anderson E, Bai Z, Bischof C, Blackford S, Demmel J, Dongarra J J, Du Croz J J, Greenbaum A, Hammarling S, McKenney A and Sorensen D (1999) LAPACK Users' Guide (3rd Edition) SIAM, Philadelphia http://www.netlib.org/lapack/lug
Buttari A, Dongarra J, Langou J, Langou J, Luszczek P and Kurzak J (2007) Mixed precision iterative refinement techniques for the solution of dense linear systems International Journal of High Performance Computing Applications
Golub G H and Van Loan C F (1996) Matrix Computations (3rd Edition) Johns Hopkins University Press, Baltimore

5 Arguments

1:   N – INTEGERInput
On entry: n, the number of linear equations, i.e., the order of the matrix A.
Constraint: N≥0.
2:   NRHS – INTEGERInput
On entry: r, the number of right-hand sides, i.e., the number of columns of the matrix B.
Constraint: NRHS≥0.
3:   A LDA* – COMPLEX (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array A must be at least max 1,N.
On entry: the n by n coefficient matrix A.
On exit: if iterative refinement has been successfully used (i.e., if INFO=0 and ITER≥0), then A is unchanged. If double precision factorization has been used (when INFO=0 and ITER<0), A contains the factors L and U from the factorization A=PLU; the unit diagonal elements of L are not stored.
4:   LDA – INTEGERInput
On entry: the first dimension of the array A as declared in the (sub)program from which F07AQF (ZCGESV) is called.
Constraint: LDA≥max 1,N.
5:   IPIV N – INTEGER arrayOutput
On exit: if no constraints are violated, the pivot indices that define the permutation matrix P; at the ith step row i of the matrix was interchanged with row IPIV i. IPIV i=i indicates a row interchange was not required. IPIV corresponds either to the single precision factorization (if INFO=0 and ITER≥0) or to the double precision factorization (if INFO=0 and ITER<0).
6:   B LDB* – COMPLEX (KIND=nag_wp) arrayInput
Note: the second dimension of the array B must be at least max 1,NRHS.
On entry: the n by r right-hand side matrix B.
7:   LDB – INTEGERInput
On entry: the first dimension of the array B as declared in the (sub)program from which F07AQF (ZCGESV) is called.
Constraint: LDB≥max 1,N.
8:   X LDX* – COMPLEX (KIND=nag_wp) arrayOutput
Note: the second dimension of the array X must be at least max 1,NRHS.
On exit: if INFO=0, the n by r solution matrix X.
9:   LDX – INTEGERInput
On entry: the first dimension of the array X as declared in the (sub)program from which F07AQF (ZCGESV) is called.
Constraint: LDX≥max 1,N.
10:   WORK N*NRHS – COMPLEX (KIND=nag_wp) arrayWorkspace
11:   SWORK N×N+NRHS – COMPLEX (KIND=nag_rp) arrayWorkspace
Note: this array is utilized in the reduced precision computation, consequently its type nag_rp reflects this usage.
12:   RWORK N – REAL (KIND=nag_wp) arrayWorkspace
13:   ITER – INTEGEROutput
On exit: if ITER>0, iterative refinement has been successfully used and ITER is the number of iterations carried out.
If ITER<0, iterative refinement has failed for one of the reasons given below and double precision factorization has been carried out instead.
ITER=-1
Taking into account machine parameters, and the values of N and NRHS, it is not worth working in single precision.
ITER=-2
Overflow of an entry occurred when moving from double to single precision.
ITER=-3
An intermediate single precision factorization failed.
ITER=-31
The maximum permitted number of iterations was exceeded.
14:   INFO – INTEGEROutput
On exit: INFO=0 unless the routine detects an error (see Section 6).

6 Error Indicators and Warnings

INFO<0
If INFO=-i, argument i had an illegal value. An explanatory message is output, and execution of the program is terminated.
INFO>0
Element value of the diagonal is exactly zero. The factorization has been completed, but the factor U is exactly singular, so the solution could not be computed.

7 Accuracy

The computed solution for a single right-hand side, x^ , satisfies the equation of the form
A+E x^=b ,
where
E 1 = O ε A 1
and ε is the machine precision. An approximate error bound for the computed solution is given by
x^ - x 1 x 1 ≤ κ A E 1 A 1
where κ A = A-1 1 A 1 , the condition number of A with respect to the solution of the linear equations. See Section 4.4 of Anderson et al. (1999) for further details.

8 Parallelism and Performance

F07AQF (ZCGESV) is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
F07AQF (ZCGESV) makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The real analogue of this routine is F07ACF (DSGESV).

10 Example

This example solves the equations
Ax = b ,
where A is the general matrix
A = -1.34+2.55 i 0.28+3.17 i -6.39-2.20 i 0.72-0.92 i -0.17-1.41 i 3.31-0.15 i -0.15+1.34 i 1.29+1.38 i -3.29-2.39 i -1.91+4.42 i -0.14-1.35 i 1.72+1.35 i 2.41+0.39 i -0.56+1.47 i -0.83-0.69 i -1.96+0.67 i   and   b = 26.26+51.78 i 6.43-0 8.68 i -5.75+25.31 i 1.16+0 2.57 i .

10.1 Program Text

Program Text (f07aqfe.f90)

10.2 Program Data

Program Data (f07aqfe.d)

10.3 Program Results

Program Results (f07aqfe.r)

F07 Chapter Contents
F07 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F07ARF (ZGETRF) : NAG Library, Mark 26

F07 Chapter Contents
F07 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F07ARF (ZGETRF)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F07ARF (ZGETRF) computes the LU factorization of a complex m by n matrix.

2 Specification

SUBROUTINE F07ARF ( M, N, A, LDA, IPIV, INFO)
INTEGER | M, N, LDA, IPIV(min(M,N)), INFO
COMPLEX (KIND=nag_wp) | A(LDA,*)
The routine may be called by its LAPACK name zgetrf.

3 Description

F07ARF (ZGETRF) forms the LU factorization of a complex m by n matrix A as A=PLU, where P is a permutation matrix, L is lower triangular with unit diagonal elements (lower trapezoidal if m>n) and U is upper triangular (upper trapezoidal if m<n). Usually A is square m=n, and both L and U are triangular. The routine uses partial pivoting, with row interchanges.

4 References

Golub G H and Van Loan C F (1996) Matrix Computations (3rd Edition) Johns Hopkins University Press, Baltimore

5 Arguments

1:   M – INTEGERInput
On entry: m, the number of rows of the matrix A.
Constraint: M≥0.
2:   N – INTEGERInput
On entry: n, the number of columns of the matrix A.
Constraint: N≥0.
3:   A LDA* – COMPLEX (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array A must be at least max 1,N.
On entry: the m by n matrix A.
On exit: the factors L and U from the factorization A=PLU; the unit diagonal elements of L are not stored.
4:   LDA – INTEGERInput
On entry: the first dimension of the array A as declared in the (sub)program from which F07ARF (ZGETRF) is called.
Constraint: LDA≥max 1,M.
5:   IPIV min M,N – INTEGER arrayOutput
On exit: the pivot indices that define the permutation matrix. At the ith step, if IPIV i>i then row i of the matrix A was interchanged with row IPIV i, for i=1,2,…,min m,n. IPIV i≤i indicates that, at the ith step, a row interchange was not required.
6:   INFO – INTEGEROutput
On exit: INFO=0 unless the routine detects an error (see Section 6).

6 Error Indicators and Warnings

INFO<0
If INFO=-i, argument i had an illegal value. An explanatory message is output, and execution of the program is terminated.
INFO>0
Element value of the diagonal is exactly zero. The factorization has been completed, but the factor U is exactly singular, and division by zero will occur if it is used to solve a system of equations.

7 Accuracy

The computed factors L and U are the exact factors of a perturbed matrix A+E, where
E ≤ c min m,n ε P L U ,
c n is a modest linear function of n, and ε is the machine precision.

8 Parallelism and Performance

F07ARF (ZGETRF) is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
F07ARF (ZGETRF) makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The total number of real floating-point operations is approximately 83 n 3 if m=n (the usual case), 43 n 2 3 m-n if m>n and 43 m 2 3 n-m if m<n.
A call to this routine with m=n may be followed by calls to the routines:
  • F07ASF (ZGETRS) to solve AX=B, AT X=B or AH X=B;
  • F07AUF (ZGECON) to estimate the condition number of A;
  • F07AWF (ZGETRI) to compute the inverse of A.
The real analogue of this routine is F07ADF (DGETRF).

10 Example

This example computes the LU factorization of the matrix A, where
A= -1.34+2.55 i 0.28+3.17 i -6.39-2.20 i 0.72-0.92 i -0.17-1.41 i 3.31-0.15 i -0.15+1.34 i 1.29+1.38 i -3.29-2.39 i -1.91+4.42 i -0.14-1.35 i 1.72+1.35 i 2.41+0.39 i -0.56+1.47 i -0.83-0.69 i -1.96+0.67 i .

10.1 Program Text

Program Text (f07arfe.f90)

10.2 Program Data

Program Data (f07arfe.d)

10.3 Program Results

Program Results (f07arfe.r)

F07 Chapter Contents
F07 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F07ASF (ZGETRS) : NAG Library, Mark 26

F07 Chapter Contents
F07 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F07ASF (ZGETRS)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F07ASF (ZGETRS) solves a complex system of linear equations with multiple right-hand sides,
AX=B ,  AT X=B   or   AH X=B ,
where A has been factorized by F07ARF (ZGETRF).

2 Specification

SUBROUTINE F07ASF ( TRANS, N, NRHS, A, LDA, IPIV, B, LDB, INFO)
INTEGER | N, NRHS, LDA, IPIV(*), LDB, INFO
COMPLEX (KIND=nag_wp) | A(LDA,*), B(LDB,*)
CHARACTER(1) | TRANS
The routine may be called by its LAPACK name zgetrs.

3 Description

F07ASF (ZGETRS) is used to solve a complex system of linear equations AX=B, AT X=B or AH X=B, the routine must be preceded by a call to F07ARF (ZGETRF) which computes the LU factorization of A as A=PLU. The solution is computed by forward and backward substitution.
If TRANS='N', the solution is computed by solving PLY=B and then UX=Y.
If TRANS='T', the solution is computed by solving UT Y=B and then LTPT X=Y.
If TRANS='C', the solution is computed by solving UH Y=B and then LHPT X=Y.

4 References

Golub G H and Van Loan C F (1996) Matrix Computations (3rd Edition) Johns Hopkins University Press, Baltimore

5 Arguments

1:   TRANS – CHARACTER(1)Input
On entry: indicates the form of the equations.
TRANS='N'
AX=B is solved for X.
TRANS='T'
AT X=B is solved for X.
TRANS='C'
AH X=B is solved for X.
Constraint: TRANS='N', 'T' or 'C'.
2:   N – INTEGERInput
On entry: n, the order of the matrix A.
Constraint: N≥0.
3:   NRHS – INTEGERInput
On entry: r, the number of right-hand sides.
Constraint: NRHS≥0.
4:   A LDA* – COMPLEX (KIND=nag_wp) arrayInput
Note: the second dimension of the array A must be at least max 1,N.
On entry: the LU factorization of A, as returned by F07ARF (ZGETRF).
5:   LDA – INTEGERInput
On entry: the first dimension of the array A as declared in the (sub)program from which F07ASF (ZGETRS) is called.
Constraint: LDA≥max 1,N.
6:   IPIV* – INTEGER arrayInput
Note: the dimension of the array IPIV must be at least max 1,N.
On entry: the pivot indices, as returned by F07ARF (ZGETRF).
7:   B LDB* – COMPLEX (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array B must be at least max 1,NRHS.
On entry: the n by r right-hand side matrix B.
On exit: the n by r solution matrix X.
8:   LDB – INTEGERInput
On entry: the first dimension of the array B as declared in the (sub)program from which F07ASF (ZGETRS) is called.
Constraint: LDB≥max 1,N.
9:   INFO – INTEGEROutput
On exit: INFO=0 unless the routine detects an error (see Section 6).

6 Error Indicators and Warnings

INFO<0
If INFO=-i, argument i had an illegal value. An explanatory message is output, and execution of the program is terminated.

7 Accuracy

For each right-hand side vector b, the computed solution x is the exact solution of a perturbed system of equations A+E x=b, where
E≤c n εP LU ,
c n is a modest linear function of n, and ε is the machine precision.
If x^ is the true solution, then the computed solution x satisfies a forward error bound of the form
x-x^∞ x∞ ≤c n cond A,x ε
where cond A,x = A-1 A x ∞ / x∞ ≤ cond A = A-1 A ∞ ≤ κ∞ A .
Note that cond A,x can be much smaller than cond A, and cond AH (which is the same as cond AT) can be much larger (or smaller) than cond A.
Forward and backward error bounds can be computed by calling F07AVF (ZGERFS), and an estimate for κ∞A can be obtained by calling F07AUF (ZGECON) with NORM='I'.

8 Parallelism and Performance

F07ASF (ZGETRS) is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
F07ASF (ZGETRS) makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The total number of real floating-point operations is approximately 8⁢n 2 r.
This routine may be followed by a call to F07AVF (ZGERFS) to refine the solution and return an error estimate.
The real analogue of this routine is F07AEF (DGETRS).

10 Example

This example solves the system of equations AX=B, where
A= -1.34+2.55 i 0.28+3.17 i -6.39-2.20 i 0.72-0.92 i -0.17-1.41 i 3.31-0.15 i -0.15+1.34 i 1.29+1.38 i -3.29-2.39 i -1.91+4.42 i -0.14-1.35 i 1.72+1.35 i 2.41+0.39 i -0.56+1.47 i -0.83-0.69 i -1.96+0.67 i
and
B= 26.26+51.78 i 31.32-0 6.70 i 6.43-0 8.68 i 15.86-0 1.42 i -5.75+25.31 i -2.15+30.19 i 1.16+0 2.57 i -2.56+0 7.55 i .
Here A is nonsymmetric and must first be factorized by F07ARF (ZGETRF).

10.1 Program Text

Program Text (f07asfe.f90)

10.2 Program Data

Program Data (f07asfe.d)

10.3 Program Results

Program Results (f07asfe.r)

F07 Chapter Contents
F07 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F07ATF (ZGEEQU) : NAG Library, Mark 26

F07 Chapter Contents
F07 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F07ATF (ZGEEQU)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F07ATF (ZGEEQU) computes real diagonal scaling matrices DR and DC intended to equilibrate a complex m by n matrix A and reduce its condition number.

2 Specification

SUBROUTINE F07ATF ( M, N, A, LDA, R, C, ROWCND, COLCND, AMAX, INFO)
INTEGER | M, N, LDA, INFO
REAL (KIND=nag_wp) | R(M), C(N), ROWCND, COLCND, AMAX
COMPLEX (KIND=nag_wp) | A(LDA,*)
The routine may be called by its LAPACK name zgeequ.

3 Description

F07ATF (ZGEEQU) computes the diagonal scaling matrices. The diagonal scaling matrices are chosen to try to make the elements of largest absolute value in each row and column of the matrix B given by
B=DR A DC
have absolute value 1. The diagonal elements of DR and DC are restricted to lie in the safe range δ,1/δ , where δ is the value returned by routine X02AMF. Use of these scaling factors is not guaranteed to reduce the condition number of A but works well in practice.

4 References

None.

5 Arguments

1:   M – INTEGERInput
On entry: m, the number of rows of the matrix A.
Constraint: M≥0.
2:   N – INTEGERInput
On entry: n, the number of columns of the matrix A.
Constraint: N≥0.
3:   A LDA* – COMPLEX (KIND=nag_wp) arrayInput
Note: the second dimension of the array A must be at least max 1,N.
On entry: the matrix A whose scaling factors are to be computed.
4:   LDA – INTEGERInput
On entry: the first dimension of the array A as declared in the (sub)program from which F07ATF (ZGEEQU) is called.
Constraint: LDA≥max 1,M.
5:   R M – REAL (KIND=nag_wp) arrayOutput
On exit: if INFO=0 or INFO>M, R contains the row scale factors, the diagonal elements of DR. The elements of R will be positive.
6:   C N – REAL (KIND=nag_wp) arrayOutput
On exit: if INFO=0, C contains the column scale factors, the diagonal elements of DC. The elements of C will be positive.
7:   ROWCND – REAL (KIND=nag_wp)Output
On exit: if INFO=0 or INFO>M, ROWCND contains the ratio of the smallest value of R i to the largest value of R i. If ROWCND≥0.1 and AMAX is neither too large nor too small, it is not worth scaling by DR.
8:   COLCND – REAL (KIND=nag_wp)Output
On exit: if INFO=0, COLCND contains the ratio of the smallest value of C i to the largest value of C i.
If COLCND≥0.1, it is not worth scaling by DC.
9:   AMAX – REAL (KIND=nag_wp)Output
On exit: max a ij. If AMAX is very close to overflow or underflow, the matrix A should be scaled.
10:   INFO – INTEGEROutput
On exit: INFO=0 unless the routine detects an error (see Section 6).

6 Error Indicators and Warnings

INFO<0
If INFO=-i, argument i had an illegal value. An explanatory message is output, and execution of the program is terminated.
INFO>0 and INFO≤M
Row value of A is exactly zero.
INFO>M
Column value of A is exactly zero.

7 Accuracy

The computed scale factors will be close to the exact scale factors.

8 Parallelism and Performance

F07ATF (ZGEEQU) is not threaded in any implementation.

9 Further Comments

The real analogue of this routine is F07AFF (DGEEQU).

10 Example

This example equilibrates the general matrix A given by
A = -1.34+2.55 i (0.28+3.17 i×1010 ((-6.39-2.20 i -1.70-1.41 i (3.31-0.15 i×1010 ((-0.15+1.34 i (2.41+0.39 i×10-10 -0.56+1.47 i (-0.83-0.69 i×10-10 .
Details of the scaling factors, and the scaled matrix are output.

10.1 Program Text

Program Text (f07atfe.f90)

10.2 Program Data

Program Data (f07atfe.d)

10.3 Program Results

Program Results (f07atfe.r)

F07 Chapter Contents
F07 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F07AUF (ZGECON) : NAG Library, Mark 26

F07 Chapter Contents
F07 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F07AUF (ZGECON)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F07AUF (ZGECON) estimates the condition number of a complex matrix A, where A has been factorized by F07ARF (ZGETRF).

2 Specification

SUBROUTINE F07AUF ( NORM, N, A, LDA, ANORM, RCOND, WORK, RWORK, INFO)
INTEGER | N, LDA, INFO
REAL (KIND=nag_wp) | ANORM, RCOND, RWORK(2*N)
COMPLEX (KIND=nag_wp) | A(LDA,*), WORK(2*N)
CHARACTER(1) | NORM
The routine may be called by its LAPACK name zgecon.

3 Description

F07AUF (ZGECON) estimates the condition number of a complex matrix A, in either the 1-norm or the ∞-norm:
κ 1 A = A 1 A-1 1   or   κ∞ A = A∞ A-1∞ .
Note that κ∞A=κ 1 AH.
Because the condition number is infinite if A is singular, the routine actually returns an estimate of the reciprocal of the condition number.
The routine should be preceded by a call to F06UAF to compute A 1 or A∞, and a call to F07ARF (ZGETRF) to compute the LU factorization of A. The routine then uses Higham's implementation of Hager's method (see Higham (1988)) to estimate A-1 1 or A-1∞.

4 References

Higham N J (1988) FORTRAN codes for estimating the one-norm of a real or complex matrix, with applications to condition estimation ACM Trans. Math. Software 14 381–396

5 Arguments

1:   NORM – CHARACTER(1)Input
On entry: indicates whether κ 1 A or κ∞A is estimated.
NORM='1' or 'O'
κ 1 A is estimated.
NORM='I'
κ∞A is estimated.
Constraint: NORM='1', 'O' or 'I'.
2:   N – INTEGERInput
On entry: n, the order of the matrix A.
Constraint: N≥0.
3:   A LDA* – COMPLEX (KIND=nag_wp) arrayInput
Note: the second dimension of the array A must be at least max 1,N.
On entry: the LU factorization of A, as returned by F07ARF (ZGETRF).
4:   LDA – INTEGERInput
On entry: the first dimension of the array A as declared in the (sub)program from which F07AUF (ZGECON) is called.
Constraint: LDA≥max 1,N.
5:   ANORM – REAL (KIND=nag_wp)Input
On entry: if NORM='1' or 'O', the 1-norm of the original matrix A.
If NORM='I', the ∞-norm of the original matrix A.
ANORM may be computed by calling F06UAF with the same value for the argument NORM.
ANORM must be computed either before calling F07ARF (ZGETRF) or else from a copy of the original matrix A (see Section 10).
Constraint: ANORM≥0.0.
6:   RCOND – REAL (KIND=nag_wp)Output
On exit: an estimate of the reciprocal of the condition number of A. RCOND is set to zero if exact singularity is detected or the estimate underflows. If RCOND is less than machine precision, A is singular to working precision.
7:   WORK 2×N – COMPLEX (KIND=nag_wp) arrayWorkspace
8:   RWORK 2×N – REAL (KIND=nag_wp) arrayWorkspace
9:   INFO – INTEGEROutput
On exit: INFO=0 unless the routine detects an error (see Section 6).

6 Error Indicators and Warnings

INFO<0
If INFO=-i, argument i had an illegal value. An explanatory message is output, and execution of the program is terminated.

7 Accuracy

The computed estimate RCOND is never less than the true value ρ, and in practice is nearly always less than 10 ρ, although examples can be constructed where RCOND is much larger.

8 Parallelism and Performance

F07AUF (ZGECON) makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

A call to F07AUF (ZGECON) involves solving a number of systems of linear equations of the form Ax=b or AH x=b; the number is usually 5 and never more than 11. Each solution involves approximately 8⁢n 2 real floating-point operations but takes considerably longer than a call to F07ASF (ZGETRS) with one right-hand side, because extra care is taken to avoid overflow when A is approximately singular.
The real analogue of this routine is F07AGF (DGECON).

10 Example

This example estimates the condition number in the 1-norm of the matrix A, where
A= -1.34+2.55 i 0.28+3.17 i -6.39-2.20 i 0.72-0.92 i -0.17-1.41 i 3.31-0.15 i -0.15+1.34 i 1.29+1.38 i -3.29-2.39 i -1.91+4.42 i -0.14-1.35 i 1.72+1.35 i 2.41+0.39 i -0.56+1.47 i -0.83-0.69 i -1.96+0.67 i .
Here A is nonsymmetric and must first be factorized by F07ARF (ZGETRF). The true condition number in the 1-norm is 231.86.

10.1 Program Text

Program Text (f07aufe.f90)

10.2 Program Data

Program Data (f07aufe.d)

10.3 Program Results

Program Results (f07aufe.r)

F07 Chapter Contents
F07 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F07AVF (ZGERFS) : NAG Library, Mark 26

F07 Chapter Contents
F07 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F07AVF (ZGERFS)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F07AVF (ZGERFS) returns error bounds for the solution of a complex system of linear equations with multiple right-hand sides, AX=B, AT X=B or AH X=B. It improves the solution by iterative refinement, in order to reduce the backward error as much as possible.

2 Specification

SUBROUTINE F07AVF ( TRANS, N, NRHS, A, LDA, AF, LDAF, IPIV, B, LDB, X, LDX, FERR, BERR, WORK, RWORK, INFO)
INTEGER | N, NRHS, LDA, LDAF, IPIV(*), LDB, LDX, INFO
REAL (KIND=nag_wp) | FERR(NRHS), BERR(NRHS), RWORK(N)
COMPLEX (KIND=nag_wp) | A(LDA,*), AF(LDAF,*), B(LDB,*), X(LDX,*), WORK(2*N)
CHARACTER(1) | TRANS
The routine may be called by its LAPACK name zgerfs.

3 Description

F07AVF (ZGERFS) returns the backward errors and estimated bounds on the forward errors for the solution of a complex system of linear equations with multiple right-hand sides AX=B, AT X=B or AH X=B. The routine handles each right-hand side vector (stored as a column of the matrix B) independently, so we describe the function of F07AVF (ZGERFS) in terms of a single right-hand side b and solution x.
Given a computed solution x, the routine computes the component-wise backward error β. This is the size of the smallest relative perturbation in each element of A and b such that x is the exact solution of a perturbed system
A+δA x=b+δb δ a ij≤β a ij   and   δ bi≤β bi .
Then the routine estimates a bound for the component-wise forward error in the computed solution, defined by:
maxi xi - x^i / maxi xi
where x^ is the true solution.
For details of the method, see the F07 Chapter Introduction.

4 References

Golub G H and Van Loan C F (1996) Matrix Computations (3rd Edition) Johns Hopkins University Press, Baltimore

5 Arguments

1:   TRANS – CHARACTER(1)Input
On entry: indicates the form of the linear equations for which X is the computed solution as follows:
TRANS='N'
The linear equations are of the form AX=B.
TRANS='T'
The linear equations are of the form AT X=B.
TRANS='C'
The linear equations are of the form AH X=B.
Constraint: TRANS='N', 'T' or 'C'.
2:   N – INTEGERInput
On entry: n, the order of the matrix A.
Constraint: N≥0.
3:   NRHS – INTEGERInput
On entry: r, the number of right-hand sides.
Constraint: NRHS≥0.
4:   A LDA* – COMPLEX (KIND=nag_wp) arrayInput
Note: the second dimension of the array A must be at least max 1,N.
On entry: the n by n original matrix A as supplied to F07ARF (ZGETRF).
5:   LDA – INTEGERInput
On entry: the first dimension of the array A as declared in the (sub)program from which F07AVF (ZGERFS) is called.
Constraint: LDA≥max 1,N.
6:   AF LDAF* – COMPLEX (KIND=nag_wp) arrayInput
Note: the second dimension of the array AF must be at least max 1,N.
On entry: the LU factorization of A, as returned by F07ARF (ZGETRF).
7:   LDAF – INTEGERInput
On entry: the first dimension of the array AF as declared in the (sub)program from which F07AVF (ZGERFS) is called.
Constraint: LDAF≥max 1,N.
8:   IPIV* – INTEGER arrayInput
Note: the dimension of the array IPIV must be at least max 1,N.
On entry: the pivot indices, as returned by F07ARF (ZGETRF).
9:   B LDB* – COMPLEX (KIND=nag_wp) arrayInput
Note: the second dimension of the array B must be at least max 1,NRHS.
On entry: the n by r right-hand side matrix B.
10:   LDB – INTEGERInput
On entry: the first dimension of the array B as declared in the (sub)program from which F07AVF (ZGERFS) is called.
Constraint: LDB≥max 1,N.
11:   X LDX* – COMPLEX (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array X must be at least max 1,NRHS.
On entry: the n by r solution matrix X, as returned by F07ASF (ZGETRS).
On exit: the improved solution matrix X.
12:   LDX – INTEGERInput
On entry: the first dimension of the array X as declared in the (sub)program from which F07AVF (ZGERFS) is called.
Constraint: LDX≥max 1,N.
13:   FERR NRHS – REAL (KIND=nag_wp) arrayOutput
On exit: FERR j contains an estimated error bound for the jth solution vector, that is, the jth column of X, for j=1,2,…,r.
14:   BERR NRHS – REAL (KIND=nag_wp) arrayOutput
On exit: BERR j contains the component-wise backward error bound β for the jth solution vector, that is, the jth column of X, for j=1,2,…,r.
15:   WORK 2×N – COMPLEX (KIND=nag_wp) arrayWorkspace
16:   RWORK N – REAL (KIND=nag_wp) arrayWorkspace
17:   INFO – INTEGEROutput
On exit: INFO=0 unless the routine detects an error (see Section 6).

6 Error Indicators and Warnings

INFO<0
If INFO=-i, argument i had an illegal value. An explanatory message is output, and execution of the program is terminated.

7 Accuracy

The bounds returned in FERR are not rigorous, because they are estimated, not computed exactly; but in practice they almost always overestimate the actual error.

8 Parallelism and Performance

F07AVF (ZGERFS) is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
F07AVF (ZGERFS) makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

For each right-hand side, computation of the backward error involves a minimum of 16⁢n 2 real floating-point operations. Each step of iterative refinement involves an additional 24⁢n 2 real operations. At most five steps of iterative refinement are performed, but usually only one or two steps are required.
Estimating the forward error involves solving a number of systems of linear equations of the form Ax=b or AH x=b; the number is usually 5 and never more than 11. Each solution involves approximately 8⁢n 2 real operations.
The real analogue of this routine is F07AHF (DGERFS).

10 Example

This example solves the system of equations AX=B using iterative refinement and to compute the forward and backward error bounds, where
A= -1.34+2.55 i 0.28+3.17 i -6.39-2.20 i 0.72-0.92 i -0.17-1.41 i 3.31-0.15 i -0.15+1.34 i 1.29+1.38 i -3.29-2.39 i -1.91+4.42 i -0.14-1.35 i 1.72+1.35 i 2.41+0.39 i -0.56+1.47 i -0.83-0.69 i -1.96+0.67 i
and
B= 26.26+51.78 i 31.32-0 6.70 i 6.43-0 8.68 i 15.86-0 1.42 i -5.75+25.31 i -2.15+30.19 i 1.16+0 2.57 i -2.56+0 7.55 i .
Here A is nonsymmetric and must first be factorized by F07ARF (ZGETRF).

10.1 Program Text

Program Text (f07avfe.f90)

10.2 Program Data

Program Data (f07avfe.d)

10.3 Program Results

Program Results (f07avfe.r)

F07 Chapter Contents
F07 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F07AWF (ZGETRI) : NAG Library, Mark 26

F07 Chapter Contents
F07 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F07AWF (ZGETRI)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F07AWF (ZGETRI) computes the inverse of a complex matrix A, where A has been factorized by F07ARF (ZGETRF).

2 Specification

SUBROUTINE F07AWF ( N, A, LDA, IPIV, WORK, LWORK, INFO)
INTEGER | N, LDA, IPIV(*), LWORK, INFO
COMPLEX (KIND=nag_wp) | A(LDA,*), WORK(max(1,LWORK))
The routine may be called by its LAPACK name zgetri.

3 Description

F07AWF (ZGETRI) is used to compute the inverse of a complex matrix A, the routine must be preceded by a call to F07ARF (ZGETRF), which computes the LU factorization of A as A=PLU. The inverse of A is computed by forming U-1 and then solving the equation XPL=U-1 for X.

4 References

Du Croz J J and Higham N J (1992) Stability of methods for matrix inversion IMA J. Numer. Anal. 12 1–19

5 Arguments

1:   N – INTEGERInput
On entry: n, the order of the matrix A.
Constraint: N≥0.
2:   A LDA* – COMPLEX (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array A must be at least max 1,N.
On entry: the LU factorization of A, as returned by F07ARF (ZGETRF).
On exit: the factorization is overwritten by the n by n matrix A-1.
3:   LDA – INTEGERInput
On entry: the first dimension of the array A as declared in the (sub)program from which F07AWF (ZGETRI) is called.
Constraint: LDA≥max 1,N.
4:   IPIV* – INTEGER arrayInput
Note: the dimension of the array IPIV must be at least max 1,N.
On entry: the pivot indices, as returned by F07ARF (ZGETRF).
5:   WORK max 1,LWORK – COMPLEX (KIND=nag_wp) arrayWorkspace
On exit: if INFO=0, WORK 1 contains the minimum value of LWORK required for optimum performance.
6:   LWORK – INTEGERInput
On entry: the dimension of the array WORK as declared in the (sub)program from which F07AWF (ZGETRI) is called, unless LWORK=-1, in which case a workspace query is assumed and the routine only calculates the optimal dimension of WORK (using the formula given below).
Suggested value: for optimum performance LWORK should be at least N×nb, where nb is the block size.
Constraint: LWORK≥max 1,N or LWORK=-1.
7:   INFO – INTEGEROutput
On exit: INFO=0 unless the routine detects an error (see Section 6).

6 Error Indicators and Warnings

INFO<0
If INFO=-i, argument i had an illegal value. An explanatory message is output, and execution of the program is terminated.
INFO>0
Element value of the diagonal is zero. U is singular, and the inverse of A cannot be computed.

7 Accuracy

The computed inverse X satisfies a bound of the form:
XA-I≤c n ε X P LU ,
where c n is a modest linear function of n, and ε is the machine precision.
Note that a similar bound for AX-I cannot be guaranteed, although it is almost always satisfied. See Du Croz and Higham (1992).

8 Parallelism and Performance

F07AWF (ZGETRI) makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The total number of real floating-point operations is approximately 163 n 3.
The real analogue of this routine is F07AJF (DGETRI).

10 Example

This example computes the inverse of the matrix A, where
A= -1.34+2.55 i 0.28+3.17 i -6.39-2.20 i 0.72-0.92 i -0.17-1.41 i 3.31-0.15 i -0.15+1.34 i 1.29+1.38 i -3.29-2.39 i -1.91+4.42 i -0.14-1.35 i 1.72+1.35 i 2.41+0.39 i -0.56+1.47 i -0.83-0.69 i -1.96+0.67 i .
Here A is nonsymmetric and must first be factorized by F07ARF (ZGETRF).

10.1 Program Text

Program Text (f07awfe.f90)

10.2 Program Data

Program Data (f07awfe.d)

10.3 Program Results

Program Results (f07awfe.r)

F07 Chapter Contents
F07 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F07BAF (DGBSV) : NAG Library, Mark 26

F07 Chapter Contents
F07 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F07BAF (DGBSV)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F07BAF (DGBSV) computes the solution to a real system of linear equations
AX=B ,
where A is an n by n band matrix, with kl subdiagonals and ku superdiagonals, and X and B are n by r matrices.

2 Specification

SUBROUTINE F07BAF ( N, KL, KU, NRHS, AB, LDAB, IPIV, B, LDB, INFO)
INTEGER | N, KL, KU, NRHS, LDAB, IPIV(N), LDB, INFO
REAL (KIND=nag_wp) | AB(LDAB,*), B(LDB,*)
The routine may be called by its LAPACK name dgbsv.

3 Description

F07BAF (DGBSV) uses the LU decomposition with partial pivoting and row interchanges to factor A as A=PLU, where P is a permutation matrix, L is a product of permutation and unit lower triangular matrices with kl subdiagonals, and U is upper triangular with kl+ku superdiagonals. The factored form of A is then used to solve the system of equations AX=B.

4 References

Anderson E, Bai Z, Bischof C, Blackford S, Demmel J, Dongarra J J, Du Croz J J, Greenbaum A, Hammarling S, McKenney A and Sorensen D (1999) LAPACK Users' Guide (3rd Edition) SIAM, Philadelphia http://www.netlib.org/lapack/lug
Golub G H and Van Loan C F (1996) Matrix Computations (3rd Edition) Johns Hopkins University Press, Baltimore

5 Arguments

1:   N – INTEGERInput
On entry: n, the number of linear equations, i.e., the order of the matrix A.
Constraint: N≥0.
2:   KL – INTEGERInput
On entry: kl, the number of subdiagonals within the band of the matrix A.
Constraint: KL≥0.
3:   KU – INTEGERInput
On entry: ku, the number of superdiagonals within the band of the matrix A.
Constraint: KU≥0.
4:   NRHS – INTEGERInput
On entry: r, the number of right-hand sides, i.e., the number of columns of the matrix B.
Constraint: NRHS≥0.
5:   AB LDAB* – REAL (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array AB must be at least max 1,N.
On entry: the n by n coefficient matrix A.
The matrix is stored in rows kl+1 to 2 kl+ku+1; the first kl rows need not be set, more precisely, the element A ij must be stored in
AB kl+ku+1+i-j j=A ij  for ​max 1,j-ku≤i≤min n,j+kl.
See Section 9 for further details.
On exit: if INFO≥0, AB is overwritten by details of the factorization.
The upper triangular band matrix U, with kl+ku superdiagonals, is stored in rows 1 to kl+ku+1 of the array, and the multipliers used to form the matrix L are stored in rows kl+ku+2 to 2 kl+ku+1.
6:   LDAB – INTEGERInput
On entry: the first dimension of the array AB as declared in the (sub)program from which F07BAF (DGBSV) is called.
Constraint: LDAB≥2×KL+KU+1.
7:   IPIV N – INTEGER arrayOutput
On exit: if no constraints are violated, the pivot indices that define the permutation matrix P; at the ith step row i of the matrix was interchanged with row IPIV i. IPIV i=i indicates a row interchange was not required.
8:   B LDB* – REAL (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array B must be at least max 1,NRHS.
On entry: the n by r right-hand side matrix B.
On exit: if INFO=0, the n by r solution matrix X.
9:   LDB – INTEGERInput
On entry: the first dimension of the array B as declared in the (sub)program from which F07BAF (DGBSV) is called.
Constraint: LDB≥max 1,N.
10:   INFO – INTEGEROutput
On exit: INFO=0 unless the routine detects an error (see Section 6).

6 Error Indicators and Warnings

INFO<0
If INFO=-i, argument i had an illegal value. An explanatory message is output, and execution of the program is terminated.
INFO>0
Element value of the diagonal is exactly zero. The factorization has been completed, but the factor U is exactly singular, so the solution could not be computed.

7 Accuracy

The computed solution for a single right-hand side, x^ , satisfies an equation of the form
A+E x^ = b ,
where
E 1 = O ε A 1
and ε is the machine precision. An approximate error bound for the computed solution is given by
x^-x 1 x 1 ≤ κ A E 1 A 1 ,
where κ A = A-1 1 A 1 , the condition number of A with respect to the solution of the linear equations. See Section 4.4 of Anderson et al. (1999) for further details.
Following the use of F07BAF (DGBSV), F07BGF (DGBCON) can be used to estimate the condition number of A and F07BHF (DGBRFS) can be used to obtain approximate error bounds. Alternatives to F07BAF (DGBSV), which return condition and error estimates directly are F04BBF and F07BBF (DGBSVX).

8 Parallelism and Performance

F07BAF (DGBSV) is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
F07BAF (DGBSV) makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The band storage scheme for the array AB is illustrated by the following example, when n=6 , kl=1 , and ku=2 . Storage of the band matrix A in the array AB:
* * * + + + * * a 13 a 24 a 35 a 46 * a 12 a 23 a 34 a 45 a 56 a 11 a 22 a 33 a 44 a 55 a 66 a 21 a 32 a 43 a 54 a 65 *
Array elements marked * need not be set and are not referenced by the routine. Array elements marked + need not be set, but are defined on exit from the routine and contain the elements u 14 , u 25 and u 36 .
The total number of floating-point operations required to solve the equations AX=B depends upon the pivoting required, but if n≫kl + ku then it is approximately bounded by O n kl kl + ku for the factorization and O n 2 kl + ku r for the solution following the factorization.
The complex analogue of this routine is F07BNF (ZGBSV).

10 Example

This example solves the equations
Ax=b ,
where A is the band matrix
A = -0.23 2.54 -3.66 0.00 -6.98 2.46 -2.73 -2.13 0.00 2.56 2.46 4.07 0.00 0.00 -4.78 -3.82   and   b = 4.42 27.13 -6.14 10.50 .
Details of the LU factorization of A are also output.

10.1 Program Text

Program Text (f07bafe.f90)

10.2 Program Data

Program Data (f07bafe.d)

10.3 Program Results

Program Results (f07bafe.r)

F07 Chapter Contents
F07 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F07BBF (DGBSVX) : NAG Library, Mark 26

F07 Chapter Contents
F07 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F07BBF (DGBSVX)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F07BBF (DGBSVX) uses the LU factorization to compute the solution to a real system of linear equations
AX=B   or   AT X=B ,
where A is an n by n band matrix with kl subdiagonals and ku superdiagonals, and X and B are n by r matrices. Error bounds on the solution and a condition estimate are also provided.

2 Specification

SUBROUTINE F07BBF ( FACT, TRANS, N, KL, KU, NRHS, AB, LDAB, AFB, LDAFB, IPIV, EQUED, R, C, B, LDB, X, LDX, RCOND, FERR, BERR, WORK, IWORK, INFO)
INTEGER | N, KL, KU, NRHS, LDAB, LDAFB, IPIV(*), LDB, LDX, IWORK(N), INFO
REAL (KIND=nag_wp) | AB(LDAB,*), AFB(LDAFB,*), R(*), C(*), B(LDB,*), X(LDX,*), RCOND, FERR(NRHS), BERR(NRHS), WORK(max(1,3*N))
CHARACTER(1) | FACT, TRANS, EQUED
The routine may be called by its LAPACK name dgbsvx.

3 Description

F07BBF (DGBSVX) performs the following steps:
1. Equilibration
The linear system to be solved may be badly scaled. However, the system can be equilibrated as a first stage by setting FACT='E'. In this case, real scaling factors are computed and these factors then determine whether the system is to be equilibrated. Equilibrated forms of the systems AX=B and AT X=B are
DR A DC DC-1 X = DR B
and
DR A DC T DR-1 X = DC B ,
respectively, where DR and DC are diagonal matrices, with positive diagonal elements, formed from the computed scaling factors.
When equilibration is used, A will be overwritten by DR A DC and B will be overwritten by DR B (or DC B when the solution of AT X=B is sought).
2. Factorization
The matrix A, or its scaled form, is copied and factored using the LU decomposition
A=PLU ,
where P is a permutation matrix, L is a unit lower triangular matrix, and U is upper triangular.
This stage can be by-passed when a factored matrix (with scaled matrices and scaling factors) are supplied; for example, as provided by a previous call to F07BBF (DGBSVX) with the same matrix A.
3. Condition Number Estimation
The LU factorization of A determines whether a solution to the linear system exists. If some diagonal element of U is zero, then U is exactly singular, no solution exists and the routine returns with a failure. Otherwise the factorized form of A is used to estimate the condition number of the matrix A. If the reciprocal of the condition number is less than machine precision then a warning code is returned on final exit.
4. Solution
The (equilibrated) system is solved for X ( DC-1 X or DR-1 X ) using the factored form of A ( DR A DC ).
5. Iterative Refinement
Iterative refinement is applied to improve the computed solution matrix and to calculate error bounds and backward error estimates for the computed solution.
6. Construct Solution Matrix X
If equilibration was used, the matrix X is premultiplied by DC (if TRANS='N') or DR (if TRANS='T' or 'C') so that it solves the original system before equilibration.

4 References

Anderson E, Bai Z, Bischof C, Blackford S, Demmel J, Dongarra J J, Du Croz J J, Greenbaum A, Hammarling S, McKenney A and Sorensen D (1999) LAPACK Users' Guide (3rd Edition) SIAM, Philadelphia http://www.netlib.org/lapack/lug
Golub G H and Van Loan C F (1996) Matrix Computations (3rd Edition) Johns Hopkins University Press, Baltimore
Higham N J (2002) Accuracy and Stability of Numerical Algorithms (2nd Edition) SIAM, Philadelphia

5 Arguments

1:   FACT – CHARACTER(1)Input
On entry: specifies whether or not the factorized form of the matrix A is supplied on entry, and if not, whether the matrix A should be equilibrated before it is factorized.
FACT='F'
AFB and IPIV contain the factorized form of A. If EQUED≠'N', the matrix A has been equilibrated with scaling factors given by R and C. AB, AFB and IPIV are not modified.
FACT='N'
The matrix A will be copied to AFB and factorized.
FACT='E'
The matrix A will be equilibrated if necessary, then copied to AFB and factorized.
Constraint: FACT='F', 'N' or 'E'.
2:   TRANS – CHARACTER(1)Input
On entry: specifies the form of the system of equations.
TRANS='N'
AX=B (No transpose).
TRANS='T' or 'C'
AT X=B (Transpose).
Constraint: TRANS='N', 'T' or 'C'.
3:   N – INTEGERInput
On entry: n, the number of linear equations, i.e., the order of the matrix A.
Constraint: N≥0.
4:   KL – INTEGERInput
On entry: kl, the number of subdiagonals within the band of the matrix A.
Constraint: KL≥0.
5:   KU – INTEGERInput
On entry: ku, the number of superdiagonals within the band of the matrix A.
Constraint: KU≥0.
6:   NRHS – INTEGERInput
On entry: r, the number of right-hand sides, i.e., the number of columns of the matrix B.
Constraint: NRHS≥0.
7:   AB LDAB* – REAL (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array AB must be at least max 1,N.
On entry: the n by n coefficient matrix A.
The matrix is stored in rows 1 to kl+ku+1, more precisely, the element A ij must be stored in
AB ku+1+i-j j  for ​max 1,j-ku≤i≤min n,j+kl.
See Section 9 for further details.
If FACT='F' and EQUED≠'N', A must have been equilibrated by the scaling factors in R and/or C.
On exit: if FACT='F' or 'N', or if FACT='E' and EQUED='N', AB is not modified.
If EQUED≠'N' then, if no constraints are violated, A is scaled as follows:
  • if EQUED='R', A=Dr A;
  • if EQUED='C', A=A Dc;
  • if EQUED='B', A=Dr A Dc.
8:   LDAB – INTEGERInput
On entry: the first dimension of the array AB as declared in the (sub)program from which F07BBF (DGBSVX) is called.
Constraint: LDAB≥KL+KU+1.
9:   AFB LDAFB* – REAL (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array AFB must be at least max 1,N.
On entry: if FACT='N' or 'E', AFB need not be set.
If FACT='F', details of the LU factorization of the n by n band matrix A, as computed by F07BDF (DGBTRF).
The upper triangular band matrix U, with kl+ku superdiagonals, is stored in rows 1 to kl+ku+1 of the array, and the multipliers used to form the matrix L are stored in rows kl+ku+2 to 2 kl+ku+1.
If EQUED≠'N', AFB is the factorized form of the equilibrated matrix A.
On exit: if FACT='F', AFB is unchanged from entry.
Otherwise, if no constraints are violated, then if FACT='N', AFB returns details of the LU factorization of the band matrix A, and if FACT='E', AFB returns details of the LU factorization of the equilibrated band matrix A (see the description of AB for the form of the equilibrated matrix).
10:   LDAFB – INTEGERInput
On entry: the first dimension of the array AFB as declared in the (sub)program from which F07BBF (DGBSVX) is called.
Constraint: LDAFB≥2×KL+KU+1.
11:   IPIV* – INTEGER arrayInput/Output
Note: the dimension of the array IPIV must be at least max 1,N.
On entry: if FACT='N' or 'E', IPIV need not be set.
If FACT='F', IPIV contains the pivot indices from the factorization A=LU, as computed by F07BDF (DGBTRF); row i of the matrix was interchanged with row IPIV i.
On exit: if FACT='F', IPIV is unchanged from entry.
Otherwise, if no constraints are violated, IPIV contains the pivot indices that define the permutation matrix P; at the ith step row i of the matrix was interchanged with row IPIV i. IPIV i=i indicates a row interchange was not required.
If FACT='N', the pivot indices are those corresponding to the factorization A=LU of the original matrix A.
If FACT='E', the pivot indices are those corresponding to the factorization of A=LU of the equilibrated matrix A.
12:   EQUED – CHARACTER(1)Input/Output
On entry: if FACT='N' or 'E', EQUED need not be set.
If FACT='F', EQUED must specify the form of the equilibration that was performed as follows:
  • if EQUED='N', no equilibration;
  • if EQUED='R', row equilibration, i.e., A has been premultiplied by DR;
  • if EQUED='C', column equilibration, i.e., A has been postmultiplied by DC;
  • if EQUED='B', both row and column equilibration, i.e., A has been replaced by DR A DC.
On exit: if FACT='F', EQUED is unchanged from entry.
Otherwise, if no constraints are violated, EQUED specifies the form of equilibration that was performed as specified above.
Constraint: if FACT='F', EQUED='N', 'R', 'C' or 'B'.
13:   R* – REAL (KIND=nag_wp) arrayInput/Output
Note: the dimension of the array R must be at least max 1,N.
On entry: if FACT='N' or 'E', R need not be set.
If FACT='F' and EQUED='R' or 'B', R must contain the row scale factors for A, DR; each element of R must be positive.
On exit: if FACT='F', R is unchanged from entry.
Otherwise, if no constraints are violated and EQUED='R' or 'B', R contains the row scale factors for A, DR, such that A is multiplied on the left by DR; each element of R is positive.
14:   C* – REAL (KIND=nag_wp) arrayInput/Output
Note: the dimension of the array C must be at least max 1,N.
On entry: if FACT='N' or 'E', C need not be set.
If FACT='F' or EQUED='C' or 'B', C must contain the column scale factors for A, DC; each element of C must be positive.
On exit: if FACT='F', C is unchanged from entry.
Otherwise, if no constraints are violated and EQUED='C' or 'B', C contains the row scale factors for A, DC; each element of C is positive.
15:   B LDB* – REAL (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array B must be at least max 1,NRHS.
On entry: the n by r right-hand side matrix B.
On exit: if EQUED='N', B is not modified.
If TRANS='N' and EQUED='R' or 'B', B is overwritten by DR B.
If TRANS='T' or 'C' and EQUED='C' or 'B', B is overwritten by DC B.
16:   LDB – INTEGERInput
On entry: the first dimension of the array B as declared in the (sub)program from which F07BBF (DGBSVX) is called.
Constraint: LDB≥max 1,N.
17:   X LDX* – REAL (KIND=nag_wp) arrayOutput
Note: the second dimension of the array X must be at least max 1,NRHS.
On exit: if INFO=0 or N+1, the n by r solution matrix X to the original system of equations. Note that the arrays A and B are modified on exit if EQUED≠'N', and the solution to the equilibrated system is DC-1 X if TRANS='N' and EQUED='C' or 'B', or DR-1 X if TRANS='T' or 'C' and EQUED='R' or 'B'.
18:   LDX – INTEGERInput
On entry: the first dimension of the array X as declared in the (sub)program from which F07BBF (DGBSVX) is called.
Constraint: LDX≥max 1,N.
19:   RCOND – REAL (KIND=nag_wp)Output
On exit: if no constraints are violated, an estimate of the reciprocal condition number of the matrix A (after equilibration if that is performed), computed as RCOND=1.0/A 1 A-1 1 .
20:   FERR NRHS – REAL (KIND=nag_wp) arrayOutput
On exit: if INFO=0 or N+1, an estimate of the forward error bound for each computed solution vector, such that x^j-xj∞/xj∞≤FERR j where x^j is the jth column of the computed solution returned in the array X and xj is the corresponding column of the exact solution X. The estimate is as reliable as the estimate for RCOND, and is almost always a slight overestimate of the true error.
21:   BERR NRHS – REAL (KIND=nag_wp) arrayOutput
On exit: if INFO=0 or N+1, an estimate of the component-wise relative backward error of each computed solution vector x^j (i.e., the smallest relative change in any element of A or B that makes x^j an exact solution).
22:   WORK max 1,3×N – REAL (KIND=nag_wp) arrayOutput
On exit: if INFO=0, WORK 1 contains the reciprocal pivot growth factor max a ij/max u ij. If WORK 1 is much less than 1, then the stability of the LU factorization of the (equilibrated) matrix A could be poor. This also means that the solution X, condition estimator RCOND, and forward error bound FERR could be unreliable. If the factorization fails with INFO>0 and INFO≤N, WORK 1 contains the reciprocal pivot growth factor for the leading INFO columns of A.
23:   IWORK N – INTEGER arrayWorkspace
24:   INFO – INTEGEROutput
On exit: INFO=0 unless the routine detects an error (see Section 6).

6 Error Indicators and Warnings

INFO<0
If INFO=-i, argument i had an illegal value. An explanatory message is output, and execution of the program is terminated.
INFO>0 and INFO≤N
Element value of the diagonal is exactly zero. The factorization has been completed, but the factor U is exactly singular, so the solution and error bounds could not be computed. RCOND=0.0 is returned.
INFO=N+1
U is nonsingular, but RCOND is less than machine precision, meaning that the matrix is singular to working precision. Nevertheless, the solution and error bounds are computed because there are a number of situations where the computed solution can be more accurate than the value of RCOND would suggest.

7 Accuracy

For each right-hand side vector b, the computed solution x^ is the exact solution of a perturbed system of equations A+E x^=b, where
E≤c n εP LU ,
c n is a modest linear function of n, and ε is the machine precision. See Section 9.3 of Higham (2002) for further details.
If x is the true solution, then the computed solution x^ satisfies a forward error bound of the form
x-x^∞ x^∞ ≤ wc cond A,x^,b
where cond A,x^,b = A-1 A x^ + b ∞/ x^∞ ≤ cond A = A-1 A ∞≤κ∞ A. If x^ is the j th column of X , then wc is returned in BERR j and a bound on x - x^ ∞ / x^ ∞ is returned in FERR j . See Section 4.4 of Anderson et al. (1999) for further details.

8 Parallelism and Performance

F07BBF (DGBSVX) is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
F07BBF (DGBSVX) makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The band storage scheme for the array AB is illustrated by the following example, when n=6 , kl=1 , and ku=2 . Storage of the band matrix A in the array AB:
* * a 13 a 24 a 35 a 46 * a 12 a 23 a 34 a 45 a 56 a 11 a 22 a 33 a 44 a 55 a 66 a 21 a 32 a 43 a 54 a 65 *
The total number of floating-point operations required to solve the equations AX=B depends upon the pivoting required, but if n≫kl + ku then it is approximately bounded by O n kl kl + ku for the factorization and O n 2 kl + ku r for the solution following the factorization. The condition number estimation typically requires between four and five solves and never more than eleven solves, following the factorization. The solution is then refined, and the errors estimated, using iterative refinement; see F07BHF (DGBRFS) for information on the floating-point operations required.
In practice the condition number estimator is very reliable, but it can underestimate the true condition number; see Section 15.3 of Higham (2002) for further details.
The complex analogue of this routine is F07BPF (ZGBSVX).

10 Example

This example solves the equations
AX=B ,
where A is the band matrix
A = -0.23 2.54 -3.66 0.00 -6.98 2.46 -2.73 -2.13 0.00 2.56 2.46 4.07 0.00 0.00 -4.78 -3.82   and   B = 4.42 -36.01 27.13 -31.67 -6.14 -1.16 10.50 -25.82 .
Estimates for the backward errors, forward errors, condition number and pivot growth are also output, together with information on the equilibration of A .

10.1 Program Text

Program Text (f07bbfe.f90)

10.2 Program Data

Program Data (f07bbfe.d)

10.3 Program Results

Program Results (f07bbfe.r)

F07 Chapter Contents
F07 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F07BDF (DGBTRF) : NAG Library, Mark 26

F07 Chapter Contents
F07 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F07BDF (DGBTRF)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F07BDF (DGBTRF) computes the LU factorization of a real m by n band matrix.

2 Specification

SUBROUTINE F07BDF ( M, N, KL, KU, AB, LDAB, IPIV, INFO)
INTEGER | M, N, KL, KU, LDAB, IPIV(min(M,N)), INFO
REAL (KIND=nag_wp) | AB(LDAB,*)
The routine may be called by its LAPACK name dgbtrf.

3 Description

F07BDF (DGBTRF) forms the LU factorization of a real m by n band matrix A using partial pivoting, with row interchanges. Usually m=n, and then, if A has kl nonzero subdiagonals and ku nonzero superdiagonals, the factorization has the form A=PLU, where P is a permutation matrix, L is a lower triangular matrix with unit diagonal elements and at most kl nonzero elements in each column, and U is an upper triangular band matrix with kl+ku superdiagonals.
Note that L is not a band matrix, but the nonzero elements of L can be stored in the same space as the subdiagonal elements of A. U is a band matrix but with kl additional superdiagonals compared with A. These additional superdiagonals are created by the row interchanges.

4 References

Golub G H and Van Loan C F (1996) Matrix Computations (3rd Edition) Johns Hopkins University Press, Baltimore

5 Arguments

1:   M – INTEGERInput
On entry: m, the number of rows of the matrix A.
Constraint: M≥0.
2:   N – INTEGERInput
On entry: n, the number of columns of the matrix A.
Constraint: N≥0.
3:   KL – INTEGERInput
On entry: kl, the number of subdiagonals within the band of the matrix A.
Constraint: KL≥0.
4:   KU – INTEGERInput
On entry: ku, the number of superdiagonals within the band of the matrix A.
Constraint: KU≥0.
5:   AB LDAB* – REAL (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array AB must be at least max 1,N.
On entry: the m by n matrix A.
The matrix is stored in rows kl+1 to 2 kl+ku+1; the first kl rows need not be set, more precisely, the element A ij must be stored in
AB kl+ku+1+i-j j=A ij  for ​max 1,j-ku≤i≤min m,j+kl.
See Section 9 in F07BAF (DGBSV) for further details.
On exit: if INFO≥0, AB is overwritten by details of the factorization.
The upper triangular band matrix U, with kl+ku superdiagonals, is stored in rows 1 to kl+ku+1 of the array, and the multipliers used to form the matrix L are stored in rows kl+ku+2 to 2 kl+ku+1.
6:   LDAB – INTEGERInput
On entry: the first dimension of the array AB as declared in the (sub)program from which F07BDF (DGBTRF) is called.
Constraint: LDAB≥2×KL+KU+1.
7:   IPIV min M,N – INTEGER arrayOutput
On exit: the pivot indices that define the permutation matrix. At the ith step, if IPIV i>i then row i of the matrix A was interchanged with row IPIV i, for i=1,2,…,min m,n. IPIV i≤i indicates that, at the ith step, a row interchange was not required.
8:   INFO – INTEGEROutput
On exit: INFO=0 unless the routine detects an error (see Section 6).

6 Error Indicators and Warnings

INFO<0
If INFO=-i, argument i had an illegal value.
If INFO=-999, dynamic memory allocation failed. See Section 3.7 in How to Use the NAG Library and its Documentation for further information. An explanatory message is output, and execution of the program is terminated.
INFO>0
Element value of the diagonal is exactly zero. The factorization has been completed, but the factor U is exactly singular, and division by zero will occur if it is used to solve a system of equations.

7 Accuracy

The computed factors L and U are the exact factors of a perturbed matrix A+E, where
E≤c k εP LU ,
c k is a modest linear function of k=kl+ku+1, and ε is the machine precision. This assumes k≪min m,n.

8 Parallelism and Performance

F07BDF (DGBTRF) is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
F07BDF (DGBTRF) makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The total number of floating-point operations varies between approximately 2 n kl ku+1 and 2 n kl kl+ku+1, depending on the interchanges, assuming m=n≫kl and n≫ku.
A call to F07BDF (DGBTRF) may be followed by calls to the routines:
  • F07BEF (DGBTRS) to solve AX=B or AT X=B;
  • F07BGF (DGBCON) to estimate the condition number of A.
The complex analogue of this routine is F07BRF (ZGBTRF).

10 Example

This example computes the LU factorization of the matrix A, where
A= -0.23 2.54 -3.66 0.00 -6.98 2.46 -2.73 -2.13 0.00 2.56 2.46 4.07 0.00 0.00 -4.78 -3.82 .
Here A is treated as a band matrix with one subdiagonal and two superdiagonals.

10.1 Program Text

Program Text (f07bdfe.f90)

10.2 Program Data

Program Data (f07bdfe.d)

10.3 Program Results

Program Results (f07bdfe.r)

F07 Chapter Contents
F07 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F07BEF (DGBTRS) : NAG Library, Mark 26

F07 Chapter Contents
F07 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F07BEF (DGBTRS)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F07BEF (DGBTRS) solves a real band system of linear equations with multiple right-hand sides,
AX=B   or   AT X=B ,
where A has been factorized by F07BDF (DGBTRF).

2 Specification

SUBROUTINE F07BEF ( TRANS, N, KL, KU, NRHS, AB, LDAB, IPIV, B, LDB, INFO)
INTEGER | N, KL, KU, NRHS, LDAB, IPIV(*), LDB, INFO
REAL (KIND=nag_wp) | AB(LDAB,*), B(LDB,*)
CHARACTER(1) | TRANS
The routine may be called by its LAPACK name dgbtrs.

3 Description

F07BEF (DGBTRS) is used to solve a real band system of linear equations AX=B or AT X=B, the routine must be preceded by a call to F07BDF (DGBTRF) which computes the LU factorization of A as A=PLU. The solution is computed by forward and backward substitution.
If TRANS='N', the solution is computed by solving PLY=B and then UX=Y.
If TRANS='T' or 'C', the solution is computed by solving UT Y=B and then LTPT X=Y.

4 References

Golub G H and Van Loan C F (1996) Matrix Computations (3rd Edition) Johns Hopkins University Press, Baltimore

5 Arguments

1:   TRANS – CHARACTER(1)Input
On entry: indicates the form of the equations.
TRANS='N'
AX=B is solved for X.
TRANS='T' or 'C'
AT X=B is solved for X.
Constraint: TRANS='N', 'T' or 'C'.
2:   N – INTEGERInput
On entry: n, the order of the matrix A.
Constraint: N≥0.
3:   KL – INTEGERInput
On entry: kl, the number of subdiagonals within the band of the matrix A.
Constraint: KL≥0.
4:   KU – INTEGERInput
On entry: ku, the number of superdiagonals within the band of the matrix A.
Constraint: KU≥0.
5:   NRHS – INTEGERInput
On entry: r, the number of right-hand sides.
Constraint: NRHS≥0.
6:   AB LDAB* – REAL (KIND=nag_wp) arrayInput
Note: the second dimension of the array AB must be at least max 1,N.
On entry: the LU factorization of A, as returned by F07BDF (DGBTRF).
7:   LDAB – INTEGERInput
On entry: the first dimension of the array AB as declared in the (sub)program from which F07BEF (DGBTRS) is called.
Constraint: LDAB≥2×KL+KU+1.
8:   IPIV* – INTEGER arrayInput
Note: the dimension of the array IPIV must be at least max 1,N.
On entry: the pivot indices, as returned by F07BDF (DGBTRF).
9:   B LDB* – REAL (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array B must be at least max 1,NRHS.
On entry: the n by r right-hand side matrix B.
On exit: the n by r solution matrix X.
10:   LDB – INTEGERInput
On entry: the first dimension of the array B as declared in the (sub)program from which F07BEF (DGBTRS) is called.
Constraint: LDB≥max 1,N.
11:   INFO – INTEGEROutput
On exit: INFO=0 unless the routine detects an error (see Section 6).

6 Error Indicators and Warnings

INFO<0
If INFO=-i, argument i had an illegal value. An explanatory message is output, and execution of the program is terminated.

7 Accuracy

For each right-hand side vector b, the computed solution x is the exact solution of a perturbed system of equations A+E x=b, where
E≤c k εP LU ,
c k is a modest linear function of k=kl+ku+1, and ε is the machine precision. This assumes k≪n.
If x^ is the true solution, then the computed solution x satisfies a forward error bound of the form
x-x^∞ x∞ ≤c k cond A,x ε
where cond A,x=A-1Ax∞/x∞≤cond A=A-1A∞≤κ∞A.
Note that cond A,x can be much smaller than cond A, and cond AT can be much larger (or smaller) than cond A.
Forward and backward error bounds can be computed by calling F07BHF (DGBRFS), and an estimate for κ∞A can be obtained by calling F07BGF (DGBCON) with NORM='I'.

8 Parallelism and Performance

F07BEF (DGBTRS) is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
F07BEF (DGBTRS) makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The total number of floating-point operations is approximately 2 n 2 kl+ku r, assuming n≫kl and n≫ku.
This routine may be followed by a call to F07BHF (DGBRFS) to refine the solution and return an error estimate.
The complex analogue of this routine is F07BSF (ZGBTRS).

10 Example

This example solves the system of equations AX=B, where
A= -0.23 2.54 -3.66 0.00 -6.98 2.46 -2.73 -2.13 0.00 2.56 2.46 4.07 0.00 0.00 -4.78 -3.82   and   B= 4.42 -36.01 27.13 -31.67 -6.14 -1.16 10.50 -25.82 .
Here A is nonsymmetric and is treated as a band matrix, which must first be factorized by F07BDF (DGBTRF).

10.1 Program Text

Program Text (f07befe.f90)

10.2 Program Data

Program Data (f07befe.d)

10.3 Program Results

Program Results (f07befe.r)

F07 Chapter Contents
F07 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F07BFF (DGBEQU) : NAG Library, Mark 26

F07 Chapter Contents
F07 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F07BFF (DGBEQU)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F07BFF (DGBEQU) computes diagonal scaling matrices DR and DC intended to equilibrate a real m by n band matrix A of band width kl + ku + 1 , and reduce its condition number.

2 Specification

SUBROUTINE F07BFF ( M, N, KL, KU, AB, LDAB, R, C, ROWCND, COLCND, AMAX, INFO)
INTEGER | M, N, KL, KU, LDAB, INFO
REAL (KIND=nag_wp) | AB(LDAB,*), R(M), C(N), ROWCND, COLCND, AMAX
The routine may be called by its LAPACK name dgbequ.

3 Description

F07BFF (DGBEQU) computes the diagonal scaling matrices. The diagonal scaling matrices are chosen to try to make the elements of largest absolute value in each row and column of the matrix B given by
B = DR A DC
have absolute value 1 . The diagonal elements of DR and DC are restricted to lie in the safe range δ,1/δ , where δ is the value returned by routine X02AMF. Use of these scaling factors is not guaranteed to reduce the condition number of A but works well in practice.

4 References

None.

5 Arguments

1:   M – INTEGERInput
On entry: m, the number of rows of the matrix A.
Constraint: M≥0.
2:   N – INTEGERInput
On entry: n, the number of columns of the matrix A.
Constraint: N≥0.
3:   KL – INTEGERInput
On entry: kl, the number of subdiagonals of the matrix A.
Constraint: KL≥0.
4:   KU – INTEGERInput
On entry: ku, the number of superdiagonals of the matrix A.
Constraint: KU≥0.
5:   AB LDAB* – REAL (KIND=nag_wp) arrayInput
Note: the second dimension of the array AB must be at least max 1,N.
On entry: the m by n band matrix A whose scaling factors are to be computed.
The matrix is stored in rows 1 to kl+ku+1, more precisely, the element A ij must be stored in
AB ku+1+i-j j  for ​max 1,j-ku≤i≤min m,j+kl.
See Section 9 in F07BAF (DGBSV) for further details.
6:   LDAB – INTEGERInput
On entry: the first dimension of the array AB as declared in the (sub)program from which F07BFF (DGBEQU) is called.
Constraint: LDAB≥KL+KU+1.
7:   R M – REAL (KIND=nag_wp) arrayOutput
On exit: if INFO=0 or INFO>M, R contains the row scale factors, the diagonal elements of DR. The elements of R will be positive.
8:   C N – REAL (KIND=nag_wp) arrayOutput
On exit: if INFO=0, C contains the column scale factors, the diagonal elements of DC. The elements of C will be positive.
9:   ROWCND – REAL (KIND=nag_wp)Output
On exit: if INFO=0 or INFO>M, ROWCND contains the ratio of the smallest value of R i to the largest value of R i. If ROWCND≥0.1 and AMAX is neither too large nor too small, it is not worth scaling by DR.
10:   COLCND – REAL (KIND=nag_wp)Output
On exit: if INFO=0, COLCND contains the ratio of the smallest value of C i to the largest value of C i.
If COLCND≥0.1, it is not worth scaling by DC.
11:   AMAX – REAL (KIND=nag_wp)Output
On exit: max a ij. If AMAX is very close to overflow or underflow, the matrix A should be scaled.
12:   INFO – INTEGEROutput
On exit: INFO=0 unless the routine detects an error (see Section 6).

6 Error Indicators and Warnings

INFO<0
If INFO=-i, argument i had an illegal value. An explanatory message is output, and execution of the program is terminated.
INFO>0 and INFO≤M
Row value of A is exactly zero.
INFO>M
Column value of A is exactly zero.

7 Accuracy

The computed scale factors will be close to the exact scale factors.

8 Parallelism and Performance

F07BFF (DGBEQU) is not threaded in any implementation.

9 Further Comments

The complex analogue of this routine is F07BTF (ZGBEQU).

10 Example

This example equilibrates the band matrix A given by
A = -0.23 2.54 -3.66×10-10 -0 -6.98×1010 2.46×1010 -2.73 -2.13×1010 -0 2.56 -2.46×10-10 -4.07 -0 0 -4.78×10-10 -3.82 .
Details of the scaling factors, and the scaled matrix are output.

10.1 Program Text

Program Text (f07bffe.f90)

10.2 Program Data

Program Data (f07bffe.d)

10.3 Program Results

Program Results (f07bffe.r)

F07 Chapter Contents
F07 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F07BGF (DGBCON) : NAG Library, Mark 26

F07 Chapter Contents
F07 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F07BGF (DGBCON)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F07BGF (DGBCON) estimates the condition number of a real band matrix A, where A has been factorized by F07BDF (DGBTRF).

2 Specification

SUBROUTINE F07BGF ( NORM, N, KL, KU, AB, LDAB, IPIV, ANORM, RCOND, WORK, IWORK, INFO)
INTEGER | N, KL, KU, LDAB, IPIV(*), IWORK(N), INFO
REAL (KIND=nag_wp) | AB(LDAB,*), ANORM, RCOND, WORK(3*N)
CHARACTER(1) | NORM
The routine may be called by its LAPACK name dgbcon.

3 Description

F07BGF (DGBCON) estimates the condition number of a real band matrix A, in either the 1-norm or the ∞-norm:
κ 1 A=A 1A-1 1   or   κ∞A=A∞A-1∞ .
Note that κ∞A=κ 1 AT.
Because the condition number is infinite if A is singular, the routine actually returns an estimate of the reciprocal of the condition number.
The routine should be preceded by a call to F06RBF to compute A 1 or A∞, and a call to F07BDF (DGBTRF) to compute the LU factorization of A. The routine then uses Higham's implementation of Hager's method (see Higham (1988)) to estimate A-1 1 or A-1∞.

4 References

Higham N J (1988) FORTRAN codes for estimating the one-norm of a real or complex matrix, with applications to condition estimation ACM Trans. Math. Software 14 381–396

5 Arguments

1:   NORM – CHARACTER(1)Input
On entry: indicates whether κ 1 A or κ∞A is estimated.
NORM='1' or 'O'
κ 1 A is estimated.
NORM='I'
κ∞A is estimated.
Constraint: NORM='1', 'O' or 'I'.
2:   N – INTEGERInput
On entry: n, the order of the matrix A.
Constraint: N≥0.
3:   KL – INTEGERInput
On entry: kl, the number of subdiagonals within the band of the matrix A.
Constraint: KL≥0.
4:   KU – INTEGERInput
On entry: ku, the number of superdiagonals within the band of the matrix A.
Constraint: KU≥0.
5:   AB LDAB* – REAL (KIND=nag_wp) arrayInput
Note: the second dimension of the array AB must be at least max 1,N.
On entry: the LU factorization of A, as returned by F07BDF (DGBTRF).
6:   LDAB – INTEGERInput
On entry: the first dimension of the array AB as declared in the (sub)program from which F07BGF (DGBCON) is called.
Constraint: LDAB≥2×KL+KU+1.
7:   IPIV* – INTEGER arrayInput
Note: the dimension of the array IPIV must be at least max 1,N.
On entry: the pivot indices, as returned by F07BDF (DGBTRF).
8:   ANORM – REAL (KIND=nag_wp)Input
On entry: if NORM='1' or 'O', the 1-norm of the original matrix A.
If NORM='I', the ∞-norm of the original matrix A.
ANORM may be computed by calling F06RBF with the same value for the argument NORM.
ANORM must be computed either before calling F07BDF (DGBTRF) or else from a copy of the original matrix A (see Section 10).
Constraint: ANORM≥0.0.
9:   RCOND – REAL (KIND=nag_wp)Output
On exit: an estimate of the reciprocal of the condition number of A. RCOND is set to zero if exact singularity is detected or the estimate underflows. If RCOND is less than machine precision, A is singular to working precision.
10:   WORK 3×N – REAL (KIND=nag_wp) arrayWorkspace
11:   IWORK N – INTEGER arrayWorkspace
12:   INFO – INTEGEROutput
On exit: INFO=0 unless the routine detects an error (see Section 6).

6 Error Indicators and Warnings

INFO<0
If INFO=-i, argument i had an illegal value. An explanatory message is output, and execution of the program is terminated.

7 Accuracy

The computed estimate RCOND is never less than the true value ρ, and in practice is nearly always less than 10 ρ, although examples can be constructed where RCOND is much larger.

8 Parallelism and Performance

F07BGF (DGBCON) makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

A call to F07BGF (DGBCON) involves solving a number of systems of linear equations of the form Ax=b or AT x=b; the number is usually 4 or 5 and never more than 11. Each solution involves approximately 2 n 2 kl+ku floating-point operations (assuming n≫kl and n≫ku) but takes considerably longer than a call to F07BEF (DGBTRS) with one right-hand side, because extra care is taken to avoid overflow when A is approximately singular.
The complex analogue of this routine is F07BUF (ZGBCON).

10 Example

This example estimates the condition number in the 1-norm of the matrix A, where
A= -0.23 2.54 -3.66 0.00 -6.98 2.46 -2.73 -2.13 0.00 2.56 2.46 4.07 0.00 0.00 -4.78 -3.82 .
Here A is nonsymmetric and is treated as a band matrix, which must first be factorized by F07BDF (DGBTRF). The true condition number in the 1-norm is 56.40.

10.1 Program Text

Program Text (f07bgfe.f90)

10.2 Program Data

Program Data (f07bgfe.d)

10.3 Program Results

Program Results (f07bgfe.r)

F07 Chapter Contents
F07 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F07BHF (DGBRFS) : NAG Library, Mark 26

F07 Chapter Contents
F07 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F07BHF (DGBRFS)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F07BHF (DGBRFS) returns error bounds for the solution of a real band system of linear equations with multiple right-hand sides, AX=B or AT X=B. It improves the solution by iterative refinement, in order to reduce the backward error as much as possible.

2 Specification

SUBROUTINE F07BHF ( TRANS, N, KL, KU, NRHS, AB, LDAB, AFB, LDAFB, IPIV, B, LDB, X, LDX, FERR, BERR, WORK, IWORK, INFO)
INTEGER | N, KL, KU, NRHS, LDAB, LDAFB, IPIV(*), LDB, LDX, IWORK(N), INFO
REAL (KIND=nag_wp) | AB(LDAB,*), AFB(LDAFB,*), B(LDB,*), X(LDX,*), FERR(NRHS), BERR(NRHS), WORK(3*N)
CHARACTER(1) | TRANS
The routine may be called by its LAPACK name dgbrfs.

3 Description

F07BHF (DGBRFS) returns the backward errors and estimated bounds on the forward errors for the solution of a real band system of linear equations with multiple right-hand sides AX=B or AT X=B. The routine handles each right-hand side vector (stored as a column of the matrix B) independently, so we describe the function of F07BHF (DGBRFS) in terms of a single right-hand side b and solution x.
Given a computed solution x, the routine computes the component-wise backward error β. This is the size of the smallest relative perturbation in each element of A and b such that x is the exact solution of a perturbed system
A+δA x=b+δb δ a ij≤β a ij   and   δ bi≤β bi .
Then the routine estimates a bound for the component-wise forward error in the computed solution, defined by:
maxi xi - x^i / maxi xi
where x^ is the true solution.
For details of the method, see the F07 Chapter Introduction.

4 References

Golub G H and Van Loan C F (1996) Matrix Computations (3rd Edition) Johns Hopkins University Press, Baltimore

5 Arguments

1:   TRANS – CHARACTER(1)Input
On entry: indicates the form of the linear equations for which X is the computed solution.
TRANS='N'
The linear equations are of the form AX=B.
TRANS='T' or 'C'
The linear equations are of the form AT X=B.
Constraint: TRANS='N', 'T' or 'C'.
2:   N – INTEGERInput
On entry: n, the order of the matrix A.
Constraint: N≥0.
3:   KL – INTEGERInput
On entry: kl, the number of subdiagonals within the band of the matrix A.
Constraint: KL≥0.
4:   KU – INTEGERInput
On entry: ku, the number of superdiagonals within the band of the matrix A.
Constraint: KU≥0.
5:   NRHS – INTEGERInput
On entry: r, the number of right-hand sides.
Constraint: NRHS≥0.
6:   AB LDAB* – REAL (KIND=nag_wp) arrayInput
Note: the second dimension of the array AB must be at least max 1,N.
On entry: the original n by n band matrix A as supplied to F07BDF (DGBTRF).
The matrix is stored in rows 1 to kl+ku+1, more precisely, the element A ij must be stored in
AB ku+1+i-j j  for ​max 1,j-ku≤i≤min n,j+kl.
See Section 9 in F07BAF (DGBSV) for further details.
7:   LDAB – INTEGERInput
On entry: the first dimension of the array AB as declared in the (sub)program from which F07BHF (DGBRFS) is called.
Constraint: LDAB≥KL+KU+1.
8:   AFB LDAFB* – REAL (KIND=nag_wp) arrayInput
Note: the second dimension of the array AFB must be at least max 1,N.
On entry: the LU factorization of A, as returned by F07BDF (DGBTRF).
9:   LDAFB – INTEGERInput
On entry: the first dimension of the array AFB as declared in the (sub)program from which F07BHF (DGBRFS) is called.
Constraint: LDAFB≥2×KL+KU+1.
10:   IPIV* – INTEGER arrayInput
Note: the dimension of the array IPIV must be at least max 1,N.
On entry: the pivot indices, as returned by F07BDF (DGBTRF).
11:   B LDB* – REAL (KIND=nag_wp) arrayInput
Note: the second dimension of the array B must be at least max 1,NRHS.
On entry: the n by r right-hand side matrix B.
12:   LDB – INTEGERInput
On entry: the first dimension of the array B as declared in the (sub)program from which F07BHF (DGBRFS) is called.
Constraint: LDB≥max 1,N.
13:   X LDX* – REAL (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array X must be at least max 1,NRHS.
On entry: the n by r solution matrix X, as returned by F07BEF (DGBTRS).
On exit: the improved solution matrix X.
14:   LDX – INTEGERInput
On entry: the first dimension of the array X as declared in the (sub)program from which F07BHF (DGBRFS) is called.
Constraint: LDX≥max 1,N.
15:   FERR NRHS – REAL (KIND=nag_wp) arrayOutput
On exit: FERR j contains an estimated error bound for the jth solution vector, that is, the jth column of X, for j=1,2,…,r.
16:   BERR NRHS – REAL (KIND=nag_wp) arrayOutput
On exit: BERR j contains the component-wise backward error bound β for the jth solution vector, that is, the jth column of X, for j=1,2,…,r.
17:   WORK 3×N – REAL (KIND=nag_wp) arrayWorkspace
18:   IWORK N – INTEGER arrayWorkspace
19:   INFO – INTEGEROutput
On exit: INFO=0 unless the routine detects an error (see Section 6).

6 Error Indicators and Warnings

INFO<0
If INFO=-i, argument i had an illegal value. An explanatory message is output, and execution of the program is terminated.

7 Accuracy

The bounds returned in FERR are not rigorous, because they are estimated, not computed exactly; but in practice they almost always overestimate the actual error.

8 Parallelism and Performance

F07BHF (DGBRFS) is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
F07BHF (DGBRFS) makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

For each right-hand side, computation of the backward error involves a minimum of 4 n kl+ku floating-point operations. Each step of iterative refinement involves an additional 2 n 4 kl+3 ku operations. This assumes n≫kl and n≫ku. At most five steps of iterative refinement are performed, but usually only one or two steps are required.
Estimating the forward error involves solving a number of systems of linear equations of the form Ax=b or AT x=b; the number is usually 4 or 5 and never more than 11. Each solution involves approximately 2 n 2 kl+ku operations.
The complex analogue of this routine is F07BVF (ZGBRFS).

10 Example

This example solves the system of equations AX=B using iterative refinement and to compute the forward and backward error bounds, where
A= -0.23 2.54 -3.66 0.00 -6.98 2.46 -2.73 -2.13 0.00 2.56 2.46 4.07 0.00 0.00 -4.78 -3.82   and   B= 4.42 -36.01 27.13 -31.67 -6.14 -1.16 10.50 -25.82 .
Here A is nonsymmetric and is treated as a band matrix, which must first be factorized by F07BDF (DGBTRF).

10.1 Program Text

Program Text (f07bhfe.f90)

10.2 Program Data

Program Data (f07bhfe.d)

10.3 Program Results

Program Results (f07bhfe.r)

F07 Chapter Contents
F07 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F07BNF (ZGBSV) : NAG Library, Mark 26

F07 Chapter Contents
F07 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F07BNF (ZGBSV)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F07BNF (ZGBSV) computes the solution to a complex system of linear equations
AX=B ,
where A is an n by n band matrix, with kl subdiagonals and ku superdiagonals, and X and B are n by r matrices.

2 Specification

SUBROUTINE F07BNF ( N, KL, KU, NRHS, AB, LDAB, IPIV, B, LDB, INFO)
INTEGER | N, KL, KU, NRHS, LDAB, IPIV(N), LDB, INFO
COMPLEX (KIND=nag_wp) | AB(LDAB,*), B(LDB,*)
The routine may be called by its LAPACK name zgbsv.

3 Description

F07BNF (ZGBSV) uses the LU decomposition with partial pivoting and row interchanges to factor A as A=PLU, where P is a permutation matrix, L is a product of permutation and unit lower triangular matrices with kl subdiagonals, and U is upper triangular with kl+ku superdiagonals. The factored form of A is then used to solve the system of equations AX=B.

4 References

Anderson E, Bai Z, Bischof C, Blackford S, Demmel J, Dongarra J J, Du Croz J J, Greenbaum A, Hammarling S, McKenney A and Sorensen D (1999) LAPACK Users' Guide (3rd Edition) SIAM, Philadelphia http://www.netlib.org/lapack/lug
Golub G H and Van Loan C F (1996) Matrix Computations (3rd Edition) Johns Hopkins University Press, Baltimore

5 Arguments

1:   N – INTEGERInput
On entry: n, the number of linear equations, i.e., the order of the matrix A.
Constraint: N≥0.
2:   KL – INTEGERInput
On entry: kl, the number of subdiagonals within the band of the matrix A.
Constraint: KL≥0.
3:   KU – INTEGERInput
On entry: ku, the number of superdiagonals within the band of the matrix A.
Constraint: KU≥0.
4:   NRHS – INTEGERInput
On entry: r, the number of right-hand sides, i.e., the number of columns of the matrix B.
Constraint: NRHS≥0.
5:   AB LDAB* – COMPLEX (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array AB must be at least max 1,N.
On entry: the n by n coefficient matrix A.
The matrix is stored in rows kl+1 to 2 kl+ku+1; the first kl rows need not be set, more precisely, the element A ij must be stored in
AB kl+ku+1+i-j j=A ij  for ​max 1,j-ku≤i≤min n,j+kl.
See Section 9 for further details.
On exit: if INFO≥0, AB is overwritten by details of the factorization.
The upper triangular band matrix U, with kl+ku superdiagonals, is stored in rows 1 to kl+ku+1 of the array, and the multipliers used to form the matrix L are stored in rows kl+ku+2 to 2 kl+ku+1.
6:   LDAB – INTEGERInput
On entry: the first dimension of the array AB as declared in the (sub)program from which F07BNF (ZGBSV) is called.
Constraint: LDAB≥2×KL+KU+1.
7:   IPIV N – INTEGER arrayOutput
On exit: if no constraints are violated, the pivot indices that define the permutation matrix P; at the ith step row i of the matrix was interchanged with row IPIV i. IPIV i=i indicates a row interchange was not required.
8:   B LDB* – COMPLEX (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array B must be at least max 1,NRHS.
On entry: the n by r right-hand side matrix B.
On exit: if INFO=0, the n by r solution matrix X.
9:   LDB – INTEGERInput
On entry: the first dimension of the array B as declared in the (sub)program from which F07BNF (ZGBSV) is called.
Constraint: LDB≥max 1,N.
10:   INFO – INTEGEROutput
On exit: INFO=0 unless the routine detects an error (see Section 6).

6 Error Indicators and Warnings

INFO<0
If INFO=-i, argument i had an illegal value. An explanatory message is output, and execution of the program is terminated.
INFO>0
Element value of the diagonal is exactly zero. The factorization has been completed, but the factor U is exactly singular, so the solution could not be computed.

7 Accuracy

The computed solution for a single right-hand side, x^ , satisfies an equation of the form
A+E x^ = b ,
where
E 1 = O ε A 1
and ε is the machine precision. An approximate error bound for the computed solution is given by
x^-x 1 x 1 ≤ κ A E 1 A 1 ,
where κ A = A-1 1 A 1 , the condition number of A with respect to the solution of the linear equations. See Section 4.4 of Anderson et al. (1999) for further details.
Following the use of F07BNF (ZGBSV), F07BUF (ZGBCON) can be used to estimate the condition number of A and F07BVF (ZGBRFS) can be used to obtain approximate error bounds. Alternatives to F07BNF (ZGBSV), which return condition and error estimates directly are F04CBF and F07BPF (ZGBSVX).

8 Parallelism and Performance

F07BNF (ZGBSV) is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
F07BNF (ZGBSV) makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The band storage scheme for the array AB is illustrated by the following example, when n=6 , kl=1 , and ku=2 . Storage of the band matrix A in the array AB:
* * * + + + * * a 13 a 24 a 35 a 46 * a 12 a 23 a 34 a 45 a 56 a 11 a 22 a 33 a 44 a 55 a 66 a 21 a 32 a 43 a 54 a 65 *
Array elements marked * need not be set and are not referenced by the routine. Array elements marked + need not be set, but are defined on exit from the routine and contain the elements u 14 , u 25 and u 36 .
The total number of floating-point operations required to solve the equations AX=B depends upon the pivoting required, but if n≫kl + ku then it is approximately bounded by O n kl kl + ku for the factorization and O n 2 kl + ku r for the solution following the factorization.
The real analogue of this routine is F07BAF (DGBSV).

10 Example

This example solves the equations
Ax=b ,
where A is the band matrix
A = -1.65+2.26 i -2.05-0.85 i 0.97-2.84 i 0.00i+0.00 6.30 i -1.48-1.75 i -3.99+4.01 i 0.59-0.48 i 0.00i+0.00 -0.77+2.83 i -1.06+1.94 i 3.33-1.04 i 0.00i+0.00 0.00i+0.00 4.48-1.09 i -0.46-1.72 i
and
b = -1.06+21.50 i -22.72-53.90 i 28.24-38.60 i -34.56+16.73 i .
Details of the LU factorization of A are also output.

10.1 Program Text

Program Text (f07bnfe.f90)

10.2 Program Data

Program Data (f07bnfe.d)

10.3 Program Results

Program Results (f07bnfe.r)

F07 Chapter Contents
F07 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F07BPF (ZGBSVX) : NAG Library, Mark 26

F07 Chapter Contents
F07 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F07BPF (ZGBSVX)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F07BPF (ZGBSVX) uses the LU factorization to compute the solution to a complex system of linear equations
AX=B ,  AT X=B   or   AH X=B ,
where A is an n by n band matrix with kl subdiagonals and ku superdiagonals, and X and B are n by r matrices. Error bounds on the solution and a condition estimate are also provided.

2 Specification

SUBROUTINE F07BPF ( FACT, TRANS, N, KL, KU, NRHS, AB, LDAB, AFB, LDAFB, IPIV, EQUED, R, C, B, LDB, X, LDX, RCOND, FERR, BERR, WORK, RWORK, INFO)
INTEGER | N, KL, KU, NRHS, LDAB, LDAFB, IPIV(*), LDB, LDX, INFO
REAL (KIND=nag_wp) | R(*), C(*), RCOND, FERR(NRHS), BERR(NRHS), RWORK(max(1,N))
COMPLEX (KIND=nag_wp) | AB(LDAB,*), AFB(LDAFB,*), B(LDB,*), X(LDX,*), WORK(2*N)
CHARACTER(1) | FACT, TRANS, EQUED
The routine may be called by its LAPACK name zgbsvx.

3 Description

F07BPF (ZGBSVX) performs the following steps:
1. Equilibration
The linear system to be solved may be badly scaled. However, the system can be equilibrated as a first stage by setting FACT='E'. In this case, real scaling factors are computed and these factors then determine whether the system is to be equilibrated. Equilibrated forms of the systems AX=B , AT X=B and AH X=B are
DR A DC DC-1 X = DR B ,
DR A DC T DR-1 X = DC B ,
and
DR A DC H DR-1 X = DC B ,
respectively, where DR and DC are diagonal matrices, with positive diagonal elements, formed from the computed scaling factors.
When equilibration is used, A will be overwritten by DR A DC and B will be overwritten by DR B (or DC B when the solution of AT X=B or AH X=B is sought).
2. Factorization
The matrix A, or its scaled form, is copied and factored using the LU decomposition
A=PLU ,
where P is a permutation matrix, L is a unit lower triangular matrix, and U is upper triangular.
This stage can be by-passed when a factored matrix (with scaled matrices and scaling factors) are supplied; for example, as provided by a previous call to F07BPF (ZGBSVX) with the same matrix A.
3. Condition Number Estimation
The LU factorization of A determines whether a solution to the linear system exists. If some diagonal element of U is zero, then U is exactly singular, no solution exists and the routine returns with a failure. Otherwise the factorized form of A is used to estimate the condition number of the matrix A. If the reciprocal of the condition number is less than machine precision then a warning code is returned on final exit.
4. Solution
The (equilibrated) system is solved for X ( DC-1 X or DR-1 X ) using the factored form of A ( DR A DC ).
5. Iterative Refinement
Iterative refinement is applied to improve the computed solution matrix and to calculate error bounds and backward error estimates for the computed solution.
6. Construct Solution Matrix X
If equilibration was used, the matrix X is premultiplied by DC (if TRANS='N') or DR (if TRANS='T' or 'C') so that it solves the original system before equilibration.

4 References

Anderson E, Bai Z, Bischof C, Blackford S, Demmel J, Dongarra J J, Du Croz J J, Greenbaum A, Hammarling S, McKenney A and Sorensen D (1999) LAPACK Users' Guide (3rd Edition) SIAM, Philadelphia http://www.netlib.org/lapack/lug
Golub G H and Van Loan C F (1996) Matrix Computations (3rd Edition) Johns Hopkins University Press, Baltimore
Higham N J (2002) Accuracy and Stability of Numerical Algorithms (2nd Edition) SIAM, Philadelphia

5 Arguments

1:   FACT – CHARACTER(1)Input
On entry: specifies whether or not the factorized form of the matrix A is supplied on entry, and if not, whether the matrix A should be equilibrated before it is factorized.
FACT='F'
AFB and IPIV contain the factorized form of A. If EQUED≠'N', the matrix A has been equilibrated with scaling factors given by R and C. AB, AFB and IPIV are not modified.
FACT='N'
The matrix A will be copied to AFB and factorized.
FACT='E'
The matrix A will be equilibrated if necessary, then copied to AFB and factorized.
Constraint: FACT='F', 'N' or 'E'.
2:   TRANS – CHARACTER(1)Input
On entry: specifies the form of the system of equations.
TRANS='N'
AX=B (No transpose).
TRANS='T'
AT X=B (Transpose).
TRANS='C'
AH X=B (Conjugate transpose).
Constraint: TRANS='N', 'T' or 'C'.
3:   N – INTEGERInput
On entry: n, the number of linear equations, i.e., the order of the matrix A.
Constraint: N≥0.
4:   KL – INTEGERInput
On entry: kl, the number of subdiagonals within the band of the matrix A.
Constraint: KL≥0.
5:   KU – INTEGERInput
On entry: ku, the number of superdiagonals within the band of the matrix A.
Constraint: KU≥0.
6:   NRHS – INTEGERInput
On entry: r, the number of right-hand sides, i.e., the number of columns of the matrix B.
Constraint: NRHS≥0.
7:   AB LDAB* – COMPLEX (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array AB must be at least max 1,N.
On entry: the n by n coefficient matrix A.
The matrix is stored in rows 1 to kl+ku+1, more precisely, the element A ij must be stored in
AB ku+1+i-j j  for ​max 1,j-ku≤i≤min n,j+kl.
See Section 9 for further details.
If FACT='F' and EQUED≠'N', A must have been equilibrated by the scaling factors in R and/or C.
On exit: if FACT='F' or 'N', or if FACT='E' and EQUED='N', AB is not modified.
If EQUED≠'N' then, if no constraints are violated, A is scaled as follows:
  • if EQUED='R', A=Dr A;
  • if EQUED='C', A=A Dc;
  • if EQUED='B', A=Dr A Dc.
8:   LDAB – INTEGERInput
On entry: the first dimension of the array AB as declared in the (sub)program from which F07BPF (ZGBSVX) is called.
Constraint: LDAB≥KL+KU+1.
9:   AFB LDAFB* – COMPLEX (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array AFB must be at least max 1,N.
On entry: if FACT='N' or 'E', AFB need not be set.
If FACT='F', details of the LU factorization of the n by n band matrix A, as computed by F07BRF (ZGBTRF).
The upper triangular band matrix U, with kl+ku superdiagonals, is stored in rows 1 to kl+ku+1 of the array, and the multipliers used to form the matrix L are stored in rows kl+ku+2 to 2 kl+ku+1.
If EQUED≠'N', AFB is the factorized form of the equilibrated matrix A.
On exit: if FACT='F', AFB is unchanged from entry.
Otherwise, if no constraints are violated, then if FACT='N', AFB returns details of the LU factorization of the band matrix A, and if FACT='E', AFB returns details of the LU factorization of the equilibrated band matrix A (see the description of AB for the form of the equilibrated matrix).
10:   LDAFB – INTEGERInput
On entry: the first dimension of the array AFB as declared in the (sub)program from which F07BPF (ZGBSVX) is called.
Constraint: LDAFB≥2×KL+KU+1.
11:   IPIV* – INTEGER arrayInput/Output
Note: the dimension of the array IPIV must be at least max 1,N.
On entry: if FACT='N' or 'E', IPIV need not be set.
If FACT='F', IPIV contains the pivot indices from the factorization A=LU, as computed by F07BDF (DGBTRF); row i of the matrix was interchanged with row IPIV i.
On exit: if FACT='F', IPIV is unchanged from entry.
Otherwise, if no constraints are violated, IPIV contains the pivot indices that define the permutation matrix P; at the ith step row i of the matrix was interchanged with row IPIV i. IPIV i=i indicates a row interchange was not required.
If FACT='N', the pivot indices are those corresponding to the factorization A=LU of the original matrix A.
If FACT='E', the pivot indices are those corresponding to the factorization of A=LU of the equilibrated matrix A.
12:   EQUED – CHARACTER(1)Input/Output
On entry: if FACT='N' or 'E', EQUED need not be set.
If FACT='F', EQUED must specify the form of the equilibration that was performed as follows:
  • if EQUED='N', no equilibration;
  • if EQUED='R', row equilibration, i.e., A has been premultiplied by DR;
  • if EQUED='C', column equilibration, i.e., A has been postmultiplied by DC;
  • if EQUED='B', both row and column equilibration, i.e., A has been replaced by DR A DC.
On exit: if FACT='F', EQUED is unchanged from entry.
Otherwise, if no constraints are violated, EQUED specifies the form of equilibration that was performed as specified above.
Constraint: if FACT='F', EQUED='N', 'R', 'C' or 'B'.
13:   R* – REAL (KIND=nag_wp) arrayInput/Output
Note: the dimension of the array R must be at least max 1,N.
On entry: if FACT='N' or 'E', R need not be set.
If FACT='F' and EQUED='R' or 'B', R must contain the row scale factors for A, DR; each element of R must be positive.
On exit: if FACT='F', R is unchanged from entry.
Otherwise, if no constraints are violated and EQUED='R' or 'B', R contains the row scale factors for A, DR, such that A is multiplied on the left by DR; each element of R is positive.
14:   C* – REAL (KIND=nag_wp) arrayInput/Output
Note: the dimension of the array C must be at least max 1,N.
On entry: if FACT='N' or 'E', C need not be set.
If FACT='F' or EQUED='C' or 'B', C must contain the column scale factors for A, DC; each element of C must be positive.
On exit: if FACT='F', C is unchanged from entry.
Otherwise, if no constraints are violated and EQUED='C' or 'B', C contains the row scale factors for A, DC; each element of C is positive.
15:   B LDB* – COMPLEX (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array B must be at least max 1,NRHS.
On entry: the n by r right-hand side matrix B.
On exit: if EQUED='N', B is not modified.
If TRANS='N' and EQUED='R' or 'B', B is overwritten by DR B.
If TRANS='T' or 'C' and EQUED='C' or 'B', B is overwritten by DC B.
16:   LDB – INTEGERInput
On entry: the first dimension of the array B as declared in the (sub)program from which F07BPF (ZGBSVX) is called.
Constraint: LDB≥max 1,N.
17:   X LDX* – COMPLEX (KIND=nag_wp) arrayOutput
Note: the second dimension of the array X must be at least max 1,NRHS.
On exit: if INFO=0 or N+1, the n by r solution matrix X to the original system of equations. Note that the arrays A and B are modified on exit if EQUED≠'N', and the solution to the equilibrated system is DC-1 X if TRANS='N' and EQUED='C' or 'B', or DR-1 X if TRANS='T' or 'C' and EQUED='R' or 'B'.
18:   LDX – INTEGERInput
On entry: the first dimension of the array X as declared in the (sub)program from which F07BPF (ZGBSVX) is called.
Constraint: LDX≥max 1,N.
19:   RCOND – REAL (KIND=nag_wp)Output
On exit: if no constraints are violated, an estimate of the reciprocal condition number of the matrix A (after equilibration if that is performed), computed as RCOND=1.0/A 1 A-1 1 .
20:   FERR NRHS – REAL (KIND=nag_wp) arrayOutput
On exit: if INFO=0 or N+1, an estimate of the forward error bound for each computed solution vector, such that x^j-xj∞/xj∞≤FERR j where x^j is the jth column of the computed solution returned in the array X and xj is the corresponding column of the exact solution X. The estimate is as reliable as the estimate for RCOND, and is almost always a slight overestimate of the true error.
21:   BERR NRHS – REAL (KIND=nag_wp) arrayOutput
On exit: if INFO=0 or N+1, an estimate of the component-wise relative backward error of each computed solution vector x^j (i.e., the smallest relative change in any element of A or B that makes x^j an exact solution).
22:   WORK 2×N – COMPLEX (KIND=nag_wp) arrayWorkspace
23:   RWORK max 1,N – REAL (KIND=nag_wp) arrayOutput
On exit: if INFO=0, RWORK 1 contains the reciprocal pivot growth factor max a ij/max u ij. If RWORK 1 is much less than 1, then the stability of the LU factorization of the (equilibrated) matrix A could be poor. This also means that the solution X, condition estimator RCOND, and forward error bound FERR could be unreliable. If the factorization fails with INFO>0 and INFO≤N, RWORK 1 contains the reciprocal pivot growth factor for the leading INFO columns of A.
24:   INFO – INTEGEROutput
On exit: INFO=0 unless the routine detects an error (see Section 6).

6 Error Indicators and Warnings

INFO<0
If INFO=-i, argument i had an illegal value. An explanatory message is output, and execution of the program is terminated.
INFO>0 and INFO≤N
Element value of the diagonal is exactly zero. The factorization has been completed, but the factor U is exactly singular, so the solution and error bounds could not be computed. RCOND=0.0 is returned.
INFO=N+1
U is nonsingular, but RCOND is less than machine precision, meaning that the matrix is singular to working precision. Nevertheless, the solution and error bounds are computed because there are a number of situations where the computed solution can be more accurate than the value of RCOND would suggest.

7 Accuracy

For each right-hand side vector b, the computed solution x^ is the exact solution of a perturbed system of equations A+E x^=b, where
E≤c n εP LU ,
c n is a modest linear function of n, and ε is the machine precision. See Section 9.3 of Higham (2002) for further details.
If x is the true solution, then the computed solution x^ satisfies a forward error bound of the form
x-x^∞ x^∞ ≤ wc cond A,x^,b
where cond A,x^,b = A-1 A x^ + b ∞/ x^∞ ≤ cond A = A-1 A ∞≤κ∞ A. If x^ is the j th column of X , then wc is returned in BERR j and a bound on x - x^ ∞ / x^ ∞ is returned in FERR j . See Section 4.4 of Anderson et al. (1999) for further details.

8 Parallelism and Performance

F07BPF (ZGBSVX) is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
F07BPF (ZGBSVX) makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The band storage scheme for the array AB is illustrated by the following example, when n=6 , kl=1 , and ku=2 . Storage of the band matrix A in the array AB:
* * a 13 a 24 a 35 a 46 * a 12 a 23 a 34 a 45 a 56 a 11 a 22 a 33 a 44 a 55 a 66 a 21 a 32 a 43 a 54 a 65 *
The total number of floating-point operations required to solve the equations AX=B depends upon the pivoting required, but if n≫kl + ku then it is approximately bounded by O n kl kl + ku for the factorization and O n 2 kl + ku r for the solution following the factorization. The condition number estimation typically requires between four and five solves and never more than eleven solves, following the factorization. The solution is then refined, and the errors estimated, using iterative refinement; see F07BVF (ZGBRFS) for information on the floating-point operations required.
In practice the condition number estimator is very reliable, but it can underestimate the true condition number; see Section 15.3 of Higham (2002) for further details.
The real analogue of this routine is F07BBF (DGBSVX).

10 Example

This example solves the equations
AX=B ,
where A is the band matrix
A = -1.65+2.26 i -2.05-0.85 i 0.97-2.84 i 0.00i+0.00 6.30 i -1.48-1.75 i -3.99+4.01 i 0.59-0.48 i 0.00i+0.00 -0.77+2.83 i -1.06+1.94 i 3.33-1.04 i 0.00i+0.00 0.00i+0.00 4.48-1.09 i -0.46-1.72 i
and
B = -1.06+21.50 i 12.85+0 2.84 i -22.72-53.90 i -70.22+21.57 i 28.24-38.60 i -20.73-0 1.23 i -34.56+16.73 i 26.01+31.97 i .
Estimates for the backward errors, forward errors, condition number and pivot growth are also output, together with information on the equilibration of A .

10.1 Program Text

Program Text (f07bpfe.f90)

10.2 Program Data

Program Data (f07bpfe.d)

10.3 Program Results

Program Results (f07bpfe.r)

F07 Chapter Contents
F07 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F07BRF (ZGBTRF) : NAG Library, Mark 26

F07 Chapter Contents
F07 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F07BRF (ZGBTRF)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F07BRF (ZGBTRF) computes the LU factorization of a complex m by n band matrix.

2 Specification

SUBROUTINE F07BRF ( M, N, KL, KU, AB, LDAB, IPIV, INFO)
INTEGER | M, N, KL, KU, LDAB, IPIV(min(M,N)), INFO
COMPLEX (KIND=nag_wp) | AB(LDAB,*)
The routine may be called by its LAPACK name zgbtrf.

3 Description

F07BRF (ZGBTRF) forms the LU factorization of a complex m by n band matrix A using partial pivoting, with row interchanges. Usually m=n, and then, if A has kl nonzero subdiagonals and ku nonzero superdiagonals, the factorization has the form A=PLU, where P is a permutation matrix, L is a lower triangular matrix with unit diagonal elements and at most kl nonzero elements in each column, and U is an upper triangular band matrix with kl+ku superdiagonals.
Note that L is not a band matrix, but the nonzero elements of L can be stored in the same space as the subdiagonal elements of A. U is a band matrix but with kl additional superdiagonals compared with A. These additional superdiagonals are created by the row interchanges.

4 References

Golub G H and Van Loan C F (1996) Matrix Computations (3rd Edition) Johns Hopkins University Press, Baltimore

5 Arguments

1:   M – INTEGERInput
On entry: m, the number of rows of the matrix A.
Constraint: M≥0.
2:   N – INTEGERInput
On entry: n, the number of columns of the matrix A.
Constraint: N≥0.
3:   KL – INTEGERInput
On entry: kl, the number of subdiagonals within the band of the matrix A.
Constraint: KL≥0.
4:   KU – INTEGERInput
On entry: ku, the number of superdiagonals within the band of the matrix A.
Constraint: KU≥0.
5:   AB LDAB* – COMPLEX (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array AB must be at least max 1,N.
On entry: the m by n matrix A.
The matrix is stored in rows kl+1 to 2 kl+ku+1; the first kl rows need not be set, more precisely, the element A ij must be stored in
AB kl+ku+1+i-j j=A ij  for ​max 1,j-ku≤i≤min m,j+kl.
See Section 9 in F07BNF (ZGBSV) for further details.
On exit: if INFO≥0, AB is overwritten by details of the factorization.
The upper triangular band matrix U, with kl+ku superdiagonals, is stored in rows 1 to kl+ku+1 of the array, and the multipliers used to form the matrix L are stored in rows kl+ku+2 to 2 kl+ku+1.
6:   LDAB – INTEGERInput
On entry: the first dimension of the array AB as declared in the (sub)program from which F07BRF (ZGBTRF) is called.
Constraint: LDAB≥2×KL+KU+1.
7:   IPIV min M,N – INTEGER arrayOutput
On exit: the pivot indices that define the permutation matrix. At the ith step, if IPIV i>i then row i of the matrix A was interchanged with row IPIV i, for i=1,2,…,min m,n. IPIV i≤i indicates that, at the ith step, a row interchange was not required.
8:   INFO – INTEGEROutput
On exit: INFO=0 unless the routine detects an error (see Section 6).

6 Error Indicators and Warnings

INFO<0
If INFO=-i, argument i had an illegal value.
If INFO=-999, dynamic memory allocation failed. See Section 3.7 in How to Use the NAG Library and its Documentation for further information. An explanatory message is output, and execution of the program is terminated.
INFO>0
Element value of the diagonal is exactly zero. The factorization has been completed, but the factor U is exactly singular, and division by zero will occur if it is used to solve a system of equations.

7 Accuracy

The computed factors L and U are the exact factors of a perturbed matrix A+E, where
E≤c k εP LU ,
c k is a modest linear function of k=kl+ku+1, and ε is the machine precision. This assumes k ≪ min m,n .

8 Parallelism and Performance

F07BRF (ZGBTRF) is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
F07BRF (ZGBTRF) makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The total number of real floating-point operations varies between approximately 8 n kl ku+1 and 8 n kl kl+ku+1, depending on the interchanges, assuming m=n≫kl and n≫ku.
A call to F07BRF (ZGBTRF) may be followed by calls to the routines:
  • F07BSF (ZGBTRS) to solve AX=B, AT X=B or AH X=B;
  • F07BUF (ZGBCON) to estimate the condition number of A.
The real analogue of this routine is F07BDF (DGBTRF).

10 Example

This example computes the LU factorization of the matrix A, where
A= -1.65+2.26 i -2.05-0.85 i 0.97-2.84 i 0.00+0.00 i 0.00+6.30 i -1.48-1.75 i -3.99+4.01 i 0.59-0.48 i 0.00+0.00 i -0.77+2.83 i -1.06+1.94 i 3.33-1.04 i 0.00+0.00 i 0.00+0.00 i 4.48-1.09 i -0.46-1.72 i .
Here A is treated as a band matrix with one subdiagonal and two superdiagonals.

10.1 Program Text

Program Text (f07brfe.f90)

10.2 Program Data

Program Data (f07brfe.d)

10.3 Program Results

Program Results (f07brfe.r)

F07 Chapter Contents
F07 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F07BSF (ZGBTRS) : NAG Library, Mark 26

F07 Chapter Contents
F07 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F07BSF (ZGBTRS)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F07BSF (ZGBTRS) solves a complex band system of linear equations with multiple right-hand sides,
AX=B ,  AT X=B   or   AH X=B ,
where A has been factorized by F07BRF (ZGBTRF).

2 Specification

SUBROUTINE F07BSF ( TRANS, N, KL, KU, NRHS, AB, LDAB, IPIV, B, LDB, INFO)
INTEGER | N, KL, KU, NRHS, LDAB, IPIV(*), LDB, INFO
COMPLEX (KIND=nag_wp) | AB(LDAB,*), B(LDB,*)
CHARACTER(1) | TRANS
The routine may be called by its LAPACK name zgbtrs.

3 Description

F07BSF (ZGBTRS) is used to solve a complex band system of linear equations AX=B, AT X=B or AH X=B, the routine must be preceded by a call to F07BRF (ZGBTRF) which computes the LU factorization of A as A=PLU. The solution is computed by forward and backward substitution.
If TRANS='N', the solution is computed by solving PLY=B and then UX=Y.
If TRANS='T', the solution is computed by solving UT Y=B and then LTPT X=Y.
If TRANS='C', the solution is computed by solving UH Y=B and then LHPT X=Y.

4 References

Golub G H and Van Loan C F (1996) Matrix Computations (3rd Edition) Johns Hopkins University Press, Baltimore

5 Arguments

1:   TRANS – CHARACTER(1)Input
On entry: indicates the form of the equations.
TRANS='N'
AX=B is solved for X.
TRANS='T'
AT X=B is solved for X.
TRANS='C'
AH X=B is solved for X.
Constraint: TRANS='N', 'T' or 'C'.
2:   N – INTEGERInput
On entry: n, the order of the matrix A.
Constraint: N≥0.
3:   KL – INTEGERInput
On entry: kl, the number of subdiagonals within the band of the matrix A.
Constraint: KL≥0.
4:   KU – INTEGERInput
On entry: ku, the number of superdiagonals within the band of the matrix A.
Constraint: KU≥0.
5:   NRHS – INTEGERInput
On entry: r, the number of right-hand sides.
Constraint: NRHS≥0.
6:   AB LDAB* – COMPLEX (KIND=nag_wp) arrayInput
Note: the second dimension of the array AB must be at least max 1,N.
On entry: the LU factorization of A, as returned by F07BRF (ZGBTRF).
7:   LDAB – INTEGERInput
On entry: the first dimension of the array AB as declared in the (sub)program from which F07BSF (ZGBTRS) is called.
Constraint: LDAB≥2×KL+KU+1.
8:   IPIV* – INTEGER arrayInput
Note: the dimension of the array IPIV must be at least max 1,N.
On entry: the pivot indices, as returned by F07BRF (ZGBTRF).
9:   B LDB* – COMPLEX (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array B must be at least max 1,NRHS.
On entry: the n by r right-hand side matrix B.
On exit: the n by r solution matrix X.
10:   LDB – INTEGERInput
On entry: the first dimension of the array B as declared in the (sub)program from which F07BSF (ZGBTRS) is called.
Constraint: LDB≥max 1,N.
11:   INFO – INTEGEROutput
On exit: INFO=0 unless the routine detects an error (see Section 6).

6 Error Indicators and Warnings

INFO<0
If INFO=-i, argument i had an illegal value. An explanatory message is output, and execution of the program is terminated.

7 Accuracy

For each right-hand side vector b, the computed solution x is the exact solution of a perturbed system of equations A+E x=b, where
E≤c k ε LU ,
c k is a modest linear function of k=kl+ku+1, and ε is the machine precision. This assumes k≪n.
If x^ is the true solution, then the computed solution x satisfies a forward error bound of the form
x-x^∞ x∞ ≤c k cond A,x ε
where cond A,x=A-1Ax∞/x∞≤cond A=A-1A∞≤κ∞A.
Note that cond A,x can be much smaller than cond A, and cond AH (which is the same as cond AT) can be much larger (or smaller) than cond A.
Forward and backward error bounds can be computed by calling F07BVF (ZGBRFS), and an estimate for κ∞A can be obtained by calling F07BUF (ZGBCON) with NORM='I'.

8 Parallelism and Performance

F07BSF (ZGBTRS) is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
F07BSF (ZGBTRS) makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The total number of real floating-point operations is approximately 8 n 2 kl+ku r, assuming n≫kl and n≫ku.
This routine may be followed by a call to F07BVF (ZGBRFS) to refine the solution and return an error estimate.
The real analogue of this routine is F07BEF (DGBTRS).

10 Example

This example solves the system of equations AX=B, where
A= -1.65+2.26 i -2.05-0.85 i 0.97-2.84 i 0.00+0.00 i 0.00+6.30 i -1.48-1.75 i -3.99+4.01 i 0.59-0.48 i 0.00+0.00 i -0.77+2.83 i -1.06+1.94 i 3.33-1.04 i 0.00+0.00 i 0.00+0.00 i 4.48-1.09 i -0.46-1.72 i
and
B= -1.06+21.50 i 12.85+0 2.84 i -22.72-53.90 i -70.22+21.57 i 28.24-38.60 i -20.7 0-31.23 i -34.56+16.73 i 26.01+31.97 i .
Here A is nonsymmetric and is treated as a band matrix, which must first be factorized by F07BRF (ZGBTRF).

10.1 Program Text

Program Text (f07bsfe.f90)

10.2 Program Data

Program Data (f07bsfe.d)

10.3 Program Results

Program Results (f07bsfe.r)

F07 Chapter Contents
F07 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F07BTF (ZGBEQU) : NAG Library, Mark 26

F07 Chapter Contents
F07 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F07BTF (ZGBEQU)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F07BTF (ZGBEQU) computes diagonal scaling matrices DR and DC intended to equilibrate a complex m by n band matrix A of band width kl + ku + 1 , and reduce its condition number.

2 Specification

SUBROUTINE F07BTF ( M, N, KL, KU, AB, LDAB, R, C, ROWCND, COLCND, AMAX, INFO)
INTEGER | M, N, KL, KU, LDAB, INFO
REAL (KIND=nag_wp) | R(M), C(N), ROWCND, COLCND, AMAX
COMPLEX (KIND=nag_wp) | AB(LDAB,*)
The routine may be called by its LAPACK name zgbequ.

3 Description

F07BTF (ZGBEQU) computes the diagonal scaling matrices. The diagonal scaling matrices are chosen to try to make the elements of largest absolute value in each row and column of the matrix B given by
B = DR A DC
have absolute value 1 . The diagonal elements of DR and DC are restricted to lie in the safe range δ,1/δ , where δ is the value returned by routine X02AMF. Use of these scaling factors is not guaranteed to reduce the condition number of A but works well in practice.

4 References

None.

5 Arguments

1:   M – INTEGERInput
On entry: m, the number of rows of the matrix A.
Constraint: M≥0.
2:   N – INTEGERInput
On entry: n, the number of columns of the matrix A.
Constraint: N≥0.
3:   KL – INTEGERInput
On entry: kl, the number of subdiagonals of the matrix A.
Constraint: KL≥0.
4:   KU – INTEGERInput
On entry: ku, the number of superdiagonals of the matrix A.
Constraint: KU≥0.
5:   AB LDAB* – COMPLEX (KIND=nag_wp) arrayInput
Note: the second dimension of the array AB must be at least max 1,N.
On entry: the m by n band matrix A whose scaling factors are to be computed.
The matrix is stored in rows 1 to kl+ku+1, more precisely, the element A ij must be stored in
AB ku+1+i-j j  for ​max 1,j-ku≤i≤min m,j+kl.
See Section 9 in F07BNF (ZGBSV) for further details.
6:   LDAB – INTEGERInput
On entry: the first dimension of the array AB as declared in the (sub)program from which F07BTF (ZGBEQU) is called.
Constraint: LDAB≥KL+KU+1.
7:   R M – REAL (KIND=nag_wp) arrayOutput
On exit: if INFO=0 or INFO>M, R contains the row scale factors, the diagonal elements of DR. The elements of R will be positive.
8:   C N – REAL (KIND=nag_wp) arrayOutput
On exit: if INFO=0, C contains the column scale factors, the diagonal elements of DC. The elements of C will be positive.
9:   ROWCND – REAL (KIND=nag_wp)Output
On exit: if INFO=0 or INFO>M, ROWCND contains the ratio of the smallest value of R i to the largest value of R i. If ROWCND≥0.1 and AMAX is neither too large nor too small, it is not worth scaling by DR.
10:   COLCND – REAL (KIND=nag_wp)Output
On exit: if INFO=0, COLCND contains the ratio of the smallest value of C i to the largest value of C i.
If COLCND≥0.1, it is not worth scaling by DC.
11:   AMAX – REAL (KIND=nag_wp)Output
On exit: max a ij. If AMAX is very close to overflow or underflow, the matrix A should be scaled.
12:   INFO – INTEGEROutput
On exit: INFO=0 unless the routine detects an error (see Section 6).

6 Error Indicators and Warnings

INFO<0
If INFO=-i, argument i had an illegal value. An explanatory message is output, and execution of the program is terminated.
INFO>0 and INFO≤M
Row value of A is exactly zero.
INFO>M
Column value of A is exactly zero.

7 Accuracy

The computed scale factors will be close to the exact scale factors.

8 Parallelism and Performance

F07BTF (ZGBEQU) is not threaded in any implementation.

9 Further Comments

The real analogue of this routine is F07BFF (DGBEQU).

10 Example

This example equilibrates the complex band matrix A given by
A = -1.65+2.26 i -2.05-0.85 i×10-10 -(0.97-2.84 i ((0 -0.00+6.30 i -1.48-1.75 i×10-10 (-3.99+4.01 i ((0.59-0.48 i -0 (-0.77+2.83 i -1.06+1.94 i×1010 (3.33-1.04 i×1010 -0 -(0 -(0.48-1.09 i -0.46-1.72 i .
Details of the scaling factors, and the scaled matrix are output.

10.1 Program Text

Program Text (f07btfe.f90)

10.2 Program Data

Program Data (f07btfe.d)

10.3 Program Results

Program Results (f07btfe.r)

F07 Chapter Contents
F07 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F07BUF (ZGBCON) : NAG Library, Mark 26

F07 Chapter Contents
F07 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F07BUF (ZGBCON)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F07BUF (ZGBCON) estimates the condition number of a complex band matrix A, where A has been factorized by F07BRF (ZGBTRF).

2 Specification

SUBROUTINE F07BUF ( NORM, N, KL, KU, AB, LDAB, IPIV, ANORM, RCOND, WORK, RWORK, INFO)
INTEGER | N, KL, KU, LDAB, IPIV(*), INFO
REAL (KIND=nag_wp) | ANORM, RCOND, RWORK(N)
COMPLEX (KIND=nag_wp) | AB(LDAB,*), WORK(2*N)
CHARACTER(1) | NORM
The routine may be called by its LAPACK name zgbcon.

3 Description

F07BUF (ZGBCON) estimates the condition number of a complex band matrix A, in either the 1-norm or the ∞-norm:
κ 1 A=A 1A-1 1   or   κ∞A=A∞A-1∞ .
Note that κ∞A=κ 1 AH.
Because the condition number is infinite if A is singular, the routine actually returns an estimate of the reciprocal of the condition number.
The routine should be preceded by a call to F06UBF to compute A 1 or A∞, and a call to F07BRF (ZGBTRF) to compute the LU factorization of A. The routine then uses Higham's implementation of Hager's method (see Higham (1988)) to estimate A-1 1 or A-1∞.

4 References

Higham N J (1988) FORTRAN codes for estimating the one-norm of a real or complex matrix, with applications to condition estimation ACM Trans. Math. Software 14 381–396

5 Arguments

1:   NORM – CHARACTER(1)Input
On entry: indicates whether κ 1 A or κ∞A is estimated.
NORM='1' or 'O'
κ 1 A is estimated.
NORM='I'
κ∞A is estimated.
Constraint: NORM='1', 'O' or 'I'.
2:   N – INTEGERInput
On entry: n, the order of the matrix A.
Constraint: N≥0.
3:   KL – INTEGERInput
On entry: kl, the number of subdiagonals within the band of the matrix A.
Constraint: KL≥0.
4:   KU – INTEGERInput
On entry: ku, the number of superdiagonals within the band of the matrix A.
Constraint: KU≥0.
5:   AB LDAB* – COMPLEX (KIND=nag_wp) arrayInput
Note: the second dimension of the array AB must be at least max 1,N.
On entry: the LU factorization of A, as returned by F07BRF (ZGBTRF).
6:   LDAB – INTEGERInput
On entry: the first dimension of the array AB as declared in the (sub)program from which F07BUF (ZGBCON) is called.
Constraint: LDAB≥2×KL+KU+1.
7:   IPIV* – INTEGER arrayInput
Note: the dimension of the array IPIV must be at least max 1,N.
On entry: the pivot indices, as returned by F07BRF (ZGBTRF).
8:   ANORM – REAL (KIND=nag_wp)Input
On entry: if NORM='1' or 'O', the 1-norm of the original matrix A.
If NORM='I', the ∞-norm of the original matrix A.
ANORM may be computed by calling F06UBF with the same value for the argument NORM.
ANORM must be computed either before calling F07BRF (ZGBTRF) or else from a copy of the original matrix A (see Section 10).
Constraint: ANORM≥0.0.
9:   RCOND – REAL (KIND=nag_wp)Output
On exit: an estimate of the reciprocal of the condition number of A. RCOND is set to zero if exact singularity is detected or the estimate underflows. If RCOND is less than machine precision, A is singular to working precision.
10:   WORK 2×N – COMPLEX (KIND=nag_wp) arrayWorkspace
11:   RWORK N – REAL (KIND=nag_wp) arrayWorkspace
12:   INFO – INTEGEROutput
On exit: INFO=0 unless the routine detects an error (see Section 6).

6 Error Indicators and Warnings

INFO<0
If INFO=-i, argument i had an illegal value. An explanatory message is output, and execution of the program is terminated.

7 Accuracy

The computed estimate RCOND is never less than the true value ρ, and in practice is nearly always less than 10 ρ, although examples can be constructed where RCOND is much larger.

8 Parallelism and Performance

F07BUF (ZGBCON) makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

A call to F07BUF (ZGBCON) involves solving a number of systems of linear equations of the form Ax=b or AH x=b; the number is usually 5 and never more than 11. Each solution involves approximately 8 n 2 kl+ku real floating-point operations (assuming n≫kl and n≫ku) but takes considerably longer than a call to F07BSF (ZGBTRS) with one right-hand side, because extra care is taken to avoid overflow when A is approximately singular.
The real analogue of this routine is F07BGF (DGBCON).

10 Example

This example estimates the condition number in the 1-norm of the matrix A, where
A= -1.65+2.26 i -2.05-0.85 i 0.97-2.84 i 0.00+0.00 i 0.00+6.30 i -1.48-1.75 i -3.99+4.01 i 0.59-0.48 i 0.00+0.00 i -0.77+2.83 i -1.06+1.94 i 3.33-1.04 i 0.00+0.00 i 0.00+0.00 i 4.48-1.09 i -0.46-1.72 i .

10.1 Program Text

Program Text (f07bufe.f90)

10.2 Program Data

Program Data (f07bufe.d)

10.3 Program Results

Program Results (f07bufe.r)

F07 Chapter Contents
F07 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F07BVF (ZGBRFS) : NAG Library, Mark 26

F07 Chapter Contents
F07 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F07BVF (ZGBRFS)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F07BVF (ZGBRFS) returns error bounds for the solution of a complex band system of linear equations with multiple right-hand sides, AX=B, AT X=B or AH X=B. It improves the solution by iterative refinement, in order to reduce the backward error as much as possible.

2 Specification

SUBROUTINE F07BVF ( TRANS, N, KL, KU, NRHS, AB, LDAB, AFB, LDAFB, IPIV, B, LDB, X, LDX, FERR, BERR, WORK, RWORK, INFO)
INTEGER | N, KL, KU, NRHS, LDAB, LDAFB, IPIV(*), LDB, LDX, INFO
REAL (KIND=nag_wp) | FERR(NRHS), BERR(NRHS), RWORK(N)
COMPLEX (KIND=nag_wp) | AB(LDAB,*), AFB(LDAFB,*), B(LDB,*), X(LDX,*), WORK(2*N)
CHARACTER(1) | TRANS
The routine may be called by its LAPACK name zgbrfs.

3 Description

F07BVF (ZGBRFS) returns the backward errors and estimated bounds on the forward errors for the solution of a complex band system of linear equations with multiple right-hand sides AX=B, AT X=B or AH X=B. The routine handles each right-hand side vector (stored as a column of the matrix B) independently, so we describe the function of F07BVF (ZGBRFS) in terms of a single right-hand side b and solution x.
Given a computed solution x, the routine computes the component-wise backward error β. This is the size of the smallest relative perturbation in each element of A and b such that x is the exact solution of a perturbed system
A+δA x=b+δb δ a ij≤β a ij   and   δ bi≤β bi .
Then the routine estimates a bound for the component-wise forward error in the computed solution, defined by:
maxi xi-x^i/maxi xi
where x^ is the true solution.
For details of the method, see the F07 Chapter Introduction.

4 References

Golub G H and Van Loan C F (1996) Matrix Computations (3rd Edition) Johns Hopkins University Press, Baltimore

5 Arguments

1:   TRANS – CHARACTER(1)Input
On entry: indicates the form of the linear equations for which X is the computed solution as follows:
TRANS='N'
The linear equations are of the form AX=B.
TRANS='T'
The linear equations are of the form AT X=B.
TRANS='C'
The linear equations are of the form AH X=B.
Constraint: TRANS='N', 'T' or 'C'.
2:   N – INTEGERInput
On entry: n, the order of the matrix A.
Constraint: N≥0.
3:   KL – INTEGERInput
On entry: kl, the number of subdiagonals within the band of the matrix A.
Constraint: KL≥0.
4:   KU – INTEGERInput
On entry: ku, the number of superdiagonals within the band of the matrix A.
Constraint: KU≥0.
5:   NRHS – INTEGERInput
On entry: r, the number of right-hand sides.
Constraint: NRHS≥0.
6:   AB LDAB* – COMPLEX (KIND=nag_wp) arrayInput
Note: the second dimension of the array AB must be at least max 1,N.
On entry: the original n by n band matrix A as supplied to F07BRF (ZGBTRF).
The matrix is stored in rows 1 to kl+ku+1, more precisely, the element A ij must be stored in
AB ku+1+i-j j  for ​max 1,j-ku≤i≤min n,j+kl.
See Section 9 in F07BNF (ZGBSV) for further details.
7:   LDAB – INTEGERInput
On entry: the first dimension of the array AB as declared in the (sub)program from which F07BVF (ZGBRFS) is called.
Constraint: LDAB≥KL+KU+1.
8:   AFB LDAFB* – COMPLEX (KIND=nag_wp) arrayInput
Note: the second dimension of the array AFB must be at least max 1,N.
On entry: the LU factorization of A, as returned by F07BRF (ZGBTRF).
9:   LDAFB – INTEGERInput
On entry: the first dimension of the array AFB as declared in the (sub)program from which F07BVF (ZGBRFS) is called.
Constraint: LDAFB≥2×KL+KU+1.
10:   IPIV* – INTEGER arrayInput
Note: the dimension of the array IPIV must be at least max 1,N.
On entry: the pivot indices, as returned by F07BRF (ZGBTRF).
11:   B LDB* – COMPLEX (KIND=nag_wp) arrayInput
Note: the second dimension of the array B must be at least max 1,NRHS.
On entry: the n by r right-hand side matrix B.
12:   LDB – INTEGERInput
On entry: the first dimension of the array B as declared in the (sub)program from which F07BVF (ZGBRFS) is called.
Constraint: LDB≥max 1,N.
13:   X LDX* – COMPLEX (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array X must be at least max 1,NRHS.
On entry: the n by r solution matrix X, as returned by F07BSF (ZGBTRS).
On exit: the improved solution matrix X.
14:   LDX – INTEGERInput
On entry: the first dimension of the array X as declared in the (sub)program from which F07BVF (ZGBRFS) is called.
Constraint: LDX≥max 1,N.
15:   FERR NRHS – REAL (KIND=nag_wp) arrayOutput
On exit: FERR j contains an estimated error bound for the jth solution vector, that is, the jth column of X, for j=1,2,…,r.
16:   BERR NRHS – REAL (KIND=nag_wp) arrayOutput
On exit: BERR j contains the component-wise backward error bound β for the jth solution vector, that is, the jth column of X, for j=1,2,…,r.
17:   WORK 2×N – COMPLEX (KIND=nag_wp) arrayWorkspace
18:   RWORK N – REAL (KIND=nag_wp) arrayWorkspace
19:   INFO – INTEGEROutput
On exit: INFO=0 unless the routine detects an error (see Section 6).

6 Error Indicators and Warnings

INFO<0
If INFO=-i, argument i had an illegal value. An explanatory message is output, and execution of the program is terminated.

7 Accuracy

The bounds returned in FERR are not rigorous, because they are estimated, not computed exactly; but in practice they almost always overestimate the actual error.

8 Parallelism and Performance

F07BVF (ZGBRFS) is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
F07BVF (ZGBRFS) makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

For each right-hand side, computation of the backward error involves a minimum of 16 n kl+ku real floating-point operations. Each step of iterative refinement involves an additional 8 n 4 kl+3 ku real operations. This assumes n≫kl and n≫ku. At most five steps of iterative refinement are performed, but usually only one or two steps are required.
Estimating the forward error involves solving a number of systems of linear equations of the form Ax=b or AH x=b; the number is usually 5 and never more than 11. Each solution involves approximately 8 n 2 kl+ku real operations.
The real analogue of this routine is F07BHF (DGBRFS).

10 Example

This example solves the system of equations AX=B using iterative refinement and to compute the forward and backward error bounds, where
A= -1.65+2.26 i -2.05-0.85 i 0.97-2.84 i 0.00+0.00 i 0.00+6.30 i -1.48-1.75 i -3.99+4.01 i 0.59-0.48 i 0.00+0.00 i -0.77+2.83 i -1.06+1.94 i 3.33-1.04 i 0.00+0.00 i 0.00+0.00 i 4.48-1.09 i -0.46-1.72 i
and
B= -1.06+21.50 i 12.85+0 2.84 i -22.72-53.90 i -70.22+21.57 i 28.24-38.60 i -20.73-0 1.23 i -34.56+16.73 i 26.01+31.97 i .
Here A is nonsymmetric and is treated as a band matrix, which must first be factorized by F07BRF (ZGBTRF).

10.1 Program Text

Program Text (f07bvfe.f90)

10.2 Program Data

Program Data (f07bvfe.d)

10.3 Program Results

Program Results (f07bvfe.r)

F07 Chapter Contents
F07 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F07CAF (DGTSV) : NAG Library, Mark 26

F07 Chapter Contents
F07 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F07CAF (DGTSV)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F07CAF (DGTSV) computes the solution to a real system of linear equations
AX=B ,
where A is an n by n tridiagonal matrix and X and B are n by r matrices.

2 Specification

SUBROUTINE F07CAF ( N, NRHS, DL, D, DU, B, LDB, INFO)
INTEGER | N, NRHS, LDB, INFO
REAL (KIND=nag_wp) | DL(*), D(*), DU(*), B(LDB,*)
The routine may be called by its LAPACK name dgtsv.

3 Description

F07CAF (DGTSV) uses Gaussian elimination with partial pivoting and row interchanges to solve the equations AX=B . The matrix A is factorized as A=PLU , where P is a permutation matrix, L is unit lower triangular with at most one nonzero subdiagonal element per column, and U is an upper triangular band matrix, with two superdiagonals.
Note that equations AT X=B may be solved by interchanging the order of the arguments DU and DL.

4 References

Anderson E, Bai Z, Bischof C, Blackford S, Demmel J, Dongarra J J, Du Croz J J, Greenbaum A, Hammarling S, McKenney A and Sorensen D (1999) LAPACK Users' Guide (3rd Edition) SIAM, Philadelphia http://www.netlib.org/lapack/lug

5 Arguments

1:   N – INTEGERInput
On entry: n, the number of linear equations, i.e., the order of the matrix A.
Constraint: N≥0.
2:   NRHS – INTEGERInput
On entry: r, the number of right-hand sides, i.e., the number of columns of the matrix B.
Constraint: NRHS≥0.
3:   DL* – REAL (KIND=nag_wp) arrayInput/Output
Note: the dimension of the array DL must be at least max 1,N-1.
On entry: must contain the n-1 subdiagonal elements of the matrix A.
On exit: if no constraints are violated, DL is overwritten by the (n-2) elements of the second superdiagonal of the upper triangular matrix U from the LU factorization of A, in DL 1,DL 2,…,DL n-2.
4:   D* – REAL (KIND=nag_wp) arrayInput/Output
Note: the dimension of the array D must be at least max 1,N.
On entry: must contain the n diagonal elements of the matrix A.
On exit: if no constraints are violated, D is overwritten by the n diagonal elements of the upper triangular matrix U from the LU factorization of A.
5:   DU* – REAL (KIND=nag_wp) arrayInput/Output
Note: the dimension of the array DU must be at least max 1,N-1.
On entry: must contain the n-1 superdiagonal elements of the matrix A.
On exit: if no constraints are violated, DU is overwritten by the n-1 elements of the first superdiagonal of U.
6:   B LDB* – REAL (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array B must be at least max 1,NRHS.
To solve the equations Ax=b, where b is a single right-hand side, B may be supplied as a one-dimensional array with length LDB=max 1,N.
On entry: the n by r right-hand side matrix B.
On exit: if INFO=0, the n by r solution matrix X.
7:   LDB – INTEGERInput
On entry: the first dimension of the array B as declared in the (sub)program from which F07CAF (DGTSV) is called.
Constraint: LDB≥max 1,N.
8:   INFO – INTEGEROutput
On exit: INFO=0 unless the routine detects an error (see Section 6).

6 Error Indicators and Warnings

INFO<0
If INFO=-i, argument i had an illegal value. An explanatory message is output, and execution of the program is terminated.
INFO>0
Element value of the diagonal is exactly zero, and the solution has not been computed. The factorization has not been completed unless N=value.

7 Accuracy

The computed solution for a single right-hand side, x^ , satisfies an equation of the form
A+E x^ = b ,
where
E 1 = O ε A 1
and ε is the machine precision. An approximate error bound for the computed solution is given by
x^-x 1 x 1 ≤ κ A E 1 A 1 ,
where κ A = A-1 1 A 1 , the condition number of A with respect to the solution of the linear equations. See Section 4.4 of Anderson et al. (1999) for further details.
Alternatives to F07CAF (DGTSV), which return condition and error estimates are F04BCF and F07CBF (DGTSVX).

8 Parallelism and Performance

F07CAF (DGTSV) is not threaded in any implementation.

9 Further Comments

The total number of floating-point operations required to solve the equations AX=B is proportional to nr .
The complex analogue of this routine is F07CNF (ZGTSV).

10 Example

This example solves the equations
Ax=b ,
where A is the tridiagonal matrix
A = 3.0 2.1 0.0 0.0 0.0 3.4 2.3 -1.0 0.0 0.0 0.0 3.6 -5.0 1.9 0.0 0.0 0.0 7.0 -0.9 8.0 0.0 0.0 0.0 -6.0 7.1   and   b = 2.7 -0.5 2.6 0.6 2.7 .

10.1 Program Text

Program Text (f07cafe.f90)

10.2 Program Data

Program Data (f07cafe.d)

10.3 Program Results

Program Results (f07cafe.r)

F07 Chapter Contents
F07 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F07CBF (DGTSVX) : NAG Library, Mark 26

F07 Chapter Contents
F07 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F07CBF (DGTSVX)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F07CBF (DGTSVX) uses the LU factorization to compute the solution to a real system of linear equations
AX=B   or   AT X=B ,
where A is a tridiagonal matrix of order n and X and B are n by r matrices. Error bounds on the solution and a condition estimate are also provided.

2 Specification

SUBROUTINE F07CBF ( FACT, TRANS, N, NRHS, DL, D, DU, DLF, DF, DUF, DU2, IPIV, B, LDB, X, LDX, RCOND, FERR, BERR, WORK, IWORK, INFO)
INTEGER | N, NRHS, IPIV(*), LDB, LDX, IWORK(N), INFO
REAL (KIND=nag_wp) | DL(*), D(*), DU(*), DLF(*), DF(*), DUF(*), DU2(*), B(LDB,*), X(LDX,*), RCOND, FERR(NRHS), BERR(NRHS), WORK(3*N)
CHARACTER(1) | FACT, TRANS
The routine may be called by its LAPACK name dgtsvx.

3 Description

F07CBF (DGTSVX) performs the following steps:
1. | If FACT='N', the LU decomposition is used to factor the matrix A as A=LU, where L is a product of permutation and unit lower bidiagonal matrices and U is upper triangular with nonzeros in only the main diagonal and first two superdiagonals.
2. | If some u ii=0, so that U is exactly singular, then the routine returns with INFO=i. Otherwise, the factored form of A is used to estimate the condition number of the matrix A. If the reciprocal of the condition number is less than machine precision, INFO=N+1 is returned as a warning, but the routine still goes on to solve for X and compute error bounds as described below.
3. | The system of equations is solved for X using the factored form of A.
4. | Iterative refinement is applied to improve the computed solution matrix and to calculate error bounds and backward error estimates for it.

4 References

Anderson E, Bai Z, Bischof C, Blackford S, Demmel J, Dongarra J J, Du Croz J J, Greenbaum A, Hammarling S, McKenney A and Sorensen D (1999) LAPACK Users' Guide (3rd Edition) SIAM, Philadelphia http://www.netlib.org/lapack/lug
Golub G H and Van Loan C F (1996) Matrix Computations (3rd Edition) Johns Hopkins University Press, Baltimore
Higham N J (2002) Accuracy and Stability of Numerical Algorithms (2nd Edition) SIAM, Philadelphia

5 Arguments

1:   FACT – CHARACTER(1)Input
On entry: specifies whether or not the factorized form of the matrix A has been supplied.
FACT='F'
DLF, DF, DUF, DU2 and IPIV contain the factorized form of the matrix A. DLF, DF, DUF, DU2 and IPIV will not be modified.
FACT='N'
The matrix A will be copied to DLF, DF and DUF and factorized.
Constraint: FACT='F' or 'N'.
2:   TRANS – CHARACTER(1)Input
On entry: specifies the form of the system of equations.
TRANS='N'
AX=B (No transpose).
TRANS='T' or 'C'
AT X=B (Transpose).
Constraint: TRANS='N', 'T' or 'C'.
3:   N – INTEGERInput
On entry: n, the order of the matrix A.
Constraint: N≥0.
4:   NRHS – INTEGERInput
On entry: r, the number of right-hand sides, i.e., the number of columns of the matrix B.
Constraint: NRHS≥0.
5:   DL* – REAL (KIND=nag_wp) arrayInput
Note: the dimension of the array DL must be at least max 1,N-1.
On entry: the n-1 subdiagonal elements of A.
6:   D* – REAL (KIND=nag_wp) arrayInput
Note: the dimension of the array D must be at least max 1,N.
On entry: the n diagonal elements of A.
7:   DU* – REAL (KIND=nag_wp) arrayInput
Note: the dimension of the array DU must be at least max 1,N-1.
On entry: the n-1 superdiagonal elements of A.
8:   DLF* – REAL (KIND=nag_wp) arrayInput/Output
Note: the dimension of the array DLF must be at least max 1,N-1.
On entry: if FACT='F', DLF contains the n-1 multipliers that define the matrix L from the LU factorization of A.
On exit: if FACT='N', DLF contains the n-1 multipliers that define the matrix L from the LU factorization of A.
9:   DF* – REAL (KIND=nag_wp) arrayInput/Output
Note: the dimension of the array DF must be at least max 1,N.
On entry: if FACT='F', DF contains the n diagonal elements of the upper triangular matrix U from the LU factorization of A.
On exit: if FACT='N', DF contains the n diagonal elements of the upper triangular matrix U from the LU factorization of A.
10:   DUF* – REAL (KIND=nag_wp) arrayInput/Output
Note: the dimension of the array DUF must be at least max 1,N-1.
On entry: if FACT='F', DUF contains the n-1 elements of the first superdiagonal of U.
On exit: if FACT='N', DUF contains the n-1 elements of the first superdiagonal of U.
11:   DU2* – REAL (KIND=nag_wp) arrayInput/Output
Note: the dimension of the array DU2 must be at least max 1,N-2.
On entry: if FACT='F', DU2 contains the (n-2) elements of the second superdiagonal of U.
On exit: if FACT='N', DU2 contains the (n-2) elements of the second superdiagonal of U.
12:   IPIV* – INTEGER arrayInput/Output
Note: the dimension of the array IPIV must be at least max 1,N.
On entry: if FACT='F', IPIV contains the pivot indices from the LU factorization of A.
On exit: if FACT='N', IPIV contains the pivot indices from the LU factorization of A; row i of the matrix was interchanged with row IPIV i. IPIV i will always be either i or i+1; IPIV i=i indicates a row interchange was not required.
13:   B LDB* – REAL (KIND=nag_wp) arrayInput
Note: the second dimension of the array B must be at least max 1,NRHS.
On entry: the n by r right-hand side matrix B.
14:   LDB – INTEGERInput
On entry: the first dimension of the array B as declared in the (sub)program from which F07CBF (DGTSVX) is called.
Constraint: LDB≥max 1,N.
15:   X LDX* – REAL (KIND=nag_wp) arrayOutput
Note: the second dimension of the array X must be at least max 1,NRHS.
On exit: if INFO=0 or N+1, the n by r solution matrix X.
16:   LDX – INTEGERInput
On entry: the first dimension of the array X as declared in the (sub)program from which F07CBF (DGTSVX) is called.
Constraint: LDX≥max 1,N.
17:   RCOND – REAL (KIND=nag_wp)Output
On exit: the estimate of the reciprocal condition number of the matrix A. If RCOND=0.0, the matrix may be exactly singular. This condition is indicated by INFO>0 and INFO≤N. Otherwise, if RCOND is less than the machine precision, the matrix is singular to working precision. This condition is indicated by INFO=N+1.
18:   FERR NRHS – REAL (KIND=nag_wp) arrayOutput
On exit: if INFO=0 or N+1, an estimate of the forward error bound for each computed solution vector, such that x^j-xj∞/xj∞≤FERR j where x^j is the jth column of the computed solution returned in the array X and xj is the corresponding column of the exact solution X. The estimate is as reliable as the estimate for RCOND, and is almost always a slight overestimate of the true error.
19:   BERR NRHS – REAL (KIND=nag_wp) arrayOutput
On exit: if INFO=0 or N+1, an estimate of the component-wise relative backward error of each computed solution vector x^j (i.e., the smallest relative change in any element of A or B that makes x^j an exact solution).
20:   WORK 3×N – REAL (KIND=nag_wp) arrayWorkspace
21:   IWORK N – INTEGER arrayWorkspace
22:   INFO – INTEGEROutput
On exit: INFO=0 unless the routine detects an error (see Section 6).

6 Error Indicators and Warnings

INFO<0
If INFO=-i, argument i had an illegal value. An explanatory message is output, and execution of the program is terminated.
INFO>0 and INFO<N
Element value of the diagonal is exactly zero. The factorization has not been completed, but the factor U is exactly singular, so the solution and error bounds could not be computed. RCOND=0.0 is returned.
INFO>0 and INFO=N
Element value of the diagonal is exactly zero. The factorization has been completed, but the factor U is exactly singular, so the solution and error bounds could not be computed. RCOND=0.0 is returned.
INFO=N+1
U is nonsingular, but RCOND is less than machine precision, meaning that the matrix is singular to working precision. Nevertheless, the solution and error bounds are computed because there are a number of situations where the computed solution can be more accurate than the value of RCOND would suggest.

7 Accuracy

For each right-hand side vector b, the computed solution x^ is the exact solution of a perturbed system of equations A+E x^=b, where
E ≤ c n ε L U ,
c n is a modest linear function of n, and ε is the machine precision. See Section 9.3 of Higham (2002) for further details.
If x is the true solution, then the computed solution x^ satisfies a forward error bound of the form
x-x^∞ x^∞ ≤ wc cond A,x^,b
where cond A,x^,b = A-1 A x^ + b ∞/ x^∞ ≤ cond A = A-1 A ∞≤κ∞ A. If x^ is the j th column of X , then wc is returned in BERR j and a bound on x - x^ ∞ / x^ ∞ is returned in FERR j . See Section 4.4 of Anderson et al. (1999) for further details.

8 Parallelism and Performance

F07CBF (DGTSVX) is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
F07CBF (DGTSVX) makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The total number of floating-point operations required to solve the equations AX=B is proportional to nr .
The condition number estimation typically requires between four and five solves and never more than eleven solves, following the factorization. The solution is then refined, and the errors estimated, using iterative refinement.
In practice the condition number estimator is very reliable, but it can underestimate the true condition number; see Section 15.3 of Higham (2002) for further details.
The complex analogue of this routine is F07CPF (ZGTSVX).

10 Example

This example solves the equations
AX=B ,
where A is the tridiagonal matrix
A = 3.0 2.1 0.0 0.0 0.0 3.4 2.3 -1.0 0.0 0.0 0.0 3.6 -5.0 1.9 0.0 0.0 0.0 7.0 -0.9 8.0 0.0 0.0 0.0 -6.0 7.1
and
B = 2.7 6.6 -0.5 10.8 2.6 -3.2 0.6 -11.2 2.7 19.1 .
Estimates for the backward errors, forward errors and condition number are also output.

10.1 Program Text

Program Text (f07cbfe.f90)

10.2 Program Data

Program Data (f07cbfe.d)

10.3 Program Results

Program Results (f07cbfe.r)

F07 Chapter Contents
F07 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F07CDF (DGTTRF) : NAG Library, Mark 26

F07 Chapter Contents
F07 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F07CDF (DGTTRF)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F07CDF (DGTTRF) computes the LU factorization of a real n by n tridiagonal matrix A .

2 Specification

SUBROUTINE F07CDF ( N, DL, D, DU, DU2, IPIV, INFO)
INTEGER | N, IPIV(N), INFO
REAL (KIND=nag_wp) | DL(*), D(*), DU(*), DU2(N-2)
The routine may be called by its LAPACK name dgttrf.

3 Description

F07CDF (DGTTRF) uses Gaussian elimination with partial pivoting and row interchanges to factorize the matrix A as
A=PLU ,
where P is a permutation matrix, L is unit lower triangular with at most one nonzero subdiagonal element in each column, and U is an upper triangular band matrix, with two superdiagonals.

4 References

Anderson E, Bai Z, Bischof C, Blackford S, Demmel J, Dongarra J J, Du Croz J J, Greenbaum A, Hammarling S, McKenney A and Sorensen D (1999) LAPACK Users' Guide (3rd Edition) SIAM, Philadelphia http://www.netlib.org/lapack/lug

5 Arguments

1:   N – INTEGERInput
On entry: n, the order of the matrix A.
Constraint: N≥0.
2:   DL* – REAL (KIND=nag_wp) arrayInput/Output
Note: the dimension of the array DL must be at least max 1,N-1.
On entry: must contain the n-1 subdiagonal elements of the matrix A.
On exit: is overwritten by the n-1 multipliers that define the matrix L of the LU factorization of A.
3:   D* – REAL (KIND=nag_wp) arrayInput/Output
Note: the dimension of the array D must be at least max 1,N.
On entry: must contain the n diagonal elements of the matrix A.
On exit: is overwritten by the n diagonal elements of the upper triangular matrix U from the LU factorization of A.
4:   DU* – REAL (KIND=nag_wp) arrayInput/Output
Note: the dimension of the array DU must be at least max 1,N-1.
On entry: must contain the n-1 superdiagonal elements of the matrix A.
On exit: is overwritten by the n-1 elements of the first superdiagonal of U.
5:   DU2 N-2 – REAL (KIND=nag_wp) arrayOutput
On exit: contains the n-2 elements of the second superdiagonal of U.
6:   IPIV N – INTEGER arrayOutput
On exit: contains the n pivot indices that define the permutation matrix P. At the ith step, row i of the matrix was interchanged with row IPIV i. IPIV i will always be either i or i+1, IPIV i=i indicating that a row interchange was not performed.
7:   INFO – INTEGEROutput
On exit: INFO=0 unless the routine detects an error (see Section 6).

6 Error Indicators and Warnings

INFO<0
If INFO=-i, argument i had an illegal value. An explanatory message is output, and execution of the program is terminated.
INFO>0
Element value of the diagonal is exactly zero. The factorization has been completed, but the factor U is exactly singular, and division by zero will occur if it is used to solve a system of equations.

7 Accuracy

The computed factorization satisfies an equation of the form
A+E=PLU ,
where
E∞=O ε A∞
and ε is the machine precision.
Following the use of this routine, F07CEF (DGTTRS) can be used to solve systems of equations AX=B or AT X=B , and F07CGF (DGTCON) can be used to estimate the condition number of A .

8 Parallelism and Performance

F07CDF (DGTTRF) is not threaded in any implementation.

9 Further Comments

The total number of floating-point operations required to factorize the matrix A is proportional to n .
The complex analogue of this routine is F07CRF (ZGTTRF).

10 Example

This example factorizes the tridiagonal matrix A given by
A = 3.0 2.1 0.0 0.0 0.0 3.4 2.3 -1.0 0.0 0.0 0.0 3.6 -5.0 1.9 0.0 0.0 0.0 7.0 -0.9 8.0 0.0 0.0 0.0 -6.0 7.1 .

10.1 Program Text

Program Text (f07cdfe.f90)

10.2 Program Data

Program Data (f07cdfe.d)

10.3 Program Results

Program Results (f07cdfe.r)

F07 Chapter Contents
F07 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F07CEF (DGTTRS) : NAG Library, Mark 26

F07 Chapter Contents
F07 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F07CEF (DGTTRS)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F07CEF (DGTTRS) computes the solution to a real system of linear equations AX=B or AT X=B , where A is an n by n tridiagonal matrix and X and B are n by r matrices, using the LU factorization returned by F07CDF (DGTTRF).

2 Specification

SUBROUTINE F07CEF ( TRANS, N, NRHS, DL, D, DU, DU2, IPIV, B, LDB, INFO)
INTEGER | N, NRHS, IPIV(*), LDB, INFO
REAL (KIND=nag_wp) | DL(*), D(*), DU(*), DU2(*), B(LDB,*)
CHARACTER(1) | TRANS
The routine may be called by its LAPACK name dgttrs.

3 Description

F07CEF (DGTTRS) should be preceded by a call to F07CDF (DGTTRF), which uses Gaussian elimination with partial pivoting and row interchanges to factorize the matrix A as
A=PLU ,
where P is a permutation matrix, L is unit lower triangular with at most one nonzero subdiagonal element in each column, and U is an upper triangular band matrix, with two superdiagonals. F07CEF (DGTTRS) then utilizes the factorization to solve the required equations.

4 References

Anderson E, Bai Z, Bischof C, Blackford S, Demmel J, Dongarra J J, Du Croz J J, Greenbaum A, Hammarling S, McKenney A and Sorensen D (1999) LAPACK Users' Guide (3rd Edition) SIAM, Philadelphia http://www.netlib.org/lapack/lug

5 Arguments

1:   TRANS – CHARACTER(1)Input
On entry: specifies the equations to be solved as follows:
TRANS='N'
Solve AX=B for X.
TRANS='T' or 'C'
Solve AT X=B for X.
Constraint: TRANS='N', 'T' or 'C'.
2:   N – INTEGERInput
On entry: n, the order of the matrix A.
Constraint: N≥0.
3:   NRHS – INTEGERInput
On entry: r, the number of right-hand sides, i.e., the number of columns of the matrix B.
Constraint: NRHS≥0.
4:   DL* – REAL (KIND=nag_wp) arrayInput
Note: the dimension of the array DL must be at least max 1,N-1.
On entry: must contain the n-1 multipliers that define the matrix L of the LU factorization of A.
5:   D* – REAL (KIND=nag_wp) arrayInput
Note: the dimension of the array D must be at least max 1,N.
On entry: must contain the n diagonal elements of the upper triangular matrix U from the LU factorization of A.
6:   DU* – REAL (KIND=nag_wp) arrayInput
Note: the dimension of the array DU must be at least max 1,N-1.
On entry: must contain the n-1 elements of the first superdiagonal of U.
7:   DU2* – REAL (KIND=nag_wp) arrayInput
Note: the dimension of the array DU2 must be at least max 1,N-2.
On entry: must contain the n-2 elements of the second superdiagonal of U.
8:   IPIV* – INTEGER arrayInput
Note: the dimension of the array IPIV must be at least max 1,N.
On entry: must contain the n pivot indices that define the permutation matrix P. At the ith step, row i of the matrix was interchanged with row IPIV i, and IPIV i must always be either i or i+1, IPIV i=i indicating that a row interchange was not performed.
9:   B LDB* – REAL (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array B must be at least max 1,NRHS.
On entry: the n by r matrix of right-hand sides B.
On exit: the n by r solution matrix X.
10:   LDB – INTEGERInput
On entry: the first dimension of the array B as declared in the (sub)program from which F07CEF (DGTTRS) is called.
Constraint: LDB≥max 1,N.
11:   INFO – INTEGEROutput
On exit: INFO=0 unless the routine detects an error (see Section 6).

6 Error Indicators and Warnings

INFO<0
If INFO=-i, argument i had an illegal value. An explanatory message is output, and execution of the program is terminated.

7 Accuracy

The computed solution for a single right-hand side, x^ , satisfies an equation of the form
A+E x^=b ,
where
E 1 =O ε A 1
and ε is the machine precision. An approximate error bound for the computed solution is given by
x^-x 1 x 1 ≤ κ A E 1 A 1 ,
where κ A = A-1 1 A 1 , the condition number of A with respect to the solution of the linear equations. See Section 4.4 of Anderson et al. (1999) for further details.
Following the use of this routine F07CGF (DGTCON) can be used to estimate the condition number of A and F07CHF (DGTRFS) can be used to obtain approximate error bounds.

8 Parallelism and Performance

F07CEF (DGTTRS) is not threaded in any implementation.

9 Further Comments

The total number of floating-point operations required to solve the equations AX=B or AT X=B is proportional to nr .
The complex analogue of this routine is F07CSF (ZGTTRS).

10 Example

This example solves the equations
AX=B ,
where A is the tridiagonal matrix
A = 3.0 2.1 0.0 0.0 0.0 3.4 2.3 -1.0 0.0 0.0 0.0 3.6 -5.0 1.9 0.0 0.0 0.0 7.0 -0.9 8.0 0.0 0.0 0.0 -6.0 7.1   and   B = 2.7 6.6 -0.5 10.8 2.6 -3.2 0.6 -11.2 2.7 19.1 .

10.1 Program Text

Program Text (f07cefe.f90)

10.2 Program Data

Program Data (f07cefe.d)

10.3 Program Results

Program Results (f07cefe.r)

F07 Chapter Contents
F07 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F07CGF (DGTCON) : NAG Library, Mark 26

F07 Chapter Contents
F07 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F07CGF (DGTCON)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F07CGF (DGTCON) estimates the reciprocal condition number of a real n by n tridiagonal matrix A , using the LU factorization returned by F07CDF (DGTTRF).

2 Specification

SUBROUTINE F07CGF ( NORM, N, DL, D, DU, DU2, IPIV, ANORM, RCOND, WORK, IWORK, INFO)
INTEGER | N, IPIV(*), IWORK(N), INFO
REAL (KIND=nag_wp) | DL(*), D(*), DU(*), DU2(*), ANORM, RCOND, WORK(2*N)
CHARACTER(1) | NORM
The routine may be called by its LAPACK name dgtcon.

3 Description

F07CGF (DGTCON) should be preceded by a call to F07CDF (DGTTRF), which uses Gaussian elimination with partial pivoting and row interchanges to factorize the matrix A as
A=PLU ,
where P is a permutation matrix, L is unit lower triangular with at most one nonzero subdiagonal element in each column, and U is an upper triangular band matrix, with two superdiagonals. F07CGF (DGTCON) then utilizes the factorization to estimate either A-1 1 or A-1∞ , from which the estimate of the reciprocal of the condition number of A , 1/κ A is computed as either
1 / κ 1 A = 1 / A 1 A-1 1
or
1 / κ∞ A = 1 / A∞ A-1∞ .
1/κ A is returned, rather than κ A , since when A is singular κ A is infinite.
Note that κ∞A=κ 1 AT .

4 References

Higham N J (2002) Accuracy and Stability of Numerical Algorithms (2nd Edition) SIAM, Philadelphia

5 Arguments

1:   NORM – CHARACTER(1)Input
On entry: specifies the norm to be used to estimate κ A.
NORM='1' or 'O'
Estimate κ 1 A.
NORM='I'
Estimate κ∞A.
Constraint: NORM='1', 'O' or 'I'.
2:   N – INTEGERInput
On entry: n, the order of the matrix A.
Constraint: N≥0.
3:   DL* – REAL (KIND=nag_wp) arrayInput
Note: the dimension of the array DL must be at least max 1,N-1.
On entry: must contain the n-1 multipliers that define the matrix L of the LU factorization of A.
4:   D* – REAL (KIND=nag_wp) arrayInput
Note: the dimension of the array D must be at least max 1,N.
On entry: must contain the n diagonal elements of the upper triangular matrix U from the LU factorization of A.
5:   DU* – REAL (KIND=nag_wp) arrayInput
Note: the dimension of the array DU must be at least max 1,N-1.
On entry: must contain the n-1 elements of the first superdiagonal of U.
6:   DU2* – REAL (KIND=nag_wp) arrayInput
Note: the dimension of the array DU2 must be at least max 1,N-2.
On entry: must contain the n-2 elements of the second superdiagonal of U.
7:   IPIV* – INTEGER arrayInput
Note: the dimension of the array IPIV must be at least max 1,N.
On entry: must contain the n pivot indices that define the permutation matrix P. At the ith step, row i of the matrix was interchanged with row IPIV i, and IPIV i must always be either i or i+1, IPIV i=i indicating that a row interchange was not performed.
8:   ANORM – REAL (KIND=nag_wp)Input
On entry: if NORM='1' or 'O', the 1-norm of the original matrix A.
If NORM='I', the ∞-norm of the original matrix A.
ANORM may be computed by calling F06RNF with the same value for the argument NORM.
ANORM must be computed either before calling F07CDF (DGTTRF) or else from a copy of the original matrix A (see Section 10).
Constraint: ANORM≥0.0.
9:   RCOND – REAL (KIND=nag_wp)Output
On exit: contains an estimate of the reciprocal condition number.
10:   WORK 2×N – REAL (KIND=nag_wp) arrayWorkspace
11:   IWORK N – INTEGER arrayWorkspace
12:   INFO – INTEGEROutput
On exit: INFO=0 unless the routine detects an error (see Section 6).

6 Error Indicators and Warnings

INFO<0
If INFO=-i, argument i had an illegal value. An explanatory message is output, and execution of the program is terminated.

7 Accuracy

In practice the condition number estimator is very reliable, but it can underestimate the true condition number; see Section 15.3 of Higham (2002) for further details.

8 Parallelism and Performance

F07CGF (DGTCON) makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The condition number estimation typically requires between four and five solves and never more than eleven solves, following the factorization. The total number of floating-point operations required to perform a solve is proportional to n .
The complex analogue of this routine is F07CUF (ZGTCON).

10 Example

This example estimates the condition number in the 1-norm of the tridiagonal matrix A given by
A = 3.0 2.1 0.0 0.0 0.0 3.4 2.3 -1.0 0.0 0.0 0.0 3.6 -5.0 1.9 0.0 0.0 0.0 7.0 -0.9 8.0 0.0 0.0 0.0 -6.0 7.1 .

10.1 Program Text

Program Text (f07cgfe.f90)

10.2 Program Data

Program Data (f07cgfe.d)

10.3 Program Results

Program Results (f07cgfe.r)

F07 Chapter Contents
F07 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F07CHF (DGTRFS) : NAG Library, Mark 26

F07 Chapter Contents
F07 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F07CHF (DGTRFS)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F07CHF (DGTRFS) computes error bounds and refines the solution to a real system of linear equations AX=B or AT X=B , where A is an n by n tridiagonal matrix and X and B are n by r matrices, using the LU factorization returned by F07CDF (DGTTRF) and an initial solution returned by F07CEF (DGTTRS). Iterative refinement is used to reduce the backward error as much as possible.

2 Specification

SUBROUTINE F07CHF ( TRANS, N, NRHS, DL, D, DU, DLF, DF, DUF, DU2, IPIV, B, LDB, X, LDX, FERR, BERR, WORK, IWORK, INFO)
INTEGER | N, NRHS, IPIV(*), LDB, LDX, IWORK(N), INFO
REAL (KIND=nag_wp) | DL(*), D(*), DU(*), DLF(*), DF(*), DUF(*), DU2(*), B(LDB,*), X(LDX,*), FERR(NRHS), BERR(NRHS), WORK(3*N)
CHARACTER(1) | TRANS
The routine may be called by its LAPACK name dgtrfs.

3 Description

F07CHF (DGTRFS) should normally be preceded by calls to F07CDF (DGTTRF) and F07CEF (DGTTRS). F07CDF (DGTTRF) uses Gaussian elimination with partial pivoting and row interchanges to factorize the matrix A as
A=PLU ,
where P is a permutation matrix, L is unit lower triangular with at most one nonzero subdiagonal element in each column, and U is an upper triangular band matrix, with two superdiagonals. F07CEF (DGTTRS) then utilizes the factorization to compute a solution, X^ , to the required equations. Letting x^ denote a column of X^ , F07CHF (DGTRFS) computes a component-wise backward error, β , the smallest relative perturbation in each element of A and b such that x^ is the exact solution of a perturbed system
A+E x^=b+f , with  e ij ≤β a ij , and  fj ≤β bj .
The routine also estimates a bound for the component-wise forward error in the computed solution defined by max xi - xi^ / max xi^ , where x is the corresponding column of the exact solution, X .

4 References

Anderson E, Bai Z, Bischof C, Blackford S, Demmel J, Dongarra J J, Du Croz J J, Greenbaum A, Hammarling S, McKenney A and Sorensen D (1999) LAPACK Users' Guide (3rd Edition) SIAM, Philadelphia http://www.netlib.org/lapack/lug

5 Arguments

1:   TRANS – CHARACTER(1)Input
On entry: specifies the equations to be solved as follows:
TRANS='N'
Solve AX=B for X.
TRANS='T' or 'C'
Solve AT X=B for X.
Constraint: TRANS='N', 'T' or 'C'.
2:   N – INTEGERInput
On entry: n, the order of the matrix A.
Constraint: N≥0.
3:   NRHS – INTEGERInput
On entry: r, the number of right-hand sides, i.e., the number of columns of the matrix B.
Constraint: NRHS≥0.
4:   DL* – REAL (KIND=nag_wp) arrayInput
Note: the dimension of the array DL must be at least max 1,N-1.
On entry: must contain the n-1 subdiagonal elements of the matrix A.
5:   D* – REAL (KIND=nag_wp) arrayInput
Note: the dimension of the array D must be at least max 1,N.
On entry: must contain the n diagonal elements of the matrix A.
6:   DU* – REAL (KIND=nag_wp) arrayInput
Note: the dimension of the array DU must be at least max 1,N-1.
On entry: must contain the n-1 superdiagonal elements of the matrix A.
7:   DLF* – REAL (KIND=nag_wp) arrayInput
Note: the dimension of the array DLF must be at least max 1,N-1.
On entry: must contain the n-1 multipliers that define the matrix L of the LU factorization of A.
8:   DF* – REAL (KIND=nag_wp) arrayInput
Note: the dimension of the array DF must be at least max 1,N.
On entry: must contain the n diagonal elements of the upper triangular matrix U from the LU factorization of A.
9:   DUF* – REAL (KIND=nag_wp) arrayInput
Note: the dimension of the array DUF must be at least max 1,N-1.
On entry: must contain the n-1 elements of the first superdiagonal of U.
10:   DU2* – REAL (KIND=nag_wp) arrayInput
Note: the dimension of the array DU2 must be at least max 1,N-2.
On entry: must contain the n-2 elements of the second superdiagonal of U.
11:   IPIV* – INTEGER arrayInput
Note: the dimension of the array IPIV must be at least max 1,N.
On entry: must contain the n pivot indices that define the permutation matrix P. At the ith step, row i of the matrix was interchanged with row IPIV i, and IPIV i must always be either i or i+1, IPIV i=i indicating that a row interchange was not performed.
12:   B LDB* – REAL (KIND=nag_wp) arrayInput
Note: the second dimension of the array B must be at least max 1,NRHS.
On entry: the n by r matrix of right-hand sides B.
13:   LDB – INTEGERInput
On entry: the first dimension of the array B as declared in the (sub)program from which F07CHF (DGTRFS) is called.
Constraint: LDB≥max 1,N.
14:   X LDX* – REAL (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array X must be at least max 1,NRHS.
On entry: the n by r initial solution matrix X.
On exit: the n by r refined solution matrix X.
15:   LDX – INTEGERInput
On entry: the first dimension of the array X as declared in the (sub)program from which F07CHF (DGTRFS) is called.
Constraint: LDX≥max 1,N.
16:   FERR NRHS – REAL (KIND=nag_wp) arrayOutput
On exit: estimate of the forward error bound for each computed solution vector, such that x^j-xj∞/x^j∞≤FERR j, where x^j is the jth column of the computed solution returned in the array X and xj is the corresponding column of the exact solution X. The estimate is almost always a slight overestimate of the true error.
17:   BERR NRHS – REAL (KIND=nag_wp) arrayOutput
On exit: estimate of the component-wise relative backward error of each computed solution vector x^j (i.e., the smallest relative change in any element of A or B that makes x^j an exact solution).
18:   WORK 3×N – REAL (KIND=nag_wp) arrayWorkspace
19:   IWORK N – INTEGER arrayWorkspace
20:   INFO – INTEGEROutput
On exit: INFO=0 unless the routine detects an error (see Section 6).

6 Error Indicators and Warnings

INFO<0
If INFO=-i, argument i had an illegal value. An explanatory message is output, and execution of the program is terminated.

7 Accuracy

The computed solution for a single right-hand side, x^ , satisfies an equation of the form
A+E x^=b ,
where
E∞=O ε A∞
and ε is the machine precision. An approximate error bound for the computed solution is given by
x^-x ∞ x∞ ≤ κ A E∞ A∞ ,
where κ A=A-1∞ A∞ , the condition number of A with respect to the solution of the linear equations. See Section 4.4 of Anderson et al. (1999) for further details.
Routine F07CGF (DGTCON) can be used to estimate the condition number of A .

8 Parallelism and Performance

F07CHF (DGTRFS) is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
F07CHF (DGTRFS) makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The total number of floating-point operations required to solve the equations AX=B or AT X=B is proportional to nr . At most five steps of iterative refinement are performed, but usually only one or two steps are required.
The complex analogue of this routine is F07CVF (ZGTRFS).

10 Example

This example solves the equations
AX=B ,
where A is the tridiagonal matrix
A = 3.0 2.1 0.0 0.0 0.0 3.4 2.3 -1.0 0.0 0.0 0.0 3.6 -5.0 1.9 0.0 0.0 0.0 7.0 -0.9 8.0 0.0 0.0 0.0 -6.0 7.1   and   B = 2.7 6.6 -0.5 10.8 2.6 -3.2 0.6 -11.2 2.7 19.1 .
Estimates for the backward errors and forward errors are also output.

10.1 Program Text

Program Text (f07chfe.f90)

10.2 Program Data

Program Data (f07chfe.d)

10.3 Program Results

Program Results (f07chfe.r)

F07 Chapter Contents
F07 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F07CNF (ZGTSV) : NAG Library, Mark 26

F07 Chapter Contents
F07 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F07CNF (ZGTSV)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F07CNF (ZGTSV) computes the solution to a complex system of linear equations
AX=B ,
where A is an n by n tridiagonal matrix and X and B are n by r matrices.

2 Specification

SUBROUTINE F07CNF ( N, NRHS, DL, D, DU, B, LDB, INFO)
INTEGER | N, NRHS, LDB, INFO
COMPLEX (KIND=nag_wp) | DL(*), D(*), DU(*), B(LDB,*)
The routine may be called by its LAPACK name zgtsv.

3 Description

F07CNF (ZGTSV) uses Gaussian elimination with partial pivoting and row interchanges to solve the equations AX=B . The matrix A is factorized as A=PLU , where P is a permutation matrix, L is unit lower triangular with at most one nonzero subdiagonal element per column, and U is an upper triangular band matrix, with two superdiagonals.
Note that the equations AT X=B may be solved by interchanging the order of the arguments DU and DL.

4 References

Anderson E, Bai Z, Bischof C, Blackford S, Demmel J, Dongarra J J, Du Croz J J, Greenbaum A, Hammarling S, McKenney A and Sorensen D (1999) LAPACK Users' Guide (3rd Edition) SIAM, Philadelphia http://www.netlib.org/lapack/lug

5 Arguments

1:   N – INTEGERInput
On entry: n, the number of linear equations, i.e., the order of the matrix A.
Constraint: N≥0.
2:   NRHS – INTEGERInput
On entry: r, the number of right-hand sides, i.e., the number of columns of the matrix B.
Constraint: NRHS≥0.
3:   DL* – COMPLEX (KIND=nag_wp) arrayInput/Output
Note: the dimension of the array DL must be at least max 1,N-1.
On entry: must contain the n-1 subdiagonal elements of the matrix A.
On exit: if no constraints are violated, DL is overwritten by the (n-2) elements of the second superdiagonal of the upper triangular matrix U from the LU factorization of A, in DL 1,DL 2,…,DL n-2.
4:   D* – COMPLEX (KIND=nag_wp) arrayInput/Output
Note: the dimension of the array D must be at least max 1,N.
On entry: must contain the n diagonal elements of the matrix A.
On exit: if no constraints are violated, D is overwritten by the n diagonal elements of the upper triangular matrix U from the LU factorization of A.
5:   DU* – COMPLEX (KIND=nag_wp) arrayInput/Output
Note: the dimension of the array DU must be at least max 1,N-1.
On entry: must contain the n-1 superdiagonal elements of the matrix A.
On exit: if no constraints are violated, DU is overwritten by the n-1 elements of the first superdiagonal of U.
6:   B LDB* – COMPLEX (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array B must be at least max 1,NRHS.
To solve the equations Ax=b, where b is a single right-hand side, B may be supplied as a one-dimensional array with length LDB=max 1,N.
On entry: the n by r right-hand side matrix B.
On exit: if INFO=0, the n by r solution matrix X.
7:   LDB – INTEGERInput
On entry: the first dimension of the array B as declared in the (sub)program from which F07CNF (ZGTSV) is called.
Constraint: LDB≥max 1,N.
8:   INFO – INTEGEROutput
On exit: INFO=0 unless the routine detects an error (see Section 6).

6 Error Indicators and Warnings

INFO<0
If INFO=-i, argument i had an illegal value. An explanatory message is output, and execution of the program is terminated.
INFO>0
Element value of the diagonal is exactly zero, and the solution has not been computed. The factorization has not been completed unless N=value.

7 Accuracy

The computed solution for a single right-hand side, x^ , satisfies an equation of the form
A+E x^ = b ,
where
E 1 = O ε A 1
and ε is the machine precision. An approximate error bound for the computed solution is given by
x^-x 1 x 1 ≤ κ A E 1 A 1 ,
where κ A = A-1 1 A 1 , the condition number of A with respect to the solution of the linear equations. See Section 4.4 of Anderson et al. (1999) for further details.
Alternatives to F07CNF (ZGTSV), which return condition and error estimates are F04CCF and F07CPF (ZGTSVX).

8 Parallelism and Performance

F07CNF (ZGTSV) is not threaded in any implementation.

9 Further Comments

The total number of floating-point operations required to solve the equations AX=B is proportional to nr .
The real analogue of this routine is F07CAF (DGTSV).

10 Example

This example solves the equations
Ax=b ,
where A is the tridiagonal matrix
A = -1.3+1.3 i 2.0-1.0 i 0.0i+0.0 0.0i+0.0 0.0i+0.0 1.0-2.0 i -1.3+1.3 i 2.0+1.0 i 0.0i+0.0 0.0i+0.0 0.0i+0.0 1.0+1.0 i -1.3+3.3 i -1.0+1.0 i 0.0i+0.0 0.0i+0.0 0.0i+0.0 2.0-3.0 i -0.3+4.3 i 1.0-1.0 i 0.0i+0.0 0.0i+0.0 0.0i+0.0 1.0+1.0 i -3.3+1.3 i
and
b = 2.4-0 5.0 i 3.4+18.2 i -14.7+0 9.7 i 31.9-0 7.7 i -1.0+0 1.6 i .

10.1 Program Text

Program Text (f07cnfe.f90)

10.2 Program Data

Program Data (f07cnfe.d)

10.3 Program Results

Program Results (f07cnfe.r)

F07 Chapter Contents
F07 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F07 Chapter Contents : NAG Library Manual, Mark 26

F07 Chapter Introduction
NAG Library Manual

NAG Library Chapter Contents

F07 – Linear Equations (LAPACK)

F07 Chapter Introduction – a description of the Chapter and an overview of the algorithms available

Routine Name | Mark of Introduction | Purpose
F07AAF (DGESV) Example Text Example Data | 21 | DGESV nagf_lapack_dgesv Computes the solution to a real system of linear equations
F07ABF (DGESVX) Example Text Example Data | 21 | DGESVX nagf_lapack_dgesvx Uses the LU factorization to compute the solution, error-bound and condition estimate for a real system of linear equations
F07ACF (DSGESV) Example Text Example Data | 22 | DSGESV nagf_lapack_dsgesv Computes the solution to a real system of linear equations using mixed precision arithmetic
F07ADF (DGETRF) Example Text Example Data | 15 | DGETRF nagf_lapack_dgetrf LU factorization of real m by n matrix
F07AEF (DGETRS) Example Text Example Data | 15 | DGETRS nagf_lapack_dgetrs Solution of real system of linear equations, multiple right-hand sides, matrix already factorized by F07ADF (DGETRF)
F07AFF (DGEEQU) Example Text Example Data | 21 | DGEEQU nagf_lapack_dgeequ Computes row and column scalings intended to equilibrate a general real matrix and reduce its condition number
F07AGF (DGECON) Example Text Example Data | 15 | DGECON nagf_lapack_dgecon Estimate condition number of real matrix, matrix already factorized by F07ADF (DGETRF)
F07AHF (DGERFS) Example Text Example Data | 15 | DGERFS nagf_lapack_dgerfs Refined solution with error bounds of real system of linear equations, multiple right-hand sides
F07AJF (DGETRI) Example Text Example Data | 15 | DGETRI nagf_lapack_dgetri Inverse of real matrix, matrix already factorized by F07ADF (DGETRF)
F07ANF (ZGESV) Example Text Example Data | 21 | ZGESV nagf_lapack_zgesv Computes the solution to a complex system of linear equations
F07APF (ZGESVX) Example Text Example Data | 21 | ZGESVX nagf_lapack_zgesvx Uses the LU factorization to compute the solution, error-bound and condition estimate for a complex system of linear equations
F07AQF (ZCGESV) Example Text Example Data | 22 | ZCGESV nagf_lapack_zcgesv Computes the solution to a complex system of linear equations using mixed precision arithmetic
F07ARF (ZGETRF) Example Text Example Data | 15 | ZGETRF nagf_lapack_zgetrf LU factorization of complex m by n matrix
F07ASF (ZGETRS) Example Text Example Data | 15 | ZGETRS nagf_lapack_zgetrs Solution of complex system of linear equations, multiple right-hand sides, matrix already factorized by F07ARF (ZGETRF)
F07ATF (ZGEEQU) Example Text Example Data | 21 | ZGEEQU nagf_lapack_zgeequ Computes row and column scalings intended to equilibrate a general complex matrix and reduce its condition number
F07AUF (ZGECON) Example Text Example Data | 15 | ZGECON nagf_lapack_zgecon Estimate condition number of complex matrix, matrix already factorized by F07ARF (ZGETRF)
F07AVF (ZGERFS) Example Text Example Data | 15 | ZGERFS nagf_lapack_zgerfs Refined solution with error bounds of complex system of linear equations, multiple right-hand sides
F07AWF (ZGETRI) Example Text Example Data | 15 | ZGETRI nagf_lapack_zgetri Inverse of complex matrix, matrix already factorized by F07ARF (ZGETRF)
F07BAF (DGBSV) Example Text Example Data | 21 | DGBSV nagf_lapack_dgbsv Computes the solution to a real banded system of linear equations
F07BBF (DGBSVX) Example Text Example Data | 21 | DGBSVX nagf_lapack_dgbsvx Uses the LU factorization to compute the solution, error-bound and condition estimate for a real banded system of linear equations
F07BDF (DGBTRF) Example Text Example Data | 15 | DGBTRF nagf_lapack_dgbtrf LU factorization of real m by n band matrix
F07BEF (DGBTRS) Example Text Example Data | 15 | DGBTRS nagf_lapack_dgbtrs Solution of real band system of linear equations, multiple right-hand sides, matrix already factorized by F07BDF (DGBTRF)
F07BFF (DGBEQU) Example Text Example Data | 21 | DGBEQU nagf_lapack_dgbequ Computes row and column scalings intended to equilibrate a real banded matrix and reduce its condition number
F07BGF (DGBCON) Example Text Example Data | 15 | DGBCON nagf_lapack_dgbcon Estimate condition number of real band matrix, matrix already factorized by F07BDF (DGBTRF)
F07BHF (DGBRFS) Example Text Example Data | 15 | DGBRFS nagf_lapack_dgbrfs Refined solution with error bounds of real band system of linear equations, multiple right-hand sides
F07BNF (ZGBSV) Example Text Example Data | 21 | ZGBSV nagf_lapack_zgbsv Computes the solution to a complex banded system of linear equations
F07BPF (ZGBSVX) Example Text Example Data | 21 | ZGBSVX nagf_lapack_zgbsvx Uses the LU factorization to compute the solution, error-bound and condition estimate for a complex banded system of linear equations
F07BRF (ZGBTRF) Example Text Example Data | 15 | ZGBTRF nagf_lapack_zgbtrf LU factorization of complex m by n band matrix
F07BSF (ZGBTRS) Example Text Example Data | 15 | ZGBTRS nagf_lapack_zgbtrs Solution of complex band system of linear equations, multiple right-hand sides, matrix already factorized by F07BRF (ZGBTRF)
F07BTF (ZGBEQU) Example Text Example Data | 21 | ZGBEQU nagf_lapack_zgbequ Computes row and column scalings intended to equilibrate a complex banded matrix and reduce its condition number
F07BUF (ZGBCON) Example Text Example Data | 15 | ZGBCON nagf_lapack_zgbcon Estimate condition number of complex band matrix, matrix already factorized by F07BRF (ZGBTRF)
F07BVF (ZGBRFS) Example Text Example Data | 15 | ZGBRFS nagf_lapack_zgbrfs Refined solution with error bounds of complex band system of linear equations, multiple right-hand sides
F07CAF (DGTSV) Example Text Example Data | 21 | DGTSV nagf_lapack_dgtsv Computes the solution to a real tridiagonal system of linear equations
F07CBF (DGTSVX) Example Text Example Data | 21 | DGTSVX nagf_lapack_dgtsvx Uses the LU factorization to compute the solution, error-bound and condition estimate for a real tridiagonal system of linear equations
F07CDF (DGTTRF) Example Text Example Data | 21 | DGTTRF nagf_lapack_dgttrf LU factorization of real tridiagonal matrix
F07CEF (DGTTRS) Example Text Example Data | 21 | DGTTRS nagf_lapack_dgttrs Solves a real tridiagonal system of linear equations using the LU factorization computed by F07CDF (DGTTRF)
F07CGF (DGTCON) Example Text Example Data | 21 | DGTCON nagf_lapack_dgtcon Estimates the reciprocal of the condition number of a real tridiagonal matrix using the LU factorization computed by F07CDF (DGTTRF)
F07CHF (DGTRFS) Example Text Example Data | 21 | DGTRFS nagf_lapack_dgtrfs Refined solution with error bounds of real tridiagonal system of linear equations, multiple right-hand sides
F07CNF (ZGTSV) Example Text Example Data | 21 | ZGTSV nagf_lapack_zgtsv Computes the solution to a complex tridiagonal system of linear equations
F07CPF (ZGTSVX) Example Text Example Data | 21 | ZGTSVX nagf_lapack_zgtsvx Uses the LU factorization to compute the solution, error-bound and condition estimate for a complex tridiagonal system of linear equations
F07CRF (ZGTTRF) Example Text Example Data | 21 | ZGTTRF nagf_lapack_zgttrf LU factorization of complex tridiagonal matrix
F07CSF (ZGTTRS) Example Text Example Data | 21 | ZGTTRS nagf_lapack_zgttrs Solves a complex tridiagonal system of linear equations using the LU factorization computed by F07CDF (DGTTRF)
F07CUF (ZGTCON) Example Text Example Data | 21 | ZGTCON nagf_lapack_zgtcon Estimates the reciprocal of the condition number of a complex tridiagonal matrix using the LU factorization computed by F07CDF (DGTTRF)
F07CVF (ZGTRFS) Example Text Example Data | 21 | ZGTRFS nagf_lapack_zgtrfs Refined solution with error bounds of complex tridiagonal system of linear equations, multiple right-hand sides
F07FAF (DPOSV) Example Text Example Data | 21 | DPOSV nagf_lapack_dposv Computes the solution to a real symmetric positive definite system of linear equations
F07FBF (DPOSVX) Example Text Example Data | 21 | DPOSVX nagf_lapack_dposvx Uses the Cholesky factorization to compute the solution, error-bound and condition estimate for a real symmetric positive definite system of linear equations
F07FCF (DSPOSV) Example Text Example Data | 23 | DSPOSV nagf_lapack_dsposv Computes the solution to a real symmetric positive definite system of linear equations using mixed precision arithmetic
F07FDF (DPOTRF) Example Text Example Data | 15 | DPOTRF nagf_lapack_dpotrf Cholesky factorization of real symmetric positive definite matrix
F07FEF (DPOTRS) Example Text Example Data | 15 | DPOTRS nagf_lapack_dpotrs Solution of real symmetric positive definite system of linear equations, multiple right-hand sides, matrix already factorized by F07FDF (DPOTRF)
F07FFF (DPOEQU) Example Text Example Data | 21 | DPOEQU nagf_lapack_dpoequ Computes row and column scalings intended to equilibrate a real symmetric positive definite matrix and reduce its condition number
F07FGF (DPOCON) Example Text Example Data | 15 | DPOCON nagf_lapack_dpocon Estimate condition number of real symmetric positive definite matrix, matrix already factorized by F07FDF (DPOTRF)
F07FHF (DPORFS) Example Text Example Data | 15 | DPORFS nagf_lapack_dporfs Refined solution with error bounds of real symmetric positive definite system of linear equations, multiple right-hand sides
F07FJF (DPOTRI) Example Text Example Data | 15 | DPOTRI nagf_lapack_dpotri Inverse of real symmetric positive definite matrix, matrix already factorized by F07FDF (DPOTRF)
F07FNF (ZPOSV) Example Text Example Data | 21 | ZPOSV nagf_lapack_zposv Computes the solution to a complex Hermitian positive definite system of linear equations
F07FPF (ZPOSVX) Example Text Example Data | 21 | ZPOSVX nagf_lapack_zposvx Uses the Cholesky factorization to compute the solution, error-bound and condition estimate for a complex Hermitian positive definite system of linear equations
F07FQF (ZCPOSV) Example Text Example Data | 23 | ZCPOSV nagf_lapack_zcposv Computes the solution to a complex Hermitian positive definite system of linear equations using mixed precision arithmetic
F07FRF (ZPOTRF) Example Text Example Data | 15 | ZPOTRF nagf_lapack_zpotrf Cholesky factorization of complex Hermitian positive definite matrix
F07FSF (ZPOTRS) Example Text Example Data | 15 | ZPOTRS nagf_lapack_zpotrs Solution of complex Hermitian positive definite system of linear equations, multiple right-hand sides, matrix already factorized by F07FRF (ZPOTRF)
F07FTF (ZPOEQU) Example Text Example Data | 21 | ZPOEQU nagf_lapack_zpoequ Computes row and column scalings intended to equilibrate a complex Hermitian positive definite matrix and reduce its condition number
F07FUF (ZPOCON) Example Text Example Data | 15 | ZPOCON nagf_lapack_zpocon Estimate condition number of complex Hermitian positive definite matrix, matrix already factorized by F07FRF (ZPOTRF)
F07FVF (ZPORFS) Example Text Example Data | 15 | ZPORFS nagf_lapack_zporfs Refined solution with error bounds of complex Hermitian positive definite system of linear equations, multiple right-hand sides
F07FWF (ZPOTRI) Example Text Example Data | 15 | ZPOTRI nagf_lapack_zpotri Inverse of complex Hermitian positive definite matrix, matrix already factorized by F07FRF (ZPOTRF)
F07GAF (DPPSV) Example Text Example Data | 21 | DPPSV nagf_lapack_dppsv Computes the solution to a real symmetric positive definite system of linear equations, packed storage
F07GBF (DPPSVX) Example Text Example Data | 21 | DPPSVX nagf_lapack_dppsvx Uses the Cholesky factorization to compute the solution, error-bound and condition estimate for a real symmetric positive definite system of linear equations, packed storage
F07GDF (DPPTRF) Example Text Example Data | 15 | DPPTRF nagf_lapack_dpptrf Cholesky factorization of real symmetric positive definite matrix, packed storage
F07GEF (DPPTRS) Example Text Example Data | 15 | DPPTRS nagf_lapack_dpptrs Solution of real symmetric positive definite system of linear equations, multiple right-hand sides, matrix already factorized by F07GDF (DPPTRF), packed storage
F07GFF (DPPEQU) Example Text Example Data | 21 | DPPEQU nagf_lapack_dppequ Computes row and column scalings intended to equilibrate a real symmetric positive definite matrix and reduce its condition number, packed storage
F07GGF (DPPCON) Example Text Example Data | 15 | DPPCON nagf_lapack_dppcon Estimate condition number of real symmetric positive definite matrix, matrix already factorized by F07GDF (DPPTRF), packed storage
F07GHF (DPPRFS) Example Text Example Data | 15 | DPPRFS nagf_lapack_dpprfs Refined solution with error bounds of real symmetric positive definite system of linear equations, multiple right-hand sides, packed storage
F07GJF (DPPTRI) Example Text Example Data | 15 | DPPTRI nagf_lapack_dpptri Inverse of real symmetric positive definite matrix, matrix already factorized by F07GDF (DPPTRF), packed storage
F07GNF (ZPPSV) Example Text Example Data | 21 | ZPPSV nagf_lapack_zppsv Computes the solution to a complex Hermitian positive definite system of linear equations, packed storage
F07GPF (ZPPSVX) Example Text Example Data | 21 | ZPPSVX nagf_lapack_zppsvx Uses the Cholesky factorization to compute the solution, error-bound and condition estimate for a complex Hermitian positive definite system of linear equations, packed storage
F07GRF (ZPPTRF) Example Text Example Data | 15 | ZPPTRF nagf_lapack_zpptrf Cholesky factorization of complex Hermitian positive definite matrix, packed storage
F07GSF (ZPPTRS) Example Text Example Data | 15 | ZPPTRS nagf_lapack_zpptrs Solution of complex Hermitian positive definite system of linear equations, multiple right-hand sides, matrix already factorized by F07GRF (ZPPTRF), packed storage
F07GTF (ZPPEQU) Example Text Example Data | 21 | ZPPEQU nagf_lapack_zppequ Computes row and column scalings intended to equilibrate a complex Hermitian positive definite matrix and reduce its condition number, packed storage
F07GUF (ZPPCON) Example Text Example Data | 15 | ZPPCON nagf_lapack_zppcon Estimate condition number of complex Hermitian positive definite matrix, matrix already factorized by F07GRF (ZPPTRF), packed storage
F07GVF (ZPPRFS) Example Text Example Data | 15 | ZPPRFS nagf_lapack_zpprfs Refined solution with error bounds of complex Hermitian positive definite system of linear equations, multiple right-hand sides, packed storage
F07GWF (ZPPTRI) Example Text Example Data | 15 | ZPPTRI nagf_lapack_zpptri Inverse of complex Hermitian positive definite matrix, matrix already factorized by F07GRF (ZPPTRF), packed storage
F07HAF (DPBSV) Example Text Example Data | 21 | DPBSV nagf_lapack_dpbsv Computes the solution to a real symmetric positive definite banded system of linear equations
F07HBF (DPBSVX) Example Text Example Data | 21 | DPBSVX nagf_lapack_dpbsvx Uses the Cholesky factorization to compute the solution, error-bound and condition estimate for a real symmetric positive definite banded system of linear equations
F07HDF (DPBTRF) Example Text Example Data | 15 | DPBTRF nagf_lapack_dpbtrf Cholesky factorization of real symmetric positive definite band matrix
F07HEF (DPBTRS) Example Text Example Data | 15 | DPBTRS nagf_lapack_dpbtrs Solution of real symmetric positive definite band system of linear equations, multiple right-hand sides, matrix already factorized by F07HDF (DPBTRF)
F07HFF (DPBEQU) Example Text Example Data | 21 | DPBEQU nagf_lapack_dpbequ Computes row and column scalings intended to equilibrate a real symmetric positive definite banded matrix and reduce its condition number
F07HGF (DPBCON) Example Text Example Data | 15 | DPBCON nagf_lapack_dpbcon Estimate condition number of real symmetric positive definite band matrix, matrix already factorized by F07HDF (DPBTRF)
F07HHF (DPBRFS) Example Text Example Data | 15 | DPBRFS nagf_lapack_dpbrfs Refined solution with error bounds of real symmetric positive definite band system of linear equations, multiple right-hand sides
F07HNF (ZPBSV) Example Text Example Data | 21 | ZPBSV nagf_lapack_zpbsv Computes the solution to a complex Hermitian positive definite banded system of linear equations
F07HPF (ZPBSVX) Example Text Example Data | 21 | ZPBSVX nagf_lapack_zpbsvx Uses the Cholesky factorization to compute the solution, error-bound and condition estimate for a complex Hermitian positive definite banded system of linear equations
F07HRF (ZPBTRF) Example Text Example Data | 15 | ZPBTRF nagf_lapack_zpbtrf Cholesky factorization of complex Hermitian positive definite band matrix
F07HSF (ZPBTRS) Example Text Example Data | 15 | ZPBTRS nagf_lapack_zpbtrs Solution of complex Hermitian positive definite band system of linear equations, multiple right-hand sides, matrix already factorized by F07HRF (ZPBTRF)
F07HTF (ZPBEQU) Example Text Example Data | 21 | ZPBEQU nagf_lapack_zpbequ Computes row and column scalings intended to equilibrate a complex Hermitian positive definite banded matrix and reduce its condition number
F07HUF (ZPBCON) Example Text Example Data | 15 | ZPBCON nagf_lapack_zpbcon Estimate condition number of complex Hermitian positive definite band matrix, matrix already factorized by F07HRF (ZPBTRF)
F07HVF (ZPBRFS) Example Text Example Data | 15 | ZPBRFS nagf_lapack_zpbrfs Refined solution with error bounds of complex Hermitian positive definite band system of linear equations, multiple right-hand sides
F07JAF (DPTSV) Example Text Example Data | 21 | DPTSV nagf_lapack_dptsv Computes the solution to a real symmetric positive definite tridiagonal system of linear equations
F07JBF (DPTSVX) Example Text Example Data | 21 | DPTSVX nagf_lapack_dptsvx Uses the LDLT factorization to compute the solution, error-bound and condition estimate for a real symmetric positive definite tridiagonal system of linear equations
F07JDF (DPTTRF) Example Text Example Data | 21 | DPTTRF nagf_lapack_dpttrf Computes the LDLT factorization of a real symmetric positive definite tridiagonal matrix
F07JEF (DPTTRS) Example Text Example Data | 21 | DPTTRS nagf_lapack_dpttrs Solves a real symmetric positive definite tridiagonal system using the LDLT factorization computed by F07JDF (DPTTRF)
F07JGF (DPTCON) Example Text Example Data | 21 | DPTCON nagf_lapack_dptcon Computes the reciprocal of the condition number of a real symmetric positive definite tridiagonal system using the LDLT factorization computed by F07JDF (DPTTRF)
F07JHF (DPTRFS) Example Text Example Data | 21 | DPTRFS nagf_lapack_dptrfs Refined solution with error bounds of real symmetric positive definite tridiagonal system of linear equations, multiple right-hand sides
F07JNF (ZPTSV) Example Text Example Data | 21 | ZPTSV nagf_lapack_zptsv Computes the solution to a complex Hermitian positive definite tridiagonal system of linear equations
F07JPF (ZPTSVX) Example Text Example Data | 21 | ZPTSVX nagf_lapack_zptsvx Uses the LDLT factorization to compute the solution, error-bound and condition estimate for a complex Hermitian positive definite tridiagonal system of linear equations
F07JRF (ZPTTRF) Example Text Example Data | 21 | ZPTTRF nagf_lapack_zpttrf Computes the LDLH factorization of a complex Hermitian positive definite tridiagonal matrix
F07JSF (ZPTTRS) Example Text Example Data | 21 | ZPTTRS nagf_lapack_zpttrs Solves a complex Hermitian positive definite tridiagonal system using the LDLH factorization computed by F07JRF (ZPTTRF)
F07JUF (ZPTCON) Example Text Example Data | 21 | ZPTCON nagf_lapack_zptcon Computes the reciprocal of the condition number of a complex Hermitian positive definite tridiagonal system using the LDLH factorization computed by F07JRF (ZPTTRF)
F07JVF (ZPTRFS) Example Text Example Data | 21 | ZPTRFS nagf_lapack_zptrfs Refined solution with error bounds of complex Hermitian positive definite tridiagonal system of linear equations, multiple right-hand sides
F07KDF (DPSTRF) Example Text Example Data | 23 | DPSTRF nagf_lapack_dpstrf Cholesky factorization, with complete pivoting, of a real, symmetric, positive semidefinite matrix
F07KRF (ZPSTRF) Example Text Example Data | 23 | ZPSTRF nagf_lapack_zpstrf Cholesky factorization of complex Hermitian positive semidefinite matrix
F07MAF (DSYSV) Example Text Example Data | 21 | DSYSV nagf_lapack_dsysv Computes the solution to a real symmetric system of linear equations
F07MBF (DSYSVX) Example Text Example Data | 21 | DSYSVX nagf_lapack_dsysvx Uses the diagonal pivoting factorization to compute the solution to a real symmetric system of linear equations
F07MDF (DSYTRF) Example Text Example Data | 15 | DSYTRF nagf_lapack_dsytrf Bunch–Kaufman factorization of real symmetric indefinite matrix
F07MEF (DSYTRS) Example Text Example Data | 15 | DSYTRS nagf_lapack_dsytrs Solution of real symmetric indefinite system of linear equations, multiple right-hand sides, matrix already factorized by F07MDF (DSYTRF)
F07MGF (DSYCON) Example Text Example Data | 15 | DSYCON nagf_lapack_dsycon Estimate condition number of real symmetric indefinite matrix, matrix already factorized by F07MDF (DSYTRF)
F07MHF (DSYRFS) Example Text Example Data | 15 | DSYRFS nagf_lapack_dsyrfs Refined solution with error bounds of real symmetric indefinite system of linear equations, multiple right-hand sides
F07MJF (DSYTRI) Example Text Example Data | 15 | DSYTRI nagf_lapack_dsytri Inverse of real symmetric indefinite matrix, matrix already factorized by F07MDF (DSYTRF)
F07MNF (ZHESV) Example Text Example Data | 21 | ZHESV nagf_lapack_zhesv Computes the solution to a complex Hermitian system of linear equations
F07MPF (ZHESVX) Example Text Example Data | 21 | ZHESVX nagf_lapack_zhesvx Uses the diagonal pivoting factorization to compute the solution to a complex Hermitian system of linear equations
F07MRF (ZHETRF) Example Text Example Data | 15 | ZHETRF nagf_lapack_zhetrf Bunch–Kaufman factorization of complex Hermitian indefinite matrix
F07MSF (ZHETRS) Example Text Example Data | 15 | ZHETRS nagf_lapack_zhetrs Solution of complex Hermitian indefinite system of linear equations, multiple right-hand sides, matrix already factorized by F07MRF (ZHETRF)
F07MUF (ZHECON) Example Text Example Data | 15 | ZHECON nagf_lapack_zhecon Estimate condition number of complex Hermitian indefinite matrix, matrix already factorized by F07MRF (ZHETRF)
F07MVF (ZHERFS) Example Text Example Data | 15 | ZHERFS nagf_lapack_zherfs Refined solution with error bounds of complex Hermitian indefinite system of linear equations, multiple right-hand sides
F07MWF (ZHETRI) Example Text Example Data | 15 | ZHETRI nagf_lapack_zhetri Inverse of complex Hermitian indefinite matrix, matrix already factorized by F07MRF (ZHETRF)
F07NNF (ZSYSV) Example Text Example Data | 21 | ZSYSV nagf_lapack_zsysv Computes the solution to a complex symmetric system of linear equations
F07NPF (ZSYSVX) Example Text Example Data | 21 | ZSYSVX nagf_lapack_zsysvx Uses the diagonal pivoting factorization to compute the solution to a complex symmetric system of linear equations
F07NRF (ZSYTRF) Example Text Example Data | 15 | ZSYTRF nagf_lapack_zsytrf Bunch–Kaufman factorization of complex symmetric matrix
F07NSF (ZSYTRS) Example Text Example Data | 15 | ZSYTRS nagf_lapack_zsytrs Solution of complex symmetric system of linear equations, multiple right-hand sides, matrix already factorized by F07NRF (ZSYTRF)
F07NUF (ZSYCON) Example Text Example Data | 15 | ZSYCON nagf_lapack_zsycon Estimate condition number of complex symmetric matrix, matrix already factorized by F07NRF (ZSYTRF)
F07NVF (ZSYRFS) Example Text Example Data | 15 | ZSYRFS nagf_lapack_zsyrfs Refined solution with error bounds of complex symmetric system of linear equations, multiple right-hand sides
F07NWF (ZSYTRI) Example Text Example Data | 15 | ZSYTRI nagf_lapack_zsytri Inverse of complex symmetric matrix, matrix already factorized by F07NRF (ZSYTRF)
F07PAF (DSPSV) Example Text Example Data | 21 | DSPSV nagf_lapack_dspsv Computes the solution to a real symmetric system of linear equations, packed storage
F07PBF (DSPSVX) Example Text Example Data | 21 | DSPSVX nagf_lapack_dspsvx Uses the diagonal pivoting factorization to compute the solution to a real symmetric system of linear equations, packed storage. Error bounds and a condition estimate are also computed.
F07PDF (DSPTRF) Example Text Example Data | 15 | DSPTRF nagf_lapack_dsptrf Bunch–Kaufman factorization of real symmetric indefinite matrix, packed storage
F07PEF (DSPTRS) Example Text Example Data | 15 | DSPTRS nagf_lapack_dsptrs Solution of real symmetric indefinite system of linear equations, multiple right-hand sides, matrix already factorized by F07PDF (DSPTRF), packed storage
F07PGF (DSPCON) Example Text Example Data | 15 | DSPCON nagf_lapack_dspcon Estimate condition number of real symmetric indefinite matrix, matrix already factorized by F07PDF (DSPTRF), packed storage
F07PHF (DSPRFS) Example Text Example Data | 15 | DSPRFS nagf_lapack_dsprfs Refined solution with error bounds of real symmetric indefinite system of linear equations, multiple right-hand sides, packed storage
F07PJF (DSPTRI) Example Text Example Data | 15 | DSPTRI nagf_lapack_dsptri Inverse of real symmetric indefinite matrix, matrix already factorized by F07PDF (DSPTRF), packed storage
F07PNF (ZHPSV) Example Text Example Data | 21 | ZHPSV nagf_lapack_zhpsv Computes the solution to a complex Hermitian system of linear equations, packed storage
F07PPF (ZHPSVX) Example Text Example Data | 21 | ZHPSVX nagf_lapack_zhpsvx Uses the diagonal pivoting factorization to compute the solution to a complex, Hermitian, system of linear equations, error bounds and condition estimates. Packed storage
F07PRF (ZHPTRF) Example Text Example Data | 15 | ZHPTRF nagf_lapack_zhptrf Bunch–Kaufman factorization of complex Hermitian indefinite matrix, packed storage
F07PSF (ZHPTRS) Example Text Example Data | 15 | ZHPTRS nagf_lapack_zhptrs Solution of complex Hermitian indefinite system of linear equations, multiple right-hand sides, matrix already factorized by F07PRF (ZHPTRF), packed storage
F07PUF (ZHPCON) Example Text Example Data | 15 | ZHPCON nagf_lapack_zhpcon Estimate condition number of complex Hermitian indefinite matrix, matrix already factorized by F07PRF (ZHPTRF), packed storage
F07PVF (ZHPRFS) Example Text Example Data | 15 | ZHPRFS nagf_lapack_zhprfs Refined solution with error bounds of complex Hermitian indefinite system of linear equations, multiple right-hand sides, packed storage
F07PWF (ZHPTRI) Example Text Example Data | 15 | ZHPTRI nagf_lapack_zhptri Inverse of complex Hermitian indefinite matrix, matrix already factorized by F07PRF (ZHPTRF), packed storage
F07QNF (ZSPSV) Example Text Example Data | 21 | ZSPSV nagf_lapack_zspsv Computes the solution to a complex symmetric system of linear equations, packed storage
F07QPF (ZSPSVX) Example Text Example Data | 21 | ZSPSVX nagf_lapack_zspsvx Uses the diagonal pivoting factorization to compute the solution to a complex, symmetric, system of linear equations, error bounds and condition estimates. Packed storage
F07QRF (ZSPTRF) Example Text Example Data | 15 | ZSPTRF nagf_lapack_zsptrf Bunch–Kaufman factorization of complex symmetric matrix, packed storage
F07QSF (ZSPTRS) Example Text Example Data | 15 | ZSPTRS nagf_lapack_zsptrs Solution of complex symmetric system of linear equations, multiple right-hand sides, matrix already factorized by F07QRF (ZSPTRF), packed storage
F07QUF (ZSPCON) Example Text Example Data | 15 | ZSPCON nagf_lapack_zspcon Estimate condition number of complex symmetric matrix, matrix already factorized by F07QRF (ZSPTRF), packed storage
F07QVF (ZSPRFS) Example Text Example Data | 15 | ZSPRFS nagf_lapack_zsprfs Refined solution with error bounds of complex symmetric system of linear equations, multiple right-hand sides, packed storage
F07QWF (ZSPTRI) Example Text Example Data | 15 | ZSPTRI nagf_lapack_zsptri Inverse of complex symmetric matrix, matrix already factorized by F07QRF (ZSPTRF), packed storage
F07TEF (DTRTRS) Example Text Example Data | 15 | DTRTRS nagf_lapack_dtrtrs Solution of real triangular system of linear equations, multiple right-hand sides
F07TGF (DTRCON) Example Text Example Data | 15 | DTRCON nagf_lapack_dtrcon Estimate condition number of real triangular matrix
F07THF (DTRRFS) Example Text Example Data | 15 | DTRRFS nagf_lapack_dtrrfs Error bounds for solution of real triangular system of linear equations, multiple right-hand sides
F07TJF (DTRTRI) Example Text Example Data | 15 | DTRTRI nagf_lapack_dtrtri Inverse of real triangular matrix
F07TSF (ZTRTRS) Example Text Example Data | 15 | ZTRTRS nagf_lapack_ztrtrs Solution of complex triangular system of linear equations, multiple right-hand sides
F07TUF (ZTRCON) Example Text Example Data | 15 | ZTRCON nagf_lapack_ztrcon Estimate condition number of complex triangular matrix
F07TVF (ZTRRFS) Example Text Example Data | 15 | ZTRRFS nagf_lapack_ztrrfs Error bounds for solution of complex triangular system of linear equations, multiple right-hand sides
F07TWF (ZTRTRI) Example Text Example Data | 15 | ZTRTRI nagf_lapack_ztrtri Inverse of complex triangular matrix
F07UEF (DTPTRS) Example Text Example Data | 15 | DTPTRS nagf_lapack_dtptrs Solution of real triangular system of linear equations, multiple right-hand sides, packed storage
F07UGF (DTPCON) Example Text Example Data | 15 | DTPCON nagf_lapack_dtpcon Estimate condition number of real triangular matrix, packed storage
F07UHF (DTPRFS) Example Text Example Data | 15 | DTPRFS nagf_lapack_dtprfs Error bounds for solution of real triangular system of linear equations, multiple right-hand sides, packed storage
F07UJF (DTPTRI) Example Text Example Data | 15 | DTPTRI nagf_lapack_dtptri Inverse of real triangular matrix, packed storage
F07USF (ZTPTRS) Example Text Example Data | 15 | ZTPTRS nagf_lapack_ztptrs Solution of complex triangular system of linear equations, multiple right-hand sides, packed storage
F07UUF (ZTPCON) Example Text Example Data | 15 | ZTPCON nagf_lapack_ztpcon Estimate condition number of complex triangular matrix, packed storage
F07UVF (ZTPRFS) Example Text Example Data | 15 | ZTPRFS nagf_lapack_ztprfs Error bounds for solution of complex triangular system of linear equations, multiple right-hand sides, packed storage
F07UWF (ZTPTRI) Example Text Example Data | 15 | ZTPTRI nagf_lapack_ztptri Inverse of complex triangular matrix, packed storage
F07VEF (DTBTRS) Example Text Example Data | 15 | DTBTRS nagf_lapack_dtbtrs Solution of real band triangular system of linear equations, multiple right-hand sides
F07VGF (DTBCON) Example Text Example Data | 15 | DTBCON nagf_lapack_dtbcon Estimate condition number of real band triangular matrix
F07VHF (DTBRFS) Example Text Example Data | 15 | DTBRFS nagf_lapack_dtbrfs Error bounds for solution of real band triangular system of linear equations, multiple right-hand sides
F07VSF (ZTBTRS) Example Text Example Data | 15 | ZTBTRS nagf_lapack_ztbtrs Solution of complex band triangular system of linear equations, multiple right-hand sides
F07VUF (ZTBCON) Example Text Example Data | 15 | ZTBCON nagf_lapack_ztbcon Estimate condition number of complex band triangular matrix
F07VVF (ZTBRFS) Example Text Example Data | 15 | ZTBRFS nagf_lapack_ztbrfs Error bounds for solution of complex band triangular system of linear equations, multiple right-hand sides
F07WDF (DPFTRF) Example Text Example Data | 23 | DPFTRF nagf_lapack_dpftrf Cholesky factorization of real symmetric positive definite matrix, Rectangular Full Packed format
F07WEF (DPFTRS) Example Text Example Data | 23 | DPFTRS nagf_lapack_dpftrs Solution of real symmetric positive definite system of linear equations, multiple right-hand sides, coefficient matrix already factorized by F07WDF (DPFTRF), Rectangular Full Packed format
F07WJF (DPFTRI) Example Text Example Data | 23 | DPFTRI nagf_lapack_dpftri Inverse of real symmetric positive definite matrix, matrix already factorized by F07WDF (DPFTRF), Rectangular Full Packed format
F07WKF (DTFTRI) Example Text Example Data | 23 | DTFTRI nagf_lapack_dtftri Inverse of real triangular matrix, Rectangular Full Packed format
F07WRF (ZPFTRF) Example Text Example Data | 23 | ZPFTRF nagf_lapack_zpftrf Cholesky factorization of complex Hermitian positive definite matrix, Rectangular Full Packed format
F07WSF (ZPFTRS) Example Text Example Data | 23 | ZPFTRS nagf_lapack_zpftrs Solution of complex Hermitian positive definite system of linear equations, multiple right-hand sides, coefficient matrix already factorized by F07WRF (ZPFTRF), Rectangular Full Packed format
F07WWF (ZPFTRI) Example Text Example Data | 23 | ZPFTRI nagf_lapack_zpftri Inverse of complex Hermitian positive definite matrix, matrix already factorized by F07WRF (ZPFTRF), Rectangular Full Packed format
F07WXF (ZTFTRI) Example Text Example Data | 23 | ZTFTRI nagf_lapack_ztftri Inverse of complex triangular matrix, Rectangular Full Packed format
F07 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F07CPF (ZGTSVX) : NAG Library, Mark 26

F07 Chapter Contents
F07 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F07CPF (ZGTSVX)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F07CPF (ZGTSVX) uses the LU factorization to compute the solution to a complex system of linear equations
AX=B ,  AT X=B   or   AH X=B ,
where A is a tridiagonal matrix of order n and X and B are n by r matrices. Error bounds on the solution and a condition estimate are also provided.

2 Specification

SUBROUTINE F07CPF ( FACT, TRANS, N, NRHS, DL, D, DU, DLF, DF, DUF, DU2, IPIV, B, LDB, X, LDX, RCOND, FERR, BERR, WORK, RWORK, INFO)
INTEGER | N, NRHS, IPIV(*), LDB, LDX, INFO
REAL (KIND=nag_wp) | RCOND, FERR(NRHS), BERR(NRHS), RWORK(N)
COMPLEX (KIND=nag_wp) | DL(*), D(*), DU(*), DLF(*), DF(*), DUF(*), DU2(*), B(LDB,*), X(LDX,*), WORK(2*N)
CHARACTER(1) | FACT, TRANS
The routine may be called by its LAPACK name zgtsvx.

3 Description

F07CPF (ZGTSVX) performs the following steps:
1. | If FACT='N', the LU decomposition is used to factor the matrix A as A=LU, where L is a product of permutation and unit lower bidiagonal matrices and U is upper triangular with nonzeros in only the main diagonal and first two superdiagonals.
2. | If some u ii=0, so that U is exactly singular, then the routine returns with INFO=i. Otherwise, the factored form of A is used to estimate the condition number of the matrix A. If the reciprocal of the condition number is less than machine precision, INFO=N+1 is returned as a warning, but the routine still goes on to solve for X and compute error bounds as described below.
3. | The system of equations is solved for X using the factored form of A.
4. | Iterative refinement is applied to improve the computed solution matrix and to calculate error bounds and backward error estimates for it.

4 References

Anderson E, Bai Z, Bischof C, Blackford S, Demmel J, Dongarra J J, Du Croz J J, Greenbaum A, Hammarling S, McKenney A and Sorensen D (1999) LAPACK Users' Guide (3rd Edition) SIAM, Philadelphia http://www.netlib.org/lapack/lug
Golub G H and Van Loan C F (1996) Matrix Computations (3rd Edition) Johns Hopkins University Press, Baltimore
Higham N J (2002) Accuracy and Stability of Numerical Algorithms (2nd Edition) SIAM, Philadelphia

5 Arguments

1:   FACT – CHARACTER(1)Input
On entry: specifies whether or not the factorized form of the matrix A has been supplied.
FACT='F'
DLF, DF, DUF, DU2 and IPIV contain the factorized form of the matrix A. DLF, DF, DUF, DU2 and IPIV will not be modified.
FACT='N'
The matrix A will be copied to DLF, DF and DUF and factorized.
Constraint: FACT='F' or 'N'.
2:   TRANS – CHARACTER(1)Input
On entry: specifies the form of the system of equations.
TRANS='N'
AX=B (No transpose).
TRANS='T'
AT X=B (Transpose).
TRANS='C'
AH X=B (Conjugate transpose).
Constraint: TRANS='N', 'T' or 'C'.
3:   N – INTEGERInput
On entry: n, the order of the matrix A.
Constraint: N≥0.
4:   NRHS – INTEGERInput
On entry: r, the number of right-hand sides, i.e., the number of columns of the matrix B.
Constraint: NRHS≥0.
5:   DL* – COMPLEX (KIND=nag_wp) arrayInput
Note: the dimension of the array DL must be at least max 1,N-1.
On entry: the n-1 subdiagonal elements of A.
6:   D* – COMPLEX (KIND=nag_wp) arrayInput
Note: the dimension of the array D must be at least max 1,N.
On entry: the n diagonal elements of A.
7:   DU* – COMPLEX (KIND=nag_wp) arrayInput
Note: the dimension of the array DU must be at least max 1,N-1.
On entry: the n-1 superdiagonal elements of A.
8:   DLF* – COMPLEX (KIND=nag_wp) arrayInput/Output
Note: the dimension of the array DLF must be at least max 1,N-1.
On entry: if FACT='F', DLF contains the n-1 multipliers that define the matrix L from the LU factorization of A.
On exit: if FACT='N', DLF contains the n-1 multipliers that define the matrix L from the LU factorization of A.
9:   DF* – COMPLEX (KIND=nag_wp) arrayInput/Output
Note: the dimension of the array DF must be at least max 1,N.
On entry: if FACT='F', DF contains the n diagonal elements of the upper triangular matrix U from the LU factorization of A.
On exit: if FACT='N', DF contains the n diagonal elements of the upper triangular matrix U from the LU factorization of A.
10:   DUF* – COMPLEX (KIND=nag_wp) arrayInput/Output
Note: the dimension of the array DUF must be at least max 1,N-1.
On entry: if FACT='F', DUF contains the n-1 elements of the first superdiagonal of U.
On exit: if FACT='N', DUF contains the n-1 elements of the first superdiagonal of U.
11:   DU2* – COMPLEX (KIND=nag_wp) arrayInput/Output
Note: the dimension of the array DU2 must be at least max 1,N-2.
On entry: if FACT='F', DU2 contains the (n-2) elements of the second superdiagonal of U.
On exit: if FACT='N', DU2 contains the (n-2) elements of the second superdiagonal of U.
12:   IPIV* – INTEGER arrayInput/Output
Note: the dimension of the array IPIV must be at least max 1,N.
On entry: if FACT='F', IPIV contains the pivot indices from the LU factorization of A.
On exit: if FACT='N', IPIV contains the pivot indices from the LU factorization of A; row i of the matrix was interchanged with row IPIV i. IPIV i will always be either i or i+1; IPIV i=i indicates a row interchange was not required.
13:   B LDB* – COMPLEX (KIND=nag_wp) arrayInput
Note: the second dimension of the array B must be at least max 1,NRHS.
On entry: the n by r right-hand side matrix B.
14:   LDB – INTEGERInput
On entry: the first dimension of the array B as declared in the (sub)program from which F07CPF (ZGTSVX) is called.
Constraint: LDB≥max 1,N.
15:   X LDX* – COMPLEX (KIND=nag_wp) arrayOutput
Note: the second dimension of the array X must be at least max 1,NRHS.
On exit: if INFO=0 or N+1, the n by r solution matrix X.
16:   LDX – INTEGERInput
On entry: the first dimension of the array X as declared in the (sub)program from which F07CPF (ZGTSVX) is called.
Constraint: LDX≥max 1,N.
17:   RCOND – REAL (KIND=nag_wp)Output
On exit: the estimate of the reciprocal condition number of the matrix A. If RCOND=0.0, the matrix may be exactly singular. This condition is indicated by INFO>0 and INFO≤N. Otherwise, if RCOND is less than the machine precision, the matrix is singular to working precision. This condition is indicated by INFO=N+1.
18:   FERR NRHS – REAL (KIND=nag_wp) arrayOutput
On exit: if INFO=0 or N+1, an estimate of the forward error bound for each computed solution vector, such that x^j-xj∞/xj∞≤FERR j where x^j is the jth column of the computed solution returned in the array X and xj is the corresponding column of the exact solution X. The estimate is as reliable as the estimate for RCOND, and is almost always a slight overestimate of the true error.
19:   BERR NRHS – REAL (KIND=nag_wp) arrayOutput
On exit: if INFO=0 or N+1, an estimate of the component-wise relative backward error of each computed solution vector x^j (i.e., the smallest relative change in any element of A or B that makes x^j an exact solution).
20:   WORK 2×N – COMPLEX (KIND=nag_wp) arrayWorkspace
21:   RWORK N – REAL (KIND=nag_wp) arrayWorkspace
22:   INFO – INTEGEROutput
On exit: INFO=0 unless the routine detects an error (see Section 6).

6 Error Indicators and Warnings

INFO<0
If INFO=-i, argument i had an illegal value. An explanatory message is output, and execution of the program is terminated.
INFO>0 and INFO<N
Element value of the diagonal is exactly zero. The factorization has not been completed, but the factor U is exactly singular, so the solution and error bounds could not be computed. RCOND=0.0 is returned.
INFO>0 and INFO=N
Element value of the diagonal is exactly zero. The factorization has been completed, but the factor U is exactly singular, so the solution and error bounds could not be computed. RCOND=0.0 is returned.
INFO=N+1
U is nonsingular, but RCOND is less than machine precision, meaning that the matrix is singular to working precision. Nevertheless, the solution and error bounds are computed because there are a number of situations where the computed solution can be more accurate than the value of RCOND would suggest.

7 Accuracy

For each right-hand side vector b, the computed solution x^ is the exact solution of a perturbed system of equations A+E x^=b, where
E ≤ c n ε L U ,
c n is a modest linear function of n, and ε is the machine precision. See Section 9.3 of Higham (2002) for further details.
If x is the true solution, then the computed solution x^ satisfies a forward error bound of the form
x-x^∞ x^∞ ≤ wc cond A,x^,b
where cond A,x^,b = A-1 A x^ + b ∞/ x^∞ ≤ cond A = A-1 A ∞≤κ∞ A. If x^ is the j th column of X , then wc is returned in BERR j and a bound on x - x^ ∞ / x^ ∞ is returned in FERR j . See Section 4.4 of Anderson et al. (1999) for further details.

8 Parallelism and Performance

F07CPF (ZGTSVX) is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
F07CPF (ZGTSVX) makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The total number of floating-point operations required to solve the equations AX=B is proportional to nr .
The condition number estimation typically requires between four and five solves and never more than eleven solves, following the factorization. The solution is then refined, and the errors estimated, using iterative refinement.
In practice the condition number estimator is very reliable, but it can underestimate the true condition number; see Section 15.3 of Higham (2002) for further details.
The real analogue of this routine is F07CBF (DGTSVX).

10 Example

This example solves the equations
AX=B ,
where A is the tridiagonal matrix
A = -1.3+1.3 i 2.0-1.0 i 0.0i+0.0 0.0i+0.0 0.0i+0.0 1.0-2.0 i -1.3+1.3 i 2.0+1.0 i 0.0i+0.0 0.0i+0.0 0.0i+0.0 1.0+1.0 i -1.3+3.3 i -1.0+1.0 i 0.0i+0.0 0.0i+0.0 0.0i+0.0 2.0-3.0 i -0.3+4.3 i 1.0-1.0 i 0.0i+0.0 0.0i+0.0 0.0i+0.0 1.0+1.0 i -3.3+1.3 i
and
B = 2.4-0 5.0 i 2.7+0 6.9 i 3.4+18.2 i -6.9-0 5.3 i -14.7+0 9.7 i -6.0-0 0.6 i 31.9-0 7.7 i -3.9+0 9.3 i -1.0+0 1.6 i -3.0+12.2 i .
Estimates for the backward errors, forward errors and condition number are also output.

10.1 Program Text

Program Text (f07cpfe.f90)

10.2 Program Data

Program Data (f07cpfe.d)

10.3 Program Results

Program Results (f07cpfe.r)

F07 Chapter Contents
F07 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F07CRF (ZGTTRF) : NAG Library, Mark 26

F07 Chapter Contents
F07 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F07CRF (ZGTTRF)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F07CRF (ZGTTRF) computes the LU factorization of a complex n by n tridiagonal matrix A .

2 Specification

SUBROUTINE F07CRF ( N, DL, D, DU, DU2, IPIV, INFO)
INTEGER | N, IPIV(N), INFO
COMPLEX (KIND=nag_wp) | DL(*), D(*), DU(*), DU2(N-2)
The routine may be called by its LAPACK name zgttrf.

3 Description

F07CRF (ZGTTRF) uses Gaussian elimination with partial pivoting and row interchanges to factorize the matrix A as
A=PLU ,
where P is a permutation matrix, L is unit lower triangular with at most one nonzero subdiagonal element in each column, and U is an upper triangular band matrix, with two superdiagonals.

4 References

Anderson E, Bai Z, Bischof C, Blackford S, Demmel J, Dongarra J J, Du Croz J J, Greenbaum A, Hammarling S, McKenney A and Sorensen D (1999) LAPACK Users' Guide (3rd Edition) SIAM, Philadelphia http://www.netlib.org/lapack/lug

5 Arguments

1:   N – INTEGERInput
On entry: n, the order of the matrix A.
Constraint: N≥0.
2:   DL* – COMPLEX (KIND=nag_wp) arrayInput/Output
Note: the dimension of the array DL must be at least max 1,N-1.
On entry: must contain the n-1 subdiagonal elements of the matrix A.
On exit: is overwritten by the n-1 multipliers that define the matrix L of the LU factorization of A.
3:   D* – COMPLEX (KIND=nag_wp) arrayInput/Output
Note: the dimension of the array D must be at least max 1,N.
On entry: must contain the n diagonal elements of the matrix A.
On exit: is overwritten by the n diagonal elements of the upper triangular matrix U from the LU factorization of A.
4:   DU* – COMPLEX (KIND=nag_wp) arrayInput/Output
Note: the dimension of the array DU must be at least max 1,N-1.
On entry: must contain the n-1 superdiagonal elements of the matrix A.
On exit: is overwritten by the n-1 elements of the first superdiagonal of U.
5:   DU2 N-2 – COMPLEX (KIND=nag_wp) arrayOutput
On exit: contains the n-2 elements of the second superdiagonal of U.
6:   IPIV N – INTEGER arrayOutput
On exit: contains the n pivot indices that define the permutation matrix P. At the ith step, row i of the matrix was interchanged with row IPIV i. IPIV i will always be either i or i+1, IPIV i=i indicating that a row interchange was not performed.
7:   INFO – INTEGEROutput
On exit: INFO=0 unless the routine detects an error (see Section 6).

6 Error Indicators and Warnings

INFO<0
If INFO=-i, argument i had an illegal value. An explanatory message is output, and execution of the program is terminated.
INFO>0
Element value of the diagonal is exactly zero. The factorization has been completed, but the factor U is exactly singular, and division by zero will occur if it is used to solve a system of equations.

7 Accuracy

The computed factorization satisfies an equation of the form
A+E=PLU ,
where
E∞=O ε A∞
and ε is the machine precision.
Following the use of this routine, F07CSF (ZGTTRS) can be used to solve systems of equations AX=B or AT X=B or AH X=B , and F07CUF (ZGTCON) can be used to estimate the condition number of A .

8 Parallelism and Performance

F07CRF (ZGTTRF) is not threaded in any implementation.

9 Further Comments

The total number of floating-point operations required to factorize the matrix A is proportional to n .
The real analogue of this routine is F07CDF (DGTTRF).

10 Example

This example factorizes the tridiagonal matrix A given by
A = -1.3+1.3 i 2.0-1.0 i 0.0i+0.0 0.0i+0.0 0.0i+0.0 1.0-2.0 i -1.3+1.3 i 2.0+1.0 i 0.0i+0.0 0.0i+0.0 0.0i+0.0 1.0+1.0 i -1.3+3.3 i -1.0+1.0 i 0.0i+0.0 0.0i+0.0 0.0i+0.0 2.0-3.0 i -0.3+4.3 i 1.0-1.0 i 0.0i+0.0 0.0i+0.0 0.0i+0.0 1.0+1.0 i -3.3+1.3 i .

10.1 Program Text

Program Text (f07crfe.f90)

10.2 Program Data

Program Data (f07crfe.d)

10.3 Program Results

Program Results (f07crfe.r)

F07 Chapter Contents
F07 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F07CSF (ZGTTRS) : NAG Library, Mark 26

F07 Chapter Contents
F07 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F07CSF (ZGTTRS)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F07CSF (ZGTTRS) computes the solution to a complex system of linear equations AX=B or AT X=B or AH X=B , where A is an n by n tridiagonal matrix and X and B are n by r matrices, using the LU factorization returned by F07CRF (ZGTTRF).

2 Specification

SUBROUTINE F07CSF ( TRANS, N, NRHS, DL, D, DU, DU2, IPIV, B, LDB, INFO)
INTEGER | N, NRHS, IPIV(*), LDB, INFO
COMPLEX (KIND=nag_wp) | DL(*), D(*), DU(*), DU2(*), B(LDB,*)
CHARACTER(1) | TRANS
The routine may be called by its LAPACK name zgttrs.

3 Description

F07CSF (ZGTTRS) should be preceded by a call to F07CRF (ZGTTRF), which uses Gaussian elimination with partial pivoting and row interchanges to factorize the matrix A as
A=PLU ,
where P is a permutation matrix, L is unit lower triangular with at most one nonzero subdiagonal element in each column, and U is an upper triangular band matrix, with two superdiagonals. F07CSF (ZGTTRS) then utilizes the factorization to solve the required equations.

4 References

Anderson E, Bai Z, Bischof C, Blackford S, Demmel J, Dongarra J J, Du Croz J J, Greenbaum A, Hammarling S, McKenney A and Sorensen D (1999) LAPACK Users' Guide (3rd Edition) SIAM, Philadelphia http://www.netlib.org/lapack/lug
Golub G H and Van Loan C F (1996) Matrix Computations (3rd Edition) Johns Hopkins University Press, Baltimore

5 Arguments

1:   TRANS – CHARACTER(1)Input
On entry: specifies the equations to be solved as follows:
TRANS='N'
Solve AX=B for X.
TRANS='T'
Solve AT X=B for X.
TRANS='C'
Solve AH X=B for X.
Constraint: TRANS='N', 'T' or 'C'.
2:   N – INTEGERInput
On entry: n, the order of the matrix A.
Constraint: N≥0.
3:   NRHS – INTEGERInput
On entry: r, the number of right-hand sides, i.e., the number of columns of the matrix B.
Constraint: NRHS≥0.
4:   DL* – COMPLEX (KIND=nag_wp) arrayInput
Note: the dimension of the array DL must be at least max 1,N-1.
On entry: must contain the n-1 multipliers that define the matrix L of the LU factorization of A.
5:   D* – COMPLEX (KIND=nag_wp) arrayInput
Note: the dimension of the array D must be at least max 1,N.
On entry: must contain the n diagonal elements of the upper triangular matrix U from the LU factorization of A.
6:   DU* – COMPLEX (KIND=nag_wp) arrayInput
Note: the dimension of the array DU must be at least max 1,N-1.
On entry: must contain the n-1 elements of the first superdiagonal of U.
7:   DU2* – COMPLEX (KIND=nag_wp) arrayInput
Note: the dimension of the array DU2 must be at least max 1,N-2.
On entry: must contain the n-2 elements of the second superdiagonal of U.
8:   IPIV* – INTEGER arrayInput
Note: the dimension of the array IPIV must be at least max 1,N.
On entry: must contain the n pivot indices that define the permutation matrix P. At the ith step, row i of the matrix was interchanged with row IPIV i, and IPIV i must always be either i or i+1, IPIV i=i indicating that a row interchange was not performed.
9:   B LDB* – COMPLEX (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array B must be at least max 1,NRHS.
On entry: the n by r matrix of right-hand sides B.
On exit: the n by r solution matrix X.
10:   LDB – INTEGERInput
On entry: the first dimension of the array B as declared in the (sub)program from which F07CSF (ZGTTRS) is called.
Constraint: LDB≥max 1,N.
11:   INFO – INTEGEROutput
On exit: INFO=0 unless the routine detects an error (see Section 6).

6 Error Indicators and Warnings

INFO<0
If INFO=-i, argument i had an illegal value. An explanatory message is output, and execution of the program is terminated.

7 Accuracy

The computed solution for a single right-hand side, x^ , satisfies an equation of the form
A+E x^=b ,
where
E 1 =O ε A 1
and ε is the machine precision. An approximate error bound for the computed solution is given by
x^-x 1 x 1 ≤ κ A E 1 A 1 ,
where κ A = A-1 1 A 1 , the condition number of A with respect to the solution of the linear equations. See Section 4.4 of Anderson et al. (1999) for further details.
Following the use of this routine F07CUF (ZGTCON) can be used to estimate the condition number of A and F07CVF (ZGTRFS) can be used to obtain approximate error bounds.

8 Parallelism and Performance

F07CSF (ZGTTRS) is not threaded in any implementation.

9 Further Comments

The total number of floating-point operations required to solve the equations AX=B or AT X=B or AH X=B is proportional to nr .
The real analogue of this routine is F07CEF (DGTTRS).

10 Example

This example solves the equations
AX=B ,
where A is the tridiagonal matrix
A = -1.3+1.3 i 2.0-1.0 i 0.0i+0.0 0.0i+0.0 0.0i+0.0 1.0-2.0 i -1.3+1.3 i 2.0+1.0 i 0.0i+0.0 0.0i+0.0 0.0i+0.0 1.0+1.0 i -1.3+3.3 i -1.0+1.0 i 0.0i+0.0 0.0i+0.0 0.0i+0.0 2.0-3.0 i -0.3+4.3 i 1.0-1.0 i 0.0i+0.0 0.0i+0.0 0.0i+0.0 1.0+1.0 i -3.3+1.3 i
and
B = 2.4-0 5.0 i 2.7+0 6.9 i 3.4+18.2 i -6.9-0 5.3 i -14.7+0 9.7 i -6.0-0 0.6 i 31.9-0 7.7 i -3.9+0 9.3 i -1.0+0 1.6 i -3.0+12.2 i .

10.1 Program Text

Program Text (f07csfe.f90)

10.2 Program Data

Program Data (f07csfe.d)

10.3 Program Results

Program Results (f07csfe.r)

F07 Chapter Contents
F07 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F07CUF (ZGTCON) : NAG Library, Mark 26

F07 Chapter Contents
F07 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F07CUF (ZGTCON)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F07CUF (ZGTCON) estimates the reciprocal condition number of a complex n by n tridiagonal matrix A , using the LU factorization returned by F07CRF (ZGTTRF).

2 Specification

SUBROUTINE F07CUF ( NORM, N, DL, D, DU, DU2, IPIV, ANORM, RCOND, WORK, INFO)
INTEGER | N, IPIV(*), INFO
REAL (KIND=nag_wp) | ANORM, RCOND
COMPLEX (KIND=nag_wp) | DL(*), D(*), DU(*), DU2(*), WORK(2*N)
CHARACTER(1) | NORM
The routine may be called by its LAPACK name zgtcon.

3 Description

F07CUF (ZGTCON) should be preceded by a call to F07CRF (ZGTTRF), which uses Gaussian elimination with partial pivoting and row interchanges to factorize the matrix A as
A=PLU ,
where P is a permutation matrix, L is unit lower triangular with at most one nonzero subdiagonal element in each column, and U is an upper triangular band matrix, with two superdiagonals. F07CUF (ZGTCON) then utilizes the factorization to estimate either A-1 1 or A-1∞ , from which the estimate of the reciprocal of the condition number of A , 1/κ A is computed as either
1 / κ 1 A = 1 / A 1 A-1 1
or
1 / κ∞ A = 1 / A∞ A-1∞ .
1/κ A is returned, rather than κ A , since when A is singular κ A is infinite.
Note that κ∞A=κ 1 AT .

4 References

Higham N J (2002) Accuracy and Stability of Numerical Algorithms (2nd Edition) SIAM, Philadelphia

5 Arguments

1:   NORM – CHARACTER(1)Input
On entry: specifies the norm to be used to estimate κ A.
NORM='1' or 'O'
Estimate κ 1 A.
NORM='I'
Estimate κ∞A.
Constraint: NORM='1', 'O' or 'I'.
2:   N – INTEGERInput
On entry: n, the order of the matrix A.
Constraint: N≥0.
3:   DL* – COMPLEX (KIND=nag_wp) arrayInput
Note: the dimension of the array DL must be at least max 1,N-1.
On entry: must contain the n-1 multipliers that define the matrix L of the LU factorization of A.
4:   D* – COMPLEX (KIND=nag_wp) arrayInput
Note: the dimension of the array D must be at least max 1,N.
On entry: must contain the n diagonal elements of the upper triangular matrix U from the LU factorization of A.
5:   DU* – COMPLEX (KIND=nag_wp) arrayInput
Note: the dimension of the array DU must be at least max 1,N-1.
On entry: must contain the n-1 elements of the first superdiagonal of U.
6:   DU2* – COMPLEX (KIND=nag_wp) arrayInput
Note: the dimension of the array DU2 must be at least max 1,N-2.
On entry: must contain the n-2 elements of the second superdiagonal of U.
7:   IPIV* – INTEGER arrayInput
Note: the dimension of the array IPIV must be at least max 1,N.
On entry: must contain the n pivot indices that define the permutation matrix P. At the ith step, row i of the matrix was interchanged with row IPIV i, and IPIV i must always be either i or i+1, IPIV i=i indicating that a row interchange was not performed.
8:   ANORM – REAL (KIND=nag_wp)Input
On entry: if NORM='1' or 'O', the 1-norm of the original matrix A.
If NORM='I', the ∞-norm of the original matrix A.
ANORM may be computed by calling F06UNF with the same value for the argument NORM.
ANORM must be computed either before calling F07CRF (ZGTTRF) or else from a copy of the original matrix A (see Section 10).
Constraint: ANORM≥0.0.
9:   RCOND – REAL (KIND=nag_wp)Output
On exit: contains an estimate of the reciprocal condition number.
10:   WORK 2×N – COMPLEX (KIND=nag_wp) arrayWorkspace
11:   INFO – INTEGEROutput
On exit: INFO=0 unless the routine detects an error (see Section 6).

6 Error Indicators and Warnings

INFO<0
If INFO=-i, argument i had an illegal value. An explanatory message is output, and execution of the program is terminated.

7 Accuracy

In practice the condition number estimator is very reliable, but it can underestimate the true condition number; see Section 15.3 of Higham (2002) for further details.

8 Parallelism and Performance

F07CUF (ZGTCON) makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The condition number estimation typically requires between four and five solves and never more than eleven solves, following the factorization. The total number of floating-point operations required to perform a solve is proportional to n .
The real analogue of this routine is F07CGF (DGTCON).

10 Example

This example estimates the condition number in the 1-norm of the tridiagonal matrix A given by
A = -1.3+1.3 i 2.0-1.0 i 0.0i+0.0 0.0i+0.0 0.0i+0.0 1.0-2.0 i -1.3+1.3 i 2.0+1.0 i 0.0i+0.0 0.0i+0.0 0.0i+0.0 1.0+1.0 i -1.3+3.3 i -1.0+1.0 i 0.0i+0.0 0.0i+0.0 0.0i+0.0 2.0-3.0 i -0.3+4.3 i 1.0-1.0 i 0.0i+0.0 0.0i+0.0 0.0i+0.0 1.0+1.0 i -3.3+1.3 i .

10.1 Program Text

Program Text (f07cufe.f90)

10.2 Program Data

Program Data (f07cufe.d)

10.3 Program Results

Program Results (f07cufe.r)

F07 Chapter Contents
F07 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F07CVF (ZGTRFS) : NAG Library, Mark 26

F07 Chapter Contents
F07 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F07CVF (ZGTRFS)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F07CVF (ZGTRFS) computes error bounds and refines the solution to a complex system of linear equations AX=B or AT X=B or AH X=B , where A is an n by n tridiagonal matrix and X and B are n by r matrices, using the LU factorization returned by F07CRF (ZGTTRF) and an initial solution returned by F07CSF (ZGTTRS). Iterative refinement is used to reduce the backward error as much as possible.

2 Specification

SUBROUTINE F07CVF ( TRANS, N, NRHS, DL, D, DU, DLF, DF, DUF, DU2, IPIV, B, LDB, X, LDX, FERR, BERR, WORK, RWORK, INFO)
INTEGER | N, NRHS, IPIV(*), LDB, LDX, INFO
REAL (KIND=nag_wp) | FERR(NRHS), BERR(NRHS), RWORK(N)
COMPLEX (KIND=nag_wp) | DL(*), D(*), DU(*), DLF(*), DF(*), DUF(*), DU2(*), B(LDB,*), X(LDX,*), WORK(2*N)
CHARACTER(1) | TRANS
The routine may be called by its LAPACK name zgtrfs.

3 Description

F07CVF (ZGTRFS) should normally be preceded by calls to F07CRF (ZGTTRF) and F07CSF (ZGTTRS). F07CRF (ZGTTRF) uses Gaussian elimination with partial pivoting and row interchanges to factorize the matrix A as
A=PLU ,
where P is a permutation matrix, L is unit lower triangular with at most one nonzero subdiagonal element in each column, and U is an upper triangular band matrix, with two superdiagonals. F07CSF (ZGTTRS) then utilizes the factorization to compute a solution, X^ , to the required equations. Letting x^ denote a column of X^ , F07CVF (ZGTRFS) computes a component-wise backward error, β , the smallest relative perturbation in each element of A and b such that x^ is the exact solution of a perturbed system
A+E x^=b+f , with  e ij ≤β a ij , and  fj ≤β bj .
The routine also estimates a bound for the component-wise forward error in the computed solution defined by max xi - xi^ / max xi^ , where x is the corresponding column of the exact solution, X .

4 References

Anderson E, Bai Z, Bischof C, Blackford S, Demmel J, Dongarra J J, Du Croz J J, Greenbaum A, Hammarling S, McKenney A and Sorensen D (1999) LAPACK Users' Guide (3rd Edition) SIAM, Philadelphia http://www.netlib.org/lapack/lug

5 Arguments

1:   TRANS – CHARACTER(1)Input
On entry: specifies the equations to be solved as follows:
TRANS='N'
Solve AX=B for X.
TRANS='T'
Solve AT X=B for X.
TRANS='C'
Solve AH X=B for X.
Constraint: TRANS='N', 'T' or 'C'.
2:   N – INTEGERInput
On entry: n, the order of the matrix A.
Constraint: N≥0.
3:   NRHS – INTEGERInput
On entry: r, the number of right-hand sides, i.e., the number of columns of the matrix B.
Constraint: NRHS≥0.
4:   DL* – COMPLEX (KIND=nag_wp) arrayInput
Note: the dimension of the array DL must be at least max 1,N-1.
On entry: must contain the n-1 subdiagonal elements of the matrix A.
5:   D* – COMPLEX (KIND=nag_wp) arrayInput
Note: the dimension of the array D must be at least max 1,N.
On entry: must contain the n diagonal elements of the matrix A.
6:   DU* – COMPLEX (KIND=nag_wp) arrayInput
Note: the dimension of the array DU must be at least max 1,N-1.
On entry: must contain the n-1 superdiagonal elements of the matrix A.
7:   DLF* – COMPLEX (KIND=nag_wp) arrayInput
Note: the dimension of the array DLF must be at least max 1,N-1.
On entry: must contain the n-1 multipliers that define the matrix L of the LU factorization of A.
8:   DF* – COMPLEX (KIND=nag_wp) arrayInput
Note: the dimension of the array DF must be at least max 1,N.
On entry: must contain the n diagonal elements of the upper triangular matrix U from the LU factorization of A.
9:   DUF* – COMPLEX (KIND=nag_wp) arrayInput
Note: the dimension of the array DUF must be at least max 1,N-1.
On entry: must contain the n-1 elements of the first superdiagonal of U.
10:   DU2* – COMPLEX (KIND=nag_wp) arrayInput
Note: the dimension of the array DU2 must be at least max 1,N-2.
On entry: must contain the n-2 elements of the second superdiagonal of U.
11:   IPIV* – INTEGER arrayInput
Note: the dimension of the array IPIV must be at least max 1,N.
On entry: must contain the n pivot indices that define the permutation matrix P. At the ith step, row i of the matrix was interchanged with row IPIV i, and IPIV i must always be either i or i+1, IPIV i=i indicating that a row interchange was not performed.
12:   B LDB* – COMPLEX (KIND=nag_wp) arrayInput
Note: the second dimension of the array B must be at least max 1,NRHS.
On entry: the n by r matrix of right-hand sides B.
13:   LDB – INTEGERInput
On entry: the first dimension of the array B as declared in the (sub)program from which F07CVF (ZGTRFS) is called.
Constraint: LDB≥max 1,N.
14:   X LDX* – COMPLEX (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array X must be at least max 1,NRHS.
On entry: the n by r initial solution matrix X.
On exit: the n by r refined solution matrix X.
15:   LDX – INTEGERInput
On entry: the first dimension of the array X as declared in the (sub)program from which F07CVF (ZGTRFS) is called.
Constraint: LDX≥max 1,N.
16:   FERR NRHS – REAL (KIND=nag_wp) arrayOutput
On exit: estimate of the forward error bound for each computed solution vector, such that x^j-xj∞/x^j∞≤FERR j, where x^j is the jth column of the computed solution returned in the array X and xj is the corresponding column of the exact solution X. The estimate is almost always a slight overestimate of the true error.
17:   BERR NRHS – REAL (KIND=nag_wp) arrayOutput
On exit: estimate of the component-wise relative backward error of each computed solution vector x^j (i.e., the smallest relative change in any element of A or B that makes x^j an exact solution).
18:   WORK 2×N – COMPLEX (KIND=nag_wp) arrayWorkspace
19:   RWORK N – REAL (KIND=nag_wp) arrayWorkspace
20:   INFO – INTEGEROutput
On exit: INFO=0 unless the routine detects an error (see Section 6).

6 Error Indicators and Warnings

INFO<0
If INFO=-i, argument i had an illegal value. An explanatory message is output, and execution of the program is terminated.

7 Accuracy

The computed solution for a single right-hand side, x^ , satisfies an equation of the form
A+E x^=b ,
where
E∞=O ε A∞
and ε is the machine precision. An approximate error bound for the computed solution is given by
x^-x ∞ x∞ ≤ κ A E∞ A∞ ,
where κ A=A-1∞ A∞ , the condition number of A with respect to the solution of the linear equations. See Section 4.4 of Anderson et al. (1999) for further details.
Routine F07CUF (ZGTCON) can be used to estimate the condition number of A .

8 Parallelism and Performance

F07CVF (ZGTRFS) is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
F07CVF (ZGTRFS) makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The total number of floating-point operations required to solve the equations AX=B or AT X=B or AH X=B is proportional to nr . At most five steps of iterative refinement are performed, but usually only one or two steps are required.
The real analogue of this routine is F07CHF (DGTRFS).

10 Example

This example solves the equations
AX=B ,
where A is the tridiagonal matrix
A = -1.3+1.3 i 2.0-1.0 i 0.0i+0.0 0.0i+0.0 0.0i+0.0 1.0-2.0 i -1.3+1.3 i 2.0+1.0 i 0.0i+0.0 0.0i+0.0 0.0i+0.0 1.0+1.0 i -1.3+3.3 i -1.0+1.0 i 0.0i+0.0 0.0i+0.0 0.0i+0.0 2.0-3.0 i -0.3+4.3 i 1.0-1.0 i 0.0i+0.0 0.0i+0.0 0.0i+0.0 1.0+1.0 i -3.3+1.3 i
and
B = 2.4-0 5.0 i 2.7+0 6.9 i 3.4+18.2 i -6.9-0 5.3 i -14.7+0 9.7 i -6.0-0 0.6 i 31.9-0 7.7 i -3.9+0 9.3 i -1.0+0 1.6 i -3.0+12.2 i .
Estimates for the backward errors and forward errors are also output.

10.1 Program Text

Program Text (f07cvfe.f90)

10.2 Program Data

Program Data (f07cvfe.d)

10.3 Program Results

Program Results (f07cvfe.r)

F07 Chapter Contents
F07 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F07FAF (DPOSV) : NAG Library, Mark 26

F07 Chapter Contents
F07 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F07FAF (DPOSV)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F07FAF (DPOSV) computes the solution to a real system of linear equations
AX=B ,
where A is an n by n symmetric positive definite matrix and X and B are n by r matrices.

2 Specification

SUBROUTINE F07FAF ( UPLO, N, NRHS, A, LDA, B, LDB, INFO)
INTEGER | N, NRHS, LDA, LDB, INFO
REAL (KIND=nag_wp) | A(LDA,*), B(LDB,*)
CHARACTER(1) | UPLO
The routine may be called by its LAPACK name dposv.

3 Description

F07FAF (DPOSV) uses the Cholesky decomposition to factor A as A=UT U if UPLO='U' or A=L LT if UPLO='L', where U is an upper triangular matrix and L is a lower triangular matrix. The factored form of A is then used to solve the system of equations AX=B.

4 References

Anderson E, Bai Z, Bischof C, Blackford S, Demmel J, Dongarra J J, Du Croz J J, Greenbaum A, Hammarling S, McKenney A and Sorensen D (1999) LAPACK Users' Guide (3rd Edition) SIAM, Philadelphia http://www.netlib.org/lapack/lug
Golub G H and Van Loan C F (1996) Matrix Computations (3rd Edition) Johns Hopkins University Press, Baltimore

5 Arguments

1:   UPLO – CHARACTER(1)Input
On entry: if UPLO='U', the upper triangle of A is stored.
If UPLO='L', the lower triangle of A is stored.
Constraint: UPLO='U' or 'L'.
2:   N – INTEGERInput
On entry: n, the number of linear equations, i.e., the order of the matrix A.
Constraint: N≥0.
3:   NRHS – INTEGERInput
On entry: r, the number of right-hand sides, i.e., the number of columns of the matrix B.
Constraint: NRHS≥0.
4:   A LDA* – REAL (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array A must be at least max 1,N.
On entry: the n by n symmetric matrix A.
  • If UPLO='U', the upper triangular part of A must be stored and the elements of the array below the diagonal are not referenced.
  • If UPLO='L', the lower triangular part of A must be stored and the elements of the array above the diagonal are not referenced.
On exit: if INFO=0, the factor U or L from the Cholesky factorization A=UT U or A=L LT.
5:   LDA – INTEGERInput
On entry: the first dimension of the array A as declared in the (sub)program from which F07FAF (DPOSV) is called.
Constraint: LDA≥max 1,N.
6:   B LDB* – REAL (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array B must be at least max 1,NRHS.
On entry: the n by r right-hand side matrix B.
On exit: if INFO=0, the n by r solution matrix X.
7:   LDB – INTEGERInput
On entry: the first dimension of the array B as declared in the (sub)program from which F07FAF (DPOSV) is called.
Constraint: LDB≥max 1,N.
8:   INFO – INTEGEROutput
On exit: INFO=0 unless the routine detects an error (see Section 6).

6 Error Indicators and Warnings

INFO<0
If INFO=-i, argument i had an illegal value. An explanatory message is output, and execution of the program is terminated.
INFO>0
The leading minor of order value of A is not positive definite, so the factorization could not be completed, and the solution has not been computed.

7 Accuracy

The computed solution for a single right-hand side, x^ , satisfies an equation of the form
A+E x^=b ,
where
E 1 = O ε A 1
and ε is the machine precision. An approximate error bound for the computed solution is given by
x^-x 1 x 1 ≤ κ A E 1 A 1 ,
where κ A = A-1 1 A 1 , the condition number of A with respect to the solution of the linear equations. See Section 4.4 of Anderson et al. (1999) for further details.
F07FBF (DPOSVX) is a comprehensive LAPACK driver that returns forward and backward error bounds and an estimate of the condition number. Alternatively, F04BDF solves Ax=b and returns a forward error bound and condition estimate. F04BDF calls F07FAF (DPOSV) to solve the equations.

8 Parallelism and Performance

F07FAF (DPOSV) is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
F07FAF (DPOSV) makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The total number of floating-point operations is approximately 13 n 3 + 2⁢n 2 r , where r is the number of right-hand sides.
The complex analogue of this routine is F07FNF (ZPOSV).

10 Example

This example solves the equations
Ax=b ,
where A is the symmetric positive definite matrix
A = 4.16 -3.12 0.56 -0.10 -3.12 5.03 -0.83 1.18 0.56 -0.83 0.76 0.34 -0.10 1.18 0.34 1.18   and   b = 8.70 -13.35 1.89 -4.14 .
Details of the Cholesky factorization of A are also output.

10.1 Program Text

Program Text (f07fafe.f90)

10.2 Program Data

Program Data (f07fafe.d)

10.3 Program Results

Program Results (f07fafe.r)

F07 Chapter Contents
F07 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F07FBF (DPOSVX) : NAG Library, Mark 26

F07 Chapter Contents
F07 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F07FBF (DPOSVX)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F07FBF (DPOSVX) uses the Cholesky factorization
A=UT U   or   A=L LT
to compute the solution to a real system of linear equations
AX=B ,
where A is an n by n symmetric positive definite matrix and X and B are n by r matrices. Error bounds on the solution and a condition estimate are also provided.

2 Specification

SUBROUTINE F07FBF ( FACT, UPLO, N, NRHS, A, LDA, AF, LDAF, EQUED, S, B, LDB, X, LDX, RCOND, FERR, BERR, WORK, IWORK, INFO)
INTEGER | N, NRHS, LDA, LDAF, LDB, LDX, IWORK(N), INFO
REAL (KIND=nag_wp) | A(LDA,*), AF(LDAF,*), S(*), B(LDB,*), X(LDX,*), RCOND, FERR(NRHS), BERR(NRHS), WORK(3*N)
CHARACTER(1) | FACT, UPLO, EQUED
The routine may be called by its LAPACK name dposvx.

3 Description

F07FBF (DPOSVX) performs the following steps:
1. If FACT='E', real diagonal scaling factors, DS , are computed to equilibrate the system:
DS A DS DS-1 X = DS B .
Whether or not the system will be equilibrated depends on the scaling of the matrix A, but if equilibration is used, A is overwritten by DS A DS and B by DS B.
2. | If FACT='N' or 'E', the Cholesky decomposition is used to factor the matrix A (after equilibration if FACT='E') as A=UT U if UPLO='U' or A=L LT if UPLO='L', where U is an upper triangular matrix and L is a lower triangular matrix.
3. | If the leading i by i principal minor of A is not positive definite, then the routine returns with INFO=i. Otherwise, the factored form of A is used to estimate the condition number of the matrix A. If the reciprocal of the condition number is less than machine precision, INFO=N+1 is returned as a warning, but the routine still goes on to solve for X and compute error bounds as described below.
4. | The system of equations is solved for X using the factored form of A.
5. | Iterative refinement is applied to improve the computed solution matrix and to calculate error bounds and backward error estimates for it.
6. | If equilibration was used, the matrix X is premultiplied by DS so that it solves the original system before equilibration.

4 References

Anderson E, Bai Z, Bischof C, Blackford S, Demmel J, Dongarra J J, Du Croz J J, Greenbaum A, Hammarling S, McKenney A and Sorensen D (1999) LAPACK Users' Guide (3rd Edition) SIAM, Philadelphia http://www.netlib.org/lapack/lug
Golub G H and Van Loan C F (1996) Matrix Computations (3rd Edition) Johns Hopkins University Press, Baltimore
Higham N J (2002) Accuracy and Stability of Numerical Algorithms (2nd Edition) SIAM, Philadelphia

5 Arguments

1:   FACT – CHARACTER(1)Input
On entry: specifies whether or not the factorized form of the matrix A is supplied on entry, and if not, whether the matrix A should be equilibrated before it is factorized.
FACT='F'
AF contains the factorized form of A. If EQUED='Y', the matrix A has been equilibrated with scaling factors given by S. A and AF will not be modified.
FACT='N'
The matrix A will be copied to AF and factorized.
FACT='E'
The matrix A will be equilibrated if necessary, then copied to AF and factorized.
Constraint: FACT='F', 'N' or 'E'.
2:   UPLO – CHARACTER(1)Input
On entry: if UPLO='U', the upper triangle of A is stored.
If UPLO='L', the lower triangle of A is stored.
Constraint: UPLO='U' or 'L'.
3:   N – INTEGERInput
On entry: n, the number of linear equations, i.e., the order of the matrix A.
Constraint: N≥0.
4:   NRHS – INTEGERInput
On entry: r, the number of right-hand sides, i.e., the number of columns of the matrix B.
Constraint: NRHS≥0.
5:   A LDA* – REAL (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array A must be at least max 1,N.
On entry: the n by n symmetric matrix A.
If FACT='F' and EQUED='Y', A must have been equilibrated by the scaling factor in S as DS A DS.
  • If UPLO='U', the upper triangular part of A must be stored and the elements of the array below the diagonal are not referenced.
  • If UPLO='L', the lower triangular part of A must be stored and the elements of the array above the diagonal are not referenced.
On exit: if FACT='F' or 'N', or if FACT='E' and EQUED='N', A is not modified.
If FACT='E' and EQUED='Y', A is overwritten by DS A DS.
6:   LDA – INTEGERInput
On entry: the first dimension of the array A as declared in the (sub)program from which F07FBF (DPOSVX) is called.
Constraint: LDA≥max 1,N.
7:   AF LDAF* – REAL (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array AF must be at least max 1,N.
On entry: if FACT='F', AF contains the triangular factor U or L from the Cholesky factorization A=UT U or A=L LT, in the same storage format as A. If EQUED≠'N', AF is the factorized form of the equilibrated matrix DS A DS.
On exit: if FACT='N', AF returns the triangular factor U or L from the Cholesky factorization A=UT U or A=L LT of the original matrix A.
If FACT='E', AF returns the triangular factor U or L from the Cholesky factorization A=UT U or A=L LT of the equilibrated matrix A (see the description of A for the form of the equilibrated matrix).
8:   LDAF – INTEGERInput
On entry: the first dimension of the array AF as declared in the (sub)program from which F07FBF (DPOSVX) is called.
Constraint: LDAF≥max 1,N.
9:   EQUED – CHARACTER(1)Input/Output
On entry: if FACT='N' or 'E', EQUED need not be set.
If FACT='F', EQUED must specify the form of the equilibration that was performed as follows:
  • if EQUED='N', no equilibration;
  • if EQUED='Y', equilibration was performed, i.e., A has been replaced by DS A DS.
On exit: if FACT='F', EQUED is unchanged from entry.
Otherwise, if no constraints are violated, EQUED specifies the form of the equilibration that was performed as specified above.
Constraint: if FACT='F', EQUED='N' or 'Y'.
10:   S* – REAL (KIND=nag_wp) arrayInput/Output
Note: the dimension of the array S must be at least max 1,N.
On entry: if FACT='N' or 'E', S need not be set.
If FACT='F' and EQUED='Y', S must contain the scale factors, DS, for A; each element of S must be positive.
On exit: if FACT='F', S is unchanged from entry.
Otherwise, if no constraints are violated and EQUED='Y', S contains the scale factors, DS, for A; each element of S is positive.
11:   B LDB* – REAL (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array B must be at least max 1,NRHS.
On entry: the n by r right-hand side matrix B.
On exit: if EQUED='N', B is not modified.
If EQUED='Y', B is overwritten by DS B.
12:   LDB – INTEGERInput
On entry: the first dimension of the array B as declared in the (sub)program from which F07FBF (DPOSVX) is called.
Constraint: LDB≥max 1,N.
13:   X LDX* – REAL (KIND=nag_wp) arrayOutput
Note: the second dimension of the array X must be at least max 1,NRHS.
On exit: if INFO=0 or N+1, the n by r solution matrix X to the original system of equations. Note that the arrays A and B are modified on exit if EQUED='Y', and the solution to the equilibrated system is DS-1 X.
14:   LDX – INTEGERInput
On entry: the first dimension of the array X as declared in the (sub)program from which F07FBF (DPOSVX) is called.
Constraint: LDX≥max 1,N.
15:   RCOND – REAL (KIND=nag_wp)Output
On exit: if no constraints are violated, an estimate of the reciprocal condition number of the matrix A (after equilibration if that is performed), computed as RCOND=1.0/A 1 A-1 1 .
16:   FERR NRHS – REAL (KIND=nag_wp) arrayOutput
On exit: if INFO=0 or N+1, an estimate of the forward error bound for each computed solution vector, such that x^j-xj∞/xj∞≤FERR j where x^j is the jth column of the computed solution returned in the array X and xj is the corresponding column of the exact solution X. The estimate is as reliable as the estimate for RCOND, and is almost always a slight overestimate of the true error.
17:   BERR NRHS – REAL (KIND=nag_wp) arrayOutput
On exit: if INFO=0 or N+1, an estimate of the component-wise relative backward error of each computed solution vector x^j (i.e., the smallest relative change in any element of A or B that makes x^j an exact solution).
18:   WORK 3×N – REAL (KIND=nag_wp) arrayWorkspace
19:   IWORK N – INTEGER arrayWorkspace
20:   INFO – INTEGEROutput
On exit: INFO=0 unless the routine detects an error (see Section 6).

6 Error Indicators and Warnings

INFO<0
If INFO=-i, argument i had an illegal value. An explanatory message is output, and execution of the program is terminated.
INFO>0 and INFO≤N
The leading minor of order value of A is not positive definite, so the factorization could not be completed, and the solution has not been computed. RCOND=0.0 is returned.
INFO=N+1
U (or L) is nonsingular, but RCOND is less than machine precision, meaning that the matrix is singular to working precision. Nevertheless, the solution and error bounds are computed because there are a number of situations where the computed solution can be more accurate than the value of RCOND would suggest.

7 Accuracy

For each right-hand side vector b, the computed solution x is the exact solution of a perturbed system of equations A+E x=b, where
  • if UPLO='U', E≤c n ε UTU;
  • if UPLO='L', E≤c n ε LLT,
c n is a modest linear function of n, and ε is the machine precision. See Section 10.1 of Higham (2002) for further details.
If x^ is the true solution, then the computed solution x satisfies a forward error bound of the form
x-x^∞ x^∞ ≤ wc cond A,x^,b
where cond A,x^,b = A-1 A x^ + b ∞/ x^∞ ≤ cond A = A-1 A ∞≤κ∞ A. If x^ is the j th column of X , then wc is returned in BERR j and a bound on x - x^ ∞ / x^ ∞ is returned in FERR j . See Section 4.4 of Anderson et al. (1999) for further details.

8 Parallelism and Performance

F07FBF (DPOSVX) is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
F07FBF (DPOSVX) makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The factorization of A requires approximately 13 n 3 floating-point operations.
For each right-hand side, computation of the backward error involves a minimum of 4⁢n 2 floating-point operations. Each step of iterative refinement involves an additional 6⁢n 2 operations. At most five steps of iterative refinement are performed, but usually only one or two steps are required. Estimating the forward error involves solving a number of systems of equations of the form Ax=b ; the number is usually 4 or 5 and never more than 11. Each solution involves approximately 2⁢n 2 operations.
The complex analogue of this routine is F07FPF (ZPOSVX).

10 Example

This example solves the equations
AX=B ,
where A is the symmetric positive definite matrix
A = 4.16 -3.12 0.56 -0.10 -3.12 5.03 -0.83 1.18 0.56 -0.83 0.76 0.34 -0.10 1.18 0.34 1.18
and
B = 8.70 8.30 -13.35 2.13 1.89 1.61 -4.14 5.00 .
Error estimates for the solutions, information on equilibration and an estimate of the reciprocal of the condition number of the scaled matrix A are also output.

10.1 Program Text

Program Text (f07fbfe.f90)

10.2 Program Data

Program Data (f07fbfe.d)

10.3 Program Results

Program Results (f07fbfe.r)

F07 Chapter Contents
F07 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F07FCF (DSPOSV) : NAG Library, Mark 26

F07 Chapter Contents
F07 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F07FCF (DSPOSV)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F07FCF (DSPOSV) uses the Cholesky factorization
A=UT U   or   A=L LT
to compute the solution to a real system of linear equations
AX=B ,
where A is an n by n symmetric positive definite matrix and X and B are n by r matrices.

2 Specification

SUBROUTINE F07FCF ( UPLO, N, NRHS, A, LDA, B, LDB, X, LDX, WORK, SWORK, ITER, INFO)
INTEGER | N, NRHS, LDA, LDB, LDX, ITER, INFO
REAL (KIND=nag_wp) | A(LDA,*), B(LDB,*), X(LDX,*), WORK(N,NRHS)
REAL (KIND=nag_rp) | SWORK(N*(N+NRHS))
CHARACTER(1) | UPLO
The routine may be called by its LAPACK name dsposv.

3 Description

F07FCF (DSPOSV) first attempts to factorize the matrix in reduced precision and use this factorization within an iterative refinement procedure to produce a solution with full precision normwise backward error quality (see below). If the approach fails the method switches to a full precision factorization and solve.
The iterative refinement can be more efficient than the corresponding direct full precision algorithm. Since the strategy implemented by F07FCF (DSPOSV) must perform iterative refinement on each right-hand side, any efficiency gains will reduce as the number of right-hand sides increases. Conversely, as the matrix size increases the cost of these iterative refinements become less significant relative to the cost of factorization. Thus, any efficiency gains will be greatest for a very small number of right-hand sides and for large matrix sizes. The cut-off values for the number of right-hand sides and matrix size, for which the iterative refinement strategy performs better, depends on the relative performance of the reduced and full precision factorization and back-substitution. F07FCF (DSPOSV) always attempts the iterative refinement strategy first; you are advised to compare the performance of F07FCF (DSPOSV) with that of its full precision counterpart F07FAF (DPOSV) to determine whether this strategy is worthwhile for your particular problem dimensions.
The iterative refinement process is stopped if ITER>30 where ITER is the number of iterations carried out thus far. The process is also stopped if for all right-hand sides we have
resid < N x A ε ,
where resid is the ∞-norm of the residual, x is the ∞-norm of the solution, A is the ∞-norm of the matrix A and ε is the machine precision returned by X02AJF.

4 References

Anderson E, Bai Z, Bischof C, Blackford S, Demmel J, Dongarra J J, Du Croz J J, Greenbaum A, Hammarling S, McKenney A and Sorensen D (1999) LAPACK Users' Guide (3rd Edition) SIAM, Philadelphia http://www.netlib.org/lapack/lug
Golub G H and Van Loan C F (1996) Matrix Computations (3rd Edition) Johns Hopkins University Press, Baltimore
Higham N J (2002) Accuracy and Stability of Numerical Algorithms (2nd Edition) SIAM, Philadelphia

5 Arguments

1:   UPLO – CHARACTER(1)Input
On entry: specifies whether the upper or lower triangular part of A is stored.
UPLO='U'
The upper triangular part of A is stored.
UPLO='L'
The lower triangular part of A is stored.
Constraint: UPLO='U' or 'L'.
2:   N – INTEGERInput
On entry: n, the number of linear equations, i.e., the order of the matrix A.
Constraint: N≥0.
3:   NRHS – INTEGERInput
On entry: r, the number of right-hand sides, i.e., the number of columns of the matrix B.
Constraint: NRHS≥0.
4:   A LDA* – REAL (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array A must be at least max 1,N.
On entry: the n by n symmetric positive definite matrix A.
  • If UPLO='U', the upper triangular part of A must be stored and the elements of the array below the diagonal are not referenced.
  • If UPLO='L', the lower triangular part of A must be stored and the elements of the array above the diagonal are not referenced.
On exit: if iterative refinement has been successfully used (INFO=0 and ITER≥0, see description below), then A is unchanged. If full precision factorization has been used (INFO=0 and ITER<0, see description below), then the array A contains the factor U or L from the Cholesky factorization A=UT U or A=L LT.
5:   LDA – INTEGERInput
On entry: the first dimension of the array A as declared in the (sub)program from which F07FCF (DSPOSV) is called.
Constraint: LDA≥max 1,N.
6:   B LDB* – REAL (KIND=nag_wp) arrayInput
Note: the second dimension of the array B must be at least max 1,NRHS.
On entry: the right-hand side matrix B.
7:   LDB – INTEGERInput
On entry: the first dimension of the array B as declared in the (sub)program from which F07FCF (DSPOSV) is called.
Constraint: LDB≥max 1,N.
8:   X LDX* – REAL (KIND=nag_wp) arrayOutput
Note: the second dimension of the array X must be at least max 1,NRHS.
On exit: if INFO=0, the n by r solution matrix X.
9:   LDX – INTEGERInput
On entry: the first dimension of the array X as declared in the (sub)program from which F07FCF (DSPOSV) is called.
Constraint: LDX≥max 1,N.
10:   WORK NNRHS – REAL (KIND=nag_wp) arrayWorkspace
11:   SWORK N×N+NRHS – REAL (KIND=nag_rp) arrayWorkspace
Note: this array is utilized in the reduced precision computation, consequently its type nag_rp reflects this usage.
12:   ITER – INTEGEROutput
On exit: information on the progress of the interative refinement process.
ITER<0
Iterative refinement has failed for one of the reasons given below, full precision factorization has been performed instead.
-1 | The routine fell back to full precision for implementation- or machine-specific reasons.
-2 | Narrowing the precision induced an overflow, the routine fell back to full precision.
-3 | An intermediate reduced precision factorization failed.
-31 | The maximum permitted number of iterations was exceeded.
ITER>0
Iterative refinement has been sucessfully used. ITER returns the number of iterations.
13:   INFO – INTEGEROutput
On exit: INFO=0 unless the routine detects an error (see Section 6).

6 Error Indicators and Warnings

INFO<0
If INFO=-i, argument i had an illegal value. An explanatory message is output, and execution of the program is terminated.
INFO>0 and INFO≤N
The leading minor of order value of A is not positive definite, so the factorization could not be completed, and the solution has not been computed.

7 Accuracy

For each right-hand side vector b, the computed solution x is the exact solution of a perturbed system of equations A+E x=b, where
  • if UPLO='U', E≤c n ε UTU;
  • if UPLO='L', E≤c n ε LLT,
c n is a modest linear function of n, and ε is the machine precision. See Section 10.1 of Higham (2002) for further details.
An approximate error bound for the computed solution is given by
x^ - x 1 x 1 ≤ κ A E 1 A 1
where κ A = A-1 1 A 1 , the condition number of A with respect to the solution of the linear equations. See Section 4.4 of Anderson et al. (1999) for further details.

8 Parallelism and Performance

F07FCF (DSPOSV) is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
F07FCF (DSPOSV) makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The complex analogue of this routine is F07FQF (ZCPOSV).

10 Example

This example solves the equations
AX=B ,
where A is the symmetric positive definite matrix
A = 4.16 -3.12 0.56 -0.10 -3.12 5.03 -0.83 1.18 0.56 -0.83 0.76 0.34 -0.10 1.18 0.34 1.18
and
B = 8.70 -13.35 1.89 -4.14 .

10.1 Program Text

Program Text (f07fcfe.f90)

10.2 Program Data

Program Data (f07fcfe.d)

10.3 Program Results

Program Results (f07fcfe.r)

F07 Chapter Contents
F07 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F07FDF (DPOTRF) : NAG Library, Mark 26

F07 Chapter Contents
F07 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F07FDF (DPOTRF)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F07FDF (DPOTRF) computes the Cholesky factorization of a real symmetric positive definite matrix.

2 Specification

SUBROUTINE F07FDF ( UPLO, N, A, LDA, INFO)
INTEGER | N, LDA, INFO
REAL (KIND=nag_wp) | A(LDA,*)
CHARACTER(1) | UPLO
The routine may be called by its LAPACK name dpotrf.

3 Description

F07FDF (DPOTRF) forms the Cholesky factorization of a real symmetric positive definite matrix A either as A=UT U if UPLO='U' or A=L LT if UPLO='L', where U is an upper triangular matrix and L is lower triangular.

4 References

Demmel J W (1989) On floating-point errors in Cholesky LAPACK Working Note No. 14 University of Tennessee, Knoxville http://www.netlib.org/lapack/lawnspdf/lawn14.pdf
Golub G H and Van Loan C F (1996) Matrix Computations (3rd Edition) Johns Hopkins University Press, Baltimore

5 Arguments

1:   UPLO – CHARACTER(1)Input
On entry: specifies whether the upper or lower triangular part of A is stored and how A is to be factorized.
UPLO='U'
The upper triangular part of A is stored and A is factorized as UT U, where U is upper triangular.
UPLO='L'
The lower triangular part of A is stored and A is factorized as L LT, where L is lower triangular.
Constraint: UPLO='U' or 'L'.
2:   N – INTEGERInput
On entry: n, the order of the matrix A.
Constraint: N≥0.
3:   A LDA* – REAL (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array A must be at least max 1,N.
On entry: the n by n symmetric positive definite matrix A.
  • If UPLO='U', the upper triangular part of A must be stored and the elements of the array below the diagonal are not referenced.
  • If UPLO='L', the lower triangular part of A must be stored and the elements of the array above the diagonal are not referenced.
On exit: the upper or lower triangle of A is overwritten by the Cholesky factor U or L as specified by UPLO.
4:   LDA – INTEGERInput
On entry: the first dimension of the array A as declared in the (sub)program from which F07FDF (DPOTRF) is called.
Constraint: LDA≥max 1,N.
5:   INFO – INTEGEROutput
On exit: INFO=0 unless the routine detects an error (see Section 6).

6 Error Indicators and Warnings

INFO<0
If INFO=-i, argument i had an illegal value. An explanatory message is output, and execution of the program is terminated.
INFO>0
The leading minor of order value is not positive definite and the factorization could not be completed. Hence A itself is not positive definite. This may indicate an error in forming the matrix A. To factorize a symmetric matrix which is not positive definite, call F07MDF (DSYTRF) instead.

7 Accuracy

If UPLO='U', the computed factor U is the exact factor of a perturbed matrix A+E, where
E≤c n ε UTU ,
c n is a modest linear function of n, and ε is the machine precision. If UPLO='L', a similar statement holds for the computed factor L. It follows that e ij≤c n ε⁢a iia jj.

8 Parallelism and Performance

F07FDF (DPOTRF) is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
F07FDF (DPOTRF) makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The total number of floating-point operations is approximately 13 n 3.
A call to F07FDF (DPOTRF) may be followed by calls to the routines:
  • F07FEF (DPOTRS) to solve AX=B;
  • F07FGF (DPOCON) to estimate the condition number of A;
  • F07FJF (DPOTRI) to compute the inverse of A.
The complex analogue of this routine is F07FRF (ZPOTRF).

10 Example

This example computes the Cholesky factorization of the matrix A, where
A= 4.16 -3.12 0.56 -0.10 -3.12 5.03 -0.83 1.18 0.56 -0.83 0.76 0.34 -0.10 1.18 0.34 1.18 .

10.1 Program Text

Program Text (f07fdfe.f90)

10.2 Program Data

Program Data (f07fdfe.d)

10.3 Program Results

Program Results (f07fdfe.r)

F07 Chapter Contents
F07 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F07FEF (DPOTRS) : NAG Library, Mark 26

F07 Chapter Contents
F07 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F07FEF (DPOTRS)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F07FEF (DPOTRS) solves a real symmetric positive definite system of linear equations with multiple right-hand sides,
AX=B ,
where A has been factorized by F07FDF (DPOTRF).

2 Specification

SUBROUTINE F07FEF ( UPLO, N, NRHS, A, LDA, B, LDB, INFO)
INTEGER | N, NRHS, LDA, LDB, INFO
REAL (KIND=nag_wp) | A(LDA,*), B(LDB,*)
CHARACTER(1) | UPLO
The routine may be called by its LAPACK name dpotrs.

3 Description

F07FEF (DPOTRS) is used to solve a real symmetric positive definite system of linear equations AX=B, this routine must be preceded by a call to F07FDF (DPOTRF) which computes the Cholesky factorization of A. The solution X is computed by forward and backward substitution.
If UPLO='U', A=UT U, where U is upper triangular; the solution X is computed by solving UT Y=B and then UX=Y.
If UPLO='L', A=L LT, where L is lower triangular; the solution X is computed by solving LY=B and then LT X=Y.

4 References

Golub G H and Van Loan C F (1996) Matrix Computations (3rd Edition) Johns Hopkins University Press, Baltimore

5 Arguments

1:   UPLO – CHARACTER(1)Input
On entry: specifies how A has been factorized.
UPLO='U'
A=UT U, where U is upper triangular.
UPLO='L'
A=L LT, where L is lower triangular.
Constraint: UPLO='U' or 'L'.
2:   N – INTEGERInput
On entry: n, the order of the matrix A.
Constraint: N≥0.
3:   NRHS – INTEGERInput
On entry: r, the number of right-hand sides.
Constraint: NRHS≥0.
4:   A LDA* – REAL (KIND=nag_wp) arrayInput
Note: the second dimension of the array A must be at least max 1,N.
On entry: the Cholesky factor of A, as returned by F07FDF (DPOTRF).
5:   LDA – INTEGERInput
On entry: the first dimension of the array A as declared in the (sub)program from which F07FEF (DPOTRS) is called.
Constraint: LDA≥max 1,N.
6:   B LDB* – REAL (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array B must be at least max 1,NRHS.
On entry: the n by r right-hand side matrix B.
On exit: the n by r solution matrix X.
7:   LDB – INTEGERInput
On entry: the first dimension of the array B as declared in the (sub)program from which F07FEF (DPOTRS) is called.
Constraint: LDB≥max 1,N.
8:   INFO – INTEGEROutput
On exit: INFO=0 unless the routine detects an error (see Section 6).

6 Error Indicators and Warnings

INFO<0
If INFO=-i, argument i had an illegal value. An explanatory message is output, and execution of the program is terminated.

7 Accuracy

For each right-hand side vector b, the computed solution x is the exact solution of a perturbed system of equations A+E x=b, where
  • if UPLO='U', E≤c n ε UTU;
  • if UPLO='L', E≤c n ε LLT,
c n is a modest linear function of n, and ε is the machine precision.
If x^ is the true solution, then the computed solution x satisfies a forward error bound of the form
x-x^∞ x∞ ≤c n cond A,x ε
where cond A,x=A-1Ax∞/x∞≤cond A=A-1A∞≤κ∞A.
Note that cond A,x can be much smaller than cond A.
Forward and backward error bounds can be computed by calling F07FHF (DPORFS), and an estimate for κ∞A (=κ 1 A) can be obtained by calling F07FGF (DPOCON).

8 Parallelism and Performance

F07FEF (DPOTRS) is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
F07FEF (DPOTRS) makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The total number of floating-point operations is approximately 2⁢n 2 r.
This routine may be followed by a call to F07FHF (DPORFS) to refine the solution and return an error estimate.
The complex analogue of this routine is F07FSF (ZPOTRS).

10 Example

This example solves the system of equations AX=B, where
A= 4.16 -3.12 0.56 -0.10 -3.12 5.03 -0.83 1.18 0.56 -0.83 0.76 0.34 -0.10 1.18 0.34 1.18   and   B= 8.70 8.30 -13.35 2.13 1.89 1.61 -4.14 5.00 .
Here A is symmetric positive definite and must first be factorized by F07FDF (DPOTRF).

10.1 Program Text

Program Text (f07fefe.f90)

10.2 Program Data

Program Data (f07fefe.d)

10.3 Program Results

Program Results (f07fefe.r)

F07 Chapter Contents
F07 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F07FFF (DPOEQU) : NAG Library, Mark 26

F07 Chapter Contents
F07 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F07FFF (DPOEQU)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F07FFF (DPOEQU) computes a diagonal scaling matrix S intended to equilibrate a real n by n symmetric positive definite matrix A and reduce its condition number.

2 Specification

SUBROUTINE F07FFF ( N, A, LDA, S, SCOND, AMAX, INFO)
INTEGER | N, LDA, INFO
REAL (KIND=nag_wp) | A(LDA,*), S(N), SCOND, AMAX
The routine may be called by its LAPACK name dpoequ.

3 Description

F07FFF (DPOEQU) computes a diagonal scaling matrix S chosen so that
sj=1 / a jj .
This means that the matrix B given by
B=SAS ,
has diagonal elements equal to unity. This in turn means that the condition number of B , κ 2 B , is within a factor n of the matrix of smallest possible condition number over all possible choices of diagonal scalings (see Corollary 7.6 of Higham (2002)).

4 References

Higham N J (2002) Accuracy and Stability of Numerical Algorithms (2nd Edition) SIAM, Philadelphia

5 Arguments

1:   N – INTEGERInput
On entry: n, the order of the matrix A.
Constraint: N≥0.
2:   A LDA* – REAL (KIND=nag_wp) arrayInput
Note: the second dimension of the array A must be at least max 1,N.
On entry: the matrix A whose scaling factors are to be computed. Only the diagonal elements of the array A are referenced.
3:   LDA – INTEGERInput
On entry: the first dimension of the array A as declared in the (sub)program from which F07FFF (DPOEQU) is called.
Constraint: LDA≥max 1,N.
4:   S N – REAL (KIND=nag_wp) arrayOutput
On exit: if INFO=0, S contains the diagonal elements of the scaling matrix S.
5:   SCOND – REAL (KIND=nag_wp)Output
On exit: if INFO=0, SCOND contains the ratio of the smallest value of S to the largest value of S. If SCOND≥0.1 and AMAX is neither too large nor too small, it is not worth scaling by S.
6:   AMAX – REAL (KIND=nag_wp)Output
On exit: max a ij. If AMAX is very close to overflow or underflow, the matrix A should be scaled.
7:   INFO – INTEGEROutput
On exit: INFO=0 unless the routine detects an error (see Section 6).

6 Error Indicators and Warnings

INFO<0
If INFO=-i, argument i had an illegal value. An explanatory message is output, and execution of the program is terminated.
INFO>0
The valueth diagonal element of A is not positive (and hence A cannot be positive definite).

7 Accuracy

The computed scale factors will be close to the exact scale factors.

8 Parallelism and Performance

F07FFF (DPOEQU) is not threaded in any implementation.

9 Further Comments

The complex analogue of this routine is F07FTF (ZPOEQU).

10 Example

This example equilibrates the symmetric positive definite matrix A given by
A = -4.16 -3.12×105 -0.56 -0.10 -3.12×105 -5.03×1010 -0.83×105 -1.18×105 -0.56 -0.83×105 -0.76 -0.34 -0.10 -1.18×105 -0.34 -1.18 .
Details of the scaling factors and the scaled matrix are output.

10.1 Program Text

Program Text (f07fffe.f90)

10.2 Program Data

Program Data (f07fffe.d)

10.3 Program Results

Program Results (f07fffe.r)

F07 Chapter Contents
F07 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F07FGF (DPOCON) : NAG Library, Mark 26

F07 Chapter Contents
F07 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F07FGF (DPOCON)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F07FGF (DPOCON) estimates the condition number of a real symmetric positive definite matrix A, where A has been factorized by F07FDF (DPOTRF).

2 Specification

SUBROUTINE F07FGF ( UPLO, N, A, LDA, ANORM, RCOND, WORK, IWORK, INFO)
INTEGER | N, LDA, IWORK(N), INFO
REAL (KIND=nag_wp) | A(LDA,*), ANORM, RCOND, WORK(3*N)
CHARACTER(1) | UPLO
The routine may be called by its LAPACK name dpocon.

3 Description

F07FGF (DPOCON) estimates the condition number (in the 1-norm) of a real symmetric positive definite matrix A:
κ 1 A=A 1A-1 1 .
Since A is symmetric, κ 1 A=κ∞A=A∞A-1∞.
Because κ 1 A is infinite if A is singular, the routine actually returns an estimate of the reciprocal of κ 1 A.
The routine should be preceded by a call to F06RCF to compute A 1 and a call to F07FDF (DPOTRF) to compute the Cholesky factorization of A. The routine then uses Higham's implementation of Hager's method (see Higham (1988)) to estimate A-1 1.

4 References

Higham N J (1988) FORTRAN codes for estimating the one-norm of a real or complex matrix, with applications to condition estimation ACM Trans. Math. Software 14 381–396

5 Arguments

1:   UPLO – CHARACTER(1)Input
On entry: specifies how A has been factorized.
UPLO='U'
A=UT U, where U is upper triangular.
UPLO='L'
A=L LT, where L is lower triangular.
Constraint: UPLO='U' or 'L'.
2:   N – INTEGERInput
On entry: n, the order of the matrix A.
Constraint: N≥0.
3:   A LDA* – REAL (KIND=nag_wp) arrayInput
Note: the second dimension of the array A must be at least max 1,N.
On entry: the Cholesky factor of A, as returned by F07FDF (DPOTRF).
4:   LDA – INTEGERInput
On entry: the first dimension of the array A as declared in the (sub)program from which F07FGF (DPOCON) is called.
Constraint: LDA≥max 1,N.
5:   ANORM – REAL (KIND=nag_wp)Input
On entry: the 1-norm of the original matrix A, which may be computed by calling F06RCF with its argument NORM='1'. ANORM must be computed either before calling F07FDF (DPOTRF) or else from a copy of the original matrix A.
Constraint: ANORM≥0.0.
6:   RCOND – REAL (KIND=nag_wp)Output
On exit: an estimate of the reciprocal of the condition number of A. RCOND is set to zero if exact singularity is detected or the estimate underflows. If RCOND is less than machine precision, A is singular to working precision.
7:   WORK 3×N – REAL (KIND=nag_wp) arrayWorkspace
8:   IWORK N – INTEGER arrayWorkspace
9:   INFO – INTEGEROutput
On exit: INFO=0 unless the routine detects an error (see Section 6).

6 Error Indicators and Warnings

INFO<0
If INFO=-i, argument i had an illegal value. An explanatory message is output, and execution of the program is terminated.

7 Accuracy

The computed estimate RCOND is never less than the true value ρ, and in practice is nearly always less than 10 ρ, although examples can be constructed where RCOND is much larger.

8 Parallelism and Performance

F07FGF (DPOCON) makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

A call to F07FGF (DPOCON) involves solving a number of systems of linear equations of the form Ax=b; the number is usually 4 or 5 and never more than 11. Each solution involves approximately 2⁢n 2 floating-point operations but takes considerably longer than a call to F07FEF (DPOTRS) with one right-hand side, because extra care is taken to avoid overflow when A is approximately singular.
The complex analogue of this routine is F07FUF (ZPOCON).

10 Example

This example estimates the condition number in the 1-norm (or ∞-norm) of the matrix A, where
A= 4.16 -3.12 0.56 -0.10 -3.12 5.03 -0.83 1.18 0.56 -0.83 0.76 0.34 -0.10 1.18 0.34 1.18 .
Here A is symmetric positive definite and must first be factorized by F07FDF (DPOTRF). The true condition number in the 1-norm is 97.32.

10.1 Program Text

Program Text (f07fgfe.f90)

10.2 Program Data

Program Data (f07fgfe.d)

10.3 Program Results

Program Results (f07fgfe.r)

F07 Chapter Contents
F07 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F07FHF (DPORFS) : NAG Library, Mark 26

F07 Chapter Contents
F07 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F07FHF (DPORFS)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F07FHF (DPORFS) returns error bounds for the solution of a real symmetric positive definite system of linear equations with multiple right-hand sides, AX=B. It improves the solution by iterative refinement, in order to reduce the backward error as much as possible.

2 Specification

SUBROUTINE F07FHF ( UPLO, N, NRHS, A, LDA, AF, LDAF, B, LDB, X, LDX, FERR, BERR, WORK, IWORK, INFO)
INTEGER | N, NRHS, LDA, LDAF, LDB, LDX, IWORK(N), INFO
REAL (KIND=nag_wp) | A(LDA,*), AF(LDAF,*), B(LDB,*), X(LDX,*), FERR(NRHS), BERR(NRHS), WORK(3*N)
CHARACTER(1) | UPLO
The routine may be called by its LAPACK name dporfs.

3 Description

F07FHF (DPORFS) returns the backward errors and estimated bounds on the forward errors for the solution of a real symmetric positive definite system of linear equations with multiple right-hand sides AX=B. The routine handles each right-hand side vector (stored as a column of the matrix B) independently, so we describe the function of F07FHF (DPORFS) in terms of a single right-hand side b and solution x.
Given a computed solution x, the routine computes the component-wise backward error β. This is the size of the smallest relative perturbation in each element of A and b such that x is the exact solution of a perturbed system
A+δA x=b+δb δ a ij≤β a ij   and   δ bi≤β bi .
Then the routine estimates a bound for the component-wise forward error in the computed solution, defined by:
maxi xi-x^i/maxi xi
where x^ is the true solution.
For details of the method, see the F07 Chapter Introduction.

4 References

Golub G H and Van Loan C F (1996) Matrix Computations (3rd Edition) Johns Hopkins University Press, Baltimore

5 Arguments

1:   UPLO – CHARACTER(1)Input
On entry: specifies whether the upper or lower triangular part of A is stored and how A is to be factorized.
UPLO='U'
The upper triangular part of A is stored and A is factorized as UT U, where U is upper triangular.
UPLO='L'
The lower triangular part of A is stored and A is factorized as L LT, where L is lower triangular.
Constraint: UPLO='U' or 'L'.
2:   N – INTEGERInput
On entry: n, the order of the matrix A.
Constraint: N≥0.
3:   NRHS – INTEGERInput
On entry: r, the number of right-hand sides.
Constraint: NRHS≥0.
4:   A LDA* – REAL (KIND=nag_wp) arrayInput
Note: the second dimension of the array A must be at least max 1,N.
On entry: the n by n original symmetric positive definite matrix A as supplied to F07FDF (DPOTRF).
5:   LDA – INTEGERInput
On entry: the first dimension of the array A as declared in the (sub)program from which F07FHF (DPORFS) is called.
Constraint: LDA≥max 1,N.
6:   AF LDAF* – REAL (KIND=nag_wp) arrayInput
Note: the second dimension of the array AF must be at least max 1,N.
On entry: the Cholesky factor of A, as returned by F07FDF (DPOTRF).
7:   LDAF – INTEGERInput
On entry: the first dimension of the array AF as declared in the (sub)program from which F07FHF (DPORFS) is called.
Constraint: LDAF≥max 1,N.
8:   B LDB* – REAL (KIND=nag_wp) arrayInput
Note: the second dimension of the array B must be at least max 1,NRHS.
On entry: the n by r right-hand side matrix B.
9:   LDB – INTEGERInput
On entry: the first dimension of the array B as declared in the (sub)program from which F07FHF (DPORFS) is called.
Constraint: LDB≥max 1,N.
10:   X LDX* – REAL (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array X must be at least max 1,NRHS.
On entry: the n by r solution matrix X, as returned by F07FEF (DPOTRS).
On exit: the improved solution matrix X.
11:   LDX – INTEGERInput
On entry: the first dimension of the array X as declared in the (sub)program from which F07FHF (DPORFS) is called.
Constraint: LDX≥max 1,N.
12:   FERR NRHS – REAL (KIND=nag_wp) arrayOutput
On exit: FERR j contains an estimated error bound for the jth solution vector, that is, the jth column of X, for j=1,2,…,r.
13:   BERR NRHS – REAL (KIND=nag_wp) arrayOutput
On exit: BERR j contains the component-wise backward error bound β for the jth solution vector, that is, the jth column of X, for j=1,2,…,r.
14:   WORK 3×N – REAL (KIND=nag_wp) arrayWorkspace
15:   IWORK N – INTEGER arrayWorkspace
16:   INFO – INTEGEROutput
On exit: INFO=0 unless the routine detects an error (see Section 6).

6 Error Indicators and Warnings

INFO<0
If INFO=-i, argument i had an illegal value. An explanatory message is output, and execution of the program is terminated.

7 Accuracy

The bounds returned in FERR are not rigorous, because they are estimated, not computed exactly; but in practice they almost always overestimate the actual error.

8 Parallelism and Performance

F07FHF (DPORFS) is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
F07FHF (DPORFS) makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

For each right-hand side, computation of the backward error involves a minimum of 4⁢n 2 floating-point operations. Each step of iterative refinement involves an additional 6⁢n 2 operations. At most five steps of iterative refinement are performed, but usually only one or two steps are required.
Estimating the forward error involves solving a number of systems of linear equations of the form Ax=b; the number is usually 4 or 5 and never more than 11. Each solution involves approximately 2⁢n 2 operations.
The complex analogue of this routine is F07FVF (ZPORFS).

10 Example

This example solves the system of equations AX=B using iterative refinement and to compute the forward and backward error bounds, where
A= 4.16 -3.12 0.56 -0.10 -3.12 5.03 -0.83 1.18 0.56 -0.83 0.76 0.34 -0.10 1.18 0.34 1.18   and   B= 8.70 8.30 -13.35 2.13 1.89 1.61 -4.14 5.00 .
Here A is symmetric positive definite and must first be factorized by F07FDF (DPOTRF).

10.1 Program Text

Program Text (f07fhfe.f90)

10.2 Program Data

Program Data (f07fhfe.d)

10.3 Program Results

Program Results (f07fhfe.r)

F07 Chapter Contents
F07 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F07FJF (DPOTRI) : NAG Library, Mark 26

F07 Chapter Contents
F07 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F07FJF (DPOTRI)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F07FJF (DPOTRI) computes the inverse of a real symmetric positive definite matrix A, where A has been factorized by F07FDF (DPOTRF).

2 Specification

SUBROUTINE F07FJF ( UPLO, N, A, LDA, INFO)
INTEGER | N, LDA, INFO
REAL (KIND=nag_wp) | A(LDA,*)
CHARACTER(1) | UPLO
The routine may be called by its LAPACK name dpotri.

3 Description

F07FJF (DPOTRI) is used to compute the inverse of a real symmetric positive definite matrix A, the routine must be preceded by a call to F07FDF (DPOTRF), which computes the Cholesky factorization of A.
If UPLO='U', A=UT U and A-1 is computed by first inverting U and then forming U-1 U-T.
If UPLO='L', A=L LT and A-1 is computed by first inverting L and then forming L-T L-1.

4 References

Du Croz J J and Higham N J (1992) Stability of methods for matrix inversion IMA J. Numer. Anal. 12 1–19

5 Arguments

1:   UPLO – CHARACTER(1)Input
On entry: specifies how A has been factorized.
UPLO='U'
A=UT U, where U is upper triangular.
UPLO='L'
A=L LT, where L is lower triangular.
Constraint: UPLO='U' or 'L'.
2:   N – INTEGERInput
On entry: n, the order of the matrix A.
Constraint: N≥0.
3:   A LDA* – REAL (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array A must be at least max 1,N.
On entry: the upper triangular matrix U if UPLO='U' or the lower triangular matrix L if UPLO='L', as returned by F07FDF (DPOTRF).
On exit: U is overwritten by the upper triangle of A-1 if UPLO='U'; L is overwritten by the lower triangle of A-1 if UPLO='L'.
4:   LDA – INTEGERInput
On entry: the first dimension of the array A as declared in the (sub)program from which F07FJF (DPOTRI) is called.
Constraint: LDA≥max 1,N.
5:   INFO – INTEGEROutput
On exit: INFO=0 unless the routine detects an error (see Section 6).

6 Error Indicators and Warnings

INFO<0
If INFO=-i, argument i had an illegal value. An explanatory message is output, and execution of the program is terminated.
INFO>0
Diagonal element value of the Cholesky factor is zero; the Cholesky factor is singular and the inverse of A cannot be computed.

7 Accuracy

The computed inverse X satisfies
XA-I 2≤c n ε κ 2 A   and   AX-I 2≤c n ε κ 2 A ,
where c n is a modest function of n, ε is the machine precision and κ 2 A is the condition number of A defined by
κ 2 A=A 2A-1 2 .

8 Parallelism and Performance

F07FJF (DPOTRI) makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The total number of floating-point operations is approximately 23 n 3.
The complex analogue of this routine is F07FWF (ZPOTRI).

10 Example

This example computes the inverse of the matrix A, where
A= 4.16 -3.12 0.56 -0.10 -3.12 5.03 -0.83 1.18 0.56 -0.83 0.76 0.34 -0.10 1.18 0.34 1.18 .
Here A is symmetric positive definite and must first be factorized by F07FDF (DPOTRF).

10.1 Program Text

Program Text (f07fjfe.f90)

10.2 Program Data

Program Data (f07fjfe.d)

10.3 Program Results

Program Results (f07fjfe.r)

F07 Chapter Contents
F07 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F07FNF (ZPOSV) : NAG Library, Mark 26

F07 Chapter Contents
F07 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F07FNF (ZPOSV)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F07FNF (ZPOSV) computes the solution to a complex system of linear equations
AX=B ,
where A is an n by n Hermitian positive definite matrix and X and B are n by r matrices.

2 Specification

SUBROUTINE F07FNF ( UPLO, N, NRHS, A, LDA, B, LDB, INFO)
INTEGER | N, NRHS, LDA, LDB, INFO
COMPLEX (KIND=nag_wp) | A(LDA,*), B(LDB,*)
CHARACTER(1) | UPLO
The routine may be called by its LAPACK name zposv.

3 Description

F07FNF (ZPOSV) uses the Cholesky decomposition to factor A as A=UH U if UPLO='U' or A=L LH if UPLO='L', where U is an upper triangular matrix and L is a lower triangular matrix. The factored form of A is then used to solve the system of equations AX=B.

4 References

Anderson E, Bai Z, Bischof C, Blackford S, Demmel J, Dongarra J J, Du Croz J J, Greenbaum A, Hammarling S, McKenney A and Sorensen D (1999) LAPACK Users' Guide (3rd Edition) SIAM, Philadelphia http://www.netlib.org/lapack/lug
Golub G H and Van Loan C F (1996) Matrix Computations (3rd Edition) Johns Hopkins University Press, Baltimore

5 Arguments

1:   UPLO – CHARACTER(1)Input
On entry: if UPLO='U', the upper triangle of A is stored.
If UPLO='L', the lower triangle of A is stored.
Constraint: UPLO='U' or 'L'.
2:   N – INTEGERInput
On entry: n, the number of linear equations, i.e., the order of the matrix A.
Constraint: N≥0.
3:   NRHS – INTEGERInput
On entry: r, the number of right-hand sides, i.e., the number of columns of the matrix B.
Constraint: NRHS≥0.
4:   A LDA* – COMPLEX (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array A must be at least max 1,N.
On entry: the n by n Hermitian matrix A.
  • If UPLO='U', the upper triangular part of A must be stored and the elements of the array below the diagonal are not referenced.
  • If UPLO='L', the lower triangular part of A must be stored and the elements of the array above the diagonal are not referenced.
On exit: if INFO=0, the factor U or L from the Cholesky factorization A=UH U or A=L LH.
5:   LDA – INTEGERInput
On entry: the first dimension of the array A as declared in the (sub)program from which F07FNF (ZPOSV) is called.
Constraint: LDA≥max 1,N.
6:   B LDB* – COMPLEX (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array B must be at least max 1,NRHS.
To solve the equations Ax=b, where b is a single right-hand side, B may be supplied as a one-dimensional array with length LDB=max 1,N.
On entry: the n by r right-hand side matrix B.
On exit: if INFO=0, the n by r solution matrix X.
7:   LDB – INTEGERInput
On entry: the first dimension of the array B as declared in the (sub)program from which F07FNF (ZPOSV) is called.
Constraint: LDB≥max 1,N.
8:   INFO – INTEGEROutput
On exit: INFO=0 unless the routine detects an error (see Section 6).

6 Error Indicators and Warnings

INFO<0
If INFO=-i, argument i had an illegal value. An explanatory message is output, and execution of the program is terminated.
INFO>0
The leading minor of order value of A is not positive definite, so the factorization could not be completed, and the solution has not been computed.

7 Accuracy

The computed solution for a single right-hand side, x^ , satisfies an equation of the form
A+E x^=b ,
where
E 1 = O ε A 1
and ε is the machine precision. An approximate error bound for the computed solution is given by
x^-x 1 x 1 ≤ κ A E 1 A 1 ,
where κ A = A-1 1 A 1 , the condition number of A with respect to the solution of the linear equations. See Section 4.4 of Anderson et al. (1999) for further details.
F07FPF (ZPOSVX) is a comprehensive LAPACK driver that returns forward and backward error bounds and an estimate of the condition number. Alternatively, F04CDF solves Ax=b and returns a forward error bound and condition estimate. F04CDF calls F07FNF (ZPOSV) to solve the equations.

8 Parallelism and Performance

F07FNF (ZPOSV) is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
F07FNF (ZPOSV) makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The total number of floating-point operations is approximately 43 n 3 + 8⁢n 2 r , where r is the number of right-hand sides.
The real analogue of this routine is F07FAF (DPOSV).

10 Example

This example solves the equations
Ax=b ,
where A is the symmetric positive definite matrix
A = 3.23 i+0.00 1.51-1.92 i 1.90+0.84 i 0.42+2.50 i 1.51+1.92 i 3.58 i+0.00 -0.23+1.11 i -1.18+1.37 i 1.90-0.84 i -0.23-1.11 i 4.09 i+0.00 2.33-0.14 i 0.42-2.50 i -1.18-1.37 i 2.33+0.14 i 4.29 i+0.00
and
b = 3.93-0 6.14 i 6.17+0 9.42 i -7.17-21.83 i 1.99-14.38 i .
Details of the Cholesky factorization of A are also output.

10.1 Program Text

Program Text (f07fnfe.f90)

10.2 Program Data

Program Data (f07fnfe.d)

10.3 Program Results

Program Results (f07fnfe.r)

F07 Chapter Contents
F07 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F07FPF (ZPOSVX) : NAG Library, Mark 26

F07 Chapter Contents
F07 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F07FPF (ZPOSVX)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F07FPF (ZPOSVX) uses the Cholesky factorization
A=UH U   or   A=L LH
to compute the solution to a complex system of linear equations
AX=B ,
where A is an n by n Hermitian positive definite matrix and X and B are n by r matrices. Error bounds on the solution and a condition estimate are also provided.

2 Specification

SUBROUTINE F07FPF ( FACT, UPLO, N, NRHS, A, LDA, AF, LDAF, EQUED, S, B, LDB, X, LDX, RCOND, FERR, BERR, WORK, RWORK, INFO)
INTEGER | N, NRHS, LDA, LDAF, LDB, LDX, INFO
REAL (KIND=nag_wp) | S(*), RCOND, FERR(NRHS), BERR(NRHS), RWORK(N)
COMPLEX (KIND=nag_wp) | A(LDA,*), AF(LDAF,*), B(LDB,*), X(LDX,*), WORK(2*N)
CHARACTER(1) | FACT, UPLO, EQUED
The routine may be called by its LAPACK name zposvx.

3 Description

F07FPF (ZPOSVX) performs the following steps:
1. If FACT='E', real diagonal scaling factors, DS , are computed to equilibrate the system:
DS A DS DS-1 X = DS B .
Whether or not the system will be equilibrated depends on the scaling of the matrix A, but if equilibration is used, A is overwritten by DS A DS and B by DS B.
2. | If FACT='N' or 'E', the Cholesky decomposition is used to factor the matrix A (after equilibration if FACT='E') as A=UH U if UPLO='U' or A=L LH if UPLO='L', where U is an upper triangular matrix and L is a lower triangular matrix.
3. | If the leading i by i principal minor of A is not positive definite, then the routine returns with INFO=i. Otherwise, the factored form of A is used to estimate the condition number of the matrix A. If the reciprocal of the condition number is less than machine precision, INFO=N+1 is returned as a warning, but the routine still goes on to solve for X and compute error bounds as described below.
4. | The system of equations is solved for X using the factored form of A.
5. | Iterative refinement is applied to improve the computed solution matrix and to calculate error bounds and backward error estimates for it.
6. | If equilibration was used, the matrix X is premultiplied by DS so that it solves the original system before equilibration.

4 References

Anderson E, Bai Z, Bischof C, Blackford S, Demmel J, Dongarra J J, Du Croz J J, Greenbaum A, Hammarling S, McKenney A and Sorensen D (1999) LAPACK Users' Guide (3rd Edition) SIAM, Philadelphia http://www.netlib.org/lapack/lug
Golub G H and Van Loan C F (1996) Matrix Computations (3rd Edition) Johns Hopkins University Press, Baltimore
Higham N J (2002) Accuracy and Stability of Numerical Algorithms (2nd Edition) SIAM, Philadelphia

5 Arguments

1:   FACT – CHARACTER(1)Input
On entry: specifies whether or not the factorized form of the matrix A is supplied on entry, and if not, whether the matrix A should be equilibrated before it is factorized.
FACT='F'
AF contains the factorized form of A. If EQUED='Y', the matrix A has been equilibrated with scaling factors given by S. A and AF will not be modified.
FACT='N'
The matrix A will be copied to AF and factorized.
FACT='E'
The matrix A will be equilibrated if necessary, then copied to AF and factorized.
Constraint: FACT='F', 'N' or 'E'.
2:   UPLO – CHARACTER(1)Input
On entry: if UPLO='U', the upper triangle of A is stored.
If UPLO='L', the lower triangle of A is stored.
Constraint: UPLO='U' or 'L'.
3:   N – INTEGERInput
On entry: n, the number of linear equations, i.e., the order of the matrix A.
Constraint: N≥0.
4:   NRHS – INTEGERInput
On entry: r, the number of right-hand sides, i.e., the number of columns of the matrix B.
Constraint: NRHS≥0.
5:   A LDA* – COMPLEX (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array A must be at least max 1,N.
On entry: the n by n Hermitian matrix A.
If FACT='F' and EQUED='Y', A must have been equilibrated by the scaling factor in S as DS A DS.
  • If UPLO='U', the upper triangular part of A must be stored and the elements of the array below the diagonal are not referenced.
  • If UPLO='L', the lower triangular part of A must be stored and the elements of the array above the diagonal are not referenced.
On exit: if FACT='F' or 'N', or if FACT='E' and EQUED='N', A is not modified.
If FACT='E' and EQUED='Y', A is overwritten by DS A DS.
6:   LDA – INTEGERInput
On entry: the first dimension of the array A as declared in the (sub)program from which F07FPF (ZPOSVX) is called.
Constraint: LDA≥max 1,N.
7:   AF LDAF* – COMPLEX (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array AF must be at least max 1,N.
On entry: if FACT='F', AF contains the triangular factor U or L from the Cholesky factorization A=UH U or A=L LH, in the same storage format as A. If EQUED≠'N', AF is the factorized form of the equilibrated matrix DS A DS.
On exit: if FACT='N', AF returns the triangular factor U or L from the Cholesky factorization A=UH U or A=L LH of the original matrix A.
If FACT='E', AF returns the triangular factor U or L from the Cholesky factorization A=UH U or A=L LH of the equilibrated matrix A (see the description of A for the form of the equilibrated matrix).
8:   LDAF – INTEGERInput
On entry: the first dimension of the array AF as declared in the (sub)program from which F07FPF (ZPOSVX) is called.
Constraint: LDAF≥max 1,N.
9:   EQUED – CHARACTER(1)Input/Output
On entry: if FACT='N' or 'E', EQUED need not be set.
If FACT='F', EQUED must specify the form of the equilibration that was performed as follows:
  • if EQUED='N', no equilibration;
  • if EQUED='Y', equilibration was performed, i.e., A has been replaced by DS A DS.
On exit: if FACT='F', EQUED is unchanged from entry.
Otherwise, if no constraints are violated, EQUED specifies the form of the equilibration that was performed as specified above.
Constraint: if FACT='F', EQUED='N' or 'Y'.
10:   S* – REAL (KIND=nag_wp) arrayInput/Output
Note: the dimension of the array S must be at least max 1,N.
On entry: if FACT='N' or 'E', S need not be set.
If FACT='F' and EQUED='Y', S must contain the scale factors, DS, for A; each element of S must be positive.
On exit: if FACT='F', S is unchanged from entry.
Otherwise, if no constraints are violated and EQUED='Y', S contains the scale factors, DS, for A; each element of S is positive.
11:   B LDB* – COMPLEX (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array B must be at least max 1,NRHS.
On entry: the n by r right-hand side matrix B.
On exit: if EQUED='N', B is not modified.
If EQUED='Y', B is overwritten by DS B.
12:   LDB – INTEGERInput
On entry: the first dimension of the array B as declared in the (sub)program from which F07FPF (ZPOSVX) is called.
Constraint: LDB≥max 1,N.
13:   X LDX* – COMPLEX (KIND=nag_wp) arrayOutput
Note: the second dimension of the array X must be at least max 1,NRHS.
On exit: if INFO=0 or N+1, the n by r solution matrix X to the original system of equations. Note that the arrays A and B are modified on exit if EQUED='Y', and the solution to the equilibrated system is DS-1 X.
14:   LDX – INTEGERInput
On entry: the first dimension of the array X as declared in the (sub)program from which F07FPF (ZPOSVX) is called.
Constraint: LDX≥max 1,N.
15:   RCOND – REAL (KIND=nag_wp)Output
On exit: if no constraints are violated, an estimate of the reciprocal condition number of the matrix A (after equilibration if that is performed), computed as RCOND=1.0/A 1 A-1 1 .
16:   FERR NRHS – REAL (KIND=nag_wp) arrayOutput
On exit: if INFO=0 or N+1, an estimate of the forward error bound for each computed solution vector, such that x^j-xj∞/xj∞≤FERR j where x^j is the jth column of the computed solution returned in the array X and xj is the corresponding column of the exact solution X. The estimate is as reliable as the estimate for RCOND, and is almost always a slight overestimate of the true error.
17:   BERR NRHS – REAL (KIND=nag_wp) arrayOutput
On exit: if INFO=0 or N+1, an estimate of the component-wise relative backward error of each computed solution vector x^j (i.e., the smallest relative change in any element of A or B that makes x^j an exact solution).
18:   WORK 2×N – COMPLEX (KIND=nag_wp) arrayWorkspace
19:   RWORK N – REAL (KIND=nag_wp) arrayWorkspace
20:   INFO – INTEGEROutput
On exit: INFO=0 unless the routine detects an error (see Section 6).

6 Error Indicators and Warnings

INFO<0
If INFO=-i, argument i had an illegal value. An explanatory message is output, and execution of the program is terminated.
INFO>0 and INFO≤N
The leading minor of order value of A is not positive definite, so the factorization could not be completed, and the solution has not been computed. RCOND=0.0 is returned.
INFO=N+1
U (or L) is nonsingular, but RCOND is less than machine precision, meaning that the matrix is singular to working precision. Nevertheless, the solution and error bounds are computed because there are a number of situations where the computed solution can be more accurate than the value of RCOND would suggest.

7 Accuracy

For each right-hand side vector b, the computed solution x is the exact solution of a perturbed system of equations A+E x=b, where
  • if UPLO='U', E≤c n ε UHU;
  • if UPLO='L', E≤c n ε LLH,
c n is a modest linear function of n, and ε is the machine precision. See Section 10.1 of Higham (2002) for further details.
If x^ is the true solution, then the computed solution x satisfies a forward error bound of the form
x-x^∞ x^∞ ≤ wc cond A,x^,b
where cond A,x^,b = A-1 A x^ + b ∞/ x^∞ ≤ cond A = A-1 A ∞≤κ∞ A. If x^ is the j th column of X , then wc is returned in BERR j and a bound on x - x^ ∞ / x^ ∞ is returned in FERR j . See Section 4.4 of Anderson et al. (1999) for further details.

8 Parallelism and Performance

F07FPF (ZPOSVX) is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
F07FPF (ZPOSVX) makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The factorization of A requires approximately 43 n 3 floating-point operations.
For each right-hand side, computation of the backward error involves a minimum of 16⁢n 2 floating-point operations. Each step of iterative refinement involves an additional 24⁢n 2 operations. At most five steps of iterative refinement are performed, but usually only one or two steps are required. Estimating the forward error involves solving a number of systems of equations of the form Ax=b ; the number is usually 4 or 5 and never more than 11. Each solution involves approximately 8⁢n 2 operations.
The real analogue of this routine is F07FBF (DPOSVX).

10 Example

This example solves the equations
AX=B ,
where A is the Hermitian positive definite matrix
A = 3.23 i+0.00 1.51-1.92 i 1.90+0.84 i 0.42+2.50 i 1.51+1.92 i 3.58 i+0.00 -0.23+1.11 i -1.18+1.37 i 1.90-0.84 i -0.23-1.11 i 4.09 i+0.00 2.33-0.14 i 0.42-2.50 i -1.18-1.37 i 2.33+0.14 i 4.29 i+0.00
and
B = 3.93-0 6.14 i 1.48+0 6.58 i 6.17+0 9.42 i 4.64-0 4.75 i -7.17-21.83 i -4.91+0 2.29 i 1.99-14.38 i 7.64-10.79 i .
Error estimates for the solutions, information on equilibration and an estimate of the reciprocal of the condition number of the scaled matrix A are also output.

10.1 Program Text

Program Text (f07fpfe.f90)

10.2 Program Data

Program Data (f07fpfe.d)

10.3 Program Results

Program Results (f07fpfe.r)

F07 Chapter Contents
F07 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F07FQF (ZCPOSV) : NAG Library, Mark 26

F07 Chapter Contents
F07 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F07FQF (ZCPOSV)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F07FQF (ZCPOSV) uses the Cholesky factorization
A=UH U   or   A=L LH
to compute the solution to a complex system of linear equations
AX=B ,
where A is an n by n Hermitian positive definite matrix and X and B are n by r matrices.

2 Specification

SUBROUTINE F07FQF ( UPLO, N, NRHS, A, LDA, B, LDB, X, LDX, WORK, SWORK, RWORK, ITER, INFO)
INTEGER | N, NRHS, LDA, LDB, LDX, ITER, INFO
REAL (KIND=nag_wp) | RWORK(N)
COMPLEX (KIND=nag_wp) | A(LDA,*), B(LDB,*), X(LDX,*), WORK(N,NRHS)
COMPLEX (KIND=nag_rp) | SWORK(N*(N+NRHS))
CHARACTER(1) | UPLO
The routine may be called by its LAPACK name zcposv.

3 Description

F07FQF (ZCPOSV) first attempts to factorize the matrix in reduced precision and use this factorization within an iterative refinement procedure to produce a solution with full precision normwise backward error quality (see below). If the approach fails the method switches to a full precision factorization and solve.
The iterative refinement can be more efficient than the corresponding direct full precision algorithm. Since the strategy implemented by F07FQF (ZCPOSV) must perform iterative refinement on each right-hand side, any efficiency gains will reduce as the number of right-hand sides increases. Conversely, as the matrix size increases the cost of these iterative refinements become less significant relative to the cost of factorization. Thus, any efficiency gains will be greatest for a very small number of right-hand sides and for large matrix sizes. The cut-off values for the number of right-hand sides and matrix size, for which the iterative refinement strategy performs better, depends on the relative performance of the reduced and full precision factorization and back-substitution. F07FQF (ZCPOSV) always attempts the iterative refinement strategy first; you are advised to compare the performance of F07FQF (ZCPOSV) with that of its full precision counterpart F07FNF (ZPOSV) to determine whether this strategy is worthwhile for your particular problem dimensions.
The iterative refinement process is stopped if ITER>30 where ITER is the number of iterations carried out thus far. The process is also stopped if for all right-hand sides we have
resid < N x A ε ,
where resid is the ∞-norm of the residual, x is the ∞-norm of the solution, A is the ∞-norm of the matrix A and ε is the machine precision returned by X02AJF.

4 References

Anderson E, Bai Z, Bischof C, Blackford S, Demmel J, Dongarra J J, Du Croz J J, Greenbaum A, Hammarling S, McKenney A and Sorensen D (1999) LAPACK Users' Guide (3rd Edition) SIAM, Philadelphia http://www.netlib.org/lapack/lug
Golub G H and Van Loan C F (1996) Matrix Computations (3rd Edition) Johns Hopkins University Press, Baltimore
Higham N J (2002) Accuracy and Stability of Numerical Algorithms (2nd Edition) SIAM, Philadelphia

5 Arguments

1:   UPLO – CHARACTER(1)Input
On entry: specifies whether the upper or lower triangular part of A is stored.
UPLO='U'
The upper triangular part of A is stored.
UPLO='L'
The lower triangular part of A is stored.
Constraint: UPLO='U' or 'L'.
2:   N – INTEGERInput
On entry: n, the number of linear equations, i.e., the order of the matrix A.
Constraint: N≥0.
3:   NRHS – INTEGERInput
On entry: r, the number of right-hand sides, i.e., the number of columns of the matrix B.
Constraint: NRHS≥0.
4:   A LDA* – COMPLEX (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array A must be at least max 1,N.
On entry: the n by n Hermitian positive definite matrix A.
  • If UPLO='U', the upper triangular part of A must be stored and the elements of the array below the diagonal are not referenced.
  • If UPLO='L', the lower triangular part of A must be stored and the elements of the array above the diagonal are not referenced.
On exit: if iterative refinement has been successfully used (INFO=0 and ITER≥0, see description below), then A is unchanged. If full precision factorization has been used (INFO=0 and ITER<0, see description below), then the array A contains the factor U or L from the Cholesky factorization A=UH U or A=L LH.
5:   LDA – INTEGERInput
On entry: the first dimension of the array A as declared in the (sub)program from which F07FQF (ZCPOSV) is called.
Constraint: LDA≥max 1,N.
6:   B LDB* – COMPLEX (KIND=nag_wp) arrayInput
Note: the second dimension of the array B must be at least max 1,NRHS.
On entry: the right-hand side matrix B.
7:   LDB – INTEGERInput
On entry: the first dimension of the array B as declared in the (sub)program from which F07FQF (ZCPOSV) is called.
Constraint: LDB≥max 1,N.
8:   X LDX* – COMPLEX (KIND=nag_wp) arrayOutput
Note: the second dimension of the array X must be at least max 1,NRHS.
On exit: if INFO=0, the n by r solution matrix X.
9:   LDX – INTEGERInput
On entry: the first dimension of the array X as declared in the (sub)program from which F07FQF (ZCPOSV) is called.
Constraint: LDX≥max 1,N.
10:   WORK NNRHS – COMPLEX (KIND=nag_wp) arrayWorkspace
11:   SWORK N×N+NRHS – COMPLEX (KIND=nag_rp) arrayWorkspace
Note: this array is utilized in the reduced precision computation, consequently its type nag_rp reflects this usage.
12:   RWORK N – REAL (KIND=nag_wp) arrayWorkspace
13:   ITER – INTEGEROutput
On exit: information on the progress of the interative refinement process.
ITER<0
Iterative refinement has failed for one of the reasons given below, full precision factorization has been performed instead.
-1 | The routine fell back to full precision for implementation- or machine-specific reasons.
-2 | Narrowing the precision induced an overflow, the routine fell back to full precision.
-3 | An intermediate reduced precision factorization failed.
-31 | The maximum permitted number of iterations was exceeded.
ITER>0
Iterative refinement has been sucessfully used. ITER returns the number of iterations.
14:   INFO – INTEGEROutput
On exit: INFO=0 unless the routine detects an error (see Section 6).

6 Error Indicators and Warnings

INFO<0
If INFO=-i, argument i had an illegal value. An explanatory message is output, and execution of the program is terminated.
INFO>0 and INFO≤N
The leading minor of order value of A is not positive definite, so the factorization could not be completed, and the solution has not been computed.

7 Accuracy

For each right-hand side vector b, the computed solution x is the exact solution of a perturbed system of equations A+E x=b, where
  • if UPLO='U', E≤c n ε UHU;
  • if UPLO='L', E≤c n ε LLH,
c n is a modest linear function of n, and ε is the machine precision. See Section 10.1 of Higham (2002) for further details.
An approximate error bound for the computed solution is given by
x^ - x 1 x 1 ≤ κ A E 1 A 1
where κ A = A-1 1 A 1 , the condition number of A with respect to the solution of the linear equations. See Section 4.4 of Anderson et al. (1999) for further details.

8 Parallelism and Performance

F07FQF (ZCPOSV) is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
F07FQF (ZCPOSV) makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The real analogue of this routine is F07FCF (DSPOSV).

10 Example

This example solves the equations
AX=B ,
where A is the Hermitian positive definite matrix
A = 3.23 i+0.00 1.51-1.92 i 1.90+0.84 i 0.42+2.50 i 1.51+1.92 i 3.58 i+0.00 -0.23+1.11 i -1.18+1.37 i 1.90-0.84 i -0.23-1.11 i 4.09 i+0.00 2.33-0.14 i 0.42-2.50 i -1.18-1.37 i 2.33+0.14 i 4.29 i+0.00
and
B = 3.93-0 6.14 i 6.17+0 9.42 i -7.17-21.83 i 1.99-14.38 i .

10.1 Program Text

Program Text (f07fqfe.f90)

10.2 Program Data

Program Data (f07fqfe.d)

10.3 Program Results

Program Results (f07fqfe.r)

F07 Chapter Contents
F07 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F07FRF (ZPOTRF) : NAG Library, Mark 26

F07 Chapter Contents
F07 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F07FRF (ZPOTRF)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F07FRF (ZPOTRF) computes the Cholesky factorization of a complex Hermitian positive definite matrix.

2 Specification

SUBROUTINE F07FRF ( UPLO, N, A, LDA, INFO)
INTEGER | N, LDA, INFO
COMPLEX (KIND=nag_wp) | A(LDA,*)
CHARACTER(1) | UPLO
The routine may be called by its LAPACK name zpotrf.

3 Description

F07FRF (ZPOTRF) forms the Cholesky factorization of a complex Hermitian positive definite matrix A either as A=UH U if UPLO='U' or A=L LH if UPLO='L', where U is an upper triangular matrix and L is lower triangular.

4 References

Demmel J W (1989) On floating-point errors in Cholesky LAPACK Working Note No. 14 University of Tennessee, Knoxville http://www.netlib.org/lapack/lawnspdf/lawn14.pdf
Golub G H and Van Loan C F (1996) Matrix Computations (3rd Edition) Johns Hopkins University Press, Baltimore

5 Arguments

1:   UPLO – CHARACTER(1)Input
On entry: specifies whether the upper or lower triangular part of A is stored and how A is to be factorized.
UPLO='U'
The upper triangular part of A is stored and A is factorized as UH U, where U is upper triangular.
UPLO='L'
The lower triangular part of A is stored and A is factorized as L LH, where L is lower triangular.
Constraint: UPLO='U' or 'L'.
2:   N – INTEGERInput
On entry: n, the order of the matrix A.
Constraint: N≥0.
3:   A LDA* – COMPLEX (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array A must be at least max 1,N.
On entry: the n by n Hermitian positive definite matrix A.
  • If UPLO='U', the upper triangular part of A must be stored and the elements of the array below the diagonal are not referenced.
  • If UPLO='L', the lower triangular part of A must be stored and the elements of the array above the diagonal are not referenced.
On exit: the upper or lower triangle of A is overwritten by the Cholesky factor U or L as specified by UPLO.
4:   LDA – INTEGERInput
On entry: the first dimension of the array A as declared in the (sub)program from which F07FRF (ZPOTRF) is called.
Constraint: LDA≥max 1,N.
5:   INFO – INTEGEROutput
On exit: INFO=0 unless the routine detects an error (see Section 6).

6 Error Indicators and Warnings

INFO<0
If INFO=-i, argument i had an illegal value. An explanatory message is output, and execution of the program is terminated.
INFO>0
The leading minor of order value is not positive definite and the factorization could not be completed. Hence A itself is not positive definite. This may indicate an error in forming the matrix A. To factorize a Hermitian matrix which is not positive definite, call F07MRF (ZHETRF) instead.

7 Accuracy

If UPLO='U', the computed factor U is the exact factor of a perturbed matrix A+E, where
E≤c n ε UHU ,
c n is a modest linear function of n, and ε is the machine precision. If UPLO='L', a similar statement holds for the computed factor L. It follows that e ij≤c n ε⁢a iia jj.

8 Parallelism and Performance

F07FRF (ZPOTRF) is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
F07FRF (ZPOTRF) makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The total number of real floating-point operations is approximately 43 n 3.
A call to F07FRF (ZPOTRF) may be followed by calls to the routines:
  • F07FSF (ZPOTRS) to solve AX=B;
  • F07FUF (ZPOCON) to estimate the condition number of A;
  • F07FWF (ZPOTRI) to compute the inverse of A.
The real analogue of this routine is F07FDF (DPOTRF).

10 Example

This example computes the Cholesky factorization of the matrix A, where
A= 3.23+0.00 i 1.51-1.92 i 1.90+0.84 i 0.42+2.50 i 1.51+1.92 i 3.58+0.00 i -0.23+1.11 i -1.18+1.37 i 1.90-0.84 i -0.23-1.11 i 4.09+0.00 i 2.33-0.14 i 0.42-2.50 i -1.18-1.37 i 2.33+0.14 i 4.29+0.00 i .

10.1 Program Text

Program Text (f07frfe.f90)

10.2 Program Data

Program Data (f07frfe.d)

10.3 Program Results

Program Results (f07frfe.r)

F07 Chapter Contents
F07 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F07FSF (ZPOTRS) : NAG Library, Mark 26

F07 Chapter Contents
F07 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F07FSF (ZPOTRS)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F07FSF (ZPOTRS) solves a complex Hermitian positive definite system of linear equations with multiple right-hand sides,
AX=B ,
where A has been factorized by F07FRF (ZPOTRF).

2 Specification

SUBROUTINE F07FSF ( UPLO, N, NRHS, A, LDA, B, LDB, INFO)
INTEGER | N, NRHS, LDA, LDB, INFO
COMPLEX (KIND=nag_wp) | A(LDA,*), B(LDB,*)
CHARACTER(1) | UPLO
The routine may be called by its LAPACK name zpotrs.

3 Description

F07FSF (ZPOTRS) is used to solve a complex Hermitian positive definite system of linear equations AX=B, this routine must be preceded by a call to F07FRF (ZPOTRF) which computes the Cholesky factorization of A. The solution X is computed by forward and backward substitution.
If UPLO='U', A=UH U, where U is upper triangular; the solution X is computed by solving UH Y=B and then UX=Y.
If UPLO='L', A=L LH, where L is lower triangular; the solution X is computed by solving LY=B and then LH X=Y.

4 References

Golub G H and Van Loan C F (1996) Matrix Computations (3rd Edition) Johns Hopkins University Press, Baltimore

5 Arguments

1:   UPLO – CHARACTER(1)Input
On entry: specifies how A has been factorized.
UPLO='U'
A=UH U, where U is upper triangular.
UPLO='L'
A=L LH, where L is lower triangular.
Constraint: UPLO='U' or 'L'.
2:   N – INTEGERInput
On entry: n, the order of the matrix A.
Constraint: N≥0.
3:   NRHS – INTEGERInput
On entry: r, the number of right-hand sides.
Constraint: NRHS≥0.
4:   A LDA* – COMPLEX (KIND=nag_wp) arrayInput
Note: the second dimension of the array A must be at least max 1,N.
On entry: the Cholesky factor of A, as returned by F07FRF (ZPOTRF).
5:   LDA – INTEGERInput
On entry: the first dimension of the array A as declared in the (sub)program from which F07FSF (ZPOTRS) is called.
Constraint: LDA≥max 1,N.
6:   B LDB* – COMPLEX (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array B must be at least max 1,NRHS.
On entry: the n by r right-hand side matrix B.
On exit: the n by r solution matrix X.
7:   LDB – INTEGERInput
On entry: the first dimension of the array B as declared in the (sub)program from which F07FSF (ZPOTRS) is called.
Constraint: LDB≥max 1,N.
8:   INFO – INTEGEROutput
On exit: INFO=0 unless the routine detects an error (see Section 6).

6 Error Indicators and Warnings

INFO<0
If INFO=-i, argument i had an illegal value. An explanatory message is output, and execution of the program is terminated.

7 Accuracy

For each right-hand side vector b, the computed solution x is the exact solution of a perturbed system of equations A+E x=b, where
  • if UPLO='U', E≤c n ε UHU;
  • if UPLO='L', E≤c n ε LLH,
c n is a modest linear function of n, and ε is the machine precision.
If x^ is the true solution, then the computed solution x satisfies a forward error bound of the form
x-x^∞ x∞ ≤c n cond A,x ε
where cond A,x=A-1Ax∞/x∞≤cond A=A-1A∞≤κ∞A.
Note that cond A,x can be much smaller than cond A.
Forward and backward error bounds can be computed by calling F07FVF (ZPORFS), and an estimate for κ∞A (=κ 1 A) can be obtained by calling F07FUF (ZPOCON).

8 Parallelism and Performance

F07FSF (ZPOTRS) is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
F07FSF (ZPOTRS) makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The total number of real floating-point operations is approximately 8⁢n 2 r.
This routine may be followed by a call to F07FVF (ZPORFS) to refine the solution and return an error estimate.
The real analogue of this routine is F07FEF (DPOTRS).

10 Example

This example solves the system of equations AX=B, where
A= 3.23+0.00 i 1.51-1.92 i 1.90+0.84 i 0.42+2.50 i 1.51+1.92 i 3.58+0.00 i -0.23+1.11 i -1.18+1.37 i 1.90-0.84 i -0.23-1.11 i 4.09+0.00 i 2.33-0.14 i 0.42-2.50 i -1.18-1.37 i 2.33+0.14 i 4.29+0.00 i
and
B= 3.93-0 6.14 i 1.48+0 6.58 i 6.17+0 9.42 i 4.65-0 4.75 i -7.17-21.83 i -4.91+0 2.29 i 1.99-14.38 i 7.64-10.79 i .
Here A is Hermitian positive definite and must first be factorized by F07FRF (ZPOTRF).

10.1 Program Text

Program Text (f07fsfe.f90)

10.2 Program Data

Program Data (f07fsfe.d)

10.3 Program Results

Program Results (f07fsfe.r)

F07 Chapter Contents
F07 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F07FTF (ZPOEQU) : NAG Library, Mark 26

F07 Chapter Contents
F07 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F07FTF (ZPOEQU)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F07FTF (ZPOEQU) computes a diagonal scaling matrix S intended to equilibrate a complex n by n Hermitian positive definite matrix A and reduce its condition number.

2 Specification

SUBROUTINE F07FTF ( N, A, LDA, S, SCOND, AMAX, INFO)
INTEGER | N, LDA, INFO
REAL (KIND=nag_wp) | S(N), SCOND, AMAX
COMPLEX (KIND=nag_wp) | A(LDA,*)
The routine may be called by its LAPACK name zpoequ.

3 Description

F07FTF (ZPOEQU) computes a diagonal scaling matrix S chosen so that
sj=1 / a jj .
This means that the matrix B given by
B=SAS ,
has diagonal elements equal to unity. This in turn means that the condition number of B , κ 2 B , is within a factor n of the matrix of smallest possible condition number over all possible choices of diagonal scalings (see Corollary 7.6 of Higham (2002)).

4 References

Higham N J (2002) Accuracy and Stability of Numerical Algorithms (2nd Edition) SIAM, Philadelphia

5 Arguments

1:   N – INTEGERInput
On entry: n, the order of the matrix A.
Constraint: N≥0.
2:   A LDA* – COMPLEX (KIND=nag_wp) arrayInput
Note: the second dimension of the array A must be at least max 1,N.
On entry: the matrix A whose scaling factors are to be computed. Only the diagonal elements of the array A are referenced.
3:   LDA – INTEGERInput
On entry: the first dimension of the array A as declared in the (sub)program from which F07FTF (ZPOEQU) is called.
Constraint: LDA≥max 1,N.
4:   S N – REAL (KIND=nag_wp) arrayOutput
On exit: if INFO=0, S contains the diagonal elements of the scaling matrix S.
5:   SCOND – REAL (KIND=nag_wp)Output
On exit: if INFO=0, SCOND contains the ratio of the smallest value of S to the largest value of S. If SCOND≥0.1 and AMAX is neither too large nor too small, it is not worth scaling by S.
6:   AMAX – REAL (KIND=nag_wp)Output
On exit: max a ij. If AMAX is very close to overflow or underflow, the matrix A should be scaled.
7:   INFO – INTEGEROutput
On exit: INFO=0 unless the routine detects an error (see Section 6).

6 Error Indicators and Warnings

INFO<0
If INFO=-i, argument i had an illegal value. An explanatory message is output, and execution of the program is terminated.
INFO>0
The valueth diagonal element of A is not positive (and hence A cannot be positive definite).

7 Accuracy

The computed scale factors will be close to the exact scale factors.

8 Parallelism and Performance

F07FTF (ZPOEQU) is not threaded in any implementation.

9 Further Comments

The real analogue of this routine is F07FFF (DPOEQU).

10 Example

This example equilibrates the Hermitian positive definite matrix A given by
A = (3.23 -(1.51-1.92 i 1.90+0.84 i×10 5 0 -0.42+2.50 i (1.51+1.92 i -(3.58 -0.23+1.11 i×10 5 0 -1.18+1.37 i 1.90-0.84 i×105 -0.23-1.11 i×105 -4.09×1010 (2.33-0.14 i×105 (0.42-2.50 i (-1.18-1.37 i 2.33+0.14 i×10 5 0 -4.29 .
Details of the scaling factors and the scaled matrix are output.

10.1 Program Text

Program Text (f07ftfe.f90)

10.2 Program Data

Program Data (f07ftfe.d)

10.3 Program Results

Program Results (f07ftfe.r)

F07 Chapter Contents
F07 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F07FUF (ZPOCON) : NAG Library, Mark 26

F07 Chapter Contents
F07 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F07FUF (ZPOCON)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F07FUF (ZPOCON) estimates the condition number of a complex Hermitian positive definite matrix A, where A has been factorized by F07FRF (ZPOTRF).

2 Specification

SUBROUTINE F07FUF ( UPLO, N, A, LDA, ANORM, RCOND, WORK, RWORK, INFO)
INTEGER | N, LDA, INFO
REAL (KIND=nag_wp) | ANORM, RCOND, RWORK(N)
COMPLEX (KIND=nag_wp) | A(LDA,*), WORK(2*N)
CHARACTER(1) | UPLO
The routine may be called by its LAPACK name zpocon.

3 Description

F07FUF (ZPOCON) estimates the condition number (in the 1-norm) of a complex Hermitian positive definite matrix A:
κ 1 A=A 1A-1 1 .
Since A is Hermitian, κ 1 A=κ∞A=A∞A-1∞.
Because κ 1 A is infinite if A is singular, the routine actually returns an estimate of the reciprocal of κ 1 A.
The routine should be preceded by a call to F06UCF to compute A 1 and a call to F07FRF (ZPOTRF) to compute the Cholesky factorization of A. The routine then uses Higham's implementation of Hager's method (see Higham (1988)) to estimate A-1 1.

4 References

Higham N J (1988) FORTRAN codes for estimating the one-norm of a real or complex matrix, with applications to condition estimation ACM Trans. Math. Software 14 381–396

5 Arguments

1:   UPLO – CHARACTER(1)Input
On entry: specifies how A has been factorized.
UPLO='U'
A=UH U, where U is upper triangular.
UPLO='L'
A=L LH, where L is lower triangular.
Constraint: UPLO='U' or 'L'.
2:   N – INTEGERInput
On entry: n, the order of the matrix A.
Constraint: N≥0.
3:   A LDA* – COMPLEX (KIND=nag_wp) arrayInput
Note: the second dimension of the array A must be at least max 1,N.
On entry: the Cholesky factor of A, as returned by F07FRF (ZPOTRF).
4:   LDA – INTEGERInput
On entry: the first dimension of the array A as declared in the (sub)program from which F07FUF (ZPOCON) is called.
Constraint: LDA≥max 1,N.
5:   ANORM – REAL (KIND=nag_wp)Input
On entry: the 1-norm of the original matrix A, which may be computed by calling F06UCF with its argument NORM='1'. ANORM must be computed either before calling F07FRF (ZPOTRF) or else from a copy of the original matrix A.
Constraint: ANORM≥0.0.
6:   RCOND – REAL (KIND=nag_wp)Output
On exit: an estimate of the reciprocal of the condition number of A. RCOND is set to zero if exact singularity is detected or the estimate underflows. If RCOND is less than machine precision, A is singular to working precision.
7:   WORK 2×N – COMPLEX (KIND=nag_wp) arrayWorkspace
8:   RWORK N – REAL (KIND=nag_wp) arrayWorkspace
9:   INFO – INTEGEROutput
On exit: INFO=0 unless the routine detects an error (see Section 6).

6 Error Indicators and Warnings

INFO<0
If INFO=-i, argument i had an illegal value. An explanatory message is output, and execution of the program is terminated.

7 Accuracy

The computed estimate RCOND is never less than the true value ρ, and in practice is nearly always less than 10 ρ, although examples can be constructed where RCOND is much larger.

8 Parallelism and Performance

F07FUF (ZPOCON) makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

A call to F07FUF (ZPOCON) involves solving a number of systems of linear equations of the form Ax=b; the number is usually 5 and never more than 11. Each solution involves approximately 8⁢n 2 real floating-point operations but takes considerably longer than a call to F07FSF (ZPOTRS) with one right-hand side, because extra care is taken to avoid overflow when A is approximately singular.
The real analogue of this routine is F07FGF (DPOCON).

10 Example

This example estimates the condition number in the 1-norm (or ∞-norm) of the matrix A, where
A= 3.23+0.00 i 1.51-1.92 i 1.90+0.84 i 0.42+2.50 i 1.51+1.92 i 3.58+0.00 i -0.23+1.11 i -1.18+1.37 i 1.90-0.84 i -0.23-1.11 i 4.09+0.00 i 2.33-0.14 i 0.42-2.50 i -1.18-1.37 i 2.33+0.14 i 4.29+0.00 i .
Here A is Hermitian positive definite and must first be factorized by F07FRF (ZPOTRF). The true condition number in the 1-norm is 201.92.

10.1 Program Text

Program Text (f07fufe.f90)

10.2 Program Data

Program Data (f07fufe.d)

10.3 Program Results

Program Results (f07fufe.r)

F07 Chapter Contents
F07 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F07FVF (ZPORFS) : NAG Library, Mark 26

F07 Chapter Contents
F07 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F07FVF (ZPORFS)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F07FVF (ZPORFS) returns error bounds for the solution of a complex Hermitian positive definite system of linear equations with multiple right-hand sides, AX=B. It improves the solution by iterative refinement, in order to reduce the backward error as much as possible.

2 Specification

SUBROUTINE F07FVF ( UPLO, N, NRHS, A, LDA, AF, LDAF, B, LDB, X, LDX, FERR, BERR, WORK, RWORK, INFO)
INTEGER | N, NRHS, LDA, LDAF, LDB, LDX, INFO
REAL (KIND=nag_wp) | FERR(NRHS), BERR(NRHS), RWORK(N)
COMPLEX (KIND=nag_wp) | A(LDA,*), AF(LDAF,*), B(LDB,*), X(LDX,*), WORK(2*N)
CHARACTER(1) | UPLO
The routine may be called by its LAPACK name zporfs.

3 Description

F07FVF (ZPORFS) returns the backward errors and estimated bounds on the forward errors for the solution of a complex Hermitian positive definite system of linear equations with multiple right-hand sides AX=B. The routine handles each right-hand side vector (stored as a column of the matrix B) independently, so we describe the function of F07FVF (ZPORFS) in terms of a single right-hand side b and solution x.
Given a computed solution x, the routine computes the component-wise backward error β. This is the size of the smallest relative perturbation in each element of A and b such that x is the exact solution of a perturbed system
A+δA x=b+δb δ a ij≤β a ij   and   δ bi≤β bi .
Then the routine estimates a bound for the component-wise forward error in the computed solution, defined by:
maxi xi-x^i/maxi xi
where x^ is the true solution.
For details of the method, see the F07 Chapter Introduction.

4 References

Golub G H and Van Loan C F (1996) Matrix Computations (3rd Edition) Johns Hopkins University Press, Baltimore

5 Arguments

1:   UPLO – CHARACTER(1)Input
On entry: specifies whether the upper or lower triangular part of A is stored and how A is to be factorized.
UPLO='U'
The upper triangular part of A is stored and A is factorized as UH U, where U is upper triangular.
UPLO='L'
The lower triangular part of A is stored and A is factorized as L LH, where L is lower triangular.
Constraint: UPLO='U' or 'L'.
2:   N – INTEGERInput
On entry: n, the order of the matrix A.
Constraint: N≥0.
3:   NRHS – INTEGERInput
On entry: r, the number of right-hand sides.
Constraint: NRHS≥0.
4:   A LDA* – COMPLEX (KIND=nag_wp) arrayInput
Note: the second dimension of the array A must be at least max 1,N.
On entry: the n by n original Hermitian positive definite matrix A as supplied to F07FRF (ZPOTRF).
5:   LDA – INTEGERInput
On entry: the first dimension of the array A as declared in the (sub)program from which F07FVF (ZPORFS) is called.
Constraint: LDA≥max 1,N.
6:   AF LDAF* – COMPLEX (KIND=nag_wp) arrayInput
Note: the second dimension of the array AF must be at least max 1,N.
On entry: the Cholesky factor of A, as returned by F07FRF (ZPOTRF).
7:   LDAF – INTEGERInput
On entry: the first dimension of the array AF as declared in the (sub)program from which F07FVF (ZPORFS) is called.
Constraint: LDAF≥max 1,N.
8:   B LDB* – COMPLEX (KIND=nag_wp) arrayInput
Note: the second dimension of the array B must be at least max 1,NRHS.
On entry: the n by r right-hand side matrix B.
9:   LDB – INTEGERInput
On entry: the first dimension of the array B as declared in the (sub)program from which F07FVF (ZPORFS) is called.
Constraint: LDB≥max 1,N.
10:   X LDX* – COMPLEX (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array X must be at least max 1,NRHS.
On entry: the n by r solution matrix X, as returned by F07FSF (ZPOTRS).
On exit: the improved solution matrix X.
11:   LDX – INTEGERInput
On entry: the first dimension of the array X as declared in the (sub)program from which F07FVF (ZPORFS) is called.
Constraint: LDX≥max 1,N.
12:   FERR NRHS – REAL (KIND=nag_wp) arrayOutput
On exit: FERR j contains an estimated error bound for the jth solution vector, that is, the jth column of X, for j=1,2,…,r.
13:   BERR NRHS – REAL (KIND=nag_wp) arrayOutput
On exit: BERR j contains the component-wise backward error bound β for the jth solution vector, that is, the jth column of X, for j=1,2,…,r.
14:   WORK 2×N – COMPLEX (KIND=nag_wp) arrayWorkspace
15:   RWORK N – REAL (KIND=nag_wp) arrayWorkspace
16:   INFO – INTEGEROutput
On exit: INFO=0 unless the routine detects an error (see Section 6).

6 Error Indicators and Warnings

INFO<0
If INFO=-i, argument i had an illegal value. An explanatory message is output, and execution of the program is terminated.

7 Accuracy

The bounds returned in FERR are not rigorous, because they are estimated, not computed exactly; but in practice they almost always overestimate the actual error.

8 Parallelism and Performance

F07FVF (ZPORFS) is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
F07FVF (ZPORFS) makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

For each right-hand side, computation of the backward error involves a minimum of 16⁢n 2 real floating-point operations. Each step of iterative refinement involves an additional 24⁢n 2 real operations. At most five steps of iterative refinement are performed, but usually only one or two steps are required.
Estimating the forward error involves solving a number of systems of linear equations of the form Ax=b; the number is usually 5 and never more than 11. Each solution involves approximately 8⁢n 2 real operations.
The real analogue of this routine is F07FHF (DPORFS).

10 Example

This example solves the system of equations AX=B using iterative refinement and to compute the forward and backward error bounds, where
A= 3.23+0.00 i 1.51-1.92 i 1.90+0.84 i 0.42+2.50 i 1.51+1.92 i 3.58+0.00 i -0.23+1.11 i -1.18+1.37 i 1.90-0.84 i -0.23-1.11 i 4.09+0.00 i 2.33-0.14 i 0.42-2.50 i -1.18-1.37 i 2.33+0.14 i 4.29+0.00 i
and
B= 3.93-0 6.14 i 1.48+0 6.58 i 6.17+0 9.42 i 4.65-0 4.75 i -7.17-21.83 i -4.91+0 2.29 i 1.99-14.38 i 7.64-10.79 i .
Here A is Hermitian positive definite and must first be factorized by F07FRF (ZPOTRF).

10.1 Program Text

Program Text (f07fvfe.f90)

10.2 Program Data

Program Data (f07fvfe.d)

10.3 Program Results

Program Results (f07fvfe.r)

F07 Chapter Contents
F07 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F07FWF (ZPOTRI) : NAG Library, Mark 26

F07 Chapter Contents
F07 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F07FWF (ZPOTRI)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F07FWF (ZPOTRI) computes the inverse of a complex Hermitian positive definite matrix A, where A has been factorized by F07FRF (ZPOTRF).

2 Specification

SUBROUTINE F07FWF ( UPLO, N, A, LDA, INFO)
INTEGER | N, LDA, INFO
COMPLEX (KIND=nag_wp) | A(LDA,*)
CHARACTER(1) | UPLO
The routine may be called by its LAPACK name zpotri.

3 Description

F07FWF (ZPOTRI) is used to compute the inverse of a complex Hermitian positive definite matrix A, the routine must be preceded by a call to F07FRF (ZPOTRF), which computes the Cholesky factorization of A.
If UPLO='U', A=UH U and A-1 is computed by first inverting U and then forming U-1 U-H.
If UPLO='L', A=L LH and A-1 is computed by first inverting L and then forming L-H L-1.

4 References

Du Croz J J and Higham N J (1992) Stability of methods for matrix inversion IMA J. Numer. Anal. 12 1–19

5 Arguments

1:   UPLO – CHARACTER(1)Input
On entry: specifies how A has been factorized.
UPLO='U'
A=UH U, where U is upper triangular.
UPLO='L'
A=L LH, where L is lower triangular.
Constraint: UPLO='U' or 'L'.
2:   N – INTEGERInput
On entry: n, the order of the matrix A.
Constraint: N≥0.
3:   A LDA* – COMPLEX (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array A must be at least max 1,N.
On entry: the upper triangular matrix U if UPLO='U' or the lower triangular matrix L if UPLO='L', as returned by F07FRF (ZPOTRF).
On exit: U is overwritten by the upper triangle of A-1 if UPLO='U'; L is overwritten by the lower triangle of A-1 if UPLO='L'.
4:   LDA – INTEGERInput
On entry: the first dimension of the array A as declared in the (sub)program from which F07FWF (ZPOTRI) is called.
Constraint: LDA≥max 1,N.
5:   INFO – INTEGEROutput
On exit: INFO=0 unless the routine detects an error (see Section 6).

6 Error Indicators and Warnings

INFO<0
If INFO=-i, argument i had an illegal value. An explanatory message is output, and execution of the program is terminated.
INFO>0
Diagonal element value of the Cholesky factor is zero; the Cholesky factor is singular and the inverse of A cannot be computed.

7 Accuracy

The computed inverse X satisfies
XA-I 2≤c n ε κ 2 A   and   AX-I 2≤c n ε κ 2 A ,
where c n is a modest function of n, ε is the machine precision and κ 2 A is the condition number of A defined by
κ 2 A=A 2A-1 2 .

8 Parallelism and Performance

F07FWF (ZPOTRI) makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The total number of real floating-point operations is approximately 83 n 3.
The real analogue of this routine is F07FJF (DPOTRI).

10 Example

This example computes the inverse of the matrix A, where
A= 3.23+0.00 i 1.51-1.92 i 1.90+0.84 i 0.42+2.50 i 1.51+1.92 i 3.58+0.00 i -0.23+1.11 i -1.18+1.37 i 1.90-0.84 i -0.23-1.11 i 4.09+0.00 i 2.33-0.14 i 0.42-2.50 i -1.18-1.37 i 2.33+0.14 i 4.29+0.00 i .
Here A is Hermitian positive definite and must first be factorized by F07FRF (ZPOTRF).

10.1 Program Text

Program Text (f07fwfe.f90)

10.2 Program Data

Program Data (f07fwfe.d)

10.3 Program Results

Program Results (f07fwfe.r)

F07 Chapter Contents
F07 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F07GAF (DPPSV) : NAG Library, Mark 26

F07 Chapter Contents
F07 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F07GAF (DPPSV)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F07GAF (DPPSV) computes the solution to a real system of linear equations
AX=B ,
where A is an n by n symmetric positive definite matrix stored in packed format and X and B are n by r matrices.

2 Specification

SUBROUTINE F07GAF ( UPLO, N, NRHS, AP, B, LDB, INFO)
INTEGER | N, NRHS, LDB, INFO
REAL (KIND=nag_wp) | AP(*), B(LDB,*)
CHARACTER(1) | UPLO
The routine may be called by its LAPACK name dppsv.

3 Description

F07GAF (DPPSV) uses the Cholesky decomposition to factor A as A=UT U if UPLO='U' or A=L LT if UPLO='L', where U is an upper triangular matrix and L is a lower triangular matrix. The factored form of A is then used to solve the system of equations AX=B.

4 References

Anderson E, Bai Z, Bischof C, Blackford S, Demmel J, Dongarra J J, Du Croz J J, Greenbaum A, Hammarling S, McKenney A and Sorensen D (1999) LAPACK Users' Guide (3rd Edition) SIAM, Philadelphia http://www.netlib.org/lapack/lug
Golub G H and Van Loan C F (1996) Matrix Computations (3rd Edition) Johns Hopkins University Press, Baltimore

5 Arguments

1:   UPLO – CHARACTER(1)Input
On entry: if UPLO='U', the upper triangle of A is stored.
If UPLO='L', the lower triangle of A is stored.
Constraint: UPLO='U' or 'L'.
2:   N – INTEGERInput
On entry: n, the number of linear equations, i.e., the order of the matrix A.
Constraint: N≥0.
3:   NRHS – INTEGERInput
On entry: r, the number of right-hand sides, i.e., the number of columns of the matrix B.
Constraint: NRHS≥0.
4:   AP* – REAL (KIND=nag_wp) arrayInput/Output
Note: the dimension of the array AP must be at least max 1,N×N+1/2.
On entry: the n by n symmetric matrix A, packed by columns.
More precisely,
  • if UPLO='U', the upper triangle of A must be stored with element A ij in AP i+j j-1/2 for i≤j;
  • if UPLO='L', the lower triangle of A must be stored with element A ij in AP i+2 n-jj-1/2 for i≥j.
On exit: if INFO=0, the factor U or L from the Cholesky factorization A=UT U or A=L LT, in the same storage format as A.
5:   B LDB* – REAL (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array B must be at least max 1,NRHS.
On entry: the n by r right-hand side matrix B.
On exit: if INFO=0, the n by r solution matrix X.
6:   LDB – INTEGERInput
On entry: the first dimension of the array B as declared in the (sub)program from which F07GAF (DPPSV) is called.
Constraint: LDB≥max 1,N.
7:   INFO – INTEGEROutput
On exit: INFO=0 unless the routine detects an error (see Section 6).

6 Error Indicators and Warnings

INFO<0
If INFO=-i, argument i had an illegal value. An explanatory message is output, and execution of the program is terminated.
INFO>0
The leading minor of order value of A is not positive definite, so the factorization could not be completed, and the solution has not been computed.

7 Accuracy

The computed solution for a single right-hand side, x^ , satisfies an equation of the form
A+E x^=b ,
where
E 1 = O ε A 1
and ε is the machine precision. An approximate error bound for the computed solution is given by
x^-x 1 x 1 ≤ κ A E 1 A 1 ,
where κ A = A-1 1 A 1 , the condition number of A with respect to the solution of the linear equations. See Section 4.4 of Anderson et al. (1999) for further details.
F07GBF (DPPSVX) is a comprehensive LAPACK driver that returns forward and backward error bounds and an estimate of the condition number. Alternatively, F04BEF solves Ax=b and returns a forward error bound and condition estimate. F04BEF calls F07GAF (DPPSV) to solve the equations.

8 Parallelism and Performance

F07GAF (DPPSV) is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
F07GAF (DPPSV) makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The total number of floating-point operations is approximately 13 n 3 + 2⁢n 2 r , where r is the number of right-hand sides.
The complex analogue of this routine is F07GNF (ZPPSV).

10 Example

This example solves the equations
Ax=b ,
where A is the symmetric positive definite matrix
A = 4.16 -3.12 0.56 -0.10 -3.12 5.03 -0.83 1.18 0.56 -0.83 0.76 0.34 -0.10 1.18 0.34 1.18   and   b = 8.70 -13.35 1.89 -4.14 .
Details of the Cholesky factorization of A are also output.

10.1 Program Text

Program Text (f07gafe.f90)

10.2 Program Data

Program Data (f07gafe.d)

10.3 Program Results

Program Results (f07gafe.r)

F07 Chapter Contents
F07 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F07GBF (DPPSVX) : NAG Library, Mark 26

F07 Chapter Contents
F07 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F07GBF (DPPSVX)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F07GBF (DPPSVX) uses the Cholesky factorization
A=UT U   or   A=L LT
to compute the solution to a real system of linear equations
AX=B ,
where A is an n by n symmetric positive definite matrix stored in packed format and X and B are n by r matrices. Error bounds on the solution and a condition estimate are also provided.

2 Specification

SUBROUTINE F07GBF ( FACT, UPLO, N, NRHS, AP, AFP, EQUED, S, B, LDB, X, LDX, RCOND, FERR, BERR, WORK, IWORK, INFO)
INTEGER | N, NRHS, LDB, LDX, IWORK(N), INFO
REAL (KIND=nag_wp) | AP(*), AFP(*), S(*), B(LDB,*), X(LDX,*), RCOND, FERR(NRHS), BERR(NRHS), WORK(3*N)
CHARACTER(1) | FACT, UPLO, EQUED
The routine may be called by its LAPACK name dppsvx.

3 Description

F07GBF (DPPSVX) performs the following steps:
1. If FACT='E', real diagonal scaling factors, DS , are computed to equilibrate the system:
DS A DS DS-1 X = DS B .
Whether or not the system will be equilibrated depends on the scaling of the matrix A, but if equilibration is used, A is overwritten by DS A DS and B by DS B.
2. | If FACT='N' or 'E', the Cholesky decomposition is used to factor the matrix A (after equilibration if FACT='E') as A=UT U if UPLO='U' or A=L LT if UPLO='L', where U is an upper triangular matrix and L is a lower triangular matrix.
3. | If the leading i by i principal minor of A is not positive definite, then the routine returns with INFO=i. Otherwise, the factored form of A is used to estimate the condition number of the matrix A. If the reciprocal of the condition number is less than machine precision, INFO=N+1 is returned as a warning, but the routine still goes on to solve for X and compute error bounds as described below.
4. | The system of equations is solved for X using the factored form of A.
5. | Iterative refinement is applied to improve the computed solution matrix and to calculate error bounds and backward error estimates for it.
6. | If equilibration was used, the matrix X is premultiplied by DS so that it solves the original system before equilibration.

4 References

Anderson E, Bai Z, Bischof C, Blackford S, Demmel J, Dongarra J J, Du Croz J J, Greenbaum A, Hammarling S, McKenney A and Sorensen D (1999) LAPACK Users' Guide (3rd Edition) SIAM, Philadelphia http://www.netlib.org/lapack/lug
Golub G H and Van Loan C F (1996) Matrix Computations (3rd Edition) Johns Hopkins University Press, Baltimore
Higham N J (2002) Accuracy and Stability of Numerical Algorithms (2nd Edition) SIAM, Philadelphia

5 Arguments

1:   FACT – CHARACTER(1)Input
On entry: specifies whether or not the factorized form of the matrix A is supplied on entry, and if not, whether the matrix A should be equilibrated before it is factorized.
FACT='F'
AFP contains the factorized form of A. If EQUED='Y', the matrix A has been equilibrated with scaling factors given by S. AP and AFP will not be modified.
FACT='N'
The matrix A will be copied to AFP and factorized.
FACT='E'
The matrix A will be equilibrated if necessary, then copied to AFP and factorized.
Constraint: FACT='F', 'N' or 'E'.
2:   UPLO – CHARACTER(1)Input
On entry: if UPLO='U', the upper triangle of A is stored.
If UPLO='L', the lower triangle of A is stored.
Constraint: UPLO='U' or 'L'.
3:   N – INTEGERInput
On entry: n, the number of linear equations, i.e., the order of the matrix A.
Constraint: N≥0.
4:   NRHS – INTEGERInput
On entry: r, the number of right-hand sides, i.e., the number of columns of the matrix B.
Constraint: NRHS≥0.
5:   AP* – REAL (KIND=nag_wp) arrayInput/Output
Note: the dimension of the array AP must be at least max 1,N×N+1/2.
On entry: if FACT='F' and EQUED='Y', AP must contain the equilibrated matrix DS A DS; otherwise, AP must contain the n by n symmetric matrix A, packed by columns.
More precisely,
  • if UPLO='U', the upper triangle of A must be stored with element A ij in AP i+j j-1/2 for i≤j;
  • if UPLO='L', the lower triangle of A must be stored with element A ij in AP i+2 n-jj-1/2 for i≥j.
On exit: if FACT='F' or 'N', or if FACT='E' and EQUED='N', AP is not modified.
If FACT='E' and EQUED='Y', AP is overwritten by DS A DS.
6:   AFP* – REAL (KIND=nag_wp) arrayInput/Output
Note: the dimension of the array AFP must be at least max 1,N×N+1/2.
On entry: if FACT='F', AFP contains the triangular factor U or L from the Cholesky factorization A=UT U or A=L LT, in the same storage format as AP. If EQUED='Y', AFP is the factorized form of the equilibrated matrix DS A DS.
On exit: if FACT='N' or if FACT='E' and EQUED='N', AFP returns the triangular factor U or L from the Cholesky factorization A=UT U or A=L LT of the original matrix A.
If FACT='E' and EQUED='Y', AFP returns the triangular factor U or L from the Cholesky factorization A=UT U or A=L LT of the equilibrated matrix A (see the description of AP for the form of the equilibrated matrix).
7:   EQUED – CHARACTER(1)Input/Output
On entry: if FACT='N' or 'E', EQUED need not be set.
If FACT='F', EQUED must specify the form of the equilibration that was performed as follows:
  • if EQUED='N', no equilibration;
  • if EQUED='Y', equilibration was performed, i.e., A has been replaced by DS A DS.
On exit: if FACT='F', EQUED is unchanged from entry.
Otherwise, if no constraints are violated, EQUED specifies the form of the equilibration that was performed as specified above.
Constraint: if FACT='F', EQUED='N' or 'Y'.
8:   S* – REAL (KIND=nag_wp) arrayInput/Output
Note: the dimension of the array S must be at least max 1,N.
On entry: if FACT='N' or 'E', S need not be set.
If FACT='F' and EQUED='Y', S must contain the scale factors, DS, for A; each element of S must be positive.
On exit: if FACT='F', S is unchanged from entry.
Otherwise, if no constraints are violated and EQUED='Y', S contains the scale factors, DS, for A; each element of S is positive.
9:   B LDB* – REAL (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array B must be at least max 1,NRHS.
On entry: the n by r right-hand side matrix B.
On exit: if EQUED='N', B is not modified.
If EQUED='Y', B is overwritten by DS B.
10:   LDB – INTEGERInput
On entry: the first dimension of the array B as declared in the (sub)program from which F07GBF (DPPSVX) is called.
Constraint: LDB≥max 1,N.
11:   X LDX* – REAL (KIND=nag_wp) arrayOutput
Note: the second dimension of the array X must be at least max 1,NRHS.
On exit: if INFO=0 or N+1, the n by r solution matrix X to the original system of equations. Note that the arrays A and B are modified on exit if EQUED='Y', and the solution to the equilibrated system is DS-1 X.
12:   LDX – INTEGERInput
On entry: the first dimension of the array X as declared in the (sub)program from which F07GBF (DPPSVX) is called.
Constraint: LDX≥max 1,N.
13:   RCOND – REAL (KIND=nag_wp)Output
On exit: if no constraints are violated, an estimate of the reciprocal condition number of the matrix A (after equilibration if that is performed), computed as RCOND=1.0/A 1 A-1 1 .
14:   FERR NRHS – REAL (KIND=nag_wp) arrayOutput
On exit: if INFO=0 or N+1, an estimate of the forward error bound for each computed solution vector, such that x^j-xj∞/xj∞≤FERR j where x^j is the jth column of the computed solution returned in the array X and xj is the corresponding column of the exact solution X. The estimate is as reliable as the estimate for RCOND, and is almost always a slight overestimate of the true error.
15:   BERR NRHS – REAL (KIND=nag_wp) arrayOutput
On exit: if INFO=0 or N+1, an estimate of the component-wise relative backward error of each computed solution vector x^j (i.e., the smallest relative change in any element of A or B that makes x^j an exact solution).
16:   WORK 3×N – REAL (KIND=nag_wp) arrayWorkspace
17:   IWORK N – INTEGER arrayWorkspace
18:   INFO – INTEGEROutput
On exit: INFO=0 unless the routine detects an error (see Section 6).

6 Error Indicators and Warnings

INFO<0
If INFO=-i, argument i had an illegal value. An explanatory message is output, and execution of the program is terminated.
INFO>0 and INFO≤N
The leading minor of order value of A is not positive definite, so the factorization could not be completed, and the solution has not been computed. RCOND=0.0 is returned.
INFO=N+1
U (or L) is nonsingular, but RCOND is less than machine precision, meaning that the matrix is singular to working precision. Nevertheless, the solution and error bounds are computed because there are a number of situations where the computed solution can be more accurate than the value of RCOND would suggest.

7 Accuracy

For each right-hand side vector b, the computed solution x is the exact solution of a perturbed system of equations A+E x=b, where
  • if UPLO='U', E≤c n ε UTU;
  • if UPLO='L', E≤c n ε LLT,
c n is a modest linear function of n, and ε is the machine precision. See Section 10.1 of Higham (2002) for further details.
If x^ is the true solution, then the computed solution x satisfies a forward error bound of the form
x-x^∞ x^∞ ≤ wc cond A,x^,b ,
where cond A,x^,b = A-1 A x^ + b ∞/ x^∞ ≤ cond A = A-1 A ∞≤κ∞ A . If x^ is the j th column of X , then wc is returned in BERR j and a bound on x - x^ ∞ / x^ ∞ is returned in FERR j . See Section 4.4 of Anderson et al. (1999) for further details.

8 Parallelism and Performance

F07GBF (DPPSVX) is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
F07GBF (DPPSVX) makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The factorization of A requires approximately 13 n 3 floating-point operations.
For each right-hand side, computation of the backward error involves a minimum of 4⁢n 2 floating-point operations. Each step of iterative refinement involves an additional 6⁢n 2 operations. At most five steps of iterative refinement are performed, but usually only one or two steps are required. Estimating the forward error involves solving a number of systems of equations of the form Ax=b ; the number is usually 4 or 5 and never more than 11. Each solution involves approximately 2⁢n 2 operations.
The complex analogue of this routine is F07GPF (ZPPSVX).

10 Example

This example solves the equations
AX=B ,
where A is the symmetric positive definite matrix
A = 4.16 -3.12 0.56 -0.10 -3.12 5.03 -0.83 1.18 0.56 -0.83 0.76 0.34 -0.10 1.18 0.34 1.18
and
B = 8.70 8.30 -13.35 2.13 1.89 1.61 -4.14 5.00 .
Error estimates for the solutions, information on equilibration and an estimate of the reciprocal of the condition number of the scaled matrix A are also output.

10.1 Program Text

Program Text (f07gbfe.f90)

10.2 Program Data

Program Data (f07gbfe.d)

10.3 Program Results

Program Results (f07gbfe.r)

F07 Chapter Contents
F07 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F07GDF (DPPTRF) : NAG Library, Mark 26

F07 Chapter Contents
F07 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F07GDF (DPPTRF)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F07GDF (DPPTRF) computes the Cholesky factorization of a real symmetric positive definite matrix, using packed storage.

2 Specification

SUBROUTINE F07GDF ( UPLO, N, AP, INFO)
INTEGER | N, INFO
REAL (KIND=nag_wp) | AP(*)
CHARACTER(1) | UPLO
The routine may be called by its LAPACK name dpptrf.

3 Description

F07GDF (DPPTRF) forms the Cholesky factorization of a real symmetric positive definite matrix A either as A=UT U if UPLO='U' or A=L LT if UPLO='L', where U is an upper triangular matrix and L is lower triangular, using packed storage.

4 References

Demmel J W (1989) On floating-point errors in Cholesky LAPACK Working Note No. 14 University of Tennessee, Knoxville http://www.netlib.org/lapack/lawnspdf/lawn14.pdf
Golub G H and Van Loan C F (1996) Matrix Computations (3rd Edition) Johns Hopkins University Press, Baltimore

5 Arguments

1:   UPLO – CHARACTER(1)Input
On entry: specifies whether the upper or lower triangular part of A is stored and how A is to be factorized.
UPLO='U'
The upper triangular part of A is stored and A is factorized as UT U, where U is upper triangular.
UPLO='L'
The lower triangular part of A is stored and A is factorized as L LT, where L is lower triangular.
Constraint: UPLO='U' or 'L'.
2:   N – INTEGERInput
On entry: n, the order of the matrix A.
Constraint: N≥0.
3:   AP* – REAL (KIND=nag_wp) arrayInput/Output
Note: the dimension of the array AP must be at least max 1,N×N+1/2.
On entry: the n by n symmetric matrix A, packed by columns.
More precisely,
  • if UPLO='U', the upper triangle of A must be stored with element A ij in AP i+j j-1/2 for i≤j;
  • if UPLO='L', the lower triangle of A must be stored with element A ij in AP i+2 n-jj-1/2 for i≥j.
On exit: if INFO=0, the factor U or L from the Cholesky factorization A=UT U or A=L LT, in the same storage format as A.
4:   INFO – INTEGEROutput
On exit: INFO=0 unless the routine detects an error (see Section 6).

6 Error Indicators and Warnings

INFO<0
If INFO=-i, argument i had an illegal value. An explanatory message is output, and execution of the program is terminated.
INFO>0
The leading minor of order value is not positive definite and the factorization could not be completed. Hence A itself is not positive definite. This may indicate an error in forming the matrix A. To factorize a symmetric matrix which is not positive definite, call F07PDF (DSPTRF) instead.

7 Accuracy

If UPLO='U', the computed factor U is the exact factor of a perturbed matrix A+E, where
E≤c n ε UTU ,
c n is a modest linear function of n, and ε is the machine precision.
If UPLO='L', a similar statement holds for the computed factor L. It follows that e ij≤c n ε⁢a iia jj.

8 Parallelism and Performance

F07GDF (DPPTRF) makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The total number of floating-point operations is approximately 13 n 3.
A call to F07GDF (DPPTRF) may be followed by calls to the routines:
  • F07GEF (DPPTRS) to solve AX=B;
  • F07GGF (DPPCON) to estimate the condition number of A;
  • F07GJF (DPPTRI) to compute the inverse of A.
The complex analogue of this routine is F07GRF (ZPPTRF).

10 Example

This example computes the Cholesky factorization of the matrix A, where
A= 4.16 -3.12 0.56 -0.10 -3.12 5.03 -0.83 1.18 0.56 -0.83 0.76 0.34 -0.10 1.18 0.34 1.18 ,
using packed storage.

10.1 Program Text

Program Text (f07gdfe.f90)

10.2 Program Data

Program Data (f07gdfe.d)

10.3 Program Results

Program Results (f07gdfe.r)

F07 Chapter Contents
F07 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F07GEF (DPPTRS) : NAG Library, Mark 26

F07 Chapter Contents
F07 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F07GEF (DPPTRS)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F07GEF (DPPTRS) solves a real symmetric positive definite system of linear equations with multiple right-hand sides,
AX=B ,
where A has been factorized by F07GDF (DPPTRF), using packed storage.

2 Specification

SUBROUTINE F07GEF ( UPLO, N, NRHS, AP, B, LDB, INFO)
INTEGER | N, NRHS, LDB, INFO
REAL (KIND=nag_wp) | AP(*), B(LDB,*)
CHARACTER(1) | UPLO
The routine may be called by its LAPACK name dpptrs.

3 Description

F07GEF (DPPTRS) is used to solve a real symmetric positive definite system of linear equations AX=B, the routine must be preceded by a call to F07GDF (DPPTRF) which computes the Cholesky factorization of A, using packed storage. The solution X is computed by forward and backward substitution.
If UPLO='U', A=UT U, where U is upper triangular; the solution X is computed by solving UT Y=B and then UX=Y.
If UPLO='L', A=L LT, where L is lower triangular; the solution X is computed by solving LY=B and then LT X=Y.

4 References

Golub G H and Van Loan C F (1996) Matrix Computations (3rd Edition) Johns Hopkins University Press, Baltimore

5 Arguments

1:   UPLO – CHARACTER(1)Input
On entry: specifies how A has been factorized.
UPLO='U'
A=UT U, where U is upper triangular.
UPLO='L'
A=L LT, where L is lower triangular.
Constraint: UPLO='U' or 'L'.
2:   N – INTEGERInput
On entry: n, the order of the matrix A.
Constraint: N≥0.
3:   NRHS – INTEGERInput
On entry: r, the number of right-hand sides.
Constraint: NRHS≥0.
4:   AP* – REAL (KIND=nag_wp) arrayInput
Note: the dimension of the array AP must be at least max 1,N×N+1/2.
On entry: the Cholesky factor of A stored in packed form, as returned by F07GDF (DPPTRF).
5:   B LDB* – REAL (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array B must be at least max 1,NRHS.
On entry: the n by r right-hand side matrix B.
On exit: the n by r solution matrix X.
6:   LDB – INTEGERInput
On entry: the first dimension of the array B as declared in the (sub)program from which F07GEF (DPPTRS) is called.
Constraint: LDB≥max 1,N.
7:   INFO – INTEGEROutput
On exit: INFO=0 unless the routine detects an error (see Section 6).

6 Error Indicators and Warnings

INFO<0
If INFO=-i, argument i had an illegal value. An explanatory message is output, and execution of the program is terminated.

7 Accuracy

For each right-hand side vector b, the computed solution x is the exact solution of a perturbed system of equations A+E x=b, where
  • if UPLO='U', E≤c n ε UTU;
  • if UPLO='L', E≤c n ε LLT,
c n is a modest linear function of n, and ε is the machine precision.
If x^ is the true solution, then the computed solution x satisfies a forward error bound of the form
x-x^∞ x∞ ≤c n cond A,x ε
where cond A,x=A-1Ax∞/x∞≤cond A=A-1A∞≤κ∞A.
Note that cond A,x can be much smaller than cond A.
Forward and backward error bounds can be computed by calling F07GHF (DPPRFS), and an estimate for κ∞A (=κ 1 A) can be obtained by calling F07GGF (DPPCON).

8 Parallelism and Performance

F07GEF (DPPTRS) is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
F07GEF (DPPTRS) makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The total number of floating-point operations is approximately 2⁢n 2 r.
This routine may be followed by a call to F07GHF (DPPRFS) to refine the solution and return an error estimate.
The complex analogue of this routine is F07GSF (ZPPTRS).

10 Example

This example solves the system of equations AX=B, where
A= 4.16 -3.12 0.56 -0.10 -3.12 5.03 -0.83 1.18 0.56 -0.83 0.76 0.34 -0.10 1.18 0.34 1.18   and   B= 8.70 8.30 -13.35 2.13 1.89 1.61 -4.14 5.00 .
Here A is symmetric positive definite, stored in packed form, and must first be factorized by F07GDF (DPPTRF).

10.1 Program Text

Program Text (f07gefe.f90)

10.2 Program Data

Program Data (f07gefe.d)

10.3 Program Results

Program Results (f07gefe.r)

F07 Chapter Contents
F07 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F07GFF (DPPEQU) : NAG Library, Mark 26

F07 Chapter Contents
F07 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F07GFF (DPPEQU)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F07GFF (DPPEQU) computes a diagonal scaling matrix S intended to equilibrate a real n by n symmetric positive definite matrix A , stored in packed format, and reduce its condition number.

2 Specification

SUBROUTINE F07GFF ( UPLO, N, AP, S, SCOND, AMAX, INFO)
INTEGER | N, INFO
REAL (KIND=nag_wp) | AP(*), S(N), SCOND, AMAX
CHARACTER(1) | UPLO
The routine may be called by its LAPACK name dppequ.

3 Description

F07GFF (DPPEQU) computes a diagonal scaling matrix S chosen so that
sj=1 / a jj .
This means that the matrix B given by
B=SAS ,
has diagonal elements equal to unity. This in turn means that the condition number of B , κ 2 B , is within a factor n of the matrix of smallest possible condition number over all possible choices of diagonal scalings (see Corollary 7.6 of Higham (2002)).

4 References

Higham N J (2002) Accuracy and Stability of Numerical Algorithms (2nd Edition) SIAM, Philadelphia

5 Arguments

1:   UPLO – CHARACTER(1)Input
On entry: indicates whether the upper or lower triangular part of A is stored in the array AP, as follows:
UPLO='U'
The upper triangle of A is stored.
UPLO='L'
The lower triangle of A is stored.
Constraint: UPLO='U' or 'L'.
2:   N – INTEGERInput
On entry: n, the order of the matrix A.
Constraint: N≥0.
3:   AP* – REAL (KIND=nag_wp) arrayInput
Note: the dimension of the array AP must be at least max 1,N×N+1/2.
On entry: the n by n symmetric matrix A, packed by columns.
More precisely,
  • if UPLO='U', the upper triangle of A must be stored with element A ij in AP i+j j-1/2 for i≤j;
  • if UPLO='L', the lower triangle of A must be stored with element A ij in AP i+2 n-jj-1/2 for i≥j.
Only the elements of AP corresponding to the diagonal elements A are referenced.
4:   S N – REAL (KIND=nag_wp) arrayOutput
On exit: if INFO=0, S contains the diagonal elements of the scaling matrix S.
5:   SCOND – REAL (KIND=nag_wp)Output
On exit: if INFO=0, SCOND contains the ratio of the smallest value of S to the largest value of S. If SCOND≥0.1 and AMAX is neither too large nor too small, it is not worth scaling by S.
6:   AMAX – REAL (KIND=nag_wp)Output
On exit: max a ij. If AMAX is very close to overflow or underflow, the matrix A should be scaled.
7:   INFO – INTEGEROutput
On exit: INFO=0 unless the routine detects an error (see Section 6).

6 Error Indicators and Warnings

INFO<0
If INFO=-i, argument i had an illegal value. An explanatory message is output, and execution of the program is terminated.
INFO>0
The valueth diagonal element of A is not positive (and hence A cannot be positive definite).

7 Accuracy

The computed scale factors will be close to the exact scale factors.

8 Parallelism and Performance

F07GFF (DPPEQU) is not threaded in any implementation.

9 Further Comments

The complex analogue of this routine is F07GTF (ZPPEQU).

10 Example

This example equilibrates the symmetric positive definite matrix A given by
A = -4.16 -3.12×105 -0.56 -0.10 -3.12×105 -5.03×1010 -0.83×105 -1.18×105 -0.56 -0.83×105 -0.76 -0.34 -0.10 -1.18×105 -0.34 -1.18 .
Details of the scaling factors and the scaled matrix are output.

10.1 Program Text

Program Text (f07gffe.f90)

10.2 Program Data

Program Data (f07gffe.d)

10.3 Program Results

Program Results (f07gffe.r)

F07 Chapter Contents
F07 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F07GGF (DPPCON) : NAG Library, Mark 26

F07 Chapter Contents
F07 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F07GGF (DPPCON)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F07GGF (DPPCON) estimates the condition number of a real symmetric positive definite matrix A, where A has been factorized by F07GDF (DPPTRF), using packed storage.

2 Specification

SUBROUTINE F07GGF ( UPLO, N, AP, ANORM, RCOND, WORK, IWORK, INFO)
INTEGER | N, IWORK(N), INFO
REAL (KIND=nag_wp) | AP(*), ANORM, RCOND, WORK(3*N)
CHARACTER(1) | UPLO
The routine may be called by its LAPACK name dppcon.

3 Description

F07GGF (DPPCON) estimates the condition number (in the 1-norm) of a real symmetric positive definite matrix A:
κ 1 A=A 1A-1 1 .
Since A is symmetric, κ 1 A=κ∞A=A∞A-1∞.
Because κ 1 A is infinite if A is singular, the routine actually returns an estimate of the reciprocal of κ 1 A.
The routine should be preceded by a call to F06RDF to compute A 1 and a call to F07GDF (DPPTRF) to compute the Cholesky factorization of A. The routine then uses Higham's implementation of Hager's method (see Higham (1988)) to estimate A-1 1.

4 References

Higham N J (1988) FORTRAN codes for estimating the one-norm of a real or complex matrix, with applications to condition estimation ACM Trans. Math. Software 14 381–396

5 Arguments

1:   UPLO – CHARACTER(1)Input
On entry: specifies how A has been factorized.
UPLO='U'
A=UT U, where U is upper triangular.
UPLO='L'
A=L LT, where L is lower triangular.
Constraint: UPLO='U' or 'L'.
2:   N – INTEGERInput
On entry: n, the order of the matrix A.
Constraint: N≥0.
3:   AP* – REAL (KIND=nag_wp) arrayInput
Note: the dimension of the array AP must be at least max 1,N×N+1/2.
On entry: the Cholesky factor of A stored in packed form, as returned by F07GDF (DPPTRF).
4:   ANORM – REAL (KIND=nag_wp)Input
On entry: the 1-norm of the original matrix A, which may be computed by calling F06RDF with its argument NORM='1'. ANORM must be computed either before calling F07GDF (DPPTRF) or else from a copy of the original matrix A.
Constraint: ANORM≥0.0.
5:   RCOND – REAL (KIND=nag_wp)Output
On exit: an estimate of the reciprocal of the condition number of A. RCOND is set to zero if exact singularity is detected or the estimate underflows. If RCOND is less than machine precision, A is singular to working precision.
6:   WORK 3×N – REAL (KIND=nag_wp) arrayWorkspace
7:   IWORK N – INTEGER arrayWorkspace
8:   INFO – INTEGEROutput
On exit: INFO=0 unless the routine detects an error (see Section 6).

6 Error Indicators and Warnings

INFO<0
If INFO=-i, argument i had an illegal value. An explanatory message is output, and execution of the program is terminated.

7 Accuracy

The computed estimate RCOND is never less than the true value ρ, and in practice is nearly always less than 10 ρ, although examples can be constructed where RCOND is much larger.

8 Parallelism and Performance

F07GGF (DPPCON) makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

A call to F07GGF (DPPCON) involves solving a number of systems of linear equations of the form Ax=b; the number is usually 4 or 5 and never more than 11. Each solution involves approximately 2⁢n 2 floating-point operations but takes considerably longer than a call to F07GEF (DPPTRS) with one right-hand side, because extra care is taken to avoid overflow when A is approximately singular.
The complex analogue of this routine is F07GUF (ZPPCON).

10 Example

This example estimates the condition number in the 1-norm (or ∞-norm) of the matrix A, where
A= 4.16 -3.12 0.56 -0.10 -3.12 5.03 -0.83 1.18 0.56 -0.83 0.76 0.34 -0.10 1.18 0.34 1.18 .
Here A is symmetric positive definite, stored in packed form, and must first be factorized by F07GDF (DPPTRF). The true condition number in the 1-norm is 97.32.

10.1 Program Text

Program Text (f07ggfe.f90)

10.2 Program Data

Program Data (f07ggfe.d)

10.3 Program Results

Program Results (f07ggfe.r)

F07 Chapter Contents
F07 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F07GHF (DPPRFS) : NAG Library, Mark 26

F07 Chapter Contents
F07 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F07GHF (DPPRFS)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F07GHF (DPPRFS) returns error bounds for the solution of a real symmetric positive definite system of linear equations with multiple right-hand sides, AX=B, using packed storage. It improves the solution by iterative refinement, in order to reduce the backward error as much as possible.

2 Specification

SUBROUTINE F07GHF ( UPLO, N, NRHS, AP, AFP, B, LDB, X, LDX, FERR, BERR, WORK, IWORK, INFO)
INTEGER | N, NRHS, LDB, LDX, IWORK(N), INFO
REAL (KIND=nag_wp) | AP(*), AFP(*), B(LDB,*), X(LDX,*), FERR(NRHS), BERR(NRHS), WORK(3*N)
CHARACTER(1) | UPLO
The routine may be called by its LAPACK name dpprfs.

3 Description

F07GHF (DPPRFS) returns the backward errors and estimated bounds on the forward errors for the solution of a real symmetric positive definite system of linear equations with multiple right-hand sides AX=B, using packed storage. The routine handles each right-hand side vector (stored as a column of the matrix B) independently, so we describe the function of F07GHF (DPPRFS) in terms of a single right-hand side b and solution x.
Given a computed solution x, the routine computes the component-wise backward error β. This is the size of the smallest relative perturbation in each element of A and b such that x is the exact solution of a perturbed system
A+δA x=b+δb δ a ij≤β a ij   and   δ bi≤β bi .
Then the routine estimates a bound for the component-wise forward error in the computed solution, defined by:
maxi xi-x^i/maxi xi
where x^ is the true solution.
For details of the method, see the F07 Chapter Introduction.

4 References

Golub G H and Van Loan C F (1996) Matrix Computations (3rd Edition) Johns Hopkins University Press, Baltimore

5 Arguments

1:   UPLO – CHARACTER(1)Input
On entry: specifies whether the upper or lower triangular part of A is stored and how A is to be factorized.
UPLO='U'
The upper triangular part of A is stored and A is factorized as UT U, where U is upper triangular.
UPLO='L'
The lower triangular part of A is stored and A is factorized as L LT, where L is lower triangular.
Constraint: UPLO='U' or 'L'.
2:   N – INTEGERInput
On entry: n, the order of the matrix A.
Constraint: N≥0.
3:   NRHS – INTEGERInput
On entry: r, the number of right-hand sides.
Constraint: NRHS≥0.
4:   AP* – REAL (KIND=nag_wp) arrayInput
Note: the dimension of the array AP must be at least max 1,N×N+1/2.
On entry: the n by n original symmetric positive definite matrix A as supplied to F07GDF (DPPTRF).
5:   AFP* – REAL (KIND=nag_wp) arrayInput
Note: the dimension of the array AFP must be at least max 1,N×N+1/2.
On entry: the Cholesky factor of A stored in packed form, as returned by F07GDF (DPPTRF).
6:   B LDB* – REAL (KIND=nag_wp) arrayInput
Note: the second dimension of the array B must be at least max 1,NRHS.
On entry: the n by r right-hand side matrix B.
7:   LDB – INTEGERInput
On entry: the first dimension of the array B as declared in the (sub)program from which F07GHF (DPPRFS) is called.
Constraint: LDB≥max 1,N.
8:   X LDX* – REAL (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array X must be at least max 1,NRHS.
On entry: the n by r solution matrix X, as returned by F07GEF (DPPTRS).
On exit: the improved solution matrix X.
9:   LDX – INTEGERInput
On entry: the first dimension of the array X as declared in the (sub)program from which F07GHF (DPPRFS) is called.
Constraint: LDX≥max 1,N.
10:   FERR NRHS – REAL (KIND=nag_wp) arrayOutput
On exit: FERR j contains an estimated error bound for the jth solution vector, that is, the jth column of X, for j=1,2,…,r.
11:   BERR NRHS – REAL (KIND=nag_wp) arrayOutput
On exit: BERR j contains the component-wise backward error bound β for the jth solution vector, that is, the jth column of X, for j=1,2,…,r.
12:   WORK 3×N – REAL (KIND=nag_wp) arrayWorkspace
13:   IWORK N – INTEGER arrayWorkspace
14:   INFO – INTEGEROutput
On exit: INFO=0 unless the routine detects an error (see Section 6).

6 Error Indicators and Warnings

INFO<0
If INFO=-i, argument i had an illegal value. An explanatory message is output, and execution of the program is terminated.

7 Accuracy

The bounds returned in FERR are not rigorous, because they are estimated, not computed exactly; but in practice they almost always overestimate the actual error.

8 Parallelism and Performance

F07GHF (DPPRFS) is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
F07GHF (DPPRFS) makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

For each right-hand side, computation of the backward error involves a minimum of 4⁢n 2 floating-point operations. Each step of iterative refinement involves an additional 6 n 2 operations. At most five steps of iterative refinement are performed, but usually only 1 or 2 steps are required.
Estimating the forward error involves solving a number of systems of linear equations of the form Ax=b; the number is usually 4 or 5 and never more than 11. Each solution involves approximately 2 n 2 operations.
The complex analogue of this routine is F07GVF (ZPPRFS).

10 Example

This example solves the system of equations AX=B using iterative refinement and to compute the forward and backward error bounds, where
A= 4.16 -3.12 0.56 -0.10 -3.12 5.03 -0.83 1.18 0.56 -0.83 0.76 0.34 -0.10 1.18 0.34 1.18   and   B= 8.70 8.30 -13.35 2.13 1.89 1.61 -4.14 5.00 .
Here A is symmetric positive definite, stored in packed form, and must first be factorized by F07GDF (DPPTRF).

10.1 Program Text

Program Text (f07ghfe.f90)

10.2 Program Data

Program Data (f07ghfe.d)

10.3 Program Results

Program Results (f07ghfe.r)

F07 Chapter Contents
F07 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F07GJF (DPPTRI) : NAG Library, Mark 26

F07 Chapter Contents
F07 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F07GJF (DPPTRI)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F07GJF (DPPTRI) computes the inverse of a real symmetric positive definite matrix A, where A has been factorized by F07GDF (DPPTRF), using packed storage.

2 Specification

SUBROUTINE F07GJF ( UPLO, N, AP, INFO)
INTEGER | N, INFO
REAL (KIND=nag_wp) | AP(*)
CHARACTER(1) | UPLO
The routine may be called by its LAPACK name dpptri.

3 Description

F07GJF (DPPTRI) is used to compute the inverse of a real symmetric positive definite matrix A, the routine must be preceded by a call to F07GDF (DPPTRF), which computes the Cholesky factorization of A, using packed storage.
If UPLO='U', A=UT U and A-1 is computed by first inverting U and then forming U-1 U-T.
If UPLO='L', A=L LT and A-1 is computed by first inverting L and then forming L-T L-1.

4 References

Du Croz J J and Higham N J (1992) Stability of methods for matrix inversion IMA J. Numer. Anal. 12 1–19

5 Arguments

1:   UPLO – CHARACTER(1)Input
On entry: specifies how A has been factorized.
UPLO='U'
A=UT U, where U is upper triangular.
UPLO='L'
A=L LT, where L is lower triangular.
Constraint: UPLO='U' or 'L'.
2:   N – INTEGERInput
On entry: n, the order of the matrix A.
Constraint: N≥0.
3:   AP* – REAL (KIND=nag_wp) arrayInput/Output
Note: the dimension of the array AP must be at least max 1,N×N+1/2.
On entry: the Cholesky factor of A stored in packed form, as returned by F07GDF (DPPTRF).
On exit: the factorization is overwritten by the n by n matrix A-1.
More precisely,
  • if UPLO='U', the upper triangle of A-1 must be stored with element A ij in AP i+j j-1/2 for i≤j;
  • if UPLO='L', the lower triangle of A-1 must be stored with element A ij in AP i+2 n-jj-1/2 for i≥j.
4:   INFO – INTEGEROutput
On exit: INFO=0 unless the routine detects an error (see Section 6).

6 Error Indicators and Warnings

INFO<0
If INFO=-i, argument i had an illegal value. An explanatory message is output, and execution of the program is terminated.
INFO>0
Diagonal element value of the Cholesky factor is zero; the Cholesky factor is singular and the inverse of A cannot be computed.

7 Accuracy

The computed inverse X satisfies
XA-I 2≤c n ε κ 2 A   and   AX-I 2≤c n ε κ 2 A ,
where c n is a modest function of n, ε is the machine precision and κ 2 A is the condition number of A defined by
κ 2 A=A 2A-1 2 .

8 Parallelism and Performance

F07GJF (DPPTRI) makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The total number of floating-point operations is approximately 23 n 3.
The complex analogue of this routine is F07GWF (ZPPTRI).

10 Example

This example computes the inverse of the matrix A, where
A= 4.16 -3.12 0.56 -0.10 -3.12 5.03 -0.83 1.18 0.56 -0.83 0.76 0.34 -0.10 1.18 0.34 1.18 .
Here A is symmetric positive definite, stored in packed form, and must first be factorized by F07GDF (DPPTRF).

10.1 Program Text

Program Text (f07gjfe.f90)

10.2 Program Data

Program Data (f07gjfe.d)

10.3 Program Results

Program Results (f07gjfe.r)

F07 Chapter Contents
F07 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F07GNF (ZPPSV) : NAG Library, Mark 26

F07 Chapter Contents
F07 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F07GNF (ZPPSV)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F07GNF (ZPPSV) computes the solution to a complex system of linear equations
AX=B ,
where A is an n by n Hermitian positive definite matrix stored in packed format and X and B are n by r matrices.

2 Specification

SUBROUTINE F07GNF ( UPLO, N, NRHS, AP, B, LDB, INFO)
INTEGER | N, NRHS, LDB, INFO
COMPLEX (KIND=nag_wp) | AP(*), B(LDB,*)
CHARACTER(1) | UPLO
The routine may be called by its LAPACK name zppsv.

3 Description

F07GNF (ZPPSV) uses the Cholesky decomposition to factor A as A=UH U if UPLO='U' or A=L LH if UPLO='L', where U is an upper triangular matrix and L is a lower triangular matrix. The factored form of A is then used to solve the system of equations AX=B.

4 References

Anderson E, Bai Z, Bischof C, Blackford S, Demmel J, Dongarra J J, Du Croz J J, Greenbaum A, Hammarling S, McKenney A and Sorensen D (1999) LAPACK Users' Guide (3rd Edition) SIAM, Philadelphia http://www.netlib.org/lapack/lug
Golub G H and Van Loan C F (1996) Matrix Computations (3rd Edition) Johns Hopkins University Press, Baltimore

5 Arguments

1:   UPLO – CHARACTER(1)Input
On entry: if UPLO='U', the upper triangle of A is stored.
If UPLO='L', the lower triangle of A is stored.
Constraint: UPLO='U' or 'L'.
2:   N – INTEGERInput
On entry: n, the number of linear equations, i.e., the order of the matrix A.
Constraint: N≥0.
3:   NRHS – INTEGERInput
On entry: r, the number of right-hand sides, i.e., the number of columns of the matrix B.
Constraint: NRHS≥0.
4:   AP* – COMPLEX (KIND=nag_wp) arrayInput/Output
Note: the dimension of the array AP must be at least max 1,N×N+1/2.
On entry: the n by n Hermitian matrix A, packed by columns.
More precisely,
  • if UPLO='U', the upper triangle of A must be stored with element A ij in AP i+j j-1/2 for i≤j;
  • if UPLO='L', the lower triangle of A must be stored with element A ij in AP i+2 n-jj-1/2 for i≥j.
On exit: if INFO=0, the factor U or L from the Cholesky factorization A=UH U or A=L LH, in the same storage format as A.
5:   B LDB* – COMPLEX (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array B must be at least max 1,NRHS.
To solve the equations Ax=b, where b is a single right-hand side, B may be supplied as a one-dimensional array with length LDB=max 1,N.
On entry: the n by r right-hand side matrix B.
On exit: if INFO=0, the n by r solution matrix X.
6:   LDB – INTEGERInput
On entry: the first dimension of the array B as declared in the (sub)program from which F07GNF (ZPPSV) is called.
Constraint: LDB≥max 1,N.
7:   INFO – INTEGEROutput
On exit: INFO=0 unless the routine detects an error (see Section 6).

6 Error Indicators and Warnings

INFO<0
If INFO=-i, argument i had an illegal value. An explanatory message is output, and execution of the program is terminated.
INFO>0
The leading minor of order value of A is not positive definite, so the factorization could not be completed, and the solution has not been computed.

7 Accuracy

The computed solution for a single right-hand side, x^ , satisfies an equation of the form
A+E x^=b ,
where
E 1 = O ε A 1
and ε is the machine precision. An approximate error bound for the computed solution is given by
x^-x 1 x 1 ≤ κ A E 1 A 1 ,
where κ A = A-1 1 A 1 , the condition number of A with respect to the solution of the linear equations. See Section 4.4 of Anderson et al. (1999) for further details.
F07GPF (ZPPSVX) is a comprehensive LAPACK driver that returns forward and backward error bounds and an estimate of the condition number. Alternatively, F04CEF solves Ax=b and returns a forward error bound and condition estimate. F04CEF calls F07GNF (ZPPSV) to solve the equations.

8 Parallelism and Performance

F07GNF (ZPPSV) is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
F07GNF (ZPPSV) makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The total number of floating-point operations is approximately 43 n 3 + 8⁢n 2 r , where r is the number of right-hand sides.
The real analogue of this routine is F07GAF (DPPSV).

10 Example

This example solves the equations
Ax=b ,
where A is the Hermitian positive definite matrix
A = 3.23 i+0.00 1.51-1.92 i 1.90+0.84 i 0.42+2.50 i 1.51+1.92 i 3.58 i+0.00 -0.23+1.11 i -1.18+1.37 i 1.90-0.84 i -0.23-1.11 i 4.09 i+0.00 2.33-0.14 i 0.42-2.50 i -1.18-1.37 i 2.33+0.14 i 4.29 i+0.00
and
b = 3.93-0 6.14 i 6.17+0 9.42 i -7.17-21.83 i 1.99-14.38 i .
Details of the Cholesky factorization of A are also output.

10.1 Program Text

Program Text (f07gnfe.f90)

10.2 Program Data

Program Data (f07gnfe.d)

10.3 Program Results

Program Results (f07gnfe.r)

F07 Chapter Contents
F07 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F07GPF (ZPPSVX) : NAG Library, Mark 26

F07 Chapter Contents
F07 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F07GPF (ZPPSVX)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F07GPF (ZPPSVX) uses the Cholesky factorization
A=UH U   or   A=L LH
to compute the solution to a complex system of linear equations
AX=B ,
where A is an n by n Hermitian positive definite matrix stored in packed format and X and B are n by r matrices. Error bounds on the solution and a condition estimate are also provided.

2 Specification

SUBROUTINE F07GPF ( FACT, UPLO, N, NRHS, AP, AFP, EQUED, S, B, LDB, X, LDX, RCOND, FERR, BERR, WORK, RWORK, INFO)
INTEGER | N, NRHS, LDB, LDX, INFO
REAL (KIND=nag_wp) | S(*), RCOND, FERR(NRHS), BERR(NRHS), RWORK(N)
COMPLEX (KIND=nag_wp) | AP(*), AFP(*), B(LDB,*), X(LDX,*), WORK(2*N)
CHARACTER(1) | FACT, UPLO, EQUED
The routine may be called by its LAPACK name zppsvx.

3 Description

F07GPF (ZPPSVX) performs the following steps:
1. If FACT='E', real diagonal scaling factors, DS , are computed to equilibrate the system:
DS A DS DS-1 X = DS B .
Whether or not the system will be equilibrated depends on the scaling of the matrix A, but if equilibration is used, A is overwritten by DS A DS and B by DS B.
2. | If FACT='N' or 'E', the Cholesky decomposition is used to factor the matrix A (after equilibration if FACT='E') as A=UH U if UPLO='U' or A=L LH if UPLO='L', where U is an upper triangular matrix and L is a lower triangular matrix.
3. | If the leading i by i principal minor of A is not positive definite, then the routine returns with INFO=i. Otherwise, the factored form of A is used to estimate the condition number of the matrix A. If the reciprocal of the condition number is less than machine precision, INFO=N+1 is returned as a warning, but the routine still goes on to solve for X and compute error bounds as described below.
4. | The system of equations is solved for X using the factored form of A.
5. | Iterative refinement is applied to improve the computed solution matrix and to calculate error bounds and backward error estimates for it.
6. | If equilibration was used, the matrix X is premultiplied by DS so that it solves the original system before equilibration.

4 References

Anderson E, Bai Z, Bischof C, Blackford S, Demmel J, Dongarra J J, Du Croz J J, Greenbaum A, Hammarling S, McKenney A and Sorensen D (1999) LAPACK Users' Guide (3rd Edition) SIAM, Philadelphia http://www.netlib.org/lapack/lug
Golub G H and Van Loan C F (1996) Matrix Computations (3rd Edition) Johns Hopkins University Press, Baltimore
Higham N J (2002) Accuracy and Stability of Numerical Algorithms (2nd Edition) SIAM, Philadelphia

5 Arguments

1:   FACT – CHARACTER(1)Input
On entry: specifies whether or not the factorized form of the matrix A is supplied on entry, and if not, whether the matrix A should be equilibrated before it is factorized.
FACT='F'
AFP contains the factorized form of A. If EQUED='Y', the matrix A has been equilibrated with scaling factors given by S. AP and AFP will not be modified.
FACT='N'
The matrix A will be copied to AFP and factorized.
FACT='E'
The matrix A will be equilibrated if necessary, then copied to AFP and factorized.
Constraint: FACT='F', 'N' or 'E'.
2:   UPLO – CHARACTER(1)Input
On entry: if UPLO='U', the upper triangle of A is stored.
If UPLO='L', the lower triangle of A is stored.
Constraint: UPLO='U' or 'L'.
3:   N – INTEGERInput
On entry: n, the number of linear equations, i.e., the order of the matrix A.
Constraint: N≥0.
4:   NRHS – INTEGERInput
On entry: r, the number of right-hand sides, i.e., the number of columns of the matrix B.
Constraint: NRHS≥0.
5:   AP* – COMPLEX (KIND=nag_wp) arrayInput/Output
Note: the dimension of the array AP must be at least max 1,N×N+1/2.
On entry: if FACT='F' and EQUED='Y', AP must contain the equilibrated matrix DS A DS; otherwise, AP must contain the n by n Hermitian matrix A, packed by columns.
More precisely,
  • if UPLO='U', the upper triangle of A must be stored with element A ij in AP i+j j-1/2 for i≤j;
  • if UPLO='L', the lower triangle of A must be stored with element A ij in AP i+2 n-jj-1/2 for i≥j.
On exit: if FACT='F' or 'N', or if FACT='E' and EQUED='N', AP is not modified.
If FACT='E' and EQUED='Y', AP is overwritten by DS A DS.
6:   AFP* – COMPLEX (KIND=nag_wp) arrayInput/Output
Note: the dimension of the array AFP must be at least max 1,N×N+1/2.
On entry: if FACT='F', AFP contains the triangular factor U or L from the Cholesky factorization A=UH U or A=L LH, in the same storage format as AP. If EQUED='Y', AFP is the factorized form of the equilibrated matrix DS A DS.
On exit: if FACT='N' or if FACT='E' and EQUED='N', AFP returns the triangular factor U or L from the Cholesky factorization A=UH U or A=L LH of the original matrix A.
If FACT='E' and EQUED='Y', AFP returns the triangular factor U or L from the Cholesky factorization A=UH U or A=L LH of the equilibrated matrix A (see the description of AP for the form of the equilibrated matrix).
7:   EQUED – CHARACTER(1)Input/Output
On entry: if FACT='N' or 'E', EQUED need not be set.
If FACT='F', EQUED must specify the form of the equilibration that was performed as follows:
  • if EQUED='N', no equilibration;
  • if EQUED='Y', equilibration was performed, i.e., A has been replaced by DS A DS.
On exit: if FACT='F', EQUED is unchanged from entry.
Otherwise, if no constraints are violated, EQUED specifies the form of the equilibration that was performed as specified above.
Constraint: if FACT='F', EQUED='N' or 'Y'.
8:   S* – REAL (KIND=nag_wp) arrayInput/Output
Note: the dimension of the array S must be at least max 1,N.
On entry: if FACT='N' or 'E', S need not be set.
If FACT='F' and EQUED='Y', S must contain the scale factors, DS, for A; each element of S must be positive.
On exit: if FACT='F', S is unchanged from entry.
Otherwise, if no constraints are violated and EQUED='Y', S contains the scale factors, DS, for A; each element of S is positive.
9:   B LDB* – COMPLEX (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array B must be at least max 1,NRHS.
On entry: the n by r right-hand side matrix B.
On exit: if EQUED='N', B is not modified.
If EQUED='Y', B is overwritten by DS B.
10:   LDB – INTEGERInput
On entry: the first dimension of the array B as declared in the (sub)program from which F07GPF (ZPPSVX) is called.
Constraint: LDB≥max 1,N.
11:   X LDX* – COMPLEX (KIND=nag_wp) arrayOutput
Note: the second dimension of the array X must be at least max 1,NRHS.
On exit: if INFO=0 or N+1, the n by r solution matrix X to the original system of equations. Note that the arrays A and B are modified on exit if EQUED='Y', and the solution to the equilibrated system is DS-1 X.
12:   LDX – INTEGERInput
On entry: the first dimension of the array X as declared in the (sub)program from which F07GPF (ZPPSVX) is called.
Constraint: LDX≥max 1,N.
13:   RCOND – REAL (KIND=nag_wp)Output
On exit: if no constraints are violated, an estimate of the reciprocal condition number of the matrix A (after equilibration if that is performed), computed as RCOND=1.0/A 1 A-1 1 .
14:   FERR NRHS – REAL (KIND=nag_wp) arrayOutput
On exit: if INFO=0 or N+1, an estimate of the forward error bound for each computed solution vector, such that x^j-xj∞/xj∞≤FERR j where x^j is the jth column of the computed solution returned in the array X and xj is the corresponding column of the exact solution X. The estimate is as reliable as the estimate for RCOND, and is almost always a slight overestimate of the true error.
15:   BERR NRHS – REAL (KIND=nag_wp) arrayOutput
On exit: if INFO=0 or N+1, an estimate of the component-wise relative backward error of each computed solution vector x^j (i.e., the smallest relative change in any element of A or B that makes x^j an exact solution).
16:   WORK 2×N – COMPLEX (KIND=nag_wp) arrayWorkspace
17:   RWORK N – REAL (KIND=nag_wp) arrayWorkspace
18:   INFO – INTEGEROutput
On exit: INFO=0 unless the routine detects an error (see Section 6).

6 Error Indicators and Warnings

INFO<0
If INFO=-i, argument i had an illegal value. An explanatory message is output, and execution of the program is terminated.
INFO>0 and INFO≤N
The leading minor of order value of A is not positive definite, so the factorization could not be completed, and the solution has not been computed. RCOND=0.0 is returned.
INFO=N+1
U (or L) is nonsingular, but RCOND is less than machine precision, meaning that the matrix is singular to working precision. Nevertheless, the solution and error bounds are computed because there are a number of situations where the computed solution can be more accurate than the value of RCOND would suggest.

7 Accuracy

For each right-hand side vector b, the computed solution x is the exact solution of a perturbed system of equations A+E x=b, where
  • if UPLO='U', E≤c n ε UHU;
  • if UPLO='L', E≤c n ε LLH,
c n is a modest linear function of n, and ε is the machine precision. See Section 10.1 of Higham (2002) for further details.
If x^ is the true solution, then the computed solution x satisfies a forward error bound of the form
x-x^∞ x^∞ ≤ wc cond A,x^,b ,
where cond A,x^,b = A-1 A x^ + b ∞/ x^∞ ≤ cond A = A-1 A ∞≤κ∞ A . If x^ is the j th column of X , then wc is returned in BERR j and a bound on x - x^ ∞ / x^ ∞ is returned in FERR j . See Section 4.4 of Anderson et al. (1999) for further details.

8 Parallelism and Performance

F07GPF (ZPPSVX) is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
F07GPF (ZPPSVX) makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The factorization of A requires approximately 43 n 3 floating-point operations.
For each right-hand side, computation of the backward error involves a minimum of 16⁢n 2 floating-point operations. Each step of iterative refinement involves an additional 24⁢n 2 operations. At most five steps of iterative refinement are performed, but usually only one or two steps are required. Estimating the forward error involves solving a number of systems of equations of the form Ax=b ; the number is usually 4 or 5 and never more than 11. Each solution involves approximately 8⁢n 2 operations.
The real analogue of this routine is F07GBF (DPPSVX).

10 Example

This example solves the equations
AX=B ,
where A is the Hermitian positive definite matrix
A = 3.23 i+0.00 1.51-1.92 i 1.90+0.84 i 0.42+2.50 i 1.51+1.92 i 3.58 i+0.00 -0.23+1.11 i -1.18+1.37 i 1.90-0.84 i -0.23-1.11 i 4.09 i+0.00 2.33-0.14 i 0.42-2.50 i -1.18-1.37 i 2.33+0.14 i 4.29 i+0.00
and
B = 3.93-0 6.14 i 1.48+0 6.58 i 6.17+0 9.42 i 4.65-0 4.75 i -7.17-21.83 i -4.91+0 2.29 i 1.99-14.38 i 7.64-10.79 i .
Error estimates for the solutions, information on equilibration and an estimate of the reciprocal of the condition number of the scaled matrix A are also output.

10.1 Program Text

Program Text (f07gpfe.f90)

10.2 Program Data

Program Data (f07gpfe.d)

10.3 Program Results

Program Results (f07gpfe.r)

F07 Chapter Contents
F07 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F07GRF (ZPPTRF) : NAG Library, Mark 26

F07 Chapter Contents
F07 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F07GRF (ZPPTRF)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F07GRF (ZPPTRF) computes the Cholesky factorization of a complex Hermitian positive definite matrix, using packed storage.

2 Specification

SUBROUTINE F07GRF ( UPLO, N, AP, INFO)
INTEGER | N, INFO
COMPLEX (KIND=nag_wp) | AP(*)
CHARACTER(1) | UPLO
The routine may be called by its LAPACK name zpptrf.

3 Description

F07GRF (ZPPTRF) forms the Cholesky factorization of a complex Hermitian positive definite matrix A either as A=UH U if UPLO='U' or A=L LH if UPLO='L', where U is an upper triangular matrix and L is lower triangular, using packed storage.

4 References

Demmel J W (1989) On floating-point errors in Cholesky LAPACK Working Note No. 14 University of Tennessee, Knoxville http://www.netlib.org/lapack/lawnspdf/lawn14.pdf
Golub G H and Van Loan C F (1996) Matrix Computations (3rd Edition) Johns Hopkins University Press, Baltimore

5 Arguments

1:   UPLO – CHARACTER(1)Input
On entry: specifies whether the upper or lower triangular part of A is stored and how A is to be factorized.
UPLO='U'
The upper triangular part of A is stored and A is factorized as UH U, where U is upper triangular.
UPLO='L'
The lower triangular part of A is stored and A is factorized as L LH, where L is lower triangular.
Constraint: UPLO='U' or 'L'.
2:   N – INTEGERInput
On entry: n, the order of the matrix A.
Constraint: N≥0.
3:   AP* – COMPLEX (KIND=nag_wp) arrayInput/Output
Note: the dimension of the array AP must be at least max 1,N×N+1/2.
On entry: the n by n Hermitian matrix A, packed by columns.
More precisely,
  • if UPLO='U', the upper triangle of A must be stored with element A ij in AP i+j j-1/2 for i≤j;
  • if UPLO='L', the lower triangle of A must be stored with element A ij in AP i+2 n-jj-1/2 for i≥j.
On exit: if INFO=0, the factor U or L from the Cholesky factorization A=UH U or A=L LH, in the same storage format as A.
4:   INFO – INTEGEROutput
On exit: INFO=0 unless the routine detects an error (see Section 6).

6 Error Indicators and Warnings

INFO<0
If INFO=-i, argument i had an illegal value. An explanatory message is output, and execution of the program is terminated.
INFO>0
The leading minor of order value is not positive definite and the factorization could not be completed. Hence A itself is not positive definite. This may indicate an error in forming the matrix A. To factorize a Hermitian matrix which is not positive definite, call F07PRF (ZHPTRF) instead.

7 Accuracy

If UPLO='U', the computed factor U is the exact factor of a perturbed matrix A+E, where
E≤c n ε UHU ,
c n is a modest linear function of n, and ε is the machine precision.
If UPLO='L', a similar statement holds for the computed factor L. It follows that e ij≤c n ε⁢a iia jj.

8 Parallelism and Performance

F07GRF (ZPPTRF) makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The total number of real floating-point operations is approximately 43 n 3.
A call to F07GRF (ZPPTRF) may be followed by calls to the routines:
  • F07GSF (ZPPTRS) to solve AX=B;
  • F07GUF (ZPPCON) to estimate the condition number of A;
  • F07GWF (ZPPTRI) to compute the inverse of A.
The real analogue of this routine is F07GDF (DPPTRF).

10 Example

This example computes the Cholesky factorization of the matrix A, where
A= 3.23+0.00 i 1.51-1.92 i 1.90+0.84 i 0.42+2.50 i 1.51+1.92 i 3.58+0.00 i -0.23+1.11 i -1.18+1.37 i 1.90-0.84 i -0.23-1.11 i 4.09+0.00 i 2.33-0.14 i 0.42-2.50 i -1.18-1.37 i 2.33+0.14 i 4.29+0.00 i .
using packed storage.

10.1 Program Text

Program Text (f07grfe.f90)

10.2 Program Data

Program Data (f07grfe.d)

10.3 Program Results

Program Results (f07grfe.r)

F07 Chapter Contents
F07 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F07GSF (ZPPTRS) : NAG Library, Mark 26

F07 Chapter Contents
F07 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F07GSF (ZPPTRS)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F07GSF (ZPPTRS) solves a complex Hermitian positive definite system of linear equations with multiple right-hand sides,
AX=B ,
where A has been factorized by F07GRF (ZPPTRF), using packed storage.

2 Specification

SUBROUTINE F07GSF ( UPLO, N, NRHS, AP, B, LDB, INFO)
INTEGER | N, NRHS, LDB, INFO
COMPLEX (KIND=nag_wp) | AP(*), B(LDB,*)
CHARACTER(1) | UPLO
The routine may be called by its LAPACK name zpptrs.

3 Description

F07GSF (ZPPTRS) is used to solve a complex Hermitian positive definite system of linear equations AX=B, the routine must be preceded by a call to F07GRF (ZPPTRF) which computes the Cholesky factorization of A, using packed storage. The solution X is computed by forward and backward substitution.
If UPLO='U', A=UH U, where U is upper triangular; the solution X is computed by solving UH Y=B and then UX=Y.
If UPLO='L', A=L LH, where L is lower triangular; the solution X is computed by solving LY=B and then LH X=Y.

4 References

Golub G H and Van Loan C F (1996) Matrix Computations (3rd Edition) Johns Hopkins University Press, Baltimore

5 Arguments

1:   UPLO – CHARACTER(1)Input
On entry: specifies how A has been factorized.
UPLO='U'
A=UH U, where U is upper triangular.
UPLO='L'
A=L LH, where L is lower triangular.
Constraint: UPLO='U' or 'L'.
2:   N – INTEGERInput
On entry: n, the order of the matrix A.
Constraint: N≥0.
3:   NRHS – INTEGERInput
On entry: r, the number of right-hand sides.
Constraint: NRHS≥0.
4:   AP* – COMPLEX (KIND=nag_wp) arrayInput
Note: the dimension of the array AP must be at least max 1,N×N+1/2.
On entry: the Cholesky factor of A stored in packed form, as returned by F07GRF (ZPPTRF).
5:   B LDB* – COMPLEX (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array B must be at least max 1,NRHS.
On entry: the n by r right-hand side matrix B.
On exit: the n by r solution matrix X.
6:   LDB – INTEGERInput
On entry: the first dimension of the array B as declared in the (sub)program from which F07GSF (ZPPTRS) is called.
Constraint: LDB≥max 1,N.
7:   INFO – INTEGEROutput
On exit: INFO=0 unless the routine detects an error (see Section 6).

6 Error Indicators and Warnings

INFO<0
If INFO=-i, argument i had an illegal value. An explanatory message is output, and execution of the program is terminated.

7 Accuracy

For each right-hand side vector b, the computed solution x is the exact solution of a perturbed system of equations A+E x=b, where
  • if UPLO='U', E≤c n ε UHU;
  • if UPLO='L', E≤c n ε LLH,
c n is a modest linear function of n, and ε is the machine precision.
If x^ is the true solution, then the computed solution x satisfies a forward error bound of the form
x-x^∞ x∞ ≤c n cond A,x ε
where cond A,x=A-1Ax∞/x∞≤cond A=A-1A∞≤κ∞A.
Note that cond A,x can be much smaller than cond A.
Forward and backward error bounds can be computed by calling F07GVF (ZPPRFS), and an estimate for κ∞A (=κ 1 A) can be obtained by calling F07GUF (ZPPCON).

8 Parallelism and Performance

F07GSF (ZPPTRS) is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
F07GSF (ZPPTRS) makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The total number of real floating-point operations is approximately 8⁢n 2 r.
This routine may be followed by a call to F07GVF (ZPPRFS) to refine the solution and return an error estimate.
The real analogue of this routine is F07GEF (DPPTRS).

10 Example

This example solves the system of equations AX=B, where
A= 3.23+0.00 i 1.51-1.92 i 1.90+0.84 i 0.42+2.50 i 1.51+1.92 i 3.58+0.00 i -0.23+1.11 i -1.18+1.37 i 1.90-0.84 i -0.23-1.11 i 4.09+0.00 i 2.33-0.14 i 0.42-2.50 i -1.18-1.37 i 2.33+0.14 i 4.29+0.00 i
and
B= 3.93-0 6.14 i 1.48+0 6.58 i 6.17+0 9.42 i 4.65-0 4.75 i -7.17-21.83 i -4.91+0 2.29 i 1.99-14.38 i 7.64-10.79 i .
Here A is Hermitian positive definite, stored in packed form, and must first be factorized by F07GRF (ZPPTRF).

10.1 Program Text

Program Text (f07gsfe.f90)

10.2 Program Data

Program Data (f07gsfe.d)

10.3 Program Results

Program Results (f07gsfe.r)

F07 Chapter Contents
F07 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F07GTF (ZPPEQU) : NAG Library, Mark 26

F07 Chapter Contents
F07 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F07GTF (ZPPEQU)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F07GTF (ZPPEQU) computes a diagonal scaling matrix S intended to equilibrate a complex n by n Hermitian positive definite matrix A , stored in packed format, and reduce its condition number.

2 Specification

SUBROUTINE F07GTF ( UPLO, N, AP, S, SCOND, AMAX, INFO)
INTEGER | N, INFO
REAL (KIND=nag_wp) | S(N), SCOND, AMAX
COMPLEX (KIND=nag_wp) | AP(*)
CHARACTER(1) | UPLO
The routine may be called by its LAPACK name zppequ.

3 Description

F07GTF (ZPPEQU) computes a diagonal scaling matrix S chosen so that
sj=1 / a jj .
This means that the matrix B given by
B=SAS ,
has diagonal elements equal to unity. This in turn means that the condition number of B , κ 2 B , is within a factor n of the matrix of smallest possible condition number over all possible choices of diagonal scalings (see Corollary 7.6 of Higham (2002)).

4 References

Higham N J (2002) Accuracy and Stability of Numerical Algorithms (2nd Edition) SIAM, Philadelphia

5 Arguments

1:   UPLO – CHARACTER(1)Input
On entry: indicates whether the upper or lower triangular part of A is stored in the array AP, as follows:
UPLO='U'
The upper triangle of A is stored.
UPLO='L'
The lower triangle of A is stored.
Constraint: UPLO='U' or 'L'.
2:   N – INTEGERInput
On entry: n, the order of the matrix A.
Constraint: N≥0.
3:   AP* – COMPLEX (KIND=nag_wp) arrayInput
Note: the dimension of the array AP must be at least max 1,N×N+1/2.
On entry: the n by n Hermitian matrix A, packed by columns.
More precisely,
  • if UPLO='U', the upper triangle of A must be stored with element A ij in AP i+j j-1/2 for i≤j;
  • if UPLO='L', the lower triangle of A must be stored with element A ij in AP i+2 n-jj-1/2 for i≥j.
Only the elements of AP corresponding to the diagonal elements A are referenced.
4:   S N – REAL (KIND=nag_wp) arrayOutput
On exit: if INFO=0, S contains the diagonal elements of the scaling matrix S.
5:   SCOND – REAL (KIND=nag_wp)Output
On exit: if INFO=0, SCOND contains the ratio of the smallest value of S to the largest value of S. If SCOND≥0.1 and AMAX is neither too large nor too small, it is not worth scaling by S.
6:   AMAX – REAL (KIND=nag_wp)Output
On exit: max a ij. If AMAX is very close to overflow or underflow, the matrix A should be scaled.
7:   INFO – INTEGEROutput
On exit: INFO=0 unless the routine detects an error (see Section 6).

6 Error Indicators and Warnings

INFO<0
If INFO=-i, argument i had an illegal value. An explanatory message is output, and execution of the program is terminated.
INFO>0
The valueth diagonal element of A is not positive (and hence A cannot be positive definite).

7 Accuracy

The computed scale factors will be close to the exact scale factors.

8 Parallelism and Performance

F07GTF (ZPPEQU) is not threaded in any implementation.

9 Further Comments

The real analogue of this routine is F07GFF (DPPEQU).

10 Example

This example equilibrates the Hermitian positive definite matrix A given by
A = (3.23 ((1.51-1.92 i 1.90+0.84 i×105 ((0.42+2.50 i (1.51+1.92 i ((3.58 -0.23+1.11 i×105 -1.18+1.37 i 1.90-0.84 i×105 -0.23-1.11 i×105 4.09×1010 (2.33-0.14 i×105 (0.42-2.50 i (-1.18-1.37 i 2.33+0.14 i×105 ((4.29 .
Details of the scaling factors and the scaled matrix are output.

10.1 Program Text

Program Text (f07gtfe.f90)

10.2 Program Data

Program Data (f07gtfe.d)

10.3 Program Results

Program Results (f07gtfe.r)

F07 Chapter Contents
F07 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F07GUF (ZPPCON) : NAG Library, Mark 26

F07 Chapter Contents
F07 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F07GUF (ZPPCON)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F07GUF (ZPPCON) estimates the condition number of a complex Hermitian positive definite matrix A, where A has been factorized by F07GRF (ZPPTRF), using packed storage.

2 Specification

SUBROUTINE F07GUF ( UPLO, N, AP, ANORM, RCOND, WORK, RWORK, INFO)
INTEGER | N, INFO
REAL (KIND=nag_wp) | ANORM, RCOND, RWORK(N)
COMPLEX (KIND=nag_wp) | AP(*), WORK(2*N)
CHARACTER(1) | UPLO
The routine may be called by its LAPACK name zppcon.

3 Description

F07GUF (ZPPCON) estimates the condition number (in the 1-norm) of a complex Hermitian positive definite matrix A:
κ 1 A=A 1A-1 1 .
Since A is Hermitian, κ 1 A=κ∞A=A∞A-1∞.
Because κ 1 A is infinite if A is singular, the routine actually returns an estimate of the reciprocal of κ 1 A.
The routine should be preceded by a call to F06UDF to compute A 1 and a call to F07GRF (ZPPTRF) to compute the Cholesky factorization of A. The routine then uses Higham's implementation of Hager's method (see Higham (1988)) to estimate A-1 1.

4 References

Higham N J (1988) FORTRAN codes for estimating the one-norm of a real or complex matrix, with applications to condition estimation ACM Trans. Math. Software 14 381–396

5 Arguments

1:   UPLO – CHARACTER(1)Input
On entry: specifies how A has been factorized.
UPLO='U'
A=UH U, where U is upper triangular.
UPLO='L'
A=L LH, where L is lower triangular.
Constraint: UPLO='U' or 'L'.
2:   N – INTEGERInput
On entry: n, the order of the matrix A.
Constraint: N≥0.
3:   AP* – COMPLEX (KIND=nag_wp) arrayInput
Note: the dimension of the array AP must be at least max 1,N×N+1/2.
On entry: the Cholesky factor of A stored in packed form, as returned by F07GRF (ZPPTRF).
4:   ANORM – REAL (KIND=nag_wp)Input
On entry: the 1-norm of the original matrix A, which may be computed by calling F06UDF with its argument NORM='1'. ANORM must be computed either before calling F07GRF (ZPPTRF) or else from a copy of the original matrix A.
Constraint: ANORM≥0.0.
5:   RCOND – REAL (KIND=nag_wp)Output
On exit: an estimate of the reciprocal of the condition number of A. RCOND is set to zero if exact singularity is detected or the estimate underflows. If RCOND is less than machine precision, A is singular to working precision.
6:   WORK 2×N – COMPLEX (KIND=nag_wp) arrayWorkspace
7:   RWORK N – REAL (KIND=nag_wp) arrayWorkspace
8:   INFO – INTEGEROutput
On exit: INFO=0 unless the routine detects an error (see Section 6).

6 Error Indicators and Warnings

INFO<0
If INFO=-i, argument i had an illegal value. An explanatory message is output, and execution of the program is terminated.

7 Accuracy

The computed estimate RCOND is never less than the true value ρ, and in practice is nearly always less than 10 ρ, although examples can be constructed where RCOND is much larger.

8 Parallelism and Performance

F07GUF (ZPPCON) makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

A call to F07GUF (ZPPCON) involves solving a number of systems of linear equations of the form Ax=b; the number is usually 5 and never more than 11. Each solution involves approximately 8⁢n 2 real floating-point operations but takes considerably longer than a call to F07GSF (ZPPTRS) with one right-hand side, because extra care is taken to avoid overflow when A is approximately singular.
The real analogue of this routine is F07GGF (DPPCON).

10 Example

This example estimates the condition number in the 1-norm (or ∞-norm) of the matrix A, where
A= 3.23+0.00 i 1.51-1.92 i 1.90+0.84 i 0.42+2.50 i 1.51+1.92 i 3.58+0.00 i -0.23+1.11 i -1.18+1.37 i 1.90-0.84 i -0.23-1.11 i 4.09+0.00 i 2.33-0.14 i 0.42-2.50 i -1.18-1.37 i 2.33+0.14 i 4.29+0.00 i .
Here A is Hermitian positive definite, stored in packed form, and must first be factorized by F07GRF (ZPPTRF). The true condition number in the 1-norm is 201.92.

10.1 Program Text

Program Text (f07gufe.f90)

10.2 Program Data

Program Data (f07gufe.d)

10.3 Program Results

Program Results (f07gufe.r)

F07 Chapter Contents
F07 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F07GVF (ZPPRFS) : NAG Library, Mark 26

F07 Chapter Contents
F07 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F07GVF (ZPPRFS)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F07GVF (ZPPRFS) returns error bounds for the solution of a complex Hermitian positive definite system of linear equations with multiple right-hand sides, AX=B, using packed storage. It improves the solution by iterative refinement, in order to reduce the backward error as much as possible.

2 Specification

SUBROUTINE F07GVF ( UPLO, N, NRHS, AP, AFP, B, LDB, X, LDX, FERR, BERR, WORK, RWORK, INFO)
INTEGER | N, NRHS, LDB, LDX, INFO
REAL (KIND=nag_wp) | FERR(NRHS), BERR(NRHS), RWORK(N)
COMPLEX (KIND=nag_wp) | AP(*), AFP(*), B(LDB,*), X(LDX,*), WORK(2*N)
CHARACTER(1) | UPLO
The routine may be called by its LAPACK name zpprfs.

3 Description

F07GVF (ZPPRFS) returns the backward errors and estimated bounds on the forward errors for the solution of a complex Hermitian positive definite system of linear equations with multiple right-hand sides AX=B, using packed storage. The routine handles each right-hand side vector (stored as a column of the matrix B) independently, so we describe the function of F07GVF (ZPPRFS) in terms of a single right-hand side b and solution x.
Given a computed solution x, the routine computes the component-wise backward error β. This is the size of the smallest relative perturbation in each element of A and b such that x is the exact solution of a perturbed system
A+δA x=b+δb δ a ij≤β a ij   and   δ bi≤β bi .
Then the routine estimates a bound for the component-wise forward error in the computed solution, defined by:
maxi xi-x^i/maxi xi
where x^ is the true solution.
For details of the method, see the F07 Chapter Introduction.

4 References

Golub G H and Van Loan C F (1996) Matrix Computations (3rd Edition) Johns Hopkins University Press, Baltimore

5 Arguments

1:   UPLO – CHARACTER(1)Input
On entry: specifies whether the upper or lower triangular part of A is stored and how A is to be factorized.
UPLO='U'
The upper triangular part of A is stored and A is factorized as UH U, where U is upper triangular.
UPLO='L'
The lower triangular part of A is stored and A is factorized as L LH, where L is lower triangular.
Constraint: UPLO='U' or 'L'.
2:   N – INTEGERInput
On entry: n, the order of the matrix A.
Constraint: N≥0.
3:   NRHS – INTEGERInput
On entry: r, the number of right-hand sides.
Constraint: NRHS≥0.
4:   AP* – COMPLEX (KIND=nag_wp) arrayInput
Note: the dimension of the array AP must be at least max 1,N×N+1/2.
On entry: the n by n original Hermitian positive definite matrix A as supplied to F07GRF (ZPPTRF).
5:   AFP* – COMPLEX (KIND=nag_wp) arrayInput
Note: the dimension of the array AFP must be at least max 1,N×N+1/2.
On entry: the Cholesky factor of A stored in packed form, as returned by F07GRF (ZPPTRF).
6:   B LDB* – COMPLEX (KIND=nag_wp) arrayInput
Note: the second dimension of the array B must be at least max 1,NRHS.
On entry: the n by r right-hand side matrix B.
7:   LDB – INTEGERInput
On entry: the first dimension of the array B as declared in the (sub)program from which F07GVF (ZPPRFS) is called.
Constraint: LDB≥max 1,N.
8:   X LDX* – COMPLEX (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array X must be at least max 1,NRHS.
On entry: the n by r solution matrix X, as returned by F07GSF (ZPPTRS).
On exit: the improved solution matrix X.
9:   LDX – INTEGERInput
On entry: the first dimension of the array X as declared in the (sub)program from which F07GVF (ZPPRFS) is called.
Constraint: LDX≥max 1,N.
10:   FERR NRHS – REAL (KIND=nag_wp) arrayOutput
On exit: FERR j contains an estimated error bound for the jth solution vector, that is, the jth column of X, for j=1,2,…,r.
11:   BERR NRHS – REAL (KIND=nag_wp) arrayOutput
On exit: BERR j contains the component-wise backward error bound β for the jth solution vector, that is, the jth column of X, for j=1,2,…,r.
12:   WORK 2×N – COMPLEX (KIND=nag_wp) arrayWorkspace
13:   RWORK N – REAL (KIND=nag_wp) arrayWorkspace
14:   INFO – INTEGEROutput
On exit: INFO=0 unless the routine detects an error (see Section 6).

6 Error Indicators and Warnings

INFO<0
If INFO=-i, argument i had an illegal value. An explanatory message is output, and execution of the program is terminated.

7 Accuracy

The bounds returned in FERR are not rigorous, because they are estimated, not computed exactly; but in practice they almost always overestimate the actual error.

8 Parallelism and Performance

F07GVF (ZPPRFS) is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
F07GVF (ZPPRFS) makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

For each right-hand side, computation of the backward error involves a minimum of 16⁢n 2 real floating-point operations. Each step of iterative refinement involves an additional 24 n 2 real operations. At most five steps of iterative refinement are performed, but usually only one or two steps are required.
Estimating the forward error involves solving a number of systems of linear equations of the form Ax=b; the number is usually 5 and never more than 11. Each solution involves approximately 8 n 2 real operations.
The real analogue of this routine is F07GHF (DPPRFS).

10 Example

This example solves the system of equations AX=B using iterative refinement and to compute the forward and backward error bounds, where
A= 3.23+0.00 i 1.51-1.92 i 1.90+0.84 i 0.42+2.50 i 1.51+1.92 i 3.58+0.00 i -0.23+1.11 i -1.18+1.37 i 1.90-0.84 i -0.23-1.11 i 4.09+0.00 i 2.33-0.14 i 0.42-2.50 i -1.18-1.37 i 2.33+0.14 i 4.29+0.00 i
and
B= 3.93-0 6.14 i 1.48+0 6.58 i 6.17+0 9.42 i 4.65-0 4.75 i -7.17-21.83 i -4.91+0 2.29 i 1.99-14.38 i 7.64-10.79 i .
Here A is Hermitian positive definite, stored in packed form, and must first be factorized by F07GRF (ZPPTRF).

10.1 Program Text

Program Text (f07gvfe.f90)

10.2 Program Data

Program Data (f07gvfe.d)

10.3 Program Results

Program Results (f07gvfe.r)

F07 Chapter Contents
F07 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F07GWF (ZPPTRI) : NAG Library, Mark 26

F07 Chapter Contents
F07 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F07GWF (ZPPTRI)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F07GWF (ZPPTRI) computes the inverse of a complex Hermitian positive definite matrix A, where A has been factorized by F07GRF (ZPPTRF), using packed storage.

2 Specification

SUBROUTINE F07GWF ( UPLO, N, AP, INFO)
INTEGER | N, INFO
COMPLEX (KIND=nag_wp) | AP(*)
CHARACTER(1) | UPLO
The routine may be called by its LAPACK name zpptri.

3 Description

F07GWF (ZPPTRI) is used to compute the inverse of a complex Hermitian positive definite matrix A, the routine must be preceded by a call to F07GRF (ZPPTRF), which computes the Cholesky factorization of A, using packed storage.
If UPLO='U', A=UH U and A-1 is computed by first inverting U and then forming U-1 U-H.
If UPLO='L', A=L LH and A-1 is computed by first inverting L and then forming L-H L-1.

4 References

Du Croz J J and Higham N J (1992) Stability of methods for matrix inversion IMA J. Numer. Anal. 12 1–19

5 Arguments

1:   UPLO – CHARACTER(1)Input
On entry: specifies how A has been factorized.
UPLO='U'
A=UH U, where U is upper triangular.
UPLO='L'
A=L LH, where L is lower triangular.
Constraint: UPLO='U' or 'L'.
2:   N – INTEGERInput
On entry: n, the order of the matrix A.
Constraint: N≥0.
3:   AP* – COMPLEX (KIND=nag_wp) arrayInput/Output
Note: the dimension of the array AP must be at least max 1,N×N+1/2.
On entry: the Cholesky factor of A stored in packed form, as returned by F07GRF (ZPPTRF).
On exit: the factorization is overwritten by the n by n matrix A-1.
More precisely,
  • if UPLO='U', the upper triangle of A-1 must be stored with element A ij in AP i+j j-1/2 for i≤j;
  • if UPLO='L', the lower triangle of A-1 must be stored with element A ij in AP i+2 n-jj-1/2 for i≥j.
4:   INFO – INTEGEROutput
On exit: INFO=0 unless the routine detects an error (see Section 6).

6 Error Indicators and Warnings

INFO<0
If INFO=-i, argument i had an illegal value. An explanatory message is output, and execution of the program is terminated.
INFO>0
Diagonal element value of the Cholesky factor is zero; the Cholesky factor is singular and the inverse of A cannot be computed.

7 Accuracy

The computed inverse X satisfies
XA-I 2≤c n ε κ 2 A   and   AX-I 2≤c n ε κ 2 A ,
where c n is a modest function of n, ε is the machine precision and κ 2 A is the condition number of A defined by
κ 2 A=A 2A-1 2 .

8 Parallelism and Performance

F07GWF (ZPPTRI) makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The total number of real floating-point operations is approximately 83 n 3.
The real analogue of this routine is F07GJF (DPPTRI).

10 Example

This example computes the inverse of the matrix A, where
A= 3.23+0.00 i 1.51-1.92 i 1.90+0.84 i 0.42+2.50 i 1.51+1.92 i 3.58+0.00 i -0.23+1.11 i -1.18+1.37 i 1.90-0.84 i -0.23-1.11 i 4.09+0.00 i 2.33-0.14 i 0.42-2.50 i -1.18-1.37 i 2.33+0.14 i 4.29+0.00 i .
Here A is Hermitian positive definite, stored in packed form, and must first be factorized by F07GRF (ZPPTRF).

10.1 Program Text

Program Text (f07gwfe.f90)

10.2 Program Data

Program Data (f07gwfe.d)

10.3 Program Results

Program Results (f07gwfe.r)

F07 Chapter Contents
F07 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F07HAF (DPBSV) : NAG Library, Mark 26

F07 Chapter Contents
F07 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F07HAF (DPBSV)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F07HAF (DPBSV) computes the solution to a real system of linear equations
AX=B ,
where A is an n by n symmetric positive definite band matrix of bandwidth 2 kd + 1 and X and B are n by r matrices.

2 Specification

SUBROUTINE F07HAF ( UPLO, N, KD, NRHS, AB, LDAB, B, LDB, INFO)
INTEGER | N, KD, NRHS, LDAB, LDB, INFO
REAL (KIND=nag_wp) | AB(LDAB,*), B(LDB,*)
CHARACTER(1) | UPLO
The routine may be called by its LAPACK name dpbsv.

3 Description

F07HAF (DPBSV) uses the Cholesky decomposition to factor A as A=UT U if UPLO='U' or A=L LT if UPLO='L', where U is an upper triangular band matrix, and L is a lower triangular band matrix, with the same number of superdiagonals or subdiagonals as A. The factored form of A is then used to solve the system of equations AX=B.

4 References

Anderson E, Bai Z, Bischof C, Blackford S, Demmel J, Dongarra J J, Du Croz J J, Greenbaum A, Hammarling S, McKenney A and Sorensen D (1999) LAPACK Users' Guide (3rd Edition) SIAM, Philadelphia http://www.netlib.org/lapack/lug
Golub G H and Van Loan C F (1996) Matrix Computations (3rd Edition) Johns Hopkins University Press, Baltimore

5 Arguments

1:   UPLO – CHARACTER(1)Input
On entry: if UPLO='U', the upper triangle of A is stored.
If UPLO='L', the lower triangle of A is stored.
Constraint: UPLO='U' or 'L'.
2:   N – INTEGERInput
On entry: n, the number of linear equations, i.e., the order of the matrix A.
Constraint: N≥0.
3:   KD – INTEGERInput
On entry: kd, the number of superdiagonals of the matrix A if UPLO='U', or the number of subdiagonals if UPLO='L'.
Constraint: KD≥0.
4:   NRHS – INTEGERInput
On entry: r, the number of right-hand sides, i.e., the number of columns of the matrix B.
Constraint: NRHS≥0.
5:   AB LDAB* – REAL (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array AB must be at least max 1,N.
On entry: the upper or lower triangle of the symmetric band matrix A.
The matrix is stored in rows 1 to kd+1, more precisely,
  • if UPLO='U', the elements of the upper triangle of A within the band must be stored with element A ij in AB kd+1+i-j j​ for ​max 1,j-kd≤i≤j;
  • if UPLO='L', the elements of the lower triangle of A within the band must be stored with element A ij in AB 1+i-j j​ for ​j≤i≤min n,j+kd.
On exit: if INFO=0, the triangular factor U or L from the Cholesky factorization A=UT U or A=L LT of the band matrix A, in the same storage format as A.
6:   LDAB – INTEGERInput
On entry: the first dimension of the array AB as declared in the (sub)program from which F07HAF (DPBSV) is called.
Constraint: LDAB≥KD+1.
7:   B LDB* – REAL (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array B must be at least max 1,NRHS.
On entry: the n by r right-hand side matrix B.
On exit: if INFO=0, the n by r solution matrix X.
8:   LDB – INTEGERInput
On entry: the first dimension of the array B as declared in the (sub)program from which F07HAF (DPBSV) is called.
Constraint: LDB≥max 1,N.
9:   INFO – INTEGEROutput
On exit: INFO=0 unless the routine detects an error (see Section 6).

6 Error Indicators and Warnings

INFO<0
If INFO=-i, argument i had an illegal value. An explanatory message is output, and execution of the program is terminated.
INFO>0
The leading minor of order value of A is not positive definite, so the factorization could not be completed, and the solution has not been computed.

7 Accuracy

The computed solution for a single right-hand side, x^ , satisfies an equation of the form
A+E x^=b ,
where
E 1 = O ε A 1
and ε is the machine precision. An approximate error bound for the computed solution is given by
x^-x 1 x 1 ≤ κ A E 1 A 1 ,
where κ A = A-1 1 A 1 , the condition number of A with respect to the solution of the linear equations. See Section 4.4 of Anderson et al. (1999) for further details.
F07HBF (DPBSVX) is a comprehensive LAPACK driver that returns forward and backward error bounds and an estimate of the condition number. Alternatively, F04BFF solves Ax=b and returns a forward error bound and condition estimate. F04BFF calls F07HAF (DPBSV) to solve the equations.

8 Parallelism and Performance

F07HAF (DPBSV) is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
F07HAF (DPBSV) makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

When n≫k , the total number of floating-point operations is approximately n k+1 2+4 nkr , where k is the number of superdiagonals and r is the number of right-hand sides.
The complex analogue of this routine is F07HNF (ZPBSV).

10 Example

This example solves the equations
Ax=b ,
where A is the symmetric positive definite band matrix
A = 5.49 2.68 0.00 0.00 2.68 5.63 -2.39 0.00 0.00 -2.39 2.60 -2.22 0.00 0.00 -2.22 5.17   and   b = 22.09 9.31 -5.24 11.83 .
Details of the Cholesky factorization of A are also output.

10.1 Program Text

Program Text (f07hafe.f90)

10.2 Program Data

Program Data (f07hafe.d)

10.3 Program Results

Program Results (f07hafe.r)

F07 Chapter Contents
F07 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F07HBF (DPBSVX) : NAG Library, Mark 26

F07 Chapter Contents
F07 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F07HBF (DPBSVX)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F07HBF (DPBSVX) uses the Cholesky factorization
A=UT U   or   A=L LT
to compute the solution to a real system of linear equations
AX=B ,
where A is an n by n symmetric positive definite band matrix of bandwidth 2 kd + 1 and X and B are n by r matrices. Error bounds on the solution and a condition estimate are also provided.

2 Specification

SUBROUTINE F07HBF ( FACT, UPLO, N, KD, NRHS, AB, LDAB, AFB, LDAFB, EQUED, S, B, LDB, X, LDX, RCOND, FERR, BERR, WORK, IWORK, INFO)
INTEGER | N, KD, NRHS, LDAB, LDAFB, LDB, LDX, IWORK(N), INFO
REAL (KIND=nag_wp) | AB(LDAB,*), AFB(LDAFB,*), S(*), B(LDB,*), X(LDX,*), RCOND, FERR(NRHS), BERR(NRHS), WORK(3*N)
CHARACTER(1) | FACT, UPLO, EQUED
The routine may be called by its LAPACK name dpbsvx.

3 Description

F07HBF (DPBSVX) performs the following steps:
1. If FACT='E', real diagonal scaling factors, DS , are computed to equilibrate the system:
DS A DS DS-1 X = DS B .
Whether or not the system will be equilibrated depends on the scaling of the matrix A, but if equilibration is used, A is overwritten by DS A DS and B by DS B.
2. | If FACT='N' or 'E', the Cholesky decomposition is used to factor the matrix A (after equilibration if FACT='E') as A=UT U if UPLO='U' or A=L LT if UPLO='L', where U is an upper triangular matrix and L is a lower triangular matrix.
3. | If the leading i by i principal minor of A is not positive definite, then the routine returns with INFO=i. Otherwise, the factored form of A is used to estimate the condition number of the matrix A. If the reciprocal of the condition number is less than machine precision, INFO=N+1 is returned as a warning, but the routine still goes on to solve for X and compute error bounds as described below.
4. | The system of equations is solved for X using the factored form of A.
5. | Iterative refinement is applied to improve the computed solution matrix and to calculate error bounds and backward error estimates for it.
6. | If equilibration was used, the matrix X is premultiplied by DS so that it solves the original system before equilibration.

4 References

Anderson E, Bai Z, Bischof C, Blackford S, Demmel J, Dongarra J J, Du Croz J J, Greenbaum A, Hammarling S, McKenney A and Sorensen D (1999) LAPACK Users' Guide (3rd Edition) SIAM, Philadelphia http://www.netlib.org/lapack/lug
Golub G H and Van Loan C F (1996) Matrix Computations (3rd Edition) Johns Hopkins University Press, Baltimore
Higham N J (2002) Accuracy and Stability of Numerical Algorithms (2nd Edition) SIAM, Philadelphia

5 Arguments

1:   FACT – CHARACTER(1)Input
On entry: specifies whether or not the factorized form of the matrix A is supplied on entry, and if not, whether the matrix A should be equilibrated before it is factorized.
FACT='F'
AFB contains the factorized form of A. If EQUED='Y', the matrix A has been equilibrated with scaling factors given by S. AB and AFB will not be modified.
FACT='N'
The matrix A will be copied to AFB and factorized.
FACT='E'
The matrix A will be equilibrated if necessary, then copied to AFB and factorized.
Constraint: FACT='F', 'N' or 'E'.
2:   UPLO – CHARACTER(1)Input
On entry: if UPLO='U', the upper triangle of A is stored.
If UPLO='L', the lower triangle of A is stored.
Constraint: UPLO='U' or 'L'.
3:   N – INTEGERInput
On entry: n, the number of linear equations, i.e., the order of the matrix A.
Constraint: N≥0.
4:   KD – INTEGERInput
On entry: kd, the number of superdiagonals of the matrix A if UPLO='U', or the number of subdiagonals if UPLO='L'.
Constraint: KD≥0.
5:   NRHS – INTEGERInput
On entry: r, the number of right-hand sides, i.e., the number of columns of the matrix B.
Constraint: NRHS≥0.
6:   AB LDAB* – REAL (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array AB must be at least max 1,N.
On entry: the upper or lower triangle of the symmetric band matrix A, except if FACT='F' and EQUED='Y', in which case AB must contain the equilibrated matrix DS A DS.
The matrix is stored in rows 1 to kd+1, more precisely,
  • if UPLO='U', the elements of the upper triangle of A within the band must be stored with element A ij in AB kd+1+i-j j​ for ​max 1,j-kd≤i≤j;
  • if UPLO='L', the elements of the lower triangle of A within the band must be stored with element A ij in AB 1+i-j j​ for ​j≤i≤min n,j+kd.
On exit: if FACT='E' and EQUED='Y', AB is overwritten by DS A DS.
7:   LDAB – INTEGERInput
On entry: the first dimension of the array AB as declared in the (sub)program from which F07HBF (DPBSVX) is called.
Constraint: LDAB≥KD+1.
8:   AFB LDAFB* – REAL (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array AFB must be at least max 1,N.
On entry: if FACT='F', AFB contains the triangular factor U or L from the Cholesky factorization A=UT U or A=L LT of the band matrix A, in the same storage format as A. If EQUED='Y', AFB is the factorized form of the equilibrated matrix A.
On exit: if FACT='N', AFB returns the triangular factor U or L from the Cholesky factorization A=UT U or A=L LT.
If FACT='E', AFB returns the triangular factor U or L from the Cholesky factorization A=UT U or A=L LT of the equilibrated matrix A (see the description of AB for the form of the equilibrated matrix).
9:   LDAFB – INTEGERInput
On entry: the first dimension of the array AFB as declared in the (sub)program from which F07HBF (DPBSVX) is called.
Constraint: LDAFB≥KD+1.
10:   EQUED – CHARACTER(1)Input/Output
On entry: if FACT='N' or 'E', EQUED need not be set.
If FACT='F', EQUED must specify the form of the equilibration that was performed as follows:
  • if EQUED='N', no equilibration;
  • if EQUED='Y', equilibration was performed, i.e., A has been replaced by DS A DS.
On exit: if FACT='F', EQUED is unchanged from entry.
Otherwise, if no constraints are violated, EQUED specifies the form of the equilibration that was performed as specified above.
Constraint: if FACT='F', EQUED='N' or 'Y'.
11:   S* – REAL (KIND=nag_wp) arrayInput/Output
Note: the dimension of the array S must be at least max 1,N.
On entry: if FACT='N' or 'E', S need not be set.
If FACT='F' and EQUED='Y', S must contain the scale factors, DS, for A; each element of S must be positive.
On exit: if FACT='F', S is unchanged from entry.
Otherwise, if no constraints are violated and EQUED='Y', S contains the scale factors, DS, for A; each element of S is positive.
12:   B LDB* – REAL (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array B must be at least max 1,NRHS.
On entry: the n by r right-hand side matrix B.
On exit: if EQUED='N', B is not modified.
If EQUED='Y', B is overwritten by DS B.
13:   LDB – INTEGERInput
On entry: the first dimension of the array B as declared in the (sub)program from which F07HBF (DPBSVX) is called.
Constraint: LDB≥max 1,N.
14:   X LDX* – REAL (KIND=nag_wp) arrayOutput
Note: the second dimension of the array X must be at least max 1,NRHS.
On exit: if INFO=0 or N+1, the n by r solution matrix X to the original system of equations. Note that the arrays A and B are modified on exit if EQUED='Y', and the solution to the equilibrated system is DS-1 X.
15:   LDX – INTEGERInput
On entry: the first dimension of the array X as declared in the (sub)program from which F07HBF (DPBSVX) is called.
Constraint: LDX≥max 1,N.
16:   RCOND – REAL (KIND=nag_wp)Output
On exit: if no constraints are violated, an estimate of the reciprocal condition number of the matrix A (after equilibration if that is performed), computed as RCOND=1.0/A 1 A-1 1 .
17:   FERR NRHS – REAL (KIND=nag_wp) arrayOutput
On exit: if INFO=0 or N+1, an estimate of the forward error bound for each computed solution vector, such that x^j-xj∞/xj∞≤FERR j where x^j is the jth column of the computed solution returned in the array X and xj is the corresponding column of the exact solution X. The estimate is as reliable as the estimate for RCOND, and is almost always a slight overestimate of the true error.
18:   BERR NRHS – REAL (KIND=nag_wp) arrayOutput
On exit: if INFO=0 or N+1, an estimate of the component-wise relative backward error of each computed solution vector x^j (i.e., the smallest relative change in any element of A or B that makes x^j an exact solution).
19:   WORK 3×N – REAL (KIND=nag_wp) arrayWorkspace
20:   IWORK N – INTEGER arrayWorkspace
21:   INFO – INTEGEROutput
On exit: INFO=0 unless the routine detects an error (see Section 6).

6 Error Indicators and Warnings

INFO<0
If INFO=-i, argument i had an illegal value. An explanatory message is output, and execution of the program is terminated.
INFO>0 and INFO≤N
The leading minor of order value of A is not positive definite, so the factorization could not be completed, and the solution has not been computed. RCOND=0.0 is returned.
INFO=N+1
U (or L) is nonsingular, but RCOND is less than machine precision, meaning that the matrix is singular to working precision. Nevertheless, the solution and error bounds are computed because there are a number of situations where the computed solution can be more accurate than the value of RCOND would suggest.

7 Accuracy

For each right-hand side vector b, the computed solution x is the exact solution of a perturbed system of equations A+E x = b, where
  • if UPLO='U', E≤c n ε UTU;
  • if UPLO='L', E≤c n ε LLT,
c n is a modest linear function of n, and ε is the machine precision. See Section 10.1 of Higham (2002) for further details.
If x^ is the true solution, then the computed solution x satisfies a forward error bound of the form
x-x^∞ x^∞ ≤ wc cond A,x^,b
where cond A,x^,b = A-1 A x^ + b ∞/ x^∞ ≤ cond A = A-1 A ∞≤κ∞ A. If x^ is the j th column of X , then wc is returned in BERR j and a bound on x - x^ ∞ / x^ ∞ is returned in FERR j . See Section 4.4 of Anderson et al. (1999) for further details.

8 Parallelism and Performance

F07HBF (DPBSVX) is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
F07HBF (DPBSVX) makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

When n≫k , the factorization of A requires approximately n k+1 2 floating-point operations, where k is the number of superdiagonals.
For each right-hand side, computation of the backward error involves a minimum of 8 nk floating-point operations. Each step of iterative refinement involves an additional 12 nk operations. At most five steps of iterative refinement are performed, but usually only one or two steps are required. Estimating the forward error involves solving a number of systems of equations of the form Ax=b ; the number is usually 4 or 5 and never more than 11. Each solution involves approximately 4 nk operations.
The complex analogue of this routine is F07HPF (ZPBSVX).

10 Example

This example solves the equations
AX=B ,
where A is the symmetric positive definite band matrix
A = 5.49 2.68 0.00 0.00 2.68 5.63 -2.39 0.00 0.00 -2.39 2.60 -2.22 0.00 0.00 -2.22 5.17
and
B = 22.09 5.10 9.31 30.81 -5.24 -25.82 11.83 22.90 .
Error estimates for the solutions, information on equilibration and an estimate of the reciprocal of the condition number of the scaled matrix A are also output.

10.1 Program Text

Program Text (f07hbfe.f90)

10.2 Program Data

Program Data (f07hbfe.d)

10.3 Program Results

Program Results (f07hbfe.r)

F07 Chapter Contents
F07 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F07HDF (DPBTRF) : NAG Library, Mark 26

F07 Chapter Contents
F07 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F07HDF (DPBTRF)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F07HDF (DPBTRF) computes the Cholesky factorization of a real symmetric positive definite band matrix.

2 Specification

SUBROUTINE F07HDF ( UPLO, N, KD, AB, LDAB, INFO)
INTEGER | N, KD, LDAB, INFO
REAL (KIND=nag_wp) | AB(LDAB,*)
CHARACTER(1) | UPLO
The routine may be called by its LAPACK name dpbtrf.

3 Description

F07HDF (DPBTRF) forms the Cholesky factorization of a real symmetric positive definite band matrix A either as A=UT U if UPLO='U' or A=L LT if UPLO='L', where U (or L) is an upper (or lower) triangular band matrix with the same number of superdiagonals (or subdiagonals) as A.

4 References

Demmel J W (1989) On floating-point errors in Cholesky LAPACK Working Note No. 14 University of Tennessee, Knoxville http://www.netlib.org/lapack/lawnspdf/lawn14.pdf
Golub G H and Van Loan C F (1996) Matrix Computations (3rd Edition) Johns Hopkins University Press, Baltimore

5 Arguments

1:   UPLO – CHARACTER(1)Input
On entry: specifies whether the upper or lower triangular part of A is stored and how A is to be factorized.
UPLO='U'
The upper triangular part of A is stored and A is factorized as UT U, where U is upper triangular.
UPLO='L'
The lower triangular part of A is stored and A is factorized as L LT, where L is lower triangular.
Constraint: UPLO='U' or 'L'.
2:   N – INTEGERInput
On entry: n, the order of the matrix A.
Constraint: N≥0.
3:   KD – INTEGERInput
On entry: kd, the number of superdiagonals or subdiagonals of the matrix A.
Constraint: KD≥0.
4:   AB LDAB* – REAL (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array AB must be at least max 1,N.
On entry: the n by n symmetric positive definite band matrix A.
The matrix is stored in rows 1 to kd+1, more precisely,
  • if UPLO='U', the elements of the upper triangle of A within the band must be stored with element A ij in AB kd+1+i-j j​ for ​max 1,j-kd≤i≤j;
  • if UPLO='L', the elements of the lower triangle of A within the band must be stored with element A ij in AB 1+i-j j​ for ​j≤i≤min n,j+kd.
On exit: the upper or lower triangle of A is overwritten by the Cholesky factor U or L as specified by UPLO, using the same storage format as described above.
5:   LDAB – INTEGERInput
On entry: the first dimension of the array AB as declared in the (sub)program from which F07HDF (DPBTRF) is called.
Constraint: LDAB≥KD+1.
6:   INFO – INTEGEROutput
On exit: INFO=0 unless the routine detects an error (see Section 6).

6 Error Indicators and Warnings

INFO<0
If INFO=-i, argument i had an illegal value.
If INFO=-999, dynamic memory allocation failed. See Section 3.7 in How to Use the NAG Library and its Documentation for further information. An explanatory message is output, and execution of the program is terminated.
INFO>0
The leading minor of order value is not positive definite and the factorization could not be completed. Hence A itself is not positive definite. This may indicate an error in forming the matrix A. There is no routine specifically designed to factorize a symmetric band matrix which is not positive definite; the matrix must be treated either as a nonsymmetric band matrix, by calling F07BDF (DGBTRF) or as a full symmetric matrix, by calling F07MDF (DSYTRF).

7 Accuracy

If UPLO='U', the computed factor U is the exact factor of a perturbed matrix A+E, where
E≤c k+1 ε UTU ,
c k+1 is a modest linear function of k+1, and ε is the machine precision.
If UPLO='L', a similar statement holds for the computed factor L. It follows that e ij≤c k+1 ε⁢a iia jj.

8 Parallelism and Performance

F07HDF (DPBTRF) makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The total number of floating-point operations is approximately n k+1 2, assuming n≫k.
A call to F07HDF (DPBTRF) may be followed by calls to the routines:
  • F07HEF (DPBTRS) to solve AX=B;
  • F07HGF (DPBCON) to estimate the condition number of A.
The complex analogue of this routine is F07HRF (ZPBTRF).

10 Example

This example computes the Cholesky factorization of the matrix A, where
A= 5.49 2.68 0.00 0.00 2.68 5.63 -2.39 0.00 0.00 -2.39 2.60 -2.22 0.00 0.00 -2.22 5.17 .

10.1 Program Text

Program Text (f07hdfe.f90)

10.2 Program Data

Program Data (f07hdfe.d)

10.3 Program Results

Program Results (f07hdfe.r)

F07 Chapter Contents
F07 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F07HEF (DPBTRS) : NAG Library, Mark 26

F07 Chapter Contents
F07 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F07HEF (DPBTRS)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F07HEF (DPBTRS) solves a real symmetric positive definite band system of linear equations with multiple right-hand sides,
AX=B ,
where A has been factorized by F07HDF (DPBTRF).

2 Specification

SUBROUTINE F07HEF ( UPLO, N, KD, NRHS, AB, LDAB, B, LDB, INFO)
INTEGER | N, KD, NRHS, LDAB, LDB, INFO
REAL (KIND=nag_wp) | AB(LDAB,*), B(LDB,*)
CHARACTER(1) | UPLO
The routine may be called by its LAPACK name dpbtrs.

3 Description

F07HEF (DPBTRS) is used to solve a real symmetric positive definite band system of linear equations AX=B, the routine must be preceded by a call to F07HDF (DPBTRF) which computes the Cholesky factorization of A. The solution X is computed by forward and backward substitution.
If UPLO='U', A=UT U, where U is upper triangular; the solution X is computed by solving UT Y=B and then UX=Y.
If UPLO='L', A=L LT, where L is lower triangular; the solution X is computed by solving LY=B and then LT X=Y.

4 References

Golub G H and Van Loan C F (1996) Matrix Computations (3rd Edition) Johns Hopkins University Press, Baltimore

5 Arguments

1:   UPLO – CHARACTER(1)Input
On entry: specifies how A has been factorized.
UPLO='U'
A=UT U, where U is upper triangular.
UPLO='L'
A=L LT, where L is lower triangular.
Constraint: UPLO='U' or 'L'.
2:   N – INTEGERInput
On entry: n, the order of the matrix A.
Constraint: N≥0.
3:   KD – INTEGERInput
On entry: kd, the number of superdiagonals or subdiagonals of the matrix A.
Constraint: KD≥0.
4:   NRHS – INTEGERInput
On entry: r, the number of right-hand sides.
Constraint: NRHS≥0.
5:   AB LDAB* – REAL (KIND=nag_wp) arrayInput
Note: the second dimension of the array AB must be at least max 1,N.
On entry: the Cholesky factor of A, as returned by F07HDF (DPBTRF).
6:   LDAB – INTEGERInput
On entry: the first dimension of the array AB as declared in the (sub)program from which F07HEF (DPBTRS) is called.
Constraint: LDAB≥KD+1.
7:   B LDB* – REAL (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array B must be at least max 1,NRHS.
On entry: the n by r right-hand side matrix B.
On exit: the n by r solution matrix X.
8:   LDB – INTEGERInput
On entry: the first dimension of the array B as declared in the (sub)program from which F07HEF (DPBTRS) is called.
Constraint: LDB≥max 1,N.
9:   INFO – INTEGEROutput
On exit: INFO=0 unless the routine detects an error (see Section 6).

6 Error Indicators and Warnings

INFO<0
If INFO=-i, argument i had an illegal value. An explanatory message is output, and execution of the program is terminated.

7 Accuracy

For each right-hand side vector b, the computed solution x is the exact solution of a perturbed system of equations A+E x=b, where
  • if UPLO='U', E≤c k+1 ε UTU;
  • if UPLO='L', E≤c k+1 ε LLT,
c k+1 is a modest linear function of k+1, and ε is the machine precision.
If x^ is the true solution, then the computed solution x satisfies a forward error bound of the form
x-x^∞ x∞ ≤c k+1 cond A,x ε
where cond A,x=A-1Ax∞/x∞≤cond A=A-1A∞≤κ∞A. Note that cond A,x can be much smaller than cond A.
Forward and backward error bounds can be computed by calling F07HHF (DPBRFS), and an estimate for κ∞A (=κ 1 A) can be obtained by calling F07HGF (DPBCON).

8 Parallelism and Performance

F07HEF (DPBTRS) is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
F07HEF (DPBTRS) makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The total number of floating-point operations is approximately 4 nkr, assuming n≫k.
This routine may be followed by a call to F07HHF (DPBRFS) to refine the solution and return an error estimate.
The complex analogue of this routine is F07HSF (ZPBTRS).

10 Example

This example solves the system of equations AX=B, where
A= 5.49 2.68 0.00 0.00 2.68 5.63 -2.39 0.00 0.00 -2.39 2.60 -2.22 0.00 0.00 -2.22 5.17   and   B= 22.09 5.10 9.31 30.81 -5.24 -25.82 11.83 22.90 .
Here A is symmetric and positive definite, and is treated as a band matrix, which must first be factorized by F07HDF (DPBTRF).

10.1 Program Text

Program Text (f07hefe.f90)

10.2 Program Data

Program Data (f07hefe.d)

10.3 Program Results

Program Results (f07hefe.r)

F07 Chapter Contents
F07 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F07HFF (DPBEQU) : NAG Library, Mark 26

F07 Chapter Contents
F07 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F07HFF (DPBEQU)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F07HFF (DPBEQU) computes a diagonal scaling matrix S intended to equilibrate a real n by n symmetric positive definite band matrix A , with bandwidth 2 kd+1 , and reduce its condition number.

2 Specification

SUBROUTINE F07HFF ( UPLO, N, KD, AB, LDAB, S, SCOND, AMAX, INFO)
INTEGER | N, KD, LDAB, INFO
REAL (KIND=nag_wp) | AB(LDAB,*), S(N), SCOND, AMAX
CHARACTER(1) | UPLO
The routine may be called by its LAPACK name dpbequ.

3 Description

F07HFF (DPBEQU) computes a diagonal scaling matrix S chosen so that
sj=1 / a jj .
This means that the matrix B given by
B=SAS ,
has diagonal elements equal to unity. This in turn means that the condition number of B , κ 2 B , is within a factor n of the matrix of smallest possible condition number over all possible choices of diagonal scalings (see Corollary 7.6 of Higham (2002)).

4 References

Higham N J (2002) Accuracy and Stability of Numerical Algorithms (2nd Edition) SIAM, Philadelphia

5 Arguments

1:   UPLO – CHARACTER(1)Input
On entry: indicates whether the upper or lower triangular part of A is stored in the array AB, as follows:
UPLO='U'
The upper triangle of A is stored.
UPLO='L'
The lower triangle of A is stored.
Constraint: UPLO='U' or 'L'.
2:   N – INTEGERInput
On entry: n, the order of the matrix A.
Constraint: N≥0.
3:   KD – INTEGERInput
On entry: kd, the number of superdiagonals of the matrix A if UPLO='U', or the number of subdiagonals if UPLO='L'.
Constraint: KD≥0.
4:   AB LDAB* – REAL (KIND=nag_wp) arrayInput
Note: the second dimension of the array AB must be at least max 1,N.
On entry: the upper or lower triangle of the symmetric positive definite band matrix A whose scaling factors are to be computed.
The matrix is stored in rows 1 to kd+1, more precisely,
  • if UPLO='U', the elements of the upper triangle of A within the band must be stored with element A ij in AB kd+1+i-j j​ for ​max 1,j-kd≤i≤j;
  • if UPLO='L', the elements of the lower triangle of A within the band must be stored with element A ij in AB 1+i-j j​ for ​j≤i≤min n,j+kd.
Only the elements of the array AB corresponding to the diagonal elements of A are referenced. (Row kd+1 of AB when UPLO='U', row 1 of AB when UPLO='L'.)
5:   LDAB – INTEGERInput
On entry: the first dimension of the array AB as declared in the (sub)program from which F07HFF (DPBEQU) is called.
Constraint: LDAB≥KD+1.
6:   S N – REAL (KIND=nag_wp) arrayOutput
On exit: if INFO=0, S contains the diagonal elements of the scaling matrix S.
7:   SCOND – REAL (KIND=nag_wp)Output
On exit: if INFO=0, SCOND contains the ratio of the smallest value of S to the largest value of S. If SCOND≥0.1 and AMAX is neither too large nor too small, it is not worth scaling by S.
8:   AMAX – REAL (KIND=nag_wp)Output
On exit: max a ij. If AMAX is very close to overflow or underflow, the matrix A should be scaled.
9:   INFO – INTEGEROutput
On exit: INFO=0 unless the routine detects an error (see Section 6).

6 Error Indicators and Warnings

INFO<0
If INFO=-i, argument i had an illegal value. An explanatory message is output, and execution of the program is terminated.
INFO>0
The valueth diagonal element of A is not positive (and hence A cannot be positive definite).

7 Accuracy

The computed scale factors will be close to the exact scale factors.

8 Parallelism and Performance

F07HFF (DPBEQU) is not threaded in any implementation.

9 Further Comments

The complex analogue of this routine is F07HTF (ZPBEQU).

10 Example

This example equilibrates the symmetric positive definite matrix A given by
A = 5.49 -2.68×1010 -0 -0 2.68×1010 -5.63×1020 -2.39×1010 -0 0 -2.39×1010 -2.60 -2.22 0 -0 -2.22 -5.17 .
Details of the scaling factors and the scaled matrix are output.

10.1 Program Text

Program Text (f07hffe.f90)

10.2 Program Data

Program Data (f07hffe.d)

10.3 Program Results

Program Results (f07hffe.r)

F07 Chapter Contents
F07 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F07HGF (DPBCON) : NAG Library, Mark 26

F07 Chapter Contents
F07 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F07HGF (DPBCON)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F07HGF (DPBCON) estimates the condition number of a real symmetric positive definite band matrix A, where A has been factorized by F07HDF (DPBTRF).

2 Specification

SUBROUTINE F07HGF ( UPLO, N, KD, AB, LDAB, ANORM, RCOND, WORK, IWORK, INFO)
INTEGER | N, KD, LDAB, IWORK(N), INFO
REAL (KIND=nag_wp) | AB(LDAB,*), ANORM, RCOND, WORK(3*N)
CHARACTER(1) | UPLO
The routine may be called by its LAPACK name dpbcon.

3 Description

F07HGF (DPBCON) estimates the condition number (in the 1-norm) of a real symmetric positive definite band matrix A:
κ 1 A=A 1A-1 1 .
Since A is symmetric, κ 1 A=κ∞A=A∞A-1∞.
Because κ 1 A is infinite if A is singular, the routine actually returns an estimate of the reciprocal of κ 1 A.
The routine should be preceded by a call to F06REF to compute A 1 and a call to F07HDF (DPBTRF) to compute the Cholesky factorization of A. The routine then uses Higham's implementation of Hager's method (see Higham (1988)) to estimate A-1 1.

4 References

Higham N J (1988) FORTRAN codes for estimating the one-norm of a real or complex matrix, with applications to condition estimation ACM Trans. Math. Software 14 381–396

5 Arguments

1:   UPLO – CHARACTER(1)Input
On entry: specifies how A has been factorized.
UPLO='U'
A=UT U, where U is upper triangular.
UPLO='L'
A=L LT, where L is lower triangular.
Constraint: UPLO='U' or 'L'.
2:   N – INTEGERInput
On entry: n, the order of the matrix A.
Constraint: N≥0.
3:   KD – INTEGERInput
On entry: kd, the number of superdiagonals or subdiagonals of the matrix A.
Constraint: KD≥0.
4:   AB LDAB* – REAL (KIND=nag_wp) arrayInput
Note: the second dimension of the array AB must be at least max 1,N.
On entry: the Cholesky factor of A, as returned by F07HDF (DPBTRF).
5:   LDAB – INTEGERInput
On entry: the first dimension of the array AB as declared in the (sub)program from which F07HGF (DPBCON) is called.
Constraint: LDAB≥KD+1.
6:   ANORM – REAL (KIND=nag_wp)Input
On entry: the 1-norm of the original matrix A, which may be computed by calling F06REF with its argument NORM='1'. ANORM must be computed either before calling F07HDF (DPBTRF) or else from a copy of the original matrix A.
Constraint: ANORM≥0.0.
7:   RCOND – REAL (KIND=nag_wp)Output
On exit: an estimate of the reciprocal of the condition number of A. RCOND is set to zero if exact singularity is detected or the estimate underflows. If RCOND is less than machine precision, A is singular to working precision.
8:   WORK 3×N – REAL (KIND=nag_wp) arrayWorkspace
9:   IWORK N – INTEGER arrayWorkspace
10:   INFO – INTEGEROutput
On exit: INFO=0 unless the routine detects an error (see Section 6).

6 Error Indicators and Warnings

INFO<0
If INFO=-i, argument i had an illegal value. An explanatory message is output, and execution of the program is terminated.

7 Accuracy

The computed estimate RCOND is never less than the true value ρ, and in practice is nearly always less than 10 ρ, although examples can be constructed where RCOND is much larger.

8 Parallelism and Performance

F07HGF (DPBCON) makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

A call to F07HGF (DPBCON) involves solving a number of systems of linear equations of the form Ax=b; the number is usually 4 or 5 and never more than 11. Each solution involves approximately 4 nk floating-point operations (assuming n≫k) but takes considerably longer than a call to F07HEF (DPBTRS) with one right-hand side, because extra care is taken to avoid overflow when A is approximately singular.
The complex analogue of this routine is F07HUF (ZPBCON).

10 Example

This example estimates the condition number in the 1-norm (or ∞-norm) of the matrix A, where
A= 5.49 2.68 0.00 0.00 2.68 5.63 -2.39 0.00 0.00 -2.39 2.60 -2.22 0.00 0.00 -2.22 5.17 .
Here A is symmetric and positive definite, and is treated as a band matrix, which must first be factorized by F07HDF (DPBTRF). The true condition number in the 1-norm is 74.15.

10.1 Program Text

Program Text (f07hgfe.f90)

10.2 Program Data

Program Data (f07hgfe.d)

10.3 Program Results

Program Results (f07hgfe.r)

F07 Chapter Contents
F07 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F07HHF (DPBRFS) : NAG Library, Mark 26

F07 Chapter Contents
F07 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F07HHF (DPBRFS)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F07HHF (DPBRFS) returns error bounds for the solution of a real symmetric positive definite band system of linear equations with multiple right-hand sides, AX=B. It improves the solution by iterative refinement, in order to reduce the backward error as much as possible.

2 Specification

SUBROUTINE F07HHF ( UPLO, N, KD, NRHS, AB, LDAB, AFB, LDAFB, B, LDB, X, LDX, FERR, BERR, WORK, IWORK, INFO)
INTEGER | N, KD, NRHS, LDAB, LDAFB, LDB, LDX, IWORK(N), INFO
REAL (KIND=nag_wp) | AB(LDAB,*), AFB(LDAFB,*), B(LDB,*), X(LDX,*), FERR(NRHS), BERR(NRHS), WORK(3*N)
CHARACTER(1) | UPLO
The routine may be called by its LAPACK name dpbrfs.

3 Description

F07HHF (DPBRFS) returns the backward errors and estimated bounds on the forward errors for the solution of a real symmetric positive definite band system of linear equations with multiple right-hand sides AX=B. The routine handles each right-hand side vector (stored as a column of the matrix B) independently, so we describe the function of F07HHF (DPBRFS) in terms of a single right-hand side b and solution x.
Given a computed solution x, the routine computes the component-wise backward error β. This is the size of the smallest relative perturbation in each element of A and b such that x is the exact solution of a perturbed system
A+δA x=b+δb δ a ij≤β a ij   and   δ bi≤β bi .
Then the routine estimates a bound for the component-wise forward error in the computed solution, defined by:
maxi xi-x^i/maxi xi
where x^ is the true solution.
For details of the method, see the F07 Chapter Introduction.

4 References

Golub G H and Van Loan C F (1996) Matrix Computations (3rd Edition) Johns Hopkins University Press, Baltimore

5 Arguments

1:   UPLO – CHARACTER(1)Input
On entry: specifies whether the upper or lower triangular part of A is stored and how A is to be factorized.
UPLO='U'
The upper triangular part of A is stored and A is factorized as UT U, where U is upper triangular.
UPLO='L'
The lower triangular part of A is stored and A is factorized as L LT, where L is lower triangular.
Constraint: UPLO='U' or 'L'.
2:   N – INTEGERInput
On entry: n, the order of the matrix A.
Constraint: N≥0.
3:   KD – INTEGERInput
On entry: kd, the number of superdiagonals or subdiagonals of the matrix A.
Constraint: KD≥0.
4:   NRHS – INTEGERInput
On entry: r, the number of right-hand sides.
Constraint: NRHS≥0.
5:   AB LDAB* – REAL (KIND=nag_wp) arrayInput
Note: the second dimension of the array AB must be at least max 1,N.
On entry: the n by n original symmetric positive definite band matrix A as supplied to F07HDF (DPBTRF).
6:   LDAB – INTEGERInput
On entry: the first dimension of the array AB as declared in the (sub)program from which F07HHF (DPBRFS) is called.
Constraint: LDAB≥KD+1.
7:   AFB LDAFB* – REAL (KIND=nag_wp) arrayInput
Note: the second dimension of the array AFB must be at least max 1,N.
On entry: the Cholesky factor of A, as returned by F07HDF (DPBTRF).
8:   LDAFB – INTEGERInput
On entry: the first dimension of the array AFB as declared in the (sub)program from which F07HHF (DPBRFS) is called.
Constraint: LDAFB≥KD+1.
9:   B LDB* – REAL (KIND=nag_wp) arrayInput
Note: the second dimension of the array B must be at least max 1,NRHS.
On entry: the n by r right-hand side matrix B.
10:   LDB – INTEGERInput
On entry: the first dimension of the array B as declared in the (sub)program from which F07HHF (DPBRFS) is called.
Constraint: LDB≥max 1,N.
11:   X LDX* – REAL (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array X must be at least max 1,NRHS.
On entry: the n by r solution matrix X, as returned by F07HEF (DPBTRS).
On exit: the improved solution matrix X.
12:   LDX – INTEGERInput
On entry: the first dimension of the array X as declared in the (sub)program from which F07HHF (DPBRFS) is called.
Constraint: LDX≥max 1,N.
13:   FERR NRHS – REAL (KIND=nag_wp) arrayOutput
On exit: FERR j contains an estimated error bound for the jth solution vector, that is, the jth column of X, for j=1,2,…,r.
14:   BERR NRHS – REAL (KIND=nag_wp) arrayOutput
On exit: BERR j contains the component-wise backward error bound β for the jth solution vector, that is, the jth column of X, for j=1,2,…,r.
15:   WORK 3×N – REAL (KIND=nag_wp) arrayWorkspace
16:   IWORK N – INTEGER arrayWorkspace
17:   INFO – INTEGEROutput
On exit: INFO=0 unless the routine detects an error (see Section 6).

6 Error Indicators and Warnings

INFO<0
If INFO=-i, argument i had an illegal value. An explanatory message is output, and execution of the program is terminated.

7 Accuracy

The bounds returned in FERR are not rigorous, because they are estimated, not computed exactly; but in practice they almost always overestimate the actual error.

8 Parallelism and Performance

F07HHF (DPBRFS) is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
F07HHF (DPBRFS) makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

For each right-hand side, computation of the backward error involves a minimum of 8 nk floating-point operations. Each step of iterative refinement involves an additional 12 nk operations. This assumes n≫k. At most five steps of iterative refinement are performed, but usually only one or two steps are required.
Estimating the forward error involves solving a number of systems of linear equations of the form Ax=b; the number is usually 4 or 5 and never more than 11. Each solution involves approximately 4 nk operations.
The complex analogue of this routine is F07HVF (ZPBRFS).

10 Example

This example solves the system of equations AX=B using iterative refinement and to compute the forward and backward error bounds, where
A= 5.49 2.68 0.00 0.00 2.68 5.63 -2.39 0.00 0.00 -2.39 2.60 -2.22 0.00 0.00 -2.22 5.17   and   B= 22.09 5.10 9.31 30.81 -5.24 -25.82 11.83 22.90 .
Here A is symmetric and positive definite, and is treated as a band matrix, which must first be factorized by F07HDF (DPBTRF).

10.1 Program Text

Program Text (f07hhfe.f90)

10.2 Program Data

Program Data (f07hhfe.d)

10.3 Program Results

Program Results (f07hhfe.r)

F07 Chapter Contents
F07 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F07HNF (ZPBSV) : NAG Library, Mark 26

F07 Chapter Contents
F07 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F07HNF (ZPBSV)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F07HNF (ZPBSV) computes the solution to a complex system of linear equations
AX=B ,
where A is an n by n Hermitian positive definite band matrix of bandwidth 2 kd + 1 and X and B are n by r matrices.

2 Specification

SUBROUTINE F07HNF ( UPLO, N, KD, NRHS, AB, LDAB, B, LDB, INFO)
INTEGER | N, KD, NRHS, LDAB, LDB, INFO
COMPLEX (KIND=nag_wp) | AB(LDAB,*), B(LDB,*)
CHARACTER(1) | UPLO
The routine may be called by its LAPACK name zpbsv.

3 Description

F07HNF (ZPBSV) uses the Cholesky decomposition to factor A as A=UH U if UPLO='U' or A=L LH if UPLO='L', where U is an upper triangular band matrix, and L is a lower triangular band matrix, with the same number of superdiagonals or subdiagonals as A. The factored form of A is then used to solve the system of equations AX=B.

4 References

Anderson E, Bai Z, Bischof C, Blackford S, Demmel J, Dongarra J J, Du Croz J J, Greenbaum A, Hammarling S, McKenney A and Sorensen D (1999) LAPACK Users' Guide (3rd Edition) SIAM, Philadelphia http://www.netlib.org/lapack/lug
Golub G H and Van Loan C F (1996) Matrix Computations (3rd Edition) Johns Hopkins University Press, Baltimore

5 Arguments

1:   UPLO – CHARACTER(1)Input
On entry: if UPLO='U', the upper triangle of A is stored.
If UPLO='L', the lower triangle of A is stored.
Constraint: UPLO='U' or 'L'.
2:   N – INTEGERInput
On entry: n, the number of linear equations, i.e., the order of the matrix A.
Constraint: N≥0.
3:   KD – INTEGERInput
On entry: kd, the number of superdiagonals of the matrix A if UPLO='U', or the number of subdiagonals if UPLO='L'.
Constraint: KD≥0.
4:   NRHS – INTEGERInput
On entry: r, the number of right-hand sides, i.e., the number of columns of the matrix B.
Constraint: NRHS≥0.
5:   AB LDAB* – COMPLEX (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array AB must be at least max 1,N.
On entry: the upper or lower triangle of the Hermitian band matrix A.
The matrix is stored in rows 1 to kd+1, more precisely,
  • if UPLO='U', the elements of the upper triangle of A within the band must be stored with element A ij in AB kd+1+i-j j​ for ​max 1,j-kd≤i≤j;
  • if UPLO='L', the elements of the lower triangle of A within the band must be stored with element A ij in AB 1+i-j j​ for ​j≤i≤min n,j+kd.
On exit: if INFO=0, the triangular factor U or L from the Cholesky factorization A=UH U or A=L LH of the band matrix A, in the same storage format as A.
6:   LDAB – INTEGERInput
On entry: the first dimension of the array AB as declared in the (sub)program from which F07HNF (ZPBSV) is called.
Constraint: LDAB≥KD+1.
7:   B LDB* – COMPLEX (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array B must be at least max 1,NRHS.
On entry: the n by r right-hand side matrix B.
On exit: if INFO=0, the n by r solution matrix X.
8:   LDB – INTEGERInput
On entry: the first dimension of the array B as declared in the (sub)program from which F07HNF (ZPBSV) is called.
Constraint: LDB≥max 1,N.
9:   INFO – INTEGEROutput
On exit: INFO=0 unless the routine detects an error (see Section 6).

6 Error Indicators and Warnings

INFO<0
If INFO=-i, argument i had an illegal value. An explanatory message is output, and execution of the program is terminated.
INFO>0
The leading minor of order value of A is not positive definite, so the factorization could not be completed, and the solution has not been computed.

7 Accuracy

The computed solution for a single right-hand side, x^ , satisfies an equation of the form
A+E x^=b ,
where
E 1 = O ε A 1
and ε is the machine precision. An approximate error bound for the computed solution is given by
x^-x 1 x 1 ≤ κ A E 1 A 1 ,
where κ A = A-1 1 A 1 , the condition number of A with respect to the solution of the linear equations. See Section 4.4 of Anderson et al. (1999) for further details.
F07HPF (ZPBSVX) is a comprehensive LAPACK driver that returns forward and backward error bounds and an estimate of the condition number. Alternatively, F04CFF solves Ax=b and returns a forward error bound and condition estimate. F04CFF calls F07HNF (ZPBSV) to solve the equations.

8 Parallelism and Performance

F07HNF (ZPBSV) is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
F07HNF (ZPBSV) makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

When n≫k , the total number of floating-point operations is approximately 4 n k+1 2+16 nkr , where k is the number of superdiagonals and r is the number of right-hand sides.
The real analogue of this routine is F07HAF (DPBSV).

10 Example

This example solves the equations
Ax=b ,
where A is the Hermitian positive definite band matrix
A = 9.39 i+0.00 1.08-1.73 i 0.00i+0.00 0.00i+0.00 1.08+1.73 i 1.69 i+0.00 -0.04+0.29 i 0.00i+0.00 0.00i+0.00 -0.04-0.29 i 2.65 i+0.00 -0.33+2.24 i 0.00i+0.00 0.00i+0.00 -0.33-2.24 i 2.17 i+0.00
and
b = -12.42+68.42 i -9.93+0 0.88 i -27.30-0 0.01 i 5.31+23.63 i .
Details of the Cholesky factorization of A are also output.

10.1 Program Text

Program Text (f07hnfe.f90)

10.2 Program Data

Program Data (f07hnfe.d)

10.3 Program Results

Program Results (f07hnfe.r)

F07 Chapter Contents
F07 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F07HPF (ZPBSVX) : NAG Library, Mark 26

F07 Chapter Contents
F07 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F07HPF (ZPBSVX)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F07HPF (ZPBSVX) uses the Cholesky factorization
A=UH U   or   A=L LH
to compute the solution to a complex system of linear equations
AX=B ,
where A is an n by n Hermitian positive definite band matrix of bandwidth 2 kd + 1 and X and B are n by r matrices. Error bounds on the solution and a condition estimate are also provided.

2 Specification

SUBROUTINE F07HPF ( FACT, UPLO, N, KD, NRHS, AB, LDAB, AFB, LDAFB, EQUED, S, B, LDB, X, LDX, RCOND, FERR, BERR, WORK, RWORK, INFO)
INTEGER | N, KD, NRHS, LDAB, LDAFB, LDB, LDX, INFO
REAL (KIND=nag_wp) | S(*), RCOND, FERR(NRHS), BERR(NRHS), RWORK(N)
COMPLEX (KIND=nag_wp) | AB(LDAB,*), AFB(LDAFB,*), B(LDB,*), X(LDX,*), WORK(2*N)
CHARACTER(1) | FACT, UPLO, EQUED
The routine may be called by its LAPACK name zpbsvx.

3 Description

F07HPF (ZPBSVX) performs the following steps:
1. If FACT='E', real diagonal scaling factors, DS , are computed to equilibrate the system:
DS A DS DS-1 X = DS B .
Whether or not the system will be equilibrated depends on the scaling of the matrix A, but if equilibration is used, A is overwritten by DS A DS and B by DS B.
2. | If FACT='N' or 'E', the Cholesky decomposition is used to factor the matrix A (after equilibration if FACT='E') as A=UH U if UPLO='U' or A=L LH if UPLO='L', where U is an upper triangular matrix and L is a lower triangular matrix.
3. | If the leading i by i principal minor of A is not positive definite, then the routine returns with INFO=i. Otherwise, the factored form of A is used to estimate the condition number of the matrix A. If the reciprocal of the condition number is less than machine precision, INFO=N+1 is returned as a warning, but the routine still goes on to solve for X and compute error bounds as described below.
4. | The system of equations is solved for X using the factored form of A.
5. | Iterative refinement is applied to improve the computed solution matrix and to calculate error bounds and backward error estimates for it.
6. | If equilibration was used, the matrix X is premultiplied by DS so that it solves the original system before equilibration.

4 References

Anderson E, Bai Z, Bischof C, Blackford S, Demmel J, Dongarra J J, Du Croz J J, Greenbaum A, Hammarling S, McKenney A and Sorensen D (1999) LAPACK Users' Guide (3rd Edition) SIAM, Philadelphia http://www.netlib.org/lapack/lug
Golub G H and Van Loan C F (1996) Matrix Computations (3rd Edition) Johns Hopkins University Press, Baltimore
Higham N J (2002) Accuracy and Stability of Numerical Algorithms (2nd Edition) SIAM, Philadelphia

5 Arguments

1:   FACT – CHARACTER(1)Input
On entry: specifies whether or not the factorized form of the matrix A is supplied on entry, and if not, whether the matrix A should be equilibrated before it is factorized.
FACT='F'
AFB contains the factorized form of A. If EQUED='Y', the matrix A has been equilibrated with scaling factors given by S. AB and AFB will not be modified.
FACT='N'
The matrix A will be copied to AFB and factorized.
FACT='E'
The matrix A will be equilibrated if necessary, then copied to AFB and factorized.
Constraint: FACT='F', 'N' or 'E'.
2:   UPLO – CHARACTER(1)Input
On entry: if UPLO='U', the upper triangle of A is stored.
If UPLO='L', the lower triangle of A is stored.
Constraint: UPLO='U' or 'L'.
3:   N – INTEGERInput
On entry: n, the number of linear equations, i.e., the order of the matrix A.
Constraint: N≥0.
4:   KD – INTEGERInput
On entry: kd, the number of superdiagonals of the matrix A if UPLO='U', or the number of subdiagonals if UPLO='L'.
Constraint: KD≥0.
5:   NRHS – INTEGERInput
On entry: r, the number of right-hand sides, i.e., the number of columns of the matrix B.
Constraint: NRHS≥0.
6:   AB LDAB* – COMPLEX (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array AB must be at least max 1,N.
On entry: the upper or lower triangle of the Hermitian band matrix A, except if FACT='F' and EQUED='Y', in which case AB must contain the equilibrated matrix DS A DS.
The matrix is stored in rows 1 to kd+1, more precisely,
  • if UPLO='U', the elements of the upper triangle of A within the band must be stored with element A ij in AB kd+1+i-j j​ for ​max 1,j-kd≤i≤j;
  • if UPLO='L', the elements of the lower triangle of A within the band must be stored with element A ij in AB 1+i-j j​ for ​j≤i≤min n,j+kd.
On exit: if FACT='E' and EQUED='Y', AB is overwritten by DS A DS.
7:   LDAB – INTEGERInput
On entry: the first dimension of the array AB as declared in the (sub)program from which F07HPF (ZPBSVX) is called.
Constraint: LDAB≥KD+1.
8:   AFB LDAFB* – COMPLEX (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array AFB must be at least max 1,N.
On entry: if FACT='F', AFB contains the triangular factor U or L from the Cholesky factorization A=UH U or A=L LH of the band matrix A, in the same storage format as A. If EQUED='Y', AFB is the factorized form of the equilibrated matrix A.
On exit: if FACT='N', AFB returns the triangular factor U or L from the Cholesky factorization A=UH U or A=L LH.
If FACT='E', AFB returns the triangular factor U or L from the Cholesky factorization A=UH U or A=L LH of the equilibrated matrix A (see the description of AB for the form of the equilibrated matrix).
9:   LDAFB – INTEGERInput
On entry: the first dimension of the array AFB as declared in the (sub)program from which F07HPF (ZPBSVX) is called.
Constraint: LDAFB≥KD+1.
10:   EQUED – CHARACTER(1)Input/Output
On entry: if FACT='N' or 'E', EQUED need not be set.
If FACT='F', EQUED must specify the form of the equilibration that was performed as follows:
  • if EQUED='N', no equilibration;
  • if EQUED='Y', equilibration was performed, i.e., A has been replaced by DS A DS.
On exit: if FACT='F', EQUED is unchanged from entry.
Otherwise, if no constraints are violated, EQUED specifies the form of the equilibration that was performed as specified above.
Constraint: if FACT='F', EQUED='N' or 'Y'.
11:   S* – REAL (KIND=nag_wp) arrayInput/Output
Note: the dimension of the array S must be at least max 1,N.
On entry: if FACT='N' or 'E', S need not be set.
If FACT='F' and EQUED='Y', S must contain the scale factors, DS, for A; each element of S must be positive.
On exit: if FACT='F', S is unchanged from entry.
Otherwise, if no constraints are violated and EQUED='Y', S contains the scale factors, DS, for A; each element of S is positive.
12:   B LDB* – COMPLEX (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array B must be at least max 1,NRHS.
On entry: the n by r right-hand side matrix B.
On exit: if EQUED='N', B is not modified.
If EQUED='Y', B is overwritten by DS B.
13:   LDB – INTEGERInput
On entry: the first dimension of the array B as declared in the (sub)program from which F07HPF (ZPBSVX) is called.
Constraint: LDB≥max 1,N.
14:   X LDX* – COMPLEX (KIND=nag_wp) arrayOutput
Note: the second dimension of the array X must be at least max 1,NRHS.
On exit: if INFO=0 or N+1, the n by r solution matrix X to the original system of equations. Note that the arrays A and B are modified on exit if EQUED='Y', and the solution to the equilibrated system is DS-1 X.
15:   LDX – INTEGERInput
On entry: the first dimension of the array X as declared in the (sub)program from which F07HPF (ZPBSVX) is called.
Constraint: LDX≥max 1,N.
16:   RCOND – REAL (KIND=nag_wp)Output
On exit: if no constraints are violated, an estimate of the reciprocal condition number of the matrix A (after equilibration if that is performed), computed as RCOND=1.0/A 1 A-1 1 .
17:   FERR NRHS – REAL (KIND=nag_wp) arrayOutput
On exit: if INFO=0 or N+1, an estimate of the forward error bound for each computed solution vector, such that x^j-xj∞/xj∞≤FERR j where x^j is the jth column of the computed solution returned in the array X and xj is the corresponding column of the exact solution X. The estimate is as reliable as the estimate for RCOND, and is almost always a slight overestimate of the true error.
18:   BERR NRHS – REAL (KIND=nag_wp) arrayOutput
On exit: if INFO=0 or N+1, an estimate of the component-wise relative backward error of each computed solution vector x^j (i.e., the smallest relative change in any element of A or B that makes x^j an exact solution).
19:   WORK 2×N – COMPLEX (KIND=nag_wp) arrayWorkspace
20:   RWORK N – REAL (KIND=nag_wp) arrayWorkspace
21:   INFO – INTEGEROutput
On exit: INFO=0 unless the routine detects an error (see Section 6).

6 Error Indicators and Warnings

INFO<0
If INFO=-i, argument i had an illegal value. An explanatory message is output, and execution of the program is terminated.
INFO>0 and INFO≤N
The leading minor of order value of A is not positive definite, so the factorization could not be completed, and the solution has not been computed. RCOND=0.0 is returned.
INFO=N+1
U (or L) is nonsingular, but RCOND is less than machine precision, meaning that the matrix is singular to working precision. Nevertheless, the solution and error bounds are computed because there are a number of situations where the computed solution can be more accurate than the value of RCOND would suggest.

7 Accuracy

For each right-hand side vector b, the computed solution x is the exact solution of a perturbed system of equations A+E x = b, where
  • if UPLO='U', E≤c n ε UHU;
  • if UPLO='L', E≤c n ε LLH,
c n is a modest linear function of n, and ε is the machine precision. See Section 10.1 of Higham (2002) for further details.
If x^ is the true solution, then the computed solution x satisfies a forward error bound of the form
x-x^∞ x^∞ ≤ wc cond A,x^,b
where cond A,x^,b = A-1 A x^ + b ∞/ x^∞ ≤ cond A = A-1 A ∞≤κ∞ A. If x^ is the j th column of X , then wc is returned in BERR j and a bound on x - x^ ∞ / x^ ∞ is returned in FERR j . See Section 4.4 of Anderson et al. (1999) for further details.

8 Parallelism and Performance

F07HPF (ZPBSVX) is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
F07HPF (ZPBSVX) makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

When n≫k , the factorization of A requires approximately 4 n k+1 2 floating-point operations, where k is the number of superdiagonals.
For each right-hand side, computation of the backward error involves a minimum of 32 nk floating-point operations. Each step of iterative refinement involves an additional 48 nk operations. At most five steps of iterative refinement are performed, but usually only one or two steps are required. Estimating the forward error involves solving a number of systems of equations of the form Ax=b ; the number is usually 4 or 5 and never more than 11. Each solution involves approximately 16 nk operations.
The real analogue of this routine is F07HBF (DPBSVX).

10 Example

This example solves the equations
AX=B ,
where A is the Hermitian positive definite band matrix
A = 9.39 i+0.00 1.08-1.73 i 0.00i+0.00 0.00i+0.00 1.08+1.73 i 1.69 i+0.00 -0.04+0.29 i 0.00i+0.00 0.00i+0.00 -0.04-0.29 i 2.65 i+0.00 -0.33+2.24 i 0.00i+0.00 0.00i+0.00 -0.33-2.24 i 2.17 i+0.00
and
B = -12.42+68.42 i 54.30-56.56 i -9.93+0 0.88 i 18.32+0 4.76 i -27.30-0 0.01 i -4.40+0 9.97 i 5.31+23.63 i 9.43+0 1.41 i .
Error estimates for the solutions, information on equilibration and an estimate of the reciprocal of the condition number of the scaled matrix A are also output.

10.1 Program Text

Program Text (f07hpfe.f90)

10.2 Program Data

Program Data (f07hpfe.d)

10.3 Program Results

Program Results (f07hpfe.r)

F07 Chapter Contents
F07 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F07HRF (ZPBTRF) : NAG Library, Mark 26

F07 Chapter Contents
F07 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F07HRF (ZPBTRF)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F07HRF (ZPBTRF) computes the Cholesky factorization of a complex Hermitian positive definite band matrix.

2 Specification

SUBROUTINE F07HRF ( UPLO, N, KD, AB, LDAB, INFO)
INTEGER | N, KD, LDAB, INFO
COMPLEX (KIND=nag_wp) | AB(LDAB,*)
CHARACTER(1) | UPLO
The routine may be called by its LAPACK name zpbtrf.

3 Description

F07HRF (ZPBTRF) forms the Cholesky factorization of a complex Hermitian positive definite band matrix A either as A=UH U if UPLO='U' or A=L LH if UPLO='L', where U (or L) is an upper (or lower) triangular band matrix with the same number of superdiagonals (or subdiagonals) as A.

4 References

Demmel J W (1989) On floating-point errors in Cholesky LAPACK Working Note No. 14 University of Tennessee, Knoxville http://www.netlib.org/lapack/lawnspdf/lawn14.pdf
Golub G H and Van Loan C F (1996) Matrix Computations (3rd Edition) Johns Hopkins University Press, Baltimore

5 Arguments

1:   UPLO – CHARACTER(1)Input
On entry: specifies whether the upper or lower triangular part of A is stored and how A is to be factorized.
UPLO='U'
The upper triangular part of A is stored and A is factorized as UH U, where U is upper triangular.
UPLO='L'
The lower triangular part of A is stored and A is factorized as L LH, where L is lower triangular.
Constraint: UPLO='U' or 'L'.
2:   N – INTEGERInput
On entry: n, the order of the matrix A.
Constraint: N≥0.
3:   KD – INTEGERInput
On entry: kd, the number of superdiagonals or subdiagonals of the matrix A.
Constraint: KD≥0.
4:   AB LDAB* – COMPLEX (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array AB must be at least max 1,N.
On entry: the n by n Hermitian positive definite band matrix A.
The matrix is stored in rows 1 to kd+1, more precisely,
  • if UPLO='U', the elements of the upper triangle of A within the band must be stored with element A ij in AB kd+1+i-j j​ for ​max 1,j-kd≤i≤j;
  • if UPLO='L', the elements of the lower triangle of A within the band must be stored with element A ij in AB 1+i-j j​ for ​j≤i≤min n,j+kd.
On exit: the upper or lower triangle of A is overwritten by the Cholesky factor U or L as specified by UPLO, using the same storage format as described above.
5:   LDAB – INTEGERInput
On entry: the first dimension of the array AB as declared in the (sub)program from which F07HRF (ZPBTRF) is called.
Constraint: LDAB≥KD+1.
6:   INFO – INTEGEROutput
On exit: INFO=0 unless the routine detects an error (see Section 6).

6 Error Indicators and Warnings

INFO<0
If INFO=-i, argument i had an illegal value.
If INFO=-999, dynamic memory allocation failed. See Section 3.7 in How to Use the NAG Library and its Documentation for further information. An explanatory message is output, and execution of the program is terminated.
INFO>0
The leading minor of order value is not positive definite and the factorization could not be completed. Hence A itself is not positive definite. This may indicate an error in forming the matrix A. There is no routine specifically designed to factorize a Hermitian band matrix which is not positive definite; the matrix must be treated either as a nonsymmetric band matrix, by calling F07BRF (ZGBTRF) or as a full Hermitian matrix, by calling F07MRF (ZHETRF).

7 Accuracy

If UPLO='U', the computed factor U is the exact factor of a perturbed matrix A+E, where
E≤c k+1 ε UHU ,
c k+1 is a modest linear function of k+1, and ε is the machine precision.
If UPLO='L', a similar statement holds for the computed factor L. It follows that e ij≤c k+1 ε⁢a iia jj.

8 Parallelism and Performance

F07HRF (ZPBTRF) makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The total number of real floating-point operations is approximately 4 n k+1 2, assuming n≫k.
A call to F07HRF (ZPBTRF) may be followed by calls to the routines:
  • F07HSF (ZPBTRS) to solve AX=B;
  • F07HUF (ZPBCON) to estimate the condition number of A.
The real analogue of this routine is F07HDF (DPBTRF).

10 Example

This example computes the Cholesky factorization of the matrix A, where
A= 9.39+0.00 i 1.08-1.73 i 0.00+0.00 i 0.00+0.00 i 1.08+1.73 i 1.69+0.00 i -0.04+0.29 i 0.00+0.00 i 0.00+0.00 i -0.04-0.29 i 2.65+0.00 i -0.33+2.24 i 0.00+0.00 i 0.00+0.00 i -0.33-2.24 i 2.17+0.00 i .

10.1 Program Text

Program Text (f07hrfe.f90)

10.2 Program Data

Program Data (f07hrfe.d)

10.3 Program Results

Program Results (f07hrfe.r)

F07 Chapter Contents
F07 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F07HSF (ZPBTRS) : NAG Library, Mark 26

F07 Chapter Contents
F07 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F07HSF (ZPBTRS)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F07HSF (ZPBTRS) solves a complex Hermitian positive definite band system of linear equations with multiple right-hand sides,
AX=B ,
where A has been factorized by F07HRF (ZPBTRF).

2 Specification

SUBROUTINE F07HSF ( UPLO, N, KD, NRHS, AB, LDAB, B, LDB, INFO)
INTEGER | N, KD, NRHS, LDAB, LDB, INFO
COMPLEX (KIND=nag_wp) | AB(LDAB,*), B(LDB,*)
CHARACTER(1) | UPLO
The routine may be called by its LAPACK name zpbtrs.

3 Description

F07HSF (ZPBTRS) is used to solve a complex Hermitian positive definite band system of linear equations AX=B, the routine must be preceded by a call to F07HRF (ZPBTRF) which computes the Cholesky factorization of A. The solution X is computed by forward and backward substitution.
If UPLO='U', A=UH U, where U is upper triangular; the solution X is computed by solving UH Y=B and then UX=Y.
If UPLO='L', A=L LH, where L is lower triangular; the solution X is computed by solving LY=B and then LH X=Y.

4 References

Golub G H and Van Loan C F (1996) Matrix Computations (3rd Edition) Johns Hopkins University Press, Baltimore

5 Arguments

1:   UPLO – CHARACTER(1)Input
On entry: specifies how A has been factorized.
UPLO='U'
A=UH U, where U is upper triangular.
UPLO='L'
A=L LH, where L is lower triangular.
Constraint: UPLO='U' or 'L'.
2:   N – INTEGERInput
On entry: n, the order of the matrix A.
Constraint: N≥0.
3:   KD – INTEGERInput
On entry: kd, the number of superdiagonals or subdiagonals of the matrix A.
Constraint: KD≥0.
4:   NRHS – INTEGERInput
On entry: r, the number of right-hand sides.
Constraint: NRHS≥0.
5:   AB LDAB* – COMPLEX (KIND=nag_wp) arrayInput
Note: the second dimension of the array AB must be at least max 1,N.
On entry: the Cholesky factor of A, as returned by F07HRF (ZPBTRF).
6:   LDAB – INTEGERInput
On entry: the first dimension of the array AB as declared in the (sub)program from which F07HSF (ZPBTRS) is called.
Constraint: LDAB≥KD+1.
7:   B LDB* – COMPLEX (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array B must be at least max 1,NRHS.
On entry: the n by r right-hand side matrix B.
On exit: the n by r solution matrix X.
8:   LDB – INTEGERInput
On entry: the first dimension of the array B as declared in the (sub)program from which F07HSF (ZPBTRS) is called.
Constraint: LDB≥max 1,N.
9:   INFO – INTEGEROutput
On exit: INFO=0 unless the routine detects an error (see Section 6).

6 Error Indicators and Warnings

INFO<0
If INFO=-i, argument i had an illegal value. An explanatory message is output, and execution of the program is terminated.

7 Accuracy

For each right-hand side vector b, the computed solution x is the exact solution of a perturbed system of equations A+E x=b, where
  • if UPLO='U', E≤c k+1 ε UHU;
  • if UPLO='L', E≤c k+1 ε LLH,
c k+1 is a modest linear function of k+1, and ε is the machine precision.
If x^ is the true solution, then the computed solution x satisfies a forward error bound of the form
x-x^∞ x∞ ≤c k+1 cond A,x ε
where cond A,x=A-1Ax∞/x∞≤cond A=A-1A∞≤κ∞A. Note that cond A,x can be much smaller than cond A.
Forward and backward error bounds can be computed by calling F07HVF (ZPBRFS), and an estimate for κ∞A (=κ 1 A) can be obtained by calling F07HUF (ZPBCON).

8 Parallelism and Performance

F07HSF (ZPBTRS) is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
F07HSF (ZPBTRS) makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The total number of real floating-point operations is approximately 16 nkr, assuming n≫k.
This routine may be followed by a call to F07HVF (ZPBRFS) to refine the solution and return an error estimate.
The real analogue of this routine is F07HEF (DPBTRS).

10 Example

This example solves the system of equations AX=B, where
A= 9.39+0.00 i 1.08-1.73 i 0.00+0.00 i 0.00+0.00 i 1.08+1.73 i 1.69+0.00 i -0.04+0.29 i 0.00+0.00 i 0.00+0.00 i -0.04-0.29 i 2.65+0.00 i -0.33+2.24 i 0.00+0.00 i 0.00+0.00 i -0.33-2.24 i 2.17+0.00 i
and
B= -12.42+68.42 i 54.30-56.56 i -9.93+0 0.88 i 18.32+0 4.76 i -27.30-0 0.01 i -4.40+0 9.97 i 5.31+23.63 i 9.43+0 1.41 i .
Here A is Hermitian positive definite, and is treated as a band matrix, which must first be factorized by F07HRF (ZPBTRF).

10.1 Program Text

Program Text (f07hsfe.f90)

10.2 Program Data

Program Data (f07hsfe.d)

10.3 Program Results

Program Results (f07hsfe.r)

F07 Chapter Contents
F07 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F07HTF (ZPBEQU) : NAG Library, Mark 26

F07 Chapter Contents
F07 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F07HTF (ZPBEQU)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F07HTF (ZPBEQU) computes a diagonal scaling matrix S intended to equilibrate a complex n by n Hermitian positive definite band matrix A , with bandwidth 2 kd+1 , and reduce its condition number.

2 Specification

SUBROUTINE F07HTF ( UPLO, N, KD, AB, LDAB, S, SCOND, AMAX, INFO)
INTEGER | N, KD, LDAB, INFO
REAL (KIND=nag_wp) | S(N), SCOND, AMAX
COMPLEX (KIND=nag_wp) | AB(LDAB,*)
CHARACTER(1) | UPLO
The routine may be called by its LAPACK name zpbequ.

3 Description

F07HTF (ZPBEQU) computes a diagonal scaling matrix S chosen so that
sj=1 / a jj .
This means that the matrix B given by
B=SAS ,
has diagonal elements equal to unity. This in turn means that the condition number of B , κ 2 B , is within a factor n of the matrix of smallest possible condition number over all possible choices of diagonal scalings (see Corollary 7.6 of Higham (2002)).

4 References

Higham N J (2002) Accuracy and Stability of Numerical Algorithms (2nd Edition) SIAM, Philadelphia

5 Arguments

1:   UPLO – CHARACTER(1)Input
On entry: indicates whether the upper or lower triangular part of A is stored in the array AB, as follows:
UPLO='U'
The upper triangle of A is stored.
UPLO='L'
The lower triangle of A is stored.
Constraint: UPLO='U' or 'L'.
2:   N – INTEGERInput
On entry: n, the order of the matrix A.
Constraint: N≥0.
3:   KD – INTEGERInput
On entry: kd, the number of superdiagonals of the matrix A if UPLO='U', or the number of subdiagonals if UPLO='L'.
Constraint: KD≥0.
4:   AB LDAB* – COMPLEX (KIND=nag_wp) arrayInput
Note: the second dimension of the array AB must be at least max 1,N.
On entry: the upper or lower triangle of the Hermitian positive definite band matrix A whose scaling factors are to be computed.
The matrix is stored in rows 1 to kd+1, more precisely,
  • if UPLO='U', the elements of the upper triangle of A within the band must be stored with element A ij in AB kd+1+i-j j​ for ​max 1,j-kd≤i≤j;
  • if UPLO='L', the elements of the lower triangle of A within the band must be stored with element A ij in AB 1+i-j j​ for ​j≤i≤min n,j+kd.
Only the elements of the array AB corresponding to the diagonal elements of A are referenced. (Row kd+1 of AB when UPLO='U', row 1 of AB when UPLO='L'.)
5:   LDAB – INTEGERInput
On entry: the first dimension of the array AB as declared in the (sub)program from which F07HTF (ZPBEQU) is called.
Constraint: LDAB≥KD+1.
6:   S N – REAL (KIND=nag_wp) arrayOutput
On exit: if INFO=0, S contains the diagonal elements of the scaling matrix S.
7:   SCOND – REAL (KIND=nag_wp)Output
On exit: if INFO=0, SCOND contains the ratio of the smallest value of S to the largest value of S. If SCOND≥0.1 and AMAX is neither too large nor too small, it is not worth scaling by S.
8:   AMAX – REAL (KIND=nag_wp)Output
On exit: max a ij. If AMAX is very close to overflow or underflow, the matrix A should be scaled.
9:   INFO – INTEGEROutput
On exit: INFO=0 unless the routine detects an error (see Section 6).

6 Error Indicators and Warnings

INFO<0
If INFO=-i, argument i had an illegal value. An explanatory message is output, and execution of the program is terminated.
INFO>0
The valueth diagonal element of A is not positive (and hence A cannot be positive definite).

7 Accuracy

The computed scale factors will be close to the exact scale factors.

8 Parallelism and Performance

F07HTF (ZPBEQU) is not threaded in any implementation.

9 Further Comments

The real analogue of this routine is F07HFF (DPBEQU).

10 Example

This example equilibrates the Hermitian positive definite matrix A given by
A = 9.39 -i 1.08-1.73 i -i 0 -i 0 1.08+1.73 i -i 1.69 -0.04+0.29 i×1010 -i 0 0 -0.04-0.29 i×1010 2.65×1020 -0.33+2.24 i×1010 0 -i 0 -0.33-2.24 i×1010 -i 2.17 .
Details of the scaling factors and the scaled matrix are output.

10.1 Program Text

Program Text (f07htfe.f90)

10.2 Program Data

Program Data (f07htfe.d)

10.3 Program Results

Program Results (f07htfe.r)

F07 Chapter Contents
F07 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F07HUF (ZPBCON) : NAG Library, Mark 26

F07 Chapter Contents
F07 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F07HUF (ZPBCON)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F07HUF (ZPBCON) estimates the condition number of a complex Hermitian positive definite band matrix A, where A has been factorized by F07HRF (ZPBTRF).

2 Specification

SUBROUTINE F07HUF ( UPLO, N, KD, AB, LDAB, ANORM, RCOND, WORK, RWORK, INFO)
INTEGER | N, KD, LDAB, INFO
REAL (KIND=nag_wp) | ANORM, RCOND, RWORK(N)
COMPLEX (KIND=nag_wp) | AB(LDAB,*), WORK(2*N)
CHARACTER(1) | UPLO
The routine may be called by its LAPACK name zpbcon.

3 Description

F07HUF (ZPBCON) estimates the condition number (in the 1-norm) of a complex Hermitian positive definite band matrix A:
κ 1 A=A 1A-1 1 .
Since A is Hermitian, κ 1 A=κ∞A=A∞A-1∞.
Because κ 1 A is infinite if A is singular, the routine actually returns an estimate of the reciprocal of κ 1 A.
The routine should be preceded by a call to F06UEF to compute A 1 and a call to F07HRF (ZPBTRF) to compute the Cholesky factorization of A. The routine then uses Higham's implementation of Hager's method (see Higham (1988)) to estimate A-1 1.

4 References

Higham N J (1988) FORTRAN codes for estimating the one-norm of a real or complex matrix, with applications to condition estimation ACM Trans. Math. Software 14 381–396

5 Arguments

1:   UPLO – CHARACTER(1)Input
On entry: specifies how A has been factorized.
UPLO='U'
A=UH U, where U is upper triangular.
UPLO='L'
A=L LH, where L is lower triangular.
Constraint: UPLO='U' or 'L'.
2:   N – INTEGERInput
On entry: n, the order of the matrix A.
Constraint: N≥0.
3:   KD – INTEGERInput
On entry: kd, the number of superdiagonals or subdiagonals of the matrix A.
Constraint: KD≥0.
4:   AB LDAB* – COMPLEX (KIND=nag_wp) arrayInput
Note: the second dimension of the array AB must be at least max 1,N.
On entry: the Cholesky factor of A, as returned by F07HRF (ZPBTRF).
5:   LDAB – INTEGERInput
On entry: the first dimension of the array AB as declared in the (sub)program from which F07HUF (ZPBCON) is called.
Constraint: LDAB≥KD+1.
6:   ANORM – REAL (KIND=nag_wp)Input
On entry: the 1-norm of the original matrix A, which may be computed by calling F06UEF with its argument NORM='1'. ANORM must be computed either before calling F07HRF (ZPBTRF) or else from a copy of the original matrix A.
Constraint: ANORM≥0.0.
7:   RCOND – REAL (KIND=nag_wp)Output
On exit: an estimate of the reciprocal of the condition number of A. RCOND is set to zero if exact singularity is detected or the estimate underflows. If RCOND is less than machine precision, A is singular to working precision.
8:   WORK 2×N – COMPLEX (KIND=nag_wp) arrayWorkspace
9:   RWORK N – REAL (KIND=nag_wp) arrayWorkspace
10:   INFO – INTEGEROutput
On exit: INFO=0 unless the routine detects an error (see Section 6).

6 Error Indicators and Warnings

INFO<0
If INFO=-i, argument i had an illegal value. An explanatory message is output, and execution of the program is terminated.

7 Accuracy

The computed estimate RCOND is never less than the true value ρ, and in practice is nearly always less than 10 ρ, although examples can be constructed where RCOND is much larger.

8 Parallelism and Performance

F07HUF (ZPBCON) makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

A call to F07HUF (ZPBCON) involves solving a number of systems of linear equations of the form Ax=b; the number is usually 5 and never more than 11. Each solution involves approximately 16 nk real floating-point operations (assuming n≫k) but takes considerably longer than a call to F07HSF (ZPBTRS) with one right-hand side, because extra care is taken to avoid overflow when A is approximately singular.
The real analogue of this routine is F07HGF (DPBCON).

10 Example

This example estimates the condition number in the 1-norm (or ∞-norm) of the matrix A, where
A= 9.39+0.00 i 1.08-1.73 i 0.00+0.00 i 0.00+0.00 i 1.08+1.73 i 1.69+0.00 i -0.04+0.29 i 0.00+0.00 i 0.00+0.00 i -0.04-0.29 i 2.65+0.00 i -0.33+2.24 i 0.00+0.00 i 0.00+0.00 i -0.33-2.24 i 2.17+0.00 i .
Here A is Hermitian positive definite, and is treated as a band matrix, which must first be factorized by F07HRF (ZPBTRF). The true condition number in the 1-norm is 153.45.

10.1 Program Text

Program Text (f07hufe.f90)

10.2 Program Data

Program Data (f07hufe.d)

10.3 Program Results

Program Results (f07hufe.r)

F07 Chapter Contents
F07 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F07HVF (ZPBRFS) : NAG Library, Mark 26

F07 Chapter Contents
F07 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F07HVF (ZPBRFS)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F07HVF (ZPBRFS) returns error bounds for the solution of a complex Hermitian positive definite band system of linear equations with multiple right-hand sides, AX=B. It improves the solution by iterative refinement, in order to reduce the backward error as much as possible.

2 Specification

SUBROUTINE F07HVF ( UPLO, N, KD, NRHS, AB, LDAB, AFB, LDAFB, B, LDB, X, LDX, FERR, BERR, WORK, RWORK, INFO)
INTEGER | N, KD, NRHS, LDAB, LDAFB, LDB, LDX, INFO
REAL (KIND=nag_wp) | FERR(NRHS), BERR(NRHS), RWORK(N)
COMPLEX (KIND=nag_wp) | AB(LDAB,*), AFB(LDAFB,*), B(LDB,*), X(LDX,*), WORK(2*N)
CHARACTER(1) | UPLO
The routine may be called by its LAPACK name zpbrfs.

3 Description

F07HVF (ZPBRFS) returns the backward errors and estimated bounds on the forward errors for the solution of a complex Hermitian positive definite band system of linear equations with multiple right-hand sides AX=B. The routine handles each right-hand side vector (stored as a column of the matrix B) independently, so we describe the function of F07HVF (ZPBRFS) in terms of a single right-hand side b and solution x.
Given a computed solution x, the routine computes the component-wise backward error β. This is the size of the smallest relative perturbation in each element of A and b such that x is the exact solution of a perturbed system
A+δA x=b+δb δ a ij≤β a ij   and   δ bi≤β bi .
Then the routine estimates a bound for the component-wise forward error in the computed solution, defined by:
maxi xi-x^i/maxi xi
where x^ is the true solution.
For details of the method, see the F07 Chapter Introduction.

4 References

Golub G H and Van Loan C F (1996) Matrix Computations (3rd Edition) Johns Hopkins University Press, Baltimore

5 Arguments

1:   UPLO – CHARACTER(1)Input
On entry: specifies whether the upper or lower triangular part of A is stored and how A is to be factorized.
UPLO='U'
The upper triangular part of A is stored and A is factorized as UH U, where U is upper triangular.
UPLO='L'
The lower triangular part of A is stored and A is factorized as L LH, where L is lower triangular.
Constraint: UPLO='U' or 'L'.
2:   N – INTEGERInput
On entry: n, the order of the matrix A.
Constraint: N≥0.
3:   KD – INTEGERInput
On entry: kd, the number of superdiagonals or subdiagonals of the matrix A.
Constraint: KD≥0.
4:   NRHS – INTEGERInput
On entry: r, the number of right-hand sides.
Constraint: NRHS≥0.
5:   AB LDAB* – COMPLEX (KIND=nag_wp) arrayInput
Note: the second dimension of the array AB must be at least max 1,N.
On entry: the n by n original Hermitian positive definite band matrix A as supplied to F07HRF (ZPBTRF).
6:   LDAB – INTEGERInput
On entry: the first dimension of the array AB as declared in the (sub)program from which F07HVF (ZPBRFS) is called.
Constraint: LDAB≥KD+1.
7:   AFB LDAFB* – COMPLEX (KIND=nag_wp) arrayInput
Note: the second dimension of the array AFB must be at least max 1,N.
On entry: the Cholesky factor of A, as returned by F07HRF (ZPBTRF).
8:   LDAFB – INTEGERInput
On entry: the first dimension of the array AFB as declared in the (sub)program from which F07HVF (ZPBRFS) is called.
Constraint: LDAFB≥KD+1.
9:   B LDB* – COMPLEX (KIND=nag_wp) arrayInput
Note: the second dimension of the array B must be at least max 1,NRHS.
On entry: the n by r right-hand side matrix B.
10:   LDB – INTEGERInput
On entry: the first dimension of the array B as declared in the (sub)program from which F07HVF (ZPBRFS) is called.
Constraint: LDB≥max 1,N.
11:   X LDX* – COMPLEX (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array X must be at least max 1,NRHS.
On entry: the n by r solution matrix X, as returned by F07HSF (ZPBTRS).
On exit: the improved solution matrix X.
12:   LDX – INTEGERInput
On entry: the first dimension of the array X as declared in the (sub)program from which F07HVF (ZPBRFS) is called.
Constraint: LDX≥max 1,N.
13:   FERR NRHS – REAL (KIND=nag_wp) arrayOutput
On exit: FERR j contains an estimated error bound for the jth solution vector, that is, the jth column of X, for j=1,2,…,r.
14:   BERR NRHS – REAL (KIND=nag_wp) arrayOutput
On exit: BERR j contains the component-wise backward error bound β for the jth solution vector, that is, the jth column of X, for j=1,2,…,r.
15:   WORK 2×N – COMPLEX (KIND=nag_wp) arrayWorkspace
16:   RWORK N – REAL (KIND=nag_wp) arrayWorkspace
17:   INFO – INTEGEROutput
On exit: INFO=0 unless the routine detects an error (see Section 6).

6 Error Indicators and Warnings

INFO<0
If INFO=-i, argument i had an illegal value. An explanatory message is output, and execution of the program is terminated.

7 Accuracy

The bounds returned in FERR are not rigorous, because they are estimated, not computed exactly; but in practice they almost always overestimate the actual error.

8 Parallelism and Performance

F07HVF (ZPBRFS) is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
F07HVF (ZPBRFS) makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

For each right-hand side, computation of the backward error involves a minimum of 32 nk real floating-point operations. Each step of iterative refinement involves an additional 48 nk real operations. This assumes n≫k. At most five steps of iterative refinement are performed, but usually only one or two steps are required.
Estimating the forward error involves solving a number of systems of linear equations of the form Ax=b; the number is usually 5 and never more than 11. Each solution involves approximately 16 nk real operations.
The real analogue of this routine is F07HHF (DPBRFS).

10 Example

This example solves the system of equations AX=B using iterative refinement and to compute the forward and backward error bounds, where
A= 9.39+0.00 i 1.08-1.73 i 0.00+0.00 i 0.00+0.00 i 1.08+1.73 i 1.69+0.00 i -0.04+0.29 i 0.00+0.00 i 0.00+0.00 i -0.04-0.29 i 2.65+0.00 i -0.33+2.24 i 0.00+0.00 i 0.00+0.00 i -0.33-2.24 i 2.17+0.00 i
and
B= -12.42+68.42 i 54.30-56.56 i -9.93+0 0.88 i 18.32+0 4.76 i -27.30-0 0.01 i -4.40+0 9.97 i 5.31+23.63 i 9.43+0 1.41 i .
Here A is Hermitian positive definite, and is treated as a band matrix, which must first be factorized by F07HRF (ZPBTRF).

10.1 Program Text

Program Text (f07hvfe.f90)

10.2 Program Data

Program Data (f07hvfe.d)

10.3 Program Results

Program Results (f07hvfe.r)

F07 Chapter Contents
F07 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F07 Chapter Introduction : NAG Library, Mark 26

F07 Chapter Contents
NAG Library Manual

NAG Library Chapter Introduction

F07 – Linear Equations (LAPACK)

▸▿ Contents

1 Scope of the Chapter
▸▿ 2 Background to the Problems
2.1 Notation
2.2 Matrix Factorizations
2.3 Solution of Systems of Equations
▸▿ 2.4 Sensitivity and Error Analysis
2.4.1 Normwise error bounds
2.4.2 Estimating condition numbers
2.4.3 Scaling and Equilibration
2.4.4 Componentwise error bounds
2.4.5 Iterative refinement of the solution
2.5 Matrix Inversion
2.6 Packed Storage Formats
2.7 Band and Tridiagonal Matrices
2.8 Block Partitioned Algorithms
2.9 Mixed Precision LAPACK Routines
▸▿ 3 Recommendations on Choice and Use of Available Routines
3.1 Available Routines
3.2 NAG Names and LAPACK Names
▸▿ 3.3 Matrix Storage Schemes
3.3.1 Conventional storage
3.3.2 Packed storage
3.3.3 Rectangular Full Packed (RFP) Storage
3.3.4 Band storage
3.3.5 Unit triangular matrices
3.3.6 Real diagonal elements of complex matrices
▸▿ 3.4 Parameter Conventions
3.4.1 Option arguments
3.4.2 Problem dimensions
3.4.3 Length of work arrays
3.4.4 Error-handling and the diagnostic argument INFO
▸▿ 3.5 Tables of Driver and Computational Routines
3.5.1 Real matrices
3.5.2 Complex matrices
4 Functionality Index
5 Auxiliary Routines Associated with Library Routine Arguments
6 Routines Withdrawn or Scheduled for Withdrawal
7 References

1 Scope of the Chapter

This chapter provides routines for the solution of systems of simultaneous linear equations, and associated computations. It provides routines for
  • matrix factorizations;
  • solution of linear equations;
  • estimating matrix condition numbers;
  • computing error bounds for the solution of linear equations;
  • matrix inversion;
  • computing scaling factors to equilibrate a matrix.
Routines are provided for both real and complex data.
For a general introduction to the solution of systems of linear equations, you should turn first to the F04 Chapter Introduction. The decision trees, in Section 4 in the F04 Chapter Introduction, direct you to the most appropriate routines in Chapters F04 or F07 for solving your particular problem. In particular, Chapters F04 and F07 contain Black Box (or driver) routines which enable some standard types of problem to be solved by a call to a single routine. Where possible, routines in Chapter F04 call Chapter F07 routines to perform the necessary computational tasks.
There are two types of driver routines in this chapter: simple drivers which just return the solution to the linear equations; and expert drivers which also return condition and error estimates and, in many cases, also allow equilibration. The simple drivers for real matrices have names of the form F07_AF (D__SV) and for complex matrices have names of the form F07_NF (Z__SV). The expert drivers for real matrices have names of the form F07_BF (D__SVX) and for complex matrices have names of the form F07_PF (Z__SVX).
The routines in this chapter (Chapter F07) handle only dense and band matrices (not matrices with more specialised structures, or general sparse matrices).
The routines in this chapter have all been derived from the LAPACK project (see Anderson et al. (1999)). They have been designed to be efficient on a wide range of high-performance computers, without compromising efficiency on conventional serial machines.

2 Background to the Problems

This section is only a brief introduction to the numerical solution of systems of linear equations. Consult a standard textbook, for example Golub and Van Loan (1996) for a more thorough discussion.

2.1 Notation

We use the standard notation for a system of simultaneous linear equations:
Ax=b (1)
where A is the coefficient matrix, b is the right-hand side, and x is the solution. A is assumed to be a square matrix of order n.
If there are several right-hand sides, we write
AX=B (2)
where the columns of B are the individual right-hand sides, and the columns of X are the corresponding solutions.
We also use the following notation, both here and in the routine documents:
x^ | a computed solution to Ax=b, (which usually differs from the exact solution x because of round-off error)
r = b-A x^ | the residual corresponding to the computed solution x^
x∞= maxi xi | the ∞-norm of the vector x
x 1 = ∑ j=1 n xj | the 1-norm of the vector x
A∞ = maxi ∑j a ij | the ∞-norm of the matrix A
A 1 = maxj ∑ i=1 n a ij | the 1-norm of the matrix A
x | the vector with elements xi
A | the matrix with elements a ij
Inequalities of the form A≤B are interpreted component-wise, that is a ij≤b ij for all i,j.

2.2 Matrix Factorizations

If A is upper or lower triangular, Ax=b can be solved by a straightforward process of backward or forward substitution.
Otherwise, the solution is obtained after first factorizing A, as follows.
General matrices (LU factorization with partial pivoting)
A=PLU
where P is a permutation matrix, L is lower-triangular with diagonal elements equal to 1, and U is upper-triangular; the permutation matrix P (which represents row interchanges) is needed to ensure numerical stability.
Symmetric positive definite matrices (Cholesky factorization)
A=UT U   or   A=L LT
where U is upper triangular and L is lower triangular.
Symmetric positive semidefinite matrices (pivoted Cholesky factorization)
A=P UT U PT  or  A=PL LTPT
where P is a permutation matrix, U is upper triangular and L is lower triangular. The permutation matrix P (which represents row-and-column interchanges) is needed to ensure numerical stability and to reveal the numerical rank of A.
Symmetric indefinite matrices (Bunch–Kaufman factorization)
A = PUD UT PT   or   A = PLD LT PT
where P is a permutation matrix, U is upper triangular, L is lower triangular, and D is a block diagonal matrix with diagonal blocks of order 1 or 2; U and L have diagonal elements equal to 1, and have 2 by 2 unit matrices on the diagonal corresponding to the 2 by 2 blocks of D. The permutation matrix P (which represents symmetric row-and-column interchanges) and the 2 by 2 blocks in D are needed to ensure numerical stability. If A is in fact positive definite, no interchanges are needed and the factorization reduces to A=UD UT or A=LD LT with diagonal D, which is simply a variant form of the Cholesky factorization.

2.3 Solution of Systems of Equations

Given one of the above matrix factorizations, it is straightforward to compute a solution to Ax=b by solving two subproblems, as shown below, first for y and then for x. Each subproblem consists essentially of solving a triangular system of equations by forward or backward substitution; the permutation matrix P and the block diagonal matrix D introduce only a little extra complication:
General matrices ( LU factorization)
Ly=PT b Ux=y
Symmetric positive definite matrices (Cholesky factorization)
UT y=b Ux=y   or   Ly=b LT x=y
Symmetric indefinite matrices (Bunch–Kaufman factorization)
PUDy=b UTPT x=y   or   PLDy=b LTPT x=y

2.4 Sensitivity and Error Analysis

2.4.1 Normwise error bounds

Frequently, in practical problems the data A and b are not known exactly, and it is then important to understand how uncertainties or perturbations in the data can affect the solution.
If x is the exact solution to Ax=b, and x+δx is the exact solution to a perturbed problem A+δAx+δx=b+δb, then
δx x ≤κ A δA A +δb b +⋯second-order terms
where κ A is the condition number of A defined by
κ A = A.A-1 . (3)
In other words, relative errors in A or b may be amplified in x by a factor κ A. Section 2.4.2 discusses how to compute or estimate κ A.
Similar considerations apply when we study the effects of rounding errors introduced by computation in finite precision. The effects of rounding errors can be shown to be equivalent to perturbations in the original data, such that δA A and δb b are usually at most p n ε, where ε is the machine precision and p n is an increasing function of n which is seldom larger than 10 n (although in theory it can be as large as 2 n-1).
In other words, the computed solution x^ is the exact solution of a linear system A+δA x^=b+δb which is close to the original system in a normwise sense.

2.4.2 Estimating condition numbers

The previous section has emphasized the usefulness of the quantity κ A in understanding the sensitivity of the solution of Ax=b. To compute the value of κ A from equation (3) is more expensive than solving Ax=b in the first place. Hence it is standard practice to estimate κ A, in either the 1-norm or the ∞-norm, by a method which only requires O n 2 additional operations, assuming that a suitable factorization of A is available.
The method used in this chapter is Higham's modification of Hager's method (see Higham (1988)). It yields an estimate which is never larger than the true value, but which seldom falls short by more than a factor of 3 (although artificial examples can be constructed where it is much smaller). This is acceptable since it is the order of magnitude of κ A which is important rather than its precise value.
Because κ A is infinite if A is singular, the routines in this chapter actually return the reciprocal of κ A.

2.4.3 Scaling and Equilibration

The condition of a matrix and hence the accuracy of the computed solution, may be improved by scaling; thus if D 1 and D 2 are diagonal matrices with positive diagonal elements, then
B = D 1 A D 2
is the scaled matrix. A general matrix is said to be equilibrated if it is scaled so that the lengths of its rows and columns have approximately equal magnitude. Similarly a general matrix is said to be row-equilibrated (column-equilibrated) if it is scaled so that the lengths of its rows (columns) have approximately equal magnitude. Note that row scaling can affect the choice of pivot when partial pivoting is used in the factorization of A.
A symmetric or Hermitian positive definite matrix is said to be equilibrated if the diagonal elements are all approximately equal to unity.
For further information on scaling and equilibration see Section 3.5.2 of Golub and Van Loan (1996), Section 7.2, 7.3 and 9.8 of Higham (1988) and Section 5 of Chapter 4 of Wilkinson (1965).
Routines are provided to return the scaling factors that equilibrate a matrix for general, general band, symmetric and Hermitian positive definite and symmetric and Hermitian positive definite band matrices.

2.4.4 Componentwise error bounds

A disadvantage of normwise error bounds is that they do not reflect any special structure in the data A and b – that is, a pattern of elements which are known to be zero – and the bounds are dominated by the largest elements in the data.
Componentwise error bounds overcome these limitations. Instead of the normwise relative error, we can bound the relative error in each component of A and b:
max ijk δ a ij a ij , δ bk bk ≤ω
where the component-wise backward error bound ω is given by
ω= maxi ri A. x^+b i .
Routines are provided in this chapter which compute ω, and also compute a forward error bound which is sometimes much sharper than the normwise bound given earlier:
x- x^ ∞ x∞ ≤ A-1 . r ∞ x∞ .
Care is taken when computing this bound to allow for rounding errors in computing r. The norm A-1.r∞ is estimated cheaply (without computing A-1) by a modification of the method used to estimate κ A.

2.4.5 Iterative refinement of the solution

If x^ is an approximate computed solution to Ax=b, and r is the corresponding residual, then a procedure for iterative refinement of x^ can be defined as follows, starting with x 0=x^:
  • for i=0,1,…, until convergence
    compute | ri=b-A xi
    solve | A di=ri
    compute | x i+1=xi+di
In Chapter F04, routines are provided which perform this procedure using additional precision to compute r, and are thus able to reduce the forward error to the level of machine precision.
The routines in this chapter do not use additional precision to compute r, and cannot guarantee a small forward error, but can guarantee a small backward error (except in rare cases when A is very ill-conditioned, or when A and x are sparse in such a way that A.x has a zero or very small component). The iterations continue until the backward error has been reduced as much as possible; usually only one iteration is needed.

2.5 Matrix Inversion

It is seldom necessary to compute an explicit inverse of a matrix. In particular, do not attempt to solve Ax=b by first computing A-1 and then forming the matrix-vector product x=A-1 b; the procedure described in Section 2.3 is more efficient and more accurate.
However, routines are provided for the rare occasions when an inverse is needed, using one of the factorizations described in Section 2.2.

2.6 Packed Storage Formats

Routines which handle symmetric matrices are usually designed so that they use either the upper or lower triangle of the matrix; it is not necessary to store the whole matrix. If the upper or lower triangle is stored conventionally in the upper or lower triangle of a two-dimensional array, the remaining elements of the array can be used to store other useful data.
However, that is not always convenient, and if it is important to economize on storage, the upper or lower triangle can be stored in a one-dimensional array of length n n+1/2 or a two-dimensional array with n n+1/2 elements; in other words, the storage is almost halved.
The one-dimensional array storage format is referred to as packed storage; it is described in Section 3.3.2. The two-dimensional array storage format is referred to as Rectangular Full Packed (RFP) format; it is described in Section 3.3.3. They may also be used for triangular matrices.
Routines designed for these packed storage formats perform the same number of arithmetic operations as routines which use conventional storage. Those using a packed one-dimensional array are usually less efficient, especially on high-performance computers, so there is then a trade-off between storage and efficiency. The RFP routines are as efficient as for conventional storage, although only a small subset of routines use this format.

2.7 Band and Tridiagonal Matrices

A band matrix is one whose nonzero elements are confined to a relatively small number of subdiagonals or superdiagonals on either side of the main diagonal. A tridiagonal matrix is a special case of a band matrix with just one subdiagonal and one superdiagonal. Algorithms can take advantage of bandedness to reduce the amount of work and storage required. The storage scheme used for band matrices is described in Section 3.3.4.
The LU factorization for general matrices, and the Cholesky factorization for symmetric and Hermitian positive definite matrices both preserve bandedness. Hence routines are provided which take advantage of the band structure when solving systems of linear equations.
The Cholesky factorization preserves bandedness in a very precise sense: the factor U or L has the same number of superdiagonals or subdiagonals as the original matrix. In the LU factorization, the row-interchanges modify the band structure: if A has kl subdiagonals and ku superdiagonals, then L is not a band matrix but still has at most kl nonzero elements below the diagonal in each column; and U has at most kl+ku superdiagonals.
The Bunch–Kaufman factorization does not preserve bandedness, because of the need for symmetric row-and-column permutations; hence no routines are provided for symmetric indefinite band matrices.
The inverse of a band matrix does not in general have a band structure, so no routines are provided for computing inverses of band matrices.

2.8 Block Partitioned Algorithms

Many of the routines in this chapter use what is termed a block partitioned algorithm. This means that at each major step of the algorithm a block of rows or columns is updated, and most of the computation is performed by matrix-matrix operations on these blocks. The matrix-matrix operations are performed by calls to the Level 3 BLAS (see Chapter F06), which are the key to achieving high performance on many modern computers. See Golub and Van Loan (1996) or Anderson et al. (1999) for more about block partitioned algorithms.
The performance of a block partitioned algorithm varies to some extent with the block size – that is, the number of rows or columns per block. This is a machine-dependent argument, which is set to a suitable value when the library is implemented on each range of machines. You do not normally need to be aware of what value is being used. Different block sizes may be used for different routines. Values in the range 16 to 64 are typical.
On some machines there may be no advantage from using a block partitioned algorithm, and then the routines use an unblocked algorithm (effectively a block size of 1), relying solely on calls to the Level 2 BLAS (see Chapter F06 again).
The only situation in which you need some awareness of the block size is when it affects the amount of workspace to be supplied to a particular routine. This is discussed in Section 3.4.3.

2.9 Mixed Precision LAPACK Routines

Some LAPACK routines use mixed precision arithmetic in an effort to solve problems more efficiently on modern hardware. They work by converting a double precision problem into an equivalent single precision problem, solving it and then using iterative refinement in double precision to find a full precision solution to the original problem. The method may fail if the problem is too ill-conditioned to allow the initial single precision solution, in which case the routines fall back to solve the original problem entirely in double precision. The vast majority of problems are not so ill-conditioned, and in those cases the technique can lead to significant gains in speed without loss of accuracy. This is particularly true on machines where double precision arithmetic is significantly slower than single precision.

3 Recommendations on Choice and Use of Available Routines

3.1 Available Routines

Tables 1 to 8 in Section 3.5 show the routines which are provided for performing different computations on different types of matrices. Tables 1 to 4 show routines for real matrices; Tables 5 to 8 show routines for complex matrices. Each entry in the table gives the NAG routine name and the LAPACK double precision name (see Section 3.2).
Routines are provided for the following types of matrix:
  • general
  • general band
  • general tridiagonal
  • symmetric or Hermitian positive definite
  • symmetric or Hermitian positive definite (packed storage)
  • symmetric or Hermitian positive definite (RFP storage)
  • symmetric or Hermitian positive definite band
  • symmetric or Hermitian positive definite tridiagonal
  • symmetric or Hermitian indefinite
  • symmetric or Hermitian indefinite (packed storage)
  • triangular
  • triangular (packed storage)
  • triangular (RFP storage)
  • triangular band
For each of the above types of matrix (except where indicated), routines are provided to perform the following computations:
(a) | (except for RFP matrices) solve a system of linear equations (driver routines);
(b) | (except for RFP matrices) solve a system of linear equations with condition and error estimation (expert drivers);
(c) | (except for triangular matrices) factorize the matrix (see Section 2.2);
(d) | solve a system of linear equations, using the factorization (see Section 2.3);
(e) | (except for RFP matrices) estimate the condition number of the matrix, using the factorization (see Section 2.4.2); these routines also require the norm of the original matrix (except when the matrix is triangular) which may be computed by a routine in Chapter F06;
(f) | (except for RFP matrices) refine the solution and compute forward and backward error bounds (see Sections 2.4.4 and 2.4.5); these routines require the original matrix and right-hand side, as well as the factorization returned from (a) and the solution returned from (b);
(g) | (except for band and tridiagonal matrices) invert the matrix, using the factorization (see Section 2.5);
(h) | (except for tridiagonal, symmetric indefinite, triangular and RFP matrices) compute scale factors to equilibrate the matrix (see Section 2.4.3).
Thus, to solve a particular problem, it is usually only necessary to call a single driver routine, but alternatively two or more routines may be called in succession. This is illustrated in the example programs in the routine documents.

3.2 NAG Names and LAPACK Names

As well as the NAG routine name (beginning F07), Tables 1 to 8 show the LAPACK routine names in double precision.
The routines may be called either by their NAG names or by their LAPACK names. When using the NAG Library, the double precision form of the LAPACK name must be used (beginning with D- or Z-).
References to Chapter F07 routines in the manual normally include the LAPACK double precision names, for example, F07ADF (DGETRF).
The LAPACK routine names follow a simple scheme (which is similar to that used for the BLAS in Chapter F06). Most names have the structure XYYZZZ, where the components have the following meanings:
– the initial letter X indicates the data type (real or complex) and precision:
S | – real, single precision (in Fortran 77, REAL)
D | – real, double precision (in Fortran 77, DOUBLE PRECISION)
C | – complex, single precision (in Fortran 77, COMPLEX)
Z | – complex, double precision (in Fortran 77, COMPLEX*16 or DOUBLE COMPLEX)
– exceptionally, the mixed precision LAPACK routines described in Section 2.9 replace the initial first letter by a pair of letters, as:
DS | – double precision routine using single precision internally
ZC | – double complex routine using single precision complex internally
– the letters YY indicate the type of the matrix A (and in some cases its storage scheme):
GE | – general
GB | – general band
PO | – symmetric or Hermitian positive definite
PF | – symmetric or Hermitian positive definite (RFP storage)
PP | – symmetric or Hermitian positive definite (packed storage)
PB | – symmetric or Hermitian positive definite band
SY | – symmetric indefinite
SF | – symmetric indefinite (RFP storage)
SP | – symmetric indefinite (packed storage)
HE | – (complex) Hermitian indefinite
HF | – (complex) Hermitian indefinite (RFP storage)
HP | – (complex) Hermitian indefinite (packed storage)
GT | – general tridiagonal
PT | – symmetric or Hermitian positive definite tridiagonal
TR | – triangular
TF | – triangular (RFP storage)
TP | – triangular (packed storage)
TB | – triangular band
– the last two or three letters ZZ or ZZZ indicate the computation performed. Examples are:
TRF | – triangular factorization
TRS | – solution of linear equations, using the factorization
CON | – estimate condition number
RFS | – refine solution and compute error bounds
TRI | – compute inverse, using the factorization
Thus the routine DGETRF performs a triangular factorization of a real general matrix in double precision; the corresponding routine for a complex general matrix is ZGETRF.

3.3 Matrix Storage Schemes

In this chapter the following different storage schemes are used for matrices:
  • – conventional storage in a two-dimensional array;
  • – packed storage for symmetric, Hermitian or triangular matrices;
  • – rectangular full packed (RFP) storage for symmetric, Hermitian or triangular matrices;
  • – band storage for band matrices.
These storage schemes are compatible with those used in Chapter F06 (especially in the BLAS) and Chapter F08, but different schemes for packed or band storage are used in a few older routines in Chapters F01, F02, F03 and F04.
In the examples below, * indicates an array element which need not be set and is not referenced by the routines. The examples illustrate only the relevant part of the arrays; array arguments may of course have additional rows or columns, according to the usual rules for passing array arguments in Fortran 77.

3.3.1 Conventional storage

The default scheme for storing matrices is the obvious one: a matrix A is stored in a two-dimensional array A, with matrix element a ij stored in array element A i,j .
If a matrix is triangular (upper or lower, as specified by the argument UPLO), only the elements of the relevant triangle are stored; the remaining elements of the array need not be set. Such elements are indicated by * or ⌴ in the examples below.
For example, when n=4:
UPLO | Triangular matrix A | Storage in array A
'U' | a 11 a 12 a 13 a 14 a 22 a 23 a 24 a 33 a 34 a 44 | a 11 a 12 a 13 a 14 ⌴ a 22 a 23 a 24 ⌴ ⌴ a 33 a 34 ⌴ ⌴ ⌴ a 44
'L' | a 11 a 21 a 22 a 31 a 32 a 33 a 41 a 42 a 43 a 44 | a 11 ⌴ ⌴ ⌴ a 21 a 22 ⌴ ⌴ a 31 a 32 a 33 ⌴ a 41 a 42 a 43 a 44
Routines which handle symmetric or Hermitian matrices allow for either the upper or lower triangle of the matrix (as specified by UPLO) to be stored in the corresponding elements of the array; the remaining elements of the array need not be set.
For example, when n=4:
UPLO | Hermitian matrix A | Storage in array A
'U' | a 11 a 12 a 13 a 14 a-12 a 22 a 23 a 24 a-13 a-23 a 33 a 34 a-14 a-24 a-34 a 44 | a 11 a 12 a 13 a 14 ⌴ a 22 a 23 a 24 ⌴ ⌴ a 33 a 34 ⌴ ⌴ ⌴ a 44
'L' | a 11 a-21 a-31 a-41 a 21 a 22 a-32 a-42 a 31 a 32 a 33 a-43 a 41 a 42 a 43 a 44 | a 11 ⌴ ⌴ ⌴ a 21 a 22 ⌴ ⌴ a 31 a 32 a 33 ⌴ a 41 a 42 a 43 a 44

3.3.2 Packed storage

Symmetric, Hermitian or triangular matrices may be stored more compactly, if the relevant triangle (again as specified by UPLO) is packed by columns in a one-dimensional array. In this chapter, as in Chapters F06 and F08, arrays which hold matrices in packed storage, have names ending in P. For a matrix of order n, the array must have at least n n+1/2 elements. So:
  • if UPLO='U', a ij is stored in AP i+j j-1/2 for i≤j;
  • if UPLO='L', a ij is stored in AP i+2 n-jj-1/2 for j≤i.
For example:
 | Triangle of matrix A | Packed storage in array AP
UPLO='U' | a 11 a 12 a 13 a 14 a 22 a 23 a 24 a 33 a 34 a 44 | a 11 a 12 a 22 ︸ a 13 a 23 a 33 ︸ a 14 a 24 a 34 a 44 ︸
UPLO='L' | a 11 a 21 a 22 a 31 a 32 a 33 a 41 a 42 a 43 a 44 | a 11 a 21 a 31 a 41 ︸ a 22 a 32 a 42 ︸ a 33 a 43 ︸ a 44
Note that for real symmetric matrices, packing the upper triangle by columns is equivalent to packing the lower triangle by rows; packing the lower triangle by columns is equivalent to packing the upper triangle by rows. (For complex Hermitian matrices, the only difference is that the off-diagonal elements are conjugated.)

3.3.3 Rectangular Full Packed (RFP) Storage

The rectangular full packed (RFP) storage format offers the same savings in storage as the packed storage format (described in Section 3.3.2), but is likely to be much more efficient in general since the block structure of the matrix is maintained. This structure can be exploited using block partition algorithms (see Section 2.8) in a similar way to matrices that use conventional storage.
Figure 1
Figure 1 gives a graphical representation of the key idea of RFP for the particular case of a lower triangular matrix of even dimensions. In all cases the original triangular matrix of stored elements is separated into a trapezoidal part and a triangular part. The number of columns in these two parts is equal when the dimension of the matrix is even, n=2 k, while the trapezoidal part has k+1 columns when n=2 k+1. The smaller part is then transposed and fitted onto the trapezoidal part forming a rectangle. The rectangle has dimensions 2 k+1 and q, where q=k when n is even and q=k+1 when n is odd.
For routines using RFP there is the option of storing the rectangle as described above (TRANSR='N') or its transpose (TRANSR='T', for real A) or its conjugate transpose (TRANSR='C', for complex A).
As an example, we first consider RFP for the case n=2 k with k=3.
If TRANSR='N', then AR holds A as follows:
  • For UPLO='U' the upper trapezoid AR 1:61:3 consists of the last three columns of A upper. The lower triangle AR 5:71:3 consists of the transpose of the first three columns of A upper.
  • For UPLO='L' the lower trapezoid AR 2:71:3 consists of the first three columns of A lower. The upper triangle AR 1:31:3 consists of the transpose of the last three columns of A lower.
If TRANSR='T', then AR in both UPLO cases is just the transpose of AR as defined when TRANSR='N'.
UPLO | Triangle of matrix A | Rectangular Full Packed matrix AR
 |  | TRANSR='N' | TRANSR='T'
'U' | 00 01 02 03 04 05 11 12 13 14 15 22 23 24 25 33 34 35 44 45 55 | 03 04 05 13 14 15 23 24 25 33 34 35 00 44 45 01 11 55 02 12 22 | 03 13 23 33 00 01 02 04 1424 3444 11 12 05 1525 35 4555 22
'L' | 00 10 11 20 21 22 30 31 32 33 40 41 42 43 44 50 51 52 53 54 55 | 33 43 53 00 44 54 10 11 55 20 21 22 30 31 32 40 41 42 50 51 52 | 33 00 10 20 30 40 50 43 44 11 21 31 41 51 53 54 55 22 32 42 52
Now we consider RFP for the case n=2 k+1 and k=2.
If TRANSR='N'. AR holds A as follows:
  • if UPLO='U' the upper trapezoid AR 1:51:3 consists of the last three columns of A upper. The lower triangle AR 4:51:2 consists of the transpose of the first two columns of A upper;
  • if UPLO='L' the lower trapezoid AR 1:51:3 consists of the first three columns of A lower. The upper triangle AR 1:22:3 consists of the transpose of the last two columns of A lower.
If TRANSR='T'. AR in both UPLO cases is just the transpose of AR as defined when TRANSR='N'.
UPLO | Triangle of matrix A | Rectangular Full Packed matrix AR
 |  | TRANSR='N' | TRANSR='T'
'U' | 00 01 02 03 04 11 12 13 14 22 23 24 33 34 44 | 02 03 04 12 13 14 22 23 24 00 33 34 01 11 44 | 02 12 22 00 01 03 13 23 33 11 04 14 24 34 44
'L' | 00 10 11 20 21 22 30 31 32 33 40 41 42 43 44 | 00 33 43 10 11 44 20 21 22 30 31 32 40 41 42 | 00 10 20 30 40 50 33 11 21 31 41 51 43 44 22 32 42 52
Explicitly, in the real matrix case, AR is a one-dimensional array of length n n+1/2 and contains the elements of A as follows:
for UPLO='U' and TRANSR='N',
a ij is stored in AR 2 k+1 i-1 + j + k + 1 , for 1≤j≤k and 1≤i≤j, and
a ij is stored in AR 2 k+1 j-k-1 + i , for k<j≤n and 1≤i≤j;
for UPLO='U' and TRANSR='T',
a ij is stored in AR q j+k +i , for 1≤j≤k and 1≤i≤j, and
a ij is stored in AR q i-1 + j - k , for k<j≤n and 1≤i≤j;
for UPLO='L' and TRANSR='N',
a ij is stored in AR 2 k+1 j-1 +i +k -q +1 , for 1≤j≤q and j≤i≤n, and
a ij is stored in AR 2 k+1 i-k-1 +j-q , for q<j≤n and j≤i≤n;
for UPLO='L' and TRANSR='T',
a ij is stored in AR q i+k-q +j , for 1≤j≤q and 1≤i≤n, and
a ij is stored in AR q j-1-q +i-k , for q<j≤n and 1≤i≤n.
In the case of complex matrices, the assumption is that the full matrix, if it existed, would be Hermitian. Thus, when TRANSR='N', the triangular portion of A that is, in the real case, transposed into the notional 2 k+1 by q RFP matrix is also conjugated. When TRANSR='C' the notional q by 2 k+1 RFP matrix is the conjugate transpose of the corresponding TRANSR='N' RFP matrix. Explicitly, for complex A, the array AR contains the elements (or conjugated elements) of A as follows:
for UPLO='U' and TRANSR='N',
a-ij is stored in AR 2 k+1 i-1 + j + k + 1 , for 1≤j≤k and 1≤i≤j, and
a ij is stored in AR 2 k+1 j-k-1 + i , for k<j≤n and 1≤i≤j;
for UPLO='U' and TRANSR='C',
a ij is stored in AR q j+k +i , for 1≤j≤k and 1≤i≤j, and
a-ij is stored in AR q i-1 + j - k , for k<j≤n and 1≤i≤j;
for UPLO='L' and TRANSR='N',
a ij is stored in AR 2 k+1 j-1 +i +k -q +1 , for 1≤j≤q and j≤i≤n, and
a-ij is stored in AR 2 k+1 i-k-1 +j-q , for q<j≤n and j≤i≤n;
for UPLO='L' and TRANSR='C',
a-ij is stored in AR q i+k-q +j , for 1≤j≤q and 1≤i≤n, and
a ij is stored in AR q j-1-q +i-k , for q<j≤n and 1≤i≤n.

3.3.4 Band storage

A band matrix with kl subdiagonals and ku superdiagonals may be stored compactly in a two-dimensional array with kl+ku+1 rows and n columns. Columns of the matrix are stored in corresponding columns of the array, and diagonals of the matrix are stored in rows of the array. This storage scheme should be used in practice only if kl, ku≪n, although the routines in Chapters F07 and F08 work correctly for all values of kl and ku. In Chapters F07 and F08 arrays which hold matrices in band storage have names ending in B.
To be precise, elements of matrix elements a ij are stored as follows:
  • a ij is stored in AB ku+1+i-j j for max 1,j-ku ≤ i ≤ min n,j+kl .
For example, when n=5, kl=2 and ku=1:
Band matrix A | Band storage in array AB
a 11 a 12 a 21 a 22 a 23 a 31 a 32 a 33 a 34 a 42 a 43 a 44 a 45 a 53 a 54 a 55 | * a 12 a 23 a 34 a 45 a 11 a 22 a 33 a 44 a 55 a 21 a 32 a 43 a 54 * a 31 a 42 a 53 * *
The elements marked * in the upper left and lower right corners of the array AB need not be set, and are not referenced by the routines.
Note: when a general band matrix is supplied for LU factorization, space must be allowed to store an additional kl superdiagonals, generated by fill-in as a result of row interchanges. This means that the matrix is stored according to the above scheme, but with kl+ku superdiagonals.
Triangular band matrices are stored in the same format, with either kl=0 if upper triangular, or ku=0 if lower triangular.
For symmetric or Hermitian band matrices with k subdiagonals or superdiagonals, only the upper or lower triangle (as specified by UPLO) need be stored:
  • if UPLO='U', a ij is stored in AB k+1+i-j,j for max 1,j-k≤i≤j;
  • if UPLO='L', a ij is stored in AB 1+i-j,j for j≤i≤min n,j+k.
For example, when n=5 and k=2:
UPLO | Hermitian band matrix A | Band storage in array AB
'U' | a 11 a 12 a 13 a-12 a 22 a 23 a 24 a-13 a-23 a 33 a 34 a 35 a-24 a-34 a 44 a 45 a-35 a-45 a 55 | * * a 13 a 24 a 35 * a 12 a 23 a 34 a 45 a 11 a 22 a 33 a 44 a 55
'L' | a 11 a-21 a-31 a 21 a 22 a-32 a-42 a 31 a 32 a 33 a-43 a-53 a 42 a 43 a 44 a-54 a 53 a 54 a 55 | a 11 a 22 a 33 a 44 a 55 a 21 a 32 a 43 a 54 * a 31 a 42 a 53 * *
Note that different storage schemes for band matrices are used by some routines in Chapters F01, F02, F03 and F04.

3.3.5 Unit triangular matrices

Some routines in this chapter have an option to handle unit triangular matrices (that is, triangular matrices with diagonal elements =1). This option is specified by an argument DIAG. If DIAG='U' (Unit triangular), the diagonal elements of the matrix need not be stored, and the corresponding array elements are not referenced by the routines. The storage scheme for the rest of the matrix (whether conventional, packed or band) remains unchanged.

3.3.6 Real diagonal elements of complex matrices

Complex Hermitian matrices have diagonal elements that are by definition purely real. In addition, complex triangular matrices which arise in Cholesky factorization are defined by the algorithm to have real diagonal elements.
If such matrices are supplied as input to routines in Chapters F07 and F08, the imaginary parts of the diagonal elements are not referenced, but are assumed to be zero. If such matrices are returned as output by the routines, the computed imaginary parts are explicitly set to zero.

3.4 Parameter Conventions

3.4.1 Option arguments

Most routines in this chapter have one or more option arguments, of type CHARACTER. The descriptions in Section 5 of the routine documents refer only to upper-case values (for example UPLO='U' or 'L'); however, in every case, the corresponding lower-case characters may be supplied (with the same meaning). Any other value is illegal.
A longer character string can be passed as the actual argument, making the calling program more readable, but only the first character is significant. (This is a feature of Fortran 77.) For example:
CALL DGETRS('Transpose',...)

3.4.2 Problem dimensions

It is permissible for the problem dimensions (for example, M in F07ADF (DGETRF), N or NRHS in F07AEF (DGETRS)) to be passed as zero, in which case the computation (or part of it) is skipped. Negative dimensions are regarded as an error.

3.4.3 Length of work arrays

A few routines implementing block partitioned algorithms require workspace sufficient to hold one block of rows or columns of the matrix if they are to achieve optimum levels of performance — for example, workspace of size n×nb, where nb is the optimum block size. In such cases, the actual declared length of the work array must be passed as a separate argument LWORK, which immediately follows WORK in the argument-list.
The routine will still perform correctly when less workspace is provided: it uses the largest block size allowed by the amount of workspace supplied, as long as this is likely to give better performance than the unblocked algorithm. On exit, WORK 1 contains the minimum value of LWORK which would allow the routine to use the optimum block size; this value of LWORK may be used for subsequent runs.
If LWORK indicates that there is insufficient workspace to perform the unblocked algorithm, this is regarded as an illegal value of LWORK, and is treated like any other illegal argument value (see Section 3.4.4), though WORK 1 will still be set as described above.
If you are in doubt how much workspace to supply and are concerned to achieve optimum performance, supply a generous amount (assume a block size of 64, say), and then examine the value of WORK 1 on exit.

3.4.4 Error-handling and the diagnostic argument INFO

Routines in this chapter do not use the usual NAG Library error-handling mechanism, involving the argument IFAIL. Instead they have a diagnostic argument INFO. (Thus they preserve complete compatibility with the LAPACK specification.)
Whereas IFAIL is an Input/Output argument and must be set before calling a routine, INFO is purely an Output argument and need not be set before entry.
INFO indicates the success or failure of the computation, as follows:
  • INFO=0: successful termination
  • INFO>0: failure in the course of computation, control returned to the calling program
If the routine document specifies that the routine may terminate with INFO>0, then it is essential to test INFO on exit from the routine. (This corresponds to a soft failure in terms of the usual NAG error-handling terminology.) No error message is output.
All routines check that input arguments such as N or LDA or option arguments of type CHARACTER have permitted values. If an illegal value of the ith argument is detected, INFO is set to -i, a message is output, and execution of the program is terminated. (This corresponds to a hard failure in the usual NAG terminology.)

3.5 Tables of Driver and Computational Routines

3.5.1 Real matrices

Each entry in the following tables, listing real matrices, gives:
  • the NAG routine name and
  • the double precision LAPACK routine name.
 | Type of matrix and storage scheme
Operation | general | general band | general tridiagonal
driver | F07AAF (DGESV) | F07BAF (DGBSV) | F07CAF (DGTSV)
expert driver | F07ABF (DGESVX) | F07BBF (DGBSVX) | F07CBF (DGTSVX)
mixed precision driver | F07ACF (DSGESV) |  |
factorize | F07ADF (DGETRF) | F07BDF (DGBTRF) | F07CDF (DGTTRF)
solve | F07AEF (DGETRS) | F07BEF (DGBTRS) | F07CEF (DGTTRS)
scaling factors | F07AFF (DGEEQU) | F07BFF (DGBEQU) |
condition number | F07AGF (DGECON) | F07BGF (DGBCON) | F07CGF (DGTCON)
error estimate | F07AHF (DGERFS) | F07BHF (DGBRFS) | F07CHF (DGTRFS)
invert | F07AJF (DGETRI) |  |
Table 1
Routines for real general matrices
 | Type of matrix and storage scheme
Operation | symmetric positive definite | symmetric positive definite (packed storage) | symmetric positive definite (RFP storage) | symmetric positive definite band | symmetric positive definite tridiagonal | symmetric positive semidefinite
driver | F07FAF (DPOSV) | F07GAF (DPPSV) |  | F07HAF (DPBSV) | F07JAF (DPTSV) |
expert driver | F07FBF (DPOSVX) | F07GBF (DPPSVX) |  | F07HBF (DPBSVX) | F07JBF (DPTSVX) |
mixed precision | F07FCF (DSPOSV) |  |  |  |  |
factorize | F07FDF (DPOTRF) | F07GDF (DPPTRF) | F07WDF (DPFTRF) | F07HDF (DPBTRF) | F07JDF (DPTTRF) | F07KDF (DPSTRF)
solve | F07FEF (DPOTRS) | F07GEF (DPPTRS) | F07WEF (DPFTRS) | F07HEF (DPBTRS) | F07JEF (DPTTRS) |
scaling factors | F07FFF (DPOEQU) | F07GFF (DPPEQU) |  | F07HFF (DPBEQU) |  |
condition number | F07FGF (DPOCON) | F07GGF (DPPCON) |  | F07HGF (DPBCON) | F07JGF (DPTCON) |
error estimate | F07FHF (DPORFS) | F07GHF (DPPRFS) |  | F07HHF (DPBRFS) | F07JHF (DPTRFS) |
invert | F07FJF (DPOTRI) | F07GJF (DPPTRI) | F07WJF (DPFTRI) |  |  |
Table 2
Routines for real symmetric positive definite and positive semidefinite matrices
 | Type of matrix and storage scheme
Operation | symmetric indefinite | symmetric indefinite (packed storage)
driver | F07MAF (DSYSV) | F07PAF (DSPSV)
expert driver | F07MBF (DSYSVX) | F07PBF (DSPSVX)
factorize | F07MDF (DSYTRF) | F07PDF (DSPTRF)
solve | F07MEF (DSYTRS) | F07PEF (DSPTRS)
condition number | F07MGF (DSYCON) | F07PGF (DSPCON)
error estimate | F07MHF (DSYRFS) | F07PHF (DSPRFS)
invert | F07MJF (DSYTRI) | F07PJF (DSPTRI)
Table 3
Routines for real symmetric indefinite matrices
 | Type of matrix and storage scheme
Operation | triangular | triangular (packed storage) | triangular (RFP storage) | triangular band
solve | F07TEF (DTRTRS) | F07UEF (DTPTRS) |  | F07VEF (DTBTRS)
condition number | F07TGF (DTRCON) | F07UGF (DTPCON) |  | F07VGF (DTBCON)
error estimate | F07THF (DTRRFS) | F07UHF (DTPRFS) |  | F07VHF (DTBRFS)
invert | F07TJF (DTRTRI) | F07UJF (DTPTRI) | F07WKF (DTFTRI) |
Table 4
Routines for real triangular matrices

3.5.2 Complex matrices

Each entry in the following tables, listing complex matrices, gives:
  • the NAG routine name and
  • the double precision LAPACK routine name.
 | Type of matrix and storage scheme
Operation | general | general band | general tridiagonal
driver | F07ANF (ZGESV) | F07BNF (ZGBSV) | F07CNF (ZGTSV)
expert driver | F07APF (ZGESVX) | F07BPF (ZGBSVX) | F07CPF (ZGTSVX)
mixed precision driver | F07AQF (ZCGESV) |  |
factorize | F07ARF (ZGETRF) | F07BRF (ZGBTRF) | F07CRF (ZGTTRF)
solve | F07ASF (ZGETRS) | F07BSF (ZGBTRS) | F07CSF (ZGTTRS)
scaling factors | F07ATF (ZGEEQU) | F07BTF (ZGBEQU) |
condition number | F07AUF (ZGECON) | F07BUF (ZGBCON) | F07CUF (ZGTCON)
error estimate | F07AVF (ZGERFS) | F07BVF (ZGBRFS) | F07CVF (ZGTRFS)
invert | F07AWF (ZGETRI) |  |
Table 5
Routines for complex general matrices
 | Type of matrix and storage scheme
Operation | Hermitian positive definite | Hermitian positive definite (packed storage) | Hermitian positive definite (RFP storage) | Hermitian positive definite band | Hermitian positive definite tridiagonal | Hermitian positive semidefinite
driver | F07FNF (ZPOSV) | F07GNF (ZPPSV) |  | F07HNF (ZPBSV) | F07JNF (ZPTSV) |
expert driver | F07FPF (ZPOSVX) | F07GPF (ZPPSVX) |  | F07HPF (ZPBSVX) | F07JPF (ZPTSVX) |
mixed precision driver | F07FQF (ZCPOSV) |  |  |  |  |
factorize | F07FRF (ZPOTRF) | F07GRF (ZPPTRF) | F07WRF (ZPFTRF) | F07HRF (ZPBTRF) | F07JRF (ZPTTRF) | F07KRF (ZPSTRF)
solve | F07FSF (ZPOTRS) | F07GSF (ZPPTRS) | F07WSF (ZPFTRS) | F07HSF (ZPBTRS) | F07JSF (ZPTTRS) |
scaling factors | F07FTF (ZPOEQU) | F07GTF (ZPPEQU) |  |  |  |
condition number | F07FUF (ZPOCON) | F07GUF (ZPPCON) |  | F07HUF (ZPBCON) | F07JUF (ZPTCON) |
error estimate | F07FVF (ZPORFS) | F07GVF (ZPPRFS) |  | F07HVF (ZPBRFS) | F07JVF (ZPTRFS) |
invert | F07FWF (ZPOTRI) | F07GWF (ZPPTRI) | F07WWF (ZPFTRI) |  |  |
Table 6
Routines for complex Hermitian positive definite and positive semidefinite matrices
 | Type of matrix and storage scheme
Operation | Hermitian indefinite | symmetric indefinite (packed storage) | Hermitian indefinite band | symmetric indefinite tridiagonal
driver | F07MNF (ZHESV) | F07NNF (ZSYSV) | F07PNF (ZHPSV) | F07QNF (ZSPSV)
expert driver | F07MPF (ZHESVX) | F07NPF (ZSYSVX) | F07PPF (ZHPSVX) | F07QPF (ZSPSVX)
factorize | F07MRF (ZHETRF) | F07NRF (ZSYTRF) | F07PRF (ZHPTRF) | F07QRF (ZSPTRF)
solve | F07MSF (ZHETRS) | F07NSF (ZSYTRS) | F07PSF (ZHPTRS) | F07QSF (ZSPTRS)
condition number | F07MUF (ZHECON) | F07NUF (ZSYCON) | F07PUF (ZHPCON) | F07QUF (ZSPCON)
error estimate | F07MVF (ZHERFS) | F07NVF (ZSYRFS) | F07PVF (ZHPRFS) | F07QVF (ZSPRFS)
invert | F07MWF (ZHETRI) | F07NWF (ZSYTRI) | F07PWF (ZHPTRI) | F07QWF (ZSPTRI)
Table 7
Routines for complex Hermitian and symmetric indefinite matrices
 | Type of matrix and storage scheme
Operation | triangular | triangular (packed storage) | triangular (RFP storage) | triangular band
solve | F07TSF (ZTRTRS) | F07USF (ZTPTRS) |  | F07VSF (ZTBTRS)
condition number | F07TUF (ZTRCON) | F07UUF (ZTPCON) |  | F07VUF (ZTBCON)
error estimate | F07TVF (ZTRRFS) | F07UVF (ZTPRFS) |  | F07VVF (ZTBRFS)
invert | F07TWF (ZTRTRI) | F07UWF (ZTPTRI) | F07WXF (ZTFTRI) |
Table 8
Routines for complex triangular matrices

4 Functionality Index

Apply iterative refinement to the solution and compute error estimates,
after factorizing the matrix of coefficients,
complex band matrix F07BVF (ZGBRFS)
complex Hermitian indefinite matrix F07MVF (ZHERFS)
complex Hermitian indefinite matrix, packed storage F07PVF (ZHPRFS)
complex Hermitian positive definite band matrix F07HVF (ZPBRFS)
complex Hermitian positive definite matrix F07FVF (ZPORFS)
complex Hermitian positive definite matrix, packed storage F07GVF (ZPPRFS)
complex Hermitian positive definite tridiagonal matrix F07JVF (ZPTRFS)
complex matrix F07AVF (ZGERFS)
complex symmetric indefinite matrix F07NVF (ZSYRFS)
complex symmetric indefinite matrix, packed storage F07QVF (ZSPRFS)
complex tridiagonal matrix F07CVF (ZGTRFS)
real band matrix F07BHF (DGBRFS)
real matrix F07AHF (DGERFS)
real symmetric indefinite matrix F07MHF (DSYRFS)
real symmetric indefinite matrix, packed storage F07PHF (DSPRFS)
real symmetric positive definite band matrix F07HHF (DPBRFS)
real symmetric positive definite matrix F07FHF (DPORFS)
real symmetric positive definite matrix, packed storage F07GHF (DPPRFS)
real symmetric positive definite tridiagonal matrix F07JHF (DPTRFS)
real tridiagonal matrix F07CHF (DGTRFS)
Compute error estimates,
complex triangular band matrix F07VVF (ZTBRFS)
complex triangular matrix F07TVF (ZTRRFS)
complex triangular matrix, packed storage F07UVF (ZTPRFS)
real triangular band matrix F07VHF (DTBRFS)
real triangular matrix F07THF (DTRRFS)
real triangular matrix, packed storage F07UHF (DTPRFS)
Compute row and column scalings,
complex band matrix F07BTF (ZGBEQU)
complex Hermitian positive definite band matrix F07HTF (ZPBEQU)
complex Hermitian positive definite matrix F07FTF (ZPOEQU)
complex Hermitian positive definite matrix, packed storage F07GTF (ZPPEQU)
complex matrix F07ATF (ZGEEQU)
real band matrix F07BFF (DGBEQU)
real matrix F07AFF (DGEEQU)
real symmetric positive definite band matrix F07HFF (DPBEQU)
real symmetric positive definite matrix F07FFF (DPOEQU)
real symmetric positive definite matrix, packed storage F07GFF (DPPEQU)
Condition number estimation,
after factorizing the matrix of coefficients,
complex band matrix F07BUF (ZGBCON)
complex Hermitian indefinite matrix F07MUF (ZHECON)
complex Hermitian indefinite matrix, packed storage F07PUF (ZHPCON)
complex Hermitian positive definite band matrix F07HUF (ZPBCON)
complex Hermitian positive definite matrix F07FUF (ZPOCON)
complex Hermitian positive definite matrix, packed storage F07GUF (ZPPCON)
complex Hermitian positive definite tridiagonal matrix F07JUF (ZPTCON)
complex matrix F07AUF (ZGECON)
complex symmetric indefinite matrix F07NUF (ZSYCON)
complex symmetric indefinite matrix, packed storage F07QUF (ZSPCON)
complex tridiagonal matrix F07CUF (ZGTCON)
real band matrix F07BGF (DGBCON)
real matrix F07AGF (DGECON)
real symmetric indefinite matrix F07MGF (DSYCON)
real symmetric indefinite matrix, packed storage F07PGF (DSPCON)
real symmetric positive definite band matrix F07HGF (DPBCON)
real symmetric positive definite matrix F07FGF (DPOCON)
real symmetric positive definite matrix, packed storage F07GGF (DPPCON)
real symmetric positive definite tridiagonal matrix F07JGF (DPTCON)
real tridiagonal matrix F07CGF (DGTCON)
complex triangular band matrix F07VUF (ZTBCON)
complex triangular matrix F07TUF (ZTRCON)
complex triangular matrix, packed storage F07UUF (ZTPCON)
real triangular band matrix F07VGF (DTBCON)
real triangular matrix F07TGF (DTRCON)
real triangular matrix, packed storage F07UGF (DTPCON)
LD LT factorization,
complex Hermitian positive definite tridiagonal matrix F07JRF (ZPTTRF)
real symmetric positive definite tridiagonal matrix F07JDF (DPTTRF)
L LT or UT U factorization,
complex Hermitian positive definite band matrix F07HRF (ZPBTRF)
complex Hermitian positive definite matrix F07FRF (ZPOTRF)
complex Hermitian positive definite matrix, packed storage F07GRF (ZPPTRF)
complex Hermitian positive definite matrix, RFP storage F07WRF (ZPFTRF)
complex Hermitian positive semidefinite matrix F07KRF (ZPSTRF)
real symmetric positive definite band matrix F07HDF (DPBTRF)
real symmetric positive definite matrix F07FDF (DPOTRF)
real symmetric positive definite matrix, packed storage F07GDF (DPPTRF)
real symmetric positive definite matrix, RFP storage F07WDF (DPFTRF)
real symmetric positive semidefinite matrix F07KDF (DPSTRF)
LU factorization,
complex band matrix F07BRF (ZGBTRF)
complex matrix F07ARF (ZGETRF)
complex tridiagonal matrix F07CRF (ZGTTRF)
real band matrix F07BDF (DGBTRF)
real matrix F07ADF (DGETRF)
real tridiagonal matrix F07CDF (DGTTRF)
Matrix inversion,
after factorizing the matrix of coefficients,
complex Hermitian indefinite matrix F07MWF (ZHETRI)
complex Hermitian indefinite matrix, packed storage F07PWF (ZHPTRI)
complex Hermitian positive definite matrix F07FWF (ZPOTRI)
complex Hermitian positive definite matrix, packed storage F07GWF (ZPPTRI)
complex Hermitian positive definite matrix, RFP storage F07WWF (ZPFTRI)
complex matrix F07AWF (ZGETRI)
complex symmetric indefinite matrix F07NWF (ZSYTRI)
complex symmetric indefinite matrix, packed storage F07QWF (ZSPTRI)
real matrix F07AJF (DGETRI)
real symmetric indefinite matrix F07MJF (DSYTRI)
real symmetric indefinite matrix, packed storage F07PJF (DSPTRI)
real symmetric positive definite matrix F07FJF (DPOTRI)
real symmetric positive definite matrix, packed storage F07GJF (DPPTRI)
real symmetric positive definite matrix, RFP storage F07WJF (DPFTRI)
complex triangular matrix F07TWF (ZTRTRI)
complex triangular matrix, packed storage F07UWF (ZTPTRI)
complex triangular matrix, RFP storage,
expert driver F07WXF (ZTFTRI)
real triangular matrix F07TJF (DTRTRI)
real triangular matrix, packed storage F07UJF (DTPTRI)
real triangular matrix, RFP storage,
expert driver F07WKF (DTFTRI)
PLD LTPT or PUD UTPT factorization,
complex Hermitian indefinite matrix F07MRF (ZHETRF)
complex Hermitian indefinite matrix, packed storage F07PRF (ZHPTRF)
complex symmetric indefinite matrix F07NRF (ZSYTRF)
complex symmetric indefinite matrix, packed storage F07QRF (ZSPTRF)
real symmetric indefinite matrix F07MDF (DSYTRF)
real symmetric indefinite matrix, packed storage F07PDF (DSPTRF)
Solution of simultaneous linear equations,
after factorizing the matrix of coefficients,
complex band matrix F07BSF (ZGBTRS)
complex Hermitian indefinite matrix F07MSF (ZHETRS)
complex Hermitian indefinite matrix, packed storage F07PSF (ZHPTRS)
complex Hermitian positive definite band matrix F07HSF (ZPBTRS)
complex Hermitian positive definite matrix F07FSF (ZPOTRS)
complex Hermitian positive definite matrix, packed storage F07GSF (ZPPTRS)
complex Hermitian positive definite matrix, RFP storage F07WSF (ZPFTRS)
complex Hermitian positive definite tridiagonal matrix F07JSF (ZPTTRS)
complex matrix F07ASF (ZGETRS)
complex symmetric indefinite matrix F07NSF (ZSYTRS)
complex symmetric indefinite matrix, packed storage F07QSF (ZSPTRS)
complex tridiagonal matrix F07CSF (ZGTTRS)
real band matrix F07BEF (DGBTRS)
real matrix F07AEF (DGETRS)
real symmetric indefinite matrix F07MEF (DSYTRS)
real symmetric indefinite matrix, packed storage F07PEF (DSPTRS)
real symmetric positive definite band matrix F07HEF (DPBTRS)
real symmetric positive definite matrix F07FEF (DPOTRS)
real symmetric positive definite matrix, packed storage F07GEF (DPPTRS)
real symmetric positive definite matrix, RFP storage F07WEF (DPFTRS)
real symmetric positive definite tridiagonal matrix F07JEF (DPTTRS)
real tridiagonal matrix F07CEF (DGTTRS)
expert drivers (with condition and error estimation):
complex band matrix F07BPF (ZGBSVX)
complex Hermitian indefinite matrix F07MPF (ZHESVX)
complex Hermitian indefinite matrix, packed storage F07PPF (ZHPSVX)
complex Hermitian positive definite band matrix F07HPF (ZPBSVX)
complex Hermitian positive definite matrix F07FPF (ZPOSVX)
complex Hermitian positive definite matrix, packed storage F07GPF (ZPPSVX)
complex Hermitian positive definite tridiagonal matrix F07JPF (ZPTSVX)
complex matrix F07APF (ZGESVX)
complex symmetric indefinite matrix F07NPF (ZSYSVX)
complex symmetric indefinite matrix, packed storage F07QPF (ZSPSVX)
complex tridiagonal matrix F07CPF (ZGTSVX)
real band matrix F07BBF (DGBSVX)
real matrix F07ABF (DGESVX)
real symmetric indefinite matrix F07MBF (DSYSVX)
real symmetric indefinite matrix, packed storage F07PBF (DSPSVX)
real symmetric positive definite band matrix F07HBF (DPBSVX)
real symmetric positive definite matrix F07FBF (DPOSVX)
real symmetric positive definite matrix, packed storage F07GBF (DPPSVX)
real symmetric positive definite tridiagonal matrix F07JBF (DPTSVX)
real tridiagonal matrix F07CBF (DGTSVX)
simple drivers,
complex band matrix F07BNF (ZGBSV)
complex Hermitian indefinite matrix F07MNF (ZHESV)
complex Hermitian indefinite matrix, packed storage F07PNF (ZHPSV)
complex Hermitian positive definite band matrix F07HNF (ZPBSV)
complex Hermitian positive definite matrix F07FNF (ZPOSV)
complex Hermitian positive definite matrix, packed storage F07GNF (ZPPSV)
complex Hermitian positive definite matrix, using mixed precision F07FQF (ZCPOSV)
complex Hermitian positive definite tridiagonal matrix F07JNF (ZPTSV)
complex matrix F07ANF (ZGESV)
complex matrix, using mixed precision F07AQF (ZCGESV)
complex symmetric indefinite matrix F07NNF (ZSYSV)
complex symmetric indefinite matrix, packed storage F07QNF (ZSPSV)
complex triangular band matrix F07VSF (ZTBTRS)
complex triangular matrix F07TSF (ZTRTRS)
complex triangular matrix, packed storage F07USF (ZTPTRS)
complex tridiagonal matrix F07CNF (ZGTSV)
real band matrix F07BAF (DGBSV)
real matrix F07AAF (DGESV)
real matrix, using mixed precision F07ACF (DSGESV)
real symmetric indefinite matrix F07MAF (DSYSV)
real symmetric indefinite matrix, packed storage F07PAF (DSPSV)
real symmetric positive definite band matrix F07HAF (DPBSV)
real symmetric positive definite matrix F07FAF (DPOSV)
real symmetric positive definite matrix, packed storage F07GAF (DPPSV)
real symmetric positive definite matrix, using mixed precision F07FCF (DSPOSV)
real symmetric positive definite tridiagonal matrix F07JAF (DPTSV)
real triangular band matrix F07VEF (DTBTRS)
real triangular matrix F07TEF (DTRTRS)
real triangular matrix, packed storage F07UEF (DTPTRS)
real tridiagonal matrix F07CAF (DGTSV)

5 Auxiliary Routines Associated with Library Routine Arguments

None.

6 Routines Withdrawn or Scheduled for Withdrawal

None.

7 References

Anderson E, Bai Z, Bischof C, Blackford S, Demmel J, Dongarra J J, Du Croz J J, Greenbaum A, Hammarling S, McKenney A and Sorensen D (1999) LAPACK Users' Guide (3rd Edition) SIAM, Philadelphia
Golub G H and Van Loan C F (1996) Matrix Computations (3rd Edition) Johns Hopkins University Press, Baltimore
Higham N J (1988) Algorithm 674: Fortran codes for estimating the one-norm of a real or complex matrix, with applications to condition estimation ACM Trans. Math. Software 14 381–396
Wilkinson J H (1965) The Algebraic Eigenvalue Problem Oxford University Press, Oxford
F07 Chapter Contents
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F07JAF (DPTSV) : NAG Library, Mark 26

F07 Chapter Contents
F07 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F07JAF (DPTSV)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F07JAF (DPTSV) computes the solution to a real system of linear equations
AX=B ,
where A is an n by n symmetric positive definite tridiagonal matrix, and X and B are n by r matrices.

2 Specification

SUBROUTINE F07JAF ( N, NRHS, D, E, B, LDB, INFO)
INTEGER | N, NRHS, LDB, INFO
REAL (KIND=nag_wp) | D(*), E(*), B(LDB,*)
The routine may be called by its LAPACK name dptsv.

3 Description

F07JAF (DPTSV) factors A as A=LD LT. The factored form of A is then used to solve the system of equations.

4 References

Anderson E, Bai Z, Bischof C, Blackford S, Demmel J, Dongarra J J, Du Croz J J, Greenbaum A, Hammarling S, McKenney A and Sorensen D (1999) LAPACK Users' Guide (3rd Edition) SIAM, Philadelphia http://www.netlib.org/lapack/lug
Golub G H and Van Loan C F (1996) Matrix Computations (3rd Edition) Johns Hopkins University Press, Baltimore

5 Arguments

1:   N – INTEGERInput
On entry: n, the order of the matrix A.
Constraint: N≥0.
2:   NRHS – INTEGERInput
On entry: r, the number of right-hand sides, i.e., the number of columns of the matrix B.
Constraint: NRHS≥0.
3:   D* – REAL (KIND=nag_wp) arrayInput/Output
Note: the dimension of the array D must be at least max 1,N.
On entry: the n diagonal elements of the tridiagonal matrix A.
On exit: the n diagonal elements of the diagonal matrix D from the factorization A=LD LT.
4:   E* – REAL (KIND=nag_wp) arrayInput/Output
Note: the dimension of the array E must be at least max 1,N-1.
On entry: the n-1 subdiagonal elements of the tridiagonal matrix A.
On exit: the n-1 subdiagonal elements of the unit bidiagonal factor L from the LD LT factorization of A. (E can also be regarded as the superdiagonal of the unit bidiagonal factor U from the UT DU factorization of A.)
5:   B LDB* – REAL (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array B must be at least max 1,NRHS.
On entry: the n by r right-hand side matrix B.
On exit: if INFO=0, the n by r solution matrix X.
6:   LDB – INTEGERInput
On entry: the first dimension of the array B as declared in the (sub)program from which F07JAF (DPTSV) is called.
Constraint: LDB≥max 1,N.
7:   INFO – INTEGEROutput
On exit: INFO=0 unless the routine detects an error (see Section 6).

6 Error Indicators and Warnings

INFO<0
If INFO=-i, argument i had an illegal value. An explanatory message is output, and execution of the program is terminated.
INFO>0
The leading minor of order value is not positive definite, and the solution has not been computed. The factorization has not been completed unless N=value.

7 Accuracy

The computed solution for a single right-hand side, x^ , satisfies an equation of the form
A+E x^=b ,
where
E 1 = O ε A 1
and ε is the machine precision. An approximate error bound for the computed solution is given by
x^-x 1 x 1 ≤ κ A E 1 A 1 ,
where κ A = A-1 1 A 1 , the condition number of A with respect to the solution of the linear equations. See Section 4.4 of Anderson et al. (1999) for further details.
F07JBF (DPTSVX) is a comprehensive LAPACK driver that returns forward and backward error bounds and an estimate of the condition number. Alternatively, F04BGF solves Ax=b and returns a forward error bound and condition estimate. F04BGF calls F07JAF (DPTSV) to solve the equations.

8 Parallelism and Performance

F07JAF (DPTSV) makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The number of floating-point operations required for the factorization of A is proportional to n , and the number of floating-point operations required for the solution of the equations is proportional to nr , where r is the number of right-hand sides.
The complex analogue of this routine is F07JNF (ZPTSV).

10 Example

This example solves the equations
Ax=b ,
where A is the symmetric positive definite tridiagonal matrix
A = 4.0 -2.0 0 0 0 -2.0 10.0 -6.0 0 0 0 -6.0 29.0 15.0 0 0 0 15.0 25.0 8.0 0 0 0 8.0 5.0   and   b = 6.0 9.0 2.0 14.0 7.0 .
Details of the LD LT factorization of A are also output.

10.1 Program Text

Program Text (f07jafe.f90)

10.2 Program Data

Program Data (f07jafe.d)

10.3 Program Results

Program Results (f07jafe.r)

F07 Chapter Contents
F07 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F07JBF (DPTSVX) : NAG Library, Mark 26

F07 Chapter Contents
F07 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F07JBF (DPTSVX)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F07JBF (DPTSVX) uses the factorization
A=LD LT
to compute the solution to a real system of linear equations
AX=B ,
where A is an n by n symmetric positive definite tridiagonal matrix and X and B are n by r matrices. Error bounds on the solution and a condition estimate are also provided.

2 Specification

SUBROUTINE F07JBF ( FACT, N, NRHS, D, E, DF, EF, B, LDB, X, LDX, RCOND, FERR, BERR, WORK, INFO)
INTEGER | N, NRHS, LDB, LDX, INFO
REAL (KIND=nag_wp) | D(*), E(*), DF(*), EF(*), B(LDB,*), X(LDX,*), RCOND, FERR(NRHS), BERR(NRHS), WORK(2*N)
CHARACTER(1) | FACT
The routine may be called by its LAPACK name dptsvx.

3 Description

F07JBF (DPTSVX) performs the following steps:
1. | If FACT='N', the matrix A is factorized as A=LD LT, where L is a unit lower bidiagonal matrix and D is diagonal. The factorization can also be regarded as having the form A=UT DU.
2. | If the leading i by i principal minor is not positive definite, then the routine returns with INFO=i. Otherwise, the factored form of A is used to estimate the condition number of the matrix A. If the reciprocal of the condition number is less than machine precision, INFO=N+1 is returned as a warning, but the routine still goes on to solve for X and compute error bounds as described below.
3. | The system of equations is solved for X using the factored form of A.
4. | Iterative refinement is applied to improve the computed solution matrix and to calculate error bounds and backward error estimates for it.

4 References

Anderson E, Bai Z, Bischof C, Blackford S, Demmel J, Dongarra J J, Du Croz J J, Greenbaum A, Hammarling S, McKenney A and Sorensen D (1999) LAPACK Users' Guide (3rd Edition) SIAM, Philadelphia http://www.netlib.org/lapack/lug
Golub G H and Van Loan C F (1996) Matrix Computations (3rd Edition) Johns Hopkins University Press, Baltimore
Higham N J (2002) Accuracy and Stability of Numerical Algorithms (2nd Edition) SIAM, Philadelphia

5 Arguments

1:   FACT – CHARACTER(1)Input
On entry: specifies whether or not the factorized form of the matrix A has been supplied.
FACT='F'
DF and EF contain the factorized form of the matrix A. DF and EF will not be modified.
FACT='N'
The matrix A will be copied to DF and EF and factorized.
Constraint: FACT='F' or 'N'.
2:   N – INTEGERInput
On entry: n, the order of the matrix A.
Constraint: N≥0.
3:   NRHS – INTEGERInput
On entry: r, the number of right-hand sides, i.e., the number of columns of the matrix B.
Constraint: NRHS≥0.
4:   D* – REAL (KIND=nag_wp) arrayInput
Note: the dimension of the array D must be at least max 1,N.
On entry: the n diagonal elements of the tridiagonal matrix A.
5:   E* – REAL (KIND=nag_wp) arrayInput
Note: the dimension of the array E must be at least max 1,N-1.
On entry: the n-1 subdiagonal elements of the tridiagonal matrix A.
6:   DF* – REAL (KIND=nag_wp) arrayInput/Output
Note: the dimension of the array DF must be at least max 1,N.
On entry: if FACT='F', DF must contain the n diagonal elements of the diagonal matrix D from the LD LT factorization of A.
On exit: if FACT='N', DF contains the n diagonal elements of the diagonal matrix D from the LD LT factorization of A.
7:   EF* – REAL (KIND=nag_wp) arrayInput/Output
Note: the dimension of the array EF must be at least max 1,N-1.
On entry: if FACT='F', EF must contain the n-1 subdiagonal elements of the unit bidiagonal factor L from the LD LT factorization of A.
On exit: if FACT='N', EF contains the n-1 subdiagonal elements of the unit bidiagonal factor L from the LD LT factorization of A.
8:   B LDB* – REAL (KIND=nag_wp) arrayInput
Note: the second dimension of the array B must be at least max 1,NRHS.
On entry: the n by r right-hand side matrix B.
9:   LDB – INTEGERInput
On entry: the first dimension of the array B as declared in the (sub)program from which F07JBF (DPTSVX) is called.
Constraint: LDB≥max 1,N.
10:   X LDX* – REAL (KIND=nag_wp) arrayOutput
Note: the second dimension of the array X must be at least max 1,NRHS.
On exit: if INFO=0 or N+1, the n by r solution matrix X.
11:   LDX – INTEGERInput
On entry: the first dimension of the array X as declared in the (sub)program from which F07JBF (DPTSVX) is called.
Constraint: LDX≥max 1,N.
12:   RCOND – REAL (KIND=nag_wp)Output
On exit: the reciprocal condition number of the matrix A. If RCOND is less than the machine precision (in particular, if RCOND=0.0), the matrix is singular to working precision. This condition is indicated by a return code of INFO=N+1.
13:   FERR NRHS – REAL (KIND=nag_wp) arrayOutput
On exit: the forward error bound for each solution vector x^j (the jth column of the solution matrix X). If xj is the true solution corresponding to x^j, FERR j is an estimated upper bound for the magnitude of the largest element in (x^j-xj) divided by the magnitude of the largest element in x^j.
14:   BERR NRHS – REAL (KIND=nag_wp) arrayOutput
On exit: the component-wise relative backward error of each solution vector x^j (i.e., the smallest relative change in any element of A or B that makes x^j an exact solution).
15:   WORK 2×N – REAL (KIND=nag_wp) arrayWorkspace
16:   INFO – INTEGEROutput
On exit: INFO=0 unless the routine detects an error (see Section 6).

6 Error Indicators and Warnings

INFO<0
If INFO=-i, argument i had an illegal value. An explanatory message is output, and execution of the program is terminated.
INFO>0 and INFO≤N
The leading minor of order value of A is not positive definite, so the factorization could not be completed, and the solution has not been computed. RCOND=0.0 is returned.
INFO=N+1
D is nonsingular, but RCOND is less than machine precision, meaning that the matrix is singular to working precision. Nevertheless, the solution and error bounds are computed because there are a number of situations where the computed solution can be more accurate than the value of RCOND would suggest.

7 Accuracy

For each right-hand side vector b, the computed solution x^ is the exact solution of a perturbed system of equations A+E x^=b, where
E ≤ c n ε R RT , where ​ R = L D 12 ,
c n is a modest linear function of n, and ε is the machine precision. See Section 10.1 of Higham (2002) for further details.
If x is the true solution, then the computed solution x^ satisfies a forward error bound of the form
x-x^∞ x^∞ ≤ wc cond A,x^,b
where cond A,x^,b = A-1 A x^ + b ∞/ x^∞ ≤ cond A = A-1 A ∞≤κ∞ A. If x^ is the j th column of X , then wc is returned in BERR j and a bound on x - x^ ∞ / x^ ∞ is returned in FERR j . See Section 4.4 of Anderson et al. (1999) for further details.

8 Parallelism and Performance

F07JBF (DPTSVX) is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
F07JBF (DPTSVX) makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The number of floating-point operations required for the factorization, and for the estimation of the condition number of A is proportional to n . The number of floating-point operations required for the solution of the equations, and for the estimation of the forward and backward error is proportional to nr , where r is the number of right-hand sides.
The condition estimation is based upon Equation (15.11) of Higham (2002). For further details of the error estimation, see Section 4.4 of Anderson et al. (1999).
The complex analogue of this routine is F07JPF (ZPTSVX).

10 Example

This example solves the equations
AX=B ,
where A is the symmetric positive definite tridiagonal matrix
A = 4.0 -2.0 0 0 0 -2.0 10.0 -6.0 0 0 0 -6.0 29.0 15.0 0 0 0 15.0 25.0 8.0 0 0 0 8.0 5.0
and
B = 6.0 10.0 9.0 4.0 2.0 9.0 14.0 65.0 7.0 23.0 .
Error estimates for the solutions and an estimate of the reciprocal of the condition number of A are also output.

10.1 Program Text

Program Text (f07jbfe.f90)

10.2 Program Data

Program Data (f07jbfe.d)

10.3 Program Results

Program Results (f07jbfe.r)

F07 Chapter Contents
F07 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F07JDF (DPTTRF) : NAG Library, Mark 26

F07 Chapter Contents
F07 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F07JDF (DPTTRF)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F07JDF (DPTTRF) computes the modified Cholesky factorization of a real n by n symmetric positive definite tridiagonal matrix A .

2 Specification

SUBROUTINE F07JDF ( N, D, E, INFO)
INTEGER | N, INFO
REAL (KIND=nag_wp) | D(*), E(*)
The routine may be called by its LAPACK name dpttrf.

3 Description

F07JDF (DPTTRF) factorizes the matrix A as
A=LD LT ,
where L is a unit lower bidiagonal matrix and D is a diagonal matrix with positive diagonal elements. The factorization may also be regarded as having the form UT DU , where U is a unit upper bidiagonal matrix.

4 References

None.

5 Arguments

1:   N – INTEGERInput
On entry: n, the order of the matrix A.
Constraint: N≥0.
2:   D* – REAL (KIND=nag_wp) arrayInput/Output
Note: the dimension of the array D must be at least max 1,N.
On entry: must contain the n diagonal elements of the matrix A.
On exit: is overwritten by the n diagonal elements of the diagonal matrix D from the LD LT factorization of A.
3:   E* – REAL (KIND=nag_wp) arrayInput/Output
Note: the dimension of the array E must be at least max 1,N-1.
On entry: must contain the n-1 subdiagonal elements of the matrix A.
On exit: is overwritten by the n-1 subdiagonal elements of the lower bidiagonal matrix L. (E can also be regarded as containing the n-1 superdiagonal elements of the upper bidiagonal matrix U.)
4:   INFO – INTEGEROutput
On exit: INFO=0 unless the routine detects an error (see Section 6).

6 Error Indicators and Warnings

INFO<0
If INFO=-i, argument i had an illegal value. An explanatory message is output, and execution of the program is terminated.
INFO>0 and INFO<N
The leading minor of order value is not positive definite, the factorization could not be completed.
INFO>0 and INFO=N
The leading minor of order n is not positive definite, the factorization was completed, but D N≤0.

7 Accuracy

The computed factorization satisfies an equation of the form
A+E=LD LT ,
where
E∞=O ε A∞
and ε is the machine precision.
Following the use of this routine, F07JEF (DPTTRS) can be used to solve systems of equations AX=B , and F07JGF (DPTCON) can be used to estimate the condition number of A .

8 Parallelism and Performance

F07JDF (DPTTRF) is not threaded in any implementation.

9 Further Comments

The total number of floating-point operations required to factorize the matrix A is proportional to n .
The complex analogue of this routine is F07JRF (ZPTTRF).

10 Example

This example factorizes the symmetric positive definite tridiagonal matrix A given by
A = 4.0 -2.0 0.0 0.0 0.0 -2.0 10.0 -6.0 0.0 0.0 0.0 -6.0 29.0 15.0 0.0 0.0 0.0 15.0 25.0 8.0 0.0 0.0 0.0 8.0 5.0 .

10.1 Program Text

Program Text (f07jdfe.f90)

10.2 Program Data

Program Data (f07jdfe.d)

10.3 Program Results

Program Results (f07jdfe.r)

F07 Chapter Contents
F07 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F07JEF (DPTTRS) : NAG Library, Mark 26

F07 Chapter Contents
F07 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F07JEF (DPTTRS)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F07JEF (DPTTRS) computes the solution to a real system of linear equations AX=B , where A is an n by n symmetric positive definite tridiagonal matrix and X and B are n by r matrices, using the LD LT factorization returned by F07JDF (DPTTRF).

2 Specification

SUBROUTINE F07JEF ( N, NRHS, D, E, B, LDB, INFO)
INTEGER | N, NRHS, LDB, INFO
REAL (KIND=nag_wp) | D(*), E(*), B(LDB,*)
The routine may be called by its LAPACK name dpttrs.

3 Description

F07JEF (DPTTRS) should be preceded by a call to F07JDF (DPTTRF), which computes a modified Cholesky factorization of the matrix A as
A=LD LT ,
where L is a unit lower bidiagonal matrix and D is a diagonal matrix, with positive diagonal elements. F07JEF (DPTTRS) then utilizes the factorization to solve the required equations. Note that the factorization may also be regarded as having the form UT DU , where U is a unit upper bidiagonal matrix.

4 References

Anderson E, Bai Z, Bischof C, Blackford S, Demmel J, Dongarra J J, Du Croz J J, Greenbaum A, Hammarling S, McKenney A and Sorensen D (1999) LAPACK Users' Guide (3rd Edition) SIAM, Philadelphia http://www.netlib.org/lapack/lug

5 Arguments

1:   N – INTEGERInput
On entry: n, the order of the matrix A.
Constraint: N≥0.
2:   NRHS – INTEGERInput
On entry: r, the number of right-hand sides, i.e., the number of columns of the matrix B.
Constraint: NRHS≥0.
3:   D* – REAL (KIND=nag_wp) arrayInput
Note: the dimension of the array D must be at least max 1,N.
On entry: must contain the n diagonal elements of the diagonal matrix D from the LD LT factorization of A.
4:   E* – REAL (KIND=nag_wp) arrayInput
Note: the dimension of the array E must be at least max 1,N-1.
On entry: must contain the n-1 subdiagonal elements of the unit lower bidiagonal matrix L. (E can also be regarded as the superdiagonal of the unit upper bidiagonal matrix U from the UT DU factorization of A.)
5:   B LDB* – REAL (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array B must be at least max 1,NRHS.
On entry: the n by r matrix of right-hand sides B.
On exit: the n by r solution matrix X.
6:   LDB – INTEGERInput
On entry: the first dimension of the array B as declared in the (sub)program from which F07JEF (DPTTRS) is called.
Constraint: LDB≥max 1,N.
7:   INFO – INTEGEROutput
On exit: INFO=0 unless the routine detects an error (see Section 6).

6 Error Indicators and Warnings

INFO<0
If INFO=-i, argument i had an illegal value. An explanatory message is output, and execution of the program is terminated.

7 Accuracy

The computed solution for a single right-hand side, x^ , satisfies an equation of the form
A+E x^=b ,
where
E 1 =O ε A 1
and ε is the machine precision. An approximate error bound for the computed solution is given by
x^ - x 1 x 1 ≤ κ A E 1 A 1 ,
where κ A = A-1 1 A 1 , the condition number of A with respect to the solution of the linear equations. See Section 4.4 of Anderson et al. (1999) for further details.
Following the use of this routine F07JGF (DPTCON) can be used to estimate the condition number of A and F07JHF (DPTRFS) can be used to obtain approximate error bounds.

8 Parallelism and Performance

F07JEF (DPTTRS) makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The total number of floating-point operations required to solve the equations AX=B is proportional to nr .
The complex analogue of this routine is F07JSF (ZPTTRS).

10 Example

This example solves the equations
AX=B ,
where A is the symmetric positive definite tridiagonal matrix
A = 4.0 -2.0 0.0 0.0 0.0 -2.0 10.0 -6.0 0.0 0.0 0.0 -6.0 29.0 15.0 0.0 0.0 0.0 15.0 25.0 8.0 0.0 0.0 0.0 8.0 5.0   and   B = 6.0 10.0 9.0 4.0 2.0 9.0 14.0 65.0 7.0 23.0 .

10.1 Program Text

Program Text (f07jefe.f90)

10.2 Program Data

Program Data (f07jefe.d)

10.3 Program Results

Program Results (f07jefe.r)

F07 Chapter Contents
F07 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F07JGF (DPTCON) : NAG Library, Mark 26

F07 Chapter Contents
F07 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F07JGF (DPTCON)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F07JGF (DPTCON) computes the reciprocal condition number of a real n by n symmetric positive definite tridiagonal matrix A , using the LD LT factorization returned by F07JDF (DPTTRF).

2 Specification

SUBROUTINE F07JGF ( N, D, E, ANORM, RCOND, WORK, INFO)
INTEGER | N, INFO
REAL (KIND=nag_wp) | D(*), E(*), ANORM, RCOND, WORK(N)
The routine may be called by its LAPACK name dptcon.

3 Description

F07JGF (DPTCON) should be preceded by a call to F07JDF (DPTTRF), which computes a modified Cholesky factorization of the matrix A as
A=LD LT ,
where L is a unit lower bidiagonal matrix and D is a diagonal matrix, with positive diagonal elements. F07JGF (DPTCON) then utilizes the factorization to compute A-1 1 by a direct method, from which the reciprocal of the condition number of A , 1/κ A is computed as
1/κ 1 A=1 / A 1 A-1 1 .
1/κ A is returned, rather than κ A , since when A is singular κ A is infinite.

4 References

Higham N J (2002) Accuracy and Stability of Numerical Algorithms (2nd Edition) SIAM, Philadelphia

5 Arguments

1:   N – INTEGERInput
On entry: n, the order of the matrix A.
Constraint: N≥0.
2:   D* – REAL (KIND=nag_wp) arrayInput
Note: the dimension of the array D must be at least max 1,N.
On entry: must contain the n diagonal elements of the diagonal matrix D from the LD LT factorization of A.
3:   E* – REAL (KIND=nag_wp) arrayInput
Note: the dimension of the array E must be at least max 1,N-1.
On entry: must contain the n-1 subdiagonal elements of the unit lower bidiagonal matrix L. (E can also be regarded as the superdiagonal of the unit upper bidiagonal matrix U from the UT DU factorization of A.)
4:   ANORM – REAL (KIND=nag_wp)Input
On entry: the 1-norm of the original matrix A, which may be computed by calling F06RPF with its argument NORM='1'. ANORM must be computed either before calling F07JDF (DPTTRF) or else from a copy of the original matrix A.
Constraint: ANORM≥0.0.
5:   RCOND – REAL (KIND=nag_wp)Output
On exit: the reciprocal condition number, 1/κ 1 A=1/A 1A-1 1.
6:   WORK N – REAL (KIND=nag_wp) arrayWorkspace
7:   INFO – INTEGEROutput
On exit: INFO=0 unless the routine detects an error (see Section 6).

6 Error Indicators and Warnings

INFO<0
If INFO=-i, argument i had an illegal value. An explanatory message is output, and execution of the program is terminated.

7 Accuracy

The computed condition number will be the exact condition number for a closely neighbouring matrix.

8 Parallelism and Performance

F07JGF (DPTCON) is not threaded in any implementation.

9 Further Comments

The condition number estimation requires O n floating-point operations.
See Section 15.6 of Higham (2002) for further details on computing the condition number of tridiagonal matrices.
The complex analogue of this routine is F07JUF (ZPTCON).

10 Example

This example computes the condition number of the symmetric positive definite tridiagonal matrix A given by
A = 4.0 -2.0 0 0 0 -2.0 10.0 -6.0 0 0 0 -6.0 29.0 15.0 0 0 0 15.0 25.0 8.0 0 0 0 8.0 5.0 .

10.1 Program Text

Program Text (f07jgfe.f90)

10.2 Program Data

Program Data (f07jgfe.d)

10.3 Program Results

Program Results (f07jgfe.r)

F07 Chapter Contents
F07 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F07JHF (DPTRFS) : NAG Library, Mark 26

F07 Chapter Contents
F07 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F07JHF (DPTRFS)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F07JHF (DPTRFS) computes error bounds and refines the solution to a real system of linear equations AX=B , where A is an n by n symmetric positive definite tridiagonal matrix and X and B are n by r matrices, using the modified Cholesky factorization returned by F07JDF (DPTTRF) and an initial solution returned by F07JEF (DPTTRS). Iterative refinement is used to reduce the backward error as much as possible.

2 Specification

SUBROUTINE F07JHF ( N, NRHS, D, E, DF, EF, B, LDB, X, LDX, FERR, BERR, WORK, INFO)
INTEGER | N, NRHS, LDB, LDX, INFO
REAL (KIND=nag_wp) | D(*), E(*), DF(*), EF(*), B(LDB,*), X(LDX,*), FERR(NRHS), BERR(NRHS), WORK(2*N)
The routine may be called by its LAPACK name dptrfs.

3 Description

F07JHF (DPTRFS) should normally be preceded by calls to F07JDF (DPTTRF) and F07JEF (DPTTRS). F07JDF (DPTTRF) computes a modified Cholesky factorization of the matrix A as
A=LD LT ,
where L is a unit lower bidiagonal matrix and D is a diagonal matrix, with positive diagonal elements. F07JEF (DPTTRS) then utilizes the factorization to compute a solution, X^ , to the required equations. Letting x^ denote a column of X^ , F07JHF (DPTRFS) computes a component-wise backward error, β , the smallest relative perturbation in each element of A and b such that x^ is the exact solution of a perturbed system
A+E x^ = b + f , with  e ij ≤ β a ij , and  fj ≤ β bj .
The routine also estimates a bound for the component-wise forward error in the computed solution defined by max xi - xi^ / max xi^ , where x is the corresponding column of the exact solution, X .
Note that the modified Cholesky factorization of A can also be expressed as
A=UT DU ,
where U is unit upper bidiagonal.

4 References

Anderson E, Bai Z, Bischof C, Blackford S, Demmel J, Dongarra J J, Du Croz J J, Greenbaum A, Hammarling S, McKenney A and Sorensen D (1999) LAPACK Users' Guide (3rd Edition) SIAM, Philadelphia http://www.netlib.org/lapack/lug

5 Arguments

1:   N – INTEGERInput
On entry: n, the order of the matrix A.
Constraint: N≥0.
2:   NRHS – INTEGERInput
On entry: r, the number of right-hand sides, i.e., the number of columns of the matrix B.
Constraint: NRHS≥0.
3:   D* – REAL (KIND=nag_wp) arrayInput
Note: the dimension of the array D must be at least max 1,N.
On entry: must contain the n diagonal elements of the matrix of A.
4:   E* – REAL (KIND=nag_wp) arrayInput
Note: the dimension of the array E must be at least max 1,N-1.
On entry: must contain the n-1 subdiagonal elements of the matrix A.
5:   DF* – REAL (KIND=nag_wp) arrayInput
Note: the dimension of the array DF must be at least max 1,N.
On entry: must contain the n diagonal elements of the diagonal matrix D from the LD LT factorization of A.
6:   EF* – REAL (KIND=nag_wp) arrayInput
Note: the dimension of the array EF must be at least max 1,N.
On entry: must contain the n-1 subdiagonal elements of the unit bidiagonal matrix L from the LD LT factorization of A.
7:   B LDB* – REAL (KIND=nag_wp) arrayInput
Note: the second dimension of the array B must be at least max 1,NRHS.
On entry: the n by r matrix of right-hand sides B.
8:   LDB – INTEGERInput
On entry: the first dimension of the array B as declared in the (sub)program from which F07JHF (DPTRFS) is called.
Constraint: LDB≥max 1,N.
9:   X LDX* – REAL (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array X must be at least max 1,NRHS.
On entry: the n by r initial solution matrix X.
On exit: the n by r refined solution matrix X.
10:   LDX – INTEGERInput
On entry: the first dimension of the array X as declared in the (sub)program from which F07JHF (DPTRFS) is called.
Constraint: LDX≥max 1,N.
11:   FERR NRHS – REAL (KIND=nag_wp) arrayOutput
On exit: estimate of the forward error bound for each computed solution vector, such that x^j-xj∞/x^j∞≤FERR j, where x^j is the jth column of the computed solution returned in the array X and xj is the corresponding column of the exact solution X. The estimate is almost always a slight overestimate of the true error.
12:   BERR NRHS – REAL (KIND=nag_wp) arrayOutput
On exit: estimate of the component-wise relative backward error of each computed solution vector x^j (i.e., the smallest relative change in any element of A or B that makes x^j an exact solution).
13:   WORK 2×N – REAL (KIND=nag_wp) arrayWorkspace
14:   INFO – INTEGEROutput
On exit: INFO=0 unless the routine detects an error (see Section 6).

6 Error Indicators and Warnings

INFO<0
If INFO=-i, argument i had an illegal value. An explanatory message is output, and execution of the program is terminated.

7 Accuracy

The computed solution for a single right-hand side, x^ , satisfies an equation of the form
A+E x^=b ,
where
E∞=O ε A∞
and ε is the machine precision. An approximate error bound for the computed solution is given by
x^ - x ∞ x∞ ≤ κ A E∞ A∞ ,
where κ A=A-1∞ A∞ , the condition number of A with respect to the solution of the linear equations. See Section 4.4 of Anderson et al. (1999) for further details.
Routine F07JGF (DPTCON) can be used to compute the condition number of A .

8 Parallelism and Performance

F07JHF (DPTRFS) is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
F07JHF (DPTRFS) makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The total number of floating-point operations required to solve the equations AX=B is proportional to nr . At most five steps of iterative refinement are performed, but usually only one or two steps are required.
The complex analogue of this routine is F07JVF (ZPTRFS).

10 Example

This example solves the equations
AX=B ,
where A is the symmetric positive definite tridiagonal matrix
A = 4.0 -2.0 0 0 0 -2.0 10.0 -6.0 0 0 0 -6.0 29.0 15.0 0 0 0 15.0 25.0 8.0 0 0 0 8.0 5.0   and   B = 6.0 10.0 9.0 4.0 2.0 9.0 14.0 65.0 7.0 23.0 .
Estimates for the backward errors and forward errors are also output.

10.1 Program Text

Program Text (f07jhfe.f90)

10.2 Program Data

Program Data (f07jhfe.d)

10.3 Program Results

Program Results (f07jhfe.r)

F07 Chapter Contents
F07 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F07JNF (ZPTSV) : NAG Library, Mark 26

F07 Chapter Contents
F07 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F07JNF (ZPTSV)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F07JNF (ZPTSV) computes the solution to a complex system of linear equations
AX=B ,
where A is an n by n Hermitian positive definite tridiagonal matrix, and X and B are n by r matrices.

2 Specification

SUBROUTINE F07JNF ( N, NRHS, D, E, B, LDB, INFO)
INTEGER | N, NRHS, LDB, INFO
REAL (KIND=nag_wp) | D(*)
COMPLEX (KIND=nag_wp) | E(*), B(LDB,*)
The routine may be called by its LAPACK name zptsv.

3 Description

F07JNF (ZPTSV) factors A as A=LD LH. The factored form of A is then used to solve the system of equations.

4 References

Anderson E, Bai Z, Bischof C, Blackford S, Demmel J, Dongarra J J, Du Croz J J, Greenbaum A, Hammarling S, McKenney A and Sorensen D (1999) LAPACK Users' Guide (3rd Edition) SIAM, Philadelphia http://www.netlib.org/lapack/lug
Golub G H and Van Loan C F (1996) Matrix Computations (3rd Edition) Johns Hopkins University Press, Baltimore

5 Arguments

1:   N – INTEGERInput
On entry: n, the order of the matrix A.
Constraint: N≥0.
2:   NRHS – INTEGERInput
On entry: r, the number of right-hand sides, i.e., the number of columns of the matrix B.
Constraint: NRHS≥0.
3:   D* – REAL (KIND=nag_wp) arrayInput/Output
Note: the dimension of the array D must be at least max 1,N.
On entry: the n diagonal elements of the tridiagonal matrix A.
On exit: the n diagonal elements of the diagonal matrix D from the factorization A=LD LH.
4:   E* – COMPLEX (KIND=nag_wp) arrayInput/Output
Note: the dimension of the array E must be at least max 1,N-1.
On entry: the n-1 subdiagonal elements of the tridiagonal matrix A.
On exit: the n-1 subdiagonal elements of the unit bidiagonal factor L from the LD LH factorization of A. (E can also be regarded as the superdiagonal of the unit bidiagonal factor U from the UH DU factorization of A.)
5:   B LDB* – COMPLEX (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array B must be at least max 1,NRHS.
On entry: the n by r right-hand side matrix B.
On exit: if INFO=0, the n by r solution matrix X.
6:   LDB – INTEGERInput
On entry: the first dimension of the array B as declared in the (sub)program from which F07JNF (ZPTSV) is called.
Constraint: LDB≥max 1,N.
7:   INFO – INTEGEROutput
On exit: INFO=0 unless the routine detects an error (see Section 6).

6 Error Indicators and Warnings

INFO<0
If INFO=-i, argument i had an illegal value. An explanatory message is output, and execution of the program is terminated.
INFO>0
The leading minor of order value is not positive definite, and the solution has not been computed. The factorization has not been completed unless N=value.

7 Accuracy

The computed solution for a single right-hand side, x^ , satisfies an equation of the form
A+E x^=b ,
where
E 1 = O ε A 1
and ε is the machine precision. An approximate error bound for the computed solution is given by
x^-x 1 x 1 ≤ κ A E 1 A 1 ,
where κ A = A-1 1 A 1 , the condition number of A with respect to the solution of the linear equations. See Section 4.4 of Anderson et al. (1999) for further details.
F07JPF (ZPTSVX) is a comprehensive LAPACK driver that returns forward and backward error bounds and an estimate of the condition number. Alternatively, F04CGF solves Ax=b and returns a forward error bound and condition estimate. F04CGF calls F07JNF (ZPTSV) to solve the equations.

8 Parallelism and Performance

F07JNF (ZPTSV) makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The number of floating-point operations required for the factorization of A is proportional to n , and the number of floating-point operations required for the solution of the equations is proportional to nr , where r is the number of right-hand sides.
The real analogue of this routine is F07JAF (DPTSV).

10 Example

This example solves the equations
Ax=b ,
where A is the Hermitian positive definite tridiagonal matrix
A = 16.0 i+00.0 16.0-16.0 i 0.0i+0.0 0.0i+0.0 16.0+16.0 i 41.0 i+00.0 18.0+9.0 i 0.0i+0.0 0.0i+00.0 18.0-0 9.0 i 46.0 i+0.0 1.0+4.0 i 0.0i+00.0 0.0i+00.0 1.0-4.0 i 21.0 i+0.0
and
b = 64.0+16.0 i 93.0+62.0 i 78.0-80.0 i 14.0-27.0 i .
Details of the LD LH factorization of A are also output.

10.1 Program Text

Program Text (f07jnfe.f90)

10.2 Program Data

Program Data (f07jnfe.d)

10.3 Program Results

Program Results (f07jnfe.r)

F07 Chapter Contents
F07 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F07JPF (ZPTSVX) : NAG Library, Mark 26

F07 Chapter Contents
F07 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F07JPF (ZPTSVX)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F07JPF (ZPTSVX) uses the factorization
A=LD LH
to compute the solution to a complex system of linear equations
AX=B ,
where A is an n by n Hermitian positive definite tridiagonal matrix and X and B are n by r matrices. Error bounds on the solution and a condition estimate are also provided.

2 Specification

SUBROUTINE F07JPF ( FACT, N, NRHS, D, E, DF, EF, B, LDB, X, LDX, RCOND, FERR, BERR, WORK, RWORK, INFO)
INTEGER | N, NRHS, LDB, LDX, INFO
REAL (KIND=nag_wp) | D(*), DF(*), RCOND, FERR(NRHS), BERR(NRHS), RWORK(N)
COMPLEX (KIND=nag_wp) | E(*), EF(*), B(LDB,*), X(LDX,*), WORK(N)
CHARACTER(1) | FACT
The routine may be called by its LAPACK name zptsvx.

3 Description

F07JPF (ZPTSVX) performs the following steps:
1. | If FACT='N', the matrix A is factorized as A=LD LH, where L is a unit lower bidiagonal matrix and D is diagonal. The factorization can also be regarded as having the form A=UH DU.
2. | If the leading i by i principal minor is not positive definite, then the routine returns with INFO=i. Otherwise, the factored form of A is used to estimate the condition number of the matrix A. If the reciprocal of the condition number is less than machine precision, INFO=N+1 is returned as a warning, but the routine still goes on to solve for X and compute error bounds as described below.
3. | The system of equations is solved for X using the factored form of A.
4. | Iterative refinement is applied to improve the computed solution matrix and to calculate error bounds and backward error estimates for it.

4 References

Anderson E, Bai Z, Bischof C, Blackford S, Demmel J, Dongarra J J, Du Croz J J, Greenbaum A, Hammarling S, McKenney A and Sorensen D (1999) LAPACK Users' Guide (3rd Edition) SIAM, Philadelphia http://www.netlib.org/lapack/lug
Golub G H and Van Loan C F (1996) Matrix Computations (3rd Edition) Johns Hopkins University Press, Baltimore
Higham N J (2002) Accuracy and Stability of Numerical Algorithms (2nd Edition) SIAM, Philadelphia

5 Arguments

1:   FACT – CHARACTER(1)Input
On entry: specifies whether or not the factorized form of the matrix A has been supplied.
FACT='F'
DF and EF contain the factorized form of the matrix A. DF and EF will not be modified.
FACT='N'
The matrix A will be copied to DF and EF and factorized.
Constraint: FACT='F' or 'N'.
2:   N – INTEGERInput
On entry: n, the order of the matrix A.
Constraint: N≥0.
3:   NRHS – INTEGERInput
On entry: r, the number of right-hand sides, i.e., the number of columns of the matrix B.
Constraint: NRHS≥0.
4:   D* – REAL (KIND=nag_wp) arrayInput
Note: the dimension of the array D must be at least max 1,N.
On entry: the n diagonal elements of the tridiagonal matrix A.
5:   E* – COMPLEX (KIND=nag_wp) arrayInput
Note: the dimension of the array E must be at least max 1,N-1.
On entry: the n-1 subdiagonal elements of the tridiagonal matrix A.
6:   DF* – REAL (KIND=nag_wp) arrayInput/Output
Note: the dimension of the array DF must be at least max 1,N.
On entry: if FACT='F', DF must contain the n diagonal elements of the diagonal matrix D from the LD LH factorization of A.
On exit: if FACT='N', DF contains the n diagonal elements of the diagonal matrix D from the LD LH factorization of A.
7:   EF* – COMPLEX (KIND=nag_wp) arrayInput/Output
Note: the dimension of the array EF must be at least max 1,N-1.
On entry: if FACT='F', EF must contain the n-1 subdiagonal elements of the unit bidiagonal factor L from the LD LH factorization of A.
On exit: if FACT='N', EF contains the n-1 subdiagonal elements of the unit bidiagonal factor L from the LD LH factorization of A.
8:   B LDB* – COMPLEX (KIND=nag_wp) arrayInput
Note: the second dimension of the array B must be at least max 1,NRHS.
On entry: the n by r right-hand side matrix B.
9:   LDB – INTEGERInput
On entry: the first dimension of the array B as declared in the (sub)program from which F07JPF (ZPTSVX) is called.
Constraint: LDB≥max 1,N.
10:   X LDX* – COMPLEX (KIND=nag_wp) arrayOutput
Note: the second dimension of the array X must be at least max 1,NRHS.
On exit: if INFO=0 or N+1, the n by r solution matrix X.
11:   LDX – INTEGERInput
On entry: the first dimension of the array X as declared in the (sub)program from which F07JPF (ZPTSVX) is called.
Constraint: LDX≥max 1,N.
12:   RCOND – REAL (KIND=nag_wp)Output
On exit: the reciprocal condition number of the matrix A. If RCOND is less than the machine precision (in particular, if RCOND=0.0), the matrix is singular to working precision. This condition is indicated by a return code of INFO=N+1.
13:   FERR NRHS – REAL (KIND=nag_wp) arrayOutput
On exit: the forward error bound for each solution vector x^j (the jth column of the solution matrix X). If xj is the true solution corresponding to x^j, FERR j is an estimated upper bound for the magnitude of the largest element in (x^j-xj) divided by the magnitude of the largest element in x^j.
14:   BERR NRHS – REAL (KIND=nag_wp) arrayOutput
On exit: the component-wise relative backward error of each solution vector x^j (i.e., the smallest relative change in any element of A or B that makes x^j an exact solution).
15:   WORK N – COMPLEX (KIND=nag_wp) arrayWorkspace
16:   RWORK N – REAL (KIND=nag_wp) arrayWorkspace
17:   INFO – INTEGEROutput
On exit: INFO=0 unless the routine detects an error (see Section 6).

6 Error Indicators and Warnings

INFO<0
If INFO=-i, argument i had an illegal value. An explanatory message is output, and execution of the program is terminated.
INFO>0 and INFO≤N
The leading minor of order value of A is not positive definite, so the factorization could not be completed, and the solution has not been computed. RCOND=0.0 is returned.
INFO=N+1
D is nonsingular, but RCOND is less than machine precision, meaning that the matrix is singular to working precision. Nevertheless, the solution and error bounds are computed because there are a number of situations where the computed solution can be more accurate than the value of RCOND would suggest.

7 Accuracy

For each right-hand side vector b, the computed solution x^ is the exact solution of a perturbed system of equations A+E x^=b, where
E ≤ c n ε RT R , where ​ R = D 12 U ,
c n is a modest linear function of n, and ε is the machine precision. See Section 10.1 of Higham (2002) for further details.
If x is the true solution, then the computed solution x^ satisfies a forward error bound of the form
x-x^∞ x^∞ ≤ wc cond A,x^,b
where cond A,x^,b = A-1 A x^ + b ∞/ x^∞ ≤ cond A = A-1 A ∞≤κ∞ A. If x^ is the j th column of X , then wc is returned in BERR j and a bound on x - x^ ∞ / x^ ∞ is returned in FERR j . See Section 4.4 of Anderson et al. (1999) for further details.

8 Parallelism and Performance

F07JPF (ZPTSVX) is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
F07JPF (ZPTSVX) makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The number of floating-point operations required for the factorization, and for the estimation of the condition number of A is proportional to n . The number of floating-point operations required for the solution of the equations, and for the estimation of the forward and backward error is proportional to nr , where r is the number of right-hand sides.
The condition estimation is based upon Equation (15.11) of Higham (2002). For further details of the error estimation, see Section 4.4 of Anderson et al. (1999).
The real analogue of this routine is F07JBF (DPTSVX).

10 Example

This example solves the equations
AX=B ,
where A is the Hermitian positive definite tridiagonal matrix
A = 16.0 i+00.0 16.0-16.0 i 0.0i+0.0 0.0i+0.0 16.0+16.0 i 41.0 i+00.0 18.0+9.0 i 0.0i+0.0 0.0i+00.0 18.0-0 9.0 i 46.0 i+0.0 1.0+4.0 i 0.0i+00.0 0.0i+00.0 1.0-4.0 i 21.0 i+0.0
and
B = 64.0+16.0 i -16.0-32.0 i 93.0+62.0 i 61.0-66.0 i 78.0-80.0 i 71.0-74.0 i 14.0-27.0 i 35.0+15.0 i .
Error estimates for the solutions and an estimate of the reciprocal of the condition number of A are also output.

10.1 Program Text

Program Text (f07jpfe.f90)

10.2 Program Data

Program Data (f07jpfe.d)

10.3 Program Results

Program Results (f07jpfe.r)

F07 Chapter Contents
F07 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F07JRF (ZPTTRF) : NAG Library, Mark 26

F07 Chapter Contents
F07 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F07JRF (ZPTTRF)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F07JRF (ZPTTRF) computes the modified Cholesky factorization of a complex n by n Hermitian positive definite tridiagonal matrix A .

2 Specification

SUBROUTINE F07JRF ( N, D, E, INFO)
INTEGER | N, INFO
REAL (KIND=nag_wp) | D(*)
COMPLEX (KIND=nag_wp) | E(*)
The routine may be called by its LAPACK name zpttrf.

3 Description

F07JRF (ZPTTRF) factorizes the matrix A as
A=LD LH ,
where L is a unit lower bidiagonal matrix and D is a diagonal matrix with positive diagonal elements. The factorization may also be regarded as having the form UH DU , where U is a unit upper bidiagonal matrix.

4 References

None.

5 Arguments

1:   N – INTEGERInput
On entry: n, the order of the matrix A.
Constraint: N≥0.
2:   D* – REAL (KIND=nag_wp) arrayInput/Output
Note: the dimension of the array D must be at least max 1,N.
On entry: must contain the n diagonal elements of the matrix A.
On exit: is overwritten by the n diagonal elements of the diagonal matrix D from the LD LH factorization of A.
3:   E* – COMPLEX (KIND=nag_wp) arrayInput/Output
Note: the dimension of the array E must be at least max 1,N-1.
On entry: must contain the n-1 subdiagonal elements of the matrix A.
On exit: is overwritten by the n-1 subdiagonal elements of the lower bidiagonal matrix L. (E can also be regarded as containing the n-1 superdiagonal elements of the upper bidiagonal matrix U.)
4:   INFO – INTEGEROutput
On exit: INFO=0 unless the routine detects an error (see Section 6).

6 Error Indicators and Warnings

INFO<0
If INFO=-i, argument i had an illegal value. An explanatory message is output, and execution of the program is terminated.
INFO>0 and INFO<N
The leading minor of order value is not positive definite, the factorization could not be completed.
INFO>0 and INFO=N
The leading minor of order n is not positive definite, the factorization was completed, but D N≤0.

7 Accuracy

The computed factorization satisfies an equation of the form
A+E=LD LH ,
where
E∞=O ε A∞
and ε is the machine precision.
Following the use of this routine, F07JSF (ZPTTRS) can be used to solve systems of equations AX=B , and F07JUF (ZPTCON) can be used to estimate the condition number of A .

8 Parallelism and Performance

F07JRF (ZPTTRF) is not threaded in any implementation.

9 Further Comments

The total number of floating-point operations required to factorize the matrix A is proportional to n .
The real analogue of this routine is F07JDF (DPTTRF).

10 Example

This example factorizes the Hermitian positive definite tridiagonal matrix A given by
A = 16.0 i+00.0 16.0-16.0 i 0.0i+0.0 0.0i+0.0 16.0+16.0 i 41.0 i+00.0 18.0+9.0 i 0.0i+0.0 0.0i+00.0 18.0-0 9.0 i 46.0 i+0.0 1.0+4.0 i 0.0i+00.0 0.0i+00.0 1.0-4.0 i 21.0 i+0.0 .

10.1 Program Text

Program Text (f07jrfe.f90)

10.2 Program Data

Program Data (f07jrfe.d)

10.3 Program Results

Program Results (f07jrfe.r)

F07 Chapter Contents
F07 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F07JSF (ZPTTRS) : NAG Library, Mark 26

F07 Chapter Contents
F07 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F07JSF (ZPTTRS)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F07JSF (ZPTTRS) computes the solution to a complex system of linear equations AX=B , where A is an n by n Hermitian positive definite tridiagonal matrix and X and B are n by r matrices, using the LD LH factorization returned by F07JRF (ZPTTRF).

2 Specification

SUBROUTINE F07JSF ( UPLO, N, NRHS, D, E, B, LDB, INFO)
INTEGER | N, NRHS, LDB, INFO
REAL (KIND=nag_wp) | D(*)
COMPLEX (KIND=nag_wp) | E(*), B(LDB,*)
CHARACTER(1) | UPLO
The routine may be called by its LAPACK name zpttrs.

3 Description

F07JSF (ZPTTRS) should be preceded by a call to F07JRF (ZPTTRF), which computes a modified Cholesky factorization of the matrix A as
A=LD LH ,
where L is a unit lower bidiagonal matrix and D is a diagonal matrix, with positive diagonal elements. F07JSF (ZPTTRS) then utilizes the factorization to solve the required equations. Note that the factorization may also be regarded as having the form UH DU , where U is a unit upper bidiagonal matrix.

4 References

Anderson E, Bai Z, Bischof C, Blackford S, Demmel J, Dongarra J J, Du Croz J J, Greenbaum A, Hammarling S, McKenney A and Sorensen D (1999) LAPACK Users' Guide (3rd Edition) SIAM, Philadelphia http://www.netlib.org/lapack/lug

5 Arguments

1:   UPLO – CHARACTER(1)Input
On entry: specifies the form of the factorization as follows:
UPLO='U'
A=UH DU.
UPLO='L'
A=LD LH.
Constraint: UPLO='U' or 'L'.
2:   N – INTEGERInput
On entry: n, the order of the matrix A.
Constraint: N≥0.
3:   NRHS – INTEGERInput
On entry: r, the number of right-hand sides, i.e., the number of columns of the matrix B.
Constraint: NRHS≥0.
4:   D* – REAL (KIND=nag_wp) arrayInput
Note: the dimension of the array D must be at least max 1,N.
On entry: must contain the n diagonal elements of the diagonal matrix D from the LD LH or UH DU factorization of A.
5:   E* – COMPLEX (KIND=nag_wp) arrayInput
Note: the dimension of the array E must be at least max 1,N-1.
On entry: if UPLO='U', E must contain the n-1 superdiagonal elements of the unit upper bidiagonal matrix U from the UH DU factorization of A.
If UPLO='L', E must contain the n-1 subdiagonal elements of the unit lower bidiagonal matrix L from the LD LH factorization of A.
6:   B LDB* – COMPLEX (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array B must be at least max 1,NRHS.
On entry: the n by r matrix of right-hand sides B.
On exit: the n by r solution matrix X.
7:   LDB – INTEGERInput
On entry: the first dimension of the array B as declared in the (sub)program from which F07JSF (ZPTTRS) is called.
Constraint: LDB≥max 1,N.
8:   INFO – INTEGEROutput
On exit: INFO=0 unless the routine detects an error (see Section 6).

6 Error Indicators and Warnings

INFO<0
If INFO=-i, argument i had an illegal value. An explanatory message is output, and execution of the program is terminated.

7 Accuracy

The computed solution for a single right-hand side, x^ , satisfies an equation of the form
A+E x^=b ,
where
E 1 =O ε A 1
and ε is the machine precision. An approximate error bound for the computed solution is given by
x^ - x 1 x 1 ≤ κ A E 1 A 1 ,
where κ A = A-1 1 A 1 , the condition number of A with respect to the solution of the linear equations. See Section 4.4 of Anderson et al. (1999) for further details.
Following the use of this routine F07JUF (ZPTCON) can be used to estimate the condition number of A and F07JVF (ZPTRFS) can be used to obtain approximate error bounds.

8 Parallelism and Performance

F07JSF (ZPTTRS) makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The total number of floating-point operations required to solve the equations AX=B is proportional to nr .
The real analogue of this routine is F07JEF (DPTTRS).

10 Example

This example solves the equations
AX=B ,
where A is the Hermitian positive definite tridiagonal matrix
A = 16.0 i+00.0 16.0-16.0 i 0.0i+0.0 0.0i+0.0 16.0+16.0 i 41.0 i+00.0 18.0+9.0 i 0.0 i+0.0 0.0i+00.0 18.0-0 9.0 i 46.0 i+0.0 1.0+4.0 i 0.0i+00.0 0.0i+00.0 1.0-4.0 i 21.0 i+0.0
and
B = 64.0+16.0 i -16.0-32.0 i 93.0+62.0 i 61.0-66.0 i 78.0-80.0 i 71.0-74.0 i 14.0-27.0 i 35.0+15.0 i .

10.1 Program Text

Program Text (f07jsfe.f90)

10.2 Program Data

Program Data (f07jsfe.d)

10.3 Program Results

Program Results (f07jsfe.r)

F07 Chapter Contents
F07 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F07JUF (ZPTCON) : NAG Library, Mark 26

F07 Chapter Contents
F07 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F07JUF (ZPTCON)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F07JUF (ZPTCON) computes the reciprocal condition number of a complex n by n Hermitian positive definite tridiagonal matrix A , using the LD LH factorization returned by F07JRF (ZPTTRF).

2 Specification

SUBROUTINE F07JUF ( N, D, E, ANORM, RCOND, RWORK, INFO)
INTEGER | N, INFO
REAL (KIND=nag_wp) | D(*), ANORM, RCOND, RWORK(N)
COMPLEX (KIND=nag_wp) | E(*)
The routine may be called by its LAPACK name zptcon.

3 Description

F07JUF (ZPTCON) should be preceded by a call to F07JRF (ZPTTRF), which computes a modified Cholesky factorization of the matrix A as
A=LD LH ,
where L is a unit lower bidiagonal matrix and D is a diagonal matrix, with positive diagonal elements. F07JUF (ZPTCON) then utilizes the factorization to compute A-1 1 by a direct method, from which the reciprocal of the condition number of A , 1/κ A is computed as
1/κ 1 A=1 / A 1 A-1 1 .
1/κ A is returned, rather than κ A , since when A is singular κ A is infinite.

4 References

Higham N J (2002) Accuracy and Stability of Numerical Algorithms (2nd Edition) SIAM, Philadelphia

5 Arguments

1:   N – INTEGERInput
On entry: n, the order of the matrix A.
Constraint: N≥0.
2:   D* – REAL (KIND=nag_wp) arrayInput
Note: the dimension of the array D must be at least max 1,N.
On entry: must contain the n diagonal elements of the diagonal matrix D from the LD LH factorization of A.
3:   E* – COMPLEX (KIND=nag_wp) arrayInput
Note: the dimension of the array E must be at least max 1,N-1.
On entry: must contain the n-1 subdiagonal elements of the unit lower bidiagonal matrix L. (E can also be regarded as the superdiagonal of the unit upper bidiagonal matrix U from the UH DU factorization of A.)
4:   ANORM – REAL (KIND=nag_wp)Input
On entry: the 1-norm of the original matrix A, which may be computed by calling F06UPF with its argument NORM='1'. ANORM must be computed either before calling F07JRF (ZPTTRF) or else from a copy of the original matrix A.
Constraint: ANORM≥0.0.
5:   RCOND – REAL (KIND=nag_wp)Output
On exit: the reciprocal condition number, 1/κ 1 A=1/A 1A-1 1.
6:   RWORK N – REAL (KIND=nag_wp) arrayWorkspace
7:   INFO – INTEGEROutput
On exit: INFO=0 unless the routine detects an error (see Section 6).

6 Error Indicators and Warnings

INFO<0
If INFO=-i, argument i had an illegal value. An explanatory message is output, and execution of the program is terminated.

7 Accuracy

The computed condition number will be the exact condition number for a closely neighbouring matrix.

8 Parallelism and Performance

F07JUF (ZPTCON) is not threaded in any implementation.

9 Further Comments

The condition number estimation requires O n floating-point operations.
See Section 15.6 of Higham (2002) for further details on computing the condition number of tridiagonal matrices.
The real analogue of this routine is F07JGF (DPTCON).

10 Example

This example computes the condition number of the Hermitian positive definite tridiagonal matrix A given by
A = 16.0 i+00.0 16.0-16.0 i 0.0i+0.0 0.0i+0.0 16.0+16.0 i 41.0 i+00.0 18.0+9.0 i 0.0i+0.0 0.0i+00.0 18.0-0 9.0 i 46.0 i+0.0 1.0+4.0 i 0.0i+00.0 0.0i+00.0 1.0-4.0 i 21.0 i+0.0 .

10.1 Program Text

Program Text (f07jufe.f90)

10.2 Program Data

Program Data (f07jufe.d)

10.3 Program Results

Program Results (f07jufe.r)

F07 Chapter Contents
F07 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F07JVF (ZPTRFS) : NAG Library, Mark 26

F07 Chapter Contents
F07 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F07JVF (ZPTRFS)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F07JVF (ZPTRFS) computes error bounds and refines the solution to a complex system of linear equations AX=B , where A is an n by n Hermitian positive definite tridiagonal matrix and X and B are n by r matrices, using the modified Cholesky factorization returned by F07JRF (ZPTTRF) and an initial solution returned by F07JSF (ZPTTRS). Iterative refinement is used to reduce the backward error as much as possible.

2 Specification

SUBROUTINE F07JVF ( UPLO, N, NRHS, D, E, DF, EF, B, LDB, X, LDX, FERR, BERR, WORK, RWORK, INFO)
INTEGER | N, NRHS, LDB, LDX, INFO
REAL (KIND=nag_wp) | D(*), DF(*), FERR(NRHS), BERR(NRHS), RWORK(N)
COMPLEX (KIND=nag_wp) | E(*), EF(*), B(LDB,*), X(LDX,*), WORK(N)
CHARACTER(1) | UPLO
The routine may be called by its LAPACK name zptrfs.

3 Description

F07JVF (ZPTRFS) should normally be preceded by calls to F07JRF (ZPTTRF) and F07JSF (ZPTTRS). F07JRF (ZPTTRF) computes a modified Cholesky factorization of the matrix A as
A=LD LH ,
where L is a unit lower bidiagonal matrix and D is a diagonal matrix, with positive diagonal elements. F07JSF (ZPTTRS) then utilizes the factorization to compute a solution, X^ , to the required equations. Letting x^ denote a column of X^ , F07JVF (ZPTRFS) computes a component-wise backward error, β , the smallest relative perturbation in each element of A and b such that x^ is the exact solution of a perturbed system
A+E x^ = b + f , with  e ij ≤ β a ij , and  fj ≤ β bj .
The routine also estimates a bound for the component-wise forward error in the computed solution defined by max xi - xi^ / max xi^ , where x is the corresponding column of the exact solution, X .
Note that the modified Cholesky factorization of A can also be expressed as
A=UH DU ,
where U is unit upper bidiagonal.

4 References

Anderson E, Bai Z, Bischof C, Blackford S, Demmel J, Dongarra J J, Du Croz J J, Greenbaum A, Hammarling S, McKenney A and Sorensen D (1999) LAPACK Users' Guide (3rd Edition) SIAM, Philadelphia http://www.netlib.org/lapack/lug

5 Arguments

1:   UPLO – CHARACTER(1)Input
On entry: specifies the form of the factorization as follows:
UPLO='U'
A=UH DU.
UPLO='L'
A=LD LH.
Constraint: UPLO='U' or 'L'.
2:   N – INTEGERInput
On entry: n, the order of the matrix A.
Constraint: N≥0.
3:   NRHS – INTEGERInput
On entry: r, the number of right-hand sides, i.e., the number of columns of the matrix B.
Constraint: NRHS≥0.
4:   D* – REAL (KIND=nag_wp) arrayInput
Note: the dimension of the array D must be at least max 1,N.
On entry: must contain the n diagonal elements of the matrix of A.
5:   E* – COMPLEX (KIND=nag_wp) arrayInput
Note: the dimension of the array E must be at least max 1,N-1.
On entry: if UPLO='U', E must contain the n-1 superdiagonal elements of the matrix A.
If UPLO='L', E must contain the n-1 subdiagonal elements of the matrix A.
6:   DF* – REAL (KIND=nag_wp) arrayInput
Note: the dimension of the array DF must be at least max 1,N.
On entry: must contain the n diagonal elements of the diagonal matrix D from the LD LT factorization of A.
7:   EF* – COMPLEX (KIND=nag_wp) arrayInput
Note: the dimension of the array EF must be at least max 1,N-1.
On entry: if UPLO='U', EF must contain the n-1 superdiagonal elements of the unit upper bidiagonal matrix U from the UH DU factorization of A.
If UPLO='L', EF must contain the n-1 subdiagonal elements of the unit lower bidiagonal matrix L from the LD LH factorization of A.
8:   B LDB* – COMPLEX (KIND=nag_wp) arrayInput
Note: the second dimension of the array B must be at least max 1,NRHS.
On entry: the n by r matrix of right-hand sides B.
9:   LDB – INTEGERInput
On entry: the first dimension of the array B as declared in the (sub)program from which F07JVF (ZPTRFS) is called.
Constraint: LDB≥max 1,N.
10:   X LDX* – COMPLEX (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array X must be at least max 1,NRHS.
On entry: the n by r initial solution matrix X.
On exit: the n by r refined solution matrix X.
11:   LDX – INTEGERInput
On entry: the first dimension of the array X as declared in the (sub)program from which F07JVF (ZPTRFS) is called.
Constraint: LDX≥max 1,N.
12:   FERR NRHS – REAL (KIND=nag_wp) arrayOutput
On exit: estimate of the forward error bound for each computed solution vector, such that x^j-xj∞/x^j∞≤FERR j, where x^j is the jth column of the computed solution returned in the array X and xj is the corresponding column of the exact solution X. The estimate is almost always a slight overestimate of the true error.
13:   BERR NRHS – REAL (KIND=nag_wp) arrayOutput
On exit: estimate of the component-wise relative backward error of each computed solution vector x^j (i.e., the smallest relative change in any element of A or B that makes x^j an exact solution).
14:   WORK N – COMPLEX (KIND=nag_wp) arrayWorkspace
15:   RWORK N – REAL (KIND=nag_wp) arrayWorkspace
16:   INFO – INTEGEROutput
On exit: INFO=0 unless the routine detects an error (see Section 6).

6 Error Indicators and Warnings

INFO<0
If INFO=-i, argument i had an illegal value. An explanatory message is output, and execution of the program is terminated.

7 Accuracy

The computed solution for a single right-hand side, x^ , satisfies an equation of the form
A+E x^=b ,
where
E∞=O ε A∞
and ε is the machine precision. An approximate error bound for the computed solution is given by
x^ - x ∞ x∞ ≤ κ A E∞ A∞ ,
where κ A=A-1∞ A∞ , the condition number of A with respect to the solution of the linear equations. See Section 4.4 of Anderson et al. (1999) for further details.
Routine F07JUF (ZPTCON) can be used to compute the condition number of A .

8 Parallelism and Performance

F07JVF (ZPTRFS) is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
F07JVF (ZPTRFS) makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The total number of floating-point operations required to solve the equations AX=B is proportional to nr . At most five steps of iterative refinement are performed, but usually only one or two steps are required.
The real analogue of this routine is F07JHF (DPTRFS).

10 Example

This example solves the equations
AX=B ,
where A is the Hermitian positive definite tridiagonal matrix
A = 16.0 i+00.0 16.0-16.0 i 0.0i+0.0 0.0i+0.0 16.0+16.0 i 41.0 i+00.0 18.0+9.0 i 0.0i+0.0 0.0i+00.0 18.0-0 9.0 i 46.0 i+0.0 1.0+4.0 i 0.0i+00.0 0.0i+00.0 1.0-4.0 i 21.0 i+0.0
and
B = 64.0+16.0 i -16.0-32.0 i 93.0+62.0 i 61.0-66.0 i 78.0-80.0 i 71.0-74.0 i 14.0-27.0 i 35.0+15.0 i .
Estimates for the backward errors and forward errors are also output.

10.1 Program Text

Program Text (f07jvfe.f90)

10.2 Program Data

Program Data (f07jvfe.d)

10.3 Program Results

Program Results (f07jvfe.r)

F07 Chapter Contents
F07 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F07KDF (DPSTRF) : NAG Library, Mark 26

F07 Chapter Contents
F07 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F07KDF (DPSTRF)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F07KDF (DPSTRF) computes the Cholesky factorization with complete pivoting of a real symmetric positive semidefinite matrix.

2 Specification

SUBROUTINE F07KDF ( UPLO, N, A, LDA, PIV, RANK, TOL, WORK, INFO)
INTEGER | N, LDA, PIV(N), RANK, INFO
REAL (KIND=nag_wp) | A(LDA,*), TOL, WORK(2*N)
CHARACTER(1) | UPLO
The routine may be called by its LAPACK name dpstrf.

3 Description

F07KDF (DPSTRF) forms the Cholesky factorization of a real symmetric positive semidefinite matrix A either as PT AP=UT U if UPLO='U' or PT AP=L LT if UPLO='L', where P is a permutation matrix, U is an upper triangular matrix and L is lower triangular.
This algorithm does not attempt to check that A is positive semidefinite.

4 References

Higham N J (2002) Accuracy and Stability of Numerical Algorithms (2nd Edition) SIAM, Philadelphia
Lucas C (2004) LAPACK-style codes for Level 2 and 3 pivoted Cholesky factorizations LAPACK Working Note No. 161. Technical Report CS-04-522 Department of Computer Science, University of Tennessee, 107 Ayres Hall, Knoxville, TN 37996-1301, USA http://www.netlib.org/lapack/lawnspdf/lawn161.pdf

5 Arguments

1:   UPLO – CHARACTER(1)Input
On entry: specifies whether the upper or lower triangular part of A is stored and how A is to be factorized.
UPLO='U'
The upper triangular part of A is stored and A is factorized as UT U, where U is upper triangular.
UPLO='L'
The lower triangular part of A is stored and A is factorized as L LT, where L is lower triangular.
Constraint: UPLO='U' or 'L'.
2:   N – INTEGERInput
On entry: n, the order of the matrix A.
Constraint: N≥0.
3:   A LDA* – REAL (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array A must be at least max 1,N.
On entry: the n by n symmetric positive semidefinite matrix A.
  • If UPLO='U', the upper triangular part of A must be stored and the elements of the array below the diagonal are not referenced.
  • If UPLO='L', the lower triangular part of A must be stored and the elements of the array above the diagonal are not referenced.
On exit: if UPLO='U', the first RANK rows of the upper triangle of A are overwritten with the nonzero elements of the Cholesky factor U, and the remaining rows of the triangle are destroyed.
If UPLO='L', the first RANK columns of the lower triangle of A are overwritten with the nonzero elements of the Cholesky factor L, and the remaining columns of the triangle are destroyed.
4:   LDA – INTEGERInput
On entry: the first dimension of the array A as declared in the (sub)program from which F07KDF (DPSTRF) is called.
Constraint: LDA≥max 1,N.
5:   PIV N – INTEGER arrayOutput
On exit: PIV is such that the nonzero entries of P are P PIV k,k =1, for k=1,2,…,n.
6:   RANK – INTEGEROutput
On exit: the computed rank of A given by the number of steps the algorithm completed.
7:   TOL – REAL (KIND=nag_wp)Input
On entry: user defined tolerance. If TOL<0, then n×max k=1,n A kk×machine precision will be used. The algorithm terminates at the rth step if the r+1th step pivot <TOL.
8:   WORK 2*N – REAL (KIND=nag_wp) arrayWorkspace
9:   INFO – INTEGEROutput
On exit: INFO=0 unless the routine detects an error (see Section 6).

6 Error Indicators and Warnings

INFO<0
If INFO=-i, argument i had an illegal value. An explanatory message is output, and execution of the program is terminated.
INFO=1
The matrix A is not positive definite. It is either positive semidefinite with computed rank as returned in RANK and less than n, or it may be indefinite, see Section 9.

7 Accuracy

If UPLO='L' and RANK=r, the computed Cholesky factor L and permutation matrix P satisfy the following upper bound
A - PL LTPT 2 A 2 ≤ 2 r c r ε W 2 + 1 2 + O ε 2 ,
where
W = L 11 -1 L 12 ,   L = L 11 0 L 12 0 ,   L 11 ∈ ℝ r×r ,
c r is a modest linear function of r, ε is machine precision, and
W 2 ≤ 13 n-r 4 r-1 .
So there is no guarantee of stability of the algorithm for large n and r, although W 2 is generally small in practice.

8 Parallelism and Performance

F07KDF (DPSTRF) makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The total number of floating-point operations is approximately n r 2-2/3 r 3, where r is the computed rank of A.
This algorithm does not attempt to check that A is positive semidefinite, and in particular the rank detection criterion in the algorithm is based on A being positive semidefinite. If there is doubt over semidefiniteness then you should use the indefinite factorization F07MDF (DSYTRF). See Lucas (2004) for further information.
The complex analogue of this routine is F07KRF (ZPSTRF).

10 Example

This example computes the Cholesky factorization of the matrix A, where
A= 2.51 4.04 3.34 1.34 1.29 4.04 8.22 7.38 2.68 2.44 3.34 7.38 7.06 2.24 2.14 1.34 2.68 2.24 0.96 0.80 1.29 2.44 2.14 0.80 0.74 .

10.1 Program Text

Program Text (f07kdfe.f90)

10.2 Program Data

Program Data (f07kdfe.d)

10.3 Program Results

Program Results (f07kdfe.r)

F07 Chapter Contents
F07 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F07KRF (ZPSTRF) : NAG Library, Mark 26

F07 Chapter Contents
F07 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F07KRF (ZPSTRF)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F07KRF (ZPSTRF) computes the Cholesky factorization with complete pivoting of a complex Hermitian positive semidefinite matrix.

2 Specification

SUBROUTINE F07KRF ( UPLO, N, A, LDA, PIV, RANK, TOL, WORK, INFO)
INTEGER | N, LDA, PIV(N), RANK, INFO
REAL (KIND=nag_wp) | TOL, WORK(2*N)
COMPLEX (KIND=nag_wp) | A(LDA,*)
CHARACTER(1) | UPLO
The routine may be called by its LAPACK name zpstrf.

3 Description

F07KRF (ZPSTRF) forms the Cholesky factorization of a complex Hermitian positive semidefinite matrix A either as PT AP=UH U if UPLO='U' or PT AP=L LH if UPLO='L', where P is a permutation matrix, U is an upper triangular matrix and L is lower triangular.
This algorithm does not attempt to check that A is positive semidefinite.

4 References

Higham N J (2002) Accuracy and Stability of Numerical Algorithms (2nd Edition) SIAM, Philadelphia
Lucas C (2004) LAPACK-style codes for Level 2 and 3 pivoted Cholesky factorizations LAPACK Working Note No. 161. Technical Report CS-04-522 Department of Computer Science, University of Tennessee, 107 Ayres Hall, Knoxville, TN 37996-1301, USA http://www.netlib.org/lapack/lawnspdf/lawn161.pdf

5 Arguments

1:   UPLO – CHARACTER(1)Input
On entry: specifies whether the upper or lower triangular part of A is stored and how A is to be factorized.
UPLO='U'
The upper triangular part of A is stored and A is factorized as UH U, where U is upper triangular.
UPLO='L'
The lower triangular part of A is stored and A is factorized as L LH, where L is lower triangular.
Constraint: UPLO='U' or 'L'.
2:   N – INTEGERInput
On entry: n, the order of the matrix A.
Constraint: N≥0.
3:   A LDA* – COMPLEX (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array A must be at least max 1,N.
On entry: the n by n Hermitian positive semidefinite matrix A.
  • If UPLO='U', the upper triangular part of A must be stored and the elements of the array below the diagonal are not referenced.
  • If UPLO='L', the lower triangular part of A must be stored and the elements of the array above the diagonal are not referenced.
On exit: if UPLO='U', the first RANK rows of the upper triangle of A are overwritten with the nonzero elements of the Cholesky factor U, and the remaining rows of the triangle are destroyed.
If UPLO='L', the first RANK columns of the lower triangle of A are overwritten with the nonzero elements of the Cholesky factor L, and the remaining columns of the triangle are destroyed.
4:   LDA – INTEGERInput
On entry: the first dimension of the array A as declared in the (sub)program from which F07KRF (ZPSTRF) is called.
Constraint: LDA≥max 1,N.
5:   PIV N – INTEGER arrayOutput
On exit: PIV is such that the nonzero entries of P are P PIV k,k =1, for k=1,2,…,n.
6:   RANK – INTEGEROutput
On exit: the computed rank of A given by the number of steps the algorithm completed.
7:   TOL – REAL (KIND=nag_wp)Input
On entry: user defined tolerance. If TOL<0, then n×max k=1,n A kk×machine precision will be used. The algorithm terminates at the rth step if the r+1th step pivot <TOL.
8:   WORK 2*N – REAL (KIND=nag_wp) arrayWorkspace
9:   INFO – INTEGEROutput
On exit: INFO=0 unless the routine detects an error (see Section 6).

6 Error Indicators and Warnings

INFO<0
If INFO=-i, argument i had an illegal value. An explanatory message is output, and execution of the program is terminated.
INFO=1
The matrix A is not positive definite. It is either positive semidefinite with computed rank as returned in RANK and less than n, or it may be indefinite, see Section 9.

7 Accuracy

If UPLO='L' and RANK=r, the computed Cholesky factor L and permutation matrix P satisfy the following upper bound
A - PL LHPT 2 A 2 ≤ 2 r c r ε W 2 + 1 2 + O ε 2 ,
where
W = L 11 -1 L 12 ,   L = L 11 0 L 12 0 ,   L 11 ∈ ℂ r×r ,
c r is a modest linear function of r, ε is machine precision, and
W 2 ≤ 13 n-r 4 r-1 .
So there is no guarantee of stability of the algorithm for large n and r, although W 2 is generally small in practice.

8 Parallelism and Performance

F07KRF (ZPSTRF) makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The total number of real floating-point operations is approximately 4 n r 2-8/3 r 3, where r is the computed rank of A.
This algorithm does not attempt to check that A is positive semidefinite, and in particular the rank detection criterion in the algorithm is based on A being positive semidefinite. If there is doubt over semidefiniteness then you should use the indefinite factorization F07MRF (ZHETRF). See Lucas (2004) for further information.
The real analogue of this routine is F07KDF (DPSTRF).

10 Example

This example computes the Cholesky factorization of the matrix A, where
A= 12.40+0.00 i 2.39+0.00 i 5.50+0.05 i 4.47+0.00 i 11.89+0.00 i 2.39+0.00 i 1.63+0.00 i 1.04+0.10 i 1.14+0.00 i 1.81+0.00 i 5.50+0.05 i 1.04+0.10 i 2.45+0.00 i 1.98-0.03 i 5.28-0.02 i 4.47+0.00 i 1.14+0.00 i 1.98-0.03 i 1.71+0.00 i 4.14+0.00 i 11.89+0.00 i 1.81+0.00 i 5.28-0.02 i 4.14+0.00 i 11.63+0.00 i .

10.1 Program Text

Program Text (f07krfe.f90)

10.2 Program Data

Program Data (f07krfe.d)

10.3 Program Results

Program Results (f07krfe.r)

F07 Chapter Contents
F07 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F07MAF (DSYSV) : NAG Library, Mark 26

F07 Chapter Contents
F07 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F07MAF (DSYSV)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F07MAF (DSYSV) computes the solution to a real system of linear equations
AX=B ,
where A is an n by n symmetric matrix and X and B are n by r matrices.

2 Specification

SUBROUTINE F07MAF ( UPLO, N, NRHS, A, LDA, IPIV, B, LDB, WORK, LWORK, INFO)
INTEGER | N, NRHS, LDA, IPIV(*), LDB, LWORK, INFO
REAL (KIND=nag_wp) | A(LDA,*), B(LDB,*), WORK(max(1,LWORK))
CHARACTER(1) | UPLO
The routine may be called by its LAPACK name dsysv.

3 Description

F07MAF (DSYSV) uses the diagonal pivoting method to factor A as A=UD UT if UPLO='U' or A=LD LT if UPLO='L', where U (or L) is a product of permutation and unit upper (lower) triangular matrices, and D is symmetric and block diagonal with 1 by 1 and 2 by 2 diagonal blocks. The factored form of A is then used to solve the system of equations AX=B.
Note that, in general, different permutations (pivot sequences) and diagonal block structures are obtained for UPLO='U' or 'L'

4 References

Anderson E, Bai Z, Bischof C, Blackford S, Demmel J, Dongarra J J, Du Croz J J, Greenbaum A, Hammarling S, McKenney A and Sorensen D (1999) LAPACK Users' Guide (3rd Edition) SIAM, Philadelphia http://www.netlib.org/lapack/lug
Golub G H and Van Loan C F (1996) Matrix Computations (3rd Edition) Johns Hopkins University Press, Baltimore

5 Arguments

1:   UPLO – CHARACTER(1)Input
On entry: if UPLO='U', the upper triangle of A is stored.
If UPLO='L', the lower triangle of A is stored.
Constraint: UPLO='U' or 'L'.
2:   N – INTEGERInput
On entry: n, the number of linear equations, i.e., the order of the matrix A.
Constraint: N≥0.
3:   NRHS – INTEGERInput
On entry: r, the number of right-hand sides, i.e., the number of columns of the matrix B.
Constraint: NRHS≥0.
4:   A LDA* – REAL (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array A must be at least max 1,N.
On entry: the n by n symmetric matrix A.
  • If UPLO='U', the upper triangular part of A must be stored and the elements of the array below the diagonal are not referenced.
  • If UPLO='L', the lower triangular part of A must be stored and the elements of the array above the diagonal are not referenced.
On exit: if INFO=0, the block diagonal matrix D and the multipliers used to obtain the factor U or L from the factorization A=UD UT or A=LD LT as computed by F07MDF (DSYTRF).
5:   LDA – INTEGERInput
On entry: the first dimension of the array A as declared in the (sub)program from which F07MAF (DSYSV) is called.
Constraint: LDA≥max 1,N.
6:   IPIV* – INTEGER arrayOutput
Note: the dimension of the array IPIV must be at least max 1,N.
On exit: details of the interchanges and the block structure of D. More precisely,
  • if IPIV i=k>0, d ii is a 1 by 1 pivot block and the ith row and column of A were interchanged with the kth row and column;
  • if UPLO='U' and IPIV i-1=IPIV i=-l<0, d i-1,i-1d-i,i-1 d-i,i-1d ii is a 2 by 2 pivot block and the i-1th row and column of A were interchanged with the lth row and column;
  • if UPLO='L' and IPIV i=IPIV i+1=-m<0, d iid i+1,id i+1,id i+1,i+1 is a 2 by 2 pivot block and the i+1th row and column of A were interchanged with the mth row and column.
7:   B LDB* – REAL (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array B must be at least max 1,NRHS.
On entry: the n by r right-hand side matrix B.
On exit: if INFO=0, the n by r solution matrix X.
8:   LDB – INTEGERInput
On entry: the first dimension of the array B as declared in the (sub)program from which F07MAF (DSYSV) is called.
Constraint: LDB≥max 1,N.
9:   WORK max 1,LWORK – REAL (KIND=nag_wp) arrayWorkspace
On exit: if INFO=0, WORK 1 returns the optimal LWORK.
10:   LWORK – INTEGERInput
On entry: the dimension of the array WORK as declared in the (sub)program from which F07MAF (DSYSV) is called.
LWORK≥1, and for best performance LWORK≥max 1,N×nb, where nb is the optimal block size for F07MDF (DSYTRF).
If LWORK=-1, a workspace query is assumed; the routine only calculates the optimal size of the WORK array, returns this value as the first entry of the WORK array, and no error message related to LWORK is issued.
11:   INFO – INTEGEROutput
On exit: INFO=0 unless the routine detects an error (see Section 6).

6 Error Indicators and Warnings

INFO<0
If INFO=-i, argument i had an illegal value. An explanatory message is output, and execution of the program is terminated.
INFO>0
Element value of the diagonal is exactly zero. The factorization has been completed, but the block diagonal matrix D is exactly singular, so the solution could not be computed.

7 Accuracy

The computed solution for a single right-hand side, x^ , satisfies an equation of the form
A+E x^=b ,
where
E 1 = O ε A 1
and ε is the machine precision. An approximate error bound for the computed solution is given by
x^-x 1 x 1 ≤ κ A E 1 A 1 ,
where κ A = A-1 1 A 1 , the condition number of A with respect to the solution of the linear equations. See Section 4.4 of Anderson et al. (1999) for further details.
F07MBF (DSYSVX) is a comprehensive LAPACK driver that returns forward and backward error bounds and an estimate of the condition number. Alternatively, F04BHF solves Ax=b and returns a forward error bound and condition estimate. F04BHF calls F07MAF (DSYSV) to solve the equations.

8 Parallelism and Performance

F07MAF (DSYSV) makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The total number of floating-point operations is approximately 13 n 3 + 2⁢n 2 r , where r is the number of right-hand sides.
The complex analogues of F07MAF (DSYSV) are F07MNF (ZHESV) for Hermitian matrices, and F07NNF (ZSYSV) for symmetric matrices.

10 Example

This example solves the equations
Ax=b ,
where A is the symmetric matrix
A = -1.81 2.06 0.63 -1.15 2.06 1.15 1.87 4.20 0.63 1.87 -0.21 3.87 -1.15 4.20 3.87 2.07   and   b = 0.96 6.07 8.38 9.50 .
Details of the factorization of A are also output.

10.1 Program Text

Program Text (f07mafe.f90)

10.2 Program Data

Program Data (f07mafe.d)

10.3 Program Results

Program Results (f07mafe.r)

F07 Chapter Contents
F07 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F07MBF (DSYSVX) : NAG Library, Mark 26

F07 Chapter Contents
F07 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F07MBF (DSYSVX)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F07MBF (DSYSVX) uses the diagonal pivoting factorization to compute the solution to a real system of linear equations
AX=B ,
where A is an n by n symmetric matrix and X and B are n by r matrices. Error bounds on the solution and a condition estimate are also provided.

2 Specification

SUBROUTINE F07MBF ( FACT, UPLO, N, NRHS, A, LDA, AF, LDAF, IPIV, B, LDB, X, LDX, RCOND, FERR, BERR, WORK, LWORK, IWORK, INFO)
INTEGER | N, NRHS, LDA, LDAF, IPIV(*), LDB, LDX, LWORK, IWORK(*), INFO
REAL (KIND=nag_wp) | A(LDA,*), AF(LDAF,*), B(LDB,*), X(LDX,*), RCOND, FERR(*), BERR(*), WORK(max(1,LWORK))
CHARACTER(1) | FACT, UPLO
The routine may be called by its LAPACK name dsysvx.

3 Description

F07MBF (DSYSVX) performs the following steps:
1. | If FACT='N', the diagonal pivoting method is used to factor A. The form of the factorization is A=UD UT if UPLO='U' or A=LD LT if UPLO='L', where U (or L) is a product of permutation and unit upper (lower) triangular matrices, and D is symmetric and block diagonal with 1 by 1 and 2 by 2 diagonal blocks.
2. | If some d ii=0, so that D is exactly singular, then the routine returns with INFO=i. Otherwise, the factored form of A is used to estimate the condition number of the matrix A. If the reciprocal of the condition number is less than machine precision, INFO=N+1 is returned as a warning, but the routine still goes on to solve for X and compute error bounds as described below.
3. | The system of equations is solved for X using the factored form of A.
4. | Iterative refinement is applied to improve the computed solution matrix and to calculate error bounds and backward error estimates for it.

4 References

Anderson E, Bai Z, Bischof C, Blackford S, Demmel J, Dongarra J J, Du Croz J J, Greenbaum A, Hammarling S, McKenney A and Sorensen D (1999) LAPACK Users' Guide (3rd Edition) SIAM, Philadelphia http://www.netlib.org/lapack/lug
Golub G H and Van Loan C F (1996) Matrix Computations (3rd Edition) Johns Hopkins University Press, Baltimore
Higham N J (2002) Accuracy and Stability of Numerical Algorithms (2nd Edition) SIAM, Philadelphia

5 Arguments

1:   FACT – CHARACTER(1)Input
On entry: specifies whether or not the factorized form of the matrix A has been supplied.
FACT='F'
AF and IPIV contain the factorized form of the matrix A. AF and IPIV will not be modified.
FACT='N'
The matrix A will be copied to AF and factorized.
Constraint: FACT='F' or 'N'.
2:   UPLO – CHARACTER(1)Input
On entry: if UPLO='U', the upper triangle of A is stored.
If UPLO='L', the lower triangle of A is stored.
Constraint: UPLO='U' or 'L'.
3:   N – INTEGERInput
On entry: n, the number of linear equations, i.e., the order of the matrix A.
Constraint: N≥0.
4:   NRHS – INTEGERInput
On entry: r, the number of right-hand sides, i.e., the number of columns of the matrix B.
Constraint: NRHS≥0.
5:   A LDA* – REAL (KIND=nag_wp) arrayInput
Note: the second dimension of the array A must be at least max 1,N.
On entry: the n by n symmetric matrix A.
  • If UPLO='U', the upper triangular part of A must be stored and the elements of the array below the diagonal are not referenced.
  • If UPLO='L', the lower triangular part of A must be stored and the elements of the array above the diagonal are not referenced.
6:   LDA – INTEGERInput
On entry: the first dimension of the array A as declared in the (sub)program from which F07MBF (DSYSVX) is called.
Constraint: LDA≥max 1,N.
7:   AF LDAF* – REAL (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array AF must be at least max 1,N.
On entry: if FACT='F', AF contains the block diagonal matrix D and the multipliers used to obtain the factor U or L from the factorization A=UD UT or A=LD LT as computed by F07MDF (DSYTRF).
On exit: if FACT='N', AF returns the block diagonal matrix D and the multipliers used to obtain the factor U or L from the factorization A=UD UT or A=LD LT.
8:   LDAF – INTEGERInput
On entry: the first dimension of the array AF as declared in the (sub)program from which F07MBF (DSYSVX) is called.
Constraint: LDAF≥max 1,N.
9:   IPIV* – INTEGER arrayInput/Output
Note: the dimension of the array IPIV must be at least max 1,N.
On entry: if FACT='F', IPIV contains details of the interchanges and the block structure of D, as determined by F07MDF (DSYTRF).
  • if IPIV i=k>0, d ii is a 1 by 1 pivot block and the ith row and column of A were interchanged with the kth row and column;
  • if UPLO='U' and IPIV i-1=IPIV i=-l<0, d i-1,i-1d-i,i-1 d-i,i-1d ii is a 2 by 2 pivot block and the i-1th row and column of A were interchanged with the lth row and column;
  • if UPLO='L' and IPIV i=IPIV i+1=-m<0, d iid i+1,id i+1,id i+1,i+1 is a 2 by 2 pivot block and the i+1th row and column of A were interchanged with the mth row and column.
On exit: if FACT='N', IPIV contains details of the interchanges and the block structure of D, as determined by F07MDF (DSYTRF), as described above.
10:   B LDB* – REAL (KIND=nag_wp) arrayInput
Note: the second dimension of the array B must be at least max 1,NRHS.
On entry: the n by r right-hand side matrix B.
11:   LDB – INTEGERInput
On entry: the first dimension of the array B as declared in the (sub)program from which F07MBF (DSYSVX) is called.
Constraint: LDB≥max 1,N.
12:   X LDX* – REAL (KIND=nag_wp) arrayOutput
Note: the second dimension of the array X must be at least max 1,NRHS.
On exit: if INFO=0 or N+1, the n by r solution matrix X.
13:   LDX – INTEGERInput
On entry: the first dimension of the array X as declared in the (sub)program from which F07MBF (DSYSVX) is called.
Constraint: LDX≥max 1,N.
14:   RCOND – REAL (KIND=nag_wp)Output
On exit: the estimate of the reciprocal condition number of the matrix A. If RCOND=0.0, the matrix may be exactly singular. This condition is indicated by INFO>0 and INFO≤N. Otherwise, if RCOND is less than the machine precision, the matrix is singular to working precision. This condition is indicated by INFO=N+1.
15:   FERR* – REAL (KIND=nag_wp) arrayOutput
Note: the dimension of the array FERR must be at least max 1,NRHS.
On exit: if INFO=0 or N+1, an estimate of the forward error bound for each computed solution vector, such that x^j-xj∞/xj∞≤FERR j where x^j is the jth column of the computed solution returned in the array X and xj is the corresponding column of the exact solution X. The estimate is as reliable as the estimate for RCOND, and is almost always a slight overestimate of the true error.
16:   BERR* – REAL (KIND=nag_wp) arrayOutput
Note: the dimension of the array BERR must be at least max 1,NRHS.
On exit: if INFO=0 or N+1, an estimate of the component-wise relative backward error of each computed solution vector x^j (i.e., the smallest relative change in any element of A or B that makes x^j an exact solution).
17:   WORK max 1,LWORK – REAL (KIND=nag_wp) arrayWorkspace
On exit: if INFO=0, WORK 1 returns the optimal LWORK.
18:   LWORK – INTEGERInput
On entry: the dimension of the array WORK as declared in the (sub)program from which F07MBF (DSYSVX) is called.
LWORK≥max 1,3×N, and for best performance, when FACT='N', LWORK≥max 1,3×N,N×nb, where nb is the optimal block size for F07MDF (DSYTRF).
If LWORK=-1, a workspace query is assumed; the routine only calculates the optimal size of the WORK array, returns this value as the first entry of the WORK array, and no error message related to LWORK is issued.
19:   IWORK* – INTEGER arrayWorkspace
Note: the dimension of the array IWORK must be at least max 1,N.
20:   INFO – INTEGEROutput
On exit: INFO=0 unless the routine detects an error (see Section 6).

6 Error Indicators and Warnings

INFO<0
If INFO=-i, argument i had an illegal value. An explanatory message is output, and execution of the program is terminated.
INFO>0 and INFO≤N
Element value of the diagonal is exactly zero. The factorization has been completed, but the factor D is exactly singular, so the solution and error bounds could not be computed. RCOND=0.0 is returned.
INFO=N+1
D is nonsingular, but RCOND is less than machine precision, meaning that the matrix is singular to working precision. Nevertheless, the solution and error bounds are computed because there are a number of situations where the computed solution can be more accurate than the value of RCOND would suggest.

7 Accuracy

For each right-hand side vector b, the computed solution x^ is the exact solution of a perturbed system of equations A+E x^=b, where
E 1 = O ε A 1 ,
where ε is the machine precision. See Chapter 11 of Higham (2002) for further details.
If x^ is the true solution, then the computed solution x satisfies a forward error bound of the form
x-x^∞ x^∞ ≤ wc cond A,x^,b
where cond A,x^,b = A-1 A x^ + b ∞/ x^∞ ≤ cond A = A-1 A ∞≤κ∞ A. If x^ is the j th column of X , then wc is returned in BERR j and a bound on x - x^ ∞ / x^ ∞ is returned in FERR j . See Section 4.4 of Anderson et al. (1999) for further details.

8 Parallelism and Performance

F07MBF (DSYSVX) is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
F07MBF (DSYSVX) makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The factorization of A requires approximately 13 n 3 floating-point operations.
For each right-hand side, computation of the backward error involves a minimum of 4⁢n 2 floating-point operations. Each step of iterative refinement involves an additional 6⁢n 2 operations. At most five steps of iterative refinement are performed, but usually only one or two steps are required. Estimating the forward error involves solving a number of systems of equations of the form Ax=b ; the number is usually 4 or 5 and never more than 11. Each solution involves approximately 2⁢n 2 operations.
The complex analogues of this routine are F07MPF (ZHESVX) for Hermitian matrices, and F07NPF (ZSYSVX) for symmetric matrices.

10 Example

This example solves the equations
AX=B ,
where A is the symmetric matrix
A = -1.81 2.06 0.63 -1.15 2.06 1.15 1.87 4.20 0.63 1.87 -0.21 3.87 -1.15 4.20 3.87 2.07   and   B = 0.96 3.93 6.07 19.25 8.38 9.90 9.50 27.85 .
Error estimates for the solutions, and an estimate of the reciprocal of the condition number of the matrix A are also output.

10.1 Program Text

Program Text (f07mbfe.f90)

10.2 Program Data

Program Data (f07mbfe.d)

10.3 Program Results

Program Results (f07mbfe.r)

F07 Chapter Contents
F07 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F07MDF (DSYTRF) : NAG Library, Mark 26

F07 Chapter Contents
F07 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F07MDF (DSYTRF)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F07MDF (DSYTRF) computes the Bunch–Kaufman factorization of a real symmetric indefinite matrix.

2 Specification

SUBROUTINE F07MDF ( UPLO, N, A, LDA, IPIV, WORK, LWORK, INFO)
INTEGER | N, LDA, IPIV(*), LWORK, INFO
REAL (KIND=nag_wp) | A(LDA,*), WORK(max(1,LWORK))
CHARACTER(1) | UPLO
The routine may be called by its LAPACK name dsytrf.

3 Description

F07MDF (DSYTRF) factorizes a real symmetric matrix A, using the Bunch–Kaufman diagonal pivoting method. A is factorized as either A=PUD UTPT if UPLO='U' or A=PLD LTPT if UPLO='L', where P is a permutation matrix, U (or L) is a unit upper (or lower) triangular matrix and D is a symmetric block diagonal matrix with 1 by 1 and 2 by 2 diagonal blocks; U (or L) has 2 by 2 unit diagonal blocks corresponding to the 2 by 2 blocks of D. Row and column interchanges are performed to ensure numerical stability while preserving symmetry.
This method is suitable for symmetric matrices which are not known to be positive definite. If A is in fact positive definite, no interchanges are performed and no 2 by 2 blocks occur in D.

4 References

Golub G H and Van Loan C F (1996) Matrix Computations (3rd Edition) Johns Hopkins University Press, Baltimore

5 Arguments

1:   UPLO – CHARACTER(1)Input
On entry: specifies whether the upper or lower triangular part of A is stored and how A is to be factorized.
UPLO='U'
The upper triangular part of A is stored and A is factorized as PUD UTPT, where U is upper triangular.
UPLO='L'
The lower triangular part of A is stored and A is factorized as PLD LTPT, where L is lower triangular.
Constraint: UPLO='U' or 'L'.
2:   N – INTEGERInput
On entry: n, the order of the matrix A.
Constraint: N≥0.
3:   A LDA* – REAL (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array A must be at least max 1,N.
On entry: the n by n symmetric indefinite matrix A.
  • If UPLO='U', the upper triangular part of A must be stored and the elements of the array below the diagonal are not referenced.
  • If UPLO='L', the lower triangular part of A must be stored and the elements of the array above the diagonal are not referenced.
On exit: the upper or lower triangle of A is overwritten by details of the block diagonal matrix D and the multipliers used to obtain the factor U or L as specified by UPLO.
4:   LDA – INTEGERInput
On entry: the first dimension of the array A as declared in the (sub)program from which F07MDF (DSYTRF) is called.
Constraint: LDA≥max 1,N.
5:   IPIV* – INTEGER arrayOutput
Note: the dimension of the array IPIV must be at least max 1,N.
On exit: details of the interchanges and the block structure of D. More precisely,
  • if IPIV i=k>0, d ii is a 1 by 1 pivot block and the ith row and column of A were interchanged with the kth row and column;
  • if UPLO='U' and IPIV i-1=IPIV i=-l<0, d i-1,i-1d-i,i-1 d-i,i-1d ii is a 2 by 2 pivot block and the i-1th row and column of A were interchanged with the lth row and column;
  • if UPLO='L' and IPIV i=IPIV i+1=-m<0, d iid i+1,id i+1,id i+1,i+1 is a 2 by 2 pivot block and the i+1th row and column of A were interchanged with the mth row and column.
6:   WORK max 1,LWORK – REAL (KIND=nag_wp) arrayWorkspace
On exit: if INFO=0, WORK 1 contains the minimum value of LWORK required for optimum performance.
7:   LWORK – INTEGERInput
On entry: the dimension of the array WORK as declared in the (sub)program from which F07MDF (DSYTRF) is called, unless LWORK=-1, in which case a workspace query is assumed and the routine only calculates the optimal dimension of WORK (using the formula given below).
Suggested value: for optimum performance LWORK should be at least N×nb, where nb is the block size.
Constraint: LWORK≥1 or LWORK=-1.
8:   INFO – INTEGEROutput
On exit: INFO=0 unless the routine detects an error (see Section 6).

6 Error Indicators and Warnings

INFO<0
If INFO=-i, argument i had an illegal value. An explanatory message is output, and execution of the program is terminated.
INFO>0
Element value of the diagonal is exactly zero. The factorization has been completed, but the block diagonal matrix D is exactly singular, and division by zero will occur if it is used to solve a system of equations.

7 Accuracy

If UPLO='U', the computed factors U and D are the exact factors of a perturbed matrix A+E, where
E≤c n εP UDUT PT ,
c n is a modest linear function of n, and ε is the machine precision.
If UPLO='L', a similar statement holds for the computed factors L and D.

8 Parallelism and Performance

F07MDF (DSYTRF) makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The elements of D overwrite the corresponding elements of A; if D has 2 by 2 blocks, only the upper or lower triangle is stored, as specified by UPLO.
The unit diagonal elements of U or L and the 2 by 2 unit diagonal blocks are not stored. The remaining elements of U or L are stored in the corresponding columns of the array A, but additional row interchanges must be applied to recover U or L explicitly (this is seldom necessary). If IPIV i=i, for i=1,2,…,n (as is the case when A is positive definite), then U or L is stored explicitly (except for its unit diagonal elements which are equal to 1).
The total number of floating-point operations is approximately 13 n 3.
A call to F07MDF (DSYTRF) may be followed by calls to the routines:
  • F07MEF (DSYTRS) to solve AX=B;
  • F07MGF (DSYCON) to estimate the condition number of A;
  • F07MJF (DSYTRI) to compute the inverse of A.
The complex analogues of this routine are F07MRF (ZHETRF) for Hermitian matrices and F07NRF (ZSYTRF) for symmetric matrices.

10 Example

This example computes the Bunch–Kaufman factorization of the matrix A, where
A= 2.07 3.87 4.20 -1.15 3.87 -0.21 1.87 0.63 4.20 1.87 1.15 2.06 -1.15 0.63 2.06 -1.81 .

10.1 Program Text

Program Text (f07mdfe.f90)

10.2 Program Data

Program Data (f07mdfe.d)

10.3 Program Results

Program Results (f07mdfe.r)

F07 Chapter Contents
F07 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F07MEF (DSYTRS) : NAG Library, Mark 26

F07 Chapter Contents
F07 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F07MEF (DSYTRS)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F07MEF (DSYTRS) solves a real symmetric indefinite system of linear equations with multiple right-hand sides,
AX=B ,
where A has been factorized by F07MDF (DSYTRF).

2 Specification

SUBROUTINE F07MEF ( UPLO, N, NRHS, A, LDA, IPIV, B, LDB, INFO)
INTEGER | N, NRHS, LDA, IPIV(*), LDB, INFO
REAL (KIND=nag_wp) | A(LDA,*), B(LDB,*)
CHARACTER(1) | UPLO
The routine may be called by its LAPACK name dsytrs.

3 Description

F07MEF (DSYTRS) is used to solve a real symmetric indefinite system of linear equations AX=B, this routine must be preceded by a call to F07MDF (DSYTRF) which computes the Bunch–Kaufman factorization of A.
If UPLO='U', A=PUD UTPT, where P is a permutation matrix, U is an upper triangular matrix and D is a symmetric block diagonal matrix with 1 by 1 and 2 by 2 blocks; the solution X is computed by solving PUDY=B and then UTPT X=Y.
If UPLO='L', A=PLD LTPT, where L is a lower triangular matrix; the solution X is computed by solving PLDY=B and then LTPT X=Y.

4 References

Golub G H and Van Loan C F (1996) Matrix Computations (3rd Edition) Johns Hopkins University Press, Baltimore

5 Arguments

1:   UPLO – CHARACTER(1)Input
On entry: specifies how A has been factorized.
UPLO='U'
A=PUD UTPT, where U is upper triangular.
UPLO='L'
A=PLD LTPT, where L is lower triangular.
Constraint: UPLO='U' or 'L'.
2:   N – INTEGERInput
On entry: n, the order of the matrix A.
Constraint: N≥0.
3:   NRHS – INTEGERInput
On entry: r, the number of right-hand sides.
Constraint: NRHS≥0.
4:   A LDA* – REAL (KIND=nag_wp) arrayInput
Note: the second dimension of the array A must be at least max 1,N.
On entry: details of the factorization of A, as returned by F07MDF (DSYTRF).
5:   LDA – INTEGERInput
On entry: the first dimension of the array A as declared in the (sub)program from which F07MEF (DSYTRS) is called.
Constraint: LDA≥max 1,N.
6:   IPIV* – INTEGER arrayInput
Note: the dimension of the array IPIV must be at least max 1,N.
On entry: details of the interchanges and the block structure of D, as returned by F07MDF (DSYTRF).
7:   B LDB* – REAL (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array B must be at least max 1,NRHS.
On entry: the n by r right-hand side matrix B.
On exit: the n by r solution matrix X.
8:   LDB – INTEGERInput
On entry: the first dimension of the array B as declared in the (sub)program from which F07MEF (DSYTRS) is called.
Constraint: LDB≥max 1,N.
9:   INFO – INTEGEROutput
On exit: INFO=0 unless the routine detects an error (see Section 6).

6 Error Indicators and Warnings

INFO<0
If INFO=-i, argument i had an illegal value. An explanatory message is output, and execution of the program is terminated.

7 Accuracy

For each right-hand side vector b, the computed solution x is the exact solution of a perturbed system of equations A+E x=b, where
  • if UPLO='U', E≤c n εP UDUT PT;
  • if UPLO='L', E≤c n εP LDLT PT,
c n is a modest linear function of n, and ε is the machine precision.
If x^ is the true solution, then the computed solution x satisfies a forward error bound of the form
x-x^∞ x∞ ≤c n cond A,x ε
where cond A,x=A-1Ax∞/x∞≤cond A=A-1A∞≤κ∞A.
Note that cond A,x can be much smaller than cond A.
Forward and backward error bounds can be computed by calling F07MHF (DSYRFS), and an estimate for κ∞A (=κ 1 A) can be obtained by calling F07MGF (DSYCON).

8 Parallelism and Performance

F07MEF (DSYTRS) makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The total number of floating-point operations is approximately 2⁢n 2 r.
This routine may be followed by a call to F07MHF (DSYRFS) to refine the solution and return an error estimate.
The complex analogues of this routine are F07MSF (ZHETRS) for Hermitian matrices and F07NSF (ZSYTRS) for symmetric matrices.

10 Example

This example solves the system of equations AX=B, where
A= 2.07 3.87 4.20 -1.15 3.87 -0.21 1.87 0.63 4.20 1.87 1.15 2.06 -1.15 0.63 2.06 -1.81   and   B= -9.50 27.85 -8.38 9.90 -6.07 19.25 -0.96 3.93 .
Here A is symmetric indefinite and must first be factorized by F07MDF (DSYTRF).

10.1 Program Text

Program Text (f07mefe.f90)

10.2 Program Data

Program Data (f07mefe.d)

10.3 Program Results

Program Results (f07mefe.r)

F07 Chapter Contents
F07 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F07MGF (DSYCON) : NAG Library, Mark 26

F07 Chapter Contents
F07 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F07MGF (DSYCON)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F07MGF (DSYCON) estimates the condition number of a real symmetric indefinite matrix A, where A has been factorized by F07MDF (DSYTRF).

2 Specification

SUBROUTINE F07MGF ( UPLO, N, A, LDA, IPIV, ANORM, RCOND, WORK, IWORK, INFO)
INTEGER | N, LDA, IPIV(*), IWORK(N), INFO
REAL (KIND=nag_wp) | A(LDA,*), ANORM, RCOND, WORK(2*N)
CHARACTER(1) | UPLO
The routine may be called by its LAPACK name dsycon.

3 Description

F07MGF (DSYCON) estimates the condition number (in the 1-norm) of a real symmetric indefinite matrix A:
κ 1 A=A 1A-1 1 .
Since A is symmetric, κ 1 A=κ∞A=A∞A-1∞.
Because κ 1 A is infinite if A is singular, the routine actually returns an estimate of the reciprocal of κ 1 A.
The routine should be preceded by a call to F06RCF to compute A 1 and a call to F07MDF (DSYTRF) to compute the Bunch–Kaufman factorization of A. The routine then uses Higham's implementation of Hager's method (see Higham (1988)) to estimate A-1 1.

4 References

Higham N J (1988) FORTRAN codes for estimating the one-norm of a real or complex matrix, with applications to condition estimation ACM Trans. Math. Software 14 381–396

5 Arguments

1:   UPLO – CHARACTER(1)Input
On entry: specifies how A has been factorized.
UPLO='U'
A=PUD UTPT, where U is upper triangular.
UPLO='L'
A=PLD LTPT, where L is lower triangular.
Constraint: UPLO='U' or 'L'.
2:   N – INTEGERInput
On entry: n, the order of the matrix A.
Constraint: N≥0.
3:   A LDA* – REAL (KIND=nag_wp) arrayInput
Note: the second dimension of the array A must be at least max 1,N.
On entry: details of the factorization of A, as returned by F07MDF (DSYTRF).
4:   LDA – INTEGERInput
On entry: the first dimension of the array A as declared in the (sub)program from which F07MGF (DSYCON) is called.
Constraint: LDA≥max 1,N.
5:   IPIV* – INTEGER arrayInput
Note: the dimension of the array IPIV must be at least max 1,N.
On entry: details of the interchanges and the block structure of D, as returned by F07MDF (DSYTRF).
6:   ANORM – REAL (KIND=nag_wp)Input
On entry: the 1-norm of the original matrix A, which may be computed by calling F06RCF with its argument NORM='1'. ANORM must be computed either before calling F07MDF (DSYTRF) or else from a copy of the original matrix A.
Constraint: ANORM≥0.0.
7:   RCOND – REAL (KIND=nag_wp)Output
On exit: an estimate of the reciprocal of the condition number of A. RCOND is set to zero if exact singularity is detected or the estimate underflows. If RCOND is less than machine precision, A is singular to working precision.
8:   WORK 2×N – REAL (KIND=nag_wp) arrayWorkspace
9:   IWORK N – INTEGER arrayWorkspace
10:   INFO – INTEGEROutput
On exit: INFO=0 unless the routine detects an error (see Section 6).

6 Error Indicators and Warnings

INFO<0
If INFO=-i, argument i had an illegal value. An explanatory message is output, and execution of the program is terminated.

7 Accuracy

The computed estimate RCOND is never less than the true value ρ, and in practice is nearly always less than 10 ρ, although examples can be constructed where RCOND is much larger.

8 Parallelism and Performance

F07MGF (DSYCON) makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

A call to F07MGF (DSYCON) involves solving a number of systems of linear equations of the form Ax=b; the number is usually 4 or 5 and never more than 11. Each solution involves approximately 2⁢n 2 floating-point operations but takes considerably longer than a call to F07MEF (DSYTRS) with one right-hand side, because extra care is taken to avoid overflow when A is approximately singular.
The complex analogues of this routine are F07MUF (ZHECON) for Hermitian matrices and F07NUF (ZSYCON) for symmetric matrices.

10 Example

This example estimates the condition number in the 1-norm (or ∞-norm) of the matrix A, where
A= 2.07 3.87 4.20 -1.15 3.87 -0.21 1.87 0.63 4.20 1.87 1.15 2.06 -1.15 0.63 2.06 -1.81 .
Here A is symmetric indefinite and must first be factorized by F07MDF (DSYTRF). The true condition number in the 1-norm is 75.68.

10.1 Program Text

Program Text (f07mgfe.f90)

10.2 Program Data

Program Data (f07mgfe.d)

10.3 Program Results

Program Results (f07mgfe.r)

F07 Chapter Contents
F07 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F07MHF (DSYRFS) : NAG Library, Mark 26

F07 Chapter Contents
F07 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F07MHF (DSYRFS)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F07MHF (DSYRFS) returns error bounds for the solution of a real symmetric indefinite system of linear equations with multiple right-hand sides, AX=B. It improves the solution by iterative refinement, in order to reduce the backward error as much as possible.

2 Specification

SUBROUTINE F07MHF ( UPLO, N, NRHS, A, LDA, AF, LDAF, IPIV, B, LDB, X, LDX, FERR, BERR, WORK, IWORK, INFO)
INTEGER | N, NRHS, LDA, LDAF, IPIV(*), LDB, LDX, IWORK(N), INFO
REAL (KIND=nag_wp) | A(LDA,*), AF(LDAF,*), B(LDB,*), X(LDX,*), FERR(NRHS), BERR(NRHS), WORK(3*N)
CHARACTER(1) | UPLO
The routine may be called by its LAPACK name dsyrfs.

3 Description

F07MHF (DSYRFS) returns the backward errors and estimated bounds on the forward errors for the solution of a real symmetric indefinite system of linear equations with multiple right-hand sides AX=B. The routine handles each right-hand side vector (stored as a column of the matrix B) independently, so we describe the function of F07MHF (DSYRFS) in terms of a single right-hand side b and solution x.
Given a computed solution x, the routine computes the component-wise backward error β. This is the size of the smallest relative perturbation in each element of A and b such that x is the exact solution of a perturbed system
A+δA x=b+δb δ a ij≤β a ij   and   δ bi≤β bi .
Then the routine estimates a bound for the component-wise forward error in the computed solution, defined by:
maxi xi-x^i/maxi xi
where x^ is the true solution.
For details of the method, see the F07 Chapter Introduction.

4 References

Golub G H and Van Loan C F (1996) Matrix Computations (3rd Edition) Johns Hopkins University Press, Baltimore

5 Arguments

1:   UPLO – CHARACTER(1)Input
On entry: specifies whether the upper or lower triangular part of A is stored and how A is to be factorized.
UPLO='U'
The upper triangular part of A is stored and A is factorized as PUD UTPT, where U is upper triangular.
UPLO='L'
The lower triangular part of A is stored and A is factorized as PLD LTPT, where L is lower triangular.
Constraint: UPLO='U' or 'L'.
2:   N – INTEGERInput
On entry: n, the order of the matrix A.
Constraint: N≥0.
3:   NRHS – INTEGERInput
On entry: r, the number of right-hand sides.
Constraint: NRHS≥0.
4:   A LDA* – REAL (KIND=nag_wp) arrayInput
Note: the second dimension of the array A must be at least max 1,N.
On entry: the n by n original symmetric matrix A as supplied to F07MDF (DSYTRF).
5:   LDA – INTEGERInput
On entry: the first dimension of the array A as declared in the (sub)program from which F07MHF (DSYRFS) is called.
Constraint: LDA≥max 1,N.
6:   AF LDAF* – REAL (KIND=nag_wp) arrayInput
Note: the second dimension of the array AF must be at least max 1,N.
On entry: details of the factorization of A, as returned by F07MDF (DSYTRF).
7:   LDAF – INTEGERInput
On entry: the first dimension of the array AF as declared in the (sub)program from which F07MHF (DSYRFS) is called.
Constraint: LDAF≥max 1,N.
8:   IPIV* – INTEGER arrayInput
Note: the dimension of the array IPIV must be at least max 1,N.
On entry: details of the interchanges and the block structure of D, as returned by F07MDF (DSYTRF).
9:   B LDB* – REAL (KIND=nag_wp) arrayInput
Note: the second dimension of the array B must be at least max 1,NRHS.
On entry: the n by r right-hand side matrix B.
10:   LDB – INTEGERInput
On entry: the first dimension of the array B as declared in the (sub)program from which F07MHF (DSYRFS) is called.
Constraint: LDB≥max 1,N.
11:   X LDX* – REAL (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array X must be at least max 1,NRHS.
On entry: the n by r solution matrix X, as returned by F07MEF (DSYTRS).
On exit: the improved solution matrix X.
12:   LDX – INTEGERInput
On entry: the first dimension of the array X as declared in the (sub)program from which F07MHF (DSYRFS) is called.
Constraint: LDX≥max 1,N.
13:   FERR NRHS – REAL (KIND=nag_wp) arrayOutput
On exit: FERR j contains an estimated error bound for the jth solution vector, that is, the jth column of X, for j=1,2,…,r.
14:   BERR NRHS – REAL (KIND=nag_wp) arrayOutput
On exit: BERR j contains the component-wise backward error bound β for the jth solution vector, that is, the jth column of X, for j=1,2,…,r.
15:   WORK 3×N – REAL (KIND=nag_wp) arrayWorkspace
16:   IWORK N – INTEGER arrayWorkspace
17:   INFO – INTEGEROutput
On exit: INFO=0 unless the routine detects an error (see Section 6).

6 Error Indicators and Warnings

INFO<0
If INFO=-i, argument i had an illegal value. An explanatory message is output, and execution of the program is terminated.

7 Accuracy

The bounds returned in FERR are not rigorous, because they are estimated, not computed exactly; but in practice they almost always overestimate the actual error.

8 Parallelism and Performance

F07MHF (DSYRFS) is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
F07MHF (DSYRFS) makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

For each right-hand side, computation of the backward error involves a minimum of 4⁢n 2 floating-point operations. Each step of iterative refinement involves an additional 6⁢n 2 operations. At most five steps of iterative refinement are performed, but usually only one or two steps are required.
Estimating the forward error involves solving a number of systems of linear equations of the form Ax=b; the number is usually 4 or 5 and never more than 11. Each solution involves approximately 2⁢n 2 operations.
The complex analogues of this routine are F07MVF (ZHERFS) for Hermitian matrices and F07NVF (ZSYRFS) for symmetric matrices.

10 Example

This example solves the system of equations AX=B using iterative refinement and to compute the forward and backward error bounds, where
A= 2.07 3.87 4.20 -1.15 3.87 -0.21 1.87 0.63 4.20 1.87 1.15 2.06 -1.15 0.63 2.06 -1.81   and   B= -9.50 27.85 -8.38 9.90 -6.07 19.25 -0.96 3.93 .
Here A is symmetric indefinite and must first be factorized by F07MDF (DSYTRF).

10.1 Program Text

Program Text (f07mhfe.f90)

10.2 Program Data

Program Data (f07mhfe.d)

10.3 Program Results

Program Results (f07mhfe.r)

F07 Chapter Contents
F07 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F07MJF (DSYTRI) : NAG Library, Mark 26

F07 Chapter Contents
F07 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F07MJF (DSYTRI)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F07MJF (DSYTRI) computes the inverse of a real symmetric indefinite matrix A, where A has been factorized by F07MDF (DSYTRF).

2 Specification

SUBROUTINE F07MJF ( UPLO, N, A, LDA, IPIV, WORK, INFO)
INTEGER | N, LDA, IPIV(*), INFO
REAL (KIND=nag_wp) | A(LDA,*), WORK(N)
CHARACTER(1) | UPLO
The routine may be called by its LAPACK name dsytri.

3 Description

F07MJF (DSYTRI) is used to compute the inverse of a real symmetric indefinite matrix A, the routine must be preceded by a call to F07MDF (DSYTRF), which computes the Bunch–Kaufman factorization of A.
If UPLO='U', A=PUD UTPT and A-1 is computed by solving UTPT XPU=D-1 for X.
If UPLO='L', A=PLD LTPT and A-1 is computed by solving LTPT XPL=D-1 for X.

4 References

Du Croz J J and Higham N J (1992) Stability of methods for matrix inversion IMA J. Numer. Anal. 12 1–19

5 Arguments

1:   UPLO – CHARACTER(1)Input
On entry: specifies how A has been factorized.
UPLO='U'
A=PUD UTPT, where U is upper triangular.
UPLO='L'
A=PLD LTPT, where L is lower triangular.
Constraint: UPLO='U' or 'L'.
2:   N – INTEGERInput
On entry: n, the order of the matrix A.
Constraint: N≥0.
3:   A LDA* – REAL (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array A must be at least max 1,N.
On entry: details of the factorization of A, as returned by F07MDF (DSYTRF).
On exit: the factorization is overwritten by the n by n symmetric matrix A-1.
If UPLO='U', the upper triangle of A-1 is stored in the upper triangular part of the array.
If UPLO='L', the lower triangle of A-1 is stored in the lower triangular part of the array.
4:   LDA – INTEGERInput
On entry: the first dimension of the array A as declared in the (sub)program from which F07MJF (DSYTRI) is called.
Constraint: LDA≥max 1,N.
5:   IPIV* – INTEGER arrayInput
Note: the dimension of the array IPIV must be at least max 1,N.
On entry: details of the interchanges and the block structure of D, as returned by F07MDF (DSYTRF).
6:   WORK N – REAL (KIND=nag_wp) arrayWorkspace
7:   INFO – INTEGEROutput
On exit: INFO=0 unless the routine detects an error (see Section 6).

6 Error Indicators and Warnings

-999<INFO<0
If INFO=-i, argument i had an illegal value. An explanatory message is output, and execution of the program is terminated.
INFO=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.
An explanatory message is output, and execution of the program is terminated.
INFO>0
Element value of the diagonal is exactly zero. D is singular and the inverse of A cannot be computed.

7 Accuracy

The computed inverse X satisfies a bound of the form
  • if UPLO='U', D UTPT XPU-I≤c n ε DUT PT X P U+DD-1;
  • if UPLO='L', D LTPT XPL-I≤c n ε DLT PT X P L+DD-1,
c n is a modest linear function of n, and ε is the machine precision.

8 Parallelism and Performance

F07MJF (DSYTRI) makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The total number of floating-point operations is approximately 23 n 3.
The complex analogues of this routine are F07MWF (ZHETRI) for Hermitian matrices and F07NWF (ZSYTRI) for symmetric matrices.

10 Example

This example computes the inverse of the matrix A, where
A= 2.07 3.87 4.20 -1.15 3.87 -0.21 1.87 0.63 4.20 1.87 1.15 2.06 -1.15 0.63 2.06 -1.81 .
Here A is symmetric indefinite and must first be factorized by F07MDF (DSYTRF).

10.1 Program Text

Program Text (f07mjfe.f90)

10.2 Program Data

Program Data (f07mjfe.d)

10.3 Program Results

Program Results (f07mjfe.r)

F07 Chapter Contents
F07 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F07MNF (ZHESV) : NAG Library, Mark 26

F07 Chapter Contents
F07 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F07MNF (ZHESV)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F07MNF (ZHESV) computes the solution to a complex system of linear equations
AX=B ,
where A is an n by n Hermitian matrix and X and B are n by r matrices.

2 Specification

SUBROUTINE F07MNF ( UPLO, N, NRHS, A, LDA, IPIV, B, LDB, WORK, LWORK, INFO)
INTEGER | N, NRHS, LDA, IPIV(*), LDB, LWORK, INFO
COMPLEX (KIND=nag_wp) | A(LDA,*), B(LDB,*), WORK(max(1,LWORK))
CHARACTER(1) | UPLO
The routine may be called by its LAPACK name zhesv.

3 Description

F07MNF (ZHESV) uses the diagonal pivoting method to factor A as A=UD UH if UPLO='U' or A=LD LH if UPLO='L', where U (or L) is a product of permutation and unit upper (lower) triangular matrices, and D is Hermitian and block diagonal with 1 by 1 and 2 by 2 diagonal blocks. The factored form of A is then used to solve the system of equations AX=B.

4 References

Anderson E, Bai Z, Bischof C, Blackford S, Demmel J, Dongarra J J, Du Croz J J, Greenbaum A, Hammarling S, McKenney A and Sorensen D (1999) LAPACK Users' Guide (3rd Edition) SIAM, Philadelphia http://www.netlib.org/lapack/lug
Golub G H and Van Loan C F (1996) Matrix Computations (3rd Edition) Johns Hopkins University Press, Baltimore

5 Arguments

1:   UPLO – CHARACTER(1)Input
On entry: if UPLO='U', the upper triangle of A is stored.
If UPLO='L', the lower triangle of A is stored.
Constraint: UPLO='U' or 'L'.
2:   N – INTEGERInput
On entry: n, the number of linear equations, i.e., the order of the matrix A.
Constraint: N≥0.
3:   NRHS – INTEGERInput
On entry: r, the number of right-hand sides, i.e., the number of columns of the matrix B.
Constraint: NRHS≥0.
4:   A LDA* – COMPLEX (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array A must be at least max 1,N.
On entry: the n by n Hermitian matrix A.
  • If UPLO='U', the upper triangular part of A must be stored and the elements of the array below the diagonal are not referenced.
  • If UPLO='L', the lower triangular part of A must be stored and the elements of the array above the diagonal are not referenced.
On exit: if INFO=0, the block diagonal matrix D and the multipliers used to obtain the factor U or L from the factorization A=UD UH or A=LD LH as computed by F07MRF (ZHETRF).
5:   LDA – INTEGERInput
On entry: the first dimension of the array A as declared in the (sub)program from which F07MNF (ZHESV) is called.
Constraint: LDA≥max 1,N.
6:   IPIV* – INTEGER arrayOutput
Note: the dimension of the array IPIV must be at least max 1,N.
On exit: details of the interchanges and the block structure of D. More precisely,
  • if IPIV i=k>0, d ii is a 1 by 1 pivot block and the ith row and column of A were interchanged with the kth row and column;
  • if UPLO='U' and IPIV i-1=IPIV i=-l<0, d i-1,i-1d-i,i-1 d-i,i-1d ii is a 2 by 2 pivot block and the i-1th row and column of A were interchanged with the lth row and column;
  • if UPLO='L' and IPIV i=IPIV i+1=-m<0, d iid i+1,id i+1,id i+1,i+1 is a 2 by 2 pivot block and the i+1th row and column of A were interchanged with the mth row and column.
7:   B LDB* – COMPLEX (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array B must be at least max 1,NRHS.
To solve the equations Ax=b, where b is a single right-hand side, B may be supplied as a one-dimensional array with length LDB=max 1,N.
On entry: the n by r right-hand side matrix B.
On exit: if INFO=0, the n by r solution matrix X.
8:   LDB – INTEGERInput
On entry: the first dimension of the array B as declared in the (sub)program from which F07MNF (ZHESV) is called.
Constraint: LDB≥max 1,N.
9:   WORK max 1,LWORK – COMPLEX (KIND=nag_wp) arrayWorkspace
On exit: if INFO=0, WORK 1 returns the optimal LWORK.
10:   LWORK – INTEGERInput
On entry: the dimension of the array WORK as declared in the (sub)program from which F07MNF (ZHESV) is called.
LWORK≥1, and for best performance LWORK≥max 1,N×nb, where nb is the optimal block size for F07MRF (ZHETRF).
If LWORK=-1, a workspace query is assumed; the routine only calculates the optimal size of the WORK array, returns this value as the first entry of the WORK array, and no error message related to LWORK is issued.
11:   INFO – INTEGEROutput
On exit: INFO=0 unless the routine detects an error (see Section 6).

6 Error Indicators and Warnings

INFO<0
If INFO=-i, argument i had an illegal value. An explanatory message is output, and execution of the program is terminated.
INFO>0
Element value of the diagonal is exactly zero. The factorization has been completed, but the block diagonal matrix D is exactly singular, so the solution could not be computed.

7 Accuracy

The computed solution for a single right-hand side, x^ , satisfies an equation of the form
A+E x^=b ,
where
E 1 = O ε A 1
and ε is the machine precision. An approximate error bound for the computed solution is given by
x^-x 1 x 1 ≤ κ A E 1 A 1 ,
where κ A = A-1 1 A 1 , the condition number of A with respect to the solution of the linear equations. See Section 4.4 of Anderson et al. (1999) for further details.
F07MPF (ZHESVX) is a comprehensive LAPACK driver that returns forward and backward error bounds and an estimate of the condition number. Alternatively, F04CHF solves Ax=b and returns a forward error bound and condition estimate. F04CHF calls F07MNF (ZHESV) to solve the equations.

8 Parallelism and Performance

F07MNF (ZHESV) makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The total number of floating-point operations is approximately 43 n 3 + 8⁢n 2 r , where r is the number of right-hand sides.
The real analogue of this routine is F07MAF (DSYSV). The complex symmetric analogue of this routine is F07NNF (ZSYSV).

10 Example

This example solves the equations
Ax=b ,
where A is the Hermitian matrix
A = -1.84 i+0.00 0.11-0.11 i -1.78-1.18 i 3.91-1.50 i 0.11+0.11 i -4.63 i+0.00 -1.84+0.03 i 2.21+0.21 i -1.78+1.18 i -1.84-0.03 i -8.87 i+0.00 1.58-0.90 i 3.91+1.50 i 2.21-0.21 i 1.58+0.90 i -1.36 i+0.00
and
b = 2.98-10.18 i -9.58+0 3.88 i -0.77-16.05 i 7.79+0 5.48 i .
Details of the factorization of A are also output.

10.1 Program Text

Program Text (f07mnfe.f90)

10.2 Program Data

Program Data (f07mnfe.d)

10.3 Program Results

Program Results (f07mnfe.r)

F07 Chapter Contents
F07 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F07MPF (ZHESVX) : NAG Library, Mark 26

F07 Chapter Contents
F07 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F07MPF (ZHESVX)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F07MPF (ZHESVX) uses the diagonal pivoting factorization to compute the solution to a complex system of linear equations
AX=B ,
where A is an n by n Hermitian matrix and X and B are n by r matrices. Error bounds on the solution and a condition estimate are also provided.

2 Specification

SUBROUTINE F07MPF ( FACT, UPLO, N, NRHS, A, LDA, AF, LDAF, IPIV, B, LDB, X, LDX, RCOND, FERR, BERR, WORK, LWORK, RWORK, INFO)
INTEGER | N, NRHS, LDA, LDAF, IPIV(*), LDB, LDX, LWORK, INFO
REAL (KIND=nag_wp) | RCOND, FERR(*), BERR(*), RWORK(*)
COMPLEX (KIND=nag_wp) | A(LDA,*), AF(LDAF,*), B(LDB,*), X(LDX,*), WORK(max(1,LWORK))
CHARACTER(1) | FACT, UPLO
The routine may be called by its LAPACK name zhesvx.

3 Description

F07MPF (ZHESVX) performs the following steps:
1. | If FACT='N', the diagonal pivoting method is used to factor A. The form of the factorization is A=UD UH if UPLO='U' or A=LD LH if UPLO='L', where U (or L) is a product of permutation and unit upper (lower) triangular matrices, and D is Hermitian and block diagonal with 1 by 1 and 2 by 2 diagonal blocks.
2. | If some d ii=0, so that D is exactly singular, then the routine returns with INFO=i. Otherwise, the factored form of A is used to estimate the condition number of the matrix A. If the reciprocal of the condition number is less than machine precision, INFO=N+1 is returned as a warning, but the routine still goes on to solve for X and compute error bounds as described below.
3. | The system of equations is solved for X using the factored form of A.
4. | Iterative refinement is applied to improve the computed solution matrix and to calculate error bounds and backward error estimates for it.

4 References

Anderson E, Bai Z, Bischof C, Blackford S, Demmel J, Dongarra J J, Du Croz J J, Greenbaum A, Hammarling S, McKenney A and Sorensen D (1999) LAPACK Users' Guide (3rd Edition) SIAM, Philadelphia http://www.netlib.org/lapack/lug
Golub G H and Van Loan C F (1996) Matrix Computations (3rd Edition) Johns Hopkins University Press, Baltimore
Higham N J (2002) Accuracy and Stability of Numerical Algorithms (2nd Edition) SIAM, Philadelphia

5 Arguments

1:   FACT – CHARACTER(1)Input
On entry: specifies whether or not the factorized form of the matrix A has been supplied.
FACT='F'
AF and IPIV contain the factorized form of the matrix A. AF and IPIV will not be modified.
FACT='N'
The matrix A will be copied to AF and factorized.
Constraint: FACT='F' or 'N'.
2:   UPLO – CHARACTER(1)Input
On entry: if UPLO='U', the upper triangle of A is stored.
If UPLO='L', the lower triangle of A is stored.
Constraint: UPLO='U' or 'L'.
3:   N – INTEGERInput
On entry: n, the number of linear equations, i.e., the order of the matrix A.
Constraint: N≥0.
4:   NRHS – INTEGERInput
On entry: r, the number of right-hand sides, i.e., the number of columns of the matrix B.
Constraint: NRHS≥0.
5:   A LDA* – COMPLEX (KIND=nag_wp) arrayInput
Note: the second dimension of the array A must be at least max 1,N.
On entry: the n by n Hermitian matrix A.
  • If UPLO='U', the upper triangular part of A must be stored and the elements of the array below the diagonal are not referenced.
  • If UPLO='L', the lower triangular part of A must be stored and the elements of the array above the diagonal are not referenced.
6:   LDA – INTEGERInput
On entry: the first dimension of the array A as declared in the (sub)program from which F07MPF (ZHESVX) is called.
Constraint: LDA≥max 1,N.
7:   AF LDAF* – COMPLEX (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array AF must be at least max 1,N.
On entry: if FACT='F', AF contains the block diagonal matrix D and the multipliers used to obtain the factor U or L from the factorization A=UD UH or A=LD LH as computed by F07MRF (ZHETRF).
On exit: if FACT='N', AF returns the block diagonal matrix D and the multipliers used to obtain the factor U or L from the factorization A=UD UH or A=LD LH.
8:   LDAF – INTEGERInput
On entry: the first dimension of the array AF as declared in the (sub)program from which F07MPF (ZHESVX) is called.
Constraint: LDAF≥max 1,N.
9:   IPIV* – INTEGER arrayInput/Output
Note: the dimension of the array IPIV must be at least max 1,N.
On entry: if FACT='F', IPIV contains details of the interchanges and the block structure of D, as determined by F07MRF (ZHETRF).
  • if IPIV i=k>0, d ii is a 1 by 1 pivot block and the ith row and column of A were interchanged with the kth row and column;
  • if UPLO='U' and IPIV i-1=IPIV i=-l<0, d i-1,i-1d-i,i-1 d-i,i-1d ii is a 2 by 2 pivot block and the i-1th row and column of A were interchanged with the lth row and column;
  • if UPLO='L' and IPIV i=IPIV i+1=-m<0, d iid i+1,id i+1,id i+1,i+1 is a 2 by 2 pivot block and the i+1th row and column of A were interchanged with the mth row and column.
On exit: if FACT='N', IPIV contains details of the interchanges and the block structure of D, as determined by F07MRF (ZHETRF), as described above.
10:   B LDB* – COMPLEX (KIND=nag_wp) arrayInput
Note: the second dimension of the array B must be at least max 1,NRHS.
On entry: the n by r right-hand side matrix B.
11:   LDB – INTEGERInput
On entry: the first dimension of the array B as declared in the (sub)program from which F07MPF (ZHESVX) is called.
Constraint: LDB≥max 1,N.
12:   X LDX* – COMPLEX (KIND=nag_wp) arrayOutput
Note: the second dimension of the array X must be at least max 1,NRHS.
On exit: if INFO=0 or N+1, the n by r solution matrix X.
13:   LDX – INTEGERInput
On entry: the first dimension of the array X as declared in the (sub)program from which F07MPF (ZHESVX) is called.
Constraint: LDX≥max 1,N.
14:   RCOND – REAL (KIND=nag_wp)Output
On exit: the estimate of the reciprocal condition number of the matrix A. If RCOND=0.0, the matrix may be exactly singular. This condition is indicated by INFO>0 and INFO≤N. Otherwise, if RCOND is less than the machine precision, the matrix is singular to working precision. This condition is indicated by INFO=N+1.
15:   FERR* – REAL (KIND=nag_wp) arrayOutput
Note: the dimension of the array FERR must be at least max 1,NRHS.
On exit: if INFO=0 or N+1, an estimate of the forward error bound for each computed solution vector, such that x^j-xj∞/xj∞≤FERR j where x^j is the jth column of the computed solution returned in the array X and xj is the corresponding column of the exact solution X. The estimate is as reliable as the estimate for RCOND, and is almost always a slight overestimate of the true error.
16:   BERR* – REAL (KIND=nag_wp) arrayOutput
Note: the dimension of the array BERR must be at least max 1,NRHS.
On exit: if INFO=0 or N+1, an estimate of the component-wise relative backward error of each computed solution vector x^j (i.e., the smallest relative change in any element of A or B that makes x^j an exact solution).
17:   WORK max 1,LWORK – COMPLEX (KIND=nag_wp) arrayWorkspace
On exit: if INFO=0, WORK 1 returns the optimal LWORK.
18:   LWORK – INTEGERInput
On entry: the dimension of the array WORK as declared in the (sub)program from which F07MPF (ZHESVX) is called.
LWORK≥max 1,2×N, and for best performance, when FACT='N', LWORK≥max 1,2×N,N×nb, where nb is the optimal block size for F07MRF (ZHETRF).
If LWORK=-1, a workspace query is assumed; the routine only calculates the optimal size of the WORK array, returns this value as the first entry of the WORK array, and no error message related to LWORK is issued.
19:   RWORK* – REAL (KIND=nag_wp) arrayWorkspace
Note: the dimension of the array RWORK must be at least max 1,N.
20:   INFO – INTEGEROutput
On exit: INFO=0 unless the routine detects an error (see Section 6).

6 Error Indicators and Warnings

INFO<0
If INFO=-i, argument i had an illegal value. An explanatory message is output, and execution of the program is terminated.
INFO>0 and INFO≤N
Element value of the diagonal is exactly zero. The factorization has been completed, but the factor D is exactly singular, so the solution and error bounds could not be computed. RCOND=0.0 is returned.
INFO=N+1
D is nonsingular, but RCOND is less than machine precision, meaning that the matrix is singular to working precision. Nevertheless, the solution and error bounds are computed because there are a number of situations where the computed solution can be more accurate than the value of RCOND would suggest.

7 Accuracy

For each right-hand side vector b, the computed solution x^ is the exact solution of a perturbed system of equations A+E x^=b, where
E 1 = O ε A 1 ,
where ε is the machine precision. See Chapter 11 of Higham (2002) for further details.
If x^ is the true solution, then the computed solution x satisfies a forward error bound of the form
x-x^∞ x^∞ ≤ wc cond A,x^,b
where cond A,x^,b = A-1 A x^ + b ∞/ x^∞ ≤ cond A = A-1 A ∞≤κ∞ A. If x^ is the j th column of X , then wc is returned in BERR j and a bound on x - x^ ∞ / x^ ∞ is returned in FERR j . See Section 4.4 of Anderson et al. (1999) for further details.

8 Parallelism and Performance

F07MPF (ZHESVX) is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
F07MPF (ZHESVX) makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The factorization of A requires approximately 43 n 3 floating-point operations.
For each right-hand side, computation of the backward error involves a minimum of 16⁢n 2 floating-point operations. Each step of iterative refinement involves an additional 24⁢n 2 operations. At most five steps of iterative refinement are performed, but usually only one or two steps are required. Estimating the forward error involves solving a number of systems of equations of the form Ax=b ; the number is usually 4 or 5 and never more than 11. Each solution involves approximately 8⁢n 2 operations.
The real analogue of this routine is F07MBF (DSYSVX). The complex symmetric analogue of this routine is F07NPF (ZSYSVX).

10 Example

This example solves the equations
AX=B ,
where A is the Hermitian matrix
A = -1.84 i+0.00 0.11-0.11 i -1.78-1.18 i 3.91-1.50 i 0.11+0.11 i -4.63 i+0.00 -1.84+0.03 i 2.21+0.21 i -1.78+1.18 i -1.84-0.03 i -8.87 i+0.00 1.58-0.90 i 3.91+1.50 i 2.21-0.21 i 1.58+0.90 i -1.36 i+0.00
and
B = 2.98-10.18 i 28.68-39.89 i -9.58+0 3.88 i -24.79-0 8.40 i -0.77-16.05 i 4.23-70.02 i 7.79+0 5.48 i -35.39+18.01 i .
Error estimates for the solutions, and an estimate of the reciprocal of the condition number of the matrix A are also output.

10.1 Program Text

Program Text (f07mpfe.f90)

10.2 Program Data

Program Data (f07mpfe.d)

10.3 Program Results

Program Results (f07mpfe.r)

F07 Chapter Contents
F07 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F07MRF (ZHETRF) : NAG Library, Mark 26

F07 Chapter Contents
F07 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F07MRF (ZHETRF)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F07MRF (ZHETRF) computes the Bunch–Kaufman factorization of a complex Hermitian indefinite matrix.

2 Specification

SUBROUTINE F07MRF ( UPLO, N, A, LDA, IPIV, WORK, LWORK, INFO)
INTEGER | N, LDA, IPIV(*), LWORK, INFO
COMPLEX (KIND=nag_wp) | A(LDA,*), WORK(max(1,LWORK))
CHARACTER(1) | UPLO
The routine may be called by its LAPACK name zhetrf.

3 Description

F07MRF (ZHETRF) factorizes a complex Hermitian matrix A, using the Bunch–Kaufman diagonal pivoting method. A is factorized either as A=PUD UHPT if UPLO='U' or A=PLD LHPT if UPLO='L', where P is a permutation matrix, U (or L) is a unit upper (or lower) triangular matrix and D is an Hermitian block diagonal matrix with 1 by 1 and 2 by 2 diagonal blocks; U (or L) has 2 by 2 unit diagonal blocks corresponding to the 2 by 2 blocks of D. Row and column interchanges are performed to ensure numerical stability while keeping the matrix Hermitian.
This method is suitable for Hermitian matrices which are not known to be positive definite. If A is in fact positive definite, no interchanges are performed and no 2 by 2 blocks occur in D.

4 References

Golub G H and Van Loan C F (1996) Matrix Computations (3rd Edition) Johns Hopkins University Press, Baltimore

5 Arguments

1:   UPLO – CHARACTER(1)Input
On entry: specifies whether the upper or lower triangular part of A is stored and how A is to be factorized.
UPLO='U'
The upper triangular part of A is stored and A is factorized as PUD UHPT, where U is upper triangular.
UPLO='L'
The lower triangular part of A is stored and A is factorized as PLD LHPT, where L is lower triangular.
Constraint: UPLO='U' or 'L'.
2:   N – INTEGERInput
On entry: n, the order of the matrix A.
Constraint: N≥0.
3:   A LDA* – COMPLEX (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array A must be at least max 1,N.
On entry: the n by n Hermitian indefinite matrix A.
  • If UPLO='U', the upper triangular part of A must be stored and the elements of the array below the diagonal are not referenced.
  • If UPLO='L', the lower triangular part of A must be stored and the elements of the array above the diagonal are not referenced.
On exit: the upper or lower triangle of A is overwritten by details of the block diagonal matrix D and the multipliers used to obtain the factor U or L as specified by UPLO.
4:   LDA – INTEGERInput
On entry: the first dimension of the array A as declared in the (sub)program from which F07MRF (ZHETRF) is called.
Constraint: LDA≥max 1,N.
5:   IPIV* – INTEGER arrayOutput
Note: the dimension of the array IPIV must be at least max 1,N.
On exit: details of the interchanges and the block structure of D. More precisely,
  • if IPIV i=k>0, d ii is a 1 by 1 pivot block and the ith row and column of A were interchanged with the kth row and column;
  • if UPLO='U' and IPIV i-1=IPIV i=-l<0, d i-1,i-1d-i,i-1 d-i,i-1d ii is a 2 by 2 pivot block and the i-1th row and column of A were interchanged with the lth row and column;
  • if UPLO='L' and IPIV i=IPIV i+1=-m<0, d iid i+1,id i+1,id i+1,i+1 is a 2 by 2 pivot block and the i+1th row and column of A were interchanged with the mth row and column.
6:   WORK max 1,LWORK – COMPLEX (KIND=nag_wp) arrayWorkspace
On exit: if INFO=0, WORK 1 contains the minimum value of LWORK required for optimum performance.
7:   LWORK – INTEGERInput
On entry: the dimension of the array WORK as declared in the (sub)program from which F07MRF (ZHETRF) is called, unless LWORK=-1, in which case a workspace query is assumed and the routine only calculates the optimal dimension of WORK (using the formula given below).
Suggested value: for optimum performance LWORK should be at least N×nb, where nb is the block size.
Constraint: LWORK≥1 or LWORK=-1.
8:   INFO – INTEGEROutput
On exit: INFO=0 unless the routine detects an error (see Section 6).

6 Error Indicators and Warnings

INFO<0
If INFO=-i, argument i had an illegal value. An explanatory message is output, and execution of the program is terminated.
INFO>0
Element value of the diagonal is exactly zero. The factorization has been completed, but the block diagonal matrix D is exactly singular, and division by zero will occur if it is used to solve a system of equations.

7 Accuracy

If UPLO='U', the computed factors U and D are the exact factors of a perturbed matrix A+E, where
E≤c n εP UDUH PT ,
c n is a modest linear function of n, and ε is the machine precision.
If UPLO='L', a similar statement holds for the computed factors L and D.

8 Parallelism and Performance

F07MRF (ZHETRF) makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The elements of D overwrite the corresponding elements of A; if D has 2 by 2 blocks, only the upper or lower triangle is stored, as specified by UPLO.
The unit diagonal elements of U or L and the 2 by 2 unit diagonal blocks are not stored. The remaining elements of U or L are stored in the corresponding columns of the array A, but additional row interchanges must be applied to recover U or L explicitly (this is seldom necessary). If IPIV i=i, for i=1,2,…,n (as is the case when A is positive definite), then U or L is stored explicitly (except for its unit diagonal elements which are equal to 1).
The total number of real floating-point operations is approximately 43 n 3.
A call to F07MRF (ZHETRF) may be followed by calls to the routines:
  • F07MSF (ZHETRS) to solve AX=B;
  • F07MUF (ZHECON) to estimate the condition number of A;
  • F07MWF (ZHETRI) to compute the inverse of A.
The real analogue of this routine is F07MDF (DSYTRF).

10 Example

This example computes the Bunch–Kaufman factorization of the matrix A, where
A= -1.36+0.00 i 1.58+0.90 i 2.21-0.21 i 3.91+1.50 i 1.58-0.90 i -8.87+0.00 i -1.84-0.03 i -1.78+1.18 i 2.21+0.21 i -1.84+0.03 i -4.63+0.00 i 0.11+0.11 i 3.91-1.50 i -1.78-1.18 i 0.11-0.11 i -1.84+0.00 i .

10.1 Program Text

Program Text (f07mrfe.f90)

10.2 Program Data

Program Data (f07mrfe.d)

10.3 Program Results

Program Results (f07mrfe.r)

F07 Chapter Contents
F07 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F07MSF (ZHETRS) : NAG Library, Mark 26

F07 Chapter Contents
F07 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F07MSF (ZHETRS)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F07MSF (ZHETRS) solves a complex Hermitian indefinite system of linear equations with multiple right-hand sides,
AX=B ,
where A has been factorized by F07MRF (ZHETRF).

2 Specification

SUBROUTINE F07MSF ( UPLO, N, NRHS, A, LDA, IPIV, B, LDB, INFO)
INTEGER | N, NRHS, LDA, IPIV(*), LDB, INFO
COMPLEX (KIND=nag_wp) | A(LDA,*), B(LDB,*)
CHARACTER(1) | UPLO
The routine may be called by its LAPACK name zhetrs.

3 Description

F07MSF (ZHETRS) is used to solve a complex Hermitian indefinite system of linear equations AX=B, this routine must be preceded by a call to F07MRF (ZHETRF) which computes the Bunch–Kaufman factorization of A.
If UPLO='U', A=PUD UHPT, where P is a permutation matrix, U is an upper triangular matrix and D is an Hermitian block diagonal matrix with 1 by 1 and 2 by 2 blocks; the solution X is computed by solving PUDY=B and then UHPT X=Y.
If UPLO='L', A=PLD LHPT, where L is a lower triangular matrix; the solution X is computed by solving PLDY=B and then LHPT X=Y.

4 References

Golub G H and Van Loan C F (1996) Matrix Computations (3rd Edition) Johns Hopkins University Press, Baltimore

5 Arguments

1:   UPLO – CHARACTER(1)Input
On entry: specifies how A has been factorized.
UPLO='U'
A=PUD UHPT, where U is upper triangular.
UPLO='L'
A=PLD LHPT, where L is lower triangular.
Constraint: UPLO='U' or 'L'.
2:   N – INTEGERInput
On entry: n, the order of the matrix A.
Constraint: N≥0.
3:   NRHS – INTEGERInput
On entry: r, the number of right-hand sides.
Constraint: NRHS≥0.
4:   A LDA* – COMPLEX (KIND=nag_wp) arrayInput
Note: the second dimension of the array A must be at least max 1,N.
On entry: details of the factorization of A, as returned by F07MRF (ZHETRF).
5:   LDA – INTEGERInput
On entry: the first dimension of the array A as declared in the (sub)program from which F07MSF (ZHETRS) is called.
Constraint: LDA≥max 1,N.
6:   IPIV* – INTEGER arrayInput
Note: the dimension of the array IPIV must be at least max 1,N.
On entry: details of the interchanges and the block structure of D, as returned by F07MRF (ZHETRF).
7:   B LDB* – COMPLEX (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array B must be at least max 1,NRHS.
On entry: the n by r right-hand side matrix B.
On exit: the n by r solution matrix X.
8:   LDB – INTEGERInput
On entry: the first dimension of the array B as declared in the (sub)program from which F07MSF (ZHETRS) is called.
Constraint: LDB≥max 1,N.
9:   INFO – INTEGEROutput
On exit: INFO=0 unless the routine detects an error (see Section 6).

6 Error Indicators and Warnings

INFO<0
If INFO=-i, argument i had an illegal value. An explanatory message is output, and execution of the program is terminated.

7 Accuracy

For each right-hand side vector b, the computed solution x is the exact solution of a perturbed system of equations A+E x=b, where
  • if UPLO='U', E≤c n εP UDUH PT;
  • if UPLO='L', E≤c n εP LDLH PT,
c n is a modest linear function of n, and ε is the machine precision.
If x^ is the true solution, then the computed solution x satisfies a forward error bound of the form
x-x^∞ x∞ ≤c n cond A,x ε
where cond A,x=A-1Ax∞/x∞≤cond A=A-1A∞≤κ∞A.
Note that cond A,x can be much smaller than cond A.
Forward and backward error bounds can be computed by calling F07MVF (ZHERFS), and an estimate for κ∞A (=κ 1 A) can be obtained by calling F07MUF (ZHECON).

8 Parallelism and Performance

F07MSF (ZHETRS) makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The total number of real floating-point operations is approximately 8⁢n 2 r.
This routine may be followed by a call to F07MVF (ZHERFS) to refine the solution and return an error estimate.
The real analogue of this routine is F07MEF (DSYTRS).

10 Example

This example solves the system of equations AX=B, where
A= -1.36+0.00 i 1.58+0.90 i 2.21-0.21 i 3.91+1.50 i 1.58-0.90 i -8.87+0.00 i -1.84-0.03 i -1.78+1.18 i 2.21+0.21 i -1.84+0.03 i -4.63+0.00 i 0.11+0.11 i 3.91-1.50 i -1.78-1.18 i 0.11-0.11 i -1.84+0.00 i
and
B= 7.79+0 5.48 i -35.39+18.01 i -0.77-16.05 i 4.23-70.02 i -9.58+0 3.88 i -24.79-0 8.40 i 2.98-10.18 i 28.68-39.89 i .
Here A is Hermitian indefinite and must first be factorized by F07MRF (ZHETRF).

10.1 Program Text

Program Text (f07msfe.f90)

10.2 Program Data

Program Data (f07msfe.d)

10.3 Program Results

Program Results (f07msfe.r)

F07 Chapter Contents
F07 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F07MUF (ZHECON) : NAG Library, Mark 26

F07 Chapter Contents
F07 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F07MUF (ZHECON)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F07MUF (ZHECON) estimates the condition number of a complex Hermitian indefinite matrix A, where A has been factorized by F07MRF (ZHETRF).

2 Specification

SUBROUTINE F07MUF ( UPLO, N, A, LDA, IPIV, ANORM, RCOND, WORK, INFO)
INTEGER | N, LDA, IPIV(*), INFO
REAL (KIND=nag_wp) | ANORM, RCOND
COMPLEX (KIND=nag_wp) | A(LDA,*), WORK(2*N)
CHARACTER(1) | UPLO
The routine may be called by its LAPACK name zhecon.

3 Description

F07MUF (ZHECON) estimates the condition number (in the 1-norm) of a complex Hermitian indefinite matrix A:
κ 1 A=A 1A-1 1 .
Since A is Hermitian, κ 1 A=κ∞A=A∞A-1∞.
Because κ 1 A is infinite if A is singular, the routine actually returns an estimate of the reciprocal of κ 1 A.
The routine should be preceded by a call to F06UCF to compute A 1 and a call to F07MRF (ZHETRF) to compute the Bunch–Kaufman factorization of A. The routine then uses Higham's implementation of Hager's method (see Higham (1988)) to estimate A-1 1.

4 References

Higham N J (1988) FORTRAN codes for estimating the one-norm of a real or complex matrix, with applications to condition estimation ACM Trans. Math. Software 14 381–396

5 Arguments

1:   UPLO – CHARACTER(1)Input
On entry: specifies how A has been factorized.
UPLO='U'
A=PUD UHPT, where U is upper triangular.
UPLO='L'
A=PLD LHPT, where L is lower triangular.
Constraint: UPLO='U' or 'L'.
2:   N – INTEGERInput
On entry: n, the order of the matrix A.
Constraint: N≥0.
3:   A LDA* – COMPLEX (KIND=nag_wp) arrayInput
Note: the second dimension of the array A must be at least max 1,N.
On entry: details of the factorization of A, as returned by F07MRF (ZHETRF).
4:   LDA – INTEGERInput
On entry: the first dimension of the array A as declared in the (sub)program from which F07MUF (ZHECON) is called.
Constraint: LDA≥max 1,N.
5:   IPIV* – INTEGER arrayInput
Note: the dimension of the array IPIV must be at least max 1,N.
On entry: details of the interchanges and the block structure of D, as returned by F07MRF (ZHETRF).
6:   ANORM – REAL (KIND=nag_wp)Input
On entry: the 1-norm of the original matrix A, which may be computed by calling F06UCF with its argument NORM='1'. ANORM must be computed either before calling F07MRF (ZHETRF) or else from a copy of the original matrix A.
Constraint: ANORM≥0.0.
7:   RCOND – REAL (KIND=nag_wp)Output
On exit: an estimate of the reciprocal of the condition number of A. RCOND is set to zero if exact singularity is detected or the estimate underflows. If RCOND is less than machine precision, A is singular to working precision.
8:   WORK 2×N – COMPLEX (KIND=nag_wp) arrayWorkspace
9:   INFO – INTEGEROutput
On exit: INFO=0 unless the routine detects an error (see Section 6).

6 Error Indicators and Warnings

INFO<0
If INFO=-i, argument i had an illegal value. An explanatory message is output, and execution of the program is terminated.

7 Accuracy

The computed estimate RCOND is never less than the true value ρ, and in practice is nearly always less than 10 ρ, although examples can be constructed where RCOND is much larger.

8 Parallelism and Performance

F07MUF (ZHECON) makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

A call to F07MUF (ZHECON) involves solving a number of systems of linear equations of the form Ax=b; the number is usually 5 and never more than 11. Each solution involves approximately 8⁢n 2 real floating-point operations but takes considerably longer than a call to F07MSF (ZHETRS) with one right-hand side, because extra care is taken to avoid overflow when A is approximately singular.
The real analogue of this routine is F07MGF (DSYCON).

10 Example

This example estimates the condition number in the 1-norm (or ∞-norm) of the matrix A, where
A= -1.36+0.00 i 1.58+0.90 i 2.21-0.21 i 3.91+1.50 i 1.58-0.90 i -8.87+0.00 i -1.84-0.03 i -1.78+1.18 i 2.21+0.21 i -1.84+0.03 i -4.63+0.00 i 0.11+0.11 i 3.91-1.50 i -1.78-1.18 i 0.11-0.11 i -1.84+0.00 i .
Here A is Hermitian indefinite and must first be factorized by F07MRF (ZHETRF). The true condition number in the 1-norm is 9.10.

10.1 Program Text

Program Text (f07mufe.f90)

10.2 Program Data

Program Data (f07mufe.d)

10.3 Program Results

Program Results (f07mufe.r)

F07 Chapter Contents
F07 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F07MVF (ZHERFS) : NAG Library, Mark 26

F07 Chapter Contents
F07 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F07MVF (ZHERFS)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F07MVF (ZHERFS) returns error bounds for the solution of a complex Hermitian indefinite system of linear equations with multiple right-hand sides, AX=B. It improves the solution by iterative refinement, in order to reduce the backward error as much as possible.

2 Specification

SUBROUTINE F07MVF ( UPLO, N, NRHS, A, LDA, AF, LDAF, IPIV, B, LDB, X, LDX, FERR, BERR, WORK, RWORK, INFO)
INTEGER | N, NRHS, LDA, LDAF, IPIV(*), LDB, LDX, INFO
REAL (KIND=nag_wp) | FERR(NRHS), BERR(NRHS), RWORK(N)
COMPLEX (KIND=nag_wp) | A(LDA,*), AF(LDAF,*), B(LDB,*), X(LDX,*), WORK(2*N)
CHARACTER(1) | UPLO
The routine may be called by its LAPACK name zherfs.

3 Description

F07MVF (ZHERFS) returns the backward errors and estimated bounds on the forward errors for the solution of a complex Hermitian indefinite system of linear equations with multiple right-hand sides AX=B. The routine handles each right-hand side vector (stored as a column of the matrix B) independently, so we describe the function of F07MVF (ZHERFS) in terms of a single right-hand side b and solution x.
Given a computed solution x, the routine computes the component-wise backward error β. This is the size of the smallest relative perturbation in each element of A and b such that x is the exact solution of a perturbed system
A+δA x=b+δb δ a ij≤β a ij   and   δ bi≤β bi .
Then the routine estimates a bound for the component-wise forward error in the computed solution, defined by:
maxi xi-x^i/maxi xi
where x^ is the true solution.
For details of the method, see the F07 Chapter Introduction.

4 References

Golub G H and Van Loan C F (1996) Matrix Computations (3rd Edition) Johns Hopkins University Press, Baltimore

5 Arguments

1:   UPLO – CHARACTER(1)Input
On entry: specifies whether the upper or lower triangular part of A is stored and how A is to be factorized.
UPLO='U'
The upper triangular part of A is stored and A is factorized as PUD UHPT, where U is upper triangular.
UPLO='L'
The lower triangular part of A is stored and A is factorized as PLD LHPT, where L is lower triangular.
Constraint: UPLO='U' or 'L'.
2:   N – INTEGERInput
On entry: n, the order of the matrix A.
Constraint: N≥0.
3:   NRHS – INTEGERInput
On entry: r, the number of right-hand sides.
Constraint: NRHS≥0.
4:   A LDA* – COMPLEX (KIND=nag_wp) arrayInput
Note: the second dimension of the array A must be at least max 1,N.
On entry: the n by n original Hermitian matrix A as supplied to F07MRF (ZHETRF).
5:   LDA – INTEGERInput
On entry: the first dimension of the array A as declared in the (sub)program from which F07MVF (ZHERFS) is called.
Constraint: LDA≥max 1,N.
6:   AF LDAF* – COMPLEX (KIND=nag_wp) arrayInput
Note: the second dimension of the array AF must be at least max 1,N.
On entry: details of the factorization of A, as returned by F07MRF (ZHETRF).
7:   LDAF – INTEGERInput
On entry: the first dimension of the array AF as declared in the (sub)program from which F07MVF (ZHERFS) is called.
Constraint: LDAF≥max 1,N.
8:   IPIV* – INTEGER arrayInput
Note: the dimension of the array IPIV must be at least max 1,N.
On entry: details of the interchanges and the block structure of D, as returned by F07MRF (ZHETRF).
9:   B LDB* – COMPLEX (KIND=nag_wp) arrayInput
Note: the second dimension of the array B must be at least max 1,NRHS.
On entry: the n by r right-hand side matrix B.
10:   LDB – INTEGERInput
On entry: the first dimension of the array B as declared in the (sub)program from which F07MVF (ZHERFS) is called.
Constraint: LDB≥max 1,N.
11:   X LDX* – COMPLEX (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array X must be at least max 1,NRHS.
On entry: the n by r solution matrix X, as returned by F07MSF (ZHETRS).
On exit: the improved solution matrix X.
12:   LDX – INTEGERInput
On entry: the first dimension of the array X as declared in the (sub)program from which F07MVF (ZHERFS) is called.
Constraint: LDX≥max 1,N.
13:   FERR NRHS – REAL (KIND=nag_wp) arrayOutput
On exit: FERR j contains an estimated error bound for the jth solution vector, that is, the jth column of X, for j=1,2,…,r.
14:   BERR NRHS – REAL (KIND=nag_wp) arrayOutput
On exit: BERR j contains the component-wise backward error bound β for the jth solution vector, that is, the jth column of X, for j=1,2,…,r.
15:   WORK 2×N – COMPLEX (KIND=nag_wp) arrayWorkspace
16:   RWORK N – REAL (KIND=nag_wp) arrayWorkspace
17:   INFO – INTEGEROutput
On exit: INFO=0 unless the routine detects an error (see Section 6).

6 Error Indicators and Warnings

INFO<0
If INFO=-i, argument i had an illegal value. An explanatory message is output, and execution of the program is terminated.

7 Accuracy

The bounds returned in FERR are not rigorous, because they are estimated, not computed exactly; but in practice they almost always overestimate the actual error.

8 Parallelism and Performance

F07MVF (ZHERFS) is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
F07MVF (ZHERFS) makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

For each right-hand side, computation of the backward error involves a minimum of 16⁢n 2 real floating-point operations. Each step of iterative refinement involves an additional 24⁢n 2 real operations. At most five steps of iterative refinement are performed, but usually only one or two steps are required.
Estimating the forward error involves solving a number of systems of linear equations of the form Ax=b; the number is usually 5 and never more than 11. Each solution involves approximately 8⁢n 2 real operations.
The real analogue of this routine is F07MHF (DSYRFS).

10 Example

This example solves the system of equations AX=B using iterative refinement and to compute the forward and backward error bounds, where
A= -1.36+0.00 i 1.58+0.90 i 2.21-0.21 i 3.91+1.50 i 1.58-0.90 i -8.87+0.00 i -1.84-0.03 i -1.78+1.18 i 2.21+0.21 i -1.84+0.03 i -4.63+0.00 i 0.11+0.11 i 3.91-1.50 i -1.78-1.18 i 0.11-0.11 i -1.84+0.00 i
and
B= 7.79+0 5.48 i -35.39+18.01 i -0.77-16.05 i 4.23-70.02 i -9.58+0 3.88 i -24.79-0 8.40 i 2.98-10.18 i 28.68-39.89 i .
Here A is Hermitian indefinite and must first be factorized by F07MRF (ZHETRF).

10.1 Program Text

Program Text (f07mvfe.f90)

10.2 Program Data

Program Data (f07mvfe.d)

10.3 Program Results

Program Results (f07mvfe.r)

F07 Chapter Contents
F07 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F07MWF (ZHETRI) : NAG Library, Mark 26

F07 Chapter Contents
F07 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F07MWF (ZHETRI)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F07MWF (ZHETRI) computes the inverse of a complex Hermitian indefinite matrix A, where A has been factorized by F07MRF (ZHETRF).

2 Specification

SUBROUTINE F07MWF ( UPLO, N, A, LDA, IPIV, WORK, INFO)
INTEGER | N, LDA, IPIV(*), INFO
COMPLEX (KIND=nag_wp) | A(LDA,*), WORK(N)
CHARACTER(1) | UPLO
The routine may be called by its LAPACK name zhetri.

3 Description

F07MWF (ZHETRI) is used to compute the inverse of a complex Hermitian indefinite matrix A, the routine must be preceded by a call to F07MRF (ZHETRF), which computes the Bunch–Kaufman factorization of A.
If UPLO='U', A=PUD UHPT and A-1 is computed by solving UHPT XPU=D-1 for X.
If UPLO='L', A=PLD LHPT and A-1 is computed by solving LHPT XPL=D-1 for X.

4 References

Du Croz J J and Higham N J (1992) Stability of methods for matrix inversion IMA J. Numer. Anal. 12 1–19

5 Arguments

1:   UPLO – CHARACTER(1)Input
On entry: specifies how A has been factorized.
UPLO='U'
A=PUD UHPT, where U is upper triangular.
UPLO='L'
A=PLD LHPT, where L is lower triangular.
Constraint: UPLO='U' or 'L'.
2:   N – INTEGERInput
On entry: n, the order of the matrix A.
Constraint: N≥0.
3:   A LDA* – COMPLEX (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array A must be at least max 1,N.
On entry: details of the factorization of A, as returned by F07MRF (ZHETRF).
On exit: the factorization is overwritten by the n by n Hermitian matrix A-1.
If UPLO='U', the upper triangle of A-1 is stored in the upper triangular part of the array.
If UPLO='L', the lower triangle of A-1 is stored in the lower triangular part of the array.
4:   LDA – INTEGERInput
On entry: the first dimension of the array A as declared in the (sub)program from which F07MWF (ZHETRI) is called.
Constraint: LDA≥max 1,N.
5:   IPIV* – INTEGER arrayInput
Note: the dimension of the array IPIV must be at least max 1,N.
On entry: details of the interchanges and the block structure of D, as returned by F07MRF (ZHETRF).
6:   WORK N – COMPLEX (KIND=nag_wp) arrayWorkspace
7:   INFO – INTEGEROutput
On exit: INFO=0 unless the routine detects an error (see Section 6).

6 Error Indicators and Warnings

-999<INFO<0
If INFO=-i, argument i had an illegal value. An explanatory message is output, and execution of the program is terminated.
INFO=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.
An explanatory message is output, and execution of the program is terminated.
INFO>0
Element value of the diagonal is exactly zero. D is singular and the inverse of A cannot be computed.

7 Accuracy

The computed inverse X satisfies a bound of the form
  • if UPLO='U', D UHPT XPU-I≤c n ε DUH PT X P U+DD-1;
  • if UPLO='L', D LHPT XPL-I≤c n ε DLH PT X P L+DD-1,
c n is a modest linear function of n, and ε is the machine precision.

8 Parallelism and Performance

F07MWF (ZHETRI) makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The total number of real floating-point operations is approximately 83 n 3.
The real analogue of this routine is F07MJF (DSYTRI).

10 Example

This example computes the inverse of the matrix A, where
A= -1.36+0.00 i 1.58+0.90 i 2.21-0.21 i 3.91+1.50 i 1.58-0.90 i -8.87+0.00 i -1.84-0.03 i -1.78+1.18 i 2.21+0.21 i -1.84+0.03 i -4.63+0.00 i 0.11+0.11 i 3.91-1.50 i -1.78-1.18 i 0.11-0.11 i -1.84+0.00 i .
Here A is Hermitian indefinite and must first be factorized by F07MRF (ZHETRF).

10.1 Program Text

Program Text (f07mwfe.f90)

10.2 Program Data

Program Data (f07mwfe.d)

10.3 Program Results

Program Results (f07mwfe.r)

F07 Chapter Contents
F07 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F07NNF (ZSYSV) : NAG Library, Mark 26

F07 Chapter Contents
F07 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F07NNF (ZSYSV)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F07NNF (ZSYSV) computes the solution to a complex system of linear equations
AX=B ,
where A is an n by n symmetric matrix and X and B are n by r matrices.

2 Specification

SUBROUTINE F07NNF ( UPLO, N, NRHS, A, LDA, IPIV, B, LDB, WORK, LWORK, INFO)
INTEGER | N, NRHS, LDA, IPIV(*), LDB, LWORK, INFO
COMPLEX (KIND=nag_wp) | A(LDA,*), B(LDB,*), WORK(max(1,LWORK))
CHARACTER(1) | UPLO
The routine may be called by its LAPACK name zsysv.

3 Description

F07NNF (ZSYSV) uses the diagonal pivoting method to factor A as A=UD UT if UPLO='U' or A=LD LT if UPLO='L', where U (or L) is a product of permutation and unit upper (lower) triangular matrices, and D is symmetric and block diagonal with 1 by 1 and 2 by 2 diagonal blocks. The factored form of A is then used to solve the system of equations AX=B.

4 References

Anderson E, Bai Z, Bischof C, Blackford S, Demmel J, Dongarra J J, Du Croz J J, Greenbaum A, Hammarling S, McKenney A and Sorensen D (1999) LAPACK Users' Guide (3rd Edition) SIAM, Philadelphia http://www.netlib.org/lapack/lug
Golub G H and Van Loan C F (1996) Matrix Computations (3rd Edition) Johns Hopkins University Press, Baltimore
Higham N J (2002) Accuracy and Stability of Numerical Algorithms (2nd Edition) SIAM, Philadelphia

5 Arguments

1:   UPLO – CHARACTER(1)Input
On entry: if UPLO='U', the upper triangle of A is stored.
If UPLO='L', the lower triangle of A is stored.
Constraint: UPLO='U' or 'L'.
2:   N – INTEGERInput
On entry: n, the number of linear equations, i.e., the order of the matrix A.
Constraint: N≥0.
3:   NRHS – INTEGERInput
On entry: r, the number of right-hand sides, i.e., the number of columns of the matrix B.
Constraint: NRHS≥0.
4:   A LDA* – COMPLEX (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array A must be at least max 1,N.
On entry: the n by n symmetric matrix A.
  • If UPLO='U', the upper triangular part of A must be stored and the elements of the array below the diagonal are not referenced.
  • If UPLO='L', the lower triangular part of A must be stored and the elements of the array above the diagonal are not referenced.
On exit: if INFO=0, the block diagonal matrix D and the multipliers used to obtain the factor U or L from the factorization A=UD UT or A=LD LT as computed by F07NRF (ZSYTRF).
5:   LDA – INTEGERInput
On entry: the first dimension of the array A as declared in the (sub)program from which F07NNF (ZSYSV) is called.
Constraint: LDA≥max 1,N.
6:   IPIV* – INTEGER arrayOutput
Note: the dimension of the array IPIV must be at least max 1,N.
On exit: details of the interchanges and the block structure of D. More precisely,
  • if IPIV i=k>0, d ii is a 1 by 1 pivot block and the ith row and column of A were interchanged with the kth row and column;
  • if UPLO='U' and IPIV i-1=IPIV i=-l<0, d i-1,i-1d-i,i-1 d-i,i-1d ii is a 2 by 2 pivot block and the i-1th row and column of A were interchanged with the lth row and column;
  • if UPLO='L' and IPIV i=IPIV i+1=-m<0, d iid i+1,id i+1,id i+1,i+1 is a 2 by 2 pivot block and the i+1th row and column of A were interchanged with the mth row and column.
7:   B LDB* – COMPLEX (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array B must be at least max 1,NRHS.
To solve the equations Ax=b, where b is a single right-hand side, B may be supplied as a one-dimensional array with length LDB=max 1,N.
On entry: the n by r right-hand side matrix B.
On exit: if INFO=0, the n by r solution matrix X.
8:   LDB – INTEGERInput
On entry: the first dimension of the array B as declared in the (sub)program from which F07NNF (ZSYSV) is called.
Constraint: LDB≥max 1,N.
9:   WORK max 1,LWORK – COMPLEX (KIND=nag_wp) arrayWorkspace
On exit: if INFO=0, WORK 1 returns the optimal LWORK.
10:   LWORK – INTEGERInput
On entry: the dimension of the array WORK as declared in the (sub)program from which F07NNF (ZSYSV) is called.
LWORK≥1, and for best performance LWORK≥max 1,N×nb, where nb is the optimal block size for F07NRF (ZSYTRF).
If LWORK=-1, a workspace query is assumed; the routine only calculates the optimal size of the WORK array, returns this value as the first entry of the WORK array, and no error message related to LWORK is issued.
11:   INFO – INTEGEROutput
On exit: INFO=0 unless the routine detects an error (see Section 6).

6 Error Indicators and Warnings

INFO<0
If INFO=-i, argument i had an illegal value. An explanatory message is output, and execution of the program is terminated.
INFO>0
Element value of the diagonal is exactly zero. The factorization has been completed, but the block diagonal matrix D is exactly singular, so the solution could not be computed.

7 Accuracy

The computed solution for a single right-hand side, x^ , satisfies an equation of the form
A+E x^=b ,
where
E 1 = O ε A 1
and ε is the machine precision. An approximate error bound for the computed solution is given by
x^-x 1 x 1 ≤ κ A E 1 A 1 ,
where κ A = A-1 1 A 1 , the condition number of A with respect to the solution of the linear equations. See Section 4.4 of Anderson et al. (1999) and Chapter 11 of Higham (2002) for further details.
F07NPF (ZSYSVX) is a comprehensive LAPACK driver that returns forward and backward error bounds and an estimate of the condition number. Alternatively, F04DHF solves Ax=b and returns a forward error bound and condition estimate. F04DHF calls F07NNF (ZSYSV) to solve the equations.

8 Parallelism and Performance

F07NNF (ZSYSV) makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The total number of floating-point operations is approximately 43 n 3 + 8⁢n 2 r , where r is the number of right-hand sides.
The real analogue of this routine is F07MAF (DSYSV). The complex Hermitian analogue of this routine is F07MNF (ZHESV).

10 Example

This example solves the equations
Ax=b ,
where A is the complex symmetric matrix
A = -0.56+0.12 i -1.54-2.86 i 5.32-1.59 i 3.80+0.92 i -1.54-2.86 i -2.83-0.03 i -3.52+0.58 i -7.86-2.96 i 5.32-1.59 i -3.52+0.58 i 8.86+1.81 i 5.14-0.64 i 3.80+0.92 i -7.86-2.96 i 5.14-0.64 i -0.39-0.71 i
and
b = -6.43+19.24 i -0.49-0 1.47 i -48.18+66.00 i -55.64+41.22 i .
Details of the factorization of A are also output.

10.1 Program Text

Program Text (f07nnfe.f90)

10.2 Program Data

Program Data (f07nnfe.d)

10.3 Program Results

Program Results (f07nnfe.r)

F07 Chapter Contents
F07 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F07NPF (ZSYSVX) : NAG Library, Mark 26

F07 Chapter Contents
F07 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F07NPF (ZSYSVX)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F07NPF (ZSYSVX) uses the diagonal pivoting factorization to compute the solution to a complex system of linear equations
AX=B ,
where A is an n by n symmetric matrix and X and B are n by r matrices. Error bounds on the solution and a condition estimate are also provided.

2 Specification

SUBROUTINE F07NPF ( FACT, UPLO, N, NRHS, A, LDA, AF, LDAF, IPIV, B, LDB, X, LDX, RCOND, FERR, BERR, WORK, LWORK, RWORK, INFO)
INTEGER | N, NRHS, LDA, LDAF, IPIV(*), LDB, LDX, LWORK, INFO
REAL (KIND=nag_wp) | RCOND, FERR(*), BERR(*), RWORK(*)
COMPLEX (KIND=nag_wp) | A(LDA,*), AF(LDAF,*), B(LDB,*), X(LDX,*), WORK(max(1,LWORK))
CHARACTER(1) | FACT, UPLO
The routine may be called by its LAPACK name zsysvx.

3 Description

F07NPF (ZSYSVX) performs the following steps:
1. | If FACT='N', the diagonal pivoting method is used to factor A. The form of the factorization is A=UD UT if UPLO='U' or A=LD LT if UPLO='L', where U (or L) is a product of permutation and unit upper (lower) triangular matrices, and D is symmetric and block diagonal with 1 by 1 and 2 by 2 diagonal blocks.
2. | If some d ii=0, so that D is exactly singular, then the routine returns with INFO=i. Otherwise, the factored form of A is used to estimate the condition number of the matrix A. If the reciprocal of the condition number is less than machine precision, INFO=N+1 is returned as a warning, but the routine still goes on to solve for X and compute error bounds as described below.
3. | The system of equations is solved for X using the factored form of A.
4. | Iterative refinement is applied to improve the computed solution matrix and to calculate error bounds and backward error estimates for it.

4 References

Anderson E, Bai Z, Bischof C, Blackford S, Demmel J, Dongarra J J, Du Croz J J, Greenbaum A, Hammarling S, McKenney A and Sorensen D (1999) LAPACK Users' Guide (3rd Edition) SIAM, Philadelphia http://www.netlib.org/lapack/lug
Golub G H and Van Loan C F (1996) Matrix Computations (3rd Edition) Johns Hopkins University Press, Baltimore
Higham N J (2002) Accuracy and Stability of Numerical Algorithms (2nd Edition) SIAM, Philadelphia

5 Arguments

1:   FACT – CHARACTER(1)Input
On entry: specifies whether or not the factorized form of the matrix A has been supplied.
FACT='F'
AF and IPIV contain the factorized form of the matrix A. AF and IPIV will not be modified.
FACT='N'
The matrix A will be copied to AF and factorized.
Constraint: FACT='F' or 'N'.
2:   UPLO – CHARACTER(1)Input
On entry: if UPLO='U', the upper triangle of A is stored.
If UPLO='L', the lower triangle of A is stored.
Constraint: UPLO='U' or 'L'.
3:   N – INTEGERInput
On entry: n, the number of linear equations, i.e., the order of the matrix A.
Constraint: N≥0.
4:   NRHS – INTEGERInput
On entry: r, the number of right-hand sides, i.e., the number of columns of the matrix B.
Constraint: NRHS≥0.
5:   A LDA* – COMPLEX (KIND=nag_wp) arrayInput
Note: the second dimension of the array A must be at least max 1,N.
On entry: the n by n symmetric matrix A.
  • If UPLO='U', the upper triangular part of A must be stored and the elements of the array below the diagonal are not referenced.
  • If UPLO='L', the lower triangular part of A must be stored and the elements of the array above the diagonal are not referenced.
6:   LDA – INTEGERInput
On entry: the first dimension of the array A as declared in the (sub)program from which F07NPF (ZSYSVX) is called.
Constraint: LDA≥max 1,N.
7:   AF LDAF* – COMPLEX (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array AF must be at least max 1,N.
On entry: if FACT='F', AF contains the block diagonal matrix D and the multipliers used to obtain the factor U or L from the factorization A=UD UT or A=LD LT as computed by F07NRF (ZSYTRF).
On exit: if FACT='N', AF returns the block diagonal matrix D and the multipliers used to obtain the factor U or L from the factorization A=UD UT or A=LD LT.
8:   LDAF – INTEGERInput
On entry: the first dimension of the array AF as declared in the (sub)program from which F07NPF (ZSYSVX) is called.
Constraint: LDAF≥max 1,N.
9:   IPIV* – INTEGER arrayInput/Output
Note: the dimension of the array IPIV must be at least max 1,N.
On entry: if FACT='F', IPIV contains details of the interchanges and the block structure of D, as determined by F07NRF (ZSYTRF).
  • if IPIV i=k>0, d ii is a 1 by 1 pivot block and the ith row and column of A were interchanged with the kth row and column;
  • if UPLO='U' and IPIV i-1=IPIV i=-l<0, d i-1,i-1d-i,i-1 d-i,i-1d ii is a 2 by 2 pivot block and the i-1th row and column of A were interchanged with the lth row and column;
  • if UPLO='L' and IPIV i=IPIV i+1=-m<0, d iid i+1,id i+1,id i+1,i+1 is a 2 by 2 pivot block and the i+1th row and column of A were interchanged with the mth row and column.
On exit: if FACT='N', IPIV contains details of the interchanges and the block structure of D, as determined by F07NRF (ZSYTRF), as described above.
10:   B LDB* – COMPLEX (KIND=nag_wp) arrayInput
Note: the second dimension of the array B must be at least max 1,NRHS.
On entry: the n by r right-hand side matrix B.
11:   LDB – INTEGERInput
On entry: the first dimension of the array B as declared in the (sub)program from which F07NPF (ZSYSVX) is called.
Constraint: LDB≥max 1,N.
12:   X LDX* – COMPLEX (KIND=nag_wp) arrayOutput
Note: the second dimension of the array X must be at least max 1,NRHS.
On exit: if INFO=0 or N+1, the n by r solution matrix X.
13:   LDX – INTEGERInput
On entry: the first dimension of the array X as declared in the (sub)program from which F07NPF (ZSYSVX) is called.
Constraint: LDX≥max 1,N.
14:   RCOND – REAL (KIND=nag_wp)Output
On exit: the estimate of the reciprocal condition number of the matrix A. If RCOND=0.0, the matrix may be exactly singular. This condition is indicated by INFO>0 and INFO≤N. Otherwise, if RCOND is less than the machine precision, the matrix is singular to working precision. This condition is indicated by INFO=N+1.
15:   FERR* – REAL (KIND=nag_wp) arrayOutput
Note: the dimension of the array FERR must be at least max 1,NRHS.
On exit: if INFO=0 or N+1, an estimate of the forward error bound for each computed solution vector, such that x^j-xj∞/xj∞≤FERR j where x^j is the jth column of the computed solution returned in the array X and xj is the corresponding column of the exact solution X. The estimate is as reliable as the estimate for RCOND, and is almost always a slight overestimate of the true error.
16:   BERR* – REAL (KIND=nag_wp) arrayOutput
Note: the dimension of the array BERR must be at least max 1,NRHS.
On exit: if INFO=0 or N+1, an estimate of the component-wise relative backward error of each computed solution vector x^j (i.e., the smallest relative change in any element of A or B that makes x^j an exact solution).
17:   WORK max 1,LWORK – COMPLEX (KIND=nag_wp) arrayWorkspace
On exit: if INFO=0, WORK 1 returns the optimal LWORK.
18:   LWORK – INTEGERInput
On entry: the dimension of the array WORK as declared in the (sub)program from which F07NPF (ZSYSVX) is called.
LWORK≥max 1,2×N, and for best performance, when FACT='N', LWORK≥max 1,2×N,N×nb, where nb is the optimal block size for F07NRF (ZSYTRF).
If LWORK=-1, a workspace query is assumed; the routine only calculates the optimal size of the WORK array, returns this value as the first entry of the WORK array, and no error message related to LWORK is issued.
19:   RWORK* – REAL (KIND=nag_wp) arrayWorkspace
Note: the dimension of the array RWORK must be at least max 1,N.
20:   INFO – INTEGEROutput
On exit: INFO=0 unless the routine detects an error (see Section 6).

6 Error Indicators and Warnings

INFO<0
If INFO=-i, argument i had an illegal value. An explanatory message is output, and execution of the program is terminated.
INFO>0 and INFO≤N
Element value of the diagonal is exactly zero. The factorization has been completed, but the factor D is exactly singular, so the solution and error bounds could not be computed. RCOND=0.0 is returned.
INFO=N+1
D is nonsingular, but RCOND is less than machine precision, meaning that the matrix is singular to working precision. Nevertheless, the solution and error bounds are computed because there are a number of situations where the computed solution can be more accurate than the value of RCOND would suggest.

7 Accuracy

For each right-hand side vector b, the computed solution x^ is the exact solution of a perturbed system of equations A+E x^=b, where
E 1 = O ε A 1 ,
where ε is the machine precision. See Chapter 11 of Higham (2002) for further details.
If x^ is the true solution, then the computed solution x satisfies a forward error bound of the form
x-x^∞ x^∞ ≤ wc cond A,x^,b
where cond A,x^,b = A-1 A x^ + b ∞/ x^∞ ≤ cond A = A-1 A ∞≤κ∞ A. If x^ is the j th column of X , then wc is returned in BERR j and a bound on x - x^ ∞ / x^ ∞ is returned in FERR j . See Section 4.4 of Anderson et al. (1999) for further details.

8 Parallelism and Performance

F07NPF (ZSYSVX) is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
F07NPF (ZSYSVX) makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The factorization of A requires approximately 43 n 3 floating-point operations.
For each right-hand side, computation of the backward error involves a minimum of 16⁢n 2 floating-point operations. Each step of iterative refinement involves an additional 24⁢n 2 operations. At most five steps of iterative refinement are performed, but usually only one or two steps are required. Estimating the forward error involves solving a number of systems of equations of the form Ax=b ; the number is usually 4 or 5 and never more than 11. Each solution involves approximately 8⁢n 2 operations.
The real analogue of this routine is F07MBF (DSYSVX). The complex Hermitian analogue of this routine is F07MPF (ZHESVX).

10 Example

This example solves the equations
AX=B ,
where A is the complex symmetric matrix
A = -0.56+0.12 i -1.54-2.86 i 5.32-1.59 i 3.80+0.92 i -1.54-2.86 i -2.83-0.03 i -3.52+0.58 i -7.86-2.96 i 5.32-1.59 i -3.52+0.58 i 8.86+1.81 i 5.14-0.64 i 3.80+0.92 i -7.86-2.96 i 5.14-0.64 i -0.39-0.71 i
and
B = -6.43+19.24 i -4.59-35.53 i -0.49-0 1.47 i 6.95+20.49 i -48.18+66.00 i -12.08-27.02 i -55.64+41.22 i -19.09-35.97 i .
Error estimates for the solutions, and an estimate of the reciprocal of the condition number of the matrix A are also output.

10.1 Program Text

Program Text (f07npfe.f90)

10.2 Program Data

Program Data (f07npfe.d)

10.3 Program Results

Program Results (f07npfe.r)

F07 Chapter Contents
F07 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F07NRF (ZSYTRF) : NAG Library, Mark 26

F07 Chapter Contents
F07 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F07NRF (ZSYTRF)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F07NRF (ZSYTRF) computes the Bunch–Kaufman factorization of a complex symmetric matrix.

2 Specification

SUBROUTINE F07NRF ( UPLO, N, A, LDA, IPIV, WORK, LWORK, INFO)
INTEGER | N, LDA, IPIV(*), LWORK, INFO
COMPLEX (KIND=nag_wp) | A(LDA,*), WORK(max(1,LWORK))
CHARACTER(1) | UPLO
The routine may be called by its LAPACK name zsytrf.

3 Description

F07NRF (ZSYTRF) factorizes a complex symmetric matrix A, using the Bunch–Kaufman diagonal pivoting method. A is factorized as either A=PUD UTPT if UPLO='U' or A=PLD LTPT if UPLO='L', where P is a permutation matrix, U (or L) is a unit upper (or lower) triangular matrix and D is a symmetric block diagonal matrix with 1 by 1 and 2 by 2 diagonal blocks; U (or L) has 2 by 2 unit diagonal blocks corresponding to the 2 by 2 blocks of D. Row and column interchanges are performed to ensure numerical stability while preserving symmetry.

4 References

Golub G H and Van Loan C F (1996) Matrix Computations (3rd Edition) Johns Hopkins University Press, Baltimore

5 Arguments

1:   UPLO – CHARACTER(1)Input
On entry: specifies whether the upper or lower triangular part of A is stored and how A is to be factorized.
UPLO='U'
The upper triangular part of A is stored and A is factorized as PUD UTPT, where U is upper triangular.
UPLO='L'
The lower triangular part of A is stored and A is factorized as PLD LTPT, where L is lower triangular.
Constraint: UPLO='U' or 'L'.
2:   N – INTEGERInput
On entry: n, the order of the matrix A.
Constraint: N≥0.
3:   A LDA* – COMPLEX (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array A must be at least max 1,N.
On entry: the n by n symmetric indefinite matrix A.
  • If UPLO='U', the upper triangular part of A must be stored and the elements of the array below the diagonal are not referenced.
  • If UPLO='L', the lower triangular part of A must be stored and the elements of the array above the diagonal are not referenced.
On exit: the upper or lower triangle of A is overwritten by details of the block diagonal matrix D and the multipliers used to obtain the factor U or L as specified by UPLO.
4:   LDA – INTEGERInput
On entry: the first dimension of the array A as declared in the (sub)program from which F07NRF (ZSYTRF) is called.
Constraint: LDA≥max 1,N.
5:   IPIV* – INTEGER arrayOutput
Note: the dimension of the array IPIV must be at least max 1,N.
On exit: details of the interchanges and the block structure of D. More precisely,
  • if IPIV i=k>0, d ii is a 1 by 1 pivot block and the ith row and column of A were interchanged with the kth row and column;
  • if UPLO='U' and IPIV i-1=IPIV i=-l<0, d i-1,i-1d-i,i-1 d-i,i-1d ii is a 2 by 2 pivot block and the i-1th row and column of A were interchanged with the lth row and column;
  • if UPLO='L' and IPIV i=IPIV i+1=-m<0, d iid i+1,id i+1,id i+1,i+1 is a 2 by 2 pivot block and the i+1th row and column of A were interchanged with the mth row and column.
6:   WORK max 1,LWORK – COMPLEX (KIND=nag_wp) arrayWorkspace
On exit: if INFO=0, WORK 1 contains the minimum value of LWORK required for optimum performance.
7:   LWORK – INTEGERInput
On entry: the dimension of the array WORK as declared in the (sub)program from which F07NRF (ZSYTRF) is called, unless LWORK=-1, in which case a workspace query is assumed and the routine only calculates the optimal dimension of WORK (using the formula given below).
Suggested value: for optimum performance LWORK should be at least N×nb, where nb is the block size.
Constraint: LWORK≥1 or LWORK=-1.
8:   INFO – INTEGEROutput
On exit: INFO=0 unless the routine detects an error (see Section 6).

6 Error Indicators and Warnings

INFO<0
If INFO=-i, argument i had an illegal value. An explanatory message is output, and execution of the program is terminated.
INFO>0
Element value of the diagonal is exactly zero. The factorization has been completed, but the block diagonal matrix D is exactly singular, and division by zero will occur if it is used to solve a system of equations.

7 Accuracy

If UPLO='U', the computed factors U and D are the exact factors of a perturbed matrix A+E, where
E≤c n εP UDUT PT ,
c n is a modest linear function of n, and ε is the machine precision.
If UPLO='L', a similar statement holds for the computed factors L and D.

8 Parallelism and Performance

F07NRF (ZSYTRF) makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The elements of D overwrite the corresponding elements of A; if D has 2 by 2 blocks, only the upper or lower triangle is stored, as specified by UPLO.
The unit diagonal elements of U or L and the 2 by 2 unit diagonal blocks are not stored. The remaining elements of U or L are stored in the corresponding columns of the array A, but additional row interchanges must be applied to recover U or L explicitly (this is seldom necessary). If IPIV i=i, for i=1,2,…,n, then U or L is stored explicitly (except for its unit diagonal elements which are equal to 1).
The total number of real floating-point operations is approximately 43 n 3.
A call to F07NRF (ZSYTRF) may be followed by calls to the routines:
  • F07NSF (ZSYTRS) to solve AX=B;
  • F07NUF (ZSYCON) to estimate the condition number of A;
  • F07NWF (ZSYTRI) to compute the inverse of A.
The real analogue of this routine is F07MDF (DSYTRF).

10 Example

This example computes the Bunch–Kaufman factorization of the matrix A, where
A= -0.39-0.71 i 5.14-0.64 i -7.86-2.96 i 3.80+0.92 i 5.14-0.64 i 8.86+1.81 i -3.52+0.58 i 5.32-1.59 i -7.86-2.96 i -3.52+0.58 i -2.83-0.03 i -1.54-2.86 i 3.80+0.92 i 5.32-1.59 i -1.54-2.86 i -0.56+0.12 i .

10.1 Program Text

Program Text (f07nrfe.f90)

10.2 Program Data

Program Data (f07nrfe.d)

10.3 Program Results

Program Results (f07nrfe.r)

F07 Chapter Contents
F07 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F07NSF (ZSYTRS) : NAG Library, Mark 26

F07 Chapter Contents
F07 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F07NSF (ZSYTRS)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F07NSF (ZSYTRS) solves a complex symmetric system of linear equations with multiple right-hand sides,
AX=B ,
where A has been factorized by F07NRF (ZSYTRF).

2 Specification

SUBROUTINE F07NSF ( UPLO, N, NRHS, A, LDA, IPIV, B, LDB, INFO)
INTEGER | N, NRHS, LDA, IPIV(*), LDB, INFO
COMPLEX (KIND=nag_wp) | A(LDA,*), B(LDB,*)
CHARACTER(1) | UPLO
The routine may be called by its LAPACK name zsytrs.

3 Description

F07NSF (ZSYTRS) is used to solve a complex symmetric system of linear equations AX=B, this routine must be preceded by a call to F07NRF (ZSYTRF) which computes the Bunch–Kaufman factorization of A.
If UPLO='U', A=PUD UTPT, where P is a permutation matrix, U is an upper triangular matrix and D is a symmetric block diagonal matrix with 1 by 1 and 2 by 2 blocks; the solution X is computed by solving PUDY=B and then UTPT X=Y.
If UPLO='L', A=PLD LTPT, where L is a lower triangular matrix; the solution X is computed by solving PLDY=B and then LTPT X=Y.

4 References

Golub G H and Van Loan C F (1996) Matrix Computations (3rd Edition) Johns Hopkins University Press, Baltimore

5 Arguments

1:   UPLO – CHARACTER(1)Input
On entry: specifies how A has been factorized.
UPLO='U'
A=PUD UTPT, where U is upper triangular.
UPLO='L'
A=PLD LTPT, where L is lower triangular.
Constraint: UPLO='U' or 'L'.
2:   N – INTEGERInput
On entry: n, the order of the matrix A.
Constraint: N≥0.
3:   NRHS – INTEGERInput
On entry: r, the number of right-hand sides.
Constraint: NRHS≥0.
4:   A LDA* – COMPLEX (KIND=nag_wp) arrayInput
Note: the second dimension of the array A must be at least max 1,N.
On entry: details of the factorization of A, as returned by F07NRF (ZSYTRF).
5:   LDA – INTEGERInput
On entry: the first dimension of the array A as declared in the (sub)program from which F07NSF (ZSYTRS) is called.
Constraint: LDA≥max 1,N.
6:   IPIV* – INTEGER arrayInput
Note: the dimension of the array IPIV must be at least max 1,N.
On entry: details of the interchanges and the block structure of D, as returned by F07NRF (ZSYTRF).
7:   B LDB* – COMPLEX (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array B must be at least max 1,NRHS.
On entry: the n by r right-hand side matrix B.
On exit: the n by r solution matrix X.
8:   LDB – INTEGERInput
On entry: the first dimension of the array B as declared in the (sub)program from which F07NSF (ZSYTRS) is called.
Constraint: LDB≥max 1,N.
9:   INFO – INTEGEROutput
On exit: INFO=0 unless the routine detects an error (see Section 6).

6 Error Indicators and Warnings

INFO<0
If INFO=-i, argument i had an illegal value. An explanatory message is output, and execution of the program is terminated.

7 Accuracy

For each right-hand side vector b, the computed solution x is the exact solution of a perturbed system of equations A+E x=b, where
  • if UPLO='U', E≤c n εP UDUT PT;
  • if UPLO='L', E≤c n εP LDLT PT,
c n is a modest linear function of n, and ε is the machine precision.
If x^ is the true solution, then the computed solution x satisfies a forward error bound of the form
x-x^∞ x∞ ≤c n cond A,x ε
where cond A,x=A-1Ax∞/x∞≤cond A=A-1A∞≤κ∞A.
Note that cond A,x can be much smaller than cond A.
Forward and backward error bounds can be computed by calling F07NVF (ZSYRFS), and an estimate for κ∞A (=κ 1 A) can be obtained by calling F07NUF (ZSYCON).

8 Parallelism and Performance

F07NSF (ZSYTRS) makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The total number of real floating-point operations is approximately 8⁢n 2 r.
This routine may be followed by a call to F07NVF (ZSYRFS) to refine the solution and return an error estimate.
The real analogue of this routine is F07MEF (DSYTRS).

10 Example

This example solves the system of equations AX=B, where
A= -0.39-0.71 i 5.14-0.64 i -7.86-2.96 i 3.80+0.92 i 5.14-0.64 i 8.86+1.81 i -3.52+0.58 i 5.32-1.59 i -7.86-2.96 i -3.52+0.58 i -2.83-0.03 i -1.54-2.86 i 3.80+0.92 i 5.32-1.59 i -1.54-2.86 i -0.56+0.12 i
and
B= -55.64+41.22 i -19.09-35.97 i -48.18+66.00 i -12.08-27.02 i -0.49-0 1.47 i 6.95+20.49 i -6.43+19.24 i -4.59-35.53 i .
Here A is symmetric and must first be factorized by F07NRF (ZSYTRF).

10.1 Program Text

Program Text (f07nsfe.f90)

10.2 Program Data

Program Data (f07nsfe.d)

10.3 Program Results

Program Results (f07nsfe.r)

F07 Chapter Contents
F07 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F07NUF (ZSYCON) : NAG Library, Mark 26

F07 Chapter Contents
F07 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F07NUF (ZSYCON)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F07NUF (ZSYCON) estimates the condition number of a complex symmetric matrix A, where A has been factorized by F07NRF (ZSYTRF).

2 Specification

SUBROUTINE F07NUF ( UPLO, N, A, LDA, IPIV, ANORM, RCOND, WORK, INFO)
INTEGER | N, LDA, IPIV(*), INFO
REAL (KIND=nag_wp) | ANORM, RCOND
COMPLEX (KIND=nag_wp) | A(LDA,*), WORK(2*N)
CHARACTER(1) | UPLO
The routine may be called by its LAPACK name zsycon.

3 Description

F07NUF (ZSYCON) estimates the condition number (in the 1-norm) of a complex symmetric matrix A:
κ 1 A=A 1A-1 1 .
Since A is symmetric, κ 1 A=κ∞A=A∞A-1∞.
Because κ 1 A is infinite if A is singular, the routine actually returns an estimate of the reciprocal of κ 1 A.
The routine should be preceded by a call to F06UFF to compute A 1 and a call to F07NRF (ZSYTRF) to compute the Bunch–Kaufman factorization of A. The routine then uses Higham's implementation of Hager's method (see Higham (1988)) to estimate A-1 1.

4 References

Higham N J (1988) FORTRAN codes for estimating the one-norm of a real or complex matrix, with applications to condition estimation ACM Trans. Math. Software 14 381–396

5 Arguments

1:   UPLO – CHARACTER(1)Input
On entry: specifies how A has been factorized.
UPLO='U'
A=PUD UTPT, where U is upper triangular.
UPLO='L'
A=PLD LTPT, where L is lower triangular.
Constraint: UPLO='U' or 'L'.
2:   N – INTEGERInput
On entry: n, the order of the matrix A.
Constraint: N≥0.
3:   A LDA* – COMPLEX (KIND=nag_wp) arrayInput
Note: the second dimension of the array A must be at least max 1,N.
On entry: details of the factorization of A, as returned by F07NRF (ZSYTRF).
4:   LDA – INTEGERInput
On entry: the first dimension of the array A as declared in the (sub)program from which F07NUF (ZSYCON) is called.
Constraint: LDA≥max 1,N.
5:   IPIV* – INTEGER arrayInput
Note: the dimension of the array IPIV must be at least max 1,N.
On entry: details of the interchanges and the block structure of D, as returned by F07NRF (ZSYTRF).
6:   ANORM – REAL (KIND=nag_wp)Input
On entry: the 1-norm of the original matrix A, which may be computed by calling F06UFF with its argument NORM='1'. ANORM must be computed either before calling F07NRF (ZSYTRF) or else from a copy of the original matrix A.
Constraint: ANORM≥0.0.
7:   RCOND – REAL (KIND=nag_wp)Output
On exit: an estimate of the reciprocal of the condition number of A. RCOND is set to zero if exact singularity is detected or the estimate underflows. If RCOND is less than machine precision, A is singular to working precision.
8:   WORK 2×N – COMPLEX (KIND=nag_wp) arrayWorkspace
9:   INFO – INTEGEROutput
On exit: INFO=0 unless the routine detects an error (see Section 6).

6 Error Indicators and Warnings

INFO<0
If INFO=-i, argument i had an illegal value. An explanatory message is output, and execution of the program is terminated.

7 Accuracy

The computed estimate RCOND is never less than the true value ρ, and in practice is nearly always less than 10 ρ, although examples can be constructed where RCOND is much larger.

8 Parallelism and Performance

F07NUF (ZSYCON) makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

A call to F07NUF (ZSYCON) involves solving a number of systems of linear equations of the form Ax=b; the number is usually 5 and never more than 11. Each solution involves approximately 8⁢n 2 real floating-point operations but takes considerably longer than a call to F07NSF (ZSYTRS) with one right-hand side, because extra care is taken to avoid overflow when A is approximately singular.
The real analogue of this routine is F07MGF (DSYCON).

10 Example

This example estimates the condition number in the 1-norm (or ∞-norm) of the matrix A, where
A= -0.39-0.71 i 5.14-0.64 i -7.86-2.96 i 3.80+0.92 i 5.14-0.64 i 8.86+1.81 i -3.52+0.58 i 5.32-1.59 i -7.86-2.96 i -3.52+0.58 i -2.83-0.03 i -1.54-2.86 i 3.80+0.92 i 5.32-1.59 i -1.54-2.86 i -0.56+0.12 i .
Here A is symmetric and must first be factorized by F07NRF (ZSYTRF). The true condition number in the 1-norm is 32.92.

10.1 Program Text

Program Text (f07nufe.f90)

10.2 Program Data

Program Data (f07nufe.d)

10.3 Program Results

Program Results (f07nufe.r)

F07 Chapter Contents
F07 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F07NVF (ZSYRFS) : NAG Library, Mark 26

F07 Chapter Contents
F07 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F07NVF (ZSYRFS)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F07NVF (ZSYRFS) returns error bounds for the solution of a complex symmetric system of linear equations with multiple right-hand sides, AX=B. It improves the solution by iterative refinement, in order to reduce the backward error as much as possible.

2 Specification

SUBROUTINE F07NVF ( UPLO, N, NRHS, A, LDA, AF, LDAF, IPIV, B, LDB, X, LDX, FERR, BERR, WORK, RWORK, INFO)
INTEGER | N, NRHS, LDA, LDAF, IPIV(*), LDB, LDX, INFO
REAL (KIND=nag_wp) | FERR(NRHS), BERR(NRHS), RWORK(N)
COMPLEX (KIND=nag_wp) | A(LDA,*), AF(LDAF,*), B(LDB,*), X(LDX,*), WORK(2*N)
CHARACTER(1) | UPLO
The routine may be called by its LAPACK name zsyrfs.

3 Description

F07NVF (ZSYRFS) returns the backward errors and estimated bounds on the forward errors for the solution of a complex symmetric system of linear equations with multiple right-hand sides AX=B. The routine handles each right-hand side vector (stored as a column of the matrix B) independently, so we describe the function of F07NVF (ZSYRFS) in terms of a single right-hand side b and solution x.
Given a computed solution x, the routine computes the component-wise backward error β. This is the size of the smallest relative perturbation in each element of A and b such that x is the exact solution of a perturbed system
A+δA x=b+δb δ a ij≤β a ij   and   δ bi≤β bi .
Then the routine estimates a bound for the component-wise forward error in the computed solution, defined by:
maxi xi-x^i/maxi xi
where x^ is the true solution.
For details of the method, see the F07 Chapter Introduction.

4 References

Golub G H and Van Loan C F (1996) Matrix Computations (3rd Edition) Johns Hopkins University Press, Baltimore

5 Arguments

1:   UPLO – CHARACTER(1)Input
On entry: specifies whether the upper or lower triangular part of A is stored and how A is to be factorized.
UPLO='U'
The upper triangular part of A is stored and A is factorized as PUD UTPT, where U is upper triangular.
UPLO='L'
The lower triangular part of A is stored and A is factorized as PLD LTPT, where L is lower triangular.
Constraint: UPLO='U' or 'L'.
2:   N – INTEGERInput
On entry: n, the order of the matrix A.
Constraint: N≥0.
3:   NRHS – INTEGERInput
On entry: r, the number of right-hand sides.
Constraint: NRHS≥0.
4:   A LDA* – COMPLEX (KIND=nag_wp) arrayInput
Note: the second dimension of the array A must be at least max 1,N.
On entry: the n by n original symmetric matrix A as supplied to F07NRF (ZSYTRF).
5:   LDA – INTEGERInput
On entry: the first dimension of the array A as declared in the (sub)program from which F07NVF (ZSYRFS) is called.
Constraint: LDA≥max 1,N.
6:   AF LDAF* – COMPLEX (KIND=nag_wp) arrayInput
Note: the second dimension of the array AF must be at least max 1,N.
On entry: details of the factorization of A, as returned by F07NRF (ZSYTRF).
7:   LDAF – INTEGERInput
On entry: the first dimension of the array AF as declared in the (sub)program from which F07NVF (ZSYRFS) is called.
Constraint: LDAF≥max 1,N.
8:   IPIV* – INTEGER arrayInput
Note: the dimension of the array IPIV must be at least max 1,N.
On entry: details of the interchanges and the block structure of D, as returned by F07NRF (ZSYTRF).
9:   B LDB* – COMPLEX (KIND=nag_wp) arrayInput
Note: the second dimension of the array B must be at least max 1,NRHS.
On entry: the n by r right-hand side matrix B.
10:   LDB – INTEGERInput
On entry: the first dimension of the array B as declared in the (sub)program from which F07NVF (ZSYRFS) is called.
Constraint: LDB≥max 1,N.
11:   X LDX* – COMPLEX (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array X must be at least max 1,NRHS.
On entry: the n by r solution matrix X, as returned by F07NSF (ZSYTRS).
On exit: the improved solution matrix X.
12:   LDX – INTEGERInput
On entry: the first dimension of the array X as declared in the (sub)program from which F07NVF (ZSYRFS) is called.
Constraint: LDX≥max 1,N.
13:   FERR NRHS – REAL (KIND=nag_wp) arrayOutput
On exit: FERR j contains an estimated error bound for the jth solution vector, that is, the jth column of X, for j=1,2,…,r.
14:   BERR NRHS – REAL (KIND=nag_wp) arrayOutput
On exit: BERR j contains the component-wise backward error bound β for the jth solution vector, that is, the jth column of X, for j=1,2,…,r.
15:   WORK 2×N – COMPLEX (KIND=nag_wp) arrayWorkspace
16:   RWORK N – REAL (KIND=nag_wp) arrayWorkspace
17:   INFO – INTEGEROutput
On exit: INFO=0 unless the routine detects an error (see Section 6).

6 Error Indicators and Warnings

INFO<0
If INFO=-i, argument i had an illegal value. An explanatory message is output, and execution of the program is terminated.

7 Accuracy

The bounds returned in FERR are not rigorous, because they are estimated, not computed exactly; but in practice they almost always overestimate the actual error.

8 Parallelism and Performance

F07NVF (ZSYRFS) is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
F07NVF (ZSYRFS) makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

For each right-hand side, computation of the backward error involves a minimum of 16 n 2 real floating-point operations. Each step of iterative refinement involves an additional 24 n 2 real operations. At most five steps of iterative refinement are performed, but usually only one or two steps are required.
Estimating the forward error involves solving a number of systems of linear equations of the form Ax=b; the number is usually 5 and never more than 11. Each solution involves approximately 8 n 2 real operations.
The real analogue of this routine is F07MHF (DSYRFS).

10 Example

This example solves the system of equations AX=B using iterative refinement and to compute the forward and backward error bounds, where
A= -0.39-0.71 i 5.14-0.64 i -7.86-2.96 i 3.80+0.92 i 5.14-0.64 i 8.86+1.81 i -3.52+0.58 i 5.32-1.59 i -7.86-2.96 i -3.52+0.58 i -2.83-0.03 i -1.54-2.86 i 3.80+0.92 i 5.32-1.59 i -1.54-2.86 i -0.56+0.12 i
and
B= -55.64+41.22 i -19.09-35.97 i -48.18+66.00 i -12.08-27.02 i -0.49-0 1.47 i 6.95+20.49 i -6.43+19.24 i -4.59-35.53 i .
Here A is symmetric and must first be factorized by F07NRF (ZSYTRF).

10.1 Program Text

Program Text (f07nvfe.f90)

10.2 Program Data

Program Data (f07nvfe.d)

10.3 Program Results

Program Results (f07nvfe.r)

F07 Chapter Contents
F07 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F07NWF (ZSYTRI) : NAG Library, Mark 26

F07 Chapter Contents
F07 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F07NWF (ZSYTRI)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F07NWF (ZSYTRI) computes the inverse of a complex symmetric matrix A, where A has been factorized by F07NRF (ZSYTRF).

2 Specification

SUBROUTINE F07NWF ( UPLO, N, A, LDA, IPIV, WORK, INFO)
INTEGER | N, LDA, IPIV(*), INFO
COMPLEX (KIND=nag_wp) | A(LDA,*), WORK(2*N)
CHARACTER(1) | UPLO
The routine may be called by its LAPACK name zsytri.

3 Description

F07NWF (ZSYTRI) is used to compute the inverse of a complex symmetric matrix A, the routine must be preceded by a call to F07NRF (ZSYTRF), which computes the Bunch–Kaufman factorization of A.
If UPLO='U', A=PUD UTPT and A-1 is computed by solving UTPT XPU=D-1 for X.
If UPLO='L', A=PLD LTPT and A-1 is computed by solving LTPT XPL=D-1 for X.

4 References

Du Croz J J and Higham N J (1992) Stability of methods for matrix inversion IMA J. Numer. Anal. 12 1–19

5 Arguments

1:   UPLO – CHARACTER(1)Input
On entry: specifies how A has been factorized.
UPLO='U'
A=PUD UTPT, where U is upper triangular.
UPLO='L'
A=PLD LTPT, where L is lower triangular.
Constraint: UPLO='U' or 'L'.
2:   N – INTEGERInput
On entry: n, the order of the matrix A.
Constraint: N≥0.
3:   A LDA* – COMPLEX (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array A must be at least max 1,N.
On entry: details of the factorization of A, as returned by F07NRF (ZSYTRF).
On exit: the factorization is overwritten by the n by n symmetric matrix A-1.
If UPLO='U', the upper triangle of A-1 is stored in the upper triangular part of the array.
If UPLO='L', the lower triangle of A-1 is stored in the lower triangular part of the array.
4:   LDA – INTEGERInput
On entry: the first dimension of the array A as declared in the (sub)program from which F07NWF (ZSYTRI) is called.
Constraint: LDA≥max 1,N.
5:   IPIV* – INTEGER arrayInput
Note: the dimension of the array IPIV must be at least max 1,N.
On entry: details of the interchanges and the block structure of D, as returned by F07NRF (ZSYTRF).
6:   WORK 2×N – COMPLEX (KIND=nag_wp) arrayWorkspace
7:   INFO – INTEGEROutput
On exit: INFO=0 unless the routine detects an error (see Section 6).

6 Error Indicators and Warnings

-999<INFO<0
If INFO=-i, argument i had an illegal value. An explanatory message is output, and execution of the program is terminated.
INFO=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.
An explanatory message is output, and execution of the program is terminated.
INFO>0
Element value of the diagonal is exactly zero. D is singular and the inverse of A cannot be computed.

7 Accuracy

The computed inverse X satisfies a bound of the form
  • if UPLO='U', D UTPT XPU-I≤c n ε DUT PT X P U+DD-1;
  • if UPLO='L', D LTPT XPL-I≤c n ε DLT PT X P L+DD-1,
c n is a modest linear function of n, and ε is the machine precision.

8 Parallelism and Performance

F07NWF (ZSYTRI) makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The total number of real floating-point operations is approximately 83 n 3.
The real analogue of this routine is F07MJF (DSYTRI).

10 Example

This example computes the inverse of the matrix A, where
A= -0.39-0.71 i 5.14-0.64 i -7.86-2.96 i 3.80+0.92 i 5.14-0.64 i 8.86+1.81 i -3.52+0.58 i 5.32-1.59 i -7.86-2.96 i -3.52+0.58 i -2.83-0.03 i -1.54-2.86 i 3.80+0.92 i 5.32-1.59 i -1.54-2.86 i -0.56+0.12 i .
Here A is symmetric and must first be factorized by F07NRF (ZSYTRF).

10.1 Program Text

Program Text (f07nwfe.f90)

10.2 Program Data

Program Data (f07nwfe.d)

10.3 Program Results

Program Results (f07nwfe.r)

F07 Chapter Contents
F07 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F07PAF (DSPSV) : NAG Library, Mark 26

F07 Chapter Contents
F07 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F07PAF (DSPSV)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F07PAF (DSPSV) computes the solution to a real system of linear equations
AX=B ,
where A is an n by n symmetric matrix stored in packed format and X and B are n by r matrices.

2 Specification

SUBROUTINE F07PAF ( UPLO, N, NRHS, AP, IPIV, B, LDB, INFO)
INTEGER | N, NRHS, IPIV(N), LDB, INFO
REAL (KIND=nag_wp) | AP(*), B(LDB,*)
CHARACTER(1) | UPLO
The routine may be called by its LAPACK name dspsv.

3 Description

F07PAF (DSPSV) uses the diagonal pivoting method to factor A as A=UD UT if UPLO='U' or A=LD LT if UPLO='L', where U (or L) is a product of permutation and unit upper (lower) triangular matrices, D is symmetric and block diagonal with 1 by 1 and 2 by 2 diagonal blocks. The factored form of A is then used to solve the system of equations AX=B.

4 References

Anderson E, Bai Z, Bischof C, Blackford S, Demmel J, Dongarra J J, Du Croz J J, Greenbaum A, Hammarling S, McKenney A and Sorensen D (1999) LAPACK Users' Guide (3rd Edition) SIAM, Philadelphia http://www.netlib.org/lapack/lug
Golub G H and Van Loan C F (1996) Matrix Computations (3rd Edition) Johns Hopkins University Press, Baltimore
Higham N J (2002) Accuracy and Stability of Numerical Algorithms (2nd Edition) SIAM, Philadelphia

5 Arguments

1:   UPLO – CHARACTER(1)Input
On entry: if UPLO='U', the upper triangle of A is stored.
If UPLO='L', the lower triangle of A is stored.
Constraint: UPLO='U' or 'L'.
2:   N – INTEGERInput
On entry: n, the number of linear equations, i.e., the order of the matrix A.
Constraint: N≥0.
3:   NRHS – INTEGERInput
On entry: r, the number of right-hand sides, i.e., the number of columns of the matrix B.
Constraint: NRHS≥0.
4:   AP* – REAL (KIND=nag_wp) arrayInput/Output
Note: the dimension of the array AP must be at least max 1,N×N+1/2.
On entry: the n by n symmetric matrix A, packed by columns.
More precisely,
  • if UPLO='U', the upper triangle of A must be stored with element A ij in AP i+j j-1/2 for i≤j;
  • if UPLO='L', the lower triangle of A must be stored with element A ij in AP i+2 n-jj-1/2 for i≥j.
On exit: the block diagonal matrix D and the multipliers used to obtain the factor U or L from the factorization A=UD UT or A=LD LT as computed by F07PDF (DSPTRF), stored as a packed triangular matrix in the same storage format as A.
5:   IPIV N – INTEGER arrayOutput
On exit: details of the interchanges and the block structure of D. More precisely,
  • if IPIV i=k>0, d ii is a 1 by 1 pivot block and the ith row and column of A were interchanged with the kth row and column;
  • if UPLO='U' and IPIV i-1=IPIV i=-l<0, d i-1,i-1d-i,i-1 d-i,i-1d ii is a 2 by 2 pivot block and the i-1th row and column of A were interchanged with the lth row and column;
  • if UPLO='L' and IPIV i=IPIV i+1=-m<0, d iid i+1,id i+1,id i+1,i+1 is a 2 by 2 pivot block and the i+1th row and column of A were interchanged with the mth row and column.
6:   B LDB* – REAL (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array B must be at least max 1,NRHS.
On entry: the n by r right-hand side matrix B.
On exit: if INFO=0, the n by r solution matrix X.
7:   LDB – INTEGERInput
On entry: the first dimension of the array B as declared in the (sub)program from which F07PAF (DSPSV) is called.
Constraint: LDB≥max 1,N.
8:   INFO – INTEGEROutput
On exit: INFO=0 unless the routine detects an error (see Section 6).

6 Error Indicators and Warnings

INFO<0
If INFO=-i, argument i had an illegal value. An explanatory message is output, and execution of the program is terminated.
INFO>0
Element value of the diagonal is exactly zero. The factorization has been completed, but the block diagonal matrix D is exactly singular, so the solution could not be computed.

7 Accuracy

The computed solution for a single right-hand side, x^ , satisfies an equation of the form
A+E x^=b ,
where
E 1 = O ε A 1
and ε is the machine precision. An approximate error bound for the computed solution is given by
x^-x 1 x 1 ≤ κ A E 1 A 1 ,
where κ A = A-1 1 A 1 , the condition number of A with respect to the solution of the linear equations. See Section 4.4 of Anderson et al. (1999) and Chapter 11 of Higham (2002) for further details.
F07PBF (DSPSVX) is a comprehensive LAPACK driver that returns forward and backward error bounds and an estimate of the condition number. Alternatively, F04BJF solves AX=B and returns a forward error bound and condition estimate. F04BJF calls F07PAF (DSPSV) to solve the equations.

8 Parallelism and Performance

F07PAF (DSPSV) makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The total number of floating-point operations is approximately 13 n 3 + 2⁢n 2 r , where r is the number of right-hand sides.
The complex analogues of F07PAF (DSPSV) are F07PNF (ZHPSV) for Hermitian matrices, and F07QNF (ZSPSV) for symmetric matrices.

10 Example

This example solves the equations
Ax=b ,
where A is the symmetric matrix
A = -1.81 2.06 0.63 -1.15 2.06 1.15 1.87 4.20 0.63 1.87 -0.21 3.87 -1.15 4.20 3.87 2.07   and   b = 0.96 6.07 8.38 9.50 .
Details of the factorization of A are also output.

10.1 Program Text

Program Text (f07pafe.f90)

10.2 Program Data

Program Data (f07pafe.d)

10.3 Program Results

Program Results (f07pafe.r)

F07 Chapter Contents
F07 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F07PBF (DSPSVX) : NAG Library, Mark 26

F07 Chapter Contents
F07 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F07PBF (DSPSVX)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F07PBF (DSPSVX) uses the diagonal pivoting factorization
A=UD UT   or   A=LD LT
to compute the solution to a real system of linear equations
AX=B ,
where A is an n by n symmetric matrix stored in packed format and X and B are n by r matrices. Error bounds on the solution and a condition estimate are also provided.

2 Specification

SUBROUTINE F07PBF ( FACT, UPLO, N, NRHS, AP, AFP, IPIV, B, LDB, X, LDX, RCOND, FERR, BERR, WORK, IWORK, INFO)
INTEGER | N, NRHS, IPIV(N), LDB, LDX, IWORK(N), INFO
REAL (KIND=nag_wp) | AP(*), AFP(*), B(LDB,*), X(LDX,*), RCOND, FERR(NRHS), BERR(NRHS), WORK(3*N)
CHARACTER(1) | FACT, UPLO
The routine may be called by its LAPACK name dspsvx.

3 Description

F07PBF (DSPSVX) performs the following steps:
1. | If FACT='N', the diagonal pivoting method is used to factor A as A=UD UT if UPLO='U' or A=LD LT if UPLO='L', where U (or L) is a product of permutation and unit upper (lower) triangular matrices and D is symmetric and block diagonal with 1 by 1 and 2 by 2 diagonal blocks.
2. | If some d ii=0, so that D is exactly singular, then the routine returns with INFO=i. Otherwise, the factored form of A is used to estimate the condition number of the matrix A. If the reciprocal of the condition number is less than machine precision, INFO=N+1 is returned as a warning, but the routine still goes on to solve for X and compute error bounds as described below.
3. | The system of equations is solved for X using the factored form of A.
4. | Iterative refinement is applied to improve the computed solution matrix and to calculate error bounds and backward error estimates for it.

4 References

Anderson E, Bai Z, Bischof C, Blackford S, Demmel J, Dongarra J J, Du Croz J J, Greenbaum A, Hammarling S, McKenney A and Sorensen D (1999) LAPACK Users' Guide (3rd Edition) SIAM, Philadelphia http://www.netlib.org/lapack/lug
Golub G H and Van Loan C F (1996) Matrix Computations (3rd Edition) Johns Hopkins University Press, Baltimore
Higham N J (2002) Accuracy and Stability of Numerical Algorithms (2nd Edition) SIAM, Philadelphia

5 Arguments

1:   FACT – CHARACTER(1)Input
On entry: specifies whether or not the factorized form of the matrix A has been supplied.
FACT='F'
AFP and IPIV contain the factorized form of the matrix A. AFP and IPIV will not be modified.
FACT='N'
The matrix A will be copied to AFP and factorized.
Constraint: FACT='F' or 'N'.
2:   UPLO – CHARACTER(1)Input
On entry: if UPLO='U', the upper triangle of A is stored.
If UPLO='L', the lower triangle of A is stored.
Constraint: UPLO='U' or 'L'.
3:   N – INTEGERInput
On entry: n, the number of linear equations, i.e., the order of the matrix A.
Constraint: N≥0.
4:   NRHS – INTEGERInput
On entry: r, the number of right-hand sides, i.e., the number of columns of the matrix B.
Constraint: NRHS≥0.
5:   AP* – REAL (KIND=nag_wp) arrayInput
Note: the dimension of the array AP must be at least max 1,N×N+1/2.
On entry: the n by n symmetric matrix A, packed by columns.
More precisely,
  • if UPLO='U', the upper triangle of A must be stored with element A ij in AP i+j j-1/2 for i≤j;
  • if UPLO='L', the lower triangle of A must be stored with element A ij in AP i+2 n-jj-1/2 for i≥j.
6:   AFP* – REAL (KIND=nag_wp) arrayInput/Output
Note: the dimension of the array AFP must be at least max 1,N×N+1/2.
On entry: if FACT='F', AFP contains the block diagonal matrix D and the multipliers used to obtain the factor U or L from the factorization A=UD UT or A=LD LT as computed by F07PDF (DSPTRF), stored as a packed triangular matrix in the same storage format as A.
On exit: if FACT='N', AFP contains the block diagonal matrix D and the multipliers used to obtain the factor U or L from the factorization A=UD UT or A=LD LT as computed by F07PDF (DSPTRF), stored as a packed triangular matrix in the same storage format as A.
7:   IPIV N – INTEGER arrayInput/Output
On entry: if FACT='F', IPIV contains details of the interchanges and the block structure of D, as determined by F07PDF (DSPTRF).
  • if IPIV i=k>0, d ii is a 1 by 1 pivot block and the ith row and column of A were interchanged with the kth row and column;
  • if UPLO='U' and IPIV i-1=IPIV i=-l<0, d i-1,i-1d-i,i-1 d-i,i-1d ii is a 2 by 2 pivot block and the i-1th row and column of A were interchanged with the lth row and column;
  • if UPLO='L' and IPIV i=IPIV i+1=-m<0, d iid i+1,id i+1,id i+1,i+1 is a 2 by 2 pivot block and the i+1th row and column of A were interchanged with the mth row and column.
On exit: if FACT='N', IPIV contains details of the interchanges and the block structure of D, as determined by F07PDF (DSPTRF), as described above.
8:   B LDB* – REAL (KIND=nag_wp) arrayInput
Note: the second dimension of the array B must be at least max 1,NRHS.
On entry: the n by r right-hand side matrix B.
9:   LDB – INTEGERInput
On entry: the first dimension of the array B as declared in the (sub)program from which F07PBF (DSPSVX) is called.
Constraint: LDB≥max 1,N.
10:   X LDX* – REAL (KIND=nag_wp) arrayOutput
Note: the second dimension of the array X must be at least max 1,NRHS.
On exit: if INFO=0 or N+1, the n by r solution matrix X.
11:   LDX – INTEGERInput
On entry: the first dimension of the array X as declared in the (sub)program from which F07PBF (DSPSVX) is called.
Constraint: LDX≥max 1,N.
12:   RCOND – REAL (KIND=nag_wp)Output
On exit: the estimate of the reciprocal condition number of the matrix A. If RCOND=0.0, the matrix may be exactly singular. This condition is indicated by INFO>0 and INFO≤N. Otherwise, if RCOND is less than the machine precision, the matrix is singular to working precision. This condition is indicated by INFO=N+1.
13:   FERR NRHS – REAL (KIND=nag_wp) arrayOutput
On exit: if INFO=0 or N+1, an estimate of the forward error bound for each computed solution vector, such that x^j-xj∞/xj∞≤FERR j where x^j is the jth column of the computed solution returned in the array X and xj is the corresponding column of the exact solution X. The estimate is as reliable as the estimate for RCOND, and is almost always a slight overestimate of the true error.
14:   BERR NRHS – REAL (KIND=nag_wp) arrayOutput
On exit: if INFO=0 or N+1, an estimate of the component-wise relative backward error of each computed solution vector x^j (i.e., the smallest relative change in any element of A or B that makes x^j an exact solution).
15:   WORK 3×N – REAL (KIND=nag_wp) arrayWorkspace
16:   IWORK N – INTEGER arrayWorkspace
17:   INFO – INTEGEROutput
On exit: INFO=0 unless the routine detects an error (see Section 6).

6 Error Indicators and Warnings

INFO<0
If INFO=-i, argument i had an illegal value. An explanatory message is output, and execution of the program is terminated.
INFO>0 and INFO≤N
Element value of the diagonal is exactly zero. The factorization has been completed, but the factor D is exactly singular, so the solution and error bounds could not be computed. RCOND=0.0 is returned.
INFO=N+1
D is nonsingular, but RCOND is less than machine precision, meaning that the matrix is singular to working precision. Nevertheless, the solution and error bounds are computed because there are a number of situations where the computed solution can be more accurate than the value of RCOND would suggest.

7 Accuracy

For each right-hand side vector b, the computed solution x^ is the exact solution of a perturbed system of equations A+E x^=b, where
E 1 = O ε A 1 ,
where ε is the machine precision. See Chapter 11 of Higham (2002) for further details.
If x^ is the true solution, then the computed solution x satisfies a forward error bound of the form
x-x^∞ x^∞ ≤ wc cond A,x^,b
where cond A,x^,b = A-1 A x^ + b ∞/ x^∞ ≤ cond A = A-1 A ∞≤κ∞ A. If x^ is the j th column of X , then wc is returned in BERR j and a bound on x - x^ ∞ / x^ ∞ is returned in FERR j . See Section 4.4 of Anderson et al. (1999) for further details.

8 Parallelism and Performance

F07PBF (DSPSVX) is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
F07PBF (DSPSVX) makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The factorization of A requires approximately 13 n 3 floating-point operations.
For each right-hand side, computation of the backward error involves a minimum of 4⁢n 2 floating-point operations. Each step of iterative refinement involves an additional 6⁢n 2 operations. At most five steps of iterative refinement are performed, but usually only one or two steps are required. Estimating the forward error involves solving a number of systems of equations of the form Ax=b ; the number is usually 4 or 5 and never more than 11. Each solution involves approximately 2⁢n 2 operations.
The complex analogues of this routine are F07PPF (ZHPSVX) for Hermitian matrices, and F07QPF (ZSPSVX) for symmetric matrices.

10 Example

This example solves the equations
AX=B ,
where A is the symmetric matrix
A = -1.81 2.06 0.63 -1.15 2.06 1.15 1.87 4.20 0.63 1.87 -0.21 3.87 -1.15 4.20 3.87 2.07   and   B = 0.96 3.93 6.07 19.25 8.38 9.90 9.50 27.85 .
Error estimates for the solutions, and an estimate of the reciprocal of the condition number of the matrix A are also output.

10.1 Program Text

Program Text (f07pbfe.f90)

10.2 Program Data

Program Data (f07pbfe.d)

10.3 Program Results

Program Results (f07pbfe.r)

F07 Chapter Contents
F07 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F07PDF (DSPTRF) : NAG Library, Mark 26

F07 Chapter Contents
F07 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F07PDF (DSPTRF)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F07PDF (DSPTRF) computes the Bunch–Kaufman factorization of a real symmetric indefinite matrix, using packed storage.

2 Specification

SUBROUTINE F07PDF ( UPLO, N, AP, IPIV, INFO)
INTEGER | N, IPIV(N), INFO
REAL (KIND=nag_wp) | AP(*)
CHARACTER(1) | UPLO
The routine may be called by its LAPACK name dsptrf.

3 Description

F07PDF (DSPTRF) factorizes a real symmetric matrix A, using the Bunch–Kaufman diagonal pivoting method and packed storage. A is factorized as either A=PUD UTPT if UPLO='U' or A=PLD LTPT if UPLO='L', where P is a permutation matrix, U (or L) is a unit upper (or lower) triangular matrix and D is a symmetric block diagonal matrix with 1 by 1 and 2 by 2 diagonal blocks; U (or L) has 2 by 2 unit diagonal blocks corresponding to the 2 by 2 blocks of D. Row and column interchanges are performed to ensure numerical stability while preserving symmetry.
This method is suitable for symmetric matrices which are not known to be positive definite. If A is in fact positive definite, no interchanges are performed and no 2 by 2 blocks occur in D.

4 References

Golub G H and Van Loan C F (1996) Matrix Computations (3rd Edition) Johns Hopkins University Press, Baltimore

5 Arguments

1:   UPLO – CHARACTER(1)Input
On entry: specifies whether the upper or lower triangular part of A is stored and how A is to be factorized.
UPLO='U'
The upper triangular part of A is stored and A is factorized as PUD UTPT, where U is upper triangular.
UPLO='L'
The lower triangular part of A is stored and A is factorized as PLD LTPT, where L is lower triangular.
Constraint: UPLO='U' or 'L'.
2:   N – INTEGERInput
On entry: n, the order of the matrix A.
Constraint: N≥0.
3:   AP* – REAL (KIND=nag_wp) arrayInput/Output
Note: the dimension of the array AP must be at least max 1,N×N+1/2.
On entry: the n by n symmetric matrix A, packed by columns.
More precisely,
  • if UPLO='U', the upper triangle of A must be stored with element A ij in AP i+j j-1/2 for i≤j;
  • if UPLO='L', the lower triangle of A must be stored with element A ij in AP i+2 n-jj-1/2 for i≥j.
On exit: A is overwritten by details of the block diagonal matrix D and the multipliers used to obtain the factor U or L as specified by UPLO.
4:   IPIV N – INTEGER arrayOutput
On exit: details of the interchanges and the block structure of D. More precisely,
  • if IPIV i=k>0, d ii is a 1 by 1 pivot block and the ith row and column of A were interchanged with the kth row and column;
  • if UPLO='U' and IPIV i-1=IPIV i=-l<0, d i-1,i-1d-i,i-1 d-i,i-1d ii is a 2 by 2 pivot block and the i-1th row and column of A were interchanged with the lth row and column;
  • if UPLO='L' and IPIV i=IPIV i+1=-m<0, d iid i+1,id i+1,id i+1,i+1 is a 2 by 2 pivot block and the i+1th row and column of A were interchanged with the mth row and column.
5:   INFO – INTEGEROutput
On exit: INFO=0 unless the routine detects an error (see Section 6).

6 Error Indicators and Warnings

INFO<0
If INFO=-i, argument i had an illegal value. An explanatory message is output, and execution of the program is terminated.
INFO>0
Element value of the diagonal is exactly zero. The factorization has been completed, but the block diagonal matrix D is exactly singular, and division by zero will occur if it is used to solve a system of equations.

7 Accuracy

If UPLO='U', the computed factors U and D are the exact factors of a perturbed matrix A+E, where
E≤c n εP UDUT PT ,
c n is a modest linear function of n, and ε is the machine precision.
If UPLO='L', a similar statement holds for the computed factors L and D.

8 Parallelism and Performance

F07PDF (DSPTRF) makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The elements of D overwrite the corresponding elements of A; if D has 2 by 2 blocks, only the upper or lower triangle is stored, as specified by UPLO.
The unit diagonal elements of U or L and the 2 by 2 unit diagonal blocks are not stored. The remaining elements of U or L overwrite elements in the corresponding columns of A, but additional row interchanges must be applied to recover U or L explicitly (this is seldom necessary). If IPIV i=i, for i=1,2,…,n (as is the case when A is positive definite), then U or L are stored explicitly in packed form (except for their unit diagonal elements which are equal to 1).
The total number of floating-point operations is approximately 13 n 3.
A call to F07PDF (DSPTRF) may be followed by calls to the routines:
  • F07PEF (DSPTRS) to solve AX=B;
  • F07PGF (DSPCON) to estimate the condition number of A;
  • F07PJF (DSPTRI) to compute the inverse of A.
The complex analogues of this routine are F07PRF (ZHPTRF) for Hermitian matrices and F07QRF (ZSPTRF) for symmetric matrices.

10 Example

This example computes the Bunch–Kaufman factorization of the matrix A, where
A= 2.07 3.87 4.20 -1.15 3.87 -0.21 1.87 0.63 4.20 1.87 1.15 2.06 -1.15 0.63 2.06 -1.81 ,
using packed storage.

10.1 Program Text

Program Text (f07pdfe.f90)

10.2 Program Data

Program Data (f07pdfe.d)

10.3 Program Results

Program Results (f07pdfe.r)

F07 Chapter Contents
F07 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F07PEF (DSPTRS) : NAG Library, Mark 26

F07 Chapter Contents
F07 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F07PEF (DSPTRS)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F07PEF (DSPTRS) solves a real symmetric indefinite system of linear equations with multiple right-hand sides,
AX=B ,
where A has been factorized by F07PDF (DSPTRF), using packed storage.

2 Specification

SUBROUTINE F07PEF ( UPLO, N, NRHS, AP, IPIV, B, LDB, INFO)
INTEGER | N, NRHS, IPIV(*), LDB, INFO
REAL (KIND=nag_wp) | AP(*), B(LDB,*)
CHARACTER(1) | UPLO
The routine may be called by its LAPACK name dsptrs.

3 Description

F07PEF (DSPTRS) is used to solve a real symmetric indefinite system of linear equations AX=B, the routine must be preceded by a call to F07PDF (DSPTRF) which computes the Bunch–Kaufman factorization of A, using packed storage.
If UPLO='U', A=PUD UTPT, where P is a permutation matrix, U is an upper triangular matrix and D is a symmetric block diagonal matrix with 1 by 1 and 2 by 2 blocks; the solution X is computed by solving PUDY=B and then UTPT X=Y.
If UPLO='L', A=PLD LTPT, where L is a lower triangular matrix; the solution X is computed by solving PLDY=B and then LTPT X=Y.

4 References

Golub G H and Van Loan C F (1996) Matrix Computations (3rd Edition) Johns Hopkins University Press, Baltimore

5 Arguments

1:   UPLO – CHARACTER(1)Input
On entry: specifies how A has been factorized.
UPLO='U'
A=PUD UTPT, where U is upper triangular.
UPLO='L'
A=PLD LTPT, where L is lower triangular.
Constraint: UPLO='U' or 'L'.
2:   N – INTEGERInput
On entry: n, the order of the matrix A.
Constraint: N≥0.
3:   NRHS – INTEGERInput
On entry: r, the number of right-hand sides.
Constraint: NRHS≥0.
4:   AP* – REAL (KIND=nag_wp) arrayInput
Note: the dimension of the array AP must be at least max 1,N×N+1/2.
On entry: the factorization of A stored in packed form, as returned by F07PDF (DSPTRF).
5:   IPIV* – INTEGER arrayInput
Note: the dimension of the array IPIV must be at least max 1,N.
On entry: details of the interchanges and the block structure of D, as returned by F07PDF (DSPTRF).
6:   B LDB* – REAL (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array B must be at least max 1,NRHS.
On entry: the n by r right-hand side matrix B.
On exit: the n by r solution matrix X.
7:   LDB – INTEGERInput
On entry: the first dimension of the array B as declared in the (sub)program from which F07PEF (DSPTRS) is called.
Constraint: LDB≥max 1,N.
8:   INFO – INTEGEROutput
On exit: INFO=0 unless the routine detects an error (see Section 6).

6 Error Indicators and Warnings

INFO<0
If INFO=-i, argument i had an illegal value. An explanatory message is output, and execution of the program is terminated.

7 Accuracy

For each right-hand side vector b, the computed solution x is the exact solution of a perturbed system of equations A+E x=b, where
  • if UPLO='U', E≤c n εP UDUT PT;
  • if UPLO='L', E≤c n εP LDLT PT,
c n is a modest linear function of n, and ε is the machine precision.
If x^ is the true solution, then the computed solution x satisfies a forward error bound of the form
x-x^∞ x∞ ≤c n cond A,x ε
where cond A,x=A-1Ax∞/x∞≤cond A=A-1A∞≤κ∞A.
Note that cond A,x can be much smaller than cond A.
Forward and backward error bounds can be computed by calling F07PHF (DSPRFS), and an estimate for κ∞A (=κ 1 A) can be obtained by calling F07PGF (DSPCON).

8 Parallelism and Performance

F07PEF (DSPTRS) makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The total number of floating-point operations is approximately 2⁢n 2 r.
This routine may be followed by a call to F07PHF (DSPRFS) to refine the solution and return an error estimate.
The complex analogues of this routine are F07PSF (ZHPTRS) for Hermitian matrices and F07QSF (ZSPTRS) for symmetric matrices.

10 Example

This example solves the system of equations AX=B, where
A= 2.07 3.87 4.20 -1.15 3.87 -0.21 1.87 0.63 4.20 1.87 1.15 2.06 -1.15 0.63 2.06 -1.81   and   B= -9.50 27.85 -8.38 9.90 -6.07 19.25 -0.96 3.93 .
Here A is symmetric indefinite, stored in packed form, and must first be factorized by F07PDF (DSPTRF).

10.1 Program Text

Program Text (f07pefe.f90)

10.2 Program Data

Program Data (f07pefe.d)

10.3 Program Results

Program Results (f07pefe.r)

F07 Chapter Contents
F07 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F07PGF (DSPCON) : NAG Library, Mark 26

F07 Chapter Contents
F07 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F07PGF (DSPCON)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F07PGF (DSPCON) estimates the condition number of a real symmetric indefinite matrix A, where A has been factorized by F07PDF (DSPTRF), using packed storage.

2 Specification

SUBROUTINE F07PGF ( UPLO, N, AP, IPIV, ANORM, RCOND, WORK, IWORK, INFO)
INTEGER | N, IPIV(*), IWORK(N), INFO
REAL (KIND=nag_wp) | AP(*), ANORM, RCOND, WORK(2*N)
CHARACTER(1) | UPLO
The routine may be called by its LAPACK name dspcon.

3 Description

F07PGF (DSPCON) estimates the condition number (in the 1-norm) of a real symmetric indefinite matrix A:
κ 1 A=A 1A-1 1 .
Since A is symmetric, κ 1 A=κ∞A=A∞A-1∞.
Because κ 1 A is infinite if A is singular, the routine actually returns an estimate of the reciprocal of κ 1 A.
The routine should be preceded by a call to F06RDF to compute A 1 and a call to F07PDF (DSPTRF) to compute the Bunch–Kaufman factorization of A. The routine then uses Higham's implementation of Hager's method (see Higham (1988)) to estimate A-1 1.

4 References

Higham N J (1988) FORTRAN codes for estimating the one-norm of a real or complex matrix, with applications to condition estimation ACM Trans. Math. Software 14 381–396

5 Arguments

1:   UPLO – CHARACTER(1)Input
On entry: specifies how A has been factorized.
UPLO='U'
A=PUD UTPT, where U is upper triangular.
UPLO='L'
A=PLD LTPT, where L is lower triangular.
Constraint: UPLO='U' or 'L'.
2:   N – INTEGERInput
On entry: n, the order of the matrix A.
Constraint: N≥0.
3:   AP* – REAL (KIND=nag_wp) arrayInput
Note: the dimension of the array AP must be at least max 1,N×N+1/2.
On entry: the factorization of A stored in packed form, as returned by F07PDF (DSPTRF).
4:   IPIV* – INTEGER arrayInput
Note: the dimension of the array IPIV must be at least max 1,N.
On entry: details of the interchanges and the block structure of D, as returned by F07PDF (DSPTRF).
5:   ANORM – REAL (KIND=nag_wp)Input
On entry: the 1-norm of the original matrix A, which may be computed by calling F06RDF with its argument NORM='1'. ANORM must be computed either before calling F07PDF (DSPTRF) or else from a copy of the original matrix A.
Constraint: ANORM≥0.0.
6:   RCOND – REAL (KIND=nag_wp)Output
On exit: an estimate of the reciprocal of the condition number of A. RCOND is set to zero if exact singularity is detected or the estimate underflows. If RCOND is less than machine precision, A is singular to working precision.
7:   WORK 2×N – REAL (KIND=nag_wp) arrayWorkspace
8:   IWORK N – INTEGER arrayWorkspace
9:   INFO – INTEGEROutput
On exit: INFO=0 unless the routine detects an error (see Section 6).

6 Error Indicators and Warnings

INFO<0
If INFO=-i, argument i had an illegal value. An explanatory message is output, and execution of the program is terminated.

7 Accuracy

The computed estimate RCOND is never less than the true value ρ, and in practice is nearly always less than 10 ρ, although examples can be constructed where RCOND is much larger.

8 Parallelism and Performance

F07PGF (DSPCON) makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

A call to F07PGF (DSPCON) involves solving a number of systems of linear equations of the form Ax=b; the number is usually 4 or 5 and never more than 11. Each solution involves approximately 2⁢n 2 floating-point operations but takes considerably longer than a call to F07PEF (DSPTRS) with one right-hand side, because extra care is taken to avoid overflow when A is approximately singular.
The complex analogues of this routine are F07PUF (ZHPCON) for Hermitian matrices and F07QUF (ZSPCON) for symmetric matrices.

10 Example

This example estimates the condition number in the 1-norm (or ∞-norm) of the matrix A, where
A= 2.07 3.87 4.20 -1.15 3.87 -0.21 1.87 0.63 4.20 1.87 1.15 2.06 -1.15 0.63 2.06 -1.81 .
Here A is symmetric indefinite, stored in packed form, and must first be factorized by F07PDF (DSPTRF). The true condition number in the 1-norm is 75.68.

10.1 Program Text

Program Text (f07pgfe.f90)

10.2 Program Data

Program Data (f07pgfe.d)

10.3 Program Results

Program Results (f07pgfe.r)

F07 Chapter Contents
F07 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F07PHF (DSPRFS) : NAG Library, Mark 26

F07 Chapter Contents
F07 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F07PHF (DSPRFS)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F07PHF (DSPRFS) returns error bounds for the solution of a real symmetric indefinite system of linear equations with multiple right-hand sides, AX=B, using packed storage. It improves the solution by iterative refinement, in order to reduce the backward error as much as possible.

2 Specification

SUBROUTINE F07PHF ( UPLO, N, NRHS, AP, AFP, IPIV, B, LDB, X, LDX, FERR, BERR, WORK, IWORK, INFO)
INTEGER | N, NRHS, IPIV(*), LDB, LDX, IWORK(N), INFO
REAL (KIND=nag_wp) | AP(*), AFP(*), B(LDB,*), X(LDX,*), FERR(NRHS), BERR(NRHS), WORK(3*N)
CHARACTER(1) | UPLO
The routine may be called by its LAPACK name dsprfs.

3 Description

F07PHF (DSPRFS) returns the backward errors and estimated bounds on the forward errors for the solution of a real symmetric indefinite system of linear equations with multiple right-hand sides AX=B, using packed storage. The routine handles each right-hand side vector (stored as a column of the matrix B) independently, so we describe the function of F07PHF (DSPRFS) in terms of a single right-hand side b and solution x.
Given a computed solution x, the routine computes the component-wise backward error β. This is the size of the smallest relative perturbation in each element of A and b such that x is the exact solution of a perturbed system
A+δA x=b+δb δ a ij≤β a ij   and   δ bi≤β bi .
Then the routine estimates a bound for the component-wise forward error in the computed solution, defined by:
maxi xi-x^i/maxi xi
where x^ is the true solution.
For details of the method, see the F07 Chapter Introduction.

4 References

Golub G H and Van Loan C F (1996) Matrix Computations (3rd Edition) Johns Hopkins University Press, Baltimore

5 Arguments

1:   UPLO – CHARACTER(1)Input
On entry: specifies whether the upper or lower triangular part of A is stored and how A is to be factorized.
UPLO='U'
The upper triangular part of A is stored and A is factorized as PUD UTPT, where U is upper triangular.
UPLO='L'
The lower triangular part of A is stored and A is factorized as PLD LTPT, where L is lower triangular.
Constraint: UPLO='U' or 'L'.
2:   N – INTEGERInput
On entry: n, the order of the matrix A.
Constraint: N≥0.
3:   NRHS – INTEGERInput
On entry: r, the number of right-hand sides.
Constraint: NRHS≥0.
4:   AP* – REAL (KIND=nag_wp) arrayInput
Note: the dimension of the array AP must be at least max 1,N×N+1/2.
On entry: the n by n original symmetric matrix A as supplied to F07PDF (DSPTRF).
5:   AFP* – REAL (KIND=nag_wp) arrayInput
Note: the dimension of the array AFP must be at least max 1,N×N+1/2.
On entry: the factorization of A stored in packed form, as returned by F07PDF (DSPTRF).
6:   IPIV* – INTEGER arrayInput
Note: the dimension of the array IPIV must be at least max 1,N.
On entry: details of the interchanges and the block structure of D, as returned by F07PDF (DSPTRF).
7:   B LDB* – REAL (KIND=nag_wp) arrayInput
Note: the second dimension of the array B must be at least max 1,NRHS.
On entry: the n by r right-hand side matrix B.
8:   LDB – INTEGERInput
On entry: the first dimension of the array B as declared in the (sub)program from which F07PHF (DSPRFS) is called.
Constraint: LDB≥max 1,N.
9:   X LDX* – REAL (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array X must be at least max 1,NRHS.
On entry: the n by r solution matrix X, as returned by F07PEF (DSPTRS).
On exit: the improved solution matrix X.
10:   LDX – INTEGERInput
On entry: the first dimension of the array X as declared in the (sub)program from which F07PHF (DSPRFS) is called.
Constraint: LDX≥max 1,N.
11:   FERR NRHS – REAL (KIND=nag_wp) arrayOutput
On exit: FERR j contains an estimated error bound for the jth solution vector, that is, the jth column of X, for j=1,2,…,r.
12:   BERR NRHS – REAL (KIND=nag_wp) arrayOutput
On exit: BERR j contains the component-wise backward error bound β for the jth solution vector, that is, the jth column of X, for j=1,2,…,r.
13:   WORK 3×N – REAL (KIND=nag_wp) arrayWorkspace
14:   IWORK N – INTEGER arrayWorkspace
15:   INFO – INTEGEROutput
On exit: INFO=0 unless the routine detects an error (see Section 6).

6 Error Indicators and Warnings

INFO<0
If INFO=-i, argument i had an illegal value. An explanatory message is output, and execution of the program is terminated.

7 Accuracy

The bounds returned in FERR are not rigorous, because they are estimated, not computed exactly; but in practice they almost always overestimate the actual error.

8 Parallelism and Performance

F07PHF (DSPRFS) is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
F07PHF (DSPRFS) makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

For each right-hand side, computation of the backward error involves a minimum of 4⁢n 2 floating-point operations. Each step of iterative refinement involves an additional 6 n 2 operations. At most five steps of iterative refinement are performed, but usually only 1 or 2 steps are required.
Estimating the forward error involves solving a number of systems of linear equations of the form Ax=b; the number is usually 4 or 5 and never more than 11. Each solution involves approximately 2 n 2 operations.
The complex analogues of this routine are F07PVF (ZHPRFS) for Hermitian matrices and F07QVF (ZSPRFS) for symmetric matrices.

10 Example

This example solves the system of equations AX=B using iterative refinement and to compute the forward and backward error bounds, where
A= 2.07 3.87 4.20 -1.15 3.87 -0.21 1.87 0.63 4.20 1.87 1.15 2.06 -1.15 0.63 2.06 -1.81   and   B= -9.50 27.85 -8.38 9.90 -6.07 19.25 -0.96 3.93 .
Here A is symmetric indefinite, stored in packed form, and must first be factorized by F07PDF (DSPTRF).

10.1 Program Text

Program Text (f07phfe.f90)

10.2 Program Data

Program Data (f07phfe.d)

10.3 Program Results

Program Results (f07phfe.r)

F07 Chapter Contents
F07 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F07PJF (DSPTRI) : NAG Library, Mark 26

F07 Chapter Contents
F07 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F07PJF (DSPTRI)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F07PJF (DSPTRI) computes the inverse of a real symmetric indefinite matrix A, where A has been factorized by F07PDF (DSPTRF), using packed storage.

2 Specification

SUBROUTINE F07PJF ( UPLO, N, AP, IPIV, WORK, INFO)
INTEGER | N, IPIV(*), INFO
REAL (KIND=nag_wp) | AP(*), WORK(N)
CHARACTER(1) | UPLO
The routine may be called by its LAPACK name dsptri.

3 Description

F07PJF (DSPTRI) is used to compute the inverse of a real symmetric indefinite matrix A, the routine must be preceded by a call to F07PDF (DSPTRF), which computes the Bunch–Kaufman factorization of A, using packed storage.
If UPLO='U', A=PUD UTPT and A-1 is computed by solving UTPT XPU=D-1.
If UPLO='L', A=PLD LTPT and A-1 is computed by solving LTPT XPL=D-1.

4 References

Du Croz J J and Higham N J (1992) Stability of methods for matrix inversion IMA J. Numer. Anal. 12 1–19

5 Arguments

1:   UPLO – CHARACTER(1)Input
On entry: specifies how A has been factorized.
UPLO='U'
A=PUD UTPT, where U is upper triangular.
UPLO='L'
A=PLD LTPT, where L is lower triangular.
Constraint: UPLO='U' or 'L'.
2:   N – INTEGERInput
On entry: n, the order of the matrix A.
Constraint: N≥0.
3:   AP* – REAL (KIND=nag_wp) arrayInput/Output
Note: the dimension of the array AP must be at least max 1,N×N+1/2.
On entry: the factorization of A stored in packed form, as returned by F07PDF (DSPTRF).
On exit: the factorization is overwritten by the n by n matrix A-1.
More precisely,
  • if UPLO='U', the upper triangle of A-1 must be stored with element A ij in AP i+j j-1/2 for i≤j;
  • if UPLO='L', the lower triangle of A-1 must be stored with element A ij in AP i+2 n-jj-1/2 for i≥j.
4:   IPIV* – INTEGER arrayInput
Note: the dimension of the array IPIV must be at least max 1,N.
On entry: details of the interchanges and the block structure of D, as returned by F07PDF (DSPTRF).
5:   WORK N – REAL (KIND=nag_wp) arrayWorkspace
6:   INFO – INTEGEROutput
On exit: INFO=0 unless the routine detects an error (see Section 6).

6 Error Indicators and Warnings

INFO<0
If INFO=-i, argument i had an illegal value. An explanatory message is output, and execution of the program is terminated.
INFO>0
Element value of the diagonal is exactly zero. D is singular and the inverse of A cannot be computed.

7 Accuracy

The computed inverse X satisfies a bound of the form
  • if UPLO='U', D UTPT XPU-I≤c n ε DUT PT X P U+DD-1;
  • if UPLO='L', D LTPT XPL-I≤c n ε DLT PT X P L+DD-1,
c n is a modest linear function of n, and ε is the machine precision.

8 Parallelism and Performance

F07PJF (DSPTRI) makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The total number of floating-point operations is approximately 23 n 3.
The complex analogues of this routine are F07PWF (ZHPTRI) for Hermitian matrices and F07QWF (ZSPTRI) for symmetric matrices.

10 Example

This example computes the inverse of the matrix A, where
A= 2.07 3.87 4.20 -1.15 3.87 -0.21 1.87 0.63 4.20 1.87 1.15 2.06 -1.15 0.63 2.06 -1.81 .
Here A is symmetric indefinite, stored in packed form, and must first be factorized by F07PDF (DSPTRF).

10.1 Program Text

Program Text (f07pjfe.f90)

10.2 Program Data

Program Data (f07pjfe.d)

10.3 Program Results

Program Results (f07pjfe.r)

F07 Chapter Contents
F07 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F07PNF (ZHPSV) : NAG Library, Mark 26

F07 Chapter Contents
F07 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F07PNF (ZHPSV)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F07PNF (ZHPSV) computes the solution to a complex system of linear equations
AX=B ,
where A is an n by n Hermitian matrix stored in packed format and X and B are n by r matrices.

2 Specification

SUBROUTINE F07PNF ( UPLO, N, NRHS, AP, IPIV, B, LDB, INFO)
INTEGER | N, NRHS, IPIV(N), LDB, INFO
COMPLEX (KIND=nag_wp) | AP(*), B(LDB,*)
CHARACTER(1) | UPLO
The routine may be called by its LAPACK name zhpsv.

3 Description

F07PNF (ZHPSV) uses the diagonal pivoting method to factor A as A=UD UH if UPLO='U' or A=LD LH if UPLO='L', where U (or L) is a product of permutation and unit upper (lower) triangular matrices, D is Hermitian and block diagonal with 1 by 1 and 2 by 2 diagonal blocks. The factored form of A is then used to solve the system of equations AX=B.

4 References

Anderson E, Bai Z, Bischof C, Blackford S, Demmel J, Dongarra J J, Du Croz J J, Greenbaum A, Hammarling S, McKenney A and Sorensen D (1999) LAPACK Users' Guide (3rd Edition) SIAM, Philadelphia http://www.netlib.org/lapack/lug
Golub G H and Van Loan C F (1996) Matrix Computations (3rd Edition) Johns Hopkins University Press, Baltimore
Higham N J (2002) Accuracy and Stability of Numerical Algorithms (2nd Edition) SIAM, Philadelphia

5 Arguments

1:   UPLO – CHARACTER(1)Input
On entry: if UPLO='U', the upper triangle of A is stored.
If UPLO='L', the lower triangle of A is stored.
Constraint: UPLO='U' or 'L'.
2:   N – INTEGERInput
On entry: n, the number of linear equations, i.e., the order of the matrix A.
Constraint: N≥0.
3:   NRHS – INTEGERInput
On entry: r, the number of right-hand sides, i.e., the number of columns of the matrix B.
Constraint: NRHS≥0.
4:   AP* – COMPLEX (KIND=nag_wp) arrayInput/Output
Note: the dimension of the array AP must be at least max 1,N×N+1/2.
On entry: the n by n Hermitian matrix A, packed by columns.
More precisely,
  • if UPLO='U', the upper triangle of A must be stored with element A ij in AP i+j j-1/2 for i≤j;
  • if UPLO='L', the lower triangle of A must be stored with element A ij in AP i+2 n-jj-1/2 for i≥j.
On exit: the block diagonal matrix D and the multipliers used to obtain the factor U or L from the factorization A=UD UH or A=LD LH as computed by F07PRF (ZHPTRF), stored as a packed triangular matrix in the same storage format as A.
5:   IPIV N – INTEGER arrayOutput
On exit: details of the interchanges and the block structure of D. More precisely,
  • if IPIV i=k>0, d ii is a 1 by 1 pivot block and the ith row and column of A were interchanged with the kth row and column;
  • if UPLO='U' and IPIV i-1=IPIV i=-l<0, d i-1,i-1d-i,i-1 d-i,i-1d ii is a 2 by 2 pivot block and the i-1th row and column of A were interchanged with the lth row and column;
  • if UPLO='L' and IPIV i=IPIV i+1=-m<0, d iid i+1,id i+1,id i+1,i+1 is a 2 by 2 pivot block and the i+1th row and column of A were interchanged with the mth row and column.
6:   B LDB* – COMPLEX (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array B must be at least max 1,NRHS.
To solve the equations Ax=b, where b is a single right-hand side, B may be supplied as a one-dimensional array with length LDB=max 1,N.
On entry: the n by r right-hand side matrix B.
On exit: if INFO=0, the n by r solution matrix X.
7:   LDB – INTEGERInput
On entry: the first dimension of the array B as declared in the (sub)program from which F07PNF (ZHPSV) is called.
Constraint: LDB≥max 1,N.
8:   INFO – INTEGEROutput
On exit: INFO=0 unless the routine detects an error (see Section 6).

6 Error Indicators and Warnings

INFO<0
If INFO=-i, argument i had an illegal value. An explanatory message is output, and execution of the program is terminated.
INFO>0
Element value of the diagonal is exactly zero. The factorization has been completed, but the block diagonal matrix D is exactly singular, so the solution could not be computed.

7 Accuracy

The computed solution for a single right-hand side, x^ , satisfies an equation of the form
A+E x^=b ,
where
E 1 = O ε A 1
and ε is the machine precision. An approximate error bound for the computed solution is given by
x^-x 1 x 1 ≤ κ A E 1 A 1 ,
where κ A = A-1 1 A 1 , the condition number of A with respect to the solution of the linear equations. See Section 4.4 of Anderson et al. (1999) and Chapter 11 of Higham (2002) for further details.
F07PPF (ZHPSVX) is a comprehensive LAPACK driver that returns forward and backward error bounds and an estimate of the condition number. Alternatively, F04CJF solves AX=B and returns a forward error bound and condition estimate. F04CJF calls F07PNF (ZHPSV) to solve the equations.

8 Parallelism and Performance

F07PNF (ZHPSV) makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The total number of floating-point operations is approximately 43 n 3 + 8⁢n 2 r , where r is the number of right-hand sides.
The real analogue of this routine is F07PAF (DSPSV). The complex symmetric analogue of this routine is F07QNF (ZSPSV).

10 Example

This example solves the equations
Ax=b ,
where A is the Hermitian matrix
A = -1.84 i+0.00 0.11-0.11 i -1.78-1.18 i 3.91-1.50 i 0.11+0.11 i -4.63 i+0.00 -1.84+0.03 i 2.21+0.21 i -1.78+1.18 i -1.84-0.03 i -8.87 i+0.00 1.58-0.90 i 3.91+1.50 i 2.21-0.21 i 1.58+0.90 i -1.36 i+0.00
and
b = 2.98-10.18 i -9.58+0 3.88 i -0.77-16.05 i 7.79+0 5.48 i .
Details of the factorization of A are also output.

10.1 Program Text

Program Text (f07pnfe.f90)

10.2 Program Data

Program Data (f07pnfe.d)

10.3 Program Results

Program Results (f07pnfe.r)

F07 Chapter Contents
F07 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F07PPF (ZHPSVX) : NAG Library, Mark 26

F07 Chapter Contents
F07 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F07PPF (ZHPSVX)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F07PPF (ZHPSVX) uses the diagonal pivoting factorization
A=UD UH   or   A=LD LH
to compute the solution to a complex system of linear equations
AX=B ,
where A is an n by n Hermitian matrix stored in packed format and X and B are n by r matrices. Error bounds on the solution and a condition estimate are also provided.

2 Specification

SUBROUTINE F07PPF ( FACT, UPLO, N, NRHS, AP, AFP, IPIV, B, LDB, X, LDX, RCOND, FERR, BERR, WORK, RWORK, INFO)
INTEGER | N, NRHS, IPIV(N), LDB, LDX, INFO
REAL (KIND=nag_wp) | RCOND, FERR(NRHS), BERR(NRHS), RWORK(N)
COMPLEX (KIND=nag_wp) | AP(*), AFP(*), B(LDB,*), X(LDX,*), WORK(2*N)
CHARACTER(1) | FACT, UPLO
The routine may be called by its LAPACK name zhpsvx.

3 Description

F07PPF (ZHPSVX) performs the following steps:
1. | If FACT='N', the diagonal pivoting method is used to factor A as A=UD UH if UPLO='U' or A=LD LH if UPLO='L', where U (or L) is a product of permutation and unit upper (lower) triangular matrices and D is Hermitian and block diagonal with 1 by 1 and 2 by 2 diagonal blocks.
2. | If some d ii=0, so that D is exactly singular, then the routine returns with INFO=i. Otherwise, the factored form of A is used to estimate the condition number of the matrix A. If the reciprocal of the condition number is less than machine precision, INFO=N+1 is returned as a warning, but the routine still goes on to solve for X and compute error bounds as described below.
3. | The system of equations is solved for X using the factored form of A.
4. | Iterative refinement is applied to improve the computed solution matrix and to calculate error bounds and backward error estimates for it.

4 References

Anderson E, Bai Z, Bischof C, Blackford S, Demmel J, Dongarra J J, Du Croz J J, Greenbaum A, Hammarling S, McKenney A and Sorensen D (1999) LAPACK Users' Guide (3rd Edition) SIAM, Philadelphia http://www.netlib.org/lapack/lug
Golub G H and Van Loan C F (1996) Matrix Computations (3rd Edition) Johns Hopkins University Press, Baltimore
Higham N J (2002) Accuracy and Stability of Numerical Algorithms (2nd Edition) SIAM, Philadelphia

5 Arguments

1:   FACT – CHARACTER(1)Input
On entry: specifies whether or not the factorized form of the matrix A has been supplied.
FACT='F'
AFP and IPIV contain the factorized form of the matrix A. AFP and IPIV will not be modified.
FACT='N'
The matrix A will be copied to AFP and factorized.
Constraint: FACT='F' or 'N'.
2:   UPLO – CHARACTER(1)Input
On entry: if UPLO='U', the upper triangle of A is stored.
If UPLO='L', the lower triangle of A is stored.
Constraint: UPLO='U' or 'L'.
3:   N – INTEGERInput
On entry: n, the number of linear equations, i.e., the order of the matrix A.
Constraint: N≥0.
4:   NRHS – INTEGERInput
On entry: r, the number of right-hand sides, i.e., the number of columns of the matrix B.
Constraint: NRHS≥0.
5:   AP* – COMPLEX (KIND=nag_wp) arrayInput
Note: the dimension of the array AP must be at least max 1,N×N+1/2.
On entry: the n by n Hermitian matrix A, packed by columns.
More precisely,
  • if UPLO='U', the upper triangle of A must be stored with element A ij in AP i+j j-1/2 for i≤j;
  • if UPLO='L', the lower triangle of A must be stored with element A ij in AP i+2 n-jj-1/2 for i≥j.
6:   AFP* – COMPLEX (KIND=nag_wp) arrayInput/Output
Note: the dimension of the array AFP must be at least max 1,N×N+1/2.
On entry: if FACT='F', AFP contains the block diagonal matrix D and the multipliers used to obtain the factor U or L from the factorization A=UD UH or A=LD LH as computed by F07PRF (ZHPTRF), stored as a packed triangular matrix in the same storage format as A.
On exit: if FACT='N', AFP contains the block diagonal matrix D and the multipliers used to obtain the factor U or L from the factorization A=UD UH or A=LD LH as computed by F07PRF (ZHPTRF), stored as a packed triangular matrix in the same storage format as A.
7:   IPIV N – INTEGER arrayInput/Output
On entry: if FACT='F', IPIV contains details of the interchanges and the block structure of D, as determined by F07PRF (ZHPTRF).
  • if IPIV i=k>0, d ii is a 1 by 1 pivot block and the ith row and column of A were interchanged with the kth row and column;
  • if UPLO='U' and IPIV i-1=IPIV i=-l<0, d i-1,i-1d-i,i-1 d-i,i-1d ii is a 2 by 2 pivot block and the i-1th row and column of A were interchanged with the lth row and column;
  • if UPLO='L' and IPIV i=IPIV i+1=-m<0, d iid i+1,id i+1,id i+1,i+1 is a 2 by 2 pivot block and the i+1th row and column of A were interchanged with the mth row and column.
On exit: if FACT='N', IPIV contains details of the interchanges and the block structure of D, as determined by F07PRF (ZHPTRF), as described above.
8:   B LDB* – COMPLEX (KIND=nag_wp) arrayInput
Note: the second dimension of the array B must be at least max 1,NRHS.
On entry: the n by r right-hand side matrix B.
9:   LDB – INTEGERInput
On entry: the first dimension of the array B as declared in the (sub)program from which F07PPF (ZHPSVX) is called.
Constraint: LDB≥max 1,N.
10:   X LDX* – COMPLEX (KIND=nag_wp) arrayOutput
Note: the second dimension of the array X must be at least max 1,NRHS.
On exit: if INFO=0 or N+1, the n by r solution matrix X.
11:   LDX – INTEGERInput
On entry: the first dimension of the array X as declared in the (sub)program from which F07PPF (ZHPSVX) is called.
Constraint: LDX≥max 1,N.
12:   RCOND – REAL (KIND=nag_wp)Output
On exit: the estimate of the reciprocal condition number of the matrix A. If RCOND=0.0, the matrix may be exactly singular. This condition is indicated by INFO>0 and INFO≤N. Otherwise, if RCOND is less than the machine precision, the matrix is singular to working precision. This condition is indicated by INFO=N+1.
13:   FERR NRHS – REAL (KIND=nag_wp) arrayOutput
On exit: if INFO=0 or N+1, an estimate of the forward error bound for each computed solution vector, such that x^j-xj∞/xj∞≤FERR j where x^j is the jth column of the computed solution returned in the array X and xj is the corresponding column of the exact solution X. The estimate is as reliable as the estimate for RCOND, and is almost always a slight overestimate of the true error.
14:   BERR NRHS – REAL (KIND=nag_wp) arrayOutput
On exit: if INFO=0 or N+1, an estimate of the component-wise relative backward error of each computed solution vector x^j (i.e., the smallest relative change in any element of A or B that makes x^j an exact solution).
15:   WORK 2×N – COMPLEX (KIND=nag_wp) arrayWorkspace
16:   RWORK N – REAL (KIND=nag_wp) arrayWorkspace
17:   INFO – INTEGEROutput
On exit: INFO=0 unless the routine detects an error (see Section 6).

6 Error Indicators and Warnings

INFO<0
If INFO=-i, argument i had an illegal value. An explanatory message is output, and execution of the program is terminated.
INFO>0 and INFO≤N
Element value of the diagonal is exactly zero. The factorization has been completed, but the factor D is exactly singular, so the solution and error bounds could not be computed. RCOND=0.0 is returned.
INFO=N+1
D is nonsingular, but RCOND is less than machine precision, meaning that the matrix is singular to working precision. Nevertheless, the solution and error bounds are computed because there are a number of situations where the computed solution can be more accurate than the value of RCOND would suggest.

7 Accuracy

For each right-hand side vector b, the computed solution x^ is the exact solution of a perturbed system of equations A+E x^=b, where
E 1 = O ε A 1 ,
where ε is the machine precision. See Chapter 11 of Higham (2002) for further details.
If x^ is the true solution, then the computed solution x satisfies a forward error bound of the form
x-x^∞ x^∞ ≤ wc cond A,x^,b
where cond A,x^,b = A-1 A x^ + b ∞/ x^∞ ≤ cond A = A-1 A ∞≤κ∞ A. If x^ is the j th column of X , then wc is returned in BERR j and a bound on x - x^ ∞ / x^ ∞ is returned in FERR j . See Section 4.4 of Anderson et al. (1999) for further details.

8 Parallelism and Performance

F07PPF (ZHPSVX) is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
F07PPF (ZHPSVX) makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The factorization of A requires approximately 43 n 3 floating-point operations.
For each right-hand side, computation of the backward error involves a minimum of 16⁢n 2 floating-point operations. Each step of iterative refinement involves an additional 24⁢n 2 operations. At most five steps of iterative refinement are performed, but usually only one or two steps are required. Estimating the forward error involves solving a number of systems of equations of the form Ax=b ; the number is usually 4 or 5 and never more than 11. Each solution involves approximately 8⁢n 2 operations.
The real analogue of this routine is F07PBF (DSPSVX). The complex symmetric analogue of this routine is F07QPF (ZSPSVX).

10 Example

This example solves the equations
AX=B ,
where A is the Hermitian matrix
A = -1.84 i+0.00 0.11-0.11 i -1.78-1.18 i 3.91-1.50 i 0.11+0.11 i -4.63 i+0.00 -1.84+0.03 i 2.21+0.21 i -1.78+1.18 i -1.84-0.03 i -8.87 i+0.00 1.58-0.90 i 3.91+1.50 i 2.21-0.21 i 1.58+0.90 i -1.36 i+0.00
and
B = 2.98-10.18 i 28.68-39.89 i -9.58+0 3.88 i -24.79-0 8.40 i -0.77-16.05 i 4.23-70.02 i 7.79+0 5.48 i -35.39+18.01 i .
Error estimates for the solutions, and an estimate of the reciprocal of the condition number of the matrix A are also output.

10.1 Program Text

Program Text (f07ppfe.f90)

10.2 Program Data

Program Data (f07ppfe.d)

10.3 Program Results

Program Results (f07ppfe.r)

F07 Chapter Contents
F07 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F07PRF (ZHPTRF) : NAG Library, Mark 26

F07 Chapter Contents
F07 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F07PRF (ZHPTRF)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F07PRF (ZHPTRF) computes the Bunch–Kaufman factorization of a complex Hermitian indefinite matrix, using packed storage.

2 Specification

SUBROUTINE F07PRF ( UPLO, N, AP, IPIV, INFO)
INTEGER | N, IPIV(N), INFO
COMPLEX (KIND=nag_wp) | AP(*)
CHARACTER(1) | UPLO
The routine may be called by its LAPACK name zhptrf.

3 Description

F07PRF (ZHPTRF) factorizes a complex Hermitian matrix A, using the Bunch–Kaufman diagonal pivoting method and packed storage. A is factorized as either A=PUD UHPT if UPLO='U' or A=PLD LHPT if UPLO='L', where P is a permutation matrix, U (or L) is a unit upper (or lower) triangular matrix and D is an Hermitian block diagonal matrix with 1 by 1 and 2 by 2 diagonal blocks; U (or L) has 2 by 2 unit diagonal blocks corresponding to the 2 by 2 blocks of D. Row and column interchanges are performed to ensure numerical stability while keeping the matrix Hermitian.
This method is suitable for Hermitian matrices which are not known to be positive definite. If A is in fact positive definite, no interchanges are performed and no 2 by 2 blocks occur in D.

4 References

Golub G H and Van Loan C F (1996) Matrix Computations (3rd Edition) Johns Hopkins University Press, Baltimore

5 Arguments

1:   UPLO – CHARACTER(1)Input
On entry: specifies whether the upper or lower triangular part of A is stored and how A is to be factorized.
UPLO='U'
The upper triangular part of A is stored and A is factorized as PUD UHPT, where U is upper triangular.
UPLO='L'
The lower triangular part of A is stored and A is factorized as PLD LHPT, where L is lower triangular.
Constraint: UPLO='U' or 'L'.
2:   N – INTEGERInput
On entry: n, the order of the matrix A.
Constraint: N≥0.
3:   AP* – COMPLEX (KIND=nag_wp) arrayInput/Output
Note: the dimension of the array AP must be at least max 1,N×N+1/2.
On entry: the n by n Hermitian matrix A, packed by columns.
More precisely,
  • if UPLO='U', the upper triangle of A must be stored with element A ij in AP i+j j-1/2 for i≤j;
  • if UPLO='L', the lower triangle of A must be stored with element A ij in AP i+2 n-jj-1/2 for i≥j.
On exit: A is overwritten by details of the block diagonal matrix D and the multipliers used to obtain the factor U or L as specified by UPLO.
4:   IPIV N – INTEGER arrayOutput
On exit: details of the interchanges and the block structure of D. More precisely,
  • if IPIV i=k>0, d ii is a 1 by 1 pivot block and the ith row and column of A were interchanged with the kth row and column;
  • if UPLO='U' and IPIV i-1=IPIV i=-l<0, d i-1,i-1d-i,i-1 d-i,i-1d ii is a 2 by 2 pivot block and the i-1th row and column of A were interchanged with the lth row and column;
  • if UPLO='L' and IPIV i=IPIV i+1=-m<0, d iid i+1,id i+1,id i+1,i+1 is a 2 by 2 pivot block and the i+1th row and column of A were interchanged with the mth row and column.
5:   INFO – INTEGEROutput
On exit: INFO=0 unless the routine detects an error (see Section 6).

6 Error Indicators and Warnings

INFO<0
If INFO=-i, argument i had an illegal value. An explanatory message is output, and execution of the program is terminated.
INFO>0
Element value of the diagonal is exactly zero. The factorization has been completed, but the block diagonal matrix D is exactly singular, and division by zero will occur if it is used to solve a system of equations.

7 Accuracy

If UPLO='U', the computed factors U and D are the exact factors of a perturbed matrix A+E, where
E≤c n εP UDUH PT ,
c n is a modest linear function of n, and ε is the machine precision.
If UPLO='L', a similar statement holds for the computed factors L and D.

8 Parallelism and Performance

F07PRF (ZHPTRF) makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The elements of D overwrite the corresponding elements of A; if D has 2 by 2 blocks, only the upper or lower triangle is stored, as specified by UPLO.
The unit diagonal elements of U or L and the 2 by 2 unit diagonal blocks are not stored. The remaining elements of U and L are stored in the corresponding columns of the array AP, but additional row interchanges must be applied to recover U or L explicitly (this is seldom necessary). If IPIV i=i, for i=1,2,…,n (as is the case when A is positive definite), then U or L are stored explicitly in packed form (except for their unit diagonal elements which are equal to 1).
The total number of real floating-point operations is approximately 43 n 3.
A call to F07PRF (ZHPTRF) may be followed by calls to the routines:
  • F07PSF (ZHPTRS) to solve AX=B;
  • F07PUF (ZHPCON) to estimate the condition number of A;
  • F07PWF (ZHPTRI) to compute the inverse of A.
The real analogue of this routine is F07PDF (DSPTRF).

10 Example

This example computes the Bunch–Kaufman factorization of the matrix A, where
A= -1.36+0.00 i 1.58+0.90 i 2.21-0.21 i 3.91+1.50 i 1.58-0.90 i -8.87+0.00 i -1.84-0.03 i -1.78+1.18 i 2.21+0.21 i -1.84+0.03 i -4.63+0.00 i 0.11+0.11 i 3.91-1.50 i -1.78-1.18 i 0.11-0.11 i -1.84+0.00 i ,
using packed storage.

10.1 Program Text

Program Text (f07prfe.f90)

10.2 Program Data

Program Data (f07prfe.d)

10.3 Program Results

Program Results (f07prfe.r)

F07 Chapter Contents
F07 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F07PSF (ZHPTRS) : NAG Library, Mark 26

F07 Chapter Contents
F07 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F07PSF (ZHPTRS)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F07PSF (ZHPTRS) solves a complex Hermitian indefinite system of linear equations with multiple right-hand sides,
AX=B ,
where A has been factorized by F07PRF (ZHPTRF), using packed storage.

2 Specification

SUBROUTINE F07PSF ( UPLO, N, NRHS, AP, IPIV, B, LDB, INFO)
INTEGER | N, NRHS, IPIV(*), LDB, INFO
COMPLEX (KIND=nag_wp) | AP(*), B(LDB,*)
CHARACTER(1) | UPLO
The routine may be called by its LAPACK name zhptrs.

3 Description

F07PSF (ZHPTRS) is used to solve a complex Hermitian indefinite system of linear equations AX=B, the routine must be preceded by a call to F07PRF (ZHPTRF) which computes the Bunch–Kaufman factorization of A, using packed storage.
If UPLO='U', A=PUD UHPT, where P is a permutation matrix, U is an upper triangular matrix and D is an Hermitian block diagonal matrix with 1 by 1 and 2 by 2 blocks; the solution X is computed by solving PUDY=B and then UHPT X=Y.
If UPLO='L', A=PLD LHPT, where L is a lower triangular matrix; the solution X is computed by solving PLDY=B and then LHPT X=Y.

4 References

Golub G H and Van Loan C F (1996) Matrix Computations (3rd Edition) Johns Hopkins University Press, Baltimore

5 Arguments

1:   UPLO – CHARACTER(1)Input
On entry: specifies how A has been factorized.
UPLO='U'
A=PUD UHPT, where U is upper triangular.
UPLO='L'
A=PLD LHPT, where L is lower triangular.
Constraint: UPLO='U' or 'L'.
2:   N – INTEGERInput
On entry: n, the order of the matrix A.
Constraint: N≥0.
3:   NRHS – INTEGERInput
On entry: r, the number of right-hand sides.
Constraint: NRHS≥0.
4:   AP* – COMPLEX (KIND=nag_wp) arrayInput
Note: the dimension of the array AP must be at least max 1,N×N+1/2.
On entry: the factorization of A stored in packed form, as returned by F07PRF (ZHPTRF).
5:   IPIV* – INTEGER arrayInput
Note: the dimension of the array IPIV must be at least max 1,N.
On entry: details of the interchanges and the block structure of D, as returned by F07PRF (ZHPTRF).
6:   B LDB* – COMPLEX (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array B must be at least max 1,NRHS.
On entry: the n by r right-hand side matrix B.
On exit: the n by r solution matrix X.
7:   LDB – INTEGERInput
On entry: the first dimension of the array B as declared in the (sub)program from which F07PSF (ZHPTRS) is called.
Constraint: LDB≥max 1,N.
8:   INFO – INTEGEROutput
On exit: INFO=0 unless the routine detects an error (see Section 6).

6 Error Indicators and Warnings

INFO<0
If INFO=-i, argument i had an illegal value. An explanatory message is output, and execution of the program is terminated.

7 Accuracy

For each right-hand side vector b, the computed solution x is the exact solution of a perturbed system of equations A+E x=b, where
  • if UPLO='U', E≤c n εP UDUH PT;
  • if UPLO='L', E≤c n εP LDLH PT,
c n is a modest linear function of n, and ε is the machine precision.
If x^ is the true solution, then the computed solution x satisfies a forward error bound of the form
x-x^∞ x∞ ≤c n cond A,x ε
where cond A,x=A-1Ax∞/x∞≤cond A=A-1A∞≤κ∞A.
Note that cond A,x can be much smaller than cond A.
Forward and backward error bounds can be computed by calling F07PVF (ZHPRFS), and an estimate for κ∞A (=κ 1 A) can be obtained by calling F07PUF (ZHPCON).

8 Parallelism and Performance

F07PSF (ZHPTRS) makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The total number of real floating-point operations is approximately 8⁢n 2 r.
This routine may be followed by a call to F07PVF (ZHPRFS) to refine the solution and return an error estimate.
The real analogue of this routine is F07PEF (DSPTRS).

10 Example

This example solves the system of equations AX=B, where
A= -1.36+0.00 i 1.58+0.90 i 2.21-0.21 i 3.91+1.50 i 1.58-0.90 i -8.87+0.00 i -1.84-0.03 i -1.78+1.18 i 2.21+0.21 i -1.84+0.03 i -4.63+0.00 i 0.11+0.11 i 3.91-1.50 i -1.78-1.18 i 0.11-0.11 i -1.84+0.00 i
and
B= 7.79+0 5.48 i -35.39+18.01 i -0.77-16.05 i 4.23-70.02 i -9.58+0 3.88 i -24.79-0 8.40 i 2.98-10.18 i 28.68-39.89 i .
Here A is Hermitian indefinite, stored in packed form, and must first be factorized by F07PRF (ZHPTRF).

10.1 Program Text

Program Text (f07psfe.f90)

10.2 Program Data

Program Data (f07psfe.d)

10.3 Program Results

Program Results (f07psfe.r)

F07 Chapter Contents
F07 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F07PUF (ZHPCON) : NAG Library, Mark 26

F07 Chapter Contents
F07 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F07PUF (ZHPCON)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F07PUF (ZHPCON) estimates the condition number of a complex Hermitian indefinite matrix A, where A has been factorized by F07PRF (ZHPTRF), using packed storage.

2 Specification

SUBROUTINE F07PUF ( UPLO, N, AP, IPIV, ANORM, RCOND, WORK, INFO)
INTEGER | N, IPIV(*), INFO
REAL (KIND=nag_wp) | ANORM, RCOND
COMPLEX (KIND=nag_wp) | AP(*), WORK(2*N)
CHARACTER(1) | UPLO
The routine may be called by its LAPACK name zhpcon.

3 Description

F07PUF (ZHPCON) estimates the condition number (in the 1-norm) of a complex Hermitian indefinite matrix A:
κ 1 A=A 1A-1 1 .
Since A is Hermitian, κ 1 A=κ∞A=A∞A-1∞.
Because κ 1 A is infinite if A is singular, the routine actually returns an estimate of the reciprocal of κ 1 A.
The routine should be preceded by a call to F06UDF to compute A 1 and a call to F07PRF (ZHPTRF) to compute the Bunch–Kaufman factorization of A. The routine then uses Higham's implementation of Hager's method (see Higham (1988)) to estimate A-1 1.

4 References

Higham N J (1988) FORTRAN codes for estimating the one-norm of a real or complex matrix, with applications to condition estimation ACM Trans. Math. Software 14 381–396

5 Arguments

1:   UPLO – CHARACTER(1)Input
On entry: specifies how A has been factorized.
UPLO='U'
A=PUD UHPT, where U is upper triangular.
UPLO='L'
A=PLD LHPT, where L is lower triangular.
Constraint: UPLO='U' or 'L'.
2:   N – INTEGERInput
On entry: n, the order of the matrix A.
Constraint: N≥0.
3:   AP* – COMPLEX (KIND=nag_wp) arrayInput
Note: the dimension of the array AP must be at least max 1,N×N+1/2.
On entry: the factorization of A stored in packed form, as returned by F07PRF (ZHPTRF).
4:   IPIV* – INTEGER arrayInput
Note: the dimension of the array IPIV must be at least max 1,N.
On entry: details of the interchanges and the block structure of D, as returned by F07PRF (ZHPTRF).
5:   ANORM – REAL (KIND=nag_wp)Input
On entry: the 1-norm of the original matrix A, which may be computed by calling F06UDF with its argument NORM='1'. ANORM must be computed either before calling F07PRF (ZHPTRF) or else from a copy of the original matrix A.
Constraint: ANORM≥0.0.
6:   RCOND – REAL (KIND=nag_wp)Output
On exit: an estimate of the reciprocal of the condition number of A. RCOND is set to zero if exact singularity is detected or the estimate underflows. If RCOND is less than machine precision, A is singular to working precision.
7:   WORK 2×N – COMPLEX (KIND=nag_wp) arrayWorkspace
8:   INFO – INTEGEROutput
On exit: INFO=0 unless the routine detects an error (see Section 6).

6 Error Indicators and Warnings

INFO<0
If INFO=-i, argument i had an illegal value. An explanatory message is output, and execution of the program is terminated.

7 Accuracy

The computed estimate RCOND is never less than the true value ρ, and in practice is nearly always less than 10 ρ, although examples can be constructed where RCOND is much larger.

8 Parallelism and Performance

F07PUF (ZHPCON) makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

A call to F07PUF (ZHPCON) involves solving a number of systems of linear equations of the form Ax=b; the number is usually 5 and never more than 11. Each solution involves approximately 8⁢n 2 real floating-point operations but takes considerably longer than a call to F07PSF (ZHPTRS) with one right-hand side, because extra care is taken to avoid overflow when A is approximately singular.
The real analogue of this routine is F07PGF (DSPCON).

10 Example

This example estimates the condition number in the 1-norm (or ∞-norm) of the matrix A, where
A= -1.36+0.00 i 1.58+0.90 i 2.21-0.21 i 3.91+1.50 i 1.58-0.90 i -8.87+0.00 i -1.84-0.03 i -1.78+1.18 i 2.21+0.21 i -1.84+0.03 i -4.63+0.00 i 0.11+0.11 i 3.91-1.50 i -1.78-1.18 i 0.11-0.11 i -1.84+0.00 i .
Here A is Hermitian indefinite, stored in packed form, and must first be factorized by F07PRF (ZHPTRF). The true condition number in the 1-norm is 9.10.

10.1 Program Text

Program Text (f07pufe.f90)

10.2 Program Data

Program Data (f07pufe.d)

10.3 Program Results

Program Results (f07pufe.r)

F07 Chapter Contents
F07 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F07PVF (ZHPRFS) : NAG Library, Mark 26

F07 Chapter Contents
F07 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F07PVF (ZHPRFS)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F07PVF (ZHPRFS) returns error bounds for the solution of a complex Hermitian indefinite system of linear equations with multiple right-hand sides, AX=B, using packed storage. It improves the solution by iterative refinement, in order to reduce the backward error as much as possible.

2 Specification

SUBROUTINE F07PVF ( UPLO, N, NRHS, AP, AFP, IPIV, B, LDB, X, LDX, FERR, BERR, WORK, RWORK, INFO)
INTEGER | N, NRHS, IPIV(*), LDB, LDX, INFO
REAL (KIND=nag_wp) | FERR(NRHS), BERR(NRHS), RWORK(N)
COMPLEX (KIND=nag_wp) | AP(*), AFP(*), B(LDB,*), X(LDX,*), WORK(2*N)
CHARACTER(1) | UPLO
The routine may be called by its LAPACK name zhprfs.

3 Description

F07PVF (ZHPRFS) returns the backward errors and estimated bounds on the forward errors for the solution of a complex Hermitian indefinite system of linear equations with multiple right-hand sides AX=B, using packed storage. The routine handles each right-hand side vector (stored as a column of the matrix B) independently, so we describe the function of F07PVF (ZHPRFS) in terms of a single right-hand side b and solution x.
Given a computed solution x, the routine computes the component-wise backward error β. This is the size of the smallest relative perturbation in each element of A and b such that x is the exact solution of a perturbed system
A+δA x=b+δb δ a ij≤β a ij   and   δ bi≤β bi .
Then the routine estimates a bound for the component-wise forward error in the computed solution, defined by:
maxi xi-x^i/maxi xi
where x^ is the true solution.
For details of the method, see the F07 Chapter Introduction.

4 References

Golub G H and Van Loan C F (1996) Matrix Computations (3rd Edition) Johns Hopkins University Press, Baltimore

5 Arguments

1:   UPLO – CHARACTER(1)Input
On entry: specifies whether the upper or lower triangular part of A is stored and how A is to be factorized.
UPLO='U'
The upper triangular part of A is stored and A is factorized as PUD UHPT, where U is upper triangular.
UPLO='L'
The lower triangular part of A is stored and A is factorized as PLD LHPT, where L is lower triangular.
Constraint: UPLO='U' or 'L'.
2:   N – INTEGERInput
On entry: n, the order of the matrix A.
Constraint: N≥0.
3:   NRHS – INTEGERInput
On entry: r, the number of right-hand sides.
Constraint: NRHS≥0.
4:   AP* – COMPLEX (KIND=nag_wp) arrayInput
Note: the dimension of the array AP must be at least max 1,N×N+1/2.
On entry: the n by n original Hermitian matrix A as supplied to F07PRF (ZHPTRF).
5:   AFP* – COMPLEX (KIND=nag_wp) arrayInput
Note: the dimension of the array AFP must be at least max 1,N×N+1/2.
On entry: the factorization of A stored in packed form, as returned by F07PRF (ZHPTRF).
6:   IPIV* – INTEGER arrayInput
Note: the dimension of the array IPIV must be at least max 1,N.
On entry: details of the interchanges and the block structure of D, as returned by F07PRF (ZHPTRF).
7:   B LDB* – COMPLEX (KIND=nag_wp) arrayInput
Note: the second dimension of the array B must be at least max 1,NRHS.
On entry: the n by r right-hand side matrix B.
8:   LDB – INTEGERInput
On entry: the first dimension of the array B as declared in the (sub)program from which F07PVF (ZHPRFS) is called.
Constraint: LDB≥max 1,N.
9:   X LDX* – COMPLEX (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array X must be at least max 1,NRHS.
On entry: the n by r solution matrix X, as returned by F07PSF (ZHPTRS).
On exit: the improved solution matrix X.
10:   LDX – INTEGERInput
On entry: the first dimension of the array X as declared in the (sub)program from which F07PVF (ZHPRFS) is called.
Constraint: LDX≥max 1,N.
11:   FERR NRHS – REAL (KIND=nag_wp) arrayOutput
On exit: FERR j contains an estimated error bound for the jth solution vector, that is, the jth column of X, for j=1,2,…,r.
12:   BERR NRHS – REAL (KIND=nag_wp) arrayOutput
On exit: BERR j contains the component-wise backward error bound β for the jth solution vector, that is, the jth column of X, for j=1,2,…,r.
13:   WORK 2×N – COMPLEX (KIND=nag_wp) arrayWorkspace
14:   RWORK N – REAL (KIND=nag_wp) arrayWorkspace
15:   INFO – INTEGEROutput
On exit: INFO=0 unless the routine detects an error (see Section 6).

6 Error Indicators and Warnings

INFO<0
If INFO=-i, argument i had an illegal value. An explanatory message is output, and execution of the program is terminated.

7 Accuracy

The bounds returned in FERR are not rigorous, because they are estimated, not computed exactly; but in practice they almost always overestimate the actual error.

8 Parallelism and Performance

F07PVF (ZHPRFS) is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
F07PVF (ZHPRFS) makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

For each right-hand side, computation of the backward error involves a minimum of 16 ⁢n 2 real floating-point operations. Each step of iterative refinement involves an additional 24 n 2 real operations. At most five steps of iterative refinement are performed, but usually only 1 or 2 steps are required.
Estimating the forward error involves solving a number of systems of linear equations of the form Ax=b; the number is usually 5 and never more than 11. Each solution involves approximately 8 n 2 real operations.
The real analogue of this routine is F07PHF (DSPRFS).

10 Example

This example solves the system of equations AX=B using iterative refinement and to compute the forward and backward error bounds, where
A= -1.36+0.00 i 1.58+0.90 i 2.21-0.21 i 3.91+1.50 i 1.58-0.90 i -8.87+0.00 i -1.84-0.03 i -1.78+1.18 i 2.21+0.21 i -1.84+0.03 i -4.63+0.00 i 0.11+0.11 i 3.91-1.50 i -1.78-1.18 i 0.11-0.11 i -1.84+0.00 i
and
B= 7.79+0 5.48 i -35.39+18.01 i -0.77-16.05 i 4.23-70.02 i -9.58+0 3.88 i -24.79-0 8.40 i 2.98-10.18 i 28.68-39.89 i .
Here A is Hermitian indefinite, stored in packed form, and must first be factorized by F07PRF (ZHPTRF).

10.1 Program Text

Program Text (f07pvfe.f90)

10.2 Program Data

Program Data (f07pvfe.d)

10.3 Program Results

Program Results (f07pvfe.r)

F07 Chapter Contents
F07 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F07PWF (ZHPTRI) : NAG Library, Mark 26

F07 Chapter Contents
F07 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F07PWF (ZHPTRI)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F07PWF (ZHPTRI) computes the inverse of a complex Hermitian indefinite matrix A, where A has been factorized by F07PRF (ZHPTRF), using packed storage.

2 Specification

SUBROUTINE F07PWF ( UPLO, N, AP, IPIV, WORK, INFO)
INTEGER | N, IPIV(*), INFO
COMPLEX (KIND=nag_wp) | AP(*), WORK(N)
CHARACTER(1) | UPLO
The routine may be called by its LAPACK name zhptri.

3 Description

F07PWF (ZHPTRI) is used to compute the inverse of a complex Hermitian indefinite matrix A, the routine must be preceded by a call to F07PRF (ZHPTRF), which computes the Bunch–Kaufman factorization of A, using packed storage.
If UPLO='U', A=PUD UHPT and A-1 is computed by solving UHPT XPU=D-1 for X.
If UPLO='L', A=PLD LHPT and A-1 is computed by solving LHPT XPL=D-1 for X.

4 References

Du Croz J J and Higham N J (1992) Stability of methods for matrix inversion IMA J. Numer. Anal. 12 1–19

5 Arguments

1:   UPLO – CHARACTER(1)Input
On entry: specifies how A has been factorized.
UPLO='U'
A=PUD UHPT, where U is upper triangular.
UPLO='L'
A=PLD LHPT, where L is lower triangular.
Constraint: UPLO='U' or 'L'.
2:   N – INTEGERInput
On entry: n, the order of the matrix A.
Constraint: N≥0.
3:   AP* – COMPLEX (KIND=nag_wp) arrayInput/Output
Note: the dimension of the array AP must be at least max 1,N×N+1/2.
On entry: the factorization of A stored in packed form, as returned by F07PRF (ZHPTRF).
On exit: the factorization is overwritten by the n by n matrix A-1.
More precisely,
  • if UPLO='U', the upper triangle of A-1 must be stored with element A ij in AP i+j j-1/2 for i≤j;
  • if UPLO='L', the lower triangle of A-1 must be stored with element A ij in AP i+2 n-jj-1/2 for i≥j.
4:   IPIV* – INTEGER arrayInput
Note: the dimension of the array IPIV must be at least max 1,N.
On entry: details of the interchanges and the block structure of D, as returned by F07PRF (ZHPTRF).
5:   WORK N – COMPLEX (KIND=nag_wp) arrayWorkspace
6:   INFO – INTEGEROutput
On exit: INFO=0 unless the routine detects an error (see Section 6).

6 Error Indicators and Warnings

INFO<0
If INFO=-i, argument i had an illegal value. An explanatory message is output, and execution of the program is terminated.
INFO>0
Element value of the diagonal is exactly zero. D is singular and the inverse of A cannot be computed.

7 Accuracy

The computed inverse X satisfies a bound of the form
  • if UPLO='U', D UTPT XPU-I≤c n ε DUT PT X P U+DD-1;
  • if UPLO='L', D LTPT XPL-I≤c n ε DLT PT X P L+DD-1,
c n is a modest linear function of n, and ε is the machine precision.

8 Parallelism and Performance

F07PWF (ZHPTRI) makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The total number of real floating-point operations is approximately 83 n 3.
The real analogue of this routine is F07PJF (DSPTRI).

10 Example

This example computes the inverse of the matrix A, where
A= -1.36+0.00 i 1.58+0.90 i 2.21-0.21 i 3.91+1.50 i 1.58-0.90 i -8.87+0.00 i -1.84-0.03 i -1.78+1.18 i 2.21+0.21 i -1.84+0.03 i -4.63+0.00 i 0.11+0.11 i 3.91-1.50 i -1.78-1.18 i 0.11-0.11 i -1.84+0.00 i .
Here A is Hermitian indefinite, stored in packed form, and must first be factorized by F07PRF (ZHPTRF).

10.1 Program Text

Program Text (f07pwfe.f90)

10.2 Program Data

Program Data (f07pwfe.d)

10.3 Program Results

Program Results (f07pwfe.r)

F07 Chapter Contents
F07 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F07QNF (ZSPSV) : NAG Library, Mark 26

F07 Chapter Contents
F07 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F07QNF (ZSPSV)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F07QNF (ZSPSV) computes the solution to a complex system of linear equations
AX=B ,
where A is an n by n symmetric matrix stored in packed format and X and B are n by r matrices.

2 Specification

SUBROUTINE F07QNF ( UPLO, N, NRHS, AP, IPIV, B, LDB, INFO)
INTEGER | N, NRHS, IPIV(N), LDB, INFO
COMPLEX (KIND=nag_wp) | AP(*), B(LDB,*)
CHARACTER(1) | UPLO
The routine may be called by its LAPACK name zspsv.

3 Description

F07QNF (ZSPSV) uses the diagonal pivoting method to factor A as A=UD UT if UPLO='U' or A=LD LT if UPLO='L', where U (or L) is a product of permutation and unit upper (lower) triangular matrices, D is symmetric and block diagonal with 1 by 1 and 2 by 2 diagonal blocks. The factored form of A is then used to solve the system of equations AX=B.

4 References

Anderson E, Bai Z, Bischof C, Blackford S, Demmel J, Dongarra J J, Du Croz J J, Greenbaum A, Hammarling S, McKenney A and Sorensen D (1999) LAPACK Users' Guide (3rd Edition) SIAM, Philadelphia http://www.netlib.org/lapack/lug
Golub G H and Van Loan C F (1996) Matrix Computations (3rd Edition) Johns Hopkins University Press, Baltimore
Higham N J (2002) Accuracy and Stability of Numerical Algorithms (2nd Edition) SIAM, Philadelphia

5 Arguments

1:   UPLO – CHARACTER(1)Input
On entry: if UPLO='U', the upper triangle of A is stored.
If UPLO='L', the lower triangle of A is stored.
Constraint: UPLO='U' or 'L'.
2:   N – INTEGERInput
On entry: n, the number of linear equations, i.e., the order of the matrix A.
Constraint: N≥0.
3:   NRHS – INTEGERInput
On entry: r, the number of right-hand sides, i.e., the number of columns of the matrix B.
Constraint: NRHS≥0.
4:   AP* – COMPLEX (KIND=nag_wp) arrayInput/Output
Note: the dimension of the array AP must be at least max 1,N×N+1/2.
On entry: the n by n symmetric matrix A, packed by columns.
More precisely,
  • if UPLO='U', the upper triangle of A must be stored with element A ij in AP i+j j-1/2 for i≤j;
  • if UPLO='L', the lower triangle of A must be stored with element A ij in AP i+2 n-jj-1/2 for i≥j.
On exit: the block diagonal matrix D and the multipliers used to obtain the factor U or L from the factorization A=UD UT or A=LD LT as computed by F07QRF (ZSPTRF), stored as a packed triangular matrix in the same storage format as A.
5:   IPIV N – INTEGER arrayOutput
On exit: details of the interchanges and the block structure of D. More precisely,
  • if IPIV i=k>0, d ii is a 1 by 1 pivot block and the ith row and column of A were interchanged with the kth row and column;
  • if UPLO='U' and IPIV i-1=IPIV i=-l<0, d i-1,i-1d-i,i-1 d-i,i-1d ii is a 2 by 2 pivot block and the i-1th row and column of A were interchanged with the lth row and column;
  • if UPLO='L' and IPIV i=IPIV i+1=-m<0, d iid i+1,id i+1,id i+1,i+1 is a 2 by 2 pivot block and the i+1th row and column of A were interchanged with the mth row and column.
6:   B LDB* – COMPLEX (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array B must be at least max 1,NRHS.
To solve the equations Ax=b, where b is a single right-hand side, B may be supplied as a one-dimensional array with length LDB=max 1,N.
On entry: the n by r right-hand side matrix B.
On exit: if INFO=0, the n by r solution matrix X.
7:   LDB – INTEGERInput
On entry: the first dimension of the array B as declared in the (sub)program from which F07QNF (ZSPSV) is called.
Constraint: LDB≥max 1,N.
8:   INFO – INTEGEROutput
On exit: INFO=0 unless the routine detects an error (see Section 6).

6 Error Indicators and Warnings

INFO<0
If INFO=-i, argument i had an illegal value. An explanatory message is output, and execution of the program is terminated.
INFO>0
Element value of the diagonal is exactly zero. The factorization has been completed, but the block diagonal matrix D is exactly singular, so the solution could not be computed.

7 Accuracy

The computed solution for a single right-hand side, x^ , satisfies an equation of the form
A+E x^=b ,
where
E 1 = O ε A 1
and ε is the machine precision. An approximate error bound for the computed solution is given by
x^-x 1 x 1 ≤ κ A E 1 A 1 ,
where κ A = A-1 1 A 1 , the condition number of A with respect to the solution of the linear equations. See Section 4.4 of Anderson et al. (1999) and Chapter 11 of Higham (2002) for further details.
F07QPF (ZSPSVX) is a comprehensive LAPACK driver that returns forward and backward error bounds and an estimate of the condition number. Alternatively, F04DJF solves AX=B and returns a forward error bound and condition estimate. F04DJF calls F07QNF (ZSPSV) to solve the equations.

8 Parallelism and Performance

F07QNF (ZSPSV) makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The total number of floating-point operations is approximately 43 n 3 + 8⁢n 2 r , where r is the number of right-hand sides.
The real analogue of this routine is F07PAF (DSPSV). The complex Hermitian analogue of this routine is F07PNF (ZHPSV).

10 Example

This example solves the equations
Ax=b ,
where A is the complex symmetric matrix
A = -0.56+0.12 i -1.54-2.86 i 5.32-1.59 i 3.80+0.92 i -1.54-2.86 i -2.83-0.03 i -3.52+0.58 i -7.86-2.96 i 5.32-1.59 i -3.52+0.58 i 8.86+1.81 i 5.14-0.64 i 3.80+0.92 i -7.86-2.96 i 5.14-0.64 i -0.39-0.71 i
and
b = -6.43+19.24 i -0.49-0 1.47 i -48.18+66.00 i -55.64+41.22 i .
Details of the factorization of A are also output.

10.1 Program Text

Program Text (f07qnfe.f90)

10.2 Program Data

Program Data (f07qnfe.d)

10.3 Program Results

Program Results (f07qnfe.r)

F07 Chapter Contents
F07 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F07QPF (ZSPSVX) : NAG Library, Mark 26

F07 Chapter Contents
F07 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F07QPF (ZSPSVX)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F07QPF (ZSPSVX) uses the diagonal pivoting factorization
A=UD UT   or   A=LD LT
to compute the solution to a complex system of linear equations
AX=B ,
where A is an n by n symmetric matrix stored in packed format and X and B are n by r matrices. Error bounds on the solution and a condition estimate are also provided.

2 Specification

SUBROUTINE F07QPF ( FACT, UPLO, N, NRHS, AP, AFP, IPIV, B, LDB, X, LDX, RCOND, FERR, BERR, WORK, RWORK, INFO)
INTEGER | N, NRHS, IPIV(N), LDB, LDX, INFO
REAL (KIND=nag_wp) | RCOND, FERR(NRHS), BERR(NRHS), RWORK(N)
COMPLEX (KIND=nag_wp) | AP(*), AFP(*), B(LDB,*), X(LDX,*), WORK(2*N)
CHARACTER(1) | FACT, UPLO
The routine may be called by its LAPACK name zspsvx.

3 Description

F07QPF (ZSPSVX) performs the following steps:
1. | If FACT='N', the diagonal pivoting method is used to factor A as A=UD UT if UPLO='U' or A=LD LT if UPLO='L', where U (or L) is a product of permutation and unit upper (lower) triangular matrices and D is symmetric and block diagonal with 1 by 1 and 2 by 2 diagonal blocks.
2. | If some d ii=0, so that D is exactly singular, then the routine returns with INFO=i. Otherwise, the factored form of A is used to estimate the condition number of the matrix A. If the reciprocal of the condition number is less than machine precision, INFO=N+1 is returned as a warning, but the routine still goes on to solve for X and compute error bounds as described below.
3. | The system of equations is solved for X using the factored form of A.
4. | Iterative refinement is applied to improve the computed solution matrix and to calculate error bounds and backward error estimates for it.

4 References

Anderson E, Bai Z, Bischof C, Blackford S, Demmel J, Dongarra J J, Du Croz J J, Greenbaum A, Hammarling S, McKenney A and Sorensen D (1999) LAPACK Users' Guide (3rd Edition) SIAM, Philadelphia http://www.netlib.org/lapack/lug
Golub G H and Van Loan C F (1996) Matrix Computations (3rd Edition) Johns Hopkins University Press, Baltimore
Higham N J (2002) Accuracy and Stability of Numerical Algorithms (2nd Edition) SIAM, Philadelphia

5 Arguments

1:   FACT – CHARACTER(1)Input
On entry: specifies whether or not the factorized form of the matrix A has been supplied.
FACT='F'
AFP and IPIV contain the factorized form of the matrix A. AFP and IPIV will not be modified.
FACT='N'
The matrix A will be copied to AFP and factorized.
Constraint: FACT='F' or 'N'.
2:   UPLO – CHARACTER(1)Input
On entry: if UPLO='U', the upper triangle of A is stored.
If UPLO='L', the lower triangle of A is stored.
Constraint: UPLO='U' or 'L'.
3:   N – INTEGERInput
On entry: n, the number of linear equations, i.e., the order of the matrix A.
Constraint: N≥0.
4:   NRHS – INTEGERInput
On entry: r, the number of right-hand sides, i.e., the number of columns of the matrix B.
Constraint: NRHS≥0.
5:   AP* – COMPLEX (KIND=nag_wp) arrayInput
Note: the dimension of the array AP must be at least max 1,N×N+1/2.
On entry: the n by n symmetric matrix A, packed by columns.
More precisely,
  • if UPLO='U', the upper triangle of A must be stored with element A ij in AP i+j j-1/2 for i≤j;
  • if UPLO='L', the lower triangle of A must be stored with element A ij in AP i+2 n-jj-1/2 for i≥j.
6:   AFP* – COMPLEX (KIND=nag_wp) arrayInput/Output
Note: the dimension of the array AFP must be at least max 1,N×N+1/2.
On entry: if FACT='F', AFP contains the block diagonal matrix D and the multipliers used to obtain the factor U or L from the factorization A=UD UT or A=LD LT as computed by F07QRF (ZSPTRF), stored as a packed triangular matrix in the same storage format as A.
On exit: if FACT='N', AFP contains the block diagonal matrix D and the multipliers used to obtain the factor U or L from the factorization A=UD UT or A=LD LT as computed by F07QRF (ZSPTRF), stored as a packed triangular matrix in the same storage format as A.
7:   IPIV N – INTEGER arrayInput/Output
On entry: if FACT='F', IPIV contains details of the interchanges and the block structure of D, as determined by F07QRF (ZSPTRF).
  • if IPIV i=k>0, d ii is a 1 by 1 pivot block and the ith row and column of A were interchanged with the kth row and column;
  • if UPLO='U' and IPIV i-1=IPIV i=-l<0, d i-1,i-1d-i,i-1 d-i,i-1d ii is a 2 by 2 pivot block and the i-1th row and column of A were interchanged with the lth row and column;
  • if UPLO='L' and IPIV i=IPIV i+1=-m<0, d iid i+1,id i+1,id i+1,i+1 is a 2 by 2 pivot block and the i+1th row and column of A were interchanged with the mth row and column.
On exit: if FACT='N', IPIV contains details of the interchanges and the block structure of D, as determined by F07QRF (ZSPTRF), as described above.
8:   B LDB* – COMPLEX (KIND=nag_wp) arrayInput
Note: the second dimension of the array B must be at least max 1,NRHS.
On entry: the n by r right-hand side matrix B.
9:   LDB – INTEGERInput
On entry: the first dimension of the array B as declared in the (sub)program from which F07QPF (ZSPSVX) is called.
Constraint: LDB≥max 1,N.
10:   X LDX* – COMPLEX (KIND=nag_wp) arrayOutput
Note: the second dimension of the array X must be at least max 1,NRHS.
On exit: if INFO=0 or N+1, the n by r solution matrix X.
11:   LDX – INTEGERInput
On entry: the first dimension of the array X as declared in the (sub)program from which F07QPF (ZSPSVX) is called.
Constraint: LDX≥max 1,N.
12:   RCOND – REAL (KIND=nag_wp)Output
On exit: the estimate of the reciprocal condition number of the matrix A. If RCOND=0.0, the matrix may be exactly singular. This condition is indicated by INFO>0 and INFO≤N. Otherwise, if RCOND is less than the machine precision, the matrix is singular to working precision. This condition is indicated by INFO=N+1.
13:   FERR NRHS – REAL (KIND=nag_wp) arrayOutput
On exit: if INFO=0 or N+1, an estimate of the forward error bound for each computed solution vector, such that x^j-xj∞/xj∞≤FERR j where x^j is the jth column of the computed solution returned in the array X and xj is the corresponding column of the exact solution X. The estimate is as reliable as the estimate for RCOND, and is almost always a slight overestimate of the true error.
14:   BERR NRHS – REAL (KIND=nag_wp) arrayOutput
On exit: if INFO=0 or N+1, an estimate of the component-wise relative backward error of each computed solution vector x^j (i.e., the smallest relative change in any element of A or B that makes x^j an exact solution).
15:   WORK 2×N – COMPLEX (KIND=nag_wp) arrayWorkspace
16:   RWORK N – REAL (KIND=nag_wp) arrayWorkspace
17:   INFO – INTEGEROutput
On exit: INFO=0 unless the routine detects an error (see Section 6).

6 Error Indicators and Warnings

INFO<0
If INFO=-i, argument i had an illegal value. An explanatory message is output, and execution of the program is terminated.
INFO>0 and INFO≤N
Element value of the diagonal is exactly zero. The factorization has been completed, but the factor D is exactly singular, so the solution and error bounds could not be computed. RCOND=0.0 is returned.
INFO=N+1
D is nonsingular, but RCOND is less than machine precision, meaning that the matrix is singular to working precision. Nevertheless, the solution and error bounds are computed because there are a number of situations where the computed solution can be more accurate than the value of RCOND would suggest.

7 Accuracy

For each right-hand side vector b, the computed solution x^ is the exact solution of a perturbed system of equations A+E x^=b, where
E 1 = O ε A 1 ,
where ε is the machine precision. See Chapter 11 of Higham (2002) for further details.
If x^ is the true solution, then the computed solution x satisfies a forward error bound of the form
x-x^∞ x^∞ ≤ wc cond A,x^,b
where cond A,x^,b = A-1 A x^ + b ∞/ x^∞ ≤ cond A = A-1 A ∞≤κ∞ A. If x^ is the j th column of X , then wc is returned in BERR j and a bound on x - x^ ∞ / x^ ∞ is returned in FERR j . See Section 4.4 of Anderson et al. (1999) for further details.

8 Parallelism and Performance

F07QPF (ZSPSVX) is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
F07QPF (ZSPSVX) makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The factorization of A requires approximately 43 n 3 floating-point operations.
For each right-hand side, computation of the backward error involves a minimum of 16⁢n 2 floating-point operations. Each step of iterative refinement involves an additional 24⁢n 2 operations. At most five steps of iterative refinement are performed, but usually only one or two steps are required. Estimating the forward error involves solving a number of systems of equations of the form Ax=b ; the number is usually 4 or 5 and never more than 11. Each solution involves approximately 8⁢n 2 operations.
The real analogue of this routine is F07PBF (DSPSVX). The complex Hermitian analogue of this routine is F07PPF (ZHPSVX).

10 Example

This example solves the equations
AX=B ,
where A is the complex symmetric matrix
A = -0.56+0.12 i -1.54-2.86 i 5.32-1.59 i 3.80+0.92 i -1.54-2.86 i -2.83-0.03 i -3.52+0.58 i -7.86-2.96 i 5.32-1.59 i -3.52+0.58 i 8.86+1.81 i 5.14-0.64 i 3.80+0.92 i -7.86-2.96 i 5.14-0.64 i -0.39-0.71 i
and
B = -6.43+19.24 i -4.59-35.53 i -0.49-0 1.47 i 6.95+20.49 i -48.18+66.00 i -12.08-27.02 i -55.64+41.22 i -19.09-35.97 i .
Error estimates for the solutions, and an estimate of the reciprocal of the condition number of the matrix A are also output.

10.1 Program Text

Program Text (f07qpfe.f90)

10.2 Program Data

Program Data (f07qpfe.d)

10.3 Program Results

Program Results (f07qpfe.r)

F07 Chapter Contents
F07 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F07QRF (ZSPTRF) : NAG Library, Mark 26

F07 Chapter Contents
F07 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F07QRF (ZSPTRF)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F07QRF (ZSPTRF) computes the Bunch–Kaufman factorization of a complex symmetric matrix, using packed storage.

2 Specification

SUBROUTINE F07QRF ( UPLO, N, AP, IPIV, INFO)
INTEGER | N, IPIV(N), INFO
COMPLEX (KIND=nag_wp) | AP(*)
CHARACTER(1) | UPLO
The routine may be called by its LAPACK name zsptrf.

3 Description

F07QRF (ZSPTRF) factorizes a complex symmetric matrix A, using the Bunch–Kaufman diagonal pivoting method and packed storage. A is factorized as either A=PUD UTPT if UPLO='U' or A=PLD LTPT if UPLO='L', where P is a permutation matrix, U (or L) is a unit upper (or lower) triangular matrix and D is a symmetric block diagonal matrix with 1 by 1 and 2 by 2 diagonal blocks; U (or L) has 2 by 2 unit diagonal blocks corresponding to the 2 by 2 blocks of D. Row and column interchanges are performed to ensure numerical stability while preserving symmetry.

4 References

Golub G H and Van Loan C F (1996) Matrix Computations (3rd Edition) Johns Hopkins University Press, Baltimore

5 Arguments

1:   UPLO – CHARACTER(1)Input
On entry: specifies whether the upper or lower triangular part of A is stored and how A is to be factorized.
UPLO='U'
The upper triangular part of A is stored and A is factorized as PUD UTPT, where U is upper triangular.
UPLO='L'
The lower triangular part of A is stored and A is factorized as PLD LTPT, where L is lower triangular.
Constraint: UPLO='U' or 'L'.
2:   N – INTEGERInput
On entry: n, the order of the matrix A.
Constraint: N≥0.
3:   AP* – COMPLEX (KIND=nag_wp) arrayInput/Output
Note: the dimension of the array AP must be at least max 1,N×N+1/2.
On entry: the n by n symmetric matrix A, packed by columns.
More precisely,
  • if UPLO='U', the upper triangle of A must be stored with element A ij in AP i+j j-1/2 for i≤j;
  • if UPLO='L', the lower triangle of A must be stored with element A ij in AP i+2 n-jj-1/2 for i≥j.
On exit: A is overwritten by details of the block diagonal matrix D and the multipliers used to obtain the factor U or L as specified by UPLO.
4:   IPIV N – INTEGER arrayOutput
On exit: details of the interchanges and the block structure of D. More precisely,
  • if IPIV i=k>0, d ii is a 1 by 1 pivot block and the ith row and column of A were interchanged with the kth row and column;
  • if UPLO='U' and IPIV i-1=IPIV i=-l<0, d i-1,i-1d-i,i-1 d-i,i-1d ii is a 2 by 2 pivot block and the i-1th row and column of A were interchanged with the lth row and column;
  • if UPLO='L' and IPIV i=IPIV i+1=-m<0, d iid i+1,id i+1,id i+1,i+1 is a 2 by 2 pivot block and the i+1th row and column of A were interchanged with the mth row and column.
5:   INFO – INTEGEROutput
On exit: INFO=0 unless the routine detects an error (see Section 6).

6 Error Indicators and Warnings

INFO<0
If INFO=-i, argument i had an illegal value. An explanatory message is output, and execution of the program is terminated.
INFO>0
Element value of the diagonal is exactly zero. The factorization has been completed, but the block diagonal matrix D is exactly singular, and division by zero will occur if it is used to solve a system of equations.

7 Accuracy

If UPLO='U', the computed factors U and D are the exact factors of a perturbed matrix A+E, where
E≤c n εP UDUT PT ,
c n is a modest linear function of n, and ε is the machine precision.
If UPLO='L', a similar statement holds for the computed factors L and D.

8 Parallelism and Performance

F07QRF (ZSPTRF) makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The elements of D overwrite the corresponding elements of A; if D has 2 by 2 blocks, only the upper or lower triangle is stored, as specified by UPLO.
The unit diagonal elements of U or L and the 2 by 2 unit diagonal blocks are not stored. The remaining elements of U or L overwrite elements in the corresponding columns of A, but additional row interchanges must be applied to recover U or L explicitly (this is seldom necessary). If IPIV i=i, for i=1,2,…,n, then U or L are stored explicitly in packed form (except for their unit diagonal elements which are equal to 1).
The total number of real floating-point operations is approximately 43 n 3.
A call to F07QRF (ZSPTRF) may be followed by calls to the routines:
  • F07QSF (ZSPTRS) to solve AX=B;
  • F07QUF (ZSPCON) to estimate the condition number of A;
  • F07QWF (ZSPTRI) to compute the inverse of A.
The real analogue of this routine is F07PDF (DSPTRF).

10 Example

This example computes the Bunch–Kaufman factorization of the matrix A, where
A= -0.39-0.71 i 5.14-0.64 i -7.86-2.96 i 3.80+0.92 i 5.14-0.64 i 8.86+1.81 i -3.52+0.58 i 5.32-1.59 i -7.86-2.96 i -3.52+0.58 i -2.83-0.03 i -1.54-2.86 i 3.80+0.92 i 5.32-1.59 i -1.54-2.86 i -0.56+0.12 i ,
using packed storage.

10.1 Program Text

Program Text (f07qrfe.f90)

10.2 Program Data

Program Data (f07qrfe.d)

10.3 Program Results

Program Results (f07qrfe.r)

F07 Chapter Contents
F07 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F07QSF (ZSPTRS) : NAG Library, Mark 26

F07 Chapter Contents
F07 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F07QSF (ZSPTRS)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F07QSF (ZSPTRS) solves a complex symmetric system of linear equations with multiple right-hand sides,
AX=B ,
where A has been factorized by F07QRF (ZSPTRF), using packed storage.

2 Specification

SUBROUTINE F07QSF ( UPLO, N, NRHS, AP, IPIV, B, LDB, INFO)
INTEGER | N, NRHS, IPIV(*), LDB, INFO
COMPLEX (KIND=nag_wp) | AP(*), B(LDB,*)
CHARACTER(1) | UPLO
The routine may be called by its LAPACK name zsptrs.

3 Description

F07QSF (ZSPTRS) is used to solve a complex symmetric system of linear equations AX=B, the routine must be preceded by a call to F07QRF (ZSPTRF) which computes the Bunch–Kaufman factorization of A, using packed storage.
If UPLO='U', A=PUD UTPT, where P is a permutation matrix, U is an upper triangular matrix and D is a symmetric block diagonal matrix with 1 by 1 and 2 by 2 blocks; the solution X is computed by solving PUDY=B and then UTPT X=Y.
If UPLO='L', A=PLD LTPT, where L is a lower triangular matrix; the solution X is computed by solving PLDY=B and then LTPT X=Y.

4 References

Golub G H and Van Loan C F (1996) Matrix Computations (3rd Edition) Johns Hopkins University Press, Baltimore

5 Arguments

1:   UPLO – CHARACTER(1)Input
On entry: specifies how A has been factorized.
UPLO='U'
A=PUD UTPT, where U is upper triangular.
UPLO='L'
A=PLD LTPT, where L is lower triangular.
Constraint: UPLO='U' or 'L'.
2:   N – INTEGERInput
On entry: n, the order of the matrix A.
Constraint: N≥0.
3:   NRHS – INTEGERInput
On entry: r, the number of right-hand sides.
Constraint: NRHS≥0.
4:   AP* – COMPLEX (KIND=nag_wp) arrayInput
Note: the dimension of the array AP must be at least max 1,N×N+1/2.
On entry: the factorization of A stored in packed form, as returned by F07QRF (ZSPTRF).
5:   IPIV* – INTEGER arrayInput
Note: the dimension of the array IPIV must be at least max 1,N.
On entry: details of the interchanges and the block structure of D, as returned by F07QRF (ZSPTRF).
6:   B LDB* – COMPLEX (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array B must be at least max 1,NRHS.
On entry: the n by r right-hand side matrix B.
On exit: the n by r solution matrix X.
7:   LDB – INTEGERInput
On entry: the first dimension of the array B as declared in the (sub)program from which F07QSF (ZSPTRS) is called.
Constraint: LDB≥max 1,N.
8:   INFO – INTEGEROutput
On exit: INFO=0 unless the routine detects an error (see Section 6).

6 Error Indicators and Warnings

INFO<0
If INFO=-i, argument i had an illegal value. An explanatory message is output, and execution of the program is terminated.

7 Accuracy

For each right-hand side vector b, the computed solution x is the exact solution of a perturbed system of equations A+E x=b, where
  • if UPLO='U', E≤c n εP UDUT PT;
  • if UPLO='L', E≤c n εP LDLT PT,
c n is a modest linear function of n, and ε is the machine precision.
If x^ is the true solution, then the computed solution x satisfies a forward error bound of the form
x-x^∞ x∞ ≤c n cond A,x ε
where cond A,x=A-1Ax∞/x∞≤cond A=A-1A∞≤κ∞A.
Note that cond A,x can be much smaller than cond A.
Forward and backward error bounds can be computed by calling F07QVF (ZSPRFS), and an estimate for κ∞A (=κ 1 A) can be obtained by calling F07QUF (ZSPCON).

8 Parallelism and Performance

F07QSF (ZSPTRS) makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The total number of real floating-point operations is approximately 8⁢n 2 r.
This routine may be followed by a call to F07QVF (ZSPRFS) to refine the solution and return an error estimate.
The real analogue of this routine is F07PEF (DSPTRS).

10 Example

This example solves the system of equations AX=B, where
A= -0.39-0.71 i 5.14-0.64 i -7.86-2.96 i 3.80+0.92 i 5.14-0.64 i 8.86+1.81 i -3.52+0.58 i 5.32-1.59 i -7.86-2.96 i -3.52+0.58 i -2.83-0.03 i -1.54-2.86 i 3.80+0.92 i 5.32-1.59 i -1.54-2.86 i -0.56+0.12 i
and
B= -55.64+41.22 i -19.09-35.97 i -48.18+66.00 i -12.08-27.02 i -0.49-0 1.47 i 6.95+20.49 i -6.43+19.24 i -4.59-35.53 i .
Here A is symmetric, stored in packed form, and must first be factorized by F07QRF (ZSPTRF).

10.1 Program Text

Program Text (f07qsfe.f90)

10.2 Program Data

Program Data (f07qsfe.d)

10.3 Program Results

Program Results (f07qsfe.r)

F07 Chapter Contents
F07 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F07QUF (ZSPCON) : NAG Library, Mark 26

F07 Chapter Contents
F07 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F07QUF (ZSPCON)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F07QUF (ZSPCON) estimates the condition number of a complex symmetric matrix A, where A has been factorized by F07QRF (ZSPTRF), using packed storage.

2 Specification

SUBROUTINE F07QUF ( UPLO, N, AP, IPIV, ANORM, RCOND, WORK, INFO)
INTEGER | N, IPIV(*), INFO
REAL (KIND=nag_wp) | ANORM, RCOND
COMPLEX (KIND=nag_wp) | AP(*), WORK(2*N)
CHARACTER(1) | UPLO
The routine may be called by its LAPACK name zspcon.

3 Description

F07QUF (ZSPCON) estimates the condition number (in the 1-norm) of a complex symmetric matrix A:
κ 1 A=A 1A-1 1 .
Since A is symmetric, κ 1 A=κ∞A=A∞A-1∞.
Because κ 1 A is infinite if A is singular, the routine actually returns an estimate of the reciprocal of κ 1 A.
The routine should be preceded by a call to F06UGF to compute A 1 and a call to F07QRF (ZSPTRF) to compute the Bunch–Kaufman factorization of A. The routine then uses Higham's implementation of Hager's method (see Higham (1988)) to estimate A-1 1.

4 References

Higham N J (1988) FORTRAN codes for estimating the one-norm of a real or complex matrix, with applications to condition estimation ACM Trans. Math. Software 14 381–396

5 Arguments

1:   UPLO – CHARACTER(1)Input
On entry: specifies how A has been factorized.
UPLO='U'
A=PUD UTPT, where U is upper triangular.
UPLO='L'
A=PLD LTPT, where L is lower triangular.
Constraint: UPLO='U' or 'L'.
2:   N – INTEGERInput
On entry: n, the order of the matrix A.
Constraint: N≥0.
3:   AP* – COMPLEX (KIND=nag_wp) arrayInput
Note: the dimension of the array AP must be at least max 1,N×N+1/2.
On entry: the factorization of A stored in packed form, as returned by F07QRF (ZSPTRF).
4:   IPIV* – INTEGER arrayInput
Note: the dimension of the array IPIV must be at least max 1,N.
On entry: details of the interchanges and the block structure of D, as returned by F07QRF (ZSPTRF).
5:   ANORM – REAL (KIND=nag_wp)Input
On entry: the 1-norm of the original matrix A, which may be computed by calling F06UGF with its argument NORM='1'. ANORM must be computed either before calling F07QRF (ZSPTRF) or else from a copy of the original matrix A.
Constraint: ANORM≥0.0.
6:   RCOND – REAL (KIND=nag_wp)Output
On exit: an estimate of the reciprocal of the condition number of A. RCOND is set to zero if exact singularity is detected or the estimate underflows. If RCOND is less than machine precision, A is singular to working precision.
7:   WORK 2×N – COMPLEX (KIND=nag_wp) arrayWorkspace
8:   INFO – INTEGEROutput
On exit: INFO=0 unless the routine detects an error (see Section 6).

6 Error Indicators and Warnings

INFO<0
If INFO=-i, argument i had an illegal value. An explanatory message is output, and execution of the program is terminated.

7 Accuracy

The computed estimate RCOND is never less than the true value ρ, and in practice is nearly always less than 10 ρ, although examples can be constructed where RCOND is much larger.

8 Parallelism and Performance

F07QUF (ZSPCON) makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

A call to F07QUF (ZSPCON) involves solving a number of systems of linear equations of the form Ax=b; the number is usually 5 and never more than 11. Each solution involves approximately 8⁢n 2 real floating-point operations but takes considerably longer than a call to F07QSF (ZSPTRS) with one right-hand side, because extra care is taken to avoid overflow when A is approximately singular.
The real analogue of this routine is F07PGF (DSPCON).

10 Example

This example estimates the condition number in the 1-norm (or ∞-norm) of the matrix A, where
A= -0.39-0.71 i 5.14-0.64 i -7.86-2.96 i 3.80+0.92 i 5.14-0.64 i 8.86+1.81 i -3.52+0.58 i 5.32-1.59 i -7.86-2.96 i -3.52+0.58 i -2.83-0.03 i -1.54-2.86 i 3.80+0.92 i 5.32-1.59 i -1.54-2.86 i -0.56+0.12 i .
Here A is symmetric, stored in packed form, and must first be factorized by F07QRF (ZSPTRF). The true condition number in the 1-norm is 32.92.

10.1 Program Text

Program Text (f07qufe.f90)

10.2 Program Data

Program Data (f07qufe.d)

10.3 Program Results

Program Results (f07qufe.r)

F07 Chapter Contents
F07 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F07QVF (ZSPRFS) : NAG Library, Mark 26

F07 Chapter Contents
F07 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F07QVF (ZSPRFS)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F07QVF (ZSPRFS) returns error bounds for the solution of a complex symmetric system of linear equations with multiple right-hand sides, AX=B, using packed storage. It improves the solution by iterative refinement, in order to reduce the backward error as much as possible.

2 Specification

SUBROUTINE F07QVF ( UPLO, N, NRHS, AP, AFP, IPIV, B, LDB, X, LDX, FERR, BERR, WORK, RWORK, INFO)
INTEGER | N, NRHS, IPIV(*), LDB, LDX, INFO
REAL (KIND=nag_wp) | FERR(NRHS), BERR(NRHS), RWORK(N)
COMPLEX (KIND=nag_wp) | AP(*), AFP(*), B(LDB,*), X(LDX,*), WORK(2*N)
CHARACTER(1) | UPLO
The routine may be called by its LAPACK name zsprfs.

3 Description

F07QVF (ZSPRFS) returns the backward errors and estimated bounds on the forward errors for the solution of a complex symmetric system of linear equations with multiple right-hand sides AX=B, using packed storage. The routine handles each right-hand side vector (stored as a column of the matrix B) independently, so we describe the function of F07QVF (ZSPRFS) in terms of a single right-hand side b and solution x.
Given a computed solution x, the routine computes the component-wise backward error β. This is the size of the smallest relative perturbation in each element of A and b such that x is the exact solution of a perturbed system
A+δA x=b+δb δ a ij≤β a ij   and   δ bi≤β bi .
Then the routine estimates a bound for the component-wise forward error in the computed solution, defined by:
maxi xi-x^i/maxi xi
where x^ is the true solution.
For details of the method, see the F07 Chapter Introduction.

4 References

Golub G H and Van Loan C F (1996) Matrix Computations (3rd Edition) Johns Hopkins University Press, Baltimore

5 Arguments

1:   UPLO – CHARACTER(1)Input
On entry: specifies whether the upper or lower triangular part of A is stored and how A is to be factorized.
UPLO='U'
The upper triangular part of A is stored and A is factorized as PUD UTPT, where U is upper triangular.
UPLO='L'
The lower triangular part of A is stored and A is factorized as PLD LTPT, where L is lower triangular.
Constraint: UPLO='U' or 'L'.
2:   N – INTEGERInput
On entry: n, the order of the matrix A.
Constraint: N≥0.
3:   NRHS – INTEGERInput
On entry: r, the number of right-hand sides.
Constraint: NRHS≥0.
4:   AP* – COMPLEX (KIND=nag_wp) arrayInput
Note: the dimension of the array AP must be at least max 1,N×N+1/2.
On entry: the n by n original symmetric matrix A as supplied to F07QRF (ZSPTRF).
5:   AFP* – COMPLEX (KIND=nag_wp) arrayInput
Note: the dimension of the array AFP must be at least max 1,N×N+1/2.
On entry: the factorization of A stored in packed form, as returned by F07QRF (ZSPTRF).
6:   IPIV* – INTEGER arrayInput
Note: the dimension of the array IPIV must be at least max 1,N.
On entry: details of the interchanges and the block structure of D, as returned by F07QRF (ZSPTRF).
7:   B LDB* – COMPLEX (KIND=nag_wp) arrayInput
Note: the second dimension of the array B must be at least max 1,NRHS.
On entry: the n by r right-hand side matrix B.
8:   LDB – INTEGERInput
On entry: the first dimension of the array B as declared in the (sub)program from which F07QVF (ZSPRFS) is called.
Constraint: LDB≥max 1,N.
9:   X LDX* – COMPLEX (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array X must be at least max 1,NRHS.
On entry: the n by r solution matrix X, as returned by F07QSF (ZSPTRS).
On exit: the improved solution matrix X.
10:   LDX – INTEGERInput
On entry: the first dimension of the array X as declared in the (sub)program from which F07QVF (ZSPRFS) is called.
Constraint: LDX≥max 1,N.
11:   FERR NRHS – REAL (KIND=nag_wp) arrayOutput
On exit: FERR j contains an estimated error bound for the jth solution vector, that is, the jth column of X, for j=1,2,…,r.
12:   BERR NRHS – REAL (KIND=nag_wp) arrayOutput
On exit: BERR j contains the component-wise backward error bound β for the jth solution vector, that is, the jth column of X, for j=1,2,…,r.
13:   WORK 2×N – COMPLEX (KIND=nag_wp) arrayWorkspace
14:   RWORK N – REAL (KIND=nag_wp) arrayWorkspace
15:   INFO – INTEGEROutput
On exit: INFO=0 unless the routine detects an error (see Section 6).

6 Error Indicators and Warnings

INFO<0
If INFO=-i, argument i had an illegal value. An explanatory message is output, and execution of the program is terminated.

7 Accuracy

The bounds returned in FERR are not rigorous, because they are estimated, not computed exactly; but in practice they almost always overestimate the actual error.

8 Parallelism and Performance

F07QVF (ZSPRFS) is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
F07QVF (ZSPRFS) makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

For each right-hand side, computation of the backward error involves a minimum of 16 n 2 real floating-point operations. Each step of iterative refinement involves an additional 24 n 2 real operations. At most five steps of iterative refinement are performed, but usually only one or two steps are required.
Estimating the forward error involves solving a number of systems of linear equations of the form Ax=b; the number is usually 5 and never more than 11. Each solution involves approximately 8 n 2 real operations.
The real analogue of this routine is F07PHF (DSPRFS).

10 Example

This example solves the system of equations AX=B using iterative refinement and to compute the forward and backward error bounds, where
A= -0.39-0.71 i 5.14-0.64 i -7.86-2.96 i 3.80+0.92 i 5.14-0.64 i 8.86+1.81 i -3.52+0.58 i 5.32-1.59 i -7.86-2.96 i -3.52+0.58 i -2.83-0.03 i -1.54-2.86 i 3.80+0.92 i 5.32-1.59 i -1.54-2.86 i -0.56+0.12 i
and
B= -55.64+41.22 i -19.09-35.97 i -48.18+66.00 i -12.08-27.02 i -0.49-0 1.47 i 6.95+20.49 i -6.43+19.24 i -4.59-35.53 i .
Here A is symmetric, stored in packed form, and must first be factorized by F07QRF (ZSPTRF).

10.1 Program Text

Program Text (f07qvfe.f90)

10.2 Program Data

Program Data (f07qvfe.d)

10.3 Program Results

Program Results (f07qvfe.r)

F07 Chapter Contents
F07 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F07QWF (ZSPTRI) : NAG Library, Mark 26

F07 Chapter Contents
F07 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F07QWF (ZSPTRI)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F07QWF (ZSPTRI) computes the inverse of a complex symmetric matrix A, where A has been factorized by F07QRF (ZSPTRF), using packed storage.

2 Specification

SUBROUTINE F07QWF ( UPLO, N, AP, IPIV, WORK, INFO)
INTEGER | N, IPIV(*), INFO
COMPLEX (KIND=nag_wp) | AP(*), WORK(N)
CHARACTER(1) | UPLO
The routine may be called by its LAPACK name zsptri.

3 Description

F07QWF (ZSPTRI) is used to compute the inverse of a complex symmetric matrix A, the routine must be preceded by a call to F07QRF (ZSPTRF), which computes the Bunch–Kaufman factorization of A, using packed storage.
If UPLO='U', A=PUD UTPT and A-1 is computed by solving UTPT XPU=D-1.
If UPLO='L', A=PLD LTPT and A-1 is computed by solving LTPT XPL=D-1.

4 References

Du Croz J J and Higham N J (1992) Stability of methods for matrix inversion IMA J. Numer. Anal. 12 1–19

5 Arguments

1:   UPLO – CHARACTER(1)Input
On entry: specifies how A has been factorized.
UPLO='U'
A=PUD UTPT, where U is upper triangular.
UPLO='L'
A=PLD LTPT, where L is lower triangular.
Constraint: UPLO='U' or 'L'.
2:   N – INTEGERInput
On entry: n, the order of the matrix A.
Constraint: N≥0.
3:   AP* – COMPLEX (KIND=nag_wp) arrayInput/Output
Note: the dimension of the array AP must be at least max 1,N×N+1/2.
On entry: the factorization of A stored in packed form, as returned by F07QRF (ZSPTRF).
On exit: the factorization is overwritten by the n by n matrix A-1.
More precisely,
  • if UPLO='U', the upper triangle of A-1 must be stored with element A ij in AP i+j j-1/2 for i≤j;
  • if UPLO='L', the lower triangle of A-1 must be stored with element A ij in AP i+2 n-jj-1/2 for i≥j.
4:   IPIV* – INTEGER arrayInput
Note: the dimension of the array IPIV must be at least max 1,N.
On entry: details of the interchanges and the block structure of D, as returned by F07QRF (ZSPTRF).
5:   WORK N – COMPLEX (KIND=nag_wp) arrayWorkspace
6:   INFO – INTEGEROutput
On exit: INFO=0 unless the routine detects an error (see Section 6).

6 Error Indicators and Warnings

INFO<0
If INFO=-i, argument i had an illegal value. An explanatory message is output, and execution of the program is terminated.
INFO>0
Element value of the diagonal is exactly zero. D is singular and the inverse of A cannot be computed.

7 Accuracy

The computed inverse X satisfies a bound of the form
  • if UPLO='U', D UTPT XPU-I≤c n ε DUT PT X P U+DD-1;
  • if UPLO='L', D LTPT XPL-I≤c n ε DLT PT X P L+DD-1,
c n is a modest linear function of n, and ε is the machine precision.

8 Parallelism and Performance

F07QWF (ZSPTRI) makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The total number of real floating-point operations is approximately 83 n 3.
The real analogue of this routine is F07PJF (DSPTRI).

10 Example

This example computes the inverse of the matrix A, where
A= -0.39-0.71 i 5.14-0.64 i -7.86-2.96 i 3.80+0.92 i 5.14-0.64 i 8.86+1.81 i -3.52+0.58 i 5.32-1.59 i -7.86-2.96 i -3.52+0.58 i -2.83-0.03 i -1.54-2.86 i 3.80+0.92 i 5.32-1.59 i -1.54-2.86 i -0.56+0.12 i .
Here A is symmetric, stored in packed form, and must first be factorized by F07QRF (ZSPTRF).

10.1 Program Text

Program Text (f07qwfe.f90)

10.2 Program Data

Program Data (f07qwfe.d)

10.3 Program Results

Program Results (f07qwfe.r)

F07 Chapter Contents
F07 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F07TEF (DTRTRS) : NAG Library, Mark 26

F07 Chapter Contents
F07 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F07TEF (DTRTRS)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F07TEF (DTRTRS) solves a real triangular system of linear equations with multiple right-hand sides, AX=B or AT X=B.

2 Specification

SUBROUTINE F07TEF ( UPLO, TRANS, DIAG, N, NRHS, A, LDA, B, LDB, INFO)
INTEGER | N, NRHS, LDA, LDB, INFO
REAL (KIND=nag_wp) | A(LDA,*), B(LDB,*)
CHARACTER(1) | UPLO, TRANS, DIAG
The routine may be called by its LAPACK name dtrtrs.

3 Description

F07TEF (DTRTRS) solves a real triangular system of linear equations AX=B or AT X=B.

4 References

Golub G H and Van Loan C F (1996) Matrix Computations (3rd Edition) Johns Hopkins University Press, Baltimore
Higham N J (1989) The accuracy of solutions to triangular systems SIAM J. Numer. Anal. 26 1252–1265

5 Arguments

1:   UPLO – CHARACTER(1)Input
On entry: specifies whether A is upper or lower triangular.
UPLO='U'
A is upper triangular.
UPLO='L'
A is lower triangular.
Constraint: UPLO='U' or 'L'.
2:   TRANS – CHARACTER(1)Input
On entry: indicates the form of the equations.
TRANS='N'
The equations are of the form AX=B.
TRANS='T' or 'C'
The equations are of the form AT X=B.
Constraint: TRANS='N', 'T' or 'C'.
3:   DIAG – CHARACTER(1)Input
On entry: indicates whether A is a nonunit or unit triangular matrix.
DIAG='N'
A is a nonunit triangular matrix.
DIAG='U'
A is a unit triangular matrix; the diagonal elements are not referenced and are assumed to be 1.
Constraint: DIAG='N' or 'U'.
4:   N – INTEGERInput
On entry: n, the order of the matrix A.
Constraint: N≥0.
5:   NRHS – INTEGERInput
On entry: r, the number of right-hand sides.
Constraint: NRHS≥0.
6:   A LDA* – REAL (KIND=nag_wp) arrayInput
Note: the second dimension of the array A must be at least max 1,N.
On entry: the n by n triangular matrix A.
  • If UPLO='U', A is upper triangular and the elements of the array below the diagonal are not referenced.
  • If UPLO='L', A is lower triangular and the elements of the array above the diagonal are not referenced.
  • If DIAG='U', the diagonal elements of A are assumed to be 1, and are not referenced.
7:   LDA – INTEGERInput
On entry: the first dimension of the array A as declared in the (sub)program from which F07TEF (DTRTRS) is called.
Constraint: LDA≥max 1,N.
8:   B LDB* – REAL (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array B must be at least max 1,NRHS.
On entry: the n by r right-hand side matrix B.
On exit: the n by r solution matrix X.
9:   LDB – INTEGERInput
On entry: the first dimension of the array B as declared in the (sub)program from which F07TEF (DTRTRS) is called.
Constraint: LDB≥max 1,N.
10:   INFO – INTEGEROutput
On exit: INFO=0 unless the routine detects an error (see Section 6).

6 Error Indicators and Warnings

INFO<0
If INFO=-i, argument i had an illegal value. An explanatory message is output, and execution of the program is terminated.
INFO>0
Element value of the diagonal is exactly zero. A is singular and the solution has not been computed.

7 Accuracy

The solutions of triangular systems of equations are usually computed to high accuracy. See Higham (1989).
For each right-hand side vector b, the computed solution x is the exact solution of a perturbed system of equations A+E x=b, where
E≤c n ε A ,
c n is a modest linear function of n, and ε is the machine precision.
If x^ is the true solution, then the computed solution x satisfies a forward error bound of the form
x-x^∞ x∞ ≤c n cond A,x ε ,   provided   c n cond A,x ε<1 ,
where cond A,x=A-1Ax∞/x∞.
Note that cond A,x≤cond A=A-1A∞≤κ∞A; cond A,x can be much smaller than cond A and it is also possible for cond AT to be much larger (or smaller) than cond A.
Forward and backward error bounds can be computed by calling F07THF (DTRRFS), and an estimate for κ∞A can be obtained by calling F07TGF (DTRCON) with NORM='I'.

8 Parallelism and Performance

F07TEF (DTRTRS) makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The total number of floating-point operations is approximately n 2 r.
The complex analogue of this routine is F07TSF (ZTRTRS).

10 Example

This example solves the system of equations AX=B, where
A= 4.30 0.00 0.00 0.00 -3.96 -4.87 0.00 0.00 0.40 0.31 -8.02 0.00 -0.27 0.07 -5.95 0.12   and   B= -12.90 -21.50 16.75 14.93 -17.55 6.33 -11.04 8.09 .

10.1 Program Text

Program Text (f07tefe.f90)

10.2 Program Data

Program Data (f07tefe.d)

10.3 Program Results

Program Results (f07tefe.r)

F07 Chapter Contents
F07 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F07TGF (DTRCON) : NAG Library, Mark 26

F07 Chapter Contents
F07 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F07TGF (DTRCON)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F07TGF (DTRCON) estimates the condition number of a real triangular matrix.

2 Specification

SUBROUTINE F07TGF ( NORM, UPLO, DIAG, N, A, LDA, RCOND, WORK, IWORK, INFO)
INTEGER | N, LDA, IWORK(N), INFO
REAL (KIND=nag_wp) | A(LDA,*), RCOND, WORK(3*N)
CHARACTER(1) | NORM, UPLO, DIAG
The routine may be called by its LAPACK name dtrcon.

3 Description

F07TGF (DTRCON) estimates the condition number of a real triangular matrix A, in either the 1-norm or the ∞-norm:
κ 1 A = A 1 A-1 1   or   κ∞ A = A∞ A-1∞ .
Note that κ∞A=κ 1 AT.
Because the condition number is infinite if A is singular, the routine actually returns an estimate of the reciprocal of the condition number.
The routine computes A 1 or A∞ exactly, and uses Higham's implementation of Hager's method (see Higham (1988)) to estimate A-1 1 or A-1∞.

4 References

Higham N J (1988) FORTRAN codes for estimating the one-norm of a real or complex matrix, with applications to condition estimation ACM Trans. Math. Software 14 381–396

5 Arguments

1:   NORM – CHARACTER(1)Input
On entry: indicates whether κ 1 A or κ∞A is estimated.
NORM='1' or 'O'
κ 1 A is estimated.
NORM='I'
κ∞A is estimated.
Constraint: NORM='1', 'O' or 'I'.
2:   UPLO – CHARACTER(1)Input
On entry: specifies whether A is upper or lower triangular.
UPLO='U'
A is upper triangular.
UPLO='L'
A is lower triangular.
Constraint: UPLO='U' or 'L'.
3:   DIAG – CHARACTER(1)Input
On entry: indicates whether A is a nonunit or unit triangular matrix.
DIAG='N'
A is a nonunit triangular matrix.
DIAG='U'
A is a unit triangular matrix; the diagonal elements are not referenced and are assumed to be 1.
Constraint: DIAG='N' or 'U'.
4:   N – INTEGERInput
On entry: n, the order of the matrix A.
Constraint: N≥0.
5:   A LDA* – REAL (KIND=nag_wp) arrayInput
Note: the second dimension of the array A must be at least max 1,N.
On entry: the n by n triangular matrix A.
  • If UPLO='U', A is upper triangular and the elements of the array below the diagonal are not referenced.
  • If UPLO='L', A is lower triangular and the elements of the array above the diagonal are not referenced.
  • If DIAG='U', the diagonal elements of A are assumed to be 1, and are not referenced.
6:   LDA – INTEGERInput
On entry: the first dimension of the array A as declared in the (sub)program from which F07TGF (DTRCON) is called.
Constraint: LDA≥max 1,N.
7:   RCOND – REAL (KIND=nag_wp)Output
On exit: an estimate of the reciprocal of the condition number of A. RCOND is set to zero if exact singularity is detected or if the estimate underflows. If RCOND is less than machine precision, then A is singular to working precision.
8:   WORK 3×N – REAL (KIND=nag_wp) arrayWorkspace
9:   IWORK N – INTEGER arrayWorkspace
10:   INFO – INTEGEROutput
On exit: INFO=0 unless the routine detects an error (see Section 6).

6 Error Indicators and Warnings

INFO<0
If INFO=-i, argument i had an illegal value. An explanatory message is output, and execution of the program is terminated.

7 Accuracy

The computed estimate RCOND is never less than the true value ρ, and in practice is nearly always less than 10 ρ, although examples can be constructed where RCOND is much larger.

8 Parallelism and Performance

F07TGF (DTRCON) makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

A call to F07TGF (DTRCON) involves solving a number of systems of linear equations of the form Ax=b or AT x=b; the number is usually 4 or 5 and never more than 11. Each solution involves approximately n 2 floating-point operations but takes considerably longer than a call to F07TEF (DTRTRS) with one right-hand side, because extra care is taken to avoid overflow when A is approximately singular.
The complex analogue of this routine is F07TUF (ZTRCON).

10 Example

This example estimates the condition number in the 1-norm of the matrix A, where
A= 4.30 0.00 0.00 0.00 -3.96 -4.87 0.00 0.00 0.40 0.31 -8.02 0.00 -0.27 0.07 -5.95 0.12 .
The true condition number in the 1-norm is 116.41.

10.1 Program Text

Program Text (f07tgfe.f90)

10.2 Program Data

Program Data (f07tgfe.d)

10.3 Program Results

Program Results (f07tgfe.r)

F07 Chapter Contents
F07 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F07THF (DTRRFS) : NAG Library, Mark 26

F07 Chapter Contents
F07 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F07THF (DTRRFS)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F07THF (DTRRFS) returns error bounds for the solution of a real triangular system of linear equations with multiple right-hand sides, AX=B or AT X=B.

2 Specification

SUBROUTINE F07THF ( UPLO, TRANS, DIAG, N, NRHS, A, LDA, B, LDB, X, LDX, FERR, BERR, WORK, IWORK, INFO)
INTEGER | N, NRHS, LDA, LDB, LDX, IWORK(N), INFO
REAL (KIND=nag_wp) | A(LDA,*), B(LDB,*), X(LDX,*), FERR(NRHS), BERR(NRHS), WORK(3*N)
CHARACTER(1) | UPLO, TRANS, DIAG
The routine may be called by its LAPACK name dtrrfs.

3 Description

F07THF (DTRRFS) returns the backward errors and estimated bounds on the forward errors for the solution of a real triangular system of linear equations with multiple right-hand sides AX=B or AT X=B. The routine handles each right-hand side vector (stored as a column of the matrix B) independently, so we describe the function of F07THF (DTRRFS) in terms of a single right-hand side b and solution x.
Given a computed solution x, the routine computes the component-wise backward error β. This is the size of the smallest relative perturbation in each element of A and b such that x is the exact solution of a perturbed system
A+δA x=b+δb δ a ij≤β a ij   and   δ bi≤β bi .
Then the routine estimates a bound for the component-wise forward error in the computed solution, defined by:
maxi xi-x^i/maxi xi
where x^ is the true solution.
For details of the method, see the F07 Chapter Introduction.

4 References

Golub G H and Van Loan C F (1996) Matrix Computations (3rd Edition) Johns Hopkins University Press, Baltimore

5 Arguments

1:   UPLO – CHARACTER(1)Input
On entry: specifies whether A is upper or lower triangular.
UPLO='U'
A is upper triangular.
UPLO='L'
A is lower triangular.
Constraint: UPLO='U' or 'L'.
2:   TRANS – CHARACTER(1)Input
On entry: indicates the form of the equations.
TRANS='N'
The equations are of the form AX=B.
TRANS='T' or 'C'
The equations are of the form AT X=B.
Constraint: TRANS='N', 'T' or 'C'.
3:   DIAG – CHARACTER(1)Input
On entry: indicates whether A is a nonunit or unit triangular matrix.
DIAG='N'
A is a nonunit triangular matrix.
DIAG='U'
A is a unit triangular matrix; the diagonal elements are not referenced and are assumed to be 1.
Constraint: DIAG='N' or 'U'.
4:   N – INTEGERInput
On entry: n, the order of the matrix A.
Constraint: N≥0.
5:   NRHS – INTEGERInput
On entry: r, the number of right-hand sides.
Constraint: NRHS≥0.
6:   A LDA* – REAL (KIND=nag_wp) arrayInput
Note: the second dimension of the array A must be at least max 1,N.
On entry: the n by n triangular matrix A.
  • If UPLO='U', A is upper triangular and the elements of the array below the diagonal are not referenced.
  • If UPLO='L', A is lower triangular and the elements of the array above the diagonal are not referenced.
  • If DIAG='U', the diagonal elements of A are assumed to be 1, and are not referenced.
7:   LDA – INTEGERInput
On entry: the first dimension of the array A as declared in the (sub)program from which F07THF (DTRRFS) is called.
Constraint: LDA≥max 1,N.
8:   B LDB* – REAL (KIND=nag_wp) arrayInput
Note: the second dimension of the array B must be at least max 1,NRHS.
On entry: the n by r right-hand side matrix B.
9:   LDB – INTEGERInput
On entry: the first dimension of the array B as declared in the (sub)program from which F07THF (DTRRFS) is called.
Constraint: LDB≥max 1,N.
10:   X LDX* – REAL (KIND=nag_wp) arrayInput
Note: the second dimension of the array X must be at least max 1,NRHS.
On entry: the n by r solution matrix X, as returned by F07TEF (DTRTRS).
11:   LDX – INTEGERInput
On entry: the first dimension of the array X as declared in the (sub)program from which F07THF (DTRRFS) is called.
Constraint: LDX≥max 1,N.
12:   FERR NRHS – REAL (KIND=nag_wp) arrayOutput
On exit: FERR j contains an estimated error bound for the jth solution vector, that is, the jth column of X, for j=1,2,…,r.
13:   BERR NRHS – REAL (KIND=nag_wp) arrayOutput
On exit: BERR j contains the component-wise backward error bound β for the jth solution vector, that is, the jth column of X, for j=1,2,…,r.
14:   WORK 3×N – REAL (KIND=nag_wp) arrayWorkspace
15:   IWORK N – INTEGER arrayWorkspace
16:   INFO – INTEGEROutput
On exit: INFO=0 unless the routine detects an error (see Section 6).

6 Error Indicators and Warnings

INFO<0
If INFO=-i, argument i had an illegal value. An explanatory message is output, and execution of the program is terminated.

7 Accuracy

The bounds returned in FERR are not rigorous, because they are estimated, not computed exactly; but in practice they almost always overestimate the actual error.

8 Parallelism and Performance

F07THF (DTRRFS) is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
F07THF (DTRRFS) makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

A call to F07THF (DTRRFS), for each right-hand side, involves solving a number of systems of linear equations of the form Ax=b or AT x=b; the number is usually 4 or 5 and never more than 11. Each solution involves approximately n 2 floating-point operations.
The complex analogue of this routine is F07TVF (ZTRRFS).

10 Example

This example solves the system of equations AX=B and to compute forward and backward error bounds, where
A= 4.30 0.00 0.00 0.00 -3.96 -4.87 0.00 0.00 0.40 0.31 -8.02 0.00 -0.27 0.07 -5.95 0.12   and   B= -12.90 -21.50 16.75 14.93 -17.55 6.33 -11.04 8.09 .

10.1 Program Text

Program Text (f07thfe.f90)

10.2 Program Data

Program Data (f07thfe.d)

10.3 Program Results

Program Results (f07thfe.r)

F07 Chapter Contents
F07 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F07TJF (DTRTRI) : NAG Library, Mark 26

F07 Chapter Contents
F07 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F07TJF (DTRTRI)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F07TJF (DTRTRI) computes the inverse of a real triangular matrix.

2 Specification

SUBROUTINE F07TJF ( UPLO, DIAG, N, A, LDA, INFO)
INTEGER | N, LDA, INFO
REAL (KIND=nag_wp) | A(LDA,*)
CHARACTER(1) | UPLO, DIAG
The routine may be called by its LAPACK name dtrtri.

3 Description

F07TJF (DTRTRI) forms the inverse of a real triangular matrix A. Note that the inverse of an upper (lower) triangular matrix is also upper (lower) triangular.

4 References

Du Croz J J and Higham N J (1992) Stability of methods for matrix inversion IMA J. Numer. Anal. 12 1–19

5 Arguments

1:   UPLO – CHARACTER(1)Input
On entry: specifies whether A is upper or lower triangular.
UPLO='U'
A is upper triangular.
UPLO='L'
A is lower triangular.
Constraint: UPLO='U' or 'L'.
2:   DIAG – CHARACTER(1)Input
On entry: indicates whether A is a nonunit or unit triangular matrix.
DIAG='N'
A is a nonunit triangular matrix.
DIAG='U'
A is a unit triangular matrix; the diagonal elements are not referenced and are assumed to be 1.
Constraint: DIAG='N' or 'U'.
3:   N – INTEGERInput
On entry: n, the order of the matrix A.
Constraint: N≥0.
4:   A LDA* – REAL (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array A must be at least max 1,N.
On entry: the n by n triangular matrix A.
  • If UPLO='U', A is upper triangular and the elements of the array below the diagonal are not referenced.
  • If UPLO='L', A is lower triangular and the elements of the array above the diagonal are not referenced.
  • If DIAG='U', the diagonal elements of A are assumed to be 1, and are not referenced.
On exit: A is overwritten by A-1, using the same storage format as described above.
5:   LDA – INTEGERInput
On entry: the first dimension of the array A as declared in the (sub)program from which F07TJF (DTRTRI) is called.
Constraint: LDA≥max 1,N.
6:   INFO – INTEGEROutput
On exit: INFO=0 unless the routine detects an error (see Section 6).

6 Error Indicators and Warnings

INFO<0
If INFO=-i, argument i had an illegal value. An explanatory message is output, and execution of the program is terminated.
INFO>0
Element value of the diagonal is exactly zero. A is singular its inverse cannot be computed.

7 Accuracy

The computed inverse X satisfies
XA-I≤c n ε XA ,
where c n is a modest linear function of n, and ε is the machine precision.
Note that a similar bound for AX-I cannot be guaranteed, although it is almost always satisfied.
The computed inverse satisfies the forward error bound
X-A-1≤c n ε A-1AX .
See Du Croz and Higham (1992).

8 Parallelism and Performance

F07TJF (DTRTRI) makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The total number of floating-point operations is approximately 13 n 3.
The complex analogue of this routine is F07TWF (ZTRTRI).

10 Example

This example computes the inverse of the matrix A, where
A= 4.30 0.00 0.00 0.00 -3.96 -4.87 0.00 0.00 0.40 0.31 -8.02 0.00 -0.27 0.07 -5.95 0.12 .

10.1 Program Text

Program Text (f07tjfe.f90)

10.2 Program Data

Program Data (f07tjfe.d)

10.3 Program Results

Program Results (f07tjfe.r)

F07 Chapter Contents
F07 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F07TSF (ZTRTRS) : NAG Library, Mark 26

F07 Chapter Contents
F07 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F07TSF (ZTRTRS)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F07TSF (ZTRTRS) solves a complex triangular system of linear equations with multiple right-hand sides, AX=B, AT X=B or AH X=B.

2 Specification

SUBROUTINE F07TSF ( UPLO, TRANS, DIAG, N, NRHS, A, LDA, B, LDB, INFO)
INTEGER | N, NRHS, LDA, LDB, INFO
COMPLEX (KIND=nag_wp) | A(LDA,*), B(LDB,*)
CHARACTER(1) | UPLO, TRANS, DIAG
The routine may be called by its LAPACK name ztrtrs.

3 Description

F07TSF (ZTRTRS) solves a complex triangular system of linear equations AX=B, AT X=B or AH X=B.

4 References

Golub G H and Van Loan C F (1996) Matrix Computations (3rd Edition) Johns Hopkins University Press, Baltimore
Higham N J (1989) The accuracy of solutions to triangular systems SIAM J. Numer. Anal. 26 1252–1265

5 Arguments

1:   UPLO – CHARACTER(1)Input
On entry: specifies whether A is upper or lower triangular.
UPLO='U'
A is upper triangular.
UPLO='L'
A is lower triangular.
Constraint: UPLO='U' or 'L'.
2:   TRANS – CHARACTER(1)Input
On entry: indicates the form of the equations.
TRANS='N'
The equations are of the form AX=B.
TRANS='T'
The equations are of the form AT X=B.
TRANS='C'
The equations are of the form AH X=B.
Constraint: TRANS='N', 'T' or 'C'.
3:   DIAG – CHARACTER(1)Input
On entry: indicates whether A is a nonunit or unit triangular matrix.
DIAG='N'
A is a nonunit triangular matrix.
DIAG='U'
A is a unit triangular matrix; the diagonal elements are not referenced and are assumed to be 1.
Constraint: DIAG='N' or 'U'.
4:   N – INTEGERInput
On entry: n, the order of the matrix A.
Constraint: N≥0.
5:   NRHS – INTEGERInput
On entry: r, the number of right-hand sides.
Constraint: NRHS≥0.
6:   A LDA* – COMPLEX (KIND=nag_wp) arrayInput
Note: the second dimension of the array A must be at least max 1,N.
On entry: the n by n triangular matrix A.
  • If UPLO='U', A is upper triangular and the elements of the array below the diagonal are not referenced.
  • If UPLO='L', A is lower triangular and the elements of the array above the diagonal are not referenced.
  • If DIAG='U', the diagonal elements of A are assumed to be 1, and are not referenced.
7:   LDA – INTEGERInput
On entry: the first dimension of the array A as declared in the (sub)program from which F07TSF (ZTRTRS) is called.
Constraint: LDA≥max 1,N.
8:   B LDB* – COMPLEX (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array B must be at least max 1,NRHS.
On entry: the n by r right-hand side matrix B.
On exit: the n by r solution matrix X.
9:   LDB – INTEGERInput
On entry: the first dimension of the array B as declared in the (sub)program from which F07TSF (ZTRTRS) is called.
Constraint: LDB≥max 1,N.
10:   INFO – INTEGEROutput
On exit: INFO=0 unless the routine detects an error (see Section 6).

6 Error Indicators and Warnings

INFO<0
If INFO=-i, argument i had an illegal value. An explanatory message is output, and execution of the program is terminated.
INFO>0
Element value of the diagonal is exactly zero. A is singular and the solution has not been computed.

7 Accuracy

The solutions of triangular systems of equations are usually computed to high accuracy. See Higham (1989).
For each right-hand side vector b, the computed solution x is the exact solution of a perturbed system of equations A+E x=b, where
E≤c n ε A ,
c n is a modest linear function of n, and ε is the machine precision.
If x^ is the true solution, then the computed solution x satisfies a forward error bound of the form
x-x^∞ x∞ ≤c n cond A,x ε ,   provided   c n cond A,x ε<1 ,
where cond A,x=A-1Ax∞/x∞.
Note that cond A,x≤cond A=A-1A∞≤κ∞A; cond A,x can be much smaller than cond A and it is also possible for cond AH, which is the same as cond AT, to be much larger (or smaller) than cond A.
Forward and backward error bounds can be computed by calling F07TVF (ZTRRFS), and an estimate for κ∞A can be obtained by calling F07TUF (ZTRCON) with NORM='I'.

8 Parallelism and Performance

F07TSF (ZTRTRS) makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The total number of real floating-point operations is approximately 4 n 2 r.
The real analogue of this routine is F07TEF (DTRTRS).

10 Example

This example solves the system of equations AX=B, where
A= 4.78+4.56 i 0.00+0.00 i 0.00+0.00 i 0.00+0.00 i 2.00-0.30 i -4.11+1.25 i 0.00+0.00 i 0.00+0.00 i 2.89-1.34 i 2.36-4.25 i 4.15+0.80 i 0.00+0.00 i -1.89+1.15 i 0.04-3.69 i -0.02+0.46 i 0.33-0.26 i
and
B= -14.78-32.36 i -18.02+28.46 i 2.98-0 2.14 i 14.22+15.42 i -20.96+17.06 i 5.62+35.89 i 9.54+0 9.91 i -16.46-0 1.73 i .

10.1 Program Text

Program Text (f07tsfe.f90)

10.2 Program Data

Program Data (f07tsfe.d)

10.3 Program Results

Program Results (f07tsfe.r)

F07 Chapter Contents
F07 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F07TUF (ZTRCON) : NAG Library, Mark 26

F07 Chapter Contents
F07 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F07TUF (ZTRCON)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F07TUF (ZTRCON) estimates the condition number of a complex triangular matrix.

2 Specification

SUBROUTINE F07TUF ( NORM, UPLO, DIAG, N, A, LDA, RCOND, WORK, RWORK, INFO)
INTEGER | N, LDA, INFO
REAL (KIND=nag_wp) | RCOND, RWORK(N)
COMPLEX (KIND=nag_wp) | A(LDA,*), WORK(2*N)
CHARACTER(1) | NORM, UPLO, DIAG
The routine may be called by its LAPACK name ztrcon.

3 Description

F07TUF (ZTRCON) estimates the condition number of a complex triangular matrix A, in either the 1-norm or the ∞-norm:
κ 1 A = A 1 A-1 1   or   κ∞ A = A∞ A-1∞ .
Note that κ∞A=κ 1 AT.
Because the condition number is infinite if A is singular, the routine actually returns an estimate of the reciprocal of the condition number.
The routine computes A 1 or A∞ exactly, and uses Higham's implementation of Hager's method (see Higham (1988)) to estimate A-1 1 or A-1∞.

4 References

Higham N J (1988) FORTRAN codes for estimating the one-norm of a real or complex matrix, with applications to condition estimation ACM Trans. Math. Software 14 381–396

5 Arguments

1:   NORM – CHARACTER(1)Input
On entry: indicates whether κ 1 A or κ∞A is estimated.
NORM='1' or 'O'
κ 1 A is estimated.
NORM='I'
κ∞A is estimated.
Constraint: NORM='1', 'O' or 'I'.
2:   UPLO – CHARACTER(1)Input
On entry: specifies whether A is upper or lower triangular.
UPLO='U'
A is upper triangular.
UPLO='L'
A is lower triangular.
Constraint: UPLO='U' or 'L'.
3:   DIAG – CHARACTER(1)Input
On entry: indicates whether A is a nonunit or unit triangular matrix.
DIAG='N'
A is a nonunit triangular matrix.
DIAG='U'
A is a unit triangular matrix; the diagonal elements are not referenced and are assumed to be 1.
Constraint: DIAG='N' or 'U'.
4:   N – INTEGERInput
On entry: n, the order of the matrix A.
Constraint: N≥0.
5:   A LDA* – COMPLEX (KIND=nag_wp) arrayInput
Note: the second dimension of the array A must be at least max 1,N.
On entry: the n by n triangular matrix A.
  • If UPLO='U', A is upper triangular and the elements of the array below the diagonal are not referenced.
  • If UPLO='L', A is lower triangular and the elements of the array above the diagonal are not referenced.
  • If DIAG='U', the diagonal elements of A are assumed to be 1, and are not referenced.
6:   LDA – INTEGERInput
On entry: the first dimension of the array A as declared in the (sub)program from which F07TUF (ZTRCON) is called.
Constraint: LDA≥max 1,N.
7:   RCOND – REAL (KIND=nag_wp)Output
On exit: an estimate of the reciprocal of the condition number of A. RCOND is set to zero if exact singularity is detected or the estimate underflows. If RCOND is less than machine precision, A is singular to working precision.
8:   WORK 2×N – COMPLEX (KIND=nag_wp) arrayWorkspace
9:   RWORK N – REAL (KIND=nag_wp) arrayWorkspace
10:   INFO – INTEGEROutput
On exit: INFO=0 unless the routine detects an error (see Section 6).

6 Error Indicators and Warnings

INFO<0
If INFO=-i, argument i had an illegal value. An explanatory message is output, and execution of the program is terminated.

7 Accuracy

The computed estimate RCOND is never less than the true value ρ, and in practice is nearly always less than 10 ρ, although examples can be constructed where RCOND is much larger.

8 Parallelism and Performance

F07TUF (ZTRCON) makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

A call to F07TUF (ZTRCON) involves solving a number of systems of linear equations of the form Ax=b or AH x=b; the number is usually 5 and never more than 11. Each solution involves approximately 4 n 2 real floating-point operations but takes considerably longer than a call to F07TSF (ZTRTRS) with one right-hand side, because extra care is taken to avoid overflow when A is approximately singular.
The real analogue of this routine is F07TGF (DTRCON).

10 Example

This example estimates the condition number in the 1-norm of the matrix A, where
A= 4.78+4.56 i 0.00+0.00 i 0.00+0.00 i 0.00+0.00 i 2.00-0.30 i -4.11+1.25 i 0.00+0.00 i 0.00+0.00 i 2.89-1.34 i 2.36-4.25 i 4.15+0.80 i 0.00+0.00 i -1.89+1.15 i 0.04-3.69 i -0.02+0.46 i 0.33-0.26 i .
The true condition number in the 1-norm is 70.27.

10.1 Program Text

Program Text (f07tufe.f90)

10.2 Program Data

Program Data (f07tufe.d)

10.3 Program Results

Program Results (f07tufe.r)

F07 Chapter Contents
F07 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F07TVF (ZTRRFS) : NAG Library, Mark 26

F07 Chapter Contents
F07 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F07TVF (ZTRRFS)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F07TVF (ZTRRFS) returns error bounds for the solution of a complex triangular system of linear equations with multiple right-hand sides, AX=B, AT X=B or AH X=B.

2 Specification

SUBROUTINE F07TVF ( UPLO, TRANS, DIAG, N, NRHS, A, LDA, B, LDB, X, LDX, FERR, BERR, WORK, RWORK, INFO)
INTEGER | N, NRHS, LDA, LDB, LDX, INFO
REAL (KIND=nag_wp) | FERR(NRHS), BERR(NRHS), RWORK(N)
COMPLEX (KIND=nag_wp) | A(LDA,*), B(LDB,*), X(LDX,*), WORK(2*N)
CHARACTER(1) | UPLO, TRANS, DIAG
The routine may be called by its LAPACK name ztrrfs.

3 Description

F07TVF (ZTRRFS) returns the backward errors and estimated bounds on the forward errors for the solution of a complex triangular system of linear equations with multiple right-hand sides AX=B, AT X=B or AH X=B. The routine handles each right-hand side vector (stored as a column of the matrix B) independently, so we describe the function of F07TVF (ZTRRFS) in terms of a single right-hand side b and solution x.
Given a computed solution x, the routine computes the component-wise backward error β. This is the size of the smallest relative perturbation in each element of A and b such that x is the exact solution of a perturbed system
A+δA x=b+δb δ a ij≤β a ij   and   δ bi≤β bi .
Then the routine estimates a bound for the component-wise forward error in the computed solution, defined by:
maxi xi-x^i/maxi xi
where x^ is the true solution.
For details of the method, see the F07 Chapter Introduction.

4 References

Golub G H and Van Loan C F (1996) Matrix Computations (3rd Edition) Johns Hopkins University Press, Baltimore

5 Arguments

1:   UPLO – CHARACTER(1)Input
On entry: specifies whether A is upper or lower triangular.
UPLO='U'
A is upper triangular.
UPLO='L'
A is lower triangular.
Constraint: UPLO='U' or 'L'.
2:   TRANS – CHARACTER(1)Input
On entry: indicates the form of the equations.
TRANS='N'
The equations are of the form AX=B.
TRANS='T'
The equations are of the form AT X=B.
TRANS='C'
The equations are of the form AH X=B.
Constraint: TRANS='N', 'T' or 'C'.
3:   DIAG – CHARACTER(1)Input
On entry: indicates whether A is a nonunit or unit triangular matrix.
DIAG='N'
A is a nonunit triangular matrix.
DIAG='U'
A is a unit triangular matrix; the diagonal elements are not referenced and are assumed to be 1.
Constraint: DIAG='N' or 'U'.
4:   N – INTEGERInput
On entry: n, the order of the matrix A.
Constraint: N≥0.
5:   NRHS – INTEGERInput
On entry: r, the number of right-hand sides.
Constraint: NRHS≥0.
6:   A LDA* – COMPLEX (KIND=nag_wp) arrayInput
Note: the second dimension of the array A must be at least max 1,N.
On entry: the n by n triangular matrix A.
  • If UPLO='U', A is upper triangular and the elements of the array below the diagonal are not referenced.
  • If UPLO='L', A is lower triangular and the elements of the array above the diagonal are not referenced.
  • If DIAG='U', the diagonal elements of A are assumed to be 1, and are not referenced.
7:   LDA – INTEGERInput
On entry: the first dimension of the array A as declared in the (sub)program from which F07TVF (ZTRRFS) is called.
Constraint: LDA≥max 1,N.
8:   B LDB* – COMPLEX (KIND=nag_wp) arrayInput
Note: the second dimension of the array B must be at least max 1,NRHS.
On entry: the n by r right-hand side matrix B.
9:   LDB – INTEGERInput
On entry: the first dimension of the array B as declared in the (sub)program from which F07TVF (ZTRRFS) is called.
Constraint: LDB≥max 1,N.
10:   X LDX* – COMPLEX (KIND=nag_wp) arrayInput
Note: the second dimension of the array X must be at least max 1,NRHS.
On entry: the n by r solution matrix X, as returned by F07TSF (ZTRTRS).
11:   LDX – INTEGERInput
On entry: the first dimension of the array X as declared in the (sub)program from which F07TVF (ZTRRFS) is called.
Constraint: LDX≥max 1,N.
12:   FERR NRHS – REAL (KIND=nag_wp) arrayOutput
On exit: FERR j contains an estimated error bound for the jth solution vector, that is, the jth column of X, for j=1,2,…,r.
13:   BERR NRHS – REAL (KIND=nag_wp) arrayOutput
On exit: BERR j contains the component-wise backward error bound β for the jth solution vector, that is, the jth column of X, for j=1,2,…,r.
14:   WORK 2×N – COMPLEX (KIND=nag_wp) arrayWorkspace
15:   RWORK N – REAL (KIND=nag_wp) arrayWorkspace
16:   INFO – INTEGEROutput
On exit: INFO=0 unless the routine detects an error (see Section 6).

6 Error Indicators and Warnings

INFO<0
If INFO=-i, argument i had an illegal value. An explanatory message is output, and execution of the program is terminated.

7 Accuracy

The bounds returned in FERR are not rigorous, because they are estimated, not computed exactly; but in practice they almost always overestimate the actual error.

8 Parallelism and Performance

F07TVF (ZTRRFS) is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
F07TVF (ZTRRFS) makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

A call to F07TVF (ZTRRFS), for each right-hand side, involves solving a number of systems of linear equations of the form Ax=b or AH x=b; the number is usually 5 and never more than 11. Each solution involves approximately 4 n 2 real floating-point operations.
The real analogue of this routine is F07THF (DTRRFS).

10 Example

This example solves the system of equations AX=B and to compute forward and backward error bounds, where
A= 4.78+4.56 i 0.00+0.00 i 0.00+0.00 i 0.00+0.00 i 2.00-0.30 i -4.11+1.25 i 0.00+0.00 i 0.00+0.00 i 2.89-1.34 i 2.36-4.25 i 4.15+0.80 i 0.00+0.00 i -1.89+1.15 i 0.04-3.69 i -0.02+0.46 i 0.33-0.26 i
and
B= -14.78-32.36 i -18.02+28.46 i 2.98-0 2.14 i 14.22+15.42 i -20.96+17.06 i 5.62+35.89 i 9.54+0 9.91 i -16.46-0 1.73 i .

10.1 Program Text

Program Text (f07tvfe.f90)

10.2 Program Data

Program Data (f07tvfe.d)

10.3 Program Results

Program Results (f07tvfe.r)

F07 Chapter Contents
F07 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F07TWF (ZTRTRI) : NAG Library, Mark 26

F07 Chapter Contents
F07 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F07TWF (ZTRTRI)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F07TWF (ZTRTRI) computes the inverse of a complex triangular matrix.

2 Specification

SUBROUTINE F07TWF ( UPLO, DIAG, N, A, LDA, INFO)
INTEGER | N, LDA, INFO
COMPLEX (KIND=nag_wp) | A(LDA,*)
CHARACTER(1) | UPLO, DIAG
The routine may be called by its LAPACK name ztrtri.

3 Description

F07TWF (ZTRTRI) forms the inverse of a complex triangular matrix A. Note that the inverse of an upper (lower) triangular matrix is also upper (lower) triangular.

4 References

Du Croz J J and Higham N J (1992) Stability of methods for matrix inversion IMA J. Numer. Anal. 12 1–19

5 Arguments

1:   UPLO – CHARACTER(1)Input
On entry: specifies whether A is upper or lower triangular.
UPLO='U'
A is upper triangular.
UPLO='L'
A is lower triangular.
Constraint: UPLO='U' or 'L'.
2:   DIAG – CHARACTER(1)Input
On entry: indicates whether A is a nonunit or unit triangular matrix.
DIAG='N'
A is a nonunit triangular matrix.
DIAG='U'
A is a unit triangular matrix; the diagonal elements are not referenced and are assumed to be 1.
Constraint: DIAG='N' or 'U'.
3:   N – INTEGERInput
On entry: n, the order of the matrix A.
Constraint: N≥0.
4:   A LDA* – COMPLEX (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array A must be at least max 1,N.
On entry: the n by n triangular matrix A.
  • If UPLO='U', A is upper triangular and the elements of the array below the diagonal are not referenced.
  • If UPLO='L', A is lower triangular and the elements of the array above the diagonal are not referenced.
  • If DIAG='U', the diagonal elements of A are assumed to be 1, and are not referenced.
On exit: A is overwritten by A-1, using the same storage format as described above.
5:   LDA – INTEGERInput
On entry: the first dimension of the array A as declared in the (sub)program from which F07TWF (ZTRTRI) is called.
Constraint: LDA≥max 1,N.
6:   INFO – INTEGEROutput
On exit: INFO=0 unless the routine detects an error (see Section 6).

6 Error Indicators and Warnings

INFO<0
If INFO=-i, argument i had an illegal value. An explanatory message is output, and execution of the program is terminated.
INFO>0
Element value of the diagonal is exactly zero. A is singular its inverse cannot be computed.

7 Accuracy

The computed inverse X satisfies
XA-I≤c n ε XA ,
where c n is a modest linear function of n, and ε is the machine precision.
Note that a similar bound for AX-I cannot be guaranteed, although it is almost always satisfied.
The computed inverse satisfies the forward error bound
X-A-1≤c n ε A-1AX .
See Du Croz and Higham (1992).

8 Parallelism and Performance

F07TWF (ZTRTRI) makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The total number of real floating-point operations is approximately 43 n 3.
The real analogue of this routine is F07TJF (DTRTRI).

10 Example

This example computes the inverse of the matrix A, where
A= 4.78+4.56 i 0.00+0.00 i 0.00+0.00 i 0.00+0.00 i 2.00-0.30 i -4.11+1.25 i 0.00+0.00 i 0.00+0.00 i 2.89-1.34 i 2.36-4.25 i 4.15+0.80 i 0.00+0.00 i -1.89+1.15 i 0.04-3.69 i -0.02+0.46 i 0.33-0.26 i .

10.1 Program Text

Program Text (f07twfe.f90)

10.2 Program Data

Program Data (f07twfe.d)

10.3 Program Results

Program Results (f07twfe.r)

F07 Chapter Contents
F07 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F07UEF (DTPTRS) : NAG Library, Mark 26

F07 Chapter Contents
F07 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F07UEF (DTPTRS)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F07UEF (DTPTRS) solves a real triangular system of linear equations with multiple right-hand sides, AX=B or AT X=B, using packed storage.

2 Specification

SUBROUTINE F07UEF ( UPLO, TRANS, DIAG, N, NRHS, AP, B, LDB, INFO)
INTEGER | N, NRHS, LDB, INFO
REAL (KIND=nag_wp) | AP(*), B(LDB,*)
CHARACTER(1) | UPLO, TRANS, DIAG
The routine may be called by its LAPACK name dtptrs.

3 Description

F07UEF (DTPTRS) solves a real triangular system of linear equations AX=B or AT X=B, using packed storage.

4 References

Golub G H and Van Loan C F (1996) Matrix Computations (3rd Edition) Johns Hopkins University Press, Baltimore
Higham N J (1989) The accuracy of solutions to triangular systems SIAM J. Numer. Anal. 26 1252–1265

5 Arguments

1:   UPLO – CHARACTER(1)Input
On entry: specifies whether A is upper or lower triangular.
UPLO='U'
A is upper triangular.
UPLO='L'
A is lower triangular.
Constraint: UPLO='U' or 'L'.
2:   TRANS – CHARACTER(1)Input
On entry: indicates the form of the equations.
TRANS='N'
The equations are of the form AX=B.
TRANS='T' or 'C'
The equations are of the form AT X=B.
Constraint: TRANS='N', 'T' or 'C'.
3:   DIAG – CHARACTER(1)Input
On entry: indicates whether A is a nonunit or unit triangular matrix.
DIAG='N'
A is a nonunit triangular matrix.
DIAG='U'
A is a unit triangular matrix; the diagonal elements are not referenced and are assumed to be 1.
Constraint: DIAG='N' or 'U'.
4:   N – INTEGERInput
On entry: n, the order of the matrix A.
Constraint: N≥0.
5:   NRHS – INTEGERInput
On entry: r, the number of right-hand sides.
Constraint: NRHS≥0.
6:   AP* – REAL (KIND=nag_wp) arrayInput
Note: the dimension of the array AP must be at least max 1,N×N+1/2.
On entry: the n by n triangular matrix A, packed by columns.
More precisely,
  • if UPLO='U', the upper triangle of A must be stored with element A ij in AP i+j j-1/2 for i≤j;
  • if UPLO='L', the lower triangle of A must be stored with element A ij in AP i+2 n-jj-1/2 for i≥j.
If DIAG='U', the diagonal elements of A are assumed to be 1, and are not referenced; the same storage scheme is used whether DIAG='N' or ‘U’.
7:   B LDB* – REAL (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array B must be at least max 1,NRHS.
On entry: the n by r right-hand side matrix B.
On exit: the n by r solution matrix X.
8:   LDB – INTEGERInput
On entry: the first dimension of the array B as declared in the (sub)program from which F07UEF (DTPTRS) is called.
Constraint: LDB≥max 1,N.
9:   INFO – INTEGEROutput
On exit: INFO=0 unless the routine detects an error (see Section 6).

6 Error Indicators and Warnings

INFO<0
If INFO=-i, argument i had an illegal value. An explanatory message is output, and execution of the program is terminated.
INFO>0
Element value of the diagonal is exactly zero. A is singular and the solution has not been computed.

7 Accuracy

The solutions of triangular systems of equations are usually computed to high accuracy. See Higham (1989).
For each right-hand side vector b, the computed solution x is the exact solution of a perturbed system of equations A+E x=b, where
E≤c n ε A ,
c n is a modest linear function of n, and ε is the machine precision.
If x^ is the true solution, then the computed solution x satisfies a forward error bound of the form
x-x^∞ x∞ ≤ c n cond A,x ε ,   provided   c n cond A,x ε<1 ,
where cond A,x=A-1Ax∞/x∞.
Note that cond A,x≤cond A=A-1A∞≤κ∞A; cond A,x can be much smaller than cond A and it is also possible for cond AT to be much larger (or smaller) than cond A.
Forward and backward error bounds can be computed by calling F07UHF (DTPRFS), and an estimate for κ∞A can be obtained by calling F07UGF (DTPCON) with NORM='I'.

8 Parallelism and Performance

F07UEF (DTPTRS) is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
F07UEF (DTPTRS) makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The total number of floating-point operations is approximately n 2 r.
The complex analogue of this routine is F07USF (ZTPTRS).

10 Example

This example solves the system of equations AX=B, where
A= 4.30 0.00 0.00 0.00 -3.96 -4.87 0.00 0.00 0.40 0.31 -8.02 0.00 -0.27 0.07 -5.95 0.12   and   B= -12.90 -21.50 16.75 14.93 -17.55 6.33 -11.04 8.09 ,
using packed storage for A.

10.1 Program Text

Program Text (f07uefe.f90)

10.2 Program Data

Program Data (f07uefe.d)

10.3 Program Results

Program Results (f07uefe.r)

F07 Chapter Contents
F07 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F07UGF (DTPCON) : NAG Library, Mark 26

F07 Chapter Contents
F07 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F07UGF (DTPCON)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F07UGF (DTPCON) estimates the condition number of a real triangular matrix, using packed storage.

2 Specification

SUBROUTINE F07UGF ( NORM, UPLO, DIAG, N, AP, RCOND, WORK, IWORK, INFO)
INTEGER | N, IWORK(N), INFO
REAL (KIND=nag_wp) | AP(*), RCOND, WORK(3*N)
CHARACTER(1) | NORM, UPLO, DIAG
The routine may be called by its LAPACK name dtpcon.

3 Description

F07UGF (DTPCON) estimates the condition number of a real triangular matrix A, in either the 1-norm or the ∞-norm, using packed storage:
κ 1 A = A 1 A-1 1   or   κ∞ A = A∞ A-1∞ .
Note that κ∞A=κ 1 AT.
Because the condition number is infinite if A is singular, the routine actually returns an estimate of the reciprocal of the condition number.
The routine computes A 1 or A∞ exactly, and uses Higham's implementation of Hager's method (see Higham (1988)) to estimate A-1 1 or A-1∞.

4 References

Higham N J (1988) FORTRAN codes for estimating the one-norm of a real or complex matrix, with applications to condition estimation ACM Trans. Math. Software 14 381–396

5 Arguments

1:   NORM – CHARACTER(1)Input
On entry: indicates whether κ 1 A or κ∞A is estimated.
NORM='1' or 'O'
κ 1 A is estimated.
NORM='I'
κ∞A is estimated.
Constraint: NORM='1', 'O' or 'I'.
2:   UPLO – CHARACTER(1)Input
On entry: specifies whether A is upper or lower triangular.
UPLO='U'
A is upper triangular.
UPLO='L'
A is lower triangular.
Constraint: UPLO='U' or 'L'.
3:   DIAG – CHARACTER(1)Input
On entry: indicates whether A is a nonunit or unit triangular matrix.
DIAG='N'
A is a nonunit triangular matrix.
DIAG='U'
A is a unit triangular matrix; the diagonal elements are not referenced and are assumed to be 1.
Constraint: DIAG='N' or 'U'.
4:   N – INTEGERInput
On entry: n, the order of the matrix A.
Constraint: N≥0.
5:   AP* – REAL (KIND=nag_wp) arrayInput
Note: the dimension of the array AP must be at least max 1,N×N+1/2.
On entry: the n by n triangular matrix A, packed by columns.
More precisely,
  • if UPLO='U', the upper triangle of A must be stored with element A ij in AP i+j j-1/2 for i≤j;
  • if UPLO='L', the lower triangle of A must be stored with element A ij in AP i+2 n-jj-1/2 for i≥j.
If DIAG='U', the diagonal elements of A are assumed to be 1, and are not referenced; the same storage scheme is used whether DIAG='N' or ‘U’.
6:   RCOND – REAL (KIND=nag_wp)Output
On exit: an estimate of the reciprocal of the condition number of A. RCOND is set to zero if exact singularity is detected or the estimate underflows. If RCOND is less than machine precision, A is singular to working precision.
7:   WORK 3×N – REAL (KIND=nag_wp) arrayWorkspace
8:   IWORK N – INTEGER arrayWorkspace
9:   INFO – INTEGEROutput
On exit: INFO=0 unless the routine detects an error (see Section 6).

6 Error Indicators and Warnings

INFO<0
If INFO=-i, argument i had an illegal value. An explanatory message is output, and execution of the program is terminated.

7 Accuracy

The computed estimate RCOND is never less than the true value ρ, and in practice is nearly always less than 10 ρ, although examples can be constructed where RCOND is much larger.

8 Parallelism and Performance

F07UGF (DTPCON) makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

A call to F07UGF (DTPCON) involves solving a number of systems of linear equations of the form Ax=b or AT x=b; the number is usually 4 or 5 and never more than 11. Each solution involves approximately n 2 floating-point operations but takes considerably longer than a call to F07UEF (DTPTRS) with one right-hand side, because extra care is taken to avoid overflow when A is approximately singular.
The complex analogue of this routine is F07UUF (ZTPCON).

10 Example

This example estimates the condition number in the 1-norm of the matrix A, where
A= 4.30 0.00 0.00 0.00 -3.96 -4.87 0.00 0.00 0.40 0.31 -8.02 0.00 -0.27 0.07 -5.95 0.12 ,
using packed storage. The true condition number in the 1-norm is 116.41.

10.1 Program Text

Program Text (f07ugfe.f90)

10.2 Program Data

Program Data (f07ugfe.d)

10.3 Program Results

Program Results (f07ugfe.r)

F07 Chapter Contents
F07 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F07UHF (DTPRFS) : NAG Library, Mark 26

F07 Chapter Contents
F07 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F07UHF (DTPRFS)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F07UHF (DTPRFS) returns error bounds for the solution of a real triangular system of linear equations with multiple right-hand sides, AX=B or AT X=B, using packed storage.

2 Specification

SUBROUTINE F07UHF ( UPLO, TRANS, DIAG, N, NRHS, AP, B, LDB, X, LDX, FERR, BERR, WORK, IWORK, INFO)
INTEGER | N, NRHS, LDB, LDX, IWORK(N), INFO
REAL (KIND=nag_wp) | AP(*), B(LDB,*), X(LDX,*), FERR(NRHS), BERR(NRHS), WORK(3*N)
CHARACTER(1) | UPLO, TRANS, DIAG
The routine may be called by its LAPACK name dtprfs.

3 Description

F07UHF (DTPRFS) returns the backward errors and estimated bounds on the forward errors for the solution of a real triangular system of linear equations with multiple right-hand sides AX=B or AT X=B, using packed storage. The routine handles each right-hand side vector (stored as a column of the matrix B) independently, so we describe the function of F07UHF (DTPRFS) in terms of a single right-hand side b and solution x.
Given a computed solution x, the routine computes the component-wise backward error β. This is the size of the smallest relative perturbation in each element of A and b such that x is the exact solution of a perturbed system
A+δA x=b+δb δ a ij≤β a ij   and   δ bi≤β bi .
Then the routine estimates a bound for the component-wise forward error in the computed solution, defined by:
maxi xi-x^i/maxi xi
where x^ is the true solution.
For details of the method, see the F07 Chapter Introduction.

4 References

Golub G H and Van Loan C F (1996) Matrix Computations (3rd Edition) Johns Hopkins University Press, Baltimore

5 Arguments

1:   UPLO – CHARACTER(1)Input
On entry: specifies whether A is upper or lower triangular.
UPLO='U'
A is upper triangular.
UPLO='L'
A is lower triangular.
Constraint: UPLO='U' or 'L'.
2:   TRANS – CHARACTER(1)Input
On entry: indicates the form of the equations.
TRANS='N'
The equations are of the form AX=B.
TRANS='T' or 'C'
The equations are of the form AT X=B.
Constraint: TRANS='N', 'T' or 'C'.
3:   DIAG – CHARACTER(1)Input
On entry: indicates whether A is a nonunit or unit triangular matrix.
DIAG='N'
A is a nonunit triangular matrix.
DIAG='U'
A is a unit triangular matrix; the diagonal elements are not referenced and are assumed to be 1.
Constraint: DIAG='N' or 'U'.
4:   N – INTEGERInput
On entry: n, the order of the matrix A.
Constraint: N≥0.
5:   NRHS – INTEGERInput
On entry: r, the number of right-hand sides.
Constraint: NRHS≥0.
6:   AP* – REAL (KIND=nag_wp) arrayInput
Note: the dimension of the array AP must be at least max 1,N×N+1/2.
On entry: the n by n triangular matrix A, packed by columns.
More precisely,
  • if UPLO='U', the upper triangle of A must be stored with element A ij in AP i+j j-1/2 for i≤j;
  • if UPLO='L', the lower triangle of A must be stored with element A ij in AP i+2 n-jj-1/2 for i≥j.
If DIAG='U', the diagonal elements of A are assumed to be 1, and are not referenced; the same storage scheme is used whether DIAG='N' or ‘U’.
7:   B LDB* – REAL (KIND=nag_wp) arrayInput
Note: the second dimension of the array B must be at least max 1,NRHS.
On entry: the n by r right-hand side matrix B.
8:   LDB – INTEGERInput
On entry: the first dimension of the array B as declared in the (sub)program from which F07UHF (DTPRFS) is called.
Constraint: LDB≥max 1,N.
9:   X LDX* – REAL (KIND=nag_wp) arrayInput
Note: the second dimension of the array X must be at least max 1,NRHS.
On entry: the n by r solution matrix X, as returned by F07UEF (DTPTRS).
10:   LDX – INTEGERInput
On entry: the first dimension of the array X as declared in the (sub)program from which F07UHF (DTPRFS) is called.
Constraint: LDX≥max 1,N.
11:   FERR NRHS – REAL (KIND=nag_wp) arrayOutput
On exit: FERR j contains an estimated error bound for the jth solution vector, that is, the jth column of X, for j=1,2,…,r.
12:   BERR NRHS – REAL (KIND=nag_wp) arrayOutput
On exit: BERR j contains the component-wise backward error bound β for the jth solution vector, that is, the jth column of X, for j=1,2,…,r.
13:   WORK 3×N – REAL (KIND=nag_wp) arrayWorkspace
14:   IWORK N – INTEGER arrayWorkspace
15:   INFO – INTEGEROutput
On exit: INFO=0 unless the routine detects an error (see Section 6).

6 Error Indicators and Warnings

INFO<0
If INFO=-i, argument i had an illegal value. An explanatory message is output, and execution of the program is terminated.

7 Accuracy

The bounds returned in FERR are not rigorous, because they are estimated, not computed exactly; but in practice they almost always overestimate the actual error.

8 Parallelism and Performance

F07UHF (DTPRFS) is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
F07UHF (DTPRFS) makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

A call to F07UHF (DTPRFS), for each right-hand side, involves solving a number of systems of linear equations of the form Ax=b or AT x=b; the number is usually 4 or 5 and never more than 11. Each solution involves approximately n 2 floating-point operations.
The complex analogue of this routine is F07UVF (ZTPRFS).

10 Example

This example solves the system of equations AX=B and to compute forward and backward error bounds, where
A= 4.30 0.00 0.00 0.00 -3.96 -4.87 0.00 0.00 0.40 0.31 -8.02 0.00 -0.27 0.07 -5.95 0.12   and   B= -12.90 -21.50 16.75 14.93 -17.55 6.33 -11.04 8.09 ,
using packed storage for A.

10.1 Program Text

Program Text (f07uhfe.f90)

10.2 Program Data

Program Data (f07uhfe.d)

10.3 Program Results

Program Results (f07uhfe.r)

F07 Chapter Contents
F07 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F07UJF (DTPTRI) : NAG Library, Mark 26

F07 Chapter Contents
F07 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F07UJF (DTPTRI)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F07UJF (DTPTRI) computes the inverse of a real triangular matrix, using packed storage.

2 Specification

SUBROUTINE F07UJF ( UPLO, DIAG, N, AP, INFO)
INTEGER | N, INFO
REAL (KIND=nag_wp) | AP(*)
CHARACTER(1) | UPLO, DIAG
The routine may be called by its LAPACK name dtptri.

3 Description

F07UJF (DTPTRI) forms the inverse of a real triangular matrix A, using packed storage. Note that the inverse of an upper (lower) triangular matrix is also upper (lower) triangular.

4 References

Du Croz J J and Higham N J (1992) Stability of methods for matrix inversion IMA J. Numer. Anal. 12 1–19

5 Arguments

1:   UPLO – CHARACTER(1)Input
On entry: specifies whether A is upper or lower triangular.
UPLO='U'
A is upper triangular.
UPLO='L'
A is lower triangular.
Constraint: UPLO='U' or 'L'.
2:   DIAG – CHARACTER(1)Input
On entry: indicates whether A is a nonunit or unit triangular matrix.
DIAG='N'
A is a nonunit triangular matrix.
DIAG='U'
A is a unit triangular matrix; the diagonal elements are not referenced and are assumed to be 1.
Constraint: DIAG='N' or 'U'.
3:   N – INTEGERInput
On entry: n, the order of the matrix A.
Constraint: N≥0.
4:   AP* – REAL (KIND=nag_wp) arrayInput/Output
Note: the dimension of the array AP must be at least max 1,N×N+1/2.
On entry: the n by n triangular matrix A, packed by columns.
More precisely,
  • if UPLO='U', the upper triangle of A must be stored with element A ij in AP i+j j-1/2 for i≤j;
  • if UPLO='L', the lower triangle of A must be stored with element A ij in AP i+2 n-jj-1/2 for i≥j.
If DIAG='U', the diagonal elements of A are assumed to be 1, and are not referenced; the same storage scheme is used whether DIAG='N' or ‘U’.
On exit: A is overwritten by A-1, using the same storage format as described above.
5:   INFO – INTEGEROutput
On exit: INFO=0 unless the routine detects an error (see Section 6).

6 Error Indicators and Warnings

INFO<0
If INFO=-i, argument i had an illegal value. An explanatory message is output, and execution of the program is terminated.
INFO>0
Element value of the diagonal is exactly zero. A is singular its inverse cannot be computed.

7 Accuracy

The computed inverse X satisfies
XA-I≤c n ε XA ,
where c n is a modest linear function of n, and ε is the machine precision.
Note that a similar bound for AX-I cannot be guaranteed, although it is almost always satisfied.
The computed inverse satisfies the forward error bound
X-A-1≤c n ε A-1AX .
See Du Croz and Higham (1992).

8 Parallelism and Performance

F07UJF (DTPTRI) makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The total number of floating-point operations is approximately 13 n 3.
The complex analogue of this routine is F07UWF (ZTPTRI).

10 Example

This example computes the inverse of the matrix A, where
A= 4.30 0.00 0.00 0.00 -3.96 -4.87 0.00 0.00 0.40 0.31 -8.02 0.00 -0.27 0.07 -5.95 0.12 ,
using packed storage.

10.1 Program Text

Program Text (f07ujfe.f90)

10.2 Program Data

Program Data (f07ujfe.d)

10.3 Program Results

Program Results (f07ujfe.r)

F07 Chapter Contents
F07 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F07USF (ZTPTRS) : NAG Library, Mark 26

F07 Chapter Contents
F07 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F07USF (ZTPTRS)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F07USF (ZTPTRS) solves a complex triangular system of linear equations with multiple right-hand sides, AX=B, AT X=B or AH X=B, using packed storage.

2 Specification

SUBROUTINE F07USF ( UPLO, TRANS, DIAG, N, NRHS, AP, B, LDB, INFO)
INTEGER | N, NRHS, LDB, INFO
COMPLEX (KIND=nag_wp) | AP(*), B(LDB,*)
CHARACTER(1) | UPLO, TRANS, DIAG
The routine may be called by its LAPACK name ztptrs.

3 Description

F07USF (ZTPTRS) solves a complex triangular system of linear equations AX=B, AT X=B or AH X=B, using packed storage.

4 References

Golub G H and Van Loan C F (1996) Matrix Computations (3rd Edition) Johns Hopkins University Press, Baltimore
Higham N J (1989) The accuracy of solutions to triangular systems SIAM J. Numer. Anal. 26 1252–1265

5 Arguments

1:   UPLO – CHARACTER(1)Input
On entry: specifies whether A is upper or lower triangular.
UPLO='U'
A is upper triangular.
UPLO='L'
A is lower triangular.
Constraint: UPLO='U' or 'L'.
2:   TRANS – CHARACTER(1)Input
On entry: indicates the form of the equations.
TRANS='N'
The equations are of the form AX=B.
TRANS='T'
The equations are of the form AT X=B.
TRANS='C'
The equations are of the form AH X=B.
Constraint: TRANS='N', 'T' or 'C'.
3:   DIAG – CHARACTER(1)Input
On entry: indicates whether A is a nonunit or unit triangular matrix.
DIAG='N'
A is a nonunit triangular matrix.
DIAG='U'
A is a unit triangular matrix; the diagonal elements are not referenced and are assumed to be 1.
Constraint: DIAG='N' or 'U'.
4:   N – INTEGERInput
On entry: n, the order of the matrix A.
Constraint: N≥0.
5:   NRHS – INTEGERInput
On entry: r, the number of right-hand sides.
Constraint: NRHS≥0.
6:   AP* – COMPLEX (KIND=nag_wp) arrayInput
Note: the dimension of the array AP must be at least max 1,N×N+1/2.
On entry: the n by n triangular matrix A, packed by columns.
More precisely,
  • if UPLO='U', the upper triangle of A must be stored with element A ij in AP i+j j-1/2 for i≤j;
  • if UPLO='L', the lower triangle of A must be stored with element A ij in AP i+2 n-jj-1/2 for i≥j.
If DIAG='U', the diagonal elements of A are assumed to be 1, and are not referenced; the same storage scheme is used whether DIAG='N' or ‘U’.
7:   B LDB* – COMPLEX (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array B must be at least max 1,NRHS.
On entry: the n by r right-hand side matrix B.
On exit: the n by r solution matrix X.
8:   LDB – INTEGERInput
On entry: the first dimension of the array B as declared in the (sub)program from which F07USF (ZTPTRS) is called.
Constraint: LDB≥max 1,N.
9:   INFO – INTEGEROutput
On exit: INFO=0 unless the routine detects an error (see Section 6).

6 Error Indicators and Warnings

INFO<0
If INFO=-i, argument i had an illegal value. An explanatory message is output, and execution of the program is terminated.
INFO>0
Element value of the diagonal is exactly zero. A is singular and the solution has not been computed.

7 Accuracy

The solutions of triangular systems of equations are usually computed to high accuracy. See Higham (1989).
For each right-hand side vector b, the computed solution x is the exact solution of a perturbed system of equations A+E x=b, where
E≤c n ε A ,
c n is a modest linear function of n, and ε is the machine precision.
If x^ is the true solution, then the computed solution x satisfies a forward error bound of the form
x-x^∞ x∞ ≤ c n cond A,x ε ,   provided   c n cond A,x ε<1 ,
where cond A,x=A-1Ax∞/x∞.
Note that cond A,x≤cond A=A-1A∞≤κ∞A; cond A,x can be much smaller than cond A and it is also possible for cond AH, which is the same as cond AT, to be much larger (or smaller) than cond A.
Forward and backward error bounds can be computed by calling F07UVF (ZTPRFS), and an estimate for κ∞A can be obtained by calling F07UUF (ZTPCON) with NORM='I'.

8 Parallelism and Performance

F07USF (ZTPTRS) is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
F07USF (ZTPTRS) makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The total number of real floating-point operations is approximately 4 n 2 r.
The real analogue of this routine is F07UEF (DTPTRS).

10 Example

This example solves the system of equations AX=B, where
A= 4.78+4.56 i 0.00+0.00 i 0.00+0.00 i 0.00+0.00 i 2.00-0.30 i -4.11+1.25 i 0.00+0.00 i 0.00+0.00 i 2.89-1.34 i 2.36-4.25 i 4.15+0.80 i 0.00+0.00 i -1.89+1.15 i 0.04-3.69 i -0.02+0.46 i 0.33-0.26 i
and
B= -14.78-32.36 i -18.02+28.46 i 2.98-0 2.14 i 14.22+15.42 i -20.96+17.06 i 5.62+35.89 i 9.54+0 9.91 i -16.46-0 1.73 i ,
using packed storage for A.

10.1 Program Text

Program Text (f07usfe.f90)

10.2 Program Data

Program Data (f07usfe.d)

10.3 Program Results

Program Results (f07usfe.r)

F07 Chapter Contents
F07 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F07UUF (ZTPCON) : NAG Library, Mark 26

F07 Chapter Contents
F07 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F07UUF (ZTPCON)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F07UUF (ZTPCON) estimates the condition number of a complex triangular matrix, using packed storage.

2 Specification

SUBROUTINE F07UUF ( NORM, UPLO, DIAG, N, AP, RCOND, WORK, RWORK, INFO)
INTEGER | N, INFO
REAL (KIND=nag_wp) | RCOND, RWORK(N)
COMPLEX (KIND=nag_wp) | AP(*), WORK(2*N)
CHARACTER(1) | NORM, UPLO, DIAG
The routine may be called by its LAPACK name ztpcon.

3 Description

F07UUF (ZTPCON) estimates the condition number of a complex triangular matrix A, in either the 1-norm or the ∞-norm, using packed storage:
κ 1 A = A 1 A-1 1   or   κ∞ A = A∞ A-1∞ .
Note that κ∞A=κ 1 AT.
Because the condition number is infinite if A is singular, the routine actually returns an estimate of the reciprocal of the condition number.
The routine computes A 1 or A∞ exactly, and uses Higham's implementation of Hager's method (see Higham (1988)) to estimate A-1 1 or A-1∞.

4 References

Higham N J (1988) FORTRAN codes for estimating the one-norm of a real or complex matrix, with applications to condition estimation ACM Trans. Math. Software 14 381–396

5 Arguments

1:   NORM – CHARACTER(1)Input
On entry: indicates whether κ 1 A or κ∞A is estimated.
NORM='1' or 'O'
κ 1 A is estimated.
NORM='I'
κ∞A is estimated.
Constraint: NORM='1', 'O' or 'I'.
2:   UPLO – CHARACTER(1)Input
On entry: specifies whether A is upper or lower triangular.
UPLO='U'
A is upper triangular.
UPLO='L'
A is lower triangular.
Constraint: UPLO='U' or 'L'.
3:   DIAG – CHARACTER(1)Input
On entry: indicates whether A is a nonunit or unit triangular matrix.
DIAG='N'
A is a nonunit triangular matrix.
DIAG='U'
A is a unit triangular matrix; the diagonal elements are not referenced and are assumed to be 1.
Constraint: DIAG='N' or 'U'.
4:   N – INTEGERInput
On entry: n, the order of the matrix A.
Constraint: N≥0.
5:   AP* – COMPLEX (KIND=nag_wp) arrayInput
Note: the dimension of the array AP must be at least max 1,N×N+1/2.
On entry: the n by n triangular matrix A, packed by columns.
More precisely,
  • if UPLO='U', the upper triangle of A must be stored with element A ij in AP i+j j-1/2 for i≤j;
  • if UPLO='L', the lower triangle of A must be stored with element A ij in AP i+2 n-jj-1/2 for i≥j.
If DIAG='U', the diagonal elements of A are assumed to be 1, and are not referenced; the same storage scheme is used whether DIAG='N' or ‘U’.
6:   RCOND – REAL (KIND=nag_wp)Output
On exit: an estimate of the reciprocal of the condition number of A. RCOND is set to zero if exact singularity is detected or the estimate underflows. If RCOND is less than machine precision, A is singular to working precision.
7:   WORK 2×N – COMPLEX (KIND=nag_wp) arrayWorkspace
8:   RWORK N – REAL (KIND=nag_wp) arrayWorkspace
9:   INFO – INTEGEROutput
On exit: INFO=0 unless the routine detects an error (see Section 6).

6 Error Indicators and Warnings

INFO<0
If INFO=-i, argument i had an illegal value. An explanatory message is output, and execution of the program is terminated.

7 Accuracy

The computed estimate RCOND is never less than the true value ρ, and in practice is nearly always less than 10 ρ, although examples can be constructed where RCOND is much larger.

8 Parallelism and Performance

F07UUF (ZTPCON) makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

A call to F07UUF (ZTPCON) involves solving a number of systems of linear equations of the form Ax=b or AH x=b; the number is usually 5 and never more than 11. Each solution involves approximately 4 n 2 real floating-point operations but takes considerably longer than a call to F07USF (ZTPTRS) with one right-hand side, because extra care is taken to avoid overflow when A is approximately singular.
The real analogue of this routine is F07UGF (DTPCON).

10 Example

This example estimates the condition number in the 1-norm of the matrix A, where
A= 4.78+4.56 i 0.00+0.00 i 0.00+0.00 i 0.00+0.00 i 2.00-0.30 i -4.11+1.25 i 0.00+0.00 i 0.00+0.00 i 2.89-1.34 i 2.36-4.25 i 4.15+0.80 i 0.00+0.00 i -1.89+1.15 i 0.04-3.69 i -0.02+0.46 i 0.33-0.26 i ,
using packed storage. The true condition number in the 1-norm is 70.27.

10.1 Program Text

Program Text (f07uufe.f90)

10.2 Program Data

Program Data (f07uufe.d)

10.3 Program Results

Program Results (f07uufe.r)

F07 Chapter Contents
F07 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F07UVF (ZTPRFS) : NAG Library, Mark 26

F07 Chapter Contents
F07 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F07UVF (ZTPRFS)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F07UVF (ZTPRFS) returns error bounds for the solution of a complex triangular system of linear equations with multiple right-hand sides, AX=B, AT X=B or AH X=B, using packed storage.

2 Specification

SUBROUTINE F07UVF ( UPLO, TRANS, DIAG, N, NRHS, AP, B, LDB, X, LDX, FERR, BERR, WORK, RWORK, INFO)
INTEGER | N, NRHS, LDB, LDX, INFO
REAL (KIND=nag_wp) | FERR(NRHS), BERR(NRHS), RWORK(N)
COMPLEX (KIND=nag_wp) | AP(*), B(LDB,*), X(LDX,*), WORK(2*N)
CHARACTER(1) | UPLO, TRANS, DIAG
The routine may be called by its LAPACK name ztprfs.

3 Description

F07UVF (ZTPRFS) returns the backward errors and estimated bounds on the forward errors for the solution of a complex triangular system of linear equations with multiple right-hand sides AX=B, AT X=B or AH X=B, using packed storage. The routine handles each right-hand side vector (stored as a column of the matrix B) independently, so we describe the function of F07UVF (ZTPRFS) in terms of a single right-hand side b and solution x.
Given a computed solution x, the routine computes the component-wise backward error β. This is the size of the smallest relative perturbation in each element of A and b such that x is the exact solution of a perturbed system
A+δA x=b+δb δ a ij≤β a ij   and   δ bi≤β bi .
Then the routine estimates a bound for the component-wise forward error in the computed solution, defined by:
maxi xi-x^i/maxi xi
where x^ is the true solution.
For details of the method, see the F07 Chapter Introduction.

4 References

Golub G H and Van Loan C F (1996) Matrix Computations (3rd Edition) Johns Hopkins University Press, Baltimore

5 Arguments

1:   UPLO – CHARACTER(1)Input
On entry: specifies whether A is upper or lower triangular.
UPLO='U'
A is upper triangular.
UPLO='L'
A is lower triangular.
Constraint: UPLO='U' or 'L'.
2:   TRANS – CHARACTER(1)Input
On entry: indicates the form of the equations.
TRANS='N'
The equations are of the form AX=B.
TRANS='T'
The equations are of the form AT X=B.
TRANS='C'
The equations are of the form AH X=B.
Constraint: TRANS='N', 'T' or 'C'.
3:   DIAG – CHARACTER(1)Input
On entry: indicates whether A is a nonunit or unit triangular matrix.
DIAG='N'
A is a nonunit triangular matrix.
DIAG='U'
A is a unit triangular matrix; the diagonal elements are not referenced and are assumed to be 1.
Constraint: DIAG='N' or 'U'.
4:   N – INTEGERInput
On entry: n, the order of the matrix A.
Constraint: N≥0.
5:   NRHS – INTEGERInput
On entry: r, the number of right-hand sides.
Constraint: NRHS≥0.
6:   AP* – COMPLEX (KIND=nag_wp) arrayInput
Note: the dimension of the array AP must be at least max 1,N×N+1/2.
On entry: the n by n triangular matrix A, packed by columns.
More precisely,
  • if UPLO='U', the upper triangle of A must be stored with element A ij in AP i+j j-1/2 for i≤j;
  • if UPLO='L', the lower triangle of A must be stored with element A ij in AP i+2 n-jj-1/2 for i≥j.
If DIAG='U', the diagonal elements of A are assumed to be 1, and are not referenced; the same storage scheme is used whether DIAG='N' or ‘U’.
7:   B LDB* – COMPLEX (KIND=nag_wp) arrayInput
Note: the second dimension of the array B must be at least max 1,NRHS.
On entry: the n by r right-hand side matrix B.
8:   LDB – INTEGERInput
On entry: the first dimension of the array B as declared in the (sub)program from which F07UVF (ZTPRFS) is called.
Constraint: LDB≥max 1,N.
9:   X LDX* – COMPLEX (KIND=nag_wp) arrayInput
Note: the second dimension of the array X must be at least max 1,NRHS.
On entry: the n by r solution matrix X, as returned by F07USF (ZTPTRS).
10:   LDX – INTEGERInput
On entry: the first dimension of the array X as declared in the (sub)program from which F07UVF (ZTPRFS) is called.
Constraint: LDX≥max 1,N.
11:   FERR NRHS – REAL (KIND=nag_wp) arrayOutput
On exit: FERR j contains an estimated error bound for the jth solution vector, that is, the jth column of X, for j=1,2,…,r.
12:   BERR NRHS – REAL (KIND=nag_wp) arrayOutput
On exit: BERR j contains the component-wise backward error bound β for the jth solution vector, that is, the jth column of X, for j=1,2,…,r.
13:   WORK 2×N – COMPLEX (KIND=nag_wp) arrayWorkspace
14:   RWORK N – REAL (KIND=nag_wp) arrayWorkspace
15:   INFO – INTEGEROutput
On exit: INFO=0 unless the routine detects an error (see Section 6).

6 Error Indicators and Warnings

INFO<0
If INFO=-i, argument i had an illegal value. An explanatory message is output, and execution of the program is terminated.

7 Accuracy

The bounds returned in FERR are not rigorous, because they are estimated, not computed exactly; but in practice they almost always overestimate the actual error.

8 Parallelism and Performance

F07UVF (ZTPRFS) is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
F07UVF (ZTPRFS) makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

A call to F07UVF (ZTPRFS), for each right-hand side, involves solving a number of systems of linear equations of the form Ax=b or AH x=b; the number is usually 5 and never more than 11. Each solution involves approximately 4 n 2 real floating-point operations.
The real analogue of this routine is F07UHF (DTPRFS).

10 Example

This example solves the system of equations AX=B and to compute forward and backward error bounds, where
A= 4.78+4.56 i 0.00+0.00 i 0.00+0.00 i 0.00+0.00 i 2.00-0.30 i -4.11+1.25 i 0.00+0.00 i 0.00+0.00 i 2.89-1.34 i 2.36-4.25 i 4.15+0.80 i 0.00+0.00 i -1.89+1.15 i 0.04-3.69 i -0.02+0.46 i 0.33-0.26 i
and
B= -14.78-32.36 i -18.02+28.46 i 2.98-0 2.14 i 14.22+15.42 i -20.96+17.06 i 5.62+35.89 i 9.54+0 9.91 i -16.46-0 1.73 i ,
using packed storage for A.

10.1 Program Text

Program Text (f07uvfe.f90)

10.2 Program Data

Program Data (f07uvfe.d)

10.3 Program Results

Program Results (f07uvfe.r)

F07 Chapter Contents
F07 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F07UWF (ZTPTRI) : NAG Library, Mark 26

F07 Chapter Contents
F07 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F07UWF (ZTPTRI)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F07UWF (ZTPTRI) computes the inverse of a complex triangular matrix, using packed storage.

2 Specification

SUBROUTINE F07UWF ( UPLO, DIAG, N, AP, INFO)
INTEGER | N, INFO
COMPLEX (KIND=nag_wp) | AP(*)
CHARACTER(1) | UPLO, DIAG
The routine may be called by its LAPACK name ztptri.

3 Description

F07UWF (ZTPTRI) forms the inverse of a complex triangular matrix A, using packed storage. Note that the inverse of an upper (lower) triangular matrix is also upper (lower) triangular.

4 References

Du Croz J J and Higham N J (1992) Stability of methods for matrix inversion IMA J. Numer. Anal. 12 1–19

5 Arguments

1:   UPLO – CHARACTER(1)Input
On entry: specifies whether A is upper or lower triangular.
UPLO='U'
A is upper triangular.
UPLO='L'
A is lower triangular.
Constraint: UPLO='U' or 'L'.
2:   DIAG – CHARACTER(1)Input
On entry: indicates whether A is a nonunit or unit triangular matrix.
DIAG='N'
A is a nonunit triangular matrix.
DIAG='U'
A is a unit triangular matrix; the diagonal elements are not referenced and are assumed to be 1.
Constraint: DIAG='N' or 'U'.
3:   N – INTEGERInput
On entry: n, the order of the matrix A.
Constraint: N≥0.
4:   AP* – COMPLEX (KIND=nag_wp) arrayInput/Output
Note: the dimension of the array AP must be at least max 1,N×N+1/2.
On entry: the n by n triangular matrix A, packed by columns.
More precisely,
  • if UPLO='U', the upper triangle of A must be stored with element A ij in AP i+j j-1/2 for i≤j;
  • if UPLO='L', the lower triangle of A must be stored with element A ij in AP i+2 n-jj-1/2 for i≥j.
If DIAG='U', the diagonal elements of A are assumed to be 1, and are not referenced; the same storage scheme is used whether DIAG='N' or ‘U’.
On exit: A is overwritten by A-1, using the same storage format as described above.
5:   INFO – INTEGEROutput
On exit: INFO=0 unless the routine detects an error (see Section 6).

6 Error Indicators and Warnings

INFO<0
If INFO=-i, argument i had an illegal value. An explanatory message is output, and execution of the program is terminated.
INFO>0
Element value of the diagonal is exactly zero. A is singular its inverse cannot be computed.

7 Accuracy

The computed inverse X satisfies
XA-I≤c n ε XA ,
where c n is a modest linear function of n, and ε is the machine precision.
Note that a similar bound for AX-I cannot be guaranteed, although it is almost always satisfied.
The computed inverse satisfies the forward error bound
X-A-1≤c n ε A-1AX .
See Du Croz and Higham (1992).

8 Parallelism and Performance

F07UWF (ZTPTRI) makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The total number of real floating-point operations is approximately 43 n 3.
The real analogue of this routine is F07UJF (DTPTRI).

10 Example

This example computes the inverse of the matrix A, where
A= 4.78+4.56 i 0.00+0.00 i 0.00+0.00 i 0.00+0.00 i 2.00-0.30 i -4.11+1.25 i 0.00+0.00 i 0.00+0.00 i 2.89-1.34 i 2.36-4.25 i 4.15+0.80 i 0.00+0.00 i -1.89+1.15 i 0.04-3.69 i -0.02+0.46 i 0.33-0.26 i ,
using packed storage.

10.1 Program Text

Program Text (f07uwfe.f90)

10.2 Program Data

Program Data (f07uwfe.d)

10.3 Program Results

Program Results (f07uwfe.r)

F07 Chapter Contents
F07 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F07VEF (DTBTRS) : NAG Library, Mark 26

F07 Chapter Contents
F07 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F07VEF (DTBTRS)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F07VEF (DTBTRS) solves a real triangular band system of linear equations with multiple right-hand sides, AX=B or AT X=B.

2 Specification

SUBROUTINE F07VEF ( UPLO, TRANS, DIAG, N, KD, NRHS, AB, LDAB, B, LDB, INFO)
INTEGER | N, KD, NRHS, LDAB, LDB, INFO
REAL (KIND=nag_wp) | AB(LDAB,*), B(LDB,*)
CHARACTER(1) | UPLO, TRANS, DIAG
The routine may be called by its LAPACK name dtbtrs.

3 Description

F07VEF (DTBTRS) solves a real triangular band system of linear equations AX=B or AT X=B.

4 References

Golub G H and Van Loan C F (1996) Matrix Computations (3rd Edition) Johns Hopkins University Press, Baltimore
Higham N J (1989) The accuracy of solutions to triangular systems SIAM J. Numer. Anal. 26 1252–1265

5 Arguments

1:   UPLO – CHARACTER(1)Input
On entry: specifies whether A is upper or lower triangular.
UPLO='U'
A is upper triangular.
UPLO='L'
A is lower triangular.
Constraint: UPLO='U' or 'L'.
2:   TRANS – CHARACTER(1)Input
On entry: indicates the form of the equations.
TRANS='N'
The equations are of the form AX=B.
TRANS='T' or 'C'
The equations are of the form AT X=B.
Constraint: TRANS='N', 'T' or 'C'.
3:   DIAG – CHARACTER(1)Input
On entry: indicates whether A is a nonunit or unit triangular matrix.
DIAG='N'
A is a nonunit triangular matrix.
DIAG='U'
A is a unit triangular matrix; the diagonal elements are not referenced and are assumed to be 1.
Constraint: DIAG='N' or 'U'.
4:   N – INTEGERInput
On entry: n, the order of the matrix A.
Constraint: N≥0.
5:   KD – INTEGERInput
On entry: kd, the number of superdiagonals of the matrix A if UPLO='U', or the number of subdiagonals if UPLO='L'.
Constraint: KD≥0.
6:   NRHS – INTEGERInput
On entry: r, the number of right-hand sides.
Constraint: NRHS≥0.
7:   AB LDAB* – REAL (KIND=nag_wp) arrayInput
Note: the second dimension of the array AB must be at least max 1,N.
On entry: the n by n triangular band matrix A.
The matrix is stored in rows 1 to kd+1, more precisely,
  • if UPLO='U', the elements of the upper triangle of A within the band must be stored with element A ij in AB kd+1+i-j j​ for ​max 1,j-kd≤i≤j;
  • if UPLO='L', the elements of the lower triangle of A within the band must be stored with element A ij in AB 1+i-j j​ for ​j≤i≤min n,j+kd.
If DIAG='U', the diagonal elements of A are assumed to be 1, and are not referenced.
8:   LDAB – INTEGERInput
On entry: the first dimension of the array AB as declared in the (sub)program from which F07VEF (DTBTRS) is called.
Constraint: LDAB≥KD+1.
9:   B LDB* – REAL (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array B must be at least max 1,NRHS.
On entry: the n by r right-hand side matrix B.
On exit: the n by r solution matrix X.
10:   LDB – INTEGERInput
On entry: the first dimension of the array B as declared in the (sub)program from which F07VEF (DTBTRS) is called.
Constraint: LDB≥max 1,N.
11:   INFO – INTEGEROutput
On exit: INFO=0 unless the routine detects an error (see Section 6).

6 Error Indicators and Warnings

INFO<0
If INFO=-i, argument i had an illegal value. An explanatory message is output, and execution of the program is terminated.
INFO>0
Element value of the diagonal is exactly zero. A is singular and the solution has not been computed.

7 Accuracy

The solutions of triangular systems of equations are usually computed to high accuracy. See Higham (1989).
For each right-hand side vector b, the computed solution x is the exact solution of a perturbed system of equations A+E x=b, where
E≤c k ε A ,
c k is a modest linear function of k, and ε is the machine precision.
If x^ is the true solution, then the computed solution x satisfies a forward error bound of the form
x-x^∞ x∞ ≤c k cond A,x ε ,   provided   c k cond A,x ε<1 ,
where cond A,x=A-1Ax∞/x∞.
Note that cond A,x≤cond A=A-1A∞≤κ∞A; cond A,x can be much smaller than cond A and it is also possible for cond AT to be much larger (or smaller) than cond A.
Forward and backward error bounds can be computed by calling F07VHF (DTBRFS), and an estimate for κ∞A can be obtained by calling F07VGF (DTBCON) with NORM='I'.

8 Parallelism and Performance

F07VEF (DTBTRS) is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
F07VEF (DTBTRS) makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The total number of floating-point operations is approximately 2 nkr if k≪n.
The complex analogue of this routine is F07VSF (ZTBTRS).

10 Example

This example solves the system of equations AX=B, where
A= -4.16 0.00 0.00 0.00 -2.25 4.78 0.00 0.00 0.00 5.86 6.32 0.00 0.00 0.00 -4.82 0.16   and   B= -16.64 -4.16 -13.78 -16.59 13.10 -4.94 -14.14 -9.96 .
Here A is treated as a lower triangular band matrix with one subdiagonal.

10.1 Program Text

Program Text (f07vefe.f90)

10.2 Program Data

Program Data (f07vefe.d)

10.3 Program Results

Program Results (f07vefe.r)

F07 Chapter Contents
F07 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F07VGF (DTBCON) : NAG Library, Mark 26

F07 Chapter Contents
F07 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F07VGF (DTBCON)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F07VGF (DTBCON) estimates the condition number of a real triangular band matrix.

2 Specification

SUBROUTINE F07VGF ( NORM, UPLO, DIAG, N, KD, AB, LDAB, RCOND, WORK, IWORK, INFO)
INTEGER | N, KD, LDAB, IWORK(N), INFO
REAL (KIND=nag_wp) | AB(LDAB,*), RCOND, WORK(3*N)
CHARACTER(1) | NORM, UPLO, DIAG
The routine may be called by its LAPACK name dtbcon.

3 Description

F07VGF (DTBCON) estimates the condition number of a real triangular band matrix A, in either the 1-norm or the ∞-norm:
κ 1 A=A 1A-1 1   or   κ∞A=A∞A-1∞ .
Note that κ∞A=κ 1 AT.
Because the condition number is infinite if A is singular, the routine actually returns an estimate of the reciprocal of the condition number.
The routine computes A 1 or A∞ exactly, and uses Higham's implementation of Hager's method (see Higham (1988)) to estimate A-1 1 or A-1∞.

4 References

Higham N J (1988) FORTRAN codes for estimating the one-norm of a real or complex matrix, with applications to condition estimation ACM Trans. Math. Software 14 381–396

5 Arguments

1:   NORM – CHARACTER(1)Input
On entry: indicates whether κ 1 A or κ∞A is estimated.
NORM='1' or 'O'
κ 1 A is estimated.
NORM='I'
κ∞A is estimated.
Constraint: NORM='1', 'O' or 'I'.
2:   UPLO – CHARACTER(1)Input
On entry: specifies whether A is upper or lower triangular.
UPLO='U'
A is upper triangular.
UPLO='L'
A is lower triangular.
Constraint: UPLO='U' or 'L'.
3:   DIAG – CHARACTER(1)Input
On entry: indicates whether A is a nonunit or unit triangular matrix.
DIAG='N'
A is a nonunit triangular matrix.
DIAG='U'
A is a unit triangular matrix; the diagonal elements are not referenced and are assumed to be 1.
Constraint: DIAG='N' or 'U'.
4:   N – INTEGERInput
On entry: n, the order of the matrix A.
Constraint: N≥0.
5:   KD – INTEGERInput
On entry: kd, the number of superdiagonals of the matrix A if UPLO='U', or the number of subdiagonals if UPLO='L'.
Constraint: KD≥0.
6:   AB LDAB* – REAL (KIND=nag_wp) arrayInput
Note: the second dimension of the array AB must be at least max 1,N.
On entry: the n by n triangular band matrix A.
The matrix is stored in rows 1 to kd+1, more precisely,
  • if UPLO='U', the elements of the upper triangle of A within the band must be stored with element A ij in AB kd+1+i-j j​ for ​max 1,j-kd≤i≤j;
  • if UPLO='L', the elements of the lower triangle of A within the band must be stored with element A ij in AB 1+i-j j​ for ​j≤i≤min n,j+kd.
If DIAG='U', the diagonal elements of A are assumed to be 1, and are not referenced.
7:   LDAB – INTEGERInput
On entry: the first dimension of the array AB as declared in the (sub)program from which F07VGF (DTBCON) is called.
Constraint: LDAB≥KD+1.
8:   RCOND – REAL (KIND=nag_wp)Output
On exit: an estimate of the reciprocal of the condition number of A. RCOND is set to zero if exact singularity is detected or the estimate underflows. If RCOND is less than machine precision, A is singular to working precision.
9:   WORK 3×N – REAL (KIND=nag_wp) arrayWorkspace
10:   IWORK N – INTEGER arrayWorkspace
11:   INFO – INTEGEROutput
On exit: INFO=0 unless the routine detects an error (see Section 6).

6 Error Indicators and Warnings

INFO<0
If INFO=-i, argument i had an illegal value. An explanatory message is output, and execution of the program is terminated.

7 Accuracy

The computed estimate RCOND is never less than the true value ρ, and in practice is nearly always less than 10 ρ, although examples can be constructed where RCOND is much larger.

8 Parallelism and Performance

F07VGF (DTBCON) makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

A call to F07VGF (DTBCON) involves solving a number of systems of linear equations of the form Ax=b or AT x=b; the number is usually 4 or 5 and never more than 11. Each solution involves approximately 2 nk floating-point operations (assuming n≫k) but takes considerably longer than a call to F07VEF (DTBTRS) with one right-hand side, because extra care is taken to avoid overflow when A is approximately singular.
The complex analogue of this routine is F07VUF (ZTBCON).

10 Example

This example estimates the condition number in the 1-norm of the matrix A, where
A= -4.16 0.00 0.00 0.00 -2.25 4.78 0.00 0.00 0.00 5.86 6.32 0.00 0.00 0.00 -4.82 0.16 .
Here A is treated as a lower triangular band matrix with one subdiagonal. The true condition number in the 1-norm is 69.62.

10.1 Program Text

Program Text (f07vgfe.f90)

10.2 Program Data

Program Data (f07vgfe.d)

10.3 Program Results

Program Results (f07vgfe.r)

F07 Chapter Contents
F07 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F07VHF (DTBRFS) : NAG Library, Mark 26

F07 Chapter Contents
F07 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F07VHF (DTBRFS)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F07VHF (DTBRFS) returns error bounds for the solution of a real triangular band system of linear equations with multiple right-hand sides, AX=B or AT X=B.

2 Specification

SUBROUTINE F07VHF ( UPLO, TRANS, DIAG, N, KD, NRHS, AB, LDAB, B, LDB, X, LDX, FERR, BERR, WORK, IWORK, INFO)
INTEGER | N, KD, NRHS, LDAB, LDB, LDX, IWORK(N), INFO
REAL (KIND=nag_wp) | AB(LDAB,*), B(LDB,*), X(LDX,*), FERR(NRHS), BERR(NRHS), WORK(3*N)
CHARACTER(1) | UPLO, TRANS, DIAG
The routine may be called by its LAPACK name dtbrfs.

3 Description

F07VHF (DTBRFS) returns the backward errors and estimated bounds on the forward errors for the solution of a real triangular band system of linear equations with multiple right-hand sides AX=B or AT X=B. The routine handles each right-hand side vector (stored as a column of the matrix B) independently, so we describe the function of F07VHF (DTBRFS) in terms of a single right-hand side b and solution x.
Given a computed solution x, the routine computes the component-wise backward error β. This is the size of the smallest relative perturbation in each element of A and b such that x is the exact solution of a perturbed system
A+δA x=b+δb δ a ij≤β a ij   and   δ bi≤β bi .
Then the routine estimates a bound for the component-wise forward error in the computed solution, defined by:
maxi xi-x^i/maxi xi
where x^ is the true solution.
For details of the method, see the F07 Chapter Introduction.

4 References

Golub G H and Van Loan C F (1996) Matrix Computations (3rd Edition) Johns Hopkins University Press, Baltimore

5 Arguments

1:   UPLO – CHARACTER(1)Input
On entry: specifies whether A is upper or lower triangular.
UPLO='U'
A is upper triangular.
UPLO='L'
A is lower triangular.
Constraint: UPLO='U' or 'L'.
2:   TRANS – CHARACTER(1)Input
On entry: indicates the form of the equations.
TRANS='N'
The equations are of the form AX=B.
TRANS='T' or 'C'
The equations are of the form AT X=B.
Constraint: TRANS='N', 'T' or 'C'.
3:   DIAG – CHARACTER(1)Input
On entry: indicates whether A is a nonunit or unit triangular matrix.
DIAG='N'
A is a nonunit triangular matrix.
DIAG='U'
A is a unit triangular matrix; the diagonal elements are not referenced and are assumed to be 1.
Constraint: DIAG='N' or 'U'.
4:   N – INTEGERInput
On entry: n, the order of the matrix A.
Constraint: N≥0.
5:   KD – INTEGERInput
On entry: kd, the number of superdiagonals of the matrix A if UPLO='U', or the number of subdiagonals if UPLO='L'.
Constraint: KD≥0.
6:   NRHS – INTEGERInput
On entry: r, the number of right-hand sides.
Constraint: NRHS≥0.
7:   AB LDAB* – REAL (KIND=nag_wp) arrayInput
Note: the second dimension of the array AB must be at least max 1,N.
On entry: the n by n triangular band matrix A.
The matrix is stored in rows 1 to kd+1, more precisely,
  • if UPLO='U', the elements of the upper triangle of A within the band must be stored with element A ij in AB kd+1+i-j j​ for ​max 1,j-kd≤i≤j;
  • if UPLO='L', the elements of the lower triangle of A within the band must be stored with element A ij in AB 1+i-j j​ for ​j≤i≤min n,j+kd.
If DIAG='U', the diagonal elements of A are assumed to be 1, and are not referenced.
8:   LDAB – INTEGERInput
On entry: the first dimension of the array AB as declared in the (sub)program from which F07VHF (DTBRFS) is called.
Constraint: LDAB≥KD+1.
9:   B LDB* – REAL (KIND=nag_wp) arrayInput
Note: the second dimension of the array B must be at least max 1,NRHS.
On entry: the n by r right-hand side matrix B.
10:   LDB – INTEGERInput
On entry: the first dimension of the array B as declared in the (sub)program from which F07VHF (DTBRFS) is called.
Constraint: LDB≥max 1,N.
11:   X LDX* – REAL (KIND=nag_wp) arrayInput
Note: the second dimension of the array X must be at least max 1,NRHS.
On entry: the n by r solution matrix X, as returned by F07VEF (DTBTRS).
12:   LDX – INTEGERInput
On entry: the first dimension of the array X as declared in the (sub)program from which F07VHF (DTBRFS) is called.
Constraint: LDX≥max 1,N.
13:   FERR NRHS – REAL (KIND=nag_wp) arrayOutput
On exit: FERR j contains an estimated error bound for the jth solution vector, that is, the jth column of X, for j=1,2,…,r.
14:   BERR NRHS – REAL (KIND=nag_wp) arrayOutput
On exit: BERR j contains the component-wise backward error bound β for the jth solution vector, that is, the jth column of X, for j=1,2,…,r.
15:   WORK 3×N – REAL (KIND=nag_wp) arrayWorkspace
16:   IWORK N – INTEGER arrayWorkspace
17:   INFO – INTEGEROutput
On exit: INFO=0 unless the routine detects an error (see Section 6).

6 Error Indicators and Warnings

INFO<0
If INFO=-i, argument i had an illegal value. An explanatory message is output, and execution of the program is terminated.

7 Accuracy

The bounds returned in FERR are not rigorous, because they are estimated, not computed exactly; but in practice they almost always overestimate the actual error.

8 Parallelism and Performance

F07VHF (DTBRFS) is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
F07VHF (DTBRFS) makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

A call to F07VHF (DTBRFS), for each right-hand side, involves solving a number of systems of linear equations of the form Ax=b or AT x=b; the number is usually 4 or 5 and never more than 11. Each solution involves approximately 2 nk floating-point operations (assuming n≫k).
The complex analogue of this routine is F07VVF (ZTBRFS).

10 Example

This example solves the system of equations AX=B and to compute forward and backward error bounds, where
A= -4.16 0.00 0.00 0.00 -2.25 4.78 0.00 0.00 0.00 5.86 6.32 0.00 0.00 0.00 -4.82 0.16   and   B= -16.64 -4.16 -13.78 -16.59 13.10 -4.94 -14.14 -9.96 .

10.1 Program Text

Program Text (f07vhfe.f90)

10.2 Program Data

Program Data (f07vhfe.d)

10.3 Program Results

Program Results (f07vhfe.r)

F07 Chapter Contents
F07 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F07VSF (ZTBTRS) : NAG Library, Mark 26

F07 Chapter Contents
F07 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F07VSF (ZTBTRS)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F07VSF (ZTBTRS) solves a complex triangular band system of linear equations with multiple right-hand sides, AX=B, AT X=B or AH X=B.

2 Specification

SUBROUTINE F07VSF ( UPLO, TRANS, DIAG, N, KD, NRHS, AB, LDAB, B, LDB, INFO)
INTEGER | N, KD, NRHS, LDAB, LDB, INFO
COMPLEX (KIND=nag_wp) | AB(LDAB,*), B(LDB,*)
CHARACTER(1) | UPLO, TRANS, DIAG
The routine may be called by its LAPACK name ztbtrs.

3 Description

F07VSF (ZTBTRS) solves a complex triangular band system of linear equations AX=B, AT X=B or AH X=B.

4 References

Golub G H and Van Loan C F (1996) Matrix Computations (3rd Edition) Johns Hopkins University Press, Baltimore
Higham N J (1989) The accuracy of solutions to triangular systems SIAM J. Numer. Anal. 26 1252–1265

5 Arguments

1:   UPLO – CHARACTER(1)Input
On entry: specifies whether A is upper or lower triangular.
UPLO='U'
A is upper triangular.
UPLO='L'
A is lower triangular.
Constraint: UPLO='U' or 'L'.
2:   TRANS – CHARACTER(1)Input
On entry: indicates the form of the equations.
TRANS='N'
The equations are of the form AX=B.
TRANS='T'
The equations are of the form AT X=B.
TRANS='C'
The equations are of the form AH X=B.
Constraint: TRANS='N', 'T' or 'C'.
3:   DIAG – CHARACTER(1)Input
On entry: indicates whether A is a nonunit or unit triangular matrix.
DIAG='N'
A is a nonunit triangular matrix.
DIAG='U'
A is a unit triangular matrix; the diagonal elements are not referenced and are assumed to be 1.
Constraint: DIAG='N' or 'U'.
4:   N – INTEGERInput
On entry: n, the order of the matrix A.
Constraint: N≥0.
5:   KD – INTEGERInput
On entry: kd, the number of superdiagonals of the matrix A if UPLO='U', or the number of subdiagonals if UPLO='L'.
Constraint: KD≥0.
6:   NRHS – INTEGERInput
On entry: r, the number of right-hand sides.
Constraint: NRHS≥0.
7:   AB LDAB* – COMPLEX (KIND=nag_wp) arrayInput
Note: the second dimension of the array AB must be at least max 1,N.
On entry: the n by n triangular band matrix A.
The matrix is stored in rows 1 to kd+1, more precisely,
  • if UPLO='U', the elements of the upper triangle of A within the band must be stored with element A ij in AB kd+1+i-j j​ for ​max 1,j-kd≤i≤j;
  • if UPLO='L', the elements of the lower triangle of A within the band must be stored with element A ij in AB 1+i-j j​ for ​j≤i≤min n,j+kd.
If DIAG='U', the diagonal elements of A are assumed to be 1, and are not referenced.
8:   LDAB – INTEGERInput
On entry: the first dimension of the array AB as declared in the (sub)program from which F07VSF (ZTBTRS) is called.
Constraint: LDAB≥KD+1.
9:   B LDB* – COMPLEX (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array B must be at least max 1,NRHS.
On entry: the n by r right-hand side matrix B.
On exit: the n by r solution matrix X.
10:   LDB – INTEGERInput
On entry: the first dimension of the array B as declared in the (sub)program from which F07VSF (ZTBTRS) is called.
Constraint: LDB≥max 1,N.
11:   INFO – INTEGEROutput
On exit: INFO=0 unless the routine detects an error (see Section 6).

6 Error Indicators and Warnings

INFO<0
If INFO=-i, argument i had an illegal value. An explanatory message is output, and execution of the program is terminated.
INFO>0
Element value of the diagonal is exactly zero. A is singular and the solution has not been computed.

7 Accuracy

The solutions of triangular systems of equations are usually computed to high accuracy. See Higham (1989).
For each right-hand side vector b, the computed solution x is the exact solution of a perturbed system of equations A+E x=b, where
E≤c k ε A ,
c k is a modest linear function of k, and ε is the machine precision.
If x^ is the true solution, then the computed solution x satisfies a forward error bound of the form
x-x^∞ x∞ ≤c k cond A,x ε ,   provided   c k cond A,x ε<1 ,
where cond A,x=A-1Ax∞/x∞.
Note that cond A,x≤cond A=A-1A∞≤κ∞A; cond A,x can be much smaller than cond A and it is also possible for cond AH, which is the same as cond AT, to be much larger (or smaller) than cond A.
Forward and backward error bounds can be computed by calling F07VVF (ZTBRFS), and an estimate for κ∞A can be obtained by calling F07VUF (ZTBCON) with NORM='I'.

8 Parallelism and Performance

F07VSF (ZTBTRS) is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
F07VSF (ZTBTRS) makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The total number of real floating-point operations is approximately 8 nkr if k≪n.
The real analogue of this routine is F07VEF (DTBTRS).

10 Example

This example solves the system of equations AX=B, where
A= -1.94+4.43 i 0.00+0.00 i 0.00+0.00 i 0.00+0.00 i -3.39+3.44 i 4.12-4.27 i 0.00+0.00 i 0.00+0.00 i 1.62+3.68 i -1.84+5.53 i 0.43-2.66 i 0.00+0.00 i 0.00+0.00 i -2.77-1.93 i 1.74-0.04 i 0.44+0.10 i
and
B= -8.86-0 3.88 i -24.09-0 5.27 i -15.57-23.41 i -57.97+0 8.14 i -7.63+22.78 i 19.09-29.51 i -14.74-0 2.40 i 19.17+21.33 i .
Here A is treated as a lower triangular band matrix with two subdiagonals.

10.1 Program Text

Program Text (f07vsfe.f90)

10.2 Program Data

Program Data (f07vsfe.d)

10.3 Program Results

Program Results (f07vsfe.r)

F07 Chapter Contents
F07 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F07VUF (ZTBCON) : NAG Library, Mark 26

F07 Chapter Contents
F07 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F07VUF (ZTBCON)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F07VUF (ZTBCON) estimates the condition number of a complex triangular band matrix.

2 Specification

SUBROUTINE F07VUF ( NORM, UPLO, DIAG, N, KD, AB, LDAB, RCOND, WORK, RWORK, INFO)
INTEGER | N, KD, LDAB, INFO
REAL (KIND=nag_wp) | RCOND, RWORK(N)
COMPLEX (KIND=nag_wp) | AB(LDAB,*), WORK(2*N)
CHARACTER(1) | NORM, UPLO, DIAG
The routine may be called by its LAPACK name ztbcon.

3 Description

F07VUF (ZTBCON) estimates the condition number of a complex triangular band matrix A, in either the 1-norm or the ∞-norm:
κ 1 A=A 1A-1 1   or   κ∞A=A∞A-1∞ .
Note that κ∞A=κ 1 AT.
Because the condition number is infinite if A is singular, the routine actually returns an estimate of the reciprocal of the condition number.
The routine computes A 1 or A∞ exactly, and uses Higham's implementation of Hager's method (see Higham (1988)) to estimate A-1 1 or A-1∞.

4 References

Higham N J (1988) FORTRAN codes for estimating the one-norm of a real or complex matrix, with applications to condition estimation ACM Trans. Math. Software 14 381–396

5 Arguments

1:   NORM – CHARACTER(1)Input
On entry: indicates whether κ 1 A or κ∞A is estimated.
NORM='1' or 'O'
κ 1 A is estimated.
NORM='I'
κ∞A is estimated.
Constraint: NORM='1', 'O' or 'I'.
2:   UPLO – CHARACTER(1)Input
On entry: specifies whether A is upper or lower triangular.
UPLO='U'
A is upper triangular.
UPLO='L'
A is lower triangular.
Constraint: UPLO='U' or 'L'.
3:   DIAG – CHARACTER(1)Input
On entry: indicates whether A is a nonunit or unit triangular matrix.
DIAG='N'
A is a nonunit triangular matrix.
DIAG='U'
A is a unit triangular matrix; the diagonal elements are not referenced and are assumed to be 1.
Constraint: DIAG='N' or 'U'.
4:   N – INTEGERInput
On entry: n, the order of the matrix A.
Constraint: N≥0.
5:   KD – INTEGERInput
On entry: kd, the number of superdiagonals of the matrix A if UPLO='U', or the number of subdiagonals if UPLO='L'.
Constraint: KD≥0.
6:   AB LDAB* – COMPLEX (KIND=nag_wp) arrayInput
Note: the second dimension of the array AB must be at least max 1,N.
On entry: the n by n triangular band matrix A.
The matrix is stored in rows 1 to kd+1, more precisely,
  • if UPLO='U', the elements of the upper triangle of A within the band must be stored with element A ij in AB kd+1+i-j j​ for ​max 1,j-kd≤i≤j;
  • if UPLO='L', the elements of the lower triangle of A within the band must be stored with element A ij in AB 1+i-j j​ for ​j≤i≤min n,j+kd.
If DIAG='U', the diagonal elements of A are assumed to be 1, and are not referenced.
7:   LDAB – INTEGERInput
On entry: the first dimension of the array AB as declared in the (sub)program from which F07VUF (ZTBCON) is called.
Constraint: LDAB≥KD+1.
8:   RCOND – REAL (KIND=nag_wp)Output
On exit: an estimate of the reciprocal of the condition number of A. RCOND is set to zero if exact singularity is detected or the estimate underflows. If RCOND is less than machine precision, A is singular to working precision.
9:   WORK 2×N – COMPLEX (KIND=nag_wp) arrayWorkspace
10:   RWORK N – REAL (KIND=nag_wp) arrayWorkspace
11:   INFO – INTEGEROutput
On exit: INFO=0 unless the routine detects an error (see Section 6).

6 Error Indicators and Warnings

INFO<0
If INFO=-i, argument i had an illegal value. An explanatory message is output, and execution of the program is terminated.

7 Accuracy

The computed estimate RCOND is never less than the true value ρ, and in practice is nearly always less than 10 ρ, although examples can be constructed where RCOND is much larger.

8 Parallelism and Performance

F07VUF (ZTBCON) makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

A call to F07VUF (ZTBCON) involves solving a number of systems of linear equations of the form Ax=b or AH x=b; the number is usually 5 and never more than 11. Each solution involves approximately 8 nk real floating-point operations (assuming n≫k) but takes considerably longer than a call to F07VSF (ZTBTRS) with one right-hand side, because extra care is taken to avoid overflow when A is approximately singular.
The real analogue of this routine is F07VGF (DTBCON).

10 Example

This example estimates the condition number in the 1-norm of the matrix A, where
A= -1.94+4.43 i 0.00+0.00 i 0.00+0.00 i 0.00+0.00 i -3.39+3.44 i 4.12-4.27 i 0.00+0.00 i 0.00+0.00 i 1.62+3.68 i -1.84+5.53 i 0.43-2.66 i 0.00+0.00 i 0.00+0.00 i -2.77-1.93 i 1.74-0.04 i 0.44+0.10 i .
Here A is treated as a lower triangular band matrix with two subdiagonals. The true condition number in the 1-norm is 71.51.

10.1 Program Text

Program Text (f07vufe.f90)

10.2 Program Data

Program Data (f07vufe.d)

10.3 Program Results

Program Results (f07vufe.r)

F07 Chapter Contents
F07 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F07VVF (ZTBRFS) : NAG Library, Mark 26

F07 Chapter Contents
F07 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F07VVF (ZTBRFS)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F07VVF (ZTBRFS) returns error bounds for the solution of a complex triangular band system of linear equations with multiple right-hand sides, AX=B, AT X=B or AH X=B.

2 Specification

SUBROUTINE F07VVF ( UPLO, TRANS, DIAG, N, KD, NRHS, AB, LDAB, B, LDB, X, LDX, FERR, BERR, WORK, RWORK, INFO)
INTEGER | N, KD, NRHS, LDAB, LDB, LDX, INFO
REAL (KIND=nag_wp) | FERR(NRHS), BERR(NRHS), RWORK(N)
COMPLEX (KIND=nag_wp) | AB(LDAB,*), B(LDB,*), X(LDX,*), WORK(2*N)
CHARACTER(1) | UPLO, TRANS, DIAG
The routine may be called by its LAPACK name ztbrfs.

3 Description

F07VVF (ZTBRFS) returns the backward errors and estimated bounds on the forward errors for the solution of a complex triangular band system of linear equations with multiple right-hand sides AX=B, AT X=B or AH X=B. The routine handles each right-hand side vector (stored as a column of the matrix B) independently, so we describe the function of F07VVF (ZTBRFS) in terms of a single right-hand side b and solution x.
Given a computed solution x, the routine computes the component-wise backward error β. This is the size of the smallest relative perturbation in each element of A and b such that x is the exact solution of a perturbed system
A+δA x=b+δb δ a ij≤β a ij   and   δ bi≤β bi .
Then the routine estimates a bound for the component-wise forward error in the computed solution, defined by:
maxi xi-x^i/maxi xi
where x^ is the true solution.
For details of the method, see the F07 Chapter Introduction.

4 References

Golub G H and Van Loan C F (1996) Matrix Computations (3rd Edition) Johns Hopkins University Press, Baltimore

5 Arguments

1:   UPLO – CHARACTER(1)Input
On entry: specifies whether A is upper or lower triangular.
UPLO='U'
A is upper triangular.
UPLO='L'
A is lower triangular.
Constraint: UPLO='U' or 'L'.
2:   TRANS – CHARACTER(1)Input
On entry: indicates the form of the equations.
TRANS='N'
The equations are of the form AX=B.
TRANS='T'
The equations are of the form AT X=B.
TRANS='C'
The equations are of the form AH X=B.
Constraint: TRANS='N', 'T' or 'C'.
3:   DIAG – CHARACTER(1)Input
On entry: indicates whether A is a nonunit or unit triangular matrix.
DIAG='N'
A is a nonunit triangular matrix.
DIAG='U'
A is a unit triangular matrix; the diagonal elements are not referenced and are assumed to be 1.
Constraint: DIAG='N' or 'U'.
4:   N – INTEGERInput
On entry: n, the order of the matrix A.
Constraint: N≥0.
5:   KD – INTEGERInput
On entry: kd, the number of superdiagonals of the matrix A if UPLO='U', or the number of subdiagonals if UPLO='L'.
Constraint: KD≥0.
6:   NRHS – INTEGERInput
On entry: r, the number of right-hand sides.
Constraint: NRHS≥0.
7:   AB LDAB* – COMPLEX (KIND=nag_wp) arrayInput
Note: the second dimension of the array AB must be at least max 1,N.
On entry: the n by n triangular band matrix A.
The matrix is stored in rows 1 to kd+1, more precisely,
  • if UPLO='U', the elements of the upper triangle of A within the band must be stored with element A ij in AB kd+1+i-j j​ for ​max 1,j-kd≤i≤j;
  • if UPLO='L', the elements of the lower triangle of A within the band must be stored with element A ij in AB 1+i-j j​ for ​j≤i≤min n,j+kd.
If DIAG='U', the diagonal elements of A are assumed to be 1, and are not referenced.
8:   LDAB – INTEGERInput
On entry: the first dimension of the array AB as declared in the (sub)program from which F07VVF (ZTBRFS) is called.
Constraint: LDAB≥KD+1.
9:   B LDB* – COMPLEX (KIND=nag_wp) arrayInput
Note: the second dimension of the array B must be at least max 1,NRHS.
On entry: the n by r right-hand side matrix B.
10:   LDB – INTEGERInput
On entry: the first dimension of the array B as declared in the (sub)program from which F07VVF (ZTBRFS) is called.
Constraint: LDB≥max 1,N.
11:   X LDX* – COMPLEX (KIND=nag_wp) arrayInput
Note: the second dimension of the array X must be at least max 1,NRHS.
On entry: the n by r solution matrix X, as returned by F07VSF (ZTBTRS).
12:   LDX – INTEGERInput
On entry: the first dimension of the array X as declared in the (sub)program from which F07VVF (ZTBRFS) is called.
Constraint: LDX≥max 1,N.
13:   FERR NRHS – REAL (KIND=nag_wp) arrayOutput
On exit: FERR j contains an estimated error bound for the jth solution vector, that is, the jth column of X, for j=1,2,…,r.
14:   BERR NRHS – REAL (KIND=nag_wp) arrayOutput
On exit: BERR j contains the component-wise backward error bound β for the jth solution vector, that is, the jth column of X, for j=1,2,…,r.
15:   WORK 2×N – COMPLEX (KIND=nag_wp) arrayWorkspace
16:   RWORK N – REAL (KIND=nag_wp) arrayWorkspace
17:   INFO – INTEGEROutput
On exit: INFO=0 unless the routine detects an error (see Section 6).

6 Error Indicators and Warnings

INFO<0
If INFO=-i, argument i had an illegal value. An explanatory message is output, and execution of the program is terminated.

7 Accuracy

The bounds returned in FERR are not rigorous, because they are estimated, not computed exactly; but in practice they almost always overestimate the actual error.

8 Parallelism and Performance

F07VVF (ZTBRFS) is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
F07VVF (ZTBRFS) makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

A call to F07VVF (ZTBRFS), for each right-hand side, involves solving a number of systems of linear equations of the form Ax=b or AH x=b; the number is usually 5 and never more than 11. Each solution involves approximately 8 nk real floating-point operations (assuming n≫k).
The real analogue of this routine is F07VHF (DTBRFS).

10 Example

This example solves the system of equations AX=B and to compute forward and backward error bounds, where
A= -1.94+4.43 i 0.00+0.00 i 0.00+0.00 i 0.00+0.00 i -3.39+3.44 i 4.12-4.27 i 0.00+0.00 i 0.00+0.00 i 1.62+3.68 i -1.84+5.53 i 0.43-2.66 i 0.00+0.00 i 0.00+0.00 i -2.77-1.93 i 1.74-0.04 i 0.44+0.10 i
and
B= -8.86-0 3.88 i -24.09-0 5.27 i -15.57-23.41 i -57.97+0 8.14 i -7.63+22.78 i 19.09-29.51 i -14.74-0 2.40 i 19.17+21.33 i .

10.1 Program Text

Program Text (f07vvfe.f90)

10.2 Program Data

Program Data (f07vvfe.d)

10.3 Program Results

Program Results (f07vvfe.r)

F07 Chapter Contents
F07 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F07WDF (DPFTRF) : NAG Library, Mark 26

F07 Chapter Contents
F07 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F07WDF (DPFTRF)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F07WDF (DPFTRF) computes the Cholesky factorization of a real symmetric positive definite matrix stored in Rectangular Full Packed (RFP) format.

2 Specification

SUBROUTINE F07WDF ( TRANSR, UPLO, N, AR, INFO)
INTEGER | N, INFO
REAL (KIND=nag_wp) | AR(N*(N+1)/2)
CHARACTER(1) | TRANSR, UPLO
The routine may be called by its LAPACK name dpftrf.

3 Description

F07WDF (DPFTRF) forms the Cholesky factorization of a real symmetric positive definite matrix A either as A=UT U if UPLO='U' or A=L LT if UPLO='L', where U is an upper triangular matrix and L is a lower triangular, stored in RFP format. The RFP storage format is described in Section 3.3.3 in the F07 Chapter Introduction.

4 References

Demmel J W (1989) On floating-point errors in Cholesky LAPACK Working Note No. 14 University of Tennessee, Knoxville http://www.netlib.org/lapack/lawnspdf/lawn14.pdf
Gustavson F G, Waśniewski J, Dongarra J J and Langou J (2010) Rectangular full packed format for Cholesky's algorithm: factorization, solution, and inversion ACM Trans. Math. Software 37, 2

5 Arguments

1:   TRANSR – CHARACTER(1)Input
On entry: specifies whether the RFP representation of A is normal or transposed.
TRANSR='N'
The matrix A is stored in normal RFP format.
TRANSR='T'
The matrix A is stored in transposed RFP format.
Constraint: TRANSR='N' or 'T'.
2:   UPLO – CHARACTER(1)Input
On entry: specifies whether the upper or lower triangular part of A is stored.
UPLO='U'
The upper triangular part of A is stored, and A is factorized as UT U, where U is upper triangular.
UPLO='L'
The lower triangular part of A is stored, and A is factorized as L LT, where L is lower triangular.
Constraint: UPLO='U' or 'L'.
3:   N – INTEGERInput
On entry: n, the order of the matrix A.
Constraint: N≥0.
4:   AR N×N+1/2 – REAL (KIND=nag_wp) arrayInput/Output
On entry: the upper or lower triangular part (as specified by UPLO) of the n by n symmetric matrix A, in either normal or transposed RFP format (as specified by TRANSR). The storage format is described in detail in Section 3.3.3 in the F07 Chapter Introduction.
On exit: if INFO=0, the factor U or L from the Cholesky factorization A=UT U or A=L LT, in the same storage format as A.
5:   INFO – INTEGEROutput
On exit: INFO=0 unless the routine detects an error (see Section 6).

6 Error Indicators and Warnings

INFO<0
If INFO=-i, argument i had an illegal value. An explanatory message is output, and execution of the program is terminated.
INFO>0
The leading minor of order value is not positive definite and the factorization could not be completed. Hence A itself is not positive definite. This may indicate an error in forming the matrix A. There is no routine specifically designed to factorize a symmetric matrix stored in RFP format which is not positive definite; the matrix must be treated as a full symmetric matrix, by calling F07MDF (DSYTRF).

7 Accuracy

If UPLO='U', the computed factor U is the exact factor of a perturbed matrix A+E, where
E≤c n ε UTU ,
c n is a modest linear function of n, and ε is the machine precision.
If UPLO='L', a similar statement holds for the computed factor L. It follows that e ij≤c n ε⁢a iia jj.

8 Parallelism and Performance

F07WDF (DPFTRF) is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
F07WDF (DPFTRF) makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The total number of floating-point operations is approximately 13 n 3.
A call to F07WDF (DPFTRF) may be followed by calls to the routines:
  • F07WEF (DPFTRS) to solve AX=B;
  • F07WJF (DPFTRI) to compute the inverse of A.
The complex analogue of this routine is F07WRF (ZPFTRF).

10 Example

This example computes the Cholesky factorization of the matrix A, where
A= 4.16 -3.12 0.56 -0.10 -3.12 5.03 -0.83 1.18 0.56 -0.83 0.76 0.34 -0.10 1.18 0.34 1.18 ,
and is stored using RFP format.

10.1 Program Text

Program Text (f07wdfe.f90)

10.2 Program Data

Program Data (f07wdfe.d)

10.3 Program Results

Program Results (f07wdfe.r)

F07 Chapter Contents
F07 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F07WEF (DPFTRS) : NAG Library, Mark 26

F07 Chapter Contents
F07 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F07WEF (DPFTRS)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F07WEF (DPFTRS) solves a real symmetric positive definite system of linear equations with multiple right-hand sides,
AX=B ,
using the Cholesky factorization computed by F07WDF (DPFTRF) stored in Rectangular Full Packed (RFP) format.

2 Specification

SUBROUTINE F07WEF ( TRANSR, UPLO, N, NRHS, AR, B, LDB, INFO)
INTEGER | N, NRHS, LDB, INFO
REAL (KIND=nag_wp) | AR(N*(N+1)/2), B(LDB,*)
CHARACTER(1) | TRANSR, UPLO
The routine may be called by its LAPACK name dpftrs.

3 Description

F07WEF (DPFTRS) is used to solve a real symmetric positive definite system of linear equations AX=B, the routine must be preceded by a call to F07WDF (DPFTRF) which computes the Cholesky factorization of A, stored in RFP format. The RFP storage format is described in Section 3.3.3 in the F07 Chapter Introduction. The solution X is computed by forward and backward substitution.
If UPLO='U', A=UT U, where U is upper triangular; the solution X is computed by solving UT Y=B and then UX=Y.
If UPLO='L', A=L LT, where L is lower triangular; the solution X is computed by solving LY=B and then LT X=Y.

4 References

Gustavson F G, Waśniewski J, Dongarra J J and Langou J (2010) Rectangular full packed format for Cholesky's algorithm: factorization, solution, and inversion ACM Trans. Math. Software 37, 2

5 Arguments

1:   TRANSR – CHARACTER(1)Input
On entry: specifies whether the RFP representation of A is normal or transposed.
TRANSR='N'
The matrix A is stored in normal RFP format.
TRANSR='T'
The matrix A is stored in transposed RFP format.
Constraint: TRANSR='N' or 'T'.
2:   UPLO – CHARACTER(1)Input
On entry: specifies how A has been factorized.
UPLO='U'
A=UT U, where U is upper triangular.
UPLO='L'
A=L LT, where L is lower triangular.
Constraint: UPLO='U' or 'L'.
3:   N – INTEGERInput
On entry: n, the order of the matrix A.
Constraint: N≥0.
4:   NRHS – INTEGERInput
On entry: r, the number of right-hand sides.
Constraint: NRHS≥0.
5:   AR N×N+1/2 – REAL (KIND=nag_wp) arrayInput
On entry: the Cholesky factorization of A stored in RFP format, as returned by F07WDF (DPFTRF).
6:   B LDB* – REAL (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array B must be at least max 1,NRHS.
On entry: the n by r right-hand side matrix B.
On exit: the n by r solution matrix X.
7:   LDB – INTEGERInput
On entry: the first dimension of the array B as declared in the (sub)program from which F07WEF (DPFTRS) is called.
Constraint: LDB≥max 1,N.
8:   INFO – INTEGEROutput
On exit: INFO=0 unless the routine detects an error (see Section 6).

6 Error Indicators and Warnings

INFO<0
If INFO=-i, argument i had an illegal value. An explanatory message is output, and execution of the program is terminated.

7 Accuracy

For each right-hand side vector b, the computed solution x is the exact solution of a perturbed system of equations A+E x=b, where
  • if UPLO='U', E≤c n ε UTU;
  • if UPLO='L', E≤c n ε LLT,
c n is a modest linear function of n, and ε is the machine precision.
If x^ is the true solution, then the computed solution x satisfies a forward error bound of the form
x-x^∞ x∞ ≤c n cond A,x ε
where cond A,x=A-1Ax∞/x∞≤cond A=A-1A∞≤κ∞A and κ∞A is the condition number when using the ∞-norm.
Note that cond A,x can be much smaller than cond A.

8 Parallelism and Performance

F07WEF (DPFTRS) makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The total number of floating-point operations is approximately 2 n 2 r.
The complex analogue of this routine is F07WSF (ZPFTRS).

10 Example

This example solves the system of equations AX=B, where
A= 4.16 -3.12 0.56 -0.10 -3.12 5.03 -0.83 1.18 0.56 -0.83 0.76 0.34 -0.10 1.18 0.34 1.18   and   B= 8.70 8.30 -13.35 2.13 1.89 1.61 -4.14 5.00 .
Here A is symmetric positive definite, stored in RFP format, and must first be factorized by F07WDF (DPFTRF).

10.1 Program Text

Program Text (f07wefe.f90)

10.2 Program Data

Program Data (f07wefe.d)

10.3 Program Results

Program Results (f07wefe.r)

F07 Chapter Contents
F07 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F07WJF (DPFTRI) : NAG Library, Mark 26

F07 Chapter Contents
F07 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F07WJF (DPFTRI)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F07WJF (DPFTRI) computes the inverse of a real symmetric positive definite matrix using the Cholesky factorization computed by F07WDF (DPFTRF) stored in Rectangular Full Packed (RFP) format.

2 Specification

SUBROUTINE F07WJF ( TRANSR, UPLO, N, AR, INFO)
INTEGER | N, INFO
REAL (KIND=nag_wp) | AR(N*(N+1)/2)
CHARACTER(1) | TRANSR, UPLO
The routine may be called by its LAPACK name dpftri.

3 Description

F07WJF (DPFTRI) is used to compute the inverse of a real symmetric positive definite matrix A, stored in RFP format. The RFP storage format is described in Section 3.3.3 in the F07 Chapter Introduction. The routine must be preceded by a call to F07WDF (DPFTRF), which computes the Cholesky factorization of A.
If UPLO='U', A=UT U and A-1 is computed by first inverting U and then forming U-1 U-T.
If UPLO='L', A=L LT and A-1 is computed by first inverting L and then forming L-T L-1.

4 References

Du Croz J J and Higham N J (1992) Stability of methods for matrix inversion IMA J. Numer. Anal. 12 1–19
Gustavson F G, Waśniewski J, Dongarra J J and Langou J (2010) Rectangular full packed format for Cholesky's algorithm: factorization, solution, and inversion ACM Trans. Math. Software 37, 2

5 Arguments

1:   TRANSR – CHARACTER(1)Input
On entry: specifies whether the RFP representation of A is normal or transposed.
TRANSR='N'
The matrix A is stored in normal RFP format.
TRANSR='T'
The matrix A is stored in transposed RFP format.
Constraint: TRANSR='N' or 'T'.
2:   UPLO – CHARACTER(1)Input
On entry: specifies how A has been factorized.
UPLO='U'
A=UT U, where U is upper triangular.
UPLO='L'
A=L LT, where L is lower triangular.
Constraint: UPLO='U' or 'L'.
3:   N – INTEGERInput
On entry: n, the order of the matrix A.
Constraint: N≥0.
4:   AR N×N+1/2 – REAL (KIND=nag_wp) arrayInput/Output
On entry: the Cholesky factorization of A stored in RFP format, as returned by F07WDF (DPFTRF).
On exit: the factorization is overwritten by the n by n matrix A-1 stored in RFP format.
5:   INFO – INTEGEROutput
On exit: INFO=0 unless the routine detects an error (see Section 6).

6 Error Indicators and Warnings

INFO<0
If INFO=-i, argument i had an illegal value. An explanatory message is output, and execution of the program is terminated.
INFO>0
The leading minor of order value is not positive definite and the factorization could not be completed. Hence A itself is not positive definite. This may indicate an error in forming the matrix A. There is no routine specifically designed to invert a symmetric matrix stored in RFP format which is not positive definite; the matrix must be treated as a full symmetric matrix, by calling F07MJF (DSYTRI).

7 Accuracy

The computed inverse X satisfies
XA-I 2≤c n ε κ 2 A   and   AX-I 2≤c n ε κ 2 A ,
where c n is a modest function of n, ε is the machine precision and κ 2 A is the condition number of A defined by
κ 2 A=A 2A-1 2 .

8 Parallelism and Performance

F07WJF (DPFTRI) makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The total number of floating-point operations is approximately 23 n 3.
The complex analogue of this routine is F07WWF (ZPFTRI).

10 Example

This example computes the inverse of the matrix A, where
A= 4.16 -3.12 0.56 -0.10 -3.12 5.03 -0.83 1.18 0.56 -0.83 0.76 0.34 -0.10 1.18 0.34 1.18 .
Here A is symmetric positive definite, stored in RFP format, and must first be factorized by F07WDF (DPFTRF).

10.1 Program Text

Program Text (f07wjfe.f90)

10.2 Program Data

Program Data (f07wjfe.d)

10.3 Program Results

Program Results (f07wjfe.r)

F07 Chapter Contents
F07 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F07WKF (DTFTRI) : NAG Library, Mark 26

F07 Chapter Contents
F07 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F07WKF (DTFTRI)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F07WKF (DTFTRI) computes the inverse of a real triangular matrix stored in Rectangular Full Packed (RFP) format.

2 Specification

SUBROUTINE F07WKF ( TRANSR, UPLO, DIAG, N, AR, INFO)
INTEGER | N, INFO
REAL (KIND=nag_wp) | AR(N*(N+1)/2)
CHARACTER(1) | TRANSR, UPLO, DIAG
The routine may be called by its LAPACK name dtftri.

3 Description

F07WKF (DTFTRI) forms the inverse of a real triangular matrix A, stored using RFP format. The RFP storage format is described in Section 3.3.3 in the F07 Chapter Introduction. Note that the inverse of an upper (lower) triangular matrix is also upper (lower) triangular.

4 References

Du Croz J J and Higham N J (1992) Stability of methods for matrix inversion IMA J. Numer. Anal. 12 1–19
Gustavson F G, Waśniewski J, Dongarra J J and Langou J (2010) Rectangular full packed format for Cholesky's algorithm: factorization, solution, and inversion ACM Trans. Math. Software 37, 2

5 Arguments

1:   TRANSR – CHARACTER(1)Input
On entry: specifies whether the RFP representation of A is normal or transposed.
TRANSR='N'
The matrix A is stored in normal RFP format.
TRANSR='T'
The matrix A is stored in transposed RFP format.
Constraint: TRANSR='N' or 'T'.
2:   UPLO – CHARACTER(1)Input
On entry: specifies whether A is upper or lower triangular.
UPLO='U'
A is upper triangular.
UPLO='L'
A is lower triangular.
Constraint: UPLO='U' or 'L'.
3:   DIAG – CHARACTER(1)Input
On entry: indicates whether A is a nonunit or unit triangular matrix.
DIAG='N'
A is a nonunit triangular matrix.
DIAG='U'
A is a unit triangular matrix; the diagonal elements are not referenced and are assumed to be 1.
Constraint: DIAG='N' or 'U'.
4:   N – INTEGERInput
On entry: n, the order of the matrix A.
Constraint: N≥0.
5:   AR N×N+1/2 – REAL (KIND=nag_wp) arrayInput/Output
On entry: the upper or lower triangular part (as specified by UPLO) of the n by n symmetric matrix A, in either normal or transposed RFP format (as specified by TRANSR). The storage format is described in detail in Section 3.3.3 in the F07 Chapter Introduction.
On exit: A is overwritten by A-1, in the same storage format as A.
6:   INFO – INTEGEROutput
On exit: INFO=0 unless the routine detects an error (see Section 6).

6 Error Indicators and Warnings

INFO<0
If INFO=-i, argument i had an illegal value. An explanatory message is output, and execution of the program is terminated.
INFO>0
Diagonal element value of A is exactly zero. A is singular its inverse cannot be computed.

7 Accuracy

The computed inverse X satisfies
XA-I≤c n ε XA ,
where c n is a modest linear function of n, and ε is the machine precision.
Note that a similar bound for AX-I cannot be guaranteed, although it is almost always satisfied.
The computed inverse satisfies the forward error bound
X-A-1≤c n ε A-1AX .
See Du Croz and Higham (1992).

8 Parallelism and Performance

F07WKF (DTFTRI) makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The total number of floating-point operations is approximately 13 n 3.
The complex analogue of this routine is F07WXF (ZTFTRI).

10 Example

This example computes the inverse of the matrix A, where
A= 4.30 0.00 0.00 0.00 -3.96 -4.87 0.00 0.00 0.40 0.31 -8.02 0.00 -0.27 0.07 -5.95 0.12
and is stored using RFP format.

10.1 Program Text

Program Text (f07wkfe.f90)

10.2 Program Data

Program Data (f07wkfe.d)

10.3 Program Results

Program Results (f07wkfe.r)

F07 Chapter Contents
F07 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F07WRF (ZPFTRF) : NAG Library, Mark 26

F07 Chapter Contents
F07 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F07WRF (ZPFTRF)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F07WRF (ZPFTRF) computes the Cholesky factorization of a complex Hermitian positive definite matrix stored in Rectangular Full Packed (RFP) format.

2 Specification

SUBROUTINE F07WRF ( TRANSR, UPLO, N, AR, INFO)
INTEGER | N, INFO
COMPLEX (KIND=nag_wp) | AR(N*(N+1)/2)
CHARACTER(1) | TRANSR, UPLO
The routine may be called by its LAPACK name zpftrf.

3 Description

F07WRF (ZPFTRF) forms the Cholesky factorization of a complex Hermitian positive definite matrix A either as A=UH U if UPLO='U' or A=L LH if UPLO='L', where U is an upper triangular matrix and L is a lower triangular, stored in RFP format. The RFP storage format is described in Section 3.3.3 in the F07 Chapter Introduction.

4 References

Demmel J W (1989) On floating-point errors in Cholesky LAPACK Working Note No. 14 University of Tennessee, Knoxville http://www.netlib.org/lapack/lawnspdf/lawn14.pdf
Gustavson F G, Waśniewski J, Dongarra J J and Langou J (2010) Rectangular full packed format for Cholesky's algorithm: factorization, solution, and inversion ACM Trans. Math. Software 37, 2

5 Arguments

1:   TRANSR – CHARACTER(1)Input
On entry: specifies whether the normal RFP representation of A or its conjugate transpose is stored.
TRANSR='N'
The matrix A is stored in normal RFP format.
TRANSR='C'
The conjugate transpose of the RFP representation of the matrix A is stored.
Constraint: TRANSR='N' or 'C'.
2:   UPLO – CHARACTER(1)Input
On entry: specifies whether the upper or lower triangular part of A is stored.
UPLO='U'
The upper triangular part of A is stored, and A is factorized as UH U, where U is upper triangular.
UPLO='L'
The lower triangular part of A is stored, and A is factorized as L LH, where L is lower triangular.
Constraint: UPLO='U' or 'L'.
3:   N – INTEGERInput
On entry: n, the order of the matrix A.
Constraint: N≥0.
4:   AR N×N+1/2 – COMPLEX (KIND=nag_wp) arrayInput/Output
On entry: the upper or lower triangular part (as specified by UPLO) of the n by n Hermitian matrix A, in either normal or transposed RFP format (as specified by TRANSR). The storage format is described in detail in Section 3.3.3 in the F07 Chapter Introduction.
On exit: if INFO=0, the factor U or L from the Cholesky factorization A=UH U or A=L LH, in the same storage format as A.
5:   INFO – INTEGEROutput
On exit: INFO=0 unless the routine detects an error (see Section 6).

6 Error Indicators and Warnings

INFO<0
If INFO=-i, argument i had an illegal value. An explanatory message is output, and execution of the program is terminated.
INFO>0
The leading minor of order value is not positive definite and the factorization could not be completed. Hence A itself is not positive definite. This may indicate an error in forming the matrix A. There is no routine specifically designed to factorize a Hermitian matrix stored in RFP format which is not positive definite; the matrix must be treated as a full Hermitian matrix, by calling F07MRF (ZHETRF).

7 Accuracy

If UPLO='U', the computed factor U is the exact factor of a perturbed matrix A+E, where
E≤c n ε UHU ,
c n is a modest linear function of n, and ε is the machine precision.
If UPLO='L', a similar statement holds for the computed factor L. It follows that e ij≤c n ε⁢a iia jj.

8 Parallelism and Performance

F07WRF (ZPFTRF) is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
F07WRF (ZPFTRF) makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The total number of real floating-point operations is approximately 43 n 3.
A call to F07WRF (ZPFTRF) may be followed by calls to the routines:
  • F07WSF (ZPFTRS) to solve AX=B;
  • F07WWF (ZPFTRI) to compute the inverse of A.
The real analogue of this routine is F07WDF (DPFTRF).

10 Example

This example computes the Cholesky factorization of the matrix A, where
A= 3.23+0.00 i 1.51-1.92 i 1.90+0.84 i 0.42+2.50 i 1.51+1.92 i 3.58+0.00 i -0.23+1.11 i -1.18+1.37 i 1.90-0.84 i -0.23-1.11 i 4.09+0.00 i 2.33-0.14 i 0.42-2.50 i -1.18-1.37 i 2.33+0.14 i 4.29+0.00 i .
and is stored using RFP format.

10.1 Program Text

Program Text (f07wrfe.f90)

10.2 Program Data

Program Data (f07wrfe.d)

10.3 Program Results

Program Results (f07wrfe.r)

F07 Chapter Contents
F07 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F07WSF (ZPFTRS) : NAG Library, Mark 26

F07 Chapter Contents
F07 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F07WSF (ZPFTRS)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F07WSF (ZPFTRS) solves a complex Hermitian positive definite system of linear equations with multiple right-hand sides,
AX=B ,
using the Cholesky factorization computed by F07WRF (ZPFTRF) stored in Rectangular Full Packed (RFP) format.

2 Specification

SUBROUTINE F07WSF ( TRANSR, UPLO, N, NRHS, AR, B, LDB, INFO)
INTEGER | N, NRHS, LDB, INFO
COMPLEX (KIND=nag_wp) | AR(N*(N+1)/2), B(LDB,*)
CHARACTER(1) | TRANSR, UPLO
The routine may be called by its LAPACK name zpftrs.

3 Description

F07WSF (ZPFTRS) is used to solve a complex Hermitian positive definite system of linear equations AX=B, the routine must be preceded by a call to F07WRF (ZPFTRF) which computes the Cholesky factorization of A, stored in RFP format. The RFP storage format is described in Section 3.3.3 in the F07 Chapter Introduction. The solution X is computed by forward and backward substitution.
If UPLO='U', A=UH U, where U is upper triangular; the solution X is computed by solving UH Y=B and then UX=Y.
If UPLO='L', A=L LH, where L is lower triangular; the solution X is computed by solving LY=B and then LH X=Y.

4 References

Gustavson F G, Waśniewski J, Dongarra J J and Langou J (2010) Rectangular full packed format for Cholesky's algorithm: factorization, solution, and inversion ACM Trans. Math. Software 37, 2

5 Arguments

1:   TRANSR – CHARACTER(1)Input
On entry: specifies whether the normal RFP representation of A or its conjugate transpose is stored.
TRANSR='N'
The matrix A is stored in normal RFP format.
TRANSR='C'
The conjugate transpose of the RFP representation of the matrix A is stored.
Constraint: TRANSR='N' or 'C'.
2:   UPLO – CHARACTER(1)Input
On entry: specifies how A has been factorized.
UPLO='U'
A=UH U, where U is upper triangular.
UPLO='L'
A=L LH, where L is lower triangular.
Constraint: UPLO='U' or 'L'.
3:   N – INTEGERInput
On entry: n, the order of the matrix A.
Constraint: N≥0.
4:   NRHS – INTEGERInput
On entry: r, the number of right-hand sides.
Constraint: NRHS≥0.
5:   AR N×N+1/2 – COMPLEX (KIND=nag_wp) arrayInput
On entry: the Cholesky factorization of A stored in RFP format, as returned by F07WRF (ZPFTRF).
6:   B LDB* – COMPLEX (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array B must be at least max 1,NRHS.
On entry: the n by r right-hand side matrix B.
On exit: the n by r solution matrix X.
7:   LDB – INTEGERInput
On entry: the first dimension of the array B as declared in the (sub)program from which F07WSF (ZPFTRS) is called.
Constraint: LDB≥max 1,N.
8:   INFO – INTEGEROutput
On exit: INFO=0 unless the routine detects an error (see Section 6).

6 Error Indicators and Warnings

INFO<0
If INFO=-i, argument i had an illegal value. An explanatory message is output, and execution of the program is terminated.

7 Accuracy

For each right-hand side vector b, the computed solution x is the exact solution of a perturbed system of equations A+E x=b, where
  • if UPLO='U', E≤c n ε UHU;
  • if UPLO='L', E≤c n ε LLH,
c n is a modest linear function of n, and ε is the machine precision.
If x^ is the true solution, then the computed solution x satisfies a forward error bound of the form
x-x^∞ x∞ ≤c n cond A,x ε
where cond A,x=A-1Ax∞/x∞≤cond A=A-1A∞≤κ∞A and κ∞A is the condition number when using the ∞-norm.
Note that cond A,x can be much smaller than cond A.

8 Parallelism and Performance

F07WSF (ZPFTRS) makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The total number of real floating-point operations is approximately 8 n 2 r.
The real analogue of this routine is F07WEF (DPFTRS).

10 Example

This example solves the system of equations AX=B, where
A= 3.23+0.00 i 1.51-1.92 i 1.90+0.84 i 0.42+2.50 i 1.51+1.92 i 3.58+0.00 i -0.23+1.11 i -1.18+1.37 i 1.90-0.84 i -0.23-1.11 i 4.09+0.00 i 2.33-0.14 i 0.42-2.50 i -1.18-1.37 i 2.33+0.14 i 4.29+0.00 i
and
B= 3.93-0 6.14 i 1.48+0 6.58 i 6.17+0 9.42 i 4.65-0 4.75 i -7.17-21.83 i -4.91+0 2.29 i 1.99-14.38 i 7.64-10.79 i .
Here A is Hermitian positive definite, stored in RFP format, and must first be factorized by F07WRF (ZPFTRF).

10.1 Program Text

Program Text (f07wsfe.f90)

10.2 Program Data

Program Data (f07wsfe.d)

10.3 Program Results

Program Results (f07wsfe.r)

F07 Chapter Contents
F07 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F07WWF (ZPFTRI) : NAG Library, Mark 26

F07 Chapter Contents
F07 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F07WWF (ZPFTRI)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F07WWF (ZPFTRI) computes the inverse of a complex Hermitian positive definite matrix using the Cholesky factorization computed by F07WRF (ZPFTRF) stored in Rectangular Full Packed (RFP) format.

2 Specification

SUBROUTINE F07WWF ( TRANSR, UPLO, N, AR, INFO)
INTEGER | N, INFO
COMPLEX (KIND=nag_wp) | AR(N*(N+1)/2)
CHARACTER(1) | TRANSR, UPLO
The routine may be called by its LAPACK name zpftri.

3 Description

F07WWF (ZPFTRI) is used to compute the inverse of a complex Hermitian positive definite matrix A, stored in RFP format. The RFP storage format is described in Section 3.3.3 in the F07 Chapter Introduction. The routine must be preceded by a call to F07WRF (ZPFTRF), which computes the Cholesky factorization of A.
If UPLO='U', A=UH U and A-1 is computed by first inverting U and then forming U-1 U-H.
If UPLO='L', A=L LH and A-1 is computed by first inverting L and then forming L-H L-1.

4 References

Du Croz J J and Higham N J (1992) Stability of methods for matrix inversion IMA J. Numer. Anal. 12 1–19
Gustavson F G, Waśniewski J, Dongarra J J and Langou J (2010) Rectangular full packed format for Cholesky's algorithm: factorization, solution, and inversion ACM Trans. Math. Software 37, 2

5 Arguments

1:   TRANSR – CHARACTER(1)Input
On entry: specifies whether the normal RFP representation of A or its conjugate transpose is stored.
TRANSR='N'
The matrix A is stored in normal RFP format.
TRANSR='C'
The conjugate transpose of the RFP representation of the matrix A is stored.
Constraint: TRANSR='N' or 'C'.
2:   UPLO – CHARACTER(1)Input
On entry: specifies how A has been factorized.
UPLO='U'
A=UH U, where U is upper triangular.
UPLO='L'
A=L LH, where L is lower triangular.
Constraint: UPLO='U' or 'L'.
3:   N – INTEGERInput
On entry: n, the order of the matrix A.
Constraint: N≥0.
4:   AR N×N+1/2 – COMPLEX (KIND=nag_wp) arrayInput/Output
On entry: the Cholesky factorization of A stored in RFP format, as returned by F07WRF (ZPFTRF).
On exit: the factorization is overwritten by the n by n matrix A-1 stored in RFP format.
5:   INFO – INTEGEROutput
On exit: INFO=0 unless the routine detects an error (see Section 6).

6 Error Indicators and Warnings

INFO<0
If INFO=-i, argument i had an illegal value. An explanatory message is output, and execution of the program is terminated.
INFO>0
The leading minor of order value is not positive definite and the factorization could not be completed. Hence A itself is not positive definite. This may indicate an error in forming the matrix A. There is no routine specifically designed to invert a Hermitian matrix stored in RFP format which is not positive definite; the matrix must be treated as a full Hermitian matrix, by calling F07MWF (ZHETRI).

7 Accuracy

The computed inverse X satisfies
XA-I 2≤c n ε κ 2 A   and   AX-I 2≤c n ε κ 2 A ,
where c n is a modest function of n, ε is the machine precision and κ 2 A is the condition number of A defined by
κ 2 A=A 2A-1 2 .

8 Parallelism and Performance

F07WWF (ZPFTRI) makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The total number of real floating-point operations is approximately 83 n 3.
The real analogue of this routine is F07WJF (DPFTRI).

10 Example

This example computes the inverse of the matrix A, where
A= 3.23+0.00 i 1.51-1.92 i 1.90+0.84 i 0.42+2.50 i 1.51+1.92 i 3.58+0.00 i -0.23+1.11 i -1.18+1.37 i 1.90-0.84 i -0.23-1.11 i 4.09+0.00 i 2.33-0.14 i 0.42-2.50 i -1.18-1.37 i 2.33+0.14 i 4.29+0.00 i .
Here A is Hermitian positive definite, stored in RFP format, and must first be factorized by F07WRF (ZPFTRF).

10.1 Program Text

Program Text (f07wwfe.f90)

10.2 Program Data

Program Data (f07wwfe.d)

10.3 Program Results

Program Results (f07wwfe.r)

F07 Chapter Contents
F07 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F07WXF (ZTFTRI) : NAG Library, Mark 26

F07 Chapter Contents
F07 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F07WXF (ZTFTRI)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F07WXF (ZTFTRI) computes the inverse of a complex triangular matrix stored in Rectangular Full Packed (RFP) format.

2 Specification

SUBROUTINE F07WXF ( TRANSR, UPLO, DIAG, N, AR, INFO)
INTEGER | N, INFO
COMPLEX (KIND=nag_wp) | AR(N*(N+1)/2)
CHARACTER(1) | TRANSR, UPLO, DIAG
The routine may be called by its LAPACK name ztftri.

3 Description

F07WXF (ZTFTRI) forms the inverse of a complex triangular matrix A, stored using RFP format. The RFP storage format is described in Section 3.3.3 in the F07 Chapter Introduction. Note that the inverse of an upper (lower) triangular matrix is also upper (lower) triangular.

4 References

Du Croz J J and Higham N J (1992) Stability of methods for matrix inversion IMA J. Numer. Anal. 12 1–19
Gustavson F G, Waśniewski J, Dongarra J J and Langou J (2010) Rectangular full packed format for Cholesky's algorithm: factorization, solution, and inversion ACM Trans. Math. Software 37, 2

5 Arguments

1:   TRANSR – CHARACTER(1)Input
On entry: specifies whether the normal RFP representation of A or its conjugate transpose is stored.
TRANSR='N'
The matrix A is stored in normal RFP format.
TRANSR='C'
The conjugate transpose of the RFP representation of the matrix A is stored.
Constraint: TRANSR='N' or 'C'.
2:   UPLO – CHARACTER(1)Input
On entry: specifies whether A is upper or lower triangular.
UPLO='U'
A is upper triangular.
UPLO='L'
A is lower triangular.
Constraint: UPLO='U' or 'L'.
3:   DIAG – CHARACTER(1)Input
On entry: indicates whether A is a nonunit or unit triangular matrix.
DIAG='N'
A is a nonunit triangular matrix.
DIAG='U'
A is a unit triangular matrix; the diagonal elements are not referenced and are assumed to be 1.
Constraint: DIAG='N' or 'U'.
4:   N – INTEGERInput
On entry: n, the order of the matrix A.
Constraint: N≥0.
5:   AR N×N+1/2 – COMPLEX (KIND=nag_wp) arrayInput/Output
On entry: the upper or lower triangular part (as specified by UPLO) of the n by n Hermitian matrix A, in either normal or transposed RFP format (as specified by TRANSR). The storage format is described in detail in Section 3.3.3 in the F07 Chapter Introduction.
On exit: A is overwritten by A-1, in the same storage format as A.
6:   INFO – INTEGEROutput
On exit: INFO=0 unless the routine detects an error (see Section 6).

6 Error Indicators and Warnings

INFO<0
If INFO=-i, argument i had an illegal value. An explanatory message is output, and execution of the program is terminated.
INFO>0
Diagonal element value of A is exactly zero. A is singular its inverse cannot be computed.

7 Accuracy

The computed inverse X satisfies
XA-I≤c n ε XA ,
where c n is a modest linear function of n, and ε is the machine precision.
Note that a similar bound for AX-I cannot be guaranteed, although it is almost always satisfied.
The computed inverse satisfies the forward error bound
X-A-1≤c n ε A-1AX .
See Du Croz and Higham (1992).

8 Parallelism and Performance

F07WXF (ZTFTRI) makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The total number of real floating-point operations is approximately 43 n 3.
The real analogue of this routine is F07WKF (DTFTRI).

10 Example

This example computes the inverse of the matrix A, where
A= 4.78+4.56 i 0.00+0.00 i 0.00+0.00 i 0.00+0.00 i 2.00-0.30 i -4.11+1.25 i 0.00+0.00 i 0.00+0.00 i 2.89-1.34 i 2.36-4.25 i 4.15+0.80 i 0.00+0.00 i -1.89+1.15 i 0.04-3.69 i -0.02+0.46 i 0.33-0.26 i
and is stored using RFP format.

10.1 Program Text

Program Text (f07wxfe.f90)

10.2 Program Data

Program Data (f07wxfe.d)

10.3 Program Results

Program Results (f07wxfe.r)

F07 Chapter Contents
F07 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F08AAF (DGELS) : NAG Library, Mark 26

F08 Chapter Contents
F08 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F08AAF (DGELS)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F08AAF (DGELS) solves linear least squares problems of the form
minx b-Ax 2   or   minx b-AT x 2 ,
where A is an m by n real matrix of full rank, using a QR or LQ factorization of A.

2 Specification

SUBROUTINE F08AAF ( TRANS, M, N, NRHS, A, LDA, B, LDB, WORK, LWORK, INFO)
INTEGER | M, N, NRHS, LDA, LDB, LWORK, INFO
REAL (KIND=nag_wp) | A(LDA,*), B(LDB,*), WORK(max(1,LWORK))
CHARACTER(1) | TRANS
The routine may be called by its LAPACK name dgels.

3 Description

The following options are provided:
1. If TRANS='N' and m≥n: find the least squares solution of an overdetermined system, i.e., solve the least squares problem
minx b-Ax 2 .
2. | If TRANS='N' and m<n: find the minimum norm solution of an underdetermined system Ax=b.
3. | If TRANS='T' and m≥n: find the minimum norm solution of an undetermined system AT x=b.
4. If TRANS='T' and m<n: find the least squares solution of an overdetermined system, i.e., solve the least squares problem
minx b-AT x 2 .
Several right-hand side vectors b and solution vectors x can be handled in a single call; they are stored as the columns of the m by r right-hand side matrix B and the n by r solution matrix X.

4 References

Anderson E, Bai Z, Bischof C, Blackford S, Demmel J, Dongarra J J, Du Croz J J, Greenbaum A, Hammarling S, McKenney A and Sorensen D (1999) LAPACK Users' Guide (3rd Edition) SIAM, Philadelphia http://www.netlib.org/lapack/lug
Golub G H and Van Loan C F (1996) Matrix Computations (3rd Edition) Johns Hopkins University Press, Baltimore

5 Arguments

1:   TRANS – CHARACTER(1)Input
On entry: if TRANS='N', the linear system involves A.
If TRANS='T', the linear system involves AT.
Constraint: TRANS='N' or 'T'.
2:   M – INTEGERInput
On entry: m, the number of rows of the matrix A.
Constraint: M≥0.
3:   N – INTEGERInput
On entry: n, the number of columns of the matrix A.
Constraint: N≥0.
4:   NRHS – INTEGERInput
On entry: r, the number of right-hand sides, i.e., the number of columns of the matrices B and X.
Constraint: NRHS≥0.
5:   A LDA* – REAL (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array A must be at least max 1,N.
On entry: the m by n matrix A.
On exit: if M≥N, A is overwritten by details of its QR factorization, as returned by F08AEF (DGEQRF).
If M<N, A is overwritten by details of its LQ factorization, as returned by F08AHF (DGELQF).
6:   LDA – INTEGERInput
On entry: the first dimension of the array A as declared in the (sub)program from which F08AAF (DGELS) is called.
Constraint: LDA≥max 1,M.
7:   B LDB* – REAL (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array B must be at least max 1,NRHS.
On entry: the matrix B of right-hand side vectors, stored in columns; B is m by r if TRANS='N', or n by r if TRANS='T'.
On exit: B is overwritten by the solution vectors, x, stored in columns:
  • if TRANS='N' and m≥n, or TRANS='T' and m<n, elements 1 to min m,n in each column of B contain the least squares solution vectors; the residual sum of squares for the solution is given by the sum of squares of the modulus of elements min m,n+1 to max m,n in that column;
  • otherwise, elements 1 to max m,n in each column of B contain the minimum norm solution vectors.
8:   LDB – INTEGERInput
On entry: the first dimension of the array B as declared in the (sub)program from which F08AAF (DGELS) is called.
Constraint: LDB≥max 1,M,N.
9:   WORK max 1,LWORK – REAL (KIND=nag_wp) arrayWorkspace
On exit: if INFO=0, WORK 1 contains the minimum value of LWORK required for optimal performance.
10:   LWORK – INTEGERInput
On entry: the dimension of the array WORK as declared in the (sub)program from which F08AAF (DGELS) is called.
If LWORK=-1, a workspace query is assumed; the routine only calculates the optimal size of the WORK array, returns this value as the first entry of the WORK array, and no error message related to LWORK is issued.
Suggested value: for optimal performance, LWORK≥ min M,N + max 1,M,N,NRHS × nb , where nb is the optimal block size.
Constraint: LWORK≥min M,N+max 1,M,N,NRHS or LWORK=-1.
11:   INFO – INTEGEROutput
On exit: INFO=0 unless the routine detects an error (see Section 6).

6 Error Indicators and Warnings

INFO<0
If INFO=-i, argument i had an illegal value. An explanatory message is output, and execution of the program is terminated.
INFO>0
If INFO=i, diagonal element i of the triangular factor of A is zero, so that A does not have full rank; the least squares solution could not be computed.

7 Accuracy

See Section 4.5 of Anderson et al. (1999) for details of error bounds.

8 Parallelism and Performance

F08AAF (DGELS) is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
F08AAF (DGELS) makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The total number of floating-point operations required to factorize A is approximately 23 n 2 3 m-n if m≥n and 23 m 2 3 n-m otherwise. Following the factorization the solution for a single vector x requires O min m 2,n 2 operations.
The complex analogue of this routine is F08ANF (ZGELS).

10 Example

This example solves the linear least squares problem
minx b-Ax 2 ,
where
A = -0.57 -1.28 -0.39 0.25 -1.93 1.08 -0.31 -2.14 2.30 0.24 0.40 -0.35 -1.93 0.64 -0.66 0.08 0.15 0.30 0.15 -2.13 -0.02 1.03 -1.43 0.50   and   b= -2.67 -0.55 3.34 -0.77 0.48 4.10 .
The square root of the residual sum of squares is also output.
Note that the block size (NB) of 64 assumed in this example is not realistic for such a small problem, but should be suitable for large problems.

10.1 Program Text

Program Text (f08aafe.f90)

10.2 Program Data

Program Data (f08aafe.d)

10.3 Program Results

Program Results (f08aafe.r)

F08 Chapter Contents
F08 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F08ABF (DGEQRT) : NAG Library, Mark 26

F08 Chapter Contents
F08 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F08ABF (DGEQRT)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F08ABF (DGEQRT) recursively computes, with explicit blocking, the QR factorization of a real m by n matrix.

2 Specification

SUBROUTINE F08ABF ( M, N, NB, A, LDA, T, LDT, WORK, INFO)
INTEGER | M, N, NB, LDA, LDT, INFO
REAL (KIND=nag_wp) | A(LDA,*), T(LDT,*), WORK(NB*N)
The routine may be called by its LAPACK name dgeqrt.

3 Description

F08ABF (DGEQRT) forms the QR factorization of an arbitrary rectangular real m by n matrix. No pivoting is performed.
It differs from F08AEF (DGEQRF) in that it: requires an explicit block size; stores reflector factors that are upper triangular matrices of the chosen block size (rather than scalars); and recursively computes the QR factorization based on the algorithm of Elmroth and Gustavson (2000).
If m≥n, the factorization is given by:
A = Q R 0 ,
where R is an n by n upper triangular matrix and Q is an m by m orthogonal matrix. It is sometimes more convenient to write the factorization as
A = Q 1 Q 2 R 0 ,
which reduces to
A = Q 1 R ,
where Q 1 consists of the first n columns of Q, and Q 2 the remaining m-n columns.
If m<n, R is upper trapezoidal, and the factorization can be written
A = Q R 1 R 2 ,
where R 1 is upper triangular and R 2 is rectangular.
The matrix Q is not formed explicitly but is represented as a product of min m,n elementary reflectors (see the F08 Chapter Introduction for details). Routines are provided to work with Q in this representation (see Section 9).
Note also that for any k<n, the information returned represents a QR factorization of the first k columns of the original matrix A.

4 References

Elmroth E and Gustavson F (2000) Applying Recursion to Serial and Parallel QR Factorization Leads to Better Performance IBM Journal of Research and Development. (Volume 44) 4 605–624
Golub G H and Van Loan C F (2012) Matrix Computations (4th Edition) Johns Hopkins University Press, Baltimore

5 Arguments

1:   M – INTEGERInput
On entry: m, the number of rows of the matrix A.
Constraint: M≥0.
2:   N – INTEGERInput
On entry: n, the number of columns of the matrix A.
Constraint: N≥0.
3:   NB – INTEGERInput
On entry: the explicitly chosen block size to be used in computing the QR factorization. See Section 9 for details.
Constraints:
  • NB≥1;
  • if min M,N>0, NB≤min M,N.
4:   A LDA* – REAL (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array A must be at least max 1,N.
On entry: the m by n matrix A.
On exit: if m≥n, the elements below the diagonal are overwritten by details of the orthogonal matrix Q and the upper triangle is overwritten by the corresponding elements of the n by n upper triangular matrix R.
If m<n, the strictly lower triangular part is overwritten by details of the orthogonal matrix Q and the remaining elements are overwritten by the corresponding elements of the m by n upper trapezoidal matrix R.
5:   LDA – INTEGERInput
On entry: the first dimension of the array A as declared in the (sub)program from which F08ABF (DGEQRT) is called.
Constraint: LDA≥max 1,M.
6:   T LDT* – REAL (KIND=nag_wp) arrayOutput
Note: the second dimension of the array T must be at least max 1,min M,N.
On exit: further details of the orthogonal matrix Q. The number of blocks is b=kNB, where k=min m,n and each block is of order NB except for the last block, which is of order k-b-1×NB. For each of the blocks, an upper triangular block reflector factor is computed: T 1,T 2,…,Tb. These are stored in the NB by n matrix T as T=T 1|T 2|…|Tb.
7:   LDT – INTEGERInput
On entry: the first dimension of the array T as declared in the (sub)program from which F08ABF (DGEQRT) is called.
Constraint: LDT≥NB.
8:   WORK NB×N – REAL (KIND=nag_wp) arrayWorkspace
9:   INFO – INTEGEROutput
On exit: INFO=0 unless the routine detects an error (see Section 6).

6 Error Indicators and Warnings

INFO<0
If INFO=-i, argument i had an illegal value. An explanatory message is output, and execution of the program is terminated.

7 Accuracy

The computed factorization is the exact factorization of a nearby matrix A+E, where
E 2 = O ε A 2 ,
and ε is the machine precision.

8 Parallelism and Performance

F08ABF (DGEQRT) makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The total number of floating-point operations is approximately 23 n 2 3 m-n if m≥n or 23 m 2 3 n-m if m<n.
To apply Q to an arbitrary real rectangular matrix C, F08ABF (DGEQRT) may be followed by a call to F08ACF (DGEMQRT). For example,
CALL DGEMQRT('Left','Transpose',M,P,MIN(M,N),NB,A,LDA,T,LDT,C,LDC, &
              WORK,INFO)
forms C=QT C, where C is m by p.
To form the orthogonal matrix Q explicitly, simply initialize the m by m matrix C to the identity matrix and form C=QC using F08ACF (DGEMQRT) as above.
The block size, NB, used by F08ABF (DGEQRT) is supplied explicitly through the interface. For moderate and large sizes of matrix, the block size can have a marked effect on the efficiency of the algorithm with the optimal value being dependent on problem size and platform. A value of NB=64≪min m,n is likely to achieve good efficiency and it is unlikely that an optimal value would exceed 340.
To compute a QR factorization with column pivoting, use F08BBF (DTPQRT) or F08BEF (DGEQPF).
The complex analogue of this routine is F08APF (ZGEQRT).

10 Example

This example solves the linear least squares problems
minimize⁡ A xi - bi 2 ,   i=1,2
where b 1 and b 2 are the columns of the matrix B,
A = -0.57 -1.28 -0.39 0.25 -1.93 1.08 -0.31 -2.14 2.30 0.24 0.40 -0.35 -1.93 0.64 -0.66 0.08 0.15 0.30 0.15 -2.13 -0.02 1.03 -1.43 0.50   and   B= -2.67 0.41 -0.55 -3.10 3.34 -4.01 -0.77 2.76 0.48 -6.17 4.10 0.21 .

10.1 Program Text

Program Text (f08abfe.f90)

10.2 Program Data

Program Data (f08abfe.d)

10.3 Program Results

Program Results (f08abfe.r)

F08 Chapter Contents
F08 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F08ACF (DGEMQRT) : NAG Library, Mark 26

F08 Chapter Contents
F08 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F08ACF (DGEMQRT)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
10 Example

1 Purpose

F08ACF (DGEMQRT) multiplies an arbitrary real matrix C by the real orthogonal matrix Q from a QR factorization computed by F08ABF (DGEQRT).

2 Specification

SUBROUTINE F08ACF ( SIDE, TRANS, M, N, K, NB, V, LDV, T, LDT, C, LDC, WORK, INFO)
INTEGER | M, N, K, NB, LDV, LDT, LDC, INFO
REAL (KIND=nag_wp) | V(LDV,*), T(LDT,*), C(LDC,*), WORK(*)
CHARACTER(1) | SIDE, TRANS
The routine may be called by its LAPACK name dgemqrt.

3 Description

F08ACF (DGEMQRT) is intended to be used after a call to F08ABF (DGEQRT) which performs a QR factorization of a real matrix A. The orthogonal matrix Q is represented as a product of elementary reflectors.
This routine may be used to form one of the matrix products
QC , QT C , CQ ​ or ​ C QT ,
overwriting the result on C (which may be any real rectangular matrix).
A common application of this routine is in solving linear least squares problems, as described in the F08 Chapter Introduction and illustrated in Section 10 in F08ABF (DGEQRT).

4 References

Golub G H and Van Loan C F (2012) Matrix Computations (4th Edition) Johns Hopkins University Press, Baltimore

5 Arguments

1:   SIDE – CHARACTER(1)Input
On entry: indicates how Q or QT is to be applied to C.
SIDE='L'
Q or QT is applied to C from the left.
SIDE='R'
Q or QT is applied to C from the right.
Constraint: SIDE='L' or 'R'.
2:   TRANS – CHARACTER(1)Input
On entry: indicates whether Q or QT is to be applied to C.
TRANS='N'
Q is applied to C.
TRANS='T'
QT is applied to C.
Constraint: TRANS='N' or 'T'.
3:   M – INTEGERInput
On entry: m, the number of rows of the matrix C.
Constraint: M≥0.
4:   N – INTEGERInput
On entry: n, the number of columns of the matrix C.
Constraint: N≥0.
5:   K – INTEGERInput
On entry: k, the number of elementary reflectors whose product defines the matrix Q. Usually K=min mA,nA where mA, nA are the dimensions of the matrix A supplied in a previous call to F08ABF (DGEQRT).
Constraints:
  • if SIDE='L', M≥ K≥ 0 ;
  • if SIDE='R', N≥ K≥ 0 .
6:   NB – INTEGERInput
On entry: the block size used in the QR factorization performed in a previous call to F08ABF (DGEQRT); this value must remain unchanged from that call.
Constraints:
  • NB≥1;
  • if K>0, NB≤K.
7:   V LDV* – REAL (KIND=nag_wp) arrayInput
Note: the second dimension of the array V must be at least max 1,K.
On entry: details of the vectors which define the elementary reflectors, as returned by F08ABF (DGEQRT) in the first k columns of its array argument A.
8:   LDV – INTEGERInput
On entry: the first dimension of the array V as declared in the (sub)program from which F08ACF (DGEMQRT) is called.
Constraints:
  • if SIDE='L', LDV≥ max 1,M ;
  • if SIDE='R', LDV≥ max 1,N .
9:   T LDT* – REAL (KIND=nag_wp) arrayInput
Note: the second dimension of the array T must be at least max 1,K.
On entry: further details of the orthogonal matrix Q as returned by F08ABF (DGEQRT). The number of blocks is b=kNB, where k=min m,n and each block is of order NB except for the last block, which is of order k-b-1×NB. For the b blocks the upper triangular block reflector factors T 1,T 2,…,Tb are stored in the NB by n matrix T as T=T 1|T 2|…|Tb.
10:   LDT – INTEGERInput
On entry: the first dimension of the array T as declared in the (sub)program from which F08ACF (DGEMQRT) is called.
Constraint: LDT≥NB.
11:   C LDC* – REAL (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array C must be at least max 1,N.
On entry: the m by n matrix C.
On exit: C is overwritten by QC or QT C or CQ or C QT as specified by SIDE and TRANS.
12:   LDC – INTEGERInput
On entry: the first dimension of the array C as declared in the (sub)program from which F08ACF (DGEMQRT) is called.
Constraint: LDC≥max 1,M.
13:   WORK* – REAL (KIND=nag_wp) arrayWorkspace
Note: the dimension of the array WORK must be at least N×NB if SIDE='L' and at least M×NB if SIDE='R'.
14:   INFO – INTEGEROutput
On exit: INFO=0 unless the routine detects an error (see Section 6).

6 Error Indicators and Warnings

INFO<0
If INFO=-i, argument i had an illegal value. An explanatory message is output, and execution of the program is terminated.

7 Accuracy

The computed result differs from the exact result by a matrix E such that
E 2 = O ε C 2 ,
where ε is the machine precision.

8 Parallelism and Performance

F08ACF (DGEMQRT) makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The total number of floating-point operations is approximately 2 nk 2 m-k if SIDE='L' and 2 mk 2 n-k if SIDE='R'.
The complex analogue of this routine is F08AQF (ZGEMQRT).

10 Example

See Section 10 in F08ABF (DGEQRT).
F08 Chapter Contents
F08 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F08AEF (DGEQRF) : NAG Library, Mark 26

F08 Chapter Contents
F08 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F08AEF (DGEQRF)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F08AEF (DGEQRF) computes the QR factorization of a real m by n matrix.

2 Specification

SUBROUTINE F08AEF ( M, N, A, LDA, TAU, WORK, LWORK, INFO)
INTEGER | M, N, LDA, LWORK, INFO
REAL (KIND=nag_wp) | A(LDA,*), TAU(*), WORK(max(1,LWORK))
The routine may be called by its LAPACK name dgeqrf.

3 Description

F08AEF (DGEQRF) forms the QR factorization of an arbitrary rectangular real m by n matrix. No pivoting is performed.
If m≥n, the factorization is given by:
A = Q R 0 ,
where R is an n by n upper triangular matrix and Q is an m by m orthogonal matrix. It is sometimes more convenient to write the factorization as
A = Q 1 Q 2 R 0 ,
which reduces to
A = Q 1 R ,
where Q 1 consists of the first n columns of Q, and Q 2 the remaining m-n columns.
If m<n, R is trapezoidal, and the factorization can be written
A = Q R 1 R 2 ,
where R 1 is upper triangular and R 2 is rectangular.
The matrix Q is not formed explicitly but is represented as a product of min m,n elementary reflectors (see the F08 Chapter Introduction for details). Routines are provided to work with Q in this representation (see Section 9).
Note also that for any k<n, the information returned in the first k columns of the array A represents a QR factorization of the first k columns of the original matrix A.

4 References

Golub G H and Van Loan C F (1996) Matrix Computations (3rd Edition) Johns Hopkins University Press, Baltimore

5 Arguments

1:   M – INTEGERInput
On entry: m, the number of rows of the matrix A.
Constraint: M≥0.
2:   N – INTEGERInput
On entry: n, the number of columns of the matrix A.
Constraint: N≥0.
3:   A LDA* – REAL (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array A must be at least max 1,N.
On entry: the m by n matrix A.
On exit: if m≥n, the elements below the diagonal are overwritten by details of the orthogonal matrix Q and the upper triangle is overwritten by the corresponding elements of the n by n upper triangular matrix R.
If m<n, the strictly lower triangular part is overwritten by details of the orthogonal matrix Q and the remaining elements are overwritten by the corresponding elements of the m by n upper trapezoidal matrix R.
4:   LDA – INTEGERInput
On entry: the first dimension of the array A as declared in the (sub)program from which F08AEF (DGEQRF) is called.
Constraint: LDA≥max 1,M.
5:   TAU* – REAL (KIND=nag_wp) arrayOutput
Note: the dimension of the array TAU must be at least max 1,min M,N.
On exit: further details of the orthogonal matrix Q.
6:   WORK max 1,LWORK – REAL (KIND=nag_wp) arrayWorkspace
On exit: if INFO=0, WORK 1 contains the minimum value of LWORK required for optimal performance.
7:   LWORK – INTEGERInput
On entry: the dimension of the array WORK as declared in the (sub)program from which F08AEF (DGEQRF) is called.
If LWORK=-1, a workspace query is assumed; the routine only calculates the optimal size of the WORK array, returns this value as the first entry of the WORK array, and no error message related to LWORK is issued.
Suggested value: for optimal performance, LWORK≥N×nb, where nb is the optimal block size.
Constraint: LWORK≥max 1,N or LWORK=-1.
8:   INFO – INTEGEROutput
On exit: INFO=0 unless the routine detects an error (see Section 6).

6 Error Indicators and Warnings

INFO<0
If INFO=-i, argument i had an illegal value. An explanatory message is output, and execution of the program is terminated.

7 Accuracy

The computed factorization is the exact factorization of a nearby matrix A+E, where
E 2 = O ε A 2 ,
and ε is the machine precision.

8 Parallelism and Performance

F08AEF (DGEQRF) is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
F08AEF (DGEQRF) makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The total number of floating-point operations is approximately 23 n 2 3 m-n if m≥n or 23 m 2 3 n-m if m<n.
To form the orthogonal matrix Q F08AEF (DGEQRF) may be followed by a call to F08AFF (DORGQR):
CALL DORGQR(M,M,MIN(M,N),A,LDA,TAU,WORK,LWORK,INFO)
but note that the second dimension of the array A must be at least M, which may be larger than was required by F08AEF (DGEQRF).
When m≥n, it is often only the first n columns of Q that are required, and they may be formed by the call:
CALL DORGQR(M,N,N,A,LDA,TAU,WORK,LWORK,INFO)
To apply Q to an arbitrary real rectangular matrix C, F08AEF (DGEQRF) may be followed by a call to F08AGF (DORMQR). For example,
CALL DORMQR('Left','Transpose',M,P,MIN(M,N),A,LDA,TAU,C,LDC,WORK, &
              LWORK,INFO)
forms C=QT C, where C is m by p.
To compute a QR factorization with column pivoting, use F08BBF (DTPQRT) or F08BEF (DGEQPF).
The complex analogue of this routine is F08ASF (ZGEQRF).

10 Example

This example solves the linear least squares problems
minimize⁡ A xi - bi 2 ,   i=1,2
where b 1 and b 2 are the columns of the matrix B,
A = -0.57 -1.28 -0.39 0.25 -1.93 1.08 -0.31 -2.14 2.30 0.24 0.40 -0.35 -1.93 0.64 -0.66 0.08 0.15 0.30 0.15 -2.13 -0.02 1.03 -1.43 0.50   and   B= -3.15 2.19 -0.11 -3.64 1.99 0.57 -2.70 8.23 0.26 -6.35 4.50 -1.48 .

10.1 Program Text

Program Text (f08aefe.f90)

10.2 Program Data

Program Data (f08aefe.d)

10.3 Program Results

Program Results (f08aefe.r)

F08 Chapter Contents
F08 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F08AFF (DORGQR) : NAG Library, Mark 26

F08 Chapter Contents
F08 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F08AFF (DORGQR)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F08AFF (DORGQR) generates all or part of the real orthogonal matrix Q from a QR factorization computed by F08AEF (DGEQRF), F08BEF (DGEQPF) or F08BFF (DGEQP3).

2 Specification

SUBROUTINE F08AFF ( M, N, K, A, LDA, TAU, WORK, LWORK, INFO)
INTEGER | M, N, K, LDA, LWORK, INFO
REAL (KIND=nag_wp) | A(LDA,*), TAU(*), WORK(max(1,LWORK))
The routine may be called by its LAPACK name dorgqr.

3 Description

F08AFF (DORGQR) is intended to be used after a call to F08AEF (DGEQRF), F08BEF (DGEQPF) or F08BFF (DGEQP3). which perform a QR factorization of a real matrix A. The orthogonal matrix Q is represented as a product of elementary reflectors.
This routine may be used to generate Q explicitly as a square matrix, or to form only its leading columns.
Usually Q is determined from the QR factorization of an m by p matrix A with m≥p. The whole of Q may be computed by:
CALL DORGQR(M,M,P,A,LDA,TAU,WORK,LWORK,INFO)
(note that the array A must have at least m columns) or its leading p columns by:
CALL DORGQR(M,P,P,A,LDA,TAU,WORK,LWORK,INFO)
The columns of Q returned by the last call form an orthonormal basis for the space spanned by the columns of A; thus F08AEF (DGEQRF) followed by F08AFF (DORGQR) can be used to orthogonalize the columns of A.
The information returned by the QR factorization routines also yields the QR factorization of the leading k columns of A, where k<p. The orthogonal matrix arising from this factorization can be computed by:
CALL DORGQR(M,M,K,A,LDA,TAU,WORK,LWORK,INFO)
or its leading k columns by:
CALL DORGQR(M,K,K,A,LDA,TAU,WORK,LWORK,INFO)

4 References

Golub G H and Van Loan C F (1996) Matrix Computations (3rd Edition) Johns Hopkins University Press, Baltimore

5 Arguments

1:   M – INTEGERInput
On entry: m, the order of the orthogonal matrix Q.
Constraint: M≥0.
2:   N – INTEGERInput
On entry: n, the number of columns of the matrix Q.
Constraint: M≥N≥0.
3:   K – INTEGERInput
On entry: k, the number of elementary reflectors whose product defines the matrix Q.
Constraint: N≥K≥0.
4:   A LDA* – REAL (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array A must be at least max 1,N.
On entry: details of the vectors which define the elementary reflectors, as returned by F08AEF (DGEQRF), F08BEF (DGEQPF) or F08BFF (DGEQP3).
On exit: the m by n matrix Q.
5:   LDA – INTEGERInput
On entry: the first dimension of the array A as declared in the (sub)program from which F08AFF (DORGQR) is called.
Constraint: LDA≥max 1,M.
6:   TAU* – REAL (KIND=nag_wp) arrayInput
Note: the dimension of the array TAU must be at least max 1,K.
On entry: further details of the elementary reflectors, as returned by F08AEF (DGEQRF), F08BEF (DGEQPF) or F08BFF (DGEQP3).
7:   WORK max 1,LWORK – REAL (KIND=nag_wp) arrayWorkspace
On exit: if INFO=0, WORK 1 contains the minimum value of LWORK required for optimal performance.
8:   LWORK – INTEGERInput
On entry: the dimension of the array WORK as declared in the (sub)program from which F08AFF (DORGQR) is called.
If LWORK=-1, a workspace query is assumed; the routine only calculates the optimal size of the WORK array, returns this value as the first entry of the WORK array, and no error message related to LWORK is issued.
Suggested value: for optimal performance, LWORK≥N×nb, where nb is the optimal block size.
Constraint: LWORK≥max 1,N or LWORK=-1.
9:   INFO – INTEGEROutput
On exit: INFO=0 unless the routine detects an error (see Section 6).

6 Error Indicators and Warnings

INFO<0
If INFO=-i, argument i had an illegal value. An explanatory message is output, and execution of the program is terminated.

7 Accuracy

The computed matrix Q differs from an exactly orthogonal matrix by a matrix E such that
E 2 = O ε ,
where ε is the machine precision.

8 Parallelism and Performance

F08AFF (DORGQR) is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
F08AFF (DORGQR) makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The total number of floating-point operations is approximately 4 mnk-2 m+n k 2 + 43 k 3 ; when n=k, the number is approximately 23 n 2 3 m-n .
The complex analogue of this routine is F08ATF (ZUNGQR).

10 Example

This example forms the leading 4 columns of the orthogonal matrix Q from the QR factorization of the matrix A, where
A = -0.57 -1.28 -0.39 0.25 -1.93 1.08 -0.31 -2.14 2.30 0.24 0.40 -0.35 -1.93 0.64 -0.66 0.08 0.15 0.30 0.15 -2.13 -0.02 1.03 -1.43 0.50 .
The columns of Q form an orthonormal basis for the space spanned by the columns of A.

10.1 Program Text

Program Text (f08affe.f90)

10.2 Program Data

Program Data (f08affe.d)

10.3 Program Results

Program Results (f08affe.r)

F08 Chapter Contents
F08 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F08AGF (DORMQR) : NAG Library, Mark 26

F08 Chapter Contents
F08 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F08AGF (DORMQR)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
10 Example

1 Purpose

F08AGF (DORMQR) multiplies an arbitrary real matrix C by the real orthogonal matrix Q from a QR factorization computed by F08AEF (DGEQRF), F08BEF (DGEQPF) or F08BFF (DGEQP3).

2 Specification

SUBROUTINE F08AGF ( SIDE, TRANS, M, N, K, A, LDA, TAU, C, LDC, WORK, LWORK, INFO)
INTEGER | M, N, K, LDA, LDC, LWORK, INFO
REAL (KIND=nag_wp) | A(LDA,*), TAU(*), C(LDC,*), WORK(max(1,LWORK))
CHARACTER(1) | SIDE, TRANS
The routine may be called by its LAPACK name dormqr.

3 Description

F08AGF (DORMQR) is intended to be used after a call to F08AEF (DGEQRF), F08BEF (DGEQPF) or F08BFF (DGEQP3) which perform a QR factorization of a real matrix A. The orthogonal matrix Q is represented as a product of elementary reflectors.
This routine may be used to form one of the matrix products
QC , QT C , CQ ​ or ​ C QT ,
overwriting the result on C (which may be any real rectangular matrix).
A common application of this routine is in solving linear least squares problems, as described in the F08 Chapter Introduction and illustrated in Section 10 in F08AEF (DGEQRF).

4 References

Golub G H and Van Loan C F (1996) Matrix Computations (3rd Edition) Johns Hopkins University Press, Baltimore

5 Arguments

1:   SIDE – CHARACTER(1)Input
On entry: indicates how Q or QT is to be applied to C.
SIDE='L'
Q or QT is applied to C from the left.
SIDE='R'
Q or QT is applied to C from the right.
Constraint: SIDE='L' or 'R'.
2:   TRANS – CHARACTER(1)Input
On entry: indicates whether Q or QT is to be applied to C.
TRANS='N'
Q is applied to C.
TRANS='T'
QT is applied to C.
Constraint: TRANS='N' or 'T'.
3:   M – INTEGERInput
On entry: m, the number of rows of the matrix C.
Constraint: M≥0.
4:   N – INTEGERInput
On entry: n, the number of columns of the matrix C.
Constraint: N≥0.
5:   K – INTEGERInput
On entry: k, the number of elementary reflectors whose product defines the matrix Q.
Constraints:
  • if SIDE='L', M≥ K≥ 0 ;
  • if SIDE='R', N≥ K≥ 0 .
6:   A LDA* – REAL (KIND=nag_wp) arrayInput
Note: the second dimension of the array A must be at least max 1,K.
On entry: details of the vectors which define the elementary reflectors, as returned by F08AEF (DGEQRF), F08BEF (DGEQPF) or F08BFF (DGEQP3).
7:   LDA – INTEGERInput
On entry: the first dimension of the array A as declared in the (sub)program from which F08AGF (DORMQR) is called.
Constraints:
  • if SIDE='L', LDA≥ max 1,M ;
  • if SIDE='R', LDA≥ max 1,N .
8:   TAU* – REAL (KIND=nag_wp) arrayInput
Note: the dimension of the array TAU must be at least max 1,K.
On entry: further details of the elementary reflectors, as returned by F08AEF (DGEQRF), F08BEF (DGEQPF) or F08BFF (DGEQP3).
9:   C LDC* – REAL (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array C must be at least max 1,N.
On entry: the m by n matrix C.
On exit: C is overwritten by QC or QT C or CQ or C QT as specified by SIDE and TRANS.
10:   LDC – INTEGERInput
On entry: the first dimension of the array C as declared in the (sub)program from which F08AGF (DORMQR) is called.
Constraint: LDC≥max 1,M.
11:   WORK max 1,LWORK – REAL (KIND=nag_wp) arrayWorkspace
On exit: if INFO=0, WORK 1 contains the minimum value of LWORK required for optimal performance.
12:   LWORK – INTEGERInput
On entry: the dimension of the array WORK as declared in the (sub)program from which F08AGF (DORMQR) is called.
If LWORK=-1, a workspace query is assumed; the routine only calculates the optimal size of the WORK array, returns this value as the first entry of the WORK array, and no error message related to LWORK is issued.
Suggested value: for optimal performance, LWORK≥N×nb if SIDE='L' and at least M×nb if SIDE='R', where nb is the optimal block size.
Constraints:
  • if SIDE='L', LWORK≥max 1,N or LWORK=-1;
  • if SIDE='R', LWORK≥max 1,M or LWORK=-1.
13:   INFO – INTEGEROutput
On exit: INFO=0 unless the routine detects an error (see Section 6).

6 Error Indicators and Warnings

INFO<0
If INFO=-i, argument i had an illegal value.
If INFO=-999, dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.
An explanatory message is output, and execution of the program is terminated.

7 Accuracy

The computed result differs from the exact result by a matrix E such that
E 2 = O ε C 2 ,
where ε is the machine precision.

8 Parallelism and Performance

F08AGF (DORMQR) is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
F08AGF (DORMQR) makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The total number of floating-point operations is approximately 2 nk 2 m-k if SIDE='L' and 2 mk 2 n-k if SIDE='R'.
The complex analogue of this routine is F08AUF (ZUNMQR).

10 Example

See Section 10 in F08AEF (DGEQRF).
F08 Chapter Contents
F08 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F08AHF (DGELQF) : NAG Library, Mark 26

F08 Chapter Contents
F08 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F08AHF (DGELQF)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F08AHF (DGELQF) computes the LQ factorization of a real m by n matrix.

2 Specification

SUBROUTINE F08AHF ( M, N, A, LDA, TAU, WORK, LWORK, INFO)
INTEGER | M, N, LDA, LWORK, INFO
REAL (KIND=nag_wp) | A(LDA,*), TAU(*), WORK(max(1,LWORK))
The routine may be called by its LAPACK name dgelqf.

3 Description

F08AHF (DGELQF) forms the LQ factorization of an arbitrary rectangular real m by n matrix. No pivoting is performed.
If m≤n, the factorization is given by:
A = L 0 Q
where L is an m by m lower triangular matrix and Q is an n by n orthogonal matrix. It is sometimes more convenient to write the factorization as
A = L 0 Q 1 Q 2
which reduces to
A = L Q 1 ,
where Q 1 consists of the first m rows of Q, and Q 2 the remaining n-m rows.
If m>n, L is trapezoidal, and the factorization can be written
A = L 1 L 2 Q
where L 1 is lower triangular and L 2 is rectangular.
The LQ factorization of A is essentially the same as the QR factorization of AT, since
A = L 0 Q⇔AT= QT LT 0 .
The matrix Q is not formed explicitly but is represented as a product of min m,n elementary reflectors (see the F08 Chapter Introduction for details). Routines are provided to work with Q in this representation (see Section 9).
Note also that for any k<m, the information returned in the first k rows of the array A represents an LQ factorization of the first k rows of the original matrix A.

4 References

None.

5 Arguments

1:   M – INTEGERInput
On entry: m, the number of rows of the matrix A.
Constraint: M≥0.
2:   N – INTEGERInput
On entry: n, the number of columns of the matrix A.
Constraint: N≥0.
3:   A LDA* – REAL (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array A must be at least max 1,N.
On entry: the m by n matrix A.
On exit: if m≤n, the elements above the diagonal are overwritten by details of the orthogonal matrix Q and the lower triangle is overwritten by the corresponding elements of the m by m lower triangular matrix L.
If m>n, the strictly upper triangular part is overwritten by details of the orthogonal matrix Q and the remaining elements are overwritten by the corresponding elements of the m by n lower trapezoidal matrix L.
4:   LDA – INTEGERInput
On entry: the first dimension of the array A as declared in the (sub)program from which F08AHF (DGELQF) is called.
Constraint: LDA≥max 1,M.
5:   TAU* – REAL (KIND=nag_wp) arrayOutput
Note: the dimension of the array TAU must be at least max 1,min M,N.
On exit: further details of the orthogonal matrix Q.
6:   WORK max 1,LWORK – REAL (KIND=nag_wp) arrayWorkspace
On exit: if INFO=0, WORK 1 contains the minimum value of LWORK required for optimal performance.
7:   LWORK – INTEGERInput
On entry: the dimension of the array WORK as declared in the (sub)program from which F08AHF (DGELQF) is called.
If LWORK=-1, a workspace query is assumed; the routine only calculates the optimal size of the WORK array, returns this value as the first entry of the WORK array, and no error message related to LWORK is issued.
Suggested value: for optimal performance, LWORK≥M×nb, where nb is the optimal block size.
Constraint: LWORK≥max 1,M or LWORK=-1.
8:   INFO – INTEGEROutput
On exit: INFO=0 unless the routine detects an error (see Section 6).

6 Error Indicators and Warnings

INFO<0
If INFO=-i, argument i had an illegal value. An explanatory message is output, and execution of the program is terminated.

7 Accuracy

The computed factorization is the exact factorization of a nearby matrix A+E, where
E 2 = O ε A 2 ,
and ε is the machine precision.

8 Parallelism and Performance

F08AHF (DGELQF) makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The total number of floating-point operations is approximately 23 m 2 3 n-m if m≤n or 23 n 2 3 m-n if m>n.
To form the orthogonal matrix Q F08AHF (DGELQF) may be followed by a call to F08AJF (DORGLQ):
CALL DORGLQ(N,N,MIN(M,N),A,LDA,TAU,WORK,LWORK,INFO)
but note that the first dimension of the array A, specified by the argument LDA, must be at least N, which may be larger than was required by F08AHF (DGELQF).
When m≤n, it is often only the first m rows of Q that are required, and they may be formed by the call:
CALL DORGLQ(M,N,M,A,LDA,TAU,WORK,LWORK,INFO)
To apply Q to an arbitrary real rectangular matrix C, F08AHF (DGELQF) may be followed by a call to F08AKF (DORMLQ). For example,
CALL DORMLQ('Left','Transpose',M,P,MIN(M,N),A,LDA,TAU,C,LDC, &
              WORK,LWORK,INFO)
forms the matrix product C=QT C, where C is m by p.
The complex analogue of this routine is F08AVF (ZGELQF).

10 Example

This example finds the minimum norm solutions of the under-determined systems of linear equations
A x 1= b 1   and   A x 2= b 2
where b 1 and b 2 are the columns of the matrix B,
A = -5.42 3.28 -3.68 0.27 2.06 0.46 -1.65 -3.40 -3.20 -1.03 -4.06 -0.01 -0.37 2.35 1.90 4.31 -1.76 1.13 -3.15 -0.11 1.99 -2.70 0.26 4.50   and   B= -2.87 -5.23 1.63 0.29 -3.52 4.76 0.45 -8.41 .

10.1 Program Text

Program Text (f08ahfe.f90)

10.2 Program Data

Program Data (f08ahfe.d)

10.3 Program Results

Program Results (f08ahfe.r)

F08 Chapter Contents
F08 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F08AJF (DORGLQ) : NAG Library, Mark 26

F08 Chapter Contents
F08 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F08AJF (DORGLQ)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F08AJF (DORGLQ) generates all or part of the real orthogonal matrix Q from an LQ factorization computed by F08AHF (DGELQF).

2 Specification

SUBROUTINE F08AJF ( M, N, K, A, LDA, TAU, WORK, LWORK, INFO)
INTEGER | M, N, K, LDA, LWORK, INFO
REAL (KIND=nag_wp) | A(LDA,*), TAU(*), WORK(max(1,LWORK))
The routine may be called by its LAPACK name dorglq.

3 Description

F08AJF (DORGLQ) is intended to be used after a call to F08AHF (DGELQF), which performs an LQ factorization of a real matrix A. The orthogonal matrix Q is represented as a product of elementary reflectors.
This routine may be used to generate Q explicitly as a square matrix, or to form only its leading rows.
Usually Q is determined from the LQ factorization of a p by n matrix A with p≤n. The whole of Q may be computed by:
CALL DORGLQ(N,N,P,A,LDA,TAU,WORK,LWORK,INFO)
(note that the array A must have at least n rows) or its leading p rows by:
CALL DORGLQ(P,N,P,A,LDA,TAU,WORK,LWORK,INFO)
The rows of Q returned by the last call form an orthonormal basis for the space spanned by the rows of A; thus F08AHF (DGELQF) followed by F08AJF (DORGLQ) can be used to orthogonalize the rows of A.
The information returned by the LQ factorization routines also yields the LQ factorization of the leading k rows of A, where k<p. The orthogonal matrix arising from this factorization can be computed by:
CALL DORGLQ(N,N,K,A,LDA,TAU,WORK,LWORK,INFO)
or its leading k rows by:
CALL DORGLQ(K,N,K,A,LDA,TAU,WORK,LWORK,INFO)

4 References

Golub G H and Van Loan C F (1996) Matrix Computations (3rd Edition) Johns Hopkins University Press, Baltimore

5 Arguments

1:   M – INTEGERInput
On entry: m, the number of rows of the matrix Q.
Constraint: M≥0.
2:   N – INTEGERInput
On entry: n, the number of columns of the matrix Q.
Constraint: N≥M.
3:   K – INTEGERInput
On entry: k, the number of elementary reflectors whose product defines the matrix Q.
Constraint: M≥K≥0.
4:   A LDA* – REAL (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array A must be at least max 1,N.
On entry: details of the vectors which define the elementary reflectors, as returned by F08AHF (DGELQF).
On exit: the m by n matrix Q.
5:   LDA – INTEGERInput
On entry: the first dimension of the array A as declared in the (sub)program from which F08AJF (DORGLQ) is called.
Constraint: LDA≥max 1,M.
6:   TAU* – REAL (KIND=nag_wp) arrayInput
Note: the dimension of the array TAU must be at least max 1,K.
On entry: further details of the elementary reflectors, as returned by F08AHF (DGELQF).
7:   WORK max 1,LWORK – REAL (KIND=nag_wp) arrayWorkspace
On exit: if INFO=0, WORK 1 contains the minimum value of LWORK required for optimal performance.
8:   LWORK – INTEGERInput
On entry: the dimension of the array WORK as declared in the (sub)program from which F08AJF (DORGLQ) is called.
If LWORK=-1, a workspace query is assumed; the routine only calculates the optimal size of the WORK array, returns this value as the first entry of the WORK array, and no error message related to LWORK is issued.
Suggested value: for optimal performance, LWORK≥M×nb, where nb is the optimal block size.
Constraint: LWORK≥max 1,M or LWORK=-1.
9:   INFO – INTEGEROutput
On exit: INFO=0 unless the routine detects an error (see Section 6).

6 Error Indicators and Warnings

INFO<0
If INFO=-i, argument i had an illegal value. An explanatory message is output, and execution of the program is terminated.

7 Accuracy

The computed matrix Q differs from an exactly orthogonal matrix by a matrix E such that
E 2 = O ε ,
where ε is the machine precision.

8 Parallelism and Performance

F08AJF (DORGLQ) makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The total number of floating-point operations is approximately 4 mnk-2 m+n k 2 + 43 k 3 ; when m=k, the number is approximately 23 m 2 3 n-m .
The complex analogue of this routine is F08AWF (ZUNGLQ).

10 Example

This example forms the leading 4 rows of the orthogonal matrix Q from the LQ factorization of the matrix A, where
A = -5.42 3.28 -3.68 0.27 2.06 0.46 -1.65 -3.40 -3.20 -1.03 -4.06 -0.01 -0.37 2.35 1.90 4.31 -1.76 1.13 -3.15 -0.11 1.99 -2.70 0.26 4.50 .
The rows of Q form an orthonormal basis for the space spanned by the rows of A.

10.1 Program Text

Program Text (f08ajfe.f90)

10.2 Program Data

Program Data (f08ajfe.d)

10.3 Program Results

Program Results (f08ajfe.r)

F08 Chapter Contents
F08 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F08AKF (DORMLQ) : NAG Library, Mark 26

F08 Chapter Contents
F08 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F08AKF (DORMLQ)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
10 Example

1 Purpose

F08AKF (DORMLQ) multiplies an arbitrary real matrix C by the real orthogonal matrix Q from an LQ factorization computed by F08AHF (DGELQF).

2 Specification

SUBROUTINE F08AKF ( SIDE, TRANS, M, N, K, A, LDA, TAU, C, LDC, WORK, LWORK, INFO)
INTEGER | M, N, K, LDA, LDC, LWORK, INFO
REAL (KIND=nag_wp) | A(LDA,*), TAU(*), C(LDC,*), WORK(max(1,LWORK))
CHARACTER(1) | SIDE, TRANS
The routine may be called by its LAPACK name dormlq.

3 Description

F08AKF (DORMLQ) is intended to be used after a call to F08AHF (DGELQF), which performs an LQ factorization of a real matrix A. The orthogonal matrix Q is represented as a product of elementary reflectors.
This routine may be used to form one of the matrix products
QC , QT C , CQ ​ or ​ C QT ,
overwriting the result on C (which may be any real rectangular matrix).

4 References

Golub G H and Van Loan C F (1996) Matrix Computations (3rd Edition) Johns Hopkins University Press, Baltimore

5 Arguments

1:   SIDE – CHARACTER(1)Input
On entry: indicates how Q or QT is to be applied to C.
SIDE='L'
Q or QT is applied to C from the left.
SIDE='R'
Q or QT is applied to C from the right.
Constraint: SIDE='L' or 'R'.
2:   TRANS – CHARACTER(1)Input
On entry: indicates whether Q or QT is to be applied to C.
TRANS='N'
Q is applied to C.
TRANS='T'
QT is applied to C.
Constraint: TRANS='N' or 'T'.
3:   M – INTEGERInput
On entry: m, the number of rows of the matrix C.
Constraint: M≥0.
4:   N – INTEGERInput
On entry: n, the number of columns of the matrix C.
Constraint: N≥0.
5:   K – INTEGERInput
On entry: k, the number of elementary reflectors whose product defines the matrix Q.
Constraints:
  • if SIDE='L', M≥ K≥ 0 ;
  • if SIDE='R', N≥ K≥ 0 .
6:   A LDA* – REAL (KIND=nag_wp) arrayInput
Note: the second dimension of the array A must be at least max 1,M if SIDE='L' and at least max 1,N if SIDE='R'.
On entry: details of the vectors which define the elementary reflectors, as returned by F08AHF (DGELQF).
7:   LDA – INTEGERInput
On entry: the first dimension of the array A as declared in the (sub)program from which F08AKF (DORMLQ) is called.
Constraint: LDA≥max 1,K.
8:   TAU* – REAL (KIND=nag_wp) arrayInput
Note: the dimension of the array TAU must be at least max 1,K.
On entry: further details of the elementary reflectors, as returned by F08AHF (DGELQF).
9:   C LDC* – REAL (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array C must be at least max 1,N.
On entry: the m by n matrix C.
On exit: C is overwritten by QC or QT C or CQ or C QT as specified by SIDE and TRANS.
10:   LDC – INTEGERInput
On entry: the first dimension of the array C as declared in the (sub)program from which F08AKF (DORMLQ) is called.
Constraint: LDC≥max 1,M.
11:   WORK max 1,LWORK – REAL (KIND=nag_wp) arrayWorkspace
On exit: if INFO=0, WORK 1 contains the minimum value of LWORK required for optimal performance.
12:   LWORK – INTEGERInput
On entry: the dimension of the array WORK as declared in the (sub)program from which F08AKF (DORMLQ) is called.
If LWORK=-1, a workspace query is assumed; the routine only calculates the optimal size of the WORK array, returns this value as the first entry of the WORK array, and no error message related to LWORK is issued.
Suggested value: for optimal performance, LWORK≥N×nb if SIDE='L' and at least M×nb if SIDE='R', where nb is the optimal block size.
Constraints:
  • if SIDE='L', LWORK≥max 1,N or LWORK=-1;
  • if SIDE='R', LWORK≥max 1,M or LWORK=-1.
13:   INFO – INTEGEROutput
On exit: INFO=0 unless the routine detects an error (see Section 6).

6 Error Indicators and Warnings

INFO<0
If INFO=-i, argument i had an illegal value.
If INFO=-999, dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.
An explanatory message is output, and execution of the program is terminated.

7 Accuracy

The computed result differs from the exact result by a matrix E such that
E 2 = O ε C 2 ,
where ε is the machine precision.

8 Parallelism and Performance

F08AKF (DORMLQ) makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The total number of floating-point operations is approximately 2 nk 2 m-k if SIDE='L' and 2 mk 2 n-k if SIDE='R'.
The complex analogue of this routine is F08AXF (ZUNMLQ).

10 Example

See Section 10 in F08AHF (DGELQF).
F08 Chapter Contents
F08 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F08ANF (ZGELS) : NAG Library, Mark 26

F08 Chapter Contents
F08 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F08ANF (ZGELS)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F08ANF (ZGELS) solves linear least squares problems of the form
minx b-Ax 2   or   minx b-AH x 2 ,
where A is an m by n complex matrix of full rank, using a QR or LQ factorization of A.

2 Specification

SUBROUTINE F08ANF ( TRANS, M, N, NRHS, A, LDA, B, LDB, WORK, LWORK, INFO)
INTEGER | M, N, NRHS, LDA, LDB, LWORK, INFO
COMPLEX (KIND=nag_wp) | A(LDA,*), B(LDB,*), WORK(max(1,LWORK))
CHARACTER(1) | TRANS
The routine may be called by its LAPACK name zgels.

3 Description

The following options are provided:
1. If TRANS='N' and m≥n: find the least squares solution of an overdetermined system, i.e., solve the least squares problem
minx b-Ax 2 .
2. | If TRANS='N' and m<n: find the minimum norm solution of an underdetermined system Ax=b.
3. | If TRANS='C' and m≥n: find the minimum norm solution of an undetermined system AH x=b.
4. If TRANS='C' and m<n: find the least squares solution of an overdetermined system, i.e., solve the least squares problem
minx b-AH x 2 .
Several right-hand side vectors b and solution vectors x can be handled in a single call; they are stored as the columns of the m by r right-hand side matrix B and the n by r solution matrix X.

4 References

Anderson E, Bai Z, Bischof C, Blackford S, Demmel J, Dongarra J J, Du Croz J J, Greenbaum A, Hammarling S, McKenney A and Sorensen D (1999) LAPACK Users' Guide (3rd Edition) SIAM, Philadelphia http://www.netlib.org/lapack/lug
Golub G H and Van Loan C F (1996) Matrix Computations (3rd Edition) Johns Hopkins University Press, Baltimore

5 Arguments

1:   TRANS – CHARACTER(1)Input
On entry: if TRANS='N', the linear system involves A.
If TRANS='C', the linear system involves AH.
Constraint: TRANS='N' or 'C'.
2:   M – INTEGERInput
On entry: m, the number of rows of the matrix A.
Constraint: M≥0.
3:   N – INTEGERInput
On entry: n, the number of columns of the matrix A.
Constraint: N≥0.
4:   NRHS – INTEGERInput
On entry: r, the number of right-hand sides, i.e., the number of columns of the matrices B and X.
Constraint: NRHS≥0.
5:   A LDA* – COMPLEX (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array A must be at least max 1,N.
On entry: the m by n matrix A.
On exit: if M≥N, A is overwritten by details of its QR factorization, as returned by F08ASF (ZGEQRF).
If M<N, A is overwritten by details of its LQ factorization, as returned by F08AVF (ZGELQF).
6:   LDA – INTEGERInput
On entry: the first dimension of the array A as declared in the (sub)program from which F08ANF (ZGELS) is called.
Constraint: LDA≥max 1,M.
7:   B LDB* – COMPLEX (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array B must be at least max 1,NRHS.
On entry: the matrix B of right-hand side vectors, stored in columns; B is m by r if TRANS='N', or n by r if TRANS='C'.
On exit: B is overwritten by the solution vectors, x, stored in columns:
  • if TRANS='N' and m≥n, or TRANS='C' and m<n, elements 1 to min m,n in each column of B contain the least squares solution vectors; the residual sum of squares for the solution is given by the sum of squares of the modulus of elements min m,n+1 to max m,n in that column;
  • otherwise, elements 1 to max m,n in each column of B contain the minimum norm solution vectors.
8:   LDB – INTEGERInput
On entry: the first dimension of the array B as declared in the (sub)program from which F08ANF (ZGELS) is called.
Constraint: LDB≥max 1,M,N.
9:   WORK max 1,LWORK – COMPLEX (KIND=nag_wp) arrayWorkspace
On exit: if INFO=0, the real part of WORK 1 contains the minimum value of LWORK required for optimal performance.
10:   LWORK – INTEGERInput
On entry: the dimension of the array WORK as declared in the (sub)program from which F08ANF (ZGELS) is called.
If LWORK=-1, a workspace query is assumed; the routine only calculates the optimal size of the WORK array, returns this value as the first entry of the WORK array, and no error message related to LWORK is issued.
Suggested value: for optimal performance, LWORK≥ min M,N + max 1,M,N,NRHS × nb , where nb is the optimal block size.
Constraint: LWORK≥min M,N+max 1,M,N,NRHS or LWORK=-1.
11:   INFO – INTEGEROutput
On exit: INFO=0 unless the routine detects an error (see Section 6).

6 Error Indicators and Warnings

INFO<0
If INFO=-i, argument i had an illegal value. An explanatory message is output, and execution of the program is terminated.
INFO>0
If INFO=i, diagonal element i of the triangular factor of A is zero, so that A does not have full rank; the least squares solution could not be computed.

7 Accuracy

See Section 4.5 of Anderson et al. (1999) for details of error bounds.

8 Parallelism and Performance

F08ANF (ZGELS) is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
F08ANF (ZGELS) makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The total number of floating-point operations required to factorize A is approximately 83 n 2 3 m-n if m≥n and 83 m 2 3 n-m otherwise. Following the factorization the solution for a single vector x requires O min m 2,n 2 operations.
The real analogue of this routine is F08AAF (DGELS).

10 Example

This example solves the linear least squares problem
minx b-Ax 2 ,
where
A = 0.96-0.81 i -0.03+0.96 i -0.91+2.06 i -0.05+0.41 i -0.98+1.98 i -1.20+0.19 i -0.66+0.42 i -0.81+0.56 i 0.62-0.46 i 1.01+0.02 i 0.63-0.17 i -1.11+0.60 i -0.37+0.38 i 0.19-0.54 i -0.98-0.36 i 0.22-0.20 i 0.83+0.51 i 0.20+0.01 i -0.17-0.46 i 1.47+1.59 i 1.08-0.28 i 0.20-0.12 i -0.07+1.23 i 0.26+0.26 i
and
b = -2.09+1.93 i 3.34-3.53 i -4.94-2.04 i 0.17+4.23 i -5.19+3.63 i 0.98+2.53 i .
The square root of the residual sum of squares is also output.
Note that the block size (NB) of 64 assumed in this example is not realistic for such a small problem, but should be suitable for large problems.

10.1 Program Text

Program Text (f08anfe.f90)

10.2 Program Data

Program Data (f08anfe.d)

10.3 Program Results

Program Results (f08anfe.r)

F08 Chapter Contents
F08 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F08APF (ZGEQRT) : NAG Library, Mark 26

F08 Chapter Contents
F08 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F08APF (ZGEQRT)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F08APF (ZGEQRT) recursively computes, with explicit blocking, the QR factorization of a complex m by n matrix.

2 Specification

SUBROUTINE F08APF ( M, N, NB, A, LDA, T, LDT, WORK, INFO)
INTEGER | M, N, NB, LDA, LDT, INFO
COMPLEX (KIND=nag_wp) | A(LDA,*), T(LDT,*), WORK(NB*N)
The routine may be called by its LAPACK name zgeqrt.

3 Description

F08APF (ZGEQRT) forms the QR factorization of an arbitrary rectangular complex m by n matrix. No pivoting is performed.
It differs from F08ASF (ZGEQRF) in that it: requires an explicit block size; stores reflector factors that are upper triangular matrices of the chosen block size (rather than scalars); and recursively computes the QR factorization based on the algorithm of Elmroth and Gustavson (2000).
If m≥n, the factorization is given by:
A = Q R 0 ,
where R is an n by n upper triangular matrix (with real diagonal elements) and Q is an m by m unitary matrix. It is sometimes more convenient to write the factorization as
A = Q 1 Q 2 R 0 ,
which reduces to
A = Q 1 R ,
where Q 1 consists of the first n columns of Q, and Q 2 the remaining m-n columns.
If m<n, R is upper trapezoidal, and the factorization can be written
A = Q R 1 R 2 ,
where R 1 is upper triangular and R 2 is rectangular.
The matrix Q is not formed explicitly but is represented as a product of min m,n elementary reflectors (see the F08 Chapter Introduction for details). Routines are provided to work with Q in this representation (see Section 9).
Note also that for any k<n, the information returned represents a QR factorization of the first k columns of the original matrix A.

4 References

Elmroth E and Gustavson F (2000) Applying Recursion to Serial and Parallel QR Factorization Leads to Better Performance IBM Journal of Research and Development. (Volume 44) 4 605–624
Golub G H and Van Loan C F (2012) Matrix Computations (4th Edition) Johns Hopkins University Press, Baltimore

5 Arguments

1:   M – INTEGERInput
On entry: m, the number of rows of the matrix A.
Constraint: M≥0.
2:   N – INTEGERInput
On entry: n, the number of columns of the matrix A.
Constraint: N≥0.
3:   NB – INTEGERInput
On entry: the explicitly chosen block size to be used in computing the QR factorization. See Section 9 for details.
Constraints:
  • NB≥1;
  • if min M,N>0, NB≤min M,N.
4:   A LDA* – COMPLEX (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array A must be at least max 1,N.
On entry: the m by n matrix A.
On exit: if m≥n, the elements below the diagonal are overwritten by details of the unitary matrix Q and the upper triangle is overwritten by the corresponding elements of the n by n upper triangular matrix R.
If m<n, the strictly lower triangular part is overwritten by details of the unitary matrix Q and the remaining elements are overwritten by the corresponding elements of the m by n upper trapezoidal matrix R.
The diagonal elements of R are real.
5:   LDA – INTEGERInput
On entry: the first dimension of the array A as declared in the (sub)program from which F08APF (ZGEQRT) is called.
Constraint: LDA≥max 1,M.
6:   T LDT* – COMPLEX (KIND=nag_wp) arrayOutput
Note: the second dimension of the array T must be at least max 1,min M,N.
On exit: further details of the unitary matrix Q. The number of blocks is b=kNB, where k=min m,n and each block is of order NB except for the last block, which is of order k-b-1×NB. For each of the blocks, an upper triangular block reflector factor is computed: T 1,T 2,…,Tb. These are stored in the NB by n matrix T as T=T 1|T 2|…|Tb.
7:   LDT – INTEGERInput
On entry: the first dimension of the array T as declared in the (sub)program from which F08APF (ZGEQRT) is called.
Constraint: LDT≥NB.
8:   WORK NB×N – COMPLEX (KIND=nag_wp) arrayWorkspace
9:   INFO – INTEGEROutput
On exit: INFO=0 unless the routine detects an error (see Section 6).

6 Error Indicators and Warnings

INFO<0
If INFO=-i, argument i had an illegal value. An explanatory message is output, and execution of the program is terminated.

7 Accuracy

The computed factorization is the exact factorization of a nearby matrix A+E, where
E 2 = O ε A 2 ,
and ε is the machine precision.

8 Parallelism and Performance

F08APF (ZGEQRT) makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The total number of real floating-point operations is approximately 83 n 2 3 m-n if m≥n or 83 m 2 3 n-m if m<n.
To apply Q to an arbitrary complex rectangular matrix C, F08APF (ZGEQRT) may be followed by a call to F08AQF (ZGEMQRT). For example,
CALL ZGEMQRT('Left','Conjugate Transpose',M,P,MIN(M,N),NB,A,LDA, &
              T,LDT,C,LDC,WORK,INFO)
forms C=QH C, where C is m by p.
To form the unitary matrix Q explicitly, simply initialize the m by m matrix C to the identity matrix and form C=QC using F08AQF (ZGEMQRT) as above.
The block size, NB, used by F08APF (ZGEQRT) is supplied explicitly through the interface. For moderate and large sizes of matrix, the block size can have a marked effect on the efficiency of the algorithm with the optimal value being dependent on problem size and platform. A value of NB=64≪min m,n is likely to achieve good efficiency and it is unlikely that an optimal value would exceed 340.
To compute a QR factorization with column pivoting, use F08BPF (ZTPQRT) or F08BSF (ZGEQPF).
The real analogue of this routine is F08ABF (DGEQRT).

10 Example

This example solves the linear least squares problems
minimize⁡ A xi - bi 2 ,   i=1,2
where b 1 and b 2 are the columns of the matrix B,
A = 0.96-0.81 i -0.03+0.96 i -0.91+2.06 i -0.05+0.41 i -0.98+1.98 i -1.20+0.19 i -0.66+0.42 i -0.81+0.56 i 0.62-0.46 i 1.01+0.02 i 0.63-0.17 i -1.11+0.60 i -0.37+0.38 i 0.19-0.54 i -0.98-0.36 i 0.22-0.20 i 0.83+0.51 i 0.20+0.01 i -0.17-0.46 i 1.47+1.59 i 1.08-0.28 i 0.20-0.12 i -0.07+1.23 i 0.26+0.26 i
and
B = -2.09+1.93 i 3.26-2.70 i 3.34-3.53 i -6.22+1.16 i -4.94-2.04 i 7.94-3.13 i 0.17+4.23 i 1.04-4.26 i -5.19+3.63 i -2.31-2.12 i 0.98+2.53 i -1.39-4.05 i .

10.1 Program Text

Program Text (f08apfe.f90)

10.2 Program Data

Program Data (f08apfe.d)

10.3 Program Results

Program Results (f08apfe.r)

F08 Chapter Contents
F08 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F08AQF (ZGEMQRT) : NAG Library, Mark 26

F08 Chapter Contents
F08 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F08AQF (ZGEMQRT)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
10 Example

1 Purpose

F08AQF (ZGEMQRT) multiplies an arbitrary complex matrix C by the complex unitary matrix Q from a QR factorization computed by F08APF (ZGEQRT).

2 Specification

SUBROUTINE F08AQF ( SIDE, TRANS, M, N, K, NB, V, LDV, T, LDT, C, LDC, WORK, INFO)
INTEGER | M, N, K, NB, LDV, LDT, LDC, INFO
COMPLEX (KIND=nag_wp) | V(LDV,*), T(LDT,*), C(LDC,*), WORK(*)
CHARACTER(1) | SIDE, TRANS
The routine may be called by its LAPACK name zgemqrt.

3 Description

F08AQF (ZGEMQRT) is intended to be used after a call to F08APF (ZGEQRT), which performs a QR factorization of a complex matrix A. The unitary matrix Q is represented as a product of elementary reflectors.
This routine may be used to form one of the matrix products
QC , QH C , CQ ​ or ​ C QH ,
overwriting the result on C (which may be any complex rectangular matrix).
A common application of this routine is in solving linear least squares problems, as described in the F08 Chapter Introduction and illustrated in Section 10 in F08APF (ZGEQRT).

4 References

Golub G H and Van Loan C F (2012) Matrix Computations (4th Edition) Johns Hopkins University Press, Baltimore

5 Arguments

1:   SIDE – CHARACTER(1)Input
On entry: indicates how Q or QH is to be applied to C.
SIDE='L'
Q or QH is applied to C from the left.
SIDE='R'
Q or QH is applied to C from the right.
Constraint: SIDE='L' or 'R'.
2:   TRANS – CHARACTER(1)Input
On entry: indicates whether Q or QH is to be applied to C.
TRANS='N'
Q is applied to C.
TRANS='C'
QH is applied to C.
Constraint: TRANS='N' or 'C'.
3:   M – INTEGERInput
On entry: m, the number of rows of the matrix C.
Constraint: M≥0.
4:   N – INTEGERInput
On entry: n, the number of columns of the matrix C.
Constraint: N≥0.
5:   K – INTEGERInput
On entry: k, the number of elementary reflectors whose product defines the matrix Q. Usually K=min mA,nA where mA, nA are the dimensions of the matrix A supplied in a previous call to F08APF (ZGEQRT).
Constraints:
  • if SIDE='L', M≥ K≥ 0 ;
  • if SIDE='R', N≥ K≥ 0 .
6:   NB – INTEGERInput
On entry: the block size used in the QR factorization performed in a previous call to F08APF (ZGEQRT); this value must remain unchanged from that call.
Constraints:
  • NB≥1;
  • if K>0, NB≤K.
7:   V LDV* – COMPLEX (KIND=nag_wp) arrayInput
Note: the second dimension of the array V must be at least max 1,K.
On entry: details of the vectors which define the elementary reflectors, as returned by F08APF (ZGEQRT) in the first k columns of its array argument A.
8:   LDV – INTEGERInput
On entry: the first dimension of the array V as declared in the (sub)program from which F08AQF (ZGEMQRT) is called.
Constraints:
  • if SIDE='L', LDV≥ max 1,M ;
  • if SIDE='R', LDV≥ max 1,N .
9:   T LDT* – COMPLEX (KIND=nag_wp) arrayInput
Note: the second dimension of the array T must be at least max 1,K.
On entry: further details of the unitary matrix Q as returned by F08APF (ZGEQRT). The number of blocks is b=kNB, where k=min m,n and each block is of order NB except for the last block, which is of order k-b-1×NB. For the b blocks the upper triangular block reflector factors T 1,T 2,…,Tb are stored in the NB by n matrix T as T=T 1|T 2|…|Tb.
10:   LDT – INTEGERInput
On entry: the first dimension of the array T as declared in the (sub)program from which F08AQF (ZGEMQRT) is called.
Constraint: LDT≥NB.
11:   C LDC* – COMPLEX (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array C must be at least max 1,N.
On entry: the m by n matrix C.
On exit: C is overwritten by QC or QH C or CQ or C QH as specified by SIDE and TRANS.
12:   LDC – INTEGERInput
On entry: the first dimension of the array C as declared in the (sub)program from which F08AQF (ZGEMQRT) is called.
Constraint: LDC≥max 1,M.
13:   WORK* – COMPLEX (KIND=nag_wp) arrayWorkspace
Note: the dimension of the array WORK must be at least N×NB if SIDE='L' and at least M×NB if SIDE='R'.
14:   INFO – INTEGEROutput
On exit: INFO=0 unless the routine detects an error (see Section 6).

6 Error Indicators and Warnings

INFO<0
If INFO=-i, argument i had an illegal value. An explanatory message is output, and execution of the program is terminated.

7 Accuracy

The computed result differs from the exact result by a matrix E such that
E 2 = O ε C 2 ,
where ε is the machine precision.

8 Parallelism and Performance

F08AQF (ZGEMQRT) makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The total number of real floating-point operations is approximately 8 nk 2 m-k if SIDE='L' and 8 mk 2 n-k if SIDE='R'.
The real analogue of this routine is F08ACF (DGEMQRT).

10 Example

See Section 10 in F08APF (ZGEQRT).
F08 Chapter Contents
F08 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F08ASF (ZGEQRF) : NAG Library, Mark 26

F08 Chapter Contents
F08 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F08ASF (ZGEQRF)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F08ASF (ZGEQRF) computes the QR factorization of a complex m by n matrix.

2 Specification

SUBROUTINE F08ASF ( M, N, A, LDA, TAU, WORK, LWORK, INFO)
INTEGER | M, N, LDA, LWORK, INFO
COMPLEX (KIND=nag_wp) | A(LDA,*), TAU(*), WORK(max(1,LWORK))
The routine may be called by its LAPACK name zgeqrf.

3 Description

F08ASF (ZGEQRF) forms the QR factorization of an arbitrary rectangular complex m by n matrix. No pivoting is performed.
If m≥n, the factorization is given by:
A = Q R 0 ,
where R is an n by n upper triangular matrix (with real diagonal elements) and Q is an m by m unitary matrix. It is sometimes more convenient to write the factorization as
A = Q 1 Q 2 R 0 ,
which reduces to
A = Q 1 R ,
where Q 1 consists of the first n columns of Q, and Q 2 the remaining m-n columns.
If m<n, R is trapezoidal, and the factorization can be written
A = Q R 1 R 2 ,
where R 1 is upper triangular and R 2 is rectangular.
The matrix Q is not formed explicitly but is represented as a product of min m,n elementary reflectors (see the F08 Chapter Introduction for details). Routines are provided to work with Q in this representation (see Section 9).
Note also that for any k<n, the information returned in the first k columns of the array A represents a QR factorization of the first k columns of the original matrix A.

4 References

Golub G H and Van Loan C F (1996) Matrix Computations (3rd Edition) Johns Hopkins University Press, Baltimore

5 Arguments

1:   M – INTEGERInput
On entry: m, the number of rows of the matrix A.
Constraint: M≥0.
2:   N – INTEGERInput
On entry: n, the number of columns of the matrix A.
Constraint: N≥0.
3:   A LDA* – COMPLEX (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array A must be at least max 1,N.
On entry: the m by n matrix A.
On exit: if m≥n, the elements below the diagonal are overwritten by details of the unitary matrix Q and the upper triangle is overwritten by the corresponding elements of the n by n upper triangular matrix R.
If m<n, the strictly lower triangular part is overwritten by details of the unitary matrix Q and the remaining elements are overwritten by the corresponding elements of the m by n upper trapezoidal matrix R.
The diagonal elements of R are real.
4:   LDA – INTEGERInput
On entry: the first dimension of the array A as declared in the (sub)program from which F08ASF (ZGEQRF) is called.
Constraint: LDA≥max 1,M.
5:   TAU* – COMPLEX (KIND=nag_wp) arrayOutput
Note: the dimension of the array TAU must be at least max 1,min M,N.
On exit: further details of the unitary matrix Q.
6:   WORK max 1,LWORK – COMPLEX (KIND=nag_wp) arrayWorkspace
On exit: if INFO=0, the real part of WORK 1 contains the minimum value of LWORK required for optimal performance.
7:   LWORK – INTEGERInput
On entry: the dimension of the array WORK as declared in the (sub)program from which F08ASF (ZGEQRF) is called.
If LWORK=-1, a workspace query is assumed; the routine only calculates the optimal size of the WORK array, returns this value as the first entry of the WORK array, and no error message related to LWORK is issued.
Suggested value: for optimal performance, LWORK≥N×nb, where nb is the optimal block size.
Constraint: LWORK≥max 1,N or LWORK=-1.
8:   INFO – INTEGEROutput
On exit: INFO=0 unless the routine detects an error (see Section 6).

6 Error Indicators and Warnings

INFO<0
If INFO=-i, argument i had an illegal value. An explanatory message is output, and execution of the program is terminated.

7 Accuracy

The computed factorization is the exact factorization of a nearby matrix A+E, where
E 2 = O ε A 2 ,
and ε is the machine precision.

8 Parallelism and Performance

F08ASF (ZGEQRF) is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
F08ASF (ZGEQRF) makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The total number of real floating-point operations is approximately 83 n 2 3 m-n if m≥n or 83 m 2 3 n-m if m<n.
To form the unitary matrix Q F08ASF (ZGEQRF) may be followed by a call to F08ATF (ZUNGQR):
CALL ZUNGQR(M,M,MIN(M,N),A,LDA,TAU,WORK,LWORK,INFO)
but note that the second dimension of the array A must be at least M, which may be larger than was required by F08ASF (ZGEQRF).
When m≥n, it is often only the first n columns of Q that are required, and they may be formed by the call:
CALL ZUNGQR(M,N,N,A,LDA,TAU,WORK,LWORK,INFO)
To apply Q to an arbitrary complex rectangular matrix C, F08ASF (ZGEQRF) may be followed by a call to F08AUF (ZUNMQR). For example,
CALL ZUNMQR('Left','Conjugate Transpose',M,P,MIN(M,N),A,LDA,TAU, &
              C,LDC,WORK,LWORK,INFO)
forms C=QH C, where C is m by p.
To compute a QR factorization with column pivoting, use F08BSF (ZGEQPF).
The real analogue of this routine is F08AEF (DGEQRF).

10 Example

This example solves the linear least squares problems
minimize⁡ A xi - bi 2 ,   i=1,2
where b 1 and b 2 are the columns of the matrix B,
A = 0.96-0.81 i -0.03+0.96 i -0.91+2.06 i -0.05+0.41 i -0.98+1.98 i -1.20+0.19 i -0.66+0.42 i -0.81+0.56 i 0.62-0.46 i 1.01+0.02 i 0.63-0.17 i -1.11+0.60 i -0.37+0.38 i 0.19-0.54 i -0.98-0.36 i 0.22-0.20 i 0.83+0.51 i 0.20+0.01 i -0.17-0.46 i 1.47+1.59 i 1.08-0.28 i 0.20-0.12 i -0.07+1.23 i 0.26+0.26 i
and
B = -1.54+0.76 i 3.17-2.09 i 0.12-1.92 i -6.53+4.18 i -9.08-4.31 i 7.28+0.73 i 7.49+3.65 i 0.91-3.97 i -5.63-2.12 i -5.46-1.64 i 2.37+8.03 i -2.84-5.86 i .

10.1 Program Text

Program Text (f08asfe.f90)

10.2 Program Data

Program Data (f08asfe.d)

10.3 Program Results

Program Results (f08asfe.r)

F08 Chapter Contents
F08 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F08ATF (ZUNGQR) : NAG Library, Mark 26

F08 Chapter Contents
F08 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F08ATF (ZUNGQR)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F08ATF (ZUNGQR) generates all or part of the complex unitary matrix Q from a QR factorization computed by F08ASF (ZGEQRF), F08BSF (ZGEQPF) or F08BTF (ZGEQP3).

2 Specification

SUBROUTINE F08ATF ( M, N, K, A, LDA, TAU, WORK, LWORK, INFO)
INTEGER | M, N, K, LDA, LWORK, INFO
COMPLEX (KIND=nag_wp) | A(LDA,*), TAU(*), WORK(max(1,LWORK))
The routine may be called by its LAPACK name zungqr.

3 Description

F08ATF (ZUNGQR) is intended to be used after a call to F08ASF (ZGEQRF), F08BSF (ZGEQPF) or F08BTF (ZGEQP3), which perform a QR factorization of a complex matrix A. The unitary matrix Q is represented as a product of elementary reflectors.
This routine may be used to generate Q explicitly as a square matrix, or to form only its leading columns.
Usually Q is determined from the QR factorization of an m by p matrix A with m≥p. The whole of Q may be computed by:
CALL ZUNGQR(M,M,P,A,LDA,TAU,WORK,LWORK,INFO)
(note that the array A must have at least m columns) or its leading p columns by:
CALL ZUNGQR(M,P,P,A,LDA,TAU,WORK,LWORK,INFO)
The columns of Q returned by the last call form an orthonormal basis for the space spanned by the columns of A; thus F08ASF (ZGEQRF) followed by F08ATF (ZUNGQR) can be used to orthogonalize the columns of A.
The information returned by the QR factorization routines also yields the QR factorization of the leading k columns of A, where k<p. The unitary matrix arising from this factorization can be computed by:
CALL ZUNGQR(M,M,K,A,LDA,TAU,WORK,LWORK,INFO)
or its leading k columns by:
CALL ZUNGQR(M,K,K,A,LDA,TAU,WORK,LWORK,INFO)

4 References

Golub G H and Van Loan C F (1996) Matrix Computations (3rd Edition) Johns Hopkins University Press, Baltimore

5 Arguments

1:   M – INTEGERInput
On entry: m, the order of the unitary matrix Q.
Constraint: M≥0.
2:   N – INTEGERInput
On entry: n, the number of columns of the matrix Q.
Constraint: M≥N≥0.
3:   K – INTEGERInput
On entry: k, the number of elementary reflectors whose product defines the matrix Q.
Constraint: N≥K≥0.
4:   A LDA* – COMPLEX (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array A must be at least max 1,N.
On entry: details of the vectors which define the elementary reflectors, as returned by F08ASF (ZGEQRF), F08BSF (ZGEQPF) or F08BTF (ZGEQP3).
On exit: the m by n matrix Q.
5:   LDA – INTEGERInput
On entry: the first dimension of the array A as declared in the (sub)program from which F08ATF (ZUNGQR) is called.
Constraint: LDA≥max 1,M.
6:   TAU* – COMPLEX (KIND=nag_wp) arrayInput
Note: the dimension of the array TAU must be at least max 1,K.
On entry: further details of the elementary reflectors, as returned by F08ASF (ZGEQRF), F08BSF (ZGEQPF) or F08BTF (ZGEQP3).
7:   WORK max 1,LWORK – COMPLEX (KIND=nag_wp) arrayWorkspace
On exit: if INFO=0, the real part of WORK 1 contains the minimum value of LWORK required for optimal performance.
8:   LWORK – INTEGERInput
On entry: the dimension of the array WORK as declared in the (sub)program from which F08ATF (ZUNGQR) is called.
If LWORK=-1, a workspace query is assumed; the routine only calculates the optimal size of the WORK array, returns this value as the first entry of the WORK array, and no error message related to LWORK is issued.
Suggested value: for optimal performance, LWORK≥N×nb, where nb is the optimal block size.
Constraint: LWORK≥max 1,N or LWORK=-1.
9:   INFO – INTEGEROutput
On exit: INFO=0 unless the routine detects an error (see Section 6).

6 Error Indicators and Warnings

INFO<0
If INFO=-i, argument i had an illegal value. An explanatory message is output, and execution of the program is terminated.

7 Accuracy

The computed matrix Q differs from an exactly unitary matrix by a matrix E such that
E 2 = O ε ,
where ε is the machine precision.

8 Parallelism and Performance

F08ATF (ZUNGQR) is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
F08ATF (ZUNGQR) makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The total number of real floating-point operations is approximately 16 mnk-8 m+n k 2 + 163 k 3 ; when n=k, the number is approximately 83 n 2 3 m-n .
The real analogue of this routine is F08AFF (DORGQR).

10 Example

This example forms the leading 4 columns of the unitary matrix Q from the QR factorization of the matrix A, where
A = 0.96-0.81 i -0.03+0.96 i -0.91+2.06 i -0.05+0.41 i -0.98+1.98 i -1.20+0.19 i -0.66+0.42 i -0.81+0.56 i 0.62-0.46 i 1.01+0.02 i 0.63-0.17 i -1.11+0.60 i -0.37+0.38 i 0.19-0.54 i -0.98-0.36 i 0.22-0.20 i 0.83+0.51 i 0.20+0.01 i -0.17-0.46 i 1.47+1.59 i 1.08-0.28 i 0.20-0.12 i -0.07+1.23 i 0.26+0.26 i .
The columns of Q form an orthonormal basis for the space spanned by the columns of A.

10.1 Program Text

Program Text (f08atfe.f90)

10.2 Program Data

Program Data (f08atfe.d)

10.3 Program Results

Program Results (f08atfe.r)

F08 Chapter Contents
F08 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F08AUF (ZUNMQR) : NAG Library, Mark 26

F08 Chapter Contents
F08 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F08AUF (ZUNMQR)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
10 Example

1 Purpose

F08AUF (ZUNMQR) multiplies an arbitrary complex matrix C by the complex unitary matrix Q from a QR factorization computed by F08ASF (ZGEQRF), F08BSF (ZGEQPF) or F08BTF (ZGEQP3).

2 Specification

SUBROUTINE F08AUF ( SIDE, TRANS, M, N, K, A, LDA, TAU, C, LDC, WORK, LWORK, INFO)
INTEGER | M, N, K, LDA, LDC, LWORK, INFO
COMPLEX (KIND=nag_wp) | A(LDA,*), TAU(*), C(LDC,*), WORK(max(1,LWORK))
CHARACTER(1) | SIDE, TRANS
The routine may be called by its LAPACK name zunmqr.

3 Description

F08AUF (ZUNMQR) is intended to be used after a call to F08ASF (ZGEQRF), F08BSF (ZGEQPF) or F08BTF (ZGEQP3), which perform a QR factorization of a complex matrix A. The unitary matrix Q is represented as a product of elementary reflectors.
This routine may be used to form one of the matrix products
QC , QH C , CQ ​ or ​ C QH ,
overwriting the result on C (which may be any complex rectangular matrix).
A common application of this routine is in solving linear least squares problems, as described in the F08 Chapter Introduction and illustrated in Section 10 in F08ASF (ZGEQRF).

4 References

Golub G H and Van Loan C F (1996) Matrix Computations (3rd Edition) Johns Hopkins University Press, Baltimore

5 Arguments

1:   SIDE – CHARACTER(1)Input
On entry: indicates how Q or QH is to be applied to C.
SIDE='L'
Q or QH is applied to C from the left.
SIDE='R'
Q or QH is applied to C from the right.
Constraint: SIDE='L' or 'R'.
2:   TRANS – CHARACTER(1)Input
On entry: indicates whether Q or QH is to be applied to C.
TRANS='N'
Q is applied to C.
TRANS='C'
QH is applied to C.
Constraint: TRANS='N' or 'C'.
3:   M – INTEGERInput
On entry: m, the number of rows of the matrix C.
Constraint: M≥0.
4:   N – INTEGERInput
On entry: n, the number of columns of the matrix C.
Constraint: N≥0.
5:   K – INTEGERInput
On entry: k, the number of elementary reflectors whose product defines the matrix Q.
Constraints:
  • if SIDE='L', M≥ K≥ 0 ;
  • if SIDE='R', N≥ K≥ 0 .
6:   A LDA* – COMPLEX (KIND=nag_wp) arrayInput
Note: the second dimension of the array A must be at least max 1,K.
On entry: details of the vectors which define the elementary reflectors, as returned by F08ASF (ZGEQRF), F08BSF (ZGEQPF) or F08BTF (ZGEQP3).
7:   LDA – INTEGERInput
On entry: the first dimension of the array A as declared in the (sub)program from which F08AUF (ZUNMQR) is called.
Constraints:
  • if SIDE='L', LDA≥ max 1,M ;
  • if SIDE='R', LDA≥ max 1,N .
8:   TAU* – COMPLEX (KIND=nag_wp) arrayInput
Note: the dimension of the array TAU must be at least max 1,K.
On entry: further details of the elementary reflectors, as returned by F08ASF (ZGEQRF), F08BSF (ZGEQPF) or F08BTF (ZGEQP3).
9:   C LDC* – COMPLEX (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array C must be at least max 1,N.
On entry: the m by n matrix C.
On exit: C is overwritten by QC or QH C or CQ or C QH as specified by SIDE and TRANS.
10:   LDC – INTEGERInput
On entry: the first dimension of the array C as declared in the (sub)program from which F08AUF (ZUNMQR) is called.
Constraint: LDC≥max 1,M.
11:   WORK max 1,LWORK – COMPLEX (KIND=nag_wp) arrayWorkspace
On exit: if INFO=0, the real part of WORK 1 contains the minimum value of LWORK required for optimal performance.
12:   LWORK – INTEGERInput
On entry: the dimension of the array WORK as declared in the (sub)program from which F08AUF (ZUNMQR) is called.
If LWORK=-1, a workspace query is assumed; the routine only calculates the optimal size of the WORK array, returns this value as the first entry of the WORK array, and no error message related to LWORK is issued.
Suggested value: for optimal performance, LWORK≥N×nb if SIDE='L' and at least M×nb if SIDE='R', where nb is the optimal block size.
Constraints:
  • if SIDE='L', LWORK≥max 1,N or LWORK=-1;
  • if SIDE='R', LWORK≥max 1,M or LWORK=-1.
13:   INFO – INTEGEROutput
On exit: INFO=0 unless the routine detects an error (see Section 6).

6 Error Indicators and Warnings

INFO<0
If INFO=-i, argument i had an illegal value.
If INFO=-999, dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.
An explanatory message is output, and execution of the program is terminated.

7 Accuracy

The computed result differs from the exact result by a matrix E such that
E 2 = O ε C 2 ,
where ε is the machine precision.

8 Parallelism and Performance

F08AUF (ZUNMQR) is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
F08AUF (ZUNMQR) makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The total number of real floating-point operations is approximately 8 nk 2 m-k if SIDE='L' and 8 mk 2 n-k if SIDE='R'.
The real analogue of this routine is F08AGF (DORMQR).

10 Example

See Section 10 in F08ASF (ZGEQRF).
F08 Chapter Contents
F08 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F08AVF (ZGELQF) : NAG Library, Mark 26

F08 Chapter Contents
F08 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F08AVF (ZGELQF)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F08AVF (ZGELQF) computes the LQ factorization of a complex m by n matrix.

2 Specification

SUBROUTINE F08AVF ( M, N, A, LDA, TAU, WORK, LWORK, INFO)
INTEGER | M, N, LDA, LWORK, INFO
COMPLEX (KIND=nag_wp) | A(LDA,*), TAU(*), WORK(max(1,LWORK))
The routine may be called by its LAPACK name zgelqf.

3 Description

F08AVF (ZGELQF) forms the LQ factorization of an arbitrary rectangular complex m by n matrix. No pivoting is performed.
If m≤n, the factorization is given by:
A = L 0 Q
where L is an m by m lower triangular matrix (with real diagonal elements) and Q is an n by n unitary matrix. It is sometimes more convenient to write the factorization as
A = L 0 Q 1 Q 2
which reduces to
A = L Q 1 ,
where Q 1 consists of the first m rows of Q, and Q 2 the remaining n-m rows.
If m>n, L is trapezoidal, and the factorization can be written
A = L 1 L 2 Q
where L 1 is lower triangular and L 2 is rectangular.
The LQ factorization of A is essentially the same as the QR factorization of AH, since
A = L 0 Q⇔AH= QH LH 0 .
The matrix Q is not formed explicitly but is represented as a product of min m,n elementary reflectors (see the F08 Chapter Introduction for details). Routines are provided to work with Q in this representation (see Section 9).
Note also that for any k<m, the information returned in the first k rows of the array A represents an LQ factorization of the first k rows of the original matrix A.

4 References

None.

5 Arguments

1:   M – INTEGERInput
On entry: m, the number of rows of the matrix A.
Constraint: M≥0.
2:   N – INTEGERInput
On entry: n, the number of columns of the matrix A.
Constraint: N≥0.
3:   A LDA* – COMPLEX (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array A must be at least max 1,N.
On entry: the m by n matrix A.
On exit: if m≤n, the elements above the diagonal are overwritten by details of the unitary matrix Q and the lower triangle is overwritten by the corresponding elements of the m by m lower triangular matrix L.
If m>n, the strictly upper triangular part is overwritten by details of the unitary matrix Q and the remaining elements are overwritten by the corresponding elements of the m by n lower trapezoidal matrix L.
The diagonal elements of L are real.
4:   LDA – INTEGERInput
On entry: the first dimension of the array A as declared in the (sub)program from which F08AVF (ZGELQF) is called.
Constraint: LDA≥max 1,M.
5:   TAU* – COMPLEX (KIND=nag_wp) arrayOutput
Note: the dimension of the array TAU must be at least max 1,min M,N.
On exit: further details of the unitary matrix Q.
6:   WORK max 1,LWORK – COMPLEX (KIND=nag_wp) arrayWorkspace
On exit: if INFO=0, the real part of WORK 1 contains the minimum value of LWORK required for optimal performance.
7:   LWORK – INTEGERInput
On entry: the dimension of the array WORK as declared in the (sub)program from which F08AVF (ZGELQF) is called.
If LWORK=-1, a workspace query is assumed; the routine only calculates the optimal size of the WORK array, returns this value as the first entry of the WORK array, and no error message related to LWORK is issued.
Suggested value: for optimal performance, LWORK≥M×nb, where nb is the optimal block size.
Constraint: LWORK≥max 1,M or LWORK=-1.
8:   INFO – INTEGEROutput
On exit: INFO=0 unless the routine detects an error (see Section 6).

6 Error Indicators and Warnings

INFO<0
If INFO=-i, argument i had an illegal value. An explanatory message is output, and execution of the program is terminated.

7 Accuracy

The computed factorization is the exact factorization of a nearby matrix A+E, where
E 2 = O ε A 2 ,
and ε is the machine precision.

8 Parallelism and Performance

F08AVF (ZGELQF) makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The total number of real floating-point operations is approximately 83 m 2 3 n-m if m≤n or 83 n 2 3 m-n if m>n.
To form the unitary matrix Q F08AVF (ZGELQF) may be followed by a call to F08AWF (ZUNGLQ):
CALL ZUNGLQ(N,N,MIN(M,N),A,LDA,TAU,WORK,LWORK,INFO)
but note that the first dimension of the array A, specified by the argument LDA, must be at least N, which may be larger than was required by F08AVF (ZGELQF).
When m≤n, it is often only the first m rows of Q that are required, and they may be formed by the call:
CALL ZUNGLQ(M,N,M,A,LDA,TAU,WORK,LWORK,INFO)
To apply Q to an arbitrary complex rectangular matrix C, F08AVF (ZGELQF) may be followed by a call to F08AXF (ZUNMLQ). For example,
CALL ZUNMLQ('Left','Conjugate Transpose',M,P,MIN(M,N),A,LDA,TAU, &
             C,LDC,WORK,LWORK,INFO)
forms the matrix product C=QH C, where C is m by p.
The real analogue of this routine is F08AHF (DGELQF).

10 Example

This example finds the minimum norm solutions of the under-determined systems of linear equations
A x 1= b 1   and   A x 2= b 2
where b 1 and b 2 are the columns of the matrix B,
A = 0.28-0.36 i 0.50-0.86 i -0.77-0.48 i 1.58+0.66 i -0.50-1.10 i -1.21+0.76 i -0.32-0.24 i -0.27-1.15 i 0.36-0.51 i -0.07+1.33 i -0.75+0.47 i -0.08+1.01 i
and
B = -1.35+0.19 i 4.83-2.67 i 9.41-3.56 i -7.28+3.34 i -7.57+6.93 i 0.62+4.53 i .

10.1 Program Text

Program Text (f08avfe.f90)

10.2 Program Data

Program Data (f08avfe.d)

10.3 Program Results

Program Results (f08avfe.r)

F08 Chapter Contents
F08 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F08AWF (ZUNGLQ) : NAG Library, Mark 26

F08 Chapter Contents
F08 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F08AWF (ZUNGLQ)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F08AWF (ZUNGLQ) generates all or part of the complex unitary matrix Q from an LQ factorization computed by F08AVF (ZGELQF).

2 Specification

SUBROUTINE F08AWF ( M, N, K, A, LDA, TAU, WORK, LWORK, INFO)
INTEGER | M, N, K, LDA, LWORK, INFO
COMPLEX (KIND=nag_wp) | A(LDA,*), TAU(*), WORK(max(1,LWORK))
The routine may be called by its LAPACK name zunglq.

3 Description

F08AWF (ZUNGLQ) is intended to be used after a call to F08AVF (ZGELQF), which performs an LQ factorization of a complex matrix A. The unitary matrix Q is represented as a product of elementary reflectors.
This routine may be used to generate Q explicitly as a square matrix, or to form only its leading rows.
Usually Q is determined from the LQ factorization of a p by n matrix A with p≤n. The whole of Q may be computed by:
CALL ZUNGLQ(N,N,P,A,LDA,TAU,WORK,LWORK,INFO)
(note that the array A must have at least n rows) or its leading p rows by:
CALL ZUNGLQ(P,N,P,A,LDA,TAU,WORK,LWORK,INFO)
The rows of Q returned by the last call form an orthonormal basis for the space spanned by the rows of A; thus F08AVF (ZGELQF) followed by F08AWF (ZUNGLQ) can be used to orthogonalize the rows of A.
The information returned by the LQ factorization routines also yields the LQ factorization of the leading k rows of A, where k<p. The unitary matrix arising from this factorization can be computed by:
CALL ZUNGLQ(N,N,K,A,LDA,TAU,WORK,LWORK,INFO)
or its leading k rows by:
CALL ZUNGLQ(K,N,K,A,LDA,TAU,WORK,LWORK,INFO)

4 References

Golub G H and Van Loan C F (1996) Matrix Computations (3rd Edition) Johns Hopkins University Press, Baltimore

5 Arguments

1:   M – INTEGERInput
On entry: m, the number of rows of the matrix Q.
Constraint: M≥0.
2:   N – INTEGERInput
On entry: n, the number of columns of the matrix Q.
Constraint: N≥M.
3:   K – INTEGERInput
On entry: k, the number of elementary reflectors whose product defines the matrix Q.
Constraint: M≥K≥0.
4:   A LDA* – COMPLEX (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array A must be at least max 1,N.
On entry: details of the vectors which define the elementary reflectors, as returned by F08AVF (ZGELQF).
On exit: the m by n matrix Q.
5:   LDA – INTEGERInput
On entry: the first dimension of the array A as declared in the (sub)program from which F08AWF (ZUNGLQ) is called.
Constraint: LDA≥max 1,M.
6:   TAU* – COMPLEX (KIND=nag_wp) arrayInput
Note: the dimension of the array TAU must be at least max 1,K.
On entry: further details of the elementary reflectors, as returned by F08AVF (ZGELQF).
7:   WORK max 1,LWORK – COMPLEX (KIND=nag_wp) arrayWorkspace
On exit: if INFO=0, the real part of WORK 1 contains the minimum value of LWORK required for optimal performance.
8:   LWORK – INTEGERInput
On entry: the dimension of the array WORK as declared in the (sub)program from which F08AWF (ZUNGLQ) is called.
If LWORK=-1, a workspace query is assumed; the routine only calculates the optimal size of the WORK array, returns this value as the first entry of the WORK array, and no error message related to LWORK is issued.
Suggested value: for optimal performance, LWORK≥M×nb, where nb is the optimal block size.
Constraint: LWORK≥max 1,M or LWORK=-1.
9:   INFO – INTEGEROutput
On exit: INFO=0 unless the routine detects an error (see Section 6).

6 Error Indicators and Warnings

INFO<0
If INFO=-i, argument i had an illegal value. An explanatory message is output, and execution of the program is terminated.

7 Accuracy

The computed matrix Q differs from an exactly unitary matrix by a matrix E such that
E 2 = O ε ,
where ε is the machine precision.

8 Parallelism and Performance

F08AWF (ZUNGLQ) makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The total number of real floating-point operations is approximately 16 mnk-8 m+n k 2 + 163 k 3 ; when m=k, the number is approximately 83 m 2 3 n-m .
The real analogue of this routine is F08AJF (DORGLQ).

10 Example

This example forms the leading 4 rows of the unitary matrix Q from the LQ factorization of the matrix A, where
A = 0.28-0.36 i 0.50-0.86 i -0.77-0.48 i 1.58+0.66 i -0.50-1.10 i -1.21+0.76 i -0.32-0.24 i -0.27-1.15 i 0.36-0.51 i -0.07+1.33 i -0.75+0.47 i -0.08+1.01 i .
The rows of Q form an orthonormal basis for the space spanned by the rows of A.

10.1 Program Text

Program Text (f08awfe.f90)

10.2 Program Data

Program Data (f08awfe.d)

10.3 Program Results

Program Results (f08awfe.r)

F08 Chapter Contents
F08 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F08AXF (ZUNMLQ) : NAG Library, Mark 26

F08 Chapter Contents
F08 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F08AXF (ZUNMLQ)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
10 Example

1 Purpose

F08AXF (ZUNMLQ) multiplies an arbitrary complex matrix C by the complex unitary matrix Q from an LQ factorization computed by F08AVF (ZGELQF).

2 Specification

SUBROUTINE F08AXF ( SIDE, TRANS, M, N, K, A, LDA, TAU, C, LDC, WORK, LWORK, INFO)
INTEGER | M, N, K, LDA, LDC, LWORK, INFO
COMPLEX (KIND=nag_wp) | A(LDA,*), TAU(*), C(LDC,*), WORK(max(1,LWORK))
CHARACTER(1) | SIDE, TRANS
The routine may be called by its LAPACK name zunmlq.

3 Description

F08AXF (ZUNMLQ) is intended to be used after a call to F08AVF (ZGELQF), which performs an LQ factorization of a complex matrix A. The unitary matrix Q is represented as a product of elementary reflectors.
This routine may be used to form one of the matrix products
QC , QH C , CQ ​ or ​ C QH ,
overwriting the result on C (which may be any complex rectangular matrix).

4 References

Golub G H and Van Loan C F (1996) Matrix Computations (3rd Edition) Johns Hopkins University Press, Baltimore

5 Arguments

1:   SIDE – CHARACTER(1)Input
On entry: indicates how Q or QH is to be applied to C.
SIDE='L'
Q or QH is applied to C from the left.
SIDE='R'
Q or QH is applied to C from the right.
Constraint: SIDE='L' or 'R'.
2:   TRANS – CHARACTER(1)Input
On entry: indicates whether Q or QH is to be applied to C.
TRANS='N'
Q is applied to C.
TRANS='C'
QH is applied to C.
Constraint: TRANS='N' or 'C'.
3:   M – INTEGERInput
On entry: m, the number of rows of the matrix C.
Constraint: M≥0.
4:   N – INTEGERInput
On entry: n, the number of columns of the matrix C.
Constraint: N≥0.
5:   K – INTEGERInput
On entry: k, the number of elementary reflectors whose product defines the matrix Q.
Constraints:
  • if SIDE='L', M≥ K≥ 0 ;
  • if SIDE='R', N≥ K≥ 0 .
6:   A LDA* – COMPLEX (KIND=nag_wp) arrayInput
Note: the second dimension of the array A must be at least max 1,M if SIDE='L' and at least max 1,N if SIDE='R'.
On entry: details of the vectors which define the elementary reflectors, as returned by F08AVF (ZGELQF).
7:   LDA – INTEGERInput
On entry: the first dimension of the array A as declared in the (sub)program from which F08AXF (ZUNMLQ) is called.
Constraint: LDA≥max 1,K.
8:   TAU* – COMPLEX (KIND=nag_wp) arrayInput
Note: the dimension of the array TAU must be at least max 1,K.
On entry: further details of the elementary reflectors, as returned by F08AVF (ZGELQF).
9:   C LDC* – COMPLEX (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array C must be at least max 1,N.
On entry: the m by n matrix C.
On exit: C is overwritten by QC or QH C or CQ or C QH as specified by SIDE and TRANS.
10:   LDC – INTEGERInput
On entry: the first dimension of the array C as declared in the (sub)program from which F08AXF (ZUNMLQ) is called.
Constraint: LDC≥max 1,M.
11:   WORK max 1,LWORK – COMPLEX (KIND=nag_wp) arrayWorkspace
On exit: if INFO=0, the real part of WORK 1 contains the minimum value of LWORK required for optimal performance.
12:   LWORK – INTEGERInput
On entry: the dimension of the array WORK as declared in the (sub)program from which F08AXF (ZUNMLQ) is called.
If LWORK=-1, a workspace query is assumed; the routine only calculates the optimal size of the WORK array, returns this value as the first entry of the WORK array, and no error message related to LWORK is issued.
Suggested value: for optimal performance, LWORK≥N×nb if SIDE='L' and at least M×nb if SIDE='R', where nb is the optimal block size.
Constraints:
  • if SIDE='L', LWORK≥max 1,N or LWORK=-1;
  • if SIDE='R', LWORK≥max 1,M or LWORK=-1.
13:   INFO – INTEGEROutput
On exit: INFO=0 unless the routine detects an error (see Section 6).

6 Error Indicators and Warnings

INFO<0
If INFO=-i, argument i had an illegal value.
If INFO=-999, dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.
An explanatory message is output, and execution of the program is terminated.

7 Accuracy

The computed result differs from the exact result by a matrix E such that
E 2 = O ε C 2 ,
where ε is the machine precision.

8 Parallelism and Performance

F08AXF (ZUNMLQ) makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The total number of real floating-point operations is approximately 8 nk 2 m-k if SIDE='L' and 8 mk 2 n-k if SIDE='R'.
The real analogue of this routine is F08AKF (DORMLQ).

10 Example

See Section 10 in F08AVF (ZGELQF).
F08 Chapter Contents
F08 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F08BAF (DGELSY) : NAG Library, Mark 26

F08 Chapter Contents
F08 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F08BAF (DGELSY)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F08BAF (DGELSY) computes the minimum norm solution to a real linear least squares problem
minx b-Ax 2
using a complete orthogonal factorization of A. A is an m by n matrix which may be rank-deficient. Several right-hand side vectors b and solution vectors x can be handled in a single call.

2 Specification

SUBROUTINE F08BAF ( M, N, NRHS, A, LDA, B, LDB, JPVT, RCOND, RANK, WORK, LWORK, INFO)
INTEGER | M, N, NRHS, LDA, LDB, JPVT(*), RANK, LWORK, INFO
REAL (KIND=nag_wp) | A(LDA,*), B(LDB,*), RCOND, WORK(max(1,LWORK))
The routine may be called by its LAPACK name dgelsy.

3 Description

The right-hand side vectors are stored as the columns of the m by r matrix B and the solution vectors in the n by r matrix X.
F08BAF (DGELSY) first computes a QR factorization with column pivoting
AP= Q R 11 R 12 0 R 22 ,
with R 11 defined as the largest leading sub-matrix whose estimated condition number is less than 1/RCOND. The order of R 11, RANK, is the effective rank of A.
Then, R 22 is considered to be negligible, and R 12 is annihilated by orthogonal transformations from the right, arriving at the complete orthogonal factorization
AP= Q T 11 0 0 0 Z .
The minimum norm solution is then
X = P ZT T 11-1 Q 1 T b 0
where Q 1 consists of the first RANK columns of Q.

4 References

Anderson E, Bai Z, Bischof C, Blackford S, Demmel J, Dongarra J J, Du Croz J J, Greenbaum A, Hammarling S, McKenney A and Sorensen D (1999) LAPACK Users' Guide (3rd Edition) SIAM, Philadelphia http://www.netlib.org/lapack/lug
Golub G H and Van Loan C F (1996) Matrix Computations (3rd Edition) Johns Hopkins University Press, Baltimore

5 Arguments

1:   M – INTEGERInput
On entry: m, the number of rows of the matrix A.
Constraint: M≥0.
2:   N – INTEGERInput
On entry: n, the number of columns of the matrix A.
Constraint: N≥0.
3:   NRHS – INTEGERInput
On entry: r, the number of right-hand sides, i.e., the number of columns of the matrices B and X.
Constraint: NRHS≥0.
4:   A LDA* – REAL (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array A must be at least max 1,N.
On entry: the m by n matrix A.
On exit: A has been overwritten by details of its complete orthogonal factorization.
5:   LDA – INTEGERInput
On entry: the first dimension of the array A as declared in the (sub)program from which F08BAF (DGELSY) is called.
Constraint: LDA≥max 1,M.
6:   B LDB* – REAL (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array B must be at least max 1,NRHS.
On entry: the m by r right-hand side matrix B.
On exit: the n by r solution matrix X.
7:   LDB – INTEGERInput
On entry: the first dimension of the array B as declared in the (sub)program from which F08BAF (DGELSY) is called.
Constraint: LDB≥max 1,M,N.
8:   JPVT* – INTEGER arrayInput/Output
Note: the dimension of the array JPVT must be at least max 1,N.
On entry: if JPVT i≠0, the ith column of A is permuted to the front of AP, otherwise column i is a free column.
On exit: if JPVT i=k, then the ith column of AP was the kth column of A.
9:   RCOND – REAL (KIND=nag_wp)Input
On entry: used to determine the effective rank of A, which is defined as the order of the largest leading triangular sub-matrix R 11 in the QR factorization of A, whose estimated condition number is <1/RCOND.
Suggested value: if the condition number of A is not known then RCOND=ε/2 (where ε is machine precision, see X02AJF) is a good choice. Negative values or values less than machine precision should be avoided since this will cause A to have an effective rank=min M,N that could be larger than its actual rank, leading to meaningless results.
10:   RANK – INTEGEROutput
On exit: the effective rank of A, i.e., the order of the sub-matrix R 11. This is the same as the order of the sub-matrix T 11 in the complete orthogonal factorization of A.
11:   WORK max 1,LWORK – REAL (KIND=nag_wp) arrayWorkspace
On exit: if INFO=0, WORK 1 contains the minimum value of LWORK required for optimal performance.
12:   LWORK – INTEGERInput
On entry: the dimension of the array WORK as declared in the (sub)program from which F08BAF (DGELSY) is called.
If LWORK=-1, a workspace query is assumed; the routine only calculates the optimal size of the WORK array, returns this value as the first entry of the WORK array, and no error message related to LWORK is issued.
Suggested value: for optimal performance,
LWORK ≥ max k + 2 × N + nb × N+1 , 2 × k + nb × NRHS ,
where k = min M,N and nb is the optimal block size.
Constraint: LWORK ≥ k + max 2×k,N+1,k+NRHS , where ​ k = min M,N or
LWORK=-1.
13:   INFO – INTEGEROutput
On exit: INFO=0 unless the routine detects an error (see Section 6).

6 Error Indicators and Warnings

INFO<0
If INFO=-i, argument i had an illegal value. An explanatory message is output, and execution of the program is terminated.

7 Accuracy

See Section 4.5 of Anderson et al. (1999) for details of error bounds.

8 Parallelism and Performance

F08BAF (DGELSY) is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
F08BAF (DGELSY) makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The complex analogue of this routine is F08BNF (ZGELSY).

10 Example

This example solves the linear least squares problem
minx b-Ax 2
for the solution, x, of minimum norm, where
A = -0.09 0.14 -0.46 0.68 1.29 -1.56 0.20 0.29 1.09 0.51 -1.48 -0.43 0.89 -0.71 -0.96 -1.09 0.84 0.77 2.11 -1.27 0.08 0.55 -1.13 0.14 1.74 -1.59 -0.72 1.06 1.24 0.34   and   b= 7.4 4.2 -8.3 1.8 8.6 2.1 .
A tolerance of 0.01 is used to determine the effective rank of A.
Note that the block size (NB) of 64 assumed in this example is not realistic for such a small problem, but should be suitable for large problems.

10.1 Program Text

Program Text (f08bafe.f90)

10.2 Program Data

Program Data (f08bafe.d)

10.3 Program Results

Program Results (f08bafe.r)

F08 Chapter Contents
F08 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F08BBF (DTPQRT) : NAG Library, Mark 26

F08 Chapter Contents
F08 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F08BBF (DTPQRT)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F08BBF (DTPQRT) computes the QR factorization of a real m+n by n triangular-pentagonal matrix.

2 Specification

SUBROUTINE F08BBF ( M, N, L, NB, A, LDA, B, LDB, T, LDT, WORK, INFO)
INTEGER | M, N, L, NB, LDA, LDB, LDT, INFO
REAL (KIND=nag_wp) | A(LDA,*), B(LDB,*), T(LDT,*), WORK(*)
The routine may be called by its LAPACK name dtpqrt.

3 Description

F08BBF (DTPQRT) forms the QR factorization of a real m+n by n triangular-pentagonal matrix C,
C= A B
where A is an upper triangular n by n matrix and B is an m by n pentagonal matrix consisting of an m-l by n rectangular matrix B 1 on top of an l by n upper trapezoidal matrix B 2:
B= B 1 B 2 .
The upper trapezoidal matrix B 2 consists of the first l rows of an n by n upper triangular matrix, where 0≤l≤min m,n. If l=0, B is m by n rectangular; if l=n and m=n, B is upper triangular.
A recursive, explicitly blocked, QR factorization (see F08ABF (DGEQRT)) is performed on the matrix C. The upper triangular matrix R, details of the orthogonal matrix Q, and further details (the block reflector factors) of Q are returned.
Typically the matrix A or B 2 contains the matrix R from the QR factorization of a subproblem and F08BBF (DTPQRT) performs the QR update operation from the inclusion of matrix B 1.
For example, consider the QR factorization of an l by n matrix B^ with l<n: B^ = Q^R^ , R^ = R 1^ R 2^ , where R 1^ is l by l upper triangular and R 2^ is n-l by n rectangular (this can be performed by F08ABF (DGEQRT)). Given an initial least-squares problem B^ X^ = Y^ where X and Y are l by nrhs matrices, we have R^ X^ = Q^T Y^ .
Now, adding an additional m-l rows to the original system gives the augmented least squares problem
BX=Y
where B is an m by n matrix formed by adding m-l rows on top of R^ and Y is an m by nrhs matrix formed by adding m-l rows on top of Q^T Y^.
F08BBF (DTPQRT) can then be used to perform the QR factorization of the pentagonal matrix B; the n by n matrix A will be zero on input and contain R on output.
In the case where B^ is r by n, r≥n, R^ is n by n upper triangular (forming A) on top of r-n rows of zeros (forming first r-n rows of B). Augmentation is then performed by adding rows to the bottom of B with l=0.

4 References

Elmroth E and Gustavson F (2000) Applying Recursion to Serial and Parallel QR Factorization Leads to Better Performance IBM Journal of Research and Development. (Volume 44) 4 605–624
Golub G H and Van Loan C F (2012) Matrix Computations (4th Edition) Johns Hopkins University Press, Baltimore

5 Arguments

1:   M – INTEGERInput
On entry: m, the number of rows of the matrix B.
Constraint: M≥0.
2:   N – INTEGERInput
On entry: n, the number of columns of the matrix B and the order of the upper triangular matrix A.
Constraint: N≥0.
3:   L – INTEGERInput
On entry: l, the number of rows of the trapezoidal part of B (i.e., B 2).
Constraint: 0≤L≤min M,N.
4:   NB – INTEGERInput
On entry: the explicitly chosen block-size to be used in the algorithm for computing the QR factorization. See Section 9 for details.
Constraints:
  • NB≥1;
  • if N>0, NB≤N.
5:   A LDA* – REAL (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array A must be at least max 1,N.
On entry: the n by n upper triangular matrix A.
On exit: the upper triangle is overwritten by the corresponding elements of the n by n upper triangular matrix R.
6:   LDA – INTEGERInput
On entry: the first dimension of the array A as declared in the (sub)program from which F08BBF (DTPQRT) is called.
Constraint: LDA≥max 1,N.
7:   B LDB* – REAL (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array B must be at least max 1,N.
On entry: the m by n pentagonal matrix B composed of an m-l by n rectangular matrix B 1 above an l by n upper trapezoidal matrix B 2.
On exit: details of the orthogonal matrix Q.
8:   LDB – INTEGERInput
On entry: the first dimension of the array B as declared in the (sub)program from which F08BBF (DTPQRT) is called.
Constraint: LDB≥max 1,M.
9:   T LDT* – REAL (KIND=nag_wp) arrayOutput
Note: the second dimension of the array T must be at least N.
On exit: further details of the orthogonal matrix Q. The number of blocks is b=kNB, where k=min m,n and each block is of order NB except for the last block, which is of order k-b-1×NB. For each of the blocks, an upper triangular block reflector factor is computed: T 1,T 2,…,Tb. These are stored in the NB by n matrix T as T=T 1|T 2|…|Tb.
10:   LDT – INTEGERInput
On entry: the first dimension of the array T as declared in the (sub)program from which F08BBF (DTPQRT) is called.
Constraint: LDT≥NB.
11:   WORK* – REAL (KIND=nag_wp) arrayWorkspace
Note: the dimension of the array WORK must be at least NB×N.
12:   INFO – INTEGEROutput
On exit: INFO=0 unless the routine detects an error (see Section 6).

6 Error Indicators and Warnings

INFO<0
If INFO=-i, argument i had an illegal value. An explanatory message is output, and execution of the program is terminated.

7 Accuracy

The computed factorization is the exact factorization of a nearby matrix A+E, where
E 2 = O ε A 2 ,
and ε is the machine precision.

8 Parallelism and Performance

F08BBF (DTPQRT) makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The total number of floating-point operations is approximately 23 n 2 3 m-n if m≥n or 23 m 2 3 n-m if m<n.
The block size, NB, used by F08BBF (DTPQRT) is supplied explicitly through the interface. For moderate and large sizes of matrix, the block size can have a marked effect on the efficiency of the algorithm with the optimal value being dependent on problem size and platform. A value of NB=64≪min m,n is likely to achieve good efficiency and it is unlikely that an optimal value would exceed 340.
To apply Q to an arbitrary real rectangular matrix C, F08BBF (DTPQRT) may be followed by a call to F08BCF (DTPMQRT). For example,
CALL DTPMQRT('Left','Transpose',M,P,N,L,NB,B,LDB, &
              T,LDT,C,LDC,C(n+1,1),LDC,WORK,INFO)
forms C=QT C, where C is m+n by p.
To form the orthogonal matrix Q explicitly set p=m+n, initialize C to the identity matrix and make a call to F08BCF (DTPMQRT) as above.

10 Example

This example finds the basic solutions for the linear least squares problems
minimize⁡ A xi - bi 2 ,   i=1,2
where b 1 and b 2 are the columns of the matrix B,
A = -0.57 -1.28 -0.39 0.25 -1.93 1.08 -0.31 -2.14 2.30 0.24 0.40 -0.35 -1.93 0.64 -0.66 0.08 0.15 0.30 0.15 -2.13 -0.02 1.03 -1.43 0.50   and  B= -2.67 0.41 -0.55 -3.10 3.34 -4.01 -0.77 2.76 0.48 -6.17 4.10 0.21 .
A QR factorization is performed on the first 4 rows of A using F08ABF (DGEQRT) after which the first 4 rows of B are updated by applying QT using F08ACF (DGEMQRT). The remaining row is added by performing a QR update using F08BBF (DTPQRT); B is updated by applying the new QT using F08BCF (DTPMQRT); the solution is finally obtained by triangular solve using R from the updated QR.

10.1 Program Text

Program Text (f08bbfe.f90)

10.2 Program Data

Program Data (f08bbfe.d)

10.3 Program Results

Program Results (f08bbfe.r)

F08 Chapter Contents
F08 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F08BCF (DTPMQRT) : NAG Library, Mark 26

F08 Chapter Contents
F08 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F08BCF (DTPMQRT)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
10 Example

1 Purpose

F08BCF (DTPMQRT) multiplies an arbitrary real matrix C by the real orthogonal matrix Q from a QR factorization computed by F08BBF (DTPQRT).

2 Specification

SUBROUTINE F08BCF ( SIDE, TRANS, M, N, K, L, NB, V, LDV, T, LDT, C1, LDC1, C2, LDC2, WORK, INFO)
INTEGER | M, N, K, L, NB, LDV, LDT, LDC1, LDC2, INFO
REAL (KIND=nag_wp) | V(LDV,*), T(LDT,*), C1(LDC1,*), C2(LDC2,*), WORK(*)
CHARACTER(1) | SIDE, TRANS
The routine may be called by its LAPACK name dtpmqrt.

3 Description

F08BCF (DTPMQRT) is intended to be used after a call to F08BBF (DTPQRT) which performs a QR factorization of a triangular-pentagonal matrix containing an upper triangular matrix A over a pentagonal matrix B. The orthogonal matrix Q is represented as a product of elementary reflectors.
This routine may be used to form the matrix products
QC , QT C , CQ ​ or ​ C QT ,
where the real rectangular mc by nc matrix C is split into component matrices C 1 and C 2.
If Q is being applied from the left (QC or QT C) then
C = C 1 C 2
where C 1 is k by nc, C 2 is mv by nc, mc=k+mv is fixed and mv is the number of rows of the matrix V containing the elementary reflectors (i.e., M as passed to F08BBF (DTPQRT)); the number of columns of V is nv (i.e., N as passed to F08BBF (DTPQRT)).
If Q is being applied from the right (CQ or C QT) then
C = C 1 C 2
where C 1 is mc by k, and C 2 is mc by mv and nc=k+mv is fixed.
The matrices C 1 and C 2 are overwriten by the result of the matrix product.
A common application of this routine is in updating the solution of a linear least squares problem as illustrated in Section 10 in F08BBF (DTPQRT).

4 References

Golub G H and Van Loan C F (2012) Matrix Computations (4th Edition) Johns Hopkins University Press, Baltimore

5 Arguments

1:   SIDE – CHARACTER(1)Input
On entry: indicates how Q or QT is to be applied to C.
SIDE='L'
Q or QT is applied to C from the left.
SIDE='R'
Q or QT is applied to C from the right.
Constraint: SIDE='L' or 'R'.
2:   TRANS – CHARACTER(1)Input
On entry: indicates whether Q or QT is to be applied to C.
TRANS='N'
Q is applied to C.
TRANS='T'
QT is applied to C.
Constraint: TRANS='N' or 'T'.
3:   M – INTEGERInput
On entry: the number of rows of the matrix C 2, that is,
if SIDE='L'
then mv, the number of rows of the matrix V;
if SIDE='R'
then mc, the number of rows of the matrix C.
Constraint: M≥0.
4:   N – INTEGERInput
On entry: the number of columns of the matrix C 2, that is,
if SIDE='L'
then nc, the number of columns of the matrix C;
if SIDE='R'
then nv, the number of columns of the matrix V.
Constraint: N≥0.
5:   K – INTEGERInput
On entry: k, the number of elementary reflectors whose product defines the matrix Q.
Constraint: K≥0.
6:   L – INTEGERInput
On entry: l, the number of rows of the upper trapezoidal part of the pentagonal composite matrix V, passed (as B) in a previous call to F08BBF (DTPQRT). This must be the same value used in the previous call to F08BBF (DTPQRT) (see L in F08BBF (DTPQRT)).
Constraint: 0≤L≤K.
7:   NB – INTEGERInput
On entry: nb, the blocking factor used in a previous call to F08BBF (DTPQRT) to compute the QR factorization of a triangular-pentagonal matrix containing composite matrices A and B.
Constraints:
  • NB≥1;
  • if K>0, NB≤K.
8:   V LDV* – REAL (KIND=nag_wp) arrayInput
Note: the second dimension of the array LDV must be at least max 1,K.
On entry: the mv by nv matrix V; this should remain unchanged from the array B returned by a previous call to F08BBF (DTPQRT).
9:   LDV – INTEGERInput
On entry: the first dimension of the array V as declared in the (sub)program from which F08BCF (DTPMQRT) is called.
Constraints:
  • if SIDE='L', LDV≥ max 1,M ;
  • if SIDE='R', LDV≥ max 1,N .
10:   T LDT* – REAL (KIND=nag_wp) arrayInput
Note: the second dimension of the array T must be at least max 1,K.
On entry: this must remain unchanged from a previous call to F08BBF (DTPQRT) (see T in F08BBF (DTPQRT)).
11:   LDT – INTEGERInput
On entry: the first dimension of the array T as declared in the (sub)program from which F08BCF (DTPMQRT) is called.
Constraint: LDT≥NB.
12:   C1 LDC1* – REAL (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array C1 must be at least max 1,N if SIDE='L' and at least max 1,K if SIDE='R'.
On entry: C 1, the first part of the composite matrix C:
if SIDE='L'
then C1 contains the first k rows of C;
if SIDE='R'
then C1 contains the first k columns of C.
On exit: C1 is overwritten by the corresponding block of QC or QT C or CQ or C QT.
13:   LDC1 – INTEGERInput
On entry: the first dimension of the array C1 as declared in the (sub)program from which F08BCF (DTPMQRT) is called.
Constraints:
  • if SIDE='L', LDC1≥ max 1,K ;
  • if SIDE='R', LDC1≥ max 1,M .
14:   C2 LDC2* – REAL (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array C2 must be at least max 1,N.
On entry: C 2, the second part of the composite matrix C.
if SIDE='L'
then C2 contains the remaining mv rows of C;
if SIDE='R'
then C2 contains the remaining mv columns of C;
On exit: C2 is overwritten by the corresponding block of QC or QT C or CQ or C QT.
15:   LDC2 – INTEGERInput
On entry: the first dimension of the array C2 as declared in the (sub)program from which F08BCF (DTPMQRT) is called.
Constraint: LDC2≥ max 1,M .
16:   WORK* – REAL (KIND=nag_wp) arrayWorkspace
Note: the dimension of the array WORK must be at least N×NB if SIDE='L' and at least M×NB if SIDE='R'.
17:   INFO – INTEGEROutput
On exit: INFO=0 unless the routine detects an error (see Section 6).

6 Error Indicators and Warnings

INFO<0
If INFO=-i, argument i had an illegal value. An explanatory message is output, and execution of the program is terminated.

7 Accuracy

The computed result differs from the exact result by a matrix E such that
E 2 = O ε C 2 ,
where ε is the machine precision.

8 Parallelism and Performance

F08BCF (DTPMQRT) makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The total number of floating-point operations is approximately 2 nk 2 m-k if SIDE='L' and 2 mk 2 n-k if SIDE='R'.
The complex analogue of this routine is F08BQF (ZTPMQRT).

10 Example

See Section 10 in F08BBF (DTPQRT).
F08 Chapter Contents
F08 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F08BEF (DGEQPF) : NAG Library, Mark 26

F08 Chapter Contents
F08 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F08BEF (DGEQPF)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F08BEF (DGEQPF) computes the QR factorization, with column pivoting, of a real m by n matrix.

2 Specification

SUBROUTINE F08BEF ( M, N, A, LDA, JPVT, TAU, WORK, INFO)
INTEGER | M, N, LDA, JPVT(*), INFO
REAL (KIND=nag_wp) | A(LDA,*), TAU(min(M,N)), WORK(3*N)
The routine may be called by its LAPACK name dgeqpf.

3 Description

F08BEF (DGEQPF) forms the QR factorization, with column pivoting, of an arbitrary rectangular real m by n matrix.
If m≥n, the factorization is given by:
AP= Q R 0 ,
where R is an n by n upper triangular matrix, Q is an m by m orthogonal matrix and P is an n by n permutation matrix. It is sometimes more convenient to write the factorization as
AP= Q 1 Q 2 R 0 ,
which reduces to
AP= Q 1 R ,
where Q 1 consists of the first n columns of Q, and Q 2 the remaining m-n columns.
If m<n, R is trapezoidal, and the factorization can be written
AP= Q R 1 R 2 ,
where R 1 is upper triangular and R 2 is rectangular.
The matrix Q is not formed explicitly but is represented as a product of min m,n elementary reflectors (see the F08 Chapter Introduction for details). Routines are provided to work with Q in this representation (see Section 9).
Note also that for any k<n, the information returned in the first k columns of the array A represents a QR factorization of the first k columns of the permuted matrix AP.
The routine allows specified columns of A to be moved to the leading columns of AP at the start of the factorization and fixed there. The remaining columns are free to be interchanged so that at the ith stage the pivot column is chosen to be the column which maximizes the 2-norm of elements i to m over columns i to n.

4 References

Golub G H and Van Loan C F (1996) Matrix Computations (3rd Edition) Johns Hopkins University Press, Baltimore

5 Arguments

1:   M – INTEGERInput
On entry: m, the number of rows of the matrix A.
Constraint: M≥0.
2:   N – INTEGERInput
On entry: n, the number of columns of the matrix A.
Constraint: N≥0.
3:   A LDA* – REAL (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array A must be at least max 1,N.
On entry: the m by n matrix A.
On exit: if m≥n, the elements below the diagonal are overwritten by details of the orthogonal matrix Q and the upper triangle is overwritten by the corresponding elements of the n by n upper triangular matrix R.
If m<n, the strictly lower triangular part is overwritten by details of the orthogonal matrix Q and the remaining elements are overwritten by the corresponding elements of the m by n upper trapezoidal matrix R.
4:   LDA – INTEGERInput
On entry: the first dimension of the array A as declared in the (sub)program from which F08BEF (DGEQPF) is called.
Constraint: LDA≥max 1,M.
5:   JPVT* – INTEGER arrayInput/Output
Note: the dimension of the array JPVT must be at least max 1,N.
On entry: if JPVT i≠0, then the i th column of A is moved to the beginning of AP before the decomposition is computed and is fixed in place during the computation. Otherwise, the i th column of A is a free column (i.e., one which may be interchanged during the computation with any other free column).
On exit: details of the permutation matrix P. More precisely, if JPVT i=k, then the kth column of A is moved to become the i th column of AP; in other words, the columns of AP are the columns of A in the order JPVT 1,JPVT 2,…,JPVT n.
6:   TAU min M,N – REAL (KIND=nag_wp) arrayOutput
On exit: further details of the orthogonal matrix Q.
7:   WORK 3×N – REAL (KIND=nag_wp) arrayWorkspace
8:   INFO – INTEGEROutput
On exit: INFO=0 unless the routine detects an error (see Section 6).

6 Error Indicators and Warnings

INFO<0
If INFO=-i, argument i had an illegal value. An explanatory message is output, and execution of the program is terminated.

7 Accuracy

The computed factorization is the exact factorization of a nearby matrix A+E, where
E 2 = O ε A 2 ,
and ε is the machine precision.

8 Parallelism and Performance

F08BEF (DGEQPF) makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The total number of floating-point operations is approximately 23 n 2 3 m-n if m≥n or 23 m 2 3 n-m if m<n.
To form the orthogonal matrix Q F08BEF (DGEQPF) may be followed by a call to F08AFF (DORGQR):
CALL DORGQR(M,M,MIN(M,N),A,LDA,TAU,WORK,LWORK,INFO)
but note that the second dimension of the array A must be at least M, which may be larger than was required by F08BEF (DGEQPF).
When m≥n, it is often only the first n columns of Q that are required, and they may be formed by the call:
CALL DORGQR(M,N,N,A,LDA,TAU,WORK,LWORK,INFO)
To apply Q to an arbitrary real rectangular matrix C, F08BEF (DGEQPF) may be followed by a call to F08AGF (DORMQR). For example,
CALL DORMQR('Left','Transpose',M,P,MIN(M,N),A,LDA,TAU,C,LDC,WORK, &
              LWORK,INFO)
forms C=QT C, where C is m by p.
To compute a QR factorization without column pivoting, use F08AEF (DGEQRF).
The complex analogue of this routine is F08BSF (ZGEQPF).

10 Example

This example finds the basic solutions for the linear least squares problems
minimize⁡ A xi - bi 2 ,   i=1,2
where b 1 and b 2 are the columns of the matrix B,
A = -0.09 0.14 -0.46 0.68 1.29 -1.56 0.20 0.29 1.09 0.51 -1.48 -0.43 0.89 -0.71 -0.96 -1.09 0.84 0.77 2.11 -1.27 0.08 0.55 -1.13 0.14 1.74 -1.59 -0.72 1.06 1.24 0.34   and  B= -0.01 -0.04 0.04 -0.03 0.05 0.01 -0.03 -0.02 0.02 0.05 -0.06 0.07 .
Here A is approximately rank-deficient, and hence it is preferable to use F08BEF (DGEQPF) rather than F08AEF (DGEQRF).

10.1 Program Text

Program Text (f08befe.f90)

10.2 Program Data

Program Data (f08befe.d)

10.3 Program Results

Program Results (f08befe.r)

F08 Chapter Contents
F08 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F08BFF (DGEQP3) : NAG Library, Mark 26

F08 Chapter Contents
F08 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F08BFF (DGEQP3)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F08BFF (DGEQP3) computes the QR factorization, with column pivoting, of a real m by n matrix.

2 Specification

SUBROUTINE F08BFF ( M, N, A, LDA, JPVT, TAU, WORK, LWORK, INFO)
INTEGER | M, N, LDA, JPVT(*), LWORK, INFO
REAL (KIND=nag_wp) | A(LDA,*), TAU(*), WORK(max(1,LWORK))
The routine may be called by its LAPACK name dgeqp3.

3 Description

F08BFF (DGEQP3) forms the QR factorization, with column pivoting, of an arbitrary rectangular real m by n matrix.
If m≥n, the factorization is given by:
AP= Q R 0 ,
where R is an n by n upper triangular matrix, Q is an m by m orthogonal matrix and P is an n by n permutation matrix. It is sometimes more convenient to write the factorization as
AP= Q 1 Q 2 R 0 ,
which reduces to
AP= Q 1 R ,
where Q 1 consists of the first n columns of Q, and Q 2 the remaining m-n columns.
If m<n, R is trapezoidal, and the factorization can be written
AP= Q R 1 R 2 ,
where R 1 is upper triangular and R 2 is rectangular.
The matrix Q is not formed explicitly but is represented as a product of min m,n elementary reflectors (see the F08 Chapter Introduction for details). Routines are provided to work with Q in this representation (see Section 9).
Note also that for any k<n, the information returned in the first k columns of the array A represents a QR factorization of the first k columns of the permuted matrix AP.
The routine allows specified columns of A to be moved to the leading columns of AP at the start of the factorization and fixed there. The remaining columns are free to be interchanged so that at the ith stage the pivot column is chosen to be the column which maximizes the 2-norm of elements i to m over columns i to n.

4 References

Anderson E, Bai Z, Bischof C, Blackford S, Demmel J, Dongarra J J, Du Croz J J, Greenbaum A, Hammarling S, McKenney A and Sorensen D (1999) LAPACK Users' Guide (3rd Edition) SIAM, Philadelphia http://www.netlib.org/lapack/lug
Golub G H and Van Loan C F (1996) Matrix Computations (3rd Edition) Johns Hopkins University Press, Baltimore

5 Arguments

1:   M – INTEGERInput
On entry: m, the number of rows of the matrix A.
Constraint: M≥0.
2:   N – INTEGERInput
On entry: n, the number of columns of the matrix A.
Constraint: N≥0.
3:   A LDA* – REAL (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array A must be at least max 1,N.
On entry: the m by n matrix A.
On exit: if m≥n, the elements below the diagonal are overwritten by details of the orthogonal matrix Q and the upper triangle is overwritten by the corresponding elements of the n by n upper triangular matrix R.
If m<n, the strictly lower triangular part is overwritten by details of the orthogonal matrix Q and the remaining elements are overwritten by the corresponding elements of the m by n upper trapezoidal matrix R.
4:   LDA – INTEGERInput
On entry: the first dimension of the array A as declared in the (sub)program from which F08BFF (DGEQP3) is called.
Constraint: LDA≥max 1,M.
5:   JPVT* – INTEGER arrayInput/Output
Note: the dimension of the array JPVT must be at least max 1,N.
On entry: if JPVT j≠0, then the j th column of A is moved to the beginning of AP before the decomposition is computed and is fixed in place during the computation. Otherwise, the j th column of A is a free column (i.e., one which may be interchanged during the computation with any other free column).
On exit: details of the permutation matrix P. More precisely, if JPVT j=k, then the kth column of A is moved to become the j th column of AP; in other words, the columns of AP are the columns of A in the order JPVT 1,JPVT 2,…,JPVT n.
6:   TAU* – REAL (KIND=nag_wp) arrayOutput
Note: the dimension of the array TAU must be at least max 1,min M,N.
On exit: the scalar factors of the elementary reflectors.
7:   WORK max 1,LWORK – REAL (KIND=nag_wp) arrayWorkspace
On exit: if INFO=0, WORK 1 contains the minimum value of LWORK required for optimal performance.
8:   LWORK – INTEGERInput
On entry: the dimension of the array WORK as declared in the (sub)program from which F08BFF (DGEQP3) is called.
If LWORK=-1, a workspace query is assumed; the routine only calculates the optimal size of the WORK array, returns this value as the first entry of the WORK array, and no error message related to LWORK is issued.
Suggested value: for optimal performance, LWORK≥2×N+N+1×nb, where nb is the optimal block size.
Constraint: LWORK≥3×N+1 or LWORK=-1.
9:   INFO – INTEGEROutput
On exit: INFO=0 unless the routine detects an error (see Section 6).

6 Error Indicators and Warnings

INFO<0
If INFO=-i, argument i had an illegal value. An explanatory message is output, and execution of the program is terminated.

7 Accuracy

The computed factorization is the exact factorization of a nearby matrix A+E, where
E 2 = O ε A 2 ,
and ε is the machine precision.

8 Parallelism and Performance

F08BFF (DGEQP3) is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
F08BFF (DGEQP3) makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The total number of floating-point operations is approximately 23 n 2 3 m-n if m≥n or 23 m 2 3 n-m if m<n.
To form the orthogonal matrix Q F08BFF (DGEQP3) may be followed by a call to F08AFF (DORGQR):
CALL DORGQR(M,M,MIN(M,N),A,LDA,TAU,WORK,LWORK,INFO)
but note that the second dimension of the array A must be at least M, which may be larger than was required by F08BFF (DGEQP3).
When m≥n, it is often only the first n columns of Q that are required, and they may be formed by the call:
CALL DORGQR(M,N,N,A,LDA,TAU,WORK,LWORK,INFO)
To apply Q to an arbitrary real rectangular matrix C, F08BFF (DGEQP3) may be followed by a call to F08AGF (DORMQR). For example,
CALL DORMQR('Left','Transpose',M,P,MIN(M,N),A,LDA,TAU,C,LDC,WORK, &
              LWORK,INFO)
forms C=QT C, where C is m by p.
To compute a QR factorization without column pivoting, use F08AEF (DGEQRF).
The complex analogue of this routine is F08BTF (ZGEQP3).

10 Example

This example solves the linear least squares problems
minx bj - A xj 2 ,   j=1,2
for the basic solutions x 1 and x 2, where
A = -0.09 0.14 -0.46 0.68 1.29 -1.56 0.20 0.29 1.09 0.51 -1.48 -0.43 0.89 -0.71 -0.96 -1.09 0.84 0.77 2.11 -1.27 0.08 0.55 -1.13 0.14 1.74 -1.59 -0.72 1.06 1.24 0.34   and  B= 7.4 2.7 4.2 -3.0 -8.3 -9.6 1.8 1.1 8.6 4.0 2.1 -5.7
and bj is the jth column of the matrix B. The solution is obtained by first obtaining a QR factorization with column pivoting of the matrix A. A tolerance of 0.01 is used to estimate the rank of A from the upper triangular factor, R.
Note that the block size (NB) of 64 assumed in this example is not realistic for such a small problem, but should be suitable for large problems.

10.1 Program Text

Program Text (f08bffe.f90)

10.2 Program Data

Program Data (f08bffe.d)

10.3 Program Results

Program Results (f08bffe.r)

F08 Chapter Contents
F08 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F08BHF (DTZRZF) : NAG Library, Mark 26

F08 Chapter Contents
F08 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F08BHF (DTZRZF)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F08BHF (DTZRZF) reduces the m by n (m≤n) real upper trapezoidal matrix A to upper triangular form by means of orthogonal transformations.

2 Specification

SUBROUTINE F08BHF ( M, N, A, LDA, TAU, WORK, LWORK, INFO)
INTEGER | M, N, LDA, LWORK, INFO
REAL (KIND=nag_wp) | A(LDA,*), TAU(*), WORK(max(1,LWORK))
The routine may be called by its LAPACK name dtzrzf.

3 Description

The m by n (m≤n) real upper trapezoidal matrix A given by
A = R 1 R 2 ,
where R 1 is an m by m upper triangular matrix and R 2 is an m by n-m matrix, is factorized as
A = R 0 Z ,
where R is also an m by m upper triangular matrix and Z is an n by n orthogonal matrix.

4 References

Anderson E, Bai Z, Bischof C, Blackford S, Demmel J, Dongarra J J, Du Croz J J, Greenbaum A, Hammarling S, McKenney A and Sorensen D (1999) LAPACK Users' Guide (3rd Edition) SIAM, Philadelphia http://www.netlib.org/lapack/lug

5 Arguments

1:   M – INTEGERInput
On entry: m, the number of rows of the matrix A.
Constraint: M≥0.
2:   N – INTEGERInput
On entry: n, the number of columns of the matrix A.
Constraint: N≥0.
3:   A LDA* – REAL (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array A must be at least max 1,N.
On entry: the leading m by n upper trapezoidal part of the array A must contain the matrix to be factorized.
On exit: the leading m by m upper triangular part of A contains the upper triangular matrix R, and elements M+1 to N of the first m rows of A, with the array TAU, represent the orthogonal matrix Z as a product of m elementary reflectors (see Section 3.3.6 in the F08 Chapter Introduction).
4:   LDA – INTEGERInput
On entry: the first dimension of the array A as declared in the (sub)program from which F08BHF (DTZRZF) is called.
Constraint: LDA≥max 1,M.
5:   TAU* – REAL (KIND=nag_wp) arrayOutput
Note: the dimension of the array TAU must be at least max 1,M.
On exit: the scalar factors of the elementary reflectors.
6:   WORK max 1,LWORK – REAL (KIND=nag_wp) arrayWorkspace
On exit: if INFO=0, WORK 1 contains the minimum value of LWORK required for optimal performance.
7:   LWORK – INTEGERInput
On entry: the dimension of the array WORK as declared in the (sub)program from which F08BHF (DTZRZF) is called.
If LWORK=-1, a workspace query is assumed; the routine only calculates the optimal size of the WORK array, returns this value as the first entry of the WORK array, and no error message related to LWORK is issued.
Suggested value: for optimal performance, LWORK≥M×nb, where nb is the optimal block size.
Constraint: LWORK≥max 1,M or LWORK=-1.
8:   INFO – INTEGEROutput
On exit: INFO=0 unless the routine detects an error (see Section 6).

6 Error Indicators and Warnings

INFO<0
If INFO=-i, argument i had an illegal value. An explanatory message is output, and execution of the program is terminated.

7 Accuracy

The computed factorization is the exact factorization of a nearby matrix A+E, where
E 2 = O⁡ε A 2
and ε is the machine precision.

8 Parallelism and Performance

F08BHF (DTZRZF) makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The total number of floating-point operations is approximately 4 m 2 n-m.
The complex analogue of this routine is F08BVF (ZTZRZF).

10 Example

This example solves the linear least squares problems
minx bj - A xj 2 ,   j=1,2
for the minimum norm solutions x 1 and x 2, where bj is the jth column of the matrix B,
A = -0.09 0.14 -0.46 0.68 1.29 -1.56 0.20 0.29 1.09 0.51 -1.48 -0.43 0.89 -0.71 -0.96 -1.09 0.84 0.77 2.11 -1.27 0.08 0.55 -1.13 0.14 1.74 -1.59 -0.72 1.06 1.24 0.34   and   B= 7.4 2.7 4.2 -3.0 -8.3 -9.6 1.8 1.1 8.6 4.0 2.1 -5.7 .
The solution is obtained by first obtaining a QR factorization with column pivoting of the matrix A, and then the RZ factorization of the leading k by k part of R is computed, where k is the estimated rank of A. A tolerance of 0.01 is used to estimate the rank of A from the upper triangular factor, R.
Note that the block size (NB) of 64 assumed in this example is not realistic for such a small problem, but should be suitable for large problems.

10.1 Program Text

Program Text (f08bhfe.f90)

10.2 Program Data

Program Data (f08bhfe.d)

10.3 Program Results

Program Results (f08bhfe.r)

F08 Chapter Contents
F08 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F08BKF (DORMRZ) : NAG Library, Mark 26

F08 Chapter Contents
F08 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F08BKF (DORMRZ)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
10 Example

1 Purpose

F08BKF (DORMRZ) multiplies a general real m by n matrix C by the real orthogonal matrix Z from an RZ factorization computed by F08BHF (DTZRZF).

2 Specification

SUBROUTINE F08BKF ( SIDE, TRANS, M, N, K, L, A, LDA, TAU, C, LDC, WORK, LWORK, INFO)
INTEGER | M, N, K, L, LDA, LDC, LWORK, INFO
REAL (KIND=nag_wp) | A(LDA,*), TAU(*), C(LDC,*), WORK(max(1,LWORK))
CHARACTER(1) | SIDE, TRANS
The routine may be called by its LAPACK name dormrz.

3 Description

F08BKF (DORMRZ) is intended to be used following a call to F08BHF (DTZRZF), which performs an RZ factorization of a real upper trapezoidal matrix A and represents the orthogonal matrix Z as a product of elementary reflectors.
This routine may be used to form one of the matrix products
ZC ,   ZT C ,   CZ ,   C ZT ,
overwriting the result on C, which may be any real rectangular m by n matrix.

4 References

Anderson E, Bai Z, Bischof C, Blackford S, Demmel J, Dongarra J J, Du Croz J J, Greenbaum A, Hammarling S, McKenney A and Sorensen D (1999) LAPACK Users' Guide (3rd Edition) SIAM, Philadelphia http://www.netlib.org/lapack/lug

5 Arguments

1:   SIDE – CHARACTER(1)Input
On entry: indicates how Z or ZT is to be applied to C.
SIDE='L'
Z or ZT is applied to C from the left.
SIDE='R'
Z or ZT is applied to C from the right.
Constraint: SIDE='L' or 'R'.
2:   TRANS – CHARACTER(1)Input
On entry: indicates whether Z or ZT is to be applied to C.
TRANS='N'
Z is applied to C.
TRANS='T'
ZT is applied to C.
Constraint: TRANS='N' or 'T'.
3:   M – INTEGERInput
On entry: m, the number of rows of the matrix C.
Constraint: M≥0.
4:   N – INTEGERInput
On entry: n, the number of columns of the matrix C.
Constraint: N≥0.
5:   K – INTEGERInput
On entry: k, the number of elementary reflectors whose product defines the matrix Z.
Constraints:
  • if SIDE='L', M≥ K≥ 0 ;
  • if SIDE='R', N≥ K≥ 0 .
6:   L – INTEGERInput
On entry: l, the number of columns of the matrix A containing the meaningful part of the Householder reflectors.
Constraints:
  • if SIDE='L', M≥ L≥ 0 ;
  • if SIDE='R', N≥ L≥ 0 .
7:   A LDA* – REAL (KIND=nag_wp) arrayInput
Note: the second dimension of the array A must be at least max 1,M if SIDE='L' and at least max 1,N if SIDE='R'.
On entry: the ith row of A must contain the vector which defines the elementary reflector Hi, for i=1,2,…,k, as returned by F08BHF (DTZRZF).
8:   LDA – INTEGERInput
On entry: the first dimension of the array A as declared in the (sub)program from which F08BKF (DORMRZ) is called.
Constraint: LDA≥max 1,K.
9:   TAU* – REAL (KIND=nag_wp) arrayInput
Note: the dimension of the array TAU must be at least max 1,K.
On entry: TAU i must contain the scalar factor of the elementary reflector Hi, as returned by F08BHF (DTZRZF).
10:   C LDC* – REAL (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array C must be at least max 1,N.
On entry: the m by n matrix C.
On exit: C is overwritten by ZC or ZT C or CZ or ZT C as specified by SIDE and TRANS.
11:   LDC – INTEGERInput
On entry: the first dimension of the array C as declared in the (sub)program from which F08BKF (DORMRZ) is called.
Constraint: LDC≥max 1,M.
12:   WORK max 1,LWORK – REAL (KIND=nag_wp) arrayWorkspace
On exit: if INFO=0, WORK 1 contains the minimum value of LWORK required for optimal performance.
13:   LWORK – INTEGERInput
On entry: the dimension of the array WORK as declared in the (sub)program from which F08BKF (DORMRZ) is called.
If LWORK=-1, a workspace query is assumed; the routine only calculates the optimal size of the WORK array, returns this value as the first entry of the WORK array, and no error message related to LWORK is issued.
Suggested value: for optimal performance, LWORK≥N×nb if SIDE='L' and at least M×nb if SIDE='R', where nb is the optimal block size.
Constraints:
  • if SIDE='L', LWORK≥max 1,N or LWORK=-1;
  • if SIDE='R', LWORK≥max 1,M or LWORK=-1.
14:   INFO – INTEGEROutput
On exit: INFO=0 unless the routine detects an error (see Section 6).

6 Error Indicators and Warnings

INFO<0
If INFO=-i, argument i had an illegal value.
If INFO=-999, dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.
An explanatory message is output, and execution of the program is terminated.

7 Accuracy

The computed result differs from the exact result by a matrix E such that
E 2 = O⁡ε C 2
where ε is the machine precision.

8 Parallelism and Performance

F08BKF (DORMRZ) makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The total number of floating-point operations is approximately 4 nlk if SIDE='L' and 4 mlk if SIDE='R'.
The complex analogue of this routine is F08BXF (ZUNMRZ).

10 Example

See Section 10 in F08BHF (DTZRZF).
F08 Chapter Contents
F08 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F08BNF (ZGELSY) : NAG Library, Mark 26

F08 Chapter Contents
F08 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F08BNF (ZGELSY)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F08BNF (ZGELSY) computes the minimum norm solution to a complex linear least squares problem
minx b-Ax 2
using a complete orthogonal factorization of A. A is an m by n matrix which may be rank-deficient. Several right-hand side vectors b and solution vectors x can be handled in a single call.

2 Specification

SUBROUTINE F08BNF ( M, N, NRHS, A, LDA, B, LDB, JPVT, RCOND, RANK, WORK, LWORK, RWORK, INFO)
INTEGER | M, N, NRHS, LDA, LDB, JPVT(*), RANK, LWORK, INFO
REAL (KIND=nag_wp) | RCOND, RWORK(*)
COMPLEX (KIND=nag_wp) | A(LDA,*), B(LDB,*), WORK(max(1,LWORK))
The routine may be called by its LAPACK name zgelsy.

3 Description

The right-hand side vectors are stored as the columns of the m by r matrix B and the solution vectors in the n by r matrix X.
F08BNF (ZGELSY) first computes a QR factorization with column pivoting
AP= Q R 11 R 12 0 R 22 ,
with R 11 defined as the largest leading sub-matrix whose estimated condition number is less than 1/RCOND. The order of R 11, RANK, is the effective rank of A.
Then, R 22 is considered to be negligible, and R 12 is annihilated by orthogonal transformations from the right, arriving at the complete orthogonal factorization
AP= Q T 11 0 0 0 Z .
The minimum norm solution is then
X = P ZH T 11-1 Q 1 H b 0
where Q 1 consists of the first RANK columns of Q.

4 References

Anderson E, Bai Z, Bischof C, Blackford S, Demmel J, Dongarra J J, Du Croz J J, Greenbaum A, Hammarling S, McKenney A and Sorensen D (1999) LAPACK Users' Guide (3rd Edition) SIAM, Philadelphia http://www.netlib.org/lapack/lug
Golub G H and Van Loan C F (1996) Matrix Computations (3rd Edition) Johns Hopkins University Press, Baltimore

5 Arguments

1:   M – INTEGERInput
On entry: m, the number of rows of the matrix A.
Constraint: M≥0.
2:   N – INTEGERInput
On entry: n, the number of columns of the matrix A.
Constraint: N≥0.
3:   NRHS – INTEGERInput
On entry: r, the number of right-hand sides, i.e., the number of columns of the matrices B and X.
Constraint: NRHS≥0.
4:   A LDA* – COMPLEX (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array A must be at least max 1,N.
On entry: the m by n matrix A.
On exit: A has been overwritten by details of its complete orthogonal factorization.
5:   LDA – INTEGERInput
On entry: the first dimension of the array A as declared in the (sub)program from which F08BNF (ZGELSY) is called.
Constraint: LDA≥max 1,M.
6:   B LDB* – COMPLEX (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array B must be at least max 1,NRHS.
On entry: the m by r right-hand side matrix B.
On exit: the n by r solution matrix X.
7:   LDB – INTEGERInput
On entry: the first dimension of the array B as declared in the (sub)program from which F08BNF (ZGELSY) is called.
Constraint: LDB≥max 1,M,N.
8:   JPVT* – INTEGER arrayInput/Output
Note: the dimension of the array JPVT must be at least max 1,N.
On entry: if JPVT i≠0, the ith column of A is permuted to the front of AP, otherwise column i is a free column.
On exit: if JPVT i=k, then the ith column of AP was the kth column of A.
9:   RCOND – REAL (KIND=nag_wp)Input
On entry: used to determine the effective rank of A, which is defined as the order of the largest leading triangular sub-matrix R 11 in the QR factorization of A, whose estimated condition number is <1/RCOND.
Suggested value: if the condition number of A is not known then RCOND=ε/2 (where ε is machine precision, see X02AJF) is a good choice. Negative values or values less than machine precision should be avoided since this will cause A to have an effective rank=min M,N that could be larger than its actual rank, leading to meaningless results.
10:   RANK – INTEGEROutput
On exit: the effective rank of A, i.e., the order of the sub-matrix R 11. This is the same as the order of the sub-matrix T 11 in the complete orthogonal factorization of A.
11:   WORK max 1,LWORK – COMPLEX (KIND=nag_wp) arrayWorkspace
On exit: if INFO=0, the real part of WORK 1 contains the minimum value of LWORK required for optimal performance.
12:   LWORK – INTEGERInput
On entry: the dimension of the array WORK as declared in the (sub)program from which F08BNF (ZGELSY) is called.
If LWORK=-1, a workspace query is assumed; the routine only calculates the optimal size of the WORK array, returns this value as the first entry of the WORK array, and no error message related to LWORK is issued.
Suggested value: for optimal performance,
LWORK ≥ max k + 2 × N + nb × N+1 , 2 × k + nb × NRHS ,
where k = min M,N and nb is the optimal block size.
Constraint: LWORK ≥ k + max 2×k,N+1,k+NRHS , where ​ k = min M,N or
LWORK=-1.
13:   RWORK* – REAL (KIND=nag_wp) arrayWorkspace
Note: the dimension of the array RWORK must be at least max 1,2×N.
14:   INFO – INTEGEROutput
On exit: INFO=0 unless the routine detects an error (see Section 6).

6 Error Indicators and Warnings

INFO<0
If INFO=-i, argument i had an illegal value. An explanatory message is output, and execution of the program is terminated.

7 Accuracy

See Section 4.5 of Anderson et al. (1999) for details of error bounds.

8 Parallelism and Performance

F08BNF (ZGELSY) is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
F08BNF (ZGELSY) makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The real analogue of this routine is F08BAF (DGELSY).

10 Example

This example solves the linear least squares problem
minx b-Ax 2
for the solution, x, of minimum norm, where
A = 0.47-0.34 i -0.40+0.54 i 0.60+0.01 i 0.80-1.02 i -0.32-0.23 i -0.05+0.20 i -0.26-0.44 i -0.43+0.17 i 0.35-0.60 i -0.52-0.34 i 0.87-0.11 i -0.34-0.09 i 0.89+0.71 i -0.45-0.45 i -0.02-0.57 i 1.14-0.78 i -0.19+0.06 i 0.11-0.85 i 1.44+0.80 i 0.07+1.14 i
and
b = -1.08-2.59 i -2.61-1.49 i 3.13-3.61 i 7.33-8.01 i 9.12+7.63 i .
A tolerance of 0.01 is used to determine the effective rank of A.
Note that the block size (NB) of 64 assumed in this example is not realistic for such a small problem, but should be suitable for large problems.

10.1 Program Text

Program Text (f08bnfe.f90)

10.2 Program Data

Program Data (f08bnfe.d)

10.3 Program Results

Program Results (f08bnfe.r)

F08 Chapter Contents
F08 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F08BPF (ZTPQRT) : NAG Library, Mark 26

F08 Chapter Contents
F08 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F08BPF (ZTPQRT)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F08BPF (ZTPQRT) computes the QR factorization of a complex m+n by n triangular-pentagonal matrix.

2 Specification

SUBROUTINE F08BPF ( M, N, L, NB, A, LDA, B, LDB, T, LDT, WORK, INFO)
INTEGER | M, N, L, NB, LDA, LDB, LDT, INFO
COMPLEX (KIND=nag_wp) | A(LDA,*), B(LDB,*), T(LDT,*), WORK(*)
The routine may be called by its LAPACK name ztpqrt.

3 Description

F08BPF (ZTPQRT) forms the QR factorization of a complex m+n by n triangular-pentagonal matrix C,
C= A B
where A is an upper triangular n by n matrix and B is an m by n pentagonal matrix consisting of an m-l by n rectangular matrix B 1 on top of an l by n upper trapezoidal matrix B 2:
B= B 1 B 2 .
The upper trapezoidal matrix B 2 consists of the first l rows of an n by n upper triangular matrix, where 0≤l≤min m,n. If l=0, B is m by n rectangular; if l=n and m=n, B is upper triangular.
A recursive, explicitly blocked, QR factorization (see F08APF (ZGEQRT)) is performed on the matrix C. The upper triangular matrix R, details of the unitary matrix Q, and further details (the block reflector factors) of Q are returned.
Typically the matrix A or B 2 contains the matrix R from the QR factorization of a subproblem and F08BPF (ZTPQRT) performs the QR update operation from the inclusion of matrix B 1.
For example, consider the QR factorization of an l by n matrix B^ with l<n: B^ = Q^R^ , R^ = R 1^ R 2^ , where R 1^ is l by l upper triangular and R 2^ is n-l by n rectangular (this can be performed by F08APF (ZGEQRT)). Given an initial least-squares problem B^ X^ = Y^ where X and Y are l by nrhs matrices, we have R^ X^ = Q^H Y^ .
Now, adding an additional m-l rows to the original system gives the augmented least squares problem
BX=Y
where B is an m by n matrix formed by adding m-l rows on top of R^ and Y is an m by nrhs matrix formed by adding m-l rows on top of Q^H Y^.
F08BPF (ZTPQRT) can then be used to perform the QR factorization of the pentagonal matrix B; the n by n matrix A will be zero on input and contain R on output.
In the case where B^ is r by n, r≥n, R^ is n by n upper triangular (forming A) on top of r-n rows of zeros (forming first r-n rows of B). Augmentation is then performed by adding rows to the bottom of B with l=0.

4 References

Elmroth E and Gustavson F (2000) Applying Recursion to Serial and Parallel QR Factorization Leads to Better Performance IBM Journal of Research and Development. (Volume 44) 4 605–624
Golub G H and Van Loan C F (2012) Matrix Computations (4th Edition) Johns Hopkins University Press, Baltimore

5 Arguments

1:   M – INTEGERInput
On entry: m, the number of rows of the matrix B.
Constraint: M≥0.
2:   N – INTEGERInput
On entry: n, the number of columns of the matrix B and the order of the upper triangular matrix A.
Constraint: N≥0.
3:   L – INTEGERInput
On entry: l, the number of rows of the trapezoidal part of B (i.e., B 2).
Constraint: 0≤L≤min M,N.
4:   NB – INTEGERInput
On entry: the explicitly chosen block-size to be used in the algorithm for computing the QR factorization. See Section 9 for details.
Constraints:
  • NB≥1;
  • if N>0, NB≤N.
5:   A LDA* – COMPLEX (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array A must be at least max 1,N.
On entry: the n by n upper triangular matrix A.
On exit: the upper triangle is overwritten by the corresponding elements of the n by n upper triangular matrix R.
6:   LDA – INTEGERInput
On entry: the first dimension of the array A as declared in the (sub)program from which F08BPF (ZTPQRT) is called.
Constraint: LDA≥max 1,N.
7:   B LDB* – COMPLEX (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array B must be at least max 1,N.
On entry: the m by n pentagonal matrix B composed of an m-l by n rectangular matrix B 1 above an l by n upper trapezoidal matrix B 2.
On exit: details of the unitary matrix Q.
8:   LDB – INTEGERInput
On entry: the first dimension of the array B as declared in the (sub)program from which F08BPF (ZTPQRT) is called.
Constraint: LDB≥max 1,M.
9:   T LDT* – COMPLEX (KIND=nag_wp) arrayOutput
Note: the second dimension of the array T must be at least N.
On exit: further details of the unitary matrix Q. The number of blocks is b=kNB, where k=min m,n and each block is of order NB except for the last block, which is of order k-b-1×NB. For each of the blocks, an upper triangular block reflector factor is computed: T 1,T 2,…,Tb. These are stored in the NB by n matrix T as T=T 1|T 2|…|Tb.
10:   LDT – INTEGERInput
On entry: the first dimension of the array T as declared in the (sub)program from which F08BPF (ZTPQRT) is called.
Constraint: LDT≥NB.
11:   WORK* – COMPLEX (KIND=nag_wp) arrayWorkspace
Note: the dimension of the array WORK must be at least NB×N.
12:   INFO – INTEGEROutput
On exit: INFO=0 unless the routine detects an error (see Section 6).

6 Error Indicators and Warnings

INFO<0
If INFO=-i, argument i had an illegal value. An explanatory message is output, and execution of the program is terminated.

7 Accuracy

The computed factorization is the exact factorization of a nearby matrix A+E, where
E 2 = O ε A 2 ,
and ε is the machine precision.

8 Parallelism and Performance

F08BPF (ZTPQRT) makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The total number of floating-point operations is approximately 23 n 2 3 m-n if m≥n or 23 m 2 3 n-m if m<n.
The block size, NB, used by F08BPF (ZTPQRT) is supplied explicitly through the interface. For moderate and large sizes of matrix, the block size can have a marked effect on the efficiency of the algorithm with the optimal value being dependent on problem size and platform. A value of NB=64≪min m,n is likely to achieve good efficiency and it is unlikely that an optimal value would exceed 340.
To apply Q to an arbitrary complex rectangular matrix C, F08BPF (ZTPQRT) may be followed by a call to F08BQF (ZTPMQRT). For example,
CALL ZTPMQRT('Left','Transpose',M,P,N,L,NB,B,LDB, &
              T,LDT,C,LDC,C(n+1,1),LDC,WORK,INFO)
forms C=QH C, where C is m+n by p.
To form the unitary matrix Q explicitly set p=m+n, initialize C to the identity matrix and make a call to F08BQF (ZTPMQRT) as above.

10 Example

This example finds the basic solutions for the linear least squares problems
minimize⁡ A xi - bi 2 ,   i=1,2
where b 1 and b 2 are the columns of the matrix B,
A = 0.96-0.81 i -0.03+0.96 i -0.91+2.06 i -0.05+0.41 i -0.98+1.98 i -1.20+0.19 i -0.66+0.42 i -0.81+0.56 i 0.62-0.46 i 1.01+0.02 i 0.63-0.17 i -1.11+0.60 i -0.37+0.38 i 0.19-0.54 i -0.98-0.36 i 0.22-0.20 i 0.83+0.51 i 0.20+0.01 i -0.17-0.46 i 1.47+1.59 i 1.08-0.28 i 0.20-0.12 i -0.07+1.23 i 0.26+0.26 i   and
B= -2.09+1.93 i 3.26-2.70 i 3.34-3.53 i -6.22+1.16 i -4.94-2.04 i 7.94-3.13 i 0.17+4.23 i 1.04-4.26 i -5.19+3.63 i -2.31-2.12 i 0.98+2.53 i -1.39-4.05 i .
A QR factorization is performed on the first 4 rows of A using F08APF (ZGEQRT) after which the first 4 rows of B are updated by applying QT using F08AQF (ZGEMQRT). The remaining row is added by performing a QR update using F08BPF (ZTPQRT); B is updated by applying the new QT using F08BQF (ZTPMQRT); the solution is finally obtained by triangular solve using R from the updated QR.

10.1 Program Text

Program Text (f08bpfe.f90)

10.2 Program Data

Program Data (f08bpfe.d)

10.3 Program Results

Program Results (f08bpfe.r)

F08 Chapter Contents
F08 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F08BQF (ZTPMQRT) : NAG Library, Mark 26

F08 Chapter Contents
F08 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F08BQF (ZTPMQRT)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
10 Example

1 Purpose

F08BQF (ZTPMQRT) multiplies an arbitrary complex matrix C by the complex unitary matrix Q from a QR factorization computed by F08BPF (ZTPQRT).

2 Specification

SUBROUTINE F08BQF ( SIDE, TRANS, M, N, K, L, NB, V, LDV, T, LDT, C1, LDC1, C2, LDC2, WORK, INFO)
INTEGER | M, N, K, L, NB, LDV, LDT, LDC1, LDC2, INFO
COMPLEX (KIND=nag_wp) | V(LDV,*), T(LDT,*), C1(LDC1,*), C2(LDC2,*), WORK(*)
CHARACTER(1) | SIDE, TRANS
The routine may be called by its LAPACK name ztpmqrt.

3 Description

F08BQF (ZTPMQRT) is intended to be used after a call to F08BPF (ZTPQRT) which performs a QR factorization of a triangular-pentagonal matrix containing an upper triangular matrix A over a pentagonal matrix B. The unitary matrix Q is represented as a product of elementary reflectors.
This routine may be used to form the matrix products
QC , QH C , CQ ​ or ​ C QH ,
where the complex rectangular mc by nc matrix C is split into component matrices C 1 and C 2.
If Q is being applied from the left (QC or QH C) then
C = C 1 C 2
where C 1 is k by nc, C 2 is mv by nc, mc=k+mv is fixed and mv is the number of rows of the matrix V containing the elementary reflectors (i.e., M as passed to F08BPF (ZTPQRT)); the number of columns of V is nv (i.e., N as passed to F08BPF (ZTPQRT)).
If Q is being applied from the right (CQ or C QH) then
C = C 1 C 2
where C 1 is mc by k, and C 2 is mc by mv and nc=k+mv is fixed.
The matrices C 1 and C 2 are overwriten by the result of the matrix product.
A common application of this routine is in updating the solution of a linear least squares problem as illustrated in Section 10 in F08BPF (ZTPQRT).

4 References

Golub G H and Van Loan C F (2012) Matrix Computations (4th Edition) Johns Hopkins University Press, Baltimore

5 Arguments

1:   SIDE – CHARACTER(1)Input
On entry: indicates how Q or QH is to be applied to C.
SIDE='L'
Q or QH is applied to C from the left.
SIDE='R'
Q or QH is applied to C from the right.
Constraint: SIDE='L' or 'R'.
2:   TRANS – CHARACTER(1)Input
On entry: indicates whether Q or QH is to be applied to C.
TRANS='N'
Q is applied to C.
TRANS='C'
QH is applied to C.
Constraint: TRANS='N' or 'C'.
3:   M – INTEGERInput
On entry: the number of rows of the matrix C 2, that is,
if SIDE='L'
then mv, the number of rows of the matrix V;
if SIDE='R'
then mc, the number of rows of the matrix C.
Constraint: M≥0.
4:   N – INTEGERInput
On entry: the number of columns of the matrix C 2, that is,
if SIDE='L'
then nc, the number of columns of the matrix C;
if SIDE='R'
then nv, the number of columns of the matrix V.
Constraint: N≥0.
5:   K – INTEGERInput
On entry: k, the number of elementary reflectors whose product defines the matrix Q.
Constraint: K≥0.
6:   L – INTEGERInput
On entry: l, the number of rows of the upper trapezoidal part of the pentagonal composite matrix V, passed (as B) in a previous call to F08BPF (ZTPQRT). This must be the same value used in the previous call to F08BPF (ZTPQRT) (see L in F08BPF (ZTPQRT)).
Constraint: 0≤L≤K.
7:   NB – INTEGERInput
On entry: nb, the blocking factor used in a previous call to F08BPF (ZTPQRT) to compute the QR factorization of a triangular-pentagonal matrix containing composite matrices A and B.
Constraints:
  • NB≥1;
  • if K>0, NB≤K.
8:   V LDV* – COMPLEX (KIND=nag_wp) arrayInput
Note: the second dimension of the array LDV must be at least max 1,K.
On entry: the mv by nv matrix V; this should remain unchanged from the array B returned by a previous call to F08BPF (ZTPQRT).
9:   LDV – INTEGERInput
On entry: the first dimension of the array V as declared in the (sub)program from which F08BQF (ZTPMQRT) is called.
Constraints:
  • if SIDE='L', LDV≥ max 1,M ;
  • if SIDE='R', LDV≥ max 1,N .
10:   T LDT* – COMPLEX (KIND=nag_wp) arrayInput
Note: the second dimension of the array T must be at least max 1,K.
On entry: this must remain unchanged from a previous call to F08BPF (ZTPQRT) (see T in F08BPF (ZTPQRT)).
11:   LDT – INTEGERInput
On entry: the first dimension of the array T as declared in the (sub)program from which F08BQF (ZTPMQRT) is called.
Constraint: LDT≥NB.
12:   C1 LDC1* – COMPLEX (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array C1 must be at least max 1,N if SIDE='L' and at least max 1,K if SIDE='R'.
On entry: C 1, the first part of the composite matrix C:
if SIDE='L'
then C1 contains the first k rows of C;
if SIDE='R'
then C1 contains the first k columns of C.
On exit: C1 is overwritten by the corresponding block of QC or QH C or CQ or C QH.
13:   LDC1 – INTEGERInput
On entry: the first dimension of the array C1 as declared in the (sub)program from which F08BQF (ZTPMQRT) is called.
Constraints:
  • if SIDE='L', LDC1≥ max 1,K ;
  • if SIDE='R', LDC1≥ max 1,M .
14:   C2 LDC2* – COMPLEX (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array C2 must be at least max 1,N.
On entry: C 2, the second part of the composite matrix C.
if SIDE='L'
then C2 contains the remaining mv rows of C;
if SIDE='R'
then C2 contains the remaining mv columns of C;
On exit: C2 is overwritten by the corresponding block of QC or QH C or CQ or C QH.
15:   LDC2 – INTEGERInput
On entry: the first dimension of the array C2 as declared in the (sub)program from which F08BQF (ZTPMQRT) is called.
Constraint: LDC2≥ max 1,M .
16:   WORK* – COMPLEX (KIND=nag_wp) arrayWorkspace
Note: the dimension of the array WORK must be at least N×NB if SIDE='L' and at least M×NB if SIDE='R'.
17:   INFO – INTEGEROutput
On exit: INFO=0 unless the routine detects an error (see Section 6).

6 Error Indicators and Warnings

INFO<0
If INFO=-i, argument i had an illegal value. An explanatory message is output, and execution of the program is terminated.

7 Accuracy

The computed result differs from the exact result by a matrix E such that
E 2 = O ε C 2 ,
where ε is the machine precision.

8 Parallelism and Performance

F08BQF (ZTPMQRT) makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The total number of floating-point operations is approximately 2 nk 2 m-k if SIDE='L' and 2 mk 2 n-k if SIDE='R'.
The real analogue of this routine is F08BCF (DTPMQRT).

10 Example

See Section 10 in F08BPF (ZTPQRT).
F08 Chapter Contents
F08 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F08BSF (ZGEQPF) : NAG Library, Mark 26

F08 Chapter Contents
F08 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F08BSF (ZGEQPF)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F08BSF (ZGEQPF) computes the QR factorization, with column pivoting, of a complex m by n matrix.

2 Specification

SUBROUTINE F08BSF ( M, N, A, LDA, JPVT, TAU, WORK, RWORK, INFO)
INTEGER | M, N, LDA, JPVT(*), INFO
REAL (KIND=nag_wp) | RWORK(2*N)
COMPLEX (KIND=nag_wp) | A(LDA,*), TAU(min(M,N)), WORK(N)
The routine may be called by its LAPACK name zgeqpf.

3 Description

F08BSF (ZGEQPF) forms the QR factorization, with column pivoting, of an arbitrary rectangular complex m by n matrix.
If m≥n, the factorization is given by:
AP= Q R 0 ,
where R is an n by n upper triangular matrix (with real diagonal elements), Q is an m by m unitary matrix and P is an n by n permutation matrix. It is sometimes more convenient to write the factorization as
AP= Q 1 Q 2 R 0 ,
which reduces to
AP= Q 1 R ,
where Q 1 consists of the first n columns of Q, and Q 2 the remaining m-n columns.
If m<n, R is trapezoidal, and the factorization can be written
AP= Q R 1 R 2 ,
where R 1 is upper triangular and R 2 is rectangular.
The matrix Q is not formed explicitly but is represented as a product of min m,n elementary reflectors (see the F08 Chapter Introduction for details). Routines are provided to work with Q in this representation (see Section 9).
Note also that for any k<n, the information returned in the first k columns of the array A represents a QR factorization of the first k columns of the permuted matrix AP.
The routine allows specified columns of A to be moved to the leading columns of AP at the start of the factorization and fixed there. The remaining columns are free to be interchanged so that at the ith stage the pivot column is chosen to be the column which maximizes the 2-norm of elements i to m over columns i to n.

4 References

Golub G H and Van Loan C F (1996) Matrix Computations (3rd Edition) Johns Hopkins University Press, Baltimore

5 Arguments

1:   M – INTEGERInput
On entry: m, the number of rows of the matrix A.
Constraint: M≥0.
2:   N – INTEGERInput
On entry: n, the number of columns of the matrix A.
Constraint: N≥0.
3:   A LDA* – COMPLEX (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array A must be at least max 1,N.
On entry: the m by n matrix A.
On exit: if m≥n, the elements below the diagonal are overwritten by details of the unitary matrix Q and the upper triangle is overwritten by the corresponding elements of the n by n upper triangular matrix R.
If m<n, the strictly lower triangular part is overwritten by details of the unitary matrix Q and the remaining elements are overwritten by the corresponding elements of the m by n upper trapezoidal matrix R.
The diagonal elements of R are real.
4:   LDA – INTEGERInput
On entry: the first dimension of the array A as declared in the (sub)program from which F08BSF (ZGEQPF) is called.
Constraint: LDA≥max 1,M.
5:   JPVT* – INTEGER arrayInput/Output
Note: the dimension of the array JPVT must be at least max 1,N.
On entry: if JPVT i≠0, then the i th column of A is moved to the beginning of AP before the decomposition is computed and is fixed in place during the computation. Otherwise, the i th column of A is a free column (i.e., one which may be interchanged during the computation with any other free column).
On exit: details of the permutation matrix P. More precisely, if JPVT i=k, then the kth column of A is moved to become the i th column of AP; in other words, the columns of AP are the columns of A in the order JPVT 1,JPVT 2,…,JPVT n.
6:   TAU min M,N – COMPLEX (KIND=nag_wp) arrayOutput
On exit: further details of the unitary matrix Q.
7:   WORK N – COMPLEX (KIND=nag_wp) arrayWorkspace
8:   RWORK 2×N – REAL (KIND=nag_wp) arrayWorkspace
9:   INFO – INTEGEROutput
On exit: INFO=0 unless the routine detects an error (see Section 6).

6 Error Indicators and Warnings

INFO<0
If INFO=-i, argument i had an illegal value. An explanatory message is output, and execution of the program is terminated.

7 Accuracy

The computed factorization is the exact factorization of a nearby matrix A+E, where
E 2 = O ε A 2 ,
and ε is the machine precision.

8 Parallelism and Performance

F08BSF (ZGEQPF) makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The total number of real floating-point operations is approximately 83 n 2 3 m-n if m≥n or 83 m 2 3 n-m if m<n.
To form the unitary matrix Q F08BSF (ZGEQPF) may be followed by a call to F08ATF (ZUNGQR):
CALL ZUNGQR(M,M,MIN(M,N),A,LDA,TAU,WORK,LWORK,INFO)
but note that the second dimension of the array A must be at least M, which may be larger than was required by F08BSF (ZGEQPF).
When m≥n, it is often only the first n columns of Q that are required, and they may be formed by the call:
CALL ZUNGQR(M,N,N,A,LDA,TAU,WORK,LWORK,INFO)
To apply Q to an arbitrary complex rectangular matrix C, F08BSF (ZGEQPF) may be followed by a call to F08AUF (ZUNMQR). For example,
CALL ZUNMQR('Left','Conjugate Transpose',M,P,MIN(M,N),A,LDA,TAU, &
              C,LDC,WORK,LWORK,INFO)
forms C=QH C, where C is m by p.
To compute a QR factorization without column pivoting, use F08ASF (ZGEQRF).
The real analogue of this routine is F08BEF (DGEQPF).

10 Example

This example solves the linear least squares problems
minimize⁡ A xi - bi 2 ,   i=1,2
where b 1 and b 2 are the columns of the matrix B,
A = 0.47-0.34 i -0.40+0.54 i 0.60+0.01 i 0.80-1.02 i -0.32-0.23 i -0.05+0.20 i -0.26-0.44 i -0.43+0.17 i 0.35-0.60 i -0.52-0.34 i 0.87-0.11 i -0.34-0.09 i 0.89+0.71 i -0.45-0.45 i -0.02-0.57 i 1.14-0.78 i -0.19+0.06 i 0.11-0.85 i 1.44+0.80 i 0.07+1.14 i
and
B = -0.85-1.63 i 2.49+4.01 i -2.16+3.52 i -0.14+7.98 i 4.57-5.71 i 8.36-0.28 i 6.38-7.40 i -3.55+1.29 i 8.41+9.39 i -6.72+5.03 i .
Here A is approximately rank-deficient, and hence it is preferable to use F08BSF (ZGEQPF) rather than F08ASF (ZGEQRF).

10.1 Program Text

Program Text (f08bsfe.f90)

10.2 Program Data

Program Data (f08bsfe.d)

10.3 Program Results

Program Results (f08bsfe.r)

F08 Chapter Contents
F08 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F08BTF (ZGEQP3) : NAG Library, Mark 26

F08 Chapter Contents
F08 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F08BTF (ZGEQP3)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F08BTF (ZGEQP3) computes the QR factorization, with column pivoting, of a complex m by n matrix.

2 Specification

SUBROUTINE F08BTF ( M, N, A, LDA, JPVT, TAU, WORK, LWORK, RWORK, INFO)
INTEGER | M, N, LDA, JPVT(*), LWORK, INFO
REAL (KIND=nag_wp) | RWORK(*)
COMPLEX (KIND=nag_wp) | A(LDA,*), TAU(*), WORK(max(1,LWORK))
The routine may be called by its LAPACK name zgeqp3.

3 Description

F08BTF (ZGEQP3) forms the QR factorization, with column pivoting, of an arbitrary rectangular complex m by n matrix.
If m≥n, the factorization is given by:
AP= Q R 0 ,
where R is an n by n upper triangular matrix (with real diagonal elements), Q is an m by m unitary matrix and P is an n by n permutation matrix. It is sometimes more convenient to write the factorization as
AP= Q 1 Q 2 R 0 ,
which reduces to
AP= Q 1 R ,
where Q 1 consists of the first n columns of Q, and Q 2 the remaining m-n columns.
If m<n, R is trapezoidal, and the factorization can be written
AP= Q R 1 R 2 ,
where R 1 is upper triangular and R 2 is rectangular.
The matrix Q is not formed explicitly but is represented as a product of min m,n elementary reflectors (see the F08 Chapter Introduction for details). Routines are provided to work with Q in this representation (see Section 9).
Note also that for any k<n, the information returned in the first k columns of the array A represents a QR factorization of the first k columns of the permuted matrix AP.
The routine allows specified columns of A to be moved to the leading columns of AP at the start of the factorization and fixed there. The remaining columns are free to be interchanged so that at the ith stage the pivot column is chosen to be the column which maximizes the 2-norm of elements i to m over columns i to n.

4 References

Anderson E, Bai Z, Bischof C, Blackford S, Demmel J, Dongarra J J, Du Croz J J, Greenbaum A, Hammarling S, McKenney A and Sorensen D (1999) LAPACK Users' Guide (3rd Edition) SIAM, Philadelphia http://www.netlib.org/lapack/lug
Golub G H and Van Loan C F (1996) Matrix Computations (3rd Edition) Johns Hopkins University Press, Baltimore

5 Arguments

1:   M – INTEGERInput
On entry: m, the number of rows of the matrix A.
Constraint: M≥0.
2:   N – INTEGERInput
On entry: n, the number of columns of the matrix A.
Constraint: N≥0.
3:   A LDA* – COMPLEX (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array A must be at least max 1,N.
On entry: the m by n matrix A.
On exit: if m≥n, the elements below the diagonal are overwritten by details of the unitary matrix Q and the upper triangle is overwritten by the corresponding elements of the n by n upper triangular matrix R.
If m<n, the strictly lower triangular part is overwritten by details of the unitary matrix Q and the remaining elements are overwritten by the corresponding elements of the m by n upper trapezoidal matrix R.
The diagonal elements of R are real.
4:   LDA – INTEGERInput
On entry: the first dimension of the array A as declared in the (sub)program from which F08BTF (ZGEQP3) is called.
Constraint: LDA≥max 1,M.
5:   JPVT* – INTEGER arrayInput/Output
Note: the dimension of the array JPVT must be at least max 1,N.
On entry: if JPVT j≠0, then the j th column of A is moved to the beginning of AP before the decomposition is computed and is fixed in place during the computation. Otherwise, the j th column of A is a free column (i.e., one which may be interchanged during the computation with any other free column).
On exit: details of the permutation matrix P. More precisely, if JPVT j=k, then the kth column of A is moved to become the j th column of AP; in other words, the columns of AP are the columns of A in the order JPVT 1,JPVT 2,…,JPVT n.
6:   TAU* – COMPLEX (KIND=nag_wp) arrayOutput
Note: the dimension of the array TAU must be at least max 1,min M,N.
On exit: further details of the unitary matrix Q.
7:   WORK max 1,LWORK – COMPLEX (KIND=nag_wp) arrayWorkspace
On exit: if INFO=0, the real part of WORK 1 contains the minimum value of LWORK required for optimal performance.
8:   LWORK – INTEGERInput
On entry: the dimension of the array WORK as declared in the (sub)program from which F08BTF (ZGEQP3) is called.
If LWORK=-1, a workspace query is assumed; the routine only calculates the optimal size of the WORK array, returns this value as the first entry of the WORK array, and no error message related to LWORK is issued.
Suggested value: for optimal performance, LWORK≥N+1×nb, where nb is the optimal block size.
Constraint: LWORK≥N+1 or LWORK=-1.
9:   RWORK* – REAL (KIND=nag_wp) arrayWorkspace
Note: the dimension of the array RWORK must be at least max 1,2×N.
10:   INFO – INTEGEROutput
On exit: INFO=0 unless the routine detects an error (see Section 6).

6 Error Indicators and Warnings

INFO<0
If INFO=-i, argument i had an illegal value. An explanatory message is output, and execution of the program is terminated.

7 Accuracy

The computed factorization is the exact factorization of a nearby matrix A+E, where
E 2 = O ε A 2 ,
and ε is the machine precision.

8 Parallelism and Performance

F08BTF (ZGEQP3) is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
F08BTF (ZGEQP3) makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The total number of real floating-point operations is approximately 83 n 2 3 m-n if m≥n or 83 m 2 3 n-m if m<n.
To form the unitary matrix Q F08BTF (ZGEQP3) may be followed by a call to F08ATF (ZUNGQR):
CALL ZUNGQR(M,M,MIN(M,N),A,LDA,TAU,WORK,LWORK,INFO)
but note that the second dimension of the array A must be at least M, which may be larger than was required by F08BTF (ZGEQP3).
When m≥n, it is often only the first n columns of Q that are required, and they may be formed by the call:
CALL ZUNGQR(M,N,N,A,LDA,TAU,WORK,LWORK,INFO)
To apply Q to an arbitrary complex rectangular matrix C, F08BTF (ZGEQP3) may be followed by a call to F08AUF (ZUNMQR). For example,
CALL ZUNMQR('Left','Conjugate Transpose',M,P,MIN(M,N),A,LDA,TAU, &
              C,LDC,WORK,LWORK,INFO)
forms C=QH C, where C is m by p.
To compute a QR factorization without column pivoting, use F08ASF (ZGEQRF).
The real analogue of this routine is F08BFF (DGEQP3).

10 Example

This example solves the linear least squares problems
minx bj - A xj 2 ,   j=1,2
for the basic solutions x 1 and x 2, where
A = 0.47-0.34 i -0.40+0.54 i 0.60+0.01 i 0.80-1.02 i -0.32-0.23 i -0.05+0.20 i -0.26-0.44 i -0.43+0.17 i 0.35-0.60 i -0.52-0.34 i 0.87-0.11 i -0.34-0.09 i 0.89+0.71 i -0.45-0.45 i -0.02-0.57 i 1.14-0.78 i -0.19+0.06 i 0.11-0.85 i 1.44+0.80 i 0.07+1.14 i
and
B = -1.08-2.59 i 2.22+2.35 i -2.61-1.49 i 1.62-1.48 i 3.13-3.61 i 1.65+3.43 i 7.33-8.01 i -0.98+3.08 i 9.12+7.63 i -2.84+2.78 i .
and bj is the jth column of the matrix B. The solution is obtained by first obtaining a QR factorization with column pivoting of the matrix A. A tolerance of 0.01 is used to estimate the rank of A from the upper triangular factor, R.
Note that the block size (NB) of 64 assumed in this example is not realistic for such a small problem, but should be suitable for large problems.

10.1 Program Text

Program Text (f08btfe.f90)

10.2 Program Data

Program Data (f08btfe.d)

10.3 Program Results

Program Results (f08btfe.r)

F08 Chapter Contents
F08 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F08BVF (ZTZRZF) : NAG Library, Mark 26

F08 Chapter Contents
F08 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F08BVF (ZTZRZF)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F08BVF (ZTZRZF) reduces the m by n (m≤n) complex upper trapezoidal matrix A to upper triangular form by means of unitary transformations.

2 Specification

SUBROUTINE F08BVF ( M, N, A, LDA, TAU, WORK, LWORK, INFO)
INTEGER | M, N, LDA, LWORK, INFO
COMPLEX (KIND=nag_wp) | A(LDA,*), TAU(*), WORK(max(1,LWORK))
The routine may be called by its LAPACK name ztzrzf.

3 Description

The m by n (m≤n) complex upper trapezoidal matrix A given by
A = R 1 R 2 ,
where R 1 is an m by m upper triangular matrix and R 2 is an m by n-m matrix, is factorized as
A = R 0 Z ,
where R is also an m by m upper triangular matrix and Z is an n by n unitary matrix.

4 References

Anderson E, Bai Z, Bischof C, Blackford S, Demmel J, Dongarra J J, Du Croz J J, Greenbaum A, Hammarling S, McKenney A and Sorensen D (1999) LAPACK Users' Guide (3rd Edition) SIAM, Philadelphia http://www.netlib.org/lapack/lug

5 Arguments

1:   M – INTEGERInput
On entry: m, the number of rows of the matrix A.
Constraint: M≥0.
2:   N – INTEGERInput
On entry: n, the number of columns of the matrix A.
Constraint: N≥0.
3:   A LDA* – COMPLEX (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array A must be at least max 1,N.
On entry: the leading m by n upper trapezoidal part of the array A must contain the matrix to be factorized.
On exit: the leading m by m upper triangular part of A contains the upper triangular matrix R, and elements M+1 to N of the first m rows of A, with the array TAU, represent the unitary matrix Z as a product of m elementary reflectors (see Section 3.3.6 in the F08 Chapter Introduction).
4:   LDA – INTEGERInput
On entry: the first dimension of the array A as declared in the (sub)program from which F08BVF (ZTZRZF) is called.
Constraint: LDA≥max 1,M.
5:   TAU* – COMPLEX (KIND=nag_wp) arrayOutput
Note: the dimension of the array TAU must be at least max 1,M.
On exit: the scalar factors of the elementary reflectors.
6:   WORK max 1,LWORK – COMPLEX (KIND=nag_wp) arrayWorkspace
On exit: if INFO=0, the real part of WORK 1 contains the minimum value of LWORK required for optimal performance.
7:   LWORK – INTEGERInput
On entry: the dimension of the array WORK as declared in the (sub)program from which F08BVF (ZTZRZF) is called.
If LWORK=-1, a workspace query is assumed; the routine only calculates the optimal size of the WORK array, returns this value as the first entry of the WORK array, and no error message related to LWORK is issued.
Suggested value: for optimal performance, LWORK≥M×nb, where nb is the optimal block size.
Constraint: LWORK≥max 1,M or LWORK=-1.
8:   INFO – INTEGEROutput
On exit: INFO=0 unless the routine detects an error (see Section 6).

6 Error Indicators and Warnings

INFO<0
If INFO=-i, argument i had an illegal value. An explanatory message is output, and execution of the program is terminated.

7 Accuracy

The computed factorization is the exact factorization of a nearby matrix A+E, where
E 2 = O⁡ε A 2
and ε is the machine precision.

8 Parallelism and Performance

F08BVF (ZTZRZF) makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The total number of floating-point operations is approximately 16 m 2 n-m.
The real analogue of this routine is F08BHF (DTZRZF).

10 Example

This example solves the linear least squares problems
minx bj - A xj 2 ,   j=1,2
for the minimum norm solutions x 1 and x 2, where bj is the jth column of the matrix B,
A = 0.47-0.34 i -0.40+0.54 i 0.60+0.01 i 0.80-1.02 i -0.32-0.23 i -0.05+0.20 i -0.26-0.44 i -0.43+0.17 i 0.35-0.60 i -0.52-0.34 i 0.87-0.11 i -0.34-0.09 i 0.89+0.71 i -0.45-0.45 i -0.02-0.57 i 1.14-0.78 i -0.19+0.06 i 0.11-0.85 i 1.44+0.80 i 0.07+1.14 i
and
B = -1.08-2.59 i 2.22+2.35 i -2.61-1.49 i 1.62-1.48 i 3.13-3.61 i 1.65+3.43 i 7.33-8.01 i -0.98+3.08 i 9.12+7.63 i -2.84+2.78 i .
The solution is obtained by first obtaining a QR factorization with column pivoting of the matrix A, and then the RZ factorization of the leading k by k part of R is computed, where k is the estimated rank of A. A tolerance of 0.01 is used to estimate the rank of A from the upper triangular factor, R.
Note that the block size (NB) of 64 assumed in this example is not realistic for such a small problem, but should be suitable for large problems.

10.1 Program Text

Program Text (f08bvfe.f90)

10.2 Program Data

Program Data (f08bvfe.d)

10.3 Program Results

Program Results (f08bvfe.r)

F08 Chapter Contents
F08 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F08BXF (ZUNMRZ) : NAG Library, Mark 26

F08 Chapter Contents
F08 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F08BXF (ZUNMRZ)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
10 Example

1 Purpose

F08BXF (ZUNMRZ) multiplies a general complex m by n matrix C by the complex unitary matrix Z from an RZ factorization computed by F08BVF (ZTZRZF).

2 Specification

SUBROUTINE F08BXF ( SIDE, TRANS, M, N, K, L, A, LDA, TAU, C, LDC, WORK, LWORK, INFO)
INTEGER | M, N, K, L, LDA, LDC, LWORK, INFO
COMPLEX (KIND=nag_wp) | A(LDA,*), TAU(*), C(LDC,*), WORK(max(1,LWORK))
CHARACTER(1) | SIDE, TRANS
The routine may be called by its LAPACK name zunmrz.

3 Description

F08BXF (ZUNMRZ) is intended to be used following a call to F08BVF (ZTZRZF), which performs an RZ factorization of a real upper trapezoidal matrix A and represents the unitary matrix Z as a product of elementary reflectors.
This routine may be used to form one of the matrix products
ZC ,   ZH C ,   CZ ,   C ZH ,
overwriting the result on C, which may be any complex rectangular m by n matrix.

4 References

Anderson E, Bai Z, Bischof C, Blackford S, Demmel J, Dongarra J J, Du Croz J J, Greenbaum A, Hammarling S, McKenney A and Sorensen D (1999) LAPACK Users' Guide (3rd Edition) SIAM, Philadelphia http://www.netlib.org/lapack/lug

5 Arguments

1:   SIDE – CHARACTER(1)Input
On entry: indicates how Z or ZH is to be applied to C.
SIDE='L'
Z or ZH is applied to C from the left.
SIDE='R'
Z or ZH is applied to C from the right.
Constraint: SIDE='L' or 'R'.
2:   TRANS – CHARACTER(1)Input
On entry: indicates whether Z or ZH is to be applied to C.
TRANS='N'
Z is applied to C.
TRANS='C'
ZH is applied to C.
Constraint: TRANS='N' or 'C'.
3:   M – INTEGERInput
On entry: m, the number of rows of the matrix C.
Constraint: M≥0.
4:   N – INTEGERInput
On entry: n, the number of columns of the matrix C.
Constraint: N≥0.
5:   K – INTEGERInput
On entry: k, the number of elementary reflectors whose product defines the matrix Z.
Constraints:
  • if SIDE='L', M≥ K≥ 0 ;
  • if SIDE='R', N≥ K≥ 0 .
6:   L – INTEGERInput
On entry: l, the number of columns of the matrix A containing the meaningful part of the Householder reflectors.
Constraints:
  • if SIDE='L', M≥ L≥ 0 ;
  • if SIDE='R', N≥ L≥ 0 .
7:   A LDA* – COMPLEX (KIND=nag_wp) arrayInput
Note: the second dimension of the array A must be at least max 1,M if SIDE='L' and at least max 1,N if SIDE='R'.
On entry: the ith row of A must contain the vector which defines the elementary reflector Hi, for i=1,2,…,k, as returned by F08BVF (ZTZRZF).
8:   LDA – INTEGERInput
On entry: the first dimension of the array A as declared in the (sub)program from which F08BXF (ZUNMRZ) is called.
Constraint: LDA≥max 1,K.
9:   TAU* – COMPLEX (KIND=nag_wp) arrayInput
Note: the dimension of the array TAU must be at least max 1,K.
On entry: TAU i must contain the scalar factor of the elementary reflector Hi, as returned by F08BVF (ZTZRZF).
10:   C LDC* – COMPLEX (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array C must be at least max 1,N.
On entry: the m by n matrix C.
On exit: C is overwritten by ZC or ZH C or CZ or ZH C as specified by SIDE and TRANS.
11:   LDC – INTEGERInput
On entry: the first dimension of the array C as declared in the (sub)program from which F08BXF (ZUNMRZ) is called.
Constraint: LDC≥max 1,M.
12:   WORK max 1,LWORK – COMPLEX (KIND=nag_wp) arrayWorkspace
On exit: if INFO=0, the real part of WORK 1 contains the minimum value of LWORK required for optimal performance.
13:   LWORK – INTEGERInput
On entry: the dimension of the array WORK as declared in the (sub)program from which F08BXF (ZUNMRZ) is called.
If LWORK=-1, a workspace query is assumed; the routine only calculates the optimal size of the WORK array, returns this value as the first entry of the WORK array, and no error message related to LWORK is issued.
Suggested value: for optimal performance, LWORK≥N×nb if SIDE='L' and at least M×nb if SIDE='R', where nb is the optimal block size.
Constraints:
  • if SIDE='L', LWORK≥max 1,N or LWORK=-1;
  • if SIDE='R', LWORK≥max 1,M or LWORK=-1.
14:   INFO – INTEGEROutput
On exit: INFO=0 unless the routine detects an error (see Section 6).

6 Error Indicators and Warnings

INFO<0
If INFO=-i, argument i had an illegal value.
If INFO=-999, dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.
An explanatory message is output, and execution of the program is terminated.

7 Accuracy

The computed result differs from the exact result by a matrix E such that
E 2 = O⁡ε C 2
where ε is the machine precision.

8 Parallelism and Performance

F08BXF (ZUNMRZ) makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The total number of floating-point operations is approximately 16 nlk if SIDE='L' and 16 mlk if SIDE='R'.
The real analogue of this routine is F08BKF (DORMRZ).

10 Example

See Section 10 in F08BVF (ZTZRZF).
F08 Chapter Contents
F08 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F08CEF (DGEQLF) : NAG Library, Mark 26

F08 Chapter Contents
F08 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F08CEF (DGEQLF)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F08CEF (DGEQLF) computes a QL factorization of a real m by n matrix A.

2 Specification

SUBROUTINE F08CEF ( M, N, A, LDA, TAU, WORK, LWORK, INFO)
INTEGER | M, N, LDA, LWORK, INFO
REAL (KIND=nag_wp) | A(LDA,*), TAU(*), WORK(max(1,LWORK))
The routine may be called by its LAPACK name dgeqlf.

3 Description

F08CEF (DGEQLF) forms the QL factorization of an arbitrary rectangular real m by n matrix.
If m≥n, the factorization is given by:
A = Q 0 L ,
where L is an n by n lower triangular matrix and Q is an m by m orthogonal matrix. If m<n the factorization is given by
A = QL ,
where L is an m by n lower trapezoidal matrix and Q is again an m by m orthogonal matrix. In the case where m>n the factorization can be expressed as
A = Q 1 Q 2 0 L = Q 2 L ,
where Q 1 consists of the first m-n columns of Q, and Q 2 the remaining n columns.
The matrix Q is not formed explicitly but is represented as a product of min m,n elementary reflectors (see Section 3.3.6 in the F08 Chapter Introduction for details). Routines are provided to work with Q in this representation (see Section 9).
Note also that for any k<n, the information returned in the last k columns of the array A represents a QL factorization of the last k columns of the original matrix A.

4 References

Anderson E, Bai Z, Bischof C, Blackford S, Demmel J, Dongarra J J, Du Croz J J, Greenbaum A, Hammarling S, McKenney A and Sorensen D (1999) LAPACK Users' Guide (3rd Edition) SIAM, Philadelphia http://www.netlib.org/lapack/lug
Golub G H and Van Loan C F (1996) Matrix Computations (3rd Edition) Johns Hopkins University Press, Baltimore

5 Arguments

1:   M – INTEGERInput
On entry: m, the number of rows of the matrix A.
Constraint: M≥0.
2:   N – INTEGERInput
On entry: n, the number of columns of the matrix A.
Constraint: N≥0.
3:   A LDA* – REAL (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array A must be at least max 1,N.
On entry: the m by n matrix A.
On exit: if m≥n, the lower triangle of the subarray A m-n+1:m1:n contains the n by n lower triangular matrix L.
If m≤n, the elements on and below the n-mth superdiagonal contain the m by n lower trapezoidal matrix L. The remaining elements, with the array TAU, represent the orthogonal matrix Q as a product of elementary reflectors (see Section 3.3.6 in the F08 Chapter Introduction).
4:   LDA – INTEGERInput
On entry: the first dimension of the array A as declared in the (sub)program from which F08CEF (DGEQLF) is called.
Constraint: LDA≥max 1,M.
5:   TAU* – REAL (KIND=nag_wp) arrayOutput
Note: the dimension of the array TAU must be at least max 1,min M,N.
On exit: the scalar factors of the elementary reflectors (see Section 9).
6:   WORK max 1,LWORK – REAL (KIND=nag_wp) arrayWorkspace
On exit: if INFO=0, WORK 1 contains the minimum value of LWORK required for optimal performance.
7:   LWORK – INTEGERInput
On entry: the dimension of the array WORK as declared in the (sub)program from which F08CEF (DGEQLF) is called.
If LWORK=-1, a workspace query is assumed; the routine only calculates the optimal size of the WORK array, returns this value as the first entry of the WORK array, and no error message related to LWORK is issued.
Suggested value: for optimal performance, LWORK≥N×nb, where nb is the optimal block size.
Constraint: LWORK≥max 1,N.
8:   INFO – INTEGEROutput
On exit: INFO=0 unless the routine detects an error (see Section 6).

6 Error Indicators and Warnings

INFO<0
If INFO=-i, argument i had an illegal value. An explanatory message is output, and execution of the program is terminated.

7 Accuracy

The computed factorization is the exact factorization of a nearby matrix A+E, where
E 2 = O ε A 2 ,
and ε is the machine precision.

8 Parallelism and Performance

F08CEF (DGEQLF) makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The total number of floating-point operations is approximately 23 n 2 3 m-n if m≥n or 23 m 2 3 n-m if m<n.
To form the orthogonal matrix Q F08CEF (DGEQLF) may be followed by a call to F08CFF (DORGQL):
CALL DORGQL(M,M,MIN(M,N),A,LDA,TAU,WORK,LWORK,INFO)
but note that the second dimension of the array A must be at least M, which may be larger than was required by F08CEF (DGEQLF).
When m≥n, it is often only the first n columns of Q that are required, and they may be formed by the call:
CALL DORGQL(M,N,N,A,LDA,TAU,WORK,LWORK,INFO)
To apply Q to an arbitrary real rectangular matrix C, F08CEF (DGEQLF) may be followed by a call to F08CGF (DORMQL). For example,
CALL DORMQL('Left','Transpose',M,P,MIN(M,N),A,LDA,TAU,C,LDC,WORK, &
              LWORK,INFO)
forms C=QT C, where C is m by p.
The complex analogue of this routine is F08CSF (ZGEQLF).

10 Example

This example solves the linear least squares problems
minx bj - A xj 2 , ​ j=1,2
for x 1 and x 2, where bj is the jth column of the matrix B,
A = -0.57 -1.28 -0.39 0.25 -1.93 1.08 -0.31 -2.14 2.30 0.24 0.40 -0.35 -1.93 0.64 -0.66 0.08 0.15 0.30 0.15 -2.13 -0.02 1.03 -1.43 0.50   and   B= -2.67 0.41 -0.55 -3.10 3.34 -4.01 -0.77 2.76 0.48 -6.17 4.10 0.21 .
The solution is obtained by first obtaining a QL factorization of the matrix A.
Note that the block size (NB) of 64 assumed in this example is not realistic for such a small problem, but should be suitable for large problems.

10.1 Program Text

Program Text (f08cefe.f90)

10.2 Program Data

Program Data (f08cefe.d)

10.3 Program Results

Program Results (f08cefe.r)

F08 Chapter Contents
F08 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F08CFF (DORGQL) : NAG Library, Mark 26

F08 Chapter Contents
F08 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F08CFF (DORGQL)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F08CFF (DORGQL) generates all or part of the real m by m orthogonal matrix Q from a QL factorization computed by F08CEF (DGEQLF).

2 Specification

SUBROUTINE F08CFF ( M, N, K, A, LDA, TAU, WORK, LWORK, INFO)
INTEGER | M, N, K, LDA, LWORK, INFO
REAL (KIND=nag_wp) | A(LDA,*), TAU(*), WORK(max(1,LWORK))
The routine may be called by its LAPACK name dorgql.

3 Description

F08CFF (DORGQL) is intended to be used after a call to F08CEF (DGEQLF), which performs a QL factorization of a real matrix A. The orthogonal matrix Q is represented as a product of elementary reflectors.
This routine may be used to generate Q explicitly as a square matrix, or to form only its trailing columns.
Usually Q is determined from the QL factorization of an m by p matrix A with m≥p. The whole of Q may be computed by:
CALL DORGQL(M,M,P,A,LDA,TAU,WORK,LWORK,INFO)
(note that the array A must have at least m columns) or its trailing p columns by:
CALL DORGQL(M,P,P,A,LDA,TAU,WORK,LWORK,INFO)
The columns of Q returned by the last call form an orthonormal basis for the space spanned by the columns of A; thus F08CEF (DGEQLF) followed by F08CFF (DORGQL) can be used to orthogonalize the columns of A.
The information returned by F08CEF (DGEQLF) also yields the QL factorization of the trailing k columns of A, where k<p. The orthogonal matrix arising from this factorization can be computed by:
CALL DORGQL(M,M,K,A,LDA,TAU,WORK,LWORK,INFO)
or its trailing k columns by:
CALL DORGQL(M,K,K,A,LDA,TAU,WORK,LWORK,INFO)

4 References

Anderson E, Bai Z, Bischof C, Blackford S, Demmel J, Dongarra J J, Du Croz J J, Greenbaum A, Hammarling S, McKenney A and Sorensen D (1999) LAPACK Users' Guide (3rd Edition) SIAM, Philadelphia http://www.netlib.org/lapack/lug
Golub G H and Van Loan C F (1996) Matrix Computations (3rd Edition) Johns Hopkins University Press, Baltimore

5 Arguments

1:   M – INTEGERInput
On entry: m, the number of rows of the matrix Q.
Constraint: M≥0.
2:   N – INTEGERInput
On entry: n, the number of columns of the matrix Q.
Constraint: M≥N≥0.
3:   K – INTEGERInput
On entry: k, the number of elementary reflectors whose product defines the matrix Q.
Constraint: N≥K≥0.
4:   A LDA* – REAL (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array A must be at least max 1,N.
On entry: details of the vectors which define the elementary reflectors, as returned by F08CEF (DGEQLF).
On exit: the m by n matrix Q.
5:   LDA – INTEGERInput
On entry: the first dimension of the array A as declared in the (sub)program from which F08CFF (DORGQL) is called.
Constraint: LDA≥max 1,M.
6:   TAU* – REAL (KIND=nag_wp) arrayInput
Note: the dimension of the array TAU must be at least max 1,K.
On entry: further details of the elementary reflectors, as returned by F08CEF (DGEQLF).
7:   WORK max 1,LWORK – REAL (KIND=nag_wp) arrayWorkspace
On exit: if INFO=0, WORK 1 contains the minimum value of LWORK required for optimal performance.
8:   LWORK – INTEGERInput
On entry: the dimension of the array WORK as declared in the (sub)program from which F08CFF (DORGQL) is called.
If LWORK=-1, a workspace query is assumed; the routine only calculates the optimal size of the WORK array, returns this value as the first entry of the WORK array, and no error message related to LWORK is issued.
Suggested value: for optimal performance, LWORK≥N×nb, where nb is the optimal block size.
Constraint: LWORK≥max 1,N.
9:   INFO – INTEGEROutput
On exit: INFO=0 unless the routine detects an error (see Section 6).

6 Error Indicators and Warnings

INFO<0
If INFO=-i, argument i had an illegal value. An explanatory message is output, and execution of the program is terminated.

7 Accuracy

The computed matrix Q differs from an exactly orthogonal matrix by a matrix E such that
E 2 = O ε ,
where ε is the machine precision.

8 Parallelism and Performance

F08CFF (DORGQL) makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The total number of floating-point operations is approximately 4 mnk-2 m+n k 2 + 43 k 3 ; when n=k, the number is approximately 23 n 2 3 m-n .
The complex analogue of this routine is F08CTF (ZUNGQL).

10 Example

This example generates the first four columns of the matrix Q of the QL factorization of A as returned by F08CEF (DGEQLF), where
A = -0.57 -1.28 -0.39 0.25 -1.93 1.08 -0.31 -2.14 2.30 0.24 0.40 -0.35 -1.93 0.64 -0.66 0.08 0.15 0.30 0.15 -2.13 -0.02 1.03 -1.43 0.50 .
Note that the block size (NB) of 64 assumed in this example is not realistic for such a small problem, but should be suitable for large problems.

10.1 Program Text

Program Text (f08cffe.f90)

10.2 Program Data

Program Data (f08cffe.d)

10.3 Program Results

Program Results (f08cffe.r)

F08 Chapter Contents
F08 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F08CGF (DORMQL) : NAG Library, Mark 26

F08 Chapter Contents
F08 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F08CGF (DORMQL)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
10 Example

1 Purpose

F08CGF (DORMQL) multiplies a general real m by n matrix C by the real orthogonal matrix Q from a QL factorization computed by F08CEF (DGEQLF).

2 Specification

SUBROUTINE F08CGF ( SIDE, TRANS, M, N, K, A, LDA, TAU, C, LDC, WORK, LWORK, INFO)
INTEGER | M, N, K, LDA, LDC, LWORK, INFO
REAL (KIND=nag_wp) | A(LDA,*), TAU(*), C(LDC,*), WORK(max(1,LWORK))
CHARACTER(1) | SIDE, TRANS
The routine may be called by its LAPACK name dormql.

3 Description

F08CGF (DORMQL) is intended to be used following a call to F08CEF (DGEQLF), which performs a QL factorization of a real matrix A and represents the orthogonal matrix Q as a product of elementary reflectors.
This routine may be used to form one of the matrix products
QC ,   QT C ,   CQ ,   C QT ,
overwriting the result on C, which may be any real rectangular m by n matrix.
A common application of this routine is in solving linear least squares problems, as described in the F08 Chapter Introduction, and illustrated in Section 10 in F08CEF (DGEQLF).

4 References

Anderson E, Bai Z, Bischof C, Blackford S, Demmel J, Dongarra J J, Du Croz J J, Greenbaum A, Hammarling S, McKenney A and Sorensen D (1999) LAPACK Users' Guide (3rd Edition) SIAM, Philadelphia http://www.netlib.org/lapack/lug

5 Arguments

1:   SIDE – CHARACTER(1)Input
On entry: indicates how Q or QT is to be applied to C.
SIDE='L'
Q or QT is applied to C from the left.
SIDE='R'
Q or QT is applied to C from the right.
Constraint: SIDE='L' or 'R'.
2:   TRANS – CHARACTER(1)Input
On entry: indicates whether Q or QT is to be applied to C.
TRANS='N'
Q is applied to C.
TRANS='T'
QT is applied to C.
Constraint: TRANS='N' or 'T'.
3:   M – INTEGERInput
On entry: m, the number of rows of the matrix C.
Constraint: M≥0.
4:   N – INTEGERInput
On entry: n, the number of columns of the matrix C.
Constraint: N≥0.
5:   K – INTEGERInput
On entry: k, the number of elementary reflectors whose product defines the matrix Q.
Constraints:
  • if SIDE='L', M≥ K≥ 0 ;
  • if SIDE='R', N≥ K≥ 0 .
6:   A LDA* – REAL (KIND=nag_wp) arrayInput
Note: the second dimension of the array A must be at least max 1,K.
On entry: details of the vectors which define the elementary reflectors, as returned by F08CEF (DGEQLF).
On exit: is modified by F08CGF (DORMQL) but restored on exit.
7:   LDA – INTEGERInput
On entry: the first dimension of the array A as declared in the (sub)program from which F08CGF (DORMQL) is called.
Constraints:
  • if SIDE='L', LDA≥ max 1,M ;
  • if SIDE='R', LDA≥ max 1,N .
8:   TAU* – REAL (KIND=nag_wp) arrayInput
Note: the dimension of the array TAU must be at least max 1,K.
On entry: further details of the elementary reflectors, as returned by F08CEF (DGEQLF).
9:   C LDC* – REAL (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array C must be at least max 1,N.
On entry: the m by n matrix C.
On exit: C is overwritten by QC or QT C or CQ or C QT as specified by SIDE and TRANS.
10:   LDC – INTEGERInput
On entry: the first dimension of the array C as declared in the (sub)program from which F08CGF (DORMQL) is called.
Constraint: LDC≥max 1,M.
11:   WORK max 1,LWORK – REAL (KIND=nag_wp) arrayWorkspace
On exit: if INFO=0, WORK 1 contains the minimum value of LWORK required for optimal performance.
12:   LWORK – INTEGERInput
On entry: the dimension of the array WORK as declared in the (sub)program from which F08CGF (DORMQL) is called.
If LWORK=-1, a workspace query is assumed; the routine only calculates the optimal size of the WORK array, returns this value as the first entry of the WORK array, and no error message related to LWORK is issued.
Suggested value: for optimal performance, LWORK≥N×nb if SIDE='L' and at least M×nb if SIDE='R', where nb is the optimal block size.
Constraints:
  • if SIDE='L', LWORK≥max 1,N or LWORK=-1;
  • if SIDE='R', LWORK≥max 1,M or LWORK=-1.
13:   INFO – INTEGEROutput
On exit: INFO=0 unless the routine detects an error (see Section 6).

6 Error Indicators and Warnings

INFO<0
If INFO=-i, argument i had an illegal value.
If INFO=-999, dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.
An explanatory message is output, and execution of the program is terminated.

7 Accuracy

The computed result differs from the exact result by a matrix E such that
E 2 = O⁡ε C 2
where ε is the machine precision.

8 Parallelism and Performance

F08CGF (DORMQL) makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The total number of floating-point operations is approximately 2 nk 2 m-k if SIDE='L' and 2 mk 2 n-k if SIDE='R'.
The complex analogue of this routine is F08CUF (ZUNMQL).

10 Example

See Section 10 in F08CEF (DGEQLF).
F08 Chapter Contents
F08 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F08CHF (DGERQF) : NAG Library, Mark 26

F08 Chapter Contents
F08 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F08CHF (DGERQF)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F08CHF (DGERQF) computes an RQ factorization of a real m by n matrix A.

2 Specification

SUBROUTINE F08CHF ( M, N, A, LDA, TAU, WORK, LWORK, INFO)
INTEGER | M, N, LDA, LWORK, INFO
REAL (KIND=nag_wp) | A(LDA,*), TAU(*), WORK(max(1,LWORK))
The routine may be called by its LAPACK name dgerqf.

3 Description

F08CHF (DGERQF) forms the RQ factorization of an arbitrary rectangular real m by n matrix. If m≤n, the factorization is given by
A = 0 R Q ,
where R is an m by m lower triangular matrix and Q is an n by n orthogonal matrix. If m>n the factorization is given by
A =RQ ,
where R is an m by n upper trapezoidal matrix and Q is again an n by n orthogonal matrix. In the case where m<n the factorization can be expressed as
A = 0 R Q 1 Q 2 =R Q 2 ,
where Q 1 consists of the first n-m rows of Q and Q 2 the remaining m rows.
The matrix Q is not formed explicitly, but is represented as a product of min m,n elementary reflectors (see the F08 Chapter Introduction for details). Routines are provided to work with Q in this representation (see Section 9).

4 References

Anderson E, Bai Z, Bischof C, Blackford S, Demmel J, Dongarra J J, Du Croz J J, Greenbaum A, Hammarling S, McKenney A and Sorensen D (1999) LAPACK Users' Guide (3rd Edition) SIAM, Philadelphia http://www.netlib.org/lapack/lug
Golub G H and Van Loan C F (1996) Matrix Computations (3rd Edition) Johns Hopkins University Press, Baltimore

5 Arguments

1:   M – INTEGERInput
On entry: m, the number of rows of the matrix A.
Constraint: M≥0.
2:   N – INTEGERInput
On entry: n, the number of columns of the matrix A.
Constraint: N≥0.
3:   A LDA* – REAL (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array A must be at least max 1,N.
On entry: the m by n matrix A.
On exit: if m≤n, the upper triangle of the subarray A 1:mn-m+1:n contains the m by m upper triangular matrix R.
If m≥n, the elements on and above the m-nth subdiagonal contain the m by n upper trapezoidal matrix R; the remaining elements, with the array TAU, represent the orthogonal matrix Q as a product of min m,n elementary reflectors (see Section 3.3.6 in the F08 Chapter Introduction).
4:   LDA – INTEGERInput
On entry: the first dimension of the array A as declared in the (sub)program from which F08CHF (DGERQF) is called.
Constraint: LDA≥max 1,M.
5:   TAU* – REAL (KIND=nag_wp) arrayOutput
Note: the dimension of the array TAU must be at least max 1,min M,N.
On exit: the scalar factors of the elementary reflectors.
6:   WORK max 1,LWORK – REAL (KIND=nag_wp) arrayWorkspace
On exit: if INFO=0, WORK 1 contains the minimum value of LWORK required for optimal performance.
7:   LWORK – INTEGERInput
On entry: the dimension of the array WORK as declared in the (sub)program from which F08CHF (DGERQF) is called.
If LWORK=-1, a workspace query is assumed; the routine only calculates the optimal size of the WORK array, returns this value as the first entry of the WORK array, and no error message related to LWORK is issued.
Suggested value: for optimal performance, LWORK≥M×nb, where nb is the optimal block size.
Constraint: LWORK≥max 1,M or LWORK=-1.
8:   INFO – INTEGEROutput
On exit: INFO=0 unless the routine detects an error (see Section 6).

6 Error Indicators and Warnings

INFO<0
If INFO=-i, argument i had an illegal value. An explanatory message is output, and execution of the program is terminated.

7 Accuracy

The computed factorization is the exact factorization of a nearby matrix A+E, where
E 2 = O⁡ε A 2
and ε is the machine precision.

8 Parallelism and Performance

F08CHF (DGERQF) makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The total number of floating-point operations is approximately 23 m 2 3 n-m if m≤n, or 23 n 2 3 m-n if m>n.
To form the orthogonal matrix Q F08CHF (DGERQF) may be followed by a call to F08CJF (DORGRQ):
CALL DORGRQ(N,N,MIN(M,N),A,LDA,TAU,WORK,LWORK,INFO)
but note that the first dimension of the array A must be at least N, which may be larger than was required by F08CHF (DGERQF). When m≤n, it is often only the first m rows of Q that are required and they may be formed by the call:
CALL DORGRQ(M,N,M,A,LDA,TAU,WORK,LWORK,INFO)
To apply Q to an arbitrary real rectangular matrix C, F08CHF (DGERQF) may be followed by a call to F08CKF (DORMRQ). For example:
CALL DORMRQ('Left','Transpose',N,P,MIN(M,N),A,LDA,TAU,C,LDC, &
              WORK,LWORK,INFO)
forms C=QT C, where C is n by p.
The complex analogue of this routine is F08CVF (ZGERQF).

10 Example

This example finds the minimum norm solution to the underdetermined equations
Ax=b
where
A = -5.42 3.28 -3.68 0.27 2.06 0.46 -1.65 -3.40 -3.20 -1.03 -4.06 -0.01 -0.37 2.35 1.90 4.31 -1.76 1.13 -3.15 -0.11 1.99 -2.70 0.26 4.50   and   b= -2.87 1.63 -3.52 0.45 .
The solution is obtained by first obtaining an RQ factorization of the matrix A.
Note that the block size (NB) of 64 assumed in this example is not realistic for such a small problem, but should be suitable for large problems.

10.1 Program Text

Program Text (f08chfe.f90)

10.2 Program Data

Program Data (f08chfe.d)

10.3 Program Results

Program Results (f08chfe.r)

F08 Chapter Contents
F08 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F08CJF (DORGRQ) : NAG Library, Mark 26

F08 Chapter Contents
F08 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F08CJF (DORGRQ)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F08CJF (DORGRQ) generates all or part of the real n by n orthogonal matrix Q from an RQ factorization computed by F08CHF (DGERQF).

2 Specification

SUBROUTINE F08CJF ( M, N, K, A, LDA, TAU, WORK, LWORK, INFO)
INTEGER | M, N, K, LDA, LWORK, INFO
REAL (KIND=nag_wp) | A(LDA,*), TAU(*), WORK(max(1,LWORK))
The routine may be called by its LAPACK name dorgrq.

3 Description

F08CJF (DORGRQ) is intended to be used following a call to F08CHF (DGERQF), which performs an RQ factorization of a real matrix A and represents the orthogonal matrix Q as a product of k elementary reflectors of order n.
This routine may be used to generate Q explicitly as a square matrix, or to form only its trailing rows.
Usually Q is determined from the RQ factorization of a p by n matrix A with p≤n. The whole of Q may be computed by:
CALL DORGRQ(N,N,P,A,LDA,TAU,WORK,LWORK,INFO)
(note that the matrix A must have at least n rows), or its trailing p rows as:
CALL DORGRQ(P,N,P,A,LDA,TAU,WORK,LWORK,INFO)
The rows of Q returned by the last call form an orthonormal basis for the space spanned by the rows of A; thus F08CHF (DGERQF) followed by F08CJF (DORGRQ) can be used to orthogonalize the rows of A.
The information returned by F08CHF (DGERQF) also yields the RQ factorization of the trailing k rows of A, where k<p. The orthogonal matrix arising from this factorization can be computed by:
CALL DORGRQ(N,N,K,A,LDA,TAU,WORK,LWORK,INFO)
or its leading k columns by:
CALL DORGRQ(K,N,K,A,LDA,TAU,WORK,LWORK,INFO)

4 References

Anderson E, Bai Z, Bischof C, Blackford S, Demmel J, Dongarra J J, Du Croz J J, Greenbaum A, Hammarling S, McKenney A and Sorensen D (1999) LAPACK Users' Guide (3rd Edition) SIAM, Philadelphia http://www.netlib.org/lapack/lug
Golub G H and Van Loan C F (1996) Matrix Computations (3rd Edition) Johns Hopkins University Press, Baltimore

5 Arguments

1:   M – INTEGERInput
On entry: m, the number of rows of the matrix Q.
Constraint: M≥0.
2:   N – INTEGERInput
On entry: n, the number of columns of the matrix Q.
Constraint: N≥M.
3:   K – INTEGERInput
On entry: k, the number of elementary reflectors whose product defines the matrix Q.
Constraint: M≥K≥0.
4:   A LDA* – REAL (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array A must be at least max 1,N.
On entry: details of the vectors which define the elementary reflectors, as returned by F08CHF (DGERQF).
On exit: the m by n matrix Q.
5:   LDA – INTEGERInput
On entry: the first dimension of the array A as declared in the (sub)program from which F08CJF (DORGRQ) is called.
Constraint: LDA≥max 1,M.
6:   TAU* – REAL (KIND=nag_wp) arrayInput
Note: the dimension of the array TAU must be at least max 1,K.
On entry: TAU i must contain the scalar factor of the elementary reflector Hi, as returned by F08CHF (DGERQF).
7:   WORK max 1,LWORK – REAL (KIND=nag_wp) arrayWorkspace
On exit: if INFO=0, WORK 1 contains the minimum value of LWORK required for optimal performance.
8:   LWORK – INTEGERInput
On entry: the dimension of the array WORK as declared in the (sub)program from which F08CJF (DORGRQ) is called.
If LWORK=-1, a workspace query is assumed; the routine only calculates the optimal size of the WORK array, returns this value as the first entry of the WORK array, and no error message related to LWORK is issued.
Suggested value: for optimal performance, LWORK≥N×nb, where nb is the optimal block size.
Constraint: LWORK≥max 1,M or LWORK=-1.
9:   INFO – INTEGEROutput
On exit: INFO=0 unless the routine detects an error (see Section 6).

6 Error Indicators and Warnings

INFO<0
If INFO=-i, argument i had an illegal value. An explanatory message is output, and execution of the program is terminated.

7 Accuracy

The computed matrix Q differs from an exactly orthogonal matrix by a matrix E such that
E 2 = O⁡ε
and ε is the machine precision.

8 Parallelism and Performance

F08CJF (DORGRQ) makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The total number of floating-point operations is approximately 4 mnk-2 m+n k 2+43 k 3; when m=k this becomes 23 m 2 3 n-m.
The complex analogue of this routine is F08CWF (ZUNGRQ).

10 Example

This example generates the first four rows of the matrix Q of the RQ factorization of A as returned by F08CHF (DGERQF), where
A = -0.57 -1.93 2.30 -1.93 0.15 -0.02 -1.28 1.08 0.24 0.64 0.30 1.03 -0.39 -0.31 0.40 -0.66 0.15 -1.43 0.25 -2.14 -0.35 0.08 -2.13 0.50 .
Note that the block size (NB) of 64 assumed in this example is not realistic for such a small problem, but should be suitable for large problems.

10.1 Program Text

Program Text (f08cjfe.f90)

10.2 Program Data

Program Data (f08cjfe.d)

10.3 Program Results

Program Results (f08cjfe.r)

F08 Chapter Contents
F08 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F08CKF (DORMRQ) : NAG Library, Mark 26

F08 Chapter Contents
F08 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F08CKF (DORMRQ)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
10 Example

1 Purpose

F08CKF (DORMRQ) multiplies a general real m by n matrix C by the real orthogonal matrix Q from an RQ factorization computed by F08CHF (DGERQF).

2 Specification

SUBROUTINE F08CKF ( SIDE, TRANS, M, N, K, A, LDA, TAU, C, LDC, WORK, LWORK, INFO)
INTEGER | M, N, K, LDA, LDC, LWORK, INFO
REAL (KIND=nag_wp) | A(LDA,*), TAU(*), C(LDC,*), WORK(max(1,LWORK))
CHARACTER(1) | SIDE, TRANS
The routine may be called by its LAPACK name dormrq.

3 Description

F08CKF (DORMRQ) is intended to be used following a call to F08CHF (DGERQF), which performs an RQ factorization of a real matrix A and represents the orthogonal matrix Q as a product of elementary reflectors.
This routine may be used to form one of the matrix products
QC ,   QT C ,   CQ ,   C QT ,
overwriting the result on C, which may be any real rectangular m by n matrix.
A common application of this routine is in solving underdetermined linear least squares problems, as described in the F08 Chapter Introduction, and illustrated in Section 10 in F08CHF (DGERQF).

4 References

Anderson E, Bai Z, Bischof C, Blackford S, Demmel J, Dongarra J J, Du Croz J J, Greenbaum A, Hammarling S, McKenney A and Sorensen D (1999) LAPACK Users' Guide (3rd Edition) SIAM, Philadelphia http://www.netlib.org/lapack/lug
Golub G H and Van Loan C F (1996) Matrix Computations (3rd Edition) Johns Hopkins University Press, Baltimore

5 Arguments

1:   SIDE – CHARACTER(1)Input
On entry: indicates how Q or QT is to be applied to C.
SIDE='L'
Q or QT is applied to C from the left.
SIDE='R'
Q or QT is applied to C from the right.
Constraint: SIDE='L' or 'R'.
2:   TRANS – CHARACTER(1)Input
On entry: indicates whether Q or QT is to be applied to C.
TRANS='N'
Q is applied to C.
TRANS='T'
QT is applied to C.
Constraint: TRANS='N' or 'T'.
3:   M – INTEGERInput
On entry: m, the number of rows of the matrix C.
Constraint: M≥0.
4:   N – INTEGERInput
On entry: n, the number of columns of the matrix C.
Constraint: N≥0.
5:   K – INTEGERInput
On entry: k, the number of elementary reflectors whose product defines the matrix Q.
Constraints:
  • if SIDE='L', M≥ K≥ 0 ;
  • if SIDE='R', N≥ K≥ 0 .
6:   A LDA* – REAL (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array A must be at least max 1,M if SIDE='L' and at least max 1,N if SIDE='R'.
On entry: the ith row of A must contain the vector which defines the elementary reflector Hi, for i=1,2,…,k, as returned by F08CHF (DGERQF).
On exit: is modified by F08CKF (DORMRQ) but restored on exit.
7:   LDA – INTEGERInput
On entry: the first dimension of the array A as declared in the (sub)program from which F08CKF (DORMRQ) is called.
Constraint: LDA≥max 1,K.
8:   TAU* – REAL (KIND=nag_wp) arrayInput
Note: the dimension of the array TAU must be at least max 1,K.
On entry: TAU i must contain the scalar factor of the elementary reflector Hi, as returned by F08CHF (DGERQF).
9:   C LDC* – REAL (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array C must be at least max 1,N.
On entry: the m by n matrix C.
On exit: C is overwritten by QC or QT C or CQ or C QT as specified by SIDE and TRANS.
10:   LDC – INTEGERInput
On entry: the first dimension of the array C as declared in the (sub)program from which F08CKF (DORMRQ) is called.
Constraint: LDC≥max 1,M.
11:   WORK max 1,LWORK – REAL (KIND=nag_wp) arrayWorkspace
On exit: if INFO=0, WORK 1 contains the minimum value of LWORK required for optimal performance.
12:   LWORK – INTEGERInput
On entry: the dimension of the array WORK as declared in the (sub)program from which F08CKF (DORMRQ) is called.
If LWORK=-1, a workspace query is assumed; the routine only calculates the optimal size of the WORK array, returns this value as the first entry of the WORK array, and no error message related to LWORK is issued.
Suggested value: for optimal performance, LWORK≥N×nb if SIDE='L' and at least M×nb if SIDE='R', where nb is the optimal block size.
Constraints:
  • if SIDE='L', LWORK≥max 1,N or LWORK=-1;
  • if SIDE='R', LWORK≥max 1,M or LWORK=-1.
13:   INFO – INTEGEROutput
On exit: INFO=0 unless the routine detects an error (see Section 6).

6 Error Indicators and Warnings

INFO<0
If INFO=-i, argument i had an illegal value.
If INFO=-999, dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.
An explanatory message is output, and execution of the program is terminated.

7 Accuracy

The computed result differs from the exact result by a matrix E such that
E 2 = O⁡ε C 2
where ε is the machine precision.

8 Parallelism and Performance

F08CKF (DORMRQ) makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The total number of floating-point operations is approximately 2 nk 2 m-k if SIDE='L' and 2 mk 2 n-k if SIDE='R'.
The complex analogue of this routine is F08CXF (ZUNMRQ).

10 Example

See Section 10 in F08CHF (DGERQF).
F08 Chapter Contents
F08 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F08 Chapter Contents : NAG Library Manual, Mark 26

F08 Chapter Introduction
NAG Library Manual

NAG Library Chapter Contents

F08 – Least Squares and Eigenvalue Problems (LAPACK)

F08 Chapter Introduction – a description of the Chapter and an overview of the algorithms available

Routine Name | Mark of Introduction | Purpose
F08AAF (DGELS) Example Text Example Data | 21 | DGELS nagf_lapack_dgels Solves a real linear least squares problem of full rank
F08ABF (DGEQRT) Example Text Example Data | 25 | DGEQRT nagf_lapack_dgeqrt Performs a QR factorization of real general rectangular matrix, with explicit blocking
F08ACF (DGEMQRT) | 25 | DGEMQRT nagf_lapack_dgemqrt Applies the orthogonal transformation determined by F08ABF (DGEQRT)
F08AEF (DGEQRF) Example Text Example Data | 16 | DGEQRF nagf_lapack_dgeqrf Performs a QR factorization of real general rectangular matrix
F08AFF (DORGQR) Example Text Example Data | 16 | DORGQR nagf_lapack_dorgqr Forms all or part of orthogonal Q from QR factorization determined by F08AEF (DGEQRF), F08BEF (DGEQPF) or F08BFF (DGEQP3)
F08AGF (DORMQR) | 16 | DORMQR nagf_lapack_dormqr Applies an orthogonal transformation determined by F08AEF (DGEQRF), F08BEF (DGEQPF) or F08BFF (DGEQP3)
F08AHF (DGELQF) Example Text Example Data | 16 | DGELQF nagf_lapack_dgelqf Performs a LQ factorization of real general rectangular matrix
F08AJF (DORGLQ) Example Text Example Data | 16 | DORGLQ nagf_lapack_dorglq Forms all or part of orthogonal Q from LQ factorization determined by F08AHF (DGELQF)
F08AKF (DORMLQ) | 16 | DORMLQ nagf_lapack_dormlq Applies the orthogonal transformation determined by F08AHF (DGELQF)
F08ANF (ZGELS) Example Text Example Data | 21 | ZGELS nagf_lapack_zgels Solves a complex linear least problem of full rank
F08APF (ZGEQRT) Example Text Example Data | 25 | ZGEQRT nagf_lapack_zgeqrt Performs a QR factorization of complex general rectangular matrix using recursive algorithm
F08AQF (ZGEMQRT) | 25 | ZGEMQRT nagf_lapack_zgemqrt Applies the unitary transformation determined by F08APF (ZGEQRT)
F08ASF (ZGEQRF) Example Text Example Data | 16 | ZGEQRF nagf_lapack_zgeqrf Performs a QR factorization of complex general rectangular matrix
F08ATF (ZUNGQR) Example Text Example Data | 16 | ZUNGQR nagf_lapack_zungqr Forms all or part of unitary Q from QR factorization determined by F08ASF (ZGEQRF), F08BSF (ZGEQPF) or F08BTF (ZGEQP3)
F08AUF (ZUNMQR) | 16 | ZUNMQR nagf_lapack_zunmqr Applies a unitary transformation determined by F08ASF (ZGEQRF), F08BSF (ZGEQPF) or F08BTF (ZGEQP3)
F08AVF (ZGELQF) Example Text Example Data | 16 | ZGELQF nagf_lapack_zgelqf Performs a LQ factorization of complex general rectangular matrix
F08AWF (ZUNGLQ) Example Text Example Data | 16 | ZUNGLQ nagf_lapack_zunglq Forms all or part of unitary Q from LQ factorization determined by F08AVF (ZGELQF)
F08AXF (ZUNMLQ) | 16 | ZUNMLQ nagf_lapack_zunmlq Applies the unitary transformation determined by F08AVF (ZGELQF)
F08BAF (DGELSY) Example Text Example Data | 21 | DGELSY nagf_lapack_dgelsy Computes the minimum-norm solution to a real linear least squares problem
F08BBF (DTPQRT) Example Text Example Data | 25 | DTPQRT nagf_lapack_dtpqrt QR factorization of real general triangular-pentagonal matrix
F08BCF (DTPMQRT) | 25 | DTPMQRT nagf_lapack_dtpmqrt Applies the orthogonal transformation determined by F08BBF (DTPQRT)
F08BEF (DGEQPF) Example Text Example Data | 16 | DGEQPF nagf_lapack_dgeqpf QR factorization, with column pivoting, of real general rectangular matrix
F08BFF (DGEQP3) Example Text Example Data | 21 | DGEQP3 nagf_lapack_dgeqp3 QR factorization, with column pivoting, using BLAS-3, of real general rectangular matrix
F08BHF (DTZRZF) Example Text Example Data | 21 | DTZRZF nagf_lapack_dtzrzf Reduces a real upper trapezoidal matrix to upper triangular form
F08BKF (DORMRZ) | 21 | DORMRZ nagf_lapack_dormrz Applies the orthogonal transformation determined by F08BHF (DTZRZF)
F08BNF (ZGELSY) Example Text Example Data | 21 | ZGELSY nagf_lapack_zgelsy Computes the minimum-norm solution to a complex linear least squares problem
F08BPF (ZTPQRT) Example Text Example Data | 25 | ZTPQRT nagf_lapack_ztpqrt QR factorization of complex triangular-pentagonal matrix
F08BQF (ZTPMQRT) | 25 | ZTPMQRT nagf_lapack_ztpmqrt Applies the unitary transformation determined by F08BPF (ZTPQRT)
F08BSF (ZGEQPF) Example Text Example Data | 16 | ZGEQPF nagf_lapack_zgeqpf QR factorization, with column pivoting, of complex general rectangular matrix
F08BTF (ZGEQP3) Example Text Example Data | 21 | ZGEQP3 nagf_lapack_zgeqp3 QR factorization, with column pivoting, using BLAS-3, of complex general rectangular matrix
F08BVF (ZTZRZF) Example Text Example Data | 21 | ZTZRZF nagf_lapack_ztzrzf Reduces a complex upper trapezoidal matrix to upper triangular form
F08BXF (ZUNMRZ) | 21 | ZUNMRZ nagf_lapack_zunmrz Applies the unitary transformation determined by F08BVF (ZTZRZF)
F08CEF (DGEQLF) Example Text Example Data | 21 | DGEQLF nagf_lapack_dgeqlf QL factorization of real general rectangular matrix
F08CFF (DORGQL) Example Text Example Data | 21 | DORGQL nagf_lapack_dorgql Form all or part of orthogonal Q from QL factorization determined by F08CEF (DGEQLF)
F08CGF (DORMQL) | 21 | DORMQL nagf_lapack_dormql Applies the orthogonal transformation determined by F08CEF (DGEQLF)
F08CHF (DGERQF) Example Text Example Data | 21 | DGERQF nagf_lapack_dgerqf RQ factorization of real general rectangular matrix
F08CJF (DORGRQ) Example Text Example Data | 21 | DORGRQ nagf_lapack_dorgrq Form all or part of orthogonal Q from RQ factorization determined by F08CHF (DGERQF)
F08CKF (DORMRQ) | 21 | DORMRQ nagf_lapack_dormrq Applies the orthogonal transformation determined by F08CHF (DGERQF)
F08CSF (ZGEQLF) Example Text Example Data | 21 | ZGEQLF nagf_lapack_zgeqlf QL factorization of complex general rectangular matrix
F08CTF (ZUNGQL) Example Text Example Data | 21 | ZUNGQL nagf_lapack_zungql Form all or part of unitary Q from QL factorization determined by F08CSF (ZGEQLF)
F08CUF (ZUNMQL) | 21 | ZUNMQL nagf_lapack_zunmql Applies the unitary transformation determined by F08CSF (ZGEQLF)
F08CVF (ZGERQF) Example Text Example Data | 21 | ZGERQF nagf_lapack_zgerqf RQ factorization of complex general rectangular matrix
F08CWF (ZUNGRQ) Example Text Example Data | 21 | ZUNGRQ nagf_lapack_zungrq Form all or part of unitary Q from RQ factorization determined by F08CVF (ZGERQF)
F08CXF (ZUNMRQ) | 21 | ZUNMRQ nagf_lapack_zunmrq Applies the unitary transformation determined by F08CVF (ZGERQF)
F08FAF (DSYEV) Example Text Example Data | 21 | DSYEV nagf_lapack_dsyev Computes all eigenvalues and, optionally, eigenvectors of a real symmetric matrix
F08FBF (DSYEVX) Example Text Example Data | 21 | DSYEVX nagf_lapack_dsyevx Computes selected eigenvalues and, optionally, eigenvectors of a real symmetric matrix
F08FCF (DSYEVD) Example Text Example Data | 19 | DSYEVD nagf_lapack_dsyevd Computes all eigenvalues and, optionally, all eigenvectors of real symmetric matrix (divide-and-conquer)
F08FDF (DSYEVR) Example Text Example Data | 21 | DSYEVR nagf_lapack_dsyevr Computes selected eigenvalues and, optionally, eigenvectors of a real symmetric matrix (Relatively Robust Representations)
F08FEF (DSYTRD) Example Text Example Data | 16 | DSYTRD nagf_lapack_dsytrd Orthogonal reduction of real symmetric matrix to symmetric tridiagonal form
F08FFF (DORGTR) Example Text Example Data | 16 | DORGTR nagf_lapack_dorgtr Generate orthogonal transformation matrix from reduction to tridiagonal form determined by F08FEF (DSYTRD)
F08FGF (DORMTR) Example Text Example Data | 16 | DORMTR nagf_lapack_dormtr Applies the orthogonal transformation determined by F08FEF (DSYTRD)
F08FLF (DDISNA) | 21 | DDISNA nagf_lapack_ddisna Computes the reciprocal condition numbers for the eigenvectors of a real symmetric or complex Hermitian matrix or for the left or right singular vectors of a general matrix
F08FNF (ZHEEV) Example Text Example Data | 21 | ZHEEV nagf_lapack_zheev Computes all eigenvalues and, optionally, eigenvectors of a complex Hermitian matrix
F08FPF (ZHEEVX) Example Text Example Data | 21 | ZHEEVX nagf_lapack_zheevx Computes selected eigenvalues and, optionally, eigenvectors of a complex Hermitian matrix
F08FQF (ZHEEVD) Example Text Example Data | 19 | ZHEEVD nagf_lapack_zheevd Computes all eigenvalues and, optionally, all eigenvectors of complex Hermitian matrix (divide-and-conquer)
F08FRF (ZHEEVR) Example Text Example Data | 21 | ZHEEVR nagf_lapack_zheevr Computes selected eigenvalues and, optionally, eigenvectors of a complex Hermitian matrix (Relatively Robust Representations)
F08FSF (ZHETRD) Example Text Example Data | 16 | ZHETRD nagf_lapack_zhetrd Unitary reduction of complex Hermitian matrix to real symmetric tridiagonal form
F08FTF (ZUNGTR) Example Text Example Data | 16 | ZUNGTR nagf_lapack_zungtr Generate unitary transformation matrix from reduction to tridiagonal form determined by F08FSF (ZHETRD)
F08FUF (ZUNMTR) Example Text Example Data | 16 | ZUNMTR nagf_lapack_zunmtr Applies the unitary transformation matrix determined by F08FSF (ZHETRD)
F08GAF (DSPEV) Example Text Example Data | 21 | DSPEV nagf_lapack_dspev Computes all eigenvalues and, optionally, eigenvectors of a real symmetric matrix, packed storage
F08GBF (DSPEVX) Example Text Example Data | 21 | DSPEVX nagf_lapack_dspevx Computes selected eigenvalues and, optionally, eigenvectors of a real symmetric matrix, packed storage
F08GCF (DSPEVD) Example Text Example Data | 19 | DSPEVD nagf_lapack_dspevd Computes all eigenvalues and, optionally, all eigenvectors of real symmetric matrix, packed storage (divide-and-conquer or Pal–Walker–Kahan variant of the QL or QR algorithm)
F08GEF (DSPTRD) Example Text Example Data | 16 | DSPTRD nagf_lapack_dsptrd Orthogonal reduction of real symmetric matrix to symmetric tridiagonal form, packed storage
F08GFF (DOPGTR) Example Text Example Data | 16 | DOPGTR nagf_lapack_dopgtr Generate orthogonal transformation matrix from reduction to tridiagonal form determined by F08GEF (DSPTRD)
F08GGF (DOPMTR) Example Text Example Data | 16 | DOPMTR nagf_lapack_dopmtr Applies the orthogonal transformation determined by F08GEF (DSPTRD)
F08GNF (ZHPEV) Example Text Example Data | 21 | ZHPEV nagf_lapack_zhpev Computes all eigenvalues and, optionally, eigenvectors of a complex Hermitian matrix, packed storage
F08GPF (ZHPEVX) Example Text Example Data | 21 | ZHPEVX nagf_lapack_zhpevx Computes selected eigenvalues and, optionally, eigenvectors of a complex Hermitian matrix, packed storage
F08GQF (ZHPEVD) Example Text Example Data | 19 | ZHPEVD nagf_lapack_zhpevd Computes all eigenvalues and, optionally, all eigenvectors of complex Hermitian matrix, packed storage (divide-and-conquer or Pal–Walker–Kahan variant of the QL or QR algorithm)
F08GSF (ZHPTRD) Example Text Example Data | 16 | ZHPTRD nagf_lapack_zhptrd Performs a unitary reduction of complex Hermitian matrix to real symmetric tridiagonal form, packed storage
F08GTF (ZUPGTR) Example Text Example Data | 16 | ZUPGTR nagf_lapack_zupgtr Generates a unitary transformation matrix from reduction to tridiagonal form determined by F08GSF (ZHPTRD)
F08GUF (ZUPMTR) Example Text Example Data | 16 | ZUPMTR nagf_lapack_zupmtr Applies the unitary transformation matrix determined by F08GSF (ZHPTRD)
F08HAF (DSBEV) Example Text Example Data | 21 | DSBEV nagf_lapack_dsbev Computes all eigenvalues and, optionally, eigenvectors of a real symmetric band matrix
F08HBF (DSBEVX) Example Text Example Data | 21 | DSBEVX nagf_lapack_dsbevx Computes selected eigenvalues and, optionally, eigenvectors of a real symmetric band matrix
F08HCF (DSBEVD) Example Text Example Data | 19 | DSBEVD nagf_lapack_dsbevd Computes all eigenvalues and, optionally, all eigenvectors of real symmetric band matrix (divide-and-conquer or Pal–Walker–Kahan variant of the QL or QR algorithm)
F08HEF (DSBTRD) Example Text Example Data | 16 | DSBTRD nagf_lapack_dsbtrd Performs an orthogonal reduction of real symmetric band matrix to symmetric tridiagonal form
F08HNF (ZHBEV) Example Text Example Data | 21 | ZHBEV nagf_lapack_zhbev Computes all eigenvalues and, optionally, eigenvectors of a complex Hermitian band matrix
F08HPF (ZHBEVX) Example Text Example Data | 21 | ZHBEVX nagf_lapack_zhbevx Computes selected eigenvalues and, optionally, eigenvectors of a complex Hermitian band matrix
F08HQF (ZHBEVD) Example Text Example Data | 19 | ZHBEVD nagf_lapack_zhbevd Computes all eigenvalues and, optionally, all eigenvectors of complex Hermitian band matrix (divide-and-conquer)
F08HSF (ZHBTRD) Example Text Example Data | 16 | ZHBTRD nagf_lapack_zhbtrd Performs a unitary reduction of complex Hermitian band matrix to real symmetric tridiagonal form
F08JAF (DSTEV) Example Text Example Data | 21 | DSTEV nagf_lapack_dstev Computes all eigenvalues and, optionally, eigenvectors of a real symmetric tridiagonal matrix
F08JBF (DSTEVX) Example Text Example Data | 21 | DSTEVX nagf_lapack_dstevx Computes selected eigenvalues and, optionally, eigenvectors of a real symmetric tridiagonal matrix
F08JCF (DSTEVD) Example Text Example Data | 19 | DSTEVD nagf_lapack_dstevd Computes all eigenvalues and, optionally, all eigenvectors of real symmetric tridiagonal matrix (divide-and-conquer)
F08JDF (DSTEVR) Example Text Example Data | 21 | DSTEVR nagf_lapack_dstevr Computes selected eigenvalues and, optionally, eigenvectors of a real symmetric tridiagonal matrix (Relatively Robust Representations)
F08JEF (DSTEQR) Example Text Example Data | 16 | DSTEQR nagf_lapack_dsteqr Computes all eigenvalues and eigenvectors of real symmetric tridiagonal matrix, reduced from real symmetric matrix using the implicit QL or QR algorithm
F08JFF (DSTERF) Example Text Example Data | 16 | DSTERF nagf_lapack_dsterf Computes all eigenvalues of real symmetric tridiagonal matrix, root-free variant of the QL or QR algorithm
F08JGF (DPTEQR) Example Text Example Data | 16 | DPTEQR nagf_lapack_dpteqr Computes all eigenvalues and eigenvectors of real symmetric positive definite tridiagonal matrix, reduced from real symmetric positive definite matrix
F08JHF (DSTEDC) Example Text Example Data | 21 | DSTEDC nagf_lapack_dstedc Computes all eigenvalues and, optionally, eigenvectors of a real symmetric tridiagonal matrix or a matrix reduced to this form (divide-and-conquer)
F08JJF (DSTEBZ) | 16 | DSTEBZ nagf_lapack_dstebz Computes selected eigenvalues of real symmetric tridiagonal matrix by bisection
F08JKF (DSTEIN) | 16 | DSTEIN nagf_lapack_dstein Computes selected eigenvectors of real symmetric tridiagonal matrix by inverse iteration, storing eigenvectors in real array
F08JLF (DSTEGR) Example Text Example Data | 21 | DSTEGR nagf_lapack_dstegr Computes all eigenvalues and, optionally, eigenvectors of a real symmetric tridiagonal matrix or a symmetric matrix reduced to this form (Relatively Robust Representations)
F08JSF (ZSTEQR) | 16 | ZSTEQR nagf_lapack_zsteqr Computes all eigenvalues and eigenvectors of real symmetric tridiagonal matrix, reduced from complex Hermitian matrix, using the implicit QL or QR algorithm
F08JUF (ZPTEQR) Example Text Example Data | 16 | ZPTEQR nagf_lapack_zpteqr Computes all eigenvalues and eigenvectors of real symmetric positive definite tridiagonal matrix, reduced from complex Hermitian positive definite matrix
F08JVF (ZSTEDC) Example Text Example Data | 21 | ZSTEDC nagf_lapack_zstedc Computes all eigenvalues and, optionally, eigenvectors of a real symmetric tridiagonal matrix or a complex Hermitian matrix reduced to this form (divide-and-conquer)
F08JXF (ZSTEIN) | 16 | ZSTEIN nagf_lapack_zstein Computes selected eigenvectors of real symmetric tridiagonal matrix by inverse iteration, storing eigenvectors in complex array
F08JYF (ZSTEGR) Example Text Example Data | 21 | ZSTEGR nagf_lapack_zstegr Computes all eigenvalues and, optionally, eigenvectors of a real symmetric tridiagonal matrix or a complex Hermitian matrix reduced to this form (Relatively Robust Representations)
F08KAF (DGELSS) Example Text Example Data | 21 | DGELSS nagf_lapack_dgelss Computes the minimum-norm solution to a real linear least squares problem using singular value decomposition
F08KBF (DGESVD) Example Text Example Data | 21 | DGESVD nagf_lapack_dgesvd Computes the singular value decomposition of a real matrix, optionally computing the left and/or right singular vectors
F08KCF (DGELSD) Example Text Example Data | 21 | DGELSD nagf_lapack_dgelsd Computes the minimum-norm solution to a real linear least squares problem using singular value decomposition (divide-and-conquer)
F08KDF (DGESDD) Example Text Example Data | 21 | DGESDD nagf_lapack_dgesdd Computes the singular value decomposition of a real matrix, optionally computing the left and/or right singular vectors (divide-and-conquer)
F08KEF (DGEBRD) Example Text Example Data | 16 | DGEBRD nagf_lapack_dgebrd Performs an orthogonal reduction of real general rectangular matrix to bidiagonal form
F08KFF (DORGBR) Example Text Example Data | 16 | DORGBR nagf_lapack_dorgbr Generates an orthogonal transformation matrices from reduction to bidiagonal form determined by F08KEF (DGEBRD)
F08KGF (DORMBR) Example Text Example Data | 16 | DORMBR nagf_lapack_dormbr Applies the orthogonal transformations from reduction to bidiagonal form determined by F08KEF (DGEBRD)
F08KHF (DGEJSV) Example Text Example Data | 23 | DGEJSV nagf_lapack_dgejsv Computes the singular value decomposition of a real matrix, optionally computing the left and/or right singular vectors (preconditioned Jacobi)
F08KJF (DGESVJ) Example Text Example Data | 23 | DGESVJ nagf_lapack_dgesvj Computes the singular value decomposition of a real matrix, optionally computing the left and/or right singular vectors (fast Jacobi)
F08KNF (ZGELSS) Example Text Example Data | 21 | ZGELSS nagf_lapack_zgelss Computes the minimum-norm solution to a complex linear least squares problem using singular value decomposition
F08KPF (ZGESVD) Example Text Example Data | 21 | ZGESVD nagf_lapack_zgesvd Computes the singular value decomposition of a complex matrix, optionally computing the left and/or right singular vectors
F08KQF (ZGELSD) Example Text Example Data | 21 | ZGELSD nagf_lapack_zgelsd Computes the minimum-norm solution to a complex linear least squares problem using singular value decomposition (divide-and-conquer)
F08KRF (ZGESDD) Example Text Example Data | 21 | ZGESDD nagf_lapack_zgesdd Computes the singular value decomposition of a complex matrix, optionally computing the left and/or right singular vectors (divide-and-conquer)
F08KSF (ZGEBRD) Example Text Example Data | 16 | ZGEBRD nagf_lapack_zgebrd Performs a unitary reduction of complex general rectangular matrix to bidiagonal form
F08KTF (ZUNGBR) Example Text Example Data | 16 | ZUNGBR nagf_lapack_zungbr Generates unitary transformation matrices from the reduction to bidiagonal form determined by F08KSF (ZGEBRD)
F08KUF (ZUNMBR) Example Text Example Data | 16 | ZUNMBR nagf_lapack_zunmbr Applies the unitary transformations from reduction to bidiagonal form determined by F08KSF (ZGEBRD)
F08LEF (DGBBRD) Example Text Example Data | 19 | DGBBRD nagf_lapack_dgbbrd Performs a reduction of real rectangular band matrix to upper bidiagonal form
F08LSF (ZGBBRD) Example Text Example Data | 19 | ZGBBRD nagf_lapack_zgbbrd Reduction of complex rectangular band matrix to upper bidiagonal form
F08MDF (DBDSDC) Example Text Example Data | 21 | DBDSDC nagf_lapack_dbdsdc Computes the singular value decomposition of a real bidiagonal matrix, optionally computing the singular vectors (divide-and-conquer)
F08MEF (DBDSQR) Example Text Example Data | 16 | DBDSQR nagf_lapack_dbdsqr Performs an SVD of real bidiagonal matrix reduced from real general matrix
F08MSF (ZBDSQR) | 16 | ZBDSQR nagf_lapack_zbdsqr Performs an SVD of real bidiagonal matrix reduced from complex general matrix
F08NAF (DGEEV) Example Text Example Data | 21 | DGEEV nagf_lapack_dgeev Computes all eigenvalues and, optionally, left and/or right eigenvectors of a real nonsymmetric matrix
F08NBF (DGEEVX) Example Text Example Data | 21 | DGEEVX nagf_lapack_dgeevx Computes all eigenvalues and, optionally, left and/or right eigenvectors of a real nonsymmetric matrix; also, optionally, the balancing transformation, the reciprocal condition numbers for the eigenvalues and for the right eigenvectors
F08NEF (DGEHRD) Example Text Example Data | 16 | DGEHRD nagf_lapack_dgehrd Performs an orthogonal reduction of real general matrix to upper Hessenberg form
F08NFF (DORGHR) Example Text Example Data | 16 | DORGHR nagf_lapack_dorghr Generates an orthogonal transformation matrix from reduction to Hessenberg form determined by F08NEF (DGEHRD)
F08NGF (DORMHR) Example Text Example Data | 16 | DORMHR nagf_lapack_dormhr Applies the orthogonal transformation matrix from reduction to Hessenberg form determined by F08NEF (DGEHRD)
F08NHF (DGEBAL) Example Text Example Data | 16 | DGEBAL nagf_lapack_dgebal Balances a real general matrix
F08NJF (DGEBAK) | 16 | DGEBAK nagf_lapack_dgebak Transforms eigenvectors of real balanced matrix to those of original matrix supplied to F08NHF (DGEBAL)
F08NNF (ZGEEV) Example Text Example Data | 21 | ZGEEV nagf_lapack_zgeev Computes all eigenvalues and, optionally, left and/or right eigenvectors of a complex nonsymmetric matrix
F08NPF (ZGEEVX) Example Text Example Data | 21 | ZGEEVX nagf_lapack_zgeevx Computes all eigenvalues and, optionally, left and/or right eigenvectors of a complex nonsymmetric matrix; also, optionally, the balancing transformation, the reciprocal condition numbers for the eigenvalues and for the right eigenvectors
F08NSF (ZGEHRD) Example Text Example Data | 16 | ZGEHRD nagf_lapack_zgehrd Performs a unitary reduction of complex general matrix to upper Hessenberg form
F08NTF (ZUNGHR) Example Text Example Data | 16 | ZUNGHR nagf_lapack_zunghr Generates a unitary transformation matrix from reduction to Hessenberg form determined by F08NSF (ZGEHRD)
F08NUF (ZUNMHR) Example Text Example Data | 16 | ZUNMHR nagf_lapack_zunmhr Applies the unitary transformation matrix from reduction to Hessenberg form determined by F08NSF (ZGEHRD)
F08NVF (ZGEBAL) Example Text Example Data | 16 | ZGEBAL nagf_lapack_zgebal Balances a complex general matrix
F08NWF (ZGEBAK) | 16 | ZGEBAK nagf_lapack_zgebak Transforms eigenvectors of complex balanced matrix to those of original matrix supplied to F08NVF (ZGEBAL)
F08PAF (DGEES) Example Text Example Data | 21 | DGEES nagf_lapack_dgees Computes for real square nonsymmetric matrix, the eigenvalues, the real Schur form, and, optionally, the matrix of Schur vectors
F08PBF (DGEESX) Example Text Example Data | 21 | DGEESX nagf_lapack_dgeesx Computes for real square nonsymmetric matrix, the eigenvalues, the real Schur form, and, optionally, the matrix of Schur vectors; also, optionally, computes reciprocal condition numbers for selected eigenvalues
F08PEF (DHSEQR) Example Text Example Data | 16 | DHSEQR nagf_lapack_dhseqr Computes the eigenvalues and Schur factorization of real upper Hessenberg matrix reduced from real general matrix
F08PKF (DHSEIN) | 16 | DHSEIN nagf_lapack_dhsein Computes selected right and/or left eigenvectors of real upper Hessenberg matrix by inverse iteration
F08PNF (ZGEES) Example Text Example Data | 21 | ZGEES nagf_lapack_zgees Computes for complex square nonsymmetric matrix, the eigenvalues, the Schur form, and, optionally, the matrix of Schur vectors
F08PPF (ZGEESX) Example Text Example Data | 21 | ZGEESX nagf_lapack_zgeesx Computes for real square nonsymmetric matrix, the eigenvalues, the Schur form, and, optionally, the matrix of Schur vectors; also computes a reciprocal condition number for the average of the selected eigenvalues and for the right invariant subspace corresponding to these eigenvalues
F08PSF (ZHSEQR) Example Text Example Data | 16 | ZHSEQR nagf_lapack_zhseqr Computes the eigenvalues and Schur factorization of complex upper Hessenberg matrix reduced from complex general matrix
F08PXF (ZHSEIN) | 16 | ZHSEIN nagf_lapack_zhsein Computes selected right and/or left eigenvectors of complex upper Hessenberg matrix by inverse iteration
F08QFF (DTREXC) Example Text Example Data | 16 | DTREXC nagf_lapack_dtrexc Reorders a Schur factorization of real matrix using orthogonal similarity transformation
F08QGF (DTRSEN) Example Text Example Data | 16 | DTRSEN nagf_lapack_dtrsen Reorders a Schur factorization of real matrix, form orthonormal basis of right invariant subspace for selected eigenvalues, with estimates of sensitivities
F08QHF (DTRSYL) Example Text Example Data | 16 | DTRSYL nagf_lapack_dtrsyl Solves the real Sylvester matrix equation AX+XB=C, A and B are upper quasi-triangular or transposes
F08QKF (DTREVC) | 16 | DTREVC nagf_lapack_dtrevc Computes left and right eigenvectors of real upper quasi-triangular matrix
F08QLF (DTRSNA) Example Text Example Data | 16 | DTRSNA nagf_lapack_dtrsna Computes estimates of sensitivities of selected eigenvalues and eigenvectors of real upper quasi-triangular matrix
F08QTF (ZTREXC) Example Text Example Data | 16 | ZTREXC nagf_lapack_ztrexc Reorders a Schur factorization of complex matrix using unitary similarity transformation
F08QUF (ZTRSEN) Example Text Example Data | 16 | ZTRSEN nagf_lapack_ztrsen Reorders a Schur factorization of complex matrix, form orthonormal basis of right invariant subspace for selected eigenvalues, with estimates of sensitivities
F08QVF (ZTRSYL) Example Text Example Data | 16 | ZTRSYL nagf_lapack_ztrsyl Solves the complex Sylvester matrix equation AX+XB=C, A and B are upper triangular or conjugate-transposes
F08QXF (ZTREVC) | 16 | ZTREVC nagf_lapack_ztrevc Computes left and right eigenvectors of complex upper triangular matrix
F08QYF (ZTRSNA) Example Text Example Data | 16 | ZTRSNA nagf_lapack_ztrsna Computes estimates of sensitivities of selected eigenvalues and eigenvectors of complex upper triangular matrix
F08RAF (DORCSD) Example Text Example Data | 25 | DORCSD nagf_lapack_dorcsd Computes the CS decomposition of an orthogonal matrix partitioned into four real submatrices
F08RNF (ZUNCSD) Example Text Example Data | 25 | ZUNCSD nagf_lapack_zuncsd Computes the CS decomposition of a unitary matrix partitioned into four complex submatrices
F08SAF (DSYGV) Example Text Example Data | 21 | DSYGV nagf_lapack_dsygv Computes all the eigenvalues, and optionally, the eigenvectors of a real generalized symmetric-definite eigenproblem
F08SBF (DSYGVX) Example Text Example Data | 21 | DSYGVX nagf_lapack_dsygvx Computes selected eigenvalues, and optionally, the eigenvectors of a real generalized symmetric-definite eigenproblem
F08SCF (DSYGVD) Example Text Example Data | 21 | DSYGVD nagf_lapack_dsygvd Computes all the eigenvalues, and optionally, the eigenvectors of a real generalized symmetric-definite eigenproblem (divide-and-conquer)
F08SEF (DSYGST) Example Text Example Data | 16 | DSYGST nagf_lapack_dsygst Performs a reduction to standard form of real symmetric-definite generalized eigenproblem Ax=λBx, ABx=λx or BAx=λx, B factorized by F07FDF (DPOTRF)
F08SNF (ZHEGV) Example Text Example Data | 21 | ZHEGV nagf_lapack_zhegv Computes all the eigenvalues, and optionally, the eigenvectors of a complex generalized Hermitian-definite eigenproblem
F08SPF (ZHEGVX) Example Text Example Data | 21 | ZHEGVX nagf_lapack_zhegvx Computes selected eigenvalues, and optionally, the eigenvectors of a complex generalized Hermitian-definite eigenproblem
F08SQF (ZHEGVD) Example Text Example Data | 21 | ZHEGVD nagf_lapack_zhegvd Computes all the eigenvalues, and optionally, the eigenvectors of a complex generalized Hermitian-definite eigenproblem (divide-and-conquer)
F08SSF (ZHEGST) Example Text Example Data | 16 | ZHEGST nagf_lapack_zhegst Performs a reduction to standard form of complex Hermitian-definite generalized eigenproblem Ax=λBx, ABx=λx or BAx=λx, B factorized by F07FRF (ZPOTRF)
F08TAF (DSPGV) Example Text Example Data | 21 | DSPGV nagf_lapack_dspgv Computes all the eigenvalues, and optionally, the eigenvectors of a real generalized symmetric-definite eigenproblem, packed storage
F08TBF (DSPGVX) Example Text Example Data | 21 | DSPGVX nagf_lapack_dspgvx Computes selected eigenvalues, and optionally, the eigenvectors of a real generalized symmetric-definite eigenproblem, packed storage
F08TCF (DSPGVD) Example Text Example Data | 21 | DSPGVD nagf_lapack_dspgvd Computes all the eigenvalues, and optionally, the eigenvectors of a real generalized symmetric-definite eigenproblem, packed storage (divide-and-conquer)
F08TEF (DSPGST) Example Text Example Data | 16 | DSPGST nagf_lapack_dspgst Performs a reduction to standard form of real symmetric-definite generalized eigenproblem Ax=λBx, ABx=λx or BAx=λx, packed storage, B factorized by F07GDF (DPPTRF)
F08TNF (ZHPGV) Example Text Example Data | 21 | ZHPGV nagf_lapack_zhpgv Computes all the eigenvalues, and optionally, the eigenvectors of a complex generalized Hermitian-definite eigenproblem, packed storage
F08TPF (ZHPGVX) Example Text Example Data | 21 | ZHPGVX nagf_lapack_zhpgvx Computes selected eigenvalues, and optionally, the eigenvectors of a complex generalized Hermitian-definite eigenproblem, packed storage
F08TQF (ZHPGVD) Example Text Example Data | 21 | ZHPGVD nagf_lapack_zhpgvd Computes selected eigenvalues, and optionally, the eigenvectors of a complex generalized Hermitian-definite eigenproblem, packed storage (divide-and-conquer)
F08TSF (ZHPGST) Example Text Example Data | 16 | ZHPGST nagf_lapack_zhpgst Performs a reduction to standard form of complex Hermitian-definite generalized eigenproblem Ax=λBx, ABx=λx or BAx=λx, packed storage, B factorized by F07GRF (ZPPTRF)
F08UAF (DSBGV) Example Text Example Data | 21 | DSBGV nagf_lapack_dsbgv Computes all the eigenvalues, and optionally, the eigenvectors of a real banded generalized symmetric-definite eigenproblem
F08UBF (DSBGVX) Example Text Example Data | 21 | DSBGVX nagf_lapack_dsbgvx Computes selected eigenvalues, and optionally, the eigenvectors of a real banded generalized symmetric-definite eigenproblem
F08UCF (DSBGVD) Example Text Example Data | 21 | DSBGVD nagf_lapack_dsbgvd Computes all the eigenvalues, and optionally, the eigenvectors of a real banded generalized symmetric-definite eigenproblem (divide-and-conquer)
F08UEF (DSBGST) Example Text Example Data | 19 | DSBGST nagf_lapack_dsbgst Performs a reduction of real symmetric-definite banded generalized eigenproblem Ax=λBx to standard form Cy=λy, such that C has the same bandwidth as A
F08UFF (DPBSTF) | 19 | DPBSTF nagf_lapack_dpbstf Computes a split Cholesky factorization of real symmetric positive definite band matrix A
F08UNF (ZHBGV) Example Text Example Data | 21 | ZHBGV nagf_lapack_zhbgv Computes all the eigenvalues, and optionally, the eigenvectors of a complex banded generalized Hermitian-definite eigenproblem
F08UPF (ZHBGVX) Example Text Example Data | 21 | ZHBGVX nagf_lapack_zhbgvx Computes selected eigenvalues, and optionally, the eigenvectors of a complex banded generalized Hermitian-definite eigenproblem
F08UQF (ZHBGVD) Example Text Example Data | 21 | ZHBGVD nagf_lapack_zhbgvd Computes all the eigenvalues, and optionally, the eigenvectors of a complex banded generalized Hermitian-definite eigenproblem (divide-and-conquer)
F08USF (ZHBGST) Example Text Example Data | 19 | ZHBGST nagf_lapack_zhbgst Performs a reduction of complex Hermitian-definite banded generalized eigenproblem Ax=λBx to standard form Cy=λ y, such that C has the same bandwidth as A
F08UTF (ZPBSTF) | 19 | ZPBSTF nagf_lapack_zpbstf Computes a split Cholesky factorization of complex Hermitian positive definite band matrix A
F08VAF (DGGSVD) Example Text Example Data | 21 | DGGSVD nagf_lapack_dggsvd Computes the generalized singular value decomposition of a real matrix pair
F08VCF (DGGSVD3) Example Text Example Data | 26 | DGGSVD3 nagf_lapack_dggsvd3 Computes, using BLAS-3, the generalized singular value decomposition of a real matrix pair
F08VEF (DGGSVP) Example Text Example Data | 21 | DGGSVP nagf_lapack_dggsvp Produces orthogonal matrices that simultaneously reduce the m by n matrix A and the p by n matrix B to upper triangular form
F08VGF (DGGSVP3) Example Text Example Data | 26 | DGGSVP3 nagf_lapack_dggsvp3 Produces orthogonal matrices, using BLAS-3, that simultaneously reduce the m by n matrix A and the p by n matrix B to upper triangular form
F08VNF (ZGGSVD) Example Text Example Data | 21 | ZGGSVD nagf_lapack_zggsvd Computes the generalized singular value decomposition of a complex matrix pair
F08VQF (ZGGSVD3) Example Text Example Data | 26 | ZGGSVD3 nagf_lapack_zggsvd3 Computes, using BLAS-3, the generalized singular value decomposition of a complex matrix pair
F08VSF (ZGGSVP) Example Text Example Data | 21 | ZGGSVP nagf_lapack_zggsvp Produces unitary matrices that simultaneously reduce the complex, m by n, matrix A and the complex, p by n, matrix B to upper triangular form
F08VUF (ZGGSVP3) Example Text Example Data | 26 | ZGGSVP3 nagf_lapack_zggsvp3 Produces unitary matrices, using BLAS-3, that simultaneously reduce the complex, m by n, matrix A and the complex, p by n, matrix B to upper triangular form
F08WAF (DGGEV) Example Text Example Data | 21 | DGGEV nagf_lapack_dggev Computes, for a real nonsymmetric matrix pair, the generalized eigenvalues, and optionally, the left and/or right generalized eigenvectors
F08WBF (DGGEVX) Example Text Example Data | 21 | DGGEVX nagf_lapack_dggevx Computes, for a real nonsymmetric matrix pair, the generalized eigenvalues, and optionally, the left and/or right generalized eigenvectors; also, optionally, the balancing transformation, the reciprocal condition numbers for the eigenvalues and for the right eigenvectors
F08WCF (DGGEV3) Example Text Example Data | 26 | DGGEV3 nagf_lapack_dggev3 Computes, for a real nonsymmetric matrix pair, using BLAS-3, the generalized eigenvalues, and optionally, the left and/or right generalized eigenvectors
F08WEF (DGGHRD) | 20 | DGGHRD nagf_lapack_dgghrd Performs an orthogonal reduction of a pair of real general matrices to generalized upper Hessenberg form
F08WFF (DGGHD3) | 26 | DGGHD3 nagf_lapack_dgghd3 Performs, using BLAS-3, an orthogonal reduction of a pair of real general matrices to generalized upper Hessenberg form
F08WHF (DGGBAL) | 20 | DGGBAL nagf_lapack_dggbal Balances a pair of real, square, matrices
F08WJF (DGGBAK) | 20 | DGGBAK nagf_lapack_dggbak Transforms eigenvectors of a pair of real balanced matrices to those of original matrix pair supplied to F08WHF (DGGBAL)
F08WNF (ZGGEV) Example Text Example Data | 21 | ZGGEV nagf_lapack_zggev Computes, for a complex nonsymmetric matrix pair, the generalized eigenvalues, and optionally, the left and/or right generalized eigenvectors
F08WPF (ZGGEVX) Example Text Example Data | 21 | ZGGEVX nagf_lapack_zggevx Computes, for a complex nonsymmetric matrix pair, the generalized eigenvalues, and optionally, the left and/or right generalized eigenvectors; also, optionally, the balancing transformation, the reciprocal condition numbers for the eigenvalues and for the right eigenvectors
F08WQF (ZGGEV3) Example Text Example Data | 26 | ZGGEV3 nagf_lapack_zggev3 Computes, for a complex nonsymmetric matrix pair, using BLAS-3, the generalized eigenvalues, and optionally, the left and/or right generalized eigenvectors
F08WSF (ZGGHRD) | 20 | ZGGHRD nagf_lapack_zgghrd Performs a unitary reduction of a pair of complex general matrices to generalized upper Hessenberg form
F08WTF (ZGGHD3) | 26 | ZGGHD3 nagf_lapack_zgghd3 Performs, using BLAS-3, a unitary reduction of a pair of complex general matrices to generalized upper Hessenberg form
F08WVF (ZGGBAL) | 20 | ZGGBAL nagf_lapack_zggbal Balances a pair of complex, square, matrices
F08WWF (ZGGBAK) | 20 | ZGGBAK nagf_lapack_zggbak Transforms eigenvectors of a pair of complex balanced matrices to those of original matrix pair supplied to F08WVF (ZGGBAL)
F08XAF (DGGES) Example Text Example Data | 21 | DGGES nagf_lapack_dgges Computes, for a real nonsymmetric matrix pair, the generalized eigenvalues, the generalized real Schur form and, optionally, the left and/or right matrices of Schur vectors
F08XBF (DGGESX) Example Text Example Data | 21 | DGGESX nagf_lapack_dggesx Computes, for a real nonsymmetric matrix pair, the generalized eigenvalues, the generalized real Schur form and, optionally, the left and/or right matrices of Schur vectors; also, optionally, computes reciprocal condition numbers for selected eigenvalues
F08XCF (DGGES3) Example Text Example Data | 26 | DGGES3 nagf_lapack_dgges3 Computes, for a real nonsymmetric matrix pair, using BLAS-3, the generalized eigenvalues, the generalized real Schur form and, optionally, the left and/or right matrices of Schur vectors
F08XEF (DHGEQZ) Example Text Example Data | 20 | DHGEQZ nagf_lapack_dhgeqz Computes eigenvalues and generalized Schur factorization of real generalized upper Hessenberg form reduced from a pair of real general matrices
F08XNF (ZGGES) Example Text Example Data | 21 | ZGGES nagf_lapack_zgges Computes, for a complex nonsymmetric matrix pair, the generalized eigenvalues, the generalized complex Schur form and, optionally, the left and/or right matrices of Schur vectors
F08XPF (ZGGESX) Example Text Example Data | 21 | ZGGESX nagf_lapack_zggesx Computes, for a complex nonsymmetric matrix pair, the generalized eigenvalues, the generalized complex Schur form and, optionally, the left and/or right matrices of Schur vectors; also, optionally, computes reciprocal condition numbers for selected eigenvalues
F08XQF (ZGGES3) Example Text Example Data | 26 | ZGGES3 nagf_lapack_zgges3 Computes, for a complex nonsymmetric matrix pair, using BLAS-3, the generalized eigenvalues, the generalized complex Schur form and, optionally, the left and/or right matrices of Schur vectors
F08XSF (ZHGEQZ) Example Text Example Data | 20 | ZHGEQZ nagf_lapack_zhgeqz Eigenvalues and generalized Schur factorization of complex generalized upper Hessenberg form reduced from a pair of complex, square, matrices
F08YEF (DTGSJA) Example Text Example Data | 21 | DTGSJA nagf_lapack_dtgsja Computes the generalized singular value decomposition of a real upper triangular (or trapezoidal) matrix pair
F08YFF (DTGEXC) Example Text Example Data | 21 | DTGEXC nagf_lapack_dtgexc Reorders the generalized real Schur decomposition of a real matrix pair using an orthogonal equivalence transformation
F08YGF (DTGSEN) Example Text Example Data | 21 | DTGSEN nagf_lapack_dtgsen Reorders the generalized real Schur decomposition of a real matrix pair using an orthogonal equivalence transformation, computes the generalized eigenvalues of the reordered pair and, optionally, computes the estimates of reciprocal condition numbers for eigenvalues and eigenspaces
F08YHF (DTGSYL) Example Text Example Data | 21 | DTGSYL nagf_lapack_dtgsyl Solves the real-valued, generalized, quasi-trangular, Sylvester equation
F08YKF (DTGEVC) Example Text Example Data | 20 | DTGEVC nagf_lapack_dtgevc Computes right and left generalized eigenvectors of the matrix pair A,B which is assumed to be in generalized upper Schur form
F08YLF (DTGSNA) Example Text Example Data | 21 | DTGSNA nagf_lapack_dtgsna Estimates reciprocal condition numbers for specified eigenvalues and/or eigenvectors of a real matrix pair in generalized real Schur canonical form
F08YSF (ZTGSJA) Example Text Example Data | 21 | ZTGSJA nagf_lapack_ztgsja Computes the generalized singular value decomposition of a complex upper triangular (or trapezoidal) matrix pair
F08YTF (ZTGEXC) Example Text Example Data | 21 | ZTGEXC nagf_lapack_ztgexc Reorders the generalized Schur decomposition of a complex matrix pair using an unitary equivalence transformation
F08YUF (ZTGSEN) Example Text Example Data | 21 | ZTGSEN nagf_lapack_ztgsen Reorders the generalized Schur decomposition of a complex matrix pair using an unitary equivalence transformation, computes the generalized eigenvalues of the reordered pair and, optionally, computes the estimates of reciprocal condition numbers for eigenvalues and eigenspaces
F08YVF (ZTGSYL) Example Text Example Data | 21 | ZTGSYL nagf_lapack_ztgsyl Solves the complex generalized Sylvester equation
F08YXF (ZTGEVC) Example Text Example Data | 20 | ZTGEVC nagf_lapack_ztgevc Computes left and right eigenvectors of a pair of complex upper triangular matrices
F08YYF (ZTGSNA) Example Text Example Data | 21 | ZTGSNA nagf_lapack_ztgsna Estimates reciprocal condition numbers for specified eigenvalues and/or eigenvectors of a complex matrix pair in generalized Schur canonical form
F08ZAF (DGGLSE) Example Text Example Data | 21 | DGGLSE nagf_lapack_dgglse Solves the real linear equality-constrained least squares (LSE) problem
F08ZBF (DGGGLM) Example Text Example Data | 21 | DGGGLM nagf_lapack_dggglm Solves a real general Gauss–Markov linear model (GLM) problem
F08ZEF (DGGQRF) Example Text Example Data | 21 | DGGQRF nagf_lapack_dggqrf Computes a generalized QR factorization of a real matrix pair
F08ZFF (DGGRQF) Example Text Example Data | 21 | DGGRQF nagf_lapack_dggrqf Computes a generalized RQ factorization of a real matrix pair
F08ZNF (ZGGLSE) Example Text Example Data | 21 | ZGGLSE nagf_lapack_zgglse Solves the complex linear equality-constrained least squares (LSE) problem
F08ZPF (ZGGGLM) Example Text Example Data | 21 | ZGGGLM nagf_lapack_zggglm Solves a complex general Gauss–Markov linear model (GLM) problem
F08ZSF (ZGGQRF) Example Text Example Data | 21 | ZGGQRF nagf_lapack_zggqrf Computes a generalized QR factorization of a complex matrix pair
F08ZTF (ZGGRQF) Example Text Example Data | 21 | ZGGRQF nagf_lapack_zggrqf Computes a generalized RQ factorization of a complex matrix pair
F08 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F08CSF (ZGEQLF) : NAG Library, Mark 26

F08 Chapter Contents
F08 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F08CSF (ZGEQLF)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F08CSF (ZGEQLF) computes a QL factorization of a complex m by n matrix A.

2 Specification

SUBROUTINE F08CSF ( M, N, A, LDA, TAU, WORK, LWORK, INFO)
INTEGER | M, N, LDA, LWORK, INFO
COMPLEX (KIND=nag_wp) | A(LDA,*), TAU(*), WORK(max(1,LWORK))
The routine may be called by its LAPACK name zgeqlf.

3 Description

F08CSF (ZGEQLF) forms the QL factorization of an arbitrary rectangular complex m by n matrix.
If m≥n, the factorization is given by:
A = Q 0 L ,
where L is an n by n lower triangular matrix and Q is an m by m unitary matrix. If m<n the factorization is given by
A = QL ,
where L is an m by n lower trapezoidal matrix and Q is again an m by m unitary matrix. In the case where m>n the factorization can be expressed as
A = Q 1 Q 2 0 L = Q 2 L ,
where Q 1 consists of the first m-n columns of Q, and Q 2 the remaining n columns.
The matrix Q is not formed explicitly but is represented as a product of min m,n elementary reflectors (see Section 3.3.6 in the F08 Chapter Introduction for details). Routines are provided to work with Q in this representation (see Section 9).
Note also that for any k<n, the information returned in the last k columns of the array A represents a QL factorization of the last k columns of the original matrix A.

4 References

Anderson E, Bai Z, Bischof C, Blackford S, Demmel J, Dongarra J J, Du Croz J J, Greenbaum A, Hammarling S, McKenney A and Sorensen D (1999) LAPACK Users' Guide (3rd Edition) SIAM, Philadelphia http://www.netlib.org/lapack/lug
Golub G H and Van Loan C F (1996) Matrix Computations (3rd Edition) Johns Hopkins University Press, Baltimore

5 Arguments

1:   M – INTEGERInput
On entry: m, the number of rows of the matrix A.
Constraint: M≥0.
2:   N – INTEGERInput
On entry: n, the number of columns of the matrix A.
Constraint: N≥0.
3:   A LDA* – COMPLEX (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array A must be at least max 1,N.
On entry: the m by n matrix A.
On exit: if m≥n, the lower triangle of the subarray A m-n+1:m1:n contains the n by n lower triangular matrix L.
If m≤n, the elements on and below the n-mth superdiagonal contain the m by n lower trapezoidal matrix L. The remaining elements, with the array TAU, represent the unitary matrix Q as a product of elementary reflectors (see Section 3.3.6 in the F08 Chapter Introduction).
4:   LDA – INTEGERInput
On entry: the first dimension of the array A as declared in the (sub)program from which F08CSF (ZGEQLF) is called.
Constraint: LDA≥max 1,M.
5:   TAU* – COMPLEX (KIND=nag_wp) arrayOutput
Note: the dimension of the array TAU must be at least max 1,min M,N.
On exit: the scalar factors of the elementary reflectors (see Section 9).
6:   WORK max 1,LWORK – COMPLEX (KIND=nag_wp) arrayWorkspace
On exit: if INFO=0, the real part of WORK 1 contains the minimum value of LWORK required for optimal performance.
7:   LWORK – INTEGERInput
On entry: the dimension of the array WORK as declared in the (sub)program from which F08CSF (ZGEQLF) is called.
If LWORK=-1, a workspace query is assumed; the routine only calculates the optimal size of the WORK array, returns this value as the first entry of the WORK array, and no error message related to LWORK is issued.
Suggested value: for optimal performance, LWORK≥N×nb, where nb is the optimal block size.
Constraint: LWORK≥max 1,N.
8:   INFO – INTEGEROutput
On exit: INFO=0 unless the routine detects an error (see Section 6).

6 Error Indicators and Warnings

INFO<0
If INFO=-i, argument i had an illegal value. An explanatory message is output, and execution of the program is terminated.

7 Accuracy

The computed factorization is the exact factorization of a nearby matrix A+E, where
E 2 = O ε A 2 ,
and ε is the machine precision.

8 Parallelism and Performance

F08CSF (ZGEQLF) makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The total number of real floating-point operations is approximately 83 n 2 3 m-n if m≥n or 83 m 2 3 n-m if m<n.
To form the unitary matrix Q F08CSF (ZGEQLF) may be followed by a call to F08CTF (ZUNGQL):
CALL ZUNGQL(M,M,MIN(M,N),A,LDA,TAU,WORK,LWORK,INFO)
but note that the second dimension of the array A must be at least M, which may be larger than was required by F08CSF (ZGEQLF).
When m≥n, it is often only the first n columns of Q that are required, and they may be formed by the call:
CALL ZUNGQL(M,N,N,A,LDA,TAU,WORK,LWORK,INFO)
To apply Q to an arbitrary complex rectangular matrix C, F08CSF (ZGEQLF) may be followed by a call to F08CUF (ZUNMQL). For example,
CALL ZUNMQL('Left','Conjugate Transpose',M,P,MIN(M,N),A,LDA,TAU, &
              C,LDC,WORK,LWORK,INFO)
forms C=QH C, where C is m by p.
The real analogue of this routine is F08CEF (DGEQLF).

10 Example

This example solves the linear least squares problems
minx bj - A xj 2 , ​ j=1,2
for x 1 and x 2, where bj is the jth column of the matrix B,
A = 0.96-0.81 i -0.03+0.96 i -0.91+2.06 i -0.05+0.41 i -0.98+1.98 i -1.20+0.19 i -0.66+0.42 i -0.81+0.56 i 0.62-0.46 i 1.01+0.02 i 0.63-0.17 i -1.11+0.60 i -0.37+0.38 i 0.19-0.54 i -0.98-0.36 i 0.22-0.20 i 0.83+0.51 i 0.20+0.01 i -0.17-0.46 i 1.47+1.59 i 1.08-0.28 i 0.20-0.12 i -0.07+1.23 i 0.26+0.26 i
and
B = -2.09+1.93 i 3.26-2.70 i 3.34-3.53 i -6.22+1.16 i -4.94-2.04 i 7.94-3.13 i 0.17+4.23 i 1.04-4.26 i -5.19+3.63 i -2.31-2.12 i 0.98+2.53 i -1.39-4.05 i .
The solution is obtained by first obtaining a QL factorization of the matrix A.
Note that the block size (NB) of 64 assumed in this example is not realistic for such a small problem, but should be suitable for large problems.

10.1 Program Text

Program Text (f08csfe.f90)

10.2 Program Data

Program Data (f08csfe.d)

10.3 Program Results

Program Results (f08csfe.r)

F08 Chapter Contents
F08 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F08CTF (ZUNGQL) : NAG Library, Mark 26

F08 Chapter Contents
F08 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F08CTF (ZUNGQL)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F08CTF (ZUNGQL) generates all or part of the complex m by m unitary matrix Q from a QL factorization computed by F08CSF (ZGEQLF).

2 Specification

SUBROUTINE F08CTF ( M, N, K, A, LDA, TAU, WORK, LWORK, INFO)
INTEGER | M, N, K, LDA, LWORK, INFO
COMPLEX (KIND=nag_wp) | A(LDA,*), TAU(*), WORK(max(1,LWORK))
The routine may be called by its LAPACK name zungql.

3 Description

F08CTF (ZUNGQL) is intended to be used after a call to F08CSF (ZGEQLF), which performs a QL factorization of a complex matrix A. The unitary matrix Q is represented as a product of elementary reflectors.
This routine may be used to generate Q explicitly as a square matrix, or to form only its trailing columns.
Usually Q is determined from the QL factorization of an m by p matrix A with m≥p. The whole of Q may be computed by:
CALL ZUNGQL(M,M,P,A,LDA,TAU,WORK,LWORK,INFO)
(note that the array A must have at least m columns) or its trailing p columns by:
CALL ZUNGQL(M,P,P,A,LDA,TAU,WORK,LWORK,INFO)
The columns of Q returned by the last call form an orthonormal basis for the space spanned by the columns of A; thus F08CSF (ZGEQLF) followed by F08CTF (ZUNGQL) can be used to orthogonalize the columns of A.
The information returned by F08CSF (ZGEQLF) also yields the QL factorization of the trailing k columns of A, where k<p. The unitary matrix arising from this factorization can be computed by:
CALL ZUNGQL(M,M,K,A,LDA,TAU,WORK,LWORK,INFO)
or its trailing k columns by:
CALL ZUNGQL(M,K,K,A,LDA,TAU,WORK,LWORK,INFO)

4 References

Anderson E, Bai Z, Bischof C, Blackford S, Demmel J, Dongarra J J, Du Croz J J, Greenbaum A, Hammarling S, McKenney A and Sorensen D (1999) LAPACK Users' Guide (3rd Edition) SIAM, Philadelphia http://www.netlib.org/lapack/lug
Golub G H and Van Loan C F (1996) Matrix Computations (3rd Edition) Johns Hopkins University Press, Baltimore

5 Arguments

1:   M – INTEGERInput
On entry: m, the number of rows of the matrix Q.
Constraint: M≥0.
2:   N – INTEGERInput
On entry: n, the number of columns of the matrix Q.
Constraint: M≥N≥0.
3:   K – INTEGERInput
On entry: k, the number of elementary reflectors whose product defines the matrix Q.
Constraint: N≥K≥0.
4:   A LDA* – COMPLEX (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array A must be at least max 1,N.
On entry: details of the vectors which define the elementary reflectors, as returned by F08CSF (ZGEQLF).
On exit: the m by n matrix Q.
5:   LDA – INTEGERInput
On entry: the first dimension of the array A as declared in the (sub)program from which F08CTF (ZUNGQL) is called.
Constraint: LDA≥max 1,M.
6:   TAU* – COMPLEX (KIND=nag_wp) arrayInput
Note: the dimension of the array TAU must be at least max 1,K.
On entry: further details of the elementary reflectors, as returned by F08CSF (ZGEQLF).
7:   WORK max 1,LWORK – COMPLEX (KIND=nag_wp) arrayWorkspace
On exit: if INFO=0, the real part of WORK 1 contains the minimum value of LWORK required for optimal performance.
8:   LWORK – INTEGERInput
On entry: the dimension of the array WORK as declared in the (sub)program from which F08CTF (ZUNGQL) is called.
If LWORK=-1, a workspace query is assumed; the routine only calculates the optimal size of the WORK array, returns this value as the first entry of the WORK array, and no error message related to LWORK is issued.
Suggested value: for optimal performance, LWORK≥N×nb, where nb is the optimal block size.
Constraint: LWORK≥max 1,N.
9:   INFO – INTEGEROutput
On exit: INFO=0 unless the routine detects an error (see Section 6).

6 Error Indicators and Warnings

INFO<0
If INFO=-i, argument i had an illegal value. An explanatory message is output, and execution of the program is terminated.

7 Accuracy

The computed matrix Q differs from an exactly unitary matrix by a matrix E such that
E 2 = O ε ,
where ε is the machine precision.

8 Parallelism and Performance

F08CTF (ZUNGQL) makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The total number of real floating-point operations is approximately 16 mnk-8 m+n k 2 + 163 k 3 ; when n=k, the number is approximately 83 n 2 3 m-n .
The real analogue of this routine is F08CFF (DORGQL).

10 Example

This example generates the first four columns of the matrix Q of the QL factorization of A as returned by F08CSF (ZGEQLF), where
A = 0.96-0.81 i -0.03+0.96 i -0.91+2.06 i -0.05+0.41 i -0.98+1.98 i -1.20+0.19 i -0.66+0.42 i -0.81+0.56 i 0.62-0.46 i 1.01+0.02 i 0.63-0.17 i -1.11+0.60 i -0.37+0.38 i 0.19-0.54 i -0.98-0.36 i 0.22-0.20 i 0.83+0.51 i 0.20+0.01 i -0.17-0.46 i 1.47+1.59 i 1.08-0.28 i 0.20-0.12 i -0.07+1.23 i 0.26+0.26 i .
Note that the block size (NB) of 64 assumed in this example is not realistic for such a small problem, but should be suitable for large problems.

10.1 Program Text

Program Text (f08ctfe.f90)

10.2 Program Data

Program Data (f08ctfe.d)

10.3 Program Results

Program Results (f08ctfe.r)

F08 Chapter Contents
F08 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F08CUF (ZUNMQL) : NAG Library, Mark 26

F08 Chapter Contents
F08 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F08CUF (ZUNMQL)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
10 Example

1 Purpose

F08CUF (ZUNMQL) multiplies a general complex m by n matrix C by the complex unitary matrix Q from a QL factorization computed by F08CSF (ZGEQLF).

2 Specification

SUBROUTINE F08CUF ( SIDE, TRANS, M, N, K, A, LDA, TAU, C, LDC, WORK, LWORK, INFO)
INTEGER | M, N, K, LDA, LDC, LWORK, INFO
COMPLEX (KIND=nag_wp) | A(LDA,*), TAU(*), C(LDC,*), WORK(max(1,LWORK))
CHARACTER(1) | SIDE, TRANS
The routine may be called by its LAPACK name zunmql.

3 Description

F08CUF (ZUNMQL) is intended to be used following a call to F08CSF (ZGEQLF), which performs a QL factorization of a complex matrix A and represents the unitary matrix Q as a product of elementary reflectors.
This routine may be used to form one of the matrix products
QC ,   QH C ,   CQ ,   C QH ,
overwriting the result on C, which may be any complex rectangular m by n matrix.
A common application of this routine is in solving linear least squares problems, as described in the F08 Chapter Introduction, and illustrated in Section 10 in F08CSF (ZGEQLF).

4 References

Anderson E, Bai Z, Bischof C, Blackford S, Demmel J, Dongarra J J, Du Croz J J, Greenbaum A, Hammarling S, McKenney A and Sorensen D (1999) LAPACK Users' Guide (3rd Edition) SIAM, Philadelphia http://www.netlib.org/lapack/lug

5 Arguments

1:   SIDE – CHARACTER(1)Input
On entry: indicates how Q or QH is to be applied to C.
SIDE='L'
Q or QH is applied to C from the left.
SIDE='R'
Q or QH is applied to C from the right.
Constraint: SIDE='L' or 'R'.
2:   TRANS – CHARACTER(1)Input
On entry: indicates whether Q or QH is to be applied to C.
TRANS='N'
Q is applied to C.
TRANS='C'
QH is applied to C.
Constraint: TRANS='N' or 'C'.
3:   M – INTEGERInput
On entry: m, the number of rows of the matrix C.
Constraint: M≥0.
4:   N – INTEGERInput
On entry: n, the number of columns of the matrix C.
Constraint: N≥0.
5:   K – INTEGERInput
On entry: k, the number of elementary reflectors whose product defines the matrix Q.
Constraints:
  • if SIDE='L', M≥ K≥ 0 ;
  • if SIDE='R', N≥ K≥ 0 .
6:   A LDA* – COMPLEX (KIND=nag_wp) arrayInput
Note: the second dimension of the array A must be at least max 1,K.
On entry: details of the vectors which define the elementary reflectors, as returned by F08CSF (ZGEQLF).
On exit: is modified by F08CUF (ZUNMQL) but restored on exit.
7:   LDA – INTEGERInput
On entry: the first dimension of the array A as declared in the (sub)program from which F08CUF (ZUNMQL) is called.
Constraints:
  • if SIDE='L', LDA≥ max 1,M ;
  • if SIDE='R', LDA≥ max 1,N .
8:   TAU* – COMPLEX (KIND=nag_wp) arrayInput
Note: the dimension of the array TAU must be at least max 1,K.
On entry: further details of the elementary reflectors, as returned by F08CSF (ZGEQLF).
9:   C LDC* – COMPLEX (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array C must be at least max 1,N.
On entry: the m by n matrix C.
On exit: C is overwritten by QC or QH C or CQ or C QH as specified by SIDE and TRANS.
10:   LDC – INTEGERInput
On entry: the first dimension of the array C as declared in the (sub)program from which F08CUF (ZUNMQL) is called.
Constraint: LDC≥max 1,M.
11:   WORK max 1,LWORK – COMPLEX (KIND=nag_wp) arrayWorkspace
On exit: if INFO=0, the real part of WORK 1 contains the minimum value of LWORK required for optimal performance.
12:   LWORK – INTEGERInput
On entry: the dimension of the array WORK as declared in the (sub)program from which F08CUF (ZUNMQL) is called.
If LWORK=-1, a workspace query is assumed; the routine only calculates the optimal size of the WORK array, returns this value as the first entry of the WORK array, and no error message related to LWORK is issued.
Suggested value: for optimal performance, LWORK≥N×nb if SIDE='L' and at least M×nb if SIDE='R', where nb is the optimal block size.
Constraints:
  • if SIDE='L', LWORK≥max 1,N or LWORK=-1;
  • if SIDE='R', LWORK≥max 1,M or LWORK=-1.
13:   INFO – INTEGEROutput
On exit: INFO=0 unless the routine detects an error (see Section 6).

6 Error Indicators and Warnings

INFO<0
If INFO=-i, argument i had an illegal value.
If INFO=-999, dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.
An explanatory message is output, and execution of the program is terminated.

7 Accuracy

The computed result differs from the exact result by a matrix E such that
E 2 = O⁡ε C 2
where ε is the machine precision.

8 Parallelism and Performance

F08CUF (ZUNMQL) makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The total number of floating-point operations is approximately 8 nk 2 m-k if SIDE='L' and 8 mk 2 n-k if SIDE='R'.
The real analogue of this routine is F08CGF (DORMQL).

10 Example

See Section 10 in F08CSF (ZGEQLF).
F08 Chapter Contents
F08 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F08CVF (ZGERQF) : NAG Library, Mark 26

F08 Chapter Contents
F08 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F08CVF (ZGERQF)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F08CVF (ZGERQF) computes an RQ factorization of a complex m by n matrix A.

2 Specification

SUBROUTINE F08CVF ( M, N, A, LDA, TAU, WORK, LWORK, INFO)
INTEGER | M, N, LDA, LWORK, INFO
COMPLEX (KIND=nag_wp) | A(LDA,*), TAU(*), WORK(max(1,LWORK))
The routine may be called by its LAPACK name zgerqf.

3 Description

F08CVF (ZGERQF) forms the RQ factorization of an arbitrary rectangular real m by n matrix. If m≤n, the factorization is given by
A = 0 R Q ,
where R is an m by m lower triangular matrix and Q is an n by n unitary matrix. If m>n the factorization is given by
A =RQ ,
where R is an m by n upper trapezoidal matrix and Q is again an n by n unitary matrix. In the case where m<n the factorization can be expressed as
A = 0 R Q 1 Q 2 =R Q 2 ,
where Q 1 consists of the first n-m rows of Q and Q 2 the remaining m rows.
The matrix Q is not formed explicitly, but is represented as a product of min m,n elementary reflectors (see the F08 Chapter Introduction for details). Routines are provided to work with Q in this representation (see Section 9).

4 References

Anderson E, Bai Z, Bischof C, Blackford S, Demmel J, Dongarra J J, Du Croz J J, Greenbaum A, Hammarling S, McKenney A and Sorensen D (1999) LAPACK Users' Guide (3rd Edition) SIAM, Philadelphia http://www.netlib.org/lapack/lug
Golub G H and Van Loan C F (1996) Matrix Computations (3rd Edition) Johns Hopkins University Press, Baltimore

5 Arguments

1:   M – INTEGERInput
On entry: m, the number of rows of the matrix A.
Constraint: M≥0.
2:   N – INTEGERInput
On entry: n, the number of columns of the matrix A.
Constraint: N≥0.
3:   A LDA* – COMPLEX (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array A must be at least max 1,N.
On entry: the m by n matrix A.
On exit: if m≤n, the upper triangle of the subarray A 1:mn-m+1:n contains the m by m upper triangular matrix R.
If m≥n, the elements on and above the m-nth subdiagonal contain the m by n upper trapezoidal matrix R; the remaining elements, with the array TAU, represent the unitary matrix Q as a product of min m,n elementary reflectors (see Section 3.3.6 in the F08 Chapter Introduction).
4:   LDA – INTEGERInput
On entry: the first dimension of the array A as declared in the (sub)program from which F08CVF (ZGERQF) is called.
Constraint: LDA≥max 1,M.
5:   TAU* – COMPLEX (KIND=nag_wp) arrayOutput
Note: the dimension of the array TAU must be at least max 1,min M,N.
On exit: the scalar factors of the elementary reflectors.
6:   WORK max 1,LWORK – COMPLEX (KIND=nag_wp) arrayWorkspace
On exit: if INFO=0, the real part of WORK 1 contains the minimum value of LWORK required for optimal performance.
7:   LWORK – INTEGERInput
On entry: the dimension of the array WORK as declared in the (sub)program from which F08CVF (ZGERQF) is called.
If LWORK=-1, a workspace query is assumed; the routine only calculates the optimal size of the WORK array, returns this value as the first entry of the WORK array, and no error message related to LWORK is issued.
Suggested value: for optimal performance, LWORK≥M×nb, where nb is the optimal block size.
Constraint: LWORK≥max 1,M or LWORK=-1.
8:   INFO – INTEGEROutput
On exit: INFO=0 unless the routine detects an error (see Section 6).

6 Error Indicators and Warnings

INFO<0
If INFO=-i, argument i had an illegal value. An explanatory message is output, and execution of the program is terminated.

7 Accuracy

The computed factorization is the exact factorization of a nearby matrix A+E, where
E 2 = O⁡ε A 2
and ε is the machine precision.

8 Parallelism and Performance

F08CVF (ZGERQF) makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The total number of floating-point operations is approximately 23 m 2 3 n-m if m≤n, or 23 n 2 3 m-n if m>n.
To form the unitary matrix Q F08CVF (ZGERQF) may be followed by a call to F08CWF (ZUNGRQ):
CALL ZUNGRQ(N,N,MIN(M,N),A,LDA,TAU,WORK,LWORK,INFO)
but note that the first dimension of the array A must be at least N, which may be larger than was required by F08CVF (ZGERQF). When m≤n, it is often only the first m rows of Q that are required and they may be formed by the call:
CALL ZUNGRQ(M,N,M,A,LDA,TAU,WORK,LWORK,INFO)
To apply Q to an arbitrary real rectangular matrix C, F08CVF (ZGERQF) may be followed by a call to F08CXF (ZUNMRQ). For example:
CALL ZUNMRQ('Left','C',N,P,MIN(M,N),A,LDA,TAU,C,LDC, &
              WORK,LWORK,INFO)
forms C=QH C, where C is n by p.
The real analogue of this routine is F08CHF (DGERQF).

10 Example

This example finds the minimum norm solution to the underdetermined equations
Ax=b
where
A = 0.28-0.36 i 0.50-0.86 i -0.77-0.48 i 1.58+0.66 i -0.50-1.10 i -1.21+0.76 i -0.32-0.24 i -0.27-1.15 i 0.36-0.51 i -0.07+1.33 i -0.75+0.47 i -0.08+1.01 i
and
b = -1.35+0.19 i 9.41-3.56 i -7.57+6.93 i .
The solution is obtained by first obtaining an RQ factorization of the matrix A.
Note that the block size (NB) of 64 assumed in this example is not realistic for such a small problem, but should be suitable for large problems.

10.1 Program Text

Program Text (f08cvfe.f90)

10.2 Program Data

Program Data (f08cvfe.d)

10.3 Program Results

Program Results (f08cvfe.r)

F08 Chapter Contents
F08 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F08CWF (ZUNGRQ) : NAG Library, Mark 26

F08 Chapter Contents
F08 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F08CWF (ZUNGRQ)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F08CWF (ZUNGRQ) generates all or part of the complex n by n unitary matrix Q from an RQ factorization computed by F08CVF (ZGERQF).

2 Specification

SUBROUTINE F08CWF ( M, N, K, A, LDA, TAU, WORK, LWORK, INFO)
INTEGER | M, N, K, LDA, LWORK, INFO
COMPLEX (KIND=nag_wp) | A(LDA,*), TAU(*), WORK(max(1,LWORK))
The routine may be called by its LAPACK name zungrq.

3 Description

F08CWF (ZUNGRQ) is intended to be used following a call to F08CVF (ZGERQF), which performs an RQ factorization of a complex matrix A and represents the unitary matrix Q as a product of k elementary reflectors of order n.
This routine may be used to generate Q explicitly as a square matrix, or to form only its trailing rows.
Usually Q is determined from the RQ factorization of a p by n matrix A with p≤n. The whole of Q may be computed by:
CALL ZUNGRQ(N,N,P,A,LDA,TAU,WORK,LWORK,INFO)
(note that the matrix A must have at least n rows), or its trailing p rows as:
CALL ZUNGRQ(P,N,P,A,LDA,TAU,WORK,LWORK,INFO)
The rows of Q returned by the last call form an orthonormal basis for the space spanned by the rows of A; thus F08CVF (ZGERQF) followed by F08CWF (ZUNGRQ) can be used to orthogonalize the rows of A.
The information returned by F08CVF (ZGERQF) also yields the RQ factorization of the trailing k rows of A, where k<p. The unitary matrix arising from this factorization can be computed by:
CALL ZUNGRQ(N,N,K,A,LDA,TAU,WORK,LWORK,INFO)
or its leading k columns by:
CALL ZUNGRQ(K,N,K,A,LDA,TAU,WORK,LWORK,INFO)

4 References

Anderson E, Bai Z, Bischof C, Blackford S, Demmel J, Dongarra J J, Du Croz J J, Greenbaum A, Hammarling S, McKenney A and Sorensen D (1999) LAPACK Users' Guide (3rd Edition) SIAM, Philadelphia http://www.netlib.org/lapack/lug
Golub G H and Van Loan C F (1996) Matrix Computations (3rd Edition) Johns Hopkins University Press, Baltimore

5 Arguments

1:   M – INTEGERInput
On entry: m, the number of rows of the matrix Q.
Constraint: M≥0.
2:   N – INTEGERInput
On entry: n, the number of columns of the matrix Q.
Constraint: N≥M.
3:   K – INTEGERInput
On entry: k, the number of elementary reflectors whose product defines the matrix Q.
Constraint: M≥K≥0.
4:   A LDA* – COMPLEX (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array A must be at least max 1,N.
On entry: details of the vectors which define the elementary reflectors, as returned by F08CVF (ZGERQF).
On exit: the m by n matrix Q.
5:   LDA – INTEGERInput
On entry: the first dimension of the array A as declared in the (sub)program from which F08CWF (ZUNGRQ) is called.
Constraint: LDA≥max 1,M.
6:   TAU* – COMPLEX (KIND=nag_wp) arrayInput
Note: the dimension of the array TAU must be at least max 1,K.
On entry: TAU i must contain the scalar factor of the elementary reflector Hi, as returned by F08CVF (ZGERQF).
7:   WORK max 1,LWORK – COMPLEX (KIND=nag_wp) arrayWorkspace
On exit: if INFO=0, the real part of WORK 1 contains the minimum value of LWORK required for optimal performance.
8:   LWORK – INTEGERInput
On entry: the dimension of the array WORK as declared in the (sub)program from which F08CWF (ZUNGRQ) is called.
If LWORK=-1, a workspace query is assumed; the routine only calculates the optimal size of the WORK array, returns this value as the first entry of the WORK array, and no error message related to LWORK is issued.
Suggested value: for optimal performance, LWORK≥N×nb, where nb is the optimal block size.
Constraint: LWORK≥max 1,M or LWORK=-1.
9:   INFO – INTEGEROutput
On exit: INFO=0 unless the routine detects an error (see Section 6).

6 Error Indicators and Warnings

INFO<0
If INFO=-i, argument i had an illegal value. An explanatory message is output, and execution of the program is terminated.

7 Accuracy

The computed matrix Q differs from an exactly unitary matrix by a matrix E such that
E 2 = O⁡ε
and ε is the machine precision.

8 Parallelism and Performance

F08CWF (ZUNGRQ) makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The total number of floating-point operations is approximately 16 mnk-8 m+n k 2+163 k 3; when m=k this becomes 83 m 2 3 n-m.
The real analogue of this routine is F08CJF (DORGRQ).

10 Example

This example generates the first four rows of the matrix Q of the RQ factorization of A as returned by F08CVF (ZGERQF), where
A = 0.96-0.81 i -0.98+1.98 i 0.62-0.46 i -0.37+0.38 i 0.83+0.51 i 1.08-0.28 i -0.03+0.96 i -1.20+0.19 i 1.01+0.02 i 0.19-0.54 i 0.20+0.01 i 0.20-0.12 i -0.91+2.06 i -0.66+0.42 i 0.63-0.17 i -0.98-0.36 i -0.17-0.46 i -0.07+1.23 i -0.05+0.41 i -0.81+0.56 i -1.11+0.60 i 0.22-0.20 i 1.47+1.59 i 0.26+0.26 i .
Note that the block size (NB) of 64 assumed in this example is not realistic for such a small problem, but should be suitable for large problems.

10.1 Program Text

Program Text (f08cwfe.f90)

10.2 Program Data

Program Data (f08cwfe.d)

10.3 Program Results

Program Results (f08cwfe.r)

F08 Chapter Contents
F08 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F08CXF (ZUNMRQ) : NAG Library, Mark 26

F08 Chapter Contents
F08 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F08CXF (ZUNMRQ)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
10 Example

1 Purpose

F08CXF (ZUNMRQ) multiplies a general complex m by n matrix C by the complex unitary matrix Q from an RQ factorization computed by F08CVF (ZGERQF).

2 Specification

SUBROUTINE F08CXF ( SIDE, TRANS, M, N, K, A, LDA, TAU, C, LDC, WORK, LWORK, INFO)
INTEGER | M, N, K, LDA, LDC, LWORK, INFO
COMPLEX (KIND=nag_wp) | A(LDA,*), TAU(*), C(LDC,*), WORK(max(1,LWORK))
CHARACTER(1) | SIDE, TRANS
The routine may be called by its LAPACK name zunmrq.

3 Description

F08CXF (ZUNMRQ) is intended to be used following a call to F08CVF (ZGERQF), which performs an RQ factorization of a complex matrix A and represents the unitary matrix Q as a product of elementary reflectors.
This routine may be used to form one of the matrix products
QC ,   QH C ,   CQ ,   C QH ,
overwriting the result on C, which may be any complex rectangular m by n matrix.
A common application of this routine is in solving underdetermined linear least squares problems, as described in the F08 Chapter Introduction, and illustrated in Section 10 in F08CVF (ZGERQF).

4 References

Anderson E, Bai Z, Bischof C, Blackford S, Demmel J, Dongarra J J, Du Croz J J, Greenbaum A, Hammarling S, McKenney A and Sorensen D (1999) LAPACK Users' Guide (3rd Edition) SIAM, Philadelphia http://www.netlib.org/lapack/lug
Golub G H and Van Loan C F (1996) Matrix Computations (3rd Edition) Johns Hopkins University Press, Baltimore

5 Arguments

1:   SIDE – CHARACTER(1)Input
On entry: indicates how Q or QH is to be applied to C.
SIDE='L'
Q or QH is applied to C from the left.
SIDE='R'
Q or QH is applied to C from the right.
Constraint: SIDE='L' or 'R'.
2:   TRANS – CHARACTER(1)Input
On entry: indicates whether Q or QH is to be applied to C.
TRANS='N'
Q is applied to C.
TRANS='C'
QH is applied to C.
Constraint: TRANS='N' or 'C'.
3:   M – INTEGERInput
On entry: m, the number of rows of the matrix C.
Constraint: M≥0.
4:   N – INTEGERInput
On entry: n, the number of columns of the matrix C.
Constraint: N≥0.
5:   K – INTEGERInput
On entry: k, the number of elementary reflectors whose product defines the matrix Q.
Constraints:
  • if SIDE='L', M≥ K≥ 0 ;
  • if SIDE='R', N≥ K≥ 0 .
6:   A LDA* – COMPLEX (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array A must be at least max 1,M if SIDE='L' and at least max 1,N if SIDE='R'.
On entry: the ith row of A must contain the vector which defines the elementary reflector Hi, for i=1,2,…,k, as returned by F08CVF (ZGERQF).
On exit: is modified by F08CXF (ZUNMRQ) but restored on exit.
7:   LDA – INTEGERInput
On entry: the first dimension of the array A as declared in the (sub)program from which F08CXF (ZUNMRQ) is called.
Constraint: LDA≥max 1,K.
8:   TAU* – COMPLEX (KIND=nag_wp) arrayInput
Note: the dimension of the array TAU must be at least max 1,K.
On entry: TAU i must contain the scalar factor of the elementary reflector Hi, as returned by F08CVF (ZGERQF).
9:   C LDC* – COMPLEX (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array C must be at least max 1,N.
On entry: the m by n matrix C.
On exit: C is overwritten by QC or QH C or CQ or C QH as specified by SIDE and TRANS.
10:   LDC – INTEGERInput
On entry: the first dimension of the array C as declared in the (sub)program from which F08CXF (ZUNMRQ) is called.
Constraint: LDC≥max 1,M.
11:   WORK max 1,LWORK – COMPLEX (KIND=nag_wp) arrayWorkspace
On exit: if INFO=0, the real part of WORK 1 contains the minimum value of LWORK required for optimal performance.
12:   LWORK – INTEGERInput
On entry: the dimension of the array WORK as declared in the (sub)program from which F08CXF (ZUNMRQ) is called.
If LWORK=-1, a workspace query is assumed; the routine only calculates the optimal size of the WORK array, returns this value as the first entry of the WORK array, and no error message related to LWORK is issued.
Suggested value: for optimal performance, LWORK≥N×nb if SIDE='L' and at least M×nb if SIDE='R', where nb is the optimal block size.
Constraints:
  • if SIDE='L', LWORK≥max 1,N or LWORK=-1;
  • if SIDE='R', LWORK≥max 1,M or LWORK=-1.
13:   INFO – INTEGEROutput
On exit: INFO=0 unless the routine detects an error (see Section 6).

6 Error Indicators and Warnings

INFO<0
If INFO=-i, argument i had an illegal value.
If INFO=-999, dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.
An explanatory message is output, and execution of the program is terminated.

7 Accuracy

The computed result differs from the exact result by a matrix E such that
E 2 = O⁡ε C 2
where ε is the machine precision.

8 Parallelism and Performance

F08CXF (ZUNMRQ) makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The total number of floating-point operations is approximately 8 nk 2 m-k if SIDE='L' and 8 mk 2 n-k if SIDE='R'.
The real analogue of this routine is F08CKF (DORMRQ).

10 Example

See Section 10 in F08CVF (ZGERQF).
F08 Chapter Contents
F08 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F08FAF (DSYEV) : NAG Library, Mark 26

F08 Chapter Contents
F08 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F08FAF (DSYEV)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F08FAF (DSYEV) computes all the eigenvalues and, optionally, all the eigenvectors of a real n by n symmetric matrix A.

2 Specification

SUBROUTINE F08FAF ( JOBZ, UPLO, N, A, LDA, W, WORK, LWORK, INFO)
INTEGER | N, LDA, LWORK, INFO
REAL (KIND=nag_wp) | A(LDA,*), W(N), WORK(max(1,LWORK))
CHARACTER(1) | JOBZ, UPLO
The routine may be called by its LAPACK name dsyev.

3 Description

The symmetric matrix A is first reduced to tridiagonal form, using orthogonal similarity transformations, and then the QR algorithm is applied to the tridiagonal matrix to compute the eigenvalues and (optionally) the eigenvectors.

4 References

Anderson E, Bai Z, Bischof C, Blackford S, Demmel J, Dongarra J J, Du Croz J J, Greenbaum A, Hammarling S, McKenney A and Sorensen D (1999) LAPACK Users' Guide (3rd Edition) SIAM, Philadelphia http://www.netlib.org/lapack/lug
Golub G H and Van Loan C F (1996) Matrix Computations (3rd Edition) Johns Hopkins University Press, Baltimore

5 Arguments

1:   JOBZ – CHARACTER(1)Input
On entry: indicates whether eigenvectors are computed.
JOBZ='N'
Only eigenvalues are computed.
JOBZ='V'
Eigenvalues and eigenvectors are computed.
Constraint: JOBZ='N' or 'V'.
2:   UPLO – CHARACTER(1)Input
On entry: if UPLO='U', the upper triangular part of A is stored.
If UPLO='L', the lower triangular part of A is stored.
Constraint: UPLO='U' or 'L'.
3:   N – INTEGERInput
On entry: n, the order of the matrix A.
Constraint: N≥0.
4:   A LDA* – REAL (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array A must be at least max 1,N.
On entry: the n by n symmetric matrix A.
  • If UPLO='U', the upper triangular part of A must be stored and the elements of the array below the diagonal are not referenced.
  • If UPLO='L', the lower triangular part of A must be stored and the elements of the array above the diagonal are not referenced.
On exit: if JOBZ='V', then A contains the orthonormal eigenvectors of the matrix A.
If JOBZ='N', then on exit the lower triangle (if UPLO='L') or the upper triangle (if UPLO='U') of A, including the diagonal, is overwritten.
5:   LDA – INTEGERInput
On entry: the first dimension of the array A as declared in the (sub)program from which F08FAF (DSYEV) is called.
Constraint: LDA≥max 1,N.
6:   W N – REAL (KIND=nag_wp) arrayOutput
On exit: the eigenvalues in ascending order.
7:   WORK max 1,LWORK – REAL (KIND=nag_wp) arrayWorkspace
On exit: if INFO=0, WORK 1 contains the minimum value of LWORK required for optimal performance.
8:   LWORK – INTEGERInput
On entry: the dimension of the array WORK as declared in the (sub)program from which F08FAF (DSYEV) is called.
If LWORK=-1, a workspace query is assumed; the routine only calculates the optimal size of the WORK array, returns this value as the first entry of the WORK array, and no error message related to LWORK is issued.
Suggested value: for optimal performance, LWORK≥nb+2×N, where nb is the optimal block size for F08FEF (DSYTRD).
Constraint: LWORK≥max 1,3×N-1.
9:   INFO – INTEGEROutput
On exit: INFO=0 unless the routine detects an error (see Section 6).

6 Error Indicators and Warnings

INFO<0
If INFO=-i, argument i had an illegal value. An explanatory message is output, and execution of the program is terminated.
INFO>0
If INFO=i, the algorithm failed to converge; i off-diagonal elements of an intermediate tridiagonal form did not converge to zero.

7 Accuracy

The computed eigenvalues and eigenvectors are exact for a nearby matrix A+E, where
E 2 = O ε A 2 ,
and ε is the machine precision. See Section 4.7 of Anderson et al. (1999) for further details.

8 Parallelism and Performance

F08FAF (DSYEV) is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
F08FAF (DSYEV) makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The total number of floating-point operations is proportional to n 3.
The complex analogue of this routine is F08FNF (ZHEEV).

10 Example

This example finds all the eigenvalues and eigenvectors of the symmetric matrix
A = 1 2 3 4 2 2 3 4 3 3 3 4 4 4 4 4 ,
together with approximate error bounds for the computed eigenvalues and eigenvectors.

10.1 Program Text

Program Text (f08fafe.f90)

10.2 Program Data

Program Data (f08fafe.d)

10.3 Program Results

Program Results (f08fafe.r)

F08 Chapter Contents
F08 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F08FBF (DSYEVX) : NAG Library, Mark 26

F08 Chapter Contents
F08 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F08FBF (DSYEVX)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F08FBF (DSYEVX) computes selected eigenvalues and, optionally, eigenvectors of a real n by n symmetric matrix A. Eigenvalues and eigenvectors can be selected by specifying either a range of values or a range of indices for the desired eigenvalues.

2 Specification

SUBROUTINE F08FBF ( JOBZ, RANGE, UPLO, N, A, LDA, VL, VU, IL, IU, ABSTOL, M, W, Z, LDZ, WORK, LWORK, IWORK, JFAIL, INFO)
INTEGER | N, LDA, IL, IU, M, LDZ, LWORK, IWORK(*), JFAIL(*), INFO
REAL (KIND=nag_wp) | A(LDA,*), VL, VU, ABSTOL, W(*), Z(LDZ,*), WORK(max(1,LWORK))
CHARACTER(1) | JOBZ, RANGE, UPLO
The routine may be called by its LAPACK name dsyevx.

3 Description

The symmetric matrix A is first reduced to tridiagonal form, using orthogonal similarity transformations. The required eigenvalues and eigenvectors are then computed from the tridiagonal matrix; the method used depends upon whether all, or selected, eigenvalues and eigenvectors are required.

4 References

Anderson E, Bai Z, Bischof C, Blackford S, Demmel J, Dongarra J J, Du Croz J J, Greenbaum A, Hammarling S, McKenney A and Sorensen D (1999) LAPACK Users' Guide (3rd Edition) SIAM, Philadelphia http://www.netlib.org/lapack/lug
Demmel J W and Kahan W (1990) Accurate singular values of bidiagonal matrices SIAM J. Sci. Statist. Comput. 11 873–912
Golub G H and Van Loan C F (1996) Matrix Computations (3rd Edition) Johns Hopkins University Press, Baltimore

5 Arguments

1:   JOBZ – CHARACTER(1)Input
On entry: indicates whether eigenvectors are computed.
JOBZ='N'
Only eigenvalues are computed.
JOBZ='V'
Eigenvalues and eigenvectors are computed.
Constraint: JOBZ='N' or 'V'.
2:   RANGE – CHARACTER(1)Input
On entry: if RANGE='A', all eigenvalues will be found.
If RANGE='V', all eigenvalues in the half-open interval VL,VU will be found.
If RANGE='I', the ILth to IUth eigenvalues will be found.
Constraint: RANGE='A', 'V' or 'I'.
3:   UPLO – CHARACTER(1)Input
On entry: if UPLO='U', the upper triangular part of A is stored.
If UPLO='L', the lower triangular part of A is stored.
Constraint: UPLO='U' or 'L'.
4:   N – INTEGERInput
On entry: n, the order of the matrix A.
Constraint: N≥0.
5:   A LDA* – REAL (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array A must be at least max 1,N.
On entry: the n by n symmetric matrix A.
  • If UPLO='U', the upper triangular part of A must be stored and the elements of the array below the diagonal are not referenced.
  • If UPLO='L', the lower triangular part of A must be stored and the elements of the array above the diagonal are not referenced.
On exit: the lower triangle (if UPLO='L') or the upper triangle (if UPLO='U') of A, including the diagonal, is overwritten.
6:   LDA – INTEGERInput
On entry: the first dimension of the array A as declared in the (sub)program from which F08FBF (DSYEVX) is called.
Constraint: LDA≥max 1,N.
7:   VL – REAL (KIND=nag_wp)Input
8:   VU – REAL (KIND=nag_wp)Input
On entry: if RANGE='V', the lower and upper bounds of the interval to be searched for eigenvalues.
If RANGE='A' or 'I', VL and VU are not referenced.
Constraint: if RANGE='V', VL<VU.
9:   IL – INTEGERInput
10:   IU – INTEGERInput
On entry: if RANGE='I', the indices (in ascending order) of the smallest and largest eigenvalues to be returned.
If RANGE='A' or 'V', IL and IU are not referenced.
Constraints:
  • if RANGE='I' and N=0, IL=1 and IU=0;
  • if RANGE='I' and N>0, 1≤ IL≤ IU≤ N .
11:   ABSTOL – REAL (KIND=nag_wp)Input
On entry: the absolute error tolerance for the eigenvalues. An approximate eigenvalue is accepted as converged when it is determined to lie in an interval a,b of width less than or equal to
ABSTOL+ε max a,b ,
where ε is the machine precision. If ABSTOL is less than or equal to zero, then ε T 1 will be used in its place, where T is the tridiagonal matrix obtained by reducing A to tridiagonal form. Eigenvalues will be computed most accurately when ABSTOL is set to twice the underflow threshold 2 × X02AMF , not zero. If this routine returns with INFO>0, indicating that some eigenvectors did not converge, try setting ABSTOL to 2 × X02AMF . See Demmel and Kahan (1990).
12:   M – INTEGEROutput
On exit: the total number of eigenvalues found. 0≤M≤N.
If RANGE='A', M=N.
If RANGE='I', M=IU-IL+1.
13:   W* – REAL (KIND=nag_wp) arrayOutput
Note: the dimension of the array W must be at least max 1,N.
On exit: the first M elements contain the selected eigenvalues in ascending order.
14:   Z LDZ* – REAL (KIND=nag_wp) arrayOutput
Note: the second dimension of the array Z must be at least max 1,M if JOBZ='V', and at least 1 otherwise.
On exit: if JOBZ='V', then
  • if INFO=0, the first M columns of Z contain the orthonormal eigenvectors of the matrix A corresponding to the selected eigenvalues, with the ith column of Z holding the eigenvector associated with W i;
  • if an eigenvector fails to converge (INFO>0), then that column of Z contains the latest approximation to the eigenvector, and the index of the eigenvector is returned in JFAIL.
If JOBZ='N', Z is not referenced.
Note: you must ensure that at least max 1,M columns are supplied in the array Z; if RANGE='V', the exact value of M is not known in advance and an upper bound of at least N must be used.
15:   LDZ – INTEGERInput
On entry: the first dimension of the array Z as declared in the (sub)program from which F08FBF (DSYEVX) is called.
Constraints:
  • if JOBZ='V', LDZ≥ max 1,N ;
  • otherwise LDZ≥1.
16:   WORK max 1,LWORK – REAL (KIND=nag_wp) arrayWorkspace
On exit: if INFO=0, WORK 1 contains the minimum value of LWORK required for optimal performance.
17:   LWORK – INTEGERInput
On entry: the dimension of the array WORK as declared in the (sub)program from which F08FBF (DSYEVX) is called.
If LWORK=-1, a workspace query is assumed; the routine only calculates the optimal size of the WORK array, returns this value as the first entry of the WORK array, and no error message related to LWORK is issued.
Suggested value: for optimal performance, LWORK≥nb+3×N, where nb is the largest optimal block size for F08FEF (DSYTRD) and F08FGF (DORMTR).
Constraints:
  • if N≤1, LWORK≥1;
  • otherwise LWORK≥8×N.
18:   IWORK* – INTEGER arrayWorkspace
Note: the dimension of the array IWORK must be at least max 1,5×N.
19:   JFAIL* – INTEGER arrayOutput
Note: the dimension of the array JFAIL must be at least max 1,N.
On exit: if JOBZ='V', then
  • if INFO=0, the first M elements of JFAIL are zero;
  • if INFO>0, JFAIL contains the indices of the eigenvectors that failed to converge.
If JOBZ='N', JFAIL is not referenced.
20:   INFO – INTEGEROutput
On exit: INFO=0 unless the routine detects an error (see Section 6).

6 Error Indicators and Warnings

INFO<0
If INFO=-i, argument i had an illegal value. An explanatory message is output, and execution of the program is terminated.
INFO>0
The algorithm failed to converge; value eigenvectors did not converge. Their indices are stored in array JFAIL.

7 Accuracy

The computed eigenvalues and eigenvectors are exact for a nearby matrix A+E, where
E 2 = O ε A 2 ,
and ε is the machine precision. See Section 4.7 of Anderson et al. (1999) for further details.

8 Parallelism and Performance

F08FBF (DSYEVX) is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
F08FBF (DSYEVX) makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The total number of floating-point operations is proportional to n 3.
The complex analogue of this routine is F08FPF (ZHEEVX).

10 Example

This example finds the eigenvalues in the half-open interval -1,1 , and the corresponding eigenvectors, of the symmetric matrix
A = 1 2 3 4 2 2 3 4 3 3 3 4 4 4 4 4 .

10.1 Program Text

Program Text (f08fbfe.f90)

10.2 Program Data

Program Data (f08fbfe.d)

10.3 Program Results

Program Results (f08fbfe.r)

F08 Chapter Contents
F08 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F08FCF (DSYEVD) : NAG Library, Mark 26

F08 Chapter Contents
F08 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F08FCF (DSYEVD)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.
Warning. The specification of the arguments LWORK and LIWORK changed at Mark 20 in the case where JOB='V' and N>1: the minimum dimension of the array WORK has been reduced whereas the minimum dimension of the array IWORK has been increased.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F08FCF (DSYEVD) computes all the eigenvalues and, optionally, all the eigenvectors of a real symmetric matrix. If the eigenvectors are requested, then it uses a divide-and-conquer algorithm to compute eigenvalues and eigenvectors. However, if only eigenvalues are required, then it uses the Pal–Walker–Kahan variant of the QL or QR algorithm.

2 Specification

SUBROUTINE F08FCF ( JOB, UPLO, N, A, LDA, W, WORK, LWORK, IWORK, LIWORK, INFO)
INTEGER | N, LDA, LWORK, IWORK(max(1,LIWORK)), LIWORK, INFO
REAL (KIND=nag_wp) | A(LDA,*), W(*), WORK(max(1,LWORK))
CHARACTER(1) | JOB, UPLO
The routine may be called by its LAPACK name dsyevd.

3 Description

F08FCF (DSYEVD) computes all the eigenvalues and, optionally, all the eigenvectors of a real symmetric matrix A. In other words, it can compute the spectral factorization of A as
A=ZΛ ZT,
where Λ is a diagonal matrix whose diagonal elements are the eigenvalues λi, and Z is the orthogonal matrix whose columns are the eigenvectors zi. Thus
A zi=λizi,  i=1,2,…,n.

4 References

Anderson E, Bai Z, Bischof C, Blackford S, Demmel J, Dongarra J J, Du Croz J J, Greenbaum A, Hammarling S, McKenney A and Sorensen D (1999) LAPACK Users' Guide (3rd Edition) SIAM, Philadelphia http://www.netlib.org/lapack/lug
Golub G H and Van Loan C F (1996) Matrix Computations (3rd Edition) Johns Hopkins University Press, Baltimore

5 Arguments

1:   JOB – CHARACTER(1)Input
On entry: indicates whether eigenvectors are computed.
JOB='N'
Only eigenvalues are computed.
JOB='V'
Eigenvalues and eigenvectors are computed.
Constraint: JOB='N' or 'V'.
2:   UPLO – CHARACTER(1)Input
On entry: indicates whether the upper or lower triangular part of A is stored.
UPLO='U'
The upper triangular part of A is stored.
UPLO='L'
The lower triangular part of A is stored.
Constraint: UPLO='U' or 'L'.
3:   N – INTEGERInput
On entry: n, the order of the matrix A.
Constraint: N≥0.
4:   A LDA* – REAL (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array A must be at least max 1,N.
On entry: the n by n symmetric matrix A.
  • If UPLO='U', the upper triangular part of A must be stored and the elements of the array below the diagonal are not referenced.
  • If UPLO='L', the lower triangular part of A must be stored and the elements of the array above the diagonal are not referenced.
On exit: if JOB='V', A is overwritten by the orthogonal matrix Z which contains the eigenvectors of A.
5:   LDA – INTEGERInput
On entry: the first dimension of the array A as declared in the (sub)program from which F08FCF (DSYEVD) is called.
Constraint: LDA≥max 1,N.
6:   W* – REAL (KIND=nag_wp) arrayOutput
Note: the dimension of the array W must be at least max 1,N.
On exit: the eigenvalues of the matrix A in ascending order.
7:   WORK max 1,LWORK – REAL (KIND=nag_wp) arrayWorkspace
On exit: if INFO=0, WORK 1 contains the required minimal size of LWORK.
8:   LWORK – INTEGERInput
On entry: the dimension of the array WORK as declared in the (sub)program from which F08FCF (DSYEVD) is called.
If LWORK=-1, a workspace query is assumed; the routine only calculates the minimum dimension of the WORK array, returns this value as the first entry of the WORK array, and no error message related to LWORK is issued.
Constraints:
  • if N≤1, LWORK≥1 or LWORK=-1;
  • if JOB='N' and N>1, LWORK≥2×N+1 or LWORK=-1;
  • if JOB='V' and N>1, LWORK≥2×N 2+6×N+1 or LWORK=-1.
9:   IWORK max 1,LIWORK – INTEGER arrayWorkspace
On exit: if INFO=0, IWORK 1 contains the required minimal size of LIWORK.
10:   LIWORK – INTEGERInput
On entry: the dimension of the array IWORK as declared in the (sub)program from which F08FCF (DSYEVD) is called.
If LIWORK=-1, a workspace query is assumed; the routine only calculates the minimum dimension of the IWORK array, returns this value as the first entry of the IWORK array, and no error message related to LIWORK is issued.
Constraints:
  • if N≤1, LIWORK≥1 or LIWORK=-1;
  • if JOB='N' and N>1, LIWORK≥1 or LIWORK=-1;
  • if JOB='V' and N>1, LIWORK≥5×N+3 or LIWORK=-1.
11:   INFO – INTEGEROutput
On exit: INFO=0 unless the routine detects an error (see Section 6).

6 Error Indicators and Warnings

INFO<0
If INFO=-i, argument i had an illegal value. An explanatory message is output, and execution of the program is terminated.
INFO>0
if INFO=i and JOB='N', the algorithm failed to converge; i elements of an intermediate tridiagonal form did not converge to zero; if INFO=i and JOB='V', then the algorithm failed to compute an eigenvalue while working on the submatrix lying in rows and column i/N+1 through i mod N+1.

7 Accuracy

The computed eigenvalues and eigenvectors are exact for a nearby matrix A+E, where
E 2 = O ε A 2 ,
and ε is the machine precision. See Section 4.7 of Anderson et al. (1999) for further details.

8 Parallelism and Performance

F08FCF (DSYEVD) is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
F08FCF (DSYEVD) makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The complex analogue of this routine is F08FQF (ZHEEVD).

10 Example

This example computes all the eigenvalues and eigenvectors of the symmetric matrix A, where
A = 1.0 2.0 3.0 4.0 2.0 2.0 3.0 4.0 3.0 3.0 3.0 4.0 4.0 4.0 4.0 4.0 .

10.1 Program Text

Program Text (f08fcfe.f90)

10.2 Program Data

Program Data (f08fcfe.d)

10.3 Program Results

Program Results (f08fcfe.r)

F08 Chapter Contents
F08 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F08FDF (DSYEVR) : NAG Library, Mark 26

F08 Chapter Contents
F08 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F08FDF (DSYEVR)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F08FDF (DSYEVR) computes selected eigenvalues and, optionally, eigenvectors of a real n by n symmetric matrix A. Eigenvalues and eigenvectors can be selected by specifying either a range of values or a range of indices for the desired eigenvalues.

2 Specification

SUBROUTINE F08FDF ( JOBZ, RANGE, UPLO, N, A, LDA, VL, VU, IL, IU, ABSTOL, M, W, Z, LDZ, ISUPPZ, WORK, LWORK, IWORK, LIWORK, INFO)
INTEGER | N, LDA, IL, IU, M, LDZ, ISUPPZ(*), LWORK, IWORK(max(1,LIWORK)), LIWORK, INFO
REAL (KIND=nag_wp) | A(LDA,*), VL, VU, ABSTOL, W(*), Z(LDZ,*), WORK(max(1,LWORK))
CHARACTER(1) | JOBZ, RANGE, UPLO
The routine may be called by its LAPACK name dsyevr.

3 Description

The symmetric matrix is first reduced to a tridiagonal matrix T, using orthogonal similarity transformations. Then whenever possible, F08FDF (DSYEVR) computes the eigenspectrum using Relatively Robust Representations. F08FDF (DSYEVR) computes eigenvalues by the dqds algorithm, while orthogonal eigenvectors are computed from various ‘good’ LD LT representations (also known as Relatively Robust Representations). Gram–Schmidt orthogonalization is avoided as far as possible. More specifically, the various steps of the algorithm are as follows. For the ith unreduced block of T:
(a) | compute T - σi I = Li Di LiT , such that Li Di LiT is a relatively robust representation,
(b) | compute the eigenvalues, λj, of Li Di LiT to high relative accuracy by the dqds algorithm,
(c) | if there is a cluster of close eigenvalues, ‘choose’ σi close to the cluster, and go to (a),
(d) | given the approximate eigenvalue λj of Li Di LiT , compute the corresponding eigenvector by forming a rank-revealing twisted factorization.
The desired accuracy of the output can be specified by the argument ABSTOL. For more details, see Dhillon (1997) and Parlett and Dhillon (2000).

4 References

Anderson E, Bai Z, Bischof C, Blackford S, Demmel J, Dongarra J J, Du Croz J J, Greenbaum A, Hammarling S, McKenney A and Sorensen D (1999) LAPACK Users' Guide (3rd Edition) SIAM, Philadelphia http://www.netlib.org/lapack/lug
Barlow J and Demmel J W (1990) Computing accurate eigensystems of scaled diagonally dominant matrices SIAM J. Numer. Anal. 27 762–791
Demmel J W and Kahan W (1990) Accurate singular values of bidiagonal matrices SIAM J. Sci. Statist. Comput. 11 873–912
Dhillon I (1997) A new O n 2 algorithm for the symmetric tridiagonal eigenvalue/eigenvector problem Computer Science Division Technical Report No. UCB//CSD-97-971 UC Berkeley
Golub G H and Van Loan C F (1996) Matrix Computations (3rd Edition) Johns Hopkins University Press, Baltimore
Parlett B N and Dhillon I S (2000) Relatively robust representations of symmetric tridiagonals Linear Algebra Appl. 309 121–151

5 Arguments

1:   JOBZ – CHARACTER(1)Input
On entry: indicates whether eigenvectors are computed.
JOBZ='N'
Only eigenvalues are computed.
JOBZ='V'
Eigenvalues and eigenvectors are computed.
Constraint: JOBZ='N' or 'V'.
2:   RANGE – CHARACTER(1)Input
On entry: if RANGE='A', all eigenvalues will be found.
If RANGE='V', all eigenvalues in the half-open interval VL,VU will be found.
If RANGE='I', the ILth to IUth eigenvalues will be found.
For RANGE='V' or 'I' and IU-IL<N-1, F08JJF (DSTEBZ) and F08JKF (DSTEIN) are called.
Constraint: RANGE='A', 'V' or 'I'.
3:   UPLO – CHARACTER(1)Input
On entry: if UPLO='U', the upper triangular part of A is stored.
If UPLO='L', the lower triangular part of A is stored.
Constraint: UPLO='U' or 'L'.
4:   N – INTEGERInput
On entry: n, the order of the matrix A.
Constraint: N≥0.
5:   A LDA* – REAL (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array A must be at least max 1,N.
On entry: the n by n symmetric matrix A.
  • If UPLO='U', the upper triangular part of A must be stored and the elements of the array below the diagonal are not referenced.
  • If UPLO='L', the lower triangular part of A must be stored and the elements of the array above the diagonal are not referenced.
On exit: the lower triangle (if UPLO='L') or the upper triangle (if UPLO='U') of A, including the diagonal, is overwritten.
6:   LDA – INTEGERInput
On entry: the first dimension of the array A as declared in the (sub)program from which F08FDF (DSYEVR) is called.
Constraint: LDA≥max 1,N.
7:   VL – REAL (KIND=nag_wp)Input
8:   VU – REAL (KIND=nag_wp)Input
On entry: if RANGE='V', the lower and upper bounds of the interval to be searched for eigenvalues.
If RANGE='A' or 'I', VL and VU are not referenced.
Constraint: if RANGE='V', VL<VU.
9:   IL – INTEGERInput
10:   IU – INTEGERInput
On entry: if RANGE='I', the indices (in ascending order) of the smallest and largest eigenvalues to be returned.
If RANGE='A' or 'V', IL and IU are not referenced.
Constraints:
  • if RANGE='I' and N=0, IL=1 and IU=0;
  • if RANGE='I' and N>0, 1≤ IL≤ IU≤ N .
11:   ABSTOL – REAL (KIND=nag_wp)Input
On entry: the absolute error tolerance for the eigenvalues. An approximate eigenvalue is accepted as converged when it is determined to lie in an interval a,b of width less than or equal to
ABSTOL+ε max a,b ,
where ε is the machine precision. If ABSTOL is less than or equal to zero, then ε T 1 will be used in its place, where T is the tridiagonal matrix obtained by reducing A to tridiagonal form. See Demmel and Kahan (1990).
If high relative accuracy is important, set ABSTOL to X02AMF , although doing so does not currently guarantee that eigenvalues are computed to high relative accuracy. See Barlow and Demmel (1990) for a discussion of which matrices can define their eigenvalues to high relative accuracy.
12:   M – INTEGEROutput
On exit: the total number of eigenvalues found. 0≤M≤N.
If RANGE='A', M=N.
If RANGE='I', M=IU-IL+1.
13:   W* – REAL (KIND=nag_wp) arrayOutput
Note: the dimension of the array W must be at least max 1,N.
On exit: the first M elements contain the selected eigenvalues in ascending order.
14:   Z LDZ* – REAL (KIND=nag_wp) arrayOutput
Note: the second dimension of the array Z must be at least max 1,M if JOBZ='V', and at least 1 otherwise.
On exit: if JOBZ='V', the first M columns of Z contain the orthonormal eigenvectors of the matrix A corresponding to the selected eigenvalues, with the ith column of Z holding the eigenvector associated with W i.
If JOBZ='N', Z is not referenced.
Note: you must ensure that at least max 1,M columns are supplied in the array Z; if RANGE='V', the exact value of M is not known in advance and an upper bound of at least N must be used.
15:   LDZ – INTEGERInput
On entry: the first dimension of the array Z as declared in the (sub)program from which F08FDF (DSYEVR) is called.
Constraints:
  • if JOBZ='V', LDZ≥ max 1,N ;
  • otherwise LDZ≥1.
16:   ISUPPZ* – INTEGER arrayOutput
Note: the dimension of the array ISUPPZ must be at least max 1,2×M.
On exit: the support of the eigenvectors in Z, i.e., the indices indicating the nonzero elements in Z. The ith eigenvector is nonzero only in elements ISUPPZ 2×i-1 through ISUPPZ 2×i. Implemented only for RANGE='A' or 'I' and IU-IL=N-1.
17:   WORK max 1,LWORK – REAL (KIND=nag_wp) arrayWorkspace
On exit: if INFO=0, WORK 1 contains the minimum value of LWORK required for optimal performance.
18:   LWORK – INTEGERInput
On entry: the dimension of the array WORK as declared in the (sub)program from which F08FDF (DSYEVR) is called.
If LWORK=-1, a workspace query is assumed; the routine only calculates the optimal size of the WORK array and the minimum size of the IWORK array, returns these values as the first entries of the WORK and IWORK arrays, and no error message related to LWORK or LIWORK is issued.
Suggested value: for optimal performance, LWORK≥nb+6×N, where nb is the largest optimal block size for F08FEF (DSYTRD) and F08FGF (DORMTR).
Constraint: LWORK≥max 1,26×N.
19:   IWORK max 1,LIWORK – INTEGER arrayWorkspace
On exit: if INFO=0, IWORK 1 returns the minimum LIWORK.
20:   LIWORK – INTEGERInput
On entry: the dimension of the array IWORK as declared in the (sub)program from which F08FDF (DSYEVR) is called.
If LIWORK=-1, a workspace query is assumed; the routine only calculates the optimal size of the WORK array and the minimum size of the IWORK array, returns these values as the first entries of the WORK and IWORK arrays, and no error message related to LWORK or LIWORK is issued.
Constraint: LIWORK≥max 1,10×N.
21:   INFO – INTEGEROutput
On exit: INFO=0 unless the routine detects an error (see Section 6).

6 Error Indicators and Warnings

INFO<0
If INFO=-i, argument i had an illegal value. An explanatory message is output, and execution of the program is terminated.
INFO>0
F08FDF (DSYEVR) failed to converge.

7 Accuracy

The computed eigenvalues and eigenvectors are exact for a nearby matrix A+E, where
E 2 = O ε A 2 ,
and ε is the machine precision. See Section 4.7 of Anderson et al. (1999) for further details.

8 Parallelism and Performance

F08FDF (DSYEVR) is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
F08FDF (DSYEVR) makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The total number of floating-point operations is proportional to n 3.
The complex analogue of this routine is F08FRF (ZHEEVR).

10 Example

This example finds the eigenvalues with indices in the range 2,3 , and the corresponding eigenvectors, of the symmetric matrix
A = 1 2 3 4 2 2 3 4 3 3 3 4 4 4 4 4 .
Information on required and provided workspace is also output.

10.1 Program Text

Program Text (f08fdfe.f90)

10.2 Program Data

Program Data (f08fdfe.d)

10.3 Program Results

Program Results (f08fdfe.r)

F08 Chapter Contents
F08 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F08FEF (DSYTRD) : NAG Library, Mark 26

F08 Chapter Contents
F08 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F08FEF (DSYTRD)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F08FEF (DSYTRD) reduces a real symmetric matrix to tridiagonal form.

2 Specification

SUBROUTINE F08FEF ( UPLO, N, A, LDA, D, E, TAU, WORK, LWORK, INFO)
INTEGER | N, LDA, LWORK, INFO
REAL (KIND=nag_wp) | A(LDA,*), D(*), E(*), TAU(*), WORK(max(1,LWORK))
CHARACTER(1) | UPLO
The routine may be called by its LAPACK name dsytrd.

3 Description

F08FEF (DSYTRD) reduces a real symmetric matrix A to symmetric tridiagonal form T by an orthogonal similarity transformation: A=QT QT.
The matrix Q is not formed explicitly but is represented as a product of n-1 elementary reflectors (see the F08 Chapter Introduction for details). Routines are provided to work with Q in this representation (see Section 9).

4 References

Golub G H and Van Loan C F (1996) Matrix Computations (3rd Edition) Johns Hopkins University Press, Baltimore

5 Arguments

1:   UPLO – CHARACTER(1)Input
On entry: indicates whether the upper or lower triangular part of A is stored.
UPLO='U'
The upper triangular part of A is stored.
UPLO='L'
The lower triangular part of A is stored.
Constraint: UPLO='U' or 'L'.
2:   N – INTEGERInput
On entry: n, the order of the matrix A.
Constraint: N≥0.
3:   A LDA* – REAL (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array A must be at least max 1,N.
On entry: the n by n symmetric matrix A.
  • If UPLO='U', the upper triangular part of A must be stored and the elements of the array below the diagonal are not referenced.
  • If UPLO='L', the lower triangular part of A must be stored and the elements of the array above the diagonal are not referenced.
On exit: A is overwritten by the tridiagonal matrix T and details of the orthogonal matrix Q as specified by UPLO.
4:   LDA – INTEGERInput
On entry: the first dimension of the array A as declared in the (sub)program from which F08FEF (DSYTRD) is called.
Constraint: LDA≥max 1,N.
5:   D* – REAL (KIND=nag_wp) arrayOutput
Note: the dimension of the array D must be at least max 1,N.
On exit: the diagonal elements of the tridiagonal matrix T.
6:   E* – REAL (KIND=nag_wp) arrayOutput
Note: the dimension of the array E must be at least max 1,N-1.
On exit: the off-diagonal elements of the tridiagonal matrix T.
7:   TAU* – REAL (KIND=nag_wp) arrayOutput
Note: the dimension of the array TAU must be at least max 1,N-1.
On exit: further details of the orthogonal matrix Q.
8:   WORK max 1,LWORK – REAL (KIND=nag_wp) arrayWorkspace
On exit: if INFO=0, WORK 1 contains the minimum value of LWORK required for optimal performance.
9:   LWORK – INTEGERInput
On entry: the dimension of the array WORK as declared in the (sub)program from which F08FEF (DSYTRD) is called.
If LWORK=-1, a workspace query is assumed; the routine only calculates the optimal size of the WORK array, returns this value as the first entry of the WORK array, and no error message related to LWORK is issued.
Suggested value: for optimal performance, LWORK≥N×nb, where nb is the optimal block size.
Constraint: LWORK≥1 or LWORK=-1.
10:   INFO – INTEGEROutput
On exit: INFO=0 unless the routine detects an error (see Section 6).

6 Error Indicators and Warnings

INFO<0
If INFO=-i, argument i had an illegal value. An explanatory message is output, and execution of the program is terminated.

7 Accuracy

The computed tridiagonal matrix T is exactly similar to a nearby matrix A+E, where
E 2≤ c n ε A 2 ,
c n is a modestly increasing function of n, and ε is the machine precision.
The elements of T themselves may be sensitive to small perturbations in A or to rounding errors in the computation, but this does not affect the stability of the eigenvalues and eigenvectors.

8 Parallelism and Performance

F08FEF (DSYTRD) is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
F08FEF (DSYTRD) makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The total number of floating-point operations is approximately 43 n 3 .
To form the orthogonal matrix Q F08FEF (DSYTRD) may be followed by a call to F08FFF (DORGTR):
CALL DORGTR(UPLO,N,A,LDA,TAU,WORK,LWORK,INFO)
To apply Q to an n by p real matrix C F08FEF (DSYTRD) may be followed by a call to F08FGF (DORMTR). For example,
CALL DORMTR('Left',UPLO,'No Transpose',N,P,A,LDA,TAU,C,LDC, &
              WORK,LWORK,INFO)
forms the matrix product QC.
The complex analogue of this routine is F08FSF (ZHETRD).

10 Example

This example reduces the matrix A to tridiagonal form, where
A = 2.07 3.87 4.20 -1.15 3.87 -0.21 1.87 0.63 4.20 1.87 1.15 2.06 -1.15 0.63 2.06 -1.81 .

10.1 Program Text

Program Text (f08fefe.f90)

10.2 Program Data

Program Data (f08fefe.d)

10.3 Program Results

Program Results (f08fefe.r)

F08 Chapter Contents
F08 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F08FFF (DORGTR) : NAG Library, Mark 26

F08 Chapter Contents
F08 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F08FFF (DORGTR)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F08FFF (DORGTR) generates the real orthogonal matrix Q, which was determined by F08FEF (DSYTRD) when reducing a symmetric matrix to tridiagonal form.

2 Specification

SUBROUTINE F08FFF ( UPLO, N, A, LDA, TAU, WORK, LWORK, INFO)
INTEGER | N, LDA, LWORK, INFO
REAL (KIND=nag_wp) | A(LDA,*), TAU(*), WORK(max(1,LWORK))
CHARACTER(1) | UPLO
The routine may be called by its LAPACK name dorgtr.

3 Description

F08FFF (DORGTR) is intended to be used after a call to F08FEF (DSYTRD), which reduces a real symmetric matrix A to symmetric tridiagonal form T by an orthogonal similarity transformation: A=QT QT. F08FEF (DSYTRD) represents the orthogonal matrix Q as a product of n-1 elementary reflectors.
This routine may be used to generate Q explicitly as a square matrix.

4 References

Golub G H and Van Loan C F (1996) Matrix Computations (3rd Edition) Johns Hopkins University Press, Baltimore

5 Arguments

1:   UPLO – CHARACTER(1)Input
On entry: this must be the same argument UPLO as supplied to F08FEF (DSYTRD).
Constraint: UPLO='U' or 'L'.
2:   N – INTEGERInput
On entry: n, the order of the matrix Q.
Constraint: N≥0.
3:   A LDA* – REAL (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array A must be at least max 1,N.
On entry: details of the vectors which define the elementary reflectors, as returned by F08FEF (DSYTRD).
On exit: the n by n orthogonal matrix Q.
4:   LDA – INTEGERInput
On entry: the first dimension of the array A as declared in the (sub)program from which F08FFF (DORGTR) is called.
Constraint: LDA≥max 1,N.
5:   TAU* – REAL (KIND=nag_wp) arrayInput
Note: the dimension of the array TAU must be at least max 1,N-1.
On entry: further details of the elementary reflectors, as returned by F08FEF (DSYTRD).
6:   WORK max 1,LWORK – REAL (KIND=nag_wp) arrayWorkspace
On exit: if INFO=0, WORK 1 contains the minimum value of LWORK required for optimal performance.
7:   LWORK – INTEGERInput
On entry: the dimension of the array WORK as declared in the (sub)program from which F08FFF (DORGTR) is called.
If LWORK=-1, a workspace query is assumed; the routine only calculates the optimal size of the WORK array, returns this value as the first entry of the WORK array, and no error message related to LWORK is issued.
Suggested value: for optimal performance, LWORK≥N-1×nb, where nb is the optimal block size.
Constraint: LWORK≥max 1,N-1 or LWORK=-1.
8:   INFO – INTEGEROutput
On exit: INFO=0 unless the routine detects an error (see Section 6).

6 Error Indicators and Warnings

INFO<0
If INFO=-i, argument i had an illegal value. An explanatory message is output, and execution of the program is terminated.

7 Accuracy

The computed matrix Q differs from an exactly orthogonal matrix by a matrix E such that
E 2 = O ε ,
where ε is the machine precision.

8 Parallelism and Performance

F08FFF (DORGTR) is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
F08FFF (DORGTR) makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The total number of floating-point operations is approximately 43 n 3.
The complex analogue of this routine is F08FTF (ZUNGTR).

10 Example

This example computes all the eigenvalues and eigenvectors of the matrix A, where
A = 2.07 3.87 4.20 -1.15 3.87 -0.21 1.87 0.63 4.20 1.87 1.15 2.06 -1.15 0.63 2.06 -1.81 .
Here A is symmetric and must first be reduced to tridiagonal form by F08FEF (DSYTRD). The program then calls F08FFF (DORGTR) to form Q, and passes this matrix to F08JEF (DSTEQR) which computes the eigenvalues and eigenvectors of A.

10.1 Program Text

Program Text (f08fffe.f90)

10.2 Program Data

Program Data (f08fffe.d)

10.3 Program Results

Program Results (f08fffe.r)

F08 Chapter Contents
F08 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F08FGF (DORMTR) : NAG Library, Mark 26

F08 Chapter Contents
F08 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F08FGF (DORMTR)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F08FGF (DORMTR) multiplies an arbitrary real matrix C by the real orthogonal matrix Q which was determined by F08FEF (DSYTRD) when reducing a real symmetric matrix to tridiagonal form.

2 Specification

SUBROUTINE F08FGF ( SIDE, UPLO, TRANS, M, N, A, LDA, TAU, C, LDC, WORK, LWORK, INFO)
INTEGER | M, N, LDA, LDC, LWORK, INFO
REAL (KIND=nag_wp) | A(LDA,*), TAU(*), C(LDC,*), WORK(max(1,LWORK))
CHARACTER(1) | SIDE, UPLO, TRANS
The routine may be called by its LAPACK name dormtr.

3 Description

F08FGF (DORMTR) is intended to be used after a call to F08FEF (DSYTRD), which reduces a real symmetric matrix A to symmetric tridiagonal form T by an orthogonal similarity transformation: A=QT QT. F08FEF (DSYTRD) represents the orthogonal matrix Q as a product of elementary reflectors.
This routine may be used to form one of the matrix products
QC , QT C , CQ ​ or ​ C QT ,
overwriting the result on C (which may be any real rectangular matrix).
A common application of this routine is to transform a matrix Z of eigenvectors of T to the matrix QZ of eigenvectors of A.

4 References

Golub G H and Van Loan C F (1996) Matrix Computations (3rd Edition) Johns Hopkins University Press, Baltimore

5 Arguments

1:   SIDE – CHARACTER(1)Input
On entry: indicates how Q or QT is to be applied to C.
SIDE='L'
Q or QT is applied to C from the left.
SIDE='R'
Q or QT is applied to C from the right.
Constraint: SIDE='L' or 'R'.
2:   UPLO – CHARACTER(1)Input
On entry: this must be the same argument UPLO as supplied to F08FEF (DSYTRD).
Constraint: UPLO='U' or 'L'.
3:   TRANS – CHARACTER(1)Input
On entry: indicates whether Q or QT is to be applied to C.
TRANS='N'
Q is applied to C.
TRANS='T'
QT is applied to C.
Constraint: TRANS='N' or 'T'.
4:   M – INTEGERInput
On entry: m, the number of rows of the matrix C; m is also the order of Q if SIDE='L'.
Constraint: M≥0.
5:   N – INTEGERInput
On entry: n, the number of columns of the matrix C; n is also the order of Q if SIDE='R'.
Constraint: N≥0.
6:   A LDA* – REAL (KIND=nag_wp) arrayInput
Note: the second dimension of the array A must be at least max 1,M if SIDE='L' and at least max 1,N if SIDE='R'.
On entry: details of the vectors which define the elementary reflectors, as returned by F08FEF (DSYTRD).
7:   LDA – INTEGERInput
On entry: the first dimension of the array A as declared in the (sub)program from which F08FGF (DORMTR) is called.
Constraints:
  • if SIDE='L', LDA≥ max 1,M ;
  • if SIDE='R', LDA≥ max 1,N .
8:   TAU* – REAL (KIND=nag_wp) arrayInput
Note: the dimension of the array TAU must be at least max 1,M-1 if SIDE='L' and at least max 1,N-1 if SIDE='R'.
On entry: further details of the elementary reflectors, as returned by F08FEF (DSYTRD).
9:   C LDC* – REAL (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array C must be at least max 1,N.
On entry: the m by n matrix C.
On exit: C is overwritten by QC or QT C or CQ or C QT as specified by SIDE and TRANS.
10:   LDC – INTEGERInput
On entry: the first dimension of the array C as declared in the (sub)program from which F08FGF (DORMTR) is called.
Constraint: LDC≥max 1,M.
11:   WORK max 1,LWORK – REAL (KIND=nag_wp) arrayWorkspace
On exit: if INFO=0, WORK 1 contains the minimum value of LWORK required for optimal performance.
12:   LWORK – INTEGERInput
On entry: the dimension of the array WORK as declared in the (sub)program from which F08FGF (DORMTR) is called.
If LWORK=-1, a workspace query is assumed; the routine only calculates the optimal size of the WORK array, returns this value as the first entry of the WORK array, and no error message related to LWORK is issued.
Suggested value: for optimal performance, LWORK≥N×nb if SIDE='L' and at least M×nb if SIDE='R', where nb is the optimal block size.
Constraints:
  • if SIDE='L', LWORK≥max 1,N or LWORK=-1;
  • if SIDE='R', LWORK≥max 1,M or LWORK=-1.
13:   INFO – INTEGEROutput
On exit: INFO=0 unless the routine detects an error (see Section 6).

6 Error Indicators and Warnings

INFO<0
If INFO=-i, argument i had an illegal value. An explanatory message is output, and execution of the program is terminated.

7 Accuracy

The computed result differs from the exact result by a matrix E such that
E 2 = O ε C 2 ,
where ε is the machine precision.

8 Parallelism and Performance

F08FGF (DORMTR) is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
F08FGF (DORMTR) makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The total number of floating-point operations is approximately 2 m 2 n if SIDE='L' and 2 m n 2 if SIDE='R'.
The complex analogue of this routine is F08FUF (ZUNMTR).

10 Example

This example computes the two smallest eigenvalues, and the associated eigenvectors, of the matrix A, where
A = 2.07 3.87 4.20 -1.15 3.87 -0.21 1.87 0.63 4.20 1.87 1.15 2.06 -1.15 0.63 2.06 -1.81 .
Here A is symmetric and must first be reduced to tridiagonal form T by F08FEF (DSYTRD). The program then calls F08JJF (DSTEBZ) to compute the requested eigenvalues and F08JKF (DSTEIN) to compute the associated eigenvectors of T. Finally F08FGF (DORMTR) is called to transform the eigenvectors to those of A.

10.1 Program Text

Program Text (f08fgfe.f90)

10.2 Program Data

Program Data (f08fgfe.d)

10.3 Program Results

Program Results (f08fgfe.r)

F08 Chapter Contents
F08 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F08FLF (DDISNA) : NAG Library, Mark 26

F08 Chapter Contents
F08 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F08FLF (DDISNA)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
10 Example

1 Purpose

F08FLF (DDISNA) computes the reciprocal condition numbers for the eigenvectors of a real symmetric or complex Hermitian m by m matrix A, or for the left or right singular vectors of a general m by n matrix A.

2 Specification

SUBROUTINE F08FLF ( JOB, M, N, D, SEP, INFO)
INTEGER | M, N, INFO
REAL (KIND=nag_wp) | D(*), SEP(*)
CHARACTER(1) | JOB
The routine may be called by its LAPACK name ddisna.

3 Description

The bound on the error, measured by the angle in radians, for the ith computed vector is given by ε A 2 / sepi , where ε is the machine precision and sepi is the reciprocal condition number for the vectors, returned in the array element SEP i . SEP i is restricted to be at least ε A 2 in order to limit the size of the error bound.

4 References

Golub G H and Van Loan C F (1996) Matrix Computations (3rd Edition) Johns Hopkins University Press, Baltimore

5 Arguments

1:   JOB – CHARACTER(1)Input
On entry: specifies for which problem the reciprocal condition number should be computed.
JOB='E'
The eigenvectors of a symmetric or Hermitian matrix.
JOB='L'
The left singular vectors of a general matrix.
JOB='R'
The right singular vectors of a general matrix.
Constraint: JOB='E', 'L' or 'R'.
2:   M – INTEGERInput
On entry: m, the number of rows of the matrix A.
Constraint: M≥0.
3:   N – INTEGERInput
On entry: n, the number of columns of the matrix when JOB='L' or 'R'.
If JOB='E', N is not referenced.
Constraint: if JOB='L' or 'R', N≥0.
4:   D* – REAL (KIND=nag_wp) arrayInput
Note: the dimension of the array D must be at least max 1,M if JOB='E' and at least max 1,min M,N if JOB='L' or 'R'.
On entry: the eigenvalues if JOB='E', or singular values if JOB='L' or 'R' of the matrix A.
Constraints:
  • the elements of the array D must be in either increasing or decreasing order;
  • if JOB='L' or 'R' the elements of D must be non-negative.
5:   SEP* – REAL (KIND=nag_wp) arrayOutput
Note: the dimension of the array SEP must be at least max 1,M if JOB='E' and at least max 1,min M,N if JOB='L' or 'R'.
On exit: the reciprocal condition numbers of the vectors.
6:   INFO – INTEGEROutput
On exit: INFO=0 unless the routine detects an error (see Section 6).

6 Error Indicators and Warnings

INFO<0
If INFO=-i, argument i had an illegal value. An explanatory message is output, and execution of the program is terminated.

7 Accuracy

The reciprocal condition numbers are computed to machine precision relative to the size of the eigenvalues, or singular values.

8 Parallelism and Performance

F08FLF (DDISNA) is not threaded in any implementation.

9 Further Comments

F08FLF (DDISNA) may also be used towards computing error bounds for the eigenvectors of the generalized symmetric or Hermitian definite eigenproblem. See Golub and Van Loan (1996) for further details on the error bounds.

10 Example

The use of F08FLF (DDISNA) in computing error bounds for eigenvectors of the symmetric eigenvalue problem is illustrated in Section 10 in F08FAF (DSYEV); its use in computing error bounds for singular vectors is illustrated in Section 10 in F08KBF (DGESVD); and its use in computing error bounds for eigenvectors of the generalized symmetric definite eigenvalue problem is illustrated in Section 10 in F08SAF (DSYGV).
F08 Chapter Contents
F08 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F08FNF (ZHEEV) : NAG Library, Mark 26

F08 Chapter Contents
F08 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F08FNF (ZHEEV)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F08FNF (ZHEEV) computes all the eigenvalues and, optionally, all the eigenvectors of a complex n by n Hermitian matrix A.

2 Specification

SUBROUTINE F08FNF ( JOBZ, UPLO, N, A, LDA, W, WORK, LWORK, RWORK, INFO)
INTEGER | N, LDA, LWORK, INFO
REAL (KIND=nag_wp) | W(N), RWORK(*)
COMPLEX (KIND=nag_wp) | A(LDA,*), WORK(max(1,LWORK))
CHARACTER(1) | JOBZ, UPLO
The routine may be called by its LAPACK name zheev.

3 Description

The Hermitian matrix A is first reduced to real tridiagonal form, using unitary similarity transformations, and then the QR algorithm is applied to the tridiagonal matrix to compute the eigenvalues and (optionally) the eigenvectors.

4 References

Anderson E, Bai Z, Bischof C, Blackford S, Demmel J, Dongarra J J, Du Croz J J, Greenbaum A, Hammarling S, McKenney A and Sorensen D (1999) LAPACK Users' Guide (3rd Edition) SIAM, Philadelphia http://www.netlib.org/lapack/lug
Golub G H and Van Loan C F (1996) Matrix Computations (3rd Edition) Johns Hopkins University Press, Baltimore

5 Arguments

1:   JOBZ – CHARACTER(1)Input
On entry: indicates whether eigenvectors are computed.
JOBZ='N'
Only eigenvalues are computed.
JOBZ='V'
Eigenvalues and eigenvectors are computed.
Constraint: JOBZ='N' or 'V'.
2:   UPLO – CHARACTER(1)Input
On entry: if UPLO='U', the upper triangular part of A is stored.
If UPLO='L', the lower triangular part of A is stored.
Constraint: UPLO='U' or 'L'.
3:   N – INTEGERInput
On entry: n, the order of the matrix A.
Constraint: N≥0.
4:   A LDA* – COMPLEX (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array A must be at least max 1,N.
On entry: the n by n Hermitian matrix A.
  • If UPLO='U', the upper triangular part of A must be stored and the elements of the array below the diagonal are not referenced.
  • If UPLO='L', the lower triangular part of A must be stored and the elements of the array above the diagonal are not referenced.
On exit: if JOBZ='V', then A contains the orthonormal eigenvectors of the matrix A.
If JOBZ='N', then on exit the lower triangle (if UPLO='L') or the upper triangle (if UPLO='U') of A, including the diagonal, is overwritten.
5:   LDA – INTEGERInput
On entry: the first dimension of the array A as declared in the (sub)program from which F08FNF (ZHEEV) is called.
Constraint: LDA≥max 1,N.
6:   W N – REAL (KIND=nag_wp) arrayOutput
On exit: the eigenvalues in ascending order.
7:   WORK max 1,LWORK – COMPLEX (KIND=nag_wp) arrayWorkspace
On exit: if INFO=0, the real part of WORK 1 contains the minimum value of LWORK required for optimal performance.
8:   LWORK – INTEGERInput
On entry: the dimension of the array WORK as declared in the (sub)program from which F08FNF (ZHEEV) is called.
If LWORK=-1, a workspace query is assumed; the routine only calculates the optimal size of the WORK array, returns this value as the first entry of the WORK array, and no error message related to LWORK is issued.
Suggested value: for optimal performance, LWORK≥nb+1×N, where nb is the optimal block size for F08FSF (ZHETRD).
Constraint: LWORK≥max 1,2×N.
9:   RWORK* – REAL (KIND=nag_wp) arrayWorkspace
Note: the dimension of the array RWORK must be at least max 1,3×N-2.
10:   INFO – INTEGEROutput
On exit: INFO=0 unless the routine detects an error (see Section 6).

6 Error Indicators and Warnings

INFO<0
If INFO=-i, argument i had an illegal value. An explanatory message is output, and execution of the program is terminated.
INFO>0
If INFO=i, the algorithm failed to converge; i off-diagonal elements of an intermediate tridiagonal form did not converge to zero.

7 Accuracy

The computed eigenvalues and eigenvectors are exact for a nearby matrix A+E, where
E 2 = O ε A 2 ,
and ε is the machine precision. See Section 4.7 of Anderson et al. (1999) for further details.

8 Parallelism and Performance

F08FNF (ZHEEV) is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
F08FNF (ZHEEV) makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

Each eigenvector is normalized so that the element of largest absolute value is real.
The total number of floating-point operations is proportional to n 3.
The real analogue of this routine is F08FAF (DSYEV).

10 Example

This example finds all the eigenvalues and eigenvectors of the Hermitian matrix
A = 1 2-i 3-i 4-i 2+i 2 3-2 i 4-2 i 3+i 3+2 i 3 4-3 i 4+i 4+2 i 4+3 i 4 ,
together with approximate error bounds for the computed eigenvalues and eigenvectors.

10.1 Program Text

Program Text (f08fnfe.f90)

10.2 Program Data

Program Data (f08fnfe.d)

10.3 Program Results

Program Results (f08fnfe.r)

F08 Chapter Contents
F08 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F08FPF (ZHEEVX) : NAG Library, Mark 26

F08 Chapter Contents
F08 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F08FPF (ZHEEVX)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F08FPF (ZHEEVX) computes selected eigenvalues and, optionally, eigenvectors of a complex n by n Hermitian matrix A. Eigenvalues and eigenvectors can be selected by specifying either a range of values or a range of indices for the desired eigenvalues.

2 Specification

SUBROUTINE F08FPF ( JOBZ, RANGE, UPLO, N, A, LDA, VL, VU, IL, IU, ABSTOL, M, W, Z, LDZ, WORK, LWORK, RWORK, IWORK, JFAIL, INFO)
INTEGER | N, LDA, IL, IU, M, LDZ, LWORK, IWORK(*), JFAIL(*), INFO
REAL (KIND=nag_wp) | VL, VU, ABSTOL, W(*), RWORK(*)
COMPLEX (KIND=nag_wp) | A(LDA,*), Z(LDZ,*), WORK(max(1,LWORK))
CHARACTER(1) | JOBZ, RANGE, UPLO
The routine may be called by its LAPACK name zheevx.

3 Description

The Hermitian matrix A is first reduced to real tridiagonal form, using unitary similarity transformations. The required eigenvalues and eigenvectors are then computed from the tridiagonal matrix; the method used depends upon whether all, or selected, eigenvalues and eigenvectors are required.

4 References

Anderson E, Bai Z, Bischof C, Blackford S, Demmel J, Dongarra J J, Du Croz J J, Greenbaum A, Hammarling S, McKenney A and Sorensen D (1999) LAPACK Users' Guide (3rd Edition) SIAM, Philadelphia http://www.netlib.org/lapack/lug
Demmel J W and Kahan W (1990) Accurate singular values of bidiagonal matrices SIAM J. Sci. Statist. Comput. 11 873–912
Golub G H and Van Loan C F (1996) Matrix Computations (3rd Edition) Johns Hopkins University Press, Baltimore

5 Arguments

1:   JOBZ – CHARACTER(1)Input
On entry: indicates whether eigenvectors are computed.
JOBZ='N'
Only eigenvalues are computed.
JOBZ='V'
Eigenvalues and eigenvectors are computed.
Constraint: JOBZ='N' or 'V'.
2:   RANGE – CHARACTER(1)Input
On entry: if RANGE='A', all eigenvalues will be found.
If RANGE='V', all eigenvalues in the half-open interval VL,VU will be found.
If RANGE='I', the ILth to IUth eigenvalues will be found.
Constraint: RANGE='A', 'V' or 'I'.
3:   UPLO – CHARACTER(1)Input
On entry: if UPLO='U', the upper triangular part of A is stored.
If UPLO='L', the lower triangular part of A is stored.
Constraint: UPLO='U' or 'L'.
4:   N – INTEGERInput
On entry: n, the order of the matrix A.
Constraint: N≥0.
5:   A LDA* – COMPLEX (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array A must be at least max 1,N.
On entry: the n by n Hermitian matrix A.
  • If UPLO='U', the upper triangular part of A must be stored and the elements of the array below the diagonal are not referenced.
  • If UPLO='L', the lower triangular part of A must be stored and the elements of the array above the diagonal are not referenced.
On exit: the lower triangle (if UPLO='L') or the upper triangle (if UPLO='U') of A, including the diagonal, is overwritten.
6:   LDA – INTEGERInput
On entry: the first dimension of the array A as declared in the (sub)program from which F08FPF (ZHEEVX) is called.
Constraint: LDA≥max 1,N.
7:   VL – REAL (KIND=nag_wp)Input
8:   VU – REAL (KIND=nag_wp)Input
On entry: if RANGE='V', the lower and upper bounds of the interval to be searched for eigenvalues.
If RANGE='A' or 'I', VL and VU are not referenced.
Constraint: if RANGE='V', VL<VU.
9:   IL – INTEGERInput
10:   IU – INTEGERInput
On entry: if RANGE='I', the indices (in ascending order) of the smallest and largest eigenvalues to be returned.
If RANGE='A' or 'V', IL and IU are not referenced.
Constraints:
  • if RANGE='I' and N=0, IL=1 and IU=0;
  • if RANGE='I' and N>0, 1≤ IL≤ IU≤ N .
11:   ABSTOL – REAL (KIND=nag_wp)Input
On entry: the absolute error tolerance for the eigenvalues. An approximate eigenvalue is accepted as converged when it is determined to lie in an interval a,b of width less than or equal to
ABSTOL+ε max a,b ,
where ε is the machine precision. If ABSTOL is less than or equal to zero, then ε T 1 will be used in its place, where T is the tridiagonal matrix obtained by reducing A to tridiagonal form. Eigenvalues will be computed most accurately when ABSTOL is set to twice the underflow threshold 2 × X02AMF , not zero. If this routine returns with INFO>0, indicating that some eigenvectors did not converge, try setting ABSTOL to 2 × X02AMF . See Demmel and Kahan (1990).
12:   M – INTEGEROutput
On exit: the total number of eigenvalues found. 0≤M≤N.
If RANGE='A', M=N.
If RANGE='I', M=IU-IL+1.
13:   W* – REAL (KIND=nag_wp) arrayOutput
Note: the dimension of the array W must be at least max 1,N.
On exit: the first M elements contain the selected eigenvalues in ascending order.
14:   Z LDZ* – COMPLEX (KIND=nag_wp) arrayOutput
Note: the second dimension of the array Z must be at least max 1,M if JOBZ='V', and at least 1 otherwise.
On exit: if JOBZ='V', then
  • if INFO=0, the first M columns of Z contain the orthonormal eigenvectors of the matrix A corresponding to the selected eigenvalues, with the ith column of Z holding the eigenvector associated with W i;
  • if an eigenvector fails to converge (INFO>0), then that column of Z contains the latest approximation to the eigenvector, and the index of the eigenvector is returned in JFAIL.
If JOBZ='N', Z is not referenced.
Note: you must ensure that at least max 1,M columns are supplied in the array Z; if RANGE='V', the exact value of M is not known in advance and an upper bound of at least N must be used.
15:   LDZ – INTEGERInput
On entry: the first dimension of the array Z as declared in the (sub)program from which F08FPF (ZHEEVX) is called.
Constraints:
  • if JOBZ='V', LDZ≥ max 1,N ;
  • otherwise LDZ≥1.
16:   WORK max 1,LWORK – COMPLEX (KIND=nag_wp) arrayWorkspace
On exit: if INFO=0, the real part of WORK 1 contains the minimum value of LWORK required for optimal performance.
17:   LWORK – INTEGERInput
On entry: the dimension of the array WORK as declared in the (sub)program from which F08FPF (ZHEEVX) is called.
If LWORK=-1, a workspace query is assumed; the routine only calculates the optimal size of the WORK array, returns this value as the first entry of the WORK array, and no error message related to LWORK is issued.
Suggested value: for optimal performance, LWORK≥nb+1×N, where nb is the largest optimal block size for F08FSF (ZHETRD) and for F08FUF (ZUNMTR).
Constraint: LWORK≥max 1,2×N.
18:   RWORK* – REAL (KIND=nag_wp) arrayWorkspace
Note: the dimension of the array RWORK must be at least max 1,7×N.
19:   IWORK* – INTEGER arrayWorkspace
Note: the dimension of the array IWORK must be at least max 1,5×N.
20:   JFAIL* – INTEGER arrayOutput
Note: the dimension of the array JFAIL must be at least max 1,N.
On exit: if JOBZ='V', then
  • if INFO=0, the first M elements of JFAIL are zero;
  • if INFO>0, JFAIL contains the indices of the eigenvectors that failed to converge.
If JOBZ='N', JFAIL is not referenced.
21:   INFO – INTEGEROutput
On exit: INFO=0 unless the routine detects an error (see Section 6).

6 Error Indicators and Warnings

INFO<0
If INFO=-i, argument i had an illegal value. An explanatory message is output, and execution of the program is terminated.
INFO>0
The algorithm failed to converge; value eigenvectors did not converge. Their indices are stored in array JFAIL.

7 Accuracy

The computed eigenvalues and eigenvectors are exact for a nearby matrix A+E, where
E 2 = O ε A 2 ,
and ε is the machine precision. See Section 4.7 of Anderson et al. (1999) for further details.

8 Parallelism and Performance

F08FPF (ZHEEVX) is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
F08FPF (ZHEEVX) makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The total number of floating-point operations is proportional to n 3.
The real analogue of this routine is F08FBF (DSYEVX).

10 Example

This example finds the eigenvalues in the half-open interval -2,2 , and the corresponding eigenvectors, of the Hermitian matrix
A = 1 2-i 3-i 4-i 2+i 2 3-2 i 4-2 i 3+i 3+2 i 3 4-3 i 4+i 4+2 i 4+3 i 4 .

10.1 Program Text

Program Text (f08fpfe.f90)

10.2 Program Data

Program Data (f08fpfe.d)

10.3 Program Results

Program Results (f08fpfe.r)

F08 Chapter Contents
F08 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F08FQF (ZHEEVD) : NAG Library, Mark 26

F08 Chapter Contents
F08 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F08FQF (ZHEEVD)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.
Warning. The specification of the arguments LRWORK and LIWORK changed at Mark 20 in the case where JOB='V' and N>1: the minimum dimension of the array RWORK has been reduced whereas the minimum dimension of the array IWORK has been increased.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F08FQF (ZHEEVD) computes all the eigenvalues and, optionally, all the eigenvectors of a complex Hermitian matrix. If the eigenvectors are requested, then it uses a divide-and-conquer algorithm to compute eigenvalues and eigenvectors. However, if only eigenvalues are required, then it uses the Pal–Walker–Kahan variant of the QL or QR algorithm.

2 Specification

SUBROUTINE F08FQF ( JOB, UPLO, N, A, LDA, W, WORK, LWORK, RWORK, LRWORK, IWORK, LIWORK, INFO)
INTEGER | N, LDA, LWORK, LRWORK, IWORK(max(1,LIWORK)), LIWORK, INFO
REAL (KIND=nag_wp) | W(*), RWORK(max(1,LRWORK))
COMPLEX (KIND=nag_wp) | A(LDA,*), WORK(max(1,LWORK))
CHARACTER(1) | JOB, UPLO
The routine may be called by its LAPACK name zheevd.

3 Description

F08FQF (ZHEEVD) computes all the eigenvalues and, optionally, all the eigenvectors of a complex Hermitian matrix A. In other words, it can compute the spectral factorization of A as
A=ZΛ ZH,
where Λ is a real diagonal matrix whose diagonal elements are the eigenvalues λi, and Z is the (complex) unitary matrix whose columns are the eigenvectors zi. Thus
A zi=λizi,  i=1,2,…,n.

4 References

Anderson E, Bai Z, Bischof C, Blackford S, Demmel J, Dongarra J J, Du Croz J J, Greenbaum A, Hammarling S, McKenney A and Sorensen D (1999) LAPACK Users' Guide (3rd Edition) SIAM, Philadelphia http://www.netlib.org/lapack/lug
Golub G H and Van Loan C F (1996) Matrix Computations (3rd Edition) Johns Hopkins University Press, Baltimore

5 Arguments

1:   JOB – CHARACTER(1)Input
On entry: indicates whether eigenvectors are computed.
JOB='N'
Only eigenvalues are computed.
JOB='V'
Eigenvalues and eigenvectors are computed.
Constraint: JOB='N' or 'V'.
2:   UPLO – CHARACTER(1)Input
On entry: indicates whether the upper or lower triangular part of A is stored.
UPLO='U'
The upper triangular part of A is stored.
UPLO='L'
The lower triangular part of A is stored.
Constraint: UPLO='U' or 'L'.
3:   N – INTEGERInput
On entry: n, the order of the matrix A.
Constraint: N≥0.
4:   A LDA* – COMPLEX (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array A must be at least max 1,N.
On entry: the n by n Hermitian matrix A.
  • If UPLO='U', the upper triangular part of A must be stored and the elements of the array below the diagonal are not referenced.
  • If UPLO='L', the lower triangular part of A must be stored and the elements of the array above the diagonal are not referenced.
On exit: if JOB='V', A is overwritten by the unitary matrix Z which contains the eigenvectors of A.
5:   LDA – INTEGERInput
On entry: the first dimension of the array A as declared in the (sub)program from which F08FQF (ZHEEVD) is called.
Constraint: LDA≥max 1,N.
6:   W* – REAL (KIND=nag_wp) arrayOutput
Note: the dimension of the array W must be at least max 1,N.
On exit: the eigenvalues of the matrix A in ascending order.
7:   WORK max 1,LWORK – COMPLEX (KIND=nag_wp) arrayWorkspace
On exit: if INFO=0, the real part of WORK 1 contains the required minimal size of LWORK.
8:   LWORK – INTEGERInput
On entry: the dimension of the array WORK as declared in the (sub)program from which F08FQF (ZHEEVD) is called.
If LWORK=-1, a workspace query is assumed; the routine only calculates the minimum dimension of the WORK array, returns this value as the first entry of the WORK array, and no error message related to LWORK is issued.
Constraints:
  • if N≤1, LWORK≥1 or LWORK=-1;
  • if JOB='N' and N>1, LWORK≥N+1 or LWORK=-1;
  • if JOB='V' and N>1, LWORK≥N×N+2 or LWORK=-1.
9:   RWORK max 1,LRWORK – REAL (KIND=nag_wp) arrayWorkspace
On exit: if INFO=0, RWORK 1 contains the required minimal size of LRWORK.
10:   LRWORK – INTEGERInput
On entry: the dimension of the array RWORK as declared in the (sub)program from which F08FQF (ZHEEVD) is called.
If LRWORK=-1, a workspace query is assumed; the routine only calculates the minimum dimension of the RWORK array, returns this value as the first entry of the RWORK array, and no error message related to LRWORK is issued.
Constraints:
  • if N≤1, LRWORK≥1 or LRWORK=-1;
  • if JOB='N' and N>1, LRWORK≥N or LRWORK=-1;
  • if JOB='V' and N>1, LRWORK≥2×N 2+5×N+1 or LRWORK=-1.
11:   IWORK max 1,LIWORK – INTEGER arrayWorkspace
On exit: if INFO=0, IWORK 1 contains the required minimal size of LIWORK.
12:   LIWORK – INTEGERInput
On entry: the dimension of the array IWORK as declared in the (sub)program from which F08FQF (ZHEEVD) is called.
If LIWORK=-1, a workspace query is assumed; the routine only calculates the minimum dimension of the IWORK array, returns this value as the first entry of the IWORK array, and no error message related to LIWORK is issued.
Constraints:
  • if N≤1, LIWORK≥1 or LIWORK=-1;
  • if JOB='N' and N>1, LIWORK≥1 or LIWORK=-1;
  • if JOB='V' and N>1, LIWORK≥5×N+3 or LIWORK=-1.
13:   INFO – INTEGEROutput
On exit: INFO=0 unless the routine detects an error (see Section 6).

6 Error Indicators and Warnings

INFO<0
If INFO=-i, argument i had an illegal value. An explanatory message is output, and execution of the program is terminated.
INFO>0
if INFO=i and JOB='N', the algorithm failed to converge; i elements of an intermediate tridiagonal form did not converge to zero; if INFO=i and JOB='V', then the algorithm failed to compute an eigenvalue while working on the submatrix lying in rows and column i/N+1 through i mod N+1.

7 Accuracy

The computed eigenvalues and eigenvectors are exact for a nearby matrix A+E, where
E 2 = O ε A 2 ,
and ε is the machine precision. See Section 4.7 of Anderson et al. (1999) for further details.

8 Parallelism and Performance

F08FQF (ZHEEVD) is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
F08FQF (ZHEEVD) makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The real analogue of this routine is F08FCF (DSYEVD).

10 Example

This example computes all the eigenvalues and eigenvectors of the Hermitian matrix A, where
A = 1.0+0.0 i 2.0-1.0 i 3.0-1.0 i 4.0-1.0 i 2.0+1.0 i 2.0+0.0 i 3.0-2.0 i 4.0-2.0 i 3.0+1.0 i 3.0+2.0 i 3.0+0.0 i 4.0-3.0 i 4.0+1.0 i 4.0+2.0 i 4.0+3.0 i 4.0+0.0 i .
The example program for F08FQF (ZHEEVD) illustrates the computation of error bounds for the eigenvalues and eigenvectors.

10.1 Program Text

Program Text (f08fqfe.f90)

10.2 Program Data

Program Data (f08fqfe.d)

10.3 Program Results

Program Results (f08fqfe.r)

F08 Chapter Contents
F08 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F08FRF (ZHEEVR) : NAG Library, Mark 26

F08 Chapter Contents
F08 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F08FRF (ZHEEVR)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F08FRF (ZHEEVR) computes selected eigenvalues and, optionally, eigenvectors of a complex n by n Hermitian matrix A. Eigenvalues and eigenvectors can be selected by specifying either a range of values or a range of indices for the desired eigenvalues.

2 Specification

SUBROUTINE F08FRF ( JOBZ, RANGE, UPLO, N, A, LDA, VL, VU, IL, IU, ABSTOL, M, W, Z, LDZ, ISUPPZ, WORK, LWORK, RWORK, LRWORK, IWORK, LIWORK, INFO)
INTEGER | N, LDA, IL, IU, M, LDZ, ISUPPZ(*), LWORK, LRWORK, IWORK(max(1,LIWORK)), LIWORK, INFO
REAL (KIND=nag_wp) | VL, VU, ABSTOL, W(*), RWORK(max(1,LRWORK))
COMPLEX (KIND=nag_wp) | A(LDA,*), Z(LDZ,*), WORK(max(1,LWORK))
CHARACTER(1) | JOBZ, RANGE, UPLO
The routine may be called by its LAPACK name zheevr.

3 Description

The Hermitian matrix is first reduced to a real tridiagonal matrix T, using unitary similarity transformations. Then whenever possible, F08FRF (ZHEEVR) computes the eigenspectrum using Relatively Robust Representations. F08FRF (ZHEEVR) computes eigenvalues by the dqds algorithm, while orthogonal eigenvectors are computed from various ‘good’ LD LT representations (also known as Relatively Robust Representations). Gram–Schmidt orthogonalization is avoided as far as possible. More specifically, the various steps of the algorithm are as follows. For the ith unreduced block of T:
(a) | compute T - σi I = Li Di LiT , such that Li Di LiT is a relatively robust representation,
(b) | compute the eigenvalues, λj, of Li Di LiT to high relative accuracy by the dqds algorithm,
(c) | if there is a cluster of close eigenvalues, ‘choose’ σi close to the cluster, and go to (a),
(d) | given the approximate eigenvalue λj of Li Di LiT , compute the corresponding eigenvector by forming a rank-revealing twisted factorization.
The desired accuracy of the output can be specified by the argument ABSTOL. For more details, see Dhillon (1997) and Parlett and Dhillon (2000).

4 References

Anderson E, Bai Z, Bischof C, Blackford S, Demmel J, Dongarra J J, Du Croz J J, Greenbaum A, Hammarling S, McKenney A and Sorensen D (1999) LAPACK Users' Guide (3rd Edition) SIAM, Philadelphia http://www.netlib.org/lapack/lug
Barlow J and Demmel J W (1990) Computing accurate eigensystems of scaled diagonally dominant matrices SIAM J. Numer. Anal. 27 762–791
Demmel J W and Kahan W (1990) Accurate singular values of bidiagonal matrices SIAM J. Sci. Statist. Comput. 11 873–912
Dhillon I (1997) A new O n 2 algorithm for the symmetric tridiagonal eigenvalue/eigenvector problem Computer Science Division Technical Report No. UCB//CSD-97-971 UC Berkeley
Golub G H and Van Loan C F (1996) Matrix Computations (3rd Edition) Johns Hopkins University Press, Baltimore
Parlett B N and Dhillon I S (2000) Relatively robust representations of symmetric tridiagonals Linear Algebra Appl. 309 121–151

5 Arguments

1:   JOBZ – CHARACTER(1)Input
On entry: indicates whether eigenvectors are computed.
JOBZ='N'
Only eigenvalues are computed.
JOBZ='V'
Eigenvalues and eigenvectors are computed.
Constraint: JOBZ='N' or 'V'.
2:   RANGE – CHARACTER(1)Input
On entry: if RANGE='A', all eigenvalues will be found.
If RANGE='V', all eigenvalues in the half-open interval VL,VU will be found.
If RANGE='I', the ILth to IUth eigenvalues will be found.
For RANGE='V' or 'I' and IU-IL<N-1, F08JJF (DSTEBZ) and F08JXF (ZSTEIN) are called.
Constraint: RANGE='A', 'V' or 'I'.
3:   UPLO – CHARACTER(1)Input
On entry: if UPLO='U', the upper triangular part of A is stored.
If UPLO='L', the lower triangular part of A is stored.
Constraint: UPLO='U' or 'L'.
4:   N – INTEGERInput
On entry: n, the order of the matrix A.
Constraint: N≥0.
5:   A LDA* – COMPLEX (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array A must be at least max 1,N.
On entry: the n by n Hermitian matrix A.
  • If UPLO='U', the upper triangular part of A must be stored and the elements of the array below the diagonal are not referenced.
  • If UPLO='L', the lower triangular part of A must be stored and the elements of the array above the diagonal are not referenced.
On exit: the lower triangle (if UPLO='L') or the upper triangle (if UPLO='U') of A, including the diagonal, is overwritten.
6:   LDA – INTEGERInput
On entry: the first dimension of the array A as declared in the (sub)program from which F08FRF (ZHEEVR) is called.
Constraint: LDA≥max 1,N.
7:   VL – REAL (KIND=nag_wp)Input
8:   VU – REAL (KIND=nag_wp)Input
On entry: if RANGE='V', the lower and upper bounds of the interval to be searched for eigenvalues.
If RANGE='A' or 'I', VL and VU are not referenced.
Constraint: if RANGE='V', VL<VU.
9:   IL – INTEGERInput
10:   IU – INTEGERInput
On entry: if RANGE='I', the indices (in ascending order) of the smallest and largest eigenvalues to be returned.
If RANGE='A' or 'V', IL and IU are not referenced.
Constraints:
  • if RANGE='I' and N=0, IL=1 and IU=0;
  • if RANGE='I' and N>0, 1≤ IL≤ IU≤ N .
11:   ABSTOL – REAL (KIND=nag_wp)Input
On entry: the absolute error tolerance for the eigenvalues. An approximate eigenvalue is accepted as converged when it is determined to lie in an interval a,b of width less than or equal to
ABSTOL+ε max a,b ,
where ε is the machine precision. If ABSTOL is less than or equal to zero, then ε T 1 will be used in its place, where T is the real tridiagonal matrix obtained by reducing A to tridiagonal form. See Demmel and Kahan (1990).
If high relative accuracy is important, set ABSTOL to X02AMF , although doing so does not currently guarantee that eigenvalues are computed to high relative accuracy. See Barlow and Demmel (1990) for a discussion of which matrices can define their eigenvalues to high relative accuracy.
12:   M – INTEGEROutput
On exit: the total number of eigenvalues found. 0≤M≤N.
If RANGE='A', M=N.
If RANGE='I', M=IU-IL+1.
13:   W* – REAL (KIND=nag_wp) arrayOutput
Note: the dimension of the array W must be at least max 1,N.
On exit: the first M elements contain the selected eigenvalues in ascending order.
14:   Z LDZ* – COMPLEX (KIND=nag_wp) arrayOutput
Note: the second dimension of the array Z must be at least max 1,M if JOBZ='V', and at least 1 otherwise.
On exit: if JOBZ='V', the first M columns of Z contain the orthonormal eigenvectors of the matrix A corresponding to the selected eigenvalues, with the ith column of Z holding the eigenvector associated with W i.
If JOBZ='N', Z is not referenced.
Note: you must ensure that at least max 1,M columns are supplied in the array Z; if RANGE='V', the exact value of M is not known in advance and an upper bound of at least N must be used.
15:   LDZ – INTEGERInput
On entry: the first dimension of the array Z as declared in the (sub)program from which F08FRF (ZHEEVR) is called.
Constraints:
  • if JOBZ='V', LDZ≥ max 1,N ;
  • otherwise LDZ≥1.
16:   ISUPPZ* – INTEGER arrayOutput
Note: the dimension of the array ISUPPZ must be at least max 1,2×M.
On exit: the support of the eigenvectors in Z, i.e., the indices indicating the nonzero elements in Z. The ith eigenvector is nonzero only in elements ISUPPZ 2×i-1 through ISUPPZ 2×i. Implemented only for RANGE='A' or 'I' and IU-IL=N-1.
17:   WORK max 1,LWORK – COMPLEX (KIND=nag_wp) arrayWorkspace
On exit: if INFO=0, the real part of WORK 1 contains the minimum value of LWORK required for optimal performance.
18:   LWORK – INTEGERInput
On entry: the dimension of the array WORK as declared in the (sub)program from which F08FRF (ZHEEVR) is called.
If LWORK=-1, a workspace query is assumed; the routine only calculates the optimal sizes of the WORK, RWORK and IWORK arrays, returns these values as the first entries of the WORK, RWORK and IWORK arrays, and no error message related to LWORK, LRWORK or LIWORK is issued.
Suggested value: for optimal performance, LWORK≥nb+1×N, where nb is the largest optimal block size for F08FSF (ZHETRD) and for F08FUF (ZUNMTR).
Constraint: LWORK≥max 1,2×N.
19:   RWORK max 1,LRWORK – REAL (KIND=nag_wp) arrayWorkspace
On exit: if INFO=0, RWORK 1 returns the optimal (and minimal) LRWORK.
20:   LRWORK – INTEGERInput
On entry: the dimension of the array RWORK as declared in the (sub)program from which F08FRF (ZHEEVR) is called.
If LRWORK=-1, a workspace query is assumed; the routine only calculates the optimal sizes of the WORK, RWORK and IWORK arrays, returns these values as the first entries of the WORK, RWORK and IWORK arrays, and no error message related to LWORK, LRWORK or LIWORK is issued.
Constraint: LRWORK≥max 1,24×N.
21:   IWORK max 1,LIWORK – INTEGER arrayWorkspace
On exit: if INFO=0, IWORK 1 returns the optimal (and minimal) LIWORK.
22:   LIWORK – INTEGERInput
On entry: the dimension of the array IWORK as declared in the (sub)program from which F08FRF (ZHEEVR) is called.
If LIWORK=-1, a workspace query is assumed; the routine only calculates the optimal sizes of the WORK, RWORK and IWORK arrays, returns these values as the first entries of the WORK, RWORK and IWORK arrays, and no error message related to LWORK, LRWORK or LIWORK is issued.
Constraint: LIWORK≥ max 1,10×N .
23:   INFO – INTEGEROutput
On exit: INFO=0 unless the routine detects an error (see Section 6).

6 Error Indicators and Warnings

INFO<0
If INFO=-i, argument i had an illegal value. An explanatory message is output, and execution of the program is terminated.
INFO>0
F08FRF (ZHEEVR) failed to converge.

7 Accuracy

The computed eigenvalues and eigenvectors are exact for a nearby matrix A+E, where
E 2 = O ε A 2 ,
and ε is the machine precision. See Section 4.7 of Anderson et al. (1999) for further details.

8 Parallelism and Performance

F08FRF (ZHEEVR) is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
F08FRF (ZHEEVR) makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The total number of floating-point operations is proportional to n 3.
The real analogue of this routine is F08FDF (DSYEVR).

10 Example

This example finds the eigenvalues with indices in the range 2,3 , and the corresponding eigenvectors, of the Hermitian matrix
A = 1 2-i 3-i 4-i 2+i 2 3-2 i 4-2 i 3+i 3+2 i 3 4-3 i 4+i 4+2 i 4+3 i 4 .
Information on required and provided workspace is also output.

10.1 Program Text

Program Text (f08frfe.f90)

10.2 Program Data

Program Data (f08frfe.d)

10.3 Program Results

Program Results (f08frfe.r)

F08 Chapter Contents
F08 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F08FSF (ZHETRD) : NAG Library, Mark 26

F08 Chapter Contents
F08 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F08FSF (ZHETRD)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F08FSF (ZHETRD) reduces a complex Hermitian matrix to tridiagonal form.

2 Specification

SUBROUTINE F08FSF ( UPLO, N, A, LDA, D, E, TAU, WORK, LWORK, INFO)
INTEGER | N, LDA, LWORK, INFO
REAL (KIND=nag_wp) | D(*), E(*)
COMPLEX (KIND=nag_wp) | A(LDA,*), TAU(*), WORK(max(1,LWORK))
CHARACTER(1) | UPLO
The routine may be called by its LAPACK name zhetrd.

3 Description

F08FSF (ZHETRD) reduces a complex Hermitian matrix A to real symmetric tridiagonal form T by a unitary similarity transformation: A=QT QH.
The matrix Q is not formed explicitly but is represented as a product of n-1 elementary reflectors (see the F08 Chapter Introduction for details). Routines are provided to work with Q in this representation (see Section 9).

4 References

Golub G H and Van Loan C F (1996) Matrix Computations (3rd Edition) Johns Hopkins University Press, Baltimore

5 Arguments

1:   UPLO – CHARACTER(1)Input
On entry: indicates whether the upper or lower triangular part of A is stored.
UPLO='U'
The upper triangular part of A is stored.
UPLO='L'
The lower triangular part of A is stored.
Constraint: UPLO='U' or 'L'.
2:   N – INTEGERInput
On entry: n, the order of the matrix A.
Constraint: N≥0.
3:   A LDA* – COMPLEX (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array A must be at least max 1,N.
On entry: the n by n Hermitian matrix A.
  • If UPLO='U', the upper triangular part of A must be stored and the elements of the array below the diagonal are not referenced.
  • If UPLO='L', the lower triangular part of A must be stored and the elements of the array above the diagonal are not referenced.
On exit: A is overwritten by the tridiagonal matrix T and details of the unitary matrix Q as specified by UPLO.
4:   LDA – INTEGERInput
On entry: the first dimension of the array A as declared in the (sub)program from which F08FSF (ZHETRD) is called.
Constraint: LDA≥max 1,N.
5:   D* – REAL (KIND=nag_wp) arrayOutput
Note: the dimension of the array D must be at least max 1,N.
On exit: the diagonal elements of the tridiagonal matrix T.
6:   E* – REAL (KIND=nag_wp) arrayOutput
Note: the dimension of the array E must be at least max 1,N-1.
On exit: the off-diagonal elements of the tridiagonal matrix T.
7:   TAU* – COMPLEX (KIND=nag_wp) arrayOutput
Note: the dimension of the array TAU must be at least max 1,N-1.
On exit: further details of the unitary matrix Q.
8:   WORK max 1,LWORK – COMPLEX (KIND=nag_wp) arrayWorkspace
On exit: if INFO=0, the real part of WORK 1 contains the minimum value of LWORK required for optimal performance.
9:   LWORK – INTEGERInput
On entry: the dimension of the array WORK as declared in the (sub)program from which F08FSF (ZHETRD) is called.
If LWORK=-1, a workspace query is assumed; the routine only calculates the optimal size of the WORK array, returns this value as the first entry of the WORK array, and no error message related to LWORK is issued.
Suggested value: for optimal performance, LWORK≥N×nb, where nb is the optimal block size.
Constraint: LWORK≥1 or LWORK=-1.
10:   INFO – INTEGEROutput
On exit: INFO=0 unless the routine detects an error (see Section 6).

6 Error Indicators and Warnings

INFO<0
If INFO=-i, argument i had an illegal value. An explanatory message is output, and execution of the program is terminated.

7 Accuracy

The computed tridiagonal matrix T is exactly similar to a nearby matrix A+E, where
E 2≤ c n ε A 2 ,
c n is a modestly increasing function of n, and ε is the machine precision.
The elements of T themselves may be sensitive to small perturbations in A or to rounding errors in the computation, but this does not affect the stability of the eigenvalues and eigenvectors.

8 Parallelism and Performance

F08FSF (ZHETRD) is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
F08FSF (ZHETRD) makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The total number of real floating-point operations is approximately 163 n 3 .
To form the unitary matrix Q F08FSF (ZHETRD) may be followed by a call to F08FTF (ZUNGTR):
CALL ZUNGTR(UPLO,N,A,LDA,TAU,WORK,LWORK,INFO)
To apply Q to an n by p complex matrix C F08FSF (ZHETRD) may be followed by a call to F08FUF (ZUNMTR). For example,
CALL ZUNMTR('Left',UPLO,'No Transpose',N,P,A,LDA,TAU,C,LDC, &
              WORK,LWORK,INFO)
forms the matrix product QC.
The real analogue of this routine is F08FEF (DSYTRD).

10 Example

This example reduces the matrix A to tridiagonal form, where
A = -2.28+0.00 i 1.78-2.03 i 2.26+0.10 i -0.12+2.53 i 1.78+2.03 i -1.12+0.00 i 0.01+0.43 i -1.07+0.86 i 2.26-0.10 i 0.01-0.43 i -0.37+0.00 i 2.31-0.92 i -0.12-2.53 i -1.07-0.86 i 2.31+0.92 i -0.73+0.00 i .

10.1 Program Text

Program Text (f08fsfe.f90)

10.2 Program Data

Program Data (f08fsfe.d)

10.3 Program Results

Program Results (f08fsfe.r)

F08 Chapter Contents
F08 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F08FTF (ZUNGTR) : NAG Library, Mark 26

F08 Chapter Contents
F08 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F08FTF (ZUNGTR)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F08FTF (ZUNGTR) generates the complex unitary matrix Q, which was determined by F08FSF (ZHETRD) when reducing a Hermitian matrix to tridiagonal form.

2 Specification

SUBROUTINE F08FTF ( UPLO, N, A, LDA, TAU, WORK, LWORK, INFO)
INTEGER | N, LDA, LWORK, INFO
COMPLEX (KIND=nag_wp) | A(LDA,*), TAU(*), WORK(max(1,LWORK))
CHARACTER(1) | UPLO
The routine may be called by its LAPACK name zungtr.

3 Description

F08FTF (ZUNGTR) is intended to be used after a call to F08FSF (ZHETRD), which reduces a complex Hermitian matrix A to real symmetric tridiagonal form T by a unitary similarity transformation: A=QT QH. F08FSF (ZHETRD) represents the unitary matrix Q as a product of n-1 elementary reflectors.
This routine may be used to generate Q explicitly as a square matrix.

4 References

Golub G H and Van Loan C F (1996) Matrix Computations (3rd Edition) Johns Hopkins University Press, Baltimore

5 Arguments

1:   UPLO – CHARACTER(1)Input
On entry: this must be the same argument UPLO as supplied to F08FSF (ZHETRD).
Constraint: UPLO='U' or 'L'.
2:   N – INTEGERInput
On entry: n, the order of the matrix Q.
Constraint: N≥0.
3:   A LDA* – COMPLEX (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array A must be at least max 1,N.
On entry: details of the vectors which define the elementary reflectors, as returned by F08FSF (ZHETRD).
On exit: the n by n unitary matrix Q.
4:   LDA – INTEGERInput
On entry: the first dimension of the array A as declared in the (sub)program from which F08FTF (ZUNGTR) is called.
Constraint: LDA≥max 1,N.
5:   TAU* – COMPLEX (KIND=nag_wp) arrayInput
Note: the dimension of the array TAU must be at least max 1,N-1.
On entry: further details of the elementary reflectors, as returned by F08FSF (ZHETRD).
6:   WORK max 1,LWORK – COMPLEX (KIND=nag_wp) arrayWorkspace
On exit: if INFO=0, the real part of WORK 1 contains the minimum value of LWORK required for optimal performance.
7:   LWORK – INTEGERInput
On entry: the dimension of the array WORK as declared in the (sub)program from which F08FTF (ZUNGTR) is called.
If LWORK=-1, a workspace query is assumed; the routine only calculates the optimal size of the WORK array, returns this value as the first entry of the WORK array, and no error message related to LWORK is issued.
Suggested value: for optimal performance, LWORK≥N-1×nb, where nb is the optimal block size.
Constraint: LWORK≥max 1,N-1 or LWORK=-1.
8:   INFO – INTEGEROutput
On exit: INFO=0 unless the routine detects an error (see Section 6).

6 Error Indicators and Warnings

INFO<0
If INFO=-i, argument i had an illegal value. An explanatory message is output, and execution of the program is terminated.

7 Accuracy

The computed matrix Q differs from an exactly unitary matrix by a matrix E such that
E 2 = O ε ,
where ε is the machine precision.

8 Parallelism and Performance

F08FTF (ZUNGTR) is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
F08FTF (ZUNGTR) makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The total number of real floating-point operations is approximately 163 n 3.
The real analogue of this routine is F08FFF (DORGTR).

10 Example

This example computes all the eigenvalues and eigenvectors of the matrix A, where
A = -2.28+0.00 i 1.78-2.03 i 2.26+0.10 i -0.12+2.53 i 1.78+2.03 i -1.12+0.00 i 0.01+0.43 i -1.07+0.86 i 2.26-0.10 i 0.01-0.43 i -0.37+0.00 i 2.31-0.92 i -0.12-2.53 i -1.07-0.86 i 2.31+0.92 i -0.73+0.00 i .
Here A is Hermitian and must first be reduced to tridiagonal form by F08FSF (ZHETRD). The program then calls F08FTF (ZUNGTR) to form Q, and passes this matrix to F08JSF (ZSTEQR) which computes the eigenvalues and eigenvectors of A.

10.1 Program Text

Program Text (f08ftfe.f90)

10.2 Program Data

Program Data (f08ftfe.d)

10.3 Program Results

Program Results (f08ftfe.r)

F08 Chapter Contents
F08 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F08FUF (ZUNMTR) : NAG Library, Mark 26

F08 Chapter Contents
F08 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F08FUF (ZUNMTR)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F08FUF (ZUNMTR) multiplies an arbitrary complex matrix C by the complex unitary matrix Q which was determined by F08FSF (ZHETRD) when reducing a complex Hermitian matrix to tridiagonal form.

2 Specification

SUBROUTINE F08FUF ( SIDE, UPLO, TRANS, M, N, A, LDA, TAU, C, LDC, WORK, LWORK, INFO)
INTEGER | M, N, LDA, LDC, LWORK, INFO
COMPLEX (KIND=nag_wp) | A(LDA,*), TAU(*), C(LDC,*), WORK(max(1,LWORK))
CHARACTER(1) | SIDE, UPLO, TRANS
The routine may be called by its LAPACK name zunmtr.

3 Description

F08FUF (ZUNMTR) is intended to be used after a call to F08FSF (ZHETRD), which reduces a complex Hermitian matrix A to real symmetric tridiagonal form T by a unitary similarity transformation: A=QT QH. F08FSF (ZHETRD) represents the unitary matrix Q as a product of elementary reflectors.
This routine may be used to form one of the matrix products
QC , QH C , CQ ​ or ​ C QH ,
overwriting the result on C (which may be any complex rectangular matrix).
A common application of this routine is to transform a matrix Z of eigenvectors of T to the matrix QZ of eigenvectors of A.

4 References

Golub G H and Van Loan C F (1996) Matrix Computations (3rd Edition) Johns Hopkins University Press, Baltimore

5 Arguments

1:   SIDE – CHARACTER(1)Input
On entry: indicates how Q or QH is to be applied to C.
SIDE='L'
Q or QH is applied to C from the left.
SIDE='R'
Q or QH is applied to C from the right.
Constraint: SIDE='L' or 'R'.
2:   UPLO – CHARACTER(1)Input
On entry: this must be the same argument UPLO as supplied to F08FSF (ZHETRD).
Constraint: UPLO='U' or 'L'.
3:   TRANS – CHARACTER(1)Input
On entry: indicates whether Q or QH is to be applied to C.
TRANS='N'
Q is applied to C.
TRANS='C'
QH is applied to C.
Constraint: TRANS='N' or 'C'.
4:   M – INTEGERInput
On entry: m, the number of rows of the matrix C; m is also the order of Q if SIDE='L'.
Constraint: M≥0.
5:   N – INTEGERInput
On entry: n, the number of columns of the matrix C; n is also the order of Q if SIDE='R'.
Constraint: N≥0.
6:   A LDA* – COMPLEX (KIND=nag_wp) arrayInput
Note: the second dimension of the array A must be at least max 1,M if SIDE='L' and at least max 1,N if SIDE='R'.
On entry: details of the vectors which define the elementary reflectors, as returned by F08FSF (ZHETRD).
7:   LDA – INTEGERInput
On entry: the first dimension of the array A as declared in the (sub)program from which F08FUF (ZUNMTR) is called.
Constraints:
  • if SIDE='L', LDA≥ max 1,M ;
  • if SIDE='R', LDA≥ max 1,N .
8:   TAU* – COMPLEX (KIND=nag_wp) arrayInput
Note: the dimension of the array TAU must be at least max 1,M-1 if SIDE='L' and at least max 1,N-1 if SIDE='R'.
On entry: further details of the elementary reflectors, as returned by F08FSF (ZHETRD).
9:   C LDC* – COMPLEX (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array C must be at least max 1,N.
On entry: the m by n matrix C.
On exit: C is overwritten by QC or QH C or CQ or C QH as specified by SIDE and TRANS.
10:   LDC – INTEGERInput
On entry: the first dimension of the array C as declared in the (sub)program from which F08FUF (ZUNMTR) is called.
Constraint: LDC≥max 1,M.
11:   WORK max 1,LWORK – COMPLEX (KIND=nag_wp) arrayWorkspace
On exit: if INFO=0, the real part of WORK 1 contains the minimum value of LWORK required for optimal performance.
12:   LWORK – INTEGERInput
On entry: the dimension of the array WORK as declared in the (sub)program from which F08FUF (ZUNMTR) is called.
If LWORK=-1, a workspace query is assumed; the routine only calculates the optimal size of the WORK array, returns this value as the first entry of the WORK array, and no error message related to LWORK is issued.
Suggested value: for optimal performance, LWORK≥N×nb if SIDE='L' and at least M×nb if SIDE='R', where nb is the optimal block size.
Constraints:
  • if SIDE='L', LWORK≥max 1,N or LWORK=-1;
  • if SIDE='R', LWORK≥max 1,M or LWORK=-1.
13:   INFO – INTEGEROutput
On exit: INFO=0 unless the routine detects an error (see Section 6).

6 Error Indicators and Warnings

INFO<0
If INFO=-i, argument i had an illegal value. An explanatory message is output, and execution of the program is terminated.

7 Accuracy

The computed result differs from the exact result by a matrix E such that
E 2 = O ε C 2 ,
where ε is the machine precision.

8 Parallelism and Performance

F08FUF (ZUNMTR) is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
F08FUF (ZUNMTR) makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The total number of real floating-point operations is approximately 8 m 2 n if SIDE='L' and 8 m n 2 if SIDE='R'.
The real analogue of this routine is F08FGF (DORMTR).

10 Example

This example computes the two smallest eigenvalues, and the associated eigenvectors, of the matrix A, where
A = -2.28+0.00 i 1.78-2.03 i 2.26+0.10 i -0.12+2.53 i 1.78+2.03 i -1.12+0.00 i 0.01+0.43 i -1.07+0.86 i 2.26-0.10 i 0.01-0.43 i -0.37+0.00 i 2.31-0.92 i -0.12-2.53 i -1.07-0.86 i 2.31+0.92 i -0.73+0.00 i .
Here A is Hermitian and must first be reduced to tridiagonal form T by F08FSF (ZHETRD). The program then calls F08JJF (DSTEBZ) to compute the requested eigenvalues and F08JXF (ZSTEIN) to compute the associated eigenvectors of T. Finally F08FUF (ZUNMTR) is called to transform the eigenvectors to those of A.

10.1 Program Text

Program Text (f08fufe.f90)

10.2 Program Data

Program Data (f08fufe.d)

10.3 Program Results

Program Results (f08fufe.r)

F08 Chapter Contents
F08 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F08GAF (DSPEV) : NAG Library, Mark 26

F08 Chapter Contents
F08 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F08GAF (DSPEV)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F08GAF (DSPEV) computes all the eigenvalues and, optionally, all the eigenvectors of a real n by n symmetric matrix A in packed storage.

2 Specification

SUBROUTINE F08GAF ( JOBZ, UPLO, N, AP, W, Z, LDZ, WORK, INFO)
INTEGER | N, LDZ, INFO
REAL (KIND=nag_wp) | AP(*), W(N), Z(LDZ,*), WORK(3*N)
CHARACTER(1) | JOBZ, UPLO
The routine may be called by its LAPACK name dspev.

3 Description

The symmetric matrix A is first reduced to tridiagonal form, using orthogonal similarity transformations, and then the QR algorithm is applied to the tridiagonal matrix to compute the eigenvalues and (optionally) the eigenvectors.

4 References

Anderson E, Bai Z, Bischof C, Blackford S, Demmel J, Dongarra J J, Du Croz J J, Greenbaum A, Hammarling S, McKenney A and Sorensen D (1999) LAPACK Users' Guide (3rd Edition) SIAM, Philadelphia http://www.netlib.org/lapack/lug
Golub G H and Van Loan C F (1996) Matrix Computations (3rd Edition) Johns Hopkins University Press, Baltimore

5 Arguments

1:   JOBZ – CHARACTER(1)Input
On entry: indicates whether eigenvectors are computed.
JOBZ='N'
Only eigenvalues are computed.
JOBZ='V'
Eigenvalues and eigenvectors are computed.
Constraint: JOBZ='N' or 'V'.
2:   UPLO – CHARACTER(1)Input
On entry: if UPLO='U', the upper triangular part of A is stored.
If UPLO='L', the lower triangular part of A is stored.
Constraint: UPLO='U' or 'L'.
3:   N – INTEGERInput
On entry: n, the order of the matrix A.
Constraint: N≥0.
4:   AP* – REAL (KIND=nag_wp) arrayInput/Output
Note: the dimension of the array AP must be at least max 1,N×N+1/2.
On entry: the upper or lower triangle of the n by n symmetric matrix A, packed by columns.
More precisely,
  • if UPLO='U', the upper triangle of A must be stored with element A ij in AP i+j j-1/2 for i≤j;
  • if UPLO='L', the lower triangle of A must be stored with element A ij in AP i+2 n-jj-1/2 for i≥j.
On exit: AP is overwritten by the values generated during the reduction to tridiagonal form. The elements of the diagonal and the off-diagonal of the tridiagonal matrix overwrite the corresponding elements of A.
5:   W N – REAL (KIND=nag_wp) arrayOutput
On exit: the eigenvalues in ascending order.
6:   Z LDZ* – REAL (KIND=nag_wp) arrayOutput
Note: the second dimension of the array Z must be at least max 1,N if JOBZ='V', and at least 1 otherwise.
On exit: if JOBZ='V', Z contains the orthonormal eigenvectors of the matrix A, with the ith column of Z holding the eigenvector associated with W i.
If JOBZ='N', Z is not referenced.
7:   LDZ – INTEGERInput
On entry: the first dimension of the array Z as declared in the (sub)program from which F08GAF (DSPEV) is called.
Constraints:
  • if JOBZ='V', LDZ≥ max 1,N ;
  • otherwise LDZ≥1.
8:   WORK 3×N – REAL (KIND=nag_wp) arrayWorkspace
9:   INFO – INTEGEROutput
On exit: INFO=0 unless the routine detects an error (see Section 6).

6 Error Indicators and Warnings

INFO<0
If INFO=-i, argument i had an illegal value. An explanatory message is output, and execution of the program is terminated.
INFO>0
If INFO=i, the algorithm failed to converge; i off-diagonal elements of an intermediate tridiagonal form did not converge to zero.

7 Accuracy

The computed eigenvalues and eigenvectors are exact for a nearby matrix A+E, where
E 2 = O ε A 2 ,
and ε is the machine precision. See Section 4.7 of Anderson et al. (1999) for further details.

8 Parallelism and Performance

F08GAF (DSPEV) is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
F08GAF (DSPEV) makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The total number of floating-point operations is proportional to n 3.
The complex analogue of this routine is F08GNF (ZHPEV).

10 Example

This example finds all the eigenvalues of the symmetric matrix
A = 1 2 3 4 2 2 3 4 3 3 3 4 4 4 4 4 ,
together with approximate error bounds for the computed eigenvalues.

10.1 Program Text

Program Text (f08gafe.f90)

10.2 Program Data

Program Data (f08gafe.d)

10.3 Program Results

Program Results (f08gafe.r)

F08 Chapter Contents
F08 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F08GBF (DSPEVX) : NAG Library, Mark 26

F08 Chapter Contents
F08 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F08GBF (DSPEVX)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F08GBF (DSPEVX) computes selected eigenvalues and, optionally, eigenvectors of a real n by n symmetric matrix A in packed storage. Eigenvalues and eigenvectors can be selected by specifying either a range of values or a range of indices for the desired eigenvalues.

2 Specification

SUBROUTINE F08GBF ( JOBZ, RANGE, UPLO, N, AP, VL, VU, IL, IU, ABSTOL, M, W, Z, LDZ, WORK, IWORK, JFAIL, INFO)
INTEGER | N, IL, IU, M, LDZ, IWORK(5*N), JFAIL(*), INFO
REAL (KIND=nag_wp) | AP(*), VL, VU, ABSTOL, W(N), Z(LDZ,*), WORK(8*N)
CHARACTER(1) | JOBZ, RANGE, UPLO
The routine may be called by its LAPACK name dspevx.

3 Description

The symmetric matrix A is first reduced to tridiagonal form, using orthogonal similarity transformations. The required eigenvalues and eigenvectors are then computed from the tridiagonal matrix; the method used depends upon whether all, or selected, eigenvalues and eigenvectors are required.

4 References

Anderson E, Bai Z, Bischof C, Blackford S, Demmel J, Dongarra J J, Du Croz J J, Greenbaum A, Hammarling S, McKenney A and Sorensen D (1999) LAPACK Users' Guide (3rd Edition) SIAM, Philadelphia http://www.netlib.org/lapack/lug
Demmel J W and Kahan W (1990) Accurate singular values of bidiagonal matrices SIAM J. Sci. Statist. Comput. 11 873–912
Golub G H and Van Loan C F (1996) Matrix Computations (3rd Edition) Johns Hopkins University Press, Baltimore

5 Arguments

1:   JOBZ – CHARACTER(1)Input
On entry: indicates whether eigenvectors are computed.
JOBZ='N'
Only eigenvalues are computed.
JOBZ='V'
Eigenvalues and eigenvectors are computed.
Constraint: JOBZ='N' or 'V'.
2:   RANGE – CHARACTER(1)Input
On entry: if RANGE='A', all eigenvalues will be found.
If RANGE='V', all eigenvalues in the half-open interval VL,VU will be found.
If RANGE='I', the ILth to IUth eigenvalues will be found.
Constraint: RANGE='A', 'V' or 'I'.
3:   UPLO – CHARACTER(1)Input
On entry: if UPLO='U', the upper triangular part of A is stored.
If UPLO='L', the lower triangular part of A is stored.
Constraint: UPLO='U' or 'L'.
4:   N – INTEGERInput
On entry: n, the order of the matrix A.
Constraint: N≥0.
5:   AP* – REAL (KIND=nag_wp) arrayInput/Output
Note: the dimension of the array AP must be at least max 1,N×N+1/2.
On entry: the upper or lower triangle of the n by n symmetric matrix A, packed by columns.
More precisely,
  • if UPLO='U', the upper triangle of A must be stored with element A ij in AP i+j j-1/2 for i≤j;
  • if UPLO='L', the lower triangle of A must be stored with element A ij in AP i+2 n-jj-1/2 for i≥j.
On exit: AP is overwritten by the values generated during the reduction to tridiagonal form. The elements of the diagonal and the off-diagonal of the tridiagonal matrix overwrite the corresponding elements of A.
6:   VL – REAL (KIND=nag_wp)Input
7:   VU – REAL (KIND=nag_wp)Input
On entry: if RANGE='V', the lower and upper bounds of the interval to be searched for eigenvalues.
If RANGE='A' or 'I', VL and VU are not referenced.
Constraint: if RANGE='V', VL<VU.
8:   IL – INTEGERInput
9:   IU – INTEGERInput
On entry: if RANGE='I', the indices (in ascending order) of the smallest and largest eigenvalues to be returned.
If RANGE='A' or 'V', IL and IU are not referenced.
Constraints:
  • if RANGE='I' and N=0, IL=1 and IU=0;
  • if RANGE='I' and N>0, 1≤ IL≤ IU≤ N .
10:   ABSTOL – REAL (KIND=nag_wp)Input
On entry: the absolute error tolerance for the eigenvalues. An approximate eigenvalue is accepted as converged when it is determined to lie in an interval a,b of width less than or equal to
ABSTOL+ε max a,b ,
where ε is the machine precision. If ABSTOL is less than or equal to zero, then ε T 1 will be used in its place, where T is the tridiagonal matrix obtained by reducing A to tridiagonal form. Eigenvalues will be computed most accurately when ABSTOL is set to twice the underflow threshold 2 × X02AMF , not zero. If this routine returns with INFO>0, indicating that some eigenvectors did not converge, try setting ABSTOL to 2 × X02AMF . See Demmel and Kahan (1990).
11:   M – INTEGEROutput
On exit: the total number of eigenvalues found. 0≤M≤N.
If RANGE='A', M=N.
If RANGE='I', M=IU-IL+1.
12:   W N – REAL (KIND=nag_wp) arrayOutput
On exit: the selected eigenvalues in ascending order.
13:   Z LDZ* – REAL (KIND=nag_wp) arrayOutput
Note: the second dimension of the array Z must be at least max 1,M if JOBZ='V', and at least 1 otherwise.
On exit: if JOBZ='V', then
  • if INFO=0, the first M columns of Z contain the orthonormal eigenvectors of the matrix A corresponding to the selected eigenvalues, with the ith column of Z holding the eigenvector associated with W i;
  • if an eigenvector fails to converge (INFO>0), then that column of Z contains the latest approximation to the eigenvector, and the index of the eigenvector is returned in JFAIL.
If JOBZ='N', Z is not referenced.
Note: you must ensure that at least max 1,M columns are supplied in the array Z; if RANGE='V', the exact value of M is not known in advance and an upper bound of at least N must be used.
14:   LDZ – INTEGERInput
On entry: the first dimension of the array Z as declared in the (sub)program from which F08GBF (DSPEVX) is called.
Constraints:
  • if JOBZ='V', LDZ≥ max 1,N ;
  • otherwise LDZ≥1.
15:   WORK 8×N – REAL (KIND=nag_wp) arrayWorkspace
16:   IWORK 5×N – INTEGER arrayWorkspace
17:   JFAIL* – INTEGER arrayOutput
Note: the dimension of the array JFAIL must be at least max 1,N.
On exit: if JOBZ='V', then
  • if INFO=0, the first M elements of JFAIL are zero;
  • if INFO>0, JFAIL contains the indices of the eigenvectors that failed to converge.
If JOBZ='N', JFAIL is not referenced.
18:   INFO – INTEGEROutput
On exit: INFO=0 unless the routine detects an error (see Section 6).

6 Error Indicators and Warnings

INFO<0
If INFO=-i, argument i had an illegal value. An explanatory message is output, and execution of the program is terminated.
INFO>0
The algorithm failed to converge; value eigenvectors did not converge. Their indices are stored in array JFAIL.

7 Accuracy

The computed eigenvalues and eigenvectors are exact for a nearby matrix A+E, where
E 2 = O ε A 2 ,
and ε is the machine precision. See Section 4.7 of Anderson et al. (1999) for further details.

8 Parallelism and Performance

F08GBF (DSPEVX) is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
F08GBF (DSPEVX) makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The total number of floating-point operations is proportional to n 3.
The complex analogue of this routine is F08GPF (ZHPEVX).

10 Example

This example finds the eigenvalues in the half-open interval -1,1 , and the corresponding eigenvectors, of the symmetric matrix
A = 1 2 3 4 2 2 3 4 3 3 3 4 4 4 4 4 .

10.1 Program Text

Program Text (f08gbfe.f90)

10.2 Program Data

Program Data (f08gbfe.d)

10.3 Program Results

Program Results (f08gbfe.r)

F08 Chapter Contents
F08 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F08GCF (DSPEVD) : NAG Library, Mark 26

F08 Chapter Contents
F08 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F08GCF (DSPEVD)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.
Warning. The specification of the arguments LWORK and LIWORK changed at Mark 20 in the case where JOB='V' and N>1: the minimum dimension of the array WORK has been reduced whereas the minimum dimension of the array IWORK has been increased.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F08GCF (DSPEVD) computes all the eigenvalues and, optionally, all the eigenvectors of a real symmetric matrix held in packed storage. If the eigenvectors are requested, then it uses a divide-and-conquer algorithm to compute eigenvalues and eigenvectors. However, if only eigenvalues are required, then it uses the Pal–Walker–Kahan variant of the QL or QR algorithm.

2 Specification

SUBROUTINE F08GCF ( JOB, UPLO, N, AP, W, Z, LDZ, WORK, LWORK, IWORK, LIWORK, INFO)
INTEGER | N, LDZ, LWORK, IWORK(max(1,LIWORK)), LIWORK, INFO
REAL (KIND=nag_wp) | AP(*), W(*), Z(LDZ,*), WORK(max(1,LWORK))
CHARACTER(1) | JOB, UPLO
The routine may be called by its LAPACK name dspevd.

3 Description

F08GCF (DSPEVD) computes all the eigenvalues and, optionally, all the eigenvectors of a real symmetric matrix A (held in packed storage). In other words, it can compute the spectral factorization of A as
A=ZΛ ZT,
where Λ is a diagonal matrix whose diagonal elements are the eigenvalues λi, and Z is the orthogonal matrix whose columns are the eigenvectors zi. Thus
A zi=λizi,  i=1,2,…,n.

4 References

Anderson E, Bai Z, Bischof C, Blackford S, Demmel J, Dongarra J J, Du Croz J J, Greenbaum A, Hammarling S, McKenney A and Sorensen D (1999) LAPACK Users' Guide (3rd Edition) SIAM, Philadelphia http://www.netlib.org/lapack/lug
Golub G H and Van Loan C F (1996) Matrix Computations (3rd Edition) Johns Hopkins University Press, Baltimore

5 Arguments

1:   JOB – CHARACTER(1)Input
On entry: indicates whether eigenvectors are computed.
JOB='N'
Only eigenvalues are computed.
JOB='V'
Eigenvalues and eigenvectors are computed.
Constraint: JOB='N' or 'V'.
2:   UPLO – CHARACTER(1)Input
On entry: indicates whether the upper or lower triangular part of A is stored.
UPLO='U'
The upper triangular part of A is stored.
UPLO='L'
The lower triangular part of A is stored.
Constraint: UPLO='U' or 'L'.
3:   N – INTEGERInput
On entry: n, the order of the matrix A.
Constraint: N≥0.
4:   AP* – REAL (KIND=nag_wp) arrayInput/Output
Note: the dimension of the array AP must be at least max 1,N×N+1/2.
On entry: the upper or lower triangle of the n by n symmetric matrix A, packed by columns.
More precisely,
  • if UPLO='U', the upper triangle of A must be stored with element A ij in AP i+j j-1/2 for i≤j;
  • if UPLO='L', the lower triangle of A must be stored with element A ij in AP i+2 n-jj-1/2 for i≥j.
On exit: AP is overwritten by the values generated during the reduction to tridiagonal form. The elements of the diagonal and the off-diagonal of the tridiagonal matrix overwrite the corresponding elements of A.
5:   W* – REAL (KIND=nag_wp) arrayOutput
Note: the dimension of the array W must be at least max 1,N.
On exit: the eigenvalues of the matrix A in ascending order.
6:   Z LDZ* – REAL (KIND=nag_wp) arrayOutput
Note: the second dimension of the array Z must be at least max 1,N if JOB='V' and at least 1 if JOB='N'.
On exit: if JOB='V', Z is overwritten by the orthogonal matrix Z which contains the eigenvectors of A.
If JOB='N', Z is not referenced.
7:   LDZ – INTEGERInput
On entry: the first dimension of the array Z as declared in the (sub)program from which F08GCF (DSPEVD) is called.
Constraints:
  • if JOB='V', LDZ≥ max 1,N ;
  • if JOB='N', LDZ≥1.
8:   WORK max 1,LWORK – REAL (KIND=nag_wp) arrayWorkspace
On exit: if INFO=0, WORK 1 contains the required minimal size of LWORK.
9:   LWORK – INTEGERInput
On entry: the dimension of the array WORK as declared in the (sub)program from which F08GCF (DSPEVD) is called.
If LWORK=-1, a workspace query is assumed; the routine only calculates the minimum dimension of the WORK array, returns this value as the first entry of the WORK array, and no error message related to LWORK is issued.
Constraints:
  • if N≤1, LWORK≥1 or LWORK=-1;
  • if JOB='N' and N>1, LWORK≥2×N or LWORK=-1;
  • if JOB='V' and N>1, LWORK≥N 2+6×N+1 or LWORK=-1.
10:   IWORK max 1,LIWORK – INTEGER arrayWorkspace
On exit: if INFO=0, IWORK 1 contains the required minimal size of LIWORK.
11:   LIWORK – INTEGERInput
On entry: the dimension of the array IWORK as declared in the (sub)program from which F08GCF (DSPEVD) is called.
If LIWORK=-1, a workspace query is assumed; the routine only calculates the minimum dimension of the IWORK array, returns this value as the first entry of the IWORK array, and no error message related to LIWORK is issued.
Constraints:
  • if JOB='N' or N≤1, LIWORK≥1 or LIWORK=-1;
  • if JOB='V' and N>1, LIWORK≥5×N+3 or LIWORK=-1.
12:   INFO – INTEGEROutput
On exit: INFO=0 unless the routine detects an error (see Section 6).

6 Error Indicators and Warnings

INFO<0
If INFO=-i, argument i had an illegal value. An explanatory message is output, and execution of the program is terminated.
INFO>0
if INFO=i and JOB='N', the algorithm failed to converge; i elements of an intermediate tridiagonal form did not converge to zero; if INFO=i and JOB='V', then the algorithm failed to compute an eigenvalue while working on the submatrix lying in rows and column i/N+1 through i mod N+1.

7 Accuracy

The computed eigenvalues and eigenvectors are exact for a nearby matrix A+E, where
E 2 = O ε A 2 ,
and ε is the machine precision. See Section 4.7 of Anderson et al. (1999) for further details.

8 Parallelism and Performance

F08GCF (DSPEVD) is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
F08GCF (DSPEVD) makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The complex analogue of this routine is F08GQF (ZHPEVD).

10 Example

This example computes all the eigenvalues and eigenvectors of the symmetric matrix A, where
A = 1.0 2.0 3.0 4.0 2.0 2.0 3.0 4.0 3.0 3.0 3.0 4.0 4.0 4.0 4.0 4.0 .

10.1 Program Text

Program Text (f08gcfe.f90)

10.2 Program Data

Program Data (f08gcfe.d)

10.3 Program Results

Program Results (f08gcfe.r)

F08 Chapter Contents
F08 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F08GEF (DSPTRD) : NAG Library, Mark 26

F08 Chapter Contents
F08 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F08GEF (DSPTRD)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F08GEF (DSPTRD) reduces a real symmetric matrix to tridiagonal form, using packed storage.

2 Specification

SUBROUTINE F08GEF ( UPLO, N, AP, D, E, TAU, INFO)
INTEGER | N, INFO
REAL (KIND=nag_wp) | AP(*), D(N), E(N-1), TAU(N-1)
CHARACTER(1) | UPLO
The routine may be called by its LAPACK name dsptrd.

3 Description

F08GEF (DSPTRD) reduces a real symmetric matrix A, held in packed storage, to symmetric tridiagonal form T by an orthogonal similarity transformation: A=QT QT.
The matrix Q is not formed explicitly but is represented as a product of n-1 elementary reflectors (see the F08 Chapter Introduction for details). Routines are provided to work with Q in this representation (see Section 9).

4 References

Golub G H and Van Loan C F (1996) Matrix Computations (3rd Edition) Johns Hopkins University Press, Baltimore

5 Arguments

1:   UPLO – CHARACTER(1)Input
On entry: indicates whether the upper or lower triangular part of A is stored.
UPLO='U'
The upper triangular part of A is stored.
UPLO='L'
The lower triangular part of A is stored.
Constraint: UPLO='U' or 'L'.
2:   N – INTEGERInput
On entry: n, the order of the matrix A.
Constraint: N≥0.
3:   AP* – REAL (KIND=nag_wp) arrayInput/Output
Note: the dimension of the array AP must be at least max 1,N×N+1/2.
On entry: the upper or lower triangle of the n by n symmetric matrix A, packed by columns.
More precisely,
  • if UPLO='U', the upper triangle of A must be stored with element A ij in AP i+j j-1/2 for i≤j;
  • if UPLO='L', the lower triangle of A must be stored with element A ij in AP i+2 n-jj-1/2 for i≥j.
On exit: AP is overwritten by the tridiagonal matrix T and details of the orthogonal matrix Q.
4:   D N – REAL (KIND=nag_wp) arrayOutput
On exit: the diagonal elements of the tridiagonal matrix T.
5:   E N-1 – REAL (KIND=nag_wp) arrayOutput
On exit: the off-diagonal elements of the tridiagonal matrix T.
6:   TAU N-1 – REAL (KIND=nag_wp) arrayOutput
On exit: further details of the orthogonal matrix Q.
7:   INFO – INTEGEROutput
On exit: INFO=0 unless the routine detects an error (see Section 6).

6 Error Indicators and Warnings

INFO<0
If INFO=-i, argument i had an illegal value. An explanatory message is output, and execution of the program is terminated.

7 Accuracy

The computed tridiagonal matrix T is exactly similar to a nearby matrix A+E, where
E 2≤ c n ε A 2 ,
c n is a modestly increasing function of n, and ε is the machine precision.
The elements of T themselves may be sensitive to small perturbations in A or to rounding errors in the computation, but this does not affect the stability of the eigenvalues and eigenvectors.

8 Parallelism and Performance

F08GEF (DSPTRD) makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The total number of floating-point operations is approximately 43 n 3 .
To form the orthogonal matrix Q F08GEF (DSPTRD) may be followed by a call to F08GFF (DOPGTR):
CALL DOPGTR(UPLO,N,AP,TAU,Q,LDQ,WORK,INFO)
To apply Q to an n by p real matrix C F08GEF (DSPTRD) may be followed by a call to F08GGF (DOPMTR). For example,
CALL DOPMTR('Left',UPLO,'No Transpose',N,P,AP,TAU,C,LDC,WORK, &
              INFO)
forms the matrix product QC.
The complex analogue of this routine is F08GSF (ZHPTRD).

10 Example

This example reduces the matrix A to tridiagonal form, where
A = 2.07 3.87 4.20 -1.15 3.87 -0.21 1.87 0.63 4.20 1.87 1.15 2.06 -1.15 0.63 2.06 -1.81 ,
using packed storage.

10.1 Program Text

Program Text (f08gefe.f90)

10.2 Program Data

Program Data (f08gefe.d)

10.3 Program Results

Program Results (f08gefe.r)

F08 Chapter Contents
F08 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F08GFF (DOPGTR) : NAG Library, Mark 26

F08 Chapter Contents
F08 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F08GFF (DOPGTR)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F08GFF (DOPGTR) generates the real orthogonal matrix Q, which was determined by F08GEF (DSPTRD) when reducing a symmetric matrix to tridiagonal form.

2 Specification

SUBROUTINE F08GFF ( UPLO, N, AP, TAU, Q, LDQ, WORK, INFO)
INTEGER | N, LDQ, INFO
REAL (KIND=nag_wp) | AP(*), TAU(*), Q(LDQ,*), WORK(N-1)
CHARACTER(1) | UPLO
The routine may be called by its LAPACK name dopgtr.

3 Description

F08GFF (DOPGTR) is intended to be used after a call to F08GEF (DSPTRD), which reduces a real symmetric matrix A to symmetric tridiagonal form T by an orthogonal similarity transformation: A=QT QT. F08GEF (DSPTRD) represents the orthogonal matrix Q as a product of n-1 elementary reflectors.
This routine may be used to generate Q explicitly as a square matrix.

4 References

Golub G H and Van Loan C F (1996) Matrix Computations (3rd Edition) Johns Hopkins University Press, Baltimore

5 Arguments

1:   UPLO – CHARACTER(1)Input
On entry: this must be the same argument UPLO as supplied to F08GEF (DSPTRD).
Constraint: UPLO='U' or 'L'.
2:   N – INTEGERInput
On entry: n, the order of the matrix Q.
Constraint: N≥0.
3:   AP* – REAL (KIND=nag_wp) arrayInput
Note: the dimension of the array AP must be at least max 1,N×N+1/2.
On entry: details of the vectors which define the elementary reflectors, as returned by F08GEF (DSPTRD).
4:   TAU* – REAL (KIND=nag_wp) arrayInput
Note: the dimension of the array TAU must be at least max 1,N-1.
On entry: further details of the elementary reflectors, as returned by F08GEF (DSPTRD).
5:   Q LDQ* – REAL (KIND=nag_wp) arrayOutput
Note: the second dimension of the array Q must be at least max 1,N.
On exit: the n by n orthogonal matrix Q.
6:   LDQ – INTEGERInput
On entry: the first dimension of the array Q as declared in the (sub)program from which F08GFF (DOPGTR) is called.
Constraint: LDQ≥max 1,N.
7:   WORK N-1 – REAL (KIND=nag_wp) arrayWorkspace
8:   INFO – INTEGEROutput
On exit: INFO=0 unless the routine detects an error (see Section 6).

6 Error Indicators and Warnings

INFO<0
If INFO=-i, argument i had an illegal value. An explanatory message is output, and execution of the program is terminated.

7 Accuracy

The computed matrix Q differs from an exactly orthogonal matrix by a matrix E such that
E 2 = O ε ,
where ε is the machine precision.

8 Parallelism and Performance

F08GFF (DOPGTR) is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
F08GFF (DOPGTR) makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The total number of floating-point operations is approximately 43 n 3.
The complex analogue of this routine is F08GTF (ZUPGTR).

10 Example

This example computes all the eigenvalues and eigenvectors of the matrix A, where
A = 2.07 3.87 4.20 -1.15 3.87 -0.21 1.87 0.63 4.20 1.87 1.15 2.06 -1.15 0.63 2.06 -1.81 ,
using packed storage. Here A is symmetric and must first be reduced to tridiagonal form by F08GEF (DSPTRD). The program then calls F08GFF (DOPGTR) to form Q, and passes this matrix to F08JEF (DSTEQR) which computes the eigenvalues and eigenvectors of A.

10.1 Program Text

Program Text (f08gffe.f90)

10.2 Program Data

Program Data (f08gffe.d)

10.3 Program Results

Program Results (f08gffe.r)

F08 Chapter Contents
F08 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F08GGF (DOPMTR) : NAG Library, Mark 26

F08 Chapter Contents
F08 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F08GGF (DOPMTR)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F08GGF (DOPMTR) multiplies an arbitrary real matrix C by the real orthogonal matrix Q which was determined by F08GEF (DSPTRD) when reducing a real symmetric matrix to tridiagonal form.

2 Specification

SUBROUTINE F08GGF ( SIDE, UPLO, TRANS, M, N, AP, TAU, C, LDC, WORK, INFO)
INTEGER | M, N, LDC, INFO
REAL (KIND=nag_wp) | AP(*), TAU(*), C(LDC,*), WORK(*)
CHARACTER(1) | SIDE, UPLO, TRANS
The routine may be called by its LAPACK name dopmtr.

3 Description

F08GGF (DOPMTR) is intended to be used after a call to F08GEF (DSPTRD), which reduces a real symmetric matrix A to symmetric tridiagonal form T by an orthogonal similarity transformation: A=QT QT. F08GEF (DSPTRD) represents the orthogonal matrix Q as a product of elementary reflectors.
This routine may be used to form one of the matrix products
QC , QT C , CQ ​ or ​ C QT ,
overwriting the result on C (which may be any real rectangular matrix).
A common application of this routine is to transform a matrix Z of eigenvectors of T to the matrix QZ of eigenvectors of A.

4 References

Golub G H and Van Loan C F (1996) Matrix Computations (3rd Edition) Johns Hopkins University Press, Baltimore

5 Arguments

1:   SIDE – CHARACTER(1)Input
On entry: indicates how Q or QT is to be applied to C.
SIDE='L'
Q or QT is applied to C from the left.
SIDE='R'
Q or QT is applied to C from the right.
Constraint: SIDE='L' or 'R'.
2:   UPLO – CHARACTER(1)Input
On entry: this must be the same argument UPLO as supplied to F08GEF (DSPTRD).
Constraint: UPLO='U' or 'L'.
3:   TRANS – CHARACTER(1)Input
On entry: indicates whether Q or QT is to be applied to C.
TRANS='N'
Q is applied to C.
TRANS='T'
QT is applied to C.
Constraint: TRANS='N' or 'T'.
4:   M – INTEGERInput
On entry: m, the number of rows of the matrix C; m is also the order of Q if SIDE='L'.
Constraint: M≥0.
5:   N – INTEGERInput
On entry: n, the number of columns of the matrix C; n is also the order of Q if SIDE='R'.
Constraint: N≥0.
6:   AP* – REAL (KIND=nag_wp) arrayInput/Output
Note: the dimension of the array AP must be at least max 1, M × M+1 / 2 if SIDE='L' and at least max 1, N × N+1 / 2 if SIDE='R'.
On entry: details of the vectors which define the elementary reflectors, as returned by F08GEF (DSPTRD).
On exit: is used as internal workspace prior to being restored and hence is unchanged.
7:   TAU* – REAL (KIND=nag_wp) arrayInput
Note: the dimension of the array TAU must be at least max 1,M-1 if SIDE='L' and at least max 1,N-1 if SIDE='R'.
On entry: further details of the elementary reflectors, as returned by F08GEF (DSPTRD).
8:   C LDC* – REAL (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array C must be at least max 1,N.
On entry: the m by n matrix C.
On exit: C is overwritten by QC or QT C or CQ or C QT as specified by SIDE and TRANS.
9:   LDC – INTEGERInput
On entry: the first dimension of the array C as declared in the (sub)program from which F08GGF (DOPMTR) is called.
Constraint: LDC≥max 1,M.
10:   WORK* – REAL (KIND=nag_wp) arrayWorkspace
Note: the dimension of the array WORK must be at least max 1,N if SIDE='L' and at least max 1,M if SIDE='R'.
11:   INFO – INTEGEROutput
On exit: INFO=0 unless the routine detects an error (see Section 6).

6 Error Indicators and Warnings

INFO<0
If INFO=-i, argument i had an illegal value. An explanatory message is output, and execution of the program is terminated.

7 Accuracy

The computed result differs from the exact result by a matrix E such that
E 2 = O ε C 2 ,
where ε is the machine precision.

8 Parallelism and Performance

F08GGF (DOPMTR) makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The total number of floating-point operations is approximately 2 m 2 n if SIDE='L' and 2 m n 2 if SIDE='R'.
The complex analogue of this routine is F08GUF (ZUPMTR).

10 Example

This example computes the two smallest eigenvalues, and the associated eigenvectors, of the matrix A, where
A = 2.07 3.87 4.20 -1.15 3.87 -0.21 1.87 0.63 4.20 1.87 1.15 2.06 -1.15 0.63 2.06 -1.81 ,
using packed storage. Here A is symmetric and must first be reduced to tridiagonal form T by F08GEF (DSPTRD). The program then calls F08JJF (DSTEBZ) to compute the requested eigenvalues and F08JKF (DSTEIN) to compute the associated eigenvectors of T. Finally F08GGF (DOPMTR) is called to transform the eigenvectors to those of A.

10.1 Program Text

Program Text (f08ggfe.f90)

10.2 Program Data

Program Data (f08ggfe.d)

10.3 Program Results

Program Results (f08ggfe.r)

F08 Chapter Contents
F08 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F08GNF (ZHPEV) : NAG Library, Mark 26

F08 Chapter Contents
F08 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F08GNF (ZHPEV)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F08GNF (ZHPEV) computes all the eigenvalues and, optionally, all the eigenvectors of a complex n by n Hermitian matrix A in packed storage.

2 Specification

SUBROUTINE F08GNF ( JOBZ, UPLO, N, AP, W, Z, LDZ, WORK, RWORK, INFO)
INTEGER | N, LDZ, INFO
REAL (KIND=nag_wp) | W(N), RWORK(3*N-2)
COMPLEX (KIND=nag_wp) | AP(*), Z(LDZ,*), WORK(2*N-1)
CHARACTER(1) | JOBZ, UPLO
The routine may be called by its LAPACK name zhpev.

3 Description

The Hermitian matrix A is first reduced to real tridiagonal form, using unitary similarity transformations, and then the QR algorithm is applied to the tridiagonal matrix to compute the eigenvalues and (optionally) the eigenvectors.

4 References

Anderson E, Bai Z, Bischof C, Blackford S, Demmel J, Dongarra J J, Du Croz J J, Greenbaum A, Hammarling S, McKenney A and Sorensen D (1999) LAPACK Users' Guide (3rd Edition) SIAM, Philadelphia http://www.netlib.org/lapack/lug
Golub G H and Van Loan C F (1996) Matrix Computations (3rd Edition) Johns Hopkins University Press, Baltimore

5 Arguments

1:   JOBZ – CHARACTER(1)Input
On entry: indicates whether eigenvectors are computed.
JOBZ='N'
Only eigenvalues are computed.
JOBZ='V'
Eigenvalues and eigenvectors are computed.
Constraint: JOBZ='N' or 'V'.
2:   UPLO – CHARACTER(1)Input
On entry: if UPLO='U', the upper triangular part of A is stored.
If UPLO='L', the lower triangular part of A is stored.
Constraint: UPLO='U' or 'L'.
3:   N – INTEGERInput
On entry: n, the order of the matrix A.
Constraint: N≥0.
4:   AP* – COMPLEX (KIND=nag_wp) arrayInput/Output
Note: the dimension of the array AP must be at least max 1,N×N+1/2.
On entry: the upper or lower triangle of the n by n Hermitian matrix A, packed by columns.
More precisely,
  • if UPLO='U', the upper triangle of A must be stored with element A ij in AP i+j j-1/2 for i≤j;
  • if UPLO='L', the lower triangle of A must be stored with element A ij in AP i+2 n-jj-1/2 for i≥j.
On exit: AP is overwritten by the values generated during the reduction to tridiagonal form. The elements of the diagonal and the off-diagonal of the tridiagonal matrix overwrite the corresponding elements of A.
5:   W N – REAL (KIND=nag_wp) arrayOutput
On exit: the eigenvalues in ascending order.
6:   Z LDZ* – COMPLEX (KIND=nag_wp) arrayOutput
Note: the second dimension of the array Z must be at least max 1,N if JOBZ='V', and at least 1 otherwise.
On exit: if JOBZ='V', Z contains the orthonormal eigenvectors of the matrix A, with the ith column of Z holding the eigenvector associated with W i.
If JOBZ='N', Z is not referenced.
7:   LDZ – INTEGERInput
On entry: the first dimension of the array Z as declared in the (sub)program from which F08GNF (ZHPEV) is called.
Constraints:
  • if JOBZ='V', LDZ≥ max 1,N ;
  • otherwise LDZ≥1.
8:   WORK 2×N-1 – COMPLEX (KIND=nag_wp) arrayWorkspace
9:   RWORK 3×N-2 – REAL (KIND=nag_wp) arrayWorkspace
10:   INFO – INTEGEROutput
On exit: INFO=0 unless the routine detects an error (see Section 6).

6 Error Indicators and Warnings

INFO<0
If INFO=-i, argument i had an illegal value. An explanatory message is output, and execution of the program is terminated.
INFO>0
If INFO=i, the algorithm failed to converge; i off-diagonal elements of an intermediate tridiagonal form did not converge to zero.

7 Accuracy

The computed eigenvalues and eigenvectors are exact for a nearby matrix A+E, where
E 2 = O ε A 2 ,
and ε is the machine precision. See Section 4.7 of Anderson et al. (1999) for further details.

8 Parallelism and Performance

F08GNF (ZHPEV) is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
F08GNF (ZHPEV) makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

Each eigenvector is normalized so that the element of largest absolute value is real.
The total number of floating-point operations is proportional to n 3.
The real analogue of this routine is F08GAF (DSPEV).

10 Example

This example finds all the eigenvalues of the Hermitian matrix
A = 1 2-i 3-i 4-i 2+i 2 3-2 i 4-2 i 3+i 3+2 i 3 4-3 i 4+i 4+2 i 4+3 i 4 ,
together with approximate error bounds for the computed eigenvalues.

10.1 Program Text

Program Text (f08gnfe.f90)

10.2 Program Data

Program Data (f08gnfe.d)

10.3 Program Results

Program Results (f08gnfe.r)

F08 Chapter Contents
F08 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F08GPF (ZHPEVX) : NAG Library, Mark 26

F08 Chapter Contents
F08 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F08GPF (ZHPEVX)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F08GPF (ZHPEVX) computes selected eigenvalues and, optionally, eigenvectors of a complex n by n Hermitian matrix A in packed storage. Eigenvalues and eigenvectors can be selected by specifying either a range of values or a range of indices for the desired eigenvalues.

2 Specification

SUBROUTINE F08GPF ( JOBZ, RANGE, UPLO, N, AP, VL, VU, IL, IU, ABSTOL, M, W, Z, LDZ, WORK, RWORK, IWORK, JFAIL, INFO)
INTEGER | N, IL, IU, M, LDZ, IWORK(5*N), JFAIL(*), INFO
REAL (KIND=nag_wp) | VL, VU, ABSTOL, W(N), RWORK(7*N)
COMPLEX (KIND=nag_wp) | AP(*), Z(LDZ,*), WORK(2*N)
CHARACTER(1) | JOBZ, RANGE, UPLO
The routine may be called by its LAPACK name zhpevx.

3 Description

The Hermitian matrix A is first reduced to real tridiagonal form, using unitary similarity transformations. The required eigenvalues and eigenvectors are then computed from the tridiagonal matrix; the method used depends upon whether all, or selected, eigenvalues and eigenvectors are required.

4 References

Anderson E, Bai Z, Bischof C, Blackford S, Demmel J, Dongarra J J, Du Croz J J, Greenbaum A, Hammarling S, McKenney A and Sorensen D (1999) LAPACK Users' Guide (3rd Edition) SIAM, Philadelphia http://www.netlib.org/lapack/lug
Demmel J W and Kahan W (1990) Accurate singular values of bidiagonal matrices SIAM J. Sci. Statist. Comput. 11 873–912
Golub G H and Van Loan C F (1996) Matrix Computations (3rd Edition) Johns Hopkins University Press, Baltimore

5 Arguments

1:   JOBZ – CHARACTER(1)Input
On entry: indicates whether eigenvectors are computed.
JOBZ='N'
Only eigenvalues are computed.
JOBZ='V'
Eigenvalues and eigenvectors are computed.
Constraint: JOBZ='N' or 'V'.
2:   RANGE – CHARACTER(1)Input
On entry: if RANGE='A', all eigenvalues will be found.
If RANGE='V', all eigenvalues in the half-open interval VL,VU will be found.
If RANGE='I', the ILth to IUth eigenvalues will be found.
Constraint: RANGE='A', 'V' or 'I'.
3:   UPLO – CHARACTER(1)Input
On entry: if UPLO='U', the upper triangular part of A is stored.
If UPLO='L', the lower triangular part of A is stored.
Constraint: UPLO='U' or 'L'.
4:   N – INTEGERInput
On entry: n, the order of the matrix A.
Constraint: N≥0.
5:   AP* – COMPLEX (KIND=nag_wp) arrayInput/Output
Note: the dimension of the array AP must be at least max 1,N×N+1/2.
On entry: the upper or lower triangle of the n by n Hermitian matrix A, packed by columns.
More precisely,
  • if UPLO='U', the upper triangle of A must be stored with element A ij in AP i+j j-1/2 for i≤j;
  • if UPLO='L', the lower triangle of A must be stored with element A ij in AP i+2 n-jj-1/2 for i≥j.
On exit: AP is overwritten by the values generated during the reduction to tridiagonal form. The elements of the diagonal and the off-diagonal of the tridiagonal matrix overwrite the corresponding elements of A.
6:   VL – REAL (KIND=nag_wp)Input
7:   VU – REAL (KIND=nag_wp)Input
On entry: if RANGE='V', the lower and upper bounds of the interval to be searched for eigenvalues.
If RANGE='A' or 'I', VL and VU are not referenced.
Constraint: if RANGE='V', VL<VU.
8:   IL – INTEGERInput
9:   IU – INTEGERInput
On entry: if RANGE='I', the indices (in ascending order) of the smallest and largest eigenvalues to be returned.
If RANGE='A' or 'V', IL and IU are not referenced.
Constraints:
  • if RANGE='I' and N=0, IL=1 and IU=0;
  • if RANGE='I' and N>0, 1≤ IL≤ IU≤ N .
10:   ABSTOL – REAL (KIND=nag_wp)Input
On entry: the absolute error tolerance for the eigenvalues. An approximate eigenvalue is accepted as converged when it is determined to lie in an interval a,b of width less than or equal to
ABSTOL+ε max a,b ,
where ε is the machine precision. If ABSTOL is less than or equal to zero, then ε T 1 will be used in its place, where T is the tridiagonal matrix obtained by reducing A to tridiagonal form. Eigenvalues will be computed most accurately when ABSTOL is set to twice the underflow threshold 2 × X02AMF , not zero. If this routine returns with INFO>0, indicating that some eigenvectors did not converge, try setting ABSTOL to 2 × X02AMF . See Demmel and Kahan (1990).
11:   M – INTEGEROutput
On exit: the total number of eigenvalues found. 0≤M≤N.
If RANGE='A', M=N.
If RANGE='I', M=IU-IL+1.
12:   W N – REAL (KIND=nag_wp) arrayOutput
On exit: the selected eigenvalues in ascending order.
13:   Z LDZ* – COMPLEX (KIND=nag_wp) arrayOutput
Note: the second dimension of the array Z must be at least max 1,M if JOBZ='V', and at least 1 otherwise.
On exit: if JOBZ='V', then
  • if INFO=0, the first M columns of Z contain the orthonormal eigenvectors of the matrix A corresponding to the selected eigenvalues, with the ith column of Z holding the eigenvector associated with W i;
  • if an eigenvector fails to converge (INFO>0), then that column of Z contains the latest approximation to the eigenvector, and the index of the eigenvector is returned in JFAIL.
If JOBZ='N', Z is not referenced.
Note: you must ensure that at least max 1,M columns are supplied in the array Z; if RANGE='V', the exact value of M is not known in advance and an upper bound of at least N must be used.
14:   LDZ – INTEGERInput
On entry: the first dimension of the array Z as declared in the (sub)program from which F08GPF (ZHPEVX) is called.
Constraints:
  • if JOBZ='V', LDZ≥ max 1,N ;
  • otherwise LDZ≥1.
15:   WORK 2×N – COMPLEX (KIND=nag_wp) arrayWorkspace
16:   RWORK 7×N – REAL (KIND=nag_wp) arrayWorkspace
17:   IWORK 5×N – INTEGER arrayWorkspace
18:   JFAIL* – INTEGER arrayOutput
Note: the dimension of the array JFAIL must be at least max 1,N.
On exit: if JOBZ='V', then
  • if INFO=0, the first M elements of JFAIL are zero;
  • if INFO>0, JFAIL contains the indices of the eigenvectors that failed to converge.
If JOBZ='N', JFAIL is not referenced.
19:   INFO – INTEGEROutput
On exit: INFO=0 unless the routine detects an error (see Section 6).

6 Error Indicators and Warnings

INFO<0
If INFO=-i, argument i had an illegal value. An explanatory message is output, and execution of the program is terminated.
INFO>0
The algorithm failed to converge; value eigenvectors did not converge. Their indices are stored in array JFAIL.

7 Accuracy

The computed eigenvalues and eigenvectors are exact for a nearby matrix A+E, where
E 2 = O ε A 2 ,
and ε is the machine precision. See Section 4.7 of Anderson et al. (1999) for further details.

8 Parallelism and Performance

F08GPF (ZHPEVX) is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
F08GPF (ZHPEVX) makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The total number of floating-point operations is proportional to n 3.
The real analogue of this routine is F08GBF (DSPEVX).

10 Example

This example finds the eigenvalues in the half-open interval -2,2 , and the corresponding eigenvectors, of the Hermitian matrix
A = 1 2-i 3-i 4-i 2+i 2 3-2 i 4-2 i 3+i 3+2 i 3 4-3 i 4+i 4+2 i 4+3 i 4 .

10.1 Program Text

Program Text (f08gpfe.f90)

10.2 Program Data

Program Data (f08gpfe.d)

10.3 Program Results

Program Results (f08gpfe.r)

F08 Chapter Contents
F08 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F08GQF (ZHPEVD) : NAG Library, Mark 26

F08 Chapter Contents
F08 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F08GQF (ZHPEVD)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.
Warning. The specification of the arguments LRWORK and LIWORK changed at Mark 20 in the case where JOB='V' and N>1: the minimum dimension of the array RWORK has been reduced whereas the minimum dimension of the array IWORK has been increased.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F08GQF (ZHPEVD) computes all the eigenvalues and, optionally, all the eigenvectors of a complex Hermitian matrix held in packed storage. If the eigenvectors are requested, then it uses a divide-and-conquer algorithm to compute eigenvalues and eigenvectors. However, if only eigenvalues are required, then it uses the Pal–Walker–Kahan variant of the QL or QR algorithm.

2 Specification

SUBROUTINE F08GQF ( JOB, UPLO, N, AP, W, Z, LDZ, WORK, LWORK, RWORK, LRWORK, IWORK, LIWORK, INFO)
INTEGER | N, LDZ, LWORK, LRWORK, IWORK(max(1,LIWORK)), LIWORK, INFO
REAL (KIND=nag_wp) | W(*), RWORK(max(1,LRWORK))
COMPLEX (KIND=nag_wp) | AP(*), Z(LDZ,*), WORK(max(1,LWORK))
CHARACTER(1) | JOB, UPLO
The routine may be called by its LAPACK name zhpevd.

3 Description

F08GQF (ZHPEVD) computes all the eigenvalues and, optionally, all the eigenvectors of a complex Hermitian matrix A (held in packed storage). In other words, it can compute the spectral factorization of A as
A=ZΛ ZH,
where Λ is a real diagonal matrix whose diagonal elements are the eigenvalues λi, and Z is the (complex) unitary matrix whose columns are the eigenvectors zi. Thus
A zi=λizi,  i=1,2,…,n.

4 References

Anderson E, Bai Z, Bischof C, Blackford S, Demmel J, Dongarra J J, Du Croz J J, Greenbaum A, Hammarling S, McKenney A and Sorensen D (1999) LAPACK Users' Guide (3rd Edition) SIAM, Philadelphia http://www.netlib.org/lapack/lug
Golub G H and Van Loan C F (1996) Matrix Computations (3rd Edition) Johns Hopkins University Press, Baltimore

5 Arguments

1:   JOB – CHARACTER(1)Input
On entry: indicates whether eigenvectors are computed.
JOB='N'
Only eigenvalues are computed.
JOB='V'
Eigenvalues and eigenvectors are computed.
Constraint: JOB='N' or 'V'.
2:   UPLO – CHARACTER(1)Input
On entry: indicates whether the upper or lower triangular part of A is stored.
UPLO='U'
The upper triangular part of A is stored.
UPLO='L'
The lower triangular part of A is stored.
Constraint: UPLO='U' or 'L'.
3:   N – INTEGERInput
On entry: n, the order of the matrix A.
Constraint: N≥0.
4:   AP* – COMPLEX (KIND=nag_wp) arrayInput/Output
Note: the dimension of the array AP must be at least max 1,N×N+1/2.
On entry: the upper or lower triangle of the n by n Hermitian matrix A, packed by columns.
More precisely,
  • if UPLO='U', the upper triangle of A must be stored with element A ij in AP i+j j-1/2 for i≤j;
  • if UPLO='L', the lower triangle of A must be stored with element A ij in AP i+2 n-jj-1/2 for i≥j.
On exit: AP is overwritten by the values generated during the reduction to tridiagonal form. The elements of the diagonal and the off-diagonal of the tridiagonal matrix overwrite the corresponding elements of A.
5:   W* – REAL (KIND=nag_wp) arrayOutput
Note: the dimension of the array W must be at least max 1,N.
On exit: the eigenvalues of the matrix A in ascending order.
6:   Z LDZ* – COMPLEX (KIND=nag_wp) arrayOutput
Note: the second dimension of the array Z must be at least max 1,N if JOB='V' and at least 1 if JOB='N'.
On exit: if JOB='V', Z is overwritten by the unitary matrix Z which contains the eigenvectors of A.
If JOB='N', Z is not referenced.
7:   LDZ – INTEGERInput
On entry: the first dimension of the array Z as declared in the (sub)program from which F08GQF (ZHPEVD) is called.
Constraints:
  • if JOB='V', LDZ≥ max 1,N ;
  • if JOB='N', LDZ≥1.
8:   WORK max 1,LWORK – COMPLEX (KIND=nag_wp) arrayWorkspace
On exit: if INFO=0, WORK 1 contains the required minimal size of LWORK.
9:   LWORK – INTEGERInput
On entry: the dimension of the array WORK as declared in the (sub)program from which F08GQF (ZHPEVD) is called.
If LWORK=-1, a workspace query is assumed; the routine only calculates the minimum dimension of the WORK array, returns this value as the first entry of the WORK array, and no error message related to LWORK is issued.
Constraints:
  • if N≤1, LWORK≥1 or LWORK=-1;
  • if JOB='N' and N>1, LWORK≥N or LWORK=-1;
  • if JOB='V' and N>1, LWORK≥2×N or LWORK=-1.
10:   RWORK max 1,LRWORK – REAL (KIND=nag_wp) arrayWorkspace
On exit: if INFO=0, RWORK 1 contains the required minimal size of LRWORK.
11:   LRWORK – INTEGERInput
On entry: the dimension of the array RWORK as declared in the (sub)program from which F08GQF (ZHPEVD) is called.
If LRWORK=-1, a workspace query is assumed; the routine only calculates the minimum dimension of the RWORK array, returns this value as the first entry of the RWORK array, and no error message related to LRWORK is issued.
Constraints:
  • if N≤1, LRWORK≥1 or LRWORK=-1;
  • if JOB='N' and N>1, LRWORK≥N or LRWORK=-1;
  • if JOB='V' and N>1, LRWORK≥2×N 2+5×N+1 or LRWORK=-1.
12:   IWORK max 1,LIWORK – INTEGER arrayWorkspace
On exit: if INFO=0, IWORK 1 contains the required minimal size of LIWORK.
13:   LIWORK – INTEGERInput
On entry: the dimension of the array IWORK as declared in the (sub)program from which F08GQF (ZHPEVD) is called.
If LIWORK=-1, a workspace query is assumed; the routine only calculates the minimum dimension of the IWORK array, returns this value as the first entry of the IWORK array, and no error message related to LIWORK is issued.
Constraints:
  • if JOB='N' or N≤1, LIWORK≥1 or LIWORK=-1;
  • if JOB='V' and N>1, LIWORK≥5×N+3 or LIWORK=-1.
14:   INFO – INTEGEROutput
On exit: INFO=0 unless the routine detects an error (see Section 6).

6 Error Indicators and Warnings

INFO<0
If INFO=-i, argument i had an illegal value. An explanatory message is output, and execution of the program is terminated.
INFO>0
if INFO=i and JOB='N', the algorithm failed to converge; i elements of an intermediate tridiagonal form did not converge to zero; if INFO=i and JOB='V', then the algorithm failed to compute an eigenvalue while working on the submatrix lying in rows and column i/N+1 through i mod N+1.

7 Accuracy

The computed eigenvalues and eigenvectors are exact for a nearby matrix A+E, where
E 2 = O ε A 2 ,
and ε is the machine precision. See Section 4.7 of Anderson et al. (1999) for further details.

8 Parallelism and Performance

F08GQF (ZHPEVD) is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
F08GQF (ZHPEVD) makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The real analogue of this routine is F08GCF (DSPEVD).

10 Example

This example computes all the eigenvalues and eigenvectors of the Hermitian matrix A, where
A = 1.0+0.0 i 2.0-1.0 i 3.0-1.0 i 4.0-1.0 i 2.0+1.0 i 2.0+0.0 i 3.0-2.0 i 4.0-2.0 i 3.0+1.0 i 3.0+2.0 i 3.0+0.0 i 4.0-3.0 i 4.0+1.0 i 4.0+2.0 i 4.0+3.0 i 4.0+0.0 i .

10.1 Program Text

Program Text (f08gqfe.f90)

10.2 Program Data

Program Data (f08gqfe.d)

10.3 Program Results

Program Results (f08gqfe.r)

F08 Chapter Contents
F08 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F08GSF (ZHPTRD) : NAG Library, Mark 26

F08 Chapter Contents
F08 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F08GSF (ZHPTRD)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F08GSF (ZHPTRD) reduces a complex Hermitian matrix to tridiagonal form, using packed storage.

2 Specification

SUBROUTINE F08GSF ( UPLO, N, AP, D, E, TAU, INFO)
INTEGER | N, INFO
REAL (KIND=nag_wp) | D(N), E(N-1)
COMPLEX (KIND=nag_wp) | AP(*), TAU(N-1)
CHARACTER(1) | UPLO
The routine may be called by its LAPACK name zhptrd.

3 Description

F08GSF (ZHPTRD) reduces a complex Hermitian matrix A, held in packed storage, to real symmetric tridiagonal form T by a unitary similarity transformation: A=QT QH.
The matrix Q is not formed explicitly but is represented as a product of n-1 elementary reflectors (see the F08 Chapter Introduction for details). Routines are provided to work with Q in this representation (see Section 9).

4 References

Golub G H and Van Loan C F (1996) Matrix Computations (3rd Edition) Johns Hopkins University Press, Baltimore

5 Arguments

1:   UPLO – CHARACTER(1)Input
On entry: indicates whether the upper or lower triangular part of A is stored.
UPLO='U'
The upper triangular part of A is stored.
UPLO='L'
The lower triangular part of A is stored.
Constraint: UPLO='U' or 'L'.
2:   N – INTEGERInput
On entry: n, the order of the matrix A.
Constraint: N≥0.
3:   AP* – COMPLEX (KIND=nag_wp) arrayInput/Output
Note: the dimension of the array AP must be at least max 1,N×N+1/2.
On entry: the upper or lower triangle of the n by n Hermitian matrix A, packed by columns.
More precisely,
  • if UPLO='U', the upper triangle of A must be stored with element A ij in AP i+j j-1/2 for i≤j;
  • if UPLO='L', the lower triangle of A must be stored with element A ij in AP i+2 n-jj-1/2 for i≥j.
On exit: AP is overwritten by the tridiagonal matrix T and details of the unitary matrix Q.
4:   D N – REAL (KIND=nag_wp) arrayOutput
On exit: the diagonal elements of the tridiagonal matrix T.
5:   E N-1 – REAL (KIND=nag_wp) arrayOutput
On exit: the off-diagonal elements of the tridiagonal matrix T.
6:   TAU N-1 – COMPLEX (KIND=nag_wp) arrayOutput
On exit: further details of the unitary matrix Q.
7:   INFO – INTEGEROutput
On exit: INFO=0 unless the routine detects an error (see Section 6).

6 Error Indicators and Warnings

INFO<0
If INFO=-i, argument i had an illegal value. An explanatory message is output, and execution of the program is terminated.

7 Accuracy

The computed tridiagonal matrix T is exactly similar to a nearby matrix A+E, where
E 2≤ c n ε A 2 ,
c n is a modestly increasing function of n, and ε is the machine precision.
The elements of T themselves may be sensitive to small perturbations in A or to rounding errors in the computation, but this does not affect the stability of the eigenvalues and eigenvectors.

8 Parallelism and Performance

F08GSF (ZHPTRD) makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The total number of real floating-point operations is approximately 163 n 3 .
To form the unitary matrix Q F08GSF (ZHPTRD) may be followed by a call to F08GTF (ZUPGTR):
CALL ZUPGTR(UPLO,N,AP,TAU,Q,LDQ,WORK,INFO)
To apply Q to an n by p complex matrix C F08GSF (ZHPTRD) may be followed by a call to F08GUF (ZUPMTR). For example,
CALL ZUPMTR('Left',UPLO,'No Transpose',N,P,AP,TAU,C,LDC,WORK, &
              INFO)
forms the matrix product QC.
The real analogue of this routine is F08GEF (DSPTRD).

10 Example

This example reduces the matrix A to tridiagonal form, where
A = -2.28+0.00 i 1.78-2.03 i 2.26+0.10 i -0.12+2.53 i 1.78+2.03 i -1.12+0.00 i 0.01+0.43 i -1.07+0.86 i 2.26-0.10 i 0.01-0.43 i -0.37+0.00 i 2.31-0.92 i -0.12-2.53 i -1.07-0.86 i 2.31+0.92 i -0.73+0.00 i ,
using packed storage.

10.1 Program Text

Program Text (f08gsfe.f90)

10.2 Program Data

Program Data (f08gsfe.d)

10.3 Program Results

Program Results (f08gsfe.r)

F08 Chapter Contents
F08 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F08GTF (ZUPGTR) : NAG Library, Mark 26

F08 Chapter Contents
F08 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F08GTF (ZUPGTR)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F08GTF (ZUPGTR) generates the complex unitary matrix Q, which was determined by F08GSF (ZHPTRD) when reducing a Hermitian matrix to tridiagonal form.

2 Specification

SUBROUTINE F08GTF ( UPLO, N, AP, TAU, Q, LDQ, WORK, INFO)
INTEGER | N, LDQ, INFO
COMPLEX (KIND=nag_wp) | AP(*), TAU(*), Q(LDQ,*), WORK(N-1)
CHARACTER(1) | UPLO
The routine may be called by its LAPACK name zupgtr.

3 Description

F08GTF (ZUPGTR) is intended to be used after a call to F08GSF (ZHPTRD), which reduces a complex Hermitian matrix A to real symmetric tridiagonal form T by a unitary similarity transformation: A=QT QH. F08GSF (ZHPTRD) represents the unitary matrix Q as a product of n-1 elementary reflectors.
This routine may be used to generate Q explicitly as a square matrix.

4 References

Golub G H and Van Loan C F (1996) Matrix Computations (3rd Edition) Johns Hopkins University Press, Baltimore

5 Arguments

1:   UPLO – CHARACTER(1)Input
On entry: this must be the same argument UPLO as supplied to F08GSF (ZHPTRD).
Constraint: UPLO='U' or 'L'.
2:   N – INTEGERInput
On entry: n, the order of the matrix Q.
Constraint: N≥0.
3:   AP* – COMPLEX (KIND=nag_wp) arrayInput
Note: the dimension of the array AP must be at least max 1,N×N+1/2.
On entry: details of the vectors which define the elementary reflectors, as returned by F08GSF (ZHPTRD).
4:   TAU* – COMPLEX (KIND=nag_wp) arrayInput
Note: the dimension of the array TAU must be at least max 1,N-1.
On entry: further details of the elementary reflectors, as returned by F08GSF (ZHPTRD).
5:   Q LDQ* – COMPLEX (KIND=nag_wp) arrayOutput
Note: the second dimension of the array Q must be at least max 1,N.
On exit: the n by n unitary matrix Q.
6:   LDQ – INTEGERInput
On entry: the first dimension of the array Q as declared in the (sub)program from which F08GTF (ZUPGTR) is called.
Constraint: LDQ≥max 1,N.
7:   WORK N-1 – COMPLEX (KIND=nag_wp) arrayWorkspace
8:   INFO – INTEGEROutput
On exit: INFO=0 unless the routine detects an error (see Section 6).

6 Error Indicators and Warnings

INFO<0
If INFO=-i, argument i had an illegal value. An explanatory message is output, and execution of the program is terminated.

7 Accuracy

The computed matrix Q differs from an exactly unitary matrix by a matrix E such that
E 2 = O ε ,
where ε is the machine precision.

8 Parallelism and Performance

F08GTF (ZUPGTR) is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
F08GTF (ZUPGTR) makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The total number of real floating-point operations is approximately 163 n 3.
The real analogue of this routine is F08GFF (DOPGTR).

10 Example

This example computes all the eigenvalues and eigenvectors of the matrix A, where
A = -2.28+0.00 i 1.78-2.03 i 2.26+0.10 i -0.12+2.53 i 1.78+2.03 i -1.12+0.00 i 0.01+0.43 i -1.07+0.86 i 2.26-0.10 i 0.01-0.43 i -0.37+0.00 i 2.31-0.92 i -0.12-2.53 i -1.07-0.86 i 2.31+0.92 i -0.73+0.00 i ,
using packed storage. Here A is Hermitian and must first be reduced to tridiagonal form by F08GSF (ZHPTRD). The program then calls F08GTF (ZUPGTR) to form Q, and passes this matrix to F08JSF (ZSTEQR) which computes the eigenvalues and eigenvectors of A.

10.1 Program Text

Program Text (f08gtfe.f90)

10.2 Program Data

Program Data (f08gtfe.d)

10.3 Program Results

Program Results (f08gtfe.r)

F08 Chapter Contents
F08 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F08GUF (ZUPMTR) : NAG Library, Mark 26

F08 Chapter Contents
F08 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F08GUF (ZUPMTR)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F08GUF (ZUPMTR) multiplies an arbitrary complex matrix C by the complex unitary matrix Q which was determined by F08GSF (ZHPTRD) when reducing a complex Hermitian matrix to tridiagonal form.

2 Specification

SUBROUTINE F08GUF ( SIDE, UPLO, TRANS, M, N, AP, TAU, C, LDC, WORK, INFO)
INTEGER | M, N, LDC, INFO
COMPLEX (KIND=nag_wp) | AP(*), TAU(*), C(LDC,*), WORK(*)
CHARACTER(1) | SIDE, UPLO, TRANS
The routine may be called by its LAPACK name zupmtr.

3 Description

F08GUF (ZUPMTR) is intended to be used after a call to F08GSF (ZHPTRD), which reduces a complex Hermitian matrix A to real symmetric tridiagonal form T by a unitary similarity transformation: A=QT QH. F08GSF (ZHPTRD) represents the unitary matrix Q as a product of elementary reflectors.
This routine may be used to form one of the matrix products
QC , QH C , CQ ​ or ​ C QH ,
overwriting the result on C (which may be any complex rectangular matrix).
A common application of this routine is to transform a matrix Z of eigenvectors of T to the matrix QZ of eigenvectors of A.

4 References

Golub G H and Van Loan C F (1996) Matrix Computations (3rd Edition) Johns Hopkins University Press, Baltimore

5 Arguments

1:   SIDE – CHARACTER(1)Input
On entry: indicates how Q or QH is to be applied to C.
SIDE='L'
Q or QH is applied to C from the left.
SIDE='R'
Q or QH is applied to C from the right.
Constraint: SIDE='L' or 'R'.
2:   UPLO – CHARACTER(1)Input
On entry: this must be the same argument UPLO as supplied to F08GSF (ZHPTRD).
Constraint: UPLO='U' or 'L'.
3:   TRANS – CHARACTER(1)Input
On entry: indicates whether Q or QH is to be applied to C.
TRANS='N'
Q is applied to C.
TRANS='C'
QH is applied to C.
Constraint: TRANS='N' or 'C'.
4:   M – INTEGERInput
On entry: m, the number of rows of the matrix C; m is also the order of Q if SIDE='L'.
Constraint: M≥0.
5:   N – INTEGERInput
On entry: n, the number of columns of the matrix C; n is also the order of Q if SIDE='R'.
Constraint: N≥0.
6:   AP* – COMPLEX (KIND=nag_wp) arrayInput/Output
Note: the dimension of the array AP must be at least max 1, M × M+1 / 2 if SIDE='L' and at least max 1, N × N+1 / 2 if SIDE='R'.
On entry: details of the vectors which define the elementary reflectors, as returned by F08GSF (ZHPTRD).
On exit: is used as internal workspace prior to being restored and hence is unchanged.
7:   TAU* – COMPLEX (KIND=nag_wp) arrayInput
Note: the dimension of the array TAU must be at least max 1,M-1 if SIDE='L' and at least max 1,N-1 if SIDE='R'.
On entry: further details of the elementary reflectors, as returned by F08GSF (ZHPTRD).
8:   C LDC* – COMPLEX (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array C must be at least max 1,N.
On entry: the m by n matrix C.
On exit: C is overwritten by QC or QH C or CQ or C QH as specified by SIDE and TRANS.
9:   LDC – INTEGERInput
On entry: the first dimension of the array C as declared in the (sub)program from which F08GUF (ZUPMTR) is called.
Constraint: LDC≥max 1,M.
10:   WORK* – COMPLEX (KIND=nag_wp) arrayWorkspace
Note: the dimension of the array WORK must be at least max 1,N if SIDE='L' and at least max 1,M if SIDE='R'.
11:   INFO – INTEGEROutput
On exit: INFO=0 unless the routine detects an error (see Section 6).

6 Error Indicators and Warnings

INFO<0
If INFO=-i, argument i had an illegal value. An explanatory message is output, and execution of the program is terminated.

7 Accuracy

The computed result differs from the exact result by a matrix E such that
E 2 = O ε C 2 ,
where ε is the machine precision.

8 Parallelism and Performance

F08GUF (ZUPMTR) makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The total number of real floating-point operations is approximately 8 m 2 n if SIDE='L' and 8 m n 2 if SIDE='R'.
The real analogue of this routine is F08GGF (DOPMTR).

10 Example

This example computes the two smallest eigenvalues, and the associated eigenvectors, of the matrix A, where
A = -2.28+0.00 i 1.78-2.03 i 2.26+0.10 i -0.12+2.53 i 1.78+2.03 i -1.12+0.00 i 0.01+0.43 i -1.07+0.86 i 2.26-0.10 i 0.01-0.43 i -0.37+0.00 i 2.31-0.92 i -0.12-2.53 i -1.07-0.86 i 2.31+0.92 i -0.73+0.00 i ,
using packed storage. Here A is Hermitian and must first be reduced to tridiagonal form T by F08GSF (ZHPTRD). The program then calls F08JJF (DSTEBZ) to compute the requested eigenvalues and F08JXF (ZSTEIN) to compute the associated eigenvectors of T. Finally F08GUF (ZUPMTR) is called to transform the eigenvectors to those of A.

10.1 Program Text

Program Text (f08gufe.f90)

10.2 Program Data

Program Data (f08gufe.d)

10.3 Program Results

Program Results (f08gufe.r)

F08 Chapter Contents
F08 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F08HAF (DSBEV) : NAG Library, Mark 26

F08 Chapter Contents
F08 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F08HAF (DSBEV)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F08HAF (DSBEV) computes all the eigenvalues and, optionally, all the eigenvectors of a real n by n symmetric band matrix A of bandwidth 2 kd+1 .

2 Specification

SUBROUTINE F08HAF ( JOBZ, UPLO, N, KD, AB, LDAB, W, Z, LDZ, WORK, INFO)
INTEGER | N, KD, LDAB, LDZ, INFO
REAL (KIND=nag_wp) | AB(LDAB,*), W(N), Z(LDZ,*), WORK(3*N-2)
CHARACTER(1) | JOBZ, UPLO
The routine may be called by its LAPACK name dsbev.

3 Description

The symmetric band matrix A is first reduced to tridiagonal form, using orthogonal similarity transformations, and then the QR algorithm is applied to the tridiagonal matrix to compute the eigenvalues and (optionally) the eigenvectors.

4 References

Anderson E, Bai Z, Bischof C, Blackford S, Demmel J, Dongarra J J, Du Croz J J, Greenbaum A, Hammarling S, McKenney A and Sorensen D (1999) LAPACK Users' Guide (3rd Edition) SIAM, Philadelphia http://www.netlib.org/lapack/lug
Golub G H and Van Loan C F (1996) Matrix Computations (3rd Edition) Johns Hopkins University Press, Baltimore

5 Arguments

1:   JOBZ – CHARACTER(1)Input
On entry: indicates whether eigenvectors are computed.
JOBZ='N'
Only eigenvalues are computed.
JOBZ='V'
Eigenvalues and eigenvectors are computed.
Constraint: JOBZ='N' or 'V'.
2:   UPLO – CHARACTER(1)Input
On entry: if UPLO='U', the upper triangular part of A is stored.
If UPLO='L', the lower triangular part of A is stored.
Constraint: UPLO='U' or 'L'.
3:   N – INTEGERInput
On entry: n, the order of the matrix A.
Constraint: N≥0.
4:   KD – INTEGERInput
On entry: if UPLO='U', the number of superdiagonals, kd, of the matrix A.
If UPLO='L', the number of subdiagonals, kd, of the matrix A.
Constraint: KD≥0.
5:   AB LDAB* – REAL (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array AB must be at least max 1,N.
On entry: the upper or lower triangle of the n by n symmetric band matrix A.
The matrix is stored in rows 1 to kd+1, more precisely,
  • if UPLO='U', the elements of the upper triangle of A within the band must be stored with element A ij in AB kd+1+i-j j​ for ​max 1,j-kd≤i≤j;
  • if UPLO='L', the elements of the lower triangle of A within the band must be stored with element A ij in AB 1+i-j j​ for ​j≤i≤min n,j+kd.
On exit: AB is overwritten by values generated during the reduction to tridiagonal form.
The first superdiagonal or subdiagonal and the diagonal of the tridiagonal matrix T are returned in AB using the same storage format as described above.
6:   LDAB – INTEGERInput
On entry: the first dimension of the array AB as declared in the (sub)program from which F08HAF (DSBEV) is called.
Constraint: LDAB≥KD+1.
7:   W N – REAL (KIND=nag_wp) arrayOutput
On exit: the eigenvalues in ascending order.
8:   Z LDZ* – REAL (KIND=nag_wp) arrayOutput
Note: the second dimension of the array Z must be at least max 1,N if JOBZ='V', and at least 1 otherwise.
On exit: if JOBZ='V', Z contains the orthonormal eigenvectors of the matrix A, with the ith column of Z holding the eigenvector associated with W i.
If JOBZ='N', Z is not referenced.
9:   LDZ – INTEGERInput
On entry: the first dimension of the array Z as declared in the (sub)program from which F08HAF (DSBEV) is called.
Constraints:
  • if JOBZ='V', LDZ≥ max 1,N ;
  • otherwise LDZ≥1.
10:   WORK 3×N-2 – REAL (KIND=nag_wp) arrayWorkspace
11:   INFO – INTEGEROutput
On exit: INFO=0 unless the routine detects an error (see Section 6).

6 Error Indicators and Warnings

INFO<0
If INFO=-i, argument i had an illegal value. An explanatory message is output, and execution of the program is terminated.
INFO>0
If INFO=i, the algorithm failed to converge; i off-diagonal elements of an intermediate tridiagonal form did not converge to zero.

7 Accuracy

The computed eigenvalues and eigenvectors are exact for a nearby matrix A+E, where
E 2 = O ε A 2 ,
and ε is the machine precision. See Section 4.7 of Anderson et al. (1999) for further details.

8 Parallelism and Performance

F08HAF (DSBEV) is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
F08HAF (DSBEV) makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The total number of floating-point operations is proportional to n 3 if JOBZ='V' and is proportional to kd n 2 otherwise.
The complex analogue of this routine is F08HNF (ZHBEV).

10 Example

This example finds all the eigenvalues and eigenvectors of the symmetric band matrix
A = 1 2 3 0 0 2 2 3 4 0 3 3 3 4 5 0 4 4 4 5 0 0 5 5 5 ,
together with approximate error bounds for the computed eigenvalues and eigenvectors.

10.1 Program Text

Program Text (f08hafe.f90)

10.2 Program Data

Program Data (f08hafe.d)

10.3 Program Results

Program Results (f08hafe.r)

F08 Chapter Contents
F08 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F08HBF (DSBEVX) : NAG Library, Mark 26

F08 Chapter Contents
F08 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F08HBF (DSBEVX)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F08HBF (DSBEVX) computes selected eigenvalues and, optionally, eigenvectors of a real n by n symmetric band matrix A of bandwidth 2 kd+1 . Eigenvalues and eigenvectors can be selected by specifying either a range of values or a range of indices for the desired eigenvalues.

2 Specification

SUBROUTINE F08HBF ( JOBZ, RANGE, UPLO, N, KD, AB, LDAB, Q, LDQ, VL, VU, IL, IU, ABSTOL, M, W, Z, LDZ, WORK, IWORK, JFAIL, INFO)
INTEGER | N, KD, LDAB, LDQ, IL, IU, M, LDZ, IWORK(5*N), JFAIL(*), INFO
REAL (KIND=nag_wp) | AB(LDAB,*), Q(LDQ,*), VL, VU, ABSTOL, W(N), Z(LDZ,*), WORK(7*N)
CHARACTER(1) | JOBZ, RANGE, UPLO
The routine may be called by its LAPACK name dsbevx.

3 Description

The symmetric band matrix A is first reduced to tridiagonal form, using orthogonal similarity transformations. The required eigenvalues and eigenvectors are then computed from the tridiagonal matrix; the method used depends upon whether all, or selected, eigenvalues and eigenvectors are required.

4 References

Anderson E, Bai Z, Bischof C, Blackford S, Demmel J, Dongarra J J, Du Croz J J, Greenbaum A, Hammarling S, McKenney A and Sorensen D (1999) LAPACK Users' Guide (3rd Edition) SIAM, Philadelphia http://www.netlib.org/lapack/lug
Demmel J W and Kahan W (1990) Accurate singular values of bidiagonal matrices SIAM J. Sci. Statist. Comput. 11 873–912
Golub G H and Van Loan C F (1996) Matrix Computations (3rd Edition) Johns Hopkins University Press, Baltimore

5 Arguments

1:   JOBZ – CHARACTER(1)Input
On entry: indicates whether eigenvectors are computed.
JOBZ='N'
Only eigenvalues are computed.
JOBZ='V'
Eigenvalues and eigenvectors are computed.
Constraint: JOBZ='N' or 'V'.
2:   RANGE – CHARACTER(1)Input
On entry: if RANGE='A', all eigenvalues will be found.
If RANGE='V', all eigenvalues in the half-open interval VL,VU will be found.
If RANGE='I', the ILth to IUth eigenvalues will be found.
Constraint: RANGE='A', 'V' or 'I'.
3:   UPLO – CHARACTER(1)Input
On entry: if UPLO='U', the upper triangular part of A is stored.
If UPLO='L', the lower triangular part of A is stored.
Constraint: UPLO='U' or 'L'.
4:   N – INTEGERInput
On entry: n, the order of the matrix A.
Constraint: N≥0.
5:   KD – INTEGERInput
On entry: if UPLO='U', the number of superdiagonals, kd, of the matrix A.
If UPLO='L', the number of subdiagonals, kd, of the matrix A.
Constraint: KD≥0.
6:   AB LDAB* – REAL (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array AB must be at least max 1,N.
On entry: the upper or lower triangle of the n by n symmetric band matrix A.
The matrix is stored in rows 1 to kd+1, more precisely,
  • if UPLO='U', the elements of the upper triangle of A within the band must be stored with element A ij in AB kd+1+i-j j​ for ​max 1,j-kd≤i≤j;
  • if UPLO='L', the elements of the lower triangle of A within the band must be stored with element A ij in AB 1+i-j j​ for ​j≤i≤min n,j+kd.
On exit: AB is overwritten by values generated during the reduction to tridiagonal form.
The first superdiagonal or subdiagonal and the diagonal of the tridiagonal matrix T are returned in AB using the same storage format as described above.
7:   LDAB – INTEGERInput
On entry: the first dimension of the array AB as declared in the (sub)program from which F08HBF (DSBEVX) is called.
Constraint: LDAB≥KD+1.
8:   Q LDQ* – REAL (KIND=nag_wp) arrayOutput
Note: the second dimension of the array Q must be at least max 1,N if JOBZ='V', and at least 1 otherwise.
On exit: if JOBZ='V', the n by n orthogonal matrix used in the reduction to tridiagonal form.
If JOBZ='N', Q is not referenced.
9:   LDQ – INTEGERInput
On entry: the first dimension of the array Q as declared in the (sub)program from which F08HBF (DSBEVX) is called.
Constraints:
  • if JOBZ='V', LDQ≥ max 1,N ;
  • otherwise LDQ≥1.
10:   VL – REAL (KIND=nag_wp)Input
11:   VU – REAL (KIND=nag_wp)Input
On entry: if RANGE='V', the lower and upper bounds of the interval to be searched for eigenvalues.
If RANGE='A' or 'I', VL and VU are not referenced.
Constraint: if RANGE='V', VL<VU.
12:   IL – INTEGERInput
13:   IU – INTEGERInput
On entry: if RANGE='I', the indices (in ascending order) of the smallest and largest eigenvalues to be returned.
If RANGE='A' or 'V', IL and IU are not referenced.
Constraints:
  • if RANGE='I' and N=0, IL=1 and IU=0;
  • if RANGE='I' and N>0, 1≤ IL≤ IU≤ N .
14:   ABSTOL – REAL (KIND=nag_wp)Input
On entry: the absolute error tolerance for the eigenvalues. An approximate eigenvalue is accepted as converged when it is determined to lie in an interval a,b of width less than or equal to
ABSTOL+ε max a,b ,
where ε is the machine precision. If ABSTOL is less than or equal to zero, then ε T 1 will be used in its place, where T is the tridiagonal matrix obtained by reducing A to tridiagonal form. Eigenvalues will be computed most accurately when ABSTOL is set to twice the underflow threshold 2 × X02AMF , not zero. If this routine returns with INFO>0, indicating that some eigenvectors did not converge, try setting ABSTOL to 2 × X02AMF . See Demmel and Kahan (1990).
15:   M – INTEGEROutput
On exit: the total number of eigenvalues found. 0≤M≤N.
If RANGE='A', M=N.
If RANGE='I', M=IU-IL+1.
16:   W N – REAL (KIND=nag_wp) arrayOutput
On exit: the first M elements contain the selected eigenvalues in ascending order.
17:   Z LDZ* – REAL (KIND=nag_wp) arrayOutput
Note: the second dimension of the array Z must be at least max 1,M if JOBZ='V', and at least 1 otherwise.
On exit: if JOBZ='V', then
  • if INFO=0, the first M columns of Z contain the orthonormal eigenvectors of the matrix A corresponding to the selected eigenvalues, with the ith column of Z holding the eigenvector associated with W i;
  • if an eigenvector fails to converge (INFO>0), then that column of Z contains the latest approximation to the eigenvector, and the index of the eigenvector is returned in JFAIL.
If JOBZ='N', Z is not referenced.
Note: you must ensure that at least max 1,M columns are supplied in the array Z; if RANGE='V', the exact value of M is not known in advance and an upper bound of at least N must be used.
18:   LDZ – INTEGERInput
On entry: the first dimension of the array Z as declared in the (sub)program from which F08HBF (DSBEVX) is called.
Constraints:
  • if JOBZ='V', LDZ≥ max 1,N ;
  • otherwise LDZ≥1.
19:   WORK 7×N – REAL (KIND=nag_wp) arrayWorkspace
20:   IWORK 5×N – INTEGER arrayWorkspace
21:   JFAIL* – INTEGER arrayOutput
Note: the dimension of the array JFAIL must be at least max 1,N.
On exit: if JOBZ='V', then
  • if INFO=0, the first M elements of JFAIL are zero;
  • if INFO>0, JFAIL contains the indices of the eigenvectors that failed to converge.
If JOBZ='N', JFAIL is not referenced.
22:   INFO – INTEGEROutput
On exit: INFO=0 unless the routine detects an error (see Section 6).

6 Error Indicators and Warnings

INFO<0
If INFO=-i, argument i had an illegal value. An explanatory message is output, and execution of the program is terminated.
INFO>0
If INFO=i, then i eigenvectors failed to converge. Their indices are stored in array JFAIL. Please see ABSTOL.

7 Accuracy

The computed eigenvalues and eigenvectors are exact for a nearby matrix A+E, where
E 2 = O ε A 2 ,
and ε is the machine precision. See Section 4.7 of Anderson et al. (1999) for further details.

8 Parallelism and Performance

F08HBF (DSBEVX) is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
F08HBF (DSBEVX) makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The total number of floating-point operations is proportional to kd n 2 if JOBZ='N', and is proportional to n 3 if JOBZ='V' and RANGE='A', otherwise the number of floating-point operations will depend upon the number of computed eigenvectors.
The complex analogue of this routine is F08HPF (ZHBEVX).

10 Example

This example finds the eigenvalues in the half-open interval -3,3 , and the corresponding eigenvectors, of the symmetric band matrix
A = 1 2 3 0 0 2 2 3 4 0 3 3 3 4 5 0 4 4 4 5 0 0 5 5 5 .

10.1 Program Text

Program Text (f08hbfe.f90)

10.2 Program Data

Program Data (f08hbfe.d)

10.3 Program Results

Program Results (f08hbfe.r)

F08 Chapter Contents
F08 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F08HCF (DSBEVD) : NAG Library, Mark 26

F08 Chapter Contents
F08 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F08HCF (DSBEVD)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.
Warning. The specification of the arguments LWORK and LIWORK changed at Mark 20 in the case where JOB='V' and N>1: the minimum dimension of the array WORK has been reduced whereas the minimum dimension of the array IWORK has been increased.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F08HCF (DSBEVD) computes all the eigenvalues and, optionally, all the eigenvectors of a real symmetric band matrix. If the eigenvectors are requested, then it uses a divide-and-conquer algorithm to compute eigenvalues and eigenvectors. However, if only eigenvalues are required, then it uses the Pal–Walker–Kahan variant of the QL or QR algorithm.

2 Specification

SUBROUTINE F08HCF ( JOB, UPLO, N, KD, AB, LDAB, W, Z, LDZ, WORK, LWORK, IWORK, LIWORK, INFO)
INTEGER | N, KD, LDAB, LDZ, LWORK, IWORK(max(1,LIWORK)), LIWORK, INFO
REAL (KIND=nag_wp) | AB(LDAB,*), W(*), Z(LDZ,*), WORK(max(1,LWORK))
CHARACTER(1) | JOB, UPLO
The routine may be called by its LAPACK name dsbevd.

3 Description

F08HCF (DSBEVD) computes all the eigenvalues and, optionally, all the eigenvectors of a real symmetric band matrix A. In other words, it can compute the spectral factorization of A as
A=ZΛ ZT,
where Λ is a diagonal matrix whose diagonal elements are the eigenvalues λi, and Z is the orthogonal matrix whose columns are the eigenvectors zi. Thus
A zi=λizi,  i=1,2,…,n.

4 References

Anderson E, Bai Z, Bischof C, Blackford S, Demmel J, Dongarra J J, Du Croz J J, Greenbaum A, Hammarling S, McKenney A and Sorensen D (1999) LAPACK Users' Guide (3rd Edition) SIAM, Philadelphia http://www.netlib.org/lapack/lug
Golub G H and Van Loan C F (1996) Matrix Computations (3rd Edition) Johns Hopkins University Press, Baltimore

5 Arguments

1:   JOB – CHARACTER(1)Input
On entry: indicates whether eigenvectors are computed.
JOB='N'
Only eigenvalues are computed.
JOB='V'
Eigenvalues and eigenvectors are computed.
Constraint: JOB='N' or 'V'.
2:   UPLO – CHARACTER(1)Input
On entry: indicates whether the upper or lower triangular part of A is stored.
UPLO='U'
The upper triangular part of A is stored.
UPLO='L'
The lower triangular part of A is stored.
Constraint: UPLO='U' or 'L'.
3:   N – INTEGERInput
On entry: n, the order of the matrix A.
Constraint: N≥0.
4:   KD – INTEGERInput
On entry: if UPLO='U', the number of superdiagonals, kd, of the matrix A.
If UPLO='L', the number of subdiagonals, kd, of the matrix A.
Constraint: KD≥0.
5:   AB LDAB* – REAL (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array AB must be at least max 1,N.
On entry: the upper or lower triangle of the n by n symmetric band matrix A.
The matrix is stored in rows 1 to kd+1, more precisely,
  • if UPLO='U', the elements of the upper triangle of A within the band must be stored with element A ij in AB kd+1+i-j j​ for ​max 1,j-kd≤i≤j;
  • if UPLO='L', the elements of the lower triangle of A within the band must be stored with element A ij in AB 1+i-j j​ for ​j≤i≤min n,j+kd.
On exit: AB is overwritten by values generated during the reduction to tridiagonal form.
The first superdiagonal or subdiagonal and the diagonal of the tridiagonal matrix T are returned in AB using the same storage format as described above.
6:   LDAB – INTEGERInput
On entry: the first dimension of the array AB as declared in the (sub)program from which F08HCF (DSBEVD) is called.
Constraint: LDAB≥KD+1.
7:   W* – REAL (KIND=nag_wp) arrayOutput
Note: the dimension of the array W must be at least max 1,N.
On exit: the eigenvalues of the matrix A in ascending order.
8:   Z LDZ* – REAL (KIND=nag_wp) arrayOutput
Note: the second dimension of the array Z must be at least max 1,N if JOB='V' and at least 1 if JOB='N'.
On exit: if JOB='V', Z is overwritten by the orthogonal matrix Z which contains the eigenvectors of A. The ith column of Z contains the eigenvector which corresponds to the eigenvalue W i.
If JOB='N', Z is not referenced.
9:   LDZ – INTEGERInput
On entry: the first dimension of the array Z as declared in the (sub)program from which F08HCF (DSBEVD) is called.
Constraints:
  • if JOB='V', LDZ≥ max 1,N ;
  • if JOB='N', LDZ≥1.
10:   WORK max 1,LWORK – REAL (KIND=nag_wp) arrayWorkspace
On exit: if INFO=0, WORK 1 contains the required minimal size of LWORK.
11:   LWORK – INTEGERInput
On entry: the dimension of the array WORK as declared in the (sub)program from which F08HCF (DSBEVD) is called.
If LWORK=-1, a workspace query is assumed; the routine only calculates the minimum dimension of the WORK array, returns this value as the first entry of the WORK array, and no error message related to LWORK is issued.
Constraints:
  • if N≤1, LWORK≥1 or LWORK=-1;
  • if JOB='N' and N>1, LWORK≥2×N or LWORK=-1;
  • if JOB='V' and N>1, LWORK≥2×N 2+5×N+1 or LWORK=-1.
12:   IWORK max 1,LIWORK – INTEGER arrayWorkspace
On exit: if INFO=0, IWORK 1 contains the required minimal size of LIWORK.
13:   LIWORK – INTEGERInput
On entry: the dimension of the array IWORK as declared in the (sub)program from which F08HCF (DSBEVD) is called.
If LIWORK=-1, a workspace query is assumed; the routine only calculates the minimum dimension of the IWORK array, returns this value as the first entry of the IWORK array, and no error message related to LIWORK is issued.
Constraints:
  • if JOB='N' or N≤1, LIWORK≥1 or LIWORK=-1;
  • if JOB='V' and N>1, LIWORK≥5×N+3 or LIWORK=-1.
14:   INFO – INTEGEROutput
On exit: INFO=0 unless the routine detects an error (see Section 6).

6 Error Indicators and Warnings

INFO<0
If INFO=-i, argument i had an illegal value. An explanatory message is output, and execution of the program is terminated.
INFO>0
if INFO=i and JOB='N', the algorithm failed to converge; i elements of an intermediate tridiagonal form did not converge to zero; if INFO=i and JOB='V', then the algorithm failed to compute an eigenvalue while working on the submatrix lying in rows and column i/N+1 through i mod N+1.

7 Accuracy

The computed eigenvalues and eigenvectors are exact for a nearby matrix A+E, where
E 2 = O ε A 2 ,
and ε is the machine precision. See Section 4.7 of Anderson et al. (1999) for further details.

8 Parallelism and Performance

F08HCF (DSBEVD) is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
F08HCF (DSBEVD) makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The complex analogue of this routine is F08HQF (ZHBEVD).

10 Example

This example computes all the eigenvalues and eigenvectors of the symmetric band matrix A, where
A = 1 2 3 0 0 2 2 3 4 0 3 3 3 4 5 0 4 4 4 5 0 0 5 5 5 .

10.1 Program Text

Program Text (f08hcfe.f90)

10.2 Program Data

Program Data (f08hcfe.d)

10.3 Program Results

Program Results (f08hcfe.r)

F08 Chapter Contents
F08 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F08HEF (DSBTRD) : NAG Library, Mark 26

F08 Chapter Contents
F08 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F08HEF (DSBTRD)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F08HEF (DSBTRD) reduces a real symmetric band matrix to tridiagonal form.

2 Specification

SUBROUTINE F08HEF ( VECT, UPLO, N, KD, AB, LDAB, D, E, Q, LDQ, WORK, INFO)
INTEGER | N, KD, LDAB, LDQ, INFO
REAL (KIND=nag_wp) | AB(LDAB,*), D(N), E(N-1), Q(LDQ,*), WORK(N)
CHARACTER(1) | VECT, UPLO
The routine may be called by its LAPACK name dsbtrd.

3 Description

F08HEF (DSBTRD) reduces a symmetric band matrix A to symmetric tridiagonal form T by an orthogonal similarity transformation:
T = QT A Q .
The orthogonal matrix Q is determined as a product of Givens rotation matrices, and may be formed explicitly by the routine if required.
The routine uses a vectorizable form of the reduction, due to Kaufman (1984).

4 References

Kaufman L (1984) Banded eigenvalue solvers on vector machines ACM Trans. Math. Software 10 73–86
Parlett B N (1998) The Symmetric Eigenvalue Problem SIAM, Philadelphia

5 Arguments

1:   VECT – CHARACTER(1)Input
On entry: indicates whether Q is to be returned.
VECT='V'
Q is returned.
VECT='U'
Q is updated (and the array Q must contain a matrix on entry).
VECT='N'
Q is not required.
Constraint: VECT='V', 'U' or 'N'.
2:   UPLO – CHARACTER(1)Input
On entry: indicates whether the upper or lower triangular part of A is stored.
UPLO='U'
The upper triangular part of A is stored.
UPLO='L'
The lower triangular part of A is stored.
Constraint: UPLO='U' or 'L'.
3:   N – INTEGERInput
On entry: n, the order of the matrix A.
Constraint: N≥0.
4:   KD – INTEGERInput
On entry: if UPLO='U', the number of superdiagonals, kd, of the matrix A.
If UPLO='L', the number of subdiagonals, kd, of the matrix A.
Constraint: KD≥0.
5:   AB LDAB* – REAL (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array AB must be at least max 1,N.
On entry: the upper or lower triangle of the n by n symmetric band matrix A.
The matrix is stored in rows 1 to kd+1, more precisely,
  • if UPLO='U', the elements of the upper triangle of A within the band must be stored with element A ij in AB kd+1+i-j j​ for ​max 1,j-kd≤i≤j;
  • if UPLO='L', the elements of the lower triangle of A within the band must be stored with element A ij in AB 1+i-j j​ for ​j≤i≤min n,j+kd.
On exit: AB is overwritten by values generated during the reduction to tridiagonal form.
The first superdiagonal or subdiagonal and the diagonal of the tridiagonal matrix T are returned in AB using the same storage format as described above.
6:   LDAB – INTEGERInput
On entry: the first dimension of the array AB as declared in the (sub)program from which F08HEF (DSBTRD) is called.
Constraint: LDAB ≥ max 1,KD+1 .
7:   D N – REAL (KIND=nag_wp) arrayOutput
On exit: the diagonal elements of the tridiagonal matrix T.
8:   E N-1 – REAL (KIND=nag_wp) arrayOutput
On exit: the off-diagonal elements of the tridiagonal matrix T.
9:   Q LDQ* – REAL (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array Q must be at least max 1,N if VECT='V' or 'U' and at least 1 if VECT='N'.
On entry: if VECT='U', Q must contain the matrix formed in a previous stage of the reduction (for example, the reduction of a banded symmetric-definite generalized eigenproblem); otherwise Q need not be set.
On exit: if VECT='V' or 'U', the n by n matrix Q.
If VECT='N', Q is not referenced.
10:   LDQ – INTEGERInput
On entry: the first dimension of the array Q as declared in the (sub)program from which F08HEF (DSBTRD) is called.
Constraints:
  • if VECT='V' or 'U', LDQ≥ max 1,N ;
  • if VECT='N', LDQ≥1.
11:   WORK N – REAL (KIND=nag_wp) arrayWorkspace
12:   INFO – INTEGEROutput
On exit: INFO=0 unless the routine detects an error (see Section 6).

6 Error Indicators and Warnings

INFO<0
If INFO=-i, argument i had an illegal value. An explanatory message is output, and execution of the program is terminated.

7 Accuracy

The computed tridiagonal matrix T is exactly similar to a nearby matrix A+E, where
E 2≤ c n ε A 2 ,
c n is a modestly increasing function of n, and ε is the machine precision.
The elements of T themselves may be sensitive to small perturbations in A or to rounding errors in the computation, but this does not affect the stability of the eigenvalues and eigenvectors.
The computed matrix Q differs from an exactly orthogonal matrix by a matrix E such that
E 2 = O ε ,
where ε is the machine precision.

8 Parallelism and Performance

F08HEF (DSBTRD) is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
F08HEF (DSBTRD) makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The total number of floating-point operations is approximately 6 n 2 k if VECT='N' with 3 n 3 k-1/k additional operations if VECT='V'.
The complex analogue of this routine is F08HSF (ZHBTRD).

10 Example

This example computes all the eigenvalues and eigenvectors of the matrix A, where
A = 4.99 0.04 0.22 0.00 0.04 1.05 -0.79 1.04 0.22 -0.79 -2.31 -1.30 0.00 1.04 -1.30 -0.43 .
Here A is symmetric and is treated as a band matrix. The program first calls F08HEF (DSBTRD) to reduce A to tridiagonal form T, and to form the orthogonal matrix Q; the results are then passed to F08JEF (DSTEQR) which computes the eigenvalues and eigenvectors of A.

10.1 Program Text

Program Text (f08hefe.f90)

10.2 Program Data

Program Data (f08hefe.d)

10.3 Program Results

Program Results (f08hefe.r)

F08 Chapter Contents
F08 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F08HNF (ZHBEV) : NAG Library, Mark 26

F08 Chapter Contents
F08 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F08HNF (ZHBEV)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F08HNF (ZHBEV) computes all the eigenvalues and, optionally, all the eigenvectors of a complex n by n Hermitian band matrix A of bandwidth 2 kd+1 .

2 Specification

SUBROUTINE F08HNF ( JOBZ, UPLO, N, KD, AB, LDAB, W, Z, LDZ, WORK, RWORK, INFO)
INTEGER | N, KD, LDAB, LDZ, INFO
REAL (KIND=nag_wp) | W(N), RWORK(3*N-2)
COMPLEX (KIND=nag_wp) | AB(LDAB,*), Z(LDZ,*), WORK(N)
CHARACTER(1) | JOBZ, UPLO
The routine may be called by its LAPACK name zhbev.

3 Description

The Hermitian band matrix A is first reduced to real tridiagonal form, using unitary similarity transformations, and then the QR algorithm is applied to the tridiagonal matrix to compute the eigenvalues and (optionally) the eigenvectors.

4 References

Anderson E, Bai Z, Bischof C, Blackford S, Demmel J, Dongarra J J, Du Croz J J, Greenbaum A, Hammarling S, McKenney A and Sorensen D (1999) LAPACK Users' Guide (3rd Edition) SIAM, Philadelphia http://www.netlib.org/lapack/lug
Golub G H and Van Loan C F (1996) Matrix Computations (3rd Edition) Johns Hopkins University Press, Baltimore

5 Arguments

1:   JOBZ – CHARACTER(1)Input
On entry: indicates whether eigenvectors are computed.
JOBZ='N'
Only eigenvalues are computed.
JOBZ='V'
Eigenvalues and eigenvectors are computed.
Constraint: JOBZ='N' or 'V'.
2:   UPLO – CHARACTER(1)Input
On entry: if UPLO='U', the upper triangular part of A is stored.
If UPLO='L', the lower triangular part of A is stored.
Constraint: UPLO='U' or 'L'.
3:   N – INTEGERInput
On entry: n, the order of the matrix A.
Constraint: N≥0.
4:   KD – INTEGERInput
On entry: if UPLO='U', the number of superdiagonals, kd, of the matrix A.
If UPLO='L', the number of subdiagonals, kd, of the matrix A.
Constraint: KD≥0.
5:   AB LDAB* – COMPLEX (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array AB must be at least max 1,N.
On entry: the upper or lower triangle of the n by n Hermitian band matrix A.
The matrix is stored in rows 1 to kd+1, more precisely,
  • if UPLO='U', the elements of the upper triangle of A within the band must be stored with element A ij in AB kd+1+i-j j​ for ​max 1,j-kd≤i≤j;
  • if UPLO='L', the elements of the lower triangle of A within the band must be stored with element A ij in AB 1+i-j j​ for ​j≤i≤min n,j+kd.
On exit: AB is overwritten by values generated during the reduction to tridiagonal form.
The first superdiagonal or subdiagonal and the diagonal of the tridiagonal matrix T are returned in AB using the same storage format as described above.
6:   LDAB – INTEGERInput
On entry: the first dimension of the array AB as declared in the (sub)program from which F08HNF (ZHBEV) is called.
Constraint: LDAB≥KD+1.
7:   W N – REAL (KIND=nag_wp) arrayOutput
On exit: the eigenvalues in ascending order.
8:   Z LDZ* – COMPLEX (KIND=nag_wp) arrayOutput
Note: the second dimension of the array Z must be at least max 1,N if JOBZ='V', and at least 1 otherwise.
On exit: if JOBZ='V', Z contains the orthonormal eigenvectors of the matrix A, with the ith column of Z holding the eigenvector associated with W i.
If JOBZ='N', Z is not referenced.
9:   LDZ – INTEGERInput
On entry: the first dimension of the array Z as declared in the (sub)program from which F08HNF (ZHBEV) is called.
Constraints:
  • if JOBZ='V', LDZ≥ max 1,N ;
  • otherwise LDZ≥1.
10:   WORK N – COMPLEX (KIND=nag_wp) arrayWorkspace
11:   RWORK 3×N-2 – REAL (KIND=nag_wp) arrayWorkspace
12:   INFO – INTEGEROutput
On exit: INFO=0 unless the routine detects an error (see Section 6).

6 Error Indicators and Warnings

INFO<0
If INFO=-i, argument i had an illegal value. An explanatory message is output, and execution of the program is terminated.
INFO>0
If INFO=i, the algorithm failed to converge; i off-diagonal elements of an intermediate tridiagonal form did not converge to zero.

7 Accuracy

The computed eigenvalues and eigenvectors are exact for a nearby matrix A+E, where
E 2 = O ε A 2 ,
and ε is the machine precision. See Section 4.7 of Anderson et al. (1999) for further details.

8 Parallelism and Performance

F08HNF (ZHBEV) is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
F08HNF (ZHBEV) makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The total number of floating-point operations is proportional to n 3 if JOBZ='V' and is proportional to kd n 2 otherwise.
The real analogue of this routine is F08HAF (DSBEV).

10 Example

This example finds all the eigenvalues and eigenvectors of the Hermitian band matrix
A = 1 2-i 3-i 0 0 2+i 2 3-2 i 4-2 i 0 3+i 3+2 i 3 4-3 i 5-3 i 0 4+2 i 4+3 i 4 5-4 i 0 0 5+3 i 5+4 i 5 ,
together with approximate error bounds for the computed eigenvalues and eigenvectors.

10.1 Program Text

Program Text (f08hnfe.f90)

10.2 Program Data

Program Data (f08hnfe.d)

10.3 Program Results

Program Results (f08hnfe.r)

F08 Chapter Contents
F08 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F08HPF (ZHBEVX) : NAG Library, Mark 26

F08 Chapter Contents
F08 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F08HPF (ZHBEVX)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F08HPF (ZHBEVX) computes selected eigenvalues and, optionally, eigenvectors of a complex n by n Hermitian band matrix A of bandwidth 2 kd+1 . Eigenvalues and eigenvectors can be selected by specifying either a range of values or a range of indices for the desired eigenvalues.

2 Specification

SUBROUTINE F08HPF ( JOBZ, RANGE, UPLO, N, KD, AB, LDAB, Q, LDQ, VL, VU, IL, IU, ABSTOL, M, W, Z, LDZ, WORK, RWORK, IWORK, JFAIL, INFO)
INTEGER | N, KD, LDAB, LDQ, IL, IU, M, LDZ, IWORK(5*N), JFAIL(*), INFO
REAL (KIND=nag_wp) | VL, VU, ABSTOL, W(N), RWORK(7*N)
COMPLEX (KIND=nag_wp) | AB(LDAB,*), Q(LDQ,*), Z(LDZ,*), WORK(N)
CHARACTER(1) | JOBZ, RANGE, UPLO
The routine may be called by its LAPACK name zhbevx.

3 Description

The Hermitian band matrix A is first reduced to real tridiagonal form, using unitary similarity transformations. The required eigenvalues and eigenvectors are then computed from the tridiagonal matrix; the method used depends upon whether all, or selected, eigenvalues and eigenvectors are required.

4 References

Anderson E, Bai Z, Bischof C, Blackford S, Demmel J, Dongarra J J, Du Croz J J, Greenbaum A, Hammarling S, McKenney A and Sorensen D (1999) LAPACK Users' Guide (3rd Edition) SIAM, Philadelphia http://www.netlib.org/lapack/lug
Demmel J W and Kahan W (1990) Accurate singular values of bidiagonal matrices SIAM J. Sci. Statist. Comput. 11 873–912
Golub G H and Van Loan C F (1996) Matrix Computations (3rd Edition) Johns Hopkins University Press, Baltimore

5 Arguments

1:   JOBZ – CHARACTER(1)Input
On entry: indicates whether eigenvectors are computed.
JOBZ='N'
Only eigenvalues are computed.
JOBZ='V'
Eigenvalues and eigenvectors are computed.
Constraint: JOBZ='N' or 'V'.
2:   RANGE – CHARACTER(1)Input
On entry: if RANGE='A', all eigenvalues will be found.
If RANGE='V', all eigenvalues in the half-open interval VL,VU will be found.
If RANGE='I', the ILth to IUth eigenvalues will be found.
Constraint: RANGE='A', 'V' or 'I'.
3:   UPLO – CHARACTER(1)Input
On entry: if UPLO='U', the upper triangular part of A is stored.
If UPLO='L', the lower triangular part of A is stored.
Constraint: UPLO='U' or 'L'.
4:   N – INTEGERInput
On entry: n, the order of the matrix A.
Constraint: N≥0.
5:   KD – INTEGERInput
On entry: if UPLO='U', the number of superdiagonals, kd, of the matrix A.
If UPLO='L', the number of subdiagonals, kd, of the matrix A.
Constraint: KD≥0.
6:   AB LDAB* – COMPLEX (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array AB must be at least max 1,N.
On entry: the upper or lower triangle of the n by n Hermitian band matrix A.
The matrix is stored in rows 1 to kd+1, more precisely,
  • if UPLO='U', the elements of the upper triangle of A within the band must be stored with element A ij in AB kd+1+i-j j​ for ​max 1,j-kd≤i≤j;
  • if UPLO='L', the elements of the lower triangle of A within the band must be stored with element A ij in AB 1+i-j j​ for ​j≤i≤min n,j+kd.
On exit: AB is overwritten by values generated during the reduction to tridiagonal form.
The first superdiagonal or subdiagonal and the diagonal of the tridiagonal matrix T are returned in AB using the same storage format as described above.
7:   LDAB – INTEGERInput
On entry: the first dimension of the array AB as declared in the (sub)program from which F08HPF (ZHBEVX) is called.
Constraint: LDAB≥KD+1.
8:   Q LDQ* – COMPLEX (KIND=nag_wp) arrayOutput
Note: the second dimension of the array Q must be at least max 1,N if JOBZ='V', and at least 1 otherwise.
On exit: if JOBZ='V', the n by n unitary matrix used in the reduction to tridiagonal form.
If JOBZ='N', Q is not referenced.
9:   LDQ – INTEGERInput
On entry: the first dimension of the array Q as declared in the (sub)program from which F08HPF (ZHBEVX) is called.
Constraints:
  • if JOBZ='V', LDQ≥ max 1,N ;
  • otherwise LDQ≥1.
10:   VL – REAL (KIND=nag_wp)Input
11:   VU – REAL (KIND=nag_wp)Input
On entry: if RANGE='V', the lower and upper bounds of the interval to be searched for eigenvalues.
If RANGE='A' or 'I', VL and VU are not referenced.
Constraint: if RANGE='V', VL<VU.
12:   IL – INTEGERInput
13:   IU – INTEGERInput
On entry: if RANGE='I', the indices (in ascending order) of the smallest and largest eigenvalues to be returned.
If RANGE='A' or 'V', IL and IU are not referenced.
Constraints:
  • if RANGE='I' and N=0, IL=1 and IU=0;
  • if RANGE='I' and N>0, 1≤ IL≤ IU≤ N .
14:   ABSTOL – REAL (KIND=nag_wp)Input
On entry: the absolute error tolerance for the eigenvalues. An approximate eigenvalue is accepted as converged when it is determined to lie in an interval a,b of width less than or equal to
ABSTOL+ε max a,b ,
where ε is the machine precision. If ABSTOL is less than or equal to zero, then ε T 1 will be used in its place, where T is the tridiagonal matrix obtained by reducing A to tridiagonal form. Eigenvalues will be computed most accurately when ABSTOL is set to twice the underflow threshold 2 × X02AMF , not zero. If this routine returns with INFO>0, indicating that some eigenvectors did not converge, try setting ABSTOL to 2 × X02AMF . See Demmel and Kahan (1990).
15:   M – INTEGEROutput
On exit: the total number of eigenvalues found. 0≤M≤N.
If RANGE='A', M=N.
If RANGE='I', M=IU-IL+1.
16:   W N – REAL (KIND=nag_wp) arrayOutput
On exit: the first M elements contain the selected eigenvalues in ascending order.
17:   Z LDZ* – COMPLEX (KIND=nag_wp) arrayOutput
Note: the second dimension of the array Z must be at least max 1,M if JOBZ='V', and at least 1 otherwise.
On exit: if JOBZ='V', then
  • if INFO=0, the first M columns of Z contain the orthonormal eigenvectors of the matrix A corresponding to the selected eigenvalues, with the ith column of Z holding the eigenvector associated with W i;
  • if an eigenvector fails to converge (INFO>0), then that column of Z contains the latest approximation to the eigenvector, and the index of the eigenvector is returned in JFAIL.
If JOBZ='N', Z is not referenced.
Note: you must ensure that at least max 1,M columns are supplied in the array Z; if RANGE='V', the exact value of M is not known in advance and an upper bound of at least N must be used.
18:   LDZ – INTEGERInput
On entry: the first dimension of the array Z as declared in the (sub)program from which F08HPF (ZHBEVX) is called.
Constraints:
  • if JOBZ='V', LDZ≥ max 1,N ;
  • otherwise LDZ≥1.
19:   WORK N – COMPLEX (KIND=nag_wp) arrayWorkspace
20:   RWORK 7×N – REAL (KIND=nag_wp) arrayWorkspace
21:   IWORK 5×N – INTEGER arrayWorkspace
22:   JFAIL* – INTEGER arrayOutput
Note: the dimension of the array JFAIL must be at least max 1,N.
On exit: if JOBZ='V', then
  • if INFO=0, the first M elements of JFAIL are zero;
  • if INFO>0, JFAIL contains the indices of the eigenvectors that failed to converge.
If JOBZ='N', JFAIL is not referenced.
23:   INFO – INTEGEROutput
On exit: INFO=0 unless the routine detects an error (see Section 6).

6 Error Indicators and Warnings

INFO<0
If INFO=-i, argument i had an illegal value. An explanatory message is output, and execution of the program is terminated.
INFO>0
If INFO=i, then i eigenvectors failed to converge. Their indices are stored in array JFAIL. Please see ABSTOL.

7 Accuracy

The computed eigenvalues and eigenvectors are exact for a nearby matrix A+E, where
E 2 = O ε A 2 ,
and ε is the machine precision. See Section 4.7 of Anderson et al. (1999) for further details.

8 Parallelism and Performance

F08HPF (ZHBEVX) is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
F08HPF (ZHBEVX) makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The total number of floating-point operations is proportional to kd n 2 if JOBZ='N', and is proportional to n 3 if JOBZ='V' and RANGE='A', otherwise the number of floating-point operations will depend upon the number of computed eigenvectors.
The real analogue of this routine is F08HBF (DSBEVX).

10 Example

This example finds the eigenvalues in the half-open interval -2,2 , and the corresponding eigenvectors, of the Hermitian band matrix
A = 1 2-i 3-i 0 0 2+i 2 3-2 i 4-2 i 0 3+i 3+2 i 3 4-3 i 5-3 i 0 4+2 i 4+3 i 4 5-4 i 0 0 5+3 i 5+4 i 5 .

10.1 Program Text

Program Text (f08hpfe.f90)

10.2 Program Data

Program Data (f08hpfe.d)

10.3 Program Results

Program Results (f08hpfe.r)

F08 Chapter Contents
F08 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F08HQF (ZHBEVD) : NAG Library, Mark 26

F08 Chapter Contents
F08 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F08HQF (ZHBEVD)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.
Warning. The specification of the arguments LRWORK and LIWORK changed at Mark 20 in the case where JOB='V' and N>1: the minimum dimension of the array RWORK has been reduced whereas the minimum dimension of the array IWORK has been increased.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F08HQF (ZHBEVD) computes all the eigenvalues and, optionally, all the eigenvectors of a complex Hermitian band matrix. If the eigenvectors are requested, then it uses a divide-and-conquer algorithm to compute eigenvalues and eigenvectors. However, if only eigenvalues are required, then it uses the Pal–Walker–Kahan variant of the QL or QR algorithm.

2 Specification

SUBROUTINE F08HQF ( JOB, UPLO, N, KD, AB, LDAB, W, Z, LDZ, WORK, LWORK, RWORK, LRWORK, IWORK, LIWORK, INFO)
INTEGER | N, KD, LDAB, LDZ, LWORK, LRWORK, IWORK(max(1,LIWORK)), LIWORK, INFO
REAL (KIND=nag_wp) | W(*), RWORK(max(1,LRWORK))
COMPLEX (KIND=nag_wp) | AB(LDAB,*), Z(LDZ,*), WORK(max(1,LWORK))
CHARACTER(1) | JOB, UPLO
The routine may be called by its LAPACK name zhbevd.

3 Description

F08HQF (ZHBEVD) computes all the eigenvalues and, optionally, all the eigenvectors of a complex Hermitian band matrix A. In other words, it can compute the spectral factorization of A as
A=ZΛ ZH,
where Λ is a real diagonal matrix whose diagonal elements are the eigenvalues λi, and Z is the (complex) unitary matrix whose columns are the eigenvectors zi. Thus
A zi=λizi,  i=1,2,…,n.

4 References

Anderson E, Bai Z, Bischof C, Blackford S, Demmel J, Dongarra J J, Du Croz J J, Greenbaum A, Hammarling S, McKenney A and Sorensen D (1999) LAPACK Users' Guide (3rd Edition) SIAM, Philadelphia http://www.netlib.org/lapack/lug
Golub G H and Van Loan C F (1996) Matrix Computations (3rd Edition) Johns Hopkins University Press, Baltimore

5 Arguments

1:   JOB – CHARACTER(1)Input
On entry: indicates whether eigenvectors are computed.
JOB='N'
Only eigenvalues are computed.
JOB='V'
Eigenvalues and eigenvectors are computed.
Constraint: JOB='N' or 'V'.
2:   UPLO – CHARACTER(1)Input
On entry: indicates whether the upper or lower triangular part of A is stored.
UPLO='U'
The upper triangular part of A is stored.
UPLO='L'
The lower triangular part of A is stored.
Constraint: UPLO='U' or 'L'.
3:   N – INTEGERInput
On entry: n, the order of the matrix A.
Constraint: N≥0.
4:   KD – INTEGERInput
On entry: if UPLO='U', the number of superdiagonals, kd, of the matrix A.
If UPLO='L', the number of subdiagonals, kd, of the matrix A.
Constraint: KD≥0.
5:   AB LDAB* – COMPLEX (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array AB must be at least max 1,N.
On entry: the upper or lower triangle of the n by n Hermitian band matrix A.
The matrix is stored in rows 1 to kd+1, more precisely,
  • if UPLO='U', the elements of the upper triangle of A within the band must be stored with element A ij in AB kd+1+i-j j​ for ​max 1,j-kd≤i≤j;
  • if UPLO='L', the elements of the lower triangle of A within the band must be stored with element A ij in AB 1+i-j j​ for ​j≤i≤min n,j+kd.
On exit: AB is overwritten by values generated during the reduction to tridiagonal form.
The first superdiagonal or subdiagonal and the diagonal of the tridiagonal matrix T are returned in AB using the same storage format as described above.
6:   LDAB – INTEGERInput
On entry: the first dimension of the array AB as declared in the (sub)program from which F08HQF (ZHBEVD) is called.
Constraint: LDAB≥KD+1.
7:   W* – REAL (KIND=nag_wp) arrayOutput
Note: the dimension of the array W must be at least max 1,N.
On exit: the eigenvalues of the matrix A in ascending order.
8:   Z LDZ* – COMPLEX (KIND=nag_wp) arrayOutput
Note: the second dimension of the array Z must be at least max 1,N if JOB='V' and at least 1 if JOB='N'.
On exit: if JOB='V', Z is overwritten by the unitary matrix Z which contains the eigenvectors of A. The ith column of Z contains the eigenvector which corresponds to the eigenvalue W i.
If JOB='N', Z is not referenced.
9:   LDZ – INTEGERInput
On entry: the first dimension of the array Z as declared in the (sub)program from which F08HQF (ZHBEVD) is called.
Constraints:
  • if JOB='V', LDZ≥ max 1,N ;
  • if JOB='N', LDZ≥1.
10:   WORK max 1,LWORK – COMPLEX (KIND=nag_wp) arrayWorkspace
On exit: if INFO=0, the real part of WORK 1 contains the required minimal size of LWORK.
11:   LWORK – INTEGERInput
On entry: the dimension of the array WORK as declared in the (sub)program from which F08HQF (ZHBEVD) is called.
If LWORK=-1, a workspace query is assumed; the routine only calculates the minimum dimension of the WORK array, returns this value as the first entry of the WORK array, and no error message related to LWORK is issued.
Constraints:
  • if N≤1, LWORK≥1 or LWORK=-1;
  • if JOB='N' and N>1, LWORK≥N or LWORK=-1;
  • if JOB='V' and N>1, LWORK≥2×N 2 or LWORK=-1.
12:   RWORK max 1,LRWORK – REAL (KIND=nag_wp) arrayWorkspace
On exit: if INFO=0, RWORK 1 contains the required minimal size of LRWORK.
13:   LRWORK – INTEGERInput
On entry: the dimension of the array RWORK as declared in the (sub)program from which F08HQF (ZHBEVD) is called.
If LRWORK=-1, a workspace query is assumed; the routine only calculates the minimum dimension of the RWORK array, returns this value as the first entry of the RWORK array, and no error message related to LRWORK is issued.
Constraints:
  • if N≤1, LRWORK≥1 or LRWORK=-1;
  • if JOB='N' and N>1, LRWORK≥N or LRWORK=-1;
  • if JOB='V' and N>1, LRWORK≥2×N 2+5×N+1 or LRWORK=-1.
14:   IWORK max 1,LIWORK – INTEGER arrayWorkspace
On exit: if INFO=0, IWORK 1 contains the required minimal size of LIWORK.
15:   LIWORK – INTEGERInput
On entry: the dimension of the array IWORK as declared in the (sub)program from which F08HQF (ZHBEVD) is called.
If LIWORK=-1, a workspace query is assumed; the routine only calculates the minimum dimension of the IWORK array, returns this value as the first entry of the IWORK array, and no error message related to LIWORK is issued.
Constraints:
  • if JOB='N' or N≤1, LIWORK≥1 or LIWORK=-1;
  • if JOB='V' and N>1, LIWORK≥5×N+3 or LIWORK=-1.
16:   INFO – INTEGEROutput
On exit: INFO=0 unless the routine detects an error (see Section 6).

6 Error Indicators and Warnings

INFO<0
If INFO=-i, argument i had an illegal value. An explanatory message is output, and execution of the program is terminated.
INFO>0
if INFO=i and JOB='N', the algorithm failed to converge; i elements of an intermediate tridiagonal form did not converge to zero; if INFO=i and JOB='V', then the algorithm failed to compute an eigenvalue while working on the submatrix lying in rows and column i/N+1 through i mod N+1.

7 Accuracy

The computed eigenvalues and eigenvectors are exact for a nearby matrix A+E, where
E 2 = O ε A 2 ,
and ε is the machine precision. See Section 4.7 of Anderson et al. (1999) for further details.

8 Parallelism and Performance

F08HQF (ZHBEVD) is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
F08HQF (ZHBEVD) makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The real analogue of this routine is F08HCF (DSBEVD).

10 Example

This example computes all the eigenvalues and eigenvectors of the Hermitian band matrix A, where
A = 1+0 i 2-1 i 3-1 i 0+0 i 0+0 i 2+1 i 2+0 i 3-2 i 4-2 i 0+0 i 3+1 i 3+2 i 3+0 i 4-3 i 5-3 i 0+0 i 4+2 i 4+3 i 4+0 i 5-4 i 0+0 i 0+0 i 5+3 i 5+4 i 5+0 i .

10.1 Program Text

Program Text (f08hqfe.f90)

10.2 Program Data

Program Data (f08hqfe.d)

10.3 Program Results

Program Results (f08hqfe.r)

F08 Chapter Contents
F08 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F08HSF (ZHBTRD) : NAG Library, Mark 26

F08 Chapter Contents
F08 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F08HSF (ZHBTRD)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F08HSF (ZHBTRD) reduces a complex Hermitian band matrix to tridiagonal form.

2 Specification

SUBROUTINE F08HSF ( VECT, UPLO, N, KD, AB, LDAB, D, E, Q, LDQ, WORK, INFO)
INTEGER | N, KD, LDAB, LDQ, INFO
REAL (KIND=nag_wp) | D(N), E(N-1)
COMPLEX (KIND=nag_wp) | AB(LDAB,*), Q(LDQ,*), WORK(N)
CHARACTER(1) | VECT, UPLO
The routine may be called by its LAPACK name zhbtrd.

3 Description

F08HSF (ZHBTRD) reduces a Hermitian band matrix A to real symmetric tridiagonal form T by a unitary similarity transformation:
T = QH A Q .
The unitary matrix Q is determined as a product of Givens rotation matrices, and may be formed explicitly by the routine if required.
The routine uses a vectorizable form of the reduction, due to Kaufman (1984).

4 References

Kaufman L (1984) Banded eigenvalue solvers on vector machines ACM Trans. Math. Software 10 73–86
Parlett B N (1998) The Symmetric Eigenvalue Problem SIAM, Philadelphia

5 Arguments

1:   VECT – CHARACTER(1)Input
On entry: indicates whether Q is to be returned.
VECT='V'
Q is returned.
VECT='U'
Q is updated (and the array Q must contain a matrix on entry).
VECT='N'
Q is not required.
Constraint: VECT='V', 'U' or 'N'.
2:   UPLO – CHARACTER(1)Input
On entry: indicates whether the upper or lower triangular part of A is stored.
UPLO='U'
The upper triangular part of A is stored.
UPLO='L'
The lower triangular part of A is stored.
Constraint: UPLO='U' or 'L'.
3:   N – INTEGERInput
On entry: n, the order of the matrix A.
Constraint: N≥0.
4:   KD – INTEGERInput
On entry: if UPLO='U', the number of superdiagonals, kd, of the matrix A.
If UPLO='L', the number of subdiagonals, kd, of the matrix A.
Constraint: KD≥0.
5:   AB LDAB* – COMPLEX (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array AB must be at least max 1,N.
On entry: the upper or lower triangle of the n by n Hermitian band matrix A.
The matrix is stored in rows 1 to kd+1, more precisely,
  • if UPLO='U', the elements of the upper triangle of A within the band must be stored with element A ij in AB kd+1+i-j j​ for ​max 1,j-kd≤i≤j;
  • if UPLO='L', the elements of the lower triangle of A within the band must be stored with element A ij in AB 1+i-j j​ for ​j≤i≤min n,j+kd.
On exit: AB is overwritten by values generated during the reduction to tridiagonal form.
The first superdiagonal or subdiagonal and the diagonal of the tridiagonal matrix T are returned in AB using the same storage format as described above.
6:   LDAB – INTEGERInput
On entry: the first dimension of the array AB as declared in the (sub)program from which F08HSF (ZHBTRD) is called.
Constraint: LDAB ≥ max 1,KD+1 .
7:   D N – REAL (KIND=nag_wp) arrayOutput
On exit: the diagonal elements of the tridiagonal matrix T.
8:   E N-1 – REAL (KIND=nag_wp) arrayOutput
On exit: the off-diagonal elements of the tridiagonal matrix T.
9:   Q LDQ* – COMPLEX (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array Q must be at least max 1,N if VECT='V' or 'U' and at least 1 if VECT='N'.
On entry: if VECT='U', Q must contain the matrix formed in a previous stage of the reduction (for example, the reduction of a banded Hermitian-definite generalized eigenproblem); otherwise Q need not be set.
On exit: if VECT='V' or 'U', the n by n matrix Q.
If VECT='N', Q is not referenced.
10:   LDQ – INTEGERInput
On entry: the first dimension of the array Q as declared in the (sub)program from which F08HSF (ZHBTRD) is called.
Constraints:
  • if VECT='V' or 'U', LDQ≥ max 1,N ;
  • if VECT='N', LDQ≥1.
11:   WORK N – COMPLEX (KIND=nag_wp) arrayWorkspace
12:   INFO – INTEGEROutput
On exit: INFO=0 unless the routine detects an error (see Section 6).

6 Error Indicators and Warnings

INFO<0
If INFO=-i, argument i had an illegal value. An explanatory message is output, and execution of the program is terminated.

7 Accuracy

The computed tridiagonal matrix T is exactly similar to a nearby matrix A+E, where
E 2≤ c n ε A 2 ,
c n is a modestly increasing function of n, and ε is the machine precision.
The elements of T themselves may be sensitive to small perturbations in A or to rounding errors in the computation, but this does not affect the stability of the eigenvalues and eigenvectors.
The computed matrix Q differs from an exactly unitary matrix by a matrix E such that
E 2 = O ε ,
where ε is the machine precision.

8 Parallelism and Performance

F08HSF (ZHBTRD) is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
F08HSF (ZHBTRD) makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The total number of real floating-point operations is approximately 20 n 2 k if VECT='N' with 10 n 3 k-1/k additional operations if VECT='V'.
The real analogue of this routine is F08HEF (DSBTRD).

10 Example

This example computes all the eigenvalues and eigenvectors of the matrix A, where
A = -3.13+0.00 i 1.94-2.10 i -3.40+0.25 i 0.00+0.00 i 1.94+2.10 i -1.91+0.00 i -0.82-0.89 i -0.67+0.34 i -3.40-0.25 i -0.82+0.89 i -2.87+0.00 i -2.10-0.16 i 0.00+0.00 i -0.67-0.34 i -2.10+0.16 i 0.50+0.00 i .
Here A is Hermitian and is treated as a band matrix. The program first calls F08HSF (ZHBTRD) to reduce A to tridiagonal form T, and to form the unitary matrix Q; the results are then passed to F08JSF (ZSTEQR) which computes the eigenvalues and eigenvectors of A.

10.1 Program Text

Program Text (f08hsfe.f90)

10.2 Program Data

Program Data (f08hsfe.d)

10.3 Program Results

Program Results (f08hsfe.r)

F08 Chapter Contents
F08 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F08 Chapter Introduction : NAG Library, Mark 26

F08 Chapter Contents
NAG Library Manual

NAG Library Chapter Introduction

F08 – Least Squares and Eigenvalue Problems (LAPACK)

▸▿ Contents

1 Scope of the Chapter
▸▿ 2 Background to the Problems
2.1 Linear Least Squares Problems
▸▿ 2.2 Orthogonal Factorizations and Least Squares Problems
2.2.1 QR factorization
2.2.2 LQ factorization
2.2.3 QR factorization with column pivoting
2.2.4 Complete orthogonal factorization
2.2.5 Updating a QR factorization
2.2.6 Other factorizations
2.3 The Singular Value Decomposition
2.4 The Singular Value Decomposition and Least Squares Problems
2.5 Generalized Linear Least Squares Problems
▸▿ 2.6 Generalized Orthogonal Factorization and Generalized Linear Least Squares Problems
2.6.1 Generalized QR Factorization
2.6.2 Generalized RQ Factorization
2.6.3 Generalized Singular Value Decomposition (GSVD)
2.6.4 The Full CS Decomposition of Orthogonal Matrices
2.7 Symmetric Eigenvalue Problems
2.8 Generalized Symmetric-definite Eigenvalue Problems
2.9 Packed Storage for Symmetric Matrices
2.10 Band Matrices
2.11 Nonsymmetric Eigenvalue Problems
2.12 Generalized Nonsymmetric Eigenvalue Problem
2.13 The Sylvester Equation and the Generalized Sylvester Equation
▸▿ 2.14 Error and Perturbation Bounds and Condition Numbers
2.14.1 Least squares problems
2.14.2 The singular value decomposition
2.14.3 The symmetric eigenproblem
2.14.4 The generalized symmetric-definite eigenproblem
2.14.5 The nonsymmetric eigenproblem
2.14.6 Balancing and condition for the nonsymmetric eigenproblem
2.14.7 The generalized nonsymmetric eigenvalue problem
2.14.8 Balancing the generalized eigenvalue problem
2.14.9 Other problems
2.15 Block Partitioned Algorithms
▸▿ 3 Recommendations on Choice and Use of Available Routines
▸▿ 3.1 Available Routines
▸▿ 3.1.1 Driver routines
3.1.1.1 Linear least squares problems (LLS)
3.1.1.2 Generalized linear least squares problems (LSE and GLM)
3.1.1.3 Symmetric eigenvalue problems (SEP)
3.1.1.4 Nonsymmetric eigenvalue problem (NEP)
3.1.1.5 Singular value decomposition (SVD)
3.1.1.6 Generalized symmetric definite eigenvalue problems (GSEP)
3.1.1.7 Generalized nonsymmetric eigenvalue problem (GNEP)
3.1.1.8 Generalized singular value decomposition (GSVD)
▸▿ 3.1.2 Computational routines
3.1.2.1 Orthogonal factorizations
3.1.2.2 Generalized orthogonal factorizations
3.1.2.3 Singular value problems
3.1.2.4 Generalized singular value decomposition
3.1.2.5 Symmetric eigenvalue problems
3.1.2.6 Generalized symmetric-definite eigenvalue problems
3.1.2.7 Nonsymmetric eigenvalue problems
3.1.2.8 Generalized nonsymmetric eigenvalue problems
3.1.2.9 The Sylvester equation and the generalized Sylvester equation
3.2 NAG Names and LAPACK Names
▸▿ 3.3 Matrix Storage Schemes
3.3.1 Conventional storage
3.3.2 Packed storage
3.3.3 Band storage
3.3.4 Tridiagonal and bidiagonal matrices
3.3.5 Real diagonal elements of complex matrices
3.3.6 Representation of orthogonal or unitary matrices
▸▿ 3.4 Argument Conventions
3.4.1 Option Arguments
3.4.2 Problem dimensions
3.4.3 Length of work arrays
3.4.4 Error-handling and the Diagnostic Argument INFO
▸▿ 4 Decision Trees
4.1 General Purpose Routines (eigenvalues and eigenvectors)
4.2 General Purpose Routines (singular value decomposition)
5 Functionality Index
6 Auxiliary Routines Associated with Library Routine Arguments
7 Routines Withdrawn or Scheduled for Withdrawal
8 References

1 Scope of the Chapter

This chapter provides routines for the solution of linear least squares problems, eigenvalue problems and singular value problems, as well as associated computations. It provides routines for:
  • solution of linear least squares problems
  • solution of symmetric eigenvalue problems
  • solution of nonsymmetric eigenvalue problems
  • solution of singular value problems
  • solution of generalized linear least squares problems
  • solution of generalized symmetric-definite eigenvalue problems
  • solution of generalized nonsymmetric eigenvalue problems
  • solution of generalized singular value problems
  • matrix factorizations associated with the above problems
  • estimating condition numbers of eigenvalue and eigenvector problems
  • estimating the numerical rank of a matrix
  • solution of the Sylvester matrix equation
Routines are provided for both real and complex data.
For a general introduction to the solution of linear least squares problems, you should turn first to Chapter F04. The decision trees, at the end of Chapter F04, direct you to the most appropriate routines in Chapters F04 or F08. Chapters F04 and F08 contain Black Box (or driver) routines which enable standard linear least squares problems to be solved by a call to a single routine.
For a general introduction to eigenvalue and singular value problems, you should turn first to Chapter F02. The decision trees, at the end of Chapter F02, direct you to the most appropriate routines in Chapters F02 or F08. Chapters F02 and F08 contain Black Box (or driver) routines which enable standard types of problem to be solved by a call to a single routine. Often routines in Chapter F02 call Chapter F08 routines to perform the necessary computational tasks.
The routines in this chapter (Chapter F08) handle only dense, band, tridiagonal and Hessenberg matrices (not matrices with more specialised structures, or general sparse matrices). The tables in Section 3 and the decision trees in Section 4 direct you to the most appropriate routines in Chapter F08.
The routines in this chapter have all been derived from the LAPACK project (see Anderson et al. (1999)). They have been designed to be efficient on a wide range of high-performance computers, without compromising efficiency on conventional serial machines.

2 Background to the Problems

This section is only a brief introduction to the numerical solution of linear least squares problems, eigenvalue and singular value problems. Consult a standard textbook for a more thorough discussion, for example Golub and Van Loan (2012).

2.1 Linear Least Squares Problems

The linear least squares problem is
minimize x b-Ax 2, (1)
where A is an m by n matrix, b is a given m element vector and x is an n-element solution vector.
In the most usual case m≥n and rank A=n, so that A has full rank and in this case the solution to problem (1) is unique; the problem is also referred to as finding a least squares solution to an overdetermined system of linear equations.
When m<n and rank A=m, there are an infinite number of solutions x which exactly satisfy b-Ax=0. In this case it is often useful to find the unique solution x which minimizes x 2, and the problem is referred to as finding a minimum norm solution to an underdetermined system of linear equations.
In the general case when we may have rank A<min m,n – in other words, A may be rank-deficient – we seek the minimum norm least squares solution x which minimizes both x 2 and b-Ax 2.
This chapter (Chapter F08) contains driver routines to solve these problems with a single call, as well as computational routines that can be combined with routines in Chapter F07 to solve these linear least squares problems. Chapter F04 also contains Black Box routines to solve these linear least squares problems in standard cases. The next two sections discuss the factorizations that can be used in the solution of linear least squares problems.

2.2 Orthogonal Factorizations and Least Squares Problems

A number of routines are provided for factorizing a general rectangular m by n matrix A, as the product of an orthogonal matrix (unitary if complex) and a triangular (or possibly trapezoidal) matrix.
A real matrix Q is orthogonal if QT Q=I; a complex matrix Q is unitary if QH Q=I. Orthogonal or unitary matrices have the important property that they leave the 2-norm of a vector invariant, so that
x 2 =Qx 2,
if Q is orthogonal or unitary. They usually help to maintain numerical stability because they do not amplify rounding errors.
Orthogonal factorizations are used in the solution of linear least squares problems. They may also be used to perform preliminary steps in the solution of eigenvalue or singular value problems, and are useful tools in the solution of a number of other problems.

2.2.1 QR factorization

The most common, and best known, of the factorizations is the QR factorization given by
A =Q R 0 ,   if ​m≥n,
where R is an n by n upper triangular matrix and Q is an m by m orthogonal (or unitary) matrix. If A is of full rank n, then R is nonsingular. It is sometimes convenient to write the factorization as
A =Q 1Q 2 R 0
which reduces to
A =Q 1 R,
where Q 1 consists of the first n columns of Q, and Q 2 the remaining m-n columns.
If m<n, R is trapezoidal, and the factorization can be written
A =Q R 1R 2 ,   if ​m<n,
where R 1 is upper triangular and R 2 is rectangular.
The QR factorization can be used to solve the linear least squares problem (1) when m≥n and A is of full rank, since
b-Ax 2= QT b-QT Ax 2= c 1-Rx c 2 2,
where
c≡ c 1 c 2 = Q 1 T b Q 2 T b =QT b;
and c 1 is an n-element vector. Then x is the solution of the upper triangular system
Rx=c 1.
The residual vector r is given by
r =b-Ax=Q 0 c 2 .
The residual sum of squares r 2 2 may be computed without forming r explicitly, since
r 2 =b-Ax 2=c 2 2.

2.2.2 LQ factorization

The LQ factorization is given by
A =L 0 Q=L 0 Q 1 Q 2 =L Q 1,   if ​m≤n,
where L is m by m lower triangular, Q is n by n orthogonal (or unitary), Q 1 consists of the first m rows of Q, and Q 2 the remaining n-m rows.
The LQ factorization of A is essentially the same as the QR factorization of AT (AH if A is complex), since
A =L 0 Q⇔AT=QT LT 0 .
The LQ factorization may be used to find a minimum norm solution of an underdetermined system of linear equations Ax=b where A is m by n with m<n and has rank m. The solution is given by
x =QT L-1 b 0 .

2.2.3 QR factorization with column pivoting

To solve a linear least squares problem (1) when A is not of full rank, or the rank of A is in doubt, we can perform either a QR factorization with column pivoting or a singular value decomposition.
The QR factorization with column pivoting is given by
A =Q R 0 PT,  m≥n,
where Q and R are as before and P is a (real) permutation matrix, chosen (in general) so that
r 11≥r 22≥⋯≥r nn
and moreover, for each k,
r kk≥R k:j,j 2,  j=k+1,…,n.
If we put
R = R 11 R 12 0 R 22
where R 11 is the leading k by k upper triangular sub-matrix of R then, in exact arithmetic, if rank A=k, the whole of the sub-matrix R 22 in rows and columns k+1 to n would be zero. In numerical computation, the aim must be to determine an index k, such that the leading sub-matrix R 11 is well-conditioned, and R 22 is negligible, so that
R = R 11 R 12 0 R 22 ≃ R 11 R 12 0 0 .
Then k is the effective rank of A. See Golub and Van Loan (2012) for a further discussion of numerical rank determination.
The so-called basic solution to the linear least squares problem (1) can be obtained from this factorization as
x =P R 11-1 c^1 0 ,
where c^1 consists of just the first k elements of c=QT b.

2.2.4 Complete orthogonal factorization

The Q R factorization with column pivoting does not enable us to compute a minimum norm solution to a rank-deficient linear least squares problem, unless R 12 = 0 . However, by applying for further orthogonal (or unitary) transformations from the right to the upper trapezoidal matrix R 11 R 12 , R 12 can be eliminated:
R 11 R 12 Z = T 11 0 .
This gives the complete orthogonal factorization
AP = Q T 11 0 0 0 ZT
from which the minimum norm solution can be obtained as
x = P Z T 11-1 c^1 0 .

2.2.5 Updating a QR factorization

Section 2.2.1 gave the forms of the QR factorization of an m by n matrix A for the two cases m≥n and m<n. Taking first the case m≥n, the least squares solution of
Ax = b = nb 1m-nb 2()
is the solution of
Rx = Q 1 T b .
If the original system is now augmented by the addition of p rows so that we require the solution of
A B x = mbpb 3()
where B is p by n, then this is equivalent to finding the least squares solution of
A^ x = nnRpB() x = Q 1 T b b 3 = b^ .
This now requires the QR factorization of the n+p by n triangular-rectangular matrix A^.
For the case m<n≤m+p, the least squares solution of the augmented system reduces to
A^x = B R 1 R 2 x = b 3 QT b = b^ ,
where A^ is pentagonal.
In both cases A^ can be written as a special case of a triangular-pentagonal matrix consisting of an upper triangular part on top of a rectangular part which is itself on top of a trapezoidal part. In the first case there is no trapezoidal part, in the second case a zero upper triangular part can be added, and more generally the two cases can be combined.

2.2.6 Other factorizations

The QL and RQ factorizations are given by
A = Q 0 L ,  if ​ m ≥ n ,
and
A = 0 R Q ,  if ​ m ≤ n .
The factorizations are less commonly used than either the QR or LQ factorizations described above, but have applications in, for example, the computation of generalized QR factorizations.

2.3 The Singular Value Decomposition

The singular value decomposition (SVD) of an m by n matrix A is given by
A =UΣ VT,  A=UΣ VH in the complex case
where U and V are orthogonal (unitary) and Σ is an m by n diagonal matrix with real diagonal elements, σi, such that
σ 1≥σ 2≥⋯≥σ min m,n≥0.
The σi are the singular values of A and the first min m,n columns of U and V are the left and right singular vectors of A. The singular values and singular vectors satisfy
A vi=σiui  and  AT ui=σivi or ​AH ui=σivi
where ui and vi are the ith columns of U and V respectively.
The computation proceeds in the following stages.
1. | The matrix A is reduced to bidiagonal form A=U 1 B V 1 T if A is real (A=U 1 B V 1 H if A is complex), where U 1 and V 1 are orthogonal (unitary if A is complex), and B is real and upper bidiagonal when m≥n and lower bidiagonal when m<n, so that B is nonzero only on the main diagonal and either on the first superdiagonal (if m≥n) or the first subdiagonal (if m<n).
2. | The SVD of the bidiagonal matrix B is computed as B=U 2 Σ V 2 T , where U 2 and V 2 are orthogonal and Σ is diagonal as described above. The singular vectors of A are then U=U 1U 2 and V=V 1V 2.
If m≫n, it may be more efficient to first perform a QR factorization of A, and then compute the SVD of the n by n matrix R, since if A=QR and R=UΣ VT, then the SVD of A is given by A=QU Σ VT.
Similarly, if m≪n, it may be more efficient to first perform an LQ factorization of A.
This chapter supports two primary algorithms for computing the SVD of a bidiagonal matrix. They are:
(i) | the divide and conquer algorithm;
(ii) | the QR algorithm.
The divide and conquer algorithm is much faster than the QR algorithm if singular vectors of large matrices are required.

2.4 The Singular Value Decomposition and Least Squares Problems

The SVD may be used to find a minimum norm solution to a (possibly) rank-deficient linear least squares problem (1). The effective rank, k, of A can be determined as the number of singular values which exceed a suitable threshold. Let Σ^ be the leading k by k sub-matrix of Σ, and V^ be the matrix consisting of the first k columns of V. Then the solution is given by
x =V^Σ^-1 c^1,
where c^1 consists of the first k elements of c=UT b= U 2 T U 1 T b.

2.5 Generalized Linear Least Squares Problems

The simple type of linear least squares problem described in Section 2.1 can be generalized in various ways.
1. Linear least squares problems with equality constraints:
find ​x​ to minimize ​S=c-Ax 2 2  subject to  Bx=d,
where A is m by n and B is p by n, with p≤n≤m+p. The equations Bx=d may be regarded as a set of equality constraints on the problem of minimizing S. Alternatively the problem may be regarded as solving an overdetermined system of equations
A B x= c d ,
where some of the equations (those involving B) are to be solved exactly, and the others (those involving A) are to be solved in a least squares sense. The problem has a unique solution on the assumptions that B has full row rank p and the matrix A B has full column rank n. (For linear least squares problems with inequality constraints, refer to Chapter E04.)
2. General Gauss–Markov linear model problems:
minimize ​y 2  subject to  d=Ax+By,
where A is m by n and B is m by p, with n≤m≤n+p. When B=I, the problem reduces to an ordinary linear least squares problem. When B is square and nonsingular, it is equivalent to a weighted linear least squares problem:
find ​x​ to minimize ​B-1 d-Ax 2.
The problem has a unique solution on the assumptions that A has full column rank n, and the matrix A,B has full row rank m. Unless B is diagonal, for numerical stability it is generally preferable to solve a weighted linear least squares problem as a general Gauss–Markov linear model problem.

2.6 Generalized Orthogonal Factorization and Generalized Linear Least Squares Problems

2.6.1 Generalized QR Factorization

The generalized QR (GQR) factorization of an n by m matrix A and an n by p matrix B is given by the pair of factorizations
A = QR   and   B = QTZ ,
where Q and Z are respectively n by n and p by p orthogonal matrices (or unitary matrices if A and B are complex). R has the form
R = mmR 11n-m0() , if ​ n ≥ m ,
or
R = nm-nnR 11R 12() , if ​ n < m ,
where R 11 is upper triangular. T has the form
T = p-nnn0T 12() , if ​ n ≤ p ,
or
T = pn-pT 11pT 21() , if ​ n > p ,
where T 12 or T 21 is upper triangular.
Note that if B is square and nonsingular, the GQR factorization of A and B implicitly gives the QR factorization of the matrix B-1 A :
B-1 A = ZT T-1 R
without explicitly computing the matrix inverse B-1 or the product B-1 A (remembering that the inverse of an invertible upper triangular matrix and the product of two upper triangular matrices is an upper triangular matrix).
The GQR factorization can be used to solve the general (Gauss–Markov) linear model problem (GLM) (see Section 2.5, but note that A and B are dimensioned differently there as m by n and p by n respectively). Using the GQR factorization of A and B, we rewrite the equation d = Ax + By as
QT d = QT Ax + QT By = Rx + TZy.
We partition this as
d 1 d 2 = mmR 11n-m0() x + p-n+mn-mmT 11T 12n-m0T 22() y 1 y 2
where
d 1 d 2 ≡ QT d ,  and   y 1 y 2 ≡ Zy .
The GLM problem is solved by setting
y 1 = 0   and   y 2 = T 22-1 d 2
from which we obtain the desired solutions
x = R 11-1 d 1 - T 12 y 2   and   y = ZT 0 y 2 .

2.6.2 Generalized RQ Factorization

The generalized RQ (GRQ) factorization of an m by n matrix A and a p by n matrix B is given by the pair of factorizations
A = R Q ,   B = Z T Q
where Q and Z are respectively n by n and p by p orthogonal matrices (or unitary matrices if A and B are complex). R has the form
R = n-mmm0R 12() ,  if ​ m≤n ,
or
R = nm-nR 11nR 21() ,  if ​ m>n ,
where R 12 or R 21 is upper triangular. T has the form
T = nnT 11p-n0() ,   if ​ p≥n ,
or
T = pn-ppT 11T 12() ,   if ​ p<n ,
where T 11 is upper triangular.
Note that if B is square and nonsingular, the GRQ factorization of A and B implicitly gives the RQ factorization of the matrix A B-1 :
A B-1 = R T-1 ZT
without explicitly computing the matrix B-1 or the product A B-1 (remembering that the inverse of an invertible upper triangular matrix and the product of two upper triangular matrices is an upper triangular matrix).
The GRQ factorization can be used to solve the linear equality-constrained least squares problem (LSE) (see Section 2.5). We use the GRQ factorization of B and A (note that B and A have swapped roles), written as
B = T Q   and   A = Z R Q .
We write the linear equality constraints Bx=d as
T Q x = d ,
which we partition as:
n-ppp0T 12() x 1 x 2 = d   where   x 1 x 2 ≡ Qx .
Therefore x 2 is the solution of the upper triangular system
T 12 x 2 = d .
Furthermore,
Ax-c 2 = ZT Ax - ZT c 2 = RQx - ZT c 2 .
We partition this expression as:
n-ppn-pR 11R 12p+m-n0R 22() x 1 x 2 - c 1 c 2 ,
where c 1 c 2 ≡ ZT c .
To solve the LSE problem, we set
R 11 x 1 + R 12 x 2 - c 1 = 0
which gives x 1 as the solution of the upper triangular system
R 11 x 1 = c 1 - R 12 x 2 .
Finally, the desired solution is given by
x = QT x 1 x 2 .

2.6.3 Generalized Singular Value Decomposition (GSVD)

The generalized (or quotient) singular value decomposition of an m by n matrix A and a p by n matrix B is given by the pair of factorizations
A = U Σ 1 0,R QT   and   B = V Σ 2 0,R QT .
The matrices in these factorizations have the following properties:
– | U is m by m, V is p by p, Q is n by n, and all three matrices are orthogonal. If A and B are complex, these matrices are unitary instead of orthogonal, and QT should be replaced by QH in the pair of factorizations.
– | R is r by r, upper triangular and nonsingular. 0,R is r by n (in other words, the 0 is an r by n-r zero matrix). The integer r is the rank of A B , and satisfies r≤n.
– | Σ 1 is m by r, Σ 2 is p by r, both are real, non-negative and diagonal, and Σ 1 T Σ 1 + Σ 2 T Σ 2 = I . Write Σ 1 T Σ 1 = diag α 12,…,αr 2 and Σ 2 T Σ 2 = diag β 12,…,βr 2 , where αi and βi lie in the interval from 0 to 1. The ratios α 1 / β 1 ,…, αr / βr are called the generalized singular values of the pair A, B. If βi = 0 , then the generalized singular value αi / βi is infinite.
Σ 1 and Σ 2 have the following detailed structures, depending on whether m≥r or m<r . In the first case, m≥r , then
Σ 1 = klkI0l0Cm-k-l00()   and   Σ 2 = kll0Sp-l00() .
Here l is the rank of B, k=r-l , C and S are diagonal matrices satisfying C 2 + S 2 = I , and S is nonsingular. We may also identify α 1 = ⋯ = αk = 1 , α k+i = c ii , for i=1,2,…, l, β 1 = ⋯ = βk = 0 , and β k+i = s ii , for i=1,2,…, l . Thus, the first k generalized singular values α 1 / β 1 ,…, αk / βk are infinite, and the remaining l generalized singular values are finite.
In the second case, when m<r ,
Σ 1 = km-kk+l-mkI00m-k0C0()
and
Σ 2 = km-kk+l-mm-k0S0k+l-m00Ip-l000() .
Again, l is the rank of B, k=r-l , C and S are diagonal matrices satisfying C 2 + S 2 = I , and S is nonsingular, and we may identify α 1 = ⋯ = αk = 1 , α k+i = c ii , for i=1,2,…, m-k , α m+1 = ⋯ = αr = 0 , β 1 = ⋯ = βk = 0 , β k+i = s ii , for i=1,2,…, m-k and β m+1 = ⋯ = βr = 1 . Thus, the first k generalized singular values α 1 / β 1 ,…, αk / βk are infinite, and the remaining l generalized singular values are finite.
Here are some important special cases of the generalized singular value decomposition. First, if B is square and nonsingular, then r=n and the generalized singular value decomposition of A and B is equivalent to the singular value decomposition of A B-1 , where the singular values of A B-1 are equal to the generalized singular values of the pair A, B:
A B-1 = U Σ 1 R QT V Σ 2 R QT -1 = U Σ 1 Σ 2-1 VT .
Second, for the matrix C, where
C ≡ A B
if the columns of C are orthonormal, then r=n, R=I and the generalized singular value decomposition of A and B is equivalent to the CS (Cosine–Sine) decomposition of C:
A B = U 0 0 V Σ 1 Σ 2 QT .
Third, the generalized eigenvalues and eigenvectors of AT A - λ BT B can be expressed in terms of the generalized singular value decomposition: Let
X = Q I 0 0 R-1 .
Then
XT AT AX = 0 0 0 Σ 1 T Σ 1   and   XT BT BX = 0 0 0 Σ 2 T Σ 2 .
Therefore, the columns of X are the eigenvectors of AT A - λ BT B , and ‘nontrivial’ eigenvalues are the squares of the generalized singular values (see also Section 2.8). ‘Trivial’ eigenvalues are those corresponding to the leading n-r columns of X, which span the common null space of AT A and BT B . The ‘trivial eigenvalues’ are not well defined.

2.6.4 The Full CS Decomposition of Orthogonal Matrices

In Section 2.6.3 the CS (Cosine-Sine) decomposition of an orthogonal matrix partitioned into two submatrices A and B was given by
A B = U 0 0 V Σ 1 Σ 2 QT .
The full CS decomposition of an m by m orthogonal matrix X partitions X into four submatrices and factorizes as
X 11 X 12 X 21 X 22 = U 1 0 0 U 2 Σ 11 -Σ 12 Σ 21 Σ 22 V 1 0 0 V 2 T
where, X 11 is a p by q submatrix (which implies the dimensions of X 12, X 21 and X 22); U 1, U 2, V 1 and V 2 are orthogonal matrices of dimensions p, m-p, q and m-q respectively; Σ 11 is the p by q single-diagonal matrix
Σ 11 = k 11-rrq-k 11k 11-rI00r0C0p-k 1100() ,  k 11 = min p,q
Σ 12 is the p by m-q single-diagonal matrix
Σ 12 = m-q-k 12rk 12-rp-k 1200r0S0k 12-r00I() ,  k 12 = min p,m-q ,
Σ 21 is the m-p by q single-diagonal matrix
Σ 21 = q-k 21rk 21-rm-p-k 2100r0S0k 21-r00I() ,  k 21 = min m-p,q ,
and, Σ 21 is the m-p by q single-diagonal matrix
Σ 22 = k 22-rrm-q-k 22k 22-rI00r0C0m-p-k 2200() ,  k 22 = min m-p,m-q
where r= min p,m-p,q,m-q and the missing zeros remind us that either the column or the row is missing. The r by r diagonal matrices C and S are such that C 2 + S 2 = I .
This is equivalent to the simultaneous singular value decomposition of the four submatrices X 11, X 12, X 21 and X 22.

2.7 Symmetric Eigenvalue Problems

The symmetric eigenvalue problem is to find the eigenvalues, λ, and corresponding eigenvectors, z≠0, such that
Az=λz,  A=AT,   where ​A​ is real.
For the Hermitian eigenvalue problem we have
Az=λ z,   A=AH,   where ​ A​ is complex.
For both problems the eigenvalues λ are real.
When all eigenvalues and eigenvectors have been computed, we write
A =ZΛ ZT or ​A=ZΛ ZH​ if complex,
where Λ is a diagonal matrix whose diagonal elements are the eigenvalues, and Z is an orthogonal (or unitary) matrix whose columns are the eigenvectors. This is the classical spectral factorization of A.
The basic task of the symmetric eigenproblem routines is to compute values of λ and, optionally, corresponding vectors z for a given matrix A. This computation proceeds in the following stages.
1. | The real symmetric or complex Hermitian matrix A is reduced to real tridiagonal form T. If A is real symmetric this decomposition is A=QT QT with Q orthogonal and T symmetric tridiagonal. If A is complex Hermitian, the decomposition is A=QT QH with Q unitary and T, as before, real symmetric tridiagonal.
2. | Eigenvalues and eigenvectors of the real symmetric tridiagonal matrix T are computed. If all eigenvalues and eigenvectors are computed, this is equivalent to factorizing T as T=SΛ ST, where S is orthogonal and Λ is diagonal. The diagonal entries of Λ are the eigenvalues of T, which are also the eigenvalues of A, and the columns of S are the eigenvectors of T; the eigenvectors of A are the columns of Z=QS, so that A=ZΛ ZT (ZΛ ZH when A is complex Hermitian).
This chapter supports four primary algorithms for computing eigenvalues and eigenvectors of real symmetric matrices and complex Hermitian matrices. They are:
(i) | the divide-and-conquer algorithm;
(ii) | the QR algorithm;
(iii) | bisection followed by inverse iteration;
(iv) | the Relatively Robust Representation (RRR).
The divide-and-conquer algorithm is generally more efficient than the traditional QR algorithm for computing all eigenvalues and eigenvectors, but the RRR algorithm tends to be fastest of all. For further information and references see Anderson et al. (1999).

2.8 Generalized Symmetric-definite Eigenvalue Problems

This section is concerned with the solution of the generalized eigenvalue problems Az=λBz, ABz=λz, and BAz=λz, where A and B are real symmetric or complex Hermitian and B is positive definite. Each of these problems can be reduced to a standard symmetric eigenvalue problem, using a Cholesky factorization of B as either B=L LT or B=UT U (L LH or UH U in the Hermitian case).
With B=L LT, we have
Az=λBz⇒L-1 A L-TLT z=λ LT z.
Hence the eigenvalues of Az=λBz are those of Cy=λy, where C is the symmetric matrix C=L-1 A L-T and y=LT z. In the complex case C is Hermitian with C=L-1 A L-H and y=LH z.
Table 1 summarises how each of the three types of problem may be reduced to standard form Cy=λy, and how the eigenvectors z of the original problem may be recovered from the eigenvectors y of the reduced problem. The table applies to real problems; for complex problems, transposed matrices must be replaced by conjugate-transposes.
 | Type of problem | Factorization of B | Reduction | Recovery of eigenvectors
1. | Az=λBz | B=L LT, B=UT U | C=L-1 A L-T, C=U-T A U-1 | z=L-T y, z=U-1 y
2. | ABz=λz | B=L LT, B=UT U | C=LT AL, C=UA UT | z=L-T y, z=U-1 y
3. | BAz=λz | B=L LT, B=UT U | C=LT AL, C=UA UT | z=Ly, z=UT y
Table 1
Reduction of generalized symmetric-definite eigenproblems to standard problems
When the generalized symmetric-definite problem has been reduced to the corresponding standard problem Cy=λy, this may then be solved using the routines described in the previous section. No special routines are needed to recover the eigenvectors z of the generalized problem from the eigenvectors y of the standard problem, because these computations are simple applications of Level 2 or Level 3 BLAS (see Chapter F06).

2.9 Packed Storage for Symmetric Matrices

Routines which handle symmetric matrices are usually designed so that they use either the upper or lower triangle of the matrix; it is not necessary to store the whole matrix. If either the upper or lower triangle is stored conventionally in the upper or lower triangle of a two-dimensional array, the remaining elements of the array can be used to store other useful data. However, that is not always convenient, and if it is important to economize on storage, the upper or lower triangle can be stored in a one-dimensional array of length n n+1/2; that is, the storage is almost halved.
This storage format is referred to as packed storage; it is described in Section 3.3.2 in the F07 Chapter Introduction.
Routines designed for packed storage are usually less efficient, especially on high-performance computers, so there is a trade-off between storage and efficiency.

2.10 Band Matrices

A band matrix is one whose elements are confined to a relatively small number of subdiagonals or superdiagonals on either side of the main diagonal. Algorithms can take advantage of bandedness to reduce the amount of work and storage required. The storage scheme for band matrices is described in Section 3.3.4 in the F07 Chapter Introduction.
If the problem is the generalized symmetric definite eigenvalue problem Az=λBz and the matrices A and B are additionally banded, the matrix C as defined in Section 2.8 is, in general, full. We can reduce the problem to a banded standard problem by modifying the definition of C thus:
C =XT AX,   where  X=U-1 Q  or ​L-T Q,
where Q is an orthogonal matrix chosen to ensure that C has bandwidth no greater than that of A.
A further refinement is possible when A and B are banded, which halves the amount of work required to form C. Instead of the standard Cholesky factorization of B as UT U or L LT, we use a split Cholesky factorization B=ST S, where
S = U 11 M 21 L 22
with U 11 upper triangular and L 22 lower triangular of order approximately n/2; S has the same bandwidth as B.

2.11 Nonsymmetric Eigenvalue Problems

The nonsymmetric eigenvalue problem is to find the eigenvalues, λ, and corresponding eigenvectors, v≠0, such that
Av=λv.
More precisely, a vector v as just defined is called a right eigenvector of A, and a vector u≠0 satisfying
uT A=λ uT uH A=λ uH  when ​u​ is complex
is called a left eigenvector of A.
A real matrix A may have complex eigenvalues, occurring as complex conjugate pairs.
This problem can be solved via the Schur factorization of A, defined in the real case as
A =ZT ZT,
where Z is an orthogonal matrix and T is an upper quasi-triangular matrix with 1 by 1 and 2 by 2 diagonal blocks, the 2 by 2 blocks corresponding to complex conjugate pairs of eigenvalues of A. In the complex case, the Schur factorization is
A =ZT ZH,
where Z is unitary and T is a complex upper triangular matrix.
The columns of Z are called the Schur vectors. For each k (1≤k≤n), the first k columns of Z form an orthonormal basis for the invariant subspace corresponding to the first k eigenvalues on the diagonal of T. Because this basis is orthonormal, it is preferable in many applications to compute Schur vectors rather than eigenvectors. It is possible to order the Schur factorization so that any desired set of k eigenvalues occupy the k leading positions on the diagonal of T.
The two basic tasks of the nonsymmetric eigenvalue routines are to compute, for a given matrix A, all n values of λ and, if desired, their associated right eigenvectors v and/or left eigenvectors u, and the Schur factorization.
These two basic tasks can be performed in the following stages.
1. | A general matrix A is reduced to upper Hessenberg form H which is zero below the first subdiagonal. The reduction may be written A=QH QT with Q orthogonal if A is real, or A=QH QH with Q unitary if A is complex.
2. | The upper Hessenberg matrix H is reduced to Schur form T, giving the Schur factorization H=ST ST (for H real) or H=ST SH (for H complex). The matrix S (the Schur vectors of H) may optionally be computed as well. Alternatively S may be postmultiplied into the matrix Q determined in stage 1, to give the matrix Z=QS, the Schur vectors of A. The eigenvalues are obtained from the diagonal elements or diagonal blocks of T.
3. | Given the eigenvalues, the eigenvectors may be computed in two different ways. Inverse iteration can be performed on H to compute the eigenvectors of H, and then the eigenvectors can be multiplied by the matrix Q in order to transform them to eigenvectors of A. Alternatively the eigenvectors of T can be computed, and optionally transformed to those of H or A if the matrix S or Z is supplied.
The accuracy with which eigenvalues can be obtained can often be improved by balancing a matrix. This is discussed further in Section 2.14.6 below.

2.12 Generalized Nonsymmetric Eigenvalue Problem

The generalized nonsymmetric eigenvalue problem is to find the eigenvalues, λ, and corresponding eigenvectors, v≠0, such that
Av=λBv.
More precisely, a vector v as just defined is called a right eigenvector of the matrix pair A,B, and a vector u≠0 satisfying
uT A=λ uT B uH A=λ uH B​ when ​u​ is complex
is called a left eigenvector of the matrix pair A,B.
If B is singular then the problem has one or more infinite eigenvalues λ=∞, corresponding to Bv=0. Note that if A is nonsingular, then the equivalent problem μAv=Bv is perfectly well defined and an infinite eigenvalue corresponds to μ=0. To deal with both finite (including zero) and infinite eigenvalues, the routines in this chapter do not compute λ explicitly, but rather return a pair of numbers α,β such that if β≠0
λ =α/β
and if α≠0 and β=0 then λ=∞. β is always returned as real and non-negative. Of course, computationally an infinite eigenvalue may correspond to a small β rather than an exact zero.
For a given pair A,B the set of all the matrices of the form A-λB is called a matrix pencil and λ and v are said to be an eigenvalue and eigenvector of the pencil A-λB. If A and B are both singular and share a common null space then
det A-λB≡0
so that the pencil A-λB is singular for all λ. In other words any λ can be regarded as an eigenvalue. In exact arithmetic a singular pencil will have α=β=0 for some α,β. Computationally if some pair α,β is small then the pencil is singular, or nearly singular, and no reliance can be placed on any of the computed eigenvalues. Singular pencils can also manifest themselves in other ways; see, in particular, Sections 2.3.5.2 and 4.11.1.4 of Anderson et al. (1999) for further details.
The generalized eigenvalue problem can be solved via the generalized Schur factorization of the pair A,B defined in the real case as
A =QS ZT,  B=QT ZT,
where Q and Z are orthogonal, T is upper triangular with non-negative diagonal elements and S is upper quasi-triangular with 1 by 1 and 2 by 2 diagonal blocks, the 2 by 2 blocks corresponding to complex conjugate pairs of eigenvalues. In the complex case, the generalized Schur factorization is
A =QS ZH,  B=QT ZH,
where Q and Z are unitary and S and T are upper triangular, with T having real non-negative diagonal elements. The columns of Q and Z are called respectively the left and right generalized Schur vectors and span pairs of deflating subspaces of A and B, which are a generalization of invariant subspaces.
It is possible to order the generalized Schur factorization so that any desired set of k eigenvalues correspond to the k leading positions on the diagonals of the pair S,T.
The two basic tasks of the generalized nonsymmetric eigenvalue routines are to compute, for a given pair A,B, all n values of λ and, if desired, their associated right eigenvectors v and/or left eigenvectors u, and the generalized Schur factorization.
These two basic tasks can be performed in the following stages.
1. | The matrix pair A,B is reduced to generalized upper Hessenberg form H,R, where H is upper Hessenberg (zero below the first subdiagonal) and R is upper triangular. The reduction may be written as A=Q 1 H Z 1 T, B=Q 1 R Z 1 T in the real case with Q 1 and Z 1 orthogonal, and A=Q 1 H Z 1 H , B=Q 1 R Z 1 H in the complex case with Q 1 and Z 1 unitary.
2. | The generalized upper Hessenberg form H,R is reduced to the generalized Schur form S,T using the generalized Schur factorization H=Q 2 S Z 2 T, R=Q 2 T Z 2 T in the real case with Q 2 and Z 2 orthogonal, and H=Q 2 S Z 2 H, R=Q 2 T Z 2 H in the complex case. The generalized Schur vectors of A,B are given by Q=Q 1Q 2, Z=Z 1Z 2. The eigenvalues are obtained from the diagonal elements (or blocks) of the pair S,T.
3. | Given the eigenvalues, the eigenvectors of the pair S,T can be computed, and optionally transformed to those of H,R or A,B.
The accuracy with which eigenvalues can be obtained can often be improved by balancing a matrix pair. This is discussed further in Section 2.14.8 below.

2.13 The Sylvester Equation and the Generalized Sylvester Equation

The Sylvester equation is a matrix equation of the form
AX+XB=C,
where A, B, and C are given matrices with A being m by m, B an n by n matrix and C, and the solution matrix X, m by n matrices. The solution of a special case of this equation occurs in the computation of the condition number for an invariant subspace, but a combination of routines in this chapter allows the solution of the general Sylvester equation.
Routines are also provided for solving a special case of the generalized Sylvester equations
AR-LB=C ,  DR-LE=F ,
where A,D, B,E and C,F are given matrix pairs, and R and L are the solution matrices.

2.14 Error and Perturbation Bounds and Condition Numbers

In this section we discuss the effects of rounding errors in the solution process and the effects of uncertainties in the data, on the solution to the problem. A number of the routines in this chapter return information, such as condition numbers, that allow these effects to be assessed. First we discuss some notation used in the error bounds of later sections.
The bounds usually contain the factor p n (or p m,n), which grows as a function of the matrix dimension n (or matrix dimensions m and n). It measures how errors can grow as a function of the matrix dimension, and represents a potentially different function for each problem. In practice, it usually grows just linearly; p n≤10 n is often true, although generally only much weaker bounds can be actually proved. We normally describe p n as a ‘modestly growing’ function of n. For detailed derivations of various p n, see Golub and Van Loan (2012) and Wilkinson (1965).
For linear equation (see Chapter F07) and least squares solvers, we consider bounds on the relative error x-x^/x in the computed solution x^, where x is the true solution. For eigenvalue problems we consider bounds on the error λi-λ^i in the ith computed eigenvalue λ^i, where λi is the true ith eigenvalue. For singular value problems we similarly consider bounds σi-σ^i.
Bounding the error in computed eigenvectors and singular vectors v^i is more subtle because these vectors are not unique: even though we restrict v^i 2=1 and vi 2=1, we may still multiply them by arbitrary constants of absolute value 1. So to avoid ambiguity we bound the angular difference between v^i and the true vector vi, so that
θ vi,v^i = acute angle between ​vi​ and ​v^i = arccos viH v^i. (2)
Here arccos θ is in the standard range: 0≤arccos θ<π. When θ vi,v^i is small, we can choose a constant α with absolute value 1 so that α vi-v^i 2≈θ vi,v^i.
In addition to bounds for individual eigenvectors, bounds can be obtained for the spaces spanned by collections of eigenvectors. These may be much more accurately determined than the individual eigenvectors which span them. These spaces are called invariant subspaces in the case of eigenvectors, because if v is any vector in the space, Av is also in the space, where A is the matrix. Again, we will use angle to measure the difference between a computed space S^ and the true space S:
θ S,S^ = acute angle between ​S​ and ​S^ = max s∈S s≠0 min s^∈S^ s^≠0 θ s,s^   or   max s^∈S^ s^≠0 min s∈S s≠0 θ s,s^ (3)
θ S,S^ may be computed as follows. Let S be a matrix whose columns are orthonormal and span⁡S. Similarly let S^ be an orthonormal matrix with columns spanning S^. Then
θ S,S^=arccos⁡σmin SH S^.
Finally, we remark on the accuracy of the bounds when they are large. Relative errors like x^-x/x and angular errors like θ v^i,vi are only of interest when they are much less than 1. Some stated bounds are not strictly true when they are close to 1, but rigorous bounds are much more complicated and supply little extra information in the interesting case of small errors. These bounds are indicated by using the symbol ≲, or ‘approximately less than’, instead of the usual ≤. Thus, when these bounds are close to 1 or greater, they indicate that the computed answer may have no significant digits at all, but do not otherwise bound the error.
A number of routines in this chapter return error estimates and/or condition number estimates directly. In other cases Anderson et al. (1999) gives code fragments to illustrate the computation of these estimates, and a number of the Chapter F08 example programs, for the driver routines, implement these code fragments.

2.14.1 Least squares problems

The conventional error analysis of linear least squares problems goes as follows. The problem is to find the x minimizing Ax-b 2. Let x^ be the solution computed using one of the methods described above. We discuss the most common case, where A is overdetermined (i.e., has more rows than columns) and has full rank.
Then the computed solution x^ has a small normwise backward error. In other words x^ minimizes A+E x^-b+f 2, where
max E 2 A 2 , f 2 b 2 ≤ p n ε
and p n is a modestly growing function of n and ε is the machine precision. Let κ 2 A=σmax A/σmin A, ρ=Ax-b 2, and sin θ=ρ/b 2. Then if p n ε is small enough, the error x^-x is bounded by
x-x^2 x 2 ≲p n ε 2 κ 2 A cos θ +tan θ κ 22 A .
If A is rank-deficient, the problem can be regularized by treating all singular values less than a user-specified threshold as exactly zero. See Golub and Van Loan (2012) for error bounds in this case, as well as for the underdetermined case.
The solution of the overdetermined, full-rank problem may also be characterised as the solution of the linear system of equations
I A AT 0 r x = b 0 .
By solving this linear system (see Chapter F07) component-wise error bounds can also be obtained (see Arioli et al. (1989)).

2.14.2 The singular value decomposition

The usual error analysis of the SVD algorithm is as follows (see Golub and Van Loan (2012)).
The computed SVD, U^Σ^V^T, is nearly the exact SVD of A+E, i.e., A+E=U^+δ U^Σ^V^+δ V^ is the true SVD, so that U^+δ U^ and V^+δ V^ are both orthogonal, where E 2/A 2≤p m,n ε, δ U^≤p m,n ε, and δ V^≤p m,n ε. Here p m,n is a modestly growing function of m and n and ε is the machine precision. Each computed singular value σ^i differs from the true σi by an amount satisfying the bound
σ^i-σi≤p m,n ε σ 1.
Thus large singular values (those near σ 1) are computed to high relative accuracy and small ones may not be.
The angular difference between the computed left singular vector u^i and the true ui satisfies the approximate bound
θ u^i,ui≲p m,n ε A 2 gapi
where
gap i = min j≠i σi-σj
is the absolute gap between σi and the nearest other singular value. Thus, if σi is close to other singular values, its corresponding singular vector ui may be inaccurate. The same bound applies to the computed right singular vector v^i and the true vector vi. The gaps may be easily obtained from the computed singular values.
Let S^ be the space spanned by a collection of computed left singular vectors u^i,i∈I, where I is a subset of the integers from 1 to n. Let S be the corresponding true space. Then
θ S^,S≲p m,n ε A 2 gapI .
where
gapI=min σi-σj   for ​ i∈I,j∉I
is the absolute gap between the singular values in I and the nearest other singular value. Thus, a cluster of close singular values which is far away from any other singular value may have a well determined space S^ even if its individual singular vectors are ill-conditioned. The same bound applies to a set of right singular vectors v^i,i∈I.
In the special case of bidiagonal matrices, the singular values and singular vectors may be computed much more accurately (see Demmel and Kahan (1990)). A bidiagonal matrix B has nonzero entries only on the main diagonal and the diagonal immediately above it (or immediately below it). Reduction of a dense matrix to bidiagonal form B can introduce additional errors, so the following bounds for the bidiagonal case do not apply to the dense case.
Using the routines in this chapter, each computed singular value of a bidiagonal matrix is accurate to nearly full relative accuracy, no matter how tiny it is, so that
σ^i-σi≤p m,n ε σi.
The computed left singular vector u^i has an angular error at most about
θ u^i,ui≲p m,n ε relgapi
where
relgapi= min j≠i σi-σj / σi+σj
is the relative gap between σi and the nearest other singular value. The same bound applies to the right singular vector v^i and vi. Since the relative gap may be much larger than the absolute gap, this error bound may be much smaller than the previous one. The relative gaps may be easily obtained from the computed singular values.

2.14.3 The symmetric eigenproblem

The usual error analysis of the symmetric eigenproblem is as follows (see Parlett (1998)).
The computed eigendecomposition Z^Λ^Z^T is nearly the exact eigendecomposition of A+E, i.e., A+E=Z^+δ Z^Λ^Z^+δ Z^T is the true eigendecomposition so that Z^+δ Z^ is orthogonal, where E 2/A 2≤p n ε and δ Z^2≤p n ε and p n is a modestly growing function of n and ε is the machine precision. Each computed eigenvalue λ^i differs from the true λi by an amount satisfying the bound
λ^i-λi≤p n ε A 2.
Thus large eigenvalues (those near max i λi = A 2 ) are computed to high relative accuracy and small ones may not be.
The angular difference between the computed unit eigenvector z^i and the true zi satisfies the approximate bound
θ z^i,zi≲p n ε A 2 gapi
if p n ε is small enough, where
gapi= min j≠i λi-λj
is the absolute gap between λi and the nearest other eigenvalue. Thus, if λi is close to other eigenvalues, its corresponding eigenvector zi may be inaccurate. The gaps may be easily obtained from the computed eigenvalues.
Let S^ be the invariant subspace spanned by a collection of eigenvectors z^i,i∈I, where I is a subset of the integers from 1 to n. Let S be the corresponding true subspace. Then
θ S^,S≲p n ε A 2 gapI
where
gapI=min λi-λj   for ​ i∈I,j∉I
is the absolute gap between the eigenvalues in I and the nearest other eigenvalue. Thus, a cluster of close eigenvalues which is far away from any other eigenvalue may have a well determined invariant subspace S^ even if its individual eigenvectors are ill-conditioned.
In the special case of a real symmetric tridiagonal matrix T, routines in this chapter can compute the eigenvalues and eigenvectors much more accurately. See Anderson et al. (1999) for further details.

2.14.4 The generalized symmetric-definite eigenproblem

The three types of problem to be considered are A-λB, AB-λI and BA-λI. In each case A and B are real symmetric (or complex Hermitian) and B is positive definite. We consider each case in turn, assuming that routines in this chapter are used to transform the generalized problem to the standard symmetric problem, followed by the solution of the symmetric problem. In all cases
gapi= min j≠i λi-λj
is the absolute gap between λi and the nearest other eigenvalue.
1. A-λB. The computed eigenvalues λ^i can differ from the true eigenvalues λi by an amount
λ^i-λi≲p n ε B-1 2A 2.
The angular difference between the computed eigenvector z^i and the true eigenvector zi is
θ z^i,zi ≲ p n ε B-1 2 A 2 κ 2 B 1/2 gapi .
2. AB-λI or BA-λI. The computed eigenvalues λ^i can differ from the true eigenvalues λi by an amount
λ^i-λi≲p n ε B 2A 2.
The angular difference between the computed eigenvector z^i and the true eigenvector zi is
θ z^i,zi ≲ p n ε B 2 A 2 κ 2 B 1/2 gapi .
These error bounds are large when B is ill-conditioned with respect to inversion (κ 2 B is large). It is often the case that the eigenvalues and eigenvectors are much better conditioned than indicated here. One way to get tighter bounds is effective when the diagonal entries of B differ widely in magnitude, as for example with a graded matrix.
1. | A-λB. Let D = diag b 11-1/2 ,…, b nn -1/2 be a diagonal matrix. Then replace B by DBD and A by DAD in the above bounds.
2. | AB-λI or BA-λI. Let D=diag b 11-1/2,…,b nn -1/2 be a diagonal matrix. Then replace B by DBD and A by D-1 A D-1 in the above bounds.
Further details can be found in Anderson et al. (1999).

2.14.5 The nonsymmetric eigenproblem

The nonsymmetric eigenvalue problem is more complicated than the symmetric eigenvalue problem. In this section, we just summarise the bounds. Further details can be found in Anderson et al. (1999).
We let λ^i be the ith computed eigenvalue and λi the ith true eigenvalue. Let v^i be the corresponding computed right eigenvector, and vi the true right eigenvector (so A vi=λi vi). If I is a subset of the integers from 1 to n, we let λI denote the average of the selected eigenvalues: λI=∑i∈I λi/ ∑i∈I 1, and similarly for λ^I. We also let SI denote the subspace spanned by vi,i∈I; it is called a right invariant subspace because if v is any vector in SI then Av is also in SI. S^I is the corresponding computed subspace.
The algorithms for the nonsymmetric eigenproblem are normwise backward stable: they compute the exact eigenvalues, eigenvectors and invariant subspaces of slightly perturbed matrices A+E , where E ≤ p n ε A . Some of the bounds are stated in terms of E 2 and others in terms of E F; one may use p n ε for either quantity.
Routines are provided so that, for each (λ^i,v^i) pair the two values si and sepi, or for a selected subset I of eigenvalues the values sI and sepI can be obtained, for which the error bounds in Table 2 are true for sufficiently small E, (which is why they are called asymptotic):
Simple eigenvalue | λ^i-λi≲E 2/si
Eigenvalue cluster | λ^I-λI≲E 2/sI
Eigenvector | θ v^i,vi≲E F/sepi
Invariant subspace | θ S^I,SI≲E F/sepI
Table 2
Asymptotic error bounds for the nonsymmetric eigenproblem
If the problem is ill-conditioned, the asymptotic bounds may only hold for extremely small E. The global error bounds of Table 3 are guaranteed to hold for all E F<s×sep/4:
Simple eigenvalue | λ^i-λi≤n E 2/si | Holds for all E
Eigenvalue cluster | λ^I-λI≤2 E 2/sI | Requires E F<sI×sepI/4
Eigenvector | θ v^i,vi≤arctan 2 E F/sepi-4 E F/si | Requires E F<si×sepi/4
Invariant subspace | θ S^I,SI≤arctan 2 E F/sepI-4 E F/sI | Requires E F<sI×sepI/4
Table 3
Global error bounds for the nonsymmetric eigenproblem

2.14.6 Balancing and condition for the nonsymmetric eigenproblem

There are two preprocessing steps one may perform on a matrix A in order to make its eigenproblem easier. The first is permutation, or reordering the rows and columns to make A more nearly upper triangular (closer to Schur form): A′=PA PT, where P is a permutation matrix. If A′ is permutable to upper triangular form (or close to it), then no floating-point operations (or very few) are needed to reduce it to Schur form. The second is scaling by a diagonal matrix D to make the rows and columns of A′ more nearly equal in norm: A′′=D A′D-1. Scaling can make the matrix norm smaller with respect to the eigenvalues, and so possibly reduce the inaccuracy contributed by roundoff (see Chapter 11 of Wilkinson and Reinsch (1971)). We refer to these two operations as balancing.
Permuting has no effect on the condition numbers or their interpretation as described previously. Scaling, however, does change their interpretation and further details can be found in Anderson et al. (1999).

2.14.7 The generalized nonsymmetric eigenvalue problem

The algorithms for the generalized nonsymmetric eigenvalue problem are normwise backward stable: they compute the exact eigenvalues (as the pairs α,β), eigenvectors and deflating subspaces of slightly perturbed pairs A+E,B+F, where
E,F F≤p n ε A,B F.
Asymptotic and global error bounds can be obtained, which are generalizations of those given in Tables 2 and 3. See Section 4.11 of Anderson et al. (1999) for details. Routines are provided to compute estimates of reciprocal conditions numbers for eigenvalues and eigenspaces.

2.14.8 Balancing the generalized eigenvalue problem

As with the standard nonsymmetric eigenvalue problem, there are two preprocessing steps one may perform on a matrix pair A,B in order to make its eigenproblem easier; permutation and scaling, which together are referred to as balancing, as indicated in the following two steps.
1. The balancing routine first attempts to permute A and B to block upper triangular form by a similarity transformation:
PA PT=F= F 11 F 12 F 13 F 22 F 23 F 33 , PB PT=G= G 11 G 12 G 13 G 22 G 23 G 33 ,
where P is a permutation matrix, F 11, F 33, G 11 and G 33 are upper triangular. Then the diagonal elements of the matrix F 11,G 11 and G 33,H 33 are generalized eigenvalues of A,B. The rest of the generalized eigenvalues are given by the matrix pair F 22,G 22. Subsequent operations to compute the eigenvalues of A,B need only be applied to the matrix F 22,G 22; this can save a significant amount of work if F 22,G 22 is smaller than the original matrix pair A,B. If no suitable permutation exists (as is often the case), then there is no gain in efficiency or accuracy.
2. The balancing routine applies a diagonal similarity transformation to F,G, to make the rows and columns of F 22,G 22 as close as possible in the norm:
DF D-1= I D 22 I F 11 F 12 F 13 F 22 F 23 F 33 I D 22-1 I , DG D-1= I D 22 I G 11 G 12 G 13 G 22 G 23 G 33 I D 22-1 I .
This transformation usually improves the accuracy of computed generalized eigenvalues and eigenvectors. However, there are exceptional occasions when this transformation increases the norm of the pencil; in this case accuracy could be lower with diagonal balancing.
See Anderson et al. (1999) for further details.

2.14.9 Other problems

Error bounds for other problems such as the generalized linear least squares problem and generalized singular value decomposition can be found in Anderson et al. (1999).

2.15 Block Partitioned Algorithms

A number of the routines in this chapter use what is termed a block partitioned algorithm. This means that at each major step of the algorithm a block of rows or columns is updated, and much of the computation is performed by matrix-matrix operations on these blocks. These matrix-matrix operations make efficient use of computer memory and are key to achieving high performance. See Golub and Van Loan (2012) or Anderson et al. (1999) for more about block partitioned algorithms.
The performance of a block partitioned algorithm varies to some extent with the block size – that is, the number of rows or columns per block. This is a machine-dependent constant, which is set to a suitable value when the library is implemented on each range of machines. Block size affects the amount of workspace that should be supplied to a particular routine. This is discussed in Section 3.4.3.

3 Recommendations on Choice and Use of Available Routines

3.1 Available Routines

The tables in the following sub-sections show the routines which are provided for performing different computations on different types of matrices. Each entry in the table gives the NAG routine name and the LAPACK double precision name(see Section 3.2).
Black box (or driver) routines are provided for the solution of most problems. In a number of cases there are simple drivers, which just return the solution to the problem, as well as expert drivers, which return additional information, such as condition number estimates, and may offer additional facilities such as balancing. The following sub-sections give tables for the driver routines.

3.1.1 Driver routines

3.1.1.1 Linear least squares problems (LLS)
Operation | real | complex
solve LLS using QR or LQ factorization solve LLS using complete orthogonal factorization solve LLS using SVD solve LLS using divide-and-conquer SVD | F08AAF (DGELS) F08BAF (DGELSY) F08KAF (DGELSS) F08KCF (DGELSD) | F08ANF (ZGELS) F08BNF (ZGELSY) F08KNF (ZGELSS) F08KQF (ZGELSD)
3.1.1.2 Generalized linear least squares problems (LSE and GLM)
Operation | real | complex
solve LSE problem using GRQ solve GLM problem using GQR | F08ZAF (DGGLSE) F08ZBF (DGGGLM) | F08ZNF (ZGGLSE) F08ZPF (ZGGGLM)
3.1.1.3 Symmetric eigenvalue problems (SEP)
Function and storage scheme | real | complex
simple driver divide-and-conquer driver expert driver RRR driver | F08FAF (DSYEV) F08FCF (DSYEVD) F08FBF (DSYEVX) F08FDF (DSYEVR) | F08FNF (ZHEEV) F08FQF (ZHEEVD) F08FPF (ZHEEVX) F08FRF (ZHEEVR)
packed storage simple driver divide-and-conquer driver expert driver | F08GAF (DSPEV) F08GCF (DSPEVD) F08GBF (DSPEVX) | F08GNF (ZHPEV) F08GQF (ZHPEVD) F08GPF (ZHPEVX)
band matrix simple driver divide-and-conquer driver expert driver | F08HAF (DSBEV) F08HCF (DSBEVD) F08HBF (DSBEVX) | F08HNF (ZHBEV) F08HQF (ZHBEVD) F08HPF (ZHBEVX)
tridiagonal matrix simple driver divide-and-conquer driver expert driver RRR driver | F08JAF (DSTEV) F08JCF (DSTEVD) F08JBF (DSTEVX) F08JDF (DSTEVR) |
3.1.1.4 Nonsymmetric eigenvalue problem (NEP)
Function and storage scheme | real | complex
simple driver for Schur factorization expert driver for Schur factorization simple driver for eigenvalues/vectors expert driver for eigenvalues/vectors | F08PAF (DGEES) F08PBF (DGEESX) F08NAF (DGEEV) F08NBF (DGEEVX) | F08PNF (ZGEES) F08PPF (ZGEESX) F08NNF (ZGEEV) F08NPF (ZGEEVX)
3.1.1.5 Singular value decomposition (SVD)
Function and storage scheme | real | complex
simple driver divide-and-conquer driver simple driver for one-sided Jacobi SVD expert driver for one-sided Jacobi SVD | F08KBF (DGESVD) F08KDF (DGESDD) F08KJF (DGESVJ) F08KHF (DGEJSV) | F08KPF (ZGESVD) F08KRF (ZGESDD)
3.1.1.6 Generalized symmetric definite eigenvalue problems (GSEP)
Function and storage scheme | real | complex
simple driver divide-and-conquer driver expert driver | F08SAF (DSYGV) F08SCF (DSYGVD) F08SBF (DSYGVX) | F08SNF (ZHEGV) F08SQF (ZHEGVD) F08SPF (ZHEGVX)
packed storage simple driver divide-and-conquer driver expert driver | F08TAF (DSPGV) F08TCF (DSPGVD) F08TBF (DSPGVX) | F08TNF (ZHPGV) F08TQF (ZHPGVD) F08TPF (ZHPGVX)
band matrix simple driver divide-and-conquer driver expert driver | F08UAF (DSBGV) F08UCF (DSBGVD) F08UBF (DSBGVX) | F08UNF (ZHBGV) F08UQF (ZHBGVD) F08UPF (ZHBGVX)
3.1.1.7 Generalized nonsymmetric eigenvalue problem (GNEP)
Function and storage scheme | real | complex
simple driver for Schur factorization expert driver for Schur factorization simple driver for eigenvalues/vectors expert driver for eigenvalues/vectors | F08XCF (DGGES3) F08XBF (DGGESX) F08WCF (DGGEV3) F08WBF (DGGEVX) | F08XQF (ZGGES3) F08XPF (ZGGESX) F08WQF (ZGGEV3) F08WPF (ZGGEVX)
3.1.1.8 Generalized singular value decomposition (GSVD)
Function and storage scheme | real | complex
singular values/vectors | F08VCF (DGGSVD3) | F08VQF (ZGGSVD3)

3.1.2 Computational routines

It is possible to solve problems by calling two or more routines in sequence. Some common sequences of routines are indicated in the tables in the following sub-sections; an asterisk (*) against a routine name means that the sequence of calls is illustrated in the example program for that routine.
3.1.2.1 Orthogonal factorizations
Routines are provided for QR factorization (with and without column pivoting), and for LQ, QL and RQ factorizations (without pivoting only), of a general real or complex rectangular matrix. A routine is also provided for the RQ factorization of a real or complex upper trapezoidal matrix. (LAPACK refers to this as the RZ factorization.)
The factorization routines do not form the matrix Q explicitly, but represent it as a product of elementary reflectors (see Section 3.3.6). Additional routines are provided to generate all or part of Q explicitly if it is required, or to apply Q in its factored form to another matrix (specifically to compute one of the matrix products QC, QT C, CQ or C QT with QT replaced by QH if C and Q are complex).
 | Factorize without pivoting | Factorize with pivoting | Factorize (blocked) | Generate matrix Q | Apply matrix Q | Apply Q (blocked)
QR factorization, real matrices | F08AEF (DGEQRF) | F08BFF (DGEQP3) | F08ABF (DGEQRT) | F08AFF (DORGQR) | F08AGF (DORMQR) | F08ACF (DGEMQRT)
QR factorization, real triangular-pentagonal |  |  | F08BBF (DTPQRT) |  |  | F08BCF (DTPMQRT)
LQ factorization, real matrices | F08AHF (DGELQF) |  |  | F08AJF (DORGLQ) | F08AKF (DORMLQ) |
QL factorization, real matrices | F08CEF (DGEQLF) |  |  | F08CFF (DORGQL) | F08CGF (DORMQL) |
RQ factorization, real matrices | F08CHF (DGERQF) |  |  | F08CJF (DORGRQ) | F08CKF (DORMRQ) |
RQ factorization, real upper trapezoidal matrices | F08BHF (DTZRZF) |  |  |  | F08BKF (DORMRZ) |
QR factorization, complex matrices | F08ASF (ZGEQRF) | F08BTF (ZGEQP3) | F08APF (ZGEQRT) | F08ATF (ZUNGQR) | F08AUF (ZUNMQR) | F08AQF (ZGEMQRT)
QR factorization, complex triangular-pentagonal |  |  | F08BPF (ZTPQRT) |  |  | F08BQF (ZTPMQRT)
LQ factorization, complex matrices | F08AVF (ZGELQF) |  |  | F08AWF (ZUNGLQ) | F08AXF (ZUNMLQ) |
QL factorization, complex matrices | F08CSF (ZGEQLF) |  |  | F08CTF (ZUNGQL) | F08CUF (ZUNMQL) |
RQ factorization, complex matrices | F08CVF (ZGERQF) |  |  | F08CWF (ZUNGRQ) | F08CXF (ZUNMRQ) |
RQ factorization, complex upper trapezoidal matrices | F08BVF (ZTZRZF) |  |  |  | F08BXF (ZUNMRZ) |
To solve linear least squares problems, as described in Sections 2.2.1 or 2.2.3, routines based on the QR factorization can be used:
real data, full-rank problem | F08AAF (DGELS), F08AEF (DGEQRF) and F08AGF (DORMQR), F08ABF (DGEQRT) and F08ACF (DGEMQRT), F06YJF (DTRSM)
complex data, full-rank problem | F08ANF (ZGELS), F08ASF (ZGEQRF) and F08AUF (ZUNMQR), F08APF (ZGEQRT) and F08AQF (ZGEMQRT), F06ZJF (ZTRSM)
real data, rank-deficient problem | F08BFF (DGEQP3)*, F06YJF (DTRSM), F08AGF (DORMQR)
complex data, rank-deficient problem | F08BTF (ZGEQP3)*, F06ZJF (ZTRSM), F08AUF (ZUNMQR)
To find the minimum norm solution of under-determined systems of linear equations, as described in Section 2.2.2, routines based on the LQ factorization can be used:
real data, full-rank problem | F08AHF (DGELQF)*, F06YJF (DTRSM), F08AKF (DORMLQ)
complex data, full-rank problem | F08AVF (ZGELQF)*, F06ZJF (ZTRSM), F08AXF (ZUNMLQ)
3.1.2.2 Generalized orthogonal factorizations
Routines are provided for the generalized QR and RQ factorizations of real and complex matrix pairs.
 | Factorize
Generalized QR factorization, real matrices | F08ZEF (DGGQRF)
Generalized RQ factorization, real matrices | F08ZFF (DGGRQF)
Generalized QR factorization, complex matrices | F08ZSF (ZGGQRF)
Generalized RQ factorization, complex matrices | F08ZTF (ZGGRQF)
3.1.2.3 Singular value problems
Routines are provided to reduce a general real or complex rectangular matrix A to real bidiagonal form B by an orthogonal transformation A=QB PT (or by a unitary transformation A=QB PH if A is complex). Different routines allow a full matrix A to be stored conventionally (see Section 3.3.1), or a band matrix to use band storage (see Section 3.3.4 in the F07 Chapter Introduction).
The routines for reducing full matrices do not form the matrix Q or P explicitly; additional routines are provided to generate all or part of them, or to apply them to another matrix, as with the routines for orthogonal factorizations. Explicit generation of Q or P is required before using the bidiagonal QR algorithm to compute left or right singular vectors of A.
The routines for reducing band matrices have options to generate Q or P if required.
Further routines are provided to compute all or part of the singular value decomposition of a real bidiagonal matrix; the same routines can be used to compute the singular value decomposition of a real or complex matrix that has been reduced to bidiagonal form.
 | Reduce to bidiagonal form | Generate matrix Q or PT | Apply matrix Q or P | Reduce band matrix to bidiagonal form | SVD of bidiagonal form (QR algorithm) | SVD of bidiagonal form (divide and conquer)
real matrices | F08KEF (DGEBRD) | F08KFF (DORGBR) | F08KGF (DORMBR) | F08LEF (DGBBRD) | F08MEF (DBDSQR) | F08MDF (DBDSDC)
complex matrices | F08KSF (ZGEBRD) | F08KTF (ZUNGBR) | F08KUF (ZUNMBR) | F08LSF (ZGBBRD) | F08MSF (ZBDSQR) |
Given the singular values, F08FLF (DDISNA) is provided to compute the reciprocal condition numbers for the left or right singular vectors of a real or complex matrix.
To compute the singular values and vectors of a rectangular matrix, as described in Section 2.3, use the following sequence of calls:
Rectangular matrix (standard storage)
real matrix, singular values and vectors | F08KEF (DGEBRD), F08KFF (DORGBR)*, F08MEF (DBDSQR)
complex matrix, singular values and vectors | F08KSF (ZGEBRD), F08KTF (ZUNGBR)*, F08MSF (ZBDSQR)
Rectangular matrix (banded)
real matrix, singular values and vectors | F08LEF (DGBBRD), F08KFF (DORGBR), F08MEF (DBDSQR)
complex matrix, singular values and vectors | F08LSF (ZGBBRD), F08KTF (ZUNGBR), F08MSF (ZBDSQR)
To use the singular value decomposition to solve a linear least squares problem, as described in Section 2.4, the following routines are required:
real data | F06YAF (DGEMM), F08KEF (DGEBRD), F08KFF (DORGBR), F08KGF (DORMBR), F08MEF (DBDSQR)
complex data | F06ZAF (ZGEMM), F08KSF (ZGEBRD), F08KTF (ZUNGBR), F08KUF (ZUNMBR), F08MSF (ZBDSQR)
3.1.2.4 Generalized singular value decomposition
Routines are provided to compute the generalized SVD of a real or complex matrix pair A,B in upper trapezoidal form. Routines are also provided to reduce a general real or complex matrix pair to the required upper trapezoidal form.
 | Reduce to trapezoidal form | Generalized SVD of trapezoidal form
real matrices | F08VGF (DGGSVP3) | F08YEF (DTGSJA)
complex matrices | F08VUF (ZGGSVP3) | F08YSF (ZTGSJA)
Routines are provided for the full CS decomposition of orthogonal and unitary matrices expressed as 2 by 2 partitions of submatrices. For real orthogonal matrices the CS decomposition is performed by F08RAF (DORCSD), while for unitary matrices the equivalent routine is F08RNF (ZUNCSD).
3.1.2.5 Symmetric eigenvalue problems
Routines are provided to reduce a real symmetric or complex Hermitian matrix A to real tridiagonal form T by an orthogonal similarity transformation A=QT QT (or by a unitary transformation A=QT QH if A is complex). Different routines allow a full matrix A to be stored conventionally (see Section 3.3.1 in the F07 Chapter Introduction) or in packed storage (see Section 3.3.2 in the F07 Chapter Introduction); or a band matrix to use band storage (see Section 3.3.4 in the F07 Chapter Introduction).
The routines for reducing full matrices do not form the matrix Q explicitly; additional routines are provided to generate Q, or to apply it to another matrix, as with the routines for orthogonal factorizations. Explicit generation of Q is required before using the QR algorithm to find all the eigenvectors of A; application of Q to another matrix is required after eigenvectors of T have been found by inverse iteration, in order to transform them to eigenvectors of A.
The routines for reducing band matrices have an option to generate Q if required.
 | Reduce to tridiagonal form | Generate matrix Q | Apply matrix Q
real symmetric matrices | F08FEF (DSYTRD) | F08FFF (DORGTR) | F08FGF (DORMTR)
real symmetric matrices (packed storage) | F08GEF (DSPTRD) | F08GFF (DOPGTR) | F08GGF (DOPMTR)
real symmetric band matrices | F08HEF (DSBTRD) |  |
complex Hermitian matrices | F08FSF (ZHETRD) | F08FTF (ZUNGTR) | F08FUF (ZUNMTR)
complex Hermitian matrices (packed storage) | F08GSF (ZHPTRD) | F08GTF (ZUPGTR) | F08GUF (ZUPMTR)
complex Hermitian band matrices | F08HSF (ZHBTRD) |  |
Given the eigenvalues, F08FLF (DDISNA) is provided to compute the reciprocal condition numbers for the eigenvectors of a real symmetric or complex Hermitian matrix.
A variety of routines are provided to compute eigenvalues and eigenvectors of the real symmetric tridiagonal matrix T, some computing all eigenvalues and eigenvectors, some computing selected eigenvalues and eigenvectors. The same routines can be used to compute eigenvalues and eigenvectors of a real symmetric or complex Hermitian matrix which has been reduced to tridiagonal form.
Eigenvalues and eigenvectors of real symmetric tridiagonal matrices:
The original (non-reduced) matrix is Real Symmetric or Complex Hermitian
all eigenvalues (root-free QR algorithm) | F08JFF (DSTERF)
all eigenvalues (root-free QR algorithm called by divide-and-conquer) | F08JCF (DSTEVD) or F08JHF (DSTEDC)
all eigenvalues (RRR) | F08JLF (DSTEGR)
selected eigenvalues (bisection) | F08JJF (DSTEBZ)
The original (non-reduced) matrix is Real Symmetric
all eigenvalues and eigenvectors (QR algorithm) | F08JEF (DSTEQR)
all eigenvalues and eigenvectors (divide-and-conquer) | F08JCF (DSTEVD) or F08JHF (DSTEDC)
all eigenvalues and eigenvectors (RRR) | F08JLF (DSTEGR)
all eigenvalues and eigenvectors (positive definite case) | F08JGF (DPTEQR)
selected eigenvectors (inverse iteration) | F08JKF (DSTEIN)
The original (non-reduced) matrix is Complex Hermitian
all eigenvalues and eigenvectors (QR algorithm) | F08JSF (ZSTEQR)
all eigenvalues and eigenvectors (divide and conquer) | F08JVF (ZSTEDC)
all eigenvalues and eigenvectors (RRR) | F08JYF (ZSTEGR)
all eigenvalues and eigenvectors (positive definite case) | F08JUF (ZPTEQR)
selected eigenvectors (inverse iteration) | F08JXF (ZSTEIN)
The following sequences of calls may be used to compute various combinations of eigenvalues and eigenvectors, as described in Section 2.7.
Sequences for computing eigenvalues and eigenvectors
Real Symmetric matrix (standard storage)
all eigenvalues and eigenvectors (using divide-and-conquer) | F08FCF (DSYEVD)
all eigenvalues and eigenvectors (using QR algorithm) | F08FEF (DSYTRD), F08FFF (DORGTR)*, F08JEF (DSTEQR)
all eigenvalues and eigenvectors (RRR) | F08FEF (DSYTRD), F08FGF (DORMTR), F08JLF (DSTEGR)
selected eigenvalues and eigenvectors (bisection and inverse iteration) | F08FEF (DSYTRD), F08FGF (DORMTR), F08JJF (DSTEBZ), F08JKF (DSTEIN)*
Real Symmetric matrix (packed storage)
all eigenvalues and eigenvectors (using divide-and-conquer) | F08GCF (DSPEVD)
all eigenvalues and eigenvectors (using QR algorithm) | F08GEF (DSPTRD), F08GFF (DOPGTR) and F08JEF (DSTEQR)
all eigenvalues and eigenvectors (RRR) | F08GEF (DSPTRD), F08GGF (DOPMTR), F08JLF (DSTEGR)
selected eigenvalues and eigenvectors (bisection and inverse iteration) | F08GEF (DSPTRD), F08GGF (DOPMTR), F08JJF (DSTEBZ), F08JKF (DSTEIN)*
Real Symmetric banded matrix
all eigenvalues and eigenvectors (using divide-and-conquer) | F08HCF (DSBEVD)
all eigenvalues and eigenvectors (using QR algorithm) | F08HEF (DSBTRD)*, F08JEF (DSTEQR)
Complex Hermitian matrix (standard storage)
all eigenvalues and eigenvectors (using divide-and-conquer) | F08FQF (ZHEEVD)
all eigenvalues and eigenvectors (using QR algorithm) | F08FSF (ZHETRD), F08FTF (ZUNGTR)*, F08JSF (ZSTEQR)
all eigenvalues and eigenvectors (RRR) | F08FSF (ZHETRD), F08FUF (ZUNMTR), F08JYF (ZSTEGR)
selected eigenvalues and eigenvectors (bisection and inverse iteration) | F08FSF (ZHETRD), F08FUF (ZUNMTR), F08JJF (DSTEBZ), F08JXF (ZSTEIN)*
Complex Hermitian matrix (packed storage)
all eigenvalues and eigenvectors (using divide-and-conquer) | F08GQF (ZHPEVD)
all eigenvalues and eigenvectors (using QR algorithm) | F08GSF (ZHPTRD), F08GTF (ZUPGTR)*, F08JSF (ZSTEQR)
all eigenvalues and eigenvectors (RRR) | F08GSF (ZHPTRD), F08GUF (ZUPMTR) and F08JYF (ZSTEGR)
selected eigenvalues and eigenvectors (bisection and inverse iteration) | F08GSF (ZHPTRD), F08GUF (ZUPMTR), F08JJF (DSTEBZ), F08JXF (ZSTEIN)*
Complex Hermitian banded matrix
all eigenvalues and eigenvectors (using divide-and-conquer) | F08HQF (ZHBEVD)
all eigenvalues and eigenvectors (using QR algorithm) | F08HSF (ZHBTRD)*, F08JSF (ZSTEQR)
3.1.2.6 Generalized symmetric-definite eigenvalue problems
Routines are provided for reducing each of the problems Ax=λBx, ABx=λx or BAx=λx to an equivalent standard eigenvalue problem Cy=λy. Different routines allow the matrices to be stored either conventionally or in packed storage. The positive definite matrix B must first be factorized using a routine from Chapter F07. There is also a routine which reduces the problem Ax=λBx where A and B are banded, to an equivalent banded standard eigenvalue problem; this uses a split Cholesky factorization for which a routine in Chapter F08 is provided.
 | Reduce to standard problem | Reduce to standard problem (packed storage) | Reduce to standard problem (band matrices)
real symmetric matrices | F08SEF (DSYGST) | F08TEF (DSPGST) | F08UEF (DSBGST)
complex Hermitian matrices | F08SSF (ZHEGST) | F08TSF (ZHPGST) | F08USF (ZHBGST)
The equivalent standard problem can then be solved using the routines discussed in Section 3.1.2.5. For example, to compute all the eigenvalues, the following routines must be called:
real symmetric-definite problem | F07FDF (DPOTRF), F08SEF (DSYGST)*, F08FEF (DSYTRD), F08JFF (DSTERF)
real symmetric-definite problem, packed storage | F07GDF (DPPTRF), F08TEF (DSPGST)*, F08GEF (DSPTRD), F08JFF (DSTERF)
real symmetric-definite banded problem | F08UFF (DPBSTF)*, F08UEF (DSBGST)*, F08HEF (DSBTRD), F08JFF (DSTERF)
complex Hermitian-definite problem | F07FRF (ZPOTRF), F08SSF (ZHEGST)*, F08FSF (ZHETRD), F08JFF (DSTERF)
complex Hermitian-definite problem, packed storage | F07GRF (ZPPTRF), F08TSF (ZHPGST)*, F08GSF (ZHPTRD), F08JFF (DSTERF)
complex Hermitian-definite banded problem | F08UTF (ZPBSTF)*, F08USF (ZHBGST)*, F08HSF (ZHBTRD), F08JFF (DSTERF)
If eigenvectors are computed, the eigenvectors of the equivalent standard problem must be transformed back to those of the original generalized problem, as indicated in Section 2.8; routines from Chapter F06 may be used for this.
3.1.2.7 Nonsymmetric eigenvalue problems
Routines are provided to reduce a general real or complex matrix A to upper Hessenberg form H by an orthogonal similarity transformation A=QH QT (or by a unitary transformation A=QH QH if A is complex).
These routines do not form the matrix Q explicitly; additional routines are provided to generate Q, or to apply it to another matrix, as with the routines for orthogonal factorizations. Explicit generation of Q is required before using the QR algorithm on H to compute the Schur vectors; application of Q to another matrix is needed after eigenvectors of H have been computed by inverse iteration, in order to transform them to eigenvectors of A.
Routines are also provided to balance the matrix before reducing it to Hessenberg form, as described in Section 2.14.6. Companion routines are required to transform Schur vectors or eigenvectors of the balanced matrix to those of the original matrix.
 | Reduce to Hessenberg form | Generate matrix Q | Apply matrix Q | Balance | Backtransform vectors after balancing
real matrices | F08NEF (DGEHRD) | F08NFF (DORGHR) | F08NGF (DORMHR) | F08NHF (DGEBAL) | F08NJF (DGEBAK)
complex matrices | F08NSF (ZGEHRD) | F08NTF (ZUNGHR) | F08NUF (ZUNMHR) | F08NVF (ZGEBAL) | F08NWF (ZGEBAK)
Routines are provided to compute the eigenvalues and all or part of the Schur factorization of an upper Hessenberg matrix. Eigenvectors may be computed either from the upper Hessenberg form by inverse iteration, or from the Schur form by back-substitution; these approaches are equally satisfactory for computing individual eigenvectors, but the latter may provide a more accurate basis for a subspace spanned by several eigenvectors.
Additional routines estimate the sensitivities of computed eigenvalues and eigenvectors, as discussed in Section 2.14.5.
 | Eigenvalues and Schur factorization (QR algorithm) | Eigenvectors from Hessenberg form (inverse iteration) | Eigenvectors from Schur factorization | Sensitivities of eigenvalues and eigenvectors
real matrices | F08PEF (DHSEQR) | F08PKF (DHSEIN) | F08QKF (DTREVC) | F08QLF (DTRSNA)
complex matrices | F08PSF (ZHSEQR) | F08PXF (ZHSEIN) | F08QXF (ZTREVC) | F08QYF (ZTRSNA)
Finally routines are provided for reordering the Schur factorization, so that eigenvalues appear in any desired order on the diagonal of the Schur form. The routines F08QFF (DTREXC) and F08QTF (ZTREXC) simply swap two diagonal elements or blocks, and may need to be called repeatedly to achieve a desired order. The routines F08QGF (DTRSEN) and F08QUF (ZTRSEN) perform the whole reordering process for the important special case where a specified cluster of eigenvalues is to appear at the top of the Schur form; if the Schur vectors are reordered at the same time, they yield an orthonormal basis for the invariant subspace corresponding to the specified cluster of eigenvalues. These routines can also compute the sensitivities of the cluster of eigenvalues and the invariant subspace.
 | Reorder Schur factorization | Reorder Schur factorization, find basis for invariant subspace and estimate sensitivities
real matrices | F08QFF (DTREXC) | F08QGF (DTRSEN)
complex matrices | F08QTF (ZTREXC) | F08QUF (ZTRSEN)
The following sequences of calls may be used to compute various combinations of eigenvalues, Schur vectors and eigenvectors, as described in Section 2.11:
real matrix, all eigenvalues and Schur factorization | F08NEF (DGEHRD), F08NFF (DORGHR)*, F08PEF (DHSEQR)
real matrix, all eigenvalues and selected eigenvectors | F08NEF (DGEHRD), F08NGF (DORMHR), F08PEF (DHSEQR), F08PKF (DHSEIN)
real matrix, all eigenvalues and eigenvectors (with balancing) | F08NHF (DGEBAL)*, F08NEF (DGEHRD), F08NFF (DORGHR), F08NJF (DGEBAK), F08PEF (DHSEQR), F08PKF (DHSEIN)
complex matrix, all eigenvalues and Schur factorization | F08NSF (ZGEHRD), F08NTF (ZUNGHR)*, F08PSF (ZHSEQR)
complex matrix, all eigenvalues and selected eigenvectors | F08NSF (ZGEHRD), F08NUF (ZUNMHR), F08PSF (ZHSEQR), F08PXF (ZHSEIN)*
complex matrix, all eigenvalues and eigenvectors (with balancing) | F08NVF (ZGEBAL)*, F08NSF (ZGEHRD), F08NTF (ZUNGHR), F08NWF (ZGEBAK), F08PSF (ZHSEQR), F08PXF (ZHSEIN)
3.1.2.8 Generalized nonsymmetric eigenvalue problems
Routines are provided to reduce a real or complex matrix pair A 1,R 1, where A 1 is general and R 1 is upper triangular, to generalized upper Hessenberg form by orthogonal transformations A 1=Q 1 H Z 1 T, R 1=Q 1 R Z 1 T, (or by unitary transformations A 1=Q 1 H Z 1 H, R=Q 1R 1 Z 1 H, in the complex case). These routines can optionally return Q 1 and/or Z 1. Note that to transform a general matrix pair A,B to the form A 1,R 1 a QR factorization of B (B=Q~R 1) should first be performed and the matrix A 1 obtained as A 1=Q~T A (see Section 3.1.2.1 above).
Routines are also provided to balance a general matrix pair before reducing it to generalized Hessenberg form, as described in Section 2.14.8. Companion routines are provided to transform vectors of the balanced pair to those of the original matrix pair.
 | Reduce to generalized Hessenberg form | Balance | Backtransform vectors after balancing
real matrices | F08WFF (DGGHD3) | F08WHF (DGGBAL) | F08WJF (DGGBAK)
complex matrices | F08WTF (ZGGHD3) | F08WVF (ZGGBAL) | F08WWF (ZGGBAK)
Routines are provided to compute the eigenvalues (as the pairs α,β) and all or part of the generalized Schur factorization of a generalized upper Hessenberg matrix pair. Eigenvectors may be computed from the generalized Schur form by back-substitution.
Additional routines estimate the sensitivities of computed eigenvalues and eigenvectors.
 | Eigenvalues and generalized Schur factorization (QZ algorithm) | Eigenvectors from generalized Schur factorization | Sensitivities of eigenvalues and eigenvectors
real matrices | F08XEF (DHGEQZ) | F08YKF (DTGEVC) | F08YLF (DTGSNA)
complex matrices | F08XSF (ZHGEQZ) | F08YXF (ZTGEVC) | F08YYF (ZTGSNA)
Finally, routines are provided for reordering the generalized Schur factorization so that eigenvalues appear in any desired order on the diagonal of the generalized Schur form. F08YFF (DTGEXC) and F08YTF (ZTGEXC) simply swap two diagonal elements or blocks, and may need to be called repeatedly to achieve a desired order. F08YGF (DTGSEN) and F08YUF (ZTGSEN) perform the whole reordering process for the important special case where a specified cluster of eigenvalues is to appear at the top of the generalized Schur form; if the Schur vectors are reordered at the same time, they yield an orthonormal basis for the deflating subspace corresponding to the specified cluster of eigenvalues. These routines can also compute the sensitivities of the cluster of eigenvalues and the deflating subspace.
 | Reorder generalized Schur factorization | Reorder generalized Schur factorization, find basis for deflating subspace and estimate sensitivites
real matrices | F08YFF (DTGEXC) | F08YGF (DTGSEN)
complex matrices | F08YTF (ZTGEXC) | F08YUF (ZTGSEN)
The following sequences of calls may be used to compute various combinations of eigenvalues, generalized Schur vectors and eigenvectors
real matrix pair, all eigenvalues (with balancing) | F08AEF (DGEQRF), F08AGF (DORMQR) (or F08ABF (DGEQRT), F08ACF (DGEMQRT)), F08WFF (DGGHD3), F08WHF (DGGBAL), F08XEF (DHGEQZ)*
real matrix pair, all eigenvalues and generalized Schur factorization | F08AEF (DGEQRF), F08AFF (DORGQR), F08AGF (DORMQR) (or F08ABF (DGEQRT), F08ACF (DGEMQRT)), F08WFF (DGGHD3), F08XEF (DHGEQZ)
real matrix pair, all eigenvalues and eigenvectors (with balancing) | F06QFF, F06QHF, F08AEF (DGEQRF), F08AFF (DORGQR), F08AGF (DORMQR) (or F08ABF (DGEQRT), F08ACF (DGEMQRT)), F08WFF (DGGHD3), F08WHF (DGGBAL), F08XEF (DHGEQZ), F08YKF (DTGEVC)*, F08WJF (DGGBAK)
complex matrix pair, all eigenvalues (with balancing) | F08ASF (ZGEQRF), F08AUF (ZUNMQR) (or F08APF (ZGEQRT), F08AQF (ZGEMQRT)), F08WTF (ZGGHD3), F08WVF (ZGGBAL), F08XSF (ZHGEQZ)*
complex matrix pair, all eigenvalues and generalized Schur factorization | F08ASF (ZGEQRF), F08ATF (ZUNGQR), F08AUF (ZUNMQR) (or F08APF (ZGEQRT), F08AQF (ZGEMQRT)), F08WTF (ZGGHD3), F08XSF (ZHGEQZ)
complex matrix pair, all eigenvalues and eigenvectors (with balancing) | F06TFF, F06THF, F08ASF (ZGEQRF), F08ATF (ZUNGQR), F08AUF (ZUNMQR) (or F08APF (ZGEQRT), F08AQF (ZGEMQRT)), F08WTF (ZGGHD3), F08WVF (ZGGBAL), F08XSF (ZHGEQZ), F08YXF (ZTGEVC)*, F08WWF (ZGGBAK)
3.1.2.9 The Sylvester equation and the generalized Sylvester equation
Routines are provided to solve the real or complex Sylvester equation AX±XB=C, where A and B are upper quasi-triangular if real, or upper triangular if complex. To solve the general form of the Sylvester equation in which A and B are general square matrices, A and B must be reduced to upper (quasi-) triangular form by the Schur factorization, using routines described in Section 3.1.2.7. For more details, see the documents for the routines listed below.
 | Solve the Sylvester equation
real matrices | F08QHF (DTRSYL)
complex matrices | F08QVF (ZTRSYL)
Routines are also provided to solve the real or complex generalized Sylvester equations
AR-LB=C ,   ​ DR-LE=F ,
where the pairs A,D and B,E are in generalized Schur form. To solve the general form of the generalized Sylvester equation in which A,D and B,E are general matrix pairs, A,D and B,E must first be reduced to generalized Schur form.
 | Solve the generalized Sylvester equation
real matrices | F08YHF (DTGSYL)
complex matrices | F08YVF (ZTGSYL)

3.2 NAG Names and LAPACK Names

As well as the NAG routine name (beginning F08), the tables in Section 3.1 show the LAPACK routine names in double precision.
The routines may be called either by their NAG or LAPACK names. When using the NAG Library, the double precision form of the LAPACK name must be used (beginning with D- or Z-).
References to Chapter F08 routines in the manual normally include the LAPACK double precision names, for example F08AEF (DGEQRF). The LAPACK routine names follow a simple scheme (which is similar to that used for the BLAS in Chapter F06). Each name has the structure XYYZZZ, where the components have the following meanings:
– the initial letter X indicates the data type (real or complex) and precision:
S | – real, single precision (in Fortran 77, REAL)
D | – real, double precision (in Fortran 77, DOUBLE PRECISION)
C | – complex, single precision (in Fortran 77, COMPLEX)
Z | – complex, double precision (in Fortran 77, COMPLEX*16 or DOUBLE COMPLEX)
– the second and third letters YY indicate the type of the matrix A or matrix pair A,B (and in some cases the storage scheme):
BD | – bidiagonal
DI | – diagonal
GB | – general band
GE | – general
GG | – general pair (B may be triangular)
HB | – (complex) Hermitian band
HE | – Hermitian
HG | – generalized upper Hessenberg
HP | – Hermitian (packed storage)
HS | – upper Hessenberg
OP | – (real) orthogonal (packed storage)
OR | – (real) orthogonal
PT | – symmetric or Hermitian positive definite tridiagonal
SB | – (real) symmetric band
SP | – symmetric (packed storage)
ST | – (real) symmetric tridiagonal
SY | – symmetric
TG | – triangular pair (one may be quasi-triangular)
TP | – triangular-pentagonal
TR | – triangular (or quasi-triangular)
UN | – (complex) unitary
UP | – (complex) unitary (packed storage)
– the last three letters ZZZ indicate the computation performed. For example, QRF is a QR factorization.
Thus the routine DGEQRF performs a QR factorization of a real general matrix; the corresponding routine for a complex general matrix is ZGEQRF.

3.3 Matrix Storage Schemes

In this chapter the following storage schemes are used for matrices:
  • – conventional storage in a two-dimensional array;
  • – packed storage for symmetric or Hermitian matrices;
  • – packed storage for orthogonal or unitary matrices;
  • – band storage for general, symmetric or Hermitian band matrices;
  • – storage of bidiagonal, symmetric or Hermitian tridiagonal matrices in two one-dimensional arrays.
These storage schemes are compatible with those used in Chapters F06 and F07, but different schemes for packed, band and tridiagonal storage are used in a few older routines in Chapters F01, F02, F03 and F04.

3.3.1 Conventional storage

Please see Section 3.3.1 in the F07 Chapter Introduction for full details.

3.3.2 Packed storage

Please see Section 3.3.2 in the F07 Chapter Introduction for full details.

3.3.3 Band storage

Please see Section 3.3.4 in the F07 Chapter Introduction for full details.

3.3.4 Tridiagonal and bidiagonal matrices

A symmetric tridiagonal or bidiagonal matrix is stored in two one-dimensional arrays, one of length n containing the diagonal elements, and one of length n-1 containing the off-diagonal elements. (Older routines in Chapter F02 store the off-diagonal elements in elements 2:n of a vector of length n.)

3.3.5 Real diagonal elements of complex matrices

Please see Section 3.3.6 in the F07 Chapter Introduction for full details.

3.3.6 Representation of orthogonal or unitary matrices

A real orthogonal or complex unitary matrix (usually denoted Q) is often represented in the NAG Library as a product of elementary reflectors – also referred to as elementary Householder matrices (usually denoted Hi). For example,
Q =H 1H 2⋯Hk.
You need not be aware of the details, because routines are provided to work with this representation, either to generate all or part of Q explicitly, or to multiply a given matrix by Q or QT (QH in the complex case) without forming Q explicitly.
Nevertheless, the following further details may occasionally be useful.
An elementary reflector (or elementary Householder matrix) H of order n is a unitary matrix of the form
H=I-τv vH (4)
where τ is a scalar, and v is an n-element vector, with τ 2v 2 2=2×Re τ; v is often referred to as the Householder vector. Often v has several leading or trailing zero elements, but for the purpose of this discussion assume that H has no such special structure.
There is some redundancy in the representation 4, which can be removed in various ways. The representation used in Chapter F08 and in LAPACK (which differs from those used in some of the routines in Chapters F01, F02, F04 and F06) sets v 1=1; hence v 1 need not be stored. In real arithmetic, 1≤τ≤2, except that τ=0 implies H=I.
In complex arithmetic, τ may be complex, and satisfies 1≤Re τ≤2 and τ-1≤1. Thus a complex H is not Hermitian (as it is in other representations), but it is unitary, which is the important property. The advantage of allowing τ to be complex is that, given an arbitrary complex vector x,H can be computed so that
HH x=β 1,0,…,0 T
with real β. This is useful, for example, when reducing a complex Hermitian matrix to real symmetric tridiagonal form, or a complex rectangular matrix to real bidiagonal form.

3.4 Argument Conventions

3.4.1 Option Arguments

Most routines in this chapter have one or more option arguments, of type CHARACTER. The descriptions in Section 5 of the routine documents refer only to upper case values (for example UPLO='U' or UPLO='L'); however in every case, the corresponding lower case characters may be supplied (with the same meaning). Any other value is illegal.
A longer character string can be passed as the actual argument, making the calling program more readable, but only the first character is significant. (This is a feature of Fortran 77.) For example:
CALL SSYTRD ('Upper',...)

3.4.2 Problem dimensions

It is permissible for the problem dimensions (for example, M or N) to be passed as zero, in which case the computation (or part of it) is skipped. Negative dimensions are regarded as an error.

3.4.3 Length of work arrays

A number of routines implementing block algorithms require workspace sufficient to hold one block of rows or columns of the matrix if they are to achieve optimum levels of performance – for example, workspace of size n×nb, where nb is the optimal block size. In such cases, the actual declared length of the work array must be passed as a separate argument LWORK, which immediately follows WORK in the argument-list.
The blocked routines in this chapter allow you to perform a workspace query. In this case the routine only calculates the optimal size of the WORK array, and returns this value as the first entry of the WORK array. You are strongly encouraged to perform such a query before using a particular routine. The routine will still perform correctly when less workspace is provided: it simply uses the largest block size allowed by the amount of workspace supplied, as long as this is likely to give better performance than the unblocked algorithm.
If LWORK indicates that there is insufficient workspace to perform the unblocked algorithm, this is regarded as an illegal value of LWORK, and is treated like any other illegal argument value (see Section 3.4.4).

3.4.4 Error-handling and the Diagnostic Argument INFO

Routines in this chapter do not use the usual NAG Library error-handling mechanism, involving the argument IFAIL. Instead they have a diagnostic argument INFO. (Thus they preserve complete compatibility with the LAPACK specification.)
Whereas IFAIL is an Input/Output argument and must be set before calling a routine, INFO is purely an Output argument and need not be set before entry.
INFO indicates the success or failure of the computation, as follows:
  • INFO=0: successful termination;
  • INFO>0: failure in the course of computation, control returned to the calling program.
If the routine document specifies that the routine may terminate with INFO>0, then it is essential to test INFO on exit from the routine. (This corresponds to a soft failure in terms of the usual NAG error-handling terminology.) No error message is output.
All routines check that input arguments such as N or LDA or option arguments of type CHARACTER have permitted values. If an illegal value of the ith argument is detected, INFO is set to -i, a message is output, and execution of the program is terminated. (This corresponds to a hard failure in the usual NAG terminology.) In some implementations, especially when linking to vendor versions of LAPACK, execution of the program may continue, in which case, it is essential to test INFO on exit from the routine.

4 Decision Trees

The following decision trees are principally for the computation (general purpose) routines. See Section 3.1.1.1 for tables of the driver (black box) routines.

4.1 General Purpose Routines (eigenvalues and eigenvectors)

Tree 1: Real Symmetric Eigenvalue Problems

Are eigenvalues only required? |  |  | Are all the eigenvalues required? |  |  | Is A tridiagonal? |  |  | F08JCF or F08JFF
 |  | yes |  |  | yes |  |  | yes
 | no |  |  | no |  |  | no |
 |  |  |  |  |  | Is A band matrix? |  |  | (F08HEF and F08JFF) or F08HCF
 |  |  |  |  |  |  |  | yes
 |  |  |  |  |  |  | no |
 |  |  |  |  |  | Is one triangle of A stored as a linear array? |  |  | (F08GEF and F08JFF) or F08GCF
 |  |  |  |  |  |  |  | yes
 |  |  |  |  |  |  | no |
 |  |  |  |  |  | (F08FEF and F08JFF) or F08FAF or F08FCF
 |  |  | Is A tridiagonal? |  |  | F08JJF
 |  |  |  |  | yes
 |  |  |  | no |
 |  |  | Is A a band matrix? |  |  | F08HEF and F08JJF
 |  |  |  |  | yes
 |  |  |  | no |
 |  |  | Is one triangle of A stored as a linear array? |  |  | F08GEF and F08JJF
 |  |  |  |  | yes
 |  |  |  | no |
 |  |  | (F08FEF and F08JJF) or F08FBF
Are all eigenvalues and eigenvectors required? |  |  | Is A tridiagonal? |  |  | F08JEF, F08JCF, F08JHF or F08JLF
 |  | yes |  |  | yes
 | no |  |  | no |
 |  |  | Is A a band matrix? |  |  | (F08HEF and F08JEF) or F08HCF
 |  |  |  |  | yes
 |  |  |  | no |
 |  |  | Is one triangle of A stored as a linear array? |  |  | (F08GEF, F08GFF and F08JEF) or F08GCF
 |  |  |  |  | yes
 |  |  |  | no |
 |  |  | (F08FEF, F08FFF and F08JEF) or F08FAF or F08FCF
Is A tridiagonal? |  |  | F08JJF and F08JKF
 |  | yes
 | no |
Is one triangle of A stored as a linear array? |  |  | F08GEF, F08JJF, F08JKF and F08GGF
 |  | yes
 | no |
(F08FEF, F08JJF, F08JKF and F08FGF) or F08FBF

Tree 2: Real Generalized Symmetric-definite Eigenvalue Problems

Are eigenvalues only required? |  |  | Are all the eigenvalues required? |  |  | Are A and B band matrices? |  |  | F08UFF, F08UEF, F08HEF and F08JFF
 |  | yes |  |  | yes |  |  | yes
 | no |  |  | no |  |  | no |
 |  |  |  |  |  | Are A and B stored with one triangle as a linear array? |  |  | F07GDF, F08TEF, F08GEF and F08JFF
 |  |  |  |  |  |  |  | yes
 |  |  |  |  |  |  | no |
 |  |  |  |  |  | F07FDF, F08SEF, F08FEF and F08JFF
 |  |  | Are A and B band matrices? |  |  | F08UFF, F08UEF, F08HEF and F08JJF
 |  |  |  |  | yes
 |  |  |  | no |
 |  |  | Are A and B stored with one triangle as a linear array? |  |  | F07GDF, F08TEF, F08GEF and F08JJF
 |  |  |  |  | yes
 |  |  |  | no |
 |  |  | F07FDF, F08SEF, F08GEF and F08JJF
Are all eigenvalues and eigenvectors required? |  |  | Are A and B stored with one triangle as a linear array? |  |  | F07GDF, F08TEF, F08GEF, F08GFF, F08JEF and F06PLF
 |  | yes |  |  | yes
 | no |  |  | no |
 |  |  | F07FDF, F08SEF, F08FEF, F08FFF, F08JEF and F06YJF
Are A and B band matrices? |  |  | F08UFF, F08UEF, F08HEF, F08JKF and F06YJF
 |  | yes
 | no |
Are A and B stored with one triangle as a linear array? |  |  | F07GDF, F08TEF, F08GEF, F08JJF, F08JKF, F08GGF and F06PLF
 |  | yes
 | no |
F07FDF, F08SEF, F08FEF, F08JJF, F08JKF, F08FGF and F06YJF
Note: the routines for band matrices only handle the problem Ax=λBx; the other routines handle all three types of problems (Ax=λBx, ABx=λx or BAx=λx) except that, if the problem is BAx=λx and eigenvectors are required, F06PHF must be used instead of F06PLF and F06YFF instead of F06YJF.

Tree 3: Real Nonsymmetric Eigenvalue Problems

Are eigenvalues required? |  |  | Is A an upper Hessenberg matrix? |  |  | F08PEF
 |  | yes |  |  | yes
 | no |  |  | no |
 |  |  | F08NAF or F08NBF or (F08NHF, F08NEF and F08PEF)
Is the Schur factorization of A required? |  |  | Is A an upper Hessenberg matrix? |  |  | F08PEF
 |  | yes |  |  | yes
 | no |  |  | no |
 |  |  | F08NBF or (F08NEF, F08NFF, F08PEF or F08NJF)
Are all eigenvectors required? |  |  | Is A an upper Hessenberg matrix? |  |  | F08PEF or F08QKF
 |  | yes |  |  | yes
 | no |  |  | no |
 |  |  | F08NAF or F08NBF or (F08NHF, F08NEF, F08NFF, F08PEF, F08QKF or F08NJF)
Is A an upper Hessenberg matrix? |  |  | F08PEF or F08PKF
 |  | yes
 | no |
F08NHF, F08NEF, F08PEF, F08PKF, F08NGF or F08NJF

Tree 4: Real Generalized Nonsymmetric Eigenvalue Problems

Are eigenvalues only required? |  |  | Are A and B in generalized upper Hessenberg form? |  |  | F08XEF
 |  | yes |  |  | yes
 | no |  |  | no |
 |  |  | F08WBF, or F08WHF and F08WCF
Is the generalized Schur factorization of A and B required? |  |  | Are A and B in generalized upper Hessenberg form? |  |  | F08XEF
 |  | yes |  |  | yes
 | no |  |  | no |
 |  |  | F08XBF or F08XCF
Are A and B in generalized upper Hessenberg form? |  |  | F08XEF and F08YKF
 |  | yes
 | no |
F08WBF, or F08WHF, F08WCF and F08WJF

Tree 5: Complex Hermitian Eigenvalue Problems

Are eigenvalues only required? |  |  | Are all the eigenvalues required? |  |  | Is A a band matrix? |  |  | (F08HSF and F08JFF) or F08HQF
 |  | yes |  |  | yes |  |  | yes
 | no |  |  | no |  |  | no |
 |  |  |  |  |  | Is one triangle of A stored as a linear array? |  |  | (F08GSF and F08JFF) or F08GQF
 |  |  |  |  |  |  |  | yes
 |  |  |  |  |  |  | no |
 |  |  |  |  |  | (F08FSF and F08JFF) or F08FQF
 |  |  | Is A a band matrix? |  |  | F08HSF and F08JJF
 |  |  |  |  | yes
 |  |  |  | no |
 |  |  | Is one triangle of A stored as a linear array? |  |  | F08GSF and F08JJF
 |  |  |  |  | yes
 |  |  |  | no |
 |  |  | F08FSF and F08JJF
Are all eigenvalues and eigenvectors required? |  |  | Is A a band matrix? |  |  | (F08HSF and F08JSF) or F08HQF
 |  | yes |  |  | yes
 | no |  |  | no |
 |  |  | Is one triangle of A stored as a linear array? |  |  | (F08GSF, F08GTF and F08JSF) or F08GQF
 |  |  |  |  | yes
 |  |  |  | no |
 |  |  | (F08FSF, F08FTF and F08JSF) or F08FQF
Is one triangle of A stored as a linear array? |  |  | F08GSF, F08JJF, F08JXF and F08GUF
 |  | yes
 | no |
F08FSF, F08JJF, F08JXF and F08FUF

Tree 6: Complex Generalized Hermitian-definite Eigenvalue Problems

Are eigenvalues only required? |  |  | Are all eigenvalues required? |  |  | Are A and B stored with one triangle as a linear array? |  |  | F07GRF, F08TSF, F08GSF and F08JFF
 |  | yes |  |  | yes |  |  | yes
 | no |  |  | no |  |  | no |
 |  |  |  |  |  | F07FRF, F08SSF, F08FSF and F08JFF
 |  |  | Are A and B stored with one triangle as a linear array? |  |  | F07GRF, F08TSF, F08GSF and F08JJF
 |  |  |  |  | yes
 |  |  |  | no |
 |  |  | F07FRF, F08SSF, F08GSF and F08JJF
Are all eigenvalues and eigenvectors required? |  |  | Are A and B stored with one triangle as a linear array? |  |  | F07GRF, F08TSF, F08GSF, F08GTF and F06PSF
 |  | yes |  |  | yes
 | no |  |  | no |
 |  |  | F07FRF, F08SSF, F08FSF, F08FTF, F08JSF and F06ZJF
Are A and B stored with one triangle as a linear array? |  |  | F07GRF, F08TSF, F08GSF, F08JJF, F08JXF, F08GUF and F06SLF
 |  | yes
 | no |
F07FRF, F08SSF, F08FSF, F08JJF, F08JXF, F08FUF and F06ZJF

Tree 7: Complex non-Hermitian Eigenvalue Problems

Are eigenvalues only required? |  |  | Is A an upper Hessenberg matrix? |  |  | F08PSF
 |  | yes |  |  | yes
 | no |  |  | no |
 |  |  | F08NVF, F08NSF and F08PSF
Is the Schur factorization of A required? |  |  | Is A an upper Hessenberg matrix? |  |  | F08PSF
 |  | yes |  |  | yes
 | no |  |  | no |
 |  |  | F08NSF, F08NTF, F08PSF and F08NWF
Are all eigenvectors required? |  |  | Is A an upper Hessenberg matrix? |  |  | F08PSF and F08QXF
 |  | yes |  |  | yes
 | no |  |  | no |
 |  |  | F08NVF, F08NSF, F08NTF, F08PSF, F08QXF and F08NWF
Is A an upper Hessenberg matrix? |  |  | F08PSF and F08PXF
 |  | yes
 | no |
F08NVF, F08NSF, F08PSF, F08PXF, F08NUF and F08NWF

Tree 8: Complex Generalized non-Hermitian Eigenvalue Problems

Are eigenvalues only required? |  |  | Are A and B in generalized upper Hessenberg form? |  |  | F08XSF
 |  | yes |  |  | yes
 | no |  |  | no |
 |  |  | F08WPF, or F08WQF and F08WVF
Is the generalized Schur factorization of A and B required? |  |  | Are A and B in generalized upper Hessenberg form? |  |  | F08XSF
 |  | yes |  |  | yes
 | no |  |  | no |
 |  |  | F08XPF or F08XQF
Are A and B in generalized upper Hessenberg form? |  |  | F08XSF and F08YXF
 |  | yes
 | no |
F08WPF, or F08WVF, F08WQF and F08WWF

4.2 General Purpose Routines (singular value decomposition)

Tree 9: Singular Value Decomposition of a Matrix

Is A a complex matrix? |  |  | Is A banded? |  |  | F08LSF and F08MSF
 |  | yes |  |  | yes
 | no |  |  | no |
 |  |  | Are singular values only required? |  |  | F08KSF and F08MSF
 |  |  |  |  | yes
 |  |  |  | no |
 |  |  | F08KSF, F08KTF and F08MSF
Is A bidiagonal? |  |  | F08MEF
 |  | yes
 | no |
Is A banded? |  |  | F08LEF and F08MEF
 |  | yes
 | no |
Are singular values only required? |  |  | F08KEF and F08MEF
 |  | yes
 | no |
F08KEF, F08KFF and F08MEF

Tree 10: Singular Value Decompositon of a Matrix Pair

Are A and B complex matrices |  |  | F08VQF
 |  | yes
 | no |
F08VCF

5 Functionality Index

Backtransformation of eigenvectors from those of balanced forms,
complex matrix F08NWF (ZGEBAK)
real matrix F08NJF (DGEBAK)
Backtransformation of generalized eigenvectors from those of balanced forms,
complex matrix F08WWF (ZGGBAK)
real matrix F08WJF (DGGBAK)
Balancing,
complex general matrix F08NVF (ZGEBAL)
complex general matrix pair F08WVF (ZGGBAL)
real general matrix F08NHF (DGEBAL)
real general matrix pair F08WHF (DGGBAL)
Eigenvalue problems for condensed forms of matrices,
complex Hermitian matrix,
eigenvalues and eigenvectors,
band matrix,
all/selected eigenvalues and eigenvectors by root-free QR algorithm F08HPF (ZHBEVX)
all eigenvalues and eigenvectors by a divide-and-conquer algorithm, using packed storage F08HQF (ZHBEVD)
all eigenvalues and eigenvectors by root-free QR algorithm F08HNF (ZHBEV)
general matrix,
all/selected eigenvalues and eigenvectors by root-free QR algorithm F08FPF (ZHEEVX)
all/selected eigenvalues and eigenvectors by root-free QR algorithm, using packed storage F08GPF (ZHPEVX)
all/selected eigenvalues and eigenvectors using Relatively Robust Representations F08FRF (ZHEEVR)
all eigenvalues and eigenvectors by a divide-and-conquer algorithm F08FQF (ZHEEVD)
all eigenvalues and eigenvectors by a divide-and-conquer algorithm, using packed storage F08GQF (ZHPEVD)
all eigenvalues and eigenvectors by root-free QR algorithm F08FNF (ZHEEV)
all eigenvalues and eigenvectors by root-free QR algorithm, using packed storage F08GNF (ZHPEV)
eigenvalues only,
band matrix,
all/selected eigenvalues by the Pal–Walker–Kahan variant of the QL or QR algorithm F08HPF (ZHBEVX)
all eigenvalues by the Pal–Walker–Kahan variant of the QL or QR algorithm F08HNF (ZHBEV)
all eigenvalues by the Pal–Walker–Kahan variant of the QL or QR algorithm, using packed storage F08HQF (ZHBEVD)
general matrix,
all/selected eigenvalues by the Pal–Walker–Kahan variant of the QL or QR algorithm F08FPF (ZHEEVX)
all/selected eigenvalues by the Pal–Walker–Kahan variant of the QL or QR algorithm, using packed storage F08GPF (ZHPEVX)
all eigenvalues by the Pal–Walker–Kahan variant of the QL or QR algorithm F08FNF (ZHEEV)
all eigenvalues by the Pal–Walker–Kahan variant of the QL or QR algorithm, using packed storage F08GNF (ZHPEV)
complex upper Hessenberg matrix, reduced from complex general matrix,
eigenvalues and Schur factorization F08PSF (ZHSEQR)
selected right and/or left eigenvectors by inverse iteration F08PXF (ZHSEIN)
real bidiagonal matrix,
singular value decomposition,
after reduction from complex general matrix F08MSF (ZBDSQR)
after reduction from real general matrix F08MEF (DBDSQR)
after reduction from real general matrix, using divide-and-conquer F08MDF (DBDSDC)
real symmetric matrix,
eigenvalues and eigenvectors,
band matrix,
all/selected eigenvalues and eigenvectors by root-free QR algorithm F08HBF (DSBEVX)
all eigenvalues and eigenvectors by a divide-and-conquer algorithm F08HCF (DSBEVD)
all eigenvalues and eigenvectors by root-free QR algorithm F08HAF (DSBEV)
general matrix,
all/selected eigenvalues and eigenvectors by root-free QR algorithm F08FBF (DSYEVX)
all/selected eigenvalues and eigenvectors by root-free QR algorithm, using packed storage F08GBF (DSPEVX)
all/selected eigenvalues and eigenvectors using Relatively Robust Representations F08FDF (DSYEVR)
all eigenvalues and eigenvectors by a divide-and-conquer algorithm F08FCF (DSYEVD)
all eigenvalues and eigenvectors by a divide-and-conquer algorithm, using packed storage F08GCF (DSPEVD)
all eigenvalues and eigenvectors by root-free QR algorithm F08FAF (DSYEV)
all eigenvalues and eigenvectors by root-free QR algorithm, using packed storage F08GAF (DSPEV)
eigenvalues only,
band matrix,
all/selected eigenvalues by the Pal–Walker–Kahan variant of the QL or QR algorithm F08HBF (DSBEVX)
all eigenvalues by the Pal–Walker–Kahan variant of the QL or QR algorithm F08HAF (DSBEV)
general matrix,
all/selected eigenvalues by the Pal–Walker–Kahan variant of the QL or QR algorithm F08FBF (DSYEVX)
all/selected eigenvalues by the Pal–Walker–Kahan variant of the QL or QR algorithm, using packed storage F08GBF (DSPEVX)
all eigenvalues by the Pal–Walker–Kahan variant of the QL or QR algorithm F08FAF (DSYEV)
all eigenvalues by the Pal–Walker–Kahan variant of the QL or QR algorithm, using packed storage F08GAF (DSPEV)
real symmetric tridiagonal matrix,
eigenvalues and eigenvectors,
after reduction from complex Hermitian matrix,
all eigenvalues and eigenvectors F08JSF (ZSTEQR)
all eigenvalues and eigenvectors, positive definite matrix F08JUF (ZPTEQR)
all eigenvalues and eigenvectors, using divide-and-conquer F08JVF (ZSTEDC)
all eigenvalues and eigenvectors, using Relatively Robust Representations F08JYF (ZSTEGR)
selected eigenvectors by inverse iteration F08JXF (ZSTEIN)
all/selected eigenvalues and eigenvectors by root-free QR algorithm F08JBF (DSTEVX)
all/selected eigenvalues and eigenvectors using Relatively Robust Representations F08JDF (DSTEVR)
all eigenvalues and eigenvectors F08JEF (DSTEQR)
all eigenvalues and eigenvectors, by divide-and-conquer F08JHF (DSTEDC)
all eigenvalues and eigenvectors, positive definite matrix F08JGF (DPTEQR)
all eigenvalues and eigenvectors, using Relatively Robust Representations F08JLF (DSTEGR)
all eigenvalues and eigenvectors by a divide-and-conquer algorithm F08JCF (DSTEVD)
all eigenvalues and eigenvectors by root-free QR algorithm F08JAF (DSTEV)
selected eigenvectors by inverse iteration F08JKF (DSTEIN)
eigenvalues only,
all/selected eigenvalues by the Pal–Walker–Kahan variant of the QL or QR algorithm F08JBF (DSTEVX)
all eigenvalues by root-free QR algorithm F08JFF (DSTERF)
all eigenvalues by the Pal–Walker–Kahan variant of the QL or QR algorithm F08JAF (DSTEV)
selected eigenvalues only F08JJF (DSTEBZ)
real upper Hessenberg matrix, reduced from real general matrix,
eigenvalues and Schur factorization F08PEF (DHSEQR)
selected right and/or left eigenvectors by inverse iteration F08PKF (DHSEIN)
Eigenvalue problems for nonsymmetric matrices,
complex matrix,
all eigenvalues, Schur form, Schur vectors and reciprocal condition numbers F08PPF (ZGEESX)
all eigenvalues, Schur form and Schur vectors F08PNF (ZGEES)
all eigenvalues and left/right eigenvectors F08NNF (ZGEEV)
all eigenvalues and left/right eigenvectors, plus balancing transformation and reciprocal condition numbers F08NPF (ZGEEVX)
real matrix,
all eigenvalues, real Schur form, Schur vectors and reciprocal condition numbers F08PBF (DGEESX)
all eigenvalues, real Schur form and Schur vectors F08PAF (DGEES)
all eigenvalues and left/right eigenvectors F08NAF (DGEEV)
all eigenvalues and left/right eigenvectors, plus balancing transformation and reciprocal condition numbers F08NBF (DGEEVX)
Eigenvalues and generalized Schur factorization,
complex generalized upper Hessenberg form F08XSF (ZHGEQZ)
real generalized upper Hessenberg form F08XEF (DHGEQZ)
General Gauss–Markov linear model,
solves a complex general Gauss–Markov linear model problem F08ZPF (ZGGGLM)
solves a real general Gauss–Markov linear model problem F08ZBF (DGGGLM)
Generalized eigenvalue problems for condensed forms of matrices,
complex Hermitian-definite eigenproblems,
banded matrices,
all eigenvalues and eigenvectors by a divide-and-conquer algorithm F08UQF (ZHBGVD)
all eigenvalues and eigenvectors by reduction to tridiagonal form F08UNF (ZHBGV)
selected eigenvalues and eigenvectors by reduction to tridiagonal form F08UPF (ZHBGVX)
general matrices,
all eigenvalues and eigenvectors by a divide-and-conquer algorithm F08SQF (ZHEGVD)
all eigenvalues and eigenvectors by a divide-and-conquer algorithm, packed storage format F08TQF (ZHPGVD)
all eigenvalues and eigenvectors by reduction to tridiagonal form F08SNF (ZHEGV)
all eigenvalues and eigenvectors by reduction to tridiagonal form, packed storage format F08TNF (ZHPGV)
selected eigenvalues and eigenvectors by reduction to tridiagonal form F08SPF (ZHEGVX)
selected eigenvalues and eigenvectors by reduction to tridiagonal form, packed storage format F08TPF (ZHPGVX)
real symmetric-definite eigenproblems,
banded matrices,
all eigenvalues and eigenvectors by a divide-and-conquer algorithm F08UCF (DSBGVD)
all eigenvalues and eigenvectors by reduction to tridiagonal form F08UAF (DSBGV)
selected eigenvalues and eigenvectors by reduction to tridiagonal form F08UBF (DSBGVX)
general matrices,
all eigenvalues and eigenvectors by a divide-and-conquer algorithm F08SCF (DSYGVD)
all eigenvalues and eigenvectors by a divide-and-conquer algorithm, packed storage format F08TCF (DSPGVD)
all eigenvalues and eigenvectors by reduction to tridiagonal form F08SAF (DSYGV)
all eigenvalues and eigenvectors by reduction to tridiagonal form, packed storage format F08TAF (DSPGV)
selected eigenvalues and eigenvectors by reduction to tridiagonal form F08SBF (DSYGVX)
selected eigenvalues and eigenvectors by reduction to tridiagonal form, packed storage format F08TBF (DSPGVX)
Generalized eigenvalue problems for nonsymmetric matrix pairs,
complex nonsymmetric matrix pairs,
all eigenvalues, generalized Schur form, Schur vectors and reciprocal condition numbers F08XPF (ZGGESX)
all eigenvalues, generalized Schur form and Schur vectors, deprecated F08XNF (ZGGES)
all eigenvalues, generalized Schur form and Schur vectors, using level 3 BLAS F08XQF (ZGGES3)
all eigenvalues and left/right eigenvectors, deprecated F08WNF (ZGGEV)
all eigenvalues and left/right eigenvectors, plus the balancing transformation and reciprocal condition numbers F08WPF (ZGGEVX)
all eigenvalues and left/right eigenvectors, using level 3 BLAS F08WQF (ZGGEV3)
real nonsymmetric matrix pairs,
all eigenvalues, generalized real Schur form and left/right Schur vectors, deprecated F08XAF (DGGES)
all eigenvalues, generalized real Schur form and left/right Schur vectors, plus reciprocal condition numbers F08XBF (DGGESX)
all eigenvalues, generalized real Schur form and left/right Schur vectors, using level 3 BLAS F08XCF (DGGES3)
all eigenvalues and left/right eigenvectors, deprecated F08WAF (DGGEV)
all eigenvalues and left/right eigenvectors, plus the balancing transformation and reciprocal condition numbers F08WBF (DGGEVX)
all eigenvalues and left/right eigenvectors, using level 3 BLAS F08WCF (DGGEV3)
Generalized QR factorization,
complex matrices F08ZSF (ZGGQRF)
real matrices F08ZEF (DGGQRF)
Generalized RQ factorization,
complex matrices F08ZTF (ZGGRQF)
real matrices F08ZFF (DGGRQF)
Generalized singular value decomposition,
after reduction from complex general matrix,
complex triangular or trapezoidal matrix pair F08YSF (ZTGSJA)
after reduction from real general matrix,
real triangular or trapezoidal matrix pair F08YEF (DTGSJA)
complex matrix pair, deprecated F08VNF (ZGGSVD)
complex matrix pair, using level 3 BLAS F08VQF (ZGGSVD3)
partitioned orthogonal matrix (CS decomposition) F08RAF (DORCSD)
partitioned unitary matrix (CS decomposition) F08RNF (ZUNCSD)
real matrix pair, deprecated F08VAF (DGGSVD)
real matrix pair, using level 3 BLAS F08VCF (DGGSVD3)
reduction of a pair of general matrices to triangular or trapezoidal form,
complex matrices, deprecated F08VSF (ZGGSVP)
complex matrices, using level 3 BLAS F08VUF (ZGGSVP3)
real matrices, deprecated F08VEF (DGGSVP)
real matrices, using level 3 BLAS F08VGF (DGGSVP3)
least squares problems,
complex matrices,
apply orthogonal matrix F08BXF (ZUNMRZ)
minimum norm solution using a complete orthogonal factorization F08BNF (ZGELSY)
minimum norm solution using the singular value decomposition F08KNF (ZGELSS)
minimum norm solution using the singular value decomposition (divide-and-conquer) F08KQF (ZGELSD)
reduction of upper trapezoidal matrix to upper triangular form F08BVF (ZTZRZF)
real matrices,
apply orthogonal matrix F08BKF (DORMRZ)
minimum norm solution using a complete orthogonal factorization F08BAF (DGELSY)
minimum norm solution using the singular value decomposition F08KAF (DGELSS)
minimum norm solution using the singular value decomposition (divide-and-conquer) F08KCF (DGELSD)
reduction of upper trapezoidal matrix to upper triangular form F08BHF (DTZRZF)
least squares problems with linear equality constraints,
complex matrices,
minimum norm solution subject to linear equality constraints using a generalized RQ factorization F08ZNF (ZGGLSE)
real matrices,
minimum norm solution subject to linear equality constraints using a generalized RQ factorization F08ZAF (DGGLSE)
Left and right eigenvectors of a pair of matrices,
complex upper triangular matrices F08YXF (ZTGEVC)
real quasi-triangular matrices F08YKF (DTGEVC)
LQ factorization and related operations,
complex matrices,
apply unitary matrix F08AXF (ZUNMLQ)
factorization F08AVF (ZGELQF)
form all or part of unitary matrix F08AWF (ZUNGLQ)
real matrices,
apply orthogonal matrix F08AKF (DORMLQ)
factorization F08AHF (DGELQF)
form all or part of orthogonal matrix F08AJF (DORGLQ)
Operations on eigenvectors of a real symmetric or complex Hermitian matrix, or singular vectors of a general matrix,
estimate condition numbers F08FLF (DDISNA)
Operations on generalized Schur factorization of a general matrix pair,
complex matrix,
estimate condition numbers of eigenvalues and/or eigenvectors F08YYF (ZTGSNA)
re-order Schur factorization F08YTF (ZTGEXC)
re-order Schur factorization, compute generalized eigenvalues and condition numbers F08YUF (ZTGSEN)
real matrix,
estimate condition numbers of eigenvalues and/or eigenvectors F08YLF (DTGSNA)
re-order Schur factorization F08YFF (DTGEXC)
re-order Schur factorization, compute generalized eigenvalues and condition numbers F08YGF (DTGSEN)
Operations on Schur factorization of a general matrix,
complex matrix,
compute left and/or right eigenvectors F08QXF (ZTREVC)
estimate sensitivities of eigenvalues and/or eigenvectors F08QYF (ZTRSNA)
re-order Schur factorization F08QTF (ZTREXC)
re-order Schur factorization, compute basis of invariant subspace, and estimate sensitivities F08QUF (ZTRSEN)
real matrix,
compute left and/or right eigenvectors F08QKF (DTREVC)
estimate sensitivities of eigenvalues and/or eigenvectors F08QLF (DTRSNA)
re-order Schur factorization F08QFF (DTREXC)
re-order Schur factorization, compute basis of invariant subspace, and estimate sensitivities F08QGF (DTRSEN)
Overdetermined and underdetermined linear systems,
complex matrices,
solves an overdetermined or undetermined complex linear system F08ANF (ZGELS)
real matrices,
solves an overdetermined or undetermined real linear system F08AAF (DGELS)
Performs a reduction of eigenvalue problems to condensed forms, and related operations,
real rectangular band matrix to upper bidiagonal form F08LEF (DGBBRD)
QL factorization and related operations,
complex matrices,
apply unitary matrix F08CUF (ZUNMQL)
factorization F08CSF (ZGEQLF)
form all or part of unitary matrix F08CTF (ZUNGQL)
real matrices,
apply orthogonal matrix F08CGF (DORMQL)
factorization F08CEF (DGEQLF)
form all or part of orthogonal matrix F08CFF (DORGQL)
QR factorization and related operations,
complex matrices,
general matrices,
apply unitary matrix F08AUF (ZUNMQR)
apply unitary matrix, explicitly blocked F08AQF (ZGEMQRT)
factorization F08ASF (ZGEQRF)
factorization,
with column pivoting, using BLAS-3 F08BTF (ZGEQP3)
factorization, explicitly blocked F08APF (ZGEQRT)
factorization, with column pivoting F08BSF (ZGEQPF)
form all or part of unitary matrix F08ATF (ZUNGQR)
triangular-pentagonal matrices,
apply unitary matrix F08BQF (ZTPMQRT)
factorization F08BPF (ZTPQRT)
real matrices,
general matrices,
apply orthogonal matrix F08AGF (DORMQR)
apply orthogonal matrix, explicitly blocked F08ACF (DGEMQRT)
factorization,
with column pivoting, using BLAS-3 F08BFF (DGEQP3)
factorization, orthogonal matrix F08AEF (DGEQRF)
factorization, with column pivoting F08BEF (DGEQPF)
factorization, with explicit blocking F08ABF (DGEQRT)
form all or part of orthogonal matrix F08AFF (DORGQR)
triangular-pentagonal matrices,
apply orthogonal matrix F08BBF (DTPQRT)
factorization F08BCF (DTPMQRT)
Reduction of a pair of general matrices to generalized upper Hessenberg form,
orthogonal reduction, real matrices, deprecated F08WEF (DGGHRD)
orthogonal reduction, real matrices, using level 3 BLAS F08WFF (DGGHD3)
unitary reduction, complex matrices, deprecated F08WSF (ZGGHRD)
unitary reduction, complex matrices, using level 3 BLAS F08WTF (ZGGHD3)
Reduction of eigenvalue problems to condensed forms, and related operations,
complex general matrix to upper Hessenberg form,
apply orthogonal matrix F08NUF (ZUNMHR)
form orthogonal matrix F08NTF (ZUNGHR)
reduce to Hessenberg form F08NSF (ZGEHRD)
complex Hermitian band matrix to real symmetric tridiagonal form F08HSF (ZHBTRD)
complex Hermitian matrix to real symmetric tridiagonal form,
apply unitary matrix F08FUF (ZUNMTR)
apply unitary matrix, packed storage F08GUF (ZUPMTR)
form unitary matrix F08FTF (ZUNGTR)
form unitary matrix, packed storage F08GTF (ZUPGTR)
reduce to tridiagonal form F08FSF (ZHETRD)
reduce to tridiagonal form, packed storage F08GSF (ZHPTRD)
complex rectangular band matrix to real upper bidiagonal form F08LSF (ZGBBRD)
complex rectangular matrix to real bidiagonal form,
apply unitary matrix F08KUF (ZUNMBR)
form unitary matrix F08KTF (ZUNGBR)
reduce to bidiagonal form F08KSF (ZGEBRD)
real general matrix to upper Hessenberg form,
apply orthogonal matrix F08NGF (DORMHR)
form orthogonal matrix F08NFF (DORGHR)
reduce to Hessenberg form F08NEF (DGEHRD)
real rectangular matrix to bidiagonal form,
apply orthogonal matrix F08KGF (DORMBR)
form orthogonal matrix F08KFF (DORGBR)
reduce to bidiagonal form F08KEF (DGEBRD)
real symmetric band matrix to symmetric tridiagonal form F08HEF (DSBTRD)
real symmetric matrix to symmetric tridiagonal form,
apply orthogonal matrix F08FGF (DORMTR)
apply orthogonal matrix, packed storage F08GGF (DOPMTR)
form orthogonal matrix F08FFF (DORGTR)
form orthogonal matrix, packed storage F08GFF (DOPGTR)
reduce to tridiagonal form F08FEF (DSYTRD)
reduce to tridiagonal form, packed storage F08GEF (DSPTRD)
Reduction of generalized eigenproblems to standard eigenproblems,
complex Hermitian-definite banded generalized eigenproblem Ax = λBx F08USF (ZHBGST)
complex Hermitian-definite generalized eigenproblem Ax = λBx, ABx = λx or BAx = λx F08SSF (ZHEGST)
complex Hermitian-definite generalized eigenproblem Ax = λBx, ABx = λx or BAx = λx, packed storage F08TSF (ZHPGST)
real symmetric-definite banded generalized eigenproblem Ax = λBx F08UEF (DSBGST)
real symmetric-definite generalized eigenproblem Ax = λBx, ABx = λx or BAx = λx F08SEF (DSYGST)
real symmetric-definite generalized eigenproblem Ax = λBx, ABx = λx or BAx = λx, packed storage F08TEF (DSPGST)
RQ factorization and related operations,
complex matrices,
apply unitary matrix F08CXF (ZUNMRQ)
factorization F08CVF (ZGERQF)
form all or part of unitary matrix F08CWF (ZUNGRQ)
real matrices,
apply orthogonal matrix F08CKF (DORMRQ)
factorization F08CHF (DGERQF)
form all or part of orthogonal matrix F08CJF (DORGRQ)
Singular value decomposition,
complex matrix,
using a divide-and-conquer algorithm F08KRF (ZGESDD)
using bidiagonal QR iteration F08KPF (ZGESVD)
real matrix,
preconditioned Jacobi SVD using fast scaled rotations and de Rijks pivoting F08KHF (DGEJSV)
using a divide-and-conquer algorithm F08KDF (DGESDD)
using bidiagonal QR iteration F08KBF (DGESVD)
using fast scaled rotation and de Rijks pivoting F08KJF (DGESVJ)
Solve generalized Sylvester equation,
complex matrices F08YVF (ZTGSYL)
real matrices F08YHF (DTGSYL)
Solve reduced form of Sylvester matrix equation,
complex matrices F08QVF (ZTRSYL)
real matrices F08QHF (DTRSYL)
Split Cholesky factorization,
complex Hermitian positive definite band matrix F08UTF (ZPBSTF)
real symmetric positive definite band matrix F08UFF (DPBSTF)

6 Auxiliary Routines Associated with Library Routine Arguments

F08PAZ | nagf_lapack_dgees_dummy_select See the description of the argument SELECT in F08PAF (DGEES) and F08PBF (DGEESX).
F08PNZ | nagf_lapack_zgees_dummy_select See the description of the argument SELECT in F08PNF (ZGEES) and F08PPF (ZGEESX).
F08XAZ | nagf_lapack_dgges_dummy_selctg See the description of the argument SELCTG in F08XAF (DGGES), F08XBF (DGGESX) and F08XCF (DGGES3).
F08XNZ | nagf_lapack_zgges_dummy_selctg See the description of the argument SELCTG in F08XNF (ZGGES), F08XPF (ZGGESX) and F08XQF (ZGGES3).

7 Routines Withdrawn or Scheduled for Withdrawal

None.

8 References

Anderson E, Bai Z, Bischof C, Blackford S, Demmel J, Dongarra J J, Du Croz J J, Greenbaum A, Hammarling S, McKenney A and Sorensen D (1999) LAPACK Users' Guide (3rd Edition) SIAM, Philadelphia
Arioli M, Duff I S and de Rijk P P M (1989) On the augmented system approach to sparse least squares problems Numer. Math. 55 667–684
Demmel J W and Kahan W (1990) Accurate singular values of bidiagonal matrices SIAM J. Sci. Statist. Comput. 11 873–912
Golub G H and Van Loan C F (2012) Matrix Computations (4th Edition) Johns Hopkins University Press, Baltimore
Moler C B and Stewart G W (1973) An algorithm for generalized matrix eigenproblems SIAM J. Numer. Anal. 10 241–256
Parlett B N (1998) The Symmetric Eigenvalue Problem SIAM, Philadelphia
Stewart G W and Sun J-G (1990) Matrix Perturbation Theory Academic Press, London
Ward R C (1981) Balancing the generalized eigenvalue problem SIAM J. Sci. Stat. Comp. 2 141–152
Wilkinson J H (1965) The Algebraic Eigenvalue Problem Oxford University Press, Oxford
Wilkinson J H and Reinsch C (1971) Handbook for Automatic Computation II, Linear Algebra Springer–Verlag
F08 Chapter Contents
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F08JAF (DSTEV) : NAG Library, Mark 26

F08 Chapter Contents
F08 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F08JAF (DSTEV)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F08JAF (DSTEV) computes all the eigenvalues and, optionally, all the eigenvectors of a real n by n symmetric tridiagonal matrix A.

2 Specification

SUBROUTINE F08JAF ( JOBZ, N, D, E, Z, LDZ, WORK, INFO)
INTEGER | N, LDZ, INFO
REAL (KIND=nag_wp) | D(*), E(*), Z(LDZ,*), WORK(*)
CHARACTER(1) | JOBZ
The routine may be called by its LAPACK name dstev.

3 Description

F08JAF (DSTEV) computes all the eigenvalues and, optionally, all the eigenvectors of A using a combination of the QR and QL algorithms, with an implicit shift.

4 References

Anderson E, Bai Z, Bischof C, Blackford S, Demmel J, Dongarra J J, Du Croz J J, Greenbaum A, Hammarling S, McKenney A and Sorensen D (1999) LAPACK Users' Guide (3rd Edition) SIAM, Philadelphia http://www.netlib.org/lapack/lug
Golub G H and Van Loan C F (1996) Matrix Computations (3rd Edition) Johns Hopkins University Press, Baltimore

5 Arguments

1:   JOBZ – CHARACTER(1)Input
On entry: indicates whether eigenvectors are computed.
JOBZ='N'
Only eigenvalues are computed.
JOBZ='V'
Eigenvalues and eigenvectors are computed.
Constraint: JOBZ='N' or 'V'.
2:   N – INTEGERInput
On entry: n, the order of the matrix.
Constraint: N≥0.
3:   D* – REAL (KIND=nag_wp) arrayInput/Output
Note: the dimension of the array D must be at least max 1,N.
On entry: the n diagonal elements of the tridiagonal matrix A.
On exit: if INFO=0, the eigenvalues in ascending order.
4:   E* – REAL (KIND=nag_wp) arrayInput/Output
Note: the dimension of the array E must be at least max 1,N-1.
On entry: the n-1 subdiagonal elements of the tridiagonal matrix A.
On exit: the contents of E are destroyed.
5:   Z LDZ* – REAL (KIND=nag_wp) arrayOutput
Note: the second dimension of the array Z must be at least max 1,N if JOBZ='V', and at least 1 otherwise.
On exit: if JOBZ='V', then if INFO=0, Z contains the orthonormal eigenvectors of the matrix A, with the ith column of Z holding the eigenvector associated with D i.
If JOBZ='N', Z is not referenced.
6:   LDZ – INTEGERInput
On entry: the first dimension of the array Z as declared in the (sub)program from which F08JAF (DSTEV) is called.
Constraints:
  • if JOBZ='V', LDZ≥ max 1,N ;
  • otherwise LDZ≥1.
7:   WORK* – REAL (KIND=nag_wp) arrayWorkspace
Note: the dimension of the array WORK must be at least max 1,2×N-2.
On exit: if JOBZ='N', WORK is not referenced.
8:   INFO – INTEGEROutput
On exit: INFO=0 unless the routine detects an error (see Section 6).

6 Error Indicators and Warnings

INFO<0
If INFO=-i, argument i had an illegal value. An explanatory message is output, and execution of the program is terminated.
INFO>0
If INFO=i, the algorithm failed to converge; i off-diagonal elements of E did not converge to zero.

7 Accuracy

The computed eigenvalues and eigenvectors are exact for a nearby matrix A+E, where
E 2 = O ε A 2 ,
and ε is the machine precision. See Section 4.7 of Anderson et al. (1999) for further details.

8 Parallelism and Performance

F08JAF (DSTEV) is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
F08JAF (DSTEV) makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The total number of floating-point operations is proportional to n 2 if JOBZ='N' and is proportional to n 3 if JOBZ='V'.

10 Example

This example finds all the eigenvalues and eigenvectors of the symmetric tridiagonal matrix
A = 1 1 0 0 1 4 2 0 0 2 9 3 0 0 3 16 ,
together with approximate error bounds for the computed eigenvalues and eigenvectors.

10.1 Program Text

Program Text (f08jafe.f90)

10.2 Program Data

Program Data (f08jafe.d)

10.3 Program Results

Program Results (f08jafe.r)

F08 Chapter Contents
F08 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F08JBF (DSTEVX) : NAG Library, Mark 26

F08 Chapter Contents
F08 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F08JBF (DSTEVX)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F08JBF (DSTEVX) computes selected eigenvalues and, optionally, eigenvectors of a real symmetric tridiagonal matrix A. Eigenvalues and eigenvectors can be selected by specifying either a range of values or a range of indices for the desired eigenvalues.

2 Specification

SUBROUTINE F08JBF ( JOBZ, RANGE, N, D, E, VL, VU, IL, IU, ABSTOL, M, W, Z, LDZ, WORK, IWORK, JFAIL, INFO)
INTEGER | N, IL, IU, M, LDZ, IWORK(5*N), JFAIL(*), INFO
REAL (KIND=nag_wp) | D(*), E(*), VL, VU, ABSTOL, W(N), Z(LDZ,*), WORK(5*N)
CHARACTER(1) | JOBZ, RANGE
The routine may be called by its LAPACK name dstevx.

3 Description

F08JBF (DSTEVX) computes the required eigenvalues and eigenvectors of A by reducing the tridiagonal matrix to diagonal form using the QR algorithm. Bisection is used to determine selected eigenvalues.

4 References

Anderson E, Bai Z, Bischof C, Blackford S, Demmel J, Dongarra J J, Du Croz J J, Greenbaum A, Hammarling S, McKenney A and Sorensen D (1999) LAPACK Users' Guide (3rd Edition) SIAM, Philadelphia http://www.netlib.org/lapack/lug
Demmel J W and Kahan W (1990) Accurate singular values of bidiagonal matrices SIAM J. Sci. Statist. Comput. 11 873–912
Golub G H and Van Loan C F (1996) Matrix Computations (3rd Edition) Johns Hopkins University Press, Baltimore

5 Arguments

1:   JOBZ – CHARACTER(1)Input
On entry: indicates whether eigenvectors are computed.
JOBZ='N'
Only eigenvalues are computed.
JOBZ='V'
Eigenvalues and eigenvectors are computed.
Constraint: JOBZ='N' or 'V'.
2:   RANGE – CHARACTER(1)Input
On entry: if RANGE='A', all eigenvalues will be found.
If RANGE='V', all eigenvalues in the half-open interval VL,VU will be found.
If RANGE='I', the ILth to IUth eigenvalues will be found.
Constraint: RANGE='A', 'V' or 'I'.
3:   N – INTEGERInput
On entry: n, the order of the matrix.
Constraint: N≥0.
4:   D* – REAL (KIND=nag_wp) arrayInput/Output
Note: the dimension of the array D must be at least max 1,N.
On entry: the n diagonal elements of the tridiagonal matrix A.
On exit: may be multiplied by a constant factor chosen to avoid over/underflow in computing the eigenvalues.
5:   E* – REAL (KIND=nag_wp) arrayInput/Output
Note: the dimension of the array E must be at least max 1,N-1.
On entry: the n-1 subdiagonal elements of the tridiagonal matrix A.
On exit: may be multiplied by a constant factor chosen to avoid over/underflow in computing the eigenvalues.
6:   VL – REAL (KIND=nag_wp)Input
7:   VU – REAL (KIND=nag_wp)Input
On entry: if RANGE='V', the lower and upper bounds of the interval to be searched for eigenvalues.
If RANGE='A' or 'I', VL and VU are not referenced.
Constraint: if RANGE='V', VL<VU.
8:   IL – INTEGERInput
9:   IU – INTEGERInput
On entry: if RANGE='I', the indices (in ascending order) of the smallest and largest eigenvalues to be returned.
If RANGE='A' or 'V', IL and IU are not referenced.
Constraints:
  • if RANGE='I' and N=0, IL=1 and IU=0;
  • if RANGE='I' and N>0, 1≤ IL≤ IU≤ N .
10:   ABSTOL – REAL (KIND=nag_wp)Input
On entry: the absolute error tolerance for the eigenvalues. An approximate eigenvalue is accepted as converged when it is determined to lie in an interval a,b of width less than or equal to
ABSTOL+ε max a,b ,
where ε is the machine precision. If ABSTOL is less than or equal to zero, then ε A 1 will be used in its place. Eigenvalues will be computed most accurately when ABSTOL is set to twice the underflow threshold 2 × X02AMF , not zero. If this routine returns with INFO>0, indicating that some eigenvectors did not converge, try setting ABSTOL to 2 × X02AMF . See Demmel and Kahan (1990).
11:   M – INTEGEROutput
On exit: the total number of eigenvalues found. 0≤M≤N.
If RANGE='A', M=N.
If RANGE='I', M=IU-IL+1.
12:   W N – REAL (KIND=nag_wp) arrayOutput
On exit: the first M elements contain the selected eigenvalues in ascending order.
13:   Z LDZ* – REAL (KIND=nag_wp) arrayOutput
Note: the second dimension of the array Z must be at least max 1,M if JOBZ='V', and at least 1 otherwise.
On exit: if JOBZ='V', then
  • if INFO=0, the first M columns of Z contain the orthonormal eigenvectors of the matrix A corresponding to the selected eigenvalues, with the ith column of Z holding the eigenvector associated with W i;
  • if an eigenvector fails to converge (INFO>0), then that column of Z contains the latest approximation to the eigenvector, and the index of the eigenvector is returned in JFAIL.
If JOBZ='N', Z is not referenced.
Note: you must ensure that at least max 1,M columns are supplied in the array Z; if RANGE='V', the exact value of M is not known in advance and an upper bound of at least N must be used.
14:   LDZ – INTEGERInput
On entry: the first dimension of the array Z as declared in the (sub)program from which F08JBF (DSTEVX) is called.
Constraints:
  • if JOBZ='V', LDZ≥ max 1,N ;
  • otherwise LDZ≥1.
15:   WORK 5×N – REAL (KIND=nag_wp) arrayWorkspace
16:   IWORK 5×N – INTEGER arrayWorkspace
17:   JFAIL* – INTEGER arrayOutput
Note: the dimension of the array JFAIL must be at least max 1,N.
On exit: if JOBZ='V', then
  • if INFO=0, the first M elements of JFAIL are zero;
  • if INFO>0, JFAIL contains the indices of the eigenvectors that failed to converge.
If JOBZ='N', JFAIL is not referenced.
18:   INFO – INTEGEROutput
On exit: INFO=0 unless the routine detects an error (see Section 6).

6 Error Indicators and Warnings

INFO<0
If INFO=-i, argument i had an illegal value. An explanatory message is output, and execution of the program is terminated.
INFO>0
The algorithm failed to converge; value eigenvectors did not converge. Their indices are stored in array JFAIL.

7 Accuracy

The computed eigenvalues and eigenvectors are exact for a nearby matrix A+E, where
E 2 = O ε A 2 ,
and ε is the machine precision. See Section 4.7 of Anderson et al. (1999) for further details.

8 Parallelism and Performance

F08JBF (DSTEVX) is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
F08JBF (DSTEVX) makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The total number of floating-point operations is proportional to n 2 if JOBZ='N' and is proportional to n 3 if JOBZ='V' and RANGE='A', otherwise the number of floating-point operations will depend upon the number of computed eigenvectors.

10 Example

This example finds the eigenvalues in the half-open interval 0,5 , and the corresponding eigenvectors, of the symmetric tridiagonal matrix
A = 1 1 0 0 1 4 2 0 0 2 9 3 0 0 3 16 .

10.1 Program Text

Program Text (f08jbfe.f90)

10.2 Program Data

Program Data (f08jbfe.d)

10.3 Program Results

Program Results (f08jbfe.r)

F08 Chapter Contents
F08 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F08JCF (DSTEVD) : NAG Library, Mark 26

F08 Chapter Contents
F08 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F08JCF (DSTEVD)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.
Warning. The specification of the arguments LWORK and LIWORK changed at Mark 20 in the case where JOB='V' and N>1: the minimum dimension of the array WORK has been reduced whereas the minimum dimension of the array IWORK has been increased.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F08JCF (DSTEVD) computes all the eigenvalues and, optionally, all the eigenvectors of a real symmetric tridiagonal matrix. If the eigenvectors are requested, then it uses a divide-and-conquer algorithm to compute eigenvalues and eigenvectors. However, if only eigenvalues are required, then it uses the Pal–Walker–Kahan variant of the QL or QR algorithm.

2 Specification

SUBROUTINE F08JCF ( JOB, N, D, E, Z, LDZ, WORK, LWORK, IWORK, LIWORK, INFO)
INTEGER | N, LDZ, LWORK, IWORK(max(1,LIWORK)), LIWORK, INFO
REAL (KIND=nag_wp) | D(*), E(*), Z(LDZ,*), WORK(max(1,LWORK))
CHARACTER(1) | JOB
The routine may be called by its LAPACK name dstevd.

3 Description

F08JCF (DSTEVD) computes all the eigenvalues and, optionally, all the eigenvectors of a real symmetric tridiagonal matrix T. In other words, it can compute the spectral factorization of T as
T=ZΛ ZT,
where Λ is a diagonal matrix whose diagonal elements are the eigenvalues λi, and Z is the orthogonal matrix whose columns are the eigenvectors zi. Thus
T zi=λizi,  i=1,2,…,n.

4 References

Golub G H and Van Loan C F (1996) Matrix Computations (3rd Edition) Johns Hopkins University Press, Baltimore

5 Arguments

1:   JOB – CHARACTER(1)Input
On entry: indicates whether eigenvectors are computed.
JOB='N'
Only eigenvalues are computed.
JOB='V'
Eigenvalues and eigenvectors are computed.
Constraint: JOB='N' or 'V'.
2:   N – INTEGERInput
On entry: n, the order of the matrix T.
Constraint: N≥0.
3:   D* – REAL (KIND=nag_wp) arrayInput/Output
Note: the dimension of the array D must be at least max 1,N.
On entry: the n diagonal elements of the tridiagonal matrix T.
On exit: the eigenvalues of the matrix T in ascending order.
4:   E* – REAL (KIND=nag_wp) arrayInput/Output
Note: the dimension of the array E must be at least max 1,N.
On entry: the n-1 off-diagonal elements of the tridiagonal matrix T. The nth element of this array is used as workspace.
On exit: E is overwritten with intermediate results.
5:   Z LDZ* – REAL (KIND=nag_wp) arrayOutput
Note: the second dimension of the array Z must be at least max 1,N if JOB='V' and at least 1 if JOB='N'.
On exit: if JOB='V', Z is overwritten by the orthogonal matrix Z which contains the eigenvectors of T.
If JOB='N', Z is not referenced.
6:   LDZ – INTEGERInput
On entry: the first dimension of the array Z as declared in the (sub)program from which F08JCF (DSTEVD) is called.
Constraints:
  • if JOB='V', LDZ≥ max 1,N ;
  • if JOB='N', LDZ≥1.
7:   WORK max 1,LWORK – REAL (KIND=nag_wp) arrayWorkspace
On exit: if INFO=0, WORK 1 contains the required minimal size of LWORK.
8:   LWORK – INTEGERInput
On entry: the dimension of the array WORK as declared in the (sub)program from which F08JCF (DSTEVD) is called.
If LWORK=-1, a workspace query is assumed; the routine only calculates the minimum dimension of the WORK array, returns this value as the first entry of the WORK array, and no error message related to LWORK is issued.
Constraints:
  • if JOB='N' or N≤1, LWORK≥1 or LWORK=-1;
  • if JOB='V' and N>1, LWORK≥N 2+4×N+1 or LWORK=-1.
9:   IWORK max 1,LIWORK – INTEGER arrayWorkspace
On exit: if INFO=0, IWORK 1 contains the required minimal size of LIWORK.
10:   LIWORK – INTEGERInput
On entry: the dimension of the array IWORK as declared in the (sub)program from which F08JCF (DSTEVD) is called.
If LIWORK=-1, a workspace query is assumed; the routine only calculates the minimum dimension of the IWORK array, returns this value as the first entry of the IWORK array, and no error message related to LIWORK is issued.
Constraints:
  • if JOB='N' or N≤1, LIWORK≥1 or LIWORK=-1;
  • if JOB='V' and N>1, LIWORK≥5×N+3 or LIWORK=-1.
11:   INFO – INTEGEROutput
On exit: INFO=0 unless the routine detects an error (see Section 6).

6 Error Indicators and Warnings

INFO<0
If INFO=-i, argument i had an illegal value. An explanatory message is output, and execution of the program is terminated.
INFO>0
if INFO=i and JOB='N', the algorithm failed to converge; i elements of an intermediate tridiagonal form did not converge to zero; if INFO=i and JOB='V', then the algorithm failed to compute an eigenvalue while working on the submatrix lying in rows and column i/N+1 through i mod N+1.

7 Accuracy

The computed eigenvalues and eigenvectors are exact for a nearby matrix T+E, where
E 2 = O ε T 2 ,
and ε is the machine precision.
If λi is an exact eigenvalue and λ~i is the corresponding computed value, then
λ~i - λi ≤ c n ε T 2 ,
where c n is a modestly increasing function of n.
If zi is the corresponding exact eigenvector, and z~i is the corresponding computed eigenvector, then the angle θ z~i,zi between them is bounded as follows:
θ z~i,zi ≤ c n ε T 2 min i≠j λi - λj .
Thus the accuracy of a computed eigenvector depends on the gap between its eigenvalue and all the other eigenvalues.

8 Parallelism and Performance

F08JCF (DSTEVD) is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
F08JCF (DSTEVD) makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

There is no complex analogue of this routine.

10 Example

This example computes all the eigenvalues and eigenvectors of the symmetric tridiagonal matrix T, where
T = 1.0 1.0 0.0 0.0 1.0 4.0 2.0 0.0 0.0 2.0 9.0 3.0 0.0 0.0 3.0 16.0 .

10.1 Program Text

Program Text (f08jcfe.f90)

10.2 Program Data

Program Data (f08jcfe.d)

10.3 Program Results

Program Results (f08jcfe.r)

F08 Chapter Contents
F08 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F08JDF (DSTEVR) : NAG Library, Mark 26

F08 Chapter Contents
F08 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F08JDF (DSTEVR)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F08JDF (DSTEVR) computes selected eigenvalues and, optionally, eigenvectors of a real n by n symmetric tridiagonal matrix T. Eigenvalues and eigenvectors can be selected by specifying either a range of values or a range of indices for the desired eigenvalues.

2 Specification

SUBROUTINE F08JDF ( JOBZ, RANGE, N, D, E, VL, VU, IL, IU, ABSTOL, M, W, Z, LDZ, ISUPPZ, WORK, LWORK, IWORK, LIWORK, INFO)
INTEGER | N, IL, IU, M, LDZ, ISUPPZ(*), LWORK, IWORK(max(1,LIWORK)), LIWORK, INFO
REAL (KIND=nag_wp) | D(*), E(*), VL, VU, ABSTOL, W(*), Z(LDZ,*), WORK(max(1,LWORK))
CHARACTER(1) | JOBZ, RANGE
The routine may be called by its LAPACK name dstevr.

3 Description

Whenever possible F08JDF (DSTEVR) computes the eigenspectrum using Relatively Robust Representations. F08JDF (DSTEVR) computes eigenvalues by the dqds algorithm, while orthogonal eigenvectors are computed from various ‘good’ LD LT representations (also known as Relatively Robust Representations). Gram–Schmidt orthogonalization is avoided as far as possible. More specifically, the various steps of the algorithm are as follows. For the ith unreduced block of T:
(a) | compute T - σi I = Li Di LiT , such that Li Di LiT is a relatively robust representation,
(b) | compute the eigenvalues, λj, of Li Di LiT to high relative accuracy by the dqds algorithm,
(c) | if there is a cluster of close eigenvalues, ‘choose’ σi close to the cluster, and go to (a),
(d) | given the approximate eigenvalue λj of Li Di LiT , compute the corresponding eigenvector by forming a rank-revealing twisted factorization.
The desired accuracy of the output can be specified by the argument ABSTOL. For more details, see Dhillon (1997) and Parlett and Dhillon (2000).

4 References

Anderson E, Bai Z, Bischof C, Blackford S, Demmel J, Dongarra J J, Du Croz J J, Greenbaum A, Hammarling S, McKenney A and Sorensen D (1999) LAPACK Users' Guide (3rd Edition) SIAM, Philadelphia http://www.netlib.org/lapack/lug
Barlow J and Demmel J W (1990) Computing accurate eigensystems of scaled diagonally dominant matrices SIAM J. Numer. Anal. 27 762–791
Demmel J W and Kahan W (1990) Accurate singular values of bidiagonal matrices SIAM J. Sci. Statist. Comput. 11 873–912
Dhillon I (1997) A new O n 2 algorithm for the symmetric tridiagonal eigenvalue/eigenvector problem Computer Science Division Technical Report No. UCB//CSD-97-971 UC Berkeley
Golub G H and Van Loan C F (1996) Matrix Computations (3rd Edition) Johns Hopkins University Press, Baltimore
Parlett B N and Dhillon I S (2000) Relatively robust representations of symmetric tridiagonals Linear Algebra Appl. 309 121–151

5 Arguments

1:   JOBZ – CHARACTER(1)Input
On entry: indicates whether eigenvectors are computed.
JOBZ='N'
Only eigenvalues are computed.
JOBZ='V'
Eigenvalues and eigenvectors are computed.
Constraint: JOBZ='N' or 'V'.
2:   RANGE – CHARACTER(1)Input
On entry: if RANGE='A', all eigenvalues will be found.
If RANGE='V', all eigenvalues in the half-open interval VL,VU will be found.
If RANGE='I', the ILth to IUth eigenvalues will be found.
Constraint: RANGE='A', 'V' or 'I'.
3:   N – INTEGERInput
On entry: n, the order of the matrix.
Constraint: N≥0.
4:   D* – REAL (KIND=nag_wp) arrayInput/Output
Note: the dimension of the array D must be at least max 1,N.
On entry: the n diagonal elements of the tridiagonal matrix T.
On exit: may be multiplied by a constant factor chosen to avoid over/underflow in computing the eigenvalues.
5:   E* – REAL (KIND=nag_wp) arrayInput/Output
Note: the dimension of the array E must be at least max 1,N-1.
On entry: the n-1 subdiagonal elements of the tridiagonal matrix T.
On exit: may be multiplied by a constant factor chosen to avoid over/underflow in computing the eigenvalues.
6:   VL – REAL (KIND=nag_wp)Input
7:   VU – REAL (KIND=nag_wp)Input
On entry: if RANGE='V', the lower and upper bounds of the interval to be searched for eigenvalues.
If RANGE='A' or 'I', VL and VU are not referenced.
Constraint: if RANGE='V', VL<VU.
8:   IL – INTEGERInput
9:   IU – INTEGERInput
On entry: if RANGE='I', the indices (in ascending order) of the smallest and largest eigenvalues to be returned.
If RANGE='A' or 'V', IL and IU are not referenced.
Constraints:
  • if RANGE='I' and N=0, IL=1 and IU=0;
  • if RANGE='I' and N>0, 1≤ IL≤ IU≤ N .
10:   ABSTOL – REAL (KIND=nag_wp)Input
On entry: the absolute error tolerance for the eigenvalues. An approximate eigenvalue is accepted as converged when it is determined to lie in an interval a,b of width less than or equal to
ABSTOL+ε max a,b ,
where ε is the machine precision. If ABSTOL is less than or equal to zero, then ε T 1 will be used in its place. See Demmel and Kahan (1990).
If high relative accuracy is important, set ABSTOL to X02AMF , although doing so does not currently guarantee that eigenvalues are computed to high relative accuracy. See Barlow and Demmel (1990) for a discussion of which matrices can define their eigenvalues to high relative accuracy.
11:   M – INTEGEROutput
On exit: the total number of eigenvalues found. 0≤M≤N.
If RANGE='A', M=N.
If RANGE='I', M=IU-IL+1.
12:   W* – REAL (KIND=nag_wp) arrayOutput
Note: the dimension of the array W must be at least max 1,N.
On exit: the first M elements contain the selected eigenvalues in ascending order.
13:   Z LDZ* – REAL (KIND=nag_wp) arrayOutput
Note: the second dimension of the array Z must be at least max 1,M if JOBZ='V', and at least 1 otherwise.
On exit: if JOBZ='V', the first M columns of Z contain the orthonormal eigenvectors of the matrix A corresponding to the selected eigenvalues, with the ith column of Z holding the eigenvector associated with W i.
If JOBZ='N', Z is not referenced.
Note: you must ensure that at least max 1,M columns are supplied in the array Z; if RANGE='V', the exact value of M is not known in advance and an upper bound of at least N must be used.
14:   LDZ – INTEGERInput
On entry: the first dimension of the array Z as declared in the (sub)program from which F08JDF (DSTEVR) is called.
Constraints:
  • if JOBZ='V', LDZ≥ max 1,N ;
  • otherwise LDZ≥1.
15:   ISUPPZ* – INTEGER arrayOutput
Note: the dimension of the array ISUPPZ must be at least max 1,2×M.
On exit: the support of the eigenvectors in Z, i.e., the indices indicating the nonzero elements in Z. The ith eigenvector is nonzero only in elements ISUPPZ 2×i-1 through ISUPPZ 2×i. Implemented only for RANGE='A' or 'I' and IU-IL=N-1.
16:   WORK max 1,LWORK – REAL (KIND=nag_wp) arrayWorkspace
On exit: if INFO=0, WORK 1 contains the minimum value of LWORK required for optimal performance.
17:   LWORK – INTEGERInput
On entry: the dimension of the array WORK as declared in the (sub)program from which F08JDF (DSTEVR) is called.
If LWORK=-1, a workspace query is assumed; the routine only calculates the minimum sizes of the WORK and IWORK arrays, returns these values as the first entries of the WORK and IWORK arrays, and no error message related to LWORK or LIWORK is issued.
Constraint: LWORK≥max 1,20×N.
18:   IWORK max 1,LIWORK – INTEGER arrayWorkspace
On exit: if INFO=0, IWORK 1 returns the minimum LIWORK.
19:   LIWORK – INTEGERInput
On entry: the dimension of the array IWORK as declared in the (sub)program from which F08JDF (DSTEVR) is called.
If LIWORK=-1, a workspace query is assumed; the routine only calculates the minimum sizes of the WORK and IWORK arrays, returns these values as the first entries of the WORK and IWORK arrays, and no error message related to LWORK or LIWORK is issued.
Constraint: LIWORK≥max 1,120×N.
20:   INFO – INTEGEROutput
On exit: INFO=0 unless the routine detects an error (see Section 6).

6 Error Indicators and Warnings

INFO<0
If INFO=-i, argument i had an illegal value. An explanatory message is output, and execution of the program is terminated.
INFO>0
An internal error has occurred in this routine. Please refer to INFO in F08JJF (DSTEBZ).

7 Accuracy

The computed eigenvalues and eigenvectors are exact for a nearby matrix A+E, where
E 2 = O ε A 2 ,
and ε is the machine precision. See Section 4.7 of Anderson et al. (1999) for further details.

8 Parallelism and Performance

F08JDF (DSTEVR) is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
F08JDF (DSTEVR) makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The total number of floating-point operations is proportional to n 2 if JOBZ='N' and is proportional to n 3 if JOBZ='V' and RANGE='A', otherwise the number of floating-point operations will depend upon the number of computed eigenvectors.

10 Example

This example finds the eigenvalues with indices in the range 2,3 , and the corresponding eigenvectors, of the symmetric tridiagonal matrix
T = 1 1 0 0 1 4 2 0 0 2 9 3 0 0 3 16 .

10.1 Program Text

Program Text (f08jdfe.f90)

10.2 Program Data

Program Data (f08jdfe.d)

10.3 Program Results

Program Results (f08jdfe.r)

F08 Chapter Contents
F08 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F08JEF (DSTEQR) : NAG Library, Mark 26

F08 Chapter Contents
F08 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F08JEF (DSTEQR)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F08JEF (DSTEQR) computes all the eigenvalues and, optionally, all the eigenvectors of a real symmetric tridiagonal matrix, or of a real symmetric matrix which has been reduced to tridiagonal form.

2 Specification

SUBROUTINE F08JEF ( COMPZ, N, D, E, Z, LDZ, WORK, INFO)
INTEGER | N, LDZ, INFO
REAL (KIND=nag_wp) | D(*), E(*), Z(LDZ,*), WORK(*)
CHARACTER(1) | COMPZ
The routine may be called by its LAPACK name dsteqr.

3 Description

F08JEF (DSTEQR) computes all the eigenvalues and, optionally, all the eigenvectors of a real symmetric tridiagonal matrix T. In other words, it can compute the spectral factorization of T as
T=ZΛ ZT,
where Λ is a diagonal matrix whose diagonal elements are the eigenvalues λi, and Z is the orthogonal matrix whose columns are the eigenvectors zi. Thus
T zi=λizi,  i=1,2,…,n.
The routine may also be used to compute all the eigenvalues and eigenvectors of a real symmetric matrix A which has been reduced to tridiagonal form T:
A =QT QT, where ​Q​ is orthogonal =QZ Λ QZ T.
In this case, the matrix Q must be formed explicitly and passed to F08JEF (DSTEQR), which must be called with COMPZ='V'. The routines which must be called to perform the reduction to tridiagonal form and form Q are:
full matrix | F08FEF (DSYTRD) and F08FFF (DORGTR)
full matrix, packed storage | F08GEF (DSPTRD) and F08GFF (DOPGTR)
band matrix | F08HEF (DSBTRD) with VECT='V'.
F08JEF (DSTEQR) uses the implicitly shifted QR algorithm, switching between the QR and QL variants in order to handle graded matrices effectively (see Greenbaum and Dongarra (1980)). The eigenvectors are normalized so that zi 2=1, but are determined only to within a factor ±1.
If only the eigenvalues of T are required, it is more efficient to call F08JFF (DSTERF) instead. If T is positive definite, small eigenvalues can be computed more accurately by F08JGF (DPTEQR).

4 References

Golub G H and Van Loan C F (1996) Matrix Computations (3rd Edition) Johns Hopkins University Press, Baltimore
Greenbaum A and Dongarra J J (1980) Experiments with QR/QL methods for the symmetric triangular eigenproblem LAPACK Working Note No. 17 (Technical Report CS-89-92) University of Tennessee, Knoxville http://www.netlib.org/lapack/lawnspdf/lawn17.pdf
Parlett B N (1998) The Symmetric Eigenvalue Problem SIAM, Philadelphia

5 Arguments

1:   COMPZ – CHARACTER(1)Input
On entry: indicates whether the eigenvectors are to be computed.
COMPZ='N'
Only the eigenvalues are computed (and the array Z is not referenced).
COMPZ='V'
The eigenvalues and eigenvectors of A are computed (and the array Z must contain the matrix Q on entry).
COMPZ='I'
The eigenvalues and eigenvectors of T are computed (and the array Z is initialized by the routine).
Constraint: COMPZ='N', 'V' or 'I'.
2:   N – INTEGERInput
On entry: n, the order of the matrix T.
Constraint: N≥0.
3:   D* – REAL (KIND=nag_wp) arrayInput/Output
Note: the dimension of the array D must be at least max 1,N.
On entry: the diagonal elements of the tridiagonal matrix T.
On exit: the n eigenvalues in ascending order, unless INFO>0 (in which case see Section 6).
4:   E* – REAL (KIND=nag_wp) arrayInput/Output
Note: the dimension of the array E must be at least max 1,N-1.
On entry: the off-diagonal elements of the tridiagonal matrix T.
On exit: E is overwritten.
5:   Z LDZ* – REAL (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array Z must be at least max 1,N if COMPZ='V' or 'I' and at least 1 if COMPZ='N'.
On entry: if COMPZ='V', Z must contain the orthogonal matrix Q from the reduction to tridiagonal form.
If COMPZ='I', Z need not be set.
On exit: if COMPZ='V' or 'I', the n required orthonormal eigenvectors stored as columns of Z; the ith column corresponds to the ith eigenvalue, where i=1,2,…,n, unless INFO>0.
If COMPZ='N', Z is not referenced.
6:   LDZ – INTEGERInput
On entry: the first dimension of the array Z as declared in the (sub)program from which F08JEF (DSTEQR) is called.
Constraints:
  • if COMPZ='V' or 'I', LDZ≥ max 1,N ;
  • if COMPZ='N', LDZ≥1.
7:   WORK* – REAL (KIND=nag_wp) arrayWorkspace
Note: the dimension of the array WORK must be at least max 1,2×N-1 if COMPZ='V' or 'I' and at least 1 if COMPZ='N'.
If COMPZ='N', WORK is not referenced.
8:   INFO – INTEGEROutput
On exit: INFO=0 unless the routine detects an error (see Section 6).

6 Error Indicators and Warnings

INFO<0
If INFO=-i, argument i had an illegal value. An explanatory message is output, and execution of the program is terminated.
INFO>0
The algorithm has failed to find all the eigenvalues after a total of 30×N iterations. In this case, D and E contain on exit the diagonal and off-diagonal elements, respectively, of a tridiagonal matrix orthogonally similar to T. If INFO=i, then i off-diagonal elements have not converged to zero.

7 Accuracy

The computed eigenvalues and eigenvectors are exact for a nearby matrix T+E, where
E 2 = O ε T 2 ,
and ε is the machine precision.
If λi is an exact eigenvalue and λ~i is the corresponding computed value, then
λ~i - λi ≤ c n ε T 2 ,
where c n is a modestly increasing function of n.
If zi is the corresponding exact eigenvector, and z~i is the corresponding computed eigenvector, then the angle θ z~i,zi between them is bounded as follows:
θ z~i,zi ≤ c n ε T 2 min i≠j λi-λj .
Thus the accuracy of a computed eigenvector depends on the gap between its eigenvalue and all the other eigenvalues.

8 Parallelism and Performance

F08JEF (DSTEQR) is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
F08JEF (DSTEQR) makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The total number of floating-point operations is typically about 24 n 2 if COMPZ='N' and about 7 n 3 if COMPZ='V' or 'I', but depends on how rapidly the algorithm converges. When COMPZ='N', the operations are all performed in scalar mode; the additional operations to compute the eigenvectors when COMPZ='V' or 'I' can be vectorized and on some machines may be performed much faster.
The complex analogue of this routine is F08JSF (ZSTEQR).

10 Example

This example computes all the eigenvalues and eigenvectors of the symmetric tridiagonal matrix T, where
T = -6.99 -0.44 0.00 0.00 -0.44 7.92 -2.63 0.00 0.00 -2.63 2.34 -1.18 0.00 0.00 -1.18 0.32 .
See also the examples for F08FFF (DORGTR), F08GFF (DOPGTR) or F08HEF (DSBTRD), which illustrate the use of this routine to compute the eigenvalues and eigenvectors of a full or band symmetric matrix.

10.1 Program Text

Program Text (f08jefe.f90)

10.2 Program Data

Program Data (f08jefe.d)

10.3 Program Results

Program Results (f08jefe.r)

F08 Chapter Contents
F08 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F08JFF (DSTERF) : NAG Library, Mark 26

F08 Chapter Contents
F08 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F08JFF (DSTERF)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F08JFF (DSTERF) computes all the eigenvalues of a real symmetric tridiagonal matrix.

2 Specification

SUBROUTINE F08JFF ( N, D, E, INFO)
INTEGER | N, INFO
REAL (KIND=nag_wp) | D(*), E(*)
The routine may be called by its LAPACK name dsterf.

3 Description

F08JFF (DSTERF) computes all the eigenvalues of a real symmetric tridiagonal matrix, using a square-root-free variant of the QR algorithm.
The routine uses an explicit shift, and, like F08JEF (DSTEQR), switches between the QR and QL variants in order to handle graded matrices effectively (see Greenbaum and Dongarra (1980)).

4 References

Greenbaum A and Dongarra J J (1980) Experiments with QR/QL methods for the symmetric triangular eigenproblem LAPACK Working Note No. 17 (Technical Report CS-89-92) University of Tennessee, Knoxville http://www.netlib.org/lapack/lawnspdf/lawn17.pdf
Parlett B N (1998) The Symmetric Eigenvalue Problem SIAM, Philadelphia

5 Arguments

1:   N – INTEGERInput
On entry: n, the order of the matrix T.
Constraint: N≥0.
2:   D* – REAL (KIND=nag_wp) arrayInput/Output
Note: the dimension of the array D must be at least max 1,N.
On entry: the diagonal elements of the tridiagonal matrix T.
On exit: the n eigenvalues in ascending order, unless INFO>0 (in which case see Section 6).
3:   E* – REAL (KIND=nag_wp) arrayInput/Output
Note: the dimension of the array E must be at least max 1,N-1.
On entry: the off-diagonal elements of the tridiagonal matrix T.
On exit: E is overwritten.
4:   INFO – INTEGEROutput
On exit: INFO=0 unless the routine detects an error (see Section 6).

6 Error Indicators and Warnings

INFO<0
If INFO=-i, argument i had an illegal value. An explanatory message is output, and execution of the program is terminated.
INFO>0
The algorithm has failed to find all the eigenvalues after a total of 30×N iterations. If INFO=i, then on exit i elements of E have not converged to zero.

7 Accuracy

The computed eigenvalues are exact for a nearby matrix T+E, where
E 2 = O ε T 2 ,
and ε is the machine precision.
If λi is an exact eigenvalue and λ~i is the corresponding computed value, then
λ~i - λi ≤ c n ε T 2 ,
where c n is a modestly increasing function of n.

8 Parallelism and Performance

F08JFF (DSTERF) is not threaded in any implementation.

9 Further Comments

The total number of floating-point operations is typically about 14 n 2, but depends on how rapidly the algorithm converges. The operations are all performed in scalar mode.
There is no complex analogue of this routine.

10 Example

This example computes all the eigenvalues of the symmetric tridiagonal matrix T, where
T = -6.99 -0.44 0.00 0.00 -0.44 7.92 -2.63 0.00 0.00 -2.63 2.34 -1.18 0.00 0.00 -1.18 0.32 .

10.1 Program Text

Program Text (f08jffe.f90)

10.2 Program Data

Program Data (f08jffe.d)

10.3 Program Results

Program Results (f08jffe.r)

F08 Chapter Contents
F08 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F08JGF (DPTEQR) : NAG Library, Mark 26

F08 Chapter Contents
F08 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F08JGF (DPTEQR)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.
Warning. The specification of the argument WORK changed at Mark 20: the length of WORK needs to be increased.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F08JGF (DPTEQR) computes all the eigenvalues and, optionally, all the eigenvectors of a real symmetric positive definite tridiagonal matrix, or of a real symmetric positive definite matrix which has been reduced to tridiagonal form.

2 Specification

SUBROUTINE F08JGF ( COMPZ, N, D, E, Z, LDZ, WORK, INFO)
INTEGER | N, LDZ, INFO
REAL (KIND=nag_wp) | D(*), E(*), Z(LDZ,*), WORK(4*N)
CHARACTER(1) | COMPZ
The routine may be called by its LAPACK name dpteqr.

3 Description

F08JGF (DPTEQR) computes all the eigenvalues and, optionally, all the eigenvectors of a real symmetric positive definite tridiagonal matrix T. In other words, it can compute the spectral factorization of T as
T=ZΛ ZT,
where Λ is a diagonal matrix whose diagonal elements are the eigenvalues λi, and Z is the orthogonal matrix whose columns are the eigenvectors zi. Thus
T zi=λizi,  i=1,2,…,n.
The routine may also be used to compute all the eigenvalues and eigenvectors of a real symmetric positive definite matrix A which has been reduced to tridiagonal form T:
A =QT QT, where ​Q​ is orthogonal =QZ Λ QZ T.
In this case, the matrix Q must be formed explicitly and passed to F08JGF (DPTEQR), which must be called with COMPZ='V'. The routines which must be called to perform the reduction to tridiagonal form and form Q are:
full matrix | F08FEF (DSYTRD) and F08FFF (DORGTR)
full matrix, packed storage | F08GEF (DSPTRD) and F08GFF (DOPGTR)
band matrix | F08HEF (DSBTRD) with VECT='V'.
F08JGF (DPTEQR) first factorizes T as LD LT where L is unit lower bidiagonal and D is diagonal. It forms the bidiagonal matrix B=L D 12, and then calls F08MEF (DBDSQR) to compute the singular values of B which are the same as the eigenvalues of T. The method used by the routine allows high relative accuracy to be achieved in the small eigenvalues of T. The eigenvectors are normalized so that zi 2=1, but are determined only to within a factor ±1.

4 References

Barlow J and Demmel J W (1990) Computing accurate eigensystems of scaled diagonally dominant matrices SIAM J. Numer. Anal. 27 762–791

5 Arguments

1:   COMPZ – CHARACTER(1)Input
On entry: indicates whether the eigenvectors are to be computed.
COMPZ='N'
Only the eigenvalues are computed (and the array Z is not referenced).
COMPZ='V'
The eigenvalues and eigenvectors of A are computed (and the array Z must contain the matrix Q on entry).
COMPZ='I'
The eigenvalues and eigenvectors of T are computed (and the array Z is initialized by the routine).
Constraint: COMPZ='N', 'V' or 'I'.
2:   N – INTEGERInput
On entry: n, the order of the matrix T.
Constraint: N≥0.
3:   D* – REAL (KIND=nag_wp) arrayInput/Output
Note: the dimension of the array D must be at least max 1,N.
On entry: the diagonal elements of the tridiagonal matrix T.
On exit: the n eigenvalues in descending order, unless INFO>0, in which case D is overwritten.
4:   E* – REAL (KIND=nag_wp) arrayInput/Output
Note: the dimension of the array E must be at least max 1,N-1.
On entry: the off-diagonal elements of the tridiagonal matrix T.
On exit: E is overwritten.
5:   Z LDZ* – REAL (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array Z must be at least max 1,N if COMPZ='V' or 'I' and at least 1 if COMPZ='N'.
On entry: if COMPZ='V', Z must contain the orthogonal matrix Q from the reduction to tridiagonal form.
If COMPZ='I', Z need not be set.
On exit: if COMPZ='V' or 'I', the n required orthonormal eigenvectors stored as columns of Z; the ith column corresponds to the ith eigenvalue, where i=1,2,…,n, unless INFO>0.
If COMPZ='N', Z is not referenced.
6:   LDZ – INTEGERInput
On entry: the first dimension of the array Z as declared in the (sub)program from which F08JGF (DPTEQR) is called.
Constraints:
  • if COMPZ='V' or 'I', LDZ≥ max 1,N ;
  • if COMPZ='N', LDZ≥1.
7:   WORK 4×N – REAL (KIND=nag_wp) arrayWorkspace
8:   INFO – INTEGEROutput
On exit: INFO=0 unless the routine detects an error (see Section 6).

6 Error Indicators and Warnings

INFO<0
If INFO=-i, argument i had an illegal value. An explanatory message is output, and execution of the program is terminated.
INFO>0
If INFO=i, the leading minor of order i is not positive definite and the Cholesky factorization of T could not be completed. Hence T itself is not positive definite.
If INFO=N+i, the algorithm to compute the singular values of the Cholesky factor B failed to converge; i off-diagonal elements did not converge to zero.

7 Accuracy

The eigenvalues and eigenvectors of T are computed to high relative accuracy which means that if they vary widely in magnitude, then any small eigenvalues (and corresponding eigenvectors) will be computed more accurately than, for example, with the standard QR method. However, the reduction to tridiagonal form (prior to calling the routine) may exclude the possibility of obtaining high relative accuracy in the small eigenvalues of the original matrix if its eigenvalues vary widely in magnitude.
To be more precise, let H be the tridiagonal matrix defined by H=DTD, where D is diagonal with d ii = t ii -12 , and h ii = 1 for all i. If λi is an exact eigenvalue of T and λ~i is the corresponding computed value, then
λ~i - λi ≤ c n ε κ 2 H λi
where c n is a modestly increasing function of n, ε is the machine precision, and κ 2 H is the condition number of H with respect to inversion defined by: κ 2 H=H·H-1.
If zi is the corresponding exact eigenvector of T, and z~i is the corresponding computed eigenvector, then the angle θ z~i,zi between them is bounded as follows:
θ z~i,zi ≤ c n ε κ 2 H relgapi
where relgapi is the relative gap between λi and the other eigenvalues, defined by
relgapi = min i≠j λi - λj λi + λj .

8 Parallelism and Performance

F08JGF (DPTEQR) is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
F08JGF (DPTEQR) makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The total number of floating-point operations is typically about 30 n 2 if COMPZ='N' and about 6 n 3 if COMPZ='V' or 'I', but depends on how rapidly the algorithm converges. When COMPZ='N', the operations are all performed in scalar mode; the additional operations to compute the eigenvectors when COMPZ='V' or 'I' can be vectorized and on some machines may be performed much faster.
The complex analogue of this routine is F08JUF (ZPTEQR).

10 Example

This example computes all the eigenvalues and eigenvectors of the symmetric positive definite tridiagonal matrix T, where
T = 4.16 3.17 0.00 0.00 3.17 5.25 -0.97 0.00 0.00 -0.97 1.09 0.55 0.00 0.00 0.55 0.62 .

10.1 Program Text

Program Text (f08jgfe.f90)

10.2 Program Data

Program Data (f08jgfe.d)

10.3 Program Results

Program Results (f08jgfe.r)

F08 Chapter Contents
F08 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F08JHF (DSTEDC) : NAG Library, Mark 26

F08 Chapter Contents
F08 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F08JHF (DSTEDC)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F08JHF (DSTEDC) computes all the eigenvalues and, optionally, all the eigenvectors of a real n by n symmetric tridiagonal matrix, or of a real full or banded symmetric matrix which has been reduced to tridiagonal form.

2 Specification

SUBROUTINE F08JHF ( COMPZ, N, D, E, Z, LDZ, WORK, LWORK, IWORK, LIWORK, INFO)
INTEGER | N, LDZ, LWORK, IWORK(max(1,LIWORK)), LIWORK, INFO
REAL (KIND=nag_wp) | D(*), E(*), Z(LDZ,*), WORK(max(1,LWORK))
CHARACTER(1) | COMPZ
The routine may be called by its LAPACK name dstedc.

3 Description

F08JHF (DSTEDC) computes all the eigenvalues and, optionally, the eigenvectors of a real symmetric tridiagonal matrix T. That is, the routine computes the spectral factorization of T given by
T = Z Λ ZT ,
where Λ is a diagonal matrix whose diagonal elements are the eigenvalues, λi, of T and Z is an orthogonal matrix whose columns are the eigenvectors, zi, of T. Thus
T zi = λi zi ,   i = 1,2,…,n .
The routine may also be used to compute all the eigenvalues and vectors of a real full, or banded, symmetric matrix A which has been reduced to tridiagonal form T as
A = QT QT ,
where Q is orthogonal. The spectral factorization of A is then given by
A = QZ Λ QZ T .
In this case Q must be formed explicitly and passed to F08JHF (DSTEDC) in the array Z, and the routine called with COMPZ='V'. Routines which may be called to form T and Q are
full matrix | F08FEF (DSYTRD) and F08FFF (DORGTR)
full matrix, packed storage | F08GEF (DSPTRD) and F08GFF (DOPGTR)
band matrix | F08HEF (DSBTRD), with VECT='V'
When only eigenvalues are required then this routine calls F08JFF (DSTERF) to compute the eigenvalues of the tridiagonal matrix T, but when eigenvectors of T are also required and the matrix is not too small, then a divide and conquer method is used, which can be much faster than F08JEF (DSTEQR), although more storage is required.

4 References

Anderson E, Bai Z, Bischof C, Blackford S, Demmel J, Dongarra J J, Du Croz J J, Greenbaum A, Hammarling S, McKenney A and Sorensen D (1999) LAPACK Users' Guide (3rd Edition) SIAM, Philadelphia http://www.netlib.org/lapack/lug
Golub G H and Van Loan C F (1996) Matrix Computations (3rd Edition) Johns Hopkins University Press, Baltimore

5 Arguments

1:   COMPZ – CHARACTER(1)Input
On entry: indicates whether the eigenvectors are to be computed.
COMPZ='N'
Only the eigenvalues are computed (and the array Z is not referenced).
COMPZ='V'
The eigenvalues and eigenvectors of A are computed (and the array Z must contain the matrix Q on entry).
COMPZ='I'
The eigenvalues and eigenvectors of T are computed (and the array Z is initialized by the routine).
Constraint: COMPZ='N', 'V' or 'I'.
2:   N – INTEGERInput
On entry: n, the order of the symmetric tridiagonal matrix T.
Constraint: N≥0.
3:   D* – REAL (KIND=nag_wp) arrayInput/Output
Note: the dimension of the array D must be at least max 1,N.
On entry: the diagonal elements of the tridiagonal matrix.
On exit: if INFO=0, the eigenvalues in ascending order.
4:   E* – REAL (KIND=nag_wp) arrayInput/Output
Note: the dimension of the array E must be at least max 1,N-1.
On entry: the subdiagonal elements of the tridiagonal matrix.
On exit: E is overwritten.
5:   Z LDZ* – REAL (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array Z must be at least max 1,N if COMPZ='V' or 'I', and at least 1 otherwise.
On entry: if COMPZ='V', Z must contain the orthogonal matrix Q used in the reduction to tridiagonal form.
On exit: if COMPZ='V', Z contains the orthonormal eigenvectors of the original symmetric matrix A, and if COMPZ='I', Z contains the orthonormal eigenvectors of the symmetric tridiagonal matrix T.
If COMPZ='N', Z is not referenced.
6:   LDZ – INTEGERInput
On entry: the first dimension of the array Z as declared in the (sub)program from which F08JHF (DSTEDC) is called.
Constraints:
  • if COMPZ='V' or 'I', LDZ≥ max 1,N ;
  • otherwise LDZ≥1.
7:   WORK max 1,LWORK – REAL (KIND=nag_wp) arrayWorkspace
On exit: if INFO=0, WORK 1 contains the minimum value of LWORK required for optimal performance.
8:   LWORK – INTEGERInput
On entry: the dimension of the array WORK as declared in the (sub)program from which F08JHF (DSTEDC) is called.
If LWORK=-1, a workspace query is assumed; the routine only calculates the minimum sizes of the WORK and IWORK arrays, returns these values as the first entries of the WORK and IWORK arrays, and no error message related to LWORK or LIWORK is issued.
Constraints:
if LWORK≠-1,
  • if COMPZ='N' or N≤1, LWORK must be at least 1;
  • if COMPZ='V' and N>1, LWORK must be at least 1+3×N+2×N×lg N+4×N 2, where lg N= smallest integer k such that 2 k≥N;
  • if COMPZ='I' and N>1, LWORK must be at least 1+4×N+N 2.
Note: that for COMPZ='V' or 'I' then if N is less than or equal to the minimum divide size, usually 25, then LWORK need only be max 1,2×N-1 .
9:   IWORK max 1,LIWORK – INTEGER arrayWorkspace
On exit: if INFO=0, IWORK 1 returns the minimum LIWORK.
10:   LIWORK – INTEGERInput
On entry: the dimension of the array IWORK as declared in the (sub)program from which F08JHF (DSTEDC) is called.
If LIWORK=-1, a workspace query is assumed; the routine only calculates the minimum sizes of the WORK and IWORK arrays, returns these values as the first entries of the WORK and IWORK arrays, and no error message related to LWORK or LIWORK is issued.
Constraints:
if LIWORK≠-1,
  • if COMPZ='N' or N≤1, LIWORK must be at least 1;
  • if COMPZ='V' and N>1, LIWORK must be at least 6+6×N+5×N×lg N;
  • if COMPZ='I' and N>1, LIWORK must be at least 3+5×N.
Note: that for COMPZ='V' or 'I', then if N is less than or equal to the minimum divide size, usually 25, then LIWORK need only be 1.
11:   INFO – INTEGEROutput
On exit: INFO=0 unless the routine detects an error (see Section 6).

6 Error Indicators and Warnings

INFO<0
If INFO=-i, argument i had an illegal value. An explanatory message is output, and execution of the program is terminated.
INFO>0
The algorithm failed to compute an eigenvalue while working on the submatrix lying in rows and columns INFO/N+1 through INFO mod N+1.

7 Accuracy

The computed eigenvalues and eigenvectors are exact for a nearby matrix T+E, where
E 2 = O ε T 2 ,
and ε is the machine precision.
If λi is an exact eigenvalue and λ~i is the corresponding computed value, then
λ~i - λi ≤ c n ε T 2 ,
where c n is a modestly increasing function of n.
If zi is the corresponding exact eigenvector, and z~i is the corresponding computed eigenvector, then the angle θ z~i,zi between them is bounded as follows:
θ z~i,zi ≤ c n ε T 2 min i≠j λi-λj .
Thus the accuracy of a computed eigenvector depends on the gap between its eigenvalue and all the other eigenvalues.
See Section 4.7 of Anderson et al. (1999) for further details. See also F08FLF (DDISNA).

8 Parallelism and Performance

F08JHF (DSTEDC) is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
F08JHF (DSTEDC) makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

If only eigenvalues are required, the total number of floating-point operations is approximately proportional to n 2. When eigenvectors are required the number of operations is bounded above by approximately the same number of operations as F08JEF (DSTEQR), but for large matrices F08JHF (DSTEDC) is usually much faster.
The complex analogue of this routine is F08JVF (ZSTEDC).

10 Example

This example finds all the eigenvalues and eigenvectors of the symmetric band matrix
A = 4.99 0.04 0.22 0.00 0.04 1.05 -0.79 1.04 0.22 -0.79 -2.31 -1.30 0.00 1.04 -1.30 -0.43 .
A is first reduced to tridiagonal form by a call to F08HEF (DSBTRD).

10.1 Program Text

Program Text (f08jhfe.f90)

10.2 Program Data

Program Data (f08jhfe.d)

10.3 Program Results

Program Results (f08jhfe.r)

F08 Chapter Contents
F08 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F08JJF (DSTEBZ) : NAG Library, Mark 26

F08 Chapter Contents
F08 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F08JJF (DSTEBZ)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
10 Example

1 Purpose

F08JJF (DSTEBZ) computes some (or all) of the eigenvalues of a real symmetric tridiagonal matrix, by bisection.

2 Specification

SUBROUTINE F08JJF ( RANGE, ORDER, N, VL, VU, IL, IU, ABSTOL, D, E, M, NSPLIT, W, IBLOCK, ISPLIT, WORK, IWORK, INFO)
INTEGER | N, IL, IU, M, NSPLIT, IBLOCK(N), ISPLIT(N), IWORK(3*N), INFO
REAL (KIND=nag_wp) | VL, VU, ABSTOL, D(*), E(*), W(N), WORK(4*N)
CHARACTER(1) | RANGE, ORDER
The routine may be called by its LAPACK name dstebz.

3 Description

F08JJF (DSTEBZ) uses bisection to compute some or all of the eigenvalues of a real symmetric tridiagonal matrix T.
It searches for zero or negligible off-diagonal elements of T to see if the matrix splits into block diagonal form:
T = T 1 T 2 . . . Tp .
It performs bisection on each of the blocks Ti and returns the block index of each computed eigenvalue, so that a subsequent call to F08JKF (DSTEIN) to compute eigenvectors can also take advantage of the block structure.

4 References

Kahan W (1966) Accurate eigenvalues of a symmetric tridiagonal matrix Report CS41 Stanford University

5 Arguments

1:   RANGE – CHARACTER(1)Input
On entry: indicates which eigenvalues are required.
RANGE='A'
All the eigenvalues are required.
RANGE='V'
All the eigenvalues in the half-open interval (VL,VU] are required.
RANGE='I'
Eigenvalues with indices IL to IU are required.
Constraint: RANGE='A', 'V' or 'I'.
2:   ORDER – CHARACTER(1)Input
On entry: indicates the order in which the eigenvalues and their block numbers are to be stored.
ORDER='B'
The eigenvalues are to be grouped by split-off block and ordered from smallest to largest within each block.
ORDER='E'
The eigenvalues for the entire matrix are to be ordered from smallest to largest.
Constraint: ORDER='B' or 'E'.
3:   N – INTEGERInput
On entry: n, the order of the matrix T.
Constraint: N≥0.
4:   VL – REAL (KIND=nag_wp)Input
5:   VU – REAL (KIND=nag_wp)Input
On entry: if RANGE='V', the lower and upper bounds, respectively, of the half-open interval
(VL,VU] within which the required eigenvalues lie.
If RANGE='A' or 'I', VL is not referenced.
Constraint: if RANGE='V', VL<VU.
6:   IL – INTEGERInput
7:   IU – INTEGERInput
On entry: if RANGE='I', the indices of the first and last eigenvalues, respectively, to be computed (assuming that the eigenvalues are in ascending order).
If RANGE='A' or 'V', IL is not referenced.
Constraint: if RANGE='I', 1≤ IL≤ IU≤ N .
8:   ABSTOL – REAL (KIND=nag_wp)Input
On entry: the absolute tolerance to which each eigenvalue is required. An eigenvalue (or cluster) is considered to have converged if it lies in an interval of width ≤ABSTOL. If ABSTOL≤0.0, then the tolerance is taken as machine precision×T 1.
9:   D* – REAL (KIND=nag_wp) arrayInput
Note: the dimension of the array D must be at least max 1,N.
On entry: the diagonal elements of the tridiagonal matrix T.
10:   E* – REAL (KIND=nag_wp) arrayInput
Note: the dimension of the array E must be at least max 1,N-1.
On entry: the off-diagonal elements of the tridiagonal matrix T.
11:   M – INTEGEROutput
On exit: m, the actual number of eigenvalues found.
12:   NSPLIT – INTEGEROutput
On exit: the number of diagonal blocks which constitute the tridiagonal matrix T.
13:   W N – REAL (KIND=nag_wp) arrayOutput
On exit: the required eigenvalues of the tridiagonal matrix T stored in W 1 to W m.
14:   IBLOCK N – INTEGER arrayOutput
On exit: at each row/column j where E j is zero or negligible, T is considered to split into a block diagonal matrix and IBLOCK i contains the block number of the eigenvalue stored in W i, for i=1,2,…,m. Note that IBLOCK i<0 for some i whenever INFO=1 or 3 (see Section 6) and RANGE='A' or 'V'.
15:   ISPLIT N – INTEGER arrayOutput
On exit: the leading NSPLIT elements contain the points at which T splits up into sub-matrices as follows. The first sub-matrix consists of rows/columns 1 to ISPLIT 1, the second sub-matrix consists of rows/columns ISPLIT 1+1 to ISPLIT 2, …, and the NSPLIT(th) sub-matrix consists of rows/columns ISPLIT NSPLIT-1+1 to ISPLIT NSPLIT (=n).
16:   WORK 4×N – REAL (KIND=nag_wp) arrayWorkspace
17:   IWORK 3×N – INTEGER arrayWorkspace
18:   INFO – INTEGEROutput
On exit: INFO=0 unless the routine detects an error (see Section 6).

6 Error Indicators and Warnings

INFO<0
If INFO=-i, argument i had an illegal value. An explanatory message is output, and execution of the program is terminated.
INFO=1
If RANGE='A' or 'V', the algorithm failed to compute some (or all) of the required eigenvalues to the required accuracy. More precisely, IBLOCK i<0 indicates that eigenvalue i (stored in W i) failed to converge.
INFO=2
If RANGE='I', the algorithm failed to compute some (or all) of the required eigenvalues. Try calling the routine again with RANGE='A'.
INFO=3
If RANGE='I', see the description above for INFO=2.
If RANGE='A' or 'V', see the description above for INFO=1.
INFO=4
No eigenvalues have been computed. The floating-point arithmetic on the computer is not behaving as expected.
If failures with INFO≥1 are causing persistent trouble and you have checked that the routine is being called correctly, please contact NAG.

7 Accuracy

The eigenvalues of T are computed to high relative accuracy which means that if they vary widely in magnitude, then any small eigenvalues will be computed more accurately than, for example, with the standard QR method. However, the reduction to tridiagonal form (prior to calling the routine) may exclude the possibility of obtaining high relative accuracy in the small eigenvalues of the original matrix if its eigenvalues vary widely in magnitude.

8 Parallelism and Performance

F08JJF (DSTEBZ) is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

There is no complex analogue of this routine.

10 Example

See Section 10 in F08FGF (DORMTR).
F08 Chapter Contents
F08 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F08JKF (DSTEIN) : NAG Library, Mark 26

F08 Chapter Contents
F08 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F08JKF (DSTEIN)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
10 Example

1 Purpose

F08JKF (DSTEIN) computes the eigenvectors of a real symmetric tridiagonal matrix corresponding to specified eigenvalues, by inverse iteration.

2 Specification

SUBROUTINE F08JKF ( N, D, E, M, W, IBLOCK, ISPLIT, Z, LDZ, WORK, IWORK, IFAILV, INFO)
INTEGER | N, M, IBLOCK(*), ISPLIT(*), LDZ, IWORK(N), IFAILV(M), INFO
REAL (KIND=nag_wp) | D(*), E(*), W(*), Z(LDZ,*), WORK(5*N)
The routine may be called by its LAPACK name dstein.

3 Description

F08JKF (DSTEIN) computes the eigenvectors of a real symmetric tridiagonal matrix T corresponding to specified eigenvalues, by inverse iteration (see Jessup and Ipsen (1992)). It is designed to be used in particular after the specified eigenvalues have been computed by F08JJF (DSTEBZ) with ORDER='B', but may also be used when the eigenvalues have been computed by other routines in Chapters F02 or F08.
If T has been formed by reduction of a full real symmetric matrix A to tridiagonal form, then eigenvectors of T may be transformed to eigenvectors of A by a call to F08FGF (DORMTR) or F08GGF (DOPMTR).
F08JJF (DSTEBZ) determines whether the matrix T splits into block diagonal form:
T = T 1 T 2 . . . Tp
and passes details of the block structure to this routine in the arrays IBLOCK and ISPLIT. This routine can then take advantage of the block structure by performing inverse iteration on each block Ti separately, which is more efficient than using the whole matrix.

4 References

Golub G H and Van Loan C F (1996) Matrix Computations (3rd Edition) Johns Hopkins University Press, Baltimore
Jessup E and Ipsen I C F (1992) Improving the accuracy of inverse iteration SIAM J. Sci. Statist. Comput. 13 550–572

5 Arguments

1:   N – INTEGERInput
On entry: n, the order of the matrix T.
Constraint: N≥0.
2:   D* – REAL (KIND=nag_wp) arrayInput
Note: the dimension of the array D must be at least max 1,N.
On entry: the diagonal elements of the tridiagonal matrix T.
3:   E* – REAL (KIND=nag_wp) arrayInput
Note: the dimension of the array E must be at least max 1,N-1.
On entry: the off-diagonal elements of the tridiagonal matrix T.
4:   M – INTEGERInput
On entry: m, the number of eigenvectors to be returned.
Constraint: 0≤M≤N.
5:   W* – REAL (KIND=nag_wp) arrayInput
Note: the dimension of the array W must be at least max 1,N.
On entry: the eigenvalues of the tridiagonal matrix T stored in W 1 to W m, as returned by F08JJF (DSTEBZ) with ORDER='B'. Eigenvalues associated with the first sub-matrix must be supplied first, in nondecreasing order; then those associated with the second sub-matrix, again in nondecreasing order; and so on.
Constraint: if IBLOCK i=IBLOCK i+1, W i≤W i+1, for i=1,2,…,M-1.
6:   IBLOCK* – INTEGER arrayInput
Note: the dimension of the array IBLOCK must be at least max 1,N.
On entry: the first m elements must contain the sub-matrix indices associated with the specified eigenvalues, as returned by F08JJF (DSTEBZ) with ORDER='B'. If the eigenvalues were not computed by F08JJF (DSTEBZ) with ORDER='B', set IBLOCK i to 1, for i=1,2,…,m.
Constraint: IBLOCK i≤IBLOCK i+1, for i=1,2,…,M-1.
7:   ISPLIT* – INTEGER arrayInput
Note: the dimension of the array ISPLIT must be at least max 1,N.
On entry: the points at which T breaks up into sub-matrices, as returned by F08JJF (DSTEBZ) with ORDER='B'. If the eigenvalues were not computed by F08JJF (DSTEBZ) with ORDER='B', set ISPLIT 1 to N.
8:   Z LDZ* – REAL (KIND=nag_wp) arrayOutput
Note: the second dimension of the array Z must be at least max 1,M.
On exit: the m eigenvectors, stored as columns of Z; the ith column corresponds to the ith specified eigenvalue, unless INFO>0 (in which case see Section 6).
9:   LDZ – INTEGERInput
On entry: the first dimension of the array Z as declared in the (sub)program from which F08JKF (DSTEIN) is called.
Constraint: LDZ≥ max 1,N .
10:   WORK 5×N – REAL (KIND=nag_wp) arrayWorkspace
11:   IWORK N – INTEGER arrayWorkspace
12:   IFAILV M – INTEGER arrayOutput
On exit: if INFO=i>0, the first i elements of IFAILV contain the indices of any eigenvectors which have failed to converge. The rest of the first M elements of IFAILV are set to 0.
13:   INFO – INTEGEROutput
On exit: INFO=0 unless the routine detects an error (see Section 6).

6 Error Indicators and Warnings

INFO<0
If INFO=-i, argument i had an illegal value. An explanatory message is output, and execution of the program is terminated.
INFO>0
If INFO=i, then i eigenvectors (as indicated by the argument IFAILV above) each failed to converge in five iterations. The current iterate after five iterations is stored in the corresponding column of Z.

7 Accuracy

Each computed eigenvector zi is the exact eigenvector of a nearby matrix A+Ei, such that
Ei = O ε A ,
where ε is the machine precision. Hence the residual is small:
A zi - λi zi = O ε A .
However, a set of eigenvectors computed by this routine may not be orthogonal to so high a degree of accuracy as those computed by F08JEF (DSTEQR).

8 Parallelism and Performance

F08JKF (DSTEIN) is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
F08JKF (DSTEIN) makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The complex analogue of this routine is F08JXF (ZSTEIN).

10 Example

See Section 10 in F08FGF (DORMTR).
F08 Chapter Contents
F08 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F08JLF (DSTEGR) : NAG Library, Mark 26

F08 Chapter Contents
F08 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F08JLF (DSTEGR)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F08JLF (DSTEGR) computes all the eigenvalues and, optionally, all the eigenvectors of a real n by n symmetric tridiagonal matrix.

2 Specification

SUBROUTINE F08JLF ( JOBZ, RANGE, N, D, E, VL, VU, IL, IU, ABSTOL, M, W, Z, LDZ, ISUPPZ, WORK, LWORK, IWORK, LIWORK, INFO)
INTEGER | N, IL, IU, M, LDZ, ISUPPZ(*), LWORK, IWORK(max(1,LIWORK)), LIWORK, INFO
REAL (KIND=nag_wp) | D(*), E(*), VL, VU, ABSTOL, W(*), Z(LDZ,*), WORK(max(1,LWORK))
CHARACTER(1) | JOBZ, RANGE
The routine may be called by its LAPACK name dstegr.

3 Description

F08JLF (DSTEGR) computes all the eigenvalues and, optionally, the eigenvectors, of a real symmetric tridiagonal matrix T. That is, the routine computes the spectral factorization of T given by
T = ZΛ ZT ,
where Λ is a diagonal matrix whose diagonal elements are the eigenvalues, λi, of T and Z is an orthogonal matrix whose columns are the eigenvectors, zi, of T. Thus
T zi= λi zi ,   i = 1,2,…,n .
The routine may also be used to compute all the eigenvalues and eigenvectors of a real symmetric matrix A which has been reduced to tridiagonal form T:
A =QT QT, where ​Q​ is orthogonal =QZ Λ QZ T.
In this case, the matrix Q must be explicitly applied to the output matrix Z. The routines which must be called to perform the reduction to tridiagonal form and apply Q are:
full matrix | F08FEF (DSYTRD) and F08FGF (DORMTR)
full matrix, packed storage | F08GEF (DSPTRD) and F08GGF (DOPMTR)
band matrix | F08HEF (DSBTRD) with VECT='V' and F06YAF (DGEMM).
This routine uses the dqds and the Relatively Robust Representation algorithms to compute the eigenvalues and eigenvectors respectively; see for example Parlett and Dhillon (2000) and Dhillon and Parlett (2004) for further details. F08JLF (DSTEGR) can usually compute all the eigenvalues and eigenvectors in O n 2 floating-point operations and so, for large matrices, is often considerably faster than the other symmetric tridiagonal routines in this chapter when all the eigenvectors are required, particularly so compared to those routines that are based on the QR algorithm.

4 References

Anderson E, Bai Z, Bischof C, Blackford S, Demmel J, Dongarra J J, Du Croz J J, Greenbaum A, Hammarling S, McKenney A and Sorensen D (1999) LAPACK Users' Guide (3rd Edition) SIAM, Philadelphia http://www.netlib.org/lapack/lug
Barlow J and Demmel J W (1990) Computing accurate eigensystems of scaled diagonally dominant matrices SIAM J. Numer. Anal. 27 762–791
Dhillon I S and Parlett B N (2004) Orthogonal eigenvectors and relative gaps. SIAM J. Appl. Math. 25 858–899
Parlett B N and Dhillon I S (2000) Relatively robust representations of symmetric tridiagonals Linear Algebra Appl. 309 121–151

5 Arguments

1:   JOBZ – CHARACTER(1)Input
On entry: indicates whether eigenvectors are computed.
JOBZ='N'
Only eigenvalues are computed.
JOBZ='V'
Eigenvalues and eigenvectors are computed.
Constraint: JOBZ='N' or 'V'.
2:   RANGE – CHARACTER(1)Input
On entry: indicates which eigenvalues should be returned.
RANGE='A'
All eigenvalues will be found.
RANGE='V'
All eigenvalues in the half-open interval VL,VU will be found.
RANGE='I'
The ILth through IUth eigenvectors will be found.
Constraint: RANGE='A', 'V' or 'I'.
3:   N – INTEGERInput
On entry: n, the order of the matrix T.
Constraint: N≥0.
4:   D* – REAL (KIND=nag_wp) arrayInput/Output
Note: the dimension of the array D must be at least max 1,N.
On entry: the n diagonal elements of the tridiagonal matrix T.
On exit: D is overwritten.
5:   E* – REAL (KIND=nag_wp) arrayInput/Output
Note: the dimension of the array E must be at least max 1,N.
On entry: E 1:N-1 contains the subdiagonal elements of the tridiagonal matrix T. E N need not be set.
On exit: E is overwritten.
6:   VL – REAL (KIND=nag_wp)Input
7:   VU – REAL (KIND=nag_wp)Input
On entry: if RANGE='V', VL and VU contain the lower and upper bounds respectively of the interval to be searched for eigenvalues.
If RANGE='A' or 'I', VL and VU are not referenced.
Constraint: if RANGE='V', VL<VU.
8:   IL – INTEGERInput
9:   IU – INTEGERInput
On entry: if RANGE='I', IL and IU contains the indices (in ascending order) of the smallest and largest eigenvalues to be returned, respectively.
If RANGE='A' or 'V', IL and IU are not referenced.
Constraints:
  • if RANGE='I' and N>0, 1≤ IL≤ IU≤ N ;
  • if RANGE='I' and N=0, IL=1 and IU=0.
10:   ABSTOL – REAL (KIND=nag_wp)Input
On entry: in earlier versions, this argument was the absolute error tolerance for the eigenvalues/eigenvectors. It is now deprecated, and only included for backwards-compatibility.
11:   M – INTEGEROutput
On exit: the total number of eigenvalues found. 0≤M≤N.
If RANGE='A', M=N.
If RANGE='I', M=IU-IL+1.
12:   W* – REAL (KIND=nag_wp) arrayOutput
Note: the dimension of the array W must be at least max 1,N.
On exit: the eigenvalues in ascending order.
13:   Z LDZ* – REAL (KIND=nag_wp) arrayOutput
Note: the second dimension of the array Z must be at least max 1,M if JOBZ='V', and at least 1 otherwise.
On exit: if JOBZ='V', then if INFO=0, the columns of Z contain the orthonormal eigenvectors of the matrix T, with the ith column of Z holding the eigenvector associated with W i.
If JOBZ='N', Z is not referenced.
Note: you must ensure that at least max 1,M columns are supplied in the array Z; if RANGE='V', the exact value of M is not known in advance and an upper bound of at least N must be used.
14:   LDZ – INTEGERInput
On entry: the first dimension of the array Z as declared in the (sub)program from which F08JLF (DSTEGR) is called.
Constraints:
  • if JOBZ='V', LDZ≥ max 1,N ;
  • otherwise LDZ≥1.
15:   ISUPPZ* – INTEGER arrayOutput
Note: the dimension of the array ISUPPZ must be at least max 1,2×M.
On exit: the support of the eigenvectors in Z, i.e., the indices indicating the nonzero elements in Z. The ith eigenvector is nonzero only in elements ISUPPZ 2×i-1 through ISUPPZ 2×i.
16:   WORK max 1,LWORK – REAL (KIND=nag_wp) arrayWorkspace
On exit: if INFO=0, WORK 1 returns the minimum LWORK.
17:   LWORK – INTEGERInput
On entry: the dimension of the array WORK as declared in the (sub)program from which F08JLF (DSTEGR) is called.
If LWORK=-1, a workspace query is assumed; the routine only calculates the minimum sizes of the WORK and IWORK arrays, returns these values as the first entries of the WORK and IWORK arrays, and no error message related to LWORK or LIWORK is issued.
Constraint: LWORK≥max 1,18×N or LWORK=-1.
18:   IWORK max 1,LIWORK – INTEGER arrayWorkspace
On exit: if INFO=0, WORK 1 returns the minimum LIWORK.
19:   LIWORK – INTEGERInput
On entry: the dimension of the array IWORK as declared in the (sub)program from which F08JLF (DSTEGR) is called.
If LIWORK=-1, a workspace query is assumed; the routine only calculates the minimum sizes of the WORK and IWORK arrays, returns these values as the first entries of the WORK and IWORK arrays, and no error message related to LWORK or LIWORK is issued.
Constraint: LIWORK≥max 1,10×N or LIWORK=-1.
20:   INFO – INTEGEROutput
On exit: INFO=0 unless the routine detects an error (see Section 6).

6 Error Indicators and Warnings

INFO<0
If INFO=-i, argument i had an illegal value. An explanatory message is output, and execution of the program is terminated.
INFO>0
If INFO=1, the dqds algorithm failed to converge, if INFO=2, inverse iteration failed to converge.

7 Accuracy

See the description for ABSTOL. See also Section 4.7 of Anderson et al. (1999) and Barlow and Demmel (1990) for further details.

8 Parallelism and Performance

F08JLF (DSTEGR) is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
F08JLF (DSTEGR) makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The total number of floating-point operations required to compute all the eigenvalues and eigenvectors is approximately proportional to n 2.
The complex analogue of this routine is F08JYF (ZSTEGR).

10 Example

This example finds all the eigenvalues and eigenvectors of the symmetric tridiagonal matrix
T = 1.0 1.0 0.0 0.0 1.0 4.0 2.0 0.0 0.0 2.0 9.0 3.0 0.0 0.0 3.0 16.0 .
ABSTOL is set to zero so that the default tolerance of nε T 1 is used.

10.1 Program Text

Program Text (f08jlfe.f90)

10.2 Program Data

Program Data (f08jlfe.d)

10.3 Program Results

Program Results (f08jlfe.r)

F08 Chapter Contents
F08 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F08JSF (ZSTEQR) : NAG Library, Mark 26

F08 Chapter Contents
F08 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F08JSF (ZSTEQR)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
10 Example

1 Purpose

F08JSF (ZSTEQR) computes all the eigenvalues and, optionally, all the eigenvectors of a complex Hermitian matrix which has been reduced to tridiagonal form.

2 Specification

SUBROUTINE F08JSF ( COMPZ, N, D, E, Z, LDZ, WORK, INFO)
INTEGER | N, LDZ, INFO
REAL (KIND=nag_wp) | D(*), E(*), WORK(*)
COMPLEX (KIND=nag_wp) | Z(LDZ,*)
CHARACTER(1) | COMPZ
The routine may be called by its LAPACK name zsteqr.

3 Description

F08JSF (ZSTEQR) computes all the eigenvalues and, optionally, all the eigenvectors of a real symmetric tridiagonal matrix T. In other words, it can compute the spectral factorization of T as
T=ZΛ ZT,
where Λ is a diagonal matrix whose diagonal elements are the eigenvalues λi, and Z is the orthogonal matrix whose columns are the eigenvectors zi. Thus
T zi=λizi,  i=1,2,…,n.
The routine stores the real orthogonal matrix Z in a complex array, so that it may also be used to compute all the eigenvalues and eigenvectors of a complex Hermitian matrix A which has been reduced to tridiagonal form T:
A =QT QH, where ​Q​ is unitary =QZ Λ QZ H.
In this case, the matrix Q must be formed explicitly and passed to F08JSF (ZSTEQR), which must be called with COMPZ='V'. The routines which must be called to perform the reduction to tridiagonal form and form Q are:
full matrix | F08FSF (ZHETRD) and F08FTF (ZUNGTR)
full matrix, packed storage | F08GSF (ZHPTRD) and F08GTF (ZUPGTR)
band matrix | F08HSF (ZHBTRD) with VECT='V'.
F08JSF (ZSTEQR) uses the implicitly shifted QR algorithm, switching between the QR and QL variants in order to handle graded matrices effectively (see Greenbaum and Dongarra (1980)). The eigenvectors are normalized so that zi 2=1, but are determined only to within a complex factor of absolute value 1.
If only the eigenvalues of T are required, it is more efficient to call F08JFF (DSTERF) instead. If T is positive definite, small eigenvalues can be computed more accurately by F08JUF (ZPTEQR).

4 References

Golub G H and Van Loan C F (1996) Matrix Computations (3rd Edition) Johns Hopkins University Press, Baltimore
Greenbaum A and Dongarra J J (1980) Experiments with QR/QL methods for the symmetric triangular eigenproblem LAPACK Working Note No. 17 (Technical Report CS-89-92) University of Tennessee, Knoxville http://www.netlib.org/lapack/lawnspdf/lawn17.pdf
Parlett B N (1998) The Symmetric Eigenvalue Problem SIAM, Philadelphia

5 Arguments

1:   COMPZ – CHARACTER(1)Input
On entry: indicates whether the eigenvectors are to be computed.
COMPZ='N'
Only the eigenvalues are computed (and the array Z is not referenced).
COMPZ='V'
The eigenvalues and eigenvectors of A are computed (and the array Z must contain the matrix Q on entry).
COMPZ='I'
The eigenvalues and eigenvectors of T are computed (and the array Z is initialized by the routine).
Constraint: COMPZ='N', 'V' or 'I'.
2:   N – INTEGERInput
On entry: n, the order of the matrix T.
Constraint: N≥0.
3:   D* – REAL (KIND=nag_wp) arrayInput/Output
Note: the dimension of the array D must be at least max 1,N.
On entry: the diagonal elements of the tridiagonal matrix T.
On exit: the n eigenvalues in ascending order, unless INFO>0 (in which case see Section 6).
4:   E* – REAL (KIND=nag_wp) arrayInput/Output
Note: the dimension of the array E must be at least max 1,N-1.
On entry: the off-diagonal elements of the tridiagonal matrix T.
On exit: E is overwritten.
5:   Z LDZ* – COMPLEX (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array Z must be at least max 1,N if COMPZ='V' or 'I' and at least 1 if COMPZ='N'.
On entry: if COMPZ='V', Z must contain the unitary matrix Q from the reduction to tridiagonal form.
If COMPZ='I', Z need not be set.
On exit: if COMPZ='V' or 'I', the n required orthonormal eigenvectors stored as columns of Z; the ith column corresponds to the ith eigenvalue, where i=1,2,…,n, unless INFO>0.
If COMPZ='N', Z is not referenced.
6:   LDZ – INTEGERInput
On entry: the first dimension of the array Z as declared in the (sub)program from which F08JSF (ZSTEQR) is called.
Constraints:
  • if COMPZ='V' or 'I', LDZ≥ max 1,N ;
  • if COMPZ='N', LDZ≥1.
7:   WORK* – REAL (KIND=nag_wp) arrayWorkspace
Note: the dimension of the array WORK must be at least max 1,2×N-1 if COMPZ='V' or 'I' and at least 1 if COMPZ='N'.
If COMPZ='N', WORK is not referenced.
8:   INFO – INTEGEROutput
On exit: INFO=0 unless the routine detects an error (see Section 6).

6 Error Indicators and Warnings

INFO<0
If INFO=-i, argument i had an illegal value. An explanatory message is output, and execution of the program is terminated.
INFO>0
The algorithm has failed to find all the eigenvalues after a total of 30×N iterations. In this case, D and E contain on exit the diagonal and off-diagonal elements, respectively, of a tridiagonal matrix unitarily similar to T. If INFO=i, then i off-diagonal elements have not converged to zero.

7 Accuracy

The computed eigenvalues and eigenvectors are exact for a nearby matrix T+E, where
E 2 = O ε T 2 ,
and ε is the machine precision.
If λi is an exact eigenvalue and λ~i is the corresponding computed value, then
λ~i - λi ≤ c n ε T 2 ,
where c n is a modestly increasing function of n.
If zi is the corresponding exact eigenvector, and z~i is the corresponding computed eigenvector, then the angle θ z~i,zi between them is bounded as follows:
θ z~i,zi ≤ c n ε T 2 min i≠j λi-λj .
Thus the accuracy of a computed eigenvector depends on the gap between its eigenvalue and all the other eigenvalues.

8 Parallelism and Performance

F08JSF (ZSTEQR) is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
F08JSF (ZSTEQR) makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The total number of real floating-point operations is typically about 24 n 2 if COMPZ='N' and about 14 n 3 if COMPZ='V' or 'I', but depends on how rapidly the algorithm converges. When COMPZ='N', the operations are all performed in scalar mode; the additional operations to compute the eigenvectors when COMPZ='V' or 'I' can be vectorized and on some machines may be performed much faster.
The real analogue of this routine is F08JEF (DSTEQR).

10 Example

See Section 10 in F08FTF (ZUNGTR), F08GTF (ZUPGTR) or F08HSF (ZHBTRD), which illustrate the use of this routine to compute the eigenvalues and eigenvectors of a full or band Hermitian matrix.
F08 Chapter Contents
F08 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F08JUF (ZPTEQR) : NAG Library, Mark 26

F08 Chapter Contents
F08 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F08JUF (ZPTEQR)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.
Warning. The specification of the argument WORK changed at Mark 20: the length of WORK needs to be increased.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F08JUF (ZPTEQR) computes all the eigenvalues and, optionally, all the eigenvectors of a complex Hermitian positive definite matrix which has been reduced to tridiagonal form.

2 Specification

SUBROUTINE F08JUF ( COMPZ, N, D, E, Z, LDZ, WORK, INFO)
INTEGER | N, LDZ, INFO
REAL (KIND=nag_wp) | D(*), E(*), WORK(4*N)
COMPLEX (KIND=nag_wp) | Z(LDZ,*)
CHARACTER(1) | COMPZ
The routine may be called by its LAPACK name zpteqr.

3 Description

F08JUF (ZPTEQR) computes all the eigenvalues and, optionally, all the eigenvectors of a real symmetric positive definite tridiagonal matrix T. In other words, it can compute the spectral factorization of T as
T=ZΛ ZT,
where Λ is a diagonal matrix whose diagonal elements are the eigenvalues λi, and Z is the orthogonal matrix whose columns are the eigenvectors zi. Thus
T zi=λizi,  i=1,2,…,n.
The routine stores the real orthogonal matrix Z in a complex array, so that it may be used to compute all the eigenvalues and eigenvectors of a complex Hermitian positive definite matrix A which has been reduced to tridiagonal form T:
A =QT QH, where ​Q​ is unitary =QZ Λ QZ H.
In this case, the matrix Q must be formed explicitly and passed to F08JUF (ZPTEQR), which must be called with COMPZ='V'. The routines which must be called to perform the reduction to tridiagonal form and form Q are:
full matrix | F08FSF (ZHETRD) and F08FTF (ZUNGTR)
full matrix, packed storage | F08GSF (ZHPTRD) and F08GTF (ZUPGTR)
band matrix | F08HSF (ZHBTRD) with VECT='V'.
F08JUF (ZPTEQR) first factorizes T as LD LH where L is unit lower bidiagonal and D is diagonal. It forms the bidiagonal matrix B=L D 12, and then calls F08MSF (ZBDSQR) to compute the singular values of B which are the same as the eigenvalues of T. The method used by the routine allows high relative accuracy to be achieved in the small eigenvalues of T. The eigenvectors are normalized so that zi 2=1, but are determined only to within a complex factor of absolute value 1.

4 References

Barlow J and Demmel J W (1990) Computing accurate eigensystems of scaled diagonally dominant matrices SIAM J. Numer. Anal. 27 762–791

5 Arguments

1:   COMPZ – CHARACTER(1)Input
On entry: indicates whether the eigenvectors are to be computed.
COMPZ='N'
Only the eigenvalues are computed (and the array Z is not referenced).
COMPZ='V'
The eigenvalues and eigenvectors of A are computed (and the array Z must contain the matrix Q on entry).
COMPZ='I'
The eigenvalues and eigenvectors of T are computed (and the array Z is initialized by the routine).
Constraint: COMPZ='N', 'V' or 'I'.
2:   N – INTEGERInput
On entry: n, the order of the matrix T.
Constraint: N≥0.
3:   D* – REAL (KIND=nag_wp) arrayInput/Output
Note: the dimension of the array D must be at least max 1,N.
On entry: the diagonal elements of the tridiagonal matrix T.
On exit: the n eigenvalues in descending order, unless INFO>0, in which case D is overwritten.
4:   E* – REAL (KIND=nag_wp) arrayInput/Output
Note: the dimension of the array E must be at least max 1,N-1.
On entry: the off-diagonal elements of the tridiagonal matrix T.
On exit: E is overwritten.
5:   Z LDZ* – COMPLEX (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array Z must be at least max 1,N if COMPZ='V' or 'I' and at least 1 if COMPZ='N'.
On entry: if COMPZ='V', Z must contain the unitary matrix Q from the reduction to tridiagonal form.
If COMPZ='I', Z need not be set.
On exit: if COMPZ='V' or 'I', the n required orthonormal eigenvectors stored as columns of Z; the ith column corresponds to the ith eigenvalue, where i=1,2,…,n, unless INFO>0.
If COMPZ='N', Z is not referenced.
6:   LDZ – INTEGERInput
On entry: the first dimension of the array Z as declared in the (sub)program from which F08JUF (ZPTEQR) is called.
Constraints:
  • if COMPZ='V' or 'I', LDZ≥ max 1,N ;
  • if COMPZ='N', LDZ≥1.
7:   WORK 4×N – REAL (KIND=nag_wp) arrayWorkspace
8:   INFO – INTEGEROutput
On exit: INFO=0 unless the routine detects an error (see Section 6).

6 Error Indicators and Warnings

INFO<0
If INFO=-i, argument i had an illegal value. An explanatory message is output, and execution of the program is terminated.
INFO>0
If INFO=i, the leading minor of order i is not positive definite and the Cholesky factorization of T could not be completed. Hence T itself is not positive definite.
If INFO=N+i, the algorithm to compute the singular values of the Cholesky factor B failed to converge; i off-diagonal elements did not converge to zero.

7 Accuracy

The eigenvalues and eigenvectors of T are computed to high relative accuracy which means that if they vary widely in magnitude, then any small eigenvalues (and corresponding eigenvectors) will be computed more accurately than, for example, with the standard QR method. However, the reduction to tridiagonal form (prior to calling the routine) may exclude the possibility of obtaining high relative accuracy in the small eigenvalues of the original matrix if its eigenvalues vary widely in magnitude.
To be more precise, let H be the tridiagonal matrix defined by H=DTD, where D is diagonal with d ii = t ii -12 , and h ii = 1 for all i. If λi is an exact eigenvalue of T and λ~i is the corresponding computed value, then
λ~i - λi ≤ c n ε κ 2 H λi
where c n is a modestly increasing function of n, ε is the machine precision, and κ 2 H is the condition number of H with respect to inversion defined by: κ 2 H=H·H-1.
If zi is the corresponding exact eigenvector of T, and z~i is the corresponding computed eigenvector, then the angle θ z~i,zi between them is bounded as follows:
θ z~i,zi ≤ c n ε κ 2 H relgapi
where relgapi is the relative gap between λi and the other eigenvalues, defined by
relgapi = min i≠j λi - λj λi + λj .

8 Parallelism and Performance

F08JUF (ZPTEQR) is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
F08JUF (ZPTEQR) makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The total number of real floating-point operations is typically about 30 n 2 if COMPZ='N' and about 12 n 3 if COMPZ='V' or 'I', but depends on how rapidly the algorithm converges. When COMPZ='N', the operations are all performed in scalar mode; the additional operations to compute the eigenvectors when COMPZ='V' or 'I' can be vectorized and on some machines may be performed much faster.
The real analogue of this routine is F08JGF (DPTEQR).

10 Example

This example computes all the eigenvalues and eigenvectors of the complex Hermitian positive definite matrix A, where
A = 6.02+0.00 i -0.45+0.25 i -1.30+1.74 i 1.45-0.66 i -0.45-0.25 i 2.91+0.00 i 0.05+1.56 i -1.04+1.27 i -1.30-1.74 i 0.05-1.56 i 3.29+0.00 i 0.14+1.70 i 1.45+0.66 i -1.04-1.27 i 0.14-1.70 i 4.18+0.00 i .

10.1 Program Text

Program Text (f08jufe.f90)

10.2 Program Data

Program Data (f08jufe.d)

10.3 Program Results

Program Results (f08jufe.r)

F08 Chapter Contents
F08 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F08JVF (ZSTEDC) : NAG Library, Mark 26

F08 Chapter Contents
F08 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F08JVF (ZSTEDC)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F08JVF (ZSTEDC) computes all the eigenvalues and, optionally, all the eigenvectors of a real n by n symmetric tridiagonal matrix, or of a complex full or banded Hermitian matrix which has been reduced to tridiagonal form.

2 Specification

SUBROUTINE F08JVF ( COMPZ, N, D, E, Z, LDZ, WORK, LWORK, RWORK, LRWORK, IWORK, LIWORK, INFO)
INTEGER | N, LDZ, LWORK, LRWORK, IWORK(max(1,LIWORK)), LIWORK, INFO
REAL (KIND=nag_wp) | D(*), E(*), RWORK(max(1,LRWORK))
COMPLEX (KIND=nag_wp) | Z(LDZ,*), WORK(max(1,LWORK))
CHARACTER(1) | COMPZ
The routine may be called by its LAPACK name zstedc.

3 Description

F08JVF (ZSTEDC) computes all the eigenvalues and, optionally, the eigenvectors of a real symmetric tridiagonal matrix T. That is, the routine computes the spectral factorization of T given by
T = Z Λ ZT ,
where Λ is a diagonal matrix whose diagonal elements are the eigenvalues, λi, of T and Z is an orthogonal matrix whose columns are the eigenvectors, zi, of T. Thus
T zi = λi zi ,   i = 1,2,…,n .
The routine may also be used to compute all the eigenvalues and eigenvectors of a complex full, or banded, Hermitian matrix A which has been reduced to real tridiagonal form T as
A = QT QH ,
where Q is unitary. The spectral factorization of A is then given by
A = QZ Λ QZ H .
In this case Q must be formed explicitly and passed to F08JVF (ZSTEDC) in the array Z, and the routine called with COMPZ='V'. Routines which may be called to form T and Q are
full matrix | F08FSF (ZHETRD) and F08FTF (ZUNGTR)
full matrix, packed storage | F08GSF (ZHPTRD) and F08GTF (ZUPGTR)
band matrix | F08HSF (ZHBTRD), with VECT='V'
When only eigenvalues are required then this routine calls F08JFF (DSTERF) to compute the eigenvalues of the tridiagonal matrix T, but when eigenvectors of T are also required and the matrix is not too small, then a divide and conquer method is used, which can be much faster than F08JSF (ZSTEQR), although more storage is required.

4 References

Anderson E, Bai Z, Bischof C, Blackford S, Demmel J, Dongarra J J, Du Croz J J, Greenbaum A, Hammarling S, McKenney A and Sorensen D (1999) LAPACK Users' Guide (3rd Edition) SIAM, Philadelphia http://www.netlib.org/lapack/lug
Golub G H and Van Loan C F (1996) Matrix Computations (3rd Edition) Johns Hopkins University Press, Baltimore

5 Arguments

1:   COMPZ – CHARACTER(1)Input
On entry: indicates whether the eigenvectors are to be computed.
COMPZ='N'
Only the eigenvalues are computed (and the array Z is not referenced).
COMPZ='V'
The eigenvalues and eigenvectors of A are computed (and the array Z must contain the matrix Q on entry).
COMPZ='I'
The eigenvalues and eigenvectors of T are computed (and the array Z is initialized by the routine).
Constraint: COMPZ='N', 'V' or 'I'.
2:   N – INTEGERInput
On entry: n, the order of the symmetric tridiagonal matrix T.
Constraint: N≥0.
3:   D* – REAL (KIND=nag_wp) arrayInput/Output
Note: the dimension of the array D must be at least max 1,N.
On entry: the diagonal elements of the tridiagonal matrix.
On exit: if INFO=0, the eigenvalues in ascending order.
4:   E* – REAL (KIND=nag_wp) arrayInput/Output
Note: the dimension of the array E must be at least max 1,N-1.
On entry: the subdiagonal elements of the tridiagonal matrix.
On exit: E is overwritten.
5:   Z LDZ* – COMPLEX (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array Z must be at least max 1,N if COMPZ='V' or 'I', and at least 1 otherwise.
On entry: if COMPZ='V', Z must contain the unitary matrix Q used in the reduction to tridiagonal form.
On exit: if COMPZ='V', Z contains the orthonormal eigenvectors of the original Hermitian matrix A, and if COMPZ='I', Z contains the orthonormal eigenvectors of the symmetric tridiagonal matrix T.
If COMPZ='N', Z is not referenced.
6:   LDZ – INTEGERInput
On entry: the first dimension of the array Z as declared in the (sub)program from which F08JVF (ZSTEDC) is called.
Constraints:
  • if COMPZ='V' or 'I', LDZ≥ max 1,N ;
  • otherwise LDZ≥1.
7:   WORK max 1,LWORK – COMPLEX (KIND=nag_wp) arrayWorkspace
On exit: if INFO=0, the real part of WORK 1 contains the minimum value of LWORK required for optimal performance.
8:   LWORK – INTEGERInput
On entry: the dimension of the array WORK as declared in the (sub)program from which F08JVF (ZSTEDC) is called.
If LWORK=-1, a workspace query is assumed; the routine only calculates the optimal sizes of the WORK, RWORK and IWORK arrays, returns these values as the first entries of the WORK, RWORK and IWORK arrays, and no error message related to LWORK, LRWORK or LIWORK is issued.
Constraints:
if LWORK≠-1,
  • if COMPZ='N' or 'I' or N≤1, LWORK must be at least 1;
  • if COMPZ='V' and N>1, LWORK must be at least N 2.
Note: that for COMPZ='V', then if N is less than or equal to the minimum divide size, usually 25, then LWORK need only be 1.
9:   RWORK max 1,LRWORK – REAL (KIND=nag_wp) arrayWorkspace
On exit: if INFO=0, RWORK 1 returns the optimal LRWORK.
10:   LRWORK – INTEGERInput
On entry: the dimension of the array RWORK as declared in the (sub)program from which F08JVF (ZSTEDC) is called.
If LRWORK=-1, a workspace query is assumed; the routine only calculates the optimal sizes of the WORK, RWORK and IWORK arrays, returns these values as the first entries of the WORK, RWORK and IWORK arrays, and no error message related to LWORK, LRWORK or LIWORK is issued.
Constraints:
if LRWORK≠-1,
  • if COMPZ='N' or N≤1, LRWORK must be at least 1;
  • if COMPZ='V' and N>1, LRWORK must be at least 1+3×N+2×N×lg N+4×N 2, where lg N=smallest integer k such that 2 k≥N;
  • if COMPZ='I' and N>1, LRWORK must be at least 1+4×N+2×N 2.
Note: that for COMPZ='V' or 'I' then if N is less than or equal to the minimum divide size, usually 25, then LRWORK need only be max 1,2×N-1 .
11:   IWORK max 1,LIWORK – INTEGER arrayWorkspace
On exit: if INFO=0, IWORK 1 returns the optimal LIWORK.
12:   LIWORK – INTEGERInput
On entry: the dimension of the array IWORK as declared in the (sub)program from which F08JVF (ZSTEDC) is called.
If LIWORK=-1, a workspace query is assumed; the routine only calculates the optimal sizes of the WORK, RWORK and IWORK arrays, returns these values as the first entries of the WORK, RWORK and IWORK arrays, and no error message related to LWORK, LRWORK or LIWORK is issued.
Constraints:
if LIWORK≠-1,
  • if COMPZ='N' or N≤1, LIWORK must be at least 1;
  • if COMPZ='V' or N>1, LIWORK must be at least 6+6×N+5×N×lg N;
  • if COMPZ='I' or N>1, LIWORK must be at least 3+5×N.
13:   INFO – INTEGEROutput
On exit: INFO=0 unless the routine detects an error (see Section 6).

6 Error Indicators and Warnings

INFO<0
If INFO=-i, argument i had an illegal value. An explanatory message is output, and execution of the program is terminated.
INFO>0
The algorithm failed to compute an eigenvalue while working on the submatrix lying in rows and columns INFO/N+1 through INFO mod N+1.

7 Accuracy

The computed eigenvalues and eigenvectors are exact for a nearby matrix T+E, where
E 2 = O ε T 2 ,
and ε is the machine precision.
If λi is an exact eigenvalue and λ~i is the corresponding computed value, then
λ~i - λi ≤ c n ε T 2 ,
where c n is a modestly increasing function of n.
If zi is the corresponding exact eigenvector, and z~i is the corresponding computed eigenvector, then the angle θ z~i,zi between them is bounded as follows:
θ z~i,zi ≤ c n ε T 2 min i≠j λi-λj .
Thus the accuracy of a computed eigenvector depends on the gap between its eigenvalue and all the other eigenvalues.
See Section 4.7 of Anderson et al. (1999) for further details. See also F08FLF (DDISNA).

8 Parallelism and Performance

F08JVF (ZSTEDC) is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
F08JVF (ZSTEDC) makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

If only eigenvalues are required, the total number of floating-point operations is approximately proportional to n 2. When eigenvectors are required the number of operations is bounded above by approximately the same number of operations as F08JSF (ZSTEQR), but for large matrices F08JVF (ZSTEDC) is usually much faster.
The real analogue of this routine is F08JHF (DSTEDC).

10 Example

This example finds all the eigenvalues and eigenvectors of the Hermitian band matrix
A = -3.13 i+0.00 1.94-2.10 i -3.40+0.25 i 0.00i+0.00 1.94+2.10 i -1.91 i+0.00 -0.82-0.89 i -0.67+0.34 i -3.40-0.25 i -0.82+0.89 i -2.87 i+0.00 -2.10-0.16 i 0.00i+0.00 -0.67-0.34 i -2.10+0.16 i 0.50 i+0.00 .
A is first reduced to tridiagonal form by a call to F08HSF (ZHBTRD).

10.1 Program Text

Program Text (f08jvfe.f90)

10.2 Program Data

Program Data (f08jvfe.d)

10.3 Program Results

Program Results (f08jvfe.r)

F08 Chapter Contents
F08 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F08JXF (ZSTEIN) : NAG Library, Mark 26

F08 Chapter Contents
F08 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F08JXF (ZSTEIN)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
10 Example

1 Purpose

F08JXF (ZSTEIN) computes the eigenvectors of a real symmetric tridiagonal matrix corresponding to specified eigenvalues, by inverse iteration, storing the eigenvectors in a complex array.

2 Specification

SUBROUTINE F08JXF ( N, D, E, M, W, IBLOCK, ISPLIT, Z, LDZ, WORK, IWORK, IFAILV, INFO)
INTEGER | N, M, IBLOCK(*), ISPLIT(*), LDZ, IWORK(N), IFAILV(M), INFO
REAL (KIND=nag_wp) | D(*), E(*), W(*), WORK(5*N)
COMPLEX (KIND=nag_wp) | Z(LDZ,*)
The routine may be called by its LAPACK name zstein.

3 Description

F08JXF (ZSTEIN) computes the eigenvectors of a real symmetric tridiagonal matrix T corresponding to specified eigenvalues, by inverse iteration (see Jessup and Ipsen (1992)). It is designed to be used in particular after the specified eigenvalues have been computed by F08JJF (DSTEBZ) with ORDER='B', but may also be used when the eigenvalues have been computed by other routines in Chapters F02 or F08.
The eigenvectors of T are real, but are stored by this routine in a complex array. If T has been formed by reduction of a full complex Hermitian matrix A to tridiagonal form, then eigenvectors of T may be transformed to (complex) eigenvectors of A by a call to F08FUF (ZUNMTR) or F08GUF (ZUPMTR).
F08JJF (DSTEBZ) determines whether the matrix T splits into block diagonal form:
T = T 1 T 2 . . . Tp
and passes details of the block structure to this routine in the arrays IBLOCK and ISPLIT. This routine can then take advantage of the block structure by performing inverse iteration on each block Ti separately, which is more efficient than using the whole matrix.

4 References

Golub G H and Van Loan C F (1996) Matrix Computations (3rd Edition) Johns Hopkins University Press, Baltimore
Jessup E and Ipsen I C F (1992) Improving the accuracy of inverse iteration SIAM J. Sci. Statist. Comput. 13 550–572

5 Arguments

1:   N – INTEGERInput
On entry: n, the order of the matrix T.
Constraint: N≥0.
2:   D* – REAL (KIND=nag_wp) arrayInput
Note: the dimension of the array D must be at least max 1,N.
On entry: the diagonal elements of the tridiagonal matrix T.
3:   E* – REAL (KIND=nag_wp) arrayInput
Note: the dimension of the array E must be at least max 1,N-1.
On entry: the off-diagonal elements of the tridiagonal matrix T.
4:   M – INTEGERInput
On entry: m, the number of eigenvectors to be returned.
Constraint: 0≤M≤N.
5:   W* – REAL (KIND=nag_wp) arrayInput
Note: the dimension of the array W must be at least max 1,N.
On entry: the eigenvalues of the tridiagonal matrix T stored in W 1 to W m, as returned by F08JJF (DSTEBZ) with ORDER='B'. Eigenvalues associated with the first sub-matrix must be supplied first, in nondecreasing order; then those associated with the second sub-matrix, again in nondecreasing order; and so on.
Constraint: if IBLOCK i=IBLOCK i+1, W i≤W i+1, for i=1,2,…,M-1.
6:   IBLOCK* – INTEGER arrayInput
Note: the dimension of the array IBLOCK must be at least max 1,N.
On entry: the first m elements must contain the sub-matrix indices associated with the specified eigenvalues, as returned by F08JJF (DSTEBZ) with ORDER='B'. If the eigenvalues were not computed by F08JJF (DSTEBZ) with ORDER='B', set IBLOCK i to 1, for i=1,2,…,m.
Constraint: IBLOCK i≤IBLOCK i+1, for i=1,2,…,M-1.
7:   ISPLIT* – INTEGER arrayInput
Note: the dimension of the array ISPLIT must be at least max 1,N.
On entry: the points at which T breaks up into sub-matrices, as returned by F08JJF (DSTEBZ) with ORDER='B'. If the eigenvalues were not computed by F08JJF (DSTEBZ) with ORDER='B', set ISPLIT 1 to N.
8:   Z LDZ* – COMPLEX (KIND=nag_wp) arrayOutput
Note: the second dimension of the array Z must be at least max 1,M.
On exit: the m eigenvectors, stored as columns of Z; the ith column corresponds to the ith specified eigenvalue, unless INFO>0 (in which case see Section 6).
9:   LDZ – INTEGERInput
On entry: the first dimension of the array Z as declared in the (sub)program from which F08JXF (ZSTEIN) is called.
Constraint: LDZ≥ max 1,N .
10:   WORK 5×N – REAL (KIND=nag_wp) arrayWorkspace
11:   IWORK N – INTEGER arrayWorkspace
12:   IFAILV M – INTEGER arrayOutput
On exit: if INFO=i>0, the first i elements of IFAILV contain the indices of any eigenvectors which have failed to converge. The rest of the first M elements of IFAILV are set to 0.
13:   INFO – INTEGEROutput
On exit: INFO=0 unless the routine detects an error (see Section 6).

6 Error Indicators and Warnings

INFO<0
If INFO=-i, argument i had an illegal value. An explanatory message is output, and execution of the program is terminated.
INFO>0
If INFO=i, then i eigenvectors (as indicated by the argument IFAILV above) each failed to converge in five iterations. The current iterate after five iterations is stored in the corresponding column of Z.

7 Accuracy

Each computed eigenvector zi is the exact eigenvector of a nearby matrix A+Ei, such that
Ei = O ε A ,
where ε is the machine precision. Hence the residual is small:
A zi - λi zi = O ε A .
However, a set of eigenvectors computed by this routine may not be orthogonal to so high a degree of accuracy as those computed by F08JSF (ZSTEQR).

8 Parallelism and Performance

F08JXF (ZSTEIN) is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
F08JXF (ZSTEIN) makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The real analogue of this routine is F08JKF (DSTEIN).

10 Example

See Section 10 in F08FUF (ZUNMTR).
F08 Chapter Contents
F08 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F08JYF (ZSTEGR) : NAG Library, Mark 26

F08 Chapter Contents
F08 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F08JYF (ZSTEGR)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F08JYF (ZSTEGR) computes all the eigenvalues and, optionally, all the eigenvectors of a real n by n symmetric tridiagonal matrix.

2 Specification

SUBROUTINE F08JYF ( JOBZ, RANGE, N, D, E, VL, VU, IL, IU, ABSTOL, M, W, Z, LDZ, ISUPPZ, WORK, LWORK, IWORK, LIWORK, INFO)
INTEGER | N, IL, IU, M, LDZ, ISUPPZ(*), LWORK, IWORK(max(1,LIWORK)), LIWORK, INFO
REAL (KIND=nag_wp) | D(*), E(*), VL, VU, ABSTOL, W(*), WORK(max(1,LWORK))
COMPLEX (KIND=nag_wp) | Z(LDZ,*)
CHARACTER(1) | JOBZ, RANGE
The routine may be called by its LAPACK name zstegr.

3 Description

F08JYF (ZSTEGR) computes all the eigenvalues and, optionally, the eigenvectors, of a real symmetric tridiagonal matrix T. That is, the routine computes the spectral factorization of T given by
T = ZΛ ZT ,
where Λ is a diagonal matrix whose diagonal elements are the eigenvalues, λi, of T and Z is an orthogonal matrix whose columns are the eigenvectors, zi, of T. Thus
T zi= λi zi ,   i = 1,2,…,n .
The routine stores the real orthogonal matrix Z in a complex array, so that it may also be used to compute all the eigenvalues and eigenvectors of a complex Hermitian matrix A which has been reduced to tridiagonal form T:
A =QT QH, where ​Q​ is unitary =QZ Λ QZ H.
In this case, the matrix Q must be explicitly applied to the output matrix Z. The routines which must be called to perform the reduction to tridiagonal form and apply Q are:
full matrix | F08FSF (ZHETRD) and F08FUF (ZUNMTR)
full matrix, packed storage | F08GSF (ZHPTRD) and F08GUF (ZUPMTR)
band matrix | F08HSF (ZHBTRD) with VECT='V' and F06ZAF (ZGEMM).
This routine uses the dqds and the Relatively Robust Representation algorithms to compute the eigenvalues and eigenvectors respectively; see for example Parlett and Dhillon (2000) and Dhillon and Parlett (2004) for further details. F08JYF (ZSTEGR) can usually compute all the eigenvalues and eigenvectors in O n 2 floating-point operations and so, for large matrices, is often considerably faster than the other symmetric tridiagonal routines in this chapter when all the eigenvectors are required, particularly so compared to those routines that are based on the QR algorithm.

4 References

Anderson E, Bai Z, Bischof C, Blackford S, Demmel J, Dongarra J J, Du Croz J J, Greenbaum A, Hammarling S, McKenney A and Sorensen D (1999) LAPACK Users' Guide (3rd Edition) SIAM, Philadelphia http://www.netlib.org/lapack/lug
Barlow J and Demmel J W (1990) Computing accurate eigensystems of scaled diagonally dominant matrices SIAM J. Numer. Anal. 27 762–791
Dhillon I S and Parlett B N (2004) Orthogonal eigenvectors and relative gaps. SIAM J. Appl. Math. 25 858–899
Parlett B N and Dhillon I S (2000) Relatively robust representations of symmetric tridiagonals Linear Algebra Appl. 309 121–151

5 Arguments

1:   JOBZ – CHARACTER(1)Input
On entry: indicates whether eigenvectors are computed.
JOBZ='N'
Only eigenvalues are computed.
JOBZ='V'
Eigenvalues and eigenvectors are computed.
Constraint: JOBZ='N' or 'V'.
2:   RANGE – CHARACTER(1)Input
On entry: indicates which eigenvalues should be returned.
RANGE='A'
All eigenvalues will be found.
RANGE='V'
All eigenvalues in the half-open interval VL,VU will be found.
RANGE='I'
The ILth through IUth eigenvectors will be found.
Constraint: RANGE='A', 'V' or 'I'.
3:   N – INTEGERInput
On entry: n, the order of the matrix T.
Constraint: N≥0.
4:   D* – REAL (KIND=nag_wp) arrayInput/Output
Note: the dimension of the array D must be at least max 1,N.
On entry: the n diagonal elements of the tridiagonal matrix T.
On exit: D is overwritten.
5:   E* – REAL (KIND=nag_wp) arrayInput/Output
Note: the dimension of the array E must be at least max 1,N.
On entry: E 1:N-1 contains the subdiagonal elements of the tridiagonal matrix T. E N need not be set.
On exit: E is overwritten.
6:   VL – REAL (KIND=nag_wp)Input
7:   VU – REAL (KIND=nag_wp)Input
On entry: if RANGE='V', VL and VU contain the lower and upper bounds respectively of the interval to be searched for eigenvalues.
If RANGE='A' or 'I', VL and VU are not referenced.
Constraint: if RANGE='V', VL<VU.
8:   IL – INTEGERInput
9:   IU – INTEGERInput
On entry: if RANGE='I', IL and IU contains the indices (in ascending order) of the smallest and largest eigenvalues to be returned, respectively.
If RANGE='A' or 'V', IL and IU are not referenced.
Constraints:
  • if RANGE='I' and N>0, 1≤ IL≤ IU≤ N ;
  • if RANGE='I' and N=0, IL=1 and IU=0.
10:   ABSTOL – REAL (KIND=nag_wp)Input
On entry: in earlier versions, this argument was the absolute error tolerance for the eigenvalues/eigenvectors. It is now deprecated, and only included for backwards-compatibility.
11:   M – INTEGEROutput
On exit: the total number of eigenvalues found. 0≤M≤N.
If RANGE='A', M=N.
If RANGE='I', M=IU-IL+1.
12:   W* – REAL (KIND=nag_wp) arrayOutput
Note: the dimension of the array W must be at least max 1,N.
On exit: the eigenvalues in ascending order.
13:   Z LDZ* – COMPLEX (KIND=nag_wp) arrayOutput
Note: the second dimension of the array Z must be at least max 1,M if JOBZ='V', and at least 1 otherwise.
On exit: if JOBZ='V', then if INFO=0, the columns of Z contain the orthonormal eigenvectors of the matrix T, with the ith column of Z holding the eigenvector associated with W i.
If JOBZ='N', Z is not referenced.
Note: you must ensure that at least max 1,M columns are supplied in the array Z; if RANGE='V', the exact value of M is not known in advance and an upper bound of at least N must be used.
14:   LDZ – INTEGERInput
On entry: the first dimension of the array Z as declared in the (sub)program from which F08JYF (ZSTEGR) is called.
Constraints:
  • if JOBZ='V', LDZ≥ max 1,N ;
  • otherwise LDZ≥1.
15:   ISUPPZ* – INTEGER arrayOutput
Note: the dimension of the array ISUPPZ must be at least max 1,2×M.
On exit: the support of the eigenvectors in Z, i.e., the indices indicating the nonzero elements in Z. The ith eigenvector is nonzero only in elements ISUPPZ 2×i-1 through ISUPPZ 2×i.
16:   WORK max 1,LWORK – REAL (KIND=nag_wp) arrayWorkspace
On exit: if INFO=0, WORK 1 returns the minimum LWORK.
17:   LWORK – INTEGERInput
On entry: the dimension of the array WORK as declared in the (sub)program from which F08JYF (ZSTEGR) is called.
If LWORK=-1, a workspace query is assumed; the routine only calculates the minimum sizes of the WORK and IWORK arrays, returns these values as the first entries of the WORK and IWORK arrays, and no error message related to LWORK or LIWORK is issued.
Constraint: LWORK≥max 1,18×N or LWORK=-1.
18:   IWORK max 1,LIWORK – INTEGER arrayWorkspace
On exit: if INFO=0, WORK 1 returns the minimum LIWORK.
19:   LIWORK – INTEGERInput
On entry: the dimension of the array IWORK as declared in the (sub)program from which F08JYF (ZSTEGR) is called.
If LIWORK=-1, a workspace query is assumed; the routine only calculates the minimum sizes of the WORK and IWORK arrays, returns these values as the first entries of the WORK and IWORK arrays, and no error message related to LWORK or LIWORK is issued.
Constraint: LIWORK≥max 1,10×N or LIWORK=-1.
20:   INFO – INTEGEROutput
On exit: INFO=0 unless the routine detects an error (see Section 6).

6 Error Indicators and Warnings

INFO<0
If INFO=-i, argument i had an illegal value. An explanatory message is output, and execution of the program is terminated.
INFO>0
If INFO=1, the dqds algorithm failed to converge, if INFO=2, inverse iteration failed to converge.

7 Accuracy

See the description for ABSTOL. See also Section 4.7 of Anderson et al. (1999) and Barlow and Demmel (1990) for further details.

8 Parallelism and Performance

F08JYF (ZSTEGR) is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
F08JYF (ZSTEGR) makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The total number of floating-point operations required to compute all the eigenvalues and eigenvectors is approximately proportional to n 2.
The real analogue of this routine is F08JLF (DSTEGR).

10 Example

This example finds all the eigenvalues and eigenvectors of the symmetric tridiagonal matrix
T = 1.0 1.0 0.0 0.0 1.0 4.0 2.0 0.0 0.0 2.0 9.0 3.0 0.0 0.0 3.0 16.0 .
ABSTOL is set to zero so that the default tolerance of nε T 1 is used.

10.1 Program Text

Program Text (f08jyfe.f90)

10.2 Program Data

Program Data (f08jyfe.d)

10.3 Program Results

Program Results (f08jyfe.r)

F08 Chapter Contents
F08 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F08KAF (DGELSS) : NAG Library, Mark 26

F08 Chapter Contents
F08 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F08KAF (DGELSS)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F08KAF (DGELSS) computes the minimum norm solution to a real linear least squares problem
minx b-Ax 2 .

2 Specification

SUBROUTINE F08KAF ( M, N, NRHS, A, LDA, B, LDB, S, RCOND, RANK, WORK, LWORK, INFO)
INTEGER | M, N, NRHS, LDA, LDB, RANK, LWORK, INFO
REAL (KIND=nag_wp) | A(LDA,*), B(LDB,*), S(*), RCOND, WORK(max(1,LWORK))
The routine may be called by its LAPACK name dgelss.

3 Description

F08KAF (DGELSS) uses the singular value decomposition (SVD) of A, where A is an m by n matrix which may be rank-deficient.
Several right-hand side vectors b and solution vectors x can be handled in a single call; they are stored as the columns of the m by r right-hand side matrix B and the n by r solution matrix X.
The effective rank of A is determined by treating as zero those singular values which are less than RCOND times the largest singular value.

4 References

Anderson E, Bai Z, Bischof C, Blackford S, Demmel J, Dongarra J J, Du Croz J J, Greenbaum A, Hammarling S, McKenney A and Sorensen D (1999) LAPACK Users' Guide (3rd Edition) SIAM, Philadelphia http://www.netlib.org/lapack/lug
Golub G H and Van Loan C F (1996) Matrix Computations (3rd Edition) Johns Hopkins University Press, Baltimore

5 Arguments

1:   M – INTEGERInput
On entry: m, the number of rows of the matrix A.
Constraint: M≥0.
2:   N – INTEGERInput
On entry: n, the number of columns of the matrix A.
Constraint: N≥0.
3:   NRHS – INTEGERInput
On entry: r, the number of right-hand sides, i.e., the number of columns of the matrices B and X.
Constraint: NRHS≥0.
4:   A LDA* – REAL (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array A must be at least max 1,N.
On entry: the m by n matrix A.
On exit: the first min m,n rows of A are overwritten with its right singular vectors, stored row-wise.
5:   LDA – INTEGERInput
On entry: the first dimension of the array A as declared in the (sub)program from which F08KAF (DGELSS) is called.
Constraint: LDA≥max 1,M.
6:   B LDB* – REAL (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array B must be at least max 1,NRHS.
On entry: the m by r right-hand side matrix B.
On exit: B is overwritten by the n by r solution matrix X. If m≥n and RANK=n, the residual sum of squares for the solution in the ith column is given by the sum of squares of elements n+1,…,m in that column.
7:   LDB – INTEGERInput
On entry: the first dimension of the array B as declared in the (sub)program from which F08KAF (DGELSS) is called.
Constraint: LDB≥max 1,M,N.
8:   S* – REAL (KIND=nag_wp) arrayOutput
Note: the dimension of the array S must be at least max 1,min M,N .
On exit: the singular values of A in decreasing order.
9:   RCOND – REAL (KIND=nag_wp)Input
On entry: used to determine the effective rank of A. Singular values S i≤RCOND×S 1 are treated as zero. If RCOND<0, machine precision is used instead.
10:   RANK – INTEGEROutput
On exit: the effective rank of A, i.e., the number of singular values which are greater than RCOND×S 1.
11:   WORK max 1,LWORK – REAL (KIND=nag_wp) arrayWorkspace
On exit: if INFO=0, WORK 1 contains the minimum value of LWORK required for optimal performance.
12:   LWORK – INTEGERInput
On entry: the dimension of the array WORK as declared in the (sub)program from which F08KAF (DGELSS) is called.
If LWORK=-1, a workspace query is assumed; the routine only calculates the optimal size of the WORK array, returns this value as the first entry of the WORK array, and no error message related to LWORK is issued.
Suggested value: for optimal performance, LWORK should generally be larger. Consider increasing LWORK by at least nb×min M,N , where nb is the optimal block size.
Constraint: LWORK≥1, and also
LWORK≥3×min M,N+max 2×min M,N,max M,N,NRHS.
13:   INFO – INTEGEROutput
On exit: INFO=0 unless the routine detects an error (see Section 6).

6 Error Indicators and Warnings

INFO<0
If INFO=-i, argument i had an illegal value. An explanatory message is output, and execution of the program is terminated.
INFO>0
The algorithm for computing the SVD failed to converge; if INFO=i, i off-diagonal elements of an intermediate bidiagonal form did not converge to zero.

7 Accuracy

See Section 4.5 of Anderson et al. (1999) for details.

8 Parallelism and Performance

F08KAF (DGELSS) is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
F08KAF (DGELSS) makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The complex analogue of this routine is F08KNF (ZGELSS).

10 Example

This example solves the linear least squares problem
minx b-Ax 2
for the solution, x, of minimum norm, where
A = -0.09 0.14 -0.46 0.68 1.29 -1.56 0.20 0.29 1.09 0.51 -1.48 -0.43 0.89 -0.71 -0.96 -1.09 0.84 0.77 2.11 -1.27 0.08 0.55 -1.13 0.14 1.74 -1.59 -0.72 1.06 1.24 0.34   and  b= 7.4 4.2 -8.3 1.8 8.6 2.1 .
A tolerance of 0.01 is used to determine the effective rank of A.
Note that the block size (NB) of 64 assumed in this example is not realistic for such a small problem, but should be suitable for large problems.

10.1 Program Text

Program Text (f08kafe.f90)

10.2 Program Data

Program Data (f08kafe.d)

10.3 Program Results

Program Results (f08kafe.r)

F08 Chapter Contents
F08 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F08KBF (DGESVD) : NAG Library, Mark 26

F08 Chapter Contents
F08 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F08KBF (DGESVD)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F08KBF (DGESVD) computes the singular value decomposition (SVD) of a real m by n matrix A, optionally computing the left and/or right singular vectors.

2 Specification

SUBROUTINE F08KBF ( JOBU, JOBVT, M, N, A, LDA, S, U, LDU, VT, LDVT, WORK, LWORK, INFO)
INTEGER | M, N, LDA, LDU, LDVT, LWORK, INFO
REAL (KIND=nag_wp) | A(LDA,*), S(*), U(LDU,*), VT(LDVT,*), WORK(max(1,LWORK))
CHARACTER(1) | JOBU, JOBVT
The routine may be called by its LAPACK name dgesvd.

3 Description

The SVD is written as
A = UΣ VT ,
where Σ is an m by n matrix which is zero except for its min m,n diagonal elements, U is an m by m orthogonal matrix, and V is an n by n orthogonal matrix. The diagonal elements of Σ are the singular values of A; they are real and non-negative, and are returned in descending order. The first min m,n columns of U and V are the left and right singular vectors of A.
Note that the routine returns VT, not V.

4 References

Anderson E, Bai Z, Bischof C, Blackford S, Demmel J, Dongarra J J, Du Croz J J, Greenbaum A, Hammarling S, McKenney A and Sorensen D (1999) LAPACK Users' Guide (3rd Edition) SIAM, Philadelphia http://www.netlib.org/lapack/lug
Golub G H and Van Loan C F (1996) Matrix Computations (3rd Edition) Johns Hopkins University Press, Baltimore

5 Arguments

1:   JOBU – CHARACTER(1)Input
On entry: specifies options for computing all or part of the matrix U.
JOBU='A'
All m columns of U are returned in array U.
JOBU='S'
The first min m,n columns of U (the left singular vectors) are returned in the array U.
JOBU='O'
The first min m,n columns of U (the left singular vectors) are overwritten on the array A.
JOBU='N'
No columns of U (no left singular vectors) are computed.
Constraint: JOBU='A', 'S', 'O' or 'N'.
2:   JOBVT – CHARACTER(1)Input
On entry: specifies options for computing all or part of the matrix VT.
JOBVT='A'
All n rows of VT are returned in the array VT.
JOBVT='S'
The first min m,n rows of VT (the right singular vectors) are returned in the array VT.
JOBVT='O'
The first min m,n rows of VT (the right singular vectors) are overwritten on the array A.
JOBVT='N'
No rows of VT (no right singular vectors) are computed.
Constraints:
  • JOBVT='A', 'S', 'O' or 'N';
  • JOBVT and JOBU cannot both be 'O'.
3:   M – INTEGERInput
On entry: m, the number of rows of the matrix A.
Constraint: M≥0.
4:   N – INTEGERInput
On entry: n, the number of columns of the matrix A.
Constraint: N≥0.
5:   A LDA* – REAL (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array A must be at least max 1,N.
On entry: the m by n matrix A.
On exit: if JOBU='O', A is overwritten with the first min m,n columns of U (the left singular vectors, stored column-wise).
If JOBVT='O', A is overwritten with the first min m,n rows of VT (the right singular vectors, stored row-wise).
If JOBU≠'O' and JOBVT≠'O', the contents of A are destroyed.
6:   LDA – INTEGERInput
On entry: the first dimension of the array A as declared in the (sub)program from which F08KBF (DGESVD) is called.
Constraint: LDA≥max 1,M.
7:   S* – REAL (KIND=nag_wp) arrayOutput
Note: the dimension of the array S must be at least max 1,min M,N .
On exit: the singular values of A, sorted so that S i≥S i+1.
8:   U LDU* – REAL (KIND=nag_wp) arrayOutput
Note: the second dimension of the array U must be at least max 1,M if JOBU='A', max 1,min M,N if JOBU='S', and at least 1 otherwise.
On exit: if JOBU='A', U contains the m by m orthogonal matrix U.
If JOBU='S', U contains the first min m,n columns of U (the left singular vectors, stored column-wise).
If JOBU='N' or 'O', U is not referenced.
9:   LDU – INTEGERInput
On entry: the first dimension of the array U as declared in the (sub)program from which F08KBF (DGESVD) is called.
Constraints:
  • if JOBU='A' or 'S', LDU≥ max 1,M ;
  • otherwise LDU≥1.
10:   VT LDVT* – REAL (KIND=nag_wp) arrayOutput
Note: the second dimension of the array VT must be at least max 1,N if JOBVT='A' or 'S', and at least 1 otherwise.
On exit: if JOBVT='A', VT contains the n by n orthogonal matrix VT.
If JOBVT='S', VT contains the first min m,n rows of VT (the right singular vectors, stored row-wise).
If JOBVT='N' or 'O', VT is not referenced.
11:   LDVT – INTEGERInput
On entry: the first dimension of the array VT as declared in the (sub)program from which F08KBF (DGESVD) is called.
Constraints:
  • if JOBVT='A', LDVT≥ max 1,N ;
  • if JOBVT='S', LDVT≥ max 1,min M,N ;
  • otherwise LDVT≥1.
12:   WORK max 1,LWORK – REAL (KIND=nag_wp) arrayWorkspace
On exit: if INFO=0, WORK 1 returns the optimal LWORK.
If INFO>0, WORK 2:min M,N contains the unconverged superdiagonal elements of an upper bidiagonal matrix B whose diagonal is in S (not necessarily sorted). B satisfies A=UB VT, so it has the same singular values as A, and singular vectors related by U and VT.
13:   LWORK – INTEGERInput
On entry: the dimension of the array WORK as declared in the (sub)program from which F08KBF (DGESVD) is called.
If LWORK=-1, a workspace query is assumed; the routine only calculates the optimal size of the WORK array, returns this value as the first entry of the WORK array, and no error message related to LWORK is issued.
Suggested value: for optimal performance, LWORK should generally be larger. Consider increasing LWORK by at least nb×min M,N , where nb is the optimal block size.
Constraint: LWORK ≥ max 1, 3 × min M,N + max M,N , 5 × min M,N .
14:   INFO – INTEGEROutput
On exit: INFO=0 unless the routine detects an error (see Section 6).

6 Error Indicators and Warnings

INFO<0
If INFO=-i, argument i had an illegal value. An explanatory message is output, and execution of the program is terminated.
INFO>0
If F08KBF (DGESVD) did not converge, INFO specifies how many superdiagonals of an intermediate bidiagonal form did not converge to zero.

7 Accuracy

The computed singular value decomposition is nearly the exact singular value decomposition for a nearby matrix A+E , where
E 2 = O ε A 2 ,
and ε is the machine precision. In addition, the computed singular vectors are nearly orthogonal to working precision. See Section 4.9 of Anderson et al. (1999) for further details.

8 Parallelism and Performance

F08KBF (DGESVD) is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
F08KBF (DGESVD) makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The total number of floating-point operations is approximately proportional to m n 2 when m>n and m 2 n otherwise.
The singular values are returned in descending order.
The complex analogue of this routine is F08KPF (ZGESVD).

10 Example

This example finds the singular values and left and right singular vectors of the 6 by 4 matrix
A = 2.27 -1.54 1.15 -1.94 0.28 -1.67 0.94 -0.78 -0.48 -3.09 0.99 -0.21 1.07 1.22 0.79 0.63 -2.35 2.93 -1.45 2.30 0.62 -7.39 1.03 -2.57 ,
together with approximate error bounds for the computed singular values and vectors.
The example program for F08KDF (DGESDD) illustrates finding a singular value decomposition for the case m≤n.

10.1 Program Text

Program Text (f08kbfe.f90)

10.2 Program Data

Program Data (f08kbfe.d)

10.3 Program Results

Program Results (f08kbfe.r)

F08 Chapter Contents
F08 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F08KCF (DGELSD) : NAG Library, Mark 26

F08 Chapter Contents
F08 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F08KCF (DGELSD)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F08KCF (DGELSD) computes the minimum norm solution to a real linear least squares problem
minx b-Ax 2 .

2 Specification

SUBROUTINE F08KCF ( M, N, NRHS, A, LDA, B, LDB, S, RCOND, RANK, WORK, LWORK, IWORK, INFO)
INTEGER | M, N, NRHS, LDA, LDB, RANK, LWORK, IWORK(*), INFO
REAL (KIND=nag_wp) | A(LDA,*), B(LDB,*), S(*), RCOND, WORK(max(1,LWORK))
The routine may be called by its LAPACK name dgelsd.

3 Description

F08KCF (DGELSD) uses the singular value decomposition (SVD) of A, where A is a real m by n matrix which may be rank-deficient.
Several right-hand side vectors b and solution vectors x can be handled in a single call; they are stored as the columns of the m by r right-hand side matrix B and the n by r solution matrix X.
The problem is solved in three steps:
1. | reduce the coefficient matrix A to bidiagonal form with Householder transformations, reducing the original problem into a ‘bidiagonal least squares problem’ (BLS);
2. | solve the BLS using a divide-and-conquer approach;
3. | apply back all the Householder transformations to solve the original least squares problem.
The effective rank of A is determined by treating as zero those singular values which are less than RCOND times the largest singular value.

4 References

Anderson E, Bai Z, Bischof C, Blackford S, Demmel J, Dongarra J J, Du Croz J J, Greenbaum A, Hammarling S, McKenney A and Sorensen D (1999) LAPACK Users' Guide (3rd Edition) SIAM, Philadelphia http://www.netlib.org/lapack/lug
Golub G H and Van Loan C F (1996) Matrix Computations (3rd Edition) Johns Hopkins University Press, Baltimore

5 Arguments

1:   M – INTEGERInput
On entry: m, the number of rows of the matrix A.
Constraint: M≥0.
2:   N – INTEGERInput
On entry: n, the number of columns of the matrix A.
Constraint: N≥0.
3:   NRHS – INTEGERInput
On entry: r, the number of right-hand sides, i.e., the number of columns of the matrices B and X.
Constraint: NRHS≥0.
4:   A LDA* – REAL (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array A must be at least max 1,N.
On entry: the m by n coefficient matrix A.
On exit: the contents of A are destroyed.
5:   LDA – INTEGERInput
On entry: the first dimension of the array A as declared in the (sub)program from which F08KCF (DGELSD) is called.
Constraint: LDA≥max 1,M.
6:   B LDB* – REAL (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array B must be at least max 1,NRHS.
On entry: the m by r right-hand side matrix B.
On exit: B is overwritten by the n by r solution matrix X. If m≥n and RANK=n, the residual sum of squares for the solution in the ith column is given by the sum of squares of elements n+1,…,m in that column.
7:   LDB – INTEGERInput
On entry: the first dimension of the array B as declared in the (sub)program from which F08KCF (DGELSD) is called.
Constraint: LDB≥max 1,M,N.
8:   S* – REAL (KIND=nag_wp) arrayOutput
Note: the dimension of the array S must be at least max 1,min M,N .
On exit: the singular values of A in decreasing order.
9:   RCOND – REAL (KIND=nag_wp)Input
On entry: used to determine the effective rank of A. Singular values S i≤RCOND×S 1 are treated as zero. If RCOND<0, machine precision is used instead.
10:   RANK – INTEGEROutput
On exit: the effective rank of A, i.e., the number of singular values which are greater than RCOND×S 1.
11:   WORK max 1,LWORK – REAL (KIND=nag_wp) arrayWorkspace
On exit: if INFO=0, WORK 1 contains the minimum value of LWORK required for optimal performance.
12:   LWORK – INTEGERInput
On entry: the dimension of the array WORK as declared in the (sub)program from which F08KCF (DGELSD) is called.
The exact minimum amount of workspace needed depends on M, N and NRHS. As long as LWORK is at least
12⁢r+ 2⁢r× smlsiz+ 8⁢r× nlvl+ r× NRHS+ smlsiz+1 2 ,
where smlsiz is equal to the maximum size of the subproblems at the bottom of the computation tree (usually about 25), nlvl = max 0, int log 2 min M,N / smlsiz+1 +1 and r=min M,N, the code will execute correctly.
If LWORK=-1, a workspace query is assumed; the routine only calculates the optimal size of the WORK array and the minimum size of the IWORK array, and returns these values as the first entries of the WORK and IWORK arrays, and no error message related to LWORK is issued.
Suggested value: for optimal performance, LWORK should generally be larger than the minimum required as set out above. Consider increasing LWORK by at least nb×min M,N , where nb is the optimal block size.
Constraint: LWORK≥12⁢r+ 2⁢r× smlsiz+ 8⁢r× nlvl+ r× NRHS+ smlsiz+1 2 ​ or ​ LWORK=-1.
13:   IWORK* – INTEGER arrayWorkspace
Note: the dimension of the array IWORK must be at least max 1,liwork, where liwork is at least max 1,3×min M,N×nlvl+11×min M,N.
On exit: if INFO=0, IWORK 1 returns the minimum liwork.
14:   INFO – INTEGEROutput
On exit: INFO=0 unless the routine detects an error (see Section 6).

6 Error Indicators and Warnings

INFO<0
If INFO=-i, argument i had an illegal value. An explanatory message is output, and execution of the program is terminated.
INFO>0
The algorithm for computing the SVD failed to converge; if INFO=i, i off-diagonal elements of an intermediate bidiagonal form did not converge to zero.

7 Accuracy

See Section 4.5 of Anderson et al. (1999) for details.

8 Parallelism and Performance

F08KCF (DGELSD) is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
F08KCF (DGELSD) makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The complex analogue of this routine is F08KQF (ZGELSD).

10 Example

This example solves the linear least squares problem
minx b-Ax 2
for the solution, x, of minimum norm, where
A = -0.09 -1.56 -1.48 -1.09 0.08 -1.59 0.14 0.20 -0.43 0.84 0.55 -0.72 -0.46 0.29 0.89 0.77 -1.13 1.06 0.68 1.09 -0.71 2.11 0.14 1.24 1.29 0.51 -0.96 -1.27 1.74 0.34   and  b= 7.4 4.3 -8.1 1.8 8.7 .
A tolerance of 0.01 is used to determine the effective rank of A.
Note that the block size (NB) of 64 assumed in this example is not realistic for such a small problem, but should be suitable for large problems.

10.1 Program Text

Program Text (f08kcfe.f90)

10.2 Program Data

Program Data (f08kcfe.d)

10.3 Program Results

Program Results (f08kcfe.r)

F08 Chapter Contents
F08 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F08KDF (DGESDD) : NAG Library, Mark 26

F08 Chapter Contents
F08 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F08KDF (DGESDD)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F08KDF (DGESDD) computes the singular value decomposition (SVD) of a real m by n matrix A, optionally computing the left and/or right singular vectors, by using a divide-and-conquer method.

2 Specification

SUBROUTINE F08KDF ( JOBZ, M, N, A, LDA, S, U, LDU, VT, LDVT, WORK, LWORK, IWORK, INFO)
INTEGER | M, N, LDA, LDU, LDVT, LWORK, IWORK(8*min(M,N)), INFO
REAL (KIND=nag_wp) | A(LDA,*), S(min(M,N)), U(LDU,*), VT(LDVT,*), WORK(max(1,LWORK))
CHARACTER(1) | JOBZ
The routine may be called by its LAPACK name dgesdd.

3 Description

The SVD is written as
A = UΣ VT ,
where Σ is an m by n matrix which is zero except for its min m,n diagonal elements, U is an m by m orthogonal matrix, and V is an n by n orthogonal matrix. The diagonal elements of Σ are the singular values of A; they are real and non-negative, and are returned in descending order. The first min m,n columns of U and V are the left and right singular vectors of A.
Note that the routine returns VT, not V.

4 References

Anderson E, Bai Z, Bischof C, Blackford S, Demmel J, Dongarra J J, Du Croz J J, Greenbaum A, Hammarling S, McKenney A and Sorensen D (1999) LAPACK Users' Guide (3rd Edition) SIAM, Philadelphia http://www.netlib.org/lapack/lug
Golub G H and Van Loan C F (1996) Matrix Computations (3rd Edition) Johns Hopkins University Press, Baltimore

5 Arguments

1:   JOBZ – CHARACTER(1)Input
On entry: specifies options for computing all or part of the matrix U.
JOBZ='A'
All m columns of U and all n rows of VT are returned in the arrays U and VT.
JOBZ='S'
The first min m,n columns of U and the first min m,n rows of VT are returned in the arrays U and VT.
JOBZ='O'
If M≥N, the first n columns of U are overwritten on the array A and all rows of VT are returned in the array VT. Otherwise, all columns of U are returned in the array U and the first m rows of VT are overwritten in the array VT.
JOBZ='N'
No columns of U or rows of VT are computed.
Constraint: JOBZ='A', 'S', 'O' or 'N'.
2:   M – INTEGERInput
On entry: m, the number of rows of the matrix A.
Constraint: M≥0.
3:   N – INTEGERInput
On entry: n, the number of columns of the matrix A.
Constraint: N≥0.
4:   A LDA* – REAL (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array A must be at least max 1,N.
On entry: the m by n matrix A.
On exit: if JOBZ='O', A is overwritten with the first n columns of U (the left singular vectors, stored column-wise) if M≥N; A is overwritten with the first m rows of VT (the right singular vectors, stored row-wise) otherwise.
If JOBZ≠'O', the contents of A are destroyed.
5:   LDA – INTEGERInput
On entry: the first dimension of the array A as declared in the (sub)program from which F08KDF (DGESDD) is called.
Constraint: LDA≥max 1,M.
6:   S min M,N – REAL (KIND=nag_wp) arrayOutput
On exit: the singular values of A, sorted so that S i≥S i+1.
7:   U LDU* – REAL (KIND=nag_wp) arrayOutput
Note: the second dimension of the array U must be at least max 1,M if JOBZ='A' or JOBZ='O' and M<N, max 1,min M,N if JOBZ='S', and at least 1 otherwise.
On exit:
If JOBZ='A' or JOBZ='O' and M<N, U contains the m by m orthogonal matrix U.
If JOBZ='S', U contains the first min m,n columns of U (the left singular vectors, stored column-wise).
If JOBZ='O' and M≥N, or JOBZ='N', U is not referenced.
8:   LDU – INTEGERInput
On entry: the first dimension of the array U as declared in the (sub)program from which F08KDF (DGESDD) is called.
Constraints:
  • if JOBZ='S' or 'A' or JOBZ='O' and M<N, LDU≥ max 1,M ;
  • otherwise LDU≥1.
9:   VT LDVT* – REAL (KIND=nag_wp) arrayOutput
Note: the second dimension of the array VT must be at least max 1,N if JOBZ='A' or 'S' or JOBZ='O' and M≥N, and at least 1 otherwise.
On exit: if JOBZ='A' or JOBZ='O' and M≥N, VT contains the n by n orthogonal matrix VT.
If JOBZ='S', VT contains the first min m,n rows of VT (the right singular vectors, stored row-wise).
If JOBZ='O' and M<N, or JOBZ='N', VT is not referenced.
10:   LDVT – INTEGERInput
On entry: the first dimension of the array VT as declared in the (sub)program from which F08KDF (DGESDD) is called.
Constraints:
  • if JOBZ='A' or JOBZ='O' and M≥N, LDVT≥ max 1,N ;
  • if JOBZ='S', LDVT≥ max 1,min M,N ;
  • otherwise LDVT≥1.
11:   WORK max 1,LWORK – REAL (KIND=nag_wp) arrayWorkspace
12:   LWORK – INTEGERInput
On entry: the dimension of the array WORK as declared in the (sub)program from which F08KDF (DGESDD) is called.
If LWORK=-1, a workspace query is assumed; the routine only calculates the optimal size of the WORK array, returns this value as the first entry of the WORK array, and no error message related to LWORK is issued.
Suggested value: for optimal performance, LWORK should generally be larger. Consider increasing LWORK by at least nb×min M,N , where nb is the optimal block size.
Constraints:
  • if JOBZ='N', LWORK≥3×min M,N+max 1,max M,N,7×min M,N;
  • if JOBZ='O', LWORK≥3×min M,N+max 1,max M,N,5×min M,N×min M,N+4×min M,N;
  • if JOBZ='S' or 'A', LWORK≥3×min M,N+max 1,max M,N,4×min M,N×min M,N+4×min M,N;
  • otherwise LWORK≥1.
13:   IWORK 8×min M,N – INTEGER arrayWorkspace
14:   INFO – INTEGEROutput
On exit: INFO=0 unless the routine detects an error (see Section 6).

6 Error Indicators and Warnings

INFO<0
If INFO=-i, argument i had an illegal value. An explanatory message is output, and execution of the program is terminated.
INFO>0
F08KDF (DGESDD) did not converge, the updating process failed.

7 Accuracy

The computed singular value decomposition is nearly the exact singular value decomposition for a nearby matrix A+E , where
E 2 = O ε A 2 ,
and ε is the machine precision. In addition, the computed singular vectors are nearly orthogonal to working precision. See Section 4.9 of Anderson et al. (1999) for further details.

8 Parallelism and Performance

F08KDF (DGESDD) is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
F08KDF (DGESDD) makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The total number of floating-point operations is approximately proportional to m n 2 when m>n and m 2 n otherwise.
The singular values are returned in descending order.
The complex analogue of this routine is F08KRF (ZGESDD).

10 Example

This example finds the singular values and left and right singular vectors of the 4 by 6 matrix
A = 2.27 0.28 -0.48 1.07 -2.35 0.62 -1.54 -1.67 -3.09 1.22 2.93 -7.39 1.15 0.94 0.99 0.79 -1.45 1.03 -1.94 -0.78 -0.21 0.63 2.30 -2.57 ,
together with approximate error bounds for the computed singular values and vectors.
The example program for F08KBF (DGESVD) illustrates finding a singular value decomposition for the case m≥n.

10.1 Program Text

Program Text (f08kdfe.f90)

10.2 Program Data

Program Data (f08kdfe.d)

10.3 Program Results

Program Results (f08kdfe.r)

F08 Chapter Contents
F08 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F08KEF (DGEBRD) : NAG Library, Mark 26

F08 Chapter Contents
F08 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F08KEF (DGEBRD)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F08KEF (DGEBRD) reduces a real m by n matrix to bidiagonal form.

2 Specification

SUBROUTINE F08KEF ( M, N, A, LDA, D, E, TAUQ, TAUP, WORK, LWORK, INFO)
INTEGER | M, N, LDA, LWORK, INFO
REAL (KIND=nag_wp) | A(LDA,*), D(*), E(*), TAUQ(*), TAUP(*), WORK(max(1,LWORK))
The routine may be called by its LAPACK name dgebrd.

3 Description

F08KEF (DGEBRD) reduces a real m by n matrix A to bidiagonal form B by an orthogonal transformation: A=QB PT, where Q and PT are orthogonal matrices of order m and n respectively.
If m≥n, the reduction is given by:
A =Q B 1 0 PT = Q 1 B 1 PT ,
where B 1 is an n by n upper bidiagonal matrix and Q 1 consists of the first n columns of Q.
If m<n, the reduction is given by
A =Q B 1 0 PT = Q B 1 P 1 T ,
where B 1 is an m by m lower bidiagonal matrix and P 1 T consists of the first m rows of PT.
The orthogonal matrices Q and P are not formed explicitly but are represented as products of elementary reflectors (see the F08 Chapter Introduction for details). Routines are provided to work with Q and P in this representation (see Section 9).

4 References

Golub G H and Van Loan C F (1996) Matrix Computations (3rd Edition) Johns Hopkins University Press, Baltimore

5 Arguments

1:   M – INTEGERInput
On entry: m, the number of rows of the matrix A.
Constraint: M≥0.
2:   N – INTEGERInput
On entry: n, the number of columns of the matrix A.
Constraint: N≥0.
3:   A LDA* – REAL (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array A must be at least max 1,N.
On entry: the m by n matrix A.
On exit: if m≥n, the diagonal and first superdiagonal are overwritten by the upper bidiagonal matrix B, elements below the diagonal are overwritten by details of the orthogonal matrix Q and elements above the first superdiagonal are overwritten by details of the orthogonal matrix P.
If m<n, the diagonal and first subdiagonal are overwritten by the lower bidiagonal matrix B, elements below the first subdiagonal are overwritten by details of the orthogonal matrix Q and elements above the diagonal are overwritten by details of the orthogonal matrix P.
4:   LDA – INTEGERInput
On entry: the first dimension of the array A as declared in the (sub)program from which F08KEF (DGEBRD) is called.
Constraint: LDA≥max 1,M.
5:   D* – REAL (KIND=nag_wp) arrayOutput
Note: the dimension of the array D must be at least max 1,min M,N.
On exit: the diagonal elements of the bidiagonal matrix B.
6:   E* – REAL (KIND=nag_wp) arrayOutput
Note: the dimension of the array E must be at least max 1,min M,N-1.
On exit: the off-diagonal elements of the bidiagonal matrix B.
7:   TAUQ* – REAL (KIND=nag_wp) arrayOutput
Note: the dimension of the array TAUQ must be at least max 1,min M,N.
On exit: further details of the orthogonal matrix Q.
8:   TAUP* – REAL (KIND=nag_wp) arrayOutput
Note: the dimension of the array TAUP must be at least max 1,min M,N.
On exit: further details of the orthogonal matrix P.
9:   WORK max 1,LWORK – REAL (KIND=nag_wp) arrayWorkspace
On exit: if INFO=0, WORK 1 contains the minimum value of LWORK required for optimal performance.
10:   LWORK – INTEGERInput
On entry: the dimension of the array WORK as declared in the (sub)program from which F08KEF (DGEBRD) is called.
If LWORK=-1, a workspace query is assumed; the routine only calculates the optimal size of the WORK array, returns this value as the first entry of the WORK array, and no error message related to LWORK is issued.
Suggested value: for optimal performance, LWORK≥M+N×nb, where nb is the optimal block size.
Constraint: LWORK≥max 1,M,N or LWORK=-1.
11:   INFO – INTEGEROutput
On exit: INFO=0 unless the routine detects an error (see Section 6).

6 Error Indicators and Warnings

INFO<0
If INFO=-i, argument i had an illegal value. An explanatory message is output, and execution of the program is terminated.

7 Accuracy

The computed bidiagonal form B satisfies QB PT=A+E, where
E 2 ≤ c n ε A 2 ,
c n is a modestly increasing function of n, and ε is the machine precision.
The elements of B themselves may be sensitive to small perturbations in A or to rounding errors in the computation, but this does not affect the stability of the singular values and vectors.

8 Parallelism and Performance

F08KEF (DGEBRD) is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
F08KEF (DGEBRD) makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The total number of floating-point operations is approximately 43 n 2 3 m-n if m≥n or 43 m 2 3 n-m if m<n.
If m≫n, it can be more efficient to first call F08AEF (DGEQRF) to perform a QR factorization of A, and then to call F08KEF (DGEBRD) to reduce the factor R to bidiagonal form. This requires approximately 2 n 2 m+n floating-point operations.
If m≪n, it can be more efficient to first call F08AHF (DGELQF) to perform an LQ factorization of A, and then to call F08KEF (DGEBRD) to reduce the factor L to bidiagonal form. This requires approximately 2 m 2 m+n operations.
To form the orthogonal matrices PT and/or Q F08KEF (DGEBRD) may be followed by calls to F08KFF (DORGBR):
to form the m by m orthogonal matrix Q
CALL DORGBR('Q',M,M,N,A,LDA,TAUQ,WORK,LWORK,INFO)
but note that the second dimension of the array A must be at least M, which may be larger than was required by F08KEF (DGEBRD);
to form the n by n orthogonal matrix PT
CALL DORGBR('P',N,N,M,A,LDA,TAUP,WORK,LWORK,INFO)
but note that the first dimension of the array A, specified by the argument LDA, must be at least N, which may be larger than was required by F08KEF (DGEBRD).
To apply Q or P to a real rectangular matrix C, F08KEF (DGEBRD) may be followed by a call to F08KGF (DORMBR).
The complex analogue of this routine is F08KSF (ZGEBRD).

10 Example

This example reduces the matrix A to bidiagonal form, where
A = -0.57 -1.28 -0.39 0.25 -1.93 1.08 -0.31 -2.14 2.30 0.24 0.40 -0.35 -1.93 0.64 -0.66 0.08 0.15 0.30 0.15 -2.13 -0.02 1.03 -1.43 0.50 .

10.1 Program Text

Program Text (f08kefe.f90)

10.2 Program Data

Program Data (f08kefe.d)

10.3 Program Results

Program Results (f08kefe.r)

F08 Chapter Contents
F08 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F08KFF (DORGBR) : NAG Library, Mark 26

F08 Chapter Contents
F08 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F08KFF (DORGBR)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F08KFF (DORGBR) generates one of the real orthogonal matrices Q or PT which were determined by F08KEF (DGEBRD) when reducing a real matrix to bidiagonal form.

2 Specification

SUBROUTINE F08KFF ( VECT, M, N, K, A, LDA, TAU, WORK, LWORK, INFO)
INTEGER | M, N, K, LDA, LWORK, INFO
REAL (KIND=nag_wp) | A(LDA,*), TAU(*), WORK(max(1,LWORK))
CHARACTER(1) | VECT
The routine may be called by its LAPACK name dorgbr.

3 Description

F08KFF (DORGBR) is intended to be used after a call to F08KEF (DGEBRD), which reduces a real rectangular matrix A to bidiagonal form B by an orthogonal transformation: A=QB PT. F08KEF (DGEBRD) represents the matrices Q and PT as products of elementary reflectors.
This routine may be used to generate Q or PT explicitly as square matrices, or in some cases just the leading columns of Q or the leading rows of PT.
The various possibilities are specified by the arguments VECT, M, N and K. The appropriate values to cover the most likely cases are as follows (assuming that A was an m by n matrix):
1. To form the full m by m matrix Q:
CALL DORGBR('Q',m,m,n,...)
(note that the array A must have at least m columns).
2. If m>n, to form the n leading columns of Q:
CALL DORGBR('Q',m,n,n,...)
3. To form the full n by n matrix PT:
CALL DORGBR('P',n,n,m,...)
(note that the array A must have at least n rows).
4. If m<n, to form the m leading rows of PT:
CALL DORGBR('P',m,n,m,...)

4 References

Golub G H and Van Loan C F (1996) Matrix Computations (3rd Edition) Johns Hopkins University Press, Baltimore

5 Arguments

1:   VECT – CHARACTER(1)Input
On entry: indicates whether the orthogonal matrix Q or PT is generated.
VECT='Q'
Q is generated.
VECT='P'
PT is generated.
Constraint: VECT='Q' or 'P'.
2:   M – INTEGERInput
On entry: m, the number of rows of the orthogonal matrix Q or PT to be returned.
Constraint: M≥0.
3:   N – INTEGERInput
On entry: n, the number of columns of the orthogonal matrix Q or PT to be returned.
Constraints:
  • N≥0;
  • if VECT='Q' and M>K, M≥N≥K;
  • if VECT='Q' and M≤K, M=N;
  • if VECT='P' and N>K, N≥M≥K;
  • if VECT='P' and N≤K, N=M.
4:   K – INTEGERInput
On entry: if VECT='Q', the number of columns in the original matrix A.
If VECT='P', the number of rows in the original matrix A.
Constraint: K≥0.
5:   A LDA* – REAL (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array A must be at least max 1,N.
On entry: details of the vectors which define the elementary reflectors, as returned by F08KEF (DGEBRD).
On exit: the orthogonal matrix Q or PT, or the leading rows or columns thereof, as specified by VECT, M and N.
6:   LDA – INTEGERInput
On entry: the first dimension of the array A as declared in the (sub)program from which F08KFF (DORGBR) is called.
Constraint: LDA≥max 1,M.
7:   TAU* – REAL (KIND=nag_wp) arrayInput
Note: the dimension of the array TAU must be at least max 1,min M,K if VECT='Q' and at least max 1,min N,K if VECT='P'.
On entry: further details of the elementary reflectors, as returned by F08KEF (DGEBRD) in its argument TAUQ if VECT='Q', or in its argument TAUP if VECT='P'.
8:   WORK max 1,LWORK – REAL (KIND=nag_wp) arrayWorkspace
On exit: if INFO=0, WORK 1 contains the minimum value of LWORK required for optimal performance.
9:   LWORK – INTEGERInput
On entry: the dimension of the array WORK as declared in the (sub)program from which F08KFF (DORGBR) is called.
If LWORK=-1, a workspace query is assumed; the routine only calculates the optimal size of the WORK array, returns this value as the first entry of the WORK array, and no error message related to LWORK is issued.
Suggested value: for optimal performance, LWORK≥min M,N×nb, where nb is the optimal block size.
Constraint: LWORK≥ max 1,min M,N or LWORK=-1.
10:   INFO – INTEGEROutput
On exit: INFO=0 unless the routine detects an error (see Section 6).

6 Error Indicators and Warnings

INFO<0
If INFO=-i, argument i had an illegal value. An explanatory message is output, and execution of the program is terminated.

7 Accuracy

The computed matrix Q differs from an exactly orthogonal matrix by a matrix E such that
E 2 = O ε ,
where ε is the machine precision. A similar statement holds for the computed matrix PT.

8 Parallelism and Performance

F08KFF (DORGBR) is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
F08KFF (DORGBR) makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The total number of floating-point operations for the cases listed in Section 3 are approximately as follows:
1. To form the whole of Q:
  • 43 n 3 m 2-3 mn+n 2 if m>n,
  • 43 m 3 if m≤n;
2. To form the n leading columns of Q when m>n:
  • 23 n 2 3 m-n ;
3. To form the whole of PT:
  • 43 n 3 if m≥n,
  • 43 m 3 n 2-3 mn+m 2 if m<n;
4. To form the m leading rows of PT when m<n:
  • 23 m 2 3 n-m .
The complex analogue of this routine is F08KTF (ZUNGBR).

10 Example

For this routine two examples are presented, both of which involve computing the singular value decomposition of a matrix A, where
A = -0.57 -1.28 -0.39 0.25 -1.93 1.08 -0.31 -2.14 2.30 0.24 0.40 -0.35 -1.93 0.64 -0.66 0.08 0.15 0.30 0.15 -2.13 -0.02 1.03 -1.43 0.50
in the first example and
A = -5.42 3.28 -3.68 0.27 2.06 0.46 -1.65 -3.40 -3.20 -1.03 -4.06 -0.01 -0.37 2.35 1.90 4.31 -1.76 1.13 -3.15 -0.11 1.99 -2.70 0.26 4.50
in the second. A must first be reduced to tridiagonal form by F08KEF (DGEBRD). The program then calls F08KFF (DORGBR) twice to form Q and PT, and passes these matrices to F08MEF (DBDSQR), which computes the singular value decomposition of A.

10.1 Program Text

Program Text (f08kffe.f90)

10.2 Program Data

Program Data (f08kffe.d)

10.3 Program Results

Program Results (f08kffe.r)

F08 Chapter Contents
F08 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F08KGF (DORMBR) : NAG Library, Mark 26

F08 Chapter Contents
F08 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F08KGF (DORMBR)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F08KGF (DORMBR) multiplies an arbitrary real m by n matrix C by one of the real orthogonal matrices Q or P which were determined by F08KEF (DGEBRD) when reducing a real matrix to bidiagonal form.

2 Specification

SUBROUTINE F08KGF ( VECT, SIDE, TRANS, M, N, K, A, LDA, TAU, C, LDC, WORK, LWORK, INFO)
INTEGER | M, N, K, LDA, LDC, LWORK, INFO
REAL (KIND=nag_wp) | A(LDA,*), TAU(*), C(LDC,*), WORK(max(1,LWORK))
CHARACTER(1) | VECT, SIDE, TRANS
The routine may be called by its LAPACK name dormbr.

3 Description

F08KGF (DORMBR) is intended to be used after a call to F08KEF (DGEBRD), which reduces a real rectangular matrix A to bidiagonal form B by an orthogonal transformation: A=QB PT. F08KEF (DGEBRD) represents the matrices Q and PT as products of elementary reflectors.
This routine may be used to form one of the matrix products
QC , QT C , CQ , C QT , PC , PT C , CP ​ or ​ C PT ,
overwriting the result on C (which may be any real rectangular matrix).

4 References

Golub G H and Van Loan C F (1996) Matrix Computations (3rd Edition) Johns Hopkins University Press, Baltimore

5 Arguments

Note: in the descriptions below, r denotes the order of Q or PT: if SIDE='L', r=M and if SIDE='R', r=N.
1:   VECT – CHARACTER(1)Input
On entry: indicates whether Q or QT or P or PT is to be applied to C.
VECT='Q'
Q or QT is applied to C.
VECT='P'
P or PT is applied to C.
Constraint: VECT='Q' or 'P'.
2:   SIDE – CHARACTER(1)Input
On entry: indicates how Q or QT or P or PT is to be applied to C.
SIDE='L'
Q or QT or P or PT is applied to C from the left.
SIDE='R'
Q or QT or P or PT is applied to C from the right.
Constraint: SIDE='L' or 'R'.
3:   TRANS – CHARACTER(1)Input
On entry: indicates whether Q or P or QT or PT is to be applied to C.
TRANS='N'
Q or P is applied to C.
TRANS='T'
QT or PT is applied to C.
Constraint: TRANS='N' or 'T'.
4:   M – INTEGERInput
On entry: m, the number of rows of the matrix C.
Constraint: M≥0.
5:   N – INTEGERInput
On entry: n, the number of columns of the matrix C.
Constraint: N≥0.
6:   K – INTEGERInput
On entry: if VECT='Q', the number of columns in the original matrix A.
If VECT='P', the number of rows in the original matrix A.
Constraint: K≥0.
7:   A LDA* – REAL (KIND=nag_wp) arrayInput
Note: the second dimension of the array A must be at least max 1,min r,K if VECT='Q' and at least max 1,r if VECT='P'.
On entry: details of the vectors which define the elementary reflectors, as returned by F08KEF (DGEBRD).
8:   LDA – INTEGERInput
On entry: the first dimension of the array A as declared in the (sub)program from which F08KGF (DORMBR) is called.
Constraints:
  • if VECT='Q', LDA≥ max 1,r ;
  • if VECT='P', LDA≥ max 1,min r,K .
9:   TAU* – REAL (KIND=nag_wp) arrayInput
Note: the dimension of the array TAU must be at least max 1,min r,K.
On entry: further details of the elementary reflectors, as returned by F08KEF (DGEBRD) in its argument TAUQ if VECT='Q', or in its argument TAUP if VECT='P'.
10:   C LDC* – REAL (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array C must be at least max 1,N.
On entry: the matrix C.
On exit: C is overwritten by QC or QT C or CQ or CT Q or PC or PT C or CP or CT P as specified by VECT, SIDE and TRANS.
11:   LDC – INTEGERInput
On entry: the first dimension of the array C as declared in the (sub)program from which F08KGF (DORMBR) is called.
Constraint: LDC≥max 1,M.
12:   WORK max 1,LWORK – REAL (KIND=nag_wp) arrayWorkspace
On exit: if INFO=0, WORK 1 contains the minimum value of LWORK required for optimal performance.
13:   LWORK – INTEGERInput
On entry: the dimension of the array WORK as declared in the (sub)program from which F08KGF (DORMBR) is called.
If LWORK=-1, a workspace query is assumed; the routine only calculates the optimal size of the WORK array, returns this value as the first entry of the WORK array, and no error message related to LWORK is issued.
Suggested value: for optimal performance, LWORK≥N×nb if SIDE='L' and at least M×nb if SIDE='R', where nb is the optimal block size.
Constraints:
  • if SIDE='L', LWORK≥max 1,N or LWORK=-1;
  • if SIDE='R', LWORK≥max 1,M or LWORK=-1.
14:   INFO – INTEGEROutput
On exit: INFO=0 unless the routine detects an error (see Section 6).

6 Error Indicators and Warnings

INFO<0
If INFO=-i, argument i had an illegal value. An explanatory message is output, and execution of the program is terminated.

7 Accuracy

The computed result differs from the exact result by a matrix E such that
E 2 = O ε C 2 ,
where ε is the machine precision.

8 Parallelism and Performance

F08KGF (DORMBR) is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
F08KGF (DORMBR) makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The total number of floating-point operations is approximately
  • if SIDE='L' and m≥k, 2 nk 2 m-k;
  • if SIDE='R' and n≥k, 2 mk 2 n-k;
  • if SIDE='L' and m<k, 2 m 2 n;
  • if SIDE='R' and n<k, 2 m n 2,
where k is the value of the argument K.
The complex analogue of this routine is F08KUF (ZUNMBR).

10 Example

For this routine two examples are presented. Both illustrate how the reduction to bidiagonal form of a matrix A may be preceded by a QR or LQ factorization of A.
In the first example, m>n, and
A = -0.57 -1.28 -0.39 0.25 -1.93 1.08 -0.31 -2.14 2.30 0.24 0.40 -0.35 -1.93 0.64 -0.66 0.08 0.15 0.30 0.15 -2.13 -0.02 1.03 -1.43 0.50 .
The routine first performs a QR factorization of A as A=Qa R and then reduces the factor R to bidiagonal form B: R=Qb B PT. Finally it forms Qa and calls F08KGF (DORMBR) to form Q=QaQb.
In the second example, m<n, and
A = -5.42 3.28 -3.68 0.27 2.06 0.46 -1.65 -3.40 -3.20 -1.03 -4.06 -0.01 -0.37 2.35 1.90 4.31 -1.76 1.13 -3.15 -0.11 1.99 -2.70 0.26 4.50 .
The routine first performs an LQ factorization of A as A=L PaT and then reduces the factor L to bidiagonal form B: L=QB PbT. Finally it forms PbT and calls F08KGF (DORMBR) to form PT=PbTPaT.

10.1 Program Text

Program Text (f08kgfe.f90)

10.2 Program Data

Program Data (f08kgfe.d)

10.3 Program Results

Program Results (f08kgfe.r)

F08 Chapter Contents
F08 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F08KHF (DGEJSV) : NAG Library, Mark 26

F08 Chapter Contents
F08 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F08KHF (DGEJSV)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F08KHF (DGEJSV) computes the singular value decomposition (SVD) of a real m by n matrix A where m≥n, and optionally computes the left and/or right singular vectors. F08KHF (DGEJSV) implements the preconditioned Jacobi SVD of Drmac and Veselic. This is the expert driver routine that calls F08KJF (DGESVJ) after certain preconditioning. In most cases F08KBF (DGESVD) or F08KDF (DGESDD) is sufficient to obtain the SVD of a real matrix. These are much simpler to use and also handle the case m<n.

2 Specification

SUBROUTINE F08KHF ( JOBA, JOBU, JOBV, JOBR, JOBT, JOBP, M, N, A, LDA, SVA, U, LDU, V, LDV, WORK, LWORK, IWORK, INFO)
INTEGER | M, N, LDA, LDU, LDV, LWORK, IWORK(M+3*N), INFO
REAL (KIND=nag_wp) | A(LDA,*), SVA(N), U(LDU,*), V(LDV,*), WORK(LWORK)
CHARACTER(1) | JOBA, JOBU, JOBV, JOBR, JOBT, JOBP
The routine may be called by its LAPACK name dgejsv.

3 Description

The SVD is written as
A = UΣ VT ,
where Σ is an m by n matrix which is zero except for its n diagonal elements, U is an m by m orthogonal matrix, and V is an n by n orthogonal matrix. The diagonal elements of Σ are the singular values of A in descending order of magnitude. The columns of U and V are the left and the right singular vectors of A. The diagonal of Σ is computed and stored in the array SVA.

4 References

Anderson E, Bai Z, Bischof C, Blackford S, Demmel J, Dongarra J J, Du Croz J J, Greenbaum A, Hammarling S, McKenney A and Sorensen D (1999) LAPACK Users' Guide (3rd Edition) SIAM, Philadelphia http://www.netlib.org/lapack/lug
Drmac Z and Veselic K (2008a) New fast and accurate Jacobi SVD algorithm I SIAM J. Matrix Anal. Appl. 29 4
Drmac Z and Veselic K (2008b) New fast and accurate Jacobi SVD algorithm II SIAM J. Matrix Anal. Appl. 29 4
Golub G H and Van Loan C F (1996) Matrix Computations (3rd Edition) Johns Hopkins University Press, Baltimore

5 Arguments

1:   JOBA – CHARACTER(1)Input
On entry: specifies the form of pivoting for the QR factorization stage; whether an estimate of the condition number of the scaled matrix is required; and the form of rank reduction that is performed.
JOBA='C'
The initial QR factorization of the input matrix is performed with column pivoting; no estimate of condition number is computed; and, the rank is reduced by only the underflowed part of the triangular factor R. This option works well (high relative accuracy) if A=BD, with well-conditioned B and arbitrary diagonal matrix D. The accuracy cannot be spoiled by column scaling. The accuracy of the computed output depends on the condition of B, and the procedure aims at the best theoretical accuracy.
JOBA='E'
Computation as with JOBA='C' with an additional estimate of the condition number of B. It provides a realistic error bound.
JOBA='F'
The initial QR factorization of the input matrix is performed with full row and column pivoting; no estimate of condition number is computed; and, the rank is reduced by only the underflowed part of the triangular factor R. If A=D 1×C×D 2 with ill-conditioned diagonal scalings D 1, D 2, and well-conditioned matrix C, this option gives higher accuracy than the JOBA='C' option. If the structure of the input matrix is not known, and relative accuracy is desirable, then this option is advisable.
JOBA='G'
Computation as with JOBA='F' with an additional estimate of the condition number of B, where A=DB (i.e., B=C×D 2). If A has heavily weighted rows, then using this condition number gives too pessimistic an error bound.
JOBA='A'
Computation as with JOBA='C' except in the treatment of rank reduction. In this case, small singular values are to be considered as noise and, if found, the matrix is treated as numerically rank deficient. The computed SVD A=UΣ VT restores A up to f m,n×ε×A, where ε is machine precision. This gives the procedure licence to discard (set to zero) all singular values below N×ε×A.
JOBA='R'
Similar to JOBA='A'. The rank revealing property of the initial QR factorization is used to reveal (using the upper triangular factor) a gap σ r+1<ε σr in which case the numerical rank is declared to be r. The SVD is computed with absolute error bounds, but more accurately than with JOBA='A'.
Constraint: JOBA='C', 'E', 'F', 'G', 'A' or 'R'.
2:   JOBU – CHARACTER(1)Input
On entry: specifies options for computing the left singular vectors U.
JOBU='U'
The first n left singular vectors (columns of U) are computed and returned in the array U.
JOBU='F'
All m left singular vectors are computed and returned in the array U.
JOBU='W'
No left singular vectors are computed, but the array U (with LDU≥M and second dimension at least N) is available as workspace for computing right singular values. See the description of U.
JOBU='N'
No left singular vectors are computed. U is not referenced.
Constraint: JOBU='U', 'F', 'W' or 'N'.
3:   JOBV – CHARACTER(1)Input
On entry: specifies options for computing the right singular vectors V.
JOBV='V'
the n right singular vectors (columns of V) are computed and returned in the array V; Jacobi rotations are not explicitly accumulated.
JOBV='J'
the n right singular vectors (columns of V) are computed and returned in the array V, but they are computed as the product of Jacobi rotations. This option is allowed only if JOBU='U' or 'F', i.e., in computing the full SVD.
JOBV='W'
No right singular values are computed, but the array V (with LDV≥N and second dimension at least N) is available as workspace for computing left singular values. See the description of V.
JOBV='N'
No right singular vectors are computed. V is not referenced.
Constraints:
  • JOBV='V', 'J', 'W' or 'N';
  • if JOBU='W' or 'N', JOBV≠'J'.
4:   JOBR – CHARACTER(1)Input
On entry: specifies the conditions under which columns of A are to be set to zero. This effectively specifies a lower limit on the range of singular values; any singular values below this limit are (through column zeroing) set to zero. If A≠0 is scaled so that the largest column (in the Euclidean norm) of cA is equal to the square root of the overflow threshold, then JOBR allows the routine to kill columns of A whose norm in cA is less than sfmin (for JOBR='R'), or less than sfmin/ε (otherwise). sfmin is the safe range argument, as returned by routine X02AMF.
JOBR='N'
Only set to zero those columns of A for which the norm of corresponding column of cA<sfmin/ε, that is, those columns that are effectively zero (to machine precision) anyway. If the condition number of A is greater than the overflow threshold λ, where λ is the value returned by X02ALF, you are recommended to use routine F08KJF (DGESVJ).
JOBR='R'
Set to zero those columns of A for which the norm of the corresponding column of cA<sfmin. This approximately represents a restricted range for σ cA of sfmin,λ.
For computing the singular values in the full range from the safe minimum up to the overflow threshold use F08KJF (DGESVJ).
Suggested value: JOBR='R'.
Constraint: JOBR='N' or 'R'.
5:   JOBT – CHARACTER(1)Input
On entry: specifies, in the case n=m, whether the routine is permitted to use the transpose of A for improved efficiency. If the matrix is square then the procedure may use transposed A if AT seems to be better with respect to convergence. If the matrix is not square, JOBT is ignored. The decision is based on two values of entropy over the adjoint orbit of AT A. See the descriptions of WORK 6 and WORK 7.
JOBT='T'
If n=m, perform an entropy test and then transpose if the test indicates possibly faster convergence of the Jacobi process if AT is taken as input. If A is replaced with AT, then the row pivoting is included automatically.
JOBT='N'
No entropy test and no transposition is performed.
The option JOBT='T' can be used to compute only the singular values, or the full SVD (U, Σ and V). In the case where only one set of singular vectors (U or V) is required, the caller must still provide both U and V, as one of the matrices is used as workspace if the matrix A is transposed. See the descriptions of U and V.
Constraint: JOBT='T' or 'N'.
6:   JOBP – CHARACTER(1)Input
On entry: specifies whether the routine should be allowed to introduce structured perturbations to drown denormalized numbers. For details see Drmac and Veselic (2008a) and Drmac and Veselic (2008b). For the sake of simplicity, these perturbations are included only when the full SVD or only the singular values are requested.
JOBP='P'
Introduce perturbation if A is found to be very badly scaled (introducing denormalized numbers).
JOBP='N'
Do not perturb.
Constraint: JOBP='P' or 'N'.
7:   M – INTEGERInput
On entry: m, the number of rows of the matrix A.
Constraint: M≥0.
8:   N – INTEGERInput
On entry: n, the number of columns of the matrix A.
Constraint: M≥N≥0.
9:   A LDA* – REAL (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array A must be at least max 1,N.
On entry: the m by n matrix A.
On exit: the contents of A are overwritten.
10:   LDA – INTEGERInput
On entry: the first dimension of the array A as declared in the (sub)program from which F08KHF (DGEJSV) is called.
Constraint: LDA≥max 1,M.
11:   SVA N – REAL (KIND=nag_wp) arrayOutput
On exit: the, possibly scaled, singular values of A.
The singular values of A are σi=α SVA i, for i=1,2,…,n, where α=WORK 1/WORK 2. Normally α=1 and no scaling is required to obtain the singular values. However, if the largest singular value of A overflows or if small singular values have been saved from underflow by scaling the input matrix A, then α≠1.
If JOBR='R' then some of the singular values may be returned as exact zeros because they are below the numerical rank threshold or are denormalized numbers.
12:   U LDU* – REAL (KIND=nag_wp) arrayOutput
Note: the second dimension of the array U must be at least max 1,M if JOBU='F', max 1,N if JOBU='U' or 'W', and at least 1 otherwise.
On exit: if JOBU='U', U contains the m by n matrix of the left singular vectors.
If JOBU='F', U contains the m by m matrix of the left singular vectors, including an orthonormal basis of the orthogonal complement of Range(A).
If JOBU='W' and (JOBV='V' and JOBT='T' and M=N), then U is used as workspace if the procedure replaces A with AT. In that case, V is computed in U as left singular vectors of AT and then copied back to the array V.
If JOBU='N', U is not referenced.
13:   LDU – INTEGERInput
On entry: the first dimension of the array U as declared in the (sub)program from which F08KHF (DGEJSV) is called.
Constraints:
  • if JOBU='F', 'U' or 'W', LDU≥max 1,M;
  • otherwise LDU≥1.
14:   V LDV* – REAL (KIND=nag_wp) arrayOutput
Note: the second dimension of the array V must be at least max 1,N if JOBV='V', 'J' or 'W', and at least 1 otherwise.
On exit: if JOBV='V' or 'J', V contains the n by n matrix of the right singular vectors.
If JOBV='W' and (JOBU='U' and JOBT='T' and M=N), then V is used as workspace if the procedure replaces A with AT. In that case, U is computed in V as right singular vectors of AT and then copied back to the array U.
If JOBV='N', V is not referenced.
15:   LDV – INTEGERInput
On entry: the first dimension of the array V as declared in the (sub)program from which F08KHF (DGEJSV) is called.
Constraints:
  • if JOBV='V', 'J' or 'W', LDV≥max 1,N;
  • otherwise LDV≥1.
16:   WORK LWORK – REAL (KIND=nag_wp) arrayWorkspace
On exit: contains information about the completed job.
WORK 1
α=WORK 1/WORK 2 is the scaling factor such that σi=α SVA i, for i=1,2,…,n are the computed singular values of A. (See the description of SVA.)
WORK 2
See the description of WORK 1.
WORK 3
sconda, an estimate for the condition number of column equilibrated A (if JOBA='E' or 'G'). sconda is an estimate of RT R-1 1. It is computed using F07FGF (DPOCON). It satisfies n-14×sconda≤R-1 2≤n 14×sconda where R is the triangular factor from the QR factorization of A. However, if R is truncated and the numerical rank is determined to be strictly smaller than n, sconda is returned as -1, thus indicating that the smallest singular values might be lost.
If full SVD is needed, and you are familiar with the details of the method, the following two condition numbers are useful for the analysis of the algorithm.
WORK 4
An estimate of the scaled condition number of the triangular factor in the first QR factorization.
WORK 5
An estimate of the scaled condition number of the triangular factor in the second QR factorization.
The following two parameters are computed if JOBT='T'.
WORK 6
The entropy of AT A: this is the Shannon entropy of diag⁡AT A/trace⁡AT A taken as a point in the probability simplex.
WORK 7
The entropy of A AT.
17:   LWORK – INTEGERInput
On entry: the dimension of the array WORK as declared in the (sub)program from which F08KHF (DGEJSV) is called.
If JOBU='N' and JOBV='N'
if JOBA≠'E' or 'G'
The minimal requirement is LWORK≥max 2 M+N,4 N+1,7.
For optimal performance the requirement is LWORK≥max 2 M+N,3 N+N+1 nb,7, where nb is the block size used by F08AEF (DGEQRF) and F08BFF (DGEQP3). Assuming a value of nb=256 is wise, but choosing a smaller value (e.g., nb=128) should still lead to acceptable performance.
if JOBA='E' or 'G'
In this case, LWORK is the maximum of the above and N×N+4 N, i.e., LWORK≥max 2 M+N,3 N+N+1 nb,N×N+4 N,7.
If JOBU≠'U' or 'F' and JOBV='V' or 'J'
The minimal requirement is LWORK≥max 2 N+M,7.
For optimal performance, LWORK≥max 2 N+M,2 N+N×nb,7, where nb is described above.
If JOBU='U' or 'F' and JOBV≠'V' or 'J'
The minimal requirement is LWORK≥max 2 N+M,7.
For optimal performance, LWORK≥max 2 N+M,2 N+N×nb,7, where nb is described above.
If JOBU='U' or 'F' and JOBV='V'
LWORK≥6 N+2 N×N.
If JOBU='U' or 'F' and JOBV='J'
The minimal requirement is LWORK≥max M+3 N+N×N,7.
For better performance LWORK≥max 3 N+N×N+M,3 N+N×N+N×nb,7, where nb is described above.
18:   IWORK M+3×N – INTEGER arrayOutput
On exit: contains information about the completed job.
IWORK 1
The numerical rank of A determined after the initial QR factorization with pivoting. See the descriptions of JOBA and JOBR.
IWORK 2
The number of computed nonzero singular values.
IWORK 3
If nonzero, a warning message: If IWORK 3=1 then some of the column norms of A were denormalized (tiny) numbers. The requested high accuracy is not warranted by the data.
19:   INFO – INTEGEROutput
On exit: INFO=0 unless the routine detects an error (see Section 6).

6 Error Indicators and Warnings

INFO<0
If INFO=-i, argument i had an illegal value. An explanatory message is output, and execution of the program is terminated.
INFO>0
F08KHF (DGEJSV) did not converge in the allowed number of iterations (30). The computed values might be inaccurate.

7 Accuracy

The computed singular value decomposition is nearly the exact singular value decomposition for a nearby matrix A+E , where
E 2 = O ε A 2 ,
and ε is the machine precision. In addition, the computed singular vectors are nearly orthogonal to working precision. See Section 4.9 of Anderson et al. (1999) for further details.

8 Parallelism and Performance

F08KHF (DGEJSV) is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
F08KHF (DGEJSV) makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

F08KHF (DGEJSV) implements a preconditioned Jacobi SVD algorithm. It uses F08AEF (DGEQRF), F08AHF (DGELQF) and F08BFF (DGEQP3) as preprocessors and preconditioners. Optionally, an additional row pivoting can be used as a preprocessor, which in some cases results in much higher accuracy. An example is matrix A with the structure A=D 1 C D 2, where D 1, D 2 are arbitrarily ill-conditioned diagonal matrices and C is a well-conditioned matrix. In that case, complete pivoting in the first QR factorizations provides accuracy dependent on the condition number of C, and independent of D 1, D 2. Such higher accuracy is not completely understood theoretically, but it works well in practice. Further, if A can be written as A=BD, with well-conditioned B and some diagonal D, then the high accuracy is guaranteed, both theoretically and in software, independent of D.

10 Example

This example finds the singular values and left and right singular vectors of the 6 by 4 matrix
A = 2.27 -1.54 1.15 -1.94 0.28 -1.67 0.94 -0.78 -0.48 -3.09 0.99 -0.21 1.07 1.22 0.79 0.63 -2.35 2.93 -1.45 2.30 0.62 -7.39 1.03 -2.57 ,
together with the condition number of A and approximate error bounds for the computed singular values and vectors.

10.1 Program Text

Program Text (f08khfe.f90)

10.2 Program Data

Program Data (f08khfe.d)

10.3 Program Results

Program Results (f08khfe.r)

F08 Chapter Contents
F08 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F08KJF (DGESVJ) : NAG Library, Mark 26

F08 Chapter Contents
F08 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F08KJF (DGESVJ)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F08KJF (DGESVJ) computes the one-sided Jacobi singular value decomposition (SVD) of a real m by n matrix A, m≥n, with fast scaled rotations and de Rijk’s pivoting, optionally computing the left and/or right singular vectors. For m<n, the routines F08KBF (DGESVD) or F08KDF (DGESDD) may be used.

2 Specification

SUBROUTINE F08KJF ( JOBA, JOBU, JOBV, M, N, A, LDA, SVA, MV, V, LDV, WORK, LWORK, INFO)
INTEGER | M, N, LDA, MV, LDV, LWORK, INFO
REAL (KIND=nag_wp) | A(LDA,*), SVA(N), V(LDV,*), WORK(LWORK)
CHARACTER(1) | JOBA, JOBU, JOBV
The routine may be called by its LAPACK name dgesvj.

3 Description

The SVD is written as
A = UΣ VT ,
where Σ is an n by n diagonal matrix, U is an m by n orthonormal matrix, and V is an n by n orthogonal matrix. The diagonal elements of Σ are the singular values of A in descending order of magnitude. The columns of U and V are the left and the right singular vectors of A.

4 References

Anderson E, Bai Z, Bischof C, Blackford S, Demmel J, Dongarra J J, Du Croz J J, Greenbaum A, Hammarling S, McKenney A and Sorensen D (1999) LAPACK Users' Guide (3rd Edition) SIAM, Philadelphia http://www.netlib.org/lapack/lug
Drmac Z and Veselic K (2008a) New fast and accurate Jacobi SVD algorithm I SIAM J. Matrix Anal. Appl. 29 4
Drmac Z and Veselic K (2008b) New fast and accurate Jacobi SVD algorithm II SIAM J. Matrix Anal. Appl. 29 4
Golub G H and Van Loan C F (1996) Matrix Computations (3rd Edition) Johns Hopkins University Press, Baltimore

5 Arguments

1:   JOBA – CHARACTER(1)Input
On entry: specifies the structure of matrix A.
JOBA='L'
The input matrix A is lower triangular.
JOBA='U'
The input matrix A is upper triangular.
JOBA='G'
The input matrix A is a general m by n matrix, M≥N.
Constraint: JOBA='L', 'U' or 'G'.
2:   JOBU – CHARACTER(1)Input
On entry: specifies whether to compute the left singular vectors and if so whether you want to control their numerical orthogonality threshold.
JOBU='U'
The left singular vectors corresponding to the nonzero singular values are computed and returned in the leading columns of A. See more details in the description of A. The numerical orthogonality threshold is set to approximately tol=ctol×ε, where ε is the machine precision and ctol=m.
JOBU='C'
Analogous to JOBU='U', except that you can control the level of numerical orthogonality of the computed left singular vectors. The orthogonality threshold is set to tol=ctol×ε, where ctol is given on input in WORK 1. The option JOBU='C' can be used if m×ε is a satisfactory orthogonality of the computed left singular vectors, so ctol=M could save a few sweeps of Jacobi rotations. See the descriptions of A and WORK 1.
JOBU='N'
The matrix U is not computed. However, see the description of A.
Constraint: JOBU='U', 'C' or 'N'.
3:   JOBV – CHARACTER(1)Input
On entry: specifies whether and how to compute the right singular vectors.
JOBV='V'
The matrix V is computed and returned in the array V.
JOBV='A'
The Jacobi rotations are applied to the leading mv by n part of the array V. In other words, the right singular vector matrix V is not computed explicitly, instead it is applied to an mv by n matrix initially stored in the first MV rows of V.
JOBV='N'
The matrix V is not computed and the array V is not referenced.
Constraint: JOBV='V', 'A' or 'N'.
4:   M – INTEGERInput
On entry: m, the number of rows of the matrix A.
Constraint: M≥0.
5:   N – INTEGERInput
On entry: n, the number of columns of the matrix A.
Constraint: M≥N≥0.
6:   A LDA* – REAL (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array A must be at least max 1,N.
On entry: the m by n matrix A.
On exit: the matrix U containing the left singular vectors of A.
If JOBU='U' or 'C'
if INFO=0
rank A orthonormal columns of U are returned in the leading rank A columns of the array A. Here rank A≤N is the number of computed singular values of A that are above the safe range parameter, as returned by X02AMF. The singular vectors corresponding to underflowed or zero singular values are not computed. The value of rank A is returned by rounding WORK 2 to the nearest whole number. Also see the descriptions of SVA and WORK. The computed columns of U are mutually numerically orthogonal up to approximately tol=m×ε; or tol=ctol×ε (JOBU='C'), where ε is the machine precision and ctol is supplied on entry in WORK 1, see the description of JOBU.
If INFO>0
F08KJF (DGESVJ) did not converge in 30 iterations (sweeps). In this case, the computed columns of U may not be orthogonal up to tol. The output U (stored in A), Σ (given by the computed singular values in SVA) and V is still a decomposition of the input matrix A in the sense that the residual A-α×U×Σ×VT 2/A 2 is small, where α is the value returned in WORK 1.
If JOBU='N'
if INFO=0
Note that the left singular vectors are ‘for free’ in the one-sided Jacobi SVD algorithm. However, if only the singular values are needed, the level of numerical orthogonality of U is not an issue and iterations are stopped when the columns of the iterated matrix are numerically orthogonal up to approximately m×ε. Thus, on exit, A contains the columns of U scaled with the corresponding singular values.
If INFO>0
F08KJF (DGESVJ) did not converge in 30 iterations (sweeps).
7:   LDA – INTEGERInput
On entry: the first dimension of the array A as declared in the (sub)program from which F08KJF (DGESVJ) is called.
Constraint: LDA≥max 1,M.
8:   SVA N – REAL (KIND=nag_wp) arrayOutput
On exit: the, possibly scaled, singular values of A.
If INFO=0
The singular values of A are σi=α SVA i, for i=1,2,…,n, where α is the scale factor stored in WORK 1. Normally α=1, however, if some of the singular values of A might underflow or overflow, then α≠1 and the scale factor needs to be applied to obtain the singular values.
If INFO>0
F08KJF (DGESVJ) did not converge in 30 iterations and α×SVA may not be accurate.
9:   MV – INTEGERInput
On entry: if JOBV='A', the product of Jacobi rotations is applied to the first mv rows of V.
If JOBV≠'A', MV is ignored. See the description of JOBV.
10:   V LDV* – REAL (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array V must be at least max 1,N if JOBV='V' or 'A', and at least 1 otherwise.
On entry: if JOBV='A', V must contain an mv by n matrix to be premultiplied by the matrix V of right singular vectors.
On exit: the right singular vectors of A.
If JOBV='V', V contains the n by n matrix of the right singular vectors.
If JOBV='A', V contains the product of the computed right singular vector matrix and the initial matrix in the array V.
If JOBV='N', V is not referenced.
11:   LDV – INTEGERInput
On entry: the first dimension of the array V as declared in the (sub)program from which F08KJF (DGESVJ) is called.
Constraints:
  • if JOBV='V', LDV≥max 1,N;
  • if JOBV='A', LDV≥max 1,MV;
  • otherwise LDV≥1.
12:   WORK LWORK – REAL (KIND=nag_wp) arrayWorkspace
On entry: if JOBU='C', WORK 1=ctol, where ctol defines the threshold for convergence. The process stops if all columns of A are mutually orthogonal up to ctol×ε. It is required that ctol≥1, i.e., it is not possible to force the routine to obtain orthogonality below ε. ctol greater than 1/ε is meaningless, where ε is the machine precision.
On exit: contains information about the completed job.
WORK 1
the scaling factor, α, such that σi=α SVA i, for i=1,2,…,n are the computed singular values of A. (See description of SVA.)
WORK 2
nint WORK 2gives the number of the computed nonzero singular values.
WORK 3
nint WORK 3 gives the number of the computed singular values that are larger than the underflow threshold.
WORK 4
nint WORK 4 gives the number of iterations (sweeps of Jacobi rotations) needed for numerical convergence.
WORK 5
max i≠j cos A:,i,A:,j in the last iteration (sweep). This is useful information in cases when F08KJF (DGESVJ) did not converge, as it can be used to estimate whether the output is still useful and for subsequent analysis.
WORK 6
The largest absolute value over all sines of the Jacobi rotation angles in the last sweep. It can be useful for subsequent analysis.
Constraint: if JOBU='C', WORK 1≥1.0.
13:   LWORK – INTEGERInput
On entry: the dimension of the array WORK as declared in the (sub)program from which F08KJF (DGESVJ) is called.
Constraint: LWORK≥max 6,M+N.
14:   INFO – INTEGEROutput
On exit: INFO=0 unless the routine detects an error (see Section 6).

6 Error Indicators and Warnings

INFO<0
If INFO=-i, argument i had an illegal value. An explanatory message is output, and execution of the program is terminated.
INFO>0
F08KJF (DGESVJ) did not converge in the allowed number of iterations (30), but its output might still be useful.

7 Accuracy

The computed singular value decomposition is nearly the exact singular value decomposition for a nearby matrix A+E , where
E 2 = O ε A 2 ,
and ε is the machine precision. In addition, the computed singular vectors are nearly orthogonal to working precision. See Section 4.9 of Anderson et al. (1999) for further details.
See Section 6 of Drmac and Veselic (2008a) for a detailed discussion of the accuracy of the computed SVD.

8 Parallelism and Performance

F08KJF (DGESVJ) makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

This SVD algorithm is numerically superior to the bidiagonalization based QR algorithm implemented by F08KBF (DGESVD) and the divide and conquer algorithm implemented by F08KDF (DGESDD) algorithms and is considerably faster than previous implementations of the (equally accurate) Jacobi SVD method. Moreover, this algorithm can compute the SVD faster than F08KBF (DGESVD) and not much slower than F08KDF (DGESDD). See Section 3.3 of Drmac and Veselic (2008b) for the details.

10 Example

This example finds the singular values and left and right singular vectors of the 6 by 4 matrix
A = 2.27 -1.54 1.15 -1.94 0.28 -1.67 0.94 -0.78 -0.48 -3.09 0.99 -0.21 1.07 1.22 0.79 0.63 -2.35 2.93 -1.45 2.30 0.62 -7.39 1.03 -2.57 ,
together with approximate error bounds for the computed singular values and vectors.

10.1 Program Text

Program Text (f08kjfe.f90)

10.2 Program Data

Program Data (f08kjfe.d)

10.3 Program Results

Program Results (f08kjfe.r)

F08 Chapter Contents
F08 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


f08kmf (dgesvdx) : NAG Library, Mark 27

F08 (lapack) Chapter Contents
F08 (lapack) Chapter Introduction
NAG Library Manual

NAG Library Routine Document

f08kmf (dgesvdx)

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1
Purpose

f08kmf (dgesvdx) computes the singular value decomposition (SVD) of a real m by n matrix A, optionally computing the left and/or right singular vectors. All singular values or a selected set of singular values may be computed.

2
Specification

Fortran Interface
Subroutine f08kmf ( jobu, jobvt, range, m, n, a, lda, vl, vu, il, iu, ns, s, u, ldu, vt, ldvt, work, lwork, iwork, info)
Integer, Intent (In) | :: | m, n, lda, il, iu, ldu, ldvt, lwork
Integer, Intent (Out) | :: | ns, iwork(12*min(n,m)), info
Real (Kind=nag_wp), Intent (In) | :: | vl, vu
Real (Kind=nag_wp), Intent (Inout) | :: | a(lda,*), u(ldu,*), vt(ldvt,*)
Real (Kind=nag_wp), Intent (Out) | :: | s(min(m,n)), work(max(1,lwork))
Character (1), Intent (In) | :: | jobu, jobvt, range
C Header Interface
#include nagmk27.h
void f08km ( const char *jobu, const char *jobvt, const char *range, const Integer *m, const Integer *n, double a[], const Integer *lda, const double *vl, const double *vu, const Integer *il, const Integer *iu, Integer *ns, double s[], double u[], const Integer *ldu, double vt[], const Integer *ldvt, double work[], const Integer *lwork, Integer iwork[], Integer *info, const Charlen length_jobu, const Charlen length_jobvt, const Charlen length_range)
The routine may be called by its LAPACK name dgesvdx.

3
Description

The SVD is written as
A = UΣ VT ,
where Σ is an m by n matrix which is zero except for its min m,n diagonal elements, U is an m by m orthogonal matrix, and V is an n by n orthogonal matrix. The diagonal elements of Σ are the singular values of A; they are real and non-negative, and are returned in descending order. The first min m,n columns of U and V are the left and right singular vectors of A.
Note that the routine returns VT, not V.
Alternative to computing all singular values of A, a selected set can be computed. The set is either those singular values lying in a given interval, σ∈vl,vu, or those whose index (counting from largest to smallest in magnitude) lies in a given range 1≤il,…,iu≤n. In these cases, the corresponding left and right singular vectors can optionally be computed.

4
References

Anderson E, Bai Z, Bischof C, Blackford S, Demmel J, Dongarra J J, Du Croz J J, Greenbaum A, Hammarling S, McKenney A and Sorensen D (1999) LAPACK Users' Guide (3rd Edition) SIAM, Philadelphia http://www.netlib.org/lapack/lug
Golub G H and Van Loan C F (1996) Matrix Computations (3rd Edition) Johns Hopkins University Press, Baltimore

5
Arguments

1:   jobu – Character(1)Input
On entry: specifies options for computing all or part of the matrix U.
jobu='V'
The ns columns of U, as specified by range, are returned in array u.
jobu='N'
No columns of U (no left singular vectors) are computed.
Constraint: jobu='V' or 'N'.
2:   jobvt – Character(1)Input
On entry: specifies options for computing all or part of the matrix VT.
jobvt='V'
The ns rows of VT, as specified by range, are returned in the array vt.
jobvt='N'
No rows of VT (no right singular vectors) are computed.
Constraint: jobvt='V' or 'N'.
3:   range – Character(1)Input
On entry: indicates which singular values should be returned.
range='A'
All singular values will be found.
range='V'
All singular values in the half-open interval vl,vu will be found.
range='I'
The ilth through iuth singular values will be found.
Constraint: range='A', 'V' or 'I'.
4:   m – IntegerInput
On entry: m, the number of rows of the matrix A.
Constraint: m≥0.
5:   n – IntegerInput
On entry: n, the number of columns of the matrix A.
Constraint: n≥0.
6:   a lda* – Real (Kind=nag_wp) arrayInput/Output
Note: the second dimension of the array a must be at least max 1,n.
On entry: the m by n matrix A.
On exit: if jobu≠'N' and jobvt≠'N', the contents of a are destroyed.
7:   lda – IntegerInput
On entry: the first dimension of the array a as declared in the (sub)program from which f08kmf (dgesvdx) is called.
Constraint: lda≥max 1,m.
8:   vl – Real (Kind=nag_wp)Input
On entry: if range='V', the lower bounds of the interval to be searched for singular values.
If range='A' or 'I', vl is not referenced.
Constraint: if range='V', 0.0≤vl.
9:   vu – Real (Kind=nag_wp)Input
On entry: if range='V', the upper bounds of the interval to be searched for singular values.
If range='A' or 'I', vu is not referenced.
Constraint: if range='V', vl<vu.
10:   il – IntegerInput
11:   iu – IntegerInput
On entry: if range='I', the indices (in ascending order) of the smallest and largest singular values to be returned.
If range='A' or 'V', il and iu are not referenced.
Constraints:
  • if range='I' and min m,n=0, il=1 and iu=0;
  • if range='I' and min m,n>0, 1≤ il≤ iu≤ min m,n .
12:   ns – IntegerOutput
On exit: the total number of singular values found. 0≤ns≤min m,n.
If range='A', ns=min m,n.
If range='I', ns=iu-il+1.
If range='V' then the value of ns is not known in advance and so an upper limit should be used when specifying array dimensions, e.g., min m,n.
13:   s min m,n – Real (Kind=nag_wp) arrayOutput
On exit: the singular values of A, sorted so that s i≥s i+1.
14:   u ldu* – Real (Kind=nag_wp) arrayOutput
Note: the second dimension of the array u must be at least max 1,nsmax if jobu='V', and at least 1 otherwise.
Where nsmax is a value larger than the output value ns.
On exit: m by ns.
If jobu='V', u contains the first ns columns of U (the left singular vectors, stored column-wise).
If jobu='N', u is not referenced.
15:   ldu – IntegerInput
On entry: the first dimension of the array u as declared in the (sub)program from which f08kmf (dgesvdx) is called.
Constraints:
  • if jobu='V', ldu≥ max 1,m ;
  • otherwise ldu≥1.
16:   vt ldvt* – Real (Kind=nag_wp) arrayOutput
Note: the second dimension of the array vt must be at least max 1,n if jobvt='V', and at least 1 otherwise.
On exit: if jobvt='V', vt contains the first ns rows of VT (the right singular vectors, stored row-wise).
If jobvt='N', vt is not referenced.
17:   ldvt – IntegerInput
Note: if jobvt='V' and range='V' then the value of ns is not known in advance and so an upper limit should be used, e.g., min m,n.
On entry: the first dimension of the array vt as declared in the (sub)program from which f08kmf (dgesvdx) is called.
Constraints:
  • if jobvt='V', ldvt≥ max 1,ns ;
  • otherwise ldvt≥1.
18:   work max 1,lwork – Real (Kind=nag_wp) arrayWorkspace
On exit: if info=0, work 1 returns the optimal lwork.
If info>0, work 2:min m,n contains the unconverged superdiagonal elements of an upper bidiagonal matrix B whose diagonal is in s (not necessarily sorted). B satisfies A=UB VT, so it has the same singular values as A, and singular vectors related by U and VT.
19:   lwork – IntegerInput
On entry: the dimension of the array work as declared in the (sub)program from which f08kmf (dgesvdx) is called.
If lwork=-1, a workspace query is assumed; the routine only calculates the optimal size of the work array, returns this value as the first entry of the work array, and no error message related to lwork is issued.
Suggested value: for optimal performance, lwork should generally be larger. Consider increasing lwork by at least nb×min m,n , where nb is the optimal block size.
Constraint: lwork ≥ max 1, 3 × min m,n + max m,n , 5 × min m,n .
20:   iwork 12×min n,m – Integer arrayWorkspace
On exit:
  • if info=0, the first ns elements of iwork are zero;
  • if info>0, iwork contains the indices of the eigenvectors that failed to converge in f08jbf (dstevx) and f08mbf (dbdsvdx).
21:   info – IntegerOutput
On exit: info=0 unless the routine detects an error (see Section 6).

6
Error Indicators and Warnings

info<0
If info=-i, argument i had an illegal value. An explanatory message is output, and execution of the program is terminated.
info>0
If f08kmf (dgesvdx) did not converge, info specifies how many superdiagonals of an intermediate bidiagonal form did not converge to zero.

7
Accuracy

The computed singular value decomposition is nearly the exact singular value decomposition for a nearby matrix A+E , where
E 2 = O ε A 2 ,
and ε is the machine precision. In addition, the computed singular vectors are nearly orthogonal to working precision. See Section 4.9 of Anderson et al. (1999) for further details.

8
Parallelism and Performance

f08kmf (dgesvdx) is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
f08kmf (dgesvdx) makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9
Further Comments

The total number of floating-point operations is approximately proportional to m n 2 when m>n and m 2 n otherwise.
The singular values are returned in descending order.
The complex analogue of this routine is f08kzf (zgesvdx).

10
Example

This example finds the singular values and left and right singular vectors of the 6 by 4 matrix
A = 2.27 -1.54 1.15 -1.94 0.28 -1.67 0.94 -0.78 -0.48 -3.09 0.99 -0.21 1.07 1.22 0.79 0.63 -2.35 2.93 -1.45 2.30 0.62 -7.39 1.03 -2.57 ,
together with approximate error bounds for the computed singular values and vectors.

10.1
Program Text

Program Text (f08kmfe.f90)

10.2
Program Data

Program Data (f08kmfe.d)

10.3
Program Results

Program Results (f08kmfe.r)

F08 (lapack) Chapter Contents
F08 (lapack) Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2017


F08KNF (ZGELSS) : NAG Library, Mark 26

F08 Chapter Contents
F08 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F08KNF (ZGELSS)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F08KNF (ZGELSS) computes the minimum norm solution to a complex linear least squares problem
minx b-Ax 2 .

2 Specification

SUBROUTINE F08KNF ( M, N, NRHS, A, LDA, B, LDB, S, RCOND, RANK, WORK, LWORK, RWORK, INFO)
INTEGER | M, N, NRHS, LDA, LDB, RANK, LWORK, INFO
REAL (KIND=nag_wp) | S(*), RCOND, RWORK(*)
COMPLEX (KIND=nag_wp) | A(LDA,*), B(LDB,*), WORK(max(1,LWORK))
The routine may be called by its LAPACK name zgelss.

3 Description

F08KNF (ZGELSS) uses the singular value decomposition (SVD) of A, where A is an m by n matrix which may be rank-deficient.
Several right-hand side vectors b and solution vectors x can be handled in a single call; they are stored as the columns of the m by r right-hand side matrix B and the n by r solution matrix X.
The effective rank of A is determined by treating as zero those singular values which are less than RCOND times the largest singular value.

4 References

Anderson E, Bai Z, Bischof C, Blackford S, Demmel J, Dongarra J J, Du Croz J J, Greenbaum A, Hammarling S, McKenney A and Sorensen D (1999) LAPACK Users' Guide (3rd Edition) SIAM, Philadelphia http://www.netlib.org/lapack/lug
Golub G H and Van Loan C F (1996) Matrix Computations (3rd Edition) Johns Hopkins University Press, Baltimore

5 Arguments

1:   M – INTEGERInput
On entry: m, the number of rows of the matrix A.
Constraint: M≥0.
2:   N – INTEGERInput
On entry: n, the number of columns of the matrix A.
Constraint: N≥0.
3:   NRHS – INTEGERInput
On entry: r, the number of right-hand sides, i.e., the number of columns of the matrices B and X.
Constraint: NRHS≥0.
4:   A LDA* – COMPLEX (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array A must be at least max 1,N.
On entry: the m by n matrix A.
On exit: the first min m,n rows of A are overwritten with its right singular vectors, stored row-wise.
5:   LDA – INTEGERInput
On entry: the first dimension of the array A as declared in the (sub)program from which F08KNF (ZGELSS) is called.
Constraint: LDA≥max 1,M.
6:   B LDB* – COMPLEX (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array B must be at least max 1,NRHS.
On entry: the m by r right-hand side matrix B.
On exit: B is overwritten by the n by r solution matrix X. If m≥n and RANK=n, the residual sum of squares for the solution in the ith column is given by the sum of squares of the modulus of elements n+1,…,m in that column.
7:   LDB – INTEGERInput
On entry: the first dimension of the array B as declared in the (sub)program from which F08KNF (ZGELSS) is called.
Constraint: LDB≥max 1,M,N.
8:   S* – REAL (KIND=nag_wp) arrayOutput
Note: the dimension of the array S must be at least max 1,min M,N .
On exit: the singular values of A in decreasing order.
9:   RCOND – REAL (KIND=nag_wp)Input
On entry: used to determine the effective rank of A. Singular values S i≤RCOND×S 1 are treated as zero. If RCOND<0, machine precision is used instead.
10:   RANK – INTEGEROutput
On exit: the effective rank of A, i.e., the number of singular values which are greater than RCOND×S 1.
11:   WORK max 1,LWORK – COMPLEX (KIND=nag_wp) arrayWorkspace
On exit: if INFO=0, the real part of WORK 1 contains the minimum value of LWORK required for optimal performance.
12:   LWORK – INTEGERInput
On entry: the dimension of the array WORK as declared in the (sub)program from which F08KNF (ZGELSS) is called.
If LWORK=-1, a workspace query is assumed; the routine only calculates the optimal size of the WORK array, returns this value as the first entry of the WORK array, and no error message related to LWORK is issued.
Suggested value: for optimal performance, LWORK should generally be larger. Consider increasing LWORK by at least nb×min M,N , where nb is the optimal block size.
Constraint: LWORK≥1 and LWORK≥2×min M,N+max M,N,NRHS.
13:   RWORK* – REAL (KIND=nag_wp) arrayWorkspace
Note: the dimension of the array RWORK must be at least max 1, 5× min M,N .
14:   INFO – INTEGEROutput
On exit: INFO=0 unless the routine detects an error (see Section 6).

6 Error Indicators and Warnings

INFO<0
If INFO=-i, argument i had an illegal value. An explanatory message is output, and execution of the program is terminated.
INFO>0
The algorithm for computing the SVD failed to converge; if INFO=i, i off-diagonal elements of an intermediate bidiagonal form did not converge to zero.

7 Accuracy

See Section 4.5 of Anderson et al. (1999) for details.

8 Parallelism and Performance

F08KNF (ZGELSS) is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
F08KNF (ZGELSS) makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The real analogue of this routine is F08KAF (DGELSS).

10 Example

This example solves the linear least squares problem
minx b-Ax 2
for the solution, x, of minimum norm, where
A = 0.47-0.34 i -0.40+0.54 i 0.60+0.01 i 0.80-1.02 i -0.32-0.23 i -0.05+0.20 i -0.26-0.44 i -0.43+0.17 i 0.35-0.60 i -0.52-0.34 i 0.87-0.11 i -0.34-0.09 i 0.89+0.71 i -0.45-0.45 i -0.02-0.57 i 1.14-0.78 i -0.19+0.06 i 0.11-0.85 i 1.44+0.80 i 0.07+1.14 i
and
b = -1.08-2.59 i -2.61-1.49 i 3.13-3.61 i 7.33-8.01 i 9.12+7.63 i .
A tolerance of 0.01 is used to determine the effective rank of A.
Note that the block size (NB) of 64 assumed in this example is not realistic for such a small problem, but should be suitable for large problems.

10.1 Program Text

Program Text (f08knfe.f90)

10.2 Program Data

Program Data (f08knfe.d)

10.3 Program Results

Program Results (f08knfe.r)

F08 Chapter Contents
F08 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F08KPF (ZGESVD) : NAG Library, Mark 26

F08 Chapter Contents
F08 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F08KPF (ZGESVD)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F08KPF (ZGESVD) computes the singular value decomposition (SVD) of a complex m by n matrix A, optionally computing the left and/or right singular vectors.

2 Specification

SUBROUTINE F08KPF ( JOBU, JOBVT, M, N, A, LDA, S, U, LDU, VT, LDVT, WORK, LWORK, RWORK, INFO)
INTEGER | M, N, LDA, LDU, LDVT, LWORK, INFO
REAL (KIND=nag_wp) | S(*), RWORK(*)
COMPLEX (KIND=nag_wp) | A(LDA,*), U(LDU,*), VT(LDVT,*), WORK(max(1,LWORK))
CHARACTER(1) | JOBU, JOBVT
The routine may be called by its LAPACK name zgesvd.

3 Description

The SVD is written as
A = UΣ VH ,
where Σ is an m by n matrix which is zero except for its min m,n diagonal elements, U is an m by m unitary matrix, and V is an n by n unitary matrix. The diagonal elements of Σ are the singular values of A; they are real and non-negative, and are returned in descending order. The first min m,n columns of U and V are the left and right singular vectors of A.
Note that the routine returns VH, not V.

4 References

Anderson E, Bai Z, Bischof C, Blackford S, Demmel J, Dongarra J J, Du Croz J J, Greenbaum A, Hammarling S, McKenney A and Sorensen D (1999) LAPACK Users' Guide (3rd Edition) SIAM, Philadelphia http://www.netlib.org/lapack/lug
Golub G H and Van Loan C F (1996) Matrix Computations (3rd Edition) Johns Hopkins University Press, Baltimore

5 Arguments

1:   JOBU – CHARACTER(1)Input
On entry: specifies options for computing all or part of the matrix U.
JOBU='A'
All m columns of U are returned in array U.
JOBU='S'
The first min m,n columns of U (the left singular vectors) are returned in the array U.
JOBU='O'
The first min m,n columns of U (the left singular vectors) are overwritten on the array A.
JOBU='N'
No columns of U (no left singular vectors) are computed.
Constraint: JOBU='A', 'S', 'O' or 'N'.
2:   JOBVT – CHARACTER(1)Input
On entry: specifies options for computing all or part of the matrix VH.
JOBVT='A'
All n rows of VH are returned in the array VT.
JOBVT='S'
The first min m,n rows of VH (the right singular vectors) are returned in the array VT.
JOBVT='O'
The first min m,n rows of VH (the right singular vectors) are overwritten on the array A.
JOBVT='N'
No rows of VH (no right singular vectors) are computed.
Constraints:
  • JOBVT='A', 'S', 'O' or 'N';
  • JOBVT and JOBU cannot both be 'O';
  • if JOBU='O', JOBVT≠'O'.
3:   M – INTEGERInput
On entry: m, the number of rows of the matrix A.
Constraint: M≥0.
4:   N – INTEGERInput
On entry: n, the number of columns of the matrix A.
Constraint: N≥0.
5:   A LDA* – COMPLEX (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array A must be at least max 1,N.
On entry: the m by n matrix A.
On exit: if JOBU='O', A is overwritten with the first min m,n columns of U (the left singular vectors, stored column-wise).
If JOBVT='O', A is overwritten with the first min m,n rows of VH (the right singular vectors, stored row-wise).
If JOBU≠'O' and JOBVT≠'O', the contents of A are destroyed.
6:   LDA – INTEGERInput
On entry: the first dimension of the array A as declared in the (sub)program from which F08KPF (ZGESVD) is called.
Constraint: LDA≥max 1,M.
7:   S* – REAL (KIND=nag_wp) arrayOutput
Note: the dimension of the array S must be at least max 1,min M,N .
On exit: the singular values of A, sorted so that S i≥S i+1.
8:   U LDU* – COMPLEX (KIND=nag_wp) arrayOutput
Note: the second dimension of the array U must be at least max 1,M if JOBU='A', max 1,min M,N if JOBU='S', and at least 1 otherwise.
On exit: if JOBU='A', U contains the m by m unitary matrix U.
If JOBU='S', U contains the first min m,n columns of U (the left singular vectors, stored column-wise).
If JOBU='N' or 'O', U is not referenced.
9:   LDU – INTEGERInput
On entry: the first dimension of the array U as declared in the (sub)program from which F08KPF (ZGESVD) is called.
Constraints:
  • if JOBU='A' or 'S', LDU≥ max 1,M ;
  • otherwise LDU≥1.
10:   VT LDVT* – COMPLEX (KIND=nag_wp) arrayOutput
Note: the second dimension of the array VT must be at least max 1,N if JOBVT='A' or 'S', and at least 1 otherwise.
On exit: if JOBVT='A', VT contains the n by n unitary matrix VH.
If JOBVT='S', VT contains the first min m,n rows of VH (the right singular vectors, stored row-wise).
If JOBVT='N' or 'O', VT is not referenced.
11:   LDVT – INTEGERInput
On entry: the first dimension of the array VT as declared in the (sub)program from which F08KPF (ZGESVD) is called.
Constraints:
  • if JOBVT='A', LDVT≥ max 1,N ;
  • if JOBVT='S', LDVT≥ max 1,min M,N ;
  • otherwise LDVT≥1.
12:   WORK max 1,LWORK – COMPLEX (KIND=nag_wp) arrayWorkspace
On exit: if INFO=0, the real part of WORK 1 contains the minimum value of LWORK required for optimal performance.
13:   LWORK – INTEGERInput
On entry: the dimension of the array WORK as declared in the (sub)program from which F08KPF (ZGESVD) is called.
If LWORK=-1, a workspace query is assumed; the routine only calculates the optimal size of the WORK array, returns this value as the first entry of the WORK array, and no error message related to LWORK is issued.
Suggested value: for optimal performance, LWORK should generally be larger. Consider increasing LWORK by at least nb×min M,N , where nb is the optimal block size.
Constraint: LWORK ≥ max 1, 2 × min M,N + max M,N .
14:   RWORK* – REAL (KIND=nag_wp) arrayWorkspace
Note: the dimension of the array RWORK must be at least max 1, 5×min M,N .
On exit: if INFO>0, RWORK 1:min M,N-1 contains the unconverged superdiagonal elements of an upper bidiagonal matrix B whose diagonal is in S (not necessarily sorted). B satisfies A=UB VH, so it has the same singular values as A, and singular vectors related by U and VH.
15:   INFO – INTEGEROutput
On exit: INFO=0 unless the routine detects an error (see Section 6).

6 Error Indicators and Warnings

INFO<0
If INFO=-i, argument i had an illegal value. An explanatory message is output, and execution of the program is terminated.
INFO>0
If F08KPF (ZGESVD) did not converge, INFO specifies how many superdiagonals of an intermediate bidiagonal form did not converge to zero. See the description of RWORK above for details.

7 Accuracy

The computed singular value decomposition is nearly the exact singular value decomposition for a nearby matrix A+E , where
E 2 = O ε A 2 ,
and ε is the machine precision. In addition, the computed singular vectors are nearly orthogonal to working precision. See Section 4.9 of Anderson et al. (1999) for further details.

8 Parallelism and Performance

F08KPF (ZGESVD) is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
F08KPF (ZGESVD) makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The total number of floating-point operations is approximately proportional to m n 2 when m>n and m 2 n otherwise.
The singular values are returned in descending order.
The real analogue of this routine is F08KBF (DGESVD).

10 Example

This example finds the singular values and left and right singular vectors of the 6 by 4 matrix
A = 0.96-0.81 i -0.03+0.96 i -0.91+2.06 i -0.05+0.41 i -0.98+1.98 i -1.20+0.19 i -0.66+0.42 i -0.81+0.56 i 0.62-0.46 i 1.01+0.02 i 0.63-0.17 i -1.11+0.60 i -0.37+0.38 i 0.19-0.54 i -0.98-0.36 i 0.22-0.20 i 0.83+0.51 i 0.20+0.01 i -0.17-0.46 i 1.47+1.59 i 1.08-0.28 i 0.20-0.12 i -0.07+1.23 i 0.26+0.26 i ,
together with approximate error bounds for the computed singular values and vectors.
The example program for F08KRF (ZGESDD) illustrates finding a singular value decomposition for the case m≤n.

10.1 Program Text

Program Text (f08kpfe.f90)

10.2 Program Data

Program Data (f08kpfe.d)

10.3 Program Results

Program Results (f08kpfe.r)

F08 Chapter Contents
F08 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F08KQF (ZGELSD) : NAG Library, Mark 26

F08 Chapter Contents
F08 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F08KQF (ZGELSD)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F08KQF (ZGELSD) computes the minimum norm solution to a complex linear least squares problem
minx b-Ax 2 .

2 Specification

SUBROUTINE F08KQF ( M, N, NRHS, A, LDA, B, LDB, S, RCOND, RANK, WORK, LWORK, RWORK, IWORK, INFO)
INTEGER | M, N, NRHS, LDA, LDB, RANK, LWORK, IWORK(*), INFO
REAL (KIND=nag_wp) | S(*), RCOND, RWORK(*)
COMPLEX (KIND=nag_wp) | A(LDA,*), B(LDB,*), WORK(max(1,LWORK))
The routine may be called by its LAPACK name zgelsd.

3 Description

F08KQF (ZGELSD) uses the singular value decomposition (SVD) of A, where A is a complex m by n matrix which may be rank-deficient.
Several right-hand side vectors b and solution vectors x can be handled in a single call; they are stored as the columns of the m by r right-hand side matrix B and the n by r solution matrix X.
The problem is solved in three steps:
1. | reduce the coefficient matrix A to bidiagonal form with Householder transformations, reducing the original problem into a ‘bidiagonal least squares problem’ (BLS);
2. | solve the BLS using a divide-and-conquer approach;
3. | apply back all the Householder transformations to solve the original least squares problem.
The effective rank of A is determined by treating as zero those singular values which are less than RCOND times the largest singular value.

4 References

Anderson E, Bai Z, Bischof C, Blackford S, Demmel J, Dongarra J J, Du Croz J J, Greenbaum A, Hammarling S, McKenney A and Sorensen D (1999) LAPACK Users' Guide (3rd Edition) SIAM, Philadelphia http://www.netlib.org/lapack/lug
Golub G H and Van Loan C F (1996) Matrix Computations (3rd Edition) Johns Hopkins University Press, Baltimore

5 Arguments

1:   M – INTEGERInput
On entry: m, the number of rows of the matrix A.
Constraint: M≥0.
2:   N – INTEGERInput
On entry: n, the number of columns of the matrix A.
Constraint: N≥0.
3:   NRHS – INTEGERInput
On entry: r, the number of right-hand sides, i.e., the number of columns of the matrices B and X.
Constraint: NRHS≥0.
4:   A LDA* – COMPLEX (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array A must be at least max 1,N.
On entry: the m by n coefficient matrix A.
On exit: the contents of A are destroyed.
5:   LDA – INTEGERInput
On entry: the first dimension of the array A as declared in the (sub)program from which F08KQF (ZGELSD) is called.
Constraint: LDA≥max 1,M.
6:   B LDB* – COMPLEX (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array B must be at least max 1,NRHS.
On entry: the m by r right-hand side matrix B.
On exit: B is overwritten by the n by r solution matrix X. If m≥n and RANK=n, the residual sum of squares for the solution in the ith column is given by the sum of squares of the modulus of elements n+1,…,m in that column.
7:   LDB – INTEGERInput
On entry: the first dimension of the array B as declared in the (sub)program from which F08KQF (ZGELSD) is called.
Constraint: LDB≥max 1,M,N.
8:   S* – REAL (KIND=nag_wp) arrayOutput
Note: the dimension of the array S must be at least max 1,min M,N .
On exit: the singular values of A in decreasing order.
9:   RCOND – REAL (KIND=nag_wp)Input
On entry: used to determine the effective rank of A. Singular values S i≤RCOND×S 1 are treated as zero. If RCOND<0, machine precision is used instead.
10:   RANK – INTEGEROutput
On exit: the effective rank of A, i.e., the number of singular values which are greater than RCOND×S 1.
11:   WORK max 1,LWORK – COMPLEX (KIND=nag_wp) arrayWorkspace
On exit: if INFO=0, the real part of WORK 1 contains the minimum value of LWORK required for optimal performance.
12:   LWORK – INTEGERInput
On entry: the dimension of the array WORK as declared in the (sub)program from which F08KQF (ZGELSD) is called.
The exact minimum amount of workspace needed depends on M, N and NRHS. As long as LWORK is at least
max 1,M+N+r,2 r+r×NRHS ,
where r=min M,N, the code will execute correctly.
If LWORK=-1, a workspace query is assumed; the routine only calculates the optimal size of the WORK array and the minimum size of the IWORK array, and returns these values as the first entries of the WORK and IWORK arrays, and no error message related to LWORK is issued.
Suggested value: for optimal performance, LWORK should generally be larger than the required minimum. Consider increasing LWORK by at least nb×min M,N , where nb is the optimal block size.
Constraint: LWORK must be at least max 1,M+N+r,2 r+r×NRHS or LWORK=-1.
13:   RWORK* – REAL (KIND=nag_wp) arrayWorkspace
Note: the dimension of the array RWORK must be at least max 1,lrwork, where lrwork is at least
10× N+2× N× smlsiz+8× N× nlvl+3× smlsiz× NRHS+smlsiz+1 2 ,   if ​ M≥N
or
10× M+2× M× smlsiz+8× M× nlvl+3× smlsiz× NRHS+smlsiz+1 2 ,   if ​ M<N
where smlsiz is equal to the maximum size of the subproblems at the bottom of the computation tree (usually about 25), and nlvl = max 0, int log 2 min M,N / smlsiz+1 +1 , the code will execute correctly.
On exit: if INFO=0, RWORK 1 contains the required minimal size of lrwork.
14:   IWORK* – INTEGER arrayWorkspace
Note: the dimension of the array IWORK must be at least max 1,liwork, where liwork is at least max 1,3×min M,N×nlvl+11×min M,N.
On exit: if INFO=0, IWORK 1 returns the minimum liwork.
15:   INFO – INTEGEROutput
On exit: INFO=0 unless the routine detects an error (see Section 6).

6 Error Indicators and Warnings

INFO<0
If INFO=-i, argument i had an illegal value. An explanatory message is output, and execution of the program is terminated.
INFO>0
The algorithm for computing the SVD failed to converge; if INFO=i, i off-diagonal elements of an intermediate bidiagonal form did not converge to zero.

7 Accuracy

See Section 4.5 of Anderson et al. (1999) for details.

8 Parallelism and Performance

F08KQF (ZGELSD) is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
F08KQF (ZGELSD) makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The real analogue of this routine is F08KCF (DGELSD).

10 Example

This example solves the linear least squares problem
minx b-Ax 2
for the solution, x, of minimum norm, where
A = 0.47-0.34 i -0.32-0.23 i 0.35-0.60 i 0.89+0.71 i -0.19+0.06 i -0.40+0.54 i -0.05+0.20 i -0.52-0.34 i -0.45-0.45 i 0.11-0.85 i 0.60+0.01 i -0.26-0.44 i 0.87-0.11 i -0.02-0.57 i 1.44+0.80 i 0.80-1.02 i -0.43+0.17 i -0.34-0.09 i 1.14-0.78 i 0.07+1.14 i
and
b = 2.15-0.20 i -2.24+1.82 i 4.45-4.28 i 5.70-6.25 i .
A tolerance of 0.01 is used to determine the effective rank of A.
Note that the block size (NB) of 64 assumed in this example is not realistic for such a small problem, but should be suitable for large problems.

10.1 Program Text

Program Text (f08kqfe.f90)

10.2 Program Data

Program Data (f08kqfe.d)

10.3 Program Results

Program Results (f08kqfe.r)

F08 Chapter Contents
F08 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F08KRF (ZGESDD) : NAG Library, Mark 26

F08 Chapter Contents
F08 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F08KRF (ZGESDD)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F08KRF (ZGESDD) computes the singular value decomposition (SVD) of a complex m by n matrix A, optionally computing the left and/or right singular vectors, by using a divide-and-conquer method.

2 Specification

SUBROUTINE F08KRF ( JOBZ, M, N, A, LDA, S, U, LDU, VT, LDVT, WORK, LWORK, RWORK, IWORK, INFO)
INTEGER | M, N, LDA, LDU, LDVT, LWORK, IWORK(8*min(M,N)), INFO
REAL (KIND=nag_wp) | S(min(M,N)), RWORK(*)
COMPLEX (KIND=nag_wp) | A(LDA,*), U(LDU,*), VT(LDVT,*), WORK(max(1,LWORK))
CHARACTER(1) | JOBZ
The routine may be called by its LAPACK name zgesdd.

3 Description

The SVD is written as
A = UΣ VH ,
where Σ is an m by n matrix which is zero except for its min m,n diagonal elements, U is an m by m unitary matrix, and V is an n by n unitary matrix. The diagonal elements of Σ are the singular values of A; they are real and non-negative, and are returned in descending order. The first min m,n columns of U and V are the left and right singular vectors of A.
Note that the routine returns VH, not V.

4 References

Anderson E, Bai Z, Bischof C, Blackford S, Demmel J, Dongarra J J, Du Croz J J, Greenbaum A, Hammarling S, McKenney A and Sorensen D (1999) LAPACK Users' Guide (3rd Edition) SIAM, Philadelphia http://www.netlib.org/lapack/lug
Golub G H and Van Loan C F (1996) Matrix Computations (3rd Edition) Johns Hopkins University Press, Baltimore

5 Arguments

1:   JOBZ – CHARACTER(1)Input
On entry: specifies options for computing all or part of the matrix U.
JOBZ='A'
All m columns of U and all n rows of VH are returned in the arrays U and VT.
JOBZ='S'
The first min m,n columns of U and the first min m,n rows of VH are returned in the arrays U and VT.
JOBZ='O'
If M≥N, the first n columns of U are overwritten on the array A and all rows of VH are returned in the array VT. Otherwise, all columns of U are returned in the array U and the first m rows of VH are overwritten in the array VT.
JOBZ='N'
No columns of U or rows of VH are computed.
Constraint: JOBZ='A', 'S', 'O' or 'N'.
2:   M – INTEGERInput
On entry: m, the number of rows of the matrix A.
Constraint: M≥0.
3:   N – INTEGERInput
On entry: n, the number of columns of the matrix A.
Constraint: N≥0.
4:   A LDA* – COMPLEX (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array A must be at least max 1,N.
On entry: the m by n matrix A.
On exit: if JOBZ='O', A is overwritten with the first n columns of U (the left singular vectors, stored column-wise) if M≥N; A is overwritten with the first m rows of VH (the right singular vectors, stored row-wise) otherwise.
If JOBZ≠'O', the contents of A are destroyed.
5:   LDA – INTEGERInput
On entry: the first dimension of the array A as declared in the (sub)program from which F08KRF (ZGESDD) is called.
Constraint: LDA≥max 1,M.
6:   S min M,N – REAL (KIND=nag_wp) arrayOutput
On exit: the singular values of A, sorted so that S i≥S i+1.
7:   U LDU* – COMPLEX (KIND=nag_wp) arrayOutput
Note: the second dimension of the array U must be at least max 1,M if JOBZ='A' or JOBZ='O' and M<N, max 1,min M,N if JOBZ='S', and at least 1 otherwise.
On exit:
If JOBZ='A' or JOBZ='O' and M<N, U contains the m by m unitary matrix U.
If JOBZ='S', U contains the first min m,n columns of U (the left singular vectors, stored column-wise).
If JOBZ='O' and M≥N, or JOBZ='N', U is not referenced.
8:   LDU – INTEGERInput
On entry: the first dimension of the array U as declared in the (sub)program from which F08KRF (ZGESDD) is called.
Constraints:
  • if JOBZ='S' or 'A' or JOBZ='O' and M<N, LDU≥ max 1,M ;
  • otherwise LDU≥1.
9:   VT LDVT* – COMPLEX (KIND=nag_wp) arrayOutput
Note: the second dimension of the array VT must be at least max 1,N if JOBZ='A' or 'S' or JOBZ='O' and M≥N, and at least 1 otherwise.
On exit: if JOBZ='A' or JOBZ='O' and M≥N, VT contains the n by n unitary matrix VH.
If JOBZ='S', VT contains the first min m,n rows of VH (the right singular vectors, stored row-wise).
If JOBZ='O' and M<N, or JOBZ='N', VT is not referenced.
10:   LDVT – INTEGERInput
On entry: the first dimension of the array VT as declared in the (sub)program from which F08KRF (ZGESDD) is called.
Constraints:
  • if JOBZ='A' or JOBZ='O' and M≥N, LDVT≥ max 1,N ;
  • if JOBZ='S', LDVT≥ max 1,min M,N ;
  • otherwise LDVT≥1.
11:   WORK max 1,LWORK – COMPLEX (KIND=nag_wp) arrayWorkspace
On exit: if INFO=0, the real part of WORK 1 contains the minimum value of LWORK required for optimal performance.
12:   LWORK – INTEGERInput
On entry: the dimension of the array WORK as declared in the (sub)program from which F08KRF (ZGESDD) is called.
If LWORK=-1, a workspace query is assumed; the routine only calculates the optimal size of the WORK array, returns this value as the first entry of the WORK array, and no error message related to LWORK is issued.
Suggested value: for optimal performance, LWORK should generally be larger. Consider increasing LWORK by at least nb×min M,N , where nb is the optimal block size.
Constraints:
  • if JOBZ='N', LWORK≥2× min M,N+ max 1,M,N ;
  • if JOBZ='O', LWORK≥2× min M,N× min M,N+2× min M,N+ max 1,M,N ;
  • if JOBZ='S' or 'A', LWORK≥ min M,N× min M,N+2× min M,N+ max 1,M,N;
  • otherwise LWORK≥1.
13:   RWORK* – REAL (KIND=nag_wp) arrayWorkspace
Note: the dimension of the array RWORK must be at least max 1,7×min M,N if JOBZ='N', and at least max 1, min M,N× max 5× min M,N+7 , 2× max M,N+ 2× min M,N+ 1 otherwise.
14:   IWORK 8×min M,N – INTEGER arrayWorkspace
15:   INFO – INTEGEROutput
On exit: INFO=0 unless the routine detects an error (see Section 6).

6 Error Indicators and Warnings

INFO<0
If INFO=-i, argument i had an illegal value. An explanatory message is output, and execution of the program is terminated.
INFO>0
F08KRF (ZGESDD) did not converge, the updating process failed.

7 Accuracy

The computed singular value decomposition is nearly the exact singular value decomposition for a nearby matrix A+E , where
E 2 = O ε A 2 ,
and ε is the machine precision. In addition, the computed singular vectors are nearly orthogonal to working precision. See Section 4.9 of Anderson et al. (1999) for further details.

8 Parallelism and Performance

F08KRF (ZGESDD) is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
F08KRF (ZGESDD) makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The total number of floating-point operations is approximately proportional to m n 2 when m>n and m 2 n otherwise.
The singular values are returned in descending order.
The real analogue of this routine is F08KDF (DGESDD).

10 Example

This example finds the singular values and left and right singular vectors of the 4 by 6 matrix
A = 0.96+0.81 i -0.98-1.98 i 0.62+0.46 i -0.37-0.38 i 0.83-0.51 i 1.08+0.28 i -0.03-0.96 i -1.20-0.19 i 1.01-0.02 i 0.19+0.54 i 0.20-0.01 i 0.20+0.12 i -0.91-2.06 i -0.66-0.42 i 0.63+0.17 i -0.98+0.36 i -0.17+0.46 i -0.07-1.23 i -0.05-0.41 i -0.81-0.56 i -1.11-0.60 i 0.22+0.20 i 1.47-1.59 i 0.26-0.26 i ,
together with approximate error bounds for the computed singular values and vectors.
The example program for F08KPF (ZGESVD) illustrates finding a singular value decomposition for the case m≥n.

10.1 Program Text

Program Text (f08krfe.f90)

10.2 Program Data

Program Data (f08krfe.d)

10.3 Program Results

Program Results (f08krfe.r)

F08 Chapter Contents
F08 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F08KSF (ZGEBRD) : NAG Library, Mark 26

F08 Chapter Contents
F08 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F08KSF (ZGEBRD)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F08KSF (ZGEBRD) reduces a complex m by n matrix to bidiagonal form.

2 Specification

SUBROUTINE F08KSF ( M, N, A, LDA, D, E, TAUQ, TAUP, WORK, LWORK, INFO)
INTEGER | M, N, LDA, LWORK, INFO
REAL (KIND=nag_wp) | D(*), E(*)
COMPLEX (KIND=nag_wp) | A(LDA,*), TAUQ(*), TAUP(*), WORK(max(1,LWORK))
The routine may be called by its LAPACK name zgebrd.

3 Description

F08KSF (ZGEBRD) reduces a complex m by n matrix A to real bidiagonal form B by a unitary transformation: A=QB PH, where Q and PH are unitary matrices of order m and n respectively.
If m≥n, the reduction is given by:
A =Q B 1 0 PH = Q 1 B 1 PH ,
where B 1 is a real n by n upper bidiagonal matrix and Q 1 consists of the first n columns of Q.
If m<n, the reduction is given by
A =Q B 1 0 PH = Q B 1 P 1 H ,
where B 1 is a real m by m lower bidiagonal matrix and P 1 H consists of the first m rows of PH.
The unitary matrices Q and P are not formed explicitly but are represented as products of elementary reflectors (see the F08 Chapter Introduction for details). Routines are provided to work with Q and P in this representation (see Section 9).

4 References

Golub G H and Van Loan C F (1996) Matrix Computations (3rd Edition) Johns Hopkins University Press, Baltimore

5 Arguments

1:   M – INTEGERInput
On entry: m, the number of rows of the matrix A.
Constraint: M≥0.
2:   N – INTEGERInput
On entry: n, the number of columns of the matrix A.
Constraint: N≥0.
3:   A LDA* – COMPLEX (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array A must be at least max 1,N.
On entry: the m by n matrix A.
On exit: if m≥n, the diagonal and first superdiagonal are overwritten by the upper bidiagonal matrix B, elements below the diagonal are overwritten by details of the unitary matrix Q and elements above the first superdiagonal are overwritten by details of the unitary matrix P.
If m<n, the diagonal and first subdiagonal are overwritten by the lower bidiagonal matrix B, elements below the first subdiagonal are overwritten by details of the unitary matrix Q and elements above the diagonal are overwritten by details of the unitary matrix P.
4:   LDA – INTEGERInput
On entry: the first dimension of the array A as declared in the (sub)program from which F08KSF (ZGEBRD) is called.
Constraint: LDA≥max 1,M.
5:   D* – REAL (KIND=nag_wp) arrayOutput
Note: the dimension of the array D must be at least max 1,min M,N.
On exit: the diagonal elements of the bidiagonal matrix B.
6:   E* – REAL (KIND=nag_wp) arrayOutput
Note: the dimension of the array E must be at least max 1,min M,N-1.
On exit: the off-diagonal elements of the bidiagonal matrix B.
7:   TAUQ* – COMPLEX (KIND=nag_wp) arrayOutput
Note: the dimension of the array TAUQ must be at least max 1,min M,N.
On exit: further details of the unitary matrix Q.
8:   TAUP* – COMPLEX (KIND=nag_wp) arrayOutput
Note: the dimension of the array TAUP must be at least max 1,min M,N.
On exit: further details of the unitary matrix P.
9:   WORK max 1,LWORK – COMPLEX (KIND=nag_wp) arrayWorkspace
On exit: if INFO=0, the real part of WORK 1 contains the minimum value of LWORK required for optimal performance.
10:   LWORK – INTEGERInput
On entry: the dimension of the array WORK as declared in the (sub)program from which F08KSF (ZGEBRD) is called.
If LWORK=-1, a workspace query is assumed; the routine only calculates the optimal size of the WORK array, returns this value as the first entry of the WORK array, and no error message related to LWORK is issued.
Suggested value: for optimal performance, LWORK≥M+N×nb, where nb is the optimal block size.
Constraint: LWORK≥max 1,M,N or LWORK=-1.
11:   INFO – INTEGEROutput
On exit: INFO=0 unless the routine detects an error (see Section 6).

6 Error Indicators and Warnings

INFO<0
If INFO=-i, argument i had an illegal value. An explanatory message is output, and execution of the program is terminated.

7 Accuracy

The computed bidiagonal form B satisfies QB PH=A+E, where
E 2 ≤ c n ε A 2 ,
c n is a modestly increasing function of n, and ε is the machine precision.
The elements of B themselves may be sensitive to small perturbations in A or to rounding errors in the computation, but this does not affect the stability of the singular values and vectors.

8 Parallelism and Performance

F08KSF (ZGEBRD) is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
F08KSF (ZGEBRD) makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The total number of real floating-point operations is approximately 16 n 2 3 m-n/3 if m≥n or 16 m 2 3 n-m/3 if m<n.
If m≫n, it can be more efficient to first call F08ASF (ZGEQRF) to perform a QR factorization of A, and then to call F08KSF (ZGEBRD) to reduce the factor R to bidiagonal form. This requires approximately 8 n 2 m+n floating-point operations.
If m≪n, it can be more efficient to first call F08AVF (ZGELQF) to perform an LQ factorization of A, and then to call F08KSF (ZGEBRD) to reduce the factor L to bidiagonal form. This requires approximately 8 m 2 m+n operations.
To form the unitary matrices PH and/or Q F08KSF (ZGEBRD) may be followed by calls to F08KTF (ZUNGBR):
to form the m by m unitary matrix Q
CALL ZUNGBR('Q',M,M,N,A,LDA,TAUQ,WORK,LWORK,INFO)
but note that the second dimension of the array A must be at least M, which may be larger than was required by F08KSF (ZGEBRD);
to form the n by n unitary matrix PH
CALL ZUNGBR('P',N,N,M,A,LDA,TAUP,WORK,LWORK,INFO)
but note that the first dimension of the array A, specified by the argument LDA, must be at least N, which may be larger than was required by F08KSF (ZGEBRD).
To apply Q or P to a complex rectangular matrix C, F08KSF (ZGEBRD) may be followed by a call to F08KUF (ZUNMBR).
The real analogue of this routine is F08KEF (DGEBRD).

10 Example

This example reduces the matrix A to bidiagonal form, where
A = 0.96-0.81 i -0.03+0.96 i -0.91+2.06 i -0.05+0.41 i -0.98+1.98 i -1.20+0.19 i -0.66+0.42 i -0.81+0.56 i 0.62-0.46 i 1.01+0.02 i 0.63-0.17 i -1.11+0.60 i -0.37+0.38 i 0.19-0.54 i -0.98-0.36 i 0.22-0.20 i 0.83+0.51 i 0.20+0.01 i -0.17-0.46 i 1.47+1.59 i 1.08-0.28 i 0.20-0.12 i -0.07+1.23 i 0.26+0.26 i .

10.1 Program Text

Program Text (f08ksfe.f90)

10.2 Program Data

Program Data (f08ksfe.d)

10.3 Program Results

Program Results (f08ksfe.r)

F08 Chapter Contents
F08 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F08KTF (ZUNGBR) : NAG Library, Mark 26

F08 Chapter Contents
F08 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F08KTF (ZUNGBR)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F08KTF (ZUNGBR) generates one of the complex unitary matrices Q or PH which were determined by F08KSF (ZGEBRD) when reducing a complex matrix to bidiagonal form.

2 Specification

SUBROUTINE F08KTF ( VECT, M, N, K, A, LDA, TAU, WORK, LWORK, INFO)
INTEGER | M, N, K, LDA, LWORK, INFO
COMPLEX (KIND=nag_wp) | A(LDA,*), TAU(*), WORK(max(1,LWORK))
CHARACTER(1) | VECT
The routine may be called by its LAPACK name zungbr.

3 Description

F08KTF (ZUNGBR) is intended to be used after a call to F08KSF (ZGEBRD), which reduces a complex rectangular matrix A to real bidiagonal form B by a unitary transformation: A=QB PH. F08KSF (ZGEBRD) represents the matrices Q and PH as products of elementary reflectors.
This routine may be used to generate Q or PH explicitly as square matrices, or in some cases just the leading columns of Q or the leading rows of PH.
The various possibilities are specified by the arguments VECT, M, N and K. The appropriate values to cover the most likely cases are as follows (assuming that A was an m by n matrix):
1. To form the full m by m matrix Q:
CALL ZUNGBR('Q',m,m,n,...)
(note that the array A must have at least m columns).
2. If m>n, to form the n leading columns of Q:
CALL ZUNGBR('Q',m,n,n,...)
3. To form the full n by n matrix PH:
CALL ZUNGBR('P',n,n,m,...)
(note that the array A must have at least n rows).
4. If m<n, to form the m leading rows of PH:
CALL ZUNGBR('P',m,n,m,...)

4 References

Golub G H and Van Loan C F (1996) Matrix Computations (3rd Edition) Johns Hopkins University Press, Baltimore

5 Arguments

1:   VECT – CHARACTER(1)Input
On entry: indicates whether the unitary matrix Q or PH is generated.
VECT='Q'
Q is generated.
VECT='P'
PH is generated.
Constraint: VECT='Q' or 'P'.
2:   M – INTEGERInput
On entry: m, the number of rows of the unitary matrix Q or PH to be returned.
Constraint: M≥0.
3:   N – INTEGERInput
On entry: n, the number of columns of the unitary matrix Q or PH to be returned.
Constraints:
  • N≥0;
  • if VECT='Q' and M>K, M≥N≥K;
  • if VECT='Q' and M≤K, M=N;
  • if VECT='P' and N>K, N≥M≥K;
  • if VECT='P' and N≤K, N=M.
4:   K – INTEGERInput
On entry: if VECT='Q', the number of columns in the original matrix A.
If VECT='P', the number of rows in the original matrix A.
Constraint: K≥0.
5:   A LDA* – COMPLEX (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array A must be at least max 1,N.
On entry: details of the vectors which define the elementary reflectors, as returned by F08KSF (ZGEBRD).
On exit: the unitary matrix Q or PH, or the leading rows or columns thereof, as specified by VECT, M and N.
6:   LDA – INTEGERInput
On entry: the first dimension of the array A as declared in the (sub)program from which F08KTF (ZUNGBR) is called.
Constraint: LDA≥max 1,M.
7:   TAU* – COMPLEX (KIND=nag_wp) arrayInput
Note: the dimension of the array TAU must be at least max 1,min M,K if VECT='Q' and at least max 1,min N,K if VECT='P'.
On entry: further details of the elementary reflectors, as returned by F08KSF (ZGEBRD) in its argument TAUQ if VECT='Q', or in its argument TAUP if VECT='P'.
8:   WORK max 1,LWORK – COMPLEX (KIND=nag_wp) arrayWorkspace
On exit: if INFO=0, the real part of WORK 1 contains the minimum value of LWORK required for optimal performance.
9:   LWORK – INTEGERInput
On entry: the dimension of the array WORK as declared in the (sub)program from which F08KTF (ZUNGBR) is called.
If LWORK=-1, a workspace query is assumed; the routine only calculates the optimal size of the WORK array, returns this value as the first entry of the WORK array, and no error message related to LWORK is issued.
Suggested value: for optimal performance, LWORK≥min M,N×nb, where nb is the optimal block size.
Constraint: LWORK≥ max 1,min M,N or LWORK=-1.
10:   INFO – INTEGEROutput
On exit: INFO=0 unless the routine detects an error (see Section 6).

6 Error Indicators and Warnings

INFO<0
If INFO=-i, argument i had an illegal value. An explanatory message is output, and execution of the program is terminated.

7 Accuracy

The computed matrix Q differs from an exactly unitary matrix by a matrix E such that
E 2 = O ε ,
where ε is the machine precision. A similar statement holds for the computed matrix PH.

8 Parallelism and Performance

F08KTF (ZUNGBR) is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
F08KTF (ZUNGBR) makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The total number of real floating-point operations for the cases listed in Section 3 are approximately as follows:
1. To form the whole of Q:
  • 163 n 3 m 2-3 mn+n 2 if m>n,
  • 163 m 3 if m≤n;
2. To form the n leading columns of Q when m>n:
  • 83 n 2 3 m-n;
3. To form the whole of PH:
  • 163 n 3 if m≥n,
  • 163 m 3 3 n 2-3 mn+m 2 if m<n;
4. To form the m leading rows of PH when m<n:
  • 83 m 2 3 n-m.
The real analogue of this routine is F08KFF (DORGBR).

10 Example

For this routine two examples are presented, both of which involve computing the singular value decomposition of a matrix A, where
A = 0.96-0.81 i -0.03+0.96 i -0.91+2.06 i -0.05+0.41 i -0.98+1.98 i -1.20+0.19 i -0.66+0.42 i -0.81+0.56 i 0.62-0.46 i 1.01+0.02 i 0.63-0.17 i -1.11+0.60 i -0.37+0.38 i 0.19-0.54 i -0.98-0.36 i 0.22-0.20 i 0.83+0.51 i 0.20+0.01 i -0.17-0.46 i 1.47+1.59 i 1.08-0.28 i 0.20-0.12 i -0.07+1.23 i 0.26+0.26 i
in the first example and
A = 0.28-0.36 i 0.50-0.86 i -0.77-0.48 i 1.58+0.66 i -0.50-1.10 i -1.21+0.76 i -0.32-0.24 i -0.27-1.15 i 0.36-0.51 i -0.07+1.33 i -0.75+0.47 i -0.08+1.01 i
in the second. A must first be reduced to tridiagonal form by F08KSF (ZGEBRD). The program then calls F08KTF (ZUNGBR) twice to form Q and PH, and passes these matrices to F08MSF (ZBDSQR), which computes the singular value decomposition of A.

10.1 Program Text

Program Text (f08ktfe.f90)

10.2 Program Data

Program Data (f08ktfe.d)

10.3 Program Results

Program Results (f08ktfe.r)

F08 Chapter Contents
F08 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F08KUF (ZUNMBR) : NAG Library, Mark 26

F08 Chapter Contents
F08 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F08KUF (ZUNMBR)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F08KUF (ZUNMBR) multiplies an arbitrary complex m by n matrix C by one of the complex unitary matrices Q or P which were determined by F08KSF (ZGEBRD) when reducing a complex matrix to bidiagonal form.

2 Specification

SUBROUTINE F08KUF ( VECT, SIDE, TRANS, M, N, K, A, LDA, TAU, C, LDC, WORK, LWORK, INFO)
INTEGER | M, N, K, LDA, LDC, LWORK, INFO
COMPLEX (KIND=nag_wp) | A(LDA,*), TAU(*), C(LDC,*), WORK(max(1,LWORK))
CHARACTER(1) | VECT, SIDE, TRANS
The routine may be called by its LAPACK name zunmbr.

3 Description

F08KUF (ZUNMBR) is intended to be used after a call to F08KSF (ZGEBRD), which reduces a complex rectangular matrix A to real bidiagonal form B by a unitary transformation: A=QB PH. F08KSF (ZGEBRD) represents the matrices Q and PH as products of elementary reflectors.
This routine may be used to form one of the matrix products
QC , QH C , CQ , C QH , PC , PH C , CP ​ or ​ C PH ,
overwriting the result on C (which may be any complex rectangular matrix).

4 References

Golub G H and Van Loan C F (1996) Matrix Computations (3rd Edition) Johns Hopkins University Press, Baltimore

5 Arguments

Note: in the descriptions below, r denotes the order of Q or PH: if SIDE='L', r=M and if SIDE='R', r=N.
1:   VECT – CHARACTER(1)Input
On entry: indicates whether Q or QH or P or PH is to be applied to C.
VECT='Q'
Q or QH is applied to C.
VECT='P'
P or PH is applied to C.
Constraint: VECT='Q' or 'P'.
2:   SIDE – CHARACTER(1)Input
On entry: indicates how Q or QH or P or PH is to be applied to C.
SIDE='L'
Q or QH or P or PH is applied to C from the left.
SIDE='R'
Q or QH or P or PH is applied to C from the right.
Constraint: SIDE='L' or 'R'.
3:   TRANS – CHARACTER(1)Input
On entry: indicates whether Q or P or QH or PH is to be applied to C.
TRANS='N'
Q or P is applied to C.
TRANS='C'
QH or PH is applied to C.
Constraint: TRANS='N' or 'C'.
4:   M – INTEGERInput
On entry: m, the number of rows of the matrix C.
Constraint: M≥0.
5:   N – INTEGERInput
On entry: n, the number of columns of the matrix C.
Constraint: N≥0.
6:   K – INTEGERInput
On entry: if VECT='Q', the number of columns in the original matrix A.
If VECT='P', the number of rows in the original matrix A.
Constraint: K≥0.
7:   A LDA* – COMPLEX (KIND=nag_wp) arrayInput
Note: the second dimension of the array A must be at least max 1,min r,K if VECT='Q' and at least max 1,r if VECT='P'.
On entry: details of the vectors which define the elementary reflectors, as returned by F08KSF (ZGEBRD).
8:   LDA – INTEGERInput
On entry: the first dimension of the array A as declared in the (sub)program from which F08KUF (ZUNMBR) is called.
Constraints:
  • if VECT='Q', LDA≥ max 1,r ;
  • if VECT='P', LDA≥ max 1,min r,K .
9:   TAU* – COMPLEX (KIND=nag_wp) arrayInput
Note: the dimension of the array TAU must be at least max 1,min r,K.
On entry: further details of the elementary reflectors, as returned by F08KSF (ZGEBRD) in its argument TAUQ if VECT='Q', or in its argument TAUP if VECT='P'.
10:   C LDC* – COMPLEX (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array C must be at least max 1,N.
On entry: the matrix C.
On exit: C is overwritten by QC or QH C or CQ or CH Q or PC or PH C or CP or CH P as specified by VECT, SIDE and TRANS.
11:   LDC – INTEGERInput
On entry: the first dimension of the array C as declared in the (sub)program from which F08KUF (ZUNMBR) is called.
Constraint: LDC≥max 1,M.
12:   WORK max 1,LWORK – COMPLEX (KIND=nag_wp) arrayWorkspace
On exit: if INFO=0, the real part of WORK 1 contains the minimum value of LWORK required for optimal performance.
13:   LWORK – INTEGERInput
On entry: the dimension of the array WORK as declared in the (sub)program from which F08KUF (ZUNMBR) is called.
If LWORK=-1, a workspace query is assumed; the routine only calculates the optimal size of the WORK array, returns this value as the first entry of the WORK array, and no error message related to LWORK is issued.
Suggested value: for optimal performance, LWORK≥N×nb if SIDE='L' and at least M×nb if SIDE='R', where nb is the optimal block size.
Constraints:
  • if SIDE='L', LWORK≥max 1,N or LWORK=-1;
  • if SIDE='R', LWORK≥max 1,M or LWORK=-1.
14:   INFO – INTEGEROutput
On exit: INFO=0 unless the routine detects an error (see Section 6).

6 Error Indicators and Warnings

INFO<0
If INFO=-i, argument i had an illegal value. An explanatory message is output, and execution of the program is terminated.

7 Accuracy

The computed result differs from the exact result by a matrix E such that
E 2 = O ε C 2 ,
where ε is the machine precision.

8 Parallelism and Performance

F08KUF (ZUNMBR) is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
F08KUF (ZUNMBR) makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The total number of real floating-point operations is approximately
  • if SIDE='L' and m≥k, 8 nk 2 m-k;
  • if SIDE='R' and n≥k, 8 mk 2 n-k;
  • if SIDE='L' and m<k, 8 m 2 n;
  • if SIDE='R' and n<k, 8 m n 2,
where k is the value of the argument K.
The real analogue of this routine is F08KGF (DORMBR).

10 Example

For this routine two examples are presented. Both illustrate how the reduction to bidiagonal form of a matrix A may be preceded by a QR or LQ factorization of A.
In the first example, m>n, and
A = 0.96-0.81 i -0.03+0.96 i -0.91+2.06 i -0.05+0.41 i -0.98+1.98 i -1.20+0.19 i -0.66+0.42 i -0.81+0.56 i 0.62-0.46 i 1.01+0.02 i 0.63-0.17 i -1.11+0.60 i -0.37+0.38 i 0.19-0.54 i -0.98-0.36 i 0.22-0.20 i 0.83+0.51 i 0.20+0.01 i -0.17-0.46 i 1.47+1.59 i 1.08-0.28 i 0.20-0.12 i -0.07+1.23 i 0.26+0.26 i .
The routine first performs a QR factorization of A as A=Qa R and then reduces the factor R to bidiagonal form B: R=Qb B PH. Finally it forms Qa and calls F08KUF (ZUNMBR) to form Q=QaQb.
In the second example, m<n, and
A = 0.28-0.36 i 0.50-0.86 i -0.77-0.48 i 1.58+0.66 i -0.50-1.10 i -1.21+0.76 i -0.32-0.24 i -0.27-1.15 i 0.36-0.51 i -0.07+1.33 i -0.75+0.47 i -0.08+1.01 i .
The routine first performs an LQ factorization of A as A=L PaH and then reduces the factor L to bidiagonal form B: L=QB PbH. Finally it forms PbH and calls F08KUF (ZUNMBR) to form PH=PbHPaH.

10.1 Program Text

Program Text (f08kufe.f90)

10.2 Program Data

Program Data (f08kufe.d)

10.3 Program Results

Program Results (f08kufe.r)

F08 Chapter Contents
F08 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


f08kvf (zgejsv) : NAG Library, Mark 27

F08 (lapack) Chapter Contents
F08 (lapack) Chapter Introduction
NAG Library Manual

NAG Library Routine Document

f08kvf (zgejsv)

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1
Purpose

f08kvf (zgejsv) computes the singular value decomposition (SVD) of a real m by n matrix A where m≥n, and optionally computes the left and/or right singular vectors. f08kvf (zgejsv) implements the preconditioned Jacobi SVD of Drmac and Veselic. This is the expert driver routine that calls f08kwf (zgesvj) after certain preconditioning. In most cases f08kwf (zgesvj) (m≥n), or, where m<n, f08kpf (zgesvd) or f08krf (zgesdd) is sufficient to obtain the SVD of a real matrix and is much simpler to use. These are much simpler to use and also handle the case m<n.

2
Specification

Fortran Interface
Subroutine f08kvf ( joba, jobu, jobv, jobr, jobt, jobp, m, n, a, lda, sva, u, ldu, v, ldv, cwork, lwork, rwork, lrwork, iwork, info)
Integer, Intent (In) | :: | m, n, lda, ldu, ldv, lwork, lrwork
Integer, Intent (Out) | :: | iwork(m+3*n), info
Real (Kind=nag_wp), Intent (Out) | :: | sva(n), rwork(max(1,lrwork))
Complex (Kind=nag_wp), Intent (Inout) | :: | a(lda,*), u(ldu,*), v(ldv,*)
Complex (Kind=nag_wp), Intent (Out) | :: | cwork(lwork)
Character (1), Intent (In) | :: | joba, jobu, jobv, jobr, jobt, jobp
C Header Interface
#include nagmk27.h
void f08kv ( const char *joba, const char *jobu, const char *jobv, const char *jobr, const char *jobt, const char *jobp, const Integer *m, const Integer *n, Complex a[], const Integer *lda, double sva[], Complex u[], const Integer *ldu, Complex v[], const Integer *ldv, Complex cwork[], const Integer *lwork, double rwork[], const Integer *lrwork, Integer iwork[], Integer *info, const Charlen length_joba, const Charlen length_jobu, const Charlen length_jobv, const Charlen length_jobr, const Charlen length_jobt, const Charlen length_jobp)
The routine may be called by its LAPACK name zgejsv.

3
Description

The SVD is written as
A = UΣ VH ,
where Σ is an m by n matrix which is zero except for its n diagonal elements, U is an m by m unitary matrix, and V is an n by n unitary matrix. The diagonal elements of Σ are the singular values of A in descending order of magnitude. The columns of U and V are the left and the right singular vectors of A. The diagonal of Σ is computed and stored in the array sva.

4
References

Anderson E, Bai Z, Bischof C, Blackford S, Demmel J, Dongarra J J, Du Croz J J, Greenbaum A, Hammarling S, McKenney A and Sorensen D (1999) LAPACK Users' Guide (3rd Edition) SIAM, Philadelphia http://www.netlib.org/lapack/lug
Drmac Z and Veselic K (2008a) New fast and accurate Jacobi SVD algorithm I SIAM J. Matrix Anal. Appl. 29 4
Drmac Z and Veselic K (2008b) New fast and accurate Jacobi SVD algorithm II SIAM J. Matrix Anal. Appl. 29 4
Golub G H and Van Loan C F (1996) Matrix Computations (3rd Edition) Johns Hopkins University Press, Baltimore

5
Arguments

1:   joba – Character(1)Input
On entry: specifies the form of pivoting for the QR factorization stage; whether an estimate of the condition number of the scaled matrix is required; and the form of rank reduction that is performed.
joba='C'
The initial QR factorization of the input matrix is performed with column pivoting; no estimate of condition number is computed; and, the rank is reduced by only the underflowed part of the triangular factor R. This option works well (high relative accuracy) if A=BD, with well-conditioned B and arbitrary diagonal matrix D. The accuracy cannot be spoiled by column scaling. The accuracy of the computed output depends on the condition of B, and the procedure aims at the best theoretical accuracy.
joba='E'
Computation as with joba='C' with an additional estimate of the condition number of B. It provides a realistic error bound.
joba='F'
The initial QR factorization of the input matrix is performed with full row and column pivoting; no estimate of condition number is computed; and, the rank is reduced by only the underflowed part of the triangular factor R. If A=D 1×C×D 2 with ill-conditioned diagonal scalings D 1, D 2, and well-conditioned matrix C, this option gives higher accuracy than the joba='C' option. If the structure of the input matrix is not known, and relative accuracy is desirable, then this option is advisable.
joba='G'
Computation as with joba='F' with an additional estimate of the condition number of B, where A=DB (i.e., B=C×D 2). If A has heavily weighted rows, then using this condition number gives too pessimistic an error bound.
joba='A'
Computation as with joba='C' except in the treatment of rank reduction. In this case, small singular values are to be considered as noise and, if found, the matrix is treated as numerically rank deficient. The computed SVD A=UΣ VH restores A up to f m,n×ε×A, where ε is machine precision. This gives the procedure licence to discard (set to zero) all singular values below n×ε×A.
joba='R'
Similar to joba='A'. The rank revealing property of the initial QR factorization is used to reveal (using the upper triangular factor) a gap σ r+1<ε σr in which case the numerical rank is declared to be r. The SVD is computed with absolute error bounds, but more accurately than with joba='A'.
Constraint: joba='C', 'E', 'F', 'G', 'A' or 'R'.
2:   jobu – Character(1)Input
On entry: specifies options for computing the left singular vectors U.
jobu='U'
The first n left singular vectors (columns of U) are computed and returned in the array u.
jobu='F'
All m left singular vectors are computed and returned in the array u.
jobu='W'
No left singular vectors are computed, but the array u (with ldu≥m and second dimension at least n) is available as workspace for computing right singular values. See the description of u.
jobu='N'
No left singular vectors are computed. u is not referenced when jobv='N' or 'W'.
Constraint: jobu='U', 'F', 'W' or 'N'.
3:   jobv – Character(1)Input
On entry: specifies options for computing the right singular vectors V.
jobv='V'
the n right singular vectors (columns of V) are computed and returned in the array v; Jacobi rotations are not explicitly accumulated.
jobv='J'
the n right singular vectors (columns of V) are computed and returned in the array v, but they are computed as the product of Jacobi rotations. This option is allowed only if jobu='U' or 'F', i.e., in computing the full SVD.
jobv='W'
No right singular values are computed, but the array v (with ldv≥n and second dimension at least n) is available as workspace for computing left singular values. See the description of v.
jobv='N'
No right singular vectors are computed. v is not referenced when jobu='N' or 'W' or jobt='N' or m≠n.
Constraints:
  • jobv='V', 'J', 'W' or 'N';
  • if jobu='W' or 'N', jobv≠'J'.
4:   jobr – Character(1)Input
On entry: specifies the conditions under which columns of A are to be set to zero. This effectively specifies a lower limit on the range of singular values; any singular values below this limit are (through column zeroing) set to zero. If A≠0 is scaled so that the largest column (in the Euclidean norm) of cA is equal to the square root of the overflow threshold, then jobr allows the routine to kill columns of A whose norm in cA is less than sfmin (for jobr='R'), or less than sfmin/ε (otherwise). sfmin is the safe range argument, as returned by routine x02amf.
jobr='N'
Only set to zero those columns of A for which the norm of corresponding column of cA<sfmin/ε, that is, those columns that are effectively zero (to machine precision) anyway. If the condition number of A is greater than the overflow threshold λ, where λ is the value returned by x02alf, you are recommended to use routine f08kwf (zgesvj).
jobr='R'
Set to zero those columns of A for which the norm of the corresponding column of cA<sfmin. This approximately represents a restricted range for σ cA of sfmin,λ.
For computing the singular values in the full range from the safe minimum up to the overflow threshold use f08kwf (zgesvj).
Suggested value: jobr='R'.
Constraint: jobr='N' or 'R'.
5:   jobt – Character(1)Input
On entry: specifies, in the case n=m, whether the routine is permitted to use the transpose of A for improved efficiency. If the matrix is square then the procedure may use transposed A if AH seems to be better with respect to convergence. If the matrix is not square, jobt is ignored. The decision is based on two values of entropy over the adjoint orbit of AH A. See the descriptions of rwork 6 and rwork 7.
jobt='T'
If n=m, perform an entropy test and then transpose if the test indicates possibly faster convergence of the Jacobi process if AH is taken as input. If A is replaced with AH, then the row pivoting is included automatically.
jobt='N'
No entropy test and no transposition is performed.
The option jobt='T' can be used to compute only the singular values, or the full SVD (U, Σ and V). In the case where only one set of singular vectors (U or V) is required, the caller must still provide both u and v, as one of the matrices is used as workspace if the matrix A is transposed. See the descriptions of u and v.
Constraint: jobt='T' or 'N'.
6:   jobp – Character(1)Input
On entry: specifies whether the routine should be allowed to introduce structured perturbations to drown denormalized numbers. For details see Drmac and Veselic (2008a) and Drmac and Veselic (2008b). For the sake of simplicity, these perturbations are included only when the full SVD or only the singular values are requested.
jobp='P'
Introduce perturbation if A is found to be very badly scaled (introducing denormalized numbers).
jobp='N'
Do not perturb.
Constraint: jobp='P' or 'N'.
7:   m – IntegerInput
On entry: m, the number of rows of the matrix A.
Constraint: m≥0.
8:   n – IntegerInput
On entry: n, the number of columns of the matrix A.
Constraint: m≥n≥0.
9:   a lda* – Complex (Kind=nag_wp) arrayInput/Output
Note: the second dimension of the array a must be at least max 1,n.
On entry: the m by n matrix A.
On exit: the contents of a are overwritten.
10:   lda – IntegerInput
On entry: the first dimension of the array a as declared in the (sub)program from which f08kvf (zgejsv) is called.
Constraint: lda≥max 1,m.
11:   sva n – Real (Kind=nag_wp) arrayOutput
On exit: the, possibly scaled, singular values of A.
The singular values of A are σi=α sva i, for i=1,2,…,n, where α=rwork 1/rwork 2. Normally α=1 and no scaling is required to obtain the singular values. However, if the largest singular value of A overflows or if small singular values have been saved from underflow by scaling the input matrix A, then α≠1.
If jobr='R' then some of the singular values may be returned as exact zeros because they are below the numerical rank threshold or are denormalized numbers.
12:   u ldu* – Complex (Kind=nag_wp) arrayOutput
Note: the second dimension of the array u must be at least max 1,m if jobu='F', max 1,n if jobu='U' or 'W', and at least 1 otherwise.
On exit: if jobu='U', u contains the m by n matrix of the left singular vectors.
If jobu='F', u contains the m by m matrix of the left singular vectors, including an orthonormal basis of the orthogonal complement of Range(A).
u is not referenced when jobu='W' or 'N' and one of the following is satisfied:
  • jobv='W' or 'N', or
  • n=1, or
  • A is the zero matrix.
13:   ldu – IntegerInput
On entry: the first dimension of the array u as declared in the (sub)program from which f08kvf (zgejsv) is called.
Constraints:
  • if jobu='F', 'U' or 'W', ldu≥max 1,m;
  • otherwise ldu≥1.
14:   v ldv* – Complex (Kind=nag_wp) arrayOutput
Note: the second dimension of the array v must be at least max 1,n if jobv='V', 'J' or 'W', and at least 1 otherwise.
On exit: if jobv='V' or 'J', v contains the n by n matrix of the right singular vectors.
v is not referenced when jobv='W' or 'N' and one of the following is satisfied:
  • jobu='U' or 'F' and jobt='T', or
  • n=1, or
  • A is the zero matrix.
15:   ldv – IntegerInput
On entry: the first dimension of the array v as declared in the (sub)program from which f08kvf (zgejsv) is called.
Constraints:
  • if jobv='V', 'J' or 'W', ldv≥max 1,n;
  • otherwise ldv≥1.
16:   cwork lwork – Complex (Kind=nag_wp) arrayWorkspace
On exit: if info=0, cwork 1 contains the required minimal size of lwork.
17:   lwork – IntegerInput
On entry: the dimension of the array cwork as declared in the (sub)program from which f08kvf (zgejsv) is called.
If jobu='N' or 'W'
if jobv='N' or 'W'
if joba≠'E' or 'G'
the minimal requirement is lwork≥2 n+1.
For optimal performance the requirement is lwork≥n+n+1×nb, where nb is the block size used by f08asf (zgeqrf) and f08btf (zgeqp3). Assuming a value of nb=256 is wise, but choosing a smaller value (e.g., nb=128) should still lead to acceptable performance.
If joba='E' or 'G'
the minimal requirement is lwork≥n n+3.
For optimal performance the requirement is lwork≥max n+n+1×nb,n n+3.
If jobv='V' or 'J'
the minimal requirement is lwork≥3 n.
For optimal performance the requirement is lwork≥max nb,n+n nb+1.
If jobu='U' or 'F' and n≠1
jobv='N' or 'W'
the minimal requirement is lwork≥3 n.
For optimal performance the requirement is lwork≥max nb,n+n nb+1.
If jobv='V'
the minimal requirement is lwork≥n 2 n+5.
For optimal performance the minimal requirement is sufficient.
If jobv='J'
The minimal requirement is lwork≥n n+4.
For optimal performance the minimal requirement is sufficient.
If jobu='U' or 'F' and n=1
The minimal workspace requirement is lwork≥m+1.
For optimal performance, lwork≥m×nb+1.
18:   rwork max 1,lrwork – Real (Kind=nag_wp) arrayWorkspace
On exit: contains information about the completed job.
rwork 1
α=rwork 1/rwork 2 is the scaling factor such that σi=α sva i, for i=1,2,…,n are the computed singular values of A. (See the description of sva.)
rwork 2
See the description of rwork 1.
rwork 3
sconda, an estimate for the condition number of column equilibrated A (if joba='E' or 'G'). sconda is an estimate of RH R-1 1. It is computed using f07fgf (dpocon). It satisfies n-14×sconda≤R-1 2≤n 14×sconda where R is the triangular factor from the QR factorization of A. However, if R is truncated and the numerical rank is determined to be strictly smaller than n, sconda is returned as -1, thus indicating that the smallest singular values might be lost.
If full SVD is needed, and you are familiar with the details of the method, the following two condition numbers are useful for the analysis of the algorithm.
rwork 4
An estimate of the scaled condition number of the triangular factor in the first QR factorization.
rwork 5
An estimate of the scaled condition number of the triangular factor in the second QR factorization.
The following two parameters are computed if jobt='T'.
rwork 6
The entropy of AH A: this is the Shannon entropy of diag⁡AH A/trace⁡AH A taken as a point in the probability simplex.
rwork 7
The entropy of A AH.
19:   lrwork – IntegerInput
On entry: the first dimension of the array rwork as declared in the (sub)program from which f08kvf (zgejsv) is called.
Constraint: lrwork≥max 7,n+2×m.
20:   iwork m+3×n – Integer arrayOutput
On exit: contains information about the completed job.
iwork 1
The numerical rank of A determined after the initial QR factorization with pivoting. See the descriptions of joba and jobr.
iwork 2
The number of computed nonzero singular values.
iwork 3
If nonzero, a warning message: If iwork 3=1 then some of the column norms of A were denormalized (tiny) numbers. The requested high accuracy is not warranted by the data.
21:   info – IntegerOutput
On exit: info=0 unless the routine detects an error (see Section 6).

6
Error Indicators and Warnings

info<0
If info=-i, argument i had an illegal value. An explanatory message is output, and execution of the program is terminated.
info>0
f08kvf (zgejsv) did not converge in the allowed number of iterations (30). The computed values might be inaccurate.

7
Accuracy

The computed singular value decomposition is nearly the exact singular value decomposition for a nearby matrix A+E , where
E 2 = O ε A 2 ,
and ε is the machine precision. In addition, the computed singular vectors are nearly unitary to working precision. See Section 4.9 of Anderson et al. (1999) for further details.

8
Parallelism and Performance

f08kvf (zgejsv) is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
f08kvf (zgejsv) makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9
Further Comments

f08kvf (zgejsv) implements a preconditioned Jacobi SVD algorithm. It uses f08asf (zgeqrf), f08avf (zgelqf) and f08btf (zgeqp3) as preprocessors and preconditioners. Optionally, an additional row pivoting can be used as a preprocessor, which in some cases results in much higher accuracy. An example is matrix A with the structure A=D 1 C D 2, where D 1, D 2 are arbitrarily ill-conditioned diagonal matrices and C is a well-conditioned matrix. In that case, complete pivoting in the first QR factorizations provides accuracy dependent on the condition number of C, and independent of D 1, D 2. Such higher accuracy is not completely understood theoretically, but it works well in practice. Further, if A can be written as A=BD, with well-conditioned B and some diagonal D, then the high accuracy is guaranteed, both theoretically and in software, independent of D.

10
Example

This example finds the singular values and left and right singular vectors of the 6 by 4 matrix
A = 0.96-0.81 i -0.03+0.96 i -0.91+2.06 i -0.05+0.41 i -0.98+1.98 i -1.20+0.19 i -0.66+0.42 i -0.81+0.56 i 0.62-0.46 i 1.01+0.02 i 0.63-0.17 i -1.11+0.60 i -0.37+0.38 i 0.19-0.54 i -0.98-0.36 i 0.22-0.20 i 0.83+0.51 i 0.20+0.01 i -0.17-0.46 i 1.47+1.59 i 1.08-0.28 i 0.20-0.12 i -0.07+1.23 i 0.26+0.26 i ,
together with the condition number of A and approximate error bounds for the computed singular values and vectors.

10.1
Program Text

Program Text (f08kvfe.f90)

10.2
Program Data

Program Data (f08kvfe.d)

10.3
Program Results

Program Results (f08kvfe.r)

F08 (lapack) Chapter Contents
F08 (lapack) Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2017


f08kwf (zgesvj) : NAG Library, Mark 27

F08 (lapack) Chapter Contents
F08 (lapack) Chapter Introduction
NAG Library Manual

NAG Library Routine Document

f08kwf (zgesvj)

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1
Purpose

f08kwf (zgesvj) computes the one-sided Jacobi singular value decomposition (SVD) of a complex m by n matrix A, m≥n, with fast scaled rotations and de Rijk’s pivoting, optionally computing the left and/or right singular vectors. For m<n, the routines f08kpf (zgesvd) or f08krf (zgesdd) may be used.

2
Specification

Fortran Interface
Subroutine f08kwf ( joba, jobu, jobv, m, n, a, lda, sva, mv, v, ldv, cwork, lwork, rwork, lrwork, info)
Integer, Intent (In) | :: | m, n, lda, mv, ldv, lwork, lrwork
Integer, Intent (Out) | :: | info
Real (Kind=nag_wp), Intent (Inout) | :: | rwork(lrwork)
Real (Kind=nag_wp), Intent (Out) | :: | sva(n)
Complex (Kind=nag_wp), Intent (Inout) | :: | a(lda,*), v(ldv,*)
Complex (Kind=nag_wp), Intent (Out) | :: | cwork(lwork)
Character (1), Intent (In) | :: | joba, jobu, jobv
C Header Interface
#include nagmk27.h
void f08kw ( const char *joba, const char *jobu, const char *jobv, const Integer *m, const Integer *n, Complex a[], const Integer *lda, double sva[], const Integer *mv, Complex v[], const Integer *ldv, Complex cwork[], const Integer *lwork, double rwork[], const Integer *lrwork, Integer *info, const Charlen length_joba, const Charlen length_jobu, const Charlen length_jobv)
The routine may be called by its LAPACK name zgesvj.

3
Description

The SVD is written as
A = UΣ VH ,
where Σ is an n by n diagonal matrix, U is an m by n unitary matrix, and V is an n by n unitary matrix. The diagonal elements of Σ are the singular values of A in descending order of magnitude. The columns of U and V are the left and the right singular vectors of A.

4
References

Anderson E, Bai Z, Bischof C, Blackford S, Demmel J, Dongarra J J, Du Croz J J, Greenbaum A, Hammarling S, McKenney A and Sorensen D (1999) LAPACK Users' Guide (3rd Edition) SIAM, Philadelphia http://www.netlib.org/lapack/lug
Drmac Z and Veselic K (2008a) New fast and accurate Jacobi SVD algorithm I SIAM J. Matrix Anal. Appl. 29 4
Drmac Z and Veselic K (2008b) New fast and accurate Jacobi SVD algorithm II SIAM J. Matrix Anal. Appl. 29 4
Golub G H and Van Loan C F (1996) Matrix Computations (3rd Edition) Johns Hopkins University Press, Baltimore

5
Arguments

1:   joba – Character(1)Input
On entry: specifies the structure of matrix A.
joba='L'
The input matrix A is lower triangular.
joba='U'
The input matrix A is upper triangular.
joba='G'
The input matrix A is a general m by n matrix, m≥n.
Constraint: joba='L', 'U' or 'G'.
2:   jobu – Character(1)Input
On entry: specifies whether to compute the left singular vectors and if so whether you want to control their numerical orthogonality threshold.
jobu='U'
The left singular vectors corresponding to the nonzero singular values are computed and returned in the leading columns of a. See more details in the description of a. The numerical orthogonality threshold is set to approximately tol=ctol×ε, where ε is the machine precision and ctol=m.
jobu='C'
Analogous to jobu='U', except that you can control the level of numerical orthogonality of the computed left singular vectors. The orthogonality threshold is set to tol=ctol×ε, where ctol is given on input in rwork 1. The option jobu='C' can be used if m×ε is a satisfactory orthogonality of the computed left singular vectors, so ctol=m could save a few sweeps of Jacobi rotations. See the descriptions of a and rwork 1.
jobu='N'
The matrix U is not computed. However, see the description of a.
Constraint: jobu='U', 'C' or 'N'.
3:   jobv – Character(1)Input
On entry: specifies whether and how to compute the right singular vectors.
jobv='V'
The matrix V is computed and returned in the array v.
jobv='A'
The Jacobi rotations are applied to the leading mv by n part of the array v. In other words, the right singular vector matrix V is not computed explicitly, instead it is applied to an mv by n matrix initially stored in the first mv rows of v.
jobv='N'
The matrix V is not computed and the array v is not referenced.
Constraint: jobv='V', 'A' or 'N'.
4:   m – IntegerInput
On entry: m, the number of rows of the matrix A.
Constraint: m≥0.
5:   n – IntegerInput
On entry: n, the number of columns of the matrix A.
Constraint: m≥n≥0.
6:   a lda* – Complex (Kind=nag_wp) arrayInput/Output
Note: the second dimension of the array a must be at least max 1,n.
On entry: the m by n matrix A.
On exit: the matrix U containing the left singular vectors of A.
If jobu='U' or 'C'
if info=0
rank A unitary columns of U are returned in the leading rank A columns of the array a. Here rank A≤n is the number of computed singular values of A that are above the safe range parameter, as returned by x02amf. The singular vectors corresponding to underflowed or zero singular values are not computed. The value of rank A is returned by rounding rwork 2 to the nearest whole number. Also see the descriptions of sva and rwork. The computed columns of U are mutually numerically unitary up to approximately tol=m×ε; or tol=ctol×ε (jobu='C'), where ε is the machine precision and ctol is supplied on entry in rwork 1, see the description of jobu.
If info>0
f08kwf (zgesvj) did not converge in 30 iterations (sweeps). In this case, the computed columns of U may not be unitary up to tol. The output U (stored in a), Σ (given by the computed singular values in sva) and V is still a decomposition of the input matrix A in the sense that the residual A-α×U×Σ×VH 2/A 2 is small, where α is the value returned in rwork 1.
If jobu='N'
if info=0
Note that the left singular vectors are ‘for free’ in the one-sided Jacobi SVD algorithm. However, if only the singular values are needed, the level of numerical orthogonality of U is not an issue and iterations are stopped when the columns of the iterated matrix are numerically unitary up to approximately m×ε. Thus, on exit, a contains the columns of U scaled with the corresponding singular values.
If info>0
f08kwf (zgesvj) did not converge in 30 iterations (sweeps).
7:   lda – IntegerInput
On entry: the first dimension of the array a as declared in the (sub)program from which f08kwf (zgesvj) is called.
Constraint: lda≥max 1,m.
8:   sva n – Real (Kind=nag_wp) arrayOutput
On exit: the, possibly scaled, singular values of A.
If info=0
The singular values of A are σi=α sva i, for i=1,2,…,n, where α is the scale factor stored in rwork 1. Normally α=1, however, if some of the singular values of A might underflow or overflow, then α≠1 and the scale factor needs to be applied to obtain the singular values.
If info>0
f08kwf (zgesvj) did not converge in 30 iterations and α×sva may not be accurate.
9:   mv – IntegerInput
On entry: if jobv='A', the product of Jacobi rotations is applied to the first mv rows of v.
If jobv≠'A', mv is ignored. See the description of jobv.
10:   v ldv* – Complex (Kind=nag_wp) arrayInput/Output
Note: the second dimension of the array v must be at least max 1,n if jobv='V' or 'A', and at least 1 otherwise.
On entry: if jobv='A', v must contain an mv by n matrix to be premultiplied by the matrix V of right singular vectors.
On exit: the right singular vectors of A.
If jobv='V', v contains the n by n matrix of the right singular vectors.
If jobv='A', v contains the product of the computed right singular vector matrix and the initial matrix in the array v.
If jobv='N', v is not referenced.
11:   ldv – IntegerInput
On entry: the first dimension of the array v as declared in the (sub)program from which f08kwf (zgesvj) is called.
Constraints:
  • if jobv='V', ldv≥max 1,n;
  • if jobv='A', ldv≥max 1,mv;
  • otherwise ldv≥1.
12:   cwork lwork – Complex (Kind=nag_wp) arrayWorkspace
On exit: if info=0, cwork 1 contains the required minimal size of lwork.
13:   lwork – IntegerInput
On entry: the dimension of the array cwork as declared in the (sub)program from which f08kwf (zgesvj) is called.
Constraint: lwork≥m+n.
14:   rwork lrwork – Real (Kind=nag_wp) arrayWorkspace
On entry: if jobu='C', rwork 1=ctol, where ctol defines the threshold for convergence. The process stops if all columns of A are mutually orthogonal up to ctol×ε. It is required that ctol≥1, i.e., it is not possible to force the routine to obtain orthogonality below ε. ctol greater than 1/ε is meaningless, where ε is the machine precision.
On exit: contains information about the completed job.
rwork 1
the scaling factor, α, such that σi=α sva i, for i=1,2,…,n are the computed singular values of A. (See description of sva.)
rwork 2
nint rwork 2gives the number of the computed nonzero singular values.
rwork 3
nint rwork 3 gives the number of the computed singular values that are larger than the underflow threshold.
rwork 4
nint rwork 4 gives the number of iterations (sweeps of Jacobi rotations) needed for numerical convergence.
rwork 5
max i≠j cos A:,i,A:,j in the last iteration (sweep). This is useful information in cases when f08kwf (zgesvj) did not converge, as it can be used to estimate whether the output is still useful and for subsequent analysis.
rwork 6
The largest absolute value over all sines of the Jacobi rotation angles in the last sweep. It can be useful for subsequent analysis.
Constraint: if jobu='C', rwork 1≥1.0.
15:   lrwork – IntegerInput
On entry: the dimension of the array rwork as declared in the (sub)program from which f08kwf (zgesvj) is called.
Constraint: lrwork≥max 6,n.
16:   info – IntegerOutput
On exit: info=0 unless the routine detects an error (see Section 6).

6
Error Indicators and Warnings

info<0
If info=-i, argument i had an illegal value. An explanatory message is output, and execution of the program is terminated.
info>0
f08kwf (zgesvj) did not converge in the allowed number of iterations (30), but its output might still be useful.

7
Accuracy

The computed singular value decomposition is nearly the exact singular value decomposition for a nearby matrix A+E , where
E 2 = O ε A 2 ,
and ε is the machine precision. In addition, the computed singular vectors are nearly unitary to working precision. See Section 4.9 of Anderson et al. (1999) for further details.
See Section 6 of Drmac and Veselic (2008a) for a detailed discussion of the accuracy of the computed SVD.

8
Parallelism and Performance

f08kwf (zgesvj) makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9
Further Comments

This SVD algorithm is numerically superior to the bidiagonalization based QR algorithm implemented by f08kpf (zgesvd) and the divide and conquer algorithm implemented by f08krf (zgesdd) algorithms and is considerably faster than previous implementations of the (equally accurate) Jacobi SVD method. Moreover, this algorithm can compute the SVD faster than f08kpf (zgesvd) and not much slower than f08krf (zgesdd). See Section 3.3 of Drmac and Veselic (2008b) for the details.
The real analogue of this routine is f08kjf (dgesvj).

10
Example

This example finds the singular values and left and right singular vectors of the 6 by 4 matrix
A = 0.96-0.81 i -0.03+0.96 i -0.91+2.06 i -0.05+0.41 i -0.98+1.98 i -1.20+0.19 i -0.66+0.42 i -0.81+0.56 i 0.62-0.46 i 1.01+0.02 i 0.63-0.17 i -1.11+0.60 i -0.37+0.38 i 0.19-0.54 i -0.98-0.36 i 0.22-0.20 i 0.83+0.51 i 0.20+0.01 i -0.17-0.46 i 1.47+1.59 i 1.08-0.28 i 0.20-0.12 i -0.07+1.23 i 0.26+0.26 i ,
together with approximate error bounds for the computed singular values and vectors.

10.1
Program Text

Program Text (f08kwfe.f90)

10.2
Program Data

Program Data (f08kwfe.d)

10.3
Program Results

Program Results (f08kwfe.r)

F08 (lapack) Chapter Contents
F08 (lapack) Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2017


f08kzf (zgesvdx) : NAG Library, Mark 27

F08 (lapack) Chapter Contents
F08 (lapack) Chapter Introduction
NAG Library Manual

NAG Library Routine Document

f08kzf (zgesvdx)

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1
Purpose

f08kzf (zgesvdx) computes the singular value decomposition (SVD) of a complex m by n matrix A, optionally computing the left and/or right singular vectors. All singular values or a selected set of singular values may be computed.

2
Specification

Fortran Interface
Subroutine f08kzf ( jobu, jobvt, range, m, n, a, lda, vl, vu, il, iu, ns, s, u, ldu, vt, ldvt, work, lwork, rwork, iwork, info)
Integer, Intent (In) | :: | m, n, lda, il, iu, ldu, ldvt, lwork
Integer, Intent (Out) | :: | ns, iwork(12*min(n,m)), info
Real (Kind=nag_wp), Intent (In) | :: | vl, vu
Real (Kind=nag_wp), Intent (Inout) | :: | rwork(*)
Real (Kind=nag_wp), Intent (Out) | :: | s(min(m,n))
Complex (Kind=nag_wp), Intent (Inout) | :: | a(lda,*), u(ldu,*), vt(ldvt,*)
Complex (Kind=nag_wp), Intent (Out) | :: | work(max(1,lwork))
Character (1), Intent (In) | :: | jobu, jobvt, range
C Header Interface
#include nagmk27.h
void f08kz ( const char *jobu, const char *jobvt, const char *range, const Integer *m, const Integer *n, Complex a[], const Integer *lda, const double *vl, const double *vu, const Integer *il, const Integer *iu, Integer *ns, double s[], Complex u[], const Integer *ldu, Complex vt[], const Integer *ldvt, Complex work[], const Integer *lwork, double rwork[], Integer iwork[], Integer *info, const Charlen length_jobu, const Charlen length_jobvt, const Charlen length_range)
The routine may be called by its LAPACK name zgesvdx.

3
Description

The SVD is written as
A = UΣ VH ,
where Σ is an m by n matrix which is zero except for its min m,n diagonal elements, U is an m by m unitary matrix, and V is an n by n unitary matrix. The diagonal elements of Σ are the singular values of A; they are complex and non-negative, and are returned in descending order. The first min m,n columns of U and V are the left and right singular vectors of A.
Note that the routine returns VH, not V.
Alternative to computing all singular values of A, a selected set can be computed. The set is either those singular values lying in a given interval, σ∈vl,vu, or those whose index (counting from largest to smallest in magnitude) lies in a given range 1≤il,…,iu≤n. In these cases, the corresponding left and right singular vectors can optionally be computed.

4
References

Anderson E, Bai Z, Bischof C, Blackford S, Demmel J, Dongarra J J, Du Croz J J, Greenbaum A, Hammarling S, McKenney A and Sorensen D (1999) LAPACK Users' Guide (3rd Edition) SIAM, Philadelphia http://www.netlib.org/lapack/lug
Golub G H and Van Loan C F (1996) Matrix Computations (3rd Edition) Johns Hopkins University Press, Baltimore

5
Arguments

1:   jobu – Character(1)Input
On entry: specifies options for computing all or part of the matrix U.
jobu='V'
The ns columns of U, as specified by range, are returned in array u.
jobu='N'
No columns of U (no left singular vectors) are computed.
Constraint: jobu='V' or 'N'.
2:   jobvt – Character(1)Input
On entry: specifies options for computing all or part of the matrix VT.
jobvt='V'
The ns rows of VT, as specified by range, are returned in the array vt.
jobvt='N'
No rows of VT (no right singular vectors) are computed.
Constraint: jobvt='V' or 'N'.
3:   range – Character(1)Input
On entry: indicates which singular values should be returned.
range='A'
All singular values will be found.
range='V'
All singular values in the half-open interval vl,vu will be found.
range='I'
The ilth through iuth singular values will be found.
Constraint: range='A', 'V' or 'I'.
4:   m – IntegerInput
On entry: m, the number of rows of the matrix A.
Constraint: m≥0.
5:   n – IntegerInput
On entry: n, the number of columns of the matrix A.
Constraint: n≥0.
6:   a lda* – Complex (Kind=nag_wp) arrayInput/Output
Note: the second dimension of the array a must be at least max 1,n.
On entry: the m by n matrix A.
On exit: if jobu≠'N' and jobvt≠'N', the contents of a are destroyed.
7:   lda – IntegerInput
On entry: the first dimension of the array a as declared in the (sub)program from which f08kzf (zgesvdx) is called.
Constraint: lda≥max 1,m.
8:   vl – Real (Kind=nag_wp)Input
On entry: if range='V', the lower bounds of the interval to be searched for singular values.
If range='A' or 'I', vl is not referenced.
Constraint: if range='V', 0.0≤vl.
9:   vu – Real (Kind=nag_wp)Input
On entry: if range='V', the upper bounds of the interval to be searched for singular values.
If range='A' or 'I', vu is not referenced.
Constraint: if range='V', vl<vu.
10:   il – IntegerInput
11:   iu – IntegerInput
On entry: if range='I', the indices (in ascending order) of the smallest and largest singular values to be returned.
If range='A' or 'V', il and iu are not referenced.
Constraints:
  • if range='I' and min m,n=0, il=1 and iu=0;
  • if range='I' and min m,n>0, 1≤ il≤ iu≤ min m,n .
12:   ns – IntegerOutput
On exit: the total number of singular values found. 0≤ns≤min m,n.
If range='A', ns=min m,n.
If range='I', ns=iu-il+1.
If range='V' then the value of ns is not known in advance and so an upper limit should be used, e.g., min m,n.
13:   s min m,n – Real (Kind=nag_wp) arrayOutput
On exit: the singular values of A, sorted so that s i≥s i+1.
14:   u ldu* – Complex (Kind=nag_wp) arrayOutput
Note: the second dimension of the array u must be at least max 1,nsmax if jobu='V', and at least 1 otherwise.
Where nsmax is a value larger than the output value ns.
On exit: m by ns.
If jobu='V', u contains the first min m,n ns columns of U (the left singular vectors, stored column-wise).
If jobu='N', u is not referenced.
15:   ldu – IntegerInput
On entry: the first dimension of the array u as declared in the (sub)program from which f08kzf (zgesvdx) is called.
Constraints:
  • if jobu='V', ldu≥ max 1,m ;
  • otherwise ldu≥1.
16:   vt ldvt* – Complex (Kind=nag_wp) arrayOutput
Note: the second dimension of the array vt must be at least max 1,n if jobvt='V', and at least 1 otherwise.
On exit: if jobvt='V', vt contains the first ns rows of VH (the right singular vectors, stored row-wise).
If jobvt='N', vt is not referenced.
17:   ldvt – IntegerInput
Note: if jobvt='V' and range='V' then the value of ns is not known in advance and so an upper limit should be used, e.g., min m,n.
On entry: the first dimension of the array vt as declared in the (sub)program from which f08kzf (zgesvdx) is called.
Constraints:
  • if jobvt='V', ldvt≥ max 1,min m,n ;
  • otherwise ldvt≥1.
18:   work max 1,lwork – Complex (Kind=nag_wp) arrayWorkspace
On exit: if info=0, work 1 returns the optimal lwork.
If info>0, work 2:min m,n contains the unconverged superdiagonal elements of an upper bidiagonal matrix B whose diagonal is in s (not necessarily sorted). B satisfies A=UB VH, so it has the same singular values as A, and singular vectors related by U and VH.
19:   lwork – IntegerInput
On entry: the dimension of the array work as declared in the (sub)program from which f08kzf (zgesvdx) is called.
If lwork=-1, a workspace query is assumed; the routine only calculates the optimal size of the work array, returns this value as the first entry of the work array, and no error message related to lwork is issued.
Suggested value: for optimal performance, lwork should generally be larger. Consider increasing lwork by at least nb×min m,n , where nb is the optimal block size.
Constraint: lwork ≥ max 1, min m,n × min m,n + 5 .
20:   rwork* – Real (Kind=nag_wp) arrayWorkspace
Note: the dimension of the array rwork must be at least min m,n × 2 × min m,n + 17 .
21:   iwork 12×min n,m – Integer arrayWorkspace
On exit:
  • if info=0, the first ns elements of iwork are zero;
  • if info>0, iwork contains the indices of the eigenvectors that failed to converge in f08jbf (dstevx) and f08mbf (dbdsvdx).
22:   info – IntegerOutput
On exit: info=0 unless the routine detects an error (see Section 6).

6
Error Indicators and Warnings

info<0
If info=-i, argument i had an illegal value. An explanatory message is output, and execution of the program is terminated.
info>0
If f08kzf (zgesvdx) did not converge, info specifies how many superdiagonals of an intermediate bidiagonal form did not converge to zero.

7
Accuracy

The computed singular value decomposition is nearly the exact singular value decomposition for a nearby matrix A+E , where
E 2 = O ε A 2 ,
and ε is the machine precision. In addition, the computed singular vectors are nearly unitary to working precision. See Section 4.9 of Anderson et al. (1999) for further details.

8
Parallelism and Performance

f08kzf (zgesvdx) is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
f08kzf (zgesvdx) makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9
Further Comments

The total number of floating-point operations is approximately proportional to m n 2 when m>n and m 2 n otherwise.
The singular values are returned in descending order.
The real analogue of this routine is f08kmf (dgesvdx).

10
Example

This example finds the singular values and left and right singular vectors of the 6 by 4 matrix
A = 0.96-0.81 i -0.03+0.96 i -0.91+2.06 i -0.05+0.04 i -0.98+1.98 i -1.20+0.19 i -0.66+0.42 i -0.81+0.56 i 0.62-0.46 i 1.01+0.02 i 0.63-0.17 i -1.11+0.60 i -0.37+0.38 i 0.19-0.54 i -0.98-0.36 i 0.22-0.20 i 0.83+0.51 i 0.20+0.01 i -0.17-0.46 i 1.47+1.59 i 1.08+0.28 i 0.20-0.12 i -0.07+1.23 i 0.26+0.26 i ,
together with approximate error bounds for the computed singular values and vectors.
The example program for f08krf (zgesdd) illustrates finding a singular value decomposition for the case m≤n.

10.1
Program Text

Program Text (f08kzfe.f90)

10.2
Program Data

Program Data (f08kzfe.d)

10.3
Program Results

Program Results (f08kzfe.r)

F08 (lapack) Chapter Contents
F08 (lapack) Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2017


F08LEF (DGBBRD) : NAG Library, Mark 26

F08 Chapter Contents
F08 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F08LEF (DGBBRD)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F08LEF (DGBBRD) reduces a real m by n band matrix to upper bidiagonal form.

2 Specification

SUBROUTINE F08LEF ( VECT, M, N, NCC, KL, KU, AB, LDAB, D, E, Q, LDQ, PT, LDPT, C, LDC, WORK, INFO)
INTEGER | M, N, NCC, KL, KU, LDAB, LDQ, LDPT, LDC, INFO
REAL (KIND=nag_wp) | AB(LDAB,*), D(min(M,N)), E(min(M,N)-1), Q(LDQ,*), PT(LDPT,*), C(LDC,*), WORK(2*max(M,N))
CHARACTER(1) | VECT
The routine may be called by its LAPACK name dgbbrd.

3 Description

F08LEF (DGBBRD) reduces a real m by n band matrix to upper bidiagonal form B by an orthogonal transformation: A=QB PT. The orthogonal matrices Q and PT, of order m and n respectively, are determined as a product of Givens rotation matrices, and may be formed explicitly by the routine if required. A matrix C may also be updated to give C~=QT C.
The routine uses a vectorizable form of the reduction.

4 References

None.

5 Arguments

1:   VECT – CHARACTER(1)Input
On entry: indicates whether the matrices Q and/or PT are generated.
VECT='N'
Neither Q nor PT is generated.
VECT='Q'
Q is generated.
VECT='P'
PT is generated.
VECT='B'
Both Q and PT are generated.
Constraint: VECT='N', 'Q', 'P' or 'B'.
2:   M – INTEGERInput
On entry: m, the number of rows of the matrix A.
Constraint: M≥0.
3:   N – INTEGERInput
On entry: n, the number of columns of the matrix A.
Constraint: N≥0.
4:   NCC – INTEGERInput
On entry: nC, the number of columns of the matrix C.
Constraint: NCC≥0.
5:   KL – INTEGERInput
On entry: the number of subdiagonals, kl, within the band of A.
Constraint: KL≥0.
6:   KU – INTEGERInput
On entry: the number of superdiagonals, ku, within the band of A.
Constraint: KU≥0.
7:   AB LDAB* – REAL (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array AB must be at least max 1,N.
On entry: the original m by n band matrix A.
The matrix is stored in rows 1 to kl+ku+1, more precisely, the element A ij must be stored in
AB ku+1+i-j j  for ​max 1,j-ku≤i≤min m,j+kl.
On exit: AB is overwritten by values generated during the reduction.
8:   LDAB – INTEGERInput
On entry: the first dimension of the array AB as declared in the (sub)program from which F08LEF (DGBBRD) is called.
Constraint: LDAB≥KL+KU+1.
9:   D min M,N – REAL (KIND=nag_wp) arrayOutput
On exit: the diagonal elements of the bidiagonal matrix B.
10:   E min M,N-1 – REAL (KIND=nag_wp) arrayOutput
On exit: the superdiagonal elements of the bidiagonal matrix B.
11:   Q LDQ* – REAL (KIND=nag_wp) arrayOutput
Note: the second dimension of the array Q must be at least max 1,M if VECT='Q' or 'B', and at least 1 otherwise.
On exit: if VECT='Q' or 'B', contains the m by m orthogonal matrix Q.
If VECT='N' or 'P', Q is not referenced.
12:   LDQ – INTEGERInput
On entry: the first dimension of the array Q as declared in the (sub)program from which F08LEF (DGBBRD) is called.
Constraints:
  • if VECT='Q' or 'B', LDQ≥ max 1,M ;
  • otherwise LDQ≥1.
13:   PT LDPT* – REAL (KIND=nag_wp) arrayOutput
Note: the second dimension of the array PT must be at least max 1,N if VECT='P' or 'B', and at least 1 otherwise.
On exit: the n by n orthogonal matrix PT, if VECT='P' or 'B'. If VECT='N' or 'Q', PT is not referenced.
14:   LDPT – INTEGERInput
On entry: the first dimension of the array PT as declared in the (sub)program from which F08LEF (DGBBRD) is called.
Constraints:
  • if VECT='P' or 'B', LDPT≥ max 1,N ;
  • otherwise LDPT≥1.
15:   C LDC* – REAL (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array C must be at least max 1,NCC.
On entry: an m by nC matrix C.
On exit: C is overwritten by QT C. If NCC=0, C is not referenced.
16:   LDC – INTEGERInput
On entry: the first dimension of the array C as declared in the (sub)program from which F08LEF (DGBBRD) is called.
Constraints:
  • if NCC>0, LDC≥ max 1,M ;
  • if NCC=0, LDC≥1.
17:   WORK 2×max M,N – REAL (KIND=nag_wp) arrayWorkspace
18:   INFO – INTEGEROutput
On exit: INFO=0 unless the routine detects an error (see Section 6).

6 Error Indicators and Warnings

INFO<0
If INFO=-i, argument i had an illegal value. An explanatory message is output, and execution of the program is terminated.

7 Accuracy

The computed bidiagonal form B satisfies QB PT=A+E, where
E 2 ≤ c n ε A 2 ,
c n is a modestly increasing function of n, and ε is the machine precision.
The elements of B themselves may be sensitive to small perturbations in A or to rounding errors in the computation, but this does not affect the stability of the singular values and vectors.
The computed matrix Q differs from an exactly orthogonal matrix by a matrix F such that
F 2 = O ε .
A similar statement holds for the computed matrix PT.

8 Parallelism and Performance

F08LEF (DGBBRD) makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The total number of real floating-point operations is approximately the sum of:
  • 6 n 2 k, if VECT='N' and NCC=0, and
  • 3 n 2 nC k-1/k, if C is updated, and
  • 3 n 3 k-1/k, if either Q or PT is generated (double this if both),
where k=kl+ku, assuming n≫k. For this section we assume that m=n.
The complex analogue of this routine is F08LSF (ZGBBRD).

10 Example

This example reduces the matrix A to upper bidiagonal form, where
A = -0.57 -1.28 0.00 0.00 -1.93 1.08 -0.31 0.00 2.30 0.24 0.40 -0.35 0.00 0.64 -0.66 0.08 0.00 0.00 0.15 -2.13 -0.00 0.00 0.00 0.50 .

10.1 Program Text

Program Text (f08lefe.f90)

10.2 Program Data

Program Data (f08lefe.d)

10.3 Program Results

Program Results (f08lefe.r)

F08 Chapter Contents
F08 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F08LSF (ZGBBRD) : NAG Library, Mark 26

F08 Chapter Contents
F08 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F08LSF (ZGBBRD)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F08LSF (ZGBBRD) reduces a complex m by n band matrix to real upper bidiagonal form.

2 Specification

SUBROUTINE F08LSF ( VECT, M, N, NCC, KL, KU, AB, LDAB, D, E, Q, LDQ, PT, LDPT, C, LDC, WORK, RWORK, INFO)
INTEGER | M, N, NCC, KL, KU, LDAB, LDQ, LDPT, LDC, INFO
REAL (KIND=nag_wp) | D(min(M,N)), E(min(M,N)-1), RWORK(max(M,N))
COMPLEX (KIND=nag_wp) | AB(LDAB,*), Q(LDQ,*), PT(LDPT,*), C(LDC,*), WORK(max(M,N))
CHARACTER(1) | VECT
The routine may be called by its LAPACK name zgbbrd.

3 Description

F08LSF (ZGBBRD) reduces a complex m by n band matrix to real upper bidiagonal form B by a unitary transformation: A=QB PH. The unitary matrices Q and PH, of order m and n respectively, are determined as a product of Givens rotation matrices, and may be formed explicitly by the routine if required. A matrix C may also be updated to give C~=QH C.
The routine uses a vectorizable form of the reduction.

4 References

None.

5 Arguments

1:   VECT – CHARACTER(1)Input
On entry: indicates whether the matrices Q and/or PH are generated.
VECT='N'
Neither Q nor PH is generated.
VECT='Q'
Q is generated.
VECT='P'
PH is generated.
VECT='B'
Both Q and PH are generated.
Constraint: VECT='N', 'Q', 'P' or 'B'.
2:   M – INTEGERInput
On entry: m, the number of rows of the matrix A.
Constraint: M≥0.
3:   N – INTEGERInput
On entry: n, the number of columns of the matrix A.
Constraint: N≥0.
4:   NCC – INTEGERInput
On entry: nC, the number of columns of the matrix C.
Constraint: NCC≥0.
5:   KL – INTEGERInput
On entry: the number of subdiagonals, kl, within the band of A.
Constraint: KL≥0.
6:   KU – INTEGERInput
On entry: the number of superdiagonals, ku, within the band of A.
Constraint: KU≥0.
7:   AB LDAB* – COMPLEX (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array AB must be at least max 1,N.
On entry: the original m by n band matrix A.
The matrix is stored in rows 1 to kl+ku+1, more precisely, the element A ij must be stored in
AB ku+1+i-j j  for ​max 1,j-ku≤i≤min m,j+kl.
On exit: AB is overwritten by values generated during the reduction.
8:   LDAB – INTEGERInput
On entry: the first dimension of the array AB as declared in the (sub)program from which F08LSF (ZGBBRD) is called.
Constraint: LDAB≥KL+KU+1.
9:   D min M,N – REAL (KIND=nag_wp) arrayOutput
On exit: the diagonal elements of the bidiagonal matrix B.
10:   E min M,N-1 – REAL (KIND=nag_wp) arrayOutput
On exit: the superdiagonal elements of the bidiagonal matrix B.
11:   Q LDQ* – COMPLEX (KIND=nag_wp) arrayOutput
Note: the second dimension of the array Q must be at least max 1,M if VECT='Q' or 'B', and at least 1 otherwise.
On exit: if VECT='Q' or 'B', contains the m by m unitary matrix Q.
If VECT='N' or 'P', Q is not referenced.
12:   LDQ – INTEGERInput
On entry: the first dimension of the array Q as declared in the (sub)program from which F08LSF (ZGBBRD) is called.
Constraints:
  • if VECT='Q' or 'B', LDQ≥ max 1,M ;
  • otherwise LDQ≥1.
13:   PT LDPT* – COMPLEX (KIND=nag_wp) arrayOutput
Note: the second dimension of the array PT must be at least max 1,N if VECT='P' or 'B', and at least 1 otherwise.
On exit: the n by n unitary matrix PH, if VECT='P' or 'B'. If VECT='N' or 'Q', PT is not referenced.
14:   LDPT – INTEGERInput
On entry: the first dimension of the array PT as declared in the (sub)program from which F08LSF (ZGBBRD) is called.
Constraints:
  • if VECT='P' or 'B', LDPT≥ max 1,N ;
  • otherwise LDPT≥1.
15:   C LDC* – COMPLEX (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array C must be at least max 1,NCC.
On entry: an m by nC matrix C.
On exit: C is overwritten by QH C. If NCC=0, C is not referenced.
16:   LDC – INTEGERInput
On entry: the first dimension of the array C as declared in the (sub)program from which F08LSF (ZGBBRD) is called.
Constraints:
  • if NCC>0, LDC≥ max 1,M ;
  • if NCC=0, LDC≥1.
17:   WORK max M,N – COMPLEX (KIND=nag_wp) arrayWorkspace
18:   RWORK max M,N – REAL (KIND=nag_wp) arrayWorkspace
19:   INFO – INTEGEROutput
On exit: INFO=0 unless the routine detects an error (see Section 6).

6 Error Indicators and Warnings

INFO<0
If INFO=-i, argument i had an illegal value. An explanatory message is output, and execution of the program is terminated.

7 Accuracy

The computed bidiagonal form B satisfies QB PH=A+E, where
E 2 ≤ c n ε A 2 ,
c n is a modestly increasing function of n, and ε is the machine precision.
The elements of B themselves may be sensitive to small perturbations in A or to rounding errors in the computation, but this does not affect the stability of the singular values and vectors.
The computed matrix Q differs from an exactly unitary matrix by a matrix F such that
F 2 = O ε .
A similar statement holds for the computed matrix PH.

8 Parallelism and Performance

F08LSF (ZGBBRD) makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The total number of real floating-point operations is approximately the sum of:
  • 20 n 2 k, if VECT='N' and NCC=0, and
  • 10 n 2 nC k-1/k, if C is updated, and
  • 10 n 3 k-1/k, if either Q or PH is generated (double this if both),
where k=kl+ku, assuming n≫k. For this section we assume that m=n.
The real analogue of this routine is F08LEF (DGBBRD).

10 Example

This example reduces the matrix A to upper bidiagonal form, where
A = 0.96-0.81 i -0.03+0.96 i 0.00+0.00 i 0.00+0.00 i -0.98+1.98 i -1.20+0.19 i -0.66+0.42 i 0.00+0.00 i 0.62-0.46 i 1.01+0.02 i 0.63-0.17 i -1.11+0.60 i 0.00+0.00 i 0.19-0.54 i -0.98-0.36 i 0.22-0.20 i 0.00+0.00 i 0.00+0.00 i -0.17-0.46 i 1.47+1.59 i 0.00+0.00 i 0.00+0.00 i 0.00+0.00 i 0.26+0.26 i .

10.1 Program Text

Program Text (f08lsfe.f90)

10.2 Program Data

Program Data (f08lsfe.d)

10.3 Program Results

Program Results (f08lsfe.r)

F08 Chapter Contents
F08 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


f08mbf (dbdsvdx) : NAG Library, Mark 27

F08 (lapack) Chapter Contents
F08 (lapack) Chapter Introduction
NAG Library Manual

NAG Library Routine Document

f08mbf (dbdsvdx)

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1
Purpose

f08mbf (dbdsvdx) computes all or selected singular values and, optionally, the corresponding left and right singular vectors of a real n by n (upper or lower) bidiagonal matrix B.

2
Specification

Fortran Interface
Subroutine f08mbf ( uplo, jobz, range, n, d, e, vl, vu, il, iu, ns, s, z, ldz, work, iwork, info)
Integer, Intent (In) | :: | n, il, iu, ldz
Integer, Intent (Out) | :: | ns, iwork(12*n), info
Real (Kind=nag_wp), Intent (In) | :: | d(n), e(n-1), vl, vu
Real (Kind=nag_wp), Intent (Inout) | :: | z(ldz,*)
Real (Kind=nag_wp), Intent (Out) | :: | s(n), work(14*n)
Character (1), Intent (In) | :: | uplo, jobz, range
C Header Interface
#include nagmk27.h
void f08mb ( const char *uplo, const char *jobz, const char *range, const Integer *n, const double d[], const double e[], const double *vl, const double *vu, const Integer *il, const Integer *iu, Integer *ns, double s[], double z[], const Integer *ldz, double work[], Integer iwork[], Integer *info, const Charlen length_uplo, const Charlen length_jobz, const Charlen length_range)
The routine may be called by its LAPACK name dbdsvdx.

3
Description

f08mbf (dbdsvdx) computes the singular value decomposition (SVD) of a real n by n (upper or lower) bidiagonal matrix B as
B = US VT ,
where S is a diagonal matrix with non-negative diagonal elements (the singular values of B), and U and VT are orthogonal matrices of left and right singular vectors, respectively.
Given an upper bidiagonal B with diagonal d= d 1 d 2 … dn and superdiagonal e= e 1 e 2 … e N-1 , f08mbf (dbdsvdx) computes the singular value decompositon of B through the eigenvalues and eigenvectors of the n×2 by n×2 tridiagonal matrix
TGK= 0 d 1 d 1 0 e 1 e 1 0 d 2 d 2 . . . . . .
If s,u,v is a singular triplet of B with u=v=1, then s,q and -s,q, q=1, are eigenpairs of TGK, with q= v 1,u 1,v 2,u 2,…,vn,un / 2 for s, and q= -v 1,u 1,-v 2,u 2,…,-v n,un / 2 for -s.
Given a TGK matrix, one can either
(i) | compute -s,-v and change signs so that the singular values (and corresponding vectors) are already in descending order (as in f08kbf (dgesvd)) or
(ii) | compute s,v and reorder the values (and corresponding vectors).
f08mbf (dbdsvdx) implements (i) by calling f08jbf (dstevx) (bisection plus inverse iteration, to be replaced with a version of the Multiple Relative Robust Representation algorithm. (See Williams and Lang (2013).)
Alternative to computing all singular values of A, a selected set can be computed. The set is either those singular values lying in a given interval, σ∈vl,vu, or those whose index (counting from largest to smallest in magnitude) lies in a given range 1≤il,…,iu≤n. In these cases, the corresponding left and right singular vectors can optionally be computed.

4
References

Anderson E, Bai Z, Bischof C, Blackford S, Demmel J, Dongarra J J, Du Croz J J, Greenbaum A, Hammarling S, McKenney A and Sorensen D (1999) LAPACK Users' Guide (3rd Edition) SIAM, Philadelphia http://www.netlib.org/lapack/lug
Williams P and Lang B (2013) A framework for the M R 3 algorithm: theory and implementation SIAM J. Sci. Comput. 35 740–766

5
Arguments

1:   uplo – Character(1)Input
On entry: indicates whether B is upper or lower bidiagonal.
uplo='U'
B is upper bidiagonal.
uplo='L'
B is lower bidiagonal.
Constraint: uplo='U' or 'L'.
2:   jobz – Character(1)Input
On entry: indicates whether singular vectors are computed.
jobz='N'
Only singular values are computed.
jobz='V'
Singular values and singular vectors are computed.
Constraint: jobz='N' or 'V'.
3:   range – Character(1)Input
On entry: indicates which singular values should be returned.
range='A'
All singular values will be found.
range='V'
All singular values in the half-open interval vl,vu will be found.
range='I'
The ilth through iuth singular values will be found.
Constraint: range='A', 'V' or 'I'.
4:   n – IntegerInput
On entry: n, the order of the bidiagonal matrix B.
Constraint: n≥0.
5:   d n – Real (Kind=nag_wp) arrayInput
On entry: the diagonal elements d of the bidiagonal matrix B.
6:   e n-1 – Real (Kind=nag_wp) arrayInput
On entry: the n-1 off-diagonal elements e of the bidiagonal matrix B.
7:   vl – Real (Kind=nag_wp)Input
On entry: if range='V', the lower bounds of the interval to be searched for singular values.
If range='A' or 'I', vl is not referenced.
Constraint: if range='V', 0.0≤vl.
8:   vu – Real (Kind=nag_wp)Input
On entry: if range='V', the upper bounds of the interval to be searched for singular values.
If range='A' or 'I', vu is not referenced.
Constraint: if range='V', vl<vu.
9:   il – IntegerInput
10:   iu – IntegerInput
On entry: if range='I', the indices (in ascending order) of the smallest and largest singular values to be returned.
If range='A' or 'V', il and iu are not referenced.
Constraints:
  • if range='I' and n=0, il=1 and iu=0;
  • if range='I' and n>0, 1≤ il≤ iu≤ n .
11:   ns – IntegerOutput
On exit: the total number of singular values found. 0≤ns≤n.
If range='A', ns=n.
If range='I', ns=iu-il+1.
12:   s n – Real (Kind=nag_wp) arrayOutput
On exit: the first NS elements contain the selected singular values in ascending order.
13:   z ldz* – Real (Kind=nag_wp) arrayOutput
Note: the second dimension of the array z must be at least min n,ns+1 if jobz='V', and at least 1 otherwise.
On exit: if jobz='V', then if info=0 the first ns columns of z contain the singular vectors of the matrix B corresponding to the selected singular values, with U in rows 1 to N and V in rows N+1 to N×2, i.e.,
Z= U V .
If jobz='N', then z is not referenced.
Note: the user must ensure that at least K=min n,ns+1 columns are supplied in the array Z; if range='V', the exact value of ns is not known in advance and an upper bound of at least n must be used.
14:   ldz – IntegerInput
On entry: the first dimension of the array z as declared in the (sub)program from which f08mbf (dbdsvdx) is called.
Constraints:
  • if jobz='V', ldz≥ max 2,n×2 ;
  • otherwise ldz≥1.
15:   work 14×n – Real (Kind=nag_wp) arrayWorkspace
16:   iwork 12×n – Integer arrayWorkspace
On exit: if jobz='V', then
  • if info=0, the first ns elements of iwork are zero;
  • if info>0, iwork contains the indices of the eigenvectors that failed to converge in f08jbf (dstevx).
If jobz='N', iwork is not referenced.
17:   info – IntegerOutput
On exit: info=0 unless the routine detects an error (see Section 6).

6
Error Indicators and Warnings

info<0
If info=-i, argument i had an illegal value. An explanatory message is output, and execution of the program is terminated.
info>0
The algorithm failed to converge; value eigenvectors of the associated eigenproblem did not converge. Their indices are stored in array iwork.

7
Accuracy

Each computed singular value of B is accurate to nearly full relative precision, no matter how tiny the singular value. The ith computed singular value, s^i, satisfies the bound
s^i-si ≤ p n ε si
where ε is the machine precision and p n is a modest function of n.
For bounds on the computed singular values, see Section 4.9.1 of Anderson et al. (1999). See also f08flf (ddisna).

8
Parallelism and Performance

f08mbf (dbdsvdx) is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
f08mbf (dbdsvdx) makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9
Further Comments

If only singular values are required, the total number of floating-point operations is approximately proportional to n 2. When singular vectors are required the number of operations is bounded above by approximately the same number of operations as f08mef (dbdsqr), but for large matrices f08mbf (dbdsvdx) is usually much faster.
There is no complex analogue of f08mbf (dbdsvdx).

10
Example

This example computes the singular value decomposition of the upper bidiagonal matrix
B = 3.62 1.26 0.00 0.00 0.00 -2.41 -1.53 0.00 0.00 0.00 1.92 1.19 0.00 0.00 0.00 -1.43 .

10.1
Program Text

Program Text (f08mbfe.f90)

10.2
Program Data

Program Data (f08mbfe.d)

10.3
Program Results

Program Results (f08mbfe.r)

F08 (lapack) Chapter Contents
F08 (lapack) Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2017


F08MDF (DBDSDC) : NAG Library, Mark 26

F08 Chapter Contents
F08 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F08MDF (DBDSDC)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F08MDF (DBDSDC) computes the singular values and, optionally, the left and right singular vectors of a real n by n (upper or lower) bidiagonal matrix B.

2 Specification

SUBROUTINE F08MDF ( UPLO, COMPQ, N, D, E, U, LDU, VT, LDVT, Q, IQ, WORK, IWORK, INFO)
INTEGER | N, LDU, LDVT, IQ(*), IWORK(8*N), INFO
REAL (KIND=nag_wp) | D(*), E(*), U(LDU,*), VT(LDVT,*), Q(*), WORK(*)
CHARACTER(1) | UPLO, COMPQ
The routine may be called by its LAPACK name dbdsdc.

3 Description

F08MDF (DBDSDC) computes the singular value decomposition (SVD) of the (upper or lower) bidiagonal matrix B as
B = US VT ,
where S is a diagonal matrix with non-negative diagonal elements s ii=si, such that
s 1 ≥ s 2 ≥ ⋯ ≥ sn ≥ 0 ,
and U and V are orthogonal matrices. The diagonal elements of S are the singular values of B and the columns of U and V are respectively the corresponding left and right singular vectors of B.
When only singular values are required the routine uses the QR algorithm, but when singular vectors are required a divide and conquer method is used. The singular values can optionally be returned in compact form, although currently no routine is available to apply U or V when stored in compact form.

4 References

Anderson E, Bai Z, Bischof C, Blackford S, Demmel J, Dongarra J J, Du Croz J J, Greenbaum A, Hammarling S, McKenney A and Sorensen D (1999) LAPACK Users' Guide (3rd Edition) SIAM, Philadelphia http://www.netlib.org/lapack/lug
Golub G H and Van Loan C F (1996) Matrix Computations (3rd Edition) Johns Hopkins University Press, Baltimore

5 Arguments

1:   UPLO – CHARACTER(1)Input
On entry: indicates whether B is upper or lower bidiagonal.
UPLO='U'
B is upper bidiagonal.
UPLO='L'
B is lower bidiagonal.
Constraint: UPLO='U' or 'L'.
2:   COMPQ – CHARACTER(1)Input
On entry: specifies whether singular vectors are to be computed.
COMPQ='N'
Compute singular values only.
COMPQ='P'
Compute singular values and compute singular vectors in compact form.
COMPQ='I'
Compute singular values and singular vectors.
Constraint: COMPQ='N', 'P' or 'I'.
3:   N – INTEGERInput
On entry: n, the order of the matrix B.
Constraint: N≥0.
4:   D* – REAL (KIND=nag_wp) arrayInput/Output
Note: the dimension of the array D must be at least max 1,N.
On entry: the n diagonal elements of the bidiagonal matrix B.
On exit: if INFO=0, the singular values of B.
5:   E* – REAL (KIND=nag_wp) arrayInput/Output
Note: the dimension of the array E must be at least max 1,N-1.
On entry: the n-1 off-diagonal elements of the bidiagonal matrix B.
On exit: the contents of E are destroyed.
6:   U LDU* – REAL (KIND=nag_wp) arrayOutput
Note: the second dimension of the array U must be at least max 1,N if COMPQ='I', and at least 1 otherwise.
On exit: if COMPQ='I', then if INFO=0, U contains the left singular vectors of the bidiagonal matrix B.
If COMPQ≠'I', U is not referenced.
7:   LDU – INTEGERInput
On entry: the first dimension of the array U as declared in the (sub)program from which F08MDF (DBDSDC) is called.
Constraints:
  • if COMPQ='I', LDU≥ max 1,N ;
  • otherwise LDU≥1.
8:   VT LDVT* – REAL (KIND=nag_wp) arrayOutput
Note: the second dimension of the array VT must be at least max 1,N if COMPQ='I', and at least 1 otherwise.
On exit: if COMPQ='I', then if INFO=0, the rows of VT contain the right singular vectors of the bidiagonal matrix B.
If COMPQ≠'I', VT is not referenced.
9:   LDVT – INTEGERInput
On entry: the first dimension of the array VT as declared in the (sub)program from which F08MDF (DBDSDC) is called.
Constraints:
  • if COMPQ='I', LDVT≥ max 1,N ;
  • otherwise LDVT≥1.
10:   Q* – REAL (KIND=nag_wp) arrayOutput
Note: the dimension of the array Q must be at least max 1,N 2+5 N,ldq.
On exit: if COMPQ='P', then if INFO=0, Q and IQ contain the left and right singular vectors in a compact form, requiring O N log 2⁡N space instead of 2×N 2. In particular, Q contains all the real data in the first ldq =N× 11+2× smlsiz+8× int log 2 N/ smlsiz+1 elements of Q, where smlsiz is equal to the maximum size of the subproblems at the bottom of the computation tree (usually about 25).
If COMPQ≠'P', Q is not referenced.
11:   IQ* – INTEGER arrayOutput
Note: the dimension of the array IQ must be at least max 1,ldiq.
On exit: if COMPQ='P', then if INFO=0, Q and IQ contain the left and right singular vectors in a compact form, requiring O N log 2⁡N space instead of 2×N 2. In particular, IQ contains all integer data in the first ldiq =N× 3+3× int log 2 N/ smlsiz+1 elements of IQ, where smlsiz is equal to the maximum size of the subproblems at the bottom of the computation tree (usually about 25).
If COMPQ≠'P', IQ is not referenced.
12:   WORK* – REAL (KIND=nag_wp) arrayWorkspace
Note: the dimension of the array WORK must be at least max 1,6×N-2 if COMPQ='N', max 1,6×N if COMPQ='P', max 1,3×N 2+4×N if COMPQ='I', and at least 1 otherwise.
13:   IWORK 8×N – INTEGER arrayWorkspace
14:   INFO – INTEGEROutput
On exit: INFO=0 unless the routine detects an error (see Section 6).

6 Error Indicators and Warnings

INFO<0
If INFO=-i, argument i had an illegal value. An explanatory message is output, and execution of the program is terminated.
INFO>0
The algorithm failed to compute a singular value. The update process of divide-and-conquer failed.

7 Accuracy

Each computed singular value of B is accurate to nearly full relative precision, no matter how tiny the singular value. The ith computed singular value, s^i, satisfies the bound
s^i-si ≤ p n ε si
where ε is the machine precision and p n is a modest function of n.
For bounds on the computed singular values, see Section 4.9.1 of Anderson et al. (1999). See also F08FLF (DDISNA).

8 Parallelism and Performance

F08MDF (DBDSDC) is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
F08MDF (DBDSDC) makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

If only singular values are required, the total number of floating-point operations is approximately proportional to n 2. When singular vectors are required the number of operations is bounded above by approximately the same number of operations as F08MEF (DBDSQR), but for large matrices F08MDF (DBDSDC) is usually much faster.
There is no complex analogue of F08MDF (DBDSDC).

10 Example

This example computes the singular value decomposition of the upper bidiagonal matrix
B = 3.62 1.26 0.00 0.00 0.00 -2.41 -1.53 0.00 0.00 0.00 1.92 1.19 0.00 0.00 0.00 -1.43 .

10.1 Program Text

Program Text (f08mdfe.f90)

10.2 Program Data

Program Data (f08mdfe.d)

10.3 Program Results

Program Results (f08mdfe.r)

F08 Chapter Contents
F08 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F08MEF (DBDSQR) : NAG Library, Mark 26

F08 Chapter Contents
F08 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F08MEF (DBDSQR)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.
Warning. The specification of the argument WORK changed at Mark 20: the length of WORK needs to be increased.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F08MEF (DBDSQR) computes the singular value decomposition of a real upper or lower bidiagonal matrix, or of a real general matrix which has been reduced to bidiagonal form.

2 Specification

SUBROUTINE F08MEF ( UPLO, N, NCVT, NRU, NCC, D, E, VT, LDVT, U, LDU, C, LDC, WORK, INFO)
INTEGER | N, NCVT, NRU, NCC, LDVT, LDU, LDC, INFO
REAL (KIND=nag_wp) | D(*), E(*), VT(LDVT,*), U(LDU,*), C(LDC,*), WORK(*)
CHARACTER(1) | UPLO
The routine may be called by its LAPACK name dbdsqr.

3 Description

F08MEF (DBDSQR) computes the singular values and, optionally, the left or right singular vectors of a real upper or lower bidiagonal matrix B. In other words, it can compute the singular value decomposition (SVD) of B as
B = U Σ VT .
Here Σ is a diagonal matrix with real diagonal elements σi (the singular values of B), such that
σ 1 ≥ σ 2 ≥ ⋯ ≥ σn ≥ 0 ;
U is an orthogonal matrix whose columns are the left singular vectors ui; V is an orthogonal matrix whose rows are the right singular vectors vi. Thus
B ui = σi vi   and   BT vi = σi ui ,   i = 1,2,…,n .
To compute U and/or VT, the arrays U and/or VT must be initialized to the unit matrix before F08MEF (DBDSQR) is called.
The routine may also be used to compute the SVD of a real general matrix A which has been reduced to bidiagonal form by an orthogonal transformation: A=QB PT. If A is m by n with m≥n, then Q is m by n and PT is n by n; if A is n by p with n<p, then Q is n by n and PT is n by p. In this case, the matrices Q and/or PT must be formed explicitly by F08KFF (DORGBR) and passed to F08MEF (DBDSQR) in the arrays U and/or VT respectively.
F08MEF (DBDSQR) also has the capability of forming UT C, where C is an arbitrary real matrix; this is needed when using the SVD to solve linear least squares problems.
F08MEF (DBDSQR) uses two different algorithms. If any singular vectors are required (i.e., if NCVT>0 or NRU>0 or NCC>0), the bidiagonal QR algorithm is used, switching between zero-shift and implicitly shifted forms to preserve the accuracy of small singular values, and switching between QR and QL variants in order to handle graded matrices effectively (see Demmel and Kahan (1990)). If only singular values are required (i.e., if NCVT=NRU=NCC=0), they are computed by the differential qd algorithm (see Fernando and Parlett (1994)), which is faster and can achieve even greater accuracy.
The singular vectors are normalized so that ui=vi=1, but are determined only to within a factor ±1.

4 References

Demmel J W and Kahan W (1990) Accurate singular values of bidiagonal matrices SIAM J. Sci. Statist. Comput. 11 873–912
Fernando K V and Parlett B N (1994) Accurate singular values and differential qd algorithms Numer. Math. 67 191–229
Golub G H and Van Loan C F (1996) Matrix Computations (3rd Edition) Johns Hopkins University Press, Baltimore

5 Arguments

1:   UPLO – CHARACTER(1)Input
On entry: indicates whether B is an upper or lower bidiagonal matrix.
UPLO='U'
B is an upper bidiagonal matrix.
UPLO='L'
B is a lower bidiagonal matrix.
Constraint: UPLO='U' or 'L'.
2:   N – INTEGERInput
On entry: n, the order of the matrix B.
Constraint: N≥0.
3:   NCVT – INTEGERInput
On entry: ncvt, the number of columns of the matrix VT of right singular vectors. Set NCVT=0 if no right singular vectors are required.
Constraint: NCVT≥0.
4:   NRU – INTEGERInput
On entry: nru, the number of rows of the matrix U of left singular vectors. Set NRU=0 if no left singular vectors are required.
Constraint: NRU≥0.
5:   NCC – INTEGERInput
On entry: ncc, the number of columns of the matrix C. Set NCC=0 if no matrix C is supplied.
Constraint: NCC≥0.
6:   D* – REAL (KIND=nag_wp) arrayInput/Output
Note: the dimension of the array D must be at least max 1,N.
On entry: the diagonal elements of the bidiagonal matrix B.
On exit: the singular values in decreasing order of magnitude, unless INFO>0 (in which case see Section 6).
7:   E* – REAL (KIND=nag_wp) arrayInput/Output
Note: the dimension of the array E must be at least max 1,N-1.
On entry: the off-diagonal elements of the bidiagonal matrix B.
On exit: E is overwritten, but if INFO>0 see Section 6.
8:   VT LDVT* – REAL (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array VT must be at least max 1,NCVT.
On entry: if NCVT>0, VT must contain an n by ncvt matrix. If the right singular vectors of B are required, ncvt=n and VT must contain the unit matrix; if the right singular vectors of A are required, VT must contain the orthogonal matrix PT returned by F08KFF (DORGBR) with VECT='P'.
On exit: the n by ncvt matrix VT or VTPT of right singular vectors, stored by rows.
If NCVT=0, VT is not referenced.
9:   LDVT – INTEGERInput
On entry: the first dimension of the array VT as declared in the (sub)program from which F08MEF (DBDSQR) is called.
Constraints:
  • if NCVT>0, LDVT≥ max 1,N ;
  • otherwise LDVT≥1.
10:   U LDU* – REAL (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array U must be at least max 1,N.
On entry: if NRU>0, U must contain an nru by n matrix. If the left singular vectors of B are required, nru=n and U must contain the unit matrix; if the left singular vectors of A are required, U must contain the orthogonal matrix Q returned by F08KFF (DORGBR) with VECT='Q'.
On exit: the nru by n matrix U or QU of left singular vectors, stored as columns of the matrix.
If NRU=0, U is not referenced.
11:   LDU – INTEGERInput
On entry: the first dimension of the array U as declared in the (sub)program from which F08MEF (DBDSQR) is called.
Constraint: LDU≥ max 1,NRU .
12:   C LDC* – REAL (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array C must be at least max 1,NCC.
On entry: the n by ncc matrix C if NCC>0.
On exit: C is overwritten by the matrix UT C. If NCC=0, C is not referenced.
13:   LDC – INTEGERInput
On entry: the first dimension of the array C as declared in the (sub)program from which F08MEF (DBDSQR) is called.
Constraints:
  • if NCC>0, LDC≥ max 1,N ;
  • otherwise LDC≥1.
14:   WORK* – REAL (KIND=nag_wp) arrayWorkspace
Note: the dimension of the array WORK must be at least max 1,2×N if NCVT=0 and NRU=0 and NCC=0, and at least max 1,4×N otherwise.
15:   INFO – INTEGEROutput
On exit: INFO=0 unless the routine detects an error (see Section 6).

6 Error Indicators and Warnings

INFO<0
If INFO=-i, argument i had an illegal value. An explanatory message is output, and execution of the program is terminated.
INFO>0
The algorithm failed to converge and INFO specifies how many off-diagonals did not converge. In this case, D and E contain on exit the diagonal and off-diagonal elements, respectively, of a bidiagonal matrix orthogonally equivalent to B.

7 Accuracy

Each singular value and singular vector is computed to high relative accuracy. However, the reduction to bidiagonal form (prior to calling the routine) may exclude the possibility of obtaining high relative accuracy in the small singular values of the original matrix if its singular values vary widely in magnitude.
If σi is an exact singular value of B and σ~i is the corresponding computed value, then
σ~i - σi ≤ p m,n ε σi
where p m,n is a modestly increasing function of m and n, and ε is the machine precision. If only singular values are computed, they are computed more accurately (i.e., the function p m,n is smaller), than when some singular vectors are also computed.
If ui is the corresponding exact left singular vector of B, and u~i is the corresponding computed left singular vector, then the angle θ u~i,ui between them is bounded as follows:
θ u~i,ui ≤ p m,n ε relgapi
where relgapi is the relative gap between σi and the other singular values, defined by
relgapi = min i≠j σi - σj σi + σj .
A similar error bound holds for the right singular vectors.

8 Parallelism and Performance

F08MEF (DBDSQR) is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
F08MEF (DBDSQR) makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The total number of floating-point operations is roughly proportional to n 2 if only the singular values are computed. About 6 n 2×nru additional operations are required to compute the left singular vectors and about 6 n 2×ncvt to compute the right singular vectors. The operations to compute the singular values must all be performed in scalar mode; the additional operations to compute the singular vectors can be vectorized and on some machines may be performed much faster.
The complex analogue of this routine is F08MSF (ZBDSQR).

10 Example

This example computes the singular value decomposition of the upper bidiagonal matrix B, where
B = 3.62 1.26 0.00 0.00 0.00 -2.41 -1.53 0.00 0.00 0.00 1.92 1.19 0.00 0.00 0.00 -1.43 .
See also the example for F08KFF (DORGBR), which illustrates the use of the routine to compute the singular value decomposition of a general matrix.

10.1 Program Text

Program Text (f08mefe.f90)

10.2 Program Data

Program Data (f08mefe.d)

10.3 Program Results

Program Results (f08mefe.r)

F08 Chapter Contents
F08 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F08MSF (ZBDSQR) : NAG Library, Mark 26

F08 Chapter Contents
F08 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F08MSF (ZBDSQR)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.
Warning. The specification of the argument WORK changed at Mark 20: the length of WORK needs to be increased.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
10 Example

1 Purpose

F08MSF (ZBDSQR) computes the singular value decomposition of a complex general matrix which has been reduced to bidiagonal form.

2 Specification

SUBROUTINE F08MSF ( UPLO, N, NCVT, NRU, NCC, D, E, VT, LDVT, U, LDU, C, LDC, WORK, INFO)
INTEGER | N, NCVT, NRU, NCC, LDVT, LDU, LDC, INFO
REAL (KIND=nag_wp) | D(*), E(*), WORK(*)
COMPLEX (KIND=nag_wp) | VT(LDVT,*), U(LDU,*), C(LDC,*)
CHARACTER(1) | UPLO
The routine may be called by its LAPACK name zbdsqr.

3 Description

F08MSF (ZBDSQR) computes the singular values and, optionally, the left or right singular vectors of a real upper or lower bidiagonal matrix B. In other words, it can compute the singular value decomposition (SVD) of B as
B = U Σ VT .
Here Σ is a diagonal matrix with real diagonal elements σi (the singular values of B), such that
σ 1 ≥ σ 2 ≥ ⋯ ≥ σn ≥ 0 ;
U is an orthogonal matrix whose columns are the left singular vectors ui; V is an orthogonal matrix whose rows are the right singular vectors vi. Thus
B ui = σi vi   and   BT vi = σi ui ,   i = 1,2,…,n .
To compute U and/or VT, the arrays U and/or VT must be initialized to the unit matrix before F08MSF (ZBDSQR) is called.
The routine stores the real orthogonal matrices U and VT in complex arrays U and VT, so that it may also be used to compute the SVD of a complex general matrix A which has been reduced to bidiagonal form by a unitary transformation: A=QB PH. If A is m by n with m≥n, then Q is m by n and PH is n by n; if A is n by p with n<p, then Q is n by n and PH is n by p. In this case, the matrices Q and/or PH must be formed explicitly by F08KTF (ZUNGBR) and passed to F08MSF (ZBDSQR) in the arrays U and/or VT respectively.
F08MSF (ZBDSQR) also has the capability of forming UH C, where C is an arbitrary complex matrix; this is needed when using the SVD to solve linear least squares problems.
F08MSF (ZBDSQR) uses two different algorithms. If any singular vectors are required (i.e., if NCVT>0 or NRU>0 or NCC>0), the bidiagonal QR algorithm is used, switching between zero-shift and implicitly shifted forms to preserve the accuracy of small singular values, and switching between QR and QL variants in order to handle graded matrices effectively (see Demmel and Kahan (1990)). If only singular values are required (i.e., if NCVT=NRU=NCC=0), they are computed by the differential qd algorithm (see Fernando and Parlett (1994)), which is faster and can achieve even greater accuracy.
The singular vectors are normalized so that ui=vi=1, but are determined only to within a complex factor of absolute value 1.

4 References

Demmel J W and Kahan W (1990) Accurate singular values of bidiagonal matrices SIAM J. Sci. Statist. Comput. 11 873–912
Fernando K V and Parlett B N (1994) Accurate singular values and differential qd algorithms Numer. Math. 67 191–229
Golub G H and Van Loan C F (1996) Matrix Computations (3rd Edition) Johns Hopkins University Press, Baltimore

5 Arguments

1:   UPLO – CHARACTER(1)Input
On entry: indicates whether B is an upper or lower bidiagonal matrix.
UPLO='U'
B is an upper bidiagonal matrix.
UPLO='L'
B is a lower bidiagonal matrix.
Constraint: UPLO='U' or 'L'.
2:   N – INTEGERInput
On entry: n, the order of the matrix B.
Constraint: N≥0.
3:   NCVT – INTEGERInput
On entry: ncvt, the number of columns of the matrix VH of right singular vectors. Set NCVT=0 of right singular vectors. Set NCVT=0 if no right singular vectors are required.
Constraint: NCVT≥0.
4:   NRU – INTEGERInput
On entry: nru, the number of rows of the matrix U of left singular vectors. Set NRU=0 if no left singular vectors are required.
Constraint: NRU≥0.
5:   NCC – INTEGERInput
On entry: ncc, the number of columns of the matrix C. Set NCC=0 if no matrix C is supplied.
Constraint: NCC≥0.
6:   D* – REAL (KIND=nag_wp) arrayInput/Output
Note: the dimension of the array D must be at least max 1,N.
On entry: the diagonal elements of the bidiagonal matrix B.
On exit: the singular values in decreasing order of magnitude, unless INFO>0 (in which case see Section 6).
7:   E* – REAL (KIND=nag_wp) arrayInput/Output
Note: the dimension of the array E must be at least max 1,N-1.
On entry: the off-diagonal elements of the bidiagonal matrix B.
On exit: E is overwritten, but if INFO>0 see Section 6.
8:   VT LDVT* – COMPLEX (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array VT must be at least max 1,NCVT.
On entry: if NCVT>0, VT must contain an n by ncvt matrix. If the right singular vectors of B are required, ncvt=n and VT must contain the unit matrix; if the right singular vectors of A are required, VT must contain the unitary matrix PH returned by F08KTF (ZUNGBR) with VECT='P'.
On exit: the n by ncvt matrix VH or VH of right singular vectors, stored by rows.
If NCVT=0, VT is not referenced.
9:   LDVT – INTEGERInput
On entry: the first dimension of the array VT as declared in the (sub)program from which F08MSF (ZBDSQR) is called.
Constraints:
  • if NCVT>0, LDVT≥ max 1,N ;
  • otherwise LDVT≥1.
10:   U LDU* – COMPLEX (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array U must be at least max 1,N.
On entry: if NRU>0, U must contain an nru by n matrix. If the left singular vectors of B are required, nru=n and U must contain the unit matrix; if the left singular vectors of A are required, U must contain the unitary matrix Q returned by F08KTF (ZUNGBR) with VECT='Q'.
On exit: the nru by n matrix U or QU of left singular vectors, stored as columns of the matrix.
If NRU=0, U is not referenced.
11:   LDU – INTEGERInput
On entry: the first dimension of the array U as declared in the (sub)program from which F08MSF (ZBDSQR) is called.
Constraint: LDU≥ max 1,NRU .
12:   C LDC* – COMPLEX (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array C must be at least max 1,NCC.
On entry: the n by ncc matrix C if NCC>0.
On exit: C is overwritten by the matrix UH C. If NCC=0, C is not referenced.
13:   LDC – INTEGERInput
On entry: the first dimension of the array C as declared in the (sub)program from which F08MSF (ZBDSQR) is called.
Constraints:
  • if NCC>0, LDC≥ max 1,N ;
  • otherwise LDC≥1.
14:   WORK* – REAL (KIND=nag_wp) arrayWorkspace
Note: the dimension of the array WORK must be at least max 1,2×N if NCVT=0 and NRU=0 and NCC=0, and at least max 1,4×N otherwise.
15:   INFO – INTEGEROutput
On exit: INFO=0 unless the routine detects an error (see Section 6).

6 Error Indicators and Warnings

INFO<0
If INFO=-i, argument i had an illegal value. An explanatory message is output, and execution of the program is terminated.
INFO>0
The algorithm failed to converge and INFO specifies how many off-diagonals did not converge. In this case, D and E contain on exit the diagonal and off-diagonal elements, respectively, of a bidiagonal matrix orthogonally equivalent to B.

7 Accuracy

Each singular value and singular vector is computed to high relative accuracy. However, the reduction to bidiagonal form (prior to calling the routine) may exclude the possibility of obtaining high relative accuracy in the small singular values of the original matrix if its singular values vary widely in magnitude.
If σi is an exact singular value of B and σ~i is the corresponding computed value, then
σ~i - σi ≤ p m,n ε σi
where p m,n is a modestly increasing function of m and n, and ε is the machine precision. If only singular values are computed, they are computed more accurately (i.e., the function p m,n is smaller), than when some singular vectors are also computed.
If ui is an exact left singular vector of B, and u~i is the corresponding computed left singular vector, then the angle θ u~i,ui between them is bounded as follows:
θ u~i,ui ≤ p m,n ε relgapi
where relgapi is the relative gap between σi and the other singular values, defined by
relgapi = min i≠j σi - σj σi + σj .
A similar error bound holds for the right singular vectors.

8 Parallelism and Performance

F08MSF (ZBDSQR) is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
F08MSF (ZBDSQR) makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The total number of real floating-point operations is roughly proportional to n 2 if only the singular values are computed. About 12 n 2×nru additional operations are required to compute the left singular vectors and about 12 n 2×ncvt to compute the right singular vectors. The operations to compute the singular values must all be performed in scalar mode; the additional operations to compute the singular vectors can be vectorized and on some machines may be performed much faster.
The real analogue of this routine is F08MEF (DBDSQR).

10 Example

See Section 10 in F08KTF (ZUNGBR), which illustrates the use of the routine to compute the singular value decomposition of a general matrix.
F08 Chapter Contents
F08 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F08NAF (DGEEV) : NAG Library, Mark 26

F08 Chapter Contents
F08 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F08NAF (DGEEV)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F08NAF (DGEEV) computes the eigenvalues and, optionally, the left and/or right eigenvectors for an n by n real nonsymmetric matrix A.

2 Specification

SUBROUTINE F08NAF ( JOBVL, JOBVR, N, A, LDA, WR, WI, VL, LDVL, VR, LDVR, WORK, LWORK, INFO)
INTEGER | N, LDA, LDVL, LDVR, LWORK, INFO
REAL (KIND=nag_wp) | A(LDA,*), WR(*), WI(*), VL(LDVL,*), VR(LDVR,*), WORK(max(1,LWORK))
CHARACTER(1) | JOBVL, JOBVR
The routine may be called by its LAPACK name dgeev.

3 Description

The right eigenvector vj of A satisfies
A vj = λj vj
where λj is the jth eigenvalue of A. The left eigenvector uj of A satisfies
ujH A = λj ujH
where ujH denotes the conjugate transpose of uj.
The matrix A is first reduced to upper Hessenberg form by means of orthogonal similarity transformations, and the QR algorithm is then used to further reduce the matrix to upper quasi-triangular Schur form, T, with 1 by 1 and 2 by 2 blocks on the main diagonal. The eigenvalues are computed from T, the 2 by 2 blocks corresponding to complex conjugate pairs and, optionally, the eigenvectors of T are computed and backtransformed to the eigenvectors of A.

4 References

Anderson E, Bai Z, Bischof C, Blackford S, Demmel J, Dongarra J J, Du Croz J J, Greenbaum A, Hammarling S, McKenney A and Sorensen D (1999) LAPACK Users' Guide (3rd Edition) SIAM, Philadelphia http://www.netlib.org/lapack/lug
Golub G H and Van Loan C F (1996) Matrix Computations (3rd Edition) Johns Hopkins University Press, Baltimore

5 Arguments

1:   JOBVL – CHARACTER(1)Input
On entry: if JOBVL='N', the left eigenvectors of A are not computed.
If JOBVL='V', the left eigenvectors of A are computed.
Constraint: JOBVL='N' or 'V'.
2:   JOBVR – CHARACTER(1)Input
On entry: if JOBVR='N', the right eigenvectors of A are not computed.
If JOBVR='V', the right eigenvectors of A are computed.
Constraint: JOBVR='N' or 'V'.
3:   N – INTEGERInput
On entry: n, the order of the matrix A.
Constraint: N≥0.
4:   A LDA* – REAL (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array A must be at least max 1,N.
On entry: the n by n matrix A.
On exit: A has been overwritten.
5:   LDA – INTEGERInput
On entry: the first dimension of the array A as declared in the (sub)program from which F08NAF (DGEEV) is called.
Constraint: LDA≥max 1,N.
6:   WR* – REAL (KIND=nag_wp) arrayOutput
7:   WI* – REAL (KIND=nag_wp) arrayOutput
Note: the dimension of the arrays WR and WI must be at least max 1,N.
On exit: WR and WI contain the real and imaginary parts, respectively, of the computed eigenvalues. Complex conjugate pairs of eigenvalues appear consecutively with the eigenvalue having the positive imaginary part first.
8:   VL LDVL* – REAL (KIND=nag_wp) arrayOutput
Note: the second dimension of the array VL must be at least max 1,N if JOBVL='V', and at least 1 otherwise.
On exit: if JOBVL='V', the left eigenvectors uj are stored one after another in the columns of VL, in the same order as their corresponding eigenvalues. If the jth eigenvalue is real, then uj=VL:j, the jth column of VL. If the jth and j+1st eigenvalues form a complex conjugate pair, then uj=VL:j+i×VL:j+1 and u j+1=VL:j-i×VL:j+1.
If JOBVL='N', VL is not referenced.
9:   LDVL – INTEGERInput
On entry: the first dimension of the array VL as declared in the (sub)program from which F08NAF (DGEEV) is called.
Constraints:
  • if JOBVL='V', LDVL≥ max 1,N ;
  • otherwise LDVL≥1.
10:   VR LDVR* – REAL (KIND=nag_wp) arrayOutput
Note: the second dimension of the array VR must be at least max 1,N if JOBVR='V', and at least 1 otherwise.
On exit: if JOBVR='V', the right eigenvectors vj are stored one after another in the columns of VR, in the same order as their corresponding eigenvalues. If the jth eigenvalue is real, then vj=VR:j, the jth column of VR. If the jth and j+1st eigenvalues form a complex conjugate pair, then vj=VR:j+i×VR:j+1 and v j+1=VR:j-i×VR:j+1.
If JOBVR='N', VR is not referenced.
11:   LDVR – INTEGERInput
On entry: the first dimension of the array VR as declared in the (sub)program from which F08NAF (DGEEV) is called.
Constraints:
  • if JOBVR='V', LDVR≥ max 1,N ;
  • otherwise LDVR≥1.
12:   WORK max 1,LWORK – REAL (KIND=nag_wp) arrayWorkspace
On exit: if INFO=0, WORK 1 contains the minimum value of LWORK required for optimal performance.
13:   LWORK – INTEGERInput
On entry: the dimension of the array WORK as declared in the (sub)program from which F08NAF (DGEEV) is called.
If LWORK=-1, a workspace query is assumed; the routine only calculates the optimal size of the WORK array, returns this value as the first entry of the WORK array, and no error message related to LWORK is issued.
Suggested value: for optimal performance, LWORK must generally be larger than the minimum, say, 4×N+nb×N , where nb is the optimal block size of F08NEF (DGEHRD).
Constraints:
  • if JOBVL='V' or JOBVR='V', LWORK≥4×N;
  • otherwise LWORK≥max 1,3×N.
14:   INFO – INTEGEROutput
On exit: INFO=0 unless the routine detects an error (see Section 6).

6 Error Indicators and Warnings

INFO<0
If INFO=-i, argument i had an illegal value. An explanatory message is output, and execution of the program is terminated.
INFO>0
The QR algorithm failed to compute all the eigenvalues, and no eigenvectors have been computed; elements value to N of WR and WI contain eigenvalues which have converged.

7 Accuracy

The computed eigenvalues and eigenvectors are exact for a nearby matrix A+E, where
E 2 = O ε A 2 ,
and ε is the machine precision. See Section 4.8 of Anderson et al. (1999) for further details.

8 Parallelism and Performance

F08NAF (DGEEV) is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
F08NAF (DGEEV) makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

Each eigenvector is normalized to have Euclidean norm equal to unity and the element of largest absolute value real.
The total number of floating-point operations is proportional to n 3.
The complex analogue of this routine is F08NNF (ZGEEV).

10 Example

This example finds all the eigenvalues and right eigenvectors of the matrix
A = 0.35 0.45 -0.14 -0.17 0.09 0.07 -0.54 0.35 -0.44 -0.33 -0.03 0.17 0.25 -0.32 -0.13 0.11 .
Note that the block size (NB) of 64 assumed in this example is not realistic for such a small problem, but should be suitable for large problems.

10.1 Program Text

Program Text (f08nafe.f90)

10.2 Program Data

Program Data (f08nafe.d)

10.3 Program Results

Program Results (f08nafe.r)

F08 Chapter Contents
F08 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F08NBF (DGEEVX) : NAG Library, Mark 26

F08 Chapter Contents
F08 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F08NBF (DGEEVX)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F08NBF (DGEEVX) computes the eigenvalues and, optionally, the left and/or right eigenvectors for an n by n real nonsymmetric matrix A.
Optionally, it also computes a balancing transformation to improve the conditioning of the eigenvalues and eigenvectors, reciprocal condition numbers for the eigenvalues, and reciprocal condition numbers for the right eigenvectors.

2 Specification

SUBROUTINE F08NBF ( BALANC, JOBVL, JOBVR, SENSE, N, A, LDA, WR, WI, VL, LDVL, VR, LDVR, ILO, IHI, SCALE, ABNRM, RCONDE, RCONDV, WORK, LWORK, IWORK, INFO)
INTEGER | N, LDA, LDVL, LDVR, ILO, IHI, LWORK, IWORK(*), INFO
REAL (KIND=nag_wp) | A(LDA,*), WR(*), WI(*), VL(LDVL,*), VR(LDVR,*), SCALE(*), ABNRM, RCONDE(*), RCONDV(*), WORK(max(1,LWORK))
CHARACTER(1) | BALANC, JOBVL, JOBVR, SENSE
The routine may be called by its LAPACK name dgeevx.

3 Description

The right eigenvector vj of A satisfies
A vj = λj vj
where λj is the jth eigenvalue of A. The left eigenvector uj of A satisfies
ujH A = λj ujH
where ujH denotes the conjugate transpose of uj.
Balancing a matrix means permuting the rows and columns to make it more nearly upper triangular, and applying a diagonal similarity transformation DA D-1, where D is a diagonal matrix, with the aim of making its rows and columns closer in norm and the condition numbers of its eigenvalues and eigenvectors smaller. The computed reciprocal condition numbers correspond to the balanced matrix. Permuting rows and columns will not change the condition numbers (in exact arithmetic) but diagonal scaling will. For further explanation of balancing, see Section 4.8.1.2 of Anderson et al. (1999).
Following the optional balancing, the matrix A is first reduced to upper Hessenberg form by means of unitary similarity transformations, and the QR algorithm is then used to further reduce the matrix to upper triangular Schur form, T, from which the eigenvalues are computed. Optionally, the eigenvectors of T are also computed and backtransformed to those of A.

4 References

Anderson E, Bai Z, Bischof C, Blackford S, Demmel J, Dongarra J J, Du Croz J J, Greenbaum A, Hammarling S, McKenney A and Sorensen D (1999) LAPACK Users' Guide (3rd Edition) SIAM, Philadelphia http://www.netlib.org/lapack/lug
Golub G H and Van Loan C F (1996) Matrix Computations (3rd Edition) Johns Hopkins University Press, Baltimore

5 Arguments

1:   BALANC – CHARACTER(1)Input
On entry: indicates how the input matrix should be diagonally scaled and/or permuted to improve the conditioning of its eigenvalues.
BALANC='N'
Do not diagonally scale or permute.
BALANC='P'
Perform permutations to make the matrix more nearly upper triangular. Do not diagonally scale.
BALANC='S'
Diagonally scale the matrix, i.e., replace A by DA D-1, where D is a diagonal matrix chosen to make the rows and columns of A more equal in norm. Do not permute.
BALANC='B'
Both diagonally scale and permute A.
Computed reciprocal condition numbers will be for the matrix after balancing and/or permuting. Permuting does not change condition numbers (in exact arithmetic), but balancing does.
Constraint: BALANC='N', 'P', 'S' or 'B'.
2:   JOBVL – CHARACTER(1)Input
On entry: if JOBVL='N', the left eigenvectors of A are not computed.
If JOBVL='V', the left eigenvectors of A are computed.
If SENSE='E' or 'B', JOBVL must be set to JOBVL='V'.
Constraint: JOBVL='N' or 'V'.
3:   JOBVR – CHARACTER(1)Input
On entry: if JOBVR='N', the right eigenvectors of A are not computed.
If JOBVR='V', the right eigenvectors of A are computed.
If SENSE='E' or 'B', JOBVR must be set to JOBVR='V'.
Constraint: JOBVR='N' or 'V'.
4:   SENSE – CHARACTER(1)Input
On entry: determines which reciprocal condition numbers are computed.
SENSE='N'
None are computed.
SENSE='E'
Computed for eigenvalues only.
SENSE='V'
Computed for right eigenvectors only.
SENSE='B'
Computed for eigenvalues and right eigenvectors.
If SENSE='E' or 'B', both left and right eigenvectors must also be computed (JOBVL='V' and JOBVR='V').
Constraint: SENSE='N', 'E', 'V' or 'B'.
5:   N – INTEGERInput
On entry: n, the order of the matrix A.
Constraint: N≥0.
6:   A LDA* – REAL (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array A must be at least max 1,N.
On entry: the n by n matrix A.
On exit: A has been overwritten. If JOBVL='V' or JOBVR='V', A contains the real Schur form of the balanced version of the input matrix A.
7:   LDA – INTEGERInput
On entry: the first dimension of the array A as declared in the (sub)program from which F08NBF (DGEEVX) is called.
Constraint: LDA≥max 1,N.
8:   WR* – REAL (KIND=nag_wp) arrayOutput
9:   WI* – REAL (KIND=nag_wp) arrayOutput
Note: the dimension of the arrays WR and WI must be at least max 1,N.
On exit: WR and WI contain the real and imaginary parts, respectively, of the computed eigenvalues. Complex conjugate pairs of eigenvalues appear consecutively with the eigenvalue having the positive imaginary part first.
10:   VL LDVL* – REAL (KIND=nag_wp) arrayOutput
Note: the second dimension of the array VL must be at least max 1,N if JOBVL='V', and at least 1 otherwise.
On exit: if JOBVL='V', the left eigenvectors uj are stored one after another in the columns of VL, in the same order as their corresponding eigenvalues. If the jth eigenvalue is real, then uj=VL:j, the jth column of VL. If the jth and j+1st eigenvalues form a complex conjugate pair, then uj=VL:j+i×VL:j+1 and u j+1=VL:j-i×VL:j+1.
If JOBVL='N', VL is not referenced.
11:   LDVL – INTEGERInput
On entry: the first dimension of the array VL as declared in the (sub)program from which F08NBF (DGEEVX) is called.
Constraints:
  • if JOBVL='V', LDVL≥ max 1,N ;
  • otherwise LDVL≥1.
12:   VR LDVR* – REAL (KIND=nag_wp) arrayOutput
Note: the second dimension of the array VR must be at least max 1,N if JOBVR='V', and at least 1 otherwise.
On exit: if JOBVR='V', the right eigenvectors vj are stored one after another in the columns of VR, in the same order as their corresponding eigenvalues. If the jth eigenvalue is real, then vj=VR:j, the jth column of VR. If the jth and j+1st eigenvalues form a complex conjugate pair, then vj=VR:j+i×VR:j+1 and v j+1=VR:j-i×VR:j+1.
If JOBVR='N', VR is not referenced.
13:   LDVR – INTEGERInput
On entry: the first dimension of the array VR as declared in the (sub)program from which F08NBF (DGEEVX) is called.
Constraints:
  • if JOBVR='V', LDVR≥ max 1,N ;
  • otherwise LDVR≥1.
14:   ILO – INTEGEROutput
15:   IHI – INTEGEROutput
On exit: ILO and IHI are integer values determined when A was balanced. The balanced A has a ij=0 if i>j and j=1,2,…,ILO-1 or i=IHI+1,…,N.
16:   SCALE* – REAL (KIND=nag_wp) arrayOutput
Note: the dimension of the array SCALE must be at least max 1,N.
On exit: details of the permutations and scaling factors applied when balancing A.
If pj is the index of the row and column interchanged with row and column j, and dj is the scaling factor applied to row and column j, then
  • SCALE j=pj, for j=1,2,…,ILO-1;
  • SCALE j=dj, for j=ILO,…,IHI;
  • SCALE j=pj, for j=IHI+1,…,N.
The order in which the interchanges are made is N to IHI+1, then 1 to ILO-1.
17:   ABNRM – REAL (KIND=nag_wp)Output
On exit: the 1-norm of the balanced matrix (the maximum of the sum of absolute values of elements of any column).
18:   RCONDE* – REAL (KIND=nag_wp) arrayOutput
Note: the dimension of the array RCONDE must be at least max 1,N.
On exit: RCONDE j is the reciprocal condition number of the jth eigenvalue.
19:   RCONDV* – REAL (KIND=nag_wp) arrayOutput
Note: the dimension of the array RCONDV must be at least max 1,N.
On exit: RCONDV j is the reciprocal condition number of the jth right eigenvector.
20:   WORK max 1,LWORK – REAL (KIND=nag_wp) arrayWorkspace
On exit: if INFO=0, WORK 1 contains the minimum value of LWORK required for optimal performance.
21:   LWORK – INTEGERInput
On entry: the dimension of the array WORK as declared in the (sub)program from which F08NBF (DGEEVX) is called.
If LWORK=-1, a workspace query is assumed; the routine only calculates the optimal size of the WORK array, returns this value as the first entry of the WORK array, and no error message related to LWORK is issued.
Suggested value: for optimal performance, LWORK must generally be larger than the minimum, increase LWORK by, say, N×nb , where nb is the optimal block size for F08NEF (DGEHRD).
Constraints:
  • if JOBVL='N' and JOBVR='N',
    • if SENSE='N', LWORK≥max 1,2×N;
    • otherwise LWORK≥max 1,N 2+6×N;
  • if JOBVL='V' or JOBVR='V',
    • if SENSE='N' or 'E', LWORK≥max 1,3×N;
    • otherwise LWORK≥max 1,N 2+6×N.
22:   IWORK* – INTEGER arrayWorkspace
Note: the dimension of the array IWORK must be at least max 1,2×N-1.
If SENSE='N' or 'E', IWORK is not referenced.
23:   INFO – INTEGEROutput
On exit: INFO=0 unless the routine detects an error (see Section 6).

6 Error Indicators and Warnings

INFO<0
If INFO=-i, argument i had an illegal value. An explanatory message is output, and execution of the program is terminated.
INFO>0
If INFO=i, the QR algorithm failed to compute all the eigenvalues, and no eigenvectors or condition numbers have been computed; elements 1:ILO-1 and i+1:N of WR and WI contain eigenvalues which have converged.

7 Accuracy

The computed eigenvalues and eigenvectors are exact for a nearby matrix A+E, where
E 2 = O ε A 2 ,
and ε is the machine precision. See Section 4.8 of Anderson et al. (1999) for further details.

8 Parallelism and Performance

F08NBF (DGEEVX) is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
F08NBF (DGEEVX) makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

Each eigenvector is normalized to have Euclidean norm equal to unity and the element of largest absolute value real.
The total number of floating-point operations is proportional to n 3.
The complex analogue of this routine is F08NPF (ZGEEVX).

10 Example

This example finds all the eigenvalues and right eigenvectors of the matrix
A = 0.35 0.45 -0.14 -0.17 0.09 0.07 -0.54 0.35 -0.44 -0.33 -0.03 0.17 0.25 -0.32 -0.13 0.11 ,
together with estimates of the condition number and forward error bounds for each eigenvalue and eigenvector. The option to balance the matrix is used. In order to compute the condition numbers of the eigenvalues, the left eigenvectors also have to be computed, but they are not printed out in this example.
Note that the block size (NB) of 64 assumed in this example is not realistic for such a small problem, but should be suitable for large problems.

10.1 Program Text

Program Text (f08nbfe.f90)

10.2 Program Data

Program Data (f08nbfe.d)

10.3 Program Results

Program Results (f08nbfe.r)

F08 Chapter Contents
F08 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F08NEF (DGEHRD) : NAG Library, Mark 26

F08 Chapter Contents
F08 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F08NEF (DGEHRD)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F08NEF (DGEHRD) reduces a real general matrix to Hessenberg form.

2 Specification

SUBROUTINE F08NEF ( N, ILO, IHI, A, LDA, TAU, WORK, LWORK, INFO)
INTEGER | N, ILO, IHI, LDA, LWORK, INFO
REAL (KIND=nag_wp) | A(LDA,*), TAU(*), WORK(max(1,LWORK))
The routine may be called by its LAPACK name dgehrd.

3 Description

F08NEF (DGEHRD) reduces a real general matrix A to upper Hessenberg form H by an orthogonal similarity transformation: A=QH QT.
The matrix Q is not formed explicitly, but is represented as a product of elementary reflectors (see the F08 Chapter Introduction for details). Routines are provided to work with Q in this representation (see Section 9).
The routine can take advantage of a previous call to F08NHF (DGEBAL), which may produce a matrix with the structure:
A 11 A 12 A 13 A 22 A 23 A 33
where A 11 and A 33 are upper triangular. If so, only the central diagonal block A 22, in rows and columns ilo to ihi, needs to be reduced to Hessenberg form (the blocks A 12 and A 23 will also be affected by the reduction). Therefore the values of ilo and ihi determined by F08NHF (DGEBAL) can be supplied to the routine directly. If F08NHF (DGEBAL) has not previously been called however, then ilo must be set to 1 and ihi to n.

4 References

Golub G H and Van Loan C F (1996) Matrix Computations (3rd Edition) Johns Hopkins University Press, Baltimore

5 Arguments

1:   N – INTEGERInput
On entry: n, the order of the matrix A.
Constraint: N≥0.
2:   ILO – INTEGERInput
3:   IHI – INTEGERInput
On entry: if A has been output by F08NHF (DGEBAL), then ILO and IHI must contain the values returned by that routine. Otherwise, ILO must be set to 1 and IHI to N.
Constraints:
  • if N>0, 1≤ ILO≤ IHI≤ N ;
  • if N=0, ILO=1 and IHI=0.
4:   A LDA* – REAL (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array A must be at least max 1,N.
On entry: the n by n general matrix A.
On exit: A is overwritten by the upper Hessenberg matrix H and details of the orthogonal matrix Q.
5:   LDA – INTEGERInput
On entry: the first dimension of the array A as declared in the (sub)program from which F08NEF (DGEHRD) is called.
Constraint: LDA≥max 1,N.
6:   TAU* – REAL (KIND=nag_wp) arrayOutput
Note: the dimension of the array TAU must be at least max 1,N-1.
On exit: further details of the orthogonal matrix Q.
7:   WORK max 1,LWORK – REAL (KIND=nag_wp) arrayWorkspace
On exit: if INFO=0, WORK 1 contains the minimum value of LWORK required for optimal performance.
8:   LWORK – INTEGERInput
On entry: the dimension of the array WORK as declared in the (sub)program from which F08NEF (DGEHRD) is called.
If LWORK=-1, a workspace query is assumed; the routine only calculates the optimal size of the WORK array, returns this value as the first entry of the WORK array, and no error message related to LWORK is issued.
Suggested value: for optimal performance, LWORK≥N×nb, where nb is the optimal block size.
Constraint: LWORK≥max 1,N or LWORK=-1.
9:   INFO – INTEGEROutput
On exit: INFO=0 unless the routine detects an error (see Section 6).

6 Error Indicators and Warnings

INFO<0
If INFO=-i, argument i had an illegal value.
If INFO=-999, dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.
An explanatory message is output, and execution of the program is terminated.

7 Accuracy

The computed Hessenberg matrix H is exactly similar to a nearby matrix A+E, where
E 2 ≤ c n ε A 2 ,
c n is a modestly increasing function of n, and ε is the machine precision.
The elements of H themselves may be sensitive to small perturbations in A or to rounding errors in the computation, but this does not affect the stability of the eigenvalues, eigenvectors or Schur factorization.

8 Parallelism and Performance

F08NEF (DGEHRD) is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
F08NEF (DGEHRD) makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The total number of floating-point operations is approximately 23 q 2 2 q+3 n, where q=ihi-ilo; if ilo=1 and ihi=n, the number is approximately 103 n 3.
To form the orthogonal matrix Q F08NEF (DGEHRD) may be followed by a call to F08NFF (DORGHR):
CALL DORGHR(N,ILO,IHI,A,LDA,TAU,WORK,LWORK,INFO)
To apply Q to an m by n real matrix C F08NEF (DGEHRD) may be followed by a call to F08NGF (DORMHR). For example,
CALL DORMHR('Left','No Transpose',M,N,ILO,IHI,A,LDA,TAU,C,LDC, &
              WORK,LWORK,INFO)
forms the matrix product QC.
The complex analogue of this routine is F08NSF (ZGEHRD).

10 Example

This example computes the upper Hessenberg form of the matrix A, where
A = 0.35 0.45 -0.14 -0.17 0.09 0.07 -0.54 0.35 -0.44 -0.33 -0.03 0.17 0.25 -0.32 -0.13 0.11 .

10.1 Program Text

Program Text (f08nefe.f90)

10.2 Program Data

Program Data (f08nefe.d)

10.3 Program Results

Program Results (f08nefe.r)

F08 Chapter Contents
F08 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F08NFF (DORGHR) : NAG Library, Mark 26

F08 Chapter Contents
F08 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F08NFF (DORGHR)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F08NFF (DORGHR) generates the real orthogonal matrix Q which was determined by F08NEF (DGEHRD) when reducing a real general matrix A to Hessenberg form.

2 Specification

SUBROUTINE F08NFF ( N, ILO, IHI, A, LDA, TAU, WORK, LWORK, INFO)
INTEGER | N, ILO, IHI, LDA, LWORK, INFO
REAL (KIND=nag_wp) | A(LDA,*), TAU(*), WORK(max(1,LWORK))
The routine may be called by its LAPACK name dorghr.

3 Description

F08NFF (DORGHR) is intended to be used following a call to F08NEF (DGEHRD), which reduces a real general matrix A to upper Hessenberg form H by an orthogonal similarity transformation: A=QH QT. F08NEF (DGEHRD) represents the matrix Q as a product of ihi-ilo elementary reflectors. Here ilo and ihi are values determined by F08NHF (DGEBAL) when balancing the matrix; if the matrix has not been balanced, ilo=1 and ihi=n.
This routine may be used to generate Q explicitly as a square matrix. Q has the structure:
Q = I 0 0 0 Q 22 0 0 0 I
where Q 22 occupies rows and columns ilo to ihi.

4 References

Golub G H and Van Loan C F (1996) Matrix Computations (3rd Edition) Johns Hopkins University Press, Baltimore

5 Arguments

1:   N – INTEGERInput
On entry: n, the order of the matrix Q.
Constraint: N≥0.
2:   ILO – INTEGERInput
3:   IHI – INTEGERInput
On entry: these must be the same arguments ILO and IHI, respectively, as supplied to F08NEF (DGEHRD).
Constraints:
  • if N>0, 1≤ ILO≤ IHI≤ N ;
  • if N=0, ILO=1 and IHI=0.
4:   A LDA* – REAL (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array A must be at least max 1,N.
On entry: details of the vectors which define the elementary reflectors, as returned by F08NEF (DGEHRD).
On exit: the n by n orthogonal matrix Q.
5:   LDA – INTEGERInput
On entry: the first dimension of the array A as declared in the (sub)program from which F08NFF (DORGHR) is called.
Constraint: LDA≥max 1,N.
6:   TAU* – REAL (KIND=nag_wp) arrayInput
Note: the dimension of the array TAU must be at least max 1,N-1.
On entry: further details of the elementary reflectors, as returned by F08NEF (DGEHRD).
7:   WORK max 1,LWORK – REAL (KIND=nag_wp) arrayWorkspace
On exit: if INFO=0, WORK 1 contains the minimum value of LWORK required for optimal performance.
8:   LWORK – INTEGERInput
On entry: the dimension of the array WORK as declared in the (sub)program from which F08NFF (DORGHR) is called, unless LWORK=-1, in which case a workspace query is assumed and the routine only calculates the optimal dimension of WORK (using the formula given below).
Suggested value: for optimal performance LWORK should be at least IHI-ILO×nb, where nb is the block size.
Constraint: LWORK≥max 1,IHI-ILO or LWORK=-1.
9:   INFO – INTEGEROutput
On exit: INFO=0 unless the routine detects an error (see Section 6).

6 Error Indicators and Warnings

INFO<0
If INFO=-i, argument i had an illegal value. An explanatory message is output, and execution of the program is terminated.

7 Accuracy

The computed matrix Q differs from an exactly orthogonal matrix by a matrix E such that
E 2 = O ε ,
where ε is the machine precision.

8 Parallelism and Performance

F08NFF (DORGHR) is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
F08NFF (DORGHR) makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The total number of floating-point operations is approximately 43 q 3, where q=ihi-ilo.
The complex analogue of this routine is F08NTF (ZUNGHR).

10 Example

This example computes the Schur factorization of the matrix A, where
A = 0.35 0.45 -0.14 -0.17 0.09 0.07 -0.54 0.35 -0.44 -0.33 -0.03 0.17 0.25 -0.32 -0.13 0.11 .
Here A is general and must first be reduced to Hessenberg form by F08NEF (DGEHRD). The program then calls F08NFF (DORGHR) to form Q, and passes this matrix to F08PEF (DHSEQR) which computes the Schur factorization of A.

10.1 Program Text

Program Text (f08nffe.f90)

10.2 Program Data

Program Data (f08nffe.d)

10.3 Program Results

Program Results (f08nffe.r)

F08 Chapter Contents
F08 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F08NGF (DORMHR) : NAG Library, Mark 26

F08 Chapter Contents
F08 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F08NGF (DORMHR)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F08NGF (DORMHR) multiplies an arbitrary real matrix C by the real orthogonal matrix Q which was determined by F08NEF (DGEHRD) when reducing a real general matrix to Hessenberg form.

2 Specification

SUBROUTINE F08NGF ( SIDE, TRANS, M, N, ILO, IHI, A, LDA, TAU, C, LDC, WORK, LWORK, INFO)
INTEGER | M, N, ILO, IHI, LDA, LDC, LWORK, INFO
REAL (KIND=nag_wp) | A(LDA,*), TAU(*), C(LDC,*), WORK(max(1,LWORK))
CHARACTER(1) | SIDE, TRANS
The routine may be called by its LAPACK name dormhr.

3 Description

F08NGF (DORMHR) is intended to be used following a call to F08NEF (DGEHRD), which reduces a real general matrix A to upper Hessenberg form H by an orthogonal similarity transformation: A=QH QT. F08NEF (DGEHRD) represents the matrix Q as a product of ihi-ilo elementary reflectors. Here ilo and ihi are values determined by F08NHF (DGEBAL) when balancing the matrix; if the matrix has not been balanced, ilo=1 and ihi=n.
This routine may be used to form one of the matrix products
QC , QT C , CQ ​ or ​ C QT ,
overwriting the result on C (which may be any real rectangular matrix).
A common application of this routine is to transform a matrix V of eigenvectors of H to the matrix QV of eigenvectors of A.

4 References

Golub G H and Van Loan C F (1996) Matrix Computations (3rd Edition) Johns Hopkins University Press, Baltimore

5 Arguments

1:   SIDE – CHARACTER(1)Input
On entry: indicates how Q or QT is to be applied to C.
SIDE='L'
Q or QT is applied to C from the left.
SIDE='R'
Q or QT is applied to C from the right.
Constraint: SIDE='L' or 'R'.
2:   TRANS – CHARACTER(1)Input
On entry: indicates whether Q or QT is to be applied to C.
TRANS='N'
Q is applied to C.
TRANS='T'
QT is applied to C.
Constraint: TRANS='N' or 'T'.
3:   M – INTEGERInput
On entry: m, the number of rows of the matrix C; m is also the order of Q if SIDE='L'.
Constraint: M≥0.
4:   N – INTEGERInput
On entry: n, the number of columns of the matrix C; n is also the order of Q if SIDE='R'.
Constraint: N≥0.
5:   ILO – INTEGERInput
6:   IHI – INTEGERInput
On entry: these must be the same arguments ILO and IHI, respectively, as supplied to F08NEF (DGEHRD).
Constraints:
  • if SIDE='L' and M>0, 1≤ ILO≤ IHI≤ M ;
  • if SIDE='L' and M=0, ILO=1 and IHI=0;
  • if SIDE='R' and N>0, 1≤ ILO≤ IHI≤ N ;
  • if SIDE='R' and N=0, ILO=1 and IHI=0.
7:   A LDA* – REAL (KIND=nag_wp) arrayInput
Note: the second dimension of the array A must be at least max 1,M if SIDE='L' and at least max 1,N if SIDE='R'.
On entry: details of the vectors which define the elementary reflectors, as returned by F08NEF (DGEHRD).
8:   LDA – INTEGERInput
On entry: the first dimension of the array A as declared in the (sub)program from which F08NGF (DORMHR) is called.
Constraints:
  • if SIDE='L', LDA≥ max 1,M ;
  • if SIDE='R', LDA≥ max 1,N .
9:   TAU* – REAL (KIND=nag_wp) arrayInput
Note: the dimension of the array TAU must be at least max 1,M-1 if SIDE='L' and at least max 1,N-1 if SIDE='R'.
On entry: further details of the elementary reflectors, as returned by F08NEF (DGEHRD).
10:   C LDC* – REAL (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array C must be at least max 1,N.
On entry: the m by n matrix C.
On exit: C is overwritten by QC or QT C or CQ or C QT as specified by SIDE and TRANS.
11:   LDC – INTEGERInput
On entry: the first dimension of the array C as declared in the (sub)program from which F08NGF (DORMHR) is called.
Constraint: LDC≥max 1,M.
12:   WORK max 1,LWORK – REAL (KIND=nag_wp) arrayWorkspace
On exit: if INFO=0, WORK 1 contains the minimum value of LWORK required for optimal performance.
13:   LWORK – INTEGERInput
On entry: the dimension of the array WORK as declared in the (sub)program from which F08NGF (DORMHR) is called.
If LWORK=-1, a workspace query is assumed; the routine only calculates the optimal size of the WORK array, returns this value as the first entry of the WORK array, and no error message related to LWORK is issued.
Suggested value: for optimal performance, LWORK≥N×nb if SIDE='L' and at least M×nb if SIDE='R', where nb is the optimal block size.
Constraints:
  • if SIDE='L', LWORK≥max 1,N or LWORK=-1;
  • if SIDE='R', LWORK≥max 1,M or LWORK=-1.
14:   INFO – INTEGEROutput
On exit: INFO=0 unless the routine detects an error (see Section 6).

6 Error Indicators and Warnings

INFO<0
If INFO=-i, argument i had an illegal value. An explanatory message is output, and execution of the program is terminated.

7 Accuracy

The computed result differs from the exact result by a matrix E such that
E 2 = O ε C 2 ,
where ε is the machine precision.

8 Parallelism and Performance

F08NGF (DORMHR) is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
F08NGF (DORMHR) makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The total number of floating-point operations is approximately 2 n q 2 if SIDE='L' and 2 m q 2 if SIDE='R', where q=ihi-ilo.
The complex analogue of this routine is F08NUF (ZUNMHR).

10 Example

This example computes all the eigenvalues of the matrix A, where
A = 0.35 0.45 -0.14 -0.17 0.09 0.07 -0.54 0.35 -0.44 -0.33 -0.03 0.17 0.25 -0.32 -0.13 0.11 ,
and those eigenvectors which correspond to eigenvalues λ such that Re λ<0. Here A is general and must first be reduced to upper Hessenberg form H by F08NEF (DGEHRD). The program then calls F08PEF (DHSEQR) to compute the eigenvalues, and F08PKF (DHSEIN) to compute the required eigenvectors of H by inverse iteration. Finally F08NGF (DORMHR) is called to transform the eigenvectors of H back to eigenvectors of the original matrix A.

10.1 Program Text

Program Text (f08ngfe.f90)

10.2 Program Data

Program Data (f08ngfe.d)

10.3 Program Results

Program Results (f08ngfe.r)

F08 Chapter Contents
F08 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F08NHF (DGEBAL) : NAG Library, Mark 26

F08 Chapter Contents
F08 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F08NHF (DGEBAL)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F08NHF (DGEBAL) balances a real general matrix in order to improve the accuracy of computed eigenvalues and/or eigenvectors.

2 Specification

SUBROUTINE F08NHF ( JOB, N, A, LDA, ILO, IHI, SCALE, INFO)
INTEGER | N, LDA, ILO, IHI, INFO
REAL (KIND=nag_wp) | A(LDA,*), SCALE(N)
CHARACTER(1) | JOB
The routine may be called by its LAPACK name dgebal.

3 Description

F08NHF (DGEBAL) balances a real general matrix A. The term ‘balancing’ covers two steps, each of which involves a similarity transformation of A. The routine can perform either or both of these steps.
1. The routine first attempts to permute A to block upper triangular form by a similarity transformation:
PA PT = A′ = A 11′ A 12′ A 13′ 0 A 22′ A 23′ 0 0 A 33′
where P is a permutation matrix, and A 11′ and A 33′ are upper triangular. Then the diagonal elements of A 11′ and A 33′ are eigenvalues of A. The rest of the eigenvalues of A are the eigenvalues of the central diagonal block A 22′, in rows and columns ilo to ihi. Subsequent operations to compute the eigenvalues of A (or its Schur factorization) need only be applied to these rows and columns; this can save a significant amount of work if ilo>1 and ihi<n. If no suitable permutation exists (as is often the case), the routine sets ilo=1 and ihi=n, and A 22′ is the whole of A.
2. The routine applies a diagonal similarity transformation to A′, to make the rows and columns of A 22′ as close in norm as possible:
A′′ = D A′D-1 = I 0 0 0 D 22 0 0 0 I A 11′ A 12′ A 13′ 0 A 22′ A 23′ 0 0 A 33′ I 0 0 0 D 22-1 0 0 0 I .
This scaling can reduce the norm of the matrix (i.e., A 22′′<A 22′) and hence reduce the effect of rounding errors on the accuracy of computed eigenvalues and eigenvectors.

4 References

Golub G H and Van Loan C F (1996) Matrix Computations (3rd Edition) Johns Hopkins University Press, Baltimore

5 Arguments

1:   JOB – CHARACTER(1)Input
On entry: indicates whether A is to be permuted and/or scaled (or neither).
JOB='N'
A is neither permuted nor scaled (but values are assigned to ILO, IHI and SCALE).
JOB='P'
A is permuted but not scaled.
JOB='S'
A is scaled but not permuted.
JOB='B'
A is both permuted and scaled.
Constraint: JOB='N', 'P', 'S' or 'B'.
2:   N – INTEGERInput
On entry: n, the order of the matrix A.
Constraint: N≥0.
3:   A LDA* – REAL (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array A must be at least max 1,N.
On entry: the n by n matrix A.
On exit: A is overwritten by the balanced matrix. If JOB='N', A is not referenced.
4:   LDA – INTEGERInput
On entry: the first dimension of the array A as declared in the (sub)program from which F08NHF (DGEBAL) is called.
Constraint: LDA≥max 1,N.
5:   ILO – INTEGEROutput
6:   IHI – INTEGEROutput
On exit: the values ilo and ihi such that on exit A ij is zero if i>j and 1≤j<ilo or ihi<i≤n.
If JOB='N' or 'S', ilo=1 and ihi=n.
7:   SCALE N – REAL (KIND=nag_wp) arrayOutput
On exit: details of the permutations and scaling factors applied to A. More precisely, if pj is the index of the row and column interchanged with row and column j and dj is the scaling factor used to balance row and column j then
SCALE j = pj, j=1,2,…,ilo-1 dj, j=ilo,ilo+1,…,ihi  and pj, j=ihi+1,ihi+2,…,n.
The order in which the interchanges are made is n to ihi+1 then 1 to ilo-1.
8:   INFO – INTEGEROutput
On exit: INFO=0 unless the routine detects an error (see Section 6).

6 Error Indicators and Warnings

INFO<0
If INFO=-i, argument i had an illegal value. An explanatory message is output, and execution of the program is terminated.

7 Accuracy

The errors are negligible.

8 Parallelism and Performance

F08NHF (DGEBAL) makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

If the matrix A is balanced by F08NHF (DGEBAL), then any eigenvectors computed subsequently are eigenvectors of the matrix A′′ (see Section 3) and hence F08NJF (DGEBAK) must then be called to transform them back to eigenvectors of A.
If the Schur vectors of A are required, then this routine must not be called with JOB='S' or 'B', because then the balancing transformation is not orthogonal. If this routine is called with JOB='P', then any Schur vectors computed subsequently are Schur vectors of the matrix A′′, and F08NJF (DGEBAK) must be called (with SIDE='R') to transform them back to Schur vectors of A.
The total number of floating-point operations is approximately proportional to n 2.
The complex analogue of this routine is F08NVF (ZGEBAL).

10 Example

This example computes all the eigenvalues and right eigenvectors of the matrix A, where
A = 5.14 0.91 0.00 -32.80 0.91 0.20 0.00 34.50 1.90 0.80 -0.40 -3.00 -0.33 0.35 0.00 0.66 .
The program first calls F08NHF (DGEBAL) to balance the matrix; it then computes the Schur factorization of the balanced matrix, by reduction to Hessenberg form and the QR algorithm. Then it calls F08QKF (DTREVC) to compute the right eigenvectors of the balanced matrix, and finally calls F08NJF (DGEBAK) to transform the eigenvectors back to eigenvectors of the original matrix A.

10.1 Program Text

Program Text (f08nhfe.f90)

10.2 Program Data

Program Data (f08nhfe.d)

10.3 Program Results

Program Results (f08nhfe.r)

F08 Chapter Contents
F08 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F08NJF (DGEBAK) : NAG Library, Mark 26

F08 Chapter Contents
F08 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F08NJF (DGEBAK)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
10 Example

1 Purpose

F08NJF (DGEBAK) transforms eigenvectors of a balanced matrix to those of the original real nonsymmetric matrix.

2 Specification

SUBROUTINE F08NJF ( JOB, SIDE, N, ILO, IHI, SCALE, M, V, LDV, INFO)
INTEGER | N, ILO, IHI, M, LDV, INFO
REAL (KIND=nag_wp) | SCALE(*), V(LDV,*)
CHARACTER(1) | JOB, SIDE
The routine may be called by its LAPACK name dgebak.

3 Description

F08NJF (DGEBAK) is intended to be used after a real nonsymmetric matrix A has been balanced by F08NHF (DGEBAL), and eigenvectors of the balanced matrix A 22′′ have subsequently been computed.
For a description of balancing, see the document for F08NHF (DGEBAL). The balanced matrix A′′ is obtained as A′′=DPA PTD-1, where P is a permutation matrix and D is a diagonal scaling matrix. This routine transforms left or right eigenvectors as follows:
  • if x is a right eigenvector of A′′, PTD-1 x is a right eigenvector of A;
  • if y is a left eigenvector of A′′, PT Dy is a left eigenvector of A.

4 References

None.

5 Arguments

1:   JOB – CHARACTER(1)Input
On entry: this must be the same argument JOB as supplied to F08NHF (DGEBAL).
Constraint: JOB='N', 'P', 'S' or 'B'.
2:   SIDE – CHARACTER(1)Input
On entry: indicates whether left or right eigenvectors are to be transformed.
SIDE='L'
The left eigenvectors are transformed.
SIDE='R'
The right eigenvectors are transformed.
Constraint: SIDE='L' or 'R'.
3:   N – INTEGERInput
On entry: n, the number of rows of the matrix of eigenvectors.
Constraint: N≥0.
4:   ILO – INTEGERInput
5:   IHI – INTEGERInput
On entry: the values ilo and ihi, as returned by F08NHF (DGEBAL).
Constraints:
  • if N>0, 1≤ ILO≤ IHI≤ N ;
  • if N=0, ILO=1 and IHI=0.
6:   SCALE* – REAL (KIND=nag_wp) arrayInput
Note: the dimension of the array SCALE must be at least max 1,N.
On entry: details of the permutations and/or the scaling factors used to balance the original real nonsymmetric matrix, as returned by F08NHF (DGEBAL).
7:   M – INTEGERInput
On entry: m, the number of columns of the matrix of eigenvectors.
Constraint: M≥0.
8:   V LDV* – REAL (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array V must be at least max 1,M.
On entry: the matrix of left or right eigenvectors to be transformed.
On exit: the transformed eigenvectors.
9:   LDV – INTEGERInput
On entry: the first dimension of the array V as declared in the (sub)program from which F08NJF (DGEBAK) is called.
Constraint: LDV≥ max 1,N .
10:   INFO – INTEGEROutput
On exit: INFO=0 unless the routine detects an error (see Section 6).

6 Error Indicators and Warnings

INFO<0
If INFO=-i, argument i had an illegal value. An explanatory message is output, and execution of the program is terminated.

7 Accuracy

The errors are negligible.

8 Parallelism and Performance

F08NJF (DGEBAK) makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The total number of floating-point operations is approximately proportional to nm.
The complex analogue of this routine is F08NWF (ZGEBAK).

10 Example

See Section 10 in F08NHF (DGEBAL).
F08 Chapter Contents
F08 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F08NNF (ZGEEV) : NAG Library, Mark 26

F08 Chapter Contents
F08 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F08NNF (ZGEEV)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F08NNF (ZGEEV) computes the eigenvalues and, optionally, the left and/or right eigenvectors for an n by n complex nonsymmetric matrix A.

2 Specification

SUBROUTINE F08NNF ( JOBVL, JOBVR, N, A, LDA, W, VL, LDVL, VR, LDVR, WORK, LWORK, RWORK, INFO)
INTEGER | N, LDA, LDVL, LDVR, LWORK, INFO
REAL (KIND=nag_wp) | RWORK(*)
COMPLEX (KIND=nag_wp) | A(LDA,*), W(*), VL(LDVL,*), VR(LDVR,*), WORK(max(1,LWORK))
CHARACTER(1) | JOBVL, JOBVR
The routine may be called by its LAPACK name zgeev.

3 Description

The right eigenvector vj of A satisfies
A vj = λj vj
where λj is the jth eigenvalue of A. The left eigenvector uj of A satisfies
ujH A = λj ujH
where ujH denotes the conjugate transpose of uj.
The matrix A is first reduced to upper Hessenberg form by means of unitary similarity transformations, and the QR algorithm is then used to further reduce the matrix to upper triangular Schur form, T, from which the eigenvalues are computed. Optionally, the eigenvectors of T are also computed and backtransformed to those of A.

4 References

Anderson E, Bai Z, Bischof C, Blackford S, Demmel J, Dongarra J J, Du Croz J J, Greenbaum A, Hammarling S, McKenney A and Sorensen D (1999) LAPACK Users' Guide (3rd Edition) SIAM, Philadelphia http://www.netlib.org/lapack/lug
Golub G H and Van Loan C F (1996) Matrix Computations (3rd Edition) Johns Hopkins University Press, Baltimore

5 Arguments

1:   JOBVL – CHARACTER(1)Input
On entry: if JOBVL='N', the left eigenvectors of A are not computed.
If JOBVL='V', the left eigenvectors of A are computed.
Constraint: JOBVL='N' or 'V'.
2:   JOBVR – CHARACTER(1)Input
On entry: if JOBVR='N', the right eigenvectors of A are not computed.
If JOBVR='V', the right eigenvectors of A are computed.
Constraint: JOBVR='N' or 'V'.
3:   N – INTEGERInput
On entry: n, the order of the matrix A.
Constraint: N≥0.
4:   A LDA* – COMPLEX (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array A must be at least max 1,N.
On entry: the n by n matrix A.
On exit: A has been overwritten.
5:   LDA – INTEGERInput
On entry: the first dimension of the array A as declared in the (sub)program from which F08NNF (ZGEEV) is called.
Constraint: LDA≥max 1,N.
6:   W* – COMPLEX (KIND=nag_wp) arrayOutput
Note: the dimension of the array W must be at least max 1,N.
On exit: contains the computed eigenvalues.
7:   VL LDVL* – COMPLEX (KIND=nag_wp) arrayOutput
Note: the second dimension of the array VL must be at least max 1,N if JOBVL='V', and at least 1 otherwise.
On exit: if JOBVL='V', the left eigenvectors uj are stored one after another in the columns of VL, in the same order as their corresponding eigenvalues; that is uj=VL:j, the jth column of VL.
If JOBVL='N', VL is not referenced.
8:   LDVL – INTEGERInput
On entry: the first dimension of the array VL as declared in the (sub)program from which F08NNF (ZGEEV) is called.
Constraints:
  • if JOBVL='V', LDVL≥ max 1,N ;
  • otherwise LDVL≥1.
9:   VR LDVR* – COMPLEX (KIND=nag_wp) arrayOutput
Note: the second dimension of the array VR must be at least max 1,N if JOBVR='V', and at least 1 otherwise.
On exit: if JOBVR='V', the right eigenvectors vj are stored one after another in the columns of VR, in the same order as their corresponding eigenvalues; that is vj=VR:j, the jth column of VR.
If JOBVR='N', VR is not referenced.
10:   LDVR – INTEGERInput
On entry: the first dimension of the array VR as declared in the (sub)program from which F08NNF (ZGEEV) is called.
Constraints:
  • if JOBVR='V', LDVR≥ max 1,N ;
  • otherwise LDVR≥1.
11:   WORK max 1,LWORK – COMPLEX (KIND=nag_wp) arrayWorkspace
On exit: if INFO=0, the real part of WORK 1 contains the minimum value of LWORK required for optimal performance.
12:   LWORK – INTEGERInput
On entry: the dimension of the array WORK as declared in the (sub)program from which F08NNF (ZGEEV) is called.
If LWORK=-1, a workspace query is assumed; the routine only calculates the optimal size of the WORK array, returns this value as the first entry of the WORK array, and no error message related to LWORK is issued.
Suggested value: for optimal performance, LWORK should be generally larger than the minimum, say N+nb×N , where nb is the optimal block size for F08NSF (ZGEHRD).
Constraint: LWORK≥max 1,2×N.
13:   RWORK* – REAL (KIND=nag_wp) arrayWorkspace
Note: the dimension of the array RWORK must be at least max 1,2×N.
14:   INFO – INTEGEROutput
On exit: INFO=0 unless the routine detects an error (see Section 6).

6 Error Indicators and Warnings

INFO<0
If INFO=-i, argument i had an illegal value. An explanatory message is output, and execution of the program is terminated.
INFO>0
If INFO=i, the QR algorithm failed to compute all the eigenvalues, and no eigenvectors have been computed; elements i+1:N of W contain eigenvalues which have converged.

7 Accuracy

The computed eigenvalues and eigenvectors are exact for a nearby matrix A+E, where
E 2 = O ε A 2 ,
and ε is the machine precision. See Section 4.8 of Anderson et al. (1999) for further details.

8 Parallelism and Performance

F08NNF (ZGEEV) is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
F08NNF (ZGEEV) makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

Each eigenvector is normalized to have Euclidean norm equal to unity and the element of largest absolute value real.
The total number of floating-point operations is proportional to n 3.
The real analogue of this routine is F08NAF (DGEEV).

10 Example

This example finds all the eigenvalues and right eigenvectors of the matrix
A = -3.97-5.04 i -4.11+3.70 i -0.34+1.01 i 1.29-0.86 i 0.34-1.50 i 1.52-0.43 i 1.88-5.38 i 3.36+0.65 i 3.31-3.85 i 2.50+3.45 i 0.88-1.08 i 0.64-1.48 i -1.10+0.82 i 1.81-1.59 i 3.25+1.33 i 1.57-3.44 i .
Note that the block size (NB) of 64 assumed in this example is not realistic for such a small problem, but should be suitable for large problems.

10.1 Program Text

Program Text (f08nnfe.f90)

10.2 Program Data

Program Data (f08nnfe.d)

10.3 Program Results

Program Results (f08nnfe.r)

F08 Chapter Contents
F08 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F08NPF (ZGEEVX) : NAG Library, Mark 26

F08 Chapter Contents
F08 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F08NPF (ZGEEVX)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F08NPF (ZGEEVX) computes the eigenvalues and, optionally, the left and/or right eigenvectors for an n by n complex nonsymmetric matrix A.
Optionally, it also computes a balancing transformation to improve the conditioning of the eigenvalues and eigenvectors, reciprocal condition numbers for the eigenvalues, and reciprocal condition numbers for the right eigenvectors.

2 Specification

SUBROUTINE F08NPF ( BALANC, JOBVL, JOBVR, SENSE, N, A, LDA, W, VL, LDVL, VR, LDVR, ILO, IHI, SCALE, ABNRM, RCONDE, RCONDV, WORK, LWORK, RWORK, INFO)
INTEGER | N, LDA, LDVL, LDVR, ILO, IHI, LWORK, INFO
REAL (KIND=nag_wp) | SCALE(*), ABNRM, RCONDE(*), RCONDV(*), RWORK(*)
COMPLEX (KIND=nag_wp) | A(LDA,*), W(*), VL(LDVL,*), VR(LDVR,*), WORK(max(1,LWORK))
CHARACTER(1) | BALANC, JOBVL, JOBVR, SENSE
The routine may be called by its LAPACK name zgeevx.

3 Description

The right eigenvector vj of A satisfies
A vj = λj vj
where λj is the jth eigenvalue of A. The left eigenvector uj of A satisfies
ujH A = λj ujH
where ujH denotes the conjugate transpose of uj.
Balancing a matrix means permuting the rows and columns to make it more nearly upper triangular, and applying a diagonal similarity transformation DA D-1, where D is a diagonal matrix, with the aim of making its rows and columns closer in norm and the condition numbers of its eigenvalues and eigenvectors smaller. The computed reciprocal condition numbers correspond to the balanced matrix. Permuting rows and columns will not change the condition numbers (in exact arithmetic) but diagonal scaling will. For further explanation of balancing, see Section 4.8.1.2 of Anderson et al. (1999).
Following the optional balancing, the matrix A is first reduced to upper Hessenberg form by means of unitary similarity transformations, and the QR algorithm is then used to further reduce the matrix to upper triangular Schur form, T, from which the eigenvalues are computed. Optionally, the eigenvectors of T are also computed and backtransformed to those of A.

4 References

Anderson E, Bai Z, Bischof C, Blackford S, Demmel J, Dongarra J J, Du Croz J J, Greenbaum A, Hammarling S, McKenney A and Sorensen D (1999) LAPACK Users' Guide (3rd Edition) SIAM, Philadelphia http://www.netlib.org/lapack/lug
Golub G H and Van Loan C F (1996) Matrix Computations (3rd Edition) Johns Hopkins University Press, Baltimore

5 Arguments

1:   BALANC – CHARACTER(1)Input
On entry: indicates how the input matrix should be diagonally scaled and/or permuted to improve the conditioning of its eigenvalues.
BALANC='N'
Do not diagonally scale or permute.
BALANC='P'
Perform permutations to make the matrix more nearly upper triangular. Do not diagonally scale.
BALANC='S'
Diagonally scale the matrix, i.e., replace A by DA D-1, where D is a diagonal matrix chosen to make the rows and columns of A more equal in norm. Do not permute.
BALANC='B'
Both diagonally scale and permute A.
Computed reciprocal condition numbers will be for the matrix after balancing and/or permuting. Permuting does not change condition numbers (in exact arithmetic), but balancing does.
Constraint: BALANC='N', 'P', 'S' or 'B'.
2:   JOBVL – CHARACTER(1)Input
On entry: if JOBVL='N', the left eigenvectors of A are not computed.
If JOBVL='V', the left eigenvectors of A are computed.
If SENSE='E' or 'B', JOBVL must be set to JOBVL='V'.
Constraint: JOBVL='N' or 'V'.
3:   JOBVR – CHARACTER(1)Input
On entry: if JOBVR='N', the right eigenvectors of A are not computed.
If JOBVR='V', the right eigenvectors of A are computed.
If SENSE='E' or 'B', JOBVR must be set to JOBVR='V'.
Constraint: JOBVR='N' or 'V'.
4:   SENSE – CHARACTER(1)Input
On entry: determines which reciprocal condition numbers are computed.
SENSE='N'
None are computed.
SENSE='E'
Computed for eigenvalues only.
SENSE='V'
Computed for right eigenvectors only.
SENSE='B'
Computed for eigenvalues and right eigenvectors.
If SENSE='E' or 'B', both left and right eigenvectors must also be computed (JOBVL='V' and JOBVR='V').
Constraint: SENSE='N', 'E', 'V' or 'B'.
5:   N – INTEGERInput
On entry: n, the order of the matrix A.
Constraint: N≥0.
6:   A LDA* – COMPLEX (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array A must be at least max 1,N.
On entry: the n by n matrix A.
On exit: A has been overwritten. If JOBVL='V' or JOBVR='V', A contains the Schur form of the balanced version of the matrix A.
7:   LDA – INTEGERInput
On entry: the first dimension of the array A as declared in the (sub)program from which F08NPF (ZGEEVX) is called.
Constraint: LDA≥max 1,N.
8:   W* – COMPLEX (KIND=nag_wp) arrayOutput
Note: the dimension of the array W must be at least max 1,N.
On exit: contains the computed eigenvalues.
9:   VL LDVL* – COMPLEX (KIND=nag_wp) arrayOutput
Note: the second dimension of the array VL must be at least max 1,N if JOBVL='V', and at least 1 otherwise.
On exit: if JOBVL='V', the left eigenvectors uj are stored one after another in the columns of VL, in the same order as their corresponding eigenvalues; that is uj=VL:j, the jth column of VL.
If JOBVL='N', VL is not referenced.
10:   LDVL – INTEGERInput
On entry: the first dimension of the array VL as declared in the (sub)program from which F08NPF (ZGEEVX) is called.
Constraints:
  • if JOBVL='V', LDVL≥ max 1,N ;
  • otherwise LDVL≥1.
11:   VR LDVR* – COMPLEX (KIND=nag_wp) arrayOutput
Note: the second dimension of the array VR must be at least max 1,N if JOBVR='V', and at least 1 otherwise.
On exit: if JOBVR='V', the right eigenvectors vj are stored one after another in the columns of VR, in the same order as their corresponding eigenvalues; that is vj=VR:j, the jth column of VR.
If JOBVR='N', VR is not referenced.
12:   LDVR – INTEGERInput
On entry: the first dimension of the array VR as declared in the (sub)program from which F08NPF (ZGEEVX) is called.
Constraints:
  • if JOBVR='V', LDVR≥ max 1,N ;
  • otherwise LDVR≥1.
13:   ILO – INTEGEROutput
14:   IHI – INTEGEROutput
On exit: ILO and IHI are integer values determined when A was balanced. The balanced A has a ij=0 if i>j and j=1,2,…,ILO-1 or i=IHI+1,…,N.
15:   SCALE* – REAL (KIND=nag_wp) arrayOutput
Note: the dimension of the array SCALE must be at least max 1,N.
On exit: details of the permutations and scaling factors applied when balancing A.
If pj is the index of the row and column interchanged with row and column j, and dj is the scaling factor applied to row and column j, then
  • SCALE j=pj, for j=1,2,…,ILO-1;
  • SCALE j=dj, for j=ILO,…,IHI;
  • SCALE j=pj, for j=IHI+1,…,N.
The order in which the interchanges are made is N to IHI+1, then 1 to ILO-1.
16:   ABNRM – REAL (KIND=nag_wp)Output
On exit: the 1-norm of the balanced matrix (the maximum of the sum of absolute values of elements of any column).
17:   RCONDE* – REAL (KIND=nag_wp) arrayOutput
Note: the dimension of the array RCONDE must be at least max 1,N.
On exit: RCONDE j is the reciprocal condition number of the jth eigenvalue.
18:   RCONDV* – REAL (KIND=nag_wp) arrayOutput
Note: the dimension of the array RCONDV must be at least max 1,N.
On exit: RCONDV j is the reciprocal condition number of the jth right eigenvector.
19:   WORK max 1,LWORK – COMPLEX (KIND=nag_wp) arrayWorkspace
On exit: if INFO=0, the real part of WORK 1 contains the minimum value of LWORK required for optimal performance.
20:   LWORK – INTEGERInput
On entry: the dimension of the array WORK as declared in the (sub)program from which F08NPF (ZGEEVX) is called.
If LWORK=-1, a workspace query is assumed; the routine only calculates the optimal size of the WORK array, returns this value as the first entry of the WORK array, and no error message related to LWORK is issued.
Suggested value: for optimal performance, LWORK must generally be larger than the minimum, increase LWORK by, say, N×nb , where nb is the optimal block size for F08NEF (DGEHRD).
Constraints:
  • if SENSE='N' or 'E', LWORK≥max 1,2×N;
  • if SENSE='V' or 'B', LWORK≥max 1,N×N+2×N.
21:   RWORK* – REAL (KIND=nag_wp) arrayWorkspace
Note: the dimension of the array RWORK must be at least max 1,2×N.
22:   INFO – INTEGEROutput
On exit: INFO=0 unless the routine detects an error (see Section 6).

6 Error Indicators and Warnings

INFO<0
If INFO=-i, argument i had an illegal value. An explanatory message is output, and execution of the program is terminated.
INFO>0
If INFO=i, the QR algorithm failed to compute all the eigenvalues, and no eigenvectors or condition numbers have been computed; elements 1:ILO-1 and i+1:N of W contain eigenvalues which have converged.

7 Accuracy

The computed eigenvalues and eigenvectors are exact for a nearby matrix A+E, where
E 2 = O ε A 2 ,
and ε is the machine precision. See Section 4.8 of Anderson et al. (1999) for further details.

8 Parallelism and Performance

F08NPF (ZGEEVX) is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
F08NPF (ZGEEVX) makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

Each eigenvector is normalized to have Euclidean norm equal to unity and the element of largest absolute value real.
The total number of floating-point operations is proportional to n 3.
The real analogue of this routine is F08NBF (DGEEVX).

10 Example

This example finds all the eigenvalues and right eigenvectors of the matrix
A = -3.97-5.04 i -4.11+3.70 i -0.34+1.01 i 1.29-0.86 i 0.34-1.50 i 1.52-0.43 i 1.88-5.38 i 3.36+0.65 i 3.31-3.85 i 2.50+3.45 i 0.88-1.08 i 0.64-1.48 i -1.10+0.82 i 1.81-1.59 i 3.25+1.33 i 1.57-3.44 i ,
together with estimates of the condition number and forward error bounds for each eigenvalue and eigenvector. The option to balance the matrix is used. In order to compute the condition numbers of the eigenvalues, the left eigenvectors also have to be computed, but they are not printed out in this example.
Note that the block size (NB) of 64 assumed in this example is not realistic for such a small problem, but should be suitable for large problems.

10.1 Program Text

Program Text (f08npfe.f90)

10.2 Program Data

Program Data (f08npfe.d)

10.3 Program Results

Program Results (f08npfe.r)

F08 Chapter Contents
F08 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F08NSF (ZGEHRD) : NAG Library, Mark 26

F08 Chapter Contents
F08 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F08NSF (ZGEHRD)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F08NSF (ZGEHRD) reduces a complex general matrix to Hessenberg form.

2 Specification

SUBROUTINE F08NSF ( N, ILO, IHI, A, LDA, TAU, WORK, LWORK, INFO)
INTEGER | N, ILO, IHI, LDA, LWORK, INFO
COMPLEX (KIND=nag_wp) | A(LDA,*), TAU(*), WORK(max(1,LWORK))
The routine may be called by its LAPACK name zgehrd.

3 Description

F08NSF (ZGEHRD) reduces a complex general matrix A to upper Hessenberg form H by a unitary similarity transformation: A=QH QH. H has real subdiagonal elements.
The matrix Q is not formed explicitly, but is represented as a product of elementary reflectors (see the F08 Chapter Introduction for details). Routines are provided to work with Q in this representation (see Section 9).
The routine can take advantage of a previous call to F08NVF (ZGEBAL), which may produce a matrix with the structure:
A 11 A 12 A 13 A 22 A 23 A 33
where A 11 and A 33 are upper triangular. If so, only the central diagonal block A 22, in rows and columns ilo to ihi, needs to be reduced to Hessenberg form (the blocks A 12 and A 23 will also be affected by the reduction). Therefore the values of ilo and ihi determined by F08NVF (ZGEBAL) can be supplied to the routine directly. If F08NVF (ZGEBAL) has not previously been called however, then ilo must be set to 1 and ihi to n.

4 References

Golub G H and Van Loan C F (1996) Matrix Computations (3rd Edition) Johns Hopkins University Press, Baltimore

5 Arguments

1:   N – INTEGERInput
On entry: n, the order of the matrix A.
Constraint: N≥0.
2:   ILO – INTEGERInput
3:   IHI – INTEGERInput
On entry: if A has been output by F08NVF (ZGEBAL), then ILO and IHI must contain the values returned by that routine. Otherwise, ILO must be set to 1 and IHI to N.
Constraints:
  • if N>0, 1≤ ILO≤ IHI≤ N ;
  • if N=0, ILO=1 and IHI=0.
4:   A LDA* – COMPLEX (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array A must be at least max 1,N.
On entry: the n by n general matrix A.
On exit: A is overwritten by the upper Hessenberg matrix H and details of the unitary matrix Q. The subdiagonal elements of H are real.
5:   LDA – INTEGERInput
On entry: the first dimension of the array A as declared in the (sub)program from which F08NSF (ZGEHRD) is called.
Constraint: LDA≥max 1,N.
6:   TAU* – COMPLEX (KIND=nag_wp) arrayOutput
Note: the dimension of the array TAU must be at least max 1,N-1.
On exit: further details of the unitary matrix Q.
7:   WORK max 1,LWORK – COMPLEX (KIND=nag_wp) arrayWorkspace
On exit: if INFO=0, the real part of WORK 1 contains the minimum value of LWORK required for optimal performance.
8:   LWORK – INTEGERInput
On entry: the dimension of the array WORK as declared in the (sub)program from which F08NSF (ZGEHRD) is called.
If LWORK=-1, a workspace query is assumed; the routine only calculates the optimal size of the WORK array, returns this value as the first entry of the WORK array, and no error message related to LWORK is issued.
Suggested value: for optimal performance, LWORK≥N×nb, where nb is the optimal block size.
Constraint: LWORK≥max 1,N or LWORK=-1.
9:   INFO – INTEGEROutput
On exit: INFO=0 unless the routine detects an error (see Section 6).

6 Error Indicators and Warnings

INFO<0
If INFO=-i, argument i had an illegal value.
If INFO=-999, dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.
An explanatory message is output, and execution of the program is terminated.

7 Accuracy

The computed Hessenberg matrix H is exactly similar to a nearby matrix A+E, where
E 2 ≤ c n ε A 2 ,
c n is a modestly increasing function of n, and ε is the machine precision.
The elements of H themselves may be sensitive to small perturbations in A or to rounding errors in the computation, but this does not affect the stability of the eigenvalues, eigenvectors or Schur factorization.

8 Parallelism and Performance

F08NSF (ZGEHRD) makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The total number of real floating-point operations is approximately 83 q 2 2 q+3 n, where q=ihi-ilo; if ilo=1 and ihi=n, the number is approximately 403 n 3.
To form the unitary matrix Q F08NSF (ZGEHRD) may be followed by a call to F08NTF (ZUNGHR):
CALL ZUNGHR(N,ILO,IHI,A,LDA,TAU,WORK,LWORK,INFO)
To apply Q to an m by n complex matrix C F08NSF (ZGEHRD) may be followed by a call to F08NUF (ZUNMHR). For example,
CALL ZUNMHR('Left','No Transpose',M,N,ILO,IHI,A,LDA,TAU,C,LDC, &
              WORK,LWORK,INFO)
forms the matrix product QC.
The real analogue of this routine is F08NEF (DGEHRD).

10 Example

This example computes the upper Hessenberg form of the matrix A, where
A = -3.97-5.04 i -4.11+3.70 i -0.34+1.01 i 1.29-0.86 i 0.34-1.50 i 1.52-0.43 i 1.88-5.38 i 3.36+0.65 i 3.31-3.85 i 2.50+3.45 i 0.88-1.08 i 0.64-1.48 i -1.10+0.82 i 1.81-1.59 i 3.25+1.33 i 1.57-3.44 i .

10.1 Program Text

Program Text (f08nsfe.f90)

10.2 Program Data

Program Data (f08nsfe.d)

10.3 Program Results

Program Results (f08nsfe.r)

F08 Chapter Contents
F08 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F08NTF (ZUNGHR) : NAG Library, Mark 26

F08 Chapter Contents
F08 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F08NTF (ZUNGHR)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F08NTF (ZUNGHR) generates the complex unitary matrix Q which was determined by F08NSF (ZGEHRD) when reducing a complex general matrix A to Hessenberg form.

2 Specification

SUBROUTINE F08NTF ( N, ILO, IHI, A, LDA, TAU, WORK, LWORK, INFO)
INTEGER | N, ILO, IHI, LDA, LWORK, INFO
COMPLEX (KIND=nag_wp) | A(LDA,*), TAU(*), WORK(max(1,LWORK))
The routine may be called by its LAPACK name zunghr.

3 Description

F08NTF (ZUNGHR) is intended to be used following a call to F08NSF (ZGEHRD), which reduces a complex general matrix A to upper Hessenberg form H by a unitary similarity transformation: A=QH QH. F08NSF (ZGEHRD) represents the matrix Q as a product of ihi-ilo elementary reflectors. Here ilo and ihi are values determined by F08NVF (ZGEBAL) when balancing the matrix; if the matrix has not been balanced, ilo=1 and ihi=n.
This routine may be used to generate Q explicitly as a square matrix. Q has the structure:
Q = I 0 0 0 Q 22 0 0 0 I
where Q 22 occupies rows and columns ilo to ihi.

4 References

Golub G H and Van Loan C F (1996) Matrix Computations (3rd Edition) Johns Hopkins University Press, Baltimore

5 Arguments

1:   N – INTEGERInput
On entry: n, the order of the matrix Q.
Constraint: N≥0.
2:   ILO – INTEGERInput
3:   IHI – INTEGERInput
On entry: these must be the same arguments ILO and IHI, respectively, as supplied to F08NSF (ZGEHRD).
Constraints:
  • if N>0, 1≤ ILO≤ IHI≤ N ;
  • if N=0, ILO=1 and IHI=0.
4:   A LDA* – COMPLEX (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array A must be at least max 1,N.
On entry: details of the vectors which define the elementary reflectors, as returned by F08NSF (ZGEHRD).
On exit: the n by n unitary matrix Q.
5:   LDA – INTEGERInput
On entry: the first dimension of the array A as declared in the (sub)program from which F08NTF (ZUNGHR) is called.
Constraint: LDA≥max 1,N.
6:   TAU* – COMPLEX (KIND=nag_wp) arrayInput
Note: the dimension of the array TAU must be at least max 1,N-1.
On entry: further details of the elementary reflectors, as returned by F08NSF (ZGEHRD).
7:   WORK max 1,LWORK – COMPLEX (KIND=nag_wp) arrayWorkspace
On exit: if INFO=0, the real part of WORK 1 contains the minimum value of LWORK required for optimal performance.
8:   LWORK – INTEGERInput
On entry: the dimension of the array WORK as declared in the (sub)program from which F08NTF (ZUNGHR) is called, unless LWORK=-1, in which case a workspace query is assumed and the routine only calculates the optimal dimension of WORK (using the formula given below).
Suggested value: for optimal performance LWORK should be at least IHI-ILO×nb, where nb is the block size.
Constraint: LWORK≥max 1,IHI-ILO or LWORK=-1.
9:   INFO – INTEGEROutput
On exit: INFO=0 unless the routine detects an error (see Section 6).

6 Error Indicators and Warnings

INFO<0
If INFO=-i, argument i had an illegal value. An explanatory message is output, and execution of the program is terminated.

7 Accuracy

The computed matrix Q differs from an exactly unitary matrix by a matrix E such that
E 2 = O ε ,
where ε is the machine precision.

8 Parallelism and Performance

F08NTF (ZUNGHR) is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
F08NTF (ZUNGHR) makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The total number of real floating-point operations is approximately 163 q 3, where q=ihi-ilo.
The real analogue of this routine is F08NFF (DORGHR).

10 Example

This example computes the Schur factorization of the matrix A, where
A = -3.97-5.04 i -4.11+3.70 i -0.34+1.01 i 1.29-0.86 i 0.34-1.50 i 1.52-0.43 i 1.88-5.38 i 3.36+0.65 i 3.31-3.85 i 2.50+3.45 i 0.88-1.08 i 0.64-1.48 i -1.10+0.82 i 1.81-1.59 i 3.25+1.33 i 1.57-3.44 i .
Here A is general and must first be reduced to Hessenberg form by F08NSF (ZGEHRD). The program then calls F08NTF (ZUNGHR) to form Q, and passes this matrix to F08PSF (ZHSEQR) which computes the Schur factorization of A.

10.1 Program Text

Program Text (f08ntfe.f90)

10.2 Program Data

Program Data (f08ntfe.d)

10.3 Program Results

Program Results (f08ntfe.r)

F08 Chapter Contents
F08 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F08NUF (ZUNMHR) : NAG Library, Mark 26

F08 Chapter Contents
F08 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F08NUF (ZUNMHR)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F08NUF (ZUNMHR) multiplies an arbitrary complex matrix C by the complex unitary matrix Q which was determined by F08NSF (ZGEHRD) when reducing a complex general matrix to Hessenberg form.

2 Specification

SUBROUTINE F08NUF ( SIDE, TRANS, M, N, ILO, IHI, A, LDA, TAU, C, LDC, WORK, LWORK, INFO)
INTEGER | M, N, ILO, IHI, LDA, LDC, LWORK, INFO
COMPLEX (KIND=nag_wp) | A(LDA,*), TAU(*), C(LDC,*), WORK(max(1,LWORK))
CHARACTER(1) | SIDE, TRANS
The routine may be called by its LAPACK name zunmhr.

3 Description

F08NUF (ZUNMHR) is intended to be used following a call to F08NSF (ZGEHRD), which reduces a complex general matrix A to upper Hessenberg form H by a unitary similarity transformation: A=QH QH. F08NSF (ZGEHRD) represents the matrix Q as a product of ihi-ilo elementary reflectors. Here ilo and ihi are values determined by F08NVF (ZGEBAL) when balancing the matrix; if the matrix has not been balanced, ilo=1 and ihi=n.
This routine may be used to form one of the matrix products
QC , QH C , CQ ​ or ​ C QH ,
overwriting the result on C (which may be any complex rectangular matrix).
A common application of this routine is to transform a matrix V of eigenvectors of H to the matrix QV of eigenvectors of A.

4 References

Golub G H and Van Loan C F (1996) Matrix Computations (3rd Edition) Johns Hopkins University Press, Baltimore

5 Arguments

1:   SIDE – CHARACTER(1)Input
On entry: indicates how Q or QH is to be applied to C.
SIDE='L'
Q or QH is applied to C from the left.
SIDE='R'
Q or QH is applied to C from the right.
Constraint: SIDE='L' or 'R'.
2:   TRANS – CHARACTER(1)Input
On entry: indicates whether Q or QH is to be applied to C.
TRANS='N'
Q is applied to C.
TRANS='C'
QH is applied to C.
Constraint: TRANS='N' or 'C'.
3:   M – INTEGERInput
On entry: m, the number of rows of the matrix C; m is also the order of Q if SIDE='L'.
Constraint: M≥0.
4:   N – INTEGERInput
On entry: n, the number of columns of the matrix C; n is also the order of Q if SIDE='R'.
Constraint: N≥0.
5:   ILO – INTEGERInput
6:   IHI – INTEGERInput
On entry: these must be the same arguments ILO and IHI, respectively, as supplied to F08NSF (ZGEHRD).
Constraints:
  • if SIDE='L' and M>0, 1≤ ILO≤ IHI≤ M ;
  • if SIDE='L' and M=0, ILO=1 and IHI=0;
  • if SIDE='R' and N>0, 1≤ ILO≤ IHI≤ N ;
  • if SIDE='R' and N=0, ILO=1 and IHI=0.
7:   A LDA* – COMPLEX (KIND=nag_wp) arrayInput
Note: the second dimension of the array A must be at least max 1,M if SIDE='L' and at least max 1,N if SIDE='R'.
On entry: details of the vectors which define the elementary reflectors, as returned by F08NSF (ZGEHRD).
8:   LDA – INTEGERInput
On entry: the first dimension of the array A as declared in the (sub)program from which F08NUF (ZUNMHR) is called.
Constraints:
  • if SIDE='L', LDA≥ max 1,M ;
  • if SIDE='R', LDA≥ max 1,N .
9:   TAU* – COMPLEX (KIND=nag_wp) arrayInput
Note: the dimension of the array TAU must be at least max 1,M-1 if SIDE='L' and at least max 1,N-1 if SIDE='R'.
On entry: further details of the elementary reflectors, as returned by F08NSF (ZGEHRD).
10:   C LDC* – COMPLEX (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array C must be at least max 1,N.
On entry: the m by n matrix C.
On exit: C is overwritten by QC or QH C or CQ or C QH as specified by SIDE and TRANS.
11:   LDC – INTEGERInput
On entry: the first dimension of the array C as declared in the (sub)program from which F08NUF (ZUNMHR) is called.
Constraint: LDC≥max 1,M.
12:   WORK max 1,LWORK – COMPLEX (KIND=nag_wp) arrayWorkspace
On exit: if INFO=0, the real part of WORK 1 contains the minimum value of LWORK required for optimal performance.
13:   LWORK – INTEGERInput
On entry: the dimension of the array WORK as declared in the (sub)program from which F08NUF (ZUNMHR) is called.
If LWORK=-1, a workspace query is assumed; the routine only calculates the optimal size of the WORK array, returns this value as the first entry of the WORK array, and no error message related to LWORK is issued.
Suggested value: for optimal performance, LWORK≥N×nb if SIDE='L' and at least M×nb if SIDE='R', where nb is the optimal block size.
Constraints:
  • if SIDE='L', LWORK≥max 1,N or LWORK=-1;
  • if SIDE='R', LWORK≥max 1,M or LWORK=-1.
14:   INFO – INTEGEROutput
On exit: INFO=0 unless the routine detects an error (see Section 6).

6 Error Indicators and Warnings

INFO<0
If INFO=-i, argument i had an illegal value. An explanatory message is output, and execution of the program is terminated.

7 Accuracy

The computed result differs from the exact result by a matrix E such that
E 2 = O ε C 2 ,
where ε is the machine precision.

8 Parallelism and Performance

F08NUF (ZUNMHR) is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
F08NUF (ZUNMHR) makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The total number of real floating-point operations is approximately 8 n q 2 if SIDE='L' and 8 m q 2 if SIDE='R', where q=ihi-ilo.
The real analogue of this routine is F08NGF (DORMHR).

10 Example

This example computes all the eigenvalues of the matrix A, where
A = -3.97-5.04 i -4.11+3.70 i -0.34+1.01 i 1.29-0.86 i 0.34-1.50 i 1.52-0.43 i 1.88-5.38 i 3.36+0.65 i 3.31-3.85 i 2.50+3.45 i 0.88-1.08 i 0.64-1.48 i -1.10+0.82 i 1.81-1.59 i 3.25+1.33 i 1.57-3.44 i ,
and those eigenvectors which correspond to eigenvalues λ such that Re λ<0. Here A is general and must first be reduced to upper Hessenberg form H by F08NSF (ZGEHRD). The program then calls F08PSF (ZHSEQR) to compute the eigenvalues, and F08PXF (ZHSEIN) to compute the required eigenvectors of H by inverse iteration. Finally F08NUF (ZUNMHR) is called to transform the eigenvectors of H back to eigenvectors of the original matrix A.

10.1 Program Text

Program Text (f08nufe.f90)

10.2 Program Data

Program Data (f08nufe.d)

10.3 Program Results

Program Results (f08nufe.r)

F08 Chapter Contents
F08 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F08NVF (ZGEBAL) : NAG Library, Mark 26

F08 Chapter Contents
F08 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F08NVF (ZGEBAL)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F08NVF (ZGEBAL) balances a complex general matrix in order to improve the accuracy of computed eigenvalues and/or eigenvectors.

2 Specification

SUBROUTINE F08NVF ( JOB, N, A, LDA, ILO, IHI, SCALE, INFO)
INTEGER | N, LDA, ILO, IHI, INFO
REAL (KIND=nag_wp) | SCALE(N)
COMPLEX (KIND=nag_wp) | A(LDA,*)
CHARACTER(1) | JOB
The routine may be called by its LAPACK name zgebal.

3 Description

F08NVF (ZGEBAL) balances a complex general matrix A. The term ‘balancing’ covers two steps, each of which involves a similarity transformation of A. The routine can perform either or both of these steps.
1. The routine first attempts to permute A to block upper triangular form by a similarity transformation:
PA PT = A′ = A 11′ A 12′ A 13′ 0 A 22′ A 23′ 0 0 A 33′
where P is a permutation matrix, and A 11′ and A 33′ are upper triangular. Then the diagonal elements of A 11′ and A 33′ are eigenvalues of A. The rest of the eigenvalues of A are the eigenvalues of the central diagonal block A 22′, in rows and columns ilo to ihi. Subsequent operations to compute the eigenvalues of A (or its Schur factorization) need only be applied to these rows and columns; this can save a significant amount of work if ilo>1 and ihi<n. If no suitable permutation exists (as is often the case), the routine sets ilo=1 and ihi=n, and A 22′ is the whole of A.
2. The routine applies a diagonal similarity transformation to A′, to make the rows and columns of A 22′ as close in norm as possible:
A′′ = D A′D-1 = I 0 0 0 D 22 0 0 0 I A 11′ A 12′ A 13′ 0 A 22′ A 23′ 0 0 A 33′ I 0 0 0 D 22-1 0 0 0 I .
This scaling can reduce the norm of the matrix (i.e., A 22′′<A 22′) and hence reduce the effect of rounding errors on the accuracy of computed eigenvalues and eigenvectors.

4 References

Golub G H and Van Loan C F (1996) Matrix Computations (3rd Edition) Johns Hopkins University Press, Baltimore

5 Arguments

1:   JOB – CHARACTER(1)Input
On entry: indicates whether A is to be permuted and/or scaled (or neither).
JOB='N'
A is neither permuted nor scaled (but values are assigned to ILO, IHI and SCALE).
JOB='P'
A is permuted but not scaled.
JOB='S'
A is scaled but not permuted.
JOB='B'
A is both permuted and scaled.
Constraint: JOB='N', 'P', 'S' or 'B'.
2:   N – INTEGERInput
On entry: n, the order of the matrix A.
Constraint: N≥0.
3:   A LDA* – COMPLEX (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array A must be at least max 1,N.
On entry: the n by n matrix A.
On exit: A is overwritten by the balanced matrix. If JOB='N', A is not referenced.
4:   LDA – INTEGERInput
On entry: the first dimension of the array A as declared in the (sub)program from which F08NVF (ZGEBAL) is called.
Constraint: LDA≥max 1,N.
5:   ILO – INTEGEROutput
6:   IHI – INTEGEROutput
On exit: the values ilo and ihi such that on exit A ij is zero if i>j and 1≤j<ilo or ihi<i≤n.
If JOB='N' or 'S', ilo=1 and ihi=n.
7:   SCALE N – REAL (KIND=nag_wp) arrayOutput
On exit: details of the permutations and scaling factors applied to A. More precisely, if pj is the index of the row and column interchanged with row and column j and dj is the scaling factor used to balance row and column j then
SCALE j = pj, j=1,2,…,ilo-1 dj, j=ilo,ilo+1,…,ihi  and pj, j=ihi+1,ihi+2,…,n.
The order in which the interchanges are made is n to ihi+1 then 1 to ilo-1.
8:   INFO – INTEGEROutput
On exit: INFO=0 unless the routine detects an error (see Section 6).

6 Error Indicators and Warnings

INFO<0
If INFO=-i, argument i had an illegal value. An explanatory message is output, and execution of the program is terminated.

7 Accuracy

The errors are negligible, compared with those in subsequent computations.

8 Parallelism and Performance

F08NVF (ZGEBAL) makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

If the matrix A is balanced by F08NVF (ZGEBAL), then any eigenvectors computed subsequently are eigenvectors of the matrix A′′ (see Section 3) and hence F08NWF (ZGEBAK) must then be called to transform them back to eigenvectors of A.
If the Schur vectors of A are required, then this routine must not be called with JOB='S' or 'B', because then the balancing transformation is not unitary. If this routine is called with JOB='P', then any Schur vectors computed subsequently are Schur vectors of the matrix A′′, and F08NWF (ZGEBAK) must be called (with SIDE='R') to transform them back to Schur vectors of A.
The total number of real floating-point operations is approximately proportional to n 2.
The real analogue of this routine is F08NHF (DGEBAL).

10 Example

This example computes all the eigenvalues and right eigenvectors of the matrix A, where
A = 1.50-2.75 i 0.00+0.00 i 0.00+0.00 i 0.00+0.00 i -8.06-1.24 i -2.50-0.50 i 0.00+0.00 i -0.75+0.50 i -2.09+7.56 i 1.39+3.97 i -1.25+0.75 i -4.82-5.67 i 6.18+9.79 i -0.92-0.62 i 0.00+0.00 i -2.50-0.50 i .
The program first calls F08NVF (ZGEBAL) to balance the matrix; it then computes the Schur factorization of the balanced matrix, by reduction to Hessenberg form and the QR algorithm. Then it calls F08QXF (ZTREVC) to compute the right eigenvectors of the balanced matrix, and finally calls F08NWF (ZGEBAK) to transform the eigenvectors back to eigenvectors of the original matrix A.

10.1 Program Text

Program Text (f08nvfe.f90)

10.2 Program Data

Program Data (f08nvfe.d)

10.3 Program Results

Program Results (f08nvfe.r)

F08 Chapter Contents
F08 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F08NWF (ZGEBAK) : NAG Library, Mark 26

F08 Chapter Contents
F08 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F08NWF (ZGEBAK)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
10 Example

1 Purpose

F08NWF (ZGEBAK) transforms eigenvectors of a balanced matrix to those of the original complex general matrix.

2 Specification

SUBROUTINE F08NWF ( JOB, SIDE, N, ILO, IHI, SCALE, M, V, LDV, INFO)
INTEGER | N, ILO, IHI, M, LDV, INFO
REAL (KIND=nag_wp) | SCALE(*)
COMPLEX (KIND=nag_wp) | V(LDV,*)
CHARACTER(1) | JOB, SIDE
The routine may be called by its LAPACK name zgebak.

3 Description

F08NWF (ZGEBAK) is intended to be used after a complex general matrix A has been balanced by F08NVF (ZGEBAL), and eigenvectors of the balanced matrix A 22′′ have subsequently been computed.
For a description of balancing, see the document for F08NVF (ZGEBAL). The balanced matrix A′′ is obtained as A′′=DPA PTD-1, where P is a permutation matrix and D is a diagonal scaling matrix. This routine transforms left or right eigenvectors as follows:
  • if x is a right eigenvector of A′′, PTD-1 x is a right eigenvector of A;
  • if y is a left eigenvector of A′′, PT Dy is a left eigenvector of A.

4 References

None.

5 Arguments

1:   JOB – CHARACTER(1)Input
On entry: this must be the same argument JOB as supplied to F08NVF (ZGEBAL).
Constraint: JOB='N', 'P', 'S' or 'B'.
2:   SIDE – CHARACTER(1)Input
On entry: indicates whether left or right eigenvectors are to be transformed.
SIDE='L'
The left eigenvectors are transformed.
SIDE='R'
The right eigenvectors are transformed.
Constraint: SIDE='L' or 'R'.
3:   N – INTEGERInput
On entry: n, the number of rows of the matrix of eigenvectors.
Constraint: N≥0.
4:   ILO – INTEGERInput
5:   IHI – INTEGERInput
On entry: the values ilo and ihi, as returned by F08NVF (ZGEBAL).
Constraints:
  • if N>0, 1≤ ILO≤ IHI≤ N ;
  • if N=0, ILO=1 and IHI=0.
6:   SCALE* – REAL (KIND=nag_wp) arrayInput
Note: the dimension of the array SCALE must be at least max 1,N.
On entry: details of the permutations and/or the scaling factors used to balance the original complex general matrix, as returned by F08NVF (ZGEBAL).
7:   M – INTEGERInput
On entry: m, the number of columns of the matrix of eigenvectors.
Constraint: M≥0.
8:   V LDV* – COMPLEX (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array V must be at least max 1,M.
On entry: the matrix of left or right eigenvectors to be transformed.
On exit: the transformed eigenvectors.
9:   LDV – INTEGERInput
On entry: the first dimension of the array V as declared in the (sub)program from which F08NWF (ZGEBAK) is called.
Constraint: LDV≥ max 1,N .
10:   INFO – INTEGEROutput
On exit: INFO=0 unless the routine detects an error (see Section 6).

6 Error Indicators and Warnings

INFO<0
If INFO=-i, argument i had an illegal value. An explanatory message is output, and execution of the program is terminated.

7 Accuracy

The errors are negligible.

8 Parallelism and Performance

F08NWF (ZGEBAK) makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The total number of real floating-point operations is approximately proportional to nm.
The real analogue of this routine is F08NJF (DGEBAK).

10 Example

See Section 10 in F08NVF (ZGEBAL).
F08 Chapter Contents
F08 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F08PAF (DGEES) : NAG Library, Mark 26

F08 Chapter Contents
F08 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F08PAF (DGEES)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F08PAF (DGEES) computes the eigenvalues, the real Schur form T, and, optionally, the matrix of Schur vectors Z for an n by n real nonsymmetric matrix A.

2 Specification

SUBROUTINE F08PAF ( JOBVS, SORT, SELECT, N, A, LDA, SDIM, WR, WI, VS, LDVS, WORK, LWORK, BWORK, INFO)
INTEGER | N, LDA, SDIM, LDVS, LWORK, INFO
REAL (KIND=nag_wp) | A(LDA,*), WR(*), WI(*), VS(LDVS,*), WORK(max(1,LWORK))
LOGICAL | SELECT, BWORK(*)
CHARACTER(1) | JOBVS, SORT
EXTERNAL | SELECT
The routine may be called by its LAPACK name dgees.

3 Description

The real Schur factorization of A is given by
A = Z T ZT ,
where Z, the matrix of Schur vectors, is orthogonal and T is the real Schur form. A matrix is in real Schur form if it is upper quasi-triangular with 1 by 1 and 2 by 2 blocks. 2 by 2 blocks will be standardized in the form
a b c a
where bc<0. The eigenvalues of such a block are a±bc.
Optionally, F08PAF (DGEES) also orders the eigenvalues on the diagonal of the real Schur form so that selected eigenvalues are at the top left. The leading columns of Z form an orthonormal basis for the invariant subspace corresponding to the selected eigenvalues.

4 References

Anderson E, Bai Z, Bischof C, Blackford S, Demmel J, Dongarra J J, Du Croz J J, Greenbaum A, Hammarling S, McKenney A and Sorensen D (1999) LAPACK Users' Guide (3rd Edition) SIAM, Philadelphia http://www.netlib.org/lapack/lug
Golub G H and Van Loan C F (1996) Matrix Computations (3rd Edition) Johns Hopkins University Press, Baltimore

5 Arguments

1:   JOBVS – CHARACTER(1)Input
On entry: if JOBVS='N', Schur vectors are not computed.
If JOBVS='V', Schur vectors are computed.
Constraint: JOBVS='N' or 'V'.
2:   SORT – CHARACTER(1)Input
On entry: specifies whether or not to order the eigenvalues on the diagonal of the Schur form.
SORT='N'
Eigenvalues are not ordered.
SORT='S'
Eigenvalues are ordered (see SELECT).
Constraint: SORT='N' or 'S'.
3:   SELECT – LOGICAL FUNCTION, supplied by the user.External Procedure
If SORT='S', SELECT is used to select eigenvalues to sort to the top left of the Schur form.
If SORT='N', SELECT is not referenced and F08PAF (DGEES) may be called with the dummy function F08PAZ.
An eigenvalue WR j+-1×WI j is selected if SELECT WR j,WI j is .TRUE.. If either one of a complex conjugate pair of eigenvalues is selected, then both are. Note that a selected complex eigenvalue may no longer satisfy SELECT WR j,WI j=.TRUE. after ordering, since ordering may change the value of complex eigenvalues (especially if the eigenvalue is ill-conditioned); in this case INFO is set to N+2 (see INFO below).
The specification of SELECT is:
FUNCTION SELECT ( WR, WI)
LOGICAL SELECT
REAL (KIND=nag_wp) WR, WI
1:   WR – REAL (KIND=nag_wp)Input
2:   WI – REAL (KIND=nag_wp)Input
On entry: the real and imaginary parts of the eigenvalue.
SELECT must either be a module subprogram USEd by, or declared as EXTERNAL in, the (sub)program from which F08PAF (DGEES) is called. Arguments denoted as Input must not be changed by this procedure.
4:   N – INTEGERInput
On entry: n, the order of the matrix A.
Constraint: N≥0.
5:   A LDA* – REAL (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array A must be at least max 1,N.
On entry: the n by n matrix A.
On exit: A is overwritten by its real Schur form T.
6:   LDA – INTEGERInput
On entry: the first dimension of the array A as declared in the (sub)program from which F08PAF (DGEES) is called.
Constraint: LDA≥max 1,N.
7:   SDIM – INTEGEROutput
On exit: if SORT='N', SDIM=0.
If SORT='S', SDIM= number of eigenvalues (after sorting) for which SELECT is .TRUE.. (Complex conjugate pairs for which SELECT is .TRUE. for either eigenvalue count as 2.)
8:   WR* – REAL (KIND=nag_wp) arrayOutput
Note: the dimension of the array WR must be at least max 1,N.
On exit: see the description of WI.
9:   WI* – REAL (KIND=nag_wp) arrayOutput
Note: the dimension of the array WI must be at least max 1,N.
On exit: WR and WI contain the real and imaginary parts, respectively, of the computed eigenvalues in the same order that they appear on the diagonal of the output Schur form T. Complex conjugate pairs of eigenvalues will appear consecutively with the eigenvalue having the positive imaginary part first.
10:   VS LDVS* – REAL (KIND=nag_wp) arrayOutput
Note: the second dimension of the array VS must be at least max 1,N if JOBVS='V', and at least 1 otherwise.
On exit: if JOBVS='V', VS contains the orthogonal matrix Z of Schur vectors.
If JOBVS='N', VS is not referenced.
11:   LDVS – INTEGERInput
On entry: the first dimension of the array VS as declared in the (sub)program from which F08PAF (DGEES) is called.
Constraints:
  • if JOBVS='V', LDVS≥ max 1,N ;
  • otherwise LDVS≥1.
12:   WORK max 1,LWORK – REAL (KIND=nag_wp) arrayWorkspace
On exit: if INFO=0, WORK 1 contains the minimum value of LWORK required for optimal performance.
13:   LWORK – INTEGERInput
On entry: the dimension of the array WORK as declared in the (sub)program from which F08PAF (DGEES) is called.
If LWORK=-1, a workspace query is assumed; the routine only calculates the optimal size of the WORK array, returns this value as the first entry of the WORK array, and no error message related to LWORK is issued.
Suggested value: for optimal performance, LWORK must generally be larger than the minimum, say 3×N+nb×N , where nb is the optimal block size for F08NEF (DGEHRD)
Constraint: LWORK≥max 1,3×N.
14:   BWORK* – LOGICAL arrayWorkspace
Note: the dimension of the array BWORK must be at least 1 if SORT='N', and at least max 1,N otherwise.
If SORT='N', BWORK is not referenced.
15:   INFO – INTEGEROutput
On exit: INFO=0 unless the routine detects an error (see Section 6).

6 Error Indicators and Warnings

INFO<0
If INFO=-i, argument i had an illegal value. An explanatory message is output, and execution of the program is terminated.
INFO=1 to N
If INFO=i and i≤N, the QR algorithm failed to compute all the eigenvalues.
INFO=N+1
The eigenvalues could not be reordered because some eigenvalues were too close to separate (the problem is very ill-conditioned).
INFO=N+2
After reordering, roundoff changed values of some complex eigenvalues so that leading eigenvalues in the Schur form no longer satisfy SELECT=.TRUE.. This could also be caused by underflow due to scaling.

7 Accuracy

The computed Schur factorization satisfies
A+E=ZT ZT ,
where
E 2 = O ε A 2 ,
and ε is the machine precision. See Section 4.8 of Anderson et al. (1999) for further details.

8 Parallelism and Performance

F08PAF (DGEES) is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
F08PAF (DGEES) makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The total number of floating-point operations is proportional to n 3.
The complex analogue of this routine is F08PNF (ZGEES).

10 Example

This example finds the Schur factorization of the matrix
A = 0.35 0.45 -0.14 -0.17 0.09 0.07 -0.54 0.35 -0.44 -0.33 -0.03 0.17 0.25 -0.32 -0.13 0.11 ,
such that the real positive eigenvalues of A are the top left diagonal elements of the Schur form, T.
Note that the block size (NB) of 64 assumed in this example is not realistic for such a small problem, but should be suitable for large problems.

10.1 Program Text

Program Text (f08pafe.f90)

10.2 Program Data

Program Data (f08pafe.d)

10.3 Program Results

Program Results (f08pafe.r)

F08 Chapter Contents
F08 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F08PBF (DGEESX) : NAG Library, Mark 26

F08 Chapter Contents
F08 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F08PBF (DGEESX)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F08PBF (DGEESX) computes the eigenvalues, the real Schur form T, and, optionally, the matrix of Schur vectors Z for an n by n real nonsymmetric matrix A.

2 Specification

SUBROUTINE F08PBF ( JOBVS, SORT, SELECT, SENSE, N, A, LDA, SDIM, WR, WI, VS, LDVS, RCONDE, RCONDV, WORK, LWORK, IWORK, LIWORK, BWORK, INFO)
INTEGER | N, LDA, SDIM, LDVS, LWORK, IWORK(max(1,LIWORK)), LIWORK, INFO
REAL (KIND=nag_wp) | A(LDA,*), WR(*), WI(*), VS(LDVS,*), RCONDE, RCONDV, WORK(max(1,LWORK))
LOGICAL | SELECT, BWORK(*)
CHARACTER(1) | JOBVS, SORT, SENSE
EXTERNAL | SELECT
The routine may be called by its LAPACK name dgeesx.

3 Description

The real Schur factorization of A is given by
A = Z T ZT ,
where Z, the matrix of Schur vectors, is orthogonal and T is the real Schur form. A matrix is in real Schur form if it is upper quasi-triangular with 1 by 1 and 2 by 2 blocks. 2 by 2 blocks will be standardized in the form
a b c a
where bc<0. The eigenvalues of such a block are a±bc.
Optionally, F08PBF (DGEESX) also orders the eigenvalues on the diagonal of the real Schur form so that selected eigenvalues are at the top left; computes a reciprocal condition number for the average of the selected eigenvalues (RCONDE); and computes a reciprocal condition number for the right invariant subspace corresponding to the selected eigenvalues (RCONDV). The leading columns of Z form an orthonormal basis for this invariant subspace.
For further explanation of the reciprocal condition numbers RCONDE and RCONDV, see Section 4.8 of Anderson et al. (1999) (where these quantities are called s and sep respectively).

4 References

Anderson E, Bai Z, Bischof C, Blackford S, Demmel J, Dongarra J J, Du Croz J J, Greenbaum A, Hammarling S, McKenney A and Sorensen D (1999) LAPACK Users' Guide (3rd Edition) SIAM, Philadelphia http://www.netlib.org/lapack/lug
Golub G H and Van Loan C F (1996) Matrix Computations (3rd Edition) Johns Hopkins University Press, Baltimore

5 Arguments

1:   JOBVS – CHARACTER(1)Input
On entry: if JOBVS='N', Schur vectors are not computed.
If JOBVS='V', Schur vectors are computed.
Constraint: JOBVS='N' or 'V'.
2:   SORT – CHARACTER(1)Input
On entry: specifies whether or not to order the eigenvalues on the diagonal of the Schur form.
SORT='N'
Eigenvalues are not ordered.
SORT='S'
Eigenvalues are ordered (see SELECT).
Constraint: SORT='N' or 'S'.
3:   SELECT – LOGICAL FUNCTION, supplied by the user.External Procedure
If SORT='S', SELECT is used to select eigenvalues to sort to the top left of the Schur form.
If SORT='N', SELECT is not referenced and F08PBF (DGEESX) may be called with the dummy function F08PAZ.
An eigenvalue WR j+-1×WI j is selected if SELECT WR j,WI j is .TRUE.. If either one of a complex conjugate pair of eigenvalues is selected, then both are. Note that a selected complex eigenvalue may no longer satisfy SELECT WR j,WI j=.TRUE. after ordering, since ordering may change the value of complex eigenvalues (especially if the eigenvalue is ill-conditioned); in this case INFO is set to N+2 (see INFO below).
The specification of SELECT is:
FUNCTION SELECT ( WR, WI)
LOGICAL SELECT
REAL (KIND=nag_wp) WR, WI
1:   WR – REAL (KIND=nag_wp)Input
2:   WI – REAL (KIND=nag_wp)Input
On entry: the real and imaginary parts of the eigenvalue.
SELECT must either be a module subprogram USEd by, or declared as EXTERNAL in, the (sub)program from which F08PBF (DGEESX) is called. Arguments denoted as Input must not be changed by this procedure.
4:   SENSE – CHARACTER(1)Input
On entry: determines which reciprocal condition numbers are computed.
SENSE='N'
None are computed.
SENSE='E'
Computed for average of selected eigenvalues only.
SENSE='V'
Computed for selected right invariant subspace only.
SENSE='B'
Computed for both.
If SENSE='E', 'V' or 'B', SORT='S'.
Constraint: SENSE='N', 'E', 'V' or 'B'.
5:   N – INTEGERInput
On entry: n, the order of the matrix A.
Constraint: N≥0.
6:   A LDA* – REAL (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array A must be at least max 1,N.
On entry: the n by n matrix A.
On exit: A is overwritten by its real Schur form T.
7:   LDA – INTEGERInput
On entry: the first dimension of the array A as declared in the (sub)program from which F08PBF (DGEESX) is called.
Constraint: LDA≥max 1,N.
8:   SDIM – INTEGEROutput
On exit: if SORT='N', SDIM=0.
If SORT='S', SDIM= number of eigenvalues (after sorting) for which SELECT is .TRUE.. (Complex conjugate pairs for which SELECT is .TRUE. for either eigenvalue count as 2.)
9:   WR* – REAL (KIND=nag_wp) arrayOutput
Note: the dimension of the array WR must be at least max 1,N.
On exit: see the description of WI.
10:   WI* – REAL (KIND=nag_wp) arrayOutput
Note: the dimension of the array WI must be at least max 1,N.
On exit: WR and WI contain the real and imaginary parts, respectively, of the computed eigenvalues in the same order that they appear on the diagonal of the output Schur form T. Complex conjugate pairs of eigenvalues will appear consecutively with the eigenvalue having the positive imaginary part first.
11:   VS LDVS* – REAL (KIND=nag_wp) arrayOutput
Note: the second dimension of the array VS must be at least max 1,N if JOBVS='V', and at least 1 otherwise.
On exit: if JOBVS='V', VS contains the orthogonal matrix Z of Schur vectors.
If JOBVS='N', VS is not referenced.
12:   LDVS – INTEGERInput
On entry: the first dimension of the array VS as declared in the (sub)program from which F08PBF (DGEESX) is called.
Constraints:
  • if JOBVS='V', LDVS≥ max 1,N ;
  • otherwise LDVS≥1.
13:   RCONDE – REAL (KIND=nag_wp)Output
On exit: if SENSE='E' or 'B', contains the reciprocal condition number for the average of the selected eigenvalues.
If SENSE='N' or 'V', RCONDE is not referenced.
14:   RCONDV – REAL (KIND=nag_wp)Output
On exit: if SENSE='V' or 'B', RCONDV contains the reciprocal condition number for the selected right invariant subspace.
If SENSE='N' or 'E', RCONDV is not referenced.
15:   WORK max 1,LWORK – REAL (KIND=nag_wp) arrayWorkspace
On exit: if INFO=0, WORK 1 contains the minimum value of LWORK required for optimal performance.
16:   LWORK – INTEGERInput
On entry: the dimension of the array WORK as declared in the (sub)program from which F08PBF (DGEESX) is called.
If LWORK=-1, a workspace query is assumed; the routine only calculates upper bounds on the optimal sizes of the WORK and IWORK arrays, returns these values as the first entries of the WORK and IWORK arrays, and no error messages related to LWORK or LIWORK is issued.
If SENSE='E', 'V' or 'B', LWORK≥N+2×SDIM×N-SDIM, where SDIM is the number of selected eigenvalues computed by this routine. Note that N+2×SDIM×N-SDIM≤N+N×N/2.
Note also that an error is only returned if LWORK<max 1,3×N, but if SENSE='E', 'V' or 'B' this may not be large enough.
Suggested value: for optimal performance, LWORK must generally be larger than the minimum; increase the workspace by, say, nb×N , where nb is the optimal block size for F08NEF (DGEHRD).
Constraint: LWORK≥max 1,3×N.
17:   IWORK max 1,LIWORK – INTEGER arrayWorkspace
On exit: if INFO=0, IWORK 1 returns the optimal LIWORK.
18:   LIWORK – INTEGERInput
On entry: the dimension of the array IWORK as declared in the (sub)program from which F08PBF (DGEESX) is called.
If LIWORK=-1, a workspace query is assumed; the routine only calculates upper bounds on the optimal sizes of the WORK and IWORK arrays, returns these values as the first entries of the WORK and IWORK arrays, and no error messages related to LWORK or LIWORK is issued.
Constraints:
  • if SENSE='V' or 'B', LIWORK≥SDIM×N-SDIM;
  • otherwise LIWORK≥1.
Note: SDIM×N-SDIM≤N×N/4. Note also that an error is only returned if LIWORK<1, but if SENSE='V' or 'B' this may not be large enough.
19:   BWORK* – LOGICAL arrayWorkspace
Note: the dimension of the array BWORK must be at least max 1,N if SORT≠'N', and at least 1 otherwise.
If SORT='N', BWORK is not referenced.
20:   INFO – INTEGEROutput
On exit: INFO=0 unless the routine detects an error (see Section 6).

6 Error Indicators and Warnings

INFO<0
If INFO=-i, argument i had an illegal value. An explanatory message is output, and execution of the program is terminated.
INFO=1 to N
If INFO=i and i≤N, the QR algorithm failed to compute all the eigenvalues.
INFO=N+1
The eigenvalues could not be reordered because some eigenvalues were too close to separate (the problem is very ill-conditioned).
INFO=N+2
After reordering, roundoff changed values of some complex eigenvalues so that leading eigenvalues in the Schur form no longer satisfy SELECT=.TRUE.. This could also be caused by underflow due to scaling.

7 Accuracy

The computed Schur factorization satisfies
A+E = ZT ZT ,
where
E 2 = O ε A 2 ,
and ε is the machine precision. See Section 4.8 of Anderson et al. (1999) for further details.

8 Parallelism and Performance

F08PBF (DGEESX) is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
F08PBF (DGEESX) makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The total number of floating-point operations is proportional to n 3.
The complex analogue of this routine is F08PPF (ZGEESX).

10 Example

This example finds the Schur factorization of the matrix
A = 0.35 0.45 -0.14 -0.17 0.09 0.07 -0.54 0.35 -0.44 -0.33 -0.03 0.17 0.25 -0.32 -0.13 0.11 ,
such that the real positive eigenvalues of A are the top left diagonal elements of the Schur form, T. Estimates of the condition numbers for the selected eigenvalue cluster and corresponding invariant subspace are also returned.
Note that the block size (NB) of 64 assumed in this example is not realistic for such a small problem, but should be suitable for large problems.

10.1 Program Text

Program Text (f08pbfe.f90)

10.2 Program Data

Program Data (f08pbfe.d)

10.3 Program Results

Program Results (f08pbfe.r)

F08 Chapter Contents
F08 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F08PEF (DHSEQR) : NAG Library, Mark 26

F08 Chapter Contents
F08 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F08PEF (DHSEQR)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.
Warning. The specification of the argument LWORK changed at Mark 20: LWORK is no longer redundant.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F08PEF (DHSEQR) computes all the eigenvalues and, optionally, the Schur factorization of a real Hessenberg matrix or a real general matrix which has been reduced to Hessenberg form.

2 Specification

SUBROUTINE F08PEF ( JOB, COMPZ, N, ILO, IHI, H, LDH, WR, WI, Z, LDZ, WORK, LWORK, INFO)
INTEGER | N, ILO, IHI, LDH, LDZ, LWORK, INFO
REAL (KIND=nag_wp) | H(LDH,*), WR(*), WI(*), Z(LDZ,*), WORK(max(1,LWORK))
CHARACTER(1) | JOB, COMPZ
The routine may be called by its LAPACK name dhseqr.

3 Description

F08PEF (DHSEQR) computes all the eigenvalues and, optionally, the Schur factorization of a real upper Hessenberg matrix H:
H = ZT ZT ,
where T is an upper quasi-triangular matrix (the Schur form of H), and Z is the orthogonal matrix whose columns are the Schur vectors zi. See Section 9 for details of the structure of T.
The routine may also be used to compute the Schur factorization of a real general matrix A which has been reduced to upper Hessenberg form H:
A = QH QT, where ​Q​ is orthogonal, = QZ T QZ T.
In this case, after F08NEF (DGEHRD) has been called to reduce A to Hessenberg form, F08NFF (DORGHR) must be called to form Q explicitly; Q is then passed to F08PEF (DHSEQR), which must be called with COMPZ='V'.
The routine can also take advantage of a previous call to F08NHF (DGEBAL) which may have balanced the original matrix before reducing it to Hessenberg form, so that the Hessenberg matrix H has the structure:
H 11 H 12 H 13 H 22 H 23 H 33
where H 11 and H 33 are upper triangular. If so, only the central diagonal block H 22 (in rows and columns ilo to ihi) needs to be further reduced to Schur form (the blocks H 12 and H 23 are also affected). Therefore the values of ilo and ihi can be supplied to F08PEF (DHSEQR) directly. Also, F08NJF (DGEBAK) must be called after this routine to permute the Schur vectors of the balanced matrix to those of the original matrix. If F08NHF (DGEBAL) has not been called however, then ilo must be set to 1 and ihi to n. Note that if the Schur factorization of A is required, F08NHF (DGEBAL) must not be called with JOB='S' or 'B', because the balancing transformation is not orthogonal.
F08PEF (DHSEQR) uses a multishift form of the upper Hessenberg QR algorithm, due to Bai and Demmel (1989). The Schur vectors are normalized so that zi 2=1, but are determined only to within a factor ±1.

4 References

Bai Z and Demmel J W (1989) On a block implementation of Hessenberg multishift QR iteration Internat. J. High Speed Comput. 1 97–112
Golub G H and Van Loan C F (1996) Matrix Computations (3rd Edition) Johns Hopkins University Press, Baltimore

5 Arguments

1:   JOB – CHARACTER(1)Input
On entry: indicates whether eigenvalues only or the Schur form T is required.
JOB='E'
Eigenvalues only are required.
JOB='S'
The Schur form T is required.
Constraint: JOB='E' or 'S'.
2:   COMPZ – CHARACTER(1)Input
On entry: indicates whether the Schur vectors are to be computed.
COMPZ='N'
No Schur vectors are computed (and the array Z is not referenced).
COMPZ='V'
The Schur vectors of A are computed (and the array Z must contain the matrix Q on entry).
COMPZ='I'
The Schur vectors of H are computed (and the array Z is initialized by the routine).
Constraint: COMPZ='N', 'V' or 'I'.
3:   N – INTEGERInput
On entry: n, the order of the matrix H.
Constraint: N≥0.
4:   ILO – INTEGERInput
5:   IHI – INTEGERInput
On entry: if the matrix A has been balanced by F08NHF (DGEBAL), then ILO and IHI must contain the values returned by that routine. Otherwise, ILO must be set to 1 and IHI to N.
Constraint: ILO≥1 and min ILO,N ≤ IHI≤N .
6:   H LDH* – REAL (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array H must be at least max 1,N.
On entry: the n by n upper Hessenberg matrix H, as returned by F08NEF (DGEHRD).
On exit: if JOB='E', the array contains no useful information.
If JOB='S', H is overwritten by the upper quasi-triangular matrix T from the Schur decomposition (the Schur form) unless INFO>0.
7:   LDH – INTEGERInput
On entry: the first dimension of the array H as declared in the (sub)program from which F08PEF (DHSEQR) is called.
Constraint: LDH≥max 1,N.
8:   WR* – REAL (KIND=nag_wp) arrayOutput
9:   WI* – REAL (KIND=nag_wp) arrayOutput
Note: the dimension of the arrays WR and WI must be at least max 1,N.
On exit: the real and imaginary parts, respectively, of the computed eigenvalues, unless INFO>0 (in which case see Section 6). Complex conjugate pairs of eigenvalues appear consecutively with the eigenvalue having positive imaginary part first. The eigenvalues are stored in the same order as on the diagonal of the Schur form T (if computed); see Section 9 for details.
10:   Z LDZ* – REAL (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array Z must be at least max 1,N if COMPZ='V' or 'I' and at least 1 if COMPZ='N'.
On entry: if COMPZ='V', Z must contain the orthogonal matrix Q from the reduction to Hessenberg form.
If COMPZ='I', Z need not be set.
On exit: if COMPZ='V' or 'I', Z contains the orthogonal matrix of the required Schur vectors, unless INFO>0.
If COMPZ='N', Z is not referenced.
11:   LDZ – INTEGERInput
On entry: the first dimension of the array Z as declared in the (sub)program from which F08PEF (DHSEQR) is called.
Constraints:
  • if COMPZ='V' or 'I', LDZ≥ max 1,N ;
  • if COMPZ='N', LDZ≥1.
12:   WORK max 1,LWORK – REAL (KIND=nag_wp) arrayWorkspace
On exit: if INFO=0, WORK 1 contains the minimum value of LWORK required for optimal performance.
13:   LWORK – INTEGERInput
On entry: the dimension of the array WORK as declared in the (sub)program from which F08PEF (DHSEQR) is called, unless LWORK=-1, in which case a workspace query is assumed and the routine only calculates the minimum dimension of WORK.
Constraint: LWORK≥max 1,N or LWORK=-1.
14:   INFO – INTEGEROutput
On exit: INFO=0 unless the routine detects an error (see Section 6).

6 Error Indicators and Warnings

INFO<0
If INFO=-i, argument i had an illegal value. An explanatory message is output, and execution of the program is terminated.
INFO>0
The algorithm has failed to find all the eigenvalues after a total of 30×IHI-ILO+1 iterations. If INFO=i, elements 1,2,…,ILO-1 and i+1,i+2,…,n of WR and WI contain the real and imaginary parts of contain the eigenvalues which have been found.
If JOB='E', then on exit, the remaining unconverged eigenvalues are the eigenvalues of the upper Hessenberg matrix H^, formed from H ILO:INFOILO:INFO , i.e., the ILO through INFO rows and columns of the final output matrix H.
If JOB='S', then on exit
*   Hi U = U H~
for some matrix U, where Hi is the input upper Hessenberg matrix and H~ is an upper Hessenberg matrix formed from H INFO+1:IHIINFO+1:IHI .
If COMPZ='V', then on exit
Zout = Zin U
where U is defined in * (regardless of the value of JOB).
If COMPZ='I', then on exit
Zout = U
where U is defined in * (regardless of the value of JOB).
If INFO>0 and COMPZ='N', then Z is not accessed.

7 Accuracy

The computed Schur factorization is the exact factorization of a nearby matrix H+E, where
E 2 = O ε H 2 ,
and ε is the machine precision.
If λi is an exact eigenvalue, and λ~i is the corresponding computed value, then
λ~i - λi ≤ c n ε H 2 si ,
where c n is a modestly increasing function of n, and si is the reciprocal condition number of λi. The condition numbers si may be computed by calling F08QLF (DTRSNA).

8 Parallelism and Performance

F08PEF (DHSEQR) is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
F08PEF (DHSEQR) makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The total number of floating-point operations depends on how rapidly the algorithm converges, but is typically about:
  • 7 n 3 if only eigenvalues are computed;
  • 10 n 3 if the Schur form is computed;
  • 20 n 3 if the full Schur factorization is computed.
The Schur form T has the following structure (referred to as canonical Schur form).
If all the computed eigenvalues are real, T is upper triangular, and the diagonal elements of T are the eigenvalues; WR i=t ii, for i=1,2,…,n, and WI i=0.0.
If some of the computed eigenvalues form complex conjugate pairs, then T has 2 by 2 diagonal blocks. Each diagonal block has the form
t ii t i,i+1 t i+1,i t i+1,i+1 = α β γ α
where βγ<0. The corresponding eigenvalues are α±βγ; WR i=WR i+1=α; WI i=+βγ; WI i+1=-WI i.
The complex analogue of this routine is F08PSF (ZHSEQR).

10 Example

This example computes all the eigenvalues and the Schur factorization of the upper Hessenberg matrix H, where
H = 0.3500 -0.1160 -0.3886 -0.2942 -0.5140 0.1225 0.1004 0.1126 0.0000 0.6443 -0.1357 -0.0977 0.0000 0.0000 0.4262 0.1632 .
See also Section 10 in F08NFF (DORGHR), which illustrates the use of this routine to compute the Schur factorization of a general matrix.

10.1 Program Text

Program Text (f08pefe.f90)

10.2 Program Data

Program Data (f08pefe.d)

10.3 Program Results

Program Results (f08pefe.r)

F08 Chapter Contents
F08 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F08PKF (DHSEIN) : NAG Library, Mark 26

F08 Chapter Contents
F08 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F08PKF (DHSEIN)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
10 Example

1 Purpose

F08PKF (DHSEIN) computes selected left and/or right eigenvectors of a real upper Hessenberg matrix corresponding to specified eigenvalues, by inverse iteration.

2 Specification

SUBROUTINE F08PKF ( JOB, EIGSRC, INITV, SELECT, N, H, LDH, WR, WI, VL, LDVL, VR, LDVR, MM, M, WORK, IFAILL, IFAILR, INFO)
INTEGER | N, LDH, LDVL, LDVR, MM, M, IFAILL(*), IFAILR(*), INFO
REAL (KIND=nag_wp) | H(LDH,*), WR(*), WI(*), VL(LDVL,*), VR(LDVR,*), WORK((N+2)*N)
LOGICAL | SELECT(*)
CHARACTER(1) | JOB, EIGSRC, INITV
The routine may be called by its LAPACK name dhsein.

3 Description

F08PKF (DHSEIN) computes left and/or right eigenvectors of a real upper Hessenberg matrix H, corresponding to selected eigenvalues.
The right eigenvector x, and the left eigenvector y, corresponding to an eigenvalue λ, are defined by:
Hx = λx   and   yH H = λ yH   or HT y = λ-y .
Note that even though H is real, λ, x and y may be complex. If x is an eigenvector corresponding to a complex eigenvalue λ, then the complex conjugate vector x- is the eigenvector corresponding to the complex conjugate eigenvalue λ-.
The eigenvectors are computed by inverse iteration. They are scaled so that, for a real eigenvector x, max xi = 1 , and for a complex eigenvector, max⁡ Re xi + Im⁡xi = 1 .
If H has been formed by reduction of a real general matrix A to upper Hessenberg form, then the eigenvectors of H may be transformed to eigenvectors of A by a call to F08NGF (DORMHR).

4 References

Golub G H and Van Loan C F (1996) Matrix Computations (3rd Edition) Johns Hopkins University Press, Baltimore

5 Arguments

1:   JOB – CHARACTER(1)Input
On entry: indicates whether left and/or right eigenvectors are to be computed.
JOB='R'
Only right eigenvectors are computed.
JOB='L'
Only left eigenvectors are computed.
JOB='B'
Both left and right eigenvectors are computed.
Constraint: JOB='R', 'L' or 'B'.
2:   EIGSRC – CHARACTER(1)Input
On entry: indicates whether the eigenvalues of H (stored in WR and WI) were found using F08PEF (DHSEQR).
EIGSRC='Q'
The eigenvalues of H were found using F08PEF (DHSEQR); thus if H has any zero subdiagonal elements (and so is block triangular), then the jth eigenvalue can be assumed to be an eigenvalue of the block containing the jth row/column. This property allows the routine to perform inverse iteration on just one diagonal block.
EIGSRC='N'
No such assumption is made and the routine performs inverse iteration using the whole matrix.
Constraint: EIGSRC='Q' or 'N'.
3:   INITV – CHARACTER(1)Input
On entry: indicates whether you are supplying initial estimates for the selected eigenvectors.
INITV='N'
No initial estimates are supplied.
INITV='U'
Initial estimates are supplied in VL and/or VR.
Constraint: INITV='N' or 'U'.
4:   SELECT* – LOGICAL arrayInput/Output
Note: the dimension of the array SELECT must be at least max 1,N.
On entry: specifies which eigenvectors are to be computed. To obtain the real eigenvector corresponding to the real eigenvalue WR j, SELECT j must be set .TRUE.. To select the complex eigenvector corresponding to the complex eigenvalue WR j,WI j with complex conjugate (WR j+1,WI j+1), SELECT j and/or SELECT j+1 must be set .TRUE.; the eigenvector corresponding to the first eigenvalue in the pair is computed.
On exit: if a complex eigenvector was selected as specified above, then SELECT j is set to .TRUE. and SELECT j+1 to .FALSE..
5:   N – INTEGERInput
On entry: n, the order of the matrix H.
Constraint: N≥0.
6:   H LDH* – REAL (KIND=nag_wp) arrayInput
Note: the second dimension of the array H must be at least max 1,N.
On entry: the n by n upper Hessenberg matrix H. If a NaN is detected in H, the routine will return with INFO=-6.
Constraint: No element of H is equal to NaN.
7:   LDH – INTEGERInput
On entry: the first dimension of the array H as declared in the (sub)program from which F08PKF (DHSEIN) is called.
Constraint: LDH≥max 1,N.
8:   WR* – REAL (KIND=nag_wp) arrayInput/Output
9:   WI* – REAL (KIND=nag_wp) arrayInput
Note: the dimension of the arrays WR and WI must be at least max 1,N.
On entry: the real and imaginary parts, respectively, of the eigenvalues of the matrix H. Complex conjugate pairs of values must be stored in consecutive elements of the arrays. If EIGSRC='Q', the arrays must be exactly as returned by F08PEF (DHSEQR).
On exit: some elements of WR may be modified, as close eigenvalues are perturbed slightly in searching for independent eigenvectors.
10:   VL LDVL* – REAL (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array VL must be at least max 1,MM if JOB='L' or 'B' and at least 1 if JOB='R'.
On entry: if INITV='U' and JOB='L' or 'B', VL must contain starting vectors for inverse iteration for the left eigenvectors. Each starting vector must be stored in the same column or columns as will be used to store the corresponding eigenvector (see below).
If INITV='N', VL need not be set.
On exit: if JOB='L' or 'B', VL contains the computed left eigenvectors (as specified by SELECT). The eigenvectors are stored consecutively in the columns of the array, in the same order as their eigenvalues. Corresponding to each selected real eigenvalue is a real eigenvector, occupying one column. Corresponding to each selected complex eigenvalue is a complex eigenvector, occupying two columns: the first column holds the real part and the second column holds the imaginary part.
If JOB='R', VL is not referenced.
11:   LDVL – INTEGERInput
On entry: the first dimension of the array VL as declared in the (sub)program from which F08PKF (DHSEIN) is called.
Constraints:
  • if JOB='L' or 'B', LDVL≥N;
  • if JOB='R', LDVL≥1.
12:   VR LDVR* – REAL (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array VR must be at least max 1,MM if JOB='R' or 'B' and at least 1 if JOB='L'.
On entry: if INITV='U' and JOB='R' or 'B', VR must contain starting vectors for inverse iteration for the right eigenvectors. Each starting vector must be stored in the same column or columns as will be used to store the corresponding eigenvector (see below).
If INITV='N', VR need not be set.
On exit: if JOB='R' or 'B', VR contains the computed right eigenvectors (as specified by SELECT). The eigenvectors are stored consecutively in the columns of the array, in the same order as their eigenvalues. Corresponding to each selected real eigenvalue is a real eigenvector, occupying one column. Corresponding to each selected complex eigenvalue is a complex eigenvector, occupying two columns: the first column holds the real part and the second column holds the imaginary part.
If JOB='L', VR is not referenced.
13:   LDVR – INTEGERInput
On entry: the first dimension of the array VR as declared in the (sub)program from which F08PKF (DHSEIN) is called.
Constraints:
  • if JOB='R' or 'B', LDVR≥N;
  • if JOB='L', LDVR≥1.
14:   MM – INTEGERInput
On entry: the number of columns in the arrays VL and/or VR . The actual number of columns required, m, is obtained by counting 1 for each selected real eigenvector and 2 for each selected complex eigenvector (see SELECT); 0≤m≤n.
Constraint: MM≥m.
15:   M – INTEGEROutput
On exit: m, the number of columns of VL and/or VR required to store the selected eigenvectors.
16:   WORK N+2×N – REAL (KIND=nag_wp) arrayWorkspace
17:   IFAILL* – INTEGER arrayOutput
Note: the dimension of the array IFAILL must be at least max 1,MM if JOB='L' or 'B' and at least 1 if JOB='R'.
On exit: if JOB='L' or 'B', then IFAILL i=0 if the selected left eigenvector converged and IFAILL i=j>0 if the eigenvector stored in the ith column of VL (corresponding to the jth eigenvalue as held in WR j,WI j failed to converge. If the ith and i+1th columns of VL contain a selected complex eigenvector, then IFAILL i and IFAILL i+1 are set to the same value.
If JOB='R', IFAILL is not referenced.
18:   IFAILR* – INTEGER arrayOutput
Note: the dimension of the array IFAILR must be at least max 1,MM if JOB='R' or 'B' and at least 1 if JOB='L'.
On exit: if JOB='R' or 'B', then IFAILR i=0 if the selected right eigenvector converged and IFAILR i=j>0 if the eigenvector stored in the ith row or column of VR (corresponding to the jth eigenvalue as held in WR j,WI j) failed to converge. If the ith and i+1th rows or columns of VR contain a selected complex eigenvector, then IFAILR i and IFAILR i+1 are set to the same value.
If JOB='L', IFAILR is not referenced.
19:   INFO – INTEGEROutput
On exit: INFO=0 unless the routine detects an error (see Section 6).

6 Error Indicators and Warnings

INFO<0
If INFO=-i, argument i had an illegal value. An explanatory message is output, and execution of the program is terminated.
INFO>0
If INFO=i, then i eigenvectors (as indicated by the arguments IFAILL and/or IFAILR above) failed to converge. The corresponding columns of VL and/or VR contain no useful information.

7 Accuracy

Each computed right eigenvector xi is the exact eigenvector of a nearby matrix A+Ei, such that Ei=O ε A. Hence the residual is small:
A xi - λixi = O ε A .
However, eigenvectors corresponding to close or coincident eigenvalues may not accurately span the relevant subspaces.
Similar remarks apply to computed left eigenvectors.

8 Parallelism and Performance

F08PKF (DHSEIN) is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
F08PKF (DHSEIN) makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The complex analogue of this routine is F08PXF (ZHSEIN).

10 Example

See Section 10 in F08NGF (DORMHR).
F08 Chapter Contents
F08 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F08PNF (ZGEES) : NAG Library, Mark 26

F08 Chapter Contents
F08 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F08PNF (ZGEES)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F08PNF (ZGEES) computes the eigenvalues, the Schur form T, and, optionally, the matrix of Schur vectors Z for an n by n complex nonsymmetric matrix A.

2 Specification

SUBROUTINE F08PNF ( JOBVS, SORT, SELECT, N, A, LDA, SDIM, W, VS, LDVS, WORK, LWORK, RWORK, BWORK, INFO)
INTEGER | N, LDA, SDIM, LDVS, LWORK, INFO
REAL (KIND=nag_wp) | RWORK(*)
COMPLEX (KIND=nag_wp) | A(LDA,*), W(*), VS(LDVS,*), WORK(max(1,LWORK))
LOGICAL | SELECT, BWORK(*)
CHARACTER(1) | JOBVS, SORT
EXTERNAL | SELECT
The routine may be called by its LAPACK name zgees.

3 Description

The Schur factorization of A is given by
A = Z T ZH ,
where Z, the matrix of Schur vectors, is unitary and T is the Schur form. A complex matrix is in Schur form if it is upper triangular.
Optionally, F08PNF (ZGEES) also orders the eigenvalues on the diagonal of the Schur form so that selected eigenvalues are at the top left. The leading columns of Z form an orthonormal basis for the invariant subspace corresponding to the selected eigenvalues.

4 References

Anderson E, Bai Z, Bischof C, Blackford S, Demmel J, Dongarra J J, Du Croz J J, Greenbaum A, Hammarling S, McKenney A and Sorensen D (1999) LAPACK Users' Guide (3rd Edition) SIAM, Philadelphia http://www.netlib.org/lapack/lug
Golub G H and Van Loan C F (1996) Matrix Computations (3rd Edition) Johns Hopkins University Press, Baltimore

5 Arguments

1:   JOBVS – CHARACTER(1)Input
On entry: if JOBVS='N', Schur vectors are not computed.
If JOBVS='V', Schur vectors are computed.
Constraint: JOBVS='N' or 'V'.
2:   SORT – CHARACTER(1)Input
On entry: specifies whether or not to order the eigenvalues on the diagonal of the Schur form.
SORT='N'
Eigenvalues are not ordered.
SORT='S'
Eigenvalues are ordered (see SELECT).
Constraint: SORT='N' or 'S'.
3:   SELECT – LOGICAL FUNCTION, supplied by the user.External Procedure
If SORT='S', SELECT is used to select eigenvalues to sort to the top left of the Schur form.
If SORT='N', SELECT is not referenced and F08PNF (ZGEES) may be called with the dummy function F08PNZ.
An eigenvalue W j is selected if SELECT W j is .TRUE..
The specification of SELECT is:
FUNCTION SELECT ( W)
LOGICAL SELECT
COMPLEX (KIND=nag_wp) W
1:   W – COMPLEX (KIND=nag_wp)Input
On entry: the real and imaginary parts of the eigenvalue.
SELECT must either be a module subprogram USEd by, or declared as EXTERNAL in, the (sub)program from which F08PNF (ZGEES) is called. Arguments denoted as Input must not be changed by this procedure.
4:   N – INTEGERInput
On entry: n, the order of the matrix A.
Constraint: N≥0.
5:   A LDA* – COMPLEX (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array A must be at least max 1,N.
On entry: the n by n matrix A.
On exit: A is overwritten by its Schur form T.
6:   LDA – INTEGERInput
On entry: the first dimension of the array A as declared in the (sub)program from which F08PNF (ZGEES) is called.
Constraint: LDA≥max 1,N.
7:   SDIM – INTEGEROutput
On exit: if SORT='N', SDIM=0.
If SORT='S', SDIM= number of eigenvalues for which SELECT is .TRUE..
8:   W* – COMPLEX (KIND=nag_wp) arrayOutput
Note: the dimension of the array W must be at least max 1,N.
On exit: contains the computed eigenvalues, in the same order that they appear on the diagonal of the output Schur form T.
9:   VS LDVS* – COMPLEX (KIND=nag_wp) arrayOutput
Note: the second dimension of the array VS must be at least max 1,N if JOBVS='V', and at least 1 otherwise.
On exit: if JOBVS='V', VS contains the unitary matrix Z of Schur vectors.
If JOBVS='N', VS is not referenced.
10:   LDVS – INTEGERInput
On entry: the first dimension of the array VS as declared in the (sub)program from which F08PNF (ZGEES) is called.
Constraints:
  • if JOBVS='V', LDVS≥ max 1,N ;
  • otherwise LDVS≥1.
11:   WORK max 1,LWORK – COMPLEX (KIND=nag_wp) arrayWorkspace
On exit: if INFO=0, the real part of WORK 1 contains the minimum value of LWORK required for optimal performance.
12:   LWORK – INTEGERInput
On entry: the dimension of the array WORK as declared in the (sub)program from which F08PNF (ZGEES) is called.
If LWORK=-1, a workspace query is assumed; the routine only calculates the optimal size of the WORK array, returns this value as the first entry of the WORK array, and no error message related to LWORK is issued.
Suggested value: for optimal performance, LWORK must generally be larger than the minimum, say 2×N+nb×N , where nb is the optimal block size for F08NSF (ZGEHRD).
Constraint: LWORK≥max 1,2×N.
13:   RWORK* – REAL (KIND=nag_wp) arrayWorkspace
Note: the dimension of the array RWORK must be at least max 1,N.
14:   BWORK* – LOGICAL arrayWorkspace
Note: the dimension of the array BWORK must be at least 1 if SORT='N', and at least max 1,N otherwise.
If SORT='N', BWORK is not referenced.
15:   INFO – INTEGEROutput
On exit: INFO=0 unless the routine detects an error (see Section 6).

6 Error Indicators and Warnings

INFO<0
If INFO=-i, argument i had an illegal value. An explanatory message is output, and execution of the program is terminated.
INFO=1 to N
If INFO=i and i≤N, the QR algorithm failed to compute all the eigenvalues.
INFO=N+1
The eigenvalues could not be reordered because some eigenvalues were too close to separate (the problem is very ill-conditioned).
INFO=N+2
After reordering, roundoff changed values of some complex eigenvalues so that leading eigenvalues in the Schur form no longer satisfy SELECT=.TRUE.. This could also be caused by underflow due to scaling.

7 Accuracy

The computed Schur factorization satisfies
A+E=ZT ZH ,
where
E 2 = O ε A 2 ,
and ε is the machine precision. See Section 4.8 of Anderson et al. (1999) for further details.

8 Parallelism and Performance

F08PNF (ZGEES) is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
F08PNF (ZGEES) makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The total number of floating-point operations is proportional to n 3.
The real analogue of this routine is F08PAF (DGEES).

10 Example

This example finds the Schur factorization of the matrix
A = -3.97-5.04 i -4.11+3.70 i -0.34+1.01 i 1.29-0.86 i 0.34-1.50 i 1.52-0.43 i 1.88-5.38 i 3.36+0.65 i 3.31-3.85 i 2.50+3.45 i 0.88-1.08 i 0.64-1.48 i -1.10+0.82 i 1.81-1.59 i 3.25+1.33 i 1.57-3.44 i .
Note that the block size (NB) of 64 assumed in this example is not realistic for such a small problem, but should be suitable for large problems.

10.1 Program Text

Program Text (f08pnfe.f90)

10.2 Program Data

Program Data (f08pnfe.d)

10.3 Program Results

Program Results (f08pnfe.r)

F08 Chapter Contents
F08 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F08PPF (ZGEESX) : NAG Library, Mark 26

F08 Chapter Contents
F08 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F08PPF (ZGEESX)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F08PPF (ZGEESX) computes the eigenvalues, the Schur form T, and, optionally, the matrix of Schur vectors Z for an n by n complex nonsymmetric matrix A.

2 Specification

SUBROUTINE F08PPF ( JOBVS, SORT, SELECT, SENSE, N, A, LDA, SDIM, W, VS, LDVS, RCONDE, RCONDV, WORK, LWORK, RWORK, BWORK, INFO)
INTEGER | N, LDA, SDIM, LDVS, LWORK, INFO
REAL (KIND=nag_wp) | RCONDE, RCONDV, RWORK(*)
COMPLEX (KIND=nag_wp) | A(LDA,*), W(*), VS(LDVS,*), WORK(max(1,LWORK))
LOGICAL | SELECT, BWORK(*)
CHARACTER(1) | JOBVS, SORT, SENSE
EXTERNAL | SELECT
The routine may be called by its LAPACK name zgeesx.

3 Description

The Schur factorization of A is given by
A = Z T ZH ,
where Z, the matrix of Schur vectors, is unitary and T is the Schur form. A complex matrix is in Schur form if it is upper triangular.
Optionally, F08PPF (ZGEESX) also orders the eigenvalues on the diagonal of the Schur form so that selected eigenvalues are at the top left; computes a reciprocal condition number for the average of the selected eigenvalues (RCONDE); and computes a reciprocal condition number for the right invariant subspace corresponding to the selected eigenvalues (RCONDV). The leading columns of Z form an orthonormal basis for this invariant subspace.
For further explanation of the reciprocal condition numbers RCONDE and RCONDV, see Section 4.8 of Anderson et al. (1999) (where these quantities are called s and sep respectively).

4 References

Anderson E, Bai Z, Bischof C, Blackford S, Demmel J, Dongarra J J, Du Croz J J, Greenbaum A, Hammarling S, McKenney A and Sorensen D (1999) LAPACK Users' Guide (3rd Edition) SIAM, Philadelphia http://www.netlib.org/lapack/lug
Golub G H and Van Loan C F (1996) Matrix Computations (3rd Edition) Johns Hopkins University Press, Baltimore

5 Arguments

1:   JOBVS – CHARACTER(1)Input
On entry: if JOBVS='N', Schur vectors are not computed.
If JOBVS='V', Schur vectors are computed.
Constraint: JOBVS='N' or 'V'.
2:   SORT – CHARACTER(1)Input
On entry: specifies whether or not to order the eigenvalues on the diagonal of the Schur form.
SORT='N'
Eigenvalues are not ordered.
SORT='S'
Eigenvalues are ordered (see SELECT).
Constraint: SORT='N' or 'S'.
3:   SELECT – LOGICAL FUNCTION, supplied by the user.External Procedure
If SORT='S', SELECT is used to select eigenvalues to sort to the top left of the Schur form.
If SORT='N', SELECT is not referenced and F08PPF (ZGEESX) may be called with the dummy function F08PNZ.
An eigenvalue W j is selected if SELECT W j is .TRUE..
The specification of SELECT is:
FUNCTION SELECT ( W)
LOGICAL SELECT
COMPLEX (KIND=nag_wp) W
1:   W – COMPLEX (KIND=nag_wp)Input
On entry: the real and imaginary parts of the eigenvalue.
SELECT must either be a module subprogram USEd by, or declared as EXTERNAL in, the (sub)program from which F08PPF (ZGEESX) is called. Arguments denoted as Input must not be changed by this procedure.
4:   SENSE – CHARACTER(1)Input
On entry: determines which reciprocal condition numbers are computed.
SENSE='N'
None are computed.
SENSE='E'
Computed for average of selected eigenvalues only.
SENSE='V'
Computed for selected right invariant subspace only.
SENSE='B'
Computed for both.
If SENSE='E', 'V' or 'B', SORT='S'.
Constraint: SENSE='N', 'E', 'V' or 'B'.
5:   N – INTEGERInput
On entry: n, the order of the matrix A.
Constraint: N≥0.
6:   A LDA* – COMPLEX (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array A must be at least max 1,N.
On entry: the n by n matrix A.
On exit: A is overwritten by its Schur form T.
7:   LDA – INTEGERInput
On entry: the first dimension of the array A as declared in the (sub)program from which F08PPF (ZGEESX) is called.
Constraint: LDA≥max 1,N.
8:   SDIM – INTEGEROutput
On exit: if SORT='N', SDIM=0.
If SORT='S', SDIM= number of eigenvalues for which SELECT is .TRUE..
9:   W* – COMPLEX (KIND=nag_wp) arrayOutput
Note: the dimension of the array W must be at least max 1,N.
On exit: contains the computed eigenvalues, in the same order that they appear on the diagonal of the output Schur form T.
10:   VS LDVS* – COMPLEX (KIND=nag_wp) arrayOutput
Note: the second dimension of the array VS must be at least max 1,N if JOBVS='V', and at least 1 otherwise.
On exit: if JOBVS='V', VS contains the unitary matrix Z of Schur vectors.
If JOBVS='N', VS is not referenced.
11:   LDVS – INTEGERInput
On entry: the first dimension of the array VS as declared in the (sub)program from which F08PPF (ZGEESX) is called.
Constraints:
  • if JOBVS='V', LDVS≥ max 1,N ;
  • otherwise LDVS≥1.
12:   RCONDE – REAL (KIND=nag_wp)Output
On exit: if SENSE='E' or 'B', contains the reciprocal condition number for the average of the selected eigenvalues.
If SENSE='N' or 'V', RCONDE is not referenced.
13:   RCONDV – REAL (KIND=nag_wp)Output
On exit: if SENSE='V' or 'B', RCONDV contains the reciprocal condition number for the selected right invariant subspace.
If SENSE='N' or 'E', RCONDV is not referenced.
14:   WORK max 1,LWORK – COMPLEX (KIND=nag_wp) arrayWorkspace
On exit: if INFO=0, the real part of WORK 1 contains the minimum value of LWORK required for optimal performance.
15:   LWORK – INTEGERInput
On entry: the dimension of the array WORK as declared in the (sub)program from which F08PPF (ZGEESX) is called.
If LWORK=-1, a workspace query is assumed; the routine only calculates an upper bound on the optimal size of the WORK array, returns this value as the first entry of the WORK array, and no error message related to LWORK is issued.
If SENSE='E', 'V' or 'B', LWORK≥2×SDIM×N-SDIM, where SDIM is the number of selected eigenvalues computed by this routine.
Note that 2×SDIM×N-SDIM≤N×N/2. Note also that an error is only returned if LWORK<max 1,2×N, but if SENSE='E', 'V' or 'B' this may not be large enough.
Suggested value: for optimal performance, LWORK must generally be larger than the minimum; increase the workspace by, say, nb×N , where nb is the optimal block size for F08NSF (ZGEHRD).
Constraint: LWORK≥max 1,2×N.
16:   RWORK* – REAL (KIND=nag_wp) arrayWorkspace
Note: the dimension of the array RWORK must be at least max 1,N.
17:   BWORK* – LOGICAL arrayWorkspace
Note: the dimension of the array BWORK must be at least 1 if SORT='N', and at least max 1,N otherwise.
If SORT='N', BWORK is not referenced.
18:   INFO – INTEGEROutput
On exit: INFO=0 unless the routine detects an error (see Section 6).

6 Error Indicators and Warnings

INFO<0
If INFO=-i, argument i had an illegal value. An explanatory message is output, and execution of the program is terminated.
INFO=1 to N
If INFO=i and i≤N, the QR algorithm failed to compute all the eigenvalues.
INFO=N+1
The eigenvalues could not be reordered because some eigenvalues were too close to separate (the problem is very ill-conditioned).
INFO=N+2
After reordering, roundoff changed values of some complex eigenvalues so that leading eigenvalues in the Schur form no longer satisfy SELECT=.TRUE.. This could also be caused by underflow due to scaling.

7 Accuracy

The computed Schur factorization satisfies
A+E = ZT ZH ,
where
E 2 = O ε A 2 ,
and ε is the machine precision. See Section 4.8 of Anderson et al. (1999) for further details.

8 Parallelism and Performance

F08PPF (ZGEESX) is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
F08PPF (ZGEESX) makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The total number of floating-point operations is proportional to n 3.
The real analogue of this routine is F08PBF (DGEESX).

10 Example

This example finds the Schur factorization of the matrix
A = -3.97-5.04 i -4.11+3.70 i -0.34+1.01 i 1.29-0.86 i 0.34-1.50 i 1.52-0.43 i 1.88-5.38 i 3.36+0.65 i 3.31-3.85 i 2.50+3.45 i 0.88-1.08 i 0.64-1.48 i -1.10+0.82 i 1.81-1.59 i 3.25+1.33 i 1.57-3.44 i ,
such that the eigenvalues of A with positive real part of are the top left diagonal elements of the Schur form, T. Estimates of the condition numbers for the selected eigenvalue cluster and corresponding invariant subspace are also returned.
Note that the block size (NB) of 64 assumed in this example is not realistic for such a small problem, but should be suitable for large problems.

10.1 Program Text

Program Text (f08ppfe.f90)

10.2 Program Data

Program Data (f08ppfe.d)

10.3 Program Results

Program Results (f08ppfe.r)

F08 Chapter Contents
F08 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F08PSF (ZHSEQR) : NAG Library, Mark 26

F08 Chapter Contents
F08 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F08PSF (ZHSEQR)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.
Warning. The specification of the argument LWORK changed at Mark 20: LWORK is no longer redundant.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F08PSF (ZHSEQR) computes all the eigenvalues and, optionally, the Schur factorization of a complex Hessenberg matrix or a complex general matrix which has been reduced to Hessenberg form.

2 Specification

SUBROUTINE F08PSF ( JOB, COMPZ, N, ILO, IHI, H, LDH, W, Z, LDZ, WORK, LWORK, INFO)
INTEGER | N, ILO, IHI, LDH, LDZ, LWORK, INFO
COMPLEX (KIND=nag_wp) | H(LDH,*), W(*), Z(LDZ,*), WORK(max(1,LWORK))
CHARACTER(1) | JOB, COMPZ
The routine may be called by its LAPACK name zhseqr.

3 Description

F08PSF (ZHSEQR) computes all the eigenvalues and, optionally, the Schur factorization of a complex upper Hessenberg matrix H:
H = ZT ZH ,
where T is an upper triangular matrix (the Schur form of H), and Z is the unitary matrix whose columns are the Schur vectors zi. The diagonal elements of T are the eigenvalues of H.
The routine may also be used to compute the Schur factorization of a complex general matrix A which has been reduced to upper Hessenberg form H:
A = QH QH, where ​Q​ is unitary, = QZ T QZ H.
In this case, after F08NSF (ZGEHRD) has been called to reduce A to Hessenberg form, F08NTF (ZUNGHR) must be called to form Q explicitly; Q is then passed to F08PSF (ZHSEQR), which must be called with COMPZ='V'.
The routine can also take advantage of a previous call to F08NVF (ZGEBAL) which may have balanced the original matrix before reducing it to Hessenberg form, so that the Hessenberg matrix H has the structure:
H 11 H 12 H 13 H 22 H 23 H 33
where H 11 and H 33 are upper triangular. If so, only the central diagonal block H 22 (in rows and columns ilo to ihi) needs to be further reduced to Schur form (the blocks H 12 and H 23 are also affected). Therefore the values of ilo and ihi can be supplied to F08PSF (ZHSEQR) directly. Also, F08NWF (ZGEBAK) must be called after this routine to permute the Schur vectors of the balanced matrix to those of the original matrix. If F08NVF (ZGEBAL) has not been called however, then ilo must be set to 1 and ihi to n. Note that if the Schur factorization of A is required, F08NVF (ZGEBAL) must not be called with JOB='S' or 'B', because the balancing transformation is not unitary.
F08PSF (ZHSEQR) uses a multishift form of the upper Hessenberg QR algorithm, due to Bai and Demmel (1989). The Schur vectors are normalized so that zi 2=1, but are determined only to within a complex factor of absolute value 1.

4 References

Bai Z and Demmel J W (1989) On a block implementation of Hessenberg multishift QR iteration Internat. J. High Speed Comput. 1 97–112
Golub G H and Van Loan C F (1996) Matrix Computations (3rd Edition) Johns Hopkins University Press, Baltimore

5 Arguments

1:   JOB – CHARACTER(1)Input
On entry: indicates whether eigenvalues only or the Schur form T is required.
JOB='E'
Eigenvalues only are required.
JOB='S'
The Schur form T is required.
Constraint: JOB='E' or 'S'.
2:   COMPZ – CHARACTER(1)Input
On entry: indicates whether the Schur vectors are to be computed.
COMPZ='N'
No Schur vectors are computed (and the array Z is not referenced).
COMPZ='V'
The Schur vectors of A are computed (and the array Z must contain the matrix Q on entry).
COMPZ='I'
The Schur vectors of H are computed (and the array Z is initialized by the routine).
Constraint: COMPZ='N', 'V' or 'I'.
3:   N – INTEGERInput
On entry: n, the order of the matrix H.
Constraint: N≥0.
4:   ILO – INTEGERInput
5:   IHI – INTEGERInput
On entry: if the matrix A has been balanced by F08NVF (ZGEBAL), then ILO and IHI must contain the values returned by that routine. Otherwise, ILO must be set to 1 and IHI to N.
Constraint: ILO≥1 and min ILO,N ≤ IHI≤N .
6:   H LDH* – COMPLEX (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array H must be at least max 1,N.
On entry: the n by n upper Hessenberg matrix H, as returned by F08NSF (ZGEHRD).
On exit: if JOB='E', the array contains no useful information.
If JOB='S', H is overwritten by the upper triangular matrix T from the Schur decomposition (the Schur form) unless INFO>0.
7:   LDH – INTEGERInput
On entry: the first dimension of the array H as declared in the (sub)program from which F08PSF (ZHSEQR) is called.
Constraint: LDH≥max 1,N.
8:   W* – COMPLEX (KIND=nag_wp) arrayOutput
Note: the dimension of the array W must be at least max 1,N.
On exit: the computed eigenvalues, unless INFO>0 (in which case see Section 6). The eigenvalues are stored in the same order as on the diagonal of the Schur form T (if computed).
9:   Z LDZ* – COMPLEX (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array Z must be at least max 1,N if COMPZ='V' or 'I' and at least 1 if COMPZ='N'.
On entry: if COMPZ='V', Z must contain the unitary matrix Q from the reduction to Hessenberg form.
If COMPZ='I', Z need not be set.
On exit: if COMPZ='V' or 'I', Z contains the unitary matrix of the required Schur vectors, unless INFO>0.
If COMPZ='N', Z is not referenced.
10:   LDZ – INTEGERInput
On entry: the first dimension of the array Z as declared in the (sub)program from which F08PSF (ZHSEQR) is called.
Constraints:
  • if COMPZ='V' or 'I', LDZ≥ max 1,N ;
  • if COMPZ='N', LDZ≥1.
11:   WORK max 1,LWORK – COMPLEX (KIND=nag_wp) arrayWorkspace
On exit: if INFO=0, the real part of WORK 1 contains the minimum value of LWORK required for optimal performance.
12:   LWORK – INTEGERInput
On entry: the dimension of the array WORK as declared in the (sub)program from which F08PSF (ZHSEQR) is called, unless LWORK=-1, in which case a workspace query is assumed and the routine only calculates the minimum dimension of WORK.
Constraint: LWORK≥max 1,N or LWORK=-1.
13:   INFO – INTEGEROutput
On exit: INFO=0 unless the routine detects an error (see Section 6).

6 Error Indicators and Warnings

INFO<0
If INFO=-i, argument i had an illegal value.
If INFO=-999, dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.
An explanatory message is output, and execution of the program is terminated.
INFO>0
The algorithm has failed to find all the eigenvalues after a total of 30×IHI-ILO+1 iterations. If INFO=i, elements 1,2,…,ILO-1 and i+1,i+2,…,n of W contain the eigenvalues which have been found.
If JOB='E', then on exit, the remaining unconverged eigenvalues are the eigenvalues of the upper Hessenberg matrix H^, formed from H ILO:INFOILO:INFO , i.e., the ILO through INFO rows and columns of the final output matrix H.
If JOB='S', then on exit
*   Hi U = U H~
for some matrix U, where Hi is the input upper Hessenberg matrix and H~ is an upper Hessenberg matrix formed from H INFO+1:IHIINFO+1:IHI .
If COMPZ='V', then on exit
Zout = Zin U
where U is defined in * (regardless of the value of JOB).
If COMPZ='I', then on exit
Zout = U
where U is defined in * (regardless of the value of JOB).
If INFO>0 and COMPZ='N', then Z is not accessed.

7 Accuracy

The computed Schur factorization is the exact factorization of a nearby matrix H+E, where
E 2 = O ε H 2 ,
and ε is the machine precision.
If λi is an exact eigenvalue, and λ~i is the corresponding computed value, then
λ~i - λi ≤ c n ε H 2 si ,
where c n is a modestly increasing function of n, and si is the reciprocal condition number of λi. The condition numbers si may be computed by calling F08QYF (ZTRSNA).

8 Parallelism and Performance

F08PSF (ZHSEQR) is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
F08PSF (ZHSEQR) makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The total number of real floating-point operations depends on how rapidly the algorithm converges, but is typically about:
  • 25 n 3 if only eigenvalues are computed;
  • 35 n 3 if the Schur form is computed;
  • 70 n 3 if the full Schur factorization is computed.
The real analogue of this routine is F08PEF (DHSEQR).

10 Example

This example computes all the eigenvalues and the Schur factorization of the upper Hessenberg matrix H, where
H = -3.9700-5.0400 i -1.1318-2.5693 i -4.6027-0.1426 i -1.4249+1.7330 i -5.4797+0.0000 i 1.8585-1.5502 i 4.4145-0.7638 i -0.4805-1.1976 i 0.0000+0.0000 i 6.2673+0.0000 i -0.4504-0.0290 i -1.3467+1.6579 i 0.0000+0.0000 i 0.0000+0.0000 i -3.5000+0.0000 i 2.5619-3.3708 i .
See also Section 10 in F08NTF (ZUNGHR), which illustrates the use of this routine to compute the Schur factorization of a general matrix.

10.1 Program Text

Program Text (f08psfe.f90)

10.2 Program Data

Program Data (f08psfe.d)

10.3 Program Results

Program Results (f08psfe.r)

F08 Chapter Contents
F08 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F08PXF (ZHSEIN) : NAG Library, Mark 26

F08 Chapter Contents
F08 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F08PXF (ZHSEIN)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
10 Example

1 Purpose

F08PXF (ZHSEIN) computes selected left and/or right eigenvectors of a complex upper Hessenberg matrix corresponding to specified eigenvalues, by inverse iteration.

2 Specification

SUBROUTINE F08PXF ( JOB, EIGSRC, INITV, SELECT, N, H, LDH, W, VL, LDVL, VR, LDVR, MM, M, WORK, RWORK, IFAILL, IFAILR, INFO)
INTEGER | N, LDH, LDVL, LDVR, MM, M, IFAILL(*), IFAILR(*), INFO
REAL (KIND=nag_wp) | RWORK(N)
COMPLEX (KIND=nag_wp) | H(LDH,*), W(*), VL(LDVL,*), VR(LDVR,*), WORK(N*N)
LOGICAL | SELECT(*)
CHARACTER(1) | JOB, EIGSRC, INITV
The routine may be called by its LAPACK name zhsein.

3 Description

F08PXF (ZHSEIN) computes left and/or right eigenvectors of a complex upper Hessenberg matrix H, corresponding to selected eigenvalues.
The right eigenvector x, and the left eigenvector y, corresponding to an eigenvalue λ, are defined by:
Hx = λx   and   yH H = λ yH   or HH y = λ-y .
The eigenvectors are computed by inverse iteration. They are scaled so that max⁡ Re xi + Im⁡xi = 1 .
If H has been formed by reduction of a complex general matrix A to upper Hessenberg form, then the eigenvectors of H may be transformed to eigenvectors of A by a call to F08NUF (ZUNMHR).

4 References

Golub G H and Van Loan C F (1996) Matrix Computations (3rd Edition) Johns Hopkins University Press, Baltimore

5 Arguments

1:   JOB – CHARACTER(1)Input
On entry: indicates whether left and/or right eigenvectors are to be computed.
JOB='R'
Only right eigenvectors are computed.
JOB='L'
Only left eigenvectors are computed.
JOB='B'
Both left and right eigenvectors are computed.
Constraint: JOB='R', 'L' or 'B'.
2:   EIGSRC – CHARACTER(1)Input
On entry: indicates whether the eigenvalues of H (stored in W) were found using F08PSF (ZHSEQR).
EIGSRC='Q'
The eigenvalues of H were found using F08PSF (ZHSEQR); thus if H has any zero subdiagonal elements (and so is block triangular), then the jth eigenvalue can be assumed to be an eigenvalue of the block containing the jth row/column. This property allows the routine to perform inverse iteration on just one diagonal block.
EIGSRC='N'
No such assumption is made and the routine performs inverse iteration using the whole matrix.
Constraint: EIGSRC='Q' or 'N'.
3:   INITV – CHARACTER(1)Input
On entry: indicates whether you are supplying initial estimates for the selected eigenvectors.
INITV='N'
No initial estimates are supplied.
INITV='U'
Initial estimates are supplied in VL and/or VR.
Constraint: INITV='N' or 'U'.
4:   SELECT* – LOGICAL arrayInput
Note: the dimension of the array SELECT must be at least max 1,N.
On entry: specifies which eigenvectors are to be computed. To select the eigenvector corresponding to the eigenvalue W j, SELECT j must be set to .TRUE..
5:   N – INTEGERInput
On entry: n, the order of the matrix H.
Constraint: N≥0.
6:   H LDH* – COMPLEX (KIND=nag_wp) arrayInput
Note: the second dimension of the array H must be at least max 1,N.
On entry: the n by n upper Hessenberg matrix H. If a NaN is detected in H, the routine will return with INFO=-6.
Constraint: No element of H is equal to NaN.
7:   LDH – INTEGERInput
On entry: the first dimension of the array H as declared in the (sub)program from which F08PXF (ZHSEIN) is called.
Constraint: LDH≥max 1,N.
8:   W* – COMPLEX (KIND=nag_wp) arrayInput/Output
Note: the dimension of the array W must be at least max 1,N.
On entry: the eigenvalues of the matrix H. If EIGSRC='Q', the array must be exactly as returned by F08PSF (ZHSEQR).
On exit: the real parts of some elements of W may be modified, as close eigenvalues are perturbed slightly in searching for independent eigenvectors.
9:   VL LDVL* – COMPLEX (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array VL must be at least max 1,MM if JOB='L' or 'B' and at least 1 if JOB='R'.
On entry: if INITV='U' and JOB='L' or 'B', VL must contain starting vectors for inverse iteration for the left eigenvectors. Each starting vector must be stored in the same column as will be used to store the corresponding eigenvector (see below).
If INITV='N', VL need not be set.
On exit: if JOB='L' or 'B', VL contains the computed left eigenvectors (as specified by SELECT). The eigenvectors are stored consecutively in the columns of the array, in the same order as their eigenvalues.
If JOB='R', VL is not referenced.
10:   LDVL – INTEGERInput
On entry: the first dimension of the array VL as declared in the (sub)program from which F08PXF (ZHSEIN) is called.
Constraints:
  • if JOB='L' or 'B', LDVL≥N;
  • if JOB='R', LDVL≥1.
11:   VR LDVR* – COMPLEX (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array VR must be at least max 1,MM if JOB='R' or 'B' and at least 1 if JOB='L'.
On entry: if INITV='U' and JOB='R' or 'B', VR must contain starting vectors for inverse iteration for the right eigenvectors. Each starting vector must be stored in the same column as will be used to store the corresponding eigenvector (see below).
If INITV='N', VR need not be set.
On exit: if JOB='R' or 'B', VR contains the computed right eigenvectors (as specified by SELECT). The eigenvectors are stored consecutively in the columns of the array, in the same order as their eigenvalues.
If JOB='L', VR is not referenced.
12:   LDVR – INTEGERInput
On entry: the first dimension of the array VR as declared in the (sub)program from which F08PXF (ZHSEIN) is called.
Constraints:
  • if JOB='R' or 'B', LDVR≥N;
  • if JOB='L', LDVR≥1.
13:   MM – INTEGERInput
On entry: the number of columns in the arrays VL and/or VR . The actual number of columns required, m, is obtained by counting 1 for each selected real eigenvector and 2 for each selected complex eigenvector (see SELECT); 0≤m≤n.
Constraint: MM≥m.
14:   M – INTEGEROutput
On exit: m, the number of selected eigenvectors.
15:   WORK N×N – COMPLEX (KIND=nag_wp) arrayWorkspace
16:   RWORK N – REAL (KIND=nag_wp) arrayWorkspace
17:   IFAILL* – INTEGER arrayOutput
Note: the dimension of the array IFAILL must be at least max 1,MM if JOB='L' or 'B' and at least 1 if JOB='R'.
On exit: if JOB='L' or 'B', then IFAILL i=0 if the selected left eigenvector converged and IFAILL i=j>0 if the eigenvector stored in the ith row or column of VL (corresponding to the jth eigenvalue) failed to converge.
If JOB='R', IFAILL is not referenced.
18:   IFAILR* – INTEGER arrayOutput
Note: the dimension of the array IFAILR must be at least max 1,MM if JOB='R' or 'B' and at least 1 if JOB='L'.
On exit: if JOB='R' or 'B', then IFAILR i=0 if the selected right eigenvector converged and IFAILR i=j>0 if the eigenvector stored in the ith column of VR (corresponding to the jth eigenvalue) failed to converge.
If JOB='L', IFAILR is not referenced.
19:   INFO – INTEGEROutput
On exit: INFO=0 unless the routine detects an error (see Section 6).

6 Error Indicators and Warnings

INFO<0
If INFO=-i, argument i had an illegal value. An explanatory message is output, and execution of the program is terminated.
INFO>0
If INFO=i, then i eigenvectors (as indicated by the arguments IFAILL and/or IFAILR above) failed to converge. The corresponding columns of VL and/or VR contain no useful information.

7 Accuracy

Each computed right eigenvector xi is the exact eigenvector of a nearby matrix A+Ei, such that Ei=O ε A. Hence the residual is small:
A xi - λixi = O ε A .
However, eigenvectors corresponding to close or coincident eigenvalues may not accurately span the relevant subspaces.
Similar remarks apply to computed left eigenvectors.

8 Parallelism and Performance

F08PXF (ZHSEIN) is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
F08PXF (ZHSEIN) makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The real analogue of this routine is F08PKF (DHSEIN).

10 Example

See Section 10 in F08NUF (ZUNMHR).
F08 Chapter Contents
F08 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F08QFF (DTREXC) : NAG Library, Mark 26

F08 Chapter Contents
F08 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F08QFF (DTREXC)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F08QFF (DTREXC) reorders the Schur factorization of a real general matrix.

2 Specification

SUBROUTINE F08QFF ( COMPQ, N, T, LDT, Q, LDQ, IFST, ILST, WORK, INFO)
INTEGER | N, LDT, LDQ, IFST, ILST, INFO
REAL (KIND=nag_wp) | T(LDT,*), Q(LDQ,*), WORK(N)
CHARACTER(1) | COMPQ
The routine may be called by its LAPACK name dtrexc.

3 Description

F08QFF (DTREXC) reorders the Schur factorization of a real general matrix A=QT QT, so that the diagonal element or block of T with row index IFST is moved to row ILST.
The reordered Schur form T~ is computed by an orthogonal similarity transformation: T~=ZT TZ. Optionally the updated matrix Q~ of Schur vectors is computed as Q~=QZ, giving A=Q~T~Q~T.

4 References

Golub G H and Van Loan C F (1996) Matrix Computations (3rd Edition) Johns Hopkins University Press, Baltimore

5 Arguments

1:   COMPQ – CHARACTER(1)Input
On entry: indicates whether the matrix Q of Schur vectors is to be updated.
COMPQ='V'
The matrix Q of Schur vectors is updated.
COMPQ='N'
No Schur vectors are updated.
Constraint: COMPQ='V' or 'N'.
2:   N – INTEGERInput
On entry: n, the order of the matrix T.
Constraint: N≥0.
3:   T LDT* – REAL (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array T must be at least max 1,N.
On entry: the n by n upper quasi-triangular matrix T in canonical Schur form, as returned by F08PEF (DHSEQR).
On exit: T is overwritten by the updated matrix T~. See also Section 9.
4:   LDT – INTEGERInput
On entry: the first dimension of the array T as declared in the (sub)program from which F08QFF (DTREXC) is called.
Constraint: LDT≥ max 1,N .
5:   Q LDQ* – REAL (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array Q must be at least max 1,N if COMPQ='V' and at least 1 if COMPQ='N'.
On entry: if COMPQ='V', Q must contain the n by n orthogonal matrix Q of Schur vectors.
On exit: if COMPQ='V', Q contains the updated matrix of Schur vectors.
If COMPQ='N', Q is not referenced.
6:   LDQ – INTEGERInput
On entry: the first dimension of the array Q as declared in the (sub)program from which F08QFF (DTREXC) is called.
Constraints:
  • if COMPQ='V', LDQ≥ max 1,N ;
  • if COMPQ='N', LDQ≥1.
7:   IFST – INTEGERInput/Output
8:   ILST – INTEGERInput/Output
On entry: IFST and ILST must specify the reordering of the diagonal elements or blocks of T. The element or block with row index IFST is moved to row ILST by a sequence of exchanges between adjacent elements or blocks.
On exit: if IFST pointed to the second row of a 2 by 2 block on entry, it is changed to point to the first row. ILST always points to the first row of the block in its final position (which may differ from its input value by ±1).
Constraint: 1≤IFST≤N and 1≤ILST≤N.
9:   WORK N – REAL (KIND=nag_wp) arrayWorkspace
10:   INFO – INTEGEROutput
On exit: INFO=0 unless the routine detects an error (see Section 6).

6 Error Indicators and Warnings

INFO<0
If INFO=-i, argument i had an illegal value. An explanatory message is output, and execution of the program is terminated.
INFO=1
Two adjacent diagonal elements or blocks could not be successfully exchanged. This error can only occur if the exchange involves at least one 2 by 2 block; it implies that the problem is very ill-conditioned, and that the eigenvalues of the two blocks are very close. On exit, T may have been partially reordered, and ILST points to the first row of the current position of the block being moved; Q (if requested) is updated consistently with T.

7 Accuracy

The computed matrix T~ is exactly similar to a matrix T+E, where
E 2 = O ε T 2 ,
and ε is the machine precision.
Note that if a 2 by 2 diagonal block is involved in the reordering, its off-diagonal elements are in general changed; the diagonal elements and the eigenvalues of the block are unchanged unless the block is sufficiently ill-conditioned, in which case they may be noticeably altered. It is possible for a 2 by 2 block to break into two 1 by 1 blocks, i.e., for a pair of complex eigenvalues to become purely real. The values of real eigenvalues however are never changed by the reordering.

8 Parallelism and Performance

F08QFF (DTREXC) makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The total number of floating-point operations is approximately 6 nr if COMPQ='N', and 12 nr if COMPQ='V', where r=IFST-ILST.
The input matrix T must be in canonical Schur form, as is the output matrix T~. This has the following structure.
If all the computed eigenvalues are real, T is upper triangular and its diagonal elements are the eigenvalues.
If some of the computed eigenvalues form complex conjugate pairs, then T has 2 by 2 diagonal blocks. Each diagonal block has the form
t ii t i,i+1 t i+1,i t i+1,i+1 = α β γ α
where βγ<0. The corresponding eigenvalues are α±βγ.
The complex analogue of this routine is F08QTF (ZTREXC).

10 Example

This example reorders the Schur factorization of the matrix T so that the 2 by 2 block with row index 2 is moved to row 1, where
T = 0.80 -0.11 0.01 0.03 0.00 -0.10 0.25 0.35 0.00 -0.65 -0.10 0.20 0.00 0.00 0.00 -0.10 .

10.1 Program Text

Program Text (f08qffe.f90)

10.2 Program Data

Program Data (f08qffe.d)

10.3 Program Results

Program Results (f08qffe.r)

F08 Chapter Contents
F08 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F08QGF (DTRSEN) : NAG Library, Mark 26

F08 Chapter Contents
F08 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F08QGF (DTRSEN)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F08QGF (DTRSEN) reorders the Schur factorization of a real general matrix so that a selected cluster of eigenvalues appears in the leading elements or blocks on the diagonal of the Schur form. The routine also optionally computes the reciprocal condition numbers of the cluster of eigenvalues and/or the invariant subspace.

2 Specification

SUBROUTINE F08QGF ( JOB, COMPQ, SELECT, N, T, LDT, Q, LDQ, WR, WI, M, S, SEP, WORK, LWORK, IWORK, LIWORK, INFO)
INTEGER | N, LDT, LDQ, M, LWORK, IWORK(max(1,LIWORK)), LIWORK, INFO
REAL (KIND=nag_wp) | T(LDT,*), Q(LDQ,*), WR(*), WI(*), S, SEP, WORK(max(1,LWORK))
LOGICAL | SELECT(*)
CHARACTER(1) | JOB, COMPQ
The routine may be called by its LAPACK name dtrsen.

3 Description

F08QGF (DTRSEN) reorders the Schur factorization of a real general matrix A=QT QT, so that a selected cluster of eigenvalues appears in the leading diagonal elements or blocks of the Schur form.
The reordered Schur form T~ is computed by an orthogonal similarity transformation: T~=ZT TZ. Optionally the updated matrix Q~ of Schur vectors is computed as Q~=QZ, giving A=Q~T~Q~T.
Let T~= T 11 T 12 0 T 22 , where the selected eigenvalues are precisely the eigenvalues of the leading m by m sub-matrix T 11. Let Q~ be correspondingly partitioned as Q 1 Q 2 where Q 1 consists of the first m columns of Q. Then A Q 1=Q 1T 11, and so the m columns of Q 1 form an orthonormal basis for the invariant subspace corresponding to the selected cluster of eigenvalues.
Optionally the routine also computes estimates of the reciprocal condition numbers of the average of the cluster of eigenvalues and of the invariant subspace.

4 References

Golub G H and Van Loan C F (1996) Matrix Computations (3rd Edition) Johns Hopkins University Press, Baltimore

5 Arguments

1:   JOB – CHARACTER(1)Input
On entry: indicates whether condition numbers are required for the cluster of eigenvalues and/or the invariant subspace.
JOB='N'
No condition numbers are required.
JOB='E'
Only the condition number for the cluster of eigenvalues is computed.
JOB='V'
Only the condition number for the invariant subspace is computed.
JOB='B'
Condition numbers for both the cluster of eigenvalues and the invariant subspace are computed.
Constraint: JOB='N', 'E', 'V' or 'B'.
2:   COMPQ – CHARACTER(1)Input
On entry: indicates whether the matrix Q of Schur vectors is to be updated.
COMPQ='V'
The matrix Q of Schur vectors is updated.
COMPQ='N'
No Schur vectors are updated.
Constraint: COMPQ='V' or 'N'.
3:   SELECT* – LOGICAL arrayInput
Note: the dimension of the array SELECT must be at least max 1,N.
On entry: the eigenvalues in the selected cluster. To select a real eigenvalue λj, SELECT j must be set .TRUE.. To select a complex conjugate pair of eigenvalues λj and λ j+1 (corresponding to a 2 by 2 diagonal block), SELECT j and/or SELECT j+1 must be set to .TRUE.. A complex conjugate pair of eigenvalues must be either both included in the cluster or both excluded. See also Section 9.
4:   N – INTEGERInput
On entry: n, the order of the matrix T.
Constraint: N≥0.
5:   T LDT* – REAL (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array T must be at least max 1,N.
On entry: the n by n upper quasi-triangular matrix T in canonical Schur form, as returned by F08PEF (DHSEQR). See also Section 9.
On exit: T is overwritten by the updated matrix T~.
6:   LDT – INTEGERInput
On entry: the first dimension of the array T as declared in the (sub)program from which F08QGF (DTRSEN) is called.
Constraint: LDT≥ max 1,N .
7:   Q LDQ* – REAL (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array Q must be at least max 1,N if COMPQ='V' and at least 1 if COMPQ='N'.
On entry: if COMPQ='V', Q must contain the n by n orthogonal matrix Q of Schur vectors, as returned by F08PEF (DHSEQR).
On exit: if COMPQ='V', Q contains the updated matrix of Schur vectors; the first m columns of Q form an orthonormal basis for the specified invariant subspace.
If COMPQ='N', Q is not referenced.
8:   LDQ – INTEGERInput
On entry: the first dimension of the array Q as declared in the (sub)program from which F08QGF (DTRSEN) is called.
Constraints:
  • if COMPQ='V', LDQ≥ max 1,N ;
  • if COMPQ='N', LDQ≥1.
9:   WR* – REAL (KIND=nag_wp) arrayOutput
10:   WI* – REAL (KIND=nag_wp) arrayOutput
Note: the dimension of the arrays WR and WI must be at least max 1,N.
On exit: the real and imaginary parts, respectively, of the reordered eigenvalues of T~. The eigenvalues are stored in the same order as on the diagonal of T~; see Section 9 for details. Note that if a complex eigenvalue is sufficiently ill-conditioned, then its value may differ significantly from its value before reordering.
11:   M – INTEGEROutput
On exit: m, the dimension of the specified invariant subspace. The value of m is obtained by counting 1 for each selected real eigenvalue and 2 for each selected complex conjugate pair of eigenvalues (see SELECT); 0≤m≤n.
12:   S – REAL (KIND=nag_wp)Output
On exit: if JOB='E' or 'B', S is a lower bound on the reciprocal condition number of the average of the selected cluster of eigenvalues. If M=0​ or ​N, S=1; if INFO=1 (see Section 6), S is set to zero.
If JOB='N' or 'V', S is not referenced.
13:   SEP – REAL (KIND=nag_wp)Output
On exit: if JOB='V' or 'B', SEP is the estimated reciprocal condition number of the specified invariant subspace. If M=0​ or ​N, SEP=T; if INFO=1 (see Section 6), SEP is set to zero.
If JOB='N' or 'E', SEP is not referenced.
14:   WORK max 1,LWORK – REAL (KIND=nag_wp) arrayWorkspace
On exit: if INFO=0, WORK 1 contains the minimum value of LWORK required for optimal performance.
15:   LWORK – INTEGERInput
On entry: the dimension of the array WORK as declared in the (sub)program from which F08QGF (DTRSEN) is called, unless LWORK=-1, in which case a workspace query is assumed and the routine only calculates the minimum dimension of WORK.
Constraints:
  • if JOB='N', LWORK≥max 1,N or LWORK=-1;
  • if JOB='E', LWORK≥max 1,m×N-m or LWORK=-1;
  • if JOB='V' or 'B', LWORK≥max 1,2 m×N-m or LWORK=-1.
The actual amount of workspace required cannot exceed N 2/4 if JOB='E' or N 2/2 if JOB='V' or 'B'.
16:   IWORK max 1,LIWORK – INTEGER arrayWorkspace
On exit: if INFO=0, IWORK 1 contains the required minimal size of LIWORK.
17:   LIWORK – INTEGERInput
On entry: the dimension of the array IWORK as declared in the (sub)program from which F08QGF (DTRSEN) is called, unless LIWORK=-1, in which case a workspace query is assumed and the routine only calculates the minimum dimension of IWORK.
Constraints:
  • if JOB='N' or 'E', LIWORK≥1 or LIWORK=-1;
  • if JOB='V' or 'B', LIWORK≥max 1,m×N-m or LIWORK=-1.
The actual amount of workspace required cannot exceed N 2/2 if JOB='V' or 'B'.
18:   INFO – INTEGEROutput
On exit: INFO=0 unless the routine detects an error (see Section 6).

6 Error Indicators and Warnings

INFO<0
If INFO=-i, argument i had an illegal value. An explanatory message is output, and execution of the program is terminated.
INFO=1
The reordering of T failed because a selected eigenvalue was too close to an eigenvalue which was not selected; this error exit can only occur if at least one of the eigenvalues involved was complex. The problem is too ill-conditioned: consider modifying the selection of eigenvalues so that eigenvalues which are very close together are either all included in the cluster or all excluded. On exit, T may have been partially reordered, but WR, WI and Q (if requested) are updated consistently with T; S and SEP (if requested) are both set to zero.

7 Accuracy

The computed matrix T~ is similar to a matrix T+E, where
E 2 = O ε T 2 ,
and ε is the machine precision.
S cannot underestimate the true reciprocal condition number by more than a factor of min m,n-m. SEP may differ from the true value by m n-m. The angle between the computed invariant subspace and the true subspace is O ε A 2 sep .
Note that if a 2 by 2 diagonal block is involved in the reordering, its off-diagonal elements are in general changed; the diagonal elements and the eigenvalues of the block are unchanged unless the block is sufficiently ill-conditioned, in which case they may be noticeably altered. It is possible for a 2 by 2 block to break into two 1 by 1 blocks, i.e., for a pair of complex eigenvalues to become purely real. The values of real eigenvalues however are never changed by the reordering.

8 Parallelism and Performance

F08QGF (DTRSEN) makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The input matrix T must be in canonical Schur form, as is the output matrix T~. This has the following structure.
If all the computed eigenvalues are real, T~ is upper triangular, and the diagonal elements of T~ are the eigenvalues; WR i=t~ii, for i=1,2,…,n and WI i=0.0.
If some of the computed eigenvalues form complex conjugate pairs, then T~ has 2 by 2 diagonal blocks. Each diagonal block has the form
t~ii t~i,i+1 t~i+1,i t~i+1,i+1 = α β γ α
where βγ<0. The corresponding eigenvalues are α±βγ; WR i=WR i+1=α; WI i=+βγ; WI i+1=-WI i.
The complex analogue of this routine is F08QUF (ZTRSEN).

10 Example

This example reorders the Schur factorization of the matrix A=QT QT such that the two real eigenvalues appear as the leading elements on the diagonal of the reordered matrix T~, where
T = 0.7995 -0.1144 0.0060 0.0336 0.0000 -0.0994 0.2478 0.3474 0.0000 -0.6483 -0.0994 0.2026 0.0000 0.0000 0.0000 -0.1007
and
Q = 0.6551 0.1037 0.3450 0.6641 0.5236 -0.5807 -0.6141 -0.1068 -0.5362 -0.3073 -0.2935 0.7293 0.0956 0.7467 -0.6463 0.1249 .
The example program for F08QGF (DTRSEN) illustrates the computation of error bounds for the eigenvalues.
The original matrix A is given in Section 10 in F08NFF (DORGHR).

10.1 Program Text

Program Text (f08qgfe.f90)

10.2 Program Data

Program Data (f08qgfe.d)

10.3 Program Results

Program Results (f08qgfe.r)

F08 Chapter Contents
F08 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F08QHF (DTRSYL) : NAG Library, Mark 26

F08 Chapter Contents
F08 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F08QHF (DTRSYL)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F08QHF (DTRSYL) solves the real quasi-triangular Sylvester matrix equation.

2 Specification

SUBROUTINE F08QHF ( TRANA, TRANB, ISGN, M, N, A, LDA, B, LDB, C, LDC, SCALE, INFO)
INTEGER | ISGN, M, N, LDA, LDB, LDC, INFO
REAL (KIND=nag_wp) | A(LDA,*), B(LDB,*), C(LDC,*), SCALE
CHARACTER(1) | TRANA, TRANB
The routine may be called by its LAPACK name dtrsyl.

3 Description

F08QHF (DTRSYL) solves the real Sylvester matrix equation
op A X ± X op B = αC ,
where op A = A or AT, and the matrices A and B are upper quasi-triangular matrices in canonical Schur form (as returned by F08PEF (DHSEQR)); α is a scale factor (≤1) determined by the routine to avoid overflow in X; A is m by m and B is n by n while the right-hand side matrix C and the solution matrix X are both m by n. The matrix X is obtained by a straightforward process of back-substitution (see Golub and Van Loan (1996)).
Note that the equation has a unique solution if and only if αi±βj≠0, where αi and βj are the eigenvalues of A and B respectively and the sign (+ or -) is the same as that used in the equation to be solved.

4 References

Golub G H and Van Loan C F (1996) Matrix Computations (3rd Edition) Johns Hopkins University Press, Baltimore
Higham N J (1992) Perturbation theory and backward error for AX-XB=C Numerical Analysis Report University of Manchester

5 Arguments

1:   TRANA – CHARACTER(1)Input
On entry: specifies the option op A.
TRANA='N'
op A=A.
TRANA='T' or 'C'
op A=AT.
Constraint: TRANA='N', 'T' or 'C'.
2:   TRANB – CHARACTER(1)Input
On entry: specifies the option op B.
TRANB='N'
op B=B.
TRANB='T' or 'C'
op B=BT.
Constraint: TRANB='N', 'T' or 'C'.
3:   ISGN – INTEGERInput
On entry: indicates the form of the Sylvester equation.
ISGN=+1
The equation is of the form op A X+X op B=αC.
ISGN=-1
The equation is of the form op A X-X op B=αC.
Constraint: ISGN=+1 or -1.
4:   M – INTEGERInput
On entry: m, the order of the matrix A, and the number of rows in the matrices X and C.
Constraint: M≥0.
5:   N – INTEGERInput
On entry: n, the order of the matrix B, and the number of columns in the matrices X and C.
Constraint: N≥0.
6:   A LDA* – REAL (KIND=nag_wp) arrayInput
Note: the second dimension of the array A must be at least max 1,M.
On entry: the m by m upper quasi-triangular matrix A in canonical Schur form, as returned by F08PEF (DHSEQR).
7:   LDA – INTEGERInput
On entry: the first dimension of the array A as declared in the (sub)program from which F08QHF (DTRSYL) is called.
Constraint: LDA≥max 1,M.
8:   B LDB* – REAL (KIND=nag_wp) arrayInput
Note: the second dimension of the array B must be at least max 1,N.
On entry: the n by n upper quasi-triangular matrix B in canonical Schur form, as returned by F08PEF (DHSEQR).
9:   LDB – INTEGERInput
On entry: the first dimension of the array B as declared in the (sub)program from which F08QHF (DTRSYL) is called.
Constraint: LDB≥max 1,N.
10:   C LDC* – REAL (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array C must be at least max 1,N.
On entry: the m by n right-hand side matrix C.
On exit: C is overwritten by the solution matrix X.
11:   LDC – INTEGERInput
On entry: the first dimension of the array C as declared in the (sub)program from which F08QHF (DTRSYL) is called.
Constraint: LDC≥max 1,M.
12:   SCALE – REAL (KIND=nag_wp)Output
On exit: the value of the scale factor α.
13:   INFO – INTEGEROutput
On exit: INFO=0 unless the routine detects an error (see Section 6).

6 Error Indicators and Warnings

INFO<0
If INFO=-i, argument i had an illegal value. An explanatory message is output, and execution of the program is terminated.
INFO=1
A and B have common or close eigenvalues, perturbed values of which were used to solve the equation.

7 Accuracy

Consider the equation AX-XB=C. (To apply the remarks to the equation AX+XB=C, simply replace B by -B.)
Let X~ be the computed solution and R the residual matrix:
R = C - A X~ - X~B .
Then the residual is always small:
R F = O ε A F + B F X~F .
However, X~ is not necessarily the exact solution of a slightly perturbed equation; in other words, the solution is not backwards stable.
For the forward error, the following bound holds:
X~ - X F ≤ R F sep A,B
but this may be a considerable over estimate. See Golub and Van Loan (1996) for a definition of sep A,B, and Higham (1992) for further details.
These remarks also apply to the solution of a general Sylvester equation, as described in Section 9.

8 Parallelism and Performance

F08QHF (DTRSYL) makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The total number of floating-point operations is approximately mn m+n.
To solve the general real Sylvester equation
AX ± XB = C
where A and B are general nonsymmetric matrices, A and B must first be reduced to Schur form (by calling F08PAF (DGEES), for example):
A = Q 1 A~ Q 1 T   and   B = Q 2 B~ Q 2 T
where A~ and B~ are upper quasi-triangular and Q 1 and Q 2 are orthogonal. The original equation may then be transformed to:
A~ X~ ± X~ B~ = C~
where X~ = Q 1 T X Q 2 and C~ = Q 1 T C Q 2 . C~ may be computed by matrix multiplication; F08QHF (DTRSYL) may be used to solve the transformed equation; and the solution to the original equation can be obtained as X = Q 1 X~ Q 2 T .
The complex analogue of this routine is F08QVF (ZTRSYL).

10 Example

This example solves the Sylvester equation AX+XB=C, where
A = 0.10 0.50 0.68 -0.21 -0.50 0.10 -0.24 0.67 0.00 0.00 0.19 -0.35 0.00 0.00 0.00 -0.72 ,
B = -0.99 -0.17 0.39 0.58 0.00 0.48 -0.84 -0.15 0.00 0.00 0.75 0.25 0.00 0.00 -0.25 0.75
and
C = 0.63 -0.56 0.08 -0.23 -0.45 -0.31 0.27 1.21 0.20 -0.35 0.41 0.84 0.49 -0.05 -0.52 -0.08 .

10.1 Program Text

Program Text (f08qhfe.f90)

10.2 Program Data

Program Data (f08qhfe.d)

10.3 Program Results

Program Results (f08qhfe.r)

F08 Chapter Contents
F08 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F08QKF (DTREVC) : NAG Library, Mark 26

F08 Chapter Contents
F08 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F08QKF (DTREVC)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
10 Example

1 Purpose

F08QKF (DTREVC) computes selected left and/or right eigenvectors of a real upper quasi-triangular matrix.

2 Specification

SUBROUTINE F08QKF ( JOB, HOWMNY, SELECT, N, T, LDT, VL, LDVL, VR, LDVR, MM, M, WORK, INFO)
INTEGER | N, LDT, LDVL, LDVR, MM, M, INFO
REAL (KIND=nag_wp) | T(LDT,*), VL(LDVL,*), VR(LDVR,*), WORK(3*N)
LOGICAL | SELECT(*)
CHARACTER(1) | JOB, HOWMNY
The routine may be called by its LAPACK name dtrevc.

3 Description

F08QKF (DTREVC) computes left and/or right eigenvectors of a real upper quasi-triangular matrix T in canonical Schur form. Such a matrix arises from the Schur factorization of a real general matrix, as computed by F08PEF (DHSEQR), for example.
The right eigenvector x, and the left eigenvector y, corresponding to an eigenvalue λ, are defined by:
Tx = λx   and   yH T = λ yH or ​ TT y = λ-y .
Note that even though T is real, λ, x and y may be complex. If x is an eigenvector corresponding to a complex eigenvalue λ, then the complex conjugate vector x- is the eigenvector corresponding to the complex conjugate eigenvalue λ-.
The routine can compute the eigenvectors corresponding to selected eigenvalues, or it can compute all the eigenvectors. In the latter case the eigenvectors may optionally be pre-multiplied by an input matrix Q. Normally Q is an orthogonal matrix from the Schur factorization of a matrix A as A=QT QT; if x is a (left or right) eigenvector of T, then Qx is an eigenvector of A.
The eigenvectors are computed by forward or backward substitution. They are scaled so that, for a real eigenvector x, max xi=1, and for a complex eigenvector, max Re xi + Im xi =1.

4 References

Golub G H and Van Loan C F (1996) Matrix Computations (3rd Edition) Johns Hopkins University Press, Baltimore

5 Arguments

1:   JOB – CHARACTER(1)Input
On entry: indicates whether left and/or right eigenvectors are to be computed.
JOB='R'
Only right eigenvectors are computed.
JOB='L'
Only left eigenvectors are computed.
JOB='B'
Both left and right eigenvectors are computed.
Constraint: JOB='R', 'L' or 'B'.
2:   HOWMNY – CHARACTER(1)Input
On entry: indicates how many eigenvectors are to be computed.
HOWMNY='A'
All eigenvectors (as specified by JOB) are computed.
HOWMNY='B'
All eigenvectors (as specified by JOB) are computed and then pre-multiplied by the matrix Q (which is overwritten).
HOWMNY='S'
Selected eigenvectors (as specified by JOB and SELECT) are computed.
Constraint: HOWMNY='A', 'B' or 'S'.
3:   SELECT* – LOGICAL arrayInput/Output
Note: the dimension of the array SELECT must be at least max 1,N if HOWMNY='S', and at least 1 otherwise.
On entry: specifies which eigenvectors are to be computed if HOWMNY='S'. To obtain the real eigenvector corresponding to the real eigenvalue λj, SELECT j must be set .TRUE.. To select the complex eigenvector corresponding to a complex conjugate pair of eigenvalues λj and λ j+1, SELECT j and/or SELECT j+1 must be set .TRUE.; the eigenvector corresponding to the first eigenvalue in the pair is computed.
On exit: if a complex eigenvector was selected as specified above, then SELECT j is set to .TRUE. and SELECT j+1 to .FALSE..
If HOWMNY='A' or 'B', SELECT is not referenced.
4:   N – INTEGERInput
On entry: n, the order of the matrix T.
Constraint: N≥0.
5:   T LDT* – REAL (KIND=nag_wp) arrayInput
Note: the second dimension of the array T must be at least max 1,N.
On entry: the n by n upper quasi-triangular matrix T in canonical Schur form, as returned by F08PEF (DHSEQR).
6:   LDT – INTEGERInput
On entry: the first dimension of the array T as declared in the (sub)program from which F08QKF (DTREVC) is called.
Constraint: LDT≥ max 1,N .
7:   VL LDVL* – REAL (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array VL must be at least max 1,MM if JOB='L' or 'B' and at least 1 if JOB='R'.
On entry: if HOWMNY='B' and JOB='L' or 'B', VL must contain an n by n matrix Q (usually the matrix of Schur vectors returned by F08PEF (DHSEQR)).
If HOWMNY='A' or 'S', VL need not be set.
On exit: if JOB='L' or 'B', VL contains the computed left eigenvectors (as specified by HOWMNY and SELECT). The eigenvectors are stored consecutively in the columns of the array, in the same order as their eigenvalues. Corresponding to each real eigenvalue is a real eigenvector, occupying one column. Corresponding to each complex conjugate pair of eigenvalues, is a complex eigenvector occupying two columns; the first column holds the real part and the second column holds the imaginary part.
If JOB='R', VL is not referenced.
8:   LDVL – INTEGERInput
On entry: the first dimension of the array VL as declared in the (sub)program from which F08QKF (DTREVC) is called.
Constraints:
  • if JOB='L' or 'B', LDVL≥N;
  • if JOB='R', LDVL≥1.
9:   VR LDVR* – REAL (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array VR must be at least max 1,MM if JOB='R' or 'B' and at least 1 if JOB='L'.
On entry: if HOWMNY='B' and JOB='R' or 'B', VR must contain an n by n matrix Q (usually the matrix of Schur vectors returned by F08PEF (DHSEQR)).
If HOWMNY='A' or 'S', VR need not be set.
On exit: if JOB='R' or 'B', VR contains the computed right eigenvectors (as specified by HOWMNY and SELECT). The eigenvectors are stored consecutively in the columns of the array, in the same order as their eigenvalues. Corresponding to each real eigenvalue is a real eigenvector, occupying one column. Corresponding to each complex conjugate pair of eigenvalues, is a complex eigenvector occupying two columns; the first column holds the real part and the second column holds the imaginary part.
If JOB='L', VR is not referenced.
10:   LDVR – INTEGERInput
On entry: the first dimension of the array VR as declared in the (sub)program from which F08QKF (DTREVC) is called.
Constraints:
  • if JOB='R' or 'B', LDVR≥N;
  • if JOB='L', LDVR≥1.
11:   MM – INTEGERInput
On entry: the number of columns in the arrays VL and/or VR. The precise number of columns required, m, is n if HOWMNY='A' or 'B'; if HOWMNY='S', m is obtained by counting 1 for each selected real eigenvector and 2 for each selected complex eigenvector (see SELECT), in which case 0≤m≤n.
Constraints:
  • if HOWMNY='A' or 'B', MM≥N;
  • otherwise MM≥m.
12:   M – INTEGEROutput
On exit: m, the number of columns of VL and/or VR actually used to store the computed eigenvectors. If HOWMNY='A' or 'B', M is set to n.
13:   WORK 3×N – REAL (KIND=nag_wp) arrayWorkspace
14:   INFO – INTEGEROutput
On exit: INFO=0 unless the routine detects an error (see Section 6).

6 Error Indicators and Warnings

INFO<0
If INFO=-i, argument i had an illegal value. An explanatory message is output, and execution of the program is terminated.
INFO=-11
On entry, MM=value and N=value.
Constraint: if HOWMNY≠'S', MM≥N
else MM≥m, where m is obtained by counting 1 for each selected real eigenvector and 2 for each selected complex eigenvector.

7 Accuracy

If xi is an exact right eigenvector, and x~i is the corresponding computed eigenvector, then the angle θ x~i,xi between them is bounded as follows:
θ x~i,xi ≤ c n ε T 2 sepi
where sepi is the reciprocal condition number of xi.
The condition number sepi may be computed by calling F08QLF (DTRSNA).

8 Parallelism and Performance

F08QKF (DTREVC) makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

For a description of canonical Schur form, see the document for F08PEF (DHSEQR).
The complex analogue of this routine is F08QXF (ZTREVC).

10 Example

See Section 10 in F08NHF (DGEBAL).
F08 Chapter Contents
F08 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F08QLF (DTRSNA) : NAG Library, Mark 26

F08 Chapter Contents
F08 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F08QLF (DTRSNA)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F08QLF (DTRSNA) estimates condition numbers for specified eigenvalues and/or right eigenvectors of a real upper quasi-triangular matrix.

2 Specification

SUBROUTINE F08QLF ( JOB, HOWMNY, SELECT, N, T, LDT, VL, LDVL, VR, LDVR, S, SEP, MM, M, WORK, LDWORK, IWORK, INFO)
INTEGER | N, LDT, LDVL, LDVR, MM, M, LDWORK, IWORK(*), INFO
REAL (KIND=nag_wp) | T(LDT,*), VL(LDVL,*), VR(LDVR,*), S(*), SEP(*), WORK(LDWORK,*)
LOGICAL | SELECT(*)
CHARACTER(1) | JOB, HOWMNY
The routine may be called by its LAPACK name dtrsna.

3 Description

F08QLF (DTRSNA) estimates condition numbers for specified eigenvalues and/or right eigenvectors of a real upper quasi-triangular matrix T in canonical Schur form. These are the same as the condition numbers of the eigenvalues and right eigenvectors of an original matrix A=ZT ZT (with orthogonal Z), from which T may have been derived.
F08QLF (DTRSNA) computes the reciprocal of the condition number of an eigenvalue λi as
si = vH u u Ev E ,
where u and v are the right and left eigenvectors of T, respectively, corresponding to λi. This reciprocal condition number always lies between zero (i.e., ill-conditioned) and one (i.e., well-conditioned).
An approximate error estimate for a computed eigenvalue λi is then given by
ε T si ,
where ε is the machine precision.
To estimate the reciprocal of the condition number of the right eigenvector corresponding to λi, the routine first calls F08QFF (DTREXC) to reorder the eigenvalues so that λi is in the leading position:
T =Q λi cT 0 T 22 QT.
The reciprocal condition number of the eigenvector is then estimated as sepi, the smallest singular value of the matrix T 22-λi I. This number ranges from zero (i.e., ill-conditioned) to very large (i.e., well-conditioned).
An approximate error estimate for a computed right eigenvector u corresponding to λi is then given by
ε T sepi .

4 References

Golub G H and Van Loan C F (1996) Matrix Computations (3rd Edition) Johns Hopkins University Press, Baltimore

5 Arguments

1:   JOB – CHARACTER(1)Input
On entry: indicates whether condition numbers are required for eigenvalues and/or eigenvectors.
JOB='E'
Condition numbers for eigenvalues only are computed.
JOB='V'
Condition numbers for eigenvectors only are computed.
JOB='B'
Condition numbers for both eigenvalues and eigenvectors are computed.
Constraint: JOB='E', 'V' or 'B'.
2:   HOWMNY – CHARACTER(1)Input
On entry: indicates how many condition numbers are to be computed.
HOWMNY='A'
Condition numbers for all eigenpairs are computed.
HOWMNY='S'
Condition numbers for selected eigenpairs (as specified by SELECT) are computed.
Constraint: HOWMNY='A' or 'S'.
3:   SELECT* – LOGICAL arrayInput
Note: the dimension of the array SELECT must be at least max 1,N if HOWMNY='S', and at least 1 otherwise.
On entry: specifies the eigenpairs for which condition numbers are to be computed if HOWMNY='S'. To select condition numbers for the eigenpair corresponding to the real eigenvalue λj, SELECT j must be set .TRUE.. To select condition numbers corresponding to a complex conjugate pair of eigenvalues λj and λ j+1, SELECT j and/or SELECT j+1 must be set to .TRUE..
If HOWMNY='A', SELECT is not referenced.
4:   N – INTEGERInput
On entry: n, the order of the matrix T.
Constraint: N≥0.
5:   T LDT* – REAL (KIND=nag_wp) arrayInput
Note: the second dimension of the array T must be at least max 1,N.
On entry: the n by n upper quasi-triangular matrix T in canonical Schur form, as returned by F08PEF (DHSEQR).
6:   LDT – INTEGERInput
On entry: the first dimension of the array T as declared in the (sub)program from which F08QLF (DTRSNA) is called.
Constraint: LDT≥ max 1,N .
7:   VL LDVL* – REAL (KIND=nag_wp) arrayInput
Note: the second dimension of the array VL must be at least max 1,MM if JOB='E' or 'B' and at least 1 if JOB='V'.
On entry: if JOB='E' or 'B', VL must contain the left eigenvectors of T (or of any matrix QT QT with Q orthogonal) corresponding to the eigenpairs specified by HOWMNY and SELECT. The eigenvectors must be stored in consecutive columns of VL, as returned by F08PKF (DHSEIN) or F08QKF (DTREVC).
If JOB='V', VL is not referenced.
8:   LDVL – INTEGERInput
On entry: the first dimension of the array VL as declared in the (sub)program from which F08QLF (DTRSNA) is called.
Constraints:
  • if JOB='E' or 'B', LDVL≥ max 1,N ;
  • if JOB='V', LDVL≥1.
9:   VR LDVR* – REAL (KIND=nag_wp) arrayInput
Note: the second dimension of the array VR must be at least max 1,MM if JOB='E' or 'B' and at least 1 if JOB='V'.
On entry: if JOB='E' or 'B', VR must contain the right eigenvectors of T (or of any matrix QT QT with Q orthogonal) corresponding to the eigenpairs specified by HOWMNY and SELECT. The eigenvectors must be stored in consecutive columns of VR, as returned by F08PKF (DHSEIN) or F08QKF (DTREVC).
If JOB='V', VR is not referenced.
10:   LDVR – INTEGERInput
On entry: the first dimension of the array VR as declared in the (sub)program from which F08QLF (DTRSNA) is called.
Constraints:
  • if JOB='E' or 'B', LDVR≥ max 1,N ;
  • if JOB='V', LDVR≥1.
11:   S* – REAL (KIND=nag_wp) arrayOutput
Note: the dimension of the array S must be at least max 1,MM if JOB='E' or 'B', and at least 1 otherwise.
On exit: the reciprocal condition numbers of the selected eigenvalues if JOB='E' or 'B', stored in consecutive elements of the array. Thus S j, SEP j and the jth columns of VL and VR all correspond to the same eigenpair (but not in general the jth eigenpair unless all eigenpairs have been selected). For a complex conjugate pair of eigenvalues, two consecutive elements of S are set to the same value.
If JOB='V', S is not referenced.
12:   SEP* – REAL (KIND=nag_wp) arrayOutput
Note: the dimension of the array SEP must be at least max 1,MM if JOB='V' or 'B', and at least 1 otherwise.
On exit: the estimated reciprocal condition numbers of the selected right eigenvectors if JOB='V' or 'B', stored in consecutive elements of the array. For a complex eigenvector, two consecutive elements of SEP are set to the same value. If the eigenvalues cannot be reordered to compute SEP j, then SEP j is set to zero; this can only occur when the true value would be very small anyway.
If JOB='E', SEP is not referenced.
13:   MM – INTEGERInput
On entry: the number of elements in the arrays S and SEP, and the number of columns in the arrays VL and VR (if used). The precise number required, m, is n if HOWMNY='A'; if HOWMNY='S', m is obtained by counting 1 for each selected real eigenvalue, and 2 for each selected complex conjugate pair of eigenvalues (see SELECT), in which case 0≤m≤n.
Constraint: MM≥M.
14:   M – INTEGEROutput
On exit: m, the number of elements of S and/or SEP actually used to store the estimated condition numbers. If HOWMNY='A', M is set to n.
15:   WORK LDWORK* – REAL (KIND=nag_wp) arrayWorkspace
Note: the second dimension of the array WORK must be at least max 1,N+6 if JOB='V' or 'B' and at least 1 if JOB='E'.
If JOB='E', WORK is not referenced.
16:   LDWORK – INTEGERInput
On entry: the first dimension of the array WORK as declared in the (sub)program from which F08QLF (DTRSNA) is called.
Constraints:
  • if JOB='V' or 'B', LDWORK≥ max 1,N ;
  • if JOB='E', LDWORK≥1.
17:   IWORK* – INTEGER arrayWorkspace
Note: the dimension of the array IWORK must be at least max 1,2×N-1.
18:   INFO – INTEGEROutput
On exit: INFO=0 unless the routine detects an error (see Section 6).

6 Error Indicators and Warnings

INFO<0
If INFO=-i, argument i had an illegal value. An explanatory message is output, and execution of the program is terminated.

7 Accuracy

The computed values sepi may over estimate the true value, but seldom by a factor of more than 3.

8 Parallelism and Performance

F08QLF (DTRSNA) makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

For a description of canonical Schur form, see the document for F08PEF (DHSEQR).
The complex analogue of this routine is F08QYF (ZTRSNA).

10 Example

This example computes approximate error estimates for all the eigenvalues and right eigenvectors of the matrix T, where
T = 0.7995 -0.1144 0.0060 0.0336 0.0000 -0.0994 0.2478 0.3474 0.0000 -0.6483 -0.0994 0.2026 0.0000 0.0000 0.0000 -0.1007 .

10.1 Program Text

Program Text (f08qlfe.f90)

10.2 Program Data

Program Data (f08qlfe.d)

10.3 Program Results

Program Results (f08qlfe.r)

F08 Chapter Contents
F08 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F08QTF (ZTREXC) : NAG Library, Mark 26

F08 Chapter Contents
F08 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F08QTF (ZTREXC)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F08QTF (ZTREXC) reorders the Schur factorization of a complex general matrix.

2 Specification

SUBROUTINE F08QTF ( COMPQ, N, T, LDT, Q, LDQ, IFST, ILST, INFO)
INTEGER | N, LDT, LDQ, IFST, ILST, INFO
COMPLEX (KIND=nag_wp) | T(LDT,*), Q(LDQ,*)
CHARACTER(1) | COMPQ
The routine may be called by its LAPACK name ztrexc.

3 Description

F08QTF (ZTREXC) reorders the Schur factorization of a complex general matrix A=QT QH, so that the diagonal element of T with row index IFST is moved to row ILST.
The reordered Schur form T~ is computed by a unitary similarity transformation: T~=ZH TZ. Optionally the updated matrix Q~ of Schur vectors is computed as Q~=QZ, giving A=Q~T~Q~H.

4 References

Golub G H and Van Loan C F (1996) Matrix Computations (3rd Edition) Johns Hopkins University Press, Baltimore

5 Arguments

1:   COMPQ – CHARACTER(1)Input
On entry: indicates whether the matrix Q of Schur vectors is to be updated.
COMPQ='V'
The matrix Q of Schur vectors is updated.
COMPQ='N'
No Schur vectors are updated.
Constraint: COMPQ='V' or 'N'.
2:   N – INTEGERInput
On entry: n, the order of the matrix T.
Constraint: N≥0.
3:   T LDT* – COMPLEX (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array T must be at least max 1,N.
On entry: the n by n upper triangular matrix T, as returned by F08PSF (ZHSEQR).
On exit: T is overwritten by the updated matrix T~.
4:   LDT – INTEGERInput
On entry: the first dimension of the array T as declared in the (sub)program from which F08QTF (ZTREXC) is called.
Constraint: LDT≥ max 1,N .
5:   Q LDQ* – COMPLEX (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array Q must be at least max 1,N if COMPQ='V' and at least 1 if COMPQ='N'.
On entry: if COMPQ='V', Q must contain the n by n unitary matrix Q of Schur vectors.
On exit: if COMPQ='V', Q contains the updated matrix of Schur vectors.
If COMPQ='N', Q is not referenced.
6:   LDQ – INTEGERInput
On entry: the first dimension of the array Q as declared in the (sub)program from which F08QTF (ZTREXC) is called.
Constraints:
  • if COMPQ='V', LDQ≥ max 1,N ;
  • if COMPQ='N', LDQ≥1.
7:   IFST – INTEGERInput
8:   ILST – INTEGERInput
On entry: IFST and ILST must specify the reordering of the diagonal elements of T. The element with row index IFST is moved to row ILST by a sequence of exchanges between adjacent elements.
Constraint: 1≤IFST≤N and 1≤ILST≤N.
9:   INFO – INTEGEROutput
On exit: INFO=0 unless the routine detects an error (see Section 6).

6 Error Indicators and Warnings

INFO<0
If INFO=-i, argument i had an illegal value. An explanatory message is output, and execution of the program is terminated.

7 Accuracy

The computed matrix T~ is exactly similar to a matrix T+E, where
E 2 = O ε T 2 ,
and ε is the machine precision.
The values of the eigenvalues are never changed by the reordering.

8 Parallelism and Performance

F08QTF (ZTREXC) makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The total number of real floating-point operations is approximately 20 nr if COMPQ='N', and 40 nr if COMPQ='V', where r=IFST-ILST.
The real analogue of this routine is F08QFF (DTREXC).

10 Example

This example reorders the Schur factorization of the matrix T so that element t 11 is moved to t 44, where
T = -6.00-7.00 i 0.36-0.36 i -0.19+0.48 i 0.88-0.25 i 0.00+0.00 i -5.00+2.00 i -0.03-0.72 i -0.23+0.13 i 0.00+0.00 i 0.00+0.00 i 8.00-1.00 i 0.94+0.53 i 0.00+0.00 i 0.00+0.00 i 0.00+0.00 i 3.00-4.00 i .

10.1 Program Text

Program Text (f08qtfe.f90)

10.2 Program Data

Program Data (f08qtfe.d)

10.3 Program Results

Program Results (f08qtfe.r)

F08 Chapter Contents
F08 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F08QUF (ZTRSEN) : NAG Library, Mark 26

F08 Chapter Contents
F08 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F08QUF (ZTRSEN)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F08QUF (ZTRSEN) reorders the Schur factorization of a complex general matrix so that a selected cluster of eigenvalues appears in the leading elements on the diagonal of the Schur form. The routine also optionally computes the reciprocal condition numbers of the cluster of eigenvalues and/or the invariant subspace.

2 Specification

SUBROUTINE F08QUF ( JOB, COMPQ, SELECT, N, T, LDT, Q, LDQ, W, M, S, SEP, WORK, LWORK, INFO)
INTEGER | N, LDT, LDQ, M, LWORK, INFO
REAL (KIND=nag_wp) | S, SEP
COMPLEX (KIND=nag_wp) | T(LDT,*), Q(LDQ,*), W(*), WORK(max(1,LWORK))
LOGICAL | SELECT(*)
CHARACTER(1) | JOB, COMPQ
The routine may be called by its LAPACK name ztrsen.

3 Description

F08QUF (ZTRSEN) reorders the Schur factorization of a complex general matrix A=QT QH, so that a selected cluster of eigenvalues appears in the leading diagonal elements of the Schur form.
The reordered Schur form T~ is computed by a unitary similarity transformation: T~=ZH TZ. Optionally the updated matrix Q~ of Schur vectors is computed as Q~=QZ, giving A=Q~T~Q~H.
Let T~= T 11 T 12 0 T 22 , where the selected eigenvalues are precisely the eigenvalues of the leading m by m sub-matrix T 11. Let Q~ be correspondingly partitioned as Q 1 Q 2 where Q 1 consists of the first m columns of Q. Then A Q 1=Q 1T 11, and so the m columns of Q 1 form an orthonormal basis for the invariant subspace corresponding to the selected cluster of eigenvalues.
Optionally the routine also computes estimates of the reciprocal condition numbers of the average of the cluster of eigenvalues and of the invariant subspace.

4 References

Golub G H and Van Loan C F (1996) Matrix Computations (3rd Edition) Johns Hopkins University Press, Baltimore

5 Arguments

1:   JOB – CHARACTER(1)Input
On entry: indicates whether condition numbers are required for the cluster of eigenvalues and/or the invariant subspace.
JOB='N'
No condition numbers are required.
JOB='E'
Only the condition number for the cluster of eigenvalues is computed.
JOB='V'
Only the condition number for the invariant subspace is computed.
JOB='B'
Condition numbers for both the cluster of eigenvalues and the invariant subspace are computed.
Constraint: JOB='N', 'E', 'V' or 'B'.
2:   COMPQ – CHARACTER(1)Input
On entry: indicates whether the matrix Q of Schur vectors is to be updated.
COMPQ='V'
The matrix Q of Schur vectors is updated.
COMPQ='N'
No Schur vectors are updated.
Constraint: COMPQ='V' or 'N'.
3:   SELECT* – LOGICAL arrayInput
Note: the dimension of the array SELECT must be at least max 1,N.
On entry: specifies the eigenvalues in the selected cluster. To select a complex eigenvalue λj, SELECT j must be set .TRUE..
4:   N – INTEGERInput
On entry: n, the order of the matrix T.
Constraint: N≥0.
5:   T LDT* – COMPLEX (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array T must be at least max 1,N.
On entry: the n by n upper triangular matrix T, as returned by F08PSF (ZHSEQR).
On exit: T is overwritten by the updated matrix T~.
6:   LDT – INTEGERInput
On entry: the first dimension of the array T as declared in the (sub)program from which F08QUF (ZTRSEN) is called.
Constraint: LDT≥ max 1,N .
7:   Q LDQ* – COMPLEX (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array Q must be at least max 1,N if COMPQ='V' and at least 1 if COMPQ='N'.
On entry: if COMPQ='V', Q must contain the n by n unitary matrix Q of Schur vectors, as returned by F08PSF (ZHSEQR).
On exit: if COMPQ='V', Q contains the updated matrix of Schur vectors; the first m columns of Q form an orthonormal basis for the specified invariant subspace.
If COMPQ='N', Q is not referenced.
8:   LDQ – INTEGERInput
On entry: the first dimension of the array Q as declared in the (sub)program from which F08QUF (ZTRSEN) is called.
Constraints:
  • if COMPQ='V', LDQ≥ max 1,N ;
  • if COMPQ='N', LDQ≥1.
9:   W* – COMPLEX (KIND=nag_wp) arrayOutput
Note: the dimension of the array W must be at least max 1,N.
On exit: the reordered eigenvalues of T~. The eigenvalues are stored in the same order as on the diagonal of T~.
10:   M – INTEGEROutput
On exit: m, the dimension of the specified invariant subspace, which is the same as the number of selected eigenvalues (see SELECT); 0≤m≤n.
11:   S – REAL (KIND=nag_wp)Output
On exit: if JOB='E' or 'B', S is a lower bound on the reciprocal condition number of the average of the selected cluster of eigenvalues. If M=0​ or ​N, S=1.
If JOB='N' or 'V', S is not referenced.
12:   SEP – REAL (KIND=nag_wp)Output
On exit: if JOB='V' or 'B', SEP is the estimated reciprocal condition number of the specified invariant subspace. If M=0​ or ​N, SEP=T.
If JOB='N' or 'E', SEP is not referenced.
13:   WORK max 1,LWORK – COMPLEX (KIND=nag_wp) arrayWorkspace
On exit: if INFO=0, the real part of WORK 1 contains the minimum value of LWORK required for optimal performance.
14:   LWORK – INTEGERInput
On entry: the dimension of the array WORK as declared in the (sub)program from which F08QUF (ZTRSEN) is called, unless LWORK=-1, in which case a workspace query is assumed and the routine only calculates the minimum dimension of WORK.
Constraints:
  • if JOB='N', LWORK≥1 or LWORK=-1;
  • if JOB='E', LWORK≥max 1,m×N-m or LWORK=-1;
  • if JOB='V' or 'B', LWORK≥max 1,2 m×N-m or LWORK=-1.
The actual amount of workspace required cannot exceed N 2/4 if JOB='E' or N 2/2 if JOB='V' or 'B'.
15:   INFO – INTEGEROutput
On exit: INFO=0 unless the routine detects an error (see Section 6).

6 Error Indicators and Warnings

INFO<0
If INFO=-i, argument i had an illegal value. An explanatory message is output, and execution of the program is terminated.

7 Accuracy

The computed matrix T~ is similar to a matrix T+E, where
E 2 = O ε T 2 ,
and ε is the machine precision.
S cannot underestimate the true reciprocal condition number by more than a factor of min m,n-m. SEP may differ from the true value by m n-m. The angle between the computed invariant subspace and the true subspace is O ε A 2 sep .
The values of the eigenvalues are never changed by the reordering.

8 Parallelism and Performance

F08QUF (ZTRSEN) makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The real analogue of this routine is F08QGF (DTRSEN).

10 Example

This example reorders the Schur factorization of the matrix A=QT QH such that the eigenvalues stored in elements t 11 and t 44 appear as the leading elements on the diagonal of the reordered matrix T~, where
T = -6.0004-6.9999 i 0.3637-0.3656 i -0.1880+0.4787 i 0.8785-0.2539 i 0.0000+0.0000 i -5.0000+2.0060 i -0.0307-0.7217 i -0.2290+0.1313 i 0.0000+0.0000 i 0.0000+0.0000 i 7.9982-0.9964 i 0.9357+0.5359 i 0.0000+0.0000 i 0.0000+0.0000 i 0.0000+0.0000 i 3.0023-3.9998 i
and
Q = -0.8347-0.1364 i -0.0628+0.3806 i 0.2765-0.0846 i 0.0633-0.2199 i 0.0664-0.2968 i 0.2365+0.5240 i -0.5877-0.4208 i 0.0835+0.2183 i -0.0362-0.3215 i 0.3143-0.5473 i 0.0576-0.5736 i 0.0057-0.4058 i 0.0086+0.2958 i -0.3416-0.0757 i -0.1900-0.1600 i 0.8327-0.1868 i .
The original matrix A is given in Section 10 in F08NTF (ZUNGHR).

10.1 Program Text

Program Text (f08qufe.f90)

10.2 Program Data

Program Data (f08qufe.d)

10.3 Program Results

Program Results (f08qufe.r)

F08 Chapter Contents
F08 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F08QVF (ZTRSYL) : NAG Library, Mark 26

F08 Chapter Contents
F08 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F08QVF (ZTRSYL)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F08QVF (ZTRSYL) solves the complex triangular Sylvester matrix equation.

2 Specification

SUBROUTINE F08QVF ( TRANA, TRANB, ISGN, M, N, A, LDA, B, LDB, C, LDC, SCAL, INFO)
INTEGER | ISGN, M, N, LDA, LDB, LDC, INFO
REAL (KIND=nag_wp) | SCAL
COMPLEX (KIND=nag_wp) | A(LDA,*), B(LDB,*), C(LDC,*)
CHARACTER(1) | TRANA, TRANB
The routine may be called by its LAPACK name ztrsyl.

3 Description

F08QVF (ZTRSYL) solves the complex Sylvester matrix equation
op A X ± X op B = αC ,
where op A = A or AH, and the matrices A and B are upper triangular; α is a scale factor (≤1) determined by the routine to avoid overflow in X; A is m by m and B is n by n while the right-hand side matrix C and the solution matrix X are both m by n. The matrix X is obtained by a straightforward process of back-substitution (see Golub and Van Loan (1996)).
Note that the equation has a unique solution if and only if αi±βj≠0, where αi and βj are the eigenvalues of A and B respectively and the sign (+ or -) is the same as that used in the equation to be solved.

4 References

Golub G H and Van Loan C F (1996) Matrix Computations (3rd Edition) Johns Hopkins University Press, Baltimore
Higham N J (1992) Perturbation theory and backward error for AX-XB=C Numerical Analysis Report University of Manchester

5 Arguments

1:   TRANA – CHARACTER(1)Input
On entry: specifies the option op A.
TRANA='N'
op A=A.
TRANA='C'
op A=AH.
Constraint: TRANA='N' or 'C'.
2:   TRANB – CHARACTER(1)Input
On entry: specifies the option op B.
TRANB='N'
op B=B.
TRANB='C'
op B=BH.
Constraint: TRANB='N' or 'C'.
3:   ISGN – INTEGERInput
On entry: indicates the form of the Sylvester equation.
ISGN=+1
The equation is of the form op A X+X op B=αC.
ISGN=-1
The equation is of the form op A X-X op B=αC.
Constraint: ISGN=+1 or -1.
4:   M – INTEGERInput
On entry: m, the order of the matrix A, and the number of rows in the matrices X and C.
Constraint: M≥0.
5:   N – INTEGERInput
On entry: n, the order of the matrix B, and the number of columns in the matrices X and C.
Constraint: N≥0.
6:   A LDA* – COMPLEX (KIND=nag_wp) arrayInput
Note: the second dimension of the array A must be at least max 1,M.
On entry: the m by m upper triangular matrix A.
7:   LDA – INTEGERInput
On entry: the first dimension of the array A as declared in the (sub)program from which F08QVF (ZTRSYL) is called.
Constraint: LDA≥max 1,M.
8:   B LDB* – COMPLEX (KIND=nag_wp) arrayInput
Note: the second dimension of the array B must be at least max 1,N.
On entry: the n by n upper triangular matrix B.
9:   LDB – INTEGERInput
On entry: the first dimension of the array B as declared in the (sub)program from which F08QVF (ZTRSYL) is called.
Constraint: LDB≥max 1,N.
10:   C LDC* – COMPLEX (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array C must be at least max 1,N.
On entry: the m by n right-hand side matrix C.
On exit: C is overwritten by the solution matrix X.
11:   LDC – INTEGERInput
On entry: the first dimension of the array C as declared in the (sub)program from which F08QVF (ZTRSYL) is called.
Constraint: LDC≥max 1,M.
12:   SCAL – REAL (KIND=nag_wp)Output
On exit: the value of the scale factor α.
13:   INFO – INTEGEROutput
On exit: INFO=0 unless the routine detects an error (see Section 6).

6 Error Indicators and Warnings

INFO<0
If INFO=-i, argument i had an illegal value. An explanatory message is output, and execution of the program is terminated.
INFO=1
A and B have common or close eigenvalues, perturbed values of which were used to solve the equation.

7 Accuracy

Consider the equation AX-XB=C. (To apply the remarks to the equation AX+XB=C, simply replace B by -B.)
Let X~ be the computed solution and R the residual matrix:
R = C - A X~ - X~B .
Then the residual is always small:
R F = O ε A F + B F X~F .
However, X~ is not necessarily the exact solution of a slightly perturbed equation; in other words, the solution is not backwards stable.
For the forward error, the following bound holds:
X~ - X F ≤ R F sep A,B
but this may be a considerable over estimate. See Golub and Van Loan (1996) for a definition of sep A,B, and Higham (1992) for further details.
These remarks also apply to the solution of a general Sylvester equation, as described in Section 9.

8 Parallelism and Performance

F08QVF (ZTRSYL) makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The total number of real floating-point operations is approximately 4 mn m+n.
To solve the general complex Sylvester equation
AX ± XB = C
where A and B are general matrices, A and B must first be reduced to Schur form (by calling F08PNF (ZGEES), for example):
A = Q 1 A~ Q 1 H   and   B = Q 2 B~ Q 2 H
where A~ and B~ are upper triangular and Q 1 and Q 2 are unitary. The original equation may then be transformed to:
A~ X~ ± X~ B~ = C~
where X~ = Q 1 H X Q 2 and C~ = Q 1 H C Q 2 . C~ may be computed by matrix multiplication; F08QVF (ZTRSYL) may be used to solve the transformed equation; and the solution to the original equation can be obtained as X = Q 1 X~ Q 2 H .
The real analogue of this routine is F08QHF (DTRSYL).

10 Example

This example solves the Sylvester equation AX+XB=C, where
A = -6.00-7.00 i 0.36-0.36 i -0.19+0.48 i 0.88-0.25 i 0.00+0.00 i -5.00+2.00 i -0.03-0.72 i -0.23+0.13 i 0.00+0.00 i 0.00+0.00 i 8.00-1.00 i 0.94+0.53 i 0.00+0.00 i 0.00+0.00 i 0.00+0.00 i 3.00-4.00 i ,
B = 0.50-0.20 i -0.29-0.16 i -0.37+0.84 i -0.55+0.73 i 0.00+0.00 i -0.40+0.90 i 0.06+0.22 i -0.43+0.17 i 0.00+0.00 i 0.00+0.00 i -0.90-0.10 i -0.89-0.42 i 0.00+0.00 i 0.00+0.00 i 0.00+0.00 i 0.30-0.70 i
and
C = 0.63+0.35 i 0.45-0.56 i 0.08-0.14 i -0.17-0.23 i -0.17+0.09 i -0.07-0.31 i 0.27-0.54 i 0.35+1.21 i -0.93-0.44 i -0.33-0.35 i 0.41-0.03 i 0.57+0.84 i 0.54+0.25 i -0.62-0.05 i -0.52-0.13 i 0.11-0.08 i .

10.1 Program Text

Program Text (f08qvfe.f90)

10.2 Program Data

Program Data (f08qvfe.d)

10.3 Program Results

Program Results (f08qvfe.r)

F08 Chapter Contents
F08 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F08QXF (ZTREVC) : NAG Library, Mark 26

F08 Chapter Contents
F08 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F08QXF (ZTREVC)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
10 Example

1 Purpose

F08QXF (ZTREVC) computes selected left and/or right eigenvectors of a complex upper triangular matrix.

2 Specification

SUBROUTINE F08QXF ( JOB, HOWMNY, SELECT, N, T, LDT, VL, LDVL, VR, LDVR, MM, M, WORK, RWORK, INFO)
INTEGER | N, LDT, LDVL, LDVR, MM, M, INFO
REAL (KIND=nag_wp) | RWORK(N)
COMPLEX (KIND=nag_wp) | T(LDT,*), VL(LDVL,*), VR(LDVR,*), WORK(2*N)
LOGICAL | SELECT(*)
CHARACTER(1) | JOB, HOWMNY
The routine may be called by its LAPACK name ztrevc.

3 Description

F08QXF (ZTREVC) computes left and/or right eigenvectors of a complex upper triangular matrix T. Such a matrix arises from the Schur factorization of a complex general matrix, as computed by F08PSF (ZHSEQR), for example.
The right eigenvector x, and the left eigenvector y, corresponding to an eigenvalue λ, are defined by:
Tx = λx   and   yH T = λ yH or ​ TH y = λ-y .
The routine can compute the eigenvectors corresponding to selected eigenvalues, or it can compute all the eigenvectors. In the latter case the eigenvectors may optionally be pre-multiplied by an input matrix Q. Normally Q is a unitary matrix from the Schur factorization of a matrix A as A=QT QH; if x is a (left or right) eigenvector of T, then Qx is an eigenvector of A.
The eigenvectors are computed by forward or backward substitution. They are scaled so that max⁡ Re xi + Im⁡xi =1.

4 References

Golub G H and Van Loan C F (1996) Matrix Computations (3rd Edition) Johns Hopkins University Press, Baltimore

5 Arguments

1:   JOB – CHARACTER(1)Input
On entry: indicates whether left and/or right eigenvectors are to be computed.
JOB='R'
Only right eigenvectors are computed.
JOB='L'
Only left eigenvectors are computed.
JOB='B'
Both left and right eigenvectors are computed.
Constraint: JOB='R', 'L' or 'B'.
2:   HOWMNY – CHARACTER(1)Input
On entry: indicates how many eigenvectors are to be computed.
HOWMNY='A'
All eigenvectors (as specified by JOB) are computed.
HOWMNY='B'
All eigenvectors (as specified by JOB) are computed and then pre-multiplied by the matrix Q (which is overwritten).
HOWMNY='S'
Selected eigenvectors (as specified by JOB and SELECT) are computed.
Constraint: HOWMNY='A', 'B' or 'S'.
3:   SELECT* – LOGICAL arrayInput
Note: the dimension of the array SELECT must be at least N if HOWMNY='S', and at least 1 otherwise.
On entry: specifies which eigenvectors are to be computed if HOWMNY='S'. To obtain the eigenvector corresponding to the eigenvalue λj, SELECT j must be set .TRUE..
If HOWMNY='A' or 'B', SELECT is not referenced.
4:   N – INTEGERInput
On entry: n, the order of the matrix T.
Constraint: N≥0.
5:   T LDT* – COMPLEX (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array T must be at least N.
On entry: the n by n upper triangular matrix T, as returned by F08PSF (ZHSEQR).
On exit: is used as internal workspace prior to being restored and hence is unchanged.
6:   LDT – INTEGERInput
On entry: the first dimension of the array T as declared in the (sub)program from which F08QXF (ZTREVC) is called.
Constraint: LDT≥ max 1,N .
7:   VL LDVL* – COMPLEX (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array VL must be at least MM if JOB='L' or 'B' and at least 1 if JOB='R'.
On entry: if HOWMNY='B' and JOB='L' or 'B', VL must contain an n by n matrix Q (usually the matrix of Schur vectors returned by F08PSF (ZHSEQR)).
If HOWMNY='A' or 'S', VL need not be set.
On exit: if JOB='L' or 'B', VL contains the computed left eigenvectors (as specified by HOWMNY and SELECT). The eigenvectors are stored consecutively in the columns of the array, in the same order as their eigenvalues.
If JOB='R', VL is not referenced.
8:   LDVL – INTEGERInput
On entry: the first dimension of the array VL as declared in the (sub)program from which F08QXF (ZTREVC) is called.
Constraints:
  • if JOB='L' or 'B', LDVL≥N;
  • if JOB='R', LDVL≥1.
9:   VR LDVR* – COMPLEX (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array VR must be at least MM if JOB='R' or 'B' and at least 1 if JOB='L'.
On entry: if HOWMNY='B' and JOB='R' or 'B', VR must contain an n by n matrix Q (usually the matrix of Schur vectors returned by F08PSF (ZHSEQR)).
If HOWMNY='A' or 'S', VR need not be set.
On exit: if JOB='R' or 'B', VR contains the computed right eigenvectors (as specified by HOWMNY and SELECT). The eigenvectors are stored consecutively in the columns of the array, in the same order as their eigenvalues.
If JOB='L', VR is not referenced.
10:   LDVR – INTEGERInput
On entry: the first dimension of the array VR as declared in the (sub)program from which F08QXF (ZTREVC) is called.
Constraints:
  • if JOB='R' or 'B', LDVR≥N;
  • if JOB='L', LDVR≥1.
11:   MM – INTEGERInput
On entry: the number of columns in the arrays VL and/or VR. The precise number of columns required, m, is n if HOWMNY='A' or 'B'; if HOWMNY='S', m is the number of selected eigenvectors (see SELECT), in which case 0≤m≤n.
Constraints:
  • if HOWMNY='A' or 'B', MM≥N;
  • otherwise MM≥m.
12:   M – INTEGEROutput
On exit: m, the number of selected eigenvectors. If HOWMNY='A' or 'B', M is set to n.
13:   WORK 2×N – COMPLEX (KIND=nag_wp) arrayWorkspace
14:   RWORK N – REAL (KIND=nag_wp) arrayWorkspace
15:   INFO – INTEGEROutput
On exit: INFO=0 unless the routine detects an error (see Section 6).

6 Error Indicators and Warnings

INFO<0
If INFO=-i, argument i had an illegal value. An explanatory message is output, and execution of the program is terminated.

7 Accuracy

If xi is an exact right eigenvector, and x~i is the corresponding computed eigenvector, then the angle θ x~i,xi between them is bounded as follows:
θ x~i,xi ≤ c n ε T 2 sepi
where sepi is the reciprocal condition number of xi.
The condition number sepi may be computed by calling F08QYF (ZTRSNA).

8 Parallelism and Performance

F08QXF (ZTREVC) makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The real analogue of this routine is F08QKF (DTREVC).

10 Example

See Section 10 in F08NVF (ZGEBAL).
F08 Chapter Contents
F08 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F08QYF (ZTRSNA) : NAG Library, Mark 26

F08 Chapter Contents
F08 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F08QYF (ZTRSNA)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F08QYF (ZTRSNA) estimates condition numbers for specified eigenvalues and/or right eigenvectors of a complex upper triangular matrix.

2 Specification

SUBROUTINE F08QYF ( JOB, HOWMNY, SELECT, N, T, LDT, VL, LDVL, VR, LDVR, S, SEP, MM, M, WORK, LDWORK, RWORK, INFO)
INTEGER | N, LDT, LDVL, LDVR, MM, M, LDWORK, INFO
REAL (KIND=nag_wp) | S(*), SEP(*), RWORK(*)
COMPLEX (KIND=nag_wp) | T(LDT,*), VL(LDVL,*), VR(LDVR,*), WORK(LDWORK,*)
LOGICAL | SELECT(*)
CHARACTER(1) | JOB, HOWMNY
The routine may be called by its LAPACK name ztrsna.

3 Description

F08QYF (ZTRSNA) estimates condition numbers for specified eigenvalues and/or right eigenvectors of a complex upper triangular matrix T. These are the same as the condition numbers of the eigenvalues and right eigenvectors of an original matrix A=ZT ZH (with unitary Z), from which T may have been derived.
F08QYF (ZTRSNA) computes the reciprocal of the condition number of an eigenvalue λi as
si = vH u u Ev E ,
where u and v are the right and left eigenvectors of T, respectively, corresponding to λi. This reciprocal condition number always lies between zero (i.e., ill-conditioned) and one (i.e., well-conditioned).
An approximate error estimate for a computed eigenvalue λi is then given by
ε T si ,
where ε is the machine precision.
To estimate the reciprocal of the condition number of the right eigenvector corresponding to λi, the routine first calls F08QTF (ZTREXC) to reorder the eigenvalues so that λi is in the leading position:
T =Q λi cH 0 T 22 QH.
The reciprocal condition number of the eigenvector is then estimated as sepi, the smallest singular value of the matrix T 22-λi I. This number ranges from zero (i.e., ill-conditioned) to very large (i.e., well-conditioned).
An approximate error estimate for a computed right eigenvector u corresponding to λi is then given by
ε T sepi .

4 References

Golub G H and Van Loan C F (1996) Matrix Computations (3rd Edition) Johns Hopkins University Press, Baltimore

5 Arguments

1:   JOB – CHARACTER(1)Input
On entry: indicates whether condition numbers are required for eigenvalues and/or eigenvectors.
JOB='E'
Condition numbers for eigenvalues only are computed.
JOB='V'
Condition numbers for eigenvectors only are computed.
JOB='B'
Condition numbers for both eigenvalues and eigenvectors are computed.
Constraint: JOB='E', 'V' or 'B'.
2:   HOWMNY – CHARACTER(1)Input
On entry: indicates how many condition numbers are to be computed.
HOWMNY='A'
Condition numbers for all eigenpairs are computed.
HOWMNY='S'
Condition numbers for selected eigenpairs (as specified by SELECT) are computed.
Constraint: HOWMNY='A' or 'S'.
3:   SELECT* – LOGICAL arrayInput
Note: the dimension of the array SELECT must be at least max 1,N if HOWMNY='S', and at least 1 otherwise.
On entry: specifies the eigenpairs for which condition numbers are to be computed if HOWMNY='S'. To select condition numbers for the eigenpair corresponding to the eigenvalue λj, SELECT j must be set to .TRUE..
If HOWMNY='A', SELECT is not referenced.
4:   N – INTEGERInput
On entry: n, the order of the matrix T.
Constraint: N≥0.
5:   T LDT* – COMPLEX (KIND=nag_wp) arrayInput
Note: the second dimension of the array T must be at least max 1,N.
On entry: the n by n upper triangular matrix T, as returned by F08PSF (ZHSEQR).
6:   LDT – INTEGERInput
On entry: the first dimension of the array T as declared in the (sub)program from which F08QYF (ZTRSNA) is called.
Constraint: LDT≥ max 1,N .
7:   VL LDVL* – COMPLEX (KIND=nag_wp) arrayInput
Note: the second dimension of the array VL must be at least max 1,MM if JOB='E' or 'B' and at least 1 if JOB='V'.
On entry: if JOB='E' or 'B', VL must contain the left eigenvectors of T (or of any matrix QT QH with Q unitary) corresponding to the eigenpairs specified by HOWMNY and SELECT. The eigenvectors must be stored in consecutive columns of VL, as returned by F08PXF (ZHSEIN) or F08QXF (ZTREVC).
If JOB='V', VL is not referenced.
8:   LDVL – INTEGERInput
On entry: the first dimension of the array VL as declared in the (sub)program from which F08QYF (ZTRSNA) is called.
Constraints:
  • if JOB='E' or 'B', LDVL≥ max 1,N ;
  • if JOB='V', LDVL≥1.
9:   VR LDVR* – COMPLEX (KIND=nag_wp) arrayInput
Note: the second dimension of the array VR must be at least max 1,MM if JOB='E' or 'B' and at least 1 if JOB='V'.
On entry: if JOB='E' or 'B', VR must contain the right eigenvectors of T (or of any matrix QT QH with Q unitary) corresponding to the eigenpairs specified by HOWMNY and SELECT. The eigenvectors must be stored in consecutive columns of VR, as returned by F08PXF (ZHSEIN) or F08QXF (ZTREVC).
If JOB='V', VR is not referenced.
10:   LDVR – INTEGERInput
On entry: the first dimension of the array VR as declared in the (sub)program from which F08QYF (ZTRSNA) is called.
Constraints:
  • if JOB='E' or 'B', LDVR≥ max 1,N ;
  • if JOB='V', LDVR≥1.
11:   S* – REAL (KIND=nag_wp) arrayOutput
Note: the dimension of the array S must be at least max 1,MM if JOB='E' or 'B', and at least 1 otherwise.
On exit: the reciprocal condition numbers of the selected eigenvalues if JOB='E' or 'B', stored in consecutive elements of the array. Thus S j, SEP j and the jth columns of VL and VR all correspond to the same eigenpair (but not in general the jth eigenpair unless all eigenpairs have been selected).
If JOB='V', S is not referenced.
12:   SEP* – REAL (KIND=nag_wp) arrayOutput
Note: the dimension of the array SEP must be at least max 1,MM if JOB='V' or 'B', and at least 1 otherwise.
On exit: the estimated reciprocal condition numbers of the selected right eigenvectors if JOB='V' or 'B', stored in consecutive elements of the array.
If JOB='E', SEP is not referenced.
13:   MM – INTEGERInput
On entry: the number of elements in the arrays S and SEP, and the number of columns in the arrays VL and VR (if used). The precise number required, m, is n if HOWMNY='A'; if HOWMNY='S', m is the number of selected eigenpairs (see SELECT), in which case 0≤m≤n.
Constraints:
  • if HOWMNY='A', MM≥N;
  • otherwise MM≥m.
14:   M – INTEGEROutput
On exit: m, the number of selected eigenpairs. If HOWMNY='A', M is set to n.
15:   WORK LDWORK* – COMPLEX (KIND=nag_wp) arrayWorkspace
Note: the second dimension of the array WORK must be at least max 1,N+1 if JOB='V' or 'B' and at least 1 if JOB='E'.
If JOB='E', WORK is not referenced.
16:   LDWORK – INTEGERInput
On entry: the first dimension of the array WORK as declared in the (sub)program from which F08QYF (ZTRSNA) is called.
Constraints:
  • if JOB='V' or 'B', LDWORK≥ max 1,N ;
  • if JOB='E', LDWORK≥1.
17:   RWORK* – REAL (KIND=nag_wp) arrayWorkspace
Note: the dimension of the array RWORK must be at least max 1,N.
18:   INFO – INTEGEROutput
On exit: INFO=0 unless the routine detects an error (see Section 6).

6 Error Indicators and Warnings

INFO<0
If INFO=-i, argument i had an illegal value. An explanatory message is output, and execution of the program is terminated.

7 Accuracy

The computed values sepi may over estimate the true value, but seldom by a factor of more than 3.

8 Parallelism and Performance

F08QYF (ZTRSNA) makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The real analogue of this routine is F08QLF (DTRSNA).

10 Example

This example computes approximate error estimates for all the eigenvalues and right eigenvectors of the matrix T, where
T = -6.0004-6.9999 i 0.3637-0.3656 i -0.1880+0.4787 i 0.8785-0.2539 i 0.0000+0.0000 i -5.0000+2.0060 i -0.0307-0.7217 i -0.2290+0.1313 i 0.0000+0.0000 i 0.0000+0.0000 i 7.9982-0.9964 i 0.9357+0.5359 i 0.0000+0.0000 i 0.0000+0.0000 i 0.0000+0.0000 i 3.0023-3.9998 i .

10.1 Program Text

Program Text (f08qyfe.f90)

10.2 Program Data

Program Data (f08qyfe.d)

10.3 Program Results

Program Results (f08qyfe.r)

F08 Chapter Contents
F08 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F08RAF (DORCSD) : NAG Library, Mark 26

F08 Chapter Contents
F08 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F08RAF (DORCSD)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F08RAF (DORCSD) computes the CS decomposition of a real m by m orthogonal matrix X, partitioned into a 2 by 2 array of submatrices.

2 Specification

SUBROUTINE F08RAF ( JOBU1, JOBU2, JOBV1T, JOBV2T, TRANS, SIGNS, M, P, Q, X11, LDX11, X12, LDX12, X21, LDX21, X22, LDX22, THETA, U1, LDU1, U2, LDU2, V1T, LDV1T, V2T, LDV2T, WORK, LWORK, IWORK, INFO)
INTEGER | M, P, Q, LDX11, LDX12, LDX21, LDX22, LDU1, LDU2, LDV1T, LDV2T, LWORK, IWORK(M-min(P,M-P,Q,M-Q)), INFO
REAL (KIND=nag_wp) | X11(LDX11,*), X12(LDX12,*), X21(LDX21,*), X22(LDX22,*), THETA(min(P,M-P,Q,M-Q)), U1(LDU1,*), U2(LDU2,*), V1T(LDV1T,*), V2T(LDV2T,*), WORK(max(1,LWORK))
CHARACTER(1) | JOBU1, JOBU2, JOBV1T, JOBV2T, TRANS, SIGNS
The routine may be called by its LAPACK name dorcsd.

3 Description

The m by m orthogonal matrix X is partitioned as
X= X 11 X 12 X 21 X 22
where X 11 is a p by q submatrix and the dimensions of the other submatrices X 12, X 21 and X 22 are such that X remains m by m.
The CS decomposition of X is X= U Σp VT where U, V and Σp are m by m matrices, such that
U= U 1 0 0 U 2
is an orthogonal matrix containing the p by p orthogonal matrix U 1 and the m-p by m-p orthogonal matrix U 2;
V= V 1 0 0 V 2
is an orthogonal matrix containing the q by q orthogonal matrix V 1 and the m-q by m-q orthogonal matrix V 2; and
Σp= I 11 0 0 0 C 0 0 -S 0 0 0 -I12 0 0 I 22 0 0 S C 0 0 I 21 0 0
contains the r by r non-negative diagonal submatrices C and S satisfying C 2+S 2=I, where r=min p,m-p,q,m-q and the top left partition is p by q.
The identity matrix I 11 is of order min p,q-r and vanishes if min p,q=r.
The identity matrix I 12 is of order min p,m-q-r and vanishes if min p,m-q=r.
The identity matrix I 21 is of order min m-p,q-r and vanishes if min m-p,q=r.
The identity matrix I 22 is of order min m-p,m-q-r and vanishes if min m-p,m-q=r.
In each of the four cases r=p,q,m-p,m-q at least two of the identity matrices vanish.
The indicated zeros represent augmentations by additional rows or columns (but not both) to the square diagonal matrices formed by I ij and C or S.
Σp does not need to be stored in full; it is sufficient to return only the values θi for i=1,2,…,r where C ii=cos θi and S ii=sin θi.
The algorithm used to perform the complete CS decomposition is described fully in Sutton (2009) including discussions of the stability and accuracy of the algorithm.

4 References

Anderson E, Bai Z, Bischof C, Blackford S, Demmel J, Dongarra J J, Du Croz J J, Greenbaum A, Hammarling S, McKenney A and Sorensen D (1999) LAPACK Users' Guide (3rd Edition) SIAM, Philadelphia http://www.netlib.org/lapack/lug
Golub G H and Van Loan C F (2012) Matrix Computations (4th Edition) Johns Hopkins University Press, Baltimore
Sutton B D (2009) Computing the complete CS decomposition Numerical Algorithms (Volume 50) 1017–1398 Springer US 33–65 http://dx.doi.org/10.1007/s11075-008-9215-6

5 Arguments

1:   JOBU1 – CHARACTER(1)Input
On entry:
  • if JOBU1='Y', U 1 is computed;
  • otherwise, U 1 is not computed.
2:   JOBU2 – CHARACTER(1)Input
On entry:
  • if JOBU2='Y', U 2 is computed;
  • otherwise, U 2 is not computed.
3:   JOBV1T – CHARACTER(1)Input
On entry:
  • if JOBV1T='Y', V 1 T is computed;
  • otherwise, V 1 T is not computed.
4:   JOBV2T – CHARACTER(1)Input
On entry:
  • if JOBV2T='Y', V 2 T is computed;
  • otherwise, V 2 T is not computed.
5:   TRANS – CHARACTER(1)Input
On entry:
  • if TRANS='T', X, U 1, U 2, V 1 T and V 2 T are stored in row-major order;
  • otherwise, X, U 1, U 2, V 1 T and V 2 T are stored in column-major order.
6:   SIGNS – CHARACTER(1)Input
On entry:
  • if SIGNS='O', the lower-left block is made nonpositive (the other convention);
  • otherwise, the upper-right block is made nonpositive (the default convention).
7:   M – INTEGERInput
On entry: m, the number of rows and columns in the orthogonal matrix X.
Constraint: M≥0.
8:   P – INTEGERInput
On entry: p, the number of rows in X 11 and X 12.
Constraint: 0≤P≤M.
9:   Q – INTEGERInput
On entry: q, the number of columns in X 11 and X 21.
Constraint: 0≤Q≤M.
10:   X11 LDX11* – REAL (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array X11 must be at least max 1,P if TRANS='T', and at least Q otherwise.
On entry: the upper left partition of the orthogonal matrix X whose CSD is desired.
On exit: contains details of the orthogonal matrix used in a simultaneous bidiagonalization process.
11:   LDX11 – INTEGERInput
On entry: the first dimension of the array X11 as declared in the (sub)program from which F08RAF (DORCSD) is called.
Constraints:
  • if TRANS='T', LDX11≥max 1,Q;
  • otherwise LDX11≥max 1,P.
12:   X12 LDX12* – REAL (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array X12 must be at least max 1,P if TRANS='T', and at least M-Q otherwise.
On entry: the upper right partition of the orthogonal matrix X whose CSD is desired.
On exit: contains details of the orthogonal matrix used in a simultaneous bidiagonalization process.
13:   LDX12 – INTEGERInput
On entry: the first dimension of the array X12 as declared in the (sub)program from which F08RAF (DORCSD) is called.
Constraints:
  • if TRANS='T', LDX12≥max 1,M-Q;
  • otherwise LDX12≥max 1,P.
14:   X21 LDX21* – REAL (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array X21 must be at least max 1,M-P if TRANS='T', and at least Q otherwise.
On entry: the lower left partition of the orthogonal matrix X whose CSD is desired.
On exit: contains details of the orthogonal matrix used in a simultaneous bidiagonalization process.
15:   LDX21 – INTEGERInput
On entry: the first dimension of the array X21 as declared in the (sub)program from which F08RAF (DORCSD) is called.
Constraints:
  • if TRANS='T', LDX21≥max 1,Q;
  • otherwise LDX21≥max 1,M-P.
16:   X22 LDX22* – REAL (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array X22 must be at least max 1,M-P if TRANS='T', and at least M-Q otherwise.
On entry: the lower right partition of the orthogonal matrix X CSD is desired.
On exit: contains details of the orthogonal matrix used in a simultaneous bidiagonalization process.
17:   LDX22 – INTEGERInput
On entry: the first dimension of the array X22 as declared in the (sub)program from which F08RAF (DORCSD) is called.
Constraints:
  • if TRANS='T', LDX22≥max 1,M-Q;
  • otherwise LDX22≥max 1,M-P.
18:   THETA min P,M-P,Q,M-Q – REAL (KIND=nag_wp) arrayOutput
On exit: the values θi for i=1,2,…,r where r=min p,m-p,q,m-q. The diagonal submatrices C and S of Σp are constructed from these values as
  • C= diag cos THETA 1 ,…,cos THETA r and
  • S= diag sin THETA 1 ,…,sin THETA r .
19:   U1 LDU1* – REAL (KIND=nag_wp) arrayOutput
Note: the second dimension of the array U1 must be at least max 1,P if JOBU1='Y', and at least 1 otherwise.
On exit: if JOBU1='Y', U1 contains the p by p orthogonal matrix U 1.
20:   LDU1 – INTEGERInput
On entry: the first dimension of the array U1 as declared in the (sub)program from which F08RAF (DORCSD) is called.
Constraint: if JOBU1='Y', LDU1≥max 1,P.
21:   U2 LDU2* – REAL (KIND=nag_wp) arrayOutput
Note: the second dimension of the array U2 must be at least max 1,M-P if JOBU2='Y', and at least 1 otherwise.
On exit: if JOBU2='Y', U2 contains the m-p by m-p orthogonal matrix U 2.
22:   LDU2 – INTEGERInput
On entry: the first dimension of the array U2 as declared in the (sub)program from which F08RAF (DORCSD) is called.
Constraint: if JOBU2='Y', LDU2≥max 1,M-P.
23:   V1T LDV1T* – REAL (KIND=nag_wp) arrayOutput
Note: the second dimension of the array V1T must be at least max 1,Q if JOBV1T='Y', and at least 1 otherwise.
On exit: if JOBV1T='Y', V1T contains the q by q orthogonal matrix V 1 T.
24:   LDV1T – INTEGERInput
On entry: the first dimension of the array V1T as declared in the (sub)program from which F08RAF (DORCSD) is called.
Constraint: if JOBV1T='Y', LDV1T≥max 1,Q.
25:   V2T LDV2T* – REAL (KIND=nag_wp) arrayOutput
Note: the second dimension of the array V2T must be at least max 1,M-Q if JOBV2T='Y', and at least 1 otherwise.
On exit: if JOBV2T='Y', V2T contains the m-q by m-q orthogonal matrix V 2 T.
26:   LDV2T – INTEGERInput
On entry: the first dimension of the array V2T as declared in the (sub)program from which F08RAF (DORCSD) is called.
Constraint: if JOBV2T='Y', LDV2T≥max 1,M-Q.
27:   WORK max 1,LWORK – REAL (KIND=nag_wp) arrayWorkspace
On exit: if INFO=0, WORK 1 returns the optimal LWORK.
If INFO>0 on exit, WORK 2:r contains the values PHI 1,…PHI r-1 that, together with xref arg 1,…xref arg r, define the matrix in intermediate bidiagonal-block form remaining after nonconvergence. INFO specifies the number of nonzero PHI's.
28:   LWORK – INTEGERInput
On entry:
If LWORK=-1, a workspace query is assumed; the routine only calculates the optimal size of the WORK array, returns this value as the first entry of the WORK array, and no error message related to LWORK is issued.
The minimum workspace required is 5×max 1,r-1 + 4×max 1,r + max 1,8 r + max 1,p + max 1,m-p + max 1,q + max 1,m-q + 1 where r=min p,m-p,q,m-q. The optimal workspace depends on internal block sizes and the relative dimensions of the problem.
Constraint: LWORK=-1 or
LWORK≥ 5×max 1,r-1 + 4×max 1,r + max 1,8⁢r + max 1,P + max 1,M-P + max 1,Q + max 1,M-Q + 1 .
29:   IWORK M-min P,M-P,Q,M-Q – INTEGER arrayWorkspace
30:   INFO – INTEGEROutput
On exit: INFO=0 unless the routine detects an error (see Section 6).

6 Error Indicators and Warnings

INFO<0
If INFO=-i, argument i had an illegal value. An explanatory message is output, and execution of the program is terminated.
INFO>0
The Jacobi-type procedure failed to converge during an internal reduction to bidiagonal-block form. The process requires convergence to min P,M-P,Q,M-Q values, the value of INFO gives the number of converged values.

7 Accuracy

The computed CS decomposition is nearly the exact CS decomposition for the nearby matrix X+E , where
E 2 = O ε ,
and ε is the machine precision.

8 Parallelism and Performance

F08RAF (DORCSD) is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
F08RAF (DORCSD) makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The total number of floating-point operations required to perform the full CS decomposition is approximately 2 m 3.
The complex analogue of this routine is F08RNF (ZUNCSD).

10 Example

This example finds the full CS decomposition of
X = -0.7576 0.3697 0.3838 0.2126 -0.3112 -0.4077 -0.1552 -0.1129 0.2676 0.8517 -0.0488 0.7240 -0.6730 -0.1301 0.0602 -0.2287 0.0088 0.2235 -0.9235 0.2120 0.4530 0.5612 0.5806 0.1162 0.3595
partitioned so that the top left block is 3 by 2.
The decomposition is performed both on submatrices of the orthogonal matrix X and on separated partition matrices. Code is also provided to perform a recombining check if required.

10.1 Program Text

Program Text (f08rafe.f90)

10.2 Program Data

Program Data (f08rafe.d)

10.3 Program Results

Program Results (f08rafe.r)

F08 Chapter Contents
F08 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F08RNF (ZUNCSD) : NAG Library, Mark 26

F08 Chapter Contents
F08 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F08RNF (ZUNCSD)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F08RNF (ZUNCSD) computes the CS decomposition of a complex m by m unitary matrix X, partitioned into a 2 by 2 array of submatrices.

2 Specification

SUBROUTINE F08RNF ( JOBU1, JOBU2, JOBV1T, JOBV2T, TRANS, SIGNS, M, P, Q, X11, LDX11, X12, LDX12, X21, LDX21, X22, LDX22, THETA, U1, LDU1, U2, LDU2, V1T, LDV1T, V2T, LDV2T, WORK, LWORK, RWORK, LRWORK, IWORK, INFO)
INTEGER | M, P, Q, LDX11, LDX12, LDX21, LDX22, LDU1, LDU2, LDV1T, LDV2T, LWORK, LRWORK, IWORK(M-min(P,M-P,Q,M-Q)), INFO
REAL (KIND=nag_wp) | THETA(min(P,M-P,Q,M-Q)), RWORK(max(1,LRWORK))
COMPLEX (KIND=nag_wp) | X11(LDX11,*), X12(LDX12,*), X21(LDX21,*), X22(LDX22,*), U1(LDU1,*), U2(LDU2,*), V1T(LDV1T,*), V2T(LDV2T,*), WORK(max(1,LWORK))
CHARACTER(1) | JOBU1, JOBU2, JOBV1T, JOBV2T, TRANS, SIGNS
The routine may be called by its LAPACK name zuncsd.

3 Description

The m by m unitary matrix X is partitioned as
X= X 11 X 12 X 21 X 22
where X 11 is a p by q submatrix and the dimensions of the other submatrices X 12, X 21 and X 22 are such that X remains m by m.
The CS decomposition of X is X= U Σp VT where U, V and Σp are m by m matrices, such that
U= U 1 0 0 U 2
is a unitary matrix containing the p by p unitary matrix U 1 and the m-p by m-p unitary matrix U 2;
V= V 1 0 0 V 2
is a unitary matrix containing the q by q unitary matrix V 1 and the m-q by m-q unitary matrix V 2; and
Σp= I 11 0 0 0 C 0 0 -S 0 0 0 -I12 0 0 I 22 0 0 S C 0 0 I 21 0 0
contains the r by r non-negative diagonal submatrices C and S satisfying C 2+S 2=I, where r=min p,m-p,q,m-q and the top left partition is p by q.
The identity matrix I 11 is of order min p,q-r and vanishes if min p,q=r.
The identity matrix I 12 is of order min p,m-q-r and vanishes if min p,m-q=r.
The identity matrix I 21 is of order min m-p,q-r and vanishes if min m-p,q=r.
The identity matrix I 22 is of order min m-p,m-q-r and vanishes if min m-p,m-q=r.
In each of the four cases r=p,q,m-p,m-q at least two of the identity matrices vanish.
The indicated zeros represent augmentations by additional rows or columns (but not both) to the square diagonal matrices formed by I ij and C or S.
Σp does not need to be stored in full; it is sufficient to return only the values θi for i=1,2,…,r where C ii=cos θi and S ii=sin θi.
The algorithm used to perform the complete CS decomposition is described fully in Sutton (2009) including discussions of the stability and accuracy of the algorithm.

4 References

Anderson E, Bai Z, Bischof C, Blackford S, Demmel J, Dongarra J J, Du Croz J J, Greenbaum A, Hammarling S, McKenney A and Sorensen D (1999) LAPACK Users' Guide (3rd Edition) SIAM, Philadelphia http://www.netlib.org/lapack/lug
Golub G H and Van Loan C F (2012) Matrix Computations (4th Edition) Johns Hopkins University Press, Baltimore
Sutton B D (2009) Computing the complete CS decomposition Numerical Algorithms (Volume 50) 1017–1398 Springer US 33–65 http://dx.doi.org/10.1007/s11075-008-9215-6

5 Arguments

1:   JOBU1 – CHARACTER(1)Input
On entry:
  • if JOBU1='Y', U 1 is computed;
  • otherwise, U 1 is not computed.
2:   JOBU2 – CHARACTER(1)Input
On entry:
  • if JOBU2='Y', U 2 is computed;
  • otherwise, U 2 is not computed.
3:   JOBV1T – CHARACTER(1)Input
On entry:
  • if JOBV1T='Y', V 1 T is computed;
  • otherwise, V 1 T is not computed.
4:   JOBV2T – CHARACTER(1)Input
On entry:
  • if JOBV2T='Y', V 2 T is computed;
  • otherwise, V 2 T is not computed.
5:   TRANS – CHARACTER(1)Input
On entry:
  • if TRANS='T', X, U 1, U 2, V 1 T and V 2 T are stored in row-major order;
  • otherwise, X, U 1, U 2, V 1 T and V 2 T are stored in column-major order.
6:   SIGNS – CHARACTER(1)Input
On entry:
  • if SIGNS='O', the lower-left block is made nonpositive (the other convention);
  • otherwise, the upper-right block is made nonpositive (the default convention).
7:   M – INTEGERInput
On entry: m, the number of rows and columns in the unitary matrix X.
Constraint: M≥0.
8:   P – INTEGERInput
On entry: p, the number of rows in X 11 and X 12.
Constraint: 0≤P≤M.
9:   Q – INTEGERInput
On entry: q, the number of columns in X 11 and X 21.
Constraint: 0≤Q≤M.
10:   X11 LDX11* – COMPLEX (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array X11 must be at least max 1,P if TRANS='T', and at least Q otherwise.
On entry: the upper left partition of the unitary matrix X whose CSD is desired.
On exit: contains details of the unitary matrix used in a simultaneous bidiagonalization process.
11:   LDX11 – INTEGERInput
On entry: the first dimension of the array X11 as declared in the (sub)program from which F08RNF (ZUNCSD) is called.
Constraints:
  • if TRANS='T', LDX11≥max 1,Q;
  • otherwise LDX11≥max 1,P.
12:   X12 LDX12* – COMPLEX (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array X12 must be at least max 1,P if TRANS='T', and at least M-Q otherwise.
On entry: the upper right partition of the unitary matrix X whose CSD is desired.
On exit: contains details of the unitary matrix used in a simultaneous bidiagonalization process.
13:   LDX12 – INTEGERInput
On entry: the first dimension of the array X12 as declared in the (sub)program from which F08RNF (ZUNCSD) is called.
Constraints:
  • if TRANS='T', LDX12≥max 1,M-Q;
  • otherwise LDX12≥max 1,P.
14:   X21 LDX21* – COMPLEX (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array X21 must be at least max 1,M-P if TRANS='T', and at least Q otherwise.
On entry: the lower left partition of the unitary matrix X whose CSD is desired.
On exit: contains details of the unitary matrix used in a simultaneous bidiagonalization process.
15:   LDX21 – INTEGERInput
On entry: the first dimension of the array X21 as declared in the (sub)program from which F08RNF (ZUNCSD) is called.
Constraints:
  • if TRANS='T', LDX21≥max 1,Q;
  • otherwise LDX21≥max 1,M-P.
16:   X22 LDX22* – COMPLEX (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array X22 must be at least max 1,M-P if TRANS='T', and at least M-Q otherwise.
On entry: the lower right partition of the unitary matrix X CSD is desired.
On exit: contains details of the unitary matrix used in a simultaneous bidiagonalization process.
17:   LDX22 – INTEGERInput
On entry: the first dimension of the array X22 as declared in the (sub)program from which F08RNF (ZUNCSD) is called.
Constraints:
  • if TRANS='T', LDX22≥max 1,M-Q;
  • otherwise LDX22≥max 1,M-P.
18:   THETA min P,M-P,Q,M-Q – REAL (KIND=nag_wp) arrayOutput
On exit: the values θi for i=1,2,…,r where r=min p,m-p,q,m-q. The diagonal submatrices C and S of Σp are constructed from these values as
  • C= diag cos THETA 1 ,…,cos THETA r and
  • S= diag sin THETA 1 ,…,sin THETA r .
19:   U1 LDU1* – COMPLEX (KIND=nag_wp) arrayOutput
Note: the second dimension of the array U1 must be at least max 1,P if JOBU1='Y', and at least 1 otherwise.
On exit: if JOBU1='Y', U1 contains the p by p unitary matrix U 1.
20:   LDU1 – INTEGERInput
On entry: the first dimension of the array U1 as declared in the (sub)program from which F08RNF (ZUNCSD) is called.
Constraint: if JOBU1='Y', LDU1≥max 1,P.
21:   U2 LDU2* – COMPLEX (KIND=nag_wp) arrayOutput
Note: the second dimension of the array U2 must be at least max 1,M-P if JOBU2='Y', and at least 1 otherwise.
On exit: if JOBU2='Y', U2 contains the m-p by m-p unitary matrix U 2.
22:   LDU2 – INTEGERInput
On entry: the first dimension of the array U2 as declared in the (sub)program from which F08RNF (ZUNCSD) is called.
Constraint: if JOBU2='Y', LDU2≥max 1,M-P.
23:   V1T LDV1T* – COMPLEX (KIND=nag_wp) arrayOutput
Note: the second dimension of the array V1T must be at least max 1,Q if JOBV1T='Y', and at least 1 otherwise.
On exit: if JOBV1T='Y', V1T contains the q by q unitary matrix V 1 H.
24:   LDV1T – INTEGERInput
On entry: the first dimension of the array V1T as declared in the (sub)program from which F08RNF (ZUNCSD) is called.
Constraint: if JOBV1T='Y', LDV1T≥max 1,Q.
25:   V2T LDV2T* – COMPLEX (KIND=nag_wp) arrayOutput
Note: the second dimension of the array V2T must be at least max 1,M-Q if JOBV2T='Y', and at least 1 otherwise.
On exit: if JOBV2T='Y', V2T contains the m-q by m-q unitary matrix V 2 H.
26:   LDV2T – INTEGERInput
On entry: the first dimension of the array V2T as declared in the (sub)program from which F08RNF (ZUNCSD) is called.
Constraint: if JOBV2T='Y', LDV2T≥max 1,M-Q.
27:   WORK max 1,LWORK – COMPLEX (KIND=nag_wp) arrayWorkspace
On exit: if INFO=0, WORK 1 returns the optimal LWORK.
If INFO>0 on exit, WORK 2:r contains the values PHI 1,…PHI r-1 that, together with xref arg 1,…xref arg r, define the matrix in intermediate bidiagonal-block form remaining after nonconvergence. INFO specifies the number of nonzero PHI's.
28:   LWORK – INTEGERInput
On entry:
If LWORK=-1, a workspace query is assumed; the routine only calculates the optimal size of the WORK array, returns this value as the first entry of the WORK array, and no error message related to LWORK is issued.
The minimum workspace required is max 1,P + max 1,M-P + max 1,Q + max 1,M-Q + max 1,P,M-P,Q,M-Q + 1 ; the optimal amount of workspace depends on internal block sizes and the relative problem dimensions.
Constraint:
LWORK=-1 or LWORK ≥ max 1,P + max 1,M-P + max 1,Q + max 1,M-Q + max 1,P,M-P,Q,M-Q + 1 .
29:   RWORK max 1,LRWORK – REAL (KIND=nag_wp) arrayWorkspace
30:   LRWORK – INTEGERInput
On entry:
If LRWORK=-1, a workspace query is assumed; the routine only calculates the optimal size of the WORK array, returns this value as the first entry of the WORK array, and no error message related to LRWORK is issued. Otherwise the required workspace is 5 × max 1,Q-1 + 4 × max 1,Q + max 1,8×Q +1 which equates to 11 for Q=0, 18 for Q=1 and 17×Q-4 when Q>1.
Constraint:
LRWORK=-1 ​ or ​ LRWORK≥5×max 1,Q-1+4×max 1,Q+max 1,8×Q+1.
31:   IWORK M-min P,M-P,Q,M-Q – INTEGER arrayWorkspace
32:   INFO – INTEGEROutput
On exit: INFO=0 unless the routine detects an error (see Section 6).

6 Error Indicators and Warnings

INFO<0
If INFO=-i, argument i had an illegal value. An explanatory message is output, and execution of the program is terminated.
INFO>0
The Jacobi-type procedure failed to converge during an internal reduction to bidiagonal-block form. The process requires convergence to min P,M-P,Q,M-Q values, the value of INFO gives the number of converged values.

7 Accuracy

The computed CS decomposition is nearly the exact CS decomposition for the nearby matrix X+E , where
E 2 = O ε ,
and ε is the machine precision.

8 Parallelism and Performance

F08RNF (ZUNCSD) is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
F08RNF (ZUNCSD) makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The total number of floating-point operations required to perform the full CS decomposition is approximately 2 m 3.
The real analogue of this routine is F08RAF (DORCSD).

10 Example

This example finds the full CS decomposition of a unitary 6 by 6 matrix X (see Section 10.2) partitioned so that the top left block is 2 by 4.
The decomposition is performed both on submatrices of the unitary matrix X and on separated partition matrices. Code is also provided to perform a recombining check if required.

10.1 Program Text

Program Text (f08rnfe.f90)

10.2 Program Data

Program Data (f08rnfe.d)

10.3 Program Results

Program Results (f08rnfe.r)

F08 Chapter Contents
F08 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F08SAF (DSYGV) : NAG Library, Mark 26

F08 Chapter Contents
F08 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F08SAF (DSYGV)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F08SAF (DSYGV) computes all the eigenvalues and, optionally, the eigenvectors of a real generalized symmetric-definite eigenproblem, of the form
Az=λBz ,   ABz=λz   or   BAz=λz ,
where A and B are symmetric and B is also positive definite.

2 Specification

SUBROUTINE F08SAF ( ITYPE, JOBZ, UPLO, N, A, LDA, B, LDB, W, WORK, LWORK, INFO)
INTEGER | ITYPE, N, LDA, LDB, LWORK, INFO
REAL (KIND=nag_wp) | A(LDA,*), B(LDB,*), W(N), WORK(max(1,LWORK))
CHARACTER(1) | JOBZ, UPLO
The routine may be called by its LAPACK name dsygv.

3 Description

F08SAF (DSYGV) first performs a Cholesky factorization of the matrix B as B=UT U , when UPLO='U' or B=L LT , when UPLO='L'. The generalized problem is then reduced to a standard symmetric eigenvalue problem
Cx=λx ,
which is solved for the eigenvalues and, optionally, the eigenvectors; the eigenvectors are then backtransformed to give the eigenvectors of the original problem.
For the problem Az=λBz , the eigenvectors are normalized so that the matrix of eigenvectors, z, satisfies
ZT A Z = Λ   and   ZT B Z = I ,
where Λ is the diagonal matrix whose diagonal elements are the eigenvalues. For the problem A B z = λ z we correspondingly have
Z-1 A Z-T = Λ   and   ZT B Z = I ,
and for B A z = λ z we have
ZT A Z = Λ   and   ZT B-1 Z = I .

4 References

Anderson E, Bai Z, Bischof C, Blackford S, Demmel J, Dongarra J J, Du Croz J J, Greenbaum A, Hammarling S, McKenney A and Sorensen D (1999) LAPACK Users' Guide (3rd Edition) SIAM, Philadelphia http://www.netlib.org/lapack/lug
Golub G H and Van Loan C F (1996) Matrix Computations (3rd Edition) Johns Hopkins University Press, Baltimore

5 Arguments

1:   ITYPE – INTEGERInput
On entry: specifies the problem type to be solved.
ITYPE=1
Az=λBz.
ITYPE=2
ABz=λz.
ITYPE=3
BAz=λz.
Constraint: ITYPE=1, 2 or 3.
2:   JOBZ – CHARACTER(1)Input
On entry: indicates whether eigenvectors are computed.
JOBZ='N'
Only eigenvalues are computed.
JOBZ='V'
Eigenvalues and eigenvectors are computed.
Constraint: JOBZ='N' or 'V'.
3:   UPLO – CHARACTER(1)Input
On entry: if UPLO='U', the upper triangles of A and B are stored.
If UPLO='L', the lower triangles of A and B are stored.
Constraint: UPLO='U' or 'L'.
4:   N – INTEGERInput
On entry: n, the order of the matrices A and B.
Constraint: N≥0.
5:   A LDA* – REAL (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array A must be at least max 1,N.
On entry: the n by n symmetric matrix A.
  • If UPLO='U', the upper triangular part of A must be stored and the elements of the array below the diagonal are not referenced.
  • If UPLO='L', the lower triangular part of A must be stored and the elements of the array above the diagonal are not referenced.
On exit: if JOBZ='V', A contains the matrix Z of eigenvectors. The eigenvectors are normalized as follows:
  • if ITYPE=1 or 2, ZT BZ=I;
  • if ITYPE=3, ZTB-1 Z=I.
If JOBZ='N', the upper triangle (if UPLO='U') or the lower triangle (if UPLO='L') of A, including the diagonal, is overwritten.
6:   LDA – INTEGERInput
On entry: the first dimension of the array A as declared in the (sub)program from which F08SAF (DSYGV) is called.
Constraint: LDA≥max 1,N.
7:   B LDB* – REAL (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array B must be at least max 1,N.
On entry: the n by n symmetric positive definite matrix B.
  • If UPLO='U', the upper triangular part of B must be stored and the elements of the array below the diagonal are not referenced.
  • If UPLO='L', the lower triangular part of B must be stored and the elements of the array above the diagonal are not referenced.
On exit: if 0≤INFO≤N, the part of B containing the matrix is overwritten by the triangular factor U or L from the Cholesky factorization B=UT U or B=L LT.
8:   LDB – INTEGERInput
On entry: the first dimension of the array B as declared in the (sub)program from which F08SAF (DSYGV) is called.
Constraint: LDB≥max 1,N.
9:   W N – REAL (KIND=nag_wp) arrayOutput
On exit: the eigenvalues in ascending order.
10:   WORK max 1,LWORK – REAL (KIND=nag_wp) arrayWorkspace
On exit: if INFO=0, WORK 1 contains the minimum value of LWORK required for optimal performance.
11:   LWORK – INTEGERInput
On entry: the dimension of the array WORK as declared in the (sub)program from which F08SAF (DSYGV) is called.
If LWORK=-1, a workspace query is assumed; the routine only calculates the optimal size of the WORK array, returns this value as the first entry of the WORK array, and no error message related to LWORK is issued.
Suggested value: for optimal performance, LWORK≥nb+2×N, where nb is the optimal block size for F08FEF (DSYTRD).
Constraint: LWORK≥max 1,3×N-1.
12:   INFO – INTEGEROutput
On exit: INFO=0 unless the routine detects an error (see Section 6).

6 Error Indicators and Warnings

INFO<0
If INFO=-i, argument i had an illegal value. An explanatory message is output, and execution of the program is terminated.
INFO=1 to N
If INFO=i, F08FAF (DSYEV) failed to converge; i i off-diagonal elements of an intermediate tridiagonal form did not converge to zero.
INFO>N
F07FDF (DPOTRF) returned an error code; i.e., if INFO=N+i, for 1≤i≤N, then the leading minor of order i of B is not positive definite. The factorization of B could not be completed and no eigenvalues or eigenvectors were computed.

7 Accuracy

If B is ill-conditioned with respect to inversion, then the error bounds for the computed eigenvalues and vectors may be large, although when the diagonal elements of B differ widely in magnitude the eigenvalues and eigenvectors may be less sensitive than the condition of B would suggest. See Section 4.10 of Anderson et al. (1999) for details of the error bounds.
The example program below illustrates the computation of approximate error bounds.

8 Parallelism and Performance

F08SAF (DSYGV) is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
F08SAF (DSYGV) makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The total number of floating-point operations is proportional to n 3.
The complex analogue of this routine is F08SNF (ZHEGV).

10 Example

This example finds all the eigenvalues and eigenvectors of the generalized symmetric eigenproblem Az=λBz, where
A = 0.24 0.39 0.42 -0.16 0.39 -0.11 0.79 0.63 0.42 0.79 -0.25 0.48 -0.16 0.63 0.48 -0.03   and   B= 4.16 -3.12 0.56 -0.10 -3.12 5.03 -0.83 1.09 0.56 -0.83 0.76 0.34 -0.10 1.09 0.34 1.18 ,
together with and estimate of the condition number of B, and approximate error bounds for the computed eigenvalues and eigenvectors.
The example program for F08SCF (DSYGVD) illustrates solving a generalized symmetric eigenproblem of the form ABz=λz.

10.1 Program Text

Program Text (f08safe.f90)

10.2 Program Data

Program Data (f08safe.d)

10.3 Program Results

Program Results (f08safe.r)

F08 Chapter Contents
F08 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F08SBF (DSYGVX) : NAG Library, Mark 26

F08 Chapter Contents
F08 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F08SBF (DSYGVX)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F08SBF (DSYGVX) computes selected eigenvalues and, optionally, eigenvectors of a real generalized symmetric-definite eigenproblem, of the form
Az=λBz ,   ABz=λz   or   BAz=λz ,
where A and B are symmetric and B is also positive definite. Eigenvalues and eigenvectors can be selected by specifying either a range of values or a range of indices for the desired eigenvalues.

2 Specification

SUBROUTINE F08SBF ( ITYPE, JOBZ, RANGE, UPLO, N, A, LDA, B, LDB, VL, VU, IL, IU, ABSTOL, M, W, Z, LDZ, WORK, LWORK, IWORK, JFAIL, INFO)
INTEGER | ITYPE, N, LDA, LDB, IL, IU, M, LDZ, LWORK, IWORK(5*N), JFAIL(*), INFO
REAL (KIND=nag_wp) | A(LDA,*), B(LDB,*), VL, VU, ABSTOL, W(N), Z(LDZ,*), WORK(max(1,LWORK))
CHARACTER(1) | JOBZ, RANGE, UPLO
The routine may be called by its LAPACK name dsygvx.

3 Description

F08SBF (DSYGVX) first performs a Cholesky factorization of the matrix B as B=UT U , when UPLO='U' or B=L LT , when UPLO='L'. The generalized problem is then reduced to a standard symmetric eigenvalue problem
Cx=λx ,
which is solved for the desired eigenvalues and eigenvectors; the eigenvectors are then backtransformed to give the eigenvectors of the original problem.
For the problem Az=λBz , the eigenvectors are normalized so that the matrix of eigenvectors, Z, satisfies
ZT A Z = Λ   and   ZT B Z = I ,
where Λ is the diagonal matrix whose diagonal elements are the eigenvalues. For the problem A B z = λ z we correspondingly have
Z-1 A Z-T = Λ   and   ZT B Z = I ,
and for B A z = λ z we have
ZT A Z = Λ   and   ZT B-1 Z = I .

4 References

Anderson E, Bai Z, Bischof C, Blackford S, Demmel J, Dongarra J J, Du Croz J J, Greenbaum A, Hammarling S, McKenney A and Sorensen D (1999) LAPACK Users' Guide (3rd Edition) SIAM, Philadelphia http://www.netlib.org/lapack/lug
Demmel J W and Kahan W (1990) Accurate singular values of bidiagonal matrices SIAM J. Sci. Statist. Comput. 11 873–912
Golub G H and Van Loan C F (1996) Matrix Computations (3rd Edition) Johns Hopkins University Press, Baltimore

5 Arguments

1:   ITYPE – INTEGERInput
On entry: specifies the problem type to be solved.
ITYPE=1
Az=λBz.
ITYPE=2
ABz=λz.
ITYPE=3
BAz=λz.
Constraint: ITYPE=1, 2 or 3.
2:   JOBZ – CHARACTER(1)Input
On entry: indicates whether eigenvectors are computed.
JOBZ='N'
Only eigenvalues are computed.
JOBZ='V'
Eigenvalues and eigenvectors are computed.
Constraint: JOBZ='N' or 'V'.
3:   RANGE – CHARACTER(1)Input
On entry: if RANGE='A', all eigenvalues will be found.
If RANGE='V', all eigenvalues in the half-open interval VL,VU will be found.
If RANGE='I', the ILth to IUth eigenvalues will be found.
Constraint: RANGE='A', 'V' or 'I'.
4:   UPLO – CHARACTER(1)Input
On entry: if UPLO='U', the upper triangles of A and B are stored.
If UPLO='L', the lower triangles of A and B are stored.
Constraint: UPLO='U' or 'L'.
5:   N – INTEGERInput
On entry: n, the order of the matrices A and B.
Constraint: N≥0.
6:   A LDA* – REAL (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array A must be at least max 1,N.
On entry: the n by n symmetric matrix A.
  • If UPLO='U', the upper triangular part of A must be stored and the elements of the array below the diagonal are not referenced.
  • If UPLO='L', the lower triangular part of A must be stored and the elements of the array above the diagonal are not referenced.
On exit: the lower triangle (if UPLO='L') or the upper triangle (if UPLO='U') of A, including the diagonal, is overwritten.
7:   LDA – INTEGERInput
On entry: the first dimension of the array A as declared in the (sub)program from which F08SBF (DSYGVX) is called.
Constraint: LDA≥max 1,N.
8:   B LDB* – REAL (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array B must be at least max 1,N.
On entry: the n by n symmetric matrix B.
  • If UPLO='U', the upper triangular part of B must be stored and the elements of the array below the diagonal are not referenced.
  • If UPLO='L', the lower triangular part of B must be stored and the elements of the array above the diagonal are not referenced.
On exit: the triangular factor U or L from the Cholesky factorization B=UT U or B=L LT.
9:   LDB – INTEGERInput
On entry: the first dimension of the array B as declared in the (sub)program from which F08SBF (DSYGVX) is called.
Constraint: LDB≥max 1,N.
10:   VL – REAL (KIND=nag_wp)Input
11:   VU – REAL (KIND=nag_wp)Input
On entry: if RANGE='V', the lower and upper bounds of the interval to be searched for eigenvalues.
If RANGE='A' or 'I', VL and VU are not referenced.
Constraint: if RANGE='V', VL<VU.
12:   IL – INTEGERInput
13:   IU – INTEGERInput
On entry: if RANGE='I', the indices (in ascending order) of the smallest and largest eigenvalues to be returned.
If RANGE='A' or 'V', IL and IU are not referenced.
Constraints:
  • if RANGE='I' and N=0, IL=1 and IU=0;
  • if RANGE='I' and N>0, 1≤ IL≤ IU≤ N .
14:   ABSTOL – REAL (KIND=nag_wp)Input
On entry: the absolute error tolerance for the eigenvalues. An approximate eigenvalue is accepted as converged when it is determined to lie in an interval a,b of width less than or equal to
ABSTOL+ε max a,b ,
where ε is the machine precision. If ABSTOL is less than or equal to zero, then ε T 1 will be used in its place, where T is the tridiagonal matrix obtained by reducing C to tridiagonal form. Eigenvalues will be computed most accurately when ABSTOL is set to twice the underflow threshold 2 × X02AMF , not zero. If this routine returns with INFO=1 to N, indicating that some eigenvectors did not converge, try setting ABSTOL to 2 × X02AMF . See Demmel and Kahan (1990).
15:   M – INTEGEROutput
On exit: the total number of eigenvalues found. 0≤M≤N.
If RANGE='A', M=N.
If RANGE='I', M=IU-IL+1.
16:   W N – REAL (KIND=nag_wp) arrayOutput
On exit: the first M elements contain the selected eigenvalues in ascending order.
17:   Z LDZ* – REAL (KIND=nag_wp) arrayOutput
Note: the second dimension of the array Z must be at least max 1,M if JOBZ='V', and at least 1 otherwise.
On exit: if JOBZ='V', then
  • if INFO=0, the first M columns of Z contain the orthonormal eigenvectors of the matrix A corresponding to the selected eigenvalues, with the ith column of Z holding the eigenvector associated with W i. The eigenvectors are normalized as follows:
    • if ITYPE=1 or 2, ZT BZ=I;
    • if ITYPE=3, ZTB-1 Z=I;
  • if an eigenvector fails to converge (INFO=1 to N), then that column of Z contains the latest approximation to the eigenvector, and the index of the eigenvector is returned in JFAIL.
If JOBZ='N', Z is not referenced.
Note: you must ensure that at least max 1,M columns are supplied in the array Z; if RANGE='V', the exact value of M is not known in advance and an upper bound of at least N must be used.
18:   LDZ – INTEGERInput
On entry: the first dimension of the array Z as declared in the (sub)program from which F08SBF (DSYGVX) is called.
Constraints:
  • if JOBZ='V', LDZ≥ max 1,N ;
  • otherwise LDZ≥1.
19:   WORK max 1,LWORK – REAL (KIND=nag_wp) arrayWorkspace
On exit: if INFO=0, WORK 1 contains the minimum value of LWORK required for optimal performance.
20:   LWORK – INTEGERInput
On entry: the dimension of the array WORK as declared in the (sub)program from which F08SBF (DSYGVX) is called.
If LWORK=-1, a workspace query is assumed; the routine only calculates the optimal size of the WORK array, returns this value as the first entry of the WORK array, and no error message related to LWORK is issued.
Suggested value: for optimal performance, LWORK≥nb+3×N, where nb is the optimal block size for F08FEF (DSYTRD).
Constraint: LWORK≥max 1,8×N.
21:   IWORK 5×N – INTEGER arrayWorkspace
22:   JFAIL* – INTEGER arrayOutput
Note: the dimension of the array JFAIL must be at least max 1,N.
On exit: if JOBZ='V', then
  • if INFO=0, the first M elements of JFAIL are zero;
  • if INFO=1 to N, JFAIL contains the indices of the eigenvectors that failed to converge.
If JOBZ='N', JFAIL is not referenced.
23:   INFO – INTEGEROutput
On exit: INFO=0 unless the routine detects an error (see Section 6).

6 Error Indicators and Warnings

INFO<0
If INFO=-i, argument i had an illegal value. An explanatory message is output, and execution of the program is terminated.
INFO=1 to N
If INFO=i, F08FBF (DSYEVX) failed to converge; i eigenvectors failed to converge. Their indices are stored in array JFAIL.
INFO>N
F07FDF (DPOTRF) returned an error code; i.e., if INFO=N+i, for 1≤i≤N, then the leading minor of order i of B is not positive definite. The factorization of B could not be completed and no eigenvalues or eigenvectors were computed.

7 Accuracy

If B is ill-conditioned with respect to inversion, then the error bounds for the computed eigenvalues and vectors may be large, although when the diagonal elements of B differ widely in magnitude the eigenvalues and eigenvectors may be less sensitive than the condition of B would suggest. See Section 4.10 of Anderson et al. (1999) for details of the error bounds.

8 Parallelism and Performance

F08SBF (DSYGVX) is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
F08SBF (DSYGVX) makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The total number of floating-point operations is proportional to n 3.
The complex analogue of this routine is F08SPF (ZHEGVX).

10 Example

This example finds the eigenvalues in the half-open interval -1.0,1.0, and corresponding eigenvectors, of the generalized symmetric eigenproblem Az=λBz, where
A = 0.24 0.39 0.42 -0.16 0.39 -0.11 0.79 0.63 0.42 0.79 -0.25 0.48 -0.16 0.63 0.48 -0.03   and   B= 4.16 -3.12 0.56 -0.10 -3.12 5.03 -0.83 1.09 0.56 -0.83 0.76 0.34 -0.10 1.09 0.34 1.18 .
The example program for F08SCF (DSYGVD) illustrates solving a generalized symmetric eigenproblem of the form ABz=λz.

10.1 Program Text

Program Text (f08sbfe.f90)

10.2 Program Data

Program Data (f08sbfe.d)

10.3 Program Results

Program Results (f08sbfe.r)

F08 Chapter Contents
F08 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F08SCF (DSYGVD) : NAG Library, Mark 26

F08 Chapter Contents
F08 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F08SCF (DSYGVD)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F08SCF (DSYGVD) computes all the eigenvalues and, optionally, the eigenvectors of a real generalized symmetric-definite eigenproblem, of the form
Az=λBz ,   ABz=λz   or   BAz=λz ,
where A and B are symmetric and B is also positive definite. If eigenvectors are desired, it uses a divide-and-conquer algorithm.

2 Specification

SUBROUTINE F08SCF ( ITYPE, JOBZ, UPLO, N, A, LDA, B, LDB, W, WORK, LWORK, IWORK, LIWORK, INFO)
INTEGER | ITYPE, N, LDA, LDB, LWORK, IWORK(max(1,LIWORK)), LIWORK, INFO
REAL (KIND=nag_wp) | A(LDA,*), B(LDB,*), W(N), WORK(max(1,LWORK))
CHARACTER(1) | JOBZ, UPLO
The routine may be called by its LAPACK name dsygvd.

3 Description

F08SCF (DSYGVD) first performs a Cholesky factorization of the matrix B as B=UT U , when UPLO='U' or B=L LT , when UPLO='L'. The generalized problem is then reduced to a standard symmetric eigenvalue problem
Cx=λx ,
which is solved for the eigenvalues and, optionally, the eigenvectors; the eigenvectors are then backtransformed to give the eigenvectors of the original problem.
For the problem Az=λBz , the eigenvectors are normalized so that the matrix of eigenvectors, z, satisfies
ZT A Z = Λ   and   ZT B Z = I ,
where Λ is the diagonal matrix whose diagonal elements are the eigenvalues. For the problem A B z = λ z we correspondingly have
Z-1 A Z-T = Λ   and   ZT B Z = I ,
and for B A z = λ z we have
ZT A Z = Λ   and   ZT B-1 Z = I .

4 References

Anderson E, Bai Z, Bischof C, Blackford S, Demmel J, Dongarra J J, Du Croz J J, Greenbaum A, Hammarling S, McKenney A and Sorensen D (1999) LAPACK Users' Guide (3rd Edition) SIAM, Philadelphia http://www.netlib.org/lapack/lug
Golub G H and Van Loan C F (1996) Matrix Computations (3rd Edition) Johns Hopkins University Press, Baltimore

5 Arguments

1:   ITYPE – INTEGERInput
On entry: specifies the problem type to be solved.
ITYPE=1
Az=λBz.
ITYPE=2
ABz=λz.
ITYPE=3
BAz=λz.
Constraint: ITYPE=1, 2 or 3.
2:   JOBZ – CHARACTER(1)Input
On entry: indicates whether eigenvectors are computed.
JOBZ='N'
Only eigenvalues are computed.
JOBZ='V'
Eigenvalues and eigenvectors are computed.
Constraint: JOBZ='N' or 'V'.
3:   UPLO – CHARACTER(1)Input
On entry: if UPLO='U', the upper triangles of A and B are stored.
If UPLO='L', the lower triangles of A and B are stored.
Constraint: UPLO='U' or 'L'.
4:   N – INTEGERInput
On entry: n, the order of the matrices A and B.
Constraint: N≥0.
5:   A LDA* – REAL (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array A must be at least max 1,N.
On entry: the n by n symmetric matrix A.
  • If UPLO='U', the upper triangular part of A must be stored and the elements of the array below the diagonal are not referenced.
  • If UPLO='L', the lower triangular part of A must be stored and the elements of the array above the diagonal are not referenced.
On exit: if JOBZ='V', A contains the matrix Z of eigenvectors. The eigenvectors are normalized as follows:
  • if ITYPE=1 or 2, ZT BZ=I;
  • if ITYPE=3, ZTB-1 Z=I.
If JOBZ='N', the upper triangle (if UPLO='U') or the lower triangle (if UPLO='L') of A, including the diagonal, is overwritten.
6:   LDA – INTEGERInput
On entry: the first dimension of the array A as declared in the (sub)program from which F08SCF (DSYGVD) is called.
Constraint: LDA≥max 1,N.
7:   B LDB* – REAL (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array B must be at least max 1,N.
On entry: the n by n symmetric matrix B.
  • If UPLO='U', the upper triangular part of B must be stored and the elements of the array below the diagonal are not referenced.
  • If UPLO='L', the lower triangular part of B must be stored and the elements of the array above the diagonal are not referenced.
On exit: the triangular factor U or L from the Cholesky factorization B=UT U or B=L LT.
8:   LDB – INTEGERInput
On entry: the first dimension of the array B as declared in the (sub)program from which F08SCF (DSYGVD) is called.
Constraint: LDB≥max 1,N.
9:   W N – REAL (KIND=nag_wp) arrayOutput
On exit: the eigenvalues in ascending order.
10:   WORK max 1,LWORK – REAL (KIND=nag_wp) arrayWorkspace
On exit: if INFO=0, WORK 1 contains the minimum value of LWORK required for optimal performance.
11:   LWORK – INTEGERInput
On entry: the dimension of the array WORK as declared in the (sub)program from which F08SCF (DSYGVD) is called.
If LWORK=-1, a workspace query is assumed; the routine only calculates the optimal size of the WORK array and the minimum size of the IWORK array, returns these values as the first entries of the WORK and IWORK arrays, and no error message related to LWORK or LIWORK is issued.
Suggested value: for optimal performance, LWORK should usually be larger than the minimum, try increasing by nb×N, where nb is the optimal block size.
Constraints:
  • if N≤1, LWORK≥1;
  • if JOBZ='N' and N>1, LWORK≥2×N+1;
  • if JOBZ='V' and N>1, LWORK≥1+6×N+2×N 2.
12:   IWORK max 1,LIWORK – INTEGER arrayWorkspace
On exit: if INFO=0, IWORK 1 returns the minimum LIWORK.
13:   LIWORK – INTEGERInput
On entry: the dimension of the array IWORK as declared in the (sub)program from which F08SCF (DSYGVD) is called.
If LIWORK=-1, a workspace query is assumed; the routine only calculates the optimal size of the WORK array and the minimum size of the IWORK array, returns these values as the first entries of the WORK and IWORK arrays, and no error message related to LWORK or LIWORK is issued.
Constraints:
  • if N≤1, LIWORK≥1;
  • if JOBZ='N' and N>1, LIWORK≥1;
  • if JOBZ='V' and N>1, LIWORK≥3+5×N.
14:   INFO – INTEGEROutput
On exit: INFO=0 unless the routine detects an error (see Section 6).

6 Error Indicators and Warnings

INFO<0
If INFO=-i, argument i had an illegal value. An explanatory message is output, and execution of the program is terminated.
INFO=1 to N
If INFO=i, F08FCF (DSYEVD) failed to converge; i i off-diagonal elements of an intermediate tridiagonal form did not converge to zero.
INFO>N
F07FDF (DPOTRF) returned an error code; i.e., if INFO=N+i, for 1≤i≤N, then the leading minor of order i of B is not positive definite. The factorization of B could not be completed and no eigenvalues or eigenvectors were computed.

7 Accuracy

If B is ill-conditioned with respect to inversion, then the error bounds for the computed eigenvalues and vectors may be large, although when the diagonal elements of B differ widely in magnitude the eigenvalues and eigenvectors may be less sensitive than the condition of B would suggest. See Section 4.10 of Anderson et al. (1999) for details of the error bounds.
The example program below illustrates the computation of approximate error bounds.

8 Parallelism and Performance

F08SCF (DSYGVD) is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
F08SCF (DSYGVD) makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The total number of floating-point operations is proportional to n 3 .
The complex analogue of this routine is F08SQF (ZHEGVD).

10 Example

This example finds all the eigenvalues and eigenvectors of the generalized symmetric eigenproblem ABz=λz , where
A = 0.24 0.39 0.42 -0.16 0.39 -0.11 0.79 0.63 0.42 0.79 -0.25 0.48 -0.16 0.63 0.48 -0.03   and   B = 4.16 -3.12 0.56 -0.10 -3.12 5.03 -0.83 1.09 0.56 -0.83 0.76 0.34 -0.10 1.09 0.34 1.18 ,
together with an estimate of the condition number of B, and approximate error bounds for the computed eigenvalues and eigenvectors.
The example program for F08SAF (DSYGV) illustrates solving a generalized symmetric eigenproblem of the form Az=λBz .

10.1 Program Text

Program Text (f08scfe.f90)

10.2 Program Data

Program Data (f08scfe.d)

10.3 Program Results

Program Results (f08scfe.r)

F08 Chapter Contents
F08 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F08SEF (DSYGST) : NAG Library, Mark 26

F08 Chapter Contents
F08 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F08SEF (DSYGST)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F08SEF (DSYGST) reduces a real symmetric-definite generalized eigenproblem Az=λBz, ABz=λz or BAz=λz to the standard form Cy=λy, where A is a real symmetric matrix and B has been factorized by F07FDF (DPOTRF).

2 Specification

SUBROUTINE F08SEF ( ITYPE, UPLO, N, A, LDA, B, LDB, INFO)
INTEGER | ITYPE, N, LDA, LDB, INFO
REAL (KIND=nag_wp) | A(LDA,*), B(LDB,*)
CHARACTER(1) | UPLO
The routine may be called by its LAPACK name dsygst.

3 Description

To reduce the real symmetric-definite generalized eigenproblem Az=λBz, ABz=λz or BAz=λz to the standard form Cy=λy, F08SEF (DSYGST) must be preceded by a call to F07FDF (DPOTRF) which computes the Cholesky factorization of B; B must be positive definite.
The different problem types are specified by the argument ITYPE, as indicated in the table below. The table shows how C is computed by the routine, and also how the eigenvectors z of the original problem can be recovered from the eigenvectors of the standard form.
ITYPE | Problem | UPLO | B | C | z
1 | Az=λBz | 'U' 'L' | UT U L LT | U-T A U-1 L-1 A L-T | U-1 y L-T y
2 | ABz=λz | 'U' 'L' | UT U L LT | UA UT LT AL | U-1 y L-T y
3 | BAz=λz | 'U' 'L' | UT U L LT | UA UT LT AL | UT y Ly

4 References

Golub G H and Van Loan C F (1996) Matrix Computations (3rd Edition) Johns Hopkins University Press, Baltimore

5 Arguments

1:   ITYPE – INTEGERInput
On entry: indicates how the standard form is computed.
ITYPE=1
  • if UPLO='U', C=U-T A U-1;
  • if UPLO='L', C=L-1 A L-T.
ITYPE=2 or 3
  • if UPLO='U', C=UA UT;
  • if UPLO='L', C=LT AL.
Constraint: ITYPE=1, 2 or 3.
2:   UPLO – CHARACTER(1)Input
On entry: indicates whether the upper or lower triangular part of A is stored and how B has been factorized.
UPLO='U'
The upper triangular part of A is stored and B=UT U.
UPLO='L'
The lower triangular part of A is stored and B=L LT.
Constraint: UPLO='U' or 'L'.
3:   N – INTEGERInput
On entry: n, the order of the matrices A and B.
Constraint: N≥0.
4:   A LDA* – REAL (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array A must be at least max 1,N.
On entry: the n by n symmetric matrix A.
  • If UPLO='U', the upper triangular part of A must be stored and the elements of the array below the diagonal are not referenced.
  • If UPLO='L', the lower triangular part of A must be stored and the elements of the array above the diagonal are not referenced.
On exit: the upper or lower triangle of A is overwritten by the corresponding upper or lower triangle of C as specified by ITYPE and UPLO.
5:   LDA – INTEGERInput
On entry: the first dimension of the array A as declared in the (sub)program from which F08SEF (DSYGST) is called.
Constraint: LDA≥max 1,N.
6:   B LDB* – REAL (KIND=nag_wp) arrayInput
Note: the second dimension of the array B must be at least max 1,N.
On entry: the Cholesky factor of B as specified by UPLO and returned by F07FDF (DPOTRF).
7:   LDB – INTEGERInput
On entry: the first dimension of the array B as declared in the (sub)program from which F08SEF (DSYGST) is called.
Constraint: LDB≥max 1,N.
8:   INFO – INTEGEROutput
On exit: INFO=0 unless the routine detects an error (see Section 6).

6 Error Indicators and Warnings

INFO<0
If INFO=-i, argument i had an illegal value. An explanatory message is output, and execution of the program is terminated.

7 Accuracy

Forming the reduced matrix C is a stable procedure. However it involves implicit multiplication by B-1 (if ITYPE=1) or B (if ITYPE=2 or 3). When F08SEF (DSYGST) is used as a step in the computation of eigenvalues and eigenvectors of the original problem, there may be a significant loss of accuracy if B is ill-conditioned with respect to inversion. See the document for F08SAF (DSYGV) for further details.

8 Parallelism and Performance

F08SEF (DSYGST) makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The total number of floating-point operations is approximately n 3.
The complex analogue of this routine is F08SSF (ZHEGST).

10 Example

This example computes all the eigenvalues of Az=λBz, where
A = 0.24 0.39 0.42 -0.16 0.39 -0.11 0.79 0.63 0.42 0.79 -0.25 0.48 -0.16 0.63 0.48 -0.03   and   B= 4.16 -3.12 0.56 -0.10 -3.12 5.03 -0.83 1.09 0.56 -0.83 0.76 0.34 -0.10 1.09 0.34 1.18 .
Here B is symmetric positive definite and must first be factorized by F07FDF (DPOTRF). The program calls F08SEF (DSYGST) to reduce the problem to the standard form Cy=λy; then F08FEF (DSYTRD) to reduce C to tridiagonal form, and F08JFF (DSTERF) to compute the eigenvalues.

10.1 Program Text

Program Text (f08sefe.f90)

10.2 Program Data

Program Data (f08sefe.d)

10.3 Program Results

Program Results (f08sefe.r)

F08 Chapter Contents
F08 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F08SNF (ZHEGV) : NAG Library, Mark 26

F08 Chapter Contents
F08 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F08SNF (ZHEGV)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F08SNF (ZHEGV) computes all the eigenvalues and, optionally, the eigenvectors of a complex generalized Hermitian-definite eigenproblem, of the form
Az=λBz ,   ABz=λz   or   BAz=λz ,
where A and B are Hermitian and B is also positive definite.

2 Specification

SUBROUTINE F08SNF ( ITYPE, JOBZ, UPLO, N, A, LDA, B, LDB, W, WORK, LWORK, RWORK, INFO)
INTEGER | ITYPE, N, LDA, LDB, LWORK, INFO
REAL (KIND=nag_wp) | W(N), RWORK(3*N-2)
COMPLEX (KIND=nag_wp) | A(LDA,*), B(LDB,*), WORK(max(1,LWORK))
CHARACTER(1) | JOBZ, UPLO
The routine may be called by its LAPACK name zhegv.

3 Description

F08SNF (ZHEGV) first performs a Cholesky factorization of the matrix B as B=UH U , when UPLO='U' or B=L LH , when UPLO='L'. The generalized problem is then reduced to a standard symmetric eigenvalue problem
Cx=λx ,
which is solved for the eigenvalues and, optionally, the eigenvectors; the eigenvectors are then backtransformed to give the eigenvectors of the original problem.
For the problem Az=λBz , the eigenvectors are normalized so that the matrix of eigenvectors, z, satisfies
ZH A Z = Λ   and   ZH B Z = I ,
where Λ is the diagonal matrix whose diagonal elements are the eigenvalues. For the problem A B z = λ z we correspondingly have
Z-1 A Z-H = Λ   and   ZH B Z = I ,
and for B A z = λ z we have
ZH A Z = Λ   and   ZH B-1 Z = I .

4 References

Anderson E, Bai Z, Bischof C, Blackford S, Demmel J, Dongarra J J, Du Croz J J, Greenbaum A, Hammarling S, McKenney A and Sorensen D (1999) LAPACK Users' Guide (3rd Edition) SIAM, Philadelphia http://www.netlib.org/lapack/lug
Golub G H and Van Loan C F (1996) Matrix Computations (3rd Edition) Johns Hopkins University Press, Baltimore

5 Arguments

1:   ITYPE – INTEGERInput
On entry: specifies the problem type to be solved.
ITYPE=1
Az=λBz.
ITYPE=2
ABz=λz.
ITYPE=3
BAz=λz.
Constraint: ITYPE=1, 2 or 3.
2:   JOBZ – CHARACTER(1)Input
On entry: indicates whether eigenvectors are computed.
JOBZ='N'
Only eigenvalues are computed.
JOBZ='V'
Eigenvalues and eigenvectors are computed.
Constraint: JOBZ='N' or 'V'.
3:   UPLO – CHARACTER(1)Input
On entry: if UPLO='U', the upper triangles of A and B are stored.
If UPLO='L', the lower triangles of A and B are stored.
Constraint: UPLO='U' or 'L'.
4:   N – INTEGERInput
On entry: n, the order of the matrices A and B.
Constraint: N≥0.
5:   A LDA* – COMPLEX (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array A must be at least max 1,N.
On entry: the n by n Hermitian matrix A.
  • If UPLO='U', the upper triangular part of A must be stored and the elements of the array below the diagonal are not referenced.
  • If UPLO='L', the lower triangular part of A must be stored and the elements of the array above the diagonal are not referenced.
On exit: if JOBZ='V', A contains the matrix Z of eigenvectors. The eigenvectors are normalized as follows:
  • if ITYPE=1 or 2, ZH BZ=I;
  • if ITYPE=3, ZHB-1 Z=I.
If JOBZ='N', the upper triangle (if UPLO='U') or the lower triangle (if UPLO='L') of A, including the diagonal, is overwritten.
6:   LDA – INTEGERInput
On entry: the first dimension of the array A as declared in the (sub)program from which F08SNF (ZHEGV) is called.
Constraint: LDA≥max 1,N.
7:   B LDB* – COMPLEX (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array B must be at least max 1,N.
On entry: the n by n Hermitian positive definite matrix B.
  • If UPLO='U', the upper triangular part of B must be stored and the elements of the array below the diagonal are not referenced.
  • If UPLO='L', the lower triangular part of B must be stored and the elements of the array above the diagonal are not referenced.
On exit: if 0≤INFO≤N, the part of B containing the matrix is overwritten by the triangular factor U or L from the Cholesky factorization B=UH U or B=L LH.
8:   LDB – INTEGERInput
On entry: the first dimension of the array B as declared in the (sub)program from which F08SNF (ZHEGV) is called.
Constraint: LDB≥max 1,N.
9:   W N – REAL (KIND=nag_wp) arrayOutput
On exit: the eigenvalues in ascending order.
10:   WORK max 1,LWORK – COMPLEX (KIND=nag_wp) arrayWorkspace
On exit: if INFO=0, the real part of WORK 1 contains the minimum value of LWORK required for optimal performance.
11:   LWORK – INTEGERInput
On entry: the dimension of the array WORK as declared in the (sub)program from which F08SNF (ZHEGV) is called.
If LWORK=-1, a workspace query is assumed; the routine only calculates the optimal size of the WORK array, returns this value as the first entry of the WORK array, and no error message related to LWORK is issued.
Suggested value: for optimal performance, LWORK≥nb+1×N, where nb is the optimal block size for F08FSF (ZHETRD).
Constraint: LWORK≥max 1,2×N.
12:   RWORK 3×N-2 – REAL (KIND=nag_wp) arrayWorkspace
13:   INFO – INTEGEROutput
On exit: INFO=0 unless the routine detects an error (see Section 6).

6 Error Indicators and Warnings

INFO<0
If INFO=-i, argument i had an illegal value. An explanatory message is output, and execution of the program is terminated.
INFO=1 to N
If INFO=i, F08FNF (ZHEEV) failed to converge; i i off-diagonal elements of an intermediate tridiagonal form did not converge to zero.
INFO>N
F07FRF (ZPOTRF) returned an error code; i.e., if INFO=N+i, for 1≤i≤N, then the leading minor of order i of B is not positive definite. The factorization of B could not be completed and no eigenvalues or eigenvectors were computed.

7 Accuracy

If B is ill-conditioned with respect to inversion, then the error bounds for the computed eigenvalues and vectors may be large, although when the diagonal elements of B differ widely in magnitude the eigenvalues and eigenvectors may be less sensitive than the condition of B would suggest. See Section 4.10 of Anderson et al. (1999) for details of the error bounds.
The example program below illustrates the computation of approximate error bounds.

8 Parallelism and Performance

F08SNF (ZHEGV) is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
F08SNF (ZHEGV) makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The total number of floating-point operations is proportional to n 3.
The real analogue of this routine is F08SAF (DSYGV).

10 Example

This example finds all the eigenvalues and eigenvectors of the generalized Hermitian eigenproblem Az=λBz, where
A = -7.36 i+0.00 0.77-0.43 i -0.64-0.92 i 3.01-6.97 i 0.77+0.43 i 3.49 i+0.00 2.19+4.45 i 1.90+3.73 i -0.64+0.92 i 2.19-4.45 i 0.12 i+0.00 2.88-3.17 i 3.01+6.97 i 1.90-3.73 i 2.88+3.17 i -2.54 i+0.00
and
B = 3.23 i+0.00 1.51-1.92 i 1.90+0.84 i 0.42+2.50 i 1.51+1.92 i 3.58 i+0.00 -0.23+1.11 i -1.18+1.37 i 1.90-0.84 i -0.23-1.11 i 4.09 i+0.00 2.33-0.14 i 0.42-2.50 i -1.18-1.37 i 2.33+0.14 i 4.29 i+0.00 ,
together with and estimate of the condition number of B, and approximate error bounds for the computed eigenvalues and eigenvectors.
The example program for F08SQF (ZHEGVD) illustrates solving a generalized Hermitian eigenproblem of the form ABz=λz.

10.1 Program Text

Program Text (f08snfe.f90)

10.2 Program Data

Program Data (f08snfe.d)

10.3 Program Results

Program Results (f08snfe.r)

F08 Chapter Contents
F08 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F08SPF (ZHEGVX) : NAG Library, Mark 26

F08 Chapter Contents
F08 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F08SPF (ZHEGVX)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F08SPF (ZHEGVX) computes selected eigenvalues and, optionally, eigenvectors of a complex generalized Hermitian-definite eigenproblem, of the form
Az=λBz ,   ABz=λz   or   BAz=λz ,
where A and B are Hermitian and B is also positive definite. Eigenvalues and eigenvectors can be selected by specifying either a range of values or a range of indices for the desired eigenvalues.

2 Specification

SUBROUTINE F08SPF ( ITYPE, JOBZ, RANGE, UPLO, N, A, LDA, B, LDB, VL, VU, IL, IU, ABSTOL, M, W, Z, LDZ, WORK, LWORK, RWORK, IWORK, JFAIL, INFO)
INTEGER | ITYPE, N, LDA, LDB, IL, IU, M, LDZ, LWORK, IWORK(5*N), JFAIL(*), INFO
REAL (KIND=nag_wp) | VL, VU, ABSTOL, W(N), RWORK(7*N)
COMPLEX (KIND=nag_wp) | A(LDA,*), B(LDB,*), Z(LDZ,*), WORK(max(1,LWORK))
CHARACTER(1) | JOBZ, RANGE, UPLO
The routine may be called by its LAPACK name zhegvx.

3 Description

F08SPF (ZHEGVX) first performs a Cholesky factorization of the matrix B as B=UH U , when UPLO='U' or B=L LH , when UPLO='L'. The generalized problem is then reduced to a standard symmetric eigenvalue problem
Cx=λx ,
which is solved for the desired eigenvalues and eigenvectors; the eigenvectors are then backtransformed to give the eigenvectors of the original problem.
For the problem Az=λBz , the eigenvectors are normalized so that the matrix of eigenvectors, Z, satisfies
ZH A Z = Λ   and   ZH B Z = I ,
where Λ is the diagonal matrix whose diagonal elements are the eigenvalues. For the problem A B z = λ z we correspondingly have
Z-1 A Z-H = Λ   and   ZH B Z = I ,
and for B A z = λ z we have
ZH A Z = Λ   and   ZH B-1 Z = I .

4 References

Anderson E, Bai Z, Bischof C, Blackford S, Demmel J, Dongarra J J, Du Croz J J, Greenbaum A, Hammarling S, McKenney A and Sorensen D (1999) LAPACK Users' Guide (3rd Edition) SIAM, Philadelphia http://www.netlib.org/lapack/lug
Demmel J W and Kahan W (1990) Accurate singular values of bidiagonal matrices SIAM J. Sci. Statist. Comput. 11 873–912
Golub G H and Van Loan C F (1996) Matrix Computations (3rd Edition) Johns Hopkins University Press, Baltimore

5 Arguments

1:   ITYPE – INTEGERInput
On entry: specifies the problem type to be solved.
ITYPE=1
Az=λBz.
ITYPE=2
ABz=λz.
ITYPE=3
BAz=λz.
Constraint: ITYPE=1, 2 or 3.
2:   JOBZ – CHARACTER(1)Input
On entry: indicates whether eigenvectors are computed.
JOBZ='N'
Only eigenvalues are computed.
JOBZ='V'
Eigenvalues and eigenvectors are computed.
Constraint: JOBZ='N' or 'V'.
3:   RANGE – CHARACTER(1)Input
On entry: if RANGE='A', all eigenvalues will be found.
If RANGE='V', all eigenvalues in the half-open interval VL,VU will be found.
If RANGE='I', the ILth to IUth eigenvalues will be found.
Constraint: RANGE='A', 'V' or 'I'.
4:   UPLO – CHARACTER(1)Input
On entry: if UPLO='U', the upper triangles of A and B are stored.
If UPLO='L', the lower triangles of A and B are stored.
Constraint: UPLO='U' or 'L'.
5:   N – INTEGERInput
On entry: n, the order of the matrices A and B.
Constraint: N≥0.
6:   A LDA* – COMPLEX (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array A must be at least max 1,N.
On entry: the n by n Hermitian matrix A.
  • If UPLO='U', the upper triangular part of A must be stored and the elements of the array below the diagonal are not referenced.
  • If UPLO='L', the lower triangular part of A must be stored and the elements of the array above the diagonal are not referenced.
On exit: the lower triangle (if UPLO='L') or the upper triangle (if UPLO='U') of A, including the diagonal, is overwritten.
7:   LDA – INTEGERInput
On entry: the first dimension of the array A as declared in the (sub)program from which F08SPF (ZHEGVX) is called.
Constraint: LDA≥max 1,N.
8:   B LDB* – COMPLEX (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array B must be at least max 1,N.
On entry: the n by n Hermitian matrix B.
  • If UPLO='U', the upper triangular part of B must be stored and the elements of the array below the diagonal are not referenced.
  • If UPLO='L', the lower triangular part of B must be stored and the elements of the array above the diagonal are not referenced.
On exit: the triangular factor U or L from the Cholesky factorization B=UH U or B=L LH.
9:   LDB – INTEGERInput
On entry: the first dimension of the array B as declared in the (sub)program from which F08SPF (ZHEGVX) is called.
Constraint: LDB≥max 1,N.
10:   VL – REAL (KIND=nag_wp)Input
11:   VU – REAL (KIND=nag_wp)Input
On entry: if RANGE='V', the lower and upper bounds of the interval to be searched for eigenvalues.
If RANGE='A' or 'I', VL and VU are not referenced.
Constraint: if RANGE='V', VL<VU.
12:   IL – INTEGERInput
13:   IU – INTEGERInput
On entry: if RANGE='I', the indices (in ascending order) of the smallest and largest eigenvalues to be returned.
If RANGE='A' or 'V', IL and IU are not referenced.
Constraints:
  • if RANGE='I' and N=0, IL=1 and IU=0;
  • if RANGE='I' and N>0, 1≤ IL≤ IU≤ N .
14:   ABSTOL – REAL (KIND=nag_wp)Input
On entry: the absolute error tolerance for the eigenvalues. An approximate eigenvalue is accepted as converged when it is determined to lie in an interval a,b of width less than or equal to
ABSTOL+ε max a,b ,
where ε is the machine precision. If ABSTOL is less than or equal to zero, then ε T 1 will be used in its place, where T is the tridiagonal matrix obtained by reducing C to tridiagonal form. Eigenvalues will be computed most accurately when ABSTOL is set to twice the underflow threshold 2 × X02AMF , not zero. If this routine returns with INFO=1 to N, indicating that some eigenvectors did not converge, try setting ABSTOL to 2 × X02AMF . See Demmel and Kahan (1990).
15:   M – INTEGEROutput
On exit: the total number of eigenvalues found. 0≤M≤N.
If RANGE='A', M=N.
If RANGE='I', M=IU-IL+1.
16:   W N – REAL (KIND=nag_wp) arrayOutput
On exit: the first M elements contain the selected eigenvalues in ascending order.
17:   Z LDZ* – COMPLEX (KIND=nag_wp) arrayOutput
Note: the second dimension of the array Z must be at least max 1,M if JOBZ='V', and at least 1 otherwise.
On exit: if JOBZ='V', then
  • if INFO=0, the first M columns of Z contain the orthonormal eigenvectors of the matrix A corresponding to the selected eigenvalues, with the ith column of Z holding the eigenvector associated with W i. The eigenvectors are normalized as follows:
    • if ITYPE=1 or 2, ZH BZ=I;
    • if ITYPE=3, ZHB-1 Z=I;
  • if an eigenvector fails to converge (INFO=1 to N), then that column of Z contains the latest approximation to the eigenvector, and the index of the eigenvector is returned in JFAIL.
If JOBZ='N', Z is not referenced.
Note: you must ensure that at least max 1,M columns are supplied in the array Z; if RANGE='V', the exact value of M is not known in advance and an upper bound of at least N must be used.
18:   LDZ – INTEGERInput
On entry: the first dimension of the array Z as declared in the (sub)program from which F08SPF (ZHEGVX) is called.
Constraints:
  • if JOBZ='V', LDZ≥ max 1,N ;
  • otherwise LDZ≥1.
19:   WORK max 1,LWORK – COMPLEX (KIND=nag_wp) arrayWorkspace
On exit: if INFO=0, the real part of WORK 1 contains the minimum value of LWORK required for optimal performance.
20:   LWORK – INTEGERInput
On entry: the dimension of the array WORK as declared in the (sub)program from which F08SPF (ZHEGVX) is called.
If LWORK=-1, a workspace query is assumed; the routine only calculates the optimal size of the WORK array, returns this value as the first entry of the WORK array, and no error message related to LWORK is issued.
Suggested value: for optimal performance, LWORK≥nb+1×N, where nb is the optimal block size for F08FSF (ZHETRD).
Constraint: LWORK≥max 1,2×N.
21:   RWORK 7×N – REAL (KIND=nag_wp) arrayWorkspace
22:   IWORK 5×N – INTEGER arrayWorkspace
23:   JFAIL* – INTEGER arrayOutput
Note: the dimension of the array JFAIL must be at least max 1,N.
On exit: if JOBZ='V', then
  • if INFO=0, the first M elements of JFAIL are zero;
  • if INFO=1 to N, JFAIL contains the indices of the eigenvectors that failed to converge.
If JOBZ='N', JFAIL is not referenced.
24:   INFO – INTEGEROutput
On exit: INFO=0 unless the routine detects an error (see Section 6).

6 Error Indicators and Warnings

INFO<0
If INFO=-i, argument i had an illegal value. An explanatory message is output, and execution of the program is terminated.
INFO=1 to N
If INFO=i, F08FPF (ZHEEVX) failed to converge; i eigenvectors failed to converge. Their indices are stored in array JFAIL.
INFO>N
F07FRF (ZPOTRF) returned an error code; i.e., if INFO=N+i, for 1≤i≤N, then the leading minor of order i of B is not positive definite. The factorization of B could not be completed and no eigenvalues or eigenvectors were computed.

7 Accuracy

If B is ill-conditioned with respect to inversion, then the error bounds for the computed eigenvalues and vectors may be large, although when the diagonal elements of B differ widely in magnitude the eigenvalues and eigenvectors may be less sensitive than the condition of B would suggest. See Section 4.10 of Anderson et al. (1999) for details of the error bounds.

8 Parallelism and Performance

F08SPF (ZHEGVX) is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
F08SPF (ZHEGVX) makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The total number of floating-point operations is proportional to n 3.
The real analogue of this routine is F08SBF (DSYGVX).

10 Example

This example finds the eigenvalues in the half-open interval -3,3, and corresponding eigenvectors, of the generalized Hermitian eigenproblem Az=λBz, where
A = -7.36 i+0.00 0.77-0.43 i -0.64-0.92 i 3.01-6.97 i 0.77+0.43 i 3.49 i+0.00 2.19+4.45 i 1.90+3.73 i -0.64+0.92 i 2.19-4.45 i 0.12 i+0.00 2.88-3.17 i 3.01+6.97 i 1.90-3.73 i 2.88+3.17 i -2.54 i+0.00
and
B = 3.23 i+0.00 1.51-1.92 i 1.90+0.84 i 0.42+2.50 i 1.51+1.92 i 3.58 i+0.00 -0.23+1.11 i -1.18+1.37 i 1.90-0.84 i -0.23-1.11 i 4.09 i+0.00 2.33-0.14 i 0.42-2.50 i -1.18-1.37 i 2.33+0.14 i 4.29 i+0.00 .
The example program for F08SQF (ZHEGVD) illustrates solving a generalized Hermitian eigenproblem of the form ABz=λz.

10.1 Program Text

Program Text (f08spfe.f90)

10.2 Program Data

Program Data (f08spfe.d)

10.3 Program Results

Program Results (f08spfe.r)

F08 Chapter Contents
F08 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F08SQF (ZHEGVD) : NAG Library, Mark 26

F08 Chapter Contents
F08 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F08SQF (ZHEGVD)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F08SQF (ZHEGVD) computes all the eigenvalues and, optionally, the eigenvectors of a complex generalized Hermitian-definite eigenproblem, of the form
Az=λBz ,   ABz=λz   or   BAz=λz ,
where A and B are Hermitian and B is also positive definite. If eigenvectors are desired, it uses a divide-and-conquer algorithm.

2 Specification

SUBROUTINE F08SQF ( ITYPE, JOBZ, UPLO, N, A, LDA, B, LDB, W, WORK, LWORK, RWORK, LRWORK, IWORK, LIWORK, INFO)
INTEGER | ITYPE, N, LDA, LDB, LWORK, LRWORK, IWORK(max(1,LIWORK)), LIWORK, INFO
REAL (KIND=nag_wp) | W(N), RWORK(max(1,LRWORK))
COMPLEX (KIND=nag_wp) | A(LDA,*), B(LDB,*), WORK(max(1,LWORK))
CHARACTER(1) | JOBZ, UPLO
The routine may be called by its LAPACK name zhegvd.

3 Description

F08SQF (ZHEGVD) first performs a Cholesky factorization of the matrix B as B=UH U , when UPLO='U' or B=L LH , when UPLO='L'. The generalized problem is then reduced to a standard symmetric eigenvalue problem
Cx=λx ,
which is solved for the eigenvalues and, optionally, the eigenvectors; the eigenvectors are then backtransformed to give the eigenvectors of the original problem.
For the problem Az=λBz , the eigenvectors are normalized so that the matrix of eigenvectors, z, satisfies
ZH A Z = Λ   and   ZH B Z = I ,
where Λ is the diagonal matrix whose diagonal elements are the eigenvalues. For the problem A B z = λ z we correspondingly have
Z-1 A Z-H = Λ   and   ZH B Z = I ,
and for B A z = λ z we have
ZH A Z = Λ   and   ZH B-1 Z = I .

4 References

Anderson E, Bai Z, Bischof C, Blackford S, Demmel J, Dongarra J J, Du Croz J J, Greenbaum A, Hammarling S, McKenney A and Sorensen D (1999) LAPACK Users' Guide (3rd Edition) SIAM, Philadelphia http://www.netlib.org/lapack/lug
Golub G H and Van Loan C F (1996) Matrix Computations (3rd Edition) Johns Hopkins University Press, Baltimore

5 Arguments

1:   ITYPE – INTEGERInput
On entry: specifies the problem type to be solved.
ITYPE=1
Az=λBz.
ITYPE=2
ABz=λz.
ITYPE=3
BAz=λz.
Constraint: ITYPE=1, 2 or 3.
2:   JOBZ – CHARACTER(1)Input
On entry: indicates whether eigenvectors are computed.
JOBZ='N'
Only eigenvalues are computed.
JOBZ='V'
Eigenvalues and eigenvectors are computed.
Constraint: JOBZ='N' or 'V'.
3:   UPLO – CHARACTER(1)Input
On entry: if UPLO='U', the upper triangles of A and B are stored.
If UPLO='L', the lower triangles of A and B are stored.
Constraint: UPLO='U' or 'L'.
4:   N – INTEGERInput
On entry: n, the order of the matrices A and B.
Constraint: N≥0.
5:   A LDA* – COMPLEX (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array A must be at least max 1,N.
On entry: the n by n Hermitian matrix A.
  • If UPLO='U', the upper triangular part of A must be stored and the elements of the array below the diagonal are not referenced.
  • If UPLO='L', the lower triangular part of A must be stored and the elements of the array above the diagonal are not referenced.
On exit: if JOBZ='V', A contains the matrix Z of eigenvectors. The eigenvectors are normalized as follows:
  • if ITYPE=1 or 2, ZH BZ=I;
  • if ITYPE=3, ZHB-1 Z=I.
If JOBZ='N', the upper triangle (if UPLO='U') or the lower triangle (if UPLO='L') of A, including the diagonal, is overwritten.
6:   LDA – INTEGERInput
On entry: the first dimension of the array A as declared in the (sub)program from which F08SQF (ZHEGVD) is called.
Constraint: LDA≥max 1,N.
7:   B LDB* – COMPLEX (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array B must be at least max 1,N.
On entry: the n by n Hermitian matrix B.
  • If UPLO='U', the upper triangular part of B must be stored and the elements of the array below the diagonal are not referenced.
  • If UPLO='L', the lower triangular part of B must be stored and the elements of the array above the diagonal are not referenced.
On exit: the triangular factor U or L from the Cholesky factorization B=UH U or B=L LH.
8:   LDB – INTEGERInput
On entry: the first dimension of the array B as declared in the (sub)program from which F08SQF (ZHEGVD) is called.
Constraint: LDB≥max 1,N.
9:   W N – REAL (KIND=nag_wp) arrayOutput
On exit: the eigenvalues in ascending order.
10:   WORK max 1,LWORK – COMPLEX (KIND=nag_wp) arrayWorkspace
On exit: if INFO=0, the real part of WORK 1 contains the minimum value of LWORK required for optimal performance.
11:   LWORK – INTEGERInput
On entry: the dimension of the array WORK as declared in the (sub)program from which F08SQF (ZHEGVD) is called.
If LWORK=-1, a workspace query is assumed; the routine only calculates the optimal sizes of the WORK, RWORK and IWORK arrays, returns these values as the first entries of the WORK, RWORK and IWORK arrays, and no error message related to LWORK, LRWORK or LIWORK is issued.
Suggested value: for optimal performance, LWORK should usually be larger than the minimum, try increasing by nb×N, where nb is the optimal block size.
Constraints:
  • if N≤1, LWORK≥1;
  • if JOBZ='N' and N>1, LWORK≥N+1;
  • if JOBZ='V' and N>1, LWORK≥2×N+N 2.
12:   RWORK max 1,LRWORK – REAL (KIND=nag_wp) arrayWorkspace
On exit: if INFO=0, RWORK 1 returns the optimal LRWORK.
13:   LRWORK – INTEGERInput
On entry: the dimension of the array RWORK as declared in the (sub)program from which F08SQF (ZHEGVD) is called.
If LRWORK=-1, a workspace query is assumed; the routine only calculates the optimal sizes of the WORK, RWORK and IWORK arrays, returns these values as the first entries of the WORK, RWORK and IWORK arrays, and no error message related to LWORK, LRWORK or LIWORK is issued.
Constraints:
  • if N≤1, LRWORK≥1;
  • if JOBZ='N' and N>1, LRWORK≥N;
  • if JOBZ='V' and N>1, LRWORK≥1+5×N+2×N 2.
14:   IWORK max 1,LIWORK – INTEGER arrayWorkspace
On exit: if INFO=0, IWORK 1 returns the optimal LIWORK.
15:   LIWORK – INTEGERInput
On entry: the dimension of the array IWORK as declared in the (sub)program from which F08SQF (ZHEGVD) is called.
If LIWORK=-1, a workspace query is assumed; the routine only calculates the optimal sizes of the WORK, RWORK and IWORK arrays, returns these values as the first entries of the WORK, RWORK and IWORK arrays, and no error message related to LWORK, LRWORK or LIWORK is issued.
Constraints:
  • if N≤1, LIWORK≥1;
  • if JOBZ='N' and N>1, LIWORK≥1;
  • if JOBZ='V' and N>1, LIWORK≥3+5×N.
16:   INFO – INTEGEROutput
On exit: INFO=0 unless the routine detects an error (see Section 6).

6 Error Indicators and Warnings

INFO<0
If INFO=-i, argument i had an illegal value. An explanatory message is output, and execution of the program is terminated.
INFO=1 to N
If INFO=i, F08FQF (ZHEEVD) failed to converge; i i off-diagonal elements of an intermediate tridiagonal form did not converge to zero.
INFO>N
F07FRF (ZPOTRF) returned an error code; i.e., if INFO=N+i, for 1≤i≤N, then the leading minor of order i of B is not positive definite. The factorization of B could not be completed and no eigenvalues or eigenvectors were computed.

7 Accuracy

If B is ill-conditioned with respect to inversion, then the error bounds for the computed eigenvalues and vectors may be large, although when the diagonal elements of B differ widely in magnitude the eigenvalues and eigenvectors may be less sensitive than the condition of B would suggest. See Section 4.10 of Anderson et al. (1999) for details of the error bounds.
The example program below illustrates the computation of approximate error bounds.

8 Parallelism and Performance

F08SQF (ZHEGVD) is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
F08SQF (ZHEGVD) makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The total number of floating-point operations is proportional to n 3 .
The real analogue of this routine is F08SCF (DSYGVD).

10 Example

This example finds all the eigenvalues and eigenvectors of the generalized Hermitian eigenproblem ABz=λz , where
A = -7.36 i+0.00 0.77-0.43 i -0.64-0.92 i 3.01-6.97 i 0.77+0.43 i 3.49 i+0.00 2.19+4.45 i 1.90+3.73 i -0.64+0.92 i 2.19-4.45 i 0.12 i+0.00 2.88-3.17 i 3.01+6.97 i 1.90-3.73 i 2.88+3.17 i -2.54 i+0.00
and
B = 3.23 i+0.00 1.51-1.92 i 1.90+0.84 i 0.42+2.50 i 1.51+1.92 i 3.58 i+0.00 -0.23+1.11 i -1.18+1.37 i 1.90-0.84 i -0.23-1.11 i 4.09 i+0.00 2.33-0.14 i 0.42-2.50 i -1.18-1.37 i 2.33+0.14 i 4.29 i+0.00 ,
together with an estimate of the condition number of B, and approximate error bounds for the computed eigenvalues and eigenvectors.
The example program for F08SNF (ZHEGV) illustrates solving a generalized Hermitian eigenproblem of the form Az=λBz .

10.1 Program Text

Program Text (f08sqfe.f90)

10.2 Program Data

Program Data (f08sqfe.d)

10.3 Program Results

Program Results (f08sqfe.r)

F08 Chapter Contents
F08 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F08SSF (ZHEGST) : NAG Library, Mark 26

F08 Chapter Contents
F08 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F08SSF (ZHEGST)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F08SSF (ZHEGST) reduces a complex Hermitian-definite generalized eigenproblem Az=λBz, ABz=λz or BAz=λz to the standard form Cy=λy, where A is a complex Hermitian matrix and B has been factorized by F07FRF (ZPOTRF).

2 Specification

SUBROUTINE F08SSF ( ITYPE, UPLO, N, A, LDA, B, LDB, INFO)
INTEGER | ITYPE, N, LDA, LDB, INFO
COMPLEX (KIND=nag_wp) | A(LDA,*), B(LDB,*)
CHARACTER(1) | UPLO
The routine may be called by its LAPACK name zhegst.

3 Description

To reduce the complex Hermitian-definite generalized eigenproblem Az=λBz, ABz=λz or BAz=λz to the standard form Cy=λy, F08SSF (ZHEGST) must be preceded by a call to F07FRF (ZPOTRF) which computes the Cholesky factorization of B; B must be positive definite.
The different problem types are specified by the argument ITYPE, as indicated in the table below. The table shows how C is computed by the routine, and also how the eigenvectors z of the original problem can be recovered from the eigenvectors of the standard form.
ITYPE | Problem | UPLO | B | C | z
1 | Az=λBz | 'U' 'L' | UH U L LH | U-H A U-1 L-1 A L-H | U-1 y L-H y
2 | ABz=λz | 'U' 'L' | UH U L LH | UA UH LH AL | U-1 y L-H y
3 | BAz=λz | 'U' 'L' | UH U L LH | UA UH LH AL | UH y Ly

4 References

Golub G H and Van Loan C F (1996) Matrix Computations (3rd Edition) Johns Hopkins University Press, Baltimore

5 Arguments

1:   ITYPE – INTEGERInput
On entry: indicates how the standard form is computed.
ITYPE=1
  • if UPLO='U', C=U-H A U-1;
  • if UPLO='L', C=L-1 A L-H.
ITYPE=2 or 3
  • if UPLO='U', C=UA UH;
  • if UPLO='L', C=LH AL.
Constraint: ITYPE=1, 2 or 3.
2:   UPLO – CHARACTER(1)Input
On entry: indicates whether the upper or lower triangular part of A is stored and how B has been factorized.
UPLO='U'
The upper triangular part of A is stored and B=UH U.
UPLO='L'
The lower triangular part of A is stored and B=L LH.
Constraint: UPLO='U' or 'L'.
3:   N – INTEGERInput
On entry: n, the order of the matrices A and B.
Constraint: N≥0.
4:   A LDA* – COMPLEX (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array A must be at least max 1,N.
On entry: the n by n Hermitian matrix A.
  • If UPLO='U', the upper triangular part of A must be stored and the elements of the array below the diagonal are not referenced.
  • If UPLO='L', the lower triangular part of A must be stored and the elements of the array above the diagonal are not referenced.
On exit: the upper or lower triangle of A is overwritten by the corresponding upper or lower triangle of C as specified by ITYPE and UPLO.
5:   LDA – INTEGERInput
On entry: the first dimension of the array A as declared in the (sub)program from which F08SSF (ZHEGST) is called.
Constraint: LDA≥max 1,N.
6:   B LDB* – COMPLEX (KIND=nag_wp) arrayInput
Note: the second dimension of the array B must be at least max 1,N.
On entry: the Cholesky factor of B as specified by UPLO and returned by F07FRF (ZPOTRF).
7:   LDB – INTEGERInput
On entry: the first dimension of the array B as declared in the (sub)program from which F08SSF (ZHEGST) is called.
Constraint: LDB≥max 1,N.
8:   INFO – INTEGEROutput
On exit: INFO=0 unless the routine detects an error (see Section 6).

6 Error Indicators and Warnings

INFO<0
If INFO=-i, argument i had an illegal value. An explanatory message is output, and execution of the program is terminated.

7 Accuracy

Forming the reduced matrix C is a stable procedure. However it involves implicit multiplication by B-1 (if ITYPE=1) or B (if ITYPE=2 or 3). When F08SSF (ZHEGST) is used as a step in the computation of eigenvalues and eigenvectors of the original problem, there may be a significant loss of accuracy if B is ill-conditioned with respect to inversion. See the document for F08SNF (ZHEGV) for further details.

8 Parallelism and Performance

F08SSF (ZHEGST) makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The total number of real floating-point operations is approximately 4 n 3.
The real analogue of this routine is F08SEF (DSYGST).

10 Example

This example computes all the eigenvalues of Az=λBz, where
A = -7.36+0.00 i 0.77-0.43 i -0.64-0.92 i 3.01-6.97 i 0.77+0.43 i 3.49+0.00 i 2.19+4.45 i 1.90+3.73 i -0.64+0.92 i 2.19-4.45 i 0.12+0.00 i 2.88-3.17 i 3.01+6.97 i 1.90-3.73 i 2.88+3.17 i -2.54+0.00 i
and
B = 3.23+0.00 i 1.51-1.92 i 1.90+0.84 i 0.42+2.50 i 1.51+1.92 i 3.58+0.00 i -0.23+1.11 i -1.18+1.37 i 1.90-0.84 i -0.23-1.11 i 4.09+0.00 i 2.33-0.14 i 0.42-2.50 i -1.18-1.37 i 2.33+0.14 i 4.29+0.00 i .
Here B is Hermitian positive definite and must first be factorized by F07FRF (ZPOTRF). The program calls F08SSF (ZHEGST) to reduce the problem to the standard form Cy=λy; then F08FSF (ZHETRD) to reduce C to tridiagonal form, and F08JFF (DSTERF) to compute the eigenvalues.

10.1 Program Text

Program Text (f08ssfe.f90)

10.2 Program Data

Program Data (f08ssfe.d)

10.3 Program Results

Program Results (f08ssfe.r)

F08 Chapter Contents
F08 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F08TAF (DSPGV) : NAG Library, Mark 26

F08 Chapter Contents
F08 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F08TAF (DSPGV)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F08TAF (DSPGV) computes all the eigenvalues and, optionally, all the eigenvectors of a real generalized symmetric-definite eigenproblem, of the form
Az=λBz ,   ABz=λz   or   BAz=λz ,
where A and B are symmetric, stored in packed format, and B is also positive definite.

2 Specification

SUBROUTINE F08TAF ( ITYPE, JOBZ, UPLO, N, AP, BP, W, Z, LDZ, WORK, INFO)
INTEGER | ITYPE, N, LDZ, INFO
REAL (KIND=nag_wp) | AP(*), BP(*), W(N), Z(LDZ,*), WORK(3*N)
CHARACTER(1) | JOBZ, UPLO
The routine may be called by its LAPACK name dspgv.

3 Description

F08TAF (DSPGV) first performs a Cholesky factorization of the matrix B as B=UT U , when UPLO='U' or B=L LT , when UPLO='L'. The generalized problem is then reduced to a standard symmetric eigenvalue problem
Cx=λx ,
which is solved for the eigenvalues and, optionally, the eigenvectors; the eigenvectors are then backtransformed to give the eigenvectors of the original problem.
For the problem Az=λBz , the eigenvectors are normalized so that the matrix of eigenvectors, Z, satisfies
ZT A Z = Λ   and   ZT B Z = I ,
where Λ is the diagonal matrix whose diagonal elements are the eigenvalues. For the problem A B z = λ z we correspondingly have
Z-1 A Z-T = Λ   and   ZT B Z = I ,
and for B A z = λ z we have
ZT A Z = Λ   and   ZT B-1 Z = I .

4 References

Anderson E, Bai Z, Bischof C, Blackford S, Demmel J, Dongarra J J, Du Croz J J, Greenbaum A, Hammarling S, McKenney A and Sorensen D (1999) LAPACK Users' Guide (3rd Edition) SIAM, Philadelphia http://www.netlib.org/lapack/lug
Golub G H and Van Loan C F (1996) Matrix Computations (3rd Edition) Johns Hopkins University Press, Baltimore

5 Arguments

1:   ITYPE – INTEGERInput
On entry: specifies the problem type to be solved.
ITYPE=1
Az=λBz.
ITYPE=2
ABz=λz.
ITYPE=3
BAz=λz.
Constraint: ITYPE=1, 2 or 3.
2:   JOBZ – CHARACTER(1)Input
On entry: indicates whether eigenvectors are computed.
JOBZ='N'
Only eigenvalues are computed.
JOBZ='V'
Eigenvalues and eigenvectors are computed.
Constraint: JOBZ='N' or 'V'.
3:   UPLO – CHARACTER(1)Input
On entry: if UPLO='U', the upper triangles of A and B are stored.
If UPLO='L', the lower triangles of A and B are stored.
Constraint: UPLO='U' or 'L'.
4:   N – INTEGERInput
On entry: n, the order of the matrices A and B.
Constraint: N≥0.
5:   AP* – REAL (KIND=nag_wp) arrayInput/Output
Note: the dimension of the array AP must be at least max 1,N×N+1/2.
On entry: the upper or lower triangle of the n by n symmetric matrix A, packed by columns.
More precisely,
  • if UPLO='U', the upper triangle of A must be stored with element A ij in AP i+j j-1/2 for i≤j;
  • if UPLO='L', the lower triangle of A must be stored with element A ij in AP i+2 n-jj-1/2 for i≥j.
On exit: the contents of AP are destroyed.
6:   BP* – REAL (KIND=nag_wp) arrayInput/Output
Note: the dimension of the array BP must be at least max 1,N×N+1/2.
On entry: the upper or lower triangle of the n by n symmetric matrix B, packed by columns.
More precisely,
  • if UPLO='U', the upper triangle of B must be stored with element B ij in BP i+j j-1/2 for i≤j;
  • if UPLO='L', the lower triangle of B must be stored with element B ij in BP i+2 n-jj-1/2 for i≥j.
On exit: the triangular factor U or L from the Cholesky factorization B=UT U or B=L LT, in the same storage format as B.
7:   W N – REAL (KIND=nag_wp) arrayOutput
On exit: the eigenvalues in ascending order.
8:   Z LDZ* – REAL (KIND=nag_wp) arrayOutput
Note: the second dimension of the array Z must be at least max 1,N if JOBZ='V', and at least 1 otherwise.
On exit: if JOBZ='V', Z contains the matrix Z of eigenvectors. The eigenvectors are normalized as follows:
  • if ITYPE=1 or 2, ZT BZ=I;
  • if ITYPE=3, ZTB-1 Z=I.
If JOBZ='N', Z is not referenced.
9:   LDZ – INTEGERInput
On entry: the first dimension of the array Z as declared in the (sub)program from which F08TAF (DSPGV) is called.
Constraints:
  • if JOBZ='V', LDZ≥ max 1,N ;
  • otherwise LDZ≥1.
10:   WORK 3×N – REAL (KIND=nag_wp) arrayWorkspace
11:   INFO – INTEGEROutput
On exit: INFO=0 unless the routine detects an error (see Section 6).

6 Error Indicators and Warnings

INFO<0
If INFO=-i, argument i had an illegal value. An explanatory message is output, and execution of the program is terminated.
INFO>0
F07GDF (DPPTRF) or F08GAF (DSPEV) returned an error code:
≤N | if INFO=i, F08GAF (DSPEV) failed to converge; i off-diagonal elements of an intermediate tridiagonal form did not converge to zero;
>N | if INFO=N+i, for 1≤i≤N, then the leading minor of order i of B is not positive definite. The factorization of B could not be completed and no eigenvalues or eigenvectors were computed.

7 Accuracy

If B is ill-conditioned with respect to inversion, then the error bounds for the computed eigenvalues and vectors may be large, although when the diagonal elements of B differ widely in magnitude the eigenvalues and eigenvectors may be less sensitive than the condition of B would suggest. See Section 4.10 of Anderson et al. (1999) for details of the error bounds.
The example program below illustrates the computation of approximate error bounds.

8 Parallelism and Performance

F08TAF (DSPGV) is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
F08TAF (DSPGV) makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The total number of floating-point operations is proportional to n 3 .
The complex analogue of this routine is F08TNF (ZHPGV).

10 Example

This example finds all the eigenvalues and eigenvectors of the generalized symmetric eigenproblem Az = λ Bz , where
A = 0.24 0.39 0.42 -0.16 0.39 -0.11 0.79 0.63 0.42 0.79 -0.25 0.48 -0.16 0.63 0.48 -0.03   and   B = 4.16 -3.12 0.56 -0.10 -3.12 5.03 -0.83 1.09 0.56 -0.83 0.76 0.34 -0.10 1.09 0.34 1.18 ,
together with an estimate of the condition number of B, and approximate error bounds for the computed eigenvalues and eigenvectors.
The example program for F08TCF (DSPGVD) illustrates solving a generalized symmetric eigenproblem of the form ABz=λz .

10.1 Program Text

Program Text (f08tafe.f90)

10.2 Program Data

Program Data (f08tafe.d)

10.3 Program Results

Program Results (f08tafe.r)

F08 Chapter Contents
F08 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F08TBF (DSPGVX) : NAG Library, Mark 26

F08 Chapter Contents
F08 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F08TBF (DSPGVX)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F08TBF (DSPGVX) computes selected eigenvalues and, optionally, eigenvectors of a real generalized symmetric-definite eigenproblem, of the form
Az=λBz ,   ABz=λz   or   BAz=λz ,
where A and B are symmetric, stored in packed storage, and B is also positive definite. Eigenvalues and eigenvectors can be selected by specifying either a range of values or a range of indices for the desired eigenvalues.

2 Specification

SUBROUTINE F08TBF ( ITYPE, JOBZ, RANGE, UPLO, N, AP, BP, VL, VU, IL, IU, ABSTOL, M, W, Z, LDZ, WORK, IWORK, JFAIL, INFO)
INTEGER | ITYPE, N, IL, IU, M, LDZ, IWORK(5*N), JFAIL(*), INFO
REAL (KIND=nag_wp) | AP(*), BP(*), VL, VU, ABSTOL, W(N), Z(LDZ,*), WORK(8*N)
CHARACTER(1) | JOBZ, RANGE, UPLO
The routine may be called by its LAPACK name dspgvx.

3 Description

F08TBF (DSPGVX) first performs a Cholesky factorization of the matrix B as B=UT U , when UPLO='U' or B=L LT , when UPLO='L'. The generalized problem is then reduced to a standard symmetric eigenvalue problem
Cx=λx ,
which is solved for the desired eigenvalues and eigenvectors; the eigenvectors are then backtransformed to give the eigenvectors of the original problem.
For the problem Az=λBz , the eigenvectors are normalized so that the matrix of eigenvectors, Z, satisfies
ZT A Z = Λ   and   ZT B Z = I ,
where Λ is the diagonal matrix whose diagonal elements are the eigenvalues. For the problem A B z = λ z we correspondingly have
Z-1 A Z-T = Λ   and   ZT B Z = I ,
and for B A z = λ z we have
ZT A Z = Λ   and   ZT B-1 Z = I .

4 References

Anderson E, Bai Z, Bischof C, Blackford S, Demmel J, Dongarra J J, Du Croz J J, Greenbaum A, Hammarling S, McKenney A and Sorensen D (1999) LAPACK Users' Guide (3rd Edition) SIAM, Philadelphia http://www.netlib.org/lapack/lug
Demmel J W and Kahan W (1990) Accurate singular values of bidiagonal matrices SIAM J. Sci. Statist. Comput. 11 873–912
Golub G H and Van Loan C F (1996) Matrix Computations (3rd Edition) Johns Hopkins University Press, Baltimore

5 Arguments

1:   ITYPE – INTEGERInput
On entry: specifies the problem type to be solved.
ITYPE=1
Az=λBz.
ITYPE=2
ABz=λz.
ITYPE=3
BAz=λz.
Constraint: ITYPE=1, 2 or 3.
2:   JOBZ – CHARACTER(1)Input
On entry: indicates whether eigenvectors are computed.
JOBZ='N'
Only eigenvalues are computed.
JOBZ='V'
Eigenvalues and eigenvectors are computed.
Constraint: JOBZ='N' or 'V'.
3:   RANGE – CHARACTER(1)Input
On entry: if RANGE='A', all eigenvalues will be found.
If RANGE='V', all eigenvalues in the half-open interval VL,VU will be found.
If RANGE='I', the ILth to IUth eigenvalues will be found.
Constraint: RANGE='A', 'V' or 'I'.
4:   UPLO – CHARACTER(1)Input
On entry: if UPLO='U', the upper triangles of A and B are stored.
If UPLO='L', the lower triangles of A and B are stored.
Constraint: UPLO='U' or 'L'.
5:   N – INTEGERInput
On entry: n, the order of the matrices A and B.
Constraint: N≥0.
6:   AP* – REAL (KIND=nag_wp) arrayInput/Output
Note: the dimension of the array AP must be at least max 1,N×N+1/2.
On entry: the upper or lower triangle of the n by n symmetric matrix A, packed by columns.
More precisely,
  • if UPLO='U', the upper triangle of A must be stored with element A ij in AP i+j j-1/2 for i≤j;
  • if UPLO='L', the lower triangle of A must be stored with element A ij in AP i+2 n-jj-1/2 for i≥j.
On exit: the contents of AP are destroyed.
7:   BP* – REAL (KIND=nag_wp) arrayInput/Output
Note: the dimension of the array BP must be at least max 1,N×N+1/2.
On entry: the upper or lower triangle of the n by n symmetric matrix B, packed by columns.
More precisely,
  • if UPLO='U', the upper triangle of B must be stored with element B ij in BP i+j j-1/2 for i≤j;
  • if UPLO='L', the lower triangle of B must be stored with element B ij in BP i+2 n-jj-1/2 for i≥j.
On exit: the triangular factor U or L from the Cholesky factorization B=UT U or B=L LT, in the same storage format as B.
8:   VL – REAL (KIND=nag_wp)Input
9:   VU – REAL (KIND=nag_wp)Input
On entry: if RANGE='V', the lower and upper bounds of the interval to be searched for eigenvalues.
If RANGE='A' or 'I', VL and VU are not referenced.
Constraint: if RANGE='V', VL<VU.
10:   IL – INTEGERInput
11:   IU – INTEGERInput
On entry: if RANGE='I', the indices (in ascending order) of the smallest and largest eigenvalues to be returned.
If RANGE='A' or 'V', IL and IU are not referenced.
Constraints:
  • if RANGE='I' and N=0, IL=1 and IU=0;
  • if RANGE='I' and N>0, 1≤ IL≤ IU≤ N .
12:   ABSTOL – REAL (KIND=nag_wp)Input
On entry: the absolute error tolerance for the eigenvalues. An approximate eigenvalue is accepted as converged when it is determined to lie in an interval a,b of width less than or equal to
ABSTOL+ε max a,b ,
where ε is the machine precision. If ABSTOL is less than or equal to zero, then ε T 1 will be used in its place, where T is the tridiagonal matrix obtained by reducing C to tridiagonal form. Eigenvalues will be computed most accurately when ABSTOL is set to twice the underflow threshold 2 × X02AMF , not zero. If this routine returns with INFO=1 to N, indicating that some eigenvectors did not converge, try setting ABSTOL to 2 × X02AMF . See Demmel and Kahan (1990).
13:   M – INTEGEROutput
On exit: the total number of eigenvalues found. 0≤M≤N.
If RANGE='A', M=N.
If RANGE='I', M=IU-IL+1.
14:   W N – REAL (KIND=nag_wp) arrayOutput
On exit: the first M elements contain the selected eigenvalues in ascending order.
15:   Z LDZ* – REAL (KIND=nag_wp) arrayOutput
Note: the second dimension of the array Z must be at least max 1,M if JOBZ='V', and at least 1 otherwise.
On exit: if JOBZ='V', then
  • if INFO=0, the first M columns of Z contain the orthonormal eigenvectors of the matrix A corresponding to the selected eigenvalues, with the ith column of Z holding the eigenvector associated with W i. The eigenvectors are normalized as follows:
    • if ITYPE=1 or 2, ZT BZ=I;
    • if ITYPE=3, ZTB-1 Z=I;
  • if an eigenvector fails to converge (INFO=1 to N), then that column of Z contains the latest approximation to the eigenvector, and the index of the eigenvector is returned in JFAIL.
If JOBZ='N', Z is not referenced.
Note: you must ensure that at least max 1,M columns are supplied in the array Z; if RANGE='V', the exact value of M is not known in advance and an upper bound of at least N must be used.
16:   LDZ – INTEGERInput
On entry: the first dimension of the array Z as declared in the (sub)program from which F08TBF (DSPGVX) is called.
Constraints:
  • if JOBZ='V', LDZ≥ max 1,N ;
  • otherwise LDZ≥1.
17:   WORK 8×N – REAL (KIND=nag_wp) arrayWorkspace
18:   IWORK 5×N – INTEGER arrayWorkspace
19:   JFAIL* – INTEGER arrayOutput
Note: the dimension of the array JFAIL must be at least max 1,N.
On exit: if JOBZ='V', then
  • if INFO=0, the first M elements of JFAIL are zero;
  • if INFO=1 to N, JFAIL contains the indices of the eigenvectors that failed to converge.
If JOBZ='N', JFAIL is not referenced.
20:   INFO – INTEGEROutput
On exit: INFO=0 unless the routine detects an error (see Section 6).

6 Error Indicators and Warnings

INFO<0
If INFO=-i, argument i had an illegal value. An explanatory message is output, and execution of the program is terminated.
INFO=1 to N
If INFO=i, F08GBF (DSPEVX) failed to converge; i eigenvectors failed to converge. Their indices are stored in array JFAIL.
INFO>N
F07GDF (DPPTRF) returned an error code; i.e., if INFO=N+i, for 1≤i≤N, then the leading minor of order i of B is not positive definite. The factorization of B could not be completed and no eigenvalues or eigenvectors were computed.

7 Accuracy

If B is ill-conditioned with respect to inversion, then the error bounds for the computed eigenvalues and vectors may be large, although when the diagonal elements of B differ widely in magnitude the eigenvalues and eigenvectors may be less sensitive than the condition of B would suggest. See Section 4.10 of Anderson et al. (1999) for details of the error bounds.

8 Parallelism and Performance

F08TBF (DSPGVX) is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
F08TBF (DSPGVX) makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The total number of floating-point operations is proportional to n 3 .
The complex analogue of this routine is F08TPF (ZHPGVX).

10 Example

This example finds the eigenvalues in the half-open interval -1.0,1.0 , and corresponding eigenvectors, of the generalized symmetric eigenproblem Az = λ Bz , where
A = 0.24 0.39 0.42 -0.16 0.39 -0.11 0.79 0.63 0.42 0.79 -0.25 0.48 -0.16 0.63 0.48 -0.03   and   B = 4.16 -3.12 0.56 -0.10 -3.12 5.03 -0.83 1.09 0.56 -0.83 0.76 0.34 -0.10 1.09 0.34 1.18 .
The example program for F08TCF (DSPGVD) illustrates solving a generalized symmetric eigenproblem of the form ABz=λz .

10.1 Program Text

Program Text (f08tbfe.f90)

10.2 Program Data

Program Data (f08tbfe.d)

10.3 Program Results

Program Results (f08tbfe.r)

F08 Chapter Contents
F08 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F08TCF (DSPGVD) : NAG Library, Mark 26

F08 Chapter Contents
F08 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F08TCF (DSPGVD)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F08TCF (DSPGVD) computes all the eigenvalues and, optionally, the eigenvectors of a real generalized symmetric-definite eigenproblem, of the form
Az=λBz ,   ABz=λz   or   BAz=λz ,
where A and B are symmetric, stored in packed format, and B is also positive definite. If eigenvectors are desired, it uses a divide-and-conquer algorithm.

2 Specification

SUBROUTINE F08TCF ( ITYPE, JOBZ, UPLO, N, AP, BP, W, Z, LDZ, WORK, LWORK, IWORK, LIWORK, INFO)
INTEGER | ITYPE, N, LDZ, LWORK, IWORK(max(1,LIWORK)), LIWORK, INFO
REAL (KIND=nag_wp) | AP(*), BP(*), W(N), Z(LDZ,*), WORK(max(1,LWORK))
CHARACTER(1) | JOBZ, UPLO
The routine may be called by its LAPACK name dspgvd.

3 Description

F08TCF (DSPGVD) first performs a Cholesky factorization of the matrix B as B=UT U , when UPLO='U' or B=L LT , when UPLO='L'. The generalized problem is then reduced to a standard symmetric eigenvalue problem
Cx=λx ,
which is solved for the eigenvalues and, optionally, the eigenvectors; the eigenvectors are then backtransformed to give the eigenvectors of the original problem.
For the problem Az=λBz , the eigenvectors are normalized so that the matrix of eigenvectors, z, satisfies
ZT A Z = Λ   and   ZT B Z = I ,
where Λ is the diagonal matrix whose diagonal elements are the eigenvalues. For the problem A B z = λ z we correspondingly have
Z-1 A Z-T = Λ   and   ZT B Z = I ,
and for B A z = λ z we have
ZT A Z = Λ   and   ZT B-1 Z = I .

4 References

Anderson E, Bai Z, Bischof C, Blackford S, Demmel J, Dongarra J J, Du Croz J J, Greenbaum A, Hammarling S, McKenney A and Sorensen D (1999) LAPACK Users' Guide (3rd Edition) SIAM, Philadelphia http://www.netlib.org/lapack/lug
Golub G H and Van Loan C F (1996) Matrix Computations (3rd Edition) Johns Hopkins University Press, Baltimore

5 Arguments

1:   ITYPE – INTEGERInput
On entry: specifies the problem type to be solved.
ITYPE=1
Az=λBz.
ITYPE=2
ABz=λz.
ITYPE=3
BAz=λz.
Constraint: ITYPE=1, 2 or 3.
2:   JOBZ – CHARACTER(1)Input
On entry: indicates whether eigenvectors are computed.
JOBZ='N'
Only eigenvalues are computed.
JOBZ='V'
Eigenvalues and eigenvectors are computed.
Constraint: JOBZ='N' or 'V'.
3:   UPLO – CHARACTER(1)Input
On entry: if UPLO='U', the upper triangles of A and B are stored.
If UPLO='L', the lower triangles of A and B are stored.
Constraint: UPLO='U' or 'L'.
4:   N – INTEGERInput
On entry: n, the order of the matrices A and B.
Constraint: N≥0.
5:   AP* – REAL (KIND=nag_wp) arrayInput/Output
Note: the dimension of the array AP must be at least max 1,N×N+1/2.
On entry: the upper or lower triangle of the n by n symmetric matrix A, packed by columns.
More precisely,
  • if UPLO='U', the upper triangle of A must be stored with element A ij in AP i+j j-1/2 for i≤j;
  • if UPLO='L', the lower triangle of A must be stored with element A ij in AP i+2 n-jj-1/2 for i≥j.
On exit: the contents of AP are destroyed.
6:   BP* – REAL (KIND=nag_wp) arrayInput/Output
Note: the dimension of the array BP must be at least max 1,N×N+1/2.
On entry: the upper or lower triangle of the n by n symmetric matrix B, packed by columns.
More precisely,
  • if UPLO='U', the upper triangle of B must be stored with element B ij in BP i+j j-1/2 for i≤j;
  • if UPLO='L', the lower triangle of B must be stored with element B ij in BP i+2 n-jj-1/2 for i≥j.
On exit: the triangular factor U or L from the Cholesky factorization B=UT U or B=L LT, in the same storage format as B.
7:   W N – REAL (KIND=nag_wp) arrayOutput
On exit: the eigenvalues in ascending order.
8:   Z LDZ* – REAL (KIND=nag_wp) arrayOutput
Note: the second dimension of the array Z must be at least max 1,N if JOBZ='V', and at least 1 otherwise.
On exit: if JOBZ='V', Z contains the matrix Z of eigenvectors. The eigenvectors are normalized as follows:
  • if ITYPE=1 or 2, ZT BZ=I;
  • if ITYPE=3, ZTB-1 Z=I.
If JOBZ='N', Z is not referenced.
9:   LDZ – INTEGERInput
On entry: the first dimension of the array Z as declared in the (sub)program from which F08TCF (DSPGVD) is called.
Constraints:
  • if JOBZ='V', LDZ≥max 1,N;
  • otherwise LDZ≥1.
10:   WORK max 1,LWORK – REAL (KIND=nag_wp) arrayWorkspace
On exit: if INFO=0, WORK 1 contains the minimum value of LWORK required for optimal performance.
11:   LWORK – INTEGERInput
On entry: the dimension of the array WORK as declared in the (sub)program from which F08TCF (DSPGVD) is called.
If LWORK=-1, a workspace query is assumed; the routine only calculates the minimum sizes of the WORK and IWORK arrays, returns these values as the first entries of the WORK and IWORK arrays, and no error message related to LWORK or LIWORK is issued.
Constraints:
  • if N≤1, LWORK≥1;
  • if JOBZ='N' and N>1, LWORK≥2×N;
  • if JOBZ='V' and N>1, LWORK≥1+6×N+2×N 2.
12:   IWORK max 1,LIWORK – INTEGER arrayWorkspace
On exit: if INFO=0, IWORK 1 returns the minimum LIWORK.
13:   LIWORK – INTEGERInput
On entry: the dimension of the array IWORK as declared in the (sub)program from which F08TCF (DSPGVD) is called.
If LIWORK=-1, a workspace query is assumed; the routine only calculates the minimum sizes of the WORK and IWORK arrays, returns these values as the first entries of the WORK and IWORK arrays, and no error message related to LWORK or LIWORK is issued.
Constraints:
  • if JOBZ='N' or N≤1, LIWORK≥1;
  • if JOBZ='V' and N>1, LIWORK≥3+5×N.
14:   INFO – INTEGEROutput
On exit: INFO=0 unless the routine detects an error (see Section 6).

6 Error Indicators and Warnings

INFO<0
If INFO=-i, argument i had an illegal value. An explanatory message is output, and execution of the program is terminated.
INFO>0
F07GDF (DPPTRF) or F08GCF (DSPEVD) returned an error code:
≤N | if INFO=i, F08GCF (DSPEVD) failed to converge; i off-diagonal elements of an intermediate tridiagonal form did not converge to zero;
>N | if INFO=N+i, for 1≤i≤N, then the leading minor of order i of B is not positive definite. The factorization of B could not be completed and no eigenvalues or eigenvectors were computed.

7 Accuracy

If B is ill-conditioned with respect to inversion, then the error bounds for the computed eigenvalues and vectors may be large, although when the diagonal elements of B differ widely in magnitude the eigenvalues and eigenvectors may be less sensitive than the condition of B would suggest. See Section 4.10 of Anderson et al. (1999) for details of the error bounds.
The example program below illustrates the computation of approximate error bounds.

8 Parallelism and Performance

F08TCF (DSPGVD) is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
F08TCF (DSPGVD) makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The total number of floating-point operations is proportional to n 3 .
The complex analogue of this routine is F08TQF (ZHPGVD).

10 Example

This example finds all the eigenvalues and eigenvectors of the generalized symmetric eigenproblem ABz=λz , where
A = 0.24 0.39 0.42 -0.16 0.39 -0.11 0.79 0.63 0.42 0.79 -0.25 0.48 -0.16 0.63 0.48 -0.03   and   B = 4.16 -3.12 0.56 -0.10 -3.12 5.03 -0.83 1.09 0.56 -0.83 0.76 0.34 -0.10 1.09 0.34 1.18 ,
together with an estimate of the condition number of B, and approximate error bounds for the computed eigenvalues and eigenvectors.
The example program for F08TAF (DSPGV) illustrates solving a generalized symmetric eigenproblem of the form Az = λ Bz .

10.1 Program Text

Program Text (f08tcfe.f90)

10.2 Program Data

Program Data (f08tcfe.d)

10.3 Program Results

Program Results (f08tcfe.r)

F08 Chapter Contents
F08 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F08TEF (DSPGST) : NAG Library, Mark 26

F08 Chapter Contents
F08 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F08TEF (DSPGST)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F08TEF (DSPGST) reduces a real symmetric-definite generalized eigenproblem Az=λBz, ABz=λz or BAz=λz to the standard form Cy=λy, where A is a real symmetric matrix and B has been factorized by F07GDF (DPPTRF), using packed storage.

2 Specification

SUBROUTINE F08TEF ( ITYPE, UPLO, N, AP, BP, INFO)
INTEGER | ITYPE, N, INFO
REAL (KIND=nag_wp) | AP(*), BP(*)
CHARACTER(1) | UPLO
The routine may be called by its LAPACK name dspgst.

3 Description

To reduce the real symmetric-definite generalized eigenproblem Az=λBz, ABz=λz or BAz=λz to the standard form Cy=λy using packed storage, F08TEF (DSPGST) must be preceded by a call to F07GDF (DPPTRF) which computes the Cholesky factorization of B; B must be positive definite.
The different problem types are specified by the argument ITYPE, as indicated in the table below. The table shows how C is computed by the routine, and also how the eigenvectors z of the original problem can be recovered from the eigenvectors of the standard form.
ITYPE | Problem | UPLO | B | C | z
1 | Az=λBz | 'U' 'L' | UT U L LT | U-T A U-1 L-1 A L-T | U-1 y L-T y
2 | ABz=λz | 'U' 'L' | UT U L LT | UA UT LT AL | U-1 y L-T y
3 | BAz=λz | 'U' 'L' | UT U L LT | UA UT LT AL | UT y Ly

4 References

Golub G H and Van Loan C F (1996) Matrix Computations (3rd Edition) Johns Hopkins University Press, Baltimore

5 Arguments

1:   ITYPE – INTEGERInput
On entry: indicates how the standard form is computed.
ITYPE=1
  • if UPLO='U', C=U-T A U-1;
  • if UPLO='L', C=L-1 A L-T.
ITYPE=2 or 3
  • if UPLO='U', C=UA UT;
  • if UPLO='L', C=LT AL.
Constraint: ITYPE=1, 2 or 3.
2:   UPLO – CHARACTER(1)Input
On entry: indicates whether the upper or lower triangular part of A is stored and how B has been factorized.
UPLO='U'
The upper triangular part of A is stored and B=UT U.
UPLO='L'
The lower triangular part of A is stored and B=L LT.
Constraint: UPLO='U' or 'L'.
3:   N – INTEGERInput
On entry: n, the order of the matrices A and B.
Constraint: N≥0.
4:   AP* – REAL (KIND=nag_wp) arrayInput/Output
Note: the dimension of the array AP must be at least max 1,N×N+1/2.
On entry: the upper or lower triangle of the n by n symmetric matrix A, packed by columns.
More precisely,
  • if UPLO='U', the upper triangle of A must be stored with element A ij in AP i+j j-1/2 for i≤j;
  • if UPLO='L', the lower triangle of A must be stored with element A ij in AP i+2 n-jj-1/2 for i≥j.
On exit: the upper or lower triangle of AP is overwritten by the corresponding upper or lower triangle of C as specified by ITYPE and UPLO, using the same packed storage format as described above.
5:   BP* – REAL (KIND=nag_wp) arrayInput
Note: the dimension of the array BP must be at least max 1,N×N+1/2.
On entry: the Cholesky factor of B as specified by UPLO and returned by F07GDF (DPPTRF).
6:   INFO – INTEGEROutput
On exit: INFO=0 unless the routine detects an error (see Section 6).

6 Error Indicators and Warnings

INFO<0
If INFO=-i, argument i had an illegal value. An explanatory message is output, and execution of the program is terminated.

7 Accuracy

Forming the reduced matrix C is a stable procedure. However it involves implicit multiplication by B-1 if (ITYPE=1) or B (if ITYPE=2 or 3). When F08TEF (DSPGST) is used as a step in the computation of eigenvalues and eigenvectors of the original problem, there may be a significant loss of accuracy if B is ill-conditioned with respect to inversion. See the document for F08SAF (DSYGV) for further details.

8 Parallelism and Performance

F08TEF (DSPGST) makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The total number of floating-point operations is approximately n 3.
The complex analogue of this routine is F08TSF (ZHPGST).

10 Example

This example computes all the eigenvalues of Az=λBz, where
A = 0.24 0.39 0.42 -0.16 0.39 -0.11 0.79 0.63 0.42 0.79 -0.25 0.48 -0.16 0.63 0.48 -0.03   and   B= 4.16 -3.12 0.56 -0.10 -3.12 5.03 -0.83 1.09 0.56 -0.83 0.76 0.34 -0.10 1.09 0.34 1.18 ,
using packed storage. Here B is symmetric positive definite and must first be factorized by F07GDF (DPPTRF). The program calls F08TEF (DSPGST) to reduce the problem to the standard form Cy=λy; then F08GEF (DSPTRD) to reduce C to tridiagonal form, and F08JFF (DSTERF) to compute the eigenvalues.

10.1 Program Text

Program Text (f08tefe.f90)

10.2 Program Data

Program Data (f08tefe.d)

10.3 Program Results

Program Results (f08tefe.r)

F08 Chapter Contents
F08 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F08TNF (ZHPGV) : NAG Library, Mark 26

F08 Chapter Contents
F08 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F08TNF (ZHPGV)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F08TNF (ZHPGV) computes all the eigenvalues and, optionally, all the eigenvectors of a complex generalized Hermitian-definite eigenproblem, of the form
Az=λBz ,   ABz=λz   or   BAz=λz ,
where A and B are Hermitian, stored in packed format, and B is also positive definite.

2 Specification

SUBROUTINE F08TNF ( ITYPE, JOBZ, UPLO, N, AP, BP, W, Z, LDZ, WORK, RWORK, INFO)
INTEGER | ITYPE, N, LDZ, INFO
REAL (KIND=nag_wp) | W(N), RWORK(3*N-2)
COMPLEX (KIND=nag_wp) | AP(*), BP(*), Z(LDZ,*), WORK(2*N-1)
CHARACTER(1) | JOBZ, UPLO
The routine may be called by its LAPACK name zhpgv.

3 Description

F08TNF (ZHPGV) first performs a Cholesky factorization of the matrix B as B=UH U , when UPLO='U' or B=L LH , when UPLO='L'. The generalized problem is then reduced to a standard symmetric eigenvalue problem
Cx=λx ,
which is solved for the eigenvalues and, optionally, the eigenvectors; the eigenvectors are then backtransformed to give the eigenvectors of the original problem.
For the problem Az=λBz , the eigenvectors are normalized so that the matrix of eigenvectors, Z, satisfies
ZH A Z = Λ   and   ZH B Z = I ,
where Λ is the diagonal matrix whose diagonal elements are the eigenvalues. For the problem A B z = λ z we correspondingly have
Z-1 A Z-H = Λ   and   ZH B Z = I ,
and for B A z = λ z we have
ZH A Z = Λ   and   ZH B-1 Z = I .

4 References

Anderson E, Bai Z, Bischof C, Blackford S, Demmel J, Dongarra J J, Du Croz J J, Greenbaum A, Hammarling S, McKenney A and Sorensen D (1999) LAPACK Users' Guide (3rd Edition) SIAM, Philadelphia http://www.netlib.org/lapack/lug
Golub G H and Van Loan C F (1996) Matrix Computations (3rd Edition) Johns Hopkins University Press, Baltimore

5 Arguments

1:   ITYPE – INTEGERInput
On entry: specifies the problem type to be solved.
ITYPE=1
Az=λBz.
ITYPE=2
ABz=λz.
ITYPE=3
BAz=λz.
Constraint: ITYPE=1, 2 or 3.
2:   JOBZ – CHARACTER(1)Input
On entry: indicates whether eigenvectors are computed.
JOBZ='N'
Only eigenvalues are computed.
JOBZ='V'
Eigenvalues and eigenvectors are computed.
Constraint: JOBZ='N' or 'V'.
3:   UPLO – CHARACTER(1)Input
On entry: if UPLO='U', the upper triangles of A and B are stored.
If UPLO='L', the lower triangles of A and B are stored.
Constraint: UPLO='U' or 'L'.
4:   N – INTEGERInput
On entry: n, the order of the matrices A and B.
Constraint: N≥0.
5:   AP* – COMPLEX (KIND=nag_wp) arrayInput/Output
Note: the dimension of the array AP must be at least max 1,N×N+1/2.
On entry: the upper or lower triangle of the n by n Hermitian matrix A, packed by columns.
More precisely,
  • if UPLO='U', the upper triangle of A must be stored with element A ij in AP i+j j-1/2 for i≤j;
  • if UPLO='L', the lower triangle of A must be stored with element A ij in AP i+2 n-jj-1/2 for i≥j.
On exit: the contents of AP are destroyed.
6:   BP* – COMPLEX (KIND=nag_wp) arrayInput/Output
Note: the dimension of the array BP must be at least max 1,N×N+1/2.
On entry: the upper or lower triangle of the n by n Hermitian matrix B, packed by columns.
More precisely,
  • if UPLO='U', the upper triangle of B must be stored with element B ij in BP i+j j-1/2 for i≤j;
  • if UPLO='L', the lower triangle of B must be stored with element B ij in BP i+2 n-jj-1/2 for i≥j.
On exit: the triangular factor U or L from the Cholesky factorization B=UH U or B=L LH, in the same storage format as B.
7:   W N – REAL (KIND=nag_wp) arrayOutput
On exit: the eigenvalues in ascending order.
8:   Z LDZ* – COMPLEX (KIND=nag_wp) arrayOutput
Note: the second dimension of the array Z must be at least max 1,N if JOBZ='V', and at least 1 otherwise.
On exit: if JOBZ='V', Z contains the matrix Z of eigenvectors. The eigenvectors are normalized as follows:
  • if ITYPE=1 or 2, ZH BZ=I;
  • if ITYPE=3, ZHB-1 Z=I.
If JOBZ='N', Z is not referenced.
9:   LDZ – INTEGERInput
On entry: the first dimension of the array Z as declared in the (sub)program from which F08TNF (ZHPGV) is called.
Constraints:
  • if JOBZ='V', LDZ≥ max 1,N ;
  • otherwise LDZ≥1.
10:   WORK 2×N-1 – COMPLEX (KIND=nag_wp) arrayWorkspace
11:   RWORK 3×N-2 – REAL (KIND=nag_wp) arrayWorkspace
12:   INFO – INTEGEROutput
On exit: INFO=0 unless the routine detects an error (see Section 6).

6 Error Indicators and Warnings

INFO<0
If INFO=-i, argument i had an illegal value. An explanatory message is output, and execution of the program is terminated.
INFO>0
F07GRF (ZPPTRF) or F08GNF (ZHPEV) returned an error code:
≤N | if INFO=i, F08GNF (ZHPEV) failed to converge; i off-diagonal elements of an intermediate tridiagonal form did not converge to zero;
>N | if INFO=N+i, for 1≤i≤N, then the leading minor of order i of B is not positive definite. The factorization of B could not be completed and no eigenvalues or eigenvectors were computed.

7 Accuracy

If B is ill-conditioned with respect to inversion, then the error bounds for the computed eigenvalues and vectors may be large, although when the diagonal elements of B differ widely in magnitude the eigenvalues and eigenvectors may be less sensitive than the condition of B would suggest. See Section 4.10 of Anderson et al. (1999) for details of the error bounds.
The example program below illustrates the computation of approximate error bounds.

8 Parallelism and Performance

F08TNF (ZHPGV) is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
F08TNF (ZHPGV) makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The total number of floating-point operations is proportional to n 3 .
The real analogue of this routine is F08TAF (DSPGV).

10 Example

This example finds all the eigenvalues and eigenvectors of the generalized Hermitian eigenproblem Az = λ Bz , where
A = -7.36 i+0.00 0.77-0.43 i -0.64-0.92 i 3.01-6.97 i 0.77+0.43 i 3.49 i+0.00 2.19+4.45 i 1.90+3.73 i -0.64+0.92 i 2.19-4.45 i 0.12 i+0.00 2.88-3.17 i 3.01+6.97 i 1.90-3.73 i 2.88+3.17 i -2.54 i+0.00
and
B = 3.23 i+0.00 1.51-1.92 i 1.90+0.84 i 0.42+2.50 i 1.51+1.92 i 3.58 i+0.00 -0.23+1.11 i -1.18+1.37 i 1.90-0.84 i -0.23-1.11 i 4.09 i+0.00 2.33-0.14 i 0.42-2.50 i -1.18-1.37 i 2.33+0.14 i 4.29 i+0.00 ,
together with an estimate of the condition number of B, and approximate error bounds for the computed eigenvalues and eigenvectors.
The example program for F08TQF (ZHPGVD) illustrates solving a generalized symmetric eigenproblem of the form ABz=λz .

10.1 Program Text

Program Text (f08tnfe.f90)

10.2 Program Data

Program Data (f08tnfe.d)

10.3 Program Results

Program Results (f08tnfe.r)

F08 Chapter Contents
F08 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F08TPF (ZHPGVX) : NAG Library, Mark 26

F08 Chapter Contents
F08 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F08TPF (ZHPGVX)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F08TPF (ZHPGVX) computes selected eigenvalues and, optionally, eigenvectors of a complex generalized Hermitian-definite eigenproblem, of the form
Az=λBz ,   ABz=λz   or   BAz=λz ,
where A and B are Hermitian, stored in packed format, and B is also positive definite. Eigenvalues and eigenvectors can be selected by specifying either a range of values or a range of indices for the desired eigenvalues.

2 Specification

SUBROUTINE F08TPF ( ITYPE, JOBZ, RANGE, UPLO, N, AP, BP, VL, VU, IL, IU, ABSTOL, M, W, Z, LDZ, WORK, RWORK, IWORK, JFAIL, INFO)
INTEGER | ITYPE, N, IL, IU, M, LDZ, IWORK(5*N), JFAIL(*), INFO
REAL (KIND=nag_wp) | VL, VU, ABSTOL, W(N), RWORK(7*N)
COMPLEX (KIND=nag_wp) | AP(*), BP(*), Z(LDZ,*), WORK(2*N)
CHARACTER(1) | JOBZ, RANGE, UPLO
The routine may be called by its LAPACK name zhpgvx.

3 Description

F08TPF (ZHPGVX) first performs a Cholesky factorization of the matrix B as B=UH U , when UPLO='U' or B=L LH , when UPLO='L'. The generalized problem is then reduced to a standard symmetric eigenvalue problem
Cx=λx ,
which is solved for the desired eigenvalues and eigenvectors; the eigenvectors are then backtransformed to give the eigenvectors of the original problem.
For the problem Az=λBz , the eigenvectors are normalized so that the matrix of eigenvectors, Z, satisfies
ZH A Z = Λ   and   ZH B Z = I ,
where Λ is the diagonal matrix whose diagonal elements are the eigenvalues. For the problem A B z = λ z we correspondingly have
Z-1 A Z-H = Λ   and   ZH B Z = I ,
and for B A z = λ z we have
ZH A Z = Λ   and   ZH B-1 Z = I .

4 References

Anderson E, Bai Z, Bischof C, Blackford S, Demmel J, Dongarra J J, Du Croz J J, Greenbaum A, Hammarling S, McKenney A and Sorensen D (1999) LAPACK Users' Guide (3rd Edition) SIAM, Philadelphia http://www.netlib.org/lapack/lug
Demmel J W and Kahan W (1990) Accurate singular values of bidiagonal matrices SIAM J. Sci. Statist. Comput. 11 873–912
Golub G H and Van Loan C F (1996) Matrix Computations (3rd Edition) Johns Hopkins University Press, Baltimore

5 Arguments

1:   ITYPE – INTEGERInput
On entry: specifies the problem type to be solved.
ITYPE=1
Az=λBz.
ITYPE=2
ABz=λz.
ITYPE=3
BAz=λz.
Constraint: ITYPE=1, 2 or 3.
2:   JOBZ – CHARACTER(1)Input
On entry: indicates whether eigenvectors are computed.
JOBZ='N'
Only eigenvalues are computed.
JOBZ='V'
Eigenvalues and eigenvectors are computed.
Constraint: JOBZ='N' or 'V'.
3:   RANGE – CHARACTER(1)Input
On entry: if RANGE='A', all eigenvalues will be found.
If RANGE='V', all eigenvalues in the half-open interval VL,VU will be found.
If RANGE='I', the ILth to IUth eigenvalues will be found.
Constraint: RANGE='A', 'V' or 'I'.
4:   UPLO – CHARACTER(1)Input
On entry: if UPLO='U', the upper triangles of A and B are stored.
If UPLO='L', the lower triangles of A and B are stored.
Constraint: UPLO='U' or 'L'.
5:   N – INTEGERInput
On entry: n, the order of the matrices A and B.
Constraint: N≥0.
6:   AP* – COMPLEX (KIND=nag_wp) arrayInput/Output
Note: the dimension of the array AP must be at least max 1,N×N+1/2.
On entry: the upper or lower triangle of the n by n Hermitian matrix A, packed by columns.
More precisely,
  • if UPLO='U', the upper triangle of A must be stored with element A ij in AP i+j j-1/2 for i≤j;
  • if UPLO='L', the lower triangle of A must be stored with element A ij in AP i+2 n-jj-1/2 for i≥j.
On exit: the contents of AP are destroyed.
7:   BP* – COMPLEX (KIND=nag_wp) arrayInput/Output
Note: the dimension of the array BP must be at least max 1,N×N+1/2.
On entry: the upper or lower triangle of the n by n Hermitian matrix B, packed by columns.
More precisely,
  • if UPLO='U', the upper triangle of B must be stored with element B ij in BP i+j j-1/2 for i≤j;
  • if UPLO='L', the lower triangle of B must be stored with element B ij in BP i+2 n-jj-1/2 for i≥j.
On exit: the triangular factor U or L from the Cholesky factorization B=UH U or B=L LH, in the same storage format as B.
8:   VL – REAL (KIND=nag_wp)Input
9:   VU – REAL (KIND=nag_wp)Input
On entry: if RANGE='V', the lower and upper bounds of the interval to be searched for eigenvalues.
If RANGE='A' or 'I', VL and VU are not referenced.
Constraint: if RANGE='V', VL<VU.
10:   IL – INTEGERInput
11:   IU – INTEGERInput
On entry: if RANGE='I', the indices (in ascending order) of the smallest and largest eigenvalues to be returned.
If RANGE='A' or 'V', IL and IU are not referenced.
Constraints:
  • if RANGE='I' and N=0, IL=1 and IU=0;
  • if RANGE='I' and N>0, 1≤ IL≤ IU≤ N .
12:   ABSTOL – REAL (KIND=nag_wp)Input
On entry: the absolute error tolerance for the eigenvalues. An approximate eigenvalue is accepted as converged when it is determined to lie in an interval a,b of width less than or equal to
ABSTOL+ε max a,b ,
where ε is the machine precision. If ABSTOL is less than or equal to zero, then ε T 1 will be used in its place, where T is the tridiagonal matrix obtained by reducing C to tridiagonal form. Eigenvalues will be computed most accurately when ABSTOL is set to twice the underflow threshold 2 × X02AMF , not zero. If this routine returns with INFO=1 to N, indicating that some eigenvectors did not converge, try setting ABSTOL to 2 × X02AMF . See Demmel and Kahan (1990).
13:   M – INTEGEROutput
On exit: the total number of eigenvalues found. 0≤M≤N.
If RANGE='A', M=N.
If RANGE='I', M=IU-IL+1.
14:   W N – REAL (KIND=nag_wp) arrayOutput
On exit: the first M elements contain the selected eigenvalues in ascending order.
15:   Z LDZ* – COMPLEX (KIND=nag_wp) arrayOutput
Note: the second dimension of the array Z must be at least max 1,M if JOBZ='V', and at least 1 otherwise.
On exit: if JOBZ='V', then
  • if INFO=0, the first M columns of Z contain the orthonormal eigenvectors of the matrix A corresponding to the selected eigenvalues, with the ith column of Z holding the eigenvector associated with W i. The eigenvectors are normalized as follows:
    • if ITYPE=1 or 2, ZH BZ=I;
    • if ITYPE=3, ZHB-1 Z=I;
  • if an eigenvector fails to converge (INFO=1 to N), then that column of Z contains the latest approximation to the eigenvector, and the index of the eigenvector is returned in JFAIL.
If JOBZ='N', Z is not referenced.
Note: you must ensure that at least max 1,M columns are supplied in the array Z; if RANGE='V', the exact value of M is not known in advance and an upper bound of at least N must be used.
16:   LDZ – INTEGERInput
On entry: the first dimension of the array Z as declared in the (sub)program from which F08TPF (ZHPGVX) is called.
Constraints:
  • if JOBZ='V', LDZ≥ max 1,N ;
  • otherwise LDZ≥1.
17:   WORK 2×N – COMPLEX (KIND=nag_wp) arrayWorkspace
18:   RWORK 7×N – REAL (KIND=nag_wp) arrayWorkspace
19:   IWORK 5×N – INTEGER arrayWorkspace
20:   JFAIL* – INTEGER arrayOutput
Note: the dimension of the array JFAIL must be at least max 1,N.
On exit: if JOBZ='V', then
  • if INFO=0, the first M elements of JFAIL are zero;
  • if INFO=1 to N, JFAIL contains the indices of the eigenvectors that failed to converge.
If JOBZ='N', JFAIL is not referenced.
21:   INFO – INTEGEROutput
On exit: INFO=0 unless the routine detects an error (see Section 6).

6 Error Indicators and Warnings

INFO<0
If INFO=-i, argument i had an illegal value. An explanatory message is output, and execution of the program is terminated.
INFO=1 to N
If INFO=i, F08GPF (ZHPEVX) failed to converge; i eigenvectors failed to converge. Their indices are stored in array JFAIL.
INFO>N
F07GRF (ZPPTRF) returned an error code; i.e., if INFO=N+i, for 1≤i≤N, then the leading minor of order i of B is not positive definite. The factorization of B could not be completed and no eigenvalues or eigenvectors were computed.

7 Accuracy

If B is ill-conditioned with respect to inversion, then the error bounds for the computed eigenvalues and vectors may be large, although when the diagonal elements of B differ widely in magnitude the eigenvalues and eigenvectors may be less sensitive than the condition of B would suggest. See Section 4.10 of Anderson et al. (1999) for details of the error bounds.

8 Parallelism and Performance

F08TPF (ZHPGVX) is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
F08TPF (ZHPGVX) makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The total number of floating-point operations is proportional to n 3 .
The real analogue of this routine is F08TBF (DSPGVX).

10 Example

This example finds the eigenvalues in the half-open interval -3,3 , and corresponding eigenvectors, of the generalized Hermitian eigenproblem Az = λ Bz , where
A = -7.36 i+0.00 0.77-0.43 i -0.64-0.92 i 3.01-6.97 i 0.77+0.43 i 3.49 i+0.00 2.19+4.45 i 1.90+3.73 i -0.64+0.92 i 2.19-4.45 i 0.12 i+0.00 2.88-3.17 i 3.01+6.97 i 1.90-3.73 i 2.88+3.17 i -2.54 i+0.00
and
B = 3.23 i+0.00 1.51-1.92 i 1.90+0.84 i 0.42+2.50 i 1.51+1.92 i 3.58 i+0.00 -0.23+1.11 i -1.18+1.37 i 1.90-0.84 i -0.23-1.11 i 4.09 i+0.00 2.33-0.14 i 0.42-2.50 i -1.18-1.37 i 2.33+0.14 i 4.29 i+0.00 .
The example program for F08TQF (ZHPGVD) illustrates solving a generalized symmetric eigenproblem of the form ABz=λz .

10.1 Program Text

Program Text (f08tpfe.f90)

10.2 Program Data

Program Data (f08tpfe.d)

10.3 Program Results

Program Results (f08tpfe.r)

F08 Chapter Contents
F08 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F08TQF (ZHPGVD) : NAG Library, Mark 26

F08 Chapter Contents
F08 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F08TQF (ZHPGVD)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F08TQF (ZHPGVD) computes all the eigenvalues and, optionally, the eigenvectors of a complex generalized Hermitian-definite eigenproblem, of the form
Az=λBz ,   ABz=λz   or   BAz=λz ,
where A and B are Hermitian, stored in packed format, and B is also positive definite. If eigenvectors are desired, it uses a divide-and-conquer algorithm.

2 Specification

SUBROUTINE F08TQF ( ITYPE, JOBZ, UPLO, N, AP, BP, W, Z, LDZ, WORK, LWORK, RWORK, LRWORK, IWORK, LIWORK, INFO)
INTEGER | ITYPE, N, LDZ, LWORK, LRWORK, IWORK(max(1,LIWORK)), LIWORK, INFO
REAL (KIND=nag_wp) | W(N), RWORK(max(1,LRWORK))
COMPLEX (KIND=nag_wp) | AP(*), BP(*), Z(LDZ,*), WORK(max(1,LWORK))
CHARACTER(1) | JOBZ, UPLO
The routine may be called by its LAPACK name zhpgvd.

3 Description

F08TQF (ZHPGVD) first performs a Cholesky factorization of the matrix B as B=UH U , when UPLO='U' or B=L LH , when UPLO='L'. The generalized problem is then reduced to a standard symmetric eigenvalue problem
Cx=λx ,
which is solved for the eigenvalues and, optionally, the eigenvectors; the eigenvectors are then backtransformed to give the eigenvectors of the original problem.
For the problem Az=λBz , the eigenvectors are normalized so that the matrix of eigenvectors, z, satisfies
ZH A Z = Λ   and   ZH B Z = I ,
where Λ is the diagonal matrix whose diagonal elements are the eigenvalues. For the problem A B z = λ z we correspondingly have
Z-1 A Z-H = Λ   and   ZH B Z = I ,
and for B A z = λ z we have
ZH A Z = Λ   and   ZH B-1 Z = I .

4 References

Anderson E, Bai Z, Bischof C, Blackford S, Demmel J, Dongarra J J, Du Croz J J, Greenbaum A, Hammarling S, McKenney A and Sorensen D (1999) LAPACK Users' Guide (3rd Edition) SIAM, Philadelphia http://www.netlib.org/lapack/lug
Golub G H and Van Loan C F (1996) Matrix Computations (3rd Edition) Johns Hopkins University Press, Baltimore

5 Arguments

1:   ITYPE – INTEGERInput
On entry: specifies the problem type to be solved.
ITYPE=1
Az=λBz.
ITYPE=2
ABz=λz.
ITYPE=3
BAz=λz.
Constraint: ITYPE=1, 2 or 3.
2:   JOBZ – CHARACTER(1)Input
On entry: indicates whether eigenvectors are computed.
JOBZ='N'
Only eigenvalues are computed.
JOBZ='V'
Eigenvalues and eigenvectors are computed.
Constraint: JOBZ='N' or 'V'.
3:   UPLO – CHARACTER(1)Input
On entry: if UPLO='U', the upper triangles of A and B are stored.
If UPLO='L', the lower triangles of A and B are stored.
Constraint: UPLO='U' or 'L'.
4:   N – INTEGERInput
On entry: n, the order of the matrices A and B.
Constraint: N≥0.
5:   AP* – COMPLEX (KIND=nag_wp) arrayInput/Output
Note: the dimension of the array AP must be at least max 1,N×N+1/2.
On entry: the upper or lower triangle of the n by n Hermitian matrix A, packed by columns.
More precisely,
  • if UPLO='U', the upper triangle of A must be stored with element A ij in AP i+j j-1/2 for i≤j;
  • if UPLO='L', the lower triangle of A must be stored with element A ij in AP i+2 n-jj-1/2 for i≥j.
On exit: the contents of AP are destroyed.
6:   BP* – COMPLEX (KIND=nag_wp) arrayInput/Output
Note: the dimension of the array BP must be at least max 1,N×N+1/2.
On entry: the upper or lower triangle of the n by n Hermitian matrix B, packed by columns.
More precisely,
  • if UPLO='U', the upper triangle of B must be stored with element B ij in BP i+j j-1/2 for i≤j;
  • if UPLO='L', the lower triangle of B must be stored with element B ij in BP i+2 n-jj-1/2 for i≥j.
On exit: the triangular factor U or L from the Cholesky factorization B=UH U or B=L LH, in the same storage format as B.
7:   W N – REAL (KIND=nag_wp) arrayOutput
On exit: the eigenvalues in ascending order.
8:   Z LDZ* – COMPLEX (KIND=nag_wp) arrayOutput
Note: the second dimension of the array Z must be at least max 1,N if JOBZ='V', and at least 1 otherwise.
On exit: if JOBZ='V', Z contains the matrix Z of eigenvectors. The eigenvectors are normalized as follows:
  • if ITYPE=1 or 2, ZH BZ=I;
  • if ITYPE=3, ZHB-1 Z=I.
If JOBZ='N', Z is not referenced.
9:   LDZ – INTEGERInput
On entry: the first dimension of the array Z as declared in the (sub)program from which F08TQF (ZHPGVD) is called.
Constraints:
  • if JOBZ='V', LDZ≥ max 1,N ;
  • otherwise LDZ≥1.
10:   WORK max 1,LWORK – COMPLEX (KIND=nag_wp) arrayWorkspace
On exit: if INFO=0, the real part of WORK 1 contains the minimum value of LWORK required for optimal performance.
11:   LWORK – INTEGERInput
On entry: the dimension of the array WORK as declared in the (sub)program from which F08TQF (ZHPGVD) is called.
If LWORK=-1, a workspace query is assumed; the routine only calculates the optimal sizes of the WORK, RWORK and IWORK arrays, returns these values as the first entries of the WORK, RWORK and IWORK arrays, and no error message related to LWORK, LRWORK or LIWORK is issued.
Constraints:
  • if N≤1, LWORK≥1;
  • if JOBZ='N' and N>1, LWORK≥N;
  • if JOBZ='V' and N>1, LWORK≥2×N.
12:   RWORK max 1,LRWORK – REAL (KIND=nag_wp) arrayWorkspace
On exit: if INFO=0, RWORK 1 returns the optimal LRWORK.
13:   LRWORK – INTEGERInput
On entry: the dimension of the array RWORK as declared in the (sub)program from which F08TQF (ZHPGVD) is called.
If LRWORK=-1, a workspace query is assumed; the routine only calculates the optimal sizes of the WORK, RWORK and IWORK arrays, returns these values as the first entries of the WORK, RWORK and IWORK arrays, and no error message related to LWORK, LRWORK or LIWORK is issued.
Constraints:
  • if N≤1, LRWORK≥1;
  • if JOBZ='N' and N>1, LRWORK≥N;
  • if JOBZ='V' and N>1, LRWORK≥1+5×N+2×N 2.
14:   IWORK max 1,LIWORK – INTEGER arrayWorkspace
On exit: if INFO=0, IWORK 1 returns the optimal LIWORK.
15:   LIWORK – INTEGERInput
On entry: the dimension of the array IWORK as declared in the (sub)program from which F08TQF (ZHPGVD) is called.
If LIWORK=-1, a workspace query is assumed; the routine only calculates the optimal sizes of the WORK, RWORK and IWORK arrays, returns these values as the first entries of the WORK, RWORK and IWORK arrays, and no error message related to LWORK, LRWORK or LIWORK is issued.
Constraints:
  • if JOBZ='N' or N≤1, LIWORK≥1;
  • if JOBZ='V' and N>1, LIWORK≥3+5×N.
16:   INFO – INTEGEROutput
On exit: INFO=0 unless the routine detects an error (see Section 6).

6 Error Indicators and Warnings

INFO<0
If INFO=-i, argument i had an illegal value. An explanatory message is output, and execution of the program is terminated.
INFO>0
F07GRF (ZPPTRF) or F08GQF (ZHPEVD) returned an error code:
≤N | if INFO=i, F08GQF (ZHPEVD) failed to converge; i off-diagonal elements of an intermediate tridiagonal form did not converge to zero;
>N | if INFO=N+i, for 1≤i≤N, then the leading minor of order i of B is not positive definite. The factorization of B could not be completed and no eigenvalues or eigenvectors were computed.

7 Accuracy

If B is ill-conditioned with respect to inversion, then the error bounds for the computed eigenvalues and vectors may be large, although when the diagonal elements of B differ widely in magnitude the eigenvalues and eigenvectors may be less sensitive than the condition of B would suggest. See Section 4.10 of Anderson et al. (1999) for details of the error bounds.
The example program below illustrates the computation of approximate error bounds.

8 Parallelism and Performance

F08TQF (ZHPGVD) is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
F08TQF (ZHPGVD) makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The total number of floating-point operations is proportional to n 3 .
The real analogue of this routine is F08TCF (DSPGVD).

10 Example

This example finds all the eigenvalues and eigenvectors of the generalized Hermitian eigenproblem ABz=λz , where
A = -7.36 i+0.00 0.77-0.43 i -0.64-0.92 i 3.01-6.97 i 0.77+0.43 i 3.49 i+0.00 2.19+4.45 i 1.90+3.73 i -0.64+0.92 i 2.19-4.45 i 0.12 i+0.00 2.88-3.17 i 3.01+6.97 i 1.90-3.73 i 2.88+3.17 i -2.54 i+0.00
and
B = 3.23 i+0.00 1.51-1.92 i 1.90+0.84 i 0.42+2.50 i 1.51+1.92 i 3.58 i+0.00 -0.23+1.11 i -1.18+1.37 i 1.90-0.84 i -0.23-1.11 i 4.09 i+0.00 2.33-0.14 i 0.42-2.50 i -1.18-1.37 i 2.33+0.14 i 4.29 i+0.00 ,
together with an estimate of the condition number of B, and approximate error bounds for the computed eigenvalues and eigenvectors.
The example program for F08TNF (ZHPGV) illustrates solving a generalized Hermitian eigenproblem of the form Az = λ Bz .

10.1 Program Text

Program Text (f08tqfe.f90)

10.2 Program Data

Program Data (f08tqfe.d)

10.3 Program Results

Program Results (f08tqfe.r)

F08 Chapter Contents
F08 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F08TSF (ZHPGST) : NAG Library, Mark 26

F08 Chapter Contents
F08 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F08TSF (ZHPGST)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F08TSF (ZHPGST) reduces a complex Hermitian-definite generalized eigenproblem Az=λBz, ABz=λz or BAz=λz to the standard form Cy=λy, where A is a complex Hermitian matrix and B has been factorized by F07GRF (ZPPTRF), using packed storage.

2 Specification

SUBROUTINE F08TSF ( ITYPE, UPLO, N, AP, BP, INFO)
INTEGER | ITYPE, N, INFO
COMPLEX (KIND=nag_wp) | AP(*), BP(*)
CHARACTER(1) | UPLO
The routine may be called by its LAPACK name zhpgst.

3 Description

To reduce the complex Hermitian-definite generalized eigenproblem Az=λBz, ABz=λz or BAz=λz to the standard form Cy=λy using packed storage, F08TSF (ZHPGST) must be preceded by a call to F07GRF (ZPPTRF) which computes the Cholesky factorization of B; B must be positive definite.
The different problem types are specified by the argument ITYPE, as indicated in the table below. The table shows how C is computed by the routine, and also how the eigenvectors z of the original problem can be recovered from the eigenvectors of the standard form.
ITYPE | Problem | UPLO | B | C | z
1 | Az=λBz | 'U' 'L' | UH U L LH | U-H A U-1 L-1 A L-H | U-1 y L-H y
2 | ABz=λz | 'U' 'L' | UH U L LH | UA UH LH AL | U-1 y L-H y
3 | BAz=λz | 'U' 'L' | UH U L LH | UA UH LH AL | UH y Ly

4 References

Golub G H and Van Loan C F (1996) Matrix Computations (3rd Edition) Johns Hopkins University Press, Baltimore

5 Arguments

1:   ITYPE – INTEGERInput
On entry: indicates how the standard form is computed.
ITYPE=1
  • if UPLO='U', C=U-H A U-1;
  • if UPLO='L', C=L-1 A L-H.
ITYPE=2 or 3
  • if UPLO='U', C=UA UH;
  • if UPLO='L', C=LH AL.
Constraint: ITYPE=1, 2 or 3.
2:   UPLO – CHARACTER(1)Input
On entry: indicates whether the upper or lower triangular part of A is stored and how B has been factorized.
UPLO='U'
The upper triangular part of A is stored and B=UH U.
UPLO='L'
The lower triangular part of A is stored and B=L LH.
Constraint: UPLO='U' or 'L'.
3:   N – INTEGERInput
On entry: n, the order of the matrices A and B.
Constraint: N≥0.
4:   AP* – COMPLEX (KIND=nag_wp) arrayInput/Output
Note: the dimension of the array AP must be at least max 1,N×N+1/2.
On entry: the upper or lower triangle of the n by n Hermitian matrix A, packed by columns.
More precisely,
  • if UPLO='U', the upper triangle of A must be stored with element A ij in AP i+j j-1/2 for i≤j;
  • if UPLO='L', the lower triangle of A must be stored with element A ij in AP i+2 n-jj-1/2 for i≥j.
On exit: the upper or lower triangle of AP is overwritten by the corresponding upper or lower triangle of C as specified by ITYPE and UPLO, using the same packed storage format as described above.
5:   BP* – COMPLEX (KIND=nag_wp) arrayInput
Note: the dimension of the array BP must be at least max 1,N×N+1/2.
On entry: the Cholesky factor of B as specified by UPLO and returned by F07GRF (ZPPTRF).
6:   INFO – INTEGEROutput
On exit: INFO=0 unless the routine detects an error (see Section 6).

6 Error Indicators and Warnings

INFO<0
If INFO=-i, argument i had an illegal value. An explanatory message is output, and execution of the program is terminated.

7 Accuracy

Forming the reduced matrix C is a stable procedure. However it involves implicit multiplication by B-1 if (ITYPE=1) or B (if ITYPE=2 or 3). When F08TSF (ZHPGST) is used as a step in the computation of eigenvalues and eigenvectors of the original problem, there may be a significant loss of accuracy if B is ill-conditioned with respect to inversion. See the document for F08SNF (ZHEGV) for further details.

8 Parallelism and Performance

F08TSF (ZHPGST) makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The total number of real floating-point operations is approximately 4 n 3.
The real analogue of this routine is F08TEF (DSPGST).

10 Example

This example computes all the eigenvalues of Az=λBz, where
A = -7.36+0.00 i 0.77-0.43 i -0.64-0.92 i 3.01-6.97 i 0.77+0.43 i 3.49+0.00 i 2.19+4.45 i 1.90+3.73 i -0.64+0.92 i 2.19-4.45 i 0.12+0.00 i 2.88-3.17 i 3.01+6.97 i 1.90-3.73 i 2.88+3.17 i -2.54+0.00 i
and
B = 3.23+0.00 i 1.51-1.92 i 1.90+0.84 i 0.42+2.50 i 1.51+1.92 i 3.58+0.00 i -0.23+1.11 i -1.18+1.37 i 1.90-0.84 i -0.23-1.11 i 4.09+0.00 i 2.33-0.14 i 0.42-2.50 i -1.18-1.37 i 2.33+0.14 i 4.29+0.00 i ,
using packed storage. Here B is Hermitian positive definite and must first be factorized by F07GRF (ZPPTRF). The program calls F08TSF (ZHPGST) to reduce the problem to the standard form Cy=λy; then F08GSF (ZHPTRD) to reduce C to tridiagonal form, and F08JFF (DSTERF) to compute the eigenvalues.

10.1 Program Text

Program Text (f08tsfe.f90)

10.2 Program Data

Program Data (f08tsfe.d)

10.3 Program Results

Program Results (f08tsfe.r)

F08 Chapter Contents
F08 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F08UAF (DSBGV) : NAG Library, Mark 26

F08 Chapter Contents
F08 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F08UAF (DSBGV)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F08UAF (DSBGV) computes all the eigenvalues and, optionally, the eigenvectors of a real generalized symmetric-definite banded eigenproblem, of the form
Az=λBz ,
where A and B are symmetric and banded, and B is also positive definite.

2 Specification

SUBROUTINE F08UAF ( JOBZ, UPLO, N, KA, KB, AB, LDAB, BB, LDBB, W, Z, LDZ, WORK, INFO)
INTEGER | N, KA, KB, LDAB, LDBB, LDZ, INFO
REAL (KIND=nag_wp) | AB(LDAB,*), BB(LDBB,*), W(N), Z(LDZ,*), WORK(3*N)
CHARACTER(1) | JOBZ, UPLO
The routine may be called by its LAPACK name dsbgv.

3 Description

The generalized symmetric-definite band problem
Az = λ Bz
is first reduced to a standard band symmetric problem
Cx = λx ,
where C is a symmetric band matrix, using Wilkinson's modification to Crawford's algorithm (see Crawford (1973) and Wilkinson (1977)). The symmetric eigenvalue problem is then solved for the eigenvalues and the eigenvectors, if required, which are then backtransformed to the eigenvectors of the original problem.
The eigenvectors are normalized so that the matrix of eigenvectors, Z, satisfies
ZT A Z = Λ   and   ZT B Z = I ,
where Λ is the diagonal matrix whose diagonal elements are the eigenvalues.

4 References

Anderson E, Bai Z, Bischof C, Blackford S, Demmel J, Dongarra J J, Du Croz J J, Greenbaum A, Hammarling S, McKenney A and Sorensen D (1999) LAPACK Users' Guide (3rd Edition) SIAM, Philadelphia http://www.netlib.org/lapack/lug
Crawford C R (1973) Reduction of a band-symmetric generalized eigenvalue problem Comm. ACM 16 41–44
Golub G H and Van Loan C F (1996) Matrix Computations (3rd Edition) Johns Hopkins University Press, Baltimore
Wilkinson J H (1977) Some recent advances in numerical linear algebra The State of the Art in Numerical Analysis (ed D A H Jacobs) Academic Press

5 Arguments

1:   JOBZ – CHARACTER(1)Input
On entry: indicates whether eigenvectors are computed.
JOBZ='N'
Only eigenvalues are computed.
JOBZ='V'
Eigenvalues and eigenvectors are computed.
Constraint: JOBZ='N' or 'V'.
2:   UPLO – CHARACTER(1)Input
On entry: if UPLO='U', the upper triangles of A and B are stored.
If UPLO='L', the lower triangles of A and B are stored.
Constraint: UPLO='U' or 'L'.
3:   N – INTEGERInput
On entry: n, the order of the matrices A and B.
Constraint: N≥0.
4:   KA – INTEGERInput
On entry: if UPLO='U', the number of superdiagonals, ka, of the matrix A.
If UPLO='L', the number of subdiagonals, ka, of the matrix A.
Constraint: KA≥0.
5:   KB – INTEGERInput
On entry: if UPLO='U', the number of superdiagonals, kb, of the matrix B.
If UPLO='L', the number of subdiagonals, kb, of the matrix B.
Constraint: KA≥KB≥0.
6:   AB LDAB* – REAL (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array AB must be at least max 1,N.
On entry: the upper or lower triangle of the n by n symmetric band matrix A.
The matrix is stored in rows 1 to ka+1, more precisely,
  • if UPLO='U', the elements of the upper triangle of A within the band must be stored with element A ij in AB ka+1+i-j j​ for ​max 1,j-ka≤i≤j;
  • if UPLO='L', the elements of the lower triangle of A within the band must be stored with element A ij in AB 1+i-j j​ for ​j≤i≤min n,j+ka.
On exit: the contents of AB are overwritten.
7:   LDAB – INTEGERInput
On entry: the first dimension of the array AB as declared in the (sub)program from which F08UAF (DSBGV) is called.
Constraint: LDAB≥KA+1.
8:   BB LDBB* – REAL (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array BB must be at least max 1,N.
On entry: the upper or lower triangle of the n by n symmetric band matrix B.
The matrix is stored in rows 1 to kb+1, more precisely,
  • if UPLO='U', the elements of the upper triangle of B within the band must be stored with element B ij in BB kb+1+i-j j​ for ​max 1,j-kb≤i≤j;
  • if UPLO='L', the elements of the lower triangle of B within the band must be stored with element B ij in BB 1+i-j j​ for ​j≤i≤min n,j+kb.
On exit: the factor S from the split Cholesky factorization B=ST S, as returned by F08UFF (DPBSTF).
9:   LDBB – INTEGERInput
On entry: the first dimension of the array BB as declared in the (sub)program from which F08UAF (DSBGV) is called.
Constraint: LDBB≥KB+1.
10:   W N – REAL (KIND=nag_wp) arrayOutput
On exit: the eigenvalues in ascending order.
11:   Z LDZ* – REAL (KIND=nag_wp) arrayOutput
Note: the second dimension of the array Z must be at least max 1,N if JOBZ='V', and at least 1 otherwise.
On exit: if JOBZ='V', Z contains the matrix Z of eigenvectors, with the ith column of Z holding the eigenvector associated with W i. The eigenvectors are normalized so that ZT BZ=I.
If JOBZ='N', Z is not referenced.
12:   LDZ – INTEGERInput
On entry: the first dimension of the array Z as declared in the (sub)program from which F08UAF (DSBGV) is called.
Constraints:
  • if JOBZ='V', LDZ≥ max 1,N ;
  • otherwise LDZ≥1.
13:   WORK 3×N – REAL (KIND=nag_wp) arrayWorkspace
14:   INFO – INTEGEROutput
On exit: INFO=0 unless the routine detects an error (see Section 6).

6 Error Indicators and Warnings

INFO<0
If INFO=-i, argument i had an illegal value. An explanatory message is output, and execution of the program is terminated.
INFO>0
If INFO=i and i≤N, the algorithm failed to converge; i off-diagonal elements of an intermediate tridiagonal form did not converge to zero.
If INFO=i and i>N, if INFO=N+i, for 1≤i≤N, then F08UFF (DPBSTF) returned INFO=i: B is not positive definite. The factorization of B could not be completed and no eigenvalues or eigenvectors were computed.

7 Accuracy

If B is ill-conditioned with respect to inversion, then the error bounds for the computed eigenvalues and vectors may be large, although when the diagonal elements of B differ widely in magnitude the eigenvalues and eigenvectors may be less sensitive than the condition of B would suggest. See Section 4.10 of Anderson et al. (1999) for details of the error bounds.

8 Parallelism and Performance

F08UAF (DSBGV) is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
F08UAF (DSBGV) makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The total number of floating-point operations is proportional to n 3 if JOBZ='V' and, assuming that n≫ka , is approximately proportional to n 2 ka otherwise.
The complex analogue of this routine is F08UNF (ZHBGV).

10 Example

This example finds all the eigenvalues of the generalized band symmetric eigenproblem Az = λ Bz , where
A = 0.24 0.39 0.42 0.00 0.39 -0.11 0.79 0.63 0.42 0.79 -0.25 0.48 0.00 0.63 0.48 -0.03   and   B = 2.07 0.95 0.00 0.00 0.95 1.69 -0.29 0.00 0.00 -0.29 0.65 -0.33 0.00 0.00 -0.33 1.17 .

10.1 Program Text

Program Text (f08uafe.f90)

10.2 Program Data

Program Data (f08uafe.d)

10.3 Program Results

Program Results (f08uafe.r)

F08 Chapter Contents
F08 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F08UBF (DSBGVX) : NAG Library, Mark 26

F08 Chapter Contents
F08 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F08UBF (DSBGVX)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F08UBF (DSBGVX) computes selected eigenvalues and, optionally, eigenvectors of a real generalized symmetric-definite banded eigenproblem, of the form
Az=λBz ,
where A and B are symmetric and banded, and B is also positive definite. Eigenvalues and eigenvectors can be selected by specifying either all eigenvalues, a range of values or a range of indices for the desired eigenvalues.

2 Specification

SUBROUTINE F08UBF ( JOBZ, RANGE, UPLO, N, KA, KB, AB, LDAB, BB, LDBB, Q, LDQ, VL, VU, IL, IU, ABSTOL, M, W, Z, LDZ, WORK, IWORK, JFAIL, INFO)
INTEGER | N, KA, KB, LDAB, LDBB, LDQ, IL, IU, M, LDZ, IWORK(5*N), JFAIL(*), INFO
REAL (KIND=nag_wp) | AB(LDAB,*), BB(LDBB,*), Q(LDQ,*), VL, VU, ABSTOL, W(N), Z(LDZ,*), WORK(7*N)
CHARACTER(1) | JOBZ, RANGE, UPLO
The routine may be called by its LAPACK name dsbgvx.

3 Description

The generalized symmetric-definite band problem
Az = λ Bz
is first reduced to a standard band symmetric problem
Cx = λx ,
where C is a symmetric band matrix, using Wilkinson's modification to Crawford's algorithm (see Crawford (1973) and Wilkinson (1977)). The symmetric eigenvalue problem is then solved for the required eigenvalues and eigenvectors, and the eigenvectors are then backtransformed to the eigenvectors of the original problem.
The eigenvectors are normalized so that
zT A z = λ   and   zT B z = 1 .

4 References

Anderson E, Bai Z, Bischof C, Blackford S, Demmel J, Dongarra J J, Du Croz J J, Greenbaum A, Hammarling S, McKenney A and Sorensen D (1999) LAPACK Users' Guide (3rd Edition) SIAM, Philadelphia http://www.netlib.org/lapack/lug
Crawford C R (1973) Reduction of a band-symmetric generalized eigenvalue problem Comm. ACM 16 41–44
Demmel J W and Kahan W (1990) Accurate singular values of bidiagonal matrices SIAM J. Sci. Statist. Comput. 11 873–912
Golub G H and Van Loan C F (1996) Matrix Computations (3rd Edition) Johns Hopkins University Press, Baltimore
Wilkinson J H (1977) Some recent advances in numerical linear algebra The State of the Art in Numerical Analysis (ed D A H Jacobs) Academic Press

5 Arguments

1:   JOBZ – CHARACTER(1)Input
On entry: indicates whether eigenvectors are computed.
JOBZ='N'
Only eigenvalues are computed.
JOBZ='V'
Eigenvalues and eigenvectors are computed.
Constraint: JOBZ='N' or 'V'.
2:   RANGE – CHARACTER(1)Input
On entry: if RANGE='A', all eigenvalues will be found.
If RANGE='V', all eigenvalues in the half-open interval VL,VU will be found.
If RANGE='I', the ILth to IUth eigenvalues will be found.
Constraint: RANGE='A', 'V' or 'I'.
3:   UPLO – CHARACTER(1)Input
On entry: if UPLO='U', the upper triangles of A and B are stored.
If UPLO='L', the lower triangles of A and B are stored.
Constraint: UPLO='U' or 'L'.
4:   N – INTEGERInput
On entry: n, the order of the matrices A and B.
Constraint: N≥0.
5:   KA – INTEGERInput
On entry: if UPLO='U', the number of superdiagonals, ka, of the matrix A.
If UPLO='L', the number of subdiagonals, ka, of the matrix A.
Constraint: KA≥0.
6:   KB – INTEGERInput
On entry: if UPLO='U', the number of superdiagonals, kb, of the matrix B.
If UPLO='L', the number of subdiagonals, kb, of the matrix B.
Constraint: KA≥KB≥0.
7:   AB LDAB* – REAL (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array AB must be at least max 1,N.
On entry: the upper or lower triangle of the n by n symmetric band matrix A.
The matrix is stored in rows 1 to ka+1, more precisely,
  • if UPLO='U', the elements of the upper triangle of A within the band must be stored with element A ij in AB ka+1+i-j j​ for ​max 1,j-ka≤i≤j;
  • if UPLO='L', the elements of the lower triangle of A within the band must be stored with element A ij in AB 1+i-j j​ for ​j≤i≤min n,j+ka.
On exit: the contents of AB are overwritten.
8:   LDAB – INTEGERInput
On entry: the first dimension of the array AB as declared in the (sub)program from which F08UBF (DSBGVX) is called.
Constraint: LDAB≥KA+1.
9:   BB LDBB* – REAL (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array BB must be at least max 1,N.
On entry: the upper or lower triangle of the n by n symmetric positive definite band matrix B.
The matrix is stored in rows 1 to kb+1, more precisely,
  • if UPLO='U', the elements of the upper triangle of B within the band must be stored with element B ij in BB kb+1+i-j j​ for ​max 1,j-kb≤i≤j;
  • if UPLO='L', the elements of the lower triangle of B within the band must be stored with element B ij in BB 1+i-j j​ for ​j≤i≤min n,j+kb.
On exit: the factor S from the split Cholesky factorization B=ST S, as returned by F08UFF (DPBSTF).
10:   LDBB – INTEGERInput
On entry: the first dimension of the array BB as declared in the (sub)program from which F08UBF (DSBGVX) is called.
Constraint: LDBB≥KB+1.
11:   Q LDQ* – REAL (KIND=nag_wp) arrayOutput
Note: the second dimension of the array Q must be at least max 1,N if JOBZ='V', and at least 1 otherwise.
On exit: if JOBZ='V', the n by n matrix, Q used in the reduction of the standard form, i.e., Cx=λx, from symmetric banded to tridiagonal form.
If JOBZ='N', Q is not referenced.
12:   LDQ – INTEGERInput
On entry: the first dimension of the array Q as declared in the (sub)program from which F08UBF (DSBGVX) is called.
Constraints:
  • if JOBZ='V', LDQ≥ max 1,N ;
  • otherwise LDQ≥1.
13:   VL – REAL (KIND=nag_wp)Input
14:   VU – REAL (KIND=nag_wp)Input
On entry: if RANGE='V', the lower and upper bounds of the interval to be searched for eigenvalues.
If RANGE='A' or 'I', VL and VU are not referenced.
Constraint: if RANGE='V', VL<VU.
15:   IL – INTEGERInput
16:   IU – INTEGERInput
On entry: if RANGE='I', the indices (in ascending order) of the smallest and largest eigenvalues to be returned.
If RANGE='A' or 'V', IL and IU are not referenced.
Constraints:
  • if RANGE='I' and N=0, IL=1 and IU=0;
  • if RANGE='I' and N>0, 1≤ IL≤ IU≤ N .
17:   ABSTOL – REAL (KIND=nag_wp)Input
On entry: the absolute error tolerance for the eigenvalues. An approximate eigenvalue is accepted as converged when it is determined to lie in an interval a,b of width less than or equal to
ABSTOL+ε max a,b ,
where ε is the machine precision. If ABSTOL is less than or equal to zero, then ε T 1 will be used in its place, where T is the tridiagonal matrix obtained by reducing C to tridiagonal form. Eigenvalues will be computed most accurately when ABSTOL is set to twice the underflow threshold 2 × X02AMF , not zero. If this routine returns with INFO=1 to N, indicating that some eigenvectors did not converge, try setting ABSTOL to 2 × X02AMF . See Demmel and Kahan (1990).
18:   M – INTEGEROutput
On exit: the total number of eigenvalues found. 0≤M≤N.
If RANGE='A', M=N.
If RANGE='I', M=IU-IL+1.
19:   W N – REAL (KIND=nag_wp) arrayOutput
On exit: the eigenvalues in ascending order.
20:   Z LDZ* – REAL (KIND=nag_wp) arrayOutput
Note: the second dimension of the array Z must be at least max 1,N if JOBZ='V', and at least 1 otherwise.
On exit: if JOBZ='V', Z contains the matrix Z of eigenvectors, with the ith column of Z holding the eigenvector associated with W i. The eigenvectors are normalized so that ZT BZ=I.
If JOBZ='N', Z is not referenced.
21:   LDZ – INTEGERInput
On entry: the first dimension of the array Z as declared in the (sub)program from which F08UBF (DSBGVX) is called.
Constraints:
  • if JOBZ='V', LDZ≥ max 1,N ;
  • otherwise LDZ≥1.
22:   WORK 7×N – REAL (KIND=nag_wp) arrayWorkspace
23:   IWORK 5×N – INTEGER arrayWorkspace
24:   JFAIL* – INTEGER arrayOutput
Note: the dimension of the array JFAIL must be at least max 1,N.
On exit: if JOBZ='V', then
  • if INFO=0, the first M elements of JFAIL are zero;
  • if INFO=1 to N, JFAIL contains the indices of the eigenvectors that failed to converge.
If JOBZ='N', JFAIL is not referenced.
25:   INFO – INTEGEROutput
On exit: INFO=0 unless the routine detects an error (see Section 6).

6 Error Indicators and Warnings

INFO<0
If INFO=-i, argument i had an illegal value. An explanatory message is output, and execution of the program is terminated.
INFO=1 to N
If INFO=i, then i eigenvectors failed to converge. Their indices are stored in array JFAIL. Please see ABSTOL.
INFO>N
F08UFF (DPBSTF) returned an error code; i.e., if INFO=N+i, for 1≤i≤N, then the leading minor of order i of B is not positive definite. The factorization of B could not be completed and no eigenvalues or eigenvectors were computed.

7 Accuracy

If B is ill-conditioned with respect to inversion, then the error bounds for the computed eigenvalues and vectors may be large, although when the diagonal elements of B differ widely in magnitude the eigenvalues and eigenvectors may be less sensitive than the condition of B would suggest. See Section 4.10 of Anderson et al. (1999) for details of the error bounds.

8 Parallelism and Performance

F08UBF (DSBGVX) is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
F08UBF (DSBGVX) makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The total number of floating-point operations is proportional to n 3 if JOBZ='V' and RANGE='A', and assuming that n≫ka , is approximately proportional to n 2 ka if JOBZ='N'. Otherwise the number of floating-point operations depends upon the number of eigenvectors computed.
The complex analogue of this routine is F08UPF (ZHBGVX).

10 Example

This example finds the eigenvalues in the half-open interval 0.0,1.0 , and corresponding eigenvectors, of the generalized band symmetric eigenproblem Az = λ Bz , where
A = 0.24 0.39 0.42 0.00 0.39 -0.11 0.79 0.63 0.42 0.79 -0.25 0.48 0.00 0.63 0.48 -0.03   and   B = 2.07 0.95 0.00 0.00 0.95 1.69 -0.29 0.00 0.00 -0.29 0.65 -0.33 0.00 0.00 -0.33 1.17 .

10.1 Program Text

Program Text (f08ubfe.f90)

10.2 Program Data

Program Data (f08ubfe.d)

10.3 Program Results

Program Results (f08ubfe.r)

F08 Chapter Contents
F08 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F08UCF (DSBGVD) : NAG Library, Mark 26

F08 Chapter Contents
F08 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F08UCF (DSBGVD)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F08UCF (DSBGVD) computes all the eigenvalues and, optionally, the eigenvectors of a real generalized symmetric-definite banded eigenproblem, of the form
Az=λBz ,
where A and B are symmetric and banded, and B is also positive definite. If eigenvectors are desired, it uses a divide-and-conquer algorithm.

2 Specification

SUBROUTINE F08UCF ( JOBZ, UPLO, N, KA, KB, AB, LDAB, BB, LDBB, W, Z, LDZ, WORK, LWORK, IWORK, LIWORK, INFO)
INTEGER | N, KA, KB, LDAB, LDBB, LDZ, LWORK, IWORK(max(1,LIWORK)), LIWORK, INFO
REAL (KIND=nag_wp) | AB(LDAB,*), BB(LDBB,*), W(N), Z(LDZ,*), WORK(max(1,LWORK))
CHARACTER(1) | JOBZ, UPLO
The routine may be called by its LAPACK name dsbgvd.

3 Description

The generalized symmetric-definite band problem
Az = λ Bz
is first reduced to a standard band symmetric problem
Cx = λx ,
where C is a symmetric band matrix, using Wilkinson's modification to Crawford's algorithm (see Crawford (1973) and Wilkinson (1977)). The symmetric eigenvalue problem is then solved for the eigenvalues and the eigenvectors, if required, which are then backtransformed to the eigenvectors of the original problem.
The eigenvectors are normalized so that the matrix of eigenvectors, Z, satisfies
ZT A Z = Λ   and   ZT B Z = I ,
where Λ is the diagonal matrix whose diagonal elements are the eigenvalues.

4 References

Anderson E, Bai Z, Bischof C, Blackford S, Demmel J, Dongarra J J, Du Croz J J, Greenbaum A, Hammarling S, McKenney A and Sorensen D (1999) LAPACK Users' Guide (3rd Edition) SIAM, Philadelphia http://www.netlib.org/lapack/lug
Crawford C R (1973) Reduction of a band-symmetric generalized eigenvalue problem Comm. ACM 16 41–44
Golub G H and Van Loan C F (1996) Matrix Computations (3rd Edition) Johns Hopkins University Press, Baltimore
Wilkinson J H (1977) Some recent advances in numerical linear algebra The State of the Art in Numerical Analysis (ed D A H Jacobs) Academic Press

5 Arguments

1:   JOBZ – CHARACTER(1)Input
On entry: indicates whether eigenvectors are computed.
JOBZ='N'
Only eigenvalues are computed.
JOBZ='V'
Eigenvalues and eigenvectors are computed.
Constraint: JOBZ='N' or 'V'.
2:   UPLO – CHARACTER(1)Input
On entry: if UPLO='U', the upper triangles of A and B are stored.
If UPLO='L', the lower triangles of A and B are stored.
Constraint: UPLO='U' or 'L'.
3:   N – INTEGERInput
On entry: n, the order of the matrices A and B.
Constraint: N≥0.
4:   KA – INTEGERInput
On entry: if UPLO='U', the number of superdiagonals, ka, of the matrix A.
If UPLO='L', the number of subdiagonals, ka, of the matrix A.
Constraint: KA≥0.
5:   KB – INTEGERInput
On entry: if UPLO='U', the number of superdiagonals, kb, of the matrix B.
If UPLO='L', the number of subdiagonals, kb, of the matrix B.
Constraint: KA≥KB≥0.
6:   AB LDAB* – REAL (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array AB must be at least max 1,N.
On entry: the upper or lower triangle of the n by n symmetric band matrix A.
The matrix is stored in rows 1 to ka+1, more precisely,
  • if UPLO='U', the elements of the upper triangle of A within the band must be stored with element A ij in AB ka+1+i-j j​ for ​max 1,j-ka≤i≤j;
  • if UPLO='L', the elements of the lower triangle of A within the band must be stored with element A ij in AB 1+i-j j​ for ​j≤i≤min n,j+ka.
On exit: the contents of AB are overwritten.
7:   LDAB – INTEGERInput
On entry: the first dimension of the array AB as declared in the (sub)program from which F08UCF (DSBGVD) is called.
Constraint: LDAB≥KA+1.
8:   BB LDBB* – REAL (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array BB must be at least max 1,N.
On entry: the upper or lower triangle of the n by n symmetric band matrix B.
The matrix is stored in rows 1 to kb+1, more precisely,
  • if UPLO='U', the elements of the upper triangle of B within the band must be stored with element B ij in BB kb+1+i-j j​ for ​max 1,j-kb≤i≤j;
  • if UPLO='L', the elements of the lower triangle of B within the band must be stored with element B ij in BB 1+i-j j​ for ​j≤i≤min n,j+kb.
On exit: the factor S from the split Cholesky factorization B=ST S, as returned by F08UFF (DPBSTF).
9:   LDBB – INTEGERInput
On entry: the first dimension of the array BB as declared in the (sub)program from which F08UCF (DSBGVD) is called.
Constraint: LDBB≥KB+1.
10:   W N – REAL (KIND=nag_wp) arrayOutput
On exit: the eigenvalues in ascending order.
11:   Z LDZ* – REAL (KIND=nag_wp) arrayOutput
Note: the second dimension of the array Z must be at least max 1,N if JOBZ='V', and at least 1 otherwise.
On exit: if JOBZ='V', Z contains the matrix Z of eigenvectors, with the ith column of Z holding the eigenvector associated with W i. The eigenvectors are normalized so that ZT BZ=I.
If JOBZ='N', Z is not referenced.
12:   LDZ – INTEGERInput
On entry: the first dimension of the array Z as declared in the (sub)program from which F08UCF (DSBGVD) is called.
Constraints:
  • if JOBZ='V', LDZ≥ max 1,N ;
  • otherwise LDZ≥1.
13:   WORK max 1,LWORK – REAL (KIND=nag_wp) arrayWorkspace
On exit: if INFO=0, WORK 1 contains the minimum value of LWORK required for optimal performance.
14:   LWORK – INTEGERInput
On entry: the dimension of the array WORK as declared in the (sub)program from which F08UCF (DSBGVD) is called.
If LWORK=-1, a workspace query is assumed; the routine only calculates the minimum sizes of the WORK and IWORK arrays, returns these values as the first entries of the WORK and IWORK arrays, and no error message related to LWORK or LIWORK is issued.
Constraints:
  • if N≤1, LWORK≥1;
  • if JOBZ='N' and N>1, LWORK≥max 1,3×N;
  • if JOBZ='V' and N>1, LWORK≥1+5×N+2×N 2.
15:   IWORK max 1,LIWORK – INTEGER arrayWorkspace
On exit: if INFO=0, IWORK 1 returns the minimum LIWORK.
16:   LIWORK – INTEGERInput
On entry: the dimension of the array IWORK as declared in the (sub)program from which F08UCF (DSBGVD) is called.
If LIWORK=-1, a workspace query is assumed; the routine only calculates the minimum sizes of the WORK and IWORK arrays, returns these values as the first entries of the WORK and IWORK arrays, and no error message related to LWORK or LIWORK is issued.
Constraints:
  • if JOBZ='N' or N≤1, LIWORK≥1;
  • if JOBZ='V' and N>1, LIWORK≥3+5×N.
17:   INFO – INTEGEROutput
On exit: INFO=0 unless the routine detects an error (see Section 6).

6 Error Indicators and Warnings

INFO<0
If INFO=-i, argument i had an illegal value. An explanatory message is output, and execution of the program is terminated.
INFO>0
If INFO=i and i≤N, the algorithm failed to converge; i off-diagonal elements of an intermediate tridiagonal form did not converge to zero.
If INFO=i and i>N, if INFO=N+i, for 1≤i≤N, then F08UFF (DPBSTF) returned INFO=i: B is not positive definite. The factorization of B could not be completed and no eigenvalues or eigenvectors were computed.

7 Accuracy

If B is ill-conditioned with respect to inversion, then the error bounds for the computed eigenvalues and vectors may be large, although when the diagonal elements of B differ widely in magnitude the eigenvalues and eigenvectors may be less sensitive than the condition of B would suggest. See Section 4.10 of Anderson et al. (1999) for details of the error bounds.

8 Parallelism and Performance

F08UCF (DSBGVD) is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
F08UCF (DSBGVD) makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The total number of floating-point operations is proportional to n 3 if JOBZ='V' and, assuming that n≫ka , is approximately proportional to n 2 ka otherwise.
The complex analogue of this routine is F08UQF (ZHBGVD).

10 Example

This example finds all the eigenvalues of the generalized band symmetric eigenproblem Az = λ Bz , where
A = 0.24 0.39 0.42 0.00 0.39 -0.11 0.79 0.63 0.42 0.79 -0.25 0.48 0.00 0.63 0.48 -0.03   and   B = 2.07 0.95 0.00 0.00 0.95 1.69 -0.29 0.00 0.00 -0.29 0.65 -0.33 0.00 0.00 -0.33 1.17 .

10.1 Program Text

Program Text (f08ucfe.f90)

10.2 Program Data

Program Data (f08ucfe.d)

10.3 Program Results

Program Results (f08ucfe.r)

F08 Chapter Contents
F08 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F08UEF (DSBGST) : NAG Library, Mark 26

F08 Chapter Contents
F08 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F08UEF (DSBGST)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F08UEF (DSBGST) reduces a real symmetric-definite generalized eigenproblem Az=λBz to the standard form Cy=λy, where A and B are band matrices, A is a real symmetric matrix, and B has been factorized by F08UFF (DPBSTF).

2 Specification

SUBROUTINE F08UEF ( VECT, UPLO, N, KA, KB, AB, LDAB, BB, LDBB, X, LDX, WORK, INFO)
INTEGER | N, KA, KB, LDAB, LDBB, LDX, INFO
REAL (KIND=nag_wp) | AB(LDAB,*), BB(LDBB,*), X(LDX,*), WORK(2*N)
CHARACTER(1) | VECT, UPLO
The routine may be called by its LAPACK name dsbgst.

3 Description

To reduce the real symmetric-definite generalized eigenproblem Az=λBz to the standard form Cy=λy, where A, B and C are banded, F08UEF (DSBGST) must be preceded by a call to F08UFF (DPBSTF) which computes the split Cholesky factorization of the positive definite matrix B: B=ST S. The split Cholesky factorization, compared with the ordinary Cholesky factorization, allows the work to be approximately halved.
This routine overwrites A with C=XT AX, where X=S-1 Q and Q is a orthogonal matrix chosen (implicitly) to preserve the bandwidth of A. The routine also has an option to allow the accumulation of X, and then, if z is an eigenvector of C, Xz is an eigenvector of the original system.

4 References

Crawford C R (1973) Reduction of a band-symmetric generalized eigenvalue problem Comm. ACM 16 41–44
Kaufman L (1984) Banded eigenvalue solvers on vector machines ACM Trans. Math. Software 10 73–86

5 Arguments

1:   VECT – CHARACTER(1)Input
On entry: indicates whether X is to be returned.
VECT='N'
X is not returned.
VECT='V'
X is returned.
Constraint: VECT='N' or 'V'.
2:   UPLO – CHARACTER(1)Input
On entry: indicates whether the upper or lower triangular part of A is stored.
UPLO='U'
The upper triangular part of A is stored.
UPLO='L'
The lower triangular part of A is stored.
Constraint: UPLO='U' or 'L'.
3:   N – INTEGERInput
On entry: n, the order of the matrices A and B.
Constraint: N≥0.
4:   KA – INTEGERInput
On entry: if UPLO='U', the number of superdiagonals, ka, of the matrix A.
If UPLO='L', the number of subdiagonals, ka, of the matrix A.
Constraint: KA≥0.
5:   KB – INTEGERInput
On entry: if UPLO='U', the number of superdiagonals, kb, of the matrix B.
If UPLO='L', the number of subdiagonals, kb, of the matrix B.
Constraint: KA≥KB≥0.
6:   AB LDAB* – REAL (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array AB must be at least max 1,N.
On entry: the upper or lower triangle of the n by n symmetric band matrix A.
The matrix is stored in rows 1 to ka+1, more precisely,
  • if UPLO='U', the elements of the upper triangle of A within the band must be stored with element A ij in AB ka+1+i-j j​ for ​max 1,j-ka≤i≤j;
  • if UPLO='L', the elements of the lower triangle of A within the band must be stored with element A ij in AB 1+i-j j​ for ​j≤i≤min n,j+ka.
On exit: the upper or lower triangle of AB is overwritten by the corresponding upper or lower triangle of C as specified by UPLO.
7:   LDAB – INTEGERInput
On entry: the first dimension of the array AB as declared in the (sub)program from which F08UEF (DSBGST) is called.
Constraint: LDAB≥KA+1.
8:   BB LDBB* – REAL (KIND=nag_wp) arrayInput
Note: the second dimension of the array BB must be at least max 1,N.
On entry: the banded split Cholesky factor of B as specified by UPLO, N and KB and returned by F08UFF (DPBSTF).
9:   LDBB – INTEGERInput
On entry: the first dimension of the array BB as declared in the (sub)program from which F08UEF (DSBGST) is called.
Constraint: LDBB≥KB+1.
10:   X LDX* – REAL (KIND=nag_wp) arrayOutput
Note: the second dimension of the array X must be at least max 1,N if VECT='V' and at least 1 if VECT='N'.
On exit: the n by n matrix X=S-1 Q, if VECT='V'.
If VECT='N', X is not referenced.
11:   LDX – INTEGERInput
On entry: the first dimension of the array X as declared in the (sub)program from which F08UEF (DSBGST) is called.
Constraints:
  • if VECT='V', LDX≥ max 1,N ;
  • if VECT='N', LDX≥1.
12:   WORK 2×N – REAL (KIND=nag_wp) arrayWorkspace
13:   INFO – INTEGEROutput
On exit: INFO=0 unless the routine detects an error (see Section 6).

6 Error Indicators and Warnings

INFO<0
If INFO=-i, argument i had an illegal value. An explanatory message is output, and execution of the program is terminated.

7 Accuracy

Forming the reduced matrix C is a stable procedure. However it involves implicit multiplication by B-1. When F08UEF (DSBGST) is used as a step in the computation of eigenvalues and eigenvectors of the original problem, there may be a significant loss of accuracy if B is ill-conditioned with respect to inversion.

8 Parallelism and Performance

F08UEF (DSBGST) makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The total number of floating-point operations is approximately 6 n 2 kB, when VECT='N', assuming n≫kA,kB; there are an additional 3/2 n 3 kB/kA operations when VECT='V'.
The complex analogue of this routine is F08USF (ZHBGST).

10 Example

This example computes all the eigenvalues of Az=λBz, where
A = 0.24 0.39 0.42 0.00 0.39 -0.11 0.79 0.63 0.42 0.79 -0.25 0.48 0.00 0.63 0.48 -0.03   and  B= 2.07 0.95 0.00 0.00 0.95 1.69 -0.29 0.00 0.00 -0.29 0.65 -0.33 0.00 0.00 -0.33 1.17 .
Here A is symmetric, B is symmetric positive definite, and A and B are treated as band matrices. B must first be factorized by F08UFF (DPBSTF). The program calls F08UEF (DSBGST) to reduce the problem to the standard form Cy=λy, then F08HEF (DSBTRD) to reduce C to tridiagonal form, and F08JFF (DSTERF) to compute the eigenvalues.

10.1 Program Text

Program Text (f08uefe.f90)

10.2 Program Data

Program Data (f08uefe.d)

10.3 Program Results

Program Results (f08uefe.r)

F08 Chapter Contents
F08 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F08UFF (DPBSTF) : NAG Library, Mark 26

F08 Chapter Contents
F08 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F08UFF (DPBSTF)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
10 Example

1 Purpose

F08UFF (DPBSTF) computes a split Cholesky factorization of a real symmetric positive definite band matrix.

2 Specification

SUBROUTINE F08UFF ( UPLO, N, KB, BB, LDBB, INFO)
INTEGER | N, KB, LDBB, INFO
REAL (KIND=nag_wp) | BB(LDBB,*)
CHARACTER(1) | UPLO
The routine may be called by its LAPACK name dpbstf.

3 Description

F08UFF (DPBSTF) computes a split Cholesky factorization of a real symmetric positive definite band matrix B. It is designed to be used in conjunction with F08UEF (DSBGST).
The factorization has the form B=ST S, where S is a band matrix of the same bandwidth as B and the following structure: S is upper triangular in the first n+k/2 rows, and transposed — hence, lower triangular — in the remaining rows. For example, if n=9 and k=2, then
S = s 11 s 12 s 13 s 22 s 23 s 24 s 33 s 34 s 35 s 44 s 45 s 55 s 64 s 65 s 66 s 75 s 76 s 77 s 86 s 87 s 88 s 97 s 98 s 99 .

4 References

None.

5 Arguments

1:   UPLO – CHARACTER(1)Input
On entry: indicates whether the upper or lower triangular part of B is stored.
UPLO='U'
The upper triangular part of B is stored.
UPLO='L'
The lower triangular part of B is stored.
Constraint: UPLO='U' or 'L'.
2:   N – INTEGERInput
On entry: n, the order of the matrix B.
Constraint: N≥0.
3:   KB – INTEGERInput
On entry: if UPLO='U', the number of superdiagonals, kb, of the matrix B.
If UPLO='L', the number of subdiagonals, kb, of the matrix B.
Constraint: KB≥0.
4:   BB LDBB* – REAL (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array BB must be at least max 1,N.
On entry: the n by n symmetric positive definite band matrix B.
The matrix is stored in rows 1 to kb+1, more precisely,
  • if UPLO='U', the elements of the upper triangle of B within the band must be stored with element B ij in BB kb+1+i-j j​ for ​max 1,j-kb≤i≤j;
  • if UPLO='L', the elements of the lower triangle of B within the band must be stored with element B ij in BB 1+i-j j​ for ​j≤i≤min n,j+kb.
On exit: B is overwritten by the elements of its split Cholesky factor S.
5:   LDBB – INTEGERInput
On entry: the first dimension of the array BB as declared in the (sub)program from which F08UFF (DPBSTF) is called.
Constraint: LDBB≥KB+1.
6:   INFO – INTEGEROutput
On exit: INFO=0 unless the routine detects an error (see Section 6).

6 Error Indicators and Warnings

INFO<0
If INFO=-i, argument i had an illegal value. An explanatory message is output, and execution of the program is terminated.
INFO>0
If INFO=i, the factorization could not be completed, because the updated element b i,i would be the square root of a negative number. Hence B is not positive definite. This may indicate an error in forming the matrix B.

7 Accuracy

The computed factor S is the exact factor of a perturbed matrix B+E, where
E≤c k+1 ε STS,
c k+1 is a modest linear function of k+1, and ε is the machine precision. It follows that e ij≤c k+1 ε⁢b iib jj.

8 Parallelism and Performance

F08UFF (DPBSTF) makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The total number of floating-point operations is approximately n k+1 2, assuming n≫k.
A call to F08UFF (DPBSTF) may be followed by a call to F08UEF (DSBGST) to solve the generalized eigenproblem Az=λBz, where A and B are banded and B is positive definite.
The complex analogue of this routine is F08UTF (ZPBSTF).

10 Example

See Section 10 in F08UEF (DSBGST).
F08 Chapter Contents
F08 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F08UNF (ZHBGV) : NAG Library, Mark 26

F08 Chapter Contents
F08 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F08UNF (ZHBGV)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F08UNF (ZHBGV) computes all the eigenvalues and, optionally, the eigenvectors of a complex generalized Hermitian-definite banded eigenproblem, of the form
Az=λBz ,
where A and B are Hermitian and banded, and B is also positive definite.

2 Specification

SUBROUTINE F08UNF ( JOBZ, UPLO, N, KA, KB, AB, LDAB, BB, LDBB, W, Z, LDZ, WORK, RWORK, INFO)
INTEGER | N, KA, KB, LDAB, LDBB, LDZ, INFO
REAL (KIND=nag_wp) | W(N), RWORK(3*N)
COMPLEX (KIND=nag_wp) | AB(LDAB,*), BB(LDBB,*), Z(LDZ,*), WORK(N)
CHARACTER(1) | JOBZ, UPLO
The routine may be called by its LAPACK name zhbgv.

3 Description

The generalized Hermitian-definite band problem
Az = λ Bz
is first reduced to a standard band Hermitian problem
Cx = λx ,
where C is a Hermitian band matrix, using Wilkinson's modification to Crawford's algorithm (see Crawford (1973) and Wilkinson (1977)). The Hermitian eigenvalue problem is then solved for the eigenvalues and the eigenvectors, if required, which are then backtransformed to the eigenvectors of the original problem.
The eigenvectors are normalized so that the matrix of eigenvectors, Z, satisfies
ZH A Z = Λ   and   ZH B Z = I ,
where Λ is the diagonal matrix whose diagonal elements are the eigenvalues.

4 References

Anderson E, Bai Z, Bischof C, Blackford S, Demmel J, Dongarra J J, Du Croz J J, Greenbaum A, Hammarling S, McKenney A and Sorensen D (1999) LAPACK Users' Guide (3rd Edition) SIAM, Philadelphia http://www.netlib.org/lapack/lug
Crawford C R (1973) Reduction of a band-symmetric generalized eigenvalue problem Comm. ACM 16 41–44
Golub G H and Van Loan C F (1996) Matrix Computations (3rd Edition) Johns Hopkins University Press, Baltimore
Wilkinson J H (1977) Some recent advances in numerical linear algebra The State of the Art in Numerical Analysis (ed D A H Jacobs) Academic Press

5 Arguments

1:   JOBZ – CHARACTER(1)Input
On entry: indicates whether eigenvectors are computed.
JOBZ='N'
Only eigenvalues are computed.
JOBZ='V'
Eigenvalues and eigenvectors are computed.
Constraint: JOBZ='N' or 'V'.
2:   UPLO – CHARACTER(1)Input
On entry: if UPLO='U', the upper triangles of A and B are stored.
If UPLO='L', the lower triangles of A and B are stored.
Constraint: UPLO='U' or 'L'.
3:   N – INTEGERInput
On entry: n, the order of the matrices A and B.
Constraint: N≥0.
4:   KA – INTEGERInput
On entry: if UPLO='U', the number of superdiagonals, ka, of the matrix A.
If UPLO='L', the number of subdiagonals, ka, of the matrix A.
Constraint: KA≥0.
5:   KB – INTEGERInput
On entry: if UPLO='U', the number of superdiagonals, kb, of the matrix B.
If UPLO='L', the number of subdiagonals, kb, of the matrix B.
Constraint: KA≥KB≥0.
6:   AB LDAB* – COMPLEX (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array AB must be at least max 1,N.
On entry: the upper or lower triangle of the n by n Hermitian band matrix A.
The matrix is stored in rows 1 to ka+1, more precisely,
  • if UPLO='U', the elements of the upper triangle of A within the band must be stored with element A ij in AB ka+1+i-j j​ for ​max 1,j-ka≤i≤j;
  • if UPLO='L', the elements of the lower triangle of A within the band must be stored with element A ij in AB 1+i-j j​ for ​j≤i≤min n,j+ka.
On exit: the contents of AB are overwritten.
7:   LDAB – INTEGERInput
On entry: the first dimension of the array AB as declared in the (sub)program from which F08UNF (ZHBGV) is called.
Constraint: LDAB≥KA+1.
8:   BB LDBB* – COMPLEX (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array BB must be at least max 1,N.
On entry: the upper or lower triangle of the n by n Hermitian band matrix B.
The matrix is stored in rows 1 to kb+1, more precisely,
  • if UPLO='U', the elements of the upper triangle of B within the band must be stored with element B ij in BB kb+1+i-j j​ for ​max 1,j-kb≤i≤j;
  • if UPLO='L', the elements of the lower triangle of B within the band must be stored with element B ij in BB 1+i-j j​ for ​j≤i≤min n,j+kb.
On exit: the factor S from the split Cholesky factorization B=SH S, as returned by F08UTF (ZPBSTF).
9:   LDBB – INTEGERInput
On entry: the first dimension of the array BB as declared in the (sub)program from which F08UNF (ZHBGV) is called.
Constraint: LDBB≥KB+1.
10:   W N – REAL (KIND=nag_wp) arrayOutput
On exit: the eigenvalues in ascending order.
11:   Z LDZ* – COMPLEX (KIND=nag_wp) arrayOutput
Note: the second dimension of the array Z must be at least max 1,N if JOBZ='V', and at least 1 otherwise.
On exit: if JOBZ='V', Z contains the matrix Z of eigenvectors, with the ith column of Z holding the eigenvector associated with W i. The eigenvectors are normalized so that ZH BZ=I.
If JOBZ='N', Z is not referenced.
12:   LDZ – INTEGERInput
On entry: the first dimension of the array Z as declared in the (sub)program from which F08UNF (ZHBGV) is called.
Constraints:
  • if JOBZ='V', LDZ≥ max 1,N ;
  • otherwise LDZ≥1.
13:   WORK N – COMPLEX (KIND=nag_wp) arrayWorkspace
14:   RWORK 3×N – REAL (KIND=nag_wp) arrayWorkspace
15:   INFO – INTEGEROutput
On exit: INFO=0 unless the routine detects an error (see Section 6).

6 Error Indicators and Warnings

INFO<0
If INFO=-i, argument i had an illegal value. An explanatory message is output, and execution of the program is terminated.
INFO>0
If INFO=i and i≤N, the algorithm failed to converge; i off-diagonal elements of an intermediate tridiagonal form did not converge to zero.
If INFO=i and i>N, if INFO=N+i, for 1≤i≤N, then F08UTF (ZPBSTF) returned INFO=i: B is not positive definite. The factorization of B could not be completed and no eigenvalues or eigenvectors were computed.

7 Accuracy

If B is ill-conditioned with respect to inversion, then the error bounds for the computed eigenvalues and vectors may be large, although when the diagonal elements of B differ widely in magnitude the eigenvalues and eigenvectors may be less sensitive than the condition of B would suggest. See Section 4.10 of Anderson et al. (1999) for details of the error bounds.

8 Parallelism and Performance

F08UNF (ZHBGV) is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
F08UNF (ZHBGV) makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The total number of floating-point operations is proportional to n 3 if JOBZ='V' and, assuming that n≫ka , is approximately proportional to n 2 ka otherwise.
The real analogue of this routine is F08UAF (DSBGV).

10 Example

This example finds all the eigenvalues of the generalized band Hermitian eigenproblem Az = λ Bz , where
A = -1.13 i+0.00 1.94-2.10 i -1.40+0.25 i 0.00i+0.00 1.94+2.10 i -1.91 i+0.00 -0.82-0.89 i -0.67+0.34 i -1.40-0.25 i -0.82+0.89 i -1.87 i+0.00 -1.10-0.16 i 0.00i+0.00 -0.67-0.34 i -1.10+0.16 i 0.50 i+0.00
and
B = 9.89 i+0.00 1.08-1.73 i 0.00i+0.00 0.00i+0.00 1.08+1.73 i 1.69 i+0.00 -0.04+0.29 i 0.00i+0.00 0.00i+0.00 -0.04-0.29 i 2.65 i+0.00 -0.33+2.24 i 0.00i+0.00 0.00i+0.00 -0.33-2.24 i 2.17 i+0.00 .

10.1 Program Text

Program Text (f08unfe.f90)

10.2 Program Data

Program Data (f08unfe.d)

10.3 Program Results

Program Results (f08unfe.r)

F08 Chapter Contents
F08 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F08UPF (ZHBGVX) : NAG Library, Mark 26

F08 Chapter Contents
F08 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F08UPF (ZHBGVX)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F08UPF (ZHBGVX) computes selected the eigenvalues and, optionally, the eigenvectors of a complex generalized Hermitian-definite banded eigenproblem, of the form
Az=λBz ,
where A and B are Hermitian and banded, and B is also positive definite. Eigenvalues and eigenvectors can be selected by specifying either all eigenvalues, a range of values or a range of indices for the desired eigenvalues.

2 Specification

SUBROUTINE F08UPF ( JOBZ, RANGE, UPLO, N, KA, KB, AB, LDAB, BB, LDBB, Q, LDQ, VL, VU, IL, IU, ABSTOL, M, W, Z, LDZ, WORK, RWORK, IWORK, JFAIL, INFO)
INTEGER | N, KA, KB, LDAB, LDBB, LDQ, IL, IU, M, LDZ, IWORK(5*N), JFAIL(*), INFO
REAL (KIND=nag_wp) | VL, VU, ABSTOL, W(N), RWORK(7*N)
COMPLEX (KIND=nag_wp) | AB(LDAB,*), BB(LDBB,*), Q(LDQ,*), Z(LDZ,*), WORK(N)
CHARACTER(1) | JOBZ, RANGE, UPLO
The routine may be called by its LAPACK name zhbgvx.

3 Description

The generalized Hermitian-definite band problem
Az = λ Bz
is first reduced to a standard band Hermitian problem
Cx = λx ,
where C is a Hermitian band matrix, using Wilkinson's modification to Crawford's algorithm (see Crawford (1973) and Wilkinson (1977)). The Hermitian eigenvalue problem is then solved for the required eigenvalues and eigenvectors, and the eigenvectors are then backtransformed to the eigenvectors of the original problem.
The eigenvectors are normalized so that
zH A z = λ   and   zH B z = 1 .

4 References

Anderson E, Bai Z, Bischof C, Blackford S, Demmel J, Dongarra J J, Du Croz J J, Greenbaum A, Hammarling S, McKenney A and Sorensen D (1999) LAPACK Users' Guide (3rd Edition) SIAM, Philadelphia http://www.netlib.org/lapack/lug
Crawford C R (1973) Reduction of a band-symmetric generalized eigenvalue problem Comm. ACM 16 41–44
Demmel J W and Kahan W (1990) Accurate singular values of bidiagonal matrices SIAM J. Sci. Statist. Comput. 11 873–912
Golub G H and Van Loan C F (1996) Matrix Computations (3rd Edition) Johns Hopkins University Press, Baltimore
Wilkinson J H (1977) Some recent advances in numerical linear algebra The State of the Art in Numerical Analysis (ed D A H Jacobs) Academic Press

5 Arguments

1:   JOBZ – CHARACTER(1)Input
On entry: indicates whether eigenvectors are computed.
JOBZ='N'
Only eigenvalues are computed.
JOBZ='V'
Eigenvalues and eigenvectors are computed.
Constraint: JOBZ='N' or 'V'.
2:   RANGE – CHARACTER(1)Input
On entry: if RANGE='A', all eigenvalues will be found.
If RANGE='V', all eigenvalues in the half-open interval VL,VU will be found.
If RANGE='I', the ILth to IUth eigenvalues will be found.
Constraint: RANGE='A', 'V' or 'I'.
3:   UPLO – CHARACTER(1)Input
On entry: if UPLO='U', the upper triangles of A and B are stored.
If UPLO='L', the lower triangles of A and B are stored.
Constraint: UPLO='U' or 'L'.
4:   N – INTEGERInput
On entry: n, the order of the matrices A and B.
Constraint: N≥0.
5:   KA – INTEGERInput
On entry: if UPLO='U', the number of superdiagonals, ka, of the matrix A.
If UPLO='L', the number of subdiagonals, ka, of the matrix A.
Constraint: KA≥0.
6:   KB – INTEGERInput
On entry: if UPLO='U', the number of superdiagonals, kb, of the matrix B.
If UPLO='L', the number of subdiagonals, kb, of the matrix B.
Constraint: KA≥KB≥0.
7:   AB LDAB* – COMPLEX (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array AB must be at least max 1,N.
On entry: the upper or lower triangle of the n by n Hermitian band matrix A.
The matrix is stored in rows 1 to ka+1, more precisely,
  • if UPLO='U', the elements of the upper triangle of A within the band must be stored with element A ij in AB ka+1+i-j j​ for ​max 1,j-ka≤i≤j;
  • if UPLO='L', the elements of the lower triangle of A within the band must be stored with element A ij in AB 1+i-j j​ for ​j≤i≤min n,j+ka.
On exit: the contents of AB are overwritten.
8:   LDAB – INTEGERInput
On entry: the first dimension of the array AB as declared in the (sub)program from which F08UPF (ZHBGVX) is called.
Constraint: LDAB≥KA+1.
9:   BB LDBB* – COMPLEX (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array BB must be at least max 1,N.
On entry: the upper or lower triangle of the n by n Hermitian positive definite band matrix B.
The matrix is stored in rows 1 to kb+1, more precisely,
  • if UPLO='U', the elements of the upper triangle of B within the band must be stored with element B ij in BB kb+1+i-j j​ for ​max 1,j-kb≤i≤j;
  • if UPLO='L', the elements of the lower triangle of B within the band must be stored with element B ij in BB 1+i-j j​ for ​j≤i≤min n,j+kb.
On exit: the factor S from the split Cholesky factorization B=SH S, as returned by F08UTF (ZPBSTF).
10:   LDBB – INTEGERInput
On entry: the first dimension of the array BB as declared in the (sub)program from which F08UPF (ZHBGVX) is called.
Constraint: LDBB≥KB+1.
11:   Q LDQ* – COMPLEX (KIND=nag_wp) arrayOutput
Note: the second dimension of the array Q must be at least max 1,N if JOBZ='V', and at least 1 otherwise.
On exit: if JOBZ='V', the n by n matrix, Q used in the reduction of the standard form, i.e., Cx=λx, from symmetric banded to tridiagonal form.
If JOBZ='N', Q is not referenced.
12:   LDQ – INTEGERInput
On entry: the first dimension of the array Q as declared in the (sub)program from which F08UPF (ZHBGVX) is called.
Constraints:
  • if JOBZ='V', LDQ≥ max 1,N ;
  • otherwise LDQ≥1.
13:   VL – REAL (KIND=nag_wp)Input
14:   VU – REAL (KIND=nag_wp)Input
On entry: if RANGE='V', the lower and upper bounds of the interval to be searched for eigenvalues.
If RANGE='A' or 'I', VL and VU are not referenced.
Constraint: if RANGE='V', VL<VU.
15:   IL – INTEGERInput
16:   IU – INTEGERInput
On entry: if RANGE='I', the indices (in ascending order) of the smallest and largest eigenvalues to be returned.
If RANGE='A' or 'V', IL and IU are not referenced.
Constraints:
  • if RANGE='I' and N=0, IL=1 and IU=0;
  • if RANGE='I' and N>0, 1≤ IL≤ IU≤ N .
17:   ABSTOL – REAL (KIND=nag_wp)Input
On entry: the absolute error tolerance for the eigenvalues. An approximate eigenvalue is accepted as converged when it is determined to lie in an interval a,b of width less than or equal to
ABSTOL+ε max a,b ,
where ε is the machine precision. If ABSTOL is less than or equal to zero, then ε T 1 will be used in its place, where T is the tridiagonal matrix obtained by reducing C to tridiagonal form. Eigenvalues will be computed most accurately when ABSTOL is set to twice the underflow threshold 2 × X02AMF , not zero. If this routine returns with INFO=1 to N, indicating that some eigenvectors did not converge, try setting ABSTOL to 2 × X02AMF . See Demmel and Kahan (1990).
18:   M – INTEGEROutput
On exit: the total number of eigenvalues found. 0≤M≤N.
If RANGE='A', M=N.
If RANGE='I', M=IU-IL+1.
19:   W N – REAL (KIND=nag_wp) arrayOutput
On exit: the eigenvalues in ascending order.
20:   Z LDZ* – COMPLEX (KIND=nag_wp) arrayOutput
Note: the second dimension of the array Z must be at least max 1,N if JOBZ='V', and at least 1 otherwise.
On exit: if JOBZ='V', Z contains the matrix Z of eigenvectors, with the ith column of Z holding the eigenvector associated with W i. The eigenvectors are normalized so that ZH BZ=I.
If JOBZ='N', Z is not referenced.
21:   LDZ – INTEGERInput
On entry: the first dimension of the array Z as declared in the (sub)program from which F08UPF (ZHBGVX) is called.
Constraints:
  • if JOBZ='V', LDZ≥ max 1,N ;
  • otherwise LDZ≥1.
22:   WORK N – COMPLEX (KIND=nag_wp) arrayWorkspace
23:   RWORK 7×N – REAL (KIND=nag_wp) arrayWorkspace
24:   IWORK 5×N – INTEGER arrayWorkspace
25:   JFAIL* – INTEGER arrayOutput
Note: the dimension of the array JFAIL must be at least max 1,N.
On exit: if JOBZ='V', then
  • if INFO=0, the first M elements of JFAIL are zero;
  • if INFO=1 to N, JFAIL contains the indices of the eigenvectors that failed to converge.
If JOBZ='N', JFAIL is not referenced.
26:   INFO – INTEGEROutput
On exit: INFO=0 unless the routine detects an error (see Section 6).

6 Error Indicators and Warnings

INFO<0
If INFO=-i, argument i had an illegal value. An explanatory message is output, and execution of the program is terminated.
INFO=1 to N
If INFO=i, then i eigenvectors failed to converge. Their indices are stored in array JFAIL. Please see ABSTOL.
INFO>N
F08UFF (DPBSTF) returned an error code; i.e., if INFO=N+i, for 1≤i≤N, then the leading minor of order i of B is not positive definite. The factorization of B could not be completed and no eigenvalues or eigenvectors were computed.

7 Accuracy

If B is ill-conditioned with respect to inversion, then the error bounds for the computed eigenvalues and vectors may be large, although when the diagonal elements of B differ widely in magnitude the eigenvalues and eigenvectors may be less sensitive than the condition of B would suggest. See Section 4.10 of Anderson et al. (1999) for details of the error bounds.

8 Parallelism and Performance

F08UPF (ZHBGVX) is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
F08UPF (ZHBGVX) makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The total number of floating-point operations is proportional to n 3 if JOBZ='V' and RANGE='A', and assuming that n≫ka , is approximately proportional to n 2 ka if JOBZ='N'. Otherwise the number of floating-point operations depends upon the number of eigenvectors computed.
The real analogue of this routine is F08UBF (DSBGVX).

10 Example

This example finds the eigenvalues in the half-open interval 0.0,2.0 , and corresponding eigenvectors, of the generalized band Hermitian eigenproblem Az = λ Bz , where
A = -1.13 i+0.00 1.94-2.10 i -1.40+0.25 i 0.00i+0.00 1.94+2.10 i -1.91 i+0.00 -0.82-0.89 i -0.67+0.34 i -1.40-0.25 i -0.82+0.89 i -1.87 i+0.00 -1.10-0.16 i 0.00i+0.00 -0.67-0.34 i -1.10+0.16 i 0.50 i+0.00
and
B = 9.89 i+0.00 1.08-1.73 i 0.00i+0.00 0.00i+0.00 1.08+1.73 i 1.69 i+0.00 -0.04+0.29 i 0.00i+0.00 0.00i+0.00 -0.04-0.29 i 2.65 i+0.00 -0.33+2.24 i 0.00i+0.00 0.00i+0.00 -0.33-2.24 i 2.17 i+0.00 .

10.1 Program Text

Program Text (f08upfe.f90)

10.2 Program Data

Program Data (f08upfe.d)

10.3 Program Results

Program Results (f08upfe.r)

F08 Chapter Contents
F08 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F08UQF (ZHBGVD) : NAG Library, Mark 26

F08 Chapter Contents
F08 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F08UQF (ZHBGVD)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F08UQF (ZHBGVD) computes all the eigenvalues and, optionally, the eigenvectors of a complex generalized Hermitian-definite banded eigenproblem, of the form
Az=λBz ,
where A and B are Hermitian and banded, and B is also positive definite. If eigenvectors are desired, it uses a divide-and-conquer algorithm.

2 Specification

SUBROUTINE F08UQF ( JOBZ, UPLO, N, KA, KB, AB, LDAB, BB, LDBB, W, Z, LDZ, WORK, LWORK, RWORK, LRWORK, IWORK, LIWORK, INFO)
INTEGER | N, KA, KB, LDAB, LDBB, LDZ, LWORK, LRWORK, IWORK(max(1,LIWORK)), LIWORK, INFO
REAL (KIND=nag_wp) | W(N), RWORK(max(1,LRWORK))
COMPLEX (KIND=nag_wp) | AB(LDAB,*), BB(LDBB,*), Z(LDZ,*), WORK(max(1,LWORK))
CHARACTER(1) | JOBZ, UPLO
The routine may be called by its LAPACK name zhbgvd.

3 Description

The generalized Hermitian-definite band problem
Az = λ Bz
is first reduced to a standard band Hermitian problem
Cx = λx ,
where C is a Hermitian band matrix, using Wilkinson's modification to Crawford's algorithm (see Crawford (1973) and Wilkinson (1977)). The Hermitian eigenvalue problem is then solved for the eigenvalues and the eigenvectors, if required, which are then backtransformed to the eigenvectors of the original problem.
The eigenvectors are normalized so that the matrix of eigenvectors, Z, satisfies
ZH A Z = Λ   and   ZH B Z = I ,
where Λ is the diagonal matrix whose diagonal elements are the eigenvalues.

4 References

Anderson E, Bai Z, Bischof C, Blackford S, Demmel J, Dongarra J J, Du Croz J J, Greenbaum A, Hammarling S, McKenney A and Sorensen D (1999) LAPACK Users' Guide (3rd Edition) SIAM, Philadelphia http://www.netlib.org/lapack/lug
Crawford C R (1973) Reduction of a band-symmetric generalized eigenvalue problem Comm. ACM 16 41–44
Golub G H and Van Loan C F (1996) Matrix Computations (3rd Edition) Johns Hopkins University Press, Baltimore
Wilkinson J H (1977) Some recent advances in numerical linear algebra The State of the Art in Numerical Analysis (ed D A H Jacobs) Academic Press

5 Arguments

1:   JOBZ – CHARACTER(1)Input
On entry: indicates whether eigenvectors are computed.
JOBZ='N'
Only eigenvalues are computed.
JOBZ='V'
Eigenvalues and eigenvectors are computed.
Constraint: JOBZ='N' or 'V'.
2:   UPLO – CHARACTER(1)Input
On entry: if UPLO='U', the upper triangles of A and B are stored.
If UPLO='L', the lower triangles of A and B are stored.
Constraint: UPLO='U' or 'L'.
3:   N – INTEGERInput
On entry: n, the order of the matrices A and B.
Constraint: N≥0.
4:   KA – INTEGERInput
On entry: if UPLO='U', the number of superdiagonals, ka, of the matrix A.
If UPLO='L', the number of subdiagonals, ka, of the matrix A.
Constraint: KA≥0.
5:   KB – INTEGERInput
On entry: if UPLO='U', the number of superdiagonals, kb, of the matrix B.
If UPLO='L', the number of subdiagonals, kb, of the matrix B.
Constraint: KA≥KB≥0.
6:   AB LDAB* – COMPLEX (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array AB must be at least max 1,N.
On entry: the upper or lower triangle of the n by n Hermitian band matrix A.
The matrix is stored in rows 1 to ka+1, more precisely,
  • if UPLO='U', the elements of the upper triangle of A within the band must be stored with element A ij in AB ka+1+i-j j​ for ​max 1,j-ka≤i≤j;
  • if UPLO='L', the elements of the lower triangle of A within the band must be stored with element A ij in AB 1+i-j j​ for ​j≤i≤min n,j+ka.
On exit: the contents of AB are overwritten.
7:   LDAB – INTEGERInput
On entry: the first dimension of the array AB as declared in the (sub)program from which F08UQF (ZHBGVD) is called.
Constraint: LDAB≥KA+1.
8:   BB LDBB* – COMPLEX (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array BB must be at least max 1,N.
On entry: the upper or lower triangle of the n by n Hermitian band matrix B.
The matrix is stored in rows 1 to kb+1, more precisely,
  • if UPLO='U', the elements of the upper triangle of B within the band must be stored with element B ij in BB kb+1+i-j j​ for ​max 1,j-kb≤i≤j;
  • if UPLO='L', the elements of the lower triangle of B within the band must be stored with element B ij in BB 1+i-j j​ for ​j≤i≤min n,j+kb.
On exit: the factor S from the split Cholesky factorization B=SH S, as returned by F08UTF (ZPBSTF).
9:   LDBB – INTEGERInput
On entry: the first dimension of the array BB as declared in the (sub)program from which F08UQF (ZHBGVD) is called.
Constraint: LDBB≥KB+1.
10:   W N – REAL (KIND=nag_wp) arrayOutput
On exit: the eigenvalues in ascending order.
11:   Z LDZ* – COMPLEX (KIND=nag_wp) arrayOutput
Note: the second dimension of the array Z must be at least max 1,N if JOBZ='V', and at least 1 otherwise.
On exit: if JOBZ='V', Z contains the matrix Z of eigenvectors, with the ith column of Z holding the eigenvector associated with W i. The eigenvectors are normalized so that ZH BZ=I.
If JOBZ='N', Z is not referenced.
12:   LDZ – INTEGERInput
On entry: the first dimension of the array Z as declared in the (sub)program from which F08UQF (ZHBGVD) is called.
Constraints:
  • if JOBZ='V', LDZ≥ max 1,N ;
  • otherwise LDZ≥1.
13:   WORK max 1,LWORK – COMPLEX (KIND=nag_wp) arrayWorkspace
On exit: if INFO=0, the real part of WORK 1 contains the minimum value of LWORK required for optimal performance.
14:   LWORK – INTEGERInput
On entry: the dimension of the array WORK as declared in the (sub)program from which F08UQF (ZHBGVD) is called.
If LWORK=-1, a workspace query is assumed; the routine only calculates the optimal sizes of the WORK, RWORK and IWORK arrays, returns these values as the first entries of the WORK, RWORK and IWORK arrays, and no error message related to LWORK, LRWORK or LIWORK is issued.
Constraints:
  • if N≤1, LWORK≥1;
  • if JOBZ='N' and N>1, LWORK≥max 1,N;
  • if JOBZ='V' and N>1, LWORK≥max 1,N 2.
15:   RWORK max 1,LRWORK – REAL (KIND=nag_wp) arrayWorkspace
On exit: if INFO=0, RWORK 1 returns the optimal LRWORK.
16:   LRWORK – INTEGERInput
On entry: the first dimension of the array RWORK as declared in the (sub)program from which F08UQF (ZHBGVD) is called.
If LRWORK=-1, a workspace query is assumed; the routine only calculates the optimal sizes of the WORK, RWORK and IWORK arrays, returns these values as the first entries of the WORK, RWORK and IWORK arrays, and no error message related to LWORK, LRWORK or LIWORK is issued.
Constraints:
  • if N≤1, LRWORK≥1;
  • if JOBZ='N' and N>1, LRWORK≥max 1,N;
  • if JOBZ='V' and N>1, LRWORK≥1+5×N+2×N 2.
17:   IWORK max 1,LIWORK – INTEGER arrayWorkspace
On exit: if INFO=0, IWORK 1 returns the optimal LIWORK.
18:   LIWORK – INTEGERInput
On entry: the dimension of the array IWORK as declared in the (sub)program from which F08UQF (ZHBGVD) is called.
If LIWORK=-1, a workspace query is assumed; the routine only calculates the optimal sizes of the WORK, RWORK and IWORK arrays, returns these values as the first entries of the WORK, RWORK and IWORK arrays, and no error message related to LWORK, LRWORK or LIWORK is issued.
Constraints:
  • if JOBZ='N' or N≤1, LIWORK≥1;
  • if JOBZ='V' and N>1, LIWORK≥3+5×N.
19:   INFO – INTEGEROutput
On exit: INFO=0 unless the routine detects an error (see Section 6).

6 Error Indicators and Warnings

INFO<0
If INFO=-i, argument i had an illegal value. An explanatory message is output, and execution of the program is terminated.
INFO>0
If INFO=i and i≤N, the algorithm failed to converge; i off-diagonal elements of an intermediate tridiagonal form did not converge to zero.
If INFO=i and i>N, if INFO=N+i, for 1≤i≤N, then F08UTF (ZPBSTF) returned INFO=i: B is not positive definite. The factorization of B could not be completed and no eigenvalues or eigenvectors were computed.

7 Accuracy

If B is ill-conditioned with respect to inversion, then the error bounds for the computed eigenvalues and vectors may be large, although when the diagonal elements of B differ widely in magnitude the eigenvalues and eigenvectors may be less sensitive than the condition of B would suggest. See Section 4.10 of Anderson et al. (1999) for details of the error bounds.

8 Parallelism and Performance

F08UQF (ZHBGVD) is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
F08UQF (ZHBGVD) makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The total number of floating-point operations is proportional to n 3 if JOBZ='V' and, assuming that n≫ka , is approximately proportional to n 2 ka otherwise.
The real analogue of this routine is F08UCF (DSBGVD).

10 Example

This example finds all the eigenvalues of the generalized band Hermitian eigenproblem Az = λ Bz , where
A = -1.13 i+0.00 1.94-2.10 i -1.40+0.25 i 0.00i+0.00 1.94+2.10 i -1.91 i+0.00 -0.82-0.89 i -0.67+0.34 i -1.40-0.25 i -0.82+0.89 i -1.87 i+0.00 -1.10-0.16 i 0.00i+0.00 -0.67-0.34 i -1.10+0.16 i 0.50 i+0.00
and
B = 9.89 i+0.00 1.08-1.73 i 0.00i+0.00 0.00i+0.00 1.08+1.73 i 1.69 i+0.00 -0.04+0.29 i 0.00i+0.00 0.00i+0.00 -0.04-0.29 i 2.65 i+0.00 -0.33+2.24 i 0.00i+0.00 0.00i+0.00 -0.33-2.24 i 2.17 i+0.00 .

10.1 Program Text

Program Text (f08uqfe.f90)

10.2 Program Data

Program Data (f08uqfe.d)

10.3 Program Results

Program Results (f08uqfe.r)

F08 Chapter Contents
F08 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F08USF (ZHBGST) : NAG Library, Mark 26

F08 Chapter Contents
F08 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F08USF (ZHBGST)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F08USF (ZHBGST) reduces a complex Hermitian-definite generalized eigenproblem Az=λBz to the standard form Cy=λy, where A and B are band matrices, A is a complex Hermitian matrix, and B has been factorized by F08UTF (ZPBSTF).

2 Specification

SUBROUTINE F08USF ( VECT, UPLO, N, KA, KB, AB, LDAB, BB, LDBB, X, LDX, WORK, RWORK, INFO)
INTEGER | N, KA, KB, LDAB, LDBB, LDX, INFO
REAL (KIND=nag_wp) | RWORK(N)
COMPLEX (KIND=nag_wp) | AB(LDAB,*), BB(LDBB,*), X(LDX,*), WORK(N)
CHARACTER(1) | VECT, UPLO
The routine may be called by its LAPACK name zhbgst.

3 Description

To reduce the complex Hermitian-definite generalized eigenproblem Az=λBz to the standard form Cy=λy, where A, B and C are banded, F08USF (ZHBGST) must be preceded by a call to F08UTF (ZPBSTF) which computes the split Cholesky factorization of the positive definite matrix B: B=SH S. The split Cholesky factorization, compared with the ordinary Cholesky factorization, allows the work to be approximately halved.
This routine overwrites A with C=XH AX, where X=S-1 Q and Q is a unitary matrix chosen (implicitly) to preserve the bandwidth of A. The routine also has an option to allow the accumulation of X, and then, if z is an eigenvector of C, Xz is an eigenvector of the original system.

4 References

Crawford C R (1973) Reduction of a band-symmetric generalized eigenvalue problem Comm. ACM 16 41–44
Kaufman L (1984) Banded eigenvalue solvers on vector machines ACM Trans. Math. Software 10 73–86

5 Arguments

1:   VECT – CHARACTER(1)Input
On entry: indicates whether X is to be returned.
VECT='N'
X is not returned.
VECT='V'
X is returned.
Constraint: VECT='N' or 'V'.
2:   UPLO – CHARACTER(1)Input
On entry: indicates whether the upper or lower triangular part of A is stored.
UPLO='U'
The upper triangular part of A is stored.
UPLO='L'
The lower triangular part of A is stored.
Constraint: UPLO='U' or 'L'.
3:   N – INTEGERInput
On entry: n, the order of the matrices A and B.
Constraint: N≥0.
4:   KA – INTEGERInput
On entry: if UPLO='U', the number of superdiagonals, ka, of the matrix A.
If UPLO='L', the number of subdiagonals, ka, of the matrix A.
Constraint: KA≥0.
5:   KB – INTEGERInput
On entry: if UPLO='U', the number of superdiagonals, kb, of the matrix B.
If UPLO='L', the number of subdiagonals, kb, of the matrix B.
Constraint: KA≥KB≥0.
6:   AB LDAB* – COMPLEX (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array AB must be at least max 1,N.
On entry: the upper or lower triangle of the n by n Hermitian band matrix A.
The matrix is stored in rows 1 to ka+1, more precisely,
  • if UPLO='U', the elements of the upper triangle of A within the band must be stored with element A ij in AB ka+1+i-j j​ for ​max 1,j-ka≤i≤j;
  • if UPLO='L', the elements of the lower triangle of A within the band must be stored with element A ij in AB 1+i-j j​ for ​j≤i≤min n,j+ka.
On exit: the upper or lower triangle of AB is overwritten by the corresponding upper or lower triangle of C as specified by UPLO.
7:   LDAB – INTEGERInput
On entry: the first dimension of the array AB as declared in the (sub)program from which F08USF (ZHBGST) is called.
Constraint: LDAB≥KA+1.
8:   BB LDBB* – COMPLEX (KIND=nag_wp) arrayInput
Note: the second dimension of the array BB must be at least max 1,N.
On entry: the banded split Cholesky factor of B as specified by UPLO, N and KB and returned by F08UTF (ZPBSTF).
9:   LDBB – INTEGERInput
On entry: the first dimension of the array BB as declared in the (sub)program from which F08USF (ZHBGST) is called.
Constraint: LDBB≥KB+1.
10:   X LDX* – COMPLEX (KIND=nag_wp) arrayOutput
Note: the second dimension of the array X must be at least max 1,N if VECT='V' and at least 1 if VECT='N'.
On exit: the n by n matrix X=S-1 Q, if VECT='V'.
If VECT='N', X is not referenced.
11:   LDX – INTEGERInput
On entry: the first dimension of the array X as declared in the (sub)program from which F08USF (ZHBGST) is called.
Constraints:
  • if VECT='V', LDX≥ max 1,N ;
  • if VECT='N', LDX≥1.
12:   WORK N – COMPLEX (KIND=nag_wp) arrayWorkspace
13:   RWORK N – REAL (KIND=nag_wp) arrayWorkspace
14:   INFO – INTEGEROutput
On exit: INFO=0 unless the routine detects an error (see Section 6).

6 Error Indicators and Warnings

INFO<0
If INFO=-i, argument i had an illegal value. An explanatory message is output, and execution of the program is terminated.

7 Accuracy

Forming the reduced matrix C is a stable procedure. However it involves implicit multiplication by B-1. When F08USF (ZHBGST) is used as a step in the computation of eigenvalues and eigenvectors of the original problem, there may be a significant loss of accuracy if B is ill-conditioned with respect to inversion.

8 Parallelism and Performance

F08USF (ZHBGST) makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The total number of real floating-point operations is approximately 20 n 2 kB, when VECT='N', assuming n≫kA,kB; there are an additional 5 n 3 kB/kA operations when VECT='V'.
The real analogue of this routine is F08UEF (DSBGST).

10 Example

This example computes all the eigenvalues of Az=λBz, where
A = -1.13+0.00 i 1.94-2.10 i -1.40+0.25 i 0.00+0.00 i 1.94+2.10 i -1.91+0.00 i -0.82-0.89 i -0.67+0.34 i -1.40-0.25 i -0.82+0.89 i -1.87+0.00 i -1.10-0.16 i 0.00+0.00 i -0.67-0.34 i -1.10+0.16 i 0.50+0.00 i
and
B = 9.89+0.00 i 1.08-1.73 i 0.00+0.00 i 0.00+0.00 i 1.08+1.73 i 1.69+0.00 i -0.04+0.29 i 0.00+0.00 i 0.00+0.00 i -0.04-0.29 i 2.65+0.00 i -0.33+2.24 i 0.00+0.00 i 0.00+0.00 i -0.33-2.24 i 2.17+0.00 i .
Here A is Hermitian, B is Hermitian positive definite, and A and B are treated as band matrices. B must first be factorized by F08UTF (ZPBSTF). The program calls F08USF (ZHBGST) to reduce the problem to the standard form Cy=λy, then F08HSF (ZHBTRD) to reduce C to tridiagonal form, and F08JFF (DSTERF) to compute the eigenvalues.

10.1 Program Text

Program Text (f08usfe.f90)

10.2 Program Data

Program Data (f08usfe.d)

10.3 Program Results

Program Results (f08usfe.r)

F08 Chapter Contents
F08 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F08UTF (ZPBSTF) : NAG Library, Mark 26

F08 Chapter Contents
F08 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F08UTF (ZPBSTF)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
10 Example

1 Purpose

F08UTF (ZPBSTF) computes a split Cholesky factorization of a complex Hermitian positive definite band matrix.

2 Specification

SUBROUTINE F08UTF ( UPLO, N, KB, BB, LDBB, INFO)
INTEGER | N, KB, LDBB, INFO
COMPLEX (KIND=nag_wp) | BB(LDBB,*)
CHARACTER(1) | UPLO
The routine may be called by its LAPACK name zpbstf.

3 Description

F08UTF (ZPBSTF) computes a split Cholesky factorization of a complex Hermitian positive definite band matrix B. It is designed to be used in conjunction with F08USF (ZHBGST).
The factorization has the form B=SH S, where S is a band matrix of the same bandwidth as B and the following structure: S is upper triangular in the first n+k/2 rows, and transposed — hence, lower triangular — in the remaining rows. For example, if n=9 and k=2, then
S = s 11 s 12 s 13 s 22 s 23 s 24 s 33 s 34 s 35 s 44 s 45 s 55 s 64 s 65 s 66 s 75 s 76 s 77 s 86 s 87 s 88 s 97 s 98 s 99 .

4 References

None.

5 Arguments

1:   UPLO – CHARACTER(1)Input
On entry: indicates whether the upper or lower triangular part of B is stored.
UPLO='U'
The upper triangular part of B is stored.
UPLO='L'
The lower triangular part of B is stored.
Constraint: UPLO='U' or 'L'.
2:   N – INTEGERInput
On entry: n, the order of the matrix B.
Constraint: N≥0.
3:   KB – INTEGERInput
On entry: if UPLO='U', the number of superdiagonals, kb, of the matrix B.
If UPLO='L', the number of subdiagonals, kb, of the matrix B.
Constraint: KB≥0.
4:   BB LDBB* – COMPLEX (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array BB must be at least max 1,N.
On entry: the n by n Hermitian positive definite band matrix B.
The matrix is stored in rows 1 to kb+1, more precisely,
  • if UPLO='U', the elements of the upper triangle of B within the band must be stored with element B ij in BB kb+1+i-j j​ for ​max 1,j-kb≤i≤j;
  • if UPLO='L', the elements of the lower triangle of B within the band must be stored with element B ij in BB 1+i-j j​ for ​j≤i≤min n,j+kb.
On exit: B is overwritten by the elements of its split Cholesky factor S.
5:   LDBB – INTEGERInput
On entry: the first dimension of the array BB as declared in the (sub)program from which F08UTF (ZPBSTF) is called.
Constraint: LDBB≥KB+1.
6:   INFO – INTEGEROutput
On exit: INFO=0 unless the routine detects an error (see Section 6).

6 Error Indicators and Warnings

INFO<0
If INFO=-i, argument i had an illegal value. An explanatory message is output, and execution of the program is terminated.
INFO>0
If INFO=i, the factorization could not be completed, because the updated element b i,i would be the square root of a negative number. Hence B is not positive definite. This may indicate an error in forming the matrix B.

7 Accuracy

The computed factor S is the exact factor of a perturbed matrix B+E, where
E≤c k+1 ε SHS,
c k+1 is a modest linear function of k+1, and ε is the machine precision. It follows that e ij≤c k+1 ε⁢b iib jj.

8 Parallelism and Performance

F08UTF (ZPBSTF) makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The total number of floating-point operations is approximately 4 n k+1 2, assuming n≫k.
A call to F08UTF (ZPBSTF) may be followed by a call to F08USF (ZHBGST) to solve the generalized eigenproblem Az=λBz, where A and B are banded and B is positive definite.
The real analogue of this routine is F08UFF (DPBSTF).

10 Example

See Section 10 in F08USF (ZHBGST).
F08 Chapter Contents
F08 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F08VAF (DGGSVD) : NAG Library, Mark 26

F08 Chapter Contents
F08 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F08VAF (DGGSVD)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F08VAF (DGGSVD) computes the generalized singular value decomposition (GSVD) of an m by n real matrix A and a p by n real matrix B. F08VAF (DGGSVD) is marked as deprecated by LAPACK; the replacement routine is F08VCF (DGGSVD3) which makes better use of level 3 BLAS.

2 Specification

SUBROUTINE F08VAF ( JOBU, JOBV, JOBQ, M, N, P, K, L, A, LDA, B, LDB, ALPHA, BETA, U, LDU, V, LDV, Q, LDQ, WORK, IWORK, INFO)
INTEGER | M, N, P, K, L, LDA, LDB, LDU, LDV, LDQ, IWORK(N), INFO
REAL (KIND=nag_wp) | A(LDA,*), B(LDB,*), ALPHA(N), BETA(N), U(LDU,*), V(LDV,*), Q(LDQ,*), WORK(max(3*N,M,P)+N)
CHARACTER(1) | JOBU, JOBV, JOBQ
The routine may be called by its LAPACK name dggsvd.

3 Description

The generalized singular value decomposition is given by
UT A Q = D 1 0 R ,   VT B Q = D 2 0 R ,
where U, V and Q are orthogonal matrices. Let k+l be the effective numerical rank of the matrix A B , then R is a k+l by k+l nonsingular upper triangular matrix, D 1 and D 2 are m by k+l and p by k+l ‘diagonal’ matrices structured as follows:
if m-k-l≥0,
D 1= klkI0l0Cm-k-l00()
D 2= kll0Sp-l00()
0R = n-k-lklk0R 11R 12l00R 22()
where
C = diag α k+1,…,α k+l ,
S = diag β k+1,…,β k+l ,
and
C 2 + S 2 = I .
R is stored as a submatrix of A with elements R ij stored as A i,n-k-l+j on exit.
If m-k-l<0 ,
D 1= km-kk+l-mkI00m-k0C0()
D 2= km-kk+l-mm-k0S0k+l-m00Ip-l000()
0R = n-k-lkm-kk+l-mk0R 11R 12R 13m-k00R 22R 23k+l-m000R 33()
where
C = diag α k+1,…,αm ,
S = diag β k+1,…,βm ,
and
C 2 + S 2 = I .
R 11 R 12 R 13 0 R 22 R 23 is stored as a submatrix of A with R ij stored as A i,n-k-l+j, and R 33 is stored as a submatrix of B with R 33 ij stored as B m-k+i,n+m-k-l+j.
The routine computes C, S, R and, optionally, the orthogonal transformation matrices U, V and Q.
In particular, if B is an n by n nonsingular matrix, then the GSVD of A and B implicitly gives the SVD of A B-1:
A B-1 = U D 1 D 2-1 VT .
If A B has orthonormal columns, then the GSVD of A and B is also equal to the CS decomposition of A and B. Furthermore, the GSVD can be used to derive the solution of the eigenvalue problem:
AT Ax=λ BT Bx .
In some literature, the GSVD of A and B is presented in the form
UT A X = 0D 1 ,   VT B X = 0D 2 ,
where U and V are orthogonal and X is nonsingular, and D 1 and D 2 are ‘diagonal’. The former GSVD form can be converted to the latter form by taking the nonsingular matrix X as
X = Q I 0 0 R-1 .

4 References

Anderson E, Bai Z, Bischof C, Blackford S, Demmel J, Dongarra J J, Du Croz J J, Greenbaum A, Hammarling S, McKenney A and Sorensen D (1999) LAPACK Users' Guide (3rd Edition) SIAM, Philadelphia http://www.netlib.org/lapack/lug
Golub G H and Van Loan C F (1996) Matrix Computations (3rd Edition) Johns Hopkins University Press, Baltimore

5 Arguments

1:   JOBU – CHARACTER(1)Input
On entry: if JOBU='U', the orthogonal matrix U is computed.
If JOBU='N', U is not computed.
Constraint: JOBU='U' or 'N'.
2:   JOBV – CHARACTER(1)Input
On entry: if JOBV='V', the orthogonal matrix V is computed.
If JOBV='N', V is not computed.
Constraint: JOBV='V' or 'N'.
3:   JOBQ – CHARACTER(1)Input
On entry: if JOBQ='Q', the orthogonal matrix Q is computed.
If JOBQ='N', Q is not computed.
Constraint: JOBQ='Q' or 'N'.
4:   M – INTEGERInput
On entry: m, the number of rows of the matrix A.
Constraint: M≥0.
5:   N – INTEGERInput
On entry: n, the number of columns of the matrices A and B.
Constraint: N≥0.
6:   P – INTEGERInput
On entry: p, the number of rows of the matrix B.
Constraint: P≥0.
7:   K – INTEGEROutput
8:   L – INTEGEROutput
On exit: K and L specify the dimension of the subblocks k and l as described in Section 3; k+l is the effective numerical rank of AB.
9:   A LDA* – REAL (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array A must be at least max 1,N.
On entry: the m by n matrix A.
On exit: contains the triangular matrix R, or part of R. See Section 3 for details.
10:   LDA – INTEGERInput
On entry: the first dimension of the array A as declared in the (sub)program from which F08VAF (DGGSVD) is called.
Constraint: LDA≥max 1,M.
11:   B LDB* – REAL (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array B must be at least max 1,N.
On entry: the p by n matrix B.
On exit: contains the triangular matrix R if m-k-l<0. See Section 3 for details.
12:   LDB – INTEGERInput
On entry: the first dimension of the array B as declared in the (sub)program from which F08VAF (DGGSVD) is called.
Constraint: LDB≥max 1,P.
13:   ALPHA N – REAL (KIND=nag_wp) arrayOutput
On exit: see the description of BETA.
14:   BETA N – REAL (KIND=nag_wp) arrayOutput
On exit: ALPHA and BETA contain the generalized singular value pairs of A and B, αi and βi ;
  • ALPHA 1:K = 1 ,
  • BETA 1:K = 0 ,
and if m-k-l≥0 ,
  • ALPHA K+1:K+L = C ,
  • BETA K+1:K+L = S ,
or if m-k-l<0 ,
  • ALPHA K+1:M = C ,
  • ALPHA M+1:K+L = 0 ,
  • BETA K+1:M = S ,
  • BETA M+1:K+L = 1 , and
  • ALPHA K+L+1:N = 0 ,
  • BETA K+L+1:N = 0 .
The notation ALPHA K:N above refers to consecutive elements ALPHA i, for i=K,…,N.
15:   U LDU* – REAL (KIND=nag_wp) arrayOutput
Note: the second dimension of the array U must be at least max 1,M if JOBU='U', and at least 1 otherwise.
On exit: if JOBU='U', U contains the m by m orthogonal matrix U.
If JOBU='N', U is not referenced.
16:   LDU – INTEGERInput
On entry: the first dimension of the array U as declared in the (sub)program from which F08VAF (DGGSVD) is called.
Constraints:
  • if JOBU='U', LDU≥ max 1,M ;
  • otherwise LDU≥1.
17:   V LDV* – REAL (KIND=nag_wp) arrayOutput
Note: the second dimension of the array V must be at least max 1,P if JOBV='V', and at least 1 otherwise.
On exit: if JOBV='V', V contains the p by p orthogonal matrix V.
If JOBV='N', V is not referenced.
18:   LDV – INTEGERInput
On entry: the first dimension of the array V as declared in the (sub)program from which F08VAF (DGGSVD) is called.
Constraints:
  • if JOBV='V', LDV≥ max 1,P ;
  • otherwise LDV≥1.
19:   Q LDQ* – REAL (KIND=nag_wp) arrayOutput
Note: the second dimension of the array Q must be at least max 1,N if JOBQ='Q', and at least 1 otherwise.
On exit: if JOBQ='Q', Q contains the n by n orthogonal matrix Q.
If JOBQ='N', Q is not referenced.
20:   LDQ – INTEGERInput
On entry: the first dimension of the array Q as declared in the (sub)program from which F08VAF (DGGSVD) is called.
Constraints:
  • if JOBQ='Q', LDQ≥ max 1,N ;
  • otherwise LDQ≥1.
21:   WORK max 3×N,M,P+N – REAL (KIND=nag_wp) arrayWorkspace
22:   IWORK N – INTEGER arrayOutput
On exit: stores the sorting information. More precisely, the following loop will sort ALPHA
 for I=K+1, min(M,K+L)
 swap ALPHA(I) and ALPHA(IWORK(I))
 endfor
such that ALPHA 1≥ALPHA 2≥⋯≥ALPHA N.
23:   INFO – INTEGEROutput
On exit: INFO=0 unless the routine detects an error (see Section 6).

6 Error Indicators and Warnings

INFO<0
If INFO=-i, argument i had an illegal value. An explanatory message is output, and execution of the program is terminated.
INFO=1
If INFO=1, the Jacobi-type procedure failed to converge.

7 Accuracy

The computed generalized singular value decomposition is nearly the exact generalized singular value decomposition for nearby matrices A+E and B+F , where
E 2 = O ε A 2 ​ and ​ F 2 = O ε B 2 ,
and ε is the machine precision. See Section 4.12 of Anderson et al. (1999) for further details.

8 Parallelism and Performance

F08VAF (DGGSVD) makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The complex analogue of this routine is F08VNF (ZGGSVD).

10 Example

This example finds the generalized singular value decomposition
A = U Σ 1 0R QT ,   B = V Σ 2 0R QT ,
where
A = 1 2 3 3 2 1 4 5 6 7 8 8   and   B = -2 -3 3 4 6 5 ,
together with estimates for the condition number of R and the error bound for the computed generalized singular values.
The example program assumes that m≥n, and would need slight modification if this is not the case.

10.1 Program Text

Program Text (f08vafe.f90)

10.2 Program Data

Program Data (f08vafe.d)

10.3 Program Results

Program Results (f08vafe.r)

F08 Chapter Contents
F08 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F08VCF (DGGSVD3) : NAG Library, Mark 26

F08 Chapter Contents
F08 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F08VCF (DGGSVD3)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F08VCF (DGGSVD3) computes the generalized singular value decomposition (GSVD) of an m by n real matrix A and a p by n real matrix B.

2 Specification

SUBROUTINE F08VCF ( JOBU, JOBV, JOBQ, M, N, P, K, L, A, LDA, B, LDB, ALPHA, BETA, U, LDU, V, LDV, Q, LDQ, WORK, LWORK, IWORK, INFO)
INTEGER | M, N, P, K, L, LDA, LDB, LDU, LDV, LDQ, LWORK, IWORK(N), INFO
REAL (KIND=nag_wp) | A(LDA,*), B(LDB,*), ALPHA(N), BETA(N), U(LDU,*), V(LDV,*), Q(LDQ,*), WORK(max(1,LWORK))
CHARACTER(1) | JOBU, JOBV, JOBQ
The routine may be called by its LAPACK name dggsvd3.

3 Description

Given an m by n real matrix A and a p by n real matrix B, the generalized singular value decomposition is given by
UT A Q = D 1 0 R ,   VT B Q = D 2 0 R ,
where U, V and Q are orthogonal matrices. Let l be the effective numerical rank of B and k+l be the effective numerical rank of the matrix A B , then the first k generalized singular values are infinite and the remaining l are finite. R is a k+l by k+l nonsingular upper triangular matrix, D 1 and D 2 are m by k+l and p by k+l ‘diagonal’ matrices structured as follows:
if m-k-l≥0,
D 1= klkI0l0Cm-k-l00()
D 2= kll0Sp-l00()
0R = n-k-lklk0R 11R 12l00R 22()
where
C = diag α k+1,…,α k+l ,
S = diag β k+1,…,β k+l ,
and
C 2 + S 2 = I .
R is stored as a submatrix of A with elements R ij stored as A i,n-k-l+j on exit.
If m-k-l<0 ,
D 1= km-kk+l-mkI00m-k0C0()
D 2= km-kk+l-mm-k0S0k+l-m00Ip-l000()
0R = n-k-lkm-kk+l-mk0R 11R 12R 13m-k00R 22R 23k+l-m000R 33()
where
C = diag α k+1,…,αm ,
S = diag β k+1,…,βm ,
and
C 2 + S 2 = I .
R 11 R 12 R 13 0 R 22 R 23 is stored as a submatrix of A with R ij stored as A i,n-k-l+j, and R 33 is stored as a submatrix of B with R 33 ij stored as B m-k+i,n+m-k-l+j.
The routine computes C, S, R and, optionally, the orthogonal transformation matrices U, V and Q.
In particular, if B is an n by n nonsingular matrix, then the GSVD of A and B implicitly gives the SVD of A B-1:
A B-1 = U D 1 D 2-1 VT .
If A B has orthonormal columns, then the GSVD of A and B is also equal to the CS decomposition of A and B. Furthermore, the GSVD can be used to derive the solution of the eigenvalue problem:
AT Ax=λ BT Bx .
In some literature, the GSVD of A and B is presented in the form
UT A X = 0D 1 ,   VT B X = 0D 2 ,
where U and V are orthogonal and X is nonsingular, and D 1 and D 2 are ‘diagonal’. The former GSVD form can be converted to the latter form by setting
X = Q I 0 0 R-1 .
A two stage process is used to compute the GSVD of the matrix pair A,B. The pair is first reduced to upper triangular form by orthogonal transformations using F08VGF (DGGSVP3). The GSVD of the resulting upper triangular matrix pair is then performed by F08YEF (DTGSJA) which uses a variant of the Kogbetliantz algorithm (a cyclic Jacobi method).

4 References

Anderson E, Bai Z, Bischof C, Blackford S, Demmel J, Dongarra J J, Du Croz J J, Greenbaum A, Hammarling S, McKenney A and Sorensen D (1999) LAPACK Users' Guide (3rd Edition) SIAM, Philadelphia http://www.netlib.org/lapack/lug
Golub G H and Van Loan C F (2012) Matrix Computations (4th Edition) Johns Hopkins University Press, Baltimore

5 Arguments

1:   JOBU – CHARACTER(1)Input
On entry: if JOBU='U', the orthogonal matrix U is computed.
If JOBU='N', U is not computed.
Constraint: JOBU='U' or 'N'.
2:   JOBV – CHARACTER(1)Input
On entry: if JOBV='V', the orthogonal matrix V is computed.
If JOBV='N', V is not computed.
Constraint: JOBV='V' or 'N'.
3:   JOBQ – CHARACTER(1)Input
On entry: if JOBQ='Q', the orthogonal matrix Q is computed.
If JOBQ='N', Q is not computed.
Constraint: JOBQ='Q' or 'N'.
4:   M – INTEGERInput
On entry: m, the number of rows of the matrix A.
Constraint: M≥0.
5:   N – INTEGERInput
On entry: n, the number of columns of the matrices A and B.
Constraint: N≥0.
6:   P – INTEGERInput
On entry: p, the number of rows of the matrix B.
Constraint: P≥0.
7:   K – INTEGEROutput
8:   L – INTEGEROutput
On exit: K and L specify the dimension of the subblocks k and l as described in Section 3; k+l is the effective numerical rank of AB.
9:   A LDA* – REAL (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array A must be at least max 1,N.
On entry: the m by n matrix A.
On exit: contains the triangular matrix R, or part of R. See Section 3 for details.
10:   LDA – INTEGERInput
On entry: the first dimension of the array A as declared in the (sub)program from which F08VCF (DGGSVD3) is called.
Constraint: LDA≥max 1,M.
11:   B LDB* – REAL (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array B must be at least max 1,N.
On entry: the p by n matrix B.
On exit: contains the triangular matrix R if m-k-l<0. See Section 3 for details.
12:   LDB – INTEGERInput
On entry: the first dimension of the array B as declared in the (sub)program from which F08VCF (DGGSVD3) is called.
Constraint: LDB≥max 1,P.
13:   ALPHA N – REAL (KIND=nag_wp) arrayOutput
On exit: see the description of BETA.
14:   BETA N – REAL (KIND=nag_wp) arrayOutput
On exit: ALPHA and BETA contain the generalized singular value pairs of A and B, αi and βi ;
  • ALPHA 1:K = 1 ,
  • BETA 1:K = 0 ,
and if m-k-l≥0 ,
  • ALPHA K+1:K+L = C ,
  • BETA K+1:K+L = S ,
or if m-k-l<0 ,
  • ALPHA K+1:M = C ,
  • ALPHA M+1:K+L = 0 ,
  • BETA K+1:M = S ,
  • BETA M+1:K+L = 1 , and
  • ALPHA K+L+1:N = 0 ,
  • BETA K+L+1:N = 0 .
The notation ALPHA K:N above refers to consecutive elements ALPHA i, for i=K,…,N.
15:   U LDU* – REAL (KIND=nag_wp) arrayOutput
Note: the second dimension of the array U must be at least max 1,M if JOBU='U', and at least 1 otherwise.
On exit: if JOBU='U', U contains the m by m orthogonal matrix U.
If JOBU='N', U is not referenced.
16:   LDU – INTEGERInput
On entry: the first dimension of the array U as declared in the (sub)program from which F08VCF (DGGSVD3) is called.
Constraints:
  • if JOBU='U', LDU≥ max 1,M ;
  • otherwise LDU≥1.
17:   V LDV* – REAL (KIND=nag_wp) arrayOutput
Note: the second dimension of the array V must be at least max 1,P if JOBV='V', and at least 1 otherwise.
On exit: if JOBV='V', V contains the p by p orthogonal matrix V.
If JOBV='N', V is not referenced.
18:   LDV – INTEGERInput
On entry: the first dimension of the array V as declared in the (sub)program from which F08VCF (DGGSVD3) is called.
Constraints:
  • if JOBV='V', LDV≥ max 1,P ;
  • otherwise LDV≥1.
19:   Q LDQ* – REAL (KIND=nag_wp) arrayOutput
Note: the second dimension of the array Q must be at least max 1,N if JOBQ='Q', and at least 1 otherwise.
On exit: if JOBQ='Q', Q contains the n by n orthogonal matrix Q.
If JOBQ='N', Q is not referenced.
20:   LDQ – INTEGERInput
On entry: the first dimension of the array Q as declared in the (sub)program from which F08VCF (DGGSVD3) is called.
Constraints:
  • if JOBQ='Q', LDQ≥ max 1,N ;
  • otherwise LDQ≥1.
21:   WORK max 1,LWORK – REAL (KIND=nag_wp) arrayWorkspace
On exit: if INFO=0, WORK 1 contains the minimum value of LWORK required for optimal performance.
22:   LWORK – INTEGERInput
On entry: the dimension of the array WORK as declared in the (sub)routine from which F08VCF (DGGSVD3) is called.
If LWORK=-1, a workspace query is assumed; the routine only calculates the optimal size of the WORK array, returns this value as the first entry of the WORK array, and no error message related to LWORK is issued.
Suggested value: for optimal performance, LWORK must generally be larger than the minimum; increase workspace by, say, nb×N+1, where nb is the optimal block size.
Constraints:
  • if JOBV='V', LWORK≥max 3*N+1,M,P;
  • if JOBV='N', LWORK≥max 3*N+1,M.
23:   IWORK N – INTEGER arrayOutput
On exit: stores the sorting information. More precisely, if I is the ordered set of indices of ALPHA containing C (denote as ALPHA I, see BETA), then the corresponding elements IWORK I contain the swap pivots, J, that sorts I such that ALPHA I is in descending numerical order.
The following pseudocode sorts the set I:
for ​i∈I j=Ji swap ​Ii​ and ​Ij end
24:   INFO – INTEGEROutput
On exit: INFO=0 unless the routine detects an error (see Section 6).

6 Error Indicators and Warnings

INFO<0
If INFO=-i, argument i had an illegal value. An explanatory message is output, and execution of the program is terminated.
INFO=1
The Jacobi-type procedure failed to converge.

7 Accuracy

The computed generalized singular value decomposition is nearly the exact generalized singular value decomposition for nearby matrices A+E and B+F , where
E 2 = O ε A 2 ​ and ​ F 2 = O ε B 2 ,
and ε is the machine precision. See Section 4.12 of Anderson et al. (1999) for further details.

8 Parallelism and Performance

F08VCF (DGGSVD3) is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
F08VCF (DGGSVD3) makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

This routine replaces the deprecated routine F08VAF (DGGSVD) which used an unblocked algorithm and therefore did not make best use of level 3 BLAS routines.
The complex analogue of this routine is F08VQF (ZGGSVD3).

10 Example

This example finds the generalized singular value decomposition
A = U Σ 1 0R QT ,   B = V Σ 2 0R QT ,
where
A = 1 2 3 3 2 1 4 5 6 7 8 8   and   B = -2 -3 3 4 6 5 ,
together with estimates for the condition number of R and the error bound for the computed generalized singular values.
The example program assumes that m≥n, and would need slight modification if this is not the case.

10.1 Program Text

Program Text (f08vcfe.f90)

10.2 Program Data

Program Data (f08vcfe.d)

10.3 Program Results

Program Results (f08vcfe.r)

F08 Chapter Contents
F08 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F08VEF (DGGSVP) : NAG Library, Mark 26

F08 Chapter Contents
F08 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F08VEF (DGGSVP)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F08VEF (DGGSVP) uses orthogonal transformations to simultaneously reduce the m by n matrix A and the p by n matrix B to upper triangular form. This factorization is usually used as a preprocessing step for computing the generalized singular value decomposition (GSVD). F08VEF (DGGSVP) is marked as deprecated by LAPACK; the replacement routine is F08VGF (DGGSVP3) which makes better use of level 3 BLAS.

2 Specification

SUBROUTINE F08VEF ( JOBU, JOBV, JOBQ, M, P, N, A, LDA, B, LDB, TOLA, TOLB, K, L, U, LDU, V, LDV, Q, LDQ, IWORK, TAU, WORK, INFO)
INTEGER | M, P, N, LDA, LDB, K, L, LDU, LDV, LDQ, IWORK(N), INFO
REAL (KIND=nag_wp) | A(LDA,*), B(LDB,*), TOLA, TOLB, U(LDU,*), V(LDV,*), Q(LDQ,*), TAU(N), WORK(max(3*N,M,P))
CHARACTER(1) | JOBU, JOBV, JOBQ
The routine may be called by its LAPACK name dggsvp.

3 Description

F08VEF (DGGSVP) computes orthogonal matrices U, V and Q such that
UT AQ= n-k-lklk0A 12A 13l00A 23m-k-l000() , if ​m-k-l≥0; n-k-lklk0A 12A 13m-k00A 23() , if ​m-k-l<0; VT BQ= n-k-lkll00B 13p-l000()
where the k by k matrix A 12 and l by l matrix B 13 are nonsingular upper triangular; A 23 is l by l upper triangular if m-k-l≥0 and is m-k by l upper trapezoidal otherwise. k+l is the effective numerical rank of the m+p by n matrix ATBT T.
This decomposition is usually used as the preprocessing step for computing the Generalized Singular Value Decomposition (GSVD), see routine F08VAF (DGGSVD).

4 References

Anderson E, Bai Z, Bischof C, Blackford S, Demmel J, Dongarra J J, Du Croz J J, Greenbaum A, Hammarling S, McKenney A and Sorensen D (1999) LAPACK Users' Guide (3rd Edition) SIAM, Philadelphia http://www.netlib.org/lapack/lug
Golub G H and Van Loan C F (1996) Matrix Computations (3rd Edition) Johns Hopkins University Press, Baltimore

5 Arguments

1:   JOBU – CHARACTER(1)Input
On entry: if JOBU='U', the orthogonal matrix U is computed.
If JOBU='N', U is not computed.
Constraint: JOBU='U' or 'N'.
2:   JOBV – CHARACTER(1)Input
On entry: if JOBV='V', the orthogonal matrix V is computed.
If JOBV='N', V is not computed.
Constraint: JOBV='V' or 'N'.
3:   JOBQ – CHARACTER(1)Input
On entry: if JOBQ='Q', the orthogonal matrix Q is computed.
If JOBQ='N', Q is not computed.
Constraint: JOBQ='Q' or 'N'.
4:   M – INTEGERInput
On entry: m, the number of rows of the matrix A.
Constraint: M≥0.
5:   P – INTEGERInput
On entry: p, the number of rows of the matrix B.
Constraint: P≥0.
6:   N – INTEGERInput
On entry: n, the number of columns of the matrices A and B.
Constraint: N≥0.
7:   A LDA* – REAL (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array A must be at least max 1,N.
On entry: the m by n matrix A.
On exit: contains the triangular (or trapezoidal) matrix described in Section 3.
8:   LDA – INTEGERInput
On entry: the first dimension of the array A as declared in the (sub)program from which F08VEF (DGGSVP) is called.
Constraint: LDA≥max 1,M.
9:   B LDB* – REAL (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array B must be at least max 1,N.
On entry: the p by n matrix B.
On exit: contains the triangular matrix described in Section 3.
10:   LDB – INTEGERInput
On entry: the first dimension of the array B as declared in the (sub)program from which F08VEF (DGGSVP) is called.
Constraint: LDB≥max 1,P.
11:   TOLA – REAL (KIND=nag_wp)Input
12:   TOLB – REAL (KIND=nag_wp)Input
On entry: TOLA and TOLB are the thresholds to determine the effective numerical rank of matrix B and a subblock of A. Generally, they are set to
TOLA=max M,N A ε, TOLB=max P,N B ε,
where ε is the machine precision.
The size of TOLA and TOLB may affect the size of backward errors of the decomposition.
13:   K – INTEGEROutput
14:   L – INTEGEROutput
On exit: K and L specify the dimension of the subblocks k and l as described in Section 3; k+l is the effective numerical rank of ATBT T.
15:   U LDU* – REAL (KIND=nag_wp) arrayOutput
Note: the second dimension of the array U must be at least max 1,M if JOBU='U', and at least 1 otherwise.
On exit: if JOBU='U', U contains the orthogonal matrix U.
If JOBU='N', U is not referenced.
16:   LDU – INTEGERInput
On entry: the first dimension of the array U as declared in the (sub)program from which F08VEF (DGGSVP) is called.
Constraints:
  • if JOBU='U', LDU≥ max 1,M ;
  • otherwise LDU≥1.
17:   V LDV* – REAL (KIND=nag_wp) arrayOutput
Note: the second dimension of the array V must be at least max 1,P if JOBV='V', and at least 1 otherwise.
On exit: if JOBV='V', V contains the orthogonal matrix V.
If JOBV='N', V is not referenced.
18:   LDV – INTEGERInput
On entry: the first dimension of the array V as declared in the (sub)program from which F08VEF (DGGSVP) is called.
Constraints:
  • if JOBV='V', LDV≥ max 1,P ;
  • otherwise LDV≥1.
19:   Q LDQ* – REAL (KIND=nag_wp) arrayOutput
Note: the second dimension of the array Q must be at least max 1,N if JOBQ='Q', and at least 1 otherwise.
On exit: if JOBQ='Q', Q contains the orthogonal matrix Q.
If JOBQ='N', Q is not referenced.
20:   LDQ – INTEGERInput
On entry: the first dimension of the array Q as declared in the (sub)program from which F08VEF (DGGSVP) is called.
Constraints:
  • if JOBQ='Q', LDQ≥ max 1,N ;
  • otherwise LDQ≥1.
21:   IWORK N – INTEGER arrayWorkspace
22:   TAU N – REAL (KIND=nag_wp) arrayWorkspace
23:   WORK max 3×N,M,P – REAL (KIND=nag_wp) arrayWorkspace
24:   INFO – INTEGEROutput
On exit: INFO=0 unless the routine detects an error (see Section 6).

6 Error Indicators and Warnings

INFO<0
If INFO=-i, argument i had an illegal value. An explanatory message is output, and execution of the program is terminated.

7 Accuracy

The computed factorization is nearly the exact factorization for nearby matrices A+E and B+F, where
E 2 = O ε A 2   and   F 2= O ε B 2,
and ε is the machine precision.

8 Parallelism and Performance

F08VEF (DGGSVP) makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The complex analogue of this routine is F08VSF (ZGGSVP).

10 Example

This example finds the generalized factorization
A = U Σ 1 0 S QT ,   B= V Σ 2 0 T QT ,
of the matrix pair AB, where
A = 123 321 456 788   and   B= -2-33 465 .

10.1 Program Text

Program Text (f08vefe.f90)

10.2 Program Data

Program Data (f08vefe.d)

10.3 Program Results

Program Results (f08vefe.r)

F08 Chapter Contents
F08 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F08VGF (DGGSVP3) : NAG Library, Mark 26

F08 Chapter Contents
F08 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F08VGF (DGGSVP3)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F08VGF (DGGSVP3) uses orthogonal transformations to simultaneously reduce the m by n matrix A and the p by n matrix B to upper triangular form. This factorization is usually used as a preprocessing step for computing the generalized singular value decomposition (GSVD). For sufficiently large problems, a blocked algorithm is used to make best use of level 3 BLAS.

2 Specification

SUBROUTINE F08VGF ( JOBU, JOBV, JOBQ, M, P, N, A, LDA, B, LDB, TOLA, TOLB, K, L, U, LDU, V, LDV, Q, LDQ, IWORK, TAU, WORK, LWORK, INFO)
INTEGER | M, P, N, LDA, LDB, K, L, LDU, LDV, LDQ, IWORK(N), LWORK, INFO
REAL (KIND=nag_wp) | A(LDA,*), B(LDB,*), TOLA, TOLB, U(LDU,*), V(LDV,*), Q(LDQ,*), TAU(N), WORK(max(1,LWORK))
CHARACTER(1) | JOBU, JOBV, JOBQ
The routine may be called by its LAPACK name dggsvp3.

3 Description

F08VGF (DGGSVP3) computes orthogonal matrices U, V and Q such that
UT AQ= n-k-lklk0A 12A 13l00A 23m-k-l000() , if ​m-k-l≥0; n-k-lklk0A 12A 13m-k00A 23() , if ​m-k-l<0; VT BQ= n-k-lkll00B 13p-l000()
where the k by k matrix A 12 and l by l matrix B 13 are nonsingular upper triangular; A 23 is l by l upper triangular if m-k-l≥0 and is m-k by l upper trapezoidal otherwise. k+l is the effective numerical rank of the m+p by n matrix ATBT T.
This decomposition is usually used as the preprocessing step for computing the Generalized Singular Value Decomposition (GSVD), see routine F08YEF (DTGSJA); the two steps are combined in F08VCF (DGGSVD3).

4 References

Anderson E, Bai Z, Bischof C, Blackford S, Demmel J, Dongarra J J, Du Croz J J, Greenbaum A, Hammarling S, McKenney A and Sorensen D (1999) LAPACK Users' Guide (3rd Edition) SIAM, Philadelphia http://www.netlib.org/lapack/lug
Golub G H and Van Loan C F (2012) Matrix Computations (4th Edition) Johns Hopkins University Press, Baltimore

5 Arguments

1:   JOBU – CHARACTER(1)Input
On entry: if JOBU='U', the orthogonal matrix U is computed.
If JOBU='N', U is not computed.
Constraint: JOBU='U' or 'N'.
2:   JOBV – CHARACTER(1)Input
On entry: if JOBV='V', the orthogonal matrix V is computed.
If JOBV='N', V is not computed.
Constraint: JOBV='V' or 'N'.
3:   JOBQ – CHARACTER(1)Input
On entry: if JOBQ='Q', the orthogonal matrix Q is computed.
If JOBQ='N', Q is not computed.
Constraint: JOBQ='Q' or 'N'.
4:   M – INTEGERInput
On entry: m, the number of rows of the matrix A.
Constraint: M≥0.
5:   P – INTEGERInput
On entry: p, the number of rows of the matrix B.
Constraint: P≥0.
6:   N – INTEGERInput
On entry: n, the number of columns of the matrices A and B.
Constraint: N≥0.
7:   A LDA* – REAL (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array A must be at least max 1,N.
On entry: the m by n matrix A.
On exit: contains the triangular (or trapezoidal) matrix described in Section 3.
8:   LDA – INTEGERInput
On entry: the first dimension of the array A as declared in the (sub)program from which F08VGF (DGGSVP3) is called.
Constraint: LDA≥max 1,M.
9:   B LDB* – REAL (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array B must be at least max 1,N.
On entry: the p by n matrix B.
On exit: contains the triangular matrix described in Section 3.
10:   LDB – INTEGERInput
On entry: the first dimension of the array B as declared in the (sub)program from which F08VGF (DGGSVP3) is called.
Constraint: LDB≥max 1,P.
11:   TOLA – REAL (KIND=nag_wp)Input
12:   TOLB – REAL (KIND=nag_wp)Input
On entry: TOLA and TOLB are the thresholds to determine the effective numerical rank of matrix B and a subblock of A. Generally, they are set to
TOLA=max M,N A ε, TOLB=max P,N B ε,
where ε is the machine precision.
The size of TOLA and TOLB may affect the size of backward errors of the decomposition.
13:   K – INTEGEROutput
14:   L – INTEGEROutput
On exit: K and L specify the dimension of the subblocks k and l as described in Section 3; k+l is the effective numerical rank of ATBT T.
15:   U LDU* – REAL (KIND=nag_wp) arrayOutput
Note: the second dimension of the array U must be at least max 1,M if JOBU='U', and at least 1 otherwise.
On exit: if JOBU='U', U contains the orthogonal matrix U.
If JOBU='N', U is not referenced.
16:   LDU – INTEGERInput
On entry: the first dimension of the array U as declared in the (sub)program from which F08VGF (DGGSVP3) is called.
Constraints:
  • if JOBU='U', LDU≥ max 1,M ;
  • otherwise LDU≥1.
17:   V LDV* – REAL (KIND=nag_wp) arrayOutput
Note: the second dimension of the array V must be at least max 1,P if JOBV='V', and at least 1 otherwise.
On exit: if JOBV='V', V contains the orthogonal matrix V.
If JOBV='N', V is not referenced.
18:   LDV – INTEGERInput
On entry: the first dimension of the array V as declared in the (sub)program from which F08VGF (DGGSVP3) is called.
Constraints:
  • if JOBV='V', LDV≥ max 1,P ;
  • otherwise LDV≥1.
19:   Q LDQ* – REAL (KIND=nag_wp) arrayOutput
Note: the second dimension of the array Q must be at least max 1,N if JOBQ='Q', and at least 1 otherwise.
On exit: if JOBQ='Q', Q contains the orthogonal matrix Q.
If JOBQ='N', Q is not referenced.
20:   LDQ – INTEGERInput
On entry: the first dimension of the array Q as declared in the (sub)program from which F08VGF (DGGSVP3) is called.
Constraints:
  • if JOBQ='Q', LDQ≥ max 1,N ;
  • otherwise LDQ≥1.
21:   IWORK N – INTEGER arrayWorkspace
22:   TAU N – REAL (KIND=nag_wp) arrayWorkspace
23:   WORK max 1,LWORK – REAL (KIND=nag_wp) arrayWorkspace
On exit: if INFO=0, WORK 1 contains the minimum value of LWORK required for optimal performance.
24:   LWORK – INTEGERInput
On entry: the dimension of the array WORK as declared in the (sub)routine from which F08VGF (DGGSVP3) is called.
If LWORK=-1, a workspace query is assumed; the routine only calculates the optimal size of the WORK array, returns this value as the first entry of the WORK array, and no error message related to LWORK is issued.
Suggested value: for optimal performance, LWORK must generally be larger than the minimum; increase workspace by, say, nb×N+1, where nb is the optimal block size
Constraints:
  • if JOBV='V', LWORK≥max 2*N+1,P,M;
  • if JOBV='N', LWORK≥max 2*N+1,M.
25:   INFO – INTEGEROutput
On exit: INFO=0 unless the routine detects an error (see Section 6).

6 Error Indicators and Warnings

INFO<0
If INFO=-i, argument i had an illegal value. An explanatory message is output, and execution of the program is terminated.

7 Accuracy

The computed factorization is nearly the exact factorization for nearby matrices A+E and B+F, where
E 2 = O ε A 2   and   F 2= O ε B 2,
and ε is the machine precision.

8 Parallelism and Performance

F08VGF (DGGSVP3) is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
F08VGF (DGGSVP3) makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

This routine replaces the deprecated routine F08VEF (DGGSVP) which used an unblocked algorithm and therefore did not make best use of level 3 BLAS routines.
The complex analogue of this routine is F08VUF (ZGGSVP3).

10 Example

This example finds the generalized factorization
A = U Σ 1 0 S QT ,   B= V Σ 2 0 T QT ,
of the matrix pair AB, where
A = 123 321 456 788   and   B= -2-33 465 .

10.1 Program Text

Program Text (f08vgfe.f90)

10.2 Program Data

Program Data (f08vgfe.d)

10.3 Program Results

Program Results (f08vgfe.r)

F08 Chapter Contents
F08 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F08VNF (ZGGSVD) : NAG Library, Mark 26

F08 Chapter Contents
F08 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F08VNF (ZGGSVD)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F08VNF (ZGGSVD) computes the generalized singular value decomposition (GSVD) of an m by n complex matrix A and a p by n complex matrix B. F08VNF (ZGGSVD) is marked as deprecated by LAPACK; the replacement routine is F08VQF (ZGGSVD3) which makes better use of level 3 BLAS.

2 Specification

SUBROUTINE F08VNF ( JOBU, JOBV, JOBQ, M, N, P, K, L, A, LDA, B, LDB, ALPHA, BETA, U, LDU, V, LDV, Q, LDQ, WORK, RWORK, IWORK, INFO)
INTEGER | M, N, P, K, L, LDA, LDB, LDU, LDV, LDQ, IWORK(N), INFO
REAL (KIND=nag_wp) | ALPHA(N), BETA(N), RWORK(2*N)
COMPLEX (KIND=nag_wp) | A(LDA,*), B(LDB,*), U(LDU,*), V(LDV,*), Q(LDQ,*), WORK(max(3*N,M,P)+N)
CHARACTER(1) | JOBU, JOBV, JOBQ
The routine may be called by its LAPACK name zggsvd.

3 Description

The generalized singular value decomposition is given by
UH A Q = D 1 0 R ,   VH B Q = D 2 0 R ,
where U, V and Q are unitary matrices. Let k+l be the effective numerical rank of the matrix A B , then R is a k+l by k+l nonsingular upper triangular matrix, D 1 and D 2 are m by k+l and p by k+l ‘diagonal’ matrices structured as follows:
if m-k-l≥0,
D 1= klkI0l0Cm-k-l00()
D 2= kll0Sp-l00()
0R = n-k-lklk0R 11R 12l00R 22()
where
C = diag α k+1,…,α k+l ,
S = diag β k+1,…,β k+l ,
and
C 2 + S 2 = I .
R is stored as a submatrix of A with elements R ij stored as A i,n-k-l+j on exit.
If m-k-l<0 ,
D 1= km-kk+l-mkI00m-k0C0()
D 2= km-kk+l-mm-k0S0k+l-m00Ip-l000()
0R = n-k-lkm-kk+l-mk0R 11R 12R 13m-k00R 22R 23k+l-m000R 33()
where
C = diag α k+1,…,αm ,
S = diag β k+1,…,βm ,
and
C 2 + S 2 = I .
R 11 R 12 R 13 0 R 22 R 23 is stored as a submatrix of A with R ij stored as A i,n-k-l+j, and R 33 is stored as a submatrix of B with R 33 ij stored as B m-k+i,n+m-k-l+j.
The routine computes C, S, R and, optionally, the unitary transformation matrices U, V and Q.
In particular, if B is an n by n nonsingular matrix, then the GSVD of A and B implicitly gives the SVD of A×B-1:
A B-1 = U D 1 D 2-1 VH .
If A B has orthonormal columns, then the GSVD of A and B is also equal to the CS decomposition of A and B. Furthermore, the GSVD can be used to derive the solution of the eigenvalue problem:
AH Ax=λ BH Bx .
In some literature, the GSVD of A and B is presented in the form
UH A X = 0D 1 ,   VH B X = 0D 2 ,
where U and V are orthogonal and X is nonsingular, and D 1 and D 2 are ‘diagonal’. The former GSVD form can be converted to the latter form by taking the nonsingular matrix X as
X = Q I 0 0 R-1 .

4 References

Anderson E, Bai Z, Bischof C, Blackford S, Demmel J, Dongarra J J, Du Croz J J, Greenbaum A, Hammarling S, McKenney A and Sorensen D (1999) LAPACK Users' Guide (3rd Edition) SIAM, Philadelphia http://www.netlib.org/lapack/lug
Golub G H and Van Loan C F (1996) Matrix Computations (3rd Edition) Johns Hopkins University Press, Baltimore

5 Arguments

1:   JOBU – CHARACTER(1)Input
On entry: if JOBU='U', the unitary matrix U is computed.
If JOBU='N', U is not computed.
Constraint: JOBU='U' or 'N'.
2:   JOBV – CHARACTER(1)Input
On entry: if JOBV='V', the unitary matrix V is computed.
If JOBV='N', V is not computed.
Constraint: JOBV='V' or 'N'.
3:   JOBQ – CHARACTER(1)Input
On entry: if JOBQ='Q', the unitary matrix Q is computed.
If JOBQ='N', Q is not computed.
Constraint: JOBQ='Q' or 'N'.
4:   M – INTEGERInput
On entry: m, the number of rows of the matrix A.
Constraint: M≥0.
5:   N – INTEGERInput
On entry: n, the number of columns of the matrices A and B.
Constraint: N≥0.
6:   P – INTEGERInput
On entry: p, the number of rows of the matrix B.
Constraint: P≥0.
7:   K – INTEGEROutput
8:   L – INTEGEROutput
On exit: K and L specify the dimension of the subblocks k and l as described in Section 3; k+l is the effective numerical rank of AB.
9:   A LDA* – COMPLEX (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array A must be at least max 1,N.
On entry: the m by n matrix A.
On exit: contains the triangular matrix R, or part of R. See Section 3 for details.
10:   LDA – INTEGERInput
On entry: the first dimension of the array A as declared in the (sub)program from which F08VNF (ZGGSVD) is called.
Constraint: LDA≥max 1,M.
11:   B LDB* – COMPLEX (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array B must be at least max 1,N.
On entry: the p by n matrix B.
On exit: contains the triangular matrix R if m-k-l<0. See Section 3 for details.
12:   LDB – INTEGERInput
On entry: the first dimension of the array B as declared in the (sub)program from which F08VNF (ZGGSVD) is called.
Constraint: LDB≥max 1,P.
13:   ALPHA N – REAL (KIND=nag_wp) arrayOutput
On exit: see the description of BETA.
14:   BETA N – REAL (KIND=nag_wp) arrayOutput
On exit: ALPHA and BETA contain the generalized singular value pairs of A and B, αi and βi ;
  • ALPHA 1:K = 1 ,
  • BETA 1:K = 0 ,
and if m-k-l≥0 ,
  • ALPHA K+1:K+L = C ,
  • BETA K+1:K+L = S ,
or if m-k-l<0 ,
  • ALPHA K+1:M = C ,
  • ALPHA M+1:K+L = 0 ,
  • BETA K+1:M = S ,
  • BETA M+1:K+L = 1 , and
  • ALPHA K+L+1:N = 0 ,
  • BETA K+L+1:N = 0 .
The notation ALPHA K:N above refers to consecutive elements ALPHA i, for i=K,…,N.
15:   U LDU* – COMPLEX (KIND=nag_wp) arrayOutput
Note: the second dimension of the array U must be at least max 1,M if JOBU='U', and at least 1 otherwise.
On exit: if JOBU='U', U contains the m by m unitary matrix U.
If JOBU='N', U is not referenced.
16:   LDU – INTEGERInput
On entry: the first dimension of the array U as declared in the (sub)program from which F08VNF (ZGGSVD) is called.
Constraints:
  • if JOBU='U', LDU≥ max 1,M ;
  • otherwise LDU≥1.
17:   V LDV* – COMPLEX (KIND=nag_wp) arrayOutput
Note: the second dimension of the array V must be at least max 1,P if JOBV='V', and at least 1 otherwise.
On exit: if JOBV='V', V contains the p by p unitary matrix V.
If JOBV='N', V is not referenced.
18:   LDV – INTEGERInput
On entry: the first dimension of the array V as declared in the (sub)program from which F08VNF (ZGGSVD) is called.
Constraints:
  • if JOBV='V', LDV≥ max 1,P ;
  • otherwise LDV≥1.
19:   Q LDQ* – COMPLEX (KIND=nag_wp) arrayOutput
Note: the second dimension of the array Q must be at least max 1,N if JOBQ='Q', and at least 1 otherwise.
On exit: if JOBQ='Q', Q contains the n by n unitary matrix Q.
If JOBQ='N', Q is not referenced.
20:   LDQ – INTEGERInput
On entry: the first dimension of the array Q as declared in the (sub)program from which F08VNF (ZGGSVD) is called.
Constraints:
  • if JOBQ='Q', LDQ≥ max 1,N ;
  • otherwise LDQ≥1.
21:   WORK max 3×N,M,P+N – COMPLEX (KIND=nag_wp) arrayWorkspace
22:   RWORK 2×N – REAL (KIND=nag_wp) arrayWorkspace
23:   IWORK N – INTEGER arrayOutput
On exit: stores the sorting information. More precisely, the following loop will sort ALPHA
 for I=K+1, min(M,K+L)
 swap ALPHA(I) and ALPHA(IWORK(I))
 endfor
such that ALPHA 1≥ALPHA 2≥⋯≥ALPHA N.
24:   INFO – INTEGEROutput
On exit: INFO=0 unless the routine detects an error (see Section 6).

6 Error Indicators and Warnings

INFO<0
If INFO=-i, argument i had an illegal value. An explanatory message is output, and execution of the program is terminated.
INFO=1
If INFO=1, the Jacobi-type procedure failed to converge.

7 Accuracy

The computed generalized singular value decomposition is nearly the exact generalized singular value decomposition for nearby matrices A+E and B+F , where
E 2 = O ε A 2 ​ and ​ F 2 = O ε B 2 ,
and ε is the machine precision. See Section 4.12 of Anderson et al. (1999) for further details.

8 Parallelism and Performance

F08VNF (ZGGSVD) makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The diagonal elements of the matrix R are real.
The real analogue of this routine is F08VAF (DGGSVD).

10 Example

This example finds the generalized singular value decomposition
A = U Σ 1 0R QH ,   B = V Σ 2 0R QH ,
where
A = 0.96-0.81 i -0.03+0.96 i -0.91+2.06 i -0.05+0.41 i -0.98+1.98 i -1.20+0.19 i -0.66+0.42 i -0.81+0.56 i 0.62-0.46 i 1.01+0.02 i 0.63-0.17 i -1.11+0.60 i 0.37+0.38 i 0.19-0.54 i -0.98-0.36 i 0.22-0.20 i 0.83+0.51 i 0.20+0.01 i -0.17-0.46 i 1.47+1.59 i 1.08-0.28 i 0.20-0.12 i -0.07+1.23 i 0.26+0.26 i
and
B = 1 0 -1 0 0 1 0 -1 ,
together with estimates for the condition number of R and the error bound for the computed generalized singular values.
The example program assumes that m≥n, and would need slight modification if this is not the case.

10.1 Program Text

Program Text (f08vnfe.f90)

10.2 Program Data

Program Data (f08vnfe.d)

10.3 Program Results

Program Results (f08vnfe.r)

F08 Chapter Contents
F08 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F08VQF (ZGGSVD3) : NAG Library, Mark 26

F08 Chapter Contents
F08 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F08VQF (ZGGSVD3)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F08VQF (ZGGSVD3) computes the generalized singular value decomposition (GSVD) of an m by n complex matrix A and a p by n complex matrix B.

2 Specification

SUBROUTINE F08VQF ( JOBU, JOBV, JOBQ, M, N, P, K, L, A, LDA, B, LDB, ALPHA, BETA, U, LDU, V, LDV, Q, LDQ, WORK, LWORK, RWORK, IWORK, INFO)
INTEGER | M, N, P, K, L, LDA, LDB, LDU, LDV, LDQ, LWORK, IWORK(N), INFO
REAL (KIND=nag_wp) | ALPHA(N), BETA(N), RWORK(2*N)
COMPLEX (KIND=nag_wp) | A(LDA,*), B(LDB,*), U(LDU,*), V(LDV,*), Q(LDQ,*), WORK(max(1,LWORK))
CHARACTER(1) | JOBU, JOBV, JOBQ
The routine may be called by its LAPACK name zggsvd3.

3 Description

Given an m by n complex matrix A and a p by n complex matrix B, the generalized singular value decomposition is given by
UH A Q = D 1 0 R ,   VH B Q = D 2 0 R ,
where U, V and Q are unitary matrices. Let l be the effective numerical rank of B and k+l be the effective numerical rank of the matrix A B , then the first k generalized singular values are infinite and the remaining l are finite. R is a k+l by k+l nonsingular upper triangular matrix, D 1 and D 2 are m by k+l and p by k+l ‘diagonal’ matrices structured as follows:
if m-k-l≥0,
D 1= klkI0l0Cm-k-l00()
D 2= kll0Sp-l00()
0R = n-k-lklk0R 11R 12l00R 22()
where
C = diag α k+1,…,α k+l ,
S = diag β k+1,…,β k+l ,
and
C 2 + S 2 = I .
R is stored as a submatrix of A with elements R ij stored as A i,n-k-l+j on exit.
If m-k-l<0 ,
D 1= km-kk+l-mkI00m-k0C0()
D 2= km-kk+l-mm-k0S0k+l-m00Ip-l000()
0R = n-k-lkm-kk+l-mk0R 11R 12R 13m-k00R 22R 23k+l-m000R 33()
where
C = diag α k+1,…,αm ,
S = diag β k+1,…,βm ,
and
C 2 + S 2 = I .
R 11 R 12 R 13 0 R 22 R 23 is stored as a submatrix of A with R ij stored as A i,n-k-l+j, and R 33 is stored as a submatrix of B with R 33 ij stored as B m-k+i,n+m-k-l+j.
The routine computes C, S, R and, optionally, the unitary transformation matrices U, V and Q.
In particular, if B is an n by n nonsingular matrix, then the GSVD of A and B implicitly gives the SVD of A×B-1:
A B-1 = U D 1 D 2-1 VH .
If A B has orthonormal columns, then the GSVD of A and B is also equal to the CS decomposition of A and B. Furthermore, the GSVD can be used to derive the solution of the eigenvalue problem:
AH Ax=λ BH Bx .
In some literature, the GSVD of A and B is presented in the form
UH A X = 0D 1 ,   VH B X = 0D 2 ,
where U and V are orthogonal and X is nonsingular, and D 1 and D 2 are ‘diagonal’. The former GSVD form can be converted to the latter form by setting
X = Q I 0 0 R-1 .
A two stage process is used to compute the GSVD of the matrix pair A,B. The pair is first reduced to upper triangular form by unitary transformations using F08VUF (ZGGSVP3). The GSVD of the resulting upper triangular matrix pair is then performed by F08YSF (ZTGSJA) which uses a variant of the Kogbetliantz algorithm (a cyclic Jacobi method).

4 References

Anderson E, Bai Z, Bischof C, Blackford S, Demmel J, Dongarra J J, Du Croz J J, Greenbaum A, Hammarling S, McKenney A and Sorensen D (1999) LAPACK Users' Guide (3rd Edition) SIAM, Philadelphia http://www.netlib.org/lapack/lug
Golub G H and Van Loan C F (2012) Matrix Computations (4th Edition) Johns Hopkins University Press, Baltimore

5 Arguments

1:   JOBU – CHARACTER(1)Input
On entry: if JOBU='U', the unitary matrix U is computed.
If JOBU='N', U is not computed.
Constraint: JOBU='U' or 'N'.
2:   JOBV – CHARACTER(1)Input
On entry: if JOBV='V', the unitary matrix V is computed.
If JOBV='N', V is not computed.
Constraint: JOBV='V' or 'N'.
3:   JOBQ – CHARACTER(1)Input
On entry: if JOBQ='Q', the unitary matrix Q is computed.
If JOBQ='N', Q is not computed.
Constraint: JOBQ='Q' or 'N'.
4:   M – INTEGERInput
On entry: m, the number of rows of the matrix A.
Constraint: M≥0.
5:   N – INTEGERInput
On entry: n, the number of columns of the matrices A and B.
Constraint: N≥0.
6:   P – INTEGERInput
On entry: p, the number of rows of the matrix B.
Constraint: P≥0.
7:   K – INTEGEROutput
8:   L – INTEGEROutput
On exit: K and L specify the dimension of the subblocks k and l as described in Section 3; k+l is the effective numerical rank of AB.
9:   A LDA* – COMPLEX (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array A must be at least max 1,N.
On entry: the m by n matrix A.
On exit: contains the triangular matrix R, or part of R. See Section 3 for details.
10:   LDA – INTEGERInput
On entry: the first dimension of the array A as declared in the (sub)program from which F08VQF (ZGGSVD3) is called.
Constraint: LDA≥max 1,M.
11:   B LDB* – COMPLEX (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array B must be at least max 1,N.
On entry: the p by n matrix B.
On exit: contains the triangular matrix R if m-k-l<0. See Section 3 for details.
12:   LDB – INTEGERInput
On entry: the first dimension of the array B as declared in the (sub)program from which F08VQF (ZGGSVD3) is called.
Constraint: LDB≥max 1,P.
13:   ALPHA N – REAL (KIND=nag_wp) arrayOutput
On exit: see the description of BETA.
14:   BETA N – REAL (KIND=nag_wp) arrayOutput
On exit: ALPHA and BETA contain the generalized singular value pairs of A and B, αi and βi ;
  • ALPHA 1:K = 1 ,
  • BETA 1:K = 0 ,
and if m-k-l≥0 ,
  • ALPHA K+1:K+L = C ,
  • BETA K+1:K+L = S ,
or if m-k-l<0 ,
  • ALPHA K+1:M = C ,
  • ALPHA M+1:K+L = 0 ,
  • BETA K+1:M = S ,
  • BETA M+1:K+L = 1 , and
  • ALPHA K+L+1:N = 0 ,
  • BETA K+L+1:N = 0 .
The notation ALPHA K:N above refers to consecutive elements ALPHA i, for i=K,…,N.
15:   U LDU* – COMPLEX (KIND=nag_wp) arrayOutput
Note: the second dimension of the array U must be at least max 1,M if JOBU='U', and at least 1 otherwise.
On exit: if JOBU='U', U contains the m by m unitary matrix U.
If JOBU='N', U is not referenced.
16:   LDU – INTEGERInput
On entry: the first dimension of the array U as declared in the (sub)program from which F08VQF (ZGGSVD3) is called.
Constraints:
  • if JOBU='U', LDU≥ max 1,M ;
  • otherwise LDU≥1.
17:   V LDV* – COMPLEX (KIND=nag_wp) arrayOutput
Note: the second dimension of the array V must be at least max 1,P if JOBV='V', and at least 1 otherwise.
On exit: if JOBV='V', V contains the p by p unitary matrix V.
If JOBV='N', V is not referenced.
18:   LDV – INTEGERInput
On entry: the first dimension of the array V as declared in the (sub)program from which F08VQF (ZGGSVD3) is called.
Constraints:
  • if JOBV='V', LDV≥ max 1,P ;
  • otherwise LDV≥1.
19:   Q LDQ* – COMPLEX (KIND=nag_wp) arrayOutput
Note: the second dimension of the array Q must be at least max 1,N if JOBQ='Q', and at least 1 otherwise.
On exit: if JOBQ='Q', Q contains the n by n unitary matrix Q.
If JOBQ='N', Q is not referenced.
20:   LDQ – INTEGERInput
On entry: the first dimension of the array Q as declared in the (sub)program from which F08VQF (ZGGSVD3) is called.
Constraints:
  • if JOBQ='Q', LDQ≥ max 1,N ;
  • otherwise LDQ≥1.
21:   WORK max 1,LWORK – COMPLEX (KIND=nag_wp) arrayWorkspace
On exit: if INFO=0, the real part of WORK 1 contains the minimum value of LWORK required for optimal performance.
22:   LWORK – INTEGERInput
On entry: the dimension of the array WORK as declared in the (sub)routine from which F08VQF (ZGGSVD3) is called.
If LWORK=-1, a workspace query is assumed; the routine only calculates the optimal size of the WORK array, returns this value as the first entry of the WORK array, and no error message related to LWORK is issued.
Suggested value: for optimal performance, LWORK must generally be larger than the minimum; increase workspace by, say, nb×N+1, where nb is the optimal block size.
Constraints:
  • if JOBV='V', LWORK≥max N+1,M,P;
  • if JOBV='N', LWORK≥max N+1,M.
23:   RWORK 2×N – REAL (KIND=nag_wp) arrayWorkspace
24:   IWORK N – INTEGER arrayOutput
On exit: stores the sorting information. More precisely, if I is the ordered set of indices of ALPHA containing C (denote as ALPHA I, see BETA), then the corresponding elements IWORK I contain the swap pivots, J, that sorts I such that ALPHA I is in descending numerical order.
The following pseudocode sorts the set I:
for ​i∈I j=Ji swap ​Ii​ and ​Ij end
25:   INFO – INTEGEROutput
On exit: INFO=0 unless the routine detects an error (see Section 6).

6 Error Indicators and Warnings

INFO<0
If INFO=-i, argument i had an illegal value. An explanatory message is output, and execution of the program is terminated.
INFO=1
The Jacobi-type procedure failed to converge.

7 Accuracy

The computed generalized singular value decomposition is nearly the exact generalized singular value decomposition for nearby matrices A+E and B+F , where
E 2 = O ε A 2 ​ and ​ F 2 = O ε B 2 ,
and ε is the machine precision. See Section 4.12 of Anderson et al. (1999) for further details.

8 Parallelism and Performance

F08VQF (ZGGSVD3) is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
F08VQF (ZGGSVD3) makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

This routine replaces the deprecated routine F08VNF (ZGGSVD) which used an unblocked algorithm and therefore did not make best use of level 3 BLAS routines.
The diagonal elements of the matrix R are real.
The real analogue of this routine is F08VCF (DGGSVD3).

10 Example

This example finds the generalized singular value decomposition
A = U Σ 1 0R QH ,   B = V Σ 2 0R QH ,
where
A = 0.96-0.81 i -0.03+0.96 i -0.91+2.06 i -0.05+0.41 i -0.98+1.98 i -1.20+0.19 i -0.66+0.42 i -0.81+0.56 i 0.62-0.46 i 1.01+0.02 i 0.63-0.17 i -1.11+0.60 i 0.37+0.38 i 0.19-0.54 i -0.98-0.36 i 0.22-0.20 i 0.83+0.51 i 0.20+0.01 i -0.17-0.46 i 1.47+1.59 i 1.08-0.28 i 0.20-0.12 i -0.07+1.23 i 0.26+0.26 i
and
B = 1 0 -1 0 0 1 0 -1 ,
together with estimates for the condition number of R and the error bound for the computed generalized singular values.
The example program assumes that m≥n, and would need slight modification if this is not the case.

10.1 Program Text

Program Text (f08vqfe.f90)

10.2 Program Data

Program Data (f08vqfe.d)

10.3 Program Results

Program Results (f08vqfe.r)

F08 Chapter Contents
F08 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F08VSF (ZGGSVP) : NAG Library, Mark 26

F08 Chapter Contents
F08 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F08VSF (ZGGSVP)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F08VSF (ZGGSVP) uses unitary transformations to simultaneously reduce the m by n matrix A and the p by n matrix B to upper triangular form. This factorization is usually used as a preprocessing step for computing the generalized singular value decomposition (GSVD). F08VSF (ZGGSVP) is marked as deprecated by LAPACK; the replacement routine is F08VUF (ZGGSVP3) which makes better use of level 3 BLAS.

2 Specification

SUBROUTINE F08VSF ( JOBU, JOBV, JOBQ, M, P, N, A, LDA, B, LDB, TOLA, TOLB, K, L, U, LDU, V, LDV, Q, LDQ, IWORK, RWORK, TAU, WORK, INFO)
INTEGER | M, P, N, LDA, LDB, K, L, LDU, LDV, LDQ, IWORK(N), INFO
REAL (KIND=nag_wp) | TOLA, TOLB, RWORK(2*N)
COMPLEX (KIND=nag_wp) | A(LDA,*), B(LDB,*), U(LDU,*), V(LDV,*), Q(LDQ,*), TAU(N), WORK(max(3*N,M,P))
CHARACTER(1) | JOBU, JOBV, JOBQ
The routine may be called by its LAPACK name zggsvp.

3 Description

F08VSF (ZGGSVP) computes unitary matrices U, V and Q such that
UH AQ= n-k-lklk0A 12A 13l00A 23m-k-l000() , if ​m-k-l≥0; n-k-lklk0A 12A 13m-k00A 23() , if ​m-k-l<0; VH BQ= n-k-lkll00B 13p-l000()
where the k by k matrix A 12 and l by l matrix B 13 are nonsingular upper triangular; A 23 is l by l upper triangular if m-k-l≥0 and is m-k by l upper trapezoidal otherwise. k+l is the effective numerical rank of the m+p by n matrix AHBH H.
This decomposition is usually used as the preprocessing step for computing the Generalized Singular Value Decomposition (GSVD), see routine F08VNF (ZGGSVD).

4 References

Anderson E, Bai Z, Bischof C, Blackford S, Demmel J, Dongarra J J, Du Croz J J, Greenbaum A, Hammarling S, McKenney A and Sorensen D (1999) LAPACK Users' Guide (3rd Edition) SIAM, Philadelphia http://www.netlib.org/lapack/lug
Golub G H and Van Loan C F (1996) Matrix Computations (3rd Edition) Johns Hopkins University Press, Baltimore

5 Arguments

1:   JOBU – CHARACTER(1)Input
On entry: if JOBU='U', the unitary matrix U is computed.
If JOBU='N', U is not computed.
Constraint: JOBU='U' or 'N'.
2:   JOBV – CHARACTER(1)Input
On entry: if JOBV='V', the unitary matrix V is computed.
If JOBV='N', V is not computed.
Constraint: JOBV='V' or 'N'.
3:   JOBQ – CHARACTER(1)Input
On entry: if JOBQ='Q', the unitary matrix Q is computed.
If JOBQ='N', Q is not computed.
Constraint: JOBQ='Q' or 'N'.
4:   M – INTEGERInput
On entry: m, the number of rows of the matrix A.
Constraint: M≥0.
5:   P – INTEGERInput
On entry: p, the number of rows of the matrix B.
Constraint: P≥0.
6:   N – INTEGERInput
On entry: n, the number of columns of the matrices A and B.
Constraint: N≥0.
7:   A LDA* – COMPLEX (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array A must be at least max 1,N.
On entry: the m by n matrix A.
On exit: contains the triangular (or trapezoidal) matrix described in Section 3.
8:   LDA – INTEGERInput
On entry: the first dimension of the array A as declared in the (sub)program from which F08VSF (ZGGSVP) is called.
Constraint: LDA≥max 1,M.
9:   B LDB* – COMPLEX (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array B must be at least max 1,N.
On entry: the p by n matrix B.
On exit: contains the triangular matrix described in Section 3.
10:   LDB – INTEGERInput
On entry: the first dimension of the array B as declared in the (sub)program from which F08VSF (ZGGSVP) is called.
Constraint: LDB≥max 1,P.
11:   TOLA – REAL (KIND=nag_wp)Input
12:   TOLB – REAL (KIND=nag_wp)Input
On entry: TOLA and TOLB are the thresholds to determine the effective numerical rank of matrix B and a subblock of A. Generally, they are set to
TOLA=max M,N A ε, TOLB=max P,N B ε,
where ε is the machine precision.
The size of TOLA and TOLB may affect the size of backward errors of the decomposition.
13:   K – INTEGEROutput
14:   L – INTEGEROutput
On exit: K and L specify the dimension of the subblocks k and l as described in Section 3; k+l is the effective numerical rank of ATBT T.
15:   U LDU* – COMPLEX (KIND=nag_wp) arrayOutput
Note: the second dimension of the array U must be at least max 1,M if JOBU='U', and at least 1 otherwise.
On exit: if JOBU='U', U contains the unitary matrix U.
If JOBU='N', U is not referenced.
16:   LDU – INTEGERInput
On entry: the first dimension of the array U as declared in the (sub)program from which F08VSF (ZGGSVP) is called.
Constraints:
  • if JOBU='U', LDU≥ max 1,M ;
  • otherwise LDU≥1.
17:   V LDV* – COMPLEX (KIND=nag_wp) arrayOutput
Note: the second dimension of the array V must be at least max 1,P if JOBV='V', and at least 1 otherwise.
On exit: if JOBV='V', V contains the unitary matrix V.
If JOBV='N', V is not referenced.
18:   LDV – INTEGERInput
On entry: the first dimension of the array V as declared in the (sub)program from which F08VSF (ZGGSVP) is called.
Constraints:
  • if JOBV='V', LDV≥ max 1,P ;
  • otherwise LDV≥1.
19:   Q LDQ* – COMPLEX (KIND=nag_wp) arrayOutput
Note: the second dimension of the array Q must be at least max 1,N if JOBQ='Q', and at least 1 otherwise.
On exit: if JOBQ='Q', Q contains the unitary matrix Q.
If JOBQ='N', Q is not referenced.
20:   LDQ – INTEGERInput
On entry: the first dimension of the array Q as declared in the (sub)program from which F08VSF (ZGGSVP) is called.
Constraints:
  • if JOBQ='Q', LDQ≥ max 1,N ;
  • otherwise LDQ≥1.
21:   IWORK N – INTEGER arrayWorkspace
22:   RWORK 2×N – REAL (KIND=nag_wp) arrayWorkspace
23:   TAU N – COMPLEX (KIND=nag_wp) arrayWorkspace
24:   WORK max 3×N,M,P – COMPLEX (KIND=nag_wp) arrayWorkspace
25:   INFO – INTEGEROutput
On exit: INFO=0 unless the routine detects an error (see Section 6).

6 Error Indicators and Warnings

INFO<0
If INFO=-i, argument i had an illegal value. An explanatory message is output, and execution of the program is terminated.

7 Accuracy

The computed factorization is nearly the exact factorization for nearby matrices A+E and B+F, where
E 2 = O ε A 2   and   F 2= O ε B 2,
and ε is the machine precision.

8 Parallelism and Performance

F08VSF (ZGGSVP) makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The real analogue of this routine is F08VEF (DGGSVP).

10 Example

This example finds the generalized factorization
A = U Σ 1 0 S QH ,   B= V Σ 2 0 T QH ,
of the matrix pair AB, where
A = 0.96-0.81 i -0.03+0.96 i -0.91+2.06 i -0.05+0.41 i -0.98+1.98 i -1.20+0.19 i -0.66+0.42 i -0.81+0.56 i 0.62-0.46 i 1.01+0.02 i 0.63-0.17 i -1.11+0.60 i 0.37+0.38 i 0.19-0.54 i -0.98-0.36 i 0.22-0.20 i 0.83+0.51 i 0.20+0.01 i -0.17-0.46 i 1.47+1.59 i 1.08-0.28 i 0.20-0.12 i -0.07+1.23 i 0.26+0.26 i
and
B = 10-10 010-1 .

10.1 Program Text

Program Text (f08vsfe.f90)

10.2 Program Data

Program Data (f08vsfe.d)

10.3 Program Results

Program Results (f08vsfe.r)

F08 Chapter Contents
F08 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F08VUF (ZGGSVP3) : NAG Library, Mark 26

F08 Chapter Contents
F08 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F08VUF (ZGGSVP3)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F08VUF (ZGGSVP3) uses unitary transformations to simultaneously reduce the m by n matrix A and the p by n matrix B to upper triangular form. This factorization is usually used as a preprocessing step for computing the generalized singular value decomposition (GSVD). For sufficiently large problems, a blocked algorithm is used to make best use of level 3 BLAS.

2 Specification

SUBROUTINE F08VUF ( JOBU, JOBV, JOBQ, M, P, N, A, LDA, B, LDB, TOLA, TOLB, K, L, U, LDU, V, LDV, Q, LDQ, IWORK, RWORK, TAU, WORK, LWORK, INFO)
INTEGER | M, P, N, LDA, LDB, K, L, LDU, LDV, LDQ, IWORK(N), LWORK, INFO
REAL (KIND=nag_wp) | TOLA, TOLB, RWORK(2*N)
COMPLEX (KIND=nag_wp) | A(LDA,*), B(LDB,*), U(LDU,*), V(LDV,*), Q(LDQ,*), TAU(N), WORK(max(1,LWORK))
CHARACTER(1) | JOBU, JOBV, JOBQ
The routine may be called by its LAPACK name zggsvp3.

3 Description

F08VUF (ZGGSVP3) computes unitary matrices U, V and Q such that
UH AQ= n-k-lklk0A 12A 13l00A 23m-k-l000() , if ​m-k-l≥0; n-k-lklk0A 12A 13m-k00A 23() , if ​m-k-l<0; VH BQ= n-k-lkll00B 13p-l000()
where the k by k matrix A 12 and l by l matrix B 13 are nonsingular upper triangular; A 23 is l by l upper triangular if m-k-l≥0 and is m-k by l upper trapezoidal otherwise. k+l is the effective numerical rank of the m+p by n matrix AHBH H.
This decomposition is usually used as the preprocessing step for computing the Generalized Singular Value Decomposition (GSVD), see routine F08YSF (ZTGSJA); the two steps are combined in F08VQF (ZGGSVD3).

4 References

Anderson E, Bai Z, Bischof C, Blackford S, Demmel J, Dongarra J J, Du Croz J J, Greenbaum A, Hammarling S, McKenney A and Sorensen D (1999) LAPACK Users' Guide (3rd Edition) SIAM, Philadelphia http://www.netlib.org/lapack/lug
Golub G H and Van Loan C F (2012) Matrix Computations (4th Edition) Johns Hopkins University Press, Baltimore

5 Arguments

1:   JOBU – CHARACTER(1)Input
On entry: if JOBU='U', the unitary matrix U is computed.
If JOBU='N', U is not computed.
Constraint: JOBU='U' or 'N'.
2:   JOBV – CHARACTER(1)Input
On entry: if JOBV='V', the unitary matrix V is computed.
If JOBV='N', V is not computed.
Constraint: JOBV='V' or 'N'.
3:   JOBQ – CHARACTER(1)Input
On entry: if JOBQ='Q', the unitary matrix Q is computed.
If JOBQ='N', Q is not computed.
Constraint: JOBQ='Q' or 'N'.
4:   M – INTEGERInput
On entry: m, the number of rows of the matrix A.
Constraint: M≥0.
5:   P – INTEGERInput
On entry: p, the number of rows of the matrix B.
Constraint: P≥0.
6:   N – INTEGERInput
On entry: n, the number of columns of the matrices A and B.
Constraint: N≥0.
7:   A LDA* – COMPLEX (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array A must be at least max 1,N.
On entry: the m by n matrix A.
On exit: contains the triangular (or trapezoidal) matrix described in Section 3.
8:   LDA – INTEGERInput
On entry: the first dimension of the array A as declared in the (sub)program from which F08VUF (ZGGSVP3) is called.
Constraint: LDA≥max 1,M.
9:   B LDB* – COMPLEX (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array B must be at least max 1,N.
On entry: the p by n matrix B.
On exit: contains the triangular matrix described in Section 3.
10:   LDB – INTEGERInput
On entry: the first dimension of the array B as declared in the (sub)program from which F08VUF (ZGGSVP3) is called.
Constraint: LDB≥max 1,P.
11:   TOLA – REAL (KIND=nag_wp)Input
12:   TOLB – REAL (KIND=nag_wp)Input
On entry: TOLA and TOLB are the thresholds to determine the effective numerical rank of matrix B and a subblock of A. Generally, they are set to
TOLA=max M,N A ε, TOLB=max P,N B ε,
where ε is the machine precision.
The size of TOLA and TOLB may affect the size of backward errors of the decomposition.
13:   K – INTEGEROutput
14:   L – INTEGEROutput
On exit: K and L specify the dimension of the subblocks k and l as described in Section 3; k+l is the effective numerical rank of ATBT T.
15:   U LDU* – COMPLEX (KIND=nag_wp) arrayOutput
Note: the second dimension of the array U must be at least max 1,M if JOBU='U', and at least 1 otherwise.
On exit: if JOBU='U', U contains the unitary matrix U.
If JOBU='N', U is not referenced.
16:   LDU – INTEGERInput
On entry: the first dimension of the array U as declared in the (sub)program from which F08VUF (ZGGSVP3) is called.
Constraints:
  • if JOBU='U', LDU≥ max 1,M ;
  • otherwise LDU≥1.
17:   V LDV* – COMPLEX (KIND=nag_wp) arrayOutput
Note: the second dimension of the array V must be at least max 1,P if JOBV='V', and at least 1 otherwise.
On exit: if JOBV='V', V contains the unitary matrix V.
If JOBV='N', V is not referenced.
18:   LDV – INTEGERInput
On entry: the first dimension of the array V as declared in the (sub)program from which F08VUF (ZGGSVP3) is called.
Constraints:
  • if JOBV='V', LDV≥ max 1,P ;
  • otherwise LDV≥1.
19:   Q LDQ* – COMPLEX (KIND=nag_wp) arrayOutput
Note: the second dimension of the array Q must be at least max 1,N if JOBQ='Q', and at least 1 otherwise.
On exit: if JOBQ='Q', Q contains the unitary matrix Q.
If JOBQ='N', Q is not referenced.
20:   LDQ – INTEGERInput
On entry: the first dimension of the array Q as declared in the (sub)program from which F08VUF (ZGGSVP3) is called.
Constraints:
  • if JOBQ='Q', LDQ≥ max 1,N ;
  • otherwise LDQ≥1.
21:   IWORK N – INTEGER arrayWorkspace
22:   RWORK 2×N – REAL (KIND=nag_wp) arrayWorkspace
23:   TAU N – COMPLEX (KIND=nag_wp) arrayWorkspace
24:   WORK max 1,LWORK – COMPLEX (KIND=nag_wp) arrayWorkspace
On exit: if INFO=0, the real part of WORK 1 contains the minimum value of LWORK required for optimal performance.
25:   LWORK – INTEGERInput
On entry: the dimension of the array WORK as declared in the (sub)routine from which F08VUF (ZGGSVP3) is called.
If LWORK=-1, a workspace query is assumed; the routine only calculates the optimal size of the WORK array, returns this value as the first entry of the WORK array, and no error message related to LWORK is issued.
Suggested value: for optimal performance, LWORK must generally be larger than the minimum; increase workspace by, say, nb×N+1, where nb is the optimal block size
Constraints:
  • if JOBV='V', LWORK≥max N+1,P,M;
  • if JOBV='N', LWORK≥max N+1,M.
26:   INFO – INTEGEROutput
On exit: INFO=0 unless the routine detects an error (see Section 6).

6 Error Indicators and Warnings

INFO<0
If INFO=-i, argument i had an illegal value. An explanatory message is output, and execution of the program is terminated.

7 Accuracy

The computed factorization is nearly the exact factorization for nearby matrices A+E and B+F, where
E 2 = O ε A 2   and   F 2= O ε B 2,
and ε is the machine precision.

8 Parallelism and Performance

F08VUF (ZGGSVP3) is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
F08VUF (ZGGSVP3) makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

This routine replaces the deprecated routine F08VSF (ZGGSVP) which used an unblocked algorithm and therefore did not make best use of level 3 BLAS routines.
The real analogue of this routine is F08VGF (DGGSVP3).

10 Example

This example finds the generalized factorization
A = U Σ 1 0 S QH ,   B= V Σ 2 0 T QH ,
of the matrix pair AB, where
A = 0.96-0.81 i -0.03+0.96 i -0.91+2.06 i -0.05+0.41 i -0.98+1.98 i -1.20+0.19 i -0.66+0.42 i -0.81+0.56 i 0.62-0.46 i 1.01+0.02 i 0.63-0.17 i -1.11+0.60 i 0.37+0.38 i 0.19-0.54 i -0.98-0.36 i 0.22-0.20 i 0.83+0.51 i 0.20+0.01 i -0.17-0.46 i 1.47+1.59 i 1.08-0.28 i 0.20-0.12 i -0.07+1.23 i 0.26+0.26 i
and
B = 10-10 010-1 .

10.1 Program Text

Program Text (f08vufe.f90)

10.2 Program Data

Program Data (f08vufe.d)

10.3 Program Results

Program Results (f08vufe.r)

F08 Chapter Contents
F08 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F08WAF (DGGEV) : NAG Library, Mark 26

F08 Chapter Contents
F08 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F08WAF (DGGEV)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F08WAF (DGGEV) computes for a pair of n by n real nonsymmetric matrices A,B the generalized eigenvalues and, optionally, the left and/or right generalized eigenvectors using the QZ algorithm. F08WAF (DGGEV) is marked as deprecated by LAPACK; the replacement routine is F08WCF (DGGEV3) which makes better use of level 3 BLAS.

2 Specification

SUBROUTINE F08WAF ( JOBVL, JOBVR, N, A, LDA, B, LDB, ALPHAR, ALPHAI, BETA, VL, LDVL, VR, LDVR, WORK, LWORK, INFO)
INTEGER | N, LDA, LDB, LDVL, LDVR, LWORK, INFO
REAL (KIND=nag_wp) | A(LDA,*), B(LDB,*), ALPHAR(N), ALPHAI(N), BETA(N), VL(LDVL,*), VR(LDVR,*), WORK(max(1,LWORK))
CHARACTER(1) | JOBVL, JOBVR
The routine may be called by its LAPACK name dggev.

3 Description

A generalized eigenvalue for a pair of matrices A,B is a scalar λ or a ratio α/β=λ, such that A-λB is singular. It is usually represented as the pair α,β, as there is a reasonable interpretation for β=0, and even for both being zero.
The right eigenvector vj corresponding to the eigenvalue λj of A,B satisfies
A vj = λj B vj .
The left eigenvector uj corresponding to the eigenvalue λj of A,B satisfies
ujH A = λj ujH B ,
where ujH is the conjugate-transpose of uj.
All the eigenvalues and, if required, all the eigenvectors of the generalized eigenproblem Ax=λBx, where A and B are real, square matrices, are determined using the QZ algorithm. The QZ algorithm consists of four stages:
1. | A is reduced to upper Hessenberg form and at the same time B is reduced to upper triangular form.
2. | A is further reduced to quasi-triangular form while the triangular form of B is maintained. This is the real generalized Schur form of the pair A,B .
3. The quasi-triangular form of A is reduced to triangular form and the eigenvalues extracted. This routine does not actually produce the eigenvalues λj, but instead returns αj and βj such that
λj=αj/βj,  j=1,2,…,n.
The division by βj becomes your responsibility, since βj may be zero, indicating an infinite eigenvalue. Pairs of complex eigenvalues occur with αj/βj and α j+1/β j+1 complex conjugates, even though αj and α j+1 are not conjugate.
4. | If the eigenvectors are required they are obtained from the triangular matrices and then transformed back into the original coordinate system.

4 References

Anderson E, Bai Z, Bischof C, Blackford S, Demmel J, Dongarra J J, Du Croz J J, Greenbaum A, Hammarling S, McKenney A and Sorensen D (1999) LAPACK Users' Guide (3rd Edition) SIAM, Philadelphia http://www.netlib.org/lapack/lug
Golub G H and Van Loan C F (2012) Matrix Computations (4th Edition) Johns Hopkins University Press, Baltimore
Wilkinson J H (1979) Kronecker's canonical form and the QZ algorithm Linear Algebra Appl. 28 285–303

5 Arguments

1:   JOBVL – CHARACTER(1)Input
On entry: if JOBVL='N', do not compute the left generalized eigenvectors.
If JOBVL='V', compute the left generalized eigenvectors.
Constraint: JOBVL='N' or 'V'.
2:   JOBVR – CHARACTER(1)Input
On entry: if JOBVR='N', do not compute the right generalized eigenvectors.
If JOBVR='V', compute the right generalized eigenvectors.
Constraint: JOBVR='N' or 'V'.
3:   N – INTEGERInput
On entry: n, the order of the matrices A and B.
Constraint: N≥0.
4:   A LDA* – REAL (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array A must be at least max 1,N.
On entry: the matrix A in the pair A,B.
On exit: A has been overwritten.
5:   LDA – INTEGERInput
On entry: the first dimension of the array A as declared in the (sub)program from which F08WAF (DGGEV) is called.
Constraint: LDA≥max 1,N.
6:   B LDB* – REAL (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array B must be at least max 1,N.
On entry: the matrix B in the pair A,B.
On exit: B has been overwritten.
7:   LDB – INTEGERInput
On entry: the first dimension of the array B as declared in the (sub)program from which F08WAF (DGGEV) is called.
Constraint: LDB≥max 1,N.
8:   ALPHAR N – REAL (KIND=nag_wp) arrayOutput
On exit: the element ALPHAR j contains the real part of αj.
9:   ALPHAI N – REAL (KIND=nag_wp) arrayOutput
On exit: the element ALPHAI j contains the imaginary part of αj.
10:   BETA N – REAL (KIND=nag_wp) arrayOutput
On exit: ALPHAR j+ALPHAI j×i/BETA j, for j=1,2,…,N, will be the generalized eigenvalues.
If ALPHAI j is zero, then the jth eigenvalue is real; if positive, then the jth and j+1st eigenvalues are a complex conjugate pair, with ALPHAI j+1 negative.
Note: the quotients ALPHAR j/BETA j and ALPHAI j/BETA j may easily overflow or underflow, and BETA j may even be zero. Thus, you should avoid naively computing the ratio αj/βj. However, max αj will always be less than and usually comparable with A 2 in magnitude, and max βj will always be less than and usually comparable with B 2.
11:   VL LDVL* – REAL (KIND=nag_wp) arrayOutput
Note: the second dimension of the array VL must be at least max 1,N if JOBVL='V', and at least 1 otherwise.
On exit: if JOBVL='V', the left eigenvectors uj are stored one after another in the columns of VL, in the same order as the corresponding eigenvalues.
If the jth eigenvalue is real, then uj=VL:,j, the jth column of VL.
If the jth and j+1th eigenvalues form a complex conjugate pair, then uj=VL:,j+i×VL:,j+1 and u j+1=VL:,j-i×VL:,j+1. Each eigenvector will be scaled so the largest component has real part+imag. part=1.
If JOBVL='N', VL is not referenced.
12:   LDVL – INTEGERInput
On entry: the first dimension of the array VL as declared in the (sub)program from which F08WAF (DGGEV) is called.
Constraints:
  • if JOBVL='V', LDVL≥ max 1,N ;
  • otherwise LDVL≥1.
13:   VR LDVR* – REAL (KIND=nag_wp) arrayOutput
Note: the second dimension of the array VR must be at least max 1,N if JOBVR='V', and at least 1 otherwise.
On exit: if JOBVR='V', the right eigenvectors vj are stored one after another in the columns of VR, in the same order as the corresponding eigenvalues.
If the jth eigenvalue is real, then vj=VR:,j, the jth column of VR.
If the jth and j+1th eigenvalues form a complex conjugate pair, then vj=VR:,j+i×VR:,j+1 and v j+1=VR:,j-i×VR:,j+1. Each eigenvector will be scaled so the largest component has real part+imag. part=1.
If JOBVR='N', VR is not referenced.
14:   LDVR – INTEGERInput
On entry: the first dimension of the array VR as declared in the (sub)program from which F08WAF (DGGEV) is called.
Constraints:
  • if JOBVR='V', LDVR≥ max 1,N ;
  • otherwise LDVR≥1.
15:   WORK max 1,LWORK – REAL (KIND=nag_wp) arrayWorkspace
On exit: if INFO=0, WORK 1 contains the minimum value of LWORK required for optimal performance.
16:   LWORK – INTEGERInput
On entry: the dimension of the array WORK as declared in the (sub)program from which F08WAF (DGGEV) is called.
If LWORK=-1, a workspace query is assumed; the routine only calculates the optimal size of the WORK array, returns this value as the first entry of the WORK array, and no error message related to LWORK is issued.
Suggested value: for optimal performance, LWORK must generally be larger than the minimum; increase workspace by, say, nb×N, where nb is the optimal block size.
Constraint: LWORK≥max 1,8×N.
17:   INFO – INTEGEROutput
On exit: INFO=0 unless the routine detects an error (see Section 6).

6 Error Indicators and Warnings

INFO<0
If INFO=-i, argument i had an illegal value. An explanatory message is output, and execution of the program is terminated.
INFO=1 to N
The QZ iteration failed. No eigenvectors have been calculated, but ALPHAR j, ALPHAI j, and BETA j should be correct for j=INFO+1,…,N.
INFO=N+1
Unexpected error returned from F08XEF (DHGEQZ).
INFO=N+2
Error returned from F08YKF (DTGEVC).

7 Accuracy

The computed eigenvalues and eigenvectors are exact for nearby matrices A+E and B+F, where
E,F F = O ε A,B F ,
and ε is the machine precision. See Section 4.11 of Anderson et al. (1999) for further details.
Note: interpretation of results obtained with the QZ algorithm often requires a clear understanding of the effects of small changes in the original data. These effects are reviewed in Wilkinson (1979), in relation to the significance of small values of αj and βj. It should be noted that if αj and βj are both small for any j, it may be that no reliance can be placed on any of the computed eigenvalues λi=αi/βi. You are recommended to study Wilkinson (1979) and, if in difficulty, to seek expert advice on determining the sensitivity of the eigenvalues to perturbations in the data.

8 Parallelism and Performance

F08WAF (DGGEV) is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
F08WAF (DGGEV) makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The total number of floating-point operations is proportional to n 3.
The complex analogue of this routine is F08WNF (ZGGEV).

10 Example

This example finds all the eigenvalues and right eigenvectors of the matrix pair A,B, where
A = 3.9 12.5 -34.5 -0.5 4.3 21.5 -47.5 7.5 4.3 21.5 -43.5 3.5 4.4 26.0 -46.0 6.0   and   B= 1.0 2.0 -3.0 1.0 1.0 3.0 -5.0 4.0 1.0 3.0 -4.0 3.0 1.0 3.0 -4.0 4.0 .
Note that the block size (NB) of 64 assumed in this example is not realistic for such a small problem, but should be suitable for large problems.

10.1 Program Text

Program Text (f08wafe.f90)

10.2 Program Data

Program Data (f08wafe.d)

10.3 Program Results

Program Results (f08wafe.r)

F08 Chapter Contents
F08 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F08WBF (DGGEVX) : NAG Library, Mark 26

F08 Chapter Contents
F08 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F08WBF (DGGEVX)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F08WBF (DGGEVX) computes for a pair of n by n real nonsymmetric matrices A,B the generalized eigenvalues and, optionally, the left and/or right generalized eigenvectors using the QZ algorithm.
Optionally it also computes a balancing transformation to improve the conditioning of the eigenvalues and eigenvectors, reciprocal condition numbers for the eigenvalues, and reciprocal condition numbers for the right eigenvectors.

2 Specification

SUBROUTINE F08WBF ( BALANC, JOBVL, JOBVR, SENSE, N, A, LDA, B, LDB, ALPHAR, ALPHAI, BETA, VL, LDVL, VR, LDVR, ILO, IHI, LSCALE, RSCALE, ABNRM, BBNRM, RCONDE, RCONDV, WORK, LWORK, IWORK, BWORK, INFO)
INTEGER | N, LDA, LDB, LDVL, LDVR, ILO, IHI, LWORK, IWORK(*), INFO
REAL (KIND=nag_wp) | A(LDA,*), B(LDB,*), ALPHAR(N), ALPHAI(N), BETA(N), VL(LDVL,*), VR(LDVR,*), LSCALE(N), RSCALE(N), ABNRM, BBNRM, RCONDE(*), RCONDV(*), WORK(max(1,LWORK))
LOGICAL | BWORK(*)
CHARACTER(1) | BALANC, JOBVL, JOBVR, SENSE
The routine may be called by its LAPACK name dggevx.

3 Description

A generalized eigenvalue for a pair of matrices A,B is a scalar λ or a ratio α/β=λ, such that A-λB is singular. It is usually represented as the pair α,β, as there is a reasonable interpretation for β=0, and even for both being zero.
The right eigenvector vj corresponding to the eigenvalue λj of A,B satisfies
A vj = λj B vj .
The left eigenvector uj corresponding to the eigenvalue λj of A,B satisfies
ujH A = λj ujH B ,
where ujH is the conjugate-transpose of uj.
All the eigenvalues and, if required, all the eigenvectors of the generalized eigenproblem Ax=λBx, where A and B are real, square matrices, are determined using the QZ algorithm. The QZ algorithm consists of four stages:
1. | A is reduced to upper Hessenberg form and at the same time B is reduced to upper triangular form.
2. | A is further reduced to quasi-triangular form while the triangular form of B is maintained. This is the real generalized Schur form of the pair A,B .
3. The quasi-triangular form of A is reduced to triangular form and the eigenvalues extracted. This routine does not actually produce the eigenvalues λj, but instead returns αj and βj such that
λj=αj/βj,  j=1,2,…,n.
The division by βj becomes your responsibility, since βj may be zero, indicating an infinite eigenvalue. Pairs of complex eigenvalues occur with αj/βj and α j+1/β j+1 complex conjugates, even though αj and α j+1 are not conjugate.
4. | If the eigenvectors are required they are obtained from the triangular matrices and then transformed back into the original coordinate system.
For details of the balancing option, see Section 3 in F08WHF (DGGBAL).

4 References

Anderson E, Bai Z, Bischof C, Blackford S, Demmel J, Dongarra J J, Du Croz J J, Greenbaum A, Hammarling S, McKenney A and Sorensen D (1999) LAPACK Users' Guide (3rd Edition) SIAM, Philadelphia http://www.netlib.org/lapack/lug
Golub G H and Van Loan C F (2012) Matrix Computations (4th Edition) Johns Hopkins University Press, Baltimore
Wilkinson J H (1979) Kronecker's canonical form and the QZ algorithm Linear Algebra Appl. 28 285–303

5 Arguments

1:   BALANC – CHARACTER(1)Input
On entry: specifies the balance option to be performed.
BALANC='N'
Do not diagonally scale or permute.
BALANC='P'
Permute only.
BALANC='S'
Scale only.
BALANC='B'
Both permute and scale.
Computed reciprocal condition numbers will be for the matrices after permuting and/or balancing. Permuting does not change condition numbers (in exact arithmetic), but balancing does. In the absence of other information, BALANC='B' is recommended.
Constraint: BALANC='N', 'P', 'S' or 'B'.
2:   JOBVL – CHARACTER(1)Input
On entry: if JOBVL='N', do not compute the left generalized eigenvectors.
If JOBVL='V', compute the left generalized eigenvectors.
Constraint: JOBVL='N' or 'V'.
3:   JOBVR – CHARACTER(1)Input
On entry: if JOBVR='N', do not compute the right generalized eigenvectors.
If JOBVR='V', compute the right generalized eigenvectors.
Constraint: JOBVR='N' or 'V'.
4:   SENSE – CHARACTER(1)Input
On entry: determines which reciprocal condition numbers are computed.
SENSE='N'
None are computed.
SENSE='E'
Computed for eigenvalues only.
SENSE='V'
Computed for eigenvectors only.
SENSE='B'
Computed for eigenvalues and eigenvectors.
Constraint: SENSE='N', 'E', 'V' or 'B'.
5:   N – INTEGERInput
On entry: n, the order of the matrices A and B.
Constraint: N≥0.
6:   A LDA* – REAL (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array A must be at least max 1,N.
On entry: the matrix A in the pair A,B.
On exit: A has been overwritten. If JOBVL='V' or JOBVR='V' or both, then A contains the first part of the real Schur form of the ‘balanced’ versions of the input A and B.
7:   LDA – INTEGERInput
On entry: the first dimension of the array A as declared in the (sub)program from which F08WBF (DGGEVX) is called.
Constraint: LDA≥max 1,N.
8:   B LDB* – REAL (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array B must be at least max 1,N.
On entry: the matrix B in the pair A,B.
On exit: B has been overwritten.
9:   LDB – INTEGERInput
On entry: the first dimension of the array B as declared in the (sub)program from which F08WBF (DGGEVX) is called.
Constraint: LDB≥max 1,N.
10:   ALPHAR N – REAL (KIND=nag_wp) arrayOutput
On exit: the element ALPHAR j contains the real part of αj.
11:   ALPHAI N – REAL (KIND=nag_wp) arrayOutput
On exit: the element ALPHAI j contains the imaginary part of αj.
12:   BETA N – REAL (KIND=nag_wp) arrayOutput
On exit: ALPHAR j+ALPHAI j×i/BETA j, for j=1,2,…,N, will be the generalized eigenvalues.
If ALPHAI j is zero, then the jth eigenvalue is real; if positive, then the jth and j+1st eigenvalues are a complex conjugate pair, with ALPHAI j+1 negative.
Note: the quotients ALPHAR j/BETA j and ALPHAI j/BETA j may easily overflow or underflow, and BETA j may even be zero. Thus, you should avoid naively computing the ratio αj/βj. However, max αj will always be less than and usually comparable with A 2 in magnitude, and max βj will always be less than and usually comparable with B 2.
13:   VL LDVL* – REAL (KIND=nag_wp) arrayOutput
Note: the second dimension of the array VL must be at least max 1,N if JOBVL='V', and at least 1 otherwise.
On exit: if JOBVL='V', the left generalized eigenvectors uj are stored one after another in the columns of VL, in the same order as the corresponding eigenvalues. Each eigenvector will be scaled so the largest component will have real part+imag. part=1.
If JOBVL='N', VL is not referenced.
14:   LDVL – INTEGERInput
On entry: the first dimension of the array VL as declared in the (sub)program from which F08WBF (DGGEVX) is called.
Constraints:
  • if JOBVL='V', LDVL≥ max 1,N ;
  • otherwise LDVL≥1.
15:   VR LDVR* – REAL (KIND=nag_wp) arrayOutput
Note: the second dimension of the array VR must be at least max 1,N if JOBVR='V', and at least 1 otherwise.
On exit: if JOBVR='V', the right generalized eigenvectors vj are stored one after another in the columns of VR, in the same order as the corresponding eigenvalues. Each eigenvector will be scaled so the largest component will have real part+imag. part=1.
If JOBVR='N', VR is not referenced.
16:   LDVR – INTEGERInput
On entry: the first dimension of the array VR as declared in the (sub)program from which F08WBF (DGGEVX) is called.
Constraints:
  • if JOBVR='V', LDVR≥ max 1,N ;
  • otherwise LDVR≥1.
17:   ILO – INTEGEROutput
18:   IHI – INTEGEROutput
On exit: ILO and IHI are integer values such that A ij=0 and B ij=0 if i>j and j=1,2,…,ILO-1 or i=IHI+1,…,N.
If BALANC='N' or 'S', ILO=1 and IHI=N.
19:   LSCALE N – REAL (KIND=nag_wp) arrayOutput
On exit: details of the permutations and scaling factors applied to the left side of A and B.
If plj is the index of the row interchanged with row j, and dlj is the scaling factor applied to row j, then:
  • LSCALE j = plj , for j=1,2,…,ILO-1;
  • LSCALE = dlj , for j=ILO,…,IHI;
  • LSCALE = plj , for j=IHI+1,…,N.
The order in which the interchanges are made is N to IHI+1, then 1 to ILO-1.
20:   RSCALE N – REAL (KIND=nag_wp) arrayOutput
On exit: details of the permutations and scaling factors applied to the right side of A and B.
If prj is the index of the column interchanged with column j, and drj is the scaling factor applied to column j, then:
  • RSCALE j=prj, for j=1,2,…,ILO-1;
  • if RSCALE=drj, for j=ILO,…,IHI;
  • if RSCALE=prj, for j=IHI+1,…,N.
The order in which the interchanges are made is N to IHI+1, then 1 to ILO-1.
21:   ABNRM – REAL (KIND=nag_wp)Output
On exit: the 1-norm of the balanced matrix A.
22:   BBNRM – REAL (KIND=nag_wp)Output
On exit: the 1-norm of the balanced matrix B.
23:   RCONDE* – REAL (KIND=nag_wp) arrayOutput
Note: the dimension of the array RCONDE must be at least max 1,N.
On exit: if SENSE='E' or 'B', the reciprocal condition numbers of the eigenvalues, stored in consecutive elements of the array. For a complex conjugate pair of eigenvalues two consecutive elements of RCONDE are set to the same value. Thus RCONDE j, RCONDV j, and the jth columns of VL and VR all correspond to the jth eigenpair.
If SENSE='V', RCONDE is not referenced.
24:   RCONDV* – REAL (KIND=nag_wp) arrayOutput
Note: the dimension of the array RCONDV must be at least max 1,N.
On exit: if SENSE='V' or 'B', the estimated reciprocal condition numbers of the eigenvectors, stored in consecutive elements of the array. For a complex eigenvector two consecutive elements of RCONDV are set to the same value.
If SENSE='E', RCONDV is not referenced.
25:   WORK max 1,LWORK – REAL (KIND=nag_wp) arrayWorkspace
On exit: if INFO=0, WORK 1 contains the minimum value of LWORK required for optimal performance.
26:   LWORK – INTEGERInput
On entry: the dimension of the array WORK as declared in the (sub)program from which F08WBF (DGGEVX) is called.
If LWORK=-1, a workspace query is assumed; the routine only calculates the optimal size of the WORK array, returns this value as the first entry of the WORK array, and no error message related to LWORK is issued.
Suggested value: for optimal performance, LWORK must generally be larger than the minimum; increase workspace by, say, nb×N, where nb is the optimal block size.
Constraints:
  • if SENSE='N',
    • if BALANC='N' or 'P' and JOBVL='N' and JOBVR='N', LWORK≥max 1,2×N;
    • otherwise LWORK≥max 1,6×N;
  • if SENSE='E', LWORK≥max 1,10×N;
  • if SENSE='B' or SENSE='V', LWORK≥max 10×N,2×N×N+4+16.
27:   IWORK* – INTEGER arrayWorkspace
Note: the dimension of the array IWORK must be at least N+6.
If SENSE='E', IWORK is not referenced.
28:   BWORK* – LOGICAL arrayWorkspace
Note: the dimension of the array BWORK must be at least max 1,N.
If SENSE='N', BWORK is not referenced.
29:   INFO – INTEGEROutput
On exit: INFO=0 unless the routine detects an error (see Section 6).

6 Error Indicators and Warnings

INFO<0
If INFO=-i, argument i had an illegal value. An explanatory message is output, and execution of the program is terminated.
INFO=1 to N
The QZ iteration failed. No eigenvectors have been calculated, but ALPHAR j, ALPHAI j, and BETA j should be correct for j=INFO+1,…,N.
INFO=N+1
Unexpected error returned from F08XEF (DHGEQZ).
INFO=N+2
Error returned from F08YKF (DTGEVC).

7 Accuracy

The computed eigenvalues and eigenvectors are exact for nearby matrices A+E and B+F, where
E,F F = O ε A,B F ,
and ε is the machine precision.
An approximate error bound on the chordal distance between the ith computed generalized eigenvalue w and the corresponding exact eigenvalue λ is
ε × ABNRM,BBNRM 2 / RCONDE i .
An approximate error bound for the angle between the ith computed eigenvector uj or vj is given by
ε × ABNRM,BBNRM 2 / RCONDV i .
For further explanation of the reciprocal condition numbers RCONDE and RCONDV, see Section 4.11 of Anderson et al. (1999).
Note: interpretation of results obtained with the QZ algorithm often requires a clear understanding of the effects of small changes in the original data. These effects are reviewed in Wilkinson (1979), in relation to the significance of small values of αj and βj. It should be noted that if αj and βj are both small for any j, it may be that no reliance can be placed on any of the computed eigenvalues λi=αi/βi. You are recommended to study Wilkinson (1979) and, if in difficulty, to seek expert advice on determining the sensitivity of the eigenvalues to perturbations in the data.

8 Parallelism and Performance

F08WBF (DGGEVX) is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
F08WBF (DGGEVX) makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The total number of floating-point operations is proportional to n 3.
The complex analogue of this routine is F08WPF (ZGGEVX).

10 Example

This example finds all the eigenvalues and right eigenvectors of the matrix pair A,B, where
A = 3.9 12.5 -34.5 -0.5 4.3 21.5 -47.5 7.5 4.3 21.5 -43.5 3.5 4.4 26.0 -46.0 6.0   and   B= 1.0 2.0 -3.0 1.0 1.0 3.0 -5.0 4.0 1.0 3.0 -4.0 3.0 1.0 3.0 -4.0 4.0 ,
together with estimates of the condition number and forward error bounds for each eigenvalue and eigenvector. The option to balance the matrix pair is used.
Note that the block size (NB) of 64 assumed in this example is not realistic for such a small problem, but should be suitable for large problems.

10.1 Program Text

Program Text (f08wbfe.f90)

10.2 Program Data

Program Data (f08wbfe.d)

10.3 Program Results

Program Results (f08wbfe.r)

F08 Chapter Contents
F08 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F08WCF (DGGEV3) : NAG Library, Mark 26

F08 Chapter Contents
F08 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F08WCF (DGGEV3)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F08WCF (DGGEV3) computes for a pair of n by n real nonsymmetric matrices A,B the generalized eigenvalues and, optionally, the left and/or right generalized eigenvectors using the QZ algorithm.

2 Specification

SUBROUTINE F08WCF ( JOBVL, JOBVR, N, A, LDA, B, LDB, ALPHAR, ALPHAI, BETA, VL, LDVL, VR, LDVR, WORK, LWORK, INFO)
INTEGER | N, LDA, LDB, LDVL, LDVR, LWORK, INFO
REAL (KIND=nag_wp) | A(LDA,*), B(LDB,*), ALPHAR(N), ALPHAI(N), BETA(N), VL(LDVL,*), VR(LDVR,*), WORK(max(1,LWORK))
CHARACTER(1) | JOBVL, JOBVR
The routine may be called by its LAPACK name dggev3.

3 Description

A generalized eigenvalue for a pair of matrices A,B is a scalar λ or a ratio α/β=λ, such that A-λB is singular. It is usually represented as the pair α,β, as there is a reasonable interpretation for β=0, and even for both being zero.
The right eigenvector vj corresponding to the eigenvalue λj of A,B satisfies
A vj = λj B vj .
The left eigenvector uj corresponding to the eigenvalue λj of A,B satisfies
ujH A = λj ujH B ,
where ujH is the conjugate-transpose of uj.
All the eigenvalues and, if required, all the eigenvectors of the generalized eigenproblem Ax=λBx, where A and B are real, square matrices, are determined using the QZ algorithm. The QZ algorithm consists of four stages:
1. | A is reduced to upper Hessenberg form and at the same time B is reduced to upper triangular form.
2. | A is further reduced to quasi-triangular form while the triangular form of B is maintained. This is the real generalized Schur form of the pair A,B .
3. The quasi-triangular form of A is reduced to triangular form and the eigenvalues extracted. This routine does not actually produce the eigenvalues λj, but instead returns αj and βj such that
λj=αj/βj,  j=1,2,…,n.
The division by βj becomes your responsibility, since βj may be zero, indicating an infinite eigenvalue. Pairs of complex eigenvalues occur with αj/βj and α j+1/β j+1 complex conjugates, even though αj and α j+1 are not conjugate.
4. | If the eigenvectors are required they are obtained from the triangular matrices and then transformed back into the original coordinate system.

4 References

Anderson E, Bai Z, Bischof C, Blackford S, Demmel J, Dongarra J J, Du Croz J J, Greenbaum A, Hammarling S, McKenney A and Sorensen D (1999) LAPACK Users' Guide (3rd Edition) SIAM, Philadelphia http://www.netlib.org/lapack/lug
Golub G H and Van Loan C F (2012) Matrix Computations (4th Edition) Johns Hopkins University Press, Baltimore
Wilkinson J H (1979) Kronecker's canonical form and the QZ algorithm Linear Algebra Appl. 28 285–303

5 Arguments

1:   JOBVL – CHARACTER(1)Input
On entry: if JOBVL='N', do not compute the left generalized eigenvectors.
If JOBVL='V', compute the left generalized eigenvectors.
Constraint: JOBVL='N' or 'V'.
2:   JOBVR – CHARACTER(1)Input
On entry: if JOBVR='N', do not compute the right generalized eigenvectors.
If JOBVR='V', compute the right generalized eigenvectors.
Constraint: JOBVR='N' or 'V'.
3:   N – INTEGERInput
On entry: n, the order of the matrices A and B.
Constraint: N≥0.
4:   A LDA* – REAL (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array A must be at least max 1,N.
On entry: the matrix A in the pair A,B.
On exit: A has been overwritten.
5:   LDA – INTEGERInput
On entry: the first dimension of the array A as declared in the (sub)program from which F08WCF (DGGEV3) is called.
Constraint: LDA≥max 1,N.
6:   B LDB* – REAL (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array B must be at least max 1,N.
On entry: the matrix B in the pair A,B.
On exit: B has been overwritten.
7:   LDB – INTEGERInput
On entry: the first dimension of the array B as declared in the (sub)program from which F08WCF (DGGEV3) is called.
Constraint: LDB≥max 1,N.
8:   ALPHAR N – REAL (KIND=nag_wp) arrayOutput
On exit: the element ALPHAR j contains the real part of αj.
9:   ALPHAI N – REAL (KIND=nag_wp) arrayOutput
On exit: the element ALPHAI j contains the imaginary part of αj.
10:   BETA N – REAL (KIND=nag_wp) arrayOutput
On exit: ALPHAR j+ALPHAI j×i/BETA j, for j=1,2,…,N, will be the generalized eigenvalues.
If ALPHAI j is zero, then the jth eigenvalue is real; if positive, then the jth and j+1st eigenvalues are a complex conjugate pair, with ALPHAI j+1 negative.
Note: the quotients ALPHAR j/BETA j and ALPHAI j/BETA j may easily overflow or underflow, and BETA j may even be zero. Thus, you should avoid naively computing the ratio αj/βj. However, max αj will always be less than and usually comparable with A 2 in magnitude, and max βj will always be less than and usually comparable with B 2.
11:   VL LDVL* – REAL (KIND=nag_wp) arrayOutput
Note: the second dimension of the array VL must be at least max 1,N if JOBVL='V', and at least 1 otherwise.
On exit: if JOBVL='V', the left eigenvectors uj are stored one after another in the columns of VL, in the same order as the corresponding eigenvalues.
If the jth eigenvalue is real, then uj=VL:,j, the jth column of VL.
If the jth and j+1th eigenvalues form a complex conjugate pair, then uj=VL:,j+i×VL:,j+1 and u j+1=VL:,j-i×VL:,j+1. Each eigenvector will be scaled so the largest component has real part+imag. part=1.
If JOBVL='N', VL is not referenced.
12:   LDVL – INTEGERInput
On entry: the first dimension of the array VL as declared in the (sub)program from which F08WCF (DGGEV3) is called.
Constraints:
  • if JOBVL='V', LDVL≥ max 1,N ;
  • otherwise LDVL≥1.
13:   VR LDVR* – REAL (KIND=nag_wp) arrayOutput
Note: the second dimension of the array VR must be at least max 1,N if JOBVR='V', and at least 1 otherwise.
On exit: if JOBVR='V', the right eigenvectors vj are stored one after another in the columns of VR, in the same order as the corresponding eigenvalues.
If the jth eigenvalue is real, then vj=VR:,j, the jth column of VR.
If the jth and j+1th eigenvalues form a complex conjugate pair, then vj=VR:,j+i×VR:,j+1 and v j+1=VR:,j-i×VR:,j+1. Each eigenvector will be scaled so the largest component has real part+imag. part=1.
If JOBVR='N', VR is not referenced.
14:   LDVR – INTEGERInput
On entry: the first dimension of the array VR as declared in the (sub)program from which F08WCF (DGGEV3) is called.
Constraints:
  • if JOBVR='V', LDVR≥ max 1,N ;
  • otherwise LDVR≥1.
15:   WORK max 1,LWORK – REAL (KIND=nag_wp) arrayWorkspace
On exit: if INFO=0, WORK 1 contains the minimum value of LWORK required for optimal performance.
16:   LWORK – INTEGERInput
On entry: the dimension of the array WORK as declared in the (sub)program from which F08WCF (DGGEV3) is called.
If LWORK=-1, a workspace query is assumed; the routine only calculates the optimal size of the WORK array, returns this value as the first entry of the WORK array, and no error message related to LWORK is issued.
Suggested value: for optimal performance, LWORK must generally be larger than the minimum; increase workspace by, say, 6×nb×N, where nb is the optimal block size.
Constraint: LWORK≥max 1,8×N.
17:   INFO – INTEGEROutput
On exit: INFO=0 unless the routine detects an error (see Section 6).

6 Error Indicators and Warnings

INFO<0
If INFO=-i, argument i had an illegal value. An explanatory message is output, and execution of the program is terminated.
INFO=1 to N
The QZ iteration failed. No eigenvectors have been calculated but ALPHAR j, ALPHAI j and BETA j should be correct from element value.
INFO=N+1
The QZ iteration failed with an unexpected error, please contact NAG.
INFO=N+2
A failure occurred in F08YKF (DTGEVC) while computing generalized eigenvectors.

7 Accuracy

The computed eigenvalues and eigenvectors are exact for nearby matrices A+E and B+F, where
E,F F = O ε A,B F ,
and ε is the machine precision. See Section 4.11 of Anderson et al. (1999) for further details.
Note: interpretation of results obtained with the QZ algorithm often requires a clear understanding of the effects of small changes in the original data. These effects are reviewed in Wilkinson (1979), in relation to the significance of small values of αj and βj. It should be noted that if αj and βj are both small for any j, it may be that no reliance can be placed on any of the computed eigenvalues λi=αi/βi. You are recommended to study Wilkinson (1979) and, if in difficulty, to seek expert advice on determining the sensitivity of the eigenvalues to perturbations in the data.

8 Parallelism and Performance

F08WCF (DGGEV3) is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
F08WCF (DGGEV3) makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The total number of floating-point operations is proportional to n 3.
The complex analogue of this routine is F08WQF (ZGGEV3).

10 Example

This example finds all the eigenvalues and right eigenvectors of the matrix pair A,B, where
A = 3.9 12.5 -34.5 -0.5 4.3 21.5 -47.5 7.5 4.3 21.5 -43.5 3.5 4.4 26.0 -46.0 6.0   and   B= 1.0 2.0 -3.0 1.0 1.0 3.0 -5.0 4.0 1.0 3.0 -4.0 3.0 1.0 3.0 -4.0 4.0 .

10.1 Program Text

Program Text (f08wcfe.f90)

10.2 Program Data

Program Data (f08wcfe.d)

10.3 Program Results

Program Results (f08wcfe.r)

F08 Chapter Contents
F08 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F08WEF (DGGHRD) : NAG Library, Mark 26

F08 Chapter Contents
F08 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F08WEF (DGGHRD)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
10 Example

1 Purpose

F08WEF (DGGHRD) reduces a pair of real matrices A,B, where B is upper triangular, to the generalized upper Hessenberg form using orthogonal transformations. F08WEF (DGGHRD) is marked as deprecated by LAPACK; the replacement routine is F08WFF (DGGHD3) which makes better use of level 3 BLAS.

2 Specification

SUBROUTINE F08WEF ( COMPQ, COMPZ, N, ILO, IHI, A, LDA, B, LDB, Q, LDQ, Z, LDZ, INFO)
INTEGER | N, ILO, IHI, LDA, LDB, LDQ, LDZ, INFO
REAL (KIND=nag_wp) | A(LDA,*), B(LDB,*), Q(LDQ,*), Z(LDZ,*)
CHARACTER(1) | COMPQ, COMPZ
The routine may be called by its LAPACK name dgghrd.

3 Description

F08WEF (DGGHRD) is the third step in the solution of the real generalized eigenvalue problem
Ax=λBx.
The (optional) first step balances the two matrices using F08WHF (DGGBAL). In the second step, matrix B is reduced to upper triangular form using the QR factorization routine F08AEF (DGEQRF) and this orthogonal transformation Q is applied to matrix A by calling F08AGF (DORMQR).
F08WEF (DGGHRD) reduces a pair of real matrices A,B, where B is upper triangular, to the generalized upper Hessenberg form using orthogonal transformations. This two-sided transformation is of the form
QT AZ=H QT BZ=T
where H is an upper Hessenberg matrix, T is an upper triangular matrix and Q and Z are orthogonal matrices determined as products of Givens rotations. They may either be formed explicitly, or they may be postmultiplied into input matrices Q 1 and Z 1, so that
Q 1 A Z 1 T=Q 1 Q H Z 1 Z T, Q 1 B Z 1 T=Q 1 Q T Z 1 Z T.

4 References

Golub G H and Van Loan C F (1996) Matrix Computations (3rd Edition) Johns Hopkins University Press, Baltimore
Moler C B and Stewart G W (1973) An algorithm for generalized matrix eigenproblems SIAM J. Numer. Anal. 10 241–256

5 Arguments

1:   COMPQ – CHARACTER(1)Input
On entry: specifies the form of the computed orthogonal matrix Q.
COMPQ='N'
Do not compute Q.
COMPQ='I'
The orthogonal matrix Q is returned.
COMPQ='V'
Q must contain an orthogonal matrix Q 1, and the product Q 1 Q is returned.
Constraint: COMPQ='N', 'I' or 'V'.
2:   COMPZ – CHARACTER(1)Input
On entry: specifies the form of the computed orthogonal matrix Z.
COMPZ='N'
Do not compute Z.
COMPZ='I'
The orthogonal matrix Z is returned.
COMPZ='V'
Z must contain an orthogonal matrix Z 1, and the product Z 1 Z is returned.
Constraint: COMPZ='N', 'V' or 'I'.
3:   N – INTEGERInput
On entry: n, the order of the matrices A and B.
Constraint: N≥0.
4:   ILO – INTEGERInput
5:   IHI – INTEGERInput
On entry: ilo and ihi as determined by a previous call to F08WHF (DGGBAL). Otherwise, they should be set to 1 and n, respectively.
Constraints:
  • if N>0, 1≤ ILO≤ IHI≤ N ;
  • if N=0, ILO=1 and IHI=0.
6:   A LDA* – REAL (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array A must be at least max 1,N.
On entry: the matrix A of the matrix pair A,B. Usually, this is the matrix A returned by F08AGF (DORMQR).
On exit: A is overwritten by the upper Hessenberg matrix H.
7:   LDA – INTEGERInput
On entry: the first dimension of the array A as declared in the (sub)program from which F08WEF (DGGHRD) is called.
Constraint: LDA≥max 1,N.
8:   B LDB* – REAL (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array B must be at least max 1,N.
On entry: the upper triangular matrix B of the matrix pair A,B. Usually, this is the matrix B returned by the QR factorization routine F08AEF (DGEQRF).
On exit: B is overwritten by the upper triangular matrix T.
9:   LDB – INTEGERInput
On entry: the first dimension of the array B as declared in the (sub)program from which F08WEF (DGGHRD) is called.
Constraint: LDB≥max 1,N.
10:   Q LDQ* – REAL (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array Q must be at least max 1,N if COMPQ='I' or 'V' and at least 1 if COMPQ='N'.
On entry: if COMPQ='V', Q must contain an orthogonal matrix Q 1.
If COMPQ='N', Q is not referenced.
On exit: if COMPQ='I', Q contains the orthogonal matrix Q.
If COMPQ='V', Q is overwritten by Q 1 Q.
11:   LDQ – INTEGERInput
On entry: the first dimension of the array Q as declared in the (sub)program from which F08WEF (DGGHRD) is called.
Constraints:
  • if COMPQ='I' or 'V', LDQ≥ max 1,N ;
  • if COMPQ='N', LDQ≥1.
12:   Z LDZ* – REAL (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array Z must be at least max 1,N if COMPZ='V' or 'I' and at least 1 if COMPZ='N'.
On entry: if COMPZ='V', Z must contain an orthogonal matrix Z 1.
If COMPZ='N', Z is not referenced.
On exit: if COMPZ='I', Z contains the orthogonal matrix Z.
If COMPZ='V', Z is overwritten by Z 1 Z.
13:   LDZ – INTEGERInput
On entry: the first dimension of the array Z as declared in the (sub)program from which F08WEF (DGGHRD) is called.
Constraints:
  • if COMPZ='V' or 'I', LDZ≥ max 1,N ;
  • if COMPZ='N', LDZ≥1.
14:   INFO – INTEGEROutput
On exit: INFO=0 unless the routine detects an error (see Section 6).

6 Error Indicators and Warnings

INFO<0
If INFO=-i, argument i had an illegal value. An explanatory message is output, and execution of the program is terminated.

7 Accuracy

The reduction to the generalized Hessenberg form is implemented using orthogonal transformations which are backward stable.

8 Parallelism and Performance

F08WEF (DGGHRD) makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

This routine is usually followed by F08XEF (DHGEQZ) which implements the QZ algorithm for computing generalized eigenvalues of a reduced pair of matrices.
The complex analogue of this routine is F08WSF (ZGGHRD).

10 Example

See Section 10 in F08XEF (DHGEQZ) and F08YKF (DTGEVC).
F08 Chapter Contents
F08 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F08WFF (DGGHD3) : NAG Library, Mark 26

F08 Chapter Contents
F08 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F08WFF (DGGHD3)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
10 Example

1 Purpose

F08WFF (DGGHD3) reduces a pair of real matrices A,B, where B is upper triangular, to the generalized upper Hessenberg form using orthogonal transformations.

2 Specification

SUBROUTINE F08WFF ( COMPQ, COMPZ, N, ILO, IHI, A, LDA, B, LDB, Q, LDQ, Z, LDZ, WORK, LWORK, INFO)
INTEGER | N, ILO, IHI, LDA, LDB, LDQ, LDZ, LWORK, INFO
REAL (KIND=nag_wp) | A(LDA,*), B(LDB,*), Q(LDQ,*), Z(LDZ,*), WORK(max(1,LWORK))
CHARACTER(1) | COMPQ, COMPZ
The routine may be called by its LAPACK name dgghd3.

3 Description

F08WFF (DGGHD3) is the third step in the solution of the real generalized eigenvalue problem
Ax=λBx.
The (optional) first step balances the two matrices using F08WHF (DGGBAL). In the second step, matrix B is reduced to upper triangular form using the QR factorization routine F08AEF (DGEQRF) and this orthogonal transformation Q is applied to matrix A by calling F08AGF (DORMQR). The driver, F08WCF (DGGEV3), solves the real generalized eigenvalue problem by combining all the required steps including those just listed.
F08WFF (DGGHD3) reduces a pair of real matrices A,B, where B is upper triangular, to the generalized upper Hessenberg form using orthogonal transformations. This two-sided transformation is of the form
QT AZ=H, QT BZ=T
where H is an upper Hessenberg matrix, T is an upper triangular matrix and Q and Z are orthogonal matrices determined as products of Givens rotations. They may either be formed explicitly, or they may be postmultiplied into input matrices Q 1 and Z 1, so that
Q 1 A Z 1 T=Q 1 Q H Z 1 Z T, Q 1 B Z 1 T=Q 1 Q T Z 1 Z T.

4 References

Golub G H and Van Loan C F (2012) Matrix Computations (4th Edition) Johns Hopkins University Press, Baltimore
Moler C B and Stewart G W (1973) An algorithm for generalized matrix eigenproblems SIAM J. Numer. Anal. 10 241–256

5 Arguments

1:   COMPQ – CHARACTER(1)Input
On entry: specifies the form of the computed orthogonal matrix Q.
COMPQ='N'
Do not compute Q.
COMPQ='I'
The orthogonal matrix Q is returned.
COMPQ='V'
Q must contain an orthogonal matrix Q 1, and the product Q 1 Q is returned.
Constraint: COMPQ='N', 'I' or 'V'.
2:   COMPZ – CHARACTER(1)Input
On entry: specifies the form of the computed orthogonal matrix Z.
COMPZ='N'
Do not compute Z.
COMPZ='I'
The orthogonal matrix Z is returned.
COMPZ='V'
Z must contain an orthogonal matrix Z 1, and the product Z 1 Z is returned.
Constraint: COMPZ='N', 'V' or 'I'.
3:   N – INTEGERInput
On entry: n, the order of the matrices A and B.
Constraint: N≥0.
4:   ILO – INTEGERInput
5:   IHI – INTEGERInput
On entry: ilo and ihi as determined by a previous call to F08WHF (DGGBAL). Otherwise, they should be set to 1 and n, respectively.
Constraints:
  • if N>0, 1≤ ILO≤ IHI≤ N ;
  • if N=0, ILO=1 and IHI=0.
6:   A LDA* – REAL (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array A must be at least max 1,N.
On entry: the matrix A of the matrix pair A,B. Usually, this is the matrix A returned by F08AGF (DORMQR).
On exit: A is overwritten by the upper Hessenberg matrix H.
7:   LDA – INTEGERInput
On entry: the first dimension of the array A as declared in the (sub)program from which F08WFF (DGGHD3) is called.
Constraint: LDA≥max 1,N.
8:   B LDB* – REAL (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array B must be at least max 1,N.
On entry: the upper triangular matrix B of the matrix pair A,B. Usually, this is the matrix B returned by the QR factorization routine F08AEF (DGEQRF).
On exit: B is overwritten by the upper triangular matrix T.
9:   LDB – INTEGERInput
On entry: the first dimension of the array B as declared in the (sub)program from which F08WFF (DGGHD3) is called.
Constraint: LDB≥max 1,N.
10:   Q LDQ* – REAL (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array Q must be at least max 1,N if COMPQ='I' or 'V' and at least 1 if COMPQ='N'.
On entry: if COMPQ='V', Q must contain an orthogonal matrix Q 1.
If COMPQ='N', Q is not referenced.
On exit: if COMPQ='I', Q contains the orthogonal matrix Q.
If COMPQ='V', Q is overwritten by Q 1 Q.
11:   LDQ – INTEGERInput
On entry: the first dimension of the array Q as declared in the (sub)program from which F08WFF (DGGHD3) is called.
Constraints:
  • if COMPQ='I' or 'V', LDQ≥ max 1,N ;
  • if COMPQ='N', LDQ≥1.
12:   Z LDZ* – REAL (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array Z must be at least max 1,N if COMPZ='V' or 'I' and at least 1 if COMPZ='N'.
On entry: if COMPZ='V', Z must contain an orthogonal matrix Z 1.
If COMPZ='N', Z is not referenced.
On exit: if COMPZ='I', Z contains the orthogonal matrix Z.
If COMPZ='V', Z is overwritten by Z 1 Z.
13:   LDZ – INTEGERInput
On entry: the first dimension of the array Z as declared in the (sub)program from which F08WFF (DGGHD3) is called.
Constraints:
  • if COMPZ='V' or 'I', LDZ≥ max 1,N ;
  • if COMPZ='N', LDZ≥1.
14:   WORK max 1,LWORK – REAL (KIND=nag_wp) arrayWorkspace
On exit: if INFO=0, WORK 1 contains the minimum value of LWORK required for optimal performance.
15:   LWORK – INTEGERInput
On entry: the dimension of the array WORK as declared in the (sub)routine from which F08WFF (DGGHD3) is called.
If LWORK=-1, a workspace query is assumed; the routine only calculates the optimal size of the WORK array, returns this value as the first entry of the WORK array, and no error message related to LWORK is issued.
Suggested value: for optimal performance, LWORK must generally be larger than the minimum; increase workspace by, say, 6×nb×N, where nb is the optimal block size.
16:   INFO – INTEGEROutput
On exit: INFO=0 unless the routine detects an error (see Section 6).

6 Error Indicators and Warnings

INFO<0
If INFO=-i, argument i had an illegal value. An explanatory message is output, and execution of the program is terminated.

7 Accuracy

The reduction to the generalized Hessenberg form is implemented using orthogonal transformations which are backward stable.

8 Parallelism and Performance

F08WFF (DGGHD3) makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

This routine is usually followed by F08XEF (DHGEQZ) which implements the QZ algorithm for computing generalized eigenvalues of a reduced pair of matrices.
The complex analogue of this routine is F08WTF (ZGGHD3).

10 Example

See Section 10 in F08XEF (DHGEQZ) and F08YKF (DTGEVC).
F08 Chapter Contents
F08 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F08WHF (DGGBAL) : NAG Library, Mark 26

F08 Chapter Contents
F08 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F08WHF (DGGBAL)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
10 Example

1 Purpose

F08WHF (DGGBAL) balances a pair of real square matrices A,B of order n. Balancing usually improves the accuracy of computed generalized eigenvalues and eigenvectors.

2 Specification

SUBROUTINE F08WHF ( JOB, N, A, LDA, B, LDB, ILO, IHI, LSCALE, RSCALE, WORK, INFO)
INTEGER | N, LDA, LDB, ILO, IHI, INFO
REAL (KIND=nag_wp) | A(LDA,*), B(LDB,*), LSCALE(N), RSCALE(N), WORK(*)
CHARACTER(1) | JOB
The routine may be called by its LAPACK name dggbal.

3 Description

Balancing may reduce the 1-norms of the matrices and improve the accuracy of the computed eigenvalues and eigenvectors in the real generalized eigenvalue problem
Ax=λBx.
F08WHF (DGGBAL) is usually the first step in the solution of the above generalized eigenvalue problem. Balancing is optional but it is highly recommended.
The term ‘balancing’ covers two steps, each of which involves similarity transformations on A and B. The routine can perform either or both of these steps. Both steps are optional.
1. The routine first attempts to permute A and B to block upper triangular form by a similarity transformation:
PA PT=F= F 11 F 12 F 13 F 22 F 23 F 33
PB PT=G= G 11 G 12 G 13 G 22 G 23 G 33
where P is a permutation matrix, F 11, F 33, G 11 and G 33 are upper triangular. Then the diagonal elements of the matrix pairs F 11,G 11 and F 33,G 33 are generalized eigenvalues of A,B. The rest of the generalized eigenvalues are given by the matrix pair F 22,G 22 which are in rows and columns ilo to ihi. Subsequent operations to compute the generalized eigenvalues of A,B need only be applied to the matrix pair F 22,G 22; this can save a significant amount of work if ilo>1 and ihi<n. If no suitable permutation exists (as is often the case), the routine sets ilo=1 and ihi=n.
2. The routine applies a diagonal similarity transformation to F,G, to make the rows and columns of F 22,G 22 as close in norm as possible:
DF D^= I 0 0 0 D 22 0 0 0 I F 11 F 12 F 13 F 22 F 23 F 33 I 0 0 0 D^22 0 0 0 I
DG D^= I 0 0 0 D 22 0 0 0 I G 11 G 12 G 13 G 22 G 23 G 33 I 0 0 0 D^22 0 0 0 I
This transformation usually improves the accuracy of computed generalized eigenvalues and eigenvectors.

4 References

Ward R C (1981) Balancing the generalized eigenvalue problem SIAM J. Sci. Stat. Comp. 2 141–152

5 Arguments

1:   JOB – CHARACTER(1)Input
On entry: specifies the operations to be performed on matrices A and B.
JOB='N'
No balancing is done. Initialize ILO=1, IHI=N, LSCALE i=1.0 and RSCALE i=1.0, for i=1,2,…,n.
JOB='P'
Only permutations are used in balancing.
JOB='S'
Only scalings are are used in balancing.
JOB='B'
Both permutations and scalings are used in balancing.
Constraint: JOB='N', 'P', 'S' or 'B'.
2:   N – INTEGERInput
On entry: n, the order of the matrices A and B.
Constraint: N≥0.
3:   A LDA* – REAL (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array A must be at least max 1,N.
On entry: the n by n matrix A.
On exit: A is overwritten by the balanced matrix. If JOB='N', A is not referenced.
4:   LDA – INTEGERInput
On entry: the first dimension of the array A as declared in the (sub)program from which F08WHF (DGGBAL) is called.
Constraint: LDA≥max 1,N.
5:   B LDB* – REAL (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array B must be at least max 1,N.
On entry: the n by n matrix B.
On exit: B is overwritten by the balanced matrix. If JOB='N', B is not referenced.
6:   LDB – INTEGERInput
On entry: the first dimension of the array B as declared in the (sub)program from which F08WHF (DGGBAL) is called.
Constraint: LDB≥max 1,N.
7:   ILO – INTEGEROutput
8:   IHI – INTEGEROutput
On exit: ilo and ihi are set such that A ij=0 and B ij=0 if i>j and 1≤j<ilo or ihi<i≤n.
If JOB='N' or 'S', ilo=1 and ihi=n.
9:   LSCALE N – REAL (KIND=nag_wp) arrayOutput
On exit: details of the permutations and scaling factors applied to the left side of the matrices A and B. If Pi is the index of the row interchanged with row i and di is the scaling factor applied to row i, then
  • LSCALE i=Pi, for i=1,2,…,ilo-1;
  • LSCALE i=di, for i=ilo,…,ihi;
  • LSCALE i=Pi, for i=ihi+1,…,n.
The order in which the interchanges are made is n to ihi+1, then 1 to ilo-1.
10:   RSCALE N – REAL (KIND=nag_wp) arrayOutput
On exit: details of the permutations and scaling factors applied to the right side of the matrices A and B.
If Pj is the index of the column interchanged with column j and d^j is the scaling factor applied to column j, then
  • RSCALE j=Pj, for j=1,2,…,ilo-1;
  • RSCALE j=d^j, for j=ilo,…,ihi;
  • RSCALE j=Pj, for j=ihi+1,…,n.
The order in which the interchanges are made is n to ihi+1, then 1 to ilo-1.
11:   WORK* – REAL (KIND=nag_wp) arrayWorkspace
Note: the dimension of the array WORK must be at least max 1,6×N if JOB='S' or 'B' and at least 1 if JOB='N' or 'P'.
12:   INFO – INTEGEROutput
On exit: INFO=0 unless the routine detects an error (see Section 6).

6 Error Indicators and Warnings

INFO<0
If INFO=-i, argument i had an illegal value. An explanatory message is output, and execution of the program is terminated.

7 Accuracy

The errors are negligible, compared to those in subsequent computations.

8 Parallelism and Performance

F08WHF (DGGBAL) makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

F08WHF (DGGBAL) is usually the first step in computing the real generalized eigenvalue problem but it is an optional step. The matrix B is reduced to the upper triangular form using the QR factorization routine F08AEF (DGEQRF) and this orthogonal transformation Q is applied to the matrix A by calling F08AGF (DORMQR). This is followed by F08WEF (DGGHRD) which reduces the matrix pair into the generalized Hessenberg form.
If the matrix pair A,B is balanced by this routine, then any generalized eigenvectors computed subsequently are eigenvectors of the balanced matrix pair. In that case, to compute the generalized eigenvectors of the original matrix, F08WJF (DGGBAK) must be called.
The total number of floating-point operations is approximately proportional to n 2.
The complex analogue of this routine is F08WVF (ZGGBAL).

10 Example

See Section 10 in F08XEF (DHGEQZ) and F08YKF (DTGEVC).
F08 Chapter Contents
F08 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F08WJF (DGGBAK) : NAG Library, Mark 26

F08 Chapter Contents
F08 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F08WJF (DGGBAK)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
10 Example

1 Purpose

F08WJF (DGGBAK) forms the right or left eigenvectors of the real generalized eigenvalue problem Ax=λBx, by backward transformation on the computed eigenvectors given by F08YKF (DTGEVC). It is necessary to call this routine only if the optional balancing routine F08WHF (DGGBAL) was previously called to balance the matrix pair A,B.

2 Specification

SUBROUTINE F08WJF ( JOB, SIDE, N, ILO, IHI, LSCALE, RSCALE, M, V, LDV, INFO)
INTEGER | N, ILO, IHI, M, LDV, INFO
REAL (KIND=nag_wp) | LSCALE(*), RSCALE(*), V(LDV,*)
CHARACTER(1) | JOB, SIDE
The routine may be called by its LAPACK name dggbak.

3 Description

If the matrix pair has been previously balanced using the routine F08WHF (DGGBAL) then F08WJF (DGGBAK) backtransforms the eigenvector solution given by F08YKF (DTGEVC). This is usually the sixth and last step in the solution of the generalized eigenvalue problem.
For a description of balancing, see the document for F08WHF (DGGBAL).

4 References

Ward R C (1981) Balancing the generalized eigenvalue problem SIAM J. Sci. Stat. Comp. 2 141–152

5 Arguments

1:   JOB – CHARACTER(1)Input
On entry: specifies the backward transformation step required.
JOB='N'
No transformations are done.
JOB='P'
Only do backward transformations based on permutations.
JOB='S'
Only do backward transformations based on scaling.
JOB='B'
Do backward transformations for both permutations and scaling.
Note: this must be the same argument JOB as supplied to F08WHF (DGGBAL).
Constraint: JOB='N', 'P', 'S' or 'B'.
2:   SIDE – CHARACTER(1)Input
On entry: indicates whether left or right eigenvectors are to be transformed.
SIDE='L'
The left eigenvectors are transformed.
SIDE='R'
The right eigenvectors are transformed.
Constraint: SIDE='L' or 'R'.
3:   N – INTEGERInput
On entry: n, the order of the matrices A and B of the generalized eigenvalue problem.
Constraint: N≥0.
4:   ILO – INTEGERInput
5:   IHI – INTEGERInput
On entry: ilo and ihi as determined by a previous call to F08WHF (DGGBAL).
Constraints:
  • if N>0, 1≤ ILO≤ IHI≤ N ;
  • if N=0, ILO=1 and IHI=0.
6:   LSCALE* – REAL (KIND=nag_wp) arrayInput
Note: the dimension of the array LSCALE must be at least max 1,N.
On entry: details of the permutations and scaling factors applied to the left side of the matrices A and B, as returned by a previous call to F08WHF (DGGBAL).
7:   RSCALE* – REAL (KIND=nag_wp) arrayInput
Note: the dimension of the array RSCALE must be at least max 1,N.
On entry: details of the permutations and scaling factors applied to the right side of the matrices A and B, as returned by a previous call to F08WHF (DGGBAL).
8:   M – INTEGERInput
On entry: m, the required number of left or right eigenvectors.
Constraint: 0≤M≤N.
9:   V LDV* – REAL (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array V must be at least max 1,M.
On entry: the matrix of right or left eigenvectors, as returned by F08WHF (DGGBAL).
On exit: the transformed right or left eigenvectors.
10:   LDV – INTEGERInput
On entry: the first dimension of the array V as declared in the (sub)program from which F08WJF (DGGBAK) is called.
Constraint: LDV≥ max 1,N .
11:   INFO – INTEGEROutput
On exit: INFO=0 unless the routine detects an error (see Section 6).

6 Error Indicators and Warnings

INFO<0
If INFO=-i, argument i had an illegal value. An explanatory message is output, and execution of the program is terminated.

7 Accuracy

The errors are negligible, compared with the previous computations.

8 Parallelism and Performance

F08WJF (DGGBAK) makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The number of operations is proportional to n 2.
The complex analogue of this routine is F08WWF (ZGGBAK).

10 Example

See Section 10 in F08XEF (DHGEQZ) and F08YKF (DTGEVC).
F08 Chapter Contents
F08 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F08WNF (ZGGEV) : NAG Library, Mark 26

F08 Chapter Contents
F08 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F08WNF (ZGGEV)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F08WNF (ZGGEV) computes for a pair of n by n complex nonsymmetric matrices A,B the generalized eigenvalues and, optionally, the left and/or right generalized eigenvectors using the QZ algorithm. F08WNF (ZGGEV) is marked as deprecated by LAPACK; the replacement routine is F08WQF (ZGGEV3) which makes better use of level 3 BLAS.

2 Specification

SUBROUTINE F08WNF ( JOBVL, JOBVR, N, A, LDA, B, LDB, ALPHA, BETA, VL, LDVL, VR, LDVR, WORK, LWORK, RWORK, INFO)
INTEGER | N, LDA, LDB, LDVL, LDVR, LWORK, INFO
REAL (KIND=nag_wp) | RWORK(max(1,8*N))
COMPLEX (KIND=nag_wp) | A(LDA,*), B(LDB,*), ALPHA(N), BETA(N), VL(LDVL,*), VR(LDVR,*), WORK(max(1,LWORK))
CHARACTER(1) | JOBVL, JOBVR
The routine may be called by its LAPACK name zggev.

3 Description

A generalized eigenvalue for a pair of matrices A,B is a scalar λ or a ratio α/β=λ, such that A-λB is singular. It is usually represented as the pair α,β, as there is a reasonable interpretation for β=0, and even for both being zero.
The right generalized eigenvector vj corresponding to the generalized eigenvalue λj of A,B satisfies
A vj = λj B vj .
The left generalized eigenvector uj corresponding to the generalized eigenvalue λj of A,B satisfies
ujH A = λj ujH B ,
where ujH is the conjugate-transpose of uj.
All the eigenvalues and, if required, all the eigenvectors of the complex generalized eigenproblem Ax=λBx, where A and B are complex, square matrices, are determined using the QZ algorithm. The complex QZ algorithm consists of three stages:
1. | A is reduced to upper Hessenberg form (with real, non-negative subdiagonal elements) and at the same time B is reduced to upper triangular form.
2. A is further reduced to triangular form while the triangular form of B is maintained and the diagonal elements of B are made real and non-negative. This is the generalized Schur form of the pair A,B .
This routine does not actually produce the eigenvalues λj, but instead returns αj and βj such that
λj=αj/βj,  j=1,2,…,n.
The division by βj becomes your responsibility, since βj may be zero, indicating an infinite eigenvalue.
3. | If the eigenvectors are required they are obtained from the triangular matrices and then transformed back into the original coordinate system.

4 References

Anderson E, Bai Z, Bischof C, Blackford S, Demmel J, Dongarra J J, Du Croz J J, Greenbaum A, Hammarling S, McKenney A and Sorensen D (1999) LAPACK Users' Guide (3rd Edition) SIAM, Philadelphia http://www.netlib.org/lapack/lug
Golub G H and Van Loan C F (2012) Matrix Computations (4th Edition) Johns Hopkins University Press, Baltimore
Wilkinson J H (1979) Kronecker's canonical form and the QZ algorithm Linear Algebra Appl. 28 285–303

5 Arguments

1:   JOBVL – CHARACTER(1)Input
On entry: if JOBVL='N', do not compute the left generalized eigenvectors.
If JOBVL='V', compute the left generalized eigenvectors.
Constraint: JOBVL='N' or 'V'.
2:   JOBVR – CHARACTER(1)Input
On entry: if JOBVR='N', do not compute the right generalized eigenvectors.
If JOBVR='V', compute the right generalized eigenvectors.
Constraint: JOBVR='N' or 'V'.
3:   N – INTEGERInput
On entry: n, the order of the matrices A and B.
Constraint: N≥0.
4:   A LDA* – COMPLEX (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array A must be at least max 1,N.
On entry: the matrix A in the pair A,B.
On exit: A has been overwritten.
5:   LDA – INTEGERInput
On entry: the first dimension of the array A as declared in the (sub)program from which F08WNF (ZGGEV) is called.
Constraint: LDA≥max 1,N.
6:   B LDB* – COMPLEX (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array B must be at least max 1,N.
On entry: the matrix B in the pair A,B.
On exit: B has been overwritten.
7:   LDB – INTEGERInput
On entry: the first dimension of the array B as declared in the (sub)program from which F08WNF (ZGGEV) is called.
Constraint: LDB≥max 1,N.
8:   ALPHA N – COMPLEX (KIND=nag_wp) arrayOutput
On exit: see the description of BETA.
9:   BETA N – COMPLEX (KIND=nag_wp) arrayOutput
On exit: ALPHA j/BETA j, for j=1,2,…,N, will be the generalized eigenvalues.
Note: the quotients ALPHA j/BETA j may easily overflow or underflow, and BETA j may even be zero. Thus, you should avoid naively computing the ratio αj/βj. However, max αj will always be less than and usually comparable with A 2 in magnitude, and max βj will always be less than and usually comparable with B 2.
10:   VL LDVL* – COMPLEX (KIND=nag_wp) arrayOutput
Note: the second dimension of the array VL must be at least max 1,N if JOBVL='V', and at least 1 otherwise.
On exit: if JOBVL='V', the left generalized eigenvectors uj are stored one after another in the columns of VL, in the same order as the corresponding eigenvalues. Each eigenvector will be scaled so the largest component will have real part+imag. part=1.
If JOBVL='N', VL is not referenced.
11:   LDVL – INTEGERInput
On entry: the first dimension of the array VL as declared in the (sub)program from which F08WNF (ZGGEV) is called.
Constraints:
  • if JOBVL='V', LDVL≥ max 1,N ;
  • otherwise LDVL≥1.
12:   VR LDVR* – COMPLEX (KIND=nag_wp) arrayOutput
Note: the second dimension of the array VR must be at least max 1,N if JOBVR='V', and at least 1 otherwise.
On exit: if JOBVR='V', the right generalized eigenvectors vj are stored one after another in the columns of VR, in the same order as the corresponding eigenvalues. Each eigenvector will be scaled so the largest component will have real part+imag. part=1.
If JOBVR='N', VR is not referenced.
13:   LDVR – INTEGERInput
On entry: the first dimension of the array VR as declared in the (sub)program from which F08WNF (ZGGEV) is called.
Constraints:
  • if JOBVR='V', LDVR≥ max 1,N ;
  • otherwise LDVR≥1.
14:   WORK max 1,LWORK – COMPLEX (KIND=nag_wp) arrayWorkspace
On exit: if INFO=0, the real part of WORK 1 contains the minimum value of LWORK required for optimal performance.
15:   LWORK – INTEGERInput
On entry: the dimension of the array WORK as declared in the (sub)program from which F08WNF (ZGGEV) is called.
If LWORK=-1, a workspace query is assumed; the routine only calculates the optimal size of the WORK array, returns this value as the first entry of the WORK array, and no error message related to LWORK is issued.
Suggested value: for optimal performance, LWORK must generally be larger than the minimum; increase workspace by, say, nb×N, where nb is the optimal block size.
Constraint: LWORK≥max 1,2×N.
16:   RWORK max 1,8×N – REAL (KIND=nag_wp) arrayWorkspace
17:   INFO – INTEGEROutput
On exit: INFO=0 unless the routine detects an error (see Section 6).

6 Error Indicators and Warnings

INFO<0
If INFO=-i, argument i had an illegal value. An explanatory message is output, and execution of the program is terminated.
INFO=1 to N
The QZ iteration failed. No eigenvectors have been calculated, but ALPHA j and BETA j should be correct for j=INFO+1,…,N.
INFO=N+1
Unexpected error returned from F08XSF (ZHGEQZ).
INFO=N+2
Error returned from F08YXF (ZTGEVC).

7 Accuracy

The computed eigenvalues and eigenvectors are exact for nearby matrices A+E and B+F, where
E,F F = O ε A,B F ,
and ε is the machine precision. See Section 4.11 of Anderson et al. (1999) for further details.
Note: interpretation of results obtained with the QZ algorithm often requires a clear understanding of the effects of small changes in the original data. These effects are reviewed in Wilkinson (1979), in relation to the significance of small values of αj and βj. It should be noted that if αj and βj are both small for any j, it may be that no reliance can be placed on any of the computed eigenvalues λi=αi/βi. You are recommended to study Wilkinson (1979) and, if in difficulty, to seek expert advice on determining the sensitivity of the eigenvalues to perturbations in the data.

8 Parallelism and Performance

F08WNF (ZGGEV) is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
F08WNF (ZGGEV) makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The total number of floating-point operations is proportional to n 3.
The real analogue of this routine is F08WAF (DGGEV).

10 Example

This example finds all the eigenvalues and right eigenvectors of the matrix pair A,B, where
A = -21.10-22.50 i 53.50-50.50 i -34.50+127.50 i 7.50+0 0.50 i -0.46-0 7.78 i -3.50-37.50 i -15.50+0 58.50 i -10.50-0 1.50 i 4.30-0 5.50 i 39.70-17.10 i -68.50+0 12.50 i -7.50-0 3.50 i 5.50+0 4.40 i 14.40+43.30 i -32.50-0 46.00 i -19.00-32.50 i
and
B = 1.00-5.00 i 1.60+1.20 i -3.00+0.00 i 0.00-1.00 i 0.80-0.60 i 3.00-5.00 i -4.00+3.00 i -2.40-3.20 i 1.00+0.00 i 2.40+1.80 i -4.00-5.00 i 0.00-3.00 i 0.00+1.00 i -1.80+2.40 i 0.00-4.00 i 4.00-5.00 i .
Note that the block size (NB) of 64 assumed in this example is not realistic for such a small problem, but should be suitable for large problems.

10.1 Program Text

Program Text (f08wnfe.f90)

10.2 Program Data

Program Data (f08wnfe.d)

10.3 Program Results

Program Results (f08wnfe.r)

F08 Chapter Contents
F08 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F08WPF (ZGGEVX) : NAG Library, Mark 26

F08 Chapter Contents
F08 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F08WPF (ZGGEVX)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F08WPF (ZGGEVX) computes for a pair of n by n complex nonsymmetric matrices A,B the generalized eigenvalues and, optionally, the left and/or right generalized eigenvectors using the QZ algorithm.
Optionally it also computes a balancing transformation to improve the conditioning of the eigenvalues and eigenvectors, reciprocal condition numbers for the eigenvalues, and reciprocal condition numbers for the right eigenvectors.

2 Specification

SUBROUTINE F08WPF ( BALANC, JOBVL, JOBVR, SENSE, N, A, LDA, B, LDB, ALPHA, BETA, VL, LDVL, VR, LDVR, ILO, IHI, LSCALE, RSCALE, ABNRM, BBNRM, RCONDE, RCONDV, WORK, LWORK, RWORK, IWORK, BWORK, INFO)
INTEGER | N, LDA, LDB, LDVL, LDVR, ILO, IHI, LWORK, IWORK(*), INFO
REAL (KIND=nag_wp) | LSCALE(N), RSCALE(N), ABNRM, BBNRM, RCONDE(*), RCONDV(*), RWORK(6*N)
COMPLEX (KIND=nag_wp) | A(LDA,*), B(LDB,*), ALPHA(N), BETA(N), VL(LDVL,*), VR(LDVR,*), WORK(max(1,LWORK))
LOGICAL | BWORK(*)
CHARACTER(1) | BALANC, JOBVL, JOBVR, SENSE
The routine may be called by its LAPACK name zggevx.

3 Description

A generalized eigenvalue for a pair of matrices A,B is a scalar λ or a ratio α/β=λ, such that A-λB is singular. It is usually represented as the pair α,β, as there is a reasonable interpretation for β=0, and even for both being zero.
The right generalized eigenvector vj corresponding to the generalized eigenvalue λj of A,B satisfies
A vj = λj B vj .
The left generalized eigenvector uj corresponding to the generalized eigenvalue λj of A,B satisfies
ujH A = λj ujH B ,
where ujH is the conjugate-transpose of uj.
All the eigenvalues and, if required, all the eigenvectors of the complex generalized eigenproblem Ax=λBx, where A and B are complex, square matrices, are determined using the QZ algorithm. The complex QZ algorithm consists of three stages:
1. | A is reduced to upper Hessenberg form (with real, non-negative subdiagonal elements) and at the same time B is reduced to upper triangular form.
2. A is further reduced to triangular form while the triangular form of B is maintained and the diagonal elements of B are made real and non-negative. This is the generalized Schur form of the pair A,B .
This routine does not actually produce the eigenvalues λj, but instead returns αj and βj such that
λj=αj/βj,  j=1,2,…,n.
The division by βj becomes your responsibility, since βj may be zero, indicating an infinite eigenvalue.
3. | If the eigenvectors are required they are obtained from the triangular matrices and then transformed back into the original coordinate system.
For details of the balancing option, see Section 3 in F08WVF (ZGGBAL).

4 References

Anderson E, Bai Z, Bischof C, Blackford S, Demmel J, Dongarra J J, Du Croz J J, Greenbaum A, Hammarling S, McKenney A and Sorensen D (1999) LAPACK Users' Guide (3rd Edition) SIAM, Philadelphia http://www.netlib.org/lapack/lug
Golub G H and Van Loan C F (2012) Matrix Computations (4th Edition) Johns Hopkins University Press, Baltimore
Wilkinson J H (1979) Kronecker's canonical form and the QZ algorithm Linear Algebra Appl. 28 285–303

5 Arguments

1:   BALANC – CHARACTER(1)Input
On entry: specifies the balance option to be performed.
BALANC='N'
Do not diagonally scale or permute.
BALANC='P'
Permute only.
BALANC='S'
Scale only.
BALANC='B'
Both permute and scale.
Computed reciprocal condition numbers will be for the matrices after permuting and/or balancing. Permuting does not change condition numbers (in exact arithmetic), but balancing does. In the absence of other information, BALANC='B' is recommended.
Constraint: BALANC='N', 'P', 'S' or 'B'.
2:   JOBVL – CHARACTER(1)Input
On entry: if JOBVL='N', do not compute the left generalized eigenvectors.
If JOBVL='V', compute the left generalized eigenvectors.
Constraint: JOBVL='N' or 'V'.
3:   JOBVR – CHARACTER(1)Input
On entry: if JOBVR='N', do not compute the right generalized eigenvectors.
If JOBVR='V', compute the right generalized eigenvectors.
Constraint: JOBVR='N' or 'V'.
4:   SENSE – CHARACTER(1)Input
On entry: determines which reciprocal condition numbers are computed.
SENSE='N'
None are computed.
SENSE='E'
Computed for eigenvalues only.
SENSE='V'
Computed for eigenvectors only.
SENSE='B'
Computed for eigenvalues and eigenvectors.
Constraint: SENSE='N', 'E', 'V' or 'B'.
5:   N – INTEGERInput
On entry: n, the order of the matrices A and B.
Constraint: N≥0.
6:   A LDA* – COMPLEX (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array A must be at least max 1,N.
On entry: the matrix A in the pair A,B.
On exit: A has been overwritten. If JOBVL='V' or JOBVR='V' or both, then A contains the first part of the Schur form of the ‘balanced’ versions of the input A and B.
7:   LDA – INTEGERInput
On entry: the first dimension of the array A as declared in the (sub)program from which F08WPF (ZGGEVX) is called.
Constraint: LDA≥max 1,N.
8:   B LDB* – COMPLEX (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array B must be at least max 1,N.
On entry: the matrix B in the pair A,B.
On exit: B has been overwritten.
9:   LDB – INTEGERInput
On entry: the first dimension of the array B as declared in the (sub)program from which F08WPF (ZGGEVX) is called.
Constraint: LDB≥max 1,N.
10:   ALPHA N – COMPLEX (KIND=nag_wp) arrayOutput
On exit: see the description of BETA.
11:   BETA N – COMPLEX (KIND=nag_wp) arrayOutput
On exit: ALPHA j/BETA j, for j=1,2,…,N, will be the generalized eigenvalues.
Note: the quotients ALPHA j/BETA j may easily overflow or underflow, and BETA j may even be zero. Thus, you should avoid naively computing the ratio αj/βj. However, max αj will always be less than and usually comparable with A 2 in magnitude, and max βj will always be less than and usually comparable with B 2.
12:   VL LDVL* – COMPLEX (KIND=nag_wp) arrayOutput
Note: the second dimension of the array VL must be at least max 1,N if JOBVL='V', and at least 1 otherwise.
On exit: if JOBVL='V', the left generalized eigenvectors uj are stored one after another in the columns of VL, in the same order as the corresponding eigenvalues. Each eigenvector will be scaled so the largest component will have real part+imag. part=1.
If JOBVL='N', VL is not referenced.
13:   LDVL – INTEGERInput
On entry: the first dimension of the array VL as declared in the (sub)program from which F08WPF (ZGGEVX) is called.
Constraints:
  • if JOBVL='V', LDVL≥ max 1,N ;
  • otherwise LDVL≥1.
14:   VR LDVR* – COMPLEX (KIND=nag_wp) arrayOutput
Note: the second dimension of the array VR must be at least max 1,N if JOBVR='V', and at least 1 otherwise.
On exit: if JOBVR='V', the right generalized eigenvectors vj are stored one after another in the columns of VR, in the same order as the corresponding eigenvalues. Each eigenvector will be scaled so the largest component will have real part+imag. part=1.
If JOBVR='N', VR is not referenced.
15:   LDVR – INTEGERInput
On entry: the first dimension of the array VR as declared in the (sub)program from which F08WPF (ZGGEVX) is called.
Constraints:
  • if JOBVR='V', LDVR≥ max 1,N ;
  • otherwise LDVR≥1.
16:   ILO – INTEGEROutput
17:   IHI – INTEGEROutput
On exit: ILO and IHI are integer values such that A ij=0 and B ij=0 if i>j and j=1,2,…,ILO-1 or i=IHI+1,…,N.
If BALANC='N' or 'S', ILO=1 and IHI=N.
18:   LSCALE N – REAL (KIND=nag_wp) arrayOutput
On exit: details of the permutations and scaling factors applied to the left side of A and B.
If plj is the index of the row interchanged with row j, and dlj is the scaling factor applied to row j, then:
  • LSCALE j = plj , for j=1,2,…,ILO-1;
  • LSCALE = dlj , for j=ILO,…,IHI;
  • LSCALE = plj , for j=IHI+1,…,N.
The order in which the interchanges are made is N to IHI+1, then 1 to ILO-1.
19:   RSCALE N – REAL (KIND=nag_wp) arrayOutput
On exit: details of the permutations and scaling factors applied to the right side of A and B.
If prj is the index of the column interchanged with column j, and drj is the scaling factor applied to column j, then:
  • RSCALE j=prj, for j=1,2,…,ILO-1;
  • if RSCALE=drj, for j=ILO,…,IHI;
  • if RSCALE=prj, for j=IHI+1,…,N.
The order in which the interchanges are made is N to IHI+1, then 1 to ILO-1.
20:   ABNRM – REAL (KIND=nag_wp)Output
On exit: the 1-norm of the balanced matrix A.
21:   BBNRM – REAL (KIND=nag_wp)Output
On exit: the 1-norm of the balanced matrix B.
22:   RCONDE* – REAL (KIND=nag_wp) arrayOutput
Note: the dimension of the array RCONDE must be at least max 1,N.
On exit: if SENSE='E' or 'B', the reciprocal condition numbers of the eigenvalues, stored in consecutive elements of the array.
If SENSE='N' or 'V', RCONDE is not referenced.
23:   RCONDV* – REAL (KIND=nag_wp) arrayOutput
Note: the dimension of the array RCONDV must be at least max 1,N.
On exit: if SENSE='V' or 'B', the estimated reciprocal condition numbers of the selected eigenvectors, stored in consecutive elements of the array.
If SENSE='N' or 'E', RCONDV is not referenced.
24:   WORK max 1,LWORK – COMPLEX (KIND=nag_wp) arrayWorkspace
On exit: if INFO=0, the real part of WORK 1 contains the minimum value of LWORK required for optimal performance.
25:   LWORK – INTEGERInput
On entry: the dimension of the array WORK as declared in the (sub)program from which F08WPF (ZGGEVX) is called.
If LWORK=-1, a workspace query is assumed; the routine only calculates the optimal size of the WORK array, returns this value as the first entry of the WORK array, and no error message related to LWORK is issued.
Suggested value: for optimal performance, LWORK must generally be larger than the minimum; increase workspace by, say, nb×N, where nb is the optimal block size.
Constraints:
  • if SENSE='N', LWORK≥max 1,2×N;
  • if SENSE='E', LWORK≥max 1,4×N;
  • if SENSE='B' or 'V', LWORK≥max 1,2×N×N+2×N.
26:   RWORK 6×N – REAL (KIND=nag_wp) arrayWorkspace
Real workspace.
27:   IWORK* – INTEGER arrayWorkspace
Note: the dimension of the array IWORK must be at least max 1,N+2.
If SENSE='E', IWORK is not referenced.
28:   BWORK* – LOGICAL arrayWorkspace
Note: the dimension of the array BWORK must be at least max 1,N.
If SENSE='N', BWORK is not referenced.
29:   INFO – INTEGEROutput
On exit: INFO=0 unless the routine detects an error (see Section 6).

6 Error Indicators and Warnings

INFO<0
If INFO=-i, argument i had an illegal value. An explanatory message is output, and execution of the program is terminated.
INFO=1 to N
The QZ iteration failed. No eigenvectors have been calculated, but ALPHA j and BETA j should be correct for j=INFO+1,…,N.
INFO=N+1
Unexpected error returned from F08XSF (ZHGEQZ).
INFO=N+2
Error returned from F08YXF (ZTGEVC).

7 Accuracy

The computed eigenvalues and eigenvectors are exact for nearby matrices A+E and B+F, where
E,F F = O ε A,B F ,
and ε is the machine precision.
An approximate error bound on the chordal distance between the ith computed generalized eigenvalue w and the corresponding exact eigenvalue λ is
ε × ABNRM,BBNRM 2 / RCONDE i .
An approximate error bound for the angle between the ith computed eigenvector uj or vj is given by
ε × ABNRM,BBNRM 2 / RCONDV i .
For further explanation of the reciprocal condition numbers RCONDE and RCONDV, see Section 4.11 of Anderson et al. (1999).
Note: interpretation of results obtained with the QZ algorithm often requires a clear understanding of the effects of small changes in the original data. These effects are reviewed in Wilkinson (1979), in relation to the significance of small values of αj and βj. It should be noted that if αj and βj are both small for any j, it may be that no reliance can be placed on any of the computed eigenvalues λi=αi/βi. You are recommended to study Wilkinson (1979) and, if in difficulty, to seek expert advice on determining the sensitivity of the eigenvalues to perturbations in the data.

8 Parallelism and Performance

F08WPF (ZGGEVX) is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
F08WPF (ZGGEVX) makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The total number of floating-point operations is proportional to n 3.
The real analogue of this routine is F08WBF (DGGEVX).

10 Example

This example finds all the eigenvalues and right eigenvectors of the matrix pair A,B, where
A = -21.10-22.50 i 53.50-50.50 i -34.50+127.50 i 7.50+0 0.50 i -0.46-0 7.78 i -3.50-37.50 i -15.50+0 58.50 i -10.50-0 1.50 i 4.30-0 5.50 i 39.70-17.10 i -68.50+0 12.50 i -7.50-0 3.50 i 5.50+0 4.40 i 14.40+43.30 i -32.50-0 46.00 i -19.00-32.50 i
and
B = 1.00-5.00 i 1.60+1.20 i -3.00+0.00 i 0.00-1.00 i 0.80-0.60 i 3.00-5.00 i -4.00+3.00 i -2.40-3.20 i 1.00+0.00 i 2.40+1.80 i -4.00-5.00 i 0.00-3.00 i 0.00+1.00 i -1.80+2.40 i 0.00-4.00 i 4.00-5.00 i ,
together with estimates of the condition number and forward error bounds for each eigenvalue and eigenvector. The option to balance the matrix pair is used.
Note that the block size (NB) of 64 assumed in this example is not realistic for such a small problem, but should be suitable for large problems.

10.1 Program Text

Program Text (f08wpfe.f90)

10.2 Program Data

Program Data (f08wpfe.d)

10.3 Program Results

Program Results (f08wpfe.r)

F08 Chapter Contents
F08 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F08WQF (ZGGEV3) : NAG Library, Mark 26

F08 Chapter Contents
F08 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F08WQF (ZGGEV3)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F08WQF (ZGGEV3) computes for a pair of n by n complex nonsymmetric matrices A,B the generalized eigenvalues and, optionally, the left and/or right generalized eigenvectors using the QZ algorithm.

2 Specification

SUBROUTINE F08WQF ( JOBVL, JOBVR, N, A, LDA, B, LDB, ALPHA, BETA, VL, LDVL, VR, LDVR, WORK, LWORK, RWORK, INFO)
INTEGER | N, LDA, LDB, LDVL, LDVR, LWORK, INFO
REAL (KIND=nag_wp) | RWORK(max(1,8*N))
COMPLEX (KIND=nag_wp) | A(LDA,*), B(LDB,*), ALPHA(N), BETA(N), VL(LDVL,*), VR(LDVR,*), WORK(max(1,LWORK))
CHARACTER(1) | JOBVL, JOBVR
The routine may be called by its LAPACK name zggev3.

3 Description

A generalized eigenvalue for a pair of matrices A,B is a scalar λ or a ratio α/β=λ, such that A-λB is singular. It is usually represented as the pair α,β, as there is a reasonable interpretation for β=0, and even for both being zero.
The right generalized eigenvector vj corresponding to the generalized eigenvalue λj of A,B satisfies
A vj = λj B vj .
The left generalized eigenvector uj corresponding to the generalized eigenvalue λj of A,B satisfies
ujH A = λj ujH B ,
where ujH is the conjugate-transpose of uj.
All the eigenvalues and, if required, all the eigenvectors of the complex generalized eigenproblem Ax=λBx, where A and B are complex, square matrices, are determined using the QZ algorithm. The complex QZ algorithm consists of three stages:
1. | A is reduced to upper Hessenberg form (with real, non-negative subdiagonal elements) and at the same time B is reduced to upper triangular form.
2. A is further reduced to triangular form while the triangular form of B is maintained and the diagonal elements of B are made real and non-negative. This is the generalized Schur form of the pair A,B .
This routine does not actually produce the eigenvalues λj, but instead returns αj and βj such that
λj=αj/βj,  j=1,2,…,n.
The division by βj becomes your responsibility, since βj may be zero, indicating an infinite eigenvalue.
3. | If the eigenvectors are required they are obtained from the triangular matrices and then transformed back into the original coordinate system.

4 References

Anderson E, Bai Z, Bischof C, Blackford S, Demmel J, Dongarra J J, Du Croz J J, Greenbaum A, Hammarling S, McKenney A and Sorensen D (1999) LAPACK Users' Guide (3rd Edition) SIAM, Philadelphia http://www.netlib.org/lapack/lug
Golub G H and Van Loan C F (2012) Matrix Computations (4th Edition) Johns Hopkins University Press, Baltimore
Wilkinson J H (1979) Kronecker's canonical form and the QZ algorithm Linear Algebra Appl. 28 285–303

5 Arguments

1:   JOBVL – CHARACTER(1)Input
On entry: if JOBVL='N', do not compute the left generalized eigenvectors.
If JOBVL='V', compute the left generalized eigenvectors.
Constraint: JOBVL='N' or 'V'.
2:   JOBVR – CHARACTER(1)Input
On entry: if JOBVR='N', do not compute the right generalized eigenvectors.
If JOBVR='V', compute the right generalized eigenvectors.
Constraint: JOBVR='N' or 'V'.
3:   N – INTEGERInput
On entry: n, the order of the matrices A and B.
Constraint: N≥0.
4:   A LDA* – COMPLEX (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array A must be at least max 1,N.
On entry: the matrix A in the pair A,B.
On exit: A has been overwritten.
5:   LDA – INTEGERInput
On entry: the first dimension of the array A as declared in the (sub)program from which F08WQF (ZGGEV3) is called.
Constraint: LDA≥max 1,N.
6:   B LDB* – COMPLEX (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array B must be at least max 1,N.
On entry: the matrix B in the pair A,B.
On exit: B has been overwritten.
7:   LDB – INTEGERInput
On entry: the first dimension of the array B as declared in the (sub)program from which F08WQF (ZGGEV3) is called.
Constraint: LDB≥max 1,N.
8:   ALPHA N – COMPLEX (KIND=nag_wp) arrayOutput
On exit: see the description of BETA.
9:   BETA N – COMPLEX (KIND=nag_wp) arrayOutput
On exit: ALPHA j/BETA j, for j=1,2,…,N, will be the generalized eigenvalues.
Note: the quotients ALPHA j/BETA j may easily overflow or underflow, and BETA j may even be zero. Thus, you should avoid naively computing the ratio αj/βj. However, max αj will always be less than and usually comparable with A 2 in magnitude, and max βj will always be less than and usually comparable with B 2.
10:   VL LDVL* – COMPLEX (KIND=nag_wp) arrayOutput
Note: the second dimension of the array VL must be at least max 1,N if JOBVL='V', and at least 1 otherwise.
On exit: if JOBVL='V', the left generalized eigenvectors uj are stored one after another in the columns of VL, in the same order as the corresponding eigenvalues. Each eigenvector will be scaled so the largest component will have real part+imag. part=1.
If JOBVL='N', VL is not referenced.
11:   LDVL – INTEGERInput
On entry: the first dimension of the array VL as declared in the (sub)program from which F08WQF (ZGGEV3) is called.
Constraints:
  • if JOBVL='V', LDVL≥ max 1,N ;
  • otherwise LDVL≥1.
12:   VR LDVR* – COMPLEX (KIND=nag_wp) arrayOutput
Note: the second dimension of the array VR must be at least max 1,N if JOBVR='V', and at least 1 otherwise.
On exit: if JOBVR='V', the right generalized eigenvectors vj are stored one after another in the columns of VR, in the same order as the corresponding eigenvalues. Each eigenvector will be scaled so the largest component will have real part+imag. part=1.
If JOBVR='N', VR is not referenced.
13:   LDVR – INTEGERInput
On entry: the first dimension of the array VR as declared in the (sub)program from which F08WQF (ZGGEV3) is called.
Constraints:
  • if JOBVR='V', LDVR≥ max 1,N ;
  • otherwise LDVR≥1.
14:   WORK max 1,LWORK – COMPLEX (KIND=nag_wp) arrayWorkspace
On exit: if INFO=0, the real part of WORK 1 contains the minimum value of LWORK required for optimal performance.
15:   LWORK – INTEGERInput
On entry: the dimension of the array WORK as declared in the (sub)program from which F08WQF (ZGGEV3) is called.
If LWORK=-1, a workspace query is assumed; the routine only calculates the optimal size of the WORK array, returns this value as the first entry of the WORK array, and no error message related to LWORK is issued.
Suggested value: for optimal performance, LWORK must generally be larger than the minimum; increase workspace by, say, nb×N×6, where nb is the optimal block size.
Constraint: LWORK≥max 1,2×N.
16:   RWORK max 1,8×N – REAL (KIND=nag_wp) arrayWorkspace
17:   INFO – INTEGEROutput
On exit: INFO=0 unless the routine detects an error (see Section 6).

6 Error Indicators and Warnings

INFO<0
If INFO=-i, argument i had an illegal value. An explanatory message is output, and execution of the program is terminated.
INFO=1 to N
The QZ iteration failed. No eigenvectors have been calculated but ALPHA and BETA should be correct from element value.
INFO=N+1
The QZ iteration failed with an unexpected error, please contact NAG.
INFO=N+2
A failure occurred in F08YXF (ZTGEVC) while computing generalized eigenvectors.

7 Accuracy

The computed eigenvalues and eigenvectors are exact for nearby matrices A+E and B+F, where
E,F F = O ε A,B F ,
and ε is the machine precision. See Section 4.11 of Anderson et al. (1999) for further details.
Note: interpretation of results obtained with the QZ algorithm often requires a clear understanding of the effects of small changes in the original data. These effects are reviewed in Wilkinson (1979), in relation to the significance of small values of αj and βj. It should be noted that if αj and βj are both small for any j, it may be that no reliance can be placed on any of the computed eigenvalues λi=αi/βi. You are recommended to study Wilkinson (1979) and, if in difficulty, to seek expert advice on determining the sensitivity of the eigenvalues to perturbations in the data.

8 Parallelism and Performance

F08WQF (ZGGEV3) is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
F08WQF (ZGGEV3) makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The total number of floating-point operations is proportional to n 3.
The real analogue of this routine is F08WCF (DGGEV3).

10 Example

This example finds all the eigenvalues and right eigenvectors of the matrix pair A,B, where
A = -21.10-22.50 i 53.50-50.50 i -34.50+127.50 i 7.50+0 0.50 i -0.46-0 7.78 i -3.50-37.50 i -15.50+0 58.50 i -10.50-0 1.50 i 4.30-0 5.50 i 39.70-17.10 i -68.50+0 12.50 i -7.50-0 3.50 i 5.50+0 4.40 i 14.40+43.30 i -32.50-0 46.00 i -19.00-32.50 i
and
B = 1.00-5.00 i 1.60+1.20 i -3.00+0.00 i 0.00-1.00 i 0.80-0.60 i 3.00-5.00 i -4.00+3.00 i -2.40-3.20 i 1.00+0.00 i 2.40+1.80 i -4.00-5.00 i 0.00-3.00 i 0.00+1.00 i -1.80+2.40 i 0.00-4.00 i 4.00-5.00 i .

10.1 Program Text

Program Text (f08wqfe.f90)

10.2 Program Data

Program Data (f08wqfe.d)

10.3 Program Results

Program Results (f08wqfe.r)

F08 Chapter Contents
F08 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F08WSF (ZGGHRD) : NAG Library, Mark 26

F08 Chapter Contents
F08 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F08WSF (ZGGHRD)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
10 Example

1 Purpose

F08WSF (ZGGHRD) reduces a pair of complex matrices A,B, where B is upper triangular, to the generalized upper Hessenberg form using unitary transformations.

2 Specification

SUBROUTINE F08WSF ( COMPQ, COMPZ, N, ILO, IHI, A, LDA, B, LDB, Q, LDQ, Z, LDZ, INFO)
INTEGER | N, ILO, IHI, LDA, LDB, LDQ, LDZ, INFO
COMPLEX (KIND=nag_wp) | A(LDA,*), B(LDB,*), Q(LDQ,*), Z(LDZ,*)
CHARACTER(1) | COMPQ, COMPZ
The routine may be called by its LAPACK name zgghrd.

3 Description

F08WSF (ZGGHRD) is usually the third step in the solution of the complex generalized eigenvalue problem
Ax=λBx.
The (optional) first step balances the two matrices using F08WVF (ZGGBAL). In the second step, matrix B is reduced to upper triangular form using the QR factorization routine F08ASF (ZGEQRF) and this unitary transformation Q is applied to matrix A by calling F08AUF (ZUNMQR).
F08WSF (ZGGHRD) reduces a pair of complex matrices A,B, where B is triangular, to the generalized upper Hessenberg form using unitary transformations. This two-sided transformation is of the form
QH AZ=H QH BZ=T
where H is an upper Hessenberg matrix, T is an upper triangular matrix and Q and Z are unitary matrices determined as products of Givens rotations. They may either be formed explicitly, or they may be postmultiplied into input matrices Q 1 and Z 1, so that
Q 1 A Z 1 H=Q 1 Q H Z 1 Z H, Q 1 B Z 1 H=Q 1 Q T Z 1 Z H.

4 References

Golub G H and Van Loan C F (1996) Matrix Computations (3rd Edition) Johns Hopkins University Press, Baltimore
Moler C B and Stewart G W (1973) An algorithm for generalized matrix eigenproblems SIAM J. Numer. Anal. 10 241–256

5 Arguments

1:   COMPQ – CHARACTER(1)Input
On entry: specifies the form of the computed unitary matrix Q.
COMPQ='N'
Do not compute Q.
COMPQ='I'
The unitary matrix Q is returned.
COMPQ='V'
Q must contain a unitary matrix Q 1, and the product Q 1 Q is returned.
Constraint: COMPQ='N', 'I' or 'V'.
2:   COMPZ – CHARACTER(1)Input
On entry: specifies the form of the computed unitary matrix Z.
COMPZ='N'
Do not compute Z.
COMPZ='V'
Z must contain a unitary matrix Z 1, and the product Z 1 Z is returned.
COMPZ='I'
The unitary matrix Z is returned.
Constraint: COMPZ='N', 'V' or 'I'.
3:   N – INTEGERInput
On entry: n, the order of the matrices A and B.
Constraint: N≥0.
4:   ILO – INTEGERInput
5:   IHI – INTEGERInput
On entry: ilo and ihi as determined by a previous call to F08WVF (ZGGBAL). Otherwise, they should be set to 1 and n, respectively.
Constraints:
  • if N>0, 1≤ ILO≤ IHI≤ N ;
  • if N=0, ILO=1 and IHI=0.
6:   A LDA* – COMPLEX (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array A must be at least max 1,N.
On entry: the matrix A of the matrix pair A,B. Usually, this is the matrix A returned by F08AUF (ZUNMQR).
On exit: A is overwritten by the upper Hessenberg matrix H.
7:   LDA – INTEGERInput
On entry: the first dimension of the array A as declared in the (sub)program from which F08WSF (ZGGHRD) is called.
Constraint: LDA≥max 1,N.
8:   B LDB* – COMPLEX (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array B must be at least max 1,N.
On entry: the upper triangular matrix B of the matrix pair A,B. Usually, this is the matrix B returned by the QR factorization routine F08ASF (ZGEQRF).
On exit: B is overwritten by the upper triangular matrix T.
9:   LDB – INTEGERInput
On entry: the first dimension of the array B as declared in the (sub)program from which F08WSF (ZGGHRD) is called.
Constraint: LDB≥max 1,N.
10:   Q LDQ* – COMPLEX (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array Q must be at least max 1,N if COMPQ='I' or 'V' and at least 1 if COMPQ='N'.
On entry: if COMPQ='V', Q must contain a unitary matrix Q 1.
If COMPQ='N', Q is not referenced.
On exit: if COMPQ='I', Q contains the unitary matrix Q.
Iif COMPQ='V', Q is overwritten by Q 1 Q.
11:   LDQ – INTEGERInput
On entry: the first dimension of the array Q as declared in the (sub)program from which F08WSF (ZGGHRD) is called.
Constraints:
  • if COMPQ='I' or 'V', LDQ≥ max 1,N ;
  • if COMPQ='N', LDQ≥1.
12:   Z LDZ* – COMPLEX (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array Z must be at least max 1,N if COMPZ='V' or 'I' and at least 1 if COMPZ='N'.
On entry: if COMPZ='V', Z must contain a unitary matrix Z 1.
If COMPZ='N', Z is not referenced.
On exit: if COMPZ='I', Z contains the unitary matrix Z.
If COMPZ='V', Z is overwritten by Z 1 Z.
13:   LDZ – INTEGERInput
On entry: the first dimension of the array Z as declared in the (sub)program from which F08WSF (ZGGHRD) is called.
Constraints:
  • if COMPZ='V' or 'I', LDZ≥ max 1,N ;
  • if COMPZ='N', LDZ≥1.
14:   INFO – INTEGEROutput
On exit: INFO=0 unless the routine detects an error (see Section 6).

6 Error Indicators and Warnings

INFO<0
If INFO=-i, argument i had an illegal value. An explanatory message is output, and execution of the program is terminated.

7 Accuracy

The reduction to the generalized Hessenberg form is implemented using unitary transformations which are backward stable.

8 Parallelism and Performance

F08WSF (ZGGHRD) is not threaded in any implementation.

9 Further Comments

This routine is usually followed by F08XSF (ZHGEQZ) which implements the QZ algorithm for computing generalized eigenvalues of a reduced pair of matrices.
The real analogue of this routine is F08WEF (DGGHRD).

10 Example

See Section 10 in F08XSF (ZHGEQZ) and F08YXF (ZTGEVC).
F08 Chapter Contents
F08 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F08WTF (ZGGHD3) : NAG Library, Mark 26

F08 Chapter Contents
F08 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F08WTF (ZGGHD3)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
10 Example

1 Purpose

F08WTF (ZGGHD3) reduces a pair of complex matrices A,B, where B is upper triangular, to the generalized upper Hessenberg form using unitary transformations.

2 Specification

SUBROUTINE F08WTF ( COMPQ, COMPZ, N, ILO, IHI, A, LDA, B, LDB, Q, LDQ, Z, LDZ, WORK, LWORK, INFO)
INTEGER | N, ILO, IHI, LDA, LDB, LDQ, LDZ, LWORK, INFO
COMPLEX (KIND=nag_wp) | A(LDA,*), B(LDB,*), Q(LDQ,*), Z(LDZ,*), WORK(max(1,LWORK))
CHARACTER(1) | COMPQ, COMPZ
The routine may be called by its LAPACK name zgghd3.

3 Description

F08WTF (ZGGHD3) is usually the third step in the solution of the complex generalized eigenvalue problem
Ax=λBx.
The (optional) first step balances the two matrices using F08WVF (ZGGBAL). In the second step, matrix B is reduced to upper triangular form using the QR factorization routine F08ASF (ZGEQRF) and this unitary transformation Q is applied to matrix A by calling F08AUF (ZUNMQR). The driver, F08WQF (ZGGEV3), solves the complex generalized eigenvalue problem by combining all the required steps including those just listed.
F08WTF (ZGGHD3) reduces a pair of complex matrices A,B, where B is triangular, to the generalized upper Hessenberg form using unitary transformations. This two-sided transformation is of the form
QH AZ=H, QH BZ=T
where H is an upper Hessenberg matrix, T is an upper triangular matrix and Q and Z are unitary matrices determined as products of Givens rotations. They may either be formed explicitly, or they may be postmultiplied into input matrices Q 1 and Z 1, so that
Q 1 A Z 1 H=Q 1 Q H Z 1 Z H, Q 1 B Z 1 H=Q 1 Q T Z 1 Z H.

4 References

Golub G H and Van Loan C F (2012) Matrix Computations (4th Edition) Johns Hopkins University Press, Baltimore
Moler C B and Stewart G W (1973) An algorithm for generalized matrix eigenproblems SIAM J. Numer. Anal. 10 241–256

5 Arguments

1:   COMPQ – CHARACTER(1)Input
On entry: specifies the form of the computed unitary matrix Q.
COMPQ='N'
Do not compute Q.
COMPQ='I'
The unitary matrix Q is returned.
COMPQ='V'
Q must contain a unitary matrix Q 1, and the product Q 1 Q is returned.
Constraint: COMPQ='N', 'I' or 'V'.
2:   COMPZ – CHARACTER(1)Input
On entry: specifies the form of the computed unitary matrix Z.
COMPZ='N'
Do not compute Z.
COMPZ='V'
Z must contain a unitary matrix Z 1, and the product Z 1 Z is returned.
COMPZ='I'
The unitary matrix Z is returned.
Constraint: COMPZ='N', 'V' or 'I'.
3:   N – INTEGERInput
On entry: n, the order of the matrices A and B.
Constraint: N≥0.
4:   ILO – INTEGERInput
5:   IHI – INTEGERInput
On entry: ilo and ihi as determined by a previous call to F08WVF (ZGGBAL). Otherwise, they should be set to 1 and n, respectively.
Constraints:
  • if N>0, 1≤ ILO≤ IHI≤ N ;
  • if N=0, ILO=1 and IHI=0.
6:   A LDA* – COMPLEX (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array A must be at least max 1,N.
On entry: the matrix A of the matrix pair A,B. Usually, this is the matrix A returned by F08AUF (ZUNMQR).
On exit: A is overwritten by the upper Hessenberg matrix H.
7:   LDA – INTEGERInput
On entry: the first dimension of the array A as declared in the (sub)program from which F08WTF (ZGGHD3) is called.
Constraint: LDA≥max 1,N.
8:   B LDB* – COMPLEX (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array B must be at least max 1,N.
On entry: the upper triangular matrix B of the matrix pair A,B. Usually, this is the matrix B returned by the QR factorization routine F08ASF (ZGEQRF).
On exit: B is overwritten by the upper triangular matrix T.
9:   LDB – INTEGERInput
On entry: the first dimension of the array B as declared in the (sub)program from which F08WTF (ZGGHD3) is called.
Constraint: LDB≥max 1,N.
10:   Q LDQ* – COMPLEX (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array Q must be at least max 1,N if COMPQ='I' or 'V' and at least 1 if COMPQ='N'.
On entry: if COMPQ='V', Q must contain a unitary matrix Q 1.
If COMPQ='N', Q is not referenced.
On exit: if COMPQ='I', Q contains the unitary matrix Q.
Iif COMPQ='V', Q is overwritten by Q 1 Q.
11:   LDQ – INTEGERInput
On entry: the first dimension of the array Q as declared in the (sub)program from which F08WTF (ZGGHD3) is called.
Constraints:
  • if COMPQ='I' or 'V', LDQ≥ max 1,N ;
  • if COMPQ='N', LDQ≥1.
12:   Z LDZ* – COMPLEX (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array Z must be at least max 1,N if COMPZ='V' or 'I' and at least 1 if COMPZ='N'.
On entry: if COMPZ='V', Z must contain a unitary matrix Z 1.
If COMPZ='N', Z is not referenced.
On exit: if COMPZ='I', Z contains the unitary matrix Z.
If COMPZ='V', Z is overwritten by Z 1 Z.
13:   LDZ – INTEGERInput
On entry: the first dimension of the array Z as declared in the (sub)program from which F08WTF (ZGGHD3) is called.
Constraints:
  • if COMPZ='V' or 'I', LDZ≥ max 1,N ;
  • if COMPZ='N', LDZ≥1.
14:   WORK max 1,LWORK – COMPLEX (KIND=nag_wp) arrayWorkspace
On exit: if INFO=0, the real part of WORK 1 contains the minimum value of LWORK required for optimal performance.
15:   LWORK – INTEGERInput
On entry: the dimension of the array WORK as declared in the (sub)routine from which F08WTF (ZGGHD3) is called.
If LWORK=-1, a workspace query is assumed; the routine only calculates the optimal size of the WORK array, returns this value as the first entry of the WORK array, and no error message related to LWORK is issued.
Suggested value: for optimal performance, LWORK must generally be larger than the minimum; increase workspace by, say, nb×N×6, where nb is the optimal block size.
16:   INFO – INTEGEROutput
On exit: INFO=0 unless the routine detects an error (see Section 6).

6 Error Indicators and Warnings

INFO<0
If INFO=-i, argument i had an illegal value. An explanatory message is output, and execution of the program is terminated.

7 Accuracy

The reduction to the generalized Hessenberg form is implemented using unitary transformations which are backward stable.

8 Parallelism and Performance

F08WTF (ZGGHD3) makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

This routine is usually followed by F08XSF (ZHGEQZ) which implements the QZ algorithm for computing generalized eigenvalues of a reduced pair of matrices.
The real analogue of this routine is F08WFF (DGGHD3).

10 Example

See Section 10 in F08XSF (ZHGEQZ) and F08YXF (ZTGEVC).
F08 Chapter Contents
F08 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F08WVF (ZGGBAL) : NAG Library, Mark 26

F08 Chapter Contents
F08 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F08WVF (ZGGBAL)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
10 Example

1 Purpose

F08WVF (ZGGBAL) balances a pair of complex square matrices A,B of order n. Balancing usually improves the accuracy of computed generalized eigenvalues and eigenvectors.

2 Specification

SUBROUTINE F08WVF ( JOB, N, A, LDA, B, LDB, ILO, IHI, LSCALE, RSCALE, WORK, INFO)
INTEGER | N, LDA, LDB, ILO, IHI, INFO
REAL (KIND=nag_wp) | LSCALE(N), RSCALE(N), WORK(6*N)
COMPLEX (KIND=nag_wp) | A(LDA,*), B(LDB,*)
CHARACTER(1) | JOB
The routine may be called by its LAPACK name zggbal.

3 Description

Balancing may reduce the 1-norm of the matrices and improve the accuracy of the computed eigenvalues and eigenvectors in the complex generalized eigenvalue problem
Ax=λBx.
F08WVF (ZGGBAL) is usually the first step in the solution of the above generalized eigenvalue problem. Balancing is optional but it is highly recommended.
The term ‘balancing’ covers two steps, each of which involves similarity transformations on A and B. The routine can perform either or both of these steps. Both steps are optional.
1. The routine first attempts to permute A and B to block upper triangular form by a similarity transformation:
PA PT=F= F 11 F 12 F 13 F 22 F 23 F 33
PB PT=G= G 11 G 12 G 13 G 22 G 23 G 33
where P is a permutation matrix, F 11, F 33, G 11 and G 33 are upper triangular. Then the diagonal elements of the matrix pairs F 11,G 11 and F 33,G 33 are generalized eigenvalues of A,B. The rest of the generalized eigenvalues are given by the matrix pair F 22,G 22 which are in rows and columns ilo to ihi. Subsequent operations to compute the generalized eigenvalues of A,B need only be applied to the matrix pair F 22,G 22; this can save a significant amount of work if ilo>1 and ihi<n. If no suitable permutation exists (as is often the case), the routine sets ilo=1 and ihi=n.
2. The routine applies a diagonal similarity transformation to F,G, to make the rows and columns of F 22,G 22 as close in norm as possible:
DF D^= I 0 0 0 D 22 0 0 0 I F 11 F 12 F 13 F 22 F 23 F 33 I 0 0 0 D^22 0 0 0 I
DG D-1= I 0 0 0 D 22 0 0 0 I G 11 G 12 G 13 G 22 G 23 G 33 I 0 0 0 D^22 0 0 0 I
This transformation usually improves the accuracy of computed generalized eigenvalues and eigenvectors.

4 References

Ward R C (1981) Balancing the generalized eigenvalue problem SIAM J. Sci. Stat. Comp. 2 141–152

5 Arguments

1:   JOB – CHARACTER(1)Input
On entry: specifies the operations to be performed on matrices A and B.
JOB='N'
No balancing is done. Initialize ILO=1, IHI=N, LSCALE i=1.0 and RSCALE i=1.0, for i=1,2,…,n.
JOB='P'
Only permutations are used in balancing.
JOB='S'
Only scalings are are used in balancing.
JOB='B'
Both permutations and scalings are used in balancing.
Constraint: JOB='N', 'P', 'S' or 'B'.
2:   N – INTEGERInput
On entry: n, the order of the matrices A and B.
Constraint: N≥0.
3:   A LDA* – COMPLEX (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array A must be at least max 1,N.
On entry: the n by n matrix A.
On exit: A is overwritten by the balanced matrix. If JOB='N', A is not referenced.
4:   LDA – INTEGERInput
On entry: the first dimension of the array A as declared in the (sub)program from which F08WVF (ZGGBAL) is called.
Constraint: LDA≥max 1,N.
5:   B LDB* – COMPLEX (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array B must be at least max 1,N.
On entry: the n by n matrix B.
On exit: B is overwritten by the balanced matrix. If JOB='N', B is not referenced.
6:   LDB – INTEGERInput
On entry: the first dimension of the array B as declared in the (sub)program from which F08WVF (ZGGBAL) is called.
Constraint: LDB≥max 1,N.
7:   ILO – INTEGEROutput
8:   IHI – INTEGEROutput
On exit: ilo and ihi are set such that A ij=0 and B ij=0 if i>j and 1≤j<ilo or ihi<i≤n.
If JOB='N' or 'S', ilo=1 and ihi=n.
9:   LSCALE N – REAL (KIND=nag_wp) arrayOutput
On exit: details of the permutations and scaling factors applied to the left side of the matrices A and B. If Pi is the index of the row interchanged with row i and di is the scaling factor applied to row i, then
  • LSCALE i=Pi, for i=1,2,…,ilo-1;
  • LSCALE i=di, for i=ilo,…,ihi;
  • LSCALE i=Pi, for i=ihi+1,…,n.
The order in which the interchanges are made is n to ihi+1, then 1 to ilo-1.
10:   RSCALE N – REAL (KIND=nag_wp) arrayOutput
On exit: details of the permutations and scaling factors applied to the right side of the matrices A and B.
If Pj is the index of the column interchanged with column j and d^j is the scaling factor applied to column j, then
  • RSCALE j=Pj, for j=1,2,…,ilo-1;
  • RSCALE j=d^j, for j=ilo,…,ihi;
  • RSCALE j=Pj, for j=ihi+1,…,n.
The order in which the interchanges are made is n to ihi+1, then 1 to ilo-1.
11:   WORK 6×N – REAL (KIND=nag_wp) arrayWorkspace
12:   INFO – INTEGEROutput
On exit: INFO=0 unless the routine detects an error (see Section 6).

6 Error Indicators and Warnings

INFO<0
If INFO=-i, argument i had an illegal value. An explanatory message is output, and execution of the program is terminated.

7 Accuracy

The errors are negligible, compared to those in subsequent computations.

8 Parallelism and Performance

F08WVF (ZGGBAL) makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

F08WVF (ZGGBAL) is usually the first step in computing the complex generalized eigenvalue problem but it is an optional step. The matrix B is reduced to the triangular form using the QR factorization routine F08ASF (ZGEQRF) and the unitary transformation Q is applied to the matrix A by calling F08AUF (ZUNMQR). This is followed by F08WSF (ZGGHRD) which reduces the matrix pair into the generalized Hessenberg form.
If the matrix pair A,B is balanced by this routine, then any generalized eigenvectors computed subsequently are eigenvectors of the balanced matrix pair. In that case, to compute the generalized eigenvectors of the original matrix, F08WWF (ZGGBAK) must be called.
The total number of floating-point operations is approximately proportional to n 2.
The real analogue of this routine is F08WHF (DGGBAL).

10 Example

See Section 10 in F08XSF (ZHGEQZ) and F08YXF (ZTGEVC).
F08 Chapter Contents
F08 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F08WWF (ZGGBAK) : NAG Library, Mark 26

F08 Chapter Contents
F08 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F08WWF (ZGGBAK)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
10 Example

1 Purpose

F08WWF (ZGGBAK) forms the right or left eigenvectors of the real generalized eigenvalue problem Ax=λBx, by backward transformation on the computed eigenvectors given by F08YXF (ZTGEVC). It is necessary to call this routine only if the optional balancing routine F08WVF (ZGGBAL) was previously called to balance the matrix pair A,B.

2 Specification

SUBROUTINE F08WWF ( JOB, SIDE, N, ILO, IHI, LSCALE, RSCALE, M, V, LDV, INFO)
INTEGER | N, ILO, IHI, M, LDV, INFO
REAL (KIND=nag_wp) | LSCALE(*), RSCALE(*)
COMPLEX (KIND=nag_wp) | V(LDV,*)
CHARACTER(1) | JOB, SIDE
The routine may be called by its LAPACK name zggbak.

3 Description

If the matrix pair has been previously balanced using the routine F08WVF (ZGGBAL) then F08WWF (ZGGBAK) backtransforms the eigenvector solution given by F08YXF (ZTGEVC). This is usually the sixth and last step in the solution of the generalized eigenvalue problem.
For a description of balancing, see the document for F08WVF (ZGGBAL).

4 References

Ward R C (1981) Balancing the generalized eigenvalue problem SIAM J. Sci. Stat. Comp. 2 141–152

5 Arguments

1:   JOB – CHARACTER(1)Input
On entry: specifies the backtransformation step required.
JOB='N'
No transformations are done.
JOB='P'
Only do backward transformations based on permutations.
JOB='S'
Only do backward transformations based on scaling.
JOB='B'
Do backward transformations for both permutations and scaling.
Note: this must be identical to the argument JOB as supplied to F08WVF (ZGGBAL).
Constraint: JOB='N', 'P', 'S' or 'B'.
2:   SIDE – CHARACTER(1)Input
On entry: indicates whether left or right eigenvectors are to be transformed.
SIDE='L'
The left eigenvectors are transformed.
SIDE='R'
The right eigenvectors are transformed.
Constraint: SIDE='L' or 'R'.
3:   N – INTEGERInput
On entry: n, the order of the matrices A and B of the generalized eigenvalue problem.
Constraint: N≥0.
4:   ILO – INTEGERInput
5:   IHI – INTEGERInput
On entry: ilo and ihi as determined by a previous call to F08WVF (ZGGBAL).
Constraints:
  • if N>0, 1≤ ILO≤ IHI≤ N ;
  • if N=0, ILO=1 and IHI=0.
6:   LSCALE* – REAL (KIND=nag_wp) arrayInput
Note: the dimension of the array LSCALE must be at least max 1,N.
On entry: details of the permutations and scaling factors applied to the left side of the matrices A and B, as returned by a previous call to F08WVF (ZGGBAL).
7:   RSCALE* – REAL (KIND=nag_wp) arrayInput
Note: the dimension of the array RSCALE must be at least max 1,N.
On entry: details of the permutations and scaling factors applied to the right side of the matrices A and B, as returned by a previous call to F08WVF (ZGGBAL).
8:   M – INTEGERInput
On entry: m, the required number of left or right eigenvectors.
Constraint: 0≤M≤N.
9:   V LDV* – COMPLEX (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array V must be at least max 1,M.
On entry: the matrix of right or left eigenvectors, as returned by F08WVF (ZGGBAL).
On exit: the transformed right or left eigenvectors.
10:   LDV – INTEGERInput
On entry: the first dimension of the array V as declared in the (sub)program from which F08WWF (ZGGBAK) is called.
Constraint: LDV≥ max 1,N .
11:   INFO – INTEGEROutput
On exit: INFO=0 unless the routine detects an error (see Section 6).

6 Error Indicators and Warnings

INFO<0
If INFO=-i, argument i had an illegal value. An explanatory message is output, and execution of the program is terminated.

7 Accuracy

The errors are negligible.

8 Parallelism and Performance

F08WWF (ZGGBAK) makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The number of operations is proportional to n 2.
The real analogue of this routine is F08WJF (DGGBAK).

10 Example

See Section 10 in F08XSF (ZHGEQZ) and F08YXF (ZTGEVC).
F08 Chapter Contents
F08 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F08XAF (DGGES) : NAG Library, Mark 26

F08 Chapter Contents
F08 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F08XAF (DGGES)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F08XAF (DGGES) computes the generalized eigenvalues, the generalized real Schur form S,T and, optionally, the left and/or right generalized Schur vectors for a pair of n by n real nonsymmetric matrices A,B . F08XAF (DGGES) is marked as deprecated by LAPACK; the replacement routine is F08XCF (DGGES3) which makes better use of level 3 BLAS.

2 Specification

SUBROUTINE F08XAF ( JOBVSL, JOBVSR, SORT, SELCTG, N, A, LDA, B, LDB, SDIM, ALPHAR, ALPHAI, BETA, VSL, LDVSL, VSR, LDVSR, WORK, LWORK, BWORK, INFO)
INTEGER | N, LDA, LDB, SDIM, LDVSL, LDVSR, LWORK, INFO
REAL (KIND=nag_wp) | A(LDA,*), B(LDB,*), ALPHAR(N), ALPHAI(N), BETA(N), VSL(LDVSL,*), VSR(LDVSR,*), WORK(max(1,LWORK))
LOGICAL | SELCTG, BWORK(*)
CHARACTER(1) | JOBVSL, JOBVSR, SORT
EXTERNAL | SELCTG
The routine may be called by its LAPACK name dgges.

3 Description

The generalized Schur factorization for a pair of real matrices A,B is given by
A = QS ZT ,   B = QT ZT ,
where Q and Z are orthogonal, T is upper triangular and S is upper quasi-triangular with 1 by 1 and 2 by 2 diagonal blocks. The generalized eigenvalues, λ , of A,B are computed from the diagonals of S and T and satisfy
Az = λBz ,
where z is the corresponding generalized eigenvector. λ is actually returned as the pair α,β such that
λ = α/β
since β , or even both α and β can be zero. The columns of Q and Z are the left and right generalized Schur vectors of A,B .
Optionally, F08XAF (DGGES) can order the generalized eigenvalues on the diagonals of S,T so that selected eigenvalues are at the top left. The leading columns of Q and Z then form an orthonormal basis for the corresponding eigenspaces, the deflating subspaces.
F08XAF (DGGES) computes T to have non-negative diagonal elements, and the 2 by 2 blocks of S correspond to complex conjugate pairs of generalized eigenvalues. The generalized Schur factorization, before reordering, is computed by the QZ algorithm.

4 References

Anderson E, Bai Z, Bischof C, Blackford S, Demmel J, Dongarra J J, Du Croz J J, Greenbaum A, Hammarling S, McKenney A and Sorensen D (1999) LAPACK Users' Guide (3rd Edition) SIAM, Philadelphia http://www.netlib.org/lapack/lug
Golub G H and Van Loan C F (1996) Matrix Computations (3rd Edition) Johns Hopkins University Press, Baltimore

5 Arguments

1:   JOBVSL – CHARACTER(1)Input
On entry: if JOBVSL='N', do not compute the left Schur vectors.
If JOBVSL='V', compute the left Schur vectors.
Constraint: JOBVSL='N' or 'V'.
2:   JOBVSR – CHARACTER(1)Input
On entry: if JOBVSR='N', do not compute the right Schur vectors.
If JOBVSR='V', compute the right Schur vectors.
Constraint: JOBVSR='N' or 'V'.
3:   SORT – CHARACTER(1)Input
On entry: specifies whether or not to order the eigenvalues on the diagonal of the generalized Schur form.
SORT='N'
Eigenvalues are not ordered.
SORT='S'
Eigenvalues are ordered (see SELCTG).
Constraint: SORT='N' or 'S'.
4:   SELCTG – LOGICAL FUNCTION, supplied by the user.External Procedure
If SORT='S', SELCTG is used to select generalized eigenvalues to be moved to the top left of the generalized Schur form.
If SORT='N', SELCTG is not referenced by F08XAF (DGGES), and may be called with the dummy function F08XAZ.
The specification of SELCTG is:
FUNCTION SELCTG ( AR, AI, B)
LOGICAL SELCTG
REAL (KIND=nag_wp) AR, AI, B
1:   AR – REAL (KIND=nag_wp)Input
2:   AI – REAL (KIND=nag_wp)Input
3:   B – REAL (KIND=nag_wp)Input
On entry: an eigenvalue AR j + -1 × AI j / B j is selected if SELCTG AR j,AI j,B j=.TRUE. . If either one of a complex conjugate pair is selected, then both complex generalized eigenvalues are selected.
Note that in the ill-conditioned case, a selected complex generalized eigenvalue may no longer satisfy SELCTG AR j,AI j,B j=.TRUE. after ordering. INFO=N+2 in this case.
SELCTG must either be a module subprogram USEd by, or declared as EXTERNAL in, the (sub)program from which F08XAF (DGGES) is called. Arguments denoted as Input must not be changed by this procedure.
5:   N – INTEGERInput
On entry: n, the order of the matrices A and B.
Constraint: N≥0.
6:   A LDA* – REAL (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array A must be at least max 1,N.
On entry: the first of the pair of matrices, A.
On exit: A has been overwritten by its generalized Schur form S.
7:   LDA – INTEGERInput
On entry: the first dimension of the array A as declared in the (sub)program from which F08XAF (DGGES) is called.
Constraint: LDA≥max 1,N.
8:   B LDB* – REAL (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array B must be at least max 1,N.
On entry: the second of the pair of matrices, B.
On exit: B has been overwritten by its generalized Schur form T.
9:   LDB – INTEGERInput
On entry: the first dimension of the array B as declared in the (sub)program from which F08XAF (DGGES) is called.
Constraint: LDB≥max 1,N.
10:   SDIM – INTEGEROutput
On exit: if SORT='N', SDIM=0.
If SORT='S', SDIM= number of eigenvalues (after sorting) for which SELCTG is .TRUE.. (Complex conjugate pairs for which SELCTG is .TRUE. for either eigenvalue count as 2.)
11:   ALPHAR N – REAL (KIND=nag_wp) arrayOutput
On exit: see the description of BETA.
12:   ALPHAI N – REAL (KIND=nag_wp) arrayOutput
On exit: see the description of BETA.
13:   BETA N – REAL (KIND=nag_wp) arrayOutput
On exit: ALPHAR j+ALPHAI j×i/BETA j, for j=1,2,…,N, will be the generalized eigenvalues. ALPHAR j+ALPHAI j×i, and BETA j, for j=1,2,…,N, are the diagonals of the complex Schur form S,T that would result if the 2 by 2 diagonal blocks of the real Schur form of A,B were further reduced to triangular form using 2 by 2 complex unitary transformations.
If ALPHAI j is zero, then the jth eigenvalue is real; if positive, then the jth and j+1st eigenvalues are a complex conjugate pair, with ALPHAI j+1 negative.
Note: the quotients ALPHAR j/BETA j and ALPHAI j/BETA j may easily overflow or underflow, and BETA j may even be zero. Thus, you should avoid naively computing the ratio α/β. However, ALPHAR and ALPHAI will always be less than and usually comparable with A 2 in magnitude, and BETA will always be less than and usually comparable with B 2.
14:   VSL LDVSL* – REAL (KIND=nag_wp) arrayOutput
Note: the second dimension of the array VSL must be at least max 1,N if JOBVSL='V', and at least 1 otherwise.
On exit: if JOBVSL='V', VSL will contain the left Schur vectors, Q.
If JOBVSL='N', VSL is not referenced.
15:   LDVSL – INTEGERInput
On entry: the first dimension of the array VSL as declared in the (sub)program from which F08XAF (DGGES) is called.
Constraints:
  • if JOBVSL='V', LDVSL≥ max 1,N ;
  • otherwise LDVSL≥1.
16:   VSR LDVSR* – REAL (KIND=nag_wp) arrayOutput
Note: the second dimension of the array VSR must be at least max 1,N if JOBVSR='V', and at least 1 otherwise.
On exit: if JOBVSR='V', VSR will contain the right Schur vectors, Z.
If JOBVSR='N', VSR is not referenced.
17:   LDVSR – INTEGERInput
On entry: the first dimension of the array VSR as declared in the (sub)program from which F08XAF (DGGES) is called.
Constraints:
  • if JOBVSR='V', LDVSR≥ max 1,N ;
  • otherwise LDVSR≥1.
18:   WORK max 1,LWORK – REAL (KIND=nag_wp) arrayWorkspace
On exit: if INFO=0, WORK 1 contains the minimum value of LWORK required for optimal performance.
19:   LWORK – INTEGERInput
On entry: the dimension of the array WORK as declared in the (sub)program from which F08XAF (DGGES) is called.
If LWORK=-1, a workspace query is assumed; the routine only calculates the optimal size of the WORK array, returns this value as the first entry of the WORK array, and no error message related to LWORK is issued.
Suggested value: for optimal performance, LWORK must generally be larger than the mimimum; add, say nb×N, where nb is the optimal block size.
Constraints:
  • if N=0, LWORK≥1;
  • otherwise LWORK≥ max 8×N,6×N+16 .
20:   BWORK* – LOGICAL arrayWorkspace
Note: the dimension of the array BWORK must be at least 1 if SORT='N', and at least max 1,N otherwise.
If SORT='N', BWORK is not referenced.
21:   INFO – INTEGEROutput
On exit: INFO=0 unless the routine detects an error (see Section 6).

6 Error Indicators and Warnings

INFO<0
If INFO=-i, argument i had an illegal value. An explanatory message is output, and execution of the program is terminated.
INFO=1 to N
The QZ iteration failed. A,B are not in Schur form, but ALPHAR j, ALPHAI j, and BETA j should be correct for j=INFO+1,…,N.
INFO=N+1
Unexpected error returned from F08XEF (DHGEQZ).
INFO=N+2
After reordering, roundoff changed values of some complex eigenvalues so that leading eigenvalues in the generalized Schur form no longer satisfy SELCTG=.TRUE.. This could also be caused by underflow due to scaling.
INFO=N+3
The eigenvalues could not be reordered because some eigenvalues were too close to separate (the problem is very ill-conditioned).

7 Accuracy

The computed generalized Schur factorization satisfies
A+E = QS ZT ,   B+F = QT ZT ,
where
E,F F = O ε A,B F
and ε is the machine precision. See Section 4.11 of Anderson et al. (1999) for further details.

8 Parallelism and Performance

F08XAF (DGGES) is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
F08XAF (DGGES) makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The total number of floating-point operations is proportional to n 3.
The complex analogue of this routine is F08XNF (ZGGES).

10 Example

This example finds the generalized Schur factorization of the matrix pair A,B, where
A = 3.9 12.5 -34.5 -0.5 4.3 21.5 -47.5 7.5 4.3 21.5 -43.5 3.5 4.4 26.0 -46.0 6.0   and   B= 1.0 2.0 -3.0 1.0 1.0 3.0 -5.0 4.0 1.0 3.0 -4.0 3.0 1.0 3.0 -4.0 4.0 ,
such that the real positive eigenvalues of A,B correspond to the top left diagonal elements of the generalized Schur form, S,T.
Note that the block size (NB) of 64 assumed in this example is not realistic for such a small problem, but should be suitable for large problems.

10.1 Program Text

Program Text (f08xafe.f90)

10.2 Program Data

Program Data (f08xafe.d)

10.3 Program Results

Program Results (f08xafe.r)

F08 Chapter Contents
F08 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F08XBF (DGGESX) : NAG Library, Mark 26

F08 Chapter Contents
F08 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F08XBF (DGGESX)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F08XBF (DGGESX) computes the generalized eigenvalues, the generalized real Schur form S,T and, optionally, the left and/or right generalized Schur vectors for a pair of n by n real nonsymmetric matrices A,B .
Estimates of condition numbers for selected generalized eigenvalue clusters and Schur vectors are also computed.

2 Specification

SUBROUTINE F08XBF ( JOBVSL, JOBVSR, SORT, SELCTG, SENSE, N, A, LDA, B, LDB, SDIM, ALPHAR, ALPHAI, BETA, VSL, LDVSL, VSR, LDVSR, RCONDE, RCONDV, WORK, LWORK, IWORK, LIWORK, BWORK, INFO)
INTEGER | N, LDA, LDB, SDIM, LDVSL, LDVSR, LWORK, IWORK(max(1,LIWORK)), LIWORK, INFO
REAL (KIND=nag_wp) | A(LDA,*), B(LDB,*), ALPHAR(N), ALPHAI(N), BETA(N), VSL(LDVSL,*), VSR(LDVSR,*), RCONDE(2), RCONDV(2), WORK(max(1,LWORK))
LOGICAL | SELCTG, BWORK(*)
CHARACTER(1) | JOBVSL, JOBVSR, SORT, SENSE
EXTERNAL | SELCTG
The routine may be called by its LAPACK name dggesx.

3 Description

The generalized real Schur factorization of A,B is given by
A = QS ZT ,   B = QT ZT ,
where Q and Z are orthogonal, T is upper triangular and S is upper quasi-triangular with 1 by 1 and 2 by 2 diagonal blocks. The generalized eigenvalues, λ , of A,B are computed from the diagonals of T and S and satisfy
Az = λBz ,
where z is the corresponding generalized eigenvector. λ is actually returned as the pair α,β such that
λ = α/β
since β , or even both α and β can be zero. The columns of Q and Z are the left and right generalized Schur vectors of A,B .
Optionally, F08XBF (DGGESX) can order the generalized eigenvalues on the diagonals of S,T so that selected eigenvalues are at the top left. The leading columns of Q and Z then form an orthonormal basis for the corresponding eigenspaces, the deflating subspaces.
F08XBF (DGGESX) computes T to have non-negative diagonal elements, and the 2 by 2 blocks of S correspond to complex conjugate pairs of generalized eigenvalues. The generalized Schur factorization, before reordering, is computed by the QZ algorithm.
The reciprocals of the condition estimates, the reciprocal values of the left and right projection norms, are returned in RCONDE 1 and RCONDE 2 respectively, for the selected generalized eigenvalues, together with reciprocal condition estimates for the corresponding left and right deflating subspaces, in RCONDV 1 and RCONDV 2 . See Section 4.11 of Anderson et al. (1999) for further information.

4 References

Anderson E, Bai Z, Bischof C, Blackford S, Demmel J, Dongarra J J, Du Croz J J, Greenbaum A, Hammarling S, McKenney A and Sorensen D (1999) LAPACK Users' Guide (3rd Edition) SIAM, Philadelphia http://www.netlib.org/lapack/lug
Golub G H and Van Loan C F (1996) Matrix Computations (3rd Edition) Johns Hopkins University Press, Baltimore

5 Arguments

1:   JOBVSL – CHARACTER(1)Input
On entry: if JOBVSL='N', do not compute the left Schur vectors.
If JOBVSL='V', compute the left Schur vectors.
Constraint: JOBVSL='N' or 'V'.
2:   JOBVSR – CHARACTER(1)Input
On entry: if JOBVSR='N', do not compute the right Schur vectors.
If JOBVSR='V', compute the right Schur vectors.
Constraint: JOBVSR='N' or 'V'.
3:   SORT – CHARACTER(1)Input
On entry: specifies whether or not to order the eigenvalues on the diagonal of the generalized Schur form.
SORT='N'
Eigenvalues are not ordered.
SORT='S'
Eigenvalues are ordered (see SELCTG).
Constraint: SORT='N' or 'S'.
4:   SELCTG – LOGICAL FUNCTION, supplied by the user.External Procedure
If SORT='S', SELCTG is used to select generalized eigenvalues to be moved to the top left of the generalized Schur form.
If SORT='N', SELCTG is not referenced by F08XBF (DGGESX), and may be called with the dummy function F08XAZ.
The specification of SELCTG is:
FUNCTION SELCTG ( AR, AI, B)
LOGICAL SELCTG
REAL (KIND=nag_wp) AR, AI, B
1:   AR – REAL (KIND=nag_wp)Input
2:   AI – REAL (KIND=nag_wp)Input
3:   B – REAL (KIND=nag_wp)Input
On entry: an eigenvalue AR j + -1 × AI j / B j is selected if SELCTG AR j,AI j,B j is .TRUE.. If either one of a complex conjugate pair is selected, then both complex generalized eigenvalues are selected.
Note that in the ill-conditioned case, a selected complex generalized eigenvalue may no longer satisfy SELCTG AR j,AI j,B j=.TRUE. after ordering. INFO=N+2 in this case.
SELCTG must either be a module subprogram USEd by, or declared as EXTERNAL in, the (sub)program from which F08XBF (DGGESX) is called. Arguments denoted as Input must not be changed by this procedure.
5:   SENSE – CHARACTER(1)Input
On entry: determines which reciprocal condition numbers are computed.
SENSE='N'
None are computed.
SENSE='E'
Computed for average of selected eigenvalues only.
SENSE='V'
Computed for selected deflating subspaces only.
SENSE='B'
Computed for both.
If SENSE='E', 'V' or 'B', SORT='S'.
Constraint: SENSE='N', 'E', 'V' or 'B'.
6:   N – INTEGERInput
On entry: n, the order of the matrices A and B.
Constraint: N≥0.
7:   A LDA* – REAL (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array A must be at least max 1,N.
On entry: the first of the pair of matrices, A.
On exit: A has been overwritten by its generalized Schur form S.
8:   LDA – INTEGERInput
On entry: the first dimension of the array A as declared in the (sub)program from which F08XBF (DGGESX) is called.
Constraint: LDA≥max 1,N.
9:   B LDB* – REAL (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array B must be at least max 1,N.
On entry: the second of the pair of matrices, B.
On exit: B has been overwritten by its generalized Schur form T.
10:   LDB – INTEGERInput
On entry: the first dimension of the array B as declared in the (sub)program from which F08XBF (DGGESX) is called.
Constraint: LDB≥max 1,N.
11:   SDIM – INTEGEROutput
On exit: if SORT='N', SDIM=0.
If SORT='S', SDIM= number of eigenvalues (after sorting) for which SELCTG is .TRUE.. (Complex conjugate pairs for which SELCTG is .TRUE. for either eigenvalue count as 2.)
12:   ALPHAR N – REAL (KIND=nag_wp) arrayOutput
On exit: see the description of BETA.
13:   ALPHAI N – REAL (KIND=nag_wp) arrayOutput
On exit: see the description of BETA.
14:   BETA N – REAL (KIND=nag_wp) arrayOutput
On exit: ALPHAR j+ALPHAI j×i/BETA j, for j=1,2,…,N, will be the generalized eigenvalues. ALPHAR j+ALPHAI j×i, and BETA j, for j=1,2,…,N, are the diagonals of the complex Schur form S,T that would result if the 2 by 2 diagonal blocks of the real Schur form of A,B were further reduced to triangular form using 2 by 2 complex unitary transformations.
If ALPHAI j is zero, then the jth eigenvalue is real; if positive, then the jth and j+1st eigenvalues are a complex conjugate pair, with ALPHAI j+1 negative.
Note: the quotients ALPHAR j/BETA j and ALPHAI j/BETA j may easily overflow or underflow, and BETA j may even be zero. Thus, you should avoid naively computing the ratio α/β. However, ALPHAR and ALPHAI will always be less than and usually comparable with A 2 in magnitude, and BETA will always be less than and usually comparable with B 2.
15:   VSL LDVSL* – REAL (KIND=nag_wp) arrayOutput
Note: the second dimension of the array VSL must be at least max 1,N if JOBVSL='V', and at least 1 otherwise.
On exit: if JOBVSL='V', VSL will contain the left Schur vectors, Q.
If JOBVSL='N', VSL is not referenced.
16:   LDVSL – INTEGERInput
On entry: the first dimension of the array VSL as declared in the (sub)program from which F08XBF (DGGESX) is called.
Constraints:
  • if JOBVSL='V', LDVSL≥ max 1,N ;
  • otherwise LDVSL≥1.
17:   VSR LDVSR* – REAL (KIND=nag_wp) arrayOutput
Note: the second dimension of the array VSR must be at least max 1,N if JOBVSR='V', and at least 1 otherwise.
On exit: if JOBVSR='V', VSR will contain the right Schur vectors, Z.
If JOBVSR='N', VSR is not referenced.
18:   LDVSR – INTEGERInput
On entry: the first dimension of the array VSR as declared in the (sub)program from which F08XBF (DGGESX) is called.
Constraints:
  • if JOBVSR='V', LDVSR≥ max 1,N ;
  • otherwise LDVSR≥1.
19:   RCONDE 2 – REAL (KIND=nag_wp) arrayOutput
On exit: if SENSE='E' or 'B', RCONDE 1 and RCONDE 2 contain the reciprocal condition numbers for the average of the selected eigenvalues.
If SENSE='N' or 'V', RCONDE is not referenced.
20:   RCONDV 2 – REAL (KIND=nag_wp) arrayOutput
On exit: if SENSE='V' or 'B', RCONDV 1 and RCONDV 2 contain the reciprocal condition numbers for the selected deflating subspaces.
if SENSE='N' or 'E', RCONDV is not referenced.
21:   WORK max 1,LWORK – REAL (KIND=nag_wp) arrayWorkspace
On exit: if INFO=0, WORK 1 returns the optimal LWORK.
22:   LWORK – INTEGERInput
On entry: the dimension of the array WORK as declared in the (sub)program from which F08XBF (DGGESX) is called.
If LWORK=-1, a workspace query is assumed; the routine only calculates the bound on the optimal size of the WORK array and the minimum size of the IWORK array, returns these values as the first entries of the WORK and IWORK arrays, and no error message related to LWORK or LIWORK is issued.
Constraints:
  • if SENSE='E', 'V' or 'B', LWORK≥ max 8×N+1+16,2×SDIM×N-SDIM ;
  • otherwise LWORK≥ max 1,8×N,6×N+16.
Note: that 2×SDIM×N-SDIM≤N×N/2. Note also that an error is only returned if LWORK<8×N+1+16, but if SENSE='E', 'V' or 'B' this may not be large enough. Consider increasing LWORK by nb, where nb is the optimal block size.
23:   IWORK max 1,LIWORK – INTEGER arrayWorkspace
On exit: if INFO=0, IWORK 1 returns the minimum LIWORK.
24:   LIWORK – INTEGERInput
On entry: the dimension of the array IWORK as declared in the (sub)program from which F08XBF (DGGESX) is called.
If LIWORK=-1, a workspace query is assumed; the routine only calculates the bound on the optimal size of the WORK array and the minimum size of the IWORK array, returns these values as the first entries of the WORK and IWORK arrays, and no error message related to LWORK or LIWORK is issued.
Constraints:
  • if SENSE='N' or N=0, LIWORK≥1;
  • otherwise LIWORK≥N+6.
25:   BWORK* – LOGICAL arrayWorkspace
Note: the dimension of the array BWORK must be at least 1 if SORT='N', and at least max 1,N otherwise.
If SORT='N', BWORK is not referenced.
26:   INFO – INTEGEROutput
On exit: INFO=0 unless the routine detects an error (see Section 6).

6 Error Indicators and Warnings

INFO<0
If INFO=-i, argument i had an illegal value. An explanatory message is output, and execution of the program is terminated.
INFO=1 to N
The QZ iteration failed. A,B are not in Schur form, but ALPHAR j, ALPHAI j, and BETA j should be correct for j=INFO+1,…,N.
INFO=N+1
Unexpected error returned from F08XEF (DHGEQZ).
INFO=N+2
After reordering, roundoff changed values of some complex eigenvalues so that leading eigenvalues in the generalized Schur form no longer satisfy SELCTG=.TRUE.. This could also be caused by underflow due to scaling.
INFO=N+3
The eigenvalues could not be reordered because some eigenvalues were too close to separate (the problem is very ill-conditioned).

7 Accuracy

The computed generalized Schur factorization satisfies
A+E = QS ZT ,   B+F = QT ZT ,
where
E,F F = O ε A,B F
and ε is the machine precision. See Section 4.11 of Anderson et al. (1999) for further details.

8 Parallelism and Performance

F08XBF (DGGESX) is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
F08XBF (DGGESX) makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The total number of floating-point operations is proportional to n 3.
The complex analogue of this routine is F08XPF (ZGGESX).

10 Example

This example finds the generalized Schur factorization of the matrix pair A,B, where
A = 3.9 12.5 -34.5 -0.5 4.3 21.5 -47.5 7.5 4.3 21.5 -43.5 3.5 4.4 26.0 -46.0 6.0   and   B= 1.0 2.0 -3.0 1.0 1.0 3.0 -5.0 4.0 1.0 3.0 -4.0 3.0 1.0 3.0 -4.0 4.0 ,
such that the real positive eigenvalues of A,B correspond to the top left diagonal elements of the generalized Schur form, S,T. Estimates of the condition numbers for the selected eigenvalue cluster and corresponding deflating subspaces are also returned.
Note that the block size (NB) of 64 assumed in this example is not realistic for such a small problem, but should be suitable for large problems.

10.1 Program Text

Program Text (f08xbfe.f90)

10.2 Program Data

Program Data (f08xbfe.d)

10.3 Program Results

Program Results (f08xbfe.r)

F08 Chapter Contents
F08 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F08XCF (DGGES3) : NAG Library, Mark 26

F08 Chapter Contents
F08 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F08XCF (DGGES3)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F08XCF (DGGES3) computes the generalized eigenvalues, the generalized real Schur form S,T and, optionally, the left and/or right generalized Schur vectors for a pair of n by n real nonsymmetric matrices A,B .

2 Specification

SUBROUTINE F08XCF ( JOBVSL, JOBVSR, SORT, SELCTG, N, A, LDA, B, LDB, SDIM, ALPHAR, ALPHAI, BETA, VSL, LDVSL, VSR, LDVSR, WORK, LWORK, BWORK, INFO)
INTEGER | N, LDA, LDB, SDIM, LDVSL, LDVSR, LWORK, INFO
REAL (KIND=nag_wp) | A(LDA,*), B(LDB,*), ALPHAR(N), ALPHAI(N), BETA(N), VSL(LDVSL,*), VSR(LDVSR,*), WORK(max(1,LWORK))
LOGICAL | SELCTG, BWORK(*)
CHARACTER(1) | JOBVSL, JOBVSR, SORT
EXTERNAL | SELCTG
The routine may be called by its LAPACK name dgges3.

3 Description

The generalized Schur factorization for a pair of real matrices A,B is given by
A = QS ZT ,   B = QT ZT ,
where Q and Z are orthogonal, T is upper triangular and S is upper quasi-triangular with 1 by 1 and 2 by 2 diagonal blocks. The generalized eigenvalues, λ , of A,B are computed from the diagonals of S and T and satisfy
Az = λBz ,
where z is the corresponding generalized eigenvector. λ is actually returned as the pair α,β such that
λ = α/β
since β , or even both α and β can be zero. The columns of Q and Z are the left and right generalized Schur vectors of A,B .
Optionally, F08XCF (DGGES3) can order the generalized eigenvalues on the diagonals of S,T so that selected eigenvalues are at the top left. The leading columns of Q and Z then form an orthonormal basis for the corresponding eigenspaces, the deflating subspaces.
F08XCF (DGGES3) computes T to have non-negative diagonal elements, and the 2 by 2 blocks of S correspond to complex conjugate pairs of generalized eigenvalues. The generalized Schur factorization, before reordering, is computed by the QZ algorithm.

4 References

Anderson E, Bai Z, Bischof C, Blackford S, Demmel J, Dongarra J J, Du Croz J J, Greenbaum A, Hammarling S, McKenney A and Sorensen D (1999) LAPACK Users' Guide (3rd Edition) SIAM, Philadelphia http://www.netlib.org/lapack/lug
Golub G H and Van Loan C F (2012) Matrix Computations (4th Edition) Johns Hopkins University Press, Baltimore

5 Arguments

1:   JOBVSL – CHARACTER(1)Input
On entry: if JOBVSL='N', do not compute the left Schur vectors.
If JOBVSL='V', compute the left Schur vectors.
Constraint: JOBVSL='N' or 'V'.
2:   JOBVSR – CHARACTER(1)Input
On entry: if JOBVSR='N', do not compute the right Schur vectors.
If JOBVSR='V', compute the right Schur vectors.
Constraint: JOBVSR='N' or 'V'.
3:   SORT – CHARACTER(1)Input
On entry: specifies whether or not to order the eigenvalues on the diagonal of the generalized Schur form.
SORT='N'
Eigenvalues are not ordered.
SORT='S'
Eigenvalues are ordered (see SELCTG).
Constraint: SORT='N' or 'S'.
4:   SELCTG – LOGICAL FUNCTION, supplied by the user.External Procedure
If SORT='S', SELCTG is used to select generalized eigenvalues to be moved to the top left of the generalized Schur form.
If SORT='N', SELCTG is not referenced by F08XCF (DGGES3), and may be called with the dummy function F08XAZ.
The specification of SELCTG is:
FUNCTION SELCTG ( AR, AI, B)
LOGICAL SELCTG
REAL (KIND=nag_wp) AR, AI, B
1:   AR – REAL (KIND=nag_wp)Input
2:   AI – REAL (KIND=nag_wp)Input
3:   B – REAL (KIND=nag_wp)Input
On entry: an eigenvalue AR j + -1 × AI j / B j is selected if SELCTG AR j,AI j,B j=.TRUE. . If either one of a complex conjugate pair is selected, then both complex generalized eigenvalues are selected.
Note that in the ill-conditioned case, a selected complex generalized eigenvalue may no longer satisfy SELCTG AR j,AI j,B j=.TRUE. after ordering. INFO=N+2 in this case.
SELCTG must either be a module subprogram USEd by, or declared as EXTERNAL in, the (sub)program from which F08XCF (DGGES3) is called. Arguments denoted as Input must not be changed by this procedure.
5:   N – INTEGERInput
On entry: n, the order of the matrices A and B.
Constraint: N≥0.
6:   A LDA* – REAL (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array A must be at least max 1,N.
On entry: the first of the pair of matrices, A.
On exit: A has been overwritten by its generalized Schur form S.
7:   LDA – INTEGERInput
On entry: the first dimension of the array A as declared in the (sub)program from which F08XCF (DGGES3) is called.
Constraint: LDA≥max 1,N.
8:   B LDB* – REAL (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array B must be at least max 1,N.
On entry: the second of the pair of matrices, B.
On exit: B has been overwritten by its generalized Schur form T.
9:   LDB – INTEGERInput
On entry: the first dimension of the array B as declared in the (sub)program from which F08XCF (DGGES3) is called.
Constraint: LDB≥max 1,N.
10:   SDIM – INTEGEROutput
On exit: if SORT='N', SDIM=0.
If SORT='S', SDIM= number of eigenvalues (after sorting) for which SELCTG is .TRUE.. (Complex conjugate pairs for which SELCTG is .TRUE. for either eigenvalue count as 2.)
11:   ALPHAR N – REAL (KIND=nag_wp) arrayOutput
On exit: see the description of BETA.
12:   ALPHAI N – REAL (KIND=nag_wp) arrayOutput
On exit: see the description of BETA.
13:   BETA N – REAL (KIND=nag_wp) arrayOutput
On exit: ALPHAR j+ALPHAI j×i/BETA j, for j=1,2,…,N, will be the generalized eigenvalues. ALPHAR j+ALPHAI j×i, and BETA j, for j=1,2,…,N, are the diagonals of the complex Schur form S,T that would result if the 2 by 2 diagonal blocks of the real Schur form of A,B were further reduced to triangular form using 2 by 2 complex unitary transformations.
If ALPHAI j is zero, then the jth eigenvalue is real; if positive, then the jth and j+1st eigenvalues are a complex conjugate pair, with ALPHAI j+1 negative.
Note: the quotients ALPHAR j/BETA j and ALPHAI j/BETA j may easily overflow or underflow, and BETA j may even be zero. Thus, you should avoid naively computing the ratio α/β. However, ALPHAR and ALPHAI will always be less than and usually comparable with A 2 in magnitude, and BETA will always be less than and usually comparable with B 2.
14:   VSL LDVSL* – REAL (KIND=nag_wp) arrayOutput
Note: the second dimension of the array VSL must be at least max 1,N if JOBVSL='V', and at least 1 otherwise.
On exit: if JOBVSL='V', VSL will contain the left Schur vectors, Q.
If JOBVSL='N', VSL is not referenced.
15:   LDVSL – INTEGERInput
On entry: the first dimension of the array VSL as declared in the (sub)program from which F08XCF (DGGES3) is called.
Constraints:
  • if JOBVSL='V', LDVSL≥ max 1,N ;
  • otherwise LDVSL≥1.
16:   VSR LDVSR* – REAL (KIND=nag_wp) arrayOutput
Note: the second dimension of the array VSR must be at least max 1,N if JOBVSR='V', and at least 1 otherwise.
On exit: if JOBVSR='V', VSR will contain the right Schur vectors, Z.
If JOBVSR='N', VSR is not referenced.
17:   LDVSR – INTEGERInput
On entry: the first dimension of the array VSR as declared in the (sub)program from which F08XCF (DGGES3) is called.
Constraints:
  • if JOBVSR='V', LDVSR≥ max 1,N ;
  • otherwise LDVSR≥1.
18:   WORK max 1,LWORK – REAL (KIND=nag_wp) arrayWorkspace
On exit: if INFO=0, WORK 1 contains the minimum value of LWORK required for optimal performance.
19:   LWORK – INTEGERInput
On entry: the dimension of the array WORK as declared in the (sub)program from which F08XCF (DGGES3) is called.
If LWORK=-1, a workspace query is assumed; the routine only calculates the optimal size of the WORK array, returns this value as the first entry of the WORK array, and no error message related to LWORK is issued.
Suggested value: for optimal performance, LWORK must generally be larger than the mimimum; add, say nb×N×6, where nb is the optimal block size.
Constraints:
  • if N=0, LWORK≥1;
  • otherwise LWORK≥ max 8×N,6×N+16 .
20:   BWORK* – LOGICAL arrayWorkspace
Note: the dimension of the array BWORK must be at least 1 if SORT='N', and at least max 1,N otherwise.
If SORT='N', BWORK is not referenced.
21:   INFO – INTEGEROutput
On exit: INFO=0 unless the routine detects an error (see Section 6).

6 Error Indicators and Warnings

INFO<0
If INFO=-i, argument i had an illegal value. An explanatory message is output, and execution of the program is terminated.
INFO=1 to N
The QZ iteration failed. No eigenvectors have been calculated but ALPHAR j, ALPHAI j and BETA j should be correct from element value.
INFO=N+1
The QZ iteration failed with an unexpected error, please contact NAG.
INFO=N+2
After reordering, roundoff changed values of some complex eigenvalues so that leading eigenvalues in the generalized Schur form no longer satisfy SELCTG=.TRUE.. This could also be caused by underflow due to scaling.
INFO=N+3
The eigenvalues could not be reordered because some eigenvalues were too close to separate (the problem is very ill-conditioned).

7 Accuracy

The computed generalized Schur factorization satisfies
A+E = QS ZT ,   B+F = QT ZT ,
where
E,F F = O ε A,B F
and ε is the machine precision. See Section 4.11 of Anderson et al. (1999) for further details.

8 Parallelism and Performance

F08XCF (DGGES3) is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
F08XCF (DGGES3) makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The total number of floating-point operations is proportional to n 3.
The complex analogue of this routine is F08XQF (ZGGES3).

10 Example

This example finds the generalized Schur factorization of the matrix pair A,B, where
A = 3.9 12.5 -34.5 -0.5 4.3 21.5 -47.5 7.5 4.3 21.5 -43.5 3.5 4.4 26.0 -46.0 6.0   and   B= 1.0 2.0 -3.0 1.0 1.0 3.0 -5.0 4.0 1.0 3.0 -4.0 3.0 1.0 3.0 -4.0 4.0 ,
such that the real positive eigenvalues of A,B correspond to the top left diagonal elements of the generalized Schur form, S,T.

10.1 Program Text

Program Text (f08xcfe.f90)

10.2 Program Data

Program Data (f08xcfe.d)

10.3 Program Results

Program Results (f08xcfe.r)

F08 Chapter Contents
F08 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F08XEF (DHGEQZ) : NAG Library, Mark 26

F08 Chapter Contents
F08 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F08XEF (DHGEQZ)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F08XEF (DHGEQZ) implements the QZ method for finding generalized eigenvalues of the real matrix pair A,B of order n, which is in the generalized upper Hessenberg form.

2 Specification

SUBROUTINE F08XEF ( JOB, COMPQ, COMPZ, N, ILO, IHI, A, LDA, B, LDB, ALPHAR, ALPHAI, BETA, Q, LDQ, Z, LDZ, WORK, LWORK, INFO)
INTEGER | N, ILO, IHI, LDA, LDB, LDQ, LDZ, LWORK, INFO
REAL (KIND=nag_wp) | A(LDA,*), B(LDB,*), ALPHAR(N), ALPHAI(N), BETA(N), Q(LDQ,*), Z(LDZ,*), WORK(max(1,LWORK))
CHARACTER(1) | JOB, COMPQ, COMPZ
The routine may be called by its LAPACK name dhgeqz.

3 Description

F08XEF (DHGEQZ) implements a single-double-shift version of the QZ method for finding the generalized eigenvalues of the real matrix pair A,B which is in the generalized upper Hessenberg form. If the matrix pair A,B is not in the generalized upper Hessenberg form, then the routine F08WEF (DGGHRD) should be called before invoking F08XEF (DHGEQZ).
This problem is mathematically equivalent to solving the equation
det A-λB=0.
Note that, to avoid underflow, overflow and other arithmetic problems, the generalized eigenvalues λj are never computed explicitly by this routine but defined as ratios between two computed values, αj and βj:
λj=αj/βj.
The arguments αj, in general, are finite complex values and βj are finite real non-negative values.
If desired, the matrix pair A,B may be reduced to generalized Schur form. That is, the transformed matrix B is upper triangular and the transformed matrix A is block upper triangular, where the diagonal blocks are either 1 by 1 or 2 by 2. The 1 by 1 blocks provide generalized eigenvalues which are real and the 2 by 2 blocks give complex generalized eigenvalues.
The argument JOB specifies two options. If JOB='S' then the matrix pair A,B is simultaneously reduced to Schur form by applying one orthogonal transformation (usually called Q) on the left and another (usually called Z) on the right. That is,
A←QT AZ B←QT BZ
The 2 by 2 upper-triangular diagonal blocks of B corresponding to 2 by 2 blocks of A will be reduced to non-negative diagonal matrices. That is, if A j+1 j is nonzero, then B j+1 j=B j j+1=0 and B jj and B j+1j+1 will be non-negative.
If JOB='E', then at each iteration the same transformations are computed but they are only applied to those parts of A and B which are needed to compute α and β. This option could be used if generalized eigenvalues are required but not generalized eigenvectors.
If JOB='S' and COMPQ='V' or 'I', and COMPZ='V' or 'I', then the orthogonal transformations used to reduce the pair A,B are accumulated into the input arrays Q and Z. If generalized eigenvectors are required then JOB must be set to JOB='S' and if left (right) generalized eigenvectors are to be computed then COMPQ (COMPZ) must be set to COMPQ='V' or 'I' and not COMPQ≠'N'.
If COMPQ='I', then eigenvectors are accumulated on the identity matrix and on exit the array Q contains the left eigenvector matrix Q. However, if COMPQ='V' then the transformations are accumulated on the user-supplied matrix Q 0 in array Q on entry and thus on exit Q contains the matrix product Q Q 0. A similar convention is used for COMPZ.

4 References

Anderson E, Bai Z, Bischof C, Blackford S, Demmel J, Dongarra J J, Du Croz J J, Greenbaum A, Hammarling S, McKenney A and Sorensen D (1999) LAPACK Users' Guide (3rd Edition) SIAM, Philadelphia
Golub G H and Van Loan C F (1996) Matrix Computations (3rd Edition) Johns Hopkins University Press, Baltimore
Moler C B and Stewart G W (1973) An algorithm for generalized matrix eigenproblems SIAM J. Numer. Anal. 10 241–256
Stewart G W and Sun J-G (1990) Matrix Perturbation Theory Academic Press, London

5 Arguments

1:   JOB – CHARACTER(1)Input
On entry: specifies the operations to be performed on A,B.
JOB='E'
The matrix pair A,B on exit might not be in the generalized Schur form.
JOB='S'
The matrix pair A,B on exit will be in the generalized Schur form.
Constraint: JOB='E' or 'S'.
2:   COMPQ – CHARACTER(1)Input
On entry: specifies the operations to be performed on Q:
COMPQ='N'
The array Q is unchanged.
COMPQ='V'
The left transformation Q is accumulated on the array Q.
COMPQ='I'
The array Q is initialized to the identity matrix before the left transformation Q is accumulated in Q.
Constraint: COMPQ='N', 'V' or 'I'.
3:   COMPZ – CHARACTER(1)Input
On entry: specifies the operations to be performed on Z.
COMPZ='N'
The array Z is unchanged.
COMPZ='V'
The right transformation Z is accumulated on the array Z.
COMPZ='I'
The array Z is initialized to the identity matrix before the right transformation Z is accumulated in Z.
Constraint: COMPZ='N', 'V' or 'I'.
4:   N – INTEGERInput
On entry: n, the order of the matrices A, B, Q and Z.
Constraint: N≥0.
5:   ILO – INTEGERInput
6:   IHI – INTEGERInput
On entry: the indices ilo and ihi, respectively which define the upper triangular parts of A. The submatrices A 1:ilo-1,1:ilo-1 and A ihi+1:n,ihi+1:n are then upper triangular. These arguments are provided by F08WHF (DGGBAL) if the matrix pair was previously balanced; otherwise, ILO=1 and IHI=N.
Constraints:
  • if N>0, 1≤ ILO≤ IHI≤ N ;
  • if N=0, ILO=1 and IHI=0.
7:   A LDA* – REAL (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array A must be at least max 1,N.
On entry: the n by n upper Hessenberg matrix A. The elements below the first subdiagonal must be set to zero.
On exit: if JOB='S', the matrix pair A,B will be simultaneously reduced to generalized Schur form.
If JOB='E', the 1 by 1 and 2 by 2 diagonal blocks of the matrix pair A,B will give generalized eigenvalues but the remaining elements will be irrelevant.
8:   LDA – INTEGERInput
On entry: the first dimension of the array A as declared in the (sub)program from which F08XEF (DHGEQZ) is called.
Constraint: LDA≥max 1,N.
9:   B LDB* – REAL (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array B must be at least max 1,N.
On entry: the n by n upper triangular matrix B. The elements below the diagonal must be zero.
On exit: if JOB='S', the matrix pair A,B will be simultaneously reduced to generalized Schur form.
If JOB='E', the 1 by 1 and 2 by 2 diagonal blocks of the matrix pair A,B will give generalized eigenvalues but the remaining elements will be irrelevant.
10:   LDB – INTEGERInput
On entry: the first dimension of the array B as declared in the (sub)program from which F08XEF (DHGEQZ) is called.
Constraint: LDB≥max 1,N.
11:   ALPHAR N – REAL (KIND=nag_wp) arrayOutput
On exit: the real parts of αj, for j=1,2,…,n.
12:   ALPHAI N – REAL (KIND=nag_wp) arrayOutput
On exit: the imaginary parts of αj, for j=1,2,…,n.
13:   BETA N – REAL (KIND=nag_wp) arrayOutput
On exit: βj, for j=1,2,…,n.
14:   Q LDQ* – REAL (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array Q must be at least max 1,N if COMPQ='V' or 'I' and at least 1 if COMPQ='N'.
On entry: if COMPQ='V', the matrix Q 0. The matrix Q 0 is usually the matrix Q returned by F08WEF (DGGHRD).
If COMPQ='N', Q is not referenced.
On exit: if COMPQ='V', Q contains the matrix product Q Q 0.
If COMPQ='I', Q contains the transformation matrix Q.
15:   LDQ – INTEGERInput
On entry: the first dimension of the array Q as declared in the (sub)program from which F08XEF (DHGEQZ) is called.
Constraints:
  • if COMPQ='V' or 'I', LDQ≥N;
  • if COMPQ='N', LDQ≥1.
16:   Z LDZ* – REAL (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array Z must be at least max 1,N if COMPZ='V' or 'I' and at least 1 if COMPZ='N'.
On entry: if COMPZ='V', the matrix Z 0. The matrix Z 0 is usually the matrix Z returned by F08WEF (DGGHRD).
If COMPZ='N', Z is not referenced.
On exit: if COMPZ='V', Z contains the matrix product Z Z 0.
If COMPZ='I', Z contains the transformation matrix Z.
17:   LDZ – INTEGERInput
On entry: the first dimension of the array Z as declared in the (sub)program from which F08XEF (DHGEQZ) is called.
Constraints:
  • if COMPZ='V' or 'I', LDZ≥N;
  • if COMPZ='N', LDZ≥1.
18:   WORK max 1,LWORK – REAL (KIND=nag_wp) arrayWorkspace
On exit: if INFO=0, WORK 1 contains the minimum value of LWORK required for optimal performance.
19:   LWORK – INTEGERInput
On entry: the dimension of the array WORK as declared in the (sub)program from which F08XEF (DHGEQZ) is called.
If LWORK=-1, a workspace query is assumed; the routine only calculates the minimum size of the WORK array, returns this value as the first entry of the WORK array, and no error message related to LWORK is issued.
Constraint: LWORK≥max 1,N or LWORK=-1.
20:   INFO – INTEGEROutput
On exit: INFO=0 unless the routine detects an error (see Section 6).

6 Error Indicators and Warnings

INFO<0
If INFO=-i, argument i had an illegal value. An explanatory message is output, and execution of the program is terminated.
INFO>0
If 1≤INFO≤N, the QZ iteration did not converge and the matrix pair A,B is not in the generalized Schur form at exit. However, if INFO<N, then the computed αi and βi should be correct for i=INFO+1,…,N.
If N+1≤INFO≤2×N, the computation of shifts failed and the matrix pair A,B is not in the generalized Schur form at exit. However, if INFO<2×N, then the computed αi and βi should be correct for i=INFO-N+1,…,N.
If INFO>2×N, then an unexpected Library error has occurred. Please contact NAG with details of your program.

7 Accuracy

Please consult Section 4.11 of the LAPACK Users' Guide (see Anderson et al. (1999)) and Chapter 6 of Stewart and Sun (1990), for more information.

8 Parallelism and Performance

F08XEF (DHGEQZ) makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

F08XEF (DHGEQZ) is the fifth step in the solution of the real generalized eigenvalue problem and is called after F08WEF (DGGHRD).
The complex analogue of this routine is F08XSF (ZHGEQZ).

10 Example

This example computes the α and β arguments, which defines the generalized eigenvalues, of the matrix pair A,B given by
A = 1.0 1.0 1.0 1.0 1.0 2.0 4.0 8.0 16.0 32.0 3.0 9.0 27.0 81.0 243.0 4.0 16.0 64.0 256.0 1024.0 5.0 25.0 125.0 625.0 3125.0
B = 1.0 2.0 3.0 4.0 5.0 1.0 4.0 9.0 16.0 25.0 1.0 8.0 27.0 64.0 125.0 1.0 16.0 81.0 256.0 625.0 1.0 32.0 243.0 1024.0 3125.0 .
This requires calls to five routines: F08WHF (DGGBAL) to balance the matrix, F08AEF (DGEQRF) to perform the QR factorization of B, F08AGF (DORMQR) to apply Q to A, F08WEF (DGGHRD) to reduce the matrix pair to the generalized Hessenberg form and F08XEF (DHGEQZ) to compute the eigenvalues using the QZ algorithm.

10.1 Program Text

Program Text (f08xefe.f90)

10.2 Program Data

Program Data (f08xefe.d)

10.3 Program Results

Program Results (f08xefe.r)

F08 Chapter Contents
F08 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F08XNF (ZGGES) : NAG Library, Mark 26

F08 Chapter Contents
F08 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F08XNF (ZGGES)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F08XNF (ZGGES) computes the generalized eigenvalues, the generalized Schur form S,T and, optionally, the left and/or right generalized Schur vectors for a pair of n by n complex nonsymmetric matrices A,B . F08XNF (ZGGES) is marked as deprecated by LAPACK; the replacement routine is F08XQF (ZGGES3) which makes better use of level 3 BLAS.

2 Specification

SUBROUTINE F08XNF ( JOBVSL, JOBVSR, SORT, SELCTG, N, A, LDA, B, LDB, SDIM, ALPHA, BETA, VSL, LDVSL, VSR, LDVSR, WORK, LWORK, RWORK, BWORK, INFO)
INTEGER | N, LDA, LDB, SDIM, LDVSL, LDVSR, LWORK, INFO
REAL (KIND=nag_wp) | RWORK(max(1,8*N))
COMPLEX (KIND=nag_wp) | A(LDA,*), B(LDB,*), ALPHA(N), BETA(N), VSL(LDVSL,*), VSR(LDVSR,*), WORK(max(1,LWORK))
LOGICAL | SELCTG, BWORK(*)
CHARACTER(1) | JOBVSL, JOBVSR, SORT
EXTERNAL | SELCTG
The routine may be called by its LAPACK name zgges.

3 Description

The generalized Schur factorization for a pair of complex matrices A,B is given by
A = QS ZH ,   B = QT ZH ,
where Q and Z are unitary, T and S are upper triangular. The generalized eigenvalues, λ , of A,B are computed from the diagonals of T and S and satisfy
Az = λBz ,
where z is the corresponding generalized eigenvector. λ is actually returned as the pair α,β such that
λ = α/β
since β , or even both α and β can be zero. The columns of Q and Z are the left and right generalized Schur vectors of A,B .
Optionally, F08XNF (ZGGES) can order the generalized eigenvalues on the diagonals of S,T so that selected eigenvalues are at the top left. The leading columns of Q and Z then form an orthonormal basis for the corresponding eigenspaces, the deflating subspaces.
F08XNF (ZGGES) computes T to have real non-negative diagonal entries. The generalized Schur factorization, before reordering, is computed by the QZ algorithm.

4 References

Anderson E, Bai Z, Bischof C, Blackford S, Demmel J, Dongarra J J, Du Croz J J, Greenbaum A, Hammarling S, McKenney A and Sorensen D (1999) LAPACK Users' Guide (3rd Edition) SIAM, Philadelphia http://www.netlib.org/lapack/lug
Golub G H and Van Loan C F (1996) Matrix Computations (3rd Edition) Johns Hopkins University Press, Baltimore

5 Arguments

1:   JOBVSL – CHARACTER(1)Input
On entry: if JOBVSL='N', do not compute the left Schur vectors.
If JOBVSL='V', compute the left Schur vectors.
Constraint: JOBVSL='N' or 'V'.
2:   JOBVSR – CHARACTER(1)Input
On entry: if JOBVSR='N', do not compute the right Schur vectors.
If JOBVSR='V', compute the right Schur vectors.
Constraint: JOBVSR='N' or 'V'.
3:   SORT – CHARACTER(1)Input
On entry: specifies whether or not to order the eigenvalues on the diagonal of the generalized Schur form.
SORT='N'
Eigenvalues are not ordered.
SORT='S'
Eigenvalues are ordered (see SELCTG).
Constraint: SORT='N' or 'S'.
4:   SELCTG – LOGICAL FUNCTION, supplied by the user.External Procedure
If SORT='S', SELCTG is used to select generalized eigenvalues to be moved to the top left of the generalized Schur form.
If SORT='N', SELCTG is not referenced by F08XNF (ZGGES), and may be called with the dummy function F08XNZ.
The specification of SELCTG is:
FUNCTION SELCTG ( A, B)
LOGICAL SELCTG
COMPLEX (KIND=nag_wp) A, B
1:   A – COMPLEX (KIND=nag_wp)Input
2:   B – COMPLEX (KIND=nag_wp)Input
On entry: an eigenvalue A j / B j is selected if SELCTG A j,B j is .TRUE..
Note that in the ill-conditioned case, a selected generalized eigenvalue may no longer satisfy SELCTG A j,B j=.TRUE. after ordering. INFO=N+2 in this case.
SELCTG must either be a module subprogram USEd by, or declared as EXTERNAL in, the (sub)program from which F08XNF (ZGGES) is called. Arguments denoted as Input must not be changed by this procedure.
5:   N – INTEGERInput
On entry: n, the order of the matrices A and B.
Constraint: N≥0.
6:   A LDA* – COMPLEX (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array A must be at least max 1,N.
On entry: the first of the pair of matrices, A.
On exit: A has been overwritten by its generalized Schur form S.
7:   LDA – INTEGERInput
On entry: the first dimension of the array A as declared in the (sub)program from which F08XNF (ZGGES) is called.
Constraint: LDA≥max 1,N.
8:   B LDB* – COMPLEX (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array B must be at least max 1,N.
On entry: the second of the pair of matrices, B.
On exit: B has been overwritten by its generalized Schur form T.
9:   LDB – INTEGERInput
On entry: the first dimension of the array B as declared in the (sub)program from which F08XNF (ZGGES) is called.
Constraint: LDB≥max 1,N.
10:   SDIM – INTEGEROutput
On exit: if SORT='N', SDIM=0.
If SORT='S', SDIM= number of eigenvalues (after sorting) for which SELCTG is .TRUE..
11:   ALPHA N – COMPLEX (KIND=nag_wp) arrayOutput
On exit: see the description of BETA.
12:   BETA N – COMPLEX (KIND=nag_wp) arrayOutput
On exit: ALPHA j/BETA j, for j=1,2,…,N, will be the generalized eigenvalues. ALPHA j, for j=1,2,…,N and BETA j, for j=1,2,…,N, are the diagonals of the complex Schur form A,B output by F08XNF (ZGGES). The BETA j will be non-negative real.
Note: the quotients ALPHA j/BETA j may easily overflow or underflow, and BETA j may even be zero. Thus, you should avoid naively computing the ratio α/β. However, ALPHA will always be less than and usually comparable with A 2 in magnitude, and BETA will always be less than and usually comparable with B 2.
13:   VSL LDVSL* – COMPLEX (KIND=nag_wp) arrayOutput
Note: the second dimension of the array VSL must be at least max 1,N if JOBVSL='V', and at least 1 otherwise.
On exit: if JOBVSL='V', VSL will contain the left Schur vectors, Q.
If JOBVSL='N', VSL is not referenced.
14:   LDVSL – INTEGERInput
On entry: the first dimension of the array VSL as declared in the (sub)program from which F08XNF (ZGGES) is called.
Constraints:
  • if JOBVSL='V', LDVSL≥ max 1,N ;
  • otherwise LDVSL≥1.
15:   VSR LDVSR* – COMPLEX (KIND=nag_wp) arrayOutput
Note: the second dimension of the array VSR must be at least max 1,N if JOBVSR='V', and at least 1 otherwise.
On exit: if JOBVSR='V', VSR will contain the right Schur vectors, Z.
If JOBVSR='N', VSR is not referenced.
16:   LDVSR – INTEGERInput
On entry: the first dimension of the array VSR as declared in the (sub)program from which F08XNF (ZGGES) is called.
Constraints:
  • if JOBVSR='V', LDVSR≥ max 1,N ;
  • otherwise LDVSR≥1.
17:   WORK max 1,LWORK – COMPLEX (KIND=nag_wp) arrayWorkspace
On exit: if INFO=0, the real part of WORK 1 contains the minimum value of LWORK required for optimal performance.
18:   LWORK – INTEGERInput
On entry: the dimension of the array WORK as declared in the (sub)program from which F08XNF (ZGGES) is called.
If LWORK=-1, a workspace query is assumed; the routine only calculates the optimal size of the WORK array, returns this value as the first entry of the WORK array, and no error message related to LWORK is issued.
Suggested value: for optimal performance, LWORK must generally be larger than the minimum, say 2×N+nb×N , where nb is the optimal block size for F08NSF (ZGEHRD).
Constraint: LWORK≥max 1,2×N.
19:   RWORK max 1,8×N – REAL (KIND=nag_wp) arrayWorkspace
20:   BWORK* – LOGICAL arrayWorkspace
Note: the dimension of the array BWORK must be at least 1 if SORT='N', and at least max 1,N otherwise.
If SORT='N', BWORK is not referenced.
21:   INFO – INTEGEROutput
On exit: INFO=0 unless the routine detects an error (see Section 6).

6 Error Indicators and Warnings

INFO<0
If INFO=-i, argument i had an illegal value. An explanatory message is output, and execution of the program is terminated.
INFO=1 to N
The QZ iteration failed. A,B are not in Schur form, but ALPHA j and BETA j should be correct for j=INFO+1,…,N.
INFO=N+1
Unexpected error returned from F08XSF (ZHGEQZ).
INFO=N+2
After reordering, roundoff changed values of some complex eigenvalues so that leading eigenvalues in the generalized Schur form no longer satisfy SELCTG=.TRUE.. This could also be caused by underflow due to scaling.
INFO=N+3
The eigenvalues could not be reordered because some eigenvalues were too close to separate (the problem is very ill-conditioned).

7 Accuracy

The computed generalized Schur factorization satisfies
A+E = QS ZH ,   B+F = QT ZH ,
where
E,F F = O ε A,B F
and ε is the machine precision. See Section 4.11 of Anderson et al. (1999) for further details.

8 Parallelism and Performance

F08XNF (ZGGES) is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
F08XNF (ZGGES) makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The total number of floating-point operations is proportional to n 3.
The real analogue of this routine is F08XAF (DGGES).

10 Example

This example finds the generalized Schur factorization of the matrix pair A,B, where
A = -21.10-22.50 i 53.50-50.50 i -34.50+127.50 i 7.50+0 0.50 i -0.46-0 7.78 i -3.50-37.50 i -15.50+0 58.50 i -10.50-0 1.50 i 4.30-0 5.50 i 39.70-17.10 i -68.50+0 12.50 i -7.50-0 3.50 i 5.50+0 4.40 i 14.40+43.30 i -32.50-0 46.00 i -19.00-32.50 i
and
B = 1.00-5.00 i 1.60+1.20 i -3.00+0.00 i 0.00-1.00 i 0.80-0.60 i 3.00-5.00 i -4.00+3.00 i -2.40-3.20 i 1.00+0.00 i 2.40+1.80 i -4.00-5.00 i 0.00-3.00 i 0.00+1.00 i -1.80+2.40 i 0.00-4.00 i 4.00-5.00 i .
Note that the block size (NB) of 64 assumed in this example is not realistic for such a small problem, but should be suitable for large problems.

10.1 Program Text

Program Text (f08xnfe.f90)

10.2 Program Data

Program Data (f08xnfe.d)

10.3 Program Results

Program Results (f08xnfe.r)

F08 Chapter Contents
F08 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F08XPF (ZGGESX) : NAG Library, Mark 26

F08 Chapter Contents
F08 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F08XPF (ZGGESX)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F08XPF (ZGGESX) computes the generalized eigenvalues, the generalized Schur form S,T and, optionally, the left and/or right generalized Schur vectors for a pair of n by n complex nonsymmetric matrices A,B .
Estimates of condition numbers for selected generalized eigenvalue clusters and Schur vectors are also computed.

2 Specification

SUBROUTINE F08XPF ( JOBVSL, JOBVSR, SORT, SELCTG, SENSE, N, A, LDA, B, LDB, SDIM, ALPHA, BETA, VSL, LDVSL, VSR, LDVSR, RCONDE, RCONDV, WORK, LWORK, RWORK, IWORK, LIWORK, BWORK, INFO)
INTEGER | N, LDA, LDB, SDIM, LDVSL, LDVSR, LWORK, IWORK(max(1,LIWORK)), LIWORK, INFO
REAL (KIND=nag_wp) | RCONDE(2), RCONDV(2), RWORK(max(1,8*N))
COMPLEX (KIND=nag_wp) | A(LDA,*), B(LDB,*), ALPHA(N), BETA(N), VSL(LDVSL,*), VSR(LDVSR,*), WORK(max(1,LWORK))
LOGICAL | SELCTG, BWORK(*)
CHARACTER(1) | JOBVSL, JOBVSR, SORT, SENSE
EXTERNAL | SELCTG
The routine may be called by its LAPACK name zggesx.

3 Description

The generalized Schur factorization for a pair of complex matrices A,B is given by
A = QS ZH ,   B = QT ZH ,
where Q and Z are unitary, T and S are upper triangular. The generalized eigenvalues, λ , of A,B are computed from the diagonals of T and S and satisfy
Az = λBz ,
where z is the corresponding generalized eigenvector. λ is actually returned as the pair α,β such that
λ = α/β
since β , or even both α and β can be zero. The columns of Q and Z are the left and right generalized Schur vectors of A,B .
Optionally, F08XPF (ZGGESX) can order the generalized eigenvalues on the diagonals of S,T so that selected eigenvalues are at the top left. The leading columns of Q and Z then form an orthonormal basis for the corresponding eigenspaces, the deflating subspaces.
F08XPF (ZGGESX) computes T to have real non-negative diagonal entries. The generalized Schur factorization, before reordering, is computed by the QZ algorithm.
The reciprocals of the condition estimates, the reciprocal values of the left and right projection norms, are returned in RCONDE 1 and RCONDE 2 respectively, for the selected generalized eigenvalues, together with reciprocal condition estimates for the corresponding left and right deflating subspaces, in RCONDV 1 and RCONDV 2 . See Section 4.11 of Anderson et al. (1999) for further information.

4 References

Anderson E, Bai Z, Bischof C, Blackford S, Demmel J, Dongarra J J, Du Croz J J, Greenbaum A, Hammarling S, McKenney A and Sorensen D (1999) LAPACK Users' Guide (3rd Edition) SIAM, Philadelphia http://www.netlib.org/lapack/lug
Golub G H and Van Loan C F (1996) Matrix Computations (3rd Edition) Johns Hopkins University Press, Baltimore

5 Arguments

1:   JOBVSL – CHARACTER(1)Input
On entry: if JOBVSL='N', do not compute the left Schur vectors.
If JOBVSL='V', compute the left Schur vectors.
Constraint: JOBVSL='N' or 'V'.
2:   JOBVSR – CHARACTER(1)Input
On entry: if JOBVSR='N', do not compute the right Schur vectors.
If JOBVSR='V', compute the right Schur vectors.
Constraint: JOBVSR='N' or 'V'.
3:   SORT – CHARACTER(1)Input
On entry: specifies whether or not to order the eigenvalues on the diagonal of the generalized Schur form.
SORT='N'
Eigenvalues are not ordered.
SORT='S'
Eigenvalues are ordered (see SELCTG).
Constraint: SORT='N' or 'S'.
4:   SELCTG – LOGICAL FUNCTION, supplied by the user.External Procedure
If SORT='S', SELCTG is used to select generalized eigenvalues to be moved to the top left of the generalized Schur form.
If SORT='N', SELCTG is not referenced by F08XPF (ZGGESX), and may be called with the dummy function F08XNZ.
The specification of SELCTG is:
FUNCTION SELCTG ( A, B)
LOGICAL SELCTG
COMPLEX (KIND=nag_wp) A, B
1:   A – COMPLEX (KIND=nag_wp)Input
2:   B – COMPLEX (KIND=nag_wp)Input
On entry: an eigenvalue A j / B j is selected if SELCTG A j,B j is .TRUE..
Note that in the ill-conditioned case, a selected generalized eigenvalue may no longer satisfy SELCTG A j,B j=.TRUE. after ordering. INFO=N+2 in this case.
SELCTG must either be a module subprogram USEd by, or declared as EXTERNAL in, the (sub)program from which F08XPF (ZGGESX) is called. Arguments denoted as Input must not be changed by this procedure.
5:   SENSE – CHARACTER(1)Input
On entry: determines which reciprocal condition numbers are computed.
SENSE='N'
None are computed.
SENSE='E'
Computed for average of selected eigenvalues only.
SENSE='V'
Computed for selected deflating subspaces only.
SENSE='B'
Computed for both.
If SENSE='E', 'V' or 'B', SORT='S'.
Constraint: SENSE='N', 'E', 'V' or 'B'.
6:   N – INTEGERInput
On entry: n, the order of the matrices A and B.
Constraint: N≥0.
7:   A LDA* – COMPLEX (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array A must be at least max 1,N.
On entry: the first of the pair of matrices, A.
On exit: A has been overwritten by its generalized Schur form S.
8:   LDA – INTEGERInput
On entry: the first dimension of the array A as declared in the (sub)program from which F08XPF (ZGGESX) is called.
Constraint: LDA≥max 1,N.
9:   B LDB* – COMPLEX (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array B must be at least max 1,N.
On entry: the second of the pair of matrices, B.
On exit: B has been overwritten by its generalized Schur form T.
10:   LDB – INTEGERInput
On entry: the first dimension of the array B as declared in the (sub)program from which F08XPF (ZGGESX) is called.
Constraint: LDB≥max 1,N.
11:   SDIM – INTEGEROutput
On exit: if SORT='N', SDIM=0.
If SORT='S', SDIM= number of eigenvalues (after sorting) for which SELCTG is .TRUE..
12:   ALPHA N – COMPLEX (KIND=nag_wp) arrayOutput
On exit: see the description of BETA.
13:   BETA N – COMPLEX (KIND=nag_wp) arrayOutput
On exit: ALPHA j/BETA j, for j=1,2,…,N, will be the generalized eigenvalues. ALPHA j and BETA j,j=1,2,…,N are the diagonals of the complex Schur form S,T. BETA j will be non-negative real.
Note: the quotients ALPHA j/BETA j may easily overflow or underflow, and BETA j may even be zero. Thus, you should avoid naively computing the ratio α/β. However, ALPHA will always be less than and usually comparable with A in magnitude, and BETA will always be less than and usually comparable with B.
14:   VSL LDVSL* – COMPLEX (KIND=nag_wp) arrayOutput
Note: the second dimension of the array VSL must be at least max 1,N if JOBVSL='V', and at least 1 otherwise.
On exit: if JOBVSL='V', VSL will contain the left Schur vectors, Q.
If JOBVSL='N', VSL is not referenced.
15:   LDVSL – INTEGERInput
On entry: the first dimension of the array VSL as declared in the (sub)program from which F08XPF (ZGGESX) is called.
Constraints:
  • if JOBVSL='V', LDVSL≥ max 1,N ;
  • otherwise LDVSL≥1.
16:   VSR LDVSR* – COMPLEX (KIND=nag_wp) arrayOutput
Note: the second dimension of the array VSR must be at least max 1,N if JOBVSR='V', and at least 1 otherwise.
On exit: if JOBVSR='V', VSR will contain the right Schur vectors, Z.
If JOBVSR='N', VSR is not referenced.
17:   LDVSR – INTEGERInput
On entry: the first dimension of the array VSR as declared in the (sub)program from which F08XPF (ZGGESX) is called.
Constraints:
  • if JOBVSR='V', LDVSR≥ max 1,N ;
  • otherwise LDVSR≥1.
18:   RCONDE 2 – REAL (KIND=nag_wp) arrayOutput
On exit: if SENSE='E' or 'B', RCONDE 1 and RCONDE 2 contain the reciprocal condition numbers for the average of the selected eigenvalues.
If SENSE='N' or 'V', RCONDE is not referenced.
19:   RCONDV 2 – REAL (KIND=nag_wp) arrayOutput
On exit: if SENSE='V' or 'B', RCONDV 1 and RCONDV 2 contain the reciprocal condition numbers for the selected deflating subspaces.
if SENSE='N' or 'E', RCONDV is not referenced.
20:   WORK max 1,LWORK – COMPLEX (KIND=nag_wp) arrayWorkspace
On exit: if INFO=0, the real part of WORK 1 contains a bound on the value of LWORK required for optimal performance.
21:   LWORK – INTEGERInput
On entry: the dimension of the array WORK as declared in the (sub)program from which F08XPF (ZGGESX) is called.
If LWORK=-1, a workspace query is assumed; the routine only calculates the bound on the optimal size of the WORK array and the minimum size of the IWORK array, returns these values as the first entries of the WORK and IWORK arrays, and no error message related to LWORK or LIWORK is issued.
Constraints:
  • if N=0, LWORK≥1;
  • if SENSE='E', 'V' or 'B', LWORK≥ max 1,2×N,2×SDIM×N-SDIM ;
  • otherwise LWORK≥ max 1,2×N .
Note: 2×SDIM×N-SDIM≤N×N/2. Note also that an error is only returned if LWORK < max 1,2×N , but if SENSE='E', 'V' or 'B' this may not be large enough. Consider increasing LWORK by nb, where nb is the optimal block size.
22:   RWORK max 1,8×N – REAL (KIND=nag_wp) arrayWorkspace
Real workspace.
23:   IWORK max 1,LIWORK – INTEGER arrayWorkspace
On exit: if INFO=0, IWORK 1 returns the minimum LIWORK.
24:   LIWORK – INTEGERInput
On entry: the dimension of the array IWORK as declared in the (sub)program from which F08XPF (ZGGESX) is called.
If LIWORK=-1, a workspace query is assumed; the routine only calculates the bound on the optimal size of the WORK array and the minimum size of the IWORK array, returns these values as the first entries of the WORK and IWORK arrays, and no error message related to LWORK or LIWORK is issued.
Constraints:
  • if SENSE='N' or N=0, LIWORK≥1;
  • otherwise LIWORK≥N+2.
25:   BWORK* – LOGICAL arrayWorkspace
Note: the dimension of the array BWORK must be at least 1 if SORT='N', and at least max 1,N otherwise.
If SORT='N', BWORK is not referenced.
26:   INFO – INTEGEROutput
On exit: INFO=0 unless the routine detects an error (see Section 6).

6 Error Indicators and Warnings

INFO<0
If INFO=-i, argument i had an illegal value. An explanatory message is output, and execution of the program is terminated.
INFO=1 to N
The QZ iteration failed. A,B are not in Schur form, but ALPHA j and BETA j should be correct for j=INFO+1,…,N.
INFO=N+1
Unexpected error returned from F08XSF (ZHGEQZ).
INFO=N+2
After reordering, roundoff changed values of some complex eigenvalues so that leading eigenvalues in the generalized Schur form no longer satisfy SELCTG=.TRUE.. This could also be caused by underflow due to scaling.
INFO=N+3
The eigenvalues could not be reordered because some eigenvalues were too close to separate (the problem is very ill-conditioned).

7 Accuracy

The computed generalized Schur factorization satisfies
A+E = QS ZT ,   B+F = QT ZT ,
where
E,F F = O ε A,B F
and ε is the machine precision. See Section 4.11 of Anderson et al. (1999) for further details.

8 Parallelism and Performance

F08XPF (ZGGESX) is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
F08XPF (ZGGESX) makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The total number of floating-point operations is proportional to n 3.
The real analogue of this routine is F08XBF (DGGESX).

10 Example

This example finds the generalized Schur factorization of the matrix pair A,B, where
A = -21.10-22.50 i 53.50-50.50 i -34.50+127.50 i 7.50+0 0.50 i -0.46-0 7.78 i -3.50-37.50 i -15.50+0 58.50 i -10.50-0 1.50 i 4.30-0 5.50 i 39.70-17.10 i -68.50+0 12.50 i -7.50-0 3.50 i 5.50+0 4.40 i 14.40+43.30 i -32.50-0 46.00 i -19.00-32.50 i
and
B = 1.00-5.00 i 1.60+1.20 i -3.00+0.00 i 0.00-1.00 i 0.80-0.60 i 3.00-5.00 i -4.00+3.00 i -2.40-3.20 i 1.00+0.00 i 2.40+1.80 i -4.00-5.00 i 0.00-3.00 i 0.00+1.00 i -1.80+2.40 i 0.00-4.00 i 4.00-5.00 i ,
such that the eigenvalues of A,B for which λ<6 correspond to the top left diagonal elements of the generalized Schur form, S,T. Estimates of the condition numbers for the selected eigenvalue cluster and corresponding deflating subspaces are also returned.
Note that the block size (NB) of 64 assumed in this example is not realistic for such a small problem, but should be suitable for large problems.

10.1 Program Text

Program Text (f08xpfe.f90)

10.2 Program Data

Program Data (f08xpfe.d)

10.3 Program Results

Program Results (f08xpfe.r)

F08 Chapter Contents
F08 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F08XQF (ZGGES3) : NAG Library, Mark 26

F08 Chapter Contents
F08 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F08XQF (ZGGES3)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F08XQF (ZGGES3) computes the generalized eigenvalues, the generalized Schur form S,T and, optionally, the left and/or right generalized Schur vectors for a pair of n by n complex nonsymmetric matrices A,B .

2 Specification

SUBROUTINE F08XQF ( JOBVSL, JOBVSR, SORT, SELCTG, N, A, LDA, B, LDB, SDIM, ALPHA, BETA, VSL, LDVSL, VSR, LDVSR, WORK, LWORK, RWORK, BWORK, INFO)
INTEGER | N, LDA, LDB, SDIM, LDVSL, LDVSR, LWORK, INFO
REAL (KIND=nag_wp) | RWORK(max(1,8*N))
COMPLEX (KIND=nag_wp) | A(LDA,*), B(LDB,*), ALPHA(N), BETA(N), VSL(LDVSL,*), VSR(LDVSR,*), WORK(max(1,LWORK))
LOGICAL | SELCTG, BWORK(*)
CHARACTER(1) | JOBVSL, JOBVSR, SORT
EXTERNAL | SELCTG
The routine may be called by its LAPACK name zgges3.

3 Description

The generalized Schur factorization for a pair of complex matrices A,B is given by
A = QS ZH ,   B = QT ZH ,
where Q and Z are unitary, T and S are upper triangular. The generalized eigenvalues, λ , of A,B are computed from the diagonals of T and S and satisfy
Az = λBz ,
where z is the corresponding generalized eigenvector. λ is actually returned as the pair α,β such that
λ = α/β
since β , or even both α and β can be zero. The columns of Q and Z are the left and right generalized Schur vectors of A,B .
Optionally, F08XQF (ZGGES3) can order the generalized eigenvalues on the diagonals of S,T so that selected eigenvalues are at the top left. The leading columns of Q and Z then form an orthonormal basis for the corresponding eigenspaces, the deflating subspaces.
F08XQF (ZGGES3) computes T to have real non-negative diagonal entries. The generalized Schur factorization, before reordering, is computed by the QZ algorithm.

4 References

Anderson E, Bai Z, Bischof C, Blackford S, Demmel J, Dongarra J J, Du Croz J J, Greenbaum A, Hammarling S, McKenney A and Sorensen D (1999) LAPACK Users' Guide (3rd Edition) SIAM, Philadelphia http://www.netlib.org/lapack/lug
Golub G H and Van Loan C F (2012) Matrix Computations (4th Edition) Johns Hopkins University Press, Baltimore

5 Arguments

1:   JOBVSL – CHARACTER(1)Input
On entry: if JOBVSL='N', do not compute the left Schur vectors.
If JOBVSL='V', compute the left Schur vectors.
Constraint: JOBVSL='N' or 'V'.
2:   JOBVSR – CHARACTER(1)Input
On entry: if JOBVSR='N', do not compute the right Schur vectors.
If JOBVSR='V', compute the right Schur vectors.
Constraint: JOBVSR='N' or 'V'.
3:   SORT – CHARACTER(1)Input
On entry: specifies whether or not to order the eigenvalues on the diagonal of the generalized Schur form.
SORT='N'
Eigenvalues are not ordered.
SORT='S'
Eigenvalues are ordered (see SELCTG).
Constraint: SORT='N' or 'S'.
4:   SELCTG – LOGICAL FUNCTION, supplied by the user.External Procedure
If SORT='S', SELCTG is used to select generalized eigenvalues to be moved to the top left of the generalized Schur form.
If SORT='N', SELCTG is not referenced by F08XQF (ZGGES3), and may be called with the dummy function F08XNZ.
The specification of SELCTG is:
FUNCTION SELCTG ( A, B)
LOGICAL SELCTG
COMPLEX (KIND=nag_wp) A, B
1:   A – COMPLEX (KIND=nag_wp)Input
2:   B – COMPLEX (KIND=nag_wp)Input
On entry: an eigenvalue A j / B j is selected if SELCTG A j,B j is .TRUE..
Note that in the ill-conditioned case, a selected generalized eigenvalue may no longer satisfy SELCTG A j,B j=.TRUE. after ordering. INFO=N+2 in this case.
SELCTG must either be a module subprogram USEd by, or declared as EXTERNAL in, the (sub)program from which F08XQF (ZGGES3) is called. Arguments denoted as Input must not be changed by this procedure.
5:   N – INTEGERInput
On entry: n, the order of the matrices A and B.
Constraint: N≥0.
6:   A LDA* – COMPLEX (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array A must be at least max 1,N.
On entry: the first of the pair of matrices, A.
On exit: A has been overwritten by its generalized Schur form S.
7:   LDA – INTEGERInput
On entry: the first dimension of the array A as declared in the (sub)program from which F08XQF (ZGGES3) is called.
Constraint: LDA≥max 1,N.
8:   B LDB* – COMPLEX (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array B must be at least max 1,N.
On entry: the second of the pair of matrices, B.
On exit: B has been overwritten by its generalized Schur form T.
9:   LDB – INTEGERInput
On entry: the first dimension of the array B as declared in the (sub)program from which F08XQF (ZGGES3) is called.
Constraint: LDB≥max 1,N.
10:   SDIM – INTEGEROutput
On exit: if SORT='N', SDIM=0.
If SORT='S', SDIM= number of eigenvalues (after sorting) for which SELCTG is .TRUE..
11:   ALPHA N – COMPLEX (KIND=nag_wp) arrayOutput
On exit: see the description of BETA.
12:   BETA N – COMPLEX (KIND=nag_wp) arrayOutput
On exit: ALPHA j/BETA j, for j=1,2,…,N, will be the generalized eigenvalues. ALPHA j, for j=1,2,…,N and BETA j, for j=1,2,…,N, are the diagonals of the complex Schur form A,B output by F08XQF (ZGGES3). The BETA j will be non-negative real.
Note: the quotients ALPHA j/BETA j may easily overflow or underflow, and BETA j may even be zero. Thus, you should avoid naively computing the ratio α/β. However, ALPHA will always be less than and usually comparable with A 2 in magnitude, and BETA will always be less than and usually comparable with B 2.
13:   VSL LDVSL* – COMPLEX (KIND=nag_wp) arrayOutput
Note: the second dimension of the array VSL must be at least max 1,N if JOBVSL='V', and at least 1 otherwise.
On exit: if JOBVSL='V', VSL will contain the left Schur vectors, Q.
If JOBVSL='N', VSL is not referenced.
14:   LDVSL – INTEGERInput
On entry: the first dimension of the array VSL as declared in the (sub)program from which F08XQF (ZGGES3) is called.
Constraints:
  • if JOBVSL='V', LDVSL≥ max 1,N ;
  • otherwise LDVSL≥1.
15:   VSR LDVSR* – COMPLEX (KIND=nag_wp) arrayOutput
Note: the second dimension of the array VSR must be at least max 1,N if JOBVSR='V', and at least 1 otherwise.
On exit: if JOBVSR='V', VSR will contain the right Schur vectors, Z.
If JOBVSR='N', VSR is not referenced.
16:   LDVSR – INTEGERInput
On entry: the first dimension of the array VSR as declared in the (sub)program from which F08XQF (ZGGES3) is called.
Constraints:
  • if JOBVSR='V', LDVSR≥ max 1,N ;
  • otherwise LDVSR≥1.
17:   WORK max 1,LWORK – COMPLEX (KIND=nag_wp) arrayWorkspace
On exit: if INFO=0, the real part of WORK 1 contains the minimum value of LWORK required for optimal performance.
18:   LWORK – INTEGERInput
On entry: the dimension of the array WORK as declared in the (sub)program from which F08XQF (ZGGES3) is called.
If LWORK=-1, a workspace query is assumed; the routine only calculates the optimal size of the WORK array, returns this value as the first entry of the WORK array, and no error message related to LWORK is issued.
Suggested value: for optimal performance, LWORK must generally be larger than the minimum, say 2×N+nb×N×6, where nb is the optimal block size for F08WTF (ZGGHD3).
Constraint: LWORK≥max 1,2×N.
19:   RWORK max 1,8×N – REAL (KIND=nag_wp) arrayWorkspace
20:   BWORK* – LOGICAL arrayWorkspace
Note: the dimension of the array BWORK must be at least 1 if SORT='N', and at least max 1,N otherwise.
If SORT='N', BWORK is not referenced.
21:   INFO – INTEGEROutput
On exit: INFO=0 unless the routine detects an error (see Section 6).

6 Error Indicators and Warnings

INFO<0
If INFO=-i, argument i had an illegal value. An explanatory message is output, and execution of the program is terminated.
INFO=1 to N
The QZ iteration did not converge and the matrix pair A,B is not in the generalized Schur form. The computed αi and βi should be correct for i=value,…,value.
INFO=N+1
The QZ iteration failed with an unexpected error, please contact NAG.
INFO=N+2
After reordering, roundoff changed values of some complex eigenvalues so that leading eigenvalues in the generalized Schur form no longer satisfy SELCTG=.TRUE.. This could also be caused by underflow due to scaling.
INFO=N+3
The eigenvalues could not be reordered because some eigenvalues were too close to separate (the problem is very ill-conditioned).

7 Accuracy

The computed generalized Schur factorization satisfies
A+E = QS ZH ,   B+F = QT ZH ,
where
E,F F = O ε A,B F
and ε is the machine precision. See Section 4.11 of Anderson et al. (1999) for further details.

8 Parallelism and Performance

F08XQF (ZGGES3) is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
F08XQF (ZGGES3) makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The total number of floating-point operations is proportional to n 3.
The real analogue of this routine is F08XCF (DGGES3).

10 Example

This example finds the generalized Schur factorization of the matrix pair A,B, where
A = -21.10-22.50 i 53.50-50.50 i -34.50+127.50 i 7.50+0 0.50 i -0.46-0 7.78 i -3.50-37.50 i -15.50+0 58.50 i -10.50-0 1.50 i 4.30-0 5.50 i 39.70-17.10 i -68.50+0 12.50 i -7.50-0 3.50 i 5.50+0 4.40 i 14.40+43.30 i -32.50-0 46.00 i -19.00-32.50 i
and
B = 1.00-5.00 i 1.60+1.20 i -3.00+0.00 i 0.00-1.00 i 0.80-0.60 i 3.00-5.00 i -4.00+3.00 i -2.40-3.20 i 1.00+0.00 i 2.40+1.80 i -4.00-5.00 i 0.00-3.00 i 0.00+1.00 i -1.80+2.40 i 0.00-4.00 i 4.00-5.00 i .

10.1 Program Text

Program Text (f08xqfe.f90)

10.2 Program Data

Program Data (f08xqfe.d)

10.3 Program Results

Program Results (f08xqfe.r)

F08 Chapter Contents
F08 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F08XSF (ZHGEQZ) : NAG Library, Mark 26

F08 Chapter Contents
F08 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F08XSF (ZHGEQZ)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F08XSF (ZHGEQZ) implements the QZ method for finding generalized eigenvalues of the complex matrix pair A,B of order n, which is in the generalized upper Hessenberg form.

2 Specification

SUBROUTINE F08XSF ( JOB, COMPQ, COMPZ, N, ILO, IHI, A, LDA, B, LDB, ALPHA, BETA, Q, LDQ, Z, LDZ, WORK, LWORK, RWORK, INFO)
INTEGER | N, ILO, IHI, LDA, LDB, LDQ, LDZ, LWORK, INFO
REAL (KIND=nag_wp) | RWORK(N)
COMPLEX (KIND=nag_wp) | A(LDA,*), B(LDB,*), ALPHA(N), BETA(N), Q(LDQ,*), Z(LDZ,*), WORK(max(1,LWORK))
CHARACTER(1) | JOB, COMPQ, COMPZ
The routine may be called by its LAPACK name zhgeqz.

3 Description

F08XSF (ZHGEQZ) implements a single-shift version of the QZ method for finding the generalized eigenvalues of the complex matrix pair A,B which is in the generalized upper Hessenberg form. If the matrix pair A,B is not in the generalized upper Hessenberg form, then the routine F08WSF (ZGGHRD) should be called before invoking F08XSF (ZHGEQZ).
This problem is mathematically equivalent to solving the matrix equation
det A-λB=0.
Note that, to avoid underflow, overflow and other arithmetic problems, the generalized eigenvalues λj are never computed explicitly by this routine but defined as ratios between two computed values, αj and βj:
λj=αj/βj.
The arguments αj, in general, are finite complex values and βj are finite real non-negative values.
If desired, the matrix pair A,B may be reduced to generalized Schur form. That is, the transformed matrices A and B are upper triangular and the diagonal values of A and B provide α and β.
The argument JOB specifies two options. If JOB='S' then the matrix pair A,B is simultaneously reduced to Schur form by applying one unitary transformation (usually called Q) on the left and another (usually called Z) on the right. That is,
A←QH AZ B←QH BZ
If JOB='E', then at each iteration the same transformations are computed but they are only applied to those parts of A and B which are needed to compute α and β. This option could be used if generalized eigenvalues are required but not generalized eigenvectors.
If JOB='S' and COMPQ='V' or 'I', and COMPZ='V' or 'I', then the unitary transformations used to reduce the pair A,B are accumulated into the input arrays Q and Z. If generalized eigenvectors are required then JOB must be set to JOB='S' and if left (right) generalized eigenvectors are to be computed then COMPQ (COMPZ) must be set to COMPQ='V' or 'I' rather than COMPQ='N'.
If COMPQ='I', then eigenvectors are accumulated on the identity matrix and on exit the array Q contains the left eigenvector matrix Q. However, if COMPQ='V' then the transformations are accumulated in the user-supplied matrix Q 0 in array Q on entry and thus on exit Q contains the matrix product Q Q 0. A similar convention is used for COMPZ.

4 References

Anderson E, Bai Z, Bischof C, Blackford S, Demmel J, Dongarra J J, Du Croz J J, Greenbaum A, Hammarling S, McKenney A and Sorensen D (1999) LAPACK Users' Guide (3rd Edition) SIAM, Philadelphia
Golub G H and Van Loan C F (1996) Matrix Computations (3rd Edition) Johns Hopkins University Press, Baltimore
Moler C B and Stewart G W (1973) An algorithm for generalized matrix eigenproblems SIAM J. Numer. Anal. 10 241–256
Stewart G W and Sun J-G (1990) Matrix Perturbation Theory Academic Press, London

5 Arguments

1:   JOB – CHARACTER(1)Input
On entry: specifies the operations to be performed on A,B.
JOB='E'
The matrix pair A,B on exit might not be in the generalized Schur form.
JOB='S'
The matrix pair A,B on exit will be in the generalized Schur form.
Constraint: JOB='E' or 'S'.
2:   COMPQ – CHARACTER(1)Input
On entry: specifies the operations to be performed on Q:
COMPQ='N'
The array Q is unchanged.
COMPQ='V'
The left transformation Q is accumulated on the array Q.
COMPQ='I'
The array Q is initialized to the identity matrix before the left transformation Q is accumulated in Q.
Constraint: COMPQ='N', 'V' or 'I'.
3:   COMPZ – CHARACTER(1)Input
On entry: specifies the operations to be performed on Z.
COMPZ='N'
The array Z is unchanged.
COMPZ='V'
The right transformation Z is accumulated on the array Z.
COMPZ='I'
The array Z is initialized to the identity matrix before the right transformation Z is accumulated in Z.
Constraint: COMPZ='N', 'V' or 'I'.
4:   N – INTEGERInput
On entry: n, the order of the matrices A, B, Q and Z.
Constraint: N≥0.
5:   ILO – INTEGERInput
6:   IHI – INTEGERInput
On entry: the indices ilo and ihi, respectively which define the upper triangular parts of A. The submatrices A 1:ilo-1,1:ilo-1 and A ihi+1:n,ihi+1:n are then upper triangular. These arguments are provided by F08WVF (ZGGBAL) if the matrix pair was previously balanced; otherwise, ILO=1 and IHI=N.
Constraints:
  • if N>0, 1≤ ILO≤ IHI≤ N ;
  • if N=0, ILO=1 and IHI=0.
7:   A LDA* – COMPLEX (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array A must be at least max 1,N.
On entry: the n by n upper Hessenberg matrix A. The elements below the first subdiagonal must be set to zero.
On exit: if JOB='S', the matrix pair A,B will be simultaneously reduced to generalized Schur form.
If JOB='E', the 1 by 1 and 2 by 2 diagonal blocks of the matrix pair A,B will give generalized eigenvalues but the remaining elements will be irrelevant.
8:   LDA – INTEGERInput
On entry: the first dimension of the array A as declared in the (sub)program from which F08XSF (ZHGEQZ) is called.
Constraint: LDA≥max 1,N.
9:   B LDB* – COMPLEX (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array B must be at least max 1,N.
On entry: the n by n upper triangular matrix B. The elements below the diagonal must be zero.
On exit: if JOB='S', the matrix pair A,B will be simultaneously reduced to generalized Schur form.
If JOB='E', the 1 by 1 and 2 by 2 diagonal blocks of the matrix pair A,B will give generalized eigenvalues but the remaining elements will be irrelevant.
10:   LDB – INTEGERInput
On entry: the first dimension of the array B as declared in the (sub)program from which F08XSF (ZHGEQZ) is called.
Constraint: LDB≥max 1,N.
11:   ALPHA N – COMPLEX (KIND=nag_wp) arrayOutput
On exit: αj, for j=1,2,…,n.
12:   BETA N – COMPLEX (KIND=nag_wp) arrayOutput
On exit: βj, for j=1,2,…,n.
13:   Q LDQ* – COMPLEX (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array Q must be at least max 1,N if COMPQ='V' or 'I' and at least 1 if COMPQ='N'.
On entry: if COMPQ='V', the matrix Q 0. The matrix Q 0 is usually the matrix Q returned by F08WSF (ZGGHRD).
If COMPQ='N', Q is not referenced.
On exit: if COMPQ='V', Q contains the matrix product Q Q 0.
If COMPQ='I', Q contains the transformation matrix Q.
14:   LDQ – INTEGERInput
On entry: the first dimension of the array Q as declared in the (sub)program from which F08XSF (ZHGEQZ) is called.
Constraints:
  • if COMPQ='V' or 'I', LDQ≥N;
  • if COMPQ='N', LDQ≥1.
15:   Z LDZ* – COMPLEX (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array Z must be at least max 1,N if COMPZ='V' or 'I' and at least 1 if COMPZ='N'.
On entry: if COMPZ='V', the matrix Z 0. The matrix Z 0 is usually the matrix Z returned by F08WSF (ZGGHRD).
If COMPZ='N', Z is not referenced.
On exit: if COMPZ='V', Z contains the matrix product Z Z 0.
If COMPZ='I', Z contains the transformation matrix Z.
16:   LDZ – INTEGERInput
On entry: the first dimension of the array Z as declared in the (sub)program from which F08XSF (ZHGEQZ) is called.
Constraints:
  • if COMPZ='V' or 'I', LDZ≥N;
  • if COMPZ='N', LDZ≥1.
17:   WORK max 1,LWORK – COMPLEX (KIND=nag_wp) arrayWorkspace
On exit: if INFO=0, the real part of WORK 1 contains the minimum value of LWORK required for optimal performance.
18:   LWORK – INTEGERInput
On entry: the dimension of the array WORK as declared in the (sub)program from which F08XSF (ZHGEQZ) is called.
If LWORK=-1, a workspace query is assumed; the routine only calculates the minimum size of the WORK array, returns this value as the first entry of the WORK array, and no error message related to LWORK is issued.
Constraint: LWORK≥max 1,N or LWORK=-1.
19:   RWORK N – REAL (KIND=nag_wp) arrayWorkspace
20:   INFO – INTEGEROutput
On exit: INFO=0 unless the routine detects an error (see Section 6).

6 Error Indicators and Warnings

INFO<0
If INFO=-i, argument i had an illegal value. An explanatory message is output, and execution of the program is terminated.
INFO>0
If 1≤INFO≤N, the QZ iteration did not converge and the matrix pair A,B is not in the generalized Schur form at exit. However, if INFO<N, then the computed αi and βi should be correct for i=INFO+1,…,N.
If N+1≤INFO≤2×N, the computation of shifts failed and the matrix pair A,B is not in the generalized Schur form at exit. However, if INFO<2×N, then the computed αi and βi should be correct for i=INFO-N+1,…,N.
If INFO>2×N, then an unexpected Library error has occurred. Please contact NAG with details of your program.

7 Accuracy

Please consult Section 4.11 of the LAPACK Users' Guide (see Anderson et al. (1999)) and Chapter 6 of Stewart and Sun (1990), for more information.

8 Parallelism and Performance

F08XSF (ZHGEQZ) makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

F08XSF (ZHGEQZ) is the fifth step in the solution of the complex generalized eigenvalue problem and is called after F08WSF (ZGGHRD).
The number of floating-point operations taken by this routine is proportional to n 3.
The real analogue of this routine is F08XEF (DHGEQZ).

10 Example

This example computes the α and β arguments, which defines the generalized eigenvalues, of the matrix pair A,B given by
A = 1.0+3.0 i 1.0+4.0 i 1.0+5.0 i 1.0+6.0 i 2.0+2.0 i 4.0+3.0 i 8.0+4.0 i 16.0+5.0 i 3.0+1.0 i 9.0+2.0 i 27.0+3.0 i 81.0+4.0 i 4.0+0.0 i 16.0+1.0 i 64.0+2.0 i 256.0+3.0 i
and
B = 1.0+0.0 i 2.0+1.0 i 3.0+2.0 i 4.0+3.0 i 1.0+1.0 i 4.0+2.0 i 9.0+3.0 i 16.0+4.0 i 1.0+2.0 i 8.0+3.0 i 27.0+4.0 i 64.0+5.0 i 1.0+3.0 i 16.0+4.0 i 81.0+5.0 i 256.0+6.0 i .
This requires calls to five routines: F08WVF (ZGGBAL) to balance the matrix, F08ASF (ZGEQRF) to perform the QR factorization of B, F08AUF (ZUNMQR) to apply Q to A, F08WSF (ZGGHRD) to reduce the matrix pair to the generalized Hessenberg form and F08XSF (ZHGEQZ) to compute the eigenvalues using the QZ algorithm.

10.1 Program Text

Program Text (f08xsfe.f90)

10.2 Program Data

Program Data (f08xsfe.d)

10.3 Program Results

Program Results (f08xsfe.r)

F08 Chapter Contents
F08 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F08YEF (DTGSJA) : NAG Library, Mark 26

F08 Chapter Contents
F08 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F08YEF (DTGSJA)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F08YEF (DTGSJA) computes the generalized singular value decomposition (GSVD) of two real upper trapezoidal matrices A and B, where A is an m by n matrix and B is a p by n matrix.
A and B are assumed to be in the form returned by F08VEF (DGGSVP) or F08VGF (DGGSVP3).

2 Specification

SUBROUTINE F08YEF ( JOBU, JOBV, JOBQ, M, P, N, K, L, A, LDA, B, LDB, TOLA, TOLB, ALPHA, BETA, U, LDU, V, LDV, Q, LDQ, WORK, NCYCLE, INFO)
INTEGER | M, P, N, K, L, LDA, LDB, LDU, LDV, LDQ, NCYCLE, INFO
REAL (KIND=nag_wp) | A(LDA,*), B(LDB,*), TOLA, TOLB, ALPHA(N), BETA(N), U(LDU,*), V(LDV,*), Q(LDQ,*), WORK(2*N)
CHARACTER(1) | JOBU, JOBV, JOBQ
The routine may be called by its LAPACK name dtgsja.

3 Description

F08YEF (DTGSJA) computes the GSVD of the matrices A and B which are assumed to have the form as returned by F08VEF (DGGSVP) or F08VGF (DGGSVP3)
A= n-k-lklk0A 12A 13l00A 23m-k-l000() ,   if ​ m-k-l ≥ 0; n-k-lklk0A 12A 13m-k00A 23() ,   if ​ m-k-l < 0 ; B= n-k-lkll00B 13p-l000() ,
where the k by k matrix A 12 and the l by l matrix B 13 are nonsingular upper triangular, A 23 is l by l upper triangular if m-k-l≥0 and is m-k by l upper trapezoidal otherwise.
F08YEF (DTGSJA) computes orthogonal matrices Q, U and V, diagonal matrices D 1 and D 2, and an upper triangular matrix R such that
UT AQ = D 1 0 R ,   VT BQ = D 2 0 R .
Optionally Q, U and V may or may not be computed, or they may be premultiplied by matrices Q 1, U 1 and V 1 respectively.
If m-k-l≥0 then D 1, D 2 and R have the form
D 1= klkI0l0Cm-k-l00() ,
D 2= kll0Sp-l00() ,
R = klkR 11R 12l0R 22() ,
where C=diag α k+1,,,…,,,α k+l,  S=diag β k+1,,,…,,,β k+l.
If m-k-l<0 then D 1, D 2 and R have the form
D 1= km-kk+l-mkI00m-k0C0() ,
D 2= km-kk+l-mm-k0S0k+l-m00Ip-l000() ,
R = km-kk+l-mkR 11R 12R 13m-k0R 22R 23k+l-m00R 33() ,
where C=diag α k+1,,,…,,,αm,  S=diag β k+1,,,…,,,βm.
In both cases the diagonal matrix C has non-negative diagonal elements, the diagonal matrix S has positive diagonal elements, so that S is nonsingular, and C 2+S 2=1. See Section 2.3.5.3 of Anderson et al. (1999) for further information.

4 References

Anderson E, Bai Z, Bischof C, Blackford S, Demmel J, Dongarra J J, Du Croz J J, Greenbaum A, Hammarling S, McKenney A and Sorensen D (1999) LAPACK Users' Guide (3rd Edition) SIAM, Philadelphia http://www.netlib.org/lapack/lug
Golub G H and Van Loan C F (1996) Matrix Computations (3rd Edition) Johns Hopkins University Press, Baltimore

5 Arguments

1:   JOBU – CHARACTER(1)Input
On entry: if JOBU='U', U must contain an orthogonal matrix U 1 on entry, and the product U 1 U is returned.
If JOBU='I', U is initialized to the unit matrix, and the orthogonal matrix U is returned.
If JOBU='N', U is not computed.
Constraint: JOBU='U', 'I' or 'N'.
2:   JOBV – CHARACTER(1)Input
On entry: if JOBV='V', V must contain an orthogonal matrix V 1 on entry, and the product V 1 V is returned.
If JOBV='I', V is initialized to the unit matrix, and the orthogonal matrix V is returned.
If JOBV='N', V is not computed.
Constraint: JOBV='V', 'I' or 'N'.
3:   JOBQ – CHARACTER(1)Input
On entry: if JOBQ='Q', Q must contain an orthogonal matrix Q 1 on entry, and the product Q 1 Q is returned.
If JOBQ='I', Q is initialized to the unit matrix, and the orthogonal matrix Q is returned.
If JOBQ='N', Q is not computed.
Constraint: JOBQ='Q', 'I' or 'N'.
4:   M – INTEGERInput
On entry: m, the number of rows of the matrix A.
Constraint: M≥0.
5:   P – INTEGERInput
On entry: p, the number of rows of the matrix B.
Constraint: P≥0.
6:   N – INTEGERInput
On entry: n, the number of columns of the matrices A and B.
Constraint: N≥0.
7:   K – INTEGERInput
8:   L – INTEGERInput
On entry: K and L specify the sizes, k and l, of the subblocks of A and B, whose GSVD is to be computed by F08YEF (DTGSJA).
9:   A LDA* – REAL (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array A must be at least max 1,N.
On entry: the m by n matrix A.
On exit: if m-k-l≥0, A 1:k+ln-k-l+1:n contains the k+l by k+l upper triangular matrix R.
If m-k-l<0, A 1:mn-k-l+1:n contains the first m rows of the k+l by k+l upper triangular matrix R, and the submatrix R 33 is returned in B m-k+1:ln+m-k-l+1:n .
10:   LDA – INTEGERInput
On entry: the first dimension of the array A as declared in the (sub)program from which F08YEF (DTGSJA) is called.
Constraint: LDA≥max 1,M.
11:   B LDB* – REAL (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array B must be at least max 1,N.
On entry: the p by n matrix B.
On exit: if m-k-l<0 , B m-k+1:ln+m-k-l+1:n contains the submatrix R 33 of R.
12:   LDB – INTEGERInput
On entry: the first dimension of the array B as declared in the (sub)program from which F08YEF (DTGSJA) is called.
Constraint: LDB≥max 1,P.
13:   TOLA – REAL (KIND=nag_wp)Input
14:   TOLB – REAL (KIND=nag_wp)Input
On entry: TOLA and TOLB are the convergence criteria for the Jacobi–Kogbetliantz iteration procedure. Generally, they should be the same as used in the preprocessing step performed by F08VEF (DGGSVP) or F08VGF (DGGSVP3), say
TOLA=max M,N A ε, TOLB=max P,N B ε,
where ε is the machine precision.
15:   ALPHA N – REAL (KIND=nag_wp) arrayOutput
On exit: see the description of BETA.
16:   BETA N – REAL (KIND=nag_wp) arrayOutput
On exit: ALPHA and BETA contain the generalized singular value pairs of A and B;
  • ALPHA i=1 , BETA i=0 , for i=1,2,…,k, and
  • if m-k-l≥0 , ALPHA i=αi , BETA i=βi , for i=k+1,…,k+l, or
  • if m-k-l<0 , ALPHA i=αi , BETA i=βi , for i=k+1,…,m and ALPHA i=0 , BETA i=1 , for i=m+1,…,k+l.
Furthermore, if k+l<n, ALPHA i= BETA i=0 , for i=k+l+1,…,n.
17:   U LDU* – REAL (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array U must be at least max 1,M if JOBU='U' or 'I', and at least 1 otherwise.
On entry: if JOBU='U', U must contain an m by m matrix U 1 (usually the orthogonal matrix returned by F08VEF (DGGSVP) or F08VGF (DGGSVP3)).
On exit: if JOBU='U', U contains the product U 1 U.
If JOBU='I', U contains the orthogonal matrix U.
If JOBU='N', U is not referenced.
18:   LDU – INTEGERInput
On entry: the first dimension of the array U as declared in the (sub)program from which F08YEF (DTGSJA) is called.
Constraints:
  • if JOBU='U' or 'I', LDU≥ max 1,M ;
  • otherwise LDU≥1.
19:   V LDV* – REAL (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array V must be at least max 1,P if JOBV='V' or 'I', and at least 1 otherwise.
On entry: if JOBV='V', V must contain an p by p matrix V 1 (usually the orthogonal matrix returned by F08VEF (DGGSVP) or F08VGF (DGGSVP3)).
On exit: if JOBV='I', V contains the orthogonal matrix V.
If JOBV='V', V contains the product V 1 V.
If JOBV='N', V is not referenced.
20:   LDV – INTEGERInput
On entry: the first dimension of the array V as declared in the (sub)program from which F08YEF (DTGSJA) is called.
Constraints:
  • if JOBV='V' or 'I', LDV≥ max 1,P ;
  • otherwise LDV≥1.
21:   Q LDQ* – REAL (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array Q must be at least max 1,N if JOBQ='Q' or 'I', and at least 1 otherwise.
On entry: if JOBQ='Q', Q must contain an n by n matrix Q 1 (usually the orthogonal matrix returned by F08VEF (DGGSVP) or F08VGF (DGGSVP3)).
On exit: if JOBQ='I', Q contains the orthogonal matrix Q.
If JOBQ='Q', Q contains the product Q 1 Q.
If JOBQ='N', Q is not referenced.
22:   LDQ – INTEGERInput
On entry: the first dimension of the array Q as declared in the (sub)program from which F08YEF (DTGSJA) is called.
Constraints:
  • if JOBQ='Q' or 'I', LDQ≥ max 1,N ;
  • otherwise LDQ≥1.
23:   WORK 2×N – REAL (KIND=nag_wp) arrayWorkspace
24:   NCYCLE – INTEGEROutput
On exit: the number of cycles required for convergence.
25:   INFO – INTEGEROutput
On exit: INFO=0 unless the routine detects an error (see Section 6).

6 Error Indicators and Warnings

INFO<0
If INFO=-i, argument i had an illegal value. An explanatory message is output, and execution of the program is terminated.
INFO=1
The procedure does not converge after 40 cycles.

7 Accuracy

The computed generalized singular value decomposition is nearly the exact generalized singular value decomposition for nearby matrices A+E and B+F, where
E 2 = O⁡ε A 2   and   F 2= O⁡ε B 2 ,
and ε is the machine precision. See Section 4.12 of Anderson et al. (1999) for further details.

8 Parallelism and Performance

F08YEF (DTGSJA) makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The complex analogue of this routine is F08YSF (ZTGSJA).

10 Example

This example finds the generalized singular value decomposition
A = U Σ 1 0 R QT ,   B= V Σ 2 0 R QT ,
of the matrix pair A,B, where
A = 1 2 3 3 2 1 4 5 6 7 8 8   and   B= -2 -3 3 4 6 5 .

10.1 Program Text

Program Text (f08yefe.f90)

10.2 Program Data

Program Data (f08yefe.d)

10.3 Program Results

Program Results (f08yefe.r)

F08 Chapter Contents
F08 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F08YFF (DTGEXC) : NAG Library, Mark 26

F08 Chapter Contents
F08 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F08YFF (DTGEXC)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F08YFF (DTGEXC) reorders the generalized Schur factorization of a matrix pair in real generalized Schur form.

2 Specification

SUBROUTINE F08YFF ( WANTQ, WANTZ, N, A, LDA, B, LDB, Q, LDQ, Z, LDZ, IFST, ILST, WORK, LWORK, INFO)
INTEGER | N, LDA, LDB, LDQ, LDZ, IFST, ILST, LWORK, INFO
REAL (KIND=nag_wp) | A(LDA,*), B(LDB,*), Q(LDQ,*), Z(LDZ,*), WORK(max(1,LWORK))
LOGICAL | WANTQ, WANTZ
The routine may be called by its LAPACK name dtgexc.

3 Description

F08YFF (DTGEXC) reorders the generalized real n by n matrix pair S,T in real generalized Schur form, so that the diagonal element or block of S,T with row index i 1 is moved to row i 2, using an orthogonal equivalence transformation. That is, S and T are factorized as
S = Q^ S^ Z^T ,   T= Q^ T^ Z^T ,
where S^,T^ are also in real generalized Schur form.
The pair S,T are in real generalized Schur form if S is block upper triangular with 1 by 1 and 2 by 2 diagonal blocks and T is upper triangular as returned, for example, by F08XAF (DGGES), or F08XEF (DHGEQZ) with JOB='S'.
If S and T are the result of a generalized Schur factorization of a matrix pair A,B
A = QS ZT ,   B= QT ZT
then, optionally, the matrices Q and Z can be updated as Q Q^ and Z Z^.

4 References

Anderson E, Bai Z, Bischof C, Blackford S, Demmel J, Dongarra J J, Du Croz J J, Greenbaum A, Hammarling S, McKenney A and Sorensen D (1999) LAPACK Users' Guide (3rd Edition) SIAM, Philadelphia http://www.netlib.org/lapack/lug

5 Arguments

1:   WANTQ – LOGICALInput
On entry: if WANTQ=.TRUE., update the left transformation matrix Q.
If WANTQ=.FALSE., do not update Q.
2:   WANTZ – LOGICALInput
On entry: if WANTZ=.TRUE., update the right transformation matrix Z.
If WANTZ=.FALSE., do not update Z.
3:   N – INTEGERInput
On entry: n, the order of the matrices S and T.
Constraint: N≥0.
4:   A LDA* – REAL (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array A must be at least max 1,N.
On entry: the matrix S in the pair S,T.
On exit: the updated matrix S^.
5:   LDA – INTEGERInput
On entry: the first dimension of the array A as declared in the (sub)program from which F08YFF (DTGEXC) is called.
Constraint: LDA≥max 1,N.
6:   B LDB* – REAL (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array B must be at least max 1,N.
On entry: the matrix T, in the pair S,T.
On exit: the updated matrix T^
7:   LDB – INTEGERInput
On entry: the first dimension of the array B as declared in the (sub)program from which F08YFF (DTGEXC) is called.
Constraint: LDB≥max 1,N.
8:   Q LDQ* – REAL (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array Q must be at least max 1,N if WANTQ=.TRUE., and at least 1 otherwise.
On entry: if WANTQ=.TRUE., the orthogonal matrix Q.
On exit: if WANTQ=.TRUE., the updated matrix Q Q^.
If WANTQ=.FALSE., Q is not referenced.
9:   LDQ – INTEGERInput
On entry: the first dimension of the array Q as declared in the (sub)program from which F08YFF (DTGEXC) is called.
Constraints:
  • if WANTQ=.TRUE., LDQ≥ max 1,N ;
  • otherwise LDQ≥1.
10:   Z LDZ* – REAL (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array Z must be at least max 1,N if WANTZ=.TRUE., and at least 1 otherwise.
On entry: if WANTZ=.TRUE., the orthogonal matrix Z.
On exit: if WANTZ=.TRUE., the updated matrix Z Z^.
If WANTZ=.FALSE., Z is not referenced.
11:   LDZ – INTEGERInput
On entry: the first dimension of the array Z as declared in the (sub)program from which F08YFF (DTGEXC) is called.
Constraints:
  • if WANTZ=.TRUE., LDZ≥ max 1,N ;
  • otherwise LDZ≥1.
12:   IFST – INTEGERInput/Output
13:   ILST – INTEGERInput/Output
On entry: the indices i 1 and i 2 that specify the reordering of the diagonal blocks of S,T. The block with row index IFST is moved to row ILST, by a sequence of swapping between adjacent blocks.
On exit: if IFST pointed on entry to the second row of a 2 by 2 block, it is changed to point to the first row; ILST always points to the first row of the block in its final position (which may differ from its input value by +1 or -1).
Constraint: 1≤IFST≤N and 1≤ILST≤N.
14:   WORK max 1,LWORK – REAL (KIND=nag_wp) arrayWorkspace
On exit: if INFO=0, WORK 1 contains the minimum value of LWORK required for optimal performance.
15:   LWORK – INTEGERInput
On entry: the dimension of the array WORK as declared in the (sub)program from which F08YFF (DTGEXC) is called.
If LWORK=-1, a workspace query is assumed; the routine only calculates the minimum size of the WORK array, returns this value as the first entry of the WORK array, and no error message related to LWORK is issued.
Constraints:
if LWORK≠-1,
  • if N≤1, LWORK≥1;
  • otherwise LWORK≥4×N+16.
16:   INFO – INTEGEROutput
On exit: INFO=0 unless the routine detects an error (see Section 6).

6 Error Indicators and Warnings

INFO<0
If INFO=-i, argument i had an illegal value. An explanatory message is output, and execution of the program is terminated.
INFO=1
The transformed matrix pair S^,T^ would be too far from generalized Schur form; the problem is ill-conditioned. S,T may have been partially reordered, and ILST points to the first row of the current position of the block being moved.

7 Accuracy

The computed generalized Schur form is nearly the exact generalized Schur form for nearby matrices S+E and T+F, where
E 2 = O⁡ε S 2   and   F 2= O⁡ε T 2 ,
and ε is the machine precision. See Section 4.11 of Anderson et al. (1999) for further details of error bounds for the generalized nonsymmetric eigenproblem.

8 Parallelism and Performance

F08YFF (DTGEXC) makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The complex analogue of this routine is F08YTF (ZTGEXC).

10 Example

This example exchanges blocks 2 and 1 of the matrix pair S,T, where
S = 4.0 1.0 1.0 2.0 0.0 3.0 4.0 1.0 0.0 1.0 3.0 1.0 0.0 0.0 0.0 6.0   and   T= 2.0 1.0 1.0 3.0 0.0 1.0 2.0 1.0 0.0 0.0 1.0 1.0 0.0 0.0 0.0 2.0 .

10.1 Program Text

Program Text (f08yffe.f90)

10.2 Program Data

Program Data (f08yffe.d)

10.3 Program Results

Program Results (f08yffe.r)

F08 Chapter Contents
F08 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F08YGF (DTGSEN) : NAG Library, Mark 26

F08 Chapter Contents
F08 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F08YGF (DTGSEN)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F08YGF (DTGSEN) reorders the generalized Schur factorization of a matrix pair in real generalized Schur form, so that a selected cluster of eigenvalues appears in the leading elements, or blocks on the diagonal of the generalized Schur form. The routine also, optionally, computes the reciprocal condition numbers of the cluster of eigenvalues and/or corresponding deflating subspaces.

2 Specification

SUBROUTINE F08YGF ( IJOB, WANTQ, WANTZ, SELECT, N, A, LDA, B, LDB, ALPHAR, ALPHAI, BETA, Q, LDQ, Z, LDZ, M, PL, PR, DIF, WORK, LWORK, IWORK, LIWORK, INFO)
INTEGER | IJOB, N, LDA, LDB, LDQ, LDZ, M, LWORK, IWORK(*), LIWORK, INFO
REAL (KIND=nag_wp) | A(LDA,*), B(LDB,*), ALPHAR(N), ALPHAI(N), BETA(N), Q(LDQ,*), Z(LDZ,*), PL, PR, DIF(*), WORK(max(1,LWORK))
LOGICAL | WANTQ, WANTZ, SELECT(N)
The routine may be called by its LAPACK name dtgsen.

3 Description

F08YGF (DTGSEN) factorizes the generalized real n by n matrix pair S,T in real generalized Schur form, using an orthogonal equivalence transformation as
S = Q^ S^ Z^T ,   T= Q^ T^ Z^T ,
where S^,T^ are also in real generalized Schur form and have the selected eigenvalues as the leading diagonal elements, or diagonal blocks. The leading columns of Q and Z are the generalized Schur vectors corresponding to the selected eigenvalues and form orthonormal subspaces for the left and right eigenspaces (deflating subspaces) of the pair S,T.
The pair S,T are in real generalized Schur form if S is block upper triangular with 1 by 1 and 2 by 2 diagonal blocks and T is upper triangular as returned, for example, by F08XAF (DGGES), or F08XEF (DHGEQZ) with JOB='S'. The diagonal elements, or blocks, define the generalized eigenvalues αi,βi, for i=1,2,…,n, of the pair S,T. The eigenvalues are given by
λi = αi / βi ,
but are returned as the pair αi,βi in order to avoid possible overflow in computing λi. Optionally, the routine returns reciprocals of condition number estimates for the selected eigenvalue cluster, p and q, the right and left projection norms, and of deflating subspaces, Difu and Difl. For more information see Sections 2.4.8 and 4.11 of Anderson et al. (1999).
If S and T are the result of a generalized Schur factorization of a matrix pair A,B
A = QS ZT ,   B= QT ZT
then, optionally, the matrices Q and Z can be updated as Q Q^ and Z Z^. Note that the condition numbers of the pair S,T are the same as those of the pair A,B.

4 References

Anderson E, Bai Z, Bischof C, Blackford S, Demmel J, Dongarra J J, Du Croz J J, Greenbaum A, Hammarling S, McKenney A and Sorensen D (1999) LAPACK Users' Guide (3rd Edition) SIAM, Philadelphia http://www.netlib.org/lapack/lug

5 Arguments

1:   IJOB – INTEGERInput
On entry: specifies whether condition numbers are required for the cluster of eigenvalues (p and q) or the deflating subspaces (Difu and Difl).
IJOB=0
Only reorder with respect to SELECT. No extras.
IJOB=1
Reciprocal of norms of ‘projections’ onto left and right eigenspaces with respect to the selected cluster (p and q).
IJOB=2
The upper bounds on Difu and Difl. F-norm-based estimate (DIF 1:2).
IJOB=3
Estimate of Difu and Difl. 1-norm-based estimate (DIF 1:2). About five times as expensive as IJOB=2.
IJOB=4
Compute PL, PR and DIF as in IJOB=0, 1 and 2. Economic version to get it all.
IJOB=5
Compute PL, PR and DIF as in IJOB=0, 1 and 3.
Constraint: 0≤IJOB≤5.
2:   WANTQ – LOGICALInput
On entry: if WANTQ=.TRUE., update the left transformation matrix Q.
If WANTQ=.FALSE., do not update Q.
3:   WANTZ – LOGICALInput
On entry: if WANTZ=.TRUE., update the right transformation matrix Z.
If WANTZ=.FALSE., do not update Z.
4:   SELECT N – LOGICAL arrayInput
On entry: specifies the eigenvalues in the selected cluster. To select a real eigenvalue λj, SELECT j must be set to .TRUE..
To select a complex conjugate pair of eigenvalues λj and λ j+1, corresponding to a 2 by 2 diagonal block, either SELECT j or SELECT j+1 or both must be set to .TRUE.; a complex conjugate pair of eigenvalues must be either both included in the cluster or both excluded.
5:   N – INTEGERInput
On entry: n, the order of the matrices S and T.
Constraint: N≥0.
6:   A LDA* – REAL (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array A must be at least max 1,N.
On entry: the matrix S in the pair S,T.
On exit: the updated matrix S^.
7:   LDA – INTEGERInput
On entry: the first dimension of the array A as declared in the (sub)program from which F08YGF (DTGSEN) is called.
Constraint: LDA≥max 1,N.
8:   B LDB* – REAL (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array B must be at least max 1,N.
On entry: the matrix T, in the pair S,T.
On exit: the updated matrix T^
9:   LDB – INTEGERInput
On entry: the first dimension of the array B as declared in the (sub)program from which F08YGF (DTGSEN) is called.
Constraint: LDB≥max 1,N.
10:   ALPHAR N – REAL (KIND=nag_wp) arrayOutput
On exit: see the description of BETA.
11:   ALPHAI N – REAL (KIND=nag_wp) arrayOutput
On exit: see the description of BETA.
12:   BETA N – REAL (KIND=nag_wp) arrayOutput
On exit: ALPHAR j / BETA j and ALPHAI j / BETA j are the real and imaginary parts respectively of the jth eigenvalue, for j=1,2,…,N.
If ALPHAI j is zero, then the jth eigenvalue is real; if positive then ALPHAI j+1 is negative, and the jth and j+1st eigenvalues are a complex conjugate pair.
Conjugate pairs of eigenvalues correspond to the 2 by 2 diagonal blocks of S^. These 2 by 2 blocks can be reduced by applying complex unitary transformations to S^,T^ to obtain the complex Schur form S~,T~ , where S~ is triangular (and complex). In this form ALPHAR+iALPHAI and BETA are the diagonals of S~ and T~ respectively.
13:   Q LDQ* – REAL (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array Q must be at least max 1,N if WANTQ=.TRUE., and at least 1 otherwise.
On entry: if WANTQ=.TRUE., the n by n matrix Q.
On exit: if WANTQ=.TRUE., the updated matrix Q Q^.
If WANTQ=.FALSE., Q is not referenced.
14:   LDQ – INTEGERInput
On entry: the first dimension of the array Q as declared in the (sub)program from which F08YGF (DTGSEN) is called.
Constraints:
  • if WANTQ=.TRUE., LDQ≥ max 1,N ;
  • otherwise LDQ≥1.
15:   Z LDZ* – REAL (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array Z must be at least max 1,N if WANTZ=.TRUE., and at least 1 otherwise.
On entry: if WANTZ=.TRUE., the n by n matrix Z.
On exit: if WANTZ=.TRUE., the updated matrix Z Z^.
If WANTZ=.FALSE., Z is not referenced.
16:   LDZ – INTEGERInput
On entry: the first dimension of the array Z as declared in the (sub)program from which F08YGF (DTGSEN) is called.
Constraints:
  • if WANTZ=.TRUE., LDZ≥ max 1,N ;
  • otherwise LDZ≥1.
17:   M – INTEGEROutput
On exit: the dimension of the specified pair of left and right eigenspaces (deflating subspaces).
18:   PL – REAL (KIND=nag_wp)Output
19:   PR – REAL (KIND=nag_wp)Output
On exit: if IJOB=1, 4 or 5, PL and PR are lower bounds on the reciprocal of the norm of ‘projections’ p and q onto left and right eigenspaces with respect to the selected cluster. 0<PL, PR≤1.
If M=0 or M=N, PL=PR=1.
If IJOB=0, 2 or 3, PL and PR are not referenced.
20:   DIF* – REAL (KIND=nag_wp) arrayOutput
Note: the dimension of the array DIF must be at least 2.
On exit: if IJOB≥2, DIF 1:2 store the estimates of Difu and Difl.
If IJOB=2 or 4, DIF 1:2 are F-norm-based upper bounds on Difu and Difl.
If IJOB=3 or 5, DIF 1:2 are 1-norm-based estimates of Difu and Difl.
If M=0 or n, DIF 1:2 =A,B F.
If IJOB=0 or 1, DIF is not referenced.
21:   WORK max 1,LWORK – REAL (KIND=nag_wp) arrayWorkspace
On exit: if INFO=0, WORK 1 returns the minimum LWORK.
If IJOB=0, WORK is not referenced.
22:   LWORK – INTEGERInput
On entry: the dimension of the array WORK as declared in the (sub)program from which F08YGF (DTGSEN) is called.
If LWORK=-1, a workspace query is assumed; the routine only calculates the minimum sizes of the WORK and IWORK arrays, returns these values as the first entries of the WORK and IWORK arrays, and no error message related to LWORK or LIWORK is issued.
Constraints:
if LWORK≠-1,
  • if N=0, LWORK≥1;
  • if IJOB=1, 2 or 4, LWORK≥max 4×N+16,2×M×N-M;
  • if IJOB=3 or 5, LWORK≥max 4×N+16,4×M×N-M;
  • otherwise LWORK≥4×N+16.
23:   IWORK* – INTEGER arrayWorkspace
Note: the dimension of the array IWORK must be at least max 1,LIWORK.
On exit: if INFO=0, IWORK 1 returns the minimum LIWORK.
If IJOB=0, IWORK is not referenced.
24:   LIWORK – INTEGERInput
On entry: the dimension of the array IWORK as declared in the (sub)program from which F08YGF (DTGSEN) is called.
If LIWORK=-1, a workspace query is assumed; the routine only calculates the minimum sizes of the WORK and IWORK arrays, returns these values as the first entries of the WORK and IWORK arrays, and no error message related to LWORK or LIWORK is issued.
Constraints:
if LIWORK≠-1,
  • if IJOB=1, 2 or 4, LIWORK≥N+6;
  • if IJOB=3 or 5, LIWORK≥max 2×M×N-M,N+6;
  • otherwise LIWORK≥1.
25:   INFO – INTEGEROutput
On exit: INFO=0 unless the routine detects an error (see Section 6).

6 Error Indicators and Warnings

INFO<0
If INFO=-i, argument i had an illegal value. An explanatory message is output, and execution of the program is terminated.
INFO=1
Reordering of S,T failed because the transformed matrix pair S^,T^ would be too far from generalized Schur form; the problem is very ill-conditioned. S,T may have been partially reordered. If requested, 0 is returned in DIF 1:2, PL and PR.

7 Accuracy

The computed generalized Schur form is nearly the exact generalized Schur form for nearby matrices S+E and T+F, where
E 2 = O⁡ε S 2   and   F 2= O⁡ε T 2 ,
and ε is the machine precision. See Section 4.11 of Anderson et al. (1999) for further details of error bounds for the generalized nonsymmetric eigenproblem, and for information on the condition numbers returned.

8 Parallelism and Performance

F08YGF (DTGSEN) makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The complex analogue of this routine is F08YUF (ZTGSEN).

10 Example

This example reorders the generalized Schur factors S and T and update the matrices Q and Z given by
S = 4.0 1.0 1.0 2.0 0.0 3.0 4.0 1.0 0.0 1.0 3.0 1.0 0.0 0.0 0.0 6.0 ,   T= 2.0 1.0 1.0 3.0 0.0 1.0 2.0 1.0 0.0 0.0 1.0 1.0 0.0 0.0 0.0 2.0 ,
Q = 1.0 0.0 0.0 0.0 0.0 1.0 0.0 0.0 0.0 0.0 1.0 0.0 0.0 0.0 0.0 1.0   and   Z= 1.0 0.0 0.0 0.0 0.0 1.0 0.0 0.0 0.0 0.0 1.0 0.0 0.0 0.0 0.0 1.0 ,
selecting the first and fourth generalized eigenvalues to be moved to the leading positions. Bases for the left and right deflating subspaces, and estimates of the condition numbers for the eigenvalues and Frobenius norm based bounds on the condition numbers for the deflating subspaces are also output.

10.1 Program Text

Program Text (f08ygfe.f90)

10.2 Program Data

Program Data (f08ygfe.d)

10.3 Program Results

Program Results (f08ygfe.r)

F08 Chapter Contents
F08 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F08YHF (DTGSYL) : NAG Library, Mark 26

F08 Chapter Contents
F08 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F08YHF (DTGSYL)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F08YHF (DTGSYL) solves the generalized real quasi-triangular Sylvester equations.

2 Specification

SUBROUTINE F08YHF ( TRANS, IJOB, M, N, A, LDA, B, LDB, C, LDC, D, LDD, E, LDE, F, LDF, SCALE, DIF, WORK, LWORK, IWORK, INFO)
INTEGER | IJOB, M, N, LDA, LDB, LDC, LDD, LDE, LDF, LWORK, IWORK(max(1,M+N+6)), INFO
REAL (KIND=nag_wp) | A(LDA,*), B(LDB,*), C(LDC,*), D(LDD,*), E(LDE,*), F(LDF,*), SCALE, DIF, WORK(max(1,LWORK))
CHARACTER(1) | TRANS
The routine may be called by its LAPACK name dtgsyl.

3 Description

F08YHF (DTGSYL) solves either the generalized real Sylvester equations
AR-LB =αC DR-LE =αF, (1)
or the equations
AT R+DT L =αC R BT+L ET =-α F, (2)
where the pair A,D are given m by m matrices in real generalized Schur form, B,E are given n by n matrices in real generalized Schur form and C,F are given m by n matrices. The pair R,L are the m by n solution matrices, and α is an output scaling factor determined by the routine to avoid overflow in computing R,L.
Equations (1) are equivalent to equations of the form
Zx=αb ,
where
Z = I⊗A-BT⊗I I⊗D-ET⊗I
and ⊗ is the Kronecker product. Equations (2) are then equivalent to
ZT y = αb .
The pair S,T are in real generalized Schur form if S is block upper triangular with 1 by 1 and 2 by 2 diagonal blocks on the diagonal and T is upper triangular as returned, for example, by F08XAF (DGGES), or F08XEF (DHGEQZ) with JOB='S'.
Optionally, the routine estimates Dif A,D,B,E, the separation between the matrix pairs A,D and B,E, which is the smallest singular value of Z. The estimate can be based on either the Frobenius norm, or the 1-norm. The 1-norm estimate can be three to ten times more expensive than the Frobenius norm estimate, but makes the condition estimation uniform with the nonsymmetric eigenproblem. The Frobenius norm estimate provides a low cost, but equally reliable estimate. For more information see Sections 2.4.8.3 and 4.11.1.3 of Anderson et al. (1999) and Kågström and Poromaa (1996).

4 References

Anderson E, Bai Z, Bischof C, Blackford S, Demmel J, Dongarra J J, Du Croz J J, Greenbaum A, Hammarling S, McKenney A and Sorensen D (1999) LAPACK Users' Guide (3rd Edition) SIAM, Philadelphia http://www.netlib.org/lapack/lug
Kågström B (1994) A perturbation analysis of the generalized Sylvester equation AR-LB,DR-LE=c,F SIAM J. Matrix Anal. Appl. 15 1045–1060
Kågström B and Poromaa P (1996) LAPACK-style algorithms and software for solving the generalized Sylvester equation and estimating the separation between regular matrix pairs ACM Trans. Math. Software 22 78–103

5 Arguments

1:   TRANS – CHARACTER(1)Input
On entry: if TRANS='N', solve the generalized Sylvester equation (1).
If TRANS='T', solve the ‘transposed’ system (2).
Constraint: TRANS='N' or 'T'.
2:   IJOB – INTEGERInput
On entry: specifies what kind of functionality is to be performed when TRANS='N'.
IJOB=0
Solve (1) only.
IJOB=1
The functionality of IJOB=0 and 3.
IJOB=2
The functionality of IJOB=0 and 4.
IJOB=3
Only an estimate of Dif A,D,B,E is computed based on the Frobenius norm.
IJOB=4
Only an estimate of Dif A,D,B,E is computed based on the 1-norm.
If TRANS='T', IJOB is not referenced.
Constraint: if TRANS='N', 0≤IJOB≤4.
3:   M – INTEGERInput
On entry: m, the order of the matrices A and D, and the row dimension of the matrices C, F, R and L.
Constraint: M≥0.
4:   N – INTEGERInput
On entry: n, the order of the matrices B and E, and the column dimension of the matrices C, F, R and L.
Constraint: N≥0.
5:   A LDA* – REAL (KIND=nag_wp) arrayInput
Note: the second dimension of the array A must be at least max 1,M.
On entry: the upper quasi-triangular matrix A.
6:   LDA – INTEGERInput
On entry: the first dimension of the array A as declared in the (sub)program from which F08YHF (DTGSYL) is called.
Constraint: LDA≥max 1,M.
7:   B LDB* – REAL (KIND=nag_wp) arrayInput
Note: the second dimension of the array B must be at least max 1,N.
On entry: the upper quasi-triangular matrix B.
8:   LDB – INTEGERInput
On entry: the first dimension of the array B as declared in the (sub)program from which F08YHF (DTGSYL) is called.
Constraint: LDB≥max 1,N.
9:   C LDC* – REAL (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array C must be at least max 1,N.
On entry: contains the right-hand-side matrix C.
On exit: if IJOB=0, 1 or 2, C is overwritten by the solution matrix R.
If TRANS='N' and IJOB=3 or 4, C holds R, the solution achieved during the computation of the Dif estimate.
10:   LDC – INTEGERInput
On entry: the first dimension of the array C as declared in the (sub)program from which F08YHF (DTGSYL) is called.
Constraint: LDC≥max 1,M.
11:   D LDD* – REAL (KIND=nag_wp) arrayInput
Note: the second dimension of the array D must be at least max 1,M.
On entry: the upper triangular matrix D.
12:   LDD – INTEGERInput
On entry: the first dimension of the array D as declared in the (sub)program from which F08YHF (DTGSYL) is called.
Constraint: LDD≥max 1,M.
13:   E LDE* – REAL (KIND=nag_wp) arrayInput
Note: the second dimension of the array E must be at least max 1,N.
On entry: the upper triangular matrix E.
14:   LDE – INTEGERInput
On entry: the first dimension of the array E as declared in the (sub)program from which F08YHF (DTGSYL) is called.
Constraint: LDE≥max 1,N.
15:   F LDF* – REAL (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array F must be at least max 1,N.
On entry: contains the right-hand side matrix F.
On exit: if IJOB=0, 1 or 2, F is overwritten by the solution matrix L.
If TRANS='N' and IJOB=3 or 4, F holds L, the solution achieved during the computation of the Dif estimate.
16:   LDF – INTEGERInput
On entry: the first dimension of the array F as declared in the (sub)program from which F08YHF (DTGSYL) is called.
Constraint: LDF≥max 1,M.
17:   SCALE – REAL (KIND=nag_wp)Output
On exit: α, the scaling factor in (1) or (2).
If 0<SCALE<1, C and F hold the solutions R and L, respectively, to a slightly perturbed system but the input arrays A, B, D and E have not been changed.
If SCALE=0, C and F hold the solutions R and L, respectively, to the homogeneous system with C=F=0. In this case DIF is not referenced.
Normally, SCALE=1.
18:   DIF – REAL (KIND=nag_wp)Output
On exit: the estimate of Dif. If IJOB=0, DIF is not referenced.
19:   WORK max 1,LWORK – REAL (KIND=nag_wp) arrayWorkspace
On exit: if INFO=0, WORK 1 contains the minimum value of LWORK required for optimal performance.
20:   LWORK – INTEGERInput
On entry: the dimension of the array WORK as declared in the (sub)program from which F08YHF (DTGSYL) is called.
If LWORK=-1, a workspace query is assumed; the routine only calculates the minimum size of the WORK array, returns this value as the first entry of the WORK array, and no error message related to LWORK is issued.
Constraints:
if LWORK≠-1,
  • if TRANS='N' and IJOB=1 or 2, LWORK≥max 1,2×M×N;
  • otherwise LWORK≥1.
21:   IWORK max 1,M+N+6 – INTEGER arrayWorkspace
22:   INFO – INTEGEROutput
On exit: INFO=0 unless the routine detects an error (see Section 6).

6 Error Indicators and Warnings

INFO<0
If INFO=-i, argument i had an illegal value. An explanatory message is output, and execution of the program is terminated.
INFO>0
A,D and B,E have common or close eigenvalues and so no solution could be computed.

7 Accuracy

See Kågström (1994) for a perturbation analysis of the generalized Sylvester equation.

8 Parallelism and Performance

F08YHF (DTGSYL) makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The total number of floating-point operations needed to solve the generalized Sylvester equations is approximately 2 mn n+m. The Frobenius norm estimate of Dif does not require additional significant computation, but the 1-norm estimate is typically five times more expensive.
The complex analogue of this routine is F08YVF (ZTGSYL).

10 Example

This example solves the generalized Sylvester equations
AR-LB =αC DR-LE =αF,
where
A = 4.0 1.0 1.0 2.0 0.0 3.0 4.0 1.0 0.0 1.0 3.0 1.0 0.0 0.0 0.0 6.0 ,   B= 1.0 1.0 1.0 1.0 0.0 3.0 4.0 1.0 0.0 1.0 3.0 1.0 0.0 0.0 0.0 4.0 ,
D = 2.0 1.0 1.0 3.0 0.0 1.0 2.0 1.0 0.0 0.0 1.0 1.0 0.0 0.0 0.0 2.0 ,   E= 1.0 1.0 1.0 2.0 0.0 1.0 4.0 1.0 0.0 0.0 1.0 1.0 0.0 0.0 0.0 1.0 ,
C = -4.0 7.0 1.0 12.0 -9.0 2.0 -2.0 -2.0 -4.0 2.0 -2.0 8.0 -7.0 7.0 -6.0 19.0   and   F= -7.0 5.0 0.0 7.0 -5.0 1.0 -8.0 0.0 -1.0 2.0 -3.0 5.0 -3.0 2.0 0.0 5.0 .

10.1 Program Text

Program Text (f08yhfe.f90)

10.2 Program Data

Program Data (f08yhfe.d)

10.3 Program Results

Program Results (f08yhfe.r)

F08 Chapter Contents
F08 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F08YKF (DTGEVC) : NAG Library, Mark 26

F08 Chapter Contents
F08 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F08YKF (DTGEVC)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F08YKF (DTGEVC) computes some or all of the right and/or left generalized eigenvectors of a pair of real matrices A,B which are in generalized real Schur form.

2 Specification

SUBROUTINE F08YKF ( SIDE, HOWMNY, SELECT, N, A, LDA, B, LDB, VL, LDVL, VR, LDVR, MM, M, WORK, INFO)
INTEGER | N, LDA, LDB, LDVL, LDVR, MM, M, INFO
REAL (KIND=nag_wp) | A(LDA,*), B(LDB,*), VL(LDVL,*), VR(LDVR,*), WORK(6*N)
LOGICAL | SELECT(*)
CHARACTER(1) | SIDE, HOWMNY
The routine may be called by its LAPACK name dtgevc.

3 Description

F08YKF (DTGEVC) computes some or all of the right and/or left generalized eigenvectors of the matrix pair A,B which is assumed to be in generalized upper Schur form. If the matrix pair A,B is not in the generalized upper Schur form, then F08XEF (DHGEQZ) should be called before invoking F08YKF (DTGEVC).
The right generalized eigenvector x and the left generalized eigenvector y of A,B corresponding to a generalized eigenvalue λ are defined by
A-λB x=0
and
yH A-λ B=0.
If a generalized eigenvalue is determined as 0/0, which is due to zero diagonal elements at the same locations in both A and B, a unit vector is returned as the corresponding eigenvector.
Note that the generalized eigenvalues are computed using F08XEF (DHGEQZ) but F08YKF (DTGEVC) does not explicitly require the generalized eigenvalues to compute eigenvectors. The ordering of the eigenvectors is based on the ordering of the eigenvalues as computed by F08YKF (DTGEVC).
If all eigenvectors are requested, the routine may either return the matrices X and/or Y of right or left eigenvectors of A,B, or the products ZX and/or QY, where Z and Q are two matrices supplied by you. Usually, Q and Z are chosen as the orthogonal matrices returned by F08XEF (DHGEQZ). Equivalently, Q and Z are the left and right Schur vectors of the matrix pair supplied to F08XEF (DHGEQZ). In that case, QY and ZX are the left and right generalized eigenvectors, respectively, of the matrix pair supplied to F08XEF (DHGEQZ).
A must be block upper triangular; with 1 by 1 and 2 by 2 diagonal blocks. Corresponding to each 2 by 2 diagonal block is a complex conjugate pair of eigenvalues and eigenvectors; only one eigenvector of the pair is computed, namely the one corresponding to the eigenvalue with positive imaginary part. Each 1 by 1 block gives a real generalized eigenvalue and a corresponding eigenvector.

4 References

Anderson E, Bai Z, Bischof C, Blackford S, Demmel J, Dongarra J J, Du Croz J J, Greenbaum A, Hammarling S, McKenney A and Sorensen D (1999) LAPACK Users' Guide (3rd Edition) SIAM, Philadelphia
Golub G H and Van Loan C F (1996) Matrix Computations (3rd Edition) Johns Hopkins University Press, Baltimore
Moler C B and Stewart G W (1973) An algorithm for generalized matrix eigenproblems SIAM J. Numer. Anal. 10 241–256
Stewart G W and Sun J-G (1990) Matrix Perturbation Theory Academic Press, London

5 Arguments

1:   SIDE – CHARACTER(1)Input
On entry: specifies the required sets of generalized eigenvectors.
SIDE='R'
Only right eigenvectors are computed.
SIDE='L'
Only left eigenvectors are computed.
SIDE='B'
Both left and right eigenvectors are computed.
Constraint: SIDE='B', 'L' or 'R'.
2:   HOWMNY – CHARACTER(1)Input
On entry: specifies further details of the required generalized eigenvectors.
HOWMNY='A'
All right and/or left eigenvectors are computed.
HOWMNY='B'
All right and/or left eigenvectors are computed; they are backtransformed using the input matrices supplied in arrays VR and/or VL.
HOWMNY='S'
Selected right and/or left eigenvectors, defined by the array SELECT, are computed.
Constraint: HOWMNY='A', 'B' or 'S'.
3:   SELECT* – LOGICAL arrayInput
Note: the dimension of the array SELECT must be at least max 1,N if HOWMNY='S', and at least 1 otherwise.
On entry: specifies the eigenvectors to be computed if HOWMNY='S'. To select the generalized eigenvector corresponding to the jth generalized eigenvalue, the jth element of SELECT should be set to .TRUE.; if the eigenvalue corresponds to a complex conjugate pair, then real and imaginary parts of eigenvectors corresponding to the complex conjugate eigenvalue pair will be computed.
If HOWMNY='A' or 'B', SELECT is not referenced.
Constraint: if HOWMNY='S', SELECT j=.TRUE. or .FALSE., for j=1,2,…,n.
4:   N – INTEGERInput
On entry: n, the order of the matrices A and B.
Constraint: N≥0.
5:   A LDA* – REAL (KIND=nag_wp) arrayInput
Note: the second dimension of the array A must be at least max 1,N.
On entry: the matrix pair A,B must be in the generalized Schur form. Usually, this is the matrix A returned by F08XEF (DHGEQZ).
6:   LDA – INTEGERInput
On entry: the first dimension of the array A as declared in the (sub)program from which F08YKF (DTGEVC) is called.
Constraint: LDA≥max 1,N.
7:   B LDB* – REAL (KIND=nag_wp) arrayInput
Note: the second dimension of the array B must be at least max 1,N.
On entry: the matrix pair A,B must be in the generalized Schur form. If A has a 2 by 2 diagonal block then the corresponding 2 by 2 block of B must be diagonal with positive elements. Usually, this is the matrix B returned by F08XEF (DHGEQZ).
8:   LDB – INTEGERInput
On entry: the first dimension of the array B as declared in the (sub)program from which F08YKF (DTGEVC) is called.
Constraint: LDB≥max 1,N.
9:   VL LDVL* – REAL (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array VL must be at least max 1,MM if SIDE='L' or 'B' and at least 1 if SIDE='R'.
On entry: if HOWMNY='B' and SIDE='L' or 'B', VL must be initialized to an n by n matrix Q. Usually, this is the orthogonal matrix Q of left Schur vectors returned by F08XEF (DHGEQZ).
On exit: if SIDE='L' or 'B', VL contains:
  • if HOWMNY='A', the matrix Y of left eigenvectors of A,B;
  • if HOWMNY='B', the matrix QY;
  • if HOWMNY='S', the left eigenvectors of A,B specified by SELECT, stored consecutively in the columns of the array VL, in the same order as their corresponding eigenvalues.
A complex eigenvector corresponding to a complex eigenvalue is stored in two consecutive columns, the first holding the real part, and the second the imaginary part.
If SIDE='R', VL is not referenced.
10:   LDVL – INTEGERInput
On entry: the first dimension of the array VL as declared in the (sub)program from which F08YKF (DTGEVC) is called.
Constraints:
  • if SIDE='L' or 'B', LDVL≥ max 1,N ;
  • if SIDE='R', LDVL≥1.
11:   VR LDVR* – REAL (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array VR must be at least max 1,MM if SIDE='R' or 'B' and at least 1 if SIDE='L'.
On entry: if HOWMNY='B' and SIDE='R' or 'B', VR must be initialized to an n by n matrix Z. Usually, this is the orthogonal matrix Z of right Schur vectors returned by F08XEF (DHGEQZ).
On exit: if SIDE='R' or 'B', VR contains:
  • if HOWMNY='A', the matrix X of right eigenvectors of A,B;
  • if HOWMNY='B', the matrix ZX;
  • if HOWMNY='S', the right eigenvectors of A,B specified by SELECT, stored consecutively in the columns of the array VR, in the same order as their corresponding eigenvalues.
A complex eigenvector corresponding to a complex eigenvalue is stored in two consecutive columns, the first holding the real part, and the second the imaginary part.
If SIDE='L', VR is not referenced.
12:   LDVR – INTEGERInput
On entry: the first dimension of the array VR as declared in the (sub)program from which F08YKF (DTGEVC) is called.
Constraints:
  • if SIDE='R' or 'B', LDVR≥ max 1,N ;
  • if SIDE='L', LDVR≥1.
13:   MM – INTEGERInput
On entry: the number of columns in the arrays VL and/or VR.
Constraints:
  • if HOWMNY='A' or 'B', MM≥N;
  • if HOWMNY='S', MM must not be less than the number of requested eigenvectors.
14:   M – INTEGEROutput
On exit: the number of columns in the arrays VL and/or VR actually used to store the eigenvectors. If HOWMNY='A' or 'B', M is set to N. Each selected real eigenvector occupies one column and each selected complex eigenvector occupies two columns.
15:   WORK 6×N – REAL (KIND=nag_wp) arrayWorkspace
16:   INFO – INTEGEROutput
On exit: INFO=0 unless the routine detects an error (see Section 6).

6 Error Indicators and Warnings

INFO<0
If INFO=-i, argument i had an illegal value. An explanatory message is output, and execution of the program is terminated.
INFO>0
If INFO=i, the 2 by 2 block INFO:INFO+1 does not have complex eigenvalues.

7 Accuracy

It is beyond the scope of this manual to summarise the accuracy of the solution of the generalized eigenvalue problem. Interested readers should consult Section 4.11 of the LAPACK Users' Guide (see Anderson et al. (1999)) and Chapter 6 of Stewart and Sun (1990).

8 Parallelism and Performance

F08YKF (DTGEVC) makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

F08YKF (DTGEVC) is the sixth step in the solution of the real generalized eigenvalue problem and is called after F08XEF (DHGEQZ).
The complex analogue of this routine is F08YXF (ZTGEVC).

10 Example

This example computes the α and β arguments, which defines the generalized eigenvalues and the corresponding left and right eigenvectors, of the matrix pair A,B given by
A = 1.0 1.0 1.0 1.0 1.0 2.0 4.0 8.0 16.0 32.0 3.0 9.0 27.0 81.0 243.0 4.0 16.0 64.0 256.0 1024.0 5.0 25.0 125.0 625.0 3125.0   and   B= 1.0 2.0 3.0 4.0 5.0 1.0 4.0 9.0 16.0 25.0 1.0 8.0 27.0 64.0 125.0 1.0 16.0 81.0 256.0 625.0 1.0 32.0 243.0 1024.0 3125.0 .
To compute generalized eigenvalues, it is required to call five routines: F08WHF (DGGBAL) to balance the matrix, F08AEF (DGEQRF) to perform the QR factorization of B, F08AGF (DORMQR) to apply Q to A, F08WEF (DGGHRD) to reduce the matrix pair to the generalized Hessenberg form and F08XEF (DHGEQZ) to compute the eigenvalues via the QZ algorithm.
The computation of generalized eigenvectors is done by calling F08YKF (DTGEVC) to compute the eigenvectors of the balanced matrix pair. The routine F08WJF (DGGBAK) is called to backward transform the eigenvectors to the user-supplied matrix pair. If both left and right eigenvectors are required then F08WJF (DGGBAK) must be called twice.

10.1 Program Text

Program Text (f08ykfe.f90)

10.2 Program Data

Program Data (f08ykfe.d)

10.3 Program Results

Program Results (f08ykfe.r)

F08 Chapter Contents
F08 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F08YLF (DTGSNA) : NAG Library, Mark 26

F08 Chapter Contents
F08 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F08YLF (DTGSNA)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F08YLF (DTGSNA) estimates condition numbers for specified eigenvalues and/or eigenvectors of a matrix pair in generalized real Schur form.

2 Specification

SUBROUTINE F08YLF ( JOB, HOWMNY, SELECT, N, A, LDA, B, LDB, VL, LDVL, VR, LDVR, S, DIF, MM, M, WORK, LWORK, IWORK, INFO)
INTEGER | N, LDA, LDB, LDVL, LDVR, MM, M, LWORK, IWORK(*), INFO
REAL (KIND=nag_wp) | A(LDA,*), B(LDB,*), VL(LDVL,*), VR(LDVR,*), S(*), DIF(*), WORK(max(1,LWORK))
LOGICAL | SELECT(*)
CHARACTER(1) | JOB, HOWMNY
The routine may be called by its LAPACK name dtgsna.

3 Description

F08YLF (DTGSNA) estimates condition numbers for specified eigenvalues and/or right eigenvectors of an n by n matrix pair S,T in real generalized Schur form. The routine actually returns estimates of the reciprocals of the condition numbers in order to avoid possible overflow.
The pair S,T are in real generalized Schur form if S is block upper triangular with 1 by 1 and 2 by 2 diagonal blocks and T is upper triangular as returned, for example, by F08XAF (DGGES) or F08XBF (DGGESX), or F08XEF (DHGEQZ) with JOB='S'. The diagonal elements, or blocks, define the generalized eigenvalues αi,βi, for i=1,2,…,n, of the pair S,T and the eigenvalues are given by
λi = αi / βi ,
so that
βi S xi = αi T xi   or   S xi = λi T xi ,
where xi is the corresponding (right) eigenvector.
If S and T are the result of a generalized Schur factorization of a matrix pair A,B
A = QS ZT ,   B = QT ZT
then the eigenvalues and condition numbers of the pair S,T are the same as those of the pair A,B.
Let α,β≠0,0 be a simple generalized eigenvalue of A,B. Then the reciprocal of the condition number of the eigenvalue λ=α/β is defined as
s λ= yT Ax 2 + yT Bx 2 1/2 x 2 y 2 ,
where x and y are the right and left eigenvectors of A,B corresponding to λ. If both α and β are zero, then A,B is singular and s λ=-1 is returned.
The definition of the reciprocal of the estimated condition number of the right eigenvector x and the left eigenvector y corresponding to the simple eigenvalue λ depends upon whether λ is a real eigenvalue, or one of a complex conjugate pair.
If the eigenvalue λ is real and U and V are orthogonal transformations such that
UT A,B V= S,T = α * 0 S 22 β * 0 T 22 ,
where S 22 and T 22 are n-1 by n-1 matrices, then the reciprocal condition number is given by
Dif x ≡ Dif y = Dif α,β,S 22,T 22 = σmin Z ,
where σmin Z denotes the smallest singular value of the 2 n-1 by 2 n-1 matrix
Z = α⊗I -1⊗S 22 β⊗I -1⊗T 22
and ⊗ is the Kronecker product.
If λ is part of a complex conjugate pair and U and V are orthogonal transformations such that
UT A,B V = S,T = S 11 * 0 S 22 T 11 * 0 T 22 ,
where S 11 and T 11 are two by two matrices, S 22 and T 22 are n-2 by n-2 matrices, and S 11,T 11 corresponds to the complex conjugate eigenvalue pair λ, λ-, then there exist unitary matrices U 1 and V 1 such that
U 1 H S 11 V 1 = s 11 s 12 0 s 22   and   U 1 H T 11 V 1 = t 11 t 12 0 t 22 .
The eigenvalues are given by λ=s 11/t 11 and λ-=s 22/t 22. Then the Frobenius norm-based, estimated reciprocal condition number is bounded by
Dif x ≡ Dif y ≤ min d 1,max 1, Re s 11 / Re s 22 ,d 2
where Re z denotes the real part of z, d 1=Dif s 11,t 11,s 22,t 22=σmin Z 1, Z 1 is the complex two by two matrix
Z 1 = s 11 -s 22 t 11 -t 22 ,
and d 2 is an upper bound on Dif S 11,T 11,S 22,T 22; i.e., an upper bound on σmin Z 2, where Z 2 is the 2 n-2 by 2 n-2 matrix
Z 2 = S 11 T⊗I -I⊗S 22 T 11 T⊗I -I⊗T 22 .
See Sections 2.4.8 and 4.11 of Anderson et al. (1999) and Kågström and Poromaa (1996) for further details and information.

4 References

Anderson E, Bai Z, Bischof C, Blackford S, Demmel J, Dongarra J J, Du Croz J J, Greenbaum A, Hammarling S, McKenney A and Sorensen D (1999) LAPACK Users' Guide (3rd Edition) SIAM, Philadelphia http://www.netlib.org/lapack/lug
Kågström B and Poromaa P (1996) LAPACK-style algorithms and software for solving the generalized Sylvester equation and estimating the separation between regular matrix pairs ACM Trans. Math. Software 22 78–103

5 Arguments

1:   JOB – CHARACTER(1)Input
On entry: indicates whether condition numbers are required for eigenvalues and/or eigenvectors.
JOB='E'
Condition numbers for eigenvalues only are computed.
JOB='V'
Condition numbers for eigenvectors only are computed.
JOB='B'
Condition numbers for both eigenvalues and eigenvectors are computed.
Constraint: JOB='E', 'V' or 'B'.
2:   HOWMNY – CHARACTER(1)Input
On entry: indicates how many condition numbers are to be computed.
HOWMNY='A'
Condition numbers for all eigenpairs are computed.
HOWMNY='S'
Condition numbers for selected eigenpairs (as specified by SELECT) are computed.
Constraint: HOWMNY='A' or 'S'.
3:   SELECT* – LOGICAL arrayInput
Note: the dimension of the array SELECT must be at least max 1,N if HOWMNY='S', and at least 1 otherwise.
On entry: specifies the eigenpairs for which condition numbers are to be computed if HOWMNY='S'. To select condition numbers for the eigenpair corresponding to the real eigenvalue λj, SELECT j must be set .TRUE.. To select condition numbers corresponding to a complex conjugate pair of eigenvalues λj and λ j+1, SELECT j and/or SELECT j+1 must be set to .TRUE..
If HOWMNY='A', SELECT is not referenced.
4:   N – INTEGERInput
On entry: n, the order of the matrix pair S,T.
Constraint: N≥0.
5:   A LDA* – REAL (KIND=nag_wp) arrayInput
Note: the second dimension of the array A must be at least max 1,N.
On entry: the upper quasi-triangular matrix S.
6:   LDA – INTEGERInput
On entry: the first dimension of the array A as declared in the (sub)program from which F08YLF (DTGSNA) is called.
Constraint: LDA≥max 1,N.
7:   B LDB* – REAL (KIND=nag_wp) arrayInput
Note: the second dimension of the array B must be at least max 1,N.
On entry: the upper triangular matrix T.
8:   LDB – INTEGERInput
On entry: the first dimension of the array B as declared in the (sub)program from which F08YLF (DTGSNA) is called.
Constraint: LDB≥max 1,N.
9:   VL LDVL* – REAL (KIND=nag_wp) arrayInput
Note: the second dimension of the array VL must be at least max 1,MM if JOB='E' or 'B', and at least 1 otherwise.
On entry: if JOB='E' or 'B', VL must contain left eigenvectors of S,T, corresponding to the eigenpairs specified by HOWMNY and SELECT. The eigenvectors must be stored in consecutive columns of VL, as returned by F08WAF (DGGEV) or F08YKF (DTGEVC).
If JOB='V', VL is not referenced.
10:   LDVL – INTEGERInput
On entry: the first dimension of the array VL as declared in the (sub)program from which F08YLF (DTGSNA) is called.
Constraints:
  • if JOB='E' or 'B', LDVL≥ max 1,N ;
  • otherwise LDVL≥1.
11:   VR LDVR* – REAL (KIND=nag_wp) arrayInput
Note: the second dimension of the array VR must be at least max 1,MM if JOB='E' or 'B', and at least 1 otherwise.
On entry: if JOB='E' or 'B', VR must contain right eigenvectors of S,T, corresponding to the eigenpairs specified by HOWMNY and SELECT. The eigenvectors must be stored in consecutive columns of VR, as returned by F08WAF (DGGEV) or F08YKF (DTGEVC).
If JOB='V', VR is not referenced.
12:   LDVR – INTEGERInput
On entry: the first dimension of the array VR as declared in the (sub)program from which F08YLF (DTGSNA) is called.
Constraints:
  • if JOB='E' or 'B', LDVR≥ max 1,N ;
  • otherwise LDVR≥1.
13:   S* – REAL (KIND=nag_wp) arrayOutput
Note: the dimension of the array S must be at least max 1,MM if JOB='E' or 'B', and at least 1 otherwise.
On exit: if JOB='E' or 'B', the reciprocal condition numbers of the selected eigenvalues, stored in consecutive elements of the array. For a complex conjugate pair of eigenvalues two consecutive elements of S are set to the same value. Thus S j, DIF j, and the jth columns of VL and VR all correspond to the same eigenpair (but not in general the jth eigenpair, unless all eigenpairs are selected).
If JOB='V', S is not referenced.
14:   DIF* – REAL (KIND=nag_wp) arrayOutput
Note: the dimension of the array DIF must be at least max 1,MM if JOB='V' or 'B', and at least 1 otherwise.
On exit: if JOB='V' or 'B', the estimated reciprocal condition numbers of the selected eigenvectors, stored in consecutive elements of the array. For a complex eigenvector two consecutive elements of DIF are set to the same value. If the eigenvalues cannot be reordered to compute DIF j, DIF j is set to 0; this can only occur when the true value would be very small anyway.
If JOB='E', DIF is not referenced.
15:   MM – INTEGERInput
On entry: the number of elements in the arrays S and DIF.
Constraints:
  • if HOWMNY='A', MM≥N;
  • otherwise MM≥M.
16:   M – INTEGEROutput
On exit: the number of elements of the arrays S and DIF used to store the specified condition numbers; for each selected real eigenvalue one element is used, and for each selected complex conjugate pair of eigenvalues, two elements are used. If HOWMNY='A', M is set to N.
17:   WORK max 1,LWORK – REAL (KIND=nag_wp) arrayWorkspace
On exit: if INFO=0, WORK 1 contains the minimum value of LWORK required for optimal performance.
18:   LWORK – INTEGERInput
On entry: the dimension of the array WORK as declared in the (sub)program from which F08YLF (DTGSNA) is called.
If LWORK=-1, a workspace query is assumed; the routine only calculates the minimum size of the WORK array, returns this value as the first entry of the WORK array, and no error message related to LWORK is issued.
Constraints:
if LWORK≠-1,
  • if JOB='V' or 'B', LWORK≥2×N×N+2+16;
  • otherwise LWORK≥max 1,N.
19:   IWORK* – INTEGER arrayWorkspace
Note: the dimension of the array IWORK must be at least N+6.
If JOB='E', IWORK is not referenced.
20:   INFO – INTEGEROutput
On exit: INFO=0 unless the routine detects an error (see Section 6).

6 Error Indicators and Warnings

INFO<0
If INFO=-i, argument i had an illegal value. An explanatory message is output, and execution of the program is terminated.

7 Accuracy

None.

8 Parallelism and Performance

F08YLF (DTGSNA) makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

An approximate asymptotic error bound on the chordal distance between the computed eigenvalue λ~ and the corresponding exact eigenvalue λ is
χ λ~,λ ≤ ε A,B F / S λ
where ε is the machine precision.
An approximate asymptotic error bound for the right or left computed eigenvectors x~ or y~ corresponding to the right and left eigenvectors x and y is given by
θ z~,z ≤ ε A,B F / Dif .
The complex analogue of this routine is F08YYF (ZTGSNA).

10 Example

This example estimates condition numbers and approximate error estimates for all the eigenvalues and eigenvalues and right eigenvectors of the pair S,T given by
S = 4.0 1.0 1.0 2.0 0.0 3.0 -1.0 1.0 0.0 1.0 3.0 1.0 0.0 0.0 0.0 6.0   and   T= 2.0 1.0 1.0 3.0 0.0 1.0 0.0 1.0 0.0 0.0 1.0 1.0 0.0 0.0 0.0 2.0 .
The eigenvalues and eigenvectors are computed by calling F08YKF (DTGEVC).

10.1 Program Text

Program Text (f08ylfe.f90)

10.2 Program Data

Program Data (f08ylfe.d)

10.3 Program Results

Program Results (f08ylfe.r)

F08 Chapter Contents
F08 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F08YSF (ZTGSJA) : NAG Library, Mark 26

F08 Chapter Contents
F08 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F08YSF (ZTGSJA)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F08YSF (ZTGSJA) computes the generalized singular value decomposition (GSVD) of two complex upper trapezoidal matrices A and B, where A is an m by n matrix and B is a p by n matrix.
A and B are assumed to be in the form returned by F08VSF (ZGGSVP) or F08VUF (ZGGSVP3).

2 Specification

SUBROUTINE F08YSF ( JOBU, JOBV, JOBQ, M, P, N, K, L, A, LDA, B, LDB, TOLA, TOLB, ALPHA, BETA, U, LDU, V, LDV, Q, LDQ, WORK, NCYCLE, INFO)
INTEGER | M, P, N, K, L, LDA, LDB, LDU, LDV, LDQ, NCYCLE, INFO
REAL (KIND=nag_wp) | TOLA, TOLB, ALPHA(N), BETA(N)
COMPLEX (KIND=nag_wp) | A(LDA,*), B(LDB,*), U(LDU,*), V(LDV,*), Q(LDQ,*), WORK(2*N)
CHARACTER(1) | JOBU, JOBV, JOBQ
The routine may be called by its LAPACK name ztgsja.

3 Description

F08YSF (ZTGSJA) computes the GSVD of the matrices A and B which are assumed to have the form as returned by F08VSF (ZGGSVP) or F08VUF (ZGGSVP3)
A= n-k-lklk0A 12A 13l00A 23m-k-l000() ,   if ​ m-k-l ≥ 0; n-k-lklk0A 12A 13m-k00A 23() ,   if ​ m-k-l < 0 ; B= n-k-lkll00B 13p-l000() ,
where the k by k matrix A 12 and the l by l matrix B 13 are nonsingular upper triangular, A 23 is l by l upper triangular if m-k-l≥0 and is m-k by l upper trapezoidal otherwise.
F08YSF (ZTGSJA) computes unitary matrices Q, U and V, diagonal matrices D 1 and D 2, and an upper triangular matrix R such that
UH AQ = D 1 0 R ,   VH BQ = D 2 0 R .
Optionally Q, U and V may or may not be computed, or they may be premultiplied by matrices Q 1, U 1 and V 1 respectively.
If m-k-l≥0 then D 1, D 2 and R have the form
D 1= klkI0l0Cm-k-l00() ,
D 2= kll0Sp-l00() ,
R = klkR 11R 12l0R 22() ,
where C=diag α k+1,,,…,,,α k+l,  S=diag β k+1,,,…,,,β k+l.
If m-k-l<0 then D 1, D 2 and R have the form
D 1= km-kk+l-mkI00m-k0C0() ,
D 2= km-kk+l-mm-k0S0k+l-m00Ip-l000() ,
R = km-kk+l-mkR 11R 12R 13m-k0R 22R 23k+l-m00R 33() ,
where C=diag α k+1,,,…,,,αm,  S=diag β k+1,,,…,,,βm.
In both cases the diagonal matrix C has real non-negative diagonal elements, the diagonal matrix S has real positive diagonal elements, so that S is nonsingular, and C 2+S 2=1. See Section 2.3.5.3 of Anderson et al. (1999) for further information.

4 References

Anderson E, Bai Z, Bischof C, Blackford S, Demmel J, Dongarra J J, Du Croz J J, Greenbaum A, Hammarling S, McKenney A and Sorensen D (1999) LAPACK Users' Guide (3rd Edition) SIAM, Philadelphia http://www.netlib.org/lapack/lug
Golub G H and Van Loan C F (1996) Matrix Computations (3rd Edition) Johns Hopkins University Press, Baltimore

5 Arguments

1:   JOBU – CHARACTER(1)Input
On entry: if JOBU='U', U must contain a unitary matrix U 1 on entry, and the product U 1 U is returned.
If JOBU='I', U is initialized to the unit matrix, and the unitary matrix U is returned.
If JOBU='N', U is not computed.
Constraint: JOBU='U', 'I' or 'N'.
2:   JOBV – CHARACTER(1)Input
On entry: if JOBV='V', V must contain a unitary matrix V 1 on entry, and the product V 1 V is returned.
If JOBV='I', V is initialized to the unit matrix, and the unitary matrix V is returned.
If JOBV='N', V is not computed.
Constraint: JOBV='V', 'I' or 'N'.
3:   JOBQ – CHARACTER(1)Input
On entry: if JOBQ='Q', Q must contain a unitary matrix Q 1 on entry, and the product Q 1 Q is returned.
If JOBQ='I', Q is initialized to the unit matrix, and the unitary matrix Q is returned.
If JOBQ='N', Q is not computed.
Constraint: JOBQ='Q', 'I' or 'N'.
4:   M – INTEGERInput
On entry: m, the number of rows of the matrix A.
Constraint: M≥0.
5:   P – INTEGERInput
On entry: p, the number of rows of the matrix B.
Constraint: P≥0.
6:   N – INTEGERInput
On entry: n, the number of columns of the matrices A and B.
Constraint: N≥0.
7:   K – INTEGERInput
8:   L – INTEGERInput
On entry: K and L specify the sizes, k and l, of the subblocks of A and B, whose GSVD is to be computed by F08YSF (ZTGSJA).
9:   A LDA* – COMPLEX (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array A must be at least max 1,N.
On entry: the m by n matrix A.
On exit: if m-k-l≥0, A 1:k+ln-k-l+1:n contains the k+l by k+l upper triangular matrix R.
If m-k-l<0, A 1:mn-k-l+1:n contains the first m rows of the k+l by k+l upper triangular matrix R, and the submatrix R 33 is returned in B m-k+1:ln+m-k-l+1:n .
10:   LDA – INTEGERInput
On entry: the first dimension of the array A as declared in the (sub)program from which F08YSF (ZTGSJA) is called.
Constraint: LDA≥max 1,M.
11:   B LDB* – COMPLEX (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array B must be at least max 1,N.
On entry: the p by n matrix B.
On exit: if m-k-l<0 , B m-k+1:ln+m-k-l+1:n contains the submatrix R 33 of R.
12:   LDB – INTEGERInput
On entry: the first dimension of the array B as declared in the (sub)program from which F08YSF (ZTGSJA) is called.
Constraint: LDB≥max 1,P.
13:   TOLA – REAL (KIND=nag_wp)Input
14:   TOLB – REAL (KIND=nag_wp)Input
On entry: TOLA and TOLB are the convergence criteria for the Jacobi–Kogbetliantz iteration procedure. Generally, they should be the same as used in the preprocessing step performed by F08VSF (ZGGSVP) or F08VUF (ZGGSVP3), say
TOLA=max M,N A ε, TOLB=max P,N B ε,
where ε is the machine precision.
15:   ALPHA N – REAL (KIND=nag_wp) arrayOutput
On exit: see the description of BETA.
16:   BETA N – REAL (KIND=nag_wp) arrayOutput
On exit: ALPHA and BETA contain the generalized singular value pairs of A and B;
  • ALPHA i=1 , BETA i=0 , for i=1,2,…,k, and
  • if m-k-l≥0 , ALPHA i=αi , BETA i=βi , for i=k+1,…,k+l, or
  • if m-k-l<0 , ALPHA i=αi , BETA i=βi , for i=k+1,…,m and ALPHA i=0 , BETA i=1 , for i=m+1,…,k+l.
Furthermore, if k+l<n, ALPHA i= BETA i=0 , for i=k+l+1,…,n.
17:   U LDU* – COMPLEX (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array U must be at least max 1,M if JOBU='U' or 'I', and at least 1 otherwise.
On entry: if JOBU='U', U must contain an m by m matrix U 1 (usually the unitary matrix returned by F08VSF (ZGGSVP) or F08VUF (ZGGSVP3)).
On exit: if JOBU='U', U contains the product U 1 U.
If JOBU='I', U contains the unitary matrix U.
If JOBU='N', U is not referenced.
18:   LDU – INTEGERInput
On entry: the first dimension of the array U as declared in the (sub)program from which F08YSF (ZTGSJA) is called.
Constraints:
  • if JOBU='U' or 'I', LDU≥ max 1,M ;
  • otherwise LDU≥1.
19:   V LDV* – COMPLEX (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array V must be at least max 1,P if JOBV='V' or 'I', and at least 1 otherwise.
On entry: if JOBV='V', V must contain an p by p matrix V 1 (usually the unitary matrix returned by F08VSF (ZGGSVP) or F08VUF (ZGGSVP3)).
On exit: if JOBV='I', V contains the unitary matrix V.
If JOBV='V', V contains the product V 1 V.
If JOBV='N', V is not referenced.
20:   LDV – INTEGERInput
On entry: the first dimension of the array V as declared in the (sub)program from which F08YSF (ZTGSJA) is called.
Constraints:
  • if JOBV='V' or 'I', LDV≥ max 1,P ;
  • otherwise LDV≥1.
21:   Q LDQ* – COMPLEX (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array Q must be at least max 1,N if JOBQ='Q' or 'I', and at least 1 otherwise.
On entry: if JOBQ='Q', Q must contain an n by n matrix Q 1 (usually the unitary matrix returned by F08VSF (ZGGSVP) or F08VUF (ZGGSVP3)).
On exit: if JOBQ='I', Q contains the unitary matrix Q.
If JOBQ='Q', Q contains the product Q 1 Q.
If JOBQ='N', Q is not referenced.
22:   LDQ – INTEGERInput
On entry: the first dimension of the array Q as declared in the (sub)program from which F08YSF (ZTGSJA) is called.
Constraints:
  • if JOBQ='Q' or 'I', LDQ≥ max 1,N ;
  • otherwise LDQ≥1.
23:   WORK 2×N – COMPLEX (KIND=nag_wp) arrayWorkspace
24:   NCYCLE – INTEGEROutput
On exit: the number of cycles required for convergence.
25:   INFO – INTEGEROutput
On exit: INFO=0 unless the routine detects an error (see Section 6).

6 Error Indicators and Warnings

INFO<0
If INFO=-i, argument i had an illegal value. An explanatory message is output, and execution of the program is terminated.
INFO=1
The procedure does not converge after 40 cycles.

7 Accuracy

The computed generalized singular value decomposition is nearly the exact generalized singular value decomposition for nearby matrices A+E and B+F, where
E 2 = O⁡ε A 2   and   F 2= O⁡ε B 2 ,
and ε is the machine precision. See Section 4.12 of Anderson et al. (1999) for further details.

8 Parallelism and Performance

F08YSF (ZTGSJA) makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The real analogue of this routine is F08YEF (DTGSJA).

10 Example

This example finds the generalized singular value decomposition
A = U Σ 1 0 R QH ,   B= V Σ 2 0 R QH ,
of the matrix pair A,B, where
A = 0.96-0.81 i -0.03+0.96 i -0.91+2.06 i -0.05+0.41 i -0.98+1.98 i -1.20+0.19 i -0.66+0.42 i -0.81+0.56 i 0.62-0.46 i 1.01+0.02 i 0.63-0.17 i -1.11+0.60 i 0.37+0.38 i 0.19-0.54 i -0.98-0.36 i 0.22-0.20 i 0.83+0.51 i 0.20+0.01 i -0.17-0.46 i 1.47+1.59 i 1.08-0.28 i 0.20-0.12 i -0.07+1.23 i 0.26+0.26 i
and
B = 1 0 -1 0 0 1 0 -1 .

10.1 Program Text

Program Text (f08ysfe.f90)

10.2 Program Data

Program Data (f08ysfe.d)

10.3 Program Results

Program Results (f08ysfe.r)

F08 Chapter Contents
F08 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F08YTF (ZTGEXC) : NAG Library, Mark 26

F08 Chapter Contents
F08 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F08YTF (ZTGEXC)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F08YTF (ZTGEXC) reorders the generalized Schur factorization of a complex matrix pair in generalized Schur form.

2 Specification

SUBROUTINE F08YTF ( WANTQ, WANTZ, N, A, LDA, B, LDB, Q, LDQ, Z, LDZ, IFST, ILST, INFO)
INTEGER | N, LDA, LDB, LDQ, LDZ, IFST, ILST, INFO
COMPLEX (KIND=nag_wp) | A(LDA,*), B(LDB,*), Q(LDQ,*), Z(LDZ,*)
LOGICAL | WANTQ, WANTZ
The routine may be called by its LAPACK name ztgexc.

3 Description

F08YTF (ZTGEXC) reorders the generalized complex n by n matrix pair S,T in generalized Schur form, so that the diagonal element of S,T with row index i 1 is moved to row i 2, using a unitary equivalence transformation. That is, S and T are factorized as
S = Q^ S^ Z^H ,   T= Q^ T^ Z^H ,
where S^,T^ are also in generalized Schur form.
The pair S,T are in generalized Schur form if S and T are upper triangular as returned, for example, by F08XNF (ZGGES), or F08XSF (ZHGEQZ) with JOB='S'.
If S and T are the result of a generalized Schur factorization of a matrix pair A,B
A = QS ZH ,   B= QT ZH
then, optionally, the matrices Q and Z can be updated as Q Q^ and Z Z^.

4 References

Anderson E, Bai Z, Bischof C, Blackford S, Demmel J, Dongarra J J, Du Croz J J, Greenbaum A, Hammarling S, McKenney A and Sorensen D (1999) LAPACK Users' Guide (3rd Edition) SIAM, Philadelphia http://www.netlib.org/lapack/lug

5 Arguments

1:   WANTQ – LOGICALInput
On entry: if WANTQ=.TRUE., update the left transformation matrix Q.
If WANTQ=.FALSE., do not update Q.
2:   WANTZ – LOGICALInput
On entry: if WANTZ=.TRUE., update the right transformation matrix Z.
If WANTZ=.FALSE., do not update Z.
3:   N – INTEGERInput
On entry: n, the order of the matrices S and T.
Constraint: N≥0.
4:   A LDA* – COMPLEX (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array A must be at least max 1,N.
On entry: the matrix S in the pair S,T.
On exit: the updated matrix S^.
5:   LDA – INTEGERInput
On entry: the first dimension of the array A as declared in the (sub)program from which F08YTF (ZTGEXC) is called.
Constraint: LDA≥max 1,N.
6:   B LDB* – COMPLEX (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array B must be at least max 1,N.
On entry: the matrix T, in the pair S,T.
On exit: the updated matrix T^
7:   LDB – INTEGERInput
On entry: the first dimension of the array B as declared in the (sub)program from which F08YTF (ZTGEXC) is called.
Constraint: LDB≥max 1,N.
8:   Q LDQ* – COMPLEX (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array Q must be at least max 1,N if WANTQ=.TRUE., and at least 1 otherwise.
On entry: if WANTQ=.TRUE., the unitary matrix Q.
On exit: if WANTQ=.TRUE., the updated matrix Q Q^.
If WANTQ=.FALSE., Q is not referenced.
9:   LDQ – INTEGERInput
On entry: the first dimension of the array Q as declared in the (sub)program from which F08YTF (ZTGEXC) is called.
Constraints:
  • if WANTQ=.TRUE., LDQ≥ max 1,N ;
  • otherwise LDQ≥1.
10:   Z LDZ* – COMPLEX (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array Z must be at least max 1,N if WANTZ=.TRUE., and at least 1 otherwise.
On entry: if WANTZ=.TRUE., the unitary matrix Z.
On exit: if WANTZ=.TRUE., the updated matrix Z Z^.
If WANTZ=.FALSE., Z is not referenced.
11:   LDZ – INTEGERInput
On entry: the first dimension of the array Z as declared in the (sub)program from which F08YTF (ZTGEXC) is called.
Constraints:
  • if WANTZ=.TRUE., LDZ≥ max 1,N ;
  • otherwise LDZ≥1.
12:   IFST – INTEGERInput
13:   ILST – INTEGERInput/Output
On entry: the indices i 1 and i 2 that specify the reordering of the diagonal elements of S,T. The element with row index IFST is moved to row ILST, by a sequence of swapping between adjacent diagonal elements.
On exit: ILST points to the row in its final position.
Constraint: 1≤IFST≤N and 1≤ILST≤N.
14:   INFO – INTEGEROutput
On exit: INFO=0 unless the routine detects an error (see Section 6).

6 Error Indicators and Warnings

INFO<0
If INFO=-i, argument i had an illegal value. An explanatory message is output, and execution of the program is terminated.
INFO=1
The transformed matrix pair S^,T^ would be too far from generalized Schur form; the problem is ill-conditioned. S,T may have been partially reordered, and ILST points to the first row of the current position of the block being moved.

7 Accuracy

The computed generalized Schur form is nearly the exact generalized Schur form for nearby matrices S+E and T+F, where
E 2 = O⁡ε S 2   and   F 2= O⁡ε T 2 ,
and ε is the machine precision. See Section 4.11 of Anderson et al. (1999) for further details of error bounds for the generalized nonsymmetric eigenproblem.

8 Parallelism and Performance

F08YTF (ZTGEXC) is not threaded in any implementation.

9 Further Comments

The real analogue of this routine is F08YFF (DTGEXC).

10 Example

This example exchanges rows 4 and 1 of the matrix pair S,T, where
S = 4.0+4.0 i 1.0+1.0 i 1.0+1.0 i 2.0-1.0 i 0.0i+0.0 2.0+1.0 i 1.0+1.0 i 1.0+1.0 i 0.0i+0.0 0.0i+0.0 2.0-1.0 i 1.0+1.0 i 0.0i+0.0 0.0i+0.0 0.0i+0.0 6.0-2.0 i
and
T = 2.0 1.0+1.0 i 1.0+1.0 i 3.0-1.0 i 0.0 1.0 i+0.0 2.0+1.0 i 1.0+1.0 i 0.0 0.0i+0.0 1.0 i+0.0 1.0+1.0 i 0.0 0.0i+0.0 0.0i+0.0 2.0 i+0.0 .

10.1 Program Text

Program Text (f08ytfe.f90)

10.2 Program Data

Program Data (f08ytfe.d)

10.3 Program Results

Program Results (f08ytfe.r)

F08 Chapter Contents
F08 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F08YUF (ZTGSEN) : NAG Library, Mark 26

F08 Chapter Contents
F08 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F08YUF (ZTGSEN)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F08YUF (ZTGSEN) reorders the generalized Schur factorization of a complex matrix pair in generalized Schur form, so that a selected cluster of eigenvalues appears in the leading elements on the diagonal of the generalized Schur form. The routine also, optionally, computes the reciprocal condition numbers of the cluster of eigenvalues and/or corresponding deflating subspaces.

2 Specification

SUBROUTINE F08YUF ( IJOB, WANTQ, WANTZ, SELECT, N, A, LDA, B, LDB, ALPHA, BETA, Q, LDQ, Z, LDZ, M, PL, PR, DIF, WORK, LWORK, IWORK, LIWORK, INFO)
INTEGER | IJOB, N, LDA, LDB, LDQ, LDZ, M, LWORK, IWORK(max(1,LIWORK)), LIWORK, INFO
REAL (KIND=nag_wp) | PL, PR, DIF(*)
COMPLEX (KIND=nag_wp) | A(LDA,*), B(LDB,*), ALPHA(N), BETA(N), Q(LDQ,*), Z(LDZ,*), WORK(max(1,LWORK))
LOGICAL | WANTQ, WANTZ, SELECT(N)
The routine may be called by its LAPACK name ztgsen.

3 Description

F08YUF (ZTGSEN) factorizes the generalized complex n by n matrix pair S,T in generalized Schur form, using a unitary equivalence transformation as
S = Q^ S^ Z^H ,   T= Q^ T^ Z^H ,
where S^,T^ are also in generalized Schur form and have the selected eigenvalues as the leading diagonal elements. The leading columns of Q and Z are the generalized Schur vectors corresponding to the selected eigenvalues and form orthonormal subspaces for the left and right eigenspaces (deflating subspaces) of the pair S,T.
The pair S,T are in generalized Schur form if S and T are upper triangular as returned, for example, by F08XNF (ZGGES), or F08XSF (ZHGEQZ) with JOB='S'. The diagonal elements define the generalized eigenvalues αi,βi, for i=1,2,…,n, of the pair S,T. The eigenvalues are given by
λi = αi / βi ,
but are returned as the pair αi,βi in order to avoid possible overflow in computing λi. Optionally, the routine returns reciprocals of condition number estimates for the selected eigenvalue cluster, p and q, the right and left projection norms, and of deflating subspaces, Difu and Difl. For more information see Sections 2.4.8 and 4.11 of Anderson et al. (1999).
If S and T are the result of a generalized Schur factorization of a matrix pair A,B
A = QS ZH ,   B= QT ZH
then, optionally, the matrices Q and Z can be updated as Q Q^ and Z Z^. Note that the condition numbers of the pair S,T are the same as those of the pair A,B.

4 References

Anderson E, Bai Z, Bischof C, Blackford S, Demmel J, Dongarra J J, Du Croz J J, Greenbaum A, Hammarling S, McKenney A and Sorensen D (1999) LAPACK Users' Guide (3rd Edition) SIAM, Philadelphia http://www.netlib.org/lapack/lug

5 Arguments

1:   IJOB – INTEGERInput
On entry: specifies whether condition numbers are required for the cluster of eigenvalues (p and q) or the deflating subspaces (Difu and Difl).
IJOB=0
Only reorder with respect to SELECT. No extras.
IJOB=1
Reciprocal of norms of ‘projections’ onto left and right eigenspaces with respect to the selected cluster (p and q).
IJOB=2
The upper bounds on Difu and Difl. F-norm-based estimate (DIF 1:2).
IJOB=3
Estimate of Difu and Difl. 1-norm-based estimate (DIF 1:2). About five times as expensive as IJOB=2.
IJOB=4
Compute PL, PR and DIF as in IJOB=0, 1 and 2. Economic version to get it all.
IJOB=5
Compute PL, PR and DIF as in IJOB=0, 1 and 3.
Constraint: 0≤IJOB≤5.
2:   WANTQ – LOGICALInput
On entry: if WANTQ=.TRUE., update the left transformation matrix Q.
If WANTQ=.FALSE., do not update Q.
3:   WANTZ – LOGICALInput
On entry: if WANTZ=.TRUE., update the right transformation matrix Z.
If WANTZ=.FALSE., do not update Z.
4:   SELECT N – LOGICAL arrayInput
On entry: specifies the eigenvalues in the selected cluster. To select an eigenvalue λj, SELECT j must be set to .TRUE..
5:   N – INTEGERInput
On entry: n, the order of the matrices S and T.
Constraint: N≥0.
6:   A LDA* – COMPLEX (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array A must be at least max 1,N.
On entry: the matrix S in the pair S,T.
On exit: the updated matrix S^.
7:   LDA – INTEGERInput
On entry: the first dimension of the array A as declared in the (sub)program from which F08YUF (ZTGSEN) is called.
Constraint: LDA≥max 1,N.
8:   B LDB* – COMPLEX (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array B must be at least max 1,N.
On entry: the matrix T, in the pair S,T.
On exit: the updated matrix T^
9:   LDB – INTEGERInput
On entry: the first dimension of the array B as declared in the (sub)program from which F08YUF (ZTGSEN) is called.
Constraint: LDB≥max 1,N.
10:   ALPHA N – COMPLEX (KIND=nag_wp) arrayOutput
11:   BETA N – COMPLEX (KIND=nag_wp) arrayOutput
On exit: ALPHA and BETA contain diagonal elements of S^ and T^, respectively, when the pair S,T has been reduced to generalized Schur form. ALPHA i/BETA i, for i=1,2,…,N, are the eigenvalues.
12:   Q LDQ* – COMPLEX (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array Q must be at least max 1,N if WANTQ=.TRUE., and at least 1 otherwise.
On entry: if WANTQ=.TRUE., the n by n matrix Q.
On exit: if WANTQ=.TRUE., the updated matrix Q Q^.
If WANTQ=.FALSE., Q is not referenced.
13:   LDQ – INTEGERInput
On entry: the first dimension of the array Q as declared in the (sub)program from which F08YUF (ZTGSEN) is called.
Constraints:
  • if WANTQ=.TRUE., LDQ≥ max 1,N ;
  • otherwise LDQ≥1.
14:   Z LDZ* – COMPLEX (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array Z must be at least max 1,N if WANTZ=.TRUE., and at least 1 otherwise.
On entry: if WANTZ=.TRUE., the n by n matrix Z.
On exit: if WANTZ=.TRUE., the updated matrix Z Z^.
If WANTZ=.FALSE., Z is not referenced.
15:   LDZ – INTEGERInput
On entry: the first dimension of the array Z as declared in the (sub)program from which F08YUF (ZTGSEN) is called.
Constraints:
  • if WANTZ=.TRUE., LDZ≥ max 1,N ;
  • otherwise LDZ≥1.
16:   M – INTEGEROutput
On exit: the dimension of the specified pair of left and right eigenspaces (deflating subspaces).
Constraint: 0≤M≤N.
17:   PL – REAL (KIND=nag_wp)Output
18:   PR – REAL (KIND=nag_wp)Output
On exit: if IJOB=1, 4 or 5, PL and PR are lower bounds on the reciprocal of the norm of ‘projections’ p and q onto left and right eigenspace with respect to the selected cluster. 0<PL, PR≤1.
If M=0 or M=N, PL=PR=1.
If IJOB=0, 2 or 3, PL and PR are not referenced.
19:   DIF* – REAL (KIND=nag_wp) arrayOutput
Note: the dimension of the array DIF must be at least 2.
On exit: if IJOB≥2, DIF 1:2 store the estimates of Difu and Difl.
If IJOB=2 or 4, DIF 1:2 are F-norm-based upper bounds on Difu and Difl.
If IJOB=3 or 5, DIF 1:2 are 1-norm-based estimates of Difu and Difl.
If M=0 or n, DIF 1:2 =A,B F.
If IJOB=0 or 1, DIF is not referenced.
20:   WORK max 1,LWORK – COMPLEX (KIND=nag_wp) arrayWorkspace
On exit: if INFO=0, the real part of WORK 1 contains the minimum value of LWORK required for optimal performance.
21:   LWORK – INTEGERInput
On entry: the dimension of the array WORK as declared in the (sub)program from which F08YUF (ZTGSEN) is called.
If LWORK=-1, a workspace query is assumed; the routine only calculates the minimum sizes of the WORK and IWORK arrays, returns these values as the first entries of the WORK and IWORK arrays, and no error message related to LWORK or LIWORK is issued.
Constraints:
if LWORK≠-1,
  • if IJOB=1, 2 or 4, LWORK≥max 1,2×M×N-M;
  • if IJOB=3 or 5, LWORK≥max 1,4×M×N-M;
  • otherwise LWORK≥1.
22:   IWORK max 1,LIWORK – INTEGER arrayWorkspace
On exit: if INFO=0, IWORK 1 returns the minimum LIWORK.
23:   LIWORK – INTEGERInput
On entry: the dimension of the array IWORK as declared in the (sub)program from which F08YUF (ZTGSEN) is called.
If LIWORK=-1, a workspace query is assumed; the routine only calculates the minimum sizes of the WORK and IWORK arrays, returns these values as the first entries of the WORK and IWORK arrays, and no error message related to LWORK or LIWORK is issued.
Constraints:
if LIWORK≠-1,
  • if IJOB=1, 2 or 4, LIWORK≥N+2;
  • if IJOB=3 or 5, LIWORK≥max N+2,2×M×N-M;
  • otherwise LIWORK≥1.
24:   INFO – INTEGEROutput
On exit: INFO=0 unless the routine detects an error (see Section 6).

6 Error Indicators and Warnings

INFO<0
If INFO=-i, argument i had an illegal value. An explanatory message is output, and execution of the program is terminated.
INFO=1
Reordering of S,T failed because the transformed matrix pair S^,T^ would be too far from generalized Schur form; the problem is very ill-conditioned. S,T may have been partially reordered. If requested, 0 is returned in DIF 1:2, PL and PR.

7 Accuracy

The computed generalized Schur form is nearly the exact generalized Schur form for nearby matrices S+E and T+F, where
E 2 = O⁡ε S 2   and   F 2= O⁡ε T 2 ,
and ε is the machine precision. See Section 4.11 of Anderson et al. (1999) for further details of error bounds for the generalized nonsymmetric eigenproblem, and for information on the condition numbers returned.

8 Parallelism and Performance

F08YUF (ZTGSEN) makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The real analogue of this routine is F08YGF (DTGSEN).

10 Example

This example reorders the generalized Schur factors S and T and update the matrices Q and Z given by
S = 4.0+4.0 i 1.0+1.0 i 1.0+1.0 i 2.0-1.0 i 0.0i+0.0 2.0+1.0 i 1.0+1.0 i 1.0+1.0 i 0.0i+0.0 0.0i+0.0 2.0-1.0 i 1.0+1.0 i 0.0i+0.0 0.0i+0.0 0.0i+0.0 6.0-2.0 i ,
T = 2.0 1.0+1.0 i 1.0+1.0 i 3.0-1.0 i 0.0 1.0 i+0.0 2.0+1.0 i 1.0+1.0 i 0.0 0.0i+0.0 1.0 i+0.0 1.0+1.0 i 0.0 0.0i+0.0 0.0i+0.0 2.0 i+0.0 ,
Q = 1.0 0.0 0.0 0.0 0.0 1.0 0.0 0.0 0.0 0.0 1.0 0.0 0.0 0.0 0.0 1.0   and   Z= 1.0 0.0 0.0 0.0 0.0 1.0 0.0 0.0 0.0 0.0 1.0 0.0 0.0 0.0 0.0 1.0 ,
selecting the second and third generalized eigenvalues to be moved to the leading positions. Bases for the left and right deflating subspaces, and estimates of the condition numbers for the eigenvalues and Frobenius norm based bounds on the condition numbers for the deflating subspaces are also output.

10.1 Program Text

Program Text (f08yufe.f90)

10.2 Program Data

Program Data (f08yufe.d)

10.3 Program Results

Program Results (f08yufe.r)

F08 Chapter Contents
F08 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F08YVF (ZTGSYL) : NAG Library, Mark 26

F08 Chapter Contents
F08 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F08YVF (ZTGSYL)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F08YVF (ZTGSYL) solves the generalized complex triangular Sylvester equations.

2 Specification

SUBROUTINE F08YVF ( TRANS, IJOB, M, N, A, LDA, B, LDB, C, LDC, D, LDD, E, LDE, F, LDF, SCALE, DIF, WORK, LWORK, IWORK, INFO)
INTEGER | IJOB, M, N, LDA, LDB, LDC, LDD, LDE, LDF, LWORK, IWORK(M+N+2), INFO
REAL (KIND=nag_wp) | SCALE, DIF
COMPLEX (KIND=nag_wp) | A(LDA,*), B(LDB,*), C(LDC,*), D(LDD,*), E(LDE,*), F(LDF,*), WORK(max(1,LWORK))
CHARACTER(1) | TRANS
The routine may be called by its LAPACK name ztgsyl.

3 Description

F08YVF (ZTGSYL) solves either the generalized complex Sylvester equations
AR-LB =αC DR-LE =αF, (1)
or the equations
AH R+DH L =αC R BH+L EH =-α F, (2)
where the pair A,D are given m by m matrices in generalized Schur form, B,E are given n by n matrices in generalized Schur form and C,F are given m by n matrices. The pair R,L are the m by n solution matrices, and α is an output scaling factor determined by the routine to avoid overflow in computing R,L.
Equations (1) are equivalent to equations of the form
Zx=αb ,
where
Z = I⊗A-BH⊗I I⊗D-EH⊗I
and ⊗ is the Kronecker product. Equations (2) are then equivalent to
ZH y = αb .
The pair S,T are in generalized Schur form if S and T are upper triangular as returned, for example, by F08XNF (ZGGES), or F08XSF (ZHGEQZ) with JOB='S'.
Optionally, the routine estimates Dif A,D,B,E, the separation between the matrix pairs A,D and B,E, which is the smallest singular value of Z. The estimate can be based on either the Frobenius norm, or the 1-norm. The 1-norm estimate can be three to ten times more expensive than the Frobenius norm estimate, but makes the condition estimation uniform with the nonsymmetric eigenproblem. The Frobenius norm estimate provides a low cost, but equally reliable estimate. For more information see Sections 2.4.8.3 and 4.11.1.3 of Anderson et al. (1999) and Kågström and Poromaa (1996).

4 References

Anderson E, Bai Z, Bischof C, Blackford S, Demmel J, Dongarra J J, Du Croz J J, Greenbaum A, Hammarling S, McKenney A and Sorensen D (1999) LAPACK Users' Guide (3rd Edition) SIAM, Philadelphia http://www.netlib.org/lapack/lug
Kågström B (1994) A perturbation analysis of the generalized Sylvester equation AR-LB,DR-LE=c,F SIAM J. Matrix Anal. Appl. 15 1045–1060
Kågström B and Poromaa P (1996) LAPACK-style algorithms and software for solving the generalized Sylvester equation and estimating the separation between regular matrix pairs ACM Trans. Math. Software 22 78–103

5 Arguments

1:   TRANS – CHARACTER(1)Input
On entry: if TRANS='N', solve the generalized Sylvester equation (1).
If TRANS='C', solve the ‘conjugate transposed’ system (2).
Constraint: TRANS='N' or 'C'.
2:   IJOB – INTEGERInput
On entry: specifies what kind of functionality is to be performed when TRANS='N'.
IJOB=0
Solve (1) only.
IJOB=1
The functionality of IJOB=0 and 3.
IJOB=2
The functionality of IJOB=0 and 4.
IJOB=3
Only an estimate of Dif A,D,B,E is computed based on the Frobenius norm.
IJOB=4
Only an estimate of Dif A,D,B,E is computed based on the 1-norm.
If TRANS='C', IJOB is not referenced.
Constraint: if TRANS='N', 0≤IJOB≤4.
3:   M – INTEGERInput
On entry: m, the order of the matrices A and D, and the row dimension of the matrices C, F, R and L.
Constraint: M≥0.
4:   N – INTEGERInput
On entry: n, the order of the matrices B and E, and the column dimension of the matrices C, F, R and L.
Constraint: N≥0.
5:   A LDA* – COMPLEX (KIND=nag_wp) arrayInput
Note: the second dimension of the array A must be at least max 1,M.
On entry: the upper triangular matrix A.
6:   LDA – INTEGERInput
On entry: the first dimension of the array A as declared in the (sub)program from which F08YVF (ZTGSYL) is called.
Constraint: LDA≥max 1,M.
7:   B LDB* – COMPLEX (KIND=nag_wp) arrayInput
Note: the second dimension of the array B must be at least max 1,N.
On entry: the upper triangular matrix B.
8:   LDB – INTEGERInput
On entry: the first dimension of the array B as declared in the (sub)program from which F08YVF (ZTGSYL) is called.
Constraint: LDB≥max 1,N.
9:   C LDC* – COMPLEX (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array C must be at least max 1,N.
On entry: contains the right-hand-side matrix C.
On exit: if IJOB=0, 1 or 2, C is overwritten by the solution matrix R.
If TRANS='N' and IJOB=3 or 4, C holds R, the solution achieved during the computation of the Dif estimate.
10:   LDC – INTEGERInput
On entry: the first dimension of the array C as declared in the (sub)program from which F08YVF (ZTGSYL) is called.
Constraint: LDC≥max 1,M.
11:   D LDD* – COMPLEX (KIND=nag_wp) arrayInput
Note: the second dimension of the array D must be at least max 1,M.
On entry: the upper triangular matrix D.
12:   LDD – INTEGERInput
On entry: the first dimension of the array D as declared in the (sub)program from which F08YVF (ZTGSYL) is called.
Constraint: LDD≥max 1,M.
13:   E LDE* – COMPLEX (KIND=nag_wp) arrayInput
Note: the second dimension of the array E must be at least max 1,N.
On entry: the upper triangular matrix E.
14:   LDE – INTEGERInput
On entry: the first dimension of the array E as declared in the (sub)program from which F08YVF (ZTGSYL) is called.
Constraint: LDE≥max 1,N.
15:   F LDF* – COMPLEX (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array F must be at least max 1,N.
On entry: contains the right-hand side matrix F.
On exit: if IJOB=0, 1 or 2, F is overwritten by the solution matrix L.
If TRANS='N' and IJOB=3 or 4, F holds L, the solution achieved during the computation of the Dif estimate.
16:   LDF – INTEGERInput
On entry: the first dimension of the array F as declared in the (sub)program from which F08YVF (ZTGSYL) is called.
Constraint: LDF≥max 1,M.
17:   SCALE – REAL (KIND=nag_wp)Output
On exit: α, the scaling factor in (1) or (2).
If 0<SCALE<1, C and F hold the solutions R and L, respectively, to a slightly perturbed system but the input arrays A, B, D and E have not been changed.
If SCALE=0, C and F hold the solutions R and L, respectively, to the homogeneous system with C=F=0. In this case DIF is not referenced.
Normally, SCALE=1.
18:   DIF – REAL (KIND=nag_wp)Output
On exit: the estimate of Dif. If IJOB=0, DIF is not referenced.
19:   WORK max 1,LWORK – COMPLEX (KIND=nag_wp) arrayWorkspace
On exit: if INFO=0, the real part of WORK 1 contains the minimum value of LWORK required for optimal performance.
20:   LWORK – INTEGERInput
On entry: the dimension of the array WORK as declared in the (sub)program from which F08YVF (ZTGSYL) is called.
If LWORK=-1, a workspace query is assumed; the routine only calculates the minimum size of the WORK array, returns this value as the first entry of the WORK array, and no error message related to LWORK is issued.
Constraints:
if LWORK≠-1,
  • if TRANS='N' and IJOB=1 or 2, LWORK≥2×M×N;
  • otherwise LWORK≥1.
21:   IWORK M+N+2 – INTEGER arrayWorkspace
22:   INFO – INTEGEROutput
On exit: INFO=0 unless the routine detects an error (see Section 6).

6 Error Indicators and Warnings

INFO<0
If INFO=-i, argument i had an illegal value. An explanatory message is output, and execution of the program is terminated.
INFO>0
A,D and B,E have common or close eigenvalues and so no solution could be computed.

7 Accuracy

See Kågström (1994) for a perturbation analysis of the generalized Sylvester equation.

8 Parallelism and Performance

F08YVF (ZTGSYL) makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The total number of floating-point operations needed to solve the generalized Sylvester equations is approximately 8 mn n+m. The Frobenius norm estimate of Dif does not require additional significant computation, but the 1-norm estimate is typically five times more expensive.
The real analogue of this routine is F08YHF (DTGSYL).

10 Example

This example solves the generalized Sylvester equations
AR-LB =αC DR-LE =αF,
where
A = 4.0+4.0 i 1.0+1.0 i 1.0+1.0 i 2.0-1.0 i 0.0i+0.0 2.0+1.0 i 1.0+1.0 i 1.0+1.0 i 0.0i+0.0 0.0i+0.0 2.0-1.0 i 1.0+1.0 i 0.0i+0.0 0.0i+0.0 0.0i+0.0 6.0-2.0 i ,
B = 2.0 1.0+1.0 i 1.0+1.0 i 3.0-1.0 i 0.0 1.0 i+0.0 2.0+1.0 i 1.0+1.0 i 0.0 0.0i+0.0 1.0 i+0.0 1.0+1.0 i 0.0 0.0i+0.0 0.0i+0.0 2.0 i+0.0 ,
D = 1.0+1.0 i 1.0-1.0 i 1.0+1.0 i 1.0-1.0 i 0.0i+0.0 6.0-4.0 i 1.0-1.0 i 1.0+1.0 i 0.0i+0.0 0.0i+0.0 2.0+4.0 i 1.0-1.0 i 0.0i+0.0 0.0i+0.0 0.0i+0.0 2.0+3.0 i ,
E = 1.0 1.0+1.0 i 1.0-1.0 i 1.0+1.0 i 0.0 2.0 i+0.0 1.0+1.0 i 1.0-1.0 i 0.0 0.0i+0.0 2.0 i+0.0 1.0+1.0 i 0.0 0.0i+0.0 0.0i+0.0 1.0 i+0.0 ,
C = -13.0+9.0 i 2.0+8.0 i -2.0+8.0 i -2.0+5.0 i -9.0-1.0 i 0.0+5.0 i -7.0-3.0 i -6.0-0.0 i -1.0+1.0 i 4.0+2.0 i 4.0-5.0 i 9.0-5.0 i -6.0+6.0 i 9.0+1.0 i -2.0+4.0 i 22.0-8.0 i
and
F = -6.0+0 5.0 i 4.0-4.0 i -3.0+11.0 i 3.0-0 7.0 i -5.0+11.0 i 12.0-4.0 i -2.0+0 2.0 i 0.0+14.0 i -5.0-0 1.0 i 0.0+4.0 i -2.0+10.0 i 3.0-0 1.0 i -6.0-0 2.0 i 1.0+1.0 i -7.0-0 3.0 i 4.0+0 7.0 i .

10.1 Program Text

Program Text (f08yvfe.f90)

10.2 Program Data

Program Data (f08yvfe.d)

10.3 Program Results

Program Results (f08yvfe.r)

F08 Chapter Contents
F08 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F08YXF (ZTGEVC) : NAG Library, Mark 26

F08 Chapter Contents
F08 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F08YXF (ZTGEVC)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F08YXF (ZTGEVC) computes some or all of the right and/or left generalized eigenvectors of a pair of complex upper triangular matrices A,B.

2 Specification

SUBROUTINE F08YXF ( SIDE, HOWMNY, SELECT, N, A, LDA, B, LDB, VL, LDVL, VR, LDVR, MM, M, WORK, RWORK, INFO)
INTEGER | N, LDA, LDB, LDVL, LDVR, MM, M, INFO
REAL (KIND=nag_wp) | RWORK(2*N)
COMPLEX (KIND=nag_wp) | A(LDA,*), B(LDB,*), VL(LDVL,*), VR(LDVR,*), WORK(2*N)
LOGICAL | SELECT(*)
CHARACTER(1) | SIDE, HOWMNY
The routine may be called by its LAPACK name ztgevc.

3 Description

F08YXF (ZTGEVC) computes some or all of the right and/or left generalized eigenvectors of the matrix pair A,B which is assumed to be in upper triangular form. If the matrix pair A,B is not upper triangular then the routine F08XSF (ZHGEQZ) should be called before invoking F08YXF (ZTGEVC).
The right generalized eigenvector x and the left generalized eigenvector y of A,B corresponding to a generalized eigenvalue λ are defined by
A-λB x=0
and
yH A-λ B=0.
If a generalized eigenvalue is determined as 0/0, which is due to zero diagonal elements at the same locations in both A and B, a unit vector is returned as the corresponding eigenvector.
Note that the generalized eigenvalues are computed using F08XSF (ZHGEQZ) but F08YXF (ZTGEVC) does not explicitly require the generalized eigenvalues to compute eigenvectors. The ordering of the eigenvectors is based on the ordering of the eigenvalues as computed by F08YXF (ZTGEVC).
If all eigenvectors are requested, the routine may either return the matrices X and/or Y of right or left eigenvectors of A,B, or the products ZX and/or QY, where Z and Q are two matrices supplied by you. Usually, Q and Z are chosen as the unitary matrices returned by F08XSF (ZHGEQZ). Equivalently, Q and Z are the left and right Schur vectors of the matrix pair supplied to F08XSF (ZHGEQZ). In that case, QY and ZX are the left and right generalized eigenvectors, respectively, of the matrix pair supplied to F08XSF (ZHGEQZ).

4 References

Anderson E, Bai Z, Bischof C, Blackford S, Demmel J, Dongarra J J, Du Croz J J, Greenbaum A, Hammarling S, McKenney A and Sorensen D (1999) LAPACK Users' Guide (3rd Edition) SIAM, Philadelphia
Golub G H and Van Loan C F (1996) Matrix Computations (3rd Edition) Johns Hopkins University Press, Baltimore
Moler C B and Stewart G W (1973) An algorithm for generalized matrix eigenproblems SIAM J. Numer. Anal. 10 241–256
Stewart G W and Sun J-G (1990) Matrix Perturbation Theory Academic Press, London

5 Arguments

1:   SIDE – CHARACTER(1)Input
On entry: specifies the required sets of generalized eigenvectors.
SIDE='R'
Only right eigenvectors are computed.
SIDE='L'
Only left eigenvectors are computed.
SIDE='B'
Both left and right eigenvectors are computed.
Constraint: SIDE='B', 'L' or 'R'.
2:   HOWMNY – CHARACTER(1)Input
On entry: specifies further details of the required generalized eigenvectors.
HOWMNY='A'
All right and/or left eigenvectors are computed.
HOWMNY='B'
All right and/or left eigenvectors are computed; they are backtransformed using the input matrices supplied in arrays VR and/or VL.
HOWMNY='S'
Selected right and/or left eigenvectors, defined by the array SELECT, are computed.
Constraint: HOWMNY='A', 'B' or 'S'.
3:   SELECT* – LOGICAL arrayInput
Note: the dimension of the array SELECT must be at least max 1,N if HOWMNY='S', and at least 1 otherwise.
On entry: specifies the eigenvectors to be computed if HOWMNY='S'. To select the generalized eigenvector corresponding to the jth generalized eigenvalue, the jth element of SELECT should be set to .TRUE..
Constraint: if HOWMNY='S', SELECT j=.TRUE. or .FALSE., for j=1,2,…,n.
4:   N – INTEGERInput
On entry: n, the order of the matrices A and B.
Constraint: N≥0.
5:   A LDA* – COMPLEX (KIND=nag_wp) arrayInput
Note: the second dimension of the array A must be at least max 1,N.
On entry: the matrix A must be in upper triangular form. Usually, this is the matrix A returned by F08XSF (ZHGEQZ).
6:   LDA – INTEGERInput
On entry: the first dimension of the array A as declared in the (sub)program from which F08YXF (ZTGEVC) is called.
Constraint: LDA≥max 1,N.
7:   B LDB* – COMPLEX (KIND=nag_wp) arrayInput
Note: the second dimension of the array B must be at least max 1,N.
On entry: the matrix B must be in upper triangular form with non-negative real diagonal elements. Usually, this is the matrix B returned by F08XSF (ZHGEQZ).
8:   LDB – INTEGERInput
On entry: the first dimension of the array B as declared in the (sub)program from which F08YXF (ZTGEVC) is called.
Constraint: LDB≥max 1,N.
9:   VL LDVL* – COMPLEX (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array VL must be at least max 1,MM if SIDE='L' or 'B' and at least 1 if SIDE='R'.
On entry: if HOWMNY='B' and SIDE='L' or 'B', VL must be initialized to an n by n matrix Q. Usually, this is the unitary matrix Q of left Schur vectors returned by F08XSF (ZHGEQZ).
On exit: if SIDE='L' or 'B', VL contains:
  • if HOWMNY='A', the matrix Y of left eigenvectors of A,B;
  • if HOWMNY='B', the matrix QY;
  • if HOWMNY='S', the left eigenvectors of A,B specified by SELECT, stored consecutively in the columns of the array VL, in the same order as their corresponding eigenvalues.
10:   LDVL – INTEGERInput
On entry: the first dimension of the array VL as declared in the (sub)program from which F08YXF (ZTGEVC) is called.
Constraints:
  • if SIDE='L' or 'B', LDVL≥ max 1,N ;
  • if SIDE='R', LDVL≥1.
11:   VR LDVR* – COMPLEX (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array VR must be at least max 1,MM if SIDE='R' or 'B' and at least 1 if SIDE='L'.
On entry: if HOWMNY='B' and SIDE='R' or 'B', VR must be initialized to an n by n matrix Z. Usually, this is the unitary matrix Z of right Schur vectors returned by F08XEF (DHGEQZ).
On exit: if SIDE='R' or 'B', VR contains:
  • if HOWMNY='A', the matrix X of right eigenvectors of A,B;
  • if HOWMNY='B', the matrix ZX;
  • if HOWMNY='S', the right eigenvectors of A,B specified by SELECT, stored consecutively in the columns of the array VR, in the same order as their corresponding eigenvalues.
12:   LDVR – INTEGERInput
On entry: the first dimension of the array VR as declared in the (sub)program from which F08YXF (ZTGEVC) is called.
Constraints:
  • if SIDE='R' or 'B', LDVR≥ max 1,N ;
  • if SIDE='L', LDVR≥1.
13:   MM – INTEGERInput
On entry: the number of columns in the arrays VL and/or VR.
Constraints:
  • if HOWMNY='A' or 'B', MM≥N;
  • if HOWMNY='S', MM must not be less than the number of requested eigenvectors.
14:   M – INTEGEROutput
On exit: the number of columns in the arrays VL and/or VR actually used to store the eigenvectors. If HOWMNY='A' or 'B', M is set to N. Each selected eigenvector occupies one column.
15:   WORK 2×N – COMPLEX (KIND=nag_wp) arrayWorkspace
16:   RWORK 2×N – REAL (KIND=nag_wp) arrayWorkspace
17:   INFO – INTEGEROutput
On exit: INFO=0 unless the routine detects an error (see Section 6).

6 Error Indicators and Warnings

INFO<0
If INFO=-i, argument i had an illegal value. An explanatory message is output, and execution of the program is terminated.

7 Accuracy

It is beyond the scope of this manual to summarise the accuracy of the solution of the generalized eigenvalue problem. Interested readers should consult Section 4.11 of the LAPACK Users' Guide (see Anderson et al. (1999)) and Chapter 6 of Stewart and Sun (1990).

8 Parallelism and Performance

F08YXF (ZTGEVC) makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

F08YXF (ZTGEVC) is the sixth step in the solution of the complex generalized eigenvalue problem and is usually called after F08XSF (ZHGEQZ).
The real analogue of this routine is F08YKF (DTGEVC).

10 Example

This example computes the α and β arguments, which defines the generalized eigenvalues and the corresponding left and right eigenvectors, of the matrix pair A,B given by
A = 1.0+3.0 i 1.0+4.0 i 1.0+5.0 i 1.0+6.0 i 2.0+2.0 i 4.0+3.0 i 8.0+4.0 i 16.0+5.0 i 3.0+1.0 i 9.0+2.0 i 27.0+3.0 i 81.0+4.0 i 4.0+0.0 i 16.0+1.0 i 64.0+2.0 i 256.0+3.0 i
and
B = 1.0+0.0 i 2.0+1.0 i 3.0+2.0 i 4.0+3.0 i 1.0+1.0 i 4.0+2.0 i 9.0+3.0 i 16.0+4.0 i 1.0+2.0 i 8.0+3.0 i 27.0+4.0 i 64.0+5.0 i 1.0+3.0 i 16.0+4.0 i 81.0+5.0 i 256.0+6.0 i .
To compute generalized eigenvalues, it is required to call five routines: F08WVF (ZGGBAL) to balance the matrix, F08ASF (ZGEQRF) to perform the QR factorization of B, F08AUF (ZUNMQR) to apply Q to A, F08WSF (ZGGHRD) to reduce the matrix pair to the generalized Hessenberg form and F08XSF (ZHGEQZ) to compute the eigenvalues via the QZ algorithm.
The computation of generalized eigenvectors is done by calling F08YXF (ZTGEVC) to compute the eigenvectors of the balanced matrix pair. The routine F08WWF (ZGGBAK) is called to backward transform the eigenvectors to the user-supplied matrix pair. If both left and right eigenvectors are required then F08WWF (ZGGBAK) must be called twice.

10.1 Program Text

Program Text (f08yxfe.f90)

10.2 Program Data

Program Data (f08yxfe.d)

10.3 Program Results

Program Results (f08yxfe.r)

F08 Chapter Contents
F08 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F08YYF (ZTGSNA) : NAG Library, Mark 26

F08 Chapter Contents
F08 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F08YYF (ZTGSNA)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F08YYF (ZTGSNA) estimates condition numbers for specified eigenvalues and/or eigenvectors of a complex matrix pair in generalized Schur form.

2 Specification

SUBROUTINE F08YYF ( JOB, HOWMNY, SELECT, N, A, LDA, B, LDB, VL, LDVL, VR, LDVR, S, DIF, MM, M, WORK, LWORK, IWORK, INFO)
INTEGER | N, LDA, LDB, LDVL, LDVR, MM, M, LWORK, IWORK(*), INFO
REAL (KIND=nag_wp) | S(*), DIF(*)
COMPLEX (KIND=nag_wp) | A(LDA,*), B(LDB,*), VL(LDVL,*), VR(LDVR,*), WORK(max(1,LWORK))
LOGICAL | SELECT(*)
CHARACTER(1) | JOB, HOWMNY
The routine may be called by its LAPACK name ztgsna.

3 Description

F08YYF (ZTGSNA) estimates condition numbers for specified eigenvalues and/or right eigenvectors of an n by n matrix pair S,T in generalized Schur form. The routine actually returns estimates of the reciprocals of the condition numbers in order to avoid possible overflow.
The pair S,T are in generalized Schur form if S and T are upper triangular as returned, for example, by F08XNF (ZGGES) or F08XPF (ZGGESX), or F08XSF (ZHGEQZ) with JOB='S'. The diagonal elements define the generalized eigenvalues αi,βi, for i=1,2,…,n, of the pair S,T and the eigenvalues are given by
λi = αi / βi ,
so that
βi S xi = αi T xi   or   S xi = λi T xi ,
where xi is the corresponding (right) eigenvector.
If S and T are the result of a generalized Schur factorization of a matrix pair A,B
A = QS ZH ,   B = QT ZH
then the eigenvalues and condition numbers of the pair S,T are the same as those of the pair A,B.
Let α,β≠0,0 be a simple generalized eigenvalue of A,B. Then the reciprocal of the condition number of the eigenvalue λ=α/β is defined as
s λ= yH Ax 2 + yH Bx 2 1/2 x 2 y 2 ,
where x and y are the right and left eigenvectors of A,B corresponding to λ. If both α and β are zero, then A,B is singular and s λ=-1 is returned.
If U and V are unitary transformations such that
UH A,B V= S,T = α * 0 S 22 β * 0 T 22 ,
where S 22 and T 22 are n-1 by n-1 matrices, then the reciprocal condition number is given by
Dif x ≡ Dif y = Dif α,β,S 22,T 22 = σmin Z ,
where σmin Z denotes the smallest singular value of the 2 n-1 by 2 n-1 matrix
Z = α⊗I -1⊗S 22 β⊗I -1⊗T 22
and ⊗ is the Kronecker product.
See Sections 2.4.8 and 4.11 of Anderson et al. (1999) and Kågström and Poromaa (1996) for further details and information.

4 References

Anderson E, Bai Z, Bischof C, Blackford S, Demmel J, Dongarra J J, Du Croz J J, Greenbaum A, Hammarling S, McKenney A and Sorensen D (1999) LAPACK Users' Guide (3rd Edition) SIAM, Philadelphia http://www.netlib.org/lapack/lug
Kågström B and Poromaa P (1996) LAPACK-style algorithms and software for solving the generalized Sylvester equation and estimating the separation between regular matrix pairs ACM Trans. Math. Software 22 78–103

5 Arguments

1:   JOB – CHARACTER(1)Input
On entry: indicates whether condition numbers are required for eigenvalues and/or eigenvectors.
JOB='E'
Condition numbers for eigenvalues only are computed.
JOB='V'
Condition numbers for eigenvectors only are computed.
JOB='B'
Condition numbers for both eigenvalues and eigenvectors are computed.
Constraint: JOB='E', 'V' or 'B'.
2:   HOWMNY – CHARACTER(1)Input
On entry: indicates how many condition numbers are to be computed.
HOWMNY='A'
Condition numbers for all eigenpairs are computed.
HOWMNY='S'
Condition numbers for selected eigenpairs (as specified by SELECT) are computed.
Constraint: HOWMNY='A' or 'S'.
3:   SELECT* – LOGICAL arrayInput
Note: the dimension of the array SELECT must be at least max 1,N if HOWMNY='S', and at least 1 otherwise.
On entry: specifies the eigenpairs for which condition numbers are to be computed if HOWMNY='S'. To select condition numbers for the eigenpair corresponding to the eigenvalue λj, SELECT j must be set to .TRUE..
If HOWMNY='A', SELECT is not referenced.
4:   N – INTEGERInput
On entry: n, the order of the matrix pair S,T.
Constraint: N≥0.
5:   A LDA* – COMPLEX (KIND=nag_wp) arrayInput
Note: the second dimension of the array A must be at least N.
On entry: the upper triangular matrix S.
6:   LDA – INTEGERInput
On entry: the first dimension of the array A as declared in the (sub)program from which F08YYF (ZTGSNA) is called.
Constraint: LDA≥N.
7:   B LDB* – COMPLEX (KIND=nag_wp) arrayInput
Note: the second dimension of the array B must be at least N.
On entry: the upper triangular matrix T.
8:   LDB – INTEGERInput
On entry: the first dimension of the array B as declared in the (sub)program from which F08YYF (ZTGSNA) is called.
Constraint: LDB≥N.
9:   VL LDVL* – COMPLEX (KIND=nag_wp) arrayInput
Note: the second dimension of the array VL must be at least max 1,MM if JOB='E' or 'B', and at least 1 otherwise.
On entry: if JOB='E' or 'B', VL must contain left eigenvectors of S,T, corresponding to the eigenpairs specified by HOWMNY and SELECT. The eigenvectors must be stored in consecutive columns of VL, as returned by F08WNF (ZGGEV) or F08YXF (ZTGEVC).
If JOB='V', VL is not referenced.
10:   LDVL – INTEGERInput
On entry: the first dimension of the array VL as declared in the (sub)program from which F08YYF (ZTGSNA) is called.
Constraints:
  • if JOB='E' or 'B', LDVL≥ max 1,N ;
  • otherwise LDVL≥1.
11:   VR LDVR* – COMPLEX (KIND=nag_wp) arrayInput
Note: the second dimension of the array VR must be at least max 1,MM if JOB='E' or 'B', and at least 1 otherwise.
On entry: if JOB='E' or 'B', VR must contain right eigenvectors of S,T, corresponding to the eigenpairs specified by HOWMNY and SELECT. The eigenvectors must be stored in consecutive columns of VR, as returned by F08WNF (ZGGEV) or F08YXF (ZTGEVC).
If JOB='V', VR is not referenced.
12:   LDVR – INTEGERInput
On entry: the first dimension of the array VR as declared in the (sub)program from which F08YYF (ZTGSNA) is called.
Constraints:
  • if JOB='E' or 'B', LDVR≥ max 1,N ;
  • otherwise LDVR≥1.
13:   S* – REAL (KIND=nag_wp) arrayOutput
Note: the dimension of the array S must be at least max 1,MM if JOB='E' or 'B', and at least 1 otherwise.
On exit: if JOB='E' or 'B', the reciprocal condition numbers of the selected eigenvalues, stored in consecutive elements of the array.
If JOB='V', S is not referenced.
14:   DIF* – REAL (KIND=nag_wp) arrayOutput
Note: the dimension of the array DIF must be at least max 1,MM if JOB='V' or 'B', and at least 1 otherwise.
On exit: if JOB='V' or 'B', the estimated reciprocal condition numbers of the selected eigenvectors, stored in consecutive elements of the array. If the eigenvalues cannot be reordered to compute DIF j, DIF j is set to 0; this can only occur when the true value would be very small anyway.
If JOB='E', DIF is not referenced.
15:   MM – INTEGERInput
On entry: the number of elements in the arrays S and DIF.
Constraints:
  • if HOWMNY='A', MM≥N;
  • otherwise MM≥​ the number of selected eigenvalues.
16:   M – INTEGEROutput
On exit: the number of elements of the arrays S and DIF used to store the specified condition numbers; for each selected eigenvalue one element is used.
If HOWMNY='A', M is set to N.
17:   WORK max 1,LWORK – COMPLEX (KIND=nag_wp) arrayWorkspace
On exit: if INFO=0, the real part of WORK 1 contains the minimum value of LWORK required for optimal performance.
18:   LWORK – INTEGERInput
On entry: the dimension of the array WORK as declared in the (sub)program from which F08YYF (ZTGSNA) is called.
If LWORK=-1, a workspace query is assumed; the routine only calculates the minimum size of the WORK array, returns this value as the first entry of the WORK array, and no error message related to LWORK is issued.
Constraints:
if LWORK≠-1,
  • if JOB='V' or 'B', LWORK≥max 1,2×N×N;
  • otherwise LWORK≥max 1,N.
19:   IWORK* – INTEGER arrayWorkspace
Note: the dimension of the array IWORK must be at least N+2.
If JOB='E', IWORK is not referenced.
20:   INFO – INTEGEROutput
On exit: INFO=0 unless the routine detects an error (see Section 6).

6 Error Indicators and Warnings

INFO<0
If INFO=-i, argument i had an illegal value. An explanatory message is output, and execution of the program is terminated.

7 Accuracy

None.

8 Parallelism and Performance

F08YYF (ZTGSNA) makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

An approximate asymptotic error bound on the chordal distance between the computed eigenvalue λ~ and the corresponding exact eigenvalue λ is
χ λ~,λ ≤ ε A,B F / S λ
where ε is the machine precision.
An approximate asymptotic error bound for the right or left computed eigenvectors x~ or y~ corresponding to the right and left eigenvectors x and y is given by
θ z~,z ≤ ε A,B F / Dif .
The real analogue of this routine is F08YLF (DTGSNA).

10 Example

This example estimates condition numbers and approximate error estimates for all the eigenvalues and right eigenvectors of the pair S,T given by
S = 4.0+4.0 i 1.0+1.0 i 1.0+1.0 i 2.0-1.0 i 0.0i+0.0 2.0+1.0 i 1.0+1.0 i 1.0+1.0 i 0.0i+0.0 0.0i+0.0 2.0-1.0 i 1.0+1.0 i 0.0i+0.0 0.0i+0.0 0.0i+0.0 6.0-2.0 i
and
T = 2.0 1.0+1.0 i 1.0+1.0 i 3.0-1.0 i 0.0 1.0 i+0.0 2.0+1.0 i 1.0+1.0 i 0.0 0.0i+0.0 1.0 i+0.0 1.0+1.0 i 0.0 0.0i+0.0 0.0i+0.0 2.0 i+0.0 .
The eigenvalues and eigenvectors are computed by calling F08YXF (ZTGEVC).

10.1 Program Text

Program Text (f08yyfe.f90)

10.2 Program Data

Program Data (f08yyfe.d)

10.3 Program Results

Program Results (f08yyfe.r)

F08 Chapter Contents
F08 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F08ZAF (DGGLSE) : NAG Library, Mark 26

F08 Chapter Contents
F08 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F08ZAF (DGGLSE)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F08ZAF (DGGLSE) solves a real linear equality-constrained least squares problem.

2 Specification

SUBROUTINE F08ZAF ( M, N, P, A, LDA, B, LDB, C, D, X, WORK, LWORK, INFO)
INTEGER | M, N, P, LDA, LDB, LWORK, INFO
REAL (KIND=nag_wp) | A(LDA,*), B(LDB,*), C(M), D(P), X(N), WORK(max(1,LWORK))
The routine may be called by its LAPACK name dgglse.

3 Description

F08ZAF (DGGLSE) solves the real linear equality-constrained least squares (LSE) problem
minimize x c-Ax 2  subject to  Bx=d
where A is an m by n matrix, B is a p by n matrix, c is an m element vector and d is a p element vector. It is assumed that p≤n≤m+p, rank B=p and rank E=n, where E= A B . These conditions ensure that the LSE problem has a unique solution, which is obtained using a generalized RQ factorization of the matrices B and A.

4 References

Anderson E, Bai Z, Bischof C, Blackford S, Demmel J, Dongarra J J, Du Croz J J, Greenbaum A, Hammarling S, McKenney A and Sorensen D (1999) LAPACK Users' Guide (3rd Edition) SIAM, Philadelphia
Anderson E, Bai Z and Dongarra J (1992) Generalized QR factorization and its applications Linear Algebra Appl. (Volume 162–164) 243–271
Eldèn L (1980) Perturbation theory for the least squares problem with linear equality constraints SIAM J. Numer. Anal. 17 338–350

5 Arguments

1:   M – INTEGERInput
On entry: m, the number of rows of the matrix A.
Constraint: M≥0.
2:   N – INTEGERInput
On entry: n, the number of columns of the matrices A and B.
Constraint: N≥0.
3:   P – INTEGERInput
On entry: p, the number of rows of the matrix B.
Constraint: 0≤P≤N≤M+P.
4:   A LDA* – REAL (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array A must be at least max 1,N.
On entry: the m by n matrix A.
On exit: A is overwritten.
5:   LDA – INTEGERInput
On entry: the first dimension of the array A as declared in the (sub)program from which F08ZAF (DGGLSE) is called.
Constraint: LDA≥max 1,M.
6:   B LDB* – REAL (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array B must be at least max 1,N.
On entry: the p by n matrix B.
On exit: B is overwritten.
7:   LDB – INTEGERInput
On entry: the first dimension of the array B as declared in the (sub)program from which F08ZAF (DGGLSE) is called.
Constraint: LDB≥max 1,P.
8:   C M – REAL (KIND=nag_wp) arrayInput/Output
On entry: the right-hand side vector c for the least squares part of the LSE problem.
On exit: the residual sum of squares for the solution vector x is given by the sum of squares of elements C N-P+1,C N-P+2,…,C M; the remaining elements are overwritten.
9:   D P – REAL (KIND=nag_wp) arrayInput/Output
On entry: the right-hand side vector d for the equality constraints.
On exit: D is overwritten.
10:   X N – REAL (KIND=nag_wp) arrayOutput
On exit: the solution vector x of the LSE problem.
11:   WORK max 1,LWORK – REAL (KIND=nag_wp) arrayWorkspace
On exit: if INFO=0, WORK 1 contains the minimum value of LWORK required for optimal performance.
12:   LWORK – INTEGERInput
On entry: the dimension of the array WORK as declared in the (sub)program from which F08ZAF (DGGLSE) is called.
If LWORK=-1, a workspace query is assumed; the routine only calculates the optimal size of the WORK array, returns this value as the first entry of the WORK array, and no error message related to LWORK is issued.
Suggested value: for optimal performance, LWORK≥P+min M,N+max M,N×nb, where nb is the optimal block size.
Constraint: LWORK≥ max 1,M+N+P or LWORK=-1.
13:   INFO – INTEGEROutput
On exit: INFO=0 unless the routine detects an error (see Section 6).

6 Error Indicators and Warnings

INFO<0
If INFO=-i, argument i had an illegal value. An explanatory message is output, and execution of the program is terminated.
INFO=1
The upper triangular factor R associated with B in the generalized RQ factorization of the pair B,A is singular, so that rank B<p; the least squares solution could not be computed.
INFO=2
The N-P by N-P part of the upper trapezoidal factor T associated with A in the generalized RQ factorization of the pair B,A is singular, so that the rank of the matrix (E) comprising the rows of A and B is less than n; the least squares solutions could not be computed.

7 Accuracy

For an error analysis, see Anderson et al. (1992) and Eldèn (1980). See also Section 4.6 of Anderson et al. (1999).

8 Parallelism and Performance

F08ZAF (DGGLSE) is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
F08ZAF (DGGLSE) makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

When m≥n=p, the total number of floating-point operations is approximately 23 n 2 6 m+n; if p≪n, the number reduces to approximately 23 n 2 3 m-n.
E04NCF/E04NCA may also be used to solve LSE problems. It differs from F08ZAF (DGGLSE) in that it uses an iterative (rather than direct) method, and that it allows general upper and lower bounds to be specified for the variables x and the linear constraints Bx.

10 Example

This example solves the least squares problem
minimize x c-Ax 2   subject to   Bx=d
where
c = -1.50 -2.14 1.23 -0.54 -1.68 0.82 ,
A = -0.57 -1.28 -0.39 0.25 -1.93 1.08 -0.31 -2.14 2.30 0.24 0.40 -0.35 -1.93 0.64 -0.66 0.08 0.15 0.30 0.15 -2.13 -0.02 1.03 -1.43 0.50 ,
B = 1.0 0 -1.0 0 0 1.0 0 -1.0
and
d = 0 0 .
The constraints Bx=d correspond to x 1 = x 3 and x 2 = x 4 .

10.1 Program Text

Program Text (f08zafe.f90)

10.2 Program Data

Program Data (f08zafe.d)

10.3 Program Results

Program Results (f08zafe.r)

F08 Chapter Contents
F08 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F08ZBF (DGGGLM) : NAG Library, Mark 26

F08 Chapter Contents
F08 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F08ZBF (DGGGLM)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F08ZBF (DGGGLM) solves a real general Gauss–Markov linear (least squares) model problem.

2 Specification

SUBROUTINE F08ZBF ( M, N, P, A, LDA, B, LDB, D, X, Y, WORK, LWORK, INFO)
INTEGER | M, N, P, LDA, LDB, LWORK, INFO
REAL (KIND=nag_wp) | A(LDA,*), B(LDB,*), D(M), X(N), Y(P), WORK(max(1,LWORK))
The routine may be called by its LAPACK name dggglm.

3 Description

F08ZBF (DGGGLM) solves the real general Gauss–Markov linear model (GLM) problem
minimize x y 2  subject to  d=Ax+By
where A is an m by n matrix, B is an m by p matrix and d is an m element vector. It is assumed that n≤m≤n+p, rank A=n and rank E=m, where E= A B . Under these assumptions, the problem has a unique solution x and a minimal 2-norm solution y, which is obtained using a generalized QR factorization of the matrices A and B.
In particular, if the matrix B is square and nonsingular, then the GLM problem is equivalent to the weighted linear least squares problem
minimize x B-1 d-Ax 2 .

4 References

Anderson E, Bai Z, Bischof C, Blackford S, Demmel J, Dongarra J J, Du Croz J J, Greenbaum A, Hammarling S, McKenney A and Sorensen D (1999) LAPACK Users' Guide (3rd Edition) SIAM, Philadelphia
Anderson E, Bai Z and Dongarra J (1992) Generalized QR factorization and its applications Linear Algebra Appl. (Volume 162–164) 243–271

5 Arguments

1:   M – INTEGERInput
On entry: m, the number of rows of the matrices A and B.
Constraint: M≥0.
2:   N – INTEGERInput
On entry: n, the number of columns of the matrix A.
Constraint: 0≤N≤M.
3:   P – INTEGERInput
On entry: p, the number of columns of the matrix B.
Constraint: P≥M-N.
4:   A LDA* – REAL (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array A must be at least max 1,N.
On entry: the m by n matrix A.
On exit: A is overwritten.
5:   LDA – INTEGERInput
On entry: the first dimension of the array A as declared in the (sub)program from which F08ZBF (DGGGLM) is called.
Constraint: LDA≥max 1,M.
6:   B LDB* – REAL (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array B must be at least max 1,P.
On entry: the m by p matrix B.
On exit: B is overwritten.
7:   LDB – INTEGERInput
On entry: the first dimension of the array B as declared in the (sub)program from which F08ZBF (DGGGLM) is called.
Constraint: LDB≥max 1,M.
8:   D M – REAL (KIND=nag_wp) arrayInput/Output
On entry: the left-hand side vector d of the GLM equation.
On exit: D is overwritten.
9:   X N – REAL (KIND=nag_wp) arrayOutput
On exit: the solution vector x of the GLM problem.
10:   Y P – REAL (KIND=nag_wp) arrayOutput
On exit: the solution vector y of the GLM problem.
11:   WORK max 1,LWORK – REAL (KIND=nag_wp) arrayWorkspace
On exit: if INFO=0, WORK 1 contains the minimum value of LWORK required for optimal performance.
12:   LWORK – INTEGERInput
On entry: the dimension of the array WORK as declared in the (sub)program from which F08ZBF (DGGGLM) is called.
If LWORK=-1, a workspace query is assumed; the routine only calculates the optimal size of the WORK array, returns this value as the first entry of the WORK array, and no error message related to LWORK is issued.
Suggested value: for optimal performance, LWORK≥N+min M,P+max M,P×nb, where nb is the optimal block size.
Constraint: LWORK≥ max 1,M+N+P or LWORK=-1.
13:   INFO – INTEGEROutput
On exit: INFO=0 unless the routine detects an error (see Section 6).

6 Error Indicators and Warnings

INFO<0
If INFO=-i, argument i had an illegal value. An explanatory message is output, and execution of the program is terminated.
INFO=1
The bottom M-N by M-N part of the upper trapezoidal factor T associated with B in the generalized QR factorization of the pair A,B is singular, so that rank AB<M; the least squares solutions could not be computed.
INFO=2
The upper triangular factor R associated with A in the generalized RQ factorization of the pair A,B is singular, so that rank A<n; the least squares solution could not be computed.

7 Accuracy

For an error analysis, see Anderson et al. (1992). See also Section 4.6 of Anderson et al. (1999).

8 Parallelism and Performance

F08ZBF (DGGGLM) is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
F08ZBF (DGGGLM) makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

When p=m≥n, the total number of floating-point operations is approximately 23 2 m 3-n 3+4 n m 2; when p=m=n, the total number of floating-point operations is approximately 143 m 3.

10 Example

This example solves the weighted least squares problem
minimize x B-1 d-Ax 2 ,
where
B = 0.5 0.0 0.0 0.0 0.0 1.0 0.0 0.0 0.0 0.0 2.0 0.0 0.0 0.0 0.0 5.0 ,   d= 1.32 -4.00 5.52 3.24   and   A= -0.57 -1.28 -0.39 -1.93 1.08 -0.31 2.30 0.24 -0.40 -0.02 1.03 -1.43 .

10.1 Program Text

Program Text (f08zbfe.f90)

10.2 Program Data

Program Data (f08zbfe.d)

10.3 Program Results

Program Results (f08zbfe.r)

F08 Chapter Contents
F08 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F08ZEF (DGGQRF) : NAG Library, Mark 26

F08 Chapter Contents
F08 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F08ZEF (DGGQRF)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F08ZEF (DGGQRF) computes a generalized QR factorization of a real matrix pair A,B, where A is an n by m matrix and B is an n by p matrix.

2 Specification

SUBROUTINE F08ZEF ( N, M, P, A, LDA, TAUA, B, LDB, TAUB, WORK, LWORK, INFO)
INTEGER | N, M, P, LDA, LDB, LWORK, INFO
REAL (KIND=nag_wp) | A(LDA,*), TAUA(min(N,M)), B(LDB,*), TAUB(min(N,P)), WORK(max(1,LWORK))
The routine may be called by its LAPACK name dggqrf.

3 Description

F08ZEF (DGGQRF) forms the generalized QR factorization of an n by m matrix A and an n by p matrix B
A =QR ,   B=QTZ ,
where Q is an n by n orthogonal matrix, Z is a p by p orthogonal matrix and R and T are of the form
R = mmR 11n-m0() ,   if ​n≥m; nm-nnR 11R 12() ,   if ​n<m,
with R 11 upper triangular,
T = p-nnn0T 12() ,   if ​n≤p, pn-pT 11pT 21() ,   if ​n>p,
with T 12 or T 21 upper triangular.
In particular, if B is square and nonsingular, the generalized QR factorization of A and B implicitly gives the QR factorization of B-1 A as
B-1 A= ZT T-1 R .

4 References

Anderson E, Bai Z, Bischof C, Blackford S, Demmel J, Dongarra J J, Du Croz J J, Greenbaum A, Hammarling S, McKenney A and Sorensen D (1999) LAPACK Users' Guide (3rd Edition) SIAM, Philadelphia http://www.netlib.org/lapack/lug
Anderson E, Bai Z and Dongarra J (1992) Generalized QR factorization and its applications Linear Algebra Appl. (Volume 162–164) 243–271
Hammarling S (1987) The numerical solution of the general Gauss-Markov linear model Mathematics in Signal Processing (eds T S Durrani, J B Abbiss, J E Hudson, R N Madan, J G McWhirter and T A Moore) 441–456 Oxford University Press
Paige C C (1990) Some aspects of generalized QR factorizations . In Reliable Numerical Computation (eds M G Cox and S Hammarling) 73–91 Oxford University Press

5 Arguments

1:   N – INTEGERInput
On entry: n, the number of rows of the matrices A and B.
Constraint: N≥0.
2:   M – INTEGERInput
On entry: m, the number of columns of the matrix A.
Constraint: M≥0.
3:   P – INTEGERInput
On entry: p, the number of columns of the matrix B.
Constraint: P≥0.
4:   A LDA* – REAL (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array A must be at least max 1,M.
On entry: the n by m matrix A.
On exit: the elements on and above the diagonal of the array contain the min n,m by m upper trapezoidal matrix R (R is upper triangular if n≥m); the elements below the diagonal, with the array TAUA, represent the orthogonal matrix Q as a product of min n,m elementary reflectors (see Section 3.3.6 in the F08 Chapter Introduction).
5:   LDA – INTEGERInput
On entry: the first dimension of the array A as declared in the (sub)program from which F08ZEF (DGGQRF) is called.
Constraint: LDA≥max 1,N.
6:   TAUA min N,M – REAL (KIND=nag_wp) arrayOutput
On exit: the scalar factors of the elementary reflectors which represent the orthogonal matrix Q.
7:   B LDB* – REAL (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array B must be at least max 1,P.
On entry: the n by p matrix B.
On exit: if n≤p, the upper triangle of the subarray B 1:np-n+1:p contains the n by n upper triangular matrix T 12.
If n>p, the elements on and above the n-pth subdiagonal contain the n by p upper trapezoidal matrix T; the remaining elements, with the array TAUB, represent the orthogonal matrix Z as a product of elementary reflectors (see Section 3.3.6 in the F08 Chapter Introduction).
8:   LDB – INTEGERInput
On entry: the first dimension of the array B as declared in the (sub)program from which F08ZEF (DGGQRF) is called.
Constraint: LDB≥max 1,N.
9:   TAUB min N,P – REAL (KIND=nag_wp) arrayOutput
On exit: the scalar factors of the elementary reflectors which represent the orthogonal matrix Z.
10:   WORK max 1,LWORK – REAL (KIND=nag_wp) arrayWorkspace
On exit: if INFO=0, WORK 1 contains the minimum value of LWORK required for optimal performance.
11:   LWORK – INTEGERInput
On entry: the dimension of the array WORK as declared in the (sub)program from which F08ZEF (DGGQRF) is called.
If LWORK=-1, a workspace query is assumed; the routine only calculates the optimal size of the WORK array, returns this value as the first entry of the WORK array, and no error message related to LWORK is issued.
Suggested value: for optimal performance, LWORK≥max N,M,P×max nb1,nb2,nb3, where nb1 is the optimal block size for the QR factorization of an n by m matrix, nb2 is the optimal block size for the RQ factorization of an n by p matrix, and nb3 is the optimal block size for a call of F08AGF (DORMQR).
Constraint: LWORK≥max 1,N,M,P or LWORK=-1.
12:   INFO – INTEGEROutput
On exit: INFO=0 unless the routine detects an error (see Section 6).

6 Error Indicators and Warnings

INFO<0
If INFO=-i, argument i had an illegal value. An explanatory message is output, and execution of the program is terminated.

7 Accuracy

The computed generalized QR factorization is the exact factorization for nearby matrices A+E and B+F, where
E 2 = O⁡ε A 2   and   F 2= O⁡ε B 2 ,
and ε is the machine precision.

8 Parallelism and Performance

F08ZEF (DGGQRF) is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
F08ZEF (DGGQRF) makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The orthogonal matrices Q and Z may be formed explicitly by calls to F08AFF (DORGQR) and F08CJF (DORGRQ) respectively. F08AGF (DORMQR) may be used to multiply Q by another matrix and F08CKF (DORMRQ) may be used to multiply Z by another matrix.
The complex analogue of this routine is F08ZSF (ZGGQRF).

10 Example

This example solves the general Gauss–Markov linear model problem
minx y 2   subject to   d=Ax+By
where
A = -0.57 -1.28 -0.39 -1.93 1.08 -0.31 2.30 0.24 -0.40 -0.02 1.03 -1.43 ,   B= 0.5 0.0 0.0 0.0 0.0 1.0 0.0 0.0 0.0 0.0 2.0 0.0 0.0 0.0 0.0 5.0   and   d= 1.32 -4.00 5.52 3.24 .
The solution is obtained by first computing a generalized QR factorization of the matrix pair A,B. The example illustrates the general solution process, although the above data corresponds to a simple weighted least squares problem.
Note that the block size (NB) of 64 assumed in this example is not realistic for such a small problem, but should be suitable for large problems.

10.1 Program Text

Program Text (f08zefe.f90)

10.2 Program Data

Program Data (f08zefe.d)

10.3 Program Results

Program Results (f08zefe.r)

F08 Chapter Contents
F08 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F08ZFF (DGGRQF) : NAG Library, Mark 26

F08 Chapter Contents
F08 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F08ZFF (DGGRQF)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F08ZFF (DGGRQF) computes a generalized RQ factorization of a real matrix pair A,B, where A is an m by n matrix and B is a p by n matrix.

2 Specification

SUBROUTINE F08ZFF ( M, P, N, A, LDA, TAUA, B, LDB, TAUB, WORK, LWORK, INFO)
INTEGER | M, P, N, LDA, LDB, LWORK, INFO
REAL (KIND=nag_wp) | A(LDA,*), TAUA(min(M,N)), B(LDB,*), TAUB(min(P,N)), WORK(max(1,LWORK))
The routine may be called by its LAPACK name dggrqf.

3 Description

F08ZFF (DGGRQF) forms the generalized RQ factorization of an m by n matrix A and a p by n matrix B
A = RQ ,   B= ZTQ ,
where Q is an n by n orthogonal matrix, Z is a p by p orthogonal matrix and R and T are of the form
R = n-mmm0R 12() ;   if ​ m≤n , nm-nR 11nR 21() ;   if ​ m>n ,
with R 12 or R 21 upper triangular,
T = nnT 11p-n0() ;   if ​ p≥n , pn-ppT 11T 12() ;   if ​ p<n ,
with T 11 upper triangular.
In particular, if B is square and nonsingular, the generalized RQ factorization of A and B implicitly gives the RQ factorization of A B-1 as
A B-1= R T-1 ZT .

4 References

Anderson E, Bai Z, Bischof C, Blackford S, Demmel J, Dongarra J J, Du Croz J J, Greenbaum A, Hammarling S, McKenney A and Sorensen D (1999) LAPACK Users' Guide (3rd Edition) SIAM, Philadelphia http://www.netlib.org/lapack/lug
Anderson E, Bai Z and Dongarra J (1992) Generalized QR factorization and its applications Linear Algebra Appl. (Volume 162–164) 243–271
Hammarling S (1987) The numerical solution of the general Gauss-Markov linear model Mathematics in Signal Processing (eds T S Durrani, J B Abbiss, J E Hudson, R N Madan, J G McWhirter and T A Moore) 441–456 Oxford University Press
Paige C C (1990) Some aspects of generalized QR factorizations . In Reliable Numerical Computation (eds M G Cox and S Hammarling) 73–91 Oxford University Press

5 Arguments

1:   M – INTEGERInput
On entry: m, the number of rows of the matrix A.
Constraint: M≥0.
2:   P – INTEGERInput
On entry: p, the number of rows of the matrix B.
Constraint: P≥0.
3:   N – INTEGERInput
On entry: n, the number of columns of the matrices A and B.
Constraint: N≥0.
4:   A LDA* – REAL (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array A must be at least max 1,N.
On entry: the m by n matrix A.
On exit: if m≤n, the upper triangle of the subarray A 1:mn-m+1:n contains the m by m upper triangular matrix R 12.
If m≥n, the elements on and above the m-nth subdiagonal contain the m by n upper trapezoidal matrix R; the remaining elements, with the array TAUA, represent the orthogonal matrix Q as a product of min m,n elementary reflectors (see Section 3.3.6 in the F08 Chapter Introduction).
5:   LDA – INTEGERInput
On entry: the first dimension of the array A as declared in the (sub)program from which F08ZFF (DGGRQF) is called.
Constraint: LDA≥max 1,M.
6:   TAUA min M,N – REAL (KIND=nag_wp) arrayOutput
On exit: the scalar factors of the elementary reflectors which represent the orthogonal matrix Q.
7:   B LDB* – REAL (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array B must be at least max 1,N.
On entry: the p by n matrix B.
On exit: the elements on and above the diagonal of the array contain the min p,n by n upper trapezoidal matrix T (T is upper triangular if p≥n); the elements below the diagonal, with the array TAUB, represent the orthogonal matrix Z as a product of elementary reflectors (see Section 3.3.6 in the F08 Chapter Introduction).
8:   LDB – INTEGERInput
On entry: the first dimension of the array B as declared in the (sub)program from which F08ZFF (DGGRQF) is called.
Constraint: LDB≥max 1,P.
9:   TAUB min P,N – REAL (KIND=nag_wp) arrayOutput
On exit: the scalar factors of the elementary reflectors which represent the orthogonal matrix Z.
10:   WORK max 1,LWORK – REAL (KIND=nag_wp) arrayWorkspace
On exit: if INFO=0, WORK 1 contains the minimum value of LWORK required for optimal performance.
11:   LWORK – INTEGERInput
On entry: the dimension of the array WORK as declared in the (sub)program from which F08ZFF (DGGRQF) is called.
If LWORK=-1, a workspace query is assumed; the routine only calculates the optimal size of the WORK array, returns this value as the first entry of the WORK array, and no error message related to LWORK is issued.
Suggested value: for optimal performance, LWORK≥max N,M,P×max nb1,nb2,nb3, where nb1 is the optimal block size for the RQ factorization of an m by n matrix by F08CHF (DGERQF), nb2 is the optimal block size for the QR factorization of a p by n matrix by F08AEF (DGEQRF), and nb3 is the optimal block size for a call of F08CKF (DORMRQ).
Constraint: LWORK≥max 1,N,M,P or LWORK=-1.
12:   INFO – INTEGEROutput
On exit: INFO=0 unless the routine detects an error (see Section 6).

6 Error Indicators and Warnings

INFO<0
If INFO=-i, argument i had an illegal value. An explanatory message is output, and execution of the program is terminated.

7 Accuracy

The computed generalized RQ factorization is the exact factorization for nearby matrices A+E and B+F, where
E 2 = O⁡ε A 2   and   F 2= O⁡ε B 2 ,
and ε is the machine precision.

8 Parallelism and Performance

F08ZFF (DGGRQF) is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
F08ZFF (DGGRQF) makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The orthogonal matrices Q and Z may be formed explicitly by calls to F08CJF (DORGRQ) and F08AFF (DORGQR) respectively. F08CKF (DORMRQ) may be used to multiply Q by another matrix and F08AGF (DORMQR) may be used to multiply Z by another matrix.
The complex analogue of this routine is F08ZTF (ZGGRQF).

10 Example

This example solves the least squares problem
minimize x c-Ax 2   subject to   Bx=d
where
A = -0.57 -1.28 -0.39 0.25 -1.93 1.08 -0.31 -2.14 2.30 0.24 0.40 -0.35 -1.93 0.64 -0.66 0.08 0.15 0.30 0.15 -2.13 -0.02 1.03 -1.43 0.50 ,   B= 1 0 -1 0 0 1 0 -1 ,
c = -1.50 -2.14 1.23 -0.54 -1.68 0.82   and   d= 0 0 .
The constraints Bx=d correspond to x 1=x 3 and x 2=x 4.
The solution is obtained by first computing a generalized RQ factorization of the matrix pair B,A. The example illustrates the general solution process.
Note that the block size (NB) of 64 assumed in this example is not realistic for such a small problem, but should be suitable for large problems.

10.1 Program Text

Program Text (f08zffe.f90)

10.2 Program Data

Program Data (f08zffe.d)

10.3 Program Results

Program Results (f08zffe.r)

F08 Chapter Contents
F08 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F08ZNF (ZGGLSE) : NAG Library, Mark 26

F08 Chapter Contents
F08 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F08ZNF (ZGGLSE)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F08ZNF (ZGGLSE) solves a complex linear equality-constrained least squares problem.

2 Specification

SUBROUTINE F08ZNF ( M, N, P, A, LDA, B, LDB, C, D, X, WORK, LWORK, INFO)
INTEGER | M, N, P, LDA, LDB, LWORK, INFO
COMPLEX (KIND=nag_wp) | A(LDA,*), B(LDB,*), C(M), D(P), X(N), WORK(max(1,LWORK))
The routine may be called by its LAPACK name zgglse.

3 Description

F08ZNF (ZGGLSE) solves the complex linear equality-constrained least squares (LSE) problem
minimize x c-Ax 2  subject to  Bx=d
where A is an m by n matrix, B is a p by n matrix, c is an m element vector and d is a p element vector. It is assumed that p≤n≤m+p, rank B=p and rank E=n, where E= A B . These conditions ensure that the LSE problem has a unique solution, which is obtained using a generalized RQ factorization of the matrices B and A.

4 References

Anderson E, Bai Z, Bischof C, Blackford S, Demmel J, Dongarra J J, Du Croz J J, Greenbaum A, Hammarling S, McKenney A and Sorensen D (1999) LAPACK Users' Guide (3rd Edition) SIAM, Philadelphia
Anderson E, Bai Z and Dongarra J (1992) Generalized QR factorization and its applications Linear Algebra Appl. (Volume 162–164) 243–271
Eldèn L (1980) Perturbation theory for the least squares problem with linear equality constraints SIAM J. Numer. Anal. 17 338–350

5 Arguments

1:   M – INTEGERInput
On entry: m, the number of rows of the matrix A.
Constraint: M≥0.
2:   N – INTEGERInput
On entry: n, the number of columns of the matrices A and B.
Constraint: N≥0.
3:   P – INTEGERInput
On entry: p, the number of rows of the matrix B.
Constraint: 0≤P≤N≤M+P.
4:   A LDA* – COMPLEX (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array A must be at least max 1,N.
On entry: the m by n matrix A.
On exit: A is overwritten.
5:   LDA – INTEGERInput
On entry: the first dimension of the array A as declared in the (sub)program from which F08ZNF (ZGGLSE) is called.
Constraint: LDA≥max 1,M.
6:   B LDB* – COMPLEX (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array B must be at least max 1,N.
On entry: the p by n matrix B.
On exit: B is overwritten.
7:   LDB – INTEGERInput
On entry: the first dimension of the array B as declared in the (sub)program from which F08ZNF (ZGGLSE) is called.
Constraint: LDB≥max 1,P.
8:   C M – COMPLEX (KIND=nag_wp) arrayInput/Output
On entry: the right-hand side vector c for the least squares part of the LSE problem.
On exit: the residual sum of squares for the solution vector x is given by the sum of squares of elements C N-P+1,C N-P+2,…,C M; the remaining elements are overwritten.
9:   D P – COMPLEX (KIND=nag_wp) arrayInput/Output
On entry: the right-hand side vector d for the equality constraints.
On exit: D is overwritten.
10:   X N – COMPLEX (KIND=nag_wp) arrayOutput
On exit: the solution vector x of the LSE problem.
11:   WORK max 1,LWORK – COMPLEX (KIND=nag_wp) arrayWorkspace
On exit: if INFO=0, the real part of WORK 1 contains the minimum value of LWORK required for optimal performance.
12:   LWORK – INTEGERInput
On entry: the dimension of the array WORK as declared in the (sub)program from which F08ZNF (ZGGLSE) is called.
If LWORK=-1, a workspace query is assumed; the routine only calculates the optimal size of the WORK array, returns this value as the first entry of the WORK array, and no error message related to LWORK is issued.
Suggested value: for optimal performance, LWORK≥P+min M,N+max M,N×nb, where nb is the optimal block size.
Constraint: LWORK≥ max 1,M+N+P or LWORK=-1.
13:   INFO – INTEGEROutput
On exit: INFO=0 unless the routine detects an error (see Section 6).

6 Error Indicators and Warnings

INFO<0
If INFO=-i, argument i had an illegal value. An explanatory message is output, and execution of the program is terminated.
INFO=1
The upper triangular factor R associated with B in the generalized RQ factorization of the pair B,A is singular, so that rank B<p; the least squares solution could not be computed.
INFO=2
The N-P by N-P part of the upper trapezoidal factor T associated with A in the generalized RQ factorization of the pair B,A is singular, so that the rank of the matrix (E) comprising the rows of A and B is less than n; the least squares solutions could not be computed.

7 Accuracy

For an error analysis, see Anderson et al. (1992) and Eldèn (1980). See also Section 4.6 of Anderson et al. (1999).

8 Parallelism and Performance

F08ZNF (ZGGLSE) is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
F08ZNF (ZGGLSE) makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

When m≥n=p, the total number of real floating-point operations is approximately 83 n 2 6 m+n; if p≪n, the number reduces to approximately 83 n 2 3 m-n.

10 Example

This example solves the least squares problem
minimize x c-Ax 2   subject to   Bx=d
where
c = -2.54+0.09 i 1.65-2.26 i -2.11-3.96 i 1.82+3.30 i -6.41+3.77 i 2.07+0.66 i ,
and
A = 0.96-0.81 i -0.03+0.96 i -0.91+2.06 i -0.05+0.41 i -0.98+1.98 i -1.20+0.19 i -0.66+0.42 i -0.81+0.56 i 0.62-0.46 i 1.01+0.02 i 0.63-0.17 i -1.11+0.60 i 0.37+0.38 i 0.19-0.54 i -0.98-0.36 i 0.22-0.20 i 0.83+0.51 i 0.20+0.01 i -0.17-0.46 i 1.47+1.59 i 1.08-0.28 i 0.20-0.12 i -0.07+1.23 i 0.26+0.26 i ,
B = 1.0+0.0 i 0.0i+0.0 -1.0+0.0 i 0.0i+0.0 0.0i+0.0 1.0+0.0 i 0.0i+0.0 -1.0+0.0 i
and
d = 0 0 .
The constraints Bx=d correspond to x 1 = x 3 and x 2 = x 4 .
Note that the block size (NB) of 64 assumed in this example is not realistic for such a small problem, but should be suitable for large problems.

10.1 Program Text

Program Text (f08znfe.f90)

10.2 Program Data

Program Data (f08znfe.d)

10.3 Program Results

Program Results (f08znfe.r)

F08 Chapter Contents
F08 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F08ZPF (ZGGGLM) : NAG Library, Mark 26

F08 Chapter Contents
F08 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F08ZPF (ZGGGLM)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F08ZPF (ZGGGLM) solves a complex general Gauss–Markov linear (least squares) model problem.

2 Specification

SUBROUTINE F08ZPF ( M, N, P, A, LDA, B, LDB, D, X, Y, WORK, LWORK, INFO)
INTEGER | M, N, P, LDA, LDB, LWORK, INFO
COMPLEX (KIND=nag_wp) | A(LDA,*), B(LDB,*), D(M), X(N), Y(P), WORK(max(1,LWORK))
The routine may be called by its LAPACK name zggglm.

3 Description

F08ZPF (ZGGGLM) solves the complex general Gauss–Markov linear model (GLM) problem
minimize x y 2  subject to  d=Ax+By
where A is an m by n matrix, B is an m by p matrix and d is an m element vector. It is assumed that n≤m≤n+p, rank A=n and rank E=m, where E= A B . Under these assumptions, the problem has a unique solution x and a minimal 2-norm solution y, which is obtained using a generalized QR factorization of the matrices A and B.
In particular, if the matrix B is square and nonsingular, then the GLM problem is equivalent to the weighted linear least squares problem
minimize x B-1 d-Ax 2 .

4 References

Anderson E, Bai Z, Bischof C, Blackford S, Demmel J, Dongarra J J, Du Croz J J, Greenbaum A, Hammarling S, McKenney A and Sorensen D (1999) LAPACK Users' Guide (3rd Edition) SIAM, Philadelphia
Anderson E, Bai Z and Dongarra J (1992) Generalized QR factorization and its applications Linear Algebra Appl. (Volume 162–164) 243–271

5 Arguments

1:   M – INTEGERInput
On entry: m, the number of rows of the matrices A and B.
Constraint: M≥0.
2:   N – INTEGERInput
On entry: n, the number of columns of the matrix A.
Constraint: 0≤N≤M.
3:   P – INTEGERInput
On entry: p, the number of columns of the matrix B.
Constraint: P≥M-N.
4:   A LDA* – COMPLEX (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array A must be at least max 1,N.
On entry: the m by n matrix A.
On exit: A is overwritten.
5:   LDA – INTEGERInput
On entry: the first dimension of the array A as declared in the (sub)program from which F08ZPF (ZGGGLM) is called.
Constraint: LDA≥max 1,M.
6:   B LDB* – COMPLEX (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array B must be at least max 1,P.
On entry: the m by p matrix B.
On exit: B is overwritten.
7:   LDB – INTEGERInput
On entry: the first dimension of the array B as declared in the (sub)program from which F08ZPF (ZGGGLM) is called.
Constraint: LDB≥max 1,M.
8:   D M – COMPLEX (KIND=nag_wp) arrayInput/Output
On entry: the left-hand side vector d of the GLM equation.
On exit: D is overwritten.
9:   X N – COMPLEX (KIND=nag_wp) arrayOutput
On exit: the solution vector x of the GLM problem.
10:   Y P – COMPLEX (KIND=nag_wp) arrayOutput
On exit: the solution vector y of the GLM problem.
11:   WORK max 1,LWORK – COMPLEX (KIND=nag_wp) arrayWorkspace
On exit: if INFO=0, the real part of WORK 1 contains the minimum value of LWORK required for optimal performance.
12:   LWORK – INTEGERInput
On entry: the dimension of the array WORK as declared in the (sub)program from which F08ZPF (ZGGGLM) is called.
If LWORK=-1, a workspace query is assumed; the routine only calculates the optimal size of the WORK array, returns this value as the first entry of the WORK array, and no error message related to LWORK is issued.
Suggested value: for optimal performance, LWORK≥N+min M,P+max M,P×nb, where nb is the optimal block size.
Constraint: LWORK≥ max 1,M+N+P or LWORK=-1.
13:   INFO – INTEGEROutput
On exit: INFO=0 unless the routine detects an error (see Section 6).

6 Error Indicators and Warnings

INFO<0
If INFO=-i, argument i had an illegal value. An explanatory message is output, and execution of the program is terminated.
INFO=1
The bottom M-N by M-N part of the upper trapezoidal factor T associated with B in the generalized QR factorization of the pair A,B is singular, so that rank AB<M; the least squares solutions could not be computed.
INFO=2
The upper triangular factor R associated with A in the generalized RQ factorization of the pair A,B is singular, so that rank A<n; the least squares solution could not be computed.

7 Accuracy

For an error analysis, see Anderson et al. (1992). See also Section 4.6 of Anderson et al. (1999).

8 Parallelism and Performance

F08ZPF (ZGGGLM) is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
F08ZPF (ZGGGLM) makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

When p=m≥n, the total number of real floating-point operations is approximately 83 2 m 3-n 3+16 n m 2; when p=m=n, the total number of real floating-point operations is approximately 563 m 3.

10 Example

This example solves the weighted least squares problem
minimize x B-1 d-Ax 2 ,
where
B = 0.5-1.0 i .0i+0.0 .0i+0.0 .0i+0.0 .0i+0.0 1.0-2.0 i .0i+0.0 .0i+0.0 .0i+0.0 .0i+0.0 2.0-3.0 i .0i+0.0 .0i+0.0 .0i+0.0 .0i+0.0 5.0-4.0 i ,
d = 6.00-0.40 i -5.27+0.90 i 2.72-2.13 i -1.30-2.80 i
and
A = 0.96-0.81 i -0.03+0.96 i -0.91+2.06 i -0.98+1.98 i -1.20+0.19 i -0.66+0.42 i 0.62-0.46 i 1.01+0.02 i 0.63-0.17 i 1.08-0.28 i 0.20-0.12 i -0.07+1.23 i .
Note that the block size (NB) of 64 assumed in this example is not realistic for such a small problem, but should be suitable for large problems.

10.1 Program Text

Program Text (f08zpfe.f90)

10.2 Program Data

Program Data (f08zpfe.d)

10.3 Program Results

Program Results (f08zpfe.r)

F08 Chapter Contents
F08 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F08ZSF (ZGGQRF) : NAG Library, Mark 26

F08 Chapter Contents
F08 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F08ZSF (ZGGQRF)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F08ZSF (ZGGQRF) computes a generalized QR factorization of a complex matrix pair A,B, where A is an n by m matrix and B is an n by p matrix.

2 Specification

SUBROUTINE F08ZSF ( N, M, P, A, LDA, TAUA, B, LDB, TAUB, WORK, LWORK, INFO)
INTEGER | N, M, P, LDA, LDB, LWORK, INFO
COMPLEX (KIND=nag_wp) | A(LDA,*), TAUA(min(N,M)), B(LDB,*), TAUB(min(N,P)), WORK(max(1,LWORK))
The routine may be called by its LAPACK name zggqrf.

3 Description

F08ZSF (ZGGQRF) forms the generalized QR factorization of an n by m matrix A and an n by p matrix B
A =QR ,   B=QTZ ,
where Q is an n by n unitary matrix, Z is a p by p unitary matrix and R and T are of the form
R = mmR 11n-m0() ,   if ​n≥m; nm-nnR 11R 12() ,   if ​n<m,
with R 11 upper triangular,
T = p-nnn0T 12() ,   if ​n≤p, pn-pT 11pT 21() ,   if ​n>p,
with T 12 or T 21 upper triangular.
In particular, if B is square and nonsingular, the generalized QR factorization of A and B implicitly gives the QR factorization of B-1 A as
B-1 A= ZH T-1 R .

4 References

Anderson E, Bai Z, Bischof C, Blackford S, Demmel J, Dongarra J J, Du Croz J J, Greenbaum A, Hammarling S, McKenney A and Sorensen D (1999) LAPACK Users' Guide (3rd Edition) SIAM, Philadelphia http://www.netlib.org/lapack/lug
Anderson E, Bai Z and Dongarra J (1992) Generalized QR factorization and its applications Linear Algebra Appl. (Volume 162–164) 243–271
Hammarling S (1987) The numerical solution of the general Gauss-Markov linear model Mathematics in Signal Processing (eds T S Durrani, J B Abbiss, J E Hudson, R N Madan, J G McWhirter and T A Moore) 441–456 Oxford University Press
Paige C C (1990) Some aspects of generalized QR factorizations . In Reliable Numerical Computation (eds M G Cox and S Hammarling) 73–91 Oxford University Press

5 Arguments

1:   N – INTEGERInput
On entry: n, the number of rows of the matrices A and B.
Constraint: N≥0.
2:   M – INTEGERInput
On entry: m, the number of columns of the matrix A.
Constraint: M≥0.
3:   P – INTEGERInput
On entry: p, the number of columns of the matrix B.
Constraint: P≥0.
4:   A LDA* – COMPLEX (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array A must be at least max 1,M.
On entry: the n by m matrix A.
On exit: the elements on and above the diagonal of the array contain the min n,m by m upper trapezoidal matrix R (R is upper triangular if n≥m); the elements below the diagonal, with the array TAUA, represent the unitary matrix Q as a product of min n,m elementary reflectors (see Section 3.3.6 in the F08 Chapter Introduction).
5:   LDA – INTEGERInput
On entry: the first dimension of the array A as declared in the (sub)program from which F08ZSF (ZGGQRF) is called.
Constraint: LDA≥max 1,N.
6:   TAUA min N,M – COMPLEX (KIND=nag_wp) arrayOutput
On exit: the scalar factors of the elementary reflectors which represent the unitary matrix Q.
7:   B LDB* – COMPLEX (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array B must be at least max 1,P.
On entry: the n by p matrix B.
On exit: if n≤p, the upper triangle of the subarray B 1:np-n+1:p contains the n by n upper triangular matrix T 12.
If n>p, the elements on and above the n-pth subdiagonal contain the n by p upper trapezoidal matrix T; the remaining elements, with the array TAUB, represent the unitary matrix Z as a product of elementary reflectors (see Section 3.3.6 in the F08 Chapter Introduction).
8:   LDB – INTEGERInput
On entry: the first dimension of the array B as declared in the (sub)program from which F08ZSF (ZGGQRF) is called.
Constraint: LDB≥max 1,N.
9:   TAUB min N,P – COMPLEX (KIND=nag_wp) arrayOutput
On exit: the scalar factors of the elementary reflectors which represent the unitary matrix Z.
10:   WORK max 1,LWORK – COMPLEX (KIND=nag_wp) arrayWorkspace
On exit: if INFO=0, the real part of WORK 1 contains the minimum value of LWORK required for optimal performance.
11:   LWORK – INTEGERInput
On entry: the dimension of the array WORK as declared in the (sub)program from which F08ZSF (ZGGQRF) is called.
If LWORK=-1, a workspace query is assumed; the routine only calculates the optimal size of the WORK array, returns this value as the first entry of the WORK array, and no error message related to LWORK is issued.
Suggested value: for optimal performance, LWORK≥max N,M,P×max nb1,nb2,nb3, where nb1 is the optimal block size for the QR factorization of an n by m matrix, nb2 is the optimal block size for the RQ factorization of an n by p matrix, and nb3 is the optimal block size for a call of F08AUF (ZUNMQR).
Constraint: LWORK≥max 1,N,M,P or LWORK=-1.
12:   INFO – INTEGEROutput
On exit: INFO=0 unless the routine detects an error (see Section 6).

6 Error Indicators and Warnings

INFO<0
If INFO=-i, argument i had an illegal value. An explanatory message is output, and execution of the program is terminated.

7 Accuracy

The computed generalized QR factorization is the exact factorization for nearby matrices A+E and B+F, where
E 2 = O⁡ε A 2   and   F 2= O⁡ε B 2 ,
and ε is the machine precision.

8 Parallelism and Performance

F08ZSF (ZGGQRF) is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
F08ZSF (ZGGQRF) makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The unitary matrices Q and Z may be formed explicitly by calls to F08ATF (ZUNGQR) and F08CWF (ZUNGRQ) respectively. F08AUF (ZUNMQR) may be used to multiply Q by another matrix and F08CXF (ZUNMRQ) may be used to multiply Z by another matrix.
The real analogue of this routine is F08ZEF (DGGQRF).

10 Example

This example solves the general Gauss–Markov linear model problem
minx y 2   subject to   d=Ax+By
where
A = 0.96-0.81 i -0.03+0.96 i -0.91+2.06 i -0.98+1.98 i -1.20+0.19 i -0.66+0.42 i 0.62-0.46 i 1.01+0.02 i 0.63-0.17 i 1.08-0.28 i 0.20-0.12 i -0.07+1.23 i ,
B = 0.5-1.0 i 0.0i+0.0 0.0i+0.0 0.0i+0.0 0.0i+0.0 1.0-2.0 i 0.0i+0.0 0.0i+0.0 0.0i+0.0 0.0i+0.0 2.0-3.0 i 0.0i+0.0 0.0i+0.0 0.0i+0.0 0.0i+0.0 5.0-4.0 i
and
d = 6.00-0.40 i -5.27+0.90 i 2.72-2.13 i -1.30-2.80 i .
The solution is obtained by first computing a generalized QR factorization of the matrix pair A,B. The example illustrates the general solution process, although the above data corresponds to a simple weighted least squares problem.
Note that the block size (NB) of 64 assumed in this example is not realistic for such a small problem, but should be suitable for large problems.

10.1 Program Text

Program Text (f08zsfe.f90)

10.2 Program Data

Program Data (f08zsfe.d)

10.3 Program Results

Program Results (f08zsfe.r)

F08 Chapter Contents
F08 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F08ZTF (ZGGRQF) : NAG Library, Mark 26

F08 Chapter Contents
F08 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F08ZTF (ZGGRQF)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F08ZTF (ZGGRQF) computes a generalized RQ factorization of a complex matrix pair A,B, where A is an m by n matrix and B is a p by n matrix.

2 Specification

SUBROUTINE F08ZTF ( M, P, N, A, LDA, TAUA, B, LDB, TAUB, WORK, LWORK, INFO)
INTEGER | M, P, N, LDA, LDB, LWORK, INFO
COMPLEX (KIND=nag_wp) | A(LDA,*), TAUA(min(M,N)), B(LDB,*), TAUB(min(P,N)), WORK(max(1,LWORK))
The routine may be called by its LAPACK name zggrqf.

3 Description

F08ZTF (ZGGRQF) forms the generalized RQ factorization of an m by n matrix A and a p by n matrix B
A = RQ ,   B= ZTQ ,
where Q is an n by n unitary matrix, Z is a p by p unitary matrix and R and T are of the form
R = n-mmm0R 12() ;   if ​ m≤n , nm-nR 11nR 21() ;   if ​ m>n ,
with R 12 or R 21 upper triangular,
T = nnT 11p-n0() ;   if ​ p≥n , pn-ppT 11T 12() ;   if ​ p<n ,
with T 11 upper triangular.
In particular, if B is square and nonsingular, the generalized RQ factorization of A and B implicitly gives the RQ factorization of A B-1 as
A B-1= R T-1 ZH .

4 References

Anderson E, Bai Z, Bischof C, Blackford S, Demmel J, Dongarra J J, Du Croz J J, Greenbaum A, Hammarling S, McKenney A and Sorensen D (1999) LAPACK Users' Guide (3rd Edition) SIAM, Philadelphia http://www.netlib.org/lapack/lug
Anderson E, Bai Z and Dongarra J (1992) Generalized QR factorization and its applications Linear Algebra Appl. (Volume 162–164) 243–271
Hammarling S (1987) The numerical solution of the general Gauss-Markov linear model Mathematics in Signal Processing (eds T S Durrani, J B Abbiss, J E Hudson, R N Madan, J G McWhirter and T A Moore) 441–456 Oxford University Press
Paige C C (1990) Some aspects of generalized QR factorizations . In Reliable Numerical Computation (eds M G Cox and S Hammarling) 73–91 Oxford University Press

5 Arguments

1:   M – INTEGERInput
On entry: m, the number of rows of the matrix A.
Constraint: M≥0.
2:   P – INTEGERInput
On entry: p, the number of rows of the matrix B.
Constraint: P≥0.
3:   N – INTEGERInput
On entry: n, the number of columns of the matrices A and B.
Constraint: N≥0.
4:   A LDA* – COMPLEX (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array A must be at least max 1,N.
On entry: the m by n matrix A.
On exit: if m≤n, the upper triangle of the subarray A 1:mn-m+1:n contains the m by m upper triangular matrix R 12.
If m≥n, the elements on and above the m-nth subdiagonal contain the m by n upper trapezoidal matrix R; the remaining elements, with the array TAUA, represent the unitary matrix Q as a product of min m,n elementary reflectors (see Section 3.3.6 in the F08 Chapter Introduction).
5:   LDA – INTEGERInput
On entry: the first dimension of the array A as declared in the (sub)program from which F08ZTF (ZGGRQF) is called.
Constraint: LDA≥max 1,M.
6:   TAUA min M,N – COMPLEX (KIND=nag_wp) arrayOutput
On exit: the scalar factors of the elementary reflectors which represent the unitary matrix Q.
7:   B LDB* – COMPLEX (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array B must be at least max 1,N.
On entry: the p by n matrix B.
On exit: the elements on and above the diagonal of the array contain the min p,n by n upper trapezoidal matrix T (T is upper triangular if p≥n); the elements below the diagonal, with the array TAUB, represent the unitary matrix Z as a product of elementary reflectors (see Section 3.3.6 in the F08 Chapter Introduction).
8:   LDB – INTEGERInput
On entry: the first dimension of the array B as declared in the (sub)program from which F08ZTF (ZGGRQF) is called.
Constraint: LDB≥max 1,P.
9:   TAUB min P,N – COMPLEX (KIND=nag_wp) arrayOutput
On exit: the scalar factors of the elementary reflectors which represent the unitary matrix Z.
10:   WORK max 1,LWORK – COMPLEX (KIND=nag_wp) arrayWorkspace
On exit: if INFO=0, the real part of WORK 1 contains the minimum value of LWORK required for optimal performance.
11:   LWORK – INTEGERInput
On entry: the dimension of the array WORK as declared in the (sub)program from which F08ZTF (ZGGRQF) is called.
If LWORK=-1, a workspace query is assumed; the routine only calculates the optimal size of the WORK array, returns this value as the first entry of the WORK array, and no error message related to LWORK is issued.
Suggested value: for optimal performance, LWORK≥max N,M,P×max nb1,nb2,nb3, where nb1 is the optimal block size for the RQ factorization of an m by n matrix by F08CVF (ZGERQF), nb2 is the optimal block size for the QR factorization of a p by n matrix by F08ASF (ZGEQRF), and nb3 is the optimal block size for a call of F08CXF (ZUNMRQ).
Constraint: LWORK≥max 1,N,M,P or LWORK=-1.
12:   INFO – INTEGEROutput
On exit: INFO=0 unless the routine detects an error (see Section 6).

6 Error Indicators and Warnings

INFO<0
If INFO=-i, argument i had an illegal value. An explanatory message is output, and execution of the program is terminated.

7 Accuracy

The computed generalized RQ factorization is the exact factorization for nearby matrices A+E and B+F, where
E 2 = O⁡ε A 2   and   F 2= O⁡ε B 2 ,
and ε is the machine precision.

8 Parallelism and Performance

F08ZTF (ZGGRQF) is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
F08ZTF (ZGGRQF) makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The unitary matrices Q and Z may be formed explicitly by calls to F08CWF (ZUNGRQ) and F08ATF (ZUNGQR) respectively. F08CXF (ZUNMRQ) may be used to multiply Q by another matrix and F08AUF (ZUNMQR) may be used to multiply Z by another matrix.
The real analogue of this routine is F08ZFF (DGGRQF).

10 Example

This example solves the least squares problem
minimize x c-Ax 2   subject to   Bx=d
where
A = 0.96-0.81 i -0.03+0.96 i -0.91+2.06 i -0.05+0.41 i -0.98+1.98 i -1.20+0.19 i -0.66+0.42 i -0.81+0.56 i 0.62-0.46 i 1.01+0.02 i 0.63-0.17 i -1.11+0.60 i 0.37+0.38 i 0.19-0.54 i -0.98-0.36 i 0.22-0.20 i 0.83+0.51 i 0.20+0.01 i -0.17-0.46 i 1.47+1.59 i 1.08-0.28 i 0.20-0.12 i -0.07+1.23 i 0.26+0.26 i ,
B = 1 0 -1 0 0 1 0 -1 ,   c= -2.54+0.09 i 1.65-2.26 i -2.11-3.96 i 1.82+3.30 i -6.41+3.77 i 2.07+0.66 i   and   d= 0 0 .
The constraints Bx=d correspond to x 1=x 3 and x 2=x 4.
The solution is obtained by first obtaining a generalized RQ factorization of the matrix pair A,B. The example illustrates the general solution process, although the above data corresponds to a simple weighted least squares problem.
Note that the block size (NB) of 64 assumed in this example is not realistic for such a small problem, but should be suitable for large problems.

10.1 Program Text

Program Text (f08ztfe.f90)

10.2 Program Data

Program Data (f08ztfe.d)

10.3 Program Results

Program Results (f08ztfe.r)

F08 Chapter Contents
F08 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F11BDF : NAG Library, Mark 26

F11 Chapter Contents
F11 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F11BDF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
▸▿ 3 Description
3.1 Restarted Generalized Minimum Residual Method (RGMRES)
3.2 Conjugate Gradient Squared Method (CGS)
3.3 Bi-Conjugate Gradient Stabilized (ℓ) Method (Bi-CGSTAB(ℓ))
3.4 Transpose-free Quasi-minimal Residual Method (TFQMR)
3.5 General Considerations
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F11BDF is a setup routine, the first in a suite of three routines for the iterative solution of a real general (nonsymmetric) system of simultaneous linear equations. F11BDF must be called before F11BEF, the iterative solver. The third routine in the suite, F11BFF, can be used to return additional information about the computation.
These three routines are suitable for the solution of large sparse general (nonsymmetric) systems of equations.

2 Specification

SUBROUTINE F11BDF ( METHOD, PRECON, NORM, WEIGHT, ITERM, N, M, TOL, MAXITN, ANORM, SIGMAX, MONIT, LWREQ, WORK, LWORK, IFAIL)
INTEGER | ITERM, N, M, MAXITN, MONIT, LWREQ, LWORK, IFAIL
REAL (KIND=nag_wp) | TOL, ANORM, SIGMAX, WORK(LWORK)
CHARACTER(*) | METHOD
CHARACTER(1) | PRECON, NORM, WEIGHT

3 Description

The suite consisting of the routines F11BDF, F11BEF and F11BFF is designed to solve the general (nonsymmetric) system of simultaneous linear equations Ax=b of order n, where n is large and the coefficient matrix A is sparse.
F11BDF is a setup routine which must be called before F11BEF, the iterative solver. The third routine in the suite, F11BFF, can be used to return additional information about the computation. A choice of methods is available:
  • restarted generalized minimum residual method (RGMRES);
  • conjugate gradient squared method (CGS);
  • bi-conjugate gradient stabilized (ℓ) method (Bi-CGSTAB(ℓ));
  • transpose-free quasi-minimal residual method (TFQMR).

3.1 Restarted Generalized Minimum Residual Method (RGMRES)

The restarted generalized minimum residual method (RGMRES) (see Saad and Schultz (1986), Barrett et al. (1994) and Dias da Cunha and Hopkins (1994)) starts from the residual r 0=b-A x 0, where x 0 is an initial estimate for the solution (often x 0=0). An orthogonal basis for the Krylov subspace span Ak r 0, for k=0,1,…, is generated explicitly: this is referred to as Arnoldi's method (see Arnoldi (1951)). The solution is then expanded onto the orthogonal basis so as to minimize the residual norm b-Ax 2. The lack of symmetry of A implies that the orthogonal basis is generated by applying a ‘long’ recurrence relation, whose length increases linearly with the iteration count. For all but the most trivial problems, computational and storage costs can quickly become prohibitive as the iteration count increases. RGMRES limits these costs by employing a restart strategy: every m iterations at most, the Arnoldi process is restarted from rl=b-A xl, where the subscript l denotes the last available iterate. Each group of m iterations is referred to as a ‘super-iteration’. The value of m is chosen in advance and is fixed throughout the computation. Unfortunately, an optimum value of m cannot easily be predicted.

3.2 Conjugate Gradient Squared Method (CGS)

The conjugate gradient squared method (CGS) (see Sonneveld (1989), Barrett et al. (1994) and Dias da Cunha and Hopkins (1994)) is a development of the bi-conjugate gradient method where the nonsymmetric Lanczos method is applied to reduce the coefficients matrix to real tridiagonal form: two bi-orthogonal sequences of vectors are generated starting from the residual r 0=b-A x 0, where x 0 is an initial estimate for the solution (often x 0=0) and from the shadow residual r^0 corresponding to the arbitrary problem AT x^=b^, where b^ can be any vector, but in practice is chosen so that r 0=r^0. In the course of the iteration, the residual and shadow residual ri=Pi A r 0 and r^i=Pi AT r^0 are generated, where Pi is a polynomial of order i, and bi-orthogonality is exploited by computing the vector product ρi=r^i,ri=Pi AT r^0, Pi A r 0=r^0,Pi 2 A r 0. Applying the ‘contraction’ operator Pi A twice, the iteration coefficients can still be recovered without advancing the solution of the shadow problem, which is of no interest. The CGS method often provides fast convergence; however, there is no reason why the contraction operator should also reduce the once reduced vector Pi A r 0: this may well lead to a highly irregular convergence which may result in large cancellation errors.

3.3 Bi-Conjugate Gradient Stabilized (ℓ) Method (Bi-CGSTAB(ℓ))

The bi-conjugate gradient stabilized (ℓ) method (Bi-CGSTAB(ℓ)) (see Van der Vorst (1989), Sleijpen and Fokkema (1993) and Dias da Cunha and Hopkins (1994)) is similar to the CGS method above. However, instead of generating the sequence Pi 2 A r 0, it generates the sequence Qi A Pi A r 0, where the Qi A are polynomials chosen to minimize the residual after the application of the contraction operator Pi A. Two main steps can be identified for each iteration: an OR (Orthogonal Residuals) step where a basis of order ℓ is generated by a Bi-CG iteration and an MR (Minimum Residuals) step where the residual is minimized over the basis generated, by a method akin to GMRES. For ℓ=1, the method corresponds to the Bi-CGSTAB method of Van der Vorst (1989). For ℓ>1, more information about complex eigenvalues of the iteration matrix can be taken into account, and this may lead to improved convergence and robustness. However, as ℓ increases, numerical instabilities may arise. For this reason, a maximum value of ℓ=10 is imposed, but probably ℓ=4 is sufficient in most cases.

3.4 Transpose-free Quasi-minimal Residual Method (TFQMR)

The transpose-free quasi-minimal residual method (TFQMR) (see Freund and Nachtigal (1991) and Freund (1993)) is conceptually derived from the CGS method. The residual is minimized over the space of the residual vectors generated by the CGS iterations under the simplifying assumption that residuals are almost orthogonal. In practice, this is not the case but theoretical analysis has proved the validity of the method. This has the effect of remedying the rather irregular convergence behaviour with wild oscillations in the residual norm that can degrade the numerical performance and robustness of the CGS method. In general, the TFQMR method can be expected to converge at least as fast as the CGS method, in terms of number of iterations, although each iteration involves a higher operation count. When the CGS method exhibits irregular convergence, the TFQMR method can produce much smoother, almost monotonic convergence curves. However, the close relationship between the CGS and TFQMR method implies that the overall speed of convergence is similar for both methods. In some cases, the TFQMR method may converge faster than the CGS method.

3.5 General Considerations

For each method, a sequence of solution iterates xi is generated such that, hopefully, the sequence of the residual norms ri converges to a required tolerance. Note that, in general, convergence, when it occurs, is not monotonic.
In the RGMRES and Bi-CGSTAB(ℓ) methods above, your program must provide the maximum number of basis vectors used, m or ℓ, respectively; however, a smaller number of basis vectors may be generated and used when the stability of the solution process requires this (see Section 9).
Faster convergence can be achieved using a preconditioner (see Golub and Van Loan (1996) and Barrett et al. (1994)). A preconditioner maps the original system of equations onto a different system, say
A-x-=b-, (1)
with, hopefully, better characteristics with respect to its speed of convergence: for example, the condition number of the coefficients matrix can be improved or eigenvalues in its spectrum can be made to coalesce. An orthogonal basis for the Krylov subspace span A-k r-0, for k=0,1,…, is generated and the solution proceeds as outlined above. The algorithms used are such that the solution and residual iterates of the original system are produced, not their preconditioned counterparts. Note that an unsuitable preconditioner or no preconditioning at all may result in a very slow rate, or lack, of convergence. However, preconditioning involves a trade-off between the reduction in the number of iterations required for convergence and the additional computational costs per iteration. Also, setting up a preconditioner may involve non-negligible overheads.
A left preconditioner M-1 can be used by the RGMRES, CGS and TFQMR methods, such that A-=M-1 A∼In in (1), where In is the identity matrix of order n; a right preconditioner M-1 can be used by the Bi-CGSTAB(ℓ) method, such that A-=A M-1∼In. These are formal definitions, used only in the design of the algorithms; in practice, only the means to compute the matrix–vector products v=Au and v=AT u (the latter only being required when an estimate of A 1 or A∞ is computed internally), and to solve the preconditioning equations Mv=u are required, i.e., explicit information about M, or its inverse is not required at any stage.
The first termination criterion
rk p ≤ τ b p + A p × xk p (2)
is available for all four methods. In (2), p=1, ∞​ or ​2 and τ denotes a user-specified tolerance subject to max 10,n, ε≤τ<1, where ε is the machine precision. Facilities are provided for the estimation of the norm of the coefficients matrix A 1 or A∞, when this is not known in advance, by applying Higham's method (see Higham (1988)). Note that A 2 cannot be estimated internally. This criterion uses an error bound derived from backward error analysis to ensure that the computed solution is the exact solution of a problem as close to the original as the termination tolerance requires. Termination criteria employing bounds derived from forward error analysis are not used because any such criteria would require information about the condition number κ A which is not easily obtainable.
The second termination criterion
r-k 2 ≤ τ r-0 2 + σ 1 A- × Δ x-k 2 (3)
is available for all methods except TFQMR. In (3), σ 1 A-=A-2 is the largest singular value of the (preconditioned) iteration matrix A-. This termination criterion monitors the progress of the solution of the preconditioned system of equations and is less expensive to apply than criterion (2) for the Bi-CGSTAB(ℓ) method with ℓ>1. Only the RGMRES method provides facilities to estimate σ 1 A- internally, when this is not supplied (see Section 9).
Termination criterion (2) is the recommended choice, despite its additional costs per iteration when using the Bi-CGSTAB(ℓ) method with ℓ>1. Also, if the norm of the initial estimate is much larger than the norm of the solution, that is, if x 0≫x, a dramatic loss of significant digits could result in complete lack of convergence. The use of criterion (2) will enable the detection of such a situation, and the iteration will be restarted at a suitable point. No such restart facilities are provided for criterion (3).
Optionally, a vector w of user-specified weights can be used in the computation of the vector norms in termination criterion (2), i.e., v p w=v w p, where v w i=wi vi, for i=1,2,…,n. Note that the use of weights increases the computational costs.
The sequence of calls to the routines comprising the suite is enforced: first, the setup routine F11BDF must be called, followed by the solver F11BEF. F11BFF can be called either when F11BEF is carrying out a monitoring step or after F11BEF has completed its tasks. Incorrect sequencing will raise an error condition.
In general, it is not possible to recommend one method in preference to another. RGMRES is often used in the solution of systems arising from PDEs. On the other hand, it can easily stagnate when the size m of the orthogonal basis is too small, or the preconditioner is not good enough. CGS can be the fastest method, but the computed residuals can exhibit instability which may greatly affect the convergence and quality of the solution. Bi-CGSTAB(ℓ) seems robust and reliable, but it can be slower than the other methods: if a preconditioner is used and ℓ>1, Bi-CGSTAB(ℓ) computes the solution of the preconditioned system x-k=M xk: the preconditioning equations must be solved to obtain the required solution. The algorithm employed limits to 10% or less, when no intermediate monitoring is requested, the number of times the preconditioner has to be thus applied compared with the total number of applications of the preconditioner. TFQMR can be viewed as a more robust variant of the CGS method: it shares the CGS method speed but avoids the CGS fluctuations in the residual, which may give rise to instability. Also, when the termination criterion (2) is used, the CGS, Bi-CGSTAB(ℓ) and TFQMR methods will restart the iteration automatically when necessary in order to solve the given problem.

4 References

Arnoldi W (1951) The principle of minimized iterations in the solution of the matrix eigenvalue problem Quart. Appl. Math. 9 17–29
Barrett R, Berry M, Chan T F, Demmel J, Donato J, Dongarra J, Eijkhout V, Pozo R, Romine C and Van der Vorst H (1994) Templates for the Solution of Linear Systems: Building Blocks for Iterative Methods SIAM, Philadelphia
Dias da Cunha R and Hopkins T (1994) PIM 1.1 — the parallel iterative method package for systems of linear equations user's guide — Fortran 77 version Technical Report Computing Laboratory, University of Kent at Canterbury, Kent, UK
Freund R W (1993) A transpose-free quasi-minimal residual algorithm for non-Hermitian linear systems SIAM J. Sci. Comput. 14 470–482
Freund R W and Nachtigal N (1991) QMR: a Quasi-Minimal Residual Method for Non-Hermitian Linear Systems Numer. Math. 60 315–339
Golub G H and Van Loan C F (1996) Matrix Computations (3rd Edition) Johns Hopkins University Press, Baltimore
Higham N J (1988) FORTRAN codes for estimating the one-norm of a real or complex matrix, with applications to condition estimation ACM Trans. Math. Software 14 381–396
Saad Y and Schultz M (1986) GMRES: a generalized minimal residual algorithm for solving nonsymmetric linear systems SIAM J. Sci. Statist. Comput. 7 856–869
Sleijpen G L G and Fokkema D R (1993) BiCGSTABℓ for linear equations involving matrices with complex spectrum ETNA 1 11–32
Sonneveld P (1989) CGS, a fast Lanczos-type solver for nonsymmetric linear systems SIAM J. Sci. Statist. Comput. 10 36–52
Van der Vorst H (1989) Bi-CGSTAB, a fast and smoothly converging variant of Bi-CG for the solution of nonsymmetric linear systems SIAM J. Sci. Statist. Comput. 13 631–644

5 Arguments

1:   METHOD – CHARACTER(*)Input
On entry: the iterative method to be used.
METHOD='RGMRES'
Restarted generalized minimum residual method.
METHOD='CGS'
Conjugate gradient squared method.
METHOD='BICGSTAB'
Bi-conjugate gradient stabilized (ℓ) method.
METHOD='TFQMR'
Transpose-free quasi-minimal residual method.
Constraint: METHOD='RGMRES', 'CGS', 'BICGSTAB' or 'TFQMR'.
2:   PRECON – CHARACTER(1)Input
On entry: determines whether preconditioning is used.
PRECON='N'
No preconditioning.
PRECON='P'
Preconditioning.
Constraint: PRECON='N' or 'P'.
3:   NORM – CHARACTER(1)Input
On entry: defines the matrix and vector norm to be used in the termination criteria.
NORM='1'
l 1 norm.
NORM='I'
l∞ norm.
NORM='2'
l 2 norm.
Suggested values:
  • if ITERM=1, NORM='I';
  • if ITERM=2, NORM='2'.
Constraints:
  • if ITERM=1, NORM='1', 'I' or '2';
  • if ITERM=2, NORM='2'.
4:   WEIGHT – CHARACTER(1)Input
On entry: specifies whether a vector w of user-supplied weights is to be used in the computation of the vector norms required in termination criterion (2) (ITERM=1): v p w=v w p, where vi w =wi vi, for i=1,2,…,n. The suffix p=1,2,∞ denotes the vector norm used, as specified by the argument NORM. Note that weights cannot be used when ITERM=2, i.e., when criterion (3) is used.
WEIGHT='W'
User-supplied weights are to be used and must be supplied on initial entry to F11BEF.
WEIGHT='N'
All weights are implicitly set equal to one. Weights do not need to be supplied on initial entry to F11BEF.
Suggested value: WEIGHT='N'.
Constraints:
  • if ITERM=1, WEIGHT='W' or 'N';
  • if ITERM=2, WEIGHT='N'.
5:   ITERM – INTEGERInput
On entry: defines the termination criterion to be used.
ITERM=1
Use the termination criterion defined in (2).
ITERM=2
Use the termination criterion defined in (3).
Suggested value: ITERM=1.
Constraints:
  • if METHOD='TFQMR' or WEIGHT='W' or NORM≠'2', ITERM=1;
  • otherwise ITERM=1 or 2.
Note: ITERM=2 is only appropriate for a restricted set of choices for METHOD, NORM and WEIGHT; that is NORM='2', WEIGHT='N' and METHOD≠'TFQMR'.
6:   N – INTEGERInput
On entry: n, the order of the matrix A.
Constraint: N>0.
7:   M – INTEGERInput
On entry: if METHOD='RGMRES', M is the dimension m of the restart subspace.
If METHOD='BICGSTAB', M is the order ℓ of the polynomial Bi-CGSTAB method.
Otherwise, M is not referenced.
Constraints:
  • if METHOD='RGMRES', 0<M≤min N,50;
  • if METHOD='BICGSTAB', 0<M≤min N,10.
8:   TOL – REAL (KIND=nag_wp)Input
On entry: the tolerance τ for the termination criterion. If TOL≤0.0,τ=max ε,n ε is used, where ε is the machine precision. Otherwise τ=max TOL,10 ε,n ε is used.
Constraint: TOL<1.0.
9:   MAXITN – INTEGERInput
On entry: the maximum number of iterations.
Constraint: MAXITN>0.
10:   ANORM – REAL (KIND=nag_wp)Input
On entry: if ANORM>0.0, the value of A p to be used in the termination criterion (2) (ITERM=1).
If ANORM≤0.0, ITERM=1 and NORM='1' or 'I', then A 1=A∞ is estimated internally by F11BEF.
If ITERM=2, ANORM is not referenced.
Constraint: if ITERM=1 and NORM='2', ANORM>0.0.
11:   SIGMAX – REAL (KIND=nag_wp)Input
On entry: if ITERM=2, the largest singular value σ 1 of the preconditioned iteration matrix; otherwise, SIGMAX is not referenced.
If SIGMAX≤0.0, ITERM=2 and METHOD='RGMRES', then the value of σ 1 will be estimated internally.
Constraint: if METHOD='CGS' or 'BICGSTAB' and ITERM=2, SIGMAX>0.0.
12:   MONIT – INTEGERInput
On entry: if MONIT>0, the frequency at which a monitoring step is executed by F11BEF: if METHOD='CGS' or 'TFQMR', a monitoring step is executed every MONIT iterations; otherwise, a monitoring step is executed every MONIT super-iterations (groups of up to m or ℓ iterations for RGMRES or Bi-CGSTAB(ℓ), respectively).
There are some additional computational costs involved in monitoring the solution and residual vectors when the Bi-CGSTAB(ℓ) method is used with ℓ>1.
Constraint: MONIT≤MAXITN.
13:   LWREQ – INTEGEROutput
On exit: the minimum amount of workspace required by F11BEF. (See also Section 5 in F11BEF.)
14:   WORK LWORK – REAL (KIND=nag_wp) arrayCommunication Array
On exit: the array WORK is initialized by F11BDF. It must not be modified before calling the next routine in the suite, namely F11BEF.
15:   LWORK – INTEGERInput
On entry: the dimension of the array WORK as declared in the (sub)program from which F11BDF is called.
Constraint: LWORK≥100.
Note: although the minimum value of LWORK ensures the correct functioning of F11BDF, a larger value is required by the other routines in the suite, namely F11BEF and F11BFF. The required value is as follows:
Method | Requirements
RGMRES | LWORK=100+n m+3+m m+5+1, where m is the dimension of the basis.
CGS | LWORK=100+7 n.
Bi-CGSTAB(ℓ) | LWORK=100+2 n+ℓℓ+2+p, where ℓ is the order of the method.
TFQMR | LWORK=100+10 n,
where
p=2 n | if ℓ>1 and ITERM=2 was supplied.
p=n | if ℓ>1 and a preconditioner is used or ITERM=2 was supplied.
p=0 | otherwise.
16:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
F11BDF has been called out of sequence: either F11BDF has been called twice or F11BEF has not terminated its current task.
IFAIL=-1
On entry, METHOD=value.
Constraint: METHOD='RGMRES', 'CGS', 'BICGSTAB' or 'TFQMR'.
IFAIL=-2
On entry, PRECON=value.
Constraint: PRECON='N' or 'P'.
IFAIL=-3
On entry, NORM=value.
Constraint: NORM='1', 'I' or '2'.
IFAIL=-4
On entry, WEIGHT=value.
Constraint: WEIGHT='N' or 'W'.
IFAIL=-5
On entry, ITERM=value.
Constraint: ITERM=1 or 2.
On entry, ITERM=2 and METHOD='TFQMR'.
Constraint: if ITERM=2, METHOD≠'TFQMR'.
On entry, ITERM=2 and NORM=value.
Constraint: if ITERM=2, NORM='2'.
On entry, ITERM=2 and WEIGHT=value.
Constraint: if ITERM=2, WEIGHT='N'.
IFAIL=-6
On entry, N=value.
Constraint: N>0.
IFAIL=-7
On entry, M=value, N=value and METHOD=value.
Constraint: if METHOD='RGMRES', M≤min N,50. If METHOD='BICGSTAB', M≤min N,10.
On entry, M=value and METHOD=value.
Constraint: if METHOD='RGMRES' or 'BICGSTAB', M>0.
IFAIL=-8
On entry, TOL=value.
Constraint: TOL<1.0.
IFAIL=-9
On entry, MAXITN=value.
Constraint: MAXITN>0.
IFAIL=-10
On entry, ITERM=1, NORM='2' and ANORM=value.
Constraint: if ITERM=1 and NORM='2', ANORM>0.0.
IFAIL=-11
On entry, ITERM=2, METHOD=value and SIGMAX=value.
Constraint: if ITERM=2 and METHOD='CGS' or 'BICGSTAB', SIGMAX>0.0.
IFAIL=-12
On entry, MONIT=value and MAXITN=value.
Constraint: MONIT≤MAXITN.
IFAIL=-15
On entry, LWORK=value.
Constraint: LWORK≥100.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

Not applicable.

8 Parallelism and Performance

F11BDF is not threaded in any implementation.

9 Further Comments

RGMRES can estimate internally the maximum singular value σ 1 of the iteration matrix, using σ 1∼T 1, where T is the upper triangular matrix obtained by QR factorization of the upper Hessenberg matrix generated by the Arnoldi process. The computational costs of this computation are negligible when compared to the overall costs.
Loss of orthogonality in the RGMRES method, or of bi-orthogonality in the Bi-CGSTAB(ℓ) method may degrade the solution and speed of convergence. For both methods, the algorithms employed include checks on the basis vectors so that the number of basis vectors used for a given super-iteration may be less than the value specified in the input argument M. Also, if termination criterion (2) is used the CGS, Bi-CGSTAB(ℓ) and TFQMR methods will restart automatically the computation from the last available iterates, when the stability of the solution process requires it.
Termination criterion (3), when available, involves only the residual (or norm of the residual) produced directly by the iteration process: this may differ from the norm of the true residual r~k=b-A xk, particularly when the norm of the residual is very small. Also, if the norm of the initial estimate of the solution is much larger than the norm of the exact solution, convergence can be achieved despite very large errors in the solution. On the other hand, termination criterion (3) is cheaper to use and inspects the progress of the actual iteration. Termination criterion (2) should be preferred in most cases, despite its slightly larger costs.

10 Example

This example solves an 8×8 nonsymmetric system of simultaneous linear equations using the bi-conjugate gradient stabilized method of order ℓ=1, where the coefficients matrix A has a random sparsity pattern. An incomplete LU preconditioner is used (routines F11DAF and F11DBF).

10.1 Program Text

Program Text (f11bdfe.f90)

10.2 Program Data

Program Data (f11bdfe.d)

10.3 Program Results

Program Results (f11bdfe.r)

F11 Chapter Contents
F11 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F11BEF : NAG Library, Mark 26

F11 Chapter Contents
F11 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F11BEF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
10 Example

1 Purpose

F11BEF is an iterative solver for a real general (nonsymmetric) system of simultaneous linear equations; F11BEF is the second in a suite of three routines, where the first routine, F11BDF, must be called prior to F11BEF to set up the suite, and the third routine in the suite, F11BFF, can be used to return additional information about the computation.
These three routines are suitable for the solution of large sparse general (nonsymmetric) systems of equations.

2 Specification

SUBROUTINE F11BEF ( IREVCM, U, V, WGT, WORK, LWORK, IFAIL)
INTEGER | IREVCM, LWORK, IFAIL
REAL (KIND=nag_wp) | U(*), V(*), WGT(*), WORK(LWORK)

3 Description

F11BEF solves the general (nonsymmetric) system of linear simultaneous equations Ax=b of order n, where n is large and the coefficient matrix A is sparse, using one of four available methods: RGMRES, the preconditioned restarted generalized minimum residual method (see Saad and Schultz (1986)); CGS, the preconditioned conjugate gradient squared method (see Sonneveld (1989)); Bi-CGSTAB(ℓ), the bi-conjugate gradient stabilized method of order ℓ (see Van der Vorst (1989) and Sleijpen and Fokkema (1993)); or TFQMR, the transpose-free quasi-minimal residual method (see Freund and Nachtigal (1991) and Freund (1993)).
For a general description of the methods employed you are referred to Section 3 in F11BDF.
F11BEF can solve the system after the first routine in the suite, F11BDF, has been called to initialize the computation and specify the method of solution. The third routine in the suite, F11BFF, can be used to return additional information generated by the computation, during monitoring steps and after F11BEF has completed its tasks.
F11BEF uses reverse communication, i.e., it returns repeatedly to the calling program with the argument IREVCM (see Section 5) set to specified values which require the calling program to carry out one of the following tasks:
– | compute the matrix-vector product v=Au or v=AT u (the four methods require the matrix transpose-vector product only if A 1 or A∞ is estimated internally by Higham's method (see Higham (1988)));
– | solve the preconditioning equation Mv=u;
– | notify the completion of the computation;
– | allow the calling program to monitor the solution.
Through the argument IREVCM the calling program can cause immediate or tidy termination of the execution. On final exit, the last iterates of the solution and of the residual vectors of the original system of equations are returned.
Reverse communication has the following advantages.
1. | Maximum flexibility in the representation and storage of sparse matrices: all matrix operations are performed outside the solver routine, thereby avoiding the need for a complicated interface with enough flexibility to cope with all types of storage schemes and sparsity patterns. This applies also to preconditioners.
2. | Enhanced user interaction: you can closely monitor the progress of the solution and tidy or immediate termination can be requested. This is useful, for example, when alternative termination criteria are to be employed or in case of failure of the external routines used to perform matrix operations.

4 References

Freund R W (1993) A transpose-free quasi-minimal residual algorithm for non-Hermitian linear systems SIAM J. Sci. Comput. 14 470–482
Freund R W and Nachtigal N (1991) QMR: a Quasi-Minimal Residual Method for Non-Hermitian Linear Systems Numer. Math. 60 315–339
Higham N J (1988) FORTRAN codes for estimating the one-norm of a real or complex matrix, with applications to condition estimation ACM Trans. Math. Software 14 381–396
Saad Y and Schultz M (1986) GMRES: a generalized minimal residual algorithm for solving nonsymmetric linear systems SIAM J. Sci. Statist. Comput. 7 856–869
Sleijpen G L G and Fokkema D R (1993) BiCGSTABℓ for linear equations involving matrices with complex spectrum ETNA 1 11–32
Sonneveld P (1989) CGS, a fast Lanczos-type solver for nonsymmetric linear systems SIAM J. Sci. Statist. Comput. 10 36–52
Van der Vorst H (1989) Bi-CGSTAB, a fast and smoothly converging variant of Bi-CG for the solution of nonsymmetric linear systems SIAM J. Sci. Statist. Comput. 13 631–644

5 Arguments

Note: this routine uses reverse communication. Its use involves an initial entry, intermediate exits and re-entries, and a final exit, as indicated by the argument IREVCM. Between intermediate exits and re-entries, all arguments other than IREVCM and V must remain unchanged.
1:   IREVCM – INTEGERInput/Output
On initial entry: IREVCM=0, otherwise an error condition will be raised.
On intermediate re-entry: must either be unchanged from its previous exit value, or can have one of the following values.
IREVCM=5
Tidy termination: the computation will terminate at the end of the current iteration. Further reverse communication exits may occur depending on when the termination request is issued. F11BEF will then return with the termination code IREVCM=4. Note that before calling F11BEF with IREVCM=5 the calling program must have performed the tasks required by the value of IREVCM returned by the previous call to F11BEF, otherwise subsequently returned values may be invalid.
IREVCM=6
Immediate termination: F11BEF will return immediately with termination code IREVCM=4 and with any useful information available. This includes the last iterate of the solution. The residual vector is generally not available.
Immediate termination may be useful, for example, when errors are detected during matrix-vector multiplication or during the solution of the preconditioning equation.
Changing IREVCM to any other value between calls will result in an error.
On intermediate exit: has the following meanings.
IREVCM=-1
The calling program must compute the matrix-vector product v=AT u, where u and v are stored in U and V, respectively; RGMRES, CGS and Bi-CGSTAB(ℓ) methods return IREVCM=-1 only if the matrix norm A 1 or A∞ is estimated internally using Higham's method. This can only happen if ITERM=1 in F11BDF.
IREVCM=1
The calling program must compute the matrix-vector product v=Au, where u and v are stored in U and V, respectively.
IREVCM=2
The calling program must solve the preconditioning equation Mv=u, where u and v are stored in U and V, respectively.
IREVCM=3
Monitoring step: the solution and residual at the current iteration are returned in the arrays U and V, respectively. No action by the calling program is required. F11BFF can be called at this step to return additional information.
On final exit: IREVCM=4: F11BEF has completed its tasks. The value of IFAIL determines whether the iteration has been successfully completed, errors have been detected or the calling program has requested termination.
Constraint: on initial entry, IREVCM=0; on re-entry, either IREVCM must remain unchanged or be reset to 5 or 6.
2:   U* – REAL (KIND=nag_wp) arrayInput/Output
Note: the dimension of the array U must be at least n.
On initial entry: an initial estimate, x 0, of the solution of the system of equations Ax=b.
On intermediate re-entry: must remain unchanged.
On intermediate exit: the returned value of IREVCM determines the contents of U in the following way:
  • if IREVCM=-1, 1 or 2, U holds the vector u on which the operation specified by IREVCM is to be carried out;
  • if IREVCM=3, U holds the current iterate of the solution vector.
On final exit: if IFAIL=3 or IFAIL<0, the array U is unchanged from the initial entry to F11BEF.
If IFAIL=1, the array U is unchanged from the last entry to F11BEF.
Otherwise, U holds the last available iterate of the solution of the system of equations, for all returned values of IFAIL.
3:   V* – REAL (KIND=nag_wp) arrayInput/Output
Note: the dimension of the array V must be at least n.
On initial entry: the right-hand side b of the system of equations Ax=b.
On intermediate re-entry: the returned value of IREVCM determines the contents of V in the following way:
  • if IREVCM=-1, 1 or 2, V must store the vector v, the result of the operation specified by the value of IREVCM returned by the previous call to F11BEF;
  • if IREVCM=3, V must remain unchanged.
On intermediate exit: if IREVCM=3, V holds the current iterate of the residual vector. Note that this is an approximation to the true residual vector. Otherwise, it does not contain any useful information.
On final exit: if IFAIL=3 or IFAIL<0, the array V is unchanged from the initial entry to F11BEF.
If IFAIL=1, the array V is unchanged from the last entry to F11BEF.
If IFAIL=0 or 2, the array V contains the true residual vector of the system of equations (see also Section 6).
Otherwise, V stores the last available iterate of the residual vector unless IFAIL=8 is returned on last entry, in which case V is set to 0.0.
4:   WGT* – REAL (KIND=nag_wp) arrayInput
Note: the dimension of the array WGT must be at least max 1,n.
On entry: the user-supplied weights, if these are to be used in the computation of the vector norms in the termination criterion (see Sections 3 and 5 in F11BDF).
Constraint: if weights are to be used, at least one element of WGT must be nonzero.
5:   WORK LWORK – REAL (KIND=nag_wp) arrayCommunication Array
On initial entry: the array WORK as returned by F11BDF (see also Section 5 in F11BDF).
On intermediate re-entry: must remain unchanged.
6:   LWORK – INTEGERInput
On initial entry: the dimension of the array WORK as declared in the (sub)program from which F11BEF is called (see also Sections 3 and 5 in F11BDF). The required amount of workspace is as follows:
Method | Requirements
RGMRES | LWORK=100+n m+3+m m+5+1, where m is the dimension of the basis.
CGS | LWORK=100+7 n.
Bi-CGSTAB(ℓ) | LWORK=100+2 n+ℓℓ+2+p, where ℓ is the order of the method.
TFQMR | LWORK=100+10 n,
where
p=2 n | if ℓ>1 and ITERM=2 was supplied.
p=n | if ℓ>1 and a preconditioner is used or ITERM=2 was supplied.
p=0 | otherwise.
Constraint: LWORK≥LWREQ, where LWREQ is returned by F11BDF.
7:   IFAIL – INTEGERInput/Output
On initial entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, because for this routine the values of the output arguments may be useful even if IFAIL≠0 on exit, the recommended value is -1. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On intermediate exit: the value of IFAIL is meaningless and should be ignored.
On final exit: (i.e., when IREVCM=4) IFAIL=0, unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=-i
On entry, the ith argument had an illegal value.
IFAIL=1
F11BEF has been called again after returning the termination code IREVCM=4. No further computation has been carried out and all input data and data stored for access by F11BFF have remained unchanged.
IFAIL=2
The required accuracy could not be obtained. However, F11BEF has terminated with reasonable accuracy: the last iterate of the residual satisfied the termination criterion but the exact residual r=b-Ax, did not. After the first occurrence of this situation, the iteration was restarted once, but F11BEF could not improve on the accuracy. This error code usually implies that your problem has been fully and satisfactorily solved to within or close to the accuracy available on your system. Further iterations are unlikely to improve on this situation. You should call F11BFF to check the values of the left- and right-hand sides of the termination condition.
IFAIL=3
F11BDF was either not called before calling F11BEF or it returned an error. The arguments U and V remain unchanged.
IFAIL=4
The calling program requested a tidy termination before the solution had converged. The arrays U and V return the last iterates available of the solution and of the residual vector, respectively.
IFAIL=5
The solution did not converge within the maximum number of iterations allowed. The arrays U and V return the last iterates available of the solution and of the residual vector, respectively.
IFAIL=6
Algorithmic breakdown. The last available iterates of the solution and residuals are returned, although it is possible that they are completely inaccurate.
IFAIL=8
The calling program requested an immediate termination. However, the array U returns the last iterate of the solution, the array V returns the last iterate of the residual vector, for the CGS and TFQMR methods only.
IFAIL=10
User-supplied weights are to be used, but all elements of the array WGT are zero.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

On completion, i.e., IREVCM=4 on exit, the arrays U and V will return the solution and residual vectors, xk and rk=b-A xk, respectively, at the kth iteration, the last iteration performed, unless an immediate termination was requested.
On successful completion, the termination criterion is satisfied to within the user-specified tolerance, as described in Section 3 in F11BDF. The computed values of the left- and right-hand sides of the termination criterion selected can be obtained by a call to F11BFF.

8 Parallelism and Performance

F11BEF is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
F11BEF makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The number of operations carried out by F11BEF for each iteration is likely to be principally determined by the computation of the matrix-vector products v=Au and by the solution of the preconditioning equation Mv=u in the calling program. Each of these operations is carried out once every iteration.
The number of the remaining operations in F11BEF for each iteration is approximately proportional to n.
The number of iterations required to achieve a prescribed accuracy cannot be easily determined at the onset, as it can depend dramatically on the conditioning and spectrum of the preconditioned matrix of the coefficients A-=M-1 A (RGMRES, CGS and TFQMR methods) or A-=A M-1 (Bi-CGSTAB(ℓ) method).
Additional matrix-vector products are required for the computation of A 1 or A∞, when this has not been supplied to F11BDF and is required by the termination criterion employed.
If the termination criterion rk p ≤ τ b p+A p × xk p is used (see Section 3 in F11BDF) and x 0≫xk, then the required accuracy cannot be obtained due to loss of significant digits. The iteration is restarted automatically at some suitable point: F11BEF sets x 0=xk and the computation begins again. For particularly badly scaled problems, more than one restart may be necessary. This does not apply to the RGMRES method which, by its own nature, self-restarts every super-iteration. Naturally, restarting adds to computational costs: it is recommended that the iteration should start from a value x 0 which is as close to the true solution x~ as can be estimated. Otherwise, the iteration should start from x 0=0.

10 Example

See Section 10 in F11BDF.
F11 Chapter Contents
F11 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F11BFF : NAG Library, Mark 26

F11 Chapter Contents
F11 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F11BFF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
10 Example

1 Purpose

F11BFF is the third in a suite of three routines for the iterative solution of a real general (nonsymmetric) system of simultaneous linear equations (see Golub and Van Loan (1996)). F11BFF returns information about the computations during an iteration and/or after this has been completed. The first routine of the suite, F11BDF, is a setup routine; the second routine, F11BEF, is the iterative solver itself.
These three routines are suitable for the solution of large sparse general (nonsymmetric) systems of equations.

2 Specification

SUBROUTINE F11BFF ( ITN, STPLHS, STPRHS, ANORM, SIGMAX, WORK, LWORK, IFAIL)
INTEGER | ITN, LWORK, IFAIL
REAL (KIND=nag_wp) | STPLHS, STPRHS, ANORM, SIGMAX, WORK(LWORK)

3 Description

F11BFF returns information about the solution process. It can be called either during a monitoring step of F11BEF or after F11BEF has completed its tasks. Calling F11BFF at any other time will result in an error condition being raised.
For further information you should read the documentation for F11BDF and F11BEF.

4 References

Golub G H and Van Loan C F (1996) Matrix Computations (3rd Edition) Johns Hopkins University Press, Baltimore

5 Arguments

1:   ITN – INTEGEROutput
On exit: the number of iterations carried out by F11BEF.
2:   STPLHS – REAL (KIND=nag_wp)Output
On exit: the current value of the left-hand side of the termination criterion used by F11BEF.
3:   STPRHS – REAL (KIND=nag_wp)Output
On exit: the current value of the right-hand side of the termination criterion used by F11BEF.
4:   ANORM – REAL (KIND=nag_wp)Output
On exit: if ITERM=1 in the previous call to F11BDF, then ANORM contains A p, where p=1, 2 or ∞, either supplied or, in the case of 1 or ∞, estimated by F11BEF; otherwise ANORM=0.0.
5:   SIGMAX – REAL (KIND=nag_wp)Output
On exit: if ITERM=2 in the previous call to F11BDF, the current estimate of the largest singular value σ 1 A- of the preconditioned iteration matrix, either when it has been supplied to F11BDF or it has been estimated by F11BEF (see also Sections 3 and 5 in F11BDF); otherwise, SIGMAX=0.0 is returned.
6:   WORK LWORK – REAL (KIND=nag_wp) arrayCommunication Array
On entry: the array WORK as returned by F11BEF (see also Sections 3 and 5 in F11BEF).
7:   LWORK – INTEGERInput
On entry: the dimension of the array WORK as declared in the (sub)program from which F11BFF is called (see also Section 5 in F11BDF).
Constraint: LWORK≥100.
Note: although the minimum value of LWORK ensures the correct functioning of F11BFF, a larger value is required by the iterative solver F11BEF (see also Section 5 in F11BDF).
8:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=-i
On entry, the ith argument had an illegal value.
IFAIL=1
F11BFF has been called out of sequence. For example, the last call to F11BEF did not return IREVCM=3 or 4.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

Not applicable.

8 Parallelism and Performance

F11BFF is not threaded in any implementation.

9 Further Comments

None.

10 Example

See Section 10 in F11BDF.
F11 Chapter Contents
F11 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F11BRF : NAG Library, Mark 26

F11 Chapter Contents
F11 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F11BRF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
▸▿ 3 Description
3.1 Restarted Generalized Minimum Residual Method (RGMRES)
3.2 Conjugate Gradient Squared Method (CGS)
3.3 Bi-Conjugate Gradient Stabilized (ℓ) Method (Bi-CGSTAB(ℓ))
3.4 Transpose-free Quasi-minimal Residual Method (TFQMR)
3.5 General Considerations
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F11BRF is a setup routine, the first in a suite of three routines for the iterative solution of a complex general (non-Hermitian) system of simultaneous linear equations. F11BRF must be called before F11BSF, the iterative solver. The third routine in the suite, F11BTF, can be used to return additional information about the computation.
These three routines are suitable for the solution of large sparse general (non-Hermitian) systems of equations.

2 Specification

SUBROUTINE F11BRF ( METHOD, PRECON, NORM, WEIGHT, ITERM, N, M, TOL, MAXITN, ANORM, SIGMAX, MONIT, LWREQ, WORK, LWORK, IFAIL)
INTEGER | ITERM, N, M, MAXITN, MONIT, LWREQ, LWORK, IFAIL
REAL (KIND=nag_wp) | TOL, ANORM, SIGMAX
COMPLEX (KIND=nag_wp) | WORK(LWORK)
CHARACTER(*) | METHOD
CHARACTER(1) | PRECON, NORM, WEIGHT

3 Description

The suite consisting of the routines F11BRF, F11BSF and F11BTF is designed to solve the general (non-Hermitian) system of simultaneous linear equations Ax=b of order n, where n is large and the coefficient matrix A is sparse.
F11BRF is a setup routine which must be called before F11BSF, the iterative solver. The third routine in the suite, F11BTF, can be used to return additional information about the computation. A choice of methods is available:
  • restarted generalized minimum residual method (RGMRES);
  • conjugate gradient squared method (CGS);
  • bi-conjugate gradient stabilized (ℓ) method (Bi-CGSTAB(ℓ));
  • transpose-free quasi-minimal residual method (TFQMR).

3.1 Restarted Generalized Minimum Residual Method (RGMRES)

The restarted generalized minimum residual method (RGMRES) (see Saad and Schultz (1986), Barrett et al. (1994) and Dias da Cunha and Hopkins (1994)) starts from the residual r 0=b-A x 0, where x 0 is an initial estimate for the solution (often x 0=0). An orthogonal basis for the Krylov subspace span Ak r 0, for k=0,1,…, is generated explicitly: this is referred to as Arnoldi's method (see Arnoldi (1951)). The solution is then expanded onto the orthogonal basis so as to minimize the residual norm b-Ax 2. The lack of symmetry of A implies that the orthogonal basis is generated by applying a ‘long’ recurrence relation, whose length increases linearly with the iteration count. For all but the most trivial problems, computational and storage costs can quickly become prohibitive as the iteration count increases. RGMRES limits these costs by employing a restart strategy: every m iterations at most, the Arnoldi process is restarted from rl=b-A xl, where the subscript l denotes the last available iterate. Each group of m iterations is referred to as a ‘super-iteration’. The value of m is chosen in advance and is fixed throughout the computation. Unfortunately, an optimum value of m cannot easily be predicted.

3.2 Conjugate Gradient Squared Method (CGS)

The conjugate gradient squared method (CGS) (see Sonneveld (1989), Barrett et al. (1994) and Dias da Cunha and Hopkins (1994)) is a development of the bi-conjugate gradient method where the nonsymmetric Lanczos method is applied to reduce the coefficients matrix to tridiagonal form: two bi-orthogonal sequences of vectors are generated starting from the residual r 0=b-A x 0, where x 0 is an initial estimate for the solution (often x 0=0) and from the shadow residual r^0 corresponding to the arbitrary problem AH x^=b^, where b^ can be any vector, but in practice is chosen so that r 0=r^0. In the course of the iteration, the residual and shadow residual ri=Pi A r 0 and r^i=Pi AH r^0 are generated, where Pi is a polynomial of order i, and bi-orthogonality is exploited by computing the vector product ρi=r^i,ri=Pi AH r^0, Pi A r 0=r^0,Pi 2 A r 0. Applying the ‘contraction’ operator Pi A twice, the iteration coefficients can still be recovered without advancing the solution of the shadow problem, which is of no interest. The CGS method often provides fast convergence; however, there is no reason why the contraction operator should also reduce the once reduced vector Pi A r 0: this may well lead to a highly irregular convergence which may result in large cancellation errors.

3.3 Bi-Conjugate Gradient Stabilized (ℓ) Method (Bi-CGSTAB(ℓ))

The bi-conjugate gradient stabilized (ℓ) method (Bi-CGSTAB(ℓ)) (see Van der Vorst (1989), Sleijpen and Fokkema (1993) and Dias da Cunha and Hopkins (1994)) is similar to the CGS method above. However, instead of generating the sequence Pi 2 A r 0, it generates the sequence Qi A Pi A r 0, where the Qi A are polynomials chosen to minimize the residual after the application of the contraction operator Pi A. Two main steps can be identified for each iteration: an OR (Orthogonal Residuals) step where a basis of order ℓ is generated by a Bi-CG iteration and an MR (Minimum Residuals) step where the residual is minimized over the basis generated, by a method akin to GMRES. For ℓ=1, the method corresponds to the Bi-CGSTAB method of Van der Vorst (1989). For ℓ>1, more information about complex eigenvalues of the iteration matrix can be taken into account, and this may lead to improved convergence and robustness. However, as ℓ increases, numerical instabilities may arise. For this reason, a maximum value of ℓ=10 is imposed, but probably ℓ=4 is sufficient in most cases.

3.4 Transpose-free Quasi-minimal Residual Method (TFQMR)

The transpose-free quasi-minimal residual method (TFQMR) (see Freund and Nachtigal (1991) and Freund (1993)) is conceptually derived from the CGS method. The residual is minimized over the space of the residual vectors generated by the CGS iterations under the simplifying assumption that residuals are almost orthogonal. In practice, this is not the case but theoretical analysis has proved the validity of the method. This has the effect of remedying the rather irregular convergence behaviour with wild oscillations in the residual norm that can degrade the numerical performance and robustness of the CGS method. In general, the TFQMR method can be expected to converge at least as fast as the CGS method, in terms of number of iterations, although each iteration involves a higher operation count. When the CGS method exhibits irregular convergence, the TFQMR method can produce much smoother, almost monotonic convergence curves. However, the close relationship between the CGS and TFQMR method implies that the overall speed of convergence is similar for both methods. In some cases, the TFQMR method may converge faster than the CGS method.

3.5 General Considerations

For each method, a sequence of solution iterates xi is generated such that, hopefully, the sequence of the residual norms ri converges to a required tolerance. Note that, in general, convergence, when it occurs, is not monotonic.
In the RGMRES and Bi-CGSTAB(ℓ) methods above, your program must provide the maximum number of basis vectors used, m or ℓ, respectively; however, a smaller number of basis vectors may be generated and used when the stability of the solution process requires this (see Section 9).
Faster convergence can be achieved using a preconditioner (see Golub and Van Loan (1996) and Barrett et al. (1994)). A preconditioner maps the original system of equations onto a different system, say
A-x-=b-, (1)
with, hopefully, better characteristics with respect to its speed of convergence: for example, the condition number of the coefficients matrix can be improved or eigenvalues in its spectrum can be made to coalesce. An orthogonal basis for the Krylov subspace span A-k r-0, for k=0,1,…, is generated and the solution proceeds as outlined above. The algorithms used are such that the solution and residual iterates of the original system are produced, not their preconditioned counterparts. Note that an unsuitable preconditioner or no preconditioning at all may result in a very slow rate, or lack, of convergence. However, preconditioning involves a trade-off between the reduction in the number of iterations required for convergence and the additional computational costs per iteration. Also, setting up a preconditioner may involve non-negligible overheads.
A left preconditioner M-1 can be used by the RGMRES, CGS and TFQMR methods, such that A-=M-1 A∼In in (1), where In is the identity matrix of order n; a right preconditioner M-1 can be used by the Bi-CGSTAB(ℓ) method, such that A-=A M-1∼In. These are formal definitions, used only in the design of the algorithms; in practice, only the means to compute the matrix–vector products v=Au and v=AH u (the latter only being required when an estimate of A 1 or A∞ is computed internally), and to solve the preconditioning equations Mv=u are required, i.e., explicit information about M, or its inverse is not required at any stage.
The first termination criterion
rk p ≤ τ b p + A p × xk p (2)
is available for all four methods. In (2), p=1, ∞​ or ​2 and τ denotes a user-specified tolerance subject to max 10,n, ε≤τ<1, where ε is the machine precision. Facilities are provided for the estimation of the norm of the coefficients matrix A 1 or A∞, when this is not known in advance, by applying Higham's method (see Higham (1988)). Note that A 2 cannot be estimated internally. This criterion uses an error bound derived from backward error analysis to ensure that the computed solution is the exact solution of a problem as close to the original as the termination tolerance requires. Termination criteria employing bounds derived from forward error analysis are not used because any such criteria would require information about the condition number κ A which is not easily obtainable.
The second termination criterion
r-k 2 ≤ τ r-0 2 + σ 1 A- × Δ x-k 2 (3)
is available for all methods except TFQMR. In (3), σ 1 A-=A-2 is the largest singular value of the (preconditioned) iteration matrix A-. This termination criterion monitors the progress of the solution of the preconditioned system of equations and is less expensive to apply than criterion (2) for the Bi-CGSTAB(ℓ) method with ℓ>1. Only the RGMRES method provides facilities to estimate σ 1 A- internally, when this is not supplied (see Section 9).
Termination criterion (2) is the recommended choice, despite its additional costs per iteration when using the Bi-CGSTAB(ℓ) method with ℓ>1. Also, if the norm of the initial estimate is much larger than the norm of the solution, that is, if x 0≫x, a dramatic loss of significant digits could result in complete lack of convergence. The use of criterion (2) will enable the detection of such a situation, and the iteration will be restarted at a suitable point. No such restart facilities are provided for criterion (3).
Optionally, a vector w of user-specified weights can be used in the computation of the vector norms in termination criterion (2), i.e., v p w=v w p, where v w i=wi vi, for i=1,2,…,n. Note that the use of weights increases the computational costs.
The sequence of calls to the routines comprising the suite is enforced: first, the setup routine F11BRF must be called, followed by the solver F11BSF. F11BTF can be called either when F11BSF is carrying out a monitoring step or after F11BSF has completed its tasks. Incorrect sequencing will raise an error condition.
In general, it is not possible to recommend one method in preference to another. RGMRES is often used in the solution of systems arising from PDEs. On the other hand, it can easily stagnate when the size m of the orthogonal basis is too small, or the preconditioner is not good enough. CGS can be the fastest method, but the computed residuals can exhibit instability which may greatly affect the convergence and quality of the solution. Bi-CGSTAB(ℓ) seems robust and reliable, but it can be slower than the other methods: if a preconditioner is used and ℓ>1, Bi-CGSTAB(ℓ) computes the solution of the preconditioned system x-k=M xk: the preconditioning equations must be solved to obtain the required solution. The algorithm employed limits to 10% or less, when no intermediate monitoring is requested, the number of times the preconditioner has to be thus applied compared with the total number of applications of the preconditioner. TFQMR can be viewed as a more robust variant of the CGS method: it shares the CGS method speed but avoids the CGS fluctuations in the residual, which may give rise to instability. Also, when the termination criterion (2) is used, the CGS, Bi-CGSTAB(ℓ) and TFQMR methods will restart the iteration automatically when necessary in order to solve the given problem.

4 References

Arnoldi W (1951) The principle of minimized iterations in the solution of the matrix eigenvalue problem Quart. Appl. Math. 9 17–29
Barrett R, Berry M, Chan T F, Demmel J, Donato J, Dongarra J, Eijkhout V, Pozo R, Romine C and Van der Vorst H (1994) Templates for the Solution of Linear Systems: Building Blocks for Iterative Methods SIAM, Philadelphia
Dias da Cunha R and Hopkins T (1994) PIM 1.1 — the parallel iterative method package for systems of linear equations user's guide — Fortran 77 version Technical Report Computing Laboratory, University of Kent at Canterbury, Kent, UK
Freund R W (1993) A transpose-free quasi-minimal residual algorithm for non-Hermitian linear systems SIAM J. Sci. Comput. 14 470–482
Freund R W and Nachtigal N (1991) QMR: a Quasi-Minimal Residual Method for Non-Hermitian Linear Systems Numer. Math. 60 315–339
Golub G H and Van Loan C F (1996) Matrix Computations (3rd Edition) Johns Hopkins University Press, Baltimore
Higham N J (1988) FORTRAN codes for estimating the one-norm of a real or complex matrix, with applications to condition estimation ACM Trans. Math. Software 14 381–396
Saad Y and Schultz M (1986) GMRES: a generalized minimal residual algorithm for solving nonsymmetric linear systems SIAM J. Sci. Statist. Comput. 7 856–869
Sleijpen G L G and Fokkema D R (1993) BiCGSTABℓ for linear equations involving matrices with complex spectrum ETNA 1 11–32
Sonneveld P (1989) CGS, a fast Lanczos-type solver for nonsymmetric linear systems SIAM J. Sci. Statist. Comput. 10 36–52
Van der Vorst H (1989) Bi-CGSTAB, a fast and smoothly converging variant of Bi-CG for the solution of nonsymmetric linear systems SIAM J. Sci. Statist. Comput. 13 631–644

5 Arguments

1:   METHOD – CHARACTER(*)Input
On entry: the iterative method to be used.
METHOD='RGMRES'
Restarted generalized minimum residual method.
METHOD='CGS'
Conjugate gradient squared method.
METHOD='BICGSTAB'
Bi-conjugate gradient stabilized (ℓ) method.
METHOD='TFQMR'
Transpose-free quasi-minimal residual method.
Constraint: METHOD='RGMRES', 'CGS', 'BICGSTAB' or 'TFQMR'.
2:   PRECON – CHARACTER(1)Input
On entry: determines whether preconditioning is used.
PRECON='N'
No preconditioning.
PRECON='P'
Preconditioning.
Constraint: PRECON='N' or 'P'.
3:   NORM – CHARACTER(1)Input
On entry: defines the matrix and vector norm to be used in the termination criteria.
NORM='1'
l 1 norm.
NORM='I'
l∞ norm.
NORM='2'
l 2 norm.
Suggested values:
  • if ITERM=1, NORM='I';
  • if ITERM=2, NORM='2'.
Constraints:
  • if ITERM=1, NORM='1', 'I' or '2';
  • if ITERM=2, NORM='2'.
4:   WEIGHT – CHARACTER(1)Input
On entry: specifies whether a vector w of user-supplied weights is to be used in the computation of the vector norms required in termination criterion (2) (ITERM=1): v p w=v w p, where vi w =wi vi, for i=1,2,…,n. The suffix p=1,2,∞ denotes the vector norm used, as specified by the argument NORM. Note that weights cannot be used when ITERM=2, i.e., when criterion (3) is used.
WEIGHT='W'
User-supplied weights are to be used and must be supplied on initial entry to F11BSF.
WEIGHT='N'
All weights are implicitly set equal to one. Weights do not need to be supplied on initial entry to F11BSF.
Suggested value: WEIGHT='N'.
Constraints:
  • if ITERM=1, WEIGHT='W' or 'N';
  • if ITERM=2, WEIGHT='N'.
5:   ITERM – INTEGERInput
On entry: defines the termination criterion to be used.
ITERM=1
Use the termination criterion defined in (2).
ITERM=2
Use the termination criterion defined in (3).
Suggested value: ITERM=1.
Constraints:
  • if METHOD='TFQMR' or WEIGHT='W' or NORM≠'2', ITERM=1;
  • otherwise ITERM=1 or 2.
Note: ITERM=2 is only appropriate for a restricted set of choices for METHOD, NORM and WEIGHT; that is NORM='2', WEIGHT='N' and METHOD≠'TFQMR'.
6:   N – INTEGERInput
On entry: n, the order of the matrix A.
Constraint: N>0.
7:   M – INTEGERInput
On entry: if METHOD='RGMRES', M is the dimension m of the restart subspace.
If METHOD='BICGSTAB', M is the order ℓ of the polynomial Bi-CGSTAB method.
Otherwise, M is not referenced.
Constraints:
  • if METHOD='RGMRES', 0<M≤min N,50;
  • if METHOD='BICGSTAB', 0<M≤min N,10.
8:   TOL – REAL (KIND=nag_wp)Input
On entry: the tolerance τ for the termination criterion. If TOL≤0.0,τ=max ε,n ε is used, where ε is the machine precision. Otherwise τ=max TOL,10 ε,n ε is used.
Constraint: TOL<1.0.
9:   MAXITN – INTEGERInput
On entry: the maximum number of iterations.
Constraint: MAXITN>0.
10:   ANORM – REAL (KIND=nag_wp)Input
On entry: if ANORM>0.0, the value of A p to be used in the termination criterion (2) (ITERM=1).
If ANORM≤0.0, ITERM=1 and NORM='1' or 'I', then A 1=A∞ is estimated internally by F11BSF.
If ITERM=2, ANORM is not referenced.
Constraint: if ITERM=1 and NORM='2', ANORM>0.0.
11:   SIGMAX – REAL (KIND=nag_wp)Input
On entry: if ITERM=2, the largest singular value σ 1 of the preconditioned iteration matrix; otherwise, SIGMAX is not referenced.
If SIGMAX≤0.0, ITERM=2 and METHOD='RGMRES', then the value of σ 1 will be estimated internally.
Constraint: if METHOD='CGS' or 'BICGSTAB' and ITERM=2, SIGMAX>0.0.
12:   MONIT – INTEGERInput
On entry: if MONIT>0, the frequency at which a monitoring step is executed by F11BSF: if METHOD='CGS' or 'TFQMR', a monitoring step is executed every MONIT iterations; otherwise, a monitoring step is executed every MONIT super-iterations (groups of up to m or ℓ iterations for RGMRES or Bi-CGSTAB(ℓ), respectively).
There are some additional computational costs involved in monitoring the solution and residual vectors when the Bi-CGSTAB(ℓ) method is used with ℓ>1.
Constraint: MONIT≤MAXITN.
13:   LWREQ – INTEGEROutput
On exit: the minimum amount of workspace required by F11BSF. (See also Section 5 in F11BSF.)
14:   WORK LWORK – COMPLEX (KIND=nag_wp) arrayCommunication Array
On exit: the array WORK is initialized by F11BRF. It must not be modified before calling the next routine in the suite, namely F11BSF.
15:   LWORK – INTEGERInput
On entry: the dimension of the array WORK as declared in the (sub)program from which F11BRF is called.
Constraint: LWORK≥120.
Note: although the minimum value of LWORK ensures the correct functioning of F11BRF, a larger value is required by the other routines in the suite, namely F11BSF and F11BTF. The required value is as follows:
Method | Requirements
RGMRES | LWORK=120+n m+3+m m+5+1, where m is the dimension of the basis.
CGS | LWORK=120+7 n.
Bi-CGSTAB(ℓ) | LWORK=120+2 n+ℓℓ+2+p, where ℓ is the order of the method.
TFQMR | LWORK=120+10 n,
where
p=2 n | if ℓ>1 and ITERM=2 was supplied.
p=n | if ℓ>1 and a preconditioner is used or ITERM=2 was supplied.
p=0 | otherwise.
16:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=-i
On entry, the ith argument had an illegal value.
IFAIL=1
F11BRF has been called out of sequence.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

Not applicable.

8 Parallelism and Performance

F11BRF is not threaded in any implementation.

9 Further Comments

RGMRES can estimate internally the maximum singular value σ 1 of the iteration matrix, using σ 1∼T 1, where T is the upper triangular matrix obtained by QR factorization of the upper Hessenberg matrix generated by the Arnoldi process. The computational costs of this computation are negligible when compared to the overall costs.
Loss of orthogonality in the RGMRES method, or of bi-orthogonality in the Bi-CGSTAB(ℓ) method may degrade the solution and speed of convergence. For both methods, the algorithms employed include checks on the basis vectors so that the number of basis vectors used for a given super-iteration may be less than the value specified in the input argument M. Also, if termination criterion (2) is used, the CGS, Bi-CGSTAB(ℓ) and TFQMR methods will restart automatically the computation from the last available iterates, when the stability of the solution process requires it.
Termination criterion (3), when available, involves only the residual (or norm of the residual) produced directly by the iteration process: this may differ from the norm of the true residual r~k=b-A xk, particularly when the norm of the residual is very small. Also, if the norm of the initial estimate of the solution is much larger than the norm of the exact solution, convergence can be achieved despite very large errors in the solution. On the other hand, termination criterion (3) is cheaper to use and inspects the progress of the actual iteration. Termination criterion (2) should be preferred in most cases, despite its slightly larger costs.

10 Example

This example solves an 8×8 non-Hermitian system of simultaneous linear equations using the TFQMR method where the coefficients matrix A has a random sparsity pattern. An incomplete LU preconditioner is used (routines F11DNF and F11DPF).

10.1 Program Text

Program Text (f11brfe.f90)

10.2 Program Data

Program Data (f11brfe.d)

10.3 Program Results

Program Results (f11brfe.r)

F11 Chapter Contents
F11 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F11BSF : NAG Library, Mark 26

F11 Chapter Contents
F11 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F11BSF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
10 Example

1 Purpose

F11BSF is an iterative solver for a complex general (non-Hermitian) system of simultaneous linear equations; F11BSF is the second in a suite of three routines, where the first routine, F11BRF, must be called prior to F11BSF to set up the suite, and the third routine in the suite, F11BTF, can be used to return additional information about the computation.
These three routines are suitable for the solution of large sparse general (non-Hermitian) systems of equations.

2 Specification

SUBROUTINE F11BSF ( IREVCM, U, V, WGT, WORK, LWORK, IFAIL)
INTEGER | IREVCM, LWORK, IFAIL
REAL (KIND=nag_wp) | WGT(*)
COMPLEX (KIND=nag_wp) | U(*), V(*), WORK(LWORK)

3 Description

F11BSF solves the general (non-Hermitian) system of linear simultaneous equations Ax=b of order n, where n is large and the coefficient matrix A is sparse, using one of four available methods: RGMRES, the preconditioned restarted generalized minimum residual method (see Saad and Schultz (1986)); CGS, the preconditioned conjugate gradient squared method (see Sonneveld (1989)); Bi-CGSTAB(ℓ), the bi-conjugate gradient stabilized method of order ℓ (see Van der Vorst (1989) and Sleijpen and Fokkema (1993)); or TFQMR, the transpose-free quasi-minimal residual method (see Freund and Nachtigal (1991) and Freund (1993)).
For a general description of the methods employed you are referred to Section 3 in F11BRF.
F11BSF can solve the system after the first routine in the suite, F11BRF, has been called to initialize the computation and specify the method of solution. The third routine in the suite, F11BTF, can be used to return additional information generated by the computation during monitoring steps and after F11BSF has completed its tasks.
F11BSF uses reverse communication, i.e., it returns repeatedly to the calling program with the argument IREVCM (see Section 5) set to specified values which require the calling program to carry out one of the following tasks:
  • compute the matrix-vector product v=Au or v=AH u (the four methods require the matrix transpose-vector product only if A 1 or A∞ is estimated internally by Higham's method (see Higham (1988)));
  • solve the preconditioning equation Mv=u;
  • notify the completion of the computation;
  • allow the calling program to monitor the solution.
Through the argument IREVCM the calling program can cause immediate or tidy termination of the execution. On final exit, the last iterates of the solution and of the residual vectors of the original system of equations are returned.
Reverse communication has the following advantages.
1. | Maximum flexibility in the representation and storage of sparse matrices: all matrix operations are performed outside the solver routine, thereby avoiding the need for a complicated interface with enough flexibility to cope with all types of storage schemes and sparsity patterns. This applies also to preconditioners.
2. | Enhanced user interaction: you can closely monitor the progress of the solution and tidy or immediate termination can be requested. This is useful, for example, when alternative termination criteria are to be employed or in case of failure of the external routines used to perform matrix operations.

4 References

Freund R W (1993) A transpose-free quasi-minimal residual algorithm for non-Hermitian linear systems SIAM J. Sci. Comput. 14 470–482
Freund R W and Nachtigal N (1991) QMR: a Quasi-Minimal Residual Method for Non-Hermitian Linear Systems Numer. Math. 60 315–339
Higham N J (1988) FORTRAN codes for estimating the one-norm of a real or complex matrix, with applications to condition estimation ACM Trans. Math. Software 14 381–396
Saad Y and Schultz M (1986) GMRES: a generalized minimal residual algorithm for solving nonsymmetric linear systems SIAM J. Sci. Statist. Comput. 7 856–869
Sleijpen G L G and Fokkema D R (1993) BiCGSTABℓ for linear equations involving matrices with complex spectrum ETNA 1 11–32
Sonneveld P (1989) CGS, a fast Lanczos-type solver for nonsymmetric linear systems SIAM J. Sci. Statist. Comput. 10 36–52
Van der Vorst H (1989) Bi-CGSTAB, a fast and smoothly converging variant of Bi-CG for the solution of nonsymmetric linear systems SIAM J. Sci. Statist. Comput. 13 631–644

5 Arguments

Note: this routine uses reverse communication. Its use involves an initial entry, intermediate exits and re-entries, and a final exit, as indicated by the argument IREVCM. Between intermediate exits and re-entries, all arguments other than IREVCM and V must remain unchanged.
1:   IREVCM – INTEGERInput/Output
On initial entry: IREVCM=0, otherwise an error condition will be raised.
On intermediate re-entry: must either be unchanged from its previous exit value, or can have one of the following values.
IREVCM=5
Tidy termination: the computation will terminate at the end of the current iteration. Further reverse communication exits may occur depending on when the termination request is issued. F11BSF will then return with the termination code IREVCM=4. Note that before calling F11BSF with IREVCM=5 the calling program must have performed the tasks required by the value of IREVCM returned by the previous call to F11BSF, otherwise subsequently returned values may be invalid.
IREVCM=6
Immediate termination: F11BSF will return immediately with termination code IREVCM=4 and with any useful information available. This includes the last iterate of the solution.
Immediate termination may be useful, for example, when errors are detected during matrix-vector multiplication or during the solution of the preconditioning equation.
Changing IREVCM to any other value between calls will result in an error.
On intermediate exit: has the following meanings.
IREVCM=-1
The calling program must compute the matrix-vector product v=AH u, where u and v are stored in U and V, respectively; RGMRES, CGS and Bi-CGSTAB(ℓ) methods return IREVCM=-1 only if the matrix norm A 1 or A∞ is estimated internally using Higham's method. This can only happen if ITERM=1 in F11BRF.
IREVCM=1
The calling program must compute the matrix-vector product v=Au, where u and v are stored in U and V, respectively.
IREVCM=2
The calling program must solve the preconditioning equation Mv=u, where u and v are stored in U and V, respectively.
IREVCM=3
Monitoring step: the solution and residual at the current iteration are returned in the arrays U and V, respectively. No action by the calling program is required. F11BTF can be called at this step to return additional information.
On final exit: IREVCM=4: F11BSF has completed its tasks. The value of IFAIL determines whether the iteration has been successfully completed, errors have been detected or the calling program has requested termination.
Constraint: on initial entry, IREVCM=0; on re-entry, either IREVCM must remain unchanged or be reset to IREVCM=5 or 6.
2:   U* – COMPLEX (KIND=nag_wp) arrayInput/Output
Note: the dimension of the array U must be at least n.
On initial entry: an initial estimate, x 0, of the solution of the system of equations Ax=b.
On intermediate re-entry: must remain unchanged.
On intermediate exit: the returned value of IREVCM determines the contents of U as follows.
If IREVCM=-1, 1 or 2, U holds the vector u on which the operation specified by IREVCM is to be carried out.
If IREVCM=3, U holds the current iterate of the solution vector.
On final exit: if IFAIL=3 or IFAIL<0, the array U is unchanged from the initial entry to F11BSF.
If IFAIL=1, the array U is unchanged from the last entry to F11BSF.
Otherwise, U holds the last available iterate of the solution of the system of equations, for all returned values of IFAIL.
3:   V* – COMPLEX (KIND=nag_wp) arrayInput/Output
Note: the dimension of the array V must be at least n.
On initial entry: the right-hand side b of the system of equations Ax=b.
On intermediate re-entry: the returned value of IREVCM determines the contents of V as follows.
If IREVCM=-1, 1 or 2, V must store the vector v, the result of the operation specified by the value of IREVCM returned by the previous call to F11BSF.
If IREVCM=3, V must remain unchanged.
On intermediate exit: if IREVCM=3, V holds the current iterate of the residual vector. Note that this is an approximation to the true residual vector. Otherwise, it does not contain any useful information.
On final exit: if IFAIL=3 or IFAIL<0, the array V is unchanged from the initial entry to F11BSF.
If IFAIL=1, the array V is unchanged from the last entry to F11BSF.
If IFAIL=0 or 2, the array V contains the true residual vector of the system of equations (see also Section 6).
Otherwise, V stores the last available iterate of the residual vector unless IFAIL=8 is returned on last entry, in which case V is set to 0.0.
4:   WGT* – REAL (KIND=nag_wp) arrayInput
Note: the dimension of the array WGT must be at least max 1,n.
On entry: the user-supplied weights, if these are to be used in the computation of the vector norms in the termination criterion (see Sections 3 and 5 in F11BRF).
Constraint: if weights are to be used, at least one element of WGT must be nonzero.
5:   WORK LWORK – COMPLEX (KIND=nag_wp) arrayCommunication Array
On initial entry: the array WORK as returned by F11BRF (see also Section 5 in F11BRF).
On intermediate re-entry: must remain unchanged.
6:   LWORK – INTEGERInput
On initial entry: the dimension of the array WORK as declared in the (sub)program from which F11BSF is called (see also Sections 3 and 5 in F11BRF). The required amount of workspace is as follows:
Method | Requirements
RGMRES | LWORK=120+n m+3+m m+5+1, where m is the dimension of the basis
CGS | LWORK=120+7 n
Bi-CGSTAB(ℓ) | LWORK=120+2 n+ℓℓ+2+p, where ℓ is the order of the method
TFQMR | LWORK=120+10 n,
where
  • p=2 n, if ℓ>1 and ITERM=2 was supplied;
  • p=n, if ℓ>1 and a preconditioner is used or ITERM=2 was supplied;
  • p=0, otherwise.
Constraint: LWORK≥LWREQ, where LWREQ is returned by F11BRF.
7:   IFAIL – INTEGERInput/Output
On initial entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, because for this routine the values of the output arguments may be useful even if IFAIL≠0 on exit, the recommended value is -1. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On intermediate exit: the value of IFAIL is meaningless and should be ignored.
On final exit: (i.e., when IREVCM=4) IFAIL=0, unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=-i
On entry, the ith argument had an illegal value.
IFAIL=1
F11BSF has been called again after returning the termination code IREVCM=4. No further computation has been carried out and all input data and data stored for access by F11BTF have remained unchanged.
IFAIL=2
The required accuracy could not be obtained. However, F11BSF has terminated with reasonable accuracy: the last iterate of the residual satisfied the termination criterion but the exact residual r=b-Ax, did not. After the first occurrence of this situation, the iteration was restarted once, but F11BSF could not improve on the accuracy. This error code usually implies that your problem has been fully and satisfactorily solved to within or close to the accuracy available on your system. Further iterations are unlikely to improve on this situation. You should call F11BTF to check the values of the left- and right-hand sides of the termination condition.
IFAIL=3
F11BRF was either not called before calling F11BSF or it returned an error. The arguments U and V remain unchanged.
IFAIL=4
The calling program requested a tidy termination before the solution had converged. The arrays U and V return the last iterates available of the solution and of the residual vector, respectively.
IFAIL=5
The solution did not converge within the maximum number of iterations allowed. The arrays U and V return the last iterates available of the solution and of the residual vector, respectively.
IFAIL=6
Algorithmic breakdown. The last available iterates of the solution and residuals are returned, although it is possible that they are completely inaccurate.
IFAIL=8
The calling program requested an immediate termination. However, the array U returns the last iterate of the solution, the array V returns the last iterate of the residual vector, for the CGS and TFQMR methods only.
IFAIL=10
User-supplied weights are to be used, but all elements of the array WGT are zero.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

On completion, i.e., IREVCM=4 on exit, the arrays U and V will return the solution and residual vectors, xk and rk=b-A xk, respectively, at the kth iteration, the last iteration performed, unless an immediate termination was requested.
On successful completion, the termination criterion is satisfied to within the user-specified tolerance, as described in F11BRF. The computed values of the left- and right-hand sides of the termination criterion selected can be obtained by a call to F11BTF.

8 Parallelism and Performance

F11BSF is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
F11BSF makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The number of operations carried out by F11BSF for each iteration is likely to be principally determined by the computation of the matrix-vector products v=Au and by the solution of the preconditioning equation Mv=u in the calling program. Each of these operations is carried out once every iteration.
The number of the remaining operations in F11BSF for each iteration is approximately proportional to n.
The number of iterations required to achieve a prescribed accuracy cannot be easily determined at the onset, as it can depend dramatically on the conditioning and spectrum of the preconditioned matrix of the coefficients A-=M-1 A (RGMRES, CGS and TFQMR methods) or A-=A M-1 (Bi-CGSTAB(ℓ) method).
Additional matrix-vector products are required for the computation of A 1 or A∞, when this has not been supplied to F11BRF and is required by the termination criterion employed.
If the termination criterion rk p ≤ τ b p+A p × xk p is used (see Section 3 in F11BRF) and x 0≫xk, then the required accuracy cannot be obtained due to loss of significant digits. The iteration is restarted automatically at some suitable point: F11BSF sets x 0=xk and the computation begins again. For particularly badly scaled problems, more than one restart may be necessary. This does not apply to the RGMRES method which, by its own nature, self-restarts every super-iteration. Naturally, restarting adds to computational costs: it is recommended that the iteration should start from a value x 0 which is as close to the true solution x~ as can be estimated. Otherwise, the iteration should start from x 0=0.

10 Example

See Section 10 in F11BRF.
F11 Chapter Contents
F11 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F11BTF : NAG Library, Mark 26

F11 Chapter Contents
F11 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F11BTF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
10 Example

1 Purpose

F11BTF is the third in a suite of three routines for the iterative solution of a complex general (non-Hermitian) system of simultaneous linear equations (see Golub and Van Loan (1996)). F11BTF returns information about the computations during an iteration and/or after this has been completed. The first routine of the suite, F11BRF, is a setup routine; the second routine, F11BSF, is the iterative solver itself.
These three routines are suitable for the solution of large sparse general (non-Hermitian) systems of equations.

2 Specification

SUBROUTINE F11BTF ( ITN, STPLHS, STPRHS, ANORM, SIGMAX, WORK, LWORK, IFAIL)
INTEGER | ITN, LWORK, IFAIL
REAL (KIND=nag_wp) | STPLHS, STPRHS, ANORM, SIGMAX
COMPLEX (KIND=nag_wp) | WORK(LWORK)

3 Description

F11BTF returns information about the solution process. It can be called either during a monitoring step of F11BSF or after F11BSF has completed its tasks. Calling F11BTF at any other time will result in an error condition being raised.
For further information you should read the documentation for F11BRF and F11BSF.

4 References

Golub G H and Van Loan C F (1996) Matrix Computations (3rd Edition) Johns Hopkins University Press, Baltimore

5 Arguments

1:   ITN – INTEGEROutput
On exit: the number of iterations carried out by F11BSF.
2:   STPLHS – REAL (KIND=nag_wp)Output
On exit: the current value of the left-hand side of the termination criterion used by F11BSF.
3:   STPRHS – REAL (KIND=nag_wp)Output
On exit: the current value of the right-hand side of the termination criterion used by F11BSF.
4:   ANORM – REAL (KIND=nag_wp)Output
On exit: if ITERM=1 in the previous call to F11BRF, then ANORM contains A p, where p=1, 2 or ∞, either supplied or, in the case of 1 or ∞, estimated by F11BSF; otherwise ANORM=0.0.
5:   SIGMAX – REAL (KIND=nag_wp)Output
On exit: if ITERM=2 in the previous call to F11BRF, the current estimate of the largest singular value σ 1 A- of the preconditioned iteration matrix when it is used by the termination criterion in F11BSF, either when it has been supplied to F11BRF or it has been estimated by F11BSF (see also Sections 3 and 5 in F11BRF); otherwise, SIGMAX=0.0 is returned.
6:   WORK LWORK – COMPLEX (KIND=nag_wp) arrayCommunication Array
On entry: the array WORK as returned by F11BSF (see also Sections 3 and 5 in F11BSF).
7:   LWORK – INTEGERInput
On entry: the dimension of the array WORK as declared in the (sub)program from which F11BTF is called (see also F11BRF).
Constraint: LWORK≥120.
Note: although the minimum value of LWORK ensures the correct functioning of F11BTF, a larger value is required by the iterative solver F11BSF (see also F11BRF).
8:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=-i
On entry, the ith argument had an illegal value.
IFAIL=1
F11BTF has been called out of sequence. For example, the last call to F11BSF did not return IREVCM=3 or 4.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

Not applicable.

8 Parallelism and Performance

F11BTF is not threaded in any implementation.

9 Further Comments

None.

10 Example

See Section 10 in F11BRF.
F11 Chapter Contents
F11 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F11 Chapter Contents : NAG Library Manual, Mark 26

F11 Chapter Introduction
NAG Library Manual

NAG Library Chapter Contents

F11 – Large Scale Linear Systems

F11 Chapter Introduction – a description of the Chapter and an overview of the algorithms available

Routine Name | Mark of Introduction | Purpose
F11BDF Example Text Example Data | 19 | nagf_sparse_real_gen_basic_setup Real sparse nonsymmetric linear systems, setup for F11BEF
F11BEF | 19 | nagf_sparse_real_gen_basic_solver Real sparse nonsymmetric linear systems, preconditioned RGMRES, CGS, Bi-CGSTAB or TFQMR method
F11BFF | 19 | nagf_sparse_real_gen_basic_diag Real sparse nonsymmetric linear systems, diagnostic for F11BEF
F11BRF Example Text Example Data | 19 | nagf_sparse_complex_gen_basic_setup Complex sparse non-Hermitian linear systems, setup for F11BSF
F11BSF | 19 | nagf_sparse_complex_gen_basic_solver Complex sparse non-Hermitian linear systems, preconditioned RGMRES, CGS, Bi-CGSTAB or TFQMR method
F11BTF | 19 | nagf_sparse_complex_gen_basic_diag Complex sparse non-Hermitian linear systems, diagnostic for F11BSF
F11DAF Example Text Example Data | 18 | nagf_sparse_real_gen_precon_ilu Real sparse nonsymmetric linear systems, incomplete LU factorization
F11DBF Example Text Example Data | 18 | nagf_sparse_real_gen_precon_ilu_solve Solution of linear system involving incomplete LU preconditioning matrix generated by F11DAF
F11DCF Example Text Example Data | 18 | nagf_sparse_real_gen_solve_ilu Solution of real sparse nonsymmetric linear system, RGMRES, CGS, Bi-CGSTAB or TFQMR method, preconditioner computed by F11DAF
F11DDF Example Text Example Data | 18 | nagf_sparse_real_gen_precon_ssor_solve Solution of linear system involving preconditioning matrix generated by applying SSOR to real sparse nonsymmetric matrix
F11DEF Example Text Example Data | 18 | nagf_sparse_real_gen_solve_jacssor Solution of real sparse nonsymmetric linear system, RGMRES, CGS, Bi-CGSTAB, or TFQMR method, Jacobi or SSOR preconditioner (Black Box)
F11DFF Example Text Example Data | 24 | nagf_sparse_real_gen_precon_bdilu Real sparse nonsymmetric linear system, incomplete LU factorization of local or overlapping diagonal blocks
F11DGF Example Text Example Data | 24 | nagf_sparse_real_gen_solve_bdilu Solution of real sparse nonsymmetric linear system, RGMRES, CGS, Bi-CGSTAB or TFQMR method, incomplete LU block diagonal preconditioner computed by F11DFF
F11DKF Example Text Example Data | 20 | nagf_sparse_real_gen_precon_jacobi Real, sparse, symmetric or nonsymmetric, linear systems, line Jacobi preconditioner
F11DNF Example Text Example Data | 19 | nagf_sparse_complex_gen_precon_ilu Complex sparse non-Hermitian linear systems, incomplete LU factorization
F11DPF Example Text Example Data | 19 | nagf_sparse_complex_gen_precon_ilu_solve Solution of complex linear system involving incomplete LU preconditioning matrix generated by F11DNF
F11DQF Example Text Example Data | 19 | nagf_sparse_complex_gen_solve_ilu Solution of complex sparse non-Hermitian linear system, RGMRES, CGS, Bi-CGSTAB or TFQMR method, preconditioner computed by F11DNF (Black Box)
F11DRF Example Text Example Data | 19 | nagf_sparse_complex_gen_precon_ssor_solve Solution of linear system involving preconditioning matrix generated by applying SSOR to complex sparse non-Hermitian matrix
F11DSF Example Text Example Data | 19 | nagf_sparse_complex_gen_solve_jacssor Solution of complex sparse non-Hermitian linear system, RGMRES, CGS, Bi-CGSTAB or TFQMR method, Jacobi or SSOR preconditioner Black Box
F11DTF Example Text Example Data | 24 | nagf_sparse_complex_gen_precon_bdilu Complex, sparse, non-Hermitian linear system, incomplete LU factorization of local or overlapping diagonal blocks
F11DUF Example Text Example Data | 24 | nagf_sparse_complex_gen_solve_bdilu Solution of complex, sparse, non-Hermitian linear system, RGMRES, CGS, Bi-CGSTAB or TFQMR method, incomplete LU block diagonal preconditioner computed by F11DTF
F11DXF Example Text Example Data | 20 | nagf_sparse_complex_gen_precon_jacobi Complex, sparse, Hermitian or non-Hermitian, linear systems, line Jacobi preconditioner
F11GDF Example Text Example Data | 20 | nagf_sparse_real_symm_basic_setup Real sparse symmetric linear systems, setup for F11GEF
F11GEF | 20 | nagf_sparse_real_symm_basic_solver Real sparse symmetric linear systems, preconditioned conjugate gradient or Lanczos method or the MINRES algorithm
F11GFF | 20 | nagf_sparse_real_symm_basic_diag Real sparse symmetric linear systems, diagnostic for F11GEF
F11GRF Example Text Example Data | 20 | nagf_sparse_complex_herm_basic_setup Complex sparse Hermitian linear systems, setup for F11GSF
F11GSF | 20 | nagf_sparse_complex_herm_basic_solver Complex sparse Hermitian linear systems, preconditioned conjugate gradient or Lanczos
F11GTF | 20 | nagf_sparse_complex_herm_basic_diag Complex sparse Hermitian linear systems, diagnostic for F11GSF
F11JAF Example Text Example Data | 17 | nagf_sparse_real_symm_precon_ichol Real sparse symmetric matrix, incomplete Cholesky factorization
F11JBF Example Text Example Data | 17 | nagf_sparse_real_symm_precon_ichol_solve Solution of linear system involving incomplete Cholesky preconditioning matrix generated by F11JAF
F11JCF Example Text Example Data | 17 | nagf_sparse_real_symm_solve_ichol Solution of real sparse symmetric linear system, conjugate gradient/Lanczos method, preconditioner computed by F11JAF (Black Box)
F11JDF Example Text Example Data | 17 | nagf_sparse_real_symm_precon_ssor_solve Solution of linear system involving preconditioning matrix generated by applying SSOR to real sparse symmetric matrix
F11JEF Example Text Example Data | 17 | nagf_sparse_real_symm_solve_jacssor Solution of real sparse symmetric linear system, conjugate gradient/Lanczos method, Jacobi or SSOR preconditioner (Black Box)
F11JNF Example Text Example Data | 19 | nagf_sparse_complex_herm_precon_ilu Complex sparse Hermitian matrix, incomplete Cholesky factorization
F11JPF Example Text Example Data | 19 | nagf_sparse_complex_herm_precon_ilu_solve Solution of complex linear system involving incomplete Cholesky preconditioning matrix generated by F11JNF
F11JQF Example Text Example Data | 19 | nagf_sparse_complex_herm_solve_ilu Solution of complex sparse Hermitian linear system, conjugate gradient/Lanczos method, preconditioner computed by F11JNF (Black Box)
F11JRF Example Text Example Data | 19 | nagf_sparse_complex_herm_precon_ssor_solve Solution of linear system involving preconditioning matrix generated by applying SSOR to complex sparse Hermitian matrix
F11JSF Example Text Example Data | 19 | nagf_sparse_complex_herm_solve_jacssor Solution of complex sparse Hermitian linear system, conjugate gradient/Lanczos method, Jacobi or SSOR preconditioner (Black Box)
F11MDF Example Text Example Data | 21 | nagf_sparse_direct_real_gen_setup Real sparse nonsymmetric linear systems, setup for F11MEF
F11MEF Example Text Example Data | 21 | nagf_sparse_direct_real_gen_lu LU factorization of real sparse matrix
F11MFF Example Text Example Data | 21 | nagf_sparse_direct_real_gen_solve Solution of real sparse simultaneous linear equations (coefficient matrix already factorized)
F11MGF Example Text Example Data | 21 | nagf_sparse_direct_real_gen_cond Estimate condition number of real matrix, matrix already factorized by F11MEF
F11MHF Example Text Example Data | 21 | nagf_sparse_direct_real_gen_refine Refined solution with error bounds of real system of linear equations, multiple right-hand sides
F11MKF Example Text Example Data | 21 | nagf_sparse_direct_real_gen_matmul Real sparse nonsymmetric matrix-matrix multiply, compressed column storage
F11MLF Example Text Example Data | 21 | nagf_sparse_direct_real_gen_norm 1-norm, ∞-norm, largest absolute element, real, square, sparse matrix
F11MMF Example Text Example Data | 21 | nagf_sparse_direct_real_gen_diag Real sparse nonsymmetric linear systems, diagnostic for F11MEF
F11XAF Example Text Example Data | 18 | nagf_sparse_real_gen_matvec Real, sparse, nonsymmetric matrix-vector multiply
F11XEF Example Text Example Data | 17 | nagf_sparse_real_symm_matvec Real sparse symmetric matrix-vector multiply
F11XNF Example Text Example Data | 19 | nagf_sparse_complex_gen_matvec Complex sparse non-Hermitian matrix-vector multiply
F11XSF Example Text Example Data | 19 | nagf_sparse_complex_herm_matvec Complex sparse Hermitian matrix-vector multiply
F11YEF Example Text Example Data Example Plot | 25 | nagf_sparse_sym_rcm Reverse Cuthill–McKee reordering of a sparse symmetric matrix in CCS format
F11ZAF Example Text Example Data | 18 | nagf_sparse_real_gen_sort Real sparse nonsymmetric matrix reorder routine
F11ZBF Example Text Example Data | 17 | nagf_sparse_real_symm_sort Real sparse symmetric matrix reorder routine
F11ZNF Example Text Example Data | 19 | nagf_sparse_complex_gen_sort Complex sparse non-Hermitian matrix reorder routine
F11ZPF Example Text Example Data | 19 | nagf_sparse_complex_herm_sort Complex sparse Hermitian matrix reorder routine
F11 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F11DAF : NAG Library, Mark 26

F11 Chapter Contents
F11 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F11DAF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
▸▿ 9 Further Comments
9.1 Timing
9.2 Control of Fill-in
9.3 Algorithmic Details
9.4 Choice of Arguments
9.5 Direct Solution of Sparse Linear Systems
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F11DAF computes an incomplete LU factorization of a real sparse nonsymmetric matrix, represented in coordinate storage format. This factorization may be used as a preconditioner in combination with F11BEF or F11DCF.

2 Specification

SUBROUTINE F11DAF ( N, NNZ, A, LA, IROW, ICOL, LFILL, DTOL, PSTRAT, MILU, IPIVP, IPIVQ, ISTR, IDIAG, NNZC, NPIVM, IWORK, LIWORK, IFAIL)
INTEGER | N, NNZ, LA, IROW(LA), ICOL(LA), LFILL, IPIVP(N), IPIVQ(N), ISTR(N+1), IDIAG(N), NNZC, NPIVM, IWORK(LIWORK), LIWORK, IFAIL
REAL (KIND=nag_wp) | A(LA), DTOL
CHARACTER(1) | PSTRAT, MILU

3 Description

F11DAF computes an incomplete LU factorization (see Meijerink and Van der Vorst (1977) and Meijerink and Van der Vorst (1981)) of a real sparse nonsymmetric n by n matrix A. The factorization is intended primarily for use as a preconditioner with one of the iterative solvers F11BEF or F11DCF.
The decomposition is written in the form
A=M+R
where
M=PLDUQ
and L is lower triangular with unit diagonal elements, D is diagonal, U is upper triangular with unit diagonals, P and Q are permutation matrices, and R is a remainder matrix.
The amount of fill-in occurring in the factorization can vary from zero to complete fill, and can be controlled by specifying either the maximum level of fill LFILL, or the drop tolerance DTOL.
The argument PSTRAT defines the pivoting strategy to be used. The options currently available are no pivoting, user-defined pivoting, partial pivoting by columns for stability, and complete pivoting by rows for sparsity and by columns for stability. The factorization may optionally be modified to preserve the row-sums of the original matrix.
The sparse matrix A is represented in coordinate storage (CS) format (see Section 2.1.1 in the F11 Chapter Introduction). The array A stores all the nonzero elements of the matrix A, while arrays IROW and ICOL store the corresponding row and column indices respectively. Multiple nonzero elements may not be specified for the same row and column index.
The preconditioning matrix M is returned in terms of the CS representation of the matrix
C=L+D-1+U-2 I.
Further algorithmic details are given in Section 9.3.

4 References

Meijerink J and Van der Vorst H (1977) An iterative solution method for linear systems of which the coefficient matrix is a symmetric M-matrix Math. Comput. 31 148–162
Meijerink J and Van der Vorst H (1981) Guidelines for the usage of incomplete decompositions in solving sets of linear equations as they occur in practical problems J. Comput. Phys. 44 134–155
Salvini S A and Shaw G J (1996) An evaluation of new NAG Library solvers for large sparse unsymmetric linear systems NAG Technical Report TR2/96

5 Arguments

1:   N – INTEGERInput
On entry: n, the order of the matrix A.
Constraint: N≥1.
2:   NNZ – INTEGERInput
On entry: the number of nonzero elements in the matrix A.
Constraint: 1≤NNZ≤N 2.
3:   A LA – REAL (KIND=nag_wp) arrayInput/Output
On entry: the nonzero elements in the matrix A, ordered by increasing row index, and by increasing column index within each row. Multiple entries for the same row and column indices are not permitted. The routine F11ZAF may be used to order the elements in this way.
On exit: the first NNZ entries of A contain the nonzero elements of A and the next NNZC entries contain the elements of the matrix C. Matrix elements are ordered by increasing row index, and by increasing column index within each row.
4:   LA – INTEGERInput
On entry: the dimension of the arrays A, IROW and ICOL as declared in the (sub)program from which F11DAF is called. These arrays must be of sufficient size to store both A (NNZ elements) and C (NNZC elements).
Constraint: LA≥2×NNZ.
5:   IROW LA – INTEGER arrayInput/Output
6:   ICOL LA – INTEGER arrayInput/Output
On entry: the row and column indices of the nonzero elements supplied in A.
Constraints:
IROW and ICOL must satisfy these constraints (which may be imposed by a call to F11ZAF):
  • 1≤IROW i≤N and 1≤ICOL i≤N, for i=1,2,…,NNZ;
  • either IROW i-1<IROW i or both IROW i-1=IROW i and ICOL i-1<ICOL i, for i=2,3,…,NNZ.
On exit: the row and column indices of the nonzero elements returned in A.
7:   LFILL – INTEGERInput
On entry: if LFILL≥0 its value is the maximum level of fill allowed in the decomposition (see Section 9.2). A negative value of LFILL indicates that DTOL will be used to control the fill instead.
8:   DTOL – REAL (KIND=nag_wp)Input
On entry: if LFILL<0, DTOL is used as a drop tolerance to control the fill-in (see Section 9.2); otherwise DTOL is not referenced.
Constraint: if LFILL<0, DTOL≥0.0.
9:   PSTRAT – CHARACTER(1)Input
On entry: specifies the pivoting strategy to be adopted.
PSTRAT='N'
No pivoting is carried out.
PSTRAT='U'
Pivoting is carried out according to the user-defined input values of IPIVP and IPIVQ.
PSTRAT='P'
Partial pivoting by columns for stability is carried out.
PSTRAT='C'
Complete pivoting by rows for sparsity, and by columns for stability, is carried out.
Suggested value: PSTRAT='C'.
Constraint: PSTRAT='N', 'U', 'P' or 'C'.
10:   MILU – CHARACTER(1)Input
On entry: indicates whether or not the factorization should be modified to preserve row-sums (see Section 9.4).
MILU='M'
The factorization is modified.
MILU='N'
The factorization is not modified.
Constraint: MILU='M' or 'N'.
11:   IPIVP N – INTEGER arrayInput/Output
12:   IPIVQ N – INTEGER arrayInput/Output
On entry: if PSTRAT='U', then IPIVP k and IPIVQ k must specify the row and column indices of the element used as a pivot at elimination stage k. Otherwise IPIVP and IPIVQ need not be initialized.
Constraint: if PSTRAT='U', IPIVP and IPIVQ must both hold valid permutations of the integers on [1,N].
On exit: the pivot indices. If IPIVP k=i and IPIVQ k=j then the element in row i and column j was used as the pivot at elimination stage k.
13:   ISTR N+1 – INTEGER arrayOutput
On exit: ISTR i, for i=1,2,…,N, is the starting address in the arrays A, IROW and ICOL of row i of the matrix C. ISTR N+1 is the address of the last nonzero element in C plus one.
14:   IDIAG N – INTEGER arrayOutput
On exit: IDIAG i, for i=1,2,…,N, holds the index of arrays A, IROW and ICOL which holds the diagonal element in row i of the matrix C.
15:   NNZC – INTEGEROutput
On exit: the number of nonzero elements in the matrix C.
16:   NPIVM – INTEGEROutput
On exit: if NPIVM>0 it gives the number of pivots which were modified during the factorization to ensure that M exists.
If NPIVM=-1 no pivot modifications were required, but a local restart occurred (see Section 9.3). The quality of the preconditioner will generally depend on the returned value of NPIVM.
If NPIVM is large the preconditioner may not be satisfactory. In this case it may be advantageous to call F11DAF again with an increased value of LFILL, a reduced value of DTOL, or set PSTRAT='C'. See also Section 9.5.
17:   IWORK LIWORK – INTEGER arrayWorkspace
18:   LIWORK – INTEGERInput
On entry: the dimension of the array IWORK as declared in the (sub)program from which F11DAF is called.
Constraint: LIWORK≥7×N+2.
19:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, | N<1,
or | NNZ<1,
or | NNZ>N 2,
or | LA<2×NNZ,
or | LFILL<0 and DTOL<0.0,
or | PSTRAT≠'N', 'U', 'P' or 'C',
or | MILU≠'M' or 'N',
or | LIWORK<7×N+2.
IFAIL=2
On entry, the arrays IROW and ICOL fail to satisfy the following constraints:
  • 1≤IROW i≤N and 1≤ICOL i≤N, for i=1,2,…,NNZ;
  • IROW i-1<IROW i or IROW i-1=IROW i and ICOL i-1<ICOL i, for i=2,3,…,NNZ.
Therefore a nonzero element has been supplied which does not lie within the matrix A, is out of order, or has duplicate row and column indices. Call F11ZAF to reorder and sum or remove duplicates.
IFAIL=3
On entry, PSTRAT='U', but one or both of IPIVP and IPIVQ does not represent a valid permutation of the integers in [1,N]. An input value of IPIVP or IPIVQ is either out of range or repeated.
IFAIL=4
LA is too small, resulting in insufficient storage space for fill-in elements. The decomposition has been terminated before completion. Either increase LA or reduce the amount of fill by reducing LFILL, or increasing DTOL.
IFAIL=5 (F11ZAF)
A serious error has occurred in an internal call to the specified routine. Check all subroutine calls and array sizes. Seek expert help.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

The accuracy of the factorization will be determined by the size of the elements that are dropped and the size of any modifications made to the pivot elements. If these sizes are small then the computed factors will correspond to a matrix close to A. The factorization can generally be made more accurate by increasing LFILL, or by reducing DTOL with LFILL<0.
If F11DAF is used in combination with F11BEF or F11DCF, the more accurate the factorization the fewer iterations will be required. However, the cost of the decomposition will also generally increase.

8 Parallelism and Performance

F11DAF is not threaded in any implementation.

9 Further Comments

9.1 Timing

The time taken for a call to F11DAF is roughly proportional to NNZC 2/N.

9.2 Control of Fill-in

If LFILL≥0 the amount of fill-in occurring in the incomplete factorization is controlled by limiting the maximum level of fill-in to LFILL. The original nonzero elements of A are defined to be of level 0. The fill level of a new nonzero location occurring during the factorization is defined as:
k=max ke,kc+1,
where ke is the level of fill of the element being eliminated, and kc is the level of fill of the element causing the fill-in.
If LFILL<0 the fill-in is controlled by means of the drop tolerance DTOL. A potential fill-in element a ij occurring in row i and column j will not be included if:
a ij<DTOL×α,
where α is the maximum absolute value element in the matrix A.
For either method of control, any elements which are not included are discarded unless MILU='M', in which case their contributions are subtracted from the pivot element in the relevant elimination row, to preserve the row-sums of the original matrix.
Should the factorization process break down a local restart process is implemented as described in Section 9.3. This will affect the amount of fill present in the final factorization.

9.3 Algorithmic Details

The factorization is constructed row by row. At each elimination stage a row index is chosen. In the case of complete pivoting this index is chosen in order to reduce fill-in. Otherwise the rows are treated in the order given, or some user-defined order.
The chosen row is copied from the original matrix A and modified according to those previous elimination stages which affect it. During this process any fill-in elements are either dropped or kept according to the values of LFILL or DTOL. In the case of a modified factorization (MILU='M') the sum of the dropped terms for the given row is stored.
Finally the pivot element for the row is chosen and the multipliers are computed for this elimination stage. For partial or complete pivoting the pivot element is chosen in the interests of stability as the element of largest absolute value in the row. Otherwise the pivot element is chosen in the order given, or some user-defined order.
If the factorization breaks down because the chosen pivot element is zero, or there is no nonzero pivot available, a local restart recovery process is implemented. The modification of the given pivot row according to previous elimination stages is repeated, but this time keeping all fill. Note that in this case the final factorization will include more fill than originally specified by the user-supplied value of LFILL or DTOL. The local restart usually results in a suitable nonzero pivot arising. The original criteria for dropping fill-in elements is then resumed for the next elimination stage (hence the local nature of the restart process). Should this restart process also fail to produce a nonzero pivot element an arbitrary unit pivot is introduced in an arbitrarily chosen column. F11DAF returns an integer argument NPIVM which gives the number of these arbitrary unit pivots introduced. If no pivots were modified but local restarts occurred NPIVM=-1 is returned.

9.4 Choice of Arguments

There is unfortunately no choice of the various algorithmic arguments which is optimal for all types of matrix, and some experimentation will generally be required for each new type of matrix encountered.
If the matrix A is not known to have any particular special properties the following strategy is recommended. Start with LFILL=0 and PSTRAT='C'. If the value returned for NPIVM is significantly larger than zero, i.e., a large number of pivot modifications were required to ensure that M existed, the preconditioner is not likely to be satisfactory. In this case increase LFILL until NPIVM falls to a value close to zero.
If A has non-positive off-diagonal elements, is nonsingular, and has only non-negative elements in its inverse, it is called an ‘M-matrix’. It can be shown that no pivot modifications are required in the incomplete LU factorization of an M-matrix (see Meijerink and Van der Vorst (1977)). In this case a good preconditioner can generally be expected by setting LFILL=0, PSTRAT='N' and MILU='M'.
Some illustrations of the application of F11DAF to linear systems arising from the discretization of two-dimensional elliptic partial differential equations, and to random-valued randomly structured linear systems, can be found in Salvini and Shaw (1996).

9.5 Direct Solution of Sparse Linear Systems

Although it is not their primary purpose F11DAF and F11DBF may be used together to obtain a direct solution to a nonsingular sparse linear system. To achieve this the call to F11DBF should be preceded by a complete LU factorization
A=PLDUQ=M.
A complete factorization is obtained from a call to F11DAF with LFILL<0 and DTOL=0.0, provided NPIVM≤0 on exit. A positive value of NPIVM indicates that A is singular, or ill-conditioned. A factorization with positive NPIVM may serve as a preconditioner, but will not result in a direct solution. It is therefore essential to check the output value of NPIVM if a direct solution is required.
The use of F11DAF and F11DBF as a direct method is illustrated in Section 10 in F11DBF.

10 Example

This example reads in a sparse matrix A and calls F11DAF to compute an incomplete LU factorization. It then outputs the nonzero elements of both A and C=L+D-1+U-2 I.
The call to F11DAF has LFILL=0, and PSTRAT='C', giving an unmodified zero-fill LU factorization, with row pivoting for sparsity and column pivoting for stability.

10.1 Program Text

Program Text (f11dafe.f90)

10.2 Program Data

Program Data (f11dafe.d)

10.3 Program Results

Program Results (f11dafe.r)

F11 Chapter Contents
F11 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F11DBF : NAG Library, Mark 26

F11 Chapter Contents
F11 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F11DBF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
▸▿ 9 Further Comments
9.1 Timing
9.2 Use of CHECK
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F11DBF solves a system of linear equations involving the incomplete LU preconditioning matrix generated by F11DAF.

2 Specification

SUBROUTINE F11DBF ( TRANS, N, A, LA, IROW, ICOL, IPIVP, IPIVQ, ISTR, IDIAG, CHECK, Y, X, IFAIL)
INTEGER | N, LA, IROW(LA), ICOL(LA), IPIVP(N), IPIVQ(N), ISTR(N+1), IDIAG(N), IFAIL
REAL (KIND=nag_wp) | A(LA), Y(N), X(N)
CHARACTER(1) | TRANS, CHECK

3 Description

F11DBF solves a system of linear equations
Mx=y, or MT x=y,
according to the value of the argument TRANS, where the matrix M=PLDUQ, corresponds to an incomplete LU decomposition of a sparse matrix stored in coordinate storage (CS) format (see Section 2.1.1 in the F11 Chapter Introduction), as generated by F11DAF.
In the above decomposition L is a lower triangular sparse matrix with unit diagonal elements, D is a diagonal matrix, U is an upper triangular sparse matrix with unit diagonal elements and, P and Q are permutation matrices. L, D and U are supplied to F11DBF through the matrix
C=L+D-1+U-2 I
which is an N by N sparse matrix, stored in CS format, as returned by F11DAF. The permutation matrices P and Q are returned from F11DAF via the arrays IPIVP and IPIVQ.
It is envisaged that a common use of F11DBF will be to carry out the preconditioning step required in the application of F11BEF to sparse linear systems. F11DBF is used for this purpose by the Black Box routine F11DCF.
F11DBF may also be used in combination with F11DAF to solve a sparse system of linear equations directly (see Section 9.5 in F11DAF). This use of F11DBF is demonstrated in Section 10.

4 References

None.

5 Arguments

1:   TRANS – CHARACTER(1)Input
On entry: specifies whether or not the matrix M is transposed.
TRANS='N'
Mx=y is solved.
TRANS='T'
MT x=y is solved.
Constraint: TRANS='N' or 'T'.
2:   N – INTEGERInput
On entry: n, the order of the matrix M. This must be the same value as was supplied in the preceding call to F11DAF.
Constraint: N≥1.
3:   A LA – REAL (KIND=nag_wp) arrayInput
On entry: the values returned in the array A by a previous call to F11DAF.
4:   LA – INTEGERInput
On entry: the dimension of the arrays A, IROW and ICOL as declared in the (sub)program from which F11DBF is called. This must be the same value returned by the preceding call to F11DAF.
5:   IROW LA – INTEGER arrayInput
6:   ICOL LA – INTEGER arrayInput
7:   IPIVP N – INTEGER arrayInput
8:   IPIVQ N – INTEGER arrayInput
9:   ISTR N+1 – INTEGER arrayInput
10:   IDIAG N – INTEGER arrayInput
On entry: the values returned in arrays IROW, ICOL, IPIVP, IPIVQ, ISTR and IDIAG by a previous call to F11DAF.
11:   CHECK – CHARACTER(1)Input
On entry: specifies whether or not the CS representation of the matrix M should be checked.
CHECK='C'
Checks are carried on the values of N, IROW, ICOL, IPIVP, IPIVQ, ISTR and IDIAG.
CHECK='N'
None of these checks are carried out.
See also Section 9.2.
Constraint: CHECK='C' or 'N'.
12:   Y N – REAL (KIND=nag_wp) arrayInput
On entry: the right-hand side vector y.
13:   X N – REAL (KIND=nag_wp) arrayOutput
On exit: the solution vector x.
14:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, | TRANS≠'N' or 'T',
or | CHECK≠'C' or 'N'.
IFAIL=2
On entry, N<1.
IFAIL=3
On entry, the CS representation of the preconditioning matrix M is invalid. Further details are given in the error message. Check that the call to F11DBF has been preceded by a valid call to F11DAF and that the arrays A, IROW, ICOL, IPIVP, IPIVQ, ISTR and IDIAG have not been corrupted between the two calls.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

If TRANS='N' the computed solution x is the exact solution of a perturbed system of equations M+δM x=y, where
δM≤c n εP LDU Q,
c n is a modest linear function of n, and ε is the machine precision. An equivalent result holds when TRANS='T'.

8 Parallelism and Performance

F11DBF is not threaded in any implementation.

9 Further Comments

9.1 Timing

The time taken for a call to F11DBF is proportional to the value of NNZC returned from F11DAF.

9.2 Use of CHECK

It is expected that a common use of F11DBF will be to carry out the preconditioning step required in the application of F11BEF to sparse linear systems. In this situation F11DBF is likely to be called many times with the same matrix M. In the interests of both reliability and efficiency, you are recommended to set CHECK='C' for the first of such calls, and for all subsequent calls set CHECK='N'.

10 Example

This example reads in a sparse nonsymmetric matrix A and a vector y. It then calls F11DAF, with LFILL=-1 and DTOL=0.0, to compute the complete LU decomposition
A=PLDUQ.
Finally it calls F11DBF to solve the system
PLDUQx=y.

10.1 Program Text

Program Text (f11dbfe.f90)

10.2 Program Data

Program Data (f11dbfe.d)

10.3 Program Results

Program Results (f11dbfe.r)

F11 Chapter Contents
F11 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F11DCF : NAG Library, Mark 26

F11 Chapter Contents
F11 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F11DCF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F11DCF solves a real sparse nonsymmetric system of linear equations, represented in coordinate storage format, using a restarted generalized minimal residual (RGMRES), conjugate gradient squared (CGS), stabilized bi-conjugate gradient (Bi-CGSTAB), or transpose-free quasi-minimal residual (TFQMR) method, with incomplete LU preconditioning.

2 Specification

SUBROUTINE F11DCF ( METHOD, N, NNZ, A, LA, IROW, ICOL, IPIVP, IPIVQ, ISTR, IDIAG, B, M, TOL, MAXITN, X, RNORM, ITN, WORK, LWORK, IFAIL)
INTEGER | N, NNZ, LA, IROW(LA), ICOL(LA), IPIVP(N), IPIVQ(N), ISTR(N+1), IDIAG(N), M, MAXITN, ITN, LWORK, IFAIL
REAL (KIND=nag_wp) | A(LA), B(N), TOL, X(N), RNORM, WORK(LWORK)
CHARACTER(*) | METHOD

3 Description

F11DCF solves a real sparse nonsymmetric linear system of equations:
Ax=b,
using a preconditioned RGMRES (see Saad and Schultz (1986)), CGS (see Sonneveld (1989)), Bi-CGSTAB(ℓ) (see Van der Vorst (1989) and Sleijpen and Fokkema (1993)), or TFQMR (see Freund and Nachtigal (1991) and Freund (1993)) method.
F11DCF uses the incomplete LU factorization determined by F11DAF as the preconditioning matrix. A call to F11DCF must always be preceded by a call to F11DAF. Alternative preconditioners for the same storage scheme are available by calling F11DEF.
The matrix A, and the preconditioning matrix M, are represented in coordinate storage (CS) format (see Section 2.1.1 in the F11 Chapter Introduction) in the arrays A, IROW and ICOL, as returned from F11DAF. The array A holds the nonzero entries in these matrices, while IROW and ICOL hold the corresponding row and column indices.
F11DCF is a Black Box routine which calls F11BDF, F11BEF and F11BFF. If you wish to use an alternative storage scheme, preconditioner, or termination criterion, or require additional diagnostic information, you should call these underlying routines directly.

4 References

Freund R W (1993) A transpose-free quasi-minimal residual algorithm for non-Hermitian linear systems SIAM J. Sci. Comput. 14 470–482
Freund R W and Nachtigal N (1991) QMR: a Quasi-Minimal Residual Method for Non-Hermitian Linear Systems Numer. Math. 60 315–339
Saad Y and Schultz M (1986) GMRES: a generalized minimal residual algorithm for solving nonsymmetric linear systems SIAM J. Sci. Statist. Comput. 7 856–869
Salvini S A and Shaw G J (1996) An evaluation of new NAG Library solvers for large sparse unsymmetric linear systems NAG Technical Report TR2/96
Sleijpen G L G and Fokkema D R (1993) BiCGSTABℓ for linear equations involving matrices with complex spectrum ETNA 1 11–32
Sonneveld P (1989) CGS, a fast Lanczos-type solver for nonsymmetric linear systems SIAM J. Sci. Statist. Comput. 10 36–52
Van der Vorst H (1989) Bi-CGSTAB, a fast and smoothly converging variant of Bi-CG for the solution of nonsymmetric linear systems SIAM J. Sci. Statist. Comput. 13 631–644

5 Arguments

1:   METHOD – CHARACTER(*)Input
On entry: specifies the iterative method to be used.
METHOD='RGMRES'
Restarted generalized minimum residual method.
METHOD='CGS'
Conjugate gradient squared method.
METHOD='BICGSTAB'
Bi-conjugate gradient stabilized (ℓ) method.
METHOD='TFQMR'
Transpose-free quasi-minimal residual method.
Constraint: METHOD='RGMRES', 'CGS', 'BICGSTAB' or 'TFQMR'.
2:   N – INTEGERInput
On entry: n, the order of the matrix A. This must be the same value as was supplied in the preceding call to F11DAF.
Constraint: N≥1.
3:   NNZ – INTEGERInput
On entry: the number of nonzero elements in the matrix A. This must be the same value as was supplied in the preceding call to F11DAF.
Constraint: 1≤NNZ≤N 2.
4:   A LA – REAL (KIND=nag_wp) arrayInput
On entry: the values returned in the array A by a previous call to F11DAF.
5:   LA – INTEGERInput
On entry: the dimension of the arrays A, IROW and ICOL as declared in the (sub)program from which F11DCF is called. This must be the same value as was supplied in the preceding call to F11DAF.
Constraint: LA≥2×NNZ.
6:   IROW LA – INTEGER arrayInput
7:   ICOL LA – INTEGER arrayInput
8:   IPIVP N – INTEGER arrayInput
9:   IPIVQ N – INTEGER arrayInput
10:   ISTR N+1 – INTEGER arrayInput
11:   IDIAG N – INTEGER arrayInput
On entry: the values returned in arrays IROW, ICOL, IPIVP, IPIVQ, ISTR and IDIAG by a previous call to F11DAF.
IPIVP and IPIVQ are restored on exit.
12:   B N – REAL (KIND=nag_wp) arrayInput
On entry: the right-hand side vector b.
13:   M – INTEGERInput
On entry: if METHOD='RGMRES', M is the dimension of the restart subspace.
If METHOD='BICGSTAB', M is the order ℓ of the polynomial Bi-CGSTAB method; otherwise, M is not referenced.
Constraints:
  • if METHOD='RGMRES', 0<M≤min N,50;
  • if METHOD='BICGSTAB', 0<M≤min N,10.
14:   TOL – REAL (KIND=nag_wp)Input
On entry: the required tolerance. Let xk denote the approximate solution at iteration k, and rk the corresponding residual. The algorithm is considered to have converged at iteration k if
rk∞≤τ×b∞+A∞xk∞.
If TOL≤0.0, τ=max⁡ε,10 ε,n ε is used, where ε is the machine precision. Otherwise τ=max TOL,10 ε,n ε is used.
Constraint: TOL<1.0.
15:   MAXITN – INTEGERInput
On entry: the maximum number of iterations allowed.
Constraint: MAXITN≥1.
16:   X N – REAL (KIND=nag_wp) arrayInput/Output
On entry: an initial approximation to the solution vector x.
On exit: an improved approximation to the solution vector x.
17:   RNORM – REAL (KIND=nag_wp)Output
On exit: the final value of the residual norm rk∞, where k is the output value of ITN.
18:   ITN – INTEGEROutput
On exit: the number of iterations carried out.
19:   WORK LWORK – REAL (KIND=nag_wp) arrayWorkspace
20:   LWORK – INTEGERInput
On entry: the dimension of the array WORK as declared in the (sub)program from which F11DCF is called.
Constraints:
  • if METHOD='RGMRES', LWORK≥4×N+M×M+N+5+101;
  • if METHOD='CGS', LWORK≥8×N+100;
  • if METHOD='BICGSTAB', LWORK≥2×N×M+3+M×M+2+100;
  • if METHOD='TFQMR', LWORK≥11×N+100.
21:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, | METHOD≠'RGMRES','CGS','BICGSTAB', or 'TFQMR',
or | N<1,
or | NNZ<1,
or | NNZ>N 2,
or | LA<2×NNZ,
or | M<1 and METHOD='RGMRES' or METHOD='BICGSTAB',
or | M>min N,50, with METHOD='RGMRES',
or | M>min N,10, with METHOD='BICGSTAB',
or | TOL≥1.0,
or | MAXITN<1,
or | LWORK too small.
IFAIL=2
On entry, the CS representation of A is invalid. Further details are given in the error message. Check that the call to F11DCF has been preceded by a valid call to F11DAF, and that the arrays A, IROW, and ICOL have not been corrupted between the two calls.
IFAIL=3
On entry, the CS representation of the preconditioning matrix M is invalid. Further details are given in the error message. Check that the call to F11DCF has been preceded by a valid call to F11DAF and that the arrays A, IROW, ICOL, IPIVP, IPIVQ, ISTR and IDIAG have not been corrupted between the two calls.
IFAIL=4
The required accuracy could not be obtained. However, a reasonable accuracy may have been obtained, and further iterations could not improve the result. You should check the output value of RNORM for acceptability. This error code usually implies that your problem has been fully and satisfactorily solved to within or close to the accuracy available on your system. Further iterations are unlikely to improve on this situation.
IFAIL=5
Required accuracy not obtained in MAXITN iterations.
IFAIL=6
Algorithmic breakdown. A solution is returned, although it is possible that it is completely inaccurate.
IFAIL=7 (F11BDF, F11BEF or F11BFF)
A serious error has occurred in an internal call to one of the specified routines. Check all subroutine calls and array sizes. Seek expert help.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

On successful termination, the final residual rk=b-A xk, where k=ITN, satisfies the termination criterion
rk∞≤τ×b∞+A∞xk∞.
The value of the final residual norm is returned in RNORM.

8 Parallelism and Performance

F11DCF is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
F11DCF makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The time taken by F11DCF for each iteration is roughly proportional to the value of NNZC returned from the preceding call to F11DAF.
The number of iterations required to achieve a prescribed accuracy cannot be easily determined a priori, as it can depend dramatically on the conditioning and spectrum of the preconditioned coefficient matrix A-=M-1 A.
Some illustrations of the application of F11DCF to linear systems arising from the discretization of two-dimensional elliptic partial differential equations, and to random-valued randomly structured linear systems, can be found in Salvini and Shaw (1996).

10 Example

This example solves a sparse linear system of equations using the CGS method, with incomplete LU preconditioning.

10.1 Program Text

Program Text (f11dcfe.f90)

10.2 Program Data

Program Data (f11dcfe.d)

10.3 Program Results

Program Results (f11dcfe.r)

F11 Chapter Contents
F11 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F11DDF : NAG Library, Mark 26

F11 Chapter Contents
F11 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F11DDF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
▸▿ 9 Further Comments
9.1 Timing
9.2 Use of CHECK
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F11DDF solves a system of linear equations involving the preconditioning matrix corresponding to SSOR applied to a real sparse nonsymmetric matrix, represented in coordinate storage format.

2 Specification

SUBROUTINE F11DDF ( TRANS, N, NNZ, A, IROW, ICOL, RDIAG, OMEGA, CHECK, Y, X, IWORK, IFAIL)
INTEGER | N, NNZ, IROW(NNZ), ICOL(NNZ), IWORK(2*N+1), IFAIL
REAL (KIND=nag_wp) | A(NNZ), RDIAG(N), OMEGA, Y(N), X(N)
CHARACTER(1) | TRANS, CHECK

3 Description

F11DDF solves a system of linear equations
Mx=y, or MT x=y,
according to the value of the argument TRANS, where the matrix
M=1 ω 2-ω D+ω L D-1 D+ω U
corresponds to symmetric successive-over-relaxation (SSOR) (see Young (1971)) applied to a linear system Ax=b, where A is a real sparse nonsymmetric matrix stored in coordinate storage (CS) format (see Section 2.1.1 in the F11 Chapter Introduction).
In the definition of M given above D is the diagonal part of A, L is the strictly lower triangular part of A, U is the strictly upper triangular part of A, and ω is a user-defined relaxation parameter.
It is envisaged that a common use of F11DDF will be to carry out the preconditioning step required in the application of F11BEF to sparse linear systems. For an illustration of this use of F11DDF see the example program given in Section 10. F11DDF is also used for this purpose by the Black Box routine F11DEF.

4 References

Young D (1971) Iterative Solution of Large Linear Systems Academic Press, New York

5 Arguments

1:   TRANS – CHARACTER(1)Input
On entry: specifies whether or not the matrix M is transposed.
TRANS='N'
Mx=y is solved.
TRANS='T'
MT x=y is solved.
Constraint: TRANS='N' or 'T'.
2:   N – INTEGERInput
On entry: n, the order of the matrix A.
Constraint: N≥1.
3:   NNZ – INTEGERInput
On entry: the number of nonzero elements in the matrix A.
Constraint: 1≤NNZ≤N 2.
4:   A NNZ – REAL (KIND=nag_wp) arrayInput
On entry: the nonzero elements in the matrix A, ordered by increasing row index, and by increasing column index within each row. Multiple entries for the same row and column indices are not permitted. The routine F11ZAF may be used to order the elements in this way.
5:   IROW NNZ – INTEGER arrayInput
6:   ICOL NNZ – INTEGER arrayInput
On entry: the row and column indices of the nonzero elements supplied in array A.
Constraints:
IROW and ICOL must satisfy the following constraints (which may be imposed by a call to F11ZAF):
  • 1≤IROW i≤N and 1≤ICOL i≤N, for i=1,2,…,NNZ;
  • either IROW i-1<IROW i or both IROW i-1=IROW i and ICOL i-1<ICOL i, for i=2,3,…,NNZ.
7:   RDIAG N – REAL (KIND=nag_wp) arrayInput
On entry: the elements of the diagonal matrix D-1, where D is the diagonal part of A.
8:   OMEGA – REAL (KIND=nag_wp)Input
On entry: the relaxation parameter ω.
Constraint: 0.0<OMEGA<2.0.
9:   CHECK – CHARACTER(1)Input
On entry: specifies whether or not the CS representation of the matrix M should be checked.
CHECK='C'
Checks are carried on the values of N, NNZ, IROW, ICOL and OMEGA.
CHECK='N'
None of these checks are carried out.
See also Section 9.2.
Constraint: CHECK='C' or 'N'.
10:   Y N – REAL (KIND=nag_wp) arrayInput
On entry: the right-hand side vector y.
11:   X N – REAL (KIND=nag_wp) arrayOutput
On exit: the solution vector x.
12:   IWORK 2×N+1 – INTEGER arrayWorkspace
13:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, | TRANS≠'N' or 'T',
or | CHECK≠'C' or 'N'.
IFAIL=2
On entry, | N<1,
or | NNZ<1,
or | NNZ>N 2,
or | OMEGA lies outside the interval 0.0,2.0,
IFAIL=3
On entry, the arrays IROW and ICOL fail to satisfy the following constraints:
  • 1≤IROW i≤N and 1≤ICOL i≤N, for i=1,2,…,NNZ;
  • IROW i-1<IROW i or IROW i-1=IROW i and ICOL i-1<ICOL i, for i=2,3,…,NNZ.
Therefore a nonzero element has been supplied which does not lie in the matrix A, is out of order, or has duplicate row and column indices. Call F11ZAF to reorder and sum or remove duplicates.
IFAIL=4
On entry, the matrix A has a zero diagonal element. The SSOR preconditioner is not appropriate for this problem.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

If TRANS='N' the computed solution x is the exact solution of a perturbed system of equations M+δM x=y, where
δM≤c n ε D+ωLD-1D+ωU,
c n is a modest linear function of n, and ε is the machine precision. An equivalent result holds when TRANS='T'.

8 Parallelism and Performance

F11DDF is not threaded in any implementation.

9 Further Comments

9.1 Timing

The time taken for a call to F11DDF is proportional to NNZ.

9.2 Use of CHECK

It is expected that a common use of F11DDF will be to carry out the preconditioning step required in the application of F11BEF to sparse linear systems. In this situation F11DDF is likely to be called many times with the same matrix M. In the interests of both reliability and efficiency, you are recommended to set CHECK='C' for the first of such calls, and for all subsequent calls set CHECK='N'.

10 Example

This example solves a sparse linear system of equations:
Ax=b,
using RGMRES with SSOR preconditioning.
The RGMRES algorithm itself is implemented by the reverse communication routine F11BEF, which returns repeatedly to the calling program with various values of the argument IREVCM. This argument indicates the action to be taken by the calling program.
  • If IREVCM=1, a matrix-vector product v=Au is required. This is implemented by a call to F11XAF.
  • If IREVCM=-1, a transposed matrix-vector product v=AT u is required in the estimation of the norm of A. This is implemented by a call to F11XAF.
  • If IREVCM=2, a solution of the preconditioning equation Mv=u is required. This is achieved by a call to F11DDF.
  • If IREVCM=4, F11BEF has completed its tasks. Either the iteration has terminated, or an error condition has arisen.
For further details see the routine document for F11BEF.

10.1 Program Text

Program Text (f11ddfe.f90)

10.2 Program Data

Program Data (f11ddfe.d)

10.3 Program Results

Program Results (f11ddfe.r)

F11 Chapter Contents
F11 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F11DEF : NAG Library, Mark 26

F11 Chapter Contents
F11 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F11DEF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F11DEF solves a real sparse nonsymmetric system of linear equations, represented in coordinate storage format, using a restarted generalized minimal residual (RGMRES), conjugate gradient squared (CGS), stabilized bi-conjugate gradient (Bi-CGSTAB), or transpose-free quasi-minimal residual (TFQMR) method, without preconditioning, with Jacobi, or with SSOR preconditioning.

2 Specification

SUBROUTINE F11DEF ( METHOD, PRECON, N, NNZ, A, IROW, ICOL, OMEGA, B, M, TOL, MAXITN, X, RNORM, ITN, WORK, LWORK, IWORK, IFAIL)
INTEGER | N, NNZ, IROW(NNZ), ICOL(NNZ), M, MAXITN, ITN, LWORK, IWORK(2*N+1), IFAIL
REAL (KIND=nag_wp) | A(NNZ), OMEGA, B(N), TOL, X(N), RNORM, WORK(LWORK)
CHARACTER(*) | METHOD
CHARACTER(1) | PRECON

3 Description

F11DEF solves a real sparse nonsymmetric system of linear equations
Ax=b,
using an RGMRES (see Saad and Schultz (1986)), CGS (see Sonneveld (1989)), Bi-CGSTAB(ℓ) (see Van der Vorst (1989) and Sleijpen and Fokkema (1993)), or TFQMR (see Freund and Nachtigal (1991) and Freund (1993)) method.
The routine allows the following choices for the preconditioner:
  • no preconditioning;
  • Jacobi preconditioning (see Young (1971));
  • symmetric successive-over-relaxation (SSOR) preconditioning (see Young (1971)).
For incomplete LU (ILU) preconditioning see F11DCF.
The matrix A is represented in coordinate storage (CS) format (see Section 2.1.1 in the F11 Chapter Introduction) in the arrays A, IROW and ICOL. The array A holds the nonzero entries in the matrix, while IROW and ICOL hold the corresponding row and column indices.
F11DEF is a Black Box routine which calls F11BDF, F11BEF and F11BFF. If you wish to use an alternative storage scheme, preconditioner, or termination criterion, or require additional diagnostic information, you should call these underlying routines directly.

4 References

Freund R W (1993) A transpose-free quasi-minimal residual algorithm for non-Hermitian linear systems SIAM J. Sci. Comput. 14 470–482
Freund R W and Nachtigal N (1991) QMR: a Quasi-Minimal Residual Method for Non-Hermitian Linear Systems Numer. Math. 60 315–339
Saad Y and Schultz M (1986) GMRES: a generalized minimal residual algorithm for solving nonsymmetric linear systems SIAM J. Sci. Statist. Comput. 7 856–869
Sleijpen G L G and Fokkema D R (1993) BiCGSTABℓ for linear equations involving matrices with complex spectrum ETNA 1 11–32
Sonneveld P (1989) CGS, a fast Lanczos-type solver for nonsymmetric linear systems SIAM J. Sci. Statist. Comput. 10 36–52
Van der Vorst H (1989) Bi-CGSTAB, a fast and smoothly converging variant of Bi-CG for the solution of nonsymmetric linear systems SIAM J. Sci. Statist. Comput. 13 631–644
Young D (1971) Iterative Solution of Large Linear Systems Academic Press, New York

5 Arguments

1:   METHOD – CHARACTER(*)Input
On entry: the iterative method to be used.
METHOD='RGMRES'
Restarted generalized minimum residual method.
METHOD='CGS'
Conjugate gradient squared method.
METHOD='BICGSTAB'
Bi-conjugate gradient stabilized (ℓ) method.
METHOD='TFQMR'
Transpose-free quasi-minimal residual method.
Constraint: METHOD='RGMRES', 'CGS', 'BICGSTAB' or 'TFQMR'.
2:   PRECON – CHARACTER(1)Input
On entry: specifies the type of preconditioning to be used.
PRECON='N'
No preconditioning.
PRECON='J'
Jacobi.
PRECON='S'
Symmetric successive-over-relaxation.
Constraint: PRECON='N', 'J' or 'S'.
3:   N – INTEGERInput
On entry: n, the order of the matrix A.
Constraint: N≥1.
4:   NNZ – INTEGERInput
On entry: the number of nonzero elements in the matrix A.
Constraint: 1≤NNZ≤N 2.
5:   A NNZ – REAL (KIND=nag_wp) arrayInput
On entry: the nonzero elements of the matrix A, ordered by increasing row index, and by increasing column index within each row. Multiple entries for the same row and column indices are not permitted. The routine F11ZAF may be used to order the elements in this way.
6:   IROW NNZ – INTEGER arrayInput
7:   ICOL NNZ – INTEGER arrayInput
On entry: the row and column indices of the nonzero elements supplied in A.
Constraints:
IROW and ICOL must satisfy the following constraints (which may be imposed by a call to F11ZAF):
  • 1≤IROW i≤N and 1≤ICOL i≤N, for i=1,2,…,NNZ;
  • IROW i-1<IROW i or IROW i-1=IROW i and ICOL i-1<ICOL i, for i=2,3,…,NNZ.
8:   OMEGA – REAL (KIND=nag_wp)Input
On entry: if PRECON='S', OMEGA is the relaxation parameter ω to be used in the SSOR method. Otherwise OMEGA need not be initialized and is not referenced.
Constraint: 0.0<OMEGA<2.0.
9:   B N – REAL (KIND=nag_wp) arrayInput
On entry: the right-hand side vector b.
10:   M – INTEGERInput
On entry: if METHOD='RGMRES', M is the dimension of the restart subspace.
If METHOD='BICGSTAB', M is the order ℓ of the polynomial Bi-CGSTAB method.
Otherwise, M is not referenced.
Constraints:
  • if METHOD='RGMRES', 0<M≤min N,50;
  • if METHOD='BICGSTAB', 0<M≤min N,10.
11:   TOL – REAL (KIND=nag_wp)Input
On entry: the required tolerance. Let xk denote the approximate solution at iteration k, and rk the corresponding residual. The algorithm is considered to have converged at iteration k if
rk∞≤τ×b∞+A∞xk∞.
If TOL≤0.0, τ=max⁡ε,10 ε,n ε is used, where ε is the machine precision. Otherwise τ=max TOL,10 ε,n ε is used.
Constraint: TOL<1.0.
12:   MAXITN – INTEGERInput
On entry: the maximum number of iterations allowed.
Constraint: MAXITN≥1.
13:   X N – REAL (KIND=nag_wp) arrayInput/Output
On entry: an initial approximation to the solution vector x.
On exit: an improved approximation to the solution vector x.
14:   RNORM – REAL (KIND=nag_wp)Output
On exit: the final value of the residual norm rk∞, where k is the output value of ITN.
15:   ITN – INTEGEROutput
On exit: the number of iterations carried out.
16:   WORK LWORK – REAL (KIND=nag_wp) arrayWorkspace
17:   LWORK – INTEGERInput
On entry: the dimension of the array WORK as declared in the (sub)program from which F11DEF is called.
Constraints:
  • if METHOD='RGMRES', LWORK≥4×N+M×M+N+5+ν+101;
  • if METHOD='CGS', LWORK≥8×N+ν+100;
  • if METHOD='BICGSTAB', LWORK≥2×N×M+3+M×M+2+ν+100;
  • if METHOD='TFQMR', LWORK≥11×N+ν+100.
where ν=N for PRECON='J' or 'S', and 0 otherwise
18:   IWORK 2×N+1 – INTEGER arrayWorkspace
19:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, | METHOD≠'RGMRES','CGS','BICGSTAB', or 'TFQMR',
or | PRECON≠'N', 'J' or 'S',
or | N<1,
or | NNZ<1,
or | NNZ>N 2,
or | PRECON='S' and OMEGA lies outside the interval 0.0,2.0,
or | M<1,
or | M>min N,50, with METHOD='RGMRES',
or | M>min N,10, with METHOD='BICGSTAB',
or | TOL≥1.0,
or | MAXITN<1,
or | LWORK too small.
IFAIL=2
On entry, the arrays IROW and ICOL fail to satisfy the following constraints:
  • 1≤IROW i≤N and 1≤ICOL i≤N, for i=1,2,…,NNZ;
  • IROW i-1<IROW i, or IROW i-1=IROW i and ICOL i-1<ICOL i, for i=2,3,…,NNZ.
Therefore a nonzero element has been supplied which does not lie within the matrix A, is out of order, or has duplicate row and column indices. Call F11ZAF to reorder and sum or remove duplicates.
IFAIL=3
On entry, the matrix A has a zero diagonal element. Jacobi and SSOR preconditioners are not appropriate for this problem.
IFAIL=4
The required accuracy could not be obtained. However, a reasonable accuracy may have been obtained, and further iterations could not improve the result. You should check the output value of RNORM for acceptability. This error code usually implies that your problem has been fully and satisfactorily solved to within or close to the accuracy available on your system. Further iterations are unlikely to improve on this situation.
IFAIL=5
Required accuracy not obtained in MAXITN iterations.
IFAIL=6
Algorithmic breakdown. A solution is returned, although it is possible that it is completely inaccurate.
IFAIL=7 (F11BDF, F11BEF or F11BFF)
A serious error has occurred in an internal call to one of the specified routines. Check all subroutine calls and array sizes. Seek expert help.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

On successful termination, the final residual rk=b-A xk, where k=ITN, satisfies the termination criterion
rk∞≤τ×b∞+A∞xk∞.
The value of the final residual norm is returned in RNORM.

8 Parallelism and Performance

F11DEF is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
F11DEF makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The time taken by F11DEF for each iteration is roughly proportional to NNZ.
The number of iterations required to achieve a prescribed accuracy cannot be easily determined a priori, as it can depend dramatically on the conditioning and spectrum of the preconditioned coefficient matrix A-=M-1 A.

10 Example

This example solves a sparse nonsymmetric system of equations using the RGMRES method, with SSOR preconditioning.

10.1 Program Text

Program Text (f11defe.f90)

10.2 Program Data

Program Data (f11defe.d)

10.3 Program Results

Program Results (f11defe.r)

F11 Chapter Contents
F11 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F11DFF : NAG Library, Mark 26

F11 Chapter Contents
F11 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F11DFF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F11DFF computes a block diagonal incomplete LU factorization of a real sparse nonsymmetric matrix, represented in coordinate storage format. The diagonal blocks may be composed of arbitrary rows and the corresponding columns, and may overlap. This factorization can be used to provide a block Jacobi or additive Schwarz preconditioner, for use in combination with F11BEF or F11DGF.

2 Specification

SUBROUTINE F11DFF ( N, NNZ, A, LA, IROW, ICOL, NB, ISTB, INDB, LINDB, LFILL, DTOL, PSTRAT, MILU, IPIVP, IPIVQ, ISTR, IDIAG, NNZC, NPIVM, IWORK, LIWORK, IFAIL)
INTEGER | N, NNZ, LA, IROW(LA), ICOL(LA), NB, ISTB(NB+1), INDB(LINDB), LINDB, LFILL(NB), IPIVP(LINDB), IPIVQ(LINDB), ISTR(LINDB+1), IDIAG(LINDB), NNZC, NPIVM(NB), IWORK(LIWORK), LIWORK, IFAIL
REAL (KIND=nag_wp) | A(LA), DTOL(NB)
CHARACTER(1) | PSTRAT(NB), MILU(NB)

3 Description

F11DFF computes an incomplete LU factorization (see Meijerink and Van der Vorst (1977) and Meijerink and Van der Vorst (1981)) of the (possibly overlapping) diagonal blocks Ab, for b=1,2,…,NB, of a real sparse nonsymmetric n by n matrix A. The factorization is intended primarily for use as a block Jacobi or additive Schwarz preconditioner (see Saad (1996)), with one of the iterative solvers F11BEF and F11DGF.
The NB diagonal blocks need not consist of consecutive rows and columns of A, but may be composed of arbitrarily indexed rows, and the corresponding columns, as defined in the arguments INDB and ISTB. Any given row or column index may appear in more than one diagonal block, resulting in overlap. Each diagonal block Ab, for b=1,2,…,NB, is factorized as:
Ab = Mb+Rb
where
Mb = Pb Lb Db Ub Qb
and Lb is lower triangular with unit diagonal elements, Db is diagonal, Ub is upper triangular with unit diagonals, Pb and Qb are permutation matrices, and Rb is a remainder matrix.
The amount of fill-in occurring in the factorization of block b can vary from zero to complete fill, and can be controlled by specifying either the maximum level of fill LFILL b, or the drop tolerance DTOL b.
The parameter PSTRAT b defines the pivoting strategy to be used in block b. The options currently available are no pivoting, user-defined pivoting, partial pivoting by columns for stability, and complete pivoting by rows for sparsity and by columns for stability. The factorization may optionally be modified to preserve the row-sums of the original block matrix.
The sparse matrix A is represented in coordinate storage (CS) format (see Section 2.1.1 in the F11 Chapter Introduction). The array A stores all the nonzero elements of the matrix A, while arrays IROW and ICOL store the corresponding row and column indices respectively. Multiple nonzero elements may not be specified for the same row and column index.
The preconditioning matrices Mb, for b=1,2,…,NB, are returned in terms of the CS representations of the matrices
Cb = Lb + D-1 b + Ub -2 I .

4 References

Meijerink J and Van der Vorst H (1977) An iterative solution method for linear systems of which the coefficient matrix is a symmetric M-matrix Math. Comput. 31 148–162
Meijerink J and Van der Vorst H (1981) Guidelines for the usage of incomplete decompositions in solving sets of linear equations as they occur in practical problems J. Comput. Phys. 44 134–155
Saad Y (1996) Iterative Methods for Sparse Linear Systems PWS Publishing Company, Boston, MA

5 Arguments

1:   N – INTEGERInput
On entry: n, the order of the matrix A.
Constraint: N≥1.
2:   NNZ – INTEGERInput
On entry: the number of nonzero elements in the matrix A.
Constraint: 1≤NNZ≤N 2.
3:   A LA – REAL (KIND=nag_wp) arrayInput/Output
On entry: the nonzero elements in the matrix A, ordered by increasing row index, and by increasing column index within each row. Multiple entries for the same row and column indices are not permitted. The routine F11ZAF may be used to order the elements in this way.
On exit: the first NNZ entries of A contain the nonzero elements of A and the next NNZC entries contain the elements of the matrices Cb, for b=1,2,…,NB stored consecutively. Within each block the matrix elements are ordered by increasing row index, and by increasing column index within each row.
4:   LA – INTEGERInput
On entry: the dimension of the arrays A, IROW and ICOL as declared in the (sub)program from which F11DFF is called. These arrays must be of sufficient size to store both A (NNZ elements) and C (NNZC elements).
Note: the minimum value for LA is only appropriate if LFILL and DTOL are set such that minimal fill-in occurs. If this is not the case then we recommend that LA is set much larger than the minimum value indicated in the constraint.
Constraint: LA≥2×NNZ.
5:   IROW LA – INTEGER arrayInput/Output
6:   ICOL LA – INTEGER arrayInput/Output
On entry: the row and column indices of the nonzero elements supplied in A.
Constraints:
IROW and ICOL must satisfy these constraints (which may be imposed by a call to F11ZAF):
  • 1≤IROW i≤N and 1≤ICOL i≤N, for i=1,2,…,NNZ;
  • either IROW i-1<IROW i or both IROW i-1=IROW i and ICOL i-1<ICOL i, for i=2,3,…,NNZ.
On exit: the row and column indices of the nonzero elements returned in A.
7:   NB – INTEGERInput
On entry: the number of diagonal blocks to factorize.
Constraint: 1≤NB≤N.
8:   ISTB NB+1 – INTEGER arrayInput
On entry: ISTB b, for b=1,2,…,NB, holds the indices in arrays INDB, IPIVP, IPIVQ and IDIAG that, on successful exit from this function, define block b. ISTB NB+1 holds the sum of the number of rows in all blocks plus ISTB 1.
Constraint: ISTB 1≥1, ISTB b< ISTB b+1 , for b=1,2,…,NB.
9:   INDB LINDB – INTEGER arrayInput
On entry: INDB must hold the row indices appearing in each diagonal block, stored consecutively. Thus the elements INDB ISTB b to INDB ISTB b+1-1 are the row indices in the bth block, for b=1,2,…,NB.
Constraint: 1≤INDB m≤N, for m=1,2,…,ISTB NB+1-1.
10:   LINDB – INTEGERInput
On entry: the dimension of the arrays INDB, IPIVP, IPIVQ and IDIAG as declared in the (sub)program from which F11DFF is called.
Constraint: LINDB≥ISTB NB+1-1.
11:   LFILL NB – INTEGER arrayInput
On entry: if LFILL b≥0 its value is the maximum level of fill allowed in the decomposition of the block (see Section 9.2 in F11DAF). A negative value of LFILL b indicates that DTOL b will be used to control the fill in the block instead.
12:   DTOL NB – REAL (KIND=nag_wp) arrayInput
On entry: if LFILL b<0 then DTOL b is used as a drop tolerance in the block to control the fill-in (see Section 9.2 in F11DAF); otherwise DTOL b is not referenced.
Constraint: if LFILL b<0, DTOL b≥0.0, for b=1,2,…,NB.
13:   PSTRAT NB – CHARACTER(1) arrayInput
On entry: PSTRAT b, for b=1,2,…,NB, specifies the pivoting strategy to be adopted in the block as follows:
PSTRAT b='N'
No pivoting is carried out.
PSTRAT b='U'
Pivoting is carried out according to the user-defined input values of IPIVP and IPIVQ.
PSTRAT b='P'
Partial pivoting by columns for stability is carried out.
PSTRAT b='C'
Complete pivoting by rows for sparsity, and by columns for stability, is carried out.
Suggested value: PSTRAT b='C', for b=1,2,…,NB.
Constraint: PSTRAT b='N', 'U', 'P' or 'C', for b=1,2,…,NB.
14:   MILU NB – CHARACTER(1) arrayInput
On entry: MILU b, for b=1,2,…,NB, indicates whether or not the factorization in the block should be modified to preserve row-sums (see Section 9.4 in F11DAF).
MILU b='M'
The factorization is modified.
MILU b='N'
The factorization is not modified.
Constraint: MILU b='M' or 'N', for b=1,2,…,NB.
15:   IPIVP LINDB – INTEGER arrayInput/Output
16:   IPIVQ LINDB – INTEGER arrayInput/Output
On entry: if PSTRAT b='U', then IPIVP ISTB b+k-1 and IPIVQ ISTB b+k-1 must specify the row and column indices of the element used as a pivot at elimination stage k of the factorization of the block. Otherwise IPIVP and IPIVQ need not be initialized.
Constraint: if PSTRAT b='U', the elements ISTB b to ISTB b+1-1 of IPIVP and IPIVQ must both hold valid permutations of the integers on 1,ISTB b+1-ISTB b.
On exit: the row and column indices of the pivot elements, arranged consecutively for each block, as for INDB. If IPIVP ISTB b+k-1=i and IPIVQ ISTB b+k-1=j, then the element in row i and column j of Ab was used as the pivot at elimination stage k.
17:   ISTR LINDB+1 – INTEGER arrayOutput
On exit: ISTR ISTB b+k-1, gives the index in the arrays A, IROW and ICOL of row k of the matrix Cb, for b=1,2,…,NB and k=1,2,…,ISTB b+1-ISTB b.
ISTR ISTB NB+1 contains NNZ+NNZC+1.
18:   IDIAG LINDB – INTEGER arrayOutput
On exit: IDIAG ISTB b+k-1, gives the index in the arrays A, IROW and ICOL of the diagonal element in row k of the matrix Cb, for b=1,2,…,NB and k=1,2,…,ISTB b+1-ISTB b.
19:   NNZC – INTEGEROutput
On exit: the sum total number of nonzero elements in the matrices Cb, for b=1,2,…,NB.
20:   NPIVM NB – INTEGER arrayOutput
On exit: if NPIVM b>0 it gives the number of pivots which were modified during the factorization to ensure that Mb exists.
If NPIVM b=-1 no pivot modifications were required, but a local restart occurred (see Section 9.3 in F11DAF). The quality of the preconditioner will generally depend on the returned values of NPIVM b, for b=1,2,…,NB.
If NPIVM b is large, for some block, the preconditioner may not be satisfactory. In this case it may be advantageous to call F11DFF again with an increased value of LFILL b, a reduced value of DTOL b, or PSTRAT b='C'.
21:   IWORK LIWORK – INTEGER arrayWorkspace
22:   LIWORK – INTEGERInput
On entry: the dimension of the array IWORK as declared in the (sub)program from which F11DFF is called.
Constraint: LIWORK≥9×N+3.
23:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, DTOL value=value.
Constraint: DTOL b≥0.0, for b=1,2,…,NB.
On entry, for b=value, ISTB b+1=value and ISTB b=value.
Constraint: ISTB b+1>ISTB b, for b=1,2,…,NB.
On entry, INDB value=value and N=value.
Constraint: 1≤INDB m≤N, for m=1,2,…,ISTB NB+1-1
On entry, ISTB 1=value.
Constraint: ISTB 1≥1.
On entry, LA=value and NNZ=value.
Constraint: LA≥2×NNZ.
On entry, LINDB=value, ISTB NB+1-1=value and NB=value.
Constraint: LINDB≥ISTB NB+1-1.
On entry, LIWORK=value.
Constraint: LIWORK≥value.
On entry, MILU value=value.
Constraint: MILU b='M' or 'N' for all b.
On entry, N=value.
Constraint: N≥1.
On entry, NB=value and N=value.
Constraint: 1≤NB≤N.
On entry, NNZ=value.
Constraint: NNZ≥1.
On entry, NNZ=value and N=value.
Constraint: NNZ≤N 2.
On entry, PSTRAT value=value.
Constraint: PSTRAT b='N', 'U', 'P' or 'C' for all b.
IFAIL=2
On entry, element value of A was out of order.
On entry, ICOL value=value and N=value.
Constraint: 1≤ICOL j≤N, for j=1,2,…,NNZ.
On entry, IROW value=value and N=value.
Constraint: 1≤IROW i≤N, for i=1,2,…,NNZ.
On entry, location value of IROW,ICOL was a duplicate.
IFAIL=3
On entry, the user-supplied value of IPIVP for block value lies outside its range.
On entry, the user-supplied value of IPIVP for block value was repeated.
On entry, the user-supplied value of IPIVQ for block value lies outside its range.
On entry, the user-supplied value of IPIVQ for block value was repeated.
IFAIL=4
The number of nonzero entries in the decomposition is too large.
The decomposition has been terminated before completion.
Either increase LA, or reduce the fill by reducing LFILL, or increasing DTOL.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

The accuracy of the factorization of each block Ab will be determined by the size of the elements that are dropped and the size of any modifications made to the pivot elements. If these sizes are small then the computed factors will correspond to a matrix close to Ab. The factorization can generally be made more accurate by increasing the level of fill LFILL b, or by reducing the drop tolerance DTOL b with LFILL b<0.
If F11DFF is used in combination with F11BEF or F11DGF, the more accurate the factorization the fewer iterations will be required. However, the cost of the decomposition will also generally increase.

8 Parallelism and Performance

F11DFF is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

F11DFF calls F11DAF internally for each block Ab. The comments and advice provided in Section 9 in F11DAF on timing, control of fill, algorithmic details, and choice of parameters, are all therefore relevant to F11DFF, if interpreted blockwise.

10 Example

This example program reads in a sparse matrix A and then defines a block partitioning of the row indices with a user-supplied overlap and computes an overlapping incomplete LU factorization suitable for use as an additive Schwarz preconditioner. Such a factorization is used for this purpose in the example program of F11DGF.

10.1 Program Text

Program Text (f11dffe.f90)

10.2 Program Data

Program Data (f11dffe.d)

10.3 Program Results

Program Results (f11dffe.r)

F11 Chapter Contents
F11 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F11DGF : NAG Library, Mark 26

F11 Chapter Contents
F11 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F11DGF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F11DGF solves a real sparse nonsymmetric system of linear equations, represented in coordinate storage format, using a restarted generalized minimal residual (RGMRES), conjugate gradient squared (CGS), stabilized bi-conjugate gradient (Bi-CGSTAB), or transpose-free quasi-minimal residual (TFQMR) method, with block Jacobi or additive Schwarz preconditioning.

2 Specification

SUBROUTINE F11DGF ( METHOD, N, NNZ, A, LA, IROW, ICOL, NB, ISTB, INDB, LINDB, IPIVP, IPIVQ, ISTR, IDIAG, B, M, TOL, MAXITN, X, RNORM, ITN, WORK, LWORK, IFAIL)
INTEGER | N, NNZ, LA, IROW(LA), ICOL(LA), NB, ISTB(NB+1), INDB(LINDB), LINDB, IPIVP(LINDB), IPIVQ(LINDB), ISTR(LINDB+1), IDIAG(LINDB), M, MAXITN, ITN, LWORK, IFAIL
REAL (KIND=nag_wp) | A(LA), B(N), TOL, X(N), RNORM, WORK(LWORK)
CHARACTER(*) | METHOD

3 Description

F11DGF solves a real sparse nonsymmetric linear system of equations:
Ax=b,
using a preconditioned RGMRES (see Saad and Schultz (1986)), CGS (see Sonneveld (1989)), Bi-CGSTAB(ℓ) (see Van der Vorst (1989) and Sleijpen and Fokkema (1993)), or TFQMR (see Freund and Nachtigal (1991) and Freund (1993)) method.
F11DGF uses the incomplete (possibly overlapping) block LU factorization determined by F11DFF as the preconditioning matrix. A call to F11DGF must always be preceded by a call to F11DFF. Alternative preconditioners for the same storage scheme are available by calling F11DCF or F11DEF.
The matrix A, and the preconditioning matrix M, are represented in coordinate storage (CS) format (see Section 2.1.1 in the F11 Chapter Introduction) in the arrays A, IROW and ICOL, as returned from F11DFF. The array A holds the nonzero entries in these matrices, while IROW and ICOL hold the corresponding row and column indices.
F11DGF is a Black Box routine which calls F11BDF, F11BEF and F11BFF. If you wish to use an alternative storage scheme, preconditioner, or termination criterion, or require additional diagnostic information, you should call these underlying routines directly.

4 References

Freund R W (1993) A transpose-free quasi-minimal residual algorithm for non-Hermitian linear systems SIAM J. Sci. Comput. 14 470–482
Freund R W and Nachtigal N (1991) QMR: a Quasi-Minimal Residual Method for Non-Hermitian Linear Systems Numer. Math. 60 315–339
Saad Y and Schultz M (1986) GMRES: a generalized minimal residual algorithm for solving nonsymmetric linear systems SIAM J. Sci. Statist. Comput. 7 856–869
Salvini S A and Shaw G J (1996) An evaluation of new NAG Library solvers for large sparse unsymmetric linear systems NAG Technical Report TR2/96
Sleijpen G L G and Fokkema D R (1993) BiCGSTABℓ for linear equations involving matrices with complex spectrum ETNA 1 11–32
Sonneveld P (1989) CGS, a fast Lanczos-type solver for nonsymmetric linear systems SIAM J. Sci. Statist. Comput. 10 36–52
Van der Vorst H (1989) Bi-CGSTAB, a fast and smoothly converging variant of Bi-CG for the solution of nonsymmetric linear systems SIAM J. Sci. Statist. Comput. 13 631–644

5 Arguments

1:   METHOD – CHARACTER(*)Input
On entry: specifies the iterative method to be used.
METHOD='RGMRES'
Restarted generalized minimum residual method.
METHOD='CGS'
Conjugate gradient squared method.
METHOD='BICGSTAB'
Bi-conjugate gradient stabilized (ℓ) method.
METHOD='TFQMR'
Transpose-free quasi-minimal residual method.
Constraint: METHOD='RGMRES', 'CGS', 'BICGSTAB' or 'TFQMR'.
2:   N – INTEGERInput
3:   NNZ – INTEGERInput
4:   A LA – REAL (KIND=nag_wp) arrayInput
5:   LA – INTEGERInput
6:   IROW LA – INTEGER arrayInput
7:   ICOL LA – INTEGER arrayInput
8:   NB – INTEGERInput
9:   ISTB NB+1 – INTEGER arrayInput
10:   INDB LINDB – INTEGER arrayInput
11:   LINDB – INTEGERInput
12:   IPIVP LINDB – INTEGER arrayInput
13:   IPIVQ LINDB – INTEGER arrayInput
14:   ISTR LINDB+1 – INTEGER arrayInput
15:   IDIAG LINDB – INTEGER arrayInput
On entry: the values returned in arrays IROW, ICOL, IPIVP, IPIVQ, ISTR and IDIAG by a previous call to F11DFF.
The arrays ISTB, INDB and A together with the the scalars N, NNZ, LA, NB and LINDB must be the same values that were supplied in the preceding call to F11DFF.
16:   B N – REAL (KIND=nag_wp) arrayInput
On entry: the right-hand side vector b.
17:   M – INTEGERInput
On entry: if METHOD='RGMRES', M is the dimension of the restart subspace.
If METHOD='BICGSTAB', M is the order ℓ of the polynomial Bi-CGSTAB method. Otherwise, M is not referenced.
Constraints:
  • if METHOD='RGMRES', 0<M≤min N,50;
  • if METHOD='BICGSTAB', 0<M≤min N,10.
18:   TOL – REAL (KIND=nag_wp)Input
On entry: the required tolerance. Let xk denote the approximate solution at iteration k, and rk the corresponding residual. The algorithm is considered to have converged at iteration k if
rk∞≤τ×b∞+A∞xk∞.
If TOL≤0.0, τ=max⁡ε,n ε is used, where ε is the machine precision. Otherwise τ=max TOL,10 ε,n ε is used.
Constraint: TOL<1.0.
19:   MAXITN – INTEGERInput
On entry: the maximum number of iterations allowed.
Constraint: MAXITN≥1.
20:   X N – REAL (KIND=nag_wp) arrayInput/Output
On entry: an initial approximation to the solution vector x.
On exit: an improved approximation to the solution vector x.
21:   RNORM – REAL (KIND=nag_wp)Output
On exit: the final value of the residual norm rk∞, where k is the output value of ITN.
22:   ITN – INTEGEROutput
On exit: the number of iterations carried out.
23:   WORK LWORK – REAL (KIND=nag_wp) arrayWorkspace
24:   LWORK – INTEGERInput
On entry: the dimension of the array WORK as declared in the (sub)program from which F11DGF is called.
Constraints:
  • if METHOD='RGMRES', LWORK≥6×N+M×M+N+5+101;
  • if METHOD='CGS', LWORK≥10×N+100;
  • if METHOD='BICGSTAB', LWORK≥2×N×M+8×N+M×M+2+100;
  • if METHOD='TFQMR', LWORK≥13×N+100.
25:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, for b=value, ISTB b+1=value and ISTB b=value.
Constraint: ISTB b+1>ISTB b, for b=1,2,…,NB.
On entry, INDB value=value and N=value.
Constraint: 1≤INDB m≤N, for m=1,2,…,ISTB NB+1-1
On entry, ISTB 1=value.
Constraint: ISTB 1≥1.
On entry, LA=value and NNZ=value.
Constraint: LA≥2×NNZ.
On entry, LINDB=value, ISTB NB+1-1=value and NB=value.
Constraint: LINDB≥ISTB NB+1-1.
On entry, LWORK=value.
Constraint: LWORK≥value.
On entry, M=value and N=value.
Constraint: if METHOD='RGMRES', 1≤M≤min N,value.
If METHOD='BICGSTAB', 1≤M≤min N,value.
On entry, MAXITN=value.
Constraint: MAXITN≥1.
On entry, METHOD=value.
Constraint: METHOD='RGMRES', 'CGS' or 'BICGSTAB'.
On entry, N=value.
Constraint: N≥1.
On entry, NB=value and N=value.
Constraint: 1≤NB≤N.
On entry, NNZ=value.
Constraint: NNZ≥1.
On entry, NNZ=value and N=value.
Constraint: NNZ≤N 2.
On entry, TOL=value.
Constraint: TOL<1.0.
IFAIL=2
On entry, element value of A was out of order.
Check that A, IROW, ICOL, IPIVP, IPIVQ, ISTR and IDIAG have not been corrupted between calls to F11DFF and F11DGF.
On entry, ICOL value=value and N=value.
Constraint: 1≤ICOL i≤N, for i=1,2,…,NNZ.
Check that A, IROW, ICOL, IPIVP, IPIVQ, ISTR and IDIAG have not been corrupted between calls to F11DFF and F11DGF.
On entry, IROW value=value and N=value.
Constraint: 1≤IROW i≤N, for i=1,2,…,NNZ.
Check that A, IROW, ICOL, IPIVP, IPIVQ, ISTR and IDIAG have not been corrupted between calls to F11DFF and F11DGF.
On entry, location value of IROW,ICOL was a duplicate.
Check that A, IROW, ICOL, IPIVP, IPIVQ, ISTR and IDIAG have not been corrupted between calls to F11DFF and F11DGF.
IFAIL=3
The CS representation of the preconditioner is invalid.
Check that A, IROW, ICOL, IPIVP, IPIVQ, ISTR and IDIAG have not been corrupted between calls to F11DFF and F11DGF.
IFAIL=4
The required accuracy could not be obtained. However a reasonable accuracy may have been achieved. You should check the output value of RNORM for acceptability. This error code usually implies that your problem has been fully and satisfactorily solved to within or close to the accuracy available on your system. Further iterations are unlikely to improve on this situation.
IFAIL=5
The solution has not converged after value iterations.
IFAIL=6
Algorithmic breakdown. A solution is returned, although it is possible that it is completely inaccurate.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

On successful termination, the final residual rk=b-A xk, where k=ITN, satisfies the termination criterion
rk∞≤τ×b∞+A∞xk∞.
The value of the final residual norm is returned in RNORM.

8 Parallelism and Performance

F11DGF is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
F11DGF makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The time taken by F11DGF for each iteration is roughly proportional to the value of NNZC returned from the preceding call to F11DFF.
The number of iterations required to achieve a prescribed accuracy cannot be easily determined a priori, as it can depend dramatically on the conditioning and spectrum of the preconditioned coefficient matrix A-=M-1 A.
Some illustrations of the application of F11DGF to linear systems arising from the discretization of two-dimensional elliptic partial differential equations, and to random-valued randomly structured linear systems, can be found in Salvini and Shaw (1996).

10 Example

This example program reads in a sparse matrix A and a vector b. It calls F11DFF, with the array LFILL=0 and the array DTOL=0.0, to compute an overlapping incomplete LU factorization. This is then used as an additive Schwarz preconditioner on a call to F11DGF which uses the Bi-CGSTAB method to solve Ax=b.

10.1 Program Text

Program Text (f11dgfe.f90)

10.2 Program Data

Program Data (f11dgfe.d)

10.3 Program Results

Program Results (f11dgfe.r)

F11 Chapter Contents
F11 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F11DKF : NAG Library, Mark 26

F11 Chapter Contents
F11 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F11DKF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
▸▿ 9 Further Comments
9.1 Timing
9.2 Use of CHECK
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F11DKF computes the approximate solution of a real, symmetric or nonsymmetric, sparse system of linear equations applying a number of Jacobi iterations. It is expected that F11DKF will be used as a preconditioner for the iterative solution of real sparse systems of equations.

2 Specification

SUBROUTINE F11DKF ( STORE, TRANS, INIT, NITER, N, NNZ, A, IROW, ICOL, CHECK, B, X, DIAG, WORK, IFAIL)
INTEGER | NITER, N, NNZ, IROW(NNZ), ICOL(NNZ), IFAIL
REAL (KIND=nag_wp) | A(NNZ), B(N), X(N), DIAG(N), WORK(N)
CHARACTER(1) | STORE, TRANS, INIT, CHECK

3 Description

F11DKF computes the approximate solution of the real sparse system of linear equations Ax=b using NITER iterations of the Jacobi algorithm (see also Golub and Van Loan (1996) and Young (1971)):
x k+1=xk+D-1 b-A xk (1)
where k=1,2,…,NITER and x 0=0.
F11DKF can be used both for nonsymmetric and symmetric systems of equations. For symmetric matrices, either all nonzero elements of the matrix A can be supplied using coordinate storage (CS), or only the nonzero elements of the lower triangle of A, using symmetric coordinate storage (SCS) (see the F11 Chapter Introduction).
It is expected that F11DKF will be used as a preconditioner for the iterative solution of real sparse systems of equations, using either the suite comprising the routines F11GDF, F11GEF and F11GFF, for symmetric systems, or the suite comprising the routines F11BDF, F11BEF and F11BFF, for nonsymmetric systems of equations.

4 References

Golub G H and Van Loan C F (1996) Matrix Computations (3rd Edition) Johns Hopkins University Press, Baltimore
Young D (1971) Iterative Solution of Large Linear Systems Academic Press, New York

5 Arguments

1:   STORE – CHARACTER(1)Input
On entry: specifies whether the matrix A is stored using symmetric coordinate storage (SCS) (applicable only to a symmetric matrix A) or coordinate storage (CS) (applicable to both symmetric and non-symmetric matrices).
STORE='N'
The complete matrix A is stored in CS format.
STORE='S'
The lower triangle of the symmetric matrix A is stored in SCS format.
Constraint: STORE='N' or 'S'.
2:   TRANS – CHARACTER(1)Input
On entry: if STORE='N', specifies whether the approximate solution of Ax=b or of AT x=b is required.
TRANS='N'
The approximate solution of Ax=b is calculated.
TRANS='T'
The approximate solution of AT x=b is calculated.
Suggested value: if the matrix A is symmetric and stored in CS format, it is recommended that TRANS='N' for reasons of efficiency.
Constraint: TRANS='N' or 'T'.
3:   INIT – CHARACTER(1)Input
On entry: on first entry, INIT should be set to 'I', unless the diagonal elements of A are already stored in the array DIAG. If DIAG already contains the diagonal of A, it must be set to 'N'.
INIT='N'
DIAG must contain the diagonal of A.
INIT='I'
DIAG will store the diagonal of A on exit.
Suggested value: INIT='I' on first entry; INIT='N', subsequently, unless DIAG has been overwritten.
Constraint: INIT='N' or 'I'.
4:   NITER – INTEGERInput
On entry: the number of Jacobi iterations requested.
Constraint: NITER≥1.
5:   N – INTEGERInput
On entry: n, the order of the matrix A.
Constraint: N≥1.
6:   NNZ – INTEGERInput
On entry: if STORE='N', the number of nonzero elements in the matrix A.
If STORE='S', the number of nonzero elements in the lower triangle of the matrix A.
Constraints:
  • if STORE='N', 1≤NNZ≤N 2;
  • if STORE='S', 1≤NNZ≤N×N+1/2.
7:   A NNZ – REAL (KIND=nag_wp) arrayInput
On entry: if STORE='N', the nonzero elements in the matrix A (CS format).
If STORE='S', the nonzero elements in the lower triangle of the matrix A (SCS format).
In both cases, the elements of either A or of its lower triangle must be ordered by increasing row index and by increasing column index within each row. Multiple entries for the same row and columns indices are not permitted. The routine F11ZAF or F11ZBF may be used to reorder the elements in this way for CS and SCS storage, respectively.
8:   IROW NNZ – INTEGER arrayInput
9:   ICOL NNZ – INTEGER arrayInput
On entry: if STORE='N', the row and column indices of the nonzero elements supplied in A.
If STORE='S', the row and column indices of the nonzero elements of the lower triangle of the matrix A supplied in A.
Constraints:
  • 1≤IROW i≤N, for i=1,2,…,NNZ;
  • if STORE='N', 1≤ICOL i≤N, for i=1,2,…,NNZ;
  • if STORE='S', 1≤ICOL i≤IROW i, for i=1,2,…,NNZ;
  • either IROW i-1<IROW i or both IROW i-1=IROW i and ICOL i-1<ICOL i, for i=2,3,…,NNZ.
10:   CHECK – CHARACTER(1)Input
On entry: specifies whether or not the CS or SCS representation of the matrix A should be checked.
CHECK='C'
Checks are carried out on the values of N, NNZ, IROW, ICOL; if INIT='N', DIAG is also checked.
CHECK='N'
None of these checks are carried out.
See also Section 9.2.
Constraint: CHECK='C' or 'N'.
11:   B N – REAL (KIND=nag_wp) arrayInput
On entry: the right-hand side vector b.
12:   X N – REAL (KIND=nag_wp) arrayOutput
On exit: the approximate solution vector xNITER.
13:   DIAG N – REAL (KIND=nag_wp) arrayInput/Output
On entry: if INIT='N', the diagonal elements of A.
On exit: if INIT='N', unchanged on exit.
If INIT='I', the diagonal elements of A.
14:   WORK N – REAL (KIND=nag_wp) arrayWorkspace
15:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, | STORE≠'N' or 'S',
or | TRANS≠'N' or 'T',
or | INIT≠'N' or 'I',
or | CHECK≠'C' or 'N',
or | NITER≤0.
IFAIL=2
On entry, | N<1,
or | NNZ<1,
or | NNZ>N 2, if STORE='N',
or | 1≤NNZ≤N N+1/2, if STORE='S'.
IFAIL=3
On entry, the arrays IROW and ICOL fail to satisfy the following constraints:
  • 1≤IROW i≤N and
    • if STORE='N' then 1≤ICOL i≤N, or
    • if STORE='S' then 1≤ICOL i≤IROW i, for i=1,2,…,NNZ.
  • IROW i-1<IROW i or IROW i-1=IROW i and ICOL i-1<ICOL i, for i=2,3,…,NNZ.
Therefore a nonzero element has been supplied which does not lie within the matrix A, is out of order, or has duplicate row and column indices. Call either F11ZAF or F11ZBF to reorder and sum or remove duplicates when STORE='N' or STORE='S', respectively.
IFAIL=4
On entry, INIT='N' and some diagonal elements of A stored in DIAG are zero.
IFAIL=5
On entry, INIT='I' and some diagonal elements of A are zero.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

In general, the Jacobi method cannot be used on its own to solve systems of linear equations. The rate of convergence is bound by its spectral properties (see, for example, Golub and Van Loan (1996)) and as a solver, the Jacobi method can only be applied to a limited set of matrices. One condition that guarantees convergence is strict diagonal dominance.
However, the Jacobi method can be used successfully as a preconditioner to a wider class of systems of equations. The Jacobi method has good vector/parallel properties, hence it can be applied very efficiently. Unfortunately, it is not possible to provide criteria which define the applicability of the Jacobi method as a preconditioner, and its usefulness must be judged for each case.

8 Parallelism and Performance

F11DKF is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
F11DKF makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

9.1 Timing

The time taken for a call to F11DKF is proportional to NITER×NNZ.

9.2 Use of CHECK

It is expected that a common use of F11DKF will be as preconditioner for the iterative solution of real, symmetric or nonsymmetric, linear systems. In this situation, F11DKF is likely to be called many times. In the interests of both reliability and efficiency, you are recommended to set CHECK='C' for the first of such calls, and to set CHECK='N' for all subsequent calls.

10 Example

This example solves the real sparse nonsymmetric system of equations Ax=b iteratively using F11DKF as a preconditioner.

10.1 Program Text

Program Text (f11dkfe.f90)

10.2 Program Data

Program Data (f11dkfe.d)

10.3 Program Results

Program Results (f11dkfe.r)

F11 Chapter Contents
F11 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F11DNF : NAG Library, Mark 26

F11 Chapter Contents
F11 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F11DNF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
▸▿ 9 Further Comments
9.1 Timing
9.2 Control of Fill-in
9.3 Algorithmic Details
9.4 Choice of Arguments
9.5 Direct Solution of Sparse Linear Systems
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F11DNF computes an incomplete LU factorization of a complex sparse non-Hermitian matrix, represented in coordinate storage format. This factorization may be used as a preconditioner in combination with F11BSF or F11DQF.

2 Specification

SUBROUTINE F11DNF ( N, NNZ, A, LA, IROW, ICOL, LFILL, DTOL, PSTRAT, MILU, IPIVP, IPIVQ, ISTR, IDIAG, NNZC, NPIVM, IWORK, LIWORK, IFAIL)
INTEGER | N, NNZ, LA, IROW(LA), ICOL(LA), LFILL, IPIVP(N), IPIVQ(N), ISTR(N+1), IDIAG(N), NNZC, NPIVM, IWORK(LIWORK), LIWORK, IFAIL
REAL (KIND=nag_wp) | DTOL
COMPLEX (KIND=nag_wp) | A(LA)
CHARACTER(1) | PSTRAT, MILU

3 Description

F11DNF computes an incomplete LU factorization (see Meijerink and Van der Vorst (1977) and Meijerink and Van der Vorst (1981)) of a complex sparse non-Hermitian n by n matrix A. The factorization is intended primarily for use as a preconditioner with one of the iterative solvers F11BSF or F11DQF.
The decomposition is written in the form
A=M+R,
where
M=PLDUQ
and L is lower triangular with unit diagonal elements, D is diagonal, U is upper triangular with unit diagonals, P and Q are permutation matrices, and R is a remainder matrix.
The amount of fill-in occurring in the factorization can vary from zero to complete fill, and can be controlled by specifying either the maximum level of fill LFILL, or the drop tolerance DTOL.
The argument PSTRAT defines the pivoting strategy to be used. The options currently available are no pivoting, user-defined pivoting, partial pivoting by columns for stability, and complete pivoting by rows for sparsity and by columns for stability. The factorization may optionally be modified to preserve the row-sums of the original matrix.
The sparse matrix A is represented in coordinate storage (CS) format (see Section 2.1.1 in the F11 Chapter Introduction). The array A stores all the nonzero elements of the matrix A, while arrays IROW and ICOL store the corresponding row and column indices respectively. Multiple nonzero elements may not be specified for the same row and column index.
The preconditioning matrix M is returned in terms of the CS representation of the matrix
C=L+D-1+U-2 I.
Further algorithmic details are given in Section 9.3.

4 References

Meijerink J and Van der Vorst H (1977) An iterative solution method for linear systems of which the coefficient matrix is a symmetric M-matrix Math. Comput. 31 148–162
Meijerink J and Van der Vorst H (1981) Guidelines for the usage of incomplete decompositions in solving sets of linear equations as they occur in practical problems J. Comput. Phys. 44 134–155

5 Arguments

1:   N – INTEGERInput
On entry: n, the order of the matrix A.
Constraint: N≥1.
2:   NNZ – INTEGERInput
On entry: the number of nonzero elements in the matrix A.
Constraint: 1≤NNZ≤N 2.
3:   A LA – COMPLEX (KIND=nag_wp) arrayInput/Output
On entry: the nonzero elements in the matrix A, ordered by increasing row index, and by increasing column index within each row. Multiple entries for the same row and column indices are not permitted. The routine F11ZNF may be used to order the elements in this way.
On exit: the first NNZ entries of A contain the nonzero elements of A and the next NNZC entries contain the elements of the matrix C. Matrix elements are ordered by increasing row index, and by increasing column index within each row.
4:   LA – INTEGERInput
On entry: the dimension of the arrays A, IROW and ICOL as declared in the (sub)program from which F11DNF is called. These arrays must be of sufficient size to store both A (NNZ elements) and C (NNZC elements).
Constraint: LA≥2×NNZ.
5:   IROW LA – INTEGER arrayInput/Output
6:   ICOL LA – INTEGER arrayInput/Output
On entry: the row and column indices of the nonzero elements supplied in A.
Constraints:
IROW and ICOL must satisfy these constraints (which may be imposed by a call to F11ZNF):
  • 1≤IROW i≤N and 1≤ICOL i≤N, for i=1,2,…,NNZ;
  • either IROW i-1<IROW i or both IROW i-1=IROW i and ICOL i-1<ICOL i, for i=2,3,…,NNZ.
On exit: the row and column indices of the nonzero elements returned in A.
7:   LFILL – INTEGERInput
On entry: if LFILL≥0 its value is the maximum level of fill allowed in the decomposition (see Section 9.2). A negative value of LFILL indicates that DTOL will be used to control the fill instead.
8:   DTOL – REAL (KIND=nag_wp)Input
On entry: if LFILL<0, DTOL is used as a drop tolerance to control the fill-in (see Section 9.2); otherwise DTOL is not referenced.
Constraint: if LFILL<0, DTOL≥0.0.
9:   PSTRAT – CHARACTER(1)Input
On entry: specifies the pivoting strategy to be adopted.
PSTRAT='N'
No pivoting is carried out.
PSTRAT='U'
Pivoting is carried out according to the user-defined input values of IPIVP and IPIVQ.
PSTRAT='P'
Partial pivoting by columns for stability is carried out.
PSTRAT='C'
Complete pivoting by rows for sparsity, and by columns for stability, is carried out.
Suggested value: PSTRAT='C'.
Constraint: PSTRAT='N', 'U', 'P' or 'C'.
10:   MILU – CHARACTER(1)Input
On entry: indicates whether or not the factorization should be modified to preserve row-sums (see Section 9.4).
MILU='M'
The factorization is modified.
MILU='N'
The factorization is not modified.
Constraint: MILU='M' or 'N'.
11:   IPIVP N – INTEGER arrayInput/Output
12:   IPIVQ N – INTEGER arrayInput/Output
On entry: if PSTRAT='U', then IPIVP k and IPIVQ k must specify the row and column indices of the element used as a pivot at elimination stage k. Otherwise IPIVP and IPIVQ need not be initialized.
Constraint: if PSTRAT='U', IPIVP and IPIVQ must both hold valid permutations of the integers on [1,N].
On exit: the pivot indices. If IPIVP k=i and IPIVQ k=j then the element in row i and column j was used as the pivot at elimination stage k.
13:   ISTR N+1 – INTEGER arrayOutput
On exit: ISTR i, for i=1,2,…,N, is the starting address in the arrays A, IROW and ICOL of row i of the matrix C. ISTR N+1 is the address of the last nonzero element in C plus one.
14:   IDIAG N – INTEGER arrayOutput
On exit: IDIAG i, for i=1,2,…,N, holds the index of arrays A, IROW and ICOL which holds the diagonal element in row i of the matrix C.
15:   NNZC – INTEGEROutput
On exit: the number of nonzero elements in the matrix C.
16:   NPIVM – INTEGEROutput
On exit: if NPIVM>0 it gives the number of pivots which were modified during the factorization to ensure that M exists.
If NPIVM=-1 no pivot modifications were required, but a local restart occurred (see Section 9.3). The quality of the preconditioner will generally depend on the returned value of NPIVM.
If NPIVM is large the preconditioner may not be satisfactory. In this case it may be advantageous to call F11DNF again with an increased value of LFILL, a reduced value of DTOL, or set PSTRAT='C'. See also Section 9.5.
17:   IWORK LIWORK – INTEGER arrayWorkspace
18:   LIWORK – INTEGERInput
On entry: the dimension of the array IWORK as declared in the (sub)program from which F11DNF is called.
Constraint: LIWORK≥7×N+2.
19:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, | N<1,
or | NNZ<1,
or | NNZ>N 2,
or | LA<2×NNZ,
or | LFILL<0 and DTOL<0.0,
or | PSTRAT≠'N', 'U', 'P' or 'C',
or | MILU≠'M' or 'N',
or | LIWORK<7×N+2.
IFAIL=2
On entry, the arrays IROW and ICOL fail to satisfy the following constraints:
  • 1≤IROW i≤N and 1≤ICOL i≤N, for i=1,2,…,NNZ;
  • IROW i-1<IROW i, or IROW i-1=IROW i and ICOL i-1<ICOL i, for i=2,3,…,NNZ.
Therefore a nonzero element has been supplied which does not lie within the matrix A, is out of order, or has duplicate row and column indices. Call F11ZNF to reorder and sum or remove duplicates.
IFAIL=3
On entry, PSTRAT='U', but one or both of IPIVP and IPIVQ does not represent a valid permutation of the integers in [1,N]. An input value of IPIVP or IPIVQ is either out of range or repeated.
IFAIL=4
LA is too small, resulting in insufficient storage space for fill-in elements. The decomposition has been terminated before completion. Either increase LA or reduce the amount of fill by reducing LFILL, or increasing DTOL.
IFAIL=5 (F11ZNF)
A serious error has occurred in an internal call to the specified routine. Check all subroutine calls and array sizes. Seek expert help.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

The accuracy of the factorization will be determined by the size of the elements that are dropped and the size of any modifications made to the pivot elements. If these sizes are small then the computed factors will correspond to a matrix close to A. The factorization can generally be made more accurate by increasing LFILL, or by reducing DTOL with LFILL<0.
If F11DNF is used in combination with F11BSF or F11DQF, the more accurate the factorization the fewer iterations will be required. However, the cost of the decomposition will also generally increase.

8 Parallelism and Performance

F11DNF is not threaded in any implementation.

9 Further Comments

9.1 Timing

The time taken for a call to F11DNF is roughly proportional to NNZC 2/N.

9.2 Control of Fill-in

If LFILL≥0 the amount of fill-in occurring in the incomplete factorization is controlled by limiting the maximum level of fill-in to LFILL. The original nonzero elements of A are defined to be of level 0. The fill level of a new nonzero location occurring during the factorization is defined as:
k=max ke,kc+1,
where ke is the level of fill of the element being eliminated, and kc is the level of fill of the element causing the fill-in.
If LFILL<0 the fill-in is controlled by means of the drop tolerance DTOL. A potential fill-in element a ij occurring in row i and column j will not be included if:
a ij<DTOL×α,
where α is the maximum modulus element in the matrix A.
For either method of control, any elements which are not included are discarded unless MILU='M', in which case their contributions are subtracted from the pivot element in the relevant elimination row, to preserve the row-sums of the original matrix.
Should the factorization process break down a local restart process is implemented as described in Section 9.3. This will affect the amount of fill present in the final factorization.

9.3 Algorithmic Details

The factorization is constructed row by row. At each elimination stage a row index is chosen. In the case of complete pivoting this index is chosen in order to reduce fill-in. Otherwise the rows are treated in the order given, or some user-defined order.
The chosen row is copied from the original matrix A and modified according to those previous elimination stages which affect it. During this process any fill-in elements are either dropped or kept according to the values of LFILL or DTOL. In the case of a modified factorization (MILU='M') the sum of the dropped terms for the given row is stored.
Finally the pivot element for the row is chosen and the multipliers are computed for this elimination stage. For partial or complete pivoting the pivot element is chosen in the interests of stability as the element of largest absolute value in the row. Otherwise the pivot element is chosen in the order given, or some user-defined order.
If the factorization breaks down because the chosen pivot element is zero, or there is no nonzero pivot available, a local restart recovery process is implemented. The modification of the given pivot row according to previous elimination stages is repeated, but this time keeping all fill-in. Note that in this case the final factorization will include more fill than originally specified by the user-supplied value of LFILL or DTOL. The local restart usually results in a suitable nonzero pivot arising. The original criteria for dropping fill-in elements is then resumed for the next elimination stage (hence the local nature of the restart process). Should this restart process also fail to produce a nonzero pivot element an arbitrary unit pivot is introduced in an arbitrarily chosen column. F11DNF returns an integer argument NPIVM which gives the number of these arbitrary unit pivots introduced. If no pivots were modified but local restarts occurred NPIVM=-1 is returned.

9.4 Choice of Arguments

There is unfortunately no choice of the various algorithmic arguments which is optimal for all types of matrix, and some experimentation will generally be required for each new type of matrix encountered. The recommended approach is to start with LFILL=0 and PSTRAT='C'. If the value returned for NPIVM is significantly larger than zero, i.e., a large number of pivot modifications were required to ensure that M existed, the preconditioner is not likely to be satisfactory. In this case increase LFILL until NPIVM falls to a value close to zero.
For certain classes of matrices (typically those arising from the discretization of elliptic or parabolic partial differential equations) the convergence rate of the preconditioned iterative solver can sometimes be significantly improved by using an incomplete factorization which preserves the row-sums of the original matrix. In these cases try setting MILU='M'.

9.5 Direct Solution of Sparse Linear Systems

Although it is not the primary purpose of the routines F11DNF and F11DPF, they may be used together to obtain a direct solution to a nonsingular sparse complex non-Hermitian linear system. To achieve this the call to F11DPF should be preceded by a complete LU factorization
A = PLDUQ=M .
A complete factorization is obtained from a call to F11DNF with LFILL<0 and DTOL=0.0, provided NPIVM≤0 on exit. A positive value of NPIVM indicates that A is singular, or ill-conditioned. A factorization with positive NPIVM may serve as a preconditioner, but will not result in a direct solution. It is therefore essential to check the output value of NPIVM if a direct solution is required.
The use of F11DNF and F11DPF as a direct method is illustrated in F11DPF.

10 Example

This example reads in a complex sparse non-Hermitian matrix A and calls F11DNF to compute an incomplete LU factorization. It then outputs the nonzero elements of both A and C=L+D-1+U-2 I.
The call to F11DNF has LFILL=0, and PSTRAT='C', giving an unmodified zero-fill LU factorization, with row pivoting for sparsity and column pivoting for stability.

10.1 Program Text

Program Text (f11dnfe.f90)

10.2 Program Data

Program Data (f11dnfe.d)

10.3 Program Results

Program Results (f11dnfe.r)

F11 Chapter Contents
F11 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F11DPF : NAG Library, Mark 26

F11 Chapter Contents
F11 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F11DPF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
▸▿ 9 Further Comments
9.1 Timing
9.2 Use of CHECK
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F11DPF solves a system of complex linear equations involving the incomplete LU preconditioning matrix generated by F11DNF.

2 Specification

SUBROUTINE F11DPF ( TRANS, N, A, LA, IROW, ICOL, IPIVP, IPIVQ, ISTR, IDIAG, CHECK, Y, X, IFAIL)
INTEGER | N, LA, IROW(LA), ICOL(LA), IPIVP(N), IPIVQ(N), ISTR(N+1), IDIAG(N), IFAIL
COMPLEX (KIND=nag_wp) | A(LA), Y(N), X(N)
CHARACTER(1) | TRANS, CHECK

3 Description

F11DPF solves a system of complex linear equations
Mx=y,   or  MT x=y,
according to the value of the argument TRANS, where the matrix M=PLDUQ corresponds to an incomplete LU decomposition of a complex sparse matrix stored in coordinate storage (CS) format (see Section 2.1.1 in the F11 Chapter Introduction), as generated by F11DNF.
In the above decomposition L is a lower triangular sparse matrix with unit diagonal elements, D is a diagonal matrix, U is an upper triangular sparse matrix with unit diagonal elements and, P and Q are permutation matrices. L, D and U are supplied to F11DPF through the matrix
C=L+D-1+U-2 I
which is an N by N sparse matrix, stored in CS format, as returned by F11DNF. The permutation matrices P and Q are returned from F11DNF via the arrays IPIVP and IPIVQ.
It is envisaged that a common use of F11DPF will be to carry out the preconditioning step required in the application of F11BSF to sparse complex linear systems. F11DPF is used for this purpose by the Black Box routine F11DQF.
F11DPF may also be used in combination with F11DNF to solve a sparse system of complex linear equations directly (see Section 9.5 in F11DNF). This use of F11DPF is illustrated in Section 10.

4 References

None.

5 Arguments

1:   TRANS – CHARACTER(1)Input
On entry: specifies whether or not the matrix M is transposed.
TRANS='N'
Mx=y is solved.
TRANS='T'
MT x=y is solved.
Constraint: TRANS='N' or 'T'.
2:   N – INTEGERInput
On entry: n, the order of the matrix M. This must be the same value as was supplied in the preceding call to F11DNF.
Constraint: N≥1.
3:   A LA – COMPLEX (KIND=nag_wp) arrayInput
On entry: the values returned in the array A by a previous call to F11DNF.
4:   LA – INTEGERInput
On entry: the dimension of the arrays A, IROW and ICOL as declared in the (sub)program from which F11DPF is called. This must be the same value supplied in the preceding call to F11DNF.
5:   IROW LA – INTEGER arrayInput
6:   ICOL LA – INTEGER arrayInput
7:   IPIVP N – INTEGER arrayInput
8:   IPIVQ N – INTEGER arrayInput
9:   ISTR N+1 – INTEGER arrayInput
10:   IDIAG N – INTEGER arrayInput
On entry: the values returned in arrays IROW, ICOL, IPIVP, IPIVQ, ISTR and IDIAG by a previous call to F11DNF.
11:   CHECK – CHARACTER(1)Input
On entry: specifies whether or not the CS representation of the matrix M should be checked.
CHECK='C'
Checks are carried on the values of N, IROW, ICOL, IPIVP, IPIVQ, ISTR and IDIAG.
CHECK='N'
None of these checks are carried out.
See also Section 9.2.
Constraint: CHECK='C' or 'N'.
12:   Y N – COMPLEX (KIND=nag_wp) arrayInput
On entry: the right-hand side vector y.
13:   X N – COMPLEX (KIND=nag_wp) arrayOutput
On exit: the solution vector x.
14:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, | TRANS≠'N' or 'T',
or | CHECK≠'C' or 'N'.
IFAIL=2
On entry, N<1.
IFAIL=3
On entry, the CS representation of the preconditioning matrix M is invalid. Further details are given in the error message. Check that the call to F11DPF has been preceded by a valid call to F11DNF and that the arrays A, IROW, ICOL, IPIVP, IPIVQ, ISTR and IDIAG have not been corrupted between the two calls.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

If TRANS='N' the computed solution x is the exact solution of a perturbed system of equations M+δM x=y, where
δM≤c n εP LDU Q,
c n is a modest linear function of n, and ε is the machine precision. An equivalent result holds when TRANS='T'.

8 Parallelism and Performance

F11DPF is not threaded in any implementation.

9 Further Comments

9.1 Timing

The time taken for a call to F11DPF is proportional to the value of NNZC returned from F11DNF.

9.2 Use of CHECK

It is expected that a common use of F11DPF will be to carry out the preconditioning step required in the application of F11BSF to sparse complex linear systems. In this situation F11DPF is likely to be called many times with the same matrix M. In the interests of both reliability and efficiency, you are recommended to set CHECK='C' for the first of such calls, and to set CHECK='N' for all subsequent calls.

10 Example

This example reads in a complex sparse non-Hermitian matrix A and a vector y. It then calls F11DNF, with LFILL=-1 and DTOL=0.0, to compute the complete LU decomposition
A=PLDUQ.
Finally it calls F11DPF to solve the system
PLDUQx=y.

10.1 Program Text

Program Text (f11dpfe.f90)

10.2 Program Data

Program Data (f11dpfe.d)

10.3 Program Results

Program Results (f11dpfe.r)

F11 Chapter Contents
F11 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F11DQF : NAG Library, Mark 26

F11 Chapter Contents
F11 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F11DQF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F11DQF solves a complex sparse non-Hermitian system of linear equations, represented in coordinate storage format, using a restarted generalized minimal residual (RGMRES), conjugate gradient squared (CGS), stabilized bi-conjugate gradient (Bi-CGSTAB), or transpose-free quasi-minimal residual (TFQMR) method, with incomplete LU preconditioning.

2 Specification

SUBROUTINE F11DQF ( METHOD, N, NNZ, A, LA, IROW, ICOL, IPIVP, IPIVQ, ISTR, IDIAG, B, M, TOL, MAXITN, X, RNORM, ITN, WORK, LWORK, IFAIL)
INTEGER | N, NNZ, LA, IROW(LA), ICOL(LA), IPIVP(N), IPIVQ(N), ISTR(N+1), IDIAG(N), M, MAXITN, ITN, LWORK, IFAIL
REAL (KIND=nag_wp) | TOL, RNORM
COMPLEX (KIND=nag_wp) | A(LA), B(N), X(N), WORK(LWORK)
CHARACTER(*) | METHOD

3 Description

F11DQF solves a complex sparse non-Hermitian linear system of equations
Ax=b,
using a preconditioned RGMRES (see Saad and Schultz (1986)), CGS (see Sonneveld (1989)), Bi-CGSTAB(ℓ) (see Van der Vorst (1989) and Sleijpen and Fokkema (1993)), or TFQMR (see Freund and Nachtigal (1991) and Freund (1993)) method.
F11DQF uses the incomplete LU factorization determined by F11DNF as the preconditioning matrix. A call to F11DQF must always be preceded by a call to F11DNF. Alternative preconditioners for the same storage scheme are available by calling F11DSF.
The matrix A, and the preconditioning matrix M, are represented in coordinate storage (CS) format (see Section 2.1.1 in the F11 Chapter Introduction) in the arrays A, IROW and ICOL, as returned from F11DNF. The array A holds the nonzero entries in these matrices, while IROW and ICOL hold the corresponding row and column indices.
F11DQF is a Black Box routine which calls F11BRF, F11BSF and F11BTF. If you wish to use an alternative storage scheme, preconditioner, or termination criterion, or require additional diagnostic information, you should call these underlying routines directly.

4 References

Freund R W (1993) A transpose-free quasi-minimal residual algorithm for non-Hermitian linear systems SIAM J. Sci. Comput. 14 470–482
Freund R W and Nachtigal N (1991) QMR: a Quasi-Minimal Residual Method for Non-Hermitian Linear Systems Numer. Math. 60 315–339
Saad Y and Schultz M (1986) GMRES: a generalized minimal residual algorithm for solving nonsymmetric linear systems SIAM J. Sci. Statist. Comput. 7 856–869
Sleijpen G L G and Fokkema D R (1993) BiCGSTABℓ for linear equations involving matrices with complex spectrum ETNA 1 11–32
Sonneveld P (1989) CGS, a fast Lanczos-type solver for nonsymmetric linear systems SIAM J. Sci. Statist. Comput. 10 36–52
Van der Vorst H (1989) Bi-CGSTAB, a fast and smoothly converging variant of Bi-CG for the solution of nonsymmetric linear systems SIAM J. Sci. Statist. Comput. 13 631–644

5 Arguments

1:   METHOD – CHARACTER(*)Input
On entry: specifies the iterative method to be used.
METHOD='RGMRES'
Restarted generalized minimum residual method.
METHOD='CGS'
Conjugate gradient squared method.
METHOD='BICGSTAB'
Bi-conjugate gradient stabilized (ℓ) method.
METHOD='TFQMR'
Transpose-free quasi-minimal residual method.
Constraint: METHOD='RGMRES', 'CGS', 'BICGSTAB' or 'TFQMR'.
2:   N – INTEGERInput
On entry: n, the order of the matrix A. This must be the same value as was supplied in the preceding call to F11DNF.
Constraint: N≥1.
3:   NNZ – INTEGERInput
On entry: the number of nonzero elements in the matrix A. This must be the same value as was supplied in the preceding call to F11DNF.
Constraint: 1≤NNZ≤N 2.
4:   A LA – COMPLEX (KIND=nag_wp) arrayInput
On entry: the values returned in the array A by a previous call to F11DNF.
5:   LA – INTEGERInput
On entry: the dimension of the arrays A, IROW and ICOL as declared in the (sub)program from which F11DQF is called. This must be the same value as was supplied in the preceding call to F11DNF.
Constraint: LA≥2×NNZ.
6:   IROW LA – INTEGER arrayInput
7:   ICOL LA – INTEGER arrayInput
8:   IPIVP N – INTEGER arrayInput
9:   IPIVQ N – INTEGER arrayInput
10:   ISTR N+1 – INTEGER arrayInput
11:   IDIAG N – INTEGER arrayInput
On entry: the values returned in arrays IROW, ICOL, IPIVP, IPIVQ, ISTR and IDIAG by a previous call to F11DNF.
IPIVP and IPIVQ are restored on exit.
12:   B N – COMPLEX (KIND=nag_wp) arrayInput
On entry: the right-hand side vector b.
13:   M – INTEGERInput
On entry: if METHOD='RGMRES', M is the dimension of the restart subspace.
If METHOD='BICGSTAB', M is the order ℓ of the polynomial Bi-CGSTAB method.
Otherwise, M is not referenced.
Constraints:
  • if METHOD='RGMRES', 0<M≤min N,50;
  • if METHOD='BICGSTAB', 0<M≤min N,10.
14:   TOL – REAL (KIND=nag_wp)Input
On entry: the required tolerance. Let xk denote the approximate solution at iteration k, and rk the corresponding residual. The algorithm is considered to have converged at iteration k if
rk∞≤τ×b∞+A∞xk∞.
If TOL≤0.0, τ=max⁡ε,10 ε,n ε is used, where ε is the machine precision. Otherwise τ=max TOL,10 ε,n ε is used.
Constraint: TOL<1.0.
15:   MAXITN – INTEGERInput
On entry: the maximum number of iterations allowed.
Constraint: MAXITN≥1.
16:   X N – COMPLEX (KIND=nag_wp) arrayInput/Output
On entry: an initial approximation to the solution vector x.
On exit: an improved approximation to the solution vector x.
17:   RNORM – REAL (KIND=nag_wp)Output
On exit: the final value of the residual norm rk∞, where k is the output value of ITN.
18:   ITN – INTEGEROutput
On exit: the number of iterations carried out.
19:   WORK LWORK – COMPLEX (KIND=nag_wp) arrayWorkspace
20:   LWORK – INTEGERInput
On entry: the dimension of the array WORK as declared in the (sub)program from which F11DQF is called.
Constraints:
  • if METHOD='RGMRES', LWORK≥4×N+M×M+N+5+121;
  • if METHOD='CGS', LWORK≥8×N+120;
  • if METHOD='BICGSTAB', LWORK≥2×N×M+3+M×M+2+120;
  • if METHOD='TFQMR', LWORK≥11×N+120.
21:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, | METHOD≠'RGMRES','CGS','BICGSTAB', or 'TFQMR',
or | N<1,
or | NNZ<1,
or | NNZ>N 2,
or | LA<2×NNZ,
or | M<1 and METHOD='RGMRES' or METHOD='BICGSTAB',
or | M>min N,50, with METHOD='RGMRES',
or | M>min N,10, with METHOD='BICGSTAB',
or | TOL≥1.0,
or | MAXITN<1,
or | LWORK too small.
IFAIL=2
On entry, the CS representation of A is invalid. Further details are given in the error message. Check that the call to F11DQF has been preceded by a valid call to F11DNF, and that the arrays A, IROW, and ICOL have not been corrupted between the two calls.
IFAIL=3
On entry, the CS representation of the preconditioning matrix M is invalid. Further details are given in the error message. Check that the call to F11DQF has been preceded by a valid call to F11DNF and that the arrays A, IROW, ICOL, IPIVP, IPIVQ, ISTR and IDIAG have not been corrupted between the two calls.
IFAIL=4
The required accuracy could not be obtained. However, a reasonable accuracy may have been obtained, and further iterations could not improve the result. You should check the output value of RNORM for acceptability. This error code usually implies that your problem has been fully and satisfactorily solved to within or close to the accuracy available on your system. Further iterations are unlikely to improve on this situation.
IFAIL=5
Required accuracy not obtained in MAXITN iterations.
IFAIL=6
Algorithmic breakdown. A solution is returned, although it is possible that it is completely inaccurate.
IFAIL=7 (F11BRF, F11BSF or F11BTF)
A serious error has occurred in an internal call to one of the specified routines. Check all subroutine calls and array sizes. Seek expert help.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

On successful termination, the final residual rk=b-A xk, where k=ITN, satisfies the termination criterion
rk∞≤τ×b∞+A∞xk∞.
The value of the final residual norm is returned in RNORM.

8 Parallelism and Performance

F11DQF is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
F11DQF makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The time taken by F11DQF for each iteration is roughly proportional to the value of NNZC returned from the preceding call to F11DNF.
The number of iterations required to achieve a prescribed accuracy cannot be easily determined a priori, as it can depend dramatically on the conditioning and spectrum of the preconditioned coefficient matrix A-=M-1 A.

10 Example

This example solves a complex sparse non-Hermitian linear system of equations using the CGS method, with incomplete LU preconditioning.

10.1 Program Text

Program Text (f11dqfe.f90)

10.2 Program Data

Program Data (f11dqfe.d)

10.3 Program Results

Program Results (f11dqfe.r)

F11 Chapter Contents
F11 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F11DRF : NAG Library, Mark 26

F11 Chapter Contents
F11 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F11DRF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
▸▿ 9 Further Comments
9.1 Timing
9.2 Use of CHECK
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F11DRF solves a system of linear equations involving the preconditioning matrix corresponding to SSOR applied to a complex sparse non-Hermitian matrix, represented in coordinate storage format.

2 Specification

SUBROUTINE F11DRF ( TRANS, N, NNZ, A, IROW, ICOL, RDIAG, OMEGA, CHECK, Y, X, IWORK, IFAIL)
INTEGER | N, NNZ, IROW(NNZ), ICOL(NNZ), IWORK(2*N+1), IFAIL
REAL (KIND=nag_wp) | OMEGA
COMPLEX (KIND=nag_wp) | A(NNZ), RDIAG(N), Y(N), X(N)
CHARACTER(1) | TRANS, CHECK

3 Description

F11DRF solves a system of linear equations
Mx=y,   or  MH x=y,
according to the value of the argument TRANS, where the matrix
M=1 ω 2-ω D+ω L D-1 D+ω U
corresponds to symmetric successive-over-relaxation (SSOR) Young (1971) applied to a linear system Ax=b, where A is a complex sparse non-Hermitian matrix stored in coordinate storage (CS) format (see Section 2.1.1 in the F11 Chapter Introduction).
In the definition of M given above D is the diagonal part of A, L is the strictly lower triangular part of A, U is the strictly upper triangular part of A, and ω is a user-defined relaxation parameter.
It is envisaged that a common use of F11DRF will be to carry out the preconditioning step required in the application of F11BSF to sparse linear systems. For an illustration of this use of F11DRF see the example program given in Section 10. F11DRF is also used for this purpose by the Black Box routine F11DSF.

4 References

Young D (1971) Iterative Solution of Large Linear Systems Academic Press, New York

5 Arguments

1:   TRANS – CHARACTER(1)Input
On entry: specifies whether or not the matrix M is transposed.
TRANS='N'
Mx=y is solved.
TRANS='T'
MH x=y is solved.
Constraint: TRANS='N' or 'T'.
2:   N – INTEGERInput
On entry: n, the order of the matrix A.
Constraint: N≥1.
3:   NNZ – INTEGERInput
On entry: the number of nonzero elements in the matrix A.
Constraint: 1≤NNZ≤N 2.
4:   A NNZ – COMPLEX (KIND=nag_wp) arrayInput
On entry: the nonzero elements in the matrix A, ordered by increasing row index, and by increasing column index within each row. Multiple entries for the same row and column indices are not permitted. The routine F11ZNF may be used to order the elements in this way.
5:   IROW NNZ – INTEGER arrayInput
6:   ICOL NNZ – INTEGER arrayInput
On entry: the row and column indices of the nonzero elements supplied in A.
Constraints:
IROW and ICOL must satisfy the following constraints (which may be imposed by a call to F11ZNF):
  • 1≤IROW i≤N and 1≤ICOL i≤N, for i=1,2,…,NNZ;
  • either IROW i-1<IROW i or both IROW i-1=IROW i and ICOL i-1<ICOL i, for i=2,3,…,NNZ.
7:   RDIAG N – COMPLEX (KIND=nag_wp) arrayInput
On entry: the elements of the diagonal matrix D-1, where D is the diagonal part of A.
8:   OMEGA – REAL (KIND=nag_wp)Input
On entry: the relaxation parameter ω.
Constraint: 0.0<OMEGA<2.0.
9:   CHECK – CHARACTER(1)Input
On entry: specifies whether or not the CS representation of the matrix M should be checked.
CHECK='C'
Checks are carried on the values of N, NNZ, IROW, ICOL and OMEGA.
CHECK='N'
None of these checks are carried out.
See also Section 9.2.
Constraint: CHECK='C' or 'N'.
10:   Y N – COMPLEX (KIND=nag_wp) arrayInput
On entry: the right-hand side vector y.
11:   X N – COMPLEX (KIND=nag_wp) arrayOutput
On exit: the solution vector x.
12:   IWORK 2×N+1 – INTEGER arrayWorkspace
13:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, | TRANS≠'N' or 'T',
or | CHECK≠'C' or 'N'.
IFAIL=2
On entry, | N<1,
or | NNZ<1,
or | NNZ>N 2,
or | OMEGA lies outside the interval 0.0,2.0,
IFAIL=3
On entry, the arrays IROW and ICOL fail to satisfy the following constraints:
  • 1≤IROW i≤N and 1≤ICOL i≤N, for i=1,2,…,NNZ;
  • IROW i-1<IROW i or IROW i-1=IROW i and ICOL i-1<ICOL i, for i=2,3,…,NNZ.
Therefore a nonzero element has been supplied which does not lie in the matrix A, is out of order, or has duplicate row and column indices. Call F11ZNF to reorder and sum or remove duplicates.
IFAIL=4
On entry, the matrix A has a zero diagonal element. The SSOR preconditioner is not appropriate for this problem.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

If TRANS='N' the computed solution x is the exact solution of a perturbed system of equations M+δM x=y, where
δM≤c n ε D+ωLD-1D+ωU,
c n is a modest linear function of n, and ε is the machine precision. An equivalent result holds when TRANS='T'.

8 Parallelism and Performance

F11DRF is not threaded in any implementation.

9 Further Comments

9.1 Timing

The time taken for a call to F11DRF is proportional to NNZ.

9.2 Use of CHECK

It is expected that a common use of F11DRF will be to carry out the preconditioning step required in the application of F11BSF to sparse linear systems. In this situation F11DRF is likely to be called many times with the same matrix M. In the interests of both reliability and efficiency, you are recommended to set CHECK='C' for the first of such calls, and CHECK='N' for all subsequent calls.

10 Example

This example solves a complex sparse linear system of equations
Ax=b,
using RGMRES with SSOR preconditioning.
The RGMRES algorithm itself is implemented by the reverse communication routine F11BSF, which returns repeatedly to the calling program with various values of the argument IREVCM. This argument indicates the action to be taken by the calling program.
  • If IREVCM=1, a matrix-vector product v=Au is required. This is implemented by a call to F11XNF.
  • If IREVCM=-1, a conjugate transposed matrix-vector product v=AH u is required in the estimation of the norm of A. This is implemented by a call to F11XNF.
  • If IREVCM=2, a solution of the preconditioning equation Mv=u is required. This is achieved by a call to F11DRF.
  • If IREVCM=4, F11BSF has completed its tasks. Either the iteration has terminated, or an error condition has arisen.
For further details see the routine document for F11BSF.

10.1 Program Text

Program Text (f11drfe.f90)

10.2 Program Data

Program Data (f11drfe.d)

10.3 Program Results

Program Results (f11drfe.r)

F11 Chapter Contents
F11 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F11DSF : NAG Library, Mark 26

F11 Chapter Contents
F11 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F11DSF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F11DSF solves a complex sparse non-Hermitian system of linear equations, represented in coordinate storage format, using a restarted generalized minimal residual (RGMRES), conjugate gradient squared (CGS), stabilized bi-conjugate gradient (Bi-CGSTAB), or transpose-free quasi-minimal residual (TFQMR) method, without preconditioning, with Jacobi, or with SSOR preconditioning.

2 Specification

SUBROUTINE F11DSF ( METHOD, PRECON, N, NNZ, A, IROW, ICOL, OMEGA, B, M, TOL, MAXITN, X, RNORM, ITN, WORK, LWORK, IWORK, IFAIL)
INTEGER | N, NNZ, IROW(NNZ), ICOL(NNZ), M, MAXITN, ITN, LWORK, IWORK(2*N+1), IFAIL
REAL (KIND=nag_wp) | OMEGA, TOL, RNORM
COMPLEX (KIND=nag_wp) | A(NNZ), B(N), X(N), WORK(LWORK)
CHARACTER(*) | METHOD
CHARACTER(1) | PRECON

3 Description

F11DSF solves a complex sparse non-Hermitian system of linear equations:
Ax=b,
using an RGMRES (see Saad and Schultz (1986)), CGS (see Sonneveld (1989)), Bi-CGSTAB(ℓ) (see Van der Vorst (1989) and Sleijpen and Fokkema (1993)), or TFQMR (see Freund and Nachtigal (1991) and Freund (1993)) method.
F11DSF allows the following choices for the preconditioner:
  • – no preconditioning;
  • – Jacobi preconditioning (see Young (1971));
  • – symmetric successive-over-relaxation (SSOR) preconditioning (see Young (1971)).
For incomplete LU (ILU) preconditioning see F11DQF.
The matrix A is represented in coordinate storage (CS) format (see Section 2.1.1 in the F11 Chapter Introduction) in the arrays A, IROW and ICOL. The array A holds the nonzero entries in the matrix, while IROW and ICOL hold the corresponding row and column indices.
F11DSF is a Black Box routine which calls F11BRF, F11BSF and F11BTF. If you wish to use an alternative storage scheme, preconditioner, or termination criterion, or require additional diagnostic information, you should call these underlying routines directly.

4 References

Freund R W (1993) A transpose-free quasi-minimal residual algorithm for non-Hermitian linear systems SIAM J. Sci. Comput. 14 470–482
Freund R W and Nachtigal N (1991) QMR: a Quasi-Minimal Residual Method for Non-Hermitian Linear Systems Numer. Math. 60 315–339
Saad Y and Schultz M (1986) GMRES: a generalized minimal residual algorithm for solving nonsymmetric linear systems SIAM J. Sci. Statist. Comput. 7 856–869
Sleijpen G L G and Fokkema D R (1993) BiCGSTABℓ for linear equations involving matrices with complex spectrum ETNA 1 11–32
Sonneveld P (1989) CGS, a fast Lanczos-type solver for nonsymmetric linear systems SIAM J. Sci. Statist. Comput. 10 36–52
Van der Vorst H (1989) Bi-CGSTAB, a fast and smoothly converging variant of Bi-CG for the solution of nonsymmetric linear systems SIAM J. Sci. Statist. Comput. 13 631–644
Young D (1971) Iterative Solution of Large Linear Systems Academic Press, New York

5 Arguments

1:   METHOD – CHARACTER(*)Input
On entry: specifies the iterative method to be used.
METHOD='RGMRES'
Restarted generalized minimum residual method.
METHOD='CGS'
Conjugate gradient squared method.
METHOD='BICGSTAB'
Bi-conjugate gradient stabilized (ℓ) method.
METHOD='TFQMR'
Transpose-free quasi-minimal residual method.
Constraint: METHOD='RGMRES', 'CGS', 'BICGSTAB' or 'TFQMR'.
2:   PRECON – CHARACTER(1)Input
On entry: specifies the type of preconditioning to be used.
PRECON='N'
No preconditioning.
PRECON='J'
Jacobi.
PRECON='S'
Symmetric successive-over-relaxation (SSOR).
Constraint: PRECON='N', 'J' or 'S'.
3:   N – INTEGERInput
On entry: n, the order of the matrix A.
Constraint: N≥1.
4:   NNZ – INTEGERInput
On entry: the number of nonzero elements in the matrix A.
Constraint: 1≤NNZ≤N 2.
5:   A NNZ – COMPLEX (KIND=nag_wp) arrayInput
On entry: the nonzero elements of the matrix A, ordered by increasing row index, and by increasing column index within each row. Multiple entries for the same row and column indices are not permitted. The routine F11ZNF may be used to order the elements in this way.
6:   IROW NNZ – INTEGER arrayInput
7:   ICOL NNZ – INTEGER arrayInput
On entry: the row and column indices of the nonzero elements supplied in A.
Constraints:
IROW and ICOL must satisfy the following constraints (which may be imposed by a call to F11ZNF):
  • 1≤IROW i≤N and 1≤ICOL i≤N, for i=1,2,…,NNZ;
  • either IROW i-1<IROW i or both IROW i-1=IROW i and ICOL i-1<ICOL i, for i=2,3,…,NNZ.
8:   OMEGA – REAL (KIND=nag_wp)Input
On entry: if PRECON='S', OMEGA is the relaxation parameter ω to be used in the SSOR method. Otherwise OMEGA need not be initialized and is not referenced.
Constraint: 0.0<OMEGA<2.0.
9:   B N – COMPLEX (KIND=nag_wp) arrayInput
On entry: the right-hand side vector b.
10:   M – INTEGERInput
On entry: if METHOD='RGMRES', M is the dimension of the restart subspace.
If METHOD='BICGSTAB', M is the order ℓ of the polynomial Bi-CGSTAB method.
Otherwise, M is not referenced.
Constraints:
  • if METHOD='RGMRES', 0<M≤min N,50;
  • if METHOD='BICGSTAB', 0<M≤min N,10.
11:   TOL – REAL (KIND=nag_wp)Input
On entry: the required tolerance. Let xk denote the approximate solution at iteration k, and rk the corresponding residual. The algorithm is considered to have converged at iteration k if
rk∞≤τ×b∞+A∞xk∞.
If TOL≤0.0, τ=max⁡ε,10 ε,n ε is used, where ε is the machine precision. Otherwise τ=max TOL,10 ε,n ε is used.
Constraint: TOL<1.0.
12:   MAXITN – INTEGERInput
On entry: the maximum number of iterations allowed.
Constraint: MAXITN≥1.
13:   X N – COMPLEX (KIND=nag_wp) arrayInput/Output
On entry: an initial approximation to the solution vector x.
On exit: an improved approximation to the solution vector x.
14:   RNORM – REAL (KIND=nag_wp)Output
On exit: the final value of the residual norm rk∞, where k is the output value of ITN.
15:   ITN – INTEGEROutput
On exit: the number of iterations carried out.
16:   WORK LWORK – COMPLEX (KIND=nag_wp) arrayWorkspace
17:   LWORK – INTEGERInput
On entry: the dimension of the array WORK as declared in the (sub)program from which F11DSF is called.
Constraints:
  • if METHOD='RGMRES', LWORK≥4×N+M×M+N+5+nu+121;
  • if METHOD='CGS', LWORK≥8×N+nu+120;
  • if METHOD='BICGSTAB', LWORK≥2×N×M+3+M×M+2+nu+120;
  • if METHOD='TFQMR', LWORK≥11×N+nu+120.
Where nu=N for PRECON='J' or 'S' and nu=0 otherwise.
18:   IWORK 2×N+1 – INTEGER arrayWorkspace
19:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, | METHOD≠'RGMRES', 'CGS', 'BICGSTAB' or 'TFQMR',
or | PRECON≠'N', 'J' or 'S',
or | N<1,
or | NNZ<1,
or | NNZ>N 2,
or | PRECON='S' and OMEGA lies outside the interval 0.0,2.0,
or | M<1,
or | M>min N,50, when METHOD='RGMRES',
or | M>min N,10, when METHOD='BICGSTAB',
or | TOL≥1.0,
or | MAXITN<1,
or | LWORK is too small.
IFAIL=2
On entry, the arrays IROW and ICOL fail to satisfy the following constraints:
  • 1≤IROW i≤N and 1≤ICOL i≤N, for i=1,2,…,NNZ;
  • IROW i-1<IROW i, or IROW i-1=IROW i and ICOL i-1<ICOL i, for i=2,3,…,NNZ.
Therefore a nonzero element has been supplied which does not lie within the matrix A, is out of order, or has duplicate row and column indices. Call F11ZNF to reorder and sum or remove duplicates.
IFAIL=3
On entry, the matrix A has a zero diagonal element. Jacobi and SSOR preconditioners are therefore not appropriate for this problem.
IFAIL=4
The required accuracy could not be obtained. However, a reasonable accuracy may have been obtained, and further iterations could not improve the result. You should check the output value of RNORM for acceptability. This error code usually implies that your problem has been fully and satisfactorily solved to within or close to the accuracy available on your system. Further iterations are unlikely to improve on this situation.
IFAIL=5
Required accuracy not obtained in MAXITN iterations.
IFAIL=6
Algorithmic breakdown. A solution is returned, although it is possible that it is completely inaccurate.
IFAIL=7 (F11BRF, F11BSF or F11BTF)
A serious error has occurred in an internal call to one of the specified routines. Check all subroutine calls and array sizes. Seek expert help.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

On successful termination, the final residual rk=b-A xk, where k=ITN, satisfies the termination criterion
rk∞≤τ×b∞+A∞xk∞.
The value of the final residual norm is returned in RNORM.

8 Parallelism and Performance

F11DSF is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
F11DSF makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The time taken by F11DSF for each iteration is roughly proportional to NNZ.
The number of iterations required to achieve a prescribed accuracy cannot easily be determined a priori, as it can depend dramatically on the conditioning and spectrum of the preconditioned coefficient matrix A-=M-1 A, for some preconditioning matrix M.

10 Example

This example solves a complex sparse non-Hermitian system of equations using the CGS method, with no preconditioning.

10.1 Program Text

Program Text (f11dsfe.f90)

10.2 Program Data

Program Data (f11dsfe.d)

10.3 Program Results

Program Results (f11dsfe.r)

F11 Chapter Contents
F11 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F11DTF : NAG Library, Mark 26

F11 Chapter Contents
F11 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F11DTF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F11DTF computes a block diagonal incomplete LU factorization of a complex sparse non-Hermitian matrix, represented in coordinate storage format. The diagonal blocks may be composed of arbitrary rows and the corresponding columns, and may overlap. This factorization can be used to provide a block Jacobi or additive Schwarz preconditioner, for use in combination with F11BSF or F11DUF.

2 Specification

SUBROUTINE F11DTF ( N, NNZ, A, LA, IROW, ICOL, NB, ISTB, INDB, LINDB, LFILL, DTOL, PSTRAT, MILU, IPIVP, IPIVQ, ISTR, IDIAG, NNZC, NPIVM, IWORK, LIWORK, IFAIL)
INTEGER | N, NNZ, LA, IROW(LA), ICOL(LA), NB, ISTB(NB+1), INDB(LINDB), LINDB, LFILL(NB), IPIVP(LINDB), IPIVQ(LINDB), ISTR(LINDB+1), IDIAG(LINDB), NNZC, NPIVM(NB), IWORK(LIWORK), LIWORK, IFAIL
REAL (KIND=nag_wp) | DTOL(NB)
COMPLEX (KIND=nag_wp) | A(LA)
CHARACTER(1) | PSTRAT(NB), MILU(NB)

3 Description

F11DTF computes an incomplete LU factorization (see Meijerink and Van der Vorst (1977) and Meijerink and Van der Vorst (1981)) of the (possibly overlapping) diagonal blocks Ab, b=1,2,…,NB, of a complex sparse non-Hermitian n by n matrix A. The factorization is intended primarily for use as a block Jacobi or additive Schwarz preconditioner (see Saad (1996)), with one of the iterative solvers F11BSF and F11DUF.
The NB diagonal blocks need not consist of consecutive rows and columns of A, but may be composed of arbitrarily indexed rows, and the corresponding columns, as defined in the arguments INDB and ISTB. Any given row or column index may appear in more than one diagonal block, resulting in overlap. Each diagonal block Ab, b=1,2,…,NB, is factorized as:
Ab = Mb+Rb
where
Mb = Pb Lb Db Ub Qb
and Lb is lower triangular with unit diagonal elements, Db is diagonal, Ub is upper triangular with unit diagonals, Pb and Qb are permutation matrices, and Rb is a remainder matrix.
The amount of fill-in occurring in the factorization of block b can vary from zero to complete fill, and can be controlled by specifying either the maximum level of fill LFILL b, or the drop tolerance DTOL b.
The parameter PSTRAT b defines the pivoting strategy to be used in block b. The options currently available are no pivoting, user-defined pivoting, partial pivoting by columns for stability, and complete pivoting by rows for sparsity and by columns for stability. The factorization may optionally be modified to preserve the row-sums of the original block matrix.
The sparse matrix A is represented in coordinate storage (CS) format (see Section 2.1.1 in the F11 Chapter Introduction). The array A stores all the nonzero elements of the matrix A, while arrays IROW and ICOL store the corresponding row and column indices respectively. Multiple nonzero elements may not be specified for the same row and column index.
The preconditioning matrices Mb, b=1,2,…,NB, are returned in terms of the CS representations of the matrices
Cb = Lb + D-1 b + Ub -2 I .

4 References

Meijerink J and Van der Vorst H (1977) An iterative solution method for linear systems of which the coefficient matrix is a symmetric M-matrix Math. Comput. 31 148–162
Meijerink J and Van der Vorst H (1981) Guidelines for the usage of incomplete decompositions in solving sets of linear equations as they occur in practical problems J. Comput. Phys. 44 134–155
Saad Y (1996) Iterative Methods for Sparse Linear Systems PWS Publishing Company, Boston, MA

5 Arguments

1:   N – INTEGERInput
On entry: n, the order of the matrix A.
Constraint: N≥1.
2:   NNZ – INTEGERInput
On entry: the number of nonzero elements in the matrix A.
Constraint: 1≤NNZ≤N 2.
3:   A LA – COMPLEX (KIND=nag_wp) arrayInput/Output
On entry: the nonzero elements in the matrix A, ordered by increasing row index, and by increasing column index within each row. Multiple entries for the same row and column indices are not permitted. The routine F11ZNF may be used to order the elements in this way.
On exit: the first NNZ entries of A contain the nonzero elements of A and the next NNZC entries contain the elements of the matrices Cb, for b=1,2,…,NB stored consecutively. Within each block the matrix elements are ordered by increasing row index, and by increasing column index within each row.
4:   LA – INTEGERInput
On entry: the dimension of the arrays A, IROW and ICOL as declared in the (sub)program from which F11DTF is called. These arrays must be of sufficient size to store both A (NNZ elements) and C (NNZC elements).
Note: the minimum value for LA is only appropriate if LFILL and DTOL are set such that minimal fill-in occurs. If this is not the case then we recommend that LA is set much larger than the minimum value indicated in the constraint.
Constraint: LA≥2×NNZ.
5:   IROW LA – INTEGER arrayInput/Output
6:   ICOL LA – INTEGER arrayInput/Output
On entry: the row and column indices of the nonzero elements supplied in A.
Constraints:
IROW and ICOL must satisfy these constraints (which may be imposed by a call to F11ZNF):
  • 1≤IROW i≤N and 1≤ICOL i≤N, for i=1,2,…,NNZ;
  • either IROW i-1<IROW i or both IROW i-1=IROW i and ICOL i-1<ICOL i, for i=2,3,…,NNZ.
On exit: the row and column indices of the nonzero elements returned in A.
7:   NB – INTEGERInput
On entry: the number of diagonal blocks to factorize.
Constraint: 1≤NB≤N.
8:   ISTB NB+1 – INTEGER arrayInput
On entry: ISTB b, for b=1,2,…,NB, holds the indices in arrays INDB, IPIVP, IPIVQ and IDIAG that, on successful exit from this function, define block b. ISTB NB+1 holds the sum of the number of rows in all blocks plus ISTB 1.
Constraint: ISTB 1≥1, ISTB b< ISTB b+1 , for b=1,2,…,NB.
9:   INDB LINDB – INTEGER arrayInput
On entry: INDB must hold the row indices appearing in each diagonal block, stored consecutively. Thus the elements INDB ISTB b to INDB ISTB b+1-1 are the row indices in the bth block, for b=1,2,…,NB.
Constraint: 1≤INDB m≤N, for m=1,2,…,ISTB NB+1-1.
10:   LINDB – INTEGERInput
On entry: the dimension of the arrays INDB, IPIVP, IPIVQ and IDIAG as declared in the (sub)program from which F11DTF is called.
Constraint: LINDB≥ISTB NB+1-1.
11:   LFILL NB – INTEGER arrayInput
On entry: if LFILL b≥0 its value is the maximum level of fill allowed in the decomposition of the block b (see Section 9.2 in F11DNF). A negative value of LFILL b indicates that DTOL b will be used to control the fill in block b instead.
12:   DTOL NB – REAL (KIND=nag_wp) arrayInput
On entry: if LFILL b<0 then DTOL b is used as a drop tolerance in block b to control the fill-in (see Section 9.2 in F11DNF); otherwise DTOL b is not referenced.
Constraint: if LFILL b<0, DTOL b≥0.0, for b=1,2,…,NB.
13:   PSTRAT NB – CHARACTER(1) arrayInput
On entry: PSTRAT b, for b=1,2,…,NB, specifies the pivoting strategy to be adopted in the block as follows:
PSTRAT b='N'
No pivoting is carried out.
PSTRAT b='U'
Pivoting is carried out according to the user-defined input values of IPIVP and IPIVQ.
PSTRAT b='P'
Partial pivoting by columns for stability is carried out.
PSTRAT b='C'
Complete pivoting by rows for sparsity, and by columns for stability, is carried out.
Suggested value: PSTRAT b='C', for b=1,2,…,NB.
Constraint: PSTRAT b='N', 'U', 'P' or 'C', for b=1,2,…,NB.
14:   MILU NB – CHARACTER(1) arrayInput
On entry: MILU b, for b=1,2,…,NB, indicates whether or not the factorization in block b should be modified to preserve row-sums (see Section 9.4 in F11DNF).
MILU b='M'
The factorization is modified.
MILU b='N'
The factorization is not modified.
Constraint: MILU b='M' or 'N', for b=1,2,…,NB.
15:   IPIVP LINDB – INTEGER arrayInput/Output
16:   IPIVQ LINDB – INTEGER arrayInput/Output
On entry: if PSTRAT b='U', then IPIVP ISTB b+k-1 and IPIVQ ISTB b+k-1 must specify the row and column indices of the element used as a pivot at elimination stage k of the factorization of the block. Otherwise IPIVP and IPIVQ need not be initialized.
Constraint: if PSTRAT b='U', the elements ISTB b to ISTB b+1-1 of IPIVP and IPIVQ must both hold valid permutations of the integers on 1,ISTB b+1-ISTB b.
On exit: the row and column indices of the pivot elements, arranged consecutively for each block, as for INDB. If IPIVP ISTB b+k-1=i and IPIVQ ISTB b+k-1=j, then the element in row i and column j of Ab was used as the pivot at elimination stage k.
17:   ISTR LINDB+1 – INTEGER arrayOutput
On exit: ISTR ISTB b+k-1, gives the index in the arrays A, IROW and ICOL of row k of the matrix Cb, for b=1,2,…,NB and k=1,2,…,ISTB b+1-ISTB b.
ISTR ISTB NB+1 contains NNZ+NNZC+1.
18:   IDIAG LINDB – INTEGER arrayOutput
On exit: IDIAG ISTB b+k-1, gives the index in the arrays A, IROW and ICOL of the diagonal element in row k of the matrix Cb, for b=1,2,…,NB and k=1,2,…,ISTB b+1-ISTB b.
19:   NNZC – INTEGEROutput
On exit: the sum total number of nonzero elements in the matrices Cb, for b=1,2,…,NB.
20:   NPIVM NB – INTEGER arrayOutput
On exit: if NPIVM b>0 it gives the number of pivots which were modified during the factorization to ensure that Mb exists.
If NPIVM b=-1 no pivot modifications were required, but a local restart occurred (see Section 9.3 in F11DNF). The quality of the preconditioner will generally depend on the returned values of NPIVM b, for b=1,2,…,NB.
If NPIVM b is large, for some b, the preconditioner may not be satisfactory. In this case it may be advantageous to call F11DTF again with an increased value of LFILL b, a reduced value of DTOL b, or PSTRAT b='C'.
21:   IWORK LIWORK – INTEGER arrayWorkspace
22:   LIWORK – INTEGERInput
On entry: the dimension of the array IWORK as declared in the (sub)program from which F11DTF is called.
Constraint: LIWORK≥9×N+3.
23:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, DTOL value=value.
Constraint: DTOL b≥0.0, for b=1,2,…,NB.
On entry, for b=value, ISTB b+1=value and ISTB b=value.
Constraint: ISTB b+1>ISTB b, for b=1,2,…,NB.
On entry, INDB value=value and N=value.
Constraint: 1≤INDB m≤N, for m=1,2,…,ISTB NB+1-1
On entry, ISTB 1=value.
Constraint: ISTB 1≥1.
On entry, LA=value and NNZ=value.
Constraint: LA≥2×NNZ.
On entry, LINDB=value, ISTB NB+1-1=value and NB=value.
Constraint: LINDB≥ISTB NB+1-1.
On entry, LIWORK=value.
Constraint: LIWORK≥value.
On entry, MILU value=value.
Constraint: MILU b='M' or 'N' for all b.
On entry, N=value.
Constraint: N≥1.
On entry, NB=value and N=value.
Constraint: 1≤NB≤N.
On entry, NNZ=value.
Constraint: NNZ≥1.
On entry, NNZ=value and N=value.
Constraint: NNZ≤N 2.
On entry, PSTRAT value=value.
Constraint: PSTRAT b='N', 'U', 'P' or 'C' for all b.
IFAIL=2
On entry, element value of A was out of order.
On entry, ICOL value=value and N=value.
Constraint: 1≤ICOL j≤N, for j=1,2,…,NNZ.
On entry, IROW value=value and N=value.
Constraint: 1≤IROW i≤N, for i=1,2,…,NNZ.
On entry, location value of IROW,ICOL was a duplicate.
IFAIL=3
On entry, the user-supplied value of IPIVP for block value lies outside its range.
On entry, the user-supplied value of IPIVP for block value was repeated.
On entry, the user-supplied value of IPIVQ for block value lies outside its range.
On entry, the user-supplied value of IPIVQ for block value was repeated.
IFAIL=4
The number of nonzero entries in the decomposition is too large.
The decomposition has been terminated before completion.
Either increase LA, or reduce the fill by reducing LFILL, or increasing DTOL.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

The accuracy of the factorization of each block Ab will be determined by the size of the elements that are dropped and the size of any modifications made to the pivot elements. If these sizes are small then the computed factors will correspond to a matrix close to Ab. The factorization can generally be made more accurate by increasing the level of fill LFILL b, or by reducing the drop tolerance DTOL b with LFILL b<0.
If F11DTF is used in combination with F11BSF or F11DUF, the more accurate the factorization the fewer iterations will be required. However, the cost of the decomposition will also generally increase.

8 Parallelism and Performance

F11DTF is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

F11DTF calls F11DNF internally for each block Ab. The comments and advice provided in Section 9 in F11DNF on timing, control of fill, algorithmic details, and choice of parameters, are all therefore relevant to F11DTF, if interpreted blockwise.

10 Example

This example program reads in a sparse matrix A and then defines a block partitioning of the row indices with a user-supplied overlap and computes an overlapping incomplete LU factorization suitable for use as an additive Schwarz preconditioner. Such a factorization is used for this purpose in the example program of F11DUF.

10.1 Program Text

Program Text (f11dtfe.f90)

10.2 Program Data

Program Data (f11dtfe.d)

10.3 Program Results

Program Results (f11dtfe.r)

F11 Chapter Contents
F11 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F11DUF : NAG Library, Mark 26

F11 Chapter Contents
F11 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F11DUF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F11DUF solves a complex sparse non-Hermitian system of linear equations, represented in coordinate storage format, using a restarted generalized minimal residual (RGMRES), conjugate gradient squared (CGS), stabilized bi-conjugate gradient (Bi-CGSTAB), or transpose-free quasi-minimal residual (TFQMR) method, with block Jacobi or additive Schwarz preconditioning.

2 Specification

SUBROUTINE F11DUF ( METHOD, N, NNZ, A, LA, IROW, ICOL, NB, ISTB, INDB, LINDB, IPIVP, IPIVQ, ISTR, IDIAG, B, M, TOL, MAXITN, X, RNORM, ITN, WORK, LWORK, IFAIL)
INTEGER | N, NNZ, LA, IROW(LA), ICOL(LA), NB, ISTB(NB+1), INDB(LINDB), LINDB, IPIVP(LINDB), IPIVQ(LINDB), ISTR(LINDB+1), IDIAG(LINDB), M, MAXITN, ITN, LWORK, IFAIL
REAL (KIND=nag_wp) | TOL, RNORM
COMPLEX (KIND=nag_wp) | A(LA), B(N), X(N), WORK(LWORK)
CHARACTER(*) | METHOD

3 Description

F11DUF solves a complex sparse non-Hermitian linear system of equations
Ax=b,
using a preconditioned RGMRES (see Saad and Schultz (1986)), CGS (see Sonneveld (1989)), Bi-CGSTAB(ℓ) (see Van der Vorst (1989) and Sleijpen and Fokkema (1993)), or TFQMR (see Freund and Nachtigal (1991) and Freund (1993)) method.
F11DUF uses the incomplete (possibly overlapping) block LU factorization determined by F11DTF as the preconditioning matrix. A call to F11DUF must always be preceded by a call to F11DTF. Alternative preconditioners for the same storage scheme are available by calling F11DQF or F11DSF.
The matrix A, and the preconditioning matrix M, are represented in coordinate storage (CS) format (see Section 2.1.1 in the F11 Chapter Introduction) in the arrays A, IROW and ICOL, as returned from F11DTF. The array A holds the nonzero entries in these matrices, while IROW and ICOL hold the corresponding row and column indices.
F11DUF is a Black Box routine which calls F11BRF, F11BSF and F11BTF. If you wish to use an alternative storage scheme, preconditioner, or termination criterion, or require additional diagnostic information, you should call these underlying routines directly.

4 References

Freund R W (1993) A transpose-free quasi-minimal residual algorithm for non-Hermitian linear systems SIAM J. Sci. Comput. 14 470–482
Freund R W and Nachtigal N (1991) QMR: a Quasi-Minimal Residual Method for Non-Hermitian Linear Systems Numer. Math. 60 315–339
Saad Y and Schultz M (1986) GMRES: a generalized minimal residual algorithm for solving nonsymmetric linear systems SIAM J. Sci. Statist. Comput. 7 856–869
Sleijpen G L G and Fokkema D R (1993) BiCGSTABℓ for linear equations involving matrices with complex spectrum ETNA 1 11–32
Sonneveld P (1989) CGS, a fast Lanczos-type solver for nonsymmetric linear systems SIAM J. Sci. Statist. Comput. 10 36–52
Van der Vorst H (1989) Bi-CGSTAB, a fast and smoothly converging variant of Bi-CG for the solution of nonsymmetric linear systems SIAM J. Sci. Statist. Comput. 13 631–644

5 Arguments

1:   METHOD – CHARACTER(*)Input
On entry: specifies the iterative method to be used.
METHOD='RGMRES'
Restarted generalized minimum residual method.
METHOD='CGS'
Conjugate gradient squared method.
METHOD='BICGSTAB'
Bi-conjugate gradient stabilized (ℓ) method.
METHOD='TFQMR'
Transpose-free quasi-minimal residual method.
Constraint: METHOD='RGMRES', 'CGS', 'BICGSTAB' or 'TFQMR'.
2:   N – INTEGERInput
3:   NNZ – INTEGERInput
4:   A LA – COMPLEX (KIND=nag_wp) arrayInput
5:   LA – INTEGERInput
6:   IROW LA – INTEGER arrayInput
7:   ICOL LA – INTEGER arrayInput
8:   NB – INTEGERInput
9:   ISTB NB+1 – INTEGER arrayInput
10:   INDB LINDB – INTEGER arrayInput
11:   LINDB – INTEGERInput
12:   IPIVP LINDB – INTEGER arrayInput
13:   IPIVQ LINDB – INTEGER arrayInput
14:   ISTR LINDB+1 – INTEGER arrayInput
15:   IDIAG LINDB – INTEGER arrayInput
On entry: the values returned in arrays IROW, ICOL, IPIVP, IPIVQ, ISTR and IDIAG by a previous call to F11DTF.
The arrays ISTB, INDB and A together with the scalars N, NNZ, LA, NB and LINDB must be the same values that were supplied in the preceding call to F11DTF.
On entry: the values returned in arrays IROW, ICOL, IPIVP, IPIVQ, ISTR and IDIAG by a previous call to F11DTF.
The arrays ISTB, INDB and the scalars NB and LINDB must be the same values that were supplied in the preceding call to F11DTF.
16:   B N – COMPLEX (KIND=nag_wp) arrayInput
On entry: the right-hand side vector b.
17:   M – INTEGERInput
On entry: if METHOD='RGMRES', M is the dimension of the restart subspace.
If METHOD='BICGSTAB', M is the order ℓ of the polynomial Bi-CGSTAB method.
Otherwise, M is not referenced.
Constraints:
  • if METHOD='RGMRES', 0<M≤min N,50;
  • if METHOD='BICGSTAB', 0<M≤min N,10.
18:   TOL – REAL (KIND=nag_wp)Input
On entry: the required tolerance. Let xk denote the approximate solution at iteration k, and rk the corresponding residual. The algorithm is considered to have converged at iteration k if
rk∞≤τ×b∞+A∞xk∞.
If TOL≤0.0, τ=max⁡ε,n ε is used, where ε is the machine precision. Otherwise τ=max TOL,10 ε,n ε is used.
Constraint: TOL<1.0.
19:   MAXITN – INTEGERInput
On entry: the maximum number of iterations allowed.
Constraint: MAXITN≥1.
20:   X N – COMPLEX (KIND=nag_wp) arrayInput/Output
On entry: an initial approximation to the solution vector x.
On exit: an improved approximation to the solution vector x.
21:   RNORM – REAL (KIND=nag_wp)Output
On exit: the final value of the residual norm rk∞, where k is the output value of ITN.
22:   ITN – INTEGEROutput
On exit: the number of iterations carried out.
23:   WORK LWORK – COMPLEX (KIND=nag_wp) arrayWorkspace
24:   LWORK – INTEGERInput
On entry: the dimension of the array WORK as declared in the (sub)program from which F11DUF is called.
Constraints:
  • if METHOD='RGMRES', LWORK≥6×N+M×M+N+5+121;
  • if METHOD='CGS', LWORK≥10×N+120;
  • if METHOD='BICGSTAB', LWORK≥2×N×M+8×N+M×M+2+120;
  • if METHOD='TFQMR', LWORK≥13×N+120.
25:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, for b=value, ISTB b+1=value and ISTB b=value.
Constraint: ISTB b+1>ISTB b, for b=1,2,…,NB.
On entry, INDB value=value and N=value.
Constraint: 1≤INDB m≤N, for m=1,2,…,ISTB NB+1-1
On entry, ISTB 1=value.
Constraint: ISTB 1≥1.
On entry, LA=value and NNZ=value.
Constraint: LA≥2×NNZ.
On entry, LINDB=value, ISTB NB+1-1=value and NB=value.
Constraint: LINDB≥ISTB NB+1-1.
On entry, LWORK=value.
Constraint: LWORK≥value.
On entry, M=value and N=value.
Constraint: if METHOD='RGMRES', 1≤M≤min N,value.
If METHOD='BICGSTAB', 1≤M≤min N,value.
On entry, MAXITN=value.
Constraint: MAXITN≥1.
On entry, METHOD=value.
Constraint: METHOD='RGMRES', 'CGS' or 'BICGSTAB'.
On entry, N=value.
Constraint: N≥1.
On entry, NB=value and N=value.
Constraint: 1≤NB≤N.
On entry, NNZ=value.
Constraint: NNZ≥1.
On entry, NNZ=value and N=value.
Constraint: NNZ≤N 2.
On entry, TOL=value.
Constraint: TOL<1.0.
IFAIL=2
On entry, element value of A was out of order.
Check that A, IROW, ICOL, IPIVP, IPIVQ, ISTR and IDIAG have not been corrupted between calls to F11DTF and F11DUF.
On entry, ICOL value=value and N=value.
Constraint: 1≤ICOL i≤N, for i=1,2,…,NNZ.
Check that A, IROW, ICOL, IPIVP, IPIVQ, ISTR and IDIAG have not been corrupted between calls to F11DTF and F11DUF.
On entry, IROW value=value and N=value.
Constraint: 1≤IROW i≤N, for i=1,2,…,NNZ.
Check that A, IROW, ICOL, IPIVP, IPIVQ, ISTR and IDIAG have not been corrupted between calls to F11DTF and F11DUF.
On entry, location value of IROW,ICOL was a duplicate.
Check that A, IROW, ICOL, IPIVP, IPIVQ, ISTR and IDIAG have not been corrupted between calls to F11DTF and F11DUF.
IFAIL=3
The CS representation of the preconditioner is invalid.
Check that A, IROW, ICOL, IPIVP, IPIVQ, ISTR and IDIAG have not been corrupted between calls to F11DTF and F11DUF.
IFAIL=4
The required accuracy could not be obtained. However, a reasonable accuracy may have been achieved. You should check the output value of RNORM for acceptability. This error code usually implies that your problem has been fully and satisfactorily solved to within or close to the accuracy available on your system. Further iterations are unlikely to improve on this situation.
IFAIL=5
The solution has not converged after value iterations.
IFAIL=6
Algorithmic breakdown. A solution is returned, although it is possible that it is completely inaccurate.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

On successful termination, the final residual rk=b-A xk, where k=ITN, satisfies the termination criterion
rk∞≤τ×b∞+A∞xk∞.
The value of the final residual norm is returned in RNORM.

8 Parallelism and Performance

F11DUF is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
F11DUF makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The time taken by F11DUF for each iteration is roughly proportional to the value of NNZC returned from the preceding call to F11DTF.
The number of iterations required to achieve a prescribed accuracy cannot be easily determined a priori, as it can depend dramatically on the conditioning and spectrum of the preconditioned coefficient matrix A-=M-1 A.

10 Example

This example program reads in a sparse matrix A and a vector b. It calls F11DTF, with the array LFILL=0 and the array DTOL=0.0, to compute an overlapping incomplete LU factorization. This is then used as an additive Schwarz preconditioner on a call to F11DUF which uses the RGMRES method to solve Ax=b.

10.1 Program Text

Program Text (f11dufe.f90)

10.2 Program Data

Program Data (f11dufe.d)

10.3 Program Results

Program Results (f11dufe.r)

F11 Chapter Contents
F11 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F11DXF : NAG Library, Mark 26

F11 Chapter Contents
F11 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F11DXF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
▸▿ 9 Further Comments
9.1 Timing
9.2 Use of CHECK
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F11DXF computes the approximate solution of a complex, Hermitian or non-Hermitian, sparse system of linear equations applying a number of Jacobi iterations. It is expected that F11DXF will be used as a preconditioner for the iterative solution of complex sparse systems of equations.

2 Specification

SUBROUTINE F11DXF ( STORE, TRANS, INIT, NITER, N, NNZ, A, IROW, ICOL, CHECK, B, X, DIAG, WORK, IFAIL)
INTEGER | NITER, N, NNZ, IROW(NNZ), ICOL(NNZ), IFAIL
COMPLEX (KIND=nag_wp) | A(NNZ), B(N), X(N), DIAG(N), WORK(N)
CHARACTER(1) | STORE, TRANS, INIT, CHECK

3 Description

F11DXF computes the approximate solution of the complex sparse system of linear equations Ax=b using NITER iterations of the Jacobi algorithm (see also Golub and Van Loan (1996) and Young (1971)):
x k+1=xk+D-1 b-A xk (1)
where k=1,2,…,NITER and x 0=0.
F11DXF can be used both for non-Hermitian and Hermitian systems of equations. For Hermitian matrices, either all nonzero elements of the matrix A can be supplied using coordinate storage (CS), or only the nonzero elements of the lower triangle of A, using symmetric coordinate storage (SCS) (see the F11 Chapter Introduction).
It is expected that F11DXF will be used as a preconditioner for the iterative solution of complex sparse systems of equations, using either the suite comprising the routines F11GRF, F11GSF and F11GTF, for Hermitian systems, or the suite comprising the routines F11BRF, F11BSF and F11BTF, for non-Hermitian systems of equations.

4 References

Golub G H and Van Loan C F (1996) Matrix Computations (3rd Edition) Johns Hopkins University Press, Baltimore
Young D (1971) Iterative Solution of Large Linear Systems Academic Press, New York

5 Arguments

1:   STORE – CHARACTER(1)Input
On entry: specifies whether the matrix A is stored using symmetric coordinate storage (SCS) (applicable only to a Hermitian matrix A) or coordinate storage (CS) (applicable to both Hermitian and non-Hermitian matrices).
STORE='N'
The complete matrix A is stored in CS format.
STORE='S'
The lower triangle of the Hermitian matrix A is stored in SCS format.
Constraint: STORE='N' or 'S'.
2:   TRANS – CHARACTER(1)Input
On entry: if STORE='N', specifies whether the approximate solution of Ax=b or of AH x=b is required.
TRANS='N'
The approximate solution of Ax=b is calculated.
TRANS='T'
The approximate solution of AH x=b is calculated.
Suggested value: if the matrix A is Hermitian and stored in CS format, it is recommended that TRANS='N' for reasons of efficiency.
Constraint: TRANS='N' or 'T'.
3:   INIT – CHARACTER(1)Input
On entry: on first entry, INIT should be set to 'I', unless the diagonal elements of A are already stored in the array DIAG. If DIAG already contains the diagonal of A, it must be set to 'N'.
INIT='N'
DIAG must contain the diagonal of A.
INIT='I'
DIAG will store the diagonal of A on exit.
Suggested value: INIT='I' on first entry; INIT='N', subsequently, unless DIAG has been overwritten.
Constraint: INIT='N' or 'I'.
4:   NITER – INTEGERInput
On entry: the number of Jacobi iterations requested.
Constraint: NITER≥1.
5:   N – INTEGERInput
On entry: n, the order of the matrix A.
Constraint: N≥1.
6:   NNZ – INTEGERInput
On entry: if STORE='N', the number of nonzero elements in the matrix A.
If STORE='S', the number of nonzero elements in the lower triangle of the matrix A.
Constraints:
  • if STORE='N', 1≤NNZ≤N 2;
  • if STORE='S', 1≤NNZ≤N×N+1/2.
7:   A NNZ – COMPLEX (KIND=nag_wp) arrayInput
On entry: if STORE='N', the nonzero elements in the matrix A (CS format).
If STORE='S', the nonzero elements in the lower triangle of the matrix A (SCS format).
In both cases, the elements of either A or of its lower triangle must be ordered by increasing row index and by increasing column index within each row. Multiple entries for the same row and columns indices are not permitted. The routine F11ZNF or F11ZPF may be used to reorder the elements in this way for CS and SCS storage, respectively.
8:   IROW NNZ – INTEGER arrayInput
9:   ICOL NNZ – INTEGER arrayInput
On entry: if STORE='N', the row and column indices of the nonzero elements supplied in A.
If STORE='S', the row and column indices of the nonzero elements of the lower triangle of the matrix A supplied in A.
Constraints:
  • 1≤IROW i≤N, for i=1,2,…,NNZ;
  • if STORE='N', 1≤ICOL i≤N, for i=1,2,…,NNZ;
  • if STORE='S', 1≤ICOL i≤IROW i, for i=1,2,…,NNZ;
  • either IROW i-1<IROW i or both IROW i-1=IROW i and ICOL i-1<ICOL i, for i=2,3,…,NNZ.
10:   CHECK – CHARACTER(1)Input
On entry: specifies whether or not the CS or SCS representation of the matrix A should be checked.
CHECK='C'
Checks are carried out on the values of N, NNZ, IROW, ICOL; if INIT='N', DIAG is also checked.
CHECK='N'
None of these checks are carried out.
See also Section 9.2.
Constraint: CHECK='C' or 'N'.
11:   B N – COMPLEX (KIND=nag_wp) arrayInput
On entry: the right-hand side vector b.
12:   X N – COMPLEX (KIND=nag_wp) arrayOutput
On exit: the approximate solution vector xNITER.
13:   DIAG N – COMPLEX (KIND=nag_wp) arrayInput/Output
On entry: if INIT='N', the diagonal elements of A.
On exit: if INIT='N', unchanged on exit.
If INIT='I', the diagonal elements of A.
14:   WORK N – COMPLEX (KIND=nag_wp) arrayWorkspace
15:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, | STORE≠'N' or 'S',
or | TRANS≠'N' or 'T',
or | INIT≠'N' or 'I',
or | CHECK≠'C' or 'N',
or | NITER≤0.
IFAIL=2
On entry, | N<1,
or | NNZ<1,
or | NNZ>N 2, if STORE='N',
or | 1≤NNZ≤N N+1/2, if STORE='S'.
IFAIL=3
On entry, the arrays IROW and ICOL fail to satisfy the following constraints:
  • 1≤IROW i≤N and
    • if STORE='N' then 1≤ICOL i≤N, or
    • if STORE='S' then 1≤ICOL i≤IROW i, for i=1,2,…,NNZ.
  • IROW i-1<IROW i or IROW i-1=IROW i and ICOL i-1<ICOL i, for i=2,3,…,NNZ.
Therefore a nonzero element has been supplied which does not lie within the matrix A, is out of order, or has duplicate row and column indices. Call either F11ZAF or F11ZBF to reorder and sum or remove duplicates when STORE='N' or STORE='S', respectively.
IFAIL=4
On entry, INIT='N' and some diagonal elements of A stored in DIAG are zero.
IFAIL=5
On entry, INIT='I' and some diagonal elements of A are zero.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

In general, the Jacobi method cannot be used on its own to solve systems of linear equations. The rate of convergence is bound by its spectral properties (see, for example, Golub and Van Loan (1996)) and as a solver, the Jacobi method can only be applied to a limited set of matrices. One condition that guarantees convergence is strict diagonal dominance.
However, the Jacobi method can be used successfully as a preconditioner to a wider class of systems of equations. The Jacobi method has good vector/parallel properties, hence it can be applied very efficiently. Unfortunately, it is not possible to provide criteria which define the applicability of the Jacobi method as a preconditioner, and its usefulness must be judged for each case.

8 Parallelism and Performance

F11DXF is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
F11DXF makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

9.1 Timing

The time taken for a call to F11DXF is proportional to NITER×NNZ.

9.2 Use of CHECK

It is expected that a common use of F11DXF will be as preconditioner for the iterative solution of complex, Hermitian or non-Hermitian, linear systems. In this situation, F11DXF is likely to be called many times. In the interests of both reliability and efficiency, you are recommended to set CHECK='C' for the first of such calls, and to set CHECK='N' for all subsequent calls.

10 Example

This example solves the complex sparse non-Hermitian system of equations Ax=b iteratively using F11DXF as a preconditioner.

10.1 Program Text

Program Text (f11dxfe.f90)

10.2 Program Data

Program Data (f11dxfe.d)

10.3 Program Results

Program Results (f11dxfe.r)

F11 Chapter Contents
F11 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F11GDF : NAG Library, Mark 26

F11 Chapter Contents
F11 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F11GDF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F11GDF is a setup routine, the first in a suite of three routines for the iterative solution of a symmetric system of simultaneous linear equations. F11GDF must be called before the iterative solver, F11GEF. The third routine in the suite, F11GFF, can be used to return additional information about the computation.
These three routines are suitable for the solution of large sparse symmetric systems of equations.

2 Specification

SUBROUTINE F11GDF ( METHOD, PRECON, SIGCMP, NORM, WEIGHT, ITERM, N, TOL, MAXITN, ANORM, SIGMAX, SIGTOL, MAXITS, MONIT, LWREQ, WORK, LWORK, IFAIL)
INTEGER | ITERM, N, MAXITN, MAXITS, MONIT, LWREQ, LWORK, IFAIL
REAL (KIND=nag_wp) | TOL, ANORM, SIGMAX, SIGTOL, WORK(LWORK)
CHARACTER(*) | METHOD
CHARACTER(1) | PRECON, SIGCMP, NORM, WEIGHT

3 Description

The suite consisting of the routines F11GDF, F11GEF and F11GFF is designed to solve the symmetric system of simultaneous linear equations Ax=b of order n, where n is large and the matrix of the coefficients A is sparse.
F11GDF is a setup routine which must be called before F11GEF, the iterative solver. The third routine in the suite, F11GFF can be used to return additional information about the computation. One of the following methods can be used:
1. | Conjugate Gradient Method (CG) For this method (see Hestenes and Stiefel (1952), Golub and Van Loan (1996), Barrett et al. (1994) and Dias da Cunha and Hopkins (1994)), the matrix A should ideally be positive definite. The application of the Conjugate Gradient method to indefinite matrices may lead to failure or to lack of convergence.
2. | Lanczos Method (SYMMLQ) This method, based upon the algorithm SYMMLQ (see Paige and Saunders (1975) and Barrett et al. (1994)), is suitable for both positive definite and indefinite matrices. It is more robust than the Conjugate Gradient method but less efficient when A is positive definite.
3. | Minimum Residual Method (MINRES) This method may be used when the matrix is indefinite. It seeks to reduce the norm of the residual at each iteration and often takes fewer iterations than the other methods. It does however require slightly more memory.
The CG and SYMMLQ methods start from the residual r 0=b-A x 0, where x 0 is an initial estimate for the solution (often x 0=0), and generate an orthogonal basis for the Krylov subspace span Ak r 0, for k=0,1,…, by means of three-term recurrence relations (see Golub and Van Loan (1996)). A sequence of symmetric tridiagonal matrices Tk is also generated. Here and in the following, the index k denotes the iteration count. The resulting symmetric tridiagonal systems of equations are usually more easily solved than the original problem. A sequence of solution iterates xk is thus generated such that the sequence of the norms of the residuals rk converges to a required tolerance. Note that, in general, the convergence is not monotonic.
In exact arithmetic, after n iterations, this process is equivalent to an orthogonal reduction of A to symmetric tridiagonal form, Tn=QT AQ; the solution xn would thus achieve exact convergence. In finite-precision arithmetic, cancellation and round-off errors accumulate causing loss of orthogonality. These methods must therefore be viewed as genuinely iterative methods, able to converge to a solution within a prescribed tolerance.
The orthogonal basis is not formed explicitly in either method. The basic difference between the Conjugate Gradient and Lanczos methods lies in the method of solution of the resulting symmetric tridiagonal systems of equations: the conjugate gradient method is equivalent to carrying out an LD LT (Cholesky) factorization whereas the Lanczos method (SYMMLQ) uses an LQ factorization.
Faster convergence for all the methods can be achieved using a preconditioner (see Golub and Van Loan (1996) and Barrett et al. (1994)). A preconditioner maps the original system of equations onto a different system, say
A-x-=b-, (1)
with, hopefully, better characteristics with respect to its speed of convergence: for example, the condition number of the matrix of the coefficients can be improved or eigenvalues in its spectrum can be made to coalesce. An orthogonal basis for the Krylov subspace span A-k r-0, for k=0,1,…, is generated and the solution proceeds as outlined above. The algorithms used are such that the solution and residual iterates of the original system are produced, not their preconditioned counterparts. Note that an unsuitable preconditioner or no preconditioning at all may result in a very slow rate, or lack, of convergence. However, preconditioning involves a trade-off between the reduction in the number of iterations required for convergence and the additional computational costs per iteration. Also, setting up a preconditioner may involve non-negligible overheads.
A preconditioner must be symmetric and positive definite, i.e., representable by M=E ET, where M is nonsingular, and such that A-=E-1 A E-T∼In in (1), where In is the identity matrix of order n. Also, we can define r-=E-1 r and x-=ET x. These are formal definitions, used only in the design of the algorithms; in practice, only the means to compute the matrix-vector products v=Au and to solve the preconditioning equations Mv=u are required, that is, explicit information about M, E or their inverses is not required at any stage.
The first termination criterion
rk p ≤ τ b p + A p × xk p (2)
is available for both conjugate gradient and Lanczos (SYMMLQ) methods. In (2), p=1,∞​ or ​2 and τ denotes a user-specified tolerance subject to max 10,n ε≤τ<1, where ε is the machine precision. Facilities are provided for the estimation of the norm of the matrix of the coefficients A 1=A∞, when this is not known in advance, used in (2), by applying Higham's method (see Higham (1988)). Note that A 2 cannot be estimated internally. This criterion uses an error bound derived from backward error analysis to ensure that the computed solution is the exact solution of a problem as close to the original as the termination tolerance requires. Termination criteria employing bounds derived from forward error analysis could be used, but any such criteria would require information about the condition number κ A which is not easily obtainable.
The second termination criterion
r-k 2 ≤ τ max 1.0, b 2 / r 0 2 r-0 2 + σ 1 A- × Δ x-k 2 (3)
is available only for the Lanczos method (SYMMLQ). In (3), σ 1 A-=A-2 is the largest singular value of the (preconditioned) iteration matrix A-. This termination criterion monitors the progress of the solution of the preconditioned system of equations and is less expensive to apply than criterion (2). When σ 1 A- is not supplied, facilities are provided for its estimation by σ 1 A-∼maxk σ 1 Tk. The interlacing property σ 1 T k-1≤σ 1 Tk and Gerschgorin's theorem provide lower and upper bounds from which σ 1 Tk can be easily computed by bisection. Alternatively, the less expensive estimate σ 1 A-∼maxk Tk 1 can be used, where σ 1 A-≤Tk 1 by Gerschgorin's theorem. Note that only order of magnitude estimates are required by the termination criterion.
Termination criterion (2) is the recommended choice, despite its (small) additional costs per iteration when using the Lanczos method (SYMMLQ). Also, if the norm of the initial estimate is much larger than the norm of the solution, that is, if x 0≫x, a dramatic loss of significant digits could result in complete lack of convergence. The use of criterion (2) will enable the detection of such a situation, and the iteration will be restarted at a suitable point. No such restart facilities are provided for criterion (3).
Optionally, a vector w of user-specified weights can be used in the computation of the vector norms in termination criterion (2), i.e., v p w=v w p, where v w i=wi vi, for i=1,2,…,n. Note that the use of weights increases the computational costs.
The MINRES algorithm terminates when the norm of the residual of the preconditioned system F, F 2≤τ× A-2× xk 2 , where A- is the preconditioned matrix.
The termination criteria discussed are not robust in the presence of a non-trivial nullspace of A, i.e., when A is singular. It is then possible for xk p to grow without limit, spuriously satisfying the termination criterion. If singularity is suspected, more robust routines can be found in Chapter E04.
The sequence of calls to the routines comprising the suite is enforced: first, the setup routine F11GDF must be called, followed by the solver F11GEF. The diagnostic routine F11GFF can be called either when F11GEF is carrying out a monitoring step or after F11GEF has completed its tasks. Incorrect sequencing will raise an error condition.

4 References

Barrett R, Berry M, Chan T F, Demmel J, Donato J, Dongarra J, Eijkhout V, Pozo R, Romine C and Van der Vorst H (1994) Templates for the Solution of Linear Systems: Building Blocks for Iterative Methods SIAM, Philadelphia
Dias da Cunha R and Hopkins T (1994) PIM 1.1 — the parallel iterative method package for systems of linear equations user's guide — Fortran 77 version Technical Report Computing Laboratory, University of Kent at Canterbury, Kent, UK
Golub G H and Van Loan C F (1996) Matrix Computations (3rd Edition) Johns Hopkins University Press, Baltimore
Hestenes M and Stiefel E (1952) Methods of conjugate gradients for solving linear systems J. Res. Nat. Bur. Stand. 49 409–436
Higham N J (1988) FORTRAN codes for estimating the one-norm of a real or complex matrix, with applications to condition estimation ACM Trans. Math. Software 14 381–396
Paige C C and Saunders M A (1975) Solution of sparse indefinite systems of linear equations SIAM J. Numer. Anal. 12 617–629

5 Arguments

1:   METHOD – CHARACTER(*)Input
On entry: the iterative method to be used.
METHOD='CG'
Conjugate gradient method (CG).
METHOD='SYMMLQ'
Lanczos method (SYMMLQ).
METHOD='MINRES'
Minimum residual method (MINRES).
Constraint: METHOD='CG', 'SYMMLQ' or 'MINRES'.
2:   PRECON – CHARACTER(1)Input
On entry: determines whether preconditioning is used.
PRECON='N'
No preconditioning.
PRECON='P'
Preconditioning.
Constraint: PRECON='N' or 'P'.
3:   SIGCMP – CHARACTER(1)Input
On entry: determines whether an estimate of σ 1 A-=E-1 A E-T 2, the largest singular value of the preconditioned matrix of the coefficients, is to be computed using the bisection method on the sequence of tridiagonal matrices Tk generated during the iteration. Note that A-=A when a preconditioner is not used.
If SIGMAX>0.0 (see below), i.e., when σ 1 A- is supplied, the value of SIGCMP is ignored.
SIGCMP='S'
σ 1 A- is to be computed using the bisection method.
SIGCMP='N'
The bisection method is not used.
If the termination criterion (3) is used, requiring σ 1 A-, an inexpensive estimate is computed and used (see Section 3).
It is not used if METHOD='MINRES'.
Suggested value: SIGCMP='N'.
Constraint: SIGCMP='S' or 'N'.
4:   NORM – CHARACTER(1)Input
On entry: if METHOD='CG' or 'SYMMLQ', NORM defines the matrix and vector norm to be used in the termination criteria.
NORM='1'
Use the l 1 norm.
NORM='I'
Use the l∞ norm.
NORM='2'
Use the l 2 norm.
It has no effect if METHOD='MINRES'.
Suggested values:
  • if ITERM=1, NORM='I';
  • if ITERM=2, NORM='2'.
Constraints:
  • if ITERM=1, NORM='1', 'I' or '2';
  • if ITERM=2, NORM='2'.
5:   WEIGHT – CHARACTER(1)Input
On entry: specifies whether a vector w of user-supplied weights is to be used in the vector norms used in the computation of termination criterion (2) (ITERM=1): v p w=v w p, where vi w =wi vi, for i=1,2,…,n. The suffix p=1,2,∞ denotes the vector norm used, as specified by the argument NORM. Note that weights cannot be used when ITERM=2, i.e., when criterion (3) is used.
WEIGHT='W'
User-supplied weights are to be used and must be supplied on initial entry to F11GEF.
WEIGHT='N'
All weights are implicitly set equal to one. Weights do not need to be supplied on initial entry to F11GEF.
It has no effect if METHOD='MINRES'.
Suggested value: WEIGHT='N'.
Constraints:
  • if ITERM=1, WEIGHT='W' or 'N';
  • if ITERM=2, WEIGHT='N'.
6:   ITERM – INTEGERInput
On entry: defines the termination criterion to be used.
ITERM=1
Use the termination criterion defined in (2) (both conjugate gradient and Lanczos (SYMMLQ) methods).
ITERM=2
Use the termination criterion defined in (3) (Lanczos method (SYMMLQ) only).
It has no effect if METHOD='MINRES'.
Suggested value: ITERM=1.
Constraints:
  • if METHOD='CG', ITERM=1;
  • if METHOD='SYMMLQ', ITERM=1 or 2.
7:   N – INTEGERInput
On entry: n, the order of the matrix A.
Constraint: N>0.
8:   TOL – REAL (KIND=nag_wp)Input
On entry: the tolerance τ for the termination criterion.
If TOL≤0.0, τ=max ε,n ε is used, where ε is the machine precision.
Otherwise τ=max TOL,10 ε,n ε is used.
Constraint: TOL<1.0.
9:   MAXITN – INTEGERInput
On entry: the maximum number of iterations.
Constraint: MAXITN>0.
10:   ANORM – REAL (KIND=nag_wp)Input
On entry: if ANORM>0.0, the value of A p to be used in the termination criterion (2) (ITERM=1).
If ANORM≤0.0, ITERM=1 and NORM='1' or 'I', then A 1=A∞ is estimated internally by F11GEF.
If ITERM=2, then ANORM is not referenced.
It has no effect if METHOD='MINRES'.
Constraint: if ITERM=1 and NORM=2, ANORM>0.0.
11:   SIGMAX – REAL (KIND=nag_wp)Input
On entry: if SIGMAX>0.0, the value of σ 1 A-=E-1 A E-T 2.
If SIGMAX≤0.0, σ 1 A- is estimated by F11GEF when either SIGCMP='S' or termination criterion (3) (ITERM=2) is employed, though it will be used only in the latter case.
Otherwise, or if METHOD='MINRES', SIGMAX is not referenced.
12:   SIGTOL – REAL (KIND=nag_wp)Input
On entry: the tolerance used in assessing the convergence of the estimate of σ 1 A-=A-2 when the bisection method is used.
If SIGTOL≤0.0, the default value SIGTOL=0.01 is used. The actual value used is max SIGTOL,ε.
If SIGCMP='N' or SIGMAX>0.0, then SIGTOL is not referenced.
It has no effect if METHOD='MINRES'.
Suggested value: SIGTOL=0.01 should be sufficient in most cases.
Constraint: if SIGCMP='S' and SIGMAX≤0.0, SIGTOL<1.0.
13:   MAXITS – INTEGERInput
On entry: the maximum iteration number k=MAXITS for which σ 1 Tk is computed by bisection (see also Section 3). If SIGCMP='N' or SIGMAX>0.0, or if METHOD='MINRES', then MAXITS is not referenced.
Suggested value: MAXITS=min 10,n when SIGTOL is of the order of its default value 0.01.
Constraint: if SIGCMP='S' and SIGMAX≤0.0, 1≤MAXITS≤MAXITN.
14:   MONIT – INTEGERInput
On entry: if MONIT>0, the frequency at which a monitoring step is executed by F11GEF: the current solution and residual iterates will be returned by F11GEF and a call to F11GFF made possible every MONIT iterations, starting from the (MONIT)th. Otherwise, no monitoring takes place.
There are some additional computational costs involved in monitoring the solution and residual vectors when the Lanczos method (SYMMLQ) is used.
Constraint: MONIT≤MAXITN.
15:   LWREQ – INTEGEROutput
On exit: the minimum amount of workspace required by F11GEF. (See also Section 5 in F11GEF.)
16:   WORK LWORK – REAL (KIND=nag_wp) arrayCommunication Array
On exit: the array WORK is initialized by F11GDF. It must not be modified before calling the next routine in the suite, namely F11GEF.
17:   LWORK – INTEGERInput
On entry: the dimension of the array WORK as declared in the (sub)program from which F11GDF is called.
Constraint: LWORK≥120.
Note: although the minimum value of LWORK ensures the correct functioning of F11GDF, a larger value is required by the other routines in the suite, namely F11GEF and F11GFF. The required value is as follows:
Method | Requirements
CG | LWORK=120+5 n+p.
SYMMLQ | LWORK=120+6 n+p,
MINRES | LWORK=120+9 n,
where
  • p=2*MAXITS+1, when an estimate of σ 1 A (SIGMAX) is computed;
  • p=0, otherwise.
18:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=-i
On entry, the ith argument had an illegal value.
IFAIL=1
F11GDF has been called out of sequence.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

Not applicable.

8 Parallelism and Performance

F11GDF is not threaded in any implementation.

9 Further Comments

When σ 1 A- is not supplied (SIGMAX≤0.0) but it is required, it is estimated by F11GEF using either of the two methods described in Section 3, as specified by the argument SIGCMP. In particular, if SIGCMP='S', then the computation of σ 1 A- is deemed to have converged when the differences between three successive values of σ 1 Tk differ, in a relative sense, by less than the tolerance SIGTOL, i.e., when
max σ 1 k-σ 1 k-1 σ 1 k , ​ σ 1 k-σ 1 k-2 σ 1 k ≤SIGTOL.
The computation of σ 1 A- is also terminated when the iteration count exceeds the maximum value allowed, i.e., k≥MAXITS.
Bisection is increasingly expensive with increasing iteration count. A reasonably large value of SIGTOL, of the order of the suggested value, is recommended and an excessive value of MAXITS should be avoided. Under these conditions, σ 1 A- usually converges within very few iterations.

10 Example

This example solves a symmetric system of simultaneous linear equations using the conjugate gradient method, where the matrix of the coefficients A, has a random sparsity pattern. An incomplete Cholesky preconditioner is used (F11JAF and F11JBF).

10.1 Program Text

Program Text (f11gdfe.f90)

10.2 Program Data

Program Data (f11gdfe.d)

10.3 Program Results

Program Results (f11gdfe.r)

F11 Chapter Contents
F11 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F11GEF : NAG Library, Mark 26

F11 Chapter Contents
F11 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F11GEF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
10 Example

1 Purpose

F11GEF is an iterative solver for a symmetric system of simultaneous linear equations; F11GEF is the second in a suite of three routines, where the first routine, F11GDF, must be called prior to F11GEF to set up the suite, and the third routine in the suite, F11GFF, can be used to return additional information about the computation.
These three routines are suitable for the solution of large sparse symmetric systems of equations.

2 Specification

SUBROUTINE F11GEF ( IREVCM, U, V, WGT, WORK, LWORK, IFAIL)
INTEGER | IREVCM, LWORK, IFAIL
REAL (KIND=nag_wp) | U(*), V(*), WGT(*), WORK(LWORK)

3 Description

F11GEF solves the symmetric system of linear simultaneous equations Ax=b using the preconditioned conjugate gradient method (see Hestenes and Stiefel (1952), Golub and Van Loan (1996), Barrett et al. (1994) and Dias da Cunha and Hopkins (1994)), a preconditioned Lanczos method based upon the algorithm SYMMLQ (see Paige and Saunders (1975) and Barrett et al. (1994)), or the MINRES algorithm (see Paige and Saunders (1975)).
For a general description of the methods employed you are referred to Section 3 in F11GDF.
F11GEF can solve the system after the first routine in the suite, F11GDF, has been called to initialize the computation and specify the method of solution. The third routine in the suite, F11GFF, can be used to return additional information generated by the computation during monitoring steps and after F11GEF has completed its tasks.
F11GEF uses reverse communication, i.e., F11GEF returns repeatedly to the calling program with the argument IREVCM (see Section 5) set to specified values which require the calling program to carry out a specific task: either to compute the matrix-vector product v=Au; to solve the preconditioning equation Mv=u; to notify the completion of the computation; or, to allow the calling program to monitor the solution. Through the argument IREVCM the calling program can cause immediate or tidy termination of the execution. On final exit, the last iterates of the solution and of the residual vectors of the original system of equations are returned.
Reverse communication has the following advantages.
1. | Maximum flexibility in the representation and storage of sparse matrices: all matrix operations are performed outside the solver routine, thereby avoiding the need for a complicated interface with enough flexibility to cope with all types of storage schemes and sparsity patterns. This applies also to preconditioners.
2. | Enhanced user interaction: you can closely monitor the solution and tidy or immediate termination can be requested. This is useful, for example, when alternative termination criteria are to be employed or in case of failure of the external routines used to perform matrix operations.

4 References

Barrett R, Berry M, Chan T F, Demmel J, Donato J, Dongarra J, Eijkhout V, Pozo R, Romine C and Van der Vorst H (1994) Templates for the Solution of Linear Systems: Building Blocks for Iterative Methods SIAM, Philadelphia
Dias da Cunha R and Hopkins T (1994) PIM 1.1 — the parallel iterative method package for systems of linear equations user's guide — Fortran 77 version Technical Report Computing Laboratory, University of Kent at Canterbury, Kent, UK
Golub G H and Van Loan C F (1996) Matrix Computations (3rd Edition) Johns Hopkins University Press, Baltimore
Hestenes M and Stiefel E (1952) Methods of conjugate gradients for solving linear systems J. Res. Nat. Bur. Stand. 49 409–436
Higham N J (1988) FORTRAN codes for estimating the one-norm of a real or complex matrix, with applications to condition estimation ACM Trans. Math. Software 14 381–396
Paige C C and Saunders M A (1975) Solution of sparse indefinite systems of linear equations SIAM J. Numer. Anal. 12 617–629

5 Arguments

Note: this routine uses reverse communication. Its use involves an initial entry, intermediate exits and re-entries, and a final exit, as indicated by the argument IREVCM. Between intermediate exits and re-entries, all arguments other than IREVCM and V must remain unchanged.
1:   IREVCM – INTEGERInput/Output
On initial entry: IREVCM=0, otherwise an error condition will be raised.
On intermediate re-entry: must either be unchanged from its previous exit value, or can have one of the following values.
IREVCM=5
Tidy termination: the computation will terminate at the end of the current iteration. Further reverse communication exits may occur depending on when the termination request is issued. F11GEF will then return with the termination code IREVCM=4. Note that before calling F11GEF with IREVCM=5 the calling program must have performed the tasks required by the value of IREVCM returned by the previous call to F11GEF, otherwise subsequently returned values may be invalid.
IREVCM=6
Immediate termination: F11GEF will return immediately with termination code IREVCM=4 and with any useful information available. This includes the last iterate of the solution and, for conjugate gradient only, the last iterate of the residual vector. The residual vector is generally not available when the Lanczos method (SYMMLQ) is used. F11GEF will then return with the termination code IREVCM=4.
Immediate termination may be useful, for example, when errors are detected during matrix-vector multiplication or during the solution of the preconditioning equation.
Changing IREVCM to any other value between calls will result in an error.
On intermediate exit: has the following meanings.
IREVCM=1
The calling program must compute the matrix-vector product v=Au, where u and v are stored in U and V, respectively.
IREVCM=2
The calling program must solve the preconditioning equation Mv=u, where u and v are stored in U and V, respectively.
IREVCM=3
Monitoring step: the solution and residual at the current iteration are returned in the arrays U and V, respectively. No action by the calling program is required. To return additional information F11GFF can be called at this step.
On final exit: if IREVCM=4, F11GEF has completed its tasks. The value of IFAIL determines whether the iteration has been successfully completed, errors have been detected or the calling program has requested termination.
Constraint: on initial entry, IREVCM=0; on re-entry, either IREVCM must remain unchanged or be reset to IREVCM=5 or 6.
2:   U* – REAL (KIND=nag_wp) arrayInput/Output
Note: the dimension of the array U must be at least n.
On initial entry: an initial estimate, x 0, of the solution of the system of equations Ax=b.
On intermediate re-entry: must remain unchanged.
On intermediate exit: the returned value of IREVCM determines the contents of U in the following way.
If IREVCM=1 or 2, U holds the vector u on which the operation specified by IREVCM is to be carried out.
If IREVCM=3, U holds the current iterate of the solution vector.
On final exit: if IFAIL=3 or -i, the array U is unchanged from the initial entry to F11GEF. If IFAIL=1, the array U is unchanged from the last entry to F11GEF. Otherwise, U holds the last iterate of the solution of the system of equations, for all returned values of IFAIL.
3:   V* – REAL (KIND=nag_wp) arrayInput/Output
Note: the dimension of the array V must be at least n.
On initial entry: the right-hand side b of the system of equations Ax=b.
On intermediate re-entry: the returned value of IREVCM determines the contents of V in the following way.
If IREVCM=1 or 2, V must store the vector v, the result of the operation specified by the value of IREVCM returned by the previous call to F11GEF.
If IREVCM=3, V must remain unchanged.
On intermediate exit: if IREVCM=3, V holds the current iterate of the residual vector. Note that this is an approximation to the true residual vector. Otherwise, it does not contain any useful information.
On final exit: if IFAIL=3 or -i, the array V is unchanged from the last entry to F11GEF. If IFAIL=1, the array V is unchanged from the initial entry to F11GEF. If IFAIL=0 or 2, the array V contains the true residual vector of the system of equations (see also Section 6). Otherwise, V stores the last iterate of the residual vector unless the Lanczos method (SYMMLQ) was used and IFAIL≥5, in which case V is set to 0.0.
4:   WGT* – REAL (KIND=nag_wp) arrayInput
Note: the dimension of the array WGT must be at least max 1,n.
On entry: the user-supplied weights, if these are to be used in the computation of the vector norms in the termination criterion (see Sections 3 and 5 in F11GDF).
Weights are NOT used in the MINRES algorithm.
Constraint: if weights are to be used, at least one element of WGT must be nonzero.
5:   WORK LWORK – REAL (KIND=nag_wp) arrayCommunication Array
On initial entry: the array WORK as returned by F11GDF (see also Section 5 in F11GDF).
On intermediate re-entry: must remain unchanged.
6:   LWORK – INTEGERInput
On initial entry: the dimension of the array WORK as declared in the (sub)program from which F11GEF is called (see also Section 3 in F11GDF). The required amount of workspace is as follows:
Method | Requirements
CG | LWORK=120+5 n+p.
SYMMLQ | LWORK=120+6 n+p,
MINRES | LWORK=120+9 n,
where
  • p=2*MAXITS+1, when an estimate of σ 1 A (SIGMAX) is computed;
  • p=0, otherwise.
Constraint: LWORK≥LWREQ, where LWREQ is returned by F11GDF.
7:   IFAIL – INTEGERInput/Output
On initial entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, because for this routine the values of the output arguments may be useful even if IFAIL≠0 on exit, the recommended value is -1. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On intermediate exit: the value of IFAIL is meaningless and should be ignored.
On final exit: (i.e., when IREVCM=4) IFAIL=0, unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
F11GEF has already completed its tasks. You need to set a new problem.
IFAIL=2
The required accuracy could not be obtained. However, a reasonable accuracy may have been achieved.
User-requested termination: the required accuracy could not be obtained. However, a reasonable accuracy may have been achieved.
IFAIL=3
Either F11GDF was not called before calling this routine or it has returned an error.
IFAIL=4
User-requested tidy termination. The solution has not converged after value iterations.
IFAIL=5
The solution has not converged after value iterations.
IFAIL=6
The preconditioner appears not to be positive definite. The computation cannot continue.
IFAIL=7
The matrix of the coefficients A appears not to be positive definite. The computation cannot continue.
IFAIL=8
User-requested immediate termination.
IFAIL=9
The matrix of the coefficients A appears to be singular. The computation cannot continue.
IFAIL=10
The weights in array WGT are all zero.
IFAIL=-1
On initial entry, IREVCM=value.
Constraint: IREVCM=0.
On intermediate re-entry, IREVCM=value.
Constraint: either IREVCM must be unchanged from its previous exit value or IREVCM=5 or 6.
IFAIL=-6
On entry, LWORK=value.
Constraint: LWORK≥LWREQ, where LWREQ is returned by F11GDF.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

On completion, i.e., IREVCM=4 on exit, the arrays U and V will return the solution and residual vectors, xk and rk=b-A xk, respectively, at the kth iteration, the last iteration performed, unless an immediate termination was requested and the Lanczos method (SYMMLQ) was used.
On successful completion, the termination criterion is satisfied to within the user-specified tolerance, as described in Section 3 in F11GDF. The computed values of the left- and right-hand sides of the termination criterion selected can be obtained by a call to F11GFF.

8 Parallelism and Performance

F11GEF is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
F11GEF makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The number of operations carried out by F11GEF for each iteration is likely to be principally determined by the computation of the matrix-vector products v=Au and by the solution of the preconditioning equation Mv=u in the calling program. Each of these operations is carried out once every iteration.
The number of the remaining operations in F11GEF for each iteration is approximately proportional to n. Note that the Lanczos method (SYMMLQ) requires a slightly larger number of operations than the conjugate gradient method.
The number of iterations required to achieve a prescribed accuracy cannot be easily determined at the onset, as it can depend dramatically on the conditioning and spectrum of the preconditioned matrix of the coefficients A-=E-1 A E-T.
Additional matrix-vector products are required for the computation of A 1=A∞, when this has not been supplied to F11GDF and is required by the termination criterion employed.
The number of operations required to compute σ 1 A- is negligible for reasonable values of SIGTOL and MAXITS (see Sections 5 and 9 in F11GDF).
If the termination criterion rk p ≤ τ b p+A p × xk p is used (see Section 3 in F11GDF) and x 0≫xk, so that because of loss of significant digits the required accuracy could not be obtained, the iteration is restarted automatically at some suitable point: F11GEF sets x 0=xk and the computation begins again. For particularly badly scaled problems, more than one restart may be necessary. Naturally, restarting adds to computational costs: it is recommended that the iteration should start from a value x 0 which is as close to the true solution x~ as can be estimated. Otherwise, the iteration should start from x 0=0.

10 Example

See Section 10 in F11GDF.
F11 Chapter Contents
F11 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F11GFF : NAG Library, Mark 26

F11 Chapter Contents
F11 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F11GFF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
10 Example

1 Purpose

F11GFF is the third in a suite of three routines for the iterative solution of a symmetric system of simultaneous linear equations (see Golub and Van Loan (1996)). F11GFF returns information about the computations during an iteration and/or after this has been completed. The first routine of the suite, F11GDF, is a setup routine, the second routine, F11GEF is the proper iterative solver.
These three routines are suitable for the solution of large sparse symmetric systems of equations.

2 Specification

SUBROUTINE F11GFF ( ITN, STPLHS, STPRHS, ANORM, SIGMAX, ITS, SIGERR, WORK, LWORK, IFAIL)
INTEGER | ITN, ITS, LWORK, IFAIL
REAL (KIND=nag_wp) | STPLHS, STPRHS, ANORM, SIGMAX, SIGERR, WORK(LWORK)

3 Description

F11GFF returns information about the solution process. It can be called both during a monitoring step of the solver F11GEF, or after this solver has completed its tasks. Calling F11GFF at any other time will result in an error condition being raised.
For further information you should read the documentation for F11GDF and F11GEF.

4 References

Golub G H and Van Loan C F (1996) Matrix Computations (3rd Edition) Johns Hopkins University Press, Baltimore

5 Arguments

1:   ITN – INTEGEROutput
On exit: the number of iterations carried out by F11GEF.
2:   STPLHS – REAL (KIND=nag_wp)Output
On exit: the current value of the left-hand side of the termination criterion used by F11GEF.
3:   STPRHS – REAL (KIND=nag_wp)Output
On exit: the current value of the right-hand side of the termination criterion used by F11GEF.
4:   ANORM – REAL (KIND=nag_wp)Output
On exit: for CG and SYMMLQ methods, the norm A 1=A∞ when either it has been supplied to F11GDF or it has been estimated by F11GEF (see also Sections 3 and 5 in F11GDF). Otherwise, ANORM=0.0 is returned.
For MINRES method, an estimate of the infinity norm of the preconditioned matrix operator.
5:   SIGMAX – REAL (KIND=nag_wp)Output
On exit: for CG and SYMMLQ methods, the current estimate of the largest singular value σ 1 A- of the preconditioned iteration matrix A-=E-1 A E-T, when either it has been supplied to F11GDF or it has been estimated by F11GEF (see also Sections 3 and 5 in F11GDF). Note that if ITS<ITN then SIGMAX contains the final estimate. If, on final exit from F11GEF, ITS=ITN, then the estimation of σ 1 A- may have not converged; in this case you should look at the value returned in SIGERR. Otherwise, SIGMAX=0.0 is returned.
For MINRES method, an estimate of the final transformed residual.
6:   ITS – INTEGEROutput
On exit: for CG and SYMMLQ methods, the number of iterations employed so far in the computation of the estimate of σ 1 A-, the largest singular value of the preconditioned matrix A-=E-1 A E-T, when σ 1 A- has been estimated by F11GEF using the bisection method (see also Sections 3, 5 and 9 in F11GDF). Otherwise, ITS=0 is returned.
7:   SIGERR – REAL (KIND=nag_wp)Output
On exit: for CG and SYMMLQ methods, if σ 1 A- has been estimated by F11GEF using bisection,
SIGERR=max σ 1 k-σ 1 k-1 σ 1 k,σ 1 k-σ 1 k-2 σ 1 k ,
where k=ITS denotes the iteration number. The estimation has converged if SIGERR≤SIGTOL where SIGTOL is an input argument to F11GDF. Otherwise, SIGERR=0.0 is returned.
For MINRES method, an estimate of the condition number of the preconditioned matrix.
8:   WORK LWORK – REAL (KIND=nag_wp) arrayCommunication Array
On entry: the array WORK as returned by F11GEF (see also Section 3 in F11GEF).
9:   LWORK – INTEGERInput
On entry: the dimension of the array WORK as declared in the (sub)program from which F11GFF is called (see also Section 5 in F11GDF).
Constraint: LWORK≥120.
Note: although the minimum value of LWORK ensures the correct functioning of F11GFF, a larger value is required by the iterative solver F11GEF (see also Section 5 in F11GDF).
10:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=-i
On entry, the ith argument had an illegal value.
IFAIL=1
F11GFF has been called out of sequence. For example, the last call to F11GEF did not return IREVCM=3 or 4.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

Not applicable.

8 Parallelism and Performance

F11GFF is not threaded in any implementation.

9 Further Comments

None.

10 Example

See Section 10 in F11GDF.
F11 Chapter Contents
F11 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F11GRF : NAG Library, Mark 26

F11 Chapter Contents
F11 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F11GRF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F11GRF is a setup routine, the first in a suite of three routines for the iterative solution of a complex Hermitian system of simultaneous linear equations. F11GRF must be called before F11GSF, the iterative solver. The third routine in the suite, F11GTF, can be used to return additional information about the computation.
These three routines are suitable for the solution of large sparse complex Hermitian systems of equations.

2 Specification

SUBROUTINE F11GRF ( METHOD, PRECON, SIGCMP, NORM, WEIGHT, ITERM, N, TOL, MAXITN, ANORM, SIGMAX, SIGTOL, MAXITS, MONIT, LWREQ, WORK, LWORK, IFAIL)
INTEGER | ITERM, N, MAXITN, MAXITS, MONIT, LWREQ, LWORK, IFAIL
REAL (KIND=nag_wp) | TOL, ANORM, SIGMAX, SIGTOL
COMPLEX (KIND=nag_wp) | WORK(LWORK)
CHARACTER(*) | METHOD
CHARACTER(1) | PRECON, SIGCMP, NORM, WEIGHT

3 Description

The suite consisting of the routines F11GRF, F11GSF and F11GTF is designed to solve the complex Hermitian system of simultaneous linear equations Ax=b of order n, where n is large and the matrix of the coefficients A is sparse.
F11GRF is a setup routine which must be called before the iterative solver F11GSF. F11GTF, the third routine in the suite, can be used to return additional information about the computation. Either of two methods can be used:
1. | Conjugate Gradient Method (CG) For this method (see Hestenes and Stiefel (1952), Golub and Van Loan (1996), Barrett et al. (1994) and Dias da Cunha and Hopkins (1994)), the matrix A should ideally be positive definite. The application of the Conjugate Gradient method to indefinite matrices may lead to failure or to lack of convergence.
2. | Lanczos Method (SYMMLQ) This method, based upon the algorithm SYMMLQ (see Paige and Saunders (1975) and Barrett et al. (1994)), is suitable for both positive definite and indefinite matrices. It is more robust than the Conjugate Gradient method but less efficient when A is positive definite.
Both CG and SYMMLQ methods start from the residual r 0=b-A x 0, where x 0 is an initial estimate for the solution (often x 0=0), and generate an orthogonal basis for the Krylov subspace span Ak r 0, for k=0,1,…, by means of three-term recurrence relations (see Golub and Van Loan (1996)). A sequence of real symmetric tridiagonal matrices Tk is also generated. Here and in the following, the index k denotes the iteration count. The resulting real symmetric tridiagonal systems of equations are usually more easily solved than the original problem. A sequence of solution iterates xk is thus generated such that the sequence of the norms of the residuals rk converges to a required tolerance. Note that, in general, the convergence is not monotonic.
In exact arithmetic, after n iterations, this process is equivalent to an orthogonal reduction of A to real symmetric tridiagonal form, Tn=QH AQ; the solution xn would thus achieve exact convergence. In finite-precision arithmetic, cancellation and round-off errors accumulate causing loss of orthogonality. These methods must therefore be viewed as genuinely iterative methods, able to converge to a solution within a prescribed tolerance.
The orthogonal basis is not formed explicitly in either method. The basic difference between the two methods lies in the method of solution of the resulting real symmetric tridiagonal systems of equations: the conjugate gradient method is equivalent to carrying out an LD LH (Cholesky) factorization whereas the Lanczos method (SYMMLQ) uses an LQ factorization.
Faster convergence can be achieved using a preconditioner (see Golub and Van Loan (1996) and Barrett et al. (1994)). A preconditioner maps the original system of equations onto a different system, say
A-x-=b-, (1)
with, hopefully, better characteristics with respect to its speed of convergence: for example, the condition number of the matrix of the coefficients can be improved or eigenvalues in its spectrum can be made to coalesce. An orthogonal basis for the Krylov subspace span A-k r-0, for k=0,1,…, is generated and the solution proceeds as outlined above. The algorithms used are such that the solution and residual iterates of the original system are produced, not their preconditioned counterparts. Note that an unsuitable preconditioner or no preconditioning at all may result in a very slow rate, or lack, of convergence. However, preconditioning involves a trade-off between the reduction in the number of iterations required for convergence and the additional computational costs per iteration. Also, setting up a preconditioner may involve non-negligible overheads.
A preconditioner must be Hermitian and positive definite, i.e., representable by M=E EH, where M is nonsingular, and such that A-=E-1 A E-H∼In in (1), where In is the identity matrix of order n. Also, we can define r-=E-1 r and x-=EH x. These are formal definitions, used only in the design of the algorithms; in practice, only the means to compute the matrix-vector products v=Au and to solve the preconditioning equations Mv=u are required, that is, explicit information about M, E or their inverses is not required at any stage.
The first termination criterion
rk p ≤ τ b p + A p × xk p (2)
is available for both conjugate gradient and Lanczos (SYMMLQ) methods. In (2), p=1,∞​ or ​2 and τ denotes a user-specified tolerance subject to max 10,n ε≤τ<1, where ε is the machine precision. Facilities are provided for the estimation of the norm of the matrix of the coefficients A 1=A∞, when this is not known in advance, used in (2), by applying Higham's method (see Higham (1988)). Note that A 2 cannot be estimated internally. This criterion uses an error bound derived from backward error analysis to ensure that the computed solution is the exact solution of a problem as close to the original as the termination tolerance requires. Termination criteria employing bounds derived from forward error analysis could be used, but any such criteria would require information about the condition number κ A which is not easily obtainable.
The second termination criterion
r-k 2 ≤ τ max 1.0, b 2 / r 0 2 r-0 2 + σ 1 A- × Δ x-k 2 (3)
is available only for the Lanczos method (SYMMLQ). In (3), σ 1 A-=A-2 is the largest singular value of the (preconditioned) iteration matrix A-. This termination criterion monitors the progress of the solution of the preconditioned system of equations and is less expensive to apply than criterion (2). When σ 1 A- is not supplied, facilities are provided for its estimation by σ 1 A-∼maxk σ 1 Tk. The interlacing property σ 1 T k-1≤σ 1 Tk and Gerschgorin's theorem provide lower and upper bounds from which σ 1 Tk can be easily computed by bisection. Alternatively, the less expensive estimate σ 1 A-∼maxk Tk 1 can be used, where σ 1 A-≤Tk 1 by Gerschgorin's theorem. Note that only order of magnitude estimates are required by the termination criterion.
Termination criterion (2) is the recommended choice, despite its (small) additional costs per iteration when using the Lanczos method (SYMMLQ). Also, if the norm of the initial estimate is much larger than the norm of the solution, that is, if x 0≫x, a dramatic loss of significant digits could result in complete lack of convergence. The use of criterion (2) will enable the detection of such a situation, and the iteration will be restarted at a suitable point. No such restart facilities are provided for criterion (3).
Optionally, a vector w of user-specified weights can be used in the computation of the vector norms in termination criterion (2), i.e., v p w=v w p, where v w i=wi vi, for i=1,2,…,n. Note that the use of weights increases the computational costs.
The sequence of calls to the routines comprising the suite is enforced: first, the setup routine F11GRF must be called, followed by the solver F11GSF. F11GTF can be called either when F11GSF is carrying out a monitoring step or after F11GSF has completed its tasks. Incorrect sequencing will raise an error condition.

4 References

Barrett R, Berry M, Chan T F, Demmel J, Donato J, Dongarra J, Eijkhout V, Pozo R, Romine C and Van der Vorst H (1994) Templates for the Solution of Linear Systems: Building Blocks for Iterative Methods SIAM, Philadelphia
Dias da Cunha R and Hopkins T (1994) PIM 1.1 — the parallel iterative method package for systems of linear equations user's guide — Fortran 77 version Technical Report Computing Laboratory, University of Kent at Canterbury, Kent, UK
Golub G H and Van Loan C F (1996) Matrix Computations (3rd Edition) Johns Hopkins University Press, Baltimore
Hestenes M and Stiefel E (1952) Methods of conjugate gradients for solving linear systems J. Res. Nat. Bur. Stand. 49 409–436
Higham N J (1988) FORTRAN codes for estimating the one-norm of a real or complex matrix, with applications to condition estimation ACM Trans. Math. Software 14 381–396
Paige C C and Saunders M A (1975) Solution of sparse indefinite systems of linear equations SIAM J. Numer. Anal. 12 617–629

5 Arguments

1:   METHOD – CHARACTER(*)Input
On entry: the iterative method to be used.
METHOD='CG'
Conjugate gradient method.
METHOD='SYMMLQ'
Lanczos method (SYMMLQ).
Constraint: METHOD='CG' or 'SYMMLQ'.
2:   PRECON – CHARACTER(1)Input
On entry: determines whether preconditioning is used.
PRECON='N'
No preconditioning.
PRECON='P'
Preconditioning.
Constraint: PRECON='N' or 'P'.
3:   SIGCMP – CHARACTER(1)Input
On entry: determines whether an estimate of σ 1 A-=E-1 A E-H 2, the largest singular value of the preconditioned matrix of the coefficients, is to be computed using the bisection method on the sequence of tridiagonal matrices Tk generated during the iteration. Note that A-=A when a preconditioner is not used.
If SIGMAX>0.0 (see below), i.e., when σ 1 A- is supplied, the value of SIGCMP is ignored.
SIGCMP='S'
σ 1 A- is to be computed using the bisection method.
SIGCMP='N'
The bisection method is not used.
If the termination criterion (3) is used, requiring σ 1 A-, an inexpensive estimate is computed and used (see Section 3).
Suggested value: SIGCMP='N'.
Constraint: SIGCMP='S' or 'N'.
4:   NORM – CHARACTER(1)Input
On entry: defines the matrix and vector norm to be used in the termination criteria.
NORM='1'
Use the l 1 norm.
NORM='I'
Use the l∞ norm.
NORM='2'
Use the l 2 norm.
Suggested values:
  • if ITERM=1, NORM='I';
  • if ITERM=2, NORM='2'.
Constraints:
  • if ITERM=1, NORM='1', 'I' or '2';
  • if ITERM=2, NORM='2'.
5:   WEIGHT – CHARACTER(1)Input
On entry: specifies whether a vector w of user-supplied weights is to be used in the vector norms used in the computation of termination criterion (2) (ITERM=1): v p w=v w p, where vi w =wi vi, for i=1,2,…,n. The suffix p=1,2,∞ denotes the vector norm used, as specified by the argument NORM. Note that weights cannot be used when ITERM=2, i.e., when criterion (3) is used.
WEIGHT='W'
User-supplied weights are to be used and must be supplied on initial entry to F11GSF.
WEIGHT='N'
All weights are implicitly set equal to one. Weights do not need to be supplied on initial entry to F11GSF.
Suggested value: WEIGHT='N'.
Constraints:
  • if ITERM=1, WEIGHT='W' or 'N';
  • if ITERM=2, WEIGHT='N'.
6:   ITERM – INTEGERInput
On entry: defines the termination criterion to be used.
ITERM=1
Use the termination criterion defined in (2) (both conjugate gradient and Lanczos (SYMMLQ) methods).
ITERM=2
Use the termination criterion defined in (3) (Lanczos method (SYMMLQ) only).
Suggested value: ITERM=1.
Constraints:
  • if METHOD='CG', ITERM=1;
  • if METHOD='SYMMLQ', ITERM=1 or 2.
7:   N – INTEGERInput
On entry: n, the order of the matrix A.
Constraint: N>0.
8:   TOL – REAL (KIND=nag_wp)Input
On entry: the tolerance τ for the termination criterion.
If TOL≤0.0, τ=max ε,n ε is used, where ε is the machine precision.
Otherwise τ=max TOL,10 ε,n ε is used.
Constraint: TOL<1.0.
9:   MAXITN – INTEGERInput
On entry: the maximum number of iterations.
Constraint: MAXITN>0.
10:   ANORM – REAL (KIND=nag_wp)Input
On entry: if ANORM>0.0, the value of A p to be used in the termination criterion (2) (ITERM=1).
If ANORM≤0.0, ITERM=1 and NORM='1' or 'I', then A 1=A∞ is estimated internally by F11GSF.
If ITERM=2, then ANORM is not referenced.
Constraint: if ITERM=1 and NORM=2, ANORM>0.0.
11:   SIGMAX – REAL (KIND=nag_wp)Input
On entry: if SIGMAX>0.0, the value of σ 1 A-=E-1 A E-H 2.
If SIGMAX≤0.0, σ 1 A- is estimated by F11GSF when either SIGCMP='S' or termination criterion (3) (ITERM=2) is employed, though it will be used only in the latter case.
Otherwise, SIGMAX is not referenced.
12:   SIGTOL – REAL (KIND=nag_wp)Input
On entry: the tolerance used in assessing the convergence of the estimate of σ 1 A-=A-2 when the bisection method is used.
If SIGTOL≤0.0, the default value SIGTOL=0.01 is used. The actual value used is max SIGTOL,ε.
If SIGCMP='N' or SIGMAX>0.0, then SIGTOL is not referenced.
Suggested value: SIGTOL=0.01 should be sufficient in most cases.
Constraint: if SIGCMP='S' and SIGMAX≤0.0, SIGTOL<1.0.
13:   MAXITS – INTEGERInput
On entry: the maximum iteration number k=MAXITS for which σ 1 Tk is computed by bisection (see also Section 3). If SIGCMP='N' or SIGMAX>0.0, then MAXITS is not referenced.
Suggested value: MAXITS=min 10,n when SIGTOL is of the order of its default value 0.01.
Constraint: if SIGCMP='S' and SIGMAX≤0.0, 1≤MAXITS≤MAXITN.
14:   MONIT – INTEGERInput
On entry: if MONIT>0, the frequency at which a monitoring step is executed by F11GSF: the current solution and residual iterates will be returned by F11GSF and a call to F11GTF made possible every MONIT iterations, starting from iteration number MONIT. Otherwise, no monitoring takes place. There are some additional computational costs involved in monitoring the solution and residual vectors when the Lanczos method (SYMMLQ) is used.
Constraint: MONIT≤MAXITN.
15:   LWREQ – INTEGEROutput
On exit: the minimum amount of workspace required by F11GSF. (See also Section 5 in F11GSF.)
16:   WORK LWORK – COMPLEX (KIND=nag_wp) arrayCommunication Array
On exit: the array WORK is initialized by F11GRF. It must not be modified before calling the next routine in the suite, namely F11GSF.
17:   LWORK – INTEGERInput
On entry: the dimension of the array WORK as declared in the (sub)program from which F11GRF is called.
Constraint: LWORK≥120.
Note: although the minimum value of LWORK ensures the correct functioning of F11GRF, a larger value is required by the other routines in the suite, namely F11GSF and F11GTF. The required value is as follows:
Method | Requirements
CG | LWORK=120+5 n+p
SYMMLQ | LWORK=120+6 n+p
where
  • p=2×MAXITS+1, when an estimate of σ 1 A (SIGMAX) is computed;
  • p=0, otherwise.
18:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=-i
On entry, the ith argument had an illegal value.
IFAIL=1
F11GRF has been called out of sequence.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

Not applicable.

8 Parallelism and Performance

F11GRF is not threaded in any implementation.

9 Further Comments

When σ 1 A- is not supplied (SIGMAX≤0.0) but it is required, it is estimated by F11GSF using either of the two methods described in Section 3, as specified by the argument SIGCMP. In particular, if SIGCMP='S', then the computation of σ 1 A- is deemed to have converged when the differences between three successive values of σ 1 Tk differ, in a relative sense, by less than the tolerance SIGTOL, i.e., when
max σ 1 k - σ 1 k - 1 σ 1 k , σ 1 k - σ 1 k - 2 σ 1 k ≤ SIGTOL .
The computation of σ 1 A- is also terminated when the iteration count exceeds the maximum value allowed, i.e., k≥MAXITS.
Bisection is increasingly expensive with increasing iteration count. A reasonably large value of SIGTOL, of the order of the suggested value, is recommended and an excessive value of MAXITS should be avoided. Under these conditions, σ 1 A- usually converges within very few iterations.

10 Example

This example solves a complex Hermitian system of simultaneous linear equations using the conjugate gradient method, where the matrix of the coefficients A, has a random sparsity pattern. An incomplete Cholesky preconditioner is used (F11JAF and F11JBF).

10.1 Program Text

Program Text (f11grfe.f90)

10.2 Program Data

Program Data (f11grfe.d)

10.3 Program Results

Program Results (f11grfe.r)

F11 Chapter Contents
F11 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F11GSF : NAG Library, Mark 26

F11 Chapter Contents
F11 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F11GSF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
10 Example

1 Purpose

F11GSF is an iterative solver for a complex Hermitian system of simultaneous linear equations; F11GSF is the second in a suite of three routines, where the first routine, F11GRF, must be called prior to F11GSF to set up the suite, and the third routine in the suite, F11GTF, can be used to return additional information about the computation.
These three routines are suitable for the solution of large sparse complex Hermitian systems of equations.

2 Specification

SUBROUTINE F11GSF ( IREVCM, U, V, WGT, WORK, LWORK, IFAIL)
INTEGER | IREVCM, LWORK, IFAIL
REAL (KIND=nag_wp) | WGT(*)
COMPLEX (KIND=nag_wp) | U(*), V(*), WORK(LWORK)

3 Description

F11GSF solves the complex Hermitian system of linear simultaneous equations Ax=b using either the preconditioned conjugate gradient method (see Hestenes and Stiefel (1952), Golub and Van Loan (1996), Barrett et al. (1994) and Dias da Cunha and Hopkins (1994)) or a preconditioned Lanczos method based upon the algorithm SYMMLQ (see Paige and Saunders (1975) and Barrett et al. (1994)).
For a general description of the methods employed you are referred to Section 3 in F11GRF.
F11GSF can solve the system after the first routine in the suite, F11GRF, has been called to initialize the computation and specify the method of solution. The third routine in the suite, F11GTF, can be used to return additional information generated by the computation during monitoring steps and after F11GSF has completed its tasks.
F11GSF uses reverse communication, i.e., F11GSF returns repeatedly to the calling program with the argument IREVCM (see Section 5) set to specified values which require the calling program to carry out a specific task: either to compute the matrix-vector product v=Au; to solve the preconditioning equation Mv=u; to notify the completion of the computation; or, to allow the calling program to monitor the solution. Through the argument IREVCM the calling program can cause immediate or tidy termination of the execution. On final exit, the last iterates of the solution and of the residual vectors of the original system of equations are returned.
Reverse communication has the following advantages.
1. | Maximum flexibility in the representation and storage of sparse matrices. All matrix operations are performed outside the solver routine, thereby avoiding the need for a complicated interface with enough flexibility to cope with all types of storage schemes and sparsity patterns. This applies also to preconditioners.
2. | Enhanced user interaction: you can closely monitor the progress of the solution and tidy or immediate termination can be requested. This is useful, for example, when alternative termination criteria are to be employed or in case of failure of the external routines used to perform matrix operations.

4 References

Barrett R, Berry M, Chan T F, Demmel J, Donato J, Dongarra J, Eijkhout V, Pozo R, Romine C and Van der Vorst H (1994) Templates for the Solution of Linear Systems: Building Blocks for Iterative Methods SIAM, Philadelphia
Dias da Cunha R and Hopkins T (1994) PIM 1.1 — the parallel iterative method package for systems of linear equations user's guide — Fortran 77 version Technical Report Computing Laboratory, University of Kent at Canterbury, Kent, UK
Golub G H and Van Loan C F (1996) Matrix Computations (3rd Edition) Johns Hopkins University Press, Baltimore
Hestenes M and Stiefel E (1952) Methods of conjugate gradients for solving linear systems J. Res. Nat. Bur. Stand. 49 409–436
Higham N J (1988) FORTRAN codes for estimating the one-norm of a real or complex matrix, with applications to condition estimation ACM Trans. Math. Software 14 381–396
Paige C C and Saunders M A (1975) Solution of sparse indefinite systems of linear equations SIAM J. Numer. Anal. 12 617–629

5 Arguments

Note: this routine uses reverse communication. Its use involves an initial entry, intermediate exits and re-entries, and a final exit, as indicated by the argument IREVCM. Between intermediate exits and re-entries, all arguments other than IREVCM and V must remain unchanged.
1:   IREVCM – INTEGERInput/Output
On initial entry: IREVCM=0, otherwise an error condition will be raised.
On intermediate re-entry: IREVCM must either be unchanged from its previous exit value, or can have one of the following values.
IREVCM=5
Tidy termination: the computation will terminate at the end of the current iteration. Further reverse communication exits may occur depending on when the termination request is issued. F11GSF will then return with the termination code IREVCM=4. Note that before calling F11GSF with IREVCM=5 the calling program must have performed the tasks required by the value of IREVCM returned by the previous call to F11GSF, otherwise subsequently returned values may be invalid.
IREVCM=6
Immediate termination: F11GSF will return immediately with termination code IREVCM=4 and with any useful information available. This includes the last iterate of the solution and, for conjugate gradient only, the last iterate of the residual vector. The residual vector is generally not available when the Lanczos method (SYMMLQ) is used. F11GSF will then return with the termination code IREVCM=4.
Immediate termination may be useful, for example, when errors are detected during matrix-vector multiplication or during the solution of the preconditioning equation.
Changing IREVCM to any other value between calls will result in an error.
On intermediate exit: has the following meanings.
IREVCM=1
The calling program must compute the matrix-vector product v=Au, where u and v are stored in U and V, respectively.
IREVCM=2
The calling program must solve the preconditioning equation Mv=u, where u and v are stored in U and V, respectively.
IREVCM=3
Monitoring step: the solution and residual at the current iteration are returned in the arrays U and V, respectively. No action by the calling program is required. To return additional information F11GTF can be called at this step.
On final exit: if IREVCM=4, F11GSF has completed its tasks. The value of IFAIL determines whether the iteration has been successfully completed, errors have been detected or the calling program has requested termination.
Constraint: on initial entry, IREVCM=0; on re-entry, either IREVCM must remain unchanged or be reset to IREVCM=5 or 6.
2:   U* – COMPLEX (KIND=nag_wp) arrayInput/Output
Note: the dimension of the array U must be at least n.
On initial entry: an initial estimate, x 0, of the solution of the system of equations Ax=b.
On intermediate re-entry: must remain unchanged.
On intermediate exit: the returned value of IREVCM determines the contents of U in the following way.
If IREVCM=1 or 2, U holds the vector u on which the operation specified by IREVCM is to be carried out.
If IREVCM=3, U holds the current iterate of the solution vector.
On final exit: if IFAIL=3 or -i, the array U is unchanged from the initial entry to F11GSF. If IFAIL=1, the array U is unchanged from the last entry to F11GSF. Otherwise, U holds the last iterate of the solution of the system of equations, for all returned values of IFAIL.
3:   V* – COMPLEX (KIND=nag_wp) arrayInput/Output
Note: the dimension of the array V must be at least n.
On initial entry: the right-hand side b of the system of equations Ax=b.
On intermediate re-entry: the returned value of IREVCM determines the contents of V in the following way.
If IREVCM=1 or 2, V must store the vector v, the result of the operation specified by the value of IREVCM returned by the previous call to F11GSF
If IREVCM=3, V must remain unchanged.
On intermediate exit: if IREVCM=3, V holds the current iterate of the residual vector. Note that this is an approximation to the true residual vector. Otherwise, it does not contain any useful information.
On final exit: if IFAIL=3 or 0, the array V is unchanged from the last entry to F11GSF. If IFAIL=1, the array V is unchanged from the initial entry to F11GSF. If IFAIL=0 or 2, the array V contains the true residual vector of the system of equations (see also Section 6). Otherwise, V stores the last iterate of the residual vector unless the Lanczos method (SYMMLQ) was used and IFAIL≥5, in which case V is set to 0.0.
4:   WGT* – REAL (KIND=nag_wp) arrayInput
Note: the dimension of the array WGT must be at least max 1,n.
On entry: the user-supplied weights, if these are to be used in the computation of the vector norms in the termination criterion (see Sections 3 and 5 in F11GRF).
Constraint: if weights are to be used, at least one element of WGT must be nonzero.
5:   WORK LWORK – COMPLEX (KIND=nag_wp) arrayCommunication Array
On initial entry: the array WORK as returned by F11GRF (see also Section 5 in F11GRF).
On intermediate re-entry: must remain unchanged.
6:   LWORK – INTEGERInput
On initial entry: the dimension of the array WORK as declared in the (sub)program from which F11GSF is called (see also Section 3 in F11GRF). The required amount of workspace is as follows:
Method | Requirements
CG | LWORK=120+5 n+p.
SYMMLQ | LWORK=120+6 n+p.
where
  • p=2×MAXITS+1, when an estimate of σ 1 A (SIGMAX) is computed;
  • p=0, otherwise.
Constraint: LWORK≥LWREQ, where LWREQ is returned by F11GRF.
7:   IFAIL – INTEGERInput/Output
On initial entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, because for this routine the values of the output arguments may be useful even if IFAIL≠0 on exit, the recommended value is -1. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On intermediate exit: the value of IFAIL is meaningless and should be ignored.
On final exit: (i.e., when IREVCM=4) IFAIL=0, unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=-i
On entry, the ith argument had an illegal value.
IFAIL=1
F11GSF has been called again after returning the termination code IREVCM=4. No further computation has been carried out and all input data and data stored for access by F11GTF have remained unchanged.
IFAIL=2
The required accuracy could not be obtained. However, F11GSF has terminated with reasonable accuracy: the last iterate of the residual satisfied the termination criterion but the exact residual r=b-Ax, did not. A small number of iterations have been carried out after the iterated residual satisfied the termination criterion, but were unable to improve on the accuracy. This error code usually implies that your problem has been fully and satisfactorily solved to within or close to the accuracy available on your system. Further iterations are unlikely to improve on this situation. You should call F11GTF to check the values of the left- and right-hand side of the termination condition.
IFAIL=3
F11GRF was either not called before calling F11GSF or it returned an error. The arrays U and V remain unchanged.
IFAIL=4
The calling program requested a tidy termination before the solution had converged. The arrays U and V return the last iterates available of the solution and of the residual vector, respectively.
IFAIL=5
The solution did not converge within the maximum number of iterations allowed. The arrays U and V return the last iterates available of the solution and of the residual vector, respectively.
IFAIL=6
The preconditioner appears not to be positive definite. It is likely that your results are meaningless: both methods require a positive definite preconditioner (see also Section 3). However, the array U returns the last iterate of the solution, the array V returns the last iterate of the residual vector, for the conjugate gradient method only.
IFAIL=7
The matrix of the coefficients appears not to be positive definite (conjugate gradient method only). The arrays U and V return the last iterates of the solution and residual vector, respectively. However, you should be warned that the results returned can be be in error.
IFAIL=8
The calling program requested an immediate termination. However, the array U returns the last iterate of the solution, the array V returns the last iterate of the residual vector, for the conjugate gradient method only.
IFAIL=9
The matrix appears to be singular.
IFAIL=10
User-supplied weights are to be used, but all elements of the array WGT are zero.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

On completion, i.e., IREVCM=4 on exit, the arrays U and V will return the solution and residual vectors, xk and rk=b-A xk, respectively, at the kth iteration, the last iteration performed, unless an immediate termination was requested and the Lanczos method (SYMMLQ) was used.
On successful completion, the termination criterion is satisfied to within the user-specified tolerance, as described in Section 3 in F11GRF. The computed values of the left- and right-hand sides of the termination criterion selected can be obtained by a call to F11GTF.

8 Parallelism and Performance

F11GSF is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
F11GSF makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The number of operations carried out by F11GSF for each iteration is likely to be principally determined by the computation of the matrix-vector products v=Au and by the solution of the preconditioning equation Mv=u in the calling program. Each of these operations is carried out once every iteration.
The number of the remaining operations in F11GSF for each iteration is approximately proportional to n. Note that the Lanczos method (SYMMLQ) requires a slightly larger number of operations than the conjugate gradient method.
The number of iterations required to achieve a prescribed accuracy cannot be easily determined at the onset, as it can depend dramatically on the conditioning and spectrum of the preconditioned matrix of the coefficients A-=E-1 A E-H.
Additional matrix-vector products are required for the computation of A 1=A∞, when this has not been supplied to F11GRF and is required by the termination criterion employed.
The number of operations required to compute σ 1 A- is negligible for reasonable values of SIGTOL and MAXITS (see Sections 5 and 9 in F11GRF).
If the termination criterion rk p ≤ τ b p+A p × xk p is used (see Section 3 in F11GRF) and x 0≫xk, so that because of loss of significant digits the required accuracy could not be obtained, the iteration is restarted automatically at some suitable point: F11GSF sets x 0=xk and the computation begins again. For particularly badly scaled problems, more than one restart may be necessary. Naturally, restarting adds to computational costs: it is recommended that the iteration should start from a value x 0 which is as close to the true solution x~ as can be estimated. Otherwise, the iteration should start from x 0=0.

10 Example

See Section 10 in F11GRF.
F11 Chapter Contents
F11 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F11GTF : NAG Library, Mark 26

F11 Chapter Contents
F11 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F11GTF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
10 Example

1 Purpose

F11GTF is the third in a suite of three routines for the iterative solution of a complex Hermitian system of simultaneous linear equations (see Golub and Van Loan (1996)). F11GTF returns information about the computations during an iteration and/or after this has been completed. The first routine of the suite, F11GRF, is a setup routine, the second routine, F11GSF is the proper iterative solver.
These three routines are suitable for the solution of large sparse complex Hermitian systems of equations.

2 Specification

SUBROUTINE F11GTF ( ITN, STPLHS, STPRHS, ANORM, SIGMAX, ITS, SIGERR, WORK, LWORK, IFAIL)
INTEGER | ITN, ITS, LWORK, IFAIL
REAL (KIND=nag_wp) | STPLHS, STPRHS, ANORM, SIGMAX, SIGERR
COMPLEX (KIND=nag_wp) | WORK(LWORK)

3 Description

F11GTF returns information about the solution process. It can be called both during a monitoring step of the solver F11GSF or after this solver has completed its tasks. Calling F11GTF at any other time will result in an error condition being raised.
For further information you should read the documentation for F11GRF and F11GSF.

4 References

Golub G H and Van Loan C F (1996) Matrix Computations (3rd Edition) Johns Hopkins University Press, Baltimore

5 Arguments

1:   ITN – INTEGEROutput
On exit: the number of iterations carried out by F11GSF.
2:   STPLHS – REAL (KIND=nag_wp)Output
On exit: the current value of the left-hand side of the termination criterion used by F11GSF.
3:   STPRHS – REAL (KIND=nag_wp)Output
On exit: the current value of the right-hand side of the termination criterion used by F11GSF.
4:   ANORM – REAL (KIND=nag_wp)Output
On exit: the norm A 1=A∞ when either it has been supplied to F11GRF or it has been estimated by F11GSF (see also Sections 3 and 5 in F11GRF).
Otherwise, ANORM=0.0 is returned.
5:   SIGMAX – REAL (KIND=nag_wp)Output
On exit: the current estimate of the largest singular value σ 1 A- of the preconditioned iteration matrix A-=E-1 A E-H, when either it has been supplied to F11GRF or it has been estimated by F11GSF (see also Sections 3 and 5 in F11GRF). Note that if ITS<ITN then SIGMAX contains the final estimate. If, on final exit from F11GSF, ITS=ITN, then the estimation of σ 1 A- may have not converged: in this case you should look at the value returned in SIGERR. Otherwise, SIGMAX=0.0 is returned.
6:   ITS – INTEGEROutput
On exit: the number of iterations employed so far in the computation of the estimate of σ 1 A-, the largest singular value of the preconditioned matrix A-=E-1 A E-H, when σ 1 A- has been estimated by F11GSF using the bisection method (see also Sections 3, 5 and 9 in F11GRF). Otherwise, ITS=0 is returned.
7:   SIGERR – REAL (KIND=nag_wp)Output
On exit: if σ 1 A- has been estimated by F11GSF using bisection,
SIGERR=max σ 1 k-σ 1 k-1 σ 1 k,σ 1 k-σ 1 k-2 σ 1 k ,
where k=ITS denotes the iteration number. The estimation has converged if SIGERR≤SIGTOL where SIGTOL is an input argument to F11GRF.
Otherwise, SIGERR=0.0 is returned.
8:   WORK LWORK – COMPLEX (KIND=nag_wp) arrayCommunication Array
On entry: the array WORK as returned by F11GSF (see also Section 3 in F11GSF).
9:   LWORK – INTEGERInput
On entry: the dimension of the array WORK as declared in the (sub)program from which F11GTF is called (see also Section 5 in F11GRF).
Constraint: LWORK≥120.
Note: although the minimum value of LWORK ensures the correct functioning of F11GTF, a larger value is required by the iterative solver F11GSF (see also Section 5 in F11GRF).
10:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=-i
On entry, the ith argument had an illegal value.
IFAIL=1
F11GTF has been called out of sequence. For example, the last call to F11GSF did not return IREVCM=3 or 4.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

Not applicable.

8 Parallelism and Performance

F11GTF is not threaded in any implementation.

9 Further Comments

None.

10 Example

See Section 10 in F11GRF.
F11 Chapter Contents
F11 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F11 Chapter Introduction : NAG Library, Mark 26

F11 Chapter Contents
NAG Library Manual

NAG Library Chapter Introduction

F11 – Large Scale Linear Systems

▸▿ Contents

1 Scope of the Chapter
▸▿ 2 Background to the Problems
▸▿ 2.1 Sparse Matrices and Their Storage
2.1.1 Coordinate storage (CS) format
2.1.2 Symmetric coordinate storage (SCS) format
2.1.3 Compressed column storage (CCS) format
2.2 Direct Methods
2.3 Iterative Methods
2.4 Iterative Methods for Real Nonsymmetric and Complex Non-Hermitian Linear Systems
2.5 Iterative Methods for Real Symmetric and Complex Hermitian Linear Systems
▸▿ 3 Recommendations on Choice and Use of Available Routines
3.1 Types of Routine Available
3.2 Iterative Methods for Real Nonsymmetric and Complex Non-Hermitian Linear Systems
3.3 Iterative Methods for Real Symmetric and Complex Hermitian Linear Systems
3.4 Direct Methods
4 Decision Tree
5 Functionality Index
6 Auxiliary Routines Associated with Library Routine Arguments
7 Routines Withdrawn or Scheduled for Withdrawal
8 References

1 Scope of the Chapter

This chapter provides routines for the solution of large sparse systems of simultaneous linear equations. These include iterative methods for real nonsymmetric and symmetric, complex non-Hermitian and Hermitian linear systems and direct methods for general real linear systems. Further direct methods are currently available in Chapters F01 and F04.

2 Background to the Problems

This section is only a brief introduction to the solution of sparse linear systems. For a more detailed discussion see for example Duff et al. (1986) and Demmel et al. (1999) for direct methods, or Barrett et al. (1994) for iterative methods.

2.1 Sparse Matrices and Their Storage

A matrix A may be described as sparse if the number of zero elements is sufficiently large that it is worthwhile using algorithms which avoid computations involving zero elements.
If A is sparse, and the chosen algorithm requires the matrix coefficients to be stored, a significant saving in storage can often be made by storing only the nonzero elements. A number of different formats may be used to represent sparse matrices economically. These differ according to the amount of storage required, the amount of indirect addressing required for fundamental operations such as matrix-vector products, and their suitability for vector and/or parallel architectures. For a survey of some of these storage formats see Barrett et al. (1994).
Some of the routines in this chapter have been designed to be independent of the matrix storage format. This allows you to choose your own preferred format, or to avoid storing the matrix altogether. Other routines are the so-called Black Boxes, which are easier to use, but are based on fixed storage formats. Three fixed storage formats for sparse matrices are currently used. These are known as coordinate storage (CS) format, symmetric coordinate storage (SCS) format and compressed column storage (CCS) format.

2.1.1 Coordinate storage (CS) format

This storage format represents a sparse matrix A, with NNZ nonzero elements, in terms of three one-dimensional arrays – a real or complex array A and two integer arrays IROW and ICOL. These arrays are all of dimension at least NNZ. A contains the nonzero elements themselves, while IROW and ICOL store the corresponding row and column indices respectively.
For example, the matrix
A= 1 -2 -1 -1 -3 0 -1 0 0 -4 3 0 0 0 2 2 0 4 1 1 -2 0 0 0 1
might be represented in the arrays A, IROW and ICOL as
  • A=1,2,-1,-1,-3,-1,-4,3,2,2,4,1,1,-2,1
  • IROW=1,1,1,1,1,2,2,3,3,4,4,4,4,5,5
  • ICOL=1,2,3,4,5,2,5,1,5,1,3,4,5,1,5.
Notes
(i) | The general format specifies no ordering of the array elements, but some routines may impose a specific ordering. For example, the nonzero elements may be required to be ordered by increasing row index and by increasing column index within each row, as in the example above. Utility routines are provided to order the elements appropriately (see Section 2.2).
(ii) | With this storage format it is possible to enter duplicate elements. These may be interpreted in various ways (e.g., raising an error, ignoring all but the first entry, all but the last, or summing).

2.1.2 Symmetric coordinate storage (SCS) format

This storage format is suitable for symmetric and Hermitian matrices, and is identical to the CS format described in Section 2.1.1, except that only the lower triangular nonzero elements are stored. Thus, for example, the matrix
A= 4 -1 -0 -0 -1 2 1 5 0 2 0 0 0 0 2 1 0 -1 0 2 1 3 1 0 -1 0 0 1 4 0 2 0 -1 0 0 3
might be represented in the arrays A, IROW and ICOL as
  • A=4,1,5,2,2,1,3,-1,1,4,2,-1,3.
  • IROW=1,2,2,3,4,4,4,5,5,5,6,6,6,
  • ICOL=1,1,2,3,2,3,4,1,4,5,1,3,6.

2.1.3 Compressed column storage (CCS) format

This storage format also uses three one-dimensional arrays – a real or complex array A and two integer arrays IROWIX and ICOLZP. The array A and IROWIX are of dimension at least nnz, while ICOLZP is of dimension at least N+1. A contains the nonzero elements, going down the first column, then the second and so on. For example, the matrix in Section 2.1.1 above will be represented by
  • A=1,3,2,-2,2,-1,-1,4,-1,1,-3,-4,2,1,1.
IROWIX records the row index for each entry in A, so the same matrix will have
  • IROWIX=1,3,4,5,1,2,1,4,1,4,1,2,3,4,5.
ICOLZP records the index into A which starts each new column. The last entry of ICOLZP is equal to nnz+1. An empty column (one filled with zeros, that is) is signalled by an index that is the same as the next non-empty column, or nnz+1 if all subsequent columns are empty. The above example corresponds to
  • ICOLZP=1,5,7,9,11,16
The example in Section 2.1.2 above will be represented by
  • A=4,1,-1,2,1,5,2,2,1,-1,2,1,3,1,-1,1,4,2,-1,3
  • IROWIX=1,2,5,6,1,2,4,3,4,6,2,3,4,5,1,4,5,1,3,6
  • ICOLZP=1,5,8,11,15,18,21

2.2 Direct Methods

Direct methods for the solution of the linear algebraic system
Ax=b (1)
aim to determine the solution vector x in a fixed number of arithmetic operations, which is determined a priori by the number of unknowns. For example, an LU factorization of A followed by forward and backward substitution is a direct method for (1).
If the matrix A is sparse it is possible to design direct methods which exploit the sparsity pattern and are therefore much more computationally efficient than the algorithms in Chapter F07, which in general take no account of sparsity. However, if the matrix is very large and sparse, then iterative methods, with an appropriate preconditioner, (see Section 2.3) may be more efficient still.
This chapter provides a direct LU factorization method for sparse real systems. This method is based on special coding for supernodes, broadly defined as groups of consecutive columns with the same nonzero structure, which enables use of dense BLAS kernels. The algorithms contained here come from the SuperLU software suite (see Demmel et al. (1999)). An important requirement of sparse LU factorization is keeping the factors as sparse as possible. It is well known that certain column orderings can produce much sparser factorizations than the normal left-to-right ordering. It is well worth the effort, then, to find such column orderings since they reduce both storage requirements of the factors, the time taken to compute them and the time taken to solve the linear system. The row reorderings, demanded by partial pivoting in order to keep the factorization stable, can further complicate the choice of the column ordering, but quite good and fast algorithms have been developed to make possible a fairly reliable computation of an appropriate column ordering for any sparsity pattern. We provide one such algorithm (known in the literature as COLAMD) through one routine in the suite. Similar to the case for dense matrices, routines are provided to compute the LU factorization with partial row pivoting for numerical stability, solve (1) by performing the forward and backward substitutions for multiple right hand side vectors, refine the solution, minimize the backward error and estimate the forward error of the solutions, compute norms, estimate condition numbers and perform diagnostics of the factorization. It is also possible to explicitly construct, column by column, the dense inverse of the matrix by solving equation (1) for right hand sides corresponding to columns of the identity matrix. Blocks of dense columns can be handled at one time and then stored in some chosen sparse format, as system memory allows. For more details see Section 3.4.
It is also possible to use iterative method routines in this chapter to compute a direct factorization. Such methods are available for sparse real nonsymmetric, complex non-Hermitian, real symmetric positive definite and complex Hermitian positive definite systems. Further direct methods may be found in Chapters F01, F04 and F07.

2.3 Iterative Methods

In contrast to the direct methods discussed in Section 2.2, iterative methods for (1) approach the solution through a sequence of approximations until some user-specified termination criterion is met or until some predefined maximum number of iterations has been reached. The number of iterations required for convergence is not generally known in advance, as it depends on the accuracy required, and on the matrix A – its sparsity pattern, conditioning and eigenvalue spectrum.
Faster convergence can often be achieved using a preconditioner (see Golub and Van Loan (1996) and Barrett et al. (1994)). A preconditioner maps the original system of equations onto a different system
A-x-=b-, (2)
which hopefully exhibits better convergence characteristics. For example, the condition number of the matrix A- may be better than that of A, or it may have eigenvalues of greater multiplicity.
An unsuitable preconditioner or no preconditioning at all may result in a very slow rate or lack of convergence. However, preconditioning involves a trade-off between the reduction in the number of iterations required for convergence and the additional computational costs per iteration. Setting up a preconditioner may also involve non-negligible overheads. The application of preconditioners to real nonsymmetric, complex non-Hermitian, real symmetric and complex Hermitian and real symmetric systems of equations is further considered in Sections 2.4 and 2.5.

2.4 Iterative Methods for Real Nonsymmetric and Complex Non-Hermitian Linear Systems

Many of the most effective iterative methods for the solution of (1) lie in the class of non-stationary Krylov subspace methods (see Barrett et al. (1994)). For real nonsymmetric and complex non-Hermitian matrices this class includes:
  • the restarted generalized minimum residual (RGMRES) method (see Saad and Schultz (1986));
  • the conjugate gradient squared (CGS) method (see Sonneveld (1989));
  • the polynomial stabilized bi-conjugate gradient (Bi-CGSTABℓ) method (see Van der Vorst (1989) and Sleijpen and Fokkema (1993));
  • the transpose-free quasi-minimal residual method (TFQMR) (see Freund and Nachtigal (1991) and Freund (1993)).
Here we just give a brief overview of these algorithms as implemented in this chapter. For full details see the routine documents for F11BDF and F11BRF.
RGMRES is based on the Arnoldi method, which explicitly generates an orthogonal basis for the Krylov subspace span Ak r 0, k=0,1,2,…, where r 0 is the initial residual. The solution is then expanded onto the orthogonal basis so as to minimize the residual norm. For real nonsymmetric and complex non-Hermitian matrices the generation of the basis requires a ‘long’ recurrence relation, resulting in prohibitive computational and storage costs. RGMRES limits these costs by restarting the Arnoldi process from the latest available residual every m iterations. The value of m is chosen in advance and is fixed throughout the computation. Unfortunately, an optimum value of m cannot easily be predicted.
CGS is a development of the bi-conjugate gradient method where the nonsymmetric Lanczos method is applied to reduce the coefficient matrix to tridiagonal form: two bi-orthogonal sequences of vectors are generated starting from the initial residual r 0 and from the shadow residual r^0 corresponding to the arbitrary problem AH x^=b^, where b^ is chosen so that r 0=r^0. In the course of the iteration, the residual and shadow residual ri=Pi A r 0 and r^i=Pi AH r^0 are generated, where Pi is a polynomial of order i, and bi-orthogonality is exploited by computing the vector product ρ i = r ^ i , r i = Pi AH r ^ 0 P i A r 0 = r ^ 0 , P i 2 A r 0 . Applying the ‘contraction’ operator Pi A twice, the iteration coefficients can still be recovered without advancing the solution of the shadow problem, which is of no interest. The CGS method often provides fast convergence; however, there is no reason why the contraction operator should also reduce the once reduced vector Pi A r 0: this can lead to a highly irregular convergence.
Bi-CGSTABℓ is similar to the CGS method. However, instead of generating the sequence Pi 2 A r 0, it generates the sequence Qi A Pi A r 0 where the Qi A are polynomials chosen to minimize the residual after the application of the contraction operator Pi A. Two main steps can be identified for each iteration: an OR (Orthogonal Residuals) step where a basis of order ℓ is generated by a Bi-CG iteration and an MR (Minimum Residuals) step where the residual is minimized over the basis generated, by a method similar to GMRES. For ℓ=1, the method corresponds to the Bi-CGSTAB method of Van der Vorst (1989). For ℓ>1, more information about complex eigenvalues of the iteration matrix can be taken into account, and this may lead to improved convergence and robustness. However, as ℓ increases, numerical instabilities may arise.
The transpose-free quasi-minimal residual method (TFQMR) (see Freund and Nachtigal (1991) and Freund (1993)) is conceptually derived from the CGS method. The residual is minimized over the space of the residual vectors generated by the CGS iterations under the simplifying assumption that residuals are almost orthogonal. In practice, this is not the case but theoretical analysis has proved the validity of the method. This has the effect of remedying the rather irregular convergence behaviour with wild oscillations in the residual norm that can degrade the numerical performance and robustness of the CGS method. In general, the TFQMR method can be expected to converge at least as fast as the CGS method, in terms of number of iterations, although each iteration involves a higher operation count. When the CGS method exhibits irregular convergence, the TFQMR method can produce much smoother, almost monotonic convergence curves. However, the close relationship between the CGS and TFQMR method implies that the overall speed of convergence is similar for both methods. In some cases, the TFQMR method may converge faster than the CGS method.
Faster convergence can usually be achieved by using a preconditioner. A left preconditioner M-1 can be used by the RGMRES, CGS and TFQMR methods, such that A-=M-1 A∼In in (2), where In is the identity matrix of order n; a right preconditioner M-1 can be used by the Bi-CGSTABℓ method, such that A-=A M-1∼In. These are formal definitions, used only in the design of the algorithms; in practice, only the means to compute the matrix-vector products v=Au and v=AH u (the latter only being required when an estimate of A 1 or A∞ is computed internally), and to solve the preconditioning equations Mv=u are required, that is, explicit information about M, or its inverse is not required at any stage.
Preconditioning matrices M are typically based on incomplete factorizations (see Meijerink and Van der Vorst (1981)), or on the approximate inverses occurring in stationary iterative methods (see Young (1971)). A common example is the incomplete LU factorization
M=PLDUQ=A-R
where L is lower triangular with unit diagonal elements, D is diagonal, U is upper triangular with unit diagonals, P and Q are permutation matrices, and R is a remainder matrix. A zero-fill incomplete LU factorization is one for which the matrix
S=P L+D+U Q
has the same pattern of nonzero entries as A. This is obtained by discarding any fill elements (nonzero elements of S arising during the factorization in locations where A has zero elements). Allowing some of these fill elements to be kept rather than discarded generally increases the accuracy of the factorization at the expense of some loss of sparsity. For further details see Barrett et al. (1994).

2.5 Iterative Methods for Real Symmetric and Complex Hermitian Linear Systems

Three of the best known iterative methods applicable to real symmetric and complex Hermitian linear systems are the conjugate gradient (CG) method (see Hestenes and Stiefel (1952) and Golub and Van Loan (1996)) and Lanczos type methods based on SYMMLQ and MINRES (see Paige and Saunders (1975)). The description of these methods given below is for the real symmetric cases. The generalization to complex Hermitian matrices is straightforward.
For the CG method the matrix A should ideally be positive definite. The application of CG to indefinite matrices may lead to failure, or to lack of convergence. The SYMMLQ and MINRES methods are suitable for both positive definite and indefinite symmetric matrices. They are more robust than CG, but less efficient when A is positive definite.
The methods start from the residual r 0=b-A x 0, where x 0 is an initial estimate for the solution (often x 0=0), and generate an orthogonal basis for the Krylov subspace span Ak r 0, for k=0,1,…, by means of three-term recurrence relations (see Golub and Van Loan (1996)). A sequence of symmetric tridiagonal matrices Tk is also generated. Here and in the following, the index k denotes the iteration count. The resulting symmetric tridiagonal systems of equations are usually more easily solved than the original problem. A sequence of solution iterates xk is thus generated such that the sequence of the norms of the residuals rk converges to a required tolerance. Note that, in general, the convergence is not monotonic.
In exact arithmetic, after n iterations, this process is equivalent to an orthogonal reduction of A to symmetric tridiagonal form, Tn=QT AQ; the solution xn would thus achieve exact convergence. In finite-precision arithmetic, cancellation and round-off errors accumulate causing loss of orthogonality. These methods must therefore be viewed as genuinely iterative methods, able to converge to a solution within a prescribed tolerance.
The orthogonal basis is not formed explicitly in either method. The basic difference between the methods lies in the method of solution of the resulting symmetric tridiagonal systems of equations: the CG method is equivalent to carrying out an LD LT (Cholesky) factorization whereas the Lanczos method (SYMMLQ) uses an LQ factorization. The MINRES method on the other hand minimizes the residual into 2-norm.
A preconditioner for these methods must be symmetric and positive definite, i.e., representable by M=E ET, where M is nonsingular, and such that A-=E-1 A E-T∼In in (2), where In is the identity matrix of order n. These are formal definitions, used only in the design of the algorithms; in practice, only the means to compute the matrix-vector products v=Au and to solve the preconditioning equations Mv=u are required.
Preconditioning matrices M are typically based on incomplete factorizations (see Meijerink and Van der Vorst (1977)), or on the approximate inverses occurring in stationary iterative methods (see Young (1971)). A common example is the incomplete Cholesky factorization
M=PLD LTPT=A-R
where P is a permutation matrix, L is lower triangular with unit diagonal elements, D is diagonal and R is a remainder matrix. A zero-fill incomplete Cholesky factorization is one for which the matrix
S=P L+D+LT PT
has the same pattern of nonzero entries as A. This is obtained by discarding any fill elements (nonzero elements of S arising during the factorization in locations where A has zero elements). Allowing some of these fill elements to be kept rather than discarded generally increases the accuracy of the factorization at the expense of some loss of sparsity. For further details see Barrett et al. (1994).

3 Recommendations on Choice and Use of Available Routines

3.1 Types of Routine Available

The direct method routines available in this chapter largely follow the LAPACK scheme in that four different routines separately handle the tasks of factorizing, solving, refining and condition number estimating. See Section 3.4.
The iterative method routines available in this chapter divide essentially into three types: basic routines, utility routines and Black Box routines.
Basic routines are grouped in suites of three, and implement the underlying iterative method. Each suite comprises a setup routine, a solver, and a routine to return additional information. The solver routine is independent of the matrix storage format (indeed the matrix need not be stored at all) and the type of preconditioner. It uses reverse communication (see Section 3.3.3 in How to Use the NAG Library and its Documentation for further information), i.e., it returns repeatedly to the calling program with the argument IREVCM set to specified values which require the calling program to carry out a specific task (either to compute a matrix-vector product or to solve the preconditioning equation), to signal the completion of the computation or to allow the calling program to monitor the solution. Reverse communication has the following advantages.
(i) | Maximum flexibility in the representation and storage of sparse matrices. All matrix operations are performed outside the solver routine, thereby avoiding the need for a complicated interface with enough flexibility to cope with all types of storage schemes and sparsity patterns. This also applies to preconditioners.
(ii) | Enhanced user interaction: you can closely monitor the solution and tidy or immediate termination can be requested. This is useful, for example, when alternative termination criteria are to be employed or in case of failure of the external routines used to perform matrix operations.
At present there are suites of basic routines for real symmetric and nonsymmetric systems, and for complex Hermitian and non-Hermitian systems.
Utility routines perform such tasks as initializing the preconditioning matrix M, solving linear systems involving M, or computing matrix-vector products, for particular preconditioners and matrix storage formats. Used in combination, basic routines and utility routines therefore provide iterative methods with a considerable degree of flexibility, allowing you to select from different termination criteria, monitor the approximate solution, and compute various diagnostic parameters. The tasks of computing the matrix-vector products and dealing with the preconditioner are removed from you, but at the expense of sacrificing some flexibility in the choice of preconditioner and matrix storage format.
Black Box routines call basic and utility routines in order to provide easy-to-use routines for particular preconditioners and sparse matrix storage formats. They are much less flexible than the basic routines, but do not use reverse communication, and may be suitable in many simple cases.
The structure of this chapter has been designed to cater for as many types of application as possible. If a Black Box routine exists which is suitable for a given application you are recommended to use it. If you then decide you need some additional flexibility it is easy to achieve this by using basic and utility routines which reproduce the algorithm used in the Black Box, but allow more access to algorithmic control parameters and monitoring. If you wish to use a preconditioner or storage format for which no utility routines are provided, you must call basic routines, and provide your own utility routines.

3.2 Iterative Methods for Real Nonsymmetric and Complex Non-Hermitian Linear Systems

The suite of basic routines F11BDF, F11BEF and F11BFF implements either RGMRES, CGS, Bi-CGSTABℓ, or TFQMR, for the iterative solution of the real sparse nonsymmetric linear system Ax=b. These routines allow a choice of termination criteria and the norms used in them, allow monitoring of the approximate solution, and can return estimates of the norm of A and the largest singular value of the preconditioned matrix A-.
In general, it is not possible to recommend one of these methods (RGMRES, CGS, Bi-CGSTABℓ, or TFQMR) in preference to another. RGMRES is popular, but requires the most storage, and can easily stagnate when the size m of the orthogonal basis is too small, or the preconditioner is not good enough. CGS can be the fastest method, but the computed residuals can exhibit instability which may greatly affect the convergence and quality of the solution. Bi-CGSTABℓ seems robust and reliable, but it can be slower than the other methods. TFQMR can be viewed as a more robust variant of the CGS method: it shares the CGS method speed but avoids the CGS fluctuations in the residual, which may give, rise to instability. Some further discussion of the relative merits of these methods can be found in Barrett et al. (1994).
The utility routines provided for real nonsymmetric matrices use the coordinate storage (CS) format described in Section 2.1.1. F11DAF computes a preconditioning matrix based on incomplete LU factorization, and F11DBF solves linear systems involving the preconditioner generated by F11DAF. The amount of fill-in occurring in the incomplete factorization can be controlled by specifying either the level of fill, or the drop tolerance. Partial or complete pivoting may optionally be employed, and the factorization can be modified to preserve row-sums.
F11DFF is a generalization of F11DAF. It computes incomplete LU factorizations on a set of (possibly overlapping) block diagonal matrices, using a prescribed block structure, to provide a block Jacobi or additive Schwartz preconditioner. To solve the linear system defined by the preconditioner generated by F11DFF, a sequence of calls to F11DBF (one for each block) would be required.
F11DDF is similar to F11DBF, but solves linear systems involving the preconditioner corresponding to symmetric successive-over-relaxation (SSOR). The value of the relaxation parameter ω must currently be supplied by you. Automatic procedures for choosing ω will be included in the chapter at a future mark.
F11DKF applies the iterated Jacobi method to a symmetric or nonsymmetric system of linear equations and can be used as a preconditioner. However, the domain of validity of the Jacobi method is rather restricted; you should read the routine document for F11DKF before using it.
F11XAF computes matrix-vector products for real nonsymmetric matrices stored in ordered CS format. An additional utility routine F11ZAF orders the nonzero elements of a real sparse nonsymmetric matrix stored in general CS format. The same routine can be used to convert a matrix from CS format to CCS format.
The Black Box routine F11DCF makes calls to F11BDF, F11BEF, F11BFF, F11DBF and F11XAF, to solve a real sparse nonsymmetric linear system, represented in CS format, using RGMRES, CGS, Bi-CGSTABℓ, or TFQMR, with incomplete LU preconditioning. F11DEF is similar, but has options for no preconditioning, Jacobi preconditioning or SSOR preconditioning. F11DGF is also similar to F11DCF, but uses block Jacobi or additive Schwartz preconditioning.
For complex non-Hermitian sparse matrices there is an equivalent suite of routines. F11BRF, F11BSF and F11BTF are the basic routines which implement the same methods used for real nonsymmetric systems, namely RGMRES, CGS, Bi-CGSTABℓ and TFQMR, for the solution of complex sparse non-Hermitian linear systems. F11DNF and F11DPF are the complex equivalents of F11DAF and F11DBF, respectively, providing facilities for implementing ILU preconditioning. F11DRF and F11DTF implement complex versions of the SSOR and block Jacobi (or additive Schwartz) preconditioners, respectively. F11DXF implements a complex version of the iterated Jacobi preconditioner. Utility routines F11XNF and F11ZNF are provided for computing matrix-vector products and sorting the elements of complex sparse non-Hermitian matrices, respectively. Finally, the Black Box routines F11DQF, F11DSF and F11DUF are complex equivalents of F11DCF, F11DEF and F11DFF, respectively.

3.3 Iterative Methods for Real Symmetric and Complex Hermitian Linear Systems

The suite of basic routines F11GDF, F11GEF and F11GFF implement either the conjugate gradient (CG) method, or a Lanczos method based on SYMMLQ, for the iterative solution of the real sparse symmetric linear system Ax=b. If A is known to be positive definite the CG method should be chosen; the Lanczos method is more robust but less efficient for positive definite matrices. These routines allow a choice of termination criteria and the norms used in them, allow monitoring of the approximate solution, and can return estimates of the norm of A and the largest singular value of the preconditioned matrix A-.
The utility routines provided for real symmetric matrices use the symmetric coordinate storage (SCS) format described in Section 2.1.2. F11JAF computes a preconditioning matrix based on incomplete Cholesky factorization, and F11JBF solves linear systems involving the preconditioner generated by F11JAF. The amount of fill-in occurring in the incomplete factorization can be controlled by specifying either the level of fill, or the drop tolerance. Diagonal Markowitz pivoting may optionally be employed, and the factorization can be modified to preserve row-sums. Additionally, the utility routine F11YEF can be used to discover a row and column permutation that reduces the bandwidth of A.
F11JDF is similar to F11JBF, but solves linear systems involving the preconditioner corresponding to symmetric successive-over-relaxation (SSOR). The value of the relaxation parameter ω must currently be supplied by you. Automatic procedures for choosing ω will be included in the chapter at a future mark.
F11DKF applies the iterated Jacobi method to a symmetric or nonsymmetric system of linear equations and can be used as a preconditioner. However, the domain of validity of the Jacobi method is rather restricted; you should read the routine document for F11DKF before using it.
F11XEF computes matrix-vector products for real symmetric matrices stored in ordered SCS format. An additional utility routine F11ZBF orders the nonzero elements of a real sparse symmetric matrix stored in general SCS format.
The Black Box routine F11JCF makes calls to F11GDF, F11GEF, F11GFF, F11JBF and F11XEF, to solve a real sparse symmetric linear system, represented in SCS format, using a conjugate gradient or Lanczos method, with incomplete Cholesky preconditioning. F11JEF is similar, but has options for no preconditioning, Jacobi preconditioning or SSOR preconditioning.
For complex Hermitian sparse matrices there is an equivalent suite of routines. F11GRF, F11GSF and F11GTF are the basic routines which implement the same methods used for real symmetric systems, namely CG and SYMMLQ, for the solution of complex sparse Hermitian linear systems. F11JNF and F11JPF are the complex equivalents of F11JAF and F11JBF, respectively, providing facilities for implementing incomplete Cholesky preconditioning. F11JRF implements a complex version of the SSOR preconditioner. F11DXF implements a complex version of the iterated Jacobi preconditioner. Utility routines F11XSF and F11ZPF are provided for computing matrix-vector products and sorting the elements of complex sparse Hermitian matrices, respectively. Finally, the Black Box routines F11JQF and F11JSF provide easy-to-use implementations of the CG and SYMMLQ methods for complex Hermitian linear systems.

3.4 Direct Methods

The suite of routines F11MDF, F11MEF, F11MFF, F11MGF, F11MHF, F11MKF, F11MLF and F11MMF implement the COLAMD/SuperLU direct real sparse solver and associated utilities. You are expected to first call F11MDF to compute a suitable column permutation for the subsequent factorization by F11MEF. F11MFF then solves the system of equations. A solution can be further refined by F11MHF, which also minimizes the backward error and estimates a bound for the forward error in the solution. Diagnostics are provided by F11MGF which computes an estimate of the condition number of the matrix using the factorization output by F11MEF, and F11MMF which computes the reciprocal pivot growth (a numerical stability measure) of the factorization. The two utility routines, F11MKF, which computes matrix-matrix products in the particular storage scheme demanded by the suite (CCS format), and F11MLF which computes quantities relating to norms of a matrix in that particular storage scheme, complete the suite.
Another way of computing a direct solution is to choose specific arguments for the indirect solvers. For example, routine F11DBF solves a linear system involving the incomplete LU preconditioning matrix
M=PLDUQ=A-R
generated by F11DAF, where P and Q are permutation matrices, L is lower triangular with unit diagonal elements, U is upper triangular with unit diagonal elements, D is diagonal and R is a remainder matrix.
If A is nonsingular, a call to F11DAF with LFILL<0 and DTOL=0.0 results in a zero remainder matrix R and a complete factorization. A subsequent call to F11DBF will therefore result in a direct method for real sparse nonsymmetric systems.
If A is known to be symmetric positive definite, F11JAF and F11JBF may similarly be used to give a direct solution. For further details see Section 9.4 in F11JAF.
Complex non-Hermitian systems can be solved directly in the same way using F11DNF and F11DPF, while for complex Hermitian systems F11JNF and F11JPF may be used.
Some other routines specifically designed for direct solution of sparse linear systems can currently be found in Chapters F01, F04 and F07. In particular, the following routines allow the direct solution of nonsymmetric systems:
Almost block-diagonal | F01LHF and F04LHF
Sparse | F01BRF (or F01BSF) and F04AXF
and the following routines allow the direct solution of symmetric positive definite systems:
Variable band (skyline) F01MCF and F04MCF
Routines for the solution of band and tridiagonal systems can be found in Chapters F04 and F07.

4 Decision Tree

Tree 1: Solvers

Do you have a real system and want to use a direct method? |  |  | F11MDF, F11MEF and F11MFF
 |  | yes
 | no |
Do you want to use your own storage scheme or preconditioner? |  |  | complex system? |  |  | Hermitian? |  |  | F11GRF, F11GSF and F11GTF
 |  | yes |  |  | yes |  |  | yes
 | no |  |  | no |  |  | no |
 |  |  |  |  |  | F11BRF, F11BSF and F11BTF
 |  |  | symmetric? |  |  | F11GDF, F11GEF and F11GFF
 |  |  |  |  | yes
 |  |  |  | no |
 |  |  | F11BDF, F11BEF and F11BFF
complex system? |  |  | Hermitian positive definite? |  |  | Incomplete Cholesky preconditioner? |  |  | F11JNF and F11JPF
 |  | yes |  |  | yes |  |  | yes
 | no |  |  | no |  |  | no |
 |  |  |  |  |  | F11JSF
 |  |  | Incomplete LU preconditioner? |  |  | Using (possibly overlapping) diagonal blocks? |  |  | F11DTF and F11DUF
 |  |  |  |  | yes |  |  | yes
 |  |  |  | no |  |  | no |
 |  |  |  |  |  | F11DNF and F11DQF
 |  |  | F11DSF
symmetric positive definite? |  |  | Incomplete Cholesky preconditioner? |  |  | F11JAF and F11JCF
 |  | yes |  |  | yes
 | no |  |  | no |
 |  |  | F11JEF
Incomplete LU preconditioner? |  |  | Using (possibly overlapping) diagonal blocks? |  |  | F11DFF and F11DGF
 |  | yes |  |  | yes
 | no |  |  | no |
 |  |  | F11DAF and F11DCF
F11DEF

5 Functionality Index

Basic routines for complex Hermitian linear systems,
diagnostic routine F11GTF
reverse communication CG or SYMMLQ solver routine F11GSF
setup routine F11GRF
Basic routines for complex non-Hermitian linear systems,
diagnostic routine F11BTF
reverse communication RGMRES, CGS, Bi-CGSTAB(ℓ) or TFQMR solver routine F11BSF
setup routine F11BRF
Basic routines for real nonsymmetric linear systems,
diagnostic routine F11BFF
reverse communication RGMRES, CGS, Bi-CGSTAB(ℓ) or TFQMR solver routine F11BEF
setup routine F11BDF
Basic routines for real symmetric linear systems,
diagnostic routine F11GFF
reverse communication CG or SYMMLQ solver F11GEF
setup routine F11GDF
Black Box routines for complex Hermitian linear systems,
CG or SYMMLQ solver,
with incomplete Cholesky preconditioning F11JQF
with no preconditioning, Jacobi or SSOR preconditioning F11JSF
Black Box routines for complex non-Hermitian linear systems,
RGMRES, CGS, Bi-CGSTAB(ℓ) or TFQMR solver,
with block Jacobi or additive Schwarz preconditioning F11DUF
with incomplete LU preconditioning F11DQF
with no preconditioning, Jacobi, or SSOR preconditioning F11DSF
Black Box routines for real nonsymmetric linear systems,
RGMRES, CGS, Bi-CGSTAB(ℓ) or TFQMR solver,
with block Jacobi or additive Schwarz preconditioning F11DGF
with incomplete LU preconditioning F11DCF
with no preconditioning, Jacobi, or SSOR preconditioning F11DEF
Black Box routines for real symmetric linear systems,
CG or SYMMLQ solver,
with incomplete Cholesky preconditioning F11JCF
with no preconditioning, Jacobi, or SSOR preconditioning F11JEF
Direct methods for real sparse nonsymmetric linear systems in CCS format,
apply iterative refinement to the solution and compute error estimates, after factorizing the matrix of coefficients F11MHF
condition number estimation, after factorizing the matrix of coefficients, F11MGF
LU factorization,
diagnostic F11MMF
factorize F11MEF
setup F11MDF
solution of simultaneous linear equations, after factorizing the matrix of coefficients, F11MFF
utility,
compute a norm or the element of largest absolute value, F11MLF
matrix-matrix multiplier F11MKF
Utility routine for complex Hermitian linear systems,
incomplete Cholesky factorization F11JNF
matrix-vector multiplier for complex Hermitian matrices in SCS format F11XSF
solver for linear systems involving preconditioning matrix from F11JNF F11JPF
solver for linear systems involving SSOR preconditioning matrix F11JRF
sort routine for complex Hermitian matrices in SCS format F11ZPF
Utility routine for complex linear systems,
solver for linear systems involving iterated Jacobi method F11DXF
Utility routine for complex non-Hermitian linear systems,
incomplete LU factorization F11DNF
incomplete LU factorization of local or overlapping diagonal blocks F11DTF
matrix-vector multiplier for complex non-Hermitian matrices in CS format F11XNF
solver for linear systems involving preconditioning matrix from F11DNF F11DPF
solver for linear systems involving SSOR preconditioning matrix F11DRF
sort routine for complex non-Hermitian matrices in CS format F11ZNF
Utility routine for real linear systems,
solver for linear systems involving iterated Jacobi method F11DKF
Utility routine for real nonsymmetric linear systems,
incomplete LU factorization F11DAF
incomplete LU factorization of local or overlapping diagonal blocks F11DFF
matrix-vector multiplier for real nonsymmetric matrices in CS format F11XAF
solver for linear systems involving preconditioning matrix from F11DAF F11DBF
solver for linear systems involving SSOR preconditioning matrix F11DDF
sort routine for real nonsymmetric matrices in CS format F11ZAF
Utility routine for real symmetric linear systems,
incomplete Cholesky factorization F11JAF
matrix-vector multiplier for real symmetric matrices in SCS format F11XEF
solver for linear systems involving preconditioning matrix from F11JAF F11JBF
solver for linear systems involving SSOR preconditioning matrix F11JDF
sort routine for real symmetric matrices in SCS format F11ZBF
Utility routine for real symmetric linear systems, compute bandwidth-reducing reverse Cuthill–McKee permutation F11YEF

6 Auxiliary Routines Associated with Library Routine Arguments

None.

7 Routines Withdrawn or Scheduled for Withdrawal

The following lists all those routines that have been withdrawn since Mark 19 of the Library or are scheduled for withdrawal at one of the next two marks.
Withdrawn Routine | Mark of Withdrawal | Replacement Routine(s)
F11BAF | 21 | F11BDF
F11BBF | 21 | F11BEF
F11BCF | 21 | F11BFF
F11GAF | 22 | F11GDF
F11GBF | 22 | F11GEF
F11GCF | 22 | F11GFF

8 References

Barrett R, Berry M, Chan T F, Demmel J, Donato J, Dongarra J, Eijkhout V, Pozo R, Romine C and Van der Vorst H (1994) Templates for the Solution of Linear Systems: Building Blocks for Iterative Methods SIAM, Philadelphia
Demmel J W, Eisenstat S C, Gilbert J R, Li X S and Li J W H (1999) A supernodal approach to sparse partial pivoting SIAM J. Matrix Anal. Appl. 20 720–755
Duff I S, Erisman A M and Reid J K (1986) Direct Methods for Sparse Matrices Oxford University Press, London
Freund R W (1993) A transpose-free quasi-minimal residual algorithm for non-Hermitian linear systems SIAM J. Sci. Comput. 14 470–482
Freund R W and Nachtigal N (1991) QMR: a Quasi-Minimal Residual Method for Non-Hermitian Linear Systems Numer. Math. 60 315–339
Golub G H and Van Loan C F (1996) Matrix Computations (3rd Edition) Johns Hopkins University Press, Baltimore
Hestenes M and Stiefel E (1952) Methods of conjugate gradients for solving linear systems J. Res. Nat. Bur. Stand. 49 409–436
Meijerink J and Van der Vorst H (1977) An iterative solution method for linear systems of which the coefficient matrix is a symmetric M-matrix Math. Comput. 31 148–162
Meijerink J and Van der Vorst H (1981) Guidelines for the usage of incomplete decompositions in solving sets of linear equations as they occur in practical problems J. Comput. Phys. 44 134–155
Paige C C and Saunders M A (1975) Solution of sparse indefinite systems of linear equations SIAM J. Numer. Anal. 12 617–629
Saad Y and Schultz M (1986) GMRES: a generalized minimal residual algorithm for solving nonsymmetric linear systems SIAM J. Sci. Statist. Comput. 7 856–869
Sleijpen G L G and Fokkema D R (1993) BiCGSTABℓ for linear equations involving matrices with complex spectrum ETNA 1 11–32
Sonneveld P (1989) CGS, a fast Lanczos-type solver for nonsymmetric linear systems SIAM J. Sci. Statist. Comput. 10 36–52
Van der Vorst H (1989) Bi-CGSTAB, a fast and smoothly converging variant of Bi-CG for the solution of nonsymmetric linear systems SIAM J. Sci. Statist. Comput. 13 631–644
Young D (1971) Iterative Solution of Large Linear Systems Academic Press, New York
F11 Chapter Contents
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F11JAF : NAG Library, Mark 26

F11 Chapter Contents
F11 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F11JAF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
▸▿ 9 Further Comments
9.1 Timing
9.2 Control of Fill-in
9.3 Choice of Arguments
9.4 Direct Solution of positive definite Systems
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F11JAF computes an incomplete Cholesky factorization of a real sparse symmetric matrix, represented in symmetric coordinate storage format. This factorization may be used as a preconditioner in combination with F11GEF or F11JCF.

2 Specification

SUBROUTINE F11JAF ( N, NNZ, A, LA, IROW, ICOL, LFILL, DTOL, MIC, DSCALE, PSTRAT, IPIV, ISTR, NNZC, NPIVM, IWORK, LIWORK, IFAIL)
INTEGER | N, NNZ, LA, IROW(LA), ICOL(LA), LFILL, IPIV(N), ISTR(N+1), NNZC, NPIVM, IWORK(LIWORK), LIWORK, IFAIL
REAL (KIND=nag_wp) | A(LA), DTOL, DSCALE
CHARACTER(1) | MIC, PSTRAT

3 Description

F11JAF computes an incomplete Cholesky factorization (see Meijerink and Van der Vorst (1977)) of a real sparse symmetric n by n matrix A. It is designed specifically for positive definite matrices, but may also work for some mildly indefinite cases. The factorization is intended primarily for use as a preconditioner with one of the symmetric iterative solvers F11GEF or F11JCF.
The decomposition is written in the form
A=M+R
where
M=PLD LTPT
and P is a permutation matrix, L is lower triangular with unit diagonal elements, D is diagonal and R is a remainder matrix.
The amount of fill-in occurring in the factorization can vary from zero to complete fill, and can be controlled by specifying either the maximum level of fill LFILL, or the drop tolerance DTOL. The factorization may be modified in order to preserve row sums, and the diagonal elements may be perturbed to ensure that the preconditioner is positive definite. Diagonal pivoting may optionally be employed, either with a user-defined ordering, or using the Markowitz strategy (see Markowitz (1957)), which aims to minimize fill-in. For further details see Section 9.
The sparse matrix A is represented in symmetric coordinate storage (SCS) format (see Section 2.1.2 in the F11 Chapter Introduction). The array A stores all the nonzero elements of the lower triangular part of A, while arrays IROW and ICOL store the corresponding row and column indices respectively. Multiple nonzero elements may not be specified for the same row and column index.
The preconditioning matrix M is returned in terms of the SCS representation of the lower triangular matrix
C=L+D-1-I.

4 References

Chan T F (1991) Fourier analysis of relaxed incomplete factorization preconditioners SIAM J. Sci. Statist. Comput. 12(2) 668–680
Markowitz H M (1957) The elimination form of the inverse and its application to linear programming Management Sci. 3 255–269
Meijerink J and Van der Vorst H (1977) An iterative solution method for linear systems of which the coefficient matrix is a symmetric M-matrix Math. Comput. 31 148–162
Salvini S A and Shaw G J (1995) An evaluation of new NAG Library solvers for large sparse symmetric linear systems NAG Technical Report TR1/95
Van der Vorst H A (1990) The convergence behaviour of preconditioned CG and CG-S in the presence of rounding errors Lecture Notes in Mathematics (eds O Axelsson and L Y Kolotilina) 1457 Springer–Verlag

5 Arguments

1:   N – INTEGERInput
On entry: n, the order of the matrix A.
Constraint: N≥1.
2:   NNZ – INTEGERInput
On entry: the number of nonzero elements in the lower triangular part of the matrix A.
Constraint: 1≤NNZ≤N×N+1/2.
3:   A LA – REAL (KIND=nag_wp) arrayInput/Output
On entry: the nonzero elements in the lower triangular part of the matrix A, ordered by increasing row index, and by increasing column index within each row. Multiple entries for the same row and column indices are not permitted. The routine F11ZBF may be used to order the elements in this way.
On exit: the first NNZ elements of A contain the nonzero elements of A and the next NNZC elements contain the elements of the lower triangular matrix C. Matrix elements are ordered by increasing row index, and by increasing column index within each row.
4:   LA – INTEGERInput
On entry: the dimension of the arrays A, IROW and ICOL as declared in the (sub)program from which F11JAF is called. These arrays must be of sufficient size to store both A (NNZ elements) and C (NNZC elements).
Constraint: LA≥2×NNZ.
5:   IROW LA – INTEGER arrayInput/Output
6:   ICOL LA – INTEGER arrayInput/Output
On entry: the row and column indices of the nonzero elements supplied in A.
Constraints:
IROW and ICOL must satisfy these constraints (which may be imposed by a call to F11ZBF):
  • 1≤IROW i≤N and 1≤ICOL i≤IROW i, for i=1,2,…,NNZ;
  • IROW i-1<IROW i or IROW i-1=IROW i and ICOL i-1<ICOL i, for i=2,3,…,NNZ.
On exit: the row and column indices of the nonzero elements returned in A.
7:   LFILL – INTEGERInput
On entry: if LFILL≥0 its value is the maximum level of fill allowed in the decomposition (see Section 9.2). A negative value of LFILL indicates that DTOL will be used to control the fill instead.
8:   DTOL – REAL (KIND=nag_wp)Input
On entry: if LFILL<0, DTOL is used as a drop tolerance to control the fill-in (see Section 9.2); otherwise DTOL is not referenced.
Constraint: if LFILL<0, DTOL≥0.0.
9:   MIC – CHARACTER(1)Input
On entry: indicates whether or not the factorization should be modified to preserve row sums (see Section 9.3).
MIC='M'
The factorization is modified.
MIC='N'
The factorization is not modified.
Constraint: MIC='M' or 'N'.
10:   DSCALE – REAL (KIND=nag_wp)Input
On entry: the diagonal scaling parameter. All diagonal elements are multiplied by the factor (1+DSCALE) at the start of the factorization. This can be used to ensure that the preconditioner is positive definite. See Section 9.3.
11:   PSTRAT – CHARACTER(1)Input
On entry: specifies the pivoting strategy to be adopted.
PSTRAT='N'
No pivoting is carried out.
PSTRAT='M'
Diagonal pivoting aimed at minimizing fill-in is carried out, using the Markowitz strategy.
PSTRAT='U'
Diagonal pivoting is carried out according to the user-defined input value of IPIV.
Suggested value: PSTRAT='M'.
Constraint: PSTRAT='N', 'M' or 'U'.
12:   IPIV N – INTEGER arrayInput/Output
On entry: if PSTRAT='U', then IPIV i must specify the row index of the diagonal element used as a pivot at elimination stage i. Otherwise IPIV need not be initialized.
Constraint: if PSTRAT='U', IPIV must contain a valid permutation of the integers on [1,N].
On exit: the pivot indices. If IPIV i=j then the diagonal element in row j was used as the pivot at elimination stage i.
13:   ISTR N+1 – INTEGER arrayOutput
On exit: ISTR i, for i=1,2,…,N, is the starting address in the arrays A, IROW and ICOL of row i of the matrix C. ISTR N+1 is the address of the last nonzero element in C plus one.
14:   NNZC – INTEGEROutput
On exit: the number of nonzero elements in the lower triangular matrix C.
15:   NPIVM – INTEGEROutput
On exit: the number of pivots which were modified during the factorization to ensure that M was positive definite. The quality of the preconditioner will generally depend on the returned value of NPIVM. If NPIVM is large the preconditioner may not be satisfactory. In this case it may be advantageous to call F11JAF again with an increased value of either LFILL or DSCALE. See also Section 9.4.
16:   IWORK LIWORK – INTEGER arrayWorkspace
17:   LIWORK – INTEGERInput
On entry: the dimension of the array IWORK as declared in the (sub)program from which F11JAF is called.
Constraints:
the minimum permissible value of LIWORK depends on LFILL as follows:
  • if LFILL≥0, LIWORK≥2×LA-3×NNZ+7×N+1;
  • if LFILL<0, LIWORK≥LA-NNZ+7×N+1.
18:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, | N<1,
or | NNZ<1,
or | NNZ>N×N+1/2,
or | LA<2×NNZ,
or | DTOL<0.0,
or | MIC≠'M' or 'N',
or | PSTRAT≠'N', 'M' or 'U',
or | LIWORK<2×LA-3×NNZ+7×N+1, and LFILL≥0,
or | LIWORK<LA-NNZ+7×N+1, and LFILL<0.
IFAIL=2
On entry, the arrays IROW and ICOL fail to satisfy the following constraints:
  • 1≤IROW i≤N and 1≤ICOL i≤IROW i, for i=1,2,…,NNZ;
  • IROW i-1<IROW i, or IROW i-1=IROW i and ICOL i-1<ICOL i, for i=2,3,…,NNZ.
Therefore a nonzero element has been supplied which does not lie in the lower triangular part of A, is out of order, or has duplicate row and column indices. Call F11ZBF to reorder and sum or remove duplicates.
IFAIL=3
On entry, PSTRAT='U', but IPIV does not represent a valid permutation of the integers in 1,N. An input value of IPIV is either out of range or repeated.
IFAIL=4
LA is too small, resulting in insufficient storage space for fill-in elements. The decomposition has been terminated before completion. Either increase LA or reduce the amount of fill by setting PSTRAT='M', reducing LFILL, or increasing DTOL.
IFAIL=5 (F11ZBF)
A serious error has occurred in an internal call to the specified routine. Check all subroutine calls and array sizes. Seek expert help.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

The accuracy of the factorization will be determined by the size of the elements that are dropped and the size of any modifications made to the diagonal elements. If these sizes are small then the computed factors will correspond to a matrix close to A. The factorization can generally be made more accurate by increasing LFILL, or by reducing DTOL with LFILL<0.
If F11JAF is used in combination with F11GEF or F11JCF, the more accurate the factorization the fewer iterations will be required. However, the cost of the decomposition will also generally increase.

8 Parallelism and Performance

F11JAF makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

9.1 Timing

The time taken for a call to F11JAF is roughly proportional to NNZC 2/N.

9.2 Control of Fill-in

If LFILL≥0 the amount of fill-in occurring in the incomplete factorization is controlled by limiting the maximum level of fill-in to LFILL. The original nonzero elements of A are defined to be of level 0. The fill level of a new nonzero location occurring during the factorization is defined as
k=max ke,kc+1,
where ke is the level of fill of the element being eliminated, and kc is the level of fill of the element causing the fill-in.
If LFILL<0 the fill-in is controlled by means of the drop tolerance DTOL. A potential fill-in element a ij occurring in row i and column j will not be included if
a ij<DTOL×a iia jj.
For either method of control, any elements which are not included are discarded if MIC='N', or subtracted from the diagonal element in the elimination row if MIC='M'.

9.3 Choice of Arguments

There is unfortunately no choice of the various algorithmic arguments which is optimal for all types of symmetric matrix, and some experimentation will generally be required for each new type of matrix encountered.
If the matrix A is not known to have any particular special properties the following strategy is recommended. Start with LFILL=0, MIC='N' and DSCALE=0.0. If the value returned for NPIVM is significantly larger than zero, i.e., a large number of pivot modifications were required to ensure that M was positive definite, the preconditioner is not likely to be satisfactory. In this case increase either LFILL or DSCALE until NPIVM falls to a value close to zero. Once suitable values of LFILL and DSCALE have been found try setting MIC='M' to see if any improvement can be obtained by using modified incomplete Cholesky.
F11JAF is primarily designed for positive definite matrices, but may work for some mildly indefinite problems. If NPIVM cannot be satisfactorily reduced by increasing LFILL or DSCALE then A is probably too indefinite for this routine.
If A has non-positive off-diagonal elements, is nonsingular, and has only non-negative elements in its inverse, it is called an ‘M-matrix’. It can be shown that no pivot modifications are required in the incomplete Cholesky factorization of an M-matrix (see Meijerink and Van der Vorst (1977)). In this case a good preconditioner can generally be expected by setting LFILL=0, MIC='M' and DSCALE=0.0.
For certain mesh-based problems involving M-matrices it can be shown in theory that setting MIC='M', and choosing DSCALE appropriately can reduce the order of magnitude of the condition number of the preconditioned matrix as a function of the mesh steplength (see Chan (1991)). In practise this property often holds even with DSCALE=0.0, although an improvement in condition can result from increasing DSCALE slightly (see Van der Vorst (1990)).
Some illustrations of the application of F11JAF to linear systems arising from the discretization of two-dimensional elliptic partial differential equations, and to random-valued randomly structured symmetric positive definite linear systems, can be found in Salvini and Shaw (1995).

9.4 Direct Solution of positive definite Systems

Although it is not their primary purpose, F11JAF and F11JBF may be used together to obtain a direct solution to a symmetric positive definite linear system. To achieve this the call to F11JBF should be preceded by a complete Cholesky factorization
A=PLD LTPT=M.
A complete factorization is obtained from a call to F11JAF with LFILL<0 and DTOL=0.0, provided NPIVM=0 on exit. A nonzero value of NPIVM indicates that A is not positive definite, or is ill-conditioned. A factorization with nonzero NPIVM may serve as a preconditioner, but will not result in a direct solution. It is therefore essential to check the output value of NPIVM if a direct solution is required.
The use of F11JAF and F11JBF as a direct method is illustrated in Section 10 in F11JBF.

10 Example

This example reads in a symmetric sparse matrix A and calls F11JAF to compute an incomplete Cholesky factorization. It then outputs the nonzero elements of both A and C=L+D-1-I.
The call to F11JAF has LFILL=0, MIC='N', DSCALE=0.0 and PSTRAT='M', giving an unmodified zero-fill factorization of an unperturbed matrix, with Markowitz diagonal pivoting.

10.1 Program Text

Program Text (f11jafe.f90)

10.2 Program Data

Program Data (f11jafe.d)

10.3 Program Results

Program Results (f11jafe.r)

F11 Chapter Contents
F11 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F11JBF : NAG Library, Mark 26

F11 Chapter Contents
F11 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F11JBF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
▸▿ 9 Further Comments
9.1 Timing
9.2 Use of CHECK
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F11JBF solves a system of linear equations involving the incomplete Cholesky preconditioning matrix generated by F11JAF.

2 Specification

SUBROUTINE F11JBF ( N, A, LA, IROW, ICOL, IPIV, ISTR, CHECK, Y, X, IFAIL)
INTEGER | N, LA, IROW(LA), ICOL(LA), IPIV(N), ISTR(N+1), IFAIL
REAL (KIND=nag_wp) | A(LA), Y(N), X(N)
CHARACTER(1) | CHECK

3 Description

F11JBF solves a system of linear equations
Mx=y
involving the preconditioning matrix M=PLD LTPT, corresponding to an incomplete Cholesky decomposition of a sparse symmetric matrix stored in symmetric coordinate storage (SCS) format (see Section 2.1.2 in the F11 Chapter Introduction), as generated by F11JAF.
In the above decomposition L is a lower triangular sparse matrix with unit diagonal, D is a diagonal matrix and P is a permutation matrix. L and D are supplied to F11JBF through the matrix
C=L+D-1-I
which is a lower triangular N by N sparse matrix, stored in SCS format, as returned by F11JAF. The permutation matrix P is returned from F11JAF via the array IPIV.
It is envisaged that a common use of F11JBF will be to carry out the preconditioning step required in the application of F11GEF to sparse symmetric linear systems. F11JBF is used for this purpose by the Black Box routine F11JCF.
F11JBF may also be used in combination with F11JAF to solve a sparse symmetric positive definite system of linear equations directly (see Section 9.4 in F11JAF). This use of F11JBF is demonstrated in Section 10.

4 References

None.

5 Arguments

1:   N – INTEGERInput
On entry: n, the order of the matrix M. This must be the same value as was supplied in the preceding call to F11JAF.
Constraint: N≥1.
2:   A LA – REAL (KIND=nag_wp) arrayInput
On entry: the values returned in the array A by a previous call to F11JAF.
3:   LA – INTEGERInput
On entry: the dimension of the arrays A, IROW and ICOL as declared in the (sub)program from which F11JBF is called. This must be the same value returned by the preceding call to F11JAF.
4:   IROW LA – INTEGER arrayInput
5:   ICOL LA – INTEGER arrayInput
6:   IPIV N – INTEGER arrayInput
7:   ISTR N+1 – INTEGER arrayInput
On entry: the values returned in arrays IROW, ICOL, IPIV and ISTR by a previous call to F11JAF.
8:   CHECK – CHARACTER(1)Input
On entry: specifies whether or not the input data should be checked.
CHECK='C'
Checks are carried out on the values of N, IROW, ICOL, IPIV and ISTR.
CHECK='N'
No checks are carried out.
See also Section 9.2.
Constraint: CHECK='C' or 'N'.
9:   Y N – REAL (KIND=nag_wp) arrayInput
On entry: the right-hand side vector y.
10:   X N – REAL (KIND=nag_wp) arrayOutput
On exit: the solution vector x.
11:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, CHECK≠'C' or 'N'.
IFAIL=2
On entry, N<1.
IFAIL=3
On entry, the SCS representation of the preconditioning matrix M is invalid. Further details are given in the error message. Check that the call to F11JBF has been preceded by a valid call to F11JAF and that the arrays A, IROW, ICOL, IPIV and ISTR have not been corrupted between the two calls.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

The computed solution x is the exact solution of a perturbed system of equations M+δM x=y, where
δM≤c n εP LDLT PT,
c n is a modest linear function of n, and ε is the machine precision.

8 Parallelism and Performance

F11JBF is not threaded in any implementation.

9 Further Comments

9.1 Timing

The time taken for a call to F11JBF is proportional to the value of NNZC returned from F11JAF.

9.2 Use of CHECK

It is expected that a common use of F11JBF will be to carry out the preconditioning step required in the application of F11GEF to sparse symmetric linear systems. In this situation F11JBF is likely to be called many times with the same matrix M. In the interests of both reliability and efficiency, you are recommended to set CHECK='C' for the first of such calls, and to set CHECK='N' for all subsequent calls.

10 Example

This example reads in a symmetric positive definite sparse matrix A and a vector y. It then calls F11JAF, with LFILL=-1 and DTOL=0.0, to compute the complete Cholesky decomposition of A:
A=PLD LTPT.
Then it calls F11JBF to solve the system
PLD LTPT x=y.
It then repeats the exercise for the same matrix permuted with the bandwidth-reducing Reverse Cuthill–McKee permutation, calculated with F11YEF.

10.1 Program Text

Program Text (f11jbfe.f90)

10.2 Program Data

Program Data (f11jbfe.d)

10.3 Program Results

Program Results (f11jbfe.r)

F11 Chapter Contents
F11 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F11JCF : NAG Library, Mark 26

F11 Chapter Contents
F11 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F11JCF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F11JCF solves a real sparse symmetric system of linear equations, represented in symmetric coordinate storage format, using a conjugate gradient or Lanczos method, with incomplete Cholesky preconditioning.

2 Specification

SUBROUTINE F11JCF ( METHOD, N, NNZ, A, LA, IROW, ICOL, IPIV, ISTR, B, TOL, MAXITN, X, RNORM, ITN, WORK, LWORK, IFAIL)
INTEGER | N, NNZ, LA, IROW(LA), ICOL(LA), IPIV(N), ISTR(N+1), MAXITN, ITN, LWORK, IFAIL
REAL (KIND=nag_wp) | A(LA), B(N), TOL, X(N), RNORM, WORK(LWORK)
CHARACTER(*) | METHOD

3 Description

F11JCF solves a real sparse symmetric linear system of equations
Ax=b,
using a preconditioned conjugate gradient method (see Meijerink and Van der Vorst (1977)), or a preconditioned Lanczos method based on the algorithm SYMMLQ (see Paige and Saunders (1975)). The conjugate gradient method is more efficient if A is positive definite, but may fail to converge for indefinite matrices. In this case the Lanczos method should be used instead. For further details see Barrett et al. (1994).
F11JCF uses the incomplete Cholesky factorization determined by F11JAF as the preconditioning matrix. A call to F11JCF must always be preceded by a call to F11JAF. Alternative preconditioners for the same storage scheme are available by calling F11JEF.
The matrix A, and the preconditioning matrix M, are represented in symmetric coordinate storage (SCS) format (see Section 2.1.2 in the F11 Chapter Introduction) in the arrays A, IROW and ICOL, as returned from F11JAF. The array A holds the nonzero entries in the lower triangular parts of these matrices, while IROW and ICOL hold the corresponding row and column indices.

4 References

Barrett R, Berry M, Chan T F, Demmel J, Donato J, Dongarra J, Eijkhout V, Pozo R, Romine C and Van der Vorst H (1994) Templates for the Solution of Linear Systems: Building Blocks for Iterative Methods SIAM, Philadelphia
Meijerink J and Van der Vorst H (1977) An iterative solution method for linear systems of which the coefficient matrix is a symmetric M-matrix Math. Comput. 31 148–162
Paige C C and Saunders M A (1975) Solution of sparse indefinite systems of linear equations SIAM J. Numer. Anal. 12 617–629
Salvini S A and Shaw G J (1995) An evaluation of new NAG Library solvers for large sparse symmetric linear systems NAG Technical Report TR1/95

5 Arguments

1:   METHOD – CHARACTER(*)Input
On entry: specifies the iterative method to be used.
METHOD='CG'
Conjugate gradient method.
METHOD='SYMMLQ'
Lanczos method (SYMMLQ).
Constraint: METHOD='CG' or 'SYMMLQ'.
2:   N – INTEGERInput
On entry: n, the order of the matrix A. This must be the same value as was supplied in the preceding call to F11JAF.
Constraint: N≥1.
3:   NNZ – INTEGERInput
On entry: the number of nonzero elements in the lower triangular part of the matrix A. This must be the same value as was supplied in the preceding call to F11JAF.
Constraint: 1≤NNZ≤N×N+1/2.
4:   A LA – REAL (KIND=nag_wp) arrayInput
On entry: the values returned in the array A by a previous call to F11JAF.
5:   LA – INTEGERInput
On entry: the dimension of the arrays A, IROW and ICOL as declared in the (sub)program from which F11JCF is called. This must be the same value as was supplied in the preceding call to F11JAF.
Constraint: LA≥2×NNZ.
6:   IROW LA – INTEGER arrayInput
7:   ICOL LA – INTEGER arrayInput
8:   IPIV N – INTEGER arrayInput
9:   ISTR N+1 – INTEGER arrayInput
On entry: the values returned in arrays IROW, ICOL, IPIV and ISTR by a previous call to F11JAF.
10:   B N – REAL (KIND=nag_wp) arrayInput
On entry: the right-hand side vector b.
11:   TOL – REAL (KIND=nag_wp)Input
On entry: the required tolerance. Let xk denote the approximate solution at iteration k, and rk the corresponding residual. The algorithm is considered to have converged at iteration k if
rk∞≤τ×b∞+A∞xk∞.
If TOL≤0.0, τ=max⁡ε,10 ε,n ε is used, where ε is the machine precision. Otherwise τ=max TOL,10 ε,n ε is used.
Constraint: TOL<1.0.
12:   MAXITN – INTEGERInput
On entry: the maximum number of iterations allowed.
Constraint: MAXITN≥1.
13:   X N – REAL (KIND=nag_wp) arrayInput/Output
On entry: an initial approximation to the solution vector x.
On exit: an improved approximation to the solution vector x.
14:   RNORM – REAL (KIND=nag_wp)Output
On exit: the final value of the residual norm rk∞, where k is the output value of ITN.
15:   ITN – INTEGEROutput
On exit: the number of iterations carried out.
16:   WORK LWORK – REAL (KIND=nag_wp) arrayWorkspace
17:   LWORK – INTEGERInput
On entry: the dimension of the array WORK as declared in the (sub)program from which F11JCF is called.
Constraints:
  • if METHOD='CG', LWORK≥6×N+120;
  • if METHOD='SYMMLQ', LWORK≥7×N+120.
18:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, | METHOD≠'CG' or 'SYMMLQ',
or | N<1,
or | NNZ<1,
or | NNZ>N×N+1/2,
or | LA too small,
or | TOL≥1.0,
or | MAXITN<1,
or | LWORK too small.
IFAIL=2
On entry, the SCS representation of A is invalid. Further details are given in the error message. Check that the call to F11JCF has been preceded by a valid call to F11JAF, and that the arrays A, IROW, and ICOL have not been corrupted between the two calls.
IFAIL=3
On entry, the SCS representation of the preconditioning matrix M is invalid. Further details are given in the error message. Check that the call to F11JCF has been preceded by a valid call to F11JAF and that the arrays A, IROW, ICOL, IPIV and ISTR have not been corrupted between the two calls.
IFAIL=4
The required accuracy could not be obtained. However, a reasonable accuracy has been obtained and further iterations could not improve the result.
IFAIL=5
Required accuracy not obtained in MAXITN iterations.
IFAIL=6
The preconditioner appears not to be positive definite.
IFAIL=7
The matrix of the coefficients appears not to be positive definite (conjugate gradient method only).
IFAIL=8 (F11GDF, F11GEF or F11GFF)
A serious error has occurred in an internal call to one of the specified routines. Check all subroutine calls and array sizes. Seek expert help.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

On successful termination, the final residual rk=b-A xk, where k=ITN, satisfies the termination criterion
rk∞≤τ×b∞+A∞xk∞.
The value of the final residual norm is returned in RNORM.

8 Parallelism and Performance

F11JCF is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
F11JCF makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The time taken by F11JCF for each iteration is roughly proportional to the value of NNZC returned from the preceding call to F11JAF. One iteration with the Lanczos method (SYMMLQ) requires a slightly larger number of operations than one iteration with the conjugate gradient method.
The number of iterations required to achieve a prescribed accuracy cannot be easily determined a priori, as it can depend dramatically on the conditioning and spectrum of the preconditioned matrix of the coefficients A-=M-1 A.
Some illustrations of the application of F11JCF to linear systems arising from the discretization of two-dimensional elliptic partial differential equations, and to random-valued randomly structured symmetric positive definite linear systems, can be found in Salvini and Shaw (1995).

10 Example

This example solves a symmetric positive definite system of equations using the conjugate gradient method, with incomplete Cholesky preconditioning.

10.1 Program Text

Program Text (f11jcfe.f90)

10.2 Program Data

Program Data (f11jcfe.d)

10.3 Program Results

Program Results (f11jcfe.r)

F11 Chapter Contents
F11 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F11JDF : NAG Library, Mark 26

F11 Chapter Contents
F11 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F11JDF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
▸▿ 9 Further Comments
9.1 Timing
9.2 Use of CHECK
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F11JDF solves a system of linear equations involving the preconditioning matrix corresponding to SSOR applied to a real sparse symmetric matrix, represented in symmetric coordinate storage format.

2 Specification

SUBROUTINE F11JDF ( N, NNZ, A, IROW, ICOL, RDIAG, OMEGA, CHECK, Y, X, IWORK, IFAIL)
INTEGER | N, NNZ, IROW(NNZ), ICOL(NNZ), IWORK(N+1), IFAIL
REAL (KIND=nag_wp) | A(NNZ), RDIAG(N), OMEGA, Y(N), X(N)
CHARACTER(1) | CHECK

3 Description

F11JDF solves a system of equations
Mx=y
involving the preconditioning matrix
M=1 ω 2-ω D+ω L D-1 D+ω L T
corresponding to symmetric successive-over-relaxation (SSOR) (see Young (1971)) on a linear system Ax=b, where A is a sparse symmetric matrix stored in symmetric coordinate storage (SCS) format (see Section 2.1.2 in the F11 Chapter Introduction).
In the definition of M given above D is the diagonal part of A, L is the strictly lower triangular part of A, and ω is a user-defined relaxation parameter.
It is envisaged that a common use of F11JDF will be to carry out the preconditioning step required in the application of F11GEF to sparse linear systems. For an illustration of this use of F11JDF see the example program given in Section 10.1. F11JDF is also used for this purpose by the Black Box routine F11JEF.

4 References

Young D (1971) Iterative Solution of Large Linear Systems Academic Press, New York

5 Arguments

1:   N – INTEGERInput
On entry: n, the order of the matrix A.
Constraint: N≥1.
2:   NNZ – INTEGERInput
On entry: the number of nonzero elements in the lower triangular part of A.
Constraint: 1≤NNZ≤N×N+1/2.
3:   A NNZ – REAL (KIND=nag_wp) arrayInput
On entry: the nonzero elements in the lower triangular part of the matrix A, ordered by increasing row index, and by increasing column index within each row. Multiple entries for the same row and column indices are not permitted. The routine F11ZBF may be used to order the elements in this way.
4:   IROW NNZ – INTEGER arrayInput
5:   ICOL NNZ – INTEGER arrayInput
On entry: the row and column indices of the nonzero elements supplied in array A.
Constraints:
IROW and ICOL must satisfy these constraints (which may be imposed by a call to F11ZBF):
  • 1≤IROW i≤N and 1≤ICOL i≤IROW i, for i=1,2,…,NNZ;
  • IROW i-1<IROW i or IROW i-1=IROW i and ICOL i-1<ICOL i, for i=2,3,…,NNZ.
6:   RDIAG N – REAL (KIND=nag_wp) arrayInput
On entry: the elements of the diagonal matrix D-1, where D is the diagonal part of A.
7:   OMEGA – REAL (KIND=nag_wp)Input
On entry: the relaxation parameter ω.
Constraint: 0.0<OMEGA<2.0.
8:   CHECK – CHARACTER(1)Input
On entry: specifies whether or not the input data should be checked.
CHECK='C'
Checks are carried out on the values of N, NNZ, IROW, ICOL and OMEGA.
CHECK='N'
None of these checks are carried out.
See also Section 9.2.
Constraint: CHECK='C' or 'N'.
9:   Y N – REAL (KIND=nag_wp) arrayInput
On entry: the right-hand side vector y.
10:   X N – REAL (KIND=nag_wp) arrayOutput
On exit: the solution vector x.
11:   IWORK N+1 – INTEGER arrayWorkspace
12:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, CHECK≠'C' or 'N'.
IFAIL=2
On entry, | N<1,
or | NNZ<1,
or | NNZ>N×N+1/2,
or | OMEGA lies outside the interval 0.0,2.0,
IFAIL=3
On entry, the arrays IROW and ICOL fail to satisfy the following constraints:
  • 1≤IROW i≤N and 1≤ICOL i≤IROW i, for i=1,2,…,NNZ;
  • IROW i-1<IROW i or IROW i-1=IROW i and ICOL i-1<ICOL i, for i=2,3,…,NNZ.
Therefore a nonzero element has been supplied which does not lie in the lower triangular part of A, is out of order, or has duplicate row and column indices. Call F11ZBF to reorder and sum or remove duplicates.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

The computed solution x is the exact solution of a perturbed system of equations M+δM x=y, where
δM≤c n ε D+ωLD-1D+ωL T,
c n is a modest linear function of n, and ε is the machine precision.

8 Parallelism and Performance

F11JDF is not threaded in any implementation.

9 Further Comments

9.1 Timing

The time taken for a call to F11JDF is proportional to NNZ.

9.2 Use of CHECK

It is expected that a common use of F11JDF will be to carry out the preconditioning step required in the application of F11GEF to sparse symmetric linear systems. In this situation F11JDF is likely to be called many times with the same matrix M. In the interests of both reliability and efficiency, you are recommended to set CHECK='C' for the first of such calls, and to set CHECK='N' for all subsequent calls.

10 Example

This example solves a sparse symmetric linear system of equations
Ax=b,
using the conjugate-gradient (CG) method with SSOR preconditioning.
The CG algorithm itself is implemented by the reverse communication routine F11GEF, which returns repeatedly to the calling program with various values of the argument IREVCM. This argument indicates the action to be taken by the calling program.
  • If IREVCM=1, a matrix-vector product v=Au is required. This is implemented by a call to F11XEF.
  • If IREVCM=2, a solution of the preconditioning equation Mv=u is required. This is achieved by a call to F11JDF.
  • If IREVCM=4, F11GEF has completed its tasks. Either the iteration has terminated, or an error condition has arisen.
For further details see the routine document for F11GEF.

10.1 Program Text

Program Text (f11jdfe.f90)

10.2 Program Data

Program Data (f11jdfe.d)

10.3 Program Results

Program Results (f11jdfe.r)

F11 Chapter Contents
F11 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F11JEF : NAG Library, Mark 26

F11 Chapter Contents
F11 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F11JEF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F11JEF solves a real sparse symmetric system of linear equations, represented in symmetric coordinate storage format, using a conjugate gradient or Lanczos method, without preconditioning, with Jacobi or with SSOR preconditioning.

2 Specification

SUBROUTINE F11JEF ( METHOD, PRECON, N, NNZ, A, IROW, ICOL, OMEGA, B, TOL, MAXITN, X, RNORM, ITN, WORK, LWORK, IWORK, IFAIL)
INTEGER | N, NNZ, IROW(NNZ), ICOL(NNZ), MAXITN, ITN, LWORK, IWORK(N+1), IFAIL
REAL (KIND=nag_wp) | A(NNZ), OMEGA, B(N), TOL, X(N), RNORM, WORK(LWORK)
CHARACTER(*) | METHOD
CHARACTER(1) | PRECON

3 Description

F11JEF solves a real sparse symmetric linear system of equations
Ax=b,
using a preconditioned conjugate gradient method (see Barrett et al. (1994)), or a preconditioned Lanczos method based on the algorithm SYMMLQ (see Paige and Saunders (1975)). The conjugate gradient method is more efficient if A is positive definite, but may fail to converge for indefinite matrices. In this case the Lanczos method should be used instead. For further details see Barrett et al. (1994).
The routine allows the following choices for the preconditioner:
  • no preconditioning;
  • Jacobi preconditioning (see Young (1971));
  • symmetric successive-over-relaxation (SSOR) preconditioning (see Young (1971)).
For incomplete Cholesky (IC) preconditioning see F11JCF.
The matrix A is represented in symmetric coordinate storage (SCS) format (see Section 2.1.2 in the F11 Chapter Introduction) in the arrays A, IROW and ICOL. The array A holds the nonzero entries in the lower triangular part of the matrix, while IROW and ICOL hold the corresponding row and column indices.

4 References

Barrett R, Berry M, Chan T F, Demmel J, Donato J, Dongarra J, Eijkhout V, Pozo R, Romine C and Van der Vorst H (1994) Templates for the Solution of Linear Systems: Building Blocks for Iterative Methods SIAM, Philadelphia
Paige C C and Saunders M A (1975) Solution of sparse indefinite systems of linear equations SIAM J. Numer. Anal. 12 617–629
Young D (1971) Iterative Solution of Large Linear Systems Academic Press, New York

5 Arguments

1:   METHOD – CHARACTER(*)Input
On entry: specifies the iterative method to be used.
METHOD='CG'
Conjugate gradient method.
METHOD='SYMMLQ'
Lanczos method (SYMMLQ).
Constraint: METHOD='CG' or 'SYMMLQ'.
2:   PRECON – CHARACTER(1)Input
On entry: specifies the type of preconditioning to be used.
PRECON='N'
No preconditioning.
PRECON='J'
Jacobi.
PRECON='S'
Symmetric successive-over-relaxation (SSOR).
Constraint: PRECON='N', 'J' or 'S'.
3:   N – INTEGERInput
On entry: n, the order of the matrix A.
Constraint: N≥1.
4:   NNZ – INTEGERInput
On entry: the number of nonzero elements in the lower triangular part of the matrix A.
Constraint: 1≤NNZ≤N×N+1/2.
5:   A NNZ – REAL (KIND=nag_wp) arrayInput
On entry: the nonzero elements of the lower triangular part of the matrix A, ordered by increasing row index, and by increasing column index within each row. Multiple entries for the same row and column indices are not permitted. The routine F11ZBF may be used to order the elements in this way.
6:   IROW NNZ – INTEGER arrayInput
7:   ICOL NNZ – INTEGER arrayInput
On entry: the row and column indices of the nonzero elements supplied in array A.
Constraints:
IROW and ICOL must satisfy these constraints (which may be imposed by a call to F11ZBF):
  • 1≤IROW i≤N and 1≤ICOL i≤IROW i, for i=1,2,…,NNZ;
  • IROW i-1<IROW i or IROW i-1=IROW i and ICOL i-1<ICOL i, for i=2,3,…,NNZ.
8:   OMEGA – REAL (KIND=nag_wp)Input
On entry: if PRECON='S', OMEGA is the relaxation parameter ω to be used in the SSOR method. Otherwise OMEGA need not be initialized.
Constraint: 0.0<OMEGA<2.0.
9:   B N – REAL (KIND=nag_wp) arrayInput
On entry: the right-hand side vector b.
10:   TOL – REAL (KIND=nag_wp)Input
On entry: the required tolerance. Let xk denote the approximate solution at iteration k, and rk the corresponding residual. The algorithm is considered to have converged at iteration k if
rk∞≤τ×b∞+A∞xk∞.
If TOL≤0.0, τ=max⁡ε,10 ε,n ε is used, where ε is the machine precision. Otherwise τ=max TOL,10 ε,n ε is used.
Constraint: TOL<1.0.
11:   MAXITN – INTEGERInput
On entry: the maximum number of iterations allowed.
Constraint: MAXITN≥1.
12:   X N – REAL (KIND=nag_wp) arrayInput/Output
On entry: an initial approximation to the solution vector x.
On exit: an improved approximation to the solution vector x.
13:   RNORM – REAL (KIND=nag_wp)Output
On exit: the final value of the residual norm rk∞, where k is the output value of ITN.
14:   ITN – INTEGEROutput
On exit: the number of iterations carried out.
15:   WORK LWORK – REAL (KIND=nag_wp) arrayWorkspace
16:   LWORK – INTEGERInput
On entry: the dimension of the array WORK as declared in the (sub)program from which F11JEF is called.
Constraints:
  • if METHOD='CG', LWORK≥6×N+ν+120;
  • if METHOD='SYMMLQ', LWORK≥7×N+ν+120.
where ν=N for PRECON='J' or 'S', and 0 otherwise.
17:   IWORK N+1 – INTEGER arrayWorkspace
18:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, | METHOD≠'CG' or 'SYMMLQ',
or | PRECON≠'N', 'J' or 'S',
or | N<1,
or | NNZ<1,
or | NNZ>N×N+1/2,
or | OMEGA lies outside the interval 0.0,2.0,
or | TOL≥1.0,
or | MAXITN<1,
or | LWORK too small.
IFAIL=2
On entry, the arrays IROW and ICOL fail to satisfy the following constraints:
  • 1≤IROW i≤N and 1≤ICOL i≤IROW i, for i=1,2,…,NNZ;
  • IROW i-1<IROW i, or IROW i-1=IROW i and ICOL i-1<ICOL i, for i=2,3,…,NNZ.
Therefore a nonzero element has been supplied which does not lie in the lower triangular part of A, is out of order, or has duplicate row and column indices. Call F11ZBF to reorder and sum or remove duplicates.
IFAIL=3
On entry, the matrix A has a zero diagonal element. Jacobi and SSOR preconditioners are not appropriate for this problem.
IFAIL=4
The required accuracy could not be obtained. However, a reasonable accuracy has been obtained and further iterations could not improve the result.
IFAIL=5
Required accuracy not obtained in MAXITN iterations.
IFAIL=6
The preconditioner appears not to be positive definite.
IFAIL=7
The matrix of the coefficients appears not to be positive definite (conjugate gradient method only).
IFAIL=8 (F11GDF, F11GEF or F11GFF)
A serious error has occurred in an internal call to one of the specified routines. Check all subroutine calls and array sizes. Seek expert help.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

On successful termination, the final residual rk=b-A xk, where k=ITN, satisfies the termination criterion
rk∞≤τ×b∞+A∞xk∞.
The value of the final residual norm is returned in RNORM.

8 Parallelism and Performance

F11JEF is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
F11JEF makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The time taken by F11JEF for each iteration is roughly proportional to NNZ. One iteration with the Lanczos method (SYMMLQ) requires a slightly larger number of operations than one iteration with the conjugate gradient method.
The number of iterations required to achieve a prescribed accuracy cannot be easily determined a priori, as it can depend dramatically on the conditioning and spectrum of the preconditioned matrix of the coefficients A-=M-1 A.

10 Example

This example solves a symmetric positive definite system of equations using the conjugate gradient method, with SSOR preconditioning.

10.1 Program Text

Program Text (f11jefe.f90)

10.2 Program Data

Program Data (f11jefe.d)

10.3 Program Results

Program Results (f11jefe.r)

F11 Chapter Contents
F11 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F11JNF : NAG Library, Mark 26

F11 Chapter Contents
F11 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F11JNF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
▸▿ 9 Further Comments
9.1 Timing
9.2 Control of Fill-in
9.3 Choice of Arguments
9.4 Direct Solution of positive definite Systems
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F11JNF computes an incomplete Cholesky factorization of a complex sparse Hermitian matrix, represented in symmetric coordinate storage format. This factorization may be used as a preconditioner in combination with F11JQF.

2 Specification

SUBROUTINE F11JNF ( N, NNZ, A, LA, IROW, ICOL, LFILL, DTOL, MIC, DSCALE, PSTRAT, IPIV, ISTR, NNZC, NPIVM, IWORK, LIWORK, IFAIL)
INTEGER | N, NNZ, LA, IROW(LA), ICOL(LA), LFILL, IPIV(N), ISTR(N+1), NNZC, NPIVM, IWORK(LIWORK), LIWORK, IFAIL
REAL (KIND=nag_wp) | DTOL, DSCALE
COMPLEX (KIND=nag_wp) | A(LA)
CHARACTER(1) | MIC, PSTRAT

3 Description

F11JNF computes an incomplete Cholesky factorization (see Meijerink and Van der Vorst (1977)) of a complex sparse Hermitian n by n matrix A. It is designed specifically for positive definite matrices, but may also work for some mildly indefinite cases. The factorization is intended primarily for use as a preconditioner with the complex Hermitian iterative solver F11JQF.
The decomposition is written in the form
A=M+R
where
M=PLD LHPT
and P is a permutation matrix, L is lower triangular complex with unit diagonal elements, D is real diagonal and R is a remainder matrix.
The amount of fill-in occurring in the factorization can vary from zero to complete fill, and can be controlled by specifying either the maximum level of fill LFILL, or the drop tolerance DTOL. The factorization may be modified in order to preserve row sums, and the diagonal elements may be perturbed to ensure that the preconditioner is positive definite. Diagonal pivoting may optionally be employed, either with a user-defined ordering, or using the Markowitz strategy (see Markowitz (1957)), which aims to minimize fill-in. For further details see Section 9.
The sparse matrix A is represented in symmetric coordinate storage (SCS) format (see Section 2.1.2 in the F11 Chapter Introduction). The array A stores all the nonzero elements of the lower triangular part of A, while arrays IROW and ICOL store the corresponding row and column indices respectively. Multiple nonzero elements may not be specified for the same row and column index.
The preconditioning matrix M is returned in terms of the SCS representation of the lower triangular matrix
C=L+D-1-I.

4 References

Chan T F (1991) Fourier analysis of relaxed incomplete factorization preconditioners SIAM J. Sci. Statist. Comput. 12(2) 668–680
Markowitz H M (1957) The elimination form of the inverse and its application to linear programming Management Sci. 3 255–269
Meijerink J and Van der Vorst H (1977) An iterative solution method for linear systems of which the coefficient matrix is a symmetric M-matrix Math. Comput. 31 148–162
Salvini S A and Shaw G J (1995) An evaluation of new NAG Library solvers for large sparse symmetric linear systems NAG Technical Report TR1/95
Van der Vorst H A (1990) The convergence behaviour of preconditioned CG and CG-S in the presence of rounding errors Lecture Notes in Mathematics (eds O Axelsson and L Y Kolotilina) 1457 Springer–Verlag

5 Arguments

1:   N – INTEGERInput
On entry: n, the order of the matrix A.
Constraint: N≥1.
2:   NNZ – INTEGERInput
On entry: the number of nonzero elements in the lower triangular part of the matrix A.
Constraint: 1≤NNZ≤N×N+1/2.
3:   A LA – COMPLEX (KIND=nag_wp) arrayInput/Output
On entry: the nonzero elements in the lower triangular part of the matrix A, ordered by increasing row index, and by increasing column index within each row. Multiple entries for the same row and column indices are not permitted. The routine F11ZPF may be used to order the elements in this way.
On exit: the first NNZ elements of A contain the nonzero elements of A and the next NNZC elements contain the elements of the lower triangular matrix C. Matrix elements are ordered by increasing row index, and by increasing column index within each row.
4:   LA – INTEGERInput
On entry: the dimension of the arrays A, IROW and ICOL as declared in the (sub)program from which F11JNF is called. These arrays must be of sufficient size to store both A (NNZ elements) and C (NNZC elements).
Constraint: LA≥2×NNZ.
5:   IROW LA – INTEGER arrayInput/Output
6:   ICOL LA – INTEGER arrayInput/Output
On entry: the row and column indices of the nonzero elements supplied in A.
Constraints:
IROW and ICOL must satisfy these constraints (which may be imposed by a call to F11ZPF):
  • 1≤IROW i≤N and 1≤ICOL i≤IROW i, for i=1,2,…,NNZ;
  • IROW i-1<IROW i or IROW i-1=IROW i and ICOL i-1<ICOL i, for i=2,3,…,NNZ.
On exit: the row and column indices of the nonzero elements returned in A.
7:   LFILL – INTEGERInput
On entry: if LFILL≥0 its value is the maximum level of fill allowed in the decomposition (see Section 9.2). A negative value of LFILL indicates that DTOL will be used to control the fill instead.
8:   DTOL – REAL (KIND=nag_wp)Input
On entry: if LFILL<0, DTOL is used as a drop tolerance to control the fill-in (see Section 9.2); otherwise DTOL is not referenced.
Constraint: if LFILL<0, DTOL≥0.0.
9:   MIC – CHARACTER(1)Input
On entry: indicates whether or not the factorization should be modified to preserve row sums (see Section 9.3).
MIC='M'
The factorization is modified.
MIC='N'
The factorization is not modified.
Constraint: MIC='M' or 'N'.
10:   DSCALE – REAL (KIND=nag_wp)Input
On entry: the diagonal scaling parameter. All diagonal elements are multiplied by the factor (1.0+DSCALE) at the start of the factorization. This can be used to ensure that the preconditioner is positive definite. See also Section 9.3.
11:   PSTRAT – CHARACTER(1)Input
On entry: specifies the pivoting strategy to be adopted.
PSTRAT='N'
No pivoting is carried out.
PSTRAT='M'
Diagonal pivoting aimed at minimizing fill-in is carried out, using the Markowitz strategy (see Markowitz (1957)).
PSTRAT='U'
Diagonal pivoting is carried out according to the user-defined input array IPIV.
Suggested value: PSTRAT='M'.
Constraint: PSTRAT='N', 'M' or 'U'.
12:   IPIV N – INTEGER arrayInput/Output
On entry: if PSTRAT='U', IPIV i must specify the row index of the diagonal element to be used as a pivot at elimination stage i. Otherwise IPIV need not be initialized.
Constraint: if PSTRAT='U', IPIV must contain a valid permutation of the integers on 1,N.
On exit: the pivot indices. If IPIV i=j, the diagonal element in row j was used as the pivot at elimination stage i.
13:   ISTR N+1 – INTEGER arrayOutput
On exit: ISTR i, for i=1,2,…,N, is the starting address in the arrays A, IROW and ICOL of row i of the matrix C. ISTR N+1 is the address of the last nonzero element in C plus one.
14:   NNZC – INTEGEROutput
On exit: the number of nonzero elements in the lower triangular matrix C.
15:   NPIVM – INTEGEROutput
On exit: the number of pivots which were modified during the factorization to ensure that M was positive definite. The quality of the preconditioner will generally depend on the returned value of NPIVM. If NPIVM is large the preconditioner may not be satisfactory. In this case it may be advantageous to call F11JNF again with an increased value of either LFILL or DSCALE. See also Sections 9.3 and 9.4.
16:   IWORK LIWORK – INTEGER arrayWorkspace
17:   LIWORK – INTEGERInput
On entry: the dimension of the array IWORK as declared in the (sub)program from which F11JNF is called.
Constraints:
the minimum permissible value of LIWORK depends on LFILL as follows:
  • if LFILL≥0, LIWORK≥2×LA-3×NNZ+7×N+1;
  • otherwise LIWORK≥LA-NNZ+7×N+1.
18:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, | N<1,
or | NNZ<1,
or | NNZ>N×N+1/2,
or | LA<2×NNZ,
or | DTOL<0.0,
or | MIC≠'M' or 'N',
or | PSTRAT≠'N', 'M' or 'U',
or | LIWORK is too small.
IFAIL=2
On entry, the arrays IROW and ICOL fail to satisfy the following constraints:
  • 1≤IROW i≤N and 1≤ICOL i≤IROW i, for i=1,2,…,NNZ;
  • IROW i-1<IROW i, or IROW i-1=IROW i and ICOL i-1<ICOL i, for i=2,3,…,NNZ.
Therefore a nonzero element has been supplied which does not lie in the lower triangular part of A, is out of order, or has duplicate row and column indices. Call F11ZPF to reorder and sum or remove duplicates.
IFAIL=3
On entry, PSTRAT='U', but IPIV does not represent a valid permutation of the integers in 1,N. An input value of IPIV is either out of range or repeated.
IFAIL=4
LA is too small, resulting in insufficient storage space for fill-in elements. The decomposition has been terminated before completion. Either increase LA or reduce the amount of fill by setting PSTRAT='M', reducing LFILL, or increasing DTOL.
IFAIL=5 (F11ZPF)
A serious error has occurred in an internal call to the specified routine. Check all subroutine calls and array sizes. Seek expert help.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

The accuracy of the factorization will be determined by the size of the elements that are dropped and the size of any modifications made to the diagonal elements. If these sizes are small then the computed factors will correspond to a matrix close to A. The factorization can generally be made more accurate by increasing LFILL, or by reducing DTOL with LFILL<0.
If F11JNF is used in combination with F11JQF, the more accurate the factorization the fewer iterations will be required. However, the cost of the decomposition will also generally increase.

8 Parallelism and Performance

F11JNF makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

9.1 Timing

The time taken for a call to F11JNF is roughly proportional to NNZC 2/N.

9.2 Control of Fill-in

If LFILL≥0, the amount of fill-in occurring in the incomplete factorization is controlled by limiting the maximum ‘level’ of fill-in to LFILL. The original nonzero elements of A are defined to be of level 0. The fill level of a new nonzero location occurring during the factorization is defined as:
k=max ke,kc+1,
where ke is the level of fill of the element being eliminated, and kc is the level of fill of the element causing the fill-in.
If LFILL<0, the fill-in is controlled by means of the ‘drop tolerance’ DTOL. A potential fill-in element a ij occurring in row i and column j will not be included if
a ij<DTOL×a iia jj.
For either method of control, any elements which are not included are discarded if MIC='N', or subtracted from the diagonal element in the elimination row if MIC='M'.

9.3 Choice of Arguments

There is unfortunately no choice of the various algorithmic arguments which is optimal for all types of complex Hermitian matrix, and some experimentation will generally be required for each new type of matrix encountered.
If the matrix A is not known to have any particular special properties, the following strategy is recommended. Start with LFILL=0, MIC='N' and DSCALE=0.0. If the value returned for NPIVM is significantly larger than zero, i.e., a large number of pivot modifications were required to ensure that M was positive definite, the preconditioner is not likely to be satisfactory. In this case increase either LFILL or DSCALE until NPIVM falls to a value close to zero. Once suitable values of LFILL and DSCALE have been found try setting MIC='M' to see if any improvement can be obtained by using modified incomplete Cholesky.
F11JNF is primarily designed for positive definite matrices, but may work for some mildly indefinite problems. If NPIVM cannot be satisfactorily reduced by increasing LFILL or DSCALE then A is probably too indefinite for this routine.
For certain classes of matrices (typically those arising from the discretization of elliptic or parabolic partial differential equations), the convergence rate of the preconditioned iterative solver can sometimes be significantly improved by using an incomplete factorization which preserves the row-sums of the original matrix. In these cases try setting MIC='M'.

9.4 Direct Solution of positive definite Systems

Although it is not their primary purpose, F11JNF and F11JPF may be used together to obtain a direct solution to a complex Hermitian positive definite linear system. To achieve this the call to F11JPF should be preceded by a complete Cholesky factorization
A=PLD LHPT=M.
A complete factorization is obtained from a call to F11JNF with LFILL<0 and DTOL=0.0, provided NPIVM=0 on exit. A nonzero value of NPIVM indicates that A is not positive definite, or is ill-conditioned. A factorization with nonzero NPIVM may serve as a preconditioner, but will not result in a direct solution. It is therefore essential to check the output value of NPIVM if a direct solution is required.
The use of F11JNF and F11JPF as a direct method is illustrated in F11JPF.

10 Example

This example reads in a complex sparse Hermitian matrix A and calls F11JNF to compute an incomplete Cholesky factorization. It then outputs the nonzero elements of both A and C=L+D-1-I.
The call to F11JNF has LFILL=0, MIC='N', DSCALE=0.0 and PSTRAT='M', giving an unmodified zero-fill factorization of an unperturbed matrix, with Markowitz diagonal pivoting.

10.1 Program Text

Program Text (f11jnfe.f90)

10.2 Program Data

Program Data (f11jnfe.d)

10.3 Program Results

Program Results (f11jnfe.r)

F11 Chapter Contents
F11 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F11JPF : NAG Library, Mark 26

F11 Chapter Contents
F11 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F11JPF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
▸▿ 9 Further Comments
9.1 Timing
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F11JPF solves a system of complex linear equations involving the incomplete Cholesky preconditioning matrix generated by F11JNF.

2 Specification

SUBROUTINE F11JPF ( N, A, LA, IROW, ICOL, IPIV, ISTR, CHECK, Y, X, IFAIL)
INTEGER | N, LA, IROW(LA), ICOL(LA), IPIV(N), ISTR(N+1), IFAIL
COMPLEX (KIND=nag_wp) | A(LA), Y(N), X(N)
CHARACTER(1) | CHECK

3 Description

F11JPF solves a system of linear equations
Mx=y
involving the preconditioning matrix M=PLD LHPT, corresponding to an incomplete Cholesky decomposition of a complex sparse Hermitian matrix stored in symmetric coordinate storage (SCS) format (see Section 2.1.2 in the F11 Chapter Introduction), as generated by F11JNF.
In the above decomposition L is a complex lower triangular sparse matrix with unit diagonal, D is a real diagonal matrix and P is a permutation matrix. L and D are supplied to F11JPF through the matrix
C=L+D-1-I
which is a lower triangular n by n complex sparse matrix, stored in SCS format, as returned by F11JNF. The permutation matrix P is returned from F11JNF via the array IPIV.
F11JPF may also be used in combination with F11JNF to solve a sparse complex Hermitian positive definite system of linear equations directly (see F11JNF). This is illustrated in Section 10.

4 References

None.

5 Arguments

1:   N – INTEGERInput
On entry: n, the order of the matrix M. This must be the same value as was supplied in the preceding call to F11JNF.
Constraint: N≥1.
2:   A LA – COMPLEX (KIND=nag_wp) arrayInput
On entry: the values returned in the array A by a previous call to F11JNF.
3:   LA – INTEGERInput
On entry: the dimension of the arrays A, IROW and ICOL as declared in the (sub)program from which F11JPF is called. This must be the same value supplied in the preceding call to F11JNF.
4:   IROW LA – INTEGER arrayInput
5:   ICOL LA – INTEGER arrayInput
6:   IPIV N – INTEGER arrayInput
7:   ISTR N+1 – INTEGER arrayInput
On entry: the values returned in arrays IROW, ICOL, IPIV and ISTR by a previous call to F11JNF.
8:   CHECK – CHARACTER(1)Input
On entry: specifies whether or not the input data should be checked.
CHECK='C'
Checks are carried out on the values of N, IROW, ICOL, IPIV and ISTR.
CHECK='N'
None of these checks are carried out.
Constraint: CHECK='C' or 'N'.
9:   Y N – COMPLEX (KIND=nag_wp) arrayInput
On entry: the right-hand side vector y.
10:   X N – COMPLEX (KIND=nag_wp) arrayOutput
On exit: the solution vector x.
11:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, CHECK≠'C' or 'N'.
IFAIL=2
On entry, N<1.
IFAIL=3
On entry, the SCS representation of the preconditioning matrix M is invalid. Further details are given in the error message. Check that the call to F11JPF has been preceded by a valid call to F11JNF and that the arrays A, IROW, ICOL, IPIV and ISTR have not been corrupted between the two calls.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

The computed solution x is the exact solution of a perturbed system of equations M+δM x=y, where
δM≤c n εP LDLH PT,
c n is a modest linear function of n, and ε is the machine precision.

8 Parallelism and Performance

F11JPF is not threaded in any implementation.

9 Further Comments

9.1 Timing

The time taken for a call to F11JPF is proportional to the value of NNZC returned from F11JNF.

10 Example

This example reads in a complex sparse Hermitian positive definite matrix A and a vector y. It then calls F11JNF, with LFILL=-1 and DTOL=0.0, to compute the complete Cholesky decomposition of A:
A=PLD LHPT.
Finally it calls F11JPF to solve the system
PLD LHPT x=y.

10.1 Program Text

Program Text (f11jpfe.f90)

10.2 Program Data

Program Data (f11jpfe.d)

10.3 Program Results

Program Results (f11jpfe.r)

F11 Chapter Contents
F11 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F11JQF : NAG Library, Mark 26

F11 Chapter Contents
F11 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F11JQF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F11JQF solves a complex sparse Hermitian system of linear equations, represented in symmetric coordinate storage format, using a conjugate gradient or Lanczos method, with incomplete Cholesky preconditioning.

2 Specification

SUBROUTINE F11JQF ( METHOD, N, NNZ, A, LA, IROW, ICOL, IPIV, ISTR, B, TOL, MAXITN, X, RNORM, ITN, WORK, LWORK, IFAIL)
INTEGER | N, NNZ, LA, IROW(LA), ICOL(LA), IPIV(N), ISTR(N+1), MAXITN, ITN, LWORK, IFAIL
REAL (KIND=nag_wp) | TOL, RNORM
COMPLEX (KIND=nag_wp) | A(LA), B(N), X(N), WORK(LWORK)
CHARACTER(*) | METHOD

3 Description

F11JQF solves a complex sparse Hermitian linear system of equations
Ax=b,
using a preconditioned conjugate gradient method (see Meijerink and Van der Vorst (1977)), or a preconditioned Lanczos method based on the algorithm SYMMLQ (see Paige and Saunders (1975)). The conjugate gradient method is more efficient if A is positive definite, but may fail to converge for indefinite matrices. In this case the Lanczos method should be used instead. For further details see Barrett et al. (1994).
F11JQF uses the incomplete Cholesky factorization determined by F11JNF as the preconditioning matrix. A call to F11JQF must always be preceded by a call to F11JNF. Alternative preconditioners for the same storage scheme are available by calling F11JSF.
The matrix A and the preconditioning matrix M are represented in symmetric coordinate storage (SCS) format (see Section 2.1.2 in the F11 Chapter Introduction) in the arrays A, IROW and ICOL, as returned from F11JNF. The array A holds the nonzero entries in the lower triangular parts of these matrices, while IROW and ICOL hold the corresponding row and column indices.

4 References

Barrett R, Berry M, Chan T F, Demmel J, Donato J, Dongarra J, Eijkhout V, Pozo R, Romine C and Van der Vorst H (1994) Templates for the Solution of Linear Systems: Building Blocks for Iterative Methods SIAM, Philadelphia
Meijerink J and Van der Vorst H (1977) An iterative solution method for linear systems of which the coefficient matrix is a symmetric M-matrix Math. Comput. 31 148–162
Paige C C and Saunders M A (1975) Solution of sparse indefinite systems of linear equations SIAM J. Numer. Anal. 12 617–629

5 Arguments

1:   METHOD – CHARACTER(*)Input
On entry: specifies the iterative method to be used.
METHOD='CG'
Conjugate gradient method.
METHOD='SYMMLQ'
Lanczos method (SYMMLQ).
Constraint: METHOD='CG' or 'SYMMLQ'.
2:   N – INTEGERInput
On entry: n, the order of the matrix A. This must be the same value as was supplied in the preceding call to F11JNF.
Constraint: N≥1.
3:   NNZ – INTEGERInput
On entry: the number of nonzero elements in the lower triangular part of the matrix A. This must be the same value as was supplied in the preceding call to F11JNF.
Constraint: 1≤NNZ≤N×N+1/2.
4:   A LA – COMPLEX (KIND=nag_wp) arrayInput
On entry: the values returned in the array A by a previous call to F11JNF.
5:   LA – INTEGERInput
On entry: the dimension of the arrays A, IROW and ICOL as declared in the (sub)program from which F11JQF is called. This must be the same value as was supplied in the preceding call to F11JNF.
Constraint: LA≥2×NNZ.
6:   IROW LA – INTEGER arrayInput
7:   ICOL LA – INTEGER arrayInput
8:   IPIV N – INTEGER arrayInput
9:   ISTR N+1 – INTEGER arrayInput
On entry: the values returned in arrays IROW, ICOL, IPIV and ISTR by a previous call to F11JNF.
10:   B N – COMPLEX (KIND=nag_wp) arrayInput
On entry: the right-hand side vector b.
11:   TOL – REAL (KIND=nag_wp)Input
On entry: the required tolerance. Let xk denote the approximate solution at iteration k, and rk the corresponding residual. The algorithm is considered to have converged at iteration k if
rk∞≤τ×b∞+A∞xk∞.
If TOL≤0.0, τ=max⁡ε,10 ε,n ε is used, where ε is the machine precision. Otherwise τ=max TOL,10 ε,n ε is used.
Constraint: TOL<1.0.
12:   MAXITN – INTEGERInput
On entry: the maximum number of iterations allowed.
Constraint: MAXITN≥1.
13:   X N – COMPLEX (KIND=nag_wp) arrayInput/Output
On entry: an initial approximation to the solution vector x.
On exit: an improved approximation to the solution vector x.
14:   RNORM – REAL (KIND=nag_wp)Output
On exit: the final value of the residual norm rk∞, where k is the output value of ITN.
15:   ITN – INTEGEROutput
On exit: the number of iterations carried out.
16:   WORK LWORK – COMPLEX (KIND=nag_wp) arrayWorkspace
17:   LWORK – INTEGERInput
On entry: the dimension of the array WORK as declared in the (sub)program from which F11JQF is called.
Constraints:
  • if METHOD='CG', LWORK≥6×N+120;
  • if METHOD='SYMMLQ', LWORK≥7×N+120.
18:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, | METHOD≠'CG' or 'SYMMLQ',
or | N<1,
or | NNZ<1,
or | NNZ>N×N+1/2,
or | LA too small,
or | TOL≥1.0,
or | MAXITN<1,
or | LWORK too small.
IFAIL=2
On entry, the SCS representation of A is invalid. Further details are given in the error message. Check that the call to F11JQF has been preceded by a valid call to F11JNF, and that the arrays A, IROW, and ICOL have not been corrupted between the two calls.
IFAIL=3
On entry, the SCS representation of M is invalid. Further details are given in the error message. Check that the call to F11JQF has been preceded by a valid call to F11JNF, and that the arrays A, IROW, ICOL, IPIV and ISTR have not been corrupted between the two calls.
IFAIL=4
The required accuracy could not be obtained. However, a reasonable accuracy has been obtained and further iterations could not improve the result.
IFAIL=5
Required accuracy not obtained in MAXITN iterations.
IFAIL=6
The preconditioner appears not to be positive definite.
IFAIL=7
The matrix of the coefficients appears not to be positive definite (conjugate gradient method only).
IFAIL=8
A serious error has occurred in an internal call to an auxiliary routine. Check all subroutine calls and array sizes. Seek expert help.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

On successful termination, the final residual rk=b-A xk, where k=ITN, satisfies the termination criterion
rk∞≤τ×b∞+A∞xk∞.
The value of the final residual norm is returned in RNORM.

8 Parallelism and Performance

F11JQF is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
F11JQF makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The time taken by F11JQF for each iteration is roughly proportional to the value of NNZC returned from the preceding call to F11JNF. One iteration with the Lanczos method (SYMMLQ) requires a slightly larger number of operations than one iteration with the conjugate gradient method.
The number of iterations required to achieve a prescribed accuracy cannot easily be determined a priori, as it can depend dramatically on the conditioning and spectrum of the preconditioned matrix of the coefficients A-=M-1 A.

10 Example

This example solves a complex sparse Hermitian positive definite system of equations using the conjugate gradient method, with incomplete Cholesky preconditioning.

10.1 Program Text

Program Text (f11jqfe.f90)

10.2 Program Data

Program Data (f11jqfe.d)

10.3 Program Results

Program Results (f11jqfe.r)

F11 Chapter Contents
F11 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F11JRF : NAG Library, Mark 26

F11 Chapter Contents
F11 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F11JRF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
▸▿ 9 Further Comments
9.1 Timing
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F11JRF solves a system of linear equations involving the preconditioning matrix corresponding to SSOR applied to a complex sparse Hermitian matrix, represented in symmetric coordinate storage format.

2 Specification

SUBROUTINE F11JRF ( N, NNZ, A, IROW, ICOL, RDIAG, OMEGA, CHECK, Y, X, IWORK, IFAIL)
INTEGER | N, NNZ, IROW(NNZ), ICOL(NNZ), IWORK(N+1), IFAIL
REAL (KIND=nag_wp) | RDIAG(N), OMEGA
COMPLEX (KIND=nag_wp) | A(NNZ), Y(N), X(N)
CHARACTER(1) | CHECK

3 Description

F11JRF solves a system of equations
Mx=y
involving the preconditioning matrix
M=1 ω 2-ω D+ω L D-1 D+ω L H
corresponding to symmetric successive-over-relaxation (SSOR) (see Young (1971)) on a linear system Ax=b, where A is a sparse complex Hermitian matrix stored in symmetric coordinate storage (SCS) format (see Section 2.1.2 in the F11 Chapter Introduction).
In the definition of M given above D is the diagonal part of A, L is the strictly lower triangular part of A and ω is a user-defined relaxation parameter. Note that since A is Hermitian the matrix D is necessarily real.

4 References

Young D (1971) Iterative Solution of Large Linear Systems Academic Press, New York

5 Arguments

1:   N – INTEGERInput
On entry: n, the order of the matrix A.
Constraint: N≥1.
2:   NNZ – INTEGERInput
On entry: the number of nonzero elements in the lower triangular part of the matrix A.
Constraint: 1≤NNZ≤N×N+1/2.
3:   A NNZ – COMPLEX (KIND=nag_wp) arrayInput
On entry: the nonzero elements in the lower triangular part of the matrix A, ordered by increasing row index, and by increasing column index within each row. Multiple entries for the same row and column indices are not permitted. The routine F11ZPF may be used to order the elements in this way.
4:   IROW NNZ – INTEGER arrayInput
5:   ICOL NNZ – INTEGER arrayInput
On entry: the row and column indices of the nonzero elements supplied in array A.
Constraints:
IROW and ICOL must satisfy the following constraints (which may be imposed by a call to F11ZPF):
  • 1≤IROW i≤N and 1≤ICOL i≤IROW i, for i=1,2,…,NNZ;
  • IROW i-1<IROW i or IROW i-1=IROW i and ICOL i-1<ICOL i, for i=2,3,…,NNZ.
6:   RDIAG N – REAL (KIND=nag_wp) arrayInput
On entry: the elements of the diagonal matrix D-1, where D is the diagonal part of A. Note that since A is Hermitian the elements of D-1 are necessarily real.
7:   OMEGA – REAL (KIND=nag_wp)Input
On entry: the relaxation parameter ω.
Constraint: 0.0<OMEGA<2.0.
8:   CHECK – CHARACTER(1)Input
On entry: specifies whether or not the input data should be checked.
CHECK='C'
Checks are carried out on the values of N, NNZ, IROW, ICOL and OMEGA.
CHECK='N'
None of these checks are carried out.
Constraint: CHECK='C' or 'N'.
9:   Y N – COMPLEX (KIND=nag_wp) arrayInput
On entry: the right-hand side vector y.
10:   X N – COMPLEX (KIND=nag_wp) arrayOutput
On exit: the solution vector x.
11:   IWORK N+1 – INTEGER arrayWorkspace
12:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, CHECK≠'C' or 'N'.
IFAIL=2
On entry, | N<1,
or | NNZ<1,
or | NNZ>N×N+1/2,
or | OMEGA lies outside the interval 0.0,2.0.
IFAIL=3
On entry, the arrays IROW and ICOL fail to satisfy the following constraints:
  • 1≤IROW i≤N and 1≤ICOL i≤IROW i, for i=1,2,…,NNZ;
  • IROW i-1<IROW i or IROW i-1=IROW i and ICOL i-1<ICOL i, for i=2,3,…,NNZ.
Therefore a nonzero element has been supplied which does not lie in the lower triangular part of A, is out of order, or has duplicate row and column indices. Call F11ZPF to reorder and sum or remove duplicates.
IFAIL=4
On entry, a row of A has no diagonal entry.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

The computed solution x is the exact solution of a perturbed system of equations M+δM x=y, where
δM≤c n ε D+ωLD-1D+ωL T,
c n is a modest linear function of n, and ε is the machine precision.

8 Parallelism and Performance

F11JRF is not threaded in any implementation.

9 Further Comments

9.1 Timing

The time taken for a call to F11JRF is proportional to NNZ.

10 Example

This example program solves the preconditioning equation Mx=y for a 9 by 9 sparse complex Hermitian matrix A, given in symmetric coordinate storage (SCS) format.

10.1 Program Text

Program Text (f11jrfe.f90)

10.2 Program Data

Program Data (f11jrfe.d)

10.3 Program Results

Program Results (f11jrfe.r)

F11 Chapter Contents
F11 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F11JSF : NAG Library, Mark 26

F11 Chapter Contents
F11 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F11JSF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F11JSF solves a complex sparse Hermitian system of linear equations, represented in symmetric coordinate storage format, using a conjugate gradient or Lanczos method, without preconditioning, with Jacobi or with SSOR preconditioning.

2 Specification

SUBROUTINE F11JSF ( METHOD, PRECON, N, NNZ, A, IROW, ICOL, OMEGA, B, TOL, MAXITN, X, RNORM, ITN, RDIAG, WORK, LWORK, IWORK, IFAIL)
INTEGER | N, NNZ, IROW(NNZ), ICOL(NNZ), MAXITN, ITN, LWORK, IWORK(N+1), IFAIL
REAL (KIND=nag_wp) | OMEGA, TOL, RNORM, RDIAG(N)
COMPLEX (KIND=nag_wp) | A(NNZ), B(N), X(N), WORK(LWORK)
CHARACTER(*) | METHOD
CHARACTER(1) | PRECON

3 Description

F11JSF solves a complex sparse Hermitian linear system of equations
Ax=b,
using a preconditioned conjugate gradient method (see Barrett et al. (1994)), or a preconditioned Lanczos method based on the algorithm SYMMLQ (see Paige and Saunders (1975)). The conjugate gradient method is more efficient if A is positive definite, but may fail to converge for indefinite matrices. In this case the Lanczos method should be used instead. For further details see Barrett et al. (1994).
F11JSF allows the following choices for the preconditioner:
  • – no preconditioning;
  • – Jacobi preconditioning (see Young (1971));
  • – symmetric successive-over-relaxation (SSOR) preconditioning (see Young (1971)).
For incomplete Cholesky (IC) preconditioning see F11JQF.
The matrix A is represented in symmetric coordinate storage (SCS) format (see Section 2.1.2 in the F11 Chapter Introduction) in the arrays A, IROW and ICOL. The array A holds the nonzero entries in the lower triangular part of the matrix, while IROW and ICOL hold the corresponding row and column indices.

4 References

Barrett R, Berry M, Chan T F, Demmel J, Donato J, Dongarra J, Eijkhout V, Pozo R, Romine C and Van der Vorst H (1994) Templates for the Solution of Linear Systems: Building Blocks for Iterative Methods SIAM, Philadelphia
Paige C C and Saunders M A (1975) Solution of sparse indefinite systems of linear equations SIAM J. Numer. Anal. 12 617–629
Young D (1971) Iterative Solution of Large Linear Systems Academic Press, New York

5 Arguments

1:   METHOD – CHARACTER(*)Input
On entry: specifies the iterative method to be used.
METHOD='CG'
Conjugate gradient method.
METHOD='SYMMLQ'
Lanczos method (SYMMLQ).
Constraint: METHOD='CG' or 'SYMMLQ'.
2:   PRECON – CHARACTER(1)Input
On entry: specifies the type of preconditioning to be used.
PRECON='N'
No preconditioning.
PRECON='J'
Jacobi.
PRECON='S'
Symmetric successive-over-relaxation (SSOR).
Constraint: PRECON='N', 'J' or 'S'.
3:   N – INTEGERInput
On entry: n, the order of the matrix A.
Constraint: N≥1.
4:   NNZ – INTEGERInput
On entry: the number of nonzero elements in the lower triangular part of the matrix A.
Constraint: 1≤NNZ≤N×N+1/2.
5:   A NNZ – COMPLEX (KIND=nag_wp) arrayInput
On entry: the nonzero elements of the lower triangular part of the matrix A, ordered by increasing row index, and by increasing column index within each row. Multiple entries for the same row and column indices are not permitted. The routine F11ZPF may be used to order the elements in this way.
6:   IROW NNZ – INTEGER arrayInput
7:   ICOL NNZ – INTEGER arrayInput
On entry: the row and column indices of the nonzero elements supplied in array A.
Constraints:
IROW and ICOL must satisfy these constraints (which may be imposed by a call to F11ZPF):
  • 1≤IROW i≤N and 1≤ICOL i≤IROW i, for i=1,2,…,NNZ;
  • IROW i-1<IROW i or IROW i-1=IROW i and ICOL i-1<ICOL i, for i=2,3,…,NNZ.
8:   OMEGA – REAL (KIND=nag_wp)Input
On entry: if PRECON='S', OMEGA is the relaxation parameter ω to be used in the SSOR method. Otherwise OMEGA need not be initialized.
Constraint: 0.0<OMEGA<2.0.
9:   B N – COMPLEX (KIND=nag_wp) arrayInput
On entry: the right-hand side vector b.
10:   TOL – REAL (KIND=nag_wp)Input
On entry: the required tolerance. Let xk denote the approximate solution at iteration k, and rk the corresponding residual. The algorithm is considered to have converged at iteration k if
rk∞≤τ×b∞+A∞xk∞.
If TOL≤0.0, τ=max⁡ε,10 ε,n ε is used, where ε is the machine precision. Otherwise τ=max TOL,10 ε,n ε is used.
Constraint: TOL<1.0.
11:   MAXITN – INTEGERInput
On entry: the maximum number of iterations allowed.
Constraint: MAXITN≥1.
12:   X N – COMPLEX (KIND=nag_wp) arrayInput/Output
On entry: an initial approximation to the solution vector x.
On exit: an improved approximation to the solution vector x.
13:   RNORM – REAL (KIND=nag_wp)Output
On exit: the final value of the residual norm rk, where k is the output value of ITN.
14:   ITN – INTEGEROutput
On exit: the number of iterations carried out.
15:   RDIAG N – REAL (KIND=nag_wp) arrayOutput
On exit: the elements of the diagonal matrix D-1, where D is the diagonal part of A. Note that since A is Hermitian the elements of D-1 are necessarily real.
16:   WORK LWORK – COMPLEX (KIND=nag_wp) arrayWorkspace
17:   LWORK – INTEGERInput
On entry: the dimension of the array WORK as declared in the (sub)program from which F11JSF is called.
Constraints:
  • if METHOD='CG', LWORK≥6×N+120;
  • if METHOD='SYMMLQ', LWORK≥7×N+120.
18:   IWORK N+1 – INTEGER arrayWorkspace
19:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, | METHOD≠'CG' or 'SYMMLQ',
or | PRECON≠'N', 'J' or 'S',
or | N<1,
or | NNZ<1,
or | NNZ>N×N+1/2,
or | OMEGA lies outside the interval 0.0,2.0,
or | TOL≥1.0,
or | MAXITN<1,
or | LWORK is too small.
IFAIL=2
On entry, the arrays IROW and ICOL fail to satisfy the following constraints:
  • 1≤IROW i≤N and 1≤ICOL i≤IROW i, for i=1,2,…,NNZ;
  • IROW i-1<IROW i, or IROW i-1=IROW i and ICOL i-1<ICOL i, for i=2,3,…,NNZ.
Therefore a nonzero element has been supplied which does not lie in the lower triangular part of A, is out of order, or has duplicate row and column indices. Call F11ZPF to reorder and sum or remove duplicates.
IFAIL=3
On entry, the matrix A has a zero diagonal element. Jacobi and SSOR preconditioners are not appropriate for this problem.
IFAIL=4
The required accuracy could not be obtained. However, a reasonable accuracy has been obtained and further iterations could not improve the result.
IFAIL=5
Required accuracy not obtained in MAXITN iterations.
IFAIL=6
The preconditioner appears not to be positive definite.
IFAIL=7
The matrix of the coefficients appears not to be positive definite (conjugate gradient method only).
IFAIL=8
A serious error has occurred in an internal call to an auxiliary routine. Check all subroutine calls and array sizes. Seek expert help.
IFAIL=9
The matrix of the coefficients has a non-real diagonal entry, and is therefore not Hermitian.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

On successful termination, the final residual rk=b-A xk, where k=ITN, satisfies the termination criterion
rk∞ ≤ τ × b∞ + A∞ xk∞ .
The value of the final residual norm is returned in RNORM.

8 Parallelism and Performance

F11JSF is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
F11JSF makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The time taken by F11JSF for each iteration is roughly proportional to NNZ. One iteration with the Lanczos method (SYMMLQ) requires a slightly larger number of operations than one iteration with the conjugate gradient method.
The number of iterations required to achieve a prescribed accuracy cannot easily be determined a priori, as it can depend dramatically on the conditioning and spectrum of the preconditioned matrix of the coefficients A-=M-1 A.

10 Example

This example solves a complex sparse Hermitian positive definite system of equations using the conjugate gradient method, with SSOR preconditioning.

10.1 Program Text

Program Text (f11jsfe.f90)

10.2 Program Data

Program Data (f11jsfe.d)

10.3 Program Results

Program Results (f11jsfe.r)

F11 Chapter Contents
F11 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F11MDF : NAG Library, Mark 26

F11 Chapter Contents
F11 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F11MDF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F11MDF computes a column permutation suitable for LU factorization (by F11MEF) of a real sparse matrix in compressed column (Harwell–Boeing) format and applies it to the matrix. This routine must be called prior to F11MEF.

2 Specification

SUBROUTINE F11MDF ( SPEC, N, ICOLZP, IROWIX, IPRM, IFAIL)
INTEGER | N, ICOLZP(*), IROWIX(*), IPRM(7*N), IFAIL
CHARACTER(1) | SPEC

3 Description

Given a sparse matrix in compressed column (Harwell–Boeing) format A and a choice of column permutation schemes, the routine computes those data structures that will be needed by the LU factorization routine F11MEF and associated routines F11MMF, F11MFF and F11MHF. The column permutation choices are:
  • original order (that is, no permutation);
  • user-supplied permutation;
  • a permutation, computed by the routine, designed to minimize fill-in during the LU factorization.
The algorithm for this computed permutation is based on the approximate minimum degree column ordering algorithm COLAMD. The computed permutation is not sensitive to the magnitude of the nonzero values of A.

4 References

Amestoy P R, Davis T A and Duff I S (1996) An approximate minimum degree ordering algorithm SIAM J. Matrix Anal. Appl. 17 886–905
Gilbert J R and Larimore S I (2004) A column approximate minimum degree ordering algorithm ACM Trans. Math. Software 30,3 353–376
Gilbert J R, Larimore S I and Ng E G (2004) Algorithm 836: COLAMD, an approximate minimum degree ordering algorithm ACM Trans. Math. Software 30, 3 377–380

5 Arguments

1:   SPEC – CHARACTER(1)Input
On entry: indicates the permutation to be applied.
SPEC='N'
The identity permutation is used (i.e., the columns are not permuted).
SPEC='U'
The permutation in the IPRM array is used, as supplied by you.
SPEC='M'
The permutation computed by the COLAMD algorithm is used
Constraint: SPEC='N', 'U' or 'M'.
2:   N – INTEGERInput
On entry: n, the order of the matrix A.
Constraint: N≥0.
3:   ICOLZP* – INTEGER arrayInput
Note: the dimension of the array ICOLZP must be at least N+1.
On entry: ICOLZP i contains the index in A of the start of a new column. See Section 2.1.3 in the F11 Chapter Introduction.
4:   IROWIX* – INTEGER arrayInput
Note: the dimension of the array IROWIX must be at least ICOLZP N+1-1, the number of nonzeros of the sparse matrix A.
On entry: IROWIX i contains the row index in A for element A i. See Section 2.1.3 in the F11 Chapter Introduction.
5:   IPRM 7×N – INTEGER arrayInput/Output
On entry: the first N entries contain the column permutation supplied by you. This will be used if SPEC='U', and ignored otherwise. If used, it must consist of a permutation of all the integers in the range 0,N-1, the leftmost column of the matrix A denoted by 0 and the rightmost by N-1. Labelling columns in this way, IPRM i=j means that column i-1 of A is in position j in A⁢Pc, where Pr A Pc=LU expresses the factorization to be performed.
On exit: a new permutation is returned in the first N entries. The rest of the array contains data structures that will be used by other routines. The routine computes the column elimination tree for A and a post-order permutation on the tree. It then compounds the IPRM permutation given or computed by the COLAMD algorthm with the post-order permutation. This array is needed by the LU factorization routine F11MEF and associated routines F11MFF, F11MHF and F11MMF and should be passed to them unchanged.
6:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, N=value.
Constraint: N≥0.
On entry, SPEC=value.
Constraint: SPEC='N', 'U' or 'M'.
IFAIL=2
Incorrect column permutations in array IPRM.
IFAIL=3
COLAMD algorithm failed.
IFAIL=4
Incorrect specification of argument ICOLZP.
IFAIL=5
Incorrect specification of argument IROWIX.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

Not applicable. This computation does not use floating-point numbers.

8 Parallelism and Performance

F11MDF is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

We recommend calling this routine with SPEC='M' before calling F11MEF. The COLAMD algorithm computes a sparsity-preserving permutation Pc solely from the pattern of A such that the LU factorization Pr A Pc = LU remains as sparse as possible, regardless of the subsequent choice of Pr. The algorithm takes advantage of the existence of super-columns (columns with the same sparsity pattern) to reduce running time.

10 Example

This example computes a sparsity preserving column permutation for the LU factorization of the matrix A, where
A= 2.00 1.00 0 0 0 0 0 1.00 -1.00 0 4.00 0 1.00 0 1.00 0 0 0 1.00 2.00 0 -2.00 0 0 3.00 .

10.1 Program Text

Program Text (f11mdfe.f90)

10.2 Program Data

Program Data (f11mdfe.d)

10.3 Program Results

Program Results (f11mdfe.r)

F11 Chapter Contents
F11 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F11MEF : NAG Library, Mark 26

F11 Chapter Contents
F11 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F11MEF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F11MEF computes the LU factorization of a real sparse matrix in compressed column (Harwell–Boeing), column-permuted format.

2 Specification

SUBROUTINE F11MEF ( N, IROWIX, A, IPRM, THRESH, NZLMX, NZLUMX, NZUMX, IL, LVAL, IU, UVAL, NNZL, NNZU, FLOP, IFAIL)
INTEGER | N, IROWIX(*), IPRM(7*N), NZLMX, NZLUMX, NZUMX, IL(7*N+NZLMX+4), IU(2*N+NZUMX+1), NNZL, NNZU, IFAIL
REAL (KIND=nag_wp) | A(*), THRESH, LVAL(NZLUMX), UVAL(NZUMX), FLOP

3 Description

Given a real sparse matrix A, F11MEF computes an LU factorization of A with partial pivoting, Pr A Pc = LU , where Pr is a row permutation matrix (computed by F11MEF), Pc is a (supplied) column permutation matrix, L is unit lower triangular and U is upper triangular. The column permutation matrix, Pc, must be computed by a prior call to F11MDF. The matrix A must be presented in the column permuted, compressed column (Harwell–Boeing) format.
The LU factorization is output in the form of four one-dimensional arrays: integer arrays IL and IU and real-valued arrays LVAL and UVAL. These describe the sparsity pattern and numerical values in the L and U matrices. The minimum required dimensions of these arrays cannot be given as a simple function of the size arguments (order and number of nonzero values) of the matrix A. This is due to unpredictable fill-in created by partial pivoting. F11MEF will, on return, indicate which dimensions of these arrays were not adequate for the computation or (in the case of one of them) give a firm bound. You should then allocate more storage and try again.

4 References

Demmel J W, Eisenstat S C, Gilbert J R, Li X S and Li J W H (1999) A supernodal approach to sparse partial pivoting SIAM J. Matrix Anal. Appl. 20 720–755
Demmel J W, Gilbert J R and Li X S (1999) An asynchronous parallel supernodal algorithm for sparse gaussian elimination SIAM J. Matrix Anal. Appl. 20 915–952

5 Arguments

1:   N – INTEGERInput
On entry: n, the order of the matrix A.
Constraint: N≥0.
2:   IROWIX* – INTEGER arrayInput
Note: the dimension of the array IROWIX must be at least nnz, the number of nonzeros of the sparse matrix A.
On entry: the row index array of sparse matrix A.
3:   A* – REAL (KIND=nag_wp) arrayInput
Note: the dimension of the array A must be at least nnz, the number of nonzeros of the sparse matrix A.
On entry: the array of nonzero values in the sparse matrix A.
4:   IPRM 7×N – INTEGER arrayInput/Output
On entry: contains the column permutation which defines the permutation Pc and associated data structures as computed by routine F11MDF.
On exit: part of the array is modified to record the row permutation Pr determined by pivoting.
5:   THRESH – REAL (KIND=nag_wp)Input
On entry: the diagonal pivoting threshold, t. At step j of the Gaussian elimination, if A jj≥t⁢max i≥j A ij, use A jj as a pivot, otherwise use max i≥j A ij. A value of t=1 corresponds to partial pivoting, a value of t=0 corresponds to always choosing the pivot on the diagonal (unless it is zero).
Suggested value: THRESH=1.0. Smaller values may result in a faster factorization, but the benefits are likely to be small in most cases. It might be possible to use THRESH=0.0 if you are confident about the stability of the factorization, for example, if A is diagonally dominant.
Constraint: 0.0≤THRESH≤1.0.
6:   NZLMX – INTEGERInput
On entry: indicates the available size of array IL. The dimension of IL should be at least 7×N+NZLMX+4. A good range for NZLMX that works for many problems is nnz to 8×nnz, where nnz is the number of nonzeros in the sparse matrix A. If, on exit, IFAIL=2, the given NZLMX was too small and you should attempt to provide more storage and call the routine again.
Constraint: NZLMX≥1.
7:   NZLUMX – INTEGERInput/Output
On entry: indicates the available size of array LVAL. The dimension of LVAL should be at least NZLUMX.
Constraint: NZLUMX≥1.
On exit: if IFAIL=4, the given NZLUMX was too small and is reset to a value that will be sufficient. You should then provide the indicated storage and call the routine again.
8:   NZUMX – INTEGERInput
On entry: indicates the available sizes of arrays IU and UVAL. The dimension of IU should be at least 2×N+NZUMX+1 and the dimension of UVAL should be at least NZUMX. A good range for NZUMX that works for many problems is nnz to 8×nnz, where nnz is the number of nonzeros in the sparse matrix A. If, on exit, IFAIL=3, the given NZUMX was too small and you should attempt to provide more storage and call the routine again.
Constraint: NZUMX≥1.
9:   IL 7×N+NZLMX+4 – INTEGER arrayOutput
On exit: encapsulates the sparsity pattern of matrix L.
10:   LVAL NZLUMX – REAL (KIND=nag_wp) arrayOutput
On exit: records the nonzero values of matrix L and some of the nonzero values of matrix U.
11:   IU 2×N+NZUMX+1 – INTEGER arrayOutput
On exit: encapsulates the sparsity pattern of matrix U.
12:   UVAL NZUMX – REAL (KIND=nag_wp) arrayOutput
On exit: records some of the nonzero values of matrix U.
13:   NNZL – INTEGEROutput
On exit: the number of nonzero values in the matrix L.
14:   NNZU – INTEGEROutput
On exit: the number of nonzero values in the matrix U.
15:   FLOP – REAL (KIND=nag_wp)Output
On exit: the number of floating-point operations performed.
16:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, N=value.
Constraint: N≥0.
On entry, NZLMX=value.
Constraint: NZLMX≥1.
On entry, NZLUMX=value.
Constraint: NZLUMX≥1.
On entry, NZUMX=value.
Constraint: NZUMX≥1.
On entry, THRESH=value.
Constraint: 0.0≤THRESH≤1.0.
IFAIL=2
Insufficient NZLMX.
IFAIL=3
Insufficient NZUMX.
IFAIL=4
Insufficient NZLUMX.
IFAIL=5
The matrix is singular – no factorization possible.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

The computed factors L and U are the exact factors of a perturbed matrix A+E, where
E ≤ c n ε L U ,
c n is a modest linear function of n, and ε is the machine precision, when partial pivoting is used. If no partial pivoting is used, the factorization accuracy can be considerably worse. A call to F11MMF after F11MEF can help determine the quality of the factorization.

8 Parallelism and Performance

F11MEF is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
F11MEF makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The total number of floating-point operations depends on the sparsity pattern of the matrix A.
A call to F11MEF may be followed by calls to the routines:
  • F11MFF to solve AX=B or AT X=B;
  • F11MGF to estimate the condition number of A;
  • F11MMF to estimate the reciprocal pivot growth of the LU factorization.

10 Example

This example computes the LU factorization of the matrix A, where
A= 2.00 1.00 0 0 0 0 0 1.00 -1.00 0 4.00 0 1.00 0 1.00 0 0 0 1.00 2.00 0 -2.00 0 0 3.00 .

10.1 Program Text

Program Text (f11mefe.f90)

10.2 Program Data

Program Data (f11mefe.d)

10.3 Program Results

Program Results (f11mefe.r)

F11 Chapter Contents
F11 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F11MFF : NAG Library, Mark 26

F11 Chapter Contents
F11 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F11MFF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F11MFF solves a real sparse system of linear equations with multiple right-hand sides given an LU factorization of the sparse matrix computed by F11MEF.

2 Specification

SUBROUTINE F11MFF ( TRANS, N, IPRM, IL, LVAL, IU, UVAL, NRHS, B, LDB, IFAIL)
INTEGER | N, IPRM(7*N), IL(*), IU(*), NRHS, LDB, IFAIL
REAL (KIND=nag_wp) | LVAL(*), UVAL(*), B(LDB,*)
CHARACTER(1) | TRANS

3 Description

F11MFF solves a real system of linear equations with multiple right-hand sides AX=B or AT X=B, according to the value of the argument TRANS, where the matrix factorization Pr A Pc = LU corresponds to an LU decomposition of a sparse matrix stored in compressed column (Harwell–Boeing) format, as computed by F11MEF.
In the above decomposition L is a lower triangular sparse matrix with unit diagonal elements and U is an upper triangular sparse matrix; Pr and Pc are permutation matrices.

4 References

None.

5 Arguments

1:   TRANS – CHARACTER(1)Input
On entry: specifies whether AX=B or AT X=B is solved.
TRANS='N'
AX=B is solved.
TRANS='T'
AT X=B is solved.
Constraint: TRANS='N' or 'T'.
2:   N – INTEGERInput
On entry: n, the order of the matrix A.
Constraint: N≥0.
3:   IPRM 7×N – INTEGER arrayInput
On entry: the column permutation which defines Pc, the row permutation which defines Pr, plus associated data structures as computed by F11MEF.
4:   IL* – INTEGER arrayInput
Note: the dimension of the array IL must be at least as large as the dimension of the array of the same name in F11MEF.
On entry: records the sparsity pattern of matrix L as computed by F11MEF.
5:   LVAL* – REAL (KIND=nag_wp) arrayInput
Note: the dimension of the array LVAL must be at least as large as the dimension of the array of the same name in F11MEF.
On entry: records the nonzero values of matrix L and some nonzero values of matrix U as computed by F11MEF.
6:   IU* – INTEGER arrayInput
Note: the dimension of the array IU must be at least as large as the dimension of the array of the same name in F11MEF.
On entry: records the sparsity pattern of matrix U as computed by F11MEF.
7:   UVAL* – REAL (KIND=nag_wp) arrayInput
Note: the dimension of the array UVAL must be at least as large as the dimension of the array of the same name in F11MEF.
On entry: records some nonzero values of matrix U as computed by F11MEF.
8:   NRHS – INTEGERInput
On entry: nrhs, the number of right-hand sides in B.
Constraint: NRHS≥0.
9:   B LDB* – REAL (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array B must be at least max 1,NRHS.
On entry: the N by NRHS right-hand side matrix B.
On exit: the N by NRHS solution matrix X.
10:   LDB – INTEGERInput
On entry: the first dimension of the array B as declared in the (sub)program from which F11MFF is called.
Constraint: LDB≥max 1,N.
11:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, LDB=value and N=value.
Constraint: LDB≥max 1,N.
On entry, N=value.
Constraint: N≥0.
On entry, NRHS=value.
Constraint: NRHS≥0.
On entry, TRANS=value.
Constraint: TRANS='N' or 'T'.
IFAIL=2
Incorrect row permutations in array IPRM.
IFAIL=3
Incorrect column permutations in array IPRM.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

For each right-hand side vector b, the computed solution x is the exact solution of a perturbed system of equations A+E x=b, where
E≤c n ε LU,
c n is a modest linear function of n, and ε is the machine precision, when partial pivoting is used.
If x^ is the true solution, then the computed solution x satisfies a forward error bound of the form
x-x^∞ x∞ ≤c n cond A,x ε
where cond A,x= A-1 A x ∞/ x∞≤cond A= A-1 A ∞≤κ∞ A. Note that cond A,x can be much smaller than cond A, and cond AT can be much larger (or smaller) than cond A.
Forward and backward error bounds can be computed by calling F11MHF, and an estimate for κ∞A can be obtained by calling F11MGF.

8 Parallelism and Performance

F11MFF is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
F11MFF makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

F11MFF may be followed by a call to F11MHF to refine the solution and return an error estimate.

10 Example

This example solves the system of equations AX=B, where
A= 2.00 1.00 0 0 0 0 0 1.00 -1.00 0 4.00 0 1.00 0 1.00 0 0 0 1.00 2.00 0 -2.00 0 0 3.00   and  B= 1.56 3.12 -0.25 -0.50 3.60 7.20 1.33 2.66 0.52 1.04 .
Here A is nonsymmetric and must first be factorized by F11MEF.

10.1 Program Text

Program Text (f11mffe.f90)

10.2 Program Data

Program Data (f11mffe.d)

10.3 Program Results

Program Results (f11mffe.r)

F11 Chapter Contents
F11 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F11MGF : NAG Library, Mark 26

F11 Chapter Contents
F11 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F11MGF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F11MGF computes an estimate of the reciprocal of the condition number of a sparse matrix given an LU factorization of the matrix computed by F11MEF.

2 Specification

SUBROUTINE F11MGF ( NORM, N, IL, LVAL, IU, UVAL, ANORM, RCOND, IFAIL)
INTEGER | N, IL(*), IU(*), IFAIL
REAL (KIND=nag_wp) | LVAL(*), UVAL(*), ANORM, RCOND
CHARACTER(1) | NORM

3 Description

F11MGF estimates the condition number of a real sparse matrix A, in either the 1-norm or the ∞-norm:
κ 1 A=A 1 A-1 1   or   κ∞A=A∞ A-1∞.
Note that κ∞A=κ 1 AT.
Because the condition number is infinite if A is singular, the routine actually returns an estimate of the reciprocal of the condition number.
The routine should be preceded by a call to F11MLF to compute A 1 or A∞, and a call to F11MEF to compute the LU factorization of A. The routine then estimates A-1 1 or A-1∞ and computes the reciprocal of the condition number.

4 References

None.

5 Arguments

1:   NORM – CHARACTER(1)Input
On entry: indicates whether κ 1 A or κ∞A is to be estimated.
NORM='1' or 'O'
κ 1 A is estimated.
NORM='I'
κ∞A is estimated.
Constraint: NORM='1', 'O' or 'I'.
2:   N – INTEGERInput
On entry: n, the order of the matrix A.
Constraint: N≥0.
3:   IL* – INTEGER arrayInput
Note: the dimension of the array IL must be at least as large as the dimension of the array of the same name in F11MEF.
On entry: records the sparsity pattern of matrix L as computed by F11MEF.
4:   LVAL* – REAL (KIND=nag_wp) arrayInput
Note: the dimension of the array LVAL must be at least as large as the dimension of the array of the same name in F11MEF.
On entry: records the nonzero values of matrix L and some nonzero values of matrix U as computed by F11MEF.
5:   IU* – INTEGER arrayInput
Note: the dimension of the array IU must be at least as large as the dimension of the array of the same name in F11MEF.
On entry: records the sparsity pattern of matrix U as computed by F11MEF.
6:   UVAL* – REAL (KIND=nag_wp) arrayInput
Note: the dimension of the array UVAL must be at least as large as the dimension of the array of the same name in F11MEF.
On entry: records some nonzero values of matrix U as computed by F11MEF.
7:   ANORM – REAL (KIND=nag_wp)Input
On entry: if NORM='1' or 'O', the 1-norm of the matrix A.
If NORM='I', the ∞-norm of the matrix A.
ANORM may be computed by calling F11MLF with the same value for the argument NORM.
Constraint: ANORM≥0.0.
8:   RCOND – REAL (KIND=nag_wp)Output
On exit: an estimate of the reciprocal of the condition number of A. RCOND is set to zero if exact singularity is detected or the estimate underflows. If RCOND is less than machine precision, A is singular to working precision.
9:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, ANORM=value.
Constraint: ANORM≥0.0.
On entry, N=value.
Constraint: N≥0.
On entry, NORM=value.
Constraint: NORM='1', 'O' or 'I'.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

The computed estimate RCOND is never less than the true value ρ, and in practice is nearly always less than 10 ρ, although examples can be constructed where RCOND is much larger.

8 Parallelism and Performance

F11MGF makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

A call to F11MGF involves solving a number of systems of linear equations of the form Ax=b or AT x=b.

10 Example

This example estimates the condition number in the 1-norm of the matrix A, where
A= 2.00 1.00 0 0 0 0 0 1.00 -1.00 0 4.00 0 1.00 0 1.00 0 0 0 1.00 2.00 0 -2.00 0 0 3.00 .
Here A is nonsymmetric and must first be factorized by F11MEF. The true condition number in the 1-norm is 20.25.

10.1 Program Text

Program Text (f11mgfe.f90)

10.2 Program Data

Program Data (f11mgfe.d)

10.3 Program Results

Program Results (f11mgfe.r)

F11 Chapter Contents
F11 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F11MHF : NAG Library, Mark 26

F11 Chapter Contents
F11 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F11MHF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F11MHF returns error bounds for the solution of a real sparse system of linear equations with multiple right-hand sides, AX=B or AT X=B. It improves the solution by iterative refinement in standard precision, in order to reduce the backward error as much as possible.

2 Specification

SUBROUTINE F11MHF ( TRANS, N, ICOLZP, IROWIX, A, IPRM, IL, LVAL, IU, UVAL, NRHS, B, LDB, X, LDX, FERR, BERR, IFAIL)
INTEGER | N, ICOLZP(*), IROWIX(*), IPRM(7*N), IL(*), IU(*), NRHS, LDB, LDX, IFAIL
REAL (KIND=nag_wp) | A(*), LVAL(*), UVAL(*), B(LDB,*), X(LDX,*), FERR(NRHS), BERR(NRHS)
CHARACTER(1) | TRANS

3 Description

F11MHF returns the backward errors and estimated bounds on the forward errors for the solution of a real system of linear equations with multiple right-hand sides AX=B or AT X=B. The routine handles each right-hand side vector (stored as a column of the matrix B) independently, so we describe the function of F11MHF in terms of a single right-hand side b and solution x.
Given a computed solution x, the routine computes the component-wise backward error β. This is the size of the smallest relative perturbation in each element of A and b such that if x is the exact solution of a perturbed system:
A+δA x = b + δ b then   δ a ij ≤ β a ij   and   δ bi ≤ β bi .
Then the routine estimates a bound for the component-wise forward error in the computed solution, defined by:
maxi xi - x^i / maxi xi
where x^ is the true solution.
The routine uses the LU factorization Pr A Pc = LU computed by F11MEF and the solution computed by F11MFF.

4 References

Golub G H and Van Loan C F (1996) Matrix Computations (3rd Edition) Johns Hopkins University Press, Baltimore

5 Arguments

1:   TRANS – CHARACTER(1)Input
On entry: specifies whether AX=B or AT X=B is solved.
TRANS='N'
AX=B is solved.
TRANS='T'
AT X=B is solved.
Constraint: TRANS='N' or 'T'.
2:   N – INTEGERInput
On entry: n, the order of the matrix A.
Constraint: N≥0.
3:   ICOLZP* – INTEGER arrayInput
Note: the dimension of the array ICOLZP must be at least N+1.
On entry: ICOLZP i contains the index in A of the start of a new column. See Section 2.1.3 in the F11 Chapter Introduction.
4:   IROWIX* – INTEGER arrayInput
Note: the dimension of the array IROWIX must be at least ICOLZP N+1-1, the number of nonzeros of the sparse matrix A.
On entry: the row index array of sparse matrix A.
5:   A* – REAL (KIND=nag_wp) arrayInput
Note: the dimension of the array A must be at least ICOLZP N+1-1, the number of nonzeros of the sparse matrix A.
On entry: the array of nonzero values in the sparse matrix A.
6:   IPRM 7×N – INTEGER arrayInput
On entry: the column permutation which defines Pc, the row permutation which defines Pr, plus associated data structures as computed by F11MEF.
7:   IL* – INTEGER arrayInput
Note: the dimension of the array IL must be at least as large as the dimension of the array of the same name in F11MEF.
On entry: records the sparsity pattern of matrix L as computed by F11MEF.
8:   LVAL* – REAL (KIND=nag_wp) arrayInput
Note: the dimension of the array LVAL must be at least as large as the dimension of the array of the same name in F11MEF.
On entry: records the nonzero values of matrix L and some nonzero values of matrix U as computed by F11MEF.
9:   IU* – INTEGER arrayInput
Note: the dimension of the array IU must be at least as large as the dimension of the array of the same name in F11MEF.
On entry: records the sparsity pattern of matrix U as computed by F11MEF.
10:   UVAL* – REAL (KIND=nag_wp) arrayInput
Note: the dimension of the array UVAL must be at least as large as the dimension of the array of the same name in F11MEF.
On entry: records some nonzero values of matrix U as computed by F11MEF.
11:   NRHS – INTEGERInput
On entry: nrhs, the number of right-hand sides in B.
Constraint: NRHS≥0.
12:   B LDB* – REAL (KIND=nag_wp) arrayInput
Note: the second dimension of the array B must be at least max 1,NRHS.
On entry: the n by nrhs right-hand side matrix B.
13:   LDB – INTEGERInput
On entry: the first dimension of the array B as declared in the (sub)program from which F11MHF is called.
Constraint: LDB≥max 1,N.
14:   X LDX* – REAL (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array X must be at least max 1,NRHS.
On entry: the n by nrhs solution matrix X, as returned by F11MFF.
On exit: the n by nrhs improved solution matrix X.
15:   LDX – INTEGERInput
On entry: the first dimension of the array X as declared in the (sub)program from which F11MHF is called.
Constraint: LDX≥max 1,N.
16:   FERR NRHS – REAL (KIND=nag_wp) arrayOutput
On exit: FERR j contains an estimated error bound for the jth solution vector, that is, the jth column of X, for j=1,2,…,nrhs.
17:   BERR NRHS – REAL (KIND=nag_wp) arrayOutput
On exit: BERR j contains the component-wise backward error bound β for the jth solution vector, that is, the jth column of X, for j=1,2,…,nrhs.
18:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, LDB=value and N=value.
Constraint: LDB≥max 1,N.
On entry, LDX=value and N=value.
Constraint: LDX≥max 1,N.
On entry, N=value.
Constraint: N≥0.
On entry, NRHS=value.
Constraint: NRHS≥0.
On entry, TRANS=value.
Constraint: TRANS='N' or 'T'.
IFAIL=2
Incorrect row permutations in array IPRM.
IFAIL=3
Incorrect column permutations in array IPRM.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

The bounds returned in FERR are not rigorous, because they are estimated, not computed exactly; but in practice they almost always overestimate the actual error.

8 Parallelism and Performance

F11MHF is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
F11MHF makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

At most five steps of iterative refinement are performed, but usually only one or two steps are required.
Estimating the forward error involves solving a number of systems of linear equations of the form Ax=b or AT x=b;

10 Example

This example solves the system of equations AX=B using iterative refinement and to compute the forward and backward error bounds, where
A= 2.00 1.00 0 0 0 0 0 1.00 -1.00 0 4.00 0 1.00 0 1.00 0 0 0 1.00 2.00 0 -2.00 0 0 3.00   and  B= 1.56 3.12 -0.25 -0.50 3.60 7.20 1.33 2.66 0.52 1.04 .
Here A is nonsymmetric and must first be factorized by F11MEF.

10.1 Program Text

Program Text (f11mhfe.f90)

10.2 Program Data

Program Data (f11mhfe.d)

10.3 Program Results

Program Results (f11mhfe.r)

F11 Chapter Contents
F11 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F11MKF : NAG Library, Mark 26

F11 Chapter Contents
F11 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F11MKF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F11MKF computes a matrix-matrix or transposed matrix-matrix product involving a real, square, sparse nonsymmetric matrix stored in compressed column (Harwell–Boeing) format.

2 Specification

SUBROUTINE F11MKF ( TRANS, N, M, ALPHA, ICOLZP, IROWIX, A, B, LDB, BETA, C, LDC, IFAIL)
INTEGER | N, M, ICOLZP(*), IROWIX(*), LDB, LDC, IFAIL
REAL (KIND=nag_wp) | ALPHA, A(*), B(LDB,*), BETA, C(LDC,*)
CHARACTER(1) | TRANS

3 Description

F11MKF computes either the matrix-matrix product C←αAB+βC, or the transposed matrix-matrix product C←α AT B + βC, according to the value of the argument TRANS, where A is a real n by n sparse nonsymmetric matrix, of arbitrary sparsity pattern with nnz nonzero elements, B and C are n by m real dense matrices. The matrix A is stored in compressed column (Harwell–Boeing) storage format. The array A stores all nonzero elements of A, while arrays ICOLZP and IROWIX store the compressed column indices and row indices of A respectively.

4 References

None.

5 Arguments

1:   TRANS – CHARACTER(1)Input
On entry: specifies whether or not the matrix A is transposed.
TRANS='N'
αAB+βC is computed.
TRANS='T'
α AT B+βC is computed.
Constraint: TRANS='N' or 'T'.
2:   N – INTEGERInput
On entry: n, the order of the matrix A.
Constraint: N≥0.
3:   M – INTEGERInput
On entry: m, the number of columns of matrices B and C.
Constraint: M≥0.
4:   ALPHA – REAL (KIND=nag_wp)Input
On entry: α, the scalar factor in the matrix multiplication.
5:   ICOLZP* – INTEGER arrayInput
Note: the dimension of the array ICOLZP must be at least N+1.
On entry: ICOLZP i contains the index in A of the start of a new column. See Section 2.1.3 in the F11 Chapter Introduction.
6:   IROWIX* – INTEGER arrayInput
Note: the dimension of the array IROWIX must be at least ICOLZP N+1-1, the number of nonzeros of the sparse matrix A.
On entry: the row index array of sparse matrix A.
7:   A* – REAL (KIND=nag_wp) arrayInput
Note: the dimension of the array A must be at least ICOLZP N+1-1, the number of nonzeros of the sparse matrix A.
On entry: the array of nonzero values in the sparse matrix A.
8:   B LDB* – REAL (KIND=nag_wp) arrayInput
Note: the second dimension of the array B must be at least max 1,M.
On entry: the n by m matrix B.
9:   LDB – INTEGERInput
On entry: the first dimension of the array B as declared in the (sub)program from which F11MKF is called.
Constraint: LDB≥max 1,N.
10:   BETA – REAL (KIND=nag_wp)Input
On entry: the scalar factor β.
11:   C LDC* – REAL (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array C must be at least max 1,M.
On entry: the n by m matrix C.
On exit: C is overwritten by αAB+βC or α AT B +βC depending on the value of TRANS.
12:   LDC – INTEGERInput
On entry: the first dimension of the array C as declared in the (sub)program from which F11MKF is called.
Constraint: LDC≥max 1,N.
13:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, LDB=value and N=value.
Constraint: LDB≥max 1,N.
On entry, LDC=value and N=value.
Constraint: LDC≥max 1,N.
On entry, M=value.
Constraint: M≥0.
On entry, N=value.
Constraint: N≥0.
On entry, TRANS=value.
Constraint: TRANS='N' or 'T'.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

Not applicable.

8 Parallelism and Performance

F11MKF is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

None.

10 Example

This example reads in a sparse matrix A and a dense matrix B. It then calls F11MKF to compute the matrix-matrix product C=A⁢B and the transposed matrix-matrix product C=AT⁢B, where
A= 2.00 1.00 0 0 0 0 0 1.00 -1.00 0 4.00 0 1.00 0 1.00 0 0 0 1.00 2.00 0 -2.00 0 0 3.00   and  B= 0.70 1.40 0.16 0.32 0.52 1.04 0.77 1.54 0.28 0.56 .

10.1 Program Text

Program Text (f11mkfe.f90)

10.2 Program Data

Program Data (f11mkfe.d)

10.3 Program Results

Program Results (f11mkfe.r)

F11 Chapter Contents
F11 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F11MLF : NAG Library, Mark 26

F11 Chapter Contents
F11 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F11MLF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F11MLF computes the 1-norm, the ∞-norm or the maximum absolute value of the elements of a real, square, sparse matrix which is held in compressed column (Harwell–Boeing) format.

2 Specification

SUBROUTINE F11MLF ( NORM, ANORM, N, ICOLZP, IROWIX, A, IFAIL)
INTEGER | N, ICOLZP(*), IROWIX(*), IFAIL
REAL (KIND=nag_wp) | ANORM, A(*)
CHARACTER(1) | NORM

3 Description

F11MLF computes various quantities relating to norms of a real, sparse n by n matrix A presented in compressed column (Harwell–Boeing) format.

4 References

None.

5 Arguments

1:   NORM – CHARACTER(1)Input
On entry: specifies the value to be returned in ANORM.
NORM='1' or 'O'
The 1-norm A 1 of the matrix is computed, that is max 1≤j≤n∑i=1 n A ij.
NORM='I'
The ∞-norm A∞ of the matrix is computed, that is max 1≤i≤n ∑j=1 n A ij.
NORM='M'
The value max 1≤i,j≤n A ij (not a norm).
Constraint: NORM='1', 'O', 'I' or 'M'.
2:   ANORM – REAL (KIND=nag_wp)Output
On exit: the computed quantity relating the matrix.
3:   N – INTEGERInput
On entry: n, the order of the matrix A.
Constraint: N≥0.
4:   ICOLZP* – INTEGER arrayInput
Note: the dimension of the array ICOLZP must be at least N+1.
On entry: ICOLZP i contains the index in A of the start of a new column. See Section 2.1.3 in the F11 Chapter Introduction.
5:   IROWIX* – INTEGER arrayInput
Note: the dimension of the array IROWIX must be at least ICOLZP N+1-1, the number of nonzeros of the sparse matrix A.
On entry: the row index array of sparse matrix A.
6:   A* – REAL (KIND=nag_wp) arrayInput
Note: the dimension of the array A must be at least ICOLZP N+1-1, the number of nonzeros of the sparse matrix A.
On entry: the array of nonzero values in the sparse matrix A.
7:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, N=value.
Constraint: N≥0.
On entry, NORM=value.
Constraint: NORM='1', 'O', 'I' or 'M'.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

Not applicable.

8 Parallelism and Performance

F11MLF is not threaded in any implementation.

9 Further Comments

None.

10 Example

This example computes norms and maximum absolute value of the matrix A, where
A= 2.00 1.00 0 0 0 0 0 1.00 -1.00 0 4.00 0 1.00 0 1.00 0 0 0 1.00 2.00 0 -2.00 0 0 3.00 .

10.1 Program Text

Program Text (f11mlfe.f90)

10.2 Program Data

Program Data (f11mlfe.d)

10.3 Program Results

Program Results (f11mlfe.r)

F11 Chapter Contents
F11 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F11MMF : NAG Library, Mark 26

F11 Chapter Contents
F11 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F11MMF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F11MMF computes the reciprocal pivot growth factor of an LU factorization of a real sparse matrix in compressed column (Harwell–Boeing) format.

2 Specification

SUBROUTINE F11MMF ( N, ICOLZP, A, IPRM, IL, LVAL, IU, UVAL, RPG, IFAIL)
INTEGER | N, ICOLZP(*), IPRM(7*N), IL(*), IU(*), IFAIL
REAL (KIND=nag_wp) | A(*), LVAL(*), UVAL(*), RPG

3 Description

F11MMF computes the reciprocal pivot growth factor maxj Aj∞/Uj∞ from the columns Aj and Uj of an LU factorization of the matrix A, Pr A Pc = LU where Pr is a row permutation matrix, Pc is a column permutation matrix, L is unit lower triangular and U is upper triangular as computed by F11MEF.

4 References

None.

5 Arguments

1:   N – INTEGERInput
On entry: n, the order of the matrix A.
Constraint: N≥0.
2:   ICOLZP* – INTEGER arrayInput
Note: the dimension of the array ICOLZP must be at least N+1.
On entry: ICOLZP i contains the index in A of the start of a new column. See Section 2.1.3 in the F11 Chapter Introduction.
3:   A* – REAL (KIND=nag_wp) arrayInput
Note: the dimension of the array A must be at least ICOLZP N+1-1, the number of nonzeros of the sparse matrix A.
On entry: the array of nonzero values in the sparse matrix A.
4:   IPRM 7×N – INTEGER arrayInput
On entry: the column permutation which defines Pc, the row permutation which defines Pr, plus associated data structures as computed by F11MEF.
5:   IL* – INTEGER arrayInput
Note: the dimension of the array IL must be at least as large as the dimension of the array of the same name in F11MEF.
On entry: records the sparsity pattern of matrix L as computed by F11MEF.
6:   LVAL* – REAL (KIND=nag_wp) arrayInput
Note: the dimension of the array LVAL must be at least as large as the dimension of the array of the same name in F11MEF.
On entry: records the nonzero values of matrix L and some nonzero values of matrix U as computed by F11MEF.
7:   IU* – INTEGER arrayInput
Note: the dimension of the array IU must be at least as large as the dimension of the array of the same name in F11MEF.
On entry: records the sparsity pattern of matrix U as computed by F11MEF.
8:   UVAL* – REAL (KIND=nag_wp) arrayInput
Note: the dimension of the array UVAL must be at least as large as the dimension of the array of the same name in F11MEF.
On entry: records some nonzero values of matrix U as computed by F11MEF.
9:   RPG – REAL (KIND=nag_wp)Output
On exit: the reciprocal pivot growth factor maxj Aj∞/Uj∞. If the reciprocal pivot growth factor is much less than 1, the stability of the LU factorization may be poor.
10:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, N=value.
Constraint: N≥0.
IFAIL=2
Incorrect column permutations in array IPRM.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

Not applicable.

8 Parallelism and Performance

F11MMF is not threaded in any implementation.

9 Further Comments

If the reciprocal pivot growth factor, RPG, is much less than 1, then the factorization of the matrix A could be poor. This means that using the factorization to obtain solutions to a linear system, forward error bounds and estimates of the condition number could be unreliable. Consider increasing the THRESH argument in the call to F11MEF.

10 Example

To compute the reciprocal pivot growth for the factorization of the matrix A, where
A= 2.00 1.00 0 0 0 0 0 1.00 -1.00 0 4.00 0 1.00 0 1.00 0 0 0 1.00 2.00 0 -2.00 0 0 3.00 .
In this case, it should be equal to 1.0.

10.1 Program Text

Program Text (f11mmfe.f90)

10.2 Program Data

Program Data (f11mmfe.d)

10.3 Program Results

Program Results (f11mmfe.r)

F11 Chapter Contents
F11 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F11XAF : NAG Library, Mark 26

F11 Chapter Contents
F11 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F11XAF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
▸▿ 9 Further Comments
9.1 Timing
9.2 Use of CHECK
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F11XAF computes a matrix-vector or transposed matrix-vector product involving a real sparse nonsymmetric matrix stored in coordinate storage format.

2 Specification

SUBROUTINE F11XAF ( TRANS, N, NNZ, A, IROW, ICOL, CHECK, X, Y, IFAIL)
INTEGER | N, NNZ, IROW(NNZ), ICOL(NNZ), IFAIL
REAL (KIND=nag_wp) | A(NNZ), X(N), Y(N)
CHARACTER(1) | TRANS, CHECK

3 Description

F11XAF computes either the matrix-vector product y=Ax, or the transposed matrix-vector product y=AT x, according to the value of the argument TRANS, where A is an n by n sparse nonsymmetric matrix, of arbitrary sparsity pattern. The matrix A is stored in coordinate storage (CS) format (see Section 2.1.1 in the F11 Chapter Introduction). The array A stores all nonzero elements of A, while arrays IROW and ICOL store the corresponding row and column indices respectively.
It is envisaged that a common use of F11XAF will be to compute the matrix-vector product required in the application of F11BEF to sparse linear systems. An illustration of this usage appears in Section 10 in F11DDF.

4 References

None.

5 Arguments

1:   TRANS – CHARACTER(1)Input
On entry: specifies whether or not the matrix A is transposed.
TRANS='N'
y=Ax is computed.
TRANS='T'
y=AT x is computed.
Constraint: TRANS='N' or 'T'.
2:   N – INTEGERInput
On entry: n, the order of the matrix A.
Constraint: N≥1.
3:   NNZ – INTEGERInput
On entry: the number of nonzero elements in the matrix A.
Constraint: 1≤NNZ≤N 2.
4:   A NNZ – REAL (KIND=nag_wp) arrayInput
On entry: the nonzero elements in the matrix A, ordered by increasing row index, and by increasing column index within each row. Multiple entries for the same row and column indices are not permitted. The routine F11ZAF may be used to order the elements in this way.
5:   IROW NNZ – INTEGER arrayInput
6:   ICOL NNZ – INTEGER arrayInput
On entry: the row and column indices of the nonzero elements supplied in array A.
Constraints:
IROW and ICOL must satisfy the following constraints (which may be imposed by a call to F11ZAF):
  • 1≤IROW i≤N and 1≤ICOL i≤N, for i=1,2,…,NNZ;
  • IROW i-1<IROW i or IROW i-1=IROW i and ICOL i-1<ICOL i, for i=2,3,…,NNZ.
7:   CHECK – CHARACTER(1)Input
On entry: specifies whether or not the CS representation of the matrix A, values of N, NNZ, IROW and ICOL should be checked.
CHECK='C'
Checks are carried on the values of N, NNZ, IROW and ICOL.
CHECK='N'
None of these checks are carried out.
See also Section 9.2.
Constraint: CHECK='C' or 'N'.
8:   X N – REAL (KIND=nag_wp) arrayInput
On entry: the vector x.
9:   Y N – REAL (KIND=nag_wp) arrayOutput
On exit: the vector y.
10:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, | TRANS≠'N' or 'T',
or | CHECK≠'C' or 'N'.
IFAIL=2
On entry, | N<1,
or | NNZ<1,
or | NNZ>N 2.
IFAIL=3
On entry, the arrays IROW and ICOL fail to satisfy the following constraints:
  • 1≤IROW i≤N and 1≤ICOL i≤N, for i=1,2,…,NNZ;
  • IROW i-1<IROW i, or IROW i-1=IROW i and ICOL i-1<ICOL i, for i=2,3,…,NNZ.
Therefore a nonzero element has been supplied which does not lie within the matrix A, is out of order, or has duplicate row and column indices. Call F11ZAF to reorder and sum or remove duplicates.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

The computed vector y satisfies the error bound:
  • y-Ax∞≤c n ε A∞x∞, if TRANS='N', or
  • y-AT x∞ ≤c n ε AT∞ x∞ , if TRANS='T',
where c n is a modest linear function of n, and ε is the machine precision.

8 Parallelism and Performance

F11XAF is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
F11XAF makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

9.1 Timing

The time taken for a call to F11XAF is proportional to NNZ.

9.2 Use of CHECK

It is expected that a common use of F11XAF will be to compute the matrix-vector product required in the application of F11BEF to sparse linear systems. In this situation F11XAF is likely to be called many times with the same matrix A. In the interests of both reliability and efficiency you are recommended to set CHECK='C' for the first of such calls, and to set CHECK='N' for all subsequent calls.

10 Example

This example reads in a sparse matrix A and a vector x. It then calls F11XAF to compute the matrix-vector product y=Ax and the transposed matrix-vector product y=AT x.

10.1 Program Text

Program Text (f11xafe.f90)

10.2 Program Data

Program Data (f11xafe.d)

10.3 Program Results

Program Results (f11xafe.r)

F11 Chapter Contents
F11 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F11XEF : NAG Library, Mark 26

F11 Chapter Contents
F11 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F11XEF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
▸▿ 9 Further Comments
9.1 Timing
9.2 Use of CHECK
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F11XEF computes a matrix-vector product involving a real sparse symmetric matrix stored in symmetric coordinate storage format.

2 Specification

SUBROUTINE F11XEF ( N, NNZ, A, IROW, ICOL, CHECK, X, Y, IFAIL)
INTEGER | N, NNZ, IROW(NNZ), ICOL(NNZ), IFAIL
REAL (KIND=nag_wp) | A(NNZ), X(N), Y(N)
CHARACTER(1) | CHECK

3 Description

F11XEF computes the matrix-vector product
y=Ax
where A is an n by n symmetric sparse matrix, of arbitrary sparsity pattern, stored in symmetric coordinate storage (SCS) format (see Section 2.1.2 in the F11 Chapter Introduction). The array A stores all nonzero elements in the lower triangular part of A, while arrays IROW and ICOL store the corresponding row and column indices respectively.
It is envisaged that a common use of F11XEF will be to compute the matrix-vector product required in the application of F11GEF to sparse symmetric linear systems. An illustration of this usage appears in F11JDF.

4 References

None.

5 Arguments

1:   N – INTEGERInput
On entry: n, the order of the matrix A.
Constraint: N≥1.
2:   NNZ – INTEGERInput
On entry: the number of nonzero elements in the lower triangular part of A.
Constraint: 1≤NNZ≤N×N+1/2.
3:   A NNZ – REAL (KIND=nag_wp) arrayInput
On entry: the nonzero elements in the lower triangular part of the matrix A, ordered by increasing row index, and by increasing column index within each row. Multiple entries for the same row and column indices are not permitted. The routine F11ZBF may be used to order the elements in this way.
4:   IROW NNZ – INTEGER arrayInput
5:   ICOL NNZ – INTEGER arrayInput
On entry: the row and column indices of the nonzero elements supplied in array A.
Constraints:
IROW and ICOL must satisfy these constraints (which may be imposed by a call to F11ZBF):
  • 1≤IROW i≤N and 1≤ICOL i≤IROW i, for i=1,2,…,NNZ;
  • IROW i-1<IROW i or IROW i-1=IROW i and ICOL i-1<ICOL i, for i=2,3,…,NNZ.
6:   CHECK – CHARACTER(1)Input
On entry: specifies whether or not the SCS representation of the matrix A, values of N, NNZ, IROW and ICOL should be checked.
CHECK='C'
Checks are carried out on the values of N, NNZ, IROW and ICOL.
CHECK='N'
None of these checks are carried out.
See also Section 9.2.
Constraint: CHECK='C' or 'N'.
7:   X N – REAL (KIND=nag_wp) arrayInput
On entry: the vector x.
8:   Y N – REAL (KIND=nag_wp) arrayOutput
On exit: the vector y.
9:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, CHECK≠'C' or 'N'.
IFAIL=2
On entry, | N<1,
or | NNZ<1,
or | NNZ>N×N+1/2.
IFAIL=3
On entry, the arrays IROW and ICOL fail to satisfy the following constraints:
  • 1≤IROW i≤N and 1≤ICOL i≤IROW i, for i=1,2,…,NNZ;
  • IROW i-1<IROW i or IROW i-1=IROW i and ICOL i-1<ICOL i, for i=2,3,…,NNZ.
Therefore a nonzero element has been supplied which does not lie in the lower triangular part of A, is out of order, or has duplicate row and column indices. Call F11ZBF to reorder and sum or remove duplicates.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

The computed vector y satisfies the error bound
y-Ax∞≤c n ε A∞x∞,
where c n is a modest linear function of n, and ε is the machine precision.

8 Parallelism and Performance

F11XEF is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
F11XEF makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

9.1 Timing

The time taken for a call to F11XEF is proportional to NNZ.

9.2 Use of CHECK

It is expected that a common use of F11XEF will be to compute the matrix-vector product required in the application of F11GEF to sparse symmetric linear systems. In this situation F11XEF is likely to be called many times with the same matrix A. In the interests of both reliability and efficiency you are recommended to set CHECK='C' for the first of such calls, and to set CHECK='N' for all subsequent calls.

10 Example

This example reads in a symmetric positive definite sparse matrix A and a vector x. It then calls F11XEF to compute the matrix-vector product y=Ax.

10.1 Program Text

Program Text (f11xefe.f90)

10.2 Program Data

Program Data (f11xefe.d)

10.3 Program Results

Program Results (f11xefe.r)

F11 Chapter Contents
F11 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F11XNF : NAG Library, Mark 26

F11 Chapter Contents
F11 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F11XNF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
▸▿ 9 Further Comments
9.1 Timing
9.2 Use of CHECK
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F11XNF computes a matrix-vector or conjugate transposed matrix-vector product involving a complex sparse non-Hermitian matrix stored in coordinate storage format.

2 Specification

SUBROUTINE F11XNF ( TRANS, N, NNZ, A, IROW, ICOL, CHECK, X, Y, IFAIL)
INTEGER | N, NNZ, IROW(NNZ), ICOL(NNZ), IFAIL
COMPLEX (KIND=nag_wp) | A(NNZ), X(N), Y(N)
CHARACTER(1) | TRANS, CHECK

3 Description

F11XNF computes either the matrix-vector product y=Ax, or the conjugate transposed matrix-vector product y=AH x, according to the value of the argument TRANS, where A is a complex n by n sparse non-Hermitian matrix, of arbitrary sparsity pattern. The matrix A is stored in coordinate storage (CS) format (see Section 2.1.1 in the F11 Chapter Introduction). The array A stores all the nonzero elements of A, while arrays IROW and ICOL store the corresponding row and column indices respectively.
It is envisaged that a common use of F11XNF will be to compute the matrix-vector product required in the application of F11BSF to sparse complex linear systems. This is illustrated in Section 10 in F11DRF.

4 References

None.

5 Arguments

1:   TRANS – CHARACTER(1)Input
On entry: specifies whether or not the matrix A is conjugate transposed.
TRANS='N'
y=Ax is computed.
TRANS='T'
y=AH x is computed.
Constraint: TRANS='N' or 'T'.
2:   N – INTEGERInput
On entry: n, the order of the matrix A.
Constraint: N≥1.
3:   NNZ – INTEGERInput
On entry: the number of nonzero elements in the matrix A.
Constraint: 1≤NNZ≤N 2.
4:   A NNZ – COMPLEX (KIND=nag_wp) arrayInput
On entry: the nonzero elements in the matrix A, ordered by increasing row index, and by increasing column index within each row. Multiple entries for the same row and column indices are not permitted. The routine F11ZNF may be used to order the elements in this way.
5:   IROW NNZ – INTEGER arrayInput
6:   ICOL NNZ – INTEGER arrayInput
On entry: the row and column indices of the nonzero elements supplied in array A.
Constraints:
  • 1≤IROW i≤N and 1≤ICOL i≤N, for i=1,2,…,NNZ;
  • IROW i-1<IROW i or IROW i-1=IROW i and ICOL i-1<ICOL i, for i=2,3,…,NNZ.
7:   CHECK – CHARACTER(1)Input
On entry: specifies whether or not the CS representation of the matrix A, values of N, NNZ, IROW and ICOL should be checked.
CHECK='C'
Checks are carried on the values of N, NNZ, IROW and ICOL.
CHECK='N'
None of these checks are carried out.
See also Section 9.2.
Constraint: CHECK='C' or 'N'.
8:   X N – COMPLEX (KIND=nag_wp) arrayInput
On entry: the vector x.
9:   Y N – COMPLEX (KIND=nag_wp) arrayOutput
On exit: the vector y.
10:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, | TRANS≠'N' or 'T',
or | CHECK≠'C' or 'N'.
IFAIL=2
On entry, | N<1,
or | NNZ<1,
or | NNZ>N 2.
IFAIL=3
On entry, the arrays IROW and ICOL fail to satisfy the following constraints:
  • 1≤IROW i≤N and 1≤ICOL i≤N, for i=1,2,…,NNZ;
  • IROW i-1<IROW i, or IROW i-1=IROW i and ICOL i-1<ICOL i, for i=2,3,…,NNZ.
Therefore a nonzero element has been supplied which does not lie within the matrix A, is out of order, or has duplicate row and column indices. Call F11ZNF to reorder and sum or remove duplicates.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

The computed vector y satisfies the error bound:
  • y-Ax∞≤c n ε A∞x∞, if TRANS='N', or
  • y-AH x∞ ≤c n ε AH∞ x∞, if TRANS='T',
where c n is a modest linear function of n, and ε is the machine precision.

8 Parallelism and Performance

F11XNF is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
F11XNF makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

9.1 Timing

The time taken for a call to F11XNF is proportional to NNZ.

9.2 Use of CHECK

It is expected that a common use of F11XNF will be to compute the matrix-vector product required in the application of F11BSF to sparse complex linear systems. In this situation F11XNF is likely to be called many times with the same matrix A. In the interests of both reliability and efficiency you are recommended to set CHECK='C' for the first of such calls, and to set CHECK='N' for all subsequent calls.

10 Example

This example reads in a complex sparse matrix A and a vector x. It then calls F11XNF to compute the matrix-vector product y=Ax and the conjugate transposed matrix-vector product y=AH x.

10.1 Program Text

Program Text (f11xnfe.f90)

10.2 Program Data

Program Data (f11xnfe.d)

10.3 Program Results

Program Results (f11xnfe.r)

F11 Chapter Contents
F11 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F11XSF : NAG Library, Mark 26

F11 Chapter Contents
F11 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F11XSF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
▸▿ 9 Further Comments
9.1 Timing
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F11XSF computes a matrix-vector product involving a complex sparse Hermitian matrix stored in symmetric coordinate storage format.

2 Specification

SUBROUTINE F11XSF ( N, NNZ, A, IROW, ICOL, CHECK, X, Y, IFAIL)
INTEGER | N, NNZ, IROW(NNZ), ICOL(NNZ), IFAIL
COMPLEX (KIND=nag_wp) | A(NNZ), X(N), Y(N)
CHARACTER(1) | CHECK

3 Description

F11XSF computes the matrix-vector product
y=Ax
where A is an n by n complex Hermitian sparse matrix, of arbitrary sparsity pattern, stored in symmetric coordinate storage (SCS) format (see Section 2.1.2 in the F11 Chapter Introduction). The array A stores all the nonzero elements in the lower triangular part of A, while arrays IROW and ICOL store the corresponding row and column indices respectively.

4 References

None.

5 Arguments

1:   N – INTEGERInput
On entry: n, the order of the matrix A.
Constraint: N≥1.
2:   NNZ – INTEGERInput
On entry: the number of nonzero elements in the lower triangular part of the matrix A.
Constraint: 1≤NNZ≤N×N+1/2.
3:   A NNZ – COMPLEX (KIND=nag_wp) arrayInput
On entry: the nonzero elements in the lower triangular part of the matrix A, ordered by increasing row index, and by increasing column index within each row. Multiple entries for the same row and column indices are not permitted. The routine F11ZPF may be used to order the elements in this way.
4:   IROW NNZ – INTEGER arrayInput
5:   ICOL NNZ – INTEGER arrayInput
On entry: the row and column indices of the nonzero elements supplied in array A.
Constraints:
IROW and ICOL must satisfy the following constraints (which may be imposed by a call to F11ZPF):
  • 1≤IROW i≤N and 1≤ICOL i≤IROW i, for i=1,2,…,NNZ;
  • IROW i-1<IROW i or IROW i-1=IROW i and ICOL i-1<ICOL i, for i=2,3,…,NNZ.
6:   CHECK – CHARACTER(1)Input
On entry: specifies whether or not the SCS representation of the matrix A, values of N, NNZ, IROW and ICOL should be checked.
CHECK='C'
Checks are carried out on the values of N, NNZ, IROW and ICOL.
CHECK='N'
None of these checks are carried out.
Constraint: CHECK='C' or 'N'.
7:   X N – COMPLEX (KIND=nag_wp) arrayInput
On entry: the vector x.
8:   Y N – COMPLEX (KIND=nag_wp) arrayOutput
On exit: the vector y.
9:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, CHECK≠'C' or 'N'.
IFAIL=2
On entry, | N<1,
or | NNZ<1,
or | NNZ>N×N+1/2.
IFAIL=3
On entry, the arrays IROW and ICOL fail to satisfy the following constraints:
  • 1≤IROW i≤N and 1≤ICOL i≤IROW i, for i=1,2,…,NNZ;
  • IROW i-1<IROW i or IROW i-1=IROW i and ICOL i-1<ICOL i, for i=2,3,…,NNZ.
Therefore a nonzero element has been supplied which does not lie in the lower triangular part of A, is out of order, or has duplicate row and column indices. Call F11ZPF to reorder and sum or remove duplicates.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

The computed vector y satisfies the error bound
y-Ax∞≤c n ε A∞x∞,
where c n is a modest linear function of n, and ε is the machine precision.

8 Parallelism and Performance

F11XSF is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
F11XSF makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

9.1 Timing

The time taken for a call to F11XSF is proportional to NNZ.

10 Example

This example reads in a complex sparse Hermitian positive definite matrix A and a vector x. It then calls F11XSF to compute the matrix-vector product y=Ax.

10.1 Program Text

Program Text (f11xsfe.f90)

10.2 Program Data

Program Data (f11xsfe.d)

10.3 Program Results

Program Results (f11xsfe.r)

F11 Chapter Contents
F11 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F11YEF : NAG Library, Mark 26

F11 Chapter Contents
F11 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F11YEF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F11YEF reduces the bandwidth of a sparse symmetric matrix stored in compressed column storage format using the Reverse Cuthill–McKee algorithm.

2 Specification

SUBROUTINE F11YEF ( N, NNZ, ICOLZP, IROWIX, LOPTS, MASK, PERM, INFO, IFAIL)
INTEGER | N, NNZ, ICOLZP(N+1), IROWIX(NNZ), MASK(*), PERM(N), INFO(4), IFAIL
LOGICAL | LOPTS(5)

3 Description

F11YEF takes the compressed column storage (CCS) representation (see Section 2.1.3 in the F11 Chapter Introduction) of an n by n symmetric matrix A and applies the Reverse Cuthill–McKee (RCM) algorithm which aims to minimize the bandwidth of the matrix A by reordering the rows and columns symmetrically. This also results in a lower profile of the matrix (see Section 9).
F11YEF can be useful for solving systems of equations Ax=b, as the permuted system PA PT Px=Pb (where P is the permutation matrix described by the vector PERM returned by F11YEF) may require less storage space and/or less computational steps when solving (see Wai-Hung and Sherman (1976)).
F11YEF may be used prior to F11JAF and F11JBF (see Section 10 in F11JBF).

4 References

Pissanetsky S (1984) Sparse Matrix Technology Academic Press
Wai-Hung L and Sherman A H (1976) Comparative analysis of the Cuthill–McKee and the reverse Cuthill–McKee ordering algorithms for sparse matrices SIAM J. Numer. Anal. 13(2) 198–213

5 Arguments

1:   N – INTEGERInput
On entry: n, the order of the matrix A.
Constraint: N≥1.
2:   NNZ – INTEGERInput
On entry: the number of nonzero elements in the matrix A.
Constraint: NNZ≥0.
3:   ICOLZP N+1 – INTEGER arrayInput
On entry: ICOLZP records the index into IROWIX which starts each new column.
Constraints:
  • 1≤ICOLZP i≤NNZ+1, for i=2,3,…,N;
  • ICOLZP 1=1;
  • ICOLZP N+1=NNZ+1, where ICOLZP i holds the position integer for the starts of the columns in IROWIX.
4:   IROWIX NNZ – INTEGER arrayInput
On entry: the row indices corresponding to the nonzero elements in the matrix A.
Constraint: 1≤IROWIX i≤N, for i=1,2,…,NNZ.
5:   LOPTS 5 – LOGICAL arrayInput
On entry: the options to be used by F11YEF.
LOPTS 1=.TRUE.
Row/column i of the matrix A will only be referenced if MASK i≠0, otherwise MASK will be ignored.
LOPTS 2=.TRUE.
The final permutation will not be reversed, that is, the Cuthill–McKee ordering will be returned. The bandwidth of the non-reversed matrix will be the same but the profile will be the same or larger (see Wai-Hung and Sherman (1976)).
LOPTS 3=.TRUE.
The matrix A will be checked for symmetrical sparsity pattern, otherwise not.
LOPTS 4=.TRUE.
The bandwidth and profile of the unpermuted matrix will be calculated, otherwise not.
LOPTS 5=.TRUE.
The bandwidth and profile of the permuted matrix will be calculated, otherwise not.
6:   MASK* – INTEGER arrayInput
Note: the dimension of the array MASK must be at least N if LOPTS 1=.TRUE., and at least 0 otherwise.
On entry: MASK is only referenced if LOPTS 1 is .TRUE.. A value of MASK i=0 indicates that the node corresponding to row or column i is not to be referenced. A value of MASK i≠0 indicates that the node corresponding to row or column i is to be referenced. In particular, rows and columns not referenced will not be permuted.
7:   PERM N – INTEGER arrayOutput
On exit: this will contain the permutation vector that describes the permutation matrix P for the reordering of the matrix A. The elements of the permutation matrix P are zero except for the unit elements in row i and column PERM i, i=1,2,…n.
8:   INFO 4 – INTEGER arrayOutput
On exit: statistics about the matrix A and the permuted matrix. The quantities below are calculated using any masking in effect otherwise the value zero is returned.
INFO 1
The bandwidth of the matrix A, if LOPTS 4=.TRUE..
INFO 2
The profile of the matrix A, if LOPTS 4=.TRUE..
INFO 3
The bandwidth of the permuted matrix PA PT, if LOPTS 5=.TRUE..
INFO 4
The profile of the permuted matrix PA PT, if LOPTS 5=.TRUE..
9:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, N=value.
Constraint: N≥1.
IFAIL=2
On entry, NNZ=value.
Constraint: NNZ≥1.
IFAIL=3
On entry, IROWIX value=value and N=value.
Constraint: 1≤IROWIX i≤N for all i.
IFAIL=4
On entry, ICOLZP value=value and NNZ=value.
Constraint: 1≤ICOLZP i≤NNZ for all i.
IFAIL=5
On entry, ICOLZP 1=value.
Constraint: ICOLZP 1=1.
On entry, ICOLZP N+1=value and NNZ=value.
Constraint: ICOLZP N+1=NNZ+1.
IFAIL=6
On entry, the matrix A is not symmetric.
Element value,value has no symmetric element.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

Not applicable.

8 Parallelism and Performance

F11YEF is not threaded in any implementation.

9 Further Comments

The bandwidth for a matrix A=a ij is defined as
b = max ij i-j ,   i,j=1,2,…,n​ s.t. ​a ij≠0 .
The profile is defined as
p = ∑ j=1 n bj ,  where ​ bj = max i i-j ,   i=1,2,…n ​ s.t. ​ a ij≠0 .

10 Example

This example reads the CCS representation of a real sparse matrix A and calls F11YEF to reorder the rows and columns and displays the results.

10.1 Program Text

Program Text (f11yefe.f90)

10.2 Program Data

Program Data (f11yefe.d)

10.3 Program Results

Program Results (f11yefe.r)

GnuplotProduced by GNUPLOT 4.6 patchlevel 3 Example Program Figure 1 : Original Matrix Ordering gnuplot_plot_1
GnuplotProduced by GNUPLOT 4.6 patchlevel 3 Figure 2 : Reverse Cuthill-McKee Reordering gnuplot_plot_1
F11 Chapter Contents
F11 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F11ZAF : NAG Library, Mark 26

F11 Chapter Contents
F11 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F11ZAF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F11ZAF sorts the nonzero elements of a real sparse nonsymmetric matrix, represented in coordinate storage format.

2 Specification

SUBROUTINE F11ZAF ( N, NNZ, A, IROW, ICOL, DUP, ZER, ISTR, IWORK, IFAIL)
INTEGER | N, NNZ, IROW(*), ICOL(*), ISTR(N+1), IWORK(N), IFAIL
REAL (KIND=nag_wp) | A(*)
CHARACTER(1) | DUP, ZER

3 Description

F11ZAF takes a coordinate storage (CS) representation (see Section 2.1.1 in the F11 Chapter Introduction) of a real n by n sparse nonsymmetric matrix A, and reorders the nonzero elements by increasing row index and increasing column index within each row. Entries with duplicate row and column indices may be removed, or the values may be summed. Any entries with zero values may optionally be removed.
F11ZAF also returns a pointer ISTR to the starting address of each row in A. This can be used to construct a compressed column storage (CCS) representation of the matrix (see Section 9).

4 References

None.

5 Arguments

1:   N – INTEGERInput
On entry: n, the order of the matrix A.
Constraint: N≥1.
2:   NNZ – INTEGERInput/Output
On entry: the number of nonzero elements in the matrix A.
Constraint: NNZ≥0.
On exit: the number of nonzero elements with unique row and column indices.
3:   A* – REAL (KIND=nag_wp) arrayInput/Output
Note: the dimension of the array A must be at least max 1,NNZ.
On entry: the nonzero elements of the matrix A. These may be in any order and there may be multiple nonzero elements with the same row and column indices.
On exit: the nonzero elements ordered by increasing row index, and by increasing column index within each row. Each nonzero element has a unique row and column index.
4:   IROW* – INTEGER arrayInput/Output
Note: the dimension of the array IROW must be at least max 1,NNZ.
On entry: the row indices corresponding to the nonzero elements supplied in the array A.
Constraint: 1≤IROW i≤N, for i=1,2,…,NNZ.
On exit: the first NNZ elements contain the row indices corresponding to the nonzero elements returned in the array A.
5:   ICOL* – INTEGER arrayInput/Output
Note: the dimension of the array ICOL must be at least max 1,NNZ.
On entry: the column indices corresponding to the nonzero elements supplied in the array A.
Constraint: 1≤ICOL i≤N, for i=1,2,…,NNZ.
On exit: the first NNZ elements contain the row indices corresponding to the nonzero elements returned in the array A.
6:   DUP – CHARACTER(1)Input
On entry: indicates how any nonzero elements with duplicate row and column indices are to be treated.
DUP='R'
The entries are removed.
DUP='S'
The relevant values in A are summed.
DUP='F'
The routine fails on detecting a duplicate, with IFAIL=3.
Constraint: DUP='R', 'S' or 'F'.
7:   ZER – CHARACTER(1)Input
On entry: indicates how any elements with zero values in A are to be treated.
ZER='R'
The entries are removed.
ZER='K'
The entries are kept.
ZER='F'
The routine fails on detecting a zero, with IFAIL=4.
Constraint: ZER='R', 'K' or 'F'.
8:   ISTR N+1 – INTEGER arrayOutput
On exit: ISTR i, for i=1,2,…,N, is the starting address in the arrays A, IROW and ICOL of row i of the matrix A. ISTR N+1 is the address of the last nonzero element in A plus one.
9:   IWORK N – INTEGER arrayWorkspace
10:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, | N<1,
or | NNZ<0,
or | DUP≠'R','S', or 'F',
or | ZER≠'R','K', or 'F'.
IFAIL=2
On entry, a nonzero element has been supplied which does not lie within the matrix A, i.e., one or more of the following constraints has been violated:
  • 1≤IROW i≤N,
  • 1≤ICOL i≤N,
for i=1,2,…,NNZ.
IFAIL=3
On entry, DUP='F' and nonzero elements have been supplied which have duplicate row and column indices.
IFAIL=4
On entry, ZER='F' and at least one matrix element has been supplied with a zero coefficient value.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

Not applicable.

8 Parallelism and Performance

F11ZAF is not threaded in any implementation.

9 Further Comments

The time taken for a call to F11ZAF is proportional to NNZ.
Note that the resulting matrix may have either rows or columns with no entries. If row i has no entries then ISTR i=ISTR i+1.
It is also possible to use this routine to convert between coordinate storage (CS) and compressed column storage (CCS) formats. To achieve this the CS storage format arrays IROW and ICOL must be interchanged in the call to F11ZAF. On exit from F11ZAF, the CCS representation of the matrix is then defined by arrays A, IROW and ISTR. This is illustrated in Section 10.

10 Example

This example reads the CS representation of a real sparse matrix A, calls F11ZAF to reorder the nonzero elements, and outputs the original and the reordered representations. It then calls F11ZAF again with the alternative ordering, creating a CCS representation which is then passed to a routine that computes a matrix norm for that representation.
A= 2.00 1.00 0 0 0 0 0 1.00 -1.00 0 4.00 0 1.00 0 1.00 0 0 0 1.00 2.00 0 -2.00 0 0 3.00 .

10.1 Program Text

Program Text (f11zafe.f90)

10.2 Program Data

Program Data (f11zafe.d)

10.3 Program Results

Program Results (f11zafe.r)

F11 Chapter Contents
F11 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F11ZBF : NAG Library, Mark 26

F11 Chapter Contents
F11 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F11ZBF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F11ZBF sorts the nonzero elements of a real sparse symmetric matrix, represented in symmetric coordinate storage format.

2 Specification

SUBROUTINE F11ZBF ( N, NNZ, A, IROW, ICOL, DUP, ZER, ISTR, IWORK, IFAIL)
INTEGER | N, NNZ, IROW(*), ICOL(*), ISTR(N+1), IWORK(N), IFAIL
REAL (KIND=nag_wp) | A(*)
CHARACTER(1) | DUP, ZER

3 Description

F11ZBF takes a symmetric coordinate storage (SCS) representation (see Section 2.1.2 in the F11 Chapter Introduction) of a real n by n sparse symmetric matrix A, and reorders the nonzero elements by increasing row index and increasing column index within each row. Entries with duplicate row and column indices may be removed, or the values may be summed. Any entries with zero values may optionally be removed.
F11ZBF also returns a pointer ISTR to the starting address of each row in A.

4 References

None.

5 Arguments

1:   N – INTEGERInput
On entry: n, the order of the matrix A.
Constraint: N≥1.
2:   NNZ – INTEGERInput/Output
On entry: the number of nonzero elements in the lower triangular part of the matrix A.
Constraint: NNZ≥0.
On exit: the number of lower triangular nonzero elements with unique row and column indices.
3:   A* – REAL (KIND=nag_wp) arrayInput/Output
Note: the dimension of the array A must be at least max 1,NNZ.
On entry: the nonzero elements of the lower triangular part of the real matrix A. These may be in any order and there may be multiple nonzero elements with the same row and column indices.
On exit: the lower triangular nonzero elements ordered by increasing row index, and by increasing column index within each row. Each nonzero element has a unique row and column index.
4:   IROW* – INTEGER arrayInput/Output
Note: the dimension of the array IROW must be at least max 1,NNZ.
On entry: the row indices corresponding to the nonzero elements supplied in the array A.
Constraint: 1≤IROW i≤N, for i=1,2,…,NNZ.
On exit: the first NNZ elements contain the row indices corresponding to the nonzero elements returned in the array A.
5:   ICOL* – INTEGER arrayInput/Output
Note: the dimension of the array ICOL must be at least max 1,NNZ.
On entry: the column indices corresponding to the nonzero elements supplied in the array A.
Constraint: 1≤ICOL i≤IROW i, for i=1,2,…,NNZ.
On exit: the first NNZ elements contain the column indices corresponding to the nonzero elements returned in the array A.
6:   DUP – CHARACTER(1)Input
On entry: indicates how any nonzero elements with duplicate row and column indices are to be treated.
DUP='R'
The entries are removed.
DUP='S'
The relevant values in A are summed.
Constraint: DUP='R' or 'S'.
7:   ZER – CHARACTER(1)Input
On entry: indicates how any elements with zero values in A are to be treated.
ZER='R'
The entries are removed.
ZER='K'
The entries are kept.
Constraint: ZER='R' or 'K'.
8:   ISTR N+1 – INTEGER arrayOutput
On exit: ISTR i, for i=1,2,…,N, is the starting address in the arrays A, IROW and ICOL of row i of the matrix A. ISTR N+1 is the address of the last nonzero element in A plus one.
9:   IWORK N – INTEGER arrayWorkspace
10:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, | N<1,
or | NNZ<0,
or | DUP≠'R' or 'S'.
or | ZER≠'R' or 'K'.
IFAIL=2
On entry, a nonzero element has been supplied which does not lie in the lower triangular part of A, i.e., one or more of the following constraints has been violated:
  • 1≤IROW i≤N,
  • 1≤ICOL i≤IROW i,
for i=1,2,…,NNZ.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

Not applicable.

8 Parallelism and Performance

F11ZBF is not threaded in any implementation.

9 Further Comments

The time taken for a call to F11ZBF is proportional to NNZ.
Note that the resulting matrix may have either rows or columns with no entries. If row i has no entries then ISTR i=ISTR i+1.

10 Example

This example reads the SCS representation of a real sparse symmetric matrix A, calls F11ZBF to reorder the nonzero elements, and outputs the original and the reordered representations.

10.1 Program Text

Program Text (f11zbfe.f90)

10.2 Program Data

Program Data (f11zbfe.d)

10.3 Program Results

Program Results (f11zbfe.r)

F11 Chapter Contents
F11 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F11ZNF : NAG Library, Mark 26

F11 Chapter Contents
F11 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F11ZNF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F11ZNF sorts the nonzero elements of a complex sparse non-Hermitian matrix, represented in coordinate storage format.

2 Specification

SUBROUTINE F11ZNF ( N, NNZ, A, IROW, ICOL, DUP, ZER, ISTR, IWORK, IFAIL)
INTEGER | N, NNZ, IROW(*), ICOL(*), ISTR(N+1), IWORK(N), IFAIL
COMPLEX (KIND=nag_wp) | A(*)
CHARACTER(1) | DUP, ZER

3 Description

F11ZNF takes a coordinate storage (CS) representation (see Section 2.1.1 in the F11 Chapter Introduction) of a sparse n by n complex non-Hermitian matrix A, and reorders the nonzero elements by increasing row index and increasing column index within each row. Entries with duplicate row and column indices may be removed, or the values may be summed. Any entries with zero values may optionally be removed.
The routine also returns a pointer array ISTR to the starting address of each row in A.

4 References

None.

5 Arguments

1:   N – INTEGERInput
On entry: n, the order of the matrix A.
Constraint: N≥1.
2:   NNZ – INTEGERInput/Output
On entry: the number of nonzero elements in the matrix A.
Constraint: NNZ≥0.
On exit: the number of nonzero elements with unique row and column indices.
3:   A* – COMPLEX (KIND=nag_wp) arrayInput/Output
Note: the dimension of the array A must be at least max 1,NNZ.
On entry: the nonzero elements of the matrix A. These may be in any order and there may be multiple nonzero elements with the same row and column indices.
On exit: the nonzero elements ordered by increasing row index, and by increasing column index within each row. Each nonzero element has a unique row and column index.
4:   IROW* – INTEGER arrayInput/Output
Note: the dimension of the array IROW must be at least max 1,NNZ.
On entry: the row indices corresponding to the nonzero elements supplied in the array A.
Constraint: 1≤IROW i≤N, for i=1,2,…,NNZ.
On exit: the first NNZ elements contain the row indices corresponding to the nonzero elements returned in the array A.
5:   ICOL* – INTEGER arrayInput/Output
Note: the dimension of the array ICOL must be at least max 1,NNZ.
On entry: the column indices corresponding to the nonzero elements supplied in the array A.
Constraint: 1≤ICOL i≤N, for i=1,2,…,NNZ.
On exit: the first NNZ elements contain the row indices corresponding to the nonzero elements returned in the array A.
6:   DUP – CHARACTER(1)Input
On entry: indicates how any nonzero elements with duplicate row and column indices are to be treated.
DUP='R'
The entries are removed.
DUP='S'
The relevant values in A are summed.
DUP='F'
The routine fails with IFAIL=3 on detecting a duplicate.
Constraint: DUP='R', 'S' or 'F'.
7:   ZER – CHARACTER(1)Input
On entry: indicates how any elements with zero values in array A are to be treated.
ZER='R'
The entries are removed.
ZER='K'
The entries are kept.
ZER='F'
The routine fails with IFAIL=4 on detecting a zero.
Constraint: ZER='R', 'K' or 'F'.
8:   ISTR N+1 – INTEGER arrayOutput
On exit: ISTR i, for i=1,2,…,N, is the starting address in the arrays A, IROW and ICOL of row i of the matrix A. ISTR N+1 is the address of the last nonzero element in A plus one.
9:   IWORK N – INTEGER arrayWorkspace
10:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, | N<1,
or | NNZ<0,
or | DUP≠'R', 'S' or 'F',
or | ZER≠'R', 'K' or 'F'.
IFAIL=2
On entry, a nonzero element has been supplied which does not lie within the matrix A, i.e., one or more of the following constraints have been violated:
  • 1≤IROW i≤N,
  • 1≤ICOL i≤N,
for i=1,2,…,NNZ.
IFAIL=3
On entry, DUP='F' and nonzero elements have been supplied which have duplicate row and column indices.
IFAIL=4
On entry, ZER='F' and at least one matrix element has been supplied with a zero coefficient value.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

Not applicable.

8 Parallelism and Performance

F11ZNF is not threaded in any implementation.

9 Further Comments

The time taken for a call to F11ZNF is proportional to NNZ.
Note that the resulting matrix may have either rows or columns with no entries. If row i has no entries then ISTR i=ISTR i+1.

10 Example

This example reads the CS representation of a complex sparse matrix A, calls F11ZNF to reorder the nonzero elements, and outputs the original and the reordered representations.

10.1 Program Text

Program Text (f11znfe.f90)

10.2 Program Data

Program Data (f11znfe.d)

10.3 Program Results

Program Results (f11znfe.r)

F11 Chapter Contents
F11 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F11ZPF : NAG Library, Mark 26

F11 Chapter Contents
F11 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F11ZPF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F11ZPF sorts the nonzero elements of a sparse complex Hermitian matrix, represented in symmetric coordinate storage format.

2 Specification

SUBROUTINE F11ZPF ( N, NNZ, A, IROW, ICOL, DUP, ZER, ISTR, IWORK, IFAIL)
INTEGER | N, NNZ, IROW(*), ICOL(*), ISTR(N+1), IWORK(N), IFAIL
COMPLEX (KIND=nag_wp) | A(*)
CHARACTER(1) | DUP, ZER

3 Description

F11ZPF takes a symmetric coordinate storage (SCS) representation (see Section 2.1.2 in the F11 Chapter Introduction) of a sparse n by n complex Hermitian matrix A, and reorders the nonzero elements by increasing row index and increasing column index within each row. Entries with duplicate row and column indices may be removed, or the values may be summed. Any entries with zero values may optionally be removed.
The routine also returns a pointer array ISTR to the starting address of each row in A.

4 References

None.

5 Arguments

1:   N – INTEGERInput
On entry: n, the order of the matrix A.
Constraint: N≥1.
2:   NNZ – INTEGERInput/Output
On entry: the number of nonzero elements in the lower triangular part of the matrix A.
Constraint: NNZ≥0.
On exit: the number of lower triangular nonzero elements with unique row and column indices.
3:   A* – COMPLEX (KIND=nag_wp) arrayInput/Output
Note: the dimension of the array A must be at least max 1,NNZ.
On entry: the nonzero elements of the lower triangular part of the complex matrix A. These may be in any order and there may be multiple nonzero elements with the same row and column indices.
On exit: the lower triangular nonzero elements ordered by increasing row index, and by increasing column index within each row. Each nonzero element has a unique row and column index.
4:   IROW* – INTEGER arrayInput/Output
Note: the dimension of the array IROW must be at least max 1,NNZ.
On entry: the row indices corresponding to the nonzero elements supplied in the array A.
Constraint: 1≤IROW i≤N, for i=1,2,…,NNZ.
On exit: the first NNZ elements contain the row indices corresponding to the nonzero elements returned in the array A.
5:   ICOL* – INTEGER arrayInput/Output
Note: the dimension of the array ICOL must be at least max 1,NNZ.
On entry: the column indices corresponding to the nonzero elements supplied in the array A.
Constraint: 1≤ICOL i≤IROW i, for i=1,2,…,NNZ.
On exit: the first NNZ elements contain the column indices corresponding to the nonzero elements returned in the array A.
6:   DUP – CHARACTER(1)Input
On entry: indicates how any nonzero elements with duplicate row and column indices are to be treated.
DUP='R'
The entries are removed.
DUP='S'
The relevant values in A are summed.
DUP='F'
The routine fails with IFAIL=3 on detecting a duplicate.
Constraint: DUP='R', 'S' or 'F'.
7:   ZER – CHARACTER(1)Input
On entry: indicates how any elements with zero values in array A are to be treated.
ZER='R'
The entries are removed.
ZER='K'
The entries are kept.
ZER='F'
The routine fails with IFAIL=4 on detecting a zero.
Constraint: ZER='R', 'K' or 'F'.
8:   ISTR N+1 – INTEGER arrayOutput
On exit: ISTR i, for i=1,2,…,N, is the starting address in the arrays A, IROW and ICOL of row i of the matrix A. ISTR N+1 is the address of the last nonzero element in A plus one.
9:   IWORK N – INTEGER arrayWorkspace
10:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, | N<1,
or | NNZ<0,
or | DUP≠'R', 'S' or 'F',
or | ZER≠'R', 'K' or 'F'.
IFAIL=2
On entry, a nonzero element has been supplied which does not lie in the lower triangular part of A, i.e., one or more of the following constraints have been violated:
  • 1≤IROW i≤N,
  • 1≤ICOL i≤IROW i,
for i=1,2,…,NNZ.
IFAIL=3
On entry, DUP='F' and nonzero elements have been supplied which have duplicate row and column indices.
IFAIL=4
On entry, ZER='F' and at least one matrix element has been supplied with a zero coefficient value.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

Not applicable.

8 Parallelism and Performance

F11ZPF is not threaded in any implementation.

9 Further Comments

The time taken for a call to F11ZPF is proportional to NNZ.
Note that the resulting matrix may have either rows or columns with no entries. If row i has no entries then ISTR i=ISTR i+1.

10 Example

This example reads the SCS representation of a complex sparse Hermitian matrix A, calls F11ZPF to reorder the nonzero elements, and outputs the original and the reordered representations.

10.1 Program Text

Program Text (f11zpfe.f90)

10.2 Program Data

Program Data (f11zpfe.d)

10.3 Program Results

Program Results (f11zpfe.r)

F11 Chapter Contents
F11 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F12AAF : NAG Library, Mark 26

F12 Chapter Contents
F12 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F12AAF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F12AAF is a setup routine in a suite of routines consisting of F12AAF, F12ABF, F12ACF, F12ADF and F12AEF. It is used to find some of the eigenvalues (and optionally the corresponding eigenvectors) of a standard or generalized eigenvalue problem defined by real nonsymmetric matrices.
The suite of routines is suitable for the solution of large sparse, standard or generalized, nonsymmetric eigenproblems where only a few eigenvalues from a selected range of the spectrum are required.

2 Specification

SUBROUTINE F12AAF ( N, NEV, NCV, ICOMM, LICOMM, COMM, LCOMM, IFAIL)
INTEGER | N, NEV, NCV, ICOMM(max(1,LICOMM)), LICOMM, LCOMM, IFAIL
REAL (KIND=nag_wp) | COMM(max(1,LCOMM))

3 Description

The suite of routines is designed to calculate some of the eigenvalues, λ , (and optionally the corresponding eigenvectors, x ) of a standard eigenvalue problem Ax = λx , or of a generalized eigenvalue problem Ax = λBx of order n , where n is large and the coefficient matrices A and B are sparse, real and nonsymmetric. The suite can also be used to find selected eigenvalues/eigenvectors of smaller scale dense, real and nonsymmetric problems.
F12AAF is a setup routine which must be called before F12ABF, the reverse communication iterative solver, and before F12ADF, the options setting routine. F12ACF is a post-processing routine that must be called following a successful final exit from F12ABF, while F12AEF can be used to return additional monitoring information during the computation.
This setup routine initializes the communication arrays, sets (to their default values) all options that can be set by you via the option setting routine F12ADF, and checks that the lengths of the communication arrays as passed by you are of sufficient length. For details of the options available and how to set them see Section 11.1 in F12ADF.

4 References

Lehoucq R B (2001) Implicitly restarted Arnoldi methods and subspace iteration SIAM Journal on Matrix Analysis and Applications 23 551–562
Lehoucq R B and Scott J A (1996) An evaluation of software for computing eigenvalues of sparse nonsymmetric matrices Preprint MCS-P547-1195 Argonne National Laboratory
Lehoucq R B and Sorensen D C (1996) Deflation techniques for an implicitly restarted Arnoldi iteration SIAM Journal on Matrix Analysis and Applications 17 789–821
Lehoucq R B, Sorensen D C and Yang C (1998) ARPACK Users' Guide: Solution of Large-scale Eigenvalue Problems with Implicitly Restarted Arnoldi Methods SIAM, Philidelphia

5 Arguments

1:   N – INTEGERInput
On entry: the order of the matrix A (and the order of the matrix B for the generalized problem) that defines the eigenvalue problem.
Constraint: N>0.
2:   NEV – INTEGERInput
On entry: the number of eigenvalues to be computed.
Constraint: 0<NEV<N-1.
3:   NCV – INTEGERInput
On entry: the number of Arnoldi basis vectors to use during the computation.
At present there is no a priori analysis to guide the selection of NCV relative to NEV. However, it is recommended that NCV≥2×NEV+1. If many problems of the same type are to be solved, you should experiment with increasing NCV while keeping NEV fixed for a given test problem. This will usually decrease the required number of matrix-vector operations but it also increases the work and storage required to maintain the orthogonal basis vectors. The optimal ‘cross-over’ with respect to CPU time is problem dependent and must be determined empirically.
Constraint: NEV+1<NCV≤N.
4:   ICOMM max 1,LICOMM – INTEGER arrayCommunication Array
On exit: contains data to be communicated to the other routines in the suite.
5:   LICOMM – INTEGERInput
On entry: the dimension of the array ICOMM as declared in the (sub)program from which F12AAF is called.
If LICOMM=-1, a workspace query is assumed and the routine only calculates the required dimensions of ICOMM and COMM, which it returns in ICOMM 1 and COMM 1 respectively.
Constraint: LICOMM≥140 ​ or ​ LICOMM=-1.
6:   COMM max 1,LCOMM – REAL (KIND=nag_wp) arrayCommunication Array
On exit: contains data to be communicated to the other routines in the suite.
7:   LCOMM – INTEGERInput
On entry: the dimension of the array COMM as declared in the (sub)program from which F12AAF is called.
If LCOMM=-1, a workspace query is assumed and the routine only calculates the dimensions of ICOMM and COMM required by F12ABF, which it returns in ICOMM 1 and COMM 1 respectively.
Constraint: LCOMM≥3×N+3×NCV×NCV+6×NCV+60 ​ or ​ LCOMM=-1.
8:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, N≤0.
IFAIL=2
On entry, NEV≤0.
IFAIL=3
On entry, NCV<NEV+2 or NCV>N.
IFAIL=4
On entry, LICOMM<140 and LICOMM≠-1.
IFAIL=5
On entry, LCOMM<3×N+3×NCV×NCV+6×NCV+60 and LCOMM≠-1.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

Not applicable.

8 Parallelism and Performance

F12AAF is not threaded in any implementation.

9 Further Comments

None.

10 Example

This example solves Ax = λx in regular mode, where A is obtained from the standard central difference discretization of the convection-diffusion operator ∂2 u ∂x 2 + ∂2 u ∂y 2 + ρ ∂u ∂x on the unit square, with zero Dirichlet boundary conditions, where ρ=100.

10.1 Program Text

Program Text (f12aafe.f90)

10.2 Program Data

Program Data (f12aafe.d)

10.3 Program Results

Program Results (f12aafe.r)

F12 Chapter Contents
F12 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F12ABF : NAG Library, Mark 26

F12 Chapter Contents
F12 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F12ABF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.
Note: this routine uses optional parameters to define choices in the problem specification. If you wish to use default settings for all of the optional parameters, then the option setting routine F12ADF need not be called. If, however, you wish to reset some or all of the settings please refer to Section 11 in F12ADF for a detailed description of the specification of the optional parameters.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F12ABF is an iterative solver used to find some of the eigenvalues (and optionally the corresponding eigenvectors) of a standard or generalized eigenvalue problem defined by real nonsymmetric matrices. This is part of a suite of routines that also includes F12AAF, F12ACF, F12ADF and F12AEF. It is

2 Specification

SUBROUTINE F12ABF ( IREVCM, RESID, V, LDV, X, MX, NSHIFT, COMM, ICOMM, IFAIL)
INTEGER | IREVCM, LDV, NSHIFT, ICOMM(*), IFAIL
REAL (KIND=nag_wp) | RESID(*), V(LDV,*), X(*), MX(*), COMM(*)

3 Description

The suite of routines is designed to calculate some of the eigenvalues, λ , (and optionally the corresponding eigenvectors, x ) of a standard eigenvalue problem Ax = λx , or of a generalized eigenvalue problem Ax = λBx of order n , where n is large and the coefficient matrices A and B are sparse, real and nonsymmetric. The suite can also be used to find selected eigenvalues/eigenvectors of smaller scale dense, real and nonsymmetric problems.
F12ABF is a reverse communication routine, based on the ARPACK routine dnaupd, using the Implicitly Restarted Arnoldi iteration method. The method is described in Lehoucq and Sorensen (1996) and Lehoucq (2001) while its use within the ARPACK software is described in great detail in Lehoucq et al. (1998). An evaluation of software for computing eigenvalues of sparse nonsymmetric matrices is provided in Lehoucq and Scott (1996). This suite of routines offers the same functionality as the ARPACK software for real nonsymmetric problems, but the interface design is quite different in order to make the option setting clearer and to simplify the interface of F12ABF.
The setup routine F12AAF must be called before F12ABF, the reverse communication iterative solver. Options may be set for F12ABF by prior calls to the option setting routine F12ADF and a post-processing routine F12ACF must be called following a successful final exit from F12ABF. F12AEF, may be called following certain flagged, intermediate exits from F12ABF to provide additional monitoring information about the computation.
F12ABF uses reverse communication, i.e., it returns repeatedly to the calling program with the argument IREVCM (see Section 5) set to specified values which require the calling program to carry out one of the following tasks:
  • – compute the matrix-vector product y = OPx , where OP is defined by the computational mode;
  • – compute the matrix-vector product y = Bx ;
  • – notify the completion of the computation;
  • – allow the calling program to monitor the solution.
The problem type to be solved (standard or generalized), the spectrum of eigenvalues of interest, the mode used (regular, regular inverse, shifted inverse, shifted real or shifted imaginary) and other options can all be set using the option setting routine F12ADF (see Section 11.1 in F12ADF for details on setting options and of the default settings).

4 References

Lehoucq R B (2001) Implicitly restarted Arnoldi methods and subspace iteration SIAM Journal on Matrix Analysis and Applications 23 551–562
Lehoucq R B and Scott J A (1996) An evaluation of software for computing eigenvalues of sparse nonsymmetric matrices Preprint MCS-P547-1195 Argonne National Laboratory
Lehoucq R B and Sorensen D C (1996) Deflation techniques for an implicitly restarted Arnoldi iteration SIAM Journal on Matrix Analysis and Applications 17 789–821
Lehoucq R B, Sorensen D C and Yang C (1998) ARPACK Users' Guide: Solution of Large-scale Eigenvalue Problems with Implicitly Restarted Arnoldi Methods SIAM, Philidelphia

5 Arguments

Note: this routine uses reverse communication. Its use involves an initial entry, intermediate exits and re-entries, and a final exit, as indicated by the argument IREVCM. Between intermediate exits and re-entries, all arguments other than X, MX and COMM must remain unchanged.
1:   IREVCM – INTEGERInput/Output
On initial entry: IREVCM=0, otherwise an error condition will be raised.
On intermediate re-entry: must be unchanged from its previous exit value. Changing IREVCM to any other value between calls will result in an error.
On intermediate exit: has the following meanings.
IREVCM=-1
The calling program must compute the matrix-vector product y=OPx, where x is stored in X (by default) or in the array COMM (starting from the location given by the first element of ICOMM) when the option Pointers=YES is set in a prior call to F12ADF. The result y is returned in X (by default) or in the array COMM (starting from the location given by the second element of ICOMM) when the option Pointers=YES is set. If B is not symmetric semidefinite then the precomputed values in MX should not be used (see the explanation under IREVCM=2).
IREVCM=1
The calling program must compute the matrix-vector product y=OPx. This is similar to the case IREVCM=-1 except that the result of the matrix-vector product Bx (as required in some computational modes) has already been computed and is available in MX (by default) or in the array COMM (starting from the location given by the third element of ICOMM) when the option Pointers=YES is set.
IREVCM=2
The calling program must compute the matrix-vector product y=Bx, where x is stored as described in the case IREVCM=-1 and y is returned in the location described by the case IREVCM=1. This computation is requested when solving the Generalized problem using either Shifted Inverse Imaginary or Shifted Inverse Real; in these cases B is used as an inner-product space and requires that B be symmetric semidefinite. If neither A nor B is symmetric semidefinite then the problem should be reformulated in a Standard form.
IREVCM=3
Compute the NSHIFT real and imaginary parts of the shifts where the real parts are to be returned in the first NSHIFT locations of the array X and the imaginary parts are to be returned in the first NSHIFT locations of the array MX. Only complex conjugate pairs of shifts may be applied and the pairs must be placed in consecutive locations. This value of IREVCM will only arise if the optional parameter Supplied Shifts is set in a prior call to F12ADF which is intended for experienced users only; the default and recommended option is to use exact shifts (see Lehoucq et al. (1998) for details).
IREVCM=4
Monitoring step: a call to F12AEF can now be made to return the number of Arnoldi iterations, the number of converged Ritz values, their real and imaginary parts, and the corresponding Ritz estimates.
On final exit: IREVCM=5: F12ABF has completed its tasks. The value of IFAIL determines whether the iteration has been successfully completed, or whether errors have been detected. On successful completion F12ACF must be called to return the requested eigenvalues and eigenvectors (and/or Schur vectors).
Constraint: on initial entry, IREVCM=0; on re-entry IREVCM must remain unchanged.
2:   RESID* – REAL (KIND=nag_wp) arrayInput/Output
Note: the dimension of the array RESID must be at least N (see F12AAF).
On initial entry: need not be set unless the option Initial Residual has been set in a prior call to F12ADF in which case RESID should contain an initial residual vector, possibly from a previous run.
On intermediate re-entry: must be unchanged from its previous exit. Changing RESID to any other value between calls may result in an error exit.
On intermediate exit: contains the current residual vector.
On final exit: contains the final residual vector.
3:   V LDV* – REAL (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array V must be at least max 1,NCV (see F12AAF).
On initial entry: need not be set.
On intermediate re-entry: must be unchanged from its previous exit.
On intermediate exit: contains the current set of Arnoldi basis vectors.
On final exit: contains the final set of Arnoldi basis vectors.
4:   LDV – INTEGERInput
On entry: the first dimension of the array V as declared in the (sub)program from which F12ABF is called.
Constraint: LDV≥N.
5:   X* – REAL (KIND=nag_wp) arrayInput/Output
Note: the dimension of the array X must be at least N if Pointers=NO (default) and at least 1 if Pointers=YES (see F12AAF).
On initial entry: need not be set, it is used as a convenient mechanism for accessing elements of COMM.
On intermediate re-entry: if Pointers=YES, X need not be set.
If Pointers=NO, X must contain the result of y=OPx when IREVCM returns the value -1 or +1. It must return the real parts of the computed shifts when IREVCM returns the value 3.
On intermediate exit: if Pointers=YES, X is not referenced.
If Pointers=NO, X contains the vector x when IREVCM returns the value -1 or +1.
On final exit: does not contain useful data.
6:   MX* – REAL (KIND=nag_wp) arrayInput/Output
Note: the dimension of the array MX must be at least N if Pointers=NO (default) and at least 1 if Pointers=YES (see F12AAF).
On initial entry: need not be set, it is used as a convenient mechanism for accessing elements of COMM.
On intermediate re-entry: if Pointers=YES, MX need not be set.
If Pointers=NO, MX must contain the result of y=Bx when IREVCM returns the value 2. It must return the imaginary parts of the computed shifts when IREVCM returns the value 3.
On intermediate exit: if Pointers=YES, MX is not referenced.
If Pointers=NO, MX contains the vector Bx when IREVCM returns the value +1.
On final exit: does not contain any useful data.
7:   NSHIFT – INTEGEROutput
On intermediate exit: if the option Supplied Shifts is set and IREVCM returns a value of 3, NSHIFT returns the number of complex shifts required.
8:   COMM* – REAL (KIND=nag_wp) arrayCommunication Array
Note: the dimension of the array COMM must be at least max 1,LCOMM (see F12AAF).
On initial entry: must remain unchanged following a call to the setup routine F12AAF.
On exit: contains data defining the current state of the iterative process.
9:   ICOMM* – INTEGER arrayCommunication Array
Note: the dimension of the array ICOMM must be at least max 1,LICOMM (see F12AAF).
On initial entry: must remain unchanged following a call to the setup routine F12AAF.
On exit: contains data defining the current state of the iterative process.
10:   IFAIL – INTEGERInput/Output
On initial entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, because for this routine the values of the output arguments may be useful even if IFAIL≠0 on exit, the recommended value is -1. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On intermediate exit: the value of IFAIL is meaningless and should be ignored.
On final exit: (i.e., when IREVCM=5) IFAIL=0, unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On initial entry, the maximum number of iterations ≤ 0 , the option Iteration Limit has been set to a non-positive value.
IFAIL=2
The options Generalized and Regular are incompatible.
IFAIL=3
The option Initial Residual was selected but the starting vector held in RESID is zero.
IFAIL=4
The maximum number of iterations has been reached. Some Ritz values may have converged; a subsequent call to F12ACF will return the number of converged values and the converged values.
IFAIL=5
No shifts could be applied during a cycle of the implicitly restarted Arnoldi iteration. One possibility is to increase the size of NCV relative to NEV (see Section 5 in F12AAF for details of these arguments).
IFAIL=6
Could not build an Arnoldi factorization. Consider changing NCV or NEV in the initialization routine (see Section 5 in F12AAF for details of these arguments).
IFAIL=7
Unexpected error in internal call to compute eigenvalues and corresponding error bounds of the current upper Hessenberg matrix. Please contact NAG.
IFAIL=8
Either the initialization routine F12AAF has not been called prior to the first call of this routine or a communication array has become corrupted.
IFAIL=9
An unexpected error has occurred. Please contact NAG.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

The relative accuracy of a Ritz value, λ , is considered acceptable if its Ritz estimate ≤ Tolerance × λ . The default Tolerance used is the machine precision given by X02AJF.

8 Parallelism and Performance

F12ABF is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
F12ABF makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

None.

10 Example

This example solves Ax = λx in shift-invert mode, where A is obtained from the standard central difference discretization of the convection-diffusion operator ∂2 u ∂x 2 + ∂2 u ∂y 2 + ρ ∂u ∂x on the unit square, with zero Dirichlet boundary conditions. The shift used is a real number.

10.1 Program Text

Program Text (f12abfe.f90)

10.2 Program Data

Program Data (f12abfe.d)

10.3 Program Results

Program Results (f12abfe.r)

F12 Chapter Contents
F12 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F12ACF : NAG Library, Mark 26

F12 Chapter Contents
F12 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F12ACF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.
Note: this routine uses optional parameters to define choices in the problem specification. If you wish to use default settings for all of the optional parameters, then the option setting routine F12ADF need not be called. If, however, you wish to reset some or all of the settings please refer to Section 11 in F12ADF for a detailed description of the specification of the optional parameters.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F12ACF is a post-processing routine that must be called following a final exit from F12ABF. These are part of a suite of routines for the solution of real sparse eigensystems. The suite also includes F12AAF, F12ADF and F12AEF.

2 Specification

SUBROUTINE F12ACF ( NCONV, DR, DI, Z, LDZ, SIGMAR, SIGMAI, RESID, V, LDV, COMM, ICOMM, IFAIL)
INTEGER | NCONV, LDZ, LDV, ICOMM(*), IFAIL
REAL (KIND=nag_wp) | DR(*), DI(*), Z(LDZ,*), SIGMAR, SIGMAI, RESID(*), V(LDV,*), COMM(*)

3 Description

The suite of routines is designed to calculate some of the eigenvalues, λ , (and optionally the corresponding eigenvectors, x ) of a standard eigenvalue problem Ax = λx , or of a generalized eigenvalue problem Ax = λBx of order n , where n is large and the coefficient matrices A and B are sparse, real and nonsymmetric. The suite can also be used to find selected eigenvalues/eigenvectors of smaller scale dense, real and nonsymmetric problems.
Following a call to F12ABF, F12ACF returns the converged approximations to eigenvalues and (optionally) the corresponding approximate eigenvectors and/or an orthonormal basis for the associated approximate invariant subspace. The eigenvalues (and eigenvectors) are selected from those of a standard or generalized eigenvalue problem defined by real nonsymmetric matrices. There is negligible additional cost to obtain eigenvectors; an orthonormal basis is always computed, but there is an additional storage cost if both are requested.
F12ACF is based on the routine dneupd from the ARPACK package, which uses the Implicitly Restarted Arnoldi iteration method. The method is described in Lehoucq and Sorensen (1996) and Lehoucq (2001) while its use within the ARPACK software is described in great detail in Lehoucq et al. (1998). An evaluation of software for computing eigenvalues of sparse nonsymmetric matrices is provided in Lehoucq and Scott (1996). This suite of routines offers the same functionality as the ARPACK software for real nonsymmetric problems, but the interface design is quite different in order to make the option setting clearer and to simplify some of the interfaces.
F12ACF, is a post-processing routine that must be called following a successful final exit from F12ABF. F12ACF uses data returned from F12ABF and options, set either by default or explicitly by calling F12ADF, to return the converged approximations to selected eigenvalues and (optionally):
– | the corresponding approximate eigenvectors;
– | an orthonormal basis for the associated approximate invariant subspace;
– | both.

4 References

Lehoucq R B (2001) Implicitly restarted Arnoldi methods and subspace iteration SIAM Journal on Matrix Analysis and Applications 23 551–562
Lehoucq R B and Scott J A (1996) An evaluation of software for computing eigenvalues of sparse nonsymmetric matrices Preprint MCS-P547-1195 Argonne National Laboratory
Lehoucq R B and Sorensen D C (1996) Deflation techniques for an implicitly restarted Arnoldi iteration SIAM Journal on Matrix Analysis and Applications 17 789–821
Lehoucq R B, Sorensen D C and Yang C (1998) ARPACK Users' Guide: Solution of Large-scale Eigenvalue Problems with Implicitly Restarted Arnoldi Methods SIAM, Philidelphia

5 Arguments

1:   NCONV – INTEGEROutput
On exit: the number of converged eigenvalues as found by F12ABF.
2:   DR* – REAL (KIND=nag_wp) arrayOutput
Note: the dimension of the array DR must be at least NEV (see F12AAF).
On exit: the first NCONV locations of the array DR contain the real parts of the converged approximate eigenvalues.
3:   DI* – REAL (KIND=nag_wp) arrayOutput
Note: the dimension of the array DI must be at least NEV (see F12AAF).
On exit: the first NCONV locations of the array DI contain the imaginary parts of the converged approximate eigenvalues.
4:   Z LDZ* – REAL (KIND=nag_wp) arrayOutput
Note: the second dimension of the array Z must be at least NEV+1 if the default option Vectors=RITZ has been selected and at least 1 if the option Vectors=NONE or SCHUR has been selected (see F12AAF).
On exit: if the default option Vectors=RITZ (see F12ADF) has been selected then Z contains the final set of eigenvectors corresponding to the eigenvalues held in DR and DI. The complex eigenvector associated with the eigenvalue with positive imaginary part is stored in two consecutive columns. The first column holds the real part of the eigenvector and the second column holds the imaginary part. The eigenvector associated with the eigenvalue with negative imaginary part is simply the complex conjugate of the eigenvector associated with the positive imaginary part.
5:   LDZ – INTEGERInput
On entry: the first dimension of the array Z as declared in the (sub)program from which F12ACF is called.
Constraints:
  • if the default option Vectors=Ritz has been selected, LDZ≥N;
  • if the option Vectors=None or Schur has been selected, LDZ≥1.
6:   SIGMAR – REAL (KIND=nag_wp)Input
On entry: if one of the Shifted Inverse Real modes have been selected then SIGMAR contains the real part of the shift used; otherwise SIGMAR is not referenced.
7:   SIGMAI – REAL (KIND=nag_wp)Input
On entry: if one of the Shifted Inverse Real modes have been selected then SIGMAI contains the imaginary part of the shift used; otherwise SIGMAI is not referenced.
8:   RESID* – REAL (KIND=nag_wp) arrayInput
Note: the dimension of the array RESID must be at least N (see F12AAF).
On entry: must not be modified following a call to F12ABF since it contains data required by F12ACF.
9:   V LDV* – REAL (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array V must be at least max 1,NCV (see F12AAF).
On entry: the NCV columns of V contain the Arnoldi basis vectors for OP as constructed by F12ABF.
On exit: if the option Vectors=SCHUR has been set, or the option Vectors=RITZ has been set and a separate array Z has been passed (i.e., Z does not equal V), then the first NCONV columns of V will contain approximate Schur vectors that span the desired invariant subspace.
10:   LDV – INTEGERInput
On entry: the first dimension of the array V as declared in the (sub)program from which F12ACF is called.
Constraint: LDV≥N.
11:   COMM* – REAL (KIND=nag_wp) arrayCommunication Array
Note: the dimension of the array COMM must be at least max 1,LCOMM (see F12AAF).
On initial entry: must remain unchanged from the prior call to F12ABF.
On exit: contains data on the current state of the solution.
12:   ICOMM* – INTEGER arrayCommunication Array
Note: the dimension of the array ICOMM must be at least max 1,LICOMM (see F12AAF).
On initial entry: must remain unchanged from the prior call to F12ABF.
On exit: contains data on the current state of the solution.
13:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, LDZ < max 1,N or LDZ < 1 when no vectors are required.
IFAIL=2
On entry, the option Vectors = Select was selected, but this is not yet implemented.
IFAIL=3
The number of eigenvalues found to sufficient accuracy prior to calling F12ACF, as communicated through the argument ICOMM, is zero.
IFAIL=4
The number of converged eigenvalues as calculated by F12ABF differ from the value passed to it through the argument ICOMM.
IFAIL=5
Unexpected error during calculation of a real Schur form: there was a failure to compute all the converged eigenvalues. Please contact NAG.
IFAIL=6
Unexpected error: the computed Schur form could not be reordered by an internal call. Please contact NAG.
IFAIL=7
Unexpected error in internal call while calculating eigenvectors. Please contact NAG.
IFAIL=8
Either the solver routine F12ABF has not been called prior to the call of this routine or a communication array has become corrupted.
IFAIL=9
The routine was unable to dynamically allocate sufficient internal workspace. Please contact NAG.
IFAIL=10
An unexpected error has occurred. Please contact NAG.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

The relative accuracy of a Ritz value, λ , is considered acceptable if its Ritz estimate ≤ Tolerance × λ . The default Tolerance used is the machine precision given by X02AJF.

8 Parallelism and Performance

F12ACF makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

None.

10 Example

This example solves Ax = λBx in regular-invert mode, where A and B are obtained from the standard central difference discretization of the one-dimensional convection-diffusion operator d 2 u d x 2 + ρ du dx on 0,1 , with zero Dirichlet boundary conditions.

10.1 Program Text

Program Text (f12acfe.f90)

10.2 Program Data

Program Data (f12acfe.d)

10.3 Program Results

Program Results (f12acfe.r)

F12 Chapter Contents
F12 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F12ADF : NAG Library, Mark 26

F12 Chapter Contents
F12 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F12ADF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.
Note: this routine uses optional parameters to define choices in the problem specification. If you wish to use default settings for all of the optional parameters, then this routine need not be called. If, however, you wish to reset some or all of the settings please refer to Section 11 for a detailed description of the specification of the optional parameters.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results
▸▿ 11 Optional Parameters
11.1 Description of the Optional Parameters

1 Purpose

F12ADF is an option setting routine that may be used to supply individual optional parameters to F12ABF and F12ACF. These are part of a suite of routines that also includes: F12AAF and F12AEF. The initialization routine F12AAF must have been called prior to calling F12ADF.

2 Specification

SUBROUTINE F12ADF ( STR, ICOMM, COMM, IFAIL)
INTEGER | ICOMM(*), IFAIL
REAL (KIND=nag_wp) | COMM(*)
CHARACTER(*) | STR

3 Description

F12ADF may be used to supply values for optional parameters to F12ABF and F12ACF. It is only necessary to call F12ADF for those arguments whose values are to be different from their default values. One call to F12ADF sets one argument value.
Each optional parameter is defined by a single character string consisting of one or more items. The items associated with a given option must be separated by spaces, or equals signs = . Alphabetic characters may be upper or lower case. The string
'Vectors = None'
is an example of a string used to set an optional parameter. For each option the string contains one or more of the following items:
– | a mandatory keyword;
– | a phrase that qualifies the keyword;
– | a number that specifies an integer or real value. Such numbers may be up to 16 contiguous characters in Fortran's I, F, E or D format.
F12ADF does not have an equivalent routine from the ARPACK package which passes options by directly setting values to scalar arguments or to specific elements of array arguments. F12ADF is intended to make the passing of options more transparent and follows the same principle as the single option setting routines in Chapter E04.
The setup routine F12AAF must be called prior to the first call to F12ADF and all calls to F12ADF must precede the first call to F12ABF, the reverse communication iterative solver.
A complete list of optional parameters, their abbreviations, synonyms and default values is given in Section 11.

4 References

Lehoucq R B (2001) Implicitly restarted Arnoldi methods and subspace iteration SIAM Journal on Matrix Analysis and Applications 23 551–562
Lehoucq R B and Scott J A (1996) An evaluation of software for computing eigenvalues of sparse nonsymmetric matrices Preprint MCS-P547-1195 Argonne National Laboratory
Lehoucq R B and Sorensen D C (1996) Deflation techniques for an implicitly restarted Arnoldi iteration SIAM Journal on Matrix Analysis and Applications 17 789–821
Lehoucq R B, Sorensen D C and Yang C (1998) ARPACK Users' Guide: Solution of Large-scale Eigenvalue Problems with Implicitly Restarted Arnoldi Methods SIAM, Philidelphia

5 Arguments

1:   STR – CHARACTER(*)Input
On entry: a single valid option string (as described in Section 3 and Section 11).
2:   ICOMM* – INTEGER arrayCommunication Array
Note: the dimension of the array ICOMM must be at least max 1,LICOMM (see F12AAF).
On initial entry: must remain unchanged following a call to the setup routine F12AAF.
On exit: contains data on the current options set.
3:   COMM* – REAL (KIND=nag_wp) arrayCommunication Array
Note: the dimension of the array COMM must be at least 60.
On initial entry: must remain unchanged following a call to the setup routine F12AAF.
On exit: contains data on the current options set.
4:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
The string passed in STR contains an ambiguous keyword.
IFAIL=2
The string passed in STR contains a keyword that could not be recognized.
IFAIL=3
The string passed in STR contains a second keyword that could not be recognized.
IFAIL=4
The initialization routine F12AAF has not been called or a communication array has become corrupted.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

Not applicable.

8 Parallelism and Performance

F12ADF is not threaded in any implementation.

9 Further Comments

None.

10 Example

This example solves Ax = λBx in shifted-inverse mode, where A and B are derived from the finite element discretization of the one-dimensional convection-diffusion operator d 2 u d x 2 + ρ du dx on the interval 0,1 , with zero Dirichlet boundary conditions.
The shift σ is a real number, and the operator used in the shifted-inverse iterative process is OP = A-σB -1 B .

10.1 Program Text

Program Text (f12adfe.f90)

10.2 Program Data

Program Data (f12adfe.d)

10.3 Program Results

Program Results (f12adfe.r)

11 Optional Parameters

Several optional parameters for the computational routines F12ABF and F12ACF define choices in the problem specification or the algorithm logic. In order to reduce the number of formal arguments of F12ABF and F12ACF these optional parameters have associated default values that are appropriate for most problems. Therefore, you need only specify those optional parameters whose values are to be different from their default values.
The remainder of this section can be skipped if you wish to use the default values for all optional parameters.
The following is a list of the optional parameters available. A full description of each optional parameter is provided in Section 11.1.
  • Advisory
  • Defaults
  • Exact Shifts
  • Generalized
  • Initial Residual
  • Iteration Limit
  • Largest Imaginary
  • Largest Magnitude
  • Largest Real
  • List
  • Monitoring
  • Nolist
  • Pointers
  • Print Level
  • Random Residual
  • Regular
  • Regular Inverse
  • Shifted Inverse Imaginary
  • Shifted Inverse Real
  • Smallest Imaginary
  • Smallest Magnitude
  • Smallest Real
  • Standard
  • Supplied Shifts
  • Tolerance
  • Vectors
Optional parameters may be specified by calling F12ADF before a call to F12ABF, but after a call to F12AAF. One call is necessary for each optional parameter.
All optional parameters you do not specify are set to their default values. Optional parameters you specify are unaltered by F12ABF and F12ACF (unless they define invalid values) and so remain in effect for subsequent calls unless you alter them.

11.1 Description of the Optional Parameters

For each option, we give a summary line, a description of the optional parameter and details of constraints.
The summary line contains:
  • the keywords, where the minimum abbreviation of each keyword is underlined;
  • a parameter value, where the letters a, i and r denote options that take character, integer and real values respectively;
  • the default value, where the symbol ε is a generic notation for machine precision (see X02AJF).
Keywords and character values are case and white space insensitive.
Advisory i Default = the value returned by X04ABF
The destination for advisory messages.
Defaults
This special keyword may be used to reset all optional parameters to their default values.
Exact Shifts Default
Supplied Shifts
During the Arnoldi iterative process, shifts are applied internally as part of the implicit restarting scheme. The shift strategy used by default and selected by the Exact Shifts is strongly recommended over the alternative Supplied Shifts (see Lehoucq et al. (1998) for details of shift strategies).
If Exact Shifts are used then these are computed internally by the algorithm in the implicit restarting scheme.
If Supplied Shifts are used then, during the Arnoldi iterative process, you must supply shifts through array arguments of F12ABF when F12ABF returns with IREVCM=3; the real and imaginary parts of the shifts are supplied in X and MX respectively (or in COMM when the option Pointers=YES is set). This option should only be used if you are an experienced user since this requires some algorithmic knowledge and because more operations are usually required than for the implicit shift scheme. Details on the use of explicit shifts and further references on shift strategies are available in Lehoucq et al. (1998).
Iteration Limit i Default = 300
The limit on the number of Arnoldi iterations that can be performed before F12ABF exits. If not all requested eigenvalues have converged to within Tolerance and the number of Arnoldi iterations has reached this limit then F12ABF exits with an error; F12ACF can still be called subsequently to return the number of converged eigenvalues, the converged eigenvalues and, if requested, the corresponding eigenvectors.
Largest Magnitude Default
Largest Imaginary
Largest Real
Smallest Imaginary
Smallest Magnitude
Smallest Real
The Arnoldi iterative method converges on a number of eigenvalues with given properties. The default is for F12ABF to compute the eigenvalues of largest magnitude using Largest Magnitude. Alternatively, eigenvalues may be chosen which have Largest Real part, Largest Imaginary part,Smallest Magnitude, Smallest Real part or Smallest Imaginary part.
Note that these options select the eigenvalue properties for eigenvalues of OP (and B for Generalized problems), the linear operator determined by the computational mode and problem type.
Nolist Default
List
Normally each optional parameter specification is not printed to the advisory channel as it is supplied. Optional parameter List may be used to enable printing and optional parameter Nolist may be used to suppress the printing.
Monitoring i Default = -1
If i>0, monitoring information is output to channel number i during the solution of each problem; this may be the same as the Advisory channel number. The type of information produced is dependent on the value of Print Level, see the description of the optional parameter Print Level for details of the information produced. Please see X04ACF to associate a file with a given channel number.
Pointers Default = NO
During the iterative process and reverse communication calls to F12ABF, required data can be communicated to and from F12ABF in one of two ways. When Pointers=NO is selected (the default) then the array arguments X and MX are used to supply you with required data and used to return computed values back to F12ABF. For example, when IREVCM=1, F12ABF returns the vector x in X and the matrix-vector product Bx in MX and expects the result or the linear operation OP x to be returned in X.
If Pointers=YES is selected then the data is passed through sections of the array argument COMM. The section corresponding to X when Pointers=NO begins at a location given by the first element of ICOMM; similarly the section corresponding to MX begins at a location given by the second element of ICOMM. This option allows F12ABF to perform fewer copy operations on each intermediate exit and entry, but can also lead to less elegant code in the calling program.
Print Level i Default = 0
This controls the amount of printing produced by F12ADF as follows.
=0 | No output except error messages.
>0 | The set of selected options.
=2 | Problem and timing statistics on final exit from F12ABF.
≥5 | A single line of summary output at each Arnoldi iteration.
≥10 | If Monitoring>0, Monitoring is set, then at each iteration, the length and additional steps of the current Arnoldi factorization and the number of converged Ritz values; during re-orthogonalization, the norm of initial/restarted starting vector.
≥20 | Problem and timing statistics on final exit from F12ABF. If Monitoring>0, Monitoring is set, then at each iteration, the number of shifts being applied, the eigenvalues and estimates of the Hessenberg matrix H, the size of the Arnoldi basis, the wanted Ritz values and associated Ritz estimates and the shifts applied; vector norms prior to and following re-orthogonalization.
≥30 | If Monitoring>0, Monitoring is set, then on final iteration, the norm of the residual; when computing the Schur form, the eigenvalues and Ritz estimates both before and after sorting; for each iteration, the norm of residual for compressed factorization and the compressed upper Hessenberg matrix H; during re-orthogonalization, the initial/restarted starting vector; during the Arnoldi iteration loop, a restart is flagged and the number of the residual requiring iterative refinement; while applying shifts, the indices of the shifts being applied.
≥40 | If Monitoring>0, Monitoring is set, then during the Arnoldi iteration loop, the Arnoldi vector number and norm of the current residual; while applying shifts, key measures of progress and the order of H; while computing eigenvalues of H, the last rows of the Schur and eigenvector matrices; when computing implicit shifts, the eigenvalues and Ritz estimates of H.
≥50 | If Monitoring is set, then during Arnoldi iteration loop: norms of key components and the active column of H, norms of residuals during iterative refinement, the final upper Hessenberg matrix H; while applying shifts: number of shifts, shift values, block indices, updated matrix H; while computing eigenvalues of H: the matrix H, the computed eigenvalues and Ritz estimates.
Random Residual Default
Initial Residual
To begin the Arnoldi iterative process, F12ABF requires an initial residual vector. By default F12ABF provides its own random initial residual vector; this option can also be set using optional parameter Random Residual. Alternatively, you can supply an initial residual vector (perhaps from a previous computation) to F12ABF through the array argument RESID; this option can be set using optional parameter Initial Residual.
Regular Default
Regular Inverse
Shifted Inverse Imaginary
Shifted Inverse Real
These options define the computational mode which in turn defines the form of operation OP x to be performed when F12ABF returns with IREVCM=-1 or 1 and the matrix-vector product Bx when F12ABF returns with IREVCM=2.
Given a Standard eigenvalue problem in the form Ax=λx then the following modes are available with the appropriate operator OP x.
Regular | OP=A
Shifted Inverse Real | OP=A-σI-1 where σ is real
Given a Generalized eigenvalue problem in the form Ax=λBx then the following modes are available with the appropriate operator OP x.
Regular Inverse | OP=B-1 A
Shifted Inverse Real with real shift | OP=A-σB-1 B, where σ is real
Shifted Inverse Real with complex shift | OP=Real A-σB-1 B, where σ is complex
Shifted Inverse Imaginary | OP=Imag A-σB-1 B, where σ is complex
Standard Default
Generalized
The problem to be solved is either a standard eigenvalue problem, Ax=λx, or a generalized eigenvalue problem, Ax=λBx. The optional parameter Standard should be used when a standard eigenvalue problem is being solved and the optional parameter Generalized should be used when a generalized eigenvalue problem is being solved.
Tolerance r Default = ε
An approximate eigenvalue has deemed to have converged when the corresponding Ritz estimate is within Tolerance relative to the magnitude of the eigenvalue.
Vectors Default = RITZ
The routine F12ACF can optionally compute the Schur vectors and/or the eigenvectors corresponding to the converged eigenvalues. To turn off computation of any vectors the option Vectors=NONE should be set. To compute only the Schur vectors (at very little extra cost), the option Vectors=SCHUR should be set and these will be returned in the array argument V of F12ACF. To compute the eigenvectors (Ritz vectors) corresponding to the eigenvalue estimates, the option Vectors=RITZ should be set and these will be returned in the array argument Z of F12ACF, if Z is set equal to V (as in Section 10) then the Schur vectors in V are overwritten by the eigenvectors computed by F12ACF.
F12 Chapter Contents
F12 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F12AEF : NAG Library, Mark 26

F12 Chapter Contents
F12 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F12AEF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.
Note: this routine uses optional parameters to define choices in the problem specification. If you wish to use default settings for all of the optional parameters, then the option setting routine F12ADF need not be called. If, however, you wish to reset some or all of the settings please refer to Section 11 in F12ADF for a detailed description of the specification of the optional parameters.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F12AEF can be used to return additional monitoring information during computation. It is in a suite of routines consisting of F12AAF, F12ABF, F12ACF, F12ADF and F12AEF.

2 Specification

SUBROUTINE F12AEF ( NITER, NCONV, RITZR, RITZI, RZEST, ICOMM, COMM)
INTEGER | NITER, NCONV, ICOMM(*)
REAL (KIND=nag_wp) | RITZR(*), RITZI(*), RZEST(*), COMM(*)

3 Description

The suite of routines is designed to calculate some of the eigenvalues, λ , (and optionally the corresponding eigenvectors, x ) of a standard eigenvalue problem Ax = λx , or of a generalized eigenvalue problem Ax = λBx of order n , where n is large and the coefficient matrices A and B are sparse, real and nonsymmetric. The suite can also be used to find selected eigenvalues/eigenvectors of smaller scale dense, real and nonsymmetric problems.
On an intermediate exit from F12ABF with IREVCM = 4 , F12AEF may be called to return monitoring information on the progress of the Arnoldi iterative process. The information returned by F12AEF is:
– | the number of the current Arnoldi iteration;
– | the number of converged eigenvalues at this point;
– | the real and imaginary parts of the converged eigenvalues;
– | the error bounds on the converged eigenvalues.
F12AEF does not have an equivalent routine from the ARPACK package which prints various levels of detail of monitoring information through an output channel controlled via an argument value (see Lehoucq et al. (1998) for details of ARPACK routines). F12AEF should not be called at any time other than immediately following an IREVCM = 4 return from F12ABF.

4 References

Lehoucq R B (2001) Implicitly restarted Arnoldi methods and subspace iteration SIAM Journal on Matrix Analysis and Applications 23 551–562
Lehoucq R B and Scott J A (1996) An evaluation of software for computing eigenvalues of sparse nonsymmetric matrices Preprint MCS-P547-1195 Argonne National Laboratory
Lehoucq R B and Sorensen D C (1996) Deflation techniques for an implicitly restarted Arnoldi iteration SIAM Journal on Matrix Analysis and Applications 17 789–821
Lehoucq R B, Sorensen D C and Yang C (1998) ARPACK Users' Guide: Solution of Large-scale Eigenvalue Problems with Implicitly Restarted Arnoldi Methods SIAM, Philidelphia

5 Arguments

1:   NITER – INTEGEROutput
On exit: the number of the current Arnoldi iteration.
2:   NCONV – INTEGEROutput
On exit: the number of converged eigenvalues so far.
3:   RITZR* – REAL (KIND=nag_wp) arrayOutput
Note: the dimension of the array RITZR must be at least NCV (see F12AAF).
On exit: the first NCONV locations of the array RITZR contain the real parts of the converged approximate eigenvalues.
4:   RITZI* – REAL (KIND=nag_wp) arrayOutput
Note: the dimension of the array RITZI must be at least NCV (see F12AAF).
On exit: the first NCONV locations of the array RITZI contain the imaginary parts of the converged approximate eigenvalues.
5:   RZEST* – REAL (KIND=nag_wp) arrayOutput
Note: the dimension of the array RZEST must be at least NCV (see F12AAF).
On exit: the first NCONV locations of the array RZEST contain the Ritz estimates (error bounds) on the converged approximate eigenvalues.
6:   ICOMM* – INTEGER arrayCommunication Array
Note: the dimension of the array ICOMM must be at least max 1,LICOMM, where LICOMM is passed to the setup routine (see F12AAF).
On entry: the array ICOMM output by the preceding call to F12ABF.
7:   COMM* – REAL (KIND=nag_wp) arrayCommunication Array
Note: the dimension of the array COMM must be at least max 1,LCOMM, where LCOMM is passed to the setup routine (see F12AAF).
On entry: the array COMM output by the preceding call to F12ABF.

6 Error Indicators and Warnings

None.

7 Accuracy

A Ritz value, λ , is deemed to have converged if its Ritz estimate ≤ Tolerance × λ . The default Tolerance used is the machine precision given by X02AJF.

8 Parallelism and Performance

F12AEF is not threaded in any implementation.

9 Further Comments

None.

10 Example

This example solves Ax = λBx in shifted-real mode, where A is the tridiagonal matrix with 2 on the diagonal, - 2 on the subdiagonal and 3 on the superdiagonal. The matrix B is the tridiagonal matrix with 4 on the diagonal and 1 on the off-diagonals. The shift sigma, σ , is a complex number, and the operator used in the shifted-real iterative process is OP = real A-σB -1 B .

10.1 Program Text

Program Text (f12aefe.f90)

10.2 Program Data

Program Data (f12aefe.d)

10.3 Program Results

Program Results (f12aefe.r)

F12 Chapter Contents
F12 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F12AFF : NAG Library, Mark 26

F12 Chapter Contents
F12 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F12AFF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
10 Example

1 Purpose

F12AFF is a setup routine for F12AGF which may be used for finding some eigenvalues (and optionally the corresponding eigenvectors) of a standard or generalized eigenvalue problem defined by real, banded, nonsymmetric matrices. The banded matrix must be stored using the LAPACK column ordered storage format for real banded nonsymmetric matrices (see Section 3.3.4 in the F07 Chapter Introduction).

2 Specification

SUBROUTINE F12AFF ( N, NEV, NCV, ICOMM, LICOMM, COMM, LCOMM, IFAIL)
INTEGER | N, NEV, NCV, ICOMM(max(1,LICOMM)), LICOMM, LCOMM, IFAIL
REAL (KIND=nag_wp) | COMM(max(1,LCOMM))

3 Description

The pair of routines F12AFF and F12AGF together with the option setting routine F12ADF are designed to calculate some of the eigenvalues, λ , (and optionally the corresponding eigenvectors, x ) of a standard eigenvalue problem Ax = λx , or of a generalized eigenvalue problem Ax = λBx of order n , where n is large and the coefficient matrices A and B are banded real and nonsymmetric.
F12AFF is a setup routine which must be called before the option setting routine F12ADF and the solver routine F12AGF. Internally, F12AGF makes calls to F12ABF and F12ACF; the routine documents for F12ABF and F12ACF should be consulted for details of the algorithm used.
This setup routine initializes the communication arrays, sets (to their default values) all options that can be set by you via the option setting routine F12ADF, and checks that the lengths of the communication arrays as passed by you are of sufficient length. For details of the options available and how to set them, see Section 11.1 in F12ADF.

4 References

Lehoucq R B (2001) Implicitly restarted Arnoldi methods and subspace iteration SIAM Journal on Matrix Analysis and Applications 23 551–562
Lehoucq R B and Scott J A (1996) An evaluation of software for computing eigenvalues of sparse nonsymmetric matrices Preprint MCS-P547-1195 Argonne National Laboratory
Lehoucq R B and Sorensen D C (1996) Deflation techniques for an implicitly restarted Arnoldi iteration SIAM Journal on Matrix Analysis and Applications 17 789–821
Lehoucq R B, Sorensen D C and Yang C (1998) ARPACK Users' Guide: Solution of Large-scale Eigenvalue Problems with Implicitly Restarted Arnoldi Methods SIAM, Philidelphia

5 Arguments

1:   N – INTEGERInput
On entry: the order of the matrix A (and the order of the matrix B for the generalized problem) that defines the eigenvalue problem.
Constraint: N>0.
2:   NEV – INTEGERInput
On entry: the number of eigenvalues to be computed.
Constraint: 0<NEV<N-1.
3:   NCV – INTEGERInput
On entry: the number of Lanczos basis vectors to use during the computation.
At present there is no a priori analysis to guide the selection of NCV relative to NEV. However, it is recommended that NCV≥2×NEV+1. If many problems of the same type are to be solved, you should experiment with increasing NCV while keeping NEV fixed for a given test problem. This will usually decrease the required number of matrix-vector operations but it also increases the work and storage required to maintain the orthogonal basis vectors. The optimal ‘cross-over’ with respect to CPU time is problem dependent and must be determined empirically.
Constraint: NEV+1<NCV≤N.
4:   ICOMM max 1,LICOMM – INTEGER arrayCommunication Array
On exit: contains data to be communicated to F12AGF.
5:   LICOMM – INTEGERInput
On entry: the dimension of the array ICOMM as declared in the (sub)program from which F12AFF is called.
If LICOMM=-1, a workspace query is assumed and the routine only calculates the required dimensions of ICOMM and COMM, which it returns in ICOMM 1 and COMM 1 respectively.
Constraint: LICOMM≥140 ​ or ​ LICOMM=-1.
6:   COMM max 1,LCOMM – REAL (KIND=nag_wp) arrayCommunication Array
On exit: contains data to be communicated to F12AGF.
7:   LCOMM – INTEGERInput
On entry: the dimension of the array COMM as declared in the (sub)program from which F12AFF is called.
If LCOMM=-1, a workspace query is assumed and the routine only calculates the dimensions of ICOMM and COMM required by F12AGF, which it returns in ICOMM 1 and COMM 1 respectively.
Constraint: LCOMM≥60 ​ or ​ LCOMM=-1.
8:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, N≤0.
IFAIL=2
On entry, NEV≤0.
IFAIL=3
On entry, NCV<NEV+2 or NCV>N.
IFAIL=4
On entry, LICOMM<140 and LICOMM≠-1.
IFAIL=5
On entry, LCOMM<60 and LCOMM≠-1.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

Not applicable.

8 Parallelism and Performance

F12AFF is not threaded in any implementation.

9 Further Comments

None.

10 Example

The use of F12AFF is illustrated in Section 10 in F12AGF.
F12 Chapter Contents
F12 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F12AGF : NAG Library, Mark 26

F12 Chapter Contents
F12 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F12AGF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.
Note: this routine uses optional parameters to define choices in the problem specification. If you wish to use default settings for all of the optional parameters, then the option setting routine F12ADF need not be called. If, however, you wish to reset some or all of the settings please refer to Section 11 in F12ADF for a detailed description of the specification of the optional parameters.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F12AGF is the main solver routine in a suite of routines consisting of F12ADF, F12AFF and F12AGF. It must be called following an initial call to F12AFF and following any calls to F12ADF.
F12AGF returns approximations to selected eigenvalues, and (optionally) the corresponding eigenvectors, of a standard or generalized eigenvalue problem defined by real banded nonsymmetric matrices. The banded matrix must be stored using the LAPACK storage format for real banded nonsymmetric matrices.

2 Specification

SUBROUTINE F12AGF ( KL, KU, AB, LDAB, MB, LDMB, SIGMAR, SIGMAI, NCONV, DR, DI, Z, LDZ, RESID, V, LDV, COMM, ICOMM, IFAIL)
INTEGER | KL, KU, LDAB, LDMB, NCONV, LDZ, LDV, ICOMM(*), IFAIL
REAL (KIND=nag_wp) | AB(LDAB,*), MB(LDMB,*), SIGMAR, SIGMAI, DR(*), DI(*), Z(LDZ,*), RESID(*), V(LDV,*), COMM(*)

3 Description

The suite of routines is designed to calculate some of the eigenvalues, λ , (and optionally the corresponding eigenvectors, x ) of a standard eigenvalue problem Ax = λx , or of a generalized eigenvalue problem Ax = λBx of order n , where n is large and the coefficient matrices A and B are banded, real and nonsymmetric.
Following a call to the initialization routine F12AFF, F12AGF returns the converged approximations to eigenvalues and (optionally) the corresponding approximate eigenvectors and/or an orthonormal basis for the associated approximate invariant subspace. The eigenvalues (and eigenvectors) are selected from those of a standard or generalized eigenvalue problem defined by real banded nonsymmetric matrices. There is negligible additional computational cost to obtain eigenvectors; an orthonormal basis is always computed, but there is an additional storage cost if both are requested.
The banded matrices A and B must be stored using the LAPACK column ordered storage format for banded nonsymmetric matrices; please refer to Section 3.3.2 in the F07 Chapter Introduction for details on this storage format.
F12AGF is based on the banded driver routines dnbdr1 to dnbdr6 from the ARPACK package, which uses the Implicitly Restarted Arnoldi iteration method. The method is described in Lehoucq and Sorensen (1996) and Lehoucq (2001) while its use within the ARPACK software is described in great detail in Lehoucq et al. (1998). An evaluation of software for computing eigenvalues of sparse nonsymmetric matrices is provided in Lehoucq and Scott (1996). This suite of routines offers the same functionality as the ARPACK banded driver software for real nonsymmetric problems, but the interface design is quite different in order to make the option setting clearer and to combine the different drivers into a general purpose routine.
F12AGF, is a general purpose routine that must be called following initialization by F12AFF. F12AGF uses options, set either by default or explicitly by calling F12ADF, to return the converged approximations to selected eigenvalues and (optionally):
– | the corresponding approximate eigenvectors;
– | an orthonormal basis for the associated approximate invariant subspace;
– | both.
Please note that for Generalized problems, the Shifted Inverse Imaginary and Shifted Inverse Real inverse modes are only appropriate if either A or B is symmetric semidefinite. Otherwise, if A or B is non-singular, the Standard problem can be solved using the matrix B-1 A (say).

4 References

Lehoucq R B (2001) Implicitly restarted Arnoldi methods and subspace iteration SIAM Journal on Matrix Analysis and Applications 23 551–562
Lehoucq R B and Scott J A (1996) An evaluation of software for computing eigenvalues of sparse nonsymmetric matrices Preprint MCS-P547-1195 Argonne National Laboratory
Lehoucq R B and Sorensen D C (1996) Deflation techniques for an implicitly restarted Arnoldi iteration SIAM Journal on Matrix Analysis and Applications 17 789–821
Lehoucq R B, Sorensen D C and Yang C (1998) ARPACK Users' Guide: Solution of Large-scale Eigenvalue Problems with Implicitly Restarted Arnoldi Methods SIAM, Philidelphia

5 Arguments

1:   KL – INTEGERInput
On entry: the number of subdiagonals of the matrices A and B.
Constraint: KL≥0.
2:   KU – INTEGERInput
On entry: the number of superdiagonals of the matrices A and B.
Constraint: KU≥0.
3:   AB LDAB* – REAL (KIND=nag_wp) arrayInput
Note: the second dimension of the array AB must be at least max 1,N (see F12AFF).
On entry: must contain the matrix A in LAPACK banded storage format for nonsymmetric matrices (see Section 3.3.4 in the F07 Chapter Introduction).
4:   LDAB – INTEGERInput
On entry: the first dimension of the array AB as declared in the (sub)program from which F12AGF is called.
Constraint: LDAB ≥ 2×KL+KU+1.
5:   MB LDMB* – REAL (KIND=nag_wp) arrayInput
Note: the second dimension of the array MB must be at least max 1,N (see F12AFF).
On entry: must contain the matrix B in LAPACK banded storage format for nonsymmetric matrices (see Section 3.3.4 in the F07 Chapter Introduction).
6:   LDMB – INTEGERInput
On entry: the first dimension of the array MB as declared in the (sub)program from which F12AGF is called.
Constraint: LDMB≥2×KL+KU+1.
7:   SIGMAR – REAL (KIND=nag_wp)Input
On entry: if one of the Shifted Inverse Real modes (see F12ADF) have been selected then SIGMAR must contain the real part of the shift used; otherwise SIGMAR is not referenced. Section 4.3.4 in the F12 Chapter Introduction describes the use of shift and inverse transformations.
8:   SIGMAI – REAL (KIND=nag_wp)Input
On entry: if one of the Shifted Inverse Real modes (see F12ADF) have been selected then SIGMAI must contain the imaginary part of the shift used; otherwise SIGMAI is not referenced. Section 4.3.4 in the F12 Chapter Introduction describes the use of shift and inverse transformations.
9:   NCONV – INTEGEROutput
On exit: the number of converged eigenvalues.
10:   DR* – REAL (KIND=nag_wp) arrayOutput
Note: the dimension of the array DR must be at least NEV+1 (see F12AFF).
On exit: the first NCONV locations of the array DR contain the real parts of the converged approximate eigenvalues. The number of eigenvalues returned may be one more than the number requested by NEV since complex values occur as conjugate pairs and the second in the pair can be returned in position NEV+1 of the array.
11:   DI* – REAL (KIND=nag_wp) arrayOutput
Note: the dimension of the array DI must be at least NEV+1 (see F12AFF).
On exit: the first NCONV locations of the array DI contain the imaginary parts of the converged approximate eigenvalues. The number of eigenvalues returned may be one more than the number requested by NEV since complex values occur as conjugate pairs and the second in the pair can be returned in position NEV+1 of the array.
12:   Z LDZ* – REAL (KIND=nag_wp) arrayOutput
Note: the second dimension of the array Z must be at least NEV+1 if the default option Vectors=Ritz has been selected and at least 1 if the option Vectors=None or Schur has been selected (see F12AAF).
On exit: if the default option Vectors=Ritz has been selected then Z contains the final set of eigenvectors corresponding to the eigenvalues held in DR and DI. The complex eigenvector associated with the eigenvalue with positive imaginary part is stored in two consecutive columns. The first column holds the real part of the eigenvector and the second column holds the imaginary part. The eigenvector associated with the eigenvalue with negative imaginary part is simply the complex conjugate of the eigenvector associated with the positive imaginary part.
13:   LDZ – INTEGERInput
On entry: the first dimension of the array Z as declared in the (sub)program from which F12AGF is called.
Constraints:
  • if the default option Vectors=Ritz has been selected, LDZ≥N;
  • if the option Vectors=None or Schur has been selected, LDZ≥1.
14:   RESID* – REAL (KIND=nag_wp) arrayInput/Output
Note: the dimension of the array RESID must be at least N (see F12AFF).
On entry: need not be set unless the option Initial Residual has been set in a prior call to F12ADF in which case RESID must contain an initial residual vector.
On exit: contains the final residual vector.
15:   V LDV* – REAL (KIND=nag_wp) arrayOutput
Note: the second dimension of the array V must be at least max 1,NCV (see F12AFF).
On exit: if the option Vectors (see F12ADF) has been set to Schur or Ritz then the first NCONV×n elements of V will contain approximate Schur vectors that span the desired invariant subspace.
The ith Schur vector is stored in the ith column of V.
16:   LDV – INTEGERInput
On entry: the first dimension of the array V as declared in the (sub)program from which F12AGF is called.
Constraint: LDV≥N.
17:   COMM* – REAL (KIND=nag_wp) arrayCommunication Array
On entry: must remain unchanged from the prior call to F12ADF and F12AFF.
On exit: contains no useful information.
18:   ICOMM* – INTEGER arrayCommunication Array
On entry: must remain unchanged from the prior call to F12ADF and F12AFF.
On exit: contains no useful information.
19:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, KL < 0 .
IFAIL=2
On entry, KU < 0 .
IFAIL=3
On entry, LDAB < 2×KL+KU+1 .
IFAIL=4
On entry, the option Shifted Inverse Imaginary was selected, and SIGMAI=zero, but SIGMAI must be nonzero for this computational mode.
IFAIL=5
Iteration Limit < 0 .
IFAIL=6
The options Generalized and Regular are incompatible.
IFAIL=7
The Initial Residual was selected but the starting vector held in RESID is zero.
IFAIL=8
Either the initialization routine F12AFF has not been called prior to the first call of this routine or a communication array has become corrupted.
IFAIL=9
On entry, LDZ<N or LDZ < 1 when no vectors are required.
IFAIL=10
On entry, the option Vectors = Select was selected, but this is not yet implemented.
IFAIL=11
The number of eigenvalues found to sufficient accuracy is zero.
IFAIL=12
Could not build an Arnoldi factorization. Consider changing NCV or NEV in the initialization routine (see Section 5 in F12AFF for details of these arguments).
IFAIL=13
Unexpected error in internal call to compute eigenvalues and corresponding error bounds of the current upper Hessenberg matrix. Please contact NAG.
IFAIL=14
Unexpected error during calculation of a real Schur form: there was a failure to compute all the converged eigenvalues. Please contact NAG.
IFAIL=15
Unexpected error: the computed Schur form could not be reordered by an internal call. Please contact NAG.
IFAIL=16
Unexpected error in internal call while calculating eigenvectors. Please contact NAG.
IFAIL=17
Failure during internal factorization of real banded matrix. Please contact NAG.
IFAIL=18
Failure during internal solution of real banded system. Please contact NAG.
IFAIL=19
Failure during internal factorization of complex banded matrix. Please contact NAG.
IFAIL=20
Failure during internal solution of complex banded system. Please contact NAG.
IFAIL=21
The maximum number of iterations has been reached. Some Ritz values may have converged; NCONV returns the number of converged values.
IFAIL=22
No shifts could be applied during a cycle of the implicitly restarted Arnoldi iteration. One possibility is to increase the size of NCV relative to NEV (see Section 5 in F12AFF for details of these arguments).
IFAIL=23
Overflow occurred during transformation of Ritz values to those of the original problem.
IFAIL=24
The routine was unable to dynamically allocate sufficient internal workspace. Please contact NAG.
IFAIL=25
An unexpected error has occurred. Please contact NAG.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

The relative accuracy of a Ritz value, λ , is considered acceptable if its Ritz estimate ≤ Tolerance × λ . The default Tolerance used is the machine precision given by X02AJF.

8 Parallelism and Performance

F12AGF is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
F12AGF makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

None.

10 Example

This example constructs the matrices A and B using LAPACK band storage format and solves Ax=λBx in shifted imaginary mode using the complex shift σ .

10.1 Program Text

Program Text (f12agfe.f90)

10.2 Program Data

Program Data (f12agfe.d)

10.3 Program Results

Program Results (f12agfe.r)

F12 Chapter Contents
F12 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F12ANF : NAG Library, Mark 26

F12 Chapter Contents
F12 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F12ANF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F12ANF is a setup routine in a suite of routines consisting of F12ANF, F12APF, F12AQF, F12ARF and F12ASF. It is used to find some of the eigenvalues (and optionally the corresponding eigenvectors) of a standard or generalized eigenvalue problem defined by complex nonsymmetric matrices.
The suite of routines is suitable for the solution of large sparse, standard or generalized, nonsymmetric complex eigenproblems where only a few eigenvalues from a selected range of the spectrum are required.

2 Specification

SUBROUTINE F12ANF ( N, NEV, NCV, ICOMM, LICOMM, COMM, LCOMM, IFAIL)
INTEGER | N, NEV, NCV, ICOMM(max(1,LICOMM)), LICOMM, LCOMM, IFAIL
COMPLEX (KIND=nag_wp) | COMM(max(1,LCOMM))

3 Description

The suite of routines is designed to calculate some of the eigenvalues, λ , (and optionally the corresponding eigenvectors, x ) of a standard complex eigenvalue problem Ax = λx , or of a generalized complex eigenvalue problem Ax = λBx of order n , where n is large and the coefficient matrices A and B are sparse, complex and nonsymmetric. The suite can also be used to find selected eigenvalues/eigenvectors of smaller scale dense, complex and nonsymmetric problems.
F12ANF is a setup routine which must be called before F12APF, the reverse communication iterative solver, and before F12ARF, the options setting routine. F12AQF is a post-processing routine that must be called following a successful final exit from F12APF, while F12ASF can be used to return additional monitoring information during the computation.
This setup routine initializes the communication arrays, sets (to their default values) all options that can be set by you via the option setting routine F12ARF, and checks that the lengths of the communication arrays as passed by you are of sufficient length. For details of the options available and how to set them see Section 11.1 in F12ARF.

4 References

Lehoucq R B (2001) Implicitly restarted Arnoldi methods and subspace iteration SIAM Journal on Matrix Analysis and Applications 23 551–562
Lehoucq R B and Scott J A (1996) An evaluation of software for computing eigenvalues of sparse nonsymmetric matrices Preprint MCS-P547-1195 Argonne National Laboratory
Lehoucq R B and Sorensen D C (1996) Deflation techniques for an implicitly restarted Arnoldi iteration SIAM Journal on Matrix Analysis and Applications 17 789–821
Lehoucq R B, Sorensen D C and Yang C (1998) ARPACK Users' Guide: Solution of Large-scale Eigenvalue Problems with Implicitly Restarted Arnoldi Methods SIAM, Philidelphia

5 Arguments

1:   N – INTEGERInput
On entry: the order of the matrix A (and the order of the matrix B for the generalized problem) that defines the eigenvalue problem.
Constraint: N>0.
2:   NEV – INTEGERInput
On entry: the number of eigenvalues to be computed.
Constraint: 0<NEV<N-1.
3:   NCV – INTEGERInput
On entry: the number of Arnoldi basis vectors to use during the computation.
At present there is no a priori analysis to guide the selection of NCV relative to NEV. However, it is recommended that NCV≥2×NEV+1. If many problems of the same type are to be solved, you should experiment with increasing NCV while keeping NEV fixed for a given test problem. This will usually decrease the required number of matrix-vector operations but it also increases the work and storage required to maintain the orthogonal basis vectors. The optimal ‘cross-over’ with respect to CPU time is problem dependent and must be determined empirically.
Constraint: NEV+1<NCV≤N.
4:   ICOMM max 1,LICOMM – INTEGER arrayCommunication Array
On exit: contains data to be communicated to the other routines in the suite.
5:   LICOMM – INTEGERInput
On entry: the dimension of the array ICOMM as declared in the (sub)program from which F12ANF is called.
If LICOMM=-1, a workspace query is assumed and the routine only calculates the required dimensions of ICOMM and COMM, which it returns in ICOMM 1 and COMM 1 respectively.
Constraint: LICOMM≥140 ​ or ​ LICOMM=-1.
6:   COMM max 1,LCOMM – COMPLEX (KIND=nag_wp) arrayCommunication Array
On exit: contains data to be communicated to the other routines in the suite.
7:   LCOMM – INTEGERInput
On entry: the dimension of the array COMM as declared in the (sub)program from which F12ANF is called.
If LCOMM=-1, a workspace query is assumed and the routine only calculates the dimensions of ICOMM and COMM required by F12APF, which it returns in ICOMM 1 and COMM 1 respectively.
Constraint: LCOMM≥3×N+3×NCV×NCV+5×NCV+60 ​ or ​ LCOMM=-1.
8:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, N≤0.
IFAIL=2
On entry, NEV≤0.
IFAIL=3
On entry, NCV<NEV+2 or NCV>N.
IFAIL=4
On entry, LICOMM<140 and LICOMM≠-1.
IFAIL=5
On entry, LCOMM<3×N+3×NCV×NCV+5×NCV+60 and LCOMM≠-1.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

Not applicable.

8 Parallelism and Performance

F12ANF is not threaded in any implementation.

9 Further Comments

None.

10 Example

This example solves Ax = λx in regular mode, where A is obtained from the standard central difference discretization of the convection-diffusion operator ∂2 u ∂x 2 + ∂2 u ∂y 2 + ρ ∂u ∂x on the unit square, with zero Dirichlet boundary conditions. The eigenvalues of largest magnitude are found.

10.1 Program Text

Program Text (f12anfe.f90)

10.2 Program Data

Program Data (f12anfe.d)

10.3 Program Results

Program Results (f12anfe.r)

F12 Chapter Contents
F12 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F12APF : NAG Library, Mark 26

F12 Chapter Contents
F12 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F12APF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.
Note: this routine uses optional parameters to define choices in the problem specification. If you wish to use default settings for all of the optional parameters, then the option setting routine F12ARF need not be called. If, however, you wish to reset some or all of the settings please refer to Section 11 in F12ARF for a detailed description of the specification of the optional parameters.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F12APF is an iterative solver in a suite of routines consisting of F12ANF, F12APF, F12AQF, F12ARF and F12ASF. It is used to find some of the eigenvalues (and optionally the corresponding eigenvectors) of a standard or generalized eigenvalue problem defined by complex nonsymmetric matrices.

2 Specification

SUBROUTINE F12APF ( IREVCM, RESID, V, LDV, X, MX, NSHIFT, COMM, ICOMM, IFAIL)
INTEGER | IREVCM, LDV, NSHIFT, ICOMM(*), IFAIL
COMPLEX (KIND=nag_wp) | RESID(*), V(LDV,*), X(*), MX(*), COMM(*)

3 Description

The suite of routines is designed to calculate some of the eigenvalues, λ , (and optionally the corresponding eigenvectors, x ) of a standard eigenvalue problem Ax = λx , or of a generalized eigenvalue problem Ax = λBx of order n , where n is large and the coefficient matrices A and B are sparse, complex and nonsymmetric. The suite can also be used to find selected eigenvalues/eigenvectors of smaller scale dense, complex and nonsymmetric problems.
F12APF is a reverse communication routine, based on the ARPACK routine znaupd, using the Implicitly Restarted Arnoldi iteration method. The method is described in Lehoucq and Sorensen (1996) and Lehoucq (2001) while its use within the ARPACK software is described in great detail in Lehoucq et al. (1998). An evaluation of software for computing eigenvalues of sparse nonsymmetric matrices is provided in Lehoucq and Scott (1996). This suite of routines offers the same functionality as the ARPACK software for complex nonsymmetric problems, but the interface design is quite different in order to make the option setting clearer and to simplify the interface of F12APF.
The setup routine F12ANF must be called before F12APF, the reverse communication iterative solver. Options may be set for F12APF by prior calls to the option setting routine F12ARF and a post-processing routine F12AQF must be called following a successful final exit from F12APF. F12ASF may be called following certain flagged intermediate exits from F12APF to provide additional monitoring information about the computation.
F12APF uses reverse communication, i.e., it returns repeatedly to the calling program with the argument IREVCM (see Section 5) set to specified values which require the calling program to carry out one of the following tasks:
– | compute the matrix-vector product y = OPx , where OP is defined by the computational mode;
– | compute the matrix-vector product y = Bx ;
– | notify the completion of the computation;
– | allow the calling program to monitor the solution.
The problem type to be solved (standard or generalized), the spectrum of eigenvalues of interest, the mode used (regular, regular inverse, shifted inverse, shifted real or shifted imaginary) and other options can all be set using the option setting routine F12ARF (see Section 11.1 in F12ARF for details on setting options and of the default settings).

4 References

Lehoucq R B (2001) Implicitly restarted Arnoldi methods and subspace iteration SIAM Journal on Matrix Analysis and Applications 23 551–562
Lehoucq R B and Scott J A (1996) An evaluation of software for computing eigenvalues of sparse nonsymmetric matrices Preprint MCS-P547-1195 Argonne National Laboratory
Lehoucq R B and Sorensen D C (1996) Deflation techniques for an implicitly restarted Arnoldi iteration SIAM Journal on Matrix Analysis and Applications 17 789–821
Lehoucq R B, Sorensen D C and Yang C (1998) ARPACK Users' Guide: Solution of Large-scale Eigenvalue Problems with Implicitly Restarted Arnoldi Methods SIAM, Philidelphia

5 Arguments

Note: this routine uses reverse communication. Its use involves an initial entry, intermediate exits and re-entries, and a final exit, as indicated by the argument IREVCM. Between intermediate exits and re-entries, all arguments other than X, MX and COMM must remain unchanged.
1:   IREVCM – INTEGERInput/Output
On initial entry: IREVCM=0, otherwise an error condition will be raised.
On intermediate re-entry: must be unchanged from its previous exit value. Changing IREVCM to any other value between calls will result in an error.
On intermediate exit: has the following meanings.
IREVCM=-1
The calling program must compute the matrix-vector product y=OPx, where x is stored in X (by default) or in the array COMM (starting from the location given by the first element of ICOMM) when the option Pointers=YES is set in a prior call to F12ARF. The result y is returned in X (by default) or in the array COMM (starting from the location given by the second element of ICOMM) when the option Pointers=YES is set.
IREVCM=1
The calling program must compute the matrix-vector product y=OPx. This is similar to the case IREVCM=-1 except that the result of the matrix-vector product Bx (as required in some computational modes) has already been computed and is available in MX (by default) or in the array COMM (starting from the location given by the third element of ICOMM) when the option Pointers=YES is set.
IREVCM=2
The calling program must compute the matrix-vector product y=Bx, where x is stored in X and y is returned in MX (by default) or in the array COMM (starting from the location given by the second element of ICOMM) when the option Pointers=YES is set.
IREVCM=3
Compute the NSHIFT complex shifts. This value of IREVCM will only arise if the optional parameter Supplied Shifts is set in a prior call to F12ARF which is intended for experienced users only; the default and recommended option is to use exact shifts (see Lehoucq et al. (1998) for details).
IREVCM=4
Monitoring step: a call to F12ASF can now be made to return the number of Arnoldi iterations, the number of converged Ritz values, the array of converged values, and the corresponding Ritz estimates.
On final exit: IREVCM=5: F12APF has completed its tasks. The value of IFAIL determines whether the iteration has been successfully completed, or whether errors have been detected. On successful completion F12AQF must be called to return the requested eigenvalues and eigenvectors (and/or Schur vectors).
Constraint: on initial entry, IREVCM=0; on re-entry IREVCM must remain unchanged.
2:   RESID* – COMPLEX (KIND=nag_wp) arrayInput/Output
Note: the dimension of the array RESID must be at least N (see F12ANF).
On initial entry: need not be set unless the option Initial Residual has been set in a prior call to F12ARF in which case RESID should contain an initial residual vector, possibly from a previous run.
On intermediate re-entry: must be unchanged from its previous exit. Changing RESID to any other value between calls may result in an error exit.
On intermediate exit: contains the current residual vector.
On final exit: contains the final residual vector.
3:   V LDV* – COMPLEX (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array V must be at least max 1,NCV (see F12ANF).
On initial entry: need not be set.
On intermediate re-entry: must be unchanged from its previous exit.
On intermediate exit: contains the current set of Arnoldi basis vectors.
On final exit: contains the final set of Arnoldi basis vectors.
4:   LDV – INTEGERInput
On entry: the first dimension of the array V as declared in the (sub)program from which F12APF is called.
Constraint: LDV≥N.
5:   X* – COMPLEX (KIND=nag_wp) arrayInput/Output
Note: the dimension of the array X must be at least N if Pointers=NO (default) and at least 1 if Pointers=YES (see F12ANF).
On initial entry: need not be set, it is used as a convenient mechanism for accessing elements of COMM.
On intermediate re-entry: if Pointers=YES, X need not be set.
If Pointers=NO, X must contain the result of y=OPx when IREVCM returns the value -1 or +1. It must return the computed shifts when IREVCM returns the value 3.
On intermediate exit: if Pointers=YES, X is not referenced.
If Pointers=NO, X contains the vector x when IREVCM returns the value -1 or +1.
On final exit: does not contain useful data.
6:   MX* – COMPLEX (KIND=nag_wp) arrayInput/Output
Note: the dimension of the array MX must be at least N if Pointers=NO (default) and at least 1 if Pointers=YES (see F12ANF).
On initial entry: need not be set, it is used as a convenient mechanism for accessing elements of COMM.
On intermediate re-entry: if Pointers=YES, MX need not be set.
If Pointers=NO, MX must contain the result of y=Bx when IREVCM returns the value 2.
On intermediate exit: if Pointers=YES, MX is not referenced.
If Pointers=NO, MX contains the vector Bx when IREVCM returns the value +1.
On final exit: does not contain any useful data.
7:   NSHIFT – INTEGEROutput
On intermediate exit: if the option Supplied Shifts is set and IREVCM returns a value of 3, NSHIFT returns the number of complex shifts required.
8:   COMM* – COMPLEX (KIND=nag_wp) arrayCommunication Array
Note: the dimension of the array COMM must be at least max 1,LCOMM (see F12ANF).
On initial entry: must remain unchanged following a call to the setup routine F12ANF.
On exit: contains data defining the current state of the iterative process.
9:   ICOMM* – INTEGER arrayCommunication Array
Note: the dimension of the array ICOMM must be at least max 1,LICOMM (see F12ANF).
On initial entry: must remain unchanged following a call to the setup routine F12ANF.
On exit: contains data defining the current state of the iterative process.
10:   IFAIL – INTEGERInput/Output
On initial entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, because for this routine the values of the output arguments may be useful even if IFAIL≠0 on exit, the recommended value is -1. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On intermediate exit: the value of IFAIL is meaningless and should be ignored.
On final exit: (i.e., when IREVCM=5) IFAIL=0, unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On initial entry, the maximum number of iterations ≤ 0 , the option Iteration Limit has been set to a non-positive value.
IFAIL=2
The options Generalized and Regular are incompatible.
IFAIL=3
The option Initial Residual was selected but the starting vector held in RESID is zero.
IFAIL=4
The maximum number of iterations has been reached. Some Ritz values may have converged; a subsequent call to F12AQF will return the number of converged values and the converged values.
IFAIL=5
No shifts could be applied during a cycle of the implicitly restarted Arnoldi iteration. One possibility is to increase the size of NCV relative to NEV (see Section 5 in F12ANF for details of these arguments).
IFAIL=6
Could not build an Arnoldi factorization. Consider changing NCV or NEV in the initialization routine (see Section 5 in F12ANF for details of these arguments).
IFAIL=7
Unexpected error in internal call to compute eigenvalues and corresponding error bounds of the current upper Hessenberg matrix. Please contact NAG.
IFAIL=8
Either the initialization routine F12ANF has not been called prior to the first call of this routine or a communication array has become corrupted.
IFAIL=9
An unexpected error has occurred. Please contact NAG.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

The relative accuracy of a Ritz value, λ , is considered acceptable if its Ritz estimate ≤ Tolerance × λ . The default Tolerance used is the machine precision given by X02AJF.

8 Parallelism and Performance

F12APF is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
F12APF makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

None.

10 Example

This example solves Ax = λx in shift-invert mode, where A is obtained from the standard central difference discretization of the convection-diffusion operator ∂2 u ∂x 2 + ∂2 u ∂y 2 + ρ ∂u ∂x on the unit square, with zero Dirichlet boundary conditions. The shift used is a complex number.

10.1 Program Text

Program Text (f12apfe.f90)

10.2 Program Data

Program Data (f12apfe.d)

10.3 Program Results

Program Results (f12apfe.r)

F12 Chapter Contents
F12 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F12AQF : NAG Library, Mark 26

F12 Chapter Contents
F12 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F12AQF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.
Note: this routine uses optional parameters to define choices in the problem specification. If you wish to use default settings for all of the optional parameters, then the option setting routine F12ARF need not be called. If, however, you wish to reset some or all of the settings please refer to Section 11 in F12ARF for a detailed description of the specification of the optional parameters.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F12AQF is a post-processing routine in a suite of routines consisting of F12ANF, F12APF, F12AQF, F12ARF and F12ASF, that must be called following a final exit from F12AQF.

2 Specification

SUBROUTINE F12AQF ( NCONV, D, Z, LDZ, SIGMA, RESID, V, LDV, COMM, ICOMM, IFAIL)
INTEGER | NCONV, LDZ, LDV, ICOMM(*), IFAIL
COMPLEX (KIND=nag_wp) | D(*), Z(LDZ,*), SIGMA, RESID(*), V(LDV,*), COMM(*)

3 Description

The suite of routines is designed to calculate some of the eigenvalues, λ , (and optionally the corresponding eigenvectors, x ) of a standard eigenvalue problem Ax = λx , or of a generalized eigenvalue problem Ax = λBx of order n , where n is large and the coefficient matrices A and B are sparse, complex and nonsymmetric. The suite can also be used to find selected eigenvalues/eigenvectors of smaller scale dense, complex and nonsymmetric problems.
Following a call to F12APF, F12AQF returns the converged approximations to eigenvalues and (optionally) the corresponding approximate eigenvectors and/or an orthonormal basis for the associated approximate invariant subspace. The eigenvalues (and eigenvectors) are selected from those of a standard or generalized eigenvalue problem defined by complex nonsymmetric matrices. There is negligible additional cost to obtain eigenvectors; an orthonormal basis is always computed, but there is an additional storage cost if both are requested.
F12AQF is based on the routine zneupd from the ARPACK package, which uses the Implicitly Restarted Arnoldi iteration method. The method is described in Lehoucq and Sorensen (1996) and Lehoucq (2001) while its use within the ARPACK software is described in great detail in Lehoucq et al. (1998). An evaluation of software for computing eigenvalues of sparse nonsymmetric matrices is provided in Lehoucq and Scott (1996). This suite of routines offers the same functionality as the ARPACK software for complex nonsymmetric problems, but the interface design is quite different in order to make the option setting clearer and to simplify some of the interfaces.
F12AQF is a post-processing routine that must be called following a successful final exit from F12APF. F12AQF uses data returned from F12APF and options set either by default or explicitly by calling F12ARF, to return the converged approximations to selected eigenvalues and (optionally):
– | the corresponding approximate eigenvectors;
– | an orthonormal basis for the associated approximate invariant subspace;
– | both.

4 References

Lehoucq R B (2001) Implicitly restarted Arnoldi methods and subspace iteration SIAM Journal on Matrix Analysis and Applications 23 551–562
Lehoucq R B and Scott J A (1996) An evaluation of software for computing eigenvalues of sparse nonsymmetric matrices Preprint MCS-P547-1195 Argonne National Laboratory
Lehoucq R B and Sorensen D C (1996) Deflation techniques for an implicitly restarted Arnoldi iteration SIAM Journal on Matrix Analysis and Applications 17 789–821
Lehoucq R B, Sorensen D C and Yang C (1998) ARPACK Users' Guide: Solution of Large-scale Eigenvalue Problems with Implicitly Restarted Arnoldi Methods SIAM, Philidelphia

5 Arguments

1:   NCONV – INTEGEROutput
On exit: the number of converged eigenvalues as found by F12ARF.
2:   D* – COMPLEX (KIND=nag_wp) arrayOutput
Note: the dimension of the array D must be at least NCV (see F12ANF).
On exit: the first NCONV locations of the array D contain the converged approximate eigenvalues.
3:   Z LDZ* – COMPLEX (KIND=nag_wp) arrayOutput
Note: the second dimension of the array Z must be at least NEV if the default option Vectors=RITZ has been selected and at least 1 if the option Vectors=NONE or SCHUR has been selected (see F12ANF).
On exit: if the default option Vectors=RITZ (see F12ADF) has been selected then Z contains the final set of eigenvectors corresponding to the eigenvalues held in D. The complex eigenvector associated with an eigenvalue is stored in the corresponding column of Z.
4:   LDZ – INTEGERInput
On entry: the first dimension of the array Z as declared in the (sub)program from which F12AQF is called.
Constraints:
  • if the default option Vectors=Ritz has been selected, LDZ≥N;
  • if the option Vectors=None or Schur has been selected, LDZ≥1.
5:   SIGMA – COMPLEX (KIND=nag_wp)Input
On entry: if one of the Shifted Inverse (see F12ARF) modes has been selected then SIGMA contains the shift used; otherwise SIGMA is not referenced.
6:   RESID* – COMPLEX (KIND=nag_wp) arrayInput
Note: the dimension of the array RESID must be at least N (see F12ANF).
On entry: must not be modified following a call to F12APF since it contains data required by F12AQF.
7:   V LDV* – COMPLEX (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array V must be at least max 1,NCV (see F12ANF).
On entry: the NCV columns of V contain the Arnoldi basis vectors for OP as constructed by F12APF.
On exit: if the option Vectors=SCHUR or RITZ has been set and a separate array Z has been passed (i.e., Z does not equal V), then the first NCONV columns of V will contain approximate Schur vectors that span the desired invariant subspace.
8:   LDV – INTEGERInput
On entry: the first dimension of the array V as declared in the (sub)program from which F12AQF is called.
Constraint: LDV≥N.
9:   COMM* – COMPLEX (KIND=nag_wp) arrayCommunication Array
Note: the dimension of the array COMM must be at least max 1,LCOMM (see F12ANF).
On initial entry: must remain unchanged from the prior call to F12ANF.
On exit: contains data on the current state of the solution.
10:   ICOMM* – INTEGER arrayCommunication Array
Note: the dimension of the array ICOMM must be at least max 1,LICOMM (see F12ANF).
On initial entry: must remain unchanged from the prior call to F12ANF.
On exit: contains data on the current state of the solution.
11:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, LDZ < max 1,N or LDZ < 1 when no vectors are required.
IFAIL=2
On entry, the option Vectors = Select was selected, but this is not yet implemented.
IFAIL=3
The number of eigenvalues found to sufficient accuracy prior to calling F12AQF, as communicated through the argument ICOMM, is zero.
IFAIL=4
The number of converged eigenvalues as calculated by F12APF differ from the value passed to it through the argument ICOMM.
IFAIL=5
Unexpected error during calculation of a Schur form: there was a failure to compute all the converged eigenvalues. Please contact NAG.
IFAIL=6
Unexpected error: the computed Schur form could not be reordered by an internal call. Please contact NAG.
IFAIL=7
Unexpected error in internal call while calculating eigenvectors. Please contact NAG.
IFAIL=8
Either the solver routine F12APF has not been called prior to the call of this routine or a communication array has become corrupted.
IFAIL=9
The routine was unable to dynamically allocate sufficient internal workspace. Please contact NAG.
IFAIL=10
An unexpected error has occurred. Please contact NAG.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

The relative accuracy of a Ritz value, λ , is considered acceptable if its Ritz estimate ≤ Tolerance × λ . The default Tolerance used is the machine precision given by X02AJF.

8 Parallelism and Performance

F12AQF makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

None.

10 Example

This example solves Ax = λBx in regular-invert mode, where A and B are derived from the standard central difference discretization of the one-dimensional convection-diffusion operator d 2 u d x 2 + ρ du dx on 0,1 , with zero Dirichlet boundary conditions.

10.1 Program Text

Program Text (f12aqfe.f90)

10.2 Program Data

Program Data (f12aqfe.d)

10.3 Program Results

Program Results (f12aqfe.r)

F12 Chapter Contents
F12 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F12ARF : NAG Library, Mark 26

F12 Chapter Contents
F12 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F12ARF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.
Note: this routine uses optional parameters to define choices in the problem specification. If you wish to use default settings for all of the optional parameters, then this routine need not be called. If, however, you wish to reset some or all of the settings please refer to Section 11 for a detailed description of the specification of the optional parameters.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results
▸▿ 11 Optional Parameters
11.1 Description of the Optional Parameters

1 Purpose

F12ARF is an option setting routine in a suite of routines consisting of F12ANF, F12APF, F12AQF, F12ARF and F12ASF, for which it may be used to supply individual optional parameters to F12APF and F12AQF. F12ARF is also an option setting routine in a suite of routines consisting of F12ANF, F12ATF and F12AUF for which it may be used to supply individual optional parameters to F12AUF.
The initialization routine for the appropriate suite, F12ANF or F12ATF, must have been called prior to calling F12ARF.

2 Specification

SUBROUTINE F12ARF ( STR, ICOMM, COMM, IFAIL)
INTEGER | ICOMM(*), IFAIL
COMPLEX (KIND=nag_wp) | COMM(*)
CHARACTER(*) | STR

3 Description

F12ARF may be used to supply values for optional parameters to F12APF and F12AQF, or to F12AUF. It is only necessary to call F12ARF for those arguments whose values are to be different from their default values. One call to F12ARF sets one argument value.
Each optional parameter is defined by a single character string consisting of one or more items. The items associated with a given option must be separated by spaces, or equals signs = . Alphabetic characters may be upper or lower case. The string
'Pointers = Yes'
is an example of a string used to set an optional parameter. For each option the string contains one or more of the following items:
– | a mandatory keyword;
– | a phrase that qualifies the keyword;
– | a number that specifies an integer or real value. Such numbers may be up to 16 contiguous characters in Fortran's I, F, E or D format.
F12ARF does not have an equivalent routine from the ARPACK package which passes options by directly setting values to scalar arguments or to specific elements of array arguments. F12ARF is intended to make the passing of options more transparent and follows the same principle as the single option setting routines in Chapter E04 (see E04NSF for an example).
The setup routine F12ANF must be called prior to the first call to F12ARF or F12ATF, and all calls to F12ARF must precede the first call to F12APF or F12AUF.
A complete list of optional parameters, their abbreviations, synonyms and default values is given in Section 11.

4 References

Lehoucq R B (2001) Implicitly restarted Arnoldi methods and subspace iteration SIAM Journal on Matrix Analysis and Applications 23 551–562
Lehoucq R B and Scott J A (1996) An evaluation of software for computing eigenvalues of sparse nonsymmetric matrices Preprint MCS-P547-1195 Argonne National Laboratory
Lehoucq R B and Sorensen D C (1996) Deflation techniques for an implicitly restarted Arnoldi iteration SIAM Journal on Matrix Analysis and Applications 17 789–821
Lehoucq R B, Sorensen D C and Yang C (1998) ARPACK Users' Guide: Solution of Large-scale Eigenvalue Problems with Implicitly Restarted Arnoldi Methods SIAM, Philidelphia

5 Arguments

1:   STR – CHARACTER(*)Input
On entry: a single valid option string (as described in Section 3 and Section 11).
2:   ICOMM* – INTEGER arrayCommunication Array
Note: the dimension of the array ICOMM must be at least max 1,LICOMM (see F12ANF).
On initial entry: must remain unchanged following a call to the setup routine F12ANF.
On exit: contains data on the current options set.
3:   COMM* – COMPLEX (KIND=nag_wp) arrayCommunication Array
Note: the dimension of the array COMM must be at least max 1,LCOMM (see F12ANF).
On initial entry: must remain unchanged following a call to the setup routine F12ANF.
On exit: contains data on the current options set.
4:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
The string passed in STR contains an ambiguous keyword.
IFAIL=2
The string passed in STR contains a keyword that could not be recognized.
IFAIL=3
The string passed in STR contains a second keyword that could not be recognized.
IFAIL=4
The initialization routine F12ANF or F12ATF has not been called or a communication array has become corrupted.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

Not applicable.

8 Parallelism and Performance

F12ARF is not threaded in any implementation.

9 Further Comments

None.

10 Example

This example solves Ax = λBx in shifted-inverse mode, where A and B are derived from the finite element discretization of the one-dimensional convection-diffusion operator d 2 u d x 2 + ρ du dx on the interval 0,1 , with zero Dirichlet boundary conditions.

10.1 Program Text

Program Text (f12arfe.f90)

10.2 Program Data

Program Data (f12arfe.d)

10.3 Program Results

Program Results (f12arfe.r)

11 Optional Parameters

Several optional parameters for the computational suite routines F12APF and F12AQF, and for the banded driver F12AUF, define choices in the problem specification or the algorithm logic. In order to reduce the number of formal arguments of F12APF, F12AQF and F12AUF these optional parameters have associated default values that are appropriate for most problems. Therefore, you need only specify those optional parameters whose values are to be different from their default values.
The remainder of this section can be skipped if you wish to use the default values for all optional parameters.
The following is a list of the optional parameters available. A full description of each optional parameter is provided in Section 11.1.
  • Advisory
  • Defaults
  • Exact Shifts
  • Generalized
  • Initial Residual
  • Iteration Limit
  • Largest Imaginary
  • Largest Magnitude
  • Largest Real
  • List
  • Monitoring
  • Nolist
  • Pointers
  • Print Level
  • Random Residual
  • Regular
  • Regular Inverse
  • Shifted Inverse
  • Smallest Imaginary
  • Smallest Magnitude
  • Smallest Real
  • Standard
  • Supplied Shifts
  • Tolerance
  • Vectors
Optional parameters may be specified by calling F12ARF before a call to F12APF or F12ATF, but after a corresponding call to F12ANF or F12AUF. One call is necessary for each optional parameter. Any optional parameters you do not specify are set to their default values. Optional parameters you do specify are unaltered by F12APF, F12AQF and F12AUF (unless they define invalid values) and so remain in effect for subsequent calls unless you alter them.

11.1 Description of the Optional Parameters

For each option, we give a summary line, a description of the optional parameter and details of constraints.
The summary line contains:
  • the keywords, where the minimum abbreviation of each keyword is underlined;
  • a parameter value, where the letters a, i and r denote options that take character, integer and real values respectively;
  • the default value, where the symbol ε is a generic notation for machine precision (see X02AJF).
Keywords and character values are case and white space insensitive.
Advisory i Default = the value returned by X04ABF
The destination for advisory messages.
Defaults
This special keyword may be used to reset all optional parameters to their default values.
Exact Shifts Default
Supplied Shifts
During the Arnoldi iterative process, shifts are applied as part of the implicit restarting scheme. The shift strategy used by default and selected by the optional parameter Exact Shifts is strongly recommended over the alternative Supplied Shifts and will always be used by F12AUF.
If Exact Shifts are used then these are computed internally by the algorithm in the implicit restarting scheme. This strategy is generally effective and cheaper to apply in terms of number of operations than using explicit shifts.
If Supplied Shifts are used then, during the Arnoldi iterative process, you must supply shifts through array arguments of F12APF when F12APF returns with IREVCM=3; the complex shifts are returned in X (or in COMM when the option Pointers=YES is set). This option should only be used if you are an experienced user since this requires some algorithmic knowledge and because more operations are usually required than for the implicit shift scheme. Details on the use of explicit shifts and further references on shift strategies are available in Lehoucq et al. (1998).
Iteration Limit i Default = 300
The limit on the number of Arnoldi iterations that can be performed before F12APF or F12AUF exits. If not all requested eigenvalues have converged to within Tolerance and the number of Arnoldi iterations has reached this limit then F12APF or F12AUF exits with an error; F12AUF returns the number of converged eigenvalues, the converged eigenvalues and, if requested, the corresponding eigenvectors, while F12AQF can be called subsequent to F12APF to do the same.
Largest Magnitude Default
Largest Imaginary
Largest Real
Smallest Imaginary
Smallest Magnitude
Smallest Real
The Arnoldi iterative method converges on a number of eigenvalues with given properties. The default is for F12APF or F12AUF to compute the eigenvalues of largest magnitude using Largest Magnitude. Alternatively, eigenvalues may be chosen which have Largest Real part, Largest Imaginary part,Smallest Magnitude, Smallest Real part or Smallest Imaginary part.
Note that these options select the eigenvalue properties for eigenvalues of OP (and B for Generalized problems), the linear operator determined by the computational mode and problem type.
Nolist Default
List
Normally each optional parameter specification is not printed to the advisory channel as it is supplied. Optional parameter List may be used to enable printing and optional parameter Nolist may be used to suppress the printing.
Monitoring i Default = -1
If i>0, monitoring information is output to channel number i during the solution of each problem; this may be the same as the Advisory channel number. The type of information produced is dependent on the value of Print Level, see the description of the optional parameter Print Level for details of the information produced. Please see X04ACF to associate a file with a given channel number.
Pointers Default = NO
During the iterative process and reverse communication calls to F12APF, required data can be communicated to and from F12APF in one of two ways. When Pointers=NO is selected (the default) then the array arguments X and MX are used to supply you with required data and used to return computed values back to F12APF. For example, when IREVCM=1, F12APF returns the vector x in X and the matrix-vector product Bx in MX and expects the result or the linear operation OP x to be returned in X.
If Pointers=YES is selected then the data is passed through sections of the array argument COMM. The section corresponding to X when Pointers=NO begins at a location given by the first element of ICOMM; similarly the section corresponding to MX begins at a location given by the second element of ICOMM. This option allows F12APF to perform fewer copy operations on each intermediate exit and entry, but can also lead to less elegant code in the calling program.
This option has no affect on F12AUF which sets Pointers=YES internally.
Print Level i Default = 0
This controls the amount of printing produced by F12ARF as follows.
=0 | No output except error messages.
>0 | The set of selected options.
=2 | Problem and timing statistics on final exit from F12APF or F12AUF.
≥5 | A single line of summary output at each Arnoldi iteration.
≥10 | If Monitoring>0, Monitoring is set, then at each iteration, the length and additional steps of the current Arnoldi factorization and the number of converged Ritz values; during re-orthogonalization, the norm of initial/restarted starting vector.
≥20 | Problem and timing statistics on final exit from F12APF. If Monitoring>0, Monitoring is set, then at each iteration, the number of shifts being applied, the eigenvalues and estimates of the Hessenberg matrix H, the size of the Arnoldi basis, the wanted Ritz values and associated Ritz estimates and the shifts applied; vector norms prior to and following re-orthogonalization.
≥30 | If Monitoring>0, Monitoring is set, then on final iteration, the norm of the residual; when computing the Schur form, the eigenvalues and Ritz estimates both before and after sorting; for each iteration, the norm of residual for compressed factorization and the compressed upper Hessenberg matrix H; during re-orthogonalization, the initial/restarted starting vector; during the Arnoldi iteration loop, a restart is flagged and the number of the residual requiring iterative refinement; while applying shifts, the indices of the shifts being applied.
≥40 | If Monitoring>0, Monitoring is set, then during the Arnoldi iteration loop, the Arnoldi vector number and norm of the current residual; while applying shifts, key measures of progress and the order of H; while computing eigenvalues of H, the last rows of the Schur and eigenvector matrices; when computing implicit shifts, the eigenvalues and Ritz estimates of H.
≥50 | If Monitoring is set, then during Arnoldi iteration loop: norms of key components and the active column of H, norms of residuals during iterative refinement, the final upper Hessenberg matrix H; while applying shifts: number of shifts, shift values, block indices, updated matrix H; while computing eigenvalues of H: the matrix H, the computed eigenvalues and Ritz estimates.
Random Residual Default
Initial Residual
To begin the Arnoldi iterative process, F12APF and F12AUF requires an initial residual vector. By default F12APF and F12AUF provides its own random initial residual vector; this option can also be set using optional parameter Random Residual. Alternatively, you can supply an initial residual vector (perhaps from a previous computation) to F12APF and F12AUF through the array argument RESID; this option can be set using optional parameter Initial Residual.
Regular Default
Regular Inverse
Shifted Inverse
These options define the computational mode which in turn defines the form of operation OP x to be performed by F12AUF or when F12APF returns with IREVCM=-1 or 1 and the matrix-vector product Bx when F12APF returns with IREVCM=-2.
Given a Standard eigenvalue problem in the form Ax=λx then the following modes are available with the appropriate operator OP x.
Regular | OP=A
Shifted Inverse | OP=A-σI-1
Given a Generalized eigenvalue problem in the form Ax=λBx then the following modes are available with the appropriate operator OP x.
Regular Inverse | OP=B-1 A
Shifted Inverse | OP=A-σB-1 B
Standard Default
Generalized
The problem to be solved is either a standard eigenvalue problem, Ax=λx, or a generalized eigenvalue problem, Ax=λBx. The optional parameter Standard should be used when a standard eigenvalue problem is being solved and the optional parameter Generalized should be used when a generalized eigenvalue problem is being solved.
Tolerance r Default = ε
An approximate eigenvalue has deemed to have converged when the corresponding Ritz estimate is within Tolerance relative to the magnitude of the eigenvalue.
Vectors Default = RITZ
The routine F12AQF or F12AUF can optionally compute the Schur vectors and/or the eigenvectors corresponding to the converged eigenvalues. To turn off computation of any vectors the option Vectors=NONE should be set. To compute only the Schur vectors (at very little extra cost), the option Vectors=SCHUR should be set and these will be returned in the array argument V of F12AQF or F12AUF. To compute the eigenvectors (Ritz vectors) corresponding to the eigenvalue estimates, the option Vectors=RITZ should be set and these will be returned in the array argument Z of F12AQF or F12AUF, if Z is set equal to V (as in Section 10) then the Schur vectors in V are overwritten by the eigenvectors computed by F12AQF or F12AUF.
F12 Chapter Contents
F12 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F12ASF : NAG Library, Mark 26

F12 Chapter Contents
F12 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F12ASF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.
Note: this routine uses optional parameters to define choices in the problem specification. If you wish to use default settings for all of the optional parameters, then the option setting routine F12ARF need not be called. If, however, you wish to reset some or all of the settings please refer to Section 11 in F12ARF for a detailed description of the specification of the optional parameters.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F12ASF can be used to return additional monitoring information during computation. It is in a suite of routines consisting of F12ANF, F12APF, F12AQF, F12ARF and F12ASF.

2 Specification

SUBROUTINE F12ASF ( NITER, NCONV, RITZ, RZEST, ICOMM, COMM)
INTEGER | NITER, NCONV, ICOMM(*)
COMPLEX (KIND=nag_wp) | RITZ(*), RZEST(*), COMM(*)

3 Description

The suite of routines is designed to calculate some of the eigenvalues, λ , (and optionally the corresponding eigenvectors, x ) of a standard complex eigenvalue problem Ax = λx , or of a generalized complex eigenvalue problem Ax = λBx of order n , where n is large and the coefficient matrices A and B are sparse and complex. The suite can also be used to find selected eigenvalues/eigenvectors of smaller scale dense complex problems.
On an intermediate exit from F12APF with IREVCM = 4 , F12ASF may be called to return monitoring information on the progress of the Arnoldi iterative process. The information returned by F12ASF is:
– | the number of the current Arnoldi iteration;
– | the number of converged eigenvalues at this point;
– | the converged eigenvalues;
– | the error bounds on the converged eigenvalues.
F12ASF does not have an equivalent routine from the ARPACK package which prints various levels of detail of monitoring information through an output channel controlled via an argument value (see Lehoucq et al. (1998) for details of ARPACK routines). F12ASF should not be called at any time other than immediately following an IREVCM = 4 return from F12APF.

4 References

Lehoucq R B (2001) Implicitly restarted Arnoldi methods and subspace iteration SIAM Journal on Matrix Analysis and Applications 23 551–562
Lehoucq R B and Scott J A (1996) An evaluation of software for computing eigenvalues of sparse nonsymmetric matrices Preprint MCS-P547-1195 Argonne National Laboratory
Lehoucq R B and Sorensen D C (1996) Deflation techniques for an implicitly restarted Arnoldi iteration SIAM Journal on Matrix Analysis and Applications 17 789–821
Lehoucq R B, Sorensen D C and Yang C (1998) ARPACK Users' Guide: Solution of Large-scale Eigenvalue Problems with Implicitly Restarted Arnoldi Methods SIAM, Philidelphia

5 Arguments

1:   NITER – INTEGEROutput
On exit: the number of the current Arnoldi iteration.
2:   NCONV – INTEGEROutput
On exit: the number of converged eigenvalues so far.
3:   RITZ* – COMPLEX (KIND=nag_wp) arrayOutput
Note: the dimension of the array RITZ must be at least NCV (see F12ANF).
On exit: the first NCONV locations of the array RITZ contain the converged approximate eigenvalues.
4:   RZEST* – COMPLEX (KIND=nag_wp) arrayOutput
Note: the dimension of the array RZEST must be at least NCV (see F12ANF).
On exit: the first NCONV locations of the array RZEST contain the complex Ritz estimates on the converged approximate eigenvalues.
5:   ICOMM* – INTEGER arrayCommunication Array
Note: the dimension of the array ICOMM must be at least max 1,LICOMM, where LICOMM is passed to the setup routine (see F12ANF).
On entry: the array ICOMM output by the preceding call to F12APF.
6:   COMM* – COMPLEX (KIND=nag_wp) arrayCommunication Array
Note: the dimension of the array COMM must be at least max 1,LCOMM, where LCOMM is passed to the setup routine (see F12ANF).
On entry: the array COMM output by the preceding call to F12APF.

6 Error Indicators and Warnings

None.

7 Accuracy

A Ritz value, λ , is deemed to have converged if the magnitude of its Ritz estimate ≤ Tolerance × λ . The default Tolerance used is the machine precision given by X02AJF.

8 Parallelism and Performance

F12ASF is not threaded in any implementation.

9 Further Comments

None.

10 Example

This example solves Ax = λBx in shifted-inverse mode, where A and B are obtained from the standard central difference discretization of the one-dimensional convection-diffusion operator d 2 u d x 2 + ρ du dx on 0,1 , with zero Dirichlet boundary conditions. The shift, σ , is a complex number, and the operator used in the shifted-inverse iterative process is OP = inv A - σB × B .

10.1 Program Text

Program Text (f12asfe.f90)

10.2 Program Data

Program Data (f12asfe.d)

10.3 Program Results

Program Results (f12asfe.r)

F12 Chapter Contents
F12 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F12ATF : NAG Library, Mark 26

F12 Chapter Contents
F12 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F12ATF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
10 Example

1 Purpose

F12ATF is a setup routine for F12AUF which may be used for finding some eigenvalues (and optionally the corresponding eigenvectors) of a standard or generalized eigenvalue problem defined by complex, banded, non-Hermitian matrices. The banded matrix must be stored using the LAPACK column ordered storage format for complex banded non-Hermitian matrices (see Section 3.3.4 in the F07 Chapter Introduction).

2 Specification

SUBROUTINE F12ATF ( N, NEV, NCV, ICOMM, LICOMM, COMM, LCOMM, IFAIL)
INTEGER | N, NEV, NCV, ICOMM(max(1,LICOMM)), LICOMM, LCOMM, IFAIL
COMPLEX (KIND=nag_wp) | COMM(max(1,LCOMM))

3 Description

The pair of routines F12ATF and F12AUF together with the option setting routine F12ARF are designed to calculate some of the eigenvalues, λ , (and optionally the corresponding eigenvectors, x ) of a standard eigenvalue problem Ax = λx , or of a generalized eigenvalue problem Ax = λBx of order n , where n is large and the coefficient matrices A and B are banded complex and non-Hermitian.
F12ATF is a setup routine which must be called before the option setting routine F12ARF and the solver routine F12AUF. Internally, F12AUF makes calls to F12APF and F12AQF; the routine documents for F12APF and F12AQF should be consulted for details of the algorithm used.
This setup routine initializes the communication arrays, sets (to their default values) all options that can be set by you via the option setting routine F12ARF, and checks that the lengths of the communication arrays as passed by you are of sufficient length. For details of the options available and how to set them, see Section 11.1 in F12ARF.

4 References

Lehoucq R B (2001) Implicitly restarted Arnoldi methods and subspace iteration SIAM Journal on Matrix Analysis and Applications 23 551–562
Lehoucq R B and Scott J A (1996) An evaluation of software for computing eigenvalues of sparse nonsymmetric matrices Preprint MCS-P547-1195 Argonne National Laboratory
Lehoucq R B and Sorensen D C (1996) Deflation techniques for an implicitly restarted Arnoldi iteration SIAM Journal on Matrix Analysis and Applications 17 789–821
Lehoucq R B, Sorensen D C and Yang C (1998) ARPACK Users' Guide: Solution of Large-scale Eigenvalue Problems with Implicitly Restarted Arnoldi Methods SIAM, Philidelphia

5 Arguments

1:   N – INTEGERInput
On entry: the order of the matrix A (and the order of the matrix B for the generalized problem) that defines the eigenvalue problem.
Constraint: N>0.
2:   NEV – INTEGERInput
On entry: the number of eigenvalues to be computed.
Constraint: 0<NEV<N-1.
3:   NCV – INTEGERInput
On entry: the number of Lanczos basis vectors to use during the computation.
At present there is no a priori analysis to guide the selection of NCV relative to NEV. However, it is recommended that NCV≥2×NEV+1. If many problems of the same type are to be solved, you should experiment with increasing NCV while keeping NEV fixed for a given test problem. This will usually decrease the required number of matrix-vector operations but it also increases the work and storage required to maintain the orthogonal basis vectors. The optimal ‘cross-over’ with respect to CPU time is problem dependent and must be determined empirically.
Constraint: NEV+1<NCV≤N.
4:   ICOMM max 1,LICOMM – INTEGER arrayCommunication Array
On exit: contains data to be communicated to F12AUF.
5:   LICOMM – INTEGERInput
On entry: the dimension of the array ICOMM as declared in the (sub)program from which F12ATF is called.
If LICOMM=-1, a workspace query is assumed and the routine only calculates the required dimensions of ICOMM and COMM, which it returns in ICOMM 1 and COMM 1 respectively.
Constraint: LICOMM≥140 ​ or ​ LICOMM=-1.
6:   COMM max 1,LCOMM – COMPLEX (KIND=nag_wp) arrayCommunication Array
On exit: contains data to be communicated to F12AUF.
7:   LCOMM – INTEGERInput
On entry: the dimension of the array COMM as declared in the (sub)program from which F12ATF is called.
If LCOMM=-1, a workspace query is assumed and the routine only calculates the dimensions of ICOMM and COMM required by F12AUF, which it returns in ICOMM 1 and COMM 1 respectively.
Constraint: LCOMM≥60 ​ or ​ LCOMM=-1.
8:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, N =value.
Constraint: N>0.
IFAIL=2
On entry, NEV =value.
Constraint: NEV>0.
IFAIL=3
On entry, NCV=value, NEV=value and N=value.
Constraint: NCV>NEV+1 and NCV≤N.
IFAIL=4
The length of the integer array ICOMM is too small LICOMM =value, but must be at least value.
IFAIL=5
The length of the complex array COMM is too small LCOMM =value, but must be at least value.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

Not applicable.

8 Parallelism and Performance

F12ATF is not threaded in any implementation.

9 Further Comments

None.

10 Example

The use of F12ATF is illustrated in Section 10 in F12AUF.
F12 Chapter Contents
F12 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F12AUF : NAG Library, Mark 26

F12 Chapter Contents
F12 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F12AUF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.
Note: this routine uses optional parameters to define choices in the problem specification. If you wish to use default settings for all of the optional parameters, then the option setting routine F12ARF need not be called. If, however, you wish to reset some or all of the settings please refer to Section 11 in F12ARF for a detailed description of the specification of the optional parameters.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F12AUF is the main solver routine in a suite of routines consisting of F12ARF, F12ATF and F12AUF. It must be called following an initial call to F12ATF and following any calls to F12ARF.
F12AUF returns approximations to selected eigenvalues, and (optionally) the corresponding eigenvectors, of a standard or generalized eigenvalue problem defined by complex banded non-Hermitian matrices. The banded matrix must be stored using the LAPACK storage format for complex banded non-Hermitian matrices.

2 Specification

SUBROUTINE F12AUF ( KL, KU, AB, LDAB, MB, LDMB, SIGMA, NCONV, D, Z, LDZ, RESID, V, LDV, COMM, ICOMM, IFAIL)
INTEGER | KL, KU, LDAB, LDMB, NCONV, LDZ, LDV, ICOMM(140), IFAIL
COMPLEX (KIND=nag_wp) | AB(LDAB,*), MB(LDMB,*), SIGMA, D(NEV), Z(LDZ,*), RESID(N), V(LDV,*), COMM(60)

3 Description

The suite of routines is designed to calculate some of the eigenvalues, λ , (and optionally the corresponding eigenvectors, x ) of a standard eigenvalue problem Ax = λx , or of a generalized eigenvalue problem Ax = λBx of order n , where n is large and the coefficient matrices A and B are banded, complex and non-Hermitian.
Following a call to the initialization routine F12ATF, F12AUF returns the converged approximations to eigenvalues and (optionally) the corresponding approximate eigenvectors and/or a unitary basis for the associated approximate invariant subspace. The eigenvalues (and eigenvectors) are selected from those of a standard or generalized eigenvalue problem defined by complex banded non-Hermitian matrices. There is negligible additional computational cost to obtain eigenvectors; a unitary basis is always computed, but there is an additional storage cost if both are requested.
The banded matrices A and B must be stored using the LAPACK column ordered storage format for banded non-Hermitian matrices; please refer to Section 3.3.4 in the F07 Chapter Introduction for details on this storage format.
F12AUF is based on the banded driver routines znbdr1 to znbdr4 from the ARPACK package, which uses the Implicitly Restarted Arnoldi iteration method. The method is described in Lehoucq and Sorensen (1996) and Lehoucq (2001) while its use within the ARPACK software is described in great detail in Lehoucq et al. (1998). An evaluation of software for computing eigenvalues of sparse non-Hermitian matrices is provided in Lehoucq and Scott (1996). This suite of routines offers the same functionality as the ARPACK banded driver software for complex non-Hermitian problems, but the interface design is quite different in order to make the option setting clearer and to combine the different drivers into a general purpose routine.
F12AUF, is a general purpose routine that must be called following initialization by F12ATF. F12AUF uses options, set either by default or explicitly by calling F12ARF, to return the converged approximations to selected eigenvalues and (optionally):
– | the corresponding approximate eigenvectors;
– | a unitary basis for the associated approximate invariant subspace;
– | both.

4 References

Lehoucq R B (2001) Implicitly restarted Arnoldi methods and subspace iteration SIAM Journal on Matrix Analysis and Applications 23 551–562
Lehoucq R B and Scott J A (1996) An evaluation of software for computing eigenvalues of sparse nonsymmetric matrices Preprint MCS-P547-1195 Argonne National Laboratory
Lehoucq R B and Sorensen D C (1996) Deflation techniques for an implicitly restarted Arnoldi iteration SIAM Journal on Matrix Analysis and Applications 17 789–821
Lehoucq R B, Sorensen D C and Yang C (1998) ARPACK Users' Guide: Solution of Large-scale Eigenvalue Problems with Implicitly Restarted Arnoldi Methods SIAM, Philidelphia

5 Arguments

Note: in the following description N, NEV and NCV appears. In every case they should be interpretted as the value associated with the identically named argument in a prior call to F12ATF.
1:   KL – INTEGERInput
On entry: the number of subdiagonals of the matrices A and B.
Constraint: KL≥0.
2:   KU – INTEGERInput
On entry: the number of superdiagonals of the matrices A and B.
Constraint: KU≥0.
3:   AB LDAB* – COMPLEX (KIND=nag_wp) arrayInput
Note: the second dimension of the array AB must be at least max 1,N (see F12ATF).
On entry: must contain the matrix A in LAPACK banded storage format for non-Hermitian matrices (see Section 3.3.4 in the F07 Chapter Introduction).
4:   LDAB – INTEGERInput
On entry: the first dimension of the array AB as declared in the (sub)program from which F12AUF is called.
Constraint: LDAB ≥ 2×KL+KU+1.
5:   MB LDMB* – COMPLEX (KIND=nag_wp) arrayInput
Note: the second dimension of the array MB must be at least max 1,N (see F12ATF).
On entry: must contain the matrix B in LAPACK banded storage format for non-Hermitian matrices (see Section 3.3.4 in the F07 Chapter Introduction).
6:   LDMB – INTEGERInput
On entry: the first dimension of the array MB as declared in the (sub)program from which F12AUF is called.
Constraint: LDMB≥2×KL+KU+1.
7:   SIGMA – COMPLEX (KIND=nag_wp)Input
On entry: if the Shifted Inverse mode (see F12ARF) has been selected then SIGMA must contain the shift used; otherwise SIGMA is not referenced. Section 4.2 in the F12 Chapter Introduction describes the use of shift and invert transformations.
8:   NCONV – INTEGEROutput
On exit: the number of converged eigenvalues.
9:   D NEV – COMPLEX (KIND=nag_wp) arrayOutput
On exit: the first NCONV locations of the array D contain the converged approximate eigenvalues.
10:   Z LDZ* – COMPLEX (KIND=nag_wp) arrayOutput
Note: the second dimension of the array Z must be at least NEV if the default option Vectors=Ritz has been selected and at least 1 if the option Vectors=None or Schur has been selected (see F12ARF and F12ATF).
On exit: if the default option Vectors=RITZ (see F12ARF) has been selected then Z contains the final set of eigenvectors corresponding to the eigenvalues held in D, otherwise Z is not referenced. The complex eigenvector associated with an eigenvalue D j is stored in the corresponding array section of Z, namely Z ij, for i=1,2,…,N and j=1,2,…,NCONV.
11:   LDZ – INTEGERInput
On entry: the first dimension of the array Z as declared in the (sub)program from which F12AUF is called.
Constraints:
  • if the default option Vectors=Ritz has been selected, LDZ≥N;
  • if the option Vectors=None or Schur has been selected, LDZ≥1.
12:   RESID N – COMPLEX (KIND=nag_wp) arrayInput/Output
On entry: need not be set unless the option Initial Residual has been set in a prior call to F12ARF in which case RESID must contain an initial residual vector.
On exit: contains the final residual vector. This can be used as the starting residual to improve convergence on the solution of a closely related eigenproblem. This has no relation to the error residual Ax-λx or Ax-λBx.
13:   V LDV* – COMPLEX (KIND=nag_wp) arrayOutput
Note: the second dimension of the array V must be at least max 1,NCV (see F12ATF).
On exit: if the option Vectors=SCHUR or RITZ (see F12ARF) has been set and a separate array Z has been passed (i.e., Z does not equal V), then the first NCONV columns of V will contain approximate Schur vectors that span the desired invariant subspace.
The jth Schur vector is stored in the ith column of V.
14:   LDV – INTEGERInput
On entry: the first dimension of the array V as declared in the (sub)program from which F12AUF is called.
Constraint: LDV≥N.
15:   COMM 60 – COMPLEX (KIND=nag_wp) arrayCommunication Array
On entry: must remain unchanged from the prior call to F12ARF and F12ATF.
16:   ICOMM 140 – INTEGER arrayCommunication Array
On entry: must remain unchanged from the prior call to F12ARF and F12ATF.
17:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, KL=value.
Constraint: KL ≥ 0.
IFAIL=2
On entry, KU=value.
Constraint: KU ≥ 0.
IFAIL=3
On entry, LDAB=value, 2×KL+KU+1=value.
Constraint: LDAB≥2×KL+KU+1.
IFAIL=5
The maximum number of iterations ≤0, the option Iteration Limit has been set to value.
IFAIL=6
The options Generalized and Regular are incompatible.
IFAIL=7
The option Initial Residual was selected but the starting vector held in RESID is zero.
IFAIL=8
Either the initialization routine has not been called prior to the first call of this routine or a communication array has become corrupted.
IFAIL=9
On entry, LDZ=value, N=value in F12AFF.
Constraint: LDZ≥N.
IFAIL=10
On entry, Vectors = Select , but this is not yet implemented.
IFAIL=11
The number of eigenvalues found to sufficient accuracy is zero.
IFAIL=12
Could not build an Arnoldi factorization. The size of the current Arnoldi factorization = value.
IFAIL=13
Error in internal call to compute eigenvalues and corresponding error bounds of the current upper Hessenberg matrix. Please contact NAG.
IFAIL=14
During calculation of a Schur form, there was a failure to compute a number of eigenvalues Please contact NAG.
IFAIL=15
The computed Schur form could not be reordered by an internal call. Please contact NAG.
IFAIL=16
Error in internal call to compute eigenvectors. Please contact NAG.
IFAIL=17
Failure during internal factorization of real banded matrix. Please contact NAG.
IFAIL=18
Failure during internal solution of real banded matrix. Please contact NAG.
IFAIL=19
Failure during internal factorization of complex banded matrix. Please contact NAG.
IFAIL=20
Failure during internal solution of complex banded matrix. Please contact NAG.
IFAIL=21
The maximum number of iterations has been reached. The maximum number of iterations=value. The number of converged eigenvalues =value.
IFAIL=22
No shifts could be applied during a cycle of the implicitly restarted Arnoldi iteration.
IFAIL=23
Overflow occurred during transformation of Ritz values to those of the original problem.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

The relative accuracy of a Ritz value, λ , is considered acceptable if its Ritz estimate ≤ Tolerance × λ . The default Tolerance used is the machine precision given by X02AJF.

8 Parallelism and Performance

F12AUF is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
F12AUF makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

None.

10 Example

This example constructs the matrices A and B using LAPACK band storage format and solves Ax=λBx in shifted inverse mode using the complex shift σ .

10.1 Program Text

Program Text (f12aufe.f90)

10.2 Program Data

Program Data (f12aufe.d)

10.3 Program Results

Program Results (f12aufe.r)

F12 Chapter Contents
F12 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F12 Chapter Contents : NAG Library Manual, Mark 26

F12 Chapter Introduction
NAG Library Manual

NAG Library Chapter Contents

F12 – Large Scale Eigenproblems

F12 Chapter Introduction – a description of the Chapter and an overview of the algorithms available

Routine Name | Mark of Introduction | Purpose
F12AAF Example Text Example Data | 21 | nagf_sparseig_real_init Initialization routine for (F12ABF) computing selected eigenvalues and, optionally, eigenvectors of a real nonsymmetric sparse (standard or generalized) eigenproblem
F12ABF Example Text Example Data | 21 | nagf_sparseig_real_iter Selected eigenvalues and, optionally, eigenvectors of a real nonsymmetric sparse eigenproblem, reverse communication
F12ACF Example Text Example Data | 21 | nagf_sparseig_real_proc Selected eigenvalues and, optionally, eigenvectors of a real nonsymmetric sparse eigenproblem, postprocessing for F12ABF
F12ADF Example Text Example Data | 21 | nagf_sparseig_real_option Set a single option from a string (F12ABF/F12ACF/F12AGF)
F12AEF Example Text Example Data | 21 | nagf_sparseig_real_monit Provides monitoring information for F12ABF
F12AFF | 21 | nagf_sparseig_real_band_init Initialization routine for (F12AGF) computing selected eigenvalues and, optionally, eigenvectors of a real nonsymmetric banded (standard or generalized) eigenproblem
F12AGF Example Text Example Data | 21 | nagf_sparseig_real_band_solve Selected eigenvalues and, optionally, eigenvectors of a real nonsymmetric banded eigenproblem, driver
F12ANF Example Text Example Data | 21 | nagf_sparseig_complex_init Initialization routine for (F12APF) computing selected eigenvalues and, optionally, eigenvectors of a complex sparse (standard or generalized) eigenproblem
F12APF Example Text Example Data | 21 | nagf_sparseig_complex_iter Selected eigenvalues and, optionally, eigenvectors of a complex sparse eigenproblem, reverse communication
F12AQF Example Text Example Data | 21 | nagf_sparseig_complex_proc Selected eigenvalues and, optionally, eigenvectors of a complex sparse eigenproblem, postprocessing for F12APF
F12ARF Example Text Example Data | 21 | nagf_sparseig_complex_option Set a single option from a string (F12APF/F12AQF)
F12ASF Example Text Example Data | 21 | nagf_sparseig_complex_monit Provides monitoring information for F12APF
F12ATF | 24 | nagf_sparseig_complex_band_init Initialization routine for F12AUF computing selected eigenvalues and, optionally, eigenvectors of a complex banded (standard or generalized) eigenproblem.
F12AUF Example Text Example Data | 24 | nagf_sparseig_complex_band_solve Selected eigenvalues and, optionally, eigenvectors of complex non-Hermitian banded eigenproblem, driver
F12FAF Example Text Example Data | 21 | nagf_sparseig_real_symm_init Initialization routine for (F12FBF) computing selected eigenvalues and, optionally, eigenvectors of a real symmetric sparse (standard or generalized) eigenproblem
F12FBF Example Text Example Data | 21 | nagf_sparseig_real_symm_iter Selected eigenvalues and, optionally, eigenvectors of a real symmetric sparse eigenproblem, reverse communication
F12FCF Example Text Example Data | 21 | nagf_sparseig_real_symm_proc Selected eigenvalues and, optionally, eigenvectors of a real symmetric sparse eigenproblem, postprocessing for F12FBF
F12FDF Example Text Example Data | 21 | nagf_sparseig_real_symm_option Set a single option from a string (F12FBF/F12FCF/F12FGF)
F12FEF Example Text Example Data | 21 | nagf_sparseig_real_symm_monit Provides monitoring information for F12FBF
F12FFF | 21 | nagf_sparseig_real_symm_band_init Initialization routine for (F12FGF) computing selected eigenvalues and, optionally, eigenvectors of a real symmetric banded (standard or generalized) eigenproblem
F12FGF Example Text Example Data | 21 | nagf_sparseig_real_symm_band_solve Selected eigenvalues and, optionally, eigenvectors of a real symmetric banded eigenproblem, driver
F12 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F12FAF : NAG Library, Mark 26

F12 Chapter Contents
F12 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F12FAF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F12FAF is a setup routine in a suite of routines consisting of F12FAF, F12FBF, F12FCF, F12FDF and F12FEF. It is used to find some of the eigenvalues (and optionally the corresponding eigenvectors) of a standard or generalized eigenvalue problem defined by real symmetric matrices.
The suite of routines is suitable for the solution of large sparse, standard or generalized, symmetric eigenproblems where only a few eigenvalues from a selected range of the spectrum are required.

2 Specification

SUBROUTINE F12FAF ( N, NEV, NCV, ICOMM, LICOMM, COMM, LCOMM, IFAIL)
INTEGER | N, NEV, NCV, ICOMM(max(1,LICOMM)), LICOMM, LCOMM, IFAIL
REAL (KIND=nag_wp) | COMM(max(1,LCOMM))

3 Description

The suite of routines is designed to calculate some of the eigenvalues, λ , (and optionally the corresponding eigenvectors, x ) of a standard eigenvalue problem Ax = λx , or of a generalized eigenvalue problem Ax = λBx of order n , where n is large and the coefficient matrices A and B are sparse, real and symmetric. The suite can also be used to find selected eigenvalues/eigenvectors of smaller scale dense, real and symmetric problems.
F12FAF is a setup routine which must be called before F12FBF, the reverse communication iterative solver, and before F12FDF, the options setting routine. F12FCF, is a post-processing routine that must be called following a successful final exit from F12FBF, while F12FEF can be used to return additional monitoring information during the computation.
This setup routine initializes the communication arrays, sets (to their default values) all options that can be set by you via the option setting routine F12FDF, and checks that the lengths of the communication arrays as passed by you are of sufficient length. For details of the options available and how to set them see Section 11.1 in F12FDF.

4 References

Lehoucq R B (2001) Implicitly restarted Arnoldi methods and subspace iteration SIAM Journal on Matrix Analysis and Applications 23 551–562
Lehoucq R B and Scott J A (1996) An evaluation of software for computing eigenvalues of sparse nonsymmetric matrices Preprint MCS-P547-1195 Argonne National Laboratory
Lehoucq R B and Sorensen D C (1996) Deflation techniques for an implicitly restarted Arnoldi iteration SIAM Journal on Matrix Analysis and Applications 17 789–821
Lehoucq R B, Sorensen D C and Yang C (1998) ARPACK Users' Guide: Solution of Large-scale Eigenvalue Problems with Implicitly Restarted Arnoldi Methods SIAM, Philidelphia

5 Arguments

1:   N – INTEGERInput
On entry: the order of the matrix A (and the order of the matrix B for the generalized problem) that defines the eigenvalue problem.
Constraint: N>0.
2:   NEV – INTEGERInput
On entry: the number of eigenvalues to be computed.
Constraint: 0<NEV<N-1.
3:   NCV – INTEGERInput
On entry: the number of Lanczos basis vectors to use during the computation.
At present there is no a priori analysis to guide the selection of NCV relative to NEV. However, it is recommended that NCV≥2×NEV+1. If many problems of the same type are to be solved, you should experiment with increasing NCV while keeping NEV fixed for a given test problem. This will usually decrease the required number of matrix-vector operations but it also increases the work and storage required to maintain the orthogonal basis vectors. The optimal ‘cross-over’ with respect to CPU time is problem dependent and must be determined empirically.
Constraint: NEV<NCV≤N.
4:   ICOMM max 1,LICOMM – INTEGER arrayCommunication Array
On exit: contains data to be communicated to the other routines in the suite.
5:   LICOMM – INTEGERInput
On entry: the dimension of the array ICOMM as declared in the (sub)program from which F12FAF is called.
If LICOMM=-1, a workspace query is assumed and the routine only calculates the required dimensions of ICOMM and COMM, which it returns in ICOMM 1 and COMM 1 respectively.
Constraint: LICOMM≥140 ​ or ​ LICOMM=-1.
6:   COMM max 1,LCOMM – REAL (KIND=nag_wp) arrayCommunication Array
On exit: contains data to be communicated to the other routines in the suite.
7:   LCOMM – INTEGERInput
On entry: the dimension of the array COMM as declared in the (sub)program from which F12FAF is called.
If LCOMM=-1, a workspace query is assumed and the routine only calculates the dimensions of ICOMM and COMM required by F12FBF, which it returns in ICOMM 1 and COMM 1 respectively.
Constraint: LCOMM≥3×N+NCV×NCV+8×NCV+60 ​ or ​ LCOMM=-1.
8:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, N≤0.
IFAIL=2
On entry, NEV≤0.
IFAIL=3
On entry, NCV≤NEV or NCV>N.
IFAIL=4
On entry, LICOMM<140 and LICOMM≠-1.
IFAIL=5
On entry, LCOMM<3×N+NCV×NCV+8×NCV+60 and LCOMM≠-1.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

Not applicable.

8 Parallelism and Performance

F12FAF is not threaded in any implementation.

9 Further Comments

None.

10 Example

This example solves Ax = λx in regular mode, where A is obtained from the standard central difference discretization of the Laplacian operator ∂2 u ∂x 2 + ∂2 u ∂y 2 on the unit square, with zero Dirichlet boundary conditions. Eigenvalues of smallest magnitude are selected.

10.1 Program Text

Program Text (f12fafe.f90)

10.2 Program Data

Program Data (f12fafe.d)

10.3 Program Results

Program Results (f12fafe.r)

F12 Chapter Contents
F12 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F12FBF : NAG Library, Mark 26

F12 Chapter Contents
F12 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F12FBF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.
Note: this routine uses optional parameters to define choices in the problem specification. If you wish to use default settings for all of the optional parameters, then the option setting routine F12FDF need not be called. If, however, you wish to reset some or all of the settings please refer to Section 11 in F12FDF for a detailed description of the specification of the optional parameters.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F12FBF is an iterative solver in a suite of routines consisting of F12FAF, F12FBF, F12FCF, F12FDF and F12FEF. It is used to find some of the eigenvalues (and optionally the corresponding eigenvectors) of a standard or generalized eigenvalue problem defined by real symmetric matrices.

2 Specification

SUBROUTINE F12FBF ( IREVCM, RESID, V, LDV, X, MX, NSHIFT, COMM, ICOMM, IFAIL)
INTEGER | IREVCM, LDV, NSHIFT, ICOMM(*), IFAIL
REAL (KIND=nag_wp) | RESID(*), V(LDV,*), X(*), MX(*), COMM(*)

3 Description

The suite of routines is designed to calculate some of the eigenvalues, λ , (and optionally the corresponding eigenvectors, x ) of a standard eigenvalue problem Ax = λx , or of a generalized eigenvalue problem Ax = λBx of order n , where n is large and the coefficient matrices A and B are sparse, real and symmetric. The suite can also be used to find selected eigenvalues/eigenvectors of smaller scale dense, real and symmetric problems.
F12FBF is a reverse communication routine, based on the ARPACK routine dsaupd, using the Implicitly Restarted Arnoldi iteration method, which for symmetric problems reduces to a variant of the Lanczos method. The method is described in Lehoucq and Sorensen (1996) and Lehoucq (2001) while its use within the ARPACK software is described in great detail in Lehoucq et al. (1998). An evaluation of software for computing eigenvalues of sparse symmetric matrices is provided in Lehoucq and Scott (1996). This suite of routines offers the same functionality as the ARPACK software for real symmetric problems, but the interface design is quite different in order to make the option setting clearer and to simplify the interface of F12FBF.
The setup routine F12FAF must be called before F12FBF, the reverse communication iterative solver. Options may be set for F12FBF by prior calls to the option setting routine F12FDF and a post-processing routine F12FCF must be called following a successful final exit from F12FBF. F12FEF, may be called following certain flagged, intermediate exits from F12FBF to provide additional monitoring information about the computation.
F12FBF uses reverse communication, i.e., it returns repeatedly to the calling program with the argument IREVCM (see Section 5) set to specified values which require the calling program to carry out one of the following tasks:
– | compute the matrix-vector product y = OPx , where OP is defined by the computational mode;
– | compute the matrix-vector product y = Bx ;
– | notify the completion of the computation;
– | allow the calling program to monitor the solution.
The problem type to be solved (standard or generalized), the spectrum of eigenvalues of interest, the mode used (regular, regular inverse, shifted inverse, Buckling or Cayley) and other options can all be set using the option setting routine F12FDF.

4 References

Lehoucq R B (2001) Implicitly restarted Arnoldi methods and subspace iteration SIAM Journal on Matrix Analysis and Applications 23 551–562
Lehoucq R B and Scott J A (1996) An evaluation of software for computing eigenvalues of sparse nonsymmetric matrices Preprint MCS-P547-1195 Argonne National Laboratory
Lehoucq R B and Sorensen D C (1996) Deflation techniques for an implicitly restarted Arnoldi iteration SIAM Journal on Matrix Analysis and Applications 17 789–821
Lehoucq R B, Sorensen D C and Yang C (1998) ARPACK Users' Guide: Solution of Large-scale Eigenvalue Problems with Implicitly Restarted Arnoldi Methods SIAM, Philidelphia

5 Arguments

Note: this routine uses reverse communication. Its use involves an initial entry, intermediate exits and re-entries, and a final exit, as indicated by the argument IREVCM. Between intermediate exits and re-entries, all arguments other than X, MX and COMM must remain unchanged.
1:   IREVCM – INTEGERInput/Output
On initial entry: IREVCM=0, otherwise an error condition will be raised.
On intermediate re-entry: must be unchanged from its previous exit value. Changing IREVCM to any other value between calls will result in an error.
On intermediate exit: has the following meanings.
IREVCM=-1
The calling program must compute the matrix-vector product y=OPx, where x is stored in X (by default) or in the array COMM (starting from the location given by the first element of ICOMM) when the option Pointers=YES is set in a prior call to F12FDF. The result y is returned in X (by default) or in the array COMM (starting from the location given by the second element of ICOMM) when the option Pointers=YES is set.
IREVCM=1
The calling program must compute the matrix-vector product y=OPx. This is similar to the case IREVCM=-1 except that the result of the matrix-vector product Bx (as required in some computational modes) has already been computed and is available in MX (by default) or in the array COMM (starting from the location given by the third element of ICOMM) when the option Pointers=YES is set.
IREVCM=2
The calling program must compute the matrix-vector product y=Bx, where x is stored in X and y is returned in MX (by default) or in the array COMM (starting from the location given by the second element of ICOMM) when the option Pointers=YES is set.
IREVCM=3
Compute the NSHIFT real and imaginary parts of the shifts where the real parts are to be returned in the first NSHIFT locations of the array X and the imaginary parts are to be returned in the first NSHIFT locations of the array MX. Only complex conjugate pairs of shifts may be applied and the pairs must be placed in consecutive locations. This value of IREVCM will only arise if the optional parameter Supplied Shifts is set in a prior call to F12FDF which is intended for experienced users only; the default and recommended option is to use exact shifts (see Lehoucq et al. (1998) for details and guidance on the choice of shift strategies).
IREVCM=4
Monitoring step: a call to F12FEF can now be made to return the number of Arnoldi iterations, the number of converged Ritz values, their real and imaginary parts, and the corresponding Ritz estimates.
On final exit: IREVCM=5: F12FBF has completed its tasks. The value of IFAIL determines whether the iteration has been successfully completed, or whether errors have been detected. On successful completion F12FCF must be called to return the requested eigenvalues and eigenvectors (and/or Schur vectors).
Constraint: on initial entry, IREVCM=0; on re-entry IREVCM must remain unchanged.
2:   RESID* – REAL (KIND=nag_wp) arrayInput/Output
Note: the dimension of the array RESID must be at least N (see F12FAF).
On initial entry: need not be set unless the option Initial Residual has been set in a prior call to F12FDF in which case RESID should contain an initial residual vector, possibly from a previous run.
On intermediate re-entry: must be unchanged from its previous exit. Changing RESID to any other value between calls may result in an error exit.
On intermediate exit: contains the current residual vector.
On final exit: contains the final residual vector.
3:   V LDV* – REAL (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array V must be at least max 1,NCV (see F12FAF).
On initial entry: need not be set.
On intermediate re-entry: must be unchanged from its previous exit.
On intermediate exit: contains the current set of Arnoldi basis vectors.
On final exit: contains the final set of Arnoldi basis vectors.
4:   LDV – INTEGERInput
On entry: the first dimension of the array V as declared in the (sub)program from which F12FBF is called.
Constraint: LDV≥N.
5:   X* – REAL (KIND=nag_wp) arrayInput/Output
Note: the dimension of the array X must be at least N if Pointers=NO (default) and at least 1 if Pointers=YES (see F12FAF).
On initial entry: need not be set, it is used as a convenient mechanism for accessing elements of COMM.
On intermediate re-entry: if Pointers=YES, X need not be set.
If Pointers=NO, X must contain the result of y=OPx when IREVCM returns the value -1 or +1. It must return the real parts of the computed shifts when IREVCM returns the value 3.
On intermediate exit: if Pointers=YES, X is not referenced.
If Pointers=NO, X contains the vector x when IREVCM returns the value -1 or +1.
On final exit: does not contain useful data.
6:   MX* – REAL (KIND=nag_wp) arrayInput/Output
Note: the dimension of the array MX must be at least N if Pointers=NO (default) and at least 1 if Pointers=YES (see F12FAF).
On initial entry: need not be set, it is used as a convenient mechanism for accessing elements of COMM.
On intermediate re-entry: if Pointers=YES, MX need not be set.
If Pointers=NO, MX must contain the result of y=Bx when IREVCM returns the value 2. It must return the imaginary parts of the computed shifts when IREVCM returns the value 3.
On intermediate exit: if Pointers=YES, MX is not referenced.
If Pointers=NO, MX contains the vector Bx when IREVCM returns the value +1.
On final exit: does not contain any useful data.
7:   NSHIFT – INTEGEROutput
On intermediate exit: if the option Supplied Shifts is set and IREVCM returns a value of 3, NSHIFT returns the number of complex shifts required.
8:   COMM* – REAL (KIND=nag_wp) arrayCommunication Array
Note: the dimension of the array COMM must be at least max 1,LCOMM (see F12FAF).
On initial entry: must remain unchanged following a call to the setup routine F12FAF.
On exit: contains data defining the current state of the iterative process.
9:   ICOMM* – INTEGER arrayCommunication Array
Note: the dimension of the array ICOMM must be at least max 1,LICOMM (see F12FAF).
On initial entry: must remain unchanged following a call to the setup routine F12FAF.
On exit: contains data defining the current state of the iterative process.
10:   IFAIL – INTEGERInput/Output
On initial entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, because for this routine the values of the output arguments may be useful even if IFAIL≠0 on exit, the recommended value is -1. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On intermediate exit: the value of IFAIL is meaningless and should be ignored.
On final exit: (i.e., when IREVCM=5) IFAIL=0, unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On initial entry, the maximum number of iterations ≤ 0 , the option Iteration Limit has been set to a non-positive value.
IFAIL=2
The options Generalized and Regular are incompatible.
IFAIL=3
Eigenvalues from both ends of the spectrum were requested, but the number of eigenvalues requested is one.
IFAIL=4
The option Initial Residual was selected but the starting vector held in RESID is zero.
IFAIL=5
The maximum number of iterations has been reached. Some Ritz values may have converged; a subsequent call to F12FCF will return the number of converged values and the converged values.
IFAIL=6
No shifts could be applied during a cycle of the implicitly restarted Arnoldi iteration. One possibility is to increase the size of NCV relative to NEV (see Section 5 in F12FAF for details of these arguments).
IFAIL=7
Could not build a Lanczos factorization. Consider changing NCV or NEV in the initialization routine (see Section 5 in F12FAF for details of these arguments).
IFAIL=8
Unexpected error in internal call to compute eigenvalues and corresponding error bounds of the current upper Hessenberg matrix. Please contact NAG.
IFAIL=9
Either the routine was called without an initial call to the setup routine or the communication arrays have become corrupted.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

The relative accuracy of a Ritz value, λ , is considered acceptable if its Ritz estimate ≤ Tolerance × λ . The default Tolerance used is the machine precision given by X02AJF.

8 Parallelism and Performance

F12FBF is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
F12FBF makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

None.

10 Example

For this routine two examples are presented, with a main program and two example problems given in Example 1 (EX1) and Example 2 (EX2).
Example 1 (EX1)
The example solves Ax = λx in shift-invert mode, where A is obtained from the standard central difference discretization of the one-dimensional Laplacian operator ∂2 u ∂x 2 with zero Dirichlet boundary conditions. Eigenvalues closest to the shift σ=0 are sought.
Example 2 (EX2)
This example illustrates the use of F12FBF to compute the leading terms in the singular value decomposition of a real general matrix A. The example finds a few of the largest singular values (σ) and corresponding right singular values (ν) for the matrix A by solving the symmetric problem:
AT A ν=σν .
Here A is the m by n real matrix derived from the simplest finite difference discretization of the two-dimensional kernel k s,t dt where
k s,t = s t-1 if ​0≤s≤t≤1 t s-1 if ​0≤t<s≤1 .
Note: this formulation is appropriate for the case m≥n. Reverse the rules of A and AT in the case of m<n.

10.1 Program Text

Program Text (f12fbfe.f90)

10.2 Program Data

Program Data (f12fbfe.d)

10.3 Program Results

Program Results (f12fbfe.r)

F12 Chapter Contents
F12 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F12FCF : NAG Library, Mark 26

F12 Chapter Contents
F12 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F12FCF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.
Note: this routine uses optional parameters to define choices in the problem specification. If you wish to use default settings for all of the optional parameters, then the option setting routine F12FDF need not be called. If, however, you wish to reset some or all of the settings please refer to Section 11 in F12FDF for a detailed description of the specification of the optional parameters.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F12FCF is a post-processing routine in a suite of routines which includes F12FAF, F12FBF, F12FDF and F12FEF. F12FCF must be called following a final exit from F12FBF.

2 Specification

SUBROUTINE F12FCF ( NCONV, D, Z, LDZ, SIGMA, RESID, V, LDV, COMM, ICOMM, IFAIL)
INTEGER | NCONV, LDZ, LDV, ICOMM(*), IFAIL
REAL (KIND=nag_wp) | D(*), Z(LDZ,*), SIGMA, RESID(*), V(LDV,*), COMM(*)

3 Description

The suite of routines is designed to calculate some of the eigenvalues, λ , (and optionally the corresponding eigenvectors, x ) of a standard eigenvalue problem Ax = λx , or of a generalized eigenvalue problem Ax = λBx of order n , where n is large and the coefficient matrices A and B are sparse, real and symmetric. The suite can also be used to find selected eigenvalues/eigenvectors of smaller scale dense, real and symmetric problems.
Following a call to F12FBF, F12FCF returns the converged approximations to eigenvalues and (optionally) the corresponding approximate eigenvectors and/or an orthonormal basis for the associated approximate invariant subspace. The eigenvalues (and eigenvectors) are selected from those of a standard or generalized eigenvalue problem defined by real symmetric matrices. There is negligible additional cost to obtain eigenvectors; an orthonormal basis is always computed, but there is an additional storage cost if both are requested.
F12FCF is based on the routine dseupd from the ARPACK package, which uses the Implicitly Restarted Lanczos iteration method. The method is described in Lehoucq and Sorensen (1996) and Lehoucq (2001) while its use within the ARPACK software is described in great detail in Lehoucq et al. (1998). An evaluation of software for computing eigenvalues of sparse symmetric matrices is provided in Lehoucq and Scott (1996). This suite of routines offers the same functionality as the ARPACK software for real symmetric problems, but the interface design is quite different in order to make the option setting clearer and to simplify some of the interfaces.
F12FCF, is a post-processing routine that must be called following a successful final exit from F12FBF. F12FCF uses data returned from F12FBF and options, set either by default or explicitly by calling F12FDF, to return the converged approximations to selected eigenvalues and (optionally):
– | the corresponding approximate eigenvectors;
– | an orthonormal basis for the associated approximate invariant subspace;
– | both.

4 References

Lehoucq R B (2001) Implicitly restarted Arnoldi methods and subspace iteration SIAM Journal on Matrix Analysis and Applications 23 551–562
Lehoucq R B and Scott J A (1996) An evaluation of software for computing eigenvalues of sparse nonsymmetric matrices Preprint MCS-P547-1195 Argonne National Laboratory
Lehoucq R B and Sorensen D C (1996) Deflation techniques for an implicitly restarted Arnoldi iteration SIAM Journal on Matrix Analysis and Applications 17 789–821
Lehoucq R B, Sorensen D C and Yang C (1998) ARPACK Users' Guide: Solution of Large-scale Eigenvalue Problems with Implicitly Restarted Arnoldi Methods SIAM, Philidelphia

5 Arguments

1:   NCONV – INTEGEROutput
On exit: the number of converged eigenvalues as found by F12FBF.
2:   D* – REAL (KIND=nag_wp) arrayOutput
Note: the dimension of the array D must be at least NCV (see F12FAF).
On exit: the first NCONV locations of the array D contain the converged approximate eigenvalues.
3:   Z LDZ* – REAL (KIND=nag_wp) arrayOutput
Note: the second dimension of the array Z must be at least NCV if the default option Vectors=RITZ has been selected and at least 1 if the option Vectors=NONE or SCHUR has been selected (see F12FAF).
On exit: if the default option Vectors=RITZ (see F12FDF) has been selected then Z contains the final set of eigenvectors corresponding to the eigenvalues held in D. The real eigenvector associated with an eigenvalue is stored in the corresponding column of Z.
4:   LDZ – INTEGERInput
On entry: the first dimension of the array Z as declared in the (sub)program from which F12FCF is called.
Constraints:
  • if the default option Vectors=Ritz has been selected, LDZ≥N;
  • if the option Vectors=None or Schur has been selected, LDZ≥1.
5:   SIGMA – REAL (KIND=nag_wp)Input
On entry: if one of the Shifted Inverse (see F12FDF) modes has been selected then SIGMA contains the real shift used; otherwise SIGMA is not referenced.
6:   RESID* – REAL (KIND=nag_wp) arrayInput
Note: the dimension of the array RESID must be at least N (see F12FAF).
On entry: must not be modified following a call to F12FBF since it contains data required by F12FCF.
7:   V LDV* – REAL (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array V must be at least max 1,NCV (see F12FAF).
On entry: the NCV columns of V contain the Lanczos basis vectors for OP as constructed by F12FBF.
On exit: if the option Vectors=SCHUR has been set, or the option Vectors=RITZ has been set and a separate array Z has been passed (i.e., Z does not equal V), then the first NCONV columns of V will contain approximate Schur vectors that span the desired invariant subspace.
8:   LDV – INTEGERInput
On entry: the first dimension of the array V as declared in the (sub)program from which F12FCF is called.
Constraint: LDV≥n.
9:   COMM* – REAL (KIND=nag_wp) arrayCommunication Array
Note: the dimension of the array COMM must be at least max 1,LCOMM (see F12FAF).
On initial entry: must remain unchanged from the prior call to F12FAF.
On exit: contains data on the current state of the solution.
10:   ICOMM* – INTEGER arrayCommunication Array
Note: the dimension of the array ICOMM must be at least max 1,LICOMM (see F12FAF).
On initial entry: must remain unchanged from the prior call to F12FAF.
On exit: contains data on the current state of the solution.
11:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, LDZ < max 1,N or LDZ < 1 when no vectors are required.
IFAIL=2
On entry, the option Vectors = Select was selected, but this is not yet implemented.
IFAIL=3
The number of eigenvalues found to sufficient accuracy prior to calling F12FCF, as communicated through the argument ICOMM, is zero.
IFAIL=4
The number of converged eigenvalues as calculated by F12FBF differ from the value passed to it through the argument ICOMM.
IFAIL=5
Unexpected error during calculation of a tridiagonal form: there was a failure to compute all the converged eigenvalues. Please contact NAG.
IFAIL=8
Either the routine was called out of sequence (following an initial call to the setup routine and following completion of calls to the reverse communication routine) or the communication arrays have become corrupted.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

The relative accuracy of a Ritz value, λ , is considered acceptable if its Ritz estimate ≤ Tolerance × λ . The default Tolerance used is the machine precision given by X02AJF.

8 Parallelism and Performance

F12FCF is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
F12FCF makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

None.

10 Example

This example solves Ax = λBx in regular mode, where A and B are obtained from the standard central difference discretization of the one-dimensional Laplacian operator d 2 u d x 2 on 0,1 , with zero Dirichlet boundary conditions.

10.1 Program Text

Program Text (f12fcfe.f90)

10.2 Program Data

Program Data (f12fcfe.d)

10.3 Program Results

Program Results (f12fcfe.r)

F12 Chapter Contents
F12 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F12FDF : NAG Library, Mark 26

F12 Chapter Contents
F12 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F12FDF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.
Note: this routine uses optional parameters to define choices in the problem specification. If you wish to use default settings for all of the optional parameters, then this routine need not be called. If, however, you wish to reset some or all of the settings please refer to Section 11 for a detailed description of the specification of the optional parameters.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results
▸▿ 11 Optional Parameters
11.1 Description of the Optional Parameters

1 Purpose

F12FDF is an option setting routine in a suite of routines consisting of F12FAF, F12FBF, F12FCF, F12FDF and F12FEF, and may be used to supply individual optional parameters to F12FBF and F12FCF. The initialization routine F12FAF must have been called prior to calling F12FDF.

2 Specification

SUBROUTINE F12FDF ( STR, ICOMM, COMM, IFAIL)
INTEGER | ICOMM(*), IFAIL
REAL (KIND=nag_wp) | COMM(*)
CHARACTER(*) | STR

3 Description

F12FDF may be used to supply values for optional parameters to F12FBF and F12FCF. It is only necessary to call F12FDF for those arguments whose values are to be different from their default values. One call to F12FDF sets one argument value.
Each optional parameter is defined by a single character string consisting of one or more items. The items associated with a given option must be separated by spaces, or equals signs = . Alphabetic characters may be upper or lower case. The string
'Pointers = Yes'
is an example of a string used to set an optional parameter. For each option the string contains one or more of the following items:
– | a mandatory keyword;
– | a phrase that qualifies the keyword;
– | a number that specifies an integer or real value. Such numbers may be up to 16 contiguous characters in Fortran's I, F, E or D format.
F12FDF does not have an equivalent routine from the ARPACK package which passes options by directly setting values to scalar arguments or to specific elements of array arguments. F12FDF is intended to make the passing of options more transparent and follows the same principle as the single option setting routines in Chapter E04.
The setup routine F12FAF must be called prior to the first call to F12FDF and all calls to F12FDF must precede the first call to F12FBF, the reverse communication iterative solver.
A complete list of optional parameters, their abbreviations, synonyms and default values is given in Section 11.

4 References

Lehoucq R B (2001) Implicitly restarted Arnoldi methods and subspace iteration SIAM Journal on Matrix Analysis and Applications 23 551–562
Lehoucq R B and Scott J A (1996) An evaluation of software for computing eigenvalues of sparse nonsymmetric matrices Preprint MCS-P547-1195 Argonne National Laboratory
Lehoucq R B and Sorensen D C (1996) Deflation techniques for an implicitly restarted Arnoldi iteration SIAM Journal on Matrix Analysis and Applications 17 789–821
Lehoucq R B, Sorensen D C and Yang C (1998) ARPACK Users' Guide: Solution of Large-scale Eigenvalue Problems with Implicitly Restarted Arnoldi Methods SIAM, Philidelphia

5 Arguments

1:   STR – CHARACTER(*)Input
On entry: a single valid option string (as described in Section 3 and Section 11).
2:   ICOMM* – INTEGER arrayCommunication Array
Note: the dimension of the array ICOMM must be at least max 1,LICOMM (see F12FAF).
On initial entry: must remain unchanged following a call to the setup routine F12FAF.
On exit: contains data on the current options set.
3:   COMM* – REAL (KIND=nag_wp) arrayCommunication Array
Note: the dimension of the array COMM must be at least 60.
On initial entry: must remain unchanged following a call to the setup routine F12FAF.
On exit: contains data on the current options set.
4:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
The string passed in STR contains an ambiguous keyword.
IFAIL=2
The string passed in STR contains a keyword that could not be recognized.
IFAIL=3
The string passed in STR contains a second keyword that could not be recognized.
IFAIL=4
The initialization routine F12FAF has not been called or a communication array has become corrupted.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

Not applicable.

8 Parallelism and Performance

F12FDF is not threaded in any implementation.

9 Further Comments

None.

10 Example

This example solves Ax = λBx in Shifted Inverse mode, where A and B are obtained from the standard central difference discretization of the one-dimensional Laplacian operator ∂2 u ∂x 2 on 0,1 , with zero Dirichlet boundary conditions. Data is passed to and from the reverse communication routine F12FBF using pointers to the communication array.

10.1 Program Text

Program Text (f12fdfe.f90)

10.2 Program Data

Program Data (f12fdfe.d)

10.3 Program Results

Program Results (f12fdfe.r)

11 Optional Parameters

Several optional parameters for the computational routines F12FBF and F12FCF define choices in the problem specification or the algorithm logic. In order to reduce the number of formal arguments of F12FBF and F12FCF these optional parameters have associated default values that are appropriate for most problems. Therefore, you need only specify those optional parameters whose values are to be different from their default values.
The remainder of this section can be skipped if you wish to use the default values for all optional parameters.
The following is a list of the optional parameters available. A full description of each optional parameter is provided in Section 11.1.
  • Advisory
  • Both Ends
  • Buckling
  • Cayley
  • Defaults
  • Exact Shifts
  • Generalized
  • Initial Residual
  • Iteration Limit
  • Largest Algebraic
  • Largest Magnitude
  • List
  • Monitoring
  • Nolist
  • Pointers
  • Print Level
  • Random Residual
  • Regular
  • Regular Inverse
  • Shifted Inverse
  • Smallest Algebraic
  • Smallest Magnitude
  • Standard
  • Supplied Shifts
  • Tolerance
  • Vectors
Optional parameters may be specified by calling F12FDF before a call to F12FBF, but after a call to F12FAF. One call is necessary for each optional parameter.
All optional parameters you do not specify are set to their default values. Optional parameters you do specify are unaltered by F12FBF and F12FCF (unless they define invalid values) and so remain in effect for subsequent calls unless you alter them.

11.1 Description of the Optional Parameters

For each option, we give a summary line, a description of the optional parameter and details of constraints.
The summary line contains:
  • the keywords, where the minimum abbreviation of each keyword is underlined;
  • a parameter value, where the letters a, i and r denote options that take character, integer and real values respectively;
  • the default value, where the symbol ε is a generic notation for machine precision (see X02AJF).
Keywords and character values are case and white space insensitive.
Advisory i Default = the value returned by X04ABF
The destination for advisory messages.
Defaults
This special keyword may be used to reset all optional parameters to their default values.
Exact Shifts Default
Supplied Shifts
During the Lanczos iterative process, shifts are applied internally as part of the implicit restarting scheme. The shift strategy used by default and selected by the Exact Shifts is strongly recommended over the alternative Supplied Shifts (see Lehoucq et al. (1998) for details of shift strategies).
If Exact Shifts are used then these are computed internally by the algorithm in the implicit restarting scheme.
If Supplied Shifts are used then, during the Lanczos iterative process, you must supply shifts through array arguments of F12FBF when F12FBF returns with IREVCM=3; the real and imaginary parts of the shifts are returned in X and MX respectively (or in COMM when the option Pointers=YES is set). This option should only be used if you are an experienced user since this requires some algorithmic knowledge and because more operations are usually required than for the implicit shift scheme. Details on the use of explicit shifts and further references on shift strategies are available in Lehoucq et al. (1998).
Iteration Limit i Default = 300
The limit on the number of Lanczos iterations that can be performed before F12FBF exits. If not all requested eigenvalues have converged to within Tolerance and the number of Lanczos iterations has reached this limit then F12FBF exits with an error; F12FCF can still be called subsequently to return the number of converged eigenvalues, the converged eigenvalues and, if requested, the corresponding eigenvectors.
Largest Magnitude Default
Both Ends
Largest Algebraic
Smallest Algebraic
Smallest Magnitude
The Lanczos iterative method converges on a number of eigenvalues with given properties. The default is for F12FBF to compute the eigenvalues of largest magnitude using Largest Magnitude. Alternatively, eigenvalues may be chosen which have Largest Algebraic part, Smallest Magnitude, or Smallest Algebraic part; or eigenvalues which are from Both Ends of the algebraic spectrum.
Note that these options select the eigenvalue properties for eigenvalues of OP (and B for Generalized problems), the linear operator determined by the computational mode and problem type.
Nolist Default
List
Normally each optional parameter specification is not printed to the advisory channel as it is supplied. Optional parameter List may be used to enable printing and optional parameter Nolist may be used to suppress the printing.
Monitoring i Default = -1
If i>0, monitoring information is output to channel number i during the solution of each problem; this may be the same as the Advisory channel number. The type of information produced is dependent on the value of Print Level, see the description of the optional parameter Print Level for details of the information produced. Please see X04ACF to associate a file with a given channel number.
Pointers Default = NO
During the iterative process and reverse communication calls to F12FBF, required data can be communicated to and from F12FBF in one of two ways. When Pointers=NO is selected (the default) then the array arguments X and MX are used to supply you with required data and used to return computed values back to F12FBF. For example, when IREVCM=1, F12FBF returns the vector x in X and the matrix-vector product Bx in MX and expects the result or the linear operation OP x to be returned in X.
If Pointers=YES is selected then the data is passed through sections of the array argument COMM. The section corresponding to X when Pointers=NO begins at a location given by the first element of ICOMM; similarly the section corresponding to MX begins at a location given by the second element of ICOMM. This option allows F12FBF to perform fewer copy operations on each intermediate exit and entry, but can also lead to less elegant code in the calling program.
Print Level i Default = 0
This controls the amount of printing produced by F12FDF as follows.
=0 | No output except error messages. If you want to suppress all output, set Print Level=0.
>0 | The set of selected options.
=2 | Problem and timing statistics on final exit from F12FBF.
≥5 | A single line of summary output at each Lanczos iteration.
≥10 | If Monitoring>0, Monitoring is set, then at each iteration, the length and additional steps of the current Lanczos factorization and the number of converged Ritz values; during re-orthogonalization, the norm of initial/restarted starting vector; on a final Lanczos iteration, the number of update iterations taken, the number of converged eigenvalues, the converged eigenvalues and their Ritz estimates.
≥20 | Problem and timing statistics on final exit from F12FBF. If Monitoring>0, Monitoring is set, then at each iteration, the number of shifts being applied, the eigenvalues and estimates of the symmetric tridiagonal matrix H, the size of the Lanczos basis, the wanted Ritz values and associated Ritz estimates and the shifts applied; vector norms prior to and following re-orthogonalization.
≥30 | If Monitoring>0, Monitoring is set, then on final iteration, the norm of the residual; when computing the Schur form, the eigenvalues and Ritz estimates both before and after sorting; for each iteration, the norm of residual for compressed factorization and the symmetric tridiagonal matrix H; during re-orthogonalization, the initial/restarted starting vector; during the Lanczos iteration loop, a restart is flagged and the number of the residual requiring iterative refinement; while applying shifts, some indices.
≥40 | If Monitoring>0, Monitoring is set, then during the Lanczos iteration loop, the Lanczos vector number and norm of the current residual; while applying shifts, key measures of progress and the order of H; while computing eigenvalues of H, the last rows of the Schur and eigenvector matrices; when computing implicit shifts, the eigenvalues and Ritz estimates of H.
≥50 | If Monitoring is set, then during Lanczos iteration loop: norms of key components and the active column of H, norms of residuals during iterative refinement, the final symmetric tridiagonal matrix H; while applying shifts: number of shifts, shift values, block indices, updated tridiagonal matrix H; while computing eigenvalues of H: the diagonals of H, the computed eigenvalues and Ritz estimates.
Note that setting Print Level≥30 can result in very lengthy Monitoring output.
Note that setting Print Level ≥ 30 can result in very lengthy Monitoring output.
Random Residual Default
Initial Residual
To begin the Lanczos iterative process, F12FBF requires an initial residual vector. By default F12FBF provides its own random initial residual vector; this option can also be set using optional parameter Random Residual. Alternatively, you can supply an initial residual vector (perhaps from a previous computation) to F12FBF through the array argument RESID; this option can be set using optional parameter Initial Residual.
Regular Default
Regular Inverse
Shifted Inverse
Buckling
Cayley
These options define the computational mode which in turn defines the form of operation OP x to be performed when F12FBF returns with IREVCM=-1 or 1 and the matrix-vector product Bx when F12FBF returns with IREVCM=2.
Given a Standard eigenvalue problem in the form Ax=λx then the following modes are available with the appropriate operator OP x.
Regular | OP=A
Shifted Inverse | OP=A-σI-1 where σ is real
Given a Generalized eigenvalue problem in the form Ax=λBx then the following modes are available with the appropriate operator OP x.
Regular Inverse | OP=B-1 A
Shifted Inverse | OP=A-σB-1 B, where σ is real
Buckling | OP=B-σA-1 A, where σ is real
Cayley | OP=A-σB-1 A+σB, where σ is real
Standard Default
Generalized
The problem to be solved is either a standard eigenvalue problem, Ax=λx, or a generalized eigenvalue problem, Ax=λBx. The optional parameter Standard should be used when a standard eigenvalue problem is being solved and the optional parameter Generalized should be used when a generalized eigenvalue problem is being solved.
Tolerance r Default = ε
An approximate eigenvalue has deemed to have converged when the corresponding Ritz estimate is within Tolerance relative to the magnitude of the eigenvalue.
Vectors Default = RITZ
The routine F12FCF can optionally compute the Schur vectors and/or the eigenvectors corresponding to the converged eigenvalues. To turn off computation of any vectors the option Vectors=NONE should be set. To compute only the Schur vectors (at very little extra cost), the option Vectors=SCHUR should be set and these will be returned in the array argument V of F12FCF. To compute the eigenvectors (Ritz vectors) corresponding to the eigenvalue estimates, the option Vectors=RITZ should be set and these will be returned in the array argument Z of F12FCF, if Z is set equal to V (as in Section 10) then the Schur vectors in V are overwritten by the eigenvectors computed by F12FCF.
F12 Chapter Contents
F12 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F12FEF : NAG Library, Mark 26

F12 Chapter Contents
F12 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F12FEF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.
Note: this routine uses optional parameters to define choices in the problem specification. If you wish to use default settings for all of the optional parameters, then the option setting routine F12FDF need not be called. If, however, you wish to reset some or all of the settings please refer to Section 11 in F12FDF for a detailed description of the specification of the optional parameters.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F12FEF can be used to return additional monitoring information during computation. It is in a suite of routines which includes F12FAF, F12FBF, F12FCF and F12FDF.

2 Specification

SUBROUTINE F12FEF ( NITER, NCONV, RITZ, RZEST, ICOMM, COMM)
INTEGER | NITER, NCONV, ICOMM(*)
REAL (KIND=nag_wp) | RITZ(*), RZEST(*), COMM(*)

3 Description

The suite of routines is designed to calculate some of the eigenvalues, λ , (and optionally the corresponding eigenvectors, x ) of a standard eigenvalue problem Ax = λx , or of a generalized eigenvalue problem Ax = λBx of order n , where n is large and the coefficient matrices A and B are sparse, real and symmetric. The suite can also be used to find selected eigenvalues/eigenvectors of smaller scale dense, real and symmetric problems.
On an intermediate exit from F12FBF with IREVCM = 4 , F12FEF may be called to return monitoring information on the progress of the Arnoldi iterative process. The information returned by F12FEF is:
– | the number of the current Arnoldi iteration;
– | the number of converged eigenvalues at this point;
– | the real and imaginary parts of the converged eigenvalues;
– | the error bounds on the converged eigenvalues.
F12FEF does not have an equivalent routine from the ARPACK package which prints various levels of detail of monitoring information through an output channel controlled via an argument value (see Lehoucq et al. (1998) for details of ARPACK routines). F12FEF should not be called at any time other than immediately following an IREVCM = 4 return from F12FBF.

4 References

Lehoucq R B (2001) Implicitly restarted Arnoldi methods and subspace iteration SIAM Journal on Matrix Analysis and Applications 23 551–562
Lehoucq R B and Scott J A (1996) An evaluation of software for computing eigenvalues of sparse nonsymmetric matrices Preprint MCS-P547-1195 Argonne National Laboratory
Lehoucq R B and Sorensen D C (1996) Deflation techniques for an implicitly restarted Arnoldi iteration SIAM Journal on Matrix Analysis and Applications 17 789–821
Lehoucq R B, Sorensen D C and Yang C (1998) ARPACK Users' Guide: Solution of Large-scale Eigenvalue Problems with Implicitly Restarted Arnoldi Methods SIAM, Philidelphia

5 Arguments

1:   NITER – INTEGEROutput
On exit: the number of the current Arnoldi iteration.
2:   NCONV – INTEGEROutput
On exit: the number of converged eigenvalues so far.
3:   RITZ* – REAL (KIND=nag_wp) arrayOutput
Note: the dimension of the array RITZ must be at least NCV (see F12FAF).
On exit: the first NCONV locations of the array RITZ contain the real converged approximate eigenvalues.
4:   RZEST* – REAL (KIND=nag_wp) arrayOutput
Note: the dimension of the array RZEST must be at least NCV (see F12FAF).
On exit: the first NCONV locations of the array RZEST contain the Ritz estimates (error bounds) on the real NCONV converged approximate eigenvalues.
5:   ICOMM* – INTEGER arrayCommunication Array
Note: the dimension of the array ICOMM must be at least max 1,LICOMM, where LICOMM is passed to the setup routine (see F12FAF).
On entry: the array ICOMM output by the preceding call to F12FBF.
6:   COMM* – REAL (KIND=nag_wp) arrayCommunication Array
Note: the dimension of the array COMM must be at least max 1,LCOMM, where LCOMM is passed to the setup routine (see F12FAF).
On entry: the array COMM output by the preceding call to F12FBF.

6 Error Indicators and Warnings

None.

7 Accuracy

A Ritz value, λ , is deemed to have converged if its Ritz estimate ≤ Tolerance × λ . The default Tolerance used is the machine precision given by X02AJF.

8 Parallelism and Performance

F12FEF is not threaded in any implementation.

9 Further Comments

None.

10 Example

This example solves Kx = λ KG x using the Buckling option (see F12FDF, where K and KG are obtained by the finite element method applied to the one-dimensional discrete Laplacian operator ∂2 u ∂x 2 on 0,1 , with zero Dirichlet boundary conditions using piecewise linear elements. The shift, σ , is a real number, and the operator used in the Buckling iterative process is OP = inv K - σ KG × K and B = K .

10.1 Program Text

Program Text (f12fefe.f90)

10.2 Program Data

Program Data (f12fefe.d)

10.3 Program Results

Program Results (f12fefe.r)

F12 Chapter Contents
F12 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F12FFF : NAG Library, Mark 26

F12 Chapter Contents
F12 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F12FFF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
10 Example

1 Purpose

F12FFF is a setup routine for F12FGF which can be used to find some eigenvalues (and optionally the corresponding eigenvectors) of a standard or generalized eigenvalue problem defined by real, banded, symmetric matrices. The banded matrix must be stored using the LAPACK storage format for real banded nonsymmetric matrices.

2 Specification

SUBROUTINE F12FFF ( N, NEV, NCV, ICOMM, LICOMM, COMM, LCOMM, IFAIL)
INTEGER | N, NEV, NCV, ICOMM(max(1,LICOMM)), LICOMM, LCOMM, IFAIL
REAL (KIND=nag_wp) | COMM(max(1,LCOMM))

3 Description

The pair of routines F12FFF and F12FGF together with the option setting routine F12FDF are designed to calculate some of the eigenvalues, λ , (and optionally the corresponding eigenvectors, x ) of a standard eigenvalue problem Ax = λx , or of a generalized eigenvalue problem Ax = λBx of order n , where n is large and the coefficient matrices A and B are banded real and symmetric.
F12FFF is a setup routine which must be called before the option setting routine F12FDF and the solver routine F12FGF. Internally, F12FGF makes calls to F12FBF and F12FCF; the routine documents for F12FBF and F12FCF should be consulted for details of the algorithm used.
This setup routine initializes the communication arrays, sets (to their default values) all options that can be set by you via the option setting routine F12FDF, and checks that the lengths of the communication arrays as passed by you are of sufficient length. For details of the options available and how to set them, see Section 11.1 in F12FDF.

4 References

Lehoucq R B (2001) Implicitly restarted Arnoldi methods and subspace iteration SIAM Journal on Matrix Analysis and Applications 23 551–562
Lehoucq R B and Scott J A (1996) An evaluation of software for computing eigenvalues of sparse nonsymmetric matrices Preprint MCS-P547-1195 Argonne National Laboratory
Lehoucq R B and Sorensen D C (1996) Deflation techniques for an implicitly restarted Arnoldi iteration SIAM Journal on Matrix Analysis and Applications 17 789–821
Lehoucq R B, Sorensen D C and Yang C (1998) ARPACK Users' Guide: Solution of Large-scale Eigenvalue Problems with Implicitly Restarted Arnoldi Methods SIAM, Philidelphia

5 Arguments

1:   N – INTEGERInput
On entry: the order of the matrix A (and the order of the matrix B for the generalized problem) that defines the eigenvalue problem.
Constraint: N>0.
2:   NEV – INTEGERInput
On entry: the number of eigenvalues to be computed.
Constraint: 0<NEV<N-1.
3:   NCV – INTEGERInput
On entry: the number of Lanczos basis vectors to use during the computation.
At present there is no a priori analysis to guide the selection of NCV relative to NEV. However, it is recommended that NCV≥2×NEV+1. If many problems of the same type are to be solved, you should experiment with increasing NCV while keeping NEV fixed for a given test problem. This will usually decrease the required number of matrix-vector operations but it also increases the work and storage required to maintain the orthogonal basis vectors. The optimal ‘cross-over’ with respect to CPU time is problem dependent and must be determined empirically.
Constraint: NEV<NCV≤N.
4:   ICOMM max 1,LICOMM – INTEGER arrayCommunication Array
On exit: contains data to be communicated to F12FGF.
5:   LICOMM – INTEGERInput
On entry: the dimension of the array ICOMM as declared in the (sub)program from which F12FFF is called.
If LICOMM=-1, a workspace query is assumed and the routine only calculates the required dimensions of ICOMM and COMM, which it returns in ICOMM 1 and COMM 1 respectively.
Constraint: LICOMM≥140 ​ or ​ LICOMM=-1.
6:   COMM max 1,LCOMM – REAL (KIND=nag_wp) arrayCommunication Array
On exit: contains data to be communicated to F12FGF.
7:   LCOMM – INTEGERInput
On entry: the dimension of the array COMM as declared in the (sub)program from which F12FFF is called.
If LCOMM=-1, a workspace query is assumed and the routine only calculates the dimensions of ICOMM and COMM required by F12FGF, which it returns in ICOMM 1 and COMM 1 respectively.
Constraint: LCOMM≥60 ​ or ​ LCOMM=-1.
8:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, N≤0.
IFAIL=2
On entry, NEV≤0.
IFAIL=3
On entry, NCV≤NEV or NCV>N.
IFAIL=4
On entry, LICOMM<140 and LICOMM≠-1.
IFAIL=5
On entry, LCOMM<60 and LCOMM≠-1.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

Not applicable.

8 Parallelism and Performance

F12FFF is not threaded in any implementation.

9 Further Comments

None.

10 Example

The use of F12FFF is illustrated by the example program of F12FGF (see Section 10 in F12FGF).
F12 Chapter Contents
F12 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F12FGF : NAG Library, Mark 26

F12 Chapter Contents
F12 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F12FGF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.
Note: this routine uses optional parameters to define choices in the problem specification. If you wish to use default settings for all of the optional parameters, then the option setting routine F12FDF need not be called. If, however, you wish to reset some or all of the settings please refer to Section 11 in F12FDF for a detailed description of the specification of the optional parameters.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F12FGF is the main solver routine in a suite of routines which includes F12FDF and F12FFF. F12FGF must be called following an initial call to F12FFF and following any calls to F12FDF.
F12FGF returns approximations to selected eigenvalues, and (optionally) the corresponding eigenvectors, of a standard or generalized eigenvalue problem defined by real banded symmetric matrices. The banded matrix must be stored using the LAPACK storage format for real banded nonsymmetric matrices.

2 Specification

SUBROUTINE F12FGF ( KL, KU, AB, LDAB, MB, LDMB, SIGMA, NCONV, D, Z, LDZ, RESID, V, LDV, COMM, ICOMM, IFAIL)
INTEGER | KL, KU, LDAB, LDMB, NCONV, LDZ, LDV, ICOMM(*), IFAIL
REAL (KIND=nag_wp) | AB(LDAB,*), MB(LDMB,*), SIGMA, D(*), Z(LDZ,*), RESID(*), V(LDV,*), COMM(*)

3 Description

The suite of routines is designed to calculate some of the eigenvalues, λ , (and optionally the corresponding eigenvectors, x ) of a standard eigenvalue problem Ax = λx , or of a generalized eigenvalue problem Ax = λBx of order n , where n is large and the coefficient matrices A and B are banded, real and symmetric.
Following a call to the initialization routine F12FFF, F12FGF returns the converged approximations to eigenvalues and (optionally) the corresponding approximate eigenvectors and/or an orthonormal basis for the associated approximate invariant subspace. The eigenvalues (and eigenvectors) are selected from those of a standard or generalized eigenvalue problem defined by real banded symmetric matrices. There is negligible additional computational cost to obtain eigenvectors; an orthonormal basis is always computed, but there is an additional storage cost if both are requested.
The banded matrices A and B must be stored using the LAPACK storage format for banded nonsymmetric matrices; please refer to Section 3.3.2 in the F07 Chapter Introduction for details on this storage format.
F12FGF is based on the banded driver routines dsbdr1 to dsbdr6 from the ARPACK package, which uses the Implicitly Restarted Lanczos iteration method. The method is described in Lehoucq and Sorensen (1996) and Lehoucq (2001) while its use within the ARPACK software is described in great detail in Lehoucq et al. (1998). This suite of routines offers the same functionality as the ARPACK banded driver software for real symmetric problems, but the interface design is quite different in order to make the option setting clearer and to combine the different drivers into a general purpose routine.
F12FGF, is a general purpose direct communication routine that must be called following initialization by F12FFF. F12FGF uses options, set either by default or explicitly by calling F12FDF, to return the converged approximations to selected eigenvalues and (optionally):
– | the corresponding approximate eigenvectors;
– | an orthonormal basis for the associated approximate invariant subspace;
– | both.

4 References

Lehoucq R B (2001) Implicitly restarted Arnoldi methods and subspace iteration SIAM Journal on Matrix Analysis and Applications 23 551–562
Lehoucq R B and Scott J A (1996) An evaluation of software for computing eigenvalues of sparse nonsymmetric matrices Preprint MCS-P547-1195 Argonne National Laboratory
Lehoucq R B and Sorensen D C (1996) Deflation techniques for an implicitly restarted Arnoldi iteration SIAM Journal on Matrix Analysis and Applications 17 789–821
Lehoucq R B, Sorensen D C and Yang C (1998) ARPACK Users' Guide: Solution of Large-scale Eigenvalue Problems with Implicitly Restarted Arnoldi Methods SIAM, Philidelphia

5 Arguments

1:   KL – INTEGERInput
On entry: the number of subdiagonals of the matrices A and B.
Constraint: KL≥0.
2:   KU – INTEGERInput
On entry: the number of superdiagonals of the matrices A and B. Since A and B are symmetric, the normal case is KU=KL.
Constraint: KU≥0.
3:   AB LDAB* – REAL (KIND=nag_wp) arrayInput
Note: the second dimension of the array AB must be at least max 1,N (see F12FFF).
On entry: must contain the matrix A in LAPACK banded storage format for nonsymmetric matrices (see Section 3.3.4 in the F07 Chapter Introduction).
4:   LDAB – INTEGERInput
On entry: the first dimension of the array AB as declared in the (sub)program from which F12FGF is called.
Constraint: LDAB ≥ 2×KL+KU+1.
5:   MB LDMB* – REAL (KIND=nag_wp) arrayInput
Note: the second dimension of the array MB must be at least max 1,N (see F12FFF).
On entry: must contain the matrix B in LAPACK banded storage format for nonsymmetric matrices (see Section 3.3.4 in the F07 Chapter Introduction).
6:   LDMB – INTEGERInput
On entry: the first dimension of the array MB as declared in the (sub)program from which F12FGF is called.
Constraint: LDMB≥2×KL+KU+1.
7:   SIGMA – REAL (KIND=nag_wp)Input
On entry: if one of the Shifted Inverse (see F12FDF) modes has been selected then SIGMA contains the real shift used; otherwise SIGMA is not referenced.
8:   NCONV – INTEGEROutput
On exit: the number of converged eigenvalues.
9:   D* – REAL (KIND=nag_wp) arrayOutput
Note: the dimension of the array D must be at least NCV (see F12FFF).
On exit: the first NCONV locations of the array D contain the converged approximate eigenvalues.
10:   Z LDZ* – REAL (KIND=nag_wp) arrayOutput
Note: the second dimension of the array Z must be at least NCV+1 if the default option Vectors=RITZ has been selected and at least 1 if the option Vectors=NONE or SCHUR has been selected (see F12FFF).
On exit: if the default option Vectors=RITZ (see F12FDF) has been selected then Z contains the final set of eigenvectors corresponding to the eigenvalues held in D. The real eigenvector associated with eigenvalue i-1, for i=1,2,…,NCONV, is stored in the ith column of Z.
11:   LDZ – INTEGERInput
On entry: the first dimension of the array Z as declared in the (sub)program from which F12FGF is called.
Constraints:
  • if the default option Vectors=Ritz has been selected, LDZ≥N;
  • if the option Vectors=None or Schur has been selected, LDZ≥1.
12:   RESID* – REAL (KIND=nag_wp) arrayInput/Output
Note: the dimension of the array RESID must be at least N (see F12FFF).
On entry: need not be set unless the option Initial Residual has been set in a prior call to F12FDF in which case RESID must contain an initial residual vector.
On exit: contains the final residual vector.
13:   V LDV* – REAL (KIND=nag_wp) arrayOutput
Note: the second dimension of the array V must be at least max 1,NCV (see F12FFF).
On exit: if the option Vectors (see F12FDF) has been set to Schur or Ritz and a separate array Z has been passed then the first NCONV×n elements of V will contain approximate Schur vectors that span the desired invariant subspace.
The jth Schur vector is stored in the ith column of V.
14:   LDV – INTEGERInput
On entry: the first dimension of the array V as declared in the (sub)program from which F12FGF is called.
Constraint: LDV≥n.
15:   COMM* – REAL (KIND=nag_wp) arrayCommunication Array
Note: the dimension of the array COMM must be at least max 1,LCOMM (see F12FFF).
On initial entry: must remain unchanged from the prior call to F12FDF and F12FFF.
On exit: contains no useful information.
16:   ICOMM* – INTEGER arrayCommunication Array
Note: the dimension of the array ICOMM must be at least max 1,LICOMM (see F12FFF).
On initial entry: must remain unchanged from the prior call to F12FBF and F12FDF.
On exit: contains no useful information.
17:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, KL < 0 .
IFAIL=2
On entry, KU < 0 .
IFAIL=3
On entry, LDAB < 2×KL+KU+1 .
IFAIL=4
Iteration Limit < 0 .
IFAIL=5
The options Generalized and Regular are incompatible.
IFAIL=6
Eigenvalues from Both Ends of the spectrum were requested, but only one eigenvalue (NEV) is requested.
IFAIL=7
The Initial Residual was selected but the starting vector held in RESID is zero.
IFAIL=8
On entry, LDZ < max 1,N or LDZ < 1 when no vectors are required.
IFAIL=9
On entry, the option Vectors = Select was selected, but this is not yet implemented.
IFAIL=10
The number of eigenvalues found to sufficient accuracy is zero.
IFAIL=11
Could not build a Lanczos factorization. Consider changing NCV or NEV in the initialization routine (see Section 5 in F12FAF for details of these arguments).
IFAIL=12
Unexpected error in internal call to compute eigenvalues and corresponding error bounds of the current symmetric tridiagonal matrix. Please contact NAG.
IFAIL=13
Unexpected error during calculation of a real Schur form: there was a failure to compute all the converged eigenvalues. Please contact NAG.
IFAIL=14
Failure during internal factorization of real banded matrix. Please contact NAG.
IFAIL=15
Failure during internal solution of real banded system. Please contact NAG.
IFAIL=16
The maximum number of iterations has been reached. Some Ritz values may have converged; NCONV returns the number of converged values.
IFAIL=17
No shifts could be applied during a cycle of the implicitly restarted Lanczos iteration. One possibility is to increase the size of NCV relative to NEV (see Section 5 in F12FFF for details of these arguments).
IFAIL=18
Either an initial call to the setup routine has not been made or the communication arrays have become corrupted.
IFAIL=19
The routine was unable to dynamically allocate sufficient internal workspace. Please contact NAG.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

The relative accuracy of a Ritz value, λ , is considered acceptable if its Ritz estimate ≤ Tolerance × λ . The default Tolerance used is the machine precision given by X02AJF.

8 Parallelism and Performance

F12FGF is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
F12FGF makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

None.

10 Example

This example solves Ax = λx in regular mode, where A is obtained from the standard central difference discretization of the two-dimensional convection-diffusion operator d 2 u d x 2 + d 2 u d y 2 = ρ du dx on the unit square with zero Dirichlet boundary conditions. A is stored in LAPACK banded storage format.

10.1 Program Text

Program Text (f12fgfe.f90)

10.2 Program Data

Program Data (f12fgfe.d)

10.3 Program Results

Program Results (f12fgfe.r)

F12 Chapter Contents
F12 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F12 Chapter Introduction : NAG Library, Mark 26

F12 Chapter Contents
NAG Library Manual

NAG Library Chapter Introduction

F12 – Large Scale Eigenproblems

▸▿ Contents

1 Scope of the Chapter
▸▿ 2 Background to the Problems
2.1 Sparse Matrices and their Storage
2.2 Symmetric Eigenvalue Problems
2.3 Generalized Symmetric-definite Eigenvalue Problems
2.4 Nonsymmetric Eigenvalue Problems
2.5 Generalized Nonsymmetric Eigenvalue Problem
2.6 The Singular Value Decomposition
2.7 Iterative Methods
▸▿ 3 Recommendations on Choice and Use of Available Routines
3.1 Types of Routine Available
3.2 Iterative Methods for Real Nonsymmetric and Complex Eigenvalue Problems
3.3 Iterative Methods for Real Symmetric Eigenvalue Problems
3.4 Iterative Methods for Singular Value Decomposition
3.5 Alternative Methods
▸▿ 4 General Use of Routines
4.1 Naming Conventions
▸▿ 4.2 Shift and Invert Spectral Transformations
4.2.1 B is Hermitian positive definite
4.2.2 B is not Hermitian positive semidefinite
▸▿ 4.3 Reverse Communication and Shift-invert Modes
4.3.1 Shift and invert on a generalized eigenproblem
4.3.2 Using the computational modes
4.3.3 Computational modes for real symmetric problems
4.3.4 Computational modes for non-Hermitian problems
4.3.5 Post processing
4.3.6 Solution monitoring and printing
5 Functionality Index
6 Auxiliary Routines Associated with Library Routine Arguments
7 Routines Withdrawn or Scheduled for Withdrawal
8 References

1 Scope of the Chapter

This chapter provides routines for computing some eigenvalues and eigenvectors of large-scale (sparse) standard and generalized eigenvalue problems. It provides routines for:
  • solution of symmetric eigenvalue problems;
  • solution of nonsymmetric eigenvalue problems;
  • solution of generalized symmetric-definite eigenvalue problems;
  • solution of generalized nonsymmetric eigenvalue problems;
  • partial singular value decomposition.
Routines are provided for both real and complex data.
The routines in this chapter have all been derived from the ARPACK software suite (see Lehoucq et al. (1998)), a collection of Fortran 77 subroutines designed to solve large scale eigenvalue problems. The interfaces provided in this chapter have been chosen to combine ease of use with the flexibility of the original ARPACK software. The underlying iterative methods and algorithms remain essentially the same as those in ARPACK and are described fully in Lehoucq et al. (1998).
The algorithms used are based upon an algorithmic variant of the Arnoldi process called the Implicitly Restarted Arnoldi Method. For symmetric matrices, this reduces to a variant of the Lanczos process called the Implicitly Restarted Lanczos Method. These variants may be viewed as a synthesis of the Arnoldi/Lanczos process with the Implicitly Shifted QR technique that is suitable for large scale problems. For many standard problems, a matrix factorization is not required. Only the action of the matrix on a vector is needed.

2 Background to the Problems

This section is only a brief introduction to the solution of large-scale eigenvalue problems. For a more detailed discussion see, for example, Saad (1992) or Lehoucq (1995) in addition to Lehoucq et al. (1998). The basic factorization techniques and definitions of terms used for the different problem types are given in Section 2 in the F08 Chapter Introduction.

2.1 Sparse Matrices and their Storage

A matrix A may be described as sparse if the number of zero elements is so large that it is worthwhile using algorithms which avoid computations involving zero elements.
If A is sparse, and the chosen algorithm requires the matrix coefficients to be stored, a significant saving in storage can often be made by storing only the nonzero elements. A number of different formats may be used to represent sparse matrices economically. These differ according to the amount of storage required, the amount of indirect addressing required for fundamental operations such as matrix-vector products, and their suitability for vector and/or parallel architectures. For a survey of some of these storage formats see Barrett et al. (1994).
Most of the routines in this chapter have been designed to be independent of the matrix storage format. This allows you to choose your own preferred format, or to avoid storing the matrix altogether. Other routines are general purpose, which are easier to use, but are based on fixed storage formats. One such format is currently provided. This is the banded coordinate storage format as used in Chapters F07 and F08 (LAPACK) for storing general banded matrices.

2.2 Symmetric Eigenvalue Problems

The symmetric eigenvalue problem is to find the eigenvalues, λ , and corresponding eigenvectors, z ≠ 0 , such that
A z = λ z ,   A = AT ,   where ​ A ​ is real.
For the Hermitian eigenvalue problem we have
A z = λ z ,   A = AH ,   where ​ A ​ is complex.
For both problems the eigenvalues λ are real.
The basic task of the symmetric eigenproblem routines is to compute some of the values of λ and, optionally, corresponding vectors z for a given matrix A . For example, we may wish to obtain the first ten eigenvalues of largest magnitude, of a large sparse matrix A .

2.3 Generalized Symmetric-definite Eigenvalue Problems

This section is concerned with the solution of the generalized eigenvalue problems A z = λ B z , A B z = λ z , and B A z = λ z , where A and B are real symmetric or complex Hermitian and B is positive definite. Each of these problems can be reduced to a standard symmetric eigenvalue problem, using a Cholesky factorization of B as either B = L LT or B = UT U ( L LH or UH U in the Hermitian case).
With B = L LT , we have
A z = λ B z ⇒ L-1 A L-T LT z = λ LT z .
Hence the eigenvalues of A z = λ B z are those of C y = λ y , where C is the symmetric matrix C = L-1 A L-T and y = LT z . In the complex, case C is Hermitian with C = L-1 A L-H and y = LH z .
The basic task of the generalized symmetric eigenproblem routines is to compute some of the values of λ and, optionally, corresponding vectors z for a given matrix A . For example, we may wish to obtain the first ten eigenvalues of largest magnitude, of a large sparse matrix pair A and B .

2.4 Nonsymmetric Eigenvalue Problems

The nonsymmetric eigenvalue problem is to find the eigenvalues, λ , and corresponding eigenvectors, v ≠ 0 , such that
A v = λ v .
More precisely, a vector v as just defined is called a right eigenvector of A , and a vector u ≠ 0 satisfying
uT A = λ uT   uH A = λ uH   when ​ u ​ is complex
is called a left eigenvector of A .
A real matrix A may have complex eigenvalues, occurring as complex conjugate pairs.
This problem can be solved via the Schur factorization of A , defined in the real case as
A = ZT ZT ,
where Z is an orthogonal matrix and T is an upper quasi-triangular matrix with 1 by 1 and 2 by 2 diagonal blocks, the 2 by 2 blocks corresponding to complex conjugate pairs of eigenvalues of A . In the complex case, the Schur factorization is
A = Z T ZH ,
where Z is unitary and T is a complex upper triangular matrix.
The columns of Z are called the Schur vectors. For each k ( 1 ≤ k ≤ n ), the first k columns of Z form an orthonormal basis for the invariant subspace corresponding to the first k eigenvalues on the diagonal of T . Because this basis is orthonormal, it is preferable in many applications to compute Schur vectors rather than eigenvectors. It is possible to order the Schur factorization so that any desired set of k eigenvalues occupy the k leading positions on the diagonal of T .
The two basic tasks of the nonsymmetric eigenvalue routines are to compute, for a given matrix A , some values of λ and, if desired, their associated right eigenvectors v , and the Schur factorization.

2.5 Generalized Nonsymmetric Eigenvalue Problem

The generalized nonsymmetric eigenvalue problem is to find the eigenvalues, λ , and corresponding eigenvectors, v ≠ 0 , such that
A v = λ B v ,   A B v = λ v ,  and   B A v = λ v .
More precisely, a vector v as just defined is called a right eigenvector of the matrix pair A,B , and a vector u ≠ 0 satisfying
uT A = λ uT B   uH A = λ uH B ​ when ​ u ​ is complex
is called a left eigenvector of the matrix pair A,B .

2.6 The Singular Value Decomposition

The singular value decomposition (SVD) of an m by n matrix A is given by
A=UΣ VT,  A=UΣ VH in the complex case
where U and V are orthogonal (unitary) and Σ is an m by n diagonal matrix with real diagonal elements, σi, such that
σ 1≥σ 2≥⋯≥σ min m,n≥0.
The σi are the singular values of A and the first min m,n columns of U and V are the left and right singular vectors of A. The singular values and singular vectors satisfy
A vi = σi ui   and   AT ui = σi vi   or ​ AH ui = σi vi   so that   AT A ui = σi 2 ui   ( AH A ui = σi 2 ui )
where ui and vi are the ith columns of U and V respectively.
Thus selected singular values and the corresponding right singular vectors may be computed by finding eigenvalues and eigenvectors for the symmetric matrix AT A (or the Hermitian matrix AH A if A is complex).
An alternative approach is to use the relationship
0 A AT 0 ​ ​ U V = U V Σ
and thus compute selected singular values and vectors via the symmetric matrix
C = 0 A AT 0 ​   ​ C = 0 A AH 0 ​ if ​ A ​ is complex .
In many applications, one is interested in computing a few (say k) of the largest singular values and corresponding vectors. If Uk, Vk denote the leading k columns of U and V respectively, and if Σ k denotes the leading principal submatrix of Σ, then
Ak ≡ Uk Σ k VT k   (or ​ Uk Σ k VH k )
is the best rank-k approximation to A in both the 2-norm and the Frobenius norm. Often a very small k will suffice to approximate important features of the original A or to approximately solve least squares problems involving A.

2.7 Iterative Methods

Iterative methods for the solution of the standard eigenproblem
A x = λ x (1)
approach the solution through a sequence of approximations until some user-specified termination criterion is met or until some predefined maximum number of iterations has been reached. The number of iterations required for convergence is not generally known in advance, as it depends on the accuracy required, and on the matrix A , its sparsity pattern, conditioning and eigenvalue spectrum.

3 Recommendations on Choice and Use of Available Routines

3.1 Types of Routine Available

The routines available in this chapter divide essentially into three suites of basic reverse communication routines and some general purpose routines for banded systems.
Basic routines are grouped in suites of five, and implement the underlying iterative method. Each suite comprises a setup routine, an options setting routine, a solver routine, a routine to return additional monitoring information and a post-processing routine. The solver routine is independent of the matrix storage format (indeed the matrix need not be stored at all) and the type of preconditioner. It uses reverse communication (see Section 3.3.3 in How to Use the NAG Library and its Documentation for further information), i.e., it returns repeatedly to the calling program with the argument IREVCM set to specified values which require the calling program to carry out a specific task (either to compute a matrix-vector product or to solve the preconditioning equation), to signal the completion of the computation or to allow the calling program to monitor the solution. Reverse communication has the following advantages:
(i) | Maximum flexibility in the representation and storage of sparse matrices. All matrix operations are performed outside the solver routine, thereby avoiding the need for a complicated interface with enough flexibility to cope with all types of storage schemes and sparsity patterns. This also applies to preconditioners.
(ii) | Enhanced user interaction: you can closely monitor the solution and tidy or immediate termination can be requested. This is useful, for example, when alternative termination criteria are to be employed or in case of failure of the external routines used to perform matrix operations.
At present there are suites of basic routines for real symmetric and nonsymmetric systems, and for complex systems.
General purpose routines call basic routines in order to provide easy-to-use routines for particular sparse matrix storage formats. They are much less flexible than the basic routines, but do not use reverse communication, and may be suitable in many cases.
The structure of this chapter has been designed to cater for as many types of application as possible. If a general purpose routine exists which is suitable for a given application you are recommended to use it. If you then decide you need some additional flexibility it is easy to achieve this by using basic and utility routines which reproduce the algorithm used in the general purpose routine, but allow more access to algorithmic control parameters and monitoring.

3.2 Iterative Methods for Real Nonsymmetric and Complex Eigenvalue Problems

The suite of basic routines F12AAF, F12ABF, F12ACF, F12ADF and F12AEF implements the iterative solution of real nonsymmetric eigenvalue problems, finding estimates for a specified spectrum of eigenvalues. These eigenvalue estimates are often referred to as Ritz values and the error bounds obtained are referred to as the Ritz estimates. These routines allow a choice of termination criteria and many other options for specifying the problem type, allow monitoring of the solution process, and can return Ritz estimates of the calculated Ritz values of the problem A .
For complex matrices there is an equivalent suite of routines. F12ANF, F12APF, F12AQF, F12ARF and F12ASF are the basic routines which implement corresponding methods used for real nonsymmetric systems. Note that these routines are to be used for both Hermitian and non-Hermitian problems. Occasionally, when using these routines on a complex Hermitian problem, eigenvalues will be returned with small but nonzero imaginary part due to unavoidable round-off errors. These should be ignored unless they are significant with respect to the eigenvalues of largest magnitude that have been computed.
There are general purpose routines for the case where the matrices are known to be banded. In these cases an initialization routine is called first to set up default options, and the problem is solved by a single call to a solver routine. The matrices are supplied, in LAPACK banded-storage format, as arguments to the solver routine. For real general matrices these routines are F12AFF and F12AGF; and for complex matrices the pair is F12ATF and F12AUF. With each pair non-default options can be set, following a call to the initialization routine, using F12ADF for real matrices and F12ARF for complex matrices. For real matrices that can be supplied in the sparse matrix compressed column storage (CCS) format, the driver routine F02EKF is available. This routine uses routines from Chapter F12 in conjunction with direct solver routines from Chapter F11.
There is little computational penalty in using the non-Hermitian complex routines for a Hermitian problem. The only additional cost is to compute eigenvalues of a Hessenberg rather than a tridiagonal matrix. The difference in computational cost should be negligible compared to the overall cost.

3.3 Iterative Methods for Real Symmetric Eigenvalue Problems

The suite of basic routines F12FAF, F12FBF, F12FCF, F12FDF and F12FEF implement a Lanczos method for the iterative solution of the real symmetric eigenproblem.
There is a general purpose routine pair for the case where the matrices are known to be banded. In this case an initialization routine, F12FFF, is called first to set up default options, and the problem is solved by a single call to a solver routine, F12FGF. The matrices are supplied, in LAPACK banded-storage format, as arguments to F12FGF. Non-default options can be set, following a call to F12FFF, using F12FDF.

3.4 Iterative Methods for Singular Value Decomposition

The partial singular value decomposition, Ak (as defined in Section 2.6), of an m×n matrix A can be computed efficiently using routines from this chapter. For real matrices, the suite of routines listed in Section 3.3 (for symmetric problems) can be used; for complex matrices, the corresponding suite of routines for complex problems can be used; however, there are no general purpose routines for complex problems.
The driver routine F02WGF is available for computing the partial SVD of real matrices. The matrix is not supplied to F02WGF; rather, a user-defined routine argument provides the results of performing Matrix-vector products.
For both real and complex matrices, you should use the default options (see, for example, the options listed in Section 11 in F12FDF) for problem type (Standard), computational mode (Regular) and spectrum (Largest Magnitude). The operation to be performed on request by the reverse communication routine (e.g., F12FBF) is, for real matrices, to multiply the returned vector by the symmetric matrix AT A if m≥n , or by A AT if m<n. For complex matrices, the corresponding Hermitian matrices are AH A and A AH .
The right (m≥n) or left (m<n) singular vectors are returned by the post-processing routine (e.g., F12FCF). The left (or right) singular vectors can be recovered from the returned singular vectors. Providing the largest singular vectors are not multiple or tightly clustered, there should be no problem in obtaining numerically orthogonal left singular vectors from the computed right singular vectors (or vice versa).
The second example in Section 10 in F12FBF illustrates how the partial singular value decomposition of a real matrix can be performed using the suite of routines for finding some eigenvalues of a real symmetric matrix. In this case m≥n, however, the program is easily amended to perform the same task in the case m<n.
Similarly, routines in this chapter may be used to estimate the 2-norm condition number,
K 2 A = σ 1 σn .
This can be achieved by setting the option Both Ends to get the largest and smallest few singular values, then taking the ratio of largest to smallest computed singular values as your estimate.

3.5 Alternative Methods

Other routines for the solution of sparse linear eigenproblems can be found in Chapters F02 and F08. In particular, tridiagonal and band matrices are addressed in Chapter F08 whereas sparse matrices are addressed in Chapter F02.

4 General Use of Routines

This section will describe the complete structure of the reverse communication interfaces contained in this chapter. Numerous computational modes are available, including several shift-invert strategies designed to accelerate convergence. Two of the more sophisticated modes will be described in detail. The remaining ones are quite similar in principle, but require slightly different tasks to be performed with the reverse communication interface.
This chapter is structured as follows. The naming conventions used in this chapter, and the data types available are described in Section 4.1, spectral transformations are discussed in Section 4.2. Spectral transformations are usually extremely effective but there are a number of problem dependent issues that determine which one to use. In Section 4.3 we describe the reverse communication interface needed to exercise the various shift-invert options. Each shift-invert option is specified as a computational mode and all of these are summarised in the remaining sections. There is a subsection for each problem type and hence these sections are quite similar and repetitive. Once the basic idea is understood, it is probably best to turn directly to the subsection that describes the problem setting that is most interesting to you.
Perhaps the easiest way to rapidly become acquainted with the modes in this chapter is to run each of the example programs which use the various modes. These may be used as templates and adapted to solve specific problems.

4.1 Naming Conventions

Routines for solving nonsymmetric (real and complex) eigenvalue problems have as first letter after the chapter name, the letter ‘A’, e.g., F12ABF; equivalent routines for symmetric eigenvalue problems will have this letter replaced by the letter ‘F’, e.g., F12FBF. For the letter following this, routines for real eigenvalue problems will have letters in the range ‘A to M’ while those for complex eigenvalue problems will have letters correspondingly shifted into the range ‘N to Z’; so, for example, the complex equivalent of F12ADF is F12ARF, while the real symmetric equivalent is F12FDF.
A suite of five routines are named consecutively, e.g., F12AAF, F12ABF, F12ACF, F12ADF and F12AEF. Each general purpose routine has its own initialization routine, but uses the option setting routine from the suite relevant to the problem type. Thus each general purpose routine can be viewed as belonging to a suite of three routines, even though only two routines will be named consecutively. For example, F12ADF, F12AFF and F12AGF represent the suite of routines for solving a banded real symmetric eigenvalue problem.

4.2 Shift and Invert Spectral Transformations

The most general problem that may be solved here is to compute a few selected eigenvalues and corresponding eigenvectors for
A x = λ B x ,   where ​ A ​ and ​ B ​ are real or complex ​ n × n ​ matrices. (2)
The shift and invert spectral transformation is used to enhance convergence to a desired portion of the spectrum. If x,λ is an eigen-pair for A,B and σ ≠ λ then
A - σB -1 B x = ν x ,   where ​ ν = 1 λ - σ . (3)
This transformation is effective for finding eigenvalues near σ since the n ν eigenvalues of C ≡ A - σB -1 B that are largest in magnitude correspond to the n ν eigenvalues λ j of the original problem that are nearest to the shift σ in absolute value. These transformed eigenvalues of largest magnitude are precisely the eigenvalues that are easy to compute with a Krylov method. (See Barrett et al. (1994)). Once they are found, they may be transformed back to eigenvalues of the original problem. The direct relation is
λj = σ + 1 νj
and the eigenvector x j associated with νj in the transformed problem is also an eigenvector of the original problem corresponding to λj . Usually the Arnoldi process will rapidly obtain good approximations to the eigenvalues of C of largest magnitude. However, to implement this transformation, you must provide the means to solve linear systems involving A - σB either with a matrix factorization or with an iterative method.
In general, C will be non-Hermitian even if A and B are both Hermitian. However, this is easily remedied. The assumption that B is Hermitian positive definite implies that the bilinear form
x,y ≡ xH By
is an inner product. If B is positive semidefinite and singular, then a semi-inner product results. This is a weighted B -inner product and vectors x , y are called B -orthogonal if x,y = 0 . It is easy to show that if A is Hermitian (self-adjoint) then C is Hermitian self-adjoint with respect to this B -inner product (meaning Cx,y = x,Cy for all vectors x , y ). Therefore, symmetry will be preserved if we force the computed basis vectors to be orthogonal in this B -inner product. Implementing this B -orthogonality requires you to provide a matrix-vector product Bv on request along with each application of C . In the following sections we shall discuss some of the more familiar transformations to the standard eigenproblem. However, when B is positive (semi)definite, we recommend using the shift-invert spectral transformation with B -inner products if at all possible. This is a far more robust transformation when B is ill-conditioned or singular. With a little extra manipulation (provided automatically in the post-processing routines) the semi-inner product induced by B prevents corruption of the computed basis vectors by roundoff-error associated with the presence of infinite eigenvalues. These very ill-conditioned eigenvalues are generally associated with a singular or highly ill-conditioned B . A detailed discussion of this theory may be found in Chapter 4 of Lehoucq et al. (1998).
Shift-invert spectral transformations are very effective and should even be used on standard problems, B = I , whenever possible. This is particularly true when interior eigenvalues are sought or when the desired eigenvalues are clustered. Roughly speaking, a set of eigenvalues is clustered if the maximum distance between any two eigenvalues in that set is much smaller than the minimum distance between these eigenvalues and any other eigenvalues of A,B .
If you have a generalized problem B ≠ I , then you must provide a way to solve linear systems with either A , B or a linear combination of the two matrices in order to use the reverse communication suites in this chapter. In this case, a sparse direct method should be used to factor the appropriate matrix whenever possible. The resulting factorization may be used repeatedly to solve the required linear systems once it has been obtained. If instead you decide to use an iterative method, the accuracy of the solutions must be commensurate with the convergence tolerance used for the Arnoldi iteration. A slightly more stringent tolerance is needed relative to the desired accuracy of the eigenvalue calculation.
The main drawback with using the shift-invert spectral transformation is that the coefficient matrix A - σ B is typically indefinite in the Hermitian case and has zero-valued eigenvalues in the non-Hermitian case. These are often the most difficult situations for iterative methods and also for sparse direct methods.
The decision to use a spectral transformation on a standard eigenvalue problem B = I or to use one of the simple modes is problem dependent. The simple modes have the advantage that you only need to supply a matrix vector product Av . However, this approach is usually only successful for problems where extremal non-clustered eigenvalues are sought. In non-Hermitian problems, extremal means eigenvalues near the boundary of the spectrum of A . For Hermitian problems, extremal means eigenvalues at the left- or right-hand end points of the spectrum of A . The notion of non-clustered (or well separated) is difficult to define without going into considerable detail. A simplistic notion of a well-separated eigenvalue λj for a Hermitian problem would be λi - λj > τ λn - λ1 for all j ≠ i with τ ≫ ε , where λ 1 and λn are the smallest and largest algebraically. Unless a matrix vector product is quite difficult to code or extremely expensive computationally, it is probably worth trying to use the simple mode first if you are seeking extremal eigenvalues.
The remainder of this section discusses additional transformations that may be applied to convert a generalized eigenproblem to a standard eigenproblem. These are appropriate when B is well-conditioned (Hermitian or non-Hermitian).

4.2.1 B is Hermitian positive definite

If B is Hermitian positive definite and well-conditioned ( B B-1 is of modest size), then computing the Cholesky factorization B = L LH and converting equation (2) to
L-1 A L-H y = λy ,   where ​ LH x = y
provides a transformation to a standard eigenvalue problem. In this case, a request for a matrix vector product would be satisfied with the following three steps:
(i) | Solve LH z = v for z .
(ii) | Matrix-vector multiply z ← A z .
(iii) | Solve L w = z for w .
Upon convergence, a computed eigenvector y for L-1 A L-H is converted to an eigenvector x of the original problem by solving the triangular system LH x = y . This transformation is most appropriate when A is Hermitian, B is Hermitian positive definite and extremal eigenvalues are sought. This is because when A is Hermitian, so is L-1 A L-H .
If A is Hermitian positive definite and the smallest eigenvalues are sought, then it would be best to reverse the roles of A and B in the above description and ask for the largest algebraic eigenvalues or those of largest magnitude. Upon convergence, a computed eigenvalue λ^ would then be converted to an eigenvalue of the original problem by the relation λ ← 1 λ^ .

4.2.2 B is not Hermitian positive semidefinite

If neither A nor B is Hermitian positive semidefinite, then a direct transformation to standard form is required. One simple way to obtain a direct transformation of equation (2) to a standard eigenvalue problem C x = λ x is to multiply on the left by B-1 which results in C = B-1 A . Of course, you should not perform this transformation explicitly since it will most likely convert a sparse problem into a dense one. If possible, you should obtain a direct factorization of B and when a matrix-vector product involving C is called for, it may be accomplished with the following two steps:
(i) | Matrix-vector multiply z ← A v .
(ii) | Solve B w = z for w .
Several problem-dependent issues may modify this strategy. If B is singular or if you are interested in eigenvalues near a point σ then you may choose to work with C ≡ A-σB -1 B but without using the B -inner products discussed previously. In this case you will have to transform the converged eigenvalues of C to eigenvalues of the original problem.

4.3 Reverse Communication and Shift-invert Modes

The reverse communication interface routine for real nonsymmetric problems is F12ABF; for complex problems is F12APF; and for real symmetric problems is F12FBF. First the reverse communication loop structure will be described and then the details and nuances of the problem setup will be discussed. We use the symbol OP for the operator that is applied to vectors in the Arnoldi/Lanczos process and B will stand for the matrix to use in the weighted inner product described previously. For the shift-invert spectral transformation mode OP denotes A-σB -1 B .
The basic idea is to set up a loop that repeatedly call one of F12ABF, F12APF and F12FBF. On each return, you must either apply OP or B to a specified vector or exit the loop depending upon the value returned in the reverse communication argument IREVCM.

4.3.1 Shift and invert on a generalized eigenproblem

The example program in Section 10 in F12AEF illustrates the reverse communication loop for F12ABF in shift-invert mode for a generalized nonsymmetric eigenvalue problem. This loop structure will be identical for the symmetric problem calling F12FBF. The loop structure is also identical for the complex arithmetic subroutine F12APF.
In the example, the matrix B is assumed to be symmetric and positive semidefinite. In the loop structure, you will have to supply a routine to obtain a matrix factorization of A-σB that may repeatedly be used to solve linear systems. Moreover, a routine needs to be provided to perform the matrix-vector product z = Bv and a routine is required to solve linear systems of the form A-σB w = z as needed using the previously computed factorization.
When convergence has taken place (indicated by IREVCM = 5 and IFAIL = 0 ), the reverse communication loop will be exited. Then, post-processing using the relevant routine from F12ACF, F12AQF and F12FCF must be done to recover the eigenvalues and corresponding eigenvectors of the original problem. When operating in shift-invert mode, the eigenvalue selection option is normally set to Largest Magnitude. The post-processing routine is then used to convert the converged eigenvalues of OP to eigenvalues of the original problem (2). Also, when B is singular or ill-conditioned, the post-processing routine takes steps to purify the eigenvectors and rid them of numerical corruption from eigenvectors corresponding to near-infinite eigenvalues. These procedures are performed automatically when operating in any one of the computational modes described above and later in this section.
You may wish to construct alternative computational modes using spectral transformations that are not addressed by any of the modes specified in this chapter. The reverse communication interface will easily accommodate these modifications. However, it will most likely be necessary to construct explicit transformations of the eigenvalues of OP to eigenvalues of the original problem in these situations.

4.3.2 Using the computational modes

The problem set up is similar for all of the available computational modes. In the previous section, a detailed description of the reverse communication loop for a specific mode (Shift-invert for a Generalized Problem) was given. To use this or any of the other modes listed below, you are strongly urged to modify one of the example programs.
The first thing to decide is whether the problem will require a spectral transformation. If the problem is generalized, B ≠ I , then a spectral transformation will be required (see Section 4.2). Such a transformation will most likely be needed for a standard problem if the desired eigenvalues are in the interior of the spectrum or if they are clustered at the desired part of the spectrum. Once this decision has been made and OP has been specified, an efficient means to implement the action of the operator OP on a vector must be devised. The expense of applying OP to a vector will of course have direct impact on performance.
Shift-invert spectral transformations may be implemented with or without the use of a weighted B -inner product. The relation between the eigenvalues of OP and the eigenvalues of the original problem must also be understood in order to make the appropriate eigenvalue selection option (e.g., Largest Magnitude) in order to recover eigenvalues of interest for the original problem. You must specify the number of eigenvalues to compute, which eigenvalues are of interest, the number of basis vectors to use, and whether or not the problem is standard or generalized. These items are controlled by setting options via the option setting routine.
Setting the number of eigenvalues NEV and the number of basis vectors NCV (in the setup routine) for optimal performance is very much problem dependent. If possible, it is best to avoid setting NEV in a way that will split clusters of eigenvalues. As a rule of thumb NCV ≥ 2 × NEV is reasonable. There are trade-offs due to the cost of the user-supplied matrix-vector products and the cost of the implicit restart mechanism. If the user-supplied matrix-vector product is relatively cheap, then a smaller value of NCV may lead to more user matrix-vector products and implicit Arnoldi iterations but an overall decrease in computation time. Convergence behaviour can be quite different depending on which of the spectrum options (e.g., Largest Magnitude) is chosen. The Arnoldi process tends to converge most rapidly to extreme points of the spectrum. Implicit restarting can be effective in focusing on and isolating a selected set of eigenvalues near these extremes. In principle, implicit restarting could isolate eigenvalues in the interior, but in practice this is difficult and usually unsuccessful. If you are interested in eigenvalues near a point that is in the interior of the spectrum, a shift-invert strategy is usually required for reasonable convergence.
The integer argument IREVCM is the reverse communication flag that will specify a requested action on return from one of the solver routines F12ABF, F12APF and F12FBF. The options Standard and Generalized specify if this is a standard or generalized eigenvalue problem. The dimension of the problem is specified on the call to the initialization routine only; this value, together with the number of eigenvalues and the dimension of the basis vectors is passed through the communication array. There are a number of spectrum options which specify the eigenvalues to be computed; these options differ depending on whether a Hermitian or non-Hermitian eigenvalue problem is to be solved. For example, the Both Ends is specific to Hermitian (symmetric) problems while the Largest Imaginary is specific to non-Hermitian eigenvalue problems (see Section 11.1 in F12ADF). The specification of problem type will be described separately but the reverse communication interface and loop structure is the same for each type of the basic modes Regular, Regular Inverse, Shifted Inverse (also Shifted Inverse Real and Shifted Inverse Imaginary for real nonsymmetric problems), and for the problem type: Standard or Generalized. There are some additional specialised modes for symmetric problems, Buckling and Cayley, and for real nonsymmetric problems with complex shifts applied in real arithmetic. You are encouraged to examine the documented example programs for these modes.
The Tolerance specifies the accuracy requested. If you wish to supply shifts for implicit restarting then the Supplied Shifts must be selected, otherwise the default Exact Shifts strategy will be used. The Supplied Shifts should only be used when you have a great deal of knowledge about the spectrum and about the implicit restarted Arnoldi method and its underlying theory. The Iteration Limit should be set to the maximum number of implicit restarts allowed. The cost of an implicit restart step (major iteration) is in the order of 4 n NCV - NEV floating-point operations for the dense matrix operations and NCV - NEV matrix-vector products w ← Av with the matrix A .
The choice of computational mode through the option setting routine is very important. The legitimate computational mode options available differ with each problem type and are listed below for each of them.

4.3.3 Computational modes for real symmetric problems

The reverse communication interface subroutine for symmetric eigenvalue problems is F12FBF. The option for selecting the region of the spectrum of interest can be one of those listed in Table 1.
Largest Magnitude | The eigenvalues of greatest magnitude
Largest Algebraic | The eigenvalues of largest algebraic value (rightmost)
Smallest Magnitude | The eigenvalues of least magnitude.
Smallest Algebraic | The eigenvalues of smallest algebraic value (leftmost)
Both Ends | The eigenvalues from both ends of the algebraic spectrum
Table 1
Eigenvalue spectrum options for symmetric eigenproblems
Table 2 lists the spectral transformation options for symmetric eigenvalue problems together with the specification of OP and B for each mode and the problem type option setting.
Problem Type | Mode | Problem | OP | B
Standard | Regular | Ax=λx | A | I
Standard | Shifted Inverse | Ax=λx | A-σI-1 | I
Generalized | Regular Inverse | Ax=λBx | B-1 Ax | B
Generalized | Shifted Inverse | Ax=λBx | A-σB-1 B | B
Generalized | Buckling | Kx=λ KG x | K-σ KG-1 K | K
Generalized | Cayley | Ax=λBx | A-σB-1 A+σB | B
Table 2
Problem types, computational modes and spectral transformations for
symmetric eigenproblems

4.3.4 Computational modes for non-Hermitian problems

When A is a general non-Hermitian matrix and B is Hermitian and positive semidefinite, then the selection of the eigenvalues is controlled by the choice of one of the options in Table 3.
Largest Magnitude | The eigenvalues of greatest magnitude
Smallest Magnitude | The eigenvalues of least magnitude
Largest Real | The eigenvalues with largest real part
Smallest Real | The eigenvalues with smallest real part
Largest Imaginary | The eigenvalues with largest imaginary part
Smallest Imaginary | The eigenvalues with smallest imaginary part
Table 3
Eigenvalue spectrum options for real nonsymmetric and
complex eigenproblems
Table 4 lists the spectral transformation options for real nonsymmetric eigenvalue problems together with the specification of OP and B for each mode and the problem type option setting. The equivalent listing for complex non-Hermitian eigenvalue problems is given in Table 5.
Problem Type | Mode | Problem | OP | B
Standard | Regular | Ax = λx | A | I
Standard | Shifted Inverse Real | Ax = λx | A - σI -1 | I
Generalized | Regular Inverse | Ax = λBx | B-1 Ax | B
Generalized | Shifted Inverse Real with real σ | Ax = λBx | A - σB -1 B | B
Generalized | Shifted Inverse Real with complex σ | Ax = λBx | real A - σB -1 B | B
Generalized | Shifted Inverse Imaginary with complex σ | Ax = λBx | imag A - σB -1 B | B
Table 4
Problem types, computational modes and spectral transformations for
real nonsymmetric eigenproblems
Note that there are two shifted inverse modes with complex shifts in Table 4. Since σ is complex, these both require the factorization of the matrix A - σ B in complex arithmetic even though, in the case of real nonsymmetric problems, both A and B are real. The only advantage of using this option for real nonsymmetric problems instead of using the equivalent suite for complex problems is that all of the internal operations in the Arnoldi process are executed in real arithmetic. This results in a factor of two saving in storage and a factor of four saving in computational cost. There is additional post-processing that is somewhat more complicated than the other modes in order to get the eigenvalues and eigenvectors of the original problem. These modes are only recommended if storage is extremely critical.
Problem Type | Mode | Problem | OP | B
Standard | Regular | Ax = λx | A | I
Standard | Shifted Inverse | Ax = λx | A - σI -1 | I
Generalized | Regular Inverse | Ax = λBx | B-1 Ax | B
Generalized | Shifted Inverse | Ax = λBx | A - σB -1 B | B
Table 5
Problem types, computational modes and spectral transformations for
complex non-Hermitian eigenproblems

4.3.5 Post processing

On the final successful return from a reverse communication routine, the corresponding post-processing routine must be called to get eigenvalues of the original problem and the corresponding eigenvectors if desired. In the case of Shifted Inverse modes for Generalized problems, there are some subtleties to recovering eigenvectors when B is ill-conditioned. This process is called eigenvector purification. It prevents eigenvectors from being corrupted with noise due to the presence of eigenvectors corresponding to near infinite eigenvalues. These operations are completely transparent to you. There is negligible additional cost to obtain eigenvectors. An orthonormal (Arnoldi/Lanczos) basis is always computed. The approximate eigenvalues of the original problem are returned in ascending algebraic order. The option relevant to this routine is Vectors which may be set to values that determine whether only eigenvalues are desired or whether corresponding eigenvectors and/or Schur vectors are required. The value of the shift σ used in spectral transformations must be passed to the post-processing routine through the appropriately named argument(s). The eigenvectors returned are normalized to have unit length with respect to the semi-inner product that was used. Thus, if B = I then they will have unit length in the standard-norm. In general, a computed eigenvector x will satisfy xH B x = 1 .

4.3.6 Solution monitoring and printing

The option setting routine for each suite allows the setting of three options that control solution printing and the monitoring of the iterative and post-processing stages. These three options are: Advisory, Monitoring and Print Level. By default, no solution monitoring or printing is performed. The Advisory option controls where solution details are printed; the Monitoring option controls where monitoring details are to be printed and is mainly used for debugging purposes; the Print Level option controls the amount of detail to be printed, see individual option setting routine documents for specifications of each print level. The value passed to Advisory and Monitoring can be the same, but it is recommended that the two sets of information be kept separate. Note that the monitoring information can become very voluminous for the highest settings of Print Level.

5 Functionality Index

Standard or generalized eigenvalue problems for complex matrices,
banded matrices,
initialize problem and method F12ATF
selected eigenvalues, eigenvectors and/or Schur vectors F12AUF
general matrices,
initialize problem and method F12ANF
option setting F12ARF
reverse communication implicitly restarted Arnoldi method F12APF
reverse communication monitoring F12ASF
selected eigenvalues, eigenvectors and/or Schur vectors of original problem F12AQF
Standard or generalized eigenvalue problems for real nonsymmetric matrices,
banded matrices,
initialize problem and method F12AFF
selected eigenvalues, eigenvectors and/or Schur vectors F12AGF
general matrices,
initialize problem and method F12AAF
option setting F12ADF
reverse communication implicitly restarted Arnoldi method F12ABF
reverse communication monitoring F12AEF
selected eigenvalues, eigenvectors and/or Schur vectors of original problem F12ACF
Standard or generalized eigenvalue problems for real symmetric matrices,
banded matrices,
initialize problem and method F12FFF
selected eigenvalues, eigenvectors and/or Schur vectors F12FGF
general matrices,
initialize problem and method F12FAF
option setting F12FDF
reverse communication implicitly restarted Arnoldi(Lanczos) method F12FBF
reverse communication monitoring F12FEF
selected eigenvalues and eigenvectors and/or Schur vectors of original problem F12FCF

6 Auxiliary Routines Associated with Library Routine Arguments

None.

7 Routines Withdrawn or Scheduled for Withdrawal

None.

8 References

Barrett R, Berry M, Chan T F, Demmel J, Donato J, Dongarra J, Eijkhout V, Pozo R, Romine C and Van der Vorst H (1994) Templates for the Solution of Linear Systems: Building Blocks for Iterative Methods SIAM, Philadelphia
Lehoucq R B (1995) Analysis and implementation of an implicitly restarted iteration PhD Thesis Rice University, Houston, Texas
Lehoucq R B (2001) Implicitly restarted Arnoldi methods and subspace iteration SIAM Journal on Matrix Analysis and Applications 23 551–562
Lehoucq R B and Scott J A (1996) An evaluation of software for computing eigenvalues of sparse nonsymmetric matrices Preprint MCS-P547-1195 Argonne National Laboratory
Lehoucq R B and Sorensen D C (1996) Deflation techniques for an implicitly restarted Arnoldi iteration SIAM Journal on Matrix Analysis and Applications 17 789–821
Lehoucq R B, Sorensen D C and Yang C (1998) ARPACK Users' Guide: Solution of Large-scale Eigenvalue Problems with Implicitly Restarted Arnoldi Methods SIAM, Philidelphia
Saad Y (1992) Numerical Methods for Large Eigenvalue Problems Manchester University Press, Manchester, UK
F12 Chapter Contents
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F16 Chapter Contents : NAG Library Manual, Mark 26

F16 Chapter Introduction
NAG Library Manual

NAG Library Chapter Contents

F16 – Further Linear Algebra Support Routines

F16 Chapter Introduction – a description of the Chapter and an overview of the algorithms available

Routine Name | Mark of Introduction | Purpose
F16DLF Example Text Example Data | 22 | nagf_blast_isum Sum elements of integer vector
F16DNF Example Text Example Data | 22 | nagf_blast_imax_val Maximum value and location, integer vector
F16DPF Example Text Example Data | 22 | nagf_blast_imin_val Minimum value and location, integer vector
F16DQF Example Text Example Data | 22 | nagf_blast_iamax_val Maximum absolute value and location, integer vector
F16DRF Example Text Example Data | 22 | nagf_blast_iamin_val Minimum absolute value and location, integer vector
F16EAF (BLAS_DDOT) Example Text Example Data | 25 | BLAS_DDOT nagf_blast_ddot Dot product of two vectors, allows scaling and accumulation.
F16ECF (BLAS_DAXPBY) Example Text Example Data | 24 | BLAS_DAXPBY nagf_blast_daxpby Real weighted vector addition
F16EHF (BLAS_DWAXPBY) Example Text Example Data | 22 | BLAS_DWAXPBY nagf_blast_dwaxpby Real weighted vector addition preserving input
F16ELF (BLAS_DSUM) Example Text Example Data | 22 | BLAS_DSUM nagf_blast_dsum Sum elements of real vector
F16GCF (BLAS_ZAXPBY) Example Text Example Data | 24 | BLAS_ZAXPBY nagf_blast_zaxpby Complex weighted vector addition
F16GHF (BLAS_ZWAXPBY) Example Text Example Data | 22 | BLAS_ZWAXPBY nagf_blast_zwaxpby Complex weighted vector addition preserving input
F16GLF (BLAS_ZSUM) Example Text Example Data | 22 | BLAS_ZSUM nagf_blast_zsum Sum elements of complex vector
F16JNF (BLAS_DMAX_VAL) Example Text Example Data | 22 | BLAS_DMAX_VAL nagf_blast_dmax_val Maximum value and location, real vector
F16JPF (BLAS_DMIN_VAL) Example Text Example Data | 22 | BLAS_DMIN_VAL nagf_blast_dmin_val Minimum value and location, real vector
F16JQF (BLAS_DAMAX_VAL) Example Text Example Data | 22 | BLAS_DAMAX_VAL nagf_blast_damax_val Maximum absolute value and location, real vector
F16JRF (BLAS_DAMIN_VAL) Example Text Example Data | 22 | BLAS_DAMIN_VAL nagf_blast_damin_val Minimum absolute value and location, real vector
F16JSF (BLAS_ZAMAX_VAL) Example Text Example Data | 22 | BLAS_ZAMAX_VAL nagf_blast_zamax_val Maximum absolute value and location, complex vector
F16JTF (BLAS_ZAMIN_VAL) Example Text Example Data | 22 | BLAS_ZAMIN_VAL nagf_blast_zamin_val Minimum absolute value and location, complex vector
F16RBF Example Text Example Data | 23 | nagf_blast_dgb_norm 1-norm, ∞-norm, Frobenius norm, largest absolute element, real band matrix
F16UBF Example Text Example Data | 23 | nagf_blast_zgb_norm 1-norm, ∞-norm, Frobenius norm, largest absolute element, complex band matrix
F16 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F16DLF : NAG Library, Mark 26

F16 Chapter Contents
F16 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F16DLF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F16DLF sums the elements of an integer vector.

2 Specification

FUNCTION F16DLF ( N, X, INCX)
INTEGER F16DLF
INTEGER N, X(1+(N-1)*ABS(INCX)), INCX

3 Description

F16DLF returns the sum
x 1 + x 2 + ⋯ + xn
of the elements of an n-element integer vector x, via the function name.
If N≤0 on entry, F16DLF immediately returns the value 0.

4 References

Basic Linear Algebra Subprograms Technical (BLAST) Forum (2001) Basic Linear Algebra Subprograms Technical (BLAST) Forum Standard University of Tennessee, Knoxville, Tennessee http://www.netlib.org/blas/blast-forum/blas-report.pdf

5 Arguments

1:   N – INTEGERInput
On entry: n, the number of elements in x.
2:   X 1+N-1×INCX – INTEGER arrayInput
On entry: the n-element vector x.
If INCX>0, xi must be stored in X i-1×INCX+1, for i=1,2,…,N.
If INCX<0, xi must be stored in X N-i×INCX+1, for i=1,2,…,N.
Intermediate elements of X are not referenced. If N=0, X is not referenced.
3:   INCX – INTEGERInput
On entry: the increment in the subscripts of X between successive elements of x.
Constraint: INCX≠0.

6 Error Indicators and Warnings

If INCX=0, an error message is printed and program execution is terminated.

7 Accuracy

The BLAS standard requires accurate implementations which avoid unnecessary over/underflow (see Section 2.7 of Basic Linear Algebra Subprograms Technical (BLAST) Forum (2001)).

8 Parallelism and Performance

F16DLF is not threaded in any implementation.

9 Further Comments

None.

10 Example

This example computes the sum of the elements of
x = 1,10,11,-2,9 T .

10.1 Program Text

Program Text (f16dlfe.f90)

10.2 Program Data

Program Data (f16dlfe.d)

10.3 Program Results

Program Results (f16dlfe.r)

F16 Chapter Contents
F16 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F16DNF : NAG Library, Mark 26

F16 Chapter Contents
F16 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F16DNF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F16DNF computes the largest component of an integer vector, along with the index of that component.

2 Specification

SUBROUTINE F16DNF ( N, X, INCX, K, I)
INTEGER N, X(1+(N-1)*ABS(INCX)), INCX, K, I

3 Description

F16DNF computes the largest component, i, of an n-element integer vector x, and determines the smallest index, k, such that
i=xk=maxj xj.

4 References

Basic Linear Algebra Subprograms Technical (BLAST) Forum (2001) Basic Linear Algebra Subprograms Technical (BLAST) Forum Standard University of Tennessee, Knoxville, Tennessee http://www.netlib.org/blas/blast-forum/blas-report.pdf

5 Arguments

1:   N – INTEGERInput
On entry: n, the number of elements in x.
2:   X 1+N-1×INCX – INTEGER arrayInput
On entry: the n-element vector x.
If INCX>0, xi must be stored in X i-1×INCX+1, for i=1,2,…,N.
If INCX<0, xi must be stored in X N-i×INCX+1, for i=1,2,…,N.
Intermediate elements of X are not referenced. If N=0, X is not referenced.
3:   INCX – INTEGERInput
On entry: the increment in the subscripts of X between successive elements of x.
Constraint: INCX≠0.
4:   K – INTEGEROutput
On exit: k, the index, from the set 1,2,…,N , of the largest component of x. If N≤0 on input then K is returned as 0.
5:   I – INTEGEROutput
On exit: i, the largest component of x. If N≤0 on input then I is returned as 0.

6 Error Indicators and Warnings

If INCX=0, an error message is printed and program execution is terminated.

7 Accuracy

The BLAS standard requires accurate implementations which avoid unnecessary over/underflow (see Section 2.7 of Basic Linear Algebra Subprograms Technical (BLAST) Forum (2001)).

8 Parallelism and Performance

F16DNF is not threaded in any implementation.

9 Further Comments

None.

10 Example

This example computes the largest component and index of that component for the vector
x= 1,10,11,-2,9 T .

10.1 Program Text

Program Text (f16dnfe.f90)

10.2 Program Data

Program Data (f16dnfe.d)

10.3 Program Results

Program Results (f16dnfe.r)

F16 Chapter Contents
F16 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F16DPF : NAG Library, Mark 26

F16 Chapter Contents
F16 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F16DPF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F16DPF computes the smallest component of an integer vector, along with the index of that component.

2 Specification

SUBROUTINE F16DPF ( N, X, INCX, K, I)
INTEGER N, X(1+(N-1)*ABS(INCX)), INCX, K, I

3 Description

F16DPF computes the smallest component, i, of an n-element integer vector x, and determines the smallest index, k, such that
i=xk=minj xj.

4 References

Basic Linear Algebra Subprograms Technical (BLAST) Forum (2001) Basic Linear Algebra Subprograms Technical (BLAST) Forum Standard University of Tennessee, Knoxville, Tennessee http://www.netlib.org/blas/blast-forum/blas-report.pdf

5 Arguments

1:   N – INTEGERInput
On entry: n, the number of elements in x.
2:   X 1+N-1×INCX – INTEGER arrayInput
On entry: the n-element vector x.
If INCX>0, xi must be stored in X i-1×INCX+1, for i=1,2,…,N.
If INCX<0, xi must be stored in X N-i×INCX+1, for i=1,2,…,N.
Intermediate elements of X are not referenced. If N=0, X is not referenced.
3:   INCX – INTEGERInput
On entry: the increment in the subscripts of X between successive elements of x.
Constraint: INCX≠0.
4:   K – INTEGEROutput
On exit: k, the index, from the set 1,2,…,N , of the smallest component of x. If N≤0 on input then K is returned as 0.
5:   I – INTEGEROutput
On exit: i, the smallest component of x. If N≤0 on input then I is returned as 0.

6 Error Indicators and Warnings

If INCX=0, an error message is printed and program execution is terminated.

7 Accuracy

The BLAS standard requires accurate implementations which avoid unnecessary over/underflow (see Section 2.7 of Basic Linear Algebra Subprograms Technical (BLAST) Forum (2001)).

8 Parallelism and Performance

F16DPF is not threaded in any implementation.

9 Further Comments

None.

10 Example

This example computes the smallest component and index of that component for the vector
x= 1,10,11,-2,9 T .

10.1 Program Text

Program Text (f16dpfe.f90)

10.2 Program Data

Program Data (f16dpfe.d)

10.3 Program Results

Program Results (f16dpfe.r)

F16 Chapter Contents
F16 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F16DQF : NAG Library, Mark 26

F16 Chapter Contents
F16 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F16DQF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F16DQF computes, with respect to absolute value, the largest component of an integer vector, along with the index of that component.

2 Specification

SUBROUTINE F16DQF ( N, X, INCX, K, I)
INTEGER N, X(1+(N-1)*ABS(INCX)), INCX, K, I

3 Description

F16DQF computes, with respect to absolute value, the largest component, i, of an n-element integer vector x, and determines the smallest index, k, such that
i=xk=maxj xj.

4 References

Basic Linear Algebra Subprograms Technical (BLAST) Forum (2001) Basic Linear Algebra Subprograms Technical (BLAST) Forum Standard University of Tennessee, Knoxville, Tennessee http://www.netlib.org/blas/blast-forum/blas-report.pdf

5 Arguments

1:   N – INTEGERInput
On entry: n, the number of elements in x.
2:   X 1+N-1×INCX – INTEGER arrayInput
On entry: the n-element vector x.
If INCX>0, xi must be stored in X i-1×INCX+1, for i=1,2,…,N.
If INCX<0, xi must be stored in X N-i×INCX+1, for i=1,2,…,N.
Intermediate elements of X are not referenced. If N=0, X is not referenced.
3:   INCX – INTEGERInput
On entry: the increment in the subscripts of X between successive elements of x.
Constraint: INCX≠0.
4:   K – INTEGEROutput
On exit: k, the index, from the set 1,2,…,N , of the largest component of x with respect to absolute value. If N≤0 on input then K is returned as 0.
5:   I – INTEGEROutput
On exit: i, the largest component of x with respect to absolute value. If N≤0 on input then I is returned as 0.

6 Error Indicators and Warnings

If INCX=0, an error message is printed and program execution is terminated.

7 Accuracy

The BLAS standard requires accurate implementations which avoid unnecessary over/underflow (see Section 2.7 of Basic Linear Algebra Subprograms Technical (BLAST) Forum (2001)).

8 Parallelism and Performance

F16DQF is not threaded in any implementation.

9 Further Comments

None.

10 Example

This example computes the largest component with respect to absolute value and index of that component for the vector
x= 1,10,11,-2,9 T .

10.1 Program Text

Program Text (f16dqfe.f90)

10.2 Program Data

Program Data (f16dqfe.d)

10.3 Program Results

Program Results (f16dqfe.r)

F16 Chapter Contents
F16 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F16DRF : NAG Library, Mark 26

F16 Chapter Contents
F16 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F16DRF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F16DRF computes, with respect to absolute value, the smallest component of an integer vector, along with the index of that component.

2 Specification

SUBROUTINE F16DRF ( N, X, INCX, K, I)
INTEGER N, X(1+(N-1)*ABS(INCX)), INCX, K, I

3 Description

F16DRF computes, with respect to absolute value, the smallest component, i, of an n-element integer vector x, and determines the smallest index, k, such that
i=xk=minj xj.

4 References

Basic Linear Algebra Subprograms Technical (BLAST) Forum (2001) Basic Linear Algebra Subprograms Technical (BLAST) Forum Standard University of Tennessee, Knoxville, Tennessee http://www.netlib.org/blas/blast-forum/blas-report.pdf

5 Arguments

1:   N – INTEGERInput
On entry: n, the number of elements in x.
2:   X 1+N-1×INCX – INTEGER arrayInput
On entry: the n-element vector x.
If INCX>0, xi must be stored in X i-1×INCX+1, for i=1,2,…,N.
If INCX<0, xi must be stored in X N-i×INCX+1, for i=1,2,…,N.
Intermediate elements of X are not referenced. If N=0, X is not referenced.
3:   INCX – INTEGERInput
On entry: the increment in the subscripts of X between successive elements of x.
Constraint: INCX≠0.
4:   K – INTEGEROutput
On exit: k, the index, from the set 1,2,…,N , of the smallest component of x with respect to absolute value. If N≤0 on input then K is returned as 0.
5:   I – INTEGEROutput
On exit: i, the smallest component of x with respect to absolute value. If N≤0 on input then I is returned as 0.

6 Error Indicators and Warnings

If INCX=0, an error message is printed and program execution is terminated.

7 Accuracy

The BLAS standard requires accurate implementations which avoid unnecessary over/underflow (see Section 2.7 of Basic Linear Algebra Subprograms Technical (BLAST) Forum (2001)).

8 Parallelism and Performance

F16DRF is not threaded in any implementation.

9 Further Comments

None.

10 Example

This example computes the smallest component with respect to absolute value and index of that component for the vector
x= 1,10,11,-2,9 T .

10.1 Program Text

Program Text (f16drfe.f90)

10.2 Program Data

Program Data (f16drfe.d)

10.3 Program Results

Program Results (f16drfe.r)

F16 Chapter Contents
F16 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F16EAF (BLAS_DDOT) : NAG Library, Mark 26

F16 Chapter Contents
F16 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F16EAF (BLAS_DDOT)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F16EAF (BLAS_DDOT) updates a scalar by a scaled dot product of two real vectors.

2 Specification

SUBROUTINE F16EAF ( CONJ, N, ALPHA, X, INCX, BETA, Y, INCY, R)
INTEGER | CONJ, N, INCX, INCY
REAL (KIND=nag_wp) | ALPHA, X(1+(N-1)*ABS(INCX)), BETA, Y(1+(N-1)*ABS(INCY)), R
The routine may be called by its BLAST name blas_ddot.

3 Description

F16EAF (BLAS_DDOT) performs the operation
r← βr+ α xT y
where x and y are n-element real vectors, and r, α and β real scalars. If n is less than zero, or, if β is equal to one and either α or n is equal to zero, this routine returns immediately.

4 References

Basic Linear Algebra Subprograms Technical (BLAST) Forum (2001) Basic Linear Algebra Subprograms Technical (BLAST) Forum Standard University of Tennessee, Knoxville, Tennessee http://www.netlib.org/blas/blast-forum/blas-report.pdf

5 Arguments

1:   CONJ – INTEGERInput
On entry: CONJ is not referenced and need not be set. The presence of this argument in the BLAST standard is for consistency with the interface of the complex variant of this routine.
2:   N – INTEGERInput
On entry: n, the number of elements in x and y.
3:   ALPHA – REAL (KIND=nag_wp)Input
On entry: the scalar α.
4:   X 1+N-1×INCX – REAL (KIND=nag_wp) arrayInput
On entry: the n-element vector x.
If INCX>0, xi must be stored in X i-1×INCX+1, for i=1,2,…,N.
If INCX<0, xi must be stored in X N-i×INCX+1, for i=1,2,…,N.
Intermediate elements of X are not referenced. If α=0.0 or N=0, X is not referenced.
5:   INCX – INTEGERInput
On entry: the increment in the subscripts of X between successive elements of x.
Constraint: INCX≠0.
6:   BETA – REAL (KIND=nag_wp)Input
On entry: the scalar β.
7:   Y 1+N-1×INCY – REAL (KIND=nag_wp) arrayInput
On entry: the n-element vector y.
If INCY>0, yi must be stored in Y i-1×INCY+1, for i=1,2,…,N.
If INCY<0, yi must be stored in Y N-i×INCY+1, for i=1,2,…,N.
Intermediate elements of Y are not referenced. If α=0.0 or N=0, Y is not referenced.
8:   INCY – INTEGERInput
On entry: the increment in the subscripts of Y between successive elements of y.
Constraint: INCY≠0.
9:   R – REAL (KIND=nag_wp)Input/Output
On entry: the initial value, r, to be updated. If β=0.0, R need not be set on entry.
On exit: the value r, scaled by β and updated by the scaled dot product of x and y.

6 Error Indicators and Warnings

If INCX=0 or INCY=0, an error message is printed and program execution is terminated.

7 Accuracy

The dot product xT y is computed using the BLAS routine DDOT.
The BLAS standard requires accurate implementations which avoid unnecessary over/underflow (see Section 2.7 of Basic Linear Algebra Subprograms Technical (BLAST) Forum (2001)).

8 Parallelism and Performance

F16EAF (BLAS_DDOT) is not threaded in any implementation.

9 Further Comments

None.

10 Example

This example computes the scaled sum of two dot products, r= α 1 xT y+ α 2 uT v , where
α 1=0.3 ,  x= 1,2,3,4,5 ,  y= -5,-4,3,2,1 ,  α 2 = -7.0 ,  u=v= 0.4,0.3,0.2,0.1 .
y and v are stored in reverse order, and u is stored in reverse order in every other element of a real array.

10.1 Program Text

Program Text (f16eafe.f90)

10.2 Program Data

Program Data (f16eafe.d)

10.3 Program Results

Program Results (f16eafe.r)

F16 Chapter Contents
F16 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F16ECF (BLAS_DAXPBY) : NAG Library, Mark 26

F16 Chapter Contents
F16 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F16ECF (BLAS_DAXPBY)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F16ECF (BLAS_DAXPBY) computes the sum of two scaled vectors, for real vectors and scalars.

2 Specification

SUBROUTINE F16ECF ( N, ALPHA, X, INCX, BETA, Y, INCY)
INTEGER | N, INCX, INCY
REAL (KIND=nag_wp) | ALPHA, X(1+(N-1)*ABS(INCX)), BETA, Y(1+(N-1)*ABS(INCY))
The routine may be called by its BLAST name blas_daxpby.

3 Description

F16ECF (BLAS_DAXPBY) performs the operation
y←α x+β y
where x and y are n-element real vectors, and α and β real scalars. If n is equal to zero, or if α is equal to zero and β is equal to 1, this routine returns immediately.

4 References

Basic Linear Algebra Subprograms Technical (BLAST) Forum (2001) Basic Linear Algebra Subprograms Technical (BLAST) Forum Standard University of Tennessee, Knoxville, Tennessee http://www.netlib.org/blas/blast-forum/blas-report.pdf

5 Arguments

1:   N – INTEGERInput
On entry: n, the number of elements in x and y.
2:   ALPHA – REAL (KIND=nag_wp)Input
On entry: the scalar α.
3:   X 1+N-1×INCX – REAL (KIND=nag_wp) arrayInput
On entry: the n-element vector x.
If INCX>0, xi must be stored in X i-1×INCX+1, for i=1,2,…,N.
If INCX<0, xi must be stored in X N-i×INCX+1, for i=1,2,…,N.
Intermediate elements of X are not referenced. If N=0, X is not referenced.
4:   INCX – INTEGERInput
On entry: the increment in the subscripts of X between successive elements of x.
Constraint: INCX≠0.
5:   BETA – REAL (KIND=nag_wp)Input
On entry: the scalar β.
6:   Y 1+N-1×INCY – REAL (KIND=nag_wp) arrayInput/Output
On entry: the n-element vector y.
If INCY>0, yi must be stored in Y i-1×INCY+1, for i=1,2,…,N.
If INCY<0, yi must be stored in Y N-i×INCY+1, for i=1,2,…,N.
Intermediate elements of Y are not referenced.
On exit: the updated vector y stored in the array elements used to supply the original vector y.
Intermediate elements of Y are unchanged.
7:   INCY – INTEGERInput
On entry: the increment in the subscripts of Y between successive elements of y.
Constraint: INCY≠0.

6 Error Indicators and Warnings

If INCX=0 or INCY=0, an error message is printed and program execution is terminated.

7 Accuracy

The BLAS standard requires accurate implementations which avoid unnecessary over/underflow (see Section 2.7 of Basic Linear Algebra Subprograms Technical (BLAST) Forum (2001)).

8 Parallelism and Performance

F16ECF (BLAS_DAXPBY) makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

None.

10 Example

This example computes the result of a scaled vector accumulation for
α=3,   x = -6,4.5,3.7,2.1,-4 T , β=-1,   y = -5.1,-5,6.4,-2.4,-3 T .
x and y are stored in reverse order.

10.1 Program Text

Program Text (f16ecfe.f90)

10.2 Program Data

Program Data (f16ecfe.d)

10.3 Program Results

Program Results (f16ecfe.r)

F16 Chapter Contents
F16 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F16EHF (BLAS_DWAXPBY) : NAG Library, Mark 26

F16 Chapter Contents
F16 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F16EHF (BLAS_DWAXPBY)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F16EHF (BLAS_DWAXPBY) computes the sum of two scaled vectors, preserving input, for real scalars and vectors.

2 Specification

SUBROUTINE F16EHF ( N, ALPHA, X, INCX, BETA, Y, INCY, W, INCW)
INTEGER | N, INCX, INCY, INCW
REAL (KIND=nag_wp) | ALPHA, X(1+(N-1)*ABS(INCX)), BETA, Y(1+(N-1)*ABS(INCY)), W(1+(N-1)*ABS(INCW))
The routine may be called by its BLAST name blas_dwaxpby.

3 Description

F16EHF (BLAS_DWAXPBY) performs the operation
w ← αx+βy,
where x and y are n-element real vectors, and α and β are real scalars.

4 References

Basic Linear Algebra Subprograms Technical (BLAST) Forum (2001) Basic Linear Algebra Subprograms Technical (BLAST) Forum Standard University of Tennessee, Knoxville, Tennessee http://www.netlib.org/blas/blast-forum/blas-report.pdf

5 Arguments

1:   N – INTEGERInput
On entry: n, the number of elements in x, y and w.
2:   ALPHA – REAL (KIND=nag_wp)Input
On entry: the scalar α.
3:   X 1+N-1×INCX – REAL (KIND=nag_wp) arrayInput
On entry: the n-element vector x.
If INCX>0, xi must be stored in X i-1×INCX+1, for i=1,2,…,N.
If INCX<0, xi must be stored in X N-i×INCX+1, for i=1,2,…,N.
Intermediate elements of X are not referenced. If N=0, X is not referenced.
4:   INCX – INTEGERInput
On entry: the increment in the subscripts of X between successive elements of x.
Constraint: INCX≠0.
5:   BETA – REAL (KIND=nag_wp)Input
On entry: the scalar β.
6:   Y 1+N-1×INCY – REAL (KIND=nag_wp) arrayInput
On entry: the n-element vector y.
If INCY>0, yi must be stored in Y i-1×INCY+1, for i=1,2,…,N.
If INCY<0, yi must be stored in Y N-i×INCY+1, for i=1,2,…,N.
Intermediate elements of Y are not referenced. If β=0.0 or N=0, Y is not referenced.
7:   INCY – INTEGERInput
On entry: the increment in the subscripts of Y between successive elements of y.
Constraint: INCY≠0.
8:   W 1+N-1×INCW – REAL (KIND=nag_wp) arrayOutput
On exit: the n-element vector w.
If INCW>0, wi is in W i-1×INCW+1, for i=1,2,…,N.
If INCW<0, wi is in W N-i×INCW+1, for i=1,2,…,N.
Intermediate elements of W are not referenced.
9:   INCW – INTEGERInput
On entry: the increment in the subscripts of W between successive elements of w.
Constraint: INCW≠0.

6 Error Indicators and Warnings

If INCX=0 or INCY=0 or INCW=0, an error message is printed and program execution is terminated.

7 Accuracy

The BLAS standard requires accurate implementations which avoid unnecessary over/underflow (see Section 2.7 of Basic Linear Algebra Subprograms Technical (BLAST) Forum (2001)).

8 Parallelism and Performance

F16EHF (BLAS_DWAXPBY) is not threaded in any implementation.

9 Further Comments

None.

10 Example

This example computes the result of a scaled vector accumulation for
α=3,   x = -6,4.5,3.7,2.1,-4 T , β=-1,   y = -5.1,-5,6.4,-2.4,-3 T .
x and y, and also the sum vector w, are stored in reverse order.

10.1 Program Text

Program Text (f16ehfe.f90)

10.2 Program Data

Program Data (f16ehfe.d)

10.3 Program Results

Program Results (f16ehfe.r)

F16 Chapter Contents
F16 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F16ELF (BLAS_DSUM) : NAG Library, Mark 26

F16 Chapter Contents
F16 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F16ELF (BLAS_DSUM)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F16ELF (BLAS_DSUM) sums the elements of a real vector.

2 Specification

FUNCTION F16ELF ( N, X, INCX)
REAL (KIND=nag_wp) F16ELF
INTEGER | N, INCX
REAL (KIND=nag_wp) | X(1+(N-1)*ABS(INCX))
The routine may be called by its BLAST name blas_dsum.

3 Description

F16ELF (BLAS_DSUM) returns the sum
x 1 + x 2 + ⋯ + xn
of the elements of an n-element real vector x, via the function name.
If N≤0 on entry, F16ELF (BLAS_DSUM) returns the value 0.

4 References

Basic Linear Algebra Subprograms Technical (BLAST) Forum (2001) Basic Linear Algebra Subprograms Technical (BLAST) Forum Standard University of Tennessee, Knoxville, Tennessee http://www.netlib.org/blas/blast-forum/blas-report.pdf

5 Arguments

1:   N – INTEGERInput
On entry: n, the number of elements in x.
2:   X 1+N-1×INCX – REAL (KIND=nag_wp) arrayInput
On entry: the n-element vector x.
If INCX>0, xi must be stored in X i-1×INCX+1, for i=1,2,…,N.
If INCX<0, xi must be stored in X N-i×INCX+1, for i=1,2,…,N.
Intermediate elements of X are not referenced. If N=0, X is not referenced.
3:   INCX – INTEGERInput
On entry: the increment in the subscripts of X between successive elements of x.
Constraint: INCX≠0.

6 Error Indicators and Warnings

If INCX=0, an error message is printed and program execution is terminated.

7 Accuracy

The BLAS standard requires accurate implementations which avoid unnecessary over/underflow (see Section 2.7 of Basic Linear Algebra Subprograms Technical (BLAST) Forum (2001)).

8 Parallelism and Performance

F16ELF (BLAS_DSUM) is not threaded in any implementation.

9 Further Comments

None.

10 Example

This example computes the sum of the elements of
x = 1.1,10.2,11.5,-2.7,9.2 T .

10.1 Program Text

Program Text (f16elfe.f90)

10.2 Program Data

Program Data (f16elfe.d)

10.3 Program Results

Program Results (f16elfe.r)

F16 Chapter Contents
F16 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F16GCF (BLAS_ZAXPBY) : NAG Library, Mark 26

F16 Chapter Contents
F16 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F16GCF (BLAS_ZAXPBY)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F16GCF (BLAS_ZAXPBY) computes the sum of two scaled vectors, for complex scalars and vectors.

2 Specification

SUBROUTINE F16GCF ( N, ALPHA, X, INCX, BETA, Y, INCY)
INTEGER | N, INCX, INCY
COMPLEX (KIND=nag_wp) | ALPHA, X(1+(N-1)*ABS(INCX)), BETA, Y(1+(N-1)*ABS(INCY))
The routine may be called by its BLAST name blas_zaxpby.

3 Description

F16GCF (BLAS_ZAXPBY) performs the operation
y ← αx+βy,
where x and y are n-element complex vectors, and α and β are complex scalars. If n is less than or equal to zero, or if α is equal to zero and β is equal to 1, this routine returns immediately.

4 References

Basic Linear Algebra Subprograms Technical (BLAST) Forum (2001) Basic Linear Algebra Subprograms Technical (BLAST) Forum Standard University of Tennessee, Knoxville, Tennessee http://www.netlib.org/blas/blast-forum/blas-report.pdf

5 Arguments

1:   N – INTEGERInput
On entry: n, the number of elements in x and y.
2:   ALPHA – COMPLEX (KIND=nag_wp)Input
On entry: the scalar α.
3:   X 1+N-1×INCX – COMPLEX (KIND=nag_wp) arrayInput
On entry: the n-element vector x.
If INCX>0, xi must be stored in X i-1×INCX+1, for i=1,2,…,N.
If INCX<0, xi must be stored in X N-i×INCX+1, for i=1,2,…,N.
Intermediate elements of X are not referenced. If N=0, X is not referenced.
4:   INCX – INTEGERInput
On entry: the increment in the subscripts of X between successive elements of x.
Constraint: INCX≠0.
5:   BETA – COMPLEX (KIND=nag_wp)Input
On entry: the scalar β.
6:   Y 1+N-1×INCY – COMPLEX (KIND=nag_wp) arrayInput/Output
On entry: the n-element vector y.
If INCY>0, yi must be stored in Y i-1×INCY+1, for i=1,2,…,N.
If INCY<0, yi must be stored in Y N-i×INCY+1, for i=1,2,…,N.
Intermediate elements of Y are not referenced.
On exit: the updated vector y stored in the array elements used to supply the original vector y.
Intermediate elements of Y are unchanged.
7:   INCY – INTEGERInput
On entry: the increment in the subscripts of Y between successive elements of y.
Constraint: INCY≠0.

6 Error Indicators and Warnings

If INCX=0 or INCY=0, an error message is printed and program execution is terminated.

7 Accuracy

The BLAS standard requires accurate implementations which avoid unnecessary over/underflow (see Section 2.7 of Basic Linear Algebra Subprograms Technical (BLAST) Forum (2001)).

8 Parallelism and Performance

F16GCF (BLAS_ZAXPBY) makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

None.

10 Example

This example computes the result of a scaled vector accumulation for
α=3+2 i,   x = -6+1.2 i,3.7+4.5 i,-4+2.1 i T , β=-i,   y = -5.1,6.4-5 i,-3-2.4 i T .
x and y are stored in reverse order.

10.1 Program Text

Program Text (f16gcfe.f90)

10.2 Program Data

Program Data (f16gcfe.d)

10.3 Program Results

Program Results (f16gcfe.r)

F16 Chapter Contents
F16 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F16GHF (BLAS_ZWAXPBY) : NAG Library, Mark 26

F16 Chapter Contents
F16 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F16GHF (BLAS_ZWAXPBY)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F16GHF (BLAS_ZWAXPBY) computes the sum of two scaled vectors, preserving input, for complex scalars and vectors.

2 Specification

SUBROUTINE F16GHF ( N, ALPHA, X, INCX, BETA, Y, INCY, W, INCW)
INTEGER | N, INCX, INCY, INCW
COMPLEX (KIND=nag_wp) | ALPHA, X(1+(N-1)*ABS(INCX)), BETA, Y(1+(N-1)*ABS(INCY)), W(1+(N-1)*ABS(INCW))
The routine may be called by its BLAST name blas_zwaxpby.

3 Description

F16GHF (BLAS_ZWAXPBY) performs the operation
w ← αx+βy,
where x and y are n-element complex vectors, and α and β are complex scalars.

4 References

Basic Linear Algebra Subprograms Technical (BLAST) Forum (2001) Basic Linear Algebra Subprograms Technical (BLAST) Forum Standard University of Tennessee, Knoxville, Tennessee http://www.netlib.org/blas/blast-forum/blas-report.pdf

5 Arguments

1:   N – INTEGERInput
On entry: n, the number of elements in x, y and w.
2:   ALPHA – COMPLEX (KIND=nag_wp)Input
On entry: the scalar α.
3:   X 1+N-1×INCX – COMPLEX (KIND=nag_wp) arrayInput
On entry: the n-element vector x.
If INCX>0, xi must be stored in X i-1×INCX+1, for i=1,2,…,N.
If INCX<0, xi must be stored in X N-i×INCX+1, for i=1,2,…,N.
Intermediate elements of X are not referenced. If N=0, X is not referenced.
4:   INCX – INTEGERInput
On entry: the increment in the subscripts of X between successive elements of x.
Constraint: INCX≠0.
5:   BETA – COMPLEX (KIND=nag_wp)Input
On entry: the scalar β.
6:   Y 1+N-1×INCY – COMPLEX (KIND=nag_wp) arrayInput
On entry: the n-element vector y.
If INCY>0, yi must be stored in Y i-1×INCY+1, for i=1,2,…,N.
If INCY<0, yi must be stored in Y N-i×INCY+1, for i=1,2,…,N.
Intermediate elements of Y are not referenced. If β=0.0 or N=0, Y is not referenced.
7:   INCY – INTEGERInput
On entry: the increment in the subscripts of Y between successive elements of y.
Constraint: INCY≠0.
8:   W 1+N-1×INCW – COMPLEX (KIND=nag_wp) arrayOutput
On exit: the n-element vector w.
If INCW>0, wi is in W i-1×INCW+1, for i=1,2,…,N.
If INCW<0, wi is in W N-i×INCW+1, for i=1,2,…,N.
Intermediate elements of W are not referenced.
9:   INCW – INTEGERInput
On entry: the increment in the subscripts of W between successive elements of w.
Constraint: INCW≠0.

6 Error Indicators and Warnings

If INCX=0 or INCY=0 or INCW=0, an error message is printed and program execution is terminated.

7 Accuracy

The BLAS standard requires accurate implementations which avoid unnecessary over/underflow (see Section 2.7 of Basic Linear Algebra Subprograms Technical (BLAST) Forum (2001)).

8 Parallelism and Performance

F16GHF (BLAS_ZWAXPBY) is not threaded in any implementation.

9 Further Comments

None.

10 Example

This example computes the result of a scaled vector accumulation for
α=3+2 i,   x = -6+1.2 i,3.7+4.5 i,-4+2.1 i T , β=-i,   y = -5.1,6.4-5 i,-3-2.4 i T .
x and y, and also the sum vector w, are stored in reverse order.

10.1 Program Text

Program Text (f16ghfe.f90)

10.2 Program Data

Program Data (f16ghfe.d)

10.3 Program Results

Program Results (f16ghfe.r)

F16 Chapter Contents
F16 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F16GLF (BLAS_ZSUM) : NAG Library, Mark 26

F16 Chapter Contents
F16 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F16GLF (BLAS_ZSUM)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F16GLF (BLAS_ZSUM) sums the elements of a complex vector.

2 Specification

FUNCTION F16GLF ( N, X, INCX)
COMPLEX (KIND=nag_wp) F16GLF
INTEGER | N, INCX
COMPLEX (KIND=nag_wp) | X(1+(N-1)*ABS(INCX))
The routine may be called by its BLAST name blas_zsum.

3 Description

F16GLF (BLAS_ZSUM) returns the sum
x 1 + x 2 + ⋯ + xn
of the elements of an n-element complex vector x, via the function name.
If N≤0 on entry, F16GLF (BLAS_ZSUM) returns the value 0+0 i.

4 References

Basic Linear Algebra Subprograms Technical (BLAST) Forum (2001) Basic Linear Algebra Subprograms Technical (BLAST) Forum Standard University of Tennessee, Knoxville, Tennessee http://www.netlib.org/blas/blast-forum/blas-report.pdf

5 Arguments

1:   N – INTEGERInput
On entry: n, the number of elements in x.
2:   X 1+N-1×INCX – COMPLEX (KIND=nag_wp) arrayInput
On entry: the n-element vector x.
If INCX>0, xi must be stored in X i-1×INCX+1, for i=1,2,…,N.
If INCX<0, xi must be stored in X N-i×INCX+1, for i=1,2,…,N.
Intermediate elements of X are not referenced. If N=0, X is not referenced.
3:   INCX – INTEGERInput
On entry: the increment in the subscripts of X between successive elements of x.
Constraint: INCX≠0.

6 Error Indicators and Warnings

If INCX=0, an error message is printed and program execution is terminated.

7 Accuracy

The BLAS standard requires accurate implementations which avoid unnecessary over/underflow (see Section 2.7 of Basic Linear Algebra Subprograms Technical (BLAST) Forum (2001)).

8 Parallelism and Performance

F16GLF (BLAS_ZSUM) is not threaded in any implementation.

9 Further Comments

None.

10 Example

This example computes the sum of the elements of
x = 1.1+10.2 i,11.5-2.7 i,9.2 T .

10.1 Program Text

Program Text (f16glfe.f90)

10.2 Program Data

Program Data (f16glfe.d)

10.3 Program Results

Program Results (f16glfe.r)

F16 Chapter Contents
F16 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F16 Chapter Introduction : NAG Library, Mark 26

F16 Chapter Contents
NAG Library Manual

NAG Library Chapter Introduction

F16 – Further Linear Algebra Support Routines

▸▿ Contents

1 Scope of the Chapter
2 Background to the Problems
▸▿ 3 Recommendations on Choice and Use of Available Routines
▸▿ 3.1 Naming Scheme
3.1.1 NAG names
3.1.2 BLAS names
3.2 The Level-0 Scalar Routines
3.3 The Level-1 Vector Routines
3.4 The Level-2 Matrix-vector and Matrix Routines
3.5 The Level-3 Matrix-matrix Routines
3.6 Vector Arguments
▸▿ 3.7 Matrix Arguments and Storage Schemes
3.7.1 Conventional storage
3.7.2 Packed storage
3.7.3 Rectangular Full Packed (RFP) storage
3.7.4 Band storage
3.7.5 Unit triangular matrices
3.7.6 Real diagonal elements of complex Hermitian matrices
▸▿ 3.8 Option Arguments
3.8.1 Matrix norms
3.9 Error Handling
4 Functionality Index
5 Auxiliary Routines Associated with Library Routine Arguments
6 Routines Withdrawn or Scheduled for Withdrawal
7 References

1 Scope of the Chapter

This chapter is concerned with basic linear algebra routines which perform elementary algebraic operations involving scalars, vectors and matrices. Most routines for such operations conform either to the specifications of the BLAS (Basic Linear Algebra Subprograms) or to the specifications of the BLAST (Basic Linear Algebra Subprograms Technical) Forum. This chapter includes routines from the BLAST specifications. Most (BLAS) routines for such operations are available in Chapter F06.

2 Background to the Problems

Most of the routines in this chapter meet the specification of Basic Linear Algebra Subprograms Technical (BLAST) Forum (2001).
They are called extensively by routines in other chapters of the NAG Library, especially in the linear algebra chapters. They are intended to be useful building-blocks for users of the Library who are developing their own applications. The routines fall into four main groups (following the definitions introduced by the BLAS):
  • Level 0: scalar operations;
  • Level 1: vector operations;
  • Level 2: matrix-vector operations and matrix operations which includes single matrix operations;
  • Level 3: matrix-matrix operations.
The terminology reflects the number of operations involved, so for example a Level 2 routine involves O n 2 operations, for vectors and matrices of order n.
Because of the overlap of functionality with Chapter F06, only a subset of BLAST routines are implemented in this chapter. A full descripion of the

3 Recommendations on Choice and Use of Available Routines

3.1 Naming Scheme

3.1.1 NAG names

Table 1 shows the naming scheme for the routines in this chapter which follows the naming scheme used in Chapter F06.
 | Level-0 | Level-1 | Level-2 | Level-3
integer | – | F16D_F | – | –
‘real’ | – | F16E_F | – | –
‘real’ | – | – | F16R_F | –
‘complex’ | – | F16G_F | – | –
‘complex’ | – | – | F16U_F | –
‘mixed type’ | – | F16J_F | – | –
Table 1
The heading ‘mixed type’ is for routines where a mixture of data types is involved, such as a routine that returns the real norm of a complex vector. In future marks of the Library, routines may be included in categories that are currently empty and further categories may be introduced.

3.1.2 BLAS names

Those routines which conform to the specifications of the BLAS may be called either by their NAG names or by their BLAS names.
In many implementations of the NAG Library, references to Chapter F06 BLAS names may be linked to an efficient machine-specific implementation of the BLAS, usually provided by the vendor of the machine; Chapter F16 BLAS routines are unlikely to be provide by a vendor. Such implementations are stringently tested before being used with the NAG Library, to ensure that they correctly meet the specifications of the BLAS, and that they return the desired accuracy. Use of BLAS names is recommended for efficiency.
References to NAG routine names (beginning F06- or F16-) are always linked to the code provided in the NAG Library and may be significantly slower (in the case of Chapter F06 routines) than the equivalent BLAS routine.
The names of the Level-2 and Level-3 BLAS follow a simple scheme (which is similar to that used for LAPACK routines in Chapters F07 and F08). Each name has the structure XYYZZZ, where the components have the following meanings:
– the initial letter X indicates the data type (real or complex) and precision:
S | real, single precision (in Fortran, REAL)
D | real, double precision (in Fortran, DOUBLE PRECISION)
C | complex, single precision (in Fortran, COMPLEX)
Z | complex, double precision (in Fortran, COMPLEX*16 or DOUBLE COMPLEX)
– the second and third letters YY indicate the type of the matrix A (and in some cases its storage scheme):
GE | general
GB | general band
SY | symmetric
SP | symmetric (packed storage)
SB | symmetric band
HE | (complex) Hermitian
HP | (complex) Hermitian (packed storage)
HB | (complex) Hermitian band
TR | triangular
TP | triangular (packed storage)
TB | triangular band
– the remaining 1, 2 or 3 letters ZZZ indicate the computation performed:
MV | matrix-vector product
MM | matrix-matrix product
R | rank-1 update
R2 | rank-2 update
RK | rank-k update
R2K | rank-2 k update
SV | solve a system of linear equations
SM | solve a system of linear equations with a matrix of right-hand sides
Thus the routine BLAS_DAXPBY performs a sum of two real, scaled vectors in double precision; the corresponding routine for complex scalars and vectors is BLAS_ZAXPBY.
The names of the Level-1 BLAS mostly follow the same convention for the initial letter (S-, C-, D- or Z-), except for a few involving data of mixed type, where the first two characters are precision-dependent.

3.2 The Level-0 Scalar Routines

The Level-0 routines perform operations on scalars or on vectors or matrices of order 2.

3.3 The Level-1 Vector Routines

The Level-1 routines perform operations either on a single vector or on a pair of vectors.

3.4 The Level-2 Matrix-vector and Matrix Routines

The Level-2 routines perform operations involving either a matrix on its own, or a matrix and one or more vectors.

3.5 The Level-3 Matrix-matrix Routines

The Level-3 routines perform operations involving matrix-matrix products.

3.6 Vector Arguments

Vector arguments (except in the Level-1 Sparse BLAS) are represented by a one-dimensional array, immediately followed by an increment argument whose name consists of the three characters INC followed by the name of the array. For example, a vector x is represented by the two arguments X and INCX. The length of the vector, n say, is passed as a separate argument, N.
The increment argument is the spacing (stride) in the array between the elements of the vector. For instance, if INCX=2, then the elements of x are in locations x 1,x 3,…,x 2 n-1 of the array X and the intermediate locations x 2,x 4,…,x 2 n-2 are not referenced.
When INCX>0, the vector element xi is in the array element X 1+i-1×INCX. When INCX≤0, the elements are stored in the reverse order so that the vector element xi is in the array element X 1-n-i×INCX and hence, in particular, the element xn is in X 1. The declared length of the array X in the calling subroutine must be at least 1+N-1×INCX.
Negative increments are permitted only for:
  • Level-1 routines which have more than one vector argument;
  • Level-2 BLAS routines (but not for other Level-2 routines)
Zero increments are formally permitted for Level-1 routines with more than one argument (in which case the element X 1 is accessed repeatedly), but their use is strongly discouraged since the effect may be implementation-dependent. There is usually an alternative routine in this chapter, with a simplified argument list, to achieve the required purpose. Zero increments are not permitted in the Level-2 BLAS.

3.7 Matrix Arguments and Storage Schemes

In this chapter the following different storage schemes are used for matrices:
  • – conventional storage in a two-dimensional array;
  • – packed and RFP storage for symmetric, Hermitian or triangular matrices;
  • – band storage for band matrices;
  • – storage for spiked matrices.
These storage schemes are compatible with those used in Chapters F07 and F08. (Different schemes for packed or band storage are used in a few older routines in Chapters F01, F02, F03 and F04.)
Chapter F01 provides some utility routines for conversion between storage schemes.
In the examples, * indicates an array element which need not be set and is not referenced by the routines. The examples illustrate only the relevant leading rows and columns of the arrays; array arguments may of course have additional rows or columns, according to the usual rules for passing array arguments in Fortran.

3.7.1 Conventional storage

Please see Section 3.3.1 in the F07 Chapter Introduction for full details.

3.7.2 Packed storage

Please see Section 3.3.2 in the F07 Chapter Introduction for full details.

3.7.3 Rectangular Full Packed (RFP) storage

Please see Section 3.3.3 in the F07 Chapter Introduction for full details.

3.7.4 Band storage

Please see Section 3.3.4 in the F07 Chapter Introduction for full details.

3.7.5 Unit triangular matrices

Please see Section 3.3.5 in the F07 Chapter Introduction for full details.

3.7.6 Real diagonal elements of complex Hermitian matrices

Please see Section 3.3.6 in the F07 Chapter Introduction for full details.

3.8 Option Arguments

Many of the routines in this chapter have one or more option arguments, of type CHARACTER. The descriptions in the routine documents refer only to upper-case values (for example UPLO='U' or UPLO='L'); however, in every case, the corresponding lower-case characters may be supplied (with the same meaning). Any other value is illegal.
A longer character string can be passed as the actual argument, making the calling program more readable, but only the first character is significant. (This is a feature of Fortran.) For example:
 CALL DTRSV('Upper','Transpose','Non-unit',...)
The following option arguments are used in this chapter:
  • If TRANS='N', operate with the matrix (Not transposed);
  • if TRANS='T', operate with the Transpose of the matrix;
  • if TRANS='C', operate with the Conjugate transpose of the matrix.
  • If UPLO='U', upper triangle or trapezoid of matrix;
  • if UPLO='L', lower triangle or trapezoid of matrix.
  • If DIAG='U', unit triangular;
  • if DIAG='N', nonunit triangular.
  • If SIDE='L', operate from the left-hand side;
  • if SIDE='R', operate from the right-hand side.
  • If NORM='1' or 'O', 1-norm of a matrix;
  • if NORM='I', ∞-norm of a matrix;
  • if NORM='F' or 'E', Frobenius or Euclidean norm of a matrix;
  • if NORM='M', maximum absolute value of the elements of a matrix (not strictly a norm).

3.8.1 Matrix norms

The option argument NORM specifies different matrix norms whose definitions are given here for reference (for a general m by n matrix A):
  • One-norm (NORM='O' or '1'):
    A 1=maxj∑i=1 m a ij;
  • Infinity-norm (NORM='I'):
    A∞=maxi∑j=1 n a ij;
  • Frobenius or Euclidean norm (NORM='F' or 'E'):
    A F= ∑i=1 m∑j=1 n a ij 2 1/2.
If A is symmetric or Hermitian, A 1=A∞.
The argument NORM can also be used to specify the maximum absolute value max i,j a ij (if NORM='M'), but this is not a norm in the strict mathematical sense.

3.9 Error Handling

Routines in this chapter do not use the usual NAG Library error-handling mechanism, involving the argument IFAIL.
If one of the Level-2 or Level-3 BLAS routines is called with an invalid value of one of its arguments, then an error message is output on the error message unit (see X04AAF), giving the name of the routine and the number of the first invalid argument, and execution of the program is terminated. The following values of arguments are invalid:
  • – any value of the arguments TRANS, TRANSA, TRANSB, UPLO, SIDE or DIAG, whose meaning is not specified;
  • – a negative value of any of the arguments M, N, K, KL or KU;
  • – too small a value for any of the leading dimension arguments;
  • – a zero value for the increment arguments INCX and INCY.
Zero values for the matrix dimensions M, N or K are considered valid.
The other routines in this chapter do not report any errors in their arguments. Normally, if called, for example, with an unspecified value for one of the option arguments, or with a negative value of one of the problem dimensions M or N, they simply do nothing and return immediately.

4 Functionality Index

Matrix-vector operations,
complex matrix and vector(s),
compute a norm or the element of largest absolute value,
band matrix F16UBF
real matrix and vector(s),
compute a norm or the element of largest absolute value,
band matrix F16RBF
Scalar and vector operations,
complex vector(s),
maximum absolute value and location F16JSF (BLAS_ZAMAX_VAL)
minimum absolute value and location F16JTF (BLAS_ZAMIN_VAL)
sum of elements F16GLF (BLAS_ZSUM)
sum of two scaled vectors F16GCF (BLAS_ZAXPBY)
sum of two scaled vectors preserving input F16GHF (BLAS_ZWAXPBY)
integer vector(s),
maximum absolute value and location F16DQF
maximum value and location F16DNF
minimum absolute value and location F16DRF
minimum value and location F16DPF
sum of elements F16DLF
real vector(s),
dot product of two vectors with optional scaling and accumulation F16EAF (BLAS_DDOT)
maximum absolute value and location F16JQF (BLAS_DAMAX_VAL)
maximum value and location F16JNF (BLAS_DMAX_VAL)
minimum absolute value and location F16JRF (BLAS_DAMIN_VAL)
minimum value and location F16JPF (BLAS_DMIN_VAL)
sum of elements F16ELF (BLAS_DSUM)
sum of two scaled vectors F16ECF (BLAS_DAXPBY)
sum of two scaled vectors preserving input F16EHF (BLAS_DWAXPBY)

5 Auxiliary Routines Associated with Library Routine Arguments

None.

6 Routines Withdrawn or Scheduled for Withdrawal

None.

7 References

Basic Linear Algebra Subprograms Technical (BLAST) Forum (2001) Basic Linear Algebra Subprograms Technical (BLAST) Forum Standard University of Tennessee, Knoxville, Tennessee http://www.netlib.org/blas/blast-forum/blas-report.pdf
Dodson D S and Grimes R G (1982) Remark on Algorithm 539 ACM Trans. Math. Software 8 403–404
Dodson D S, Grimes R G and Lewis J G (1991) Sparse extensions to the Fortran basic linear algebra subprograms ACM Trans. Math. Software 17 253–263
Dongarra J J, Du Croz J J, Duff I S and Hammarling S (1990) A set of Level 3 basic linear algebra subprograms ACM Trans. Math. Software 16 1–28
Dongarra J J, Du Croz J J, Hammarling S and Hanson R J (1988) An extended set of FORTRAN basic linear algebra subprograms ACM Trans. Math. Software 14 1–32
Dongarra J J, Moler C B, Bunch J R and Stewart G W (1979) LINPACK Users' Guide SIAM, Philadelphia
Golub G H and Van Loan C F (1996) Matrix Computations (3rd Edition) Johns Hopkins University Press, Baltimore
Lawson C L, Hanson R J, Kincaid D R and Krogh F T (1979) Basic linear algebra supbrograms for Fortran usage ACM Trans. Math. Software 5 308–325
F16 Chapter Contents
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F16JNF (BLAS_DMAX_VAL) : NAG Library, Mark 26

F16 Chapter Contents
F16 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F16JNF (BLAS_DMAX_VAL)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F16JNF (BLAS_DMAX_VAL) computes the largest component of a real vector, along with the index of that component.

2 Specification

SUBROUTINE F16JNF ( N, X, INCX, K, R)
INTEGER | N, INCX, K
REAL (KIND=nag_wp) | X(1+(N-1)*ABS(INCX)), R
The routine may be called by its BLAST name blas_dmax_val.

3 Description

F16JNF (BLAS_DMAX_VAL) computes the largest component, r, of an n-element real vector x, and determines the smallest index, k, such that
r=xk=maxj xj.

4 References

Basic Linear Algebra Subprograms Technical (BLAST) Forum (2001) Basic Linear Algebra Subprograms Technical (BLAST) Forum Standard University of Tennessee, Knoxville, Tennessee http://www.netlib.org/blas/blast-forum/blas-report.pdf

5 Arguments

1:   N – INTEGERInput
On entry: n, the number of elements in x.
2:   X 1+N-1×INCX – REAL (KIND=nag_wp) arrayInput
On entry: the n-element vector x.
If INCX>0, xi must be stored in X i-1×INCX+1, for i=1,2,…,N.
If INCX<0, xi must be stored in X N-i×INCX+1, for i=1,2,…,N.
Intermediate elements of X are not referenced. If N=0, X is not referenced.
3:   INCX – INTEGERInput
On entry: the increment in the subscripts of X between successive elements of x.
Constraint: INCX≠0.
4:   K – INTEGEROutput
On exit: k, the index, from the set 1,2,…,N , of the largest component of x. If N≤0 on input then K is returned as 0.
5:   R – REAL (KIND=nag_wp)Output
On exit: r, the largest component of x. If N≤0 on input then R is returned as 0.0.

6 Error Indicators and Warnings

If INCX=0, an error message is printed and program execution is terminated.

7 Accuracy

The BLAS standard requires accurate implementations which avoid unnecessary over/underflow (see Section 2.7 of Basic Linear Algebra Subprograms Technical (BLAST) Forum (2001)).

8 Parallelism and Performance

F16JNF (BLAS_DMAX_VAL) is not threaded in any implementation.

9 Further Comments

None.

10 Example

This example computes the largest component and index of that component for the vector
x= 1,10,11,-2,9 T .

10.1 Program Text

Program Text (f16jnfe.f90)

10.2 Program Data

Program Data (f16jnfe.d)

10.3 Program Results

Program Results (f16jnfe.r)

F16 Chapter Contents
F16 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F16JPF (BLAS_DMIN_VAL) : NAG Library, Mark 26

F16 Chapter Contents
F16 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F16JPF (BLAS_DMIN_VAL)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F16JPF (BLAS_DMIN_VAL) computes the smallest component of a real vector, along with the index of that component.

2 Specification

SUBROUTINE F16JPF ( N, X, INCX, K, R)
INTEGER | N, INCX, K
REAL (KIND=nag_wp) | X(1+(N-1)*ABS(INCX)), R
The routine may be called by its BLAST name blas_dmin_val.

3 Description

F16JPF (BLAS_DMIN_VAL) computes the smallest component, r, of an n-element real vector x, and determines the smallest index, k, such that
r=xk=minj xj.

4 References

Basic Linear Algebra Subprograms Technical (BLAST) Forum (2001) Basic Linear Algebra Subprograms Technical (BLAST) Forum Standard University of Tennessee, Knoxville, Tennessee http://www.netlib.org/blas/blast-forum/blas-report.pdf

5 Arguments

1:   N – INTEGERInput
On entry: n, the number of elements in x.
2:   X 1+N-1×INCX – REAL (KIND=nag_wp) arrayInput
On entry: the n-element vector x.
If INCX>0, xi must be stored in X i-1×INCX+1, for i=1,2,…,N.
If INCX<0, xi must be stored in X N-i×INCX+1, for i=1,2,…,N.
Intermediate elements of X are not referenced. If N=0, X is not referenced.
3:   INCX – INTEGERInput
On entry: the increment in the subscripts of X between successive elements of x.
Constraint: INCX≠0.
4:   K – INTEGEROutput
On exit: k, the index, from the set 1,2,…,N , of the smallest component of x. If N≤0 on input then K is returned as 0.
5:   R – REAL (KIND=nag_wp)Output
On exit: r, the smallest component of x. If N≤0 on input then R is returned as 0.0.

6 Error Indicators and Warnings

If INCX=0, an error message is printed and program execution is terminated.

7 Accuracy

The BLAS standard requires accurate implementations which avoid unnecessary over/underflow (see Section 2.7 of Basic Linear Algebra Subprograms Technical (BLAST) Forum (2001)).

8 Parallelism and Performance

F16JPF (BLAS_DMIN_VAL) is not threaded in any implementation.

9 Further Comments

None.

10 Example

This example computes the smallest component and index of that component for the vector
x= 1,10,11,-2,9 T .

10.1 Program Text

Program Text (f16jpfe.f90)

10.2 Program Data

Program Data (f16jpfe.d)

10.3 Program Results

Program Results (f16jpfe.r)

F16 Chapter Contents
F16 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F16JQF (BLAS_DAMAX_VAL) : NAG Library, Mark 26

F16 Chapter Contents
F16 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F16JQF (BLAS_DAMAX_VAL)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F16JQF (BLAS_DAMAX_VAL) computes, with respect to absolute value, the largest component of a real vector, along with the index of that component.

2 Specification

SUBROUTINE F16JQF ( N, X, INCX, K, R)
INTEGER | N, INCX, K
REAL (KIND=nag_wp) | X(1+(N-1)*ABS(INCX)), R
The routine may be called by its BLAST name blas_damax_val.

3 Description

F16JQF (BLAS_DAMAX_VAL) computes, with respect to absolute value, the largest component, r, of an n-element real vector x, and determines the smallest index, k, such that
r=xk=maxj xj.

4 References

Basic Linear Algebra Subprograms Technical (BLAST) Forum (2001) Basic Linear Algebra Subprograms Technical (BLAST) Forum Standard University of Tennessee, Knoxville, Tennessee http://www.netlib.org/blas/blast-forum/blas-report.pdf

5 Arguments

1:   N – INTEGERInput
On entry: n, the number of elements in x.
2:   X 1+N-1×INCX – REAL (KIND=nag_wp) arrayInput
On entry: the n-element vector x.
If INCX>0, xi must be stored in X i-1×INCX+1, for i=1,2,…,N.
If INCX<0, xi must be stored in X N-i×INCX+1, for i=1,2,…,N.
Intermediate elements of X are not referenced. If N=0, X is not referenced.
3:   INCX – INTEGERInput
On entry: the increment in the subscripts of X between successive elements of x.
Constraint: INCX≠0.
4:   K – INTEGEROutput
On exit: k, the index, from the set 1,2,…,N , of the largest component of x with respect to absolute value. If N≤0 on input then K is returned as 0.
5:   R – REAL (KIND=nag_wp)Output
On exit: r, the largest component of x with respect to absolute value. If N≤0 on input then R is returned as 0.0.

6 Error Indicators and Warnings

If INCX=0, an error message is printed and program execution is terminated.

7 Accuracy

The BLAS standard requires accurate implementations which avoid unnecessary over/underflow (see Section 2.7 of Basic Linear Algebra Subprograms Technical (BLAST) Forum (2001)).

8 Parallelism and Performance

F16JQF (BLAS_DAMAX_VAL) is not threaded in any implementation.

9 Further Comments

None.

10 Example

This example computes the largest component with respect to absolute value and index of that component for the vector
x= 1,10,11,-2,9 T .

10.1 Program Text

Program Text (f16jqfe.f90)

10.2 Program Data

Program Data (f16jqfe.d)

10.3 Program Results

Program Results (f16jqfe.r)

F16 Chapter Contents
F16 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F16JRF (BLAS_DAMIN_VAL) : NAG Library, Mark 26

F16 Chapter Contents
F16 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F16JRF (BLAS_DAMIN_VAL)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F16JRF (BLAS_DAMIN_VAL) computes, with respect to absolute value, the smallest component of a real vector, along with the index of that component.

2 Specification

SUBROUTINE F16JRF ( N, X, INCX, K, R)
INTEGER | N, INCX, K
REAL (KIND=nag_wp) | X(1+(N-1)*ABS(INCX)), R
The routine may be called by its BLAST name blas_damin_val.

3 Description

F16JRF (BLAS_DAMIN_VAL) computes, with respect to absolute value, the smallest component, r, of an n-element real vector x, and determines the smallest index, k, such that
r=xk=minj xj.

4 References

Basic Linear Algebra Subprograms Technical (BLAST) Forum (2001) Basic Linear Algebra Subprograms Technical (BLAST) Forum Standard University of Tennessee, Knoxville, Tennessee http://www.netlib.org/blas/blast-forum/blas-report.pdf

5 Arguments

1:   N – INTEGERInput
On entry: n, the number of elements in x.
2:   X 1+N-1×INCX – REAL (KIND=nag_wp) arrayInput
On entry: the n-element vector x.
If INCX>0, xi must be stored in X i-1×INCX+1, for i=1,2,…,N.
If INCX<0, xi must be stored in X N-i×INCX+1, for i=1,2,…,N.
Intermediate elements of X are not referenced. If N=0, X is not referenced.
3:   INCX – INTEGERInput
On entry: the increment in the subscripts of X between successive elements of x.
Constraint: INCX≠0.
4:   K – INTEGEROutput
On exit: k, the index, from the set 1,2,…,N , of the smallest component of x with respect to absolute value. If N≤0 on input then K is returned as 0.
5:   R – REAL (KIND=nag_wp)Output
On exit: r, the smallest component of x with respect to absolute value. If N≤0 on input then R is returned as 0.0.

6 Error Indicators and Warnings

If INCX=0, an error message is printed and program execution is terminated.

7 Accuracy

The BLAS standard requires accurate implementations which avoid unnecessary over/underflow (see Section 2.7 of Basic Linear Algebra Subprograms Technical (BLAST) Forum (2001)).

8 Parallelism and Performance

F16JRF (BLAS_DAMIN_VAL) is not threaded in any implementation.

9 Further Comments

None.

10 Example

This example computes the smallest component with respect to absolute value and index of that component for the vector
x= 1,10,11,-2,9 T .

10.1 Program Text

Program Text (f16jrfe.f90)

10.2 Program Data

Program Data (f16jrfe.d)

10.3 Program Results

Program Results (f16jrfe.r)

F16 Chapter Contents
F16 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F16JSF (BLAS_ZAMAX_VAL) : NAG Library, Mark 26

F16 Chapter Contents
F16 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F16JSF (BLAS_ZAMAX_VAL)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F16JSF (BLAS_ZAMAX_VAL) computes, with respect to absolute value, the largest component of a complex vector, along with the index of that component.

2 Specification

SUBROUTINE F16JSF ( N, X, INCX, K, R)
INTEGER | N, INCX, K
REAL (KIND=nag_wp) | R
COMPLEX (KIND=nag_wp) | X(1+(N-1)*ABS(INCX))
The routine may be called by its BLAST name blas_zamax_val.

3 Description

F16JSF (BLAS_ZAMAX_VAL) computes, with respect to absolute value, the largest component, r, of an n-element complex vector x, and determines the smallest index, k, such that
r = Re⁡xk + Im⁡xk = maxj Re⁡xj + Im⁡xj .

4 References

Basic Linear Algebra Subprograms Technical (BLAST) Forum (2001) Basic Linear Algebra Subprograms Technical (BLAST) Forum Standard University of Tennessee, Knoxville, Tennessee http://www.netlib.org/blas/blast-forum/blas-report.pdf

5 Arguments

1:   N – INTEGERInput
On entry: n, the number of elements in x.
2:   X 1+N-1×INCX – COMPLEX (KIND=nag_wp) arrayInput
On entry: the n-element vector x.
If INCX>0, xi must be stored in X i-1×INCX+1, for i=1,2,…,N.
If INCX<0, xi must be stored in X N-i×INCX+1, for i=1,2,…,N.
Intermediate elements of X are not referenced. If N=0, X is not referenced.
3:   INCX – INTEGERInput
On entry: the increment in the subscripts of X between successive elements of x.
Constraint: INCX≠0.
4:   K – INTEGEROutput
On exit: k, the index, from the set 1,2,…,N , of the largest component of x with respect to absolute value. If N≤0 on input then K is returned as 0.
5:   R – REAL (KIND=nag_wp)Output
On exit: r, the largest component of x with respect to absolute value. If N≤0 on input then R is returned as 0.0.

6 Error Indicators and Warnings

None.

7 Accuracy

The BLAS standard requires accurate implementations which avoid unnecessary over/underflow (see Section 2.7 of Basic Linear Algebra Subprograms Technical (BLAST) Forum (2001)).

8 Parallelism and Performance

F16JSF (BLAS_ZAMAX_VAL) is not threaded in any implementation.

9 Further Comments

None.

10 Example

This example computes the largest component with respect to absolute value and index of that component for the vector
x= -4+2.1 i,3.7+4.5 i,-6+1.2 i T .

10.1 Program Text

Program Text (f16jsfe.f90)

10.2 Program Data

Program Data (f16jsfe.d)

10.3 Program Results

Program Results (f16jsfe.r)

F16 Chapter Contents
F16 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F16JTF (BLAS_ZAMIN_VAL) : NAG Library, Mark 26

F16 Chapter Contents
F16 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F16JTF (BLAS_ZAMIN_VAL)

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F16JTF (BLAS_ZAMIN_VAL) computes, with respect to absolute value, the smallest component of a complex vector, along with the index of that component.

2 Specification

SUBROUTINE F16JTF ( N, X, INCX, K, R)
INTEGER | N, INCX, K
REAL (KIND=nag_wp) | R
COMPLEX (KIND=nag_wp) | X(1+(N-1)*ABS(INCX))
The routine may be called by its BLAST name blas_zamin_val.

3 Description

F16JTF (BLAS_ZAMIN_VAL) computes, with respect to absolute value, the smallest component, r, of an n-element complex vector x, and determines the smallest index, k, such that
r=Re⁡xk+Im⁡xk=minj Re⁡xj+Im⁡xj.

4 References

Basic Linear Algebra Subprograms Technical (BLAST) Forum (2001) Basic Linear Algebra Subprograms Technical (BLAST) Forum Standard University of Tennessee, Knoxville, Tennessee http://www.netlib.org/blas/blast-forum/blas-report.pdf

5 Arguments

1:   N – INTEGERInput
On entry: n, the number of elements in x.
2:   X 1+N-1×INCX – COMPLEX (KIND=nag_wp) arrayInput
On entry: the n-element vector x.
If INCX>0, xi must be stored in X i-1×INCX+1, for i=1,2,…,N.
If INCX<0, xi must be stored in X N-i×INCX+1, for i=1,2,…,N.
Intermediate elements of X are not referenced. If N=0, X is not referenced.
3:   INCX – INTEGERInput
On entry: the increment in the subscripts of X between successive elements of x.
Constraint: INCX≠0.
4:   K – INTEGEROutput
On exit: k, the index, from the set 1,2,…,N , of the smallest component of x with respect to absolute value. If N≤0 on input then K is returned as 0.
5:   R – REAL (KIND=nag_wp)Output
On exit: r, the smallest component of x with respect to absolute value. If N≤0 on input then R is returned as 0.0.

6 Error Indicators and Warnings

If INCX=0, an error message is printed and program execution is terminated.

7 Accuracy

The BLAS standard requires accurate implementations which avoid unnecessary over/underflow (see Section 2.7 of Basic Linear Algebra Subprograms Technical (BLAST) Forum (2001)).

8 Parallelism and Performance

F16JTF (BLAS_ZAMIN_VAL) is not threaded in any implementation.

9 Further Comments

None.

10 Example

This example computes the smallest component with respect to absolute value and index of that component for the vector
x= -4+2.1 i,3.7+4.5 i,-6+1.2 i T .

10.1 Program Text

Program Text (f16jtfe.f90)

10.2 Program Data

Program Data (f16jtfe.d)

10.3 Program Results

Program Results (f16jtfe.r)

F16 Chapter Contents
F16 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F16RBF : NAG Library, Mark 26

F16 Chapter Contents
F16 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F16RBF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F16RBF calculates the value of the 1-norm, the ∞-norm, the Frobenius norm or the maximum absolute value of the elements of a real m by n band matrix stored in banded form.
It can also be used to compute the value of the 2-norm of a row n-vector or a column m-vector.

2 Specification

FUNCTION F16RBF ( INORM, M, N, KL, KU, AB, LDAB)
REAL (KIND=nag_wp) F16RBF
INTEGER | INORM, M, N, KL, KU, LDAB
REAL (KIND=nag_wp) | AB(LDAB,*)

3 Description

Given a real m by n banded matrix, A, F16RBF calculates one of the values given by
A 1=maxj⁡∑i=1 m a ij | (the 1-norm of A),
A∞=maxi⁡∑j= 1 n a ij | (the ∞-norm of A),
A F=∑i=1 m∑j=1 n a ij 2 1/2 | (the Frobenius norm of A), or
max i,j a ij | (the maximum absolute element value of A).
If m or n is 1 then additionally F16RBF can calculate the value A 2=∑ai 2 (the 2-norm of A).

4 References

Basic Linear Algebra Subprograms Technical (BLAST) Forum (2001) Basic Linear Algebra Subprograms Technical (BLAST) Forum Standard University of Tennessee, Knoxville, Tennessee http://www.netlib.org/blas/blast-forum/blas-report.pdf

5 Arguments

1:   INORM – INTEGERInput
On entry: specifies the value to be returned. The integer codes shown below can be replaced by the equivalent named constants of the form NAG_?_NORM. These named constants are available via the nag_library module and are also used in the example program for clarity.
INORM=171 (NAG_ONE_NORM)
The 1-norm.
INORM=173 (NAG_TWO_NORM)
The 2-norm of a row or column vector.
INORM=174 (NAG_FROBENIUS_NORM)
The Frobenius (or Euclidean) norm.
INORM=175 (NAG_INF_NORM)
The ∞-norm.
INORM=177 (NAG_MAX_NORM)
The value max i,j a ij (not a norm).
Constraints:
  • INORM=171, 173, 174, 175 or 177;
  • if INORM=173, M=1 or N=1.
2:   M – INTEGERInput
On entry: m, the number of rows of the matrix A. If M≤0 on input, F16RBF returns 0.
3:   N – INTEGERInput
On entry: n, the number of columns of the matrix A. If N≤0 on input, F16RBF returns 0.
4:   KL – INTEGERInput
On entry: kl, the number of subdiagonals within the band of A. If KL≤0 on input, F16RBF returns 0.
5:   KU – INTEGERInput
On entry: ku, the number of superdiagonals within the band of A. If KU≤0 on input, F16RBF returns 0.
6:   AB LDAB* – REAL (KIND=nag_wp) arrayInput
Note: the second dimension of the array AB must be at least max 1,N.
On entry: the m by n band matrix A.
The matrix is stored in rows 1 to kl+ku+1, more precisely, the element A ij must be stored in
AB ku+1+i-j j  for ​max 1,j-ku≤i≤min m,j+kl.
7:   LDAB – INTEGERInput
On entry: the first dimension of the array AB as declared in the (sub)program from which F16RBF is called.
Constraint: LDAB≥KL+KU+1.

6 Error Indicators and Warnings

If any constraint on an input parameter is violated, an error message is printed and program execution is terminated.

7 Accuracy

The BLAS standard requires accurate implementations which avoid unnecessary over/underflow (see Section 2.7 of Basic Linear Algebra Subprograms Technical (BLAST) Forum (2001)).

8 Parallelism and Performance

F16RBF is not threaded in any implementation.

9 Further Comments

None.

10 Example

Calculates the various norms of a 6 by 4 banded matrix with two subdiagonals and one superdiagonal.

10.1 Program Text

Program Text (f16rbfe.f90)

10.2 Program Data

Program Data (f16rbfe.d)

10.3 Program Results

Program Results (f16rbfe.r)

F16 Chapter Contents
F16 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


F16UBF : NAG Library, Mark 26

F16 Chapter Contents
F16 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

F16UBF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

F16UBF calculates the value of the 1-norm, the ∞-norm, the Frobenius norm or the maximum absolute value of the elements of a complex m by n band matrix stored in banded packed form.
It can also be used to compute the value of the 2-norm of a row n-vector or a column m-vector.

2 Specification

FUNCTION F16UBF ( INORM, M, N, KL, KU, AB, LDAB)
REAL (KIND=nag_wp) F16UBF
INTEGER | INORM, M, N, KL, KU, LDAB
COMPLEX (KIND=nag_wp) | AB(LDAB,*)

3 Description

Given a complex m by n band matrix, A, F16UBF calculates one of the values given by
A 1=maxj⁡∑i=1 m a ij | (the 1-norm of A),
A∞=maxi⁡∑j= 1 n a ij | (the ∞-norm of A),
A F=∑i=1 m∑j=1 n a ij 2 1/2 | (the Frobenius norm of A), or
max i,j a ij | (the maximum absolute element value of A).
If m or n is 1 then additionally F16UBF can calculate the value A 2=∑ai 2 (the 2-norm of A).

4 References

Basic Linear Algebra Subprograms Technical (BLAST) Forum (2001) Basic Linear Algebra Subprograms Technical (BLAST) Forum Standard University of Tennessee, Knoxville, Tennessee http://www.netlib.org/blas/blast-forum/blas-report.pdf

5 Arguments

1:   INORM – INTEGERInput
On entry: specifies the value to be returned. The integer codes shown below can be replaced by the equivalent named constants of the form NAG_?_NORM. These named constants are available via the nag_library module and are also used in the example program for clarity.
INORM=171 (NAG_ONE_NORM)
The 1-norm.
INORM=173 (NAG_TWO_NORM)
The 2-norm of a row or column vector.
INORM=174 (NAG_FROBENIUS_NORM)
The Frobenius (or Euclidean) norm.
INORM=175 (NAG_INF_NORM)
The ∞-norm.
INORM=177 (NAG_MAX_NORM)
The value max i,j a ij (not a norm).
Constraints:
  • INORM=171, 173, 174, 175 or 177;
  • if INORM=173, M=1 or N=1.
2:   M – INTEGERInput
On entry: m, the number of rows of the matrix A. If M≤0 on input, F16UBF returns 0.
3:   N – INTEGERInput
On entry: n, the number of columns of the matrix A. If N≤0 on input, F16UBF returns 0.
4:   KL – INTEGERInput
On entry: kl, the number of subdiagonals within the band of A. If KL≤0 on input, F16UBF returns 0.
5:   KU – INTEGERInput
On entry: ku, the number of superdiagonals within the band of A. If KU≤0 on input, F16UBF returns 0.
6:   AB LDAB* – COMPLEX (KIND=nag_wp) arrayInput
Note: the second dimension of the array AB must be at least max 1,N.
On entry: the m by n band matrix A.
The matrix is stored in rows 1 to kl+ku+1, more precisely, the element A ij must be stored in
AB ku+1+i-j j  for ​max 1,j-ku≤i≤min m,j+kl.
7:   LDAB – INTEGERInput
On entry: the first dimension of the array AB as declared in the (sub)program from which F16UBF is called.
Constraint: LDAB≥KL+KU+1.

6 Error Indicators and Warnings

If any constraint on an input parameter is violated, an error message is printed and program execution is terminated.

7 Accuracy

The BLAS standard requires accurate implementations which avoid unnecessary over/underflow (see Section 2.7 of Basic Linear Algebra Subprograms Technical (BLAST) Forum (2001)).

8 Parallelism and Performance

F16UBF is not threaded in any implementation.

9 Further Comments

None.

10 Example

Reads in a 6 by 4 banded complex matrix A with two subdiagonals and one superdiagonal, and prints the four norms of A.

10.1 Program Text

Program Text (f16ubfe.f90)

10.2 Program Data

Program Data (f16ubfe.d)

10.3 Program Results

Program Results (f16ubfe.r)

F16 Chapter Contents
F16 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


Copyright Statement : NAG Library, Mark 26

NAG Library Manual

NAG Library

Copyright Statement

© The Numerical Algorithms Group Limited, 2016
All rights reserved. Duplication of this Manual in printed form or by electronic means for the private and sole use of the software licensee is permitted provided that the individual copying the document is not
– | selling or reselling the documentation;
– | distributing the documentation to others, who have not licensed the software for professional use;
– | using it for the purpose of critical review, publication in printed form or any electronic publication including the Internet without the prior written permission of the copyright owner.
The copyright owner gives no warranties and makes no representations about the contents of this Manual and specifically disclaims any implied warranties or merchantability or fitness for any purpose.
The copyright owner reserves the right to revise this Manual and to make changes from time to time in its contents without notifying any person of such revisions or changes.
Produced by NAG.
Mark 26 released August 2016
ISBN 978-1-85206-216-3
NAG is a registered trademark of:
  • The Numerical Algorithms Group Limited
  • The Numerical Algorithms Group Inc
  • Nihon Numerical Algorithms Group KK
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


Foreword : NAG Library, Mark 26

NAG Library Manual

NAG Library

Foreword

The following Foreword to the NAG Fortran Library Manual, which was released in 1975, was contributed by the late Professor Fox and the late Dr Wilkinson.
Those who have organised computing services are well aware of the two main problems which face the users of computing machines in scientific computation. First, considerable experience is needed before the user can transform a given algorithm into a very efficient program, and there are many examples in which relatively small amendments to a few instructions can transform a modest program into one considerably more economical in time and storage space. Second, our user needs knowledge of the principles and techniques of numerical analysis, however efficient he might be at program construction, before he can reasonably guarantee to have an efficient algorithm which is as free as possible from numerical instability and which gives good results in economic time. Both the cost of computation and the ever-present desire for quick results make obligatory at least a partial solution to these two problems.
Many computing laboratories and computing services have made some attempts at solution by constructing libraries of computer programs, but only in the last few years has it been possible to develop really comprehensive schemes based on two or more decades of research into methods and their error analysis by numerical mathematicians, and on the development of a new breed of expert in ‘numerical software’. This NAG Fortran Library was in fact initiated by a small mixed university band of numerical analysts and their software counterparts, but has increasingly received encouragement, support and material from many ‘extramural’ organisations.
The compilers of this library have used, as main criteria for the selection of their programs, the concepts of (i) usefulness, (ii) robustness, (iii) numerical stability, (iv) accuracy and (v) speed. But within these criteria several rather difficult decisions have to be made. First, how many different routines are needed in each particular subject area, such as linear equations, optimization, ordinary differential equations, partial differential equations and so on? What is relevant here is the number of ‘parameters’ of the particular subject area. With linear equations, for example, the matrix might be ‘dense’ or have some particular ‘sparse’ structure, it might be symmetric and, if so, possibly positive-definite, it might be too large for the high-speed store of some particular computer, it might be one for which an iterative method is known to converge, or the problem might involve the same matrix but have many different right-hand sides, and so on. Each of these sub-groups may require quite different routines for best efficiency, but within each sub-group there may also be several computing techniques requiring a further selection decision.
A second question which has to be answered is the nature and amount of material to be provided for the ‘answer’ to problems. If the data of the problem are exact, and if the problem has a unique solution, then it is meaningful to ask for results accurate to a specified number of figures. Whether one can get them easily, say with single-precision arithmetic, will depend on the sensitivity of the answers to small changes in the data. For even the storage of exact numbers cannot usually be performed exactly, so that from the outset our problem differs slightly from the one we hoped to solve. Moreover inevitable computer rounding errors will produce solutions which are the exact solutions of a perturbation of the original problem, the amount of the perturbation depending on the degree of stability of the numerical method. With so-called ‘ill-conditioned’ problems small perturbations from any of those sources produce large changes in the answers, so that ‘exact’ or very accurate solutions can be difficult to obtain even if they are meaningful.
But the data may not be known exactly. Some of them may be measured by physical apparatus or involve physical constants known with certainty only to a few figures. In that case the answers are meaningful only to a few figures and perhaps even to no figures, and whether the precision of the answers is larger or smaller than that of the data again depends on the degree of ill-conditioning of the problem. How much of this sort of information should the routines provide?
A third decision is the amount of explanation to be included with the programs. It is clearly desirable to include elements of ‘why’ something is done as well as ‘what’ is done, but the desirable amount of such information is rather delicate. If there is too much the expert may be too bored to read all of it and may herefore miss something important, while the amateur may find the discussion rather involved, appearing to him rather like an introductory text in numerical analysis, and again may skip most of it but now on the grounds of indigestibility. Too little, on the other hand, may detract from the value of the routines by giving the amateur too little guidance in the choice which he also always has to make.
This NAG Fortran Library deals with these problems about as well as could be expected in the present state of knowledge of numerical analysts, software and library compilers, and the majority of the users. With regard to the number of routines to be provided it usually gives just the best available within each sub-group, and selects the particular sub-groups which at present seem to be the most needed and for which good techniques are available.
With regard to sensitivity and accuracy it achieves rather less, but this is a problem so far not well treated even by numerical analysts. Information is provided in a fairly economical way for the solution of linear equations, in which the so-called ‘iterative refinement’ involving a little double precision arithmetic gives valuable information on the sensitivity and a more accurate answer when this is meaningful. For many other problems the user can only obtain this sort of information by his own efforts, for example by deliberately introducing small perturbations and observing their effects on his solutions. This whole area is one in which one hopes for continual improvements in the library routines when better ways to implement them are discovered.
With regard to annotation, the routines do include a fair but not prohibitive amount of ‘why’ as well as ‘what’, and there is no doubt that a mastery of this material will enable the user not only to increase the value he gets from this library but also to improve his performance in the inevitable writing of his own routines for problems not directly treated here.
Two other topics are worth mentioning. First, the routines which appear in this library are the result of years of detailed study by numerical analysts and software experts, and it is dangerous in varying degrees to tamper with them and to try to modify them for ‘local needs’. In the solution of linear equations, for example, one could without great peril omit the iterative refinement and still get useful results. One loses here just the extra but often extremely valuable knowledge about the ‘condition’ of the problem which iterative refinement gives comparatively economically. A far greater danger would arise from an attempt to ‘speed-up’ the routine by, for example, omitting the row interchanges. which are essentially unnecessary with exact arithmetic. Computer arithmetic is not exact, and this fact could cause complete rubbish in the solutions obtained by neglecting interchanges, which in this context ruins the stability of the numerical method.
Second, the library cannot help the user in the proper formulation of his problem. Given, for example, the problem of computing
Ir = e-1 ∫ 0 1 ex xr d x ,  for  r=0,1,2,…,20
the library will have routines for evaluating this integral by numerical quadrature, to whatever accuracy is required, for each value of r. But nothing in the library can tell the user that a very much faster method would use the recurrence relation (in the ‘backwards direction’)
I r-1 = 1-Ir r , with  IN = 0 ,
where N (>20) depends on the accuracy required but is determinable by simple and very rapid numerical experiment (and even, in this simple case, by elementary analysis). Nor could the library tell him that the perhaps more obvious use of the forward recurrence
Ir = 1 - r I r-1 , with  I 0 = 1 - e-1 ,
would fail to produce accurate results beyond the first few values of r with only single-precision arithmetic: that this formulation, in fact, gives a very ill-conditioned problem.
In summary, then, this NAG Fortran Library represents a timely and very important aid to the computer user in scientific computation. Here, and in future extensions, it provides the best available routines for a wide variety of numerical subject areas, backed by a non-prohibitive amount of sensible explanation of both what is being done and why it is being done. But the user must realise that the library can provide no more than it claims in its annotation, that it cannot except where explicitly stated determine for him the degree of ill-conditioning of his problem, nor help him in general to cast his problem into a better form. For such information he should study some numerical analysis or ask the advice of a colleague reasonably experienced in this field. It may happen that in future editions of the library it will be possible to give more assistance of this kind to the general user, and it is our hope, in welcoming warmly this edition, that future productions will have some useful expansions of this kind, in addition to the obvious need for new routines in the subject areas which in this first venture are not touched upon or treated only sparsely. The research involved will be both exciting and fruitful!
Professor L Fox (Oxford University)
Dr J H Wilkinson, FRS (National Physical Laboratory, England)
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


Table of Contents for the NAG Library Manual, Mark 26

NAG Library Manual

NAG Library Manual, Mark 26

Contents

  • Copyright Statement
  • Foreword

Introduction

  • How to Use the NAG Library and its Documentation
  • Mark 26 NAG Fortran Library News
  • Implementation-specific Details for Users
  • Advice on Replacement Calls for Withdrawn/Superseded Routines
  • Code Contributors
  • Support from NAG
  • Keyword and GAMS Search

Chapters of the Library

  • A00 – Library Identification
  • A02 – Complex Arithmetic
  • C02 – Zeros of Polynomials
  • C05 – Roots of One or More Transcendental Equations
  • C06 – Summation of Series
  • C09 – Wavelet Transforms
  • D01 – Quadrature
  • D02 – Ordinary Differential Equations
  • D03 – Partial Differential Equations
  • D04 – Numerical Differentiation
  • D05 – Integral Equations
  • D06 – Mesh Generation
  • E01 – Interpolation
  • E02 – Curve and Surface Fitting
  • E04 – Minimizing or Maximizing a Function
  • E05 – Global Optimization of a Function
  • F – Linear Algebra
  • F01 – Matrix Operations, Including Inversion
  • F02 – Eigenvalues and Eigenvectors
  • F03 – Determinants
  • F04 – Simultaneous Linear Equations
  • F05 – Orthogonalization
  • F06 – Linear Algebra Support Routines
  • F07 – Linear Equations (LAPACK)
  • F08 – Least Squares and Eigenvalue Problems (LAPACK)
  • F11 – Large Scale Linear Systems
  • F12 – Large Scale Eigenproblems
  • F16 – Further Linear Algebra Support Routines
  • G01 – Simple Calculations on Statistical Data
  • G02 – Correlation and Regression Analysis
  • G03 – Multivariate Methods
  • G04 – Analysis of Variance
  • G05 – Random Number Generators
  • G07 – Univariate Estimation
  • G08 – Nonparametric Statistics
  • G10 – Smoothing in Statistics
  • G11 – Contingency Table Analysis
  • G12 – Survival Analysis
  • G13 – Time Series Analysis
  • H – Operations Research
  • M01 – Sorting and Searching
  • S – Approximations of Special Functions
  • X01 – Mathematical Constants
  • X02 – Machine Constants
  • X03 – Inner Products
  • X04 – Input/Output Utilities
  • X05 – Date and Time Utilities
  • X06 – OpenMP Utilities
  • X07 – IEEE Arithmetic
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


G01ABF : NAG Library, Mark 26

G01 Chapter Contents
G01 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

G01ABF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

G01ABF computes the means, standard deviations, corrected sums of squares and products, maximum and minimum values, and the product-moment correlation coefficient for two variables. Unequal weighting may be given.

2 Specification

SUBROUTINE G01ABF ( N, X1, X2, IWT, WT, RES, IFAIL)
INTEGER | N, IWT, IFAIL
REAL (KIND=nag_wp) | X1(N), X2(N), WT(N), RES(13)

3 Description

The data consist of two samples of n observations, denoted by xi, and yi, for i=1,2,…,n, with corresponding weights wi, for i=1,2,…,n.
If no specific weighting is given, then each wi is set to 1.0 in G01ABF.
The quantities calculated are:
(a) The sum of weights,
W=∑i=1 n wi.
(b) The means,
x-=∑i= 1 n wixi W,   y-=∑i= 1 n wiyi W.
(c) The corrected sums of squares and products
c 11=∑i=1 n wi xi-x- 2 c 21=c 12=∑i=1 n wi xi-x- yi-y- c 22=∑i=1 n wi yi-y- 2 .
(d) The standard deviations
sj= c jj d ,   where   j= 1,2   and   d=W- ∑ i= 1 n wi 2 W .
(e) The product-moment correlation coefficient
R= c 12 c 11 c 22 .
(f) | The minimum and maximum elements in each of the two samples.
(g) | The number of pairs of observations, m, for which wi>0, i.e., the number of valid observations. The quantities in (d) and (e) above will only be computed if m≥2. All other items are computed if m≥1.

4 References

None.

5 Arguments

1:   N – INTEGERInput
On entry: n, the number of pairs of observations.
Constraint: N≥1.
2:   X1 N – REAL (KIND=nag_wp) arrayInput
On entry: the observations from the first sample, xi, for i=1,2,…,n.
3:   X2 N – REAL (KIND=nag_wp) arrayInput
On entry: the observations from the second sample, yi, for i=1,2,…,n.
4:   IWT – INTEGERInput/Output
On entry: indicates whether user-supplied weights are provided by you:
IWT=1
  • Indicates that user-supplied weights are given in the array WT.
IWT≠0
  • Indicates that user-supplied weights are not given. In this case the routine assigns the value 1.0 to each element of the weight array, WT.
On exit: is used to indicate the number of valid observations, m; see Section 3(g), above.
5:   WT N – REAL (KIND=nag_wp) arrayInput/Output
On entry: if weights are being supplied then the elements of WT must contain the weights associated with the observations, wi, for i=1,2,…,n.
Constraint: if IWT=1, WT i≥0.0, for i=1,2,…,N.
On exit: if IWT=1, the elements of WT are unchanged, otherwise each element of WT will be assigned the value 1.0.
6:   RES 13 – REAL (KIND=nag_wp) arrayOutput
On exit: the elements of RES contain the following results:
RES 1 | mean of the first sample, x-;
RES 2 | mean of the second sample, y-;
RES 3 | standard deviation of the first sample, s 1;
RES 4 | standard deviation of the second sample, s 2;
RES 5 | corrected sum of squares of the first sample, c 11;
RES 6 | corrected sum of products of the two samples, c 12;
RES 7 | corrected sum of squares of the second sample, c 22;
RES 8 | product-moment correlation coefficient, R;
RES 9 | minimum of the first sample;
RES 10 | maximum of the first sample;
RES 11 | minimum of the second sample;
RES 12 | maximum of the second sample;
RES 13 | sum of weights, ∑i=1 n wi (=N, if IWT=0, on entry).
7:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, N<1.
IFAIL=2
The number of valid cases, m, is 1, hence the standard deviation, 3(d), and the product-moment correlation coefficient, 3(e), cannot be calculated.
IFAIL=3
The number of valid cases, m, is 0, or at least one of the weights is negative.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

The method used is believed to be stable.

8 Parallelism and Performance

G01ABF is not threaded in any implementation.

9 Further Comments

The time taken by G01ABF increases linearly with n.

10 Example

In the program below, NPROB determines the number of datasets to be analysed. For each analysis, a set of observations and, optionally, weights, is read and printed. After calling G01ABF, all the calculated quantities are printed. In the example, there is one set of data, with 29 (unweighted) pairs of observations.

10.1 Program Text

Program Text (g01abfe.f90)

10.2 Program Data

Program Data (g01abfe.d)

10.3 Program Results

Program Results (g01abfe.r)

G01 Chapter Contents
G01 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


G01ADF : NAG Library, Mark 26

G01 Chapter Contents
G01 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

G01ADF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

G01ADF calculates the mean, standard deviation and coefficients of skewness and kurtosis for data grouped in a frequency distribution.

2 Specification

SUBROUTINE G01ADF ( K, X, IFREQ, XMEAN, S2, S3, S4, N, IFAIL)
INTEGER | K, IFREQ(K), N, IFAIL
REAL (KIND=nag_wp) | X(K), XMEAN, S2, S3, S4

3 Description

The input data consist of a univariate frequency distribution, denoted by fi, for i=1,2,…,k-1, and the boundary values of the classes xi, for i=1,2,…,k. Thus the frequency associated with the interval xi,x i+1 is fi, and G01ADF assumes that all the values in this interval are concentrated at the point
yi=x i+1+xi/2,  i=1,2,…,k-1.
The following quantities are calculated:
(a) total frequency,
n=∑i= 1 k- 1 fi.
(b) mean,
y-=∑i=1 k-1 fiyi n.
(c) standard deviation,
s 2=∑i= 1 k- 1 fi yi-y- 2 n- 1 ,   n≥ 2.
(d) coefficient of skewness,
s 3=∑i=1 k-1 fi yi-y- 3 n-1×s 23 ,  n≥2.
(e) coefficient of kurtosis,
s 4=∑i= 1 k- 1 fi yi-y- 4 n- 1×s 24 - 3,   n≥ 2.
The routine has been developed primarily for groupings of a continuous variable. If, however, the routine is to be used on the frequency distribution of a discrete variable, taking the values y 1,…,y k-1, then the boundary values for the classes may be defined as follows:
(i) for k>2,
x 1=3 y 1-y 2/2 xj=y j-1+yj/2, j=2,…,k-1 xk=3 y k-1-y k-2/2
(ii) for k=2,
x 1=y 1-a   and   x 2=y 1+a   for any ​a>0 .

4 References

None.

5 Arguments

1:   K – INTEGERInput
On entry: k, the number of class boundaries, which is one more than the number of classes of the frequency distribution.
Constraint: K>1.
2:   X K – REAL (KIND=nag_wp) arrayInput
On entry: the elements of X must contain the boundary values of the classes in ascending order, so that class i is bounded by the values in X i and X i+1, for i=1,2,…,k-1.
Constraint: X i<X i+1, for i=1,2,…,k-1.
3:   IFREQ K – INTEGER arrayInput
On entry: the ith element of IFREQ must contain the frequency associated with the ith class, for i=1,2,…,k-1. IFREQ k is not used by the routine.
Constraints:
  • IFREQ i≥0, for i=1,2,…,k-1;
  • ∑i=1 k-1 IFREQ i>0.
4:   XMEAN – REAL (KIND=nag_wp)Output
On exit: the mean value, y-.
5:   S2 – REAL (KIND=nag_wp)Output
On exit: the standard deviation, s 2.
6:   S3 – REAL (KIND=nag_wp)Output
On exit: the coefficient of skewness, s 3.
7:   S4 – REAL (KIND=nag_wp)Output
On exit: the coefficient of kurtosis, s 4.
8:   N – INTEGEROutput
On exit: the total frequency, n.
9:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, K≤1.
IFAIL=2
On entry, the boundary values of the classes in X are not in ascending order.
IFAIL=3
On entry, ∑i=1 k-1 IFREQ i=0 or IFREQ i<0 for some i, for i=1,2,…,k-1.
IFAIL=4
The total frequency, n, is less than 2, hence the quantities s 2, s 3 and s 4 cannot be calculated.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

The method used is believed to be stable.

8 Parallelism and Performance

G01ADF is not threaded in any implementation.

9 Further Comments

The time taken by G01ADF increases linearly with k.

10 Example

In the example program, NPROB determines the number of sets of data to be analysed. For each analysis, the boundary values of the classes and the frequencies are read. After G01ADF has been successfully called, the input data and calculated quantities are printed. In the example, there is one set of data, with 14 classes.

10.1 Program Text

Program Text (g01adfe.f90)

10.2 Program Data

Program Data (g01adfe.d)

10.3 Program Results

Program Results (g01adfe.r)

G01 Chapter Contents
G01 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


G01AEF : NAG Library, Mark 26

G01 Chapter Contents
G01 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

G01AEF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

G01AEF constructs a frequency distribution of a variable, according to either user-supplied, or routine-calculated class boundary values.

2 Specification

SUBROUTINE G01AEF ( N, K, X, ICLASS, CB, IFREQ, XMIN, XMAX, IFAIL)
INTEGER | N, K, ICLASS, IFREQ(K), IFAIL
REAL (KIND=nag_wp) | X(N), CB(K), XMIN, XMAX

3 Description

The data consists of a sample of n observations of a continuous variable, denoted by xi, for i=1,2,…,n. Let a = min x 1,…,xn and b = max x 1,…,xn .
G01AEF constructs a frequency distribution with k>1 classes denoted by fi, for i=1,2,…,k.
The boundary values may be either user-supplied, or routine-calculated, and are denoted by yj, for j=1,2,…,k-1.
If the boundary values of the classes are to be routine-calculated, then they are determined in one of the following ways:
(a) | if k>2, the range of x values is divided into k-2 intervals of equal length, and two extreme intervals, defined by the class boundary values y 1,y 2,…,y k-1;
(b) | if k=2, y 1=12 a+b.
However formed, the values y 1,…,y k-1 are assumed to be in ascending order. The class frequencies are formed with
  • f 1= the number of x values in the interval -∞,y 1
  • fi= the number of x values in the interval y i-1,yi ,  i=2,…,k-1
  • fk= the number of x values in the interval y k-1,∞ ,
where [ means inclusive, and ) means exclusive. If the class boundary values are routine-calculated and k>2, then f 1=fk=0, and y 1 and y k-1 are chosen so that y 1<a and y k-1>b.
If a frequency distribution is required for a discrete variable, then it is suggested that you supply the class boundary values; routine-calculated boundary values may be slightly imprecise (due to the adjustment of y 1 and y k-1 outlined above) and cause values very close to a class boundary to be assigned to the wrong class.

4 References

None.

5 Arguments

1:   N – INTEGERInput
On entry: n, the number of observations.
Constraint: N≥1.
2:   K – INTEGERInput
On entry: k, the number of classes desired in the frequency distribution. Whether or not class boundary values are user-supplied, K must include the two extreme classes which stretch to ±∞.
Constraint: K≥2.
3:   X N – REAL (KIND=nag_wp) arrayInput
On entry: the sample of observations of the variable for which the frequency distribution is required, xi, for i=1,2,…,n. The values may be in any order.
4:   ICLASS – INTEGERInput
On entry: indicates whether class boundary values are to be calculated within G01AEF, or are supplied by you.
If ICLASS=0, then the class boundary values are to be calculated within the routine.
If ICLASS=1, they are user-supplied.
Constraint: ICLASS=0 or 1.
5:   CB K – REAL (KIND=nag_wp) arrayInput/Output
On entry: if ICLASS=0, then the elements of CB need not be assigned values, as G01AEF calculates k-1 class boundary values.
If ICLASS=1, the first k-1 elements of CB must contain the class boundary values you supplied, in ascending order.
In both cases, the element CB k need not be assigned, as it is not used in the routine.
On exit: the first k-1 elements of CB contain the class boundary values in ascending order.
Constraint: if ICLASS=1, CB i<CB i+1, for i=1,2,…,k-2.
6:   IFREQ K – INTEGER arrayOutput
On exit: the elements of IFREQ contain the frequencies in each class, fi, for i=1,2,…,k. In particular IFREQ 1 contains the frequency of the class up to CB 1, f 1, and IFREQ k contains the frequency of the class greater than CB k-1, fk.
7:   XMIN – REAL (KIND=nag_wp)Output
On exit: the smallest value in the sample, a.
8:   XMAX – REAL (KIND=nag_wp)Output
On exit: the largest value in the sample, b.
9:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, K<2.
IFAIL=2
On entry, N<1.
IFAIL=3
On entry, the user-supplied class boundary values are not in ascending order.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

The method used is believed to be stable.

8 Parallelism and Performance

G01AEF is not threaded in any implementation.

9 Further Comments

The time taken by G01AEF increases with K and N. It also depends on the distribution of the sample observations.

10 Example

This example summarises a number of datasets. For each dataset the sample observations and optionally class boundary values are read. G01AEF is then called and the frequency distribution and largest and smallest observations printed.

10.1 Program Text

Program Text (g01aefe.f90)

10.2 Program Data

Program Data (g01aefe.d)

10.3 Program Results

Program Results (g01aefe.r)

G01 Chapter Contents
G01 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


G01AFF : NAG Library, Mark 26

G01 Chapter Contents
G01 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

G01AFF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

G01AFF performs the analysis of a two-way r×c contingency table or classification. If r=c=2, and the total number of objects classified is 40 or fewer, then the probabilities for Fisher's exact test are computed. Otherwise, a test statistic is computed (with Yates' correction when r=c=2), which under the assumption of no association between the classifications has approximately a chi-square distribution with r-1×c-1 degrees of freedom.

2 Specification

SUBROUTINE G01AFF ( LDNOB, LDPRED, M, N, NOBS, NUM, PRED, CHIS, P, NPOS, NDF, M1, N1, IFAIL)
INTEGER | LDNOB, LDPRED, M, N, NOBS(LDNOB,N), NUM, NPOS, NDF, M1, N1, IFAIL
REAL (KIND=nag_wp) | PRED(LDPRED,N), CHIS, P(21)

3 Description

The data consist of the frequencies for the two-way classification, denoted by n ij, for i=1,2,…,m and j=1,2,…,n with m,n>1.
A check is made to see whether any row or column of the matrix of frequencies consists entirely of zeros, and if so, the matrix of frequencies is reduced by omitting that row or column. Suppose the final size of the matrix is m 1 by n 1 (m 1,n 1>1), and let
  • Ri=∑j=1 n 1 n ij, the total frequency for the ith row, for i=1,2,…,m 1,
  • Cj=∑i=1 m 1 n ij, the total frequency for the jth column, for j=1,2,…,n 1, and
  • T=∑i=1 m 1 Ri=∑j=1 n 1 Cj, the total frequency.
There are two situations:
(i) If m 1>2 and/or n 1>2, or m 1=n 1=2 and T>40, then the matrix of expected frequencies, denoted by r ij, for i=1,2,…,m 1 and j=1,2,…,n 1, and the test statistic, χ 2, are computed, where
r ij=RiCj/T,  i=1,2,…,m 1;j=1,2,…,n 1
and
χ 2=∑i= 1 m 1∑j= 1 n 1 r ij-n ij-Y 2/r ij,
where
Y= 12  if ​ m 1=n 1=2 0  otherwise
is Yates' correction for continuity.
Under the assumption that there is no association between the two classifications, χ 2 will have approximately a chi-square distribution with m 1-1×n 1-1 degrees of freedom.
An option exists which allows for further ‘shrinkage’ of the matrix of frequencies in the case where r ij<1 for the (i,j)th cell. If this is the case, then row i or column j will be combined with the adjacent row or column with smaller total. Row i is selected for combination if Ri×m 1≤Cj×n 1. This ‘shrinking’ process is continued until r ij≥1 for all cells (i,j).
(ii) If m 1=n 1=2 and T≤40, the probabilities to enable Fisher's exact test to be made are computed.
The matrix of frequencies may be rearranged so that R 1 is the smallest marginal (i.e., column and row) total, and C 2≥C 1. Under the assumption of no association between the classifications, the probability of obtaining r entries in cell 1,1 is computed where
P r+1=R 1!R 2!C 1!C 2! T!r!R 1-r!C 1-r!T-C 1-R 1+r! ,  r=0,1,…,R 1.
The probability of obtaining the table of given frequencies is returned. A test of the assumption against some alternative may then be made by summing the relevant values of Pr.

4 References

None.

5 Arguments

1:   LDNOB – INTEGERInput
On entry: the first dimension of the array NOBS as declared in the (sub)program from which G01AFF is called.
Constraint: LDNOB≥M.
2:   LDPRED – INTEGERInput
On entry: the first dimension of the array PRED as declared in the (sub)program from which G01AFF is called.
Constraint: LDPRED≥M.
3:   M – INTEGERInput
On entry: m+1, one more than the number of rows of the frequency matrix.
Constraint: M>2.
4:   N – INTEGERInput
On entry: n+1, one more than the number of columns of the frequency matrix.
Constraint: N>2.
5:   NOBS LDNOBN – INTEGER arrayInput/Output
On entry: the elements NOBS ij, for i=1,2,…,m and j=1,2,…,n, must contain the frequencies for the two-way classification. The m+1th row and the n+1th column of NOBS need not be set.
On exit: contains the following information:
  • NOBS ij, for i=1,2,…,m 1 and j=1,2,…,n 1, contain the frequencies for the two-way classification after ‘shrinkage’ has taken place (see Section 3).
  • NOBS i n+1, for i=1,2,…,m 1, contain the total frequencies in the remaining rows, Ri.
  • NOBS m+1 j, for j=1,2,…,n 1, contain the total frequencies in the remaining columns, Cj.
  • NOBS m+1n+1, contains the total frequency, T.
If any ‘shrinkage’ has occurred, then all other cells contain no useful information.
Constraint: NOBS ij≥0, for i=1,2,…,M-1 and j=1,2,…,N-1.
6:   NUM – INTEGERInput/Output
On entry: the value assigned to NUM must determine whether automatic ‘shrinkage’ is required when any r ij<1, as outlined in Section 3 (i).
If NUM=1, shrinkage is required, otherwise shrinkage is not required.
On exit: when Fisher's exact test for a 2×2 classification is used then NUM contains the number of elements used in the array P, otherwise NUM is set to zero.
7:   PRED LDPREDN – REAL (KIND=nag_wp) arrayOutput
On exit: the elements PRED ij, where i=1,2,…,M1 and j=1,2,…,N1 contain the expected frequencies, r ij corresponding to the observed frequencies NOBS ij, except in the case when Fisher's exact test for a 2×2 classification is to be used, when PRED is not used. No other elements are utilized.
8:   CHIS – REAL (KIND=nag_wp)Output
On exit: the value of the test statistic, χ 2, except when Fisher's exact test for a 2×2 classification is used in which case it is unspecified.
9:   P 21 – REAL (KIND=nag_wp) arrayOutput
P is used only when Fisher's exact test for a 2×2 classification is to be used.
On exit: the first NUM elements contain the probabilities associated with the various possible frequency tables, Pr, for r=0,1,…,R 1, the remainder are unspecified.
10:   NPOS – INTEGEROutput
NPOS is used only when Fisher's exact test for a 2×2 classification is to be used.
On exit: P NPOS holds the probability associated with the given table of frequencies.
11:   NDF – INTEGEROutput
On exit: the value of NDF gives the number of degrees of freedom for the chi-square distribution, m 1-1×n 1-1; when Fisher's exact test is used NDF=1.
12:   M1 – INTEGEROutput
On exit: the number of rows of the two-way classification, after any ‘shrinkage’, m 1.
13:   N1 – INTEGEROutput
On exit: the number of columns of the two-way classification, after any ‘shrinkage’, n 1.
14:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
The number of rows or columns of NOBS is less than 2, possibly after shrinkage.
IFAIL=2
At least one frequency is negative, or all frequencies are zero.
IFAIL=4
On entry, | LDPRED<M,
or | LDNOB<M.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

The method used is believed to be stable.

8 Parallelism and Performance

G01AFF is not threaded in any implementation.

9 Further Comments

The time taken by G01AFF will increase with M and N, except when Fisher's exact test is to be used, in which case it increases with size of the marginal and total frequencies.
If, on exit, NUM>0, or alternatively NDF is 1 and NOBS MN≤40, the probabilities for use in Fisher's exact test for a 2×2 classification will be calculated, and not the test statistic with approximately a chi-square distribution.

10 Example

In the example program, NPROB determines the number of two-way classifications to be analysed. For each classification the frequencies are read, G01AFF called, and information given on how much ‘shrinkage’ has taken place. If Fisher's exact test is to be used, the given frequencies and the array of probabilities associated with the possible frequency tables are printed. Otherwise, if the chi-square test is to be used, the given and expected frequencies, and the test statistic with its degrees of freedom are printed. In the example, there is one 2×3 classification, with shrinkage not requested.

10.1 Program Text

Program Text (g01affe.f90)

10.2 Program Data

Program Data (g01affe.d)

10.3 Program Results

Program Results (g01affe.r)

G01 Chapter Contents
G01 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


G01AGF : NAG Library, Mark 26

G01 Chapter Contents
G01 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

G01AGF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

G01AGF performs a scatter plot of two variables on a character printing device, with a chosen number of character positions in each direction.

2 Specification

SUBROUTINE G01AGF ( X, Y, NOBS, ISORT, NSTEPX, NSTEPY, IFAIL)
INTEGER | NOBS, ISORT(NOBS), NSTEPX, NSTEPY, IFAIL
REAL (KIND=nag_wp) | X(NOBS), Y(NOBS)

3 Description

G01AGF finds the range of the data in each dimension and calculates a step size for each division on the axes; these step sizes are selected from the list
0.1,0.15,0.2,0.25,0.4,0.5,0.6,0.75,0.8 × power of ​ 10 .
The axes are drawn and annotated and data points are plotted on the nearest character position. The character plotted is either a digit 1 to 9 for the equivalent number of occurrences of a point at a particular character position, an alphabetic A–Z for 10–35 occurrences, or * if there are more than 35 coincident occurrences. Axes are drawn on all sides of the plot with the left-hand and bottom ones annotated; zero axes are also marked if included in the plotting area.
The Fortran logical unit number used for the output is the current advisory message unit number defined for each implementation. This number may be changed by an appropriate call to X04ABF before calling G01AGF.

4 References

None.

5 Arguments

1:   X NOBS – REAL (KIND=nag_wp) arrayInput
On entry: the values to be plotted in the x-direction.
2:   Y NOBS – REAL (KIND=nag_wp) arrayInput/Output
On entry: the values to be plotted in the y-direction.
On exit: the elements of Y are sorted into descending order of magnitude.
3:   NOBS – INTEGERInput
On entry: the number of observations to be plotted.
Constraint: NOBS≥1.
4:   ISORT NOBS – INTEGER arrayOutput
On exit: the key to the descending order of the elements in array Y, i.e., ISORT i contains the position of the value Y i in the original array Y, for i=1,2,…,NOBS.
5:   NSTEPX – INTEGERInput
On entry: the number of steps (character positions) to be plotted in the x-direction. If the supplied value of NSTEPX is less than 10, the value 10 will be used by G01AGF. The maximum value for NSTEPX is the number of character positions available on the chosen output device less 15, up to a maximum of 133. If NSTEPX exceeds 133 on input, the value 133 will be used by the routine.
6:   NSTEPY – INTEGERInput
On entry: the number of steps (character positions) to be plotted in the y-direction. If the supplied value of NSTEPY is less than 10, the value 10 will be used by G01AGF. There is no maximum value for NSTEPY, but you should bear in mind that NSTEPY+5 records (lines) of output are generated by the routine.
7:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, NOBS<1.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

Accuracy is limited by the number of plotting points available.

8 Parallelism and Performance

G01AGF is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The time taken by G01AGF may be expected to be approximately proportional to the product NOBS×NSTEPX×NSTEPY.
No blank records are output before or after the plot.
You must make sure that it is permissible to write records containing NSTEPX characters to the current advisory message unit.

10 Example

The data relate to wheat and potato yields in 48 counties in England in 1936. The example illustrates the use of X04ABF to set the logical unit number, used for the output of G01AGF, to a specified value.

10.1 Program Text

Program Text (g01agfe.f90)

10.2 Program Data

Program Data (g01agfe.d)

10.3 Program Results

Program Results (g01agfe.r)

G01 Chapter Contents
G01 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


G01AHF : NAG Library, Mark 26

G01 Chapter Contents
G01 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

G01AHF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

G01AHF performs a Normal probability plot on a character printing device, with a chosen number of character positions in each direction.

2 Specification

SUBROUTINE G01AHF ( X, NOBS, NSTEPX, NSTEPY, ISTAND, IWORK, WORK, LWORK, XSORT, XBAR, XSTD, IFAIL)
INTEGER | NOBS, NSTEPX, NSTEPY, ISTAND, IWORK(NOBS), LWORK, IFAIL
REAL (KIND=nag_wp) | X(NOBS), WORK(LWORK), XSORT(NOBS), XBAR, XSTD

3 Description

In a Normal probability plot, the data x are plotted against Normal scores y. The degree of linearity in the resultant plot provides a visual indication of the Normality of distribution of a set of residuals from some fitting process, such as multiple regression.
The data values are sorted into descending order prior to plotting, and may also be standardized to zero mean and unit standard deviation, if requested.
The plot is produced on a character printing device, using a chosen number of character positions in each direction. The output is directed to the current advisory message unit number (see the Users' Note for your implementation). This number may be changed by an appropriate call to X04ABF before calling G01AHF.
Axes are drawn and annotated and data points are plotted on the nearest character position. An appropriate step size for each axis is computed from the list
  • 0.1,0.15,0.2,0.25,0.4,0.5,0.6,0.75,0.8× power of 10.
Points are plotted using the digits 1 to 9 to indicate the equivalent number of observations at a particular character position, a letter A–Z for 10–35 occurrences, or * if there are 36 or more coincident occurrences. Zero axes are marked if included in the plotting area.

4 References

None.

5 Arguments

1:   X NOBS – REAL (KIND=nag_wp) arrayInput
On entry: the vector of data values.
Constraint: all data values must not be equal.
2:   NOBS – INTEGERInput
On entry: the number of data values.
Constraint: NOBS≥2.
3:   NSTEPX – INTEGERInput
On entry: the number of steps (character positions) to be plotted in the x-direction. If the supplied value of NSTEPX is less than 10, the value 10 will be used by G01AHF. The maximum value for NSTEPX is the number of character positions available on the chosen output device less 15, up to a maximum of 133. If NSTEPX exceeds 133 on input, the value 133 will be used by the routine.
4:   NSTEPY – INTEGERInput
On entry: the number of steps (character positions) to be plotted in the y-direction. If the supplied value of NSTEPY is less than 10, the value 10 will be used by G01AHF. There is no maximum value for NSTEPY, but you should bear in mind that (NSTEPY+5) records (lines) of output are generated by the routine.
5:   ISTAND – INTEGERInput
On entry: indicates whether the residuals are to be standardized prior to plotting.
If ISTAND>0, the elements of X are standardized to zero mean and unit standard deviation.
6:   IWORK NOBS – INTEGER arrayWorkspace
7:   WORK LWORK – REAL (KIND=nag_wp) arrayOutput
On exit: the first NOBS elements of WORK contain the Normal scores in ascending magnitude. The rest of the array is used as workspace.
8:   LWORK – INTEGERInput
On entry: the dimension of the array WORK as declared in the (sub)program from which G01AHF is called.
Constraint: LWORK≥5×NOBS/2.
9:   XSORT NOBS – REAL (KIND=nag_wp) arrayOutput
On exit: the data values, sorted into descending order, and standardized if ISTAND was positive on entry.
10:   XBAR – REAL (KIND=nag_wp)Output
On exit: the mean of the data values.
11:   XSTD – REAL (KIND=nag_wp)Output
On exit: the standard deviation of the data values.
12:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, NOBS<2.
IFAIL=2
All the supplied data values are equal.
IFAIL=3
On entry, LWORK<5×NOBS/2, i.e., the array WORK is too small.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

Accuracy is limited by the number of plotting positions available.

8 Parallelism and Performance

G01AHF is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

For details of timing see G01AGF and G01DAF.
No blank records are output before or after the plot.
You must make sure that it is permissible to write records containing NSTEPX characters to the current advisory message unit.

10 Example

The data are residuals from a linear regression. The 25 values are standardized and plotted against the Normal scores, and are seen to follow a straight line fairly closely, indicating that Normality assumptions are justified.

10.1 Program Text

Program Text (g01ahfe.f90)

10.2 Program Data

Program Data (g01ahfe.d)

10.3 Program Results

Program Results (g01ahfe.r)

G01 Chapter Contents
G01 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


G01AJF : NAG Library, Mark 26

G01 Chapter Contents
G01 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

G01AJF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

G01AJF prints a histogram on a character printing device, allowing you control over size, positioning, and the range of data values included.

2 Specification

SUBROUTINE G01AJF ( X, N, NSTEPX, NSTEPY, ITYPE, ISPACE, XMIN, XMAX, XSTEP, N1, MULTY, IFAIL)
INTEGER | N, NSTEPX, NSTEPY, ITYPE, ISPACE, N1, MULTY, IFAIL
REAL (KIND=nag_wp) | X(N), XMIN, XMAX, XSTEP

3 Description

A histogram is printed using vertical bars consisting of * characters. The output is directed to the current advisory message unit (see the Users' Note for your implementation). It may be redirected by a call to X04ABF before calling G01AJF.
The following options are available:
(a) | inclusion of all data values, or only of those lying within a specified range;
(b) | specification of the size of the histogram in the vertical and horizontal directions, and of positioning in the horizontal direction;
(c) | calculation of frequencies or cumulative frequencies in the histogram.
The maximum and minimum data values used, the (integral) number of observations represented by each * in the histogram, and the step size per character position in the horizontal direction, are returned.
The histogram is headed FREQUENCY or CUM.FREQ. depending on the option selected. Each line is annotated with the minimum frequency which a bar reaching that line represents. The data maximum and minimum are printed under the histogram, unless either exceeds 9999.99 in modulus, in which case they are not printed (although they are still returned).

4 References

None.

5 Arguments

1:   X N – REAL (KIND=nag_wp) arrayInput
On entry: the data values.
2:   N – INTEGERInput
On entry: the number of data values.
Constraint: N≥1.
3:   NSTEPX – INTEGERInput/Output
On entry: the number of character positions to be used in the horizontal direction, i.e., the number of categories in the histogram.
On exit: if NSTEPX<10 on entry, NSTEPX is reset to 10.
If NSTEPX>99 on entry, NSTEPX is reset to 99.
Otherwise, NSTEPX is unchanged on exit.
4:   NSTEPY – INTEGERInput/Output
On entry: the number of character positions to be used in the vertical direction, i.e., the maximum height of a histogram bar.
On exit: if NSTEPY<10 on entry, NSTEPY is reset to 10.
If NSTEPY>99 on entry, NSTEPY is reset to 99.
Otherwise, NSTEPY is unchanged on exit.
5:   ITYPE – INTEGERInput
On entry: indicates whether a histogram of frequencies or cumulative frequencies is required.
ITYPE=0 for frequencies.
ITYPE≠0 for cumulative frequencies.
The second option effectively displays the distribution function of the data rather than the density function.
6:   ISPACE – INTEGERInput/Output
On entry: indicates how many spaces are to be inserted at the beginning of each output line.
If ISPACE<0 on input, ISPACE=0 is used
If ISPACE+NSTEPX+14>120, then ISPACE=0 is used.
The second condition imposes an effective line length limit of 120 characters.
On exit: unchanged unless ISPACE<0 or ISPACE+NSTEPX+14>120, in which case ISPACE is set to 0.
7:   XMIN – REAL (KIND=nag_wp)Input/Output
8:   XMAX – REAL (KIND=nag_wp)Input/Output
On entry: if XMIN<XMAX, only those values in X such that XMIN≤X i≤XMAX, for i=1,2,…,n, are included in the histogram.
If XMIN≥XMAX, all the data are included.
On exit: if XMIN<XMAX on entry, then XMIN and XMAX are unchanged.
If XMIN≥XMAX then XMIN and XMAX contain the minimum and maximum data values respectively.
9:   XSTEP – REAL (KIND=nag_wp)Output
On exit: the width of each class interval.
10:   N1 – INTEGEROutput
On exit: the total number of observations actually included in the histogram.
11:   MULTY – INTEGEROutput
On exit: the number of observations represented by each * in the histogram.
12:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, N<1.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

Accuracy is limited by the number of plotting positions available.

8 Parallelism and Performance

G01AJF is not threaded in any implementation.

9 Further Comments

The time taken by G01AJF increases with N, NSTEPX and NSTEPY.
A total of NSTEPX+ISPACE+14 character positions are used in the horizontal direction, not including the carriage control character. It is important that this total does not exceed the maximum line length available on the output device.
A total of NSTEPY+3 output lines are normally generated, one less if XMIN and/or XMAX is too large in modulus to be printed.

10 Example

A sample of 50 random numbers form the data, which correspond to a Normal distribution with mean and standard deviation both equal to 5.0. A histogram of the entire sample is drawn first, followed by a cumulative histogram of all data values lying between -10.0 and 5.0. The first histogram is indented 10 character positions. Note the use of X04ABF to direct the output to unit number 6.

10.1 Program Text

Program Text (g01ajfe.f90)

10.2 Program Data

Program Data (g01ajfe.d)

10.3 Program Results

Program Results (g01ajfe.r)

G01 Chapter Contents
G01 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


G01ALF : NAG Library, Mark 26

G01 Chapter Contents
G01 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

G01ALF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

G01ALF calculates a five-point summary for a single sample.

2 Specification

SUBROUTINE G01ALF ( N, X, IWRK, RES, IFAIL)
INTEGER | N, IWRK(N), IFAIL
REAL (KIND=nag_wp) | X(N), RES(5)

3 Description

G01ALF calculates the minimum, lower hinge, median, upper hinge and the maximum of a sample of n observations.
The data consist of a single sample of n observations denoted by xi and let zi, for i=1,2,…,n, represent the sample observations sorted into ascending order.
Let m= n 2 if n is even and n+1 2 if n is odd,
and k= m 2 if m is even and m+1 2 if m is odd.
Then we have
Minimum | =z 1, |
Maximum | =zn, |
Median | =zm | if n is odd,
 | = zm+z m+1 2 | if n is even, 12
Lower hinge | =zk | if m is odd,
 | = zk+z k+1 2 | if m is even, 12
Upper hinge | =z n-k+1 | if m is odd,
 | = z n-k+z n-k+1 2 | if m is even. 12

4 References

Erickson B H and Nosanchuk T A (1985) Understanding Data Open University Press, Milton Keynes
Tukey J W (1977) Exploratory Data Analysis Addison–Wesley

5 Arguments

1:   N – INTEGERInput
On entry: n, number of observations in the sample.
Constraint: N≥5.
2:   X N – REAL (KIND=nag_wp) arrayInput
On entry: the sample observations, x 1,x 2,…,xn.
3:   IWRK N – INTEGER arrayWorkspace
4:   RES 5 – REAL (KIND=nag_wp) arrayOutput
On exit: RES contains the five-point summary.
RES 1
The minimum.
RES 2
The lower hinge.
RES 3
The median.
RES 4
The upper hinge.
RES 5
The maximum.
5:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, N<5.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

The computations are stable.

8 Parallelism and Performance

G01ALF is not threaded in any implementation.

9 Further Comments

The time taken by G01ALF is proportional to n.

10 Example

This example calculates a five-point summary for a sample of 12 observations.

10.1 Program Text

Program Text (g01alfe.f90)

10.2 Program Data

Program Data (g01alfe.d)

10.3 Program Results

Program Results (g01alfe.r)

G01 Chapter Contents
G01 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


G01AMF : NAG Library, Mark 26

G01 Chapter Contents
G01 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

G01AMF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

G01AMF finds specified quantiles from a vector of unsorted data.

2 Specification

SUBROUTINE G01AMF ( N, RV, NQ, Q, QV, IFAIL)
INTEGER | N, NQ, IFAIL
REAL (KIND=nag_wp) | RV(N), Q(NQ), QV(NQ)

3 Description

A quantile is a value which divides a frequency distribution such that there is a given proportion of data values below the quantile. For example, the median of a dataset is the 0.5 quantile because half the values are less than or equal to it; and the 0.25 quantile is the 25th percentile.
G01AMF uses a modified version of Singleton's ‘median-of-three’ Quicksort algorithm (Singleton (1969)) to determine specified quantiles of a vector of real values. The input vector is partially sorted, as far as is required to compute desired quantiles; for a single quantile, this is much faster than sorting the entire vector. Where necessary, linear interpolation is also carried out to return the values of quantiles which lie between two data points.

4 References

Singleton R C (1969) An efficient algorithm for sorting with minimal storage: Algorithm 347 Comm. ACM 12 185–187

5 Arguments

1:   N – INTEGERInput
On entry: the number of elements in the input vector RV.
Constraint: N>0.
2:   RV N – REAL (KIND=nag_wp) arrayInput/Output
On entry: the vector whose quantiles are to be determined.
On exit: the order of the elements in RV is not, in general, preserved.
3:   NQ – INTEGERInput
On entry: the number of quantiles requested.
Constraint: NQ>0.
4:   Q NQ – REAL (KIND=nag_wp) arrayInput
On entry: the quantiles to be calculated, in ascending order. Note that these must be between 0.0 and 1.0, with 0.0 returning the smallest element and 1.0 the largest.
Constraints:
  • 0.0≤Q i≤1.0, for i=1,2,…,NQ;
  • Q i≤Q i+1, for i=1,2,…,NQ-1.
5:   QV NQ – REAL (KIND=nag_wp) arrayOutput
On exit: QV i contains the quantile specified by the value provided in Q i, or an interpolated value if the quantile falls between two data values.
6:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, N=value.
Constraint: N>0.
IFAIL=2
On entry, NQ=value.
Constraint: NQ>0.
IFAIL=3
On entry, an element of Q was less than 0.0 or greater than 1.0.
IFAIL=4
On entry, Q was not in ascending order.
IFAIL=5
Internal error. Please contact NAG.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

Not applicable.

8 Parallelism and Performance

G01AMF is not threaded in any implementation.

9 Further Comments

The average time taken by G01AMF is approximately proportional to N×1+log NQ. The worst case time is proportional to N 2 but this is extremely unlikely to occur.

10 Example

This example computes a list of quantiles from an array of reals and an array of point values.

10.1 Program Text

Program Text (g01amfe.f90)

10.2 Program Data

Program Data (g01amfe.d)

10.3 Program Results

Program Results (g01amfe.r)

G01 Chapter Contents
G01 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


G01ANF : NAG Library, Mark 26

G01 Chapter Contents
G01 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

G01ANF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

G01ANF finds approximate quantiles from a data stream of known size using an out-of-core algorithm.

2 Specification

SUBROUTINE G01ANF ( IND, N, RV, NB, EPS, NP, Q, QV, NQ, RCOMM, LRCOMM, ICOMM, LICOMM, IFAIL)
INTEGER | IND, N, NB, NP, NQ, LRCOMM, ICOMM(LICOMM), LICOMM, IFAIL
REAL (KIND=nag_wp) | RV(*), EPS, Q(*), QV(*), RCOMM(LRCOMM)

3 Description

A quantile is a value which divides a frequency distribution such that there is a given proportion of data values below the quantile. For example, the median of a dataset is the 0.5 quantile because half the values are less than or equal to it.
G01ANF uses a slightly modified version of an algorithm described in a paper by Zhang and Wang (2007) to determine ε-approximate quantiles of a data stream of n real values, where n is known. Given any quantile q∈0.0,1.0, an ε-approximate quantile is defined as an element in the data stream whose rank falls within q-ε n,q+ε n . In case of more than one ε-approximate quantile being available, the one closest to qn is returned.

4 References

Zhang Q and Wang W (2007) A fast algorithm for approximate quantiles in high speed data streams Proceedings of the 19th International Conference on Scientific and Statistical Database Management IEEE Computer Society 29

5 Arguments

1:   IND – INTEGERInput/Output
On entry: indicates the action required in the current call to G01ANF.
IND=0
Return the required length of RCOMM and ICOMM in ICOMM 1 and ICOMM 2 respectively. N and EPS must be set and LICOMM must be at least 2.
IND=1
Initialise the communication arrays and process the first NB values from the data stream as supplied in RV.
IND=2
Process the next block of NB values from the data stream. The calling program must update RV and (if required) NB, and re-enter G01ANF with all other parameters unchanged.
IND=3
Calculate the NQ ε-approximate quantiles specified in Q. The calling program must set Q and NQ and re-enter G01ANF with all other parameters unchanged. This option can be chosen only when NP≥exp 1.0/EPS.
On exit: indicates output from a successful call.
IND=1
Lengths of RCOMM and ICOMM have been returned in ICOMM 1 and ICOMM 2 respectively.
IND=2
G01ANF has processed NP data points and expects to be called again with additional data (i.e., NP<N).
IND=3
G01ANF has returned the requested ε-approximate quantiles in QV. These quantiles are based on NP data points.
IND=4
Routine has processed all N data points (i.e., NP=N).
Constraint: on entry IND=0, 1, 2 or 3.
2:   N – INTEGERInput
On entry: n, the total number of values in the data stream.
Constraint: N>0.
3:   RV* – REAL (KIND=nag_wp) arrayInput
Note: the dimension of the array RV must be at least NB if IND=1 or 2.
On entry: if IND=1 or 2, the vector containing the current block of data, otherwise RV is not referenced.
4:   NB – INTEGERInput
On entry: if IND=1 or 2, the size of the current block of data. The size of blocks of data in array RV can vary; therefore NB can change between calls to G01ANF.
Constraint: if IND=1 or 2, NB>0.
5:   EPS – REAL (KIND=nag_wp)Input
On entry: approximation factor ε.
Constraint: EPS≥exp 1.0/N ​ and ​EPS≤1.0.
6:   NP – INTEGEROutput
On exit: the number of elements processed so far.
7:   Q* – REAL (KIND=nag_wp) arrayInput
Note: the dimension of the array Q must be at least NQ if IND=3.
On entry: if IND=3, the quantiles to be calculated, otherwise Q is not referenced. Note that Q i=0.0, corresponds to the minimum value and Q i=1.0 to the maximum value.
Constraint: if IND=3, 0.0≤Q i≤1.0, for i=1,2,…,NQ.
8:   QV* – REAL (KIND=nag_wp) arrayOutput
Note: the dimension of the array QV must be at least NQ if IND=3.
On exit: if IND=3, QV i contains the ε-approximate quantiles specified by the value provided in Q i.
9:   NQ – INTEGERInput
On entry: if IND=3, the number of quantiles requested, otherwise NQ is not referenced.
Constraint: if IND=3, NQ>0.
10:   RCOMM LRCOMM – REAL (KIND=nag_wp) arrayCommunication Array
11:   LRCOMM – INTEGERInput
On entry: the dimension of the array RCOMM as declared in the (sub)program from which G01ANF is called.
Constraint: if IND≠0, LRCOMM must be at least equal to the value returned in ICOMM 1 by a call to G01ANF with IND=0. This will not be more than x+2× min x, x/2.0 + 1 × log 2 N/x+1.0 + 1 , where x= max 1, log EPS×N / EPS .
12:   ICOMM LICOMM – INTEGER arrayCommunication Array
13:   LICOMM – INTEGERInput
On entry: the dimension of the array ICOMM as declared in the (sub)program from which G01ANF is called.
Constraints:
  • if IND=0, LICOMM≥2;
  • otherwise LICOMM must be at least equal to the value returned in ICOMM 2 by a call to G01ANF with IND=0. This will not be more than 2 × x+2 × min x, x/2.0 +1 × y + y + 6 , where x = max 1, log EPS×N / EPS and y = log 2 N/x+1.0 + 1 .
14:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
On exit: IFAIL=0 unless the routine detects an error (see Section 6).
As an out-of-core routine G01ANF will only perform certain argument checks when a data checkpoint (including completion of data input) is signaled. As such it will usually be inappropriate to halt program execution when an error is detected since any errors may be subsequently resolved without losing any processing already carried out. Therefore setting IFAIL to a value of -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, IND=value.
Constraint: IND=0, 1, 2 or 3.
IFAIL=2
On entry, N=value.
Constraint: N>0.
IFAIL=3
On entry, EPS=value.
Constraint: exp 1.0/N≤EPS≤1.0.
IFAIL=4
On entry, IND=1 or 2 and NB=value.
Constraint: if IND=1 or 2 then NB>0.
IFAIL=5
On entry, LICOMM is too small: LICOMM=value.
IFAIL=6
On entry, LRCOMM is too small: LRCOMM=value.
IFAIL=7
Number of data elements streamed, value is not sufficient for a quantile query when EPS=value.
Supply more data or reprocess the data with a higher EPS value.
IFAIL=8
On entry, IND=3 and NQ=value.
Constraint: if IND=3 then NQ>0.
IFAIL=9
On entry, IND=3 and Q value=value.
Constraint: if IND=3 then 0.0≤Q i≤1.0 for all i.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

Not applicable.

8 Parallelism and Performance

G01ANF is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The average time taken by G01ANF is N log 1/ε log εN .

10 Example

This example calculates ε-approximate quantile for q=0.25, 0.5 and 1.0 for a data stream of 60 values. The stream is read in four blocks of varying size.

10.1 Program Text

Program Text (g01anfe.f90)

10.2 Program Data

Program Data (g01anfe.d)

10.3 Program Results

Program Results (g01anfe.r)

G01 Chapter Contents
G01 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


G01APF : NAG Library, Mark 26

G01 Chapter Contents
G01 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

G01APF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

G01APF finds approximate quantiles from a large arbitrary-sized data stream using an out-of-core algorithm.

2 Specification

SUBROUTINE G01APF ( IND, RV, NB, EPS, NP, Q, QV, NQ, RCOMM, LRCOMM, ICOMM, LICOMM, IFAIL)
INTEGER | IND, NB, NP, NQ, LRCOMM, ICOMM(LICOMM), LICOMM, IFAIL
REAL (KIND=nag_wp) | RV(*), EPS, Q(*), QV(*), RCOMM(LRCOMM)

3 Description

A quantile is a value which divides a frequency distribution such that there is a given proportion of data values below the quantile. For example, the median of a dataset is the 0.5 quantile because half the values are less than or equal to it.
G01APF uses a slightly modified version of an algorithm described in a paper by Zhang and Wang (2007) to determine ε-approximate quantiles of a large arbitrary-sized data stream of real values, where ε is a user-defined approximation factor. Let m denote the number of data elements processed so far then, given any quantile q∈0.0,1.0, an ε-approximate quantile is defined as an element in the data stream whose rank falls within q-ε m,q+ε m . In case of more than one ε-approximate quantile being available, the one closest to qm is used.

4 References

Zhang Q and Wang W (2007) A fast algorithm for approximate quantiles in high speed data streams Proceedings of the 19th International Conference on Scientific and Statistical Database Management IEEE Computer Society 29

5 Arguments

1:   IND – INTEGERInput/Output
On initial entry: must be set to 0.
On entry: indicates the action required in the current call to G01APF.
IND=0
Initialize the communication arrays and attempt to process the first NB values from the data stream. EPS, RV and NB must be set and LICOMM must be at least 10.
IND=1
Attempt to process the next block of NB values from the data stream. The calling program must update RV and (if required) NB, and re-enter G01APF with all other parameters unchanged.
IND=2
Continue calculation following the reallocation of either or both of the communication arrays RCOMM and ICOMM.
IND=3
Calculate the NQ ε-approximate quantiles specified in Q. The calling program must set Q and NQ and re-enter G01APF with all other parameters unchanged. This option can be chosen only when NP≥exp 1.0/EPS.
On exit: indicates output from the call.
IND=1
G01APF has processed NP data points and expects to be called again with additional data.
IND=2
Either one or more of the communication arrays RCOMM and ICOMM is too small. The new minimum lengths of RCOMM and ICOMM have been returned in ICOMM 1 and ICOMM 2 respectively. If the new minimum length is greater than the current length then the corresponding communication array needs to be reallocated, its contents preserved and G01APF called again with all other parameters unchanged.
If there is more data to be processed, it is recommended that LRCOMM and LICOMM are made significantly bigger than the minimum to limit the number of reallocations.
IND=3
G01APF has returned the requested ε-approximate quantiles in QV. These quantiles are based on NP data points.
Constraint: IND=0, 1, 2 or 3.
2:   RV* – REAL (KIND=nag_wp) arrayInput
Note: the dimension of the array RV must be at least NB if IND=0, 1 or 2.
On entry: if IND=0, 1 or 2, the vector containing the current block of data, otherwise RV is not referenced.
3:   NB – INTEGERInput
On entry: if IND=0, 1 or 2, the size of the current block of data. The size of blocks of data in array RV can vary; therefore NB can change between calls to G01APF.
Constraint: if IND=0, 1 or 2, NB>0.
4:   EPS – REAL (KIND=nag_wp)Input
On entry: approximation factor ε.
Constraint: EPS>0.0 ​ and ​EPS≤1.0.
5:   NP – INTEGEROutput
On exit: m, the number of elements processed so far.
6:   Q* – REAL (KIND=nag_wp) arrayInput
Note: the dimension of the array Q must be at least NQ if IND=3.
On entry: if IND=3, the quantiles to be calculated, otherwise Q is not referenced. Note that Q i=0.0, corresponds to the minimum value and Q i=1.0 to the maximum value.
Constraint: if IND=3, 0.0≤Q i≤1.0, for i=1,2,…,NQ.
7:   QV* – REAL (KIND=nag_wp) arrayOutput
Note: the dimension of the array QV must be at least NQ if IND=3.
On exit: if IND=3, QV i contains the ε-approximate quantiles specified by the value provided in Q i.
8:   NQ – INTEGERInput
On entry: if IND=3, the number of quantiles requested, otherwise NQ is not referenced.
Constraint: if IND=3, NQ>0.
9:   RCOMM LRCOMM – REAL (KIND=nag_wp) arrayCommunication Array
On entry: if IND=1 or 2 then the first l elements of RCOMM as supplied to G01APF must be identical to the first l elements of RCOMM returned from the last call to G01APF, where l is the value of LRCOMM used in the last call. In other words, the contents of RCOMM must not be altered between calls to this routine. If RCOMM needs to be reallocated then its contents must be preserved. If IND=0 then RCOMM need not be set.
On exit: RCOMM holds information required by subsequent calls to G01APF
10:   LRCOMM – INTEGERInput
On entry: the dimension of the array RCOMM as declared in the (sub)program from which G01APF is called.
Constraints:
  • if IND=0, LRCOMM≥1;
  • otherwise LRCOMM≥ICOMM 1.
11:   ICOMM LICOMM – INTEGER arrayCommunication Array
On entry: if IND=1 or 2 then the first l elements of ICOMM as supplied to G01APF must be identical to the first l elements of ICOMM returned from the last call to G01APF, where l is the value of LICOMM used in the last call. In other words, the contents of ICOMM must not be altered between calls to this routine. If ICOMM needs to be reallocated then its contents must be preserved. If IND=0 then ICOMM need not be set.
On exit: ICOMM 1 holds the minimum required length for RCOMM and ICOMM 2 holds the minimum required length for ICOMM. The remaining elements of ICOMM are used for communication between subsequent calls to G01APF.
12:   LICOMM – INTEGERInput
On entry: the dimension of the array ICOMM as declared in the (sub)program from which G01APF is called.
Constraints:
  • if IND=0, LICOMM≥10;
  • otherwise LICOMM≥ICOMM 2.
13:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
On exit: IFAIL=0 unless the routine detects an error (see Section 6).
As an out-of-core routine G01APF will only perform certain argument checks when a data checkpoint (including completion of data input) is signaled. As such it will usually be inappropriate to halt program execution when an error is detected since any errors may be subsequently resolved without losing any processing already carried out. Therefore setting IFAIL to a value of -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, IND=value.
Constraint: IND=0, 1, 2 or 3.
IFAIL=2
On entry, EPS=value.
Constraint: 0.0<EPS≤1.0.
IFAIL=3
On entry, IND=0, 1 or 2 and NB=value.
Constraint: if IND=0, 1 or 2 then NB>0.
IFAIL=4
On entry, LICOMM=value.
Constraint: LICOMM≥10.
IFAIL=5
On entry, LRCOMM=value.
Constraint: LRCOMM≥1.
IFAIL=6
The contents of ICOMM have been altered between calls to this routine.
IFAIL=7
The contents of RCOMM have been altered between calls to this routine.
IFAIL=8
Number of data elements streamed, value is not sufficient for a quantile query when EPS=value.
Supply more data or reprocess the data with a higher EPS value.
IFAIL=9
On entry, IND=3 and NQ=value.
Constraint: if IND=3 then NQ>0.
IFAIL=10
On entry, IND=3 and Q value=value.
Constraint: if IND=3 then 0.0≤Q i≤1.0 for all i.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

Not applicable.

8 Parallelism and Performance

G01APF is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The average time taken by G01APF scales as NP log 1/ε log εNP .
It is not possible to determine in advance the final size of the communication arrays RCOMM and ICOMM without knowing the size of the dataset. However, if a rough size (n) is known, the speed of the computation can be increased if the sizes of the communication arrays are not smaller than
LRCOMM = log 2 n×EPS+1.0 - 2 × 1.0/EPS +1+x+ 2× min x, x/2.0 +1 × y +1 LICOMM = log 2 n×EPS+1.0 - 2 × 2 × 1.0/EPS +1 + 1 + 2 × x+2× min x, x/2.0 +1 × y + y + 11
where
x= max 1, log⁡ EPS×n / EPS y = log 2 n/x+1.0 +1 .

10 Example

This example computes a list of ε-approximate quantiles. The data is processed in blocks of 20 observations at a time to simulate a situation in which the data is made available in a piecemeal fashion.

10.1 Program Text

Program Text (g01apfe.f90)

10.2 Program Data

Program Data (g01apfe.d)

10.3 Program Results

Program Results (g01apfe.r)

G01 Chapter Contents
G01 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


G01ARF : NAG Library, Mark 26

G01 Chapter Contents
G01 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

G01ARF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

G01ARF produces a stem and leaf display for a single sample of observations.

2 Specification

SUBROUTINE G01ARF ( RANGE, PRT, N, Y, NSTEPX, NSTEPY, UNIT, PLOT, LDPLOT, LINES, SORTY, IWORK, IFAIL)
INTEGER | N, NSTEPX, NSTEPY, LDPLOT, LINES, IWORK(N), IFAIL
REAL (KIND=nag_wp) | Y(N), UNIT, SORTY(N)
CHARACTER(1) | RANGE, PRT, PLOT(LDPLOT,NSTEPX)

3 Description

G01ARF produces a stem and leaf display for a single sample of n observations. The stem and leaf display shows data values separated into the form of a ‘stem’ and a ‘leaf’. For example, a value of 473 could be represented as 47 3 where the stem is 47 and the leaf is 3. The data is scaled using a value known as the ‘leaf digit unit’. In the above example the leaf digit unit would be 1.0.
The following example illustrates a stem and leaf display.
For the 10 observations:
1.8 2.3 2.1 1.9 2.1 2.4 2.0 2.0 1.9 2.1
the stem and leaf display is:
1  1  8
3  1  99
5  2  00
5  2  111
2  2
2  2  3
1  2  4
where the leaf digit unit is 0.1 so that 1 8 represents 1.8 (i.e., 18×0.1). The leaf digit unit distinguishes between the numbers 18.0, 1.8, 0.18, etc. which may otherwise all be represented by 1 8.
Included in the above display is an initial column specifying the cumulative count of values, up to and including that particular line, from either the top or bottom of the display, whichever is smaller. An exception to this is when the line on which the median lies is reached, in which case the actual count of values on that line is displayed, rather than a cumulative count, and this is highlighted by enclosing the count in parentheses. In this case the median is 2.05 and thus falls between the two lines at which the cumulative count has reached n/2 where n is the number of observations.
Some of the other features of the stem and leaf display are illustrated by the following two examples.
For the 30 observations:
-19.0 -3.0 -1.0 0.0 1.0 2.0 2.0 3.0 3.0 3.0 4.0 4.0 4.0 4.0 4.0 5.0 5.0 5.0 5.0 6.0 6.0 6.0 7.0 7.0 8.0 10.0 11.0 11.0 13.0 31.0
the stem and leaf display may be:
 1   1.  9
 1   1*
 1  -0.
 3  -0*  13
15  +0*  012233344444
15  +0.  55556667788
 5   1*  011
 2   1.  3
 1   2
 1   2.
 1   3   1
In the above display all the data are plotted and the leaf digit unit is 1.0. Also in this display different leaves, that is different digits, may be plotted on a particular line. In this case we have 5 possible digits per line, that is 2 lines per stem, and these are represented as follows:
  • * indicates that the line may contain the digits 0 to 4;
  • . indicates that the line may contain the digits 5 to 9.
Alternatively the stem and leaf display may look like:
      LO   -19

  2   -0*  3
  3   +0T  1
  5   +0*  01
 10   +0T  22333
( 9)  +0F  444445555
 11   +0*  66677
  6   +0T  8
  5    1*  011
  2    1T  3

      HI   31
Again the leaf digit unit is 1.0 but in this display just the data between the fences, which are the hinges ±1 12× the inter-hinge range, are plotted. Any data points that fall outside the fences are presented separately in the display under the headings LO for those points below the lower fence and HI for those points above the upper fence.
Again in this display different leaves, that is different digits, may be plotted on a particular line. However in this case we have 2 possible digits per line, that is 5 lines per stem, and these are represented as follows
  • * indicates that the line may contain the digits 0 or 1;
  • T indicates that the line may contain the digits 2 or 3;
  • F indicates that the line may contain the digits 4 or 5;
  • S indicates that the line may contain the digits 6 or 7;
  • . indicates that the line may contain the digits 8 or 9.
A display may also allow 10 different digits (0 to 9) per line, that is 1 line per stem, or just 1 digit per line, that is 10 lines per stem, as in the first of the three examples above.
Note that the median here is 4.5. This falls between two lines in the first display but is highlighted on the second display since it lies on a particular line.
Finally if there are positive and negative numbers on the display these are highlighted by a + or - sign where the distinction is required, that is near the zero-point.
If there are too many leaves to fit in the plot width allowed, G01ARF plots as many leaves as possible and places an asterisk to the right to indicate that some leaves are not displayed. If this occurs and you wish to be able to plot all the leaves then the width of the plot may be adjusted.
Options also allow the leaf unit and the height of the display to be specified by you or calculated by G01ARF. These arguments may be used to control the type of the display you wish to obtain. Fixing the unit and changing the height of the display may alter the number of lines used per stem, that is the number of different digits per line. G01ARF will choose a display for the fixed unit that attempts to make as much use of the available height as possible, thus increasing the height may allow for more lines per stem whereas decreasing the height may force the display to use fewer lines per stem. Similarly you may wish to fix the height and vary the leaf digit unit used on the display. See Section 9 for further details.
The display is returned in a character array with the option of printing the display.

4 References

Erickson B H and Nosanchuk T A (1985) Understanding Data Open University Press, Milton Keynes
Tukey J W (1977) Exploratory Data Analysis Addison–Wesley
Velleman P F and Hoaglin D C (1981) Applications, Basics, and Computing of Exploratory Data Analysis Duxbury Press, Boston, MA

5 Arguments

1:   RANGE – CHARACTER(1)Input
On entry: indicates whether you wish to scale the plot to the extremes of the data or to the fences.
RANGE='E'
The display is a plot to the extremes, that is a plot of all the data.
RANGE='F'
The display is a plot of the data between the fences.
Constraint: RANGE='E' or 'F'.
2:   PRT – CHARACTER(1)Input
On entry: indicates whether the stem and leaf display is to be output to an external file.
PRT='N'
The display is not output to an external file.
PRT='P'
The display is output to the current advisory message unit as defined by X04ABF. Only the first 132 characters of each line are actually printed.
Constraint: PRT='P' or 'N'.
3:   N – INTEGERInput
On entry: n, the number of observations.
Constraint: N≥2.
4:   Y N – REAL (KIND=nag_wp) arrayInput
On entry: the n observations.
5:   NSTEPX – INTEGERInput
On entry: the number of character positions to be plotted horizontally.
Constraint: NSTEPX≥35.
6:   NSTEPY – INTEGERInput
On entry: the maximum number of character positions to be plotted vertically.
If NSTEPY≤0 a suitable value will be used by G01ARF for the number of character positions to be plotted vertically. This will clearly be less than or equal to the value of LDPLOT.
Constraint: NSTEPY≤0 or NSTEPY≥5.
7:   UNIT – REAL (KIND=nag_wp)Input/Output
On entry: indicates the leaf digit unit to be used.
If UNIT>0.0 and is not a power of ten, it will be converted to the nearest power of ten below the input value for unit.
If UNIT≤0.0, the optimum unit will be used. This is based on the range of the data to be plotted and the number of lines available for the display.
On exit: contains the actual unit used in the stem and leaf display.
8:   PLOT LDPLOTNSTEPX – CHARACTER(1) arrayOutput
On exit: the stem and leaf display.
9:   LDPLOT – INTEGERInput
On entry: the first dimension of the array PLOT as declared in the (sub)program from which G01ARF is called.
Constraint: LDPLOT≥max 5,NSTEPY.
10:   LINES – INTEGEROutput
On exit: the actual number of lines needed for the display.
11:   SORTY N – REAL (KIND=nag_wp) arrayOutput
On exit: the observations sorted into ascending order.
12:   IWORK N – INTEGER arrayWorkspace
13:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, | N<2,
or | NSTEPX<35,
or | 0<NSTEPY<5,
or | LDPLOT<5,
or | LDPLOT<NSTEPY.
IFAIL=2
On entry, | PRT≠'P' or 'N',
or | RANGE≠'E' or 'F'.
IFAIL=3
The number of lines needed to produce the display exceeds the maximum number of lines allowed. You may wish to increase NSTEPY.
IFAIL=4
One of the observations is too large and causes a value to exceed the maximum integer allowed.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

Accuracy is limited by the number of significant figures that may be represented on the display which will depend on the data, the number of lines available and the unit used.

8 Parallelism and Performance

G01ARF is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

G01ARF uses integer representations of the data. If very large data values are being used they should be scaled before using this routine. The largest integer can be found by calling X02BBF.
If an asterisk is plotted at the end of a line to indicate that some leaves are not displayed you should increase NSTEPX if they wish to be able to print the rest of the leaves on that line.
Note that if you request G01ARF to print the plot only the first 132 characters of each line are printed. The full plot is stored in the array PLOT so you do have the option of printing a plot which has more than 132 characters on a line.
When the leaf digit unit is set, the number of lines per stem is decided as follows:
Let r be the range of the data to be plotted:
  • r = largest observation – smallest observation: if all the data to both extremes are to be plotted (that is if RANGE='E'),
  • r = upper fence – lower fence: if only the data between the fences are to be plotted (that is if RANGE='F').
Let l be the number of lines available for the plot:
  • l=NSTEPY-4 if NSTEPY>0,
  • l=LDPLOT-4 if NSTEPY≤0.
  • The 4 lines are subtracted to allow space for the display headings. If only the data between the fences are to be plotted then l must be further reduced to allow space to present those values outside the fences. This will involve a minimum of another 4 lines.
Let e= r/UNIT+1 l ,
  • then the number of lines per stem is:
    0 1​ if ​5<e≤10, that is digits per line is ​10, 0 2​ if ​2<e≤0 5, that is digits per line is ​5, 0 5​ if ​1<e≤0 2, that is digits per line is ​2, 10​ if ​0<e≤0 1, that is digits per line is ​1.
The time taken by the routine increases with n.

10 Example

A program to produce two stem and leaf displays for a sample of 30 observations. The first illustrates a plot produced automatically by G01ARF and the second shows how to print the display under your control.

10.1 Program Text

Program Text (g01arfe.f90)

10.2 Program Data

Program Data (g01arfe.d)

10.3 Program Results

Program Results (g01arfe.r)

G01 Chapter Contents
G01 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


G01ASF : NAG Library, Mark 26

G01 Chapter Contents
G01 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

G01ASF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

G01ASF produces a specified number of box and whisker plots on a character printing device, with a chosen number of character positions in each direction.

2 Specification

SUBROUTINE G01ASF ( PRT, M, N, X, LDX, NSTEPX, NSTEPY, PLOT, LDPLOT, WORK, IWORK, IFAIL)
INTEGER | M, N(M), LDX, NSTEPX, NSTEPY, LDPLOT, IWORK(LDX), IFAIL
REAL (KIND=nag_wp) | X(LDX,M), WORK(5*M)
CHARACTER(1) | PRT, PLOT(LDPLOT,NSTEPX)

3 Description

G01ASF produces a series of box and whisker plots representing m data batches each of size ni, for i=1,2,…,m. A box and whisker plot is a diagrammatic representation of the five-point summary of a data batch. The plot consists of a box spanning the hinges with the median indicated by a third line and two whiskers to represent the extreme values. The five-point summary is calculated internally and is returned in the workspace array.
The plot is returned in the character array PLOT. The size of the plot may be controlled using the arguments NSTEPX and NSTEPY. Optionally the plot can be output to an external file, in which case output is directed to the current advisory message unit as defined by X04ABF.
An axis corresponding to the y axis is drawn and annotated and data points are plotted to the nearest character position.

4 References

Erickson B H and Nosanchuk T A (1985) Understanding Data Open University Press, Milton Keynes
Tukey J W (1977) Exploratory Data Analysis Addison–Wesley

5 Arguments

1:   PRT – CHARACTER(1)Input
On entry: indicates whether the box and whisker plot is to be output to an external file.
PRT='N'
The box and whisker plot is not output to an external file.
PRT='P'
The box and whisker plot is output to the current advisory message unit as defined by X04ABF.
Constraint: PRT='P' or 'N'.
2:   M – INTEGERInput
On entry: m, the number of data batches that are to be represented.
Constraint: M>0.
3:   N M – INTEGER arrayInput
On entry: N i contains the number of observations in the ith batch, ni, for i=1,2,…,m.
If ni<5 the ith batch is omitted from the plot.
Constraint: at least one N i must be greater than or equal to 5, for i=1,2,…,m.
4:   X LDXM – REAL (KIND=nag_wp) arrayInput
On entry: the ith column of X must contain the data for the ith batch, that is X ji must contain the jth observation of the ith batch, for i=1,2,…,m and j=1,2,…,ni.
5:   LDX – INTEGERInput
On entry: the first dimension of the array X and the dimension of the array IWORK as declared in the (sub)program from which G01ASF is called.
Constraint: LDX≥max N i.
6:   NSTEPX – INTEGERInput
On entry: the number of character positions to be plotted in the x-direction.
Constraint: NSTEPX≥max 19,15×M/4+9.
7:   NSTEPY – INTEGERInput
On entry: the number of character positions to be plotted in the y-direction.
Constraint: NSTEPY≥9.
8:   PLOT LDPLOTNSTEPX – CHARACTER(1) arrayOutput
On exit: contains the box and whisker plots.
9:   LDPLOT – INTEGERInput
On entry: the first dimension of the array PLOT as declared in the (sub)program from which G01ASF is called.
Constraint: LDPLOT≥NSTEPY.
10:   WORK 5×M – REAL (KIND=nag_wp) arrayOutput
On exit: WORK j, for j=i-1×5+1,…,i-1×5+5, contains the five-point summary of the ith batch.
11:   IWORK LDX – INTEGER arrayWorkspace
12:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, N i<5 for some i, for i=1,2,…,m. For each batch where this occurs, 5 crosses are plotted in a vertical line to indicate that insufficient data was provided to produce a five-point summary and box-plot for that particular batch.
IFAIL=2
On entry, NSTEPX<max 19,15×M/4+9. This indicates that the data region defined by NSTEPX is too small to produce the required plot.
IFAIL=3
On entry, NSTEPY<9.
IFAIL=4
On entry, LDPLOT<NSTEPY.
IFAIL=5
On entry, PRT≠'P' or 'N'.
IFAIL=6
On entry, LDX<max N i, for i=1,2,…,m.
IFAIL=7
The number of observations in all batches is less than 5.
IFAIL=8
On entry, the data values are all identical.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

If the range of observations in a particular batch is too small to allow each item of the five-point summary to be plotted separately, then a sequence of stars are plotted at the median point of the batch to indicate that the full box-plot could not be plotted.

8 Parallelism and Performance

G01ASF is not threaded in any implementation.

9 Further Comments

The time taken by G01ASF increases with m and ni, for i=1,2,…,m.

10 Example

The following program produces a box and whisker plot for each one of 5 data batches of sizes 5, 6, 8, 8 and 7 respectively and prints the 5 box and whisker plots on the current advisory message unit.

10.1 Program Text

Program Text (g01asfe.f90)

10.2 Program Data

Program Data (g01asfe.d)

10.3 Program Results

Program Results (g01asfe.r)

G01 Chapter Contents
G01 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


G01ATF : NAG Library, Mark 26

G01 Chapter Contents
G01 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

G01ATF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

G01ATF calculates the mean, standard deviation, coefficients of skewness and kurtosis, and the maximum and minimum values for a set of (optionally weighted) data. The input data can be split into arbitrary sized blocks, allowing large datasets to be summarised.

2 Specification

SUBROUTINE G01ATF ( NB, X, IWT, WT, PN, XMEAN, XSD, XSKEW, XKURT, XMIN, XMAX, RCOMM, IFAIL)
INTEGER | NB, IWT, PN, IFAIL
REAL (KIND=nag_wp) | X(NB), WT(*), XMEAN, XSD, XSKEW, XKURT, XMIN, XMAX, RCOMM(20)

3 Description

Given a sample of n observations, denoted by x = xi : i=1,2,…,n and a set of non-negative weights, w = wi : i=1,2,…,n , G01ATF calculates a number of quantities:
(a) Mean
x- = ∑ i=1 n wi xi W ,   where   W = ∑ i=1 n wi .
(b) Standard deviation
s 2 = ∑ i=1 n wi xi - x- 2 d ,   where   d = W - ∑ i=1 n wi 2 W .
(c) Coefficient of skewness
s 3 = ∑ i=1 n wi xi - x- 3 d ⁢ s 23 .
(d) Coefficient of kurtosis
s 4 = ∑ i=1 n wi xi - x- 4 d ⁢ s 24 -3 .
(e) Maximum and minimum elements, with wi≠0.
These quantities are calculated using the one pass algorithm of West (1979).
For large datasets, or where all the data is not available at the same time, x and w can be split into arbitrary sized blocks and G01ATF called multiple times.

4 References

West D H D (1979) Updating mean and variance estimates: An improved method Comm. ACM 22 532–555

5 Arguments

1:   NB – INTEGERInput
On entry: b, the number of observations in the current block of data. The size of the block of data supplied in X and WT can vary; therefore NB can change between calls to G01ATF.
Constraint: NB≥0.
2:   X NB – REAL (KIND=nag_wp) arrayInput
On entry: the current block of observations, corresponding to xi, for i=k+1,…,k+b, where k is the number of observations processed so far and b is the size of the current block of data.
3:   IWT – INTEGERInput
On entry: indicates whether user-supplied weights are provided:
IWT=1
User-supplied weights are given in the array WT.
IWT=0
wi=1, for all i, so no user-supplied weights are given and WT is not referenced.
Constraint: IWT=0 or 1.
4:   WT* – REAL (KIND=nag_wp) arrayInput
Note: the dimension of the array WT must be at least NB if IWT=1.
On entry: if IWT=1, WT must contain the user-supplied weights corresponding to the block of data supplied in X, that is wi, for i=k+1,…,k+b.
Constraint: if IWT=1, WT i≥0, for i=1,2,…,NB.
5:   PN – INTEGERInput/Output
On entry: the number of valid observations processed so far, that is the number of observations with wi>0, for i=1,2,…,k. On the first call to G01ATF, or when starting to summarise a new dataset, PN must be set to 0.
If PN≠0, it must be the same value as returned by the last call to G01ATF.
On exit: the updated number of valid observations processed, that is the number of observations with wi>0, for i=1,2,…,k+b.
Constraint: PN≥0.
6:   XMEAN – REAL (KIND=nag_wp)Output
On exit: x-, the mean of the first k+b observations.
7:   XSD – REAL (KIND=nag_wp)Output
On exit: s 2, the standard deviation of the first k+b observations.
8:   XSKEW – REAL (KIND=nag_wp)Output
On exit: s 3, the coefficient of skewness for the first k+b observations.
9:   XKURT – REAL (KIND=nag_wp)Output
On exit: s 4, the coefficient of kurtosis for the first k+b observations.
10:   XMIN – REAL (KIND=nag_wp)Output
On exit: the smallest value in the first k+b observations.
11:   XMAX – REAL (KIND=nag_wp)Output
On exit: the largest value in the first k+b observations.
12:   RCOMM 20 – REAL (KIND=nag_wp) arrayCommunication Array
On entry: communication array, used to store information between calls to G01ATF. If PN=0, RCOMM need not be initialized, otherwise it must be unchanged since the last call to this routine.
On exit: the updated communication array. The first five elements of RCOMM hold information that may be of interest with
RCOMM 1 = ∑ i=1 k+b wi RCOMM 2 = ∑ i=1 k+b wi 2 - ∑ i=1 k+b wi 2 RCOMM 3 = ∑ i=1 k+b wi xi - x- 2 RCOMM 4 = ∑ i=1 k+b wi xi - x- 3 RCOMM 5 = ∑ i=1 k+b wi xi - x- 4
the remaining elements of RCOMM are used for workspace and so are undefined.
13:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=11
On entry, NB=value.
Constraint: NB≥0.
IFAIL=31
On entry, IWT=value.
Constraint: IWT=0 or 1.
IFAIL=41
On entry, WT value=value.
Constraint: if IWT=1 then WT i≥0, for i=1,2,…,NB.
IFAIL=51
On entry, PN=value.
Constraint: PN≥0.
IFAIL=52
On entry, PN=value.
On exit from previous call, PN=value.
Constraint: if PN>0, PN must be unchanged since previous call.
IFAIL=53
On entry, the number of valid observations is zero.
IFAIL=71
On exit we were unable to calculate XSKEW or XKURT. A value of 0 has been returned.
IFAIL=72
On exit we were unable to calculate XSD, XSKEW or XKURT. A value of 0 has been returned.
IFAIL=121
RCOMM has been corrupted between calls.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

Not applicable.

8 Parallelism and Performance

G01ATF is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

Both G01ATF and G01AUF consolidate results from multiple summaries. Whereas the former can only be used to combine summaries calculated sequentially, the latter combines summaries calculated in an arbitrary order allowing, for example, summaries calculated on different processing units to be combined.

10 Example

This example summarises some simulated data. The data is supplied in three blocks, the first consisting of 21 observations, the second 51 observations and the last 28 observations.

10.1 Program Text

Program Text (g01atfe.f90)

10.2 Program Data

Program Data (g01atfe.d)

10.3 Program Results

Program Results (g01atfe.r)

G01 Chapter Contents
G01 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


G01AUF : NAG Library, Mark 26

G01 Chapter Contents
G01 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

G01AUF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

G01AUF combines sets of summaries produced by G01ATF.

2 Specification

SUBROUTINE G01AUF ( B, MRCOMM, PN, XMEAN, XSD, XSKEW, XKURT, XMIN, XMAX, RCOMM, IFAIL)
INTEGER | B, PN, IFAIL
REAL (KIND=nag_wp) | MRCOMM(20,B), XMEAN, XSD, XSKEW, XKURT, XMIN, XMAX, RCOMM(20)

3 Description

Assume a dataset containing n observations, denoted by x = xi : i=1,2,…,n and a set of weights, w = wi : i=1,2,…,n , has been split into b blocks, and each block summarised via a call to G01ATF. Then G01AUF takes the b communication arrays returned by G01ATF and returns the mean (x-), standard deviation (s 2), coefficients of skewness (s 3) and kurtosis (s 4), and the maximum and minimum values for the whole dataset.
For a definition of x-,s 2,s 3 and s 4 see Section 3 in G01ATF.

4 References

West D H D (1979) Updating mean and variance estimates: An improved method Comm. ACM 22 532–555

5 Arguments

1:   B – INTEGERInput
On entry: b, the number of blocks the full dataset was split into.
Constraint: B≥1.
2:   MRCOMM 20 B – REAL (KIND=nag_wp) arrayCommunication Array
On entry: the jth column of MRCOMM must contain the information returned in RCOMM from one of the runs of G01ATF.
3:   PN – INTEGEROutput
On exit: the number of valid observations, that is the number of observations with wi>0, for i=1,2,…,n.
4:   XMEAN – REAL (KIND=nag_wp)Output
On exit: x-, the mean.
5:   XSD – REAL (KIND=nag_wp)Output
On exit: s 2, the standard deviation.
6:   XSKEW – REAL (KIND=nag_wp)Output
On exit: s 3, the coefficient of skewness.
7:   XKURT – REAL (KIND=nag_wp)Output
On exit: s 4, the coefficient of kurtosis.
8:   XMIN – REAL (KIND=nag_wp)Output
On exit: the smallest value.
9:   XMAX – REAL (KIND=nag_wp)Output
On exit: the largest value.
10:   RCOMM 20 – REAL (KIND=nag_wp) arrayCommunication Array
On exit: an amalgamation of the information held in MRCOMM. This is in the same format as RCOMM from G01ATF.
11:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=11
On entry, B=value.
Constraint: B≥1.
IFAIL=21
On entry, MRCOMM is not in the expected format.
IFAIL=31
On entry, the number of valid observations is zero.
IFAIL=51
On exit we were unable to calculate XSKEW or XKURT. A value of 0 has been returned.
IFAIL=52
On exit we were unable to calculate XSD, XSKEW or XKURT. A value of 0 has been returned.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

Not applicable.

8 Parallelism and Performance

G01AUF is not threaded in any implementation.

9 Further Comments

The order that the b communication arrays are stored in MRCOMM is arbitrary. Different orders can lead to slightly different results due to numerical accuracy of floating-point calculations.
Both G01AUF and G01ATF consolidate results from multiple summaries. Whereas the former can only be used to combine summaries calculated sequentially, the latter combines summaries calculated in an arbitrary order allowing, for example, summaries calculated on different processing units to be combined.

10 Example

This example summarises some simulated data. The data is supplied in three blocks, the first consisting of 21 observations, the second 51 observations and the last 28 observations. Summaries are produced for each block of data separately and then an overall summary is produced.

10.1 Program Text

Program Text (g01aufe.f90)

10.2 Program Data

Program Data (g01aufe.d)

10.3 Program Results

Program Results (g01aufe.r)

G01 Chapter Contents
G01 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


G01BJF : NAG Library, Mark 26

G01 Chapter Contents
G01 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

G01BJF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

G01BJF returns the lower tail, upper tail and point probabilities associated with a binomial distribution.

2 Specification

SUBROUTINE G01BJF ( N, P, K, PLEK, PGTK, PEQK, IFAIL)
INTEGER | N, K, IFAIL
REAL (KIND=nag_wp) | P, PLEK, PGTK, PEQK

3 Description

Let X denote a random variable having a binomial distribution with parameters n and p (n≥0 and 0<p<1). Then
Prob X=k= n k pk1-p n-k,  k=0,1,…,n.
The mean of the distribution is np and the variance is np 1-p.
G01BJF computes for given n, p and k the probabilities:
PLEK=Prob X≤k PGTK=Prob X>k PEQK=Prob X=k .
The method is similar to the method for the Poisson distribution described in Knüsel (1986).

4 References

Knüsel L (1986) Computation of the chi-square and Poisson distribution SIAM J. Sci. Statist. Comput. 7 1022–1036

5 Arguments

1:   N – INTEGERInput
On entry: the parameter n of the binomial distribution.
Constraint: N≥0.
2:   P – REAL (KIND=nag_wp)Input
On entry: the parameter p of the binomial distribution.
Constraint: 0.0<P<1.0.
3:   K – INTEGERInput
On entry: the integer k which defines the required probabilities.
Constraint: 0≤K≤N.
4:   PLEK – REAL (KIND=nag_wp)Output
On exit: the lower tail probability, Prob X≤k.
5:   PGTK – REAL (KIND=nag_wp)Output
On exit: the upper tail probability, Prob X>k.
6:   PEQK – REAL (KIND=nag_wp)Output
On exit: the point probability, Prob X=k.
7:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, N<0.
IFAIL=2
On entry, | P≤0.0,
or | P≥1.0.
IFAIL=3
On entry, | K<0,
or | K>N.
IFAIL=4
On entry, N is too large to be represented exactly as a real number.
IFAIL=5
On entry, the variance (=np 1-p) exceeds 106.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

Results are correct to a relative accuracy of at least 10-6 on machines with a precision of 9 or more decimal digits, and to a relative accuracy of at least 10-3 on machines of lower precision (provided that the results do not underflow to zero).

8 Parallelism and Performance

G01BJF is not threaded in any implementation.

9 Further Comments

The time taken by G01BJF depends on the variance (=np 1-p) and on k. For given variance, the time is greatest when k≈np (=the mean), and is then approximately proportional to the square-root of the variance.

10 Example

This example reads values of n and p from a data file until end-of-file is reached, and prints the corresponding probabilities.

10.1 Program Text

Program Text (g01bjfe.f90)

10.2 Program Data

Program Data (g01bjfe.d)

10.3 Program Results

Program Results (g01bjfe.r)

G01 Chapter Contents
G01 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


G01BKF : NAG Library, Mark 26

G01 Chapter Contents
G01 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

G01BKF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

G01BKF returns the lower tail, upper tail and point probabilities associated with a Poisson distribution.

2 Specification

SUBROUTINE G01BKF ( RLAMDA, K, PLEK, PGTK, PEQK, IFAIL)
INTEGER | K, IFAIL
REAL (KIND=nag_wp) | RLAMDA, PLEK, PGTK, PEQK

3 Description

Let X denote a random variable having a Poisson distribution with parameter λ >0. Then
Prob X=k=e-λ λk k! ,  k=0,1,2,…
The mean and variance of the distribution are both equal to λ.
G01BKF computes for given λ and k the probabilities:
PLEK=Prob X≤k PGTK=Prob X>k PEQK=Prob X=k .
The method is described in Knüsel (1986).

4 References

Knüsel L (1986) Computation of the chi-square and Poisson distribution SIAM J. Sci. Statist. Comput. 7 1022–1036

5 Arguments

1:   RLAMDA – REAL (KIND=nag_wp)Input
On entry: the parameter λ of the Poisson distribution.
Constraint: 0.0<RLAMDA≤106.
2:   K – INTEGERInput
On entry: the integer k which defines the required probabilities.
Constraint: K≥0.
3:   PLEK – REAL (KIND=nag_wp)Output
On exit: the lower tail probability, Prob X≤k.
4:   PGTK – REAL (KIND=nag_wp)Output
On exit: the upper tail probability, Prob X>k.
5:   PEQK – REAL (KIND=nag_wp)Output
On exit: the point probability, Prob X=k.
6:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, RLAMDA≤0.0.
IFAIL=2
On entry, K<0.
IFAIL=3
On entry, RLAMDA>106.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

Results are correct to a relative accuracy of at least 10-6 on machines with a precision of 9 or more decimal digits, and to a relative accuracy of at least 10-3 on machines of lower precision (provided that the results do not underflow to zero).

8 Parallelism and Performance

G01BKF is not threaded in any implementation.

9 Further Comments

The time taken by G01BKF depends on λ and k. For given λ, the time is greatest when k≈λ, and is then approximately proportional to λ.

10 Example

This example reads values of λ and k from a data file until end-of-file is reached, and prints the corresponding probabilities.

10.1 Program Text

Program Text (g01bkfe.f90)

10.2 Program Data

Program Data (g01bkfe.d)

10.3 Program Results

Program Results (g01bkfe.r)

G01 Chapter Contents
G01 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


G01BLF : NAG Library, Mark 26

G01 Chapter Contents
G01 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

G01BLF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

G01BLF returns the lower tail, upper tail and point probabilities associated with a hypergeometric distribution.

2 Specification

SUBROUTINE G01BLF ( N, L, M, K, PLEK, PGTK, PEQK, IFAIL)
INTEGER | N, L, M, K, IFAIL
REAL (KIND=nag_wp) | PLEK, PGTK, PEQK

3 Description

Let X denote a random variable having a hypergeometric distribution with parameters n, l and m (n≥l≥0, n≥m≥0). Then
Prob X=k= m k n-m l-k n l ,
where max 0,l-n-m ≤ k ≤ min l,m , 0≤l≤n and 0≤m≤n.
The hypergeometric distribution may arise if in a population of size n a number m are marked. From this population a sample of size l is drawn and of these k are observed to be marked.
The mean of the distribution = lm n , and the variance = lm n-ln-m n 2 n-1 .
G01BLF computes for given n, l, m and k the probabilities:
PLEK=Prob X≤k PGTK=Prob X>k PEQK=Prob X=k .
The method is similar to the method for the Poisson distribution described in Knüsel (1986).

4 References

Knüsel L (1986) Computation of the chi-square and Poisson distribution SIAM J. Sci. Statist. Comput. 7 1022–1036

5 Arguments

1:   N – INTEGERInput
On entry: the parameter n of the hypergeometric distribution.
Constraint: N≥0.
2:   L – INTEGERInput
On entry: the parameter l of the hypergeometric distribution.
Constraint: 0≤L≤N.
3:   M – INTEGERInput
On entry: the parameter m of the hypergeometric distribution.
Constraint: 0≤M≤N.
4:   K – INTEGERInput
On entry: the integer k which defines the required probabilities.
Constraint: max 0,L-N-M≤K≤min L,M.
5:   PLEK – REAL (KIND=nag_wp)Output
On exit: the lower tail probability, Prob X≤k.
6:   PGTK – REAL (KIND=nag_wp)Output
On exit: the upper tail probability, Prob X>k.
7:   PEQK – REAL (KIND=nag_wp)Output
On exit: the point probability, Prob X=k.
8:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, N<0.
IFAIL=2
On entry, | L<0,
or | L>N.
IFAIL=3
On entry, | M<0,
or | M>N.
IFAIL=4
On entry, | K<0,
or | K>L,
or | K>M,
or | K<L+M-N.
IFAIL=5
On entry, N is too large to be represented exactly as a real number.
IFAIL=6
On entry, the variance (see Section 3) exceeds 106.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

Results are correct to a relative accuracy of at least 10-6 on machines with a precision of 9 or more decimal digits, and to a relative accuracy of at least 10-3 on machines of lower precision (provided that the results do not underflow to zero).

8 Parallelism and Performance

G01BLF is not threaded in any implementation.

9 Further Comments

The time taken by G01BLF depends on the variance (see Section 3) and on k. For given variance, the time is greatest when k≈lm/n (= the mean), and is then approximately proportional to the square-root of the variance.

10 Example

This example reads values of n, l, m and k from a data file until end-of-file is reached, and prints the corresponding probabilities.

10.1 Program Text

Program Text (g01blfe.f90)

10.2 Program Data

Program Data (g01blfe.d)

10.3 Program Results

Program Results (g01blfe.r)

G01 Chapter Contents
G01 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


G01 Chapter Contents : NAG Library Manual, Mark 26

G01 Chapter Introduction
NAG Library Manual

NAG Library Chapter Contents

G01 – Simple Calculations on Statistical Data

G01 Chapter Introduction – a description of the Chapter and an overview of the algorithms available

Routine Name | Mark of Introduction | Purpose
G01ABF Example Text Example Data | 4 | nagf_stat_summary_2var Means, corrected sums of squares and cross-products, etc., two variables, from raw data
G01ADF Example Text Example Data | 4 | nagf_stat_summary_freq Mean, variance, skewness, kurtosis, etc., one variable, from frequency table
G01AEF Example Text Example Data | 4 | nagf_stat_frequency_table Frequency table from raw data
G01AFF Example Text Example Data | 4 | nagf_stat_contingency_table Two-way contingency table analysis, with χ 2/Fisher's exact test
G01AGF Example Text Example Data | 8 | nagf_stat_plot_scatter_2var Lineprinter scatterplot of two variables
G01AHF Example Text Example Data | 8 | nagf_stat_plot_scatter_normal Lineprinter scatterplot of one variable against Normal scores
G01AJF Example Text Example Data | 10 | nagf_stat_plot_histogram Lineprinter histogram of one variable
G01ALF Example Text Example Data | 14 | nagf_stat_5pt_summary Computes a five-point summary (median, hinges and extremes)
G01AMF Example Text Example Data | 22 | nagf_stat_quantiles Find quantiles of an unordered vector, real numbers
G01ANF Example Text Example Data | 23 | nagf_stat_quantiles_stream_fixed Calculates approximate quantiles from a data stream of known size
G01APF Example Text Example Data | 23 | nagf_stat_quantiles_stream_arbitrary Calculates approximate quantiles from a data stream of unknown size
G01ARF Example Text Example Data | 14 | nagf_stat_plot_stem_leaf Constructs a stem and leaf plot
G01ASF Example Text Example Data | 14 | nagf_stat_plot_box_whisker Constructs a box and whisker plot
G01ATF Example Text Example Data | 24 | nagf_stat_summary_onevar Computes univariate summary information: mean, variance, skewness, kurtosis
G01AUF Example Text Example Data | 24 | nagf_stat_summary_onevar_combine Combines multiple sets of summary information, for use after G01ATF
G01BJF Example Text Example Data | 13 | nagf_stat_prob_binomial Binomial distribution function
G01BKF Example Text Example Data | 13 | nagf_stat_prob_poisson Poisson distribution function
G01BLF Example Text Example Data | 13 | nagf_stat_prob_hypergeom Hypergeometric distribution function
G01DAF Example Text Example Plot | 8 | nagf_stat_normal_scores_exact Normal scores, accurate values
G01DBF Example Text Example Plot | 12 | nagf_stat_normal_scores_approx Normal scores, approximate values
G01DCF Example Text | 12 | nagf_stat_normal_scores_var Normal scores, approximate variance-covariance matrix
G01DDF Example Text Example Data | 12 | nagf_stat_test_shapiro_wilk Shapiro and Wilk's W test for Normality
G01DHF Example Text Example Data | 15 | nagf_stat_ranks_and_scores Ranks, Normal scores, approximate Normal scores or exponential (Savage) scores
G01EAF Example Text Example Data | 15 | nagf_stat_prob_normal Computes probabilities for the standard Normal distribution
G01EBF Example Text Example Data | 14 | nagf_stat_prob_students_t Computes probabilities for Student's t-distribution
G01ECF Example Text Example Data | 14 | nagf_stat_prob_chisq Computes probabilities for χ 2 distribution
G01EDF Example Text Example Data | 14 | nagf_stat_prob_f Computes probabilities for F-distribution
G01EEF Example Text Example Data | 14 | nagf_stat_prob_beta Computes upper and lower tail probabilities and probability density function for the beta distribution
G01EFF Example Text Example Data | 14 | nagf_stat_prob_gamma Computes probabilities for the gamma distribution
G01EMF Example Text Example Data | 15 | nagf_stat_prob_studentized_range Computes probability for the Studentized range statistic
G01EPF Example Text Example Data | 15 | nagf_stat_prob_durbin_watson Computes bounds for the significance of a Durbin–Watson statistic
G01ERF Example Text Example Data | 16 | nagf_stat_prob_vonmises Computes probability for von Mises distribution
G01ETF Example Text Example Data | 21 | nagf_stat_prob_landau Landau distribution function
G01EUF Example Text Example Data | 21 | nagf_stat_prob_vavilov Vavilov distribution function
G01EWF | 25 | nagf_stat_prob_dickey_fuller_unit Computes probabilities for the Dickey–Fuller unit root test
G01EYF Example Text Example Data | 14 | nagf_stat_prob_kolmogorov1 Computes probabilities for the one-sample Kolmogorov–Smirnov distribution
G01EZF Example Text Example Data | 14 | nagf_stat_prob_kolmogorov2 Computes probabilities for the two-sample Kolmogorov–Smirnov distribution
G01FAF Example Text Example Data | 15 | nagf_stat_inv_cdf_normal Computes deviates for the standard Normal distribution
G01FBF Example Text Example Data | 14 | nagf_stat_inv_cdf_students_t Computes deviates for Student's t-distribution
G01FCF Example Text Example Data | 14 | nagf_stat_inv_cdf_chisq Computes deviates for the χ 2 distribution
G01FDF Example Text Example Data | 14 | nagf_stat_inv_cdf_f Computes deviates for the F-distribution
G01FEF Example Text Example Data | 14 | nagf_stat_inv_cdf_beta Computes deviates for the beta distribution
G01FFF Example Text Example Data | 14 | nagf_stat_inv_cdf_gamma Computes deviates for the gamma distribution
G01FMF Example Text Example Data | 15 | nagf_stat_inv_cdf_studentized_range Computes deviates for the Studentized range statistic
G01FTF Example Text Example Data | 21 | nagf_stat_inv_cdf_landau Landau inverse function Ψ x
G01GBF Example Text Example Data | 14 | nagf_stat_prob_students_t_noncentral Computes probabilities for the non-central Student's t-distribution
G01GCF Example Text Example Data | 14 | nagf_stat_prob_chisq_noncentral Computes probabilities for the non-central χ 2 distribution
G01GDF Example Text Example Data | 14 | nagf_stat_prob_f_noncentral Computes probabilities for the non-central F-distribution
G01GEF Example Text Example Data | 14 | nagf_stat_prob_beta_noncentral Computes probabilities for the non-central beta distribution
G01HAF Example Text Example Data | 14 | nagf_stat_prob_bivariate_normal Computes probability for the bivariate Normal distribution
G01HBF Example Text Example Data | 15 | nagf_stat_prob_multi_normal Computes probabilities for the multivariate Normal distribution
G01HCF Example Text Example Data | 23 | nagf_stat_prob_bivariate_students_t Computes probabilities for the bivariate Student's t-distribution
G01HDF Example Text Example Data | 24 | nagf_multi_students_t Computes the probability for the multivariate Student's t-distribution
G01JCF Example Text Example Data | 14 | nagf_stat_prob_chisq_noncentral_lincomb Computes probability for a positive linear combination of χ 2 variables
G01JDF Example Text Example Data | 15 | nagf_stat_prob_chisq_lincomb Computes lower tail probability for a linear combination of (central) χ 2 variables
G01KAF Example Text Example Data Example Plot | 23 | nagf_stat_pdf_normal Calculates the value for the probability density function of the Normal distribution at a chosen point
G01KFF Example Text Example Data Example Plot | 23 | nagf_stat_pdf_gamma Calculates the value for the probability density function of the gamma distribution at a chosen point
G01KKF Example Text Example Data Example Plot | 24 | nagf_stat_pdf_gamma_vector Computes a vector of values for the probability density function of the gamma distribution
G01KQF Example Text Example Data Example Plot | 24 | nagf_stat_pdf_normal_vector Computes a vector of values for the probability density function of the Normal distribution
G01LBF Example Text Example Data | 24 | nagf_stat_pdf_multi_normal_vector Computes a vector of values for the probability density function of the multivariate Normal distribution
G01MBF Example Text Example Data | 15 | nagf_stat_mills_ratio Computes reciprocal of Mills' Ratio
G01MTF Example Text Example Data | 21 | nagf_stat_pdf_landau Landau density function ϕ λ
G01MUF Example Text Example Data | 21 | nagf_stat_pdf_vavilov Vavilov density function ϕV λ;κ,β 2
G01NAF Example Text Example Data | 16 | nagf_stat_moments_quad_form Cumulants and moments of quadratic forms in Normal variables
G01NBF Example Text Example Data | 16 | nagf_stat_moments_ratio_quad_forms Moments of ratios of quadratic forms in Normal variables, and related statistics
G01PTF Example Text Example Data | 21 | nagf_stat_pdf_landau_moment1 Landau first moment function Φ 1 x
G01QTF Example Text Example Data | 21 | nagf_stat_pdf_landau_moment2 Landau second moment function Φ 2 x
G01RTF Example Text Example Data | 21 | nagf_stat_pdf_landau_deriv Landau derivative function ϕ′λ
G01SAF Example Text Example Data | 24 | nagf_stat_prob_normal_vector Computes a vector of probabilities for the standard Normal distribution
G01SBF Example Text Example Data | 24 | nagf_stat_prob_students_t_vector Computes a vector of probabilities for the Student's t-distribution
G01SCF Example Text Example Data | 24 | nagf_stat_prob_chisq_vector Computes a vector of probabilities for χ 2 distribution
G01SDF Example Text Example Data | 24 | nagf_stat_prob_f_vector Computes a vector of probabilities for F-distribution
G01SEF Example Text Example Data | 24 | nagf_stat_prob_beta_vector Computes a vector of probabilities for the beta distribution
G01SFF Example Text Example Data | 24 | nagf_stat_prob_gamma_vector Computes a vector of probabilities for the gamma distribution
G01SJF Example Text Example Data | 24 | nagf_stat_prob_binomial_vector Computes a vector of probabilities for the binomial distribution
G01SKF Example Text Example Data | 24 | nagf_stat_prob_poisson_vector Computes a vector of probabilities for the Poisson distribution
G01SLF Example Text Example Data | 24 | nagf_stat_prob_hypergeom_vector Computes a vector of probabilities for the hypergeometric distribution
G01TAF Example Text Example Data | 24 | nagf_stat_inv_cdf_normal_vector Computes a vector of deviates for the standard Normal distribution
G01TBF Example Text Example Data | 24 | nagf_stat_inv_cdf_students_t_vector Computes a vector of deviates for Student's t-distribution
G01TCF Example Text Example Data | 24 | nagf_stat_inv_cdf_chisq_vector Computes a vector of deviates for χ 2 distribution
G01TDF Example Text Example Data | 24 | nagf_stat_inv_cdf_f_vector Computes a vector of deviates for F-distribution
G01TEF Example Text Example Data | 24 | nagf_stat_inv_cdf_beta_vector Computes a vector of deviates for the beta distribution
G01TFF Example Text Example Data | 24 | nagf_stat_inv_cdf_gamma_vector Computes a vector of deviates for the gamma distribution
G01WAF Example Text Example Data Example Plot | 24 | nagf_stat_moving_average Computes the mean and standard deviation using a rolling window
G01ZUF | 21 | nagf_stat_init_vavilov Initialization routine for G01MUF and G01EUF
G01 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


G01DAF : NAG Library, Mark 26

G01 Chapter Contents
G01 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

G01DAF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

G01DAF computes a set of Normal scores, i.e., the expected values of an ordered set of independent observations from a Normal distribution with mean 0.0 and standard deviation 1.0.

2 Specification

SUBROUTINE G01DAF ( N, PP, ETOL, ERREST, WORK, IW, IFAIL)
INTEGER | N, IW, IFAIL
REAL (KIND=nag_wp) | PP(N), ETOL, ERREST, WORK(IW)

3 Description

If a sample of n observations from any distribution (which may be denoted by x 1,x 2,…,xn), is sorted into ascending order, the rth smallest value in the sample is often referred to as the rth ‘order statistic’, sometimes denoted by x r (see Kendall and Stuart (1969)).
The order statistics therefore have the property
x 1≤x 2≤…≤x n.
(If n=2 r+1, x r+1 is the sample median.)
For samples originating from a known distribution, the distribution of each order statistic in a sample of given size may be determined. In particular, the expected values of the order statistics may be found by integration. If the sample arises from a Normal distribution, the expected values of the order statistics are referred to as the ‘Normal scores’. The Normal scores provide a set of reference values against which the order statistics of an actual data sample of the same size may be compared, to provide an indication of Normality for the sample (see G01AHF). Normal scores have other applications; for instance, they are sometimes used as alternatives to ranks in nonparametric testing procedures.
G01DAF computes the rth Normal score for a given sample size n as
E x r=∫-∞∞xr d Gr,
where
d Gr=Ar r- 1 1-Ar n-r d Ar β r,n-r+ 1 ,   Ar=1 2 π ∫-∞xr e-t 2/2 dt,   r= 1,2,…,n,
and β denotes the complete beta function.
The routine attempts to evaluate the scores so that the estimated error in each score is less than the value ETOL specified by you. All integrations are performed in parallel and arranged so as to give good speed and reasonable accuracy.

4 References

Kendall M G and Stuart A (1969) The Advanced Theory of Statistics (Volume 1) (3rd Edition) Griffin

5 Arguments

1:   N – INTEGERInput
On entry: n, the size of the set.
Constraint: N>0.
2:   PP N – REAL (KIND=nag_wp) arrayOutput
On exit: the Normal scores. PP i contains the value E x i, for i=1,2,…,n.
3:   ETOL – REAL (KIND=nag_wp)Input
On entry: the maximum value for the estimated absolute error in the computed scores.
Constraint: ETOL>0.0.
4:   ERREST – REAL (KIND=nag_wp)Output
On exit: a computed estimate of the maximum error in the computed scores (see Section 7).
5:   WORK IW – REAL (KIND=nag_wp) arrayWorkspace
6:   IW – INTEGERInput
On entry: the dimension of the array WORK as declared in the (sub)program from which G01DAF is called.
Constraints:
  • if N must be even, IW≥3×N/2;
  • otherwise IW≥3×N-1/2.
7:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, N<1.
IFAIL=2
On entry, ETOL≤0.0.
IFAIL=3
The routine was unable to estimate the scores with estimated error less than ETOL. The best result obtained is returned together with the associated value of ERREST.
IFAIL=4
On entry, | if N is even, IW<3×N/2;
or | if N is odd, IW<3×N-1/2.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

Errors are introduced by evaluation of the functions d Gr and errors in the numerical integration process. Errors are also introduced by the approximation of the true infinite range of integration by a finite range a,b but a and b are chosen so that this effect is of lower order than that of the other two factors. In order to estimate the maximum error the functions d Gr are also integrated over the range a,b. G01DAF returns the estimated maximum error as
ERREST=maxr max a,b× ∫ab d Gr-1.0 .

8 Parallelism and Performance

G01DAF is not threaded in any implementation.

9 Further Comments

The time taken by G01DAF depends on ETOL and N. For a given value of ETOL the timing varies approximately linearly with N.

10 Example

The program below generates the Normal scores for samples of size 5, 10, 15, and prints the scores and the computed error estimates.

10.1 Program Text

Program Text (g01dafe.f90)

10.2 Program Data

None.

10.3 Program Results

Program Results (g01dafe.r)

This shows a Q-Q plot for a randomly generated set of data. The normal scores have been calculated using G01DAF and the sample quantiles obtained by sorting the observed data using M01CAF. A reference line at y=x is also shown.
GnuplotProduced by GNUPLOT 4.6 patchlevel 3 −3 −2.5 −2 −1.5 −1 −0.5 0 0.5 1 1.5 2 2.5 −2.5 −2 −1.5 −1 −0.5 0 0.5 1 1.5 2 2.5 Sample Quantiles Normal Scores Example Program Q-Q Plot for a Random Set of Data Using Exact Normal Scores gnuplot_plot_1 gnuplot_plot_2
G01 Chapter Contents
G01 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


G01DBF : NAG Library, Mark 26

G01 Chapter Contents
G01 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

G01DBF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

G01DBF calculates an approximation to the set of Normal Scores, i.e., the expected values of an ordered set of independent observations from a Normal distribution with mean 0.0 and standard deviation 1.0.

2 Specification

SUBROUTINE G01DBF ( N, PP, IFAIL)
INTEGER | N, IFAIL
REAL (KIND=nag_wp) | PP(N)

3 Description

G01DBF is an adaptation of the Applied Statistics Algorithm AS 177.3, see Royston (1982). If you are particularly concerned with the accuracy with which G01DBF computes the expected values of the order statistics (see Section 7), then G01DAF which is more accurate should be used instead at a cost of increased storage and computing time.
Let x 1,x 2,…,x n be the order statistics from a random sample of size n from the standard Normal distribution. Defining
P r,n=Φ-E x r
and
Q r,n=r-ε n+γ ,   r= 1,2,…,n,
where E x r is the expected value of x r, the current routine approximates the Normal upper tail area corresponding to E x r as,
P~r,n=Q r,n+δ 1 n Q r,n λ+δ 2 n Q r,n 2 λ-C r,n.
for r=1,2,3, and r≥4. Estimates of ε, γ, δ 1, δ 2 and λ are obtained. A small correction C r,n to P~r,n is necessary when r≤7 and n≤20.
The approximation to E X r is thus given by
E x r = - Φ-1 P ~ r , n ,   r =1,2,…,n .
Values of the inverse Normal probability integral Φ-1 are obtained from G01FAF.

4 References

Royston J P (1982) Algorithm AS 177: expected normal order statistics (exact and approximate) Appl. Statist. 31 161–165

5 Arguments

1:   N – INTEGERInput
On entry: n, the size of the sample.
Constraint: N≥1.
2:   PP N – REAL (KIND=nag_wp) arrayOutput
On exit: the Normal scores. PP i contains the value E x i, for i=1,2,…,n.
3:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, N<1.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

For n≤2000, the maximum error is 0.0001, but G01DBF is usually accurate to 5 or 6 decimal places. For n up to 5000, comparison with the exact scores calculated by G01DAF shows that the maximum error is 0.001.

8 Parallelism and Performance

G01DBF is not threaded in any implementation.

9 Further Comments

The time taken by G01DBF is proportional to n.

10 Example

A program to calculate the expected values of the order statistics for a sample of size 10.

10.1 Program Text

Program Text (g01dbfe.f90)

10.2 Program Data

None.

10.3 Program Results

Program Results (g01dbfe.r)

This shows a Q-Q plot for a randomly generated set of data. The normal scores have been calculated using G01DBF and the sample quantiles obtained by sorting the observed data using M01CAF. A reference line at y=x is also shown.
GnuplotProduced by GNUPLOT 4.6 patchlevel 3 −3 −2 −1 0 1 2 3 −2.5 −2 −1.5 −1 −0.5 0 0.5 1 1.5 2 2.5 Sample Quantiles Normal Scores Example Program Q-Q Plot for a Random Set of Data Using Approximate Normal Scores gnuplot_plot_1 gnuplot_plot_2
G01 Chapter Contents
G01 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


G01DCF : NAG Library, Mark 26

G01 Chapter Contents
G01 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

G01DCF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

G01DCF computes an approximation to the variance-covariance matrix of an ordered set of independent observations from a Normal distribution with mean 0.0 and standard deviation 1.0.

2 Specification

SUBROUTINE G01DCF ( N, EXP1, EXP2, SUMSSQ, VEC, IFAIL)
INTEGER | N, IFAIL
REAL (KIND=nag_wp) | EXP1, EXP2, SUMSSQ, VEC(N*(N+1)/2)

3 Description

G01DCF is an adaptation of the Applied Statistics Algorithm AS 128, see Davis and Stephens (1978). An approximation to the variance-covariance matrix, V, using a Taylor series expansion of the Normal distribution function is discussed in David and Johnson (1954).
However, convergence is slow for extreme variances and covariances. The present routine uses the David–Johnson approximation to provide an initial approximation and improves upon it by use of the following identities for the matrix.
For a sample of size n, let mi be the expected value of the ith largest order statistic, then:
(a) | for any i=1,2,…,n, ∑j=1 n V ij=1
(b) | V 12=V 11+mn 2-mnm n-1-1
(c) | the trace of V is tr V=n-∑i=1 n mi 2
(d) | V ij=V ji=V rs=V sr where r=n+1-i, s=n+1-j and i,j=1,2,…,n. Note that only the upper triangle of the matrix is calculated and returned column-wise in vector form.

4 References

David F N and Johnson N L (1954) Statistical treatment of censored data, Part 1. Fundamental formulae Biometrika 41 228–240
Davis C S and Stephens M A (1978) Algorithm AS 128: approximating the covariance matrix of Normal order statistics Appl. Statist. 27 206–212

5 Arguments

1:   N – INTEGERInput
On entry: n, the sample size.
Constraint: N>0.
2:   EXP1 – REAL (KIND=nag_wp)Input
On entry: the expected value of the largest Normal order statistic, mn, from a sample of size n.
3:   EXP2 – REAL (KIND=nag_wp)Input
On entry: the expected value of the second largest Normal order statistic, m n-1, from a sample of size n.
4:   SUMSSQ – REAL (KIND=nag_wp)Input
On entry: the sum of squares of the expected values of the Normal order statistics from a sample of size n.
5:   VEC N×N+1/2 – REAL (KIND=nag_wp) arrayOutput
On exit: the upper triangle of the n by n variance-covariance matrix packed by column. Thus element V ij is stored in VEC i+j×j-1/2, for 1≤i≤j≤n.
6:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, N<1.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

For n≤20, where comparison with the exact values can be made, the maximum error is less than 0.0001.

8 Parallelism and Performance

G01DCF is not threaded in any implementation.

9 Further Comments

The time taken by G01DCF is approximately proportional to n 2.
The arguments EXP1 (=mn), EXP2 (=m n-1) and SUMSSQ (=∑j=1 n mj 2) may be found from the expected values of the Normal order statistics obtained from G01DAF (exact) or G01DBF (approximate).

10 Example

A program to compute the variance-covariance matrix for a sample of size 6. G01DAF is called to provide values for EXP1, EXP2 and SUMSSQ.

10.1 Program Text

Program Text (g01dcfe.f90)

10.2 Program Data

None.

10.3 Program Results

Program Results (g01dcfe.r)

G01 Chapter Contents
G01 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


G01DDF : NAG Library, Mark 26

G01 Chapter Contents
G01 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

G01DDF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

G01DDF calculates Shapiro and Wilk's W statistic and its significance level for testing Normality.

2 Specification

SUBROUTINE G01DDF ( X, N, CALWTS, A, W, PW, IFAIL)
INTEGER | N, IFAIL
REAL (KIND=nag_wp) | X(N), A(N), W, PW
LOGICAL | CALWTS

3 Description

G01DDF calculates Shapiro and Wilk's W statistic and its significance level for any sample size between 3 and 5000. It is an adaptation of the Applied Statistics Algorithm AS R94, see Royston (1995). The full description of the theory behind this algorithm is given in Royston (1992).
Given a set of observations x 1,x 2,…,xn sorted into either ascending or descending order (M01CAF may be used to sort the data) this routine calculates the value of Shapiro and Wilk's W statistic defined as:
W= ∑i=1 n aixi 2 ∑i=1 n xi-x- 2 ,
where x- = 1 n ∑1 n xi is the sample mean and ai , for i=1,2,…,n , are a set of ‘weights’ whose values depend only on the sample size n.
On exit, the values of ai, for i=1,2,…,n, are only of interest should you wish to call the routine again to calculate W and its significance level for a different sample of the same size.
It is recommended that the routine is used in conjunction with a Normal Q-Q plot of the data. Routines G01DAF and G01DBF can be used to obtain the required Normal scores.

4 References

Royston J P (1982) Algorithm AS 181: the W test for normality Appl. Statist. 31 176–180
Royston J P (1986) A remark on AS 181: the W test for normality Appl. Statist. 35 232–234
Royston J P (1992) Approximating the Shapiro–Wilk's W test for non-normality Statistics & Computing 2 117–119
Royston J P (1995) A remark on AS R94: A remark on Algorithm AS 181: the W test for normality Appl. Statist. 44(4) 547–551

5 Arguments

1:   X N – REAL (KIND=nag_wp) arrayInput
On entry: the ordered sample values, xi, for i=1,2,…,n.
2:   N – INTEGERInput
On entry: n, the sample size.
Constraint: 3≤N≤5000.
3:   CALWTS – LOGICALInput
On entry: must be set to .TRUE. if you wish G01DDF to calculate the elements of A.
CALWTS should be set to .FALSE. if you have saved the values in A from a previous call to G01DDF.
If in doubt, set CALWTS equal to .TRUE..
4:   A N – REAL (KIND=nag_wp) arrayInput/Output
On entry: if CALWTS has been set to .FALSE. then before entry A must contain the n weights as calculated in a previous call to G01DDF, otherwise A need not be set.
On exit: the n weights required to calculate W.
5:   W – REAL (KIND=nag_wp)Output
On exit: the value of the statistic, W.
6:   PW – REAL (KIND=nag_wp)Output
On exit: the significance level of W.
7:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, N<3.
IFAIL=2
On entry, N>5000.
IFAIL=3
On entry, the elements in X are not in ascending or descending order or are all equal.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

There may be a loss of significant figures for large n.

8 Parallelism and Performance

G01DDF is not threaded in any implementation.

9 Further Comments

The time taken by G01DDF depends roughly linearly on the value of n.
For very small samples the power of the test may not be very high.
The contents of the array A should not be modified between calls to G01DDF for a given sample size, unless CALWTS is reset to .TRUE. before each call of G01DDF.
The Shapiro and Wilk's W test is very sensitive to ties. If the data has been rounded the test can be improved by using Sheppard's correction to adjust the sum of squares about the mean. This produces an adjusted value of W,
WA=W ∑ x i - x- 2 ∑i=1 n x i=x- 2 - n-1 12 ω 2 ,
where ω is the rounding width. WA can be compared with a standard Normal distribution, but a further approximation is given by Royston (1986).
If N>5000, a value for W and PW is returned, but its accuracy may not be acceptable. See Section 4 for more details.

10 Example

This example tests the following two samples (each of size 20) for Normality.
Sample Number | Data
1 | 0.11, 7.87, 4.61, 10.14, 7.95, 3.14, 0.46, 4.43, 0.21, 4.75, 0.71, 1.52, 3.24, 0.93, 0.42, 4.97, 9.53, 4.55, 0.47, 6.66
2 | 1.36, 1.14, 2.92, 2.55, 1.46, 1.06, 5.27, -1.11, 3.48, 1.10, 0.88, -0.51, 1.46, 0.52, 6.20, 1.69, 0.08, 3.67, 2.81, 3.49
The elements of A are calculated only in the first call of G01DDF, and are re-used in the second call.

10.1 Program Text

Program Text (g01ddfe.f90)

10.2 Program Data

Program Data (g01ddfe.d)

10.3 Program Results

Program Results (g01ddfe.r)

G01 Chapter Contents
G01 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


G01DHF : NAG Library, Mark 26

G01 Chapter Contents
G01 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

G01DHF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

G01DHF computes the ranks, Normal scores, an approximation to the Normal scores or the exponential scores as requested by you.

2 Specification

SUBROUTINE G01DHF ( SCORES, TIES, N, X, R, IWRK, IFAIL)
INTEGER | N, IWRK(N), IFAIL
REAL (KIND=nag_wp) | X(N), R(N)
CHARACTER(1) | SCORES, TIES

3 Description

G01DHF computes one of the following scores for a sample of observations, x 1,x 2,…,xn.
1. Rank Scores
The ranks are assigned to the data in ascending order, that is the ith observation has score si=k if it is the kth smallest observation in the sample.
2. Normal Scores
The Normal scores are the expected values of the Normal order statistics from a sample of size n. If xi is the kth smallest observation in the sample, then the score for that observation, si, is E Zk where Zk is the kth order statistic in a sample of size n from a standard Normal distribution and E is the expectation operator.
3. Blom, Tukey and van der Waerden Scores
These scores are approximations to the Normal scores. The scores are obtained by evaluating the inverse cumulative Normal distribution function, Φ-1(·), at the values of the ranks scaled into the interval 0,1 using different scaling transformations.
The Blom scores use the scaling transformation ri-38 n+14 for the rank ri, for i=1,2,…,n. Thus the Blom score corresponding to the observation xi is
si = Φ-1 ri - 38 n+14 .
The Tukey scores use the scaling transformation ri-13 n+13 ; the Tukey score corresponding to the observation xi is
si = Φ-1 ri - 13 n+13 .
The van der Waerden scores use the scaling transformation ri n+1; the van der Waerden score corresponding to the observation xi is
si = Φ-1 ri n+1 .
The van der Waerden scores may be used to carry out the van der Waerden test for testing for differences between several population distributions, see Conover (1980).
4. Savage Scores
The Savage scores are the expected values of the exponential order statistics from a sample of size n. They may be used in a test discussed by Savage (1956) and Lehmann (1975). If xi is the kth smallest observation in the sample, then the score for that observation is
si = E Yk = 1 n + 1 n-1 + ⋯ + 1 n-k+1 ,
where Yk is the kth order statistic in a sample of size n from a standard exponential distribution and E is the expectation operator.
Ties may be handled in one of five ways. Let x t i, for i=1,2,…,m, denote m tied observations, that is x t 1=x t 2=⋯=x t m with t 1<t 2<⋯<t m. If the rank of x t 1 is k, then if ties are ignored the rank of x t j will be k+j-1. Let the scores ignoring ties be s t 1*,s t 2*,…,s t m*. Then the scores, s t i, for i=1,2,…,m, may be calculated as follows:
  • – if averages are used, then s t i=∑j=1 m s t j*/m;
  • – if the lowest score is used, then s t i=s t 1*;
  • – if the highest score is used, then s t i=s t m*;
  • – if ties are to be broken randomly, then s t i=s t I* where I∈random permutation of ​1,2,…,m;
  • – if ties are to be ignored, then s t i=s t i*.

4 References

Blom G (1958) Statistical Estimates and Transformed Beta-variables Wiley
Conover W J (1980) Practical Nonparametric Statistics Wiley
Lehmann E L (1975) Nonparametrics: Statistical Methods Based on Ranks Holden–Day
Savage I R (1956) Contributions to the theory of rank order statistics – the two-sample case Ann. Math. Statist. 27 590–615
Tukey J W (1962) The future of data analysis Ann. Math. Statist. 33 1–67

5 Arguments

1:   SCORES – CHARACTER(1)Input
On entry: indicates which of the following scores are required.
SCORES='R'
The ranks.
SCORES='N'
The Normal scores, that is the expected value of the Normal order statistics.
SCORES='B'
The Blom version of the Normal scores.
SCORES='T'
The Tukey version of the Normal scores.
SCORES='V'
The van der Waerden version of the Normal scores.
SCORES='S'
The Savage scores, that is the expected value of the exponential order statistics.
Constraint: SCORES='R', 'N', 'B', 'T', 'V' or 'S'.
2:   TIES – CHARACTER(1)Input
On entry: indicates which of the following methods is to be used to assign scores to tied observations.
TIES='A'
The average of the scores for tied observations is used.
TIES='L'
The lowest score in the group of ties is used.
TIES='H'
The highest score in the group of ties is used.
TIES='N'
The nonrepeatable random number generator is used to randomly untie any group of tied observations.
TIES='R'
The repeatable random number generator is used to randomly untie any group of tied observations.
TIES='I'
Any ties are ignored, that is the scores are assigned to tied observations in the order that they appear in the data.
Constraint: TIES='A', 'L', 'H', 'N', 'R' or 'I'.
3:   N – INTEGERInput
On entry: n, the number of observations.
Constraint: N≥1.
4:   X N – REAL (KIND=nag_wp) arrayInput
On entry: the sample of observations, xi, for i=1,2,…,n.
5:   R N – REAL (KIND=nag_wp) arrayOutput
On exit: contains the scores, si, for i=1,2,…,n, as specified by SCORES.
6:   IWRK N – INTEGER arrayWorkspace
7:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, | SCORES≠'R', 'N', 'B', 'T', 'V' or 'S',
or | TIES≠'A', 'L', 'H', 'N', 'R' or 'I',
or | N<1.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

For SCORES='R', the results should be accurate to machine precision.
For SCORES='S', the results should be accurate to a small multiple of machine precision.
For SCORES='N', the results should have a relative accuracy of at least max 100×ε,10-8 where ε is the machine precision.
For SCORES='B', 'T' or 'V', the results should have a relative accuracy of at least max 10×ε,10-12.

8 Parallelism and Performance

G01DHF is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

If more accurate Normal scores are required G01DAF should be used with appropriate settings for the input argument ETOL.

10 Example

This example computes and prints the Savage scores for a sample of five observations. The average of the scores of any tied observations is used.

10.1 Program Text

Program Text (g01dhfe.f90)

10.2 Program Data

Program Data (g01dhfe.d)

10.3 Program Results

Program Results (g01dhfe.r)

G01 Chapter Contents
G01 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


G01EAF : NAG Library, Mark 26

G01 Chapter Contents
G01 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

G01EAF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

G01EAF returns a one or two tail probability for the standard Normal distribution, via the routine name.

2 Specification

FUNCTION G01EAF ( TAIL, X, IFAIL)
REAL (KIND=nag_wp) G01EAF
INTEGER | IFAIL
REAL (KIND=nag_wp) | X
CHARACTER(1) | TAIL

3 Description

The lower tail probability for the standard Normal distribution, P X≤x is defined by:
P X≤x=∫-∞x Z X dX,
where
Z X=1 2 π e-X 2/2, -∞<X< ∞.
The relationship
P X≤x=12 erfc-x 2
is used, where erfc is the complementary error function, and is computed using S15ADF. For the upper tail probability the relationship P X≥x=P X≤-x is used and for the two tail significance level probability twice the probability obtained from the absolute value of x is returned.
When the two tail confidence probability is required the relationship
P X≤x-P X≤-x=erf x 2 ,
is used, where erf is the error function, and is computed using S15AEF.

4 References

Abramowitz M and Stegun I A (1972) Handbook of Mathematical Functions (3rd Edition) Dover Publications
Hastings N A J and Peacock J B (1975) Statistical Distributions Butterworth

5 Arguments

1:   TAIL – CHARACTER(1)Input
On entry: indicates which tail the returned probability should represent.
TAIL='L'
The lower tail probability is returned, i.e., P X≤x.
TAIL='U'
The upper tail probability is returned, i.e., P X≥x.
TAIL='S'
The two tail (significance level) probability is returned, i.e., P X≥x+P X≤-x.
TAIL='C'
The two tail (confidence interval) probability is returned, i.e., P X≤x-P X≤-x.
Constraint: TAIL='L', 'U', 'S' or 'C'.
2:   X – REAL (KIND=nag_wp)Input
On entry: x, the value of the standard Normal variate.
3:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
If IFAIL≠0, then G01EAF returns 0.0.
IFAIL=1
On entry, TAIL≠'L', 'U', 'S' or 'C'.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

Accuracy is limited by machine precision. For detailed error analysis see S15ADF and S15AEF.

8 Parallelism and Performance

G01EAF is not threaded in any implementation.

9 Further Comments

None.

10 Example

Four values of TAIL and X are input and the probabilities calculated and printed.

10.1 Program Text

Program Text (g01eafe.f90)

10.2 Program Data

Program Data (g01eafe.d)

10.3 Program Results

Program Results (g01eafe.r)

G01 Chapter Contents
G01 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


G01EBF : NAG Library, Mark 26

G01 Chapter Contents
G01 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

G01EBF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

G01EBF returns the lower tail, upper tail or two tail probability for the Student's t-distribution with real degrees of freedom, via the routine name.

2 Specification

FUNCTION G01EBF ( TAIL, T, DF, IFAIL)
REAL (KIND=nag_wp) G01EBF
INTEGER | IFAIL
REAL (KIND=nag_wp) | T, DF
CHARACTER(1) | TAIL

3 Description

The lower tail probability for the Student's t-distribution with ν degrees of freedom, P T≤t:ν is defined by:
P T≤t:ν = Γ ν+1 / 2 πν Γ ν/2 ∫ -∞ t 1+ T 2 ν -ν+1 / 2 dT ,   ν≥1 .
Computationally, there are two situations:
(i) when ν<20, a transformation of the beta distribution, Pβ B≤β:a,b is used
P T≤t:ν = 12 Pβ B≤ ν ν+t 2 : ν/2, 12   when ​ t<0.0
or
P T≤t:ν = 12 + 12 Pβ B≥ ν ν+t 2 : ν/2, 12   when ​ t>0.0 ;
(ii) when ν≥20, an asymptotic normalizing expansion of the Cornish–Fisher type is used to evaluate the probability, see Hill (1970).

4 References

Abramowitz M and Stegun I A (1972) Handbook of Mathematical Functions (3rd Edition) Dover Publications
Hastings N A J and Peacock J B (1975) Statistical Distributions Butterworth
Hill G W (1970) Student's t-distribution Comm. ACM 13(10) 617–619

5 Arguments

1:   TAIL – CHARACTER(1)Input
On entry: indicates which tail the returned probability should represent.
TAIL='U'
The upper tail probability is returned, i.e., P T≥t:ν.
TAIL='S'
The two tail (significance level) probability is returned, i.e., P T≥t:ν+P T≤-t:ν.
TAIL='C'
The two tail (confidence interval) probability is returned, i.e., P T≤t:ν-P T≤-t:ν.
TAIL='L'
The lower tail probability is returned, i.e., P T≤t:ν.
Constraint: TAIL='U', 'S', 'C' or 'L'.
2:   T – REAL (KIND=nag_wp)Input
On entry: t, the value of the Student's t variate.
3:   DF – REAL (KIND=nag_wp)Input
On entry: ν, the degrees of freedom of the Student's t-distribution.
Constraint: DF≥1.0.
4:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
If IFAIL≠0, then G01EBF returns 0.0.
IFAIL=1
On entry, TAIL≠'U', 'S', 'C' or 'L'.
IFAIL=2
On entry, DF<1.0.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

The computed probability should be accurate to five significant places for reasonable probabilities but there will be some loss of accuracy for very low probabilities (less than 10-10), see Hastings and Peacock (1975).

8 Parallelism and Performance

G01EBF is not threaded in any implementation.

9 Further Comments

The probabilities could also be obtained by using the appropriate transformation to a beta distribution (see Abramowitz and Stegun (1972)) and using G01EEF. This routine allows you to set the required accuracy.

10 Example

This example reads values from, and degrees of freedom for Student's t-distributions along with the required tail. The probabilities are calculated and printed until the end of data is reached.

10.1 Program Text

Program Text (g01ebfe.f90)

10.2 Program Data

Program Data (g01ebfe.d)

10.3 Program Results

Program Results (g01ebfe.r)

G01 Chapter Contents
G01 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


G01ECF : NAG Library, Mark 26

G01 Chapter Contents
G01 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

G01ECF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

G01ECF returns the lower or upper tail probability for the χ 2-distribution with real degrees of freedom, via the routine name.

2 Specification

FUNCTION G01ECF ( TAIL, X, DF, IFAIL)
REAL (KIND=nag_wp) G01ECF
INTEGER | IFAIL
REAL (KIND=nag_wp) | X, DF
CHARACTER(1) | TAIL

3 Description

The lower tail probability for the χ 2-distribution with ν degrees of freedom, P X≤x:ν is defined by:
P X≤x:ν=1 2 ν/2 Γ ν/2 ∫0.0 x X ν/2-1e-X/2 dX,  x≥0,ν>0.
To calculate P X≤x:ν a transformation of a gamma distribution is employed, i.e., a χ 2-distribution with ν degrees of freedom is equal to a gamma distribution with scale parameter 2 and shape parameter ν/2.

4 References

Abramowitz M and Stegun I A (1972) Handbook of Mathematical Functions (3rd Edition) Dover Publications
Hastings N A J and Peacock J B (1975) Statistical Distributions Butterworth

5 Arguments

1:   TAIL – CHARACTER(1)Input
On entry: indicates whether the upper or lower tail probability is required.
TAIL='L'
The lower tail probability is returned, i.e., P X≤x:ν.
TAIL='U'
The upper tail probability is returned, i.e., P X≥x:ν.
Constraint: TAIL='L' or 'U'.
2:   X – REAL (KIND=nag_wp)Input
On entry: x, the value of the χ 2 variate with ν degrees of freedom.
Constraint: X≥0.0.
3:   DF – REAL (KIND=nag_wp)Input
On entry: ν, the degrees of freedom of the χ 2-distribution.
Constraint: DF>0.0.
4:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, because for this routine the values of the output arguments may be useful even if IFAIL≠0 on exit, the recommended value is -1. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Note: G01ECF may return useful information for one or more of the following detected errors or warnings.
Errors or warnings detected by the routine:
If IFAIL=1, 2 or 3 on exit, then G01ECF returns 0.0.
IFAIL=1
On entry, TAIL≠'L' or 'U'.
IFAIL=2
On entry, X<0.0.
IFAIL=3
On entry, DF≤0.0.
IFAIL=4
The solution has failed to converge while calculating the gamma variate. The result returned should represent an approximation to the solution.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

A relative accuracy of five significant figures is obtained in most cases.

8 Parallelism and Performance

G01ECF is not threaded in any implementation.

9 Further Comments

For higher accuracy the transformation described in Section 3 may be used with a direct call to S14BAF.

10 Example

Values from various χ 2-distributions are read, the lower tail probabilities calculated, and all these values printed out, until the end of data is reached.

10.1 Program Text

Program Text (g01ecfe.f90)

10.2 Program Data

Program Data (g01ecfe.d)

10.3 Program Results

Program Results (g01ecfe.r)

G01 Chapter Contents
G01 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


G01EDF : NAG Library, Mark 26

G01 Chapter Contents
G01 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

G01EDF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

G01EDF returns the probability for the lower or upper tail of the F or variance-ratio distribution with real degrees of freedom, via the routine name.

2 Specification

FUNCTION G01EDF ( TAIL, F, DF1, DF2, IFAIL)
REAL (KIND=nag_wp) G01EDF
INTEGER | IFAIL
REAL (KIND=nag_wp) | F, DF1, DF2
CHARACTER(1) | TAIL

3 Description

The lower tail probability for the F, or variance-ratio distribution, with ν 1 and ν 2 degrees of freedom, P F≤f:ν 1,ν 2, is defined by:
P F≤f:ν 1,ν 2=ν 1 ν 1/2ν 2 ν 2/2 Γ ν 1+ν 2/2 Γ ν 1/2 Γ ν 2/2 ∫0 f F ν 1-2/2ν 1 F+ν 2- ν 1+ν 2/2 dF,
for ν 1, ν 2>0, f≥0.
The probability is computed by means of a transformation to a beta distribution, Pβ B≤β:a,b:
P F≤f:ν 1,ν 2=Pβ B≤ν 1 f ν 1 f+ν 2 :ν 1/2,ν 2/2
and using a call to G01EEF.
For very large values of both ν 1 and ν 2, greater than 105, a normal approximation is used. If only one of ν 1 or ν 2 is greater than 105 then a χ 2 approximation is used, see Abramowitz and Stegun (1972).

4 References

Abramowitz M and Stegun I A (1972) Handbook of Mathematical Functions (3rd Edition) Dover Publications
Hastings N A J and Peacock J B (1975) Statistical Distributions Butterworth

5 Arguments

1:   TAIL – CHARACTER(1)Input
On entry: indicates whether an upper or lower tail probability is required.
TAIL='L'
The lower tail probability is returned, i.e., P F≤f:ν 1,ν 2.
TAIL='U'
The upper tail probability is returned, i.e., P F≥f:ν 1,ν 2.
Constraint: TAIL='L' or 'U'.
2:   F – REAL (KIND=nag_wp)Input
On entry: f, the value of the F variate.
Constraint: F≥0.0.
3:   DF1 – REAL (KIND=nag_wp)Input
On entry: the degrees of freedom of the numerator variance, ν 1.
Constraint: DF1>0.0.
4:   DF2 – REAL (KIND=nag_wp)Input
On entry: the degrees of freedom of the denominator variance, ν 2.
Constraint: DF2>0.0.
5:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, because for this routine the values of the output arguments may be useful even if IFAIL≠0 on exit, the recommended value is -1. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Note: G01EDF may return useful information for one or more of the following detected errors or warnings.
Errors or warnings detected by the routine:
If IFAIL=1, 2 or 3 on exit, then G01EDF returns 0.0.
IFAIL=1
On entry, TAIL≠'L' or 'U'.
IFAIL=2
On entry, F<0.0.
IFAIL=3
On entry, | DF1≤0.0,
or | DF2≤0.0.
IFAIL=4
F is too far out into the tails for the probability to be evaluated exactly. The result tends to approach 1.0 if f is large, or 0.0 if f is small. The result returned is a good approximation to the required solution.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

The result should be accurate to five significant digits.

8 Parallelism and Performance

G01EDF is not threaded in any implementation.

9 Further Comments

For higher accuracy G01EEF can be used along with the transformations given in Section 3.

10 Example

This example reads values from, and degrees of freedom for, a number of F-distributions and computes the associated lower tail probabilities.

10.1 Program Text

Program Text (g01edfe.f90)

10.2 Program Data

Program Data (g01edfe.d)

10.3 Program Results

Program Results (g01edfe.r)

G01 Chapter Contents
G01 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


G01EEF : NAG Library, Mark 26

G01 Chapter Contents
G01 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

G01EEF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

G01EEF computes the upper and lower tail probabilities and the probability density function of the beta distribution with parameters a and b.

2 Specification

SUBROUTINE G01EEF ( X, A, B, TOL, P, Q, PDF, IFAIL)
INTEGER | IFAIL
REAL (KIND=nag_wp) | X, A, B, TOL, P, Q, PDF

3 Description

The probability density function of the beta distribution with parameters a and b is:
f B:a,b=Γ a+b Γ a Γ b B a-11-B b-1,  0≤B≤1;a,b>0.
The lower tail probability, P B≤β:a,b is defined by
P B≤β:a,b=Γ a+b Γ a Γ b ∫0 β B a-11-B b-1 dB=Iβ a,b,  0≤β≤1;a,b>0.
The function Ix a,b, also known as the incomplete beta function is calculated using S14CCF.

4 References

Hastings N A J and Peacock J B (1975) Statistical Distributions Butterworth

5 Arguments

1:   X – REAL (KIND=nag_wp)Input
On entry: β, the value of the beta variate.
Constraint: 0.0≤X≤1.0.
2:   A – REAL (KIND=nag_wp)Input
On entry: a, the first parameter of the required beta distribution.
Constraint: 0.0<A≤106.
3:   B – REAL (KIND=nag_wp)Input
On entry: b, the second parameter of the required beta distribution.
Constraint: 0.0<B≤106.
4:   TOL – REAL (KIND=nag_wp)Input
On entry: this argument is no longer referenced, but is included for backwards compatability.
5:   P – REAL (KIND=nag_wp)Output
On exit: the lower tail probability, P B≤β:a,b.
6:   Q – REAL (KIND=nag_wp)Output
On exit: the upper tail probability, P B≥β:a,b.
7:   PDF – REAL (KIND=nag_wp)Output
On exit: the probability density function, f B:a,b.
8:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, because for this routine the values of the output arguments may be useful even if IFAIL≠0 on exit, the recommended value is -1. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Note: G01EEF may return useful information for one or more of the following detected errors or warnings.
Errors or warnings detected by the routine:
IFAIL=1
On entry, | X<0.0,
or | X>1.0.
IFAIL=2
On entry, | A≤0.0,
or | A>106,
or | B≤0.0,
or | B>106.
IFAIL=4
X is too far out into the tails for the probability to be evaluated exactly. The results returned are 0 and 1 as appropriate. These should be a good approximation to the required solution.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

The accuracy is limited by the error in the incomplete beta function. See Section 7 in S14CCF for further details.

8 Parallelism and Performance

G01EEF is not threaded in any implementation.

9 Further Comments

None.

10 Example

This example reads values from a number of beta distributions and computes the associated upper and lower tail probabilities and the corresponding value of the probability density function.

10.1 Program Text

Program Text (g01eefe.f90)

10.2 Program Data

Program Data (g01eefe.d)

10.3 Program Results

Program Results (g01eefe.r)

G01 Chapter Contents
G01 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


G01EFF : NAG Library, Mark 26

G01 Chapter Contents
G01 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

G01EFF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

G01EFF returns the lower or upper tail probability of the gamma distribution, with parameters α and β, via the routine name.

2 Specification

FUNCTION G01EFF ( TAIL, G, A, B, IFAIL)
REAL (KIND=nag_wp) G01EFF
INTEGER | IFAIL
REAL (KIND=nag_wp) | G, A, B
CHARACTER(1) | TAIL

3 Description

The lower tail probability for the gamma distribution with parameters α and β, P G≤g, is defined by:
P G≤g ; α,β = 1 βα Γ α ∫0 g G α-1 e-G/β dG ,   α>0.0 , ​ β>0.0 .
The mean of the distribution is αβ and its variance is α β 2. The transformation Z=Gβ is applied to yield the following incomplete gamma function in normalized form,
P G≤g ; α ,β = P Z≤g/β : α,1.0 = 1 Γ α ∫0 g/β Z α-1 e-Z dZ .
This is then evaluated using S14BAF.

4 References

Hastings N A J and Peacock J B (1975) Statistical Distributions Butterworth

5 Arguments

1:   TAIL – CHARACTER(1)Input
On entry: indicates whether an upper or lower tail probability is required.
TAIL='L'
The lower tail probability is returned, that is P G≤g:α,β.
TAIL='U'
The upper tail probability is returned, that is P G≥g:α,β.
Constraint: TAIL='L' or 'U'.
2:   G – REAL (KIND=nag_wp)Input
On entry: g, the value of the gamma variate.
Constraint: G≥0.0.
3:   A – REAL (KIND=nag_wp)Input
On entry: the parameter α of the gamma distribution.
Constraint: A>0.0.
4:   B – REAL (KIND=nag_wp)Input
On entry: the parameter β of the gamma distribution.
Constraint: B>0.0.
5:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
If IFAIL=1, 2, 3 or 4 on exit, then G01EFF returns 0.0.
IFAIL=1
On entry, TAIL≠'L' or 'U'.
IFAIL=2
On entry, G<0.0.
IFAIL=3
On entry, | A≤0.0,
or | B≤0.0.
IFAIL=4
The solution did not converge in 600 iterations. See S14BAF. The probability returned should be a reasonable approximation to the solution.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

The result should have a relative accuracy of machine precision. There are rare occasions when the relative accuracy attained is somewhat less than machine precision but the error should not exceed more than 1 or 2 decimal places. Note also that there is a limit of 18 decimal places on the achievable accuracy, because constants in S14BAF are given to this precision.

8 Parallelism and Performance

G01EFF is not threaded in any implementation.

9 Further Comments

The time taken by G01EFF varies slightly with the input arguments G, A and B.

10 Example

This example reads in values from a number of gamma distributions and computes the associated lower tail probabilities.

10.1 Program Text

Program Text (g01effe.f90)

10.2 Program Data

Program Data (g01effe.d)

10.3 Program Results

Program Results (g01effe.r)

G01 Chapter Contents
G01 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


G01EMF : NAG Library, Mark 26

G01 Chapter Contents
G01 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

G01EMF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

G01EMF returns the probability associated with the lower tail of the distribution of the Studentized range statistic, via the routine name.

2 Specification

FUNCTION G01EMF ( Q, V, IR, IFAIL)
REAL (KIND=nag_wp) G01EMF
INTEGER | IR, IFAIL
REAL (KIND=nag_wp) | Q, V

3 Description

The externally Studentized range, q, for a sample, x 1,x 2,…,xr, is defined as:
q = max⁡xi - min⁡xi σ^e ,
where σ^e is an independent estimate of the standard error of the xi's. The most common use of this statistic is in the testing of means from a balanced design. In this case for a set of group means, T-1,T-2,…,T-r, the Studentized range statistic is defined to be the difference between the largest and smallest means, T-largest and T-smallest, divided by the square root of the mean-square experimental error, M Serror, over the number of observations in each group, n, i.e.,
q=T-largest-T-smallest M Serror/n .
The Studentized range statistic can be used as part of a multiple comparisons procedure such as the Newman–Keuls procedure or Duncan's multiple range test (see Montgomery (1984) and Winer (1970)).
For a Studentized range statistic the probability integral, P q;v,r, for v degrees of freedom and r groups can be written as:
P q;v,r=C∫0∞x v-1e-v x 2/2 r∫-∞∞ϕ y Φ y-Φ y-qx r-1 dy dx,
where
C=v v/2 Γ v/2 2 v/2- 1 ,   ϕ y=1 2 π e-y 2/2   and   Φ y=∫-∞y ϕ t dt.
The above two-dimensional integral is evaluated using D01DAF with the upper and lower limits computed to give stated accuracy (see Section 7).
If the degrees of freedom v are greater than 2000 the probability integral can be approximated by its asymptotic form:
P q;r=r∫-∞∞ϕ y Φ y-Φ y-q r-1 dy.
This integral is evaluated using D01AMF.

4 References

Abramowitz M and Stegun I A (1972) Handbook of Mathematical Functions (3rd Edition) Dover Publications
Lund R E and Lund J R (1983) Algorithm AS 190: probabilities and upper quartiles for the studentized range Appl. Statist. 32(2) 204–210
Montgomery D C (1984) Design and Analysis of Experiments Wiley
Winer B J (1970) Statistical Principles in Experimental Design McGraw–Hill

5 Arguments

1:   Q – REAL (KIND=nag_wp)Input
On entry: q, the Studentized range statistic.
Constraint: Q>0.0.
2:   V – REAL (KIND=nag_wp)Input
On entry: v, the number of degrees of freedom for the experimental error.
Constraint: V≥1.0.
3:   IR – INTEGERInput
On entry: r, the number of groups.
Constraint: IR≥2.
4:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, because for this routine the values of the output arguments may be useful even if IFAIL≠0 on exit, the recommended value is -1. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).
If on exit IFAIL=1, then G01EMF returns to 0.0.

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Note: G01EMF may return useful information for one or more of the following detected errors or warnings.
Errors or warnings detected by the routine:
IFAIL=1
On entry, | Q≤0.0,
or | V<1.0,
or | IR<2.
IFAIL=2
There is some doubt as to whether full accuracy has been achieved.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

The returned value will have absolute accuracy to at least four decimal places (usually five), unless IFAIL=2. When IFAIL=2 it is usual that the returned value will be a good estimate of the true value.

8 Parallelism and Performance

G01EMF is not threaded in any implementation.

9 Further Comments

None.

10 Example

The lower tail probabilities for the distribution of the Studentized range statistic are computed and printed for a range of values of q, ν and r.

10.1 Program Text

Program Text (g01emfe.f90)

10.2 Program Data

Program Data (g01emfe.d)

10.3 Program Results

Program Results (g01emfe.r)

G01 Chapter Contents
G01 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


G01EPF : NAG Library, Mark 26

G01 Chapter Contents
G01 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

G01EPF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

G01EPF calculates upper and lower bounds for the significance of a Durbin–Watson statistic.

2 Specification

SUBROUTINE G01EPF ( N, IP, D, PDL, PDU, WORK, IFAIL)
INTEGER | N, IP, IFAIL
REAL (KIND=nag_wp) | D, PDL, PDU, WORK(N)

3 Description

Let r = r 1,r 2,…,rn T be the residuals from a linear regression of y on p independent variables, including the mean, where the y values y 1,y 2,…,yn can be considered as a time series. The Durbin–Watson test (see Durbin and Watson (1950), Durbin and Watson (1951) and Durbin and Watson (1971)) can be used to test for serial correlation in the error term in the regression.
The Durbin–Watson test statistic is:
d=∑i=1 n-1 r i+1-ri 2 ∑i=1 n ri 2 ,
which can be written as
d=rT Ar rT r ,
where the n by n matrix A is given by
A= 1 -1 0 … : -1 2 -1 … : 0 -1 2 … : : 0 -1 … : : : : … : : : : … -1 0 0 0 … 1
with the nonzero eigenvalues of the matrix A being λj=1-cos πj/n, for j=1,2,…,n-1.
Durbin and Watson show that the exact distribution of d depends on the eigenvalues of a matrix HA, where H is the hat matrix of independent variables, i.e., the matrix such that the vector of fitted values, y^, can be written as y^=Hy. However, bounds on the distribution can be obtained, the lower bound being
dl=∑i=1 n-p λi ui 2 ∑i=1 n-p ui 2
and the upper bound being
du=∑i= 1 n-p λ i- 1+p ui 2 ∑i= 1 n-p ui 2 ,
where ui are independent standard Normal variables.
Two algorithms are used to compute the lower tail (significance level) probabilities, pl and pu, associated with dl and du. If n≤60 the procedure due to Pan (1964) is used, see Farebrother (1980), otherwise Imhof's method (see Imhof (1961)) is used.
The bounds are for the usual test of positive correlation; if a test of negative correlation is required the value of d should be replaced by 4-d.

4 References

Durbin J and Watson G S (1950) Testing for serial correlation in least squares regression. I Biometrika 37 409–428
Durbin J and Watson G S (1951) Testing for serial correlation in least squares regression. II Biometrika 38 159–178
Durbin J and Watson G S (1971) Testing for serial correlation in least squares regression. III Biometrika 58 1–19
Farebrother R W (1980) Algorithm AS 153. Pan's procedure for the tail probabilities of the Durbin–Watson statistic Appl. Statist. 29 224–227
Imhof J P (1961) Computing the distribution of quadratic forms in Normal variables Biometrika 48 419–426
Newbold P (1988) Statistics for Business and Economics Prentice–Hall
Pan Jie–Jian (1964) Distributions of the noncircular serial correlation coefficients Shuxue Jinzhan 7 328–337

5 Arguments

1:   N – INTEGERInput
On entry: n, the number of observations used in calculating the Durbin–Watson statistic.
Constraint: N>IP.
2:   IP – INTEGERInput
On entry: p, the number of independent variables in the regression model, including the mean.
Constraint: IP≥1.
3:   D – REAL (KIND=nag_wp)Input
On entry: d, the Durbin–Watson statistic.
Constraint: D≥0.0.
4:   PDL – REAL (KIND=nag_wp)Output
On exit: lower bound for the significance of the Durbin–Watson statistic, pl.
5:   PDU – REAL (KIND=nag_wp)Output
On exit: upper bound for the significance of the Durbin–Watson statistic, pu.
6:   WORK N – REAL (KIND=nag_wp) arrayWorkspace
7:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, | N≤IP,
or | IP<1.
IFAIL=2
On entry, D<0.0.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

On successful exit at least 4 decimal places of accuracy are achieved.

8 Parallelism and Performance

G01EPF is not threaded in any implementation.

9 Further Comments

If the exact probabilities are required, then the first n-p eigenvalues of HA can be computed and G01JDF used to compute the required probabilities with C set to 0.0 and D to the Durbin–Watson statistic.

10 Example

The values of n, p and the Durbin–Watson statistic d are input and the bounds for the significance level calculated and printed.

10.1 Program Text

Program Text (g01epfe.f90)

10.2 Program Data

Program Data (g01epfe.d)

10.3 Program Results

Program Results (g01epfe.r)

G01 Chapter Contents
G01 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


G01ERF : NAG Library, Mark 26

G01 Chapter Contents
G01 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

G01ERF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

G01ERF returns the probability associated with the lower tail of the von Mises distribution between -π and π through the function name.

2 Specification

FUNCTION G01ERF ( T, VK, IFAIL)
REAL (KIND=nag_wp) G01ERF
INTEGER | IFAIL
REAL (KIND=nag_wp) | T, VK

3 Description

The von Mises distribution is a symmetric distribution used in the analysis of circular data. The lower tail area of this distribution on the circle with mean direction μ 0=0 and concentration argument kappa, κ, can be written as
Pr Θ≤θ:κ=1 2 π I 0 κ ∫-π θ e κ cos⁡Θ dΘ,
where θ is reduced modulo 2 π so that -π≤θ<π and κ≥0. Note that if θ=π then G01ERF returns a probability of 1. For very small κ the distribution is almost the uniform distribution, whereas for κ→∞ all the probability is concentrated at one point.
The method of calculation for small κ involves backwards recursion through a series expansion in terms of modified Bessel functions, while for large κ an asymptotic Normal approximation is used.
In the case of small κ the series expansion of Pr(Θ≤θ: κ) can be expressed as
Pr Θ≤θ:κ=12+θ 2 π +1 π I 0 κ ∑n=1∞n-1 In κ sin⁡n θ,
where In κ is the modified Bessel function. This series expansion can be represented as a nested expression of terms involving the modified Bessel function ratio Rn,
Rn κ=In κ I n-1 κ ,  n=1,2,3,…,
which is calculated using backwards recursion.
For large values of κ (see Section 7) an asymptotic Normal approximation is used. The angle Θ is transformed to the nearly Normally distributed variate Z,
Z=b κ sin⁡Θ 2,
where
b κ=2 π eκ I 0 κ
and b κ is computed from a continued fraction approximation. An approximation to order κ-4 of the asymptotic normalizing series for z is then used. Finally the Normal probability integral is evaluated.
For a more detailed analysis of the methods used see Hill (1977).

4 References

Hill G W (1977) Algorithm 518: Incomplete Bessel function I 0: The Von Mises distribution ACM Trans. Math. Software 3 279–284
Mardia K V (1972) Statistics of Directional Data Academic Press

5 Arguments

1:   T – REAL (KIND=nag_wp)Input
On entry: θ, the observed von Mises statistic measured in radians.
2:   VK – REAL (KIND=nag_wp)Input
On entry: the concentration parameter κ, of the von Mises distribution.
Constraint: VK≥0.0.
3:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, VK<0.0 and G01ERF returns 0.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

G01ERF uses one of two sets of constants depending on the value of machine precision. One set gives an accuracy of six digits and uses the Normal approximation when VK≥6.5, the other gives an accuracy of 12 digits and uses the Normal approximation when VK≥50.0.

8 Parallelism and Performance

G01ERF is not threaded in any implementation.

9 Further Comments

Using the series expansion for small κ the time taken by G01ERF increases linearly with κ; for larger κ, for which the asymptotic Normal approximation is used, the time taken is much less.
If angles outside the region -π≤θ<π are used care has to be taken in evaluating the probability of being in a region θ 1≤θ≤θ 2 if the region contains an odd multiple of π, 2 n+1 π. The value of F θ 2;κ-F θ 1;κ will be negative and the correct probability should then be obtained by adding one to the value.

10 Example

This example inputs four values from the von Mises distribution along with the values of the argument κ. The probabilities are computed and printed.

10.1 Program Text

Program Text (g01erfe.f90)

10.2 Program Data

Program Data (g01erfe.d)

10.3 Program Results

Program Results (g01erfe.r)

G01 Chapter Contents
G01 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


G01ETF : NAG Library, Mark 26

G01 Chapter Contents
G01 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

G01ETF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

G01ETF returns the value of the Landau distribution function Φ λ, via the routine name.

2 Specification

FUNCTION G01ETF ( X)
REAL (KIND=nag_wp) G01ETF
REAL (KIND=nag_wp) X

3 Description

G01ETF evaluates an approximation to the Landau distribution function Φ λ given by
Φ λ=∫-∞λ ϕ λ dλ,
where ϕ λ is described in G01MTF, using piecewise approximation by rational functions. Further details can be found in Kölbig and Schorr (1984).

4 References

Kölbig K S and Schorr B (1984) A program package for the Landau distribution Comp. Phys. Comm. 31 97–111

5 Arguments

1:   X – REAL (KIND=nag_wp)Input
On entry: the argument λ of the function.

6 Error Indicators and Warnings

None.

7 Accuracy

At least 7 significant digits are usually correct, but occasionally only 6. Such accuracy is normally considered to be adequate for applications in experimental physics.
Because of the asymptotic behaviour of Φ λ, which is of the order of exp-exp-λ, underflow may occur on some machines when λ is moderately large and negative.

8 Parallelism and Performance

G01ETF is not threaded in any implementation.

9 Further Comments

None.

10 Example

This example evaluates Φ λ at λ=0.5, and prints the results.

10.1 Program Text

Program Text (g01etfe.f90)

10.2 Program Data

Program Data (g01etfe.d)

10.3 Program Results

Program Results (g01etfe.r)

G01 Chapter Contents
G01 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


G01EUF : NAG Library, Mark 26

G01 Chapter Contents
G01 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

G01EUF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

G01EUF returns the value of the Vavilov distribution function ΦV λ;κ,β 2, via the routine name.
It is intended to be used after a call to G01ZUF.

2 Specification

FUNCTION G01EUF ( X, RCOMM, IFAIL)
REAL (KIND=nag_wp) G01EUF
INTEGER | IFAIL
REAL (KIND=nag_wp) | X, RCOMM(322)

3 Description

G01EUF evaluates an approximation to the Vavilov distribution function ΦV λ;κ,β 2 given by
ΦV λ;κ,β 2=∫-∞λ ϕV λ;κ,β 2 dλ,
where ϕ λ is described in G01MUF. The method used is based on Fourier expansions. Further details can be found in Schorr (1974).

4 References

Schorr B (1974) Programs for the Landau and the Vavilov distributions and the corresponding random numbers Comp. Phys. Comm. 7 215–224

5 Arguments

1:   X – REAL (KIND=nag_wp)Input
On entry: the argument λ of the function.
2:   RCOMM 322 – REAL (KIND=nag_wp) arrayCommunication Array
On entry: this must be the same argument RCOMM as returned by a previous call to G01ZUF.
3:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
Either the initialization routine has not been called prior to the first call of this routine or a communication array has become corrupted.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

At least five significant digits are usually correct.

8 Parallelism and Performance

G01EUF is not threaded in any implementation.

9 Further Comments

G01EUF can be called repeatedly with different values of λ provided that the values of κ and β 2 remain unchanged between calls. Otherwise, G01ZUF must be called again. This is illustrated in Section 10.

10 Example

This example evaluates ΦV λ;κ,β 2 at λ=0.1, κ=2.5 and β 2=0.7, and prints the results.

10.1 Program Text

Program Text (g01eufe.f90)

10.2 Program Data

Program Data (g01eufe.d)

10.3 Program Results

Program Results (g01eufe.r)

G01 Chapter Contents
G01 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


G01EWF : NAG Library, Mark 26

G01 Chapter Contents
G01 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

G01EWF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
10 Example

1 Purpose

G01EWF returns the probability associated with the lower tail of the distribution for the Dickey–Fuller unit root test statistic.

2 Specification

FUNCTION G01EWF ( METHOD, TYPE, N, TS, NSAMP, STATE, IFAIL)
REAL (KIND=nag_wp) G01EWF
INTEGER | METHOD, TYPE, N, NSAMP, STATE(*), IFAIL
REAL (KIND=nag_wp) | TS

3 Description

If the root of the characteristic equation for a time series is one then that series is said to have a unit root. Such series are nonstationary. G01EWF is designed to be called after G13AWF and returns the probability associated with one of three types of (augmented) Dickey–Fuller test statistic: τ, τμ or ττ, used to test for a unit root, a unit root with drift or a unit root with drift and a deterministic time trend, respectively. The three types of test statistic are constructed as follows:
1. To test whether a time series, yt, for t=1,2,…,n, has a unit root the regression model
∇yt = β 1 y t-1 + ∑ i=1 p-1 δi ∇ y t-i +εt
is fit and the test statistic τ constructed as
τ = β^1 σ 11
where ∇ is the difference operator, with ∇yt = yt- y t-1 , and where β^1 and σ 11 are the least squares estimate and associated standard error for β 1 respectively.
2. To test for a unit root with drift the regression model
∇yt = β 1 y t-1 + ∑ i=1 p-1 δi ∇ y t-i +α +εt
is fit and the test statistic τμ constructed as
τμ = β^1 σ 11 .
3. To test for a unit root with drift and deterministic time trend the regression model
∇yt = β 1 y t-1 + ∑ i=1 p-1 δi ∇ y t-i +α +β 2 t +εt
is fit and the test statistic ττ constructed as
ττ = β^1 σ 11 .
All three test statistics: τ, τμ and ττ can be calculated using G13AWF.
The probability distributions of these statistics are nonstandard and are a function of the length of the series of interest, n. The probability associated with a given test statistic, for a given n, can therefore only be calculated by simulation as described in Dickey and Fuller (1979). However, such simulations require a significant number of iterations and are therefore prohibitively expensive in terms of the time taken. As such G01EWF also allows the probability to be interpolated from a look-up table. Two such tables are provided, one from Dickey (1976) and one constructed as described in Section 9. The three different methods of obtaining an estimate of the probability can be chosen via the METHOD argument. Unless there is a specific reason for choosing otherwise, METHOD=1 should be used.

4 References

Dickey A D (1976) Estimation and hypothesis testing in nonstationary time series PhD Thesis Iowa State University, Ames, Iowa
Dickey A D and Fuller W A (1979) Distribution of the estimators for autoregressive time series with a unit root J. Am. Stat. Assoc. 74 366 427–431

5 Arguments

1:   METHOD – INTEGERInput
On entry: the method used to calculate the probability.
METHOD=1
The probability is interpolated from a look-up table, whose values were obtained via simulation.
METHOD=2
The probability is interpolated from a look-up table, whose values were obtained from Dickey (1976).
METHOD=3
The probability is obtained via simulation.
The probability calculated from the look-up table should give sufficient accuracy for most applications.
Suggested value: METHOD=1.
Constraint: METHOD=1, 2 or 3.
2:   TYPE – INTEGERInput
On entry: the type of test statistic, supplied in TS.
Constraint: TYPE=1, 2 or 3.
3:   N – INTEGERInput
On entry: n, the length of the time series used to calculate the test statistic.
Constraints:
  • if METHOD≠3, N>0;
  • if METHOD=3 and TYPE=1, N>2;
  • if METHOD=3 and TYPE=2, N>3;
  • if METHOD=3 and TYPE=3, N>4.
4:   TS – REAL (KIND=nag_wp)Input
On entry: the Dickey–Fuller test statistic for which the probability is required. If
TYPE=1
TS must contain τ.
TYPE=2
TS must contain τμ.
TYPE=3
TS must contain ττ.
If the test statistic was calculated using G13AWF the value of TYPE and N must not change between calls to G01EWF and G13AWF.
5:   NSAMP – INTEGERInput
On entry: if METHOD=3, the number of samples used in the simulation; otherwise NSAMP is not referenced and need not be set.
Constraint: if METHOD=3, NSAMP>0.
6:   STATE* – INTEGER arrayCommunication Array
Note: the actual argument supplied must be the array STATE supplied to the initialization routines G05KFF or G05KGF.
On entry: if METHOD=3, STATE must contain information on the selected base generator and its current state; otherwise STATE is not referenced and need not be set.
On exit: if METHOD=3, STATE contains updated information on the state of the generator otherwise a zero length vector is returned.
7:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=11
On entry, METHOD=value.
Constraint: METHOD=1, 2 or 3.
IFAIL=21
On entry, TYPE=value.
Constraint: TYPE=1, 2 or 3.
IFAIL=31
On entry, N=value.
Constraint: if METHOD≠3, N>0.
On entry, N=value.
Constraint: if METHOD=3 and TYPE=1, N>2.
On entry, N=value.
Constraint: if METHOD=3 and TYPE=2, N>3.
On entry, N=value.
Constraint: if METHOD=3 and TYPE=3, N>4.
IFAIL=51
On entry, NSAMP=value.
Constraint: if METHOD=3, NSAMP>0.
IFAIL=61
On entry, METHOD=3 and the STATE vector has been corrupted or not initialized.
IFAIL=201
The supplied input values were outside the range of at least one look-up table, therefore extrapolation was used.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

When METHOD=1, the probability returned by this routine is unlikely to be accurate to more than 4 or 5 decimal places, for METHOD=2 this accuracy is likely to drop to 2 or 3 decimal places (see Section 9 for details on how these probabilities are constructed). In both cases the accuracy of the probability is likely to be lower when extrapolation is used, particularly for small values of N (less than around 15). When METHOD=3 the accuracy of the returned probability is controlled by the number of simulations performed (i.e., the value of NSAMP used).

8 Parallelism and Performance

G01EWF is not threaded in any implementation.

9 Further Comments

When METHOD=1 or 2 the probability returned is constructed by interpolating from a series of look-up tables. In the case of METHOD=2 the look-up tables are taken directly from Dickey (1976) and the interpolation is carried out using E01SAF and E01SBF . For METHOD=1 the look-up tables were constructed as follows:
(i) | A sample size, n was chosen.
(ii) | 228 simulations were run.
(iii) | At each simulation, a time series was constructed as described in chapter five of Dickey (1976). The relevant test statistic was then calculated for each of these time series.
(iv) | A series of quantiles were calculated from the sample of 228 test statistics. The quantiles were calculated at intervals of 0.0005 between 0.0005 and 0.9995.
(v) | A spline was fit to the quantiles using E02BEF.
This process was repeated for n=25,50,75,100,150,200,250,300,350,400,450,500,600,700,800,900,1000,1500,2000,2500,5000,10000, resulting in 22 splines.
Given the 22 splines, and a user-supplied sample size, n and test statistic, τ, an estimated p-value is calculated as follows:
(i) | Evaluate each of the 22 splines, at τ, using E02BEF. If, for a particular spline, the supplied value of τ lies outside of the range of the simulated data, then a third-order Taylor expansion is used to extrapolate, with the derivatives being calculated using E02BCF.
(ii) | Fit a spline through these 22 points using E01BEF.
(iii) | Estimate the p-value using E01BFF.

10 Example

See Section 10 in G13AWF.
G01 Chapter Contents
G01 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


G01EYF : NAG Library, Mark 26

G01 Chapter Contents
G01 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

G01EYF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

G01EYF returns the upper tail probability associated with the one sample Kolmogorov–Smirnov distribution, via the routine name.

2 Specification

FUNCTION G01EYF ( N, D, IFAIL)
REAL (KIND=nag_wp) G01EYF
INTEGER | N, IFAIL
REAL (KIND=nag_wp) | D

3 Description

Let Sn x be the sample cumulative distribution function and F 0 x the hypothesised theoretical distribution function.
G01EYF returns the upper tail probability, p, associated with the one-sided Kolmogorov–Smirnov test statistic Dn+ or Dn-, where these one-sided statistics are defined as follows;
Dn+ = supx Sn x-F 0 x, Dn- = supx F 0 x-Sn x.
If n≤100 an exact method is used; for the details see Conover (1980). Otherwise a large sample approximation derived by Smirnov is used; see Feller (1948), Kendall and Stuart (1973) or Smirnov (1948).

4 References

Conover W J (1980) Practical Nonparametric Statistics Wiley
Feller W (1948) On the Kolmogorov–Smirnov limit theorems for empirical distributions Ann. Math. Statist. 19 179–181
Kendall M G and Stuart A (1973) The Advanced Theory of Statistics (Volume 2) (3rd Edition) Griffin
Siegel S (1956) Non-parametric Statistics for the Behavioral Sciences McGraw–Hill
Smirnov N (1948) Table for estimating the goodness of fit of empirical distributions Ann. Math. Statist. 19 279–281

5 Arguments

1:   N – INTEGERInput
On entry: n, the number of observations in the sample.
Constraint: N≥1.
2:   D – REAL (KIND=nag_wp)Input
On entry: contains the test statistic, Dn+ or Dn-.
Constraint: 0.0≤D≤1.0.
3:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, N<1.
IFAIL=2
On entry, | D<0.0,
or | D>1.0.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

The large sample distribution used as an approximation to the exact distribution should have a relative error of less than 2.5% for most cases.

8 Parallelism and Performance

G01EYF is not threaded in any implementation.

9 Further Comments

The upper tail probability for the two-sided statistic, Dn=max Dn+,Dn-, can be approximated by twice the probability returned via G01EYF, that is 2 p. (Note that if the probability from G01EYF is greater than 0.5 then the two-sided probability should be truncated to 1.0). This approximation to the tail probability for Dn is good for small probabilities, (e.g., p≤0.10) but becomes very poor for larger probabilities.
The time taken by the routine increases with n, until n>100. At this point the approximation is used and the time decreases significantly. The time then increases again modestly with n.

10 Example

The following example reads in 10 different sample sizes and values for the test statistic Dn. The upper tail probability is computed and printed for each case.

10.1 Program Text

Program Text (g01eyfe.f90)

10.2 Program Data

Program Data (g01eyfe.d)

10.3 Program Results

Program Results (g01eyfe.r)

G01 Chapter Contents
G01 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


G01EZF : NAG Library, Mark 26

G01 Chapter Contents
G01 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

G01EZF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

G01EZF returns the probability associated with the upper tail of the Kolmogorov–Smirnov two sample distribution, via the routine name.

2 Specification

FUNCTION G01EZF ( N1, N2, D, IFAIL)
REAL (KIND=nag_wp) G01EZF
INTEGER | N1, N2, IFAIL
REAL (KIND=nag_wp) | D

3 Description

Let F n 1 x and G n 2 x denote the empirical cumulative distribution functions for the two samples, where n 1 and n 2 are the sizes of the first and second samples respectively.
The function G01EZF computes the upper tail probability for the Kolmogorov–Smirnov two sample two-sided test statistic D n 1,n 2, where
D n 1,n 2=supx F n 1 x-G n 2 x.
The probability is computed exactly if n 1,n 2≤10000 and max n 1,n 2≤2500 using a method given by Kim and Jenrich (1973). For the case where min n 1,n 2 ≤ 10 % of the max n 1,n 2 and min n 1,n 2 ≤ 80 the Smirnov approximation is used. For all other cases the Kolmogorov approximation is used. These two approximations are discussed in Kim and Jenrich (1973).

4 References

Conover W J (1980) Practical Nonparametric Statistics Wiley
Feller W (1948) On the Kolmogorov–Smirnov limit theorems for empirical distributions Ann. Math. Statist. 19 179–181
Kendall M G and Stuart A (1973) The Advanced Theory of Statistics (Volume 2) (3rd Edition) Griffin
Kim P J and Jenrich R I (1973) Tables of exact sampling distribution of the two sample Kolmogorov–Smirnov criterion D mn m<n Selected Tables in Mathematical Statistics 1 80–129 American Mathematical Society
Siegel S (1956) Non-parametric Statistics for the Behavioral Sciences McGraw–Hill
Smirnov N (1948) Table for estimating the goodness of fit of empirical distributions Ann. Math. Statist. 19 279–281

5 Arguments

1:   N1 – INTEGERInput
On entry: the number of observations in the first sample, n 1.
Constraint: N1≥1.
2:   N2 – INTEGERInput
On entry: the number of observations in the second sample, n 2.
Constraint: N2≥1.
3:   D – REAL (KIND=nag_wp)Input
On entry: the test statistic D n 1,n 2, for the two sample Kolmogorov–Smirnov goodness-of-fit test, that is the maximum difference between the empirical cumulative distribution functions (CDFs) of the two samples.
Constraint: 0.0≤D≤1.0.
4:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, | N1<1,
or | N2<1.
IFAIL=2
On entry, | D<0.0,
or | D>1.0.
IFAIL=3
The approximation solution did not converge in 500 iterations. A tail probability of 1.0 is returned by G01EZF.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

The large sample distributions used as approximations to the exact distribution should have a relative error of less than 5% for most cases.

8 Parallelism and Performance

G01EZF is not threaded in any implementation.

9 Further Comments

The upper tail probability for the one-sided statistics, D n 1,n 2+ or D n 1,n 2-, can be approximated by halving the two-sided upper tail probability returned by G01EZF, that is p/2. This approximation to the upper tail probability for either D n 1,n 2+ or D n 1,n 2- is good for small probabilities, (e.g., p≤0.10) but becomes poor for larger probabilities.
The time taken by the routine increases with n 1 and n 2, until n 1n 2>10000 or max n 1,n 2≥2500. At this point one of the approximations is used and the time decreases significantly. The time then increases again modestly with n 1 and n 2.

10 Example

The following example reads in 10 different sample sizes and values for the test statistic D n 1,n 2. The upper tail probability is computed and printed for each case.

10.1 Program Text

Program Text (g01ezfe.f90)

10.2 Program Data

Program Data (g01ezfe.d)

10.3 Program Results

Program Results (g01ezfe.r)

G01 Chapter Contents
G01 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


G01FAF : NAG Library, Mark 26

G01 Chapter Contents
G01 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

G01FAF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

G01FAF returns the deviate associated with the given probability of the standard Normal distribution, via the routine name.

2 Specification

FUNCTION G01FAF ( TAIL, P, IFAIL)
REAL (KIND=nag_wp) G01FAF
INTEGER | IFAIL
REAL (KIND=nag_wp) | P
CHARACTER(1) | TAIL

3 Description

The deviate, xp associated with the lower tail probability, p, for the standard Normal distribution is defined as the solution to
P X≤xp=p=∫-∞xp Z X dX,
where
Z X=1 2 π e-X 2/2,   -∞<X< ∞.
The method used is an extension of that of Wichura (1988). p is first replaced by q=p-0.5.
(a) If q≤0.3, xp is computed by a rational Chebyshev approximation
xp=s A s 2 B s 2 ,
where s=2 π q and A, B are polynomials of degree 7.
(b) If 0.3<q≤0.42, xp is computed by a rational Chebyshev approximation
xp=sign⁡q C t D t ,
where t=q-0.3 and C, D are polynomials of degree 5.
(c) If q>0.42, xp is computed as
xp=sign⁡q E u F u +u ,
where u = -2 × log min p,1-p and E, F are polynomials of degree 6.
For the upper tail probability -xp is returned, while for the two tail probabilities the value x p* is returned, where p* is the required tail probability computed from the input value of p.

4 References

Abramowitz M and Stegun I A (1972) Handbook of Mathematical Functions (3rd Edition) Dover Publications
Hastings N A J and Peacock J B (1975) Statistical Distributions Butterworth
Wichura (1988) Algorithm AS 241: the percentage points of the Normal distribution Appl. Statist. 37 477–484

5 Arguments

1:   TAIL – CHARACTER(1)Input
On entry: indicates which tail the supplied probability represents.
TAIL='L'
The lower probability, i.e., P X≤xp.
TAIL='U'
The upper probability, i.e., P X≥xp.
TAIL='S'
The two tail (significance level) probability, i.e., P X≥xp+P X≤-xp.
TAIL='C'
The two tail (confidence interval) probability, i.e., P X≤xp-P X≤-xp.
Constraint: TAIL='L', 'U', 'S' or 'C'.
2:   P – REAL (KIND=nag_wp)Input
On entry: p, the probability from the standard Normal distribution as defined by TAIL.
Constraint: 0.0<P<1.0.
3:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
If on exit IFAIL≠0, then G01FAF returns 0.0.
IFAIL=1
On entry, TAIL≠'L', 'U', 'S' or 'C'.
IFAIL=2
On entry, | P≤0.0,
or | P≥1.0.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

The accuracy is mainly limited by the machine precision.

8 Parallelism and Performance

G01FAF is not threaded in any implementation.

9 Further Comments

None.

10 Example

Four values of TAIL and P are input and the deviates calculated and printed.

10.1 Program Text

Program Text (g01fafe.f90)

10.2 Program Data

Program Data (g01fafe.d)

10.3 Program Results

Program Results (g01fafe.r)

G01 Chapter Contents
G01 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


G01FBF : NAG Library, Mark 26

G01 Chapter Contents
G01 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

G01FBF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

G01FBF returns the deviate associated with the given tail probability of Student's t-distribution with real degrees of freedom, via the routine name.

2 Specification

FUNCTION G01FBF ( TAIL, P, DF, IFAIL)
REAL (KIND=nag_wp) G01FBF
INTEGER | IFAIL
REAL (KIND=nag_wp) | P, DF
CHARACTER(1) | TAIL

3 Description

The deviate, tp associated with the lower tail probability, p, of the Student's t-distribution with ν degrees of freedom is defined as the solution to
P T<tp:ν=p=Γ ν+1/2 νπ Γ ν/2 ∫-∞tp 1+T 2 ν -ν+1/2 dT,  ν≥1; ​-∞<tp<∞.
For ν=1​ or ​2 the integral equation is easily solved for tp.
For other values of ν<3 a transformation to the beta distribution is used and the result obtained from G01FEF.
For ν≥3 an inverse asymptotic expansion of Cornish–Fisher type is used. The algorithm is described by Hill (1970).

4 References

Hastings N A J and Peacock J B (1975) Statistical Distributions Butterworth
Hill G W (1970) Student's t-distribution Comm. ACM 13(10) 617–619

5 Arguments

1:   TAIL – CHARACTER(1)Input
On entry: indicates which tail the supplied probability represents.
TAIL='U'
The upper tail probability, i.e., P T≥tp:ν.
TAIL='L'
The lower tail probability, i.e., P T≤tp:ν.
TAIL='S'
The two tail (significance level) probability, i.e., P T≥tp:ν+P T≤-tp:ν.
TAIL='C'
The two tail (confidence interval) probability, i.e., P T≤tp:ν-P T≤-tp:ν.
Constraint: TAIL='U', 'L', 'S' or 'C'.
2:   P – REAL (KIND=nag_wp)Input
On entry: p, the probability from the required Student's t-distribution as defined by TAIL.
Constraint: 0.0<P<1.0.
3:   DF – REAL (KIND=nag_wp)Input
On entry: ν, the degrees of freedom of the Student's t-distribution.
Constraint: DF≥1.0.
4:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, because for this routine the values of the output arguments may be useful even if IFAIL≠0 on exit, the recommended value is -1. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Note: G01FBF may return useful information for one or more of the following detected errors or warnings.
Errors or warnings detected by the routine:
If IFAIL=1, 2 or 3 on exit, then G01FBF returns zero.
IFAIL=1
On entry, TAIL≠'U', 'S', 'C' or 'L'.
IFAIL=2
On entry, | P≤0.0,
or | P≥1.0.
IFAIL=3
On entry, DF<1.0.
IFAIL=5
Convergence in the calculation of the inverse beta value was not achieved. However, the result should be a reasonable approximation to the correct value.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

The results should be accurate to five significant digits, for most argument values. The error behaviour for various argument values is discussed in Hill (1970).

8 Parallelism and Performance

G01FBF is not threaded in any implementation.

9 Further Comments

The value tp may be calculated by using the transformation described in Section 3 and using G01FEF. This routine allows you to set the required accuracy.

10 Example

This example reads the probability, the tail that probability represents and the degrees of freedom for a number of Student's t-distributions and computes the corresponding deviates.

10.1 Program Text

Program Text (g01fbfe.f90)

10.2 Program Data

Program Data (g01fbfe.d)

10.3 Program Results

Program Results (g01fbfe.r)

G01 Chapter Contents
G01 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


G01FCF : NAG Library, Mark 26

G01 Chapter Contents
G01 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

G01FCF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

G01FCF returns the deviate associated with the given lower tail probability of the χ 2-distribution with real degrees of freedom, via the routine name.

2 Specification

FUNCTION G01FCF ( P, DF, IFAIL)
REAL (KIND=nag_wp) G01FCF
INTEGER | IFAIL
REAL (KIND=nag_wp) | P, DF

3 Description

The deviate, xp, associated with the lower tail probability p of the χ 2-distribution with ν degrees of freedom is defined as the solution to
P X≤xp:ν=p=1 2 ν/2 Γ ν/2 ∫0 xp e-X/2X v/2-1 dX,  0≤xp<∞;ν>0.
The required xp is found by using the relationship between a χ 2-distribution and a gamma distribution, i.e., a χ 2-distribution with ν degrees of freedom is equal to a gamma distribution with scale parameter 2 and shape parameter ν/2.
For very large values of ν, greater than 105, Wilson and Hilferty's normal approximation to the χ 2 is used; see Kendall and Stuart (1969).

4 References

Best D J and Roberts D E (1975) Algorithm AS 91. The percentage points of the χ 2 distribution Appl. Statist. 24 385–388
Hastings N A J and Peacock J B (1975) Statistical Distributions Butterworth
Kendall M G and Stuart A (1969) The Advanced Theory of Statistics (Volume 1) (3rd Edition) Griffin

5 Arguments

1:   P – REAL (KIND=nag_wp)Input
On entry: p, the lower tail probability from the required χ 2-distribution.
Constraint: 0.0≤P<1.0.
2:   DF – REAL (KIND=nag_wp)Input
On entry: ν, the degrees of freedom of the χ 2-distribution.
Constraint: DF>0.0.
3:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, because for this routine the values of the output arguments may be useful even if IFAIL≠0 on exit, the recommended value is -1. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Note: G01FCF may return useful information for one or more of the following detected errors or warnings.
Errors or warnings detected by the routine:
If IFAIL=1, 2, 3 or 5 on exit, then G01FCF returns 0.0.
IFAIL=1
On entry, | P<0.0,
or | P≥1.0.
IFAIL=2
On entry, DF≤0.0.
IFAIL=3
P is too close to 0 or 1 for the result to be calculated.
IFAIL=4
The solution has failed to converge. The result should be a reasonable approximation.
IFAIL=5
The series used to calculate the gamma function has failed to converge. This is an unlikely error exit.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

The results should be accurate to five significant digits for most argument values. Some accuracy is lost for p close to 0.0.

8 Parallelism and Performance

G01FCF is not threaded in any implementation.

9 Further Comments

For higher accuracy the relationship described in Section 3 may be used and a direct call to G01FFF made.

10 Example

This example reads lower tail probabilities for several χ 2-distributions, and calculates and prints the corresponding deviates until the end of data is reached.

10.1 Program Text

Program Text (g01fcfe.f90)

10.2 Program Data

Program Data (g01fcfe.d)

10.3 Program Results

Program Results (g01fcfe.r)

G01 Chapter Contents
G01 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


G01FDF : NAG Library, Mark 26

G01 Chapter Contents
G01 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

G01FDF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

G01FDF returns the deviate associated with the given lower tail probability of the F or variance-ratio distribution with real degrees of freedom, via the routine name.

2 Specification

FUNCTION G01FDF ( P, DF1, DF2, IFAIL)
REAL (KIND=nag_wp) G01FDF
INTEGER | IFAIL
REAL (KIND=nag_wp) | P, DF1, DF2

3 Description

The deviate, fp, associated with the lower tail probability, p, of the F-distribution with degrees of freedom ν 1 and ν 2 is defined as the solution to
P F ≤ fp : ν 1 ,ν 2 = p = ν 1 12 ν 1 ν 2 12 ν 2 Γ ν 1 + ν 2 2 Γ ν 1 2 Γ ν 2 2 ∫ 0 fp F 12 ν 1-2 ν 2 + ν 1 F -12 ν 1 + ν 2 dF ,
where ν 1,ν 2>0; 0≤fp<∞.
The value of fp is computed by means of a transformation to a beta distribution, Pβ B≤β:a,b:
P F≤f:ν 1,ν 2=Pβ B≤ν 1 f ν 1 f+ν 2 :ν 1/2,ν 2/2
and using a call to G01FEF.
For very large values of both ν 1 and ν 2, greater than 105, a normal approximation is used. If only one of ν 1 or ν 2 is greater than 105 then a χ 2 approximation is used; see Abramowitz and Stegun (1972).

4 References

Abramowitz M and Stegun I A (1972) Handbook of Mathematical Functions (3rd Edition) Dover Publications
Hastings N A J and Peacock J B (1975) Statistical Distributions Butterworth

5 Arguments

1:   P – REAL (KIND=nag_wp)Input
On entry: p, the lower tail probability from the required F-distribution.
Constraint: 0.0≤P<1.0.
2:   DF1 – REAL (KIND=nag_wp)Input
On entry: the degrees of freedom of the numerator variance, ν 1.
Constraint: DF1>0.0.
3:   DF2 – REAL (KIND=nag_wp)Input
On entry: the degrees of freedom of the denominator variance, ν 2.
Constraint: DF2>0.0.
4:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, because for this routine the values of the output arguments may be useful even if IFAIL≠0 on exit, the recommended value is -1. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Note: G01FDF may return useful information for one or more of the following detected errors or warnings.
Errors or warnings detected by the routine:
If on exit IFAIL=1, 2 or 4, then G01FDF returns 0.0.
IFAIL=1
On entry, | P<0.0,
or | P≥1.0.
IFAIL=2
On entry, | DF1≤0.0,
or | DF2≤0.0.
IFAIL=3
The solution has not converged. The result should still be a reasonable approximation to the solution. Alternatively, G01FEF can be used with a suitable setting of the argument TOL.
IFAIL=4
The value of P is too close to 0 or 1 for the value of fp to be computed. This will only occur when the large sample approximations are used.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

The result should be accurate to five significant digits.

8 Parallelism and Performance

G01FDF is not threaded in any implementation.

9 Further Comments

For higher accuracy G01FEF can be used along with the transformations given in Section 3.

10 Example

This example reads the lower tail probabilities for several F-distributions, and calculates and prints the corresponding deviates until the end of data is reached.

10.1 Program Text

Program Text (g01fdfe.f90)

10.2 Program Data

Program Data (g01fdfe.d)

10.3 Program Results

Program Results (g01fdfe.r)

G01 Chapter Contents
G01 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


G01FEF : NAG Library, Mark 26

G01 Chapter Contents
G01 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

G01FEF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

G01FEF returns the deviate associated with the given lower tail probability of the beta distribution, via the routine name.

2 Specification

FUNCTION G01FEF ( P, A, B, TOL, IFAIL)
REAL (KIND=nag_wp) G01FEF
INTEGER | IFAIL
REAL (KIND=nag_wp) | P, A, B, TOL

3 Description

The deviate, βp, associated with the lower tail probability, p, of the beta distribution with parameters a and b is defined as the solution to
P B≤βp:a,b=p=Γ a+b Γ a Γ b ∫0 βp B a-11-B b-1 dB,  0≤βp≤1;a,b>0.
The algorithm is a modified version of the Newton–Raphson method, following closely that of Cran et al. (1977).
An initial approximation, β 0, to βp is found (see Cran et al. (1977)), and the Newton–Raphson iteration
βi=β i-1-f β i-1 f′β i-1 ,
where f β=P B≤β:a,b-p is used, with modifications to ensure that β remains in the range 0,1.

4 References

Cran G W, Martin K J and Thomas G E (1977) Algorithm AS 109. Inverse of the incomplete beta function ratio Appl. Statist. 26 111–114
Hastings N A J and Peacock J B (1975) Statistical Distributions Butterworth

5 Arguments

1:   P – REAL (KIND=nag_wp)Input
On entry: p, the lower tail probability from the required beta distribution.
Constraint: 0.0≤P≤1.0.
2:   A – REAL (KIND=nag_wp)Input
On entry: a, the first parameter of the required beta distribution.
Constraint: 0.0<A≤106.
3:   B – REAL (KIND=nag_wp)Input
On entry: b, the second parameter of the required beta distribution.
Constraint: 0.0<B≤106.
4:   TOL – REAL (KIND=nag_wp)Input
On entry: the relative accuracy required by you in the result. If G01FEF is entered with TOL greater than or equal to 1.0 or less than 10×machine precision (see X02AJF), then the value of 10×machine precision is used instead.
5:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, because for this routine the values of the output arguments may be useful even if IFAIL≠0 on exit, the recommended value is -1. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Note: G01FEF may return useful information for one or more of the following detected errors or warnings.
Errors or warnings detected by the routine:
If on exit IFAIL=1 or 2, then G01FEF returns 0.0.
IFAIL=1
On entry, | P<0.0,
or | P>1.0.
IFAIL=2
On entry, | A≤0.0,
or | A>106,
or | B≤0.0,
or | B>106.
IFAIL=3
There is doubt concerning the accuracy of the computed result. 100 iterations of the Newton–Raphson method have been performed without satisfying the accuracy criterion (see Section 7). The result should be a reasonable approximation of the solution.
IFAIL=4
Requested accuracy not achieved when calculating beta probability. The result should be a reasonable approximation to the correct solution. You should try setting TOL larger.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

The required precision, given by TOL, should be achieved in most circumstances.

8 Parallelism and Performance

G01FEF is not threaded in any implementation.

9 Further Comments

The typical timing will be several times that of G01EEF and will be very dependent on the input argument values. See G01EEF for further comments on timings.

10 Example

This example reads lower tail probabilities for several beta distributions and calculates and prints the corresponding deviates until the end of data is reached.

10.1 Program Text

Program Text (g01fefe.f90)

10.2 Program Data

Program Data (g01fefe.d)

10.3 Program Results

Program Results (g01fefe.r)

G01 Chapter Contents
G01 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


G01FFF : NAG Library, Mark 26

G01 Chapter Contents
G01 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

G01FFF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

G01FFF returns the deviate associated with the given lower tail probability of the gamma distribution, via the routine name.

2 Specification

FUNCTION G01FFF ( P, A, B, TOL, IFAIL)
REAL (KIND=nag_wp) G01FFF
INTEGER | IFAIL
REAL (KIND=nag_wp) | P, A, B, TOL

3 Description

The deviate, gp, associated with the lower tail probability, p, of the gamma distribution with shape parameter α and scale parameter β, is defined as the solution to
P G≤gp:α,β=p=1 βα Γ α ∫0 gp e-G/βG α-1 dG,  0≤gp<∞;α,β>0.
The method used is described by Best and Roberts (1975) making use of the relationship between the gamma distribution and the χ 2-distribution.
Let y=2 gp β . The required y is found from the Taylor series expansion
y=y 0+∑r Cr y 0 r! E ϕ y 0 r,
where y 0 is a starting approximation
  • C 1 u=1,
  • C r+1 u=rΨ+ d du Cr u,
  • Ψ=12- α-1 u ,
  • E=p-∫0 y 0 ϕ u du,
  • ϕ u= 1 2 α Γ α e-u/2u α-1.
For most values of p and α the starting value
y 01=2 α z⁢1 9 α +1-1 9 α 3
is used, where z is the deviate associated with a lower tail probability of p for the standard Normal distribution.
For p close to zero,
y 02= pα 2 α Γ α 1/α
is used.
For large p values, when y 01>4.4 α+6.0,
y 03=-2 ln 1-p-α-1 ln 12 y 01+ln Γ α
is found to be a better starting value than y 01.
For small α α≤0.16, p is expressed in terms of an approximation to the exponential integral and y 04 is found by Newton–Raphson iterations.
Seven terms of the Taylor series are used to refine the starting approximation, repeating the process if necessary until the required accuracy is obtained.

4 References

Best D J and Roberts D E (1975) Algorithm AS 91. The percentage points of the χ 2 distribution Appl. Statist. 24 385–388

5 Arguments

1:   P – REAL (KIND=nag_wp)Input
On entry: p, the lower tail probability from the required gamma distribution.
Constraint: 0.0≤P<1.0.
2:   A – REAL (KIND=nag_wp)Input
On entry: α, the shape parameter of the gamma distribution.
Constraint: 0.0<A≤106.
3:   B – REAL (KIND=nag_wp)Input
On entry: β, the scale parameter of the gamma distribution.
Constraint: B>0.0.
4:   TOL – REAL (KIND=nag_wp)Input
On entry: the relative accuracy required by you in the results. The smallest recommended value is 50×δ, where δ=max 10-18,machine precision. If G01FFF is entered with TOL less than 50×δ or greater or equal to 1.0, then 50×δ is used instead.
5:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, because for this routine the values of the output arguments may be useful even if IFAIL≠0 on exit, the recommended value is -1. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Note: G01FFF may return useful information for one or more of the following detected errors or warnings.
Errors or warnings detected by the routine:
If on exit IFAIL=1, 2, 3 or 5, then G01FFF returns 0.0.
IFAIL=1
On entry, | P<0.0,
or | P≥1.0,
IFAIL=2
On entry, | A≤0.0,
or | A>106,
or | B≤0.0
IFAIL=3
P is too close to 0.0 or 1.0 to enable the result to be calculated.
IFAIL=4
The solution has failed to converge in 100 iterations. A larger value of TOL should be tried. The result may be a reasonable approximation.
IFAIL=5
The series to calculate the gamma function has failed to converge. This is an unlikely error exit.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

In most cases the relative accuracy of the results should be as specified by TOL. However, for very small values of α or very small values of p there may be some loss of accuracy.

8 Parallelism and Performance

G01FFF is not threaded in any implementation.

9 Further Comments

None.

10 Example

This example reads lower tail probabilities for several gamma distributions, and calculates and prints the corresponding deviates until the end of data is reached.

10.1 Program Text

Program Text (g01fffe.f90)

10.2 Program Data

Program Data (g01fffe.d)

10.3 Program Results

Program Results (g01fffe.r)

G01 Chapter Contents
G01 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


G01FMF : NAG Library, Mark 26

G01 Chapter Contents
G01 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

G01FMF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

G01FMF returns the deviate associated with the lower tail probability of the distribution of the Studentized range statistic, via the routine name.

2 Specification

FUNCTION G01FMF ( P, V, IR, IFAIL)
REAL (KIND=nag_wp) G01FMF
INTEGER | IR, IFAIL
REAL (KIND=nag_wp) | P, V

3 Description

The externally Studentized range, q, for a sample, x 1,x 2,…,xr, is defined as
q = max xi - min xi σ^e ,
where σ^e is an independent estimate of the standard error of the xi. The most common use of this statistic is in the testing of means from a balanced design. In this case for a set of group means, T-1,T-2,…,T-r, the Studentized range statistic is defined to be the difference between the largest and smallest means, T-largest and T-smallest, divided by the square root of the mean-square experimental error, M S error, over the number of observations in each group, n, i.e.,
q=T-largest-T-smallest M S error/n .
The Studentized range statistic can be used as part of a multiple comparisons procedure such as the Newman–Keuls procedure or Duncan's multiple range test (see Montgomery (1984) and Winer (1970)).
For a Studentized range statistic the probability integral, P q;v,r, for v degrees of freedom and r groups, can be written as:
P q;v,r=C∫0∞x v-1e-v x 2/2 r∫-∞∞ϕ y Φ y-Φ y-qx r-1 dy dx,
where
C=v v/2 Γ v/2 2 v/2- 1 ,   ϕ y=1 2 π e-y 2/2   and   Φ y=∫-∞y ϕ t dt.
For a given probability p 0, the deviate q 0 is found as the solution to the equation
P q 0;v,r=p 0, (1)
using C05AZF . Initial estimates are found using the approximation given in Lund and Lund (1983) and a simple search procedure.

4 References

Lund R E and Lund J R (1983) Algorithm AS 190: probabilities and upper quartiles for the studentized range Appl. Statist. 32(2) 204–210
Montgomery D C (1984) Design and Analysis of Experiments Wiley
Winer B J (1970) Statistical Principles in Experimental Design McGraw–Hill

5 Arguments

1:   P – REAL (KIND=nag_wp)Input
On entry: the lower tail probability for the Studentized range statistic, p 0.
Constraint: 0.0<P<1.0.
2:   V – REAL (KIND=nag_wp)Input
On entry: v, the number of degrees of freedom.
Constraint: V≥1.0.
3:   IR – INTEGERInput
On entry: r, the number of groups.
Constraint: IR≥2.
4:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, because for this routine the values of the output arguments may be useful even if IFAIL≠0 on exit, the recommended value is -1. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Note: G01FMF may return useful information for one or more of the following detected errors or warnings.
Errors or warnings detected by the routine:
If on exit IFAIL=1, then G01FMF returns 0.0.
IFAIL=1
On entry, | P≤0.0,
or | P≥1.0,
or | V<1.0,
or | IR<2.
IFAIL=2
The routine was unable to find an upper bound for the value of q 0. This will be caused by p 0 being too close to 1.0.
IFAIL=3
There is some doubt as to whether full accuracy has been achieved. The returned value should be a reasonable estimate of the true value.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

The returned solution, q*, to equation (1) is determined so that at least one of the following criteria apply.
(a) | P q*;v,r-p 0≤0.000005
(b) | q 0-q*≤0.000005×max 1.0,q*.

8 Parallelism and Performance

G01FMF is not threaded in any implementation.

9 Further Comments

To obtain the factors for Duncan's multiple-range test, equation (1) has to be solved for p 1, where p 1=p 0 r-1, so on input P should be set to p 0 r-1.

10 Example

Three values of p, ν and r are read in and the Studentized range deviates or quantiles are computed and printed.

10.1 Program Text

Program Text (g01fmfe.f90)

10.2 Program Data

Program Data (g01fmfe.d)

10.3 Program Results

Program Results (g01fmfe.r)

G01 Chapter Contents
G01 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


G01FTF : NAG Library, Mark 26

G01 Chapter Contents
G01 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

G01FTF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

G01FTF returns the value of the inverse Φ-1 x of the Landau distribution function, via the routine name.

2 Specification

FUNCTION G01FTF ( X, IFAIL)
REAL (KIND=nag_wp) G01FTF
INTEGER | IFAIL
REAL (KIND=nag_wp) | X

3 Description

G01FTF evaluates an approximation to the inverse Φ-1 x of the Landau distribution function given by
Ψ x=Φ-1 x
(where Φ λ is described in G01ETF and G01MTF), using either linear or quadratic interpolation or rational approximations which mimic the asymptotic behaviour. Further details can be found in Kölbig and Schorr (1984).
It can also be used to generate Landau distributed random numbers in the range 0<x<1.

4 References

Kölbig K S and Schorr B (1984) A program package for the Landau distribution Comp. Phys. Comm. 31 97–111

5 Arguments

1:   X – REAL (KIND=nag_wp)Input
On entry: the argument x of the function.
Constraint: 0.0<X<1.0.
2:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, | X≤0.0,
or | X≥1.0.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

At least 5-6 significant digits are correct. Such accuracy is normally considered to be adequate for applications in large scale Monte–Carlo simulations.

8 Parallelism and Performance

G01FTF is not threaded in any implementation.

9 Further Comments

None.

10 Example

This example evaluates Φ-1 x at x=0.5, and prints the results.

10.1 Program Text

Program Text (g01ftfe.f90)

10.2 Program Data

Program Data (g01ftfe.d)

10.3 Program Results

Program Results (g01ftfe.r)

G01 Chapter Contents
G01 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


G01GBF : NAG Library, Mark 26

G01 Chapter Contents
G01 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

G01GBF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

G01GBF returns the lower tail probability for the noncentral Student's t-distribution, via the routine name.

2 Specification

FUNCTION G01GBF ( T, DF, DELTA, TOL, MAXIT, IFAIL)
REAL (KIND=nag_wp) G01GBF
INTEGER | MAXIT, IFAIL
REAL (KIND=nag_wp) | T, DF, DELTA, TOL

3 Description

The lower tail probability of the noncentral Student's t-distribution with ν degrees of freedom and noncentrality parameter δ, P T≤t:ν;δ, is defined by
P T≤t:ν;δ=Cν∫0∞ 1 2 π∫-∞ αu-δ e-x 2/2 dx u ν-1e-u 2/2 du,  ν>0.0
with
Cν=1 Γ 12 ν 2 ν- 2/2 ,   α=t ν.
The probability is computed in one of two ways.
(i) When t=0.0, the relationship to the normal is used:
P T≤t:ν;δ=1 2 π∫δ∞e-u 2/2 du.
(ii) Otherwise the series expansion described in Equation 9 of Amos (1964) is used. This involves the sums of confluent hypergeometric functions, the terms of which are computed using recurrence relationships.

4 References

Amos D E (1964) Representations of the central and non-central t-distributions Biometrika 51 451–458

5 Arguments

1:   T – REAL (KIND=nag_wp)Input
On entry: t, the deviate from the Student's t-distribution with ν degrees of freedom.
2:   DF – REAL (KIND=nag_wp)Input
On entry: ν, the degrees of freedom of the Student's t-distribution.
Constraint: DF≥1.0.
3:   DELTA – REAL (KIND=nag_wp)Input
On entry: δ, the noncentrality argument of the Students t-distribution.
4:   TOL – REAL (KIND=nag_wp)Input
On entry: the absolute accuracy required by you in the results. If G01GBF is entered with TOL greater than or equal to 1.0 or less than 10×machine precision (see X02AJF), then the value of 10×machine precision is used instead.
5:   MAXIT – INTEGERInput
On entry: the maximum number of terms that are used in each of the summations.
Suggested value: 100. See Section 9 for further comments.
Constraint: MAXIT≥1.
6:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
If on exit IFAIL≠0, then G01GBF returns 0.0.
IFAIL=1
On entry, DF<1.0.
IFAIL=2
On entry, MAXIT<1.
IFAIL=3
One of the series has failed to converge. Reconsider the requested tolerance and/or maximum number of iterations.
IFAIL=4
The probability is too small to calculate accurately.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

The series described in Amos (1964) are summed until an estimated upper bound on the contribution of future terms to the probability is less than TOL. There may also be some loss of accuracy due to calculation of gamma functions.

8 Parallelism and Performance

G01GBF is not threaded in any implementation.

9 Further Comments

The rate of convergence of the series depends, in part, on the quantity t 2/t 2+ν. The smaller this quantity the faster the convergence. Thus for large t and small ν the convergence may be slow. If ν is an integer then one of the series to be summed is of finite length.
If two tail probabilities are required then the relationship of the t-distribution to the F-distribution can be used:
F=T 2,λ=δ 2,ν 1=1  and  ν 2=ν,
and a call made to G01GDF.
Note that G01GBF only allows degrees of freedom greater than or equal to 1 although values between 0 and 1 are theoretically possible.

10 Example

This example reads values from, and degrees of freedom for, and noncentrality arguments of the noncentral Student's t-distributions, calculates the lower tail probabilities and prints all these values until the end of data is reached.

10.1 Program Text

Program Text (g01gbfe.f90)

10.2 Program Data

Program Data (g01gbfe.d)

10.3 Program Results

Program Results (g01gbfe.r)

G01 Chapter Contents
G01 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


G01GCF : NAG Library, Mark 26

G01 Chapter Contents
G01 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

G01GCF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

G01GCF returns the probability associated with the lower tail of the noncentral χ 2-distribution via the routine name.

2 Specification

FUNCTION G01GCF ( X, DF, RLAMDA, TOL, MAXIT, IFAIL)
REAL (KIND=nag_wp) G01GCF
INTEGER | MAXIT, IFAIL
REAL (KIND=nag_wp) | X, DF, RLAMDA, TOL

3 Description

The lower tail probability of the noncentral χ 2-distribution with ν degrees of freedom and noncentrality parameter λ, P X≤x:ν;λ, is defined by
P X≤x:ν;λ=∑j=0∞e-λ/2 λ/2 j j! P X≤x:ν+2 j;0, (1)
where P X≤x:ν+2 j;0 is a central χ 2-distribution with ν+2 j degrees of freedom.
The value of j at which the Poisson weight, e-λ/2 λ/2 j j! , is greatest is determined and the summation (1) is made forward and backward from that value of j.
The recursive relationship:
P X≤x:a+2;0=P X≤x:a;0-xa/2 e-x/2 Γ a+1 (2)
is used during the summation in (1).

4 References

Abramowitz M and Stegun I A (1972) Handbook of Mathematical Functions (3rd Edition) Dover Publications

5 Arguments

1:   X – REAL (KIND=nag_wp)Input
On entry: the deviate from the noncentral χ 2-distribution with ν degrees of freedom and noncentrality parameter λ.
Constraint: X≥0.0.
2:   DF – REAL (KIND=nag_wp)Input
On entry: ν, the degrees of freedom of the noncentral χ 2-distribution.
Constraint: DF≥0.0.
3:   RLAMDA – REAL (KIND=nag_wp)Input
On entry: λ, the noncentrality parameter of the noncentral χ 2-distribution.
Constraint: RLAMDA≥0.0 if DF>0.0 or RLAMDA>0.0 if DF=0.0.
4:   TOL – REAL (KIND=nag_wp)Input
On entry: the required accuracy of the solution. If G01GCF is entered with TOL greater than or equal to 1.0 or less than 10×machine precision (see X02AJF), then the value of 10×machine precision is used instead.
5:   MAXIT – INTEGERInput
On entry: the maximum number of iterations to be performed.
Suggested value: 100. See Section 9 for further discussion.
Constraint: MAXIT≥1.
6:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, because for this routine the values of the output arguments may be useful even if IFAIL≠0 on exit, the recommended value is -1. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Note: G01GCF may return useful information for one or more of the following detected errors or warnings.
Errors or warnings detected by the routine:
If on exit IFAIL=1, 2, 4 or 5, then G01GCF returns 0.0.
IFAIL=1
On entry, | DF<0.0,
or | RLAMDA<0.0,
or | DF=0.0 and RLAMDA=0.0,
or | X<0.0,
or | MAXIT<1.
IFAIL=2
The initial value of the Poisson weight used in the summation (1) was too small to be calculated. The value of P X≤x:ν;λ is likely to be zero.
IFAIL=3
The solution has failed to converge in MAXIT iterations.
IFAIL=4
The value of a term required in (2) is too large to be evaluated accurately. The most likely cause of this error is both X and RLAMDA being very large.
IFAIL=5
The calculations for the central χ 2 probability has failed to converge. This is an unlikely error exit. A larger value of TOL should be used.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

The summations described in Section 3 are made until an upper bound on the truncation error relative to the current summation value is less than TOL.

8 Parallelism and Performance

G01GCF is not threaded in any implementation.

9 Further Comments

The number of terms in (1) required for a given accuracy will depend on the following factors:
(i) | The rate at which the Poisson weights tend to zero. This will be slower for larger values of λ.
(ii) | The rate at which the central χ 2 probabilities tend to zero. This will be slower for larger values of ν and x.

10 Example

This example reads values from various noncentral χ 2-distributions, calculates the lower tail probabilities and prints all these values until the end of data is reached.

10.1 Program Text

Program Text (g01gcfe.f90)

10.2 Program Data

Program Data (g01gcfe.d)

10.3 Program Results

Program Results (g01gcfe.r)

G01 Chapter Contents
G01 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


G01GDF : NAG Library, Mark 26

G01 Chapter Contents
G01 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

G01GDF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

G01GDF returns the probability associated with the lower tail of the noncentral F or variance-ratio distribution, via the routine name.

2 Specification

FUNCTION G01GDF ( F, DF1, DF2, RLAMDA, TOL, MAXIT, IFAIL)
REAL (KIND=nag_wp) G01GDF
INTEGER | MAXIT, IFAIL
REAL (KIND=nag_wp) | F, DF1, DF2, RLAMDA, TOL

3 Description

The lower tail probability of the noncentral F-distribution with ν 1 and ν 2 degrees of freedom and noncentrality parameter λ, P F≤f:ν 1,ν 2;λ, is defined by
P F≤f:ν 1,ν 2;λ=∫0 x p F:ν 1,ν 2;λ dF,
where
P F : ν 1,ν 2;λ =∑j= 0∞e-λ/2 λ/2 j j! ×ν 1+ 2 j ν 1+ 2 j/2 ν 2 ν 2/2 B ν 1+ 2 j/2,ν 2/2
×u ν 1+2 j-2/2ν 2+ν 1+2 j u -ν 1+2 j+ν 2/2
and B·,· is the beta function.
The probability is computed by means of a transformation to a noncentral beta distribution:
P F≤f:ν 1,ν 2;λ=Pβ X≤x:a,b;λ,
where x= ν 1 f ν 1 f+ν 2 and Pβ X≤x:a,b;λ is the lower tail probability integral of the noncentral beta distribution with parameters a, b, and λ.
If ν 2 is very large, greater than 106, then a χ 2 approximation is used.

4 References

Abramowitz M and Stegun I A (1972) Handbook of Mathematical Functions (3rd Edition) Dover Publications

5 Arguments

1:   F – REAL (KIND=nag_wp)Input
On entry: f, the deviate from the noncentral F-distribution.
Constraint: F>0.0.
2:   DF1 – REAL (KIND=nag_wp)Input
On entry: the degrees of freedom of the numerator variance, ν 1.
Constraint: 0.0<DF1≤106.
3:   DF2 – REAL (KIND=nag_wp)Input
On entry: the degrees of freedom of the denominator variance, ν 2.
Constraint: DF2>0.0.
4:   RLAMDA – REAL (KIND=nag_wp)Input
On entry: λ, the noncentrality parameter.
Constraint: 0.0≤RLAMDA≤-2.0log U where U is the safe range parameter as defined by X02AMF.
5:   TOL – REAL (KIND=nag_wp)Input
On entry: the relative accuracy required by you in the results. If G01GDF is entered with TOL greater than or equal to 1.0 or less than 10×machine precision (see X02AJF), then the value of 10×machine precision is used instead.
6:   MAXIT – INTEGERInput
On entry: the maximum number of iterations to be used.
Suggested value: 500. See G01GCF and G01GEF for further details.
Constraint: MAXIT≥1.
7:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, because for this routine the values of the output arguments may be useful even if IFAIL≠0 on exit, the recommended value is -1. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Note: G01GDF may return useful information for one or more of the following detected errors or warnings.
Errors or warnings detected by the routine:
If on exit IFAIL=1 or 3, then G01GDF returns 0.0.
IFAIL=1
On entry, | DF1≤0.0,
or | DF1>106,
or | DF2≤0.0,
or | F≤0.0,
or | RLAMDA<0.0,
or | MAXIT<1,
or | RLAMDA>-2.0log U, where U= safe range argument as defined by X02AMF.
IFAIL=2
The solution has failed to converge in MAXIT iterations. You should try a larger value of MAXIT or TOL.
IFAIL=3
The required probability cannot be computed accurately. This may happen if the result would be very close to 0.0 or 1.0. Alternatively the values of DF1 and F may be too large. In the latter case you could try using a normal approximation; see Abramowitz and Stegun (1972).
IFAIL=4
The required accuracy was not achieved when calculating the initial value of the central F (or χ 2) probability. You should try a larger value of TOL. If the χ 2 approximation is being used then G01GDF returns zero otherwise the value returned should be an approximation to the correct value.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

The relative accuracy should be as specified by TOL. For further details see G01GCF and G01GEF.

8 Parallelism and Performance

G01GDF is not threaded in any implementation.

9 Further Comments

When both ν 1 and ν 2 are large a Normal approximation may be used and when only ν 1 is large a χ 2 approximation may be used. In both cases λ is required to be of the same order as ν 1. See Abramowitz and Stegun (1972) for further details.

10 Example

This example reads values from, and degrees of freedom for, F-distributions, computes the lower tail probabilities and prints all these values until the end of data is reached.

10.1 Program Text

Program Text (g01gdfe.f90)

10.2 Program Data

Program Data (g01gdfe.d)

10.3 Program Results

Program Results (g01gdfe.r)

G01 Chapter Contents
G01 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


G01GEF : NAG Library, Mark 26

G01 Chapter Contents
G01 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

G01GEF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

G01GEF returns the probability associated with the lower tail of the noncentral beta distribution, via the routine name.

2 Specification

FUNCTION G01GEF ( X, A, B, RLAMDA, TOL, MAXIT, IFAIL)
REAL (KIND=nag_wp) G01GEF
INTEGER | MAXIT, IFAIL
REAL (KIND=nag_wp) | X, A, B, RLAMDA, TOL

3 Description

The lower tail probability for the noncentral beta distribution with parameters a and b and noncentrality parameter λ, P B≤β:a,b;λ, is defined by
P B≤β:a,b;λ=∑j=0∞e-λ/2 λ/2 j! P B≤β:a,b;0, (1)
where
P B≤β : a,b;0=Γ a+b Γ a Γ b ∫0 β B a- 11-B b- 1 dB,
which is the central beta probability function or incomplete beta function.
Recurrence relationships given in Abramowitz and Stegun (1972) are used to compute the values of P B≤β:a,b;0 for each step of the summation (1).
The algorithm is discussed in Lenth (1987).

4 References

Abramowitz M and Stegun I A (1972) Handbook of Mathematical Functions (3rd Edition) Dover Publications
Lenth R V (1987) Algorithm AS 226: Computing noncentral beta probabilities Appl. Statist. 36 241–244

5 Arguments

1:   X – REAL (KIND=nag_wp)Input
On entry: β, the deviate from the beta distribution, for which the probability P B≤β:a,b;λ is to be found.
Constraint: 0.0≤X≤1.0.
2:   A – REAL (KIND=nag_wp)Input
On entry: a, the first parameter of the required beta distribution.
Constraint: 0.0<A≤106.
3:   B – REAL (KIND=nag_wp)Input
On entry: b, the second parameter of the required beta distribution.
Constraint: 0.0<B≤106.
4:   RLAMDA – REAL (KIND=nag_wp)Input
On entry: λ, the noncentrality parameter of the required beta distribution.
Constraint: 0.0≤RLAMDA≤-2.0log U, where U is the safe range parameter as defined by X02AMF.
5:   TOL – REAL (KIND=nag_wp)Input
On entry: the relative accuracy required by you in the results. If G01GEF is entered with TOL greater than or equal to 1.0 or less than 10×machine precision (see X02AJF), then the value of 10×machine precision is used instead.
See Section 7 for the relationship between TOL and MAXIT.
6:   MAXIT – INTEGERInput
On entry: the maximum number of iterations that the algorithm should use.
See Section 7 for suggestions as to suitable values for MAXIT for different values of the arguments.
Suggested value: 500.
Constraint: MAXIT≥1.
7:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, because for this routine the values of the output arguments may be useful even if IFAIL≠0 on exit, the recommended value is -1. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Note: G01GEF may return useful information for one or more of the following detected errors or warnings.
Errors or warnings detected by the routine:
IFAIL=1
On entry, | A≤0.0,
or | A>106,
or | B≤0.0,
or | B>106,
or | RLAMDA<0.0,
or | RLAMDA>-2.0log U, where U= safe range argument as defined by X02AMF,
or | X<0.0,
or | X>1.0,
or | MAXIT<1.
If on exit IFAIL=1 then G01GEF returns zero.
IFAIL=2
The solution has failed to converge in MAXIT iterations. You should try a larger value of MAXIT or TOL. The returned value will be an approximation to the correct value.
IFAIL=3
The probability is too close to 0.0 or 1.0 for the algorithm to be able to calculate the required probability. G01GEF will return 0.0 or 1.0 as appropriate, this should be a reasonable approximation.
IFAIL=4
The required accuracy was not achieved when calculating the initial value of P B≤β:a,b;λ. You should try a larger value of TOL. The returned value will be an approximation to the correct value.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

Convergence is theoretically guaranteed whenever P Y>MAXIT≤TOL where Y has a Poisson distribution with mean λ/2. Excessive round-off errors are possible when the number of iterations used is high and TOL is close to machine precision. See Lenth (1987) for further comments on the error bound.

8 Parallelism and Performance

G01GEF is not threaded in any implementation.

9 Further Comments

The central beta probabilities can be obtained by setting RLAMDA=0.0.

10 Example

This example reads values for several beta distributions and calculates and prints the lower tail probabilities until the end of data is reached.

10.1 Program Text

Program Text (g01gefe.f90)

10.2 Program Data

Program Data (g01gefe.d)

10.3 Program Results

Program Results (g01gefe.r)

G01 Chapter Contents
G01 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


G01HAF : NAG Library, Mark 26

G01 Chapter Contents
G01 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

G01HAF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

G01HAF returns the lower tail probability for the bivariate Normal distribution, via the routine name.

2 Specification

FUNCTION G01HAF ( X, Y, RHO, IFAIL)
REAL (KIND=nag_wp) G01HAF
INTEGER | IFAIL
REAL (KIND=nag_wp) | X, Y, RHO

3 Description

For the two random variables X,Y following a bivariate Normal distribution with
E X=0,  E Y=0,  E X 2=1,  E Y 2=1  and  E XY=ρ,
the lower tail probability is defined by:
P X≤x,Y≤y:ρ=1 2 π⁢1-ρ 2 ∫-∞y ∫-∞x exp- X 2- 2 ρ XY+Y 2 2 1-ρ 2 dXdY.
For a more detailed description of the bivariate Normal distribution and its properties see Abramowitz and Stegun (1972) and Kendall and Stuart (1969). The method used is described by Genz (2004).

4 References

Abramowitz M and Stegun I A (1972) Handbook of Mathematical Functions (3rd Edition) Dover Publications
Genz A (2004) Numerical computation of rectangular bivariate and trivariate Normal and t probabilities Statistics and Computing 14 151–160
Kendall M G and Stuart A (1969) The Advanced Theory of Statistics (Volume 1) (3rd Edition) Griffin

5 Arguments

1:   X – REAL (KIND=nag_wp)Input
On entry: x, the first argument for which the bivariate Normal distribution function is to be evaluated.
2:   Y – REAL (KIND=nag_wp)Input
On entry: y, the second argument for which the bivariate Normal distribution function is to be evaluated.
3:   RHO – REAL (KIND=nag_wp)Input
On entry: ρ, the correlation coefficient.
Constraint: -1.0≤RHO≤1.0.
4:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, | RHO<-1.0,
or | RHO>1.0.
If on exit IFAIL=1 then G01HAF returns zero.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

Accuracy of the hybrid algorithm implemented here is discussed in Genz (2004). This algorithm should give a maximum absolute error of less than 5×10-16.

8 Parallelism and Performance

G01HAF is not threaded in any implementation.

9 Further Comments

The probabilities for the univariate Normal distribution can be computed using S15ABF and S15ACF.

10 Example

This example reads values of x and y for a bivariate Normal distribution along with the value of ρ and computes the lower tail probabilities.

10.1 Program Text

Program Text (g01hafe.f90)

10.2 Program Data

Program Data (g01hafe.d)

10.3 Program Results

Program Results (g01hafe.r)

G01 Chapter Contents
G01 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


G01HBF : NAG Library, Mark 26

G01 Chapter Contents
G01 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

G01HBF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

G01HBF returns the upper tail, lower tail or central probability associated with a multivariate Normal distribution of up to ten dimensions.

2 Specification

FUNCTION G01HBF ( TAIL, N, A, B, XMU, SIG, LDSIG, TOL, WK, LWK, IFAIL)
REAL (KIND=nag_wp) G01HBF
INTEGER | N, LDSIG, LWK, IFAIL
REAL (KIND=nag_wp) | A(N), B(N), XMU(N), SIG(LDSIG,N), TOL, WK(LWK)
CHARACTER(1) | TAIL

3 Description

Let the vector random variable X = X 1,X 2,…,Xn T follow an n-dimensional multivariate Normal distribution with mean vector μ and n by n variance-covariance matrix Σ, then the probability density function, f X:μ,Σ, is given by
f X:μ,Σ = 2 π - 1/2 n Σ -1/2 exp -12 X-μ T Σ-1 X-μ .
The lower tail probability is defined by:
P X 1≤b 1,…,Xn≤bn: μ ,Σ=∫-∞ b 1⋯∫-∞ bn f X : μ ,Σ d Xn⋯d X 1.
The upper tail probability is defined by:
P X 1≥a 1,…,Xn≥an:μ,Σ=∫a 1∞⋯∫an∞f X:μ,Σ d Xn⋯d X 1.
The central probability is defined by:
P a 1≤X 1≤b 1,…,an≤Xn≤bn: μ ,Σ=∫a 1b 1⋯∫anbn f X : μ ,Σ d Xn⋯d X 1.
To evaluate the probability for n≥3, the probability density function of X 1,X 2,…,Xn is considered as the product of the conditional probability of X 1,X 2,…,X n-2 given X n-1 and Xn and the marginal bivariate Normal distribution of X n-1 and Xn. The bivariate Normal probability can be evaluated as described in G01HAF and numerical integration is then used over the remaining n-2 dimensions. In the case of n=3, D01AJF is used and for n>3 D01FCF is used.
To evaluate the probability for n=1 a direct call to G01EAF is made and for n=2 calls to G01HAF are made.

4 References

Kendall M G and Stuart A (1969) The Advanced Theory of Statistics (Volume 1) (3rd Edition) Griffin

5 Arguments

1:   TAIL – CHARACTER(1)Input
On entry: indicates which probability is to be returned.
TAIL='L'
The lower tail probability is returned.
TAIL='U'
The upper tail probability is returned.
TAIL='C'
The central probability is returned.
Constraint: TAIL='L', 'U' or 'C'.
2:   N – INTEGERInput
On entry: n, the number of dimensions.
Constraint: 1≤N≤10.
3:   A N – REAL (KIND=nag_wp) arrayInput
On entry: if TAIL='C' or 'U', the lower bounds, ai, for i=1,2,…,n.
If TAIL='L', A is not referenced.
4:   B N – REAL (KIND=nag_wp) arrayInput
On entry: if TAIL='C' or 'L', the upper bounds, bi, for i=1,2,…,n.
If TAIL='U', B is not referenced.
Constraint: if TAIL='C', A i<B i, for i=1,2,…,n.
5:   XMU N – REAL (KIND=nag_wp) arrayInput
On entry: μ, the mean vector of the multivariate Normal distribution.
6:   SIG LDSIGN – REAL (KIND=nag_wp) arrayInput
On entry: Σ, the variance-covariance matrix of the multivariate Normal distribution. Only the lower triangle is referenced.
Constraint: Σ must be positive definite.
7:   LDSIG – INTEGERInput
On entry: the first dimension of the array SIG as declared in the (sub)program from which G01HBF is called.
Constraint: LDSIG≥N.
8:   TOL – REAL (KIND=nag_wp)Input
On entry: if n>2 the relative accuracy required for the probability, and if the upper or the lower tail probability is requested then TOL is also used to determine the cut-off points, see Section 7.
If n=1, TOL is not referenced.
Suggested value: TOL=0.0001.
Constraint: if N>1, TOL>0.0.
9:   WK LWK – REAL (KIND=nag_wp) arrayWorkspace
10:   LWK – INTEGERInput
On entry: the length of workspace provided in array WK. This workspace is used by the numerical integration routines D01AJF for n=3 and D01FCF for n>3.
If n=3, then the maximum number of sub-intervals used by D01AJF is LWK/4. Note, however, increasing LWK above 1000 will not increase the maximum number of sub-intervals above 250.
If n>3 the maximum number of integrand evaluations used by D01FCF is α LWK/n-1, where α=2 n-2+2⁢ n-2 2+2 n-2+1.
If n=1​ or ​2, then WK will not be used.
Suggested value: 2000 if n>3 and 1000 if n=3.
Constraints:
  • if N≤2, LWK≥1;
  • if N≥3, LWK≥4×N.
11:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, because for this routine the values of the output arguments may be useful even if IFAIL≠0 on exit, the recommended value is -1. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Note: G01HBF may return useful information for one or more of the following detected errors or warnings.
Errors or warnings detected by the routine:
If on exit IFAIL=1, 2 or 3, then G01HBF returns zero.
IFAIL=1
On entry, LDSIG=value and N=value.
Constraint: LDSIG≥N.
On entry, LWK=value.
Constraint: if N≤2, LWK≥1.
On entry, LWK=value.
Constraint: if N≥3, LWK≥4×N.
On entry, N=value.
Constraint: 1≤N≤10.
On entry, TAIL is not valid: TAIL=value.
On entry, TOL=value.
Constraint: TOL>0.0.
IFAIL=2
On entry, the value value in B is less than or equal to the corresponding value in A.
IFAIL=3
On entry, SIG is not positive definite.
IFAIL=4
Full accuracy not achieved, relative accuracy =value. A larger value of TOL can be tried or the length of the workspace increased. The returned value is an approximation to the required result.
IFAIL=5
Accuracy requested by TOL is too strict: TOL=value. Round-off error has prevented the requested accuracy from being achieved; a larger value of TOL can be tried. The returned value will be an approximation to the required result.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

The accuracy should be as specified by TOL. When on exit IFAIL=4 the approximate accuracy achieved is given in the error message. For the upper and lower tail probabilities the infinite limits are approximated by cut-off points for the n-2 dimensions over which the numerical integration takes place; these cut-off points are given by Φ-1 TOL/10×n, where Φ-1 is the inverse univariate Normal distribution function.

8 Parallelism and Performance

G01HBF is not threaded in any implementation.

9 Further Comments

The time taken is related to the number of dimensions, the range over which the integration takes place (bi-ai, for i=1,2,…,n) and the value of Σ as well as the accuracy required. As the numerical integration does not take place over the last two dimensions speed may be improved by arranging X so that the largest ranges of integration are for X n-1 and Xn.

10 Example

This example reads in the mean and covariance matrix for a multivariate Normal distribution and computes and prints the associated central probability.

10.1 Program Text

Program Text (g01hbfe.f90)

10.2 Program Data

Program Data (g01hbfe.d)

10.3 Program Results

Program Results (g01hbfe.r)

G01 Chapter Contents
G01 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


G01HCF : NAG Library, Mark 26

G01 Chapter Contents
G01 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

G01HCF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

G01HCF returns probabilities for the bivariate Student's t-distribution, via the routine name.

2 Specification

FUNCTION G01HCF ( TAIL, A, B, DF, RHO, IFAIL)
REAL (KIND=nag_wp) G01HCF
INTEGER | DF, IFAIL
REAL (KIND=nag_wp) | A(2), B(2), RHO
CHARACTER(1) | TAIL

3 Description

Let the vector random variable X = X 1,X 2 T follow a bivariate Student's t-distribution with degrees of freedom ν and correlation ρ, then the probability density function is given by
f X:ν,ρ = 1 2 π 1-ρ 2 1 + X 12 + X 22 - 2 ρ X 1 X 2 ν 1-ρ 2 -ν/2-1 .
The lower tail probability is defined by:
P X 1 ≤ b 1 , X 2 ≤ b 2 :ν,ρ = ∫ -∞ b 1 ∫ -∞ b 2 f X:ν,ρ d X 2 d X 1 .
The upper tail probability is defined by:
P X 1 ≥ a 1 , X 2 ≥ a 2 :ν,ρ = ∫ a 1 ∞ ∫ a 2 ∞ f X:ν,ρ d X 2 d X 1 .
The central probability is defined by:
P a 1 ≤ X 1 ≤ b 1 , a 2 ≤ X 2 ≤ b 2 :ν,ρ = ∫ a 1 b 1 ∫ a 2 b 2 f X:ν,ρ d X 2 d X 1 .
Calculations use the Dunnet and Sobel (1954) method, as described by Genz (2004).

4 References

Dunnet C W and Sobel M (1954) A bivariate generalization of Student's t-distribution, with tables for certain special cases Biometrika 41 153–169
Genz A (2004) Numerical computation of rectangular bivariate and trivariate Normal and t probabilities Statistics and Computing 14 151–160

5 Arguments

1:   TAIL – CHARACTER(1)Input
On entry: indicates which probability is to be returned.
TAIL='L'
The lower tail probability is returned.
TAIL='U'
The upper tail probability is returned.
TAIL='C'
The central probability is returned.
Constraint: TAIL='L', 'U' or 'C'.
2:   A 2 – REAL (KIND=nag_wp) arrayInput
On entry: if TAIL='C' or 'U', the lower bounds a 1 and a 2.
If TAIL='L', A is not referenced.
3:   B 2 – REAL (KIND=nag_wp) arrayInput
On entry: if TAIL='C' or 'L', the upper bounds b 1 and b 2.
If TAIL='U', B is not referenced.
Constraint: if TAIL='C', ai<bi, for i=1,2.
4:   DF – INTEGERInput
On entry: ν, the degrees of freedom of the bivariate Student's t-distribution.
Constraint: DF≥1.
5:   RHO – REAL (KIND=nag_wp)Input
On entry: ρ, the correlation of the bivariate Student's t-distribution.
Constraint: -1.0≤RHO≤1.0.
6:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
If on exit, IFAIL≠0, then G01HCF returns zero.
IFAIL=1
On entry, TAIL is not valid: TAIL=value.
IFAIL=3
On entry, B i≤A i for central probability, for some i=1,2.
IFAIL=4
On entry, DF=value.
Constraint: DF≥1.
IFAIL=5
On entry, RHO=value.
Constraint: -1.0≤RHO≤1.0.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

Accuracy of the algorithm implemented here is discussed in comparison with algorithms based on a generalized Placket formula by Genz (2004), who recommends the Dunnet and Sobel method. This implementation should give a maximum absolute error of the order of 10-16.

8 Parallelism and Performance

G01HCF is not threaded in any implementation.

9 Further Comments

None.

10 Example

This example calculates the bivariate Student's t probability given the choice of tail and degrees of freedom, correlation and bounds.

10.1 Program Text

Program Text (g01hcfe.f90)

10.2 Program Data

Program Data (g01hcfe.d)

10.3 Program Results

Program Results (g01hcfe.r)

G01 Chapter Contents
G01 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


G01HDF : NAG Library, Mark 26

G01 Chapter Contents
G01 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

G01HDF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

G01HDF returns a probability associated with a multivariate Student's t-distribution.

2 Specification

FUNCTION G01HDF ( N, TAIL, A, B, NU, DELTA, ISCOV, RC, LDRC, EPSABS, EPSREL, NUMSUB, NSAMPL, FMAX, ERREST, IFAIL)
REAL (KIND=nag_wp) G01HDF
INTEGER | N, ISCOV, LDRC, NUMSUB, NSAMPL, FMAX, IFAIL
REAL (KIND=nag_wp) | A(N), B(N), NU, DELTA(N), RC(LDRC,N), EPSABS, EPSREL, ERREST
CHARACTER(1) | TAIL(N)

3 Description

A random vector x∈ℝn that follows a Student's t-distribution with ν degrees of freedom and covariance matrix Σ has density:
Γ ν+n / 2 Γ ν/2 ν n/2 π n/2 Σ 1/2 1+ 1 ν xT Σ-1 x ν+n / 2 ,
and probability p given by:
p = Γ ν+n / 2 Γ ν/2 Σ πν n ∫ a 1 b 1 ∫ a 2 b 2 ⋯ ∫ an bn 1+ xT Σ-1 x/ν - ν+n/2 dx .
The method of calculation depends on the dimension n and degrees of freedom ν. The method of Dunnet and Sobel is used in the bivariate case if ν is a whole number. A Plackett transform followed by quadrature method is adopted in other bivariate cases and trivariate cases. In dimensions higher than three a number theoretic approach to evaluating multidimensional integrals is adopted.
Error estimates are supplied as the published accuracy in the Dunnet and Sobel case, a Monte–Carlo standard error for multidimensional integrals, and otherwise the quadrature error estimate.
A parameter δ allows for non-central probabilities. The number theoretic method is used if any δ is nonzero.
In cases other than the central bivariate with whole ν, G01HDF attempts to evaluate probabilities within a requested accuracy max εa,εr×I, for an approximate integral value I, absolute accuracy εa and relative accuracy εr.

4 References

Dunnet C W and Sobel M (1954) A bivariate generalization of Student's t-distribution, with tables for certain special cases Biometrika 41 153–169
Genz A and Bretz F (2002) Methods for the computation of multivariate t-probabilities Journal of Computational and Graphical Statistics (11) 950–971

5 Arguments

1:   N – INTEGERInput
On entry: n, the number of dimensions.
Constraint: 1<N≤1000.
2:   TAIL N – CHARACTER(1) arrayInput
On entry: defines the calculated probability, set TAIL i to:
TAIL i='L'
If the ith lower limit ai is negative infinity.
TAIL i='U'
If the ith upper limit bi is infinity.
TAIL i='C'
If both ai and bi are finite.
Constraint: TAIL i='L', 'U' or 'C', for i=1,2,…,N.
3:   A N – REAL (KIND=nag_wp) arrayInput
On entry: ai, for i=1,2,…,n, the lower integral limits of the calculation.
If TAIL i='L', A i is not referenced and the ith lower limit of integration is -∞.
4:   B N – REAL (KIND=nag_wp) arrayInput
On entry: bi, for i=1,2,…,n, the upper integral limits of the calculation.
If TAIL i='U', B i is not referenced and the ith upper limit of integration is ∞.
Constraint: if TAIL i='C', B i>A i.
5:   NU – REAL (KIND=nag_wp)Input
On entry: ν, the degrees of freedom.
Constraint: NU>0.0.
6:   DELTA N – REAL (KIND=nag_wp) arrayInput
On entry: DELTA i the noncentrality parameter for the ith dimension, for i=1,2,…,N; set DELTA i=0 for the central probability.
7:   ISCOV – INTEGERInput
On entry: set ISCOV=1 if the covariance matrix is supplied and ISCOV=2 if the correlation matrix is supplied.
Constraint: ISCOV=1 or 2.
8:   RC LDRCN – REAL (KIND=nag_wp) arrayInput/Output
On entry: the lower triangle of either the covariance matrix (if ISCOV=1) or the correlation matrix (if ISCOV=2). In either case the array elements corresponding to the upper triangle of the matrix need not be set.
On exit: the strict upper triangle of RC contains the correlation matrix used in the calculations.
9:   LDRC – INTEGERInput
On entry: the first dimension of the array RC as declared in the (sub)program from which G01HDF is called.
Constraint: LDRC≥N.
10:   EPSABS – REAL (KIND=nag_wp)Input
On entry: εa, the absolute accuracy requested in the approximation. If EPSABS is negative, the absolute value is used.
Suggested value: 0.0.
11:   EPSREL – REAL (KIND=nag_wp)Input
On entry: εr, the relative accuracy requested in the approximation. If EPSREL is negative, the absolute value is used.
Suggested value: 0.001.
12:   NUMSUB – INTEGERInput
On entry: if quadrature is used, the number of sub-intervals used by the quadrature algorithm; otherwise NUMSUB is not referenced.
Suggested value: 350.
Constraint: if referenced, NUMSUB>0.
13:   NSAMPL – INTEGERInput
On entry: if quadrature is used, NSAMPL is not referenced; otherwise NSAMPL is the number of samples used to estimate the error in the approximation.
Suggested value: 8.
Constraint: if referenced, NSAMPL>0.
14:   FMAX – INTEGERInput
On entry: if a number theoretic approach is used, the maximum number of evaluations for each integrand function.
Suggested value: 1000×N.
Constraint: if referenced, FMAX≥1.
15:   ERREST – REAL (KIND=nag_wp)Output
On exit: an estimate of the error in the calculated probability.
16:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, N=value.
Constraint: 1<N≤1000.
IFAIL=2
On entry, TAIL k=value.
Constraint: TAIL k='L', 'U' or 'C'.
IFAIL=4
On entry, k=value.
Constraint: B k>A k for a central probability.
IFAIL=5
On entry, NU=value.
Constraint: degrees of freedom NU>0.0.
IFAIL=8
On entry, ISCOV=value.
Constraint: ISCOV=1 or 2.
IFAIL=9
On entry, the information supplied in RC is invalid.
IFAIL=10
On entry, LDRC=value and N=value.
Constraint: LDRC≥N.
IFAIL=12
On entry, NUMSUB=value.
Constraint: NUMSUB≥1.
IFAIL=13
On entry, NSAMPL=value.
Constraint: NSAMPL≥1.
IFAIL=14
On entry, FMAX=value.
Constraint: FMAX≥1.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

An estimate of the error in the calculation is given by the value of ERREST on exit.

8 Parallelism and Performance

G01HDF is not threaded in any implementation.

9 Further Comments

None.

10 Example

This example prints two probabilities from the Student's t-distribution.

10.1 Program Text

Program Text (g01hdfe.f90)

10.2 Program Data

Program Data (g01hdfe.d)

10.3 Program Results

Program Results (g01hdfe.r)

G01 Chapter Contents
G01 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


G01 Chapter Introduction : NAG Library, Mark 26

G01 Chapter Contents
NAG Library Manual

NAG Library Chapter Introduction

G01 – Simple Calculations on Statistical Data

▸▿ Contents

1 Scope of the Chapter
▸▿ 2 Background to the Problems
2.1 Plots, Descriptive Statistics and Exploratory Data Analysis
2.2 Statistical Distribution Functions and Their Inverses
2.3 Testing for Normality and Other Distributions
2.4 Distribution of Quadratic Forms
2.5 Energy Loss Distributions
2.6 Vectorized Routines
▸▿ 3 Recommendations on Choice and Use of Available Routines
3.1 Working with Streamed or Extremely Large Datasets
4 Auxiliary Routines Associated with Library Routine Arguments
5 Routines Withdrawn or Scheduled for Withdrawal
6 References

1 Scope of the Chapter

This chapter covers three topics:
  • plots, descriptive statistics, and exploratory data analysis;
  • statistical distribution functions and their inverses;
  • testing for Normality and other distributions.

2 Background to the Problems

2.1 Plots, Descriptive Statistics and Exploratory Data Analysis

Plots and simple descriptive statistics are generally used for one of two purposes:
  • the presentation of data;
  • exploratory data analysis.
Exploratory data analysis (EDA) is used to pick out the important features of the data in order to guide the choice of appropriate models. EDA makes use of simple displays and summary statistics. These may suggest models or transformations of the data which can then be confirmed by further plots. The process is interactive between you, the data, and the program producing the EDA displays.
The summary statistics consist of two groups. The first group are those based on moments; for example mean, standard deviation, coefficient of skewness, and coefficient of kurtosis (sometimes called the ‘excess of kurtosis’, which has the value 0 for the Normal distribution). These statistics may be sensitive to extreme observations and some robust versions are available in Chapter G07. The second group of summary statistics are based on the order statistics, where the ith order statistic in a sample is the ith smallest observation in that sample. Examples of such statistics are minimum, maximum, median, hinges and quantiles.
In addition to summarising the data by using suitable statistics the data can be displayed using tables and diagrams. Such data displays include frequency tables, stem and leaf displays, box and whisker plots, histograms and scatter plots.

2.2 Statistical Distribution Functions and Their Inverses

Statistical distributions are commonly used in three problems:
  • evaluation of probabilities and expected frequencies for a distribution model;
  • testing of hypotheses about the variables being observed;
  • evaluation of confidence limits for parameters of fitted model, for example the mean of a Normal distribution.
Random variables can be either discrete (i.e., they can take only a limited number of values) or continuous (i.e., can take any value in a given range). However, for a large sample from a discrete distribution an approximation by a continuous distribution, usually the Normal distribution, can be used. Distributions commonly used as a model for discrete random variables are the binomial, hypergeometric, and Poisson distributions. The binomial distribution arises when there is a fixed probability of a selected outcome as in sampling with replacement, the hypergeometric distribution is used in sampling from a finite population without replacement, and the Poisson distribution is often used to model counts.
Distributions commonly used as a model for continuous random variables are the Normal, gamma, and beta distributions. The Normal is a symmetric distribution whereas the gamma is skewed and only appropriate for non-negative values. The beta is for variables in the range 0,1 and may take many different shapes. For circular data, the ‘equivalent’ to the Normal distribution is the von Mises distribution. The assumption of the Normal distribution leads to procedures for testing and interval estimation based on the χ 2, F (variance ratio), and Student's t-distributions.
In the hypothesis testing situation, a statistic X with known distribution under the null hypothesis is evaluated, and the probability α of observing such a value or one more ‘extreme’ value is found. This probability (the significance) is usually then compared with a preassigned value (the significance level of the test), to decide whether the null hypothesis can be rejected in favour of an alternate hypothesis on the basis of the sample values. Many tests make use of those distributions derived from the Normal distribution as listed above, but for some tests specific distributions such as the Studentized range distribution and the distribution of the Durbin–Watson test have been derived. Nonparametric tests as given in Chapter G08, such as the Kolmogorov–Smirnov test, often use statistics with distributions specific to the test. The probability that the null hypothesis will be rejected when the simple alternate hypothesis is true (the power of the test) can be found from the noncentral distribution.
The confidence interval problem requires the inverse calculation. In other words, given a probability α, the value x is to be found, such that the probability that a value not exceeding x is observed is equal to α. A confidence interval of size 1-2 α, for the quantity of interest, can then be computed as a function of x and the sample values.
The required statistics for either testing hypotheses or constructing confidence intervals can be computed with the aid of routines in this chapter, and Chapter G02 (for regression), Chapter G04 (for analysis of designed experiments), Chapter G13 (for time series), and Chapter E04 (for nonlinear least squares problems).
Pseudorandom numbers from many statistical distributions can be generated by routines in Chapter G05.

2.3 Testing for Normality and Other Distributions

Methods of checking that observations (or residuals from a model) come from a specified distribution, for example, the Normal distribution, are often based on order statistics. Graphical methods include the use of probability plots. These can be either P-P plots (probability–probability plots), in which the empirical probabilities are plotted against the theoretical probabilities for the distribution, or Q-Q plots (quantile–quantile plots), in which the sample points are plotted against the theoretical quantiles. Q-Q plots are more common, partly because they are invariant to differences in scale and location. In either case if the observations come from the specified distribution then the plotted points should roughly lie on a straight line.
If yi is the ith smallest observation from a sample of size n (i.e., the ith order statistic) then in a Q-Q plot for a distribution with cumulative distribution function F, the value yi is plotted against xi, where F xi=i-α/n-2 α+1, a common value of α being 12 . For the Normal distribution, the Q-Q plot is known as a Normal probability plot.
The values xi used in Q-Q plots can be regarded as approximations to the expected values of the order statistics. For a sample from a Normal distribution the expected values of the order statistics are known as Normal scores and for an exponential distribution they are known as Savage scores.
An alternative approach to probability plots are the more formal tests. A test for Normality is the Shapiro and Wilk's W Test, which uses Normal scores. Other tests are the χ 2 goodness-of-fit test and the Kolmogorov–Smirnov test; both can be found in Chapter G08.

2.4 Distribution of Quadratic Forms

Many test statistics for Normally distributed data lead to quadratic forms in Normal variables. If X is a n-dimensional Normal variable with mean μ and variance-covariance matrix Σ then for an n by n matrix A the quadratic form is
Q=XT AX.
The distribution of Q depends on the relationship between A and Σ: if AΣ is idempotent then the distribution of Q will be central or noncentral χ 2 depending on whether μ is zero.
The distribution of other statistics may be derived as the distribution of linear combinations of quadratic forms, for example the Durbin–Watson test statistic, or as ratios of quadratic forms. In some cases rather than the distribution of these functions of quadratic forms the values of the moments may be all that is required.

2.5 Energy Loss Distributions

An application of distributions in the field of high-energy physics where there is a requirement to model fluctuations in energy loss experienced by a particle passing through a layer of material. Three models are commonly used:
(i) | Gaussian (Normal) distribution;
(ii) | the Landau distribution;
(iii) | the Vavilov distribution.
Both the Landau and the Vavilov density functions can be defined in terms of a complex integral. The Vavilov distribution is the more general energy loss distribution with the Landau and Gaussian being suitable when the Vavilov parameter κ is less than 0.01 and greater than 10.0 respectively.

2.6 Vectorized Routines

A number of vectorized routines are included in this chapter. Unlike their scalar counterparts, which take a single set of parameters and perform a single function evaluation, these routines take vectors of parameters and perform multiple function evaluations in a single call. The input arrays to these vectorized routines are designed to allow maximum flexibility in the supply of the parameters by reusing, in a cyclic manner, elements of any arrays that are shorter than the number of functions to be evaluated, where the total number of functions evaluated is the size of the largest array.
To illustrate this we will consider G01SFF, a vectorized version of G01EFF, which calculates the probabilities for a gamma distribution. The gamma distribution has two parameters α and β therefore G01SFF has four input arrays, one indicating the tail required (TAIL), one giving the value of the gamma variate, g, whose probability is required (G), one for α (A) and one for β (B). The lengths of these arrays are LTAIL, LG, LA and LB respectively.
For sake of argument, lets assume that LTAIL=1, LG=2, LA=3 and LB=4, then max LTAIL,LG,LA,LB=4 values will be returned. These four probabilities would be calculated using the following parameters:
i | Tail | g | α | β
1 | TAIL 1 | G 1 | A 1 | B 1
2 | TAIL 1 | G 2 | A 2 | B 2
3 | TAIL 1 | G 1 | A 3 | B 3
4 | TAIL 1 | G 2 | A 1 | B 4

3 Recommendations on Choice and Use of Available Routines

Descriptive statistics / Exploratory analysis,
plots,
box and whisker G01ASF
histogram G01AJF
Normal probability (Q − Q) plot G01AHF
scatter plot G01AGF
stem and leaf G01ARF
summaries,
frequency / contingency table,
one variable G01AEF
two variables, with χ 2 and Fisher's exact test G01AFF
mean, variance, skewness, kurtosis (one variable),
combine summaries G01AUF
from frequency table G01ADF
from raw data G01ATF
mean, variance, sums of squares and products (two variables) G01ABF
median, hinges / quartiles, minimum, maximum G01ALF
quantiles,
approximate,
large data stream of fixed size G01ANF
large data stream of unknown size G01APF
unordered vector G01AMF
rolling window,
mean, standard deviation (one variable) G01WAF
Distributions,
Beta,
central,
deviates,
scalar G01FEF
vectorized G01TEF
probabilities and probability density function,
scalar G01EEF
vectorized G01SEF
non-central,
probabilities G01GEF
binomial,
distribution function,
scalar G01BJF
vectorized G01SJF
Dickey–Fuller unit root test,
probabilities, G01EWF
Durbin–Watson statistic,
probabilities G01EPF
energy loss distributions,
Landau,
density G01MTF
derivative of density G01RTF
distribution G01ETF
first moment G01PTF
inverse distribution G01FTF
second moment G01QTF
Vavilov,
density G01MUF
distribution G01EUF
initialization G01ZUF
F:
central,
deviates,
scalar G01FDF
vectorized G01TDF
probabilities,
scalar G01EDF
vectorized G01SDF
non-central,
probabilities G01GDF
gamma,
deviates,
scalar G01FFF
vectorized G01TFF
probabilities,
scalar G01EFF
vectorized G01SFF
probability density function,
scalar G01KFF
vectorized G01KKF
Hypergeometric,
distribution function,
scalar G01BLF
vectorized G01SLF
Kolomogorov–Smirnov,
probabilities,
one-sample G01EYF
two-sample G01EZF
Normal,
bivariate,
probabilities G01HAF
multivariate,
probabilities G01HBF
probability density function,
vectorized G01LBF
quadratic forms,
cumulants and moments G01NAF
moments of ratios G01NBF
univariate,
deviates,
scalar G01FAF
vectorized G01TAF
probabilities,
scalar G01EAF
vectorized G01SAF
probability density function,
scalar G01KAF
vectorized G01KQF
reciprocal of Mill's Ratio G01MBF
Shapiro and Wilk's test for Normality G01DDF
Poisson,
distribution function,
scalar G01BKF
vectorized G01SKF
Student's t:
central,
bivariate,
probabilities G01HCF
multivariate,
probabilities G01HDF
univariate,
deviates,
scalar G01FBF
vectorized G01TBF
probabilities,
scalar G01EBF
vectorized G01SBF
non-central,
probabilities G01GBF
Studentized range statistic,
deviates G01FMF
probabilities G01EMF
von Mises,
probabilities G01ERF
χ 2:
central,
deviates G01FCF
probabilities G01ECF
probability of linear combination G01JDF
non-central,
probabilities G01GCF
probability of linear combination G01JCF
vectorized deviates G01TCF
vectorized probabilities G01SCF
Scores,
Normal scores,
accurate G01DAF
approximate G01DBF
variance-covariance matrix G01DCF
Normal scores, ranks or exponential (Savage) scores G01DHF
Note: the Student's t, χ 2, and F routines do not aim to achieve a high degree of accuracy, only about four or five significant figures, but this should be quite sufficient for hypothesis testing. However, both the Student's t and the F-distributions can be transformed to a beta distribution and the χ 2-distribution can be transformed to a gamma distribution, so a higher accuracy can be obtained by calls to the gamma or beta routines.
Note: G01DHF computes either ranks, approximations to the Normal scores, Normal, or Savage scores for a given sample. G01DHF also gives you control over how it handles tied observations. G01DAF computes the Normal scores for a given sample size to a requested accuracy; the scores are returned in ascending order. G01DAF can be used if either high accuracy is required or if Normal scores are required for many samples of the same size, in which case you will have to sort the data or scores.

3.1 Working with Streamed or Extremely Large Datasets

The majority of the routines in this chapter are ‘in-core’, that is all the data required must be held in memory prior to calling the routine. In some situations this might not be possible, for example, when working with extremely large datasets or where all of the data is not available at once (i.e., the data is being streamed).
There are five routines in this chapter applicable to datasets of this form:
G01ATF computes the mean, variance and the coefficients of skewness and kurtosis for a single variable.
G01AUF, takes the results from two calls to G01ATF and combines them, returning the mean, variance and the coefficients of skewness and kurtosis for the combined dataset. This routine allows the easy utilization of more than one processor to spread the computational burden inherent in summarising a very large dataset.
G01ANF and G01APF compute the approximate quantiles for a dataset of known and unknown size respectively.
G01WAF computes the mean and standard deviation in a rolling window.
In addition, see G02BUF and G02BZF for routines to summarise two or more variables.

4 Auxiliary Routines Associated with Library Routine Arguments

None.

5 Routines Withdrawn or Scheduled for Withdrawal

The following lists all those routines that have been withdrawn since Mark 19 of the Library or are scheduled for withdrawal at one of the next two marks.
Withdrawn Routine | Mark of Withdrawal | Replacement Routine(s)
G01AAF | 26 | G01ATF

6 References

Hastings N A J and Peacock J B (1975) Statistical Distributions Butterworth
Kendall M G and Stuart A (1969) The Advanced Theory of Statistics (Volume 1) (3rd Edition) Griffin
Tukey J W (1977) Exploratory Data Analysis Addison–Wesley
G01 Chapter Contents
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


G01JCF : NAG Library, Mark 26

G01 Chapter Contents
G01 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

G01JCF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

G01JCF returns the lower tail probability of a distribution of a positive linear combination of χ 2 random variables.

2 Specification

SUBROUTINE G01JCF ( A, MULT, RLAMDA, N, C, P, PDF, TOL, MAXIT, WRK, IFAIL)
INTEGER | MULT(N), N, MAXIT, IFAIL
REAL (KIND=nag_wp) | A(N), RLAMDA(N), C, P, PDF, TOL, WRK(N+2*MAXIT)

3 Description

For a linear combination of noncentral χ 2 random variables with integer degrees of freedom the lower tail probability is
P ∑j=1 n aj χ 2 mj,λj≤c , (1)
where aj and c are positive constants and where χ 2 mj,λj represents an independent χ 2 random variable with mj degrees of freedom and noncentrality argument λj. The linear combination may arise from considering a quadratic form in Normal variables.
Ruben's method as described in Farebrother (1984) is used. Ruben has shown that (1) may be expanded as an infinite series of the form
∑k=0∞dk F m+2 k,c/β , (2)
where F m+2 k,c/β=P χ 2 m+2 k<c/β , i.e., the probability that a central χ 2 is less than c/β.
The value of β is set at
β=βB=2 1/amin+1/amax
unless βB>1.8 amin, in which case
β=βA=amin
is used, where amin=min aj and amax=max aj, for j=1,2,…,n.

4 References

Farebrother R W (1984) The distribution of a positive linear combination of χ 2 random variables Appl. Statist. 33(3)

5 Arguments

1:   A N – REAL (KIND=nag_wp) arrayInput
On entry: the weights, a 1,a 2,…,an.
Constraint: A i>0.0, for i=1,2,…,n.
2:   MULT N – INTEGER arrayInput
On entry: the degrees of freedom, m 1,m 2,…,mn.
Constraint: MULT i≥1, for i=1,2,…,N.
3:   RLAMDA N – REAL (KIND=nag_wp) arrayInput
On entry: the noncentrality parameters, λ 1,λ 2,…,λn.
Constraint: RLAMDA i≥0.0, for i=1,2,…,n.
4:   N – INTEGERInput
On entry: n, the number of χ 2 random variables in the combination, i.e., the number of terms in equation (1).
Constraint: N≥1.
5:   C – REAL (KIND=nag_wp)Input
On entry: c, the point for which the lower tail probability is to be evaluated.
Constraint: C≥0.0.
6:   P – REAL (KIND=nag_wp)Output
On exit: the lower tail probability associated with the linear combination of n χ 2 random variables with mj degrees of freedom, and noncentrality arguments λj, for j=1,2,…,n.
7:   PDF – REAL (KIND=nag_wp)Output
On exit: the value of the probability density function of the linear combination of χ 2 variables.
8:   TOL – REAL (KIND=nag_wp)Input
On entry: the relative accuracy required by you in the results. If G01JCF is entered with TOL greater than or equal to 1.0 or less than 10×machine precision (see X02AJF), then the value of 10×machine precision is used instead.
9:   MAXIT – INTEGERInput
On entry: the maximum number of terms that should be used during the summation.
Suggested value: 500.
Constraint: MAXIT≥1.
10:   WRK N+2×MAXIT – REAL (KIND=nag_wp) arrayWorkspace
11:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, because for this routine the values of the output arguments may be useful even if IFAIL≠0 on exit, the recommended value is -1. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Note: G01JCF may return useful information for one or more of the following detected errors or warnings.
Errors or warnings detected by the routine:
If on exit IFAIL=1 or 2, then G01JCF returns 0.0.
IFAIL=1
On entry, | N<1,
or | MAXIT<1,
or | C<0.0.
IFAIL=2
On entry, | A has an element ≤0.0,
or | MULT has an element <1,
or | RLAMDA has an element <0.0.
IFAIL=3
The central χ 2 calculation has failed to converge. This is an unlikely exit. A larger value of TOL should be tried.
IFAIL=4
The solution has failed to converge within MAXIT iterations. A larger value of MAXIT or TOL should be used. The returned value should be a reasonable approximation to the correct value.
IFAIL=5
The solution appears to be too close to 0 or 1 for accurate calculation. The value returned is 0 or 1 as appropriate.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

The series (2) is summed until a bound on the truncation error is less than TOL. See Farebrother (1984) for further discussion.

8 Parallelism and Performance

G01JCF is not threaded in any implementation.

9 Further Comments

None.

10 Example

The number of χ 2 variables is read along with their coefficients, degrees of freedom and noncentrality arguments. The lower tail probability is then computed and printed.

10.1 Program Text

Program Text (g01jcfe.f90)

10.2 Program Data

Program Data (g01jcfe.d)

10.3 Program Results

Program Results (g01jcfe.r)

G01 Chapter Contents
G01 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


G01JDF : NAG Library, Mark 26

G01 Chapter Contents
G01 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

G01JDF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

G01JDF calculates the lower tail probability for a linear combination of (central) χ 2 variables.

2 Specification

SUBROUTINE G01JDF ( METHOD, N, RLAM, D, C, PROB, WORK, IFAIL)
INTEGER | N, IFAIL
REAL (KIND=nag_wp) | RLAM(N), D, C, PROB, WORK(N+1)
CHARACTER(1) | METHOD

3 Description

Let u 1,u 2,…,un be independent Normal variables with mean zero and unit variance, so that u 12,u 22,…,un 2 have independent χ 2-distributions with unit degrees of freedom. G01JDF evaluates the probability that
λ 1 u 12+λ 2 u 22+⋯+λn un 2<d u 12+u 22+⋯+un 2+c.
If c=0.0 this is equivalent to the probability that
λ 1 u 12+λ 2 u 22+⋯+λn un 2 u 12+u 22+⋯+un 2 <d.
Alternatively let
λi*=λi-d,   ​ i= 1,2,…,n,
then G01JDF returns the probability that
λ 1*u 12+λ 2*u 22+⋯+λn*un 2<c.
Two methods are available. One due to Pan (1964) (see Farebrother (1980)) makes use of series approximations. The other method due to Imhof (1961) reduces the problem to a one-dimensional integral. If n≥6 then a non-adaptive method described in D01BDF is used to compute the value of the integral otherwise D01AJF is used.
Pan's procedure can only be used if the λi* are sufficiently distinct; G01JDF requires the λi* to be at least 1% distinct; see Section 9. If the λi* are at least 1% distinct and n≤60, then Pan's procedure is recommended; otherwise Imhof's procedure is recommended.

4 References

Farebrother R W (1980) Algorithm AS 153. Pan's procedure for the tail probabilities of the Durbin–Watson statistic Appl. Statist. 29 224–227
Imhof J P (1961) Computing the distribution of quadratic forms in Normal variables Biometrika 48 419–426
Pan Jie–Jian (1964) Distributions of the noncircular serial correlation coefficients Shuxue Jinzhan 7 328–337

5 Arguments

1:   METHOD – CHARACTER(1)Input
On entry: indicates whether Pan's, Imhof's or an appropriately selected procedure is to be used.
METHOD='P'
Pan's method is used.
METHOD='I'
Imhof's method is used.
METHOD='D'
Pan's method is used if λi*, for i=1,2,…,n are at least 1% distinct and n≤60; otherwise Imhof's method is used.
Constraint: METHOD='P', 'I' or 'D'.
2:   N – INTEGERInput
On entry: n, the number of independent standard Normal variates, (central χ 2 variates).
Constraint: N≥1.
3:   RLAM N – REAL (KIND=nag_wp) arrayInput
On entry: the weights, λi, for i=1,2,…,n, of the central χ 2 variables.
Constraint: RLAM i≠D for at least one i. If METHOD='P', then the λi* must be at least 1% distinct; see Section 9, for i=1,2,…,n.
4:   D – REAL (KIND=nag_wp)Input
On entry: d, the multiplier of the central χ 2 variables.
Constraint: D≥0.0.
5:   C – REAL (KIND=nag_wp)Input
On entry: c, the value of the constant.
6:   PROB – REAL (KIND=nag_wp)Output
On exit: the lower tail probability for the linear combination of central χ 2 variables.
7:   WORK N+1 – REAL (KIND=nag_wp) arrayWorkspace
8:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, | N<1,
or | D<0.0,
or | METHOD≠'P', 'I' or 'D'.
IFAIL=2
On entry, RLAM i=D for all values of i, for i=1,2,…,n.
IFAIL=3
On entry, METHOD='P' yet two successive values of the ordered λi*, for i=1,2,…,n, were not at least 1% distinct.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

On successful exit at least four decimal places of accuracy should be achieved.

8 Parallelism and Performance

G01JDF is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

Pan's procedure can only work if the λi* are sufficiently distinct. G01JDF uses the check wj-w j-1≥0.01×max wj,w j-1, where the wj are the ordered nonzero values of λi*.
For the situation when all the λi are positive G01JCF may be used. If the probabilities required are for the Durbin–Watson test, then the bounds for the probabilities are given by G01EPF.

10 Example

For n=10, the choice of method, values of c and d and the λi are input and the probabilities computed and printed.

10.1 Program Text

Program Text (g01jdfe.f90)

10.2 Program Data

Program Data (g01jdfe.d)

10.3 Program Results

Program Results (g01jdfe.r)

G01 Chapter Contents
G01 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


G01KAF : NAG Library, Mark 26

G01 Chapter Contents
G01 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

G01KAF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

G01KAF returns the value of the probability density function (PDF) for the Normal (Gaussian) distribution with mean μ and variance σ 2 at a point x.

2 Specification

FUNCTION G01KAF ( X, XMEAN, XSTD, IFAIL)
REAL (KIND=nag_wp) G01KAF
INTEGER | IFAIL
REAL (KIND=nag_wp) | X, XMEAN, XSTD

3 Description

The Normal distribution has probability density function (PDF)
f x = 1 σ ⁢ 2 π e -x-μ 2/2 σ 2 ,  σ>0 .

4 References

None.

5 Arguments

1:   X – REAL (KIND=nag_wp)Input
On entry: x, the value at which the PDF is to be evaluated.
2:   XMEAN – REAL (KIND=nag_wp)Input
On entry: μ, the mean of the Normal distribution.
3:   XSTD – REAL (KIND=nag_wp)Input
On entry: σ, the standard deviation of the Normal distribution.
Constraint: z<XSTD 2 π<1.0/z, where z=X02AMF, the safe range parameter.
4:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
If IFAIL≠0, then G01KAF returns 0.0.
IFAIL=1
On entry, XSTD=value.
Constraint: XSTD×2.0 π>U, where U is the safe range parameter as defined by X02AMF.
IFAIL=2
Computation abandoned owing to underflow of 1 σ×2 π.
IFAIL=3
Computation abandoned owing to an internal calculation overflowing.
This rarely occurs, and is the result of extreme values of the arguments X, XMEAN or XSTD.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

Not applicable.

8 Parallelism and Performance

G01KAF is not threaded in any implementation.

9 Further Comments

None.

10 Example

This example prints the value of the Normal distribution PDF at four different points X with differing XMEAN and XSTD.

10.1 Program Text

Program Text (g01kafe.f90)

10.2 Program Data

Program Data (g01kafe.d)

10.3 Program Results

Program Results (g01kafe.r)

GnuplotProduced by GNUPLOT 4.6 patchlevel 3 0 0.2 0.4 0.6 0.8 1 1.2 1.4 −3 −2 −1 0 1 2 3 y x Example Program Plots of the Gaussian Function (or Normal Distribution). μ=0, σ=0.3 μ=0, σ=1 μ=1, σ=0.6 gnuplot_plot_1 gnuplot_plot_2 gnuplot_plot_3
G01 Chapter Contents
G01 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


G01KFF : NAG Library, Mark 26

G01 Chapter Contents
G01 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

G01KFF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

G01KFF returns the value of the probability density function (PDF) for the gamma distribution with shape argument α and scale argument β at a point x.

2 Specification

FUNCTION G01KFF ( X, A, B, IFAIL)
REAL (KIND=nag_wp) G01KFF
INTEGER | IFAIL
REAL (KIND=nag_wp) | X, A, B

3 Description

The gamma distribution has PDF
f x= 1 βα Γ α x α-1e-x/β if ​x≥0;  α,β>0 f x=0 otherwise.
If 0.01≤x,α,β≤100 then an algorithm based directly on the gamma distribution's PDF is used. For values outside this range, the function is calculated via the Poisson distribution's PDF as described in Loader (2000) (see Section 9).

4 References

Loader C (2000) Fast and accurate computation of binomial probabilities (not yet published)

5 Arguments

1:   X – REAL (KIND=nag_wp)Input
On entry: x, the value at which the PDF is to be evaluated.
2:   A – REAL (KIND=nag_wp)Input
On entry: α, the shape argument of the gamma distribution.
Constraint: A>0.0.
3:   B – REAL (KIND=nag_wp)Input
On entry: β, the scale argument of the gamma distribution.
Constraints:
  • B>0.0;
  • XB<1 X02AMF.
4:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
If IFAIL≠0, then G01KFF returns 0.0.
IFAIL=1
On entry, A=value.
Constraint: A>0.0.
IFAIL=2
On entry, B=value.
Constraint: B>0.0.
IFAIL=3
Computation abandoned owing to overflow due to extreme parameter values.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

Not applicable.

8 Parallelism and Performance

G01KFF is not threaded in any implementation.

9 Further Comments

Due to the lack of a stable link to Loader (2000) paper, we give a brief overview of the method, as applied to the Poisson distribution. The Poisson distribution has a continuous mass function given by,
p x;λ = λx x! e-λ . (1)
The usual way of computing this quantity would be to take the logarithm and calculate,
log x;λ = x log⁡λ - log x! - λ .
For large x and λ, x log⁡λ and log x! are very large, of the same order of magnitude and when calculated have rounding errors. The subtraction of these two terms can therefore result in a number, many orders of magnitude smaller and hence we lose accuracy due to subtraction errors. For example for x=2×106 and λ=2×106, log⁡x!≈2.7×107 and log p x;λ=-8.17326744645834. But calculated with the method shown later we have log p x;λ=-8.1732674441334492. The difference between these two results suggests a loss of about 7 significant figures of precision.
Loader introduces an alternative way of expressing (1) based on the saddle point expansion,
log p x;λ = log p x;x - D x;λ , (2)
where D x;λ, the deviance for the Poisson distribution is given by,
D x;λ = log p x;x - log p x;λ , = λ D 0 x λ , (3)
and
D 0 ε = ε log⁡ε + 1 - ε .
For ε close to 1, D 0 ε can be evaluated through the series expansion
λ D 0 x λ = x-λ 2 x+λ + 2 x ∑ j=1 ∞ v 2 j+1 2 j+1 ,  where ​ v = x-λ x+λ ,
otherwise D 0 ε can be evaluated directly. In addition, Loader suggests evaluating log x! using the Stirling–De Moivre series,
log x! = 12 log⁡ 2 πx + x log x -x + δ x , (4)
where the error δ x is given by
δ x = 1 12 x - 1 360 x 3 + 1 1260 x 5 + O x-7 .
Finally log p x;λ can be evaluated by combining equations (1)–(4) to get,
p x;λ = 1 2 πx e - δ x - λ D 0 x/λ .

10 Example

This example prints the value of the gamma distribution PDF at six different points X with differing A and B.

10.1 Program Text

Program Text (g01kffe.f90)

10.2 Program Data

Program Data (g01kffe.d)

10.3 Program Results

Program Results (g01kffe.r)

GnuplotProduced by GNUPLOT 4.6 patchlevel 3 0 0.05 0.1 0.15 0.2 0.25 0.3 0 1 2 3 4 5 6 7 8 9 10 y x Example Program Plots of the Gamma Distribution α=2, β=2 α=9, β=0.5 gnuplot_plot_1 gnuplot_plot_2
G01 Chapter Contents
G01 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


G01KKF : NAG Library, Mark 26

G01 Chapter Contents
G01 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

G01KKF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

G01KKF returns a number of values of the probability density function (PDF), or its logarithm, for the gamma distribution.

2 Specification

SUBROUTINE G01KKF ( ILOG, LX, X, LA, A, LB, B, PDF, IVALID, IFAIL)
INTEGER | ILOG, LX, LA, LB, IVALID(*), IFAIL
REAL (KIND=nag_wp) | X(LX), A(LA), B(LB), PDF(*)

3 Description

The gamma distribution with shape parameter αi and scale parameter βi has PDF
f xi,αi,βi = 1 βi αi Γ αi xi αi-1 e -xi / βi if ​ xi ≥ 0 ;   αi , βi > 0 f xi,αi,βi=0 otherwise.
If 0.01≤xi,αi,βi≤100 then an algorithm based directly on the gamma distribution's PDF is used. For values outside this range, the function is calculated via the Poisson distribution's PDF as described in Loader (2000) (see Section 9).
The input arrays to this routine are designed to allow maximum flexibility in the supply of vector arguments by re-using elements of any arrays that are shorter than the total number of evaluations required. See Section 2.6 in the G01 Chapter Introduction for further information.

4 References

Loader C (2000) Fast and accurate computation of binomial probabilities (not yet published)

5 Arguments

1:   ILOG – INTEGERInput
On entry: the value of ILOG determines whether the logarithmic value is returned in PDF.
ILOG=0
f xi,αi,βi, the probability density function is returned.
ILOG=1
log f xi,αi,βi, the logarithm of the probability density function is returned.
Constraint: ILOG=0 or 1.
2:   LX – INTEGERInput
On entry: the length of the array X.
Constraint: LX>0.
3:   X LX – REAL (KIND=nag_wp) arrayInput
On entry: xi, the values at which the PDF is to be evaluated with xi=X j, j=i-1 mod LX+1, for i=1,2,…,max LX,LA,LB.
4:   LA – INTEGERInput
On entry: the length of the array A.
Constraint: LA>0.
5:   A LA – REAL (KIND=nag_wp) arrayInput
On entry: αi, the shape parameter with αi=A j, j=i-1 mod LA+1.
Constraint: A j>0.0, for j=1,2,…,LA.
6:   LB – INTEGERInput
On entry: the length of the array B.
Constraint: LB>0.
7:   B LB – REAL (KIND=nag_wp) arrayInput
On entry: βi, the scale parameter with βi=B j, j=i-1 mod LB+1.
Constraint: B j>0.0, for j=1,2,…,LB.
8:   PDF* – REAL (KIND=nag_wp) arrayOutput
Note: the dimension of the array PDF must be at least max LX,LA,LB.
On exit: f xi,αi,βi or log f xi,αi,βi.
9:   IVALID* – INTEGER arrayOutput
Note: the dimension of the array IVALID must be at least max LX,LA,LB.
On exit: IVALID i indicates any errors with the input arguments, with
IVALID i=0
No error.
IVALID i=1
αi≤0.0.
IVALID i=2
βi≤0.0.
IVALID i=3
xiβi overflows, the value returned should be a reasonable approximation.
10:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, at least one value of X, A or B was invalid.
Check IVALID for more information.
IFAIL=2
On entry, ILOG=value.
Constraint: ILOG=0 or 1.
IFAIL=3
On entry, array size=value.
Constraint: LX>0.
IFAIL=4
On entry, array size=value.
Constraint: LA>0.
IFAIL=5
On entry, array size=value.
Constraint: LB>0.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

Not applicable.

8 Parallelism and Performance

G01KKF is not threaded in any implementation.

9 Further Comments

Due to the lack of a stable link to Loader (2000) paper, we give a brief overview of the method, as applied to the Poisson distribution. The Poisson distribution has a continuous mass function given by,
p x;λ = λx x! e-λ . (1)
The usual way of computing this quantity would be to take the logarithm and calculate,
log p x;λ = x log⁡λ - log x! - λ .
For large x and λ, x log⁡λ and log x! are very large, of the same order of magnitude and when calculated have rounding errors. The subtraction of these two terms can therefore result in a number, many orders of magnitude smaller and hence we lose accuracy due to subtraction errors. For example for x=2×106 and λ=2×106, log⁡x!≈2.7×107 and log p x;λ=-8.17326744645834. But calculated with the method shown later we have log p x;λ=-8.1732674441334492. The difference between these two results suggests a loss of about 7 significant figures of precision.
Loader introduces an alternative way of expressing (1) based on the saddle point expansion,
log p x;λ = log p x;x - D x;λ , (2)
where D x;λ, the deviance for the Poisson distribution is given by,
D x;λ = log p x;x - log p x;λ , = λ D 0 x λ , (3)
and
D 0 ε = ε log⁡ε + 1 - ε .
For ε close to 1, D 0 ε can be evaluated through the series expansion
λ D 0 x λ = x-λ 2 x+λ + 2 x ∑ j=1 ∞ v 2 j+1 2 j+1 ,  where ​ v = x-λ x+λ ,
otherwise D 0 ε can be evaluated directly. In addition, Loader suggests evaluating log x! using the Stirling–De Moivre series,
log x! = 12 log⁡ 2 πx + x log x -x + δ x , (4)
where the error δ x is given by
δ x = 1 12 x - 1 360 x 3 + 1 1260 x 5 + O x-7 .
Finally log p x;λ can be evaluated by combining equations (1)–(4) to get,
p x;λ = 1 2 πx e - δ x - λ D 0 x/λ .

10 Example

This example prints the value of the gamma distribution PDF at six different points xi with differing αi and βi.

10.1 Program Text

Program Text (g01kkfe.f90)

10.2 Program Data

Program Data (g01kkfe.d)

10.3 Program Results

Program Results (g01kkfe.r)

GnuplotProduced by GNUPLOT 4.6 patchlevel 3 0 0.05 0.1 0.15 0.2 0.25 0.3 0 1 2 3 4 5 6 7 8 9 10 y x Example Program Plots of the Gamma Distribution α=2, β=2 α=9, β=0.5 gnuplot_plot_1 gnuplot_plot_2
G01 Chapter Contents
G01 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


G01KQF : NAG Library, Mark 26

G01 Chapter Contents
G01 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

G01KQF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

G01KQF returns a number of values of the probability density function (PDF), or its logarithm, for the Normal (Gaussian) distributions.

2 Specification

SUBROUTINE G01KQF ( ILOG, LX, X, LXMU, XMU, LXSTD, XSTD, PDF, IVALID, IFAIL)
INTEGER | ILOG, LX, LXMU, LXSTD, IVALID(*), IFAIL
REAL (KIND=nag_wp) | X(LX), XMU(LXMU), XSTD(LXSTD), PDF(*)

3 Description

The Normal distribution with mean μi, variance σi 2; has probability density function (PDF)
f xi,μi,σi = 1 σi⁢2 π e -xi-μi 2/2 σi 2 ,  σi>0 .
The input arrays to this routine are designed to allow maximum flexibility in the supply of vector arguments by re-using elements of any arrays that are shorter than the total number of evaluations required. See Section 2.6 in the G01 Chapter Introduction for further information.

4 References

None.

5 Arguments

1:   ILOG – INTEGERInput
On entry: the value of ILOG determines whether the logarithmic value is returned in PDF.
ILOG=0
f xi,μi,σi, the probability density function is returned.
ILOG=1
log f xi,μi,σi, the logarithm of the probability density function is returned.
Constraint: ILOG=0 or 1.
2:   LX – INTEGERInput
On entry: the length of the array X.
Constraint: LX>0.
3:   X LX – REAL (KIND=nag_wp) arrayInput
On entry: xi, the values at which the PDF is to be evaluated with xi=X j, j=i-1 mod LX+1, for i=1,2,…,max LX,LXSTD,LXMU.
4:   LXMU – INTEGERInput
On entry: the length of the array XMU.
Constraint: LXMU>0.
5:   XMU LXMU – REAL (KIND=nag_wp) arrayInput
On entry: μi, the means with μi=XMU j, j=i-1 mod LXMU+1.
6:   LXSTD – INTEGERInput
On entry: the length of the array XSTD.
Constraint: LXSTD>0.
7:   XSTD LXSTD – REAL (KIND=nag_wp) arrayInput
On entry: σi, the standard deviations with σi=XSTD j, j=i-1 mod LXSTD+1.
Constraint: XSTD j≥0.0, for j=1,2,…,LXSTD.
8:   PDF* – REAL (KIND=nag_wp) arrayOutput
Note: the dimension of the array PDF must be at least max LX,LXSTD,LXMU.
On exit: f xi,μi,σi or log f xi,μi,σi.
9:   IVALID* – INTEGER arrayOutput
Note: the dimension of the array IVALID must be at least max LX,LXSTD,LXMU.
On exit: IVALID i indicates any errors with the input arguments, with
IVALID i=0
No error.
IVALID i=1
σi<0.
10:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, at least one value of XSTD was invalid.
Check IVALID for more information.
IFAIL=2
On entry, ILOG=value.
Constraint: ILOG=0 or 1.
IFAIL=3
On entry, array size=value.
Constraint: LX>0.
IFAIL=4
On entry, array size=value.
Constraint: LXMU>0.
IFAIL=5
On entry, array size=value.
Constraint: LXSTD>0.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

Not applicable.

8 Parallelism and Performance

G01KQF is not threaded in any implementation.

9 Further Comments

None.

10 Example

This example prints the value of the Normal distribution PDF at four different points xi with differing μi and σi.

10.1 Program Text

Program Text (g01kqfe.f90)

10.2 Program Data

Program Data (g01kqfe.d)

10.3 Program Results

Program Results (g01kqfe.r)

GnuplotProduced by GNUPLOT 4.6 patchlevel 3 0 0.2 0.4 0.6 0.8 1 1.2 1.4 −3 −2 −1 0 1 2 3 y x Example Program Plots of the Gaussian Function (or Normal Distribution). μ=0, σ=0.3 μ=0, σ=1 μ=1, σ=0.6 gnuplot_plot_1 gnuplot_plot_2 gnuplot_plot_3
G01 Chapter Contents
G01 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


G01LBF : NAG Library, Mark 26

G01 Chapter Contents
G01 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

G01LBF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

G01LBF returns a number of values of the probability density function (PDF), or its logarithm, for the multivariate Normal (Gaussian) distribution.

2 Specification

SUBROUTINE G01LBF ( ILOG, K, N, X, LDX, XMU, IULD, SIG, LDSIG, PDF, RANK, IFAIL)
INTEGER | ILOG, K, N, LDX, IULD, LDSIG, RANK, IFAIL
REAL (KIND=nag_wp) | X(LDX,*), XMU(N), SIG(LDSIG,*), PDF(K)

3 Description

The probability density function, f X:μ,Σ of an n-dimensional multivariate Normal distribution with mean vector μ and n by n variance-covariance matrix Σ, is given by
f X:μ,Σ = 2⁢π n ⁢ Σ -1/2 ⁢ exp -12 ⁢ X-μ T ⁢ Σ-1 ⁢ X-μ .
If the variance-covariance matrix, Σ, is not of full rank then the probability density function, is calculated as
f X:μ,Σ = 2⁢π r ⁢ pdet Σ -1/2 ⁢ exp -12 ⁢ X-μ T ⁢ Σ- ⁢ X-μ
where pdet Σ is the pseudo-determinant, Σ- a generalized inverse of Σ and r its rank.
G01LBF evaluates the PDF at k points with a single call.

4 References

None.

5 Arguments

1:   ILOG – INTEGERInput
On entry: the value of ILOG determines whether the logarithmic value is returned in PDF.
ILOG=0
f X:μ,Σ, the probability density function is returned.
ILOG=1
log f X:μ,Σ, the logarithm of the probability density function is returned.
Constraint: ILOG=0 or 1.
2:   K – INTEGERInput
On entry: k, the number of points the PDF is to be evaluated at.
Constraint: K≥0.
3:   N – INTEGERInput
On entry: n, the number of dimensions.
Constraint: N≥2.
4:   X LDX* – REAL (KIND=nag_wp) arrayInput
Note: the second dimension of the array X must be at least K.
On entry: X, the matrix of k points at which to evaluate the probability density function, with the ith dimension for the jth point held in X ij.
5:   LDX – INTEGERInput
On entry: the first dimension of the array X as declared in the (sub)program from which G01LBF is called.
Constraint: LDX≥N.
6:   XMU N – REAL (KIND=nag_wp) arrayInput
On entry: μ, the mean vector of the multivariate Normal distribution.
7:   IULD – INTEGERInput
On entry: indicates the form of Σ and how it is stored in SIG.
IULD=1
SIG holds the lower triangular portion of Σ.
IULD=2
SIG holds the upper triangular portion of Σ.
IULD=3
Σ is a diagonal matrix and SIG only holds the diagonal elements.
IULD=4
SIG holds the lower Cholesky decomposition, L such that L⁢LT=Σ.
IULD=5
SIG holds the upper Cholesky decomposition, U such that UT⁢U=Σ.
Constraint: IULD=1, 2, 3, 4 or 5.
8:   SIG LDSIG* – REAL (KIND=nag_wp) arrayInput
Note: the second dimension of the array SIG must be at least N.
On entry: information defining the variance-covariance matrix, Σ.
IULD=1 or 2
SIG must hold the lower or upper portion of Σ, with Σ ij held in SIG ij. The supplied variance-covariance matrix must be positive semidefinite.
IULD=3
Σ is a diagonal matrix and the ith diagonal element, Σ ii, must be held in SIG 1 i
IULD=4 or 5
SIG must hold L or U, the lower or upper Cholesky decomposition of Σ, with L ij or U ij held in SIG ij, depending on the value of IULD. No check is made that L⁢LT or UT⁢U is a valid variance-covariance matrix. The diagonal elements of the supplied L or U must be greater than zero
9:   LDSIG – INTEGERInput
On entry: the first dimension of the array SIG as declared in the (sub)program from which G01LBF is called.
Constraints:
  • if IULD=3, LDSIG≥1;
  • otherwise LDSIG≥N.
10:   PDF K – REAL (KIND=nag_wp) arrayOutput
On exit: f X:μ,Σ or log f X:μ,Σ depending on the value of ILOG.
11:   RANK – INTEGEROutput
On exit: r, rank of Σ.
12:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=11
On entry, ILOG=value.
Constraint: ILOG=0 or 1.
IFAIL=21
On entry, K=value.
Constraint: K≥0.
IFAIL=31
On entry, N=value.
Constraint: N≥2.
IFAIL=51
On entry, LDX=value and N=value.
Constraint: LDX≥N.
IFAIL=71
On entry, IULD=value.
Constraint: IULD=1, 2, 3, 4 or 5.
IFAIL=81
On entry, Σ is not positive semidefinite.
IFAIL=82
On entry, at least one diagonal element of Σ is less than or equal to 0.
IFAIL=83
On entry, Σ is not positive definite and eigenvalue decomposition failed.
IFAIL=91
On entry, LDSIG=value.
Constraint: if IULD=3, LDSIG≥1.
IFAIL=92
On entry, LDSIG=value.
Constraint: if IULD≠3, LDSIG≥N.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

Not applicable.

8 Parallelism and Performance

G01LBF is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
G01LBF makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

None.

10 Example

This example prints the value of the multivariate Normal PDF at a number of different points.

10.1 Program Text

Program Text (g01lbfe.f90)

10.2 Program Data

Program Data (g01lbfe.d)

10.3 Program Results

Program Results (g01lbfe.r)

G01 Chapter Contents
G01 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


G01MBF : NAG Library, Mark 26

G01 Chapter Contents
G01 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

G01MBF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

G01MBF returns the reciprocal of Mills' Ratio, via the routine name.

2 Specification

FUNCTION G01MBF ( X)
REAL (KIND=nag_wp) G01MBF
REAL (KIND=nag_wp) X

3 Description

G01MBF calculates the reciprocal of Mills' Ratio, the hazard rate, λ x, for the standard Normal distribution. It is defined as the ratio of the ordinate to the upper tail area of the standard Normal distribution, that is,
λ x=Z x Q x =1 2 π e-x 2/2 1 2 π∫x∞e-t 2/2 dt .
The calculation is based on a Chebyshev expansion as described in S15AGF.

4 References

Gross A J and Clark V A (1975) Survival Distributions: Reliability Applications in the Biomedical Sciences Wiley

5 Arguments

1:   X – REAL (KIND=nag_wp)Input
On entry: x, the argument of the reciprocal of Mills' Ratio.

6 Error Indicators and Warnings

None.

7 Accuracy

In the left-hand tail, x<0.0, if 12 e-1/2 x 2≤ the safe range argument (X02AMF), then 0.0 is returned, which is close to the true value.
The relative accuracy is bounded by the effective machine precision. See S15AGF for further discussion.

8 Parallelism and Performance

G01MBF is not threaded in any implementation.

9 Further Comments

If, before entry, x is not a standard Normal variable, it has to be standardized, and on exit, G01MBF has to be divided by the standard deviation. That is, if the Normal distribution has mean μ and variance σ 2, then its hazard rate, λ x;μ,σ 2, is given by
λ x;μ,σ 2=λ x-μ/σ/σ.

10 Example

The hazard rate is evaluated at different values of x for Normal distributions with different means and variances. The results are then printed.

10.1 Program Text

Program Text (g01mbfe.f90)

10.2 Program Data

Program Data (g01mbfe.d)

10.3 Program Results

Program Results (g01mbfe.r)

G01 Chapter Contents
G01 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


G01MTF : NAG Library, Mark 26

G01 Chapter Contents
G01 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

G01MTF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

G01MTF returns the value of the Landau density function ϕ λ, via the routine name.

2 Specification

FUNCTION G01MTF ( X)
REAL (KIND=nag_wp) G01MTF
REAL (KIND=nag_wp) X

3 Description

G01MTF evaluates an approximation to the Landau density function ϕ λ given by
ϕ λ=1 2 πi ∫c-i∞ c+i∞exp λs+s ln⁡sds,
where c is an arbitrary real constant, using piecewise approximation by rational functions. Further details can be found in Kölbig and Schorr (1984).
To obtain the value of ϕ′λ, G01RTF can be used.

4 References

Kölbig K S and Schorr B (1984) A program package for the Landau distribution Comp. Phys. Comm. 31 97–111

5 Arguments

1:   X – REAL (KIND=nag_wp)Input
On entry: the argument λ of the function.

6 Error Indicators and Warnings

None.

7 Accuracy

At least 7 significant digits are usually correct, but occasionally only 6. Such accuracy is normally considered to be adequate for applications in experimental physics.
Because of the asymptotic behaviour of ϕ λ, which is of the order of exp-exp-λ, underflow may occur on some machines when λ is moderately large and negative.

8 Parallelism and Performance

G01MTF is not threaded in any implementation.

9 Further Comments

None.

10 Example

This example evaluates ϕ λ at λ=0.5, and prints the results.

10.1 Program Text

Program Text (g01mtfe.f90)

10.2 Program Data

Program Data (g01mtfe.d)

10.3 Program Results

Program Results (g01mtfe.r)

G01 Chapter Contents
G01 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


G01MUF : NAG Library, Mark 26

G01 Chapter Contents
G01 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

G01MUF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

G01MUF returns the value of the Vavilov density function ϕV λ;κ,β 2, via the routine name.
It is intended to be used after a call to G01ZUF.

2 Specification

FUNCTION G01MUF ( X, RCOMM, IFAIL)
REAL (KIND=nag_wp) G01MUF
INTEGER | IFAIL
REAL (KIND=nag_wp) | X, RCOMM(322)

3 Description

G01MUF evaluates an approximation to the Vavilov density function ϕV λ;κ,β 2 given by
ϕV λ;κ,β 2=1 2 πi ∫c-i∞ c+i∞e λs f s;κ,β 2 ds,
where κ>0 and 0≤β 2≤1, c is an arbitrary real constant and
f s;κ,β 2=C κ,β 2 exp s ln⁡κ+s+κ β 2 ln sκ+E 1 sκ -κ exp-sκ .
E 1 x=∫0 x t-1 1-e-t dt is the exponential integral, C κ,β 2=exp κ 1+γ β 2 and γ is Euler's constant.
The method used is based on Fourier expansions. Further details can be found in Schorr (1974).
For values of κ≤0.01, the Vavilov distribution can be replaced by the Landau distribution since λV=λL-ln⁡κ/κ. For values of κ≥10, the Vavilov distribution can be replaced by a Gaussian distribution with mean μ=γ-1-β 2-ln⁡κ and variance σ 2=2-β 2/2 κ.

4 References

Schorr B (1974) Programs for the Landau and the Vavilov distributions and the corresponding random numbers Comp. Phys. Comm. 7 215–224

5 Arguments

1:   X – REAL (KIND=nag_wp)Input
On entry: the argument λ of the function.
2:   RCOMM 322 – REAL (KIND=nag_wp) arrayCommunication Array
On entry: this must be the same argument RCOMM as returned by a previous call to G01ZUF.
3:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
Either the initialization routine has not been called prior to the first call of this routine or a communication array has become corrupted.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

At least five significant digits are usually correct.

8 Parallelism and Performance

G01MUF is not threaded in any implementation.

9 Further Comments

G01MUF can be called repeatedly with different values of λ provided that the values of κ and β 2 remain unchanged between calls. Otherwise, G01ZUF must be called again. This is illustrated in Section 10.

10 Example

This example evaluates ϕV λ;κ,β 2 at λ=2.5, κ=0.4 and β 2=0.1, and prints the results.

10.1 Program Text

Program Text (g01mufe.f90)

10.2 Program Data

Program Data (g01mufe.d)

10.3 Program Results

Program Results (g01mufe.r)

G01 Chapter Contents
G01 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


G01NAF : NAG Library, Mark 26

G01 Chapter Contents
G01 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

G01NAF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

G01NAF computes the cumulants and moments of quadratic forms in Normal variates.

2 Specification

SUBROUTINE G01NAF ( MOM, MEAN, N, A, LDA, EMU, SIGMA, LDSIG, L, RKUM, RMOM, WK, IFAIL)
INTEGER | N, LDA, LDSIG, L, IFAIL
REAL (KIND=nag_wp) | A(LDA,N), EMU(*), SIGMA(LDSIG,N), RKUM(L), RMOM(*), WK(3*N*(N+1)/2+N)
CHARACTER(1) | MOM, MEAN

3 Description

Let x have an n-dimensional multivariate Normal distribution with mean μ and variance-covariance matrix Σ. Then for a symmetric matrix A, G01NAF computes up to the first 12 moments and cumulants of the quadratic form Q=xT Ax. The sth moment (about the origin) is defined as
E Qs,
where E denotes expectation. The sth moment of Q can also be found as the coefficient of ts/s! in the expansion of E e Qt. The sth cumulant is defined as the coefficient of ts/s! in the expansion of log E e Qt.
The routine is based on the routine CUM written by Magnus and Pesaran (1993a) and based on the theory given by Magnus (1978), Magnus (1979) and Magnus (1986).

4 References

Magnus J R (1978) The moments of products of quadratic forms in Normal variables Statist. Neerlandica 32 201–210
Magnus J R (1979) The expectation of products of quadratic forms in Normal variables: the practice Statist. Neerlandica 33 131–136
Magnus J R (1986) The exact moments of a ratio of quadratic forms in Normal variables Ann. Économ. Statist. 4 95–109
Magnus J R and Pesaran B (1993a) The evaluation of cumulants and moments of quadratic forms in Normal variables (CUM): Technical description Comput. Statist. 8 39–45
Magnus J R and Pesaran B (1993b) The evaluation of moments of quadratic forms and ratios of quadratic forms in Normal variables: Background, motivation and examples Comput. Statist. 8 47–55

5 Arguments

1:   MOM – CHARACTER(1)Input
On entry: indicates if moments are computed in addition to cumulants.
MOM='C'
Only cumulants are computed.
MOM='M'
Moments are computed in addition to cumulants.
Constraint: MOM='C' or 'M'.
2:   MEAN – CHARACTER(1)Input
On entry: indicates if the mean, μ, is zero.
MEAN='Z'
μ is zero.
MEAN='M'
The value of μ is supplied in EMU.
Constraint: MEAN='Z' or 'M'.
3:   N – INTEGERInput
On entry: n, the dimension of the quadratic form.
Constraint: N>1.
4:   A LDAN – REAL (KIND=nag_wp) arrayInput
On entry: the n by n symmetric matrix A. Only the lower triangle is referenced.
5:   LDA – INTEGERInput
On entry: the first dimension of the array A as declared in the (sub)program from which G01NAF is called.
Constraint: LDA≥N.
6:   EMU* – REAL (KIND=nag_wp) arrayInput
Note: the dimension of the array EMU must be at least N if MEAN='M', and at least 1 otherwise.
On entry: if MEAN='M', EMU must contain the n elements of the vector μ.
If MEAN='Z', EMU is not referenced.
7:   SIGMA LDSIGN – REAL (KIND=nag_wp) arrayInput
On entry: the n by n variance-covariance matrix Σ. Only the lower triangle is referenced.
Constraint: the matrix Σ must be positive definite.
8:   LDSIG – INTEGERInput
On entry: the first dimension of the array SIGMA as declared in the (sub)program from which G01NAF is called.
Constraint: LDSIG≥N.
9:   L – INTEGERInput
On entry: the required number of cumulants, and moments if specified.
Constraint: 1≤L≤12.
10:   RKUM L – REAL (KIND=nag_wp) arrayOutput
On exit: the L cumulants of the quadratic form.
11:   RMOM* – REAL (KIND=nag_wp) arrayOutput
Note: the dimension of the array RMOM must be at least L if MOM='M', and at least 1 otherwise.
On exit: if MOM='M', the L moments of the quadratic form.
12:   WK 3×N×N+1/2+N – REAL (KIND=nag_wp) arrayWorkspace
13:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, | N≤1,
or | L<1,
or | L>12,
or | LDA<N,
or | LDSIG<N,
or | MOM≠'C' or 'M',
or | MEAN≠'M' or 'Z'.
IFAIL=2
On entry, the matrix Σ is not positive definite.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

In a range of tests the accuracy was found to be a modest multiple of machine precision. See Magnus and Pesaran (1993b).

8 Parallelism and Performance

G01NAF makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

None.

10 Example

This example is given by Magnus and Pesaran (1993b) and considers the simple autoregression
yt=β y t-1+ut,   t=1,2,…n,
where ut is a sequence of independent Normal variables with mean zero and variance one, and y 0 is known. The moments of the quadratic form
Q=∑t=2 n yty t-1
are computed using G01NAF. The matrix A is given by:
A i+1,i = 12,  i=1,2,…n-1; A i,j = 0,   otherwise.
The value of Σ can be computed using the relationships
var yt=β 2 var y t-1+1
and
cov yty t+k=β cov yty t+k- 1
for k≥0 and var y 1=1.
The values of β, y 0, n, and the number of moments required are read in and the moments and cumulants printed.

10.1 Program Text

Program Text (g01nafe.f90)

10.2 Program Data

Program Data (g01nafe.d)

10.3 Program Results

Program Results (g01nafe.r)

G01 Chapter Contents
G01 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


G01NBF : NAG Library, Mark 26

G01 Chapter Contents
G01 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

G01NBF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

G01NBF computes the moments of ratios of quadratic forms in Normal variables and related statistics.

2 Specification

SUBROUTINE G01NBF ( CASE, MEAN, N, A, LDA, B, LDB, C, LDC, ELA, EMU, SIGMA, LDSIG, L1, L2, LMAX, RMOM, ABSERR, EPS, WK, IFAIL)
INTEGER | N, LDA, LDB, LDC, LDSIG, L1, L2, LMAX, IFAIL
REAL (KIND=nag_wp) | A(LDA,N), B(LDB,N), C(LDC,*), ELA(*), EMU(*), SIGMA(LDSIG,N), RMOM(L2-L1+1), ABSERR, EPS, WK(3*N*N+(8+L2)*N)
CHARACTER(1) | CASE, MEAN

3 Description

Let x have an n-dimensional multivariate Normal distribution with mean μ and variance-covariance matrix Σ. Then for a symmetric matrix A and symmetric positive semidefinite matrix B, G01NBF computes a subset, l 1 to l 2, of the first 12 moments of the ratio of quadratic forms
R=xT Ax/xT Bx.
The sth moment (about the origin) is defined as
E Rs, (1)
where E denotes the expectation. Alternatively, this routine will compute the following expectations:
E Rs aT x (2)
and
E Rs xT Cx, (3)
where a is a vector of length n and C is a n by n symmetric matrix, if they exist. In the case of (2) the moments are zero if μ=0.
The conditions of theorems 1, 2 and 3 of Magnus (1986) and Magnus (1990) are used to check for the existence of the moments. If all the requested moments do not exist, the computations are carried out for those moments that are requested up to the maximum that exist, lMAX.
This routine is based on the routine QRMOM written by Magnus and Pesaran (1993a) and based on the theory given by Magnus (1986) and Magnus (1990). The computation of the moments requires first the computation of the eigenvectors of the matrix LT BL, where L LT=Σ. The matrix LT BL must be positive semidefinite and not null. Given the eigenvectors of this matrix, a function which has to be integrated over the range zero to infinity can be computed. This integration is performed using D01AMF.

4 References

Magnus J R (1986) The exact moments of a ratio of quadratic forms in Normal variables Ann. Économ. Statist. 4 95–109
Magnus J R (1990) On certain moments relating to quadratic forms in Normal variables: Further results Sankhyā, Ser. B 52 1–13
Magnus J R and Pesaran B (1993a) The evaluation of cumulants and moments of quadratic forms in Normal variables (CUM): Technical description Comput. Statist. 8 39–45
Magnus J R and Pesaran B (1993b) The evaluation of moments of quadratic forms and ratios of quadratic forms in Normal variables: Background, motivation and examples Comput. Statist. 8 47–55

5 Arguments

1:   CASE – CHARACTER(1)Input
On entry: indicates the moments of which function are to be computed.
CASE='R' (Ratio)
E Rs is computed.
CASE='L' (Linear with ratio)
E Rs aT x is computed.
CASE='Q' (Quadratic with ratio)
E Rs xT Cx is computed.
Constraint: CASE='R', 'L' or 'Q'.
2:   MEAN – CHARACTER(1)Input
On entry: indicates if the mean, μ, is zero.
MEAN='Z'
μ is zero.
MEAN='M'
The value of μ is supplied in EMU.
Constraint: MEAN='Z' or 'M'.
3:   N – INTEGERInput
On entry: n, the dimension of the quadratic form.
Constraint: N>1.
4:   A LDAN – REAL (KIND=nag_wp) arrayInput
On entry: the n by n symmetric matrix A. Only the lower triangle is referenced.
5:   LDA – INTEGERInput
On entry: the first dimension of the array A as declared in the (sub)program from which G01NBF is called.
Constraint: LDA≥N.
6:   B LDBN – REAL (KIND=nag_wp) arrayInput
On entry: the n by n positive semidefinite symmetric matrix B. Only the lower triangle is referenced.
Constraint: the matrix B must be positive semidefinite.
7:   LDB – INTEGERInput
On entry: the first dimension of the array B as declared in the (sub)program from which G01NBF is called.
Constraint: LDB≥N.
8:   C LDC* – REAL (KIND=nag_wp) arrayInput
Note: the second dimension of the array C must be at least N if CASE='Q', and at least 1 otherwise.
On entry: if CASE='Q', C must contain the n by n symmetric matrix C; only the lower triangle is referenced.
If CASE≠'Q', C is not referenced.
9:   LDC – INTEGERInput
On entry: the first dimension of the array C as declared in the (sub)program from which G01NBF is called.
Constraints:
  • if CASE='Q', LDC≥N;
  • otherwise LDC≥1.
10:   ELA* – REAL (KIND=nag_wp) arrayInput
Note: the dimension of the array ELA must be at least N if CASE='L', and at least 1 otherwise.
On entry: if CASE='L', ELA must contain the vector a of length n, otherwise ELA is not referenced.
11:   EMU* – REAL (KIND=nag_wp) arrayInput
Note: the dimension of the array EMU must be at least N if MEAN='M', and at least 1 otherwise.
On entry: if MEAN='M', EMU must contain the n elements of the vector μ.
If MEAN='Z', EMU is not referenced.
12:   SIGMA LDSIGN – REAL (KIND=nag_wp) arrayInput
On entry: the n by n variance-covariance matrix Σ. Only the lower triangle is referenced.
Constraint: the matrix Σ must be positive definite.
13:   LDSIG – INTEGERInput
On entry: the first dimension of the array SIGMA as declared in the (sub)program from which G01NBF is called.
Constraint: LDSIG≥N.
14:   L1 – INTEGERInput
On entry: the first moment to be computed, l 1.
Constraint: 0<L1≤L2.
15:   L2 – INTEGERInput
On entry: the last moment to be computed, l 2.
Constraint: L1≤L2≤12.
16:   LMAX – INTEGEROutput
On exit: the highest moment computed, lMAX. This will be l 2 if IFAIL=0 on exit.
17:   RMOM L2-L1+1 – REAL (KIND=nag_wp) arrayOutput
On exit: the l 1 to lMAX moments.
18:   ABSERR – REAL (KIND=nag_wp)Output
On exit: the estimated maximum absolute error in any computed moment.
19:   EPS – REAL (KIND=nag_wp)Input
On entry: the relative accuracy required for the moments, this value is also used in the checks for the existence of the moments.
If EPS=0.0, a value of ε where ε is the machine precision used.
Constraint: EPS=0.0 or EPS≥machine precision.
20:   WK 3×N×N+8+L2×N – REAL (KIND=nag_wp) arrayWorkspace
21:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, because for this routine the values of the output arguments may be useful even if IFAIL≠0 on exit, the recommended value is -1. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Note: G01NBF may return useful information for one or more of the following detected errors or warnings.
Errors or warnings detected by the routine:
IFAIL=1
On entry, | N≤1,
or | LDA<N,
or | LDB<N,
or | LDSIG<N,
or | CASE='Q' and LDC<N,
or | CASE≠'Q' and LDC<1,
or | L1<1,
or | L1>L2,
or | L2>12,
or | CASE≠'R', 'L' or 'Q',
or | MEAN≠'M' or 'Z',
or | EPS≠0.0 and EPS<machine precision.
IFAIL=2
On entry, | Σ is not positive definite,
or | B is not positive semidefinite or is null.
IFAIL=3
None of the required moments can be computed.
IFAIL=4
The matrix LT BL is not positive semidefinite or is null.
IFAIL=5
The computation to compute the eigenvalues required in the calculation of moments has failed to converge: this is an unlikely error exit.
IFAIL=6
Only some of the required moments have been computed, the highest is given by LMAX.
IFAIL=7
The required accuracy has not been achieved in the integration. An estimate of the accuracy is returned in ABSERR.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

The relative accuracy is specified by EPS and an estimate of the maximum absolute error for all computed moments is returned in ABSERR.

8 Parallelism and Performance

G01NBF makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

None.

10 Example

This example is given by Magnus and Pesaran (1993b) and considers the simple autoregression:
yt=β y t-1+ut,  t=1,2,…,n,
where ut is a sequence of independent Normal variables with mean zero and variance one, and y 0 is known. The least squares estimate of β, β^, is given by
β^=∑t=2 n yty t-1 ∑t=2 n yt 2 .
Thus β^ can be written as a ratio of quadratic forms and its moments computed using G01NBF. The matrix A is given by
A i+1,i=12, i=1,2,…n-1; A i,j=0, otherwise,
and the matrix B is given by
B i,i=1, i=1,2,…n-1; B i,j=0, otherwise.
The value of Σ can be computed using the relationships
var yt=β 2 var y t-1+1
and
cov yty t+k=β cov yty t+k- 1
for k≥0 and var y 1=1.
The values of β, y 0, n, and the number of moments required are read in and the moments computed and printed.

10.1 Program Text

Program Text (g01nbfe.f90)

10.2 Program Data

Program Data (g01nbfe.d)

10.3 Program Results

Program Results (g01nbfe.r)

G01 Chapter Contents
G01 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


G01PTF : NAG Library, Mark 26

G01 Chapter Contents
G01 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

G01PTF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

G01PTF returns the value of the first moment Φ 1 x of the Landau density function, via the routine name.

2 Specification

FUNCTION G01PTF ( X)
REAL (KIND=nag_wp) G01PTF
REAL (KIND=nag_wp) X

3 Description

G01PTF evaluates an approximation to the first moment Φ 1 x of the Landau density function given by
Φ 1 x=1 Φ x ∫-∞x λϕ λ dλ,
where ϕ λ is described in G01MTF, using piecewise approximation by rational functions. Further details can be found in Kölbig and Schorr (1984).
To obtain the value of Φ 2 x, G01QTF can be used.

4 References

Kölbig K S and Schorr B (1984) A program package for the Landau distribution Comp. Phys. Comm. 31 97–111

5 Arguments

1:   X – REAL (KIND=nag_wp)Input
On entry: the argument x of the function.

6 Error Indicators and Warnings

None.

7 Accuracy

At least 7 significant digits are usually correct, but occasionally only 6. Such accuracy is normally considered to be adequate for applications in experimental physics.

8 Parallelism and Performance

G01PTF is not threaded in any implementation.

9 Further Comments

None.

10 Example

This example evaluates Φ 1 x at x=0.5, and prints the results.

10.1 Program Text

Program Text (g01ptfe.f90)

10.2 Program Data

Program Data (g01ptfe.d)

10.3 Program Results

Program Results (g01ptfe.r)

G01 Chapter Contents
G01 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


G01QTF : NAG Library, Mark 26

G01 Chapter Contents
G01 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

G01QTF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

G01QTF returns the value of the second moment Φ 2 x of the Landau density function, via the routine name.

2 Specification

FUNCTION G01QTF ( X)
REAL (KIND=nag_wp) G01QTF
REAL (KIND=nag_wp) X

3 Description

G01QTF evaluates an approximation to the second moment Φ 2 x of the Landau density function given by
Φ 2 x=1 Φ x ∫-∞x λ 2 ϕ λ dλ,
where ϕ λ is described in G01MTF, using piecewise approximation by rational functions. Further details can be found in Kölbig and Schorr (1984).
To obtain the value of Φ 1 x, G01PTF can be used.

4 References

Kölbig K S and Schorr B (1984) A program package for the Landau distribution Comp. Phys. Comm. 31 97–111

5 Arguments

1:   X – REAL (KIND=nag_wp)Input
On entry: the argument x of the function.

6 Error Indicators and Warnings

None.

7 Accuracy

At least 7 significant digits are usually correct, but occasionally only 6. Such accuracy is normally considered to be adequate for applications in experimental physics.

8 Parallelism and Performance

G01QTF is not threaded in any implementation.

9 Further Comments

None.

10 Example

This example evaluates Φ 2 x at x=0.5, and prints the results.

10.1 Program Text

Program Text (g01qtfe.f90)

10.2 Program Data

Program Data (g01qtfe.d)

10.3 Program Results

Program Results (g01qtfe.r)

G01 Chapter Contents
G01 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


G01RTF : NAG Library, Mark 26

G01 Chapter Contents
G01 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

G01RTF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

G01RTF returns the value of the derivative ϕ′λ of the Landau density function, via the routine name.

2 Specification

FUNCTION G01RTF ( X)
REAL (KIND=nag_wp) G01RTF
REAL (KIND=nag_wp) X

3 Description

G01RTF evaluates an approximation to the derivative ϕ′λ of the Landau density function given by
ϕ′λ=dϕ λ dλ ,
where ϕ λ is described in G01MTF, using piecewise approximation by rational functions. Further details can be found in Kölbig and Schorr (1984).
To obtain the value of ϕ λ, G01MTF can be used.

4 References

Kölbig K S and Schorr B (1984) A program package for the Landau distribution Comp. Phys. Comm. 31 97–111

5 Arguments

1:   X – REAL (KIND=nag_wp)Input
On entry: the argument λ of the function.

6 Error Indicators and Warnings

None.

7 Accuracy

At least 7 significant digits are usually correct, but occasionally only 6. Such accuracy is normally considered to be adequate for applications in experimental physics.
Because of the asymptotic behaviour of ϕ′λ, which is of the order of exp-exp-λ, underflow may occur on some machines when λ is moderately large and negative.

8 Parallelism and Performance

G01RTF is not threaded in any implementation.

9 Further Comments

None.

10 Example

This example evaluates ϕ′λ at λ=0.5, and prints the results.

10.1 Program Text

Program Text (g01rtfe.f90)

10.2 Program Data

Program Data (g01rtfe.d)

10.3 Program Results

Program Results (g01rtfe.r)

G01 Chapter Contents
G01 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


G01SAF : NAG Library, Mark 26

G01 Chapter Contents
G01 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

G01SAF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

G01SAF returns a number of one or two tail probabilities for the Normal distribution.

2 Specification

SUBROUTINE G01SAF ( LTAIL, TAIL, LX, X, LXMU, XMU, LXSTD, XSTD, P, IVALID, IFAIL)
INTEGER | LTAIL, LX, LXMU, LXSTD, IVALID(*), IFAIL
REAL (KIND=nag_wp) | X(LX), XMU(LXMU), XSTD(LXSTD), P(*)
CHARACTER(1) | TAIL(LTAIL)

3 Description

The lower tail probability for the Normal distribution, P Xi≤xi is defined by:
P Xi≤xi = ∫ -∞ xi Zi Xi d Xi ,
where
Zi Xi = 1 2 π σi 2 e -Xi-μi 2/2 σi 2 , -∞ < Xi < ∞ .
The relationship
P Xi ≤ xi = 12 erfc - xi - μi 2 σ i
is used, where erfc is the complementary error function, and is computed using S15ADF.
When the two tail confidence probability is required the relationship
P Xi≤xi - P Xi ≤ - xi = erf xi - μi 2 σi ,
is used, where erf is the error function, and is computed using S15AEF.
The input arrays to this routine are designed to allow maximum flexibility in the supply of vector arguments by re-using elements of any arrays that are shorter than the total number of evaluations required. See Section 2.6 in the G01 Chapter Introduction for further information.

4 References

Abramowitz M and Stegun I A (1972) Handbook of Mathematical Functions (3rd Edition) Dover Publications
Hastings N A J and Peacock J B (1975) Statistical Distributions Butterworth

5 Arguments

1:   LTAIL – INTEGERInput
On entry: the length of the array TAIL.
Constraint: LTAIL>0.
2:   TAIL LTAIL – CHARACTER(1) arrayInput
On entry: indicates which tail the returned probabilities should represent. Letting Z denote a variate from a standard Normal distribution, and zi = xi - μi σi , then for j= i-1 mod LTAIL +1 , for i=1,2,…,max LX,LTAIL,LXMU,LXSTD:
TAIL j='L'
The lower tail probability is returned, i.e., pi=P Z≤zi.
TAIL j='U'
The upper tail probability is returned, i.e., pi=P Z≥zi.
TAIL j='C'
The two tail (confidence interval) probability is returned, i.e., pi=P Z≤zi-P Z≤-zi.
TAIL j='S'
The two tail (significance level) probability is returned, i.e., pi=P Z≥zi+P Z≤-zi.
Constraint: TAIL j='L', 'U', 'C' or 'S', for j=1,2,…,LTAIL.
3:   LX – INTEGERInput
On entry: the length of the array X.
Constraint: LX>0.
4:   X LX – REAL (KIND=nag_wp) arrayInput
On entry: xi, the Normal variate values with xi=X j, j=i-1 mod LX+1.
5:   LXMU – INTEGERInput
On entry: the length of the array XMU.
Constraint: LXMU>0.
6:   XMU LXMU – REAL (KIND=nag_wp) arrayInput
On entry: μi, the means with μi=XMU j, j=i-1 mod LXMU+1.
7:   LXSTD – INTEGERInput
On entry: the length of the array XSTD.
Constraint: LXSTD>0.
8:   XSTD LXSTD – REAL (KIND=nag_wp) arrayInput
On entry: σi, the standard deviations with σi=XSTD j, j=i-1 mod LXSTD+1.
Constraint: XSTD j>0.0, for j=1,2,…,LXSTD.
9:   P* – REAL (KIND=nag_wp) arrayOutput
Note: the dimension of the array P must be at least max LX,LTAIL,LXMU,LXSTD.
On exit: pi, the probabilities for the Normal distribution.
10:   IVALID* – INTEGER arrayOutput
Note: the dimension of the array IVALID must be at least max LX,LTAIL,LXMU,LXSTD.
On exit: IVALID i indicates any errors with the input arguments, with
IVALID i=0
No error.
IVALID i=1
On entry, invalid value supplied in TAIL when calculating pi.
IVALID i=2
On entry, σi≤0.0.
11:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, at least one value of TAIL or XSTD was invalid.
Check IVALID for more information.
IFAIL=2
On entry, LTAIL=value.
Constraint: LTAIL>0.
IFAIL=3
On entry, LX=value.
Constraint: LX>0.
IFAIL=4
On entry, LXMU=value.
Constraint: LXMU>0.
IFAIL=5
On entry, LXSTD=value.
Constraint: LXSTD>0.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

Accuracy is limited by machine precision. For detailed error analysis see S15ADF and S15AEF.

8 Parallelism and Performance

G01SAF is not threaded in any implementation.

9 Further Comments

None.

10 Example

Four values of TAIL, X, XMU and XSTD are input and the probabilities calculated and printed.

10.1 Program Text

Program Text (g01safe.f90)

10.2 Program Data

Program Data (g01safe.d)

10.3 Program Results

Program Results (g01safe.r)

G01 Chapter Contents
G01 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


G01SBF : NAG Library, Mark 26

G01 Chapter Contents
G01 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

G01SBF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

G01SBF returns a number of one or two tail probabilities for the Student's t-distribution with real degrees of freedom.

2 Specification

SUBROUTINE G01SBF ( LTAIL, TAIL, LT, T, LDF, DF, P, IVALID, IFAIL)
INTEGER | LTAIL, LT, LDF, IVALID(*), IFAIL
REAL (KIND=nag_wp) | T(LT), DF(LDF), P(*)
CHARACTER(1) | TAIL(LTAIL)

3 Description

The lower tail probability for the Student's t-distribution with νi degrees of freedom, P Ti ≤ ti :νi is defined by:
P Ti ≤ ti :νi = Γ νi+1 / 2 π νi Γ νi/2 ∫ -∞ ti 1+ Ti 2 νi -νi+1 / 2 d Ti ,   νi≥1 .
Computationally, there are two situations:
(i) when νi<20, a transformation of the beta distribution, P βi Bi ≤ βi :ai,bi is used
P Ti ≤ ti :νi = 12 P βi Bi≤ νi νi+ti 2 :νi/2,12   when ​ ti<0.0
or
P Ti ≤ ti :νi = 12 + 12 P βi Bi ≥ νi νi + ti 2 :νi/2,12   when ​ ti>0.0 ;
(ii) when νi≥20, an asymptotic normalizing expansion of the Cornish–Fisher type is used to evaluate the probability, see Hill (1970).
The input arrays to this routine are designed to allow maximum flexibility in the supply of vector arguments by re-using elements of any arrays that are shorter than the total number of evaluations required. See Section 2.6 in the G01 Chapter Introduction for further information.

4 References

Abramowitz M and Stegun I A (1972) Handbook of Mathematical Functions (3rd Edition) Dover Publications
Hastings N A J and Peacock J B (1975) Statistical Distributions Butterworth
Hill G W (1970) Student's t-distribution Comm. ACM 13(10) 617–619

5 Arguments

1:   LTAIL – INTEGERInput
On entry: the length of the array TAIL.
Constraint: LTAIL>0.
2:   TAIL LTAIL – CHARACTER(1) arrayInput
On entry: indicates which tail the returned probabilities should represent. For j= i-1 mod LTAIL +1 , for i=1,2,…,max LTAIL,LT,LDF:
TAIL j='L'
The lower tail probability is returned, i.e., pi = P Ti ≤ ti :νi .
TAIL j='U'
The upper tail probability is returned, i.e., pi = P Ti ≥ ti :νi .
TAIL j='C'
The two tail (confidence interval) probability is returned, i.e., pi = P Ti ≤ ti :νi - P Ti ≤ - ti :νi .
TAIL j='S'
The two tail (significance level) probability is returned, i.e., pi = P Ti ≥ ti :νi + P Ti ≤ - ti :νi .
Constraint: TAIL j='L', 'U', 'C' or 'S', for j=1,2,…,LTAIL.
3:   LT – INTEGERInput
On entry: the length of the array T.
Constraint: LT>0.
4:   T LT – REAL (KIND=nag_wp) arrayInput
On entry: ti, the values of the Student's t variates with ti=T j, j=i-1 mod LT+1.
5:   LDF – INTEGERInput
On entry: the length of the array DF.
Constraint: LDF>0.
6:   DF LDF – REAL (KIND=nag_wp) arrayInput
On entry: νi, the degrees of freedom of the Student's t-distribution with νi=DF j, j=i-1 mod LDF+1.
Constraint: DF j≥1.0, for j=1,2,…,LDF.
7:   P* – REAL (KIND=nag_wp) arrayOutput
Note: the dimension of the array P must be at least max LTAIL,LT,LDF.
On exit: pi, the probabilities for the Student's t distribution.
8:   IVALID* – INTEGER arrayOutput
Note: the dimension of the array IVALID must be at least max LTAIL,LT,LDF.
On exit: IVALID i indicates any errors with the input arguments, with
IVALID i=0
No error.
IVALID i=1
On entry, invalid value supplied in TAIL when calculating pi.
IVALID i=2
On entry, νi<1.0.
9:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, at least one value of TAIL or DF was invalid.
Check IVALID for more information.
IFAIL=2
On entry, array size=value.
Constraint: LTAIL>0.
IFAIL=3
On entry, array size=value.
Constraint: LT>0.
IFAIL=4
On entry, array size=value.
Constraint: LDF>0.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

The computed probability should be accurate to five significant places for reasonable probabilities but there will be some loss of accuracy for very low probabilities (less than 10-10), see Hastings and Peacock (1975).

8 Parallelism and Performance

G01SBF is not threaded in any implementation.

9 Further Comments

The probabilities could also be obtained by using the appropriate transformation to a beta distribution (see Abramowitz and Stegun (1972)) and using G01SEF. This routine allows you to set the required accuracy.

10 Example

This example reads values from, and degrees of freedom for Student's t-distributions along with the required tail. The probabilities are calculated and printed.

10.1 Program Text

Program Text (g01sbfe.f90)

10.2 Program Data

Program Data (g01sbfe.d)

10.3 Program Results

Program Results (g01sbfe.r)

G01 Chapter Contents
G01 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


G01SCF : NAG Library, Mark 26

G01 Chapter Contents
G01 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

G01SCF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

G01SCF returns a number of lower or upper tail probabilities for the χ 2-distribution with real degrees of freedom.

2 Specification

SUBROUTINE G01SCF ( LTAIL, TAIL, LX, X, LDF, DF, P, IVALID, IFAIL)
INTEGER | LTAIL, LX, LDF, IVALID(*), IFAIL
REAL (KIND=nag_wp) | X(LX), DF(LDF), P(*)
CHARACTER(1) | TAIL(LTAIL)

3 Description

The lower tail probability for the χ 2-distribution with νi degrees of freedom, P = Xi ≤ xi :νi is defined by:
P = Xi≤xi:νi = 1 2 νi/2 Γ νi/2 ∫ 0.0 xi Xi νi/2-1 e -Xi/2 d Xi ,   xi ≥ 0 , νi > 0 .
To calculate P = Xi ≤ xi :νi a transformation of a gamma distribution is employed, i.e., a χ 2-distribution with νi degrees of freedom is equal to a gamma distribution with scale parameter 2 and shape parameter νi/2.
The input arrays to this routine are designed to allow maximum flexibility in the supply of vector arguments by re-using elements of any arrays that are shorter than the total number of evaluations required. See Section 2.6 in the G01 Chapter Introduction for further information.

4 References

Abramowitz M and Stegun I A (1972) Handbook of Mathematical Functions (3rd Edition) Dover Publications
Hastings N A J and Peacock J B (1975) Statistical Distributions Butterworth

5 Arguments

1:   LTAIL – INTEGERInput
On entry: the length of the array TAIL.
Constraint: LTAIL>0.
2:   TAIL LTAIL – CHARACTER(1) arrayInput
On entry: indicates whether the lower or upper tail probabilities are required. For j= i-1 mod LTAIL +1 , for i=1,2,…,max LTAIL,LX,LDF:
TAIL j='L'
The lower tail probability is returned, i.e., pi = P Xi ≤ xi :νi .
TAIL j='U'
The upper tail probability is returned, i.e., pi = P Xi ≥ xi :νi .
Constraint: TAIL j='L' or 'U', for j=1,2,…,LTAIL.
3:   LX – INTEGERInput
On entry: the length of the array X.
Constraint: LX>0.
4:   X LX – REAL (KIND=nag_wp) arrayInput
On entry: xi, the values of the χ 2 variates with νi degrees of freedom with xi=X j, j=i-1 mod LX+1.
Constraint: X j≥0.0, for j=1,2,…,LX.
5:   LDF – INTEGERInput
On entry: the length of the array DF.
Constraint: LDF>0.
6:   DF LDF – REAL (KIND=nag_wp) arrayInput
On entry: νi, the degrees of freedom of the χ 2-distribution with νi=DF j, j=i-1 mod LDF+1.
Constraint: DF j>0.0, for j=1,2,…,LDF.
7:   P* – REAL (KIND=nag_wp) arrayOutput
Note: the dimension of the array P must be at least max LTAIL,LDF,LX.
On exit: pi, the probabilities for the χ 2 distribution.
8:   IVALID* – INTEGER arrayOutput
Note: the dimension of the array IVALID must be at least max LTAIL,LDF,LX.
On exit: IVALID i indicates any errors with the input arguments, with
IVALID i=0
No error.
IVALID i=1
On entry, invalid value supplied in TAIL when calculating pi.
IVALID i=2
On entry, xi<0.0.
IVALID i=3
On entry, νi≤0.0.
IVALID i=4
The solution has failed to converge while calculating the gamma variate. The result returned should represent an approximation to the solution.
9:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, because for this routine the values of the output arguments may be useful even if IFAIL≠0 on exit, the recommended value is -1. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Note: G01SCF may return useful information for one or more of the following detected errors or warnings.
Errors or warnings detected by the routine:
IFAIL=1
On entry, at least one value of X, DF or TAIL was invalid, or the solution failed to converge.
Check IVALID for more information.
IFAIL=2
On entry, array size=value.
Constraint: LTAIL>0.
IFAIL=3
On entry, array size=value.
Constraint: LX>0.
IFAIL=4
On entry, array size=value.
Constraint: LDF>0.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

A relative accuracy of five significant figures is obtained in most cases.

8 Parallelism and Performance

G01SCF is not threaded in any implementation.

9 Further Comments

For higher accuracy the transformation described in Section 3 may be used with a direct call to S14BAF.

10 Example

Values from various χ 2-distributions are read, the lower tail probabilities calculated, and all these values printed out.

10.1 Program Text

Program Text (g01scfe.f90)

10.2 Program Data

Program Data (g01scfe.d)

10.3 Program Results

Program Results (g01scfe.r)

G01 Chapter Contents
G01 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


G01SDF : NAG Library, Mark 26

G01 Chapter Contents
G01 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

G01SDF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

G01SDF returns a number of lower or upper tail probabilities for the F or variance-ratio distribution with real degrees of freedom.

2 Specification

SUBROUTINE G01SDF ( LTAIL, TAIL, LF, F, LDF1, DF1, LDF2, DF2, P, IVALID, IFAIL)
INTEGER | LTAIL, LF, LDF1, LDF2, IVALID(*), IFAIL
REAL (KIND=nag_wp) | F(LF), DF1(LDF1), DF2(LDF2), P(*)
CHARACTER(1) | TAIL(LTAIL)

3 Description

The lower tail probability for the F, or variance-ratio, distribution with ui and vi degrees of freedom, P Fi ≤ fi :ui,vi , is defined by:
P Fi ≤ fi :ui,vi = ui ui/2 vi vi/2 Γ ui + vi / 2 Γ ui/2 Γ vi/2 ∫ 0 fi Fi ui-2 / 2 ui Fi + vi - ui + vi / 2 d Fi ,
for ui, vi>0, fi≥0.
The probability is computed by means of a transformation to a beta distribution, P βi Bi ≤ βi :ai,bi :
P Fi ≤ fi :ui,vi = P βi Bi ≤ ui fi ui fi + vi : ui / 2 , vi / 2
and using a call to G01EEF.
For very large values of both ui and vi, greater than 105, a normal approximation is used. If only one of ui or vi is greater than 105 then a χ 2 approximation is used, see Abramowitz and Stegun (1972).
The input arrays to this routine are designed to allow maximum flexibility in the supply of vector arguments by re-using elements of any arrays that are shorter than the total number of evaluations required. See Section 2.6 in the G01 Chapter Introduction for further information.

4 References

Abramowitz M and Stegun I A (1972) Handbook of Mathematical Functions (3rd Edition) Dover Publications
Hastings N A J and Peacock J B (1975) Statistical Distributions Butterworth

5 Arguments

1:   LTAIL – INTEGERInput
On entry: the length of the array TAIL.
Constraint: LTAIL>0.
2:   TAIL LTAIL – CHARACTER(1) arrayInput
On entry: indicates whether the lower or upper tail probabilities are required. For j= i-1 mod LTAIL +1 , for i=1,2,…,max LTAIL,LF,LDF1,LDF2:
TAIL j='L'
The lower tail probability is returned, i.e., pi = P Fi ≤ fi :ui,vi .
TAIL j='U'
The upper tail probability is returned, i.e., pi = P Fi ≥ fi :ui,vi .
Constraint: TAIL j='L' or 'U', for j=1,2,…,LTAIL.
3:   LF – INTEGERInput
On entry: the length of the array F.
Constraint: LF>0.
4:   F LF – REAL (KIND=nag_wp) arrayInput
On entry: fi, the value of the F variate with fi=F j, j=i-1 mod LF+1.
Constraint: F j≥0.0, for j=1,2,…,LF.
5:   LDF1 – INTEGERInput
On entry: the length of the array DF1.
Constraint: LDF1>0.
6:   DF1 LDF1 – REAL (KIND=nag_wp) arrayInput
On entry: ui, the degrees of freedom of the numerator variance with ui=DF1 j, j=i-1 mod LDF1+1.
Constraint: DF1 j>0.0, for j=1,2,…,LDF1.
7:   LDF2 – INTEGERInput
On entry: the length of the array DF2.
Constraint: LDF2>0.
8:   DF2 LDF2 – REAL (KIND=nag_wp) arrayInput
On entry: vi, the degrees of freedom of the denominator variance with vi=DF2 j, j=i-1 mod LDF2+1.
Constraint: DF2 j>0.0, for j=1,2,…,LDF2.
9:   P* – REAL (KIND=nag_wp) arrayOutput
Note: the dimension of the array P must be at least max LTAIL,LF,LDF1,LDF2.
On exit: pi, the probabilities for the F-distribution.
10:   IVALID* – INTEGER arrayOutput
Note: the dimension of the array IVALID must be at least max LTAIL,LF,LDF1,LDF2.
On exit: IVALID i indicates any errors with the input arguments, with
IVALID i=0
No error.
IVALID i=1
On entry, invalid value supplied in TAIL when calculating pi.
IVALID i=2
On entry, fi<0.0.
IVALID i=3
On entry, | ui≤0.0,
or | vi≤0.0.
IVALID i=4
The solution has failed to converge. The result returned should represent an approximation to the solution.
11:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, because for this routine the values of the output arguments may be useful even if IFAIL≠0 on exit, the recommended value is -1. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Note: G01SDF may return useful information for one or more of the following detected errors or warnings.
Errors or warnings detected by the routine:
IFAIL=1
On entry, at least one value of F, DF1, DF2 or TAIL was invalid, or the solution failed to converge.
Check IVALID for more information.
IFAIL=2
On entry, array size=value.
Constraint: LTAIL>0.
IFAIL=3
On entry, array size=value.
Constraint: LF>0.
IFAIL=4
On entry, array size=value.
Constraint: LDF1>0.
IFAIL=5
On entry, array size=value.
Constraint: LDF2>0.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

The result should be accurate to five significant digits.

8 Parallelism and Performance

G01SDF is not threaded in any implementation.

9 Further Comments

For higher accuracy G01SEF can be used along with the transformations given in Section 3.

10 Example

This example reads values from, and degrees of freedom for, a number of F-distributions and computes the associated lower tail probabilities.

10.1 Program Text

Program Text (g01sdfe.f90)

10.2 Program Data

Program Data (g01sdfe.d)

10.3 Program Results

Program Results (g01sdfe.r)

G01 Chapter Contents
G01 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


G01SEF : NAG Library, Mark 26

G01 Chapter Contents
G01 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

G01SEF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

G01SEF computes a number of lower or upper tail probabilities for the beta distribution.

2 Specification

SUBROUTINE G01SEF ( LTAIL, TAIL, LBETA, BETA, LA, A, LB, B, P, IVALID, IFAIL)
INTEGER | LTAIL, LBETA, LA, LB, IVALID(*), IFAIL
REAL (KIND=nag_wp) | BETA(LBETA), A(LA), B(LB), P(*)
CHARACTER(1) | TAIL(LTAIL)

3 Description

The lower tail probability, P Bi ≤ βi :ai,bi is defined by
P Bi ≤ βi :ai,bi = Γ ai + bi Γ ai Γ bi ∫ 0 βi Bi ai-1 1-Bi bi-1 d Bi = I βi ai,bi ,   0 ≤ βi ≤ 1 ;  ai , bi > 0 .
The function I βi ai,bi, also known as the incomplete beta function is calculated using S14CCF.
The input arrays to this routine are designed to allow maximum flexibility in the supply of vector arguments by re-using elements of any arrays that are shorter than the total number of evaluations required. See Section 2.6 in the G01 Chapter Introduction for further information.

4 References

Abramowitz M and Stegun I A (1972) Handbook of Mathematical Functions (3rd Edition) Dover Publications
Hastings N A J and Peacock J B (1975) Statistical Distributions Butterworth
Majumder K L and Bhattacharjee G P (1973) Algorithm AS 63. The incomplete beta integral Appl. Statist. 22 409–411

5 Arguments

1:   LTAIL – INTEGERInput
On entry: the length of the array TAIL.
Constraint: LTAIL>0.
2:   TAIL LTAIL – CHARACTER(1) arrayInput
On entry: indicates whether a lower or upper tail probabilities are required. For j= i-1 mod LTAIL +1 , for i=1,2,…,max LTAIL,LBETA,LA,LB:
TAIL j='L'
The lower tail probability is returned, i.e., pi = P Bi ≤ βi :ai,bi .
TAIL j='U'
The upper tail probability is returned, i.e., pi = P Bi ≥ βi :ai,bi .
Constraint: TAIL j='L' or 'U', for j=1,2,…,LTAIL.
3:   LBETA – INTEGERInput
On entry: the length of the array BETA.
Constraint: LBETA>0.
4:   BETA LBETA – REAL (KIND=nag_wp) arrayInput
On entry: βi, the value of the beta variate with βi=BETA j, j=i-1 mod LBETA+1.
Constraint: 0.0≤BETA j≤1.0, for j=1,2,…,LBETA.
5:   LA – INTEGERInput
On entry: the length of the array A.
Constraint: LA>0.
6:   A LA – REAL (KIND=nag_wp) arrayInput
On entry: ai, the first parameter of the required beta distribution with ai=A j, j=i-1 mod LA+1.
Constraint: A j>0.0, for j=1,2,…,LA.
7:   LB – INTEGERInput
On entry: the length of the array B.
Constraint: LB>0.
8:   B LB – REAL (KIND=nag_wp) arrayInput
On entry: bi, the second parameter of the required beta distribution with bi=B j, j=i-1 mod LB+1.
Constraint: B j>0.0, for j=1,2,…,LB.
9:   P* – REAL (KIND=nag_wp) arrayOutput
Note: the dimension of the array P must be at least max LTAIL,LBETA,LA,LB.
On exit: pi, the probabilities for the beta distribution.
10:   IVALID* – INTEGER arrayOutput
Note: the dimension of the array IVALID must be at least max LTAIL,LBETA,LA,LB.
On exit: IVALID i indicates any errors with the input arguments, with
IVALID i=0
No error.
IVALID i=1
On entry, invalid value supplied in TAIL when calculating pi.
IVALID i=2
On entry, | βi<0.0,
or | βi>1.0.
IVALID i=3
On entry, | ai≤0.0,
or | bi≤0.0,
11:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, because for this routine the values of the output arguments may be useful even if IFAIL≠0 on exit, the recommended value is -1. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Note: G01SEF may return useful information for one or more of the following detected errors or warnings.
Errors or warnings detected by the routine:
IFAIL=1
On entry, at least one value of BETA, A, B or TAIL was invalid.
Check IVALID for more information.
IFAIL=2
On entry, array size=value.
Constraint: LTAIL>0.
IFAIL=3
On entry, array size=value.
Constraint: LBETA>0.
IFAIL=4
On entry, array size=value.
Constraint: LA>0.
IFAIL=5
On entry, array size=value.
Constraint: LB>0.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

The accuracy is limited by the error in the incomplete beta function. See Section 7 in S14CCF for further details.

8 Parallelism and Performance

G01SEF is not threaded in any implementation.

9 Further Comments

None.

10 Example

This example reads values from a number of beta distributions and computes the associated lower tail probabilities.

10.1 Program Text

Program Text (g01sefe.f90)

10.2 Program Data

Program Data (g01sefe.d)

10.3 Program Results

Program Results (g01sefe.r)

G01 Chapter Contents
G01 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


G01SFF : NAG Library, Mark 26

G01 Chapter Contents
G01 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

G01SFF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

G01SFF returns a number of lower or upper tail probabilities for the gamma distribution.

2 Specification

SUBROUTINE G01SFF ( LTAIL, TAIL, LG, G, LA, A, LB, B, P, IVALID, IFAIL)
INTEGER | LTAIL, LG, LA, LB, IVALID(*), IFAIL
REAL (KIND=nag_wp) | G(LG), A(LA), B(LB), P(*)
CHARACTER(1) | TAIL(LTAIL)

3 Description

The lower tail probability for the gamma distribution with parameters αi and βi, P Gi≤gi, is defined by:
P Gi ≤ gi :αi,βi = 1 βi αi Γ αi ∫ 0 gi Gi αi-1 e -Gi/βi d Gi ,   αi>0.0 , ​ βi>0.0 .
The mean of the distribution is αiβi and its variance is αi βi 2. The transformation Zi=Giβi is applied to yield the following incomplete gamma function in normalized form,
P Gi ≤ gi :αi,βi = P Zi ≤ gi / βi :αi,1.0 = 1 Γ αi ∫ 0 gi / βi Zi αi-1 e -Zi d Zi .
This is then evaluated using S14BAF.
The input arrays to this routine are designed to allow maximum flexibility in the supply of vector arguments by re-using elements of any arrays that are shorter than the total number of evaluations required. See Section 2.6 in the G01 Chapter Introduction for further information.

4 References

Hastings N A J and Peacock J B (1975) Statistical Distributions Butterworth

5 Arguments

1:   LTAIL – INTEGERInput
On entry: the length of the array TAIL.
Constraint: LTAIL>0.
2:   TAIL LTAIL – CHARACTER(1) arrayInput
On entry: indicates whether a lower or upper tail probability is required. For j= i-1 mod LTAIL +1 , for i=1,2,…,max LTAIL,LG,LA,LB:
TAIL j='L'
The lower tail probability is returned, i.e., pi = P Gi ≤ gi :αi,βi .
TAIL j='U'
The upper tail probability is returned, i.e., pi = P Gi ≥ gi :αi,βi .
Constraint: TAIL j='L' or 'U', for j=1,2,…,LTAIL.
3:   LG – INTEGERInput
On entry: the length of the array G.
Constraint: LG>0.
4:   G LG – REAL (KIND=nag_wp) arrayInput
On entry: gi, the value of the gamma variate with gi=G j, j=i-1 mod LG+1.
Constraint: G j≥0.0, for j=1,2,…,LG.
5:   LA – INTEGERInput
On entry: the length of the array A.
Constraint: LA>0.
6:   A LA – REAL (KIND=nag_wp) arrayInput
On entry: the parameter αi of the gamma distribution with αi=A j, j=i-1 mod LA+1.
Constraint: A j>0.0, for j=1,2,…,LA.
7:   LB – INTEGERInput
On entry: the length of the array B.
Constraint: LB>0.
8:   B LB – REAL (KIND=nag_wp) arrayInput
On entry: the parameter βi of the gamma distribution with βi=B j, j=i-1 mod LB+1.
Constraint: B j>0.0, for j=1,2,…,LB.
9:   P* – REAL (KIND=nag_wp) arrayOutput
Note: the dimension of the array P must be at least max LG,LA,LB,LTAIL.
On exit: pi, the probabilities of the beta distribution.
10:   IVALID* – INTEGER arrayOutput
Note: the dimension of the array IVALID must be at least max LG,LA,LB,LTAIL.
On exit: IVALID i indicates any errors with the input arguments, with
IVALID i=0
No error.
IVALID i=1
On entry, invalid value supplied in TAIL when calculating pi.
IVALID i=2
On entry, gi<0.0.
IVALID i=3
On entry, | αi≤0.0,
or | βi≤0.0.
IVALID i=4
The solution did not converge in 600 iterations, see S14BAF for details. The probability returned should be a reasonable approximation to the solution.
11:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, at least one value of G, A, B or TAIL was invalid, or the solution did not converge.
Check IVALID for more information.
IFAIL=2
On entry, array size=value.
Constraint: LTAIL>0.
IFAIL=3
On entry, array size=value.
Constraint: LG>0.
IFAIL=4
On entry, array size=value.
Constraint: LA>0.
IFAIL=5
On entry, array size=value.
Constraint: LB>0.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

The result should have a relative accuracy of machine precision. There are rare occasions when the relative accuracy attained is somewhat less than machine precision but the error should not exceed more than 1 or 2 decimal places.

8 Parallelism and Performance

G01SFF is not threaded in any implementation.

9 Further Comments

The time taken by G01SFF to calculate each probability varies slightly with the input arguments gi, αi and βi.

10 Example

This example reads in values from a number of gamma distributions and computes the associated lower tail probabilities.

10.1 Program Text

Program Text (g01sffe.f90)

10.2 Program Data

Program Data (g01sffe.d)

10.3 Program Results

Program Results (g01sffe.r)

G01 Chapter Contents
G01 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


G01SJF : NAG Library, Mark 26

G01 Chapter Contents
G01 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

G01SJF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

G01SJF returns a number of the lower tail, upper tail and point probabilities for the binomial distribution.

2 Specification

SUBROUTINE G01SJF ( LN, N, LP, P, LK, K, PLEK, PGTK, PEQK, IVALID, IFAIL)
INTEGER | LN, N(LN), LP, LK, K(LK), IVALID(*), IFAIL
REAL (KIND=nag_wp) | P(LP), PLEK(*), PGTK(*), PEQK(*)

3 Description

Let X = Xi: i=1 , 2 ,…, m denote a vector of random variables each having a binomial distribution with parameters ni and pi (ni≥0 and 0<pi<1). Then
Prob Xi=ki= ni ki piki1-pi ni-ki,  ki=0,1,…,ni.
The mean of the each distribution is given by nipi and the variance by nipi 1-pi.
G01SJF computes, for given ni, pi and ki, the probabilities: Prob Xi≤ki, Prob Xi>ki and Prob Xi=ki using an algorithm similar to that described in Knüsel (1986) for the Poisson distribution.
The input arrays to this routine are designed to allow maximum flexibility in the supply of vector arguments by re-using elements of any arrays that are shorter than the total number of evaluations required. See Section 2.6 in the G01 Chapter Introduction for further information.

4 References

Knüsel L (1986) Computation of the chi-square and Poisson distribution SIAM J. Sci. Statist. Comput. 7 1022–1036

5 Arguments

1:   LN – INTEGERInput
On entry: the length of the array N
Constraint: LN>0.
2:   N LN – INTEGER arrayInput
On entry: ni, the first parameter of the binomial distribution with ni=N j, j=i-1 mod LN+1, for i=1,2,…,max LN,LP,LK.
Constraint: N j≥0, for j=1,2,…,LN.
3:   LP – INTEGERInput
On entry: the length of the array P
Constraint: LP>0.
4:   P LP – REAL (KIND=nag_wp) arrayInput
On entry: pi, the second parameter of the binomial distribution with pi=P j, j=i-1 mod LP+1.
Constraint: 0.0<P j<1.0, for j=1,2,…,LP.
5:   LK – INTEGERInput
On entry: the length of the array K
Constraint: LK>0.
6:   K LK – INTEGER arrayInput
On entry: ki, the integer which defines the required probabilities with ki=K j, j=i-1 mod LK+1.
Constraint: 0 ≤ ki ≤ ni .
7:   PLEK* – REAL (KIND=nag_wp) arrayOutput
Note: the dimension of the array PLEK must be at least max LN,LP,LK.
On exit: Prob Xi ≤ ki , the lower tail probabilities.
8:   PGTK* – REAL (KIND=nag_wp) arrayOutput
Note: the dimension of the array PGTK must be at least max LN,LP,LK.
On exit: Prob Xi > ki , the upper tail probabilities.
9:   PEQK* – REAL (KIND=nag_wp) arrayOutput
Note: the dimension of the array PEQK must be at least max LN,LP,LK.
On exit: Prob Xi = ki , the point probabilities.
10:   IVALID* – INTEGER arrayOutput
Note: the dimension of the array IVALID must be at least max LN,LP,LK.
On exit: IVALID i indicates any errors with the input arguments, with
IVALID i=0
No error.
IVALID i=1
On entry, ni<0.
IVALID i=2
On entry, | pi≤0.0,
or | pi≥1.0.
IVALID i=3
On entry, | ki<0,
or | ki>ni.
IVALID i=4
On entry, ni is too large to be represented exactly as a real number.
IVALID i=5
On entry, the variance (=nipi 1-pi) exceeds 106.
11:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, at least one value of N, P or K was invalid.
Check IVALID for more information.
IFAIL=2
On entry, array size=value.
Constraint: LN>0.
IFAIL=3
On entry, array size=value.
Constraint: LP>0.
IFAIL=4
On entry, array size=value.
Constraint: LK>0.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

Results are correct to a relative accuracy of at least 10-6 on machines with a precision of 9 or more decimal digits, and to a relative accuracy of at least 10-3 on machines of lower precision (provided that the results do not underflow to zero).

8 Parallelism and Performance

G01SJF is not threaded in any implementation.

9 Further Comments

The time taken by G01SJF to calculate each probability depends on the variance (=nipi 1-pi) and on ki. For given variance, the time is greatest when ki≈nipi (=the mean), and is then approximately proportional to the square-root of the variance.

10 Example

This example reads a vector of values for n, p and k, and prints the corresponding probabilities.

10.1 Program Text

Program Text (g01sjfe.f90)

10.2 Program Data

Program Data (g01sjfe.d)

10.3 Program Results

Program Results (g01sjfe.r)

G01 Chapter Contents
G01 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


G01SKF : NAG Library, Mark 26

G01 Chapter Contents
G01 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

G01SKF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

G01SKF returns a number of the lower tail, upper tail and point probabilities for the Poisson distribution.

2 Specification

SUBROUTINE G01SKF ( LL, L, LK, K, PLEK, PGTK, PEQK, IVALID, IFAIL)
INTEGER | LL, LK, K(LK), IVALID(*), IFAIL
REAL (KIND=nag_wp) | L(LL), PLEK(*), PGTK(*), PEQK(*)

3 Description

Let X = Xi: i=1 , 2 ,…, m denote a vector of random variables each having a Poisson distribution with parameter λi >0. Then
Prob Xi = ki = e -λi λi ki ki! ,   ki = 0,1,2,…
The mean and variance of each distribution are both equal to λi.
G01SKF computes, for given λi and ki the probabilities: Prob Xi≤ki, Prob Xi>ki and Prob Xi=ki using the algorithm described in Knüsel (1986).
The input arrays to this routine are designed to allow maximum flexibility in the supply of vector arguments by re-using elements of any arrays that are shorter than the total number of evaluations required. See Section 2.6 in the G01 Chapter Introduction for further information.

4 References

Knüsel L (1986) Computation of the chi-square and Poisson distribution SIAM J. Sci. Statist. Comput. 7 1022–1036

5 Arguments

1:   LL – INTEGERInput
On entry: the length of the array L
Constraint: LL>0.
2:   L LL – REAL (KIND=nag_wp) arrayInput
On entry: λi, the parameter of the Poisson distribution with λi=L j, j=i-1 mod LL+1, for i=1,2,…,max LL,LK.
Constraint: 0.0<L j≤106, for j=1,2,…,LL.
3:   LK – INTEGERInput
On entry: the length of the array K
Constraint: LK>0.
4:   K LK – INTEGER arrayInput
On entry: ki, the integer which defines the required probabilities with ki=K j, j=i-1 mod LK+1.
Constraint: K j≥0, for j=1,2,…,LK.
5:   PLEK* – REAL (KIND=nag_wp) arrayOutput
Note: the dimension of the array PLEK must be at least max LL,LK.
On exit: Prob Xi ≤ ki , the lower tail probabilities.
6:   PGTK* – REAL (KIND=nag_wp) arrayOutput
Note: the dimension of the array PGTK must be at least max LL,LK.
On exit: Prob Xi > ki , the upper tail probabilities.
7:   PEQK* – REAL (KIND=nag_wp) arrayOutput
Note: the dimension of the array PEQK must be at least max LL,LK.
On exit: Prob Xi = ki , the point probabilities.
8:   IVALID* – INTEGER arrayOutput
Note: the dimension of the array IVALID must be at least max LL,LK.
On exit: IVALID i indicates any errors with the input arguments, with
IVALID i=0
No error.
IVALID i=1
On entry, λi≤0.0.
IVALID i=2
On entry, ki<0.
IVALID i=3
On entry, λi>106.
9:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, at least one value of L or K was invalid.
Check IVALID for more information.
IFAIL=2
On entry, array size=value.
Constraint: LL>0.
IFAIL=3
On entry, array size=value.
Constraint: LK>0.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

Results are correct to a relative accuracy of at least 10-6 on machines with a precision of 9 or more decimal digits (provided that the results do not underflow to zero).

8 Parallelism and Performance

G01SKF is not threaded in any implementation.

9 Further Comments

The time taken by G01SKF to calculate each probability depends on λi and ki. For given λi, the time is greatest when ki≈λi, and is then approximately proportional to λi.

10 Example

This example reads a vector of values for λ and k, and prints the corresponding probabilities.

10.1 Program Text

Program Text (g01skfe.f90)

10.2 Program Data

Program Data (g01skfe.d)

10.3 Program Results

Program Results (g01skfe.r)

G01 Chapter Contents
G01 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


G01SLF : NAG Library, Mark 26

G01 Chapter Contents
G01 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

G01SLF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

G01SLF returns a number of the lower tail, upper tail and point probabilities for the hypergeometric distribution.

2 Specification

SUBROUTINE G01SLF ( LN, N, LL, L, LM, M, LK, K, PLEK, PGTK, PEQK, IVALID, IFAIL)
INTEGER | LN, N(LN), LL, L(LL), LM, M(LM), LK, K(LK), IVALID(*), IFAIL
REAL (KIND=nag_wp) | PLEK(*), PGTK(*), PEQK(*)

3 Description

Let X = Xi: i=1 , 2 ,…, r denote a vector of random variables having a hypergeometric distribution with parameters ni, li and mi. Then
Prob Xi = ki = mi ki ni - mi li - ki ni li ,
where max 0, li + mi - ni ≤ ki ≤ min li,mi , 0≤li≤ni and 0≤mi≤ni.
The hypergeometric distribution may arise if in a population of size ni a number mi are marked. From this population a sample of size li is drawn and of these ki are observed to be marked.
The mean of the distribution = limi ni , and the variance = limi ni-lini-mi ni 2 ni-1 .
G01SLF computes for given ni, li, mi and ki the probabilities: Prob Xi≤ki, Prob Xi>ki and Prob Xi=ki using an algorithm similar to that described in Knüsel (1986) for the Poisson distribution.
The input arrays to this routine are designed to allow maximum flexibility in the supply of vector arguments by re-using elements of any arrays that are shorter than the total number of evaluations required. See Section 2.6 in the G01 Chapter Introduction for further information.

4 References

Knüsel L (1986) Computation of the chi-square and Poisson distribution SIAM J. Sci. Statist. Comput. 7 1022–1036

5 Arguments

1:   LN – INTEGERInput
On entry: the length of the array N
Constraint: LN>0.
2:   N LN – INTEGER arrayInput
On entry: ni, the parameter of the hypergeometric distribution with ni=N j, j=i-1 mod LN+1, for i=1,2,…,max LN,LL,LM,LK.
Constraint: N j≥0, for j=1,2,…,LN.
3:   LL – INTEGERInput
On entry: the length of the array L
Constraint: LL>0.
4:   L LL – INTEGER arrayInput
On entry: li, the parameter of the hypergeometric distribution with li=L j, j=i-1 mod LL+1.
Constraint: 0 ≤ li ≤ ni .
5:   LM – INTEGERInput
On entry: the length of the array M
Constraint: LM>0.
6:   M LM – INTEGER arrayInput
On entry: mi, the parameter of the hypergeometric distribution with mi=M j, j=i-1 mod LM+1.
Constraint: 0 ≤ mi ≤ ni .
7:   LK – INTEGERInput
On entry: the length of the array K
Constraint: LK>0.
8:   K LK – INTEGER arrayInput
On entry: ki, the integer which defines the required probabilities with ki=K j, j=i-1 mod LK+1.
Constraint: max 0, li + mi - ni ≤ ki ≤ min li,mi .
9:   PLEK* – REAL (KIND=nag_wp) arrayOutput
Note: the dimension of the array PLEK must be at least max LN,LL,LM,LK.
On exit: Prob Xi ≤ ki , the lower tail probabilities.
10:   PGTK* – REAL (KIND=nag_wp) arrayOutput
Note: the dimension of the array PGTK must be at least max LN,LL,LM,LK.
On exit: Prob Xi > ki , the upper tail probabilities.
11:   PEQK* – REAL (KIND=nag_wp) arrayOutput
Note: the dimension of the array PEQK must be at least max LN,LL,LM,LK.
On exit: Prob Xi = ki , the point probabilities.
12:   IVALID* – INTEGER arrayOutput
Note: the dimension of the array IVALID must be at least max LN,LL,LM,LK.
On exit: IVALID i indicates any errors with the input arguments, with
IVALID i=0
No error.
IVALID i=1
On entry, ni<0.
IVALID i=2
On entry, | li<0,
or | li>ni.
IVALID i=3
On entry, | mi<0,
or | mi>ni.
IVALID i=4
On entry, | ki<0,
or | ki>li,
or | ki>mi,
or | ki<li+mi-ni.
IVALID i=5
On entry, ni is too large to be represented exactly as a real number.
IVALID i=6
On entry, the variance (see Section 3) exceeds 106.
13:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, at least one value of N, L, M or K was invalid, or the variance was too large.
Check IVALID for more information.
IFAIL=2
On entry, array size=value.
Constraint: LN>0.
IFAIL=3
On entry, array size=value.
Constraint: LL>0.
IFAIL=4
On entry, array size=value.
Constraint: LM>0.
IFAIL=5
On entry, array size=value.
Constraint: LK>0.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

Results are correct to a relative accuracy of at least 10-6 on machines with a precision of 9 or more decimal digits (provided that the results do not underflow to zero).

8 Parallelism and Performance

G01SLF is not threaded in any implementation.

9 Further Comments

The time taken by G01SLF to calculate each probability depends on the variance (see Section 3) and on ki. For given variance, the time is greatest when ki≈limi/ni (= the mean), and is then approximately proportional to the square-root of the variance.

10 Example

This example reads a vector of values for n, l, m and k, and prints the corresponding probabilities.

10.1 Program Text

Program Text (g01slfe.f90)

10.2 Program Data

Program Data (g01slfe.d)

10.3 Program Results

Program Results (g01slfe.r)

G01 Chapter Contents
G01 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


G01TAF : NAG Library, Mark 26

G01 Chapter Contents
G01 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

G01TAF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

G01TAF returns a number of deviates associated with given probabilities of the Normal distribution.

2 Specification

SUBROUTINE G01TAF ( LTAIL, TAIL, LP, P, LXMU, XMU, LXSTD, XSTD, X, IVALID, IFAIL)
INTEGER | LTAIL, LP, LXMU, LXSTD, IVALID(*), IFAIL
REAL (KIND=nag_wp) | P(LP), XMU(LXMU), XSTD(LXSTD), X(*)
CHARACTER(1) | TAIL(LTAIL)

3 Description

The deviate, x pi associated with the lower tail probability, pi, for the Normal distribution is defined as the solution to
P Xi≤x pi=pi=∫-∞x pi Zi Xi d Xi,
where
Zi Xi=1 2 π σi 2 e-Xi-μi 2/2 σi 2, ​-∞<Xi< ∞.
The method used is an extension of that of Wichura (1988). pi is first replaced by qi=pi-0.5.
(a) If qi≤0.3, zi is computed by a rational Chebyshev approximation
zi=si Ai si 2 Bi si 2 ,
where si=2 π qi and Ai, Bi are polynomials of degree 7.
(b) If 0.3<qi≤0.42, zi is computed by a rational Chebyshev approximation
zi=sign⁡qi Ci ti Di ti ,
where ti=qi-0.3 and Ci, Di are polynomials of degree 5.
(c) If qi>0.42, zi is computed as
zi=sign⁡qi Ei ui Fi ui +ui ,
where ui = -2 × log min pi,1-pi and Ei, Fi are polynomials of degree 6.
x pi is then calculated from zi, using the relationsship z pi = xi - μi σi .
For the upper tail probability -x pi is returned, while for the two tail probabilities the value x i pi* is returned, where pi* is the required tail probability computed from the input value of pi.
The input arrays to this routine are designed to allow maximum flexibility in the supply of vector arguments by re-using elements of any arrays that are shorter than the total number of evaluations required. See Section 2.6 in the G01 Chapter Introduction for further information.

4 References

Abramowitz M and Stegun I A (1972) Handbook of Mathematical Functions (3rd Edition) Dover Publications
Hastings N A J and Peacock J B (1975) Statistical Distributions Butterworth
Wichura (1988) Algorithm AS 241: the percentage points of the Normal distribution Appl. Statist. 37 477–484

5 Arguments

1:   LTAIL – INTEGERInput
On entry: the length of the array TAIL.
Constraint: LTAIL>0.
2:   TAIL LTAIL – CHARACTER(1) arrayInput
On entry: indicates which tail the supplied probabilities represent. Letting Z denote a variate from a standard Normal distribution, and zi = x pi - μi σi , then for j= i-1 mod LTAIL +1 , for i=1,2,…,max LTAIL,LP,LXMU,LXSTD:
TAIL j='L'
The lower tail probability, i.e., pi=P Z≤zi.
TAIL j='U'
The upper tail probability, i.e., pi=P Z≥zi.
TAIL j='C'
The two tail (confidence interval) probability, i.e., pi=P Z≤zi-P Z≤-zi.
TAIL j='S'
The two tail (significance level) probability, i.e., pi=P Z≥zi+P Z≤-zi.
Constraint: TAIL j='L', 'U', 'C' or 'S', for j=1,2,…,LTAIL.
3:   LP – INTEGERInput
On entry: the length of the array P.
Constraint: LP>0.
4:   P LP – REAL (KIND=nag_wp) arrayInput
On entry: pi, the probabilities for the Normal distribution as defined by TAIL with pi=P j, j=i-1 mod LP+1.
Constraint: 0.0<P j<1.0, for j=1,2,…,LP.
5:   LXMU – INTEGERInput
On entry: the length of the array XMU.
Constraint: LXMU>0.
6:   XMU LXMU – REAL (KIND=nag_wp) arrayInput
On entry: μi, the means with μi=XMU j, j=i-1 mod LXMU+1.
7:   LXSTD – INTEGERInput
On entry: the length of the array XSTD.
Constraint: LXSTD>0.
8:   XSTD LXSTD – REAL (KIND=nag_wp) arrayInput
On entry: σi, the standard deviations with σi=XSTD j, j=i-1 mod LXSTD+1.
Constraint: XSTD j>0.0, for j=1,2,…,LXSTD.
9:   X* – REAL (KIND=nag_wp) arrayOutput
Note: the dimension of the array X must be at least max LTAIL,LXMU,LXSTD,LP.
On exit: x pi, the deviates for the Normal distribution.
10:   IVALID* – INTEGER arrayOutput
Note: the dimension of the array IVALID must be at least max LTAIL,LXMU,LXSTD,LP.
On exit: IVALID i indicates any errors with the input arguments, with
IVALID i=0
No error.
IVALID i=1
On entry, invalid value supplied in TAIL when calculating x pi.
IVALID i=2
On entry, | pi≤0.0,
or | pi≥1.0.
IVALID i=3
On entry, σi≤0.0.
11:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, at least one value of TAIL, XSTD or P was invalid.
Check IVALID for more information.
IFAIL=2
On entry, array size=value.
Constraint: LTAIL>0.
IFAIL=3
On entry, array size=value.
Constraint: LP>0.
IFAIL=4
On entry, array size=value.
Constraint: LXMU>0.
IFAIL=5
On entry, array size=value.
Constraint: LXSTD>0.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

The accuracy is mainly limited by the machine precision.

8 Parallelism and Performance

G01TAF is not threaded in any implementation.

9 Further Comments

None.

10 Example

This example reads vectors of values for μi, σi and pi and prints the corresponding deviates.

10.1 Program Text

Program Text (g01tafe.f90)

10.2 Program Data

Program Data (g01tafe.d)

10.3 Program Results

Program Results (g01tafe.r)

G01 Chapter Contents
G01 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


G01TBF : NAG Library, Mark 26

G01 Chapter Contents
G01 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

G01TBF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

G01TBF returns a number of deviates associated with given probabilities of Student's t-distribution with real degrees of freedom.

2 Specification

SUBROUTINE G01TBF ( LTAIL, TAIL, LP, P, LDF, DF, T, IVALID, IFAIL)
INTEGER | LTAIL, LP, LDF, IVALID(*), IFAIL
REAL (KIND=nag_wp) | P(LP), DF(LDF), T(*)
CHARACTER(1) | TAIL(LTAIL)

3 Description

The deviate, t pi associated with the lower tail probability, pi, of the Student's t-distribution with νi degrees of freedom is defined as the solution to
P Ti < t pi :νi = pi = Γ νi+1 / 2 νi π Γ νi/2 ∫ -∞ t pi 1 + Ti 2 νi - νi+1 / 2 d Ti ,   νi ≥ 1 ; ​ -∞ < t pi < ∞ .
For νi=1​ or ​2 the integral equation is easily solved for t pi.
For other values of νi<3 a transformation to the beta distribution is used and the result obtained from G01FEF.
For νi≥3 an inverse asymptotic expansion of Cornish–Fisher type is used. The algorithm is described by Hill (1970).
The input arrays to this routine are designed to allow maximum flexibility in the supply of vector arguments by re-using elements of any arrays that are shorter than the total number of evaluations required. See Section 2.6 in the G01 Chapter Introduction for further information.

4 References

Hastings N A J and Peacock J B (1975) Statistical Distributions Butterworth
Hill G W (1970) Student's t-distribution Comm. ACM 13(10) 617–619

5 Arguments

1:   LTAIL – INTEGERInput
On entry: the length of the array TAIL.
Constraint: LTAIL>0.
2:   TAIL LTAIL – CHARACTER(1) arrayInput
On entry: indicates which tail the supplied probabilities represent. For j= i-1 mod LTAIL +1 , for i=1,2,…,max LTAIL,LP,LDF:
TAIL j='L'
The lower tail probability, i.e., pi = P Ti ≤ t pi :νi .
TAIL j='U'
The upper tail probability, i.e., pi = P Ti ≥ t pi :νi .
TAIL j='C'
The two tail (confidence interval) probability,
i.e., pi = P Ti ≤ t pi :νi - P Ti ≤ - t pi :νi .
TAIL j='S'
The two tail (significance level) probability,
i.e., pi = P Ti ≥ t pi :νi + P Ti ≤ - t pi :νi .
Constraint: TAIL j='L', 'U', 'C' or 'S', for j=1,2,…,LTAIL.
3:   LP – INTEGERInput
On entry: the length of the array P.
Constraint: LP>0.
4:   P LP – REAL (KIND=nag_wp) arrayInput
On entry: pi, the probability of the required Student's t-distribution as defined by TAIL with pi=P j, j=i-1 mod LP+1.
Constraint: 0.0<P j<1.0, for j=1,2,…,LP.
5:   LDF – INTEGERInput
On entry: the length of the array DF.
Constraint: LDF>0.
6:   DF LDF – REAL (KIND=nag_wp) arrayInput
On entry: νi, the degrees of freedom of the Student's t-distribution with νi=DF j, j=i-1 mod LDF+1.
Constraint: DF j≥1.0, for j=1,2,…,LDF.
7:   T* – REAL (KIND=nag_wp) arrayOutput
Note: the dimension of the array T must be at least max LTAIL,LP,LDF.
On exit: t pi, the deviates for the Student's t-distribution.
8:   IVALID* – INTEGER arrayOutput
Note: the dimension of the array IVALID must be at least max LTAIL,LP,LDF.
On exit: IVALID i indicates any errors with the input arguments, with
IVALID i=0
No error.
IVALID i=1
On entry, invalid value supplied in TAIL when calculating t pi.
IVALID i=2
On entry, | pi≤0.0,
or | pi≥1.0.
IVALID i=3
On entry, νi<1.0.
IVALID i=4
The solution has failed to converge. The result returned should represent an approximation to the solution.
9:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, at least one value of TAIL, P or DF was invalid, or the solution failed to converge.
Check IVALID for more information.
IFAIL=2
On entry, array size=value.
Constraint: LTAIL>0.
IFAIL=3
On entry, array size=value.
Constraint: LP>0.
IFAIL=4
On entry, array size=value.
Constraint: LDF>0.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

The results should be accurate to five significant digits, for most argument values. The error behaviour for various argument values is discussed in Hill (1970).

8 Parallelism and Performance

G01TBF is not threaded in any implementation.

9 Further Comments

The value t pi may be calculated by using a transformation to the beta distribution and calling G01TEF. This routine allows you to set the required accuracy.

10 Example

This example reads the probability, the tail that probability represents and the degrees of freedom for a number of Student's t-distributions and computes the corresponding deviates.

10.1 Program Text

Program Text (g01tbfe.f90)

10.2 Program Data

Program Data (g01tbfe.d)

10.3 Program Results

Program Results (g01tbfe.r)

G01 Chapter Contents
G01 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


G01TCF : NAG Library, Mark 26

G01 Chapter Contents
G01 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

G01TCF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

G01TCF returns a number of deviates associated with the given probabilities of the χ 2-distribution with real degrees of freedom.

2 Specification

SUBROUTINE G01TCF ( LTAIL, TAIL, LP, P, LDF, DF, X, IVALID, IFAIL)
INTEGER | LTAIL, LP, LDF, IVALID(*), IFAIL
REAL (KIND=nag_wp) | P(LP), DF(LDF), X(*)
CHARACTER(1) | TAIL(LTAIL)

3 Description

The deviate, x pi, associated with the lower tail probability pi of the χ 2-distribution with νi degrees of freedom is defined as the solution to
P Xi ≤ x pi :νi = pi = 1 2 νi/2 Γ νi/2 ∫ 0 x pi e -Xi/2 Xi vi / 2 - 1 d Xi ,   0 ≤ x pi < ∞ ; ​ νi > 0 .
The required x pi is found by using the relationship between a χ 2-distribution and a gamma distribution, i.e., a χ 2-distribution with νi degrees of freedom is equal to a gamma distribution with scale parameter 2 and shape parameter νi/2.
For very large values of νi, greater than 105, Wilson and Hilferty's Normal approximation to the χ 2 is used; see Kendall and Stuart (1969).
The input arrays to this routine are designed to allow maximum flexibility in the supply of vector arguments by re-using elements of any arrays that are shorter than the total number of evaluations required. See Section 2.6 in the G01 Chapter Introduction for further information.

4 References

Best D J and Roberts D E (1975) Algorithm AS 91. The percentage points of the χ 2 distribution Appl. Statist. 24 385–388
Hastings N A J and Peacock J B (1975) Statistical Distributions Butterworth
Kendall M G and Stuart A (1969) The Advanced Theory of Statistics (Volume 1) (3rd Edition) Griffin

5 Arguments

1:   LTAIL – INTEGERInput
On entry: the length of the array TAIL.
Constraint: LTAIL>0.
2:   TAIL LTAIL – CHARACTER(1) arrayInput
On entry: indicates which tail the supplied probabilities represent. For j= i-1 mod LTAIL +1 , for i=1,2,…,max LTAIL,LP,LDF:
TAIL j='L'
The lower tail probability, i.e., pi = P Xi ≤ x pi :νi .
TAIL j='U'
The upper tail probability, i.e., pi = P Xi ≥ x pi :νi .
Constraint: TAIL j='L' or 'U', for j=1,2,…,LTAIL.
3:   LP – INTEGERInput
On entry: the length of the array P.
Constraint: LP>0.
4:   P LP – REAL (KIND=nag_wp) arrayInput
On entry: pi, the probability of the required χ 2-distribution as defined by TAIL with pi=P j, j=i-1 mod LP+1.
Constraints:
  • if TAIL k='L', 0.0≤P j<1.0;
  • otherwise 0.0<P j≤1.0.
Where k=i-1 mod LTAIL+1 and j=i-1 mod LP+1.
5:   LDF – INTEGERInput
On entry: the length of the array DF.
Constraint: LDF>0.
6:   DF LDF – REAL (KIND=nag_wp) arrayInput
On entry: νi, the degrees of freedom of the χ 2-distribution with νi=DF j, j=i-1 mod LDF+1.
Constraint: DF j>0.0, for j=1,2,…,LDF.
7:   X* – REAL (KIND=nag_wp) arrayOutput
Note: the dimension of the array X must be at least max LTAIL,LP,LDF.
On exit: x pi, the deviates for the χ 2-distribution.
8:   IVALID* – INTEGER arrayOutput
Note: the dimension of the array IVALID must be at least max LTAIL,LP,LDF.
On exit: IVALID i indicates any errors with the input arguments, with
IVALID i=0
No error.
IVALID i=1
On entry, invalid value supplied in TAIL when calculating x pi.
IVALID i=2
On entry, invalid value for pi.
IVALID i=3
On entry, νi≤0.0.
IVALID i=4
pi is too close to 0.0 or 1.0 for the result to be calculated.
IVALID i=5
The solution has failed to converge. The result should be a reasonable approximation.
9:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, at least one value of TAIL, P or DF was invalid, or the solution failed to converge.
Check IVALID for more information.
IFAIL=2
On entry, array size=value.
Constraint: LTAIL>0.
IFAIL=3
On entry, array size=value.
Constraint: LP>0.
IFAIL=4
On entry, array size=value.
Constraint: LDF>0.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

The results should be accurate to five significant digits for most argument values. Some accuracy is lost for pi close to 0.0 or 1.0.

8 Parallelism and Performance

G01TCF is not threaded in any implementation.

9 Further Comments

For higher accuracy the relationship described in Section 3 may be used and a direct call to G01TFF made.

10 Example

This example reads lower tail probabilities for several χ 2-distributions, and calculates and prints the corresponding deviates.

10.1 Program Text

Program Text (g01tcfe.f90)

10.2 Program Data

Program Data (g01tcfe.d)

10.3 Program Results

Program Results (g01tcfe.r)

G01 Chapter Contents
G01 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


G01TDF : NAG Library, Mark 26

G01 Chapter Contents
G01 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

G01TDF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

G01TDF returns a number of deviates associated with given probabilities of the F or variance-ratio distribution with real degrees of freedom.

2 Specification

SUBROUTINE G01TDF ( LTAIL, TAIL, LP, P, LDF1, DF1, LDF2, DF2, F, IVALID, IFAIL)
INTEGER | LTAIL, LP, LDF1, LDF2, IVALID(*), IFAIL
REAL (KIND=nag_wp) | P(LP), DF1(LDF1), DF2(LDF2), F(*)
CHARACTER(1) | TAIL(LTAIL)

3 Description

The deviate, f pi, associated with the lower tail probability, pi, of the F-distribution with degrees of freedom ui and vi is defined as the solution to
P Fi ≤ f pi :ui,vi = pi = u i 12 ui v i 12 vi Γ ui + vi 2 Γ ui 2 Γ vi 2 ∫ 0 f pi Fi 12 ui-2 vi + ui Fi -12 ui + vi d Fi ,
where ui,vi>0; 0≤f pi<∞.
The value of f pi is computed by means of a transformation to a beta distribution, P i βi Bi ≤ βi :ai,bi :
P Fi ≤ f pi :ui,vi = P i βi Bi ≤ ui f pi ui f pi + vi : ui / 2 , vi / 2
and using a call to G01TEF.
For very large values of both ui and vi, greater than 105, a Normal approximation is used. If only one of ui or vi is greater than 105 then a χ 2 approximation is used; see Abramowitz and Stegun (1972).
The input arrays to this routine are designed to allow maximum flexibility in the supply of vector arguments by re-using elements of any arrays that are shorter than the total number of evaluations required. See Section 2.6 in the G01 Chapter Introduction for further information.

4 References

Abramowitz M and Stegun I A (1972) Handbook of Mathematical Functions (3rd Edition) Dover Publications
Hastings N A J and Peacock J B (1975) Statistical Distributions Butterworth

5 Arguments

1:   LTAIL – INTEGERInput
On entry: the length of the array TAIL.
Constraint: LTAIL>0.
2:   TAIL LTAIL – CHARACTER(1) arrayInput
On entry: indicates which tail the supplied probabilities represent. For j= i-1 mod LTAIL +1 , for i=1,2,…,max LTAIL,LP,LDF1,LDF2:
TAIL j='L'
The lower tail probability, i.e., pi = P Fi ≤ f pi : ui , vi .
TAIL j='U'
The upper tail probability, i.e., pi = P Fi ≥ f pi : ui , vi .
Constraint: TAIL j='L' or 'U', for j=1,2,…,LTAIL.
3:   LP – INTEGERInput
On entry: the length of the array P.
Constraint: LP>0.
4:   P LP – REAL (KIND=nag_wp) arrayInput
On entry: pi, the probability of the required F-distribution as defined by TAIL with pi=P j, j=i-1 mod LP+1.
Constraints:
  • if TAIL k='L', 0.0≤P j<1.0;
  • otherwise 0.0<P j≤1.0.
Where k=i-1 mod LTAIL+1 and j=i-1 mod LP+1.
5:   LDF1 – INTEGERInput
On entry: the length of the array DF1.
Constraint: LDF1>0.
6:   DF1 LDF1 – REAL (KIND=nag_wp) arrayInput
On entry: ui, the degrees of freedom of the numerator variance with ui=DF1 j, j=i-1 mod LDF1+1.
Constraint: DF1 j>0.0, for j=1,2,…,LDF1.
7:   LDF2 – INTEGERInput
On entry: the length of the array DF2.
Constraint: LDF2>0.
8:   DF2 LDF2 – REAL (KIND=nag_wp) arrayInput
On entry: vi, the degrees of freedom of the denominator variance with vi=DF2 j, j=i-1 mod LDF2+1.
Constraint: DF2 j>0.0, for j=1,2,…,LDF2.
9:   F* – REAL (KIND=nag_wp) arrayOutput
Note: the dimension of the array F must be at least max LTAIL,LP,LDF1,LDF2.
On exit: f pi, the deviates for the F-distribution.
10:   IVALID* – INTEGER arrayOutput
Note: the dimension of the array IVALID must be at least max LTAIL,LP,LDF1,LDF2.
On exit: IVALID i indicates any errors with the input arguments, with
IVALID i=0
No error.
IVALID i=1
On entry, invalid value supplied in TAIL when calculating f pi.
IVALID i=2
On entry, invalid value for pi.
IVALID i=3
On entry, | ui≤0.0,
or | vi≤0.0.
IVALID i=4
The solution has not converged. The result should still be a reasonable approximation to the solution.
IVALID i=5
The value of pi is too close to 0.0 or 1.0 for the result to be computed. This will only occur when the large sample approximations are used.
11:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, because for this routine the values of the output arguments may be useful even if IFAIL≠0 on exit, the recommended value is -1. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Note: G01TDF may return useful information for one or more of the following detected errors or warnings.
Errors or warnings detected by the routine:
IFAIL=1
On entry, at least one value of TAIL, P, DF1, DF2 was invalid, or the solution failed to converge.
Check IVALID for more information.
IFAIL=2
On entry, array size=value.
Constraint: LTAIL>0.
IFAIL=3
On entry, array size=value.
Constraint: LP>0.
IFAIL=4
On entry, array size=value.
Constraint: LDF1>0.
IFAIL=5
On entry, array size=value.
Constraint: LDF2>0.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

The result should be accurate to five significant digits.

8 Parallelism and Performance

G01TDF is not threaded in any implementation.

9 Further Comments

For higher accuracy G01TEF can be used along with the transformations given in Section 3.

10 Example

This example reads the lower tail probabilities for several F-distributions, and calculates and prints the corresponding deviates.

10.1 Program Text

Program Text (g01tdfe.f90)

10.2 Program Data

Program Data (g01tdfe.d)

10.3 Program Results

Program Results (g01tdfe.r)

G01 Chapter Contents
G01 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


G01TEF : NAG Library, Mark 26

G01 Chapter Contents
G01 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

G01TEF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

G01TEF returns a number of deviates associated with given probabilities of the beta distribution.

2 Specification

SUBROUTINE G01TEF ( LTAIL, TAIL, LP, P, LA, A, LB, B, TOL, BETA, IVALID, IFAIL)
INTEGER | LTAIL, LP, LA, LB, IVALID(*), IFAIL
REAL (KIND=nag_wp) | P(LP), A(LA), B(LB), TOL, BETA(*)
CHARACTER(1) | TAIL(LTAIL)

3 Description

The deviate, β pi, associated with the lower tail probability, pi, of the beta distribution with parameters ai and bi is defined as the solution to
P Bi ≤ β pi :ai,bi = pi = Γ ai + bi Γ ai Γ bi ∫ 0 β pi Bi ai-1 1-Bi bi-1 d Bi ,   0 ≤ β pi ≤ 1 ; ​ ai , bi > 0 .
The algorithm is a modified version of the Newton–Raphson method, following closely that of Cran et al. (1977).
An initial approximation, β i 0, to β pi is found (see Cran et al. (1977)), and the Newton–Raphson iteration
βk = β k-1 - fi β k-1 fi′ β k-1 ,
where fi βk = P Bi ≤ βk :ai,bi - pi is used, with modifications to ensure that βk remains in the range 0,1.
The input arrays to this routine are designed to allow maximum flexibility in the supply of vector arguments by re-using elements of any arrays that are shorter than the total number of evaluations required. See Section 2.6 in the G01 Chapter Introduction for further information.

4 References

Cran G W, Martin K J and Thomas G E (1977) Algorithm AS 109. Inverse of the incomplete beta function ratio Appl. Statist. 26 111–114
Hastings N A J and Peacock J B (1975) Statistical Distributions Butterworth

5 Arguments

1:   LTAIL – INTEGERInput
On entry: the length of the array TAIL.
Constraint: LTAIL>0.
2:   TAIL LTAIL – CHARACTER(1) arrayInput
On entry: indicates which tail the supplied probabilities represent. For j= i-1 mod LTAIL +1 , for i=1,2,…,max LTAIL,LP,LA,LB:
TAIL j='L'
The lower tail probability, i.e., pi = P Bi ≤ β pi : ai , bi .
TAIL j='U'
The upper tail probability, i.e., pi = P Bi ≥ β pi : ai , bi .
Constraint: TAIL j='L' or 'U', for j=1,2,…,LTAIL.
3:   LP – INTEGERInput
On entry: the length of the array P.
Constraint: LP>0.
4:   P LP – REAL (KIND=nag_wp) arrayInput
On entry: pi, the probability of the required beta distribution as defined by TAIL with pi=P j, j=i-1 mod LP+1.
Constraint: 0.0≤P j≤1.0, for j=1,2,…,LP.
5:   LA – INTEGERInput
On entry: the length of the array A.
Constraint: LA>0.
6:   A LA – REAL (KIND=nag_wp) arrayInput
On entry: ai, the first parameter of the required beta distribution with ai=A j, j=i-1 mod LA+1.
Constraint: 0.0<A j≤106, for j=1,2,…,LA.
7:   LB – INTEGERInput
On entry: the length of the array B.
Constraint: LB>0.
8:   B LB – REAL (KIND=nag_wp) arrayInput
On entry: bi, the second parameter of the required beta distribution with bi=B j, j=i-1 mod LB+1.
Constraint: 0.0<B j≤106, for j=1,2,…,LB.
9:   TOL – REAL (KIND=nag_wp)Input
On entry: the relative accuracy required by you in the results. If G01TEF is entered with TOL greater than or equal to 1.0 or less than 10×machine precision (see X02AJF), then the value of 10×machine precision is used instead.
10:   BETA* – REAL (KIND=nag_wp) arrayOutput
Note: the dimension of the array BETA must be at least max LTAIL,LP,LA,LB.
On exit: β pi, the deviates for the beta distribution.
11:   IVALID* – INTEGER arrayOutput
Note: the dimension of the array IVALID must be at least max LTAIL,LP,LA,LB.
On exit: IVALID i indicates any errors with the input arguments, with
IVALID i=0
No error.
IVALID i=1
On entry, invalid value supplied in TAIL when calculating β pi.
IVALID i=2
On entry, | pi<0.0,
or | pi>1.0.
IVALID i=3
On entry, | ai≤0.0,
or | ai>106,
or | bi≤0.0,
or | bi>106.
IVALID i=4
The solution has not converged but the result should be a reasonable approximation to the solution.
IVALID i=5
Requested accuracy not achieved when calculating the beta probability. The result should be a reasonable approximation to the correct solution.
12:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, because for this routine the values of the output arguments may be useful even if IFAIL≠0 on exit, the recommended value is -1. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Note: G01TEF may return useful information for one or more of the following detected errors or warnings.
Errors or warnings detected by the routine:
IFAIL=1
On entry, at least one value of TAIL, P, A, or B was invalid, or the solution failed to converge.
Check IVALID for more information.
IFAIL=2
On entry, array size=value.
Constraint: LTAIL>0.
IFAIL=3
On entry, array size=value.
Constraint: LP>0.
IFAIL=4
On entry, array size=value.
Constraint: LA>0.
IFAIL=5
On entry, array size=value.
Constraint: LB>0.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

The required precision, given by TOL, should be achieved in most circumstances.

8 Parallelism and Performance

G01TEF is not threaded in any implementation.

9 Further Comments

The typical timing will be several times that of G01SEF and will be very dependent on the input argument values. See G01SEF for further comments on timings.

10 Example

This example reads lower tail probabilities for several beta distributions and calculates and prints the corresponding deviates.

10.1 Program Text

Program Text (g01tefe.f90)

10.2 Program Data

Program Data (g01tefe.d)

10.3 Program Results

Program Results (g01tefe.r)

G01 Chapter Contents
G01 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


G01TFF : NAG Library, Mark 26

G01 Chapter Contents
G01 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

G01TFF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

G01TFF returns a number of deviates associated with given probabilities of the gamma distribution.

2 Specification

SUBROUTINE G01TFF ( LTAIL, TAIL, LP, P, LA, A, LB, B, TOL, G, IVALID, IFAIL)
INTEGER | LTAIL, LP, LA, LB, IVALID(*), IFAIL
REAL (KIND=nag_wp) | P(LP), A(LA), B(LB), TOL, G(*)
CHARACTER(1) | TAIL(LTAIL)

3 Description

The deviate, g pi, associated with the lower tail probability, pi, of the gamma distribution with shape parameter αi and scale parameter βi, is defined as the solution to
P Gi ≤ g pi :αi,βi = pi = 1 βi αi Γ αi ∫ 0 g pi ei - Gi / βi Gi αi-1 d Gi ,   0 ≤ g pi < ∞ ; ​ αi , βi > 0 .
The method used is described by Best and Roberts (1975) making use of the relationship between the gamma distribution and the χ 2-distribution.
Let yi=2 g piβi . The required yi is found from the Taylor series expansion
yi=y 0+∑r Cr y 0 r! Ei ϕ y 0 r,
where y 0 is a starting approximation
  • C 1 ui=1,
  • C r+1 ui=rΨ+ d d ui Cr ui,
  • Ψi=12- αi-1 ui ,
  • Ei=pi-∫0 y 0 ϕi ui d ui,
  • ϕi ui= 1 2 αi Γ αi ei-ui/2ui αi-1.
For most values of pi and αi the starting value
y 01=2 αi zi⁢1 9 αi +1-1 9 αi 3
is used, where zi is the deviate associated with a lower tail probability of pi for the standard Normal distribution.
For pi close to zero,
y 02= piαi 2 αi Γ αi 1/αi
is used.
For large pi values, when y 01>4.4 αi+6.0,
y 03=-2 ln 1-pi-αi-1 ln 12 y 01+ln Γ αi
is found to be a better starting value than y 01.
For small αi αi≤0.16, pi is expressed in terms of an approximation to the exponential integral and y 04 is found by Newton–Raphson iterations.
Seven terms of the Taylor series are used to refine the starting approximation, repeating the process if necessary until the required accuracy is obtained.
The input arrays to this routine are designed to allow maximum flexibility in the supply of vector arguments by re-using elements of any arrays that are shorter than the total number of evaluations required. See Section 2.6 in the G01 Chapter Introduction for further information.

4 References

Best D J and Roberts D E (1975) Algorithm AS 91. The percentage points of the χ 2 distribution Appl. Statist. 24 385–388

5 Arguments

1:   LTAIL – INTEGERInput
On entry: the length of the array TAIL.
Constraint: LTAIL>0.
2:   TAIL LTAIL – CHARACTER(1) arrayInput
On entry: indicates which tail the supplied probabilities represent. For j= i-1 mod LTAIL +1 , for i=1,2,…,max LTAIL,LP,LA,LB:
TAIL j='L'
The lower tail probability, i.e., pi = P Gi ≤ g pi : αi , βi .
TAIL j='U'
The upper tail probability, i.e., pi = P Gi ≥ g pi : αi , βi .
Constraint: TAIL j='L' or 'U', for j=1,2,…,LTAIL.
3:   LP – INTEGERInput
On entry: the length of the array P.
Constraint: LP>0.
4:   P LP – REAL (KIND=nag_wp) arrayInput
On entry: pi, the probability of the required gamma distribution as defined by TAIL with pi=P j, j=i-1 mod LP+1.
Constraints:
  • if TAIL k='L', 0.0≤P j<1.0;
  • otherwise 0.0<P j≤1.0.
Where k=i-1 mod LTAIL+1 and j=i-1 mod LP+1.
5:   LA – INTEGERInput
On entry: the length of the array A.
Constraint: LA>0.
6:   A LA – REAL (KIND=nag_wp) arrayInput
On entry: αi, the first parameter of the required gamma distribution with αi=A j, j=i-1 mod LA+1.
Constraint: 0.0<A j≤106, for j=1,2,…,LA.
7:   LB – INTEGERInput
On entry: the length of the array B.
Constraint: LB>0.
8:   B LB – REAL (KIND=nag_wp) arrayInput
On entry: βi, the second parameter of the required gamma distribution with βi=B j, j=i-1 mod LB+1.
Constraint: B j>0.0, for j=1,2,…,LB.
9:   TOL – REAL (KIND=nag_wp)Input
On entry: the relative accuracy required by you in the results. If G01TFF is entered with TOL greater than or equal to 1.0 or less than 10×machine precision (see X02AJF), then the value of 10×machine precision is used instead.
10:   G* – REAL (KIND=nag_wp) arrayOutput
Note: the dimension of the array G must be at least max LTAIL,LP,LA,LB.
On exit: g pi, the deviates for the gamma distribution.
11:   IVALID* – INTEGER arrayOutput
Note: the dimension of the array IVALID must be at least max LTAIL,LP,LA,LB.
On exit: IVALID i indicates any errors with the input arguments, with
IVALID i=0
No error.
IVALID i=1
On entry, invalid value supplied in TAIL when calculating g pi.
IVALID i=2
On entry, invalid value for pi.
IVALID i=3
On entry, | αi≤0.0,
or | αi>106,
or | βi≤0.0.
IVALID i=4
pi is too close to 0.0 or 1.0 to enable the result to be calculated.
IVALID i=5
The solution has failed to converge. The result may be a reasonable approximation.
12:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, because for this routine the values of the output arguments may be useful even if IFAIL≠0 on exit, the recommended value is -1. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Note: G01TFF may return useful information for one or more of the following detected errors or warnings.
Errors or warnings detected by the routine:
IFAIL=1
On entry, at least one value of TAIL, P, A, or B was invalid.
Check IVALID for more information.
IFAIL=2
On entry, array size=value.
Constraint: LTAIL>0.
IFAIL=3
On entry, array size=value.
Constraint: LP>0.
IFAIL=4
On entry, array size=value.
Constraint: LA>0.
IFAIL=5
On entry, array size=value.
Constraint: LB>0.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

In most cases the relative accuracy of the results should be as specified by TOL. However, for very small values of αi or very small values of pi there may be some loss of accuracy.

8 Parallelism and Performance

G01TFF is not threaded in any implementation.

9 Further Comments

None.

10 Example

This example reads lower tail probabilities for several gamma distributions, and calculates and prints the corresponding deviates until the end of data is reached.

10.1 Program Text

Program Text (g01tffe.f90)

10.2 Program Data

Program Data (g01tffe.d)

10.3 Program Results

Program Results (g01tffe.r)

G01 Chapter Contents
G01 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


G01WAF : NAG Library, Mark 26

G01 Chapter Contents
G01 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

G01WAF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

G01WAF calculates the mean and, optionally, the standard deviation using a rolling window for an arbitrary sized data stream.

2 Specification

SUBROUTINE G01WAF ( M, NB, X, IWT, WT, PN, RMEAN, RSD, LRSD, RCOMM, LRCOMM, IFAIL)
INTEGER | M, NB, IWT, PN, LRSD, LRCOMM, IFAIL
REAL (KIND=nag_wp) | X(NB), WT(*), RMEAN(max(0,NB+min(0,PN-M+1))), RSD(LRSD), RCOMM(LRCOMM)

3 Description

Given a sample of n observations, denoted by x = xi : i=1,2,…,n and a set of weights, w = wj : j=1,2,…,m , G01WAF calculates the mean and, optionally, the standard deviation, in a rolling window of length m.
For the ith window the mean is defined as
μi = ∑ j=1 m wj ⁢ x i+j-1 W (1)
and the standard deviation as
σi = ∑ j=1 m wj ⁢ x i+j-1 - μi 2 W - ∑ j=1 m wj 2 W (2)
with W = ∑ j=1 m wj .
Four different types of weighting are possible:
(i) No weights (wj=1)
When no weights are required both the mean and standard deviations can be calculated in an iterative manner, with
μ i+1= μi + x i+m - xi m σ i+1 2 = m-1 ⁢ σi 2 + x i+m - μi 2 - xi - μi 2 - x i+m - xi 2 m
where the initial values μ1 and σ1 are obtained using the one pass algorithm of West (1979).
(ii) Each observation has its own weight
In this case, rather than supplying a vector of m weights a vector of n weights is supplied instead, v=vj:j=1,2,…,n and wj=v i+j-1 in (1) and (2).
If the standard deviations are not required then the mean is calculated using the iterative formula:
W i+1= Wi+ v i+m - vi μ i+1= μi + Wi-1 ⁢ v i+m ⁢ x i+m - vi ⁢ xi
where W1= ∑ i=1 m vi and μ1 = W 1-1 ⁢ ∑ i=1 m vi ⁢ xi .
If both the mean and standard deviation are required then the one pass algorithm of West (1979) is used in each window.
(iii) Each position in the window has its own weight
This is the case as described in (1) and (2), where the weight given to each observation differs depending on which summary is being produced. When these types of weights are specified both the mean and standard deviation are calculated by applying the one pass algorithm of West (1979) multiple times.
(iv) Each position in the window has a weight equal to its position number (wj=j)
This is a special case of (iii).
If the standard deviations are not required then the mean is calculated using the iterative formula:
S i+1= Si+ x i+m - xi μ i+1= μi + 2 m ⁢ x i+m - Si m ⁢ m+1
where S1= ∑ i=1 m xi and μ1 = 2 ⁢ m 2 + m -1 S 1 .
If both the mean and standard deviation are required then the one pass algorithm of West is applied multiple times.
For large datasets, or where all the data is not available at the same time, x (and if each observation has its own weight, v) can be split into arbitrary sized blocks and G01WAF called multiple times.

4 References

Chan T F, Golub G H and Leveque R J (1982) Updating Formulae and a Pairwise Algorithm for Computing Sample Variances Compstat, Physica-Verlag
West D H D (1979) Updating mean and variance estimates: An improved method Comm. ACM 22 532–555

5 Arguments

1:   M – INTEGERInput
On entry: m, the length of the rolling window.
If PN≠0, M must be unchanged since the last call to G01WAF.
Constraint: M≥1.
2:   NB – INTEGERInput
On entry: b, the number of observations in the current block of data. The size of the block of data supplied in X (and when IWT=1, WT) can vary; therefore NB can change between calls to G01WAF.
Constraints:
  • NB≥0;
  • if LRCOMM=0, NB≥M.
3:   X NB – REAL (KIND=nag_wp) arrayInput
On entry: the current block of observations, corresponding to xi, for i=k+1,…,k+b, where k is the number of observations processed so far and b is the size of the current block of data.
4:   IWT – INTEGERInput
On entry: the type of weighting to use.
IWT=0
No weights are used.
IWT=1
Each observation has its own weight.
IWT=2
Each position in the window has its own weight.
IWT=3
Each position in the window has a weight equal to its position number.
If PN≠0, IWT must be unchanged since the last call to G01WAF.
Constraint: IWT=0, 1, 2 or 3.
5:   WT* – REAL (KIND=nag_wp) arrayInput
Note: the dimension of the array WT must be at least NB if IWT=1 and at least M if IWT=2.
On entry: the user-supplied weights.
If IWT=1, WT i=ν i+k, for i=1,2,…,b.
If IWT=2, WT j=wj, for j=1,2,…,m.
Otherwise, WT is not referenced.
Constraints:
  • if IWT=1, WT i≥0, for i=1,2,…,NB;
  • if IWT=2, WT 1≠0 and ∑j=1 m WT j>0;
  • if IWT=2 and LRSD≠0, WT j≥0, for j=1,2,…,M.
6:   PN – INTEGERInput/Output
On entry: k, the number of observations processed so far. On the first call to G01WAF, or when starting to summarise a new dataset, PN must be set to 0.
If PN≠0, it must be the same value as returned by the last call to G01WAF.
On exit: k+b, the updated number of observations processed so far.
Constraint: PN≥0.
7:   RMEAN max 0,NB+min 0,PN-M+1 – REAL (KIND=nag_wp) arrayOutput
On exit: μl, the (weighted) moving averages, for l=1,2,…,b+min 0,k-m+1. Therefore, μl is the mean of the data in the window that ends on X l+m-min k,m-1-1.
If, on entry, PN≥M-1, i.e., at least one windows worth of data has been previously processed, then RMEAN l is the summary corresponding to the window that ends on X l. On the other hand, if, on entry, PN=0, i.e., no data has been previously processed, then RMEAN l is the summary corresponding to the window that ends on X M+l-1 (or, equivalently, starts on X l).
8:   RSD LRSD – REAL (KIND=nag_wp) arrayOutput
On exit: if LRSD≠0 then σl, the (weighted) standard deviation. The ordering of RSD is the same as the ordering of RMEAN.
If LRSD=0, RSD is not referenced.
9:   LRSD – INTEGERInput
On entry: the dimension of the array RSD as declared in the (sub)program from which G01WAF is called. If the standard deviations are not required then LRSD should be set to zero.
Constraint: LRSD=0 or LRSD≥max 0,NB+min 0,PN-M+1.
10:   RCOMM LRCOMM – REAL (KIND=nag_wp) arrayCommunication Array
On entry: communication array, used to store information between calls to G01WAF. If LRCOMM=0, RCOMM is not referenced and all the data must be supplied in one go.
11:   LRCOMM – INTEGERInput
On entry: the dimension of the array RCOMM as declared in the (sub)program from which G01WAF is called.
Constraint: LRCOMM=0 or LRCOMM≥2⁢M+20.
12:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=11
On entry, M=value.
Constraint: M≥1.
IFAIL=12
On entry, M=value.
On entry at previous call, M=value.
Constraint: if PN>0, M must be unchanged since previous call.
IFAIL=21
On entry, NB=value.
Constraint: NB≥0.
IFAIL=22
On entry, NB=value, M=value.
Constraint: if LRCOMM=0, NB≥M.
IFAIL=41
On entry, IWT=value.
Constraint: IWT=0, 1, 2 or 3.
IFAIL=42
On entry, IWT=value.
On entry at previous call, IWT=value.
Constraint: if PN>0, IWT must be unchanged since previous call.
IFAIL=51
On entry, WT value=value.
Constraint: WT i≥0.
IFAIL=52
On entry, WT 1=value.
Constraint: if IWT=2, WT 1>0.
IFAIL=53
On entry, at least one window had all zero weights.
IFAIL=54
On entry, unable to calculate at least one standard deviation due to the weights supplied.
IFAIL=55
On entry, sum of weights supplied in WT is value.
Constraint: if IWT=2, the sum of the weights >0.
IFAIL=61
On entry, PN=value.
Constraint: PN≥0.
IFAIL=62
On entry, PN=value.
On exit from previous call, PN=value.
Constraint: if PN>0, PN must be unchanged since previous call.
IFAIL=91
On entry, LRSD=value.
Constraint: LRSD=0 or LRSD≥value.
IFAIL=101
RCOMM has been corrupted between calls.
IFAIL=111
On entry, LRCOMM=value.
Constraint: LRCOMM≥value.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

Not applicable.

8 Parallelism and Performance

G01WAF is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
G01WAF makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The more data that is supplied to G01WAF in one call, i.e., the larger NB is, the more efficient the routine will be.

10 Example

This example calculates Spencer's 15-point moving average for the change in rate of the Earth's rotation between 1821 and 1850. The data is supplied in three chunks, the first consisting of five observations, the second 10 observations and the last 15 observations.

10.1 Program Text

Program Text (g01wafe.f90)

10.2 Program Data

Program Data (g01wafe.d)

10.3 Program Results

Program Results (g01wafe.r)

This example plot shows the smoothing effect of using different length rolling windows on the mean and standard deviation. Two different window lengths, m=5 and 10, are used to produce the unweighted rolling mean and standard deviations for the change in rate of the Earth's rotation between 1821 and 1850. The values of the rolling mean and standard deviations are plotted at the centre points of their respective windows.
GnuplotProduced by GNUPLOT 4.6 patchlevel 3 100 200 300 400 500 600 700 1820 1825 1830 1835 1840 1845 1850 Standard Deviation Year gnuplot_plot_1a gnuplot_plot_2a −2500 −2000 −1500 −1000 −500 0 500 1000 1500 Change in Day Length Example Program Raw data, mean and standard deviation from a rolling window of changes in rate of Earth's rotation (μs), 1821 to 1850 gnuplot_plot_1b window length (m) = 10 gnuplot_plot_2b window length (m) = 5 gnuplot_plot_3b
G01 Chapter Contents
G01 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


G01ZUF : NAG Library, Mark 26

G01 Chapter Contents
G01 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

G01ZUF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
10 Example

1 Purpose

G01ZUF is used to initialize routines G01EUF and G01MUF.
It is intended to be used before a call to G01EUF or G01MUF.

2 Specification

SUBROUTINE G01ZUF ( RKAPPA, BETA2, MODE, XL, XU, RCOMM, IFAIL)
INTEGER | MODE, IFAIL
REAL (KIND=nag_wp) | RKAPPA, BETA2, XL, XU, RCOMM(322)

3 Description

G01ZUF initializes the array RCOMM for use by G01EUF or G01MUF in the evaluation of the Vavilov functions ϕV λ;κ,β 2 and ΦV λ;κ,β 2 respectively.
Multiple calls to G01EUF or G01MUF can be made following a single call to G01ZUF, provided that RKAPPA or BETA2 do not change, and that either all calls are to G01EUF or all calls are to G01MUF. If you wish to call both G01EUF and G01MUF, then you will need to initialize both separately.

4 References

Schorr B (1974) Programs for the Landau and the Vavilov distributions and the corresponding random numbers Comp. Phys. Comm. 7 215–224

5 Arguments

1:   RKAPPA – REAL (KIND=nag_wp)Input
On entry: the argument κ of the function.
Constraint: 0.01≤RKAPPA≤10.0.
2:   BETA2 – REAL (KIND=nag_wp)Input
On entry: the argument β 2 of the function.
Constraint: 0.0≤BETA2≤1.0.
3:   MODE – INTEGERInput
On entry: if MODE=0, then G01MUF is to be called after the call to G01ZUF. Otherwise, G01EUF is to be called.
4:   XL – REAL (KIND=nag_wp)Output
On exit: xl, a threshold value below which ϕV λ;κ,β 2 will be set to zero by G01MUF and ΦV λ;κ,β 2 will be set to zero by G01EUF if λ<xl.
5:   XU – REAL (KIND=nag_wp)Output
On exit: xu, a threshold value above which ϕV λ;κ,β 2 will be set to zero by G01MUF and ΦV λ;κ,β 2 will be set to unity by G01EUF if λ>xu.
6:   RCOMM 322 – REAL (KIND=nag_wp) arrayCommunication Array
On exit: this argument should be passed unchanged to G01EUF or G01MUF.
7:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, | RKAPPA<0.01,
or | RKAPPA>10.0,
or | BETA2<0.0,
or | BETA2>1.0.
IFAIL=2
The initialization has been abandoned due to an internal error. This error exit is unlikely to occur, but if it does change the values of RKAPPA and/or BETA2 and rerun G01ZUF.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

At least five significant digits are usually correct.

8 Parallelism and Performance

G01ZUF is not threaded in any implementation.

9 Further Comments

None.

10 Example

See Section 10 in G01MUF and G01EUF.
G01 Chapter Contents
G01 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


G02AAF : NAG Library, Mark 26

G02 Chapter Contents
G02 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

G02AAF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

G02AAF computes the nearest correlation matrix, in the Frobenius norm, to a given square, input matrix.

2 Specification

SUBROUTINE G02AAF ( G, LDG, N, ERRTOL, MAXITS, MAXIT, X, LDX, ITER, FEVAL, NRMGRD, IFAIL)
INTEGER | LDG, N, MAXITS, MAXIT, LDX, ITER, FEVAL, IFAIL
REAL (KIND=nag_wp) | G(LDG,N), ERRTOL, X(LDX,N), NRMGRD

3 Description

A correlation matrix may be characterised as a real square matrix that is symmetric, has a unit diagonal and is positive semidefinite.
G02AAF applies an inexact Newton method to a dual formulation of the problem, as described by Qi and Sun (2006). It applies the improvements suggested by Borsdorf and Higham (2010).

4 References

Borsdorf R and Higham N J (2010) A preconditioned (Newton) algorithm for the nearest correlation matrix IMA Journal of Numerical Analysis 30(1) 94–107
Qi H and Sun D (2006) A quadratically convergent Newton method for computing the nearest correlation matrix SIAM J. Matrix AnalAppl 29(2) 360–385

5 Arguments

1:   G LDGN – REAL (KIND=nag_wp) arrayInput/Output
On entry: G, the initial matrix.
On exit: a symmetric matrix 12 G+GT with the diagonal set to I.
2:   LDG – INTEGERInput
On entry: the first dimension of the array G as declared in the (sub)program from which G02AAF is called.
Constraint: LDG≥N.
3:   N – INTEGERInput
On entry: the size of the matrix G.
Constraint: N>0.
4:   ERRTOL – REAL (KIND=nag_wp)Input
On entry: the termination tolerance for the Newton iteration. If ERRTOL≤0.0 then N×machine precision is used.
5:   MAXITS – INTEGERInput
On entry: MAXITS specifies the maximum number of iterations used for the iterative scheme used to solve the linear algebraic equations at each Newton step.
If MAXITS≤0, 2×N is used.
6:   MAXIT – INTEGERInput
On entry: specifies the maximum number of Newton iterations.
If MAXIT≤0, 200 is used.
7:   X LDXN – REAL (KIND=nag_wp) arrayOutput
On exit: contains the nearest correlation matrix.
8:   LDX – INTEGERInput
On entry: the first dimension of the array X as declared in the (sub)program from which G02AAF is called.
Constraint: LDX≥N.
9:   ITER – INTEGEROutput
On exit: the number of Newton steps taken.
10:   FEVAL – INTEGEROutput
On exit: the number of function evaluations of the dual problem.
11:   NRMGRD – REAL (KIND=nag_wp)Output
On exit: the norm of the gradient of the last Newton step.
12:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, LDG=value and N=value.
Constraint: LDG≥N.
On entry, LDX=value and N=value.
Constraint: LDX≥N.
On entry, N=value.
Constraint: N>0.
IFAIL=2
Newton iteration fails to converge in value iterations.
IFAIL=3
Machine precision is limiting convergence.
The array returned in X may still be of interest.
IFAIL=4
An intermediate eigenproblem could not be solved. This should not occur. Please contact NAG with details of your call.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

The returned accuracy is controlled by ERRTOL and limited by machine precision.

8 Parallelism and Performance

G02AAF is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
G02AAF makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

Arrays are internally allocated by G02AAF. The total size of these arrays is 11×N+3×N×N+max 2×N×N+6×N+1,120+9×N real elements and 5×N+3 integer elements.

10 Example

This example finds the nearest correlation matrix to:
G = 2 -1 0 0 -1 2 -1 0 0 -1 2 -1 0 0 -1 2

10.1 Program Text

Program Text (g02aafe.f90)

10.2 Program Data

Program Data (g02aafe.d)

10.3 Program Results

Program Results (g02aafe.r)

G02 Chapter Contents
G02 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


G02ABF : NAG Library, Mark 26

G02 Chapter Contents
G02 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

G02ABF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

G02ABF computes the nearest correlation matrix, in the Frobenius norm or weighted Frobenius norm, and optionally with bounds on the eigenvalues, to a given square, input matrix.

2 Specification

SUBROUTINE G02ABF ( G, LDG, N, OPT, ALPHA, W, ERRTOL, MAXITS, MAXIT, X, LDX, ITER, FEVAL, NRMGRD, IFAIL)
INTEGER | LDG, N, MAXITS, MAXIT, LDX, ITER, FEVAL, IFAIL
REAL (KIND=nag_wp) | G(LDG,N), ALPHA, W(N), ERRTOL, X(LDX,N), NRMGRD
CHARACTER(1) | OPT

3 Description

Finds the nearest correlation matrix X by minimizing 12 G-X 2 where G is an approximate correlation matrix.
The norm can either be the Frobenius norm or the weighted Frobenius norm 12 W 12 G-X W 12 F 2 .
You can optionally specify a lower bound on the eigenvalues, α, of the computed correlation matrix, forcing the matrix to be positive definite, 0<α<1.
Note that if the weights vary by several orders of magnitude from one another the algorithm may fail to converge.

4 References

Borsdorf R and Higham N J (2010) A preconditioned (Newton) algorithm for the nearest correlation matrix IMA Journal of Numerical Analysis 30(1) 94–107
Qi H and Sun D (2006) A quadratically convergent Newton method for computing the nearest correlation matrix SIAM J. Matrix AnalAppl 29(2) 360–385

5 Arguments

1:   G LDGN – REAL (KIND=nag_wp) arrayInput/Output
On entry: G, the initial matrix.
On exit: G is overwritten.
2:   LDG – INTEGERInput
On entry: the first dimension of the array G as declared in the (sub)program from which G02ABF is called.
Constraint: LDG≥N.
3:   N – INTEGERInput
On entry: the order of the matrix G.
Constraint: N>0.
4:   OPT – CHARACTER(1)Input
On entry: indicates the problem to be solved.
OPT='A'
The lower bound problem is solved.
OPT='W'
The weighted norm problem is solved.
OPT='B'
Both problems are solved.
Constraint: OPT='A', 'W' or 'B'.
5:   ALPHA – REAL (KIND=nag_wp)Input
On entry: the value of α.
If OPT='W', ALPHA need not be set.
Constraint: 0.0<ALPHA<1.0.
6:   W N – REAL (KIND=nag_wp) arrayInput/Output
On entry: the square roots of the diagonal elements of W, that is the diagonal of W 12.
If OPT='A', W is not referenced and need not be set.
On exit: if OPT='W' or 'B', the array is scaled so 0<W i≤1, for i=1,2,…,n.
Constraint: W i>0.0, for i=1,2,…,n.
7:   ERRTOL – REAL (KIND=nag_wp)Input
On entry: the termination tolerance for the Newton iteration. If ERRTOL≤0.0 then N×machine precision is used.
8:   MAXITS – INTEGERInput
On entry: specifies the maximum number of iterations to be used by the iterative scheme to solve the linear algebraic equations at each Newton step.
If MAXITS≤0, 2×N is used.
9:   MAXIT – INTEGERInput
On entry: specifies the maximum number of Newton iterations.
If MAXIT≤0, 200 is used.
10:   X LDXN – REAL (KIND=nag_wp) arrayOutput
On exit: contains the nearest correlation matrix.
11:   LDX – INTEGERInput
On entry: the first dimension of the array X as declared in the (sub)program from which G02ABF is called.
Constraint: LDX≥N.
12:   ITER – INTEGEROutput
On exit: the number of Newton steps taken.
13:   FEVAL – INTEGEROutput
On exit: the number of function evaluations of the dual problem.
14:   NRMGRD – REAL (KIND=nag_wp)Output
On exit: the norm of the gradient of the last Newton step.
15:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, all elements of W were not positive.
On entry, ALPHA=value.
Constraint: 0.0<ALPHA<1.0.
On entry, LDG=value and N=value.
Constraint: LDG≥N.
On entry, LDX=value and N=value.
Constraint: LDX≥N.
On entry, N=value.
Constraint: N>0.
On entry, OPT≠'A', 'W' or 'B'.
IFAIL=2
Newton iteration fails to converge in value iterations. Increase MAXIT or check the call to the routine.
IFAIL=3
The machine precision is limiting convergence. In this instance the returned value of X may be useful.
IFAIL=4
An intermediate eigenproblem could not be solved. This should not occur. Please contact NAG with details of your call.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

The returned accuracy is controlled by ERRTOL and limited by machine precision.

8 Parallelism and Performance

G02ABF is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
G02ABF makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

Arrays are internally allocated by G02ABF. The total size of these arrays is 12×N+3×N×N+max 2×N×N+6×N+1,120+9×N real elements and 5×N+3 integer elements. All allocated memory is freed before return of G02ABF.

10 Example

This example finds the nearest correlation matrix to:
G = 2 -1 0 0 -1 2 -1 0 0 -1 2 -1 0 0 -1 2
weighted by W 12 = diag 100 , 20 , 20 , 20 with minimum eigenvalue 0.02.

10.1 Program Text

Program Text (g02abfe.f90)

10.2 Program Data

Program Data (g02abfe.d)

10.3 Program Results

Program Results (g02abfe.r)

G02 Chapter Contents
G02 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


G02AEF : NAG Library, Mark 26

G02 Chapter Contents
G02 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

G02AEF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

G02AEF computes the factor loading matrix associated with the nearest correlation matrix with k-factor structure, in the Frobenius norm, to a given square, input matrix.

2 Specification

SUBROUTINE G02AEF ( G, LDG, N, K, ERRTOL, MAXIT, X, LDX, ITER, FEVAL, NRMPGD, IFAIL)
INTEGER | LDG, N, K, MAXIT, LDX, ITER, FEVAL, IFAIL
REAL (KIND=nag_wp) | G(LDG,N), ERRTOL, X(LDX,K), NRMPGD

3 Description

A correlation matrix C with k-factor structure may be characterised as a real square matrix that is symmetric, has a unit diagonal, is positive semidefinite and can be written as C=X XT+diag I-X XT, where I is the identity matrix and X has n rows and k columns. X is often referred to as the factor loading matrix.
G02AEF applies a spectral projected gradient method to the modified problem min⁡G-X XT+diag X XT-I F such that xiT 2≤1, for i=1,2,…,n, where xi is the ith row of the factor loading matrix, X, which gives us the solution.

4 References

Birgin E G, Martínez J M and Raydan M (2001) Algorithm 813: SPG–software for convex-constrained optimization ACM Trans. Math. Software 27 340–349
Borsdorf R, Higham N J and Raydan M (2010) Computing a nearest correlation matrix with factor structure. SIAM J. Matrix Anal. Appl. 31(5) 2603–2622

5 Arguments

1:   G LDGN – REAL (KIND=nag_wp) arrayInput/Output
On entry: G, the initial matrix.
On exit: a symmetric matrix 12 G+GT with the diagonal elements set to unity.
2:   LDG – INTEGERInput
On entry: the first dimension of the array G as declared in the (sub)program from which G02AEF is called.
Constraint: LDG≥N.
3:   N – INTEGERInput
On entry: n, the order of the matrix G.
Constraint: N>0.
4:   K – INTEGERInput
On entry: k, the number of factors and columns of X.
Constraint: 0<K≤N.
5:   ERRTOL – REAL (KIND=nag_wp)Input
On entry: the termination tolerance for the projected gradient norm. See references for further details. If ERRTOL≤0.0 then 0.01 is used. This is often a suitable default value.
6:   MAXIT – INTEGERInput
On entry: specifies the maximum number of iterations in the spectral projected gradient method.
If MAXIT≤0, 40000 is used.
7:   X LDXK – REAL (KIND=nag_wp) arrayOutput
On exit: contains the matrix X.
8:   LDX – INTEGERInput
On entry: the first dimension of the array X as declared in the (sub)program from which G02AEF is called.
Constraint: LDX≥N.
9:   ITER – INTEGEROutput
On exit: the number of steps taken in the spectral projected gradient method.
10:   FEVAL – INTEGEROutput
On exit: the number of evaluations of G-X XT+diag X XT-I F.
11:   NRMPGD – REAL (KIND=nag_wp)Output
On exit: the norm of the projected gradient at the final iteration.
12:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, K=value and N=value.
Constraint: 0<K≤N.
On entry, LDG=value and N=value.
Constraint: LDG≥N.
On entry, LDX=value and N=value.
Constraint: LDX≥N.
On entry, N=value.
Constraint: N>0.
IFAIL=2
Spectral gradient method fails to converge in value iterations.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

The returned accuracy is controlled by ERRTOL and limited by machine precision.

8 Parallelism and Performance

G02AEF is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
G02AEF makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

Arrays are internally allocated by G02AEF. The total size of these arrays is N×N+4×N×K+nb+3×N+N+50 real elements and 6×N integer elements. Here nb is the block size required for optimal performance by F08FEF (DSYTRD) and F08FGF (DORMTR) which are called internally. All allocated memory is freed before return of G02AEF.
See G03CAF for constructing the factor loading matrix from a known correlation matrix.

10 Example

This example finds the nearest correlation matrix with k=2 factor structure to:
G = 2 -1 0 0 -1 2 -1 0 0 -1 2 -1 0 0 -1 2

10.1 Program Text

Program Text (g02aefe.f90)

10.2 Program Data

Program Data (g02aefe.d)

10.3 Program Results

Program Results (g02aefe.r)

G02 Chapter Contents
G02 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


G02AJF : NAG Library, Mark 26

G02 Chapter Contents
G02 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

G02AJF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

G02AJF computes the nearest correlation matrix, using element-wise weighting in the Frobenius norm and optionally with bounds on the eigenvalues, to a given square, input matrix.

2 Specification

SUBROUTINE G02AJF ( G, LDG, N, ALPHA, H, LDH, ERRTOL, MAXIT, X, LDX, ITER, NORM, IFAIL)
INTEGER | LDG, N, LDH, MAXIT, LDX, ITER, IFAIL
REAL (KIND=nag_wp) | G(LDG,N), ALPHA, H(LDH,N), ERRTOL, X(LDX,N), NORM

3 Description

G02AJF finds the nearest correlation matrix, X, to an approximate correlation matrix, G, using element-wise weighting, this minimizes H ∘G-X F , where C=A∘B denotes the matrix C with elements C ij=A ij×B ij.
You can optionally specify a lower bound on the eigenvalues, α, of the computed correlation matrix, forcing the matrix to be strictly positive definite, if 0<α<1.
Zero elements in H should be used when you wish to put no emphasis on the corresponding element of G. The algorithm scales H so that the maximum element is 1. It is this scaled matrix that is used in computing the norm above and for the stopping criteria described in Section 7.
Note that if the elements in H vary by several orders of magnitude from one another the algorithm may fail to converge.

4 References

Borsdorf R and Higham N J (2010) A preconditioned (Newton) algorithm for the nearest correlation matrix IMA Journal of Numerical Analysis 30(1) 94–107
Jiang K, Sun D and Toh K-C (To appear) An inexact accelerated proximal gradient method for large scale linearly constrained convex SDP
Qi H and Sun D (2006) A quadratically convergent Newton method for computing the nearest correlation matrix SIAM J. Matrix AnalAppl 29(2) 360–385

5 Arguments

1:   G LDGN – REAL (KIND=nag_wp) arrayInput/Output
On entry: G, the initial matrix.
On exit: G is overwritten.
2:   LDG – INTEGERInput
On entry: the first dimension of the array G as declared in the (sub)program from which G02AJF is called.
Constraint: LDG≥N.
3:   N – INTEGERInput
On entry: the order of the matrix G.
Constraint: N>0.
4:   ALPHA – REAL (KIND=nag_wp)Input
On entry: the value of α.
If ALPHA<0.0, 0.0 is used.
Constraint: ALPHA<1.0.
5:   H LDHN – REAL (KIND=nag_wp) arrayInput/Output
On entry: the matrix of weights H.
On exit: a symmetric matrix 12 H+HT with its diagonal elements set to zero and the remaining elements scaled so that the maximum element is 1.0.
Constraint: H ij≥0.0, for all i and j=1,2,…,n, i≠j.
6:   LDH – INTEGERInput
On entry: the first dimension of the array H as declared in the (sub)program from which G02AJF is called.
Constraint: LDH≥N.
7:   ERRTOL – REAL (KIND=nag_wp)Input
On entry: the termination tolerance for the iteration. If ERRTOL≤0.0 then N×machine precision is used. See Section 7 for further details.
8:   MAXIT – INTEGERInput
On entry: specifies the maximum number of iterations to be used.
If MAXIT≤0, 200 is used.
9:   X LDXN – REAL (KIND=nag_wp) arrayOutput
On exit: contains the nearest correlation matrix.
10:   LDX – INTEGERInput
On entry: the first dimension of the array X as declared in the (sub)program from which G02AJF is called.
Constraint: LDX≥N.
11:   ITER – INTEGEROutput
On exit: the number of iterations taken.
12:   NORM – REAL (KIND=nag_wp)Output
On exit: the value of H∘G-X F after the final iteration.
13:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, N=value.
Constraint: N>0.
IFAIL=2
On entry, LDG=value and N=value.
Constraint: LDG≥N.
IFAIL=3
On entry, LDH=value and N=value.
Constraint: LDH≥N.
IFAIL=4
On entry, LDX=value and N=value.
Constraint: LDX≥N.
IFAIL=5
On entry, ALPHA=value.
Constraint: ALPHA<1.0.
IFAIL=6
On entry, one or more of the off-diagonal elements of H were negative.
IFAIL=7
Routine fails to converge in value iterations.
Increase MAXIT or check the call to the routine.
IFAIL=8
Failure to solve intermediate eigenproblem. This should not occur. Please contact NAG with details of your call.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

The returned accuracy is controlled by ERRTOL and limited by machine precision. If ei is the value of NORM at the ith iteration, that is
ei = H∘G-X F ,
where H has been scaled as described above, then the algorithm terminates when:
ei-e i-1 1+ max ei,e i-1 ≤ ERRTOL .

8 Parallelism and Performance

G02AJF is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
G02AJF makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

Arrays are internally allocated by G02AJF. The total size of these arrays is 15×N+5×N×N+max 2×N×N+6×N+1,120+9×N real elements and 5×N+3 integer elements. All allocated memory is freed before return of G02AJF.

10 Example

This example finds the nearest correlation matrix to:
G = 2 -1 0 0 -1 2 -1 0 0 -1 2 -1 0 0 -1 2
weighted by:
H = 0.0 10.0 0.0 0.0 10.0 0.0 1.5 1.5 0.0 1.5 0.0 0.0 0.0 1.5 0.0 0.0
with minimum eigenvalue 0.04.

10.1 Program Text

Program Text (g02ajfe.f90)

10.2 Program Data

Program Data (g02ajfe.d)

10.3 Program Results

Program Results (g02ajfe.r)

G02 Chapter Contents
G02 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


G02ANF : NAG Library, Mark 26

G02 Chapter Contents
G02 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

G02ANF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

G02ANF computes a correlation matrix, subject to preserving a leading principal submatrix and applying the smallest relative perturbation to the remainder of the approximate input matrix.

2 Specification

SUBROUTINE G02ANF ( G, LDG, N, K, ERRTOL, EIGTOL, X, LDX, ALPHA, ITER, EIGMIN, NORM, IFAIL)
INTEGER | LDG, N, K, LDX, ITER, IFAIL
REAL (KIND=nag_wp) | G(LDG,N), ERRTOL, EIGTOL, X(LDX,N), ALPHA, EIGMIN, NORM

3 Description

G02ANF finds a correlation matrix, X, starting from an approximate correlation matrix, G, with positive definite leading principal submatrix of order k. The returned correlation matrix, X, has the following structure:
X = α A 0 0 I + 1-α G
where A is the k by k leading principal submatrix of the input matrix G and positive definite, and α∈0,1.
G02ANF utilizes a shrinking method to find the minimum value of α such that X is positive definite with unit diagonal.

4 References

Higham N J, Strabić N and Šego V (2014) Restoring definiteness via shrinking, with an application to correlation matrices with a fixed block MIMS EPrint 2014.54 Manchester Institute for Mathematical Sciences, The University of Manchester, UK

5 Arguments

1:   G LDGN – REAL (KIND=nag_wp) arrayInput/Output
On entry: G, the initial matrix.
On exit: a symmetric matrix 12 G+GT with the diagonal set to I.
2:   LDG – INTEGERInput
On entry: the first dimension of the array G as declared in the (sub)program from which G02ANF is called.
Constraint: LDG≥N.
3:   N – INTEGERInput
On entry: the order of the matrix G.
Constraint: N>0.
4:   K – INTEGERInput
On entry: k, the order of the leading principal submatrix A.
Constraint: N≥K>0.
5:   ERRTOL – REAL (KIND=nag_wp)Input
On entry: the termination tolerance for the iteration.
If ERRTOL≤0, machine precision is used. See Section 7 for further details.
6:   EIGTOL – REAL (KIND=nag_wp)Input
On entry: the tolerance used in determining the definiteness of A.
If λmin A>N×λ max A×EIGTOL, where λmin A and λmax A denote the minimum and maximum eigenvalues of A respectively, A is positive definite.
If EIGTOL≤0, machine precision is used.
7:   X LDXN – REAL (KIND=nag_wp) arrayOutput
On exit: contains the matrix X.
8:   LDX – INTEGERInput
On entry: the first dimension of the array X as declared in the (sub)program from which G02ANF is called.
Constraint: LDX≥N.
9:   ALPHA – REAL (KIND=nag_wp)Output
On exit: α.
10:   ITER – INTEGEROutput
On exit: the number of iterations taken.
11:   EIGMIN – REAL (KIND=nag_wp)Output
On exit: the smallest eigenvalue of the leading principal submatrix A.
12:   NORM – REAL (KIND=nag_wp)Output
On exit: the value of G-X F after the final iteration.
13:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, N=value.
Constraint: N>0.
IFAIL=2
On entry, LDG=value and N=value.
Constraint: LDG≥N.
IFAIL=3
On entry, K=value and N=value.
Constraint: N≥K>0.
IFAIL=4
On entry, LDX=value and N=value.
Constraint: LDX≥N.
IFAIL=5
The k by k principal leading submatrix of the initial matrix G is not positive definite.
IFAIL=6
Failure to solve intermediate eigenproblem. This should not occur. Please contact NAG.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

The algorithm uses a bisection method. It is terminated when the computed α is within ERRTOL of the minimum value. The positive definiteness of X is such that it can be successfully factorized with a call to F07FDF (DPOTRF).
The number of iterations taken for the bisection will be:
log 2 1 ERRTOL .

8 Parallelism and Performance

G02ANF is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
G02ANF makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

Arrays are internally allocated by G02ANF. The total size of these arrays does not exceed 2×n 2+3×n real elements. All allocated memory is freed before return of G02ANF.

10 Example

This example finds the smallest uniform perturbation α to G, such that the output is a correlation matrix and the k by k leading principal submatrix of the input is preserved,
G = 1.0000 -0.0991 0.5665 -0.5653 -0.3441 -0.0991 1.0000 -0.4273 0.8474 0.4975 0.5665 -0.4273 1.0000 -0.1837 -0.0585 -0.5653 0.8474 -0.1837 1.0000 -0.2713 -0.3441 0.4975 -0.0585 -0.2713 1.0000 .

10.1 Program Text

Program Text (g02anfe.f90)

10.2 Program Data

Program Data (g02anfe.d)

10.3 Program Results

Program Results (g02anfe.r)

G02 Chapter Contents
G02 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


G02APF : NAG Library, Mark 26

G02 Chapter Contents
G02 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

G02APF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

G02APF computes a correlation matrix, by using a positive definite target matrix derived from weighting the approximate input matrix, with an optional bound on the minimum eigenvalue.

2 Specification

SUBROUTINE G02APF ( G, LDG, N, THETA, H, LDH, ERRTOL, EIGTOL, X, LDX, ALPHA, ITER, EIGMIN, NORM, IFAIL)
INTEGER | LDG, N, LDH, LDX, ITER, IFAIL
REAL (KIND=nag_wp) | G(LDG,N), THETA, H(LDH,N), ERRTOL, EIGTOL, X(LDX,N), ALPHA, EIGMIN, NORM

3 Description

Starting from an approximate correlation matrix, G, G02APF finds a correlation matrix, X, which has the form
X = α T + 1-α G ,
where α∈0,1 and T=H∘G is a target matrix. C=A∘B denotes the matrix C with elements C ij=A ij×B ij. H is a matrix of weights that defines the target matrix. The target matrix must be positive definite and thus have off-diagonal elements less than 1 in magnitude. A value of 1 in H essentially fixes an element in G so it is unchanged in X.
G02APF utilizes a shrinking method to find the minimum value of α such that X is positive definite with unit diagonal and with a smallest eigenvalue of at least θ∈0,1 times the smallest eigenvalue of the target matrix.

4 References

Higham N J, Strabić N and Šego V (2014) Restoring definiteness via shrinking, with an application to correlation matrices with a fixed block MIMS EPrint 2014.54 Manchester Institute for Mathematical Sciences, The University of Manchester, UK

5 Arguments

1:   G LDGN – REAL (KIND=nag_wp) arrayInput/Output
On entry: G, the initial matrix.
On exit: a symmetric matrix 12 G+GT with the diagonal elements set to 1.0.
2:   LDG – INTEGERInput
On entry: the first dimension of the array G as declared in the (sub)program from which G02APF is called.
Constraint: LDG≥N.
3:   N – INTEGERInput
On entry: the order of the matrix G.
Constraint: N>0.
4:   THETA – REAL (KIND=nag_wp)Input
On entry: the value of θ. If THETA<0.0, 0.0 is used.
Constraint: THETA<1.0.
5:   H LDHN – REAL (KIND=nag_wp) arrayInput/Output
On entry: the matrix of weights H.
On exit: a symmetric matrix 12 H+HT with its diagonal elements set to 1.0.
6:   LDH – INTEGERInput
On entry: the first dimension of the array H as declared in the (sub)program from which G02APF is called.
Constraint: LDH≥N.
7:   ERRTOL – REAL (KIND=nag_wp)Input
On entry: the termination tolerance for the iteration.
If ERRTOL≤0, machine precision is used. See Section 7 for further details.
8:   EIGTOL – REAL (KIND=nag_wp)Input
On entry: the tolerance used in determining the definiteness of the target matrix T=H∘G.
If λmin T>N×λ max T×EIGTOL, where λmin T and λmax T denote the minimum and maximum eigenvalues of T respectively, T is positive definite.
If EIGTOL≤0, machine precision is used.
9:   X LDXN – REAL (KIND=nag_wp) arrayOutput
On exit: contains the matrix X.
10:   LDX – INTEGERInput
On entry: the first dimension of the array X as declared in the (sub)program from which G02APF is called.
Constraint: LDX≥N.
11:   ALPHA – REAL (KIND=nag_wp)Output
On exit: the constant α used in the formation of X.
12:   ITER – INTEGEROutput
On exit: the number of iterations taken.
13:   EIGMIN – REAL (KIND=nag_wp)Output
On exit: the smallest eigenvalue of the target matrix T.
14:   NORM – REAL (KIND=nag_wp)Output
On exit: the value of G-X F after the final iteration.
15:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, N=value.
Constraint: N>0.
IFAIL=2
On entry, LDG=value and N=value.
Constraint: LDG≥N.
IFAIL=3
On entry, THETA=value.
Constraint: THETA<1.0.
IFAIL=4
On entry, LDH=value and N=value.
Constraint: LDH≥N.
IFAIL=5
On entry, LDX=value and N=value.
Constraint: LDX≥N.
IFAIL=6
The target matrix is not positive definite.
IFAIL=7
Failure to solve intermediate eigenproblem. This should not occur. Please contact NAG.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

The algorithm uses a bisection method. It is terminated when the computed α is within ERRTOL of the minimum value.
Note: when θ is zero X is still positive definite, in that it can be successfully factorized with a call to F07FDF (DPOTRF).
The number of iterations taken for the bisection will be:
log 2 1 ERRTOL .

8 Parallelism and Performance

G02APF is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
G02APF makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

Arrays are internally allocated by G02APF. The total size of these arrays does not exceed 2×n 2+3×n real elements. All allocated memory is freed before return of G02APF.

10 Example

This example finds the smallest α such that α H∘G+1-α G is a correlation matrix. The 2 by 2 leading principal submatrix of the input is preserved, and the last 2 by 2 diagonal block is weighted to give some emphasis to the off diagonal elements.
G = 1.0000 -0.0991 0.5665 -0.5653 -0.3441 -0.0991 1.0000 -0.4273 0.8474 0.4975 0.5665 -0.4273 1.0000 -0.1837 -0.0585 -0.5653 0.8474 -0.1837 1.0000 -0.2713 -0.3441 0.4975 -0.0585 -0.2713 1.0000
and
H = 1.0000 1.0000 0.0000 0.0000 0.0000 1.0000 1.0000 0.0000 0.0000 0.0000 0.0000 0.0000 1.0000 0.0000 0.0000 0.0000 0.0000 0.0000 1.0000 0.5000 0.0000 0.0000 0.0000 0.5000 1.0000 .

10.1 Program Text

Program Text (g02apfe.f90)

10.2 Program Data

Program Data (g02apfe.d)

10.3 Program Results

Program Results (g02apfe.r)

G02 Chapter Contents
G02 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


G02BAF : NAG Library, Mark 26

G02 Chapter Contents
G02 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

G02BAF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

G02BAF computes means and standard deviations of variables, sums of squares and cross-products of deviations from means, and Pearson product-moment correlation coefficients for a set of data.

2 Specification

SUBROUTINE G02BAF ( N, M, X, LDX, XBAR, STD, SSP, LDSSP, R, LDR, IFAIL)
INTEGER | N, M, LDX, LDSSP, LDR, IFAIL
REAL (KIND=nag_wp) | X(LDX,M), XBAR(M), STD(M), SSP(LDSSP,M), R(LDR,M)

3 Description

The input data consist of n observations for each of m variables, given as an array
x ij,  i=1,2,…,n n≥2,j=1,2,…,m m≥2,
where x ij is the ith observation on the jth variable.
The quantities calculated are:
(a) Means:
x-j=1 n∑i=1 n x ij,  j=1,2,…,m.
(b) Standard deviations:
sj=1 n- 1 ∑i= 1 n x ij-x-j 2,   j= 1,2,…,m.
(c) Sums of squares and cross-products of deviations from means:
S jk=∑i=1 n x ij-x-j x ik-x-k ,  j,k=1,2,…,m.
(d) Pearson product-moment correlation coefficients:
R jk=S jk S jjS kk ,   j,k= 1,2,…,m.
If S jj or S kk is zero, R jk is set to zero.

4 References

None.

5 Arguments

1:   N – INTEGERInput
On entry: n, the number of observations or cases.
Constraint: N≥2.
2:   M – INTEGERInput
On entry: m, the number of variables.
Constraint: M≥2.
3:   X LDXM – REAL (KIND=nag_wp) arrayInput
On entry: X ij must be set to x ij, the ith observation on the jth variable, for i=1,2,…,n and j=1,2,…,m.
4:   LDX – INTEGERInput
On entry: the first dimension of the array X as declared in the (sub)program from which G02BAF is called.
Constraint: LDX≥N.
5:   XBAR M – REAL (KIND=nag_wp) arrayOutput
On exit: the mean value, x-j, of the jth variable, for j=1,2,…,m.
6:   STD M – REAL (KIND=nag_wp) arrayOutput
On exit: the standard deviation, sj, of the jth variable, for j=1,2,…,m.
7:   SSP LDSSPM – REAL (KIND=nag_wp) arrayOutput
On exit: SSP jk is the cross-product of deviations S jk, for j=1,2,…,m and k=1,2,…,m.
8:   LDSSP – INTEGERInput
On entry: the first dimension of the array SSP as declared in the (sub)program from which G02BAF is called.
Constraint: LDSSP≥M.
9:   R LDRM – REAL (KIND=nag_wp) arrayOutput
On exit: R jk is the product-moment correlation coefficient R jk between the jth and kth variables, for j=1,2,…,m and k=1,2,…,m.
10:   LDR – INTEGERInput
On entry: the first dimension of the array R as declared in the (sub)program from which G02BAF is called.
Constraint: LDR≥M.
11:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, N<2.
IFAIL=2
On entry, M<2.
IFAIL=3
On entry, | LDX<N,
or | LDSSP<M,
or | LDR<M.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

G02BAF does not use additional precision arithmetic for the accumulation of scalar products, so there may be a loss of significant figures for large n.

8 Parallelism and Performance

G02BAF is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The time taken by G02BAF depends on n and m.
The routine uses a two-pass algorithm.

10 Example

This example reads in a set of data consisting of five observations on each of three variables. The means, standard deviations, sums of squares and cross-products of deviations from means, and Pearson product-moment correlation coefficients for all three variables are then calculated and printed.

10.1 Program Text

Program Text (g02bafe.f90)

10.2 Program Data

Program Data (g02bafe.d)

10.3 Program Results

Program Results (g02bafe.r)

G02 Chapter Contents
G02 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


G02BBF : NAG Library, Mark 26

G02 Chapter Contents
G02 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

G02BBF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

G02BBF computes means and standard deviations of variables, sums of squares and cross-products of deviations from means, and Pearson product-moment correlation coefficients for a set of data omitting completely any cases with a missing observation for any variable.

2 Specification

SUBROUTINE G02BBF ( N, M, X, LDX, MISS, XMISS, XBAR, STD, SSP, LDSSP, R, LDR, NCASES, IFAIL)
INTEGER | N, M, LDX, MISS(M), LDSSP, LDR, NCASES, IFAIL
REAL (KIND=nag_wp) | X(LDX,M), XMISS(M), XBAR(M), STD(M), SSP(LDSSP,M), R(LDR,M)

3 Description

The input data consist of n observations for each of m variables, given as an array
x ij,  i=1,2,…,n n≥2,j=1,2,…,m m≥2,
where x ij is the ith observation on the jth variable. In addition, each of the m variables may optionally have associated with it a value which is to be considered as representing a missing observation for that variable; the missing value for the jth variable is denoted by x mj. Missing values need not be specified for all variables.
Let wi=0 if observation i contains a missing value for any of those variables for which missing values have been declared, i.e., if x ij=x mj for any j for which an x mj has been assigned (see also Section 7); and wi=1 otherwise, for i=1,2,…,n.
The quantities calculated are:
(a) Means:
x-j=∑i=1 n wix ij ∑i=1 n wi ,  j=1,2,…,m.
(b) Standard deviations:
sj= ∑i= 1 n wi x ij-x-j 2 ∑i= 1 n wi- 1 ,   j= 1,2,…,m.
(c) Sums of squares and cross-products of deviations from means:
S jk=∑i=1 n wi x ij-x-jx ik-x-k,  j,k=1,2,…,m.
(d) Pearson product-moment correlation coefficients:
R jk=S jk S jjS kk ,   j,k= 1,2,…,m.
If S jj or S kk is zero, R jk is set to zero.

4 References

None.

5 Arguments

1:   N – INTEGERInput
On entry: n, the number of observations or cases.
Constraint: N≥2.
2:   M – INTEGERInput
On entry: m, the number of variables.
Constraint: M≥2.
3:   X LDXM – REAL (KIND=nag_wp) arrayInput
On entry: X ij must be set to x ij, the value of the ith observation on the jth variable, for i=1,2,…,n and j=1,2,…,m.
4:   LDX – INTEGERInput
On entry: the first dimension of the array X as declared in the (sub)program from which G02BBF is called.
Constraint: LDX≥N.
5:   MISS M – INTEGER arrayInput/Output
On entry: MISS j must be set equal to 1 if a missing value, x mj, is to be specified for the jth variable in the array X, or set equal to 0 otherwise. Values of MISS must be given for all m variables in the array X.
On exit: the array MISS is overwritten by the routine, and the information it contained on entry is lost.
6:   XMISS M – REAL (KIND=nag_wp) arrayInput/Output
On entry: XMISS j must be set to the missing value, x mj, to be associated with the jth variable in the array X, for those variables for which missing values are specified by means of the array MISS (see Section 7).
On exit: the array XMISS is overwritten by the routine, and the information it contained on entry is lost.
7:   XBAR M – REAL (KIND=nag_wp) arrayOutput
On exit: the mean value, x-j, of the jth variable, for j=1,2,…,m.
8:   STD M – REAL (KIND=nag_wp) arrayOutput
On exit: the standard deviation, sj, of the jth variable, for j=1,2,…,m.
9:   SSP LDSSPM – REAL (KIND=nag_wp) arrayOutput
On exit: SSP jk is the cross-product of deviations S jk, for j=1,2,…,m and k=1,2,…,m.
10:   LDSSP – INTEGERInput
On entry: the first dimension of the array SSP as declared in the (sub)program from which G02BBF is called.
Constraint: LDSSP≥M.
11:   R LDRM – REAL (KIND=nag_wp) arrayOutput
On exit: R jk is the product-moment correlation coefficient R jk between the jth and kth variables, for j=1,2,…,m and k=1,2,…,m.
12:   LDR – INTEGERInput
On entry: the first dimension of the array R as declared in the (sub)program from which G02BBF is called.
Constraint: LDR≥M.
13:   NCASES – INTEGEROutput
On exit: the number of cases actually used in the calculations (when cases involving missing values have been eliminated).
14:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, N<2.
IFAIL=2
On entry, M<2.
IFAIL=3
On entry, | LDX<N,
or | LDSSP<M,
or | LDR<M.
IFAIL=4
After observations with missing values were omitted, no cases remained.
IFAIL=5
After observations with missing values were omitted, only one case remained.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

G02BBF does not use additional precision arithmetic for the accumulation of scalar products, so there may be a loss of significant figures for large n.
You are warned of the need to exercise extreme care in your selection of missing values. G02BBF treats all values in the inclusive range 1±0.1 X02BEF-2×xm j, where xmj is the missing value for variable j specified in XMISS.
You must therefore ensure that the missing value chosen for each variable is sufficiently different from all valid values for that variable so that none of the valid values fall within the range indicated above.

8 Parallelism and Performance

G02BBF is not threaded in any implementation.

9 Further Comments

The time taken by G02BBF depends on n and m, and the occurrence of missing values.
The routine uses a two-pass algorithm.

10 Example

This example reads in a set of data consisting of five observations on each of three variables. Missing values of 0.0 are declared for the first and third variables; no missing value is specified for the second variable. The means, standard deviations, sums of squares and cross-products of deviations from means, and Pearson product-moment correlation coefficients for all three variables are then calculated and printed, omitting completely all cases containing missing values; cases 3 and 4 are therefore eliminated, leaving only three cases in the calculations.

10.1 Program Text

Program Text (g02bbfe.f90)

10.2 Program Data

Program Data (g02bbfe.d)

10.3 Program Results

Program Results (g02bbfe.r)

G02 Chapter Contents
G02 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


G02BCF : NAG Library, Mark 26

G02 Chapter Contents
G02 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

G02BCF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

G02BCF computes means and standard deviations of variables, sums of squares and cross-products of deviations from means, and Pearson product-moment correlation coefficients for a set of data omitting cases with missing values from only those calculations involving the variables for which the values are missing.

2 Specification

SUBROUTINE G02BCF ( N, M, X, LDX, MISS, XMISS, XBAR, STD, SSP, LDSSP, R, LDR, NCASES, CNT, LDCNT, IFAIL)
INTEGER | N, M, LDX, MISS(M), LDSSP, LDR, NCASES, LDCNT, IFAIL
REAL (KIND=nag_wp) | X(LDX,M), XMISS(M), XBAR(M), STD(M), SSP(LDSSP,M), R(LDR,M), CNT(LDCNT,M)

3 Description

The input data consist of n observations for each of m variables, given as an array
x ij,  i=1,2,…,n n≥2,j=1,2,…,m m≥2,
where x ij is the ith observation on the jth variable. In addition, each of the m variables may optionally have associated with it a value which is to be considered as representing a missing observation for that variable; the missing value for the jth variable is denoted by xmj. Missing values need not be specified for all variables.
Let w ij=0 if the ith observation for the jth variable is a missing value, i.e., if a missing value, xmj, has been declared for the jth variable, and x ij=xmj (see also Section 7); and w ij=1 otherwise, for i=1,2,…,n and j=1,2,…,m.
The quantities calculated are:
(a) Means:
x-j=∑i=1 n w ijx ij ∑i=1 n w ij ,  j=1,2,…,m.
(b) Standard deviations:
sj=∑i= 1 n w ij x ij-x-j 2 ∑i= 1 n w ij- 1 ,   j= 1,2,…,m.
(c) Sums of squares and cross-products of deviations from means:
S jk=∑i=1 n w ijw ik x ij-x-j kx ik-x-k j,  j,k=1,2,…,m,
where
x-j k=∑i= 1 n w ijw ikx ij ∑i= 1 n w ijw ik   and   x-k j=∑i= 1 n w ikw ijx ik ∑i= 1 n w ikw ij ,
(i.e., the means used in the calculation of the sums of squares and cross-products of deviations are based on the same set of observations as are the cross-products.)
(d) Pearson product-moment correlation coefficients:
R jk=S jk S jj kS kk j ,  j,k,=1,2,…,m,
where S jj k=∑i=1 n w ijw ik x ij-x-j k 2 and S kk j=∑i=1 n w ikw ij x ik-x-k j 2 and x-j k and x-k j are as defined in (c) above
(i.e., the sums of squares of deviations used in the denominator are based on the same set of observations as are used in the calculation of the numerator).
If S jj k or S kk j is zero, R jk is set to zero.
(e) The number of cases used in the calculation of each of the correlation coefficients:
c jk=∑i=1 n w ijw ik,  j,k=1,2,…,m.
(The diagonal terms, c jj, for j=1,2,…,m, also give the number of cases used in the calculation of the means, x-j, and the standard deviations, sj.)

4 References

None.

5 Arguments

1:   N – INTEGERInput
On entry: n, the number of observations or cases.
Constraint: N≥2.
2:   M – INTEGERInput
On entry: m, the number of variables.
Constraint: M≥2.
3:   X LDXM – REAL (KIND=nag_wp) arrayInput
On entry: X ij must be set to x ij, the value of the ith observation on the jth variable, for i=1,2,…,n and j=1,2,…,m.
4:   LDX – INTEGERInput
On entry: the first dimension of the array X as declared in the (sub)program from which G02BCF is called.
Constraint: LDX≥N.
5:   MISS M – INTEGER arrayInput
On entry: MISS j must be set equal to 1 if a missing value, x mj, is to be specified for the jth variable in the array X, or set equal to 0 otherwise. Values of MISS must be given for all m variables in the array X.
6:   XMISS M – REAL (KIND=nag_wp) arrayInput
On entry: XMISS j must be set to the missing value, x mj, to be associated with the jth variable in the array X, for those variables for which missing values are specified by means of the array MISS (see Section 7).
7:   XBAR M – REAL (KIND=nag_wp) arrayOutput
On exit: the mean value, x-j, of the jth variable, for j=1,2,…,m.
8:   STD M – REAL (KIND=nag_wp) arrayOutput
On exit: the standard deviation, sj, of the jth variable, for j=1,2,…,m.
9:   SSP LDSSPM – REAL (KIND=nag_wp) arrayOutput
On exit: SSP jk is the cross-product of deviations S jk, for j=1,2,…,m and k=1,2,…,m.
10:   LDSSP – INTEGERInput
On entry: the first dimension of the array SSP as declared in the (sub)program from which G02BCF is called.
Constraint: LDSSP≥M.
11:   R LDRM – REAL (KIND=nag_wp) arrayOutput
On exit: R jk is the product-moment correlation coefficient R jk between the jth and kth variables, for j=1,2,…,m and k=1,2,…,m.
12:   LDR – INTEGERInput
On entry: the first dimension of the array R as declared in the (sub)program from which G02BCF is called.
Constraint: LDR≥M.
13:   NCASES – INTEGEROutput
On exit: the minimum number of cases used in the calculation of any of the sums of squares and cross-products and correlation coefficients (when cases involving missing values have been eliminated).
14:   CNT LDCNTM – REAL (KIND=nag_wp) arrayOutput
On exit: CNT jk is the number of cases, c jk, actually used in the calculation of S jk, and R jk, the sum of cross-products and correlation coefficient for the jth and kth variables, for j=1,2,…,m and k=1,2,…,m.
15:   LDCNT – INTEGERInput
On entry: the first dimension of the array CNT as declared in the (sub)program from which G02BCF is called.
Constraint: LDCNT≥M.
16:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, because for this routine the values of the output arguments may be useful even if IFAIL≠0 on exit, the recommended value is -1. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Note: G02BCF may return useful information for one or more of the following detected errors or warnings.
Errors or warnings detected by the routine:
IFAIL=1
On entry, N<2.
IFAIL=2
On entry, M<2.
IFAIL=3
On entry, | LDX<N,
or | LDSSP<M,
or | LDR<M,
or | LDCNT<M.
IFAIL=4
After observations with missing values were omitted, fewer than two cases remained for at least one pair of variables. (The pairs of variables involved can be determined by examination of the contents of the array CNT.) All means, standard deviations, sums of squares and cross-products, and correlation coefficients based on two or more cases are returned by the routine even if IFAIL=4.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

G02BCF does not use additional precision arithmetic for the accumulation of scalar products, so there may be a loss of significant figures for large n.
You are warned of the need to exercise extreme care in your selection of missing values. G02BCF treats all values in the inclusive range 1±0.1 X02BEF-2×xm j, where xmj is the missing value for variable j specified in XMISS.
You must therefore ensure that the missing value chosen for each variable is sufficiently different from all valid values for that variable so that none of the valid values fall within the range indicated above.

8 Parallelism and Performance

G02BCF is not threaded in any implementation.

9 Further Comments

The time taken by G02BCF depends on n and m, and the occurrence of missing values.
The routine uses a two-pass algorithm.

10 Example

This example reads in a set of data consisting of five observations on each of three variables. Missing values of 0.0, -1.0 and 0.0 are declared for the first, second and third variables respectively. The means, standard deviations, sums of squares and cross-products of deviations from means, and Pearson product-moment correlation coefficients for all three variables are then calculated and printed, omitting cases with missing values from only those calculations involving the variables for which the values are missing. The program therefore omits cases 4 and 5 in calculating the correlation between the first and second variables, and cases 3 and 4 for the first and third variables etc.

10.1 Program Text

Program Text (g02bcfe.f90)

10.2 Program Data

Program Data (g02bcfe.d)

10.3 Program Results

Program Results (g02bcfe.r)

G02 Chapter Contents
G02 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


G02BDF : NAG Library, Mark 26

G02 Chapter Contents
G02 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

G02BDF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

G02BDF computes means and standard deviations of variables, sums of squares and cross-products about zero, and correlation-like coefficients for a set of data.

2 Specification

SUBROUTINE G02BDF ( N, M, X, LDX, XBAR, STD, SSPZ, LDSSPZ, RZ, LDRZ, IFAIL)
INTEGER | N, M, LDX, LDSSPZ, LDRZ, IFAIL
REAL (KIND=nag_wp) | X(LDX,M), XBAR(M), STD(M), SSPZ(LDSSPZ,M), RZ(LDRZ,M)

3 Description

The input data consists of n observations for each of m variables, given as an array
x ij,  i=1,2,…,n n≥2 ,  j=1,2,…,m m≥2,
where x ij is the ith observation on the jth variable.
The quantities calculated are:
(a) Means:
x-j=1 n∑i=1 n x ij,  j=1,2,…,m.
(b) Standard deviations:
sj=1 n- 1 ∑i= 1 n x ij-x-j 2,   j= 1,2,…,m.
(c) Sums of squares and cross-products about zero:
S~jk=∑i=1 n x ijx ik,  j,k=1,2,…,m.
(d) Correlation-like coefficients:
R~jk=S~jk S~jjS~kk ,   j,k= 1,2,…,m.
If S~jj or S~kk is zero, R~jk is set to zero.

4 References

None.

5 Arguments

1:   N – INTEGERInput
On entry: n, the number of observations or cases.
Constraint: N≥2.
2:   M – INTEGERInput
On entry: m, the number of variables.
Constraint: M≥2.
3:   X LDXM – REAL (KIND=nag_wp) arrayInput
On entry: X ij must be set to the value of x ij, the ith observation on the jth variable, for i=1,2,…,n and j=1,2,…,m.
4:   LDX – INTEGERInput
On entry: the first dimension of the array X as declared in the (sub)program from which G02BDF is called.
Constraint: LDX≥N.
5:   XBAR M – REAL (KIND=nag_wp) arrayOutput
On exit: XBAR j contains the mean value, x-j, of the jth variable, for j=1,2,…,m.
6:   STD M – REAL (KIND=nag_wp) arrayOutput
On exit: the standard deviation, sj, of the jth variable, for j=1,2,…,m.
7:   SSPZ LDSSPZM – REAL (KIND=nag_wp) arrayOutput
On exit: SSPZ jk is the cross-product about zero, S~jk, for j=1,2,…,m and k=1,2,…,m.
8:   LDSSPZ – INTEGERInput
On entry: the first dimension of the array SSPZ as declared in the (sub)program from which G02BDF is called.
Constraint: LDSSPZ≥M.
9:   RZ LDRZM – REAL (KIND=nag_wp) arrayOutput
On exit: RZ jk is the correlation-like coefficient, R~jk, between the jth and kth variables, for j=1,2,…,m and k=1,2,…,m.
10:   LDRZ – INTEGERInput
On entry: the first dimension of the array RZ as declared in the (sub)program from which G02BDF is called.
Constraint: LDRZ≥M.
11:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, N<2.
IFAIL=2
On entry, M<2.
IFAIL=3
On entry, | LDX<N,
or | LDSSPZ<M,
or | LDRZ<M.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

G02BDF does not use additional precision arithmetic for the accumulation of scalar products, so there may be a loss of significant figures for large n.

8 Parallelism and Performance

G02BDF is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The time taken by G02BDF depends on n and m.
The routine uses a two-pass algorithm.

10 Example

This example reads in a set of data consisting of five observations on each of three variables. The means, standard deviations, sums of squares and cross-products about zero, and correlation-like coefficients for all three variables are then calculated and printed.

10.1 Program Text

Program Text (g02bdfe.f90)

10.2 Program Data

Program Data (g02bdfe.d)

10.3 Program Results

Program Results (g02bdfe.r)

G02 Chapter Contents
G02 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


G02BEF : NAG Library, Mark 26

G02 Chapter Contents
G02 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

G02BEF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

G02BEF computes means and standard deviations of variables, sums of squares and cross-products about zero, and correlation-like coefficients for a set of data omitting completely any cases with a missing observation for any variable.

2 Specification

SUBROUTINE G02BEF ( N, M, X, LDX, MISS, XMISS, XBAR, STD, SSPZ, LDSSPZ, RZ, LDRZ, NCASES, IFAIL)
INTEGER | N, M, LDX, MISS(M), LDSSPZ, LDRZ, NCASES, IFAIL
REAL (KIND=nag_wp) | X(LDX,M), XMISS(M), XBAR(M), STD(M), SSPZ(LDSSPZ,M), RZ(LDRZ,M)

3 Description

The input data consists of n observations for each of m variables, given as an array
x ij,  i=1,2,…,n n≥2,j=1,2,…,m m≥2,
where x ij is the ith observation on the jth variable. In addition, each of the m variables may optionally have associated with it a value which is to be considered as representing a missing observation for that variable; the missing value for the jth variable is denoted by xmj. Missing values need not be specified for all variables.
Let wi=0 if observation i contains a missing value for any of those variables for which missing values have been declared, i.e., if x ij=xmj for any j for which an xmj has been assigned (see also Section 7); and wi=1 otherwise, for i=1,2,…,n.
The quantities calculated are:
(a) Means:
x-j=∑i=1 n wix ij ∑i=1 n wi ,  j=1,2,…,m.
(b) Standard deviations:
sj= ∑i= 1 n wi x ij-x-j 2 ∑i= 1 n wi- 1 ,   j= 1,2,…,m.
(c) Sums of squares and cross-products about zero:
S~jk=∑i=1 n wix ijx ik,  j,k=1,2,…,m.
(d) Correlation-like coefficients:
R~jk=S~jk S~jj S~kk ,   j,k= 1,2,…,m.
If S~jj or S~kk is zero, R~jk is set to zero.

4 References

None.

5 Arguments

1:   N – INTEGERInput
On entry: n, the number of observations or cases.
Constraint: N≥2.
2:   M – INTEGERInput
On entry: m, the number of variables.
Constraint: M≥2.
3:   X LDXM – REAL (KIND=nag_wp) arrayInput
On entry: X ij must be set to x ij, the value of the ith observation on the jth variable, for i=1,2,…,n and j=1,2,…,m.
4:   LDX – INTEGERInput
On entry: the first dimension of the array X as declared in the (sub)program from which G02BEF is called.
Constraint: LDX≥N.
5:   MISS M – INTEGER arrayInput/Output
On entry: MISS j must be set equal to 1 if a missing value, x mj, is to be specified for the jth variable in the array X, or set equal to 0 otherwise. Values of MISS must be given for all m variables in the array X.
On exit: the array MISS is overwritten by the routine, and the information it contained on entry is lost.
6:   XMISS M – REAL (KIND=nag_wp) arrayInput/Output
On entry: XMISS j must be set to the missing value, x mj, to be associated with the jth variable in the array X, for those variables for which missing values are specified by means of the array MISS (see Section 7).
On exit: the array XMISS is overwritten by the routine, and the information it contained on entry is lost.
7:   XBAR M – REAL (KIND=nag_wp) arrayOutput
On exit: the mean value, x-j, of the jth variable, for j=1,2,…,m.
8:   STD M – REAL (KIND=nag_wp) arrayOutput
On exit: the standard deviation, sj, of the jth variable, for j=1,2,…,m.
9:   SSPZ LDSSPZM – REAL (KIND=nag_wp) arrayOutput
On exit: SSPZ jk is the cross-product about zero, S~jk, for j=1,2,…,m and k=1,2,…,m.
10:   LDSSPZ – INTEGERInput
On entry: the first dimension of the array SSPZ as declared in the (sub)program from which G02BEF is called.
Constraint: LDSSPZ≥M.
11:   RZ LDRZM – REAL (KIND=nag_wp) arrayOutput
On exit: RZ jk is the correlation-like coefficient, R~jk, between the jth and kth variables, for j=1,2,…,m and k=1,2,…,m.
12:   LDRZ – INTEGERInput
On entry: the first dimension of the array RZ as declared in the (sub)program from which G02BEF is called.
Constraint: LDRZ≥M.
13:   NCASES – INTEGEROutput
On exit: the number of cases actually used in the calculations (when cases involving missing values have been eliminated).
14:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, N<2.
IFAIL=2
On entry, M<2.
IFAIL=3
On entry, | LDX<N,
or | LDSSPZ<M,
or | LDRZ<M.
IFAIL=4
After observations with missing values were omitted, no cases remained.
IFAIL=5
After observations with missing values were omitted, only one case remained.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

G02BEF does not use additional precision arithmetic for the accumulation of scalar products, so there may be a loss of significant figures for large n.
You are warned of the need to exercise extreme care in your selection of missing values. G02BEF treats all values in the inclusive range 1±0.1 X02BEF-2×xm j, where xmj is the missing value for variable j specified in XMISS.
You must therefore ensure that the missing value chosen for each variable is sufficiently different from all valid values for that variable so that none of the valid values fall within the range indicated above.

8 Parallelism and Performance

G02BEF is not threaded in any implementation.

9 Further Comments

The time taken by G02BEF depends on n and m, and the occurrence of missing values.
The routine uses a two-pass algorithm.

10 Example

This example reads in a set of data consisting of five observations on each of three variables. Missing values of 0.0 are declared for the first and third variables; no missing value is specified for the second variable. The means, standard deviations, sums of squares and cross-products about zero, and correlation-like coefficients for all three variables are then calculated and printed, omitting completely all cases containing missing values; cases 3 and 4 are therefore eliminated, leaving only three cases in the calculations.

10.1 Program Text

Program Text (g02befe.f90)

10.2 Program Data

Program Data (g02befe.d)

10.3 Program Results

Program Results (g02befe.r)

G02 Chapter Contents
G02 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


G02BFF : NAG Library, Mark 26

G02 Chapter Contents
G02 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

G02BFF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

G02BFF computes means and standard deviations of variables, sums of squares and cross-products about zero and correlation-like coefficients for a set of data omitting cases with missing values from only those calculations involving the variables for which the values are missing.

2 Specification

SUBROUTINE G02BFF ( N, M, X, LDX, MISS, XMISS, XBAR, STD, SSPZ, LDSSPZ, RZ, LDRZ, NCASES, CNT, LDCNT, IFAIL)
INTEGER | N, M, LDX, MISS(M), LDSSPZ, LDRZ, NCASES, LDCNT, IFAIL
REAL (KIND=nag_wp) | X(LDX,M), XMISS(M), XBAR(M), STD(M), SSPZ(LDSSPZ,M), RZ(LDRZ,M), CNT(LDCNT,M)

3 Description

The input data consists of n observations for each of m variables, given as an array
x ij,  i=1,2,…,n n≥2,j=1,2,…,m m≥2,
where x ij is the ith observation on the jth variable. In addition, each of the m variables may optionally have associated with it a value which is to be considered as representing a missing observation for that variable; the missing value for the jth variable is denoted by xmj. Missing values need not be specified for all variables.
Let w ij=0 if the ith observation for the jth variable is a missing value, i.e., if a missing value, xmj, has been declared for the jth variable, and x ij=xmj (see also Section 7); and w ij=1 otherwise, for i=1,2,…,n and j=1,2,…,m.
The quantities calculated are:
(a) Means:
x-j=∑i=1 n w ijx ij ∑i=1 n w ij ,  j=1,2,…,m.
(b) Standard deviations:
sj=∑i= 1 n w ij x ij-x-j 2 ∑i= 1 n w ij- 1 ,   j= 1,2,…,m.
(c) Sums of squares and cross-products about zero:
S~jk=∑i=1 n w ijw ikx ijx ik,  j,k=1,2,…,m.
(d) Correlation-like coefficients:
R~jk=S~jk S~jj k j k S~kk j ,   j,k= 1,2,…,m ,
where S~jj k=∑i=1 n w ijw ik x ij 2 and S~kk j=∑i=1 n w ikw ij x ik 2
(i.e., the sums of squares about zero are based on the same set of observations as are used in the calculation of the numerator).
If S~jj k or S~kk j is zero, R~jk is set to zero.
(e) The number of cases used in the calculation of each of the correlation-like coefficients:
c jk=∑i=1 n w ijw ik,  j,k=1,2,…,m.
(The diagonal terms, c jj, for j=1,2,…,m, also give the number of cases used in the calculation of the means x-j and the standard deviations sj.)

4 References

None.

5 Arguments

1:   N – INTEGERInput
On entry: n, the number of observations or cases.
Constraint: N≥2.
2:   M – INTEGERInput
On entry: m, the number of variables.
Constraint: M≥2.
3:   X LDXM – REAL (KIND=nag_wp) arrayInput
On entry: X ij must be set to x ij, the value of the ith observation on the jth variable, for i=1,2,…,n and j=1,2,…,m.
4:   LDX – INTEGERInput
On entry: the first dimension of the array X as declared in the (sub)program from which G02BFF is called.
Constraint: LDX≥N.
5:   MISS M – INTEGER arrayInput
On entry: MISS j must be set equal to 1 if a missing value, x mj, is to be specified for the jth variable in the array X, or set equal to 0 otherwise. Values of MISS must be given for all m variables in the array X.
6:   XMISS M – REAL (KIND=nag_wp) arrayInput
On entry: XMISS j must be set to the missing value, x mj, to be associated with the jth variable in the array X, for those variables for which missing values are specified by means of the array MISS (see Section 7).
7:   XBAR M – REAL (KIND=nag_wp) arrayOutput
On exit: the mean value, x-j, of the jth variable, for j=1,2,…,m.
8:   STD M – REAL (KIND=nag_wp) arrayOutput
On exit: the standard deviation, sj, of the jth variable, for j=1,2,…,m.
9:   SSPZ LDSSPZM – REAL (KIND=nag_wp) arrayOutput
On exit: SSPZ jk is the cross-product about zero, S~jk, for j=1,2,…,m and k=1,2,…,m.
10:   LDSSPZ – INTEGERInput
On entry: the first dimension of the array SSPZ as declared in the (sub)program from which G02BFF is called.
Constraint: LDSSPZ≥M.
11:   RZ LDRZM – REAL (KIND=nag_wp) arrayOutput
On exit: RZ jk is the correlation-like coefficient, R~jk, between the jth and kth variables, for j=1,2,…,m and k=1,2,…,m.
12:   LDRZ – INTEGERInput
On entry: the first dimension of the array RZ as declared in the (sub)program from which G02BFF is called.
Constraint: LDRZ≥M.
13:   NCASES – INTEGEROutput
On exit: the minimum number of cases used in the calculation of any of the sums of squares and cross-products and correlation-like coefficients (when cases involving missing values have been eliminated).
14:   CNT LDCNTM – REAL (KIND=nag_wp) arrayOutput
On exit: CNT jk is the number of cases, c jk, actually used in the calculation of S~jk, and R~jk, the sum of cross-products and correlation-like coefficient for the jth and kth variables, for j=1,2,…,m and k=1,2,…,m.
15:   LDCNT – INTEGERInput
On entry: must specify the first dimension of the array CNT as declared in the (sub)program from which G02BFF is called.
Constraint: LDCNT≥M.
16:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, because for this routine the values of the output arguments may be useful even if IFAIL≠0 on exit, the recommended value is -1. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Note: G02BFF may return useful information for one or more of the following detected errors or warnings.
Errors or warnings detected by the routine:
IFAIL=1
On entry, N<2.
IFAIL=2
On entry, M<2.
IFAIL=3
On entry, | LDX<N,
or | LDSSPZ<M,
or | LDRZ<M,
or | LDCNT<M.
IFAIL=4
After observations with missing values were omitted, fewer than two cases remained for at least one pair of variables. (The pairs of variables involved can be determined by examination of the contents of the array CNT). All means, standard deviations, sums of squares and cross-products, and correlation-like coefficients based on two or more cases are returned by the routine even if IFAIL=4.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

G02BFF does not use additional precision arithmetic for the accumulation of scalar products, so there may be a loss of significant figures for large n.
You are warned of the need to exercise extreme care in your selection of missing values. G02BFF treats all values in the inclusive range 1±0.1 X02BEF-2×xm j, where xmj is the missing value for variable j specified in XMISS.
You must therefore ensure that the missing value chosen for each variable is sufficiently different from all valid values for that variable so that none of the valid values fall within the range indicated above.

8 Parallelism and Performance

G02BFF is not threaded in any implementation.

9 Further Comments

The time taken by G02BFF depends on n and m, and the occurrence of missing values.
The routine uses a two-pass algorithm.

10 Example

This example reads in a set of data consisting of five observations on each of three variables. Missing values of 0.0, -1.0 and 0.0 are declared for the first, second and third variables respectively. The means, standard deviations, sums of squares and cross-products about zero, and correlation-like coefficients for all three variables are then calculated and printed, omitting cases with missing values from only those calculations involving the variables for which the values are missing. The program therefore omits cases 4 and 5 in calculating the correlation between the first and second variables, and cases 3 and 4 for the first and third variables, etc.

10.1 Program Text

Program Text (g02bffe.f90)

10.2 Program Data

Program Data (g02bffe.d)

10.3 Program Results

Program Results (g02bffe.r)

G02 Chapter Contents
G02 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


G02BGF : NAG Library, Mark 26

G02 Chapter Contents
G02 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

G02BGF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

G02BGF computes means and standard deviations, sums of squares and cross-products of deviations from means, and Pearson product-moment correlation coefficients for selected variables.

2 Specification

SUBROUTINE G02BGF ( N, M, X, LDX, NVARS, KVAR, XBAR, STD, SSP, LDSSP, R, LDR, IFAIL)
INTEGER | N, M, LDX, NVARS, KVAR(NVARS), LDSSP, LDR, IFAIL
REAL (KIND=nag_wp) | X(LDX,M), XBAR(NVARS), STD(NVARS), SSP(LDSSP,NVARS), R(LDR,NVARS)

3 Description

The input data consist of n observations for each of m variables, given as an array
x ij,  i=1,2,…,n n≥2,j=1,2,…,m m≥2,
where x ij is the ith observation on the jth variable, together with the subset of these variables, v 1,v 2,…,vp, for which information is required.
The quantities calculated are:
(a) Means:
x-j=1 n∑i=1 n x ij,  j=v 1,v 2,…,vp.
(b) Standard deviations:
sj=1 n- 1 ∑i= 1 n x ij-x-j 2,   j=v 1,v 2,…,vp.
(c) Sums of squares and cross-products of deviations from zero:
S jk=∑i=1 n x ij-x-jx ik-x-k,  j,k=v 1,v 2,…,vp.
(d) Pearson product-moment correlation coefficients:
R jk=S jk S jjS kk ,   j,k=v 1,v 2,…vp.
If S jj or S kk is zero, R jk is set to zero.

4 References

None.

5 Arguments

1:   N – INTEGERInput
On entry: n, the number of observations or cases.
Constraint: N≥2.
2:   M – INTEGERInput
On entry: m, the number of variables.
Constraint: M≥2.
3:   X LDXM – REAL (KIND=nag_wp) arrayInput
On entry: X ij must be set to x ij, the value of the ith observation on the jth variable, for i=1,2,…,n and j=1,2,…,m.
4:   LDX – INTEGERInput
On entry: the first dimension of the array X as declared in the (sub)program from which G02BGF is called.
Constraint: LDX≥N.
5:   NVARS – INTEGERInput
On entry: p, the number of variables for which information is required.
Constraint: 2≤NVARS≤M.
6:   KVAR NVARS – INTEGER arrayInput
On entry: KVAR j must be set to the column number in X of the jth variable for which information is required, for j=1,2,…,p.
Constraint: 1≤KVAR j≤M, for j=1,2,…,p.
7:   XBAR NVARS – REAL (KIND=nag_wp) arrayOutput
On exit: the mean value, x-j, of the variable specified in KVAR j, for j=1,2,…,p.
8:   STD NVARS – REAL (KIND=nag_wp) arrayOutput
On exit: the standard deviation, sj, of the variable specified in KVAR j, for j=1,2,…,p.
9:   SSP LDSSPNVARS – REAL (KIND=nag_wp) arrayOutput
On exit: SSP jk is the cross-product of deviations, S jk, for the variables specified in KVAR j and KVAR k, for j=1,2,…,p and k=1,2,…,p.
10:   LDSSP – INTEGERInput
On entry: the first dimension of the array SSP as declared in the (sub)program from which G02BGF is called.
Constraint: LDSSP≥NVARS.
11:   R LDRNVARS – REAL (KIND=nag_wp) arrayOutput
On exit: R jk is the product-moment correlation coefficient, R jk, between the variables specified in KVAR j and KVAR k, for j=1,2,…,p and k=1,2,…,p.
12:   LDR – INTEGERInput
On entry: the first dimension of the array R as declared in the (sub)program from which G02BGF is called.
Constraint: LDR≥NVARS.
13:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, N<2.
IFAIL=2
On entry, | NVARS<2,
or | NVARS>M.
IFAIL=3
On entry, | LDX<N,
or | LDSSP<NVARS,
or | LDR<NVARS.
IFAIL=4
On entry, | KVAR j<1,
or | KVAR j>M for some j=1,2,…,NVARS.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

G02BGF does not use additional precision arithmetic for the accumulation of scalar products, so there may be a loss of significant figures for large n.

8 Parallelism and Performance

G02BGF is not threaded in any implementation.

9 Further Comments

The time taken by G02BGF depends on n and p.
The routine uses a two pass algorithm.

10 Example

This example reads in a set of data consisting of five observations on each of four variables. The means, standard deviations, sums of squares and cross-products of deviations from means, and Pearson product-moment correlation coefficients for the fourth, first and second variables are then calculated and printed.

10.1 Program Text

Program Text (g02bgfe.f90)

10.2 Program Data

Program Data (g02bgfe.d)

10.3 Program Results

Program Results (g02bgfe.r)

G02 Chapter Contents
G02 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


G02BHF : NAG Library, Mark 26

G02 Chapter Contents
G02 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

G02BHF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

G02BHF computes means and standard deviations, sums of squares and cross-products of deviations from means, and Pearson product-moment correlation coefficients for selected variables omitting completely any cases with a missing observation for any variable (either over all variables in the dataset or over only those variables in the selected subset).

2 Specification

SUBROUTINE G02BHF ( N, M, X, LDX, MISS, XMISS, MISTYP, NVARS, KVAR, XBAR, STD, SSP, LDSSP, R, LDR, NCASES, IFAIL)
INTEGER | N, M, LDX, MISS(M), MISTYP, NVARS, KVAR(NVARS), LDSSP, LDR, NCASES, IFAIL
REAL (KIND=nag_wp) | X(LDX,M), XMISS(M), XBAR(NVARS), STD(NVARS), SSP(LDSSP,NVARS), R(LDR,NVARS)

3 Description

The input data consists of n observations for each of m variables, given as an array
x ij,  i=1,2,…,n n≥2,j=1,2,…,m m≥2,
where x ij is the ith observation on the jth variable, together with the subset of these variables, v 1,v 2,…,vp, for which information is required.
In addition, each of the m variables may optionally have associated with it a value which is to be considered as representing a missing observation for that variable; the missing value for the jth variable is denoted by xmj. Missing values need not be specified for all variables. The missing values can be utilized in two slightly different ways; you can indicate which scheme is required.
Firstly, let wi=0 if observation i contains a missing value for any of those variables in the set 1,2,…,m for which missing values have been declared, i.e., if x ij=xmj for any j (j=1,2,…,m) for which an xmj has been assigned (see also Section 7); and wi=1 otherwise, for i=1,2,…,n.
Secondly, let wi=0 if observation i contains a missing value for any of those variables in the selected subset v 1,v 2,…,vp for which missing values have been declared, i.e., if x ij=xmj for any j (j=v 1,v 2,…,vp) for which an xmj has been assigned (see also Section 7); and wi=1 otherwise, for i=1,2,…,n.
The quantities calculated are:
(a) Means:
x-j=∑i=1 n wix ij ∑i=1 n wi ,  j=v 1,v 2,…,vp.
(b) Standard deviations:
sj= ∑i= 1 n wi x ij-x-j 2 ∑i= 1 n wi- 1 ,   j=v 1,v 2,…,vp.
(c) Sums of squares and cross-products of deviations from means:
S jk=∑i=1 n wi x ij-x-jx ik-x-k,  j,k=v 1,v 2,…,vp.
(d) Pearson product-moment correlation coefficients:
R jk=S jk S jjS kk ,   j,k=v 1,v 2,…,vp.
If S jj or S kk is zero, R jk is set to zero.

4 References

None.

5 Arguments

1:   N – INTEGERInput
On entry: n, the number of observations or cases.
Constraint: N≥2.
2:   M – INTEGERInput
On entry: m, the number of variables.
Constraint: M≥2.
3:   X LDXM – REAL (KIND=nag_wp) arrayInput
On entry: X ij must be set to x ij, the value of the ith observation on the jth variable, for i=1,2,…,n and j=1,2,…,m.
4:   LDX – INTEGERInput
On entry: the first dimension of the array X as declared in the (sub)program from which G02BHF is called.
Constraint: LDX≥N.
5:   MISS M – INTEGER arrayInput/Output
On entry: MISS j must be set equal to 1 if a missing value, x mj, is to be specified for the jth variable in the array X, or set equal to 0 otherwise. Values of MISS must be given for all m variables in the array X.
On exit: the array MISS is overwritten by the routine, and the information it contained on entry is lost.
6:   XMISS M – REAL (KIND=nag_wp) arrayInput/Output
On entry: XMISS j must be set to the missing value, x mj, to be associated with the jth variable in the array X, for those variables for which missing values are specified by means of the array MISS (see Section 7).
On exit: the array XMISS is overwritten by the routine, and the information it contained on entry is lost.
7:   MISTYP – INTEGERInput
On entry: indicates the manner in which missing observations are to be treated.
MISTYP=1
A case is excluded if it contains a missing value for any of the variables 1,2,…,m.
MISTYP=0
A case is excluded if it contains a missing value for any of the p≤m variables specified in the array KVAR.
8:   NVARS – INTEGERInput
On entry: p, the number of variables for which information is required.
Constraint: 2≤NVARS≤M.
9:   KVAR NVARS – INTEGER arrayInput
On entry: KVAR j must be set to the column number in X of the jth variable for which information is required, for j=1,2,…,p.
Constraint: 1≤KVAR j≤M, for j=1,2,…,p.
10:   XBAR NVARS – REAL (KIND=nag_wp) arrayOutput
On exit: the mean value, of x-j, of the variable specified in KVAR j, for j=1,2,…,p.
11:   STD NVARS – REAL (KIND=nag_wp) arrayOutput
On exit: the standard deviation, sj, of the variable specified in KVAR j, for j=1,2,…,p.
12:   SSP LDSSPNVARS – REAL (KIND=nag_wp) arrayOutput
On exit: SSP jk is the cross-product of deviations, S jk, for the variables specified in KVAR j and KVAR k, for j=1,2,…,p and k=1,2,…,p.
13:   LDSSP – INTEGERInput
On entry: the first dimension of the array SSP as declared in the (sub)program from which G02BHF is called.
Constraint: LDSSP≥NVARS.
14:   R LDRNVARS – REAL (KIND=nag_wp) arrayOutput
On exit: R jk is the product-moment correlation coefficient, R jk, between the variables specified in KVAR j and KVAR k, for j=1,2,…,p and k=1,2,…,p.
15:   LDR – INTEGERInput
On entry: the first dimension of the array R as declared in the (sub)program from which G02BHF is called.
Constraint: LDR≥NVARS.
16:   NCASES – INTEGEROutput
On exit: the number of cases actually used in the calculations (when cases involving missing values have been eliminated).
17:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, N<2.
IFAIL=2
On entry, | NVARS<2,
or | NVARS>M.
IFAIL=3
On entry, | LDX<N,
or | LDSSP<NVARS,
or | LDR<NVARS.
IFAIL=4
On entry, | KVAR j<1,
or | KVAR j>M for some j=1,2,…,NVARS.
IFAIL=5
On entry, MISTYP≠1 or 0
IFAIL=6
After observations with missing values were omitted, no cases remained.
IFAIL=7
After observations with missing values were omitted, only one case remained.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

G02BHF does not use additional precision arithmetic for the accumulation of scalar products, so there may be a loss of significant figures for large n.
You are warned of the need to exercise extreme care in your selection of missing values. G02BHF treats all values in the inclusive range 1±0.1 X02BEF-2×xm j, where xmj is the missing value for variable j specified in XMISS.
You must therefore ensure that the missing value chosen for each variable is sufficiently different from all valid values for that variable so that none of the valid values fall within the range indicated above.

8 Parallelism and Performance

G02BHF is not threaded in any implementation.

9 Further Comments

The time taken by G02BHF depends on n and p, and the occurrence of missing values.
The routine uses a two-pass algorithm.

10 Example

This example reads in a set of data consisting of five observations on each of four variables. Missing values of 0.0 are declared for the second and fourth variables; no missing values are specified for the first and third variables. The means, standard deviations, sums of squares and cross-products of deviations from means, and Pearson product-moment correlation coefficients for the fourth, first and second variables are then calculated and printed, omitting completely all cases containing missing values for these three selected variables; cases 3 and 4 are therefore eliminated, leaving only three cases in the calculations.

10.1 Program Text

Program Text (g02bhfe.f90)

10.2 Program Data

Program Data (g02bhfe.d)

10.3 Program Results

Program Results (g02bhfe.r)

G02 Chapter Contents
G02 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


G02BJF : NAG Library, Mark 26

G02 Chapter Contents
G02 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

G02BJF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

G02BJF computes means and standard deviations, sums of squares and cross-products of deviations from means, and Pearson product-moment correlation coefficients for selected variables omitting cases with missing values from only those calculations involving the variables for which the values are missing.

2 Specification

SUBROUTINE G02BJF ( N, M, X, LDX, MISS, XMISS, NVARS, KVAR, XBAR, STD, SSP, LDSSP, R, LDR, NCASES, CNT, LDCNT, IFAIL)
INTEGER | N, M, LDX, MISS(M), NVARS, KVAR(NVARS), LDSSP, LDR, NCASES, LDCNT, IFAIL
REAL (KIND=nag_wp) | X(LDX,M), XMISS(M), XBAR(NVARS), STD(NVARS), SSP(LDSSP,NVARS), R(LDR,NVARS), CNT(LDCNT,NVARS)

3 Description

The input data consists of n observations for each of m variables, given as an array
x ij,  i=1,2,…,n n≥2,j=1,2,…,m m≥2,
where x ij is the ith observation on the jth variable, together with the subset of these variables, v 1,v 2,…,vp, for which information is required.
In addition, each of the m variables may optionally have associated with it a value which is to be considered as representing a missing observation for that variable; the missing value for the jth variable is denoted by xmj. Missing values need not be specified for all variables.
Let w ij=0 if the ith observation for the jth variable is a missing value, i.e., if a missing value, xmj, has been declared for the jth variable, and x ij=xmj (see also Section 7); and w ij=1 otherwise, for i=1,2,…,n and j=1,2,…,m.
The quantities calculated are:
(a) Means:
x-j=∑i=1 n w ijx ij ∑i=1 n w ij ,  j=v 1,v 2,…,vp.
(b) Standard deviations:
sj=∑i= 1 n w ij x ij-x-j 2 ∑i= 1 n w ij- 1 ,   j=v 1,v 2,…,vp.
(c) Sums of squares and cross-products of deviations from means:
S jk=∑i=1 n w ijw ik x ij-x-j kx ik-x-k j,  j,k=v 1,v 2,…,vp,
where
x-j k=∑i= 1 n w ijw ikx ij ∑i= 1 n w ijw ik   and   x-k j=∑i= 1 n w ikw ijx ik ∑i= 1 n w ikw ij ,
(i.e., the means used in the calculation of the sum of squares and cross-products of deviations are based on the same set of observations as are the cross-products).
(d) Pearson product-moment correlation coefficients:
R jk=S jk S jj kS kk j ,  j,k=v 1,v 2,…,vp,
where
S jj k=∑i= 1 n w ijw ik x ij-x-j k 2   and   S kk j=∑i= 1 n w ikw ij x ik-x-k j 2,
(i.e., the sums of squares of deviations used in the denominator are based on the same set of observations as are used in the calculation of the numerator).
If S jj k or S kk j is zero, R jk is set to zero.
(e) The number of cases used in the calculation of each of the correlation coefficients:
c jk=∑i=1 n w ijw ik,  j,k=v 1,v 2,…,vp.
(The diagonal terms, c jj, for j=v 1,v 2,…,vp, also give the number of cases used in the calculation of the means, x-j, and the standard deviations, sj.)

4 References

None.

5 Arguments

1:   N – INTEGERInput
On entry: n, the number of observations or cases.
Constraint: N≥2.
2:   M – INTEGERInput
On entry: m, the number of variables.
Constraint: M≥2.
3:   X LDXM – REAL (KIND=nag_wp) arrayInput
On entry: X ij must be set to x ij, the value of the ith observation on the jth variable, for i=1,2,…,n and j=1,2,…,m.
4:   LDX – INTEGERInput
On entry: the first dimension of the array X as declared in the (sub)program from which G02BJF is called.
Constraint: LDX≥N.
5:   MISS M – INTEGER arrayInput
On entry: MISS j must be set equal to 1 if a missing value, x mj, is to be specified for the jth variable in the array X, or set equal to 0 otherwise. Values of MISS must be given for all m variables in the array X.
6:   XMISS M – REAL (KIND=nag_wp) arrayInput
On entry: XMISS j must be set to the missing value, x mj, to be associated with the jth variable in the array X, for those variables for which missing values are specified by means of the array MISS (see Section 7).
7:   NVARS – INTEGERInput
On entry: p, the number of variables for which information is required.
Constraint: 2≤NVARS≤M.
8:   KVAR NVARS – INTEGER arrayInput
On entry: KVAR j must be set to the column number in X of the jth variable for which information is required, for j=1,2,…,p.
Constraint: 1≤KVAR j≤M, for j=1,2,…,p.
9:   XBAR NVARS – REAL (KIND=nag_wp) arrayOutput
On exit: the mean value, x-j, of the variable specified in KVAR j, for j=1,2,…,p.
10:   STD NVARS – REAL (KIND=nag_wp) arrayOutput
On exit: the standard deviation, sj, of the variable specified in KVAR j, for j=1,2,…,p.
11:   SSP LDSSPNVARS – REAL (KIND=nag_wp) arrayOutput
On exit: SSP jk is the cross-product of deviations, S jk, for the variables specified in KVAR j and KVAR k, for j=1,2,…,p and k=1,2,…,p.
12:   LDSSP – INTEGERInput
On entry: the first dimension of the array SSP as declared in the (sub)program from which G02BJF is called.
Constraint: LDSSP≥NVARS.
13:   R LDRNVARS – REAL (KIND=nag_wp) arrayOutput
On exit: R jk is the product-moment correlation coefficient, R jk, between the variables specified in KVAR j and KVAR k, for j=1,2,…,p and k=1,2,…,p.
14:   LDR – INTEGERInput
On entry: the first dimension of the array R as declared in the (sub)program from which G02BJF is called.
Constraint: LDR≥NVARS.
15:   NCASES – INTEGEROutput
On exit: the minimum number of cases used in the calculation of any of the sums of squares and cross-products and correlation coefficients (when cases involving missing values have been eliminated).
16:   CNT LDCNTNVARS – REAL (KIND=nag_wp) arrayOutput
On exit: CNT jk is the number of cases, c jk, actually used in the calculation of S jk, and R jk, the sum of cross-products and correlation coefficient for the variables specified in KVAR j and KVAR k, for j=1,2,…,p and k=1,2,…,p.
17:   LDCNT – INTEGERInput
On entry: the first dimension of the array CNT as declared in the (sub)program from which G02BJF is called.
Constraint: LDCNT≥NVARS.
18:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, because for this routine the values of the output arguments may be useful even if IFAIL≠0 on exit, the recommended value is -1. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Note: G02BJF may return useful information for one or more of the following detected errors or warnings.
Errors or warnings detected by the routine:
IFAIL=1
On entry, N<2.
IFAIL=2
On entry, | NVARS<2,
or | NVARS>M.
IFAIL=3
On entry, | LDX<N,
or | LDSSP<NVARS,
or | LDR<NVARS,
or | LDCNT<NVARS.
IFAIL=4
On entry, | KVAR j<1,
or | KVAR j>M for some j=1,2,…,NVARS.
IFAIL=5
After observations with missing values were omitted, fewer than two cases remained for at least one pair of variables. (The pairs of variables involved can be determined by examination of the contents of the array CNT.) All means, standard deviations, sums of squares and cross-products, and correlation coefficients based on two or more cases are returned by the routine even if IFAIL=5.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

G02BJF does not use additional precision arithmetic for the accumulation of scalar products, so there may be a loss of significant figures for large n.
You are warned of the need to exercise extreme care in your selection of missing values. G02BJF treats all values in the inclusive range 1±0.1 X02BEF-2×xm j, where xmj is the missing value for variable j specified in XMISS.
You must therefore ensure that the missing value chosen for each variable is sufficiently different from all valid values for that variable so that none of the valid values fall within the range indicated above.

8 Parallelism and Performance

G02BJF is not threaded in any implementation.

9 Further Comments

The time taken by G02BJF depends on n and p, and the occurrence of missing values.
The routine uses a two-pass algorithm.

10 Example

This example reads in a set of data consisting of five observations on each of four variables. Missing values of -1.0, 0.0 and 0.0 are declared for the first, second and fourth variables respectively; no missing value is specified for the third variable. The means, standard deviations, sums of squares and cross-products of deviations from means, and Pearson product-moment correlation coefficients for the fourth, first and second variables are then calculated and printed, omitting cases with missing values from only those calculations involving the variables for which the values are missing. The program therefore eliminates cases 4 and 5 in calculating the correlation between the fourth and first variables, and cases 3 and 4 for the fourth and second variables etc.

10.1 Program Text

Program Text (g02bjfe.f90)

10.2 Program Data

Program Data (g02bjfe.d)

10.3 Program Results

Program Results (g02bjfe.r)

G02 Chapter Contents
G02 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


G02BKF : NAG Library, Mark 26

G02 Chapter Contents
G02 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

G02BKF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

G02BKF computes means and standard deviations, sums of squares and cross-products about zero, and correlation-like coefficients for selected variables.

2 Specification

SUBROUTINE G02BKF ( N, M, X, LDX, NVARS, KVAR, XBAR, STD, SSPZ, LDSSPZ, RZ, LDRZ, IFAIL)
INTEGER | N, M, LDX, NVARS, KVAR(NVARS), LDSSPZ, LDRZ, IFAIL
REAL (KIND=nag_wp) | X(LDX,M), XBAR(NVARS), STD(NVARS), SSPZ(LDSSPZ,NVARS), RZ(LDRZ,NVARS)

3 Description

The input data consists of n observations for each of m variables, given as an array
x ij,  i=1,2,…,n n≥2,j=1,2,…,m m≥2,
where x ij is the ith observation on the jth variable, together with the subset of these variables, v 1,v 2,…,vp, for which information is required.
The quantities calculated are:
(a) Means:
x-j=∑i=1 n x ij n,  j=v 1,v 2,…,vp.
(b) Standard deviations:
sj=1 n- 1 ∑i= 1 n x ij-x-j 2,   j=v 1,v 2,…,vp.
(c) Sums of squares and cross-products about zero:
S~jk=∑i=1 n x ijx ik,  j,k=v 1,v 2,…,vp.
(d) Correlation-like coefficients:
R~jk=S~jk S~jjS~kk ,   j,k=v 1,v 2,…,vp.
If S~jj or S~kk is zero, R~jk is set to zero.

4 References

None.

5 Arguments

1:   N – INTEGERInput
On entry: n, the number of observations or cases.
Constraint: N≥2.
2:   M – INTEGERInput
On entry: m, the number of variables.
Constraint: M≥2.
3:   X LDXM – REAL (KIND=nag_wp) arrayInput
On entry: X ij must be set to x ij, the value of the ith observation on the jth variable, for i=1,2,…,n and j=1,2,…,m.
4:   LDX – INTEGERInput
On entry: the first dimension of the array X as declared in the (sub)program from which G02BKF is called.
Constraint: LDX≥N.
5:   NVARS – INTEGERInput
On entry: p, the number of variables for which information is required.
Constraint: 2≤NVARS≤M.
6:   KVAR NVARS – INTEGER arrayInput
On entry: KVAR j must be set to the column number in X of the jth variable for which information is required, for j=1,2,…,p.
Constraint: 1≤KVAR j≤M, for j=1,2,…,p.
7:   XBAR NVARS – REAL (KIND=nag_wp) arrayOutput
On exit: the mean value, x-j, of the variable specified in KVAR j, for j=1,2,…,p.
8:   STD NVARS – REAL (KIND=nag_wp) arrayOutput
On exit: the standard deviation, sj, of the variable specified in KVAR j, for j=1,2,…,p.
9:   SSPZ LDSSPZNVARS – REAL (KIND=nag_wp) arrayOutput
On exit: SSPZ jk is the cross-product about zero, S~jk, for the variables specified in KVAR j and KVAR k, for j=1,2,…,p and k=1,2,…,p.
10:   LDSSPZ – INTEGERInput
On entry: the first dimension of the array SSPZ as declared in the (sub)program from which G02BKF is called.
Constraint: LDSSPZ≥NVARS.
11:   RZ LDRZNVARS – REAL (KIND=nag_wp) arrayOutput
On exit: RZ jk is the correlation-like coefficient, R~jk, between the variables specified in KVAR j and KVAR k, for j=1,2,…,p and k=1,2,…,p.
12:   LDRZ – INTEGERInput
On entry: the first dimension of the array RZ as declared in the (sub)program from which G02BKF is called.
Constraint: LDRZ≥NVARS.
13:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, N<2.
IFAIL=2
On entry, | NVARS<2,
or | NVARS>M.
IFAIL=3
On entry, | LDX<N,
or | LDSSPZ<NVARS,
or | LDRZ<NVARS.
IFAIL=4
On entry, | KVAR j<1,
or | KVAR j>M for some j=1,2,…,NVARS.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

G02BKF does not use additional precision arithmetic for the accumulation of scalar products, so there may be a loss of significant figures for large n.

8 Parallelism and Performance

G02BKF is not threaded in any implementation.

9 Further Comments

The time taken by G02BKF depends on n and p.
The routine uses a two-pass algorithm.

10 Example

This example reads in a set of data consisting of five observations on each of four variables. The means, standard deviations, sums of squares and cross-products about zero, and correlation-like coefficients for the fourth, first and second variables are then calculated and printed.

10.1 Program Text

Program Text (g02bkfe.f90)

10.2 Program Data

Program Data (g02bkfe.d)

10.3 Program Results

Program Results (g02bkfe.r)

G02 Chapter Contents
G02 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


G02BLF : NAG Library, Mark 26

G02 Chapter Contents
G02 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

G02BLF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

G02BLF computes means and standard deviations, sums of squares and cross-products about zero, and correlation-like coefficients for selected variables omitting completely any cases with a missing observation for any variable (either over all variables in the dataset or over only those variables in the selected subset).

2 Specification

SUBROUTINE G02BLF ( N, M, X, LDX, MISS, XMISS, MISTYP, NVARS, KVAR, XBAR, STD, SSPZ, LDSSPZ, RZ, LDRZ, NCASES, IFAIL)
INTEGER | N, M, LDX, MISS(M), MISTYP, NVARS, KVAR(NVARS), LDSSPZ, LDRZ, NCASES, IFAIL
REAL (KIND=nag_wp) | X(LDX,M), XMISS(M), XBAR(NVARS), STD(NVARS), SSPZ(LDSSPZ,NVARS), RZ(LDRZ,NVARS)

3 Description

The input data consist of n observations for each of m variables, given as an array
x ij ,   i=1,2,…,n n≥2 ​ and ​ j=1,2,…,m m≥2 ,
where x ij is the ith observation on the jth variable, together with the subset of these variables, v 1,v 2,…,vp, for which information is required.
In addition, each of the m variables may optionally have associated with it a value which is to be considered as representing a missing observation for that variable; the missing value for the jth variable is denoted by xmj. Missing values need not be specified for all variables.
The missing values can be utilized in two slightly different ways, you can indicate which scheme is required.
Firstly, let wi=0 if observation i contains a missing value for any of those variables in the set 1,2,…,m for which missing values have been declared, i.e., if x ij=xmj for any j (j=1,2,…,m) for which an xmj has been assigned (see also Section 7); and wi=1 otherwise, for i=1,2,…,n.
Secondly, let wi=0 if observation i contains a missing value for any of those variables in the selected subset v 1,v 2,…,vp for which missing values have been declared, i.e., if x ij=xmj for any j j=v 1,v 2,…,vp for which an xmj has been assigned (see also Section 7); and wi=1 otherwise, for i=1,2,…,n.
The quantities calculated are:
(a) Means:
x-j=∑i=1 n wix ij ∑i=1 n wi ,  j=v 1,v 2,…,vp.
(b) Standard deviations:
Sj=∑i= 1 n wi x ij-x-j 2 ∑i= 1 n wi- 1 ,   j=v 1,v 2,…,vp.
(c) Sums of squares and cross-products about zero:
S~jk=∑i=1 n wix ijx ik,  j,k=v 1,v 2,…,vp.
(d) Correlation-like coefficients:
R~jk=S~jk S~jjS~kk ,   j,k=v 1,v 2,…,vp.
If S~jj or S~kk is zero, R~jk is set to zero.

4 References

None.

5 Arguments

1:   N – INTEGERInput
On entry: n, the number of observations or cases.
Constraint: N≥2.
2:   M – INTEGERInput
On entry: m, the number of variables.
Constraint: M≥2.
3:   X LDXM – REAL (KIND=nag_wp) arrayInput
On entry: X ij must be set to x ij, the value of the ith observation on the jth variable, for i=1,2,…,n and j=1,2,…,m.
4:   LDX – INTEGERInput
On entry: the first dimension of the array X as declared in the (sub)program from which G02BLF is called.
Constraint: LDX≥N.
5:   MISS M – INTEGER arrayInput/Output
On entry: MISS j must be set equal to 1 if a missing value, x mj, is to be specified for the jth variable in the array X, or set equal to 0 otherwise. Values of MISS must be given for all m variables in the array X.
On exit: the array MISS is overwritten by the routine, and the information it contained on entry is lost.
6:   XMISS M – REAL (KIND=nag_wp) arrayInput/Output
On entry: XMISS j must be set to the missing value, x mj, to be associated with the jth variable in the array X, for those variables for which missing values are specified by means of the array MISS (see Section 7).
On exit: the array XMISS is overwritten by the routine, and the information it contained on entry is lost.
7:   MISTYP – INTEGERInput
On entry: indicates the manner in which missing observations are to be treated.
MISTYP=1
A case is excluded if it contains a missing value for any of the variables 1,2,…,m.
MISTYP=0
A case is excluded if it contains a missing value for any of the p≤m variables specified in the array KVAR.
8:   NVARS – INTEGERInput
On entry: p, the number of variables for which information is required.
Constraint: 2≤NVARS≤M.
9:   KVAR NVARS – INTEGER arrayInput
On entry: KVAR j must be set to the column number in X of the jth variable for which information is required, for j=1,2,…,p.
Constraint: 1≤KVAR j≤M, for j=1,2,…,p.
10:   XBAR NVARS – REAL (KIND=nag_wp) arrayOutput
On exit: the mean value, x-j, of the variable specified in KVAR j, for j=1,2,…,p.
11:   STD NVARS – REAL (KIND=nag_wp) arrayOutput
On exit: the standard deviation, sj, of the variable specified in KVAR j, for j=1,2,…,p.
12:   SSPZ LDSSPZNVARS – REAL (KIND=nag_wp) arrayOutput
On exit: SSPZ jk is the cross-product about zero, S~jk, for the variables specified in KVAR j and KVAR k, for j=1,2,…,p and k=1,2,…,p.
13:   LDSSPZ – INTEGERInput
On entry: the first dimension of the array SSPZ as declared in the (sub)program from which G02BLF is called.
Constraint: LDSSPZ≥NVARS.
14:   RZ LDRZNVARS – REAL (KIND=nag_wp) arrayOutput
On exit: RZ jk is the correlation-like coefficient, R~jk, between the variables specified in KVAR j and KVAR k, for j=1,2,…,p and k=1,2,…,p.
15:   LDRZ – INTEGERInput
On entry: the first dimension of the array RZ as declared in the (sub)program from which G02BLF is called.
Constraint: LDRZ≥NVARS.
16:   NCASES – INTEGEROutput
On exit: the number of cases actually used in the calculations (when cases involving missing values have been eliminated).
17:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, N<2.
IFAIL=2
On entry, | NVARS<2,
or | NVARS>M.
IFAIL=3
On entry, | LDX<N,
or | LDSSPZ<NVARS,
or | LDRZ<NVARS.
IFAIL=4
On entry, | KVAR j<1,
or | KVAR j>M for some j=1,2,…,NVARS.
IFAIL=5
On entry, MISTYP≠1 or 0.
IFAIL=6
After observations with missing values were omitted, no cases remained.
IFAIL=7
After observations with missing values were omitted, only one case remained.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

G02BLF does not use additional precision arithmetic for the accumulation of scalar products, so there may be a loss of significant figures for large n.
You are warned of the need to exercise extreme care in your selection of missing values. G02BLF treats all values in the inclusive range 1±0.1 X02BEF-2×xm j, where xmj is the missing value for variable j specified in XMISS.
You must therefore ensure that the missing value chosen for each variable is sufficiently different from all valid values for that variable so that none of the valid values fall within the range indicated above.

8 Parallelism and Performance

G02BLF is not threaded in any implementation.

9 Further Comments

The time taken by G02BLF depends on n and p, and the occurrence of missing values.
The routine uses a two-pass algorithm.

10 Example

This example reads in a set of data consisting of five observations on each of four variables. Missing values of 0.0 are declared for the second and fourth variables; no missing values are specified for the first and third variables. The means, standard deviations, sums of squares and cross-products about zero, and correlation-like coefficients for the fourth, first and second variables are then calculated and printed, omitting completely all cases containing missing values for these three selected variables; cases 3 and 4 are therefore eliminated, leaving only three cases in the calculations.

10.1 Program Text

Program Text (g02blfe.f90)

10.2 Program Data

Program Data (g02blfe.d)

10.3 Program Results

Program Results (g02blfe.r)

G02 Chapter Contents
G02 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


G02BMF : NAG Library, Mark 26

G02 Chapter Contents
G02 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

G02BMF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

G02BMF computes means and standard deviations, sums of squares and cross-products about zero, and correlation-like coefficients for selected variables omitting cases with missing values from only those calculations involving the variables for which the values are missing.

2 Specification

SUBROUTINE G02BMF ( N, M, X, LDX, MISS, XMISS, NVARS, KVAR, XBAR, STD, SSPZ, LDSSPZ, RZ, LDRZ, NCASES, CNT, LDCNT, IFAIL)
INTEGER | N, M, LDX, MISS(M), NVARS, KVAR(NVARS), LDSSPZ, LDRZ, NCASES, LDCNT, IFAIL
REAL (KIND=nag_wp) | X(LDX,M), XMISS(M), XBAR(NVARS), STD(NVARS), SSPZ(LDSSPZ,NVARS), RZ(LDRZ,NVARS), CNT(LDCNT,NVARS)

3 Description

The input data consists of n observations for each of m variables, given as an array
x ij,  i=1,2,…,n n≥2,j=1,2,…,m m≥2,
where x ij is the ith observation on the jth variable, together with the subset of these variables, v 1,v 2,…,vp, for which information is required.
In addition, each of the m variables may optionally have associated with it a value which is to be considered as representing a missing observation for that variable; the missing value for the jth variable is denoted by xmj. Missing values need not be specified for all variables.
Let w ij=0, if the ith observation for the jth variable is a missing value, i.e., if a missing value, xmj, has been declared for the jth variable, and x ij=xmj (see also Section 7); and w ij=1 otherwise, for i=1,2,…,n and j=1,2,…,m.
The quantities calculated are:
(a) Means:
x-j=∑i=1 n w ijx ij ∑i=1 n w ij ,  j=v 1,v 2,…,vp.
(b) Standard deviations:
sj=∑i= 1 n w ij x ij-x-j 2 ∑i= 1 n w ij- 1 ,   j=v 1,v 2,…,vp.
(c) Sums of squares and cross-products about zero:
S~jk=∑i=1 n w ijw ikx ijx ik,  j,k=v 1,v 2,…,vp.
(d) Correlation-like coefficients:
R~jk=S~jk S~jj k S~kk j ,   j,k=v 1,v 2,…,vp ,
where S~jj k=∑i=1 n w ijw ik x ij 2 and S~kk j=∑i=1 n w ikw ij x ik 2
(i.e., the sums of squares about zero are based on the same set of observations as are used in the calculation of the numerator).
If S~jj k or S~kk j is zero, R~jk is set to zero.
(e) The number of cases used in the calculation of each of the correlation-like coefficients:
c jk=∑i=1 n w ijw ik,  j,k=v 1,v 2,…,vp.
(The diagonal terms, c jj, for j=1,2,…,n, also give the number of cases used in the calculation of the means x-j and the standard deviations sj.)

4 References

None.

5 Arguments

1:   N – INTEGERInput
On entry: n, the number of observations or cases.
Constraint: N≥2.
2:   M – INTEGERInput
On entry: m, the number of variables.
Constraint: M≥2.
3:   X LDXM – REAL (KIND=nag_wp) arrayInput
On entry: X ij must be set to x ij, the value of the ith observation on the jth variable, for i=1,2,…,n and j=1,2,…,m.
4:   LDX – INTEGERInput
On entry: the first dimension of the array X as declared in the (sub)program from which G02BMF is called.
Constraint: LDX≥N.
5:   MISS M – INTEGER arrayInput
On entry: MISS j must be set equal to 1 if a missing value, x mj, is to be specified for the jth variable in the array X, or set equal to 0 otherwise. Values of MISS must be given for all m variables in the array X.
6:   XMISS M – REAL (KIND=nag_wp) arrayInput
On entry: XMISS j must be set to the missing value, x mj, to be associated with the jth variable in the array X, for those variables for which missing values are specified by means of the array MISS (see Section 7).
7:   NVARS – INTEGERInput
On entry: p, the number of variables for which information is required.
Constraint: 2≤NVARS≤M.
8:   KVAR NVARS – INTEGER arrayInput
On entry: KVAR j must be set to the column number in X of the jth variable for which information is required, for j=1,2,…,p.
Constraint: 1≤KVAR j≤M, for j=1,2,…,p.
9:   XBAR NVARS – REAL (KIND=nag_wp) arrayOutput
On exit: the mean value, x-j, of the variable specified in KVAR j, for j=1,2,…,p.
10:   STD NVARS – REAL (KIND=nag_wp) arrayOutput
On exit: the standard deviation, sj, of the variable specified in KVAR j, for j=1,2,…,p.
11:   SSPZ LDSSPZNVARS – REAL (KIND=nag_wp) arrayOutput
On exit: SSPZ jk is the cross-product about zero, S~jk, for the variables specified in KVAR j and KVAR k, for j=1,2,…,p and k=1,2,…,p.
12:   LDSSPZ – INTEGERInput
On entry: the first dimension of the array SSPZ as declared in the (sub)program from which G02BMF is called.
Constraint: LDSSPZ≥NVARS.
13:   RZ LDRZNVARS – REAL (KIND=nag_wp) arrayOutput
On exit: RZ jk is the correlation-like coefficient, R~jk, between the variables specified in KVAR j and KVAR k, for j=1,2,…,p and k=1,2,…,p.
14:   LDRZ – INTEGERInput
On entry: the first dimension of the array RZ as declared in the (sub)program from which G02BMF is called.
Constraint: LDRZ≥NVARS.
15:   NCASES – INTEGEROutput
On exit: the minimum number of cases used in the calculation of any of the sums of squares and cross-products and correlation-like coefficients (when cases involving missing values have been eliminated).
16:   CNT LDCNTNVARS – REAL (KIND=nag_wp) arrayOutput
On exit: CNT jk is the number of cases, c jk, actually used in the calculation of the sum of cross-product and correlation-like coefficient for the variables specified in KVAR j and KVAR k, for j=1,2,…,p and k=1,2,…,p.
17:   LDCNT – INTEGERInput
On entry: the first dimension of the array CNT as declared in the (sub)program from which G02BMF is called.
Constraint: LDCNT≥NVARS.
18:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, because for this routine the values of the output arguments may be useful even if IFAIL≠0 on exit, the recommended value is -1. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Note: G02BMF may return useful information for one or more of the following detected errors or warnings.
Errors or warnings detected by the routine:
IFAIL=1
On entry, N<2.
IFAIL=2
On entry, | NVARS<2,
or | NVARS>M.
IFAIL=3
On entry, | LDX<N,
or | LDSSPZ<NVARS,
or | LDRZ<NVARS,
or | LDCNT<NVARS.
IFAIL=4
On entry, | KVAR j<1,
or | KVAR j>M for some j=1,2,…,NVARS.
IFAIL=5
After observations with missing values were omitted, fewer than two cases remained for at least one pair of variables. (The pairs of variables involved can be determined by examination of the contents of the array CNT.) All means, standard deviations, sums of squares and cross-products, and correlation-like coefficients based on two or more cases are returned by the routine even if IFAIL=5.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

G02BMF does not use additional precision arithmetic for the accumulation of scalar products, so there may be a loss of significant figures for large n.
You are warned of the need to exercise extreme care in your selection of missing values. G02BMF treats all values in the inclusive range 1±0.1 X02BEF-2×xm j, where xmj is the missing value for variable j specified in XMISS.
You must therefore ensure that the missing value chosen for each variable is sufficiently different from all valid values for that variable so that none of the valid values fall within the range indicated above.

8 Parallelism and Performance

G02BMF is not threaded in any implementation.

9 Further Comments

The time taken by G02BMF depends on n and p, and the occurrence of missing values.
The routine uses a two-pass algorithm.

10 Example

This example reads in a set of data consisting of five observations on each of four variables. Missing values of -1.0, 0.0 and 0.0 are declared for the first, second and fourth variables respectively; no missing value is specified for the third variable. The means, standard deviations, sums of squares and cross-products about zero, and correlation-like coefficients for the fourth, first and second variables are then calculated and printed, omitting cases with missing values from only those calculations involving the variables for which the values are missing. The program therefore eliminates cases 4 and 5 in calculating the correlation between the fourth and first variable, and cases 3 and 4 for the fourth and second variables, etc.

10.1 Program Text

Program Text (g02bmfe.f90)

10.2 Program Data

Program Data (g02bmfe.d)

10.3 Program Results

Program Results (g02bmfe.r)

G02 Chapter Contents
G02 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


G02BNF : NAG Library, Mark 26

G02 Chapter Contents
G02 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

G02BNF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

G02BNF computes Kendall and/or Spearman nonparametric rank correlation coefficients for a set of data; the data array is overwritten with the ranks of the observations.

2 Specification

SUBROUTINE G02BNF ( N, M, X, LDX, ITYPE, RR, LDRR, KWORKA, KWORKB, WORK1, WORK2, IFAIL)
INTEGER | N, M, LDX, ITYPE, LDRR, KWORKA(N), KWORKB(N), IFAIL
REAL (KIND=nag_wp) | X(LDX,M), RR(LDRR,M), WORK1(M), WORK2(M)

3 Description

The input data consists of n observations for each of m variables, given as an array
x ij,  i=1,2,…,n n≥2,j=1,2,…,m m≥2,
where x ij is the ith observation of the jth variable.
The quantities calculated are:
(a) Ranks
For a given variable, j say, each of the n observations, x 1 j,x 2 j,…,x nj, has associated with it an additional number, the ‘rank’ of the observation, which indicates the magnitude of that observation relative to the magnitudes of the other n-1 observations on that same variable.
The smallest observation for variable j is assigned the rank 1, the second smallest observation for variable j the rank 2, the third smallest the rank 3, and so on until the largest observation for variable j is given the rank n.
If a number of cases all have the same value for the given variable, j, then they are each given an ‘average’ rank, e.g., if in attempting to assign the rank h+1, k observations were found to have the same value, then instead of giving them the ranks
h+1,h+2,…,h+k,
all k observations would be assigned the rank
2 h+k+1 2
and the next value in ascending order would be assigned the rank
h+k+ 1.
The process is repeated for each of the m variables.
Let y ij be the rank assigned to the observation x ij when the jth variable is being ranked. The actual observations x ij are replaced by the ranks y ij.
(b) Nonparametric rank correlation coefficients
(i) Kendall's tau:
R jk=∑h=1 n∑i=1 n sign y hj-y ijsign y hk-y ik n n-1-Tjn n-1-Tk ,  j,k=1,2,…,m,
where | sign⁡u=1 if u>0,
 | sign⁡u=0 if u=0,
 | sign⁡u=-1 if u<0,
and Tj=∑tj tj-1, where tj is the number of ties of a particular value of variable j, and the summation is over all tied values of variable j.
(ii) Spearman's:
R jk*=n n 2-1-6∑i=1 n y ij-y ik 2-12 Tj*+Tk* n n 2-1-Tj*n n 2-1-Tk* ,  j,k=1,2,…,m,
where Tj*=∑tj tj 2-1, tj being the number of ties of a particular value of variable j, and the summation being over all tied values of variable j.

4 References

Siegel S (1956) Non-parametric Statistics for the Behavioral Sciences McGraw–Hill

5 Arguments

1:   N – INTEGERInput
On entry: n, the number of observations or cases.
Constraint: N≥2.
2:   M – INTEGERInput
On entry: m, the number of variables.
Constraint: M≥2.
3:   X LDXM – REAL (KIND=nag_wp) arrayInput/Output
On entry: X ij must be set to x ij, the value of the ith observation on the jth variable, for i=1,2,…,n and j=1,2,…,m.
On exit: X ij contains the rank y ij of the observation x ij, for i=1,2,…,n and j=1,2,…,m.
4:   LDX – INTEGERInput
On entry: the first dimension of the array X as declared in the (sub)program from which G02BNF is called.
Constraint: LDX≥N.
5:   ITYPE – INTEGERInput
On entry: the type of correlation coefficients which are to be calculated.
ITYPE=-1
Only Kendall's tau coefficients are calculated.
ITYPE=0
Both Kendall's tau and Spearman's coefficients are calculated.
ITYPE=1
Only Spearman's coefficients are calculated.
Constraint: ITYPE=-1, 0 or 1.
6:   RR LDRRM – REAL (KIND=nag_wp) arrayOutput
On exit: the requested correlation coefficients.
If only Kendall's tau coefficients are requested (ITYPE=-1), RR jk contains Kendall's tau for the jth and kth variables.
If only Spearman's coefficients are requested (ITYPE=1), RR jk contains Spearman's rank correlation coefficient for the jth and kth variables.
If both Kendall's tau and Spearman's coefficients are requested (ITYPE=0), the upper triangle of RR contains the Spearman coefficients and the lower triangle the Kendall coefficients. That is, for the jth and kth variables, where j is less than k, RR jk contains the Spearman rank correlation coefficient, and RR kj contains Kendall's tau, for j=1,2,…,m and k=1,2,…,m.
(Diagonal terms, RR jj, are unity for all three values of ITYPE.)
7:   LDRR – INTEGERInput
On entry: the first dimension of the array RR as declared in the (sub)program from which G02BNF is called.
Constraint: LDRR≥M.
8:   KWORKA N – INTEGER arrayWorkspace
9:   KWORKB N – INTEGER arrayWorkspace
10:   WORK1 M – REAL (KIND=nag_wp) arrayWorkspace
11:   WORK2 M – REAL (KIND=nag_wp) arrayWorkspace
12:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, N<2.
IFAIL=2
On entry, M<2.
IFAIL=3
On entry, | LDX<N,
or | LDRR<M.
IFAIL=4
On entry, | ITYPE<-1,
or | ITYPE>1.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

The method used is believed to be stable.

8 Parallelism and Performance

G02BNF is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The time taken by G02BNF depends on n and m.

10 Example

This example reads in a set of data consisting of nine observations on each of three variables. The program then calculates and prints the rank of each observation, and both Kendall's tau and Spearman's rank correlation coefficients for all three variables.

10.1 Program Text

Program Text (g02bnfe.f90)

10.2 Program Data

Program Data (g02bnfe.d)

10.3 Program Results

Program Results (g02bnfe.r)

G02 Chapter Contents
G02 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


G02BPF : NAG Library, Mark 26

G02 Chapter Contents
G02 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

G02BPF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

G02BPF computes Kendall and/or Spearman nonparametric rank correlation coefficients for a set of data omitting completely any cases with a missing observation for any variable; the data array is overwritten with the ranks of the observations.

2 Specification

SUBROUTINE G02BPF ( N, M, X, LDX, MISS, XMISS, ITYPE, RR, LDRR, NCASES, INCASE, KWORKA, KWORKB, KWORKC, WORK1, WORK2, IFAIL)
INTEGER | N, M, LDX, MISS(M), ITYPE, LDRR, NCASES, INCASE(N), KWORKA(N), KWORKB(N), KWORKC(N), IFAIL
REAL (KIND=nag_wp) | X(LDX,M), XMISS(M), RR(LDRR,M), WORK1(M), WORK2(M)

3 Description

The input data consists of n observations for each of m variables, given as an array
x ij ,   i = 1,2,…,n n≥2 ,   j = 1,2,…,m m≥2 ,
where x ij is the ith observation on the jth variable. In addition, each of the m variables may optionally have associated with it a value which is to be considered as representing a missing observation for that variable; the missing value for the jth variable is denoted by xmj. Missing values need not be specified for all variables.
Let wi=0 if observation i contains a missing value for any of those variables for which missing values have been declared; i.e., if x ij=xmj for any j for which an xmj has been assigned (see also Section 7); and wi=1 otherwise, for i=1,2,…,n.
The quantities calculated are:
(a) Ranks
For a given variable, j say, each of the observations x ij for which wi=1, for i=1,2,…,n, has associated with it an additional number, the ‘rank’ of the observation, which indicates the magnitude of that observation relative to the magnitudes of the other observations on that same variable for which wi=1.
The smallest of these valid observations for variable j is assigned the rank 1, the second smallest observation for variable j the rank 2, the third smallest the rank 3, and so on until the largest such observation is given the rank nc, where nc=∑i=1 n wi.
If a number of cases all have the same value for the given variable, j, then they are each given an ‘average’ rank, e.g., if in attempting to assign the rank h+1, k observations for which wi=1 were found to have the same value, then instead of giving them the ranks
h+1,h+2,…,h+k,
all k observations would be assigned the rank
2 h+k+1 2
and the next value in ascending order would be assigned the rank
h+k+ 1.
The process is repeated for each of the m variables.
Let y ij be the rank assigned to the observation x ij when the jth variable is being ranked. For those observations, i, for which wi=0, y ij=0, for j=1,2,…,m.
The actual observations x ij are replaced by the ranks y ij, for i=1,2,…,n and j=1,2,…,m.
(b) Nonparametric rank correlation coefficients
(i) Kendall's tau:
R jk=∑h=1 n∑i=1 n whwi sign y hj-y ijsign y hk-y ik nc nc-1-Tjnc nc-1-Tk ,  j,k=1,2,…,m,
where | nc=∑i=1 n wi
and | sign⁡u=1 if u>0
 | sign⁡u=0 if u=0
 | sign⁡u=-1 if u<0
and Tj=∑tj tj-1 where tj is the number of ties of a particular value of variable j, and the summation is over all tied values of variable j.
(ii) Spearman's:
R jk*=nc nc 2-1-6∑i=1 n wi y ij-y ik 2-12 Tj*+Tk* nc nc 2-1-Tj*nc nc 2-1-Tk* ,  j,k=1,2,…,m,
where nc=∑i=1 n wi
and Tj*=∑tj tj 2-1 where tj is the number of ties of a particular value of variable j, and the summation is over all tied values of variable j.

4 References

Siegel S (1956) Non-parametric Statistics for the Behavioral Sciences McGraw–Hill

5 Arguments

1:   N – INTEGERInput
On entry: n, the number of observations or cases.
Constraint: N≥2.
2:   M – INTEGERInput
On entry: m, the number of variables.
Constraint: M≥2.
3:   X LDXM – REAL (KIND=nag_wp) arrayInput/Output
On entry: X ij must be set to x ij, the value of the ith observation on the jth variable, for i=1,2,…,n and j=1,2,…,m.
On exit: X ij contains the rank y ij of the observation x ij, for i=1,2,…,n and j=1,2,…,m. (For those observations containing missing values, and therefore excluded from the calculation, y ij=0, for j=1,2,…,m.)
4:   LDX – INTEGERInput
On entry: the first dimension of the array X as declared in the (sub)program from which G02BPF is called.
Constraint: LDX≥N.
5:   MISS M – INTEGER arrayInput/Output
On entry: MISS j must be set to 1 if a missing value, x mj, is to be specified for the jth variable in the array X, or set equal to 0 otherwise. Values of MISS must be given for all m variables in the array X.
On exit: the array MISS is overwritten by the routine, and the information it contained on entry is lost.
6:   XMISS M – REAL (KIND=nag_wp) arrayInput/Output
On entry: XMISS j must be set to the missing value, x mj, to be associated with the jth variable in the array X, for those variables for which missing values are specified by means of the array MISS (see Section 7).
On exit: the array XMISS is overwritten by the routine, and the information it contained on entry is lost.
7:   ITYPE – INTEGERInput
On entry: the type of correlation coefficients which are to be calculated.
ITYPE=-1
Only Kendall's tau coefficients are calculated.
ITYPE=0
Both Kendall's tau and Spearman's coefficients are calculated.
ITYPE=1
Only Spearman's coefficients are calculated.
Constraint: ITYPE=-1, 0 or 1.
8:   RR LDRRM – REAL (KIND=nag_wp) arrayOutput
On exit: the requested correlation coefficients.
If only Kendall's tau coefficients are requested (ITYPE=-1), RR jk contains Kendall's tau for the jth and kth variables.
If only Spearman's coefficients are requested (ITYPE=1), RR jk contains Spearman's rank correlation coefficient for the jth and kth variables.
If both Kendall's tau and Spearman's coefficients are requested (ITYPE=0), the upper triangle of RR contains the Spearman coefficients and the lower triangle the Kendall coefficients. That is, for the jth and kth variables, where j is less than k, RR jk contains the Spearman rank correlation coefficient, and RR kj contains Kendall's tau, for j=1,2,…,m and k=1,2,…,m.
(Diagonal terms, RR jj, are unity for all three values of ITYPE.)
9:   LDRR – INTEGERInput
On entry: the first dimension of the array RR as declared in the (sub)program from which G02BPF is called.
Constraint: LDRR≥M.
10:   NCASES – INTEGEROutput
On exit: the number of cases, nc, actually used in the calculations (when cases involving missing values have been eliminated).
11:   INCASE N – INTEGER arrayOutput
On exit: INCASE i holds the value 1 if the ith case was included in the calculations, and the value 0 if the ith case contained a missing value for at least one variable. That is, INCASE i=wi (see Section 3), for i=1,2,…,n.
12:   KWORKA N – INTEGER arrayWorkspace
13:   KWORKB N – INTEGER arrayWorkspace
14:   KWORKC N – INTEGER arrayWorkspace
15:   WORK1 M – REAL (KIND=nag_wp) arrayWorkspace
16:   WORK2 M – REAL (KIND=nag_wp) arrayWorkspace
17:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, N<2.
IFAIL=2
On entry, M<2.
IFAIL=3
On entry, | LDX<N,
or | LDRR<M.
IFAIL=4
On entry, | ITYPE<-1,
or | ITYPE>1.
IFAIL=5
After observations with missing values were omitted, fewer than 2 cases remained.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

You are warned of the need to exercise extreme care in your selection of missing values. G02BPF treats all values in the inclusive range 1±0.1 X02BEF-2×xm j, where xmj is the missing value for variable j specified in XMISS.
You must therefore ensure that the missing value chosen for each variable is sufficiently different from all valid values for that variable so that none of the valid values fall within the range indicated above.

8 Parallelism and Performance

G02BPF is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The time taken by G02BPF depends on n and m, and the occurrence of missing values.

10 Example

This example reads in a set of data consisting of nine observations on each of three variables. Missing values of 0.99 and 0.0 are declared for the first and third variables respectively; no missing value is specified for the second variable. The program then calculates and prints the rank of each observation, and both Kendall's tau and Spearman's rank correlation coefficients for all three variables, omitting completely all cases containing missing values; cases 5, 8 and 9 are therefore eliminated, leaving only six cases in the calculations.

10.1 Program Text

Program Text (g02bpfe.f90)

10.2 Program Data

Program Data (g02bpfe.d)

10.3 Program Results

Program Results (g02bpfe.r)

G02 Chapter Contents
G02 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


G02BQF : NAG Library, Mark 26

G02 Chapter Contents
G02 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

G02BQF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

G02BQF computes Kendall and/or Spearman nonparametric rank correlation coefficients for a set of data; the data array is preserved, and the ranks of the observations are not available on exit from the routine.

2 Specification

SUBROUTINE G02BQF ( N, M, X, LDX, ITYPE, RR, LDRR, KWORKA, KWORKB, WORK1, WORK2, IFAIL)
INTEGER | N, M, LDX, ITYPE, LDRR, KWORKA(N), KWORKB(N), IFAIL
REAL (KIND=nag_wp) | X(LDX,M), RR(LDRR,M), WORK1(N), WORK2(N)

3 Description

The input data consists of n observations for each of m variables, given as an array
x ij,  i=1,2,…,n n≥2,j=1,2,…,m m≥2,
where x ij is the ith observation on the jth variable.
The observations are first ranked, as follows.
For a given variable, j say, each of the n observations, x 1 j,x 2 j,…,x nj, has associated with it an additional number, the ‘rank’ of the observation, which indicates the magnitude of that observation relative to the magnitude of the other n-1 observations on that same variable.
The smallest observation for variable j is assigned the rank 1, the second smallest observation for variable j the rank 2, the third smallest the rank 3, and so on until the largest observation for variable j is given the rank n.
If a number of cases all have the same value for the given variable, j, then they are each given an ‘average’ rank – e.g., if in attempting to assign the rank h+1, k observations were found to have the same value, then instead of giving them the ranks
h+1,h+2,…,h+k,
all k observations would be assigned the rank
2 h+k+1 2
and the next value in ascending order would be assigned the rank
h+k+ 1.
The process is repeated for each of the m variables.
Let y ij be the rank assigned to the observation x ij when the jth variable is being ranked.
The quantities calculated are:
(a) Kendall's tau rank correlation coefficients:
R jk=∑h=1 n∑i=1 n sign y hj-y ijsign y hk-y ik n n-1-Tjn n-1-Tk ,  j,k=1,2,…,m,
and | sign⁡u=1 if u>0
 | sign⁡u=0 if u=0
 | sign⁡u=-1 if u<0
and Tj=∑tj tj-1, tj being the number of ties of a particular value of variable j, and the summation being over all tied values of variable j.
(b) Spearman's rank correlation coefficients:
R jk*=n n 2-1-6∑i=1 n y ij-y ik 2-12 Tj*+Tk* n n 2-1-Tj*n n 2-1-Tk* ,  j,k=1,2,…,m,
where Tj*=∑tj tj 2-1 where tj is the number of ties of a particular value of variable j, and the summation is over all tied values of variable j.

4 References

Siegel S (1956) Non-parametric Statistics for the Behavioral Sciences McGraw–Hill

5 Arguments

1:   N – INTEGERInput
On entry: n, the number of observations or cases.
Constraint: N≥2.
2:   M – INTEGERInput
On entry: m, the number of variables.
Constraint: M≥2.
3:   X LDXM – REAL (KIND=nag_wp) arrayInput
On entry: X ij must be set to data value x ij, the value of the ith observation on the jth variable, for i=1,2,…,n and j=1,2,…,m.
4:   LDX – INTEGERInput
On entry: the first dimension of the array X as declared in the (sub)program from which G02BQF is called.
Constraint: LDX≥N.
5:   ITYPE – INTEGERInput
On entry: the type of correlation coefficients which are to be calculated.
ITYPE=-1
Only Kendall's tau coefficients are calculated.
ITYPE=0
Both Kendall's tau and Spearman's coefficients are calculated.
ITYPE=1
Only Spearman's coefficients are calculated.
Constraint: ITYPE=-1, 0 or 1.
6:   RR LDRRM – REAL (KIND=nag_wp) arrayOutput
On exit: the requested correlation coefficients.
If only Kendall's tau coefficients are requested (ITYPE=-1), RR jk contains Kendall's tau for the jth and kth variables.
If only Spearman's coefficients are requested (ITYPE=1), RR jk contains Spearman's rank correlation coefficient for the jth and kth variables.
If both Kendall's tau and Spearman's coefficients are requested (ITYPE=0), the upper triangle of RR contains the Spearman coefficients and the lower triangle the Kendall coefficients. That is, for the jth and kth variables, where j is less than k, RR jk contains the Spearman rank correlation coefficient, and RR kj contains Kendall's tau, for j=1,2,…,m and k=1,2,…,m.
(Diagonal terms, RR jj, are unity for all three values of ITYPE.)
7:   LDRR – INTEGERInput
On entry: the first dimension of the array RR as declared in the (sub)program from which G02BQF is called.
Constraint: LDRR≥M.
8:   KWORKA N – INTEGER arrayWorkspace
9:   KWORKB N – INTEGER arrayWorkspace
10:   WORK1 N – REAL (KIND=nag_wp) arrayWorkspace
11:   WORK2 N – REAL (KIND=nag_wp) arrayWorkspace
12:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, N<2.
IFAIL=2
On entry, M<2.
IFAIL=3
On entry, | LDX<N,
or | LDRR<M.
IFAIL=4
On entry, | ITYPE<-1,
or | ITYPE>1.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

The method used is believed to be stable.

8 Parallelism and Performance

G02BQF is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The time taken by G02BQF depends on n and m.

10 Example

This example reads in a set of data consisting of nine observations on each of three variables. The program then calculates and prints both Kendall's tau and Spearman's rank correlation coefficients for all three variables.

10.1 Program Text

Program Text (g02bqfe.f90)

10.2 Program Data

Program Data (g02bqfe.d)

10.3 Program Results

Program Results (g02bqfe.r)

G02 Chapter Contents
G02 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


G02BRF : NAG Library, Mark 26

G02 Chapter Contents
G02 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

G02BRF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

G02BRF computes Kendall and/or Spearman nonparametric rank correlation coefficients for a set of data, omitting completely any cases with a missing observation for any variable; the data array is preserved, and the ranks of the observations are not available on exit from the routine.

2 Specification

SUBROUTINE G02BRF ( N, M, X, LDX, MISS, XMISS, ITYPE, RR, LDRR, NCASES, INCASE, KWORKA, KWORKB, KWORKC, WORK1, WORK2, IFAIL)
INTEGER | N, M, LDX, MISS(M), ITYPE, LDRR, NCASES, INCASE(N), KWORKA(N), KWORKB(N), KWORKC(N), IFAIL
REAL (KIND=nag_wp) | X(LDX,M), XMISS(M), RR(LDRR,M), WORK1(N), WORK2(N)

3 Description

The input data consists of n observations for each of m variables, given as an array
x ij ,   i=1,2,…,n n≥2 ,   j=1,2,…,m m≥2 ,
where x ij is the ith observation on the jth variable. In addition, each of the m variables may optionally have associated with it a value which is to be considered as representing a missing observation for that variable; the missing value for the jth variable is denoted by xmj. Missing values need not be specified for all variables.
Let wi=0 if observation i contains a missing value for any of those variables for which missing values have been declared, i.e., if x ij=xmj for any j for which an xmj has been assigned (see also Section 7); and wi=1 otherwise, for i=1,2,…,n.
The observations are first ranked as follows.
For a given variable, j say, each of the observations x ij for which wi=1, (i=1,2,…,n) has associated with it an additional number, the ‘rank’ of the observation, which indicates the magnitude of that observation relative to the magnitudes of the other observations on that same variable for which wi=1.
The smallest of these valid observations for variable j is assigned the rank 1, the second smallest observation for variable j the rank 2, the third smallest the rank 3, and so on until the largest such observation is given the rank nc, where nc=∑i=1 n wi.
If a number of cases all have the same value for the given variable, j, then they are each given an ‘average’ rank, e.g., if in attempting to assign the rank h+1, k observations for which wi=1 were found to have the same value, then instead of giving them the ranks
h+1, h+2, …, h+k ,
all k observations would be assigned the rank
2 h+k+1 2
and the next value in ascending order would be assigned the rank
h+k+ 1 .
The process is repeated for each of the m variables.
Let y ij be the rank assigned to the observation x ij when the jth variable is being ranked. For those observations, i, for which wi=0, y ij=0, for j=1,2,…,m.
The quantities calculated are:
(a) Kendall's tau rank correlation coefficients:
R jk = ∑ h=1 n ∑ i=1 n wh wi sign y hj-y ij sign y hk-y ik nc nc-1-Tjnc nc-1-Tk ,   j,k=1,2,…,m ,
where | nc=∑i=1 n wi
and | sign⁡u=1 if u>0
 | sign⁡u=0 if u=0
 | sign⁡u=-1 if u<0
and Tj=∑tj tj-1 where tj is the number of ties of a particular value of variable j, and the summation is over all tied values of variable j.
(b) Spearman's rank correlation coefficients:
R jk*=nc nc 2-1-6∑i=1 n wi y ij-y ik 2-12 Tj*+Tk* nc nc 2-1-Tj*nc nc 2-1-Tk* ,  j,k=1,2,…,m,
where nc=∑i=1 n wi and Tj*=∑tj tj 2-1 where tj is the number of ties of a particular value of variable j, and the summation is over all tied values of variable j.

4 References

Siegel S (1956) Non-parametric Statistics for the Behavioral Sciences McGraw–Hill

5 Arguments

1:   N – INTEGERInput
On entry: n, the number of observations or cases.
Constraint: N≥2.
2:   M – INTEGERInput
On entry: m, the number of variables.
Constraint: M≥2.
3:   X LDXM – REAL (KIND=nag_wp) arrayInput
On entry: X ij must be set to x ij, the value of the ith observation on the jth variable, where i=1,2,…,n and j=1,2,…,m.
4:   LDX – INTEGERInput
On entry: the first dimension of the array X as declared in the (sub)program from which G02BRF is called.
Constraint: LDX≥N.
5:   MISS M – INTEGER arrayInput/Output
On entry: MISS j must be set equal to 1 if a missing value, x mj, is to be specified for the jth variable in the array X, or set equal to 0 otherwise. Values of MISS must be given for all m variables in the array X.
On exit: the array MISS is overwritten by the routine, and the information it contained on entry is lost.
6:   XMISS M – REAL (KIND=nag_wp) arrayInput/Output
On entry: XMISS j must be set to the missing value, x mj, to be associated with the jth variable in the array X, for those variables for which missing values are specified by means of the array MISS (see Section 7).
On exit: the array XMISS is overwritten by the routine, and the information it contained on entry is lost.
7:   ITYPE – INTEGERInput
On entry: the type of correlation coefficients which are to be calculated.
ITYPE=-1
Only Kendall's tau coefficients are calculated.
ITYPE=0
Both Kendall's tau and Spearman's coefficients are calculated.
ITYPE=1
Only Spearman's coefficients are calculated.
Constraint: ITYPE=-1, 0 or 1.
8:   RR LDRRM – REAL (KIND=nag_wp) arrayOutput
On exit: the requested correlation coefficients.
If only Kendall's tau coefficients are requested (ITYPE=-1), RR jk contains Kendall's tau for the jth and kth variables.
If only Spearman's coefficients are requested (ITYPE=1), RR jk contains Spearman's rank correlation coefficient for the jth and kth variables.
If both Kendall's tau and Spearman's coefficients are requested (ITYPE=0), the upper triangle of RR contains the Spearman coefficients and the lower triangle the Kendall coefficients. That is, for the jth and kth variables, where j is less than k, RR jk contains the Spearman rank correlation coefficient, and RR kj contains Kendall's tau, for j=1,2,…,m and k=1,2,…,m.
(Diagonal terms, RR jj, are unity for all three values of ITYPE.)
9:   LDRR – INTEGERInput
On entry: the first dimension of the array RR as declared in the (sub)program from which G02BRF is called.
Constraint: LDRR≥M.
10:   NCASES – INTEGEROutput
On exit: the number of cases, nc, actually used in the calculations (when cases involving missing values have been eliminated).
11:   INCASE N – INTEGER arrayOutput
On exit: INCASE i holds the value 1 if the ith case was included in the calculations, and the value 0 if the ith case contained a missing value for at least one variable. That is, INCASE i=wi (see Section 3), for i=1,2,…,n.
12:   KWORKA N – INTEGER arrayWorkspace
13:   KWORKB N – INTEGER arrayWorkspace
14:   KWORKC N – INTEGER arrayWorkspace
15:   WORK1 N – REAL (KIND=nag_wp) arrayWorkspace
16:   WORK2 N – REAL (KIND=nag_wp) arrayWorkspace
17:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, N<2.
IFAIL=2
On entry, M<2.
IFAIL=3
On entry, | LDX<N,
or | LDRR<M.
IFAIL=4
On entry, | ITYPE<-1,
or | ITYPE>1.
IFAIL=5
After observations with missing values were omitted, fewer than 2 cases remained.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

You are warned of the need to exercise extreme care in your selection of missing values. G02BRF treats all values in the inclusive range 1±0.1 X02BEF-2×xm j, where xmj is the missing value for variable j specified in XMISS.
You must therefore ensure that the missing value chosen for each variable is sufficiently different from all valid values for that variable so that none of the valid values fall within the range indicated above.

8 Parallelism and Performance

G02BRF is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The time taken by G02BRF depends on n and m, and the occurrence of missing values.

10 Example

This example reads in a set of data consisting of nine observations on each of three variables. Missing values of 0.99 and 0.0 are declared for the first and third variables respectively; no missing value is specified for the second variable. The program then calculates and prints both Kendall's tau and Spearman's rank correlation coefficients for all three variables, omitting completely all cases containing missing values; cases 5, 8 and 9 are therefore eliminated, leaving only six cases in the calculations.

10.1 Program Text

Program Text (g02brfe.f90)

10.2 Program Data

Program Data (g02brfe.d)

10.3 Program Results

Program Results (g02brfe.r)

G02 Chapter Contents
G02 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


G02BSF : NAG Library, Mark 26

G02 Chapter Contents
G02 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

G02BSF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

G02BSF computes Kendall and/or Spearman nonparametric rank correlation coefficients for a set of data omitting cases with missing values from only those calculations involving the variables for which the values are missing; the data array is preserved, and the ranks of the observations are not available on exit from the routine.

2 Specification

SUBROUTINE G02BSF ( N, M, X, LDX, MISS, XMISS, ITYPE, RR, LDRR, NCASES, CNT, LDCNT, KWORKA, KWORKB, KWORKC, KWORKD, WORK1, WORK2, IFAIL)
INTEGER | N, M, LDX, MISS(M), ITYPE, LDRR, NCASES, LDCNT, KWORKA(N), KWORKB(N), KWORKC(N), KWORKD(N), IFAIL
REAL (KIND=nag_wp) | X(LDX,M), XMISS(M), RR(LDRR,M), CNT(LDCNT,M), WORK1(N), WORK2(N)

3 Description

The input data consists of n observations for each of m variables, given as an array
x ij ,   i=1,2,…,n n≥2 ​ and ​ j=1,2,…,m m≥2 ,
where x ij is the ith observation on the jth variable. In addition each of the m variables may optionally have associated with it a value which is to be considered as representing a missing observation for that variable; the missing value for the jth variable is denoted by xmj. Missing values need not be specified for all variables.
Let w ij=0 if the ith observation for the jth variable is a missing value, i.e., if a missing value, xmj, has been declared for the jth variable, and x ij=xmj (see also Section 7); and w ij=1 otherwise, for i=1,2,…,n and j=1,2,…,m.
The observations are first ranked, a pair of variables at a time as follows:
For a given pair of variables, j and l say, each of the observations x ij for which the product w ijw il=1, for i=1,2,…,n, has associated with it an additional number, the ‘rank’ of the observation, which indicates the magnitude of that observation relative to the magnitude of the other observations on variable j for which w ijw il=1.
The smallest of these valid observations for variable j is assigned to rank 1, the second smallest valid observation for variable j the rank 2, the third smallest rank 3, and so on until the largest such observation is given the rank n jl, where
n jl=∑i=1 n w ijw il.
If a number of cases all have the same value for the variable j, then they are each given an ‘average’ rank, e.g., if in attempting to assign the rank h+1, k observations for which w ijw il=1 were found to have the same value, then instead of giving them the ranks
h+1,h+2,…,h+k,
all k observations would be assigned the rank
2 h+k+1 2
and the next value in ascending order would be assigned the rank
h+k+ 1.
The variable l is then ranked in a similar way. The process is then repeated for all pairs of variables j and l, for j=1,2,…,m and l=j,…,m. Let y ij l be the rank assigned to the observation x ij when the jth and lth variables are being ranked, and y il j be the rank assigned to the observation x il during the same process, for i=1,2,…,n, j=1,2,…,m and l=j,…,m.
The quantities calculated are:
(a) Kendall's tau rank correlation coefficients:
R jk=∑h=1 n∑i=1 n w hjw hkw ijw ik sign y hj k-y ij ksign y hk j-y ik j n jk n jk-1-T j kn jk n jk-1-T k j ,  j,k=1,2,…,m,
where | n jk=∑i=1 n w ijw ik
and | sign⁡u=1 if u>0
 | sign⁡u=0 if u=0
 | sign⁡u=-1 if u<0
and T j k=∑tj tj-1 where tj is the number of ties of a particular value of variable j when the jth and kth variables are being ranked, and the summation is over all tied values of variable j.
(b) Spearman's rank correlation coefficients:
R jk*= n jk n jk 2-1-6∑i=1 n w ijw ik y ij k-y ik j 2-12 T j k*+T k j* n jk n jk 2-1-T j k* n jk n jk 2-1-T k j* ,   j,k=1,2,…,m,
where n jk=∑i=1 n w ijw ik
and T j k*=∑tj tj 2-1, where tj is the number of ties of a particular value of variable j when the jth and kth variables are being ranked, and the summation is over all tied values of variable j.

4 References

Siegel S (1956) Non-parametric Statistics for the Behavioral Sciences McGraw–Hill

5 Arguments

1:   N – INTEGERInput
On entry: n, the number of observations or cases.
Constraint: N≥2.
2:   M – INTEGERInput
On entry: m, the number of variables.
Constraint: M≥2.
3:   X LDXM – REAL (KIND=nag_wp) arrayInput
On entry: X ij must be set to x ij, the value of the ith observation on the jth variable, for i=1,2,…,n and j=1,2,…,m.
4:   LDX – INTEGERInput
On entry: the first dimension of the array X as declared in the (sub)program from which G02BSF is called.
Constraint: LDX≥N.
5:   MISS M – INTEGER arrayInput
On entry: MISS j must be set equal to 1 if a missing value, x mj, is to be specified for the jth variable in the array X, or set equal to 0 otherwise. Values of MISS must be given for all m variables in the array X.
6:   XMISS M – REAL (KIND=nag_wp) arrayInput
On entry: XMISS j must be set to the missing value, x mj, to be associated with the jth variable in the array X, for those variables for which missing values are specified by means of the array MISS (see Section 7).
7:   ITYPE – INTEGERInput
On entry: the type of correlation coefficients which are to be calculated.
ITYPE=-1
Only Kendall's tau coefficients are calculated.
ITYPE=0
Both Kendall's tau and Spearman's coefficients are calculated.
ITYPE=1
Only Spearman's coefficients are calculated.
Constraint: ITYPE=-1, 0 or 1.
8:   RR LDRRM – REAL (KIND=nag_wp) arrayOutput
On exit: the requested correlation coefficients.
If only Kendall's tau coefficients are requested (ITYPE=-1), RR jk contains Kendall's tau for the jth and kth variables.
If only Spearman's coefficients are requested (ITYPE=1), RR jk contains Spearman's rank correlation coefficient for the jth and kth variables.
If both Kendall's tau and Spearman's coefficients are requested (ITYPE=0), the upper triangle of RR contains the Spearman coefficients and the lower triangle the Kendall coefficients. That is, for the jth and kth variables, where j is less than k, RR jk contains the Spearman rank correlation coefficient, and RR kj contains Kendall's tau, for j=1,2,…,m and k=1,2,…,m.
(Diagonal terms, RR jj, are unity for all three values of ITYPE.)
9:   LDRR – INTEGERInput
On entry: the first dimension of the array RR as declared in the (sub)program from which G02BSF is called.
Constraint: LDRR≥M.
10:   NCASES – INTEGEROutput
On exit: the minimum number of cases used in the calculation of any of the correlation coefficients (when cases involving missing values have been eliminated).
11:   CNT LDCNTM – REAL (KIND=nag_wp) arrayOutput
On exit: the number of cases, n jk, actually used in the calculation of the rank correlation coefficient for the jth and kth variables, for j=1,2,…,m and k=1,2,…,m.
12:   LDCNT – INTEGERInput
On entry: the first dimension of the array CNT as declared in the (sub)program from which G02BSF is called.
Constraint: LDCNT≥M.
13:   KWORKA N – INTEGER arrayWorkspace
14:   KWORKB N – INTEGER arrayWorkspace
15:   KWORKC N – INTEGER arrayWorkspace
16:   KWORKD N – INTEGER arrayWorkspace
17:   WORK1 N – REAL (KIND=nag_wp) arrayWorkspace
18:   WORK2 N – REAL (KIND=nag_wp) arrayWorkspace
19:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, because for this routine the values of the output arguments may be useful even if IFAIL≠0 on exit, the recommended value is -1. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Note: G02BSF may return useful information for one or more of the following detected errors or warnings.
Errors or warnings detected by the routine:
IFAIL=1
On entry, N<2.
IFAIL=2
On entry, M<2.
IFAIL=3
On entry, | LDX<N,
or | LDRR<M,
or | LDCNT<M.
IFAIL=4
On entry, | ITYPE<-1,
or | ITYPE>1.
IFAIL=5
After observations with missing values were omitted, fewer than two cases remained for at least one pair of variables. (The pairs of variables involved can be determined by examination of the contents of the array CNT.) All correlation coefficients based on two or more cases are returned by the routine even if IFAIL=5.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

You are warned of the need to exercise extreme care in your selection of missing values. G02BSF treats all values in the inclusive range 1±0.1 X02BEF-2×xm j, where xmj is the missing value for variable j specified in XMISS.
You must therefore ensure that the missing value chosen for each variable is sufficiently different from all valid values for that variable so that none of the valid values fall within the range indicated above.

8 Parallelism and Performance

G02BSF is not threaded in any implementation.

9 Further Comments

The time taken by G02BSF depends on n and m, and the occurrence of missing values.

10 Example

This example reads in a set of data consisting of nine observations on each of three variables. Missing values of 0.99, 9.0 and 0.0 are declared for the first, second and third variables respectively. The program then calculates and prints both Kendall's tau and Spearman's rank correlation coefficients for all three variables, omitting cases with missing values from only those calculations involving the variables for which the values are missing. The program therefore eliminates cases 4, 5, 7 and 9 in calculating and correlation between the first and second variables, cases 5, 8 and 9 for the first and third variables, and cases 4, 7 and 8 for the second and third variables.

10.1 Program Text

Program Text (g02bsfe.f90)

10.2 Program Data

Program Data (g02bsfe.d)

10.3 Program Results

Program Results (g02bsfe.r)

G02 Chapter Contents
G02 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


G02BTF : NAG Library, Mark 26

G02 Chapter Contents
G02 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

G02BTF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

G02BTF updates the sample means and sums of squares and cross-products, or sums of squares and cross-products of deviations about the mean, for a new observation. The data may be weighted.

2 Specification

SUBROUTINE G02BTF ( MEAN, M, WT, X, INCX, SW, XBAR, C, IFAIL)
INTEGER | M, INCX, IFAIL
REAL (KIND=nag_wp) | WT, X(M*INCX), SW, XBAR(M), C((M*M+M)/2)
CHARACTER(1) | MEAN

3 Description

G02BTF is an adaptation of West's WV2 algorithm; see West (1979). This routine updates the weighted means of variables and weighted sums of squares and cross-products or weighted sums of squares and cross-products of deviations about the mean for observations on m variables Xj, for j=1,2,…,m. For the first i-1 observations let the mean of the jth variable be x-j i-1, the cross-product about the mean for the jth and kth variables be c jk i-1 and the sum of weights be W i-1. These are updated by the ith observation, x ij, for j=1,2,…,m, with weight wi as follows:
Wi=W i-1+wi,  x-j i=x-j i-1+wiWi xj-x-j i-1,  j=1,2,…,m
and
c jk i=c jk i- 1+wiWi xj-x-j i- 1xk-x-k i- 1 W i- 1,   j= 1,2,…,m;k=j,j+ 1,2,…,m.
The algorithm is initialized by taking x-j 1=x 1 j, the first observation and c ij 1=0.0.
For the unweighted case wi=1 and Wi=i for all i.

4 References

Chan T F, Golub G H and Leveque R J (1982) Updating Formulae and a Pairwise Algorithm for Computing Sample Variances Compstat, Physica-Verlag
West D H D (1979) Updating mean and variance estimates: An improved method Comm. ACM 22 532–555

5 Arguments

1:   MEAN – CHARACTER(1)Input
On entry: indicates whether G02BTF is to calculate sums of squares and cross-products, or sums of squares and cross-products of deviations about the mean.
MEAN='M'
The sums of squares and cross-products of deviations about the mean are calculated.
MEAN='Z'
The sums of squares and cross-products are calculated.
Constraint: MEAN='M' or 'Z'.
2:   M – INTEGERInput
On entry: m, the number of variables.
Constraint: M≥1.
3:   WT – REAL (KIND=nag_wp)Input
On entry: the weight to use for the current observation, wi.
For unweighted means and cross-products set WT=1.0. The use of a suitable negative value of WT, e.g., -wi will have the effect of deleting the observation.
4:   X M×INCX – REAL (KIND=nag_wp) arrayInput
On entry: X j-1×INCX+1 must contain the value of the jth variable for the current observation, j=1,2,…,m.
5:   INCX – INTEGERInput
On entry: the increment of X. Two situations are common.
If INCX=1, the data values are to be found in consecutive locations in X, i.e., in a column.
If INCX=ldx, for some positive integer ldx, the data values are to be found as a row of an array with first dimension ldx.
Constraint: INCX>0.
6:   SW – REAL (KIND=nag_wp)Input/Output
On entry: the sum of weights for the previous observations, W i-1.
SW=0.0
The update procedure is initialized.
SW+WT=0.0
All elements of XBAR and C are set to zero.
Constraint: SW≥0.0 and SW+WT≥0.0.
On exit: contains the updated sum of weights, Wi.
7:   XBAR M – REAL (KIND=nag_wp) arrayInput/Output
On entry: if SW=0.0, XBAR is initialized, otherwise XBAR j must contain the weighted mean of the jth variable for the previous i-1 observations, x-j i-1, for j=1,2,…,m.
On exit: XBAR j contains the weighted mean of the jth variable, x-j i, for j=1,2,…,m.
8:   C M×M+M/2 – REAL (KIND=nag_wp) arrayInput/Output
On entry: if SW≠0.0, C must contain the upper triangular part of the matrix of weighted sums of squares and cross-products or weighted sums of squares and cross-products of deviations about the mean. It is stored packed form by column, i.e., the cross-product between the jth and kth variable, k≥j, is stored in C k×k-1/2+j.
On exit: the update sums of squares and cross-products stored as on input.
9:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, | M<1,
or | INCX<1.
IFAIL=2
On entry, SW<0.0.
IFAIL=3
On entry, SW+WT<0.0, the current weight causes the sum of weights to be less than 0.0.
IFAIL=4
On entry, MEAN≠'M' or 'Z'.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

For a detailed discussion of the accuracy of this method see Chan et al. (1982) and West (1979).

8 Parallelism and Performance

G02BTF is not threaded in any implementation.

9 Further Comments

G02BTF may be used to update the results returned by G02BUF.
G02BWF may be used to calculate the correlation matrix from the matrix of sums of squares and cross-products of deviations about the mean and the matrix may be scaled using F06EDF (DSCAL) or F06FDF to produce a variance-covariance matrix.

10 Example

A program to calculate the means, the required sums of squares and cross-products matrix, and the variance matrix for a set of 3 observations of 3 variables.

10.1 Program Text

Program Text (g02btfe.f90)

10.2 Program Data

Program Data (g02btfe.d)

10.3 Program Results

Program Results (g02btfe.r)

G02 Chapter Contents
G02 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


G02BUF : NAG Library, Mark 26

G02 Chapter Contents
G02 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

G02BUF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

G02BUF calculates the sample means and sums of squares and cross-products, or sums of squares and cross-products of deviations from the mean, in a single pass for a set of data. The data may be weighted.

2 Specification

SUBROUTINE G02BUF ( MEAN, WEIGHT, N, M, X, LDX, WT, SW, WMEAN, C, IFAIL)
INTEGER | N, M, LDX, IFAIL
REAL (KIND=nag_wp) | X(LDX,M), WT(*), SW, WMEAN(M), C((M*M+M)/2)
CHARACTER(1) | MEAN, WEIGHT

3 Description

G02BUF is an adaptation of West's WV2 algorithm; see West (1979). This routine calculates the (optionally weighted) sample means and (optionally weighted) sums of squares and cross-products or sums of squares and cross-products of deviations from the (weighted) mean for a sample of n observations on m variables Xj, for j=1,2,…,m. The algorithm makes a single pass through the data.
For the first i-1 observations let the mean of the jth variable be x-j i-1, the cross-product about the mean for the jth and kth variables be c jk i-1 and the sum of weights be W i-1. These are updated by the ith observation, x ij, for j=1,2,…,m, with weight wi as follows:
Wi = W i-1 + wi x-j i = x-j i-1 + wiWi xj - x-j i-1 ,   j=1,2,…,m
and
c jk i = c jk i- 1 + wi Wi xj - x-j i- 1 xk - x-k i-1 W i-1 ,   j=1,2,…,m ​ and ​ k=j,j+ 1,…,m .
The algorithm is initialized by taking x-j 1=x 1 j, the first observation, and c ij 1=0.0.
For the unweighted case wi=1 and Wi=i for all i.
Note that only the upper triangle of the matrix is calculated and returned packed by column.

4 References

Chan T F, Golub G H and Leveque R J (1982) Updating Formulae and a Pairwise Algorithm for Computing Sample Variances Compstat, Physica-Verlag
West D H D (1979) Updating mean and variance estimates: An improved method Comm. ACM 22 532–555

5 Arguments

1:   MEAN – CHARACTER(1)Input
On entry: indicates whether G02BUF is to calculate sums of squares and cross-products, or sums of squares and cross-products of deviations about the mean.
MEAN='M'
The sums of squares and cross-products of deviations about the mean are calculated.
MEAN='Z'
The sums of squares and cross-products are calculated.
Constraint: MEAN='M' or 'Z'.
2:   WEIGHT – CHARACTER(1)Input
On entry: indicates whether the data is weighted or not.
WEIGHT='U'
The calculations are performed on unweighted data.
WEIGHT='W'
The calculations are performed on weighted data.
Constraint: WEIGHT='W' or 'U'.
3:   N – INTEGERInput
On entry: n, the number of observations in the dataset.
Constraint: N≥1.
4:   M – INTEGERInput
On entry: m, the number of variables.
Constraint: M≥1.
5:   X LDXM – REAL (KIND=nag_wp) arrayInput
On entry: X ij must contain the ith observation on the jth variable, for i=1,2,…,n and j=1,2,…,m.
6:   LDX – INTEGERInput
On entry: the first dimension of the array X as declared in the (sub)program from which G02BUF is called.
Constraint: LDX≥N.
7:   WT* – REAL (KIND=nag_wp) arrayInput
Note: the dimension of the array WT must be at least N if WEIGHT='W', and at least 1 otherwise.
On entry: the optional weights of each observation.
If WEIGHT='U', WT is not referenced.
If WEIGHT='W', WT i must contain the weight for the ith observation.
Constraint: if WEIGHT='W', WT i≥0.0, for i=1,2,…,n.
8:   SW – REAL (KIND=nag_wp)Output
On exit: the sum of weights.
If WEIGHT='U', SW contains the number of observations, n.
9:   WMEAN M – REAL (KIND=nag_wp) arrayOutput
On exit: the sample means. WMEAN j contains the mean for the jth variable.
10:   C M×M+M/2 – REAL (KIND=nag_wp) arrayOutput
On exit: the cross-products.
If MEAN='M', C contains the upper triangular part of the matrix of (weighted) sums of squares and cross-products of deviations about the mean.
If MEAN='Z', C contains the upper triangular part of the matrix of (weighted) sums of squares and cross-products.
These are stored packed by columns, i.e., the cross-product between the jth and kth variable, k≥j, is stored in C k×k-1/2+j.
11:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, | M<1,
or | N<1,
or | LDX<N.
IFAIL=2
On entry, MEAN≠'M' or 'Z'.
IFAIL=3
On entry, WEIGHT≠'W' or 'U'.
IFAIL=4
On entry, WEIGHT='W', and a value of WT<0.0.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

For a detailed discussion of the accuracy of this algorithm see Chan et al. (1982) or West (1979).

8 Parallelism and Performance

G02BUF is not threaded in any implementation.

9 Further Comments

G02BWF may be used to calculate the correlation coefficients from the cross-products of deviations about the mean. The cross-products of deviations about the mean may be scaled using F06EDF (DSCAL) or F06FDF to give a variance-covariance matrix.
The means and cross-products produced by G02BUF may be updated by adding or removing observations using G02BTF.
Two sets of means and cross-products, as produced by G02BUF, can be combined using G02BZF.

10 Example

A program to calculate the means, the required sums of squares and cross-products matrix, and the variance matrix for a set of 3 observations of 3 variables.

10.1 Program Text

Program Text (g02bufe.f90)

10.2 Program Data

Program Data (g02bufe.d)

10.3 Program Results

Program Results (g02bufe.r)

G02 Chapter Contents
G02 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


G02BWF : NAG Library, Mark 26

G02 Chapter Contents
G02 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

G02BWF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

G02BWF calculates a matrix of Pearson product-moment correlation coefficients from sums of squares and cross-products of deviations about the mean.

2 Specification

SUBROUTINE G02BWF ( M, R, IFAIL)
INTEGER | M, IFAIL
REAL (KIND=nag_wp) | R((M*M+M)/2)

3 Description

G02BWF calculates a matrix of Pearson product-moment correlation coefficients from sums of squares and cross-products about the mean for observations on m variables which can be computed by a single call to G02BUF or a series of calls to G02BTF. The sums of squares and cross-products are stored in an array packed by column and are overwritten by the correlation coefficients.
Let c jk be the cross-product of deviations from the mean, for j=1,2,…,m and k=j,…,m, then the product-moment correlation coefficient, r jk is given by
r jk=c jk c jjc kk .

4 References

None.

5 Arguments

1:   M – INTEGERInput
On entry: m, the number of variables.
Constraint: M≥1.
2:   R M×M+M/2 – REAL (KIND=nag_wp) arrayInput/Output
On entry: contains the upper triangular part of the sums of squares and cross-products matrix of deviations from the mean. These are stored packed by column, i.e., the cross-product between variable j and k, k≥j, is stored in R k×k-1/2+j.
On exit: the Pearson product-moment correlation coefficients.
These are stored packed by column corresponding to the input cross-products.
3:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, because for this routine the values of the output arguments may be useful even if IFAIL≠0 on exit, the recommended value is -1. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Note: G02BWF may return useful information for one or more of the following detected errors or warnings.
Errors or warnings detected by the routine:
IFAIL=1
On entry, M<1.
IFAIL=2
A variable has a zero variance. All correlations involving the variable with zero variance will be returned as zero.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

The accuracy of G02BWF is entirely dependent upon the accuracy of the elements of array R.

8 Parallelism and Performance

G02BWF is not threaded in any implementation.

9 Further Comments

G02BWF may also be used to calculate the correlations between parameter estimates from the variance-covariance matrix of the parameter estimates as is given by several routines in this chapter.

10 Example

A program to calculate the correlation matrix from raw data. The sum of squares and cross-products about the mean are calculated from the raw data by a call to G02BUF. The correlation matrix is then calculated from these values.

10.1 Program Text

Program Text (g02bwfe.f90)

10.2 Program Data

Program Data (g02bwfe.d)

10.3 Program Results

Program Results (g02bwfe.r)

G02 Chapter Contents
G02 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


G02BXF : NAG Library, Mark 26

G02 Chapter Contents
G02 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

G02BXF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

G02BXF calculates the sample means, the standard deviations, the variance-covariance matrix, and the matrix of Pearson product-moment correlation coefficients for a set of data. Weights may be used.

2 Specification

SUBROUTINE G02BXF ( WEIGHT, N, M, X, LDX, WT, XBAR, STD, V, LDV, R, IFAIL)
INTEGER | N, M, LDX, LDV, IFAIL
REAL (KIND=nag_wp) | X(LDX,M), WT(*), XBAR(M), STD(M), V(LDV,M), R(LDV,M)
CHARACTER(1) | WEIGHT

3 Description

For n observations on m variables the one-pass algorithm of West (1979) as implemented in G02BUF is used to compute the means, the standard deviations, the variance-covariance matrix, and the Pearson product-moment correlation matrix for p selected variables. Suitables weights may be used to indicate multiple observations and to remove missing values. The quantities are defined by:
(a) The means
x - j = ∑ i=1 n w i x ij ∑ i=1 n w i   j = 1 , … , p
(b) The variance-covariance matrix
C jk = ∑ i=1 n w i x ij - x - j x ik - x - k ∑ i=1 n w i - 1   j , k = 1 , … , p
(c) The standard deviations
s j = C jj   j = 1 , … , p
(d) The Pearson product-moment correlation coefficients
R jk = C jk C jj C kk   j , k = 1 , … , p
where x ij is the value of the i th observation on the j th variable and w i is the weight for the i th observation which will be 1 in the unweighted case.
Note that the denominator for the variance-covariance is ∑ i=1 n w i - 1 , so the weights should be scaled so that the sum of weights reflects the true sample size.

4 References

Chan T F, Golub G H and Leveque R J (1982) Updating Formulae and a Pairwise Algorithm for Computing Sample Variances Compstat, Physica-Verlag
West D H D (1979) Updating mean and variance estimates: An improved method Comm. ACM 22 532–555

5 Arguments

1:   WEIGHT – CHARACTER(1)Input
On entry: indicates whether weights are to be used.
WEIGHT='U'
Weights are not used and unit weights are assumed.
WEIGHT='W' or 'V'
Weights are used and must be supplied in WT. The only difference between WEIGHT='W' or WEIGHT='V' is in computing the variance. If WEIGHT='W' the divisor for the variance is the sum of the weights minus one and if WEIGHT='V' the divisor is the number of observations with nonzero weights minus one. The former is useful if the weights represent the frequency of the observed values.
Constraint: WEIGHT='U', 'V' or 'W'.
2:   N – INTEGERInput
On entry: the number of data observations in the sample.
Constraint: N>1.
3:   M – INTEGERInput
On entry: the number of variables.
Constraint: M≥1.
4:   X LDXM – REAL (KIND=nag_wp) arrayInput
On entry: X ij must contain the ith observation for the jth variable, for i=1,2,…,N and j=1,2,…,M.
5:   LDX – INTEGERInput
On entry: the first dimension of the array X as declared in the (sub)program from which G02BXF is called.
Constraint: LDX≥N.
6:   WT* – REAL (KIND=nag_wp) arrayInput
Note: the dimension of the array WT must be at least N if WEIGHT='W' or 'V', and at least 1 otherwise.
On entry: w, the optional frequency weighting for each observation, with WT i=wi. Usually wi will be an integral value corresponding to the number of observations associated with the i th data value, or zero if the i th data value is to be ignored. If WEIGHT='U', wi is set to 1 for all i and WT is not referenced.
Constraint: if WEIGHT='W' or 'V', ∑ i=1 N WT i>1.0, WT i≥0.0, for i=1,2,…,N.
7:   XBAR M – REAL (KIND=nag_wp) arrayOutput
On exit: the sample means. XBAR j contains the mean of the jth variable.
8:   STD M – REAL (KIND=nag_wp) arrayOutput
On exit: the standard deviations. STD j contains the standard deviation for the jth variable.
9:   V LDVM – REAL (KIND=nag_wp) arrayOutput
On exit: the variance-covariance matrix. V jk contains the covariance between variables j and k, for j=1,2,…,M and k=1,2,…,M.
10:   LDV – INTEGERInput
On entry: the first dimension of the arrays R and V as declared in the (sub)program from which G02BXF is called.
Constraint: LDV≥M.
11:   R LDVM – REAL (KIND=nag_wp) arrayOutput
On exit: the matrix of Pearson product-moment correlation coefficients. R jk contains the correlation coefficient between variables j and k.
12:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, because for this routine the values of the output arguments may be useful even if IFAIL≠0 on exit, the recommended value is -1. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Note: G02BXF may return useful information for one or more of the following detected errors or warnings.
Errors or warnings detected by the routine:
IFAIL=1
On entry, | M<1,
or | N≤1,
or | LDX<N,
or | LDV<M.
IFAIL=2
On entry, WEIGHT≠'U', 'V' or 'W'.
IFAIL=3
On entry, WEIGHT='W' or 'V' and a value of WT<0.0.
IFAIL=4
WEIGHT='W' and the sum of weights is not greater than 1.0, or WEIGHT='V' and fewer than 2 observations have nonzero weights.
IFAIL=5
A variable has a zero variance. In this case V and STD are returned as calculated but R will contain zero for any correlation involving a variable with zero variance.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

For a discussion of the accuracy of the one pass algorithm see Chan et al. (1982) and West (1979).

8 Parallelism and Performance

G02BXF makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

None.

10 Example

The data are some of the results from 1988 Olympic Decathlon. They are the times (in seconds) for the 100m and 400m races and the distances (in metres) for the long jump, high jump and shot. Twenty observations are input and the correlation matrix is computed and printed.

10.1 Program Text

Program Text (g02bxfe.f90)

10.2 Program Data

Program Data (g02bxfe.d)

10.3 Program Results

Program Results (g02bxfe.r)

G02 Chapter Contents
G02 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


G02BYF : NAG Library, Mark 26

G02 Chapter Contents
G02 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

G02BYF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

G02BYF computes a partial correlation/variance-covariance matrix from a correlation or variance-covariance matrix computed by G02BXF.

2 Specification

SUBROUTINE G02BYF ( M, NY, NX, ISZ, R, LDR, P, LDP, WK, IFAIL)
INTEGER | M, NY, NX, ISZ(M), LDR, LDP, IFAIL
REAL (KIND=nag_wp) | R(LDR,M), P(LDP,NY), WK(NY*NX+NX*(NX+1)/2)

3 Description

Partial correlation can be used to explore the association between pairs of random variables in the presence of other variables. For three variables, y 1, y 2 and x 3, the partial correlation coefficient between y 1 and y 2 given x 3 is computed as:
r 12-r 13r 23 1-r 1321-r 232 ,
where r ij is the product-moment correlation coefficient between variables with subscripts i and j. The partial correlation coefficient is a measure of the linear association between y 1 and y 2 having eliminated the effect due to both y 1 and y 2 being linearly associated with x 3. That is, it is a measure of association between y 1 and y 2 conditional upon fixed values of x 3. Like the full correlation coefficients the partial correlation coefficient takes a value in the range (-1,1) with the value 0 indicating no association.
In general, let a set of variables be partitioned into two groups Y and X with ny variables in Y and nx variables in X and let the variance-covariance matrix of all ny+nx variables be partitioned into,
Σ xx Σ xy Σ yx Σ yy .
The variance-covariance of Y conditional on fixed values of the X variables is given by:
Σ y∣x=Σ yy-Σ yx Σ xx -1 Σ xy.
The partial correlation matrix is then computed by standardizing Σ y∣x,
diag⁡Σ y∣x -12 Σ y∣x diag⁡Σ y∣x -12.
To test the hypothesis that a partial correlation is zero under the assumption that the data has an approximately Normal distribution a test similar to the test for the full correlation coefficient can be used. If r is the computed partial correlation coefficient then the appropriate t statistic is
r⁢n-nx-2 1-r 2 ,
which has approximately a Student's t-distribution with n-nx-2 degrees of freedom, where n is the number of observations from which the full correlation coefficients were computed.

4 References

Krzanowski W J (1990) Principles of Multivariate Analysis Oxford University Press
Morrison D F (1967) Multivariate Statistical Methods McGraw–Hill
Osborn J F (1979) Statistical Exercises in Medical Research Blackwell
Snedecor G W and Cochran W G (1967) Statistical Methods Iowa State University Press

5 Arguments

1:   M – INTEGERInput
On entry: the number of variables in the variance-covariance/correlation matrix given in R.
Constraint: M≥3.
2:   NY – INTEGERInput
On entry: the number of Y variables, ny, for which partial correlation coefficients are to be computed.
Constraint: NY≥2.
3:   NX – INTEGERInput
On entry: the number of X variables, nx, which are to be considered as fixed.
Constraints:
  • NX≥1;
  • NY+NX≤M.
4:   ISZ M – INTEGER arrayInput
On entry: indicates which variables belong to set X and Y.
ISZ i<0
The ith variable is a Y variable, for i=1,2,…,M.
ISZ i>0
The ith variable is a X variable.
ISZ i=0
The ith variable is not included in the computations.
Constraints:
  • exactly NY elements of ISZ must be <0;
  • exactly NX elements of ISZ must be >0.
5:   R LDRM – REAL (KIND=nag_wp) arrayInput
On entry: the variance-covariance or correlation matrix for the M variables as given by G02BXF. Only the upper triangle need be given.
Note: the matrix must be a full rank variance-covariance or correlation matrix and so be positive definite. This condition is not directly checked by the routine.
6:   LDR – INTEGERInput
On entry: the first dimension of the array R as declared in the (sub)program from which G02BYF is called.
Constraint: LDR≥M.
7:   P LDPNY – REAL (KIND=nag_wp) arrayOutput
On exit: the strict upper triangle of P contains the strict upper triangular part of the ny by ny partial correlation matrix. The lower triangle contains the lower triangle of the ny by ny partial variance-covariance matrix if the matrix given in R is a variance-covariance matrix. If the matrix given in R is a partial correlation matrix then the variance-covariance matrix is for standardized variables.
8:   LDP – INTEGERInput
On entry: the first dimension of the array P as declared in the (sub)program from which G02BYF is called.
Constraint: LDP≥NY.
9:   WK NY×NX+NX×NX+1/2 – REAL (KIND=nag_wp) arrayWorkspace
10:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, | M<3,
or | NY<2,
or | NX<1,
or | NY+NX>M,
or | LDR<M,
or | LDP<NY.
IFAIL=2
On entry, | there are not exactly NY elements of ISZ<0,
or | there are not exactly NX elements of ISZ>0.
IFAIL=3
On entry, the variance-covariance/correlation matrix of the X variables, Σ xx, is not of full rank. Try removing some of the X variables by setting the appropriate element of ISZ=0.
IFAIL=4
Either a diagonal element of the partial variance-covariance matrix, Σ y∣x, is zero and/or a computed partial correlation coefficient is greater than one. Both indicate that the matrix input in R was not positive definite.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

G02BYF computes the partial variance-covariance matrix, Σ y∣x, by computing the Cholesky factorization of Σ xx. If Σ xx is not of full rank the computation will fail. For a statement on the accuracy of the Cholesky factorization see F07GDF (DPPTRF).

8 Parallelism and Performance

G02BYF is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
G02BYF makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

Models that represent the linear associations given by partial correlations can be fitted using the multiple regression routine G02DAF.

10 Example

Data, given by Osborn (1979), on the number of deaths, smoke (mg/m 3) and sulphur dioxide (parts/million) during an intense period of fog is input. The correlations are computed using G02BXF and the partial correlation between deaths and smoke given sulphur dioxide is computed using G02BYF. Both correlation matrices are printed using the routine X04CAF.

10.1 Program Text

Program Text (g02byfe.f90)

10.2 Program Data

Program Data (g02byfe.d)

10.3 Program Results

Program Results (g02byfe.r)

G02 Chapter Contents
G02 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


G02BZF : NAG Library, Mark 26

G02 Chapter Contents
G02 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

G02BZF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

G02BZF combines two sets of sample means and sums of squares and cross-products matrices. It is designed to be used in conjunction with G02BUF to allow large datasets to be summarised.

2 Specification

SUBROUTINE G02BZF ( MEAN, M, XSW, XMEAN, XC, YSW, YMEAN, YC, IFAIL)
INTEGER | M, IFAIL
REAL (KIND=nag_wp) | XSW, XMEAN(M), XC((M*M+M)/2), YSW, YMEAN(M), YC((M*M+M)/2)
CHARACTER(1) | MEAN

3 Description

Let X and Y denote two sets of data, each with m variables and nx and ny observations respectively. Let μx denote the (optionally weighted) vector of m means for the first dataset and Cx denote either the sums of squares and cross-products of deviations from μx
Cx= X-e⁢ μxT T ⁢ Dx ⁢ X-e⁢ μxT
or the sums of squares and cross-products, in which case
Cx = XT ⁢ Dx ⁢X
where e is a vector of nx ones and Dx is a diagonal matrix of (optional) weights and Wx is defined as the sum of the diagonal elements of D. Similarly, let μy, Cy and Wy denote the same quantities for the second dataset.
Given μx, μy, Cx, Cy, Wx and Wy G02BZF calculates μz, Cz and Wz as if a dataset Z, with m variables and nx+ny observations were supplied to G02BUF, with Z constructed as
Z = X Y .
G02BZF has been designed to combine the results from two calls to G02BUF allowing large datasets, or cases where all the data is not available at the same time, to be summarised.

4 References

Bennett J, Pebay P, Roe D and Thompson D (2009) Numerically stable, single-pass, parallel statistics algorithms Proceedings of IEEE International Conference on Cluster Computing

5 Arguments

1:   MEAN – CHARACTER(1)Input
On entry: indicates whether the matrices supplied in XC and YC are sums of squares and cross-products, or sums of squares and cross-products of deviations about the mean.
MEAN='M'
Sums of squares and cross-products of deviations about the mean have been supplied.
MEAN='Z'
Sums of squares and cross-products have been supplied.
Constraint: MEAN='M' or 'Z'.
2:   M – INTEGERInput
On entry: m, the number of variables.
Constraint: M≥1.
3:   XSW – REAL (KIND=nag_wp)Input/Output
On entry: Wx, the sum of weights, from the first set of data, X. If the data is unweighted then this will be the number of observations in the first dataset.
On exit: Wz, the sum of weights, from the combined dataset, Z. If both datasets are unweighted then this will be the number of observations in the combined dataset.
Constraint: XSW≥0.
4:   XMEAN M – REAL (KIND=nag_wp) arrayInput/Output
On entry: μx, the sample means for the first set of data, X.
On exit: μz, the sample means for the combined data, Z.
5:   XC M×M+M/2 – REAL (KIND=nag_wp) arrayInput/Output
On entry: Cx, the sums of squares and cross-products matrix for the first set of data, X, as returned by G02BUF.
G02BUF, returns this matrix packed by columns, i.e., the cross-product between the jth and kth variable, k≥j, is stored in XC k×k-1/2+j.
No check is made that Cx is a valid cross-products matrix.
On exit: Cz, the sums of squares and cross-products matrix for the combined dataset, Z.
This matrix is again stored packed by columns.
6:   YSW – REAL (KIND=nag_wp)Input
On entry: Wy, the sum of weights, from the second set of data, Y. If the data is unweighted then this will be the number of observations in the second dataset.
Constraint: YSW≥0.
7:   YMEAN M – REAL (KIND=nag_wp) arrayInput
On entry: μy, the sample means for the second set of data, Y.
8:   YC M×M+M/2 – REAL (KIND=nag_wp) arrayInput
On entry: Cy, the sums of squares and cross-products matrix for the second set of data, Y, as returned by G02BUF.
G02BUF, returns this matrix packed by columns, i.e., the cross-product between the jth and kth variable, k≥j, is stored in YC k×k-1/2+j.
No check is made that Cy is a valid cross-products matrix.
9:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=11
On entry, MEAN=value was an illegal value.
IFAIL=21
On entry, M=value.
Constraint: M≥1.
IFAIL=31
On entry, XSW=value.
Constraint: XSW≥0.0.
IFAIL=61
On entry, YSW=value.
Constraint: YSW≥0.0.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

Not applicable.

8 Parallelism and Performance

G02BZF makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

None.

10 Example

This example illustrates the use of G02BZF by dividing a dataset into three blocks of 4, 5 and 3 observations respectively. Each block of data is summarised using G02BUF and then the three summaries combined using G02BZF.
The resulting sums of squares and cross-products matrix is then scaled to obtain the covariance matrix for the whole dataset.

10.1 Program Text

Program Text (g02bzfe.f90)

10.2 Program Data

Program Data (g02bzfe.d)

10.3 Program Results

Program Results (g02bzfe.r)

G02 Chapter Contents
G02 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


G02CAF : NAG Library, Mark 26

G02 Chapter Contents
G02 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

G02CAF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

G02CAF performs a simple linear regression with dependent variable y and independent variable x.

2 Specification

SUBROUTINE G02CAF ( N, X, Y, RESULT, IFAIL)
INTEGER | N, IFAIL
REAL (KIND=nag_wp) | X(N), Y(N), RESULT(20)

3 Description

G02CAF fits a straight line of the form
y=a+bx
to the data points
x 1,y 1,x 2,y 2,…,xn,yn,
such that
yi=a+b xi+ei,  i=1,2,…,n n>2.
The routine calculates the regression coefficient, b, the regression constant, a (and various other statistical quantities) by minimizing
∑i=1 n ei 2.
The input data consist of the n pairs of observations
x 1,y 1,x 2,y 2,…,xn,yn
on the independent variable x and the dependent variable y.
The quantities calculated are:
(a) Means:
x-=1 n∑i=1 n xi;  y-=1 n∑i=1 n yi.
(b) Standard deviations:
sx=1 n- 1 ∑i= 1 n xi-x- 2;   sy=1 n- 1 ∑i= 1 n yi-y- 2.
(c) Pearson product-moment correlation coefficient:
r=∑i=1 n xi-x-yi-y- ∑i=1 n xi-x- 2∑i=1 n yi-y- 2 .
(d) The regression coefficient, b, and the regression constant, a:
b=∑i=1 n xi-x-yi-y- ∑i=1 n xi-x- 2 ;a=y--b x-.
(e) The sum of squares attributable to the regression, SSR, the sum of squares of deviations about the regression, SSD, and the total sum of squares, SST:
SST=∑i=1 n yi-y- 2;SSD=∑i=1 n yi-a-b xi 2;SSR=SST-SSD.
(f) The degrees of freedom attributable to the regression, DFR, the degrees of freedom of deviations about the regression, DFD, and the total degrees of freedom, DFT:
DFT=n-1; ​DFD=n-2; ​DFR=1.
(g) The mean square attributable to the regression, MSR, and the mean square of deviations about the regression, MSD:
MSR=SSR/DFR;MSD=SSD/DFD.
(h) The F value for the analysis of variance:
F=MSR/MSD.
(i) The standard error of the regression coefficient, se b, and the standard error of the regression constant, se a:
se b=MSD∑i=1 n xi-x- 2 ;  se a=MSD 1 n+x-2 ∑i=1 n xi-x- 2 .
(j) The t value for the regression coefficient, t b, and the t value for the regression constant, t a:
t b=b se b ;  t a=a se a .

4 References

Draper N R and Smith H (1985) Applied Regression Analysis (2nd Edition) Wiley

5 Arguments

1:   N – INTEGERInput
On entry: n, the number of pairs of observations.
Constraint: N>2.
2:   X N – REAL (KIND=nag_wp) arrayInput
On entry: X i must contain xi, for i=1,2,…,n.
3:   Y N – REAL (KIND=nag_wp) arrayInput
On entry: Y i must contain yi, for i=1,2,…,n.
4:   RESULT 20 – REAL (KIND=nag_wp) arrayOutput
On exit: the following information:
RESULT 1 | x-, the mean value of the independent variable, x;
RESULT 2 | y-, the mean value of the dependent variable, y;
RESULT 3 | sx the standard deviation of the independent variable, x;
RESULT 4 | sy the standard deviation of the dependent variable, y;
RESULT 5 | r, the Pearson product-moment correlation between the independent variable x and the dependent variable y;
RESULT 6 | b, the regression coefficient;
RESULT 7 | a, the regression constant;
RESULT 8 | se b, the standard error of the regression coefficient;
RESULT 9 | se a, the standard error of the regression constant;
RESULT 10 | t b, the t value for the regression coefficient;
RESULT 11 | t a, the t value for the regression constant;
RESULT 12 | SSR, the sum of squares attributable to the regression;
RESULT 13 | DFR, the degrees of freedom attributable to the regression;
RESULT 14 | MSR, the mean square attributable to the regression;
RESULT 15 | F, the F value for the analysis of variance;
RESULT 16 | SSD, the sum of squares of deviations about the regression;
RESULT 17 | DFD, the degrees of freedom of deviations about the regression
RESULT 18 | MSD, the mean square of deviations about the regression;
RESULT 19 | SST, the total sum of squares;
RESULT 20 | DFT, the total degrees of freedom.
5:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, N≤2.
IFAIL=2
On entry, all N values of at least one of the variables x and y are identical.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

G02CAF does not use additional precision arithmetic for the accumulation of scalar products, so there may be a loss of significant figures for large n.
If, in calculating F, t a or t b (see Section 3), the numbers involved are such that the result would be outside the range of numbers which can be stored by the machine, then the answer is set to the largest quantity which can be stored as a real variable, by means of a call to X02ALF.

8 Parallelism and Performance

G02CAF is not threaded in any implementation.

9 Further Comments

The time taken by G02CAF depends on n.
The routine uses a two-pass algorithm.

10 Example

This example reads in eight observations on each of two variables, and then performs a simple linear regression with the first variable as the independent variable, and the second variable as the dependent variable. Finally the results are printed.

10.1 Program Text

Program Text (g02cafe.f90)

10.2 Program Data

Program Data (g02cafe.d)

10.3 Program Results

Program Results (g02cafe.r)

G02 Chapter Contents
G02 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


G02CBF : NAG Library, Mark 26

G02 Chapter Contents
G02 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

G02CBF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

G02CBF performs a simple linear regression with no constant, with dependent variable y and independent variable x.

2 Specification

SUBROUTINE G02CBF ( N, X, Y, RESULT, IFAIL)
INTEGER | N, IFAIL
REAL (KIND=nag_wp) | X(N), Y(N), RESULT(20)

3 Description

G02CBF fits a straight line of the form
y=bx
to the data points
x 1,y 1,x 2,y 2,…,xn,yn ,
such that
yi=b xi+ei,  i=1,2,…,n n≥2.
The routine calculates the regression coefficient, b, and the various other statistical quantities by minimizing
∑i=1 n ei 2.
The input data consists of the n pairs of observations x 1,y 1,x 2,y 2,…,xn,yn on the independent variable x and the dependent variable y.
The quantities calculated are:
(a) Means:
x-=1 n∑i=1 n xi;  y-=1 n∑i=1 n yi.
(b) Standard deviations:
sx=1 n- 1 ∑i= 1 n xi-x- 2;   sy=1 n- 1 ∑i= 1 n yi-y- 2.
(c) Pearson product-moment correlation coefficient:
r=∑i=1 n xi-x-yi-y- ∑i=1 n xi-x- 2∑i=1 n yi-y- 2 .
(d) The regression coefficient, b:
b=∑i=1 n xiyi ∑i=1 n xi 2 .
(e) The sum of squares attributable to the regression, SSR, the sum of squares of deviations about the regression, SSD, and the total sum of squares, SST:
SST=∑i=1 n yi 2;   SSD=∑i=1 n yi-b xi 2,   SSR=SST-SSD.
(f) The degrees of freedom attributable to the regression, DFR, the degrees of freedom of deviations about the regression, DFD, and the total degrees of freedom, DFT:
DFT=n;  DFD=n-1,  DFR=1.
(g) The mean square attributable to the regression, MSR, and the mean square of deviations about the regression, MSD.
MSR=SSR/DFR;  MSD=SSD/DFD.
(h) The F value for the analysis of variance:
F=MSR/MSD.
(i) The standard error of the regression coefficient:
se b=MSD ∑i= 1 n xi 2 .
(j) The t value for the regression coefficient:
t b=b se b .

4 References

Draper N R and Smith H (1985) Applied Regression Analysis (2nd Edition) Wiley

5 Arguments

1:   N – INTEGERInput
On entry: n, the number of pairs of observations.
Constraint: N>2.
2:   X N – REAL (KIND=nag_wp) arrayInput
On entry: X i must contain xi, for i=1,2,…,n.
3:   Y N – REAL (KIND=nag_wp) arrayInput
On entry: Y i must contain yi, for i=1,2,…,n.
4:   RESULT 20 – REAL (KIND=nag_wp) arrayOutput
On exit: the following information:
RESULT 1 | x-, the mean value of the independent variable, x;
RESULT 2 | y-, the mean value of the dependent variable, y;
RESULT 3 | sx, the standard deviation of the independent variable, x;
RESULT 4 | sy, the standard deviation of the dependent variable, y;
RESULT 5 | r, the Pearson product-moment correlation between the independent variable x and the dependent variable y;
RESULT 6 | b, the regression coefficient;
RESULT 7 | the value 0.0;
RESULT 8 | se b, the standard error of the regression coefficient;
RESULT 9 | the value 0.0;
RESULT 10 | t b, the t value for the regression coefficient;
RESULT 11 | the value 0.0;
RESULT 12 | SSR, the sum of squares attributable to the regression;
RESULT 13 | DFR, the degrees of freedom attributable to the regression;
RESULT 14 | MSR, the mean square attributable to the regression;
RESULT 15 | F, the F value for the analysis of variance;
RESULT 16 | SSD, the sum of squares of deviations about the regression;
RESULT 17 | DFD, the degrees of freedom of deviations about the regression;
RESULT 18 | MSD, the mean square of deviations about the regression;
RESULT 19 | SST, the total sum of squares;
RESULT 20 | DFT, the total degrees of freedom.
5:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, N<2.
IFAIL=2
On entry, all N values of at least one of the variables x and y are identical.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

G02CBF does not use additional precision arithmetic for the accumulation of scalar products, so there may be a loss of significant figures for large n.
If, in calculating F or t b (see Section 3), the numbers involved are such that the result would be outside the range of numbers which can be stored by the machine, then the answer is set to the largest quantity which can be stored as a real variable, by means of a call to X02ALF.

8 Parallelism and Performance

G02CBF is not threaded in any implementation.

9 Further Comments

Computation time depends on n.
G02CBF uses a two-pass algorithm.

10 Example

This example reads in eight observations on each of two variables, and then performs a simple linear regression with no constant with the first variable as the independent variable, and the second variable as the dependent variable. Finally the results are printed.

10.1 Program Text

Program Text (g02cbfe.f90)

10.2 Program Data

Program Data (g02cbfe.d)

10.3 Program Results

Program Results (g02cbfe.r)

G02 Chapter Contents
G02 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


G02CCF : NAG Library, Mark 26

G02 Chapter Contents
G02 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

G02CCF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

G02CCF performs a simple linear regression with dependent variable y and independent variable x, omitting cases involving missing values.

2 Specification

SUBROUTINE G02CCF ( N, X, Y, XMISS, YMISS, RESULT, IFAIL)
INTEGER | N, IFAIL
REAL (KIND=nag_wp) | X(N), Y(N), XMISS, YMISS, RESULT(21)

3 Description

G02CCF fits a straight line of the form
y=a+bx
to those of the data points
x 1,y 1,x 2,y 2,…,xn,yn
that do not include missing values, such that
yi=a+b xi+ei
for those xi,yi, i=1,2,…,n n>2 which do not include missing values.
The routine eliminates all pairs of observations xi,yi which contain a missing value for either x or y, and then calculates the regression coefficient, b, the regression constant, a, and various other statistical quantities, by minimizing the sum of the ei 2 over those cases remaining in the calculations.
The input data consists of the n pairs of observations x 1,y 1,x 2,y 2,…,xn,yn on the independent variable x and the dependent variable y.
In addition two values, xm and ym, are given which are considered to represent missing observations for x and y respectively. (See Section 7).
Let wi=0 if the ith observation of either x or y is missing, i.e., if xi=xm and/or yi=ym; and wi=1 otherwise, for i=1,2,…,n.
The quantities calculated are:
(a) Means:
x-=∑i=1 n wixi ∑i=1 n wi ;  y-=∑i=1 n wiyi ∑i=1 n wi .
(b) Standard deviations:
sx= ∑i= 1 n wi xi-x- 2 ∑i= 1 n wi- 1 ;   sy= ∑i= 1 n wi yi-y- 2 ∑i= 1 n wi- 1 .
(c) Pearson product-moment correlation coefficient:
r=∑i=1 n wi xi-x-yi-y- ∑i=1 n wi xi-x- 2∑i=1 n wi yi-y- 2 .
(d) The regression coefficient, b, and the regression constant, a:
b=∑i=1 n wi xi-x-yi-y- ∑i=1 n wi xi-x- 2 ,  a=y--b x-.
(e) The sum of squares attributable to the regression, SSR, the sum of squares of deviations about the regression, SSD, and the total sum of squares, SST:
SST=∑i=1 n wi yi-y- 2;  SSD=∑i=1 n wi yi-a-b xi 2;  SSR=SST-SSD.
(f) The degrees of freedom attributable to the regression, DFR, the degrees of freedom of deviations about the regression, DFD, and the total degrees of freedom, DFT:
DFT=∑i=1 n wi-1;  DFD=∑i=1 n wi-2;  DFR=1.
(g) The mean square attributable to the regression, MSR, and the mean square of deviations about the regression, MSD:
MSR=SSR/DFR;  MSD=SSD/DFD.
(h) The F value for the analysis of variance:
F=MSR/MSD.
(i) The standard error of the regression coefficient, se b, and the standard error of the regression constant, se a:
se b=MSD ∑i=1 n wi xi-x- 2 ;  se a=MSD 1∑i=1 n wi +x-2 ∑i=1 n wi xi-x- 2 .
(j) The t value for the regression coefficient, t b, and the t value for the regression constant, t a:
t b=b se b ;  t a=a se a .
(k) The number of observations used in the calculations:
nc=∑i= 1 n wi.

4 References

Draper N R and Smith H (1985) Applied Regression Analysis (2nd Edition) Wiley

5 Arguments

1:   N – INTEGERInput
On entry: n, the number of pairs of observations.
Constraint: N>2.
2:   X N – REAL (KIND=nag_wp) arrayInput
On entry: X i must contain xi, for i=1,2,…,n.
3:   Y N – REAL (KIND=nag_wp) arrayInput
On entry: Y i must contain yi, for i=1,2,…,n.
4:   XMISS – REAL (KIND=nag_wp)Input
On entry: the value xm which is to be taken as the missing value for the variable x. See Section 7.
5:   YMISS – REAL (KIND=nag_wp)Input
On entry: the value ym which is to be taken as the missing value for the variable y. See Section 7.
6:   RESULT 21 – REAL (KIND=nag_wp) arrayOutput
On exit: the following information:
RESULT 1 | x-, the mean value of the independent variable, x;
RESULT 2 | y-, the mean value of the dependent variable, y;
RESULT 3 | sx, the standard deviation of the independent variable, x;
RESULT 4 | sy, the standard deviation of the dependent variable, y;
RESULT 5 | r, the Pearson product-moment correlation between the independent variable x and the dependent variable y
RESULT 6 | b, the regression coefficient;
RESULT 7 | a, the regression constant;
RESULT 8 | se b, the standard error of the regression coefficient;
RESULT 9 | se a, the standard error of the regression constant;
RESULT 10 | t b, the t value for the regression coefficient;
RESULT 11 | t a, the t value for the regression constant;
RESULT 12 | SSR, the sum of squares attributable to the regression;
RESULT 13 | DFR, the degrees of freedom attributable to the regression;
RESULT 14 | MSR, the mean square attributable to the regression;
RESULT 15 | F, the F value for the analysis of variance;
RESULT 16 | SSD, the sum of squares of deviations about the regression;
RESULT 17 | DFD, the degrees of freedom of deviations about the regression;
RESULT 18 | MSD, the mean square of deviations about the regression;
RESULT 19 | SST, the total sum of squares;
RESULT 20 | DFT, the total degrees of freedom;
RESULT 21 | nc, the number of observations used in the calculations.
7:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, N≤2.
IFAIL=2
After observations with missing values were omitted, two or fewer cases remained.
IFAIL=3
After observations with missing values were omitted, all remaining values of at least one of the variables x and y were identical.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

G02CCF does not use additional precision arithmetic for the accumulation of scalar products, so there may be a loss of significant figures for large n.
You are warned of the need to exercise extreme care in your selection of missing values. G02CCF treats all values in the inclusive range 1±0.1 X02BEF-2×xm j, where xmj is the missing value for variable j specified in XMISS.
You must therefore ensure that the missing value chosen for each variable is sufficiently different from all valid values for that variable so that none of the valid values fall within the range indicated above.
If, in calculating F or t a (see Section 3), the numbers involved are such that the result would be outside the range of numbers which can be stored by the machine, then the answer is set to the largest quantity which can be stored as a real variable, by means of a call to X02ALF.

8 Parallelism and Performance

G02CCF is not threaded in any implementation.

9 Further Comments

The time taken by G02CCF depends on n and the number of missing observations.
The routine uses a two-pass algorithm.

10 Example

This example reads in eight observations on each of two variables, and then performs a simple linear regression with the first variable as the independent variable, and the second variable as the dependent variable, omitting cases involving missing values (0.0 for the first variable, 99.0 for the second). Finally the results are printed.

10.1 Program Text

Program Text (g02ccfe.f90)

10.2 Program Data

Program Data (g02ccfe.d)

10.3 Program Results

Program Results (g02ccfe.r)

G02 Chapter Contents
G02 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


G02CDF : NAG Library, Mark 26

G02 Chapter Contents
G02 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

G02CDF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

G02CDF performs a simple linear regression with no constant, with dependent variable y and independent variable x, omitting cases involving missing values.

2 Specification

SUBROUTINE G02CDF ( N, X, Y, XMISS, YMISS, RESULT, IFAIL)
INTEGER | N, IFAIL
REAL (KIND=nag_wp) | X(N), Y(N), XMISS, YMISS, RESULT(21)

3 Description

G02CDF fits a straight line of the form
y=bx
to those of the data points
x 1,y 1,x 2,y 2,…,xn,yn
that do not include missing values, such that
yi=b xi+ei
for those xi,yi, for i=1,2,…,n n≥2 which do not include missing values.
The routine eliminates all pairs of observations xi,yi which contain a missing value for either x or y, and then calculates the regression coefficient, b, and various other statistical quantities by minimizing the sum of the ei 2 over those cases remaining in the calculations.
The input data consists of the n pairs of observations x 1,y 1,x 2,y 2,…,xn,yn on the independent variable x and the dependent variable y.
In addition two values, xm and ym, are given which are considered to represent missing observations for x and y respectively. (See Section 7).
Let wi=0, if the ith observation of either x or y is missing, i.e., if xi=xm and/or yi=ym; and wi=1 otherwise, for i=1,2,…,n.
The quantities calculated are:
(a) Means:
x-=∑i=1 n wixi ∑i=1 n wi ;  y-=∑i=1 n wiyi ∑i=1 n wi .
(b) Standard deviations:
sx=∑i= 1 n wi xi-x- 2 ∑i= 1 n wi- 1 ;   sy=∑i= 1 n wi yi-y- 2 ∑i= 1 n wi- 1 .
(c) Pearson product-moment correlation coefficient:
r=∑i=1 n wi xi-x-yi-y- ∑i=1 n wi xi-x- 2∑i=1 n wi yi-y- 2 .
(d) The regression coefficient, b:
b=∑i=1 n wixiyi ∑i=1 n wi xi 2 .
(e) The sum of squares attributable to the regression, SSR, the sum of squares of deviations about the regression, SSD, and the total sum of squares, SST:
SST=∑i=1 n wi yi 2;  SSD=∑i=1 n wi yi-b xi 2;  SSR=SST-SSD.
(f) The degrees of freedom attributable to the regression, DFR, the degrees of freedom of deviations about the regression, DFD, and the total degrees of freedom, DFT:
DFT=∑i=1 n wi;  DFD=∑i=1 n wi-1;  DFR=1.
(g) The mean square attributable to the regression, MSR, and the mean square of deviations about the regression, MSD:
MSR=SSR/DFR;  MSD=SSD/DFD.
(h) The F value for the analysis of variance:
F=MSR/MSD.
(i) The standard error of the regression coefficient:
se b=MSD ∑i= 1 n wi xi 2 .
(j) The t value for the regression coefficient:
t b=b se b .
(k) The number of observations used in the calculations:
nc=∑i= 1 n wi.

4 References

Draper N R and Smith H (1985) Applied Regression Analysis (2nd Edition) Wiley

5 Arguments

1:   N – INTEGERInput
On entry: n, the number of pairs of observations.
Constraint: N≥2.
2:   X N – REAL (KIND=nag_wp) arrayInput
On entry: X i must contain xi, for i=1,2,…,n.
3:   Y N – REAL (KIND=nag_wp) arrayInput
On entry: Y i must contain yi, for i=1,2,…,n.
4:   XMISS – REAL (KIND=nag_wp)Input
On entry: the value xm, which is to be taken as the missing value for the variable x (see Section 7).
5:   YMISS – REAL (KIND=nag_wp)Input
On entry: the value ym, which is to be taken as the missing value for the variable y (see Section 7).
6:   RESULT 21 – REAL (KIND=nag_wp) arrayOutput
On exit: the following information:
RESULT 1 | x-, the mean value of the independent variable, x;
RESULT 2 | y-, the mean value of the dependent variable, y;
RESULT 3 | sx, the standard deviation of the independent variable, x;
RESULT 4 | sy, the standard deviation of the dependent variable, y;
RESULT 5 | r, the Pearson product-moment correlation between the independent variable x and the dependent variable, y;
RESULT 6 | b, the regression coefficient;
RESULT 7 | the value 0.0;
RESULT 8 | se b, the standard error of the regression coefficient;
RESULT 9 | the value 0.0;
RESULT 10 | t b, the t value for the regression coefficient;
RESULT 11 | the value 0.0;
RESULT 12 | SSR, the sum of squares attributable to the regression;
RESULT 13 | DFR, the degrees of freedom attributable to the regression;
RESULT 14 | MSR, the mean square attributable to the regression;
RESULT 15 | F, the F value for the analysis of variance;
RESULT 16 | SSD, the sum of squares of deviations about the regression;
RESULT 17 | DFD, the degrees of freedom of deviations about the regression;
RESULT 18 | MSD, the mean square of deviations about the regression;
RESULT 19 | SST, the total sum of squares
RESULT 20 | DFT, the total degrees of freedom;
RESULT 21 | nc, the number of observations used in the calculations.
7:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, N<2.
IFAIL=2
After observations with missing values were omitted, fewer than two cases remained.
IFAIL=3
After observations with missing values were omitted, all remaining values of at least one of the variables x and y were identical.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

G02CDF does not use additional precision arithmetic for the accumulation of scalar products, so there may be a loss of significant figures for large n.
You are warned of the need to exercise extreme care in your selection of missing values. G02CDF treats all values in the inclusive range 1±0.1 X02BEF-2×xm j, where xmj is the missing value for variable j specified in XMISS.
You must therefore ensure that the missing value chosen for each variable is sufficiently different from all valid values for that variable so that none of the valid values fall within the range indicated above.
If, in calculating F or t b (see Section 3), the numbers involved are such that the result would be outside the range of numbers which can be stored by the machine, then the answer is set to the largest quantity which can be stored as a real variable, by means of a call to X02ALF.

8 Parallelism and Performance

G02CDF is not threaded in any implementation.

9 Further Comments

The time taken by G02CDF depends on n and the number of missing observations.
The routine uses a two-pass algorithm.

10 Example

This example reads in eight observations on each of two variables, and then performs a simple linear regression with no constant, with the first variable as the independent variable, and the second variable as the dependent variable, omitting cases involving missing values (0.0 for the first variable, 99.0 for the second). Finally the results are printed.

10.1 Program Text

Program Text (g02cdfe.f90)

10.2 Program Data

Program Data (g02cdfe.d)

10.3 Program Results

Program Results (g02cdfe.r)

G02 Chapter Contents
G02 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


G02CEF : NAG Library, Mark 26

G02 Chapter Contents
G02 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

G02CEF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

G02CEF takes selected elements from two vectors (typically vectors of means and standard deviations) to form two smaller vectors, and selected rows and columns from two matrices (typically either matrices of sums of squares and cross-products of deviations from means and Pearson product-moment correlation coefficients, or matrices of sums of squares and cross-products about zero and correlation-like coefficients) to form two smaller matrices, allowing reordering of elements in the process.

2 Specification

SUBROUTINE G02CEF ( N, XBAR, STD, SSP, LDSSP, R, LDR, M, KORDER, XBAR2, STD2, SSP2, LDSSP2, R2, LDR2, IFAIL)
INTEGER | N, LDSSP, LDR, M, KORDER(M), LDSSP2, LDR2, IFAIL
REAL (KIND=nag_wp) | XBAR(N), STD(N), SSP(LDSSP,N), R(LDR,N), XBAR2(M), STD2(M), SSP2(LDSSP2,M), R2(LDR2,M)

3 Description

Input to the routine consists of:
(a) A vector of means:
x-1,x-2,x-3,…,x-n,
where n is the number of input variables.
(b) A vector of standard deviations:
s 1,s 2,s 3,…,sn.
(c) A matrix of sums of squares and cross-products of deviations from means:
S 11 S 12 S 13 . . . S 1 n S 21 S 22 S 2 n S 31 . . . . . . . S n 1 S n 2 . . . . S nn .
(d) A matrix of correlation coefficients:
R 11 R 12 R 13 . . . R 1 n R 21 R 22 R 2 n R 31 . . . . . . . R n 1 R n 2 . . . . R nn .
(e) The number of variables, m, in the required subset, and their row/column numbers in the input data, i 1,i 2,i 3,…,im,
i≤ik≤n  for k=1,2,…,m n≥2,m≥1 and m≤n.
New vectors and matrices are output containing the following information:
(i) A vector of means:
x-i 1,x-i 2,x-i 3,…,x-im.
(ii) A vector of standard deviations:
s i 1,s i 2,s i 3,…,s im.
(iii) A matrix of sums of squares and cross-products of deviations from means:
S i 1i 1 S i 1i 2 S i 1i 3 . . . S i 1im S i 2i 1 S i 2i 2 . S i 3i 1 . . . . . . . S imi 1 S imi 2 . . . . S imim .
(iv) A matrix of correlation coefficients:
R i 1i 1 R i 1i 2 R i 1i 3 . . . R i 1im R i 2i 1 R i 2i 2 . R i 3i 1 . . . . . . . R imi 1 R imi 2 . . . . R imim .
Note: for sums of squares of cross-products of deviations about zero and correlation-like coefficients S ij and R ij should be replaced by S~ij and R~ij in the description of the input and output above.

4 References

None.

5 Arguments

1:   N – INTEGERInput
On entry: n, the number of variables in the input data.
Constraint: N≥2.
2:   XBAR N – REAL (KIND=nag_wp) arrayInput
On entry: XBAR i must be set to x-i, the mean of variable i, for i=1,2,…,n.
3:   STD N – REAL (KIND=nag_wp) arrayInput
On entry: STD i must be set to si, the standard deviation of variable i, for i=1,2,…,n.
4:   SSP LDSSPN – REAL (KIND=nag_wp) arrayInput
On entry: SSP ij must be set to the sum of cross-products of deviations from means S ij (or about zero, S~ij) for variables i and j, for i=1,2,…,n and j=1,2,…,n.
5:   LDSSP – INTEGERInput
On entry: the first dimension of the array SSP as declared in the (sub)program from which G02CEF is called.
Constraint: LDSSP≥N.
6:   R LDRN – REAL (KIND=nag_wp) arrayInput
On entry: R ij must be set to the Pearson product-moment correlation coefficient R ij (or the correlation-like coefficient, R~ij) for variables i and j, for i=1,2,…,n and j=1,2,…,n.
7:   LDR – INTEGERInput
On entry: the first dimension of the array R as declared in the (sub)program from which G02CEF is called.
Constraint: LDR≥N.
8:   M – INTEGERInput
On entry: the number of variables m, required in the reduced vectors and matrices.
Constraint: 1≤M≤N.
9:   KORDER M – INTEGER arrayInput
On entry: KORDER i must be set to the number of the original variable which is to be the ith variable in the output vectors and matrices, for i=1,2,…,m.
Constraint: 1≤KORDER i≤N, for i=1,2,…,m.
10:   XBAR2 M – REAL (KIND=nag_wp) arrayOutput
On exit: the mean of variable i, XBAR i, where i=KORDER k, for k=1,2,…,m. (The array XBAR2 must differ from XBAR and STD.)
11:   STD2 M – REAL (KIND=nag_wp) arrayOutput
On exit: the standard deviation of variable i, STD i, where i=KORDER k, for k=1,2,…,m. (The array STD2 must differ from both XBAR and STD.)
12:   SSP2 LDSSP2M – REAL (KIND=nag_wp) arrayOutput
On exit: SSP2 kl contains the value of SSP ij, where i=KORDER k and j=KORDER l, for k=1,2,…,m and l=1,2,…,m. (The array SSP2 must differ from both SSP and R.)
That is to say: on exit, SSP2 kl contains the sum of cross-products of deviations from means S ij (or about zero, S~ij).
13:   LDSSP2 – INTEGERInput
On entry: the first dimension of the array SSP2 as declared in the (sub)program from which G02CEF is called.
Constraint: LDSSP2≥M.
14:   R2 LDR2M – REAL (KIND=nag_wp) arrayOutput
On exit: R2 kl contains the value of R ij, where i=KORDER k and j=KORDER l, for k=1,2,…,m and l=1,2,…,m. (The array R2 must differ from both SSP and R.)
That is to say: on exit, R2 kl contains the Pearson product-moment coefficient R ij (or the correlation-like coefficient, R~ij).
15:   LDR2 – INTEGERInput
On entry: the first dimension of the array R2 as declared in the (sub)program from which G02CEF is called.
Constraint: LDR2≥M.
16:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, | N<2,
or | M<1.
IFAIL=2
On entry, N<M.
IFAIL=3
On entry, | LDSSP<N,
or | LDR<N,
or | LDSSP<M,
or | LDR2<M.
IFAIL=4
On entry, | KORDER i<1,
or | KORDER i>N for some i=1,2,…,m.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

Not applicable.

8 Parallelism and Performance

G02CEF is not threaded in any implementation.

9 Further Comments

The time taken by G02CEF depends on n and m.
The routine is intended primarily for use when a subset of variables from a larger set of variables is to be used in a regression, and is described accordingly. There is however no reason why the routine should not also be used to select specific rows and columns from vectors and arrays which contain any other non-statistical information; the matrices need not be symmetric.
The routine may be used either with sums of squares and cross-products of deviations from means and Pearson product-moment correlation coefficients in connection with a regression involving a constant, or with sums of squares and cross-products about zero and correlation-like coefficients in connection with a regression with no constant.

10 Example

This example reads in the means, standard deviations, sums of squares and cross-products, and correlation coefficients for four variables. New vectors and matrices are created containing the means, standard deviations, sums of squares and cross-products, and correlation coefficients for the fourth, first and second variables (in that order). Finally these new vectors and matrices are printed.

10.1 Program Text

Program Text (g02cefe.f90)

10.2 Program Data

Program Data (g02cefe.d)

10.3 Program Results

Program Results (g02cefe.r)

G02 Chapter Contents
G02 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


G02CFF : NAG Library, Mark 26

G02 Chapter Contents
G02 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

G02CFF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

G02CFF reorders the elements in two vectors (typically vectors of means and standard deviations), and the rows and columns in two matrices (typically either matrices of sums of squares and cross-products of deviations from means and Pearson product-moment correlation coefficients, or matrices of sums of squares and cross-products about zero and correlation-like coefficients).

2 Specification

SUBROUTINE G02CFF ( N, KORDER, XBAR, STD, SSP, LDSSP, R, LDR, KWORK, IFAIL)
INTEGER | N, KORDER(N), LDSSP, LDR, KWORK(N), IFAIL
REAL (KIND=nag_wp) | XBAR(N), STD(N), SSP(LDSSP,N), R(LDR,N)

3 Description

Input to the routine consists of:
(a) A list of the order in which the n variables are to be arranged on exit:
i 1,i 2,i 3,…,in.
(b) A vector of means:
x-1,x-2,x-3,…,x-n .
(c) A vector of standard deviations:
s 1,s 2,s 3,…,sn.
(d) A matrix of sums of squares and cross-products of deviations from means:
S 11 S 12 S 13 . . . S 1 n S 21 S 22 . S 31 . . . . . . . S n 1 S n 2 . . . . S nn .
(e) A matrix of correlation coefficients:
R 11 R 12 R 13 . . . R 1 n R 21 R 22 . R 31 . . . . . . . R n 1 R n 2 . . . . R nn .
On exit from the routine, these same vectors and matrices are reordered, in the manner specified, and contain the following information:
(i) The vector of means:
x-i 1,x-i 2,x-i 3,…,x-in .
(ii) The vector of standard deviations:
s i 1,s i 2,s i 3,…s in.
(iii) The matrix of sums of squares and cross-products of deviations from means:
S i 1i 1 S i 1i 2 S i 1i 3 . . . S i 1in S i 2i 1 S i 2i 2 . S i 3i 1 . . . . . . . S ini 1 S ini 2 . . . . S inin .
(iv) The matrix of correlation coefficients:
R i 1i 1 R i 1i 2 R i 1i 3 . . . R i 1in R i 2i 1 R i 2i 2 . R i 3i 1 . . . . . . . R ini 1 R ini 2 . . . . R inin .
Note: for sums of squares of cross-products of deviations about zero and correlation-like coefficients S ij and R ij should be replaced by S~ij and R~ij in the description of the input and output above.

4 References

None.

5 Arguments

1:   N – INTEGERInput
On entry: n, the number of variables in the input data.
Constraint: N≥2.
2:   KORDER N – INTEGER arrayInput
On entry: KORDER i must be set to the number of the original variable which is to be the ith variable in the re-arranged data, for i=1,2,…,n.
Constraint: 1≤KORDER i≤N, for i=1,2,…,n.
3:   XBAR N – REAL (KIND=nag_wp) arrayInput/Output
On entry: XBAR i must be set to the mean of variable i, for i=1,2,…,n.
On exit: XBAR i contains the mean of variable k where k=KORDER i, for i=1,2,…,n.
4:   STD N – REAL (KIND=nag_wp) arrayInput/Output
On entry: STD i must be set to the standard deviation of variable i, for i=1,2,…,n.
On exit: STD i contains the standard deviation of variable k where k=KORDER i, for i=1,2,…,n.
5:   SSP LDSSPN – REAL (KIND=nag_wp) arrayInput/Output
On entry: SSP ij must be set to the sum of cross-products of deviations from means S ij (or about zero S~ij) for variables i and j, for i=1,2,…,n and j=1,2,…,n.
On exit: SSP ij contains the sum of cross-products of deviations from means S kl (or about zero S~kl) for variables k and l, where k=KORDER i, and l=KORDER j, i,j=1,2,…,n.
6:   LDSSP – INTEGERInput
On entry: the first dimension of the array SSP as declared in the (sub)program from which G02CFF is called.
Constraint: LDSSP≥N.
7:   R LDRN – REAL (KIND=nag_wp) arrayInput/Output
On entry: R ij must be set to the Pearson product-moment correlation coefficient R ij (or the correlation-like coefficient R~ij) for variables i and j, for i=1,2,…,n and j=1,2,…,n.
On exit: R ij contains the Pearson product-moment correlation coefficient R kl (or the correlation-like coefficient R~kl) for variables k and l, where k=KORDER i and l=KORDER j, for i=1,2,…,n and j=1,2,…,n.
8:   LDR – INTEGERInput
On entry: the first dimension of the array R as declared in the (sub)program from which G02CFF is called.
Constraint: LDR≥N.
9:   KWORK N – INTEGER arrayWorkspace
10:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, N<2.
IFAIL=2
On entry, | LDSSP<N,
or | LDR<N.
IFAIL=3
On entry, | KORDER i<1,
or | KORDER i>N for some i=1,2,…,n.
IFAIL=4
On entry, there is not a one-to-one correspondence between the old variables and the new variables; at least one of the original variables is not included in the new set, and consequently at least one other variable has been included more than once.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

Not applicable.

8 Parallelism and Performance

G02CFF is not threaded in any implementation.

9 Further Comments

The time taken by G02CFF depends on n and the amount of re-arrangement involved.
The routine is intended primarily for use when a set of variables is to be reordered for use in a regression, and is described accordingly. There is however no reason why the routine should not also be used to reorder vectors and matrices which contain any other non-statistical information; the matrices need not be symmetric.
The routine may be used either with sums of squares and cross-products of deviations from means and Pearson product-moment correlation coefficients in connection with a regression involving a constant, or with sums of squares and cross-products about zero and correlation-like coefficients in connection with a regression with no constant.

10 Example

This example reads in the means, standard deviations, sums of squares and cross-products, and correlation coefficients for three variables. The vectors and matrices are reordered so that they contain the means, standard deviations, sums of squares and cross-products, and correlation coefficients for the first, third and second variables (in that order). Finally the reordered vectors and matrices are printed.

10.1 Program Text

Program Text (g02cffe.f90)

10.2 Program Data

Program Data (g02cffe.d)

10.3 Program Results

Program Results (g02cffe.r)

G02 Chapter Contents
G02 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


G02CGF : NAG Library, Mark 26

G02 Chapter Contents
G02 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

G02CGF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

G02CGF performs a multiple linear regression on a set of variables whose means, sums of squares and cross-products of deviations from means, and Pearson product-moment correlation coefficients are given.

2 Specification

SUBROUTINE G02CGF ( N, K1, K, XBAR, SSP, LDSSP, R, LDR, RESULT, COEF, LDCOEF, CON, RINV, LDRINV, C, LDC, WKZ, LDWKZ, IFAIL)
INTEGER | N, K1, K, LDSSP, LDR, LDCOEF, LDRINV, LDC, LDWKZ, IFAIL
REAL (KIND=nag_wp) | XBAR(K1), SSP(LDSSP,K1), R(LDR,K1), RESULT(13), COEF(LDCOEF,3), CON(3), RINV(LDRINV,K), C(LDC,K), WKZ(LDWKZ,K)

3 Description

G02CGF fits a curve of the form
y=a+b 1x 1+b 2x 2+⋯+bkxk
to the data points
x 11,x 21,…,x k 1,y 1 x 12,x 22,…,x k 2,y 2 ⋮ x 1 n,x 2 n,…,x kn,yn
such that
yi=a+b 1x 1 i+b 2x 2 i+⋯+bkx ki+ei,  i=1,2,…,n.
The routine calculates the regression coefficients, b 1,b 2,…,bk, the regression constant, a, and various other statistical quantities by minimizing
∑i=1 n ei 2.
The actual data values x 1 i,x 2 i,…,x ki,yi are not provided as input to the routine. Instead, input consists of:
(i) | The number of cases, n, on which the regression is based.
(ii) | The total number of variables, dependent and independent, in the regression, k+1.
(iii) | The number of independent variables in the regression, k.
(iv) | The means of all k+1 variables in the regression, both the independent variables x 1,x 2,…,xk and the dependent variable y, which is the k+1th variable: i.e., x-1,x-2,…,x-k,y-.
(v) | The k+1 by k+1 matrix [S ij] of sums of squares and cross-products of deviations from means of all the variables in the regression; the terms involving the dependent variable, y, appear in the k+1th row and column.
(vi) | The k+1 by k+1 matrix [R ij] of the Pearson product-moment correlation coefficients for all the variables in the regression; the correlations involving the dependent variable, y, appear in the k+1th row and column.
The quantities calculated are:
(a) The inverse of the k by k partition of the matrix of correlation coefficients, [R ij], involving only the independent variables. The inverse is obtained using an accurate method which assumes that this sub-matrix is positive definite.
(b) The modified inverse matrix, C=c ij, where
c ij=R ijr ij S ij,  i,j=1,2,…,k,
where r ij is the i,jth element of the inverse matrix of [R ij] as described in (a) above. Each element of C is thus the corresponding element of the matrix of correlation coefficients multiplied by the corresponding element of the inverse of this matrix, divided by the corresponding element of the matrix of sums of squares and cross-products of deviations from means.
(c) The regression coefficients:
bi=∑j=i k c ijS j k+1,  i=1,2,…,k,
where S j k+1 is the sum of cross-products of deviations from means for the independent variable xj and the dependent variable y.
(d) The sum of squares attributable to the regression, SSR, the sum of squares of deviations about the regression, SSD, and the total sum of squares, SST:
  • SST=S k+1k+1, the sum of squares of deviations from the mean for the dependent variable, y;
  • SSR=∑j=1 k bjS j k+1;  SSD=SST-SSR
(e) The degrees of freedom attributable to the regression, DFR, the degrees of freedom of deviations about the regression, DFD, and the total degrees of freedom, DFT:
DFR=k;  DFD=n-k-1;  DFT=n-1.
(f) The mean square attributable to the regression, MSR, and the mean square of deviations about the regression, MSD:
MSR=SSR/DFR;  MSD=SSD/DFD.
(g) The F values for the analysis of variance:
F=MSR/MSD.
(h) The standard error estimate:
s=MSD.
(i) The coefficient of multiple correlation, R, the coefficient of multiple determination, R 2 and the coefficient of multiple determination corrected for the degrees of freedom, R-2;
R=1-SSD SST ;  R 2=1-SSD SST ;  R-2=1-SSD×DFT SST×DFD .
(j) The standard error of the regression coefficients:
se bi=MSD×c ii,   i= 1,2,…,k.
(k) The t values for the regression coefficients:
t bi=bi se bi ,  i=1,2,…,k.
(l) The regression constant, a, its standard error, se a, and its t value, t a:
a=y--∑i=1 k bix-i;  se a=MSD×1 n+∑i=1 k∑j=1 k x-ic ijx-j ;  t a=a se a .

4 References

Draper N R and Smith H (1985) Applied Regression Analysis (2nd Edition) Wiley

5 Arguments

1:   N – INTEGERInput
On entry: the number of cases n, used in calculating the sums of squares and cross-products and correlation coefficients.
2:   K1 – INTEGERInput
On entry: the total number of variables, independent and dependent, k+1, in the regression.
Constraint: 2≤K1<N.
3:   K – INTEGERInput
On entry: the number of independent variables k in the regression.
Constraint: K=K1-1.
4:   XBAR K1 – REAL (KIND=nag_wp) arrayInput
On entry: XBAR i must be set to x-i, the mean value of the ith variable, for i=1,2,…,k+1; the mean of the dependent variable must be contained in XBAR k+1.
5:   SSP LDSSPK1 – REAL (KIND=nag_wp) arrayInput
On entry: SSP ij must be set to S ij, the sum of cross-products of deviations from means for the ith and jth variables, for i=1,2,…,k+1 and j=1,2,…,k+1; terms involving the dependent variable appear in row k+1 and column k+1.
6:   LDSSP – INTEGERInput
On entry: the first dimension of the array SSP as declared in the (sub)program from which G02CGF is called.
Constraint: LDSSP≥K1.
7:   R LDRK1 – REAL (KIND=nag_wp) arrayInput
On entry: R ij must be set to R ij, the Pearson product-moment correlation coefficient for the ith and jth variables, for i=1,2,…,k+1 and j=1,2,…,k+1; terms involving the dependent variable appear in row k+1 and column k+1.
8:   LDR – INTEGERInput
On entry: the first dimension of the array R as declared in the (sub)program from which G02CGF is called.
Constraint: LDR≥K1.
9:   RESULT 13 – REAL (KIND=nag_wp) arrayOutput
On exit: the following information:
RESULT 1 | SSR, the sum of squares attributable to the regression;
RESULT 2 | DFR, the degrees of freedom attributable to the regression;
RESULT 3 | MSR, the mean square attributable to the regression;
RESULT 4 | F, the F value for the analysis of variance;
RESULT 5 | SSD, the sum of squares of deviations about the regression;
RESULT 6 | DFD, the degrees of freedom of deviations about the regression;
RESULT 7 | MSD, the mean square of deviations about the regression;
RESULT 8 | SST, the total sum of squares;
RESULT 9 | DFT, the total degrees of freedom;
RESULT 10 | s, the standard error estimate;
RESULT 11 | R, the coefficient of multiple correlation;
RESULT 12 | R 2, the coefficient of multiple determination;
RESULT 13 | R-2, the coefficient of multiple determination corrected for the degrees of freedom.
10:   COEF LDCOEF 3 – REAL (KIND=nag_wp) arrayOutput
On exit: for i=1,2,…,k, the following information:
COEF i 1
bi, the regression coefficient for the ith variable.
COEF i 2
se bi, the standard error of the regression coefficient for the ith variable.
COEF i 3
t bi, the t value of the regression coefficient for the ith variable.
11:   LDCOEF – INTEGERInput
On entry: the first dimension of the array COEF as declared in the (sub)program from which G02CGF is called.
Constraint: LDCOEF≥K.
12:   CON 3 – REAL (KIND=nag_wp) arrayOutput
On exit: the following information:
CON 1 | a, the regression constant;
CON 2 | se a, the standard error of the regression constant;
CON 3 | t a, the t value for the regression constant.
13:   RINV LDRINVK – REAL (KIND=nag_wp) arrayOutput
On exit: the inverse of the matrix of correlation coefficients for the independent variables; that is, the inverse of the matrix consisting of the first k rows and columns of R.
14:   LDRINV – INTEGERInput
On entry: the first dimension of the array RINV as declared in the (sub)program from which G02CGF is called.
Constraint: LDRINV≥K.
15:   C LDCK – REAL (KIND=nag_wp) arrayOutput
On exit: the modified inverse matrix, where
  • C ij=R ij×RINV ij/SSP ij, for i=1,2,…,k and j=1,2,…,k.
16:   LDC – INTEGERInput
On entry: the first dimension of the array C as declared in the (sub)program from which G02CGF is called.
Constraint: LDC≥K.
17:   WKZ LDWKZK – REAL (KIND=nag_wp) arrayWorkspace
18:   LDWKZ – INTEGERInput
On entry: the first dimension of the array WKZ as declared in the (sub)program from which G02CGF is called.
Constraint: LDWKZ≥K.
19:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, K1<2.
IFAIL=2
On entry, K1≠K+1.
IFAIL=3
On entry, N≤K1.
IFAIL=4
On entry, | LDSSP<K1,
or | LDR<K1,
or | LDCOEF<K,
or | LDRINV<K,
or | LDC<K,
or | LDWKZ<K.
IFAIL=5
The k by k partition of the matrix R which is to be inverted is not positive definite.
IFAIL=6
The refinement following the actual inversion fails, indicating that the k by k partition of the matrix R, which is to be inverted, is ill-conditioned. The use of G02DAF, which employs a different numerical technique, may avoid this difficulty (an extra ‘variable’ representing the constant term must be introduced for G02DAF).
IFAIL=7
An unexpected error has been triggered internally whilst solving a set of linear equations. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

The accuracy of G02CGF is almost entirely dependent on the accuracy of the matrix inversion method used. As G02CGF works with the matrix of correlation coefficients rather than that of the sums of squares and cross-products of deviations from means all terms in the matrix being inverted are of a similar order and therefore the scope for computational error is reduced. An alternative, and potentially more numerically reliable, routine is G02DAF. G02DAF works directly with the data matrix and therefore avoids explicitly performing a matrix inversion. However, G02DAF does not handle missing values, nor does it provide the same output as this routine.
If, in calculating F, t a, or any of the t bi (see Section 3), the numbers involved are such that the result would be outside the range of numbers which can be stored by the machine, then the answer is set to the largest quantity which can be stored as a real variable, by means of a call to X02ALF.

8 Parallelism and Performance

G02CGF is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
G02CGF makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The time taken by G02CGF depends on k.
This routine assumes that the matrix of correlation coefficients for the independent variables in the regression is positive definite; it fails if this is not the case.
This correlation matrix will in fact be positive definite whenever the correlation matrix and the sums of squares and cross-products (of deviations from means) matrix have been formed either without regard to missing values, or by eliminating completely any cases involving missing values, for any variable. If, however, these matrices are formed by eliminating cases with missing values from only those calculations involving the variables for which the values are missing, no such statement can be made, and the correlation matrix may or may not be positive definite. You should be aware of the possible dangers of using correlation matrices formed in this way (see the G02 Chapter Introduction), but if they nevertheless wish to carry out regression using such matrices, this routine is capable of handling the inversion of such matrices provided they are positive definite.
If a matrix is positive definite, its subsequent re-organisation by either G02CEF or G02CFF will not affect this property, and the new matrix can safely be used in this routine. Thus correlation matrices produced by any of G02BAF, G02BBF, G02BGF or G02BHF, even if subsequently modified by either G02CEF or G02CFF, can be handled by this routine.
It should be noted that in forming the sums of squares and cross-products matrix and the correlation matrix a column of constants should not be added to the data as an additional ‘variable’ in order to obtain a constant term in the regression. This routine automatically calculates the regression constant, a, and any attempt to insert such a ‘dummy variable’ is likely to cause the routine to fail.
It should also be noted that the routine requires the dependent variable to be the last of the k+1 variables whose statistics are provided as input to the routine. If this variable is not correctly positioned in the original data, the means, standard deviations, sums of squares and cross-products of deviations from means, and correlation coefficients can be manipulated by using G02CEF or G02CFF to reorder the variables as necessary.

10 Example

This example reads in the means, sums of squares and cross-products of deviations from means, and correlation coefficients for three variables. A multiple linear regression is then performed with the third and final variable as the dependent variable. Finally the results are printed.

10.1 Program Text

Program Text (g02cgfe.f90)

10.2 Program Data

Program Data (g02cgfe.d)

10.3 Program Results

Program Results (g02cgfe.r)

G02 Chapter Contents
G02 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


G02CHF : NAG Library, Mark 26

G02 Chapter Contents
G02 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

G02CHF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

G02CHF performs a multiple linear regression with no constant on a set of variables whose sums of squares and cross-products about zero and correlation-like coefficients are given.

2 Specification

SUBROUTINE G02CHF ( N, K1, K, SSPZ, LDSSPZ, RZ, LDRZ, RESULT, COEF, LDCOEF, RZNV, LDRZNV, CZ, LDCZ, WKZ, LDWKZ, IFAIL)
INTEGER | N, K1, K, LDSSPZ, LDRZ, LDCOEF, LDRZNV, LDCZ, LDWKZ, IFAIL
REAL (KIND=nag_wp) | SSPZ(LDSSPZ,K1), RZ(LDRZ,K1), RESULT(13), COEF(LDCOEF,3), RZNV(LDRZNV,K), CZ(LDCZ,K), WKZ(LDWKZ,K)

3 Description

G02CHF fits a curve of the form
y=b 1x 1+b 2x 2+⋯+bkxk
to the data points
x 11,x 21,…,x k 1,y 1 x 12,x 22,…,x k 2,y 2 ⋮ x 1 n,x 2 n,…,x kn,yn
such that
yi=b 1x 1 i+b 2x 2 i+⋯+bkx ki+ei,  i=1,2,…,n.
The routine calculates the regression coefficients, b 1,b 2,…,bk, (and various other statistical quantities) by minimizing
∑i=1 n ei 2.
The actual data values x 1 i,x 2 i,…,x ki,yi are not provided as input to the routine. Instead, input to the routine consists of:
(i) | The number of cases, n, on which the regression is based.
(ii) | The total number of variables, dependent and independent, in the regression, k+1.
(iii) | The number of independent variables in the regression, k.
(iv) | The k+1 by k+1 matrix S~ij of sums of squares and cross-products about zero of all the variables in the regression; the terms involving the dependent variable, y, appear in the k+1th row and column.
(v) | The k+1 by k+1 matrix R~ij of correlation-like coefficients for all the variables in the regression; the correlations involving the dependent variable, y, appear in the k+1th row and column.
The quantities calculated are:
(a) The inverse of the k by k partition of the matrix of correlation-like coefficients, R~ij, involving only the independent variables. The inverse is obtained using an accurate method which assumes that this sub-matrix is positive definite (see Section 9).
(b) The modified matrix, C=c ij, where
c ij=R~ij r~ij S~ij,  i,j=1,2,…,k,
where r~ij is the i,jth element of the inverse matrix of R~ij as described in (a) above. Each element of C is thus the corresponding element of the matrix of correlation-like coefficients multiplied by the corresponding element of the inverse of this matrix, divided by the corresponding element of the matrix of sums of squares and cross-products about zero.
(c) The regression coefficients:
bi=∑j=1 k c ijS~j k+1,  i=1,2,…,k,
where S~j k+1 is the sum of cross-products about zero for the independent variable xj and the dependent variable y.
(d) The sum of squares attributable to the regression, SSR, the sum of squares of deviations about the regression, SSD, and the total sum of squares, SST:
  • SST=S~k+1k+1, the sum of squares about zero for the dependent variable, y;
  • SSR=∑j=1 k bjS~j k+1;  SSD=SST-SSR.
(e) The degrees of freedom attributable to the regression, DFR, the degrees of freedom of deviations about the regression, DFD, and the total degrees of freedom, DFT:
DFR=k;  DFD=n-k;  DFT=n.
(f) The mean square attributable to the regression, MSR, and the mean square of deviations about the regression, MSD:
MSR=SSR/DFR;  MSD=SSD/DFD.
(g) The F value for the analysis of variance:
F=MSR/MSD.
(h) The standard error estimate:
s=MSD.
(i) The coefficient of multiple correlation, R, the coefficient of multiple determination, R 2, and the coefficient of multiple determination corrected for the degrees of freedom, R-2:
R=1-SSD SST ;  R 2=1-SSD SST ;   R-2=1-SSD×DFT SST×DFD .
(j) The standard error of the regression coefficients:
se bi=MSD×c ii,   i= 1,2,…,k.
(k) The t values for the regression coefficients:
t bi=bi se bi ,  i=1,2,…,k.

4 References

Draper N R and Smith H (1985) Applied Regression Analysis (2nd Edition) Wiley

5 Arguments

1:   N – INTEGERInput
On entry: n, the number of cases used in calculating the sums of squares and cross-products and correlation-like coefficients.
2:   K1 – INTEGERInput
On entry: the total number of variables, independent and dependent k+1, in the regression.
Constraint: 2≤K1≤N.
3:   K – INTEGERInput
On entry: the number of independent variables k in the regression.
Constraint: K=K1-1.
4:   SSPZ LDSSPZK1 – REAL (KIND=nag_wp) arrayInput
On entry: SSPZ ij must be set to S~ij, the sum of cross-products about zero for the ith and jth variables, for i=1,2,…,k+1 and j=1,2,…,k+1; terms involving the dependent variable appear in row k+1 and column k+1.
5:   LDSSPZ – INTEGERInput
On entry: the first dimension of the array SSPZ as declared in the (sub)program from which G02CHF is called.
Constraint: LDSSPZ≥K1.
6:   RZ LDRZK1 – REAL (KIND=nag_wp) arrayInput
On entry: RZ ij must be set to R~ij, the correlation-like coefficient for the ith and jth variables, for i=1,2,…,k+1 and j=1,2,…,k+1; coefficients involving the dependent variable appear in row k+1 and column k+1.
7:   LDRZ – INTEGERInput
On entry: the first dimension of the array RZ as declared in the (sub)program from which G02CHF is called.
Constraint: LDRZ≥K1.
8:   RESULT 13 – REAL (KIND=nag_wp) arrayOutput
On exit: the following information:
RESULT 1 | SSR, the sum of squares attributable to the regression;
RESULT 2 | DFR, the degrees of freedom attributable to the regression;
RESULT 3 | MSR, the mean square attributable to the regression;
RESULT 4 | F, the F value for the analysis of variance;
RESULT 5 | SSD, the sum of squares of deviations about the regression;
RESULT 6 | DFD, the degrees of freedom of deviations about the regression;
RESULT 7 | MSD, the mean square of deviations about the regression;
RESULT 8 | SST, the total sum of squares;
RESULT 9 | DFT, the total degrees of freedom;
RESULT 10 | s, the standard error estimate;
RESULT 11 | R, the coefficient of multiple correlation;
RESULT 12 | R 2, the coefficient of multiple determination;
RESULT 13 | R-2, the coefficient of multiple determination corrected for the degrees of freedom.
9:   COEF LDCOEF 3 – REAL (KIND=nag_wp) arrayOutput
On exit: for i=1,2,…,k, the following information:
COEF i 1
bi, the regression coefficient for the ith variable.
COEF i 2
se bi, the standard error of the regression coefficient for the ith variable.
COEF i 3
t bi, the t value of the regression coefficient for the ith variable.
10:   LDCOEF – INTEGERInput
On entry: the first dimension of the array COEF as declared in the (sub)program from which G02CHF is called.
Constraint: LDCOEF≥K.
11:   RZNV LDRZNVK – REAL (KIND=nag_wp) arrayOutput
On exit: the inverse of the matrix of correlation-like coefficients for the independent variables; that is, the inverse of the matrix consisting of the first k rows and columns of RZ.
12:   LDRZNV – INTEGERInput
On entry: the first dimension of the array RZNV as declared in the (sub)program from which G02CHF is called.
Constraint: LDRZNV≥K.
13:   CZ LDCZK – REAL (KIND=nag_wp) arrayOutput
On exit: the modified inverse matrix, C, where
CZ ij=RZ ij×RZNV ij SSPZ ij ,  i,j=1,2,…,k.
14:   LDCZ – INTEGERInput
On entry: the first dimension of the array CZ as declared in the (sub)program from which G02CHF is called.
Constraint: LDCZ≥K.
15:   WKZ LDWKZK – REAL (KIND=nag_wp) arrayWorkspace
16:   LDWKZ – INTEGERInput
On entry: the first dimension of the array WKZ as declared in the (sub)program from which G02CHF is called.
Constraint: LDWKZ≥K.
17:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, K1<2.
IFAIL=2
On entry, K1≠K+1.
IFAIL=3
On entry, N<K1.
IFAIL=4
On entry, | LDSSPZ<K1,
or | LDRZ<K1,
or | LDCOEF<K,
or | LDRZNV<K,
or | LDCZ<K,
or | LDWKZ<K.
IFAIL=5
This indicates that the k by k partition of the matrix held in RZ, which is to be inverted, is not positive definite.
IFAIL=6
This indicates that the refinement following the actual inversion fails, indicating that the k by k partition of the matrix held in RZ, which is to be inverted, is ill-conditioned. The use of G02DAF, which employs a different numerical technique, may avoid the difficulty.
IFAIL=7
An unexpected error has been triggered internally whilst solving a set of linear equations. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

The accuracy of G02CHF is almost entirely dependent on the accuracy of the matrix inversion method used. As G02CHF works with the matrix of correlation coefficients rather than that of the sums of squares and cross-products of deviations from means all terms in the matrix being inverted are of a similar order and therefore the scope for computational error is reduced. An alternative, and potentially more numerically reliable, routine is G02DAF. G02DAF works directly with the data matrix and therefore avoids explicitly performing a matrix inversion. However, G02DAF does not handle missing values, nor does it provide the same output as this routine.
If, in calculating F or any of the t bi (see Section 3), the numbers involved are such that the result would be outside the range of numbers which can be stored by the machine, then the answer is set to the largest quantity which can be stored as a real variable, by means of a call to X02ALF.

8 Parallelism and Performance

G02CHF is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
G02CHF makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The time taken by G02CHF depends on k.
This routine assumes that the matrix of correlation-like coefficients for the independent variables in the regression is positive definite; it fails if this is not the case.
This correlation matrix will in fact be positive definite whenever the correlation-like matrix and the sums of squares and cross-products (about zero) matrix have been formed either without regard to missing values, or by eliminating completely any cases involving missing values for any variable. If, however, these matrices are formed by eliminating cases with missing values from only those calculations involving the variables for which the values are missing, no such statement can be made, and the correlation-like matrix may or may not be positive definite. You should be aware of the possible dangers of using correlation matrices formed in this way (see the G02 Chapter Introduction), but if they nevertheless wish to carry out regressions using such matrices, this routine is capable of handling the inversion of such matrices, provided they are positive definite.
If a matrix is positive definite, its subsequent re-organisation by either of G02CEF or G02CFF will not affect this property and the new matrix can safely be used in this routine. Thus correlation matrices produced by any of G02BDF, G02BEF, G02BKF or G02BLF, even if subsequently modified by either G02CEF or G02CFF, can be handled by this routine.
It should be noted that the routine requires the dependent variable to be the last of the k+1 variables whose statistics are provided as input to the routine. If this variable is not correctly positioned in the original data, the means, standard deviations, sums of squares and cross-products about zero, and correlation-like coefficients can be manipulated by using G02CEF or G02CFF to reorder the variables as necessary.

10 Example

This example reads in the sums of squares and cross-products about zero, and correlation-like coefficients for three variables. A multiple linear regression with no constant is then performed with the third and final variable as the dependent variable. Finally the results are printed.

10.1 Program Text

Program Text (g02chfe.f90)

10.2 Program Data

Program Data (g02chfe.d)

10.3 Program Results

Program Results (g02chfe.r)

G02 Chapter Contents
G02 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


G02 Chapter Contents : NAG Library Manual, Mark 26

G02 Chapter Introduction
NAG Library Manual

NAG Library Chapter Contents

G02 – Correlation and Regression Analysis

G02 Chapter Introduction – a description of the Chapter and an overview of the algorithms available

Routine Name | Mark of Introduction | Purpose
G02AAF Example Text Example Data | 22 | nagf_correg_corrmat_nearest Computes the nearest correlation matrix to a real square matrix, using the method of Qi and Sun
G02ABF Example Text Example Data | 23 | nagf_correg_corrmat_nearest_bounded Computes the nearest correlation matrix to a real square matrix, augmented G02AAF to incorporate weights and bounds
G02AEF Example Text Example Data | 23 | nagf_correg_corrmat_nearest_kfactor Computes the nearest correlation matrix with k-factor structure to a real square matrix
G02AJF Example Text Example Data | 24 | nagf_nearest_correlation_h_weight Computes the nearest correlation matrix to a real square matrix, using element-wise weighting
G02ANF Example Text Example Data | 25 | nagf_nearest_correlation_shrinking Computes a correlation matrix from an approximate matrix with fixed submatrix
G02APF Example Text Example Data | 26 | nagf_nearest_correlation_target Computes a correlation matrix from an approximate one using a specified target matrix
G02BAF Example Text Example Data | 4 | nagf_correg_coeffs_pearson Pearson product-moment correlation coefficients, all variables, no missing values
G02BBF Example Text Example Data | 4 | nagf_correg_coeffs_pearson_miss_case Pearson product-moment correlation coefficients, all variables, casewise treatment of missing values
G02BCF Example Text Example Data | 4 | nagf_correg_coeffs_pearson_miss_pair Pearson product-moment correlation coefficients, all variables, pairwise treatment of missing values
G02BDF Example Text Example Data | 4 | nagf_correg_coeffs_zero Correlation-like coefficients (about zero), all variables, no missing values
G02BEF Example Text Example Data | 4 | nagf_correg_coeffs_zero_miss_case Correlation-like coefficients (about zero), all variables, casewise treatment of missing values
G02BFF Example Text Example Data | 4 | nagf_correg_coeffs_zero_miss_pair Correlation-like coefficients (about zero), all variables, pairwise treatment of missing values
G02BGF Example Text Example Data | 4 | nagf_correg_coeffs_pearson_subset Pearson product-moment correlation coefficients, subset of variables, no missing values
G02BHF Example Text Example Data | 4 | nagf_correg_coeffs_pearson_subset_miss_case Pearson product-moment correlation coefficients, subset of variables, casewise treatment of missing values
G02BJF Example Text Example Data | 4 | nagf_correg_coeffs_pearson_subset_miss_pair Pearson product-moment correlation coefficients, subset of variables, pairwise treatment of missing values
G02BKF Example Text Example Data | 4 | nagf_correg_coeffs_zero_subset Correlation-like coefficients (about zero), subset of variables, no missing values
G02BLF Example Text Example Data | 4 | nagf_correg_coeffs_zero_subset_miss_case Correlation-like coefficients (about zero), subset of variables, casewise treatment of missing values
G02BMF Example Text Example Data | 4 | nagf_correg_coeffs_zero_subset_miss_pair Correlation-like coefficients (about zero), subset of variables, pairwise treatment of missing values
G02BNF Example Text Example Data | 4 | nagf_correg_coeffs_kspearman_overwrite Kendall/Spearman non-parametric rank correlation coefficients, no missing values, overwriting input data
G02BPF Example Text Example Data | 4 | nagf_correg_coeffs_kspearman_miss_case_overwrite Kendall/Spearman non-parametric rank correlation coefficients, casewise treatment of missing values, overwriting input data
G02BQF Example Text Example Data | 4 | nagf_correg_coeffs_kspearman Kendall/Spearman non-parametric rank correlation coefficients, no missing values, preserving input data
G02BRF Example Text Example Data | 4 | nagf_correg_coeffs_kspearman_miss_case Kendall/Spearman non-parametric rank correlation coefficients, casewise treatment of missing values, preserving input data
G02BSF Example Text Example Data | 4 | nagf_correg_coeffs_kspearman_miss_pair Kendall/Spearman non-parametric rank correlation coefficients, pairwise treatment of missing values
G02BTF Example Text Example Data | 14 | nagf_correg_ssqmat_update Update a weighted sum of squares matrix with a new observation
G02BUF Example Text Example Data | 14 | nagf_correg_ssqmat Computes a weighted sum of squares matrix
G02BWF Example Text Example Data | 14 | nagf_correg_ssqmat_to_corrmat Computes a correlation matrix from a sum of squares matrix
G02BXF Example Text Example Data | 14 | nagf_correg_corrmat Computes (optionally weighted) correlation and covariance matrices
G02BYF Example Text Example Data | 17 | nagf_correg_corrmat_partial Computes partial correlation/variance-covariance matrix from correlation/variance-covariance matrix computed by G02BXF
G02BZF Example Text Example Data | 24 | nagf_correg_ssqmat_combine Combines two sums of squares matrices, for use after G02BUF
G02CAF Example Text Example Data | 4 | nagf_correg_linregs_const Simple linear regression with constant term, no missing values
G02CBF Example Text Example Data | 4 | nagf_correg_linregs_noconst Simple linear regression without constant term, no missing values
G02CCF Example Text Example Data | 4 | nagf_correg_linregs_const_miss Simple linear regression with constant term, missing values
G02CDF Example Text Example Data | 4 | nagf_correg_linregs_noconst_miss Simple linear regression without constant term, missing values
G02CEF Example Text Example Data | 4 | nagf_correg_linregm_service_select Service routine for multiple linear regression, select elements from vectors and matrices
G02CFF Example Text Example Data | 4 | nagf_correg_linregm_service_reorder Service routine for multiple linear regression, reorder elements of vectors and matrices
G02CGF Example Text Example Data | 4 | nagf_correg_linregm_coeffs_const Multiple linear regression, from correlation coefficients, with constant term
G02CHF Example Text Example Data | 4 | nagf_correg_linregm_coeffs_noconst Multiple linear regression, from correlation-like coefficients, without constant term
G02DAF Example Text Example Data | 14 | nagf_correg_linregm_fit Fits a general (multiple) linear regression model
G02DCF Example Text Example Data | 14 | nagf_correg_linregm_obs_edit Add/delete an observation to/from a general linear regression model
G02DDF Example Text Example Data | 14 | nagf_correg_linregm_update Estimates of linear parameters and general linear regression model from updated model
G02DEF Example Text Example Data | 14 | nagf_correg_linregm_var_add Add a new independent variable to a general linear regression model
G02DFF Example Text Example Data | 14 | nagf_correg_linregm_var_del Delete an independent variable from a general linear regression model
G02DGF Example Text Example Data | 14 | nagf_correg_linregm_fit_newvar Fits a general linear regression model to new dependent variable
G02DKF Example Text Example Data | 14 | nagf_correg_linregm_constrain Estimates and standard errors of parameters of a general linear regression model for given constraints
G02DNF Example Text Example Data | 14 | nagf_correg_linregm_estfunc Computes estimable function of a general linear regression model and its standard error
G02EAF Example Text Example Data | 14 | nagf_correg_linregm_rssq Computes residual sums of squares for all possible linear regressions for a set of independent variables
G02ECF Example Text Example Data | 14 | nagf_correg_linregm_rssq_stat Calculates R 2 and CP values from residual sums of squares
G02EEF Example Text Example Data | 14 | nagf_correg_linregm_fit_onestep Fits a linear regression model by forward selection
G02EFF Example Text Example Data | 21 | nagf_correg_linregm_fit_stepwise Stepwise linear regression
G02FAF Example Text Example Data | 14 | nagf_correg_linregm_stat_resinf Calculates standardized residuals and influence statistics
G02FCF Example Text Example Data | 15 | nagf_correg_linregm_stat_durbwat Computes Durbin–Watson test statistic
G02GAF Example Text Example Data | 14 | nagf_correg_glm_normal Fits a generalized linear model with Normal errors
G02GBF Example Text Example Data | 14 | nagf_correg_glm_binomial Fits a generalized linear model with binomial errors
G02GCF Example Text Example Data | 14 | nagf_correg_glm_poisson Fits a generalized linear model with Poisson errors
G02GDF Example Text Example Data | 14 | nagf_correg_glm_gamma Fits a generalized linear model with gamma errors
G02GKF Example Text Example Data | 14 | nagf_correg_glm_constrain Estimates and standard errors of parameters of a general linear model for given constraints
G02GNF Example Text Example Data | 14 | nagf_correg_glm_estfunc Computes estimable function of a generalized linear model and its standard error
G02GPF Example Text Example Data | 22 | nagf_correg_glm_predict Computes a predicted value and its associated standard error based on a previously fitted generalized linear model
G02HAF Example Text Example Data | 13 | nagf_correg_robustm Robust regression, standard M-estimates
G02HBF Example Text Example Data | 13 | nagf_correg_robustm_wts Robust regression, compute weights for use with G02HDF
G02HDF Example Text Example Data | 13 | nagf_correg_robustm_user Robust regression, compute regression with user-supplied functions and weights
G02HFF Example Text Example Data | 13 | nagf_correg_robustm_user_varmat Robust regression, variance-covariance matrix following G02HDF
G02HKF Example Text Example Data | 14 | nagf_correg_robustm_corr_huber Calculates a robust estimation of a covariance matrix, Huber's weight function
G02HLF Example Text Example Data | 14 | nagf_correg_robustm_corr_user_deriv Calculates a robust estimation of a covariance matrix, user-supplied weight function plus derivatives
G02HMF Example Text Example Data | 14 | nagf_correg_robustm_corr_user Calculates a robust estimation of a covariance matrix, user-supplied weight function
G02JAF Example Text Example Data | 21 | nagf_correg_mixeff_reml Linear mixed effects regression using Restricted Maximum Likelihood (REML)
G02JBF Example Text Example Data | 21 | nagf_correg_mixeff_ml Linear mixed effects regression using Maximum Likelihood (ML)
G02JCF | 23 | nagf_correg_mixeff_hier_init Hierarchical mixed effects regression, initialization routine for G02JDF and G02JEF
G02JDF Example Text Example Data | 23 | nagf_correg_mixeff_hier_reml Hierarchical mixed effects regression using Restricted Maximum Likelihood (REML)
G02JEF Example Text Example Data | 23 | nagf_correg_mixeff_hier_ml Hierarchical mixed effects regression using Maximum Likelihood (ML)
G02KAF Example Text Example Data | 22 | nagf_correg_ridge_opt Ridge regression, optimizing a ridge regression parameter
G02KBF Example Text Example Data | 22 | nagf_correg_ridge Ridge regression using a number of supplied ridge regression parameters
G02LAF Example Text Example Data | 22 | nagf_correg_pls_svd Partial least squares (PLS) regression using singular value decomposition
G02LBF Example Text Example Data | 22 | nagf_correg_pls_wold Partial least squares (PLS) regression using Wold's iterative method
G02LCF Example Text Example Data | 22 | nagf_correg_pls_fit PLS parameter estimates following partial least squares regression by G02LAF or G02LBF
G02LDF Example Text Example Data | 22 | nagf_correg_pls_pred PLS predictions based on parameter estimates from G02LCF
G02MAF Example Text Example Data Example Plot | 25 | nagf_correg_lars Least angle regression (LARS), least absolute shrinkage and selection operator (LASSO) and forward stagewise regression
G02MBF Example Text Example Data Example Plot | 25 | nagf_correg_lars_xtx Least Angle Regression (LARS), Least Absolute Shrinkage and Selection Operator (LASSO) and forward stagewise regression using the cross-products matrix
G02MCF Example Text Example Data | 25 | nagf_correg_lars_param Calculates additional parameter estimates following Least Angle Regression (LARS), Least Absolute Shrinkage and Selection Operator (LASSO) or forward stagewise regression
G02QFF Example Text Example Data Example Plot | 23 | nagf_correg_quantile_linreg_easy Linear quantile regression, simple interface, independent, identically distributed (IID) errors
G02QGF Example Text Example Data Example Plot | 23 | nagf_correg_quantile_linreg Linear quantile regression, comprehensive interface
G02ZKF | 23 | nagf_correg_optset Option setting routine for G02QGF
G02ZLF | 23 | nagf_correg_optget Option getting routine for G02QGF
G02 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


G02DAF : NAG Library, Mark 26

G02 Chapter Contents
G02 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

G02DAF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

G02DAF performs a general multiple linear regression when the independent variables may be linearly dependent. Parameter estimates, standard errors, residuals and influence statistics are computed. G02DAF may be used to perform a weighted regression.

2 Specification

SUBROUTINE G02DAF ( MEAN, WEIGHT, N, X, LDX, M, ISX, IP, Y, WT, RSS, IDF, B, SE, COV, RES, H, Q, LDQ, SVD, IRANK, P, TOL, WK, IFAIL)
INTEGER | N, LDX, M, ISX(M), IP, IDF, LDQ, IRANK, IFAIL
REAL (KIND=nag_wp) | X(LDX,M), Y(N), WT(*), RSS, B(IP), SE(IP), COV(IP*(IP+1)/2), RES(N), H(N), Q(LDQ,IP+1), P(2*IP+IP*IP), TOL, WK(max(2,5*(IP-1)+IP*IP))
LOGICAL | SVD
CHARACTER(1) | MEAN, WEIGHT

3 Description

The general linear regression model is defined by
y=Xβ+ε,
where
  • y is a vector of n observations on the dependent variable,
  • X is an n by p matrix of the independent variables of column rank k,
  • β is a vector of length p of unknown arguments, and
  • ε is a vector of length n of unknown random errors such that var⁡ε=V σ 2, where V is a known diagonal matrix.
If V=I, the identity matrix, then least squares estimation is used. If V≠I, then for a given weight matrix W∝V-1, weighted least squares estimation is used.
The least squares estimates β^ of the arguments β minimize y-Xβ T y-Xβ while the weighted least squares estimates minimize y-Xβ T W y-Xβ .
G02DAF finds a QR decomposition of X (or W 1/2 X in weighted case), i.e.,
X=Q R* or  W 1/2 X=Q R*,
where R*= R 0 and R is a p by p upper triangular matrix and Q is an n by n orthogonal matrix. If R is of full rank, then β^ is the solution to
R β^=c 1,
where c=QT y (or QTW 1/2 y) and c 1 is the first p elements of c. If R is not of full rank a solution is obtained by means of a singular value decomposition (SVD) of R,
R=Q* D 0 0 0 PT,
where D is a k by k diagonal matrix with nonzero diagonal elements, k being the rank of R, and Q* and P are p by p orthogonal matrices. This gives the solution
β^=P 1 D-1 Q*1 T c 1,
P 1 being the first k columns of P, i.e., P=P 1P 0, and Q*1 being the first k columns of Q*.
Details of the SVD, are made available, in the form of the matrix P*:
P*= D-1 P 1 T P 0 T .
This will be only one of the possible solutions. Other estimates may be obtained by applying constraints to the arguments. These solutions can be obtained by using G02DKF after using G02DAF. Only certain linear combinations of the arguments will have unique estimates; these are known as estimable functions.
The fit of the model can be examined by considering the residuals, ri=yi-y^, where y^=X β^ are the fitted values. The fitted values can be written as Hy for an n by n matrix H. The ith diagonal elements of H, hi, give a measure of the influence of the ith values of the independent variables on the fitted regression model. The values hi are sometimes known as leverages. Both ri and hi are provided by G02DAF.
The output of G02DAF also includes β^, the residual sum of squares and associated degrees of freedom, n-k, the standard errors of the parameter estimates and the variance-covariance matrix of the parameter estimates.
In many linear regression models the first term is taken as a mean term or an intercept, i.e., X i,1=1, for i=1,2,…,n. This is provided as an option. Also only some of the possible independent variables are required to be included in a model, a facility to select variables to be included in the model is provided.
Details of the QR decomposition and, if used, the SVD, are made available. These allow the regression to be updated by adding or deleting an observation using G02DCF, adding or deleting a variable using G02DEF and G02DFF or estimating and testing an estimable function using G02DNF.

4 References

Cook R D and Weisberg S (1982) Residuals and Influence in Regression Chapman and Hall
Draper N R and Smith H (1985) Applied Regression Analysis (2nd Edition) Wiley
Golub G H and Van Loan C F (1996) Matrix Computations (3rd Edition) Johns Hopkins University Press, Baltimore
Hammarling S (1985) The singular value decomposition in multivariate statistics SIGNUM Newsl. 20(3) 2–25
McCullagh P and Nelder J A (1983) Generalized Linear Models Chapman and Hall
Searle S R (1971) Linear Models Wiley

5 Arguments

1:   MEAN – CHARACTER(1)Input
On entry: indicates if a mean term is to be included.
MEAN='M'
A mean term, intercept, will be included in the model.
MEAN='Z'
The model will pass through the origin, zero-point.
Constraint: MEAN='M' or 'Z'.
2:   WEIGHT – CHARACTER(1)Input
On entry: indicates if weights are to be used.
WEIGHT='U'
Least squares estimation is used.
WEIGHT='W'
Weighted least squares is used and weights must be supplied in array WT.
Constraint: WEIGHT='U' or 'W'.
3:   N – INTEGERInput
On entry: n, the number of observations.
Constraint: N≥2.
4:   X LDXM – REAL (KIND=nag_wp) arrayInput
On entry: X ij must contain the ith observation for the jth independent variable, for i=1,2,…,N and j=1,2,…,M.
5:   LDX – INTEGERInput
On entry: the first dimension of the array X as declared in the (sub)program from which G02DAF is called.
Constraint: LDX≥N.
6:   M – INTEGERInput
On entry: m, the total number of independent variables in the dataset.
Constraint: M≥1.
7:   ISX M – INTEGER arrayInput
On entry: indicates which independent variables are to be included in the model.
ISX j>0
The variable contained in the jth column of X is included in the regression model.
Constraints:
  • ISX j≥0, for j=1,2,…,m;
  • if MEAN='M', exactly IP-1 values of ISX must be >0;
  • if MEAN='Z', exactly IP values of ISX must be >0.
8:   IP – INTEGERInput
On entry: the number of independent variables in the model, including the mean or intercept if present.
Constraints:
  • if MEAN='M', 1≤IP≤M+1;
  • if MEAN='Z', 1≤IP≤M;
  • otherwise 1≤IP≤N.
9:   Y N – REAL (KIND=nag_wp) arrayInput
On entry: y, the observations on the dependent variable.
10:   WT* – REAL (KIND=nag_wp) arrayInput
Note: the dimension of the array WT must be at least N if WEIGHT='W', and at least 1 otherwise.
On entry: if WEIGHT='W', WT must contain the weights to be used in the weighted regression.
If WT i=0.0, the ith observation is not included in the model, in which case the effective number of observations is the number of observations with nonzero weights. The values of RES and H will be set to zero for observations with zero weights.
If WEIGHT='U', WT is not referenced and the effective number of observations is n.
Constraint: if WEIGHT='W', WT i≥0.0, for i=1,2,…,n.
11:   RSS – REAL (KIND=nag_wp)Output
On exit: the residual sum of squares for the regression.
12:   IDF – INTEGEROutput
On exit: the degrees of freedom associated with the residual sum of squares.
13:   B IP – REAL (KIND=nag_wp) arrayOutput
On exit: B i, i=1,2,…,IP contains the least squares estimates of the parameters of the regression model, β^.
If MEAN='M', B 1 will contain the estimate of the mean parameter and B i+1 will contain the coefficient of the variable contained in column j of X, where ISX j is the ith positive value in the array ISX.
If MEAN='Z', B i will contain the coefficient of the variable contained in column j of X, where ISX j is the ith positive value in the array ISX.
14:   SE IP – REAL (KIND=nag_wp) arrayOutput
On exit: SE i, i=1,2,…,IP contains the standard errors of the IP parameter estimates given in B.
15:   COV IP×IP+1/2 – REAL (KIND=nag_wp) arrayOutput
On exit: the first IP×IP+1/2 elements of COV contain the upper triangular part of the variance-covariance matrix of the IP parameter estimates given in B. They are stored packed by column, i.e., the covariance between the parameter estimate given in B i and the parameter estimate given in B j, j≥i, is stored in COV j×j-1/2+i.
16:   RES N – REAL (KIND=nag_wp) arrayOutput
On exit: the (weighted) residuals, ri, for i=1,2,…,n.
17:   H N – REAL (KIND=nag_wp) arrayOutput
On exit: the diagonal elements of H, hi, for i=1,2,…,n.
18:   Q LDQ IP+1 – REAL (KIND=nag_wp) arrayOutput
On exit: the results of the QR decomposition:
  • the first column of Q contains c;
  • the upper triangular part of columns 2 to IP+1 contain the R matrix;
  • the strictly lower triangular part of columns 2 to IP+1 contain details of the Q matrix.
19:   LDQ – INTEGERInput
On entry: the first dimension of the array Q as declared in the (sub)program from which G02DAF is called.
Constraint: LDQ≥N.
20:   SVD – LOGICALOutput
On exit: if a singular value decomposition has been performed then SVD will be .TRUE., otherwise SVD will be .FALSE..
21:   IRANK – INTEGEROutput
On exit: the rank of the independent variables.
If SVD=.FALSE., IRANK=IP.
If SVD=.TRUE., IRANK is an estimate of the rank of the independent variables.
IRANK is calculated as the number of singular values greater that TOL× (largest singular value). It is possible for the SVD to be carried out but IRANK to be returned as IP.
22:   P 2×IP+IP×IP – REAL (KIND=nag_wp) arrayOutput
On exit: details of the QR decomposition and SVD if used.
If SVD=.FALSE., only the first IP elements of P are used these will contain the zeta values for the QR decomposition (see F08AEF (DGEQRF) for details).
If SVD=.TRUE., the first IP elements of P will contain the zeta values for the QR decomposition (see F08AEF (DGEQRF) for details) and the next IP elements of P contain singular values. The following IP by IP elements contain the matrix P* stored by columns.
23:   TOL – REAL (KIND=nag_wp)Input
On entry: the value of TOL is used to decide if the independent variables are of full rank and if not what is the rank of the independent variables. The smaller the value of TOL the stricter the criterion for selecting the singular value decomposition. If TOL=0.0, the singular value decomposition will never be used; this may cause run time errors or inaccurate results if the independent variables are not of full rank.
Suggested value: TOL=0.000001.
Constraint: TOL≥0.0.
24:   WK max 2,5×IP-1+IP×IP – REAL (KIND=nag_wp) arrayOutput
On exit: if on exit SVD=.TRUE., WK contains information which is needed by G02DGF; otherwise WK is used as workspace.
25:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, | N<2,
or | M<1,
or | LDX<N,
or | LDQ<N,
or | TOL<0.0,
or | IP≤0,
or | IP>N.
IFAIL=2
On entry, | MEAN≠'M' or 'Z',
or | WEIGHT≠'W' or 'U'.
IFAIL=3
On entry, WEIGHT='W' and a value of WT<0.0.
IFAIL=4
On entry, | a value of ISX<0,
or | the value of IP is incompatible with the values of MEAN and ISX,
or | IP is greater than the effective number of observations.
IFAIL=5
The degrees of freedom for the residuals are zero, i.e., the designated number of arguments is equal to the effective number of observations. In this case the parameter estimates will be returned along with the diagonal elements of H, but neither standard errors nor the variance-covariance matrix will be calculated.
IFAIL=6
The singular value decomposition has failed to converge, see F02WUF. This is an unlikely error.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

The accuracy of G02DAF is closely related to the accuracy of F02WUF and F08AEF (DGEQRF). These routine documents should be consulted.

8 Parallelism and Performance

G02DAF is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
G02DAF makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

Standardized residuals and further measures of influence can be computed using G02FAF. G02FAF requires, in particular, the results stored in RES and H.

10 Example

Data from an experiment with four treatments and three observations per treatment are read in. The treatments are represented by dummy (0-1) variables. An unweighted model is fitted with a mean included in the model. G02BUF is then called to calculate the total sums of squares and the coefficient of determination (R 2), adjusted R 2 and Akaike's information criteria (AIC) are calculated.
G02BUF is then called to calculate the total sums of squares and the coefficient of determination (R 2), adjusted R 2 and Akaike's information criteria (AIC) are calculated.

10.1 Program Text

Program Text (g02dafe.f90)

10.2 Program Data

Program Data (g02dafe.d)

10.3 Program Results

Program Results (g02dafe.r)

G02 Chapter Contents
G02 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


G02DCF : NAG Library, Mark 26

G02 Chapter Contents
G02 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

G02DCF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

G02DCF adds or deletes an observation from a general regression model fitted by G02DAF.

2 Specification

SUBROUTINE G02DCF ( UPDATE, MEAN, WEIGHT, M, ISX, Q, LDQ, IP, X, IX, Y, WT, RSS, WK, IFAIL)
INTEGER | M, ISX(M), LDQ, IP, IX, IFAIL
REAL (KIND=nag_wp) | Q(LDQ,IP+1), X(*), Y, WT, RSS, WK(3*IP)
CHARACTER(1) | UPDATE, MEAN, WEIGHT

3 Description

G02DAF fits a general linear regression model to a dataset. You may wish to change the model by either adding or deleting an observation from the dataset. G02DCF takes the results from G02DAF and makes the required changes to the vector c and the upper triangular matrix R produced by G02DAF. The regression coefficients, standard errors and the variance-covariance matrix of the regression coefficients can be obtained from G02DDF after all required changes to the dataset have been made.
G02DAF performs a QR decomposition on the (weighted) X matrix of independent variables. To add a new observation to a model with p arguments, the upper triangular matrix R and vector c 1 (the first p elements of c) are augmented by the new observation on independent variables in xT and dependent variable y new. Givens rotations are then used to restore the upper triangular form.
R:c 1 x:y new → R*:c 1* 0:y new* .
Note: only R and the upper part of c are updated the remainder of the Q matrix is unchanged.

4 References

Golub G H and Van Loan C F (1996) Matrix Computations (3rd Edition) Johns Hopkins University Press, Baltimore
Hammarling S (1985) The singular value decomposition in multivariate statistics SIGNUM Newsl. 20(3) 2–25

5 Arguments

1:   UPDATE – CHARACTER(1)Input
On entry: indicates if an observation is to be added or deleted.
UPDATE='A'
The observation is added.
UPDATE='D'
The observation is deleted.
Constraint: UPDATE='A' or 'D'.
2:   MEAN – CHARACTER(1)Input
On entry: indicates if a mean has been used in the model.
MEAN='M'
A mean term or intercept will have been included in the model by G02DAF.
MEAN='Z'
A model with no mean term or intercept will have been fitted by G02DAF.
Constraint: MEAN='M' or 'Z'.
3:   WEIGHT – CHARACTER(1)Input
On entry: indicates if a weight is to be used.
WEIGHT='U'
The new observation is unweighted.
WEIGHT='W'
The new observation is to be weighted and the weight must be supplied in WT.
Constraint: WEIGHT='U' or 'W'.
4:   M – INTEGERInput
On entry: m, the total number of independent variables in the dataset.
Constraint: M≥1.
5:   ISX M – INTEGER arrayInput
On entry: if ISX j is greater than 0, the value contained in X j-1×IX+1 is to be included as a value of xT, for j=1,2,…,M.
Constraint: if MEAN='M', exactly IP-1 elements of ISX must be >0 and if MEAN='Z', exactly IP elements of ISX must be >0.
6:   Q LDQ IP+1 – REAL (KIND=nag_wp) arrayInput/Output
On entry: must be array Q as output by G02DAF, G02DEF, G02DFF or G02EEF, or a previous call to G02DCF.
On exit: the first IP elements of the first column of Q will contain c 1* the upper triangular part of columns 2 to IP+1 will contain R* the remainder is unchanged.
7:   LDQ – INTEGERInput
On entry: the first dimension of the array Q as declared in the (sub)program from which G02DCF is called.
Constraint: LDQ≥IP.
8:   IP – INTEGERInput
On entry: the number of linear terms in general linear regression model (including mean if there is one).
Constraint: IP≥1.
9:   X* – REAL (KIND=nag_wp) arrayInput
Note: the dimension of the array X must be at least M-1×IX+1 .
On entry: the IP values for the dependent variables of the new observation, xT. The positions will depend on the value of IX.
10:   IX – INTEGERInput
On entry: the increment for elements of X. Two situations are common:
IX=1
The values of x are to be chosen from consecutive locations in X, i.e., X 1,X 2,…,X M.
IX=LDX
The values of x are to be chosen from a row of a two-dimensional array with first dimension LDX, i.e., X 1,X LDX+1,…,X M-1 LDX+1.
Constraint: IX≥1.
11:   Y – REAL (KIND=nag_wp)Input
On entry: the value of the dependent variable for the new observation, y new.
12:   WT – REAL (KIND=nag_wp)Input
On entry: if WEIGHT='W', WT must contain the weight to be used with the new observation.
If WT=0.0, the observation is not included in the model.
If WEIGHT='U', WT is not referenced.
Constraint: if WT≥0.0, WEIGHT='W'.
13:   RSS – REAL (KIND=nag_wp)Input/Output
On entry: the value of the residual sums of squares for the original set of observations.
Constraint: RSS≥0.0.
On exit: the updated values of the residual sums of squares.
Note: this will only be valid if the model is of full rank.
14:   WK 3×IP – REAL (KIND=nag_wp) arrayWorkspace
15:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, | IP<1,
or | LDQ<IP,
or | M<1,
or | IX<1,
or | RSS<0.0,
or | UPDATE≠'A' or 'D',
or | MEAN≠'M' or 'Z',
or | WEIGHT≠'U' or 'W',
or | MEAN='M' and there are not exactly IP-1 nonzero values of ISX,
or | MEAN='Z' and there are not exactly IP nonzero values of ISX,
IFAIL=2
On entry, WEIGHT='W' and WT<0.0.
IFAIL=3
The R matrix could not be updated. This may occur if an attempt is made to delete an observation which was not in the original dataset or to add an observation to a R matrix with a zero diagonal element. This error is also possible when removing an observation which reduces the rank of design matrix. In such cases the model should be recomputed using G02DAF.
IFAIL=4
The residual sums of squares cannot be updated. This will occur if the input residual sum of squares is less than the calculated decrease in residual sum of squares when the new observation is deleted.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

Higher accuracy is achieved by updating the R matrix rather than the traditional methods of updating X′X.

8 Parallelism and Performance

G02DCF makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

Care should be taken with the use of G02DCF.
(a) | It is possible to delete observations which were not included in the original model.
(b) | If several additions/deletions have been performed you are advised to recompute the regression using G02DAF.
(c) | Adding or deleting observations can alter the rank of the model. Such changes will only be detected when a call to G02DDF has been made. G02DDF should also be used to compute the new residual sum of squares when the model is not of full rank.
G02DCF may also be used after G02DEF, G02DFF and G02EEF.

10 Example

A dataset consisting of 12 observations with four independent variables is read in and a general linear regression model fitted by G02DAF and parameter estimates printed. The last observation is then dropped and the parameter estimates recalculated, using G02DDF, and printed. Finally a new observation is added and new parameter estimates computed and printed.

10.1 Program Text

Program Text (g02dcfe.f90)

10.2 Program Data

Program Data (g02dcfe.d)

10.3 Program Results

Program Results (g02dcfe.r)

G02 Chapter Contents
G02 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


G02DDF : NAG Library, Mark 26

G02 Chapter Contents
G02 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

G02DDF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

G02DDF calculates the regression arguments for a general linear regression model. It is intended to be called after G02DCF, G02DEF or G02DFF.

2 Specification

SUBROUTINE G02DDF ( N, IP, Q, LDQ, RSS, IDF, B, SE, COV, SVD, IRANK, P, TOL, WK, IFAIL)
INTEGER | N, IP, LDQ, IDF, IRANK, IFAIL
REAL (KIND=nag_wp) | Q(LDQ,IP+1), RSS, B(IP), SE(IP), COV(IP*(IP+1)/2), P(IP*IP+2*IP), TOL, WK(IP*IP+(IP-1)*5)
LOGICAL | SVD

3 Description

A general linear regression model fitted by G02DAF may be adjusted by adding or deleting an observation using G02DCF, adding a new independent variable using G02DEF or deleting an existing independent variable using G02DFF. Alternatively a model may be constructed by a forward selection procedure using G02EEF. These routines compute the vector c and the upper triangular matrix R. G02DDF takes these basic results and computes the regression coefficients, β^, their standard errors and their variance-covariance matrix.
If R is of full rank, then β^ is the solution to
R β^=c 1,
where c 1 is the first p elements of c.
If R is not of full rank a solution is obtained by means of a singular value decomposition (SVD) of R,
R=Q* D 0 0 0 PT,
where D is a k by k diagonal matrix with nonzero diagonal elements, k being the rank of R, and Q* and P are p by p orthogonal matrices. This gives the solution
β^=P 1 D-1 Q*1 T c 1.
P 1 being the first k columns of P, i.e., P=P 1P 0, and Q*1 being the first k columns of Q*.
Details of the SVD are made available in the form of the matrix P*:
P*= D-1 P 1 T P 0 T .
This will be only one of the possible solutions. Other estimates may be obtained by applying constraints to the arguments. These solutions can be obtained by calling G02DKF after calling G02DDF. Only certain linear combinations of the arguments will have unique estimates; these are known as estimable functions. These can be estimated using G02DNF.
The residual sum of squares required to calculate the standard errors and the variance-covariance matrix can either be input or can be calculated if additional information on c for the whole sample is provided.

4 References

Golub G H and Van Loan C F (1996) Matrix Computations (3rd Edition) Johns Hopkins University Press, Baltimore
Hammarling S (1985) The singular value decomposition in multivariate statistics SIGNUM Newsl. 20(3) 2–25
Searle S R (1971) Linear Models Wiley

5 Arguments

1:   N – INTEGERInput
On entry: the number of observations.
Constraint: N≥1.
2:   IP – INTEGERInput
On entry: p, the number of terms in the regression model.
Constraint: IP≥1.
3:   Q LDQ IP+1 – REAL (KIND=nag_wp) arrayInput
On entry: must be the array Q as output by G02DCF, G02DEF, G02DFF or G02EEF. If on entry RSS≤0.0 then all N elements of c are needed. This is provided by routines G02DEF, G02DFF or G02EEF.
4:   LDQ – INTEGERInput
On entry: the first dimension of the array Q as declared in the (sub)program from which G02DDF is called.
Constraints:
  • if RSS≤0.0, LDQ≥N;
  • otherwise LDQ≥IP.
5:   RSS – REAL (KIND=nag_wp)Input/Output
On entry: either the residual sum of squares or a value less than or equal to 0.0 to indicate that the residual sum of squares is to be calculated by the routine.
On exit: if RSS≤0.0 on entry, then on exit RSS will contain the residual sum of squares as calculated by G02DDF.
If RSS was positive on entry, it will be unchanged.
6:   IDF – INTEGEROutput
On exit: the degrees of freedom associated with the residual sum of squares.
7:   B IP – REAL (KIND=nag_wp) arrayOutput
On exit: the estimates of the p parameters, β^.
8:   SE IP – REAL (KIND=nag_wp) arrayOutput
On exit: the standard errors of the p parameters given in B.
9:   COV IP×IP+1/2 – REAL (KIND=nag_wp) arrayOutput
On exit: the upper triangular part of the variance-covariance matrix of the p parameter estimates given in B. They are stored packed by column, i.e., the covariance between the parameter estimate given in B i and the parameter estimate given in B j, j≥i, is stored in COV j×j-1/2+i.
10:   SVD – LOGICALOutput
On exit: if a singular value decomposition has been performed, SVD=.TRUE., otherwise SVD=.FALSE..
11:   IRANK – INTEGEROutput
On exit: the rank of the independent variables.
If SVD=.FALSE., IRANK=IP.
If SVD=.TRUE., IRANK is an estimate of the rank of the independent variables.
IRANK is calculated as the number of singular values greater than TOL× (largest singular value). It is possible for the SVD to be carried out but IRANK to be returned as IP.
12:   P IP×IP+2×IP – REAL (KIND=nag_wp) arrayOutput
On exit: contains details of the singular value decomposition if used.
If SVD=.FALSE., P is not referenced.
If SVD=.TRUE., the first IP elements of P will not be referenced, the next IP values contain the singular values. The following IP×IP values contain the matrix P* stored by columns.
13:   TOL – REAL (KIND=nag_wp)Input
On entry: the value of TOL is used to decide if the independent variables are of full rank and, if not, what is the rank of the independent variables. The smaller the value of TOL the stricter the criterion for selecting the singular value decomposition. If TOL=0.0, the singular value decomposition will never be used, this may cause run time errors or inaccuracies if the independent variables are not of full rank.
Suggested value: TOL=0.000001.
Constraint: TOL≥0.0.
14:   WK IP×IP+IP-1×5 – REAL (KIND=nag_wp) arrayWorkspace
15:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, | N<1,
or | IP<1,
or | LDQ<IP,
or | LDQ<N,
or | TOL<0.0.
IFAIL=2
The degrees of freedom for error are less than or equal to 0. In this case the estimates of β are returned but not the standard errors or covariances.
IFAIL=3
The singular value decomposition, if used, has failed to converge, see F02WUF. This is an unlikely error exit.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

The accuracy of the results will depend on the accuracy of the input R matrix, which may lose accuracy if a large number of observations or variables have been dropped.

8 Parallelism and Performance

G02DDF is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
G02DDF makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

None.

10 Example

A dataset consisting of 12 observations and four independent variables is input and a regression model fitted by calls to G02DEF. The arguments are then calculated by G02DDF and the results printed.

10.1 Program Text

Program Text (g02ddfe.f90)

10.2 Program Data

Program Data (g02ddfe.d)

10.3 Program Results

Program Results (g02ddfe.r)

G02 Chapter Contents
G02 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


G02DEF : NAG Library, Mark 26

G02 Chapter Contents
G02 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

G02DEF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

G02DEF adds a new independent variable to a general linear regression model.

2 Specification

SUBROUTINE G02DEF ( WEIGHT, N, IP, Q, LDQ, P, WT, X, RSS, TOL, IFAIL)
INTEGER | N, IP, LDQ, IFAIL
REAL (KIND=nag_wp) | Q(LDQ,IP+2), P(IP+1), WT(*), X(N), RSS, TOL
CHARACTER(1) | WEIGHT

3 Description

A linear regression model may be built up by adding new independent variables to an existing model. G02DEF updates the QR decomposition used in the computation of the linear regression model. The QR decomposition may come from G02DAF or a previous call to G02DEF. The general linear regression model is defined by
y=Xβ+ε,
where | y is a vector of n observations on the dependent variable,
 | X is an n by p matrix of the independent variables of column rank k,
 | β is a vector of length p of unknown arguments,
and | ε is a vector of length n of unknown random errors such that var⁡ε=V σ 2, where V is a known diagonal matrix.
If V=I, the identity matrix, then least squares estimation is used. If V≠I, then for a given weight matrix W∝V-1, weighted least squares estimation is used.
The least squares estimates, β^ of the arguments β minimize y-Xβ T y-Xβ while the weighted least squares estimates, minimize y-Xβ T W y-Xβ .
The parameter estimates may be found by computing a QR decomposition of X (or W 12 X in the weighted case), i.e.,
X=Q R* or  W 12 X=Q R*,
where R*= R 0 and R is a p by p upper triangular matrix and Q is an n by n orthogonal matrix.
If R is of full rank, then β^ is the solution to
R β^=c 1,
where c=QT y (or QTW 12 y) and c 1 is the first p elements of c.
If R is not of full rank a solution is obtained by means of a singular value decomposition (SVD) of R.
To add a new independent variable, x p+1, R and c have to be updated. The matrix Q p+1 is found such that Q p+1 T R:QT x p+1 (or Q p+1 T R:QTW 12 x p+1) is upper triangular. The vector c is then updated by multiplying by Q p+1 T .
The new independent variable is tested to see if it is linearly related to the existing independent variables by checking that at least one of the values QT x p+1 i, for i=p+2,…,n, is nonzero.
The new parameter estimates, β^, can then be obtained by a call to G02DDF.
The routine can be used with p=0, in which case R and c are initialized.

4 References

Draper N R and Smith H (1985) Applied Regression Analysis (2nd Edition) Wiley
Golub G H and Van Loan C F (1996) Matrix Computations (3rd Edition) Johns Hopkins University Press, Baltimore
Hammarling S (1985) The singular value decomposition in multivariate statistics SIGNUM Newsl. 20(3) 2–25
McCullagh P and Nelder J A (1983) Generalized Linear Models Chapman and Hall
Searle S R (1971) Linear Models Wiley

5 Arguments

1:   WEIGHT – CHARACTER(1)Input
On entry: indicates if weights are to be used.
WEIGHT='U'
Least squares estimation is used.
WEIGHT='W'
Weighted least squares is used and weights must be supplied in array WT.
Constraint: WEIGHT='U' or 'W'.
2:   N – INTEGERInput
On entry: n, the number of observations.
Constraint: N≥1.
3:   IP – INTEGERInput
On entry: p, the number of independent variables already in the model.
Constraint: IP≥0 and IP<N.
4:   Q LDQ IP+2 – REAL (KIND=nag_wp) arrayInput/Output
On entry: if IP≠0, Q must contain the results of the QR decomposition for the model with p arguments as returned by G02DAF or a previous call to G02DEF.
If IP=0, the first column of Q should contain the n values of the dependent variable, y.
On exit: the results of the QR decomposition for the model with p+1 arguments:
  • the first column of Q contains the updated value of c;
  • the columns 2 to IP+1 are unchanged;
  • the first IP+1 elements of column IP+2 contain the new column of R, while the remaining N-IP-1 elements contain details of the matrix Q p+1.
5:   LDQ – INTEGERInput
On entry: the first dimension of the array Q as declared in the (sub)program from which G02DEF is called.
Constraint: LDQ≥N.
6:   P IP+1 – REAL (KIND=nag_wp) arrayInput/Output
On entry: contains further details of the QR decomposition used. The first IP elements of P must contain the zeta values for the QR decomposition (see F08AEF (DGEQRF) for details).
The first IP elements of array P are provided by G02DAF or by previous calls to G02DEF.
On exit: the first IP elements of P are unchanged and the IP+1th element contains the zeta value for Q p+1.
7:   WT* – REAL (KIND=nag_wp) arrayInput
Note: the dimension of the array WT must be at least N if WEIGHT='W', and at least 1 otherwise.
On entry: if WEIGHT='W' , WT must contain the weights to be used.
If WT i=0.0, the ith observation is not included in the model, in which case the effective number of observations is the number of observations with nonzero weights.
If WEIGHT='U', WT is not referenced and the effective number of observations is n.
Constraint: if WEIGHT='W', WT i≥0.0, for i=1,2,…,n.
8:   X N – REAL (KIND=nag_wp) arrayInput
On entry: x, the new independent variable.
9:   RSS – REAL (KIND=nag_wp)Output
On exit: the residual sum of squares for the new fitted model.
Note: this will only be valid if the model is of full rank, see Section 9.
10:   TOL – REAL (KIND=nag_wp)Input
On entry: the value of TOL is used to decide if the new independent variable is linearly related to independent variables already included in the model. If the new variable is linearly related then c is not updated. The smaller the value of TOL the stricter the criterion for deciding if there is a linear relationship.
Suggested value: TOL=0.000001.
Constraint: TOL>0.0.
11:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, because for this routine the values of the output arguments may be useful even if IFAIL≠0 on exit, the recommended value is -1. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Note: G02DEF may return useful information for one or more of the following detected errors or warnings.
Errors or warnings detected by the routine:
IFAIL=1
On entry, | N<1,
or | IP<0,
or | IP≥N,
or | LDQ<N,
or | TOL≤0.0,
or | WEIGHT≠'U' or 'W'.
IFAIL=2
On entry, WEIGHT='W' and a value of WT<0.0.
IFAIL=3
The new independent variable is a linear combination of existing variables. The IP+2th column of Q will therefore be null.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

The accuracy is closely related to the accuracy of F08AGF (DORMQR) which should be consulted for further details.

8 Parallelism and Performance

G02DEF is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
G02DEF makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

It should be noted that the residual sum of squares produced by G02DEF may not be correct if the model to which the new independent variable is added is not of full rank. In such a case G02DDF should be used to calculate the residual sum of squares.

10 Example

A dataset consisting of 12 observations is read in. The four independent variables are stored in the array X while the dependent variable is read into the first column of Q. If the character variable mean indicates that a mean should be included in the model a variable taking the value 1.0 for all observations is set up and fitted. Subsequently, one variable at a time is selected to enter the model as indicated by the input value of indx. After the variable has been added the parameter estimates are calculated by G02DDF and the results printed. This is repeated until the input value of indx is 0.

10.1 Program Text

Program Text (g02defe.f90)

10.2 Program Data

Program Data (g02defe.d)

10.3 Program Results

Program Results (g02defe.r)

G02 Chapter Contents
G02 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


G02DFF : NAG Library, Mark 26

G02 Chapter Contents
G02 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

G02DFF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

G02DFF deletes an independent variable from a general linear regression model.

2 Specification

SUBROUTINE G02DFF ( IP, Q, LDQ, INDX, RSS, WK, IFAIL)
INTEGER | IP, LDQ, INDX, IFAIL
REAL (KIND=nag_wp) | Q(LDQ,IP+1), RSS, WK(2*IP)

3 Description

When selecting a linear regression model it is sometimes useful to drop independent variables from the model and to examine the resulting sub-model. G02DFF updates the QR decomposition used in the computation of the linear regression model. The QR decomposition may come from G02DAF or G02DEF, or a previous call to G02DFF.
For the general linear regression model with p independent variables fitted G02DAF or G02DEF compute a QR decomposition of the (weighted) independent variables and form an upper triangular matrix R and a vector c. To remove an independent variable R and c have to be updated. The column of R corresponding to the variable to be dropped is removed and the matrix is then restored to upper triangular form by applying a series of Givens rotations. The rotations are then applied to c. Note only the first p elements of c are affected.
The method used means that while the updated values of R and c are computed an updated value of Q from the QR decomposition is not available so a call to G02DEF cannot be made after a call to G02DFF.
G02DDF can be used to calculate the parameter estimates, β^, from the information provided by G02DFF.

4 References

Golub G H and Van Loan C F (1996) Matrix Computations (3rd Edition) Johns Hopkins University Press, Baltimore
Hammarling S (1985) The singular value decomposition in multivariate statistics SIGNUM Newsl. 20(3) 2–25

5 Arguments

1:   IP – INTEGERInput
On entry: p, the number of independent variables already in the model.
Constraint: IP≥1.
2:   Q LDQ IP+1 – REAL (KIND=nag_wp) arrayInput/Output
On entry: the results of the QR decomposition as returned by routines G02DAF, G02DCF, G02DEF or G02EEF, or previous calls to G02DFF.
On exit: the updated QR decomposition.
3:   LDQ – INTEGERInput
On entry: the first dimension of the array Q as declared in the (sub)program from which G02DFF is called.
Constraint: LDQ≥IP.
4:   INDX – INTEGERInput
On entry: indicates which independent variable is to be deleted from the model.
Constraint: 1≤INDX≤IP.
5:   RSS – REAL (KIND=nag_wp)Input/Output
On entry: the residual sum of squares for the full regression.
Constraint: RSS≥0.0.
On exit: the residual sum of squares with the (INDX)th variable removed. Note that the residual sum of squares will only be valid if the regression is of full rank, otherwise the residual sum of squares should be obtained using G02DDF.
6:   WK 2×IP – REAL (KIND=nag_wp) arrayWorkspace
7:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, | IP<1,
or | LDQ<IP,
or | INDX<1,
or | INDX>IP,
or | RSS<0.0.
IFAIL=2
On entry, a diagonal element of R is zero.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

There will inevitably be some loss in accuracy in fitting a model by dropping terms from a more complex model rather than fitting it afresh using G02DAF.

8 Parallelism and Performance

G02DFF makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

None.

10 Example

A dataset consisting of 12 observations on four independent variables and one dependent variable is read in. The full model, including a mean term, is fitted using G02DAF. The value of INDX is read in and that variable dropped from the regression. The parameter estimates are calculated by G02DDF and printed. This process is repeated until INDX is 0.

10.1 Program Text

Program Text (g02dffe.f90)

10.2 Program Data

Program Data (g02dffe.d)

10.3 Program Results

Program Results (g02dffe.r)

G02 Chapter Contents
G02 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


G02DGF : NAG Library, Mark 26

G02 Chapter Contents
G02 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

G02DGF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

G02DGF calculates the estimates of the arguments of a general linear regression model for a new dependent variable after a call to G02DAF.

2 Specification

SUBROUTINE G02DGF ( WEIGHT, N, WT, RSS, IP, IRANK, COV, Q, LDQ, SVD, P, Y, B, SE, RES, WK, IFAIL)
INTEGER | N, IP, IRANK, LDQ, IFAIL
REAL (KIND=nag_wp) | WT(*), RSS, COV(IP*(IP+1)/2), Q(LDQ,IP+1), P(*), Y(N), B(IP), SE(IP), RES(N), WK(5*(IP-1)+IP*IP)
LOGICAL | SVD
CHARACTER(1) | WEIGHT

3 Description

G02DGF uses the results given by G02DAF to fit the same set of independent variables to a new dependent variable.
G02DAF computes a QR decomposition of the matrix of p independent variables and also, if the model is not of full rank, a singular value decomposition (SVD). These results can be used to compute estimates of the arguments for a general linear model with a new dependent variable. The QR decomposition leads to the formation of an upper triangular p by p matrix R and an n by n orthogonal matrix Q. In addition the vector c=QT y (or QTW 1/2 y) is computed. For a new dependent variable, ynew, G02DGF computes a new value of c=QT y new or QTW 1/2 y new.
If R is of full rank, then the least squares parameter estimates, β^, are the solution to
R β^=c 1,
where c 1 is the first p elements of c.
If R is not of full rank, then G02DAF will have computed an SVD of R,
R=Q* D 0 0 0 PT,
where D is a k by k diagonal matrix with nonzero diagonal elements, k being the rank of R, and Q* and P are p by p orthogonal matrices. This gives the solution
β^=P 1 D-1 Q*1 T c 1,
P 1 being the first k columns of P, i.e., P=P 1P 0, and Q*1 being the first k columns of Q*. Details of the SVD are made available by G02DAF in the form of the matrix P*:
P*= D-1 P 1 T P 0 T .
The matrix Q* is made available through the workspace of G02DAF.
In addition to parameter estimates, the new residuals are computed and the variance-covariance matrix of the parameter estimates are found by scaling the variance-covariance matrix for the original regression.

4 References

Golub G H and Van Loan C F (1996) Matrix Computations (3rd Edition) Johns Hopkins University Press, Baltimore
Hammarling S (1985) The singular value decomposition in multivariate statistics SIGNUM Newsl. 20(3) 2–25
Searle S R (1971) Linear Models Wiley

5 Arguments

1:   WEIGHT – CHARACTER(1)Input
On entry: indicates if weights are to be used.
WEIGHT='U'
Least squares estimation is used.
WEIGHT='W'
Weighted least squares is used and weights must be supplied in array WT.
Constraint: WEIGHT='U' or 'W'.
2:   N – INTEGERInput
On entry: n, the number of observations.
Constraint: N≥IP.
3:   WT* – REAL (KIND=nag_wp) arrayInput
Note: the dimension of the array WT must be at least N if WEIGHT='W', and at least 1 otherwise.
On entry: if WEIGHT='W' >, WT must contain the weights to be used in the weighted regression.
If WT i=0.0, the ith observation is not included in the model, in which case the effective number of observations is the number of observations with nonzero weights.
If WEIGHT='U', WT is not referenced and the effective number of observations is n.
Constraint: if WEIGHT='W', WT i≥0.0, for i=1,2,…,n.
4:   RSS – REAL (KIND=nag_wp)Input/Output
On entry: the residual sum of squares for the original dependent variable.
On exit: the residual sum of squares for the new dependent variable.
Constraint: RSS>0.0.
5:   IP – INTEGERInput
On entry: p, the number of independent variables (including the mean if fitted).
Constraint: 1≤IP≤N.
6:   IRANK – INTEGERInput
On entry: the rank of the independent variables, as given by G02DAF.
Constraint: IRANK>0, and if SVD=.FALSE., then IRANK=IP, else IRANK≤IP.
7:   COV IP×IP+1/2 – REAL (KIND=nag_wp) arrayInput/Output
On entry: the covariance matrix of the parameter estimates as given by G02DAF.
On exit: the upper triangular part of the variance-covariance matrix of the IP parameter estimates given in B. They are stored packed by column, i.e., the covariance between the parameter estimate given in B i and the parameter estimate given in B j, j≥i, is stored in COV j×j-1/2+i.
8:   Q LDQ IP+1 – REAL (KIND=nag_wp) arrayInput/Output
On entry: the results of the QR decomposition as returned by G02DAF.
On exit: the first column of Q contains the new values of c, the remainder of Q will be unchanged.
9:   LDQ – INTEGERInput
On entry: the first dimension of the array Q as declared in the (sub)program from which G02DGF is called.
Constraint: LDQ≥N.
10:   SVD – LOGICALInput
On entry: indicates if a singular value decomposition was used by G02DAF.
SVD=.TRUE.
A singular value decomposition was used by G02DAF.
SVD=.FALSE.
A singular value decomposition was not used by G02DAF.
11:   P* – REAL (KIND=nag_wp) arrayInput
Note: the dimension of the array P must be at least IP if SVD=.FALSE., and at least IP×IP+2×IP otherwise.
On entry: details of the QR decomposition and SVD, if used, as returned in array P by G02DAF.
If SVD=.FALSE., only the first IP elements of P are used; these contain the zeta values for the QR decomposition (see F08AEF (DGEQRF) for details).
If SVD=.TRUE., the first IP elements of P contain the zeta values for the QR decomposition (see F08AEF (DGEQRF) for details) and the next IP×IP+IP elements of P contain details of the singular value decomposition.
12:   Y N – REAL (KIND=nag_wp) arrayInput
On entry: the new dependent variable, y new.
13:   B IP – REAL (KIND=nag_wp) arrayOutput
On exit: the least squares estimates of the parameters of the regression model, β^.
14:   SE IP – REAL (KIND=nag_wp) arrayOutput
On exit: the standard error of the estimates of the parameters.
15:   RES N – REAL (KIND=nag_wp) arrayOutput
On exit: the residuals for the new regression model.
16:   WK 5×IP-1+IP×IP – REAL (KIND=nag_wp) arrayInput
On entry: if SVD=.TRUE., WK must be unaltered from the previous call to G02DAF or G02DGF.
If SVD=.FALSE., WK is used as workspace.
17:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, | IP<1,
or | N<IP,
or | IRANK≤0,
or | SVD=.FALSE. and IRANK≠IP,
or | SVD=.TRUE. and IRANK>IP,
or | LDQ<N,
or | RSS≤0.0,
or | WEIGHT≠'U' or 'W'.
IFAIL=2
On entry, WEIGHT='W' and a value of WT<0.0.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

The same accuracy as G02DAF is obtained.

8 Parallelism and Performance

G02DGF is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
G02DGF makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The values of the leverages, hi, are unaltered by a change in the dependent variable so a call to G02FAF can be made using the value of H from G02DAF.

10 Example

A dataset consisting of 12 observations with four independent variables and two dependent variables are read in. A model with all four independent variables is fitted to the first dependent variable by G02DAF and the results printed. The model is then fitted to the second dependent variable by G02DGF and those results printed.

10.1 Program Text

Program Text (g02dgfe.f90)

10.2 Program Data

Program Data (g02dgfe.d)

10.3 Program Results

Program Results (g02dgfe.r)

G02 Chapter Contents
G02 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


G02DKF : NAG Library, Mark 26

G02 Chapter Contents
G02 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

G02DKF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

G02DKF calculates the estimates of the arguments of a general linear regression model for given constraints from the singular value decomposition results.

2 Specification

SUBROUTINE G02DKF ( IP, ICONST, P, C, LDC, B, RSS, IDF, SE, COV, WK, IFAIL)
INTEGER | IP, ICONST, LDC, IDF, IFAIL
REAL (KIND=nag_wp) | P(IP*IP+2*IP), C(LDC,ICONST), B(IP), RSS, SE(IP), COV(IP*(IP+1)/2), WK(2*IP*IP+IP*ICONST+2*ICONST*ICONST+4*ICONST)

3 Description

G02DKF computes the estimates given a set of linear constraints for a general linear regression model which is not of full rank. It is intended for use after a call to G02DAF or G02DDF.
In the case of a model not of full rank the routines use a singular value decomposition (SVD) to find the parameter estimates, β^svd, and their variance-covariance matrix. Details of the SVD are made available in the form of the matrix P*:
P*= D-1 P 1 T P 0 T ,
as described by G02DAF and G02DDF.
Alternative solutions can be formed by imposing constraints on the arguments. If there are p arguments and the rank of the model is k, then nc=p-k constraints will have to be imposed to obtain a unique solution.
Let C be a p by nc matrix of constraints, such that
CT β=0
then the new parameter estimates β^c are given by
β^c =A β^svd; =I-P 0 CT P 0-1 β^svd,
where I is the identity matrix, and the variance-covariance matrix is given by
A P 1 D-2 P 1 T AT,
provided CT P 0-1 exists.

4 References

Golub G H and Van Loan C F (1996) Matrix Computations (3rd Edition) Johns Hopkins University Press, Baltimore
Hammarling S (1985) The singular value decomposition in multivariate statistics SIGNUM Newsl. 20(3) 2–25
Searle S R (1971) Linear Models Wiley

5 Arguments

1:   IP – INTEGERInput
On entry: p, the number of terms in the linear model.
Constraint: IP≥1.
2:   ICONST – INTEGERInput
On entry: the number of constraints to be imposed on the arguments, nc.
Constraint: 0<ICONST<IP.
3:   P IP×IP+2×IP – REAL (KIND=nag_wp) arrayInput
On entry: as returned by G02DAF and G02DDF.
4:   C LDCICONST – REAL (KIND=nag_wp) arrayInput
On entry: the ICONST constraints stored by column, i.e., the ith constraint is stored in the ith column of C.
5:   LDC – INTEGERInput
On entry: the first dimension of the array C as declared in the (sub)program from which G02DKF is called.
Constraint: LDC≥IP.
6:   B IP – REAL (KIND=nag_wp) arrayInput/Output
On entry: the parameter estimates computed by using the singular value decomposition, β^svd.
On exit: the parameter estimates of the arguments with the constraints imposed, β^c.
7:   RSS – REAL (KIND=nag_wp)Input
On entry: the residual sum of squares as returned by G02DAF or G02DDF.
Constraint: RSS>0.0.
8:   IDF – INTEGERInput
On entry: the degrees of freedom associated with the residual sum of squares as returned by G02DAF or G02DDF.
Constraint: IDF>0.
9:   SE IP – REAL (KIND=nag_wp) arrayOutput
On exit: the standard error of the parameter estimates in B.
10:   COV IP×IP+1/2 – REAL (KIND=nag_wp) arrayOutput
On exit: the upper triangular part of the variance-covariance matrix of the IP parameter estimates given in B. They are stored packed by column, i.e., the covariance between the parameter estimate given in B i and the parameter estimate given in B j, j≥i, is stored in COV j×j-1/2+i.
11:   WK 2×IP×IP+IP×ICONST+2×ICONST×ICONST+4×ICONST – REAL (KIND=nag_wp) arrayWorkspace
Note that a simple upper bound for the size of the workspace is 5×IP×IP.
12:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, | IP<1,
or | ICONST≤0,
or | ICONST≥IP,
or | LDC<IP,
or | RSS≤0.0,
or | IDF≤0.
IFAIL=2
C does not give a model of full rank.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

It should be noted that due to rounding errors an argument that should be zero when the constraints have been imposed may be returned as a value of order machine precision.

8 Parallelism and Performance

G02DKF is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
G02DKF makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

G02DKF is intended for use in situations in which dummy (0–1) variables have been used such as in the analysis of designed experiments when you do not wish to change the arguments of the model to give a full rank model. The routine is not intended for situations in which the relationships between the independent variables are only approximate.

10 Example

Data from an experiment with four treatments and three observations per treatment are read in. A model, including the mean term, is fitted by G02DAF and the results printed. The constraint that the sum of treatment effect is zero is then read in and the parameter estimates with this constraint imposed are computed by G02DKF and printed.

10.1 Program Text

Program Text (g02dkfe.f90)

10.2 Program Data

Program Data (g02dkfe.d)

10.3 Program Results

Program Results (g02dkfe.r)

G02 Chapter Contents
G02 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


G02DNF : NAG Library, Mark 26

G02 Chapter Contents
G02 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

G02DNF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

G02DNF gives the estimate of an estimable function along with its standard error.

2 Specification

SUBROUTINE G02DNF ( IP, IRANK, B, COV, P, F, EST, STAT, SESTAT, T, TOL, WK, IFAIL)
INTEGER | IP, IRANK, IFAIL
REAL (KIND=nag_wp) | B(IP), COV(IP*(IP+1)/2), P(IP*IP+2*IP), F(IP), STAT, SESTAT, T, TOL, WK(IP)
LOGICAL | EST

3 Description

G02DNF computes the estimates of an estimable function for a general linear regression model which is not of full rank. It is intended for use after a call to G02DAF or G02DDF. An estimable function is a linear combination of the arguments such that it has a unique estimate. For a full rank model all linear combinations of arguments are estimable.
In the case of a model not of full rank the routines use a singular value decomposition (SVD) to find the parameter estimates, β^, and their variance-covariance matrix. Given the upper triangular matrix R obtained from the QR decomposition of the independent variables the SVD gives
R=Q* D 0 0 0 PT,
where D is a k by k diagonal matrix with nonzero diagonal elements, k being the rank of R, and Q* and P are p by p orthogonal matrices. This gives the solution
β^=P 1 D-1 Q*1 T c 1,
P 1 being the first k columns of P, i.e., P=P 1P 0, Q*1 being the first k columns of Q*, and c 1 being the first p elements of c.
Details of the SVD are made available in the form of the matrix P*:
P*= D-1 P 1 T P 0 T ,
as given by G02DAF and G02DDF.
A linear function of the arguments, F=fT β, can be tested to see if it is estimable by computing ζ= P 0 T f. If ζ is zero, then the function is estimable; if not, the function is not estimable. In practice ζ is tested against some small quantity η.
Given that F is estimable it can be estimated by fT β^ and its standard error calculated from the variance-covariance matrix of β^, Cβ, as
se F=fT Cβ f.
Also a t-statistic,
t=fT β^ se F ,
can be computed. The t-statistic will have a Student's t-distribution with degrees of freedom as given by the degrees of freedom for the residual sum of squares for the model.

4 References

Golub G H and Van Loan C F (1996) Matrix Computations (3rd Edition) Johns Hopkins University Press, Baltimore
Hammarling S (1985) The singular value decomposition in multivariate statistics SIGNUM Newsl. 20(3) 2–25
Searle S R (1971) Linear Models Wiley

5 Arguments

1:   IP – INTEGERInput
On entry: p, the number of terms in the linear model.
Constraint: IP≥1.
2:   IRANK – INTEGERInput
On entry: k, the rank of the independent variables.
Constraint: 1≤IRANK≤IP.
3:   B IP – REAL (KIND=nag_wp) arrayInput
On entry: the IP values of the estimates of the arguments of the model, β^.
4:   COV IP×IP+1/2 – REAL (KIND=nag_wp) arrayInput
On entry: the upper triangular part of the variance-covariance matrix of the IP parameter estimates given in B. They are stored packed by column, i.e., the covariance between the parameter estimate given in B i and the parameter estimate given in B j, j≥i, is stored in COV j×j-1/2+i.
5:   P IP×IP+2×IP – REAL (KIND=nag_wp) arrayInput
On entry: as returned by G02DAF and G02DDF.
6:   F IP – REAL (KIND=nag_wp) arrayInput
On entry: f, the linear function to be estimated.
7:   EST – LOGICALOutput
On exit: indicates if the function was estimable.
EST=.TRUE.
The function is estimable.
EST=.FALSE.
The function is not estimable and STAT, SESTAT and T are not set.
8:   STAT – REAL (KIND=nag_wp)Output
On exit: if EST=.TRUE., STAT contains the estimate of the function, fT β^.
9:   SESTAT – REAL (KIND=nag_wp)Output
On exit: if EST=.TRUE., SESTAT contains the standard error of the estimate of the function, se F.
10:   T – REAL (KIND=nag_wp)Output
On exit: if EST=.TRUE., T contains the t-statistic for the test of the function being equal to zero.
11:   TOL – REAL (KIND=nag_wp)Input
On entry: η, the tolerance value used in the check for estimability.
TOL≤0.0
ε, where ε is the machine precision, is used instead.
12:   WK IP – REAL (KIND=nag_wp) arrayWorkspace
13:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, because for this routine the values of the output arguments may be useful even if IFAIL≠0 on exit, the recommended value is -1. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Note: G02DNF may return useful information for one or more of the following detected errors or warnings.
Errors or warnings detected by the routine:
IFAIL=1
On entry, | IP<1,
or | IRANK<1,
or | IRANK>IP.
IFAIL=2
On entry, IRANK=IP. In this case EST is returned as true and all statistics are calculated.
IFAIL=3
Standard error of statistic =0.0; this may be due to rounding errors if the standard error is very small or due to mis-specified inputs COV and F.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

The computations are believed to be stable.

8 Parallelism and Performance

G02DNF makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The value of estimable functions is independent of the solution chosen from the many possible solutions. While G02DNF may be used to estimate functions of the arguments of the model as computed by G02DKF, βc, these must be expressed in terms of the original arguments, β. The relation between the two sets of arguments may not be straightforward.

10 Example

Data from an experiment with four treatments and three observations per treatment are read in. A model, with a mean term, is fitted by G02DAF. The number of functions to be tested is read in, then the linear functions themselves are read in and tested with G02DNF. The results of G02DNF are printed.

10.1 Program Text

Program Text (g02dnfe.f90)

10.2 Program Data

Program Data (g02dnfe.d)

10.3 Program Results

Program Results (g02dnfe.r)

G02 Chapter Contents
G02 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


G02EAF : NAG Library, Mark 26

G02 Chapter Contents
G02 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

G02EAF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

G02EAF calculates the residual sums of squares for all possible linear regressions for a given set of independent variables.

2 Specification

SUBROUTINE G02EAF ( MEAN, WEIGHT, N, M, X, LDX, VNAME, ISX, Y, WT, NMOD, MODL, LDMODL, RSS, NTERMS, MRANK, WK, IFAIL)
INTEGER | N, M, LDX, ISX(M), NMOD, LDMODL, NTERMS(LDMODL), MRANK(LDMODL), IFAIL
REAL (KIND=nag_wp) | X(LDX,M), Y(N), WT(*), RSS(LDMODL), WK(N*(M+1))
CHARACTER(*) | VNAME(M), MODL(LDMODL,M)
CHARACTER(1) | MEAN, WEIGHT

3 Description

For a set of k possible independent variables there are 2 k linear regression models with from zero to k independent variables in each model. For example if k=3 and the variables are A, B and C then the possible models are:
(i) | null model
(ii) | A
(iii) | B
(iv) | C
(v) | A and B
(vi) | A and C
(vii) | B and C
(viii) | A, B and C.
G02EAF calculates the residual sums of squares from each of the 2 k possible models. The method used involves a QR decomposition of the matrix of possible independent variables. Independent variables are then moved into and out of the model by a series of Givens rotations and the residual sums of squares computed for each model; see Clark (1981) and Smith and Bremner (1989).
The computed residual sums of squares are then ordered first by increasing number of terms in the model, then by decreasing size of residual sums of squares. So the first model will always have the largest residual sum of squares and the 2 kth will always have the smallest. This aids you in selecting the best possible model from the given set of independent variables.
G02EAF allows you to specify some independent variables that must be in the model, the forced variables. The other independent variables from which the possible models are to be formed are the free variables.

4 References

Clark M R B (1981) A Givens algorithm for moving from one linear model to another without going back to the data Appl. Statist. 30 198–203
Smith D M and Bremner J M (1989) All possible subset regressions using the QR decomposition Comput. Statist. Data Anal. 7 217–236
Weisberg S (1985) Applied Linear Regression Wiley

5 Arguments

1:   MEAN – CHARACTER(1)Input
On entry: indicates if a mean term is to be included.
MEAN='M'
A mean term, intercept, will be included in the model.
MEAN='Z'
The model will pass through the origin, zero-point.
Constraint: MEAN='M' or 'Z'.
2:   WEIGHT – CHARACTER(1)Input
On entry: indicates if weights are to be used.
WEIGHT='U'
Least squares estimation is used.
WEIGHT='W'
Weighted least squares is used and weights must be supplied in array WT.
Constraint: WEIGHT='U' or 'W'.
3:   N – INTEGERInput
On entry: n, the number of observations.
Constraints:
  • N≥2;
  • N≥m, is the number of independent variables to be considered (forced plus free plus mean if included), as specified by MEAN and ISX.
4:   M – INTEGERInput
On entry: the number of variables contained in X.
Constraint: M≥2.
5:   X LDXM – REAL (KIND=nag_wp) arrayInput
On entry: X ij must contain the ith observation for the jth independent variable, for i=1,2,…,N and j=1,2,…,M.
6:   LDX – INTEGERInput
On entry: the first dimension of the array X as declared in the (sub)program from which G02EAF is called.
Constraint: LDX≥N.
7:   VNAME M – CHARACTER(*) arrayInput
On entry: VNAME j must contain the name of the variable in column j of X, for j=1,2,…,M.
8:   ISX M – INTEGER arrayInput
On entry: indicates which independent variables are to be considered in the model.
ISX j≥2
The variable contained in the jth column of X is included in all regression models, i.e., is a forced variable.
ISX j=1
The variable contained in the jth column of X is included in the set from which the regression models are chosen, i.e., is a free variable.
ISX j=0
The variable contained in the jth column of X is not included in the models.
Constraints:
  • ISX j≥0, for j=1,2,…,M;
  • at least one value of ISX=1.
9:   Y N – REAL (KIND=nag_wp) arrayInput
On entry: Y i must contain the ith observation on the dependent variable, yi, for i=1,2,…,n.
10:   WT* – REAL (KIND=nag_wp) arrayInput
Note: the dimension of the array WT must be at least N if WEIGHT='W'.
On entry: if WEIGHT='W', WT must contain the weights to be used in the weighted regression.
If WT i=0.0, the ith observation is not included in the model, in which case the effective number of observations is the number of observations with nonzero weights.
If WEIGHT='U', WT is not referenced and the effective number of observations is N.
Constraint: if WEIGHT='W', WT i≥0.0, for i=1,2,…,n.
11:   NMOD – INTEGEROutput
On exit: the total number of models for which residual sums of squares have been calculated.
12:   MODL LDMODLM – CHARACTER(*) arrayOutput
On exit: the first NTERMS i elements of the ith row of MODL contain the names of the independent variables, as given in VNAME, that are included in the ith model.
Constraint: the length of MODL should be greater or equal to the length of VNAME.
13:   LDMODL – INTEGERInput
On entry: the first dimension of the array MODL and the dimension of the arrays RSS, NTERMS and MRANK as declared in the (sub)program from which G02EAF is called.
Constraints:
  • LDMODL≥M;
  • LDMODL≥2 k, k is the number of free variables in the model as specified in ISX, and hence 2 k is the total number of models to be generated.
14:   RSS LDMODL – REAL (KIND=nag_wp) arrayOutput
On exit: RSS i contains the residual sum of squares for the ith model, for i=1,2,…,NMOD.
15:   NTERMS LDMODL – INTEGER arrayOutput
On exit: NTERMS i contains the number of independent variables in the ith model, not including the mean if one is fitted, for i=1,2,…,NMOD.
16:   MRANK LDMODL – INTEGER arrayOutput
On exit: MRANK i contains the rank of the residual sum of squares for the ith model.
17:   WK N×M+1 – REAL (KIND=nag_wp) arrayWorkspace
18:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, | N<2,
or | M<2,
or | LDX<N,
or | LDMODL<M,
or | MEAN≠'M' or 'Z',
or | WEIGHT≠'U' or 'W'.
IFAIL=2
On entry, WEIGHT='W' and a value of WT<0.0.
IFAIL=3
On entry, | a value of ISX<0,
or | there are no free variables, i.e., no element of ISX=1.
IFAIL=4
On entry, LDMODL< the number of possible models =2 k, where k is the number of free independent variables from ISX.
IFAIL=5
On entry, the number of independent variables to be considered (forced plus free plus mean if included) is greater or equal to the effective number of observations.
IFAIL=6
The full model is not of full rank, i.e., some of the independent variables may be linear combinations of other independent variables. Variables must be excluded from the model in order to give full rank.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

For a discussion of the improved accuracy obtained by using a method based on the QR decomposition see Smith and Bremner (1989).

8 Parallelism and Performance

G02EAF is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
G02EAF makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

G02ECF may be used to compute R 2 and Cp-values from the results of G02EAF.
If a mean has been included in the model and no variables are forced in then RSS 1 contains the total sum of squares and in many situations a reasonable estimate of the variance of the errors is given by RSS NMOD/N-1-NTERMS NMOD.

10 Example

The data for this example is given in Weisberg (1985). The independent variables and the dependent variable are read, as are the names of the variables. These names are as given in Weisberg (1985). The residual sums of squares computed and printed with the names of the variables in the model.

10.1 Program Text

Program Text (g02eafe.f90)

10.2 Program Data

Program Data (g02eafe.d)

10.3 Program Results

Program Results (g02eafe.r)

G02 Chapter Contents
G02 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


G02ECF : NAG Library, Mark 26

G02 Chapter Contents
G02 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

G02ECF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

G02ECF calculates R 2 and Cp-values from the residual sums of squares for a series of linear regression models.

2 Specification

SUBROUTINE G02ECF ( MEAN, N, SIGSQ, TSS, NMOD, NTERMS, RSS, RSQ, CP, IFAIL)
INTEGER | N, NMOD, NTERMS(NMOD), IFAIL
REAL (KIND=nag_wp) | SIGSQ, TSS, RSS(NMOD), RSQ(NMOD), CP(NMOD)
CHARACTER(1) | MEAN

3 Description

When selecting a linear regression model for a set of n observations a balance has to be found between the number of independent variables in the model and fit as measured by the residual sum of squares. The more variables included the smaller will be the residual sum of squares. Two statistics can help in selecting the best model.
(a) R 2 represents the proportion of variation in the dependent variable that is explained by the independent variables.
R 2=Regression Sum of SquaresTotal Sum of Squares,
where | Total Sum of Squares=TSS=∑ y-y- 2 (if mean is fitted, otherwise TSS=∑y 2) and
 | Regression Sum of Squares=RegSS=TSS-RSS, where RSS=residual sum of squares=∑ y-y^ 2.
The R 2-values can be examined to find a model with a high R 2-value but with small number of independent variables.
(b) Cp statistic.
Cp=RSS σ^2 -n-2 p,
where p is the number of arguments (including the mean) in the model and σ^2 is an estimate of the true variance of the errors. This can often be obtained from fitting the full model.
A well fitting model will have Cp≃p. Cp is often plotted against p to see which models are closest to the Cp=p line.
G02ECF may be called after G02EAF which calculates the residual sums of squares for all possible linear regression models.

4 References

Draper N R and Smith H (1985) Applied Regression Analysis (2nd Edition) Wiley
Weisberg S (1985) Applied Linear Regression Wiley

5 Arguments

1:   MEAN – CHARACTER(1)Input
On entry: indicates if a mean term is to be included.
MEAN='M'
A mean term, intercept, will be included in the model.
MEAN='Z'
The model will pass through the origin, zero-point.
Constraint: MEAN='M' or 'Z'.
2:   N – INTEGERInput
On entry: n, the number of observations used in the regression model.
Constraint: N must be greater than 2×pmax, where pmax is the largest number of independent variables fitted (including the mean if fitted).
3:   SIGSQ – REAL (KIND=nag_wp)Input
On entry: the best estimate of true variance of the errors, σ^2.
Constraint: SIGSQ>0.0.
4:   TSS – REAL (KIND=nag_wp)Input
On entry: the total sum of squares for the regression model.
Constraint: TSS>0.0.
5:   NMOD – INTEGERInput
On entry: the number of regression models.
Constraint: NMOD>0.
6:   NTERMS NMOD – INTEGER arrayInput
On entry: NTERMS i must contain the number of independent variables (not counting the mean) fitted to the ith model, for i=1,2,…,NMOD.
7:   RSS NMOD – REAL (KIND=nag_wp) arrayInput
On entry: RSS i must contain the residual sum of squares for the ith model.
Constraint: RSS i≤TSS, for i=1,2,…,NMOD.
8:   RSQ NMOD – REAL (KIND=nag_wp) arrayOutput
On exit: RSQ i contains the R 2-value for the ith model, for i=1,2,…,NMOD.
9:   CP NMOD – REAL (KIND=nag_wp) arrayOutput
On exit: CP i contains the Cp-value for the ith model, for i=1,2,…,NMOD.
10:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, | NMOD<1,
or | SIGSQ≤0.0,
or | TSS≤0.0.
or | MEAN≠'M' or 'Z'.
IFAIL=2
On entry, the number of arguments for a model is too large for the number of observations, i.e., 2×p≥n.
IFAIL=3
On entry, RSS i>TSS, for some i=1,2,…,NMOD.
IFAIL=4
A value of Cp is less than 0.0. This may occur if SIGSQ is too large or if RSS, N or IP are incorrect.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

Accuracy is sufficient for all practical purposes.

8 Parallelism and Performance

G02ECF is not threaded in any implementation.

9 Further Comments

None.

10 Example

The data, from an oxygen uptake experiment, is given by Weisberg (1985). The independent and dependent variables are read and the residual sums of squares for all possible models computed using G02EAF. The values of R 2 and Cp are then computed and printed along with the names of variables in the models.

10.1 Program Text

Program Text (g02ecfe.f90)

10.2 Program Data

Program Data (g02ecfe.d)

10.3 Program Results

Program Results (g02ecfe.r)

G02 Chapter Contents
G02 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


G02EEF : NAG Library, Mark 26

G02 Chapter Contents
G02 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

G02EEF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

G02EEF carries out one step of a forward selection procedure in order to enable the ‘best’ linear regression model to be found.

2 Specification

SUBROUTINE G02EEF ( ISTEP, MEAN, WEIGHT, N, M, X, LDX, VNAME, ISX, MAXIP, Y, WT, FIN, ADDVAR, NEWVAR, CHRSS, F, MODEL, NTERM, RSS, IDF, IFR, FREE, EXSS, Q, LDQ, P, WK, IFAIL)
INTEGER | ISTEP, N, M, LDX, ISX(M), MAXIP, NTERM, IDF, IFR, LDQ, IFAIL
REAL (KIND=nag_wp) | X(LDX,M), Y(N), WT(*), FIN, CHRSS, F, RSS, EXSS(MAXIP), Q(LDQ,MAXIP+2), P(MAXIP+1), WK(2*MAXIP)
LOGICAL | ADDVAR
CHARACTER(*) | VNAME(M), NEWVAR, MODEL(MAXIP), FREE(MAXIP)
CHARACTER(1) | MEAN, WEIGHT

3 Description

One method of selecting a linear regression model from a given set of independent variables is by forward selection. The following procedure is used:
(i) | Select the best fitting independent variable, i.e., the independent variable which gives the smallest residual sum of squares. If the F-test for this variable is greater than a chosen critical value, Fc, then include the variable in the model, else stop.
(ii) | Find the independent variable that leads to the greatest reduction in the residual sum of squares when added to the current model.
(iii) | If the F-test for this variable is greater than a chosen critical value, Fc, then include the variable in the model and go to (ii), otherwise stop.
At any step the variables not in the model are known as the free terms.
G02EEF allows you to specify some independent variables that must be in the model, these are known as forced variables.
The computational procedure involves the use of QR decompositions, the R and the Q matrices being updated as each new variable is added to the model. In addition the matrix QT Xfree, where Xfree is the matrix of variables not included in the model, is updated.
G02EEF computes one step of the forward selection procedure at a call. The results produced at each step may be printed or used as inputs to G02DDF, in order to compute the regression coefficients for the model fitted at that step. Repeated calls to G02EEF should be made until F<Fc is indicated.

4 References

Draper N R and Smith H (1985) Applied Regression Analysis (2nd Edition) Wiley
Weisberg S (1985) Applied Linear Regression Wiley

5 Arguments

Note: after the initial call to G02EEF with ISTEP=0 all arguments except FIN must not be changed by you between calls.
1:   ISTEP – INTEGERInput/Output
On entry: indicates which step in the forward selection process is to be carried out.
ISTEP=0
The process is initialized.
Constraint: ISTEP≥0.
On exit: is incremented by 1.
2:   MEAN – CHARACTER(1)Input
On entry: indicates if a mean term is to be included.
MEAN='M'
A mean term, intercept, will be included in the model.
MEAN='Z'
The model will pass through the origin, zero-point.
Constraint: MEAN='M' or 'Z'.
3:   WEIGHT – CHARACTER(1)Input
On entry: indicates if weights are to be used.
WEIGHT='U'
Least squares estimation is used.
WEIGHT='W'
Weighted least squares is used and weights must be supplied in array WT.
Constraint: WEIGHT='U' or 'W'.
4:   N – INTEGERInput
On entry: n, the number of observations.
Constraint: N≥2.
5:   M – INTEGERInput
On entry: m, the total number of independent variables in the dataset.
Constraint: M≥1.
6:   X LDXM – REAL (KIND=nag_wp) arrayInput
On entry: X ij must contain the ith observation for the jth independent variable, for i=1,2,…,N and j=1,2,…,M.
7:   LDX – INTEGERInput
On entry: the first dimension of the array X as declared in the (sub)program from which G02EEF is called.
Constraint: LDX≥N.
8:   VNAME M – CHARACTER(*) arrayInput
On entry: VNAME j must contain the name of the independent variable in column j of X, for j=1,2,…,M.
9:   ISX M – INTEGER arrayInput
On entry: indicates which independent variables could be considered for inclusion in the regression.
ISX j≥2
The variable contained in the jth column of X is automatically included in the regression model, for j=1,2,…,M.
ISX j=1
The variable contained in the jth column of X is considered for inclusion in the regression model, for j=1,2,…,M.
ISX j=0
The variable in the jth column is not considered for inclusion in the model, for j=1,2,…,M.
Constraint: ISX j≥0 and at least one value of ISX j=1, for j=1,2,…,M.
10:   MAXIP – INTEGERInput
On entry: the maximum number of independent variables to be included in the model.
Constraints:
  • if MEAN='M', MAXIP≥1+ number of values of ISX>0;
  • if MEAN='Z', MAXIP≥ number of values of ISX>0.
11:   Y N – REAL (KIND=nag_wp) arrayInput
On entry: the dependent variable.
12:   WT* – REAL (KIND=nag_wp) arrayInput
Note: the dimension of the array WT must be at least N if WEIGHT='W'.
On entry: if WEIGHT='W', WT must contain the weights to be used in the weighted regression, W.
If WT i=0.0, the ith observation is not included in the model, in which case the effective number of observations is the number of observations with nonzero weights.
If WEIGHT='U', WT is not referenced and the effective number of observations is N.
Constraint: if WEIGHT='W', WT i≥0.0, for i=1,2,…,N.
13:   FIN – REAL (KIND=nag_wp)Input
On entry: the critical value of the F statistic for the term to be included in the model, Fc.
Suggested value: 2.0 is a commonly used value in exploratory modelling.
Constraint: FIN≥0.0.
14:   ADDVAR – LOGICALOutput
On exit: indicates if a variable has been added to the model.
ADDVAR=.TRUE.
A variable has been added to the model.
ADDVAR=.FALSE.
No variable had an F value greater than Fc and none were added to the model.
15:   NEWVAR – CHARACTER(*)Output
On exit: if ADDVAR=.TRUE., NEWVAR contains the name of the variable added to the model.
Constraint: the declared size of NEWVAR must be greater than or equal to the declared size of VNAME.
16:   CHRSS – REAL (KIND=nag_wp)Output
On exit: if ADDVAR=.TRUE., CHRSS contains the change in the residual sum of squares due to adding variable NEWVAR.
17:   F – REAL (KIND=nag_wp)Output
On exit: if ADDVAR=.TRUE., F contains the F statistic for the inclusion of the variable in NEWVAR.
18:   MODEL MAXIP – CHARACTER(*) arrayInput/Output
On entry: if ISTEP=0, MODEL need not be set.
If ISTEP≠0, MODEL must contain the values returned by the previous call to G02EEF.
Constraint: the declared size of MODEL must be greater than or equal to the declared size of VNAME.
On exit: the names of the variables in the current model.
19:   NTERM – INTEGERInput/Output
On entry: if ISTEP=0, NTERM need not be set.
If ISTEP≠0, NTERM must contain the value returned by the previous call to G02EEF.
Constraint: if ISTEP≠0, NTERM>0.
On exit: the number of independent variables in the current model, not including the mean, if any.
20:   RSS – REAL (KIND=nag_wp)Input/Output
On entry: if ISTEP=0, RSS need not be set.
If ISTEP≠0, RSS must contain the value returned by the previous call to G02EEF.
Constraint: if ISTEP≠0, RSS>0.0.
On exit: the residual sums of squares for the current model.
21:   IDF – INTEGERInput/Output
On entry: if ISTEP=0, IDF need not be set.
If ISTEP≠0, IDF must contain the value returned by the previous call to G02EEF.
On exit: the degrees of freedom for the residual sum of squares for the current model.
22:   IFR – INTEGERInput/Output
On entry: if ISTEP=0, IFR need not be set.
If ISTEP≠0, IFR must contain the value returned by the previous call to G02EEF.
On exit: the number of free independent variables, i.e., the number of variables not in the model that are still being considered for selection.
23:   FREE MAXIP – CHARACTER(*) arrayInput/Output
On entry: if ISTEP=0, FREE need not be set.
If ISTEP≠0, FREE must contain the values returned by the previous call to G02EEF.
Constraint: the declared size of FREE must be greater than or equal to the declared size of VNAME.
On exit: the first IFR values of FREE contain the names of the free variables.
24:   EXSS MAXIP – REAL (KIND=nag_wp) arrayOutput
On exit: the first IFR values of EXSS contain what would be the change in regression sum of squares if the free variables had been added to the model, i.e., the extra sum of squares for the free variables. EXSS i contains what would be the change in regression sum of squares if the variable FREE i had been added to the model.
25:   Q LDQ MAXIP+2 – REAL (KIND=nag_wp) arrayInput/Output
On entry: if ISTEP=0, Q need not be set.
If ISTEP≠0, Q must contain the values returned by the previous call to G02EEF.
On exit: the results of the QR decomposition for the current model:
  • the first column of Q contains c=QT y (or QTW 12 y where W is the vector of weights if used);
  • the upper triangular part of columns 2 to p+1 contain the R matrix;
  • the strictly lower triangular part of columns 2 to p+1 contain details of the Q matrix;
  • the remaining p+1 to p+IFR columns of contain QT Xfree (or QTW 12 Xfree),
where p=NTERM, or p=NTERM+1 if MEAN='M'.
26:   LDQ – INTEGERInput
On entry: the first dimension of the array Q as declared in the (sub)program from which G02EEF is called.
Constraint: LDQ≥N.
27:   P MAXIP+1 – REAL (KIND=nag_wp) arrayInput/Output
On entry: if ISTEP=0, P need not be set.
If ISTEP≠0, P must contain the values returned by the previous call to G02EEF.
On exit: the first p elements of P contain details of the QR decomposition, where p=NTERM, or p=NTERM+1 if MEAN='M'.
28:   WK 2×MAXIP – REAL (KIND=nag_wp) arrayWorkspace
29:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, | N<1,
or | M<1,
or | LDX<N,
or | LDQ<N,
or | ISTEP<0,
or | ISTEP≠0 and NTERM=0,
or | ISTEP≠0 and RSS≤0.0,
or | FIN<0.0,
or | MEAN≠'M' or 'Z',
or | WEIGHT≠'U' or 'W'.
IFAIL=2
On entry, WEIGHT='W' and a value of WT<0.0.
IFAIL=3
On entry, the degrees of freedom will be zero if a variable is selected, i.e., the number of variables in the model plus 1 is equal to the effective number of observations.
IFAIL=4
On entry, | a value of ISX<0,
or | there are no forced or free variables, i.e., no element of ISX>0,
or | the value of MAXIP is too small for number of variables indicated by ISX.
IFAIL=5
On entry, the variables forced into the model are not of full rank, i.e., some of these variables are linear combinations of others.
IFAIL=6
On entry, there are no free variables, i.e., no element of ISX=0.
IFAIL=7
The value of the change in the sum of squares is greater than the input value of RSS. This may occur due to rounding errors if the true residual sum of squares for the new model is small relative to the residual sum of squares for the previous model.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

As G02EEF uses a QR transformation the results will often be more accurate than traditional algorithms using methods based on the cross-products of the dependent and independent variables.

8 Parallelism and Performance

G02EEF is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
G02EEF makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

None.

10 Example

The data, from an oxygen uptake experiment, is given by Weisberg (1985). The names of the variables are as given in Weisberg (1985). The independent and dependent variables are read and G02EEF is repeatedly called until ADDVAR=.FALSE.. At each step the F statistic, the free variables and their extra sum of squares are printed; also, except for when ADDVAR=.FALSE., the new variable, the change in the residual sum of squares and the terms in the model are printed.

10.1 Program Text

Program Text (g02eefe.f90)

10.2 Program Data

Program Data (g02eefe.d)

10.3 Program Results

Program Results (g02eefe.r)

G02 Chapter Contents
G02 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


G02EFF : NAG Library, Mark 26

G02 Chapter Contents
G02 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

G02EFF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

G02EFF calculates a full stepwise selection from p variables by using Clarke's sweep algorithm on the correlation matrix of a design and data matrix, Z. The (weighted) variance-covariance, (weighted) means and sum of weights of Z must be supplied.

2 Specification

SUBROUTINE G02EFF ( M, N, WMEAN, C, SW, ISX, FIN, FOUT, TAU, B, SE, RSQ, RMS, DF, MONLEV, MONFUN, IUSER, RUSER, IFAIL)
INTEGER | M, N, ISX(M), DF, MONLEV, IUSER(*), IFAIL
REAL (KIND=nag_wp) | WMEAN(M+1), C((M+1)*(M+2)/2), SW, FIN, FOUT, TAU, B(M+1), SE(M+1), RSQ, RMS, RUSER(*)
EXTERNAL | MONFUN

3 Description

The general multiple linear regression model is defined by
y = β 0 +Xβ+ε,
where
  • y is a vector of n observations on the dependent variable,
  • β 0 is an intercept coefficient,
  • X is an n by p matrix of p explanatory variables,
  • β is a vector of p unknown coefficients, and
  • ε is a vector of length n of unknown, Normally distributed, random errors.
G02EFF employs a full stepwise regression to select a subset of explanatory variables from the p available variables (the intercept is included in the model) and computes regression coefficients and their standard errors, and various other statistical quantities, by minimizing the sum of squares of residuals. The method applies repeatedly a forward selection step followed by a backward elimination step and halts when neither step updates the current model.
The criterion used to update a current model is the variance ratio of residual sum of squares. Let s 1 and s 2 be the residual sum of squares of the current model and this model after undergoing a single update, with degrees of freedom q 1 and q 2, respectively. Then the condition:
s 2 - s 1 / q 2 - q 1 s 1 / q 1 > f 1 ,
must be satisfied if a variable k will be considered for entry to the current model, and the condition:
s 1 - s 2 / q 1 - q 2 s 1 / q 1 < f 2 ,
must be satisfied if a variable k will be considered for removal from the current model, where f 1 and f 2 are user-supplied values and f 2≤f 1.
In the entry step the entry statistic is computed for each variable not in the current model. If no variable is associated with a test value that exceeds f 1 then this step is terminated; otherwise the variable associated with the largest value for the entry statistic is entered into the model.
In the removal step the removal statistic is computed for each variable in the current model. If no variable is associated with a test value less than f 2 then this step is terminated; otherwise the variable associated with the smallest value for the removal statistic is removed from the model.
The data values X and y are not provided as input to the routine. Instead, summary statistics of the design and data matrix Z=X∣y are required.
Explanatory variables are entered into and removed from the current model by using sweep operations on the correlation matrix R of Z, given by:
R = 1 … r 1 p r 1 y ⋮ ⋱ ⋮ ⋮ r p 1 … 1 r py r y 1 … r yp 1 ,
where r ij is the correlation between the explanatory variables i and j, for i=1,2,…,p and j=1,2,…,p, and r yi (and r iy) is the correlation between the response variable y and the ith explanatory variable, for i=1,2,…,p.
A sweep operation on the kth row and column (k≤p) of R replaces:
r kk ​ by ​ -1 / r kk ; r ik ​ by ​ r ik / r kk ,  i=1,2,…,p+1 ​ ​ i≠k ; r kj ​ by ​ r kj / r kk ,  j=1,2,…,p+1 ​ ​ j≠k ; r ij ​ by ​ r ij - r ik r kj / r kk ,  ​ i=1,2,…,p+1 ​ ​ i≠k ; ​ j=1,2,…,p+1 ​ ​ j≠k .
The kth explanatory variable is eligible for entry into the current model if it satisfies the collinearity tests: r kk>τ and
r ii - r ik r ki r kk τ≤1 ,
for a user-supplied value (>0) of τ and where the index i runs over explanatory variables in the current model. The sweep operation is its own inverse, therefore pivoting on an explanatory variable k in the current model has the effect of removing it from the model.
Once the stepwise model selection procedure is finished, the routine calculates:
(a) | the least squares estimate for the ith explanatory variable included in the fitted model;
(b) | standard error estimates for each coefficient in the final model;
(c) | the square root of the mean square of residuals and its degrees of freedom;
(d) | the multiple correlation coefficient.
The routine makes use of the symmetry of the sweep operations and correlation matrix which reduces by almost one half the storage and computation required by the sweep algorithm, see Clarke (1981) for details.

4 References

Clarke M R B (1981) Algorithm AS 178: the Gauss–Jordan sweep operator with detection of collinearity Appl. Statist. 31 166–169
Dempster A P (1969) Elements of Continuous Multivariate Analysis Addison–Wesley
Draper N R and Smith H (1985) Applied Regression Analysis (2nd Edition) Wiley

5 Arguments

1:   M – INTEGERInput
On entry: the number of explanatory variables available in the design matrix, Z.
Constraint: M>1.
2:   N – INTEGERInput
On entry: the number of observations used in the calculations.
Constraint: N>1.
3:   WMEAN M+1 – REAL (KIND=nag_wp) arrayInput
On entry: the mean of the design matrix, Z.
4:   C M+1×M+2/2 – REAL (KIND=nag_wp) arrayInput
On entry: the upper-triangular variance-covariance matrix packed by column for the design matrix, Z. Because the routine computes the correlation matrix R from C, the variance-covariance matrix need only be supplied up to a scaling factor.
5:   SW – REAL (KIND=nag_wp)Input
On entry: if weights were used to calculate C then SW is the sum of positive weight values; otherwise SW is the number of observations used to calculate C.
Constraint: SW>1.0.
6:   ISX M – INTEGER arrayInput/Output
On entry: the value of ISX j determines the set of variables used to perform full stepwise model selection, for j=1,2,…,M.
ISX j=-1
To exclude the variable corresponding to the jth column of X from the final model.
ISX j=1
To consider the variable corresponding to the jth column of X for selection in the final model.
ISX j=2
To force the inclusion of the variable corresponding to the jth column of X in the final model.
Constraint: ISX j=-1,1​ or ​2, for j=1,2,…,M.
On exit: the value of ISX j indicates the status of the jth explanatory variable in the model.
ISX j=-1
Forced exclusion.
ISX j=0
Excluded.
ISX j=1
Selected.
ISX j=2
Forced selection.
7:   FIN – REAL (KIND=nag_wp)Input
On entry: the value of the variance ratio which an explanatory variable must exceed to be included in a model.
Suggested value: FIN=4.0.
Constraint: FIN>0.0.
8:   FOUT – REAL (KIND=nag_wp)Input
On entry: the explanatory variable in a model with the lowest variance ratio value is removed from the model if its value is less than FOUT. FOUT is usually set equal to the value of FIN; a value less than FIN is occasionally preferred.
Suggested value: FOUT=FIN.
Constraint: 0.0≤FOUT≤FIN.
9:   TAU – REAL (KIND=nag_wp)Input
On entry: the tolerance, τ, for detecting collinearities between variables when adding or removing an explanatory variable from a model. Explanatory variables deemed to be collinear are excluded from the final model.
Suggested value: TAU=1.0×10-6.
Constraint: TAU>0.0.
10:   B M+1 – REAL (KIND=nag_wp) arrayOutput
On exit: B 1 contains the estimate for the intercept term in the fitted model. If ISX j≠0 then B j+1 contains the estimate for the jth explanatory variable in the fitted model; otherwise B j+1=0.
11:   SE M+1 – REAL (KIND=nag_wp) arrayOutput
On exit: SE j contains the standard error for the estimate of B j, for j=1,2,…,M+1.
12:   RSQ – REAL (KIND=nag_wp)Output
On exit: the R 2-statistic for the fitted regression model.
13:   RMS – REAL (KIND=nag_wp)Output
On exit: the mean square of residuals for the fitted regression model.
14:   DF – INTEGEROutput
On exit: the number of degrees of freedom for the sum of squares of residuals.
15:   MONLEV – INTEGERInput
On entry: if a subroutine is provided by you to monitor the model selection process, set MONLEV to 1; otherwise set MONLEV to 0.
Constraint: MONLEV=0 or 1.
16:   MONFUN – SUBROUTINE, supplied by the NAG Library or the user.External Procedure
You may define your own function or specify the NAG defined default function G02EFH.
If MONLEV=0, MONFUN is not referenced; otherwise its specification is:
The specification of MONFUN is:
SUBROUTINE MONFUN ( FLAG, VAR, VAL, IUSER, RUSER)
INTEGER | VAR, IUSER(*)
REAL (KIND=nag_wp) | VAL, RUSER(*)
CHARACTER(1) | FLAG
1:   FLAG – CHARACTER(1)Input
On entry: the value of FLAG indicates the stage of the stepwise selection of explanatory variables.
FLAG='A'
Variable VAR was added to the current model.
FLAG='B'
Beginning the backward elimination step.
FLAG='C'
Variable VAR failed the collinearity test and is excluded from the model.
FLAG='D'
Variable VAR was dropped from the current model.
FLAG='F'
Beginning the forward selection step
FLAG='K'
Backward elimination did not remove any variables from the current model.
FLAG='S'
Starting stepwise selection procedure.
FLAG='V'
The variance ratio for variable VAR takes the value VAL.
FLAG='X'
Finished stepwise selection procedure.
2:   VAR – INTEGERInput
On entry: the index of the explanatory variable in the design matrix Z to which FLAG pertains.
3:   VAL – REAL (KIND=nag_wp)Input
On entry: if FLAG='V', VAL is the variance ratio value for the coefficient associated with explanatory variable index VAR.
4:   IUSER* – INTEGER arrayUser Workspace
5:   RUSER* – REAL (KIND=nag_wp) arrayUser Workspace
MONFUN is called with the arguments IUSER and RUSER as supplied to G02EFF. You are free to use the arrays IUSER and RUSER to supply information to MONFUN as an alternative to using COMMON global variables.
MONFUN must either be a module subprogram USEd by, or declared as EXTERNAL in, the (sub)program from which G02EFF is called. Arguments denoted as Input must not be changed by this procedure.
17:   IUSER* – INTEGER arrayUser Workspace
18:   RUSER* – REAL (KIND=nag_wp) arrayUser Workspace
IUSER and RUSER are not used by G02EFF, but are passed directly to MONFUN and may be used to pass information to this routine as an alternative to using COMMON global variables.
19:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, FIN=value.
Constraint: FIN > 0.0.
On entry, FOUT=value; FIN=value.
Constraint: 0.0≤FOUT≤FIN.
On entry, M=value.
Constraint: M > 1.
On entry, MONLEV=value.
Constraint: MONLEV=0 or 1.
On entry, N=value.
Constraint: N>1.
On entry, SW=value.
Constraint: SW>1.0.
On entry, TAU=value.
Constraint: TAU>0.0.
IFAIL=2
No free variables from which to select.
At least one element of ISX should be set to 1.
On entry, invalid value for ISX value=value.
On entry at least one diagonal element of C ≤0.0.
IFAIL=3
The design and data matrix Z is not positive definite, results may be inaccurate. All output is returned as documented.
IFAIL=4
All variables are collinear, no model to select.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

G02EFF returns a warning if the design and data matrix is not positive definite.

8 Parallelism and Performance

G02EFF is not threaded in any implementation.

9 Further Comments

Although the condition for removing or adding a variable to the current model is based on a ratio of variances, these values should not be interpreted as F-statistics with the usual interpretation of significance unless the probability levels are adjusted to account for correlations between variables under consideration and the number of possible updates (see, e.g., Draper and Smith (1985)).
G02EFF allocates internally O 4×M+ M+1 × M+2 /2+2 of real storage.

10 Example

This example calculates a full stepwise model selection for the Hald data described in Dempster (1969). Means, the upper-triangular variance-covariance matrix and the sum of weights are calculated by G02BUF. The NAG defined default monitor function G02EFH is used to print information at each step of the model selection process.

10.1 Program Text

Program Text (g02effe.f90)

10.2 Program Data

Program Data (g02effe.d)

10.3 Program Results

Program Results (g02effe.r)

G02 Chapter Contents
G02 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


G02FAF : NAG Library, Mark 26

G02 Chapter Contents
G02 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

G02FAF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

G02FAF calculates two types of standardized residuals and two measures of influence for a linear regression.

2 Specification

SUBROUTINE G02FAF ( N, IP, NRES, RES, H, RMS, SRES, LDSRES, IFAIL)
INTEGER | N, IP, NRES, LDSRES, IFAIL
REAL (KIND=nag_wp) | RES(NRES), H(NRES), RMS, SRES(LDSRES,4)

3 Description

For the general linear regression model
y=Xβ+ε,
where | y is a vector of length n of the dependent variable,
 | X is an n by p matrix of the independent variables,
 | β is a vector of length p of unknown arguments,
and | ε is a vector of length n of unknown random errors such that var⁡ε=σ 2 I.
The residuals are given by
r=y-y^=y-X β^
and the fitted values, y^=X β^, can be written as Hy for an n by n matrix H. The ith diagonal elements of H, hi, give a measure of the influence of the ith values of the independent variables on the fitted regression model. The values of r and the hi are returned by G02DAF.
G02FAF calculates statistics which help to indicate if an observation is extreme and having an undue influence on the fit of the regression model. Two types of standardized residual are calculated:
(i) The ith residual is standardized by its variance when the estimate of σ 2, s 2, is calculated from all the data; this is known as internal Studentization.
R Ii=ri s⁢1-hi .
(ii) The ith residual is standardized by its variance when the estimate of σ 2, s-i 2 is calculated from the data excluding the ith observation; this is known as external Studentization.
R Ei=ri s-i 1-hi =ri n-p-1 n-p-R Ii 2 .
The two measures of influence are:
(i) Cook's D
Di=1 p R Ei 2 hi 1-hi .
(ii) Atkinson's T
Ti=R Ei n-p p hi 1-hi .

4 References

Atkinson A C (1981) Two graphical displays for outlying and influential observations in regression Biometrika 68 13–20
Cook R D and Weisberg S (1982) Residuals and Influence in Regression Chapman and Hall

5 Arguments

1:   N – INTEGERInput
On entry: n, the number of observations included in the regression.
Constraint: N>IP+1.
2:   IP – INTEGERInput
On entry: p, the number of linear arguments estimated in the regression model.
Constraint: IP≥1.
3:   NRES – INTEGERInput
On entry: the number of residuals.
Constraint: 1≤NRES≤N.
4:   RES NRES – REAL (KIND=nag_wp) arrayInput
On entry: the residuals, ri.
5:   H NRES – REAL (KIND=nag_wp) arrayInput
On entry: the diagonal elements of H, hi, corresponding to the residuals in RES.
Constraint: 0.0<H i<1.0, for i=1,2,…,NRES.
6:   RMS – REAL (KIND=nag_wp)Input
On entry: the estimate of σ 2 based on all n observations, s 2, i.e., the residual mean square.
Constraint: RMS>0.0.
7:   SRES LDSRES 4 – REAL (KIND=nag_wp) arrayOutput
On exit: the standardized residuals and influence statistics.
For the observation with residual, ri, given in RES i.
SRES i 1
Is the internally standardized residual, RIi.
SRES i 2
Is the externally standardized residual, REi.
SRES i 3
Is Cook's D statistic, Di.
SRES i 4
Is Atkinson's T statistic, Ti.
8:   LDSRES – INTEGERInput
On entry: the first dimension of the array SRES as declared in the (sub)program from which G02FAF is called.
Constraint: LDSRES≥NRES.
9:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, | IP<1,
or | N≤IP+1,
or | NRES<1,
or | NRES>N,
or | LDSRES<NRES,
or | RMS≤0.0.
IFAIL=2
On entry, H i≤0.0 or ≥1.0, for some i=1,2,…,NRES.
IFAIL=3
On entry, the value of a residual is too large for the given value of RMS.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

Accuracy is sufficient for all practical purposes.

8 Parallelism and Performance

G02FAF is not threaded in any implementation.

9 Further Comments

None.

10 Example

A set of 24 residuals and hi values from a 11 argument model fitted to the cloud seeding data considered in Cook and Weisberg (1982) are input and the standardized residuals etc calculated and printed for the first 10 observations.

10.1 Program Text

Program Text (g02fafe.f90)

10.2 Program Data

Program Data (g02fafe.d)

10.3 Program Results

Program Results (g02fafe.r)

G02 Chapter Contents
G02 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


G02FCF : NAG Library, Mark 26

G02 Chapter Contents
G02 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

G02FCF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

G02FCF calculates the Durbin–Watson statistic, for a set of residuals, and the upper and lower bounds for its significance.

2 Specification

SUBROUTINE G02FCF ( N, IP, RES, D, PDL, PDU, WORK, IFAIL)
INTEGER | N, IP, IFAIL
REAL (KIND=nag_wp) | RES(N), D, PDL, PDU, WORK(N)

3 Description

For the general linear regression model
y=Xβ+ε,
where | y is a vector of length n of the dependent variable, X is a n by p matrix of the independent variables, β is a vector of length p of unknown arguments,
and | ε is a vector of length n of unknown random errors.
The residuals are given by
r=y-y^=y-X β^
and the fitted values, y^=X β^, can be written as Hy for a n by n matrix H. Note that when a mean term is included in the model the sum of the residuals is zero. If the observations have been taken serially, that is y 1,y 2,…,yn can be considered as a time series, the Durbin–Watson test can be used to test for serial correlation in the εi, see Durbin and Watson (1950), Durbin and Watson (1951) and Durbin and Watson (1971).
The Durbin–Watson statistic is
d=∑i=1 n-1 r i+1-ri 2 ∑i=1 n ri 2 .
Positive serial correlation in the εi will lead to a small value of d while for independent errors d will be close to 2. Durbin and Watson show that the exact distribution of d depends on the eigenvalues of the matrix HA where the matrix A is such that d can be written as
d=rT Ar rT r
and the eigenvalues of the matrix A are λj=1-cos πj/n, for j=1,2,…,n-1.
However bounds on the distribution can be obtained, the lower bound being
dl=∑i=1 n-p λi ui 2 ∑i=1 n-p ui 2
and the upper bound being
du=∑i= 1 n-p λ i- 1+p ui 2 ∑i= 1 n-p ui 2 ,
where the ui are independent standard Normal variables. The lower tail probabilities associated with these bounds, pl and pu, are computed by G01EPF. The interpretation of the bounds is that, for a test of size (significance) α, if pl≤α the test is significant, if pu>α the test is not significant, while if pl>α and pu≤α no conclusion can be reached.
The above probabilities are for the usual test of positive auto-correlation. If the alternative of negative auto-correlation is required, then a call to G01EPF should be made with the argument D taking the value of 4-d; see Newbold (1988).

4 References

Durbin J and Watson G S (1950) Testing for serial correlation in least squares regression. I Biometrika 37 409–428
Durbin J and Watson G S (1951) Testing for serial correlation in least squares regression. II Biometrika 38 159–178
Durbin J and Watson G S (1971) Testing for serial correlation in least squares regression. III Biometrika 58 1–19
Granger C W J and Newbold P (1986) Forecasting Economic Time Series (2nd Edition) Academic Press
Newbold P (1988) Statistics for Business and Economics Prentice–Hall

5 Arguments

1:   N – INTEGERInput
On entry: n, the number of residuals.
Constraint: N>IP.
2:   IP – INTEGERInput
On entry: p, the number of independent variables in the regression model, including the mean.
Constraint: IP≥1.
3:   RES N – REAL (KIND=nag_wp) arrayInput
On entry: the residuals, r 1,r 2,…,rn.
Constraint: the mean of the residuals ≤ε, where ε=machine precision.
4:   D – REAL (KIND=nag_wp)Output
On exit: the Durbin–Watson statistic, d.
5:   PDL – REAL (KIND=nag_wp)Output
On exit: lower bound for the significance of the Durbin–Watson statistic, pl.
6:   PDU – REAL (KIND=nag_wp)Output
On exit: upper bound for the significance of the Durbin–Watson statistic, pu.
7:   WORK N – REAL (KIND=nag_wp) arrayWorkspace
8:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, | N≤IP,
or | IP<1.
IFAIL=2
On entry, the mean of the residuals was >ε, where ε=machine precision.
IFAIL=3
On entry, all residuals are identical.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

The probabilities are computed to an accuracy of at least 4 decimal places.

8 Parallelism and Performance

G02FCF is not threaded in any implementation.

9 Further Comments

If the exact probabilities are required, then the first n-p eigenvalues of HA can be computed and G01JDF used to compute the required probabilities with the argument C set to 0.0 and the argument D set to the Durbin–Watson statistic d.

10 Example

A set of 10 residuals are read in and the Durbin–Watson statistic along with the probability bounds are computed and printed.

10.1 Program Text

Program Text (g02fcfe.f90)

10.2 Program Data

Program Data (g02fcfe.d)

10.3 Program Results

Program Results (g02fcfe.r)

G02 Chapter Contents
G02 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


G02GAF : NAG Library, Mark 26

G02 Chapter Contents
G02 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

G02GAF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

G02GAF fits a generalized linear model with normal errors.

2 Specification

SUBROUTINE G02GAF ( LINK, MEAN, OFFSET, WEIGHT, N, X, LDX, M, ISX, IP, Y, WT, S, A, RSS, IDF, B, IRANK, SE, COV, V, LDV, TOL, MAXIT, IPRINT, EPS, WK, IFAIL)
INTEGER | N, LDX, M, ISX(M), IP, IDF, IRANK, LDV, MAXIT, IPRINT, IFAIL
REAL (KIND=nag_wp) | X(LDX,M), Y(N), WT(*), S, A, RSS, B(IP), SE(IP), COV(IP*(IP+1)/2), V(LDV,IP+7), TOL, EPS, WK((IP*IP+3*IP+22)/2)
CHARACTER(1) | LINK, MEAN, OFFSET, WEIGHT

3 Description

A generalized linear model with Normal errors consists of the following elements:
(a) a set of n observations, yi, from a Normal distribution with probability density function:
1 2 π σ exp- y-μ 2 2 σ 2 ,
where μ is the mean and σ 2 is the variance.
(b) | X, a set of p independent variables for each observation, x 1,x 2,…,xp.
(c) a linear model:
η=∑βjxj.
(d) a link between the linear predictor, η, and the mean of the distribution, μ, i.e., η=g μ. The possible link functions are:
(i) | exponent link: η=μa, for a constant a,
(ii) | identity link: η=μ,
(iii) | log link: η=log⁡μ,
(iv) | square root link: η=μ,
(v) | reciprocal link: η=1 μ .
(e) | a measure of fit, the residual sum of squares =∑ yi-μ^i 2.
The linear arguments are estimated by iterative weighted least squares. An adjusted dependent variable, z, is formed:
z=η+y-μ dη dμ
and a working weight, w,
w= dη dμ 2.
At each iteration an approximation to the estimate of β, β^, is found by the weighted least squares regression of z on X with weights w.
G02GAF finds a QR decomposition of w 12 X, i.e., w 12 X=QR where R is a p by p triangular matrix and Q is an n by p column orthogonal matrix.
If R is of full rank, then β^ is the solution to
R β^=QTw 12 z.
If R is not of full rank a solution is obtained by means of a singular value decomposition (SVD) of R.
R=Q* D 0 0 0 PT,
where D is a k by k diagonal matrix with nonzero diagonal elements, k being the rank of R and w 12 X.
This gives the solution
β^=P 1 D-1 Q* 0 0 I QTw 12 z
P 1 being the first k columns of P, i.e., P=P 1P 0.
The iterations are continued until there is only a small change in the residual sum of squares.
The initial values for the algorithm are obtained by taking
η^=g y.
The fit of the model can be assessed by examining and testing the residual sum of squares, in particular comparing the difference in residual sums of squares between nested models, i.e., when one model is a sub-model of the other.
Let RSSf be the residual sum of squares for the full model with degrees of freedom νf and let RSSs be the residual sum of squares for the sub-model with degrees of freedom νs then:
F=RSSs-RSSf/νs-νf RSSf/νf ,
has, approximately, an F-distribution with (νs-νf), νf degrees of freedom.
The parameter estimates, β^, are asymptotically Normally distributed with variance-covariance matrix:
  • C=R-1R-1 Tσ 2 in the full rank case,
  • otherwise C=P 1 D-2 P 1 T σ 2
The residuals and influence statistics can also be examined.
The estimated linear predictor η^=X β^, can be written as H w 12 z for an n by n matrix H. The ith diagonal elements of H, hi, give a measure of the influence of the ith values of the independent variables on the fitted regression model. These are sometimes known as leverages.
The fitted values are given by μ^=g-1 η^.
G02GAF also computes the residuals, r:
ri=yi-μ^i.
An option allows prior weights ωi to be used; this gives a model with:
σi 2=σ 2 ωi.
In many linear regression models the first term is taken as a mean term or an intercept, i.e., x i,1=1, for i=1,2,…,n; this is provided as an option.
Often only some of the possible independent variables are included in a model, the facility to select variables to be included in the model is provided.
If part of the linear predictor can be represented by a variable with a known coefficient, then this can be included in the model by using an offset, o:
η=o+∑βjxj.
If the model is not of full rank the solution given will be only one of the possible solutions. Other estimates may be obtained by applying constraints to the arguments. These solutions can be obtained by using G02GKF after using G02GAF. Only certain linear combinations of the arguments will have unique estimates; these are known as estimable functions and can be estimated and tested using G02GNF.
Details of the SVD are made available, in the form of the matrix P*:
P*= D-1 P 1 T P 0 T .

4 References

Cook R D and Weisberg S (1982) Residuals and Influence in Regression Chapman and Hall
McCullagh P and Nelder J A (1983) Generalized Linear Models Chapman and Hall

5 Arguments

1:   LINK – CHARACTER(1)Input
On entry: indicates which link function is to be used.
LINK='E'
An exponent link is used.
LINK='I'
An identity link is used. You are advised not to use G02GAF with an identity link as G02DAF provides a more efficient way of fitting such a model.
LINK='L'
A log link is used.
LINK='S'
A square root link is used.
LINK='R'
A reciprocal link is used.
Constraint: LINK='E', 'I', 'L', 'S' or 'R'.
2:   MEAN – CHARACTER(1)Input
On entry: indicates if a mean term is to be included.
MEAN='M'
A mean term, intercept, will be included in the model.
MEAN='Z'
The model will pass through the origin, zero-point.
Constraint: MEAN='M' or 'Z'.
3:   OFFSET – CHARACTER(1)Input
On entry: indicates if an offset is required.
OFFSET='Y'
An offset is required and the offsets must be supplied in the seventh column of V.
OFFSET='N'
No offset is required.
Constraint: OFFSET='N' or 'Y'.
4:   WEIGHT – CHARACTER(1)Input
On entry: indicates if prior weights are to be used.
WEIGHT='U'
No prior weights are used.
WEIGHT='W'
Prior weights are used and weights must be supplied in WT.
Constraint: WEIGHT='U' or 'W'.
5:   N – INTEGERInput
On entry: n, the number of observations.
Constraint: N≥2.
6:   X LDXM – REAL (KIND=nag_wp) arrayInput
On entry: X ij must contain the ith observation for the jth independent variable, for i=1,2,…,N and j=1,2,…,M.
7:   LDX – INTEGERInput
On entry: the first dimension of the array X as declared in the (sub)program from which G02GAF is called.
Constraint: LDX≥N.
8:   M – INTEGERInput
On entry: m, the total number of independent variables.
Constraint: M≥1.
9:   ISX M – INTEGER arrayInput
On entry: indicates which independent variables are to be included in the model.
If ISX j>0, the variable contained in the jth column of X is included in the regression model.
Constraints:
  • ISX j≥0, for i=1,2,…,M;
  • if MEAN='M', exactly IP-1 values of ISX must be >0;
  • if MEAN='Z', exactly IP values of ISX must be >0.
10:   IP – INTEGERInput
On entry: the number of independent variables in the model, including the mean or intercept if present.
Constraint: IP>0.
11:   Y N – REAL (KIND=nag_wp) arrayInput
On entry: the observations on the dependent variable, yi, for i=1,2,…,n.
12:   WT* – REAL (KIND=nag_wp) arrayInput
Note: the dimension of the array WT must be at least N if WEIGHT='W', and at least 1 otherwise.
On entry: if WEIGHT='W', WT must contain the weights to be used with the model, ωi. If WT i=0.0, the ith observation is not included in the model, in which case the effective number of observations is the number of observations with nonzero weights.
If WEIGHT='U', WT is not referenced and the effective number of observations is n.
Constraint: if WEIGHT='W', WT i≥0.0, for i=1,2,…,n.
13:   S – REAL (KIND=nag_wp)Input/Output
On entry: the scale argument for the model, σ 2.
If S=0.0, the scale argument is estimated with the routine using the residual mean square.
On exit: if on input S=0.0, S contains the estimated value of the scale argument, σ^2.
If on input S≠0.0, S is unchanged on exit.
Constraint: S≥0.0.
14:   A – REAL (KIND=nag_wp)Input
On entry: if LINK='E', A must contain the power of the exponential.
If LINK≠'E', A is not referenced.
Constraint: if LINK='E', A≠0.0.
15:   RSS – REAL (KIND=nag_wp)Output
On exit: the residual sum of squares for the fitted model.
16:   IDF – INTEGEROutput
On exit: the degrees of freedom associated with the residual sum of squares for the fitted model.
17:   B IP – REAL (KIND=nag_wp) arrayOutput
On exit: the estimates of the parameters of the generalized linear model, β^.
If MEAN='M', B 1 will contain the estimate of the mean parameter and B i+1 will contain the coefficient of the variable contained in column j of X, where ISX j is the ith positive value in the array ISX.
If MEAN='Z', B i will contain the coefficient of the variable contained in column j of X, where ISX j is the ith positive value in the array ISX.
18:   IRANK – INTEGEROutput
On exit: the rank of the independent variables.
If the model is of full rank, IRANK=IP.
If the model is not of full rank, IRANK is an estimate of the rank of the independent variables. IRANK is calculated as the number of singular values greater than EPS× (largest singular value). It is possible for the SVD to be carried out but for IRANK to be returned as IP.
19:   SE IP – REAL (KIND=nag_wp) arrayOutput
On exit: the standard errors of the linear parameters.
SE i contains the standard error of the parameter estimate in B i, for i=1,2,…,IP.
20:   COV IP×IP+1/2 – REAL (KIND=nag_wp) arrayOutput
On exit: the upper triangular part of the variance-covariance matrix of the IP parameter estimates given in B. They are stored packed by column, i.e., the covariance between the parameter estimate given in B i and the parameter estimate given in B j, j≥i, is stored in COV j×j-1/2+i.
21:   V LDV IP+7 – REAL (KIND=nag_wp) arrayInput/Output
On entry: if OFFSET='N', V need not be set.
If OFFSET='Y', V i 7, for i=1,2,…,n, must contain the offset values oi. All other values need not be set.
On exit: auxiliary information on the fitted model.
V i 1 | contains the linear predictor value, ηi, for i=1,2,…,n.
V i 2 | contains the fitted value, μ^i, for i=1,2,…,n.
V i 3 | is only included for consistency with other routines. V i 3=1.0, for i=1,2,…,n.
V i 4 | contains the square root of the working weight, wi 12, for i=1,2,…,n.
V i 5 | contains the residual, ri, for i=1,2,…,n.
V i 6 | contains the leverage, hi, for i=1,2,…,n.
V i 7 | contains the offset, for i=1,2,…,n. If OFFSET='N', all values will be zero.
V ij, | for j=8,…,IP+7, contains the results of the QR decomposition or the singular value decomposition.
If the model is not of full rank, i.e., IRANK<IP, the first IP rows of columns 8 to IP+7 contain the P* matrix.
22:   LDV – INTEGERInput
On entry: the first dimension of the array V as declared in the (sub)program from which G02GAF is called.
Constraint: LDV≥N.
23:   TOL – REAL (KIND=nag_wp)Input
On entry: indicates the accuracy required for the fit of the model.
The iterative weighted least squares procedure is deemed to have converged if the absolute change in deviance between interactions is less than TOL×1.0+current residual sum of squares. This is approximately an absolute precision if the residual sum of squares is small and a relative precision if the residual sum of squares is large.
If 0.0≤TOL<machine precision, G02GAF will use 10×machine precision.
Constraint: TOL≥0.0.
24:   MAXIT – INTEGERInput
On entry: the maximum number of iterations for the iterative weighted least squares.
If MAXIT=0, a default value of 10 is used.
Constraint: MAXIT≥0.
25:   IPRINT – INTEGERInput
On entry: indicates if the printing of information on the iterations is required.
IPRINT≤0
There is no printing.
IPRINT>0
Every IPRINT iteration, the following is printed:
the deviance,
the current estimates,
and if the weighted least squares equations are singular then this is indicated.
When printing occurs the output is directed to the current advisory message unit (see X04ABF).
26:   EPS – REAL (KIND=nag_wp)Input
On entry: the value of EPS is used to decide if the independent variables are of full rank and, if not, what is the rank of the independent variables. The smaller the value of EPS the stricter the criterion for selecting the singular value decomposition.
If 0.0≤EPS<machine precision, the routine will use machine precision instead.
Constraint: EPS≥0.0.
27:   WK IP×IP+3×IP+22/2 – REAL (KIND=nag_wp) arrayWorkspace
28:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, because for this routine the values of the output arguments may be useful even if IFAIL≠0 on exit, the recommended value is -1. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Note: G02GAF may return useful information for one or more of the following detected errors or warnings.
Errors or warnings detected by the routine:
IFAIL=1
On entry, | N<2,
or | M<1,
or | LDX<N,
or | LDV<N,
or | IP<1,
or | LINK≠'E','I','L','S' or 'R',
or | S<0.0,
or | LINK='E' and A=0.0,
or | MEAN≠'M' or 'Z',
or | WEIGHT≠'U' or 'W',
or | OFFSET≠'N' or 'Y',
or | MAXIT<0,
or | TOL<0.0,
or | EPS<0.0.
IFAIL=2
On entry, WEIGHT='W' and a value of WT<0.0.
IFAIL=3
On entry, | a value of ISX<0,
or | the value of IP is incompatible with the values of MEAN and ISX,
or | IP is greater than the effective number of observations.
IFAIL=4
A fitted value is at a boundary. This will only occur with LINK='L', 'R' or 'E'. This may occur if there are small values of y and the model is not suitable for the data. The model should be reformulated with, perhaps, some observations dropped.
IFAIL=5
The singular value decomposition has failed to converge. This is an unlikely error exit, see F02WUF.
IFAIL=6
The iterative weighted least squares has failed to converge in MAXIT (or default 10) iterations. The value of MAXIT could be increased but it may be advantageous to examine the convergence using the IPRINT option. This may indicate that the convergence is slow because the solution is at a boundary in which case it may be better to reformulate the model.
IFAIL=7
The rank of the model has changed during the weighted least squares iterations. The estimate for β returned may be reasonable, but you should check how the deviance has changed during iterations.
IFAIL=8
The degrees of freedom for error are 0. A saturated model has been fitted.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

The accuracy is determined by TOL as described in Section 5. As the residual sum of squares is a function of μ 2 the accuracy of the β^ will depend on the link used and may be of the order TOL.

8 Parallelism and Performance

G02GAF is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
G02GAF makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

None.

10 Example

The model:
y=1 β 1+β 2 x +ε
for a sample of five observations.

10.1 Program Text

Program Text (g02gafe.f90)

10.2 Program Data

Program Data (g02gafe.d)

10.3 Program Results

Program Results (g02gafe.r)

G02 Chapter Contents
G02 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


G02GBF : NAG Library, Mark 26

G02 Chapter Contents
G02 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

G02GBF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

G02GBF fits a generalized linear model with binomial errors.

2 Specification

SUBROUTINE G02GBF ( LINK, MEAN, OFFSET, WEIGHT, N, X, LDX, M, ISX, IP, Y, T, WT, DEV, IDF, B, IRANK, SE, COV, V, LDV, TOL, MAXIT, IPRINT, EPS, WK, IFAIL)
INTEGER | N, LDX, M, ISX(M), IP, IDF, IRANK, LDV, MAXIT, IPRINT, IFAIL
REAL (KIND=nag_wp) | X(LDX,M), Y(N), T(N), WT(*), DEV, B(IP), SE(IP), COV(IP*(IP+1)/2), V(LDV,IP+7), TOL, EPS, WK((IP*IP+3*IP+22)/2)
CHARACTER(1) | LINK, MEAN, OFFSET, WEIGHT

3 Description

A generalized linear model with binomial errors consists of the following elements:
(a) a set of n observations, yi, from a binomial distribution:
t y πy1-π t-y.
(b) X, a set of p independent variables for each observation, x 1,x 2,…,xp.
(c) a linear model:
η=∑βjxj.
(d) a link between the linear predictor, η, and the mean of the distribution, μ=πt, the link function, η=g μ. The possible link functions are:
(i) | logistic link: η=log μ t-μ ,
(ii) | probit link: η=Φ-1 μt ,
(iii) | complementary log-log link: log-log 1-μt .
(e) a measure of fit, the deviance:
∑i=1 n dev yi,μ^i=∑i=1 n 2 yi log yiμ^i+ti-yi log ti-yi ti-μ^i .
The linear arguments are estimated by iterative weighted least squares. An adjusted dependent variable, z, is formed:
z=η+y-μ dη dμ
and a working weight, w,
w= τ dη dμ 2,   where ​τ=t μ t-μ .
At each iteration an approximation to the estimate of β, β^, is found by the weighted least squares regression of z on X with weights w.
G02GBF finds a QR decomposition of w 1/2 X, i.e., w 1/2 X=QR where R is a p by p triangular matrix and Q is an n by p column orthogonal matrix.
If R is of full rank, then β^ is the solution to
R β^=QTw 1/2 z.
If R is not of full rank a solution is obtained by means of a singular value decomposition (SVD) of R.
R=Q* D 0 0 0 PT,
where D is a k by k diagonal matrix with nonzero diagonal elements, k being the rank of R and w 1/2 X.
This gives the solution
β^=P 1 D-1 Q* 0 0 I QTw 1/2 z,
P 1 being the first k columns of P, i.e., P=P 1P 0.
The iterations are continued until there is only a small change in the deviance.
The initial values for the algorithm are obtained by taking
η^=g y.
The fit of the model can be assessed by examining and testing the deviance, in particular by comparing the difference in deviance between nested models, i.e., when one model is a sub-model of the other. The difference in deviance between two nested models has, asymptotically, a χ 2-distribution with degrees of freedom given by the difference in the degrees of freedom associated with the two deviances.
The arguments estimates, β^, are asymptotically Normally distributed with variance-covariance matrix
  • C = R-1 R-1 T in the full rank case, otherwise
  • C=P 1 D-2 P 1 T .
The residuals and influence statistics can also be examined.
The estimated linear predictor η^=X β^, can be written as H w 1/2 z for an n by n matrix H. The ith diagonal elements of H, hi, give a measure of the influence of the ith values of the independent variables on the fitted regression model. These are sometimes known as leverages.
The fitted values are given by μ^=g-1 η^.
G02GBF also computes the deviance residuals, r:
ri=sign yi-μ^i dev yi,μ^i.
An option allows the use of prior weights in the model.
In many linear regression models the first term is taken as a mean term or an intercept, i.e., x i,1=1, for i=1,2,…,n. This is provided as an option.
Often only some of the possible independent variables are included in a model; the facility to select variables to be included in the model is provided.
If part of the linear predictor can be represented by variables with a known coefficient then this can be included in the model by using an offset, o:
η=o+∑βjxj.
If the model is not of full rank the solution given will be only one of the possible solutions. Other estimates may be obtained by applying constraints to the arguments. These solutions can be obtained by using G02GKF after using G02GBF. Only certain linear combinations of the arguments will have unique estimates, these are known as estimable functions and can be estimated and tested using G02GNF.
Details of the SVD are made available in the form of the matrix P*:
P*= D-1 P 1 T P 0 T .

4 References

Cook R D and Weisberg S (1982) Residuals and Influence in Regression Chapman and Hall
Cox D R (1983) Analysis of Binary Data Chapman and Hall
McCullagh P and Nelder J A (1983) Generalized Linear Models Chapman and Hall

5 Arguments

1:   LINK – CHARACTER(1)Input
On entry: indicates which link function is to be used.
LINK='G'
A logistic link is used.
LINK='P'
A probit link is used.
LINK='C'
A complementary log-log link is used.
Constraint: LINK='G', 'P' or 'C'.
2:   MEAN – CHARACTER(1)Input
On entry: indicates if a mean term is to be included.
MEAN='M'
A mean term, intercept, will be included in the model.
MEAN='Z'
The model will pass through the origin, zero-point.
Constraint: MEAN='M' or 'Z'.
3:   OFFSET – CHARACTER(1)Input
On entry: indicates if an offset is required.
OFFSET='Y'
An offset is required and the offsets must be supplied in the seventh column of V.
OFFSET='N'
No offset is required.
Constraint: OFFSET='N' or 'Y'.
4:   WEIGHT – CHARACTER(1)Input
On entry: indicates if prior weights are to be used.
WEIGHT='U'
No prior weights are used.
WEIGHT='W'
Prior weights are used and weights must be supplied in WT.
Constraint: WEIGHT='U' or 'W'.
5:   N – INTEGERInput
On entry: n, the number of observations.
Constraint: N≥2.
6:   X LDXM – REAL (KIND=nag_wp) arrayInput
On entry: X ij must contain the ith observation for the jth independent variable, for i=1,2,…,N and j=1,2,…,M.
7:   LDX – INTEGERInput
On entry: the first dimension of the array X as declared in the (sub)program from which G02GBF is called.
Constraint: LDX≥N.
8:   M – INTEGERInput
On entry: m, the total number of independent variables.
Constraint: M≥1.
9:   ISX M – INTEGER arrayInput
On entry: indicates which independent variables are to be included in the model.
ISX j>0
The variable contained in the jth column of X is included in the regression model.
Constraints:
  • ISX j≥0, for j=1,2,…,M;
  • if MEAN='M', exactly IP-1 values of ISX must be >0;
  • if MEAN='Z', exactly IP values of ISX must be >0.
10:   IP – INTEGERInput
On entry: the number of independent variables in the model, including the mean or intercept if present.
Constraint: IP>0.
11:   Y N – REAL (KIND=nag_wp) arrayInput
On entry: the observations on the dependent variable, yi, for i=1,2,…,n.
Constraint: 0.0≤Y i≤T i, for i=1,2,…,n.
12:   T N – REAL (KIND=nag_wp) arrayInput
On entry: t, the binomial denominator.
Constraint: T i≥0.0, for i=1,2,…,n.
13:   WT* – REAL (KIND=nag_wp) arrayInput
Note: the dimension of the array WT must be at least N if WEIGHT='W', and at least 1 otherwise.
On entry: if WEIGHT='W', WT must contain the weights to be used in the weighted regression. If WT i=0.0, the ith observation is not included in the model, in which case the effective number of observations is the number of observations with nonzero weights.
If WEIGHT='U', WT is not referenced and the effective number of observations is n.
Constraint: if WEIGHT='W', WT i≥0.0, for i=1,2,…,n.
14:   DEV – REAL (KIND=nag_wp)Output
On exit: the deviance for the fitted model.
15:   IDF – INTEGEROutput
On exit: the degrees of freedom associated with the deviance for the fitted model.
16:   B IP – REAL (KIND=nag_wp) arrayOutput
On exit: the estimates of the parameters of the generalized linear model, β^.
If MEAN='M', the first element of B will contain the estimate of the mean parameter and B i+1 will contain the coefficient of the variable contained in column j of X, where ISX j is the ith positive value in the array ISX.
If MEAN='Z', B i will contain the coefficient of the variable contained in column j of X, where ISX j is the ith positive value in the array ISX.
17:   IRANK – INTEGEROutput
On exit: the rank of the independent variables.
If the model is of full rank, IRANK=IP.
If the model is not of full rank, IRANK is an estimate of the rank of the independent variables. IRANK is calculated as the number of singular values greater that EPS×(largest singular value).
It is possible for the SVD to be carried out but for IRANK to be returned as IP.
18:   SE IP – REAL (KIND=nag_wp) arrayOutput
On exit: the standard errors of the linear parameters.
SE i contains the standard error of the parameter estimate in B i, for i=1,2,…,IP.
19:   COV IP×IP+1/2 – REAL (KIND=nag_wp) arrayOutput
On exit: the upper triangular part of the variance-covariance matrix of the IP parameter estimates given in B. They are stored in packed form by column, i.e., the covariance between the parameter estimate given in B i and the parameter estimate given in B j, j≥i, is stored in COV j×j-1/2+i.
20:   V LDV IP+7 – REAL (KIND=nag_wp) arrayInput/Output
On entry: if OFFSET='N', V need not be set.
If OFFSET='Y', V i 7, for i=1,2,…,n must contain the offset values oi. All other values need not be set.
On exit: auxiliary information on the fitted model.
V i 1 | contains the linear predictor value, ηi, for i=1,2,…,n.
V i 2 | contains the fitted value, μ^i, for i=1,2,…,n.
V i 3 | contains the variance standardization, 1 τi, for i=1,2,…,n.
V i 4 | contains the square root of the working weight, wi 12, for i=1,2,…,n.
V i 5 | contains the deviance residual, ri, for i=1,2,…,n.
V i 6 | contains the leverage, hi, for i=1,2,…,n.
V i 7 | contains the offset, oi, for i=1,2,…,n. If OFFSET='N', all values will be zero.
V ij | for j=8,…,IP+7, contains the results of the QR decomposition or the singular value decomposition.
If the model is not of full rank, i.e., IRANK<IP, the first IP rows of columns 8 to IP+7 contain the P* matrix.
21:   LDV – INTEGERInput
On entry: the first dimension of the array V as declared in the (sub)program from which G02GBF is called.
Constraint: LDV≥N.
22:   TOL – REAL (KIND=nag_wp)Input
On entry: indicates the accuracy required for the fit of the model.
The iterative weighted least squares procedure is deemed to have converged if the absolute change in deviance between iterations is less than TOL×1.0+Current Deviance. This is approximately an absolute precision if the deviance is small and a relative precision if the deviance is large.
If 0.0≤TOL<machine precision, the routine will use 10×machine precision instead.
Constraint: TOL≥0.0.
23:   MAXIT – INTEGERInput
On entry: the maximum number of iterations for the iterative weighted least squares.
If MAXIT=0, a default value of 10 is used.
Constraint: MAXIT≥0.
24:   IPRINT – INTEGERInput
On entry: indicates if the printing of information on the iterations is required.
IPRINT≤0
There is no printing.
IPRINT>0
The following is printed every IPRINT iterations:
  • the deviance,
  • the current estimates,
  • and if the weighted least squares equations are singular, then this is indicated.
When printing occurs the output is directed to the current advisory message unit (see X04ABF).
25:   EPS – REAL (KIND=nag_wp)Input
On entry: the value of EPS is used to decide if the independent variables are of full rank and, if not, what is the rank of the independent variables. The smaller the value of EPS the stricter the criterion for selecting the singular value decomposition.
If 0.0≤EPS<machine precision, the routine will use machine precision instead.
Constraint: EPS≥0.0.
26:   WK IP×IP+3×IP+22/2 – REAL (KIND=nag_wp) arrayWorkspace
27:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, because for this routine the values of the output arguments may be useful even if IFAIL≠0 on exit, the recommended value is -1. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Note: G02GBF may return useful information for one or more of the following detected errors or warnings.
Errors or warnings detected by the routine:
IFAIL=1
On entry, | N<2,
or | M<1,
or | LDX<N,
or | LDV<N,
or | IP<1,
or | LINK≠'G', 'P' or 'C'.
or | MEAN≠'M' or 'Z'.
or | WEIGHT≠'U' or 'W'.
or | OFFSET≠'N' or 'Y'.
or | MAXIT<0,
or | TOL<0.0,
or | EPS<0.0.
IFAIL=2
On entry, WEIGHT='W' and a value of WT<0.0.
IFAIL=3
On entry, | a value of ISX<0,
or | the value of IP is incompatible with the values of MEAN and ISX,
or | IP is greater than the effective number of observations.
IFAIL=4
On entry, T i<0 for some i=1,2,…,n.
IFAIL=5
On entry, | Y i<0.0,
or | Y i>T i for some i=1,2,…,n.
IFAIL=6
A fitted value is at the boundary, i.e., 0.0 or 1.0. This may occur if there are y values of 0.0 or t and the model is too complex for the data. The model should be reformulated with, perhaps, some observations dropped.
IFAIL=7
The singular value decomposition has failed to converge. This is an unlikely error exit.
IFAIL=8
The iterative weighted least squares has failed to converge in MAXIT (or default 10) iterations. The value of MAXIT could be increased but it may be advantageous to examine the convergence using the IPRINT option. This may indicate that the convergence is slow because the solution is at a boundary in which case it may be better to reformulate the model.
IFAIL=9
The rank of the model has changed during the weighted least squares iterations. The estimate for β returned may be reasonable, but you should check how the deviance has changed during iterations.
IFAIL=10
The degrees of freedom for error are 0. A saturated model has been fitted.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

The accuracy will depend on the value of TOL as described in Section 5. As the deviance is a function of log⁡μ the accuracy of the β^ will be only a function of TOL, so TOL should be set smaller than the required accuracy for β^.

8 Parallelism and Performance

G02GBF is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
G02GBF makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

None.

10 Example

A linear trend x=-1,0,1 is fitted to data relating the incidence of carriers of Streptococcus pyogenes to size of tonsils. The data is described in Cox (1983).

10.1 Program Text

Program Text (g02gbfe.f90)

10.2 Program Data

Program Data (g02gbfe.d)

10.3 Program Results

Program Results (g02gbfe.r)

G02 Chapter Contents
G02 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


G02GCF : NAG Library, Mark 26

G02 Chapter Contents
G02 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

G02GCF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

G02GCF fits a generalized linear model with Poisson errors.

2 Specification

SUBROUTINE G02GCF ( LINK, MEAN, OFFSET, WEIGHT, N, X, LDX, M, ISX, IP, Y, WT, A, DEV, IDF, B, IRANK, SE, COV, V, LDV, TOL, MAXIT, IPRINT, EPS, WK, IFAIL)
INTEGER | N, LDX, M, ISX(M), IP, IDF, IRANK, LDV, MAXIT, IPRINT, IFAIL
REAL (KIND=nag_wp) | X(LDX,M), Y(N), WT(*), A, DEV, B(IP), SE(IP), COV(IP*(IP+1)/2), V(LDV,IP+7), TOL, EPS, WK((IP*IP+3*IP+22)/2)
CHARACTER(1) | LINK, MEAN, OFFSET, WEIGHT

3 Description

A generalized linear model with Poisson errors consists of the following elements:
(a) a set of n observations, yi, from a Poisson distribution:
μye-μ y! .
(b) X, a set of p independent variables for each observation, x 1,x 2,…,xp.
(c) a linear model:
η=∑βjxj.
(d) a link between the linear predictor, η, and the mean of the distribution, μ, η=g μ. The possible link functions are:
(i) | exponent link: η=μa, for a constant a,
(ii) | identity link: η=μ,
(iii) | log link: η=log⁡μ,
(iv) | square root link: η=μ,
(v) | reciprocal link: η=1 μ .
(e) a measure of fit, the deviance:
∑i=1 n dev yi,μ^i=∑i=1 n 2 yi log yiμ^i-yi-μ^i .
The linear arguments are estimated by iterative weighted least squares. An adjusted dependent variable, z, is formed:
z=η+y-μ dη dμ
and a working weight, w,
w= τd dη dμ 2,
where τ=μ.
At each iteration an approximation to the estimate of β, β^, is found by the weighted least squares regression of z on X with weights w.
G02GCF finds a QR decomposition of w 1/2 X, i.e., w 1/2 X=QR where R is a p by p triangular matrix and Q is an n by p column orthogonal matrix.
If R is of full rank, then β^ is the solution to:
R β^=QTw 1/2 z.
If R is not of full rank a solution is obtained by means of a singular value decomposition (SVD) of R.
R=Q* D 0 0 0 PT,
where D is a k by k diagonal matrix with nonzero diagonal elements, k being the rank of R and w 1/2 X.
This gives the solution
β^=P 1 D-1 Q* 0 0 I QTw 1/2 z,
P 1 being the first k columns of P, i.e., P=P 1P 0.
The iterations are continued until there is only a small change in the deviance.
The initial values for the algorithm are obtained by taking
η^=g y.
The fit of the model can be assessed by examining and testing the deviance, in particular by comparing the difference in deviance between nested models, i.e., when one model is a sub-model of the other. The difference in deviance between two nested models has, asymptotically, a χ 2-distribution with degrees of freedom given by the difference in the degrees of freedom associated with the two deviances.
The arguments estimates, β^, are asymptotically Normally distributed with variance-covariance matrix
  • C=R-1R-1 T in the full rank case, otherwise
  • C=P 1 D-2 P 1 T.
The residuals and influence statistics can also be examined.
The estimated linear predictor η^=X β^, can be written as H w 1/2 z for an n by n matrix H. The ith diagonal elements of H, hi, give a measure of the influence of the ith values of the independent variables on the fitted regression model. These are known as leverages.
The fitted values are given by μ^=g-1 η^.
G02GCF also computes the deviance residuals, r:
ri=sign yi-μ^i dev yi,μ^i.
An option allows prior weights to be used with the model.
In many linear regression models the first term is taken as a mean term or an intercept, i.e., x i,1=1, for i=1,2,…,n. This is provided as an option.
Often only some of the possible independent variables are included in a model; the facility to select variables to be included in the model is provided.
If part of the linear predictor can be represented by a variables with a known coefficient then this can be included in the model by using an offset, o:
η=o+∑βjxj.
If the model is not of full rank the solution given will be only one of the possible solutions. Other estimates may be obtained by applying constraints to the arguments. These solutions can be obtained by using G02GKF after using G02GCF. Only certain linear combinations of the arguments will have unique estimates, these are known as estimable functions, these can be estimated and tested using G02GNF.
Details of the SVD are made available in the form of the matrix P*:
P*= D-1 P 1 T P 0 T .
The generalized linear model with Poisson errors can be used to model contingency table data; see Cook and Weisberg (1982) and McCullagh and Nelder (1983).

4 References

Cook R D and Weisberg S (1982) Residuals and Influence in Regression Chapman and Hall
McCullagh P and Nelder J A (1983) Generalized Linear Models Chapman and Hall
Plackett R L (1974) The Analysis of Categorical Data Griffin

5 Arguments

1:   LINK – CHARACTER(1)Input
On entry: indicates which link function is to be used.
LINK='E'
An exponent link is used.
LINK='I'
An identity link is used.
LINK='L'
A log link is used;
LINK='S'
A square root link is used.
LINK='R'
A reciprocal link is used.
Constraint: LINK='E', 'I', 'L', 'S' or 'R'.
2:   MEAN – CHARACTER(1)Input
On entry: indicates if a mean term is to be included.
MEAN='M'
A mean term, intercept, will be included in the model.
MEAN='Z'
The model will pass through the origin, zero-point.
Constraint: MEAN='M' or 'Z'.
3:   OFFSET – CHARACTER(1)Input
On entry: indicates if an offset is required.
OFFSET='Y'
An offset is required and the offsets must be supplied in the seventh column of V.
OFFSET='N'
No offset is required.
Constraint: OFFSET='N' or 'Y'.
4:   WEIGHT – CHARACTER(1)Input
On entry: indicates if prior weights are to be used.
WEIGHT='U'
No prior weights are used.
WEIGHT='W'
Prior weights are used and weights must be supplied in WT.
Constraint: WEIGHT='U' or 'W'.
5:   N – INTEGERInput
On entry: n, the number of observations.
Constraint: N≥2.
6:   X LDXM – REAL (KIND=nag_wp) arrayInput
On entry: the matrix of all possible independent variables. X ij must contain the ijth element of X, for i=1,2,…,n and j=1,2,…,M.
7:   LDX – INTEGERInput
On entry: the first dimension of the array X as declared in the (sub)program from which G02GCF is called.
Constraint: LDX≥N.
8:   M – INTEGERInput
On entry: m, the total number of independent variables.
Constraint: M≥1.
9:   ISX M – INTEGER arrayInput
On entry: indicates which independent variables are to be included in the model.
ISX j>0
The variable contained in the jth column of X is included in the regression model.
Constraints:
  • ISX j≥0, for j=1,2,…,M;
  • if MEAN='M', exactly IP-1 values of ISX must be >0;
  • if MEAN='Z', exactly IP values of ISX must be >0.
10:   IP – INTEGERInput
On entry: the number of independent variables in the model, including the mean or intercept if present.
Constraint: IP>0.
11:   Y N – REAL (KIND=nag_wp) arrayInput
On entry: y, observations on the dependent variable.
Constraint: Y i≥0.0, for i=1,2,…,n.
12:   WT* – REAL (KIND=nag_wp) arrayInput
Note: the dimension of the array WT must be at least N if WEIGHT='W', and at least 1 otherwise.
On entry: if WEIGHT='W' >, WT must contain the weights to be used in the weighted regression.
If WT i=0.0, the ith observation is not included in the model, in which case the effective number of observations is the number of observations with nonzero weights.
If WEIGHT='U', WT is not referenced and the effective number of observations is n.
Constraint: if WEIGHT='W', WT i≥0.0, for i=1,2,…,n.
13:   A – REAL (KIND=nag_wp)Input
On entry: if LINK='E', A must contain the power of the exponential.
If LINK≠'E', A is not referenced.
Constraint: if A≠0.0, LINK='E'.
14:   DEV – REAL (KIND=nag_wp)Output
On exit: the deviance for the fitted model.
15:   IDF – INTEGEROutput
On exit: the degrees of freedom asociated with the deviance for the fitted model.
16:   B IP – REAL (KIND=nag_wp) arrayOutput
On exit: the estimates of the parameters of the generalized linear model, β^.
If MEAN='M', the first element of B will contain the estimate of the mean parameter and B i+1 will contain the coefficient of the variable contained in column j of X, where ISX j is the ith positive value in the array ISX.
If MEAN='Z', B i will contain the coefficient of the variable contained in column j of X, where ISX j is the ith positive value in the array ISX.
17:   IRANK – INTEGEROutput
On exit: the rank of the independent variables.
If the model is of full rank, IRANK=IP.
If the model is not of full rank, IRANK is an estimate of the rank of the independent variables. IRANK is calculated as the number of singular values greater that EPS×(largest singular value). It is possible for the SVD to be carried out but for IRANK to be returned as IP.
18:   SE IP – REAL (KIND=nag_wp) arrayOutput
On exit: the standard errors of the linear parameters.
SE i contains the standard error of the parameter estimate in B i, for i=1,2,…,IP.
19:   COV IP×IP+1/2 – REAL (KIND=nag_wp) arrayOutput
On exit: the upper triangular part of the variance-covariance matrix of the IP parameter estimates given in B. They are stored packed by column, i.e., the covariance between the parameter estimate given in B i and the parameter estimate given in B j, j≥i, is stored in COV j×j-1/2+i.
20:   V LDV IP+7 – REAL (KIND=nag_wp) arrayInput/Output
On entry: if OFFSET='N', V need not be set.
If OFFSET='Y', V i 7, for i=1,2,…,n must contain the offset values oi. All other values need not be set.
On exit: auxiliary information on the fitted model.
V i 1 | contains the linear predictor value, ηi, for i=1,2,…,n.
V i 2 | contains the fitted value, μ^i, for i=1,2,…,n.
V i 3 | contains the variance standardization, 1 τi, for i=1,2,…,n.
V i 4 | contains the square root of the working weight, wi 12, for i=1,2,…,n.
V i 5 | contains the deviance residual, ri, for i=1,2,…,n.
V i 6 | contains the leverage, hi, for i=1,2,…,n.
V i 7 | contains the offset, oi, for i=1,2,…,n. If OFFSET='N', all values will be zero.
V ij | for j=8,…,IP+7, contains the results of the QR decomposition or the singular value decomposition.
If the model is not of full rank, i.e., IRANK<IP, the first IP rows of columns 8 to IP+7 contain the P* matrix.
21:   LDV – INTEGERInput
On entry: the first dimension of the array V as declared in the (sub)program from which G02GCF is called.
Constraint: LDV≥N.
22:   TOL – REAL (KIND=nag_wp)Input
On entry: indicates the accuracy required for the fit of the model.
The iterative weighted least squares procedure is deemed to have converged if the absolute change in deviance between iterations is less than TOL×1.0+Current Deviance. This is approximately an absolute precision if the deviance is small and a relative precision if the deviance is large.
If 0.0≤TOL<machine precision, the routine will use 10×machine precision instead.
Constraint: TOL≥0.0.
23:   MAXIT – INTEGERInput
On entry: the maximum number of iterations for the iterative weighted least squares.
If MAXIT=0, a default value of 10 is used.
Constraint: MAXIT≥0.
24:   IPRINT – INTEGERInput
On entry: indicates if the printing of information on the iterations is required.
IPRINT≤0
There is no printing.
IPRINT>0
Every IPRINT iteration, the following are printed:
  • the deviance;
  • the current estimates;
  • and if the weighted least squares equations are singular then this is indicated.
When printing occurs the output is directed to the current advisory message unit (see X04ABF).
25:   EPS – REAL (KIND=nag_wp)Input
On entry: the value of EPS is used to decide if the independent variables are of full rank and, if not, what is the rank of the independent variables. The smaller the value of EPS the stricter the criterion for selecting the singular value decomposition.
If 0.0≤EPS<machine precision, the routine will use machine precision instead.
Constraint: EPS≥0.0.
26:   WK IP×IP+3×IP+22/2 – REAL (KIND=nag_wp) arrayWorkspace
27:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, because for this routine the values of the output arguments may be useful even if IFAIL≠0 on exit, the recommended value is -1. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Note: G02GCF may return useful information for one or more of the following detected errors or warnings.
Errors or warnings detected by the routine:
IFAIL=1
On entry, | N<2,
or | M<1,
or | LDX<N,
or | LDV<N,
or | IP<1,
or | LINK≠'E', 'I', 'L', 'S' or 'R',
or | LINK='E' and A=0.0,
or | MEAN≠'M' or 'Z',
or | WEIGHT≠'U' or 'W',
or | OFFSET≠'N' or 'Y',
or | MAXIT<0,
or | TOL<0.0,
or | EPS<0.0.
IFAIL=2
On entry, WEIGHT='W' and a value of WT<0.0.
IFAIL=3
On entry, | a value of ISX<0,
or | the value of IP is incompatible with the values of MEAN and ISX,
or | IP is greater than the effective number of observations.
IFAIL=4
On entry, Y i<0.0 for some i=1,2,…,n.
IFAIL=5
A fitted value is at the boundary, i.e., μ^=0.0. This may occur if there are y values of 0.0 and the model is too complex for the data. The model should be reformulated with, perhaps, some observations dropped.
IFAIL=6
The singular value decomposition has failed to converge. This is an unlikely error exit.
IFAIL=7
The iterative weighted least squares has failed to converge in MAXIT (or default 10) iterations. The value of MAXIT could be increased but it may be advantageous to examine the convergence using the IPRINT option. This may indicate that the convergence is slow because the solution is at a boundary in which case it may be better to reformulate the model.
IFAIL=8
The rank of the model has changed during the weighted least squares iterations. The estimate for β returned may be reasonable, but you should check how the deviance has changed during iterations.
IFAIL=9
The degrees of freedom for error are 0. A saturated model has been fitted.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

The accuracy depends on the value of TOL as described in Section 5. As the deviance is a function of log⁡μ the accuracy of the β^ will only be a function of TOL. TOL should therefore be set smaller than the accuracy required for β^.

8 Parallelism and Performance

G02GCF is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
G02GCF makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

None.

10 Example

A 3 by 5 contingency table given by Plackett (1974) is analysed by fitting terms for rows and columns. The table is:
141 67 114 79 39 131 66 143 72 35 36 14 38 28 16 .

10.1 Program Text

Program Text (g02gcfe.f90)

10.2 Program Data

Program Data (g02gcfe.d)

10.3 Program Results

Program Results (g02gcfe.r)

G02 Chapter Contents
G02 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


G02GDF : NAG Library, Mark 26

G02 Chapter Contents
G02 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

G02GDF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

G02GDF fits a generalized linear model with gamma errors.

2 Specification

SUBROUTINE G02GDF ( LINK, MEAN, OFFSET, WEIGHT, N, X, LDX, M, ISX, IP, Y, WT, S, A, DEV, IDF, B, IRANK, SE, COV, V, LDV, TOL, MAXIT, IPRINT, EPS, WK, IFAIL)
INTEGER | N, LDX, M, ISX(M), IP, IDF, IRANK, LDV, MAXIT, IPRINT, IFAIL
REAL (KIND=nag_wp) | X(LDX,M), Y(N), WT(*), S, A, DEV, B(IP), SE(IP), COV(IP*(IP+1)/2), V(LDV,IP+7), TOL, EPS, WK((IP*IP+3*IP+22)/2)
CHARACTER(1) | LINK, MEAN, OFFSET, WEIGHT

3 Description

A generalized linear model with gamma errors consists of the following elements:
(a) a set of n observations, yi, from a gamma distribution with probability density function:
1 Γ ν νy μ ν exp-νy μ 1 y
ν being constant for the sample.
(b) X, a set of p independent variables for each observation, x 1,x 2,…,xp.
(c) a linear model:
η=∑βjxj.
(d) a link between the linear predictor, η, and the mean of the distribution, μ, η=g μ. The possible link functions are:
(i) | exponent link: η=μa, for a constant a,
(ii) | identity link: η=μ,
(iii) | log link: η=log⁡μ,
(iv) | square root link: η=μ,
(v) | reciprocal link: η= 1 μ .
(e) a measure of fit, an adjusted deviance. This is a function related to the deviance, but defined for y=0:
∑i=1 n dev*yi,μ^i=∑i=1 n 2 log μ^i+yiμ^i .
The linear arguments are estimated by iterative weighted least squares. An adjusted dependent variable, z, is formed:
z=η+y-μ dη dμ
and a working weight, w,
w= τ dη dμ 2 ,   where  τ=1 μ.
At each iteration an approximation to the estimate of β, β^ is found by the weighted least squares regression of z on X with weights w.
G02GDF finds a QR decomposition of w 12 X, i.e.,
  • w 12 X=QR where R is a p by p triangular matrix and Q is an n by p column orthogonal matrix.
If R is of full rank then β^ is the solution to:
  • R β^=QTw 12 z
If R is not of full rank a solution is obtained by means of a singular value decomposition (SVD) of R.
R=Q* D 0 0 0 PT.
where D is a k by k diagonal matrix with nonzero diagonal elements, k being the rank of R and w 12 X.
This gives the solution
β^=P 1 D-1 Q* 0 0 I QTw 12 z,
where P 1 is the first k columns of P, i.e., P=P 1P 0.
The iterations are continued until there is only a small change in the deviance.
The initial values for the algorithm are obtained by taking
η^=g y.
The scale argument, ν-1 is estimated by a moment estimator:
ν^ -1 = ∑ i=1 n yi - μ^i / μ^ 2 n-k .
The fit of the model can be assessed by examining and testing the deviance, in particular, by comparing the difference in deviance between nested models, i.e., when one model is a sub-model of the other. The difference in deviance or adjusted deviance between two nested models with known ν has, asymptotically, a χ 2-distribution with degrees of freedom given by the difference in the degrees of freedom associated with the two deviances.
The arguments estimates, β^, are asymptotically Normally distributed with variance-covariance matrix:
  • C=R-1R-1 Tν-1 in the full rank case, otherwise
  • C=P 1 D-2 P 1 T ν-1.
The residuals and influence statistics can also be examined.
The estimated linear predictor η^=X β^, can be written as H w 12 z for an n by n matrix H. The ith diagonal elements of H, hi, give a measure of the influence of the ith values of the independent variables on the fitted regression model. These are known as leverages.
The fitted values are given by μ^=g-1 η^.
G02GDF also computes the Anscombe residuals, r:
ri = 3 y i 13 - μ^ i 13 μ^ i 13 .
An option allows the use of prior weights, ωi. This gives a model with:
νi = ν ωi .
In many linear regression models the first term is taken as a mean term or an intercept, i.e., x i,1 = 1 , for i=1,2,…,n . This is provided as an option.
Often only some of the possible independent variables are included in a model, the facility to select variables to be included in the model is provided.
If part of the linear predictor can be represented by a variables with a known coefficient then this can be included in the model by using an offset, o:
η = o + ∑ βj xj .
If the model is not of full rank the solution given will be only one of the possible solutions. Other estimates may be obtained by applying constraints to the arguments. These solutions can be obtained by using G02GKF after using G02GDF. Only certain linear combinations of the arguments will have unique estimates, these are known as estimable functions, and can be estimated and tested using G02GNF.
Details of the SVD are made available in the form of the matrix P*:
P* = D-1 P 1 T P 0 T .

4 References

Cook R D and Weisberg S (1982) Residuals and Influence in Regression Chapman and Hall
McCullagh P and Nelder J A (1983) Generalized Linear Models Chapman and Hall

5 Arguments

1:   LINK – CHARACTER(1)Input
On entry: indicates which link function is to be used.
LINK='E'
An exponential link is used.
LINK='I'
An identity link is used.
LINK='L'
A log link is used.
LINK='S'
A square root link is used.
LINK='R'
A reciprocal link is used.
Constraint: LINK='E', 'I', 'L', 'S' or 'R'.
2:   MEAN – CHARACTER(1)Input
On entry: indicates if a mean term is to be included.
MEAN='M'
A mean term, intercept, will be included in the model.
MEAN='Z'
The model will pass through the origin, zero-point.
Constraint: MEAN='M' or 'Z'.
3:   OFFSET – CHARACTER(1)Input
On entry: indicates if an offset is required.
OFFSET='Y'
An offset is required and the offsets must be supplied in the seventh column of V.
OFFSET='N'
No offset is required.
Constraint: OFFSET='N' or 'Y'.
4:   WEIGHT – CHARACTER(1)Input
On entry: indicates if prior weights are to be used.
WEIGHT='U'
No prior weights are used.
WEIGHT='W'
Prior weights are used and weights must be supplied in WT.
Constraint: WEIGHT='U' or 'W'.
5:   N – INTEGERInput
On entry: n, the number of observations.
Constraint: N≥2.
6:   X LDXM – REAL (KIND=nag_wp) arrayInput
On entry: X ij must contain the ith observation for the jth independent variable, for i=1,2,…,N and j=1,2,…,M.
7:   LDX – INTEGERInput
On entry: the first dimension of the array X as declared in the (sub)program from which G02GDF is called.
Constraint: LDX≥N.
8:   M – INTEGERInput
On entry: m, the total number of independent variables.
Constraint: M≥1.
9:   ISX M – INTEGER arrayInput
On entry: indicates which independent variables are to be included in the model.
If ISX j>0, the variable contained in the jth column of X is included in the regression model.
Constraints:
  • ISX j≥0, for i=1,2,…,M;
  • if MEAN='M', exactly IP-1 values of ISX must be >0;
  • if MEAN='Z', exactly IP values of ISX must be >0.
10:   IP – INTEGERInput
On entry: the number of independent variables in the model, including the mean or intercept if present.
Constraint: IP>0.
11:   Y N – REAL (KIND=nag_wp) arrayInput
On entry: y, the dependent variable.
Constraint: Y i≥0.0, for i=1,2,…,n.
12:   WT* – REAL (KIND=nag_wp) arrayInput
Note: the dimension of the array WT must be at least N if WEIGHT='W', and at least 1 otherwise.
On entry: if WEIGHT='W', WT must contain the weights to be used in the weighted regression. If WT i=0.0, the ith observation is not included in the model, in which case the effective number of observations is the number of observations with nonzero weights.
If WEIGHT='U', WT is not referenced and the effective number of observations is n.
Constraint: if WEIGHT='W', WT i≥0.0, for i=1,2,…,n.
13:   S – REAL (KIND=nag_wp)Input/Output
On entry: the scale argument for the gamma model, ν-1.
S=0.0
The scale argument is estimated with the routine using the formula described in Section 3.
Constraint: S≥0.0.
On exit: if on input S=0.0, S contains the estimated value of the scale argument, ν^-1.
If on input S≠0.0, S is unchanged on exit.
14:   A – REAL (KIND=nag_wp)Input
On entry: if LINK='E', A must contain the power of the exponential.
If LINK≠'E', A is not referenced.
Constraint: if LINK='E', A≠0.0.
15:   DEV – REAL (KIND=nag_wp)Output
On exit: the adjusted deviance for the fitted model.
16:   IDF – INTEGEROutput
On exit: the degrees of freedom asociated with the deviance for the fitted model.
17:   B IP – REAL (KIND=nag_wp) arrayOutput
On exit: the estimates of the parameters of the generalized linear model, β^.
If MEAN='M', the first element of B will contain the estimate of the mean parameter and B i+1 will contain the coefficient of the variable contained in column j of X, where ISX j is the ith positive value in the array ISX.
If MEAN='Z', B i will contain the coefficient of the variable contained in column j of X, where ISX j is the ith positive value in the array ISX.
18:   IRANK – INTEGEROutput
On exit: the rank of the independent variables.
If the model is of full rank then IRANK=IP.
If the model is not of full rank then IRANK is an estimate of the rank of the independent variables. IRANK is calculated as the number of singular values greater that EPS×(largest singular value). It is possible for the SVD to be carried out but for IRANK to be returned as IP.
19:   SE IP – REAL (KIND=nag_wp) arrayOutput
On exit: the standard errors of the linear parameters.
SE i contains the standard error of the parameter estimate in B i, for i=1,2,…,IP.
20:   COV IP×IP+1/2 – REAL (KIND=nag_wp) arrayOutput
On exit: the upper triangular part of the variance-covariance matrix of the IP parameter estimates given in B. They are stored in packed form by column, i.e., the covariance between the parameter estimate given in B i and the parameter estimate given in B j, j≥i, is stored in COV j×j-1/2+i.
21:   V LDV IP+7 – REAL (KIND=nag_wp) arrayInput/Output
On entry: if OFFSET='N', V need not be set.
If OFFSET='Y', V i 7, for i=1,2,…,n, must contain the offset values oi. All other values need not be set.
On exit: auxiliary information on the fitted model.
V i 1 | contains the linear predictor value, ηi, for i=1,2,…,n.
V i 2 | contains the fitted value, μ^i, for i=1,2,…,n.
V i 3 | contains the variance standardization, 1 τi, for i=1,2,…,n.
V i 4 | contains the square root of the working weight, wi 12, for i=1,2,…,n.
V i 5 | contains the Anscombe residual, ri, for i=1,2,…,n.
V i 6 | contains the leverage, hi, for i=1,2,…,n.
V i 7 | contains the offset, oi, for i=1,2,…,n. If OFFSET='N', all values will be zero.
V ij, | for j=8,…,IP+7, contains the results of the QR decomposition or the singular value decomposition.
If the model is not of full rank, i.e., IRANK<IP, the first IP rows of columns 8 to IP+7 contain the P* matrix.
22:   LDV – INTEGERInput
On entry: the first dimension of the array V as declared in the (sub)program from which G02GDF is called.
Constraint: LDV≥N.
23:   TOL – REAL (KIND=nag_wp)Input
On entry: indicates the accuracy required for the fit of the model.
The iterative weighted least squares procedure is deemed to have converged if the absolute change in deviance between iterations is less than TOL×1.0+Current Deviance. This is approximately an absolute precision if the deviance is small and a relative precision if the deviance is large.
If 0.0≤TOL<machine precision then the routine will use 10×machine precision instead.
Constraint: TOL≥0.0.
24:   MAXIT – INTEGERInput
On entry: the maximum number of iterations for the iterative weighted least squares.
MAXIT=0
A default value of 10 is used.
Constraint: MAXIT≥0.
25:   IPRINT – INTEGERInput
On entry: indicates if the printing of information on the iterations is required.
IPRINT≤0
There is no printing.
IPRINT>0
Every IPRINT iteration, the following are printed:
  • the deviance;
  • the current estimates;
  • and if the weighted least squares equations are singular then this is indicated.
When printing occurs the output is directed to the current advisory message unit (see X04ABF).
26:   EPS – REAL (KIND=nag_wp)Input
On entry: the value of EPS is used to decide if the independent variables are of full rank and, if not, what is the rank of the independent variables. The smaller the value of EPS the stricter the criterion for selecting the singular value decomposition.
If 0.0≤EPS<machine precision then the routine will use machine precision instead.
Constraint: EPS≥0.0.
27:   WK IP×IP+3×IP+22/2 – REAL (KIND=nag_wp) arrayWorkspace
28:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, because for this routine the values of the output arguments may be useful even if IFAIL≠0 on exit, the recommended value is -1. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Note: G02GDF may return useful information for one or more of the following detected errors or warnings.
Errors or warnings detected by the routine:
IFAIL=1
On entry, | N<2,
or | M<1,
or | LDX<N,
or | LDV<N,
or | IP<1,
or | LINK≠'E','I','L','S' or 'R',
or | S<0.0,
or | LINK='E' and A=0.0,
or | MEAN≠'M' or 'Z',
or | WEIGHT≠'U' or 'W',
or | OFFSET≠'N' or 'Y',
or | MAXIT<0,
or | TOL<0.0,
or | EPS<0.0.
IFAIL=2
On entry, WEIGHT='W' and a value of WT<0.0.
IFAIL=3
On entry, | a value of ISX<0,
or | the value of IP is incompatible with the values of MEAN and ISX,
or | IP is greater than the effective number of observations.
IFAIL=4
On entry, Y i<0.0 for some i=1,2,…,n.
IFAIL=5
A fitted value is at the boundary, i.e., μ^=0.0. This may occur if there are small values of y and the model is not suitable for the data. The model should be reformulated with, perhaps, some observations dropped.
IFAIL=6
The singular value decomposition has failed to converge. This is an unlikely error exit.
IFAIL=7
The iterative weighted least squares has failed to converge in MAXIT (or default 10) iterations. The value of MAXIT could be increased but it may be advantageous to examine the convergence using the IPRINT option. This may indicate that the convergence is slow because the solution is at a boundary in which case it may be better to reformulate the model.
IFAIL=8
The rank of the model has changed during the weighted least squares iterations. The estimate for β returned may be reasonable, but you should check how the deviance has changed during iterations.
IFAIL=9
The degrees of freedom for error are 0. A saturated model has been fitted.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

The accuracy depends on TOL as described in Section 5. As the adjusted deviance is a function of log⁡μ, the accuracy of the β^s will be a function of TOL, so TOL should be set to a smaller value than the accuracy required for β^.

8 Parallelism and Performance

G02GDF is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
G02GDF makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

None.

10 Example

A set of 10 observations from two groups is input and a model for the two groups is fitted.

10.1 Program Text

Program Text (g02gdfe.f90)

10.2 Program Data

Program Data (g02gdfe.d)

10.3 Program Results

Program Results (g02gdfe.r)

G02 Chapter Contents
G02 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


G02GKF : NAG Library, Mark 26

G02 Chapter Contents
G02 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

G02GKF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

G02GKF calculates the estimates of the arguments of a generalized linear model for given constraints from the singular value decomposition results.

2 Specification

SUBROUTINE G02GKF ( IP, ICONST, V, LDV, C, LDC, B, S, SE, COV, WK, IFAIL)
INTEGER | IP, ICONST, LDV, LDC, IFAIL
REAL (KIND=nag_wp) | V(LDV,IP+7), C(LDC,ICONST), B(IP), S, SE(IP), COV(IP*(IP+1)/2), WK(2*IP*IP+IP*ICONST+2*ICONST*ICONST+4*ICONST)

3 Description

G02GKF computes the estimates given a set of linear constraints for a generalized linear model which is not of full rank. It is intended for use after a call to G02GAF, G02GBF, G02GCF or G02GDF.
In the case of a model not of full rank the routines use a singular value decomposition to find the parameter estimates, β^svd, and their variance-covariance matrix. Details of the SVD are made available in the form of the matrix P*:
P*= D-1 P 1 T P 0 T
as described by G02GAF, G02GBF, G02GCF and G02GDF. Alternative solutions can be formed by imposing constraints on the arguments. If there are p arguments and the rank of the model is k then nc=p-k constraints will have to be imposed to obtain a unique solution.
Let C be a p by nc matrix of constraints, such that
CT β=0,
then the new parameter estimates β^c are given by:
β^c =A β^svd =I-P 0 CT P 0-1 β^svd,   where ​I​ is the identity matrix,
and the variance-covariance matrix is given by
A P 1 D-2 P 1 T AT
provided CT P 0-1 exists.

4 References

Golub G H and Van Loan C F (1996) Matrix Computations (3rd Edition) Johns Hopkins University Press, Baltimore
McCullagh P and Nelder J A (1983) Generalized Linear Models Chapman and Hall
Searle S R (1971) Linear Models Wiley

5 Arguments

1:   IP – INTEGERInput
On entry: p, the number of terms in the linear model.
Constraint: IP≥1.
2:   ICONST – INTEGERInput
On entry: the number of constraints to be imposed on the arguments, nc.
Constraint: 0<ICONST<IP.
3:   V LDV IP+7 – REAL (KIND=nag_wp) arrayInput
On entry: the array V as returned by G02GAF, G02GBF, G02GCF or G02GDF.
4:   LDV – INTEGERInput
On entry: the first dimension of the array V as declared in the (sub)program from which G02GKF is called.
Constraint: LDV≥IP.
LDV should be as supplied to G02GAF, G02GBF, G02GCF or G02GDF
5:   C LDCICONST – REAL (KIND=nag_wp) arrayInput
On entry: contains the ICONST constraints stored by column, i.e., the ith constraint is stored in the ith column of C.
6:   LDC – INTEGERInput
On entry: the first dimension of the array C as declared in the (sub)program from which G02GKF is called.
Constraint: LDC≥IP.
7:   B IP – REAL (KIND=nag_wp) arrayInput/Output
On entry: the parameter estimates computed by using the singular value decomposition, β^svd.
On exit: the parameter estimates of the arguments with the constraints imposed, β^c.
8:   S – REAL (KIND=nag_wp)Input
On entry: the estimate of the scale argument.
For results from G02GAF and G02GDF then S is the scale argument for the model.
For results from G02GBF and G02GCF then S should be set to 1.0.
Constraint: S>0.0.
9:   SE IP – REAL (KIND=nag_wp) arrayOutput
On exit: the standard error of the parameter estimates in B.
10:   COV IP×IP+1/2 – REAL (KIND=nag_wp) arrayOutput
On exit: the upper triangular part of the variance-covariance matrix of the IP parameter estimates given in B. They are stored packed by column, i.e., the covariance between the parameter estimate given in B i and the parameter estimate given in B j, j≥i, is stored in COV j×j-1/2+i.
11:   WK 2×IP×IP+IP×ICONST+2×ICONST×ICONST+4×ICONST – REAL (KIND=nag_wp) arrayWorkspace
Note: a simple upper bound for the size of the workspace is 5×IP×IP+4×IP.
12:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, | IP<1.
or | ICONST≥IP,
or | ICONST≤0,
or | LDV<IP,
or | LDC<IP,
or | S≤0.0.
IFAIL=2
C does not give a model of full rank.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

It should be noted that due to rounding errors an argument that should be zero when the constraints have been imposed may be returned as a value of order machine precision.

8 Parallelism and Performance

G02GKF is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
G02GKF makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

G02GKF is intended for use in situations in which dummy (0–1) variables have been used such as in the analysis of designed experiments when you do not wish to change the arguments of the model to give a full rank model. The routine is not intended for situations in which the relationships between the independent variables are only approximate.

10 Example

A loglinear model is fitted to a 3 by 5 contingency table by G02GCF. The model consists of terms for rows and columns. The table is
141 67 114 79 39 131 66 143 72 35 36 14 38 28 16 .
The constraints that the sum of row effects and the sum of column effects are zero are then read in and the parameter estimates with these constraints imposed are computed by G02GKF and printed.

10.1 Program Text

Program Text (g02gkfe.f90)

10.2 Program Data

Program Data (g02gkfe.d)

10.3 Program Results

Program Results (g02gkfe.r)

G02 Chapter Contents
G02 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


G02GNF : NAG Library, Mark 26

G02 Chapter Contents
G02 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

G02GNF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

G02GNF gives the estimate of an estimable function along with its standard error from the results from fitting a generalized linear model.

2 Specification

SUBROUTINE G02GNF ( IP, IRANK, B, COV, V, LDV, F, EST, STAT, SESTAT, Z, TOL, WK, IFAIL)
INTEGER | IP, IRANK, LDV, IFAIL
REAL (KIND=nag_wp) | B(IP), COV(IP*(IP+1)/2), V(LDV,IP+7), F(IP), STAT, SESTAT, Z, TOL, WK(IP)
LOGICAL | EST

3 Description

G02GNF computes the estimates of an estimable function for a generalized linear model which is not of full rank. It is intended for use after a call to G02GAF, G02GBF, G02GCF or G02GDF. An estimable function is a linear combination of the arguments such that it has a unique estimate. For a full rank model all linear combinations of arguments are estimable.
In the case of a model not of full rank the routines use a singular value decomposition (SVD) to find the parameter estimates, β^, and their variance-covariance matrix. Given the upper triangular matrix R obtained from the QR decomposition of the independent variables the SVD gives
R=Q* D 0 0 0 PT,
where D is a k by k diagonal matrix with nonzero diagonal elements, k being the rank of R, and Q* and P are p by p orthogonal matrices. This leads to a solution:
β^=P 1 D-1 Q*1 T c 1,
P 1 being the first k columns of P, i.e., P=P 1P 0; Q*1 being the first k columns of Q*, and c 1 being the first p elements of c.
Details of the SVD are made available in the form of the matrix P*:
P*= D-1 P 1 T P 0 T
as described by G02GAF, G02GBF, G02GCF and G02GDF.
A linear function of the arguments, F=fT β, can be tested to see if it is estimable by computing ζ= P 0 T f. If ζ is zero, then the function is estimable, if not; the function is not estimable. In practice ζ is tested against some small quantity η.
Given that F is estimable it can be estimated by fT β^ and its standard error calculated from the variance-covariance matrix of β^, Cβ, as
se F=fT Cβ f.
Also a z statistic
z=fT β^ se F ,
can be computed. The distribution of z will be approximately Normal.

4 References

Golub G H and Van Loan C F (1996) Matrix Computations (3rd Edition) Johns Hopkins University Press, Baltimore
McCullagh P and Nelder J A (1983) Generalized Linear Models Chapman and Hall
Searle S R (1971) Linear Models Wiley

5 Arguments

1:   IP – INTEGERInput
On entry: p, the number of terms in the linear model.
Constraint: IP≥1.
2:   IRANK – INTEGERInput
On entry: k, the rank of the dependent variables.
Constraint: 1≤IRANK≤IP.
3:   B IP – REAL (KIND=nag_wp) arrayInput
On entry: the IP values of the estimates of the arguments of the model, β^.
4:   COV IP×IP+1/2 – REAL (KIND=nag_wp) arrayInput
On entry: the upper triangular part of the variance-covariance matrix of the IP parameter estimates given in B. They are stored packed by column, i.e., the covariance between the parameter estimate given in B i and the parameter estimate given in B j, j≥i, is stored in COV j×j-1/2+i.
5:   V LDV IP+7 – REAL (KIND=nag_wp) arrayInput
On entry: as returned by G02GAF, G02GBF, G02GCF and G02GDF.
6:   LDV – INTEGERInput
On entry: the first dimension of the array V as declared in the (sub)program from which G02GNF is called.
Constraint: LDV≥IP.
7:   F IP – REAL (KIND=nag_wp) arrayInput
On entry: f, the linear function to be estimated.
8:   EST – LOGICALOutput
On exit: indicates if the function was estimable.
EST=.TRUE.
The function is estimable.
EST=.FALSE.
The function is not estimable and STAT, SESTAT and Z are not set.
9:   STAT – REAL (KIND=nag_wp)Output
On exit: if EST=.TRUE., STAT contains the estimate of the function, fT β^
10:   SESTAT – REAL (KIND=nag_wp)Output
On exit: if EST=.TRUE., SESTAT contains the standard error of the estimate of the function, se F.
11:   Z – REAL (KIND=nag_wp)Output
On exit: if EST=.TRUE., Z contains the z statistic for the test of the function being equal to zero.
12:   TOL – REAL (KIND=nag_wp)Input
On entry: the tolerance value used in the check for estimability, η.
If TOL≤0.0 then ε, where ε is the machine precision, is used instead.
13:   WK IP – REAL (KIND=nag_wp) arrayWorkspace
14:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, because for this routine the values of the output arguments may be useful even if IFAIL≠0 on exit, the recommended value is -1. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Note: G02GNF may return useful information for one or more of the following detected errors or warnings.
Errors or warnings detected by the routine:
IFAIL=1
On entry, | IP<1,
or | IRANK<1,
or | IRANK>IP,
or | LDV<IP.
IFAIL=2
On entry, IRANK=IP. In this case EST is returned as true and all statistics are calculated.
IFAIL=3
Standard error of statistic =0.0; this may be due to rounding errors if the standard error is very small or due to mis-specified inputs COV and F.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

The computations are believed to be stable.

8 Parallelism and Performance

G02GNF makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The value of estimable functions is independent of the solution chosen from the many possible solutions. While G02GNF may be used to estimate functions of the arguments of the model as computed by G02GKF, βc, these must be expressed in terms of the original arguments, β. The relation between the two sets of arguments may not be straightforward.

10 Example

A loglinear model is fitted to a 3 by 5 contingency table by G02GCF. The model consists of terms for rows and columns. The table is:
141 67 114 79 39 131 66 143 72 35 36 14 38 28 16
The number of functions to be tested is read in, then the linear functions themselves are read in and tested with G02GNF. The results of G02GNF are printed.

10.1 Program Text

Program Text (g02gnfe.f90)

10.2 Program Data

Program Data (g02gnfe.d)

10.3 Program Results

Program Results (g02gnfe.r)

G02 Chapter Contents
G02 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


G02GPF : NAG Library, Mark 26

G02 Chapter Contents
G02 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

G02GPF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

G02GPF allows prediction from a generalized linear model fit via G02GAF, G02GBF, G02GCF or G02GDF.

2 Specification

SUBROUTINE G02GPF ( ERRFN, LINK, MEAN, OFFSET, WEIGHT, N, X, LDX, M, ISX, IP, T, OFF, WT, S, A, B, COV, VFOBS, ETA, SEETA, PRED, SEPRED, IFAIL)
INTEGER | N, LDX, M, ISX(M), IP, IFAIL
REAL (KIND=nag_wp) | X(LDX,*), T(*), OFF(*), WT(*), S, A, B(IP), COV(IP*(IP+1)/2), ETA(N), SEETA(N), PRED(N), SEPRED(N)
LOGICAL | VFOBS
CHARACTER(1) | ERRFN, LINK, MEAN, OFFSET, WEIGHT

3 Description

A generalized linear model consists of the following elements:
(i) | A suitable distribution for the dependent variable y.
(ii) | A linear model, with linear predictor η=Xβ, where X is a matrix of independent variables and β a column vector of p parameters.
(iii) | A link function g. between the expected value of y and the linear predictor, that is E y=μ=g η.
In order to predict from a generalized linear model, that is estimate a value for the dependent variable, y, given a set of independent variables X, the matrix X must be supplied, along with values for the parameters β and their associated variance-covariance matrix, C. Suitable values for β and C are usually estimated by first fitting the prediction model to a training dataset with known responses, using for example G02GAF, G02GBF, G02GCF or G02GDF. The predicted variable, and its standard error can then be obtained from:
y^ = g-1 η ,   se y^ = δ g-1 x δx η se η + Ifobs Var y
where
η=o+Xβ ,   se η = diag⁡XC XT ,
o is a vector of offsets and Ifobs=0, if the variance of future observations is not taken into account, and 1 otherwise. Here diag⁡A indicates the diagonal elements of matrix A.
If required, the variance for the ith future observation, Var yi, can be calculated as:
Var yi = ϕ V θ wi
where wi is a weight, ϕ is the scale (or dispersion) parameter, and V θ is the variance function. Both the scale parameter and the variance function depend on the distribution used for the y, with:
Poisson | V θ=μi, ϕ=1
binomial | V θ=μi ti-μi ti, ϕ=1
Normal | V θ=1
gamma | V θ=μi 2
In the cases of a Normal and gamma error structure, the scale parameter (ϕ), is supplied by you. This value is usually obtained from the routine used to fit the prediction model. In many cases, for a Normal error structure, ϕ=σ^2, i.e., the estimated variance.

4 References

McCullagh P and Nelder J A (1983) Generalized Linear Models Chapman and Hall

5 Arguments

1:   ERRFN – CHARACTER(1)Input
On entry: indicates the distribution used to model the dependent variable, y.
ERRFN='B'
The binomial distribution is used.
ERRFN='G'
The gamma distribution is used.
ERRFN='N'
The Normal (Gaussian) distribution is used.
ERRFN='P'
The Poisson distribution is used.
Constraint: ERRFN='B', 'G', 'N' or 'P'.
2:   LINK – CHARACTER(1)Input
On entry: indicates which link function to be used.
LINK='C'
A complementary log-log link is used.
LINK='E'
An exponent link is used.
LINK='G'
A logistic link is used.
LINK='I'
An identity link is used.
LINK='L'
A log link is used.
LINK='P'
A probit link is used.
LINK='R'
A reciprocal link is used.
LINK='S'
A square root link is used.
Details on the functional form of the different links can be found in the G02 Chapter Introduction.
Constraints:
  • if ERRFN='B', LINK='C', 'G' or 'P';
  • otherwise LINK='E', 'I', 'L', 'R' or 'S'.
3:   MEAN – CHARACTER(1)Input
On entry: indicates if a mean term is to be included.
MEAN='M'
A mean term, intercept, will be included in the model.
MEAN='Z'
The model will pass through the origin, zero-point.
Constraint: MEAN='M' or 'Z'.
4:   OFFSET – CHARACTER(1)Input
On entry: indicates if an offset is required.
OFFSET='Y'
An offset must be supplied in OFF.
OFFSET='N'
OFF is not referenced.
Constraint: OFFSET='Y' or 'N'.
5:   WEIGHT – CHARACTER(1)Input
On entry: if VFOBS=.TRUE. indicates if weights are used, otherwise WEIGHT is not referenced.
WEIGHT='U'
No weights are used.
WEIGHT='W'
Weights are used and must be supplied in WT.
Constraint: if VFOBS=.TRUE., WEIGHT='U' or 'W'.
6:   N – INTEGERInput
On entry: n, the number of observations.
Constraint: N≥1.
7:   X LDX* – REAL (KIND=nag_wp) arrayInput
Note: the second dimension of the array X must be at least M.
On entry: X ij must contain the ith observation for the jth independent variable, for i=1,2,…,N and j=1,2,…,M.
8:   LDX – INTEGERInput
On entry: the first dimension of the array X as declared in the (sub)program from which G02GPF is called.
Constraint: LDX≥N.
9:   M – INTEGERInput
On entry: m, the total number of independent variables.
Constraint: M≥1.
10:   ISX M – INTEGER arrayInput
On entry: indicates which independent variables are to be included in the model.
If ISX j>0, the jth independent variable is included in the regression model.
Constraints:
  • ISX j≥0, for i=1,2,…,M;
  • if MEAN='M', exactly IP-1 values of ISX must be >0;
  • if MEAN='Z', exactly IP values of ISX must be >0.
11:   IP – INTEGERInput
On entry: the number of independent variables in the model, including the mean or intercept if present.
Constraint: IP>0.
12:   T* – REAL (KIND=nag_wp) arrayInput
Note: the dimension of the array must be at least N if ERRFN='B', and at least 1 otherwise.
On entry: if ERRFN='B', T i must contain the binomial denominator, ti, for the ith observation.
Otherwise T is not referenced.
Constraint: if ERRFN='B', T i≥0.0, for i=1,2,…,n.
13:   OFF* – REAL (KIND=nag_wp) arrayInput
Note: the dimension of the array must be at least N if OFFSET='Y', and at least 1 otherwise.
On entry: if OFFSET='Y', OFF i must contain the offset oi, for the ith observation.
Otherwise OFF is not referenced.
14:   WT* – REAL (KIND=nag_wp) arrayInput
Note: the dimension of the array must be at least N if WEIGHT='W' and VFOBS=.TRUE., and at least 1 otherwise.
On entry: if WEIGHT='W' and VFOBS=.TRUE., WT i must contain the weight, wi, for the ith observation.
If the variance of future observations is not included in the standard error of the predicted variable, WT is not referenced.
Constraint: if VFOBS=.TRUE. and WEIGHT='W', WT i≥0., for i=1,2,…,i.
15:   S – REAL (KIND=nag_wp)Input
On entry: if ERRFN='N' or 'G' and VFOBS=.TRUE., the scale parameter, ϕ.
Otherwise S is not referenced and ϕ=1.
Constraint: if ERRFN='N' or 'G' and VFOBS=.TRUE., S>0.0.
16:   A – REAL (KIND=nag_wp)Input
On entry: if LINK='E', A must contain the power of the exponential.
If LINK≠'E', A is not referenced.
Constraint: if LINK='E', A≠0.0.
17:   B IP – REAL (KIND=nag_wp) arrayInput
On entry: the model parameters, β.
If MEAN='M', B 1 must contain the mean parameter and B i+1 the coefficient of the variable contained in the jth independent X, where ISX j is the ith positive value in the array ISX.
If MEAN='Z', B i must contain the coefficient of the variable contained in the jth independent X, where ISX j is the ith positive value in the array ISX.
18:   COV IP×IP+1/2 – REAL (KIND=nag_wp) arrayInput
On entry: the upper triangular part of the variance-covariance matrix, C, of the model parameters. This matrix should be supplied packed by column, i.e., the covariance between parameters βi and βj, that is the values stored in B i and B j, should be supplied in COV j×j-1/2+i, for i=1,2,…,IP and j=i,…,IP.
Constraint: the matrix represented in COV must be a valid variance-covariance matrix.
19:   VFOBS – LOGICALInput
On entry: if VFOBS=.TRUE., the variance of future observations is included in the standard error of the predicted variable (i.e., Ifobs=1), otherwise Ifobs=0.
20:   ETA N – REAL (KIND=nag_wp) arrayOutput
On exit: the linear predictor, η.
21:   SEETA N – REAL (KIND=nag_wp) arrayOutput
On exit: the standard error of the linear predictor, se η.
22:   PRED N – REAL (KIND=nag_wp) arrayOutput
On exit: the predicted value, y^.
23:   SEPRED N – REAL (KIND=nag_wp) arrayOutput
On exit: the standard error of the predicted value, se y^. If PRED i could not be calculated, then G02GPF returns IFAIL=22, and SEPRED i is set to -99.0.
24:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, because for this routine the values of the output arguments may be useful even if IFAIL≠0 on exit, the recommended value is -1. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Note: G02GPF may return useful information for one or more of the following detected errors or warnings.
Errors or warnings detected by the routine:
IFAIL=1
On entry, ERRFN is invalid: ERRFN=value.
IFAIL=2
On entry, ERRFN and LINK combination is invalid: ERRFN=value, LINK=value.
On entry, LINK is invalid: LINK=value.
IFAIL=3
On entry, MEAN is invalid: MEAN=value.
IFAIL=4
On entry, OFFSET is invalid: OFFSET=value.
IFAIL=5
On entry, WEIGHT is invalid: WEIGHT=value.
IFAIL=6
On entry, N=value.
Constraint: N≥1.
IFAIL=8
On entry, LDX=value and N=value.
Constraint: LDX≥N.
IFAIL=9
On entry, M=value.
Constraint: M≥1.
IFAIL=10
On entry, ISX not consistent with IP: value values >0, expected value.
IFAIL=11
On entry, IP=value.
Constraint: IP>0.
IFAIL=12
On entry, i=value and T i=value.
Constraint: T i≥0.0, for all i.
IFAIL=14
On entry, i=value and WT i=value.
Constraint: WT i≥0.0, for all i.
IFAIL=15
On entry, S=value.
Constraint: S>0.0.
IFAIL=16
On entry, A=0.0.
IFAIL=18
On entry, COV i<0.0 for at least one diagonal element: i=value, COV i=value.
IFAIL=22
At least one predicted value could not be calculated as required. SEPRED is set to -99.0 for affected predicted values.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

Not applicable.

8 Parallelism and Performance

G02GPF makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

None.

10 Example

The model
y = 1 β 1 + β 2 x + ε
is fitted to a training dataset with five observations. The resulting model is then used to predict the response for two new observations.

10.1 Program Text

Program Text (g02gpfe.f90)

10.2 Program Data

Program Data (g02gpfe.d)

10.3 Program Results

Program Results (g02gpfe.r)

G02 Chapter Contents
G02 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


G02HAF : NAG Library, Mark 26

G02 Chapter Contents
G02 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

G02HAF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

G02HAF performs bounded influence regression (M-estimates). Several standard methods are available.

2 Specification

SUBROUTINE G02HAF ( INDW, IPSI, ISIGMA, INDC, N, M, X, LDX, Y, CPSI, H1, H2, H3, CUCV, DCHI, THETA, SIGMA, C, LDC, RS, WGT, TOL, MAXIT, NITMON, WORK, IFAIL)
INTEGER | INDW, IPSI, ISIGMA, INDC, N, M, LDX, LDC, MAXIT, NITMON, IFAIL
REAL (KIND=nag_wp) | X(LDX,M), Y(N), CPSI, H1, H2, H3, CUCV, DCHI, THETA(M), SIGMA, C(LDC,M), RS(N), WGT(N), TOL, WORK(4*N+M*(N+M))

3 Description

For the linear regression model
y = Xθ+ε ,
where | y is a vector of length n of the dependent variable,
 | X is a n by m matrix of independent variables of column rank k,
 | θ is a vector of length m of unknown arguments,
and | ε is a vector of length n of unknown errors with var εi=σ 2,
G02HAF calculates the M-estimates given by the solution, θ^, to the equation
∑ i=1 n ψ ri / σ wi wi x ij = 0 ,   j=1,2,…,m , (1)
where ri is the ith residual, i.e., the ith element of r=y-X θ^,
ψ is a suitable weight function,
wi are suitable weights,
and σ may be estimated at each iteration by the median absolute deviation of the residuals
σ^ = medi⁡ ri / β 1
or as the solution to
∑ i= 1 n χ ri / σ ^ wi wi 2 = n-k β 2
for suitable weight function χ, where β 1 and β 2 are constants, chosen so that the estimator of σ is asymptotically unbiased if the errors, εi, have a Normal distribution. Alternatively σ may be held at a constant value.
The above describes the Schweppe type regression. If the wi are assumed to equal 1 for all i then Huber type regression is obtained. A third type, due to Mallows, replaces (1) by
∑ i=1 n ψ ri / σ wi x ij = 0 ,   j=1,2,…,m .
This may be obtained by use of the transformations
wi*←wi yi*←yi wi x ij*←x ij wi, j= 1,2,…,m
(see Section 3 of Marazzi (1987a)).
For Huber and Schweppe type regressions, β 1 is the 75th percentile of the standard Normal distribution. For Mallows type regression β 1 is the solution to
1 n ∑ i=1 n Φ β 1 / wi = 0.75 ,
where Φ is the standard Normal cumulative distribution function (see S15ABF).
β 2 is given by
β 2 = ∫ -∞ ∞ χ z ϕ z dz in the Huber case; β 2 = 1 n ∑ i=1 n wi ∫ -∞ ∞ χ z ϕ z dz in the Mallows case; β 2 = 1 n ∑ i=1 n wi 2 ∫ -∞ ∞ χ z/wi ϕ z dz in the Schweppe case;
where ϕ is the standard Normal density, i.e., 1 2 π exp-12 x 2 .
The calculation of the estimates of θ can be formulated as an iterative weighted least squares problem with a diagonal weight matrix G given by
G ii = ψ ri / σ wi ri / σ wi , ri≠0 ψ′ 0 , ri=0 ,
where ψ′t is the derivative of ψ at the point t.
The value of θ at each iteration is given by the weighted least squares regression of y on X. This is carried out by first transforming the y and X by
y~i=yi G ii x~ij=x ij G ii, j=1,2,…,m
and then using F04JGF. If X is of full column rank then an orthogonal-triangular (QR) decomposition is used; if not, a singular value decomposition is used.
The following functions are available for ψ and χ in G02HAF.
(a) Unit Weights
ψ t = t ,   χ t = t 2 2 .
This gives least squares regression.
(b) Huber's Function
ψ t = max-c,min c,t ,   χ t = t 2 2 , t≤d d 2 2 , t>d
(c) Hampel's Piecewise Linear Function
ψ h 1 , h 2 , h 3 t = - ψ h 1 , h 2 , h 3 -t = t, 0≤t≤ h 1 h 1, h 1 ≤t≤ h 2 h 1 h 3 - t / h 3 - h 2 , h 2 ≤t≤ h 3 0, h 3<t
χ t = t 2 2 , t≤d d 2 2 , t>d
(d) Andrew's Sine Wave Function
ψ t = sin⁡t, -π≤t≤π 0, t>π   χ t = t 2 2 , t≤d d 2 2 , t>d
(e) Tukey's Bi-weight
ψ t = t 1 - t 2 2 , t≤ 1 0, t> 1   χ t = t 2 2 , t≤d d 2 2 , t>d
where c, h 1, h 2, h 3, and d are given constants.
Several schemes for calculating weights have been proposed, see Hampel et al. (1986) and Marazzi (1987a). As the different independent variables may be measured on different scales, one group of proposed weights aims to bound a standardized measure of influence. To obtain such weights the matrix A has to be found such that:
1 n ∑ i=1 n u zi 2 zi ziT = I
and
zi = A xi ,
where | xi is a vector of length m containing the ith row of X,
 | A is an m by m lower triangular matrix,
and | u is a suitable function.
The weights are then calculated as
wi = f zi 2
for a suitable function f.
G02HAF finds A using the iterative procedure
Ak = Sk+I A k-1 ,
where Sk = s jl ,
s jl = - min max h jl / n ,-BL,BL , j>l - min max 12 h jj/n-1 ,-BD,BD , j=l
and
h jl = ∑ i= 1 n u zi 2 z ij z il
and BL and BD are bounds set at 0.9.
Two weights are available in G02HAF:
(i) Krasker–Welsch Weights
u t = g 1 ct ,
where | g 1 t=t 2+1-t 22 Φ t-1-2 tϕ t,
 | Φ t is the standard Normal cumulative distribution function,
 | ϕ t is the standard Normal probability density function,
and | f t= 1 t .
These are for use with Schweppe type regression.
(ii) Maronna's Proposed Weights
u t = c t 2 t>c 1 t≤c f t=u t .
These are for use with Mallows type regression.
Finally the asymptotic variance-covariance matrix, C, of the estimates θ is calculated.
For Huber type regression
C = fH XT X -1 σ^2 ,
where
fH = 1 n-m ∑ i= 1 n ψ 2 ri / σ ^ 1 n ∑ i= 1 n ψ′ ri σ^ 2 κ 2
κ 2 = 1 + mn 1 n ∑ i=1 n ψ′ ri / σ^ - 1 n ∑ i=1 n ψ′ ri / σ^ 2 1 n ∑ i=1 n ψ′ ri σ^ 2 .
See Huber (1981) and Marazzi (1987b).
For Mallows and Schweppe type regressions C is of the form
σ^n 2 S 1-1 S 2 S 1-1 ,
where S 1=1 n XT DX and S 2=1 n XT PX.
D is a diagonal matrix such that the ith element approximates E ψ′ri/σ wi in the Schweppe case and E ψ′ri/σ wi in the Mallows case.
P is a diagonal matrix such that the ith element approximates E ψ 2 ri/σ wi wi 2 in the Schweppe case and E ψ 2 ri/σ wi 2 in the Mallows case.
Two approximations are available in G02HAF:
1. Average over the ri
Schweppe Mallows Di = 1 n ∑ j=1 n ψ′ rj σ^ wi wi   Di = 1 n ∑ j=1 n ψ′ rj σ^ wi Pi = 1 n ∑ j=1 n ψ 2 rj σ^ wi wi 2   Pi = 1 n ∑ j=1 n ψ 2 rj σ^ wi 2
2. Replace expected value by observed
Schweppe Mallows Di = ψ′ ri σ^ wi wi   Di = ψ′ ri σ ^ wi Pi = ψ 2 ri σ ^ wi wi 2   Pi = ψ 2 ri σ ^ wi 2 .
See Hampel et al. (1986) and Marazzi (1987b).
Note: there is no explicit provision in the routine for a constant term in the regression model. However, the addition of a dummy variable whose value is 1.0 for all observations will produce a value of θ^ corresponding to the usual constant term.
G02HAF is based on routines in ROBETH; see Marazzi (1987a).

4 References

Hampel F R, Ronchetti E M, Rousseeuw P J and Stahel W A (1986) Robust Statistics. The Approach Based on Influence Functions Wiley
Huber P J (1981) Robust Statistics Wiley
Marazzi A (1987a) Weights for bounded influence regression in ROBETH Cah. Rech. Doc. IUMSP, No. 3 ROB 3 Institut Universitaire de Médecine Sociale et Préventive, Lausanne
Marazzi A (1987b) Subroutines for robust and bounded influence regression in ROBETH Cah. Rech. Doc. IUMSP, No. 3 ROB 2 Institut Universitaire de Médecine Sociale et Préventive, Lausanne

5 Arguments

1:   INDW – INTEGERInput
On entry: specifies the type of regression to be performed.
INDW<0
Mallows type regression with Maronna's proposed weights.
INDW=0
Huber type regression.
INDW>0
Schweppe type regression with Krasker–Welsch weights.
2:   IPSI – INTEGERInput
On entry: specifies which ψ function is to be used.
IPSI=0
ψ t=t, i.e., least squares.
IPSI=1
Huber's function.
IPSI=2
Hampel's piecewise linear function.
IPSI=3
Andrew's sine wave.
IPSI=4
Tukey's bi-weight.
Constraint: 0≤IPSI≤4.
3:   ISIGMA – INTEGERInput
On entry: specifies how σ is to be estimated.
ISIGMA<0
σ is estimated by median absolute deviation of residuals.
ISIGMA=0
σ is held constant at its initial value.
ISIGMA>0
σ is estimated using the χ function.
4:   INDC – INTEGERInput
On entry: if INDW≠0, INDC specifies the approximations used in estimating the covariance matrix of θ^.
INDC=1
Averaging over residuals.
INDC≠1
Replacing expected by observed.
INDW=0
INDC is not referenced.
5:   N – INTEGERInput
On entry: n, the number of observations.
Constraint: N>1.
6:   M – INTEGERInput
On entry: m, the number of independent variables.
Constraint: 1≤M<N.
7:   X LDXM – REAL (KIND=nag_wp) arrayInput/Output
On entry: the values of the X matrix, i.e., the independent variables. X ij must contain the ijth element of X, for i=1,2,…,n and j=1,2,…,m.
If INDW<0, then during calculations the elements of X will be transformed as described in Section 3. Before exit the inverse transformation will be applied. As a result there may be slight differences between the input X and the output X.
On exit: unchanged, except as described above.
8:   LDX – INTEGERInput
On entry: the first dimension of the array X as declared in the (sub)program from which G02HAF is called.
Constraint: LDX≥N.
9:   Y N – REAL (KIND=nag_wp) arrayInput/Output
On entry: the data values of the dependent variable.
Y i must contain the value of y for the ith observation, for i=1,2,…,n.
If INDW<0, then during calculations the elements of Y will be transformed as described in Section 3. Before exit the inverse transformation will be applied. As a result there may be slight differences between the input Y and the output Y.
On exit: unchanged, except as described above.
10:   CPSI – REAL (KIND=nag_wp)Input
On entry: if IPSI=1, CPSI must specify the argument, c, of Huber's ψ function.
If IPSI≠1 on entry, CPSI is not referenced.
Constraint: if CPSI>0.0, IPSI=1.
11:   H1 – REAL (KIND=nag_wp)Input
12:   H2 – REAL (KIND=nag_wp)Input
13:   H3 – REAL (KIND=nag_wp)Input
On entry: if IPSI=2, H1, H2, and H3 must specify the arguments h 1, h 2, and h 3, of Hampel's piecewise linear ψ function. H1, H2, and H3 are not referenced if IPSI≠2.
Constraint: if IPSI=2, 0.0≤H1≤H2≤H3 and H3>0.0.
14:   CUCV – REAL (KIND=nag_wp)Input
On entry: if INDW<0, must specify the value of the constant, c, of the function u for Maronna's proposed weights.
If INDW>0, must specify the value of the function u for the Krasker–Welsch weights.
If INDW=0, is not referenced.
Constraints:
  • if INDW<0, CUCV≥M;
  • if INDW>0, CUCV≥M.
15:   DCHI – REAL (KIND=nag_wp)Input
On entry: d, the constant of the χ function. DCHI is not referenced if IPSI=0, or if ISIGMA≤0.
Constraint: if IPSI≠0 and ISIGMA>0, DCHI>0.0.
16:   THETA M – REAL (KIND=nag_wp) arrayInput/Output
On entry: starting values of the argument vector θ. These may be obtained from least squares regression. Alternatively if ISIGMA<0 and SIGMA=1 or if ISIGMA>0 and SIGMA approximately equals the standard deviation of the dependent variable, y, then THETA i=0.0, for i=1,2,…,m may provide reasonable starting values.
On exit: THETA i contains the M-estimate of θi, for i=1,2,…,m.
17:   SIGMA – REAL (KIND=nag_wp)Input/Output
On entry: a starting value for the estimation of σ. SIGMA should be approximately the standard deviation of the residuals from the model evaluated at the value of θ given by THETA on entry.
Constraint: SIGMA>0.0.
On exit: contains the final estimate of σ if ISIGMA≠0 or the value assigned on entry if ISIGMA=0.
18:   C LDCM – REAL (KIND=nag_wp) arrayOutput
On exit: the diagonal elements of C contain the estimated asymptotic standard errors of the estimates of θ, i.e., C ii contains the estimated asymptotic standard error of the estimate contained in THETA i.
The elements above the diagonal contain the estimated asymptotic correlation between the estimates of θ, i.e., C ij, 1≤i<j≤m contains the asymptotic correlation between the estimates contained in THETA i and THETA j.
The elements below the diagonal contain the estimated asymptotic covariance between the estimates of θ, i.e., C ij, 1≤j<i≤m contains the estimated asymptotic covariance between the estimates contained in THETA i and THETA j.
19:   LDC – INTEGERInput
On entry: the first dimension of the array C as declared in the (sub)program from which G02HAF is called.
Constraint: LDC≥M.
20:   RS N – REAL (KIND=nag_wp) arrayOutput
On exit: the residuals from the model evaluated at final value of THETA, i.e., RS contains the vector y-X θ^.
21:   WGT N – REAL (KIND=nag_wp) arrayOutput
On exit: the vector of weights. WGT i contains the weight for the ith observation, for i=1,2,…,n.
22:   TOL – REAL (KIND=nag_wp)Input
On entry: the relative precision for the calculation of A (if INDW≠0), the estimates of θ and the estimate of σ (if ISIGMA≠0). Convergence is assumed when the relative change in all elements being considered is less than TOL.
If INDW<0 and ISIGMA<0, TOL is also used to determine the precision of β 1.
It is advisable for TOL to be greater than 100×machine precision.
Constraint: TOL>0.0.
23:   MAXIT – INTEGERInput
On entry: the maximum number of iterations that should be used in the calculation of A (if INDW≠0), and of the estimates of θ and σ, and of β 1 (if INDW<0 and ISIGMA<0).
A value of MAXIT=50 should be adequate for most uses.
Constraint: MAXIT>0.
24:   NITMON – INTEGERInput
On entry: the amount of information that is printed on each iteration.
NITMON=0
No information is printed.
NITMON≠0
The current estimate of θ, the change in θ during the current iteration and the current value of σ are printed on the first and every abs NITMON iterations.
Also, if INDW≠0 and NITMON>0 then information on the iterations to calculate A is printed. This is the current estimate of A and the maximum value of S ij (see Section 3).
When printing occurs the output is directed to the current advisory message unit (see X04ABF).
25:   WORK 4×N+M×N+M – REAL (KIND=nag_wp) arrayOutput
On exit: the following values are assigned to WORK:
  • WORK 1=β 1 if ISIGMA<0, or WORK 1=β 2 if ISIGMA>0.
  • WORK 2= number of iterations used to calculate A.
  • WORK 3= number of iterations used to calculate final estimates of θ and σ.
  • WORK 4=k, the rank of the weighted least squares equations.
The rest of the array is used as workspace.
26:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, because for this routine the values of the output arguments may be useful even if IFAIL≠0 on exit, the recommended value is -1. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Note: G02HAF may return useful information for one or more of the following detected errors or warnings.
Errors or warnings detected by the routine:
IFAIL=1
On entry, | N≤1,
or | M<1,
or | N≤M,
or | LDX<N,
or | LDC<M.
IFAIL=2
On entry, | IPSI<0,
or | IPSI>4.
IFAIL=3
On entry, | SIGMA≤0.0,
or | IPSI=1 and CPSI≤0.0,
or | IPSI=2 and H1<0.0,
or | IPSI=2 and H1>H2,
or | IPSI=2 and H2>H3,
or | IPSI=2 and H1=H2=H3=0.0,
or | IPSI≠0 and ISIGMA>0 and DCHI≤0.0,
or | INDW>0 and CUCV<M,
or | INDW<0 and CUCV<M.
IFAIL=4
On entry, | TOL≤0.0,
or | MAXIT≤0.
IFAIL=5
The number of iterations required to calculate the weights exceeds MAXIT. (Only if INDW≠0.)
IFAIL=6
The number of iterations required to calculate β 1 exceeds MAXIT. (Only if INDW<0 and ISIGMA<0.)
IFAIL=7
Either the number of iterations required to calculate θ and σ exceeds MAXIT (note that, in this case WORK 3=MAXIT on exit), or the iterations to solve the weighted least squares equations failed to converge. The latter is an unlikely error exit.
IFAIL=8
The weighted least squares equations are not of full rank.
IFAIL=9
If INDW=0 then XT X is almost singular.
If INDW≠0 then S 1 is singular or almost singular. This may be due to too many diagonal elements of the matrix being zero, see Section 9.
IFAIL=10
In calculating the correlation factor for the asymptotic variance-covariance matrix either the value of
1 n ∑ i=1 n ψ′ ri / σ^ = 0 ,   or   κ = 0 ,   or   ∑ i=1 n ψ 2 ri / σ^ = 0 .
See Section 9. In this case C is returned as XT X.
(Only if INDW=0.)
IFAIL=11
The estimated variance for an element of θ≤0.
In this case the diagonal element of C will contain the negative variance and the above diagonal elements in the row and column corresponding to the element will be returned as zero.
This error may be caused by rounding errors or too many of the diagonal elements of P being zero, where P is defined in Section 3. See Section 9.
IFAIL=12
The degrees of freedom for error, n-k≤0 (this is an unlikely error exit), or the estimated value of σ was 0 during an iteration.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

The precision of the estimates is determined by TOL. As a more stable method is used to calculate the estimates of θ than is used to calculate the covariance matrix, it is possible for the least squares equations to be of full rank but the XT X matrix to be too nearly singular to be inverted.

8 Parallelism and Performance

G02HAF is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
G02HAF makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

In cases when ISIGMA≥0 it is important for the value of SIGMA to be of a reasonable magnitude. Too small a value may cause too many of the winsorized residuals, i.e., ψ ri/σ, to be zero or a value of ψ′ri/σ, used to estimate the asymptotic covariance matrix, to be zero. This can lead to errors IFAIL=8 or 9 (if INDW≠0), IFAIL=10 (if INDW=0) and IFAIL=11.
G02HBF, G02HDF and G02HFF together carry out the same calculations as G02HAF but for user-supplied functions for ψ, χ, ψ′ and u.

10 Example

The number of observations and the number of x variables are read in followed by the data. The option arguments are then read in (in this case giving Schweppe type regression with Hampel's ψ function and Huber's χ function and then using the ‘replace expected by observed’ option in calculating the covariances). Finally a set of values for the constants are read in.
After a call to G02HAF, θ^, its standard error and σ^ are printed. In addition the weight and residual for each observation is printed.

10.1 Program Text

Program Text (g02hafe.f90)

10.2 Program Data

Program Data (g02hafe.d)

10.3 Program Results

Program Results (g02hafe.r)

G02 Chapter Contents
G02 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


G02HBF : NAG Library, Mark 26

G02 Chapter Contents
G02 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

G02HBF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

G02HBF finds, for a real matrix X of full column rank, a lower triangular matrix A such that AT A-1 is proportional to a robust estimate of the covariance of the variables. G02HBF is intended for the calculation of weights of bounded influence regression using G02HDF.

2 Specification

SUBROUTINE G02HBF ( UCV, N, M, X, LDX, A, Z, BL, BD, TOL, MAXIT, NITMON, NIT, WK, IFAIL)
INTEGER | N, M, LDX, MAXIT, NITMON, NIT, IFAIL
REAL (KIND=nag_wp) | UCV, X(LDX,M), A(M*(M+1)/2), Z(N), BL, BD, TOL, WK(M*(M+1)/2)
EXTERNAL | UCV

3 Description

In fitting the linear regression model
y=Xθ+ε,
where | y is a vector of length n of the dependent variable,
 | X is an n by m matrix of independent variables,
 | θ is a vector of length m of unknown arguments,
and | ε is a vector of length n of unknown errors,
it may be desirable to bound the influence of rows of the X matrix. This can be achieved by calculating a weight for each observation. Several schemes for calculating weights have been proposed (see Hampel et al. (1986) and Marazzi (1987)). As the different independent variables may be measured on different scales one group of proposed weights aims to bound a standardized measure of influence. To obtain such weights the matrix A has to be found such that
1 n∑i=1 n u zi 2 zi ziT =I​  I​ is the identity matrix
and
zi=A xi,
where | xi is a vector of length m containing the elements of the ith row of X,
 | A is an m by m lower triangular matrix,
 | zi is a vector of length m,
and | u is a suitable function.
The weights for use with G02HDF may then be computed using
wi=f zi 2
for a suitable user-supplied function f.
G02HBF finds A using the iterative procedure
Ak=Sk+I A k-1,
where Sk=s jl, for j=1,2,…,m and l=1,2,…,m, is a lower triangular matrix such that
  • s jl= -min max h jl/n,-BL,BL, j>l -min max 12 h jj/n-1,-BD,BD, j=l
  • h jl=∑i=1 n u zi 2 z ijz il
and BD and BL are suitable bounds.
In addition the values of zi 2, for i=1,2,…,n, are calculated.
G02HBF is based on routines in ROBETH; see Marazzi (1987).

4 References

Hampel F R, Ronchetti E M, Rousseeuw P J and Stahel W A (1986) Robust Statistics. The Approach Based on Influence Functions Wiley
Huber P J (1981) Robust Statistics Wiley
Marazzi A (1987) Weights for bounded influence regression in ROBETH Cah. Rech. Doc. IUMSP, No. 3 ROB 3 Institut Universitaire de Médecine Sociale et Préventive, Lausanne

5 Arguments

1:   UCV – REAL (KIND=nag_wp) FUNCTION, supplied by the user.External Procedure
UCV must return the value of the function u for a given value of its argument. The value of u must be non-negative.
The specification of UCV is:
FUNCTION UCV ( T)
REAL (KIND=nag_wp) UCV
REAL (KIND=nag_wp) T
1:   T – REAL (KIND=nag_wp)Input
On entry: the argument for which UCV must be evaluated.
UCV must either be a module subprogram USEd by, or declared as EXTERNAL in, the (sub)program from which G02HBF is called. Arguments denoted as Input must not be changed by this procedure.
2:   N – INTEGERInput
On entry: n, the number of observations.
Constraint: N>1.
3:   M – INTEGERInput
On entry: m, the number of independent variables.
Constraint: 1≤M≤N.
4:   X LDXM – REAL (KIND=nag_wp) arrayInput
On entry: the real matrix X, i.e., the independent variables. X ij must contain the ijth element of X, for i=1,2,…,n and j=1,2,…,m.
5:   LDX – INTEGERInput
On entry: the first dimension of the array X as declared in the (sub)program from which G02HBF is called.
Constraint: LDX≥N.
6:   A M×M+1/2 – REAL (KIND=nag_wp) arrayInput/Output
On entry: an initial estimate of the lower triangular real matrix A. Only the lower triangular elements must be given and these should be stored row-wise in the array.
The diagonal elements must be ≠0, although in practice will usually be >0. If the magnitudes of the columns of X are of the same order the identity matrix will often provide a suitable initial value for A. If the columns of X are of different magnitudes, the diagonal elements of the initial value of A should be approximately inversely proportional to the magnitude of the columns of X.
On exit: the lower triangular elements of the matrix A, stored row-wise.
7:   Z N – REAL (KIND=nag_wp) arrayOutput
On exit: the value zi 2, for i=1,2,…,n.
8:   BL – REAL (KIND=nag_wp)Input
On entry: the magnitude of the bound for the off-diagonal elements of Sk.
Suggested value: BL=0.9.
Constraint: BL>0.0.
9:   BD – REAL (KIND=nag_wp)Input
On entry: the magnitude of the bound for the diagonal elements of Sk.
Suggested value: BD=0.9.
Constraint: BD>0.0.
10:   TOL – REAL (KIND=nag_wp)Input
On entry: the relative precision for the final value of A. Iteration will stop when the maximum value of s jl is less than TOL.
Constraint: TOL>0.0.
11:   MAXIT – INTEGERInput
On entry: the maximum number of iterations that will be used during the calculation of A.
A value of MAXIT=50 will often be adequate.
Constraint: MAXIT>0.
12:   NITMON – INTEGERInput
On entry: determines the amount of information that is printed on each iteration.
NITMON>0
The value of A and the maximum value of s jl will be printed at the first and every NITMON iterations.
NITMON≤0
No iteration monitoring is printed.
When printing occurs the output is directed to the current advisory message unit (see X04ABF).
13:   NIT – INTEGEROutput
On exit: the number of iterations performed.
14:   WK M×M+1/2 – REAL (KIND=nag_wp) arrayWorkspace
15:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, | N≤1,
or | M<1,
or | N<M,
or | LDX<N.
IFAIL=2
On entry, | TOL≤0.0,
or | MAXIT≤0,
or | diagonal element of A=0.0,
or | BL≤0.0,
or | BD≤0.0.
IFAIL=3
Value returned by UCV<0.
IFAIL=4
The routine has failed to converge in MAXIT iterations.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

On successful exit the accuracy of the results is related to the value of TOL; see Section 5.

8 Parallelism and Performance

G02HBF makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The existence of A will depend upon the function u; (see Hampel et al. (1986) and Marazzi (1987)), also if X is not of full rank a value of A will not be found. If the columns of X are almost linearly related then convergence will be slow.

10 Example

This example reads in a matrix of real numbers and computes the Krasker–Welsch weights (see Marazzi (1987)). The matrix A and the weights are then printed.

10.1 Program Text

Program Text (g02hbfe.f90)

10.2 Program Data

Program Data (g02hbfe.d)

10.3 Program Results

Program Results (g02hbfe.r)

G02 Chapter Contents
G02 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


G02HDF : NAG Library, Mark 26

G02 Chapter Contents
G02 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

G02HDF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

G02HDF performs bounded influence regression (M-estimates) using an iterative weighted least squares algorithm.

2 Specification

SUBROUTINE G02HDF ( CHI, PSI, PSIP0, BETA, INDW, ISIGMA, N, M, X, LDX, Y, WGT, THETA, K, SIGMA, RS, TOL, EPS, MAXIT, NITMON, NIT, WK, IFAIL)
INTEGER | INDW, ISIGMA, N, M, LDX, K, MAXIT, NITMON, NIT, IFAIL
REAL (KIND=nag_wp) | CHI, PSI, PSIP0, BETA, X(LDX,M), Y(N), WGT(N), THETA(M), SIGMA, RS(N), TOL, EPS, WK((M+4)*N)
EXTERNAL | CHI, PSI

3 Description

For the linear regression model
y=Xθ+ε,
where | y is a vector of length n of the dependent variable,
 | X is a n by m matrix of independent variables of column rank k,
 | θ is a vector of length m of unknown arguments,
and | ε is a vector of length n of unknown errors with var εi=σ 2,
G02HDF calculates the M-estimates given by the solution, θ^, to the equation
∑i=1 n ψ ri/σ wi wix ij=0,  j=1,2,…,m, (1)
where | ri is the ith residual, i.e., the ith element of the vector r=y-X θ^,
 | ψ is a suitable weight function,
 | wi are suitable weights such as those that can be calculated by using output from G02HBF,
and | σ may be estimated at each iteration by the median absolute deviation of the residuals σ^=medi⁡ri/β 1
or as the solution to
∑i=1 n χ ri/σ^wi wi 2=n-k β 2
for a suitable weight function χ, where β 1 and β 2 are constants, chosen so that the estimator of σ is asymptotically unbiased if the errors, εi, have a Normal distribution. Alternatively σ may be held at a constant value.
The above describes the Schweppe type regression. If the wi are assumed to equal 1 for all i, then Huber type regression is obtained. A third type, due to Mallows, replaces (1) by
∑i=1 n ψ ri/σ wix ij=0,  j=1,2,…,m.
This may be obtained by use of the transformations
wi* ←wi yi* ←yi wi x ij* ←x ij wi,   j= 1,2,…,m
(see Marazzi (1987)).
The calculation of the estimates of θ can be formulated as an iterative weighted least squares problem with a diagonal weight matrix G given by
G ii= ψ ri/σ wi ri/σ wi , ri≠0 ψ′0, ri=0. .
The value of θ at each iteration is given by the weighted least squares regression of y on X. This is carried out by first transforming the y and X by
y~i =yi G ii x~ij =x ij G ii,  j=1,2,…,m
and then using F04JGF . If X is of full column rank then an orthogonal-triangular (QR) decomposition is used; if not, a singular value decomposition is used.
Observations with zero or negative weights are not included in the solution.
Note: there is no explicit provision in the routine for a constant term in the regression model. However, the addition of a dummy variable whose value is 1.0 for all observations will produce a value of θ^ corresponding to the usual constant term.
G02HDF is based on routines in ROBETH, see Marazzi (1987).

4 References

Hampel F R, Ronchetti E M, Rousseeuw P J and Stahel W A (1986) Robust Statistics. The Approach Based on Influence Functions Wiley
Huber P J (1981) Robust Statistics Wiley
Marazzi A (1987) Subroutines for robust and bounded influence regression in ROBETH Cah. Rech. Doc. IUMSP, No. 3 ROB 2 Institut Universitaire de Médecine Sociale et Préventive, Lausanne

5 Arguments

1:   CHI – REAL (KIND=nag_wp) FUNCTION, supplied by the user.External Procedure
If ISIGMA>0, CHI must return the value of the weight function χ for a given value of its argument. The value of χ must be non-negative.
The specification of CHI is:
FUNCTION CHI ( T)
REAL (KIND=nag_wp) CHI
REAL (KIND=nag_wp) T
1:   T – REAL (KIND=nag_wp)Input
On entry: the argument for which CHI must be evaluated.
CHI must either be a module subprogram USEd by, or declared as EXTERNAL in, the (sub)program from which G02HDF is called. Arguments denoted as Input must not be changed by this procedure.
If ISIGMA≤0, the actual argument CHI may be the dummy routine G02HDZ. (G02HDZ is included in the NAG Library.)
2:   PSI – REAL (KIND=nag_wp) FUNCTION, supplied by the user.External Procedure
PSI must return the value of the weight function ψ for a given value of its argument.
The specification of PSI is:
FUNCTION PSI ( T)
REAL (KIND=nag_wp) PSI
REAL (KIND=nag_wp) T
1:   T – REAL (KIND=nag_wp)Input
On entry: the argument for which PSI must be evaluated.
PSI must either be a module subprogram USEd by, or declared as EXTERNAL in, the (sub)program from which G02HDF is called. Arguments denoted as Input must not be changed by this procedure.
3:   PSIP0 – REAL (KIND=nag_wp)Input
On entry: the value of ψ′0.
4:   BETA – REAL (KIND=nag_wp)Input
On entry: if ISIGMA<0, BETA must specify the value of β 1.
For Huber and Schweppe type regressions, β 1 is the 75th percentile of the standard Normal distribution (see G01FAF). For Mallows type regression β 1 is the solution to
1 n∑i=1 n Φ β 1/wi=0.75,
where Φ is the standard Normal cumulative distribution function (see S15ABF).
If ISIGMA>0, BETA must specify the value of β 2.
β 2= ∫-∞∞χ z ϕ z dz, in the Huber case; β 2= 1 n∑i=1 n wi∫-∞∞χ z ϕ z dz, in the Mallows case; β 2= 1 n∑i=1 n wi 2∫-∞∞χ z/wi ϕ z dz, in the Schweppe case;
where ϕ is the standard normal density, i.e., 1 2 π exp-12 x 2 .
If ISIGMA=0, BETA is not referenced.
Constraint: if ISIGMA≠0, BETA>0.0.
5:   INDW – INTEGERInput
On entry: determines the type of regression to be performed.
INDW=0
Huber type regression.
INDW<0
Mallows type regression.
INDW>0
Schweppe type regression.
6:   ISIGMA – INTEGERInput
On entry: determines how σ is to be estimated.
ISIGMA=0
σ is held constant at its initial value.
ISIGMA<0
σ is estimated by median absolute deviation of residuals.
ISIGMA>0
σ is estimated using the χ function.
7:   N – INTEGERInput
On entry: n, the number of observations.
Constraint: N>1.
8:   M – INTEGERInput
On entry: m, the number of independent variables.
Constraint: 1≤M<N.
9:   X LDXM – REAL (KIND=nag_wp) arrayInput/Output
On entry: the values of the X matrix, i.e., the independent variables. X ij must contain the ijth element of X, for i=1,2,…,n and j=1,2,…,m.
If INDW<0, during calculations the elements of X will be transformed as described in Section 3. Before exit the inverse transformation will be applied. As a result there may be slight differences between the input X and the output X.
On exit: unchanged, except as described above.
10:   LDX – INTEGERInput
On entry: the first dimension of the array X as declared in the (sub)program from which G02HDF is called.
Constraint: LDX≥N.
11:   Y N – REAL (KIND=nag_wp) arrayInput/Output
On entry: the data values of the dependent variable.
Y i must contain the value of y for the ith observation, for i=1,2,…,n.
If INDW<0, during calculations the elements of Y will be transformed as described in Section 3. Before exit the inverse transformation will be applied. As a result there may be slight differences between the input Y and the output Y.
On exit: unchanged, except as described above.
12:   WGT N – REAL (KIND=nag_wp) arrayInput/Output
On entry: the weight for the ith observation, for i=1,2,…,n.
If INDW<0, during calculations elements of WGT will be transformed as described in Section 3. Before exit the inverse transformation will be applied. As a result there may be slight differences between the input WGT and the output WGT.
If WGT i≤0, the ith observation is not included in the analysis.
If INDW=0, WGT is not referenced.
On exit: unchanged, except as described above.
13:   THETA M – REAL (KIND=nag_wp) arrayInput/Output
On entry: starting values of the argument vector θ. These may be obtained from least squares regression. Alternatively if ISIGMA<0 and SIGMA=1 or if ISIGMA>0 and SIGMA approximately equals the standard deviation of the dependent variable, y, then THETA i=0.0, for i=1,2,…,m may provide reasonable starting values.
On exit: the M-estimate of θi, for i=1,2,…,m.
14:   K – INTEGEROutput
On exit: the column rank of the matrix X.
15:   SIGMA – REAL (KIND=nag_wp)Input/Output
On entry: a starting value for the estimation of σ. SIGMA should be approximately the standard deviation of the residuals from the model evaluated at the value of θ given by THETA on entry.
Constraint: SIGMA>0.0.
On exit: the final estimate of σ if ISIGMA≠0 or the value assigned on entry if ISIGMA=0.
16:   RS N – REAL (KIND=nag_wp) arrayOutput
On exit: the residuals from the model evaluated at final value of THETA, i.e., RS contains the vector y-X θ^.
17:   TOL – REAL (KIND=nag_wp)Input
On entry: the relative precision for the final estimates. Convergence is assumed when both the relative change in the value of SIGMA and the relative change in the value of each element of THETA are less than TOL.
It is advisable for TOL to be greater than 100×machine precision.
Constraint: TOL>0.0.
18:   EPS – REAL (KIND=nag_wp)Input
On entry: a relative tolerance to be used to determine the rank of X. See F04JGF for further details.
If EPS<machine precision or EPS>1.0 then machine precision will be used in place of TOL.
A reasonable value for EPS is 5.0×10-6 where this value is possible.
19:   MAXIT – INTEGERInput
On entry: the maximum number of iterations that should be used during the estimation.
A value of MAXIT=50 should be adequate for most uses.
Constraint: MAXIT>0.
20:   NITMON – INTEGERInput
On entry: determines the amount of information that is printed on each iteration.
NITMON≤0
No information is printed.
NITMON>0
On the first and every NITMON iterations the values of SIGMA, THETA and the change in THETA during the iteration are printed.
When printing occurs the output is directed to the current advisory message unit (see X04ABF).
21:   NIT – INTEGEROutput
On exit: the number of iterations that were used during the estimation.
22:   WK M+4×N – REAL (KIND=nag_wp) arrayWorkspace
23:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, because for this routine the values of the output arguments may be useful even if IFAIL≠0 on exit, the recommended value is -1. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Note: G02HDF may return useful information for one or more of the following detected errors or warnings.
Errors or warnings detected by the routine:
IFAIL=1
On entry, | N≤1,
or | M<1,
or | N≤M,
or | LDX<N.
IFAIL=2
On entry, | BETA≤0.0, and ISIGMA≠0,
or | SIGMA≤0.0.
IFAIL=3
On entry, | TOL≤0.0,
or | MAXIT≤0.
IFAIL=4
A value returned by the CHI function is negative.
IFAIL=5
During iterations a value of SIGMA≤0.0 was encountered.
IFAIL=6
A failure occurred in F04JGF . This is an extremely unlikely error. If it occurs, please contact NAG.
IFAIL=7
The weighted least squares equations are not of full rank. This may be due to the X matrix not being of full rank, in which case the results will be valid. It may also occur if some of the G ii values become very small or zero, see Section 9. The rank of the equations is given by K. If the matrix just fails the test for nonsingularity then the result IFAIL=7 and K=M is possible (see F04JGF).
IFAIL=8
The routine has failed to converge in MAXIT iterations.
IFAIL=9
Having removed cases with zero weight, the value of N-K≤0, i.e., no degree of freedom for error. This error will only occur if ISIGMA>0.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

The accuracy of the results is controlled by TOL. For the accuracy of the weighted least squares see F04JGF.

8 Parallelism and Performance

G02HDF is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
G02HDF makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

In cases when ISIGMA≠0 it is important for the value of SIGMA to be of a reasonable magnitude. Too small a value may cause too many of the winsorized residuals, i.e., ψ ri/σ, to be zero, which will lead to convergence problems and may trigger the IFAIL=7 error.
By suitable choice of the functions CHI and PSI this routine may be used for other applications of iterative weighted least squares.
For the variance-covariance matrix of θ see G02HFF.

10 Example

Having input X, Y and the weights, a Schweppe type regression is performed using Huber's ψ function. The subroutine BETCAL calculates the appropriate value of β 2.

10.1 Program Text

Program Text (g02hdfe.f90)

10.2 Program Data

Program Data (g02hdfe.d)

10.3 Program Results

Program Results (g02hdfe.r)

G02 Chapter Contents
G02 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


G02HFF : NAG Library, Mark 26

G02 Chapter Contents
G02 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

G02HFF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

G02HFF calculates an estimate of the asymptotic variance-covariance matrix for the bounded influence regression estimates (M-estimates). It is intended for use with G02HDF.

2 Specification

SUBROUTINE G02HFF ( PSI, PSP, INDW, INDC, SIGMA, N, M, X, LDX, RS, WGT, C, LDC, WK, IFAIL)
INTEGER | INDW, INDC, N, M, LDX, LDC, IFAIL
REAL (KIND=nag_wp) | PSI, PSP, SIGMA, X(LDX,M), RS(N), WGT(N), C(LDC,M), WK(M*(N+M+1)+2*N)
EXTERNAL | PSI, PSP

3 Description

For a description of bounded influence regression see G02HDF. Let θ be the regression arguments and let C be the asymptotic variance-covariance matrix of θ^. Then for Huber type regression
C=fH XT X-1σ^2,
where
fH=1 n-m ∑i= 1 n ψ 2 ri/σ^ 1 n∑ψ′ ri σ^ 2 κ 2
κ 2=1+mn 1 n ∑i=1 n ψ′ ri/σ^-1 n∑i=1 n ψ′ ri/σ^ 2 1 n ∑i=1 n ψ′ ri σ^ 2 ,
see Huber (1981) and Marazzi (1987).
For Mallows and Schweppe type regressions, C is of the form
σ^n 2 S 1-1 S 2 S 1-1,
where S 1=1 n XT DX and S 2=1 n XT PX.
D is a diagonal matrix such that the ith element approximates E ψ′ri/σ wi in the Schweppe case and E ψ′ri/σ wi in the Mallows case.
P is a diagonal matrix such that the ith element approximates E ψ 2 ri/σ wi wi 2 in the Schweppe case and E ψ 2 ri/σ wi 2 in the Mallows case.
Two approximations are available in G02HFF:
1. Average over the ri
Schweppe Mallows Di=1 n∑j=1 n ψ′ rj σ^wi wi  Di=1 n∑j=1 n ψ′ rj σ^ wi Pi=1 n∑j=1 n ψ 2 rj σ^wi wi 2  Pi=1 n∑j=1 n ψ 2 rj σ^ wi 2
2. Replace expected value by observed
Schweppe Mallows Di=ψ′ ri σ ^wi wi   Di=ψ′ ri σ ^ wi Pi=ψ 2 ri σ ^wi wi 2   Pi=ψ 2 ri σ ^ wi 2
See Hampel et al. (1986) and Marazzi (1987).
In all cases σ^ is a robust estimate of σ.
G02HFF is based on routines in ROBETH; see Marazzi (1987).

4 References

Hampel F R, Ronchetti E M, Rousseeuw P J and Stahel W A (1986) Robust Statistics. The Approach Based on Influence Functions Wiley
Huber P J (1981) Robust Statistics Wiley
Marazzi A (1987) Subroutines for robust and bounded influence regression in ROBETH Cah. Rech. Doc. IUMSP, No. 3 ROB 2 Institut Universitaire de Médecine Sociale et Préventive, Lausanne

5 Arguments

1:   PSI – REAL (KIND=nag_wp) FUNCTION, supplied by the user.External Procedure
PSI must return the value of the ψ function for a given value of its argument.
The specification of PSI is:
FUNCTION PSI ( T)
REAL (KIND=nag_wp) PSI
REAL (KIND=nag_wp) T
1:   T – REAL (KIND=nag_wp)Input
On entry: the argument for which PSI must be evaluated.
PSI must either be a module subprogram USEd by, or declared as EXTERNAL in, the (sub)program from which G02HFF is called. Arguments denoted as Input must not be changed by this procedure.
2:   PSP – REAL (KIND=nag_wp) FUNCTION, supplied by the user.External Procedure
PSP must return the value of ψ′t=d dt ψ t for a given value of its argument.
The specification of PSP is:
FUNCTION PSP ( T)
REAL (KIND=nag_wp) PSP
REAL (KIND=nag_wp) T
1:   T – REAL (KIND=nag_wp)Input
On entry: the argument for which PSP must be evaluated.
PSP must either be a module subprogram USEd by, or declared as EXTERNAL in, the (sub)program from which G02HFF is called. Arguments denoted as Input must not be changed by this procedure.
3:   INDW – INTEGERInput
On entry: the type of regression for which the asymptotic variance-covariance matrix is to be calculated.
INDW<0
Mallows type regression.
INDW=0
Huber type regression.
INDW>0
Schweppe type regression.
4:   INDC – INTEGERInput
On entry: if INDW≠0, INDC must specify the approximation to be used.
If INDC=1, averaging over residuals.
If INDC≠1 , replacing expected by observed.
If INDW=0, INDC is not referenced.
5:   SIGMA – REAL (KIND=nag_wp)Input
On entry: the value of σ^, as given by G02HDF.
Constraint: SIGMA>0.0.
6:   N – INTEGERInput
On entry: n, the number of observations.
Constraint: N>1.
7:   M – INTEGERInput
On entry: m, the number of independent variables.
Constraint: 1≤M<N.
8:   X LDXM – REAL (KIND=nag_wp) arrayInput
On entry: the values of the X matrix, i.e., the independent variables. X ij must contain the ijth element of X, for i=1,2,…,n and j=1,2,…,m.
9:   LDX – INTEGERInput
On entry: the first dimension of the array X as declared in the (sub)program from which G02HFF is called.
Constraint: LDX≥N.
10:   RS N – REAL (KIND=nag_wp) arrayInput
On entry: the residuals from the bounded influence regression. These are given by G02HDF.
11:   WGT N – REAL (KIND=nag_wp) arrayInput
On entry: if INDW≠0, WGT must contain the vector of weights used by the bounded influence regression. These should be used with G02HDF.
If INDW=0, WGT is not referenced.
12:   C LDCM – REAL (KIND=nag_wp) arrayOutput
On exit: the estimate of the variance-covariance matrix.
13:   LDC – INTEGERInput
On entry: the first dimension of the array C as declared in the (sub)program from which G02HFF is called.
Constraint: LDC≥M.
14:   WK M×N+M+1+2×N – REAL (KIND=nag_wp) arrayOutput
On exit: if INDW≠0, WK i, for i=1,2,…,n, will contain the diagonal elements of the matrix D and WK i, for i=n+1,…,2 n, will contain the diagonal elements of matrix P.
The rest of the array is used as workspace.
15:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, | N≤1,
or | M<1,
or | N≤M,
or | LDC<M,
or | LDX<N.
IFAIL=2
On entry, SIGMA≤0.0.
IFAIL=3
If INDW=0 then the matrix XT X is either not positive definite, possibly due to rounding errors, or is ill-conditioned.
If INDW≠0 then the matrix S 1 is singular or almost singular. This may be due to many elements of D being zero.
IFAIL=4
Either the value of 1 n∑i=1 n ψ′ ri σ^=0,
or κ=0,
or ∑i=1 n ψ 2 ri σ^=0.
In this situation G02HFF returns C as XT X-1.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

In general, the accuracy of the variance-covariance matrix will depend primarily on the accuracy of the results from G02HDF.

8 Parallelism and Performance

G02HFF is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
G02HFF makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

G02HFF is only for situations in which X has full column rank.
Care has to be taken in the choice of the ψ function since if ψ′t=0 for too wide a range then either the value of fH will not exist or too many values of Di will be zero and it will not be possible to calculate C.

10 Example

The asymptotic variance-covariance matrix is calculated for a Schweppe type regression. The values of X, σ^ and the residuals and weights are read in. The averaging over residuals approximation is used.

10.1 Program Text

Program Text (g02hffe.f90)

10.2 Program Data

Program Data (g02hffe.d)

10.3 Program Results

Program Results (g02hffe.r)

G02 Chapter Contents
G02 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


G02HKF : NAG Library, Mark 26

G02 Chapter Contents
G02 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

G02HKF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

G02HKF computes a robust estimate of the covariance matrix for an expected fraction of gross errors.

2 Specification

SUBROUTINE G02HKF ( N, M, X, LDX, EPS, COV, THETA, MAXIT, NITMON, TOL, NIT, WK, IFAIL)
INTEGER | N, M, LDX, MAXIT, NITMON, NIT, IFAIL
REAL (KIND=nag_wp) | X(LDX,M), EPS, COV(M*(M+1)/2), THETA(M), TOL, WK(N+M*(M+5)/2)

3 Description

For a set of n observations on m variables in a matrix X, a robust estimate of the covariance matrix, C, and a robust estimate of location, θ, are given by
C=τ 2AT A-1,
where τ 2 is a correction factor and A is a lower triangular matrix found as the solution to the following equations:
zi=A xi-θ,
1 n ∑i= 1 n w zi 2 zi=0,
and
1 n∑i=1 n u zi 2 zi ziT -I=0,
where | xi is a vector of length m containing the elements of the ith row of X,
 | zi is a vector of length m,
 | I is the identity matrix and 0 is the zero matrix,
and | w and u are suitable functions.
G02HKF uses weight functions:
u t= au t 2, if ​t<au 2 u t=1, if ​au 2≤t≤bu 2 u t= bu t 2, if ​t>bu 2
and
w t= 1, if ​t≤cw w t= cw t, if ​t>cw
for constants au, bu and cw.
These functions solve a minimax problem considered by Huber (see Huber (1981)). The values of au, bu and cw are calculated from the expected fraction of gross errors, ε (see Huber (1981) and Marazzi (1987)). The expected fraction of gross errors is the estimated proportion of outliers in the sample.
In order to make the estimate asymptotically unbiased under a Normal model a correction factor, τ 2, is calculated, (see Huber (1981) and Marazzi (1987)).
The matrix C is calculated using G02HLF. Initial estimates of θj, for j=1,2,…,m, are given by the median of the jth column of X and the initial value of A is based on the median absolute deviation (see Marazzi (1987)). G02HKF is based on routines in ROBETH; see Marazzi (1987).

4 References

Huber P J (1981) Robust Statistics Wiley
Marazzi A (1987) Weights for bounded influence regression in ROBETH Cah. Rech. Doc. IUMSP, No. 3 ROB 3 Institut Universitaire de Médecine Sociale et Préventive, Lausanne

5 Arguments

1:   N – INTEGERInput
On entry: n, the number of observations.
Constraint: N>1.
2:   M – INTEGERInput
On entry: m, the number of columns of the matrix X, i.e., number of independent variables.
Constraint: 1≤M≤N.
3:   X LDXM – REAL (KIND=nag_wp) arrayInput
On entry: X ij must contain the ith observation for the jth variable, for i=1,2,…,N and j=1,2,…,M.
4:   LDX – INTEGERInput
On entry: the first dimension of the array X as declared in the (sub)program from which G02HKF is called.
Constraint: LDX≥N.
5:   EPS – REAL (KIND=nag_wp)Input
On entry: ε, the expected fraction of gross errors expected in the sample.
Constraint: 0.0≤EPS<1.0.
6:   COV M×M+1/2 – REAL (KIND=nag_wp) arrayOutput
On exit: a robust estimate of the covariance matrix, C. The upper triangular part of the matrix C is stored packed by columns. C ij is returned in COV j×j-1/2+i, i≤j.
7:   THETA M – REAL (KIND=nag_wp) arrayOutput
On exit: the robust estimate of the location arguments θj, for j=1,2,…,m.
8:   MAXIT – INTEGERInput
On entry: the maximum number of iterations that will be used during the calculation of the covariance matrix.
Suggested value: 150.
Constraint: MAXIT>0.
9:   NITMON – INTEGERInput
On entry: indicates the amount of information on the iteration that is printed.
NITMON>0
The value of A, θ and δ (see Section 7) will be printed at the first and every NITMON iterations.
NITMON≤0
No iteration monitoring is printed.
When printing occurs the output is directed to the current advisory message unit (see X04ABF).
10:   TOL – REAL (KIND=nag_wp)Input
On entry: the relative precision for the final estimates of the covariance matrix.
Constraint: TOL>0.0.
11:   NIT – INTEGEROutput
On exit: the number of iterations performed.
12:   WK N+M×M+5/2 – REAL (KIND=nag_wp) arrayWorkspace
13:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, | N≤1,
or | M<1,
or | N<M,
or | LDX<N,
or | EPS<0.0,
or | EPS≥1.0,
or | TOL≤0.0,
or | MAXIT≤0.
IFAIL=2
On entry, a variable has a constant value, i.e., all elements in a column of X are identical.
IFAIL=3
The iterative procedure to find C has failed to converge in MAXIT iterations.
IFAIL=4
The iterative procedure to find C has become unstable. This may happen if the value of EPS is too large for the sample.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

On successful exit the accuracy of the results is related to the value of TOL; see Section 5. At an iteration let
(i) | d 1= the maximum value of the absolute relative change in A
(ii) | d 2= the maximum absolute change in u zi 2
(iii) | d 3= the maximum absolute relative change in θj
and let δ=max d 1,d 2,d 3. Then the iterative procedure is assumed to have converged when δ<TOL.

8 Parallelism and Performance

G02HKF is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
G02HKF makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The existence of A, and hence C, will depend upon the function u (see Marazzi (1987)); also if X is not of full rank a value of A will not be found. If the columns of X are almost linearly related, then convergence will be slow.

10 Example

A sample of 10 observations on three variables is read in and the robust estimate of the covariance matrix is computed assuming 10% gross errors are to be expected. The robust covariance is then printed.

10.1 Program Text

Program Text (g02hkfe.f90)

10.2 Program Data

Program Data (g02hkfe.d)

10.3 Program Results

Program Results (g02hkfe.r)

G02 Chapter Contents
G02 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


G02HLF : NAG Library, Mark 26

G02 Chapter Contents
G02 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

G02HLF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

G02HLF calculates a robust estimate of the covariance matrix for user-supplied weight functions and their derivatives.

2 Specification

SUBROUTINE G02HLF ( UCV, RUSER, INDM, N, M, X, LDX, COV, A, WT, THETA, BL, BD, MAXIT, NITMON, TOL, NIT, WK, IFAIL)
INTEGER | INDM, N, M, LDX, MAXIT, NITMON, NIT, IFAIL
REAL (KIND=nag_wp) | RUSER(*), X(LDX,M), COV(M*(M+1)/2), A(M*(M+1)/2), WT(N), THETA(M), BL, BD, TOL, WK(2*M)
EXTERNAL | UCV

3 Description

For a set of n observations on m variables in a matrix X, a robust estimate of the covariance matrix, C, and a robust estimate of location, θ, are given by:
C=τ 2AT A-1,
where τ 2 is a correction factor and A is a lower triangular matrix found as the solution to the following equations.
zi=A xi-θ
1 n ∑i= 1 n w zi 2 zi=0
and
1 n∑i=1 n u zi 2 zi ziT -v zi 2 I=0,
where | xi is a vector of length m containing the elements of the ith row of X,
 | zi is a vector of length m,
 | I is the identity matrix and 0 is the zero matrix,
and | w and u are suitable functions.
G02HLF covers two situations:
(i) | v t=1 for all t,
(ii) | v t=u t.
The robust covariance matrix may be calculated from a weighted sum of squares and cross-products matrix about θ using weights wti=u zi. In case (i) a divisor of n is used and in case (ii) a divisor of ∑i=1 n wti is used. If w.=u., then the robust covariance matrix can be calculated by scaling each row of X by wti and calculating an unweighted covariance matrix about θ.
In order to make the estimate asymptotically unbiased under a Normal model a correction factor, τ 2, is needed. The value of the correction factor will depend on the functions employed (see Huber (1981) and Marazzi (1987)).
G02HLF finds A using the iterative procedure as given by Huber.
Ak=Sk+I A k-1
and
θ jk=bjD 1+θ j k- 1,
where Sk=s jl, for j=1,2,…,m and l=1,2,…,m, is a lower triangular matrix such that:
s jl= -min max h jl/D 3,-BL,BL, j>l -min max h jj/2 D 3-D 4/D 2,-BD,BD, j=l ,
where
  • D 1=∑i=1 n w zi 2+1 m w′zi 2 zi 2
  • D 2=∑i=1 n 1 p u′zi 2 zi 2+2 u zi 2 zi 2-v′zi 2 zi 2
  • D 3=1 m+2 ∑i=1 n 1 m u′zi 2 zi 2+2 u zi 2+u zi 2 zi 2 2
  • D 4=∑i=1 n 1 m u zi 2 zi 2 2-v zi 2 2
  • h jl=∑i=1 n u zi 2 z ijz il, for j>l
  • h jj=∑i=1 n u zi 2z ij 2-z ij 2 2/m
  • bj=∑i=1 n w zi 2x ij-bj
  • and BD and BL are suitable bounds.
G02HLF is based on routines in ROBETH; see Marazzi (1987).

4 References

Huber P J (1981) Robust Statistics Wiley
Marazzi A (1987) Weights for bounded influence regression in ROBETH Cah. Rech. Doc. IUMSP, No. 3 ROB 3 Institut Universitaire de Médecine Sociale et Préventive, Lausanne

5 Arguments

1:   UCV – SUBROUTINE, supplied by the user.External Procedure
UCV must return the values of the functions u and w and their derivatives for a given value of its argument.
The specification of UCV is:
SUBROUTINE UCV ( T, RUSER, U, UD, W, WD)
REAL (KIND=nag_wp) T, RUSER(*), U, UD, W, WD
1:   T – REAL (KIND=nag_wp)Input
On entry: the argument for which the functions u and w must be evaluated.
2:   RUSER* – REAL (KIND=nag_wp) arrayUser Workspace
UCV is called with the argument RUSER as supplied to G02HLF. You are free to use the array RUSER to supply information to UCV as an alternative to using COMMON global variables.
3:   U – REAL (KIND=nag_wp)Output
On exit: the value of the u function at the point T.
Constraint: U≥0.0.
4:   UD – REAL (KIND=nag_wp)Output
On exit: the value of the derivative of the u function at the point T.
5:   W – REAL (KIND=nag_wp)Output
On exit: the value of the w function at the point T.
Constraint: W≥0.0.
6:   WD – REAL (KIND=nag_wp)Output
On exit: the value of the derivative of the w function at the point T.
UCV must either be a module subprogram USEd by, or declared as EXTERNAL in, the (sub)program from which G02HLF is called. Arguments denoted as Input must not be changed by this procedure.
2:   RUSER* – REAL (KIND=nag_wp) arrayUser Workspace
RUSER is not used by G02HLF, but is passed directly to UCV and may be used to pass information to this routine as an alternative to using COMMON global variables.
3:   INDM – INTEGERInput
On entry: indicates which form of the function v will be used.
INDM=1
v=1.
INDM≠1
v=u.
4:   N – INTEGERInput
On entry: n, the number of observations.
Constraint: N>1.
5:   M – INTEGERInput
On entry: m, the number of columns of the matrix X, i.e., number of independent variables.
Constraint: 1≤M≤N.
6:   X LDXM – REAL (KIND=nag_wp) arrayInput
On entry: X ij must contain the ith observation on the jth variable, for i=1,2,…,n and j=1,2,…,m.
7:   LDX – INTEGERInput
On entry: the first dimension of the array X as declared in the (sub)program from which G02HLF is called.
Constraint: LDX≥N.
8:   COV M×M+1/2 – REAL (KIND=nag_wp) arrayOutput
On exit: contains a robust estimate of the covariance matrix, C. The upper triangular part of the matrix C is stored packed by columns (lower triangular stored by rows), C ij is returned in COV j×j-1/2+i, i≤j.
9:   A M×M+1/2 – REAL (KIND=nag_wp) arrayInput/Output
On entry: an initial estimate of the lower triangular real matrix A. Only the lower triangular elements must be given and these should be stored row-wise in the array.
The diagonal elements must be ≠0, and in practice will usually be >0. If the magnitudes of the columns of X are of the same order, the identity matrix will often provide a suitable initial value for A. If the columns of X are of different magnitudes, the diagonal elements of the initial value of A should be approximately inversely proportional to the magnitude of the columns of X.
Constraint: A j×j-1/2+j≠0.0, for j=1,2,…,m.
On exit: the lower triangular elements of the inverse of the matrix A, stored row-wise.
10:   WT N – REAL (KIND=nag_wp) arrayOutput
On exit: WT i contains the weights, wti=u zi 2, for i=1,2,…,n.
11:   THETA M – REAL (KIND=nag_wp) arrayInput/Output
On entry: an initial estimate of the location argument, θj, for j=1,2,…,m.
In many cases an initial estimate of θj=0, for j=1,2,…,m, will be adequate. Alternatively medians may be used as given by G07DAF.
On exit: contains the robust estimate of the location argument, θj, for j=1,2,…,m.
12:   BL – REAL (KIND=nag_wp)Input
On entry: the magnitude of the bound for the off-diagonal elements of Sk, BL.
Suggested value: BL=0.9.
Constraint: BL>0.0.
13:   BD – REAL (KIND=nag_wp)Input
On entry: the magnitude of the bound for the diagonal elements of Sk, BD.
Suggested value: BD=0.9.
Constraint: BD>0.0.
14:   MAXIT – INTEGERInput
On entry: the maximum number of iterations that will be used during the calculation of A.
Suggested value: MAXIT=150.
Constraint: MAXIT>0.
15:   NITMON – INTEGERInput
On entry: indicates the amount of information on the iteration that is printed.
NITMON>0
The value of A, θ and δ (see Section 7) will be printed at the first and every NITMON iterations.
NITMON≤0
No iteration monitoring is printed.
When printing occurs the output is directed to the current advisory message unit (see X04ABF).
16:   TOL – REAL (KIND=nag_wp)Input
On entry: the relative precision for the final estimates of the covariance matrix. Iteration will stop when maximum δ (see Section 7) is less than TOL.
Constraint: TOL>0.0.
17:   NIT – INTEGEROutput
On exit: the number of iterations performed.
18:   WK 2×M – REAL (KIND=nag_wp) arrayWorkspace
19:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, | N≤1,
or | M<1,
or | N<M,
or | LDX<N.
IFAIL=2
On entry, | TOL≤0.0,
or | MAXIT≤0,
or | diagonal element of A=0.0,
or | BL≤0.0,
or | BD≤0.0.
IFAIL=3
A column of X has a constant value.
IFAIL=4
Value of U or W returned by UCV<0.
IFAIL=5
The routine has failed to converge in MAXIT iterations.
IFAIL=6
One of the following is zero: D 1, D 2 or D 3.
This may be caused by the functions u or w being too strict for the current estimate of A (or C). You should try either a larger initial estimate of A or make u and w less strict.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

On successful exit the accuracy of the results is related to the value of TOL; see Section 5. At an iteration let
(i) | d 1= the maximum value of s jl
(ii) | d 2= the maximum absolute change in wt i
(iii) | d 3= the maximum absolute relative change in θj
and let δ=max d 1,d 2,d 3. Then the iterative procedure is assumed to have converged when δ<TOL.

8 Parallelism and Performance

G02HLF makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The existence of A will depend upon the function u (see Marazzi (1987)); also if X is not of full rank a value of A will not be found. If the columns of X are almost linearly related, then convergence will be slow.

10 Example

A sample of 10 observations on three variables is read in along with initial values for A and THETA and argument values for the u and w functions, cu and cw. The covariance matrix computed by G02HLF is printed along with the robust estimate of θ. UCV computes the Huber's weight functions:
u t=1, if  t≤cu 2 u t= cu t 2, if  t>cu 2
and
w t= 1, if   t≤cw w t= cw t, if   t>cw
and their derivatives.

10.1 Program Text

Program Text (g02hlfe.f90)

10.2 Program Data

Program Data (g02hlfe.d)

10.3 Program Results

Program Results (g02hlfe.r)

G02 Chapter Contents
G02 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


G02HMF : NAG Library, Mark 26

G02 Chapter Contents
G02 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

G02HMF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

G02HMF computes a robust estimate of the covariance matrix for user-supplied weight functions. The derivatives of the weight functions are not required.

2 Specification

SUBROUTINE G02HMF ( UCV, RUSER, INDM, N, M, X, LDX, COV, A, WT, THETA, BL, BD, MAXIT, NITMON, TOL, NIT, WK, IFAIL)
INTEGER | INDM, N, M, LDX, MAXIT, NITMON, NIT, IFAIL
REAL (KIND=nag_wp) | RUSER(*), X(LDX,M), COV(M*(M+1)/2), A(M*(M+1)/2), WT(N), THETA(M), BL, BD, TOL, WK(2*M)
EXTERNAL | UCV

3 Description

For a set of n observations on m variables in a matrix X, a robust estimate of the covariance matrix, C, and a robust estimate of location, θ, are given by
C=τ 2AT A-1,
where τ 2 is a correction factor and A is a lower triangular matrix found as the solution to the following equations.
zi=A xi-θ
1 n ∑i= 1 n w zi 2 zi=0
and
1 n∑i=1 n u zi 2 zi ziT -v zi 2 I=0,
where | xi is a vector of length m containing the elements of the ith row of X,
 | zi is a vector of length m,
 | I is the identity matrix and 0 is the zero matrix.
and | w and u are suitable functions.
G02HMF covers two situations:
(i) | v t=1 for all t,
(ii) | v t=u t.
The robust covariance matrix may be calculated from a weighted sum of squares and cross-products matrix about θ using weights wti=u zi. In case (i) a divisor of n is used and in case (ii) a divisor of ∑i=1 n wti is used. If w.=u., then the robust covariance matrix can be calculated by scaling each row of X by wti and calculating an unweighted covariance matrix about θ.
In order to make the estimate asymptotically unbiased under a Normal model a correction factor, τ 2, is needed. The value of the correction factor will depend on the functions employed (see Huber (1981) and Marazzi (1987)).
G02HMF finds A using the iterative procedure as given by Huber; see Huber (1981).
Ak=Sk+I A k-1
and
θ jk=bjD 1+θ j k- 1,
where Sk=s jl, for j=1,2,…,m and l=1,2,…,m is a lower triangular matrix such that
s jl= -min max h jl/D 2,-BL,BL, j>l -min max 12 h jj/D 2-1,-BD,BD, j=l ,
where
  • D 1=∑i=1 n w zi 2
  • D 2=∑i=1 n u zi 2
  • h jl=∑i=1 n u zi 2 z ijz il, for j≥l
  • bj=∑i=1 n w zi 2x ij-bj
and BD and BL are suitable bounds.
The value of τ may be chosen so that C is unbiased if the observations are from a given distribution.
G02HMF is based on routines in ROBETH; see Marazzi (1987).

4 References

Huber P J (1981) Robust Statistics Wiley
Marazzi A (1987) Weights for bounded influence regression in ROBETH Cah. Rech. Doc. IUMSP, No. 3 ROB 3 Institut Universitaire de Médecine Sociale et Préventive, Lausanne

5 Arguments

1:   UCV – SUBROUTINE, supplied by the user.External Procedure
UCV must return the values of the functions u and w for a given value of its argument.
The specification of UCV is:
SUBROUTINE UCV ( T, RUSER, U, W)
REAL (KIND=nag_wp) T, RUSER(*), U, W
1:   T – REAL (KIND=nag_wp)Input
On entry: the argument for which the functions u and w must be evaluated.
2:   RUSER* – REAL (KIND=nag_wp) arrayUser Workspace
UCV is called with the argument RUSER as supplied to G02HMF. You are free to use the array RUSER to supply information to UCV as an alternative to using COMMON global variables.
3:   U – REAL (KIND=nag_wp)Output
On exit: the value of the u function at the point T.
Constraint: U≥0.0.
4:   W – REAL (KIND=nag_wp)Output
On exit: the value of the w function at the point T.
Constraint: W≥0.0.
UCV must either be a module subprogram USEd by, or declared as EXTERNAL in, the (sub)program from which G02HMF is called. Arguments denoted as Input must not be changed by this procedure.
2:   RUSER* – REAL (KIND=nag_wp) arrayUser Workspace
RUSER is not used by G02HMF, but is passed directly to UCV and may be used to pass information to this routine as an alternative to using COMMON global variables.
3:   INDM – INTEGERInput
On entry: indicates which form of the function v will be used.
INDM=1
v=1.
INDM≠1
v=u.
4:   N – INTEGERInput
On entry: n, the number of observations.
Constraint: N>1.
5:   M – INTEGERInput
On entry: m, the number of columns of the matrix X, i.e., number of independent variables.
Constraint: 1≤M≤N.
6:   X LDXM – REAL (KIND=nag_wp) arrayInput
On entry: X ij must contain the ith observation on the jth variable, for i=1,2,…,n and j=1,2,…,m.
7:   LDX – INTEGERInput
On entry: the first dimension of the array X as declared in the (sub)program from which G02HMF is called.
Constraint: LDX≥N.
8:   COV M×M+1/2 – REAL (KIND=nag_wp) arrayOutput
On exit: a robust estimate of the covariance matrix, C. The upper triangular part of the matrix C is stored packed by columns (lower triangular stored by rows), that is C ij is returned in COV j×j-1/2+i, i≤j.
9:   A M×M+1/2 – REAL (KIND=nag_wp) arrayInput/Output
On entry: an initial estimate of the lower triangular real matrix A. Only the lower triangular elements must be given and these should be stored row-wise in the array.
The diagonal elements must be ≠0, and in practice will usually be >0. If the magnitudes of the columns of X are of the same order, the identity matrix will often provide a suitable initial value for A. If the columns of X are of different magnitudes, the diagonal elements of the initial value of A should be approximately inversely proportional to the magnitude of the columns of X.
Constraint: A j×j-1/2+j≠0.0, for j=1,2,…,m.
On exit: the lower triangular elements of the inverse of the matrix A, stored row-wise.
10:   WT N – REAL (KIND=nag_wp) arrayOutput
On exit: WT i contains the weights, wti=u zi 2, for i=1,2,…,n.
11:   THETA M – REAL (KIND=nag_wp) arrayInput/Output
On entry: an initial estimate of the location argument, θj, for j=1,2,…,m.
In many cases an initial estimate of θj=0, for j=1,2,…,m, will be adequate. Alternatively medians may be used as given by G07DAF.
On exit: contains the robust estimate of the location argument, θj, for j=1,2,…,m.
12:   BL – REAL (KIND=nag_wp)Input
On entry: the magnitude of the bound for the off-diagonal elements of Sk, BL.
Suggested value: BL=0.9.
Constraint: BL>0.0.
13:   BD – REAL (KIND=nag_wp)Input
On entry: the magnitude of the bound for the diagonal elements of Sk, BD.
Suggested value: BD=0.9.
Constraint: BD>0.0.
14:   MAXIT – INTEGERInput
On entry: the maximum number of iterations that will be used during the calculation of A.
Suggested value: MAXIT=150.
Constraint: MAXIT>0.
15:   NITMON – INTEGERInput
On entry: indicates the amount of information on the iteration that is printed.
NITMON>0
The value of A, θ and δ (see Section 7) will be printed at the first and every NITMON iterations.
NITMON≤0
No iteration monitoring is printed.
When printing occurs the output is directed to the current advisory message channel (See X04ABF.)
16:   TOL – REAL (KIND=nag_wp)Input
On entry: the relative precision for the final estimate of the covariance matrix. Iteration will stop when maximum δ (see Section 7) is less than TOL.
Constraint: TOL>0.0.
17:   NIT – INTEGEROutput
On exit: the number of iterations performed.
18:   WK 2×M – REAL (KIND=nag_wp) arrayWorkspace
19:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, | N≤1,
or | M<1,
or | N<M,
or | LDX<N.
IFAIL=2
On entry, | TOL≤0.0,
or | MAXIT≤0,
or | diagonal element of A=0.0,
or | BL≤0.0,
or | BD≤0.0.
IFAIL=3
A column of X has a constant value.
IFAIL=4
Value of U or W returned by UCV<0.
IFAIL=5
The routine has failed to converge in MAXIT iterations.
IFAIL=6
Either the sum D 1 or the sum D 2 is zero. This may be caused by the functions u or w being too strict for the current estimate of A (or C). You should either try a larger initial estimate of A or make the u and w functions less strict.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

On successful exit the accuracy of the results is related to the value of TOL; see Section 5. At an iteration let
(i) | d 1= the maximum value of s jl
(ii) | d 2= the maximum absolute change in wt i
(iii) | d 3= the maximum absolute relative change in θj
and let δ=max d 1,d 2,d 3. Then the iterative procedure is assumed to have converged when δ<TOL.

8 Parallelism and Performance

G02HMF makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The existence of A will depend upon the function u (see Marazzi (1987)); also if X is not of full rank a value of A will not be found. If the columns of X are almost linearly related, then convergence will be slow.
If derivatives of the u and w functions are available then the method used in G02HLF will usually give much faster convergence.

10 Example

A sample of 10 observations on three variables is read in along with initial values for A and θ and argument values for the u and w functions, cu and cw. The covariance matrix computed by G02HMF is printed along with the robust estimate of θ.
UCV computes the Huber's weight functions:
u t=1, if  t≤cu 2 u t= cu t 2, if  t>cu 2
and
w t= 1, if   t≤cw w t= cw t, if   t>cw.

10.1 Program Text

Program Text (g02hmfe.f90)

10.2 Program Data

Program Data (g02hmfe.d)

10.3 Program Results

Program Results (g02hmfe.r)

G02 Chapter Contents
G02 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


G02 Chapter Introduction : NAG Library, Mark 26

G02 Chapter Contents
NAG Library Manual

NAG Library Chapter Introduction

G02 – Correlation and Regression Analysis

▸▿ Contents

1 Scope of the Chapter
▸▿ 2 Background to the Problems
▸▿ 2.1 Correlation
2.1.1 Aims of correlation analysis
2.1.2 Correlation coefficients
2.1.3 Partial correlation
2.1.4 Robust estimation of correlation coefficients
2.1.5 Missing values
2.1.6 Nearest Correlation Matrix
▸▿ 2.2 Regression
2.2.1 Aims of regression modelling
2.2.2 Regression models and designed experiments
2.2.3 Selecting the regression model
▸▿ 2.3 Linear Regression Models
2.3.1 Fitting the regression model – least squares estimation
2.3.2 Computational methods for least squares regression
2.3.3 Examining the fit of the model
2.3.4 Ridge regression
2.4 Robust Estimation
2.5 Generalized Linear Models
2.6 Linear Mixed Effects Regression
▸▿ 2.7 Quantile Regression
2.7.1 Finding a sample quantile as an optimization problem
2.7.2 From least squares to quantile regression
2.7.3 Quantile regression as a linear programming problem
2.7.4 Estimation of the covariance matrix
2.8 Latent Variable Methods
2.9 LARS, LASSO and Forward Stagewise Regression
▸▿ 3 Recommendations on Choice and Use of Available Routines
▸▿ 3.1 Correlation
3.1.1 Product-moment correlation
3.1.2 Product-moment correlation with missing values
3.1.3 Nonparametric correlation
3.1.4 Partial correlation
3.1.5 Robust correlation
3.1.6 Nearest correlation matrix
▸▿ 3.2 Regression
3.2.1 Simple linear regression
3.2.2 Ridge regression
3.2.3 Polynomial regression and nonlinear regression
3.2.4 Multiple linear regression – general linear model
3.2.5 Selecting regression models
3.2.6 Residuals
3.2.7 Robust regression
3.2.8 Generalized linear models
3.2.9 Linear mixed effects regression
3.2.10 Linear quantile regression
3.2.11 Partial Least Squares (PLS)
3.2.12 LARS, LASSO and Forward Stagewise Regression
4 Functionality Index
5 Auxiliary Routines Associated with Library Routine Arguments
6 Routines Withdrawn or Scheduled for Withdrawal
7 References

1 Scope of the Chapter

This chapter is concerned with two techniques
(i) | correlation analysis and
(ii) | regression modelling,
both of which are concerned with determining the inter-relationships among two or more variables.
Other chapters of the NAG Library which cover similar problems are Chapters E02 and E04. Chapter E02 routines may be used to fit linear models by criteria other than least squares, and also for polynomial regression; Chapter E04 routines may be used to fit nonlinear models and linearly constrained linear models.

2 Background to the Problems

2.1 Correlation

2.1.1 Aims of correlation analysis

Correlation analysis provides a single summary statistic – the correlation coefficient – describing the strength of the association between two variables. The most common types of association which are investigated by correlation analysis are linear relationships, and there are a number of forms of linear correlation coefficients for use with different types of data.

2.1.2 Correlation coefficients

The (Pearson) product-moment correlation coefficients measure a linear relationship, while Kendall's tau and Spearman's rank order correlation coefficients measure monotonicity only. All three coefficients range from -1.0 to +1.0. A coefficient of zero always indicates that no linear relationship exists; a +1.0 coefficient implies a ‘perfect’ positive relationship (i.e., an increase in one variable is always associated with a corresponding increase in the other variable); and a coefficient of -1.0 indicates a ‘perfect’ negative relationship (i.e., an increase in one variable is always associated with a corresponding decrease in the other variable).
Consider the bivariate scattergrams in Figure 1: (a) and (b) show strictly linear functions for which the values of the product-moment correlation coefficient, and (since a linear function is also monotonic) both Kendall's tau and Spearman's rank order coefficients, would be +1.0 and -1.0 respectively. However, though the relationships in figures (c) and (d) are respectively monotonically increasing and monotonically decreasing, for which both Kendall's and Spearman's nonparametric coefficients would be +1.0 (in (c)) and -1.0 (in (d)), the functions are nonlinear so that the product-moment coefficients would not take such ‘perfect’ extreme values. There is no obvious relationship between the variables in figure (e), so all three coefficients would assume values close to zero, while in figure (f) though there is an obvious parabolic relationship between the two variables, it would not be detected by any of the correlation coefficients which would again take values near to zero; it is important therefore to examine scattergrams as well as the correlation coefficients.
In order to decide which type of correlation is the most appropriate, it is necessary to appreciate the different groups into which variables may be classified. Variables are generally divided into four types of scales: the nominal scale, the ordinal scale, the interval scale, and the ratio scale. The nominal scale is used only to categorise data; for each category a name, perhaps numeric, is assigned so that two different categories will be identified by distinct names. The ordinal scale, as well as categorising the observations, orders the categories. Each category is assigned a distinct identifying symbol, in such a way that the order of the symbols corresponds to the order of the categories. (The most common system for ordinal variables is to assign numerical identifiers to the categories, though if they have previously been assigned alphabetic characters, these may be transformed to a numerical system by any convenient method which preserves the ordering of the categories.) The interval scale not only categorises and orders the observations, but also quantifies the comparison between categories; this necessitates a common unit of measurement and an arbitrary zero-point. Finally, the ratio scale is similar to the interval scale, except that it has an absolute (as opposed to arbitrary) zero-point.
For a more complete discussion of these four types of scales, and some examples, you are referred to Churchman and Ratoosh (1959) and Hays (1970).
Figure 1
Product-moment correlation coefficients are used with variables which are interval (or ratio) scales; these coefficients measure the amount of spread about the linear least squares equation. For a product-moment correlation coefficient, r, based on n pairs of observations, testing against the null hypothesis that there is no correlation between the two variables, the statistic
r⁢n-2 1-r 2
has a Student's t-distribution with n-2 degrees of freedom; its significance can be tested accordingly.
Ranked and ordinal scale data are generally analysed by nonparametric methods – usually either Spearman's or Kendall's tau rank order correlation coefficients, which, as their names suggest, operate solely on the ranks, or relative orders, of the data values. Interval or ratio scale variables may also be validly analysed by nonparametric methods, but such techniques are statistically less powerful than a product-moment method. For a Spearman rank order correlation coefficient, R, based on n pairs of observations, testing against the null hypothesis that there is no correlation between the two variables, for large samples the statistic
R⁢n-2 1-R 2
has approximately a Student's t-distribution with n-2 degrees of freedom, and may be treated accordingly. (This is similar to the product-moment correlation coefficient, r, see above.) Kendall's tau coefficient, based on n pairs of observations, has, for large samples, an approximately Normal distribution with mean zero and standard deviation
4 n+10 9 n n-1
when tested against the null hypothesis that there is no correlation between the two variables; the coefficient should therefore be divided by this standard deviation and tested against the standard Normal distribution, N 0,1.
When the number of ordinal categories a variable takes is large, and the number of ties is relatively small, Spearman's rank order correlation coefficients have advantages over Kendall's tau; conversely, when the number of categories is small, or there are a large number of ties, Kendall's tau is usually preferred. Thus when the ordinal scale is more or less continuous, Spearman's rank order coefficients are preferred, whereas Kendall's tau is used when the data is grouped into a smaller number of categories; both measures do however include corrections for the occurrence of ties, and the basic concepts underlying the two coefficients are quite similar. The absolute value of Kendall's tau coefficient tends to be slightly smaller than Spearman's coefficient for the same set of data.
There is no authoritative dictum on the selection of correlation coefficients – particularly on the advisability of using correlations with ordinal data. This is a matter of discretion for you.

2.1.3 Partial correlation

The correlation coefficients described above measure the association between two variables ignoring any other variables in the system. Suppose there are three variables X,Y and Z as shown in the path diagram below.
Figure 2
The association between Y and Z is made up of the direct association between Y and Z and the association caused by the path through X, that is the association of both Y and Z with the third variable X. For example if Z and Y were cholesterol level and blood pressure and X were age since both blood pressure and cholesterol level may increase with age the correlation between blood pressure and cholesterol level eliminating the effect of age is required.
The correlation between two variables eliminating the effect of a third variable is known as the partial correlation. If ρ zy, ρ zx and ρ xy represent the correlations between x, y and z then the partial correlation between Z and Y given X is
ρ zy-ρ zxρ xy 1-ρ zx 21-ρ xy 2.
The partial correlation is then estimated by using product-moment correlation coefficients.
In general, let a set of variables be partitioned into two groups Y and X with ny variables in Y and nx variables in X and let the variance-covariance matrix of all ny+nx variables be partitioned into
Σ xx Σ yx Σ xy Σ yy .
Then the variance-covariance of Y conditional on fixed values of the X variables is given by
Σ y∣x=Σ yy-Σ yx Σ xx -1 Σ xy.
The partial correlation matrix is then computed by standardizing Σ y∣x.

2.1.4 Robust estimation of correlation coefficients

The product-moment correlation coefficient can be greatly affected by the presence of a few extreme observations or outliers. There are robust estimation procedures which aim to decrease the effect of extreme values.
Mathematically these methods can be described as follows. A robust estimate of the variance-covariance matrix, C, can be written as
C=τ 2AT A-1
where τ 2 is a correction factor to give an unbiased estimator if the data is Normal and A is a lower triangular matrix. Let xi be the vector of values for the ith observation and let zi=A xi-θ, θ being a robust estimate of location, then θ and A are found as solutions to
1 n∑i=1 n w zi 2 zi=0
and
1 n ∑i= 1 n w zi 2 zi ziT -v zi 2 I=0,
where w t, u t and v t are functions such that they return a value of 1 for reasonable values of t and decreasing values for large t. The correlation matrix can then be calculated from the variance-covariance matrix. If w, u, and v returned 1 for all values then the product-moment correlation coefficient would be calculated.

2.1.5 Missing values

When there are missing values in the data these may be handled in one of two ways. Firstly, if a case contains a missing observation for any variable, then that case is omitted in its entirety from all calculations; this may be termed casewise treatment of missing data. Secondly, if a case contains a missing observation for any variable, then the case is omitted from only those calculations involving the variable for which the value is missing; this may be called pairwise treatment of missing data. Pairwise deletion of missing data has the advantage of using as much of the data as possible in the computation of each coefficient. In extreme circumstances, however, it can have the disadvantage of producing coefficients which are based on a different number of cases, and even on different selections of cases or samples; furthermore, the ‘correlation’ matrices formed in this way need not necessarily be positive semidefinite, a requirement for a correlation matrix. Casewise deletion of missing data generally causes fewer cases to be used in the calculation of the coefficients than does pairwise deletion. How great this difference is will obviously depend on the distribution of the missing data, both among cases and among variables.
Pairwise treatment does therefore use more information from the sample, but should not be used without careful consideration of the location of the missing observations in the data matrix, and the consequent effect of processing the missing data in that fashion.

2.1.6 Nearest Correlation Matrix

A correlation matrix is, by definition, a symmetric, positive semidefinite matrix with unit diagonals and all elements in the range -1,1.
In practice, rather than having a true correlation matrix, you may find that you have a matrix of pairwise correlations. This usually occurs in the presence of missing values, when the missing values are treated in a pairwise fashion as discussed in Section 2.1.5. Matrices constructed in this way may not be not positive semidefinite, and therefore are not a valid correlation matrix. However, a valid correlation matrix can be calculated that is in some sense ‘close’ to the original.
Given an n×n matrix, G, there are a number of available ways of computing the ‘nearest’ correlation matrix, Σ to G:
(a) Frobenius Norm
Find Σ such that
∑ i=1 n ∑ j=1 n s ij - σ ij 2
is minimized.
Where S is the symmetric matrix defined as S = 12 G+GT and s ij and σ ij denotes the elements of S and Σ respectively.
A weighted Frobenius norm can also be used. The term being summed across therefore becomes wi wj s ij - σ ij 2 if row and column weights are being used or w ij s ij - σ ij 2 when element-wise weights are used.
(b) Factor Loading Method
This method is similar to (a) in that it finds a Σ that is closest to S in the Frobenius norm. However, it also ensures that Σ has a k-factor structure, that is Σ can be written as
Σ= X XT+ diag I-X XT
where I is the identity matrix and X has n rows and k columns.
X is often referred to as the factor loading matrix. This problem primarily arises when a factor model ξ=Xη+Dε is used to describe a multivariate time series or collateralized debt obligations. In this model η∈ℝk and ξ∈ℝn are vectors of independent random variables having zero mean and unit variance, with η and ε independent of each other, and X∈ℝ n×k with D∈ℝ n×n diagonal. In the case of modelling debt obligations ξ can, for example, model the equity returns of n different companies of a portfolio where η describes k factors influencing all companies, in contrast to the elements of ε having only an effect on the equity of the corresponding company. With this model the complex behaviour of a portfolio, with potentially thousands of equities, is captured by looking at the major factors driving the behaviour.
The number of factors usually chosen is a lot smaller than n, perhaps between 1 and 10, yielding a large reduction in the complexity. The number of the factors, k, which yields a matrix X such that G-X XT+diag I-X XT F is within a required tolerance can also be determined, by experimenting with the input k and comparing the norms.
(c) Shrinking
Find the smallest α such that
αT+1-α S
is a correlation matrix. Here T is a positive definite target matrix with unit diagonal. T can be chosen to fix elements in the resulting matrix by having elements equal to the corresponding element in S.
Shrinking algorithms can be very efficient, using bisection to find α. A solution is always found, as α=1 gives the result T, which is necessarily a valid correlation matrix.
Note that shrinking algorithms do not find the nearest correlation matrix in any mathematical sense, simply the smallest α in the structure above.

2.2 Regression

2.2.1 Aims of regression modelling

In regression analysis the relationship between one specific random variable, the dependent or response variable, and one or more known variables, called the independent variables or covariates, is studied. This relationship is represented by a mathematical model, or an equation, which associates the dependent variable with the independent variables, together with a set of relevant assumptions. The independent variables are related to the dependent variable by a function, called the regression function, which involves a set of unknown parameters. Values of the parameters which give the best fit for a given set of data are obtained; these values are known as the estimates of the parameters.
The reasons for using a regression model are twofold. The first is to obtain a description of the relationship between the variables as an indicator of possible causality. The second reason is to predict the value of the dependent variable from a set of values of the independent variables. Accordingly, the most usual statistical problems involved in regression analysis are:
(i) | to obtain best estimates of the unknown regression parameters;
(ii) | to test hypotheses about these parameters;
(iii) | to determine the adequacy of the assumed model; and
(iv) | to verify the set of relevant assumptions.

2.2.2 Regression models and designed experiments

One application of regression models is in the analysis of experiments. In this case the model relates the dependent variable to qualitative independent variables known as factors. Factors may take a number of different values known as levels. For example, in an experiment in which one of four different treatments is applied, the model will have one factor with four levels. Each level of the factor can be represented by a dummy variable taking the values 0 or 1. So in the example there are four dummy variables xj, for j=1,2,3,4, such that:
x ij =1​ if the ​i th observation received the ​j th treatment =0​ otherwise,
along with a variable for the mean x 0:
x i 0 =1​ for all ​i.
If there were 7 observations the data would be:
Treatment Y x 0 x 1 x 2 x 3 x 4 1 y 1 1 1 0 0 0 2 y 2 1 0 1 0 0 2 y 3 1 0 1 0 0 3 y 4 1 0 0 1 0 3 y 5 1 0 0 1 0 4 y 6 1 0 0 0 1 4 y 7 1 0 0 0 1
When dummy variables are used it is common for the model not to be of full rank. In the case above, the model would not be of full rank because
x i 4=x i 0-x i 1-x i 2-x i 3,  i=1,2,…,7.
This means that the effect of x 4 cannot be distinguished from the combined effect of x 0,x 1,x 2 and x 3. This is known as aliasing. In this situation, the aliasing can be deduced from the experimental design and as a result the model to be fitted; in such situations it is known as intrinsic aliasing. In the example above no matter how many times each treatment is replicated (other than 0) the aliasing will still be present. If the aliasing is due to a particular dataset to which the model is to be fitted then it is known as extrinsic aliasing. If in the example above observation 1 was missing then the x 1 term would also be aliased. In general intrinsic aliasing may be overcome by changing the model, e.g., remove x 0 or x 1 from the model, or by introducing constraints on the parameters, e.g., β 1+β 2+β 3+β 4=0.
If aliasing is present then there will no longer be a unique set of least squares estimates for the parameters of the model but the fitted values will still have a unique estimate. Some linear functions of the parameters will also have unique estimates; these are known as estimable functions. In the example given above the functions (β 0+β 1) and (β 2-β 3) are both estimable.

2.2.3 Selecting the regression model

In many situations there are several possible independent variables, not all of which may be needed in the model. In order to select a suitable set of independent variables, two basic approaches can be used.
(a) | All possible regressions In this case all the possible combinations of independent variables are fitted and the one considered the best selected. To choose the best, two conflicting criteria have to be balanced. One is the fit of the model which will improve as more variables are added to the model. The second criterion is the desire to have a model with a small number of significant terms. Depending on how the model is fit, statistics such as R 2, which gives the proportion of variation explained by the model, and Cp, which tries to balance the size of the residual sum of squares against the number of terms in the model, can be used to aid in the choice of model.
(b) | Stepwise model building In stepwise model building the regression model is constructed recursively, adding or deleting the independent variables one at a time. When the model is built up the procedure is known as forward selection. The first step is to choose the single variable which is the best predictor. The second independent variable to be added to the regression equation is that which provides the best fit in conjunction with the first variable. Further variables are then added in this recursive fashion, adding at each step the optimum variable, given the other variables already in the equation. Alternatively, backward elimination can be used. This is when all variables are added and then the variables dropped one at a time, the variable dropped being the one which has the least effect on the fit of the model at that stage. There are also hybrid techniques which combine forward selection with backward elimination.

2.3 Linear Regression Models

When the regression model is linear in the parameters (but not necessarily in the independent variables), then the regression model is said to be linear; otherwise the model is classified as nonlinear.
The most elementary form of regression model is the simple linear regression of the dependent variable, Y, on a single independent variable, x, which takes the form
E Y=β 0+β 1 x (1)
where E Y is the expected or average value of Y and β 0 and β 1 are the parameters whose values are to be estimated, or, if the regression is required to pass through the origin (i.e., no constant term),
E Y=β 1 x (2)
where β 1 is the only unknown parameter.
An extension of this is multiple linear regression in which the dependent variable, Y, is regressed on the p (p>1) independent variables, x 1,x 2,…,xp, which takes the form
E Y=β 0+β 1x 1+β 2x 2+⋯+βpxp (3)
where β 1,β 2,…,βp and β 0 are the unknown parameters. Multiple linear regression models test include factors are sometimes known as General Linear (Regression) Models.
A special case of multiple linear regression is polynomial linear regression, in which the p independent variables are in fact powers of the same single variable x (i.e., xj=xj, for j=1,2,…,p).
In this case, the model defined by (3) becomes
E Y=β 0+β 1 x+β 2 x 2+⋯+βp xp. (4)
There are a great variety of nonlinear regression models; one of the most common is exponential regression, in which the equation may take the form
E Y=a+b e cx. (5)
It should be noted that equation (4) represents a linear regression, since even though the equation is not linear in the independent variable, x, it is linear in the parameters β 0,β 1,β 2,….,βp, whereas the regression model of equation (5) is nonlinear, as it is nonlinear in the parameters (a, b and c).

2.3.1 Fitting the regression model – least squares estimation

One method used to determine values for the parameters is, based on a given set of data, to minimize the sums of squares of the differences between the observed values of the dependent variable and the values predicted by the regression equation for that set of data – hence the term least squares estimation. For example, if a regression model of the type given by equation (3), namely
E Y=β 0x 0+β 1x 1+β 2x 2+⋯+βpxp,
where x 0=1 for all observations, is to be fitted to the n data points
x 01,x 11,x 21,…,x p 1,y 1 x 02,x 12,x 22,…,x p 2,y 2 ⋮ x 0 n,x 1 n,x 2 n,…,x pn,yn (6)
such that
yi=β 0x 0+β 1x 1 i+β 2x 2 i+⋯+βpx pi+ei,   i= 1,2,…,n
where ei are unknown independent random errors with E ei=0 and var ei=σ 2, σ 2 being a constant, then the method used is to calculate the estimates of the regression parameters β 0,β 1,β 2,…,βp by minimizing
∑i=1 n ei 2. (7)
If the errors do not have constant variance, i.e.,
var ei=σi 2=σ 2 wi
then weighted least squares estimation is used in which
∑i=1 n wi ei 2
is minimized. For a more complete discussion of these least squares regression methods, and details of the mathematical techniques used, see Draper and Smith (1985) or Kendall and Stuart (1973).

2.3.2 Computational methods for least squares regression

Let X be the n by p matrix of independent variables and y be the vector of values for the dependent variable. To find the least squares estimates of the vector of parameters, β^, the QR decomposition of X is found, i.e.,
X=Q R*
where R*= R 0 , R being a p by p upper triangular matrix, and Q an n by n orthogonal matrix. If R is of full rank then β^ is the solution to
R β^=c 1
where c=QT y and c 1 is the first p rows of c. If R is not of full rank, a solution is obtained by means of a singular value decomposition (SVD) of R,
R=Q* D 0 0 0 PT,
where D is a k by k diagonal matrix with nonzero diagonal elements, k being the rank of R, and Q* and P are p by p orthogonal matrices. This gives the solution
β^=P 1 D-1 Q*1 T c 1,
P 1 being the first k columns of P and Q*1 being the first k columns of Q*.
This will be only one of the possible solutions. Other estimates may be obtained by applying constraints to the parameters. If weighted regression with a vector of weights w is required then both X and y are premultiplied by w 1/2.
The method described above will, in general, be more accurate than methods based on forming (XT X), (or a scaled version), and then solving the equations
XT X β^=XT y.

2.3.3 Examining the fit of the model

Having fitted a model two questions need to be asked: first, ‘are all the terms in the model needed?’ and second, ‘is there some systematic lack of fit?’. To answer the first question either confidence intervals can be computed for the parameters or t-tests can be calculated to test hypotheses about the regression parameters – for example, whether the value of the parameter, βk, is significantly different from a specified value, bk (often zero). If the estimate of βk is β^k and its standard error is se β^k then the t-statistic is
β^k-bk se β^k .
It should be noted that both the tests and the confidence intervals may not be independent. Alternatively F-tests based on the residual sums of squares for different models can also be used to test the significance of terms in the model. If model 1, giving residual sum of squares RSS 1 with degrees of freedom ν 1, is a sub-model of model 2, giving residual sum of squares RSS 2 with degrees of freedom ν 2, i.e., all terms in model 1 are also in model 2, then to test if the extra terms in model 2 are needed the F-statistic
F=RSS 1-RSS 2/ν 1-ν 2 RSS 2/ν 2
may be used. These tests and confidence intervals require the additional assumption that the errors, ei, are Normally distributed.
To check for systematic lack of fit the residuals, ri=yi-y^i, where y^i is the fitted value, should be examined. If the model is correct then they should be random with no discernible pattern. Due to the way they are calculated the residuals do not have constant variance. Now the vector of fitted values can be written as a linear combination of the vector of observations of the dependent variable, y, y^=Hy. The variance-covariance matrix of the residuals is then I-H σ 2, I being the identity matrix. The diagonal elements of H, h ii, can therefore be used to standardize the residuals. The h ii are a measure of the effect of the ith observation on the fitted model and are sometimes known as leverages.
If the observations were taken serially the residuals may also be used to test the assumption of the independence of the ei and hence the independence of the observations.

2.3.4 Ridge regression

When data on predictor variables x are multicollinear, ridge regression models provide an alternative to variable selection in the multiple regression model. In the ridge regression case, parameter estimates in the linear model are found by penalised least squares:
∑ i=1 n ∑ j=1 p x ij β^j - yi 2 + h ∑ j=1 p β^j 2 ,   h∈ℝ+ ,
where the value of the ridge parameter h controls the trade-off between the goodness-of-fit and smoothness of a solution.

2.4 Robust Estimation

Least squares regression can be greatly affected by a small number of unusual, atypical, or extreme observations. To protect against such occurrences, robust regression methods have been developed. These methods aim to give less weight to an observation which seems to be out of line with the rest of the data given the model under consideration. That is to seek to bound the influence. For a discussion of influence in regression, see Hampel et al. (1986) and Huber (1981).
There are two ways in which an observation for a regression model can be considered atypical. The values of the independent variables for the observation may be atypical or the residual from the model may be large.
The first problem of atypical values of the independent variables can be tackled by calculating weights for each observation which reflect how atypical it is, i.e., a strongly atypical observation would have a low weight. There are several ways of finding suitable weights; some are discussed in Hampel et al. (1986).
The second problem is tackled by bounding the contribution of the individual ei to the criterion to be minimized. When minimizing (7) a set of linear equations is formed, the solution of which gives the least squares estimates. The equations are
∑i=1 n eix ij=0, j=0,1,…,k.
These equations are replaced by
∑i=1 n ψ ei/σ x ij=0, j=0,1,…,k, (8)
where σ 2 is the variance of the ei, and ψ is a suitable function which down weights large values of the standardized residuals ei/σ. There are several suggested forms for ψ, one of which is Huber's function,
ψ t= -c,t<c -t,t≤c -c,t>c (9)
Figure 3
The solution to (8) gives the M-estimates of the regression coefficients. The weights can be included in (8) to protect against both types of extreme value. The parameter σ can be estimated by the median absolute deviations of the residuals or as a solution to, in the unweighted case,
∑i=1 n χ ei/σ^=n-k β,
where χ is a suitable function and β is a constant chosen to make the estimate unbiased. χ is often chosen to be ψ 2/2 where ψ is given in (9). Another form of robust regression is to minimize the sum of absolute deviations, i.e.,
∑i=1 n ei.
For details of robust regression, see Hampel et al. (1986) and Huber (1981).
Robust regressions using least absolute deviations can be computed using routines in Chapter E02.

2.5 Generalized Linear Models

Generalized linear models are an extension of the general linear regression model discussed above. They allow a wide range of models to be fitted. These included certain nonlinear regression models, logistic and probit regression models for binary data, and log-linear models for contingency tables. A generalized linear model consists of three basic components:
(a) A suitable distribution for the dependent variable Y. The following distributions are common:
(i) | Normal
(ii) | binomial
(iii) | Poisson
(iv) | gamma
In addition to the obvious uses of models with these distributions it should be noted that the Poisson distribution can be used in the analysis of contingency tables while the gamma distribution can be used to model variance components. The effect of the choice of the distribution is to define the relationship between the expected value of Y, E Y=μ, and its variance and so a generalized linear model with one of the above distributions may be used in a wider context when that relationship holds.
(b) A linear model η=∑βjxj, η is known as a linear predictor.
(c) A link function g(·) between the expected value of Y and the linear predictor, g μ=η. The following link functions are available:
For the binomial distribution ε, observing y out of t:
(i) | logistic link: η=log μ t-μ ;
(ii) | probit link: η=Φ-1 μt ;
(iii) | complementary log-log: η=log-log 1-μt .
For the Normal, Poisson, and gamma distributions:
(i) | exponent link: η=μa, for a constant a;
(ii) | identity link: η=μ;
(iii) | log link: η=log⁡μ;
(iv) | square root link: η=μ;
(v) | reciprocal link: η=1 μ .
For each distribution there is a canonical link. For the canonical link there exist sufficient statistics for the parameters. The canonical links are:
(i) | Normal – identity;
(ii) | binomial – logistic;
(iii) | Poisson – logarithmic;
(iv) | gamma – reciprocal.
For the general linear regression model described above the three components are:
(i) | Distribution – Normal;
(ii) | Linear model – ∑βjxj;
(iii) | Link – identity.
The model is fitted by maximum likelihood; this is equivalent to least squares in the case of the Normal distribution. The residual sums of squares used in regression models is generalized to the concept of deviance. The deviance is the logarithm of the ratio of the likelihood of the model to the full model in which μ^i=yi, where μ^i is the estimated value of μi. For the Normal distribution the deviance is the residual sum of squares. Except for the case of the Normal distribution with the identity link, the χ 2 and F-tests based on the deviance are only approximate; also the estimates of the parameters will only be approximately Normally distributed. Thus only approximate z- or t-tests may be performed on the parameter values and approximate confidence intervals computed.
The estimates are found by using an iterative weighted least squares procedure. This is equivalent to the Fisher scoring method in which the Hessian matrix used in the Newton–Raphson method is replaced by its expected value. In the case of canonical links the Fisher scoring method and the Newton–Raphson method are identical. Starting values for the iterative procedure are obtained by replacing the μi by yi in the appropriate equations.

2.6 Linear Mixed Effects Regression

In a standard linear model the independent (or explanatory) variables are assumed to take the same set of values for all units in the population of interest. This type of variable is called fixed. In contrast, an independent variable that fluctuates over the different units is said to be random. Modelling a variable as fixed allows conclusions to be drawn only about the particular set of values observed. Modelling a variable as random allows the results to be generalized to the different levels that may have been observed. In general, if the effects of the levels of a variable are thought of as being drawn from a probability distribution of such effects then the variable is random. If the levels are not a sample of possible levels then the variable is fixed. In practice many qualitative variables can be considered as having fixed effects and most blocking, sampling design, control and repeated measures as having random effects.
In a general linear regression model, defined by
y=Xβ+ε
where | y is a vector of n observations on the dependent variable,
 | X is an n by p design matrix of independent variables,
 | β is a vector of p unknown parameters,
and | ε is a vector of n, independent and identically distributed, unknown errors, with ε ~ N 0 , σ 2 ,
there are p fixed effects (the β) and a single random effect (the error term ε).
An extension to the general linear regression model that allows for additional random effects is the linear mixed effects regression model, (sometimes called the variance components model). One parameterisation of a linear mixed effects model is
y=Xβ+Zν+ε
where | y is a vector of n observations on the dependent variable,
 | X is an n by p design matrix of fixed independent variables,
 | β is a vector of p unknown fixed effects,
 | Z is an n by q design matrix of random independent variables,
 | ν is a vector of length q of unknown random effects,
 | ε is a vector of length n of unknown random errors,
and ν and ε are normally distributed with expectation zero and variance / covariance matrix defined by
Var ν ε = G 0 0 R .
The routines currently available in this chapter are restricted to cases where R= σ R 2 I , I is the n×n identity matrix and G is a diagonal matrix. Given this restriction the random variables, Z, can be subdivided into g≤q groups containing one or more variables. The variables in the ith group are identically distributed with expectation zero and variance σi 2. The model therefore contains three sets of unknowns, the fixed effects, β, the random effects, ν, and a vector of g+1 variance components, γ, with γ = σ1 2,σ2 2,…,,, σ g-1 2 ,σg2,σR2 . Rather than work directly with γ and the full likelihood function, γ is replaced by γ* = σ1 2 / σR2 , σ2 2 / σR2 ,…, σ g-1 2 / σR2 , σg2 / σR2 ,1 and the profiled likelihood function is used instead.
The model parameters are estimated using an iterative method based on maximizing either the restricted (profiled) likelihood function or the (profiled) likelihood functions. Fitting the model via restricted maximum likelihood involves maximizing the function
-2 l R = log V + n-p log rT V-1 r + log XT V-1 X + n-p 1+ log 2 π / n-p + n-p .
Whereas fitting the model via maximum likelihood involves maximizing
-2 l R = log V + n log rT V-1 r + n log 2 π / n +n .
In both cases
V = ZG ZT + R,   r=y-Xb   and   b = XT V-1 X -1 XT V-1 y .
Once the final estimates for γ * have been obtained, the value of σR 2 is given by
σR 2 = rT V-1 r / n - p .
Case weights, Wc , can be incorporated into the model by replacing XT X and ZT Z with XT Wc X and ZT Wc Z respectively, for a diagonal weight matrix Wc .

2.7 Quantile Regression

Quantile regression is related to least squares regression in that both are interested in studying the relationship between a response variable and one or more independent or explanatory variables. However, whereas least squares regression is concerned with modelling the conditional mean of the dependent variable, quantile regression models the conditional τth quantile of the dependent variable, for some value of τ∈0,1. So, for example, τ=0.5 would be the median.
Throughout this section we will be making use of the following definitions:
(a) If Z is a real valued random variable with distribution function F and density function f, such that
F α = P Z ≤ α = ∫ -∞ α f z dz
then the τth quantile, α, can be defined as
α = F-1 τ = inf z: F z ≥ τ , τ ∈ 0,1 .
(b) | I L denotes an indicator function taking the value 1 if the logical expression L is true and 0 otherwise, e.g., I z<0 = 1 if z<0 and 0 if z≥0.
(c) | y denotes a vector of n observations on the dependent (or response) variable, y = y i : i = 1, 2, …, n .
(d) | X denotes an n×p matrix of explanatory or independent variables, often referred to as the design matrix, and xi denotes a column vector of length p which holds the ith row of X.

2.7.1 Finding a sample quantile as an optimization problem

Consider the piecewise linear loss function
ρ τ z = z ⁢ τ - I z < 0
The minimum of the expectation
E ρ τ z - α = τ - 1 ∫ -∞ α z - α f z dz + τ ∫ α ∞ z - α f z dz
can be obtained by using the integral rule of Leibnitz to differentiate with respect to z and then setting the result to zero, giving
1 - τ ∫ -∞ α f z dz - ∫ α ∞ f z dz = F α - τ = 0
hence α = F - 1 τ when the solution is unique. If the solution is not unique then there exists a range of quantiles, each of which is equally valid. Taking the smallest value of such a range ensures that the empirical quantile function is left-continuous. Therefore obtaining the τth quantile of a distribution F can be achieved by minimizing the expected value of the loss function ρτ.
This idea of obtaining the quantile by solving an optimization problem can be extended to finding the τth sample quantile. Given a vector of n observed values, y, from some distribution the empirical distribution function, F n α = n-1 ∑ i=1 n I y i ≤ α provides an estimate of the unknown distribution function F giving an expected loss of
E ρ τ y - α = n - 1 ∑ i=1 n ρ τ y i - α
and therefore the problem of finding the τth sample quantile, α^ τ , can be expressed as finding the solution to the problem
minimize α ∈ ℝ ∑ i=1 n ρ τ y i - α
effectively replacing the operation of sorting, usually required when obtaining a sample quantile, with an optimization.

2.7.2 From least squares to quantile regression

Given the vector y it is a well known result that the sample mean, y^, solves the least squares problem
minimize μ ∈ ℝ ∑ i=1 n y i - μ 2 .
This result leads to least squares regression where, given design matrix X and defining the conditional mean of y as μ X = X β , an estimate of β is obtained from the solution to
minimize β ∈ ℝ p ∑ i=1 n y i - xiT β 2 .
Quantile regression can be derived in a similar manner by specifying the τth conditional quantile as Q y τ | X = X β τ and estimating β τ as the solution to
minimize β ∈ ℝ p ∑ i=1 n ρ τ y i - xiT β . (10)

2.7.3 Quantile regression as a linear programming problem

By introducing 2 n slack variables, u = u i : i = 1, 2, …, n and v = u i : i = 1, 2, …, n , the quantile regression minimization problem, (10), can be expressed as a linear programming (LP) problem, with primal and associated dual formulations
(a) Primal form
minimize u, v, β ∈ ℝ + n × ℝ + n × ℝ p τ eT u + 1 - τ eT v ​   subject to   y = Xβ + u - v (11)
where e is a vector of length n, where each element is 1.
If ri denotes the ith residual, r i = y i - xiT β , then the slack variables, u,v, can be thought as corresponding to the absolute value of the positive and negative residuals respectively with
u i = r i ​ if ​ r i > 0 0 ​ otherwise v i = - r i ​ if ​ r i < 0 0 ​ otherwise
(b) Dual form
The dual formulation of (11) is given by
maximize d yT d ​   subject to   XT d=0, d ∈ τ-1,τ n
which, on setting a=d+1-τ e, is equivalent to
maximize a yT a ​   subject to   XT a = 1 - τ XT e , a ∈ 0,1 n (12)
(c) Canonical form
Linear programming problems are often described in a standard way, called the canonical form. The canonical form of an LP problem is
minimize z cT z ​   subject to   ll ≤ z Az ≤ lu .
Letting 0 p denote a vector of p zeros ±∞p denote a vector of p arbitarily small or large values, I n×n denote the n×n identity matrix, c=a,b denote the row vector constructed by concatenating the elements of vector b to the elements of vector a and C=A,B denote the matrix constructed by concatenating the columns of matrix B onto the columns of matrix A then setting
cT = 0 p , τ ⁢ eT , 1 - τ eT zT = βT,uT,vT A = X, I n×n , - I n×n b=y lu = +∞p,∞n,∞n,y ll = -∞p,0 n,0 n,y
gives the quantile regression LP problem as described in (11).
Once expressed as an LP problem the parameter estimates β^τ can be obtained in a number of ways, for example via the inertia-controlling method of Gill and Murray (1978) (see E04MFF/E04MFA), the simplex method or an interior point method as used by G02QFF and G02QGF.

2.7.4 Estimation of the covariance matrix

Koenker (2005) shows that the limiting covariance matrix of n β^ τ - β τ is of the form of a Huber Sandwich. Therefore, under the assumption of Normally distributed errors
n β^ τ - β τ ∼ N 0, τ 1 - τ H n τ -1 J n H n τ -1 (13)
where
Jn = n-1 ⁢ ∑ i=1 n x i xiT H n τ = lim n → ∞ n-1 ⁢ ∑ i=1 n x i xiT f i Q y i τ | x i
and f i Q y i τ | x i denotes the conditional density of the response y evaluated at the τth conditional quantile.
More generally, the asymptotic covariance matrix for β^ τ 1 , β^ τ 1 ,…, β^ τ n has blocks defined by
cov n β^ τ i - β τ i , n β^ τ j - β τ j = min τi,τj - τi τj H n τi -1 Jn H n τj -1 (14)
Under the assumption of independent, identically distributed (iid) errors, (13) simplifies to
n β^τ - β τ ∼ N 0, τ 1-τ s τ 2 XT X -1
where s τ is the sparsity function, given by
s τ = 1 f F-1 τ
a similar simplification occurs with (14).
In cases where the assumption of iid errors does not hold, Powell (1991) suggests using a kernel estimator of the form
H ^ n τ = n cn -1 ∑ i=1 n K yi - xiT β^ τ cn xi xiT
for some bandwidth parameter cn satisfying lim n→∞ c n → 0 and lim n→∞ n c n → ∞ and Hendricks and Koenker (1991) suggest a method based on an extension of the idea of sparsity.
Rather than use an asymptotic estimate of the covariance matrix, it is also possible to use bootstrapping. Roughly speaking the original data is resampled and a set of parameter estimates obtained from each new sample. A sample covariance matrix is then constructed from the resulting matrix of parameter estimates.

2.8 Latent Variable Methods

Regression by means of projections to latent structures also known as partial least squares, is a latent variable linear model suited to data for which:
  • the number of x-variables is high compared to the number of observations;
  • x-variables and/or y-variables are multicollinear.
Latent variables are linear combinations of x-variables that explain variance in x and y-variables. These latent variables, known as factors, are extracted iteratively from the data. A choice of the number of factors to include in a model can be made by considering diagnostic statistics such as the variable influence on projections (VIP).

2.9 LARS, LASSO and Forward Stagewise Regression

Least Angle Regression (LARS), Least Absolute Shrinkage Selection Operator (LASSO) and forward stagewise regression are three closely related regression techniques. Of the three, only LASSO has an easily accessible mathematical description suitable for being summarised here. A full description of the all three methods and the relationship between them can be found in Efron et al. (2004) and the references there in.
Given a vector of n observed values, y = yi : i=1,2,…,n and an n×p design matrix X, where the jth column of X, denoted xj, is a vector of length n representing the jth independent variable xj, standardized such that ∑ i=1 n x ij =0 , and ∑ i=1 n x ij 2 =1 and a set of model parameters β to be estimated from the observed values, the LASSO model of Tibshirani (1996) is given by
minimize α , β∈ ℝp y- α- XT β 2   subject to   β 1 ≤t (15)
for a given value of t, where α=y-=n-1⁢∑ i=1 n yi. The positive LASSO model is the same as the standard LASSO model, given above, with the added constraint that
βj ≥ 0 ,   j=1,2,…,p .
Rather than solve (15) for a given value of t, Efron et al. (2004) defined an algorithm that returns a full solution path for all possible values of t. It turns out that this path is piecewise linear with a finite number of pieces, denoted K, corresponding to K sets of parameter estimates.

3 Recommendations on Choice and Use of Available Routines

3.1 Correlation

3.1.1 Product-moment correlation

Let SSx be the sum of squares of deviations from the mean, x-, for the variable x for a sample of size n, i.e.,
SSx=∑i=1 n xi-x- 2
and let SC xy be the cross-products of deviations from the means, x- and y-, for the variables x and y for a sample of size n, i.e.,
SC xy=∑i=1 n xi-x-yi-y-.
Then the sample covariance of x and y is
cov x,y=SC xy n-1
and the product-moment correlation coefficient is
r=cov x,y var x var y =SC xy SSxSSy .
G02BAF computes the product-moment correlation coefficients.
G02BTF updates the sample sums of squares and cross-products and deviations from the means by the addition/deletion of a (weighted) observation.
G02BUF computes the sample sums of squares and cross-products deviations from the means (optionally weighted). The output from multiple calls to G02BUF can be combined via a call to G02BZF, allowing large datasets to be summarised across multiple processing units.
G02BTF updates the sample sums of squares and cross-products and deviations from the means by the addition/deletion of a (weighted) observation.
G02BWF computes the product-moment correlation coefficients from the sample sums of squares and cross-products of deviations from the means.
The three routines compute only the upper triangle of the correlation matrix which is stored in a one-dimensional array in packed form.
G02BXF computes both the (optionally weighted) covariance matrix and the (optionally weighted) correlation matrix. These are returned in two-dimensional arrays. (Note that G02BTF and G02BUF can be used to compute the sums of squares from zero.)
G02BGF can be used to calculate the correlation coefficients for a subset of variables in the data matrix.

3.1.2 Product-moment correlation with missing values

If there are missing values then G02BUF and G02BXF, as described above, will allow casewise deletion by you giving the observation zero weight (compared with unit weight for an otherwise unweighted computation).
Other routines also handle missing values in the calculation of unweighted product-moment correlation coefficients. Casewise exclusion of missing values is provided by G02BBF while pairwise omission of missing values is carried out by G02BCF. These two routines calculate a correlation matrix for all the variables in the data matrix; similar output but for only a selected subset of variables is provided by routines G02BHF and G02BJF respectively. As well as providing the Pearson product-moment correlation coefficients, these routines also calculate the means and standard deviations of the variables, and the matrix of sums of squares and cross-products of deviations from the means. For all four routines you are free to select appropriate values for consideration as missing values, bearing in mind the nature of the data and the possible range of valid values. The missing values for each variable may be either different or alike and it is not necessary to specify missing values for all the variables.

3.1.3 Nonparametric correlation

There are five routines which perform nonparametric correlations, each of which is capable of producing both Spearman's rank order and Kendall's tau correlation coefficients. The basic underlying concept of both these methods is to replace each observation by its corresponding rank or order within the observations on that variable, and the correlations are then calculated using these ranks.
It is obviously more convenient to order the observations and calculate the ranks for a particular variable just once, and to store these ranks for subsequent use in calculating all coefficients involving that variable; this does however require an amount of store of the same size as the original data matrix, which in some cases might be excessive. Accordingly, some routines calculate the ranks only once, and replace the input data matrix by the matrix of ranks, which are then also made available to you on exit from the routine, while others preserve the data matrix and calculate the ranks a number of times within the routine; the ranks of the observations are not provided as output by routines which work in the latter way. If it is possible to arrange the program in such a way that the first technique can be used, then efficiency of timing is achieved with no additional storage, whereas in the second case, it is necessary to have a second matrix of the same size as the data matrix, which may not be acceptable in certain circumstances; in this case it is necessary to reach a compromise between efficiency of time and of storage, and this may well be dependent upon local conditions.
Routines G02BNF and G02BQF both calculate Kendall's tau and/or Spearman's rank order correlation coefficients taking no account of missing values; G02BNF does so by calculating the ranks of each variable only once, and replacing the data matrix by the matrix of ranks, whereas G02BQF calculates the ranks of each variable several times. Routines G02BPF and G02BRF provide the same output, but treat missing values in a ‘casewise’ manner (see above); G02BPF calculates the ranks of each variable only once, and overwrites the data matrix of ranks, while G02BRF determines the ranks of each variable several times. For ‘pairwise’ omission of missing data (see above), the routine G02BSF provides Kendall and/or Spearman coefficients.
Since G02BNF and G02BPF order the observations and calculate the ranks of each variable only once, then if there are M variables involved, there are only M separate ‘ranking’ operations; this should be contrasted with the method used by routines G02BQF and G02BRF which perform M M-1/2+1 similar ranking operations. These ranking operations are by far the most time-consuming parts of these nonparametric routines, so for a matrix of as few as five variables, the time taken by one of the slower routines can be expected to be at least a factor of two slower than the corresponding efficient routine; as the number of variables increases, so this relative efficiency factor increases. Only one routine, G02BSF, is provided for pairwise missing values, and this routine carries out M M-1 separate rankings; since by the very nature of the pairwise method it is necessary to treat each pair of variables separately and rank them individually, it is impossible to reduce this number of operations, and so no alternative routine is provided.

3.1.4 Partial correlation

G02BYF computes a matrix of partial correlation coefficients from the correlation coefficients or variance-covariance matrix returned by G02BXF.

3.1.5 Robust correlation

G02HLF and G02HMF compute robust estimates of the variance-covariance matrix by solving the equations
1 n∑i=1 n w zi 2 zi=0
and
1 n ∑i= 1 n u zi 2 zi ziT -v zi 2 I=0,
as described in Section 2.1.4 for user-supplied functions w and u. Two options are available for v, either v t=1 for all t or v t=u t.
G02HMF requires only the function w and u to be supplied while G02HLF also requires their derivatives.
In general G02HLF will be considerably faster than G02HMF and should be used if derivatives are available.
G02HKF computes a robust variance-covariance matrix for the following functions:
u t =au/t 2​ if ​t<au 2 u t =1​ if ​au 2≤t≤bu 2 u t =bu/t 2​ if ​t>bu 2
and
w t = 1​ if ​t≤cw w t =cw/t​ if ​t>cw
for constants au, bu and cw.
These functions solve a minimax space problem considered by Huber (1981). The values of au, bu and cw are calculated from the fraction of gross errors; see Hampel et al. (1986) and Huber (1981).
To compute a correlation matrix from the variance-covariance matrix G02BWF may be used.

3.1.6 Nearest correlation matrix

A number of routines are provided to calculate a nearest correlation matrix. The choice of routine will depend on what definition of ‘nearest’ is required and whether there is any particular structure desired in the resulting correlation matrix.
G02AAF computes the nearest correlation matrix in the Frobenius norm, using the method of Qi and Sun (2006), modified by Borsdorf and Higham (2010). An extension to this routine is G02ABF which allows a row and column weighted Frobenius norm to be used as well as a bound on the minimum eigenvalue of the resulting correlation matrix to be specified.
If elementwise weighting is required G02AJF can be used which again computes the nearest correlation matrix in the Frobenius norm and provides a bound on the eigenvalues. It should be noted, that this routine is computationally expensive. If it is desired to fix elements in the input matrix then you should consider a shrinking algorithm.
G02ANF uses the shrinking method of Higham et al. (2014) to fix the leading block of the input. However, it does not compute the nearest correlation matrix in the Frobenius norm but finds the smallest relative perturbation to the unfixed elements to give a positive definite output. This functionality is extended in G02APF which allows an arbitrary target matrix to be specified via elementwise weights.
G02AEF computes the factor loading matrix, allowing a correlation matrix with a k-factor structure to be computed.
See also the Pennon optimization suite in Chapter E04 which can be used to solve a variety of nearest correlation matrix problems. See for example Section 10 in E04RFF.

3.2 Regression

3.2.1 Simple linear regression

Four routines are provided for simple linear regressions: G02CAF and G02CCF perform the simple linear regression with a constant term (equation (1) above), while G02CBF and G02CDF fit the simple linear regression with no constant term (equation (2) above). Two of these routines, G02CCF and G02CDF, take account of missing values, which the others do not. In these two routines, an observation is omitted if it contains a missing value for either the dependent or the independent variable; this is equivalent to both the casewise and pairwise methods, since both are identical when there are only two variables involved. Input to these routines consists of the raw data, and output includes the coefficients, their standard errors and t values for testing the significance of the coefficients; the F value for testing the overall significance of the regression is also given.

3.2.2 Ridge regression

G02KAF calculates a ridge regression, optimizing the ridge parameter according to one of four prediction error criteria.
G02KBF calculates ridge regressions for a given set of ridge parameters.

3.2.3 Polynomial regression and nonlinear regression

No routines are currently provided in this chapter for polynomial regression. If you wish to perform polynomial regressions you have three alternatives: you can use the multiple linear regression routines, G02DAF, with a set of independent variables which are in fact simply the same single variable raised to different powers, or you can use the routine G04EAF to compute orthogonal polynomials which can then be used with G02DAF, or you can use the routines in Chapter E02 (Curve and Surface Fitting) which fit polynomials to sets of data points using the techniques of orthogonal polynomials. This latter course is to be preferred, since it is more efficient and liable to be more accurate, but in some cases more statistical information may be required than is provided by those routines, and it may be necessary to use the routines of this chapter.
More general nonlinear regression models may be fitted using the optimization routines in Chapter E04, which contains routines to minimize the function
∑i=1 n ei 2
where the regression parameters are the variables of the minimization problem.

3.2.4 Multiple linear regression – general linear model

G02DAF fits a general linear regression model using the QR method and an SVD if the model is not of full rank. The results returned include: residual sum of squares, parameter estimates, their standard errors and variance-covariance matrix, residuals and leverages. There are also several routines to modify the model fitted by G02DAF and to aid in the interpretation of the model.
G02DCF adds or deletes an observation from the model.
G02DDF computes the parameter estimates, and their standard errors and variance-covariance matrix for a model that is modified by G02DCF, G02DEF or G02DFF.
G02DEF adds a new variable to a model.
G02DFF drops a variable from a model.
G02DGF fits the regression to a new dependent variable, i.e., keeping the same independent variables.
G02DKF calculates the estimates of the parameters for a given set of constraints, (e.g., parameters for the levels of a factor sum to zero) for a model which is not of full rank and the SVD has been used.
G02DNF calculates the estimate of an estimable function and its standard error.
Note: G02DEF also allows you to initialize a model building process and then to build up the model by adding variables one at a time.
If you wish to use methods based on forming the cross-products/correlation matrix (i.e., (XT X) matrix) rather than the recommended use of G02DAF then the following routines should be used.
For regression through the origin (i.e., no constant) G02CHF preceded by:
  • G02BDF (no missing values, all variables)
  • G02BKF (no missing values, subset of variables)
  • G02BEF (casewise missing values, all variables)
  • G02BLF(casewise missing values, subset of variables)
  • G02BFF* (pairwise missing values, all variables)
  • G02BMF* (pairwise missing values, subset of variables)
For regression with intercept (i.e., with constant) G02CGF preceded by:
  • G02BAF (no missing values, all variables)
  • G02BGF (no missing values, subset of variables)
  • G02BBF (casewise missing values, all variables)
  • G02BHF (casewise missing values, subset of variables)
  • G02BCF* (pairwise missing values, all variables)
  • G02BJF* (pairwise missing values, subset of variables)
Note that the four routines using pairwise deletion of missing value (marked with *) should be used with great caution as the use of this method can lead to misleading results, particularly if a significant proportion of values are missing.
Both G02CGF and G02CHF require that the correlations/sums of squares involving the dependent variable must appear as the last row/column. Because the layout of the variables in your data array may not be arranged in this way, two routines, G02CEF and G02CFF, are provided for rearranging the rows and columns of vectors and matrices. G02CFF simply reorders the rows and columns while G02CEF forms smaller vectors and matrices from larger ones.
Output from G02CGF and G02CHF consists of the coefficients, their standard errors, R 2-values, t and F statistics.

3.2.5 Selecting regression models

To aid the selection of a regression model the following routines are available.
G02EAF computes the residual sums of squares for all possible regressions for a given set of dependent variables. The routine allows some variables to be forced into all regressions.
G02ECF computes the values of R 2 and Cp from the residual sums of squares as provided by G02EAF.
G02EEF enables you to fit a model by forward selection. You may call G02EEF a number of times. At each call the routine will calculate the changes in the residual sum of squares from adding each of the variables not already included in the model, select the variable which gives the largest change and then if the change in residual sum of squares meets the given criterion will add it to the model.
G02EFF uses a full stepwise selection to choose a subset of the explanatory variables. The method repeatedly applies a forward selection step followed by a backward elimination step until neither step updates the current model.

3.2.6 Residuals

G02FAF computes the following standardized residuals and measures of influence for the residuals and leverages produced by G02DAF:
(i) | Internally studentized residual;
(ii) | Externally studentized residual;
(iii) | Cook's D statistic;
(iv) | Atkinson's T statistic.
G02FCF computes the Durbin–Watson test statistic and bounds for its significance to test for serial correlation in the errors, ei.

3.2.7 Robust regression

For robust regression using M-estimates instead of least squares the routine G02HAF will generally be suitable. G02HAF provides a choice of four ψ-functions (Huber's, Hampel's, Andrew's and Tukey's) plus two different weighting methods and the option not to use weights. If other weights or different ψ-functions are needed the routine G02HDF may be used. G02HDF requires you to supply weights, if required, and also routines to calculate the ψ-function and, optionally, the χ-function. G02HBF can be used in calculating suitable weights. The routine G02HFF can be used after a call to G02HDF in order to calculate the variance-covariance estimate of the estimated regression coefficients.
For robust regression, using least absolute deviation, E02GAF can be used.

3.2.8 Generalized linear models

There are four routines for fitting generalized linear models. The output includes: the deviance, parameter estimates and their standard errors, fitted values, residuals and leverages.
G02GAF Normal distribution.
G02GBF binomial distribution.
G02GCF Poisson distribution.
G02GDF gamma distribution.
While G02GAF can be used to fit linear regression models (i.e., by using an identity link) this is not recommended as G02DAF will fit these models more efficiently. G02GCF can be used to fit log-linear models to contingency tables.
In addition to the routines to fit the models there is one routine to predict from the fitted model and two routines to aid interpretation when the fitted model is not of full rank, i.e., aliasing is present.
G02GPF computes a predicted value and its associated standard error based on a previously fitted generalized linear model.
G02GKF computes parameter estimates for a set of constraints, (e.g., sum of effects for a factor is zero), from the SVD solution provided by the fitting routine.
G02GNF calculates an estimate of an estimable function along with its standard error.

3.2.9 Linear mixed effects regression

There are four routines for fitting linear mixed effects regression.
G02JAF and G02JDF uses restricted maximum likelihood (REML) to fit the model.
G02JBF and G02JEF uses maximum likelihood to fit the model.
For all routines the output includes: either the maximum likelihood or restricted maximum likelihood and the fixed and random parameter estimates, along with their standard errors. Whilst it is possible to fit a hierachical model using G02JAF or G02JBF, G02JDF and G02JEF allow the model to be specified in a more intuitive way. G02JCF must be called prior to calling G02JDF or G02JEF.
As the estimates of the variance components are found using an iterative procedure initial values must be supplied for each σ. In all four routines you can either specify these initial values, or allow the routine to calculate them from the data using minimum variance quadratic unbiased estimation (MIVQUE0). Setting the maximum number of iterations to zero in any of the routines will return the corresponding likelihood, parameter estimates and standard errors based on these initial values.

3.2.10 Linear quantile regression

Two routines are provided for performing linear quantile regression, G02QFF and G02QGF. Of these, G02QFF provides a simplified interface to G02QGF, where many of the input parameters have been given default values and the amount of output available has been reduced.
Prior to calling G02QGF the optional parameter array must be initialized by calling G02ZKF with OPTSTR set to Initialize. Once these arrays have been initialized G02ZLF can be called to query the value of an optional parameter.

3.2.11 Partial Least Squares (PLS)

G02LAF calculates a nonlinear, iterative PLS by using singular value decomposition.
G02LBF calculates a nonlinear, iterative PLS by using Wold's method.
G02LCF calculates parameter estimates for a given number of PLS factors.
G02LDF calculates predictions given a PLS model.

3.2.12 LARS, LASSO and Forward Stagewise Regression

Two routines for fitting a LARS, LASSO or forward stagewise regression are supplied: G02MAF and G02MBF. The difference between the two routines is in the way that the data, X and y, are supplied. The first routine, G02MAF takes X and y directly, whereas G02MBF takes the data in the form of the cross-products: XT X, XT y and yT y. In most situations G02MAF will be the recommended routine as the full data tends to be available. However when there is a large number of observations (i.e., n is large) it might be preferable to split the data into smaller blocks and process one block at a time. In such situations G02BUF and G02BZF can be used to construct the required cross-products and G02MBF called to fit the required model.
Both G02MAF and G02MBF return K sets of parameter estimates, which, because of it's piecewise linear nature, define the full LARS, LASSO or forward stagewise regression solution path. However, parameter estimates are sometimes required at points along the solution path that differ from those returned by G02MAF and G02MBF, for example when performing a cross-validation. G02MCF will return the parameter estimates in such cases.

4 Functionality Index

Computes a correlation matrix from an approximate one using a specified target matrix G02APF
Computes a correlation matrix with fixed submatrix G02ANF
Computes the nearest correlation matrix using element-wise weights G02AJF
Computes the nearest correlation matrix using the k-factor model G02AEF
Computes the nearest correlation matrix using the method of Qi and Sun,
augmented G02AAF to incorporate weights and bounds G02ABF
unweighted G02AAF
Correlation-like coefficients,
all variables,
casewise treatment of missing values G02BEF
no missing values G02BDF
pairwise treatment of missing values G02BFF
subset of variables,
casewise treatment of missing values G02BLF
no missing values G02BKF
pairwise treatment of missing values G02BMF
Generalized linear models,
binomial errors G02GBF
computes estimable function G02GNF
gamma errors G02GDF
Normal errors G02GAF
Poisson errors G02GCF
prediction G02GPF
transform model parameters G02GKF
Hierarchical mixed effects regression,
initiation G02JCF
using maximum likelihood G02JEF
using restricted maximum likelihood G02JDF
Least angle regression (includes LASSO),
Additional parameter calculation G02MCF
Model fitting,
Cross-product matrix G02MBF
Raw data G02MAF
Linear mixed effects regression,
via maximum likelihood (ML) G02JBF
via restricted maximum likelihood (REML) G02JAF
Multiple linear regression,
from correlation coefficients G02CGF
from correlation-like coefficients G02CHF
Multiple linear regression/General linear model,
add/delete observation from model G02DCF
add independent variable to model G02DEF
computes estimable function G02DNF
delete independent variable from model G02DFF
general linear regression model G02DAF
regression for new dependent variable G02DGF
regression parameters from updated model G02DDF
transform model parameters G02DKF
Non-parametric rank correlation (Kendall and/or Spearman):
missing values,
casewise treatment of missing values,
overwriting input data G02BPF
preserving input data G02BRF
pairwise treatment of missing values G02BSF
no missing values,
overwriting input data G02BNF
preserving input data G02BQF
Partial least squares,
calculates predictions given an estimated PLS model G02LDF
fits a PLS model for a given number of factors G02LCF
orthogonal scores using SVD G02LAF
orthogonal scores using Wold's method G02LBF
Product-moment correlation,
correlation coefficients, all variables,
casewise treatment of missing values G02BBF
no missing values G02BAF
pairwise treatment of missing values G02BCF
correlation coefficients, subset of variables,
casewise treatment of missing values G02BHF
no missing values G02BGF
pairwise treatment of missing values G02BJF
correlation matrix,
compute correlation and covariance matrices G02BXF
compute from sum of squares matrix G02BWF
compute partial correlation and covariance matrices G02BYF
sum of squares matrix,
combine G02BZF
compute G02BUF
update G02BTF
Quantile regression,
linear,
comprehensive G02QGF
simple G02QFF
Residuals,
Durbin–Watson test G02FCF
standardized residuals and influence statistics G02FAF
Ridge regression,
ridge parameter(s) supplied G02KBF
ridge parameter optimized G02KAF
Robust correlation,
Huber's method G02HKF
user-supplied weight function only G02HMF
user-supplied weight function plus derivatives G02HLF
Robust regression,
compute weights for use with G02HDF G02HBF
standard M-estimates G02HAF
user-supplied weight functions G02HDF
variance-covariance matrix following G02HDF G02HFF
Selecting regression model,
all possible regressions G02EAF
forward selection G02EEF
R2 and Cp statistics G02ECF
Service routines,
for multiple linear regression,
reorder elements from vectors and matrices G02CFF
select elements from vectors and matrices G02CEF
general option getting routine G02ZLF
general option setting routine G02ZKF
Simple linear regression,
no intercept G02CBF
no intercept with missing values G02CDF
with intercept G02CAF
with intercept and with missing values G02CCF
Stepwise linear regression,
Clarke's sweep algorithm G02EFF

5 Auxiliary Routines Associated with Library Routine Arguments

G02EFH | nagf_correg_linregm_fit_stepwise_sample_monfun See the description of the argument MONFUN in G02EFF.
G02HDZ | nagf_correg_robustm_user_dummy_chi See the description of the argument CHI in G02HDF.

6 Routines Withdrawn or Scheduled for Withdrawal

None.

7 References

Atkinson A C (1986) Plots, Transformations and Regressions Clarendon Press, Oxford
Borsdorf R and Higham N J (2010) A preconditioned (Newton) algorithm for the nearest correlation matrix IMA Journal of Numerical Analysis 30(1) 94–107
Churchman C W and Ratoosh P (1959) Measurement Definitions and Theory Wiley
Cook R D and Weisberg S (1982) Residuals and Influence in Regression Chapman and Hall
Draper N R and Smith H (1985) Applied Regression Analysis (2nd Edition) Wiley
Efron B, Hastie T, Johnstone I and Tibshirani R (2004) Least Angle Regression The Annals of Statistics (Volume 32) 2 407–499
Gill P E and Murray W (1978) Numerically stable methods for quadratic programming Math. Programming 14 349–372
Hammarling S (1985) The singular value decomposition in multivariate statistics SIGNUM Newsl. 20(3) 2–25
Hampel F R, Ronchetti E M, Rousseeuw P J and Stahel W A (1986) Robust Statistics. The Approach Based on Influence Functions Wiley
Hays W L (1970) Statistics Holt, Rinehart and Winston
Hendricks W and Koenker R (1991) Hierarchical spline models for conditional quantiles and the demand for electricity Journal of the Maerican Statistical Association 87 58–68
Higham N J, Strabić N and Šego V (2014) Restoring definiteness via shrinking, with an application to correlation matrices with a fixed block MIMS EPrint 2014.54 Manchester Institute for Mathematical Sciences, The University of Manchester, UK
Huber P J (1981) Robust Statistics Wiley
Kendall M G and Stuart A (1973) The Advanced Theory of Statistics (Volume 2) (3rd Edition) Griffin
Koenker R (2005) Quantile Regression Econometric Society Monographs, Cambridge University Press, New York
McCullagh P and Nelder J A (1983) Generalized Linear Models Chapman and Hall
Powell J L (1991) Estimation of monotonic regression models under quantile restrictions Nonparametric and Semiparametric Methods in Econometrics Cambridge University Press, Cambridge
Qi H and Sun D (2006) A quadratically convergent Newton method for computing the nearest correlation matrix SIAM J. Matrix AnalAppl 29(2) 360–385
Searle S R (1971) Linear Models Wiley
Siegel S (1956) Non-parametric Statistics for the Behavioral Sciences McGraw–Hill
Tibshirani R (1996) Regression Shrinkage and Selection via the Lasso Journal of the Royal Statistics Society, Series B (Methodological) (Volume 58) 1 267–288
Weisberg S (1985) Applied Linear Regression Wiley
G02 Chapter Contents
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


G02JAF : NAG Library, Mark 26

G02 Chapter Contents
G02 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

G02JAF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

G02JAF fits a linear mixed effects regression model using restricted maximum likelihood (REML).

2 Specification

SUBROUTINE G02JAF ( N, NCOL, LDDAT, DAT, LEVELS, YVID, CWID, NFV, FVID, FINT, NRV, RVID, NVPR, VPR, RINT, SVID, GAMMA, NFF, NRF, DF, REML, LB, B, SE, MAXIT, TOL, WARN, IFAIL)
INTEGER | N, NCOL, LDDAT, LEVELS(NCOL), YVID, CWID, NFV, FVID(NFV), FINT, NRV, RVID(NRV), NVPR, VPR(NRV), RINT, SVID, NFF, NRF, DF, LB, MAXIT, WARN, IFAIL
REAL (KIND=nag_wp) | DAT(LDDAT,NCOL), GAMMA(NVPR+2), REML, B(LB), SE(LB), TOL

3 Description

G02JAF fits a model of the form:
y=Xβ+Zν+ε
where
  • y is a vector of n observations on the dependent variable,
  • X is a known n by p design matrix for the fixed independent variables,
  • β is a vector of length p of unknown fixed effects,
  • Z is a known n by q design matrix for the random independent variables,
  • ν is a vector of length q of unknown random effects,
and
  • ε is a vector of length n of unknown random errors.
Both ν and ε are assumed to have a Gaussian distribution with expectation zero and
Var ν ε = G 0 0 R
where R= σ R 2 I , I is the n×n identity matrix and G is a diagonal matrix. It is assumed that the random variables, Z , can be subdivided into g ≤ q groups with each group being identically distributed with expectations zero and variance σi 2 . The diagonal elements of matrix G therefore take one of the values σi 2 : i=1,2,…,g , depending on which group the associated random variable belongs to.
The model therefore contains three sets of unknowns, the fixed effects, β , the random effects ν and a vector of g+1 variance components, γ , where γ = σ1 2,σ2 2,…, σ g-1 2 ,σg2,σR2 . Rather than working directly with γ , G02JAF uses an iterative process to estimate γ* = σ1 2 / σR2 , σ2 2 / σR2 ,…, σ g-1 2 / σR2 , σg2 / σR2 ,1 . Due to the iterative nature of the estimation a set of initial values, γ 0 , for γ* is required. G02JAF allows these initial values either to be supplied by you or calculated from the data using the minimum variance quadratic unbiased estimators (MIVQUE0) suggested by Rao (1972).
G02JAF fits the model using a quasi-Newton algorithm to maximize the restricted log-likelihood function:
-2 l R = log V + n-p log r ′ V-1 r + log X ′ V-1 X + n-p 1+ log 2 π / n-p
where
V = ZG Z′ + R,   r=y-Xb   and   b = X ′ V-1 X -1 X ′ V-1 y .
Once the final estimates for γ * have been obtained, the value of σR 2 is given by:
σR 2 = r′ V-1 r / n - p .
Case weights, Wc , can be incorporated into the model by replacing X′X and Z′Z with X′Wc X and Z′Wc Z respectively, for a diagonal weight matrix Wc .
The log-likelihood, lR, is calculated using the sweep algorithm detailed in Wolfinger et al. (1994).

4 References

Goodnight J H (1979) A tutorial on the SWEEP operator The American Statistician 33(3) 149–158
Harville D A (1977) Maximum likelihood approaches to variance component estimation and to related problems JASA 72 320–340
Rao C R (1972) Estimation of variance and covariance components in a linear model J. Am. Stat. Assoc. 67 112–115
Stroup W W (1989) Predictable functions and prediction space in the mixed model procedure Applications of Mixed Models in Agriculture and Related Disciplines Southern Cooperative Series Bulletin No. 343 39–48
Wolfinger R, Tobias R and Sall J (1994) Computing Gaussian likelihoods and their derivatives for general linear mixed models SIAM Sci. Statist. Comput. 15 1294–1310

5 Arguments

1:   N – INTEGERInput
On entry: n, the number of observations.
Constraint: N≥1.
2:   NCOL – INTEGERInput
On entry: the number of columns in the data matrix, DAT.
Constraint: NCOL≥1.
3:   LDDAT – INTEGERInput
On entry: the first dimension of the array DAT as declared in the (sub)program from which G02JAF is called.
Constraint: LDDAT≥N.
4:   DAT LDDATNCOL – REAL (KIND=nag_wp) arrayInput
On entry: array containing all of the data. For the ith observation:
  • DAT iYVID holds the dependent variable, y;
  • if CWID≠0, DAT iCWID holds the case weights;
  • if SVID≠0, DAT iSVID holds the subject variable.
The remaining columns hold the values of the independent variables.
Constraints:
  • if CWID≠0, DAT iCWID≥0.0;
  • if LEVELS j≠1, 1≤DAT ij≤LEVELS j.
5:   LEVELS NCOL – INTEGER arrayInput
On entry: LEVELS i contains the number of levels associated with the ith variable of the data matrix DAT. If this variable is continuous or binary (i.e., only takes the values zero or one) then LEVELS i should be 1; if the variable is discrete then LEVELS i is the number of levels associated with it and DAT ji is assumed to take the values 1 to LEVELS i, for j=1,2,…,N.
Constraint: LEVELS i≥1, for i=1,2,…,NCOL.
6:   YVID – INTEGERInput
On entry: the column of DAT holding the dependent, y, variable.
Constraint: 1≤YVID≤NCOL.
7:   CWID – INTEGERInput
On entry: the column of DAT holding the case weights.
If CWID=0, no weights are used.
Constraint: 0≤CWID≤NCOL.
8:   NFV – INTEGERInput
On entry: the number of independent variables in the model which are to be treated as being fixed.
Constraint: 0≤NFV<NCOL.
9:   FVID NFV – INTEGER arrayInput
On entry: the columns of the data matrix DAT holding the fixed independent variables with FVID i holding the column number corresponding to the i th fixed variable.
Constraint: 1≤FVID i≤NCOL, for i=1,2,…,NFV.
10:   FINT – INTEGERInput
On entry: flag indicating whether a fixed intercept is included (FINT=1).
Constraint: FINT=0 or 1.
11:   NRV – INTEGERInput
On entry: the number of independent variables in the model which are to be treated as being random.
Constraints:
  • 0≤NRV<NCOL;
  • NRV+RINT>0.
12:   RVID NRV – INTEGER arrayInput
On entry: the columns of the data matrix DAT holding the random independent variables with RVID i holding the column number corresponding to the i th random variable.
Constraint: 1≤RVID i≤NCOL, for i=1,2,…,NRV.
13:   NVPR – INTEGERInput
On entry: if RINT=1 and SVID≠0, NVPR is the number of variance components being estimated-2, (g-1), else NVPR=g.
If NRV=0, NVPR is not referenced.
Constraint: if NRV≠0, 1≤NVPR≤NRV.
14:   VPR NRV – INTEGER arrayInput
On entry: VPR i holds a flag indicating the variance of the i th random variable. The variance of the i th random variable is σ j 2 , where j = VPR i + 1 if RINT=1 and SVID≠0 and j = VPR i otherwise. Random variables with the same value of j are assumed to be taken from the same distribution.
Constraint: 1≤VPR i≤NVPR, for i=1,2,…,NRV.
15:   RINT – INTEGERInput
On entry: flag indicating whether a random intercept is included (RINT=1).
If SVID=0, RINT is not referenced.
Constraint: RINT=0 or 1.
16:   SVID – INTEGERInput
On entry: the column of DAT holding the subject variable.
If SVID=0, no subject variable is used.
Specifying a subject variable is equivalent to specifying the interaction between that variable and all of the random-effects. Letting the notation Z 1 × ZS denote the interaction between variables Z 1 and ZS , fitting a model with RINT = 0 , random-effects Z 1 + Z 2 and subject variable ZS is equivalent to fitting a model with random-effects Z 1 × ZS + Z 2 × ZS and no subject variable. If RINT = 1 the model is equivalent to fitting ZS + Z 1 × ZS + Z 2 × ZS and no subject variable.
Constraint: 0≤SVID≤NCOL.
17:   GAMMA NVPR+2 – REAL (KIND=nag_wp) arrayInput/Output
On entry: holds the initial values of the variance components, γ 0 , with GAMMA i the initial value for σi 2/σR 2, for i=1,2,…,g. If RINT=1 and SVID≠0, g=NVPR+1, else g=NVPR.
If GAMMA 1=-1.0, the remaining elements of GAMMA are ignored and the initial values for the variance components are estimated from the data using MIVQUE0.
On exit: GAMMA i, for i=1,2,…,g, holds the final estimate of σi 2 and GAMMA g+1 holds the final estimate for σR 2.
Constraint: GAMMA 1=-1.0 ​ or ​ GAMMA i≥0.0, for i=1,2,…,g.
18:   NFF – INTEGEROutput
On exit: the number of fixed effects estimated (i.e., the number of columns, p, in the design matrix X).
19:   NRF – INTEGEROutput
On exit: the number of random effects estimated (i.e., the number of columns, q, in the design matrix Z).
20:   DF – INTEGEROutput
On exit: the degrees of freedom.
21:   REML – REAL (KIND=nag_wp)Output
On exit: - 2 lR γ^ where lR is the log of the restricted maximum likelihood calculated at γ^ , the estimated variance components returned in GAMMA.
22:   LB – INTEGERInput
On entry: the size of the array B.
Constraint: LB ≥ FINT + ∑ i=1 NFV max LEVELS FVID i-1,1 + LS × RINT + ∑ i=1 NRV LEVELS RVID i where LS = LEVELS SVID if SVID≠0 and 1 otherwise.
23:   B LB – REAL (KIND=nag_wp) arrayOutput
On exit: the parameter estimates, β,ν, with the first NFF elements of B containing the fixed effect parameter estimates, β and the next NRF elements of B containing the random effect parameter estimates, ν.
Fixed effects
If FINT=1, B 1 contains the estimate of the fixed intercept. Let Li denote the number of levels associated with the ith fixed variable, that is Li = LEVELS FVID i . Define
  • if FINT=1, F 1 = 2 else if FINT=0, F 1=1 ;
  • F i+1 = Fi + max Li-1,1 , i≥1 .
Then for i=1,2,…,NFV:
  • if Li > 1 , B Fi+j-2 contains the parameter estimate for the jth level of the ith fixed variable, for j=2,3,…,Li;
  • if Li ≤ 1 , B Fi contains the parameter estimate for the ith fixed variable.
Random effects
Redefining Li to denote the number of levels associated with the ith random variable, that is Li = LEVELS RVID i . Define
  • if RINT=1, R 1 = 2 else if RINT=0, R 1=1 ;
    R i+1 = Ri + Li , i≥1 .
Then for i = 1 , 2 , … , NRV :
  • if SVID=0,
    • if Li > 1 , B NFF + Ri +j-1 contains the parameter estimate for the jth level of the ith random variable, for j=1,2,…,Li;
    • if Li ≤ 1 , B NFF + Ri contains the parameter estimate for the ith random variable;
  • if SVID ≠ 0 ,
    • let LS denote the number of levels associated with the subject variable, that is LS = LEVELS SVID ;
    • if Li > 1 , B NFF + s-1 LS + Ri + j - 1 contains the parameter estimate for the interaction between the sth level of the subject variable and the jth level of the ith random variable, for s=1,2,…,LS and j=1,2,…,Li;
    • if Li ≤ 1 , B NFF + s-1 LS + Ri contains the parameter estimate for the interaction between the sth level of the subject variable and the ith random variable, for s=1,2,…,LS;
    • if RINT=1, B NFF+1 contains the estimate of the random intercept.
24:   SE LB – REAL (KIND=nag_wp) arrayOutput
On exit: the standard errors of the parameter estimates given in B.
25:   MAXIT – INTEGERInput
On entry: the maximum number of iterations.
If MAXIT < 0 , the default value of 100 is used.
If MAXIT=0, the parameter estimates β,ν and corresponding standard errors are calculated based on the value of γ 0 supplied in GAMMA.
26:   TOL – REAL (KIND=nag_wp)Input
On entry: the tolerance used to assess convergence.
If TOL≤0.0, the default value of ε 0.7 is used, where ε is the machine precision.
27:   WARN – INTEGEROutput
On exit: is set to 1 if a variance component was estimated to be a negative value during the fitting process. Otherwise WARN is set to 0 .
If WARN=1, the negative estimate is set to zero and the estimation process allowed to continue.
28:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, CWID=value and NCOL=value.
Constraint: 0≤CWID≤NCOL and any supplied weights must be ≥0.0.
On entry, FINT=value.
Constraint: FINT=0 or 1.
On entry, LB too small: LB=value.
On entry, LDDAT=value and N=value.
Constraint: LDDAT≥N.
On entry, N=value.
Constraint: N≥1.
On entry, N<1 (nonzero weighted observations): N=value.
On entry, NCOL=value.
Constraint: NCOL≥1.
On entry, NFV=value and NCOL=value.
Constraint: 0≤NFV<NCOL.
On entry, NRV=value and NCOL=value.
Constraint: 0≤NRV<NCOL and NRV+RINT>0.
On entry, NVPR=value and NRV=value.
Constraint: 0≤NVPR≤NRV and (NRV≠0 or NVPR≥1).
On entry, RINT=value.
Constraint: RINT=0 or 1.
On entry, SVID=value and NCOL=value.
Constraint: 0≤SVID≤NCOL.
On entry, YVID=value and NCOL=value.
Constraint: 1≤YVID≤NCOL.
IFAIL=2
On entry, GAMMA i<0.0, for at least one i.
On entry, invalid data: categorical variable with value greater than that specified in LEVELS.
On entry, LEVELS I<1, for at least one I.
On entry, NCOL=value.
Constraint: 1≤FVID i≤NCOL, for all i.
On entry, NCOL=value.
Constraint: 1≤RVID i≤NCOL, for all i.
On entry, NVPR=value.
Constraint: 1≤VPR i≤NVPR, for all i.
IFAIL=3
Degrees of freedom <1: DF=value.
This is due to the number of parameters exceeding the effective number of observations.
IFAIL=4
Routine failed to converge in MAXIT iterations: MAXIT=value.
See Section 10 for advice.
Routine failed to converge to specified tolerance: TOL=value.
See Section 10 for advice.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

The accuracy of the results can be adjusted through the use of the TOL argument.

8 Parallelism and Performance

G02JAF is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
G02JAF makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

Wherever possible any block structure present in the design matrix Z should be modelled through a subject variable, specified via SVID, rather than being explicitly entered into DAT.
G02JAF uses an iterative process to fit the specified model and for some problems this process may fail to converge (see IFAIL=4). If the routine fails to converge then the maximum number of iterations (see MAXIT) or tolerance (see TOL) may require increasing; try a different starting estimate in GAMMA. Alternatively, the model can be fit using maximum likelihood (see G02JBF) or using the noniterative MIVQUE0.
To fit the model just using MIVQUE0, the first element of GAMMA should be set to -1.0 and MAXIT should be set to zero.
Although the quasi-Newton algorithm used in G02JAF tends to require more iterations before converging compared to the Newton–Raphson algorithm recommended by Wolfinger et al. (1994), it does not require the second derivatives of the likelihood function to be calculated and consequentially takes significantly less time per iteration.

10 Example

The following dataset is taken from Stroup (1989) and arises from a balanced split-plot design with the whole plots arranged in a randomized complete block-design.
In this example the full design matrix for the random independent variable, Z , is given by:
Z = 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 1 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 1
= A 0 0 0 0 A 0 0 0 0 A 0 0 0 0 A A 0 0 0 0 A 0 0 0 0 A 0 0 0 0 A , (1)
where
A = 1 1 0 0 1 0 1 0 1 0 0 1 .
The block structure evident in (1) is modelled by specifying a four-level subject variable, taking the values 1 , 1 , 1 , 2 , 2 , 2 , 3 , 3 , 3 , 4 , 4 , 4 , 1 , 1 , 1 , 2 , 2 , 2 , 3 , 3 , 3 , 4 , 4 , 4 . The first column of 1 s is added to A by setting RINT=1. The remaining columns of A are specified by a three level factor, taking the values, 1 , 2 , 3 , 1 , 2 , 3 , 1 , … .

10.1 Program Text

Program Text (g02jafe.f90)

10.2 Program Data

Program Data (g02jafe.d)

10.3 Program Results

Program Results (g02jafe.r)

G02 Chapter Contents
G02 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


G02JBF : NAG Library, Mark 26

G02 Chapter Contents
G02 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

G02JBF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

G02JBF fits a linear mixed effects regression model using maximum likelihood (ML).

2 Specification

SUBROUTINE G02JBF ( N, NCOL, LDDAT, DAT, LEVELS, YVID, CWID, NFV, FVID, FINT, NRV, RVID, NVPR, VPR, RINT, SVID, GAMMA, NFF, NRF, DF, ML, LB, B, SE, MAXIT, TOL, WARN, IFAIL)
INTEGER | N, NCOL, LDDAT, LEVELS(NCOL), YVID, CWID, NFV, FVID(NFV), FINT, NRV, RVID(NRV), NVPR, VPR(NRV), RINT, SVID, NFF, NRF, DF, LB, MAXIT, WARN, IFAIL
REAL (KIND=nag_wp) | DAT(LDDAT,NCOL), GAMMA(NVPR+2), ML, B(LB), SE(LB), TOL

3 Description

G02JBF fits a model of the form:
y=Xβ+Zν+ε
where
  • y is a vector of n observations on the dependent variable,
  • X is a known n by p design matrix for the fixed independent variables,
  • β is a vector of length p of unknown fixed effects,
  • Z is a known n by q design matrix for the random independent variables,
  • ν is a vector of length q of unknown random effects;
and
  • ε is a vector of length n of unknown random errors.
Both ν and ε are assumed to have a Gaussian distribution with expectation zero and
Var ν ε = G 0 0 R
where R= σ R 2 I , I is the n×n identity matrix and G is a diagonal matrix. It is assumed that the random variables, Z , can be subdivided into g ≤ q groups with each group being identically distributed with expectations zero and variance σi 2 . The diagonal elements of matrix G therefore take one of the values σi 2 : i=1,2,…,g , depending on which group the associated random variable belongs to.
The model therefore contains three sets of unknowns, the fixed effects, β , the random effects ν and a vector of g+1 variance components, γ , where γ = σ1 2,σ2 2,…, σ g-1 2 ,σg2,σR2 . Rather than working directly with γ , G02JBF uses an iterative process to estimate γ* = σ1 2 / σR2 , σ2 2 / σR2 ,…, σ g-1 2 / σR2 , σg2 / σR2 ,1 . Due to the iterative nature of the estimation a set of initial values, γ 0 , for γ* is required. G02JBF allows these initial values either to be supplied by you or calculated from the data using the minimum variance quadratic unbiased estimators (MIVQUE0) suggested by Rao (1972).
G02JBF fits the model using a quasi-Newton algorithm to maximize the log-likelihood function:
-2 l R = log V + n log r ′ V-1 r + log 2 π / n
where
V = ZG Z′ + R,   r=y-Xb   and   b = X ′ V-1 X -1 X ′ V-1 y .
Once the final estimates for γ * have been obtained, the value of σR 2 is given by:
σR 2 = r′ V-1 r / n - p .
Case weights, Wc , can be incorporated into the model by replacing X′X and Z′Z with X′Wc X and Z′Wc Z respectively, for a diagonal weight matrix Wc .
The log-likelihood, lR, is calculated using the sweep algorithm detailed in Wolfinger et al. (1994).

4 References

Goodnight J H (1979) A tutorial on the SWEEP operator The American Statistician 33(3) 149–158
Harville D A (1977) Maximum likelihood approaches to variance component estimation and to related problems JASA 72 320–340
Rao C R (1972) Estimation of variance and covariance components in a linear model J. Am. Stat. Assoc. 67 112–115
Stroup W W (1989) Predictable functions and prediction space in the mixed model procedure Applications of Mixed Models in Agriculture and Related Disciplines Southern Cooperative Series Bulletin No. 343 39–48
Wolfinger R, Tobias R and Sall J (1994) Computing Gaussian likelihoods and their derivatives for general linear mixed models SIAM Sci. Statist. Comput. 15 1294–1310

5 Arguments

1:   N – INTEGERInput
On entry: n, the number of observations.
Constraint: N≥1.
2:   NCOL – INTEGERInput
On entry: the number of columns in the data matrix, DAT.
Constraint: NCOL≥1.
3:   LDDAT – INTEGERInput
On entry: the first dimension of the array DAT as declared in the (sub)program from which G02JBF is called.
Constraint: LDDAT≥N.
4:   DAT LDDATNCOL – REAL (KIND=nag_wp) arrayInput
On entry: array containing all of the data. For the ith observation:
  • DAT iYVID holds the dependent variable, y;
  • if CWID≠0, DAT iCWID holds the case weights;
  • if SVID≠0, DAT iSVID holds the subject variable.
The remaining columns hold the values of the independent variables.
Constraints:
  • if CWID≠0, DAT iCWID≥0.0;
  • if LEVELS j≠1, 1≤DAT ij≤LEVELS j.
5:   LEVELS NCOL – INTEGER arrayInput
On entry: LEVELS i contains the number of levels associated with the ith variable of the data matrix DAT. If this variable is continuous or binary (i.e., only takes the values zero or one) then LEVELS i should be 1; if the variable is discrete then LEVELS i is the number of levels associated with it and DAT ji is assumed to take the values 1 to LEVELS i, for j=1,2,…,N.
Constraint: LEVELS i≥1, for i=1,2,…,NCOL.
6:   YVID – INTEGERInput
On entry: the column of DAT holding the dependent, y, variable.
Constraint: 1≤YVID≤NCOL.
7:   CWID – INTEGERInput
On entry: the column of DAT holding the case weights.
If CWID=0, no weights are used.
Constraint: 0≤CWID≤NCOL.
8:   NFV – INTEGERInput
On entry: the number of independent variables in the model which are to be treated as being fixed.
Constraint: 0≤NFV<NCOL.
9:   FVID NFV – INTEGER arrayInput
On entry: the columns of the data matrix DAT holding the fixed independent variables with FVID i holding the column number corresponding to the i th fixed variable.
Constraint: 1≤FVID i≤NCOL, for i=1,2,…,NFV.
10:   FINT – INTEGERInput
On entry: flag indicating whether a fixed intercept is included (FINT=1).
Constraint: FINT=0 or 1.
11:   NRV – INTEGERInput
On entry: the number of independent variables in the model which are to be treated as being random.
Constraints:
  • 0≤NRV<NCOL;
  • NRV+RINT>0.
12:   RVID NRV – INTEGER arrayInput
On entry: the columns of the data matrix DAT holding the random independent variables with RVID i holding the column number corresponding to the i th random variable.
Constraint: 1≤RVID i≤NCOL, for i=1,2,…,NRV.
13:   NVPR – INTEGERInput
On entry: if RINT=1 and SVID≠0, NVPR is the number of variance components being estimated-2, (g-1), else NVPR=g.
If NRV=0, NVPR is not referenced.
Constraint: if NRV≠0, 1≤NVPR≤NRV.
14:   VPR NRV – INTEGER arrayInput
On entry: VPR i holds a flag indicating the variance of the i th random variable. The variance of the i th random variable is σ j 2 , where j = VPR i + 1 if RINT=1 and SVID≠0 and j = VPR i otherwise. Random variables with the same value of j are assumed to be taken from the same distribution.
Constraint: 1≤VPR i≤NVPR, for i=1,2,…,NRV.
15:   RINT – INTEGERInput
On entry: flag indicating whether a random intercept is included (RINT=1).
If SVID=0, RINT is not referenced.
Constraint: RINT=0 or 1.
16:   SVID – INTEGERInput
On entry: the column of DAT holding the subject variable.
If SVID=0, no subject variable is used.
Specifying a subject variable is equivalent to specifying the interaction between that variable and all of the random-effects. Letting the notation Z 1 × ZS denote the interaction between variables Z 1 and ZS , fitting a model with RINT = 0 , random-effects Z 1 + Z 2 and subject variable ZS is equivalent to fitting a model with random-effects Z 1 × ZS + Z 2 × ZS and no subject variable. If RINT = 1 the model is equivalent to fitting ZS + Z 1 × ZS + Z 2 × ZS and no subject variable.
Constraint: 0≤SVID≤NCOL.
17:   GAMMA NVPR+2 – REAL (KIND=nag_wp) arrayInput/Output
On entry: holds the initial values of the variance components, γ 0 , with GAMMA i the initial value for σi 2/σR 2, for i=1,2,…,g. If RINT=1 and SVID≠0, g=NVPR+1, else g=NVPR.
If GAMMA 1=-1.0, the remaining elements of GAMMA are ignored and the initial values for the variance components are estimated from the data using MIVQUE0.
On exit: GAMMA i, for i=1,2,…,g, holds the final estimate of σi 2 and GAMMA g+1 holds the final estimate for σR 2.
Constraint: GAMMA 1=-1.0 ​ or ​ GAMMA i≥0.0, for i=1,2,…,g.
18:   NFF – INTEGEROutput
On exit: the number of fixed effects estimated (i.e., the number of columns, p, in the design matrix X).
19:   NRF – INTEGEROutput
On exit: the number of random effects estimated (i.e., the number of columns, q, in the design matrix Z).
20:   DF – INTEGEROutput
On exit: the degrees of freedom.
21:   ML – REAL (KIND=nag_wp)Output
On exit: - 2 lR γ^ where lR is the log of the maximum likelihood calculated at γ^ , the estimated variance components returned in GAMMA.
22:   LB – INTEGERInput
On entry: the size of the array B.
Constraint: LB ≥ FINT + ∑ i=1 NFV max LEVELS FVID i-1,1 + LS × RINT + ∑ i=1 NRV LEVELS RVID i where LS = LEVELS SVID if SVID≠0 and 1 otherwise.
23:   B LB – REAL (KIND=nag_wp) arrayOutput
On exit: the parameter estimates, β,ν, with the first NFF elements of B containing the fixed effect parameter estimates, β and the next NRF elements of B containing the random effect parameter estimates, ν.
Fixed effects
If FINT=1, B 1 contains the estimate of the fixed intercept. Let Li denote the number of levels associated with the ith fixed variable, that is Li = LEVELS FVID i . Define
  • if FINT=1, F 1 = 2 else if FINT=0, F 1=1 ;
  • F i+1 = Fi + max Li-1,1 , i≥1 .
Then for i=1,2,…,NFV:
  • if Li > 1 , B Fi+j-2 contains the parameter estimate for the jth level of the ith fixed variable, for j=2,3,…,Li;
  • if Li ≤ 1 , B Fi contains the parameter estimate for the ith fixed variable.
Random effects
Redefining Li to denote the number of levels associated with the ith random variable, that is Li = LEVELS RVID i . Define
  • if RINT=1, R 1 = 2 else if RINT=0, R 1=1 ;
    R i+1 = Ri + Li , i≥1 .
Then for i = 1 , 2 , … , NRV :
  • if SVID=0,
    • if Li > 1 , B NFF + Ri +j-1 contains the parameter estimate for the jth level of the ith random variable, for j=1,2,…,Li;
    • if Li ≤ 1 , B NFF + Ri contains the parameter estimate for the ith random variable;
  • if SVID ≠ 0 ,
    • let LS denote the number of levels associated with the subject variable, that is LS = LEVELS SVID ;
    • if Li > 1 , B NFF + s-1 LS + Ri + j - 1 contains the parameter estimate for the interaction between the sth level of the subject variable and the jth level of the ith random variable, for s=1,2,…,LS and j=1,2,…,Li;
    • if Li ≤ 1 , B NFF + s-1 LS + Ri contains the parameter estimate for the interaction between the sth level of the subject variable and the ith random variable, for s=1,2,…,LS;
    • if RINT=1, B NFF+1 contains the estimate of the random intercept.
24:   SE LB – REAL (KIND=nag_wp) arrayOutput
On exit: the standard errors of the parameter estimates given in B.
25:   MAXIT – INTEGERInput
On entry: the maximum number of iterations.
If MAXIT < 0 , the default value of 100 is used.
If MAXIT=0, the parameter estimates β,ν and corresponding standard errors are calculated based on the value of γ 0 supplied in GAMMA.
26:   TOL – REAL (KIND=nag_wp)Input
On entry: the tolerance used to assess convergence.
If TOL≤0.0, the default value of ε 0.7 is used, where ε is the machine precision.
27:   WARN – INTEGEROutput
On exit: is set to 1 if a variance component was estimated to be a negative value during the fitting process. Otherwise WARN is set to 0 .
If WARN=1, the negative estimate is set to zero and the estimation process allowed to continue.
28:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, | N<2,
or | NCOL<1,
or | LDDAT<N,
or | YVID<1 or YVID>NCOL,
or | CWID<0 or CWID>NCOL,
or | NFV<0 or NFV≥NCOL,
or | FINT≠0 and FINT≠1,
or | NRV<0 or NRV>NCOL or NRV+RINT<1,
or | NVPR<0 or NVPR>NRV,
or | RINT≠0 and RINT≠1,
or | SVID<0 or SVID>NCOL,
or | LB is too small.
IFAIL=2
On entry, | LEVELS i<1, for at least one i,
or | FVID i<1, or FVID i>NCOL, for at least one i,
or | RVID i<1, or RVID i>NCOL, for at least one i,
or | VPR i<1 or VPR i>NVPR, for at least one i,
or | at least one discrete variable in array DAT has a value greater than that specified in LEVELS,
or | GAMMA i<0, for at least one i, and GAMMA 1≠-1.
IFAIL=3
Degrees of freedom <1. The number of arguments exceed the effective number of observations.
IFAIL=4
The routine failed to converge to the specified tolerance in MAXIT iterations. See Section 9 for advice.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

The accuracy of the results can be adjusted through the use of the TOL argument.

8 Parallelism and Performance

G02JBF is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
G02JBF makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

Wherever possible any block structure present in the design matrix Z should be modelled through a subject variable, specified via SVID, rather than being explicitly entered into DAT.
G02JBF uses an iterative process to fit the specified model and for some problems this process may fail to converge (see IFAIL=4). If the routine fails to converge then the maximum number of iterations (see MAXIT) or tolerance (see TOL) may require increasing; try a different starting estimate in GAMMA. Alternatively, the model can be fit using restricted maximum likelihood (see G02JAF) or using the noniterative MIVQUE0.
To fit the model just using MIVQUE0, the first element of GAMMA should be set to -1 and MAXIT should be set to zero.
Although the quasi-Newton algorithm used in G02JBF tends to require more iterations before converging compared to the Newton–Raphson algorithm recommended by Wolfinger et al. (1994), it does not require the second derivatives of the likelihood function to be calculated and consequentially takes significantly less time per iteration.

10 Example

The following dataset is taken from Stroup (1989) and arises from a balanced split-plot design with the whole plots arranged in a randomized complete block-design.
In this example the full design matrix for the random independent variable, Z , is given by:
Z = 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 1 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 1
= A 0 0 0 0 A 0 0 0 0 A 0 0 0 0 A A 0 0 0 0 A 0 0 0 0 A 0 0 0 0 A , (1)
where
A = 1 1 0 0 1 0 1 0 1 0 0 1 .
The block structure evident in (1) is modelled by specifying a four-level subject variable, taking the values 1 , 1 , 1 , 2 , 2 , 2 , 3 , 3 , 3 , 4 , 4 , 4 , 1 , 1 , 1 , 2 , 2 , 2 , 3 , 3 , 3 , 4 , 4 , 4 . The first column of 1 s is added to A by setting RINT=1. The remaining columns of A are specified by a three level factor, taking the values, 1 , 2 , 3 , 1 , 2 , 3 , 1 , … .

10.1 Program Text

Program Text (g02jbfe.f90)

10.2 Program Data

Program Data (g02jbfe.d)

10.3 Program Results

Program Results (g02jbfe.r)

G02 Chapter Contents
G02 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


G02JCF : NAG Library, Mark 26

G02 Chapter Contents
G02 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

G02JCF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
▸▿ 9 Further Comments
9.1 Construction of the fixed effects design matrix, X
9.2 Construction of random effects design matrix, Z
9.3 The RNDM argument
10 Example

1 Purpose

G02JCF preprocesses a dataset prior to fitting a linear mixed effects regression model of the following form via either G02JDF or G02JEF.

2 Specification

SUBROUTINE G02JCF ( WEIGHT, N, NCOL, DAT, LDDAT, LEVELS, Y, WT, FIXED, LFIXED, NRNDM, RNDM, LDRNDM, NFF, NLSV, NRF, RCOMM, LRCOMM, ICOMM, LICOMM, IFAIL)
INTEGER | N, NCOL, LDDAT, LEVELS(NCOL), FIXED(LFIXED), LFIXED, NRNDM, RNDM(LDRNDM,NRNDM), LDRNDM, NFF, NLSV, NRF, LRCOMM, ICOMM(LICOMM), LICOMM, IFAIL
REAL (KIND=nag_wp) | DAT(LDDAT,NCOL), Y(N), WT(*), RCOMM(LRCOMM)
CHARACTER(1) | WEIGHT

3 Description

G02JCF must be called prior to fitting a linear mixed effects regression model with either G02JDF or G02JEF.
The model fitting routines G02JDF and G02JEF fit a model of the following form:
y=Xβ+Zν+ε
where | y is a vector of n observations on the dependent variable,
 | X is an n by p design matrix of fixed independent variables,
 | β is a vector of p unknown fixed effects,
 | Z is an n by q design matrix of random independent variables,
 | ν is a vector of length q of unknown random effects,
 | ε is a vector of length n of unknown random errors,
and ν and ε are Normally distributed with expectation zero and variance/covariance matrix defined by
Var ν ε = G 0 0 R
where R= σ R 2 I , I is the n×n identity matrix and G is a diagonal matrix.
Case weights can be incorporated into the model by replacing X and Z with Wc 1/2 X and Wc 1/2 Z respectively where Wc is a diagonal weight matrix.

4 References

None.

5 Arguments

1:   WEIGHT – CHARACTER(1)Input
On entry: indicates if weights are to be used.
WEIGHT='U'
No weights are used.
WEIGHT='W'
Case weights are used and must be supplied in array WT.
Constraint: WEIGHT='U' or 'W'.
2:   N – INTEGERInput
On entry: n, the number of observations.
The effective number of observations, that is the number of observations with nonzero weight (see WT for more detail), must be greater than the number of fixed effects in the model (as returned in NFF).
Constraint: N≥1.
3:   NCOL – INTEGERInput
On entry: the number of columns in the data matrix, DAT.
Constraint: NCOL≥0.
4:   DAT LDDATNCOL – REAL (KIND=nag_wp) arrayInput
On entry: a matrix of data, with DAT ij holding the ith observation on the jth variable. The two design matrices X and Z are constructed from DAT and the information given in FIXED (for X) and RNDM (for Z).
Constraint: if LEVELS j≠1,1≤DAT ij≤LEVELS j.
5:   LDDAT – INTEGERInput
On entry: the first dimension of the array DAT as declared in the (sub)program from which G02JCF is called.
Constraint: LDDAT≥N.
6:   LEVELS NCOL – INTEGER arrayInput
On entry: LEVELS i contains the number of levels associated with the ith variable held in DAT.
If the ith variable is continuous or binary (i.e., only takes the values zero or one) then LEVELS i must be set to 1. Otherwise the ith variable is assumed to take an integer value between 1 and LEVELS i, (i.e., the ith variable is discrete with LEVELS i levels).
Constraint: LEVELS i≥1, for i=1,2,…,NCOL.
7:   Y N – REAL (KIND=nag_wp) arrayInput
On entry: y, the vector of observations on the dependent variable.
8:   WT* – REAL (KIND=nag_wp) arrayInput
Note: the dimension of the array WT must be at least N if WEIGHT='W'.
On entry: if WEIGHT='W', WT must contain the diagonal elements of the weight matrix Wc.
If WT i=0.0, the ith observation is not included in the model and the effective number of observations is the number of observations with nonzero weights.
If WEIGHT='U', WT is not referenced and the effective number of observations is n.
Constraint: if WEIGHT='W', WT i≥0.0, for i=1,2,…,n.
9:   FIXED LFIXED – INTEGER arrayInput
On entry: defines the structure of the fixed effects design matrix, X.
FIXED 1
The number of variables, NF, to include as fixed effects (not including the intercept if present).
FIXED 2
The fixed intercept flag which must contain 1 if a fixed intercept is to be included and 0 otherwise.
FIXED 2+i
The column of DAT holding the ith fixed variable, for i=1,2,…,FIXED 1.
See Section 9.1 for more details on the construction of X.
Constraints:
  • FIXED 1≥0;
  • FIXED 2=0​ or ​1;
  • 1≤FIXED 2+i≤NCOL, for i=1,2,…,FIXED 1.
10:   LFIXED – INTEGERInput
On entry: length of the vector FIXED.
Constraint: LFIXED≥2+FIXED 1.
11:   NRNDM – INTEGERInput
On entry: the second dimension of the array RNDM as declared in the (sub)program from which G02JCF is called.
Constraint: NRNDM>0.
12:   RNDM LDRNDMNRNDM – INTEGER arrayInput
On entry: RNDM ij defines the structure of the random effects design matrix, Z. The bth column of RNDM defines a block of columns in the design matrix Z.
RNDM 1 b
The number of variables, N Rb, to include as random effects in the bth block (not including the random intercept if present).
RNDM 2 b
The random intercept flag which must contain 1 if block b includes a random intercept and 0 otherwise.
RNDM 2+i b
The column of DAT holding the ith random variable in the bth block, for i=1,2,…,RNDM 1 b.
RNDM 3+N Rb b
The number of subject variables, N Sb, for the bth block. The subject variables define the nesting structure for this block.
RNDM 3+N Rb+i b
The column of DAT holding the ith subject variable in the bth block, for i=1,2,…,RNDM 3+N Rb b.
See Section 9.2 for more details on the construction of Z.
Constraints:
  • RNDM 1 b≥0;
  • RNDM 2 b=0​ or ​1;
  • at least one random variable or random intercept must be specified in each block, i.e., RNDM 1 b + RNDM 2 b > 0 ;
  • the column identifiers associated with the random variables must be in the range 1 to NCOL, i.e., 1≤ RNDM 2+i b ≤ NCOL , for i=1,2,…,RNDM 1 b;
  • RNDM 3+N Rb b ≥0 ;
  • the column identifiers associated with the subject variables must be in the range 1 to NCOL, i.e., 1≤ RNDM 3+ N R b +i b ≤NCOL , for i=1,2,…,RNDM 3+N Rb b.
13:   LDRNDM – INTEGERInput
On entry: the first dimension of the array RNDM as declared in the (sub)program from which G02JCF is called.
Constraint: LDRNDM≥ max b 3+N Rb+N Sb .
14:   NFF – INTEGEROutput
On exit: p, the number of fixed effects estimated, i.e., the number of columns in the design matrix X.
15:   NLSV – INTEGEROutput
On exit: the number of levels for the overall subject variable (see Section 9.2 for a description of what this means). If there is no overall subject variable, NLSV=1.
16:   NRF – INTEGEROutput
On exit: the number of random effects estimated in each of the overall subject blocks. The number of columns in the design matrix Z is given by q=NRF×NLSV.
17:   RCOMM LRCOMM – REAL (KIND=nag_wp) arrayCommunication Array
On exit: communication array as required by the analysis routines G02JDF and G02JEF.
18:   LRCOMM – INTEGERInput
On entry: the dimension of the array RCOMM as declared in the (sub)program from which G02JCF is called.
Constraint: LRCOMM≥NRF×NLSV+NFF+NFF×NLSV+NRF×NLSV+NFF+2.
19:   ICOMM LICOMM – INTEGER arrayCommunication Array
On exit: if LICOMM=2, ICOMM 1 holds the minimum required value for LICOMM and ICOMM 2 holds the minimum required value for LRCOMM, otherwise ICOMM is a communication array as required by the analysis routines G02JDF and G02JEF.
20:   LICOMM – INTEGERInput
On entry: the dimension of the array ICOMM as declared in the (sub)program from which G02JCF is called.
Constraint: LICOMM=2 or LICOMM≥34+ NF×MFL+1+ NRNDM×MNR×MRL+LRNDM+2×NRNDM+ NCOL+LDID×LB,
where
  • MNR = maxb N R b ,
  • MFL=maxi LEVELS FIXED 2+i ,
  • MRL=max b,i LEVELS RNDM 2+i b ,
  • LDID=maxb N Sb ,
  • LB=NFF+NRF×NLSV, and
  • LRNDM= max b 3+N Rb+N Sb
21:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, WEIGHT had an illegal value.
IFAIL=2
On entry, N=value.
Constraint: N≥1.
IFAIL=3
On entry, NCOL=value.
Constraint: NCOL≥0.
IFAIL=4
On entry, variable j of observation i is less than 1 or greater than LEVELS j: i=value, j=value, value =value, LEVELS j=value.
IFAIL=5
On entry, LDDAT=value and N=value.
Constraint: LDDAT≥N.
IFAIL=6
On entry, LEVELS value=value.
Constraint: LEVELS i≥1.
IFAIL=8
On entry, WT value=value.
Constraint: WT i≥0.0.
IFAIL=9
On entry, number of fixed parameters, value is less than zero.
IFAIL=10
On entry, LFIXED=value.
Constraint: LFIXED≥value.
IFAIL=11
On entry, NRNDM=value.
Constraint: NRNDM>0.
IFAIL=12
On entry, number of random parameters for random statement i is less than 0: i=value, number of parameters =value.
IFAIL=13
On entry, LDRNDM=value.
Constraint: LDRNDM≥value.
IFAIL=18
On entry, LRCOMM=value.
Constraint: LRCOMM≥value.
IFAIL=20
On entry, LICOMM=value.
Constraint: LICOMM≥value.
IFAIL=102
On entry, more fixed factors than observations, N=value.
Constraint: N≥value.
IFAIL=108
On entry, no observations due to zero weights.
IFAIL=109
On entry, invalid value for fixed intercept flag: value =value.
IFAIL=112
On entry, invalid value for random intercept flag for random statement i: i=value, value =value.
IFAIL=209
On entry, index of fixed variable j is less than 1 or greater than NCOL: j=value, index =value and NCOL=value.
IFAIL=212
On entry, must be at least one parameter, or an intercept in each random statement i: i=value.
IFAIL=312
On entry, index of random variable j in random statement i is less than 1 or greater than NCOL: i=value, j=value, index =value and NCOL=value.
IFAIL=412
On entry, number of subject parameters for random statement i is less than 0: i=value, number of parameters =value.
IFAIL=512
On entry, nesting variable j in random statement i has one level: j=value, i=value.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

Not applicable.

8 Parallelism and Performance

G02JCF is not threaded in any implementation.

9 Further Comments

9.1 Construction of the fixed effects design matrix, X

Let
  • NF denote the number of fixed variables, that is FIXED 1=NF;
  • Fj denote the jth fixed variable, that is the vector of values held in the kth column of DAT when FIXED 2+j=k;
  • F ij denote the ith element of Fj;
  • L Fj denote the number of levels for Fj, that is L Fj=LEVELS FIXED 2+j;
  • Dv Fj denoted an indicator function that returns a vector of values whose ith element is 1 if F ij=v and 0 otherwise.
The design matrix for the fixed effects, X, is constructed as follows:
  • set k to one and the flag done_first to false;
  • if a fixed intercept is included, that is FIXED 2=1,
    • set the first column of X to a vector of 1s;
    • set k=k+1;
    • set done_first to true;
  • loop over each fixed variable, so for each j=1,2,…,NF,
    • if L Fj=1,
      • set the kth column of X to be Fj;
      • set k=k+1;
    • else
      • if done_first is false then
        • set the L Fj columns, k to k+L Fj-1, of X to Dv Fj, for v=1,2,…,L Fj;
        • set k=k+L Fj;
        • set done_first to true;
      • else
        • set the L Fj-1 columns, k to k+L Fj-2, of X to Dv Fj, for v=2,3,…,L Fj;
        • set k=k+L Fj-1.
The number of columns in the design matrix, X, is therefore given by
p= 1+ ∑ j=1 N F LEVELS FIXED 2+j -1 .
This quantity is returned in NFF.
In summary, G02JCF converts all non-binary categorical variables (i.e., where L Fj>1) to dummy variables. If a fixed intercept is included in the model then the first level of all such variables is dropped. If a fixed intercept is not included in the model then the first level of all such variables, other than the first, is dropped. The variables are added into the model in the order they are specified in FIXED.

9.2 Construction of random effects design matrix, Z

Let
  • N Rb denote the number of random variables in the bth random statement, that is N Rb=RNDM 1 b;
  • R jb denote the jth random variable from the bth random statement, that is the vector of values held in the kth column of DAT when RNDM 2+j b=k;
  • R ijb denote the ith element of R jb;
  • L R jb denote the number of levels for R jb, that is L R jb=LEVELS RNDM 2+j b;
  • Dv R jb denoted an indicator function that returns a vector of values whose ith element is 1 if R ijb=v and 0 otherwise;
  • N Sb denote the number of subject variables in the bth random statement, that is N Sb=RNDM 3+N Rb b;
  • S jb denote the jth subject variable from the bth random statement, that is the vector of values held in the kth column of DAT when RNDM 3+N Rb+j b=k;
  • S ijb denote the ith element of S jb;
  • L S jb denote the number of levels for S jb, that is L S jb=LEVELS RNDM 3+N Rb+j b;
  • I b s1 , s2 , … , s N Sb denoted an indicator function that returns a vector of values whose ith element is 1 if S ijb = sj for all j=1,2,…,N Sb and 0 otherwise.
The design matrix for the random effects, Z, is constructed as follows:
  • set k to one;
  • loop over each random statement, so for each b=1,2,…,NRNDM,
    • loop over each level of the last subject variable, so for each s N Sb=1,2,…,L R N Sb b,
      • ⋮
        • loop over each level of the second subject variable, so for each s 2=1,2,…,L R 2 b,
          • loop over each level of the first subject variable, so for each s 1=1,2,…,L R 1 b,
            • if a random intercept is included, that is RNDM 2 b=1,
              • set the kth column of Z to Ib s1,s2,…,s N Sb;
              • set k=k+1;
            • loop over each random variable in the bth random statement, so for each j=1,2,…,N Rb,
              • if L R jb=1,
                • set the kth column of Z to R jb × I b s1 , s2 , … , s N S b where × indicates an element-wise multiplication between the two vectors, R jb and Ib…;
                • set k=k+1;
              • else
                • set the L R bj columns, k to k+L R bj, of Z to Dv R jb×Ib s1,s2,…,s N Sb, for v=1,2,…,L R jb. As before, × indicates an element-wise multiplication between the two vectors, Dv… and Ib…;
                • set k=k+L R jb.
In summary, each column of RNDM defines a block of consecutive columns in Z. G02JCF converts all non-binary categorical variables (i.e., where L R jb or L S jb>1) to dummy variables. All random variables defined within a column of RNDM are nested within all subject variables defined in the same column of RNDM. In addition each of the subject variables are nested within each other, starting with the first (i.e., each of the R jb,j=1,2,…,N Rb are nested within S 1 b which in turn is nested within S 2 b, which in turn is nested within S 3 b, etc.).
If the last subject variable in each column of RNDM are the same (i.e., S N S1 1 = S N S2 2 = … = S N Sb b ) then all random effects in the model are nested within this variable. In such instances the last subject variable ( S N S1 1 ) is called the overall subject variable. The fact that all of the random effects in the model are nested within the overall subject variable means that ZT Z is block diagonal in structure. This fact can be utilised to improve the efficiency of the underlying computation and reduce the amount of internal storage required. The number of levels in the overall subject variable is returned in NLSV=L S N S1 1.
If the last k subject variables in each column of RNDM are the same, for k>1 then the overall subject variable is defined as the interaction of these k variables and
NLSV= ∏ j=N S1-k+1 N S1 L S j1 .
If there is no overall subject variable then NLSV=1.
The number of columns in the design matrix Z is given by q=NRF×NLSV.

9.3 The RNDM argument

To illustrate some additional points about the RNDM argument, we assume that we have a dataset with three discrete variables, V 1, V 2 and V 3, with 2,4 and 3 levels respectively, and that V 1 is in the first column of DAT, V 2 in the second and V 3 the third. Also assume that we wish to fit a model containing V 1 along with V 2 nested within V 3, as random effects. In order to do this the RNDM matrix requires two columns:
RNDM= 1 1 0 0 1 2 0 1 0 3
The first column, 1,0,1,0,0, indicates one random variable (RNDM 11=1), no intercept (RNDM 21=0), the random variable is in the first column of DAT (RNDM 31=1), there are no subject variables; as no nesting is required for V1 (RNDM 41=0). The last element in this column is ignored.
The second column, 1,0,2,1,3, indicates one random variable (RNDM 12=1), no intercept (RNDM 22=0), the random variable is in the second column of DAT RNDM 32=2, there is one subject variable (RNDM 42=1), and the subject variable is in the third column of DAT RNDM 52=3.
The corresponding Z matrix would have 14 columns, with 2 coming from V 1 and 12 (4×3) from V 2 nested within V 3. The, symmetric, ZT Z matrix has the form
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 0 0 0 0 0 0 0 0 - - - - - - 0 0 0 0 0 0 0 0 - - - - - - 0 0 0 0 0 0 0 0 - - - - - - 0 0 0 0 0 0 0 0 - - 0 0 0 0 - - - - 0 0 0 0 - - 0 0 0 0 - - - - 0 0 0 0 - - 0 0 0 0 - - - - 0 0 0 0 - - 0 0 0 0 - - - - 0 0 0 0 - - 0 0 0 0 0 0 0 0 - - - - - - 0 0 0 0 0 0 0 0 - - - - - - 0 0 0 0 0 0 0 0 - - - - - - 0 0 0 0 0 0 0 0 - - - -
where 0 indicates a structural zero, i.e., it always takes the value 0, irrespective of the data, and - a value that is not a structural zero. The first two rows and columns of ZT Z correspond to V 1. The block diagonal matrix in the 12 rows and columns in the bottom right correspond to V 2 nested within V 3. With the 4×4 blocks corresponding to the levels of V 2. There are three blocks as the subject variable (V 3) has three levels.
The model fitting routines, G02JDF and G02JEF, use the sweep algorithm to calculate the log-likelihood function for a given set of variance components. This algorithm consists of moving down the diagonal elements (called pivots) of a matrix which is similar in structure to ZT Z, and updating each element in that matrix. When using the k diagonal element of a matrix A, an element a i j ,i≠k,j≠k , is adjusted by an amount equal to a i k a i j / a k k . This process can be referred to as sweeping on the kth pivot. As there are no structural zeros in the first row or column of the above ZT Z, sweeping on the first pivot of ZT Z would alter each element of the matrix and therefore destroy the structural zeros, i.e., we could no longer guarantee they would be zero.
Reordering the RNDM matrix to
RNDM= 1 1 0 0 2 1 1 0 3 0
i.e., the swapping the two columns, results in a ZT Z matrix of the form
- - - - 0 0 0 0 0 0 0 0 - - - - - - 0 0 0 0 0 0 0 0 - - - - - - 0 0 0 0 0 0 0 0 - - - - - - 0 0 0 0 0 0 0 0 - - 0 0 0 0 - - - - 0 0 0 0 - - 0 0 0 0 - - - - 0 0 0 0 - - 0 0 0 0 - - - - 0 0 0 0 - - 0 0 0 0 - - - - 0 0 0 0 - - 0 0 0 0 0 0 0 0 - - - - - - 0 0 0 0 0 0 0 0 - - - - - - 0 0 0 0 0 0 0 0 - - - - - - 0 0 0 0 0 0 0 0 - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
This matrix is identical to the previous one, except the first two rows and columns have become the last two rows and columns. Sweeping a matrix, A=a ij, of this form on the first pivot will only affect those elements a ij, where a i 1≠0​ and ​a 1 j≠0, which is only the 13th and 14th row and columns, and the top left hand block of 4 rows and columns. The block diagonal nature of the first 12 rows and columns therefore greatly reduces the amount of work the algorithm needs to perform.
G02JCF constructs the ZT Z as specified by the RNDM matrix, and does not attempt to reorder it to improve performance. Therefore for best performance some thought is required on what ordering to use. In general it is more efficient to structure RNDM in such a way that the first row relates to the deepest level of nesting, the second to the next level, etc..

10 Example

See Section 10 in G02JDF and G02JEF.
G02 Chapter Contents
G02 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


G02JDF : NAG Library, Mark 26

G02 Chapter Contents
G02 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

G02JDF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

G02JDF fits a multi-level linear mixed effects regression model using restricted maximum likelihood (REML). Prior to calling G02JDF the initialization routine G02JCF must be called.

2 Specification

SUBROUTINE G02JDF ( LVPR, VPR, NVPR, GAMMA, EFFN, RNKX, NCOV, LNLIKE, LB, ID, LDID, B, SE, CZZ, LDCZZ, CXX, LDCXX, CXZ, LDCXZ, RCOMM, ICOMM, IOPT, LIOPT, ROPT, LROPT, IFAIL)
INTEGER | LVPR, VPR(LVPR), NVPR, EFFN, RNKX, NCOV, LB, ID(LDID,LB), LDID, LDCZZ, LDCXX, LDCXZ, ICOMM(*), IOPT(LIOPT), LIOPT, LROPT, IFAIL
REAL (KIND=nag_wp) | GAMMA(NVPR+1), LNLIKE, B(LB), SE(LB), CZZ(LDCZZ,*), CXX(LDCXX,*), CXZ(LDCXZ,*), RCOMM(*), ROPT(LROPT)

3 Description

G02JDF fits a model of the form:
y=Xβ+Zν+ε
where | y is a vector of n observations on the dependent variable,
 | X is a known n by p design matrix for the fixed independent variables,
 | β is a vector of length p of unknown fixed effects,
 | Z is a known n by q design matrix for the random independent variables,
 | ν is a vector of length q of unknown random effects,
and | ε is a vector of length n of unknown random errors.
Both ν and ε are assumed to have a Gaussian distribution with expectation zero and variance/covariance matrix defined by
Var ν ε = G 0 0 R
where R= σ R 2 I , I is the n×n identity matrix and G is a diagonal matrix. It is assumed that the random variables, Z , can be subdivided into g ≤ q groups with each group being identically distributed with expectation zero and variance σi 2 . The diagonal elements of matrix G therefore take one of the values σi 2 : i=1,2,…,g , depending on which group the associated random variable belongs to.
The model therefore contains three sets of unknowns: the fixed effects β, the random effects ν and a vector of g+1 variance components γ , where γ = σ1 2,σ2 2,…, σ g-1 2 ,σg2,σR2 . Rather than working directly with γ , G02JDF uses an iterative process to estimate γ* = σ1 2 / σR2 , σ2 2 / σR2 ,…, σ g-1 2 / σR2 , σg2 / σR2 ,1 . Due to the iterative nature of the estimation a set of initial values, γ 0 , for γ* is required. G02JDF allows these initial values either to be supplied by you or calculated from the data using the minimum variance quadratic unbiased estimators (MIVQUE0) suggested by Rao (1972).
G02JDF fits the model by maximizing the restricted log-likelihood function:
-2 l R = log V + n-p log rT V-1 r + log XT V-1 X + n-p 1+ log 2 π / n-p
where
V = ZG ZT + R,   r=y-Xb   and   b = XT V-1 X -1 XT V-1 y .
Once the final estimates for γ * have been obtained, the value of σR 2 is given by
σR 2 = rT V-1 r / n - p .
Case weights, Wc , can be incorporated into the model by replacing XT X and ZT Z with XT Wc X and ZT Wc Z respectively, for a diagonal weight matrix Wc .
The log-likelihood, lR, is calculated using the sweep algorithm detailed in Wolfinger et al. (1994).

4 References

Goodnight J H (1979) A tutorial on the SWEEP operator The American Statistician 33(3) 149–158
Harville D A (1977) Maximum likelihood approaches to variance component estimation and to related problems JASA 72 320–340
Rao C R (1972) Estimation of variance and covariance components in a linear model J. Am. Stat. Assoc. 67 112–115
Stroup W W (1989) Predictable functions and prediction space in the mixed model procedure Applications of Mixed Models in Agriculture and Related Disciplines Southern Cooperative Series Bulletin No. 343 39–48
Wolfinger R, Tobias R and Sall J (1994) Computing Gaussian likelihoods and their derivatives for general linear mixed models SIAM Sci. Statist. Comput. 15 1294–1310

5 Arguments

Note: prior to calling G02JDF the initialization routine G02JCF must be called, therefore this documention should be read in conjunction with the document for G02JCF.
In particular some argument names and conventions described in that document are also relevant here, but their definition has not been repeated. Specifically, RNDM, WEIGHT, N, NFF, NRF, NLSV, LEVELS, FIXED, DAT, LICOMM and LRCOMM should be interpreted identically in both routines.
1:   LVPR – INTEGERInput
On entry: the sum of the number of random parameters and the random intercept flags specified in the call to G02JCF.
Constraint: LVPR=∑i RNDM 1,i+RNDM 2,i.
2:   VPR LVPR – INTEGER arrayInput
On entry: a vector of flags indicating the mapping between the random variables specified in RNDM and the variance components, σi 2. See Section 9 for more details.
Constraint: 1≤VPR i≤NVPR, for i=1,2,…,LVPR.
3:   NVPR – INTEGERInput
On entry: g, the number of variance components being estimated (excluding the overall variance, σR 2).
Constraint: 1≤NVPR≤LVPR .
4:   GAMMA NVPR+1 – REAL (KIND=nag_wp) arrayInput/Output
On entry: holds the initial values of the variance components, γ 0 , with GAMMA i the initial value for σi 2/σR 2, for i=1,2,…,NVPR.
If GAMMA 1=-1.0, the remaining elements of GAMMA are ignored and the initial values for the variance components are estimated from the data using MIVQUE0.
On exit: GAMMA i, for i=1,2,…,NVPR, holds the final estimate of σi 2 and GAMMA NVPR+1 holds the final estimate for σR 2.
Constraint: GAMMA 1=-1.0 ​ or ​ GAMMA i≥0.0, for i=1,2,…,g.
5:   EFFN – INTEGEROutput
On exit: effective number of observations. If there are no weights (i.e., WEIGHT='U'), or all weights are nonzero, then EFFN=N.
6:   RNKX – INTEGEROutput
On exit: the rank of the design matrix, X, for the fixed effects.
7:   NCOV – INTEGEROutput
On exit: number of variance components not estimated to be zero. If none of the variance components are estimated to be zero, then NCOV=NVPR.
8:   LNLIKE – REAL (KIND=nag_wp)Output
On exit: - 2 lR γ^ where lR is the log of the restricted maximum likelihood calculated at γ^ , the estimated variance components returned in GAMMA.
9:   LB – INTEGERInput
On entry: the dimension of the arrays B and SE and the second dimension of the array ID as declared in the (sub)program from which G02JDF is called.
Constraint: LB≥NFF+NRF×NLSV.
10:   ID LDIDLB – INTEGER arrayOutput
On exit: an array describing the parameter estimates returned in B. The first NLSV×NRF columns of ID describe the parameter estimates for the random effects and the last NFF columns the parameter estimates for the fixed effects.
The example program for this routine includes a demonstration of decoding the parameter estimates given in B using information from ID.
For fixed effects:
  • for l=NRF×NLSV+1 ,…, NRF×NLSV+NFF
    • if B l contains the parameter estimate for the intercept then
      ID 1 l = ID 2 l = ID 3 l = 0 ;
    • if B l contains the parameter estimate for the ith level of the jth fixed variable, that is the vector of values held in the kth column of DAT when FIXED j+2=k then
      ID 1 l=0,  ID 2 l=j,  ID 3 l=i;
    • if the jth variable is continuous or binary, that is LEVELS FIXED j+2=1, then ID 3 l=0;
    • any remaining rows of the lth column of ID are set to 0.
For random effects:
  • let
    • N Rb denote the number of random variables in the bth random statement, that is N Rb=RNDM 1,b;
    • R jb denote the jth random variable from the bth random statement, that is the vector of values held in the kth column of DAT when RNDM 2+j,b=k;
    • N Sb denote the number of subject variables in the bth random statement, that is N Sb=RNDM 3+N Rb,b;
    • S jb denote the jth subject variable from the bth random statement, that is the vector of values held in the kth column of DAT when RNDM 3+N Rb+j,b=k;
    • L S jb denote the number of levels for S jb, that is L S jb=LEVELS RNDM 3+N Rb+j,b;
  • then
    • for l=1,2,… NRF×NLSV, if B l contains the parameter estimate for the ith level of R jb when S kb=sk, for k=1,2,…,N Sb and 1≤sk≤L S jb, i.e., sk is a valid value for the kth subject variable, then
      ID 1 l=b,  ID 2 l=j,  ID 3 l=i,  ID 3+k l=sk, ​k=1,2,…,N Sb;
    • if the parameter being estimated is for the intercept then ID 2 l=ID 3 l=0;
    • if the jth variable is continuous, or binary, that is L S jb=1, then ID 3 l=0;
    • the remaining rows of the lth column of ID are set to 0.
In some situations, certain combinations of variables are never observed. In such circumstances all elements of the lth row of ID are set to -999.
11:   LDID – INTEGERInput
On entry: the first dimension of the array ID as declared in the (sub)program from which G02JDF is called.
Constraint: LDID≥3+maxj RNDM 3+ RNDM 1,j ,j , i.e., 3+ maximum number of subject variables (see G02JCF).
12:   B LB – REAL (KIND=nag_wp) arrayOutput
On exit: the parameter estimates, with the first NRF×NLSV elements of B containing the parameter estimates for the random effects, ν, and the remaining NFF elements containing the parameter estimates for the fixed effects, β. The order of these estimates are described by the ID argument.
13:   SE LB – REAL (KIND=nag_wp) arrayOutput
On exit: the standard errors of the parameter estimates given in B.
14:   CZZ LDCZZ* – REAL (KIND=nag_wp) arrayOutput
Note: the second dimension of the array CZZ must be at least NRF×NLSV (see G02JCF).
On exit: if NLSV=1, then CZZ holds the lower triangular portion of the matrix 1/ σ 2 ZT R^-1 Z + G^-1 , where R^ and G^ are the estimates of R and G respectively. If NLSV>1 then CZZ holds this matrix in compressed form, with the first NRF columns holding the part of the matrix corresponding to the first level of the overall subject variable, the next NRF columns the part corresponding to the second level of the overall subject variable etc.
15:   LDCZZ – INTEGERInput
On entry: the first dimension of the array CZZ as declared in the (sub)program from which G02JDF is called.
Constraint: LDCZZ≥NRF.
16:   CXX LDCXX* – REAL (KIND=nag_wp) arrayOutput
Note: the second dimension of the array CXX must be at least NFF (see G02JCF).
On exit: CXX holds the lower triangular portion of the matrix 1/ σ 2 XT V^-1 X , where V^ is the estimated value of V.
17:   LDCXX – INTEGERInput
On entry: the first dimension of the array CXX as declared in the (sub)program from which G02JDF is called.
Constraint: LDCXX≥NFF.
18:   CXZ LDCXZ* – REAL (KIND=nag_wp) arrayOutput
Note: the second dimension of the array CXZ must be at least NLSV×NRF (see G02JCF).
On exit: if NLSV=1, then CXZ holds the matrix 1/σ 2 XT V^-1 Z G^ , where V^ and G^ are the estimates of V and G respectively. If NLSV>1 then CXZ holds this matrix in compressed form, with the first NRF columns holding the part of the matrix corresponding to the first level of the overall subject variable, the next NRF columns the part corresponding to the second level of the overall subject variable etc.
19:   LDCXZ – INTEGERInput
On entry: the first dimension of the array CXZ as declared in the (sub)program from which G02JDF is called.
Constraint: LDCXZ≥NFF.
20:   RCOMM* – REAL (KIND=nag_wp) arrayCommunication Array
Note: the dimension of the array RCOMM must be at least LRCOMM (see G02JCF).
On entry: communication array initialized by a call to G02JCF.
21:   ICOMM* – INTEGER arrayCommunication Array
Note: the dimension of the array ICOMM must be at least LICOMM (see G02JCF).
On entry: communication array initialized by a call to G02JCF.
22:   IOPT LIOPT – INTEGER arrayInput
On entry: optional parameters passed to the optimization routine.
By default G02JDF fits the specified model using a modified Newton optimization algorithm as implemented in E04LBF. In some cases, where the calculation of the derivatives is computationally expensive it may be more efficient to use a sequential QP algorithm. The sequential QP algorithm as implemented in E04UCA can be chosen by setting IOPT 5=1. If LIOPT<5 or IOPT 5≠1 then E04LBF will be used.
Different optional parameters are available depending on the optimization routine used. In all cases, using a value of -1 will cause the default value to be used. In addition only the first LIOPT values of IOPT are used, so for example, if only the first element of IOPT needs changing and default values for all other optional parameters are sufficient LIOPT can be set to 1.
E04LBF is being used.

i

Description 		Equivalent
E04LBF
argument

Default Value
1 | Number of iterations | MAXCAL | 1000
2 | Unit number for monitoring information | n/a | As returned by X04ABF
3 | Print optional parameters (1= print) | n/a | -1 (no printing performed)
4 | Frequency that monitoring information is printed | IPRINT | -1
5 | Optimizer used | n/a | n/a
If requested, monitoring information is displayed in a similar format to that given by E04LBF.
E04UCA is being used.

i

Description 		Equivalent
E04UCA
argument

Default Value
1 | Number of iterations | Major Iteration Limit | max 50,3×NVPR
2 | Unit number for monitoring information | n/a | As returned by X04ABF
3 | Print optional parameters (1= print, otherwise no print) | List/Nolist | -1 (no printing performed)
4 | Frequency that monitoring information is printed | Major Print Level | 0
5 | Optimizer used | n/a | n/a
6 | Number of minor iterations | Minor Iteration Limit | max 50,3×NVPR
7 | Frequency that additional monitoring information is printed | Minor Print Level | 0
If LIOPT≤0 then default values are used for all optional parameters and IOPT is not referenced.
23:   LIOPT – INTEGERInput
On entry: length of the options array IOPT.
24:   ROPT LROPT – REAL (KIND=nag_wp) arrayInput
On entry: optional parameters passed to the optimization routine.
Different optional parameters are available depending on the optimization routine used. In all cases, using a value of -1.0 will cause the default value to be used. In addition only the first LROPT values of ROPT are used, so for example, if only the first element of ROPT needs changing and default values for all other optional parameters are sufficient LROPT can be set to 1.
E04LBF is being used.

i

Description 		Equivalent
E04LBF
argument

Default Value
1 | Sweep tolerance | n/a | max eps,eps×maxi zz ii
2 | Lower bound for γ* | n/a | eps/100
3 | Upper bound for γ* | n/a | 1020
4 | Accuracy of linear minimizations | ETA | 0.9
5 | Accuracy to which solution is required | XTOL | 0.0
6 | Initial distance from solution | STEPMX | 100000.0
E04UCA is being used.

i

Description 		Equivalent
E04UCA
argument

Default Value
1 | Sweep tolerance | n/a | max eps,eps×maxi zz ii
2 | Lower bound for γ* | n/a | eps/100
3 | Upper bound for γ* | n/a | 1020
4 | Line search tolerance | Line Search Tolerance | 0.9
5 | Optimality tolerance | Optimality Tolerance | eps 0.72
where eps is the machine precision returned by X02AJF and zz ii denotes the i diagonal element of ZT Z.
If LROPT≤0 then default values are used for all optional parameters and ROPT is not referenced.
25:   LROPT – INTEGERInput
On entry: length of the options array ROPT.
26:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, LVPR=value.
Constraint: LVPR≥value.
IFAIL=2
On entry, VPR value=value and NVPR=value.
Constraint: 1≤VPR i≤NVPR.
IFAIL=3
On entry, NVPR=value.
Constraint: 1≤NVPR≤value.
IFAIL=4
On entry, GAMMA value=value.
Constraint: GAMMA 1=-1.0 or GAMMA i≥0.0.
IFAIL=9
On entry, LB=value.
Constraint: LB≥value.
IFAIL=11
On entry, LDID=value.
Constraint: LDID≥value.
IFAIL=15
On entry, LDCZZ=value.
Constraint: LDCZZ≥value.
IFAIL=17
On entry, LDCXX=value.
Constraint: LDCXX≥value.
IFAIL=19
On entry, LDCXZ= value.
Constraint: LDCXZ≥value.
IFAIL=21
On entry, ICOMM has not been initialized correctly.
IFAIL=32
On entry, at least one value of i, for i=1,2,…,NVPR, does not appear in VPR.
IFAIL=101
Optimal solution found, but requested accuracy not achieved.
IFAIL=102
Too many major iterations.
IFAIL=103
Current point cannot be improved upon.
IFAIL=104
At least one negative estimate for GAMMA was obtained. All negative estimates have been set to zero.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

Not applicable.

8 Parallelism and Performance

G02JDF is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
G02JDF makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The argument VPR gives the mapping between the random variables and the variance components. In most cases VPR i=i, for i=1,2,…,∑i RNDM 1,i+RNDM 2,i. However, in some cases it might be necessary to associate more than one random variable with a single variance component, for example, when the columns of DAT hold dummy variables.
Consider a dataset with three variables:
DAT= 113.6 214.5 311.1 128.3 227.2 326.1
where the first column corresponds to a categorical variable with three levels, the next to a categorical variable with two levels and the last column to a continuous variable. So in a call to G02JCF
LEVELS=321
also assume a model with no fixed effects, no random intercept, no nesting and all three variables being included as random effects, then
FIXED=00; RNDM=30123 T.
Each of the three columns in DAT therefore correspond to a single variable and hence there are three variance components, one for each random variable included in the model, so
VPR=123.
This is the recommended way of supplying the data to G02JDF, however it is possible to reformat the above dataset by replacing each of the categorical variables with a series of dummy variables, one for each level. The dataset then becomes
DAT= 100103.6 010104.5 001101.1 100018.3 010017.2 001016.1
where each column only has one level
LEVELS= 111111 .
Again a model with no fixed effects, no random intercept, no nesting and all variables being included as random effects is required, so
FIXED=00 ; RNDM= 60123456 T .
With the data entered in this manner, the first three columns of DAT correspond to a single variable (the first column of the original dataset) as do the next two columns (the second column of the original dataset). Therefore VPR must reflect this
VPR= 111223 .
In most situations it is more efficient to supply the data to G02JCF in terms of categorical variables rather than transform them into dummy variables.

10 Example

This example fits a random effects model with three levels of nesting to a simulated dataset with 90 observations and 12 variables.

10.1 Program Text

Program Text (g02jdfe.f90)

10.2 Program Data

Program Data (g02jdfe.d)

10.3 Program Results

Program Results (g02jdfe.r)

G02 Chapter Contents
G02 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


G02JEF : NAG Library, Mark 26

G02 Chapter Contents
G02 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

G02JEF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

G02JEF fits a multi-level linear mixed effects regression model using maximum likelihood (ML). Prior to calling G02JEF the initialization routine G02JCF must be called.

2 Specification

SUBROUTINE G02JEF ( LVPR, VPR, NVPR, GAMMA, EFFN, RNKX, NCOV, LNLIKE, LB, ID, LDID, B, SE, CZZ, LDCZZ, CXX, LDCXX, CXZ, LDCXZ, RCOMM, ICOMM, IOPT, LIOPT, ROPT, LROPT, IFAIL)
INTEGER | LVPR, VPR(LVPR), NVPR, EFFN, RNKX, NCOV, LB, ID(LDID,LB), LDID, LDCZZ, LDCXX, LDCXZ, ICOMM(*), IOPT(LIOPT), LIOPT, LROPT, IFAIL
REAL (KIND=nag_wp) | GAMMA(NVPR+1), LNLIKE, B(LB), SE(LB), CZZ(LDCZZ,*), CXX(LDCXX,*), CXZ(LDCXZ,*), RCOMM(*), ROPT(LROPT)

3 Description

G02JEF fits a model of the form:
y=Xβ+Zν+ε
where | y is a vector of n observations on the dependent variable,
 | X is a known n by p design matrix for the fixed independent variables,
 | β is a vector of length p of unknown fixed effects,
 | Z is a known n by q design matrix for the random independent variables,
 | ν is a vector of length q of unknown random effects,
and | ε is a vector of length n of unknown random errors.
Both ν and ε are assumed to have a Gaussian distribution with expectation zero and variance/covariance matrix defined by
Var ν ε = G 0 0 R
where R= σ R 2 I , I is the n×n identity matrix and G is a diagonal matrix. It is assumed that the random variables, Z , can be subdivided into g ≤ q groups with each group being identically distributed with expectation zero and variance σi 2 . The diagonal elements of matrix G therefore take one of the values σi 2 : i=1,2,…,g , depending on which group the associated random variable belongs to.
The model therefore contains three sets of unknowns: the fixed effects β , the random effects ν and a vector of g+1 variance components γ , where γ = σ1 2,σ2 2,…, σ g-1 2 ,σg2,σR2 . Rather than working directly with γ , G02JEF uses an iterative process to estimate γ* = σ1 2 / σR2 , σ2 2 / σR2 ,…, σ g-1 2 / σR2 , σg2 / σR2 ,1 . Due to the iterative nature of the estimation a set of initial values, γ 0 , for γ* is required. G02JEF allows these initial values either to be supplied by you or calculated from the data using the minimum variance quadratic unbiased estimators (MIVQUE0) suggested by Rao (1972).
G02JEF fits the model by maximizing the log-likelihood function:
-2 l R = log V + n log rT V-1 r + log 2 π / n
where
V = ZG ZT + R,   r=y-Xb   and   b = XT V-1 X -1 XT V-1 y .
Once the final estimates for γ * have been obtained, the value of σR 2 is given by
σR 2 = rT V-1 r / n - p .
Case weights, Wc , can be incorporated into the model by replacing XT X and ZT Z with XT Wc X and ZT Wc Z respectively, for a diagonal weight matrix Wc .
The log-likelihood, lR, is calculated using the sweep algorithm detailed in Wolfinger et al. (1994).

4 References

Goodnight J H (1979) A tutorial on the SWEEP operator The American Statistician 33(3) 149–158
Harville D A (1977) Maximum likelihood approaches to variance component estimation and to related problems JASA 72 320–340
Rao C R (1972) Estimation of variance and covariance components in a linear model J. Am. Stat. Assoc. 67 112–115
Stroup W W (1989) Predictable functions and prediction space in the mixed model procedure Applications of Mixed Models in Agriculture and Related Disciplines Southern Cooperative Series Bulletin No. 343 39–48
Wolfinger R, Tobias R and Sall J (1994) Computing Gaussian likelihoods and their derivatives for general linear mixed models SIAM Sci. Statist. Comput. 15 1294–1310

5 Arguments

Note: prior to calling G02JEF the initialization routine G02JCF must be called, therefore this documention should be read in conjunction with the document for G02JCF.
In particular some argument names and conventions described in that document are also relevant here, but their definition has not been repeated. Specifically, RNDM, WEIGHT, N, NFF, NRF, NLSV, LEVELS, FIXED, DAT, LICOMM and LRCOMM should be interpreted identically in both routines.
1:   LVPR – INTEGERInput
On entry: the sum of the number of random parameters and the random intercept flags specified in the call to G02JCF.
Constraint: LVPR=∑i RNDM 1,i+RNDM 2,i.
2:   VPR LVPR – INTEGER arrayInput
On entry: a vector of flags indicating the mapping between the random variables specified in RNDM and the variance components, σi 2. See Section 9 for more details.
Constraint: 1≤VPR i≤NVPR, for i=1,2,…,LVPR.
3:   NVPR – INTEGERInput
On entry: g, the number of variance components being estimated (excluding the overall variance, σR 2).
Constraint: 1≤NVPR≤LVPR .
4:   GAMMA NVPR+1 – REAL (KIND=nag_wp) arrayInput/Output
On entry: holds the initial values of the variance components, γ 0 , with GAMMA i the initial value for σi 2/σR 2, for i=1,2,…,NVPR.
If GAMMA 1=-1.0, the remaining elements of GAMMA are ignored and the initial values for the variance components are estimated from the data using MIVQUE0.
On exit: GAMMA i, for i=1,2,…,NVPR, holds the final estimate of σi 2 and GAMMA NVPR+1 holds the final estimate for σR 2.
Constraint: GAMMA 1=-1.0 ​ or ​ GAMMA i≥0.0, for i=1,2,…,g.
5:   EFFN – INTEGEROutput
On exit: effective number of observations. If there are no weights (i.e., WEIGHT='U'), or all weights are nonzero, then EFFN=N.
6:   RNKX – INTEGEROutput
On exit: the rank of the design matrix, X, for the fixed effects.
7:   NCOV – INTEGEROutput
On exit: number of variance components not estimated to be zero. If none of the variance components are estimated to be zero, then NCOV=NVPR.
8:   LNLIKE – REAL (KIND=nag_wp)Output
On exit: - 2 lR γ^ where lR is the log of the maximum likelihood calculated at γ^ , the estimated variance components returned in GAMMA.
9:   LB – INTEGERInput
On entry: the dimension of the arrays B and SE and the second dimension of the array ID as declared in the (sub)program from which G02JEF is called.
Constraint: LB≥NFF+NRF×NLSV.
10:   ID LDIDLB – INTEGER arrayOutput
On exit: an array describing the parameter estimates returned in B. The first NLSV×NRF columns of ID describe the parameter estimates for the random effects and the last NFF columns the parameter estimates for the fixed effects.
The example program for this routine includes a demonstration of decoding the parameter estimates given in B using information from ID.
For fixed effects:
  • for l=NRF×NLSV+1 ,…, NRF×NLSV+NFF
    • if B l contains the parameter estimate for the intercept then
      ID 1 l = ID 2 l = ID 3 l = 0 ;
    • if B l contains the parameter estimate for the ith level of the jth fixed variable, that is the vector of values held in the kth column of DAT when FIXED j+2=k then
      ID 1 l=0,  ID 2 l=j,  ID 3 l=i;
    • if the jth variable is continuous or binary, that is LEVELS FIXED j+2=1, then ID 3 l=0;
    • any remaining rows of the lth column of ID are set to 0.
For random effects:
  • let
    • N Rb denote the number of random variables in the bth random statement, that is N Rb=RNDM 1,b;
    • R jb denote the jth random variable from the bth random statement, that is the vector of values held in the kth column of DAT when RNDM 2+j,b=k;
    • N Sb denote the number of subject variables in the bth random statement, that is N Sb=RNDM 3+N Rb,b;
    • S jb denote the jth subject variable from the bth random statement, that is the vector of values held in the kth column of DAT when RNDM 3+N Rb+j,b=k;
    • L S jb denote the number of levels for S jb, that is L S jb=LEVELS RNDM 3+N Rb+j,b;
  • then
    • for l=1,2,… NRF×NLSV, if B l contains the parameter estimate for the ith level of R jb when S kb=sk, for k=1,2,…,N Sb and 1≤sk≤L S jb, i.e., sk is a valid value for the kth subject variable, then
      ID 1 l=b,  ID 2 l=j,  ID 3 l=i,  ID 3+k l=sk, ​k=1,2,…,N Sb;
    • if the parameter being estimated is for the intercept then ID 2 l=ID 3 l=0;
    • if the jth variable is continuous, or binary, that is L S jb=1, then ID 3 l=0;
    • the remaining rows of the lth column of ID are set to 0.
In some situations, certain combinations of variables are never observed. In such circumstances all elements of the lth row of ID are set to -999.
11:   LDID – INTEGERInput
On entry: the first dimension of the array ID as declared in the (sub)program from which G02JEF is called.
Constraint: LDID≥3+maxj RNDM 3+ RNDM 1,j ,j , i.e., 3+ maximum number of subject variables (see G02JCF).
12:   B LB – REAL (KIND=nag_wp) arrayOutput
On exit: the parameter estimates, with the first NRF×NLSV elements of B containing the parameter estimates for the random effects, ν, and the remaining NFF elements containing the parameter estimates for the fixed effects, β. The order of these estimates are described by the ID argument.
13:   SE LB – REAL (KIND=nag_wp) arrayOutput
On exit: the standard errors of the parameter estimates given in B.
14:   CZZ LDCZZ* – REAL (KIND=nag_wp) arrayOutput
Note: the second dimension of the array CZZ must be at least NRF×NLSV (see G02JCF).
On exit: if NLSV=1, then CZZ holds the lower triangular portion of the matrix 1/ σ 2 ZT R^-1 Z + G^-1 , where R^ and G^ are the estimates of R and G respectively. If NLSV>1 then CZZ holds this matrix in compressed form, with the first NRF columns holding the part of the matrix corresponding to the first level of the overall subject variable, the next NRF columns the part corresponding to the second level of the overall subject variable etc.
15:   LDCZZ – INTEGERInput
On entry: the first dimension of the array CZZ as declared in the (sub)program from which G02JEF is called.
Constraint: LDCZZ≥NRF.
16:   CXX LDCXX* – REAL (KIND=nag_wp) arrayOutput
Note: the second dimension of the array CXX must be at least NFF (see G02JCF).
On exit: CXX holds the lower triangular portion of the matrix 1/ σ 2 XT V^-1 X , where V^ is the estimated value of V.
17:   LDCXX – INTEGERInput
On entry: the first dimension of the array CXX as declared in the (sub)program from which G02JEF is called.
Constraint: LDCXX≥NFF.
18:   CXZ LDCXZ* – REAL (KIND=nag_wp) arrayOutput
Note: the second dimension of the array CXZ must be at least NLSV×NRF (see G02JCF).
On exit: if NLSV=1, then CXZ holds the matrix 1/σ 2 XT V^-1 Z G^ , where V^ and G^ are the estimates of V and G respectively. If NLSV>1 then CXZ holds this matrix in compressed form, with the first NRF columns holding the part of the matrix corresponding to the first level of the overall subject variable, the next NRF columns the part corresponding to the second level of the overall subject variable etc.
19:   LDCXZ – INTEGERInput
On entry: the first dimension of the array CXZ as declared in the (sub)program from which G02JEF is called.
Constraint: LDCXZ≥NFF.
20:   RCOMM* – REAL (KIND=nag_wp) arrayCommunication Array
Note: the dimension of the array RCOMM must be at least LRCOMM (see G02JCF).
On entry: communication array initialized by a call to G02JCF.
21:   ICOMM* – INTEGER arrayCommunication Array
Note: the dimension of the array ICOMM must be at least LICOMM (see G02JCF).
On entry: communication array initialized by a call to G02JCF.
22:   IOPT LIOPT – INTEGER arrayInput
On entry: optional parameters passed to the optimization routine.
By default G02JEF fits the specified model using a modified Newton optimization algorithm as implemented in E04LBF. In some cases, where the calculation of the derivatives is computationally expensive it may be more efficient to use a sequential QP algorithm. The sequential QP algorithm as implemented in E04UCA can be chosen by setting IOPT 5=1. If LIOPT<5 or IOPT 5≠1 then E04LBF will be used.
Different optional parameters are available depending on the optimization routine used. In all cases, using a value of -1 will cause the default value to be used. In addition only the first LIOPT values of IOPT are used, so for example, if only the first element of IOPT needs changing and default values for all other optional parameters are sufficient LIOPT can be set to 1.
E04LBF is being used.

i

Description 		Equivalent
E04LBF
argument

Default Value
1 | Number of iterations | MAXCAL | 1000
2 | Unit number for monitoring information | n/a | As returned by X04ABF
3 | Print optional parameters (1= print) | n/a | -1 (no printing performed)
4 | Frequency that monitoring information is printed | IPRINT | -1
5 | Optimizer used | n/a | n/a
If requested, monitoring information is displayed in a similar format to that given by E04LBF.
E04UCA is being used.

i

Description 		Equivalent
E04UCA
argument

Default Value
1 | Number of iterations | Major Iteration Limit | max 50,3×NVPR
2 | Unit number for monitoring information | n/a | As returned by X04ABF
3 | Print optional parameters (1= print, otherwise no print) | List/Nolist | -1 (no printing performed)
4 | Frequency that monitoring information is printed | Major Print Level | 0
5 | Optimizer used | n/a | n/a
6 | Number of minor iterations | Minor Iteration Limit | max 50,3×NVPR
7 | Frequency that additional monitoring information is printed | Minor Print Level | 0
If LIOPT≤0 then default values are used for all optional parameters and IOPT is not referenced.
23:   LIOPT – INTEGERInput
On entry: length of the options array IOPT.
24:   ROPT LROPT – REAL (KIND=nag_wp) arrayInput
On entry: optional parameters passed to the optimization routine.
Different optional parameters are available depending on the optimization routine used. In all cases, using a value of -1.0 will cause the default value to be used. In addition only the first LROPT values of ROPT are used, so for example, if only the first element of ROPT needs changing and default values for all other optional parameters are sufficient LROPT can be set to 1.
E04LBF is being used.

i

Description 		Equivalent
E04LBF
argument

Default Value
1 | Sweep tolerance | n/a | max eps,eps×maxi zz ii
2 | Lower bound for γ* | n/a | eps/100
3 | Upper bound for γ* | n/a | 1020
4 | Accuracy of linear minimizations | ETA | 0.9
5 | Accuracy to which solution is required | XTOL | 0.0
6 | Initial distance from solution | STEPMX | 100000.0
E04UCA is being used.

i

Description 		Equivalent
E04UCA
argument

Default Value
1 | Sweep tolerance | n/a | max eps,eps×maxi zz ii
2 | Lower bound for γ* | n/a | eps/100
3 | Upper bound for γ* | n/a | 1020
4 | Line search tolerance | Line Search Tolerance | 0.9
5 | Optimality tolerance | Optimality Tolerance | eps 0.72
where eps is the machine precision returned by X02AJF and zz ii denotes the i diagonal element of ZT Z.
If LROPT≤0 then default values are used for all optional parameters and ROPT is not referenced.
25:   LROPT – INTEGERInput
On entry: length of the options array ROPT.
26:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, LVPR=value.
Constraint: LVPR≥value.
IFAIL=2
On entry, VPR value=value and NVPR=value.
Constraint: 1≤VPR i≤NVPR.
IFAIL=3
On entry, NVPR=value.
Constraint: 1≤NVPR≤value.
IFAIL=4
On entry, GAMMA value=value.
Constraint: GAMMA 1=-1.0 or GAMMA i≥0.0.
IFAIL=9
On entry, LB=value.
Constraint: LB≥value.
IFAIL=11
On entry, LDID=value.
Constraint: LDID≥value.
IFAIL=15
On entry, LDCZZ=value.
Constraint: LDCZZ≥value.
IFAIL=17
On entry, LDCXX=value.
Constraint: LDCXX≥value.
IFAIL=19
On entry, LDCXZ= value.
Constraint: LDCXZ≥value.
IFAIL=21
On entry, ICOMM has not been initialized correctly.
IFAIL=32
On entry, at least one value of i, for i=1,2,…,NVPR, does not appear in VPR.
IFAIL=101
Optimal solution found, but requested accuracy not achieved.
IFAIL=102
Too many major iterations.
IFAIL=103
Current point cannot be improved upon.
IFAIL=104
At least one negative estimate for GAMMA was obtained. All negative estimates have been set to zero.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

Not applicable.

8 Parallelism and Performance

G02JEF is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
G02JEF makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The argument VPR gives the mapping between the random variables and the variance components. In most cases VPR i=i, for i=1,2,…,∑i RNDM 1,i+RNDM 2,i. However, in some cases it might be necessary to associate more than one random variable with a single variance component, for example, when the columns of DAT hold dummy variables.
Consider a dataset with three variables:
DAT= 113.6 214.5 311.1 128.3 227.2 326.1
where the first column corresponds to a categorical variable with three levels, the next to a categorical variable with two levels and the last column to a continuous variable. So in a call to G02JCF
LEVELS=321
also assume a model with no fixed effects, no random intercept, no nesting and all three variables being included as random effects, then
FIXED=00; RNDM=30123 T.
Each of the three columns in DAT therefore correspond to a single variable and hence there are three variance components, one for each random variable included in the model, so
VPR=123.
This is the recommended way of supplying the data to G02JEF, however it is possible to reformat the above dataset by replacing each of the categorical variables with a series of dummy variables, one for each level. The dataset then becomes
DAT= 100103.6 010104.5 001101.1 100018.3 010017.2 001016.1
where each column only has one level
LEVELS= 111111 .
Again a model with no fixed effects, no random intercept, no nesting and all variables being included as random effects is required, so
FIXED=00 ; RNDM= 60123456 T .
With the data entered in this manner, the first three columns of DAT correspond to a single variable (the first column of the original dataset) as do the next two columns (the second column of the original dataset). Therefore VPR must reflect this
VPR= 111223 .
In most situations it is more efficient to supply the data to G02JCF in terms of categorical variables rather than transform them into dummy variables.

10 Example

This example fits a random effects model with three levels of nesting to a simulated dataset with 90 observations and 12 variables.

10.1 Program Text

Program Text (g02jefe.f90)

10.2 Program Data

Program Data (g02jefe.d)

10.3 Program Results

Program Results (g02jefe.r)

G02 Chapter Contents
G02 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


G02KAF : NAG Library, Mark 26

G02 Chapter Contents
G02 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

G02KAF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

G02KAF calculates a ridge regression, optimizing the ridge parameter according to one of four prediction error criteria.

2 Specification

SUBROUTINE G02KAF ( N, M, X, LDX, ISX, IP, TAU, Y, H, OPT, NITER, TOL, NEP, ORIG, B, VIF, RES, RSS, DF, OPTLOO, PERR, IFAIL)
INTEGER | N, M, LDX, ISX(M), IP, OPT, NITER, ORIG, DF, OPTLOO, IFAIL
REAL (KIND=nag_wp) | X(LDX,M), TAU, Y(N), H, TOL, NEP, B(IP+1), VIF(IP), RES(N), RSS, PERR(5)

3 Description

A linear model has the form:
y = c+Xβ+ε ,
where
  • y is an n by 1 matrix of values of a dependent variable;
  • c is a scalar intercept term;
  • X is an n by m matrix of values of independent variables;
  • β is an m by 1 matrix of unknown values of parameters;
  • ε is an n by 1 matrix of unknown random errors such that variance of ε=σ 2 I.
Let X~ be the mean-centred X and y~ the mean-centred y. Furthermore, X~ is scaled such that the diagonal elements of the cross product matrix X~T X~ are one. The linear model now takes the form:
y~ = X~ β~ + ε .
Ridge regression estimates the parameters β~ in a penalised least squares sense by finding the b~ that minimizes
X~ b~ - y~ 2 + h b~ 2 ,   h>0 ,
where · denotes the ℓ 2-norm and h is a scalar regularization or ridge parameter. For a given value of h, the parameter estimates b~ are found by evaluating
b~ = X~T X~+hI -1 X~T y~ .
Note that if h=0 the ridge regression solution is equivalent to the ordinary least squares solution.
Rather than calculate the inverse of (X~T X~+hI) directly, G02KAF uses the singular value decomposition (SVD) of X~. After decomposing X~ into UD VT where U and V are orthogonal matrices and D is a diagonal matrix, the parameter estimates become
b~ = V DT D+hI -1 D UT y~ .
A consequence of introducing the ridge parameter is that the effective number of parameters, γ, in the model is given by the sum of diagonal elements of
DT D DT D+hI-1 ,
see Moody (1992) for details.
Any multi-collinearity in the design matrix X may be highlighted by calculating the variance inflation factors for the fitted model. The jth variance inflation factor, vj, is a scaled version of the multiple correlation coefficient between independent variable j and the other independent variables, Rj, and is given by
vj = 1 1-Rj ,   j=1,2,…,m .
The m variance inflation factors are calculated as the diagonal elements of the matrix:
X~T X~+hI -1 X~T X~ X~T X~+hI -1 ,
which, using the SVD of X~, is equivalent to the diagonal elements of the matrix:
V DT D+hI -1 DT D DT D+hI -1 VT .
Although parameter estimates b~ are calculated by using X~, it is usual to report the parameter estimates b associated with X. These are calculated from b~, and the means and scalings of X. Optionally, either b~ or b may be calculated.
The method can adopt one of four criteria to minimize while calculating a suitable value for h:
(a) Generalized cross-validation (GCV):
ns n-γ 2 ;
(b) Unbiased estimate of variance (UEV):
s n-γ ;
(c) Future prediction error (FPE):
1 n s+ 2 γs n-γ ;
(d) Bayesian information criterion (BIC):
1 n s + log n γs n-γ ;
where s is the sum of squares of residuals. However, the function returns all four of the above prediction errors regardless of the one selected to minimize the ridge parameter, h. Furthermore, the function will optionally return the leave-one-out cross-validation (LOOCV) prediction error.

4 References

Hastie T, Tibshirani R and Friedman J (2003) The Elements of Statistical Learning: Data Mining, Inference and Prediction Springer Series in Statistics
Moody J.E. (1992) The effective number of parameters: An analysis of generalisation and regularisation in nonlinear learning systems In: Neural Information Processing Systems (eds J E Moody, S J Hanson, and R P Lippmann) 4 847–854 Morgan Kaufmann San Mateo CA

5 Arguments

1:   N – INTEGERInput
On entry: n, the number of observations.
Constraint: N>1.
2:   M – INTEGERInput
On entry: the number of independent variables available in the data matrix X.
Constraint: M≤N.
3:   X LDXM – REAL (KIND=nag_wp) arrayInput
On entry: the values of independent variables in the data matrix X.
4:   LDX – INTEGERInput
On entry: the first dimension of the array X as declared in the (sub)program from which G02KAF is called.
Constraint: LDX≥N.
5:   ISX M – INTEGER arrayInput
On entry: indicates which m independent variables are included in the model.
ISX j=1
The jth variable in X will be included in the model.
ISX j=0
Variable j is excluded.
Constraint: ISX j=0 ​ or ​ 1, for j=1,2,…,M.
6:   IP – INTEGERInput
On entry: m, the number of independent variables in the model.
Constraints:
  • 1≤IP≤M;
  • Exactly IP elements of ISX must be equal to 1.
7:   TAU – REAL (KIND=nag_wp)Input
On entry: singular values less than TAU of the SVD of the data matrix X will be set equal to zero.
Suggested value: TAU=0.0.
Constraint: TAU≥0.0.
8:   Y N – REAL (KIND=nag_wp) arrayInput
On entry: the n values of the dependent variable y.
9:   H – REAL (KIND=nag_wp)Input/Output
On entry: an initial value for the ridge regression parameter h; used as a starting point for the optimization.
Constraint: H>0.0.
On exit: H is the optimized value of the ridge regression parameter h.
10:   OPT – INTEGERInput
On entry: the measure of prediction error used to optimize the ridge regression parameter h. The value of OPT must be set equal to one of:
OPT=1
Generalized cross-validation (GCV);
OPT=2
Unbiased estimate of variance (UEV)
OPT=3
Future prediction error (FPE)
OPT=4
Bayesian information criteron (BIC).
Constraint: OPT=1, 2, 3 or 4.
11:   NITER – INTEGERInput/Output
On entry: the maximum number of iterations allowed to optimize the ridge regression parameter h.
Constraint: NITER≥1.
On exit: the number of iterations used to optimize the ridge regression parameter h within TOL.
12:   TOL – REAL (KIND=nag_wp)Input
On entry: iterations of the ridge regression parameter h will halt when consecutive values of h lie within TOL.
Constraint: TOL>0.0.
13:   NEP – REAL (KIND=nag_wp)Output
On exit: the number of effective parameters, γ, in the model.
14:   ORIG – INTEGERInput
On entry: if ORIG=1, the parameter estimates b are calculated for the original data; otherwise ORIG=2 and the parameter estimates b~ are calculated for the standardized data.
Constraint: ORIG=1 or 2.
15:   B IP+1 – REAL (KIND=nag_wp) arrayOutput
On exit: contains the intercept and parameter estimates for the fitted ridge regression model in the order indicated by ISX. The first element of B contains the estimate for the intercept; B j+1 contains the parameter estimate for the jth independent variable in the model, for j=1,2,…,IP.
16:   VIF IP – REAL (KIND=nag_wp) arrayOutput
On exit: the variance inflation factors in the order indicated by ISX. For the jth independent variable in the model, VIF j is the value of vj, for j=1,2,…,IP.
17:   RES N – REAL (KIND=nag_wp) arrayOutput
On exit: RES i is the value of the ith residual for the fitted ridge regression model, for i=1,2,…,N.
18:   RSS – REAL (KIND=nag_wp)Output
On exit: the sum of squares of residual values.
19:   DF – INTEGEROutput
On exit: the degrees of freedom for the residual sum of squares RSS.
20:   OPTLOO – INTEGERInput
On entry: if OPTLOO=2, the leave-one-out cross-validation estimate of prediction error is calculated; otherwise no such estimate is calculated and OPTLOO=1.
Constraint: OPTLOO=1 or 2.
21:   PERR 5 – REAL (KIND=nag_wp) arrayOutput
On exit: the first four elements contain, in this order, the measures of prediction error: GCV, UEV, FPE and BIC.
If OPTLOO=2, PERR 5 is the LOOCV estimate of prediction error; otherwise PERR 5 is not referenced.
22:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, H=value.
Constraint: H>0.0.
On entry, N=value.
Constraint: N>1.
On entry, NITER=value.
Constraint: NITER≥1.
On entry, OPT=value.
Constraint: OPT=1, 2, 3 or 4.
On entry, OPTLOO=value.
Constraint: OPTLOO=1 or 2.
On entry, ORIG=value.
Constraint: ORIG=1 or 2.
On entry, TAU=value.
Constraint: TAU≥0.0.
On entry, TOL=value.
Constraint: TOL>0.0.
IFAIL=2
On entry, IP=value; M=value.
Constraint: 1≤IP≤M.
On entry, IP=value.
Constraint: sum ISX=IP.
On entry, ISX value=value.
Constraint: ISX j=0 or 1.
On entry, LDX=value; N=value.
Constraint: LDX≥N.
On entry, M=value and N=value.
Constraint: M≤N.
IFAIL=3
SVD failed to converge.
IFAIL=-1
Maximum number of iterations used.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

Not applicable.

8 Parallelism and Performance

G02KAF is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
G02KAF makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

G02KAF allocates internally max 5 × N-1 , 2×IP×IP +N+3 × IP+N elements of double precision storage.

10 Example

This example reads in data from an experiment to model body fat, and a ridge regression is calculated that optimizes GCV prediction error.

10.1 Program Text

Program Text (g02kafe.f90)

10.2 Program Data

Program Data (g02kafe.d)

10.3 Program Results

Program Results (g02kafe.r)

G02 Chapter Contents
G02 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


G02KBF : NAG Library, Mark 26

G02 Chapter Contents
G02 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

G02KBF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

G02KBF calculates a ridge regression, with ridge parameters supplied by you.

2 Specification

SUBROUTINE G02KBF ( N, M, X, LDX, ISX, IP, Y, LH, H, NEP, WANTB, B, LDB, WANTVF, VF, LDVF, LPEC, PEC, PE, LDPE, IFAIL)
INTEGER | N, M, LDX, ISX(M), IP, LH, WANTB, LDB, WANTVF, LDVF, LPEC, LDPE, IFAIL
REAL (KIND=nag_wp) | X(LDX,M), Y(N), H(LH), NEP(LH), B(LDB,*), VF(LDVF,*), PE(LDPE,*)
CHARACTER(1) | PEC(LPEC)

3 Description

A linear model has the form:
y = c+Xβ+ε ,
where
  • y is an n by 1 matrix of values of a dependent variable;
  • c is a scalar intercept term;
  • X is an n by m matrix of values of independent variables;
  • β is a m by 1 matrix of unknown values of parameters;
  • ε is an n by 1 matrix of unknown random errors such that variance of ε=σ 2 I.
Let X~ be the mean-centred X and y~ the mean-centred y. Furthermore, X~ is scaled such that the diagonal elements of the cross product matrix X~T X~ are one. The linear model now takes the form:
y~ = X~ β~ + ε .
Ridge regression estimates the parameters β~ in a penalised least squares sense by finding the b~ that minimizes
X~ b~ - y~ 2 + h b~ 2 , h>0 ,
where · denotes the ℓ 2-norm and h is a scalar regularization or ridge parameter. For a given value of h, the parameters estimates b~ are found by evaluating
b~ = X~T X~+hI -1 X~T y~ .
Note that if h=0 the ridge regression solution is equivalent to the ordinary least squares solution.
Rather than calculate the inverse of (X~T X~+hI) directly, G02KBF uses the singular value decomposition (SVD) of X~. After decomposing X~ into UD VT where U and V are orthogonal matrices and D is a diagonal matrix, the parameter estimates become
b~ = V DT D+hI -1 D UT y~ .
A consequence of introducing the ridge parameter is that the effective number of parameters, γ, in the model is given by the sum of diagonal elements of
DT D DT D+hI -1 ,
see Moody (1992) for details.
Any multi-collinearity in the design matrix X may be highlighted by calculating the variance inflation factors for the fitted model. The jth variance inflation factor, vj, is a scaled version of the multiple correlation coefficient between independent variable j and the other independent variables, Rj, and is given by
vj = 1 1-Rj , j=1,2,…,m .
The m variance inflation factors are calculated as the diagonal elements of the matrix:
X~T X~+hI -1 X~T X~ X~T X~+hI-1 ,
which, using the SVD of X~, is equivalent to the diagonal elements of the matrix:
V DT D+hI -1 DT D DT D+hI -1 VT .
Given a value of h, any or all of the following prediction criteria are available:
(a) Generalized cross-validation (GCV):
ns n-γ 2 ;
(b) Unbiased estimate of variance (UEV):
s n-γ ;
(c) Future prediction error (FPE):
1 n s+ 2 γs n-γ ;
(d) Bayesian information criterion (BIC):
1 n s+ log n γs n-γ ;
(e) Leave-one-out cross-validation (LOOCV),
where s is the sum of squares of residuals.
Although parameter estimates b~ are calculated by using X~, it is usual to report the parameter estimates b associated with X. These are calculated from b~, and the means and scalings of X. Optionally, either b~ or b may be calculated.

4 References

Hastie T, Tibshirani R and Friedman J (2003) The Elements of Statistical Learning: Data Mining, Inference and Prediction Springer Series in Statistics
Moody J.E. (1992) The effective number of parameters: An analysis of generalisation and regularisation in nonlinear learning systems In: Neural Information Processing Systems (eds J E Moody, S J Hanson, and R P Lippmann) 4 847–854 Morgan Kaufmann San Mateo CA

5 Arguments

1:   N – INTEGERInput
On entry: n, the number of observations.
Constraint: N≥1.
2:   M – INTEGERInput
On entry: the number of independent variables available in the data matrix X.
Constraint: M≤N.
3:   X LDXM – REAL (KIND=nag_wp) arrayInput
On entry: the values of independent variables in the data matrix X.
4:   LDX – INTEGERInput
On entry: the first dimension of the array X as declared in the (sub)program from which G02KBF is called.
Constraint: LDX≥N.
5:   ISX M – INTEGER arrayInput
On entry: indicates which m independent variables are included in the model.
ISX j=1
The jth variable in X will be included in the model.
ISX j=0
Variable j is excluded.
Constraint: ISX j=0 ​ or ​ 1, for j=1,2,…,M.
6:   IP – INTEGERInput
On entry: m, the number of independent variables in the model.
Constraints:
  • 1≤IP≤M;
  • Exactly IP elements of ISX must be equal to 1.
7:   Y N – REAL (KIND=nag_wp) arrayInput
On entry: the n values of the dependent variable y.
8:   LH – INTEGERInput
On entry: the number of supplied ridge parameters.
Constraint: LH>0.
9:   H LH – REAL (KIND=nag_wp) arrayInput
On entry: H j is the value of the jth ridge parameter h.
Constraint: H j≥0.0, for j=1,2,…,LH.
10:   NEP LH – REAL (KIND=nag_wp) arrayOutput
On exit: NEP j is the number of effective parameters, γ, in the jth model, for j=1,2,…,LH.
11:   WANTB – INTEGERInput
On entry: defines the options for parameter estimates.
WANTB=0
Parameter estimates are not calculated and B is not referenced.
WANTB=1
Parameter estimates b are calculated for the original data.
WANTB=2
Parameter estimates b~ are calculated for the standardized data.
Constraint: WANTB=0, 1 or 2.
12:   B LDB* – REAL (KIND=nag_wp) arrayOutput
Note: the second dimension of the array B must be at least LH if WANTB≠0, and at least 1 otherwise.
On exit: if WANTB≠0, B contains the intercept and parameter estimates for the fitted ridge regression model in the order indicated by ISX. B 1 j, for j=1,2,…,LH, contains the estimate for the intercept; B i+1 j contains the parameter estimate for the ith independent variable in the model fitted with ridge parameter H j, for i=1,2,…,IP.
13:   LDB – INTEGERInput
On entry: the first dimension of the array B as declared in the (sub)program from which G02KBF is called.
Constraints:
  • if WANTB≠0, LDB≥IP+1;
  • otherwise LDB≥1.
14:   WANTVF – INTEGERInput
On entry: defines the options for variance inflation factors.
WANTVF=0
Variance inflation factors are not calculated and the array VF is not referenced.
WANTVF=1
Variance inflation factors are calculated.
Constraints:
  • WANTVF=0 or 1;
  • if WANTB=0, WANTVF=1.
15:   VF LDVF* – REAL (KIND=nag_wp) arrayOutput
Note: the second dimension of the array VF must be at least LH if WANTVF≠0, and at least 1 otherwise.
On exit: if WANTVF=1, the variance inflation factors. For the ith independent variable in a model fitted with ridge parameter H j, VF ij is the value of vi, for i=1,2,…,IP.
16:   LDVF – INTEGERInput
On entry: the first dimension of the array VF as declared in the (sub)program from which G02KBF is called.
Constraints:
  • if WANTVF≠0, LDVF≥IP;
  • otherwise LDVF≥1.
17:   LPEC – INTEGERInput
On entry: the number of prediction error statistics to return; set LPEC≤0 for no prediction error estimates.
18:   PEC LPEC – CHARACTER(1) arrayInput
On entry: if LPEC>0, PEC j defines the jth prediction error, for j=1,2,…,LPEC; otherwise PEC is not referenced.
PEC j='B'
Bayesian information criterion (BIC).
PEC j='F'
Future prediction error (FPE).
PEC j='G'
Generalized cross-validation (GCV).
PEC j='L'
Leave-one-out cross-validation (LOOCV).
PEC j='U'
Unbiased estimate of variance (UEV).
Constraint: if LPEC>0, PEC j='B', 'F', 'G', 'L' or 'U', for j=1,2,…,LPEC.
19:   PE LDPE* – REAL (KIND=nag_wp) arrayOutput
Note: the second dimension of the array PE must be at least LH if LPEC>0, and at least 1 otherwise.
On exit: if LPEC≤0, PE is not referenced; otherwise PE ij contains the prediction error of criterion PEC i for the model fitted with ridge parameter H j, for i=1,2,…,LPEC and j=1,2,…,LH.
20:   LDPE – INTEGERInput
On entry: the first dimension of the array PE as declared in the (sub)program from which G02KBF is called.
Constraints:
  • if LPEC>0, LDPE≥LPEC;
  • otherwise LDPE≥1.
21:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, H i<0 for at least one i.
On entry, LH=value.
Constraint: LH>0.
On entry, M=value and N=value.
Constraint: M≤N.
On entry, N=value.
Constraint: N≥1.
On entry, PEC i is invalid for at least one i.
On entry, WANTB=value.
Constraint: WANTB=0, 1 or 2.
On entry, WANTVF=value.
Constraint: WANTVF=0 or 1.
IFAIL=2
IP does not equal the sum of elements in ISX.
On entry, ISX i≠0 or 1 for at least one i.
On entry, LDB=value and IP=value.
Constraint: if WANTB≠0, LDB≥IP+1.
On entry, LDPE=value and LPEC=value.
Constraint: LDPE≥LPEC.
On entry, LDVF=value and IP=value.
Constraint: if WANTVF≠0, LDVF≥IP.
On entry, LDX=value and N=value.
Constraint: LDX≥N.
IFAIL=3
On entry, WANTB=0 and WANTVF=0.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

The accuracy of G02KBF is closely related to that of the singular value decomposition.

8 Parallelism and Performance

G02KBF is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
G02KBF makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

G02KBF allocates internally max 5×N-1,2×IP×IP+N+3×IP+N elements of double precision storage.

10 Example

This example reads in data from an experiment to model body fat, and a selection of ridge regression models are calculated.

10.1 Program Text

Program Text (g02kbfe.f90)

10.2 Program Data

Program Data (g02kbfe.d)

10.3 Program Results

Program Results (g02kbfe.r)

G02 Chapter Contents
G02 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


G02LAF : NAG Library, Mark 26

G02 Chapter Contents
G02 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

G02LAF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

G02LAF fits an orthogonal scores partial least squares (PLS) regression by using singular value decomposition.

2 Specification

SUBROUTINE G02LAF ( N, MX, X, LDX, ISX, IP, MY, Y, LDY, XBAR, YBAR, ISCALE, XSTD, YSTD, MAXFAC, XRES, LDXRES, YRES, LDYRES, W, LDW, P, LDP, T, LDT, C, LDC, U, LDU, XCV, YCV, LDYCV, IFAIL)
INTEGER | N, MX, LDX, ISX(MX), IP, MY, LDY, ISCALE, MAXFAC, LDXRES, LDYRES, LDW, LDP, LDT, LDC, LDU, LDYCV, IFAIL
REAL (KIND=nag_wp) | X(LDX,MX), Y(LDY,MY), XBAR(IP), YBAR(MY), XSTD(IP), YSTD(MY), XRES(LDXRES,IP), YRES(LDYRES,MY), W(LDW,MAXFAC), P(LDP,MAXFAC), T(LDT,MAXFAC), C(LDC,MAXFAC), U(LDU,MAXFAC), XCV(MAXFAC), YCV(LDYCV,MY)

3 Description

Let X 1 be the mean-centred n by m data matrix X of n observations on m predictor variables. Let Y 1 be the mean-centred n by r data matrix Y of n observations on r response variables.
The first of the k factors PLS methods extract from the data predicts both X 1 and Y 1 by regressing on t 1 a column vector of n scores:
X^1 = t 1 p 1 T Y^1 = t 1 c 1 T , with ​ t 1 T t 1 = 1 ,
where the column vectors of m x-loadings p 1 and r y-loadings c 1 are calculated in the least squares sense:
p 1 T = t 1 T X 1 c 1 T = t 1 T Y 1 .
The x-score vector t 1=X 1w 1 is the linear combination of predictor data X 1 that has maximum covariance with the y-scores u 1=Y 1c 1, where the x-weights vector w 1 is the normalised first left singular vector of X 1 T Y 1.
The method extracts subsequent PLS factors by repeating the above process with the residual matrices:
Xi = X i-1 - X^ i-1 Yi = Y i-1 - Y^ i-1 ,  i=2,3,…,k ,
and with orthogonal scores:
tiT tj = 0 ,   j=1,2,…,i-1 .
Optionally, in addition to being mean-centred, the data matrices X 1 and Y 1 may be scaled by standard deviations of the variables. If data are supplied mean-centred, the calculations are not affected within numerical accuracy.

4 References

None.

5 Arguments

1:   N – INTEGERInput
On entry: n, the number of observations.
Constraint: N>1.
2:   MX – INTEGERInput
On entry: the number of predictor variables.
Constraint: MX>1.
3:   X LDXMX – REAL (KIND=nag_wp) arrayInput
On entry: X ij must contain the ith observation on the jth predictor variable, for i=1,2,…,N and j=1,2,…,MX.
4:   LDX – INTEGERInput
On entry: the first dimension of the array X as declared in the (sub)program from which G02LAF is called.
Constraint: LDX≥N.
5:   ISX MX – INTEGER arrayInput
On entry: indicates which predictor variables are to be included in the model.
ISX j=1
The jth predictor variable (with variates in the jth column of X) is included in the model.
ISX j=0
Otherwise.
Constraint: the sum of elements in ISX must equal IP.
6:   IP – INTEGERInput
On entry: m, the number of predictor variables in the model.
Constraint: 1<IP≤MX.
7:   MY – INTEGERInput
On entry: r, the number of response variables.
Constraint: MY≥1.
8:   Y LDYMY – REAL (KIND=nag_wp) arrayInput
On entry: Y ij must contain the ith observation for the jth response variable, for i=1,2,…,N and j=1,2,…,MY.
9:   LDY – INTEGERInput
On entry: the first dimension of the array Y as declared in the (sub)program from which G02LAF is called.
Constraint: LDY≥N.
10:   XBAR IP – REAL (KIND=nag_wp) arrayOutput
On exit: mean values of predictor variables in the model.
11:   YBAR MY – REAL (KIND=nag_wp) arrayOutput
On exit: the mean value of each response variable.
12:   ISCALE – INTEGERInput
On entry: indicates how predictor variables are scaled.
ISCALE=1
Data are scaled by the standard deviation of variables.
ISCALE=2
Data are scaled by user-supplied scalings.
ISCALE=-1
No scaling.
Constraint: ISCALE=-1, 1 or 2.
13:   XSTD IP – REAL (KIND=nag_wp) arrayInput/Output
On entry: if ISCALE=2, XSTD j must contain the user-supplied scaling for the jth predictor variable in the model, for j=1,2,…,IP. Otherwise XSTD need not be set.
On exit: if ISCALE=1, standard deviations of predictor variables in the model. Otherwise XSTD is not changed.
14:   YSTD MY – REAL (KIND=nag_wp) arrayInput/Output
On entry: if ISCALE=2, YSTD j must contain the user-supplied scaling for the jth response variable in the model, for j=1,2,…,MY. Otherwise YSTD need not be set.
On exit: if ISCALE=1, the standard deviation of each response variable. Otherwise YSTD is not changed.
15:   MAXFAC – INTEGERInput
On entry: k, the number of latent variables to calculate.
Constraint: 1≤MAXFAC≤IP.
16:   XRES LDXRESIP – REAL (KIND=nag_wp) arrayOutput
On exit: the predictor variables' residual matrix Xk.
17:   LDXRES – INTEGERInput
On entry: the first dimension of the array XRES as declared in the (sub)program from which G02LAF is called.
Constraint: LDXRES≥N.
18:   YRES LDYRESMY – REAL (KIND=nag_wp) arrayOutput
On exit: the residuals for each response variable, Yk.
19:   LDYRES – INTEGERInput
On entry: the first dimension of the array YRES as declared in the (sub)program from which G02LAF is called.
Constraint: LDYRES≥N.
20:   W LDWMAXFAC – REAL (KIND=nag_wp) arrayOutput
On exit: the jth column of W contains the x-weights wj, for j=1,2,…,MAXFAC.
21:   LDW – INTEGERInput
On entry: the first dimension of the array W as declared in the (sub)program from which G02LAF is called.
Constraint: LDW≥IP.
22:   P LDPMAXFAC – REAL (KIND=nag_wp) arrayOutput
On exit: the jth column of P contains the x-loadings pj, for j=1,2,…,MAXFAC.
23:   LDP – INTEGERInput
On entry: the first dimension of the array P as declared in the (sub)program from which G02LAF is called.
Constraint: LDP≥IP.
24:   T LDTMAXFAC – REAL (KIND=nag_wp) arrayOutput
On exit: the jth column of T contains the x-scores tj, for j=1,2,…,MAXFAC.
25:   LDT – INTEGERInput
On entry: the first dimension of the array T as declared in the (sub)program from which G02LAF is called.
Constraint: LDT≥N.
26:   C LDCMAXFAC – REAL (KIND=nag_wp) arrayOutput
On exit: the jth column of C contains the y-loadings cj, for j=1,2,…,MAXFAC.
27:   LDC – INTEGERInput
On entry: the first dimension of the array C as declared in the (sub)program from which G02LAF is called.
Constraint: LDC≥MY.
28:   U LDUMAXFAC – REAL (KIND=nag_wp) arrayOutput
On exit: the jth column of U contains the y-scores uj, for j=1,2,…,MAXFAC.
29:   LDU – INTEGERInput
On entry: the first dimension of the array U as declared in the (sub)program from which G02LAF is called.
Constraint: LDU≥N.
30:   XCV MAXFAC – REAL (KIND=nag_wp) arrayOutput
On exit: XCV j contains the cumulative percentage of variance in the predictor variables explained by the first j factors, for j=1,2,…,MAXFAC.
31:   YCV LDYCVMY – REAL (KIND=nag_wp) arrayOutput
On exit: YCV ij is the cumulative percentage of variance of the jth response variable explained by the first i factors, for i=1,2,…,MAXFAC and j=1,2,…,MY.
32:   LDYCV – INTEGERInput
On entry: the first dimension of the array YCV as declared in the (sub)program from which G02LAF is called.
Constraint: LDYCV≥MAXFAC.
33:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, element value of ISX is invalid.
On entry, ISCALE=value.
Constraint: ISCALE=-1 or 1.
On entry, MX=value.
Constraint: MX>1.
On entry, MY=value.
Constraint: MY≥1.
On entry, N=value.
Constraint: N>1.
IFAIL=2
On entry, IP=value and MX=value.
Constraint: 1<IP≤MX.
On entry, LDC=value and MY=value.
Constraint: LDC≥MY.
On entry, LDP=value and IP=value.
Constraint: LDP≥IP.
On entry, LDT=value and N=value.
Constraint: LDT≥N.
On entry, LDU=value and N=value.
Constraint: LDU≥N.
On entry, LDW=value and IP=value.
Constraint: LDW≥IP.
On entry, LDX=value and N=value.
Constraint: LDX≥N.
On entry, LDXRES=value and N=value.
Constraint: LDXRES≥N.
On entry, LDY=value and N=value.
Constraint: LDY≥N.
On entry, LDYCV=value and MAXFAC=value.
Constraint: LDYCV≥MAXFAC.
On entry, LDYRES=value and N=value.
Constraint: LDYRES≥N.
On entry, MAXFAC=value and IP=value.
Constraint: 1≤MAXFAC≤IP.
IFAIL=3
On entry, IP is not equal to the sum of ISX elements: IP=value, sum ISX=value.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

The computed singular value decomposition is nearly the exact singular value decomposition for a nearby matrix A+E , where
E 2 = O ε A 2 ,
and ε is the machine precision.

8 Parallelism and Performance

G02LAF makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

G02LAF allocates internally 2 mr + A + max 3 A+B,5 A + r elements of real storage, where A=min m,r and B=max m,r.

10 Example

This example reads in data from an experiment to measure the biological activity in a chemical compound, and a PLS model is estimated.

10.1 Program Text

Program Text (g02lafe.f90)

10.2 Program Data

Program Data (g02lafe.d)

10.3 Program Results

Program Results (g02lafe.r)

G02 Chapter Contents
G02 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


G02LBF : NAG Library, Mark 26

G02 Chapter Contents
G02 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

G02LBF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

G02LBF fits an orthogonal scores partial least squares (PLS) regression by using Wold's iterative method.

2 Specification

SUBROUTINE G02LBF ( N, MX, X, LDX, ISX, IP, MY, Y, LDY, XBAR, YBAR, ISCALE, XSTD, YSTD, MAXFAC, MAXIT, TAU, XRES, LDXRES, YRES, LDYRES, W, LDW, P, LDP, T, LDT, C, LDC, U, LDU, XCV, YCV, LDYCV, IFAIL)
INTEGER | N, MX, LDX, ISX(MX), IP, MY, LDY, ISCALE, MAXFAC, MAXIT, LDXRES, LDYRES, LDW, LDP, LDT, LDC, LDU, LDYCV, IFAIL
REAL (KIND=nag_wp) | X(LDX,MX), Y(LDY,MY), XBAR(IP), YBAR(MY), XSTD(IP), YSTD(MY), TAU, XRES(LDXRES,IP), YRES(LDYRES,MY), W(LDW,MAXFAC), P(LDP,MAXFAC), T(LDT,MAXFAC), C(LDC,MAXFAC), U(LDU,MAXFAC), XCV(MAXFAC), YCV(LDYCV,MY)

3 Description

Let X 1 be the mean-centred n by m data matrix X of n observations on m predictor variables. Let Y 1 be the mean-centred n by r data matrix Y of n observations on r response variables.
The first of the k factors PLS methods extract from the data predicts both X 1 and Y 1 by regressing on a t 1 column vector of n scores:
X^1 = t 1 p 1 T Y^1 = t 1 c 1 T , with ​ t 1 T t 1 = 1 ,
where the column vectors of m x-loadings p 1 and r y-loadings c 1 are calculated in the least squares sense:
p 1 T = t 1 T X 1 c 1 T = t 1 T Y 1 .
The x-score vector t 1=X 1w 1 is the linear combination of predictor data X 1 that has maximum covariance with the y-scores u 1=Y 1c 1, where the x-weights vector w 1 is the normalised first left singular vector of X 1 T Y 1.
The method extracts subsequent PLS factors by repeating the above process with the residual matrices:
Xi = X i-1 - X^ i-1 Yi = Y i-1 - Y^ i-1 ,  i=2,3,…,k ,
and with orthogonal scores:
tiT tj = 0 ,   j=1,2,…,i-1 .
Optionally, in addition to being mean-centred, the data matrices X 1 and Y 1 may be scaled by standard deviations of the variables. If data are supplied mean-centred, the calculations are not affected within numerical accuracy.

4 References

Wold H (1966) Estimation of principal components and related models by iterative least squares In: Multivariate Analysis (ed P R Krishnaiah) 391–420 Academic Press NY

5 Arguments

1:   N – INTEGERInput
On entry: n, the number of observations.
Constraint: N>1.
2:   MX – INTEGERInput
On entry: the number of predictor variables.
Constraint: MX>1.
3:   X LDXMX – REAL (KIND=nag_wp) arrayInput
On entry: X ij must contain the ith observation on the jth predictor variable, for i=1,2,…,N and j=1,2,…,MX.
4:   LDX – INTEGERInput
On entry: the first dimension of the array X as declared in the (sub)program from which G02LBF is called.
Constraint: LDX≥N.
5:   ISX MX – INTEGER arrayInput
On entry: indicates which predictor variables are to be included in the model.
ISX j=1
The jth predictor variable (with variates in the jth column of X) is included in the model.
ISX j=0
Otherwise.
Constraint: the sum of elements in ISX must equal IP.
6:   IP – INTEGERInput
On entry: m, the number of predictor variables in the model.
Constraint: 1<IP≤MX.
7:   MY – INTEGERInput
On entry: r, the number of response variables.
Constraint: MY≥1.
8:   Y LDYMY – REAL (KIND=nag_wp) arrayInput
On entry: Y ij must contain the ith observation for the jth response variable, for i=1,2,…,N and j=1,2,…,MY.
9:   LDY – INTEGERInput
On entry: the first dimension of the array Y as declared in the (sub)program from which G02LBF is called.
Constraint: LDY≥N.
10:   XBAR IP – REAL (KIND=nag_wp) arrayOutput
On exit: mean values of predictor variables in the model.
11:   YBAR MY – REAL (KIND=nag_wp) arrayOutput
On exit: the mean value of each response variable.
12:   ISCALE – INTEGERInput
On entry: indicates how predictor variables are scaled.
ISCALE=1
Data are scaled by the standard deviation of variables.
ISCALE=2
Data are scaled by user-supplied scalings.
ISCALE=-1
No scaling.
Constraint: ISCALE=-1, 1 or 2.
13:   XSTD IP – REAL (KIND=nag_wp) arrayInput/Output
On entry: if ISCALE=2, XSTD j must contain the user-supplied scaling for the jth predictor variable in the model, for j=1,2,…,IP. Otherwise XSTD need not be set.
On exit: if ISCALE=1, standard deviations of predictor variables in the model. Otherwise XSTD is not changed.
14:   YSTD MY – REAL (KIND=nag_wp) arrayInput/Output
On entry: if ISCALE=2, YSTD j must contain the user-supplied scaling for the jth response variable in the model, for j=1,2,…,MY. Otherwise YSTD need not be set.
On exit: if ISCALE=1, the standard deviation of each response variable. Otherwise YSTD is not changed.
15:   MAXFAC – INTEGERInput
On entry: k, the number of latent variables to calculate.
Constraint: 1≤MAXFAC≤IP.
16:   MAXIT – INTEGERInput
On entry: if MY=1, MAXIT is not referenced; otherwise the maximum number of iterations used to calculate the x-weights.
Suggested value: MAXIT=200.
Constraint: if MY>1, MAXIT>1.
17:   TAU – REAL (KIND=nag_wp)Input
On entry: if MY=1, TAU is not referenced; otherwise the iterative procedure used to calculate the x-weights will halt if the Euclidean distance between two subsequent estimates is less than or equal to TAU.
Suggested value: TAU=1.0E−4.
Constraint: if MY>1, TAU>0.0.
18:   XRES LDXRESIP – REAL (KIND=nag_wp) arrayOutput
On exit: the predictor variables' residual matrix Xk.
19:   LDXRES – INTEGERInput
On entry: the first dimension of the array XRES as declared in the (sub)program from which G02LBF is called.
Constraint: LDXRES≥N.
20:   YRES LDYRESMY – REAL (KIND=nag_wp) arrayOutput
On exit: the residuals for each response variable, Yk.
21:   LDYRES – INTEGERInput
On entry: the first dimension of the array YRES as declared in the (sub)program from which G02LBF is called.
Constraint: LDYRES≥N.
22:   W LDWMAXFAC – REAL (KIND=nag_wp) arrayOutput
On exit: the jth column of W contains the x-weights wj, for j=1,2,…,MAXFAC.
23:   LDW – INTEGERInput
On entry: the first dimension of the array W as declared in the (sub)program from which G02LBF is called.
Constraint: LDW≥IP.
24:   P LDPMAXFAC – REAL (KIND=nag_wp) arrayOutput
On exit: the jth column of P contains the x-loadings pj, for j=1,2,…,MAXFAC.
25:   LDP – INTEGERInput
On entry: the first dimension of the array P as declared in the (sub)program from which G02LBF is called.
Constraint: LDP≥IP.
26:   T LDTMAXFAC – REAL (KIND=nag_wp) arrayOutput
On exit: the jth column of T contains the x-scores tj, for j=1,2,…,MAXFAC.
27:   LDT – INTEGERInput
On entry: the first dimension of the array T as declared in the (sub)program from which G02LBF is called.
Constraint: LDT≥N.
28:   C LDCMAXFAC – REAL (KIND=nag_wp) arrayOutput
On exit: the jth column of C contains the y-loadings cj, for j=1,2,…,MAXFAC.
29:   LDC – INTEGERInput
On entry: the first dimension of the array C as declared in the (sub)program from which G02LBF is called.
Constraint: LDC≥MY.
30:   U LDUMAXFAC – REAL (KIND=nag_wp) arrayOutput
On exit: the jth column of U contains the y-scores uj, for j=1,2,…,MAXFAC.
31:   LDU – INTEGERInput
On entry: the first dimension of the array U as declared in the (sub)program from which G02LBF is called.
Constraint: LDU≥N.
32:   XCV MAXFAC – REAL (KIND=nag_wp) arrayOutput
On exit: XCV j contains the cumulative percentage of variance in the predictor variables explained by the first j factors, for j=1,2,…,MAXFAC.
33:   YCV LDYCVMY – REAL (KIND=nag_wp) arrayOutput
On exit: YCV ij is the cumulative percentage of variance of the jth response variable explained by the first i factors, for i=1,2,…,MAXFAC and j=1,2,…,MY.
34:   LDYCV – INTEGERInput
On entry: the first dimension of the array YCV as declared in the (sub)program from which G02LBF is called.
Constraint: LDYCV≥MAXFAC.
35:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, element value of ISX is invalid.
On entry, ISCALE=value.
Constraint: ISCALE=-1 or 1.
On entry, MX=value.
Constraint: MX>1.
On entry, MY=value.
Constraint: MY≥1.
On entry, N=value.
Constraint: N>1.
IFAIL=2
On entry, IP=value and MX=value.
Constraint: 1<IP≤MX.
On entry, LDC=value and MY=value.
Constraint: LDC≥MY.
On entry, LDP=value and IP=value.
Constraint: LDP≥IP.
On entry, LDT=value and N=value.
Constraint: LDT≥N.
On entry, LDU=value and N=value.
Constraint: LDU≥N.
On entry, LDW=value and IP=value.
Constraint: LDW≥IP.
On entry, LDX=value and N=value.
Constraint: LDX≥N.
On entry, LDXRES=value and N=value.
Constraint: LDXRES≥N.
On entry, LDY=value and N=value.
Constraint: LDY≥N.
On entry, LDYCV=value and MAXFAC=value.
Constraint: LDYCV≥MAXFAC.
On entry, LDYRES=value and N=value.
Constraint: LDYRES<N.
On entry, MAXFAC=value and IP=value.
Constraint: 1≤MAXFAC≤IP.
On entry, MY=value and MAXIT=value.
Constraint: if MY>1, MAXIT>1.
On entry, TAU=value.
Constraint: if MY>1, TAU>0.0.
IFAIL=3
On entry, IP is not equal to the sum of ISX elements: IP=value, sum ISX=value.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

In general, the iterative method used in the calculations is less accurate (but faster) than the singular value decomposition approach adopted by G02LAF.

8 Parallelism and Performance

G02LBF makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

G02LBF allocates internally (n+r) elements of real storage.

10 Example

This example reads in data from an experiment to measure the biological activity in a chemical compound, and a PLS model is estimated.

10.1 Program Text

Program Text (g02lbfe.f90)

10.2 Program Data

Program Data (g02lbfe.d)

10.3 Program Results

Program Results (g02lbfe.r)

G02 Chapter Contents
G02 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


G02LCF : NAG Library, Mark 26

G02 Chapter Contents
G02 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

G02LCF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

G02LCF calculates parameter estimates for a given number of factors given the output from an orthogonal scores PLS regression (G02LAF or G02LBF).

2 Specification

SUBROUTINE G02LCF ( IP, MY, MAXFAC, NFACT, P, LDP, C, LDC, W, LDW, RCOND, B, LDB, ORIG, XBAR, YBAR, ISCALE, XSTD, YSTD, OB, LDOB, VIPOPT, YCV, LDYCV, VIP, LDVIP, IFAIL)
INTEGER | IP, MY, MAXFAC, NFACT, LDP, LDC, LDW, LDB, ORIG, ISCALE, LDOB, VIPOPT, LDYCV, LDVIP, IFAIL
REAL (KIND=nag_wp) | P(LDP,MAXFAC), C(LDC,MAXFAC), W(LDW,MAXFAC), RCOND, B(LDB,MY), XBAR(IP), YBAR(MY), XSTD(IP), YSTD(MY), OB(LDOB,MY), YCV(LDYCV,MY), VIP(LDVIP,VIPOPT)

3 Description

The parameter estimates B for a l-factor orthogonal scores PLS model with m predictor variables and r response variables are given by,
B=W PT W-1 CT ,   B∈ ℝ m×r ,
where W is the m by k (≥l) matrix of x-weights; P is the m by k matrix of x-loadings; and C is the r by k matrix of y-loadings for a fitted PLS model.
The parameter estimates B are for centred, and possibly scaled, predictor data X 1 and response data Y 1. Parameter estimates may also be given for the predictor data X and response data Y.
Optionally, G02LCF will calculate variable influence on projection (VIP) statistics, see Wold (1994).

4 References

Wold S (1994) PLS for multivariate linear modelling QSAR: chemometric methods in molecular design Methods and Principles in Medicinal Chemistry (ed van de Waterbeemd H) Verlag-Chemie

5 Arguments

1:   IP – INTEGERInput
On entry: m, the number of predictor variables in the fitted model.
Constraint: IP>1.
2:   MY – INTEGERInput
On entry: r, the number of response variables.
Constraint: MY≥1.
3:   MAXFAC – INTEGERInput
On entry: k, the number of factors available in the PLS model.
Constraint: 1≤MAXFAC≤IP.
4:   NFACT – INTEGERInput
On entry: l, the number of factors to include in the calculation of parameter estimates.
Constraint: 1≤NFACT≤MAXFAC.
5:   P LDPMAXFAC – REAL (KIND=nag_wp) arrayInput
On entry: x-loadings as returned from G02LAF and G02LBF.
6:   LDP – INTEGERInput
On entry: the first dimension of the array P as declared in the (sub)program from which G02LCF is called.
Constraint: LDP≥IP.
7:   C LDCMAXFAC – REAL (KIND=nag_wp) arrayInput
On entry: y-loadings as returned from G02LAF and G02LBF.
8:   LDC – INTEGERInput
On entry: the first dimension of the array C as declared in the (sub)program from which G02LCF is called.
Constraint: LDC≥MY.
9:   W LDWMAXFAC – REAL (KIND=nag_wp) arrayInput
On entry: x-weights as returned from G02LAF and G02LBF.
10:   LDW – INTEGERInput
On entry: the first dimension of the array W as declared in the (sub)program from which G02LCF is called.
Constraint: LDW≥IP.
11:   RCOND – REAL (KIND=nag_wp)Input
On entry: singular values of PT W less than RCOND times the maximum singular value are treated as zero when calculating parameter estimates. If RCOND is negative, a value of 0.005 is used.
12:   B LDBMY – REAL (KIND=nag_wp) arrayOutput
On exit: B ij contains the parameter estimate for the ith predictor variable in the model for the jth response variable, for i=1,2,…,IP and j=1,2,…,MY.
13:   LDB – INTEGERInput
On entry: the first dimension of the array B as declared in the (sub)program from which G02LCF is called.
Constraint: LDB≥IP.
14:   ORIG – INTEGERInput
On entry: indicates how parameter estimates are calculated.
ORIG=-1
Parameter estimates for the centred, and possibly, scaled data.
ORIG=1
Parameter estimates for the original data.
Constraint: ORIG=-1 or 1.
15:   XBAR IP – REAL (KIND=nag_wp) arrayInput
On entry: if ORIG=1, mean values of predictor variables in the model; otherwise XBAR is not referenced.
16:   YBAR MY – REAL (KIND=nag_wp) arrayInput
On entry: if ORIG=1, mean value of each response variable in the model; otherwise YBAR is not referenced.
17:   ISCALE – INTEGERInput
On entry: if ORIG=1, ISCALE must take the value supplied to either G02LAF or G02LBF; otherwise ISCALE is not referenced.
Constraint: if ORIG=1, ISCALE=-1, 1 or 2.
18:   XSTD IP – REAL (KIND=nag_wp) arrayInput
On entry: if ORIG=1 and ISCALE≠-1, the scalings of predictor variables in the model as returned from either G02LAF or G02LBF; otherwise XSTD is not referenced.
19:   YSTD MY – REAL (KIND=nag_wp) arrayInput
On entry: if ORIG=1 and ISCALE≠-1, the scalings of response variables as returned from either G02LAF or G02LBF; otherwise YSTD is not referenced.
20:   OB LDOBMY – REAL (KIND=nag_wp) arrayOutput
On exit: if ORIG=1, OB 1 j contains the intercept value for the jth response variable, and OB i+1 j contains the parameter estimate on the original scale for the ith predictor variable in the model, for i=1,2,…,IP and j=1,2,…,MY. Otherwise OB is not referenced.
21:   LDOB – INTEGERInput
On entry: the first dimension of the array OB as declared in the (sub)program from which G02LCF is called.
Constraints:
  • if ORIG=1, LDOB≥IP+1;
  • otherwise LDOB≥1.
22:   VIPOPT – INTEGERInput
On entry: a flag that determines variable influence on projections (VIP) options.
VIPOPT=0
VIP are not calculated.
VIPOPT=1
VIP are calculated for predictor variables using the mean explained variance in responses.
VIPOPT=MY
VIP are calculated for predictor variables for each response variable in the model.
Note that setting VIPOPT=MY when MY=1 gives the same result as setting VIPOPT=1 directly.
Constraint: VIPOPT=0, 1 or MY.
23:   YCV LDYCVMY – REAL (KIND=nag_wp) arrayInput
On entry: if VIPOPT≠0, YCV ij is the cumulative percentage of variance of the jth response variable explained by the first i factors, for i=1,2,…,NFACT and j=1,2,…,MY; otherwise YCV is not referenced.
24:   LDYCV – INTEGERInput
On entry: the first dimension of the array YCV as declared in the (sub)program from which G02LCF is called.
Constraint: if VIPOPT≠0, LDYCV≥NFACT.
25:   VIP LDVIPVIPOPT – REAL (KIND=nag_wp) arrayOutput
On exit: if VIPOPT=1, VIP i 1 contains the VIP statistic for the ith predictor variable in the model for all response variables, for i=1,2,…,IP.
If VIPOPT=MY, VIP ij contains the VIP statistic for the ith predictor variable in the model for the jth response variable, for i=1,2,…,IP and j=1,2,…,MY.
Otherwise VIP is not referenced.
26:   LDVIP – INTEGERInput
On entry: the first dimension of the array VIP as declared in the (sub)program from which G02LCF is called.
Constraint: if VIPOPT≠0, LDVIP≥IP.
27:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, IP=value.
Constraint: IP>1.
On entry, ISCALE=value.
Constraint: if ORIG=1, ISCALE=-1 or 1.
On entry, MY=value.
Constraint: MY≥1.
On entry, ORIG=value.
Constraint: ORIG=-1 or 1.
On entry, VIPOPT=value and MY=value.
Constraint: VIPOPT=0, 1 or MY.
IFAIL=2
On entry, LDB=value and IP=value.
Constraint: LDB≥IP.
On entry, LDC=value and MY=value.
Constraint: LDC≥MY.
On entry, LDOB=value and IP=value.
Constraint: if ORIG=1, LDOB≥IP+1.
On entry, LDP=value and IP=value.
Constraint: LDP≥IP.
On entry, LDVIP=value and IP=value.
Constraint: if VIPOPT≠0, LDVIP≥IP.
On entry, LDW=value and IP=value.
Constraint: LDW≥IP.
On entry, LDYCV=value and NFACT=value.
Constraint: if VIPOPT≠0, LDYCV≥NFACT.
On entry, MAXFAC=value and IP=value.
Constraint: 1≤MAXFAC≤IP.
On entry, NFACT=value and MAXFAC=value.
Constraint: 1≤NFACT≤MAXFAC.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

The calculations are based on the singular value decomposition of PT W.

8 Parallelism and Performance

G02LCF is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
G02LCF makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

G02LCF allocates internally l l+r+4+max 2 l,r elements of real storage.

10 Example

This example reads in details of a PLS model, and a set of parameter estimates are calculated along with their VIP statistics.

10.1 Program Text

Program Text (g02lcfe.f90)

10.2 Program Data

Program Data (g02lcfe.d)

10.3 Program Results

Program Results (g02lcfe.r)

G02 Chapter Contents
G02 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


G02LDF : NAG Library, Mark 26

G02 Chapter Contents
G02 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

G02LDF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

G02LDF calculates predictions given the output from an orthogonal scores PLS regression (G02LAF or G02LBF) and G02LCF.

2 Specification

SUBROUTINE G02LDF ( IP, MY, ORIG, XBAR, YBAR, ISCALE, XSTD, YSTD, B, LDB, N, MZ, ISZ, Z, LDZ, YHAT, LDYHAT, IFAIL)
INTEGER | IP, MY, ORIG, ISCALE, LDB, N, MZ, ISZ(MZ), LDZ, LDYHAT, IFAIL
REAL (KIND=nag_wp) | XBAR(IP), YBAR(MY), XSTD(IP), YSTD(MY), B(LDB,MY), Z(LDZ,MZ), YHAT(LDYHAT,MY)

3 Description

G02LDF calculates the predictions Y^ of a PLS model given a set Z of test data and a set B of parameter estimates as returned by G02LCF.
If G02LCF returns parameter estimates for the original data scale, no further information is required.
If G02LCF returns parameter estimates for the centred, and possibly scaled, data, further information is required. The means of variables in the fitted model must be supplied. In the case of a PLS model fitted by using scaled data, the means and standard deviations of variables in the fitted model must also be supplied. These means and standard deviations are those returned by either G02LAF and G02LBF.

4 References

None.

5 Arguments

1:   IP – INTEGERInput
On entry: the number of predictor variables in the fitted model. IP must take the same value as that supplied to G02LAF or G02LBF to fit the model.
Constraint: IP>1.
2:   MY – INTEGERInput
On entry: the number of response variables in the fitted model. MY must take the same value as that supplied to G02LAF or G02LBF to fit the model.
Constraint: MY≥1.
3:   ORIG – INTEGERInput
On entry: indicates how parameter estimates are supplied.
ORIG=1
Parameter estimates are for the original data.
ORIG=-1
Parameter estimates are for the centred, and possibly scaled, data.
Constraint: ORIG=-1 or 1.
4:   XBAR IP – REAL (KIND=nag_wp) arrayInput
On entry: if ORIG=-1, XBAR must contain mean values of predictor variables in the model; otherwise XBAR is not referenced.
5:   YBAR MY – REAL (KIND=nag_wp) arrayInput
On entry: if ORIG=-1, YBAR must contain the mean value of each response variable in the model; otherwise YBAR is not referenced.
6:   ISCALE – INTEGERInput
On entry: if ORIG=-1, ISCALE must take the value supplied to either G02LAF or G02LBF; otherwise ISCALE is not referenced.
Constraint: if ORIG=-1, ISCALE=-1, 1 or 2.
7:   XSTD IP – REAL (KIND=nag_wp) arrayInput
On entry: if ORIG=-1 and ISCALE≠-1, XSTD must contain the scalings of predictor variables in the model as returned from either G02LAF or G02LBF; otherwise XSTD is not referenced.
8:   YSTD MY – REAL (KIND=nag_wp) arrayInput
On entry: if ORIG=-1 and ISCALE≠-1, YSTD must contain the scalings of response variables as returned from either G02LAF or G02LBF; otherwise YSTD is not referenced.
9:   B LDBMY – REAL (KIND=nag_wp) arrayInput
On entry: if ORIG=-1, B must contain the parameter estimate for the centred, and possibly scaled, data as returned by G02LCF; otherwise B must contain the parameter estimates for the original data as returned by G02LCF.
10:   LDB – INTEGERInput
On entry: the first dimension of the array B as declared in the (sub)program from which G02LDF is called. If ORIG=-1, LDB must be at least IP; otherwise B also contains the estimate for the intercept parameter and consequently LDB must be at least 1+IP.
Constraints:
  • if ORIG=-1, LDB≥IP;
  • if ORIG=1, LDB≥1+IP.
11:   N – INTEGERInput
On entry: n, the number of observations in the test data Z.
Constraint: N≥1.
12:   MZ – INTEGERInput
On entry: the number of available predictor variables in the test data.
Constraint: MZ≥IP.
13:   ISZ MZ – INTEGER arrayInput
On entry: indicates which predictor variables are to be included in the model. Predictor variables included from Z must be in the same order as those included in the fitted model.
If ISZ j=1, the jth predictor variable is included in the model, for j=1,2,…,MZ, otherwise ISZ j=0.
Constraints:
  • ISZ j=0​ or ​1, for j=1,2,…,MZ;
  • ∑j ISZ j=IP.
14:   Z LDZMZ – REAL (KIND=nag_wp) arrayInput
On entry: Z ij contains the ith observation on the jth available predictor variable, for i=1,2,…,N and j=1,2,…,MZ.
15:   LDZ – INTEGERInput
On entry: the first dimension of the array Z as declared in the (sub)program from which G02LDF is called.
Constraint: LDZ≥N.
16:   YHAT LDYHATMY – REAL (KIND=nag_wp) arrayOutput
On exit: YHAT ij contains the ith predicted value of the jth y-variable in the model.
17:   LDYHAT – INTEGERInput
On entry: the first dimension of the array YHAT as declared in the (sub)program from which G02LDF is called.
Constraint: LDYHAT≥N.
18:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, IP=value.
Constraint: IP>1.
On entry, ISCALE=value.
Constraint: if ORIG=-1, ISCALE=-1, 1 or 2.
On entry, ISZ j=value, j=value.
Constraint: ISZ j=0​ or ​1.
On entry, MY=value.
Constraint: MY≥1.
On entry, N=value.
Constraint: N≥1.
On entry, ORIG=value.
Constraint: ORIG=-1 or 1.
IFAIL=2
On entry, LDB=value and IP=value.
Constraint: if ORIG=-1, LDB≥IP.
On entry, LDB=value and IP+1=value.
Constraint: if ORIG=1, LDB≥1+IP.
On entry, LDYHAT=value and N=value.
Constraint: LDYHAT≥N.
On entry, LDZ=value and N=value.
Constraint: LDZ≥N.
On entry, MZ=value and IP=value.
Constraint: MZ≥IP.
IFAIL=3
On entry, the number of elements of ISZ equal to 1 is not IP.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

Not applicable.

8 Parallelism and Performance

G02LDF makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

G02LDF allocates internally 3×IP+MY elements of real storage.

10 Example

This example reads in parameter estimates for a fitted PLS model and prediction data, and the PLS model predictions are calculated.

10.1 Program Text

Program Text (g02ldfe.f90)

10.2 Program Data

Program Data (g02ldfe.d)

10.3 Program Results

Program Results (g02ldfe.r)

G02 Chapter Contents
G02 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


G02MAF : NAG Library, Mark 26

G02 Chapter Contents
G02 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

G02MAF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

G02MAF performs Least Angle Regression (LARS), forward stagewise linear regression or Least Absolute Shrinkage and Selection Operator (LASSO).

2 Specification

SUBROUTINE G02MAF ( MTYPE, PRED, PREY, N, M, D, LDD, ISX, LISX, Y, MNSTEP, IP, NSTEP, B, LDB, FITSUM, ROPT, LROPT, IFAIL)
INTEGER | MTYPE, PRED, PREY, N, M, LDD, ISX(LISX), LISX, MNSTEP, IP, NSTEP, LDB, LROPT, IFAIL
REAL (KIND=nag_wp) | D(LDD,*), Y(N), B(LDB,*), FITSUM(6,MNSTEP+1), ROPT(LROPT)

3 Description

G02MAF implements the LARS algorithm of Efron et al. (2004) as well as the modifications needed to perform forward stagewise linear regression and fit LASSO and positive LASSO models.
Given a vector of n observed values, y = yi : i=1,2,…,n and an n×p design matrix X, where the jth column of X, denoted xj, is a vector of length n representing the jth independent variable xj, standardized such that ∑ i=1 n x ij =0 , and ∑ i=1 n x ij 2 =1 and a set of model parameters β to be estimated from the observed values, the LARS algorithm can be summarised as:
1. | Set k=1 and all coefficients to zero, that is β=0.
2. | Find the variable most correlated with y, say x j 1. Add x j 1 to the ‘most correlated’ set A. If p=1 go to 8.
3. | Take the largest possible step in the direction of x j 1 (i.e., increase the magnitude of β j 1) until some other variable, say x j 2, has the same correlation with the current residual, y-x j 1β j 1.
4. | Increment k and add x jk to A.
5. | If A=p go to 8.
6. | Proceed in the ‘least angle direction’, that is, the direction which is equiangular between all variables in A, altering the magnitude of the parameter estimates of those variables in A, until the kth variable, x jk, has the same correlation with the current residual.
7. | Go to 4.
8. | Let K=k.
As well as being a model selection process in its own right, with a small number of modifications the LARS algorithm can be used to fit the LASSO model of Tibshirani (1996), a positive LASSO model, where the independent variables enter the model in their defined direction (i.e., β kj≥0), forward stagewise linear regression (Hastie et al. (2001)) and forward selection (Weisberg (1985)). Details of the required modifications in each of these cases are given in Efron et al. (2004).
The LASSO model of Tibshirani (1996) is given by
minimize α , βk∈ ℝp y- α- XT βk 2   subject to   βk 1 ≤tk
for all values of tk, where α=y-=n-1⁢∑ i=1 n yi. The positive LASSO model is the same as the standard LASSO model, given above, with the added constraint that
β kj ≥ 0 ,   j=1,2,…,p .
Unlike the standard LARS algorithm, when fitting either of the LASSO models, variables can be dropped as well as added to the set A. Therefore the total number of steps K is no longer bounded by p.
Forward stagewise linear regression is an iterative procedure of the form:
1. | Initialize k=1 and the vector of residuals r 0=y-α.
2. | For each j=1,2,…,p calculate cj=xjT r k-1. The value cj is therefore proportional to the correlation between the jth independent variable and the vector of previous residual values, rk.
3. | Calculate jk = argmax j cj , the value of j with the largest absolute value of cj.
4. | If c jk<ε then go to 7.
5. Update the residual values, with
rk = r k-1 + δ ⁢ ​ ​ sign c jk ⁢ x jk
where δ is a small constant and sign c jk=-1 when c jk<0 and 1 otherwise.
6. | Increment k and go to 2.
7. | Set K=k.
If the largest possible step were to be taken, that is δ=c jk then forward stagewise linear regression reverts to the standard forward selection method as implemented in G02EEF.
The LARS procedure results in K models, one for each step of the fitting process. In order to aid in choosing which is the most suitable Efron et al. (2004) introduced a Cp-type statistic given by
Cp k = y- XT βk 2 σ 2 -n+2⁢νk,
where νk is the approximate degrees of freedom for the kth step and
σ 2 = n-yT y νK .
One way of choosing a model is therefore to take the one with the smallest value of Cp k.

4 References

Efron B, Hastie T, Johnstone I and Tibshirani R (2004) Least Angle Regression The Annals of Statistics (Volume 32) 2 407–499
Hastie T, Tibshirani R and Friedman J (2001) The Elements of Statistical Learning: Data Mining, Inference and Prediction Springer (New York)
Tibshirani R (1996) Regression Shrinkage and Selection via the Lasso Journal of the Royal Statistics Society, Series B (Methodological) (Volume 58) 1 267–288
Weisberg S (1985) Applied Linear Regression Wiley

5 Arguments

1:   MTYPE – INTEGERInput
On entry: indicates the type of model to fit.
MTYPE=1
LARS is performed.
MTYPE=2
Forward linear stagewise regression is performed.
MTYPE=3
LASSO model is fit.
MTYPE=4
A positive LASSO model is fit.
Constraint: MTYPE=1, 2, 3 or 4.
2:   PRED – INTEGERInput
On entry: indicates the type of data preprocessing to perform on the independent variables supplied in D to comply with the standardized form of the design matrix.
PRED=0
No preprocessing is performed.
PRED=1
Each of the independent variables, xj, for j=1,2,…,p, are mean centred prior to fitting the model. The means of the independent variables, x-, are returned in B, with x-j=B j NSTEP+2, for j=1,2,…,p.
PRED=2
Each independent variable is normalized, with the jth variable scaled by 1/xjT xj. The scaling factor used by variable j is returned in B j NSTEP+1.
PRED=3
As PRED=1 and 2, all of the independent variables are mean centred prior to being normalized.
Suggested value: PRED=3.
Constraint: PRED=0, 1, 2 or 3.
3:   PREY – INTEGERInput
On entry: indicates the type of data preprocessing to perform on the dependent variable supplied in Y.
PREY=0
No preprocessing is performed, this is equivalent to setting α=0.
PREY=1
The dependent variable, y, is mean centred prior to fitting the model, so α=y-. Which is equivalent to fitting a non-penalized intercept to the model and the degrees of freedom etc. are adjusted accordingly.
The value of α used is returned in FITSUM 1 NSTEP+1.
Suggested value: PREY=1.
Constraint: PREY=0 or 1.
4:   N – INTEGERInput
On entry: n, the number of observations.
Constraint: N≥1.
5:   M – INTEGERInput
On entry: m, the total number of independent variables.
Constraint: M≥1.
6:   D LDD* – REAL (KIND=nag_wp) arrayInput
Note: the second dimension of the array D must be at least M.
On entry: D, the data, which along with PRED and ISX, defines the design matrix X. The ith observation for the jth variable must be supplied in D ij, for i=1,2,…,N and j=1,2,…,M.
7:   LDD – INTEGERInput
On entry: the first dimension of the array D as declared in the (sub)program from which G02MAF is called.
Constraint: LDD≥N.
8:   ISX LISX – INTEGER arrayInput
On entry: indicates which independent variables from D will be included in the design matrix, X.
If LISX=0, all variables are included in the design matrix and ISX is not referenced.
If LISX=M, for j=1,2,…,M when ISX j must be set as follows:
ISX j=1
To indicate that the jth variable, as supplied in D, is included in the design matrix;
ISX j=0
To indicated that the jth variable, as supplied in D, is not included in the design matrix;
and p= ∑ j=1 m ISX j.
Constraint: if LISX=M, ISX j=0 or 1 and at least one value of ISX j≠0, for j=1,2,…,M.
9:   LISX – INTEGERInput
On entry: length of the ISX array.
Constraint: LISX=0 or M.
10:   Y N – REAL (KIND=nag_wp) arrayInput
On entry: y, the observations on the dependent variable.
11:   MNSTEP – INTEGERInput
On entry: the maximum number of steps to carry out in the model fitting process.
If MTYPE=1, i.e., a LARS is being performed, the maximum number of steps the algorithm will take is min p,n if PREY=0, otherwise min p,n-1.
If MTYPE=2, i.e., a forward linear stagewise regression is being performed, the maximum number of steps the algorithm will take is likely to be several orders of magnitude more and is no longer bound by p or n.
If MTYPE=3 or 4, i.e., a LASSO or positive LASSO model is being fit, the maximum number of steps the algorithm will take lies somewhere between that of the LARS and forward linear stagewise regression, again it is no longer bound by p or n.
Constraint: MNSTEP≥1.
12:   IP – INTEGEROutput
On exit: p, number of parameter estimates.
If LISX=0, p=M, i.e., the number of variables in D.
Otherwise p is the number of nonzero values in ISX.
13:   NSTEP – INTEGEROutput
On exit: K, the actual number of steps carried out in the model fitting process.
14:   B LDB* – REAL (KIND=nag_wp) arrayOutput
Note: the second dimension of the array B must be at least MNSTEP+2.
On exit: β the parameter estimates, with B jk=β kj, the parameter estimate for the jth variable, j=1,2,…,p at the kth step of the model fitting process, k=1,2,…,NSTEP.
By default, when PRED=2 or 3 the parameter estimates are rescaled prior to being returned. If the parameter estimates are required on the normalized scale, then this can be overridden via ROPT.
The values held in the remaining part of B depend on the type of preprocessing performed.
If PRED=0,
B j NSTEP+1 = 1 B j NSTEP+2 = 0
If PRED=1,
B j NSTEP+1 = 1 B j NSTEP+2 = x-j
If PRED=2,
B j NSTEP+1 = 1/ xjT xj B j NSTEP+2 = 0
If PRED=3,
B j NSTEP+1 = 1/ xj-x-j T xj-x-j B j NSTEP+2 = x-j
for j=1,2,…,p.
15:   LDB – INTEGERInput
On entry: the first dimension of the array B as declared in the (sub)program from which G02MAF is called.
Constraint: LDB≥p, where p is the number of parameter estimates as described in IP.
16:   FITSUM 6 MNSTEP+1 – REAL (KIND=nag_wp) arrayOutput
On exit: summaries of the model fitting process. When k=1,2,…,NSTEP,
FITSUM 1 k
βk 1, the sum of the absolute values of the parameter estimates for the kth step of the modelling fitting process. If PRED=2 or 3, the scaled parameter estimates are used in the summation.
FITSUM 2 k
RSSk, the residual sums of squares for the kth step, where RSSk= y- XT βk 2 .
FITSUM 3 k
νk, approximate degrees of freedom for the kth step.
FITSUM 4 k
Cp k, a Cp-type statistic for the kth step, where Cp k=RSSk σ 2-n+2⁢νk.
FITSUM 5 k
C^k, correlation between the residual at step k-1 and the most correlated variable not yet in the active set A, where the residual at step 0 is y.
FITSUM 6 k
γ^k, the step size used at step k.
In addition
FITSUM 1 NSTEP+1
α, with α=y- if PREY=1 and 0 otherwise.
FITSUM 2 NSTEP+1
RSS 0, the residual sums of squares for the null model, where RSS 0=yT y when PREY=0 and RSS 0=y-y-T y-y- otherwise.
FITSUM 3 NSTEP+1
ν 0, the degrees of freedom for the null model, where ν 0=0 if PREY=0 and ν 0=1 otherwise.
FITSUM 4 NSTEP+1
Cp 0, a Cp-type statistic for the null model, where Cp 0=RSS 0 σ 2-n+2⁢ν 0.
FITSUM 5 NSTEP+1
σ 2, where σ 2=n-RSSK νK and K=NSTEP.
Although the Cp statistics described above are returned when IFAIL=112 they may not be meaningful due to the estimate σ 2 not being based on the saturated model.
17:   ROPT LROPT – REAL (KIND=nag_wp) arrayInput
On entry: optional parameters to control various aspects of the LARS algorithm.
The default value will be used for ROPT i if LROPT<i, therefore setting LROPT=0 will use the default values for all optional arguments and ROPT need not be set. The default value will also be used if an invalid value is supplied for a particular argument, for example, setting ROPT i=-1 will use the default value for argument i.
ROPT 1
The minimum step size that will be taken.
Default is 100×eps is used, where eps is the machine precision returned by X02AJF.
ROPT 2
General tolerance, used amongst other things, for comparing correlations.
Default is ROPT 1.
ROPT 3
If set to 1, parameter estimates are rescaled before being returned.
If set to 0, no rescaling is performed.
This argument has no effect when PRED=0 or 1.
Default is for the parameter estimates to be rescaled.
ROPT 4
If set to 1, it is assumed that the model contains an intercept during the model fitting process and when calculating the degrees of freedom.
If set to 0, no intercept is assumed.
This has no effect on the amount of preprocessing performed on Y.
Default is to treat the model as having an intercept when PREY=1 and as not having an intercept when PREY=0.
ROPT 5
As implemented, the LARS algorithm can either work directly with y and X, or it can work with the cross-product matrices, XT y and XT X. In most cases it is more efficient to work with the cross-product matrices. This flag allows you direct control over which method is used, however, the default value will usually be the best choice.
If ROPT 5=1, y and X are worked with directly.
If ROPT 5=0, the cross-product matrices are used.
Default is 1 when p≥500 and n<p and 0 otherwise.
Constraints:
  • ROPT 1>machine precision;
  • ROPT 2>machine precision;
  • ROPT 3=0 or 1;
  • ROPT 4=0 or 1;
  • ROPT 5=0 or 1.
18:   LROPT – INTEGERInput
On entry: length of the options array ROPT.
Constraint: 0≤LROPT≤5.
19:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, because for this routine the values of the output arguments may be useful even if IFAIL≠0 on exit, the recommended value is -1. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Note: G02MAF may return useful information for one or more of the following detected errors or warnings.
Errors or warnings detected by the routine:
IFAIL=11
On entry, MTYPE=value.
Constraint: MTYPE=1, 2, 3 or 4.
IFAIL=21
On entry, PRED=value.
Constraint: PRED=0, 1, 2 or 3.
IFAIL=31
On entry, PREY=value.
Constraint: PREY=0 or 1.
IFAIL=41
On entry, N=value.
Constraint: N≥1.
IFAIL=51
On entry, M=value.
Constraint: M≥1.
IFAIL=71
On entry, LDD=value and N=value.
Constraint: LDD≥N.
IFAIL=81
On entry, ISX value=value.
Constraint: ISX i=0 or 1 for all i.
IFAIL=82
On entry, all values of ISX are zero.
Constraint: at least one value of ISX must be nonzero.
IFAIL=91
On entry, LISX=value and M=value.
Constraint: LISX=0 or M.
IFAIL=111
On entry, MNSTEP=value.
Constraint: MNSTEP≥1.
IFAIL=112
Fitting process did not finish in MNSTEP steps. Try increasing the size of MNSTEP and supplying larger output arrays.
All output is returned as documented, up to step MNSTEP, however, σ and the Cp statistics may not be meaningful.
IFAIL=151
On entry, LDB=value and M=value.
Constraint: if LISX=0 then LDB≥M.
IFAIL=152
On entry, LDB=value and p=value.
Constraint: if LISX=M then LDB≥p.
IFAIL=161
σ 2 is approximately zero and hence the Cp-type criterion cannot be calculated. All other output is returned as documented.
IFAIL=162
νK=n, therefore σ has been set to a large value. Output is returned as documented.
IFAIL=163
Degenerate model, no variables added and NSTEP=0. Output is returned as documented.
IFAIL=181
On entry, LROPT=value.
Constraint: 0≤LROPT≤5.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

Not applicable.

8 Parallelism and Performance

G02MAF is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
G02MAF makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

G02MAF returns the parameter estimates at various points along the solution path of a LARS, LASSO or stagewise regression analysis. If the solution is required at a different set of points, for example when performing cross-validation, then G02MCF can be used.
For datasets with a large number of observations, n, it may be impractical to store the full X matrix in memory in one go. In such instances the cross-product matrices XT y and XT X can be calculated, using for example, multiple calls to G02BUF and G02BZF, and G02MBF called to perform the analysis.
The amount of workspace used by G02MAF depends on whether the cross-product matrices are being used internally (as controlled by ROPT). If the cross-product matrices are being used then G02MAF internally allocates approximately 2⁢p 2+4⁢p+max np elements of real storage compared to ⁢p 2+3⁢p+max np+2⁢n+n×p elements when X and y are used directly. In both cases approximately 5⁢p elements of integer storage are also used. If a forward linear stagewise analysis is performed than an additional p 2+5⁢p elements of real storage are required.

10 Example

This example performs a LARS on a simulated dataset with 20 observations and 6 independent variables.

10.1 Program Text

Program Text (g02mafe.f90)

10.2 Program Data

Program Data (g02mafe.d)

10.3 Program Results

Program Results (g02mafe.r)

This example plot shows the regression coefficients (βk) plotted against the scaled absolute sum of the parameter estimates (βk 1).
GnuplotProduced by GNUPLOT 4.6 patchlevel 3 −1 0 1 2 3 4 0 20 40 60 80 100 120 140 160 180 200 220 Parameter Estimates (βkj) ||βk||1 Example Program Parameter estimates for a LARS model fitted to a simulated dataset gnuplot_plot_1 βk1 gnuplot_plot_2 βk2 gnuplot_plot_3 βk3 gnuplot_plot_4 βk4 gnuplot_plot_5 βk5 gnuplot_plot_6 βk6
G02 Chapter Contents
G02 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


G02MBF : NAG Library, Mark 26

G02 Chapter Contents
G02 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

G02MBF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

G02MBF performs Least Angle Regression (LARS), forward stagewise linear regression or Least Absolute Shrinkage and Selection Operator (LASSO) using cross-product matrices.

2 Specification

SUBROUTINE G02MBF ( MTYPE, PRED, INTCPT, N, M, DTD, LDDTD, ISX, LISX, DTY, YTY, MNSTEP, IP, NSTEP, B, LDB, FITSUM, ROPT, LROPT, IFAIL)
INTEGER | MTYPE, PRED, INTCPT, N, M, LDDTD, ISX(LISX), LISX, MNSTEP, IP, NSTEP, LDB, LROPT, IFAIL
REAL (KIND=nag_wp) | DTD(LDDTD,*), DTY(M), YTY, B(LDB,*), FITSUM(6,MNSTEP+1), ROPT(LROPT)

3 Description

G02MBF implements the LARS algorithm of Efron et al. (2004) as well as the modifications needed to perform forward stagewise linear regression and fit LASSO and positive LASSO models.
Given a vector of n observed values, y = yi : i=1,2,…,n and an n×p design matrix X, where the jth column of X, denoted xj, is a vector of length n representing the jth independent variable xj, standardized such that ∑ i=1 n x ij =0 , and ∑ i=1 n x ij 2 =1 and a set of model parameters β to be estimated from the observed values, the LARS algorithm can be summarised as:
1. | Set k=1 and all coefficients to zero, that is β=0.
2. | Find the variable most correlated with y, say x j 1. Add x j 1 to the ‘most correlated’ set A. If p=1 go to 8.
3. | Take the largest possible step in the direction of x j 1 (i.e., increase the magnitude of β j 1) until some other variable, say x j 2, has the same correlation with the current residual, y-x j 1β j 1.
4. | Increment k and add x jk to A.
5. | If A=p go to 8.
6. | Proceed in the ‘least angle direction’, that is, the direction which is equiangular between all variables in A, altering the magnitude of the parameter estimates of those variables in A, until the kth variable, x jk, has the same correlation with the current residual.
7. | Go to 4.
8. | Let K=k.
As well as being a model selection process in its own right, with a small number of modifications the LARS algorithm can be used to fit the LASSO model of Tibshirani (1996), a positive LASSO model, where the independent variables enter the model in their defined direction, forward stagewise linear regression (Hastie et al. (2001)) and forward selection (Weisberg (1985)). Details of the required modifications in each of these cases are given in Efron et al. (2004).
The LASSO model of Tibshirani (1996) is given by
minimize α , βk∈ ℝp y- α- XT βk 2   subject to   βk 1 ≤tk
for all values of tk, where α=y-=n-1⁢∑ i=1 n yi. The positive LASSO model is the same as the standard LASSO model, given above, with the added constraint that
β kj ≥ 0 ,   j=1,2,…,p .
Unlike the standard LARS algorithm, when fitting either of the LASSO models, variables can be dropped as well as added to the set A. Therefore the total number of steps K is no longer bounded by p.
Forward stagewise linear regression is an iterative procedure of the form:
1. | Initialize k=1 and the vector of residuals r 0=y-α.
2. | For each j=1,2,…,p calculate cj=xjT r k-1. The value cj is therefore proportional to the correlation between the jth independent variable and the vector of previous residual values, rk.
3. | Calculate jk = argmax j cj , the value of j with the largest absolute value of cj.
4. | If c jk<ε then go to 7.
5. Update the residual values, with
rk = r k-1 + δ ⁢ ​ ​ sign c jk ⁢ x jk
where δ is a small constant and sign c jk=-1 when c jk<0 and 1 otherwise.
6. | Increment k and go to 2.
7. | Set K=k.
If the largest possible step were to be taken, that is δ=c jk then forward stagewise linear regression reverts to the standard forward selection method as implemented in G02EEF.
The LARS procedure results in K models, one for each step of the fitting process. In order to aid in choosing which is the most suitable Efron et al. (2004) introduced a Cp-type statistic given by
Cp k = y- XT βk 2 σ 2 -n+2⁢νk,
where νk is the approximate degrees of freedom for the kth step and
σ 2 = n-yT y νK .
One way of choosing a model is therefore to take the one with the smallest value of Cp k.

4 References

Efron B, Hastie T, Johnstone I and Tibshirani R (2004) Least Angle Regression The Annals of Statistics (Volume 32) 2 407–499
Hastie T, Tibshirani R and Friedman J (2001) The Elements of Statistical Learning: Data Mining, Inference and Prediction Springer (New York)
Tibshirani R (1996) Regression Shrinkage and Selection via the Lasso Journal of the Royal Statistics Society, Series B (Methodological) (Volume 58) 1 267–288
Weisberg S (1985) Applied Linear Regression Wiley

5 Arguments

1:   MTYPE – INTEGERInput
On entry: indicates the type of model to fit.
MTYPE=1
LARS is performed.
MTYPE=2
Forward linear stagewise regression is performed.
MTYPE=3
LASSO model is fit.
MTYPE=4
A positive LASSO model is fit.
Constraint: MTYPE=1, 2, 3 or 4.
2:   PRED – INTEGERInput
On entry: indicates the type of preprocessing to perform on the cross-products involving the independent variables, i.e., those supplied in DTD and DTY.
PRED=0
No preprocessing is performed.
PRED=2
Each independent variable is normalized, with the jth variable scaled by 1/xjT xj. The scaling factor used by variable j is returned in B j NSTEP+1.
Constraint: PRED=0 or 2.
3:   INTCPT – INTEGERInput
On entry: indicates the type of data preprocessing that was perform on the dependent variable, y, prior to calling this routine.
INTCPT=0
No preprocessing was performed.
INTCPT=1
The dependent variable, y, was mean centred.
Constraint: INTCPT=0 or 1.
4:   N – INTEGERInput
On entry: n, the number of observations.
Constraint: N≥1.
5:   M – INTEGERInput
On entry: m, the total number of independent variables.
Constraint: M≥1.
6:   DTD LDDTD* – REAL (KIND=nag_wp) arrayInput
Note: the second dimension of the array DTD must be at least M⁢M+1/2 if LDDTD=1, and at least M otherwise.
On entry: DT D, the cross-product matrix, which along with ISX, defines the design matrix cross-product XT X.
If LDDTD=1, DTD 1 i×i-1/2+j must contain the cross-product of the ith and jth variable, for i=1,2,…,M and j=1,2,…,M. That is the cross-product stacked by columns as returned by G02BUF, for example.
Otherwise DTD ij must contain the cross-product of the ith and jth variable, for i=1,2,…,M and j=1,2,…,M. It should be noted that, even though DT D is symmetric, the full matrix must be supplied.
The matrix specified in DTD must be a valid cross-products matrix.
7:   LDDTD – INTEGERInput
On entry: the first dimension of the array DTD as declared in the (sub)program from which G02MBF is called.
Constraint: LDDTD=1​ or ​LDDTD≥M.
8:   ISX LISX – INTEGER arrayInput
On entry: indicates which independent variables from DTD will be included in the design matrix, X.
If LISX=0, all variables are included in the design matrix and ISX is not referenced.
If LISX=M,, for j=1,2,…,M when ISX j must be set as follows:
ISX j=1
To indicate that the jth variable, as supplied in DTD, is included in the design matrix;
ISX j=0
To indicate that the jth variable, as supplied in DTD, is not included in the design matrix;
and p= ∑ j=1 m ISX j.
Constraint: if LISX=M, ISX j=0 or 1 and at least one value of ISX j≠0, for j=1,2,…,M.
9:   LISX – INTEGERInput
On entry: length of the ISX array.
Constraint: LISX=0 or M.
10:   DTY M – REAL (KIND=nag_wp) arrayInput
On entry: DT y, the cross-product between the dependent variable, y, and the independent variables D.
11:   YTY – REAL (KIND=nag_wp)Input
On entry: yT y, the sums of squares of the dependent variable.
Constraint: YTY>0.0.
12:   MNSTEP – INTEGERInput
On entry: the maximum number of steps to carry out in the model fitting process.
If MTYPE=1, i.e., a LARS is being performed, the maximum number of steps the algorithm will take is min p,n if INTCPT=0, otherwise min p,n-1.
If MTYPE=2, i.e., a forward linear stagewise regression is being performed, the maximum number of steps the algorithm will take is likely to be several orders of magnitude more and is no longer bound by p or n.
If MTYPE=3 or 4, i.e., a LASSO or positive LASSO model is being fit, the maximum number of steps the algorithm will take lies somewhere between that of the LARS and forward linear stagewise regression, again it is no longer bound by p or n.
Constraint: MNSTEP≥1.
13:   IP – INTEGEROutput
On exit: p, number of parameter estimates.
If LISX=0, p=M, i.e., the number of variables in DTD.
Otherwise p is the number of nonzero values in ISX.
14:   NSTEP – INTEGEROutput
On exit: K, the actual number of steps carried out in the model fitting process.
15:   B LDB* – REAL (KIND=nag_wp) arrayOutput
Note: the second dimension of the array B must be at least MNSTEP+1.
On exit: β the parameter estimates, with B jk=β kj, the parameter estimate for the jth variable, j=1,2,…,p at the kth step of the model fitting process, k=1,2,…,NSTEP.
By default, when PRED=2 the parameter estimates are rescaled prior to being returned. If the parameter estimates are required on the normalized scale, then this can be overridden via ROPT.
The values held in the remaining part of B depend on the type of preprocessing performed.
If ​PRED=0 B j NSTEP+1 = 1, if ​PRED=2 B j NSTEP+1 = 1/ xjT xj,
for j=1,2,…p.
16:   LDB – INTEGERInput
On entry: the first dimension of the array B as declared in the (sub)program from which G02MBF is called.
Constraint: LDB≥p, where p is the number of parameter estimates as described in IP.
17:   FITSUM 6 MNSTEP+1 – REAL (KIND=nag_wp) arrayOutput
On exit: summaries of the model fitting process. When k=1,2,…,NSTEP
FITSUM 1 k
βk 1, the sum of the absolute values of the parameter estimates for the kth step of the modelling fitting process. If PRED=2, the scaled parameter estimates are used in the summation.
FITSUM 2 k
RSSk, the residual sums of squares for the kth step, where RSSk= y- XT βk 2 .
FITSUM 3 k
νk, approximate degrees of freedom for the kth step.
FITSUM 4 k
Cp k, a Cp-type statistic for the kth step, where Cp k=RSSk σ 2-n+2⁢νk.
FITSUM 5 k
C^k, correlation between the residual at step k-1 and the most correlated variable not yet in the active set A, where the residual at step 0 is y.
FITSUM 6 k
γ^k, the step size used at step k.
In addition
FITSUM 1 NSTEP+1
0.
FITSUM 2 NSTEP+1
RSS 0, the residual sums of squares for the null model, where RSS 0=yT y.
FITSUM 3 NSTEP+1
ν 0, the degrees of freedom for the null model, where ν 0=0 if INTCPT=0 and ν 0=1 otherwise.
FITSUM 4 NSTEP+1
Cp 0, a Cp-type statistic for the null model, where Cp 0=RSS 0 σ 2-n+2⁢ν 0.
FITSUM 5 NSTEP+1
σ 2, where σ 2=n-RSSK νK and K=NSTEP.
Although the Cp statistics described above are returned when IFAIL=122 they may not be meaningful due to the estimate σ 2 not being based on the saturated model.
18:   ROPT LROPT – REAL (KIND=nag_wp) arrayInput
On entry: optional parameters to control various aspects of the LARS algorithm.
The default value will be used for ROPT i if LROPT<i, therefore setting LROPT=0 will use the default values for all optional arguments and ROPT need not be set. The default value will also be used if an invalid value is supplied for a particular argument, for example, setting ROPT i=-1 will use the default value for argument i.
ROPT 1
The minimum step size that will be taken.
Default is 100×eps is used, where eps is the machine precision returned by X02AJF.
ROPT 2
General tolerance, used amongst other things, for comparing correlations.
Default is ROPT 1.
ROPT 3
If set to 1 then parameter estimates are rescaled before being returned. If set to 0 then no rescaling is performed. This argument has no effect when PRED=0.
Default is for the parameter estimates to be rescaled.
Constraints:
  • ROPT 1>machine precision;
  • ROPT 2>machine precision.
19:   LROPT – INTEGERInput
On entry: length of the options array ROPT.
Constraint: 0≤LROPT≤3.
20:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, because for this routine the values of the output arguments may be useful even if IFAIL≠0 on exit, the recommended value is -1. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Note: G02MBF may return useful information for one or more of the following detected errors or warnings.
Errors or warnings detected by the routine:
IFAIL=11
On entry, MTYPE=value.
Constraint: MTYPE=1, 2, 3 or 4.
IFAIL=21
On entry, PRED=value.
Constraint: PRED=0 or 2.
IFAIL=31
On entry, INTCPT=value.
Constraint: INTCPT=0 or 1.
IFAIL=41
On entry, N=value.
Constraint: N≥1.
IFAIL=51
On entry, M=value.
Constraint: M≥1.
IFAIL=61
The cross-product matrix supplied in DTD is not symmetric.
IFAIL=62
On entry, DTD 1 value=value.
Constraint: diagonal elements of DT D must be positive.
On entry, i=value and DTD ii=value.
Constraint: diagonal elements of DT D must be positive.
IFAIL=71
On entry, LDDTD=value and M=value
Constraint: LDDTD=1​ or ​LDDTD≥M.
IFAIL=81
On entry, ISX value=value.
Constraint: ISX i=0 or 1 for all i.
IFAIL=82
On entry, all values of ISX are zero.
Constraint: at least one value of ISX must be nonzero.
IFAIL=91
On entry, LISX=value and M=value.
Constraint: LISX=0 or M.
IFAIL=111
On entry, YTY=value.
Constraint: YTY>0.0.
IFAIL=112
A negative value for the residual sums of squares was obtained. Check the values of DTD, DTY and YTY.
IFAIL=121
On entry, MNSTEP=value.
Constraint: MNSTEP≥1.
IFAIL=122
Fitting process did not finished in MNSTEP steps. Try increasing the size of MNSTEP and supplying larger output arrays.
All output is returned as documented, up to step MNSTEP, however, σ and the Cp statistics may not be meaningful.
IFAIL=161
On entry, LDB=value and M=value.
Constraint: if LISX=0 then LDB≥M.
IFAIL=162
On entry, LDB=value and p=value.
Constraint: if LISX=M, LDB≥p.
IFAIL=171
σ 2 is approximately zero and hence the Cp-type criterion cannot be calculated. All other output is returned as documented.
IFAIL=172
νK=n, therefore sigma has been set to a large value. Output is returned as documented.
IFAIL=173
Degenerate model, no variables added and NSTEP=0. Output is returned as documented.
IFAIL=191
On entry, LROPT=value.
Constraint: 0≤LROPT≤3.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

Not applicable.

8 Parallelism and Performance

G02MBF is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
G02MBF makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The solution path to the LARS, LASSO and stagewise regression analysis is a continuous, piecewise linear. G02MBF returns the parameter estimates at various points along this path. G02MCF can be used to obtain estimates at different points along the path.
If you have the raw data values, that is D and y, then G02MAF can be used instead of G02MBF.

10 Example

This example performs a LARS on a simulated dataset with 20 observations and 6 independent variables.
The example uses G02BUF to get the cross-products of the augmented matrix D y. The first m⁢m+1/2 elements of the (column packed) cross-products matrix returned therefore contain the elements of DT D, the next m elements contain DT y and the last element yT y.

10.1 Program Text

Program Text (g02mbfe.f90)

10.2 Program Data

Program Data (g02mbfe.d)

10.3 Program Results

Program Results (g02mbfe.r)

This example plot shows the regression coefficients (βk) plotted against the scaled absolute sum of the parameter estimates (βk 1).
GnuplotProduced by GNUPLOT 4.6 patchlevel 3 −1 0 1 2 3 4 0 20 40 60 80 100 120 140 160 180 200 220 Parameter Estimates (βkj) ||βk||1 Example Program Parameter estimates for a LARS model fitted to a simulated dataset gnuplot_plot_1 βk1 gnuplot_plot_2 βk2 gnuplot_plot_3 βk3 gnuplot_plot_4 βk4 gnuplot_plot_5 βk5 gnuplot_plot_6 βk6
G02 Chapter Contents
G02 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


G02MCF : NAG Library, Mark 26

G02 Chapter Contents
G02 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

G02MCF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

G02MCF calculates additional parameter estimates following Least Angle Regression (LARS), forward stagewise linear regression or Least Absolute Shrinkage and Selection Operator (LASSO) as performed by G02MAF and G02MBF.

2 Specification

SUBROUTINE G02MCF ( NSTEP, IP, B, LDB, FITSUM, KTYPE, NK, LNK, NB, LDNB, IFAIL)
INTEGER | NSTEP, IP, LDB, KTYPE, LNK, LDNB, IFAIL
REAL (KIND=nag_wp) | B(LDB,*), FITSUM(6,NSTEP+1), NK(LNK), NB(LDNB,*)

3 Description

G02MAF and G02MBF fit either a LARS, forward stagewise linear regression, LASSO or positive LASSO model to a vector of n observed values, y = yi : i=1,2,…,n and an n×p design matrix X, where the jth column of X is given by the jth independent variable xj. The models are fit using the LARS algorithm of Efron et al. (2004).
GnuplotProduced by GNUPLOT 4.6 patchlevel 3 −1 0 1 2 3 4 0 20 40 60 80 100 120 140 160 180 200 220 Parameter Estimates (βkj) ||βk||1 gnuplot_plot_1 βk1 gnuplot_plot_2 βk2 gnuplot_plot_3 βk3 gnuplot_plot_4 βk4 gnuplot_plot_5 βk5 gnuplot_plot_6 βk6
Figure 1
The full solution path for all four of these models follow a similar pattern where the parameter estimate for a given variable is piecewise linear. One such path, for a LARS model with six variables p=6 can be seen in Figure 1. Both G02MAF and G02MBF return the vector of p parameter estimates, βk, at K points along this path (so k=1,2,…,K). Each point corresponds to a step of the LARS algorithm. The number of steps taken depends on the model being fitted. In the case of a LARS model, K=p and each step corresponds to a new variable being included in the model. In the case of the LASSO models, each step corresponds to either a new variable being included in the model or an existing variable being removed from the model; the value of K is therefore no longer bound by the number of parameters. For forward stagewise linear regression, each step no longer corresponds to the addition or removal of a variable; therefore the number of possible steps is often markedly greater than for a corresponding LASSO model.
G02MCF uses the piecewise linear nature of the solution path to predict the parameter estimates, β~, at a different point on this path. The location of the solution can either be defined in terms of a (fractional) step number or a function of the L 1 norm of the parameter estimates.

4 References

Efron B, Hastie T, Johnstone I and Tibshirani R (2004) Least Angle Regression The Annals of Statistics (Volume 32) 2 407–499
Hastie T, Tibshirani R and Friedman J (2001) The Elements of Statistical Learning: Data Mining, Inference and Prediction Springer (New York)
Tibshirani R (1996) Regression Shrinkage and Selection via the Lasso Journal of the Royal Statistics Society, Series B (Methodological) (Volume 58) 1 267–288
Weisberg S (1985) Applied Linear Regression Wiley

5 Arguments

1:   NSTEP – INTEGERInput
On entry: K, the number of steps carried out in the model fitting process, as returned by G02MAF and G02MBF.
Constraint: NSTEP≥0.
2:   IP – INTEGERInput
On entry: p, number of parameter estimates, as returned by G02MAF and G02MBF.
Constraint: IP≥1.
3:   B LDB* – REAL (KIND=nag_wp) arrayInput
Note: the second dimension of the array B must be at least NSTEP+1.
On entry: β the parameter estimates, as returned by G02MAF and G02MBF, with B jk=β kj, the parameter estimate for the jth variable, for j=1,2,…,p, at the kth step of the model fitting process.
Constraint: B should be unchanged since the last call to G02MAF or G02MBF.
4:   LDB – INTEGERInput
On entry: the first dimension of the array B as declared in the (sub)program from which G02MCF is called.
Constraint: LDB≥IP.
5:   FITSUM 6 NSTEP+1 – REAL (KIND=nag_wp) arrayInput
On entry: summaries of the model fitting process, as returned by G02MAF and G02MBF.
Constraint: FITSUM should be unchanged since the last call to G02MAF or G02MBF..
6:   KTYPE – INTEGERInput
On entry: indicates what target values are held in NK.
KTYPE=1
NK holds (fractional) LARS step numbers.
KTYPE=2
NK holds values for L 1 norm of the (scaled) parameters.
KTYPE=3
NK holds ratios with respect to the largest (scaled) L 1 norm.
KTYPE=4
NK holds values for the L 1 norm of the (unscaled) parameters.
KTYPE=5
NK holds ratios with respect to the largest (unscaled) L 1 norm.
If G02MAF was called with PRED=0 or 1 or G02MBF was called with PRED=0 then the model fitting routine did not rescale the independent variables, X, prior to fitting the model and therefore there is no difference between KTYPE=2 or 3 and KTYPE=4 or 5.
Constraint: KTYPE=1, 2, 3, 4 or 5.
7:   NK LNK – REAL (KIND=nag_wp) arrayInput
On entry: target values used for predicting the new set of parameter estimates.
Constraints:
  • if KTYPE=1, 0≤NK i≤NSTEP, for i=1,2,…,LNK;
  • if KTYPE=2, 0≤NK i≤FITSUM 1 NSTEP, for i=1,2,…,LNK;
  • if KTYPE=3 or 5, 0≤NK i≤1, for i=1,2,…,LNK;
  • if KTYPE=4, 0≤NK i≤βK 1, for i=1,2,…,LNK.
8:   LNK – INTEGERInput
On entry: number of values supplied in NK.
Constraint: LNK≥1.
9:   NB LDNB* – REAL (KIND=nag_wp) arrayOutput
Note: the second dimension of the array NB must be at least LNK.
On exit: β~ the predicted parameter estimates, with B ji=β~ij, the parameter estimate for variable j, j=1,2,…,p at the point in the fitting process associated with NK i, i=1,2,…,LNK.
10:   LDNB – INTEGERInput
On entry: the first dimension of the array NB as declared in the (sub)program from which G02MCF is called.
Constraint: LDNB≥IP.
11:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, because for this routine the values of the output arguments may be useful even if IFAIL≠0 on exit, the recommended value is -1. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Note: G02MCF may return useful information for one or more of the following detected errors or warnings.
Errors or warnings detected by the routine:
IFAIL=11
On entry, NSTEP=value.
Constraint: NSTEP≥0.
IFAIL=21
On entry, IP=value.
Constraint: IP≥1.
IFAIL=31
B has been corrupted since the last call to G02MAF or G02MBF.
IFAIL=41
On entry, LDB=value and IP=value
Constraint: LDB≥IP.
IFAIL=51
FITSUM has been corrupted since the last call to G02MAF or G02MBF.
IFAIL=61
On entry, KTYPE=value.
Constraint: KTYPE=1, 2, 3, 4 or 5.
IFAIL=71
On entry, KTYPE=1, NK value=value and NSTEP=value
Constraint: 0≤NK i≤NSTEP for all i.
IFAIL=72
On entry, KTYPE=2, NK value=value, NSTEP=value and FITSUM 1 NSTEP=value.
Constraint: 0≤NK i≤FITSUM 1 NSTEP for all i.
IFAIL=73
On entry, KTYPE=3 or 5, NK value=value.
Constraint: 0≤NK i≤1 for all i.
IFAIL=74
On entry, KTYPE=4, NK value=value and βK 1=value
Constraint: 0≤NK i≤βK 1 for all i.
IFAIL=81
On entry, LNK=value.
Constraint: LNK≥1.
IFAIL=101
On entry, LDNB=value and IP=value.
Constraint: LDNB≥IP.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

Not applicable.

8 Parallelism and Performance

G02MCF is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
G02MCF makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

None.

10 Example

This example performs a LARS on a set a simulated dataset with 20 observations and 6 independent variables.
Additional parameter estimates are obtained corresponding to a LARS step number of 0.2,1.2,3.2,4.5 and 5.2. Where, for example, 4.5 corresponds to the solution halfway between that obtained at step 4 and that obtained at step 5.

10.1 Program Text

Program Text (g02mcfe.f90)

10.2 Program Data

Program Data (g02mcfe.d)

10.3 Program Results

Program Results (g02mcfe.r)

G02 Chapter Contents
G02 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


G02QFF : NAG Library, Mark 26

G02 Chapter Contents
G02 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

G02QFF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

G02QFF performs a multiple linear quantile regression, returning the parameter estimates and associated confidence limits based on an assumption of Normal, independent, identically distributed errors. G02QFF is a simplified version of G02QGF.

2 Specification

SUBROUTINE G02QFF ( N, M, X, Y, NTAU, TAU, DF, B, BL, BU, INFO, IFAIL)
INTEGER | N, M, NTAU, INFO(NTAU), IFAIL
REAL (KIND=nag_wp) | X(N,M), Y(N), TAU(NTAU), DF, B(M,NTAU), BL(M,NTAU), BU(M,NTAU)

3 Description

Given a vector of n observed values, y = y i : i = 1, 2, …, n , an n×p design matrix X, a column vector, x, of length p holding the ith row of X and a quantile τ ∈ 0 , 1 , G02QFF estimates the p-element vector β as the solution to
minimize β ∈ ℝ p ∑ i=1 n ρ τ y i - xiT β (1)
where ρ τ is the piecewise linear loss function ρ τ z = z ⁢ τ - I z < 0 , and I z < 0 is an indicator function taking the value 1 if z<0 and 0 otherwise.
G02QFF assumes Normal, independent, identically distributed (IID) errors and calculates the asymptotic covariance matrix from
Σ = τ 1 - τ n s τ 2 XT X -1
where s is the sparsity function, which is estimated from the residuals, ri = yi - xiT ⁢ β^ (see Koenker (2005)).
Given an estimate of the covariance matrix, Σ^, lower, β^L, and upper, β^U, limits for a 95% confidence interval are calculated for each of the p parameters, via
β^ Li = β^ i - t n-p , 0.975 Σ^ ii , β^ Ui = β^ i + t n-p , 0.975 Σ^ ii
where t n-p,0.975 is the 97.5 percentile of the Student's t distribution with n-k degrees of freedom, where k is the rank of the cross-product matrix XT X.
Further details of the algorithms used by G02QFF can be found in the documentation for G02QGF.

4 References

Koenker R (2005) Quantile Regression Econometric Society Monographs, Cambridge University Press, New York

5 Arguments

1:   N – INTEGERInput
On entry: n, the number of observations in the dataset.
Constraint: N≥2.
2:   M – INTEGERInput
On entry: p, the number of variates in the model.
Constraint: 1≤M<N.
3:   X NM – REAL (KIND=nag_wp) arrayInput
On entry: X, the design matrix, with the ith value for the jth variate supplied in X ij, for i=1,2,…,N and j=1,2,…,M.
4:   Y N – REAL (KIND=nag_wp) arrayInput
On entry: y, the observations on the dependent variable.
5:   NTAU – INTEGERInput
On entry: the number of quantiles of interest.
Constraint: NTAU≥1.
6:   TAU NTAU – REAL (KIND=nag_wp) arrayInput
On entry: the vector of quantiles of interest. A separate model is fitted to each quantile.
Constraint: ε<TAU l<1-ε where ε is the machine precision returned by X02AJF, for l=1,2,…,NTAU.
7:   DF – REAL (KIND=nag_wp)Output
On exit: the degrees of freedom given by n-k, where n is the number of observations and k is the rank of the cross-product matrix XT X.
8:   B MNTAU – REAL (KIND=nag_wp) arrayOutput
On exit: β^, the estimates of the parameters of the regression model, with B jl containing the coefficient for the variable in column j of X, estimated for τ=TAU l.
9:   BL MNTAU – REAL (KIND=nag_wp) arrayOutput
On exit: β^L, the lower limit of a 95% confidence interval for β^, with BL jl holding the lower limit associated with B jl.
10:   BU MNTAU – REAL (KIND=nag_wp) arrayOutput
On exit: β^U, the upper limit of a 95% confidence interval for β^, with BU jl holding the upper limit associated with B jl.
11:   INFO NTAU – INTEGER arrayOutput
On exit: INFO l holds additional information concerning the model fitting and confidence limit calculations when τ=TAU l.
Code | Warning
0 | Model fitted and confidence limits calculated successfully.
1 | The routine did not converge whilst calculating the parameter estimates. The returned values are based on the estimate at the last iteration.
2 | A singular matrix was encountered during the optimization. The model was not fitted for this value of τ.
8 | The routine did not converge whilst calculating the confidence limits. The returned limits are based on the estimate at the last iteration.
16 | Confidence limits for this value of τ could not be calculated. The returned upper and lower limits are set to a large positive and large negative value respectively.
It is possible for multiple warnings to be applicable to a single model. In these cases the value returned in INFO is the sum of the corresponding individual nonzero warning codes.
12:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=11
On entry, N=value.
Constraint: N≥2.
IFAIL=21
On entry, M=value and N=value.
Constraint: 1≤M<N.
IFAIL=51
On entry, NTAU=value.
Constraint: NTAU≥1.
IFAIL=61
On entry, TAU value=value is invalid.
IFAIL=111
A potential problem occurred whilst fitting the model(s).
Additional information has been returned in INFO.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

Not applicable.

8 Parallelism and Performance

G02QFF is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
G02QFF makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

Calling G02QFF is equivalent to calling G02QGF with
  • SORDER=1,
  • INTCPT='N',
  • WEIGHT='U',
  • LDDAT=N,
  • setting each element of ISX to 1,
  • IP=M,
  • Interval Method=IID, and
  • Significance Level=0.95.

10 Example

A quantile regression model is fitted to Engels 1857 study of household expenditure on food. The model regresses the dependent variable, household food expenditure, against household income. An intercept is included in the model by augmenting the dataset with a column of ones.

10.1 Program Text

Program Text (g02qffe.f90)

10.2 Program Data

Program Data (g02qffe.d)

10.3 Program Results

Program Results (g02qffe.r)

GnuplotProduced by GNUPLOT 4.6 patchlevel 3 0 500 1000 1500 2000 0 500 1000 1500 2000 2500 3000 3500 4000 4500 5000 Household Food Expenditure Household Income Example Program Quantile Regression - Simple Interface Engels 1857 Study of Household Expenditure on Food gnuplot_plot_1 gnuplot_plot_2 τ = 0.10 gnuplot_plot_3 τ = 0.25 gnuplot_plot_4 τ = 0.50 gnuplot_plot_5 τ = 0.75 gnuplot_plot_6 τ = 0.90
G02 Chapter Contents
G02 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


G02QGF : NAG Library, Mark 26

G02 Chapter Contents
G02 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

G02QGF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.
Note: this routine uses optional parameters to define choices in the problem specification and in the details of the algorithm. If you wish to use default settings for all of the optional parameters, you need only read Sections 1 to 10 of this document. If, however, you wish to reset some or all of the settings please refer to Section 11 for a detailed description of the algorithm, to Section 12 for a detailed description of the specification of the optional parameters and to Section 13 for a detailed description of the monitoring information produced by the routine.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results
▸▿ 11 Algorithmic Details
▸▿ 11.1 Interior Point Algorithm
11.1.1 Central path
11.1.2 Affine scaling step
11.1.3 Nonlinearity Adjustment
11.1.4 Update and convergence
11.1.5 Additional information
11.2 Calculation of Covariance Matrix
▸▿ 12 Optional Parameters
12.1 Description of the Optional Parameters
13 Description of Monitoring Information

1 Purpose

G02QGF performs a multiple linear quantile regression. Parameter estimates and, if required, confidence limits, covariance matrices and residuals are calculated. G02QGF may be used to perform a weighted quantile regression. A simplified interface for G02QGF is provided by G02QFF.

2 Specification

SUBROUTINE G02QGF ( SORDER, INTCPT, WEIGHT, N, M, DAT, LDDAT, ISX, IP, Y, WT, NTAU, TAU, DF, B, BL, BU, CH, RES, IOPTS, OPTS, STATE, INFO, IFAIL)
INTEGER | SORDER, N, M, LDDAT, ISX(M), IP, NTAU, IOPTS(*), STATE(*), INFO(NTAU), IFAIL
REAL (KIND=nag_wp) | DAT(LDDAT,*), Y(N), WT(*), TAU(NTAU), DF, B(IP,NTAU), BL(IP,*), BU(IP,*), CH(IP,IP,*), RES(N,*), OPTS(*)
CHARACTER(1) | INTCPT, WEIGHT

3 Description

Given a vector of n observed values, y = y i : i = 1, 2, …, n , an n×p design matrix X, a column vector, x, of length p holding the ith row of X and a quantile τ ∈ 0 , 1 , G02QGF estimates the p-element vector β as the solution to
minimize β ∈ ℝ p ∑ i=1 n ρ τ y i - xiT β (1)
where ρ τ is the piecewise linear loss function ρ τ z = z ⁢ τ - I z < 0 , and I z < 0 is an indicator function taking the value 1 if z<0 and 0 otherwise. Weights can be incorporated by replacing X and y with W⁢X and W⁢y respectively, where W is an n×n diagonal matrix. Observations with zero weights can either be included or excluded from the analysis; this is in contrast to least squares regression where such observations do not contribute to the objective function and are therefore always dropped.
G02QGF uses the interior point algorithm of Portnoy and Koenker (1997), described briefly in Section 11, to obtain the parameter estimates β^, for a given value of τ.
Under the assumption of Normally distributed errors, Koenker (2005) shows that the limiting covariance matrix of β^-β has the form
Σ = τ 1 - τ n H n -1 J n H n -1
where Jn = n-1 ⁢ ∑ i=1 n x i xiT and Hn is a function of τ, as described below. Given an estimate of the covariance matrix, Σ^, lower (β^L) and upper (β^U) limits for an 100×α% confidence interval can be calculated for each of the p parameters, via
β^ Li = β^ i - t n-p , 1 + α / 2 Σ^ ii , β^ Ui = β^ i + t n-p , 1 + α / 2 Σ^ ii
where t n-p,0.975 is the 97.5 percentile of the Student's t distribution with n-k degrees of freedom, where k is the rank of the cross-product matrix XT X.
Four methods for estimating the covariance matrix, Σ, are available:
(i) Independent, identically distributed (IID) errors
Under an assumption of IID errors the asymptotic relationship for Σ simplifies to
Σ = τ 1 - τ n s τ 2 XT X -1
where s is the sparsity function. G02QGF estimates s τ from the residuals, ri = yi - xiT ⁢ β^ and a bandwidth hn.
(ii) Powell Sandwich
Powell (1991) suggested estimating the matrix Hn by a kernel estimator of the form
H^ n = n cn -1 ∑ i=1 n K r i c n ⁢ xi xiT
where K is a kernel function and cn satisfies lim n→∞ cn → 0 and lim n→∞ n cn → ∞ . When the Powell method is chosen, G02QGF uses a Gaussian kernel (i.e., K=ϕ) and sets
cn = min σr, q r 3 - q r 1 / 1.34 × Φ-1 τ + hn - Φ-1 τ - hn
where hn is a bandwidth, σr,q r 1 and q r 3 are, respectively, the standard deviation and the 25% and 75% quantiles for the residuals, ri.
(iii) Hendricks–Koenker Sandwich
Koenker (2005) suggested estimating the matrix Hn using
H^ n = n-1 ∑ i=1 n 2 ⁢ hn xiT β^ τ + hn - β^ τ - hn ⁢ xi xiT
where hn is a bandwidth and β^τ+hn denotes the parameter estimates obtained from a quantile regression using the τ+hnth quantile. Similarly with β^τ-hn.
(iv) Bootstrap
The last method uses bootstrapping to either estimate a covariance matrix or obtain confidence intervals for the parameter estimates directly. This method therefore does not assume Normally distributed errors. Samples of size n are taken from the paired data yi,xi (i.e., the independent and dependent variables are sampled together). A quantile regression is then fitted to each sample resulting in a series of bootstrap estimates for the model parameters, β. A covariance matrix can then be calculated directly from this series of values. Alternatively, confidence limits, β^L and β^U, can be obtained directly from the 1-α/2 and 1+α/2 sample quantiles of the bootstrap estimates.
Further details of the algorithms used to calculate the covariance matrices can be found in Section 11.
All three asymptotic estimates of the covariance matrix require a bandwidth, hn. Two alternative methods for determining this are provided:
(i) Sheather–Hall
hn = 1.5 ⁢ Φ-1 αb ϕ Φ-1 τ 2 n ⁢ 2⁢ Φ-1 τ + 1 13
for a user-supplied value αb,
(ii) Bofinger
hn = 4.5 ⁢ ϕ Φ-1 τ 4 n ⁢ 2⁢ Φ-1 τ + 1 2 15
G02QGF allows optional arguments to be supplied via the IOPTS and OPTS arrays (see Section 12 for details of the available options). Prior to calling G02QGF the optional parameter arrays, IOPTS and OPTS must be initialized by calling G02ZKF with OPTSTR set to Initialize=G02QGF (see Section 12 for details on the available options). If bootstrap confidence limits are required (Interval Method=BOOTSTRAP XY) then one of the random number initialization routines G05KFF (for a repeatable analysis) or G05KGF (for an unrepeatable analysis) must also have been previously called.

4 References

Koenker R (2005) Quantile Regression Econometric Society Monographs, Cambridge University Press, New York
Mehrotra S (1992) On the implementation of a primal-dual interior point method SIAM J. Optim. 2 575–601
Nocedal J and Wright S J (1999) Numerical Optimization Springer Series in Operations Research, Springer, New York
Portnoy S and Koenker R (1997) The Gaussian hare and the Laplacian tortoise: computability of squared-error versus absolute error estimators Statistical Science 4 279–300
Powell J L (1991) Estimation of monotonic regression models under quantile restrictions Nonparametric and Semiparametric Methods in Econometrics Cambridge University Press, Cambridge

5 Arguments

1:   SORDER – INTEGERInput
On entry: determines the storage order of variates supplied in DAT.
Constraint: SORDER=1 or 2.
2:   INTCPT – CHARACTER(1)Input
On entry: indicates whether an intercept will be included in the model. The intercept is included by adding a column of ones as the first column in the design matrix, X.
INTCPT='Y'
An intercept will be included in the model.
INTCPT='N'
An intercept will not be included in the model.
Constraint: INTCPT='N' or 'Y'.
3:   WEIGHT – CHARACTER(1)Input
On entry: indicates if weights are to be used.
WEIGHT='W'
A weighted regression model is fitted to the data using weights supplied in array WT.
WEIGHT='U'
An unweighted regression model is fitted to the data and array WT is not referenced.
Constraint: WEIGHT='U' or 'W'.
4:   N – INTEGERInput
On entry: the total number of observations in the dataset. If no weights are supplied, or no zero weights are supplied or observations with zero weights are included in the model then N=n. Otherwise N=n+ the number of observations with zero weights.
Constraint: N≥2.
5:   M – INTEGERInput
On entry: m, the total number of variates in the dataset.
Constraint: M≥0.
6:   DAT LDDAT* – REAL (KIND=nag_wp) arrayInput
Note: the second dimension of the array DAT must be at least M if SORDER=1 and at least N if SORDER=2.
On entry: the ith value for the jth variate, for i=1,2,…,N and j=1,2,…,M, must be supplied in
  • DAT ij if SORDER=1, and
  • DAT ji if SORDER=2.
The design matrix X is constructed from DAT, ISX and INTCPT.
7:   LDDAT – INTEGERInput
On entry: the first dimension of the array DAT as declared in the (sub)program from which G02QGF is called.
Constraints:
  • if SORDER=1, LDDAT≥N;
  • otherwise LDDAT≥M.
8:   ISX M – INTEGER arrayInput
On entry: indicates which independent variables are to be included in the model.
ISX j=0
The jth variate, supplied in DAT, is not included in the regression model.
ISX j=1
The jth variate, supplied in DAT, is included in the regression model.
Constraints:
  • ISX j=0 or 1, for j=1,2,…,M;
  • if INTCPT='Y', exactly IP-1 values of ISX must be set to 1;
  • if INTCPT='N', exactly IP values of ISX must be set to 1.
9:   IP – INTEGERInput
On entry: p, the number of independent variables in the model, including the intercept, see INTCPT, if present.
Constraints:
  • 1≤IP<N;
  • if INTCPT='Y', 1≤IP≤M+1;
  • if INTCPT='N', 1≤IP≤M.
10:   Y N – REAL (KIND=nag_wp) arrayInput
On entry: y, the observations on the dependent variable.
11:   WT* – REAL (KIND=nag_wp) arrayInput
Note: the dimension of the array WT must be at least N if WEIGHT='W'.
On entry: if WEIGHT='W', WT must contain the diagonal elements of the weight matrix W. Otherwise WT is not referenced.
When
Drop Zero Weights=YES
If WT i=0.0, the ith observation is not included in the model, in which case the effective number of observations, n, is the number of observations with nonzero weights. If Return Residuals=YES, the values of RES will be set to zero for observations with zero weights.
Drop Zero Weights=NO
All observations are included in the model and the effective number of observations is N, i.e., n=N.
Constraints:
  • If WEIGHT='W', WT i≥0.0, for i=1,2,…,N;
  • The effective number of observations ≥2.
12:   NTAU – INTEGERInput
On entry: the number of quantiles of interest.
Constraint: NTAU≥1.
13:   TAU NTAU – REAL (KIND=nag_wp) arrayInput
On entry: the vector of quantiles of interest. A separate model is fitted to each quantile.
Constraint: ε<TAU j<1-ε where ε is the machine precision returned by X02AJF, for j=1,2,…,NTAU.
14:   DF – REAL (KIND=nag_wp)Output
On exit: the degrees of freedom given by n-k, where n is the effective number of observations and k is the rank of the cross-product matrix XT X.
15:   B IPNTAU – REAL (KIND=nag_wp) arrayInput/Output
On entry: if Calculate Initial Values=NO, B il must hold an initial estimates for β^i, for i=1,2,…,IP and l=1,2,…,NTAU. If Calculate Initial Values=YES, B need not be set.
On exit: B il, for i=1,2,…,IP, contains the estimates of the parameters of the regression model, β^, estimated for τ=TAU l.
If INTCPT='Y', B 1 l will contain the estimate corresponding to the intercept and B i+1 l will contain the coefficient of the jth variate contained in DAT, where ISX j is the ith nonzero value in the array ISX.
If INTCPT='N', B il will contain the coefficient of the jth variate contained in DAT, where ISX j is the ith nonzero value in the array ISX.
16:   BL IP* – REAL (KIND=nag_wp) arrayOutput
Note: the second dimension of the array BL must be at least NTAU if Interval Method≠NONE.
On exit: if Interval Method≠NONE, BL il contains the lower limit of an 100×α% confidence interval for B il, for i=1,2,…,IP and l=1,2,…,NTAU.
If Interval Method=NONE, BL is not referenced.
The method used for calculating the interval is controlled by the optional parameters Interval Method and Bootstrap Interval Method. The size of the interval, α, is controlled by the optional parameter Significance Level.
17:   BU IP* – REAL (KIND=nag_wp) arrayOutput
Note: the second dimension of the array BU must be at least NTAU if Interval Method≠NONE.
On exit: if Interval Method≠NONE, BU il contains the upper limit of an 100×α% confidence interval for B il, for i=1,2,…,IP and l=1,2,…,NTAU.
If Interval Method=NONE, BU is not referenced.
The method used for calculating the interval is controlled by the optional parameters Interval Method and Bootstrap Interval Method. The size of the interval, α is controlled by the optional parameter Significance Level.
18:   CH IPIP* – REAL (KIND=nag_wp) arrayOutput
Note: the last dimension of the array CH must be at least NTAU if Interval Method≠NONE and Matrix Returned=COVARIANCE and at least NTAU+1 if Interval Method≠NONE, IID or BOOTSTRAP XY and Matrix Returned=H INVERSE.
On exit: depending on the supplied optional parameters, CH will either not be referenced, hold an estimate of the upper triangular part of the covariance matrix, Σ, or an estimate of the upper triangular parts of n⁢Jn and n-1⁢Hn-1.
If Interval Method=NONE or Matrix Returned=NONE, CH is not referenced.
If Interval Method=BOOTSTRAP XY or IID and Matrix Returned=H INVERSE, CH is not referenced.
Otherwise, for i,j=1,2,…,IP,j≥i and l=1,2,…,NTAU:
  • If Matrix Returned=COVARIANCE, CH ijl holds an estimate of the covariance between B il and B jl.
  • If Matrix Returned=H INVERSE, CH ij 1 holds an estimate of the i,jth element of n⁢Jn and CH ij l+1 holds an estimate of the i,jth element of n-1⁢Hn-1, for τ=TAU l.
The method used for calculating Σ and Hn-1 is controlled by the optional parameter Interval Method.
19:   RES N* – REAL (KIND=nag_wp) arrayOutput
Note: the second dimension of the array RES must be at least NTAU if Return Residuals=YES.
On exit: if Return Residuals=YES, RES il holds the (weighted) residuals, ri, for τ=TAU l, for i=1,2,…,N and l=1,2,…,NTAU.
If WEIGHT='W' and Drop Zero Weights=YES, the value of RES will be set to zero for observations with zero weights.
If Return Residuals=NO, RES is not referenced.
20:   IOPTS* – INTEGER arrayCommunication Array
Note: the dimension of this array is dictated by the requirements of associated functions that must have been previously called. This array must be the same array passed as argument IOPTS in the previous call to G02ZKF.
On entry: optional parameter array, as initialized by a call to G02ZKF.
21:   OPTS* – REAL (KIND=nag_wp) arrayCommunication Array
Note: the dimension of this array is dictated by the requirements of associated functions that must have been previously called. This array must be the same array passed as argument OPTS in the previous call to G02ZKF.
On entry: optional parameter array, as initialized by a call to G02ZKF.
22:   STATE* – INTEGER arrayCommunication Array
Note: the actual argument supplied must be the array STATE supplied to the initialization routines G05KFF or G05KGF.
The actual argument supplied must be the array STATE supplied to the initialization routines G05KFF or G05KGF.
If Interval Method=BOOTSTRAP XY, STATE contains information about the selected random number generator. Otherwise STATE is not referenced.
23:   INFO NTAU – INTEGER arrayOutput
On exit: INFO i holds additional information concerning the model fitting and confidence limit calculations when τ=TAU i.
Code | Warning
0 | Model fitted and confidence limits (if requested) calculated successfully
1 | The routine did not converge. The returned values are based on the estimate at the last iteration. Try increasing Iteration Limit whilst calculating the parameter estimates or relaxing the definition of convergence by increasing Tolerance.
2 | A singular matrix was encountered during the optimization. The model was not fitted for this value of τ.
4 | Some truncation occurred whilst calculating the confidence limits for this value of τ. See Section 11 for details. The returned upper and lower limits may be narrower than specified.
8 | The routine did not converge whilst calculating the confidence limits. The returned limits are based on the estimate at the last iteration. Try increasing Iteration Limit.
16 | Confidence limits for this value of τ could not be calculated. The returned upper and lower limits are set to a large positive and large negative value respectively as defined by the optional parameter Big.
It is possible for multiple warnings to be applicable to a single model. In these cases the value returned in INFO is the sum of the corresponding individual nonzero warning codes.
24:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=11
On entry, SORDER=value.
Constraint: SORDER=1 or 2.
IFAIL=21
On entry, INTCPT=value was an illegal value.
IFAIL=31
On entry, WEIGHT had an illegal value.
IFAIL=41
On entry, N=value.
Constraint: N≥2.
IFAIL=51
On entry, M=value.
Constraint: M≥0.
IFAIL=71
On entry, LDDAT=value and N=value.
Constraint: LDDAT≥N.
IFAIL=72
On entry, LDDAT=value and M=value.
Constraint: LDDAT≥M.
IFAIL=81
On entry, ISX value=value.
Constraint: ISX i=0 or 1 for all i.
IFAIL=91
On entry, IP=value and N=value.
Constraint: 1≤IP<N.
IFAIL=92
On entry, IP is not consistent with ISX or INTCPT: IP=value, expected value=value.
IFAIL=111
On entry, WT value=value.
Constraint: WT i≥0.0 for all i.
IFAIL=112
On entry, effective number of observations=value.
Constraint: effective number of observations≥value.
IFAIL=121
On entry, NTAU=value.
Constraint: NTAU≥1.
IFAIL=131
On entry, TAU value=value is invalid.
IFAIL=201
On entry, either the option arrays have not been initialized or they have been corrupted.
IFAIL=221
On entry, STATE vector has been corrupted or not initialized.
IFAIL=231
A potential problem occurred whilst fitting the model(s).
Additional information has been returned in INFO.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

Not applicable.

8 Parallelism and Performance

G02QGF is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
G02QGF makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

G02QGF allocates internally approximately the following elements of real storage: 13⁢n+ n⁢p+ 3⁢p 2+ 6⁢p+ 3⁢p+1×NTAU. If Interval Method=BOOTSTRAP XY then a further n⁢p elements are required, and this increases by p×NTAU×Bootstrap Iterations if Bootstrap Interval Method=QUANTILE. Where possible, any user-supplied output arrays are used as workspace and so the amount actually allocated may be less. If SORDER=2, WEIGHT='U', INTCPT='N' and IP=M an internal copy of the input data is avoided and the amount of locally allocated memory is reduced by n⁢p.

10 Example

A quantile regression model is fitted to Engels 1857 study of household expenditure on food. The model regresses the dependent variable, household food expenditure, against two explanatory variables, a column of ones and household income. The model is fit for five different values of τ and the covariance matrix is estimated assuming Normal IID errors. Both the covariance matrix and the residuals are returned.

10.1 Program Text

Program Text (g02qgfe.f90)

10.2 Program Data

Program Data (g02qgfe.d)

10.3 Program Results

Program Results (g02qgfe.r)

GnuplotProduced by GNUPLOT 4.6 patchlevel 3 0 500 1000 1500 2000 0 500 1000 1500 2000 2500 3000 3500 4000 4500 5000 Household Food Expenditure Household Income Example Program Quantile Regression Engels 1857 Study of Household Expenditure on Food gnuplot_plot_1 gnuplot_plot_2 τ = 0.10 gnuplot_plot_3 τ = 0.25 gnuplot_plot_4 τ = 0.50 gnuplot_plot_5 τ = 0.75 gnuplot_plot_6 τ = 0.90

11 Algorithmic Details

By the addition of slack variables the minimization (1) can be reformulated into the linear programming problem
minimize u, v, β ∈ ℝ + n × ℝ + n × ℝ p τ eT u + 1 - τ eT v ​   subject to   y = Xβ + u - v (2)
and its associated dual
maximize d yT d ​   subject to   XT d=0, d ∈ τ-1,τ n (3)
where e is a vector of n 1s. Setting a=d+1-τ e gives the equivalent formulation
maximize a yT a ​   subject to   XT a = 1 - τ XT e , a ∈ 0,1 n . (4)
The algorithm introduced by Portnoy and Koenker (1997) and used by G02QGF, uses the primal-dual formulation expressed in equations (2) and (4) along with a logarithmic barrier function to obtain estimates for β. The algorithm is based on the predictor-corrector algorithm of Mehrotra (1992) and further details can be obtained from Portnoy and Koenker (1997) and Koenker (2005). A good description of linear programming, interior point algorithms, barrier functions and Mehrotra's predictor-corrector algorithm can be found in Nocedal and Wright (1999).

11.1 Interior Point Algorithm

In this section a brief description of the interior point algorithm used to estimate the model parameters is presented. It should be noted that there are some differences in the equations given here – particularly (7) and (9) – compared to those given in Koenker (2005) and Portnoy and Koenker (1997).

11.1.1 Central path

Rather than optimize (4) directly, an additional slack variable s is added and the constraint a ∈ 0,1 n is replaced with a+s=e , a i ≥ 0 , s i ≥ 0 , for i= 1,2,…,n .
The positivity constraint on a and s is handled using the logarithmic barrier function
B a,s,μ = yT a + μ ⁢ ∑ i=1 n log⁡ai + log⁡si .
The primal-dual form of the problem is used giving the Lagrangian
L a,s,β,u,μ = B a,s,μ - βT XT a - 1 - τ XT e - uT a + s - e
whose central path is described by the following first order conditions
XT a = 1-τ XT e a+s = e Xβ+u-v = y SUe = μe AVe = μe (5)
where A denotes the diagonal matrix with diagonal elements given by a, similarly with S,U and V. By enforcing the inequalities on s and a strictly, i.e., ai>0 and si>0 for all i we ensure that A and S are positive definite diagonal matrices and hence A-1 and S-1 exist.
Rather than applying Newton's method to the system of equations given in (5) to obtain the step directions δβ,δa,δs,δu and δv , Mehrotra substituted the steps directly into (5) giving the augmented system of equations
XT a + δa = 1-τ XT e a + δa + s + δs = e X β + δβ + u + δu - v + δv = y S + Δs U + Δu e = μe A + Δa V + Δv e = μe (6)
where Δa,Δs,Δu and Δv denote the diagonal matrices with diagonal elements given by δa,δs,δu and δv respectively.

11.1.2 Affine scaling step

The affine scaling step is constructed by setting μ=0 in (5) and applying Newton's method to obtain an intermediate set of step directions
XT W X δ β = XT W y - X β + τ - 1 XT e + XT a δ a = W y-Xβ - X δ β δ s = - δ a δ u = S-1 U δ a - U e δ v = A-1 V δ s - V e (7)
where W = S-1 U + A-1 V -1 .
Initial step sizes for the primal (γ^P) and dual (γ^D) parameters are constructed as
γ^P = σ × min min i , δ a i < 0 ai / δ a i , min i , δ s i < 0 si / δ s i γ^D = σ × min min i , δ u i < 0 ui / δ u i , min i , δ v i < 0 vi / δ v i (8)
where σ is a user-supplied scaling factor. If γ^P × γ^D ≥ 1 then the nonlinearity adjustment, described in Section 11.1.3, is not made and the model parameters are updated using the current step size and directions.

11.1.3 Nonlinearity Adjustment

In the nonlinearity adjustment step a new estimate of μ is obtained by letting
g^γ^P,γ^D = s + γ^P δs T u + γ^D δu + a + γ^P δa T v + γ^D δv
and estimating μ as
μ = g^γ^P,γ^D g^0,0 3 ⁢ g^0,0 2⁢n .
This estimate, along with the nonlinear terms (Δu, Δs, Δa and Δv) from (6) are calculated using the values of δa,δs,δu and δv obtained from the affine scaling step.
Given an updated estimate for μ and the nonlinear terms the system of equations
XT W X δ β = XT W y - X β + μ S-1 - A-1 e + S-1 Δ s Δ u e - A-1 Δ a Δ v e + τ - 1 XT e + XT a δ a = W y-Xβ - X δ β + μ S-1 - A-1 δ s = - δ a δ u = μ S-1 e + S-1 U δ a - U e - S-1 Δs Δu e δ v = μ A-1 e + A-1 V δ s - V e - A-1 Δa Δv e (9)
are solved and updated values for δβ,δa,δs,δu,δv,γ^P and γ^D calculated.

11.1.4 Update and convergence

At each iteration the model parameters β,a,s,u,v are updated using step directions, δβ,δa,δs,δu,δv and step lengths γ^P,γ^D .
Convergence is assessed using the duality gap, that is, the differences between the objective function in the primal and dual formulations. For any feasible point u,v,s,a the duality gap can be calculated from equations (2) and (3) as
τ eT u + 1-τ ⁢ eT v - dT y = τ eT u + 1-τ ⁢ eT v - a - 1 - τ e T y = sT u + aT v = eT u - aT y + 1 - τ eT X β
and the optimization terminates if the duality gap is smaller than the tolerance supplied in the optional parameter Tolerance.

11.1.5 Additional information

Initial values are required for the parameters a,s,u,v and β. If not supplied by the user, initial values for β are calculated from a least squares regression of y on X. This regression is carried out by first constructing the cross-product matrix XT X and then using a pivoted Q⁢R decomposition as performed by F08BFF (DGEQP3). In addition, if the cross-product matrix is not of full rank, a rank reduction is carried out and, rather than using the full design matrix, X, a matrix formed from the first p-rank columns of X⁢P is used instead, where P is the pivot matrix used during the Q⁢R decomposition. Parameter estimates, confidence intervals and the rows and columns of the matrices returned in the argument CH (if any) are set to zero for variables dropped during the rank-reduction. The rank reduction step is performed irrespective of whether initial values are supplied by the user.
Once initial values have been obtained for β, the initial values for u and v are calculated from the residuals. If ri<εu then a value of ±εu is used instead, where εu is supplied in the optional parameter Epsilon. The initial values for the a and s are always set to 1-τ and τ respectively.
The solution for δβ in both (7) and (9) is obtained using a Bunch–Kaufman decomposition, as implemented in F07MDF (DSYTRF).

11.2 Calculation of Covariance Matrix

G02QGF supplies four methods to calculate the covariance matrices associated with the parameter estimates for β. This section gives some additional detail on three of the algorithms, the fourth, (which uses bootstrapping), is described in Section 3.
(i) Independent, identically distributed (IID) errors
When assuming IID errors, the covariance matrices depend on the sparsity, s τ, which G02QGF estimates as follows:
(a) | Let ri denote the residuals from the original quantile regression, that is ri = yi - xiT ⁢ β^ .
(b) | Drop any residual where ri is less than εu, supplied in the optional parameter Epsilon.
(c) | Sort and relabel the remaining residuals in ascending order, by absolute value, so that εu < r 1 < r 2 < … .
(d) | Select the first l values where l=hn⁢n, for some bandwidth hn.
(e) | Sort and relabel these l residuals again, so that r 1 < r 2 < … < rl and regress them against a design matrix with two columns (p=2) and rows given by xi = 1, i/n-p using quantile regression with τ=0.5.
(f) | Use the resulting estimate of the slope as an estimate of the sparsity.
(ii) Powell Sandwich
When using the Powell Sandwich to estimate the matrix Hn, the quantity
cn = min σr, q r 3 - q r 1 / 1.34 × Φ-1 τ + hn - Φ-1 τ - hn
is calculated. Dependent on the value of τ and the method used to calculate the bandwidth (hn), it is possible for the quantities τ±hn to be too large or small, compared to machine precision (ε). More specifically, when τ-hn≤ε, or τ+hn≥1-ε, a warning flag is raised in INFO, the value is truncated to ε or 1-ε respectively and the covariance matrix calculated as usual.
(iii) Hendricks–Koenker Sandwich
The Hendricks–Koenker Sandwich requires the calculation of the quantity di= xiT β^ τ + hn - β^ τ - hn . As with the Powell Sandwich, in cases where τ-hn≤ε, or τ+hn≥1-ε, a warning flag is raised in INFO, the value truncated to ε or 1-ε respectively and the covariance matrix calculated as usual.
In addition, it is required that di>0, in this method. Hence, instead of using 2 ⁢ hn / di in the calculation of Hn, max 2 ⁢ hn / di + εu ,0 is used instead, where εu is supplied in the optional parameter Epsilon.

12 Optional Parameters

Several optional parameters in G02QGF control aspects of the optimization algorithm, methodology used, logic or output. Their values are contained in the arrays IOPTS and OPTS; these must be initialized before calling G02QGF by first calling G02ZKF with OPTSTR set to Initialize=G02QGF.
Each optional parameter has an associated default value; to set any of them to a non-default value, use G02ZKF. The current value of an optional parameter can be queried using G02ZLF.
The remainder of this section can be skipped if you wish to use the default values for all optional parameters.
The following is a list of the optional parameters available. A full description of each optional parameter is provided in Section 12.1.
  • Band Width Alpha
  • Band Width Method
  • Big
  • Bootstrap Interval Method
  • Bootstrap Iterations
  • Bootstrap Monitoring
  • Calculate Initial Values
  • Defaults
  • Drop Zero Weights
  • Epsilon
  • Interval Method
  • Iteration Limit
  • Matrix Returned
  • Monitoring
  • QR Tolerance
  • Return Residuals
  • Sigma
  • Significance Level
  • Tolerance
  • Unit Number

12.1 Description of the Optional Parameters

For each option, we give a summary line, a description of the optional parameter and details of constraints.
The summary line contains:
  • the keywords, where the minimum abbreviation of each keyword is underlined (if no characters of an optional qualifier are underlined, the qualifier may be omitted);
  • a parameter value, where the letters a, i and r denote options that take character, integer and real values respectively;
  • the default value, where the symbol ε is a generic notation for machine precision (see X02AJF).
Keywords and character values are case and white space insensitive.
Band Width Alpha r Default =1.0
A multiplier used to construct the parameter αb used when calculating the Sheather–Hall bandwidth (see Section 3), with αb=1-α×Band Width Alpha. Here, α is the Significance Level.
Constraint: Band Width Alpha>0.0.
Band Width Method a Default ='SHEATHER HALL'
The method used to calculate the bandwidth used in the calculation of the asymptotic covariance matrix Σ and H-1 if Interval Method=HKS, KERNEL or IID (see Section 3).
Constraint: Band Width Method=SHE ATHER HAL L or BOF INGER.
Big r Default =10.020
This parameter should be set to something larger than the biggest value supplied in DAT and Y.
Constraint: Big>0.0.
Bootstrap Interval Method a Default =QUANTILE
If Interval Method=BOOTSTRAP XY, Bootstrap Interval Method controls how the confidence intervals are calculated from the bootstrap estimates.
Bootstrap Interval Method=T
t intervals are calculated. That is, the covariance matrix, Σ = σ ij : i,j = 1,2,…,p is calculated from the bootstrap estimates and the limits calculated as β i ± t n - p , 1 + α / 2 σ ii where t n - p , 1 + α / 2 is the 1 + α / 2 percentage point from a Student's t distribution on n - p degrees of freedom, n is the effective number of observations and α is given by the optional parameter Significance Level.
Bootstrap Interval Method=QUANTILE
Quantile intervals are calculated. That is, the upper and lower limits are taken as the 1 + α / 2 and 1 - α / 2 quantiles of the bootstrap estimates, as calculated using G01AMF.
Constraint: Bootstrap Interval Method=T or QUA NTILE.
Bootstrap Iterations i Default =100
The number of bootstrap samples used to calculate the confidence limits and covariance matrix (if requested) when Interval Method=BOOTSTRAP XY.
Constraint: Bootstrap Iterations>1.
Bootstrap Monitoring a Default =NO
If Bootstrap Monitoring=YES and Interval Method=BOOTSTRAP XY, then the parameter estimates for each of the bootstrap samples are displayed. This information is sent to the unit number specified by Unit Number.
Constraint: Bootstrap Monitoring=YES or NO.
Calculate Initial Values a Default =YES
If Calculate Initial Values=YES then the initial values for the regression parameters, β, are calculated from the data. Otherwise they must be supplied in B.
Constraint: Calculate Initial Values=YES or NO.
Defaults
This special keyword is used to reset all optional parameters to their default values.
Drop Zero Weights a Default =YES
If a weighted regression is being performed and Drop Zero Weights=YES then observations with zero weight are dropped from the analysis. Otherwise such observations are included.
Constraint: Drop Zero Weights=YES or NO.
Epsilon r Default =ε
εu, the tolerance used when calculating the covariance matrix and the initial values for u and v. For additional details see Section 11.2 and Section 11.1.5 respectively.
Constraint: Epsilon≥0.0.
Interval Method a Default =IID
The value of Interval Method controls whether confidence limits are returned in BL and BU and how these limits are calculated. This parameter also controls how the matrices returned in CH are calculated.
Interval Method=NONE
No limits are calculated and BL, BU and CH are not referenced.
Interval Method=KERNEL
The Powell Sandwich method with a Gaussian kernel is used.
Interval Method=HKS
The Hendricks–Koenker Sandwich is used.
Interval Method=IID
The errors are assumed to be identical, and independently distributed.
Interval Method=BOOTSTRAP XY
A bootstrap method is used, where sampling is done on the pair yi,xi. The number of bootstrap samples is controlled by the parameter Bootstrap Iterations and the type of interval constructed from the bootstrap samples is controlled by Bootstrap Interval Method.
Constraint: Interval Method=NON E, KER NEL, HKS, IID or BOO TSTRAP XY.
Iteration Limit i Default =100
The maximum number of iterations to be performed by the interior point optimization algorithm.
Constraint: Iteration Limit>0.
Matrix Returned a Default =NONE
The value of Matrix Returned controls the type of matrices returned in CH. If Interval Method=NONE, this parameter is ignored and CH is not referenced. Otherwise:
Matrix Returned=NONE
No matrices are returned and CH is not referenced.
Matrix Returned=COVARIANCE
The covariance matrices are returned.
Matrix Returned=H INVERSE
If Interval Method=KERNEL or HKS, the matrices J and H-1 are returned. Otherwise no matrices are returned and CH is not referenced.
The matrices returned are calculated as described in Section 3, with the algorithm used specified by Interval Method. In the case of Interval Method=BOOTSTRAP XY the covariance matrix is calculated directly from the bootstrap estimates.
Constraint: Matrix Returned=NON E, COV ARIANCE or H INV ERSE.
Monitoring a Default =NO
If Monitoring=YES then the duality gap is displayed at each iteration of the interior point optimization algorithm. In addition, the final estimates for β are also displayed.
The monitoring information is sent to the unit number specified by Unit Number.
Constraint: Monitoring=YES or NO.
QR Tolerance r Default =ε 0.9
The tolerance used to calculate the rank, k, of the p×p cross-product matrix, XT X. Letting Q be the orthogonal matrix obtained from a QR decomposition of XT X, then the rank is calculated by comparing Q ii with Q 11×QR Tolerance.
If the cross-product matrix is rank deficient, then the parameter estimates for the p-k columns with the smallest values of Q ii are set to zero, along with the corresponding entries in BL, BU and CH, if returned. This is equivalent to dropping these variables from the model. Details on the QR decomposition used can be found in F08BFF (DGEQP3).
Constraint: QR Tolerance>0.0.
Return Residuals a Default =NO
If Return Residuals=YES, the residuals are returned in RES. Otherwise RES is not referenced.
Constraint: Return Residuals=YES or NO.
Sigma r Default =0.99995
The scaling factor used when calculating the affine scaling step size (see equation (8)).
Constraint: 0.0<Sigma<1.0.
Significance Level r Default =0.95
α, the size of the confidence interval whose limits are returned in BL and BU.
Constraint: 0.0<Significance Level<1.0.
Tolerance r Default =ε
Convergence tolerance. The optimization is deemed to have converged if the duality gap is less than Tolerance (see Section 11.1.4).
Constraint: Tolerance>0.0.
Unit Number i Default taken from X04ABF
The unit number to which any monitoring information is sent.
Constraint: Unit Number>1.

13 Description of Monitoring Information

See the description of the optional argument Monitoring.
G02 Chapter Contents
G02 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


G02ZKF : NAG Library, Mark 26

G02 Chapter Contents
G02 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

G02ZKF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
10 Example

1 Purpose

G02ZKF either initializes or resets the optional parameter arrays or sets a single optional parameter for supported problem solving routines in Chapter G02. Currently, only G02QGF is supported.

2 Specification

SUBROUTINE G02ZKF ( OPTSTR, IOPTS, LIOPTS, OPTS, LOPTS, IFAIL)
INTEGER | IOPTS(LIOPTS), LIOPTS, LOPTS, IFAIL
REAL (KIND=nag_wp) | OPTS(LOPTS)
CHARACTER(*) | OPTSTR

3 Description

G02ZKF has three purposes: to initialize optional parameter arrays, to reset all optional parameters to their default values or to set a single optional parameter to a user-supplied value.
Optional parameters and their values are, in general, presented as a character string, OPTSTR, of the form ‘option =optval’; alphabetic characters can be supplied in either upper or lower case. Both option and optval may consist of one or more tokens separated by white space. The tokens that comprise optval will normally be either an integer, real or character value as defined in the description of the specific optional argument. In addition all optional parameters can take an optval DEFAULT which resets the optional parameter to its default value.
It is imperative that optional parameter arrays are initialized before any options are set, before the relevant problem solving routine is called and before any options are queried using G02ZLF. To initialize the optional parameter arrays IOPTS and OPTS for a specific problem solving routine, the option Initialize is used with value identifying the problem solving routine to be called, via its short name. For example, to initialize optional parameter arrays to be passed to G02QGF, G02ZKF is called as follows:
call G02ZKF('Initialize = g02qgf', IOPTS, LIOPTS, OPTS, LOPTS, IFAIL)
Information relating to available option names and their corresponding valid values is given in Section 12 in G02QGF.

4 References

None.

5 Arguments

1:   OPTSTR – CHARACTER(*)Input
On entry: a string identifying the option to be set.
Initialize=routine name
Initialize the optional parameter arrays IOPTS and OPTS for use with routine routine name, where routine name is the short name of the problem solving routine you wish to use.
Defaults
Resets all options to their default values.
option=optval
See Section 12 in G02QGF for details of valid values for option and optval. The equals sign (=) delimiter must be used to separate the option from its optval value.
OPTSTR is case insensitive. Each token in the option and optval component must be separated by at least one space.
2:   IOPTS LIOPTS – INTEGER arrayCommunication Array
On entry: optional parameter array.
If OPTSTR has the form Initialize=routine name, the contents of IOPTS need not be set.
Otherwise, IOPTS must not have been altered since the last call to G02ZKF, G02ZLF or the selected problem solving routine.
On exit: dependent on the contents of OPTSTR, either an initialized, reset or updated version of the optional parameter array.
3:   LIOPTS – INTEGERInput
On entry: the length of the array IOPTS.
Constraint: unless otherwise stated in the documentation for a specific, supported, problem solving routine, LIOPTS≥100.
4:   OPTS LOPTS – REAL (KIND=nag_wp) arrayCommunication Array
On entry: optional parameter array.
If OPTSTR has the form Initialize=routine name, the contents of OPTS need not be set.
Otherwise, OPTS must not have been altered since the last call to G02ZKF, G02ZLF or the selected problem solving routine.
On exit: dependent on the contents of OPTSTR, either an initialized, reset or updated version of the optional parameter array.
5:   LOPTS – INTEGERInput
On entry: the length of the array OPTS.
Constraint: unless otherwise stated in the documentation for a specific, supported, problem solving routine, LOPTS≥100.
6:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=11
On entry, the option supplied in OPTSTR was not recognized: OPTSTR=value.
IFAIL=12
On entry, the expected delimiter ‘=’ was not found in OPTSTR: OPTSTR=value.
IFAIL=13
On entry, could not convert the specified optval to an integer: OPTSTR=value.
On entry, could not convert the specified optval to a real: OPTSTR=value.
IFAIL=14
On entry, attempting to initialize the optional parameter arrays but specified routine name was not valid: name=value.
IFAIL=15
On entry, the optval supplied for the integer optional parameter is not valid.
OPTSTR=value.
IFAIL=16
On entry, the optval supplied for the real optional parameter is not valid.
OPTSTR=value.
IFAIL=17
On entry, the optval supplied for the character optional parameter is not valid.
OPTSTR=value.
IFAIL=21
On entry, either the option arrays have not been initialized or they have been corrupted.
IFAIL=31
On entry, LIOPTS=value.
Constraint: LIOPTS≥value.
IFAIL=51
On entry, LOPTS=value.
Constraint: LOPTS≥value.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

Not applicable.

8 Parallelism and Performance

G02ZKF is not threaded in any implementation.

9 Further Comments

Not applicable.

10 Example

See the example programs associated with the problem solving routine you wish to use for a demonstration of how to use G02ZKF to initialize option arrays and set options.
G02 Chapter Contents
G02 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


G02ZLF : NAG Library, Mark 26

G02 Chapter Contents
G02 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

G02ZLF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
10 Example

1 Purpose

G02ZLF is used to query the value of optional parameters available to supported problem solving routines in Chapter G02. Currently, only G02QGF is supported.

2 Specification

SUBROUTINE G02ZLF ( OPTSTR, IVALUE, RVALUE, CVALUE, OPTYPE, IOPTS, OPTS, IFAIL)
INTEGER | IVALUE, OPTYPE, IOPTS(*), IFAIL
REAL (KIND=nag_wp) | RVALUE, OPTS(*)
CHARACTER(*) | OPTSTR, CVALUE

3 Description

G02ZLF is used to query the current values of options. It is necessary to initalize optional parameter arrays using G02ZKF before any options are queried.
G02ZLF will normally return either an integer, real or character value dependent upon the type associated with the optional parameter being queried. Whether the option queried is of integer, real or character type is indicated by the returned value of OPTYPE.
Information on optional parameter names and whether these options are real, integer or character can be found in Section 12 in G02QGF.

4 References

None.

5 Arguments

1:   OPTSTR – CHARACTER(*)Input
On entry: a string identifying the option whose current value is required. See Section 12 in G02QGF for information on valid options. In addition, the following is a valid option:
Identify
G02ZLF returns in CVALUE the routine name supplied to G02ZKF when the optional parameter arrays IOPTS and OPTS were initialized.
2:   IVALUE – INTEGEROutput
On exit: if the optional parameter supplied in OPTSTR is an integer valued argument, IVALUE will hold its current value.
3:   RVALUE – REAL (KIND=nag_wp)Output
On exit: if the optional parameter supplied in OPTSTR is a real valued argument, RVALUE will hold its current value.
4:   CVALUE – CHARACTER(*)Output
Note: the string returned in CVALUE will never exceed 40 characters in length.
On exit: if the optional parameter supplied in OPTSTR is a character valued argument, CVALUE will hold its current value, unless Identify is specified, see OPTSTR.
5:   OPTYPE – INTEGEROutput
On exit: indicates whether the optional parameter supplied in OPTSTR is an integer, real or character valued argument and hence which of IVALUE, RVALUE or CVALUE holds the current value.
OPTYPE=1
OPTSTR is an integer valued optional parameter, its current value has been returned in IVALUE.
OPTYPE=2
OPTSTR is a real valued optional parameter, its current value has been returned in RVALUE.
OPTYPE=3
OPTSTR is a character valued optional parameter, its current value has been returned in CVALUE.
6:   IOPTS* – INTEGER arrayCommunication Array
Note: the dimension of this array is dictated by the requirements of associated functions that must have been previously called. This array must be the same array passed as argument IOPTS in the previous call to G02ZKF.
7:   OPTS* – REAL (KIND=nag_wp) arrayCommunication Array
Note: the dimension of this array is dictated by the requirements of associated functions that must have been previously called. This array must be the same array passed as argument OPTS in the previous call to G02ZKF.
8:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=11
On entry, the option in OPTSTR was not recognized: OPTSTR=value.
IFAIL=41
On entry, OPTSTR indicates a character optional parameter, but CVALUE is too short to hold the stored value. The returned value will be truncated.
IFAIL=61
On entry, either the option arrays have not been initialized or they have been corrupted.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

Not applicable.

8 Parallelism and Performance

G02ZLF is not threaded in any implementation.

9 Further Comments

Not applicable.

10 Example

See the example programs associated with the problem solving routine you wish to use for a demonstration of how to use G02ZLF to query options.
G02 Chapter Contents
G02 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


G03AAF : NAG Library, Mark 26

G03 Chapter Contents
G03 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

G03AAF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

G03AAF performs a principal component analysis on a data matrix; both the principal component loadings and the principal component scores are returned.

2 Specification

SUBROUTINE G03AAF ( MATRIX, STD, WEIGHT, N, M, X, LDX, ISX, S, WT, NVAR, E, LDE, P, LDP, V, LDV, WK, IFAIL)
INTEGER | N, M, LDX, ISX(M), NVAR, LDE, LDP, LDV, IFAIL
REAL (KIND=nag_wp) | X(LDX,M), S(M), WT(*), E(LDE,6), P(LDP,NVAR), V(LDV,NVAR), WK(1)
CHARACTER(1) | MATRIX, STD, WEIGHT

3 Description

Let X be an n by p data matrix of n observations on p variables x 1,x 2,…,xp and let the p by p variance-covariance matrix of x 1,x 2,…,xp be S. A vector a 1 of length p is found such that:
a 1 T S a 1  is maximized subject to  a 1 T a 1=1.
The variable z 1=∑i=1 p a 1 ixi is known as the first principal component and gives the linear combination of the variables that gives the maximum variation. A second principal component, z 2=∑i=1 p a 2 ixi, is found such that:
a 2 T S a 2  is maximized subject to ​a 2 T a 2=1 and ​a 2 T a 1=0.
This gives the linear combination of variables that is orthogonal to the first principal component that gives the maximum variation. Further principal components are derived in a similar way.
The vectors a 1,a 2,…,ap, are the eigenvectors of the matrix S and associated with each eigenvector is the eigenvalue, λi 2. The value of λi 2/∑λi 2 gives the proportion of variation explained by the ith principal component. Alternatively, the ai's can be considered as the right singular vectors in a singular value decomposition with singular values λi of the data matrix centred about its mean and scaled by 1/n-1, Xs. This latter approach is used in G03AAF, with
Xs=VΛ P′
where Λ is a diagonal matrix with elements λi, P is the p by p matrix with columns ai and V is an n by p matrix with V′V=I, which gives the principal component scores.
Principal component analysis is often used to reduce the dimension of a dataset, replacing a large number of correlated variables with a smaller number of orthogonal variables that still contain most of the information in the original dataset.
The choice of the number of dimensions required is usually based on the amount of variation accounted for by the leading principal components. If k principal components are selected, then a test of the equality of the remaining p-k eigenvalues is
n-2 p+5/6 -∑i=k+1 p log λi 2+p-k log∑i=k+1 p λi 2/p-k
which has, asymptotically, a χ 2-distribution with 12 p-k-1p-k+2 degrees of freedom.
Equality of the remaining eigenvalues indicates that if any more principal components are to be considered then they all should be considered.
Instead of the variance-covariance matrix the correlation matrix, the sums of squares and cross-products matrix or a standardized sums of squares and cross-products matrix may be used. In the last case S is replaced by σ-12 S σ-12 for a diagonal matrix σ with positive elements. If the correlation matrix is used, the χ 2 approximation for the statistic given above is not valid.
The principal component scores, F, are the values of the principal component variables for the observations. These can be standardized so that the variance of these scores for each principal component is 1.0 or equal to the corresponding eigenvalue.
Weights can be used with the analysis, in which case the matrix X is first centred about the weighted means then each row is scaled by an amount wi, where wi is the weight for the ith observation.

4 References

Chatfield C and Collins A J (1980) Introduction to Multivariate Analysis Chapman and Hall
Cooley W C and Lohnes P R (1971) Multivariate Data Analysis Wiley
Hammarling S (1985) The singular value decomposition in multivariate statistics SIGNUM Newsl. 20(3) 2–25
Kendall M G and Stuart A (1969) The Advanced Theory of Statistics (Volume 1) (3rd Edition) Griffin
Morrison D F (1967) Multivariate Statistical Methods McGraw–Hill

5 Arguments

1:   MATRIX – CHARACTER(1)Input
On entry: indicates for which type of matrix the principal component analysis is to be carried out.
MATRIX='C'
It is for the correlation matrix.
MATRIX='S'
It is for a standardized matrix, with standardizations given by S.
MATRIX='U'
It is for the sums of squares and cross-products matrix.
MATRIX='V'
It is for the variance-covariance matrix.
Constraint: MATRIX='C', 'S', 'U' or 'V'.
2:   STD – CHARACTER(1)Input
On entry: indicates if the principal component scores are to be standardized.
STD='S'
The principal component scores are standardized so that F′F=I, i.e., F=Xs P Λ-1=V.
STD='U'
The principal component scores are unstandardized, i.e., F=Xs P=VΛ.
STD='Z'
The principal component scores are standardized so that they have unit variance.
STD='E'
The principal component scores are standardized so that they have variance equal to the corresponding eigenvalue.
Constraint: STD='E', 'S', 'U' or 'Z'.
3:   WEIGHT – CHARACTER(1)Input
On entry: indicates if weights are to be used.
WEIGHT='U'
No weights are used.
WEIGHT='W'
Weights are used and must be supplied in WT.
Constraint: WEIGHT='U' or 'W'.
4:   N – INTEGERInput
On entry: n, the number of observations.
Constraint: N≥2.
5:   M – INTEGERInput
On entry: m, the number of variables in the data matrix.
Constraint: M≥1.
6:   X LDXM – REAL (KIND=nag_wp) arrayInput
On entry: X ij must contain the ith observation for the jth variable, for i=1,2,…,n and j=1,2,…,m.
7:   LDX – INTEGERInput
On entry: the first dimension of the array X as declared in the (sub)program from which G03AAF is called.
Constraint: LDX≥N.
8:   ISX M – INTEGER arrayInput
On entry: ISX j indicates whether or not the jth variable is to be included in the analysis.
If ISX j>0, the variable contained in the jth column of X is included in the principal component analysis, for j=1,2,…,m.
Constraint: ISX j>0 for NVAR values of j.
9:   S M – REAL (KIND=nag_wp) arrayInput/Output
On entry: the standardizations to be used, if any.
If MATRIX='S', the first m elements of S must contain the standardization coefficients, the diagonal elements of σ.
Constraint: if ISX j>0, S j>0.0, for j=1,2,…,m.
On exit: if MATRIX='S', S is unchanged on exit.
If MATRIX='C', S contains the variances of the selected variables. S j contains the variance of the variable in the jth column of X if ISX j>0.
If MATRIX='U' or 'V', S is not referenced.
10:   WT* – REAL (KIND=nag_wp) arrayInput
Note: the dimension of the array WT must be at least N if WEIGHT='W', and at least 1 otherwise.
On entry: if WEIGHT='W', the first n elements of WT must contain the weights to be used in the principal component analysis.
If WT i=0.0, the ith observation is not included in the analysis. The effective number of observations is the sum of the weights.
If WEIGHT='U', WT is not referenced and the effective number of observations is n.
Constraints:
  • WT i≥0.0, for i=1,2,…,n;
  • the sum of weights ≥NVAR+1.
11:   NVAR – INTEGERInput
On entry: p, the number of variables in the principal component analysis.
Constraint: 1≤NVAR≤min N-1,M.
12:   E LDE 6 – REAL (KIND=nag_wp) arrayOutput
On exit: the statistics of the principal component analysis.
E i 1
The eigenvalues associated with the ith principal component, λi 2, for i=1,2,…,p.
E i 2
The proportion of variation explained by the ith principal component, for i=1,2,…,p.
E i 3
The cumulative proportion of variation explained by the first ith principal components, for i=1,2,…,p.
E i 4
The χ 2 statistics, for i=1,2,…,p.
E i 5
The degrees of freedom for the χ 2 statistics, for i=1,2,…,p.
If MATRIX≠'C', E i 6 contains significance level for the χ 2 statistic, for i=1,2,…,p.
If MATRIX='C', E i 6 is returned as zero.
13:   LDE – INTEGERInput
On entry: the first dimension of the array E as declared in the (sub)program from which G03AAF is called.
Constraint: LDE≥NVAR.
14:   P LDPNVAR – REAL (KIND=nag_wp) arrayOutput
On exit: the first NVAR columns of P contain the principal component loadings, ai. The jth column of P contains the NVAR coefficients for the jth principal component.
15:   LDP – INTEGERInput
On entry: the first dimension of the array P as declared in the (sub)program from which G03AAF is called.
Constraint: LDP≥NVAR.
16:   V LDVNVAR – REAL (KIND=nag_wp) arrayOutput
On exit: the first NVAR columns of V contain the principal component scores. The jth column of V contains the N scores for the jth principal component.
If WEIGHT='W', any rows for which WT i is zero will be set to zero.
17:   LDV – INTEGERInput
On entry: the first dimension of the array V as declared in the (sub)program from which G03AAF is called.
Constraint: LDV≥N.
18:   WK 1 – REAL (KIND=nag_wp) arrayInput
This argument is no longer accessed by G03AAF. Workspace is provided internally by dynamic allocation instead.
19:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, | M<1,
or | N<2,
or | NVAR<1,
or | NVAR>M,
or | NVAR≥N,
or | LDX<N,
or | LDV<N,
or | LDP<NVAR,
or | LDE<NVAR,
or | MATRIX≠'C', 'S', 'U' or 'V',
or | STD≠'S', 'U', 'Z' or 'E',
or | WEIGHT≠'U' or 'W'.
IFAIL=2
On entry, WEIGHT='W' and a value of WT<0.0.
IFAIL=3
On entry, | there are not NVAR values of ISX>0,
or | WEIGHT='W' and the effective number of observations is less than NVAR+1.
IFAIL=4
On entry, S j≤0.0 for some j=1,2,…,m, when MATRIX='S' and ISX j>0.
IFAIL=5
The singular value decomposition has failed to converge. This is an unlikely error exit.
IFAIL=6
All eigenvalues/singular values are zero. This will be caused by all the variables being constant.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

As G03AAF uses a singular value decomposition of the data matrix, it will be less affected by ill-conditioned problems than traditional methods using the eigenvalue decomposition of the variance-covariance matrix.

8 Parallelism and Performance

G03AAF makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

None.

10 Example

A dataset is taken from Cooley and Lohnes (1971), it consists of ten observations on three variables. The unweighted principal components based on the variance-covariance matrix are computed and the principal component scores requested. The principal component scores are standardized so that they have variance equal to the corresponding eigenvalue.

10.1 Program Text

Program Text (g03aafe.f90)

10.2 Program Data

Program Data (g03aafe.d)

10.3 Program Results

Program Results (g03aafe.r)

GnuplotProduced by GNUPLOT 4.6 patchlevel 3 Example Program Principal Component Analysis −3 −2 −1 0 1 2 3 4 −5 −4 −3 −2 −1 0 1 2 3 4 5 Second Principal Component (PC 2) First Principal Component (PC 1) Observation ID for the First and Second Principal Components gnuplot_plot_1a 1 2 3 4 5 6 7 8 9 10 0 0.1 0.2 0.3 0.4 0.5 0.6 0.7 PC 1 PC 2 PC 3 Percentage Variation Scree Plot gnuplot_plot_1b
G03 Chapter Contents
G03 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


G03ACF : NAG Library, Mark 26

G03 Chapter Contents
G03 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

G03ACF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

G03ACF performs a canonical variate (canonical discrimination) analysis.

2 Specification

SUBROUTINE G03ACF ( WEIGHT, N, M, X, LDX, ISX, NX, ING, NG, WT, NIG, CVM, LDCVM, E, LDE, NCV, CVX, LDCVX, TOL, IRANKX, WK, IWK, IFAIL)
INTEGER | N, M, LDX, ISX(M), NX, ING(N), NG, NIG(NG), LDCVM, LDE, NCV, LDCVX, IRANKX, IWK, IFAIL
REAL (KIND=nag_wp) | X(LDX,M), WT(*), CVM(LDCVM,NX), E(LDE,6), CVX(LDCVX,NG-1), TOL, WK(IWK)
CHARACTER(1) | WEIGHT

3 Description

Let a sample of n observations on nx variables in a data matrix come from ng groups with n 1,n 2,…,n ng observations in each group, ∑ni=n. Canonical variate analysis finds the linear combination of the nx variables that maximizes the ratio of between-group to within-group variation. The variables formed, the canonical variates can then be used to discriminate between groups.
The canonical variates can be calculated from the eigenvectors of the within-group sums of squares and cross-products matrix. However, G03ACF calculates the canonical variates by means of a singular value decomposition (SVD) of a matrix V. Let the data matrix with variable (column) means subtracted be X, and let its rank be k; then the k by (ng-1) matrix V is given by:
V = QXT Qg ,
where Qg is an n by ng-1 orthogonal matrix that defines the groups and QX is the first k rows of the orthogonal matrix Q either from the QR decomposition of X:
X=QR
if X is of full column rank, i.e., k=nx, else from the SVD of X:
X=QD PT .
Let the SVD of V be:
V = Ux Δ UgT
then the nonzero elements of the diagonal matrix Δ, δi, for i=1,2,…,l, are the l canonical correlations associated with the l = min k,ng-1 canonical variates, where l = min k,ng .
The eigenvalues, λi 2, of the within-group sums of squares matrix are given by:
λi 2=δi 2 1-δi 2
and the value of πi=λi 2/∑λi 2 gives the proportion of variation explained by the ith canonical variate. The values of the πi's give an indication as to how many canonical variates are needed to adequately describe the data, i.e., the dimensionality of the problem.
To test for a significant dimensionality greater than i the χ 2 statistic:
n-1-ng-12 k-ng ∑ j=i+1 l log 1 + λj 2
can be used. This is asymptotically distributed as a χ 2-distribution with k-ing-1-i degrees of freedom. If the test for i=h is not significant, then the remaining tests for i>h should be ignored.
The loadings for the canonical variates are calculated from the matrix Ux. This matrix is scaled so that the canonical variates have unit within-group variance.
In addition to the canonical variates loadings the means for each canonical variate are calculated for each group.
Weights can be used with the analysis, in which case the weighted means are subtracted from each column and then each row is scaled by an amount wi, where wi is the weight for the ith observation (row).

4 References

Chatfield C and Collins A J (1980) Introduction to Multivariate Analysis Chapman and Hall
Gnanadesikan R (1977) Methods for Statistical Data Analysis of Multivariate Observations Wiley
Hammarling S (1985) The singular value decomposition in multivariate statistics SIGNUM Newsl. 20(3) 2–25
Kendall M G and Stuart A (1969) The Advanced Theory of Statistics (Volume 1) (3rd Edition) Griffin

5 Arguments

1:   WEIGHT – CHARACTER(1)Input
On entry: indicates if weights are to be used.
WEIGHT='U'
No weights are used.
WEIGHT='W' or 'V'
Weights are used and must be supplied in WT.
If WEIGHT='W', the weights are treated as frequencies and the effective number of observations is the sum of the weights.
If WEIGHT='V', the weights are treated as being inversely proportional to the variance of the observations and the effective number of observations is the number of observations with nonzero weights.
Constraint: WEIGHT='U', 'W' or 'V'.
2:   N – INTEGERInput
On entry: n, the number of observations.
Constraint: N≥NX+NG.
3:   M – INTEGERInput
On entry: m, the total number of variables.
Constraint: M≥NX.
4:   X LDXM – REAL (KIND=nag_wp) arrayInput
On entry: X ij must contain the ith observation for the jth variable, for i=1,2,…,n and j=1,2,…,m.
5:   LDX – INTEGERInput
On entry: the first dimension of the array X as declared in the (sub)program from which G03ACF is called.
Constraint: LDX≥N.
6:   ISX M – INTEGER arrayInput
On entry: ISX j indicates whether or not the jth variable is to be included in the analysis.
If ISX j>0, the variables contained in the jth column of X is included in the canonical variate analysis, for j=1,2,…,m.
Constraint: ISX j>0 for NX values of j.
7:   NX – INTEGERInput
On entry: the number of variables in the analysis, nx.
Constraint: NX≥1.
8:   ING N – INTEGER arrayInput
On entry: ING i indicates which group the ith observation is in, for i=1,2,…,n. The effective number of groups is the number of groups with nonzero membership.
Constraint: 1≤ING i≤NG, for i=1,2,…,n.
9:   NG – INTEGERInput
On entry: the number of groups, ng.
Constraint: NG≥2.
10:   WT* – REAL (KIND=nag_wp) arrayInput
Note: the dimension of the array WT must be at least N if WEIGHT='W' or 'V', and at least 1 otherwise.
On entry: if WEIGHT='W' or 'V', the first n elements of WT must contain the weights to be used in the analysis.
If WT i=0.0, the ith observation is not included in the analysis.
If WEIGHT='U', WT is not referenced.
Constraints:
  • WT i≥0.0, for i=1,2,…,n;
  • ∑1 n WT i≥NX+effective number of groups.
11:   NIG NG – INTEGER arrayOutput
On exit: NIG j gives the number of observations in group j, for j=1,2,…,ng.
12:   CVM LDCVMNX – REAL (KIND=nag_wp) arrayOutput
On exit: CVM ij contains the mean of the jth canonical variate for the ith group, for i=1,2,…,ng and j=1,2,…,l; the remaining columns, if any, are used as workspace.
13:   LDCVM – INTEGERInput
On entry: the first dimension of the array CVM as declared in the (sub)program from which G03ACF is called.
Constraint: LDCVM≥NG.
14:   E LDE 6 – REAL (KIND=nag_wp) arrayOutput
On exit: the statistics of the canonical variate analysis.
E i 1
The canonical correlations, δi, for i=1,2,…,l.
E i 2
The eigenvalues of the within-group sum of squares matrix, λi 2, for i=1,2,…,l.
E i 3
The proportion of variation explained by the ith canonical variate, for i=1,2,…,l.
E i 4
The χ 2 statistic for the ith canonical variate, for i=1,2,…,l.
E i 5
The degrees of freedom for χ 2 statistic for the ith canonical variate, for i=1,2,…,l.
E i 6
The significance level for the χ 2 statistic for the ith canonical variate, for i=1,2,…,l.
15:   LDE – INTEGERInput
On entry: the first dimension of the array E as declared in the (sub)program from which G03ACF is called.
Constraint: LDE≥min NX,NG-1.
16:   NCV – INTEGEROutput
On exit: the number of canonical variates, l. This will be the minimum of ng-1 and the rank of X.
17:   CVX LDCVX NG-1 – REAL (KIND=nag_wp) arrayOutput
On exit: the canonical variate loadings. CVX ij contains the loading coefficient for the ith variable on the jth canonical variate, for i=1,2,…,nx and j=1,2,…,l; the remaining columns, if any, are used as workspace.
18:   LDCVX – INTEGERInput
On entry: the first dimension of the array CVX as declared in the (sub)program from which G03ACF is called.
Constraint: LDCVX≥NX.
19:   TOL – REAL (KIND=nag_wp)Input
On entry: the value of TOL is used to decide if the variables are of full rank and, if not, what is the rank of the variables. The smaller the value of TOL the stricter the criterion for selecting the singular value decomposition. If a non-negative value of TOL less than machine precision is entered, the square root of machine precision is used instead.
Constraint: TOL≥0.0.
20:   IRANKX – INTEGEROutput
On exit: the rank of the dependent variables.
If the variables are of full rank then IRANKX=NX.
If the variables are not of full rank then IRANKX is an estimate of the rank of the dependent variables. IRANKX is calculated as the number of singular values greater than TOL×(largest singular value).
21:   WK IWK – REAL (KIND=nag_wp) arrayWorkspace
22:   IWK – INTEGERInput
On entry: the dimension of the array WK as declared in the (sub)program from which G03ACF is called.
Constraints:
  • if NX≥NG-1, IWK≥N×NX+max 5×NX-1+NX+1×NX,N+1;
  • if NX<NG-1, IWK≥N×NX+max 5×NX-1+NG-1×NX,N+1.
23:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, | NX<1,
or | NG<2,
or | M<NX,
or | N<NX+NG,
or | LDX<N,
or | LDCVX<NX,
or | LDCVM<NG,
or | LDE < min NX,NG-1 ,
or | NX≥NG-1 and IWK < N × NX + max 5×NX-1+NX+1×NX,N ,
or | NX<NG-1 and IWK < N × NX + max 5×NX-1+NG-1×NX,N ,
or | WEIGHT≠'U', 'W' or 'V',
or | TOL<0.0.
IFAIL=2
On entry, WEIGHT='W' or 'V' and a value of WT<0.0.
IFAIL=3
On entry, | a value of ING<1,
or | a value of ING>NG.
IFAIL=4
On entry, the number of variables to be included in the analysis as indicated by ISX is not equal to NX.
IFAIL=5
A singular value decomposition has failed to converge. This is an unlikely error exit.
IFAIL=6
A canonical correlation is equal to 1. This will happen if the variables provide an exact indication as to which group every observation is allocated.
IFAIL=7
On entry, | less than two groups have nonzero membership, i.e., the effective number of groups is less than 2,
or | the effective number of groups plus the number of variables, NX, is greater than the effective number of observations.
IFAIL=8
The rank of the variables is 0. This will happen if all the variables are constants.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

As the computation involves the use of orthogonal matrices and a singular value decomposition rather than the traditional computing of a sum of squares matrix and the use of an eigenvalue decomposition, G03ACF should be less affected by ill-conditioned problems.

8 Parallelism and Performance

G03ACF is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
G03ACF makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

None.

10 Example

This example uses a sample of nine observations, each consisting of three variables plus a group indicator. There are three groups. An unweighted canonical variate analysis is performed and the results printed.

10.1 Program Text

Program Text (g03acfe.f90)

10.2 Program Data

Program Data (g03acfe.d)

10.3 Program Results

Program Results (g03acfe.r)

G03 Chapter Contents
G03 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


G03ADF : NAG Library, Mark 26

G03 Chapter Contents
G03 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

G03ADF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

G03ADF performs canonical correlation analysis upon input data matrices.

2 Specification

SUBROUTINE G03ADF ( WEIGHT, N, M, Z, LDZ, ISZ, NX, NY, WT, E, LDE, NCV, CVX, LDCVX, MCV, CVY, LDCVY, TOL, WK, IWK, IFAIL)
INTEGER | N, M, LDZ, ISZ(M), NX, NY, LDE, NCV, LDCVX, MCV, LDCVY, IWK, IFAIL
REAL (KIND=nag_wp) | Z(LDZ,M), WT(*), E(LDE,6), CVX(LDCVX,MCV), CVY(LDCVY,MCV), TOL, WK(IWK)
CHARACTER(1) | WEIGHT

3 Description

Let there be two sets of variables, x and y. For a sample of n observations on nx variables in a data matrix X and ny variables in a data matrix Y, canonical correlation analysis seeks to find a small number of linear combinations of each set of variables in order to explain or summarise the relationships between them. The variables thus formed are known as canonical variates.
Let the variance-covariance matrix of the two datasets be
S xx S xy S yx S yy
and let
Σ=S yy -1 S yx S xx -1 S xy
then the canonical correlations can be calculated from the eigenvalues of the matrix Σ. However, G03ADF calculates the canonical correlations by means of a singular value decomposition (SVD) of a matrix V. If the rank of the data matrix X is kx and the rank of the data matrix Y is ky, and both X and Y have had variable (column) means subtracted then the kx by ky matrix V is given by:
V=QxT Qy,
where Qx is the first kx columns of the orthogonal matrix Q either from the QR decomposition of X if X is of full column rank, i.e., kx=nx:
X=QxRx
or from the SVD of X if kx<nx:
X=QxDx PxT.
Similarly Qy is the first ky columns of the orthogonal matrix Q either from the QR decomposition of Y if Y is of full column rank, i.e., ky=ny:
Y=QyRy
or from the SVD of Y if ky<ny:
Y=QyDy PyT.
Let the SVD of V be:
V=Ux Δ UyT
then the nonzero elements of the diagonal matrix Δ, δi, for i=1,2,…,l, are the l canonical correlations associated with the l canonical variates, where l = min kx,ky .
The eigenvalues, λi 2, of the matrix Σ are given by:
λi 2 = δi 2 .
The value of πi=λi 2/∑λi 2 gives the proportion of variation explained by the ith canonical variate. The values of the πi's give an indication as to how many canonical variates are needed to adequately describe the data, i.e., the dimensionality of the problem.
To test for a significant dimensionality greater than i the χ 2 statistic:
n - 12 kx + ky + 3 ∑ j=i+1 l log 1 - δj 2
can be used. This is asymptotically distributed as a χ 2-distribution with kx-iky-i degrees of freedom. If the test for i=kmin is not significant, then the remaining tests for i>kmin should be ignored.
The loadings for the canonical variates are calculated from the matrices Ux and Uy respectively. These matrices are scaled so that the canonical variates have unit variance.

4 References

Hastings N A J and Peacock J B (1975) Statistical Distributions Butterworth
Kendall M G and Stuart A (1976) The Advanced Theory of Statistics (Volume 3) (3rd Edition) Griffin
Morrison D F (1967) Multivariate Statistical Methods McGraw–Hill

5 Arguments

1:   WEIGHT – CHARACTER(1)Input
On entry: indicates if weights are to be used.
WEIGHT='U'
No weights are used.
WEIGHT='W'
Weights are used and must be supplied in WT.
Constraint: WEIGHT='U' or 'W'.
2:   N – INTEGERInput
On entry: n, the number of observations.
Constraint: N>NX+NY.
3:   M – INTEGERInput
On entry: m, the total number of variables.
Constraint: M≥NX+NY.
4:   Z LDZM – REAL (KIND=nag_wp) arrayInput
On entry: Z ij must contain the ith observation for the jth variable, for i=1,2,…,n and j=1,2,…,m.
Both x and y variables are to be included in Z, the indicator array, ISZ, being used to assign the variables in Z to the x or y sets as appropriate.
5:   LDZ – INTEGERInput
On entry: the first dimension of the array Z as declared in the (sub)program from which G03ADF is called.
Constraint: LDZ≥N.
6:   ISZ M – INTEGER arrayInput
On entry: ISZ j indicates whether or not the jth variable is included in the analysis and to which set of variables it belongs.
ISZ j>0
The variable contained in the jth column of Z is included as an x variable in the analysis.
ISZ j<0
The variable contained in the jth column of Z is included as a y variable in the analysis.
ISZ j=0
The variable contained in the jth column of Z is not included in the analysis.
Constraint: only NX elements of ISZ can be >0 and only NY elements of ISZ can be <0.
7:   NX – INTEGERInput
On entry: the number of x variables in the analysis, nx.
Constraint: NX≥1.
8:   NY – INTEGERInput
On entry: the number of y variables in the analysis, ny.
Constraint: NY≥1.
9:   WT* – REAL (KIND=nag_wp) arrayInput
Note: the dimension of the array WT must be at least N if WEIGHT='W', and at least 1 otherwise.
On entry: if WEIGHT='W', the first n elements of WT must contain the weights to be used in the analysis.
If WT i=0.0, the ith observation is not included in the analysis. The effective number of observations is the sum of weights.
If WEIGHT='U', WT is not referenced and the effective number of observations is n.
Constraints:
  • WT i≥0.0, for i=1,2,…,n;
  • the sum of weights≥NX+NY+1.
10:   E LDE 6 – REAL (KIND=nag_wp) arrayOutput
On exit: the statistics of the canonical variate analysis.
E i 1
The canonical correlations, δi, for i=1,2,…,l.
E i 2
The eigenvalues of Σ, λi 2, for i=1,2,…,l.
E i 3
The proportion of variation explained by the ith canonical variate, for i=1,2,…,l.
E i 4
The χ 2 statistic for the ith canonical variate, for i=1,2,…,l.
E i 5
The degrees of freedom for χ 2 statistic for the ith canonical variate, for i=1,2,…,l.
E i 6
The significance level for the χ 2 statistic for the ith canonical variate, for i=1,2,…,l.
11:   LDE – INTEGERInput
On entry: the first dimension of the array E as declared in the (sub)program from which G03ADF is called.
Constraint: LDE≥min NX,NY.
12:   NCV – INTEGEROutput
On exit: the number of canonical correlations, l. This will be the minimum of the rank of X and the rank of Y.
13:   CVX LDCVXMCV – REAL (KIND=nag_wp) arrayOutput
On exit: the canonical variate loadings for the x variables. CVX ij contains the loading coefficient for the ith x variable on the jth canonical variate.
14:   LDCVX – INTEGERInput
On entry: the first dimension of the array CVX as declared in the (sub)program from which G03ADF is called.
Constraint: LDCVX≥NX.
15:   MCV – INTEGERInput
On entry: an upper limit to the number of canonical variates.
Constraint: MCV≥min NX,NY.
16:   CVY LDCVYMCV – REAL (KIND=nag_wp) arrayOutput
On exit: the canonical variate loadings for the y variables. CVY ij contains the loading coefficient for the ith y variable on the jth canonical variate.
17:   LDCVY – INTEGERInput
On entry: the first dimension of the array CVY as declared in the (sub)program from which G03ADF is called.
Constraint: LDCVY≥NY.
18:   TOL – REAL (KIND=nag_wp)Input
On entry: the value of TOL is used to decide if the variables are of full rank and, if not, what is the rank of the variables. The smaller the value of TOL the stricter the criterion for selecting the singular value decomposition. If a non-negative value of TOL less than machine precision is entered, the square root of machine precision is used instead.
Constraint: TOL≥0.0.
19:   WK IWK – REAL (KIND=nag_wp) arrayWorkspace
20:   IWK – INTEGERInput
On entry: the dimension of the array WK as declared in the (sub)program from which G03ADF is called.
Constraints:
  • if NX≥NY, IWK≥N×NX+NX+NY+max 5×NX-1+NX×NX,N×NY+1;
  • if NX<NY, IWK≥N×NY+NX+NY+max 5×NY-1+NY×NY,N×NX+1.
21:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, | NX<1,
or | NY<1,
or | M<NX+NY,
or | N≤NX+NY,
or | MCV < min NX,NY ,
or | LDZ<N,
or | LDCVX<NX,
or | LDCVY<NY,
or | LDE < min NX,NY ,
or NX≥NY and
IWK<N×NX+NX+NY+max 5×NX-1+NX×NX,N×NY,
or NX<NY and
IWK<N×NY+NX+NY+max 5×NY-1+NY×NY,N×NX,
or | WEIGHT≠'U' or 'W',
or | TOL<0.0.
IFAIL=2
On entry, a WEIGHT='W' and value of WT<0.0.
IFAIL=3
On entry, | the number of x variables to be included in the analysis as indicated by ISZ is not equal to NX.
or | the number of y variables to be included in the analysis as indicated by ISZ is not equal to NY.
IFAIL=4
On entry, the effective number of observations is less than NX+NY+1.
IFAIL=5
A singular value decomposition has failed to converge. See F02WUF. This is an unlikely error exit.
IFAIL=6
A canonical correlation is equal to 1. This will happen if the x and y variables are perfectly correlated.
IFAIL=7
On entry, the rank of the X matrix or the rank of the Y matrix is 0. This will happen if all the x or y variables are constants.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

As the computation involves the use of orthogonal matrices and a singular value decomposition rather than the traditional computing of a sum of squares matrix and the use of an eigenvalue decomposition, G03ADF should be less affected by ill-conditioned problems.

8 Parallelism and Performance

G03ADF is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
G03ADF makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

None.

10 Example

This example has nine observations and two variables in each set of the four variables read in, the second and third are x variables while the first and last are y variables. Canonical variate analysis is performed and the results printed.

10.1 Program Text

Program Text (g03adfe.f90)

10.2 Program Data

Program Data (g03adfe.d)

10.3 Program Results

Program Results (g03adfe.r)

G03 Chapter Contents
G03 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


G03BAF : NAG Library, Mark 26

G03 Chapter Contents
G03 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

G03BAF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

G03BAF computes orthogonal rotations for a matrix of loadings using a generalized orthomax criterion.

2 Specification

SUBROUTINE G03BAF ( STAND, G, NVAR, K, FL, LDFL, FLR, R, LDR, ACC, MAXIT, ITER, WK, IFAIL)
INTEGER | NVAR, K, LDFL, LDR, MAXIT, ITER, IFAIL
REAL (KIND=nag_wp) | G, FL(LDFL,K), FLR(LDFL,K), R(LDR,K), ACC, WK(2*NVAR+K*K+5*(K-1))
CHARACTER(1) | STAND

3 Description

Let Λ be the p by k matrix of loadings from a variable-directed multivariate method, e.g., canonical variate analysis or factor analysis. This matrix represents the relationship between the original p variables and the k orthogonal linear combinations of these variables, the canonical variates or factors. The latter are only unique up to a rotation in the k-dimensional space they define. A rotation can then be found that simplifies the structure of the matrix of loadings, and hence the relationship between the original and the derived variables. That is, the elements, λ ij*, of the rotated matrix, Λ*, are either relatively large or small. The rotations may be found by minimizing the criterion:
V=∑j=1 k∑i=1 p λ ij* 4-γp∑j=1 k ∑i=1 p λ ij* 2 2
where the constant γ gives a family of rotations with γ=1 giving varimax rotations and γ=0 giving quartimax rotations.
It is generally advised that factor loadings should be standardized, so that the sum of squared elements for each row is one, before computing the rotations.
The matrix of rotations, R, such that Λ*=Λ R, is computed using first an algorithm based on that described by Cooley and Lohnes (1971), which involves the pairwise rotation of the factors. Then a final refinement is made using a method similar to that described by Lawley and Maxwell (1971), but instead of the eigenvalue decomposition, the algorithm has been adapted to incorporate a singular value decomposition.

4 References

Cooley W C and Lohnes P R (1971) Multivariate Data Analysis Wiley
Lawley D N and Maxwell A E (1971) Factor Analysis as a Statistical Method (2nd Edition) Butterworths

5 Arguments

1:   STAND – CHARACTER(1)Input
On entry: indicates if the matrix of loadings is to be row standardized before rotation.
STAND='S'
The loadings are row standardized.
STAND='U'
The loadings are left unstandardized.
Constraint: STAND='S' or 'U'.
2:   G – REAL (KIND=nag_wp)Input
On entry: γ, the criterion constant with γ=1.0 giving varimax rotations and γ=0.0 giving quartimax rotations.
Constraint: G≥0.0.
3:   NVAR – INTEGERInput
On entry: p, the number of original variables.
Constraint: NVAR≥K.
4:   K – INTEGERInput
On entry: k, the number of derived variates or factors.
Constraint: K≥2.
5:   FL LDFLK – REAL (KIND=nag_wp) arrayInput/Output
On entry: Λ, the matrix of loadings. FL ij must contain the loading for the ith variable on the jth factor, for i=1,2,…,p and j=1,2,…,k.
On exit: if STAND='S', the elements of FL are standardized so that the sum of squared elements for each row is 1.0 and then after the computation of the rotations are rescaled; this may lead to slight differences between the input and output values of FL.
If STAND='U', FL will be unchanged on exit.
6:   LDFL – INTEGERInput
On entry: the first dimension of the arrays FL and FLR as declared in the (sub)program from which G03BAF is called.
Constraint: LDFL≥NVAR.
7:   FLR LDFLK – REAL (KIND=nag_wp) arrayOutput
On exit: the rotated matrix of loadings, Λ*. FLR ij will contain the rotated loading for the ith variable on the jth factor, for i=1,2,…,p and j=1,2,…,k.
8:   R LDRK – REAL (KIND=nag_wp) arrayOutput
On exit: the matrix of rotations, R.
9:   LDR – INTEGERInput
On entry: the first dimension of the array R as declared in the (sub)program from which G03BAF is called.
Constraint: LDR≥K.
10:   ACC – REAL (KIND=nag_wp)Input
On entry: indicates the accuracy required. The iterative procedure of Cooley and Lohnes (1971) will be stopped and the final refinement computed when the change in V is less than ACC×max 1.0,V. If ACC is greater than or equal to 0.0 but less than machine precision or if ACC is greater than 1.0, then machine precision will be used instead.
Suggested value: 0.00001.
Constraint: ACC≥0.0.
11:   MAXIT – INTEGERInput
On entry: the maximum number of iterations.
Suggested value: 30.
Constraint: MAXIT≥1.
12:   ITER – INTEGEROutput
On exit: the number of iterations performed.
13:   WK 2×NVAR+K×K+5×K-1 – REAL (KIND=nag_wp) arrayWorkspace
14:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, | K<2,
or | NVAR<K,
or | G<0.0,
or | LDFL<NVAR,
or | LDR<K,
or | ACC<0.0,
or | MAXIT≤0,
or | STAND≠'S' or 'U'.
IFAIL=2
The singular value decomposition has failed to converge. This is an unlikely error exit.
IFAIL=3
The algorithm to find R has failed to reach the required accuracy in the given number of iterations. You should try increasing ACC or increasing MAXIT. The returned solution should be a reasonable approximation.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

The accuracy is determined by the value of ACC.

8 Parallelism and Performance

G03BAF makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

If the results of a principal component analysis as carried out by G03AAF are to be rotated, the loadings as returned in the array P by G03AAF can be supplied via the argument FL to G03BAF. The resulting rotation matrix can then be used to rotate the principal component scores as returned in the array V by G03AAF. The routine F06YAF (DGEMM) may be used for this matrix multiplication.

10 Example

This example is taken from page 75 of Lawley and Maxwell (1971). The results from a factor analysis of ten variables using three factors are input and rotated using varimax rotations without standardizing rows.

10.1 Program Text

Program Text (g03bafe.f90)

10.2 Program Data

Program Data (g03bafe.d)

10.3 Program Results

Program Results (g03bafe.r)

G03 Chapter Contents
G03 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


G03BCF : NAG Library, Mark 26

G03 Chapter Contents
G03 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

G03BCF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

G03BCF computes Procrustes rotations in which an orthogonal rotation is found so that a transformed matrix best matches a target matrix.

2 Specification

SUBROUTINE G03BCF ( STAND, PSCALE, N, M, X, LDX, Y, LDY, YHAT, R, LDR, ALPHA, RSS, RES, WK, IFAIL)
INTEGER | N, M, LDX, LDY, LDR, IFAIL
REAL (KIND=nag_wp) | X(LDX,M), Y(LDY,M), YHAT(LDY,M), R(LDR,M), ALPHA, RSS, RES(N), WK(M*M+7*M)
CHARACTER(1) | STAND, PSCALE

3 Description

Let X and Y be n by m matrices. They can be considered as representing sets of n points in an m-dimensional space. The X matrix may be a matrix of loadings from say factor or canonical variate analysis, and the Y matrix may be a postulated pattern matrix or the loadings from a different sample. The problem is to relate the two sets of points without disturbing the relationships between the points in each set. This can be achieved by translating, rotating and scaling the sets of points. The Y matrix is considered as the target matrix and the X matrix is rotated to match that matrix.
First the two sets of points are translated so that their centroids are at the origin to give Xc and Yc, i.e., the matrices will have zero column means. Then the rotation of the translated Xc matrix which minimizes the sum of squared distances between corresponding points in the two sets is found. This is computed from the singular value decomposition of the matrix:
XcT Yc=UD VT,
where U and V are orthogonal matrices and D is a diagonal matrix. The matrix of rotations, R, is computed as:
R=U VT.
After rotation, a scaling or dilation factor, α, may be estimated by least squares. Thus, the final set of points that best match Yc is given by:
Y^c=α Xc R.
Before rotation, both sets of points may be normalized to have unit sums of squares or the X matrix may be normalized to have the same sum of squares as the Y matrix. After rotation, the results may be translated to the original Y centroid.
The ith residual, ri, is given by the distance between the point given in the ith row of Y and the point given in the ith row of Y^. The residual sum of squares is also computed.

4 References

Krzanowski W J (1990) Principles of Multivariate Analysis Oxford University Press
Lawley D N and Maxwell A E (1971) Factor Analysis as a Statistical Method (2nd Edition) Butterworths

5 Arguments

1:   STAND – CHARACTER(1)Input
On entry: indicates if translation/normalization is required.
STAND='N'
There is no translation or normalization.
STAND='Z'
There is translation to the origin (i.e., to zero).
STAND='C'
There is translation to origin and then to the Y centroid after rotation.
STAND='U'
There is unit normalization.
STAND='S'
There is translation and normalization (i.e., there is standardization).
STAND='M'
There is translation and normalization to Y scale, then translation to the Y centroid after rotation (i.e., they are matched).
Constraint: STAND='N', 'Z', 'C', 'U', 'S' or 'M'.
2:   PSCALE – CHARACTER(1)Input
On entry: indicates if least squares scaling is to be applied after rotation.
PSCALE='S'
Scaling is applied.
PSCALE='U'
No scaling is applied.
Constraint: PSCALE='S' or 'U'.
3:   N – INTEGERInput
On entry: n, the number of points.
Constraint: N≥M.
4:   M – INTEGERInput
On entry: m, the number of dimensions.
Constraint: M≥1.
5:   X LDXM – REAL (KIND=nag_wp) arrayInput/Output
On entry: X, the matrix to be rotated.
On exit: if STAND='N', X will be unchanged.
If STAND='Z', 'C', 'S' or 'M', X will be translated to have zero column means.
If STAND='U' or 'S', X will be scaled to have unit sum of squares.
If STAND='M', X will be scaled to have the same sum of squares as Y.
6:   LDX – INTEGERInput
On entry: the first dimension of the array X as declared in the (sub)program from which G03BCF is called.
Constraint: LDX≥N.
7:   Y LDYM – REAL (KIND=nag_wp) arrayInput/Output
On entry: the target matrix, Y.
On exit: if STAND='N', Y will be unchanged.
If STAND='Z' or 'S', Y will be translated to have zero column means.
If STAND='U' or 'S', Y will be scaled to have unit sum of squares.
If STAND='C' or 'M', Y will be translated and then after rotation translated back. The output Y should be the same as the input Y except for rounding errors.
8:   LDY – INTEGERInput
On entry: the first dimension of the arrays Y and YHAT as declared in the (sub)program from which G03BCF is called.
Constraint: LDY≥N.
9:   YHAT LDYM – REAL (KIND=nag_wp) arrayOutput
On exit: the fitted matrix, Y^.
10:   R LDRM – REAL (KIND=nag_wp) arrayOutput
On exit: the matrix of rotations, R, see Section 9.
11:   LDR – INTEGERInput
On entry: the first dimension of the array R as declared in the (sub)program from which G03BCF is called.
Constraint: LDR≥M.
12:   ALPHA – REAL (KIND=nag_wp)Output
On exit: if PSCALE='S' the scaling factor, α; otherwise ALPHA is not set.
13:   RSS – REAL (KIND=nag_wp)Output
On exit: the residual sum of squares.
14:   RES N – REAL (KIND=nag_wp) arrayOutput
On exit: the residuals, ri, for i=1,2,…,n.
15:   WK M×M+7×M – REAL (KIND=nag_wp) arrayWorkspace
16:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, | N<M,
or | M<1,
or | LDX<N,
or | LDY<N,
or | LDR<M,
or | STAND≠'N', 'Z', 'C', 'U', 'S' or 'M',
or | PSCALE≠'S' or 'U'.
IFAIL=2
On entry, either X or Y contain only zero-points (possibly after translation) when normalization is to be applied.
IFAIL=3
The Y^ matrix contains only zero-points when least squares scaling is applied.
IFAIL=4
The singular value decomposition has failed to converge. This is an unlikely error exit.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

The accuracy of the calculation of the rotation matrix largely depends upon the singular value decomposition. See the F08 Chapter Introduction for further details.

8 Parallelism and Performance

G03BCF makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

Note that if the matrix XcT Y is not of full rank, then the matrix of rotations, R, may not be unique even if there is a unique solution in terms of the rotated matrix, Y^c. The matrix R may also include reflections as well as pure rotations, see Krzanowski (1990).
If the column dimensions of the X and Y matrices are not equal, the smaller of the two should be supplemented by columns of zeros. Adding a column of zeros to both X and Y will have the effect of allowing reflections as well as rotations.

10 Example

Three points representing the vertices of a triangle in two dimensions are input. The points are translated and rotated to match the triangle given by 0,0, 1,0, 0,2 and scaling is applied after rotation. The target matrix and fitted matrix are printed along with additional information.

10.1 Program Text

Program Text (g03bcfe.f90)

10.2 Program Data

Program Data (g03bcfe.d)

10.3 Program Results

Program Results (g03bcfe.r)

G03 Chapter Contents
G03 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


G03BDF : NAG Library, Mark 26

G03 Chapter Contents
G03 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

G03BDF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

G03BDF calculates a ProMax rotation, given information following an orthogonal rotation.

2 Specification

SUBROUTINE G03BDF ( STAND, N, M, X, LDX, RO, LDRO, POWER, FP, LDFP, R, LDR, PHI, LDPHI, FS, LDFS, IFAIL)
INTEGER | N, M, LDX, LDRO, LDFP, LDR, LDPHI, LDFS, IFAIL
REAL (KIND=nag_wp) | X(LDX,M), RO(LDRO,M), POWER, FP(LDFP,M), R(LDR,M), PHI(LDPHI,M), FS(LDFS,M)
CHARACTER(1) | STAND

3 Description

Let X and Y denote n by m matrices each representing a set of n points in an m-dimensional space. The X matrix is a matrix of loadings as returned by G03BAF, that is following an orthogonal rotation of a loadings matrix Z. The target matrix Y is calculated as a power transformation of X that preserves the sign of the loadings. Let X ij and Y ij denote the i,jth element of matrices X and Y. Given a value greater than one for the exponent p:
Y ij = δ ij X ij p ,
for
  • i=1,2,…,n;
  • j=1,2,…,m;
  • δ ij = -1 , if ​ X ij < 0 ; ​ 1 , otherwise.
The above power transformation tends to increase the difference between high and low values of loadings and is intended to increase the interpretability of a solution.
In the second step a solution of:
XW=Y ,   X,Y ∈ ℝ n×m , ​ W ∈ ℝ m×m ,
is found for W in the least squares sense by use of singular value decomposition of the orthogonal loadings X. The ProMax rotation matrix R is then given by
R=OW W~ ,  O, ​ W~ ∈ ℝ m×m ,
where O is the rotation matrix from an orthogonal transformation, and W~ is a matrix with the square root of diagonal elements of WT W-1 on its diagonal and zeros elsewhere.
The ProMax factor pattern matrix P is given by
P = X W W~ ,   P ∈ ℝ n×m ;
the inter-factor correlations Φ are given by
Φ= QT Q-1 ,   Φ ∈ ℝ m×m ;
where Q=W W~; and the factor structure S is given by
S=PΦ ,   S ∈ ℝ n×m .
Optionally, the rows of target matrix Y can be scaled by the communalities of loadings.

4 References

None.

5 Arguments

1:   STAND – CHARACTER(1)Input
On entry: indicates how loadings are normalized.
STAND='S'
Rows of Y are (Kaiser) normalized by the communalities of the loadings.
STAND='U'
Rows are not normalized.
Constraint: STAND='U' or 'S'.
2:   N – INTEGERInput
On entry: n, the number of points.
Constraint: N≥M.
3:   M – INTEGERInput
On entry: m, the number of dimensions.
Constraint: M≥1.
4:   X LDXM – REAL (KIND=nag_wp) arrayInput
On entry: the loadings matrix following an orthogonal rotation, X.
5:   LDX – INTEGERInput
On entry: the first dimension of the array X as declared in the (sub)program from which G03BDF is called.
Constraint: LDX≥N.
6:   RO LDROM – REAL (KIND=nag_wp) arrayInput
On entry: the orthogonal rotation matrix, O.
7:   LDRO – INTEGERInput
On entry: the first dimension of the array RO as declared in the (sub)program from which G03BDF is called.
Constraint: LDRO≥M.
8:   POWER – REAL (KIND=nag_wp)Input
On entry: p, the value of exponent.
Constraint: POWER>1.0.
9:   FP LDFPM – REAL (KIND=nag_wp) arrayOutput
On exit: the factor pattern matrix, P.
10:   LDFP – INTEGERInput
On entry: the first dimension of the array FP as declared in the (sub)program from which G03BDF is called.
Constraint: LDFP≥N.
11:   R LDRM – REAL (KIND=nag_wp) arrayOutput
On exit: the ProMax rotation matrix, R.
12:   LDR – INTEGERInput
On entry: the first dimension of the array R as declared in the (sub)program from which G03BDF is called.
Constraint: LDR≥M.
13:   PHI LDPHIM – REAL (KIND=nag_wp) arrayOutput
On exit: the matrix of inter-factor correlations, Φ.
14:   LDPHI – INTEGERInput
On entry: the first dimension of the array PHI as declared in the (sub)program from which G03BDF is called.
Constraint: LDPHI≥M.
15:   FS LDFSM – REAL (KIND=nag_wp) arrayOutput
On exit: the factor structure matrix, S.
16:   LDFS – INTEGERInput
On entry: the first dimension of the array FS as declared in the (sub)program from which G03BDF is called.
Constraint: LDFS≥N.
17:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, M=value.
Constraint: M≥1.
On entry, POWER=value.
Constraint: POWER>1.0.
On entry, STAND=value.
Constraint: STAND='U' or 'S'.
IFAIL=2
On entry, LDFP=value and N=value.
Constraint: LDFP≥N.
On entry, LDFS=value and N=value.
Constraint: LDFS≥N.
On entry, LDPHI=value and M=value.
Constraint: LDPHI≥M.
On entry, LDR=value and M=value.
Constraint: LDR≥M.
On entry, LDRO=value and M=value.
Constraint: LDRO≥M.
On entry, LDX=value and N=value.
Constraint: LDX≥N.
On entry, N=value and M=value.
Constraint: N≥M.
IFAIL=20
SVD failed to converge.
IFAIL=100
An internal error has occurred in this routine. Check the routine call and any array sizes. If the call is correct then please contact NAG for assistance.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

The calculations are believed to be stable.

8 Parallelism and Performance

G03BDF is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
G03BDF makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

None.

10 Example

This example reads a loadings matrix and calculates a varimax transformation before calculating P, R and σ for a ProMax rotation.

10.1 Program Text

Program Text (g03bdfe.f90)

10.2 Program Data

Program Data (g03bdfe.d)

10.3 Program Results

Program Results (g03bdfe.r)

G03 Chapter Contents
G03 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


G03CAF : NAG Library, Mark 26

G03 Chapter Contents
G03 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

G03CAF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

G03CAF computes the maximum likelihood estimates of the arguments of a factor analysis model. Either the data matrix or a correlation/covariance matrix may be input. Factor loadings, communalities and residual correlations are returned.

2 Specification

SUBROUTINE G03CAF ( MATRIX, WEIGHT, N, M, X, LDX, NVAR, ISX, NFAC, WT, E, STAT, COM, PSI, RES, FL, LDFL, IOP, IWK, WK, LWK, IFAIL)
INTEGER | N, M, LDX, NVAR, ISX(M), NFAC, LDFL, IOP(5), IWK(4*NVAR+2), LWK, IFAIL
REAL (KIND=nag_wp) | X(LDX,M), WT(*), E(NVAR), STAT(4), COM(NVAR), PSI(NVAR), RES(NVAR*(NVAR-1)/2), FL(LDFL,NFAC), WK(LWK)
CHARACTER(1) | MATRIX, WEIGHT

3 Description

Let p variables, x 1,x 2,…,xp, with variance-covariance matrix Σ be observed. The aim of factor analysis is to account for the covariances in these p variables in terms of a smaller number, k, of hypothetical variables, or factors, f 1,f 2,…,fk. These are assumed to be independent and to have unit variance. The relationship between the observed variables and the factors is given by the model:
xi=∑j=1 k λ ijfj+ei,  i=1,2,…,p
where λ ij, for i=1,2,…,p and j=1,2,…,k, are the factor loadings and ei, for i=1,2,…,p, are independent random variables with variances ψi, for i=1,2,…,p. The ψi represent the unique component of the variation of each observed variable. The proportion of variation for each variable accounted for by the factors is known as the communality. For this routine it is assumed that both the k factors and the ei's follow independent Normal distributions.
The model for the variance-covariance matrix, Σ, can be written as:
Σ=Λ ΛT+Ψ (1)
where Λ is the matrix of the factor loadings, λ ij, and Ψ is a diagonal matrix of unique variances, ψi, for i=1,2,…,p.
The estimation of the arguments of the model, Λ and Ψ, by maximum likelihood is described by Lawley and Maxwell (1971). The log-likelihood is:
-12 n-1 log Σ-12 n-1 trace S,Σ-1+constant,
where n is the number of observations, S is the sample variance-covariance matrix or, if weights are used, S is the weighted sample variance-covariance matrix and n is the effective number of observations, that is, the sum of the weights. The constant is independent of the arguments of the model. A two stage maximization is employed. It makes use of the function F Ψ, which is, up to a constant, -2/n-1 times the log-likelihood maximized over Λ. This is then minimized with respect to Ψ to give the estimates, Ψ^, of Ψ. The function F Ψ can be written as:
F Ψ=∑j=k+1 p θj-log⁡θj-p-k
where values θj, for j=1,2,…,p are the eigenvalues of the matrix:
S*=Ψ-1/2 S Ψ-1/2.
The estimates Λ^, of Λ, are then given by scaling the eigenvectors of S*, which are denoted by V:
Λ^=Ψ 1/2 V Θ-I 1/2.
where Θ is the diagonal matrix with elements θi, and I is the identity matrix.
The minimization of F Ψ is performed using E04LBF which uses a modified Newton algorithm. The computation of the Hessian matrix is described by Clark (1970). However, instead of using the eigenvalue decomposition of the matrix S* as described above, the singular value decomposition of the matrix R Ψ-1/2 is used, where R is obtained either from the QR decomposition of the (scaled) mean centred data matrix or from the Cholesky decomposition of the correlation/covariance matrix. The routine E04LBF ensures that the values of ψi are greater than a given small positive quantity, δ, so that the communality is always less than one. This avoids the so called Heywood cases.
In addition to the values of Λ, Ψ and the communalities, G03CAF returns the residual correlations, i.e., the off-diagonal elements of C-Λ ΛT+Ψ where C is the sample correlation matrix. G03CAF also returns the test statistic:
χ 2=n-1-2 p+5/6-2 k/3 F Ψ^
which can be used to test the goodness-of-fit of the model (1), see Lawley and Maxwell (1971) and Morrison (1967).

4 References

Clark M R B (1970) A rapidly convergent method for maximum likelihood factor analysis British J. Math. Statist. Psych.
Hammarling S (1985) The singular value decomposition in multivariate statistics SIGNUM Newsl. 20(3) 2–25
Lawley D N and Maxwell A E (1971) Factor Analysis as a Statistical Method (2nd Edition) Butterworths
Morrison D F (1967) Multivariate Statistical Methods McGraw–Hill

5 Arguments

1:   MATRIX – CHARACTER(1)Input
On entry: selects the type of matrix on which factor analysis is to be performed.
MATRIX='D'
The data matrix will be input in X and factor analysis will be computed for the correlation matrix.
MATRIX='S'
The data matrix will be input in X and factor analysis will be computed for the covariance matrix, i.e., the results are scaled as described in Section 9.
MATRIX='C'
The correlation/variance-covariance matrix will be input in X and factor analysis computed for this matrix.
See Section 9.
Constraint: MATRIX='D', 'S' or 'C'.
2:   WEIGHT – CHARACTER(1)Input
On entry: if MATRIX='D' or 'S', WEIGHT indicates if weights are to be used.
WEIGHT='U'
No weights are used.
WEIGHT='W'
Weights are used and must be supplied in WT.
Note: if MATRIX='C', WEIGHT is not referenced.
Constraint: if MATRIX='D' or 'S', WEIGHT='U' or 'W'.
3:   N – INTEGERInput
On entry: if MATRIX='D' or 'S' the number of observations in the data array X.
If MATRIX='C' the (effective) number of observations used in computing the (possibly weighted) correlation/variance-covariance matrix input in X.
Constraint: N>NVAR.
4:   M – INTEGERInput
On entry: the number of variables in the data/correlation/variance-covariance matrix.
Constraint: M≥NVAR.
5:   X LDXM – REAL (KIND=nag_wp) arrayInput
On entry: the input matrix.
If MATRIX='D' or 'S', X must contain the data matrix, i.e., X ij must contain the ith observation for the jth variable, for i=1,2,…,n and j=1,2,…,M.
If MATRIX='C', X must contain the correlation or variance-covariance matrix. Only the upper triangular part is required.
6:   LDX – INTEGERInput
On entry: the first dimension of the array X as declared in the (sub)program from which G03CAF is called.
Constraints:
  • if MATRIX='D' or 'S', LDX≥N;
  • if MATRIX='C', LDX≥M.
7:   NVAR – INTEGERInput
On entry: p, the number of variables in the factor analysis.
Constraint: NVAR≥2.
8:   ISX M – INTEGER arrayInput
On entry: ISX j indicates whether or not the jth variable is included in the factor analysis. If ISX j≥1, the variable represented by the jth column of X is included in the analysis; otherwise it is excluded, for j=1,2,…,M.
Constraint: ISX j>0 for NVAR values of j.
9:   NFAC – INTEGERInput
On entry: k, the number of factors.
Constraint: 1≤NFAC≤NVAR.
10:   WT* – REAL (KIND=nag_wp) arrayInput
Note: the dimension of the array WT must be at least N if WEIGHT='W' and MATRIX='D' or 'S', and at least 1 otherwise.
On entry: if WEIGHT='W' and MATRIX='D' or 'S', WT must contain the weights to be used in the factor analysis. The effective number of observations in the analysis will then be the sum of weights. If WT i=0.0, the ith observation is not included in the analysis.
If WEIGHT='U' or MATRIX='C', WT is not referenced and the effective number of observations is n.
Constraint: if WEIGHT='W', the sum of weights >NVAR, WT i≥0.0, for i=1,2,…,n.
11:   E NVAR – REAL (KIND=nag_wp) arrayOutput
On exit: the eigenvalues θi, for i=1,2,…,p.
12:   STAT 4 – REAL (KIND=nag_wp) arrayOutput
On exit: the test statistics.
STAT 1
Contains the value F Ψ^.
STAT 2
Contains the test statistic, χ 2.
STAT 3
Contains the degrees of freedom associated with the test statistic.
STAT 4
Contains the significance level.
13:   COM NVAR – REAL (KIND=nag_wp) arrayOutput
On exit: the communalities.
14:   PSI NVAR – REAL (KIND=nag_wp) arrayOutput
On exit: the estimates of ψi, for i=1,2,…,p.
15:   RES NVAR×NVAR-1/2 – REAL (KIND=nag_wp) arrayOutput
On exit: the residual correlations. The residual correlation for the ith and jth variables is stored in RES j-1 j-2 /2+i , i<j.
16:   FL LDFLNFAC – REAL (KIND=nag_wp) arrayOutput
On exit: the factor loadings. FL ij contains λ ij, for i=1,2,…,p and j=1,2,…,k.
17:   LDFL – INTEGERInput
On entry: the first dimension of the array FL as declared in the (sub)program from which G03CAF is called.
Constraint: LDFL≥NVAR.
18:   IOP 5 – INTEGER arrayInput
On entry: options for the optimization. There are four options to be set:
iprint | controls iteration monitoring;
if iprint≤0, then there is no printing of information else if iprint>0, then information is printed at every iprint iterations. The information printed consists of the value of F Ψ at that iteration, the number of evaluations of F Ψ, the current estimates of the communalities and an indication of whether or not they are at the boundary.
maxfun | the maximum number of function evaluations.
acc | the required accuracy for the estimates of ψi.
eps | a lower bound for the values of ψ, see Section 3.
Let ε=machine precision then if IOP 1=0, then the following default values are used:
  • iprint=-1
  • maxfun=100 p
  • acc=10 ε
  • eps=ε
If IOP 1≠0, then
  • iprint=IOP 2
  • maxfun=IOP 3
  • acc=10-l where l=IOP 4
  • eps=10-l where l=IOP 5
Constraint: if IOP 1≠0, IOP i must be such that maxfun≥1, ε≤acc<1 and ε≤eps<1, for i=3,4,5.
19:   IWK 4×NVAR+2 – INTEGER arrayWorkspace
20:   WK LWK – REAL (KIND=nag_wp) arrayWorkspace
21:   LWK – INTEGERInput
On entry: the dimension of the array WK as declared in the (sub)program from which G03CAF is called. The length of the workspace.
Constraints:
  • if MATRIX='D' or 'S', LWK≥max 5×NVAR×NVAR+33×NVAR-4/2,N×NVAR+7×NVAR+NVAR×NVAR-1/2;
  • if MATRIX='C', LWK≥5×NVAR×NVAR+33×NVAR-4/2.
22:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, because for this routine the values of the output arguments may be useful even if IFAIL≠0 on exit, the recommended value is -1. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Note: G03CAF may return useful information for one or more of the following detected errors or warnings.
Errors or warnings detected by the routine:
IFAIL=1
On entry, | LDFL<NVAR,
or | NVAR<2,
or | N≤NVAR,
or | NFAC<1,
or | NVAR<NFAC,
or | M<NVAR,
or | MATRIX='D' or 'S' and LDX<N,
or | MATRIX='C' and LDX<M,
or | MATRIX≠'D', 'S' or 'C',
or | MATRIX='D' or 'S' and WEIGHT≠'U' or 'W',
or | IOP 1≠0 and IOP 3 is such that maxfun<1,
or | IOP 1≠0 and IOP 4 is such that acc≥1.0,
or | IOP 1≠0 and IOP 4 is such that acc<machine precision,
or | IOP 1≠0 and IOP 5 is such that eps≥1.0,
or | IOP 1≠0 and IOP 5 is such that eps<machine precision,
or | MATRIX='C' and LWK<5×NVAR×NVAR+33×NVAR-4/2,
or MATRIX='D' or 'S' and
LWK<max 5×NVAR×NVAR+33×NVAR-4/2,N×NVAR+7×NVAR+NVAR×NVAR-1/2.
IFAIL=2
On entry, WEIGHT='W' and a value of WT<0.0.
IFAIL=3
On entry, there are not exactly NVAR elements of ISX>0, or the effective number of observations ≤NVAR.
IFAIL=4
On entry, MATRIX='D' or 'S' and the data matrix is not of full column rank, or MATRIX='C' and the input correlation/variance-covariance matrix is not positive definite.
This exit may also be caused by two of the eigenvalues of S* being equal; this is rare (see Lawley and Maxwell (1971)), and may be due to the data/correlation matrix being almost singular.
IFAIL=5
A singular value decomposition has failed to converge. This is a very unlikely error exit.
IFAIL=6
The estimation procedure has failed to converge in the given number of iterations. Change IOP to either increase number of iterations maxfun or increase the value of acc.
IFAIL=7
The convergence is not certain but a lower point could not be found. See E04LBF for further details. In this case all results are computed.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

The accuracy achieved is discussed in E04LBF with the value of the argument XTOL given by acc as described in parameter IOP.

8 Parallelism and Performance

G03CAF is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
G03CAF makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The factor loadings may be orthogonally rotated by using G03BAF and factor score coefficients can be computed using G03CCF. The maximum likelihood estimators are invariant to a change in scale. This means that the results obtained will be the same (up to a scaling factor) if either the correlation matrix or the variance-covariance matrix is used. As the correlation matrix ensures that all values of ψi are between 0 and 1 it will lead to a more efficient optimization. In the situation when the data matrix is input the results are always computed for the correlation matrix and then scaled if the results for the covariance matrix are required. When you input the covariance/correlation matrix the input matrix itself is used and you are advised to input the correlation matrix rather than the covariance matrix.

10 Example

This example is taken from Lawley and Maxwell (1971). The correlation matrix for nine variables is input and the arguments of a factor analysis model with three factors are estimated and printed.

10.1 Program Text

Program Text (g03cafe.f90)

10.2 Program Data

Program Data (g03cafe.d)

10.3 Program Results

Program Results (g03cafe.r)

G03 Chapter Contents
G03 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


G03CCF : NAG Library, Mark 26

G03 Chapter Contents
G03 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

G03CCF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

G03CCF computes factor score coefficients from the result of fitting a factor analysis model by maximum likelihood as performed by G03CAF.

2 Specification

SUBROUTINE G03CCF ( METHOD, ROTATE, NVAR, NFAC, FL, LDFL, PSI, E, R, LDR, FS, LDFS, WK, IFAIL)
INTEGER | NVAR, NFAC, LDFL, LDR, LDFS, IFAIL
REAL (KIND=nag_wp) | FL(LDFL,NFAC), PSI(NVAR), E(NVAR), R(LDR,*), FS(LDFS,NFAC), WK(NVAR)
CHARACTER(1) | METHOD, ROTATE

3 Description

A factor analysis model aims to account for the covariances among p variables, observed on n individuals, in terms of a smaller number, k, of unobserved variables or factors. The values of the factors for an individual are known as factor scores. G03CAF fits the factor analysis model by maximum likelihood and returns the estimated factor loading matrix, Λ, and the diagonal matrix of variances of the unique components, Ψ. To obtain estimates of the factors, a p by k matrix of factor score coefficients, Φ, is formed. The estimated vector of factor scores, f^, is then given by:
f^=xT Φ,
where x is the vector of observed variables for an individual.
There are two commonly used methods of obtaining factor score coefficients.
The regression method:
Φ=Ψ-1 Λ I+ΛTΨ-1 Λ -1,
and Bartlett's method:
Φ=Ψ-1 Λ ΛTΨ-1 Λ -1.
See Lawley and Maxwell (1971) for details of both methods. In the regression method as given above, it is assumed that the factors are not correlated and have unit variance; this is true for models fitted by G03CAF. Further, for models fitted by G03CAF,
ΛTΨ-1 Λ=Θ-I,
where Θ is the diagonal matrix of eigenvalues of the matrix S*, as described in G03CAF.
The factors may be orthogonally rotated using an orthogonal rotation matrix, R, as computed by G03BAF. The factor scores for the rotated matrix are then given by ΛR.

4 References

Lawley D N and Maxwell A E (1971) Factor Analysis as a Statistical Method (2nd Edition) Butterworths

5 Arguments

1:   METHOD – CHARACTER(1)Input
On entry: indicates which method is to be used to compute the factor score coefficients.
METHOD='R'
The regression method is used.
METHOD='B'
Bartlett's method is used.
Constraint: METHOD='B' or 'R'.
2:   ROTATE – CHARACTER(1)Input
On entry: indicates whether a rotation is to be applied.
ROTATE='R'
A rotation will be applied to the coefficients and the rotation matrix, R, must be given in R.
ROTATE='U'
No rotation is applied.
Constraint: ROTATE='R' or 'U'.
3:   NVAR – INTEGERInput
On entry: p, the number of observed variables in the factor analysis.
Constraint: NVAR≥NFAC.
4:   NFAC – INTEGERInput
On entry: k, the number of factors in the factor analysis.
Constraint: NFAC≥1.
5:   FL LDFLNFAC – REAL (KIND=nag_wp) arrayInput
On entry: Λ, the matrix of unrotated factor loadings as returned by G03CAF.
6:   LDFL – INTEGERInput
On entry: the first dimension of the array FL as declared in the (sub)program from which G03CCF is called.
Constraint: LDFL≥NVAR.
7:   PSI NVAR – REAL (KIND=nag_wp) arrayInput
On entry: the diagonal elements of Ψ, as returned by G03CAF.
Constraint: PSI i>0.0, for i=1,2,…,p.
8:   E NVAR – REAL (KIND=nag_wp) arrayInput
On entry: the eigenvalues of the matrix S*, as returned by G03CAF.
Constraint: E i>1.0, for i=1,2,…,p.
9:   R LDR* – REAL (KIND=nag_wp) arrayInput
Note: the second dimension of the array R must be at least 1 if ROTATE='U' and at least NFAC if ROTATE='R'.
On entry: if ROTATE='R', R must contain the orthogonal rotation matrix, R, as returned by G03BAF.
If ROTATE='U', R need not be set.
10:   LDR – INTEGERInput
On entry: the first dimension of the array R as declared in the (sub)program from which G03CCF is called.
Constraints:
  • if ROTATE='R', LDR≥NFAC;
  • otherwise 1.
11:   FS LDFSNFAC – REAL (KIND=nag_wp) arrayOutput
On exit: the matrix of factor score coefficients, Φ. FS ij contains the factor score coefficient for the jth factor and the ith observed variable, for i=1,2,…,p and j=1,2,…,k.
12:   LDFS – INTEGERInput
On entry: the first dimension of the array FS as declared in the (sub)program from which G03CCF is called.
Constraint: LDFS≥NVAR.
13:   WK NVAR – REAL (KIND=nag_wp) arrayWorkspace
14:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, | NFAC<1,
or | NVAR<NFAC,
or | LDFL<NVAR,
or | LDFS<NVAR,
or | ROTATE='R' and LDR<NFAC,
or | METHOD≠'R' or 'B',
or | ROTATE≠'R' or 'U'.
IFAIL=2
On entry, | a value of PSI≤0.0,
or | a value of E≤1.0.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

Accuracy will depend on the accuracy requested when computing the estimated factor loadings using G03CAF.

8 Parallelism and Performance

G03CCF makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

To compute the factor scores using the factor score coefficients the values for the observed variables first need to be standardized by subtracting the sample means and, if the factor analysis is based upon a correlation matrix, dividing by the sample standard deviations. This may be performed using G03ZAF. The standardized variables are then post-multiplied by the factor score coefficients. This may be performed using routines from Chapter F06, for example F06YAF (DGEMM).
If principal component analysis is required the routine G03AAF computes the principal component scores directly. Hence, the factor score coefficients are not needed.

10 Example

This example is taken from Lawley and Maxwell (1971). The correlation matrix for 220 observations on six school subjects is input and a factor analysis model with two factors fitted using G03CAF. The factor score coefficients are computed using the regression method.

10.1 Program Text

Program Text (g03ccfe.f90)

10.2 Program Data

Program Data (g03ccfe.d)

10.3 Program Results

Program Results (g03ccfe.r)

G03 Chapter Contents
G03 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


G03 Chapter Contents : NAG Library Manual, Mark 26

G03 Chapter Introduction
NAG Library Manual

NAG Library Chapter Contents

G03 – Multivariate Methods

G03 Chapter Introduction – a description of the Chapter and an overview of the algorithms available

Routine Name | Mark of Introduction | Purpose
G03AAF Example Text Example Data Example Plot | 14 | nagf_mv_prin_comp Performs principal component analysis
G03ACF Example Text Example Data | 14 | nagf_mv_canon_var Performs canonical variate analysis
G03ADF Example Text Example Data | 14 | nagf_mv_canon_corr Performs canonical correlation analysis
G03BAF Example Text Example Data | 15 | nagf_mv_rot_orthomax Computes orthogonal rotations for loading matrix, generalized orthomax criterion
G03BCF Example Text Example Data | 15 | nagf_mv_rot_procrustes Computes Procrustes rotations
G03BDF Example Text Example Data | 22 | nagf_mv_rot_promax ProMax rotations
G03CAF Example Text Example Data | 15 | nagf_mv_factor Computes maximum likelihood estimates of the parameters of a factor analysis model, factor loadings, communalities and residual correlations
G03CCF Example Text Example Data | 15 | nagf_mv_factor_score Computes factor score coefficients (for use after G03CAF)
G03DAF Example Text Example Data | 15 | nagf_mv_discrim Computes test statistic for equality of within-group covariance matrices and matrices for discriminant analysis
G03DBF Example Text Example Data | 15 | nagf_mv_discrim_mahal Computes Mahalanobis squared distances for group or pooled variance-covariance matrices (for use after G03DAF)
G03DCF Example Text Example Data | 15 | nagf_mv_discrim_group Allocates observations to groups according to selected rules (for use after G03DAF)
G03EAF Example Text Example Data | 16 | nagf_mv_distance_mat Computes distance matrix
G03ECF Example Text Example Data | 16 | nagf_mv_cluster_hier Hierarchical cluster analysis
G03EFF Example Text Example Data | 16 | nagf_mv_cluster_kmeans K-means cluster analysis
G03EHF Example Text Example Data | 16 | nagf_mv_cluster_hier_dendrogram Constructs dendrogram (for use after G03ECF)
G03EJF Example Text Example Data | 16 | nagf_mv_cluster_hier_indicator Computes cluster indicator variable (for use after G03ECF)
G03FAF Example Text Example Data Example Plot | 17 | nagf_mv_multidimscal_metric Performs principal coordinate analysis, classical metric scaling
G03FCF Example Text Example Data Example Plot | 17 | nagf_mv_multidimscal_ordinal Performs non-metric (ordinal) multidimensional scaling
G03GAF Example Text Example Data | 24 | nagf_mv_gaussian_mixture Fits a Gaussian mixture model
G03ZAF Example Text Example Data | 15 | nagf_mv_z_scores Produces standardized values (z-scores) for a data matrix
G03 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


G03DAF : NAG Library, Mark 26

G03 Chapter Contents
G03 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

G03DAF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

G03DAF computes a test statistic for the equality of within-group covariance matrices and also computes matrices for use in discriminant analysis.

2 Specification

SUBROUTINE G03DAF ( WEIGHT, N, M, X, LDX, ISX, NVAR, ING, NG, WT, NIG, GMN, LDGMN, DET, GC, STAT, DF, SIG, WK, IWK, IFAIL)
INTEGER | N, M, LDX, ISX(M), NVAR, ING(N), NG, NIG(NG), LDGMN, IWK(NG), IFAIL
REAL (KIND=nag_wp) | X(LDX,M), WT(*), GMN(LDGMN,NVAR), DET(NG), GC((NG+1)*NVAR*(NVAR+1)/2), STAT, DF, SIG, WK(N*(NVAR+1))
CHARACTER(1) | WEIGHT

3 Description

Let a sample of n observations on p variables come from ng groups with nj observations in the jth group and ∑nj=n. If the data is assumed to follow a multivariate Normal distribution with the variance-covariance matrix of the jth group Σj, then to test for equality of the variance-covariance matrices between groups, that is, Σ 1=Σ 2=⋯=Σ ng=Σ, the following likelihood-ratio test statistic, G, can be used;
G=C n-ng log S-∑j=1 ng nj-1 log Sj ,
where
C= 1-2 p 2+3 p- 1 6 p+ 1ng- 1 ∑j= 1 ng 1 nj- 1 -1 n-ng ,
and Sj are the within-group variance-covariance matrices and S is the pooled variance-covariance matrix given by
S=∑j=1 ng nj-1 Sj n-ng .
For large n, G is approximately distributed as a χ 2 variable with 12 p p+1ng-1 degrees of freedom, see Morrison (1967) for further comments. If weights are used, then S and Sj are the weighted pooled and within-group variance-covariance matrices and n is the effective number of observations, that is, the sum of the weights.
Instead of calculating the within-group variance-covariance matrices and then computing their determinants in order to calculate the test statistic, G03DAF uses a QR decomposition. The group means are subtracted from the data and then for each group, a QR decomposition is computed to give an upper triangular matrix Rj*. This matrix can be scaled to give a matrix Rj such that Sj=RjT Rj. The pooled R matrix is then computed from the Rj matrices. The values of S and the Sj can then be calculated from the diagonal elements of R and the Rj.
This approach means that the Mahalanobis squared distances for a vector observation x can be computed as zT z, where Rj z=x-x-j, x-j being the vector of means of the jth group. These distances can be calculated by G03DBF. The distances are used in discriminant analysis and G03DCF uses the results of G03DAF to perform several different types of discriminant analysis. The differences between the discriminant methods are, in part, due to whether or not the within-group variance-covariance matrices are equal.

4 References

Aitchison J and Dunsmore I R (1975) Statistical Prediction Analysis Cambridge
Kendall M G and Stuart A (1976) The Advanced Theory of Statistics (Volume 3) (3rd Edition) Griffin
Krzanowski W J (1990) Principles of Multivariate Analysis Oxford University Press
Morrison D F (1967) Multivariate Statistical Methods McGraw–Hill

5 Arguments

1:   WEIGHT – CHARACTER(1)Input
On entry: indicates if weights are to be used.
WEIGHT='U'
No weights are used.
WEIGHT='W'
Weights are to be used and must be supplied in WT.
Constraint: WEIGHT='U' or 'W'.
2:   N – INTEGERInput
On entry: n, the number of observations.
Constraint: N≥1.
3:   M – INTEGERInput
On entry: the number of variables in the data array X.
Constraint: M≥NVAR.
4:   X LDXM – REAL (KIND=nag_wp) arrayInput
On entry: X kl must contain the kth observation for the lth variable, for k=1,2,…,n and l=1,2,…,M.
5:   LDX – INTEGERInput
On entry: the first dimension of the array X as declared in the (sub)program from which G03DAF is called.
Constraint: LDX≥N.
6:   ISX M – INTEGER arrayInput
On entry: ISX l indicates whether or not the lth variable in X is to be included in the variance-covariance matrices.
If ISX l>0 the lth variable is included, for l=1,2,…,M; otherwise it is not referenced.
Constraint: ISX l>0 for NVAR values of l.
7:   NVAR – INTEGERInput
On entry: p, the number of variables in the variance-covariance matrices.
Constraint: NVAR≥1.
8:   ING N – INTEGER arrayInput
On entry: ING k indicates to which group the kth observation belongs, for k=1,2,…,n.
Constraint: 1≤ING k≤NG, for k=1,2,…,n
The values of ING must be such that each group has at least NVAR members.
9:   NG – INTEGERInput
On entry: the number of groups, ng.
Constraint: NG≥2.
10:   WT* – REAL (KIND=nag_wp) arrayInput
Note: the dimension of the array WT must be at least N if WEIGHT='W', and at least 1 otherwise.
On entry: if WEIGHT='W' the first n elements of WT must contain the weights to be used in the analysis and the effective number of observations for a group is the sum of the weights of the observations in that group. If WT k=0.0 the kth observation is excluded from the calculations.
If WEIGHT='U', WT is not referenced and the effective number of observations for a group is the number of observations in that group.
Constraint: if WEIGHT='W', WT k≥0.0, for k=1,2,…,n.
11:   NIG NG – INTEGER arrayOutput
On exit: NIG j contains the number of observations in the jth group, for j=1,2,…,ng.
12:   GMN LDGMNNVAR – REAL (KIND=nag_wp) arrayOutput
On exit: the jth row of GMN contains the means of the p selected variables for the jth group, for j=1,2,…,ng.
13:   LDGMN – INTEGERInput
On entry: the first dimension of the array GMN as declared in the (sub)program from which G03DAF is called.
Constraint: LDGMN≥NG.
14:   DET NG – REAL (KIND=nag_wp) arrayOutput
On exit: the logarithm of the determinants of the within-group variance-covariance matrices.
15:   GC NG+1×NVAR×NVAR+1/2 – REAL (KIND=nag_wp) arrayOutput
On exit: the first p p+1/2 elements of GC contain R and the remaining ng blocks of p p+1/2 elements contain the Rj matrices. All are stored in packed form by columns.
16:   STAT – REAL (KIND=nag_wp)Output
On exit: the likelihood-ratio test statistic, G.
17:   DF – REAL (KIND=nag_wp)Output
On exit: the degrees of freedom for the distribution of G.
18:   SIG – REAL (KIND=nag_wp)Output
On exit: the significance level for G.
19:   WK N×NVAR+1 – REAL (KIND=nag_wp) arrayWorkspace
20:   IWK NG – INTEGER arrayWorkspace
21:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, | NVAR<1,
or | N<1,
or | NG<2,
or | M<NVAR,
or | LDX<N,
or | LDGMN<NG,
or | WEIGHT≠'U' or 'W'.
IFAIL=2
On entry, WEIGHT='W' and a value of WT<0.0.
IFAIL=3
On entry, | there are not exactly NVAR elements of ISX>0,
or | a value of ING is not in the range 1 to NG,
or | the effective number of observations for a group is less than 1,
or | a group has less than NVAR members.
IFAIL=4
R or one of the Rj is not of full rank.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

The accuracy is dependent on the accuracy of the computation of the QR decomposition. See F08AEF (DGEQRF) for further details.

8 Parallelism and Performance

G03DAF is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
G03DAF makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The time taken will be approximately proportional to n p 2.

10 Example

The data, taken from Aitchison and Dunsmore (1975), is concerned with the diagnosis of three ‘types’ of Cushing's syndrome. The variables are the logarithms of the urinary excretion rates (mg/24hr) of two steroid metabolites. Observations for a total of 21 patients are input and the statistics computed by G03DAF. The printed results show that there is evidence that the within-group variance-covariance matrices are not equal.

10.1 Program Text

Program Text (g03dafe.f90)

10.2 Program Data

Program Data (g03dafe.d)

10.3 Program Results

Program Results (g03dafe.r)

G03 Chapter Contents
G03 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


G03DBF : NAG Library, Mark 26

G03 Chapter Contents
G03 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

G03DBF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

G03DBF computes Mahalanobis squared distances for group or pooled variance-covariance matrices. It is intended for use after G03DAF.

2 Specification

SUBROUTINE G03DBF ( EQUAL, MODE, NVAR, NG, GMN, LDGMN, GC, NOBS, M, ISX, X, LDX, D, LDD, WK, IFAIL)
INTEGER | NVAR, NG, LDGMN, NOBS, M, ISX(*), LDX, LDD, IFAIL
REAL (KIND=nag_wp) | GMN(LDGMN,NVAR), GC((NG+1)*NVAR*(NVAR+1)/2), X(LDX,*), D(LDD,NG), WK(2*NVAR)
CHARACTER(1) | EQUAL, MODE

3 Description

Consider p variables observed on ng populations or groups. Let x-j be the sample mean and Sj the within-group variance-covariance matrix for the jth group and let xk be the kth sample point in a dataset. A measure of the distance of the point from the jth population or group is given by the Mahalanobis distance, D kj:
D kj 2=xk-x-j T Sj-1 xk-x-j.
If the pooled estimated of the variance-covariance matrix S is used rather than the within-group variance-covariance matrices, then the distance is:
D kj 2=xk-x-j TS-1 xk-x-j.
Instead of using the variance-covariance matrices S and Sj, G03DBF uses the upper triangular matrices R and Rj supplied by G03DAF such that S=RT R and Sj=RjT Rj. D kj 2 can then be calculated as zT z where Rj z=xk-x-j or Rz=xk-x-j as appropriate.
A particular case is when the distance between the group or population means is to be estimated. The Mahalanobis squared distance between the ith and jth groups is:
D ij 2=x-i-x-j T Sj-1 x-i-x-j
or
D ij 2=x-i-x-j TS-1 x-i-x-j.
Note: D jj 2=0 and that in the case when the pooled variance-covariance matrix is used D ij 2=D ji 2 so in this case only the lower triangular values of D ij 2, i>j, are computed.

4 References

Aitchison J and Dunsmore I R (1975) Statistical Prediction Analysis Cambridge
Kendall M G and Stuart A (1976) The Advanced Theory of Statistics (Volume 3) (3rd Edition) Griffin
Krzanowski W J (1990) Principles of Multivariate Analysis Oxford University Press

5 Arguments

1:   EQUAL – CHARACTER(1)Input
On entry: indicates whether or not the within-group variance-covariance matrices are assumed to be equal and the pooled variance-covariance matrix used.
EQUAL='E'
The within-group variance-covariance matrices are assumed equal and the matrix R stored in the first p p+1/2 elements of GC is used.
EQUAL='U'
The within-group variance-covariance matrices are assumed to be unequal and the matrices Rj, for j=1,2,…,ng, stored in the remainder of GC are used.
Constraint: EQUAL='E' or 'U'.
2:   MODE – CHARACTER(1)Input
On entry: indicates whether distances from sample points are to be calculated or distances between the group means.
MODE='S'
The distances between the sample points given in X and the group means are calculated.
MODE='M'
The distances between the group means will be calculated.
Constraint: MODE='M' or 'S'.
3:   NVAR – INTEGERInput
On entry: p, the number of variables in the variance-covariance matrices as specified to G03DAF.
Constraint: NVAR≥1.
4:   NG – INTEGERInput
On entry: the number of groups, ng.
Constraint: NG≥2.
5:   GMN LDGMNNVAR – REAL (KIND=nag_wp) arrayInput
On entry: the jth row of GMN contains the means of the p selected variables for the jth group, for j=1,2,…,ng. These are returned by G03DAF.
6:   LDGMN – INTEGERInput
On entry: the first dimension of the array GMN as declared in the (sub)program from which G03DBF is called.
Constraint: LDGMN≥NG.
7:   GC NG+1×NVAR×NVAR+1/2 – REAL (KIND=nag_wp) arrayInput
On entry: the first p p+1/2 elements of GC should contain the upper triangular matrix R and the next ng blocks of p p+1/2 elements should contain the upper triangular matrices Rj. All matrices must be stored packed by column. These matrices are returned by G03DAF. If EQUAL='E' only the first p p+1/2 elements are referenced, if EQUAL='U' only the elements p p+1/2+1 to ng+1 p p+1/2 are referenced.
Constraints:
  • if EQUAL='E', R≠0.0;
  • if EQUAL='U', the diagonal elements of the Rj≠0.0, for j=1,2,…,NG.
8:   NOBS – INTEGERInput
On entry: if MODE='S', the number of sample points in X for which distances are to be calculated.
If MODE='M', NOBS is not referenced.
Constraint: if NOBS≥1, MODE='S'.
9:   M – INTEGERInput
On entry: if MODE='S', the number of variables in the data array X.
If MODE='M', M is not referenced.
Constraint: if M≥NVAR, MODE='S'.
10:   ISX* – INTEGER arrayInput
Note: the dimension of the array ISX must be at least max 1,M.
On entry: if MODE='S', ISX l indicates if the lth variable in X is to be included in the distance calculations. If ISX l>0 the lth variable is included, for l=1,2,…,M; otherwise the lth variable is not referenced.
If MODE='M', ISX is not referenced.
Constraint: if MODE='S', ISX l>0 for NVAR values of l.
11:   X LDX* – REAL (KIND=nag_wp) arrayInput
Note: the second dimension of the array X must be at least max 1,M.
On entry: if MODE='S' the kth row of X must contain xk. That is X kl must contain the kth sample value for the lth variable, for k=1,2,…,NOBS and l=1,2,…,M. Otherwise X is not referenced.
12:   LDX – INTEGERInput
On entry: the first dimension of the array X as declared in the (sub)program from which G03DBF is called.
Constraints:
  • if MODE='S', LDX≥NOBS;
  • otherwise 1.
13:   D LDDNG – REAL (KIND=nag_wp) arrayOutput
On exit: the squared distances.
If MODE='S', D kj contains the squared distance of the kth sample point from the jth group mean, D kj 2, for k=1,2,…,NOBS and j=1,2,…,ng.
If MODE='M' and EQUAL='U', D ij contains the squared distance between the ith mean and the jth mean, D ij 2, for i=1,2,…,ng and j=1,2,…,i-1,i+1,…,ng. The elements D ii are not referenced, for i=1,2,…,ng.
If MODE='M' and EQUAL='E', D ij contains the squared distance between the ith mean and the jth mean, D ij 2, for i=1,2,…,ng and j=1,2,…,i-1. Since D ij=D ji the elements D ij are not referenced, for i=1,2,…,ng and j=i+1,…,ng.
14:   LDD – INTEGERInput
On entry: the first dimension of the array D as declared in the (sub)program from which G03DBF is called.
Constraints:
  • if MODE='S', LDD≥NOBS;
  • if MODE='M', LDD≥NG.
15:   WK 2×NVAR – REAL (KIND=nag_wp) arrayWorkspace
16:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, | NVAR<1,
or | NG<2,
or | LDGMN<NG,
or | MODE='S' and NOBS<1,
or | MODE='S' and M<NVAR,
or | MODE='S' and LDX<NOBS,
or | MODE='S' and LDD<NOBS,
or | MODE='M' and LDD<NG,
or | EQUAL≠'E' or ‘U’,
or | MODE≠'M' or ‘S’.
IFAIL=2
On entry, | MODE='S' and the number of variables indicated by ISX is not equal to NVAR,
or | EQUAL='E' and a diagonal element of R is zero,
or | EQUAL='U' and a diagonal element of Rj for some j is zero.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

The accuracy will depend upon the accuracy of the input R or Rj matrices.

8 Parallelism and Performance

G03DBF makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

If the distances are to be used for discrimination, see also G03DCF.

10 Example

The data, taken from Aitchison and Dunsmore (1975), is concerned with the diagnosis of three ‘types’ of Cushing's syndrome. The variables are the logarithms of the urinary excretion rates (mg/24hr) of two steroid metabolites. Observations for a total of 21 patients are input and the group means and R matrices are computed by G03DAF. A further six observations of unknown type are input, and the distances from the group means of the 21 patients of known type are computed under the assumption that the within-group variance-covariance matrices are not equal. These results are printed and indicate that the first four are close to one of the groups while observations 5 and 6 are some distance from any group.

10.1 Program Text

Program Text (g03dbfe.f90)

10.2 Program Data

Program Data (g03dbfe.d)

10.3 Program Results

Program Results (g03dbfe.r)

G03 Chapter Contents
G03 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


G03DCF : NAG Library, Mark 26

G03 Chapter Contents
G03 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

G03DCF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

G03DCF allocates observations to groups according to selected rules. It is intended for use after G03DAF.

2 Specification

SUBROUTINE G03DCF ( TYP, EQUAL, PRIORS, NVAR, NG, NIG, GMN, LDGMN, GC, DET, NOBS, M, ISX, X, LDX, PRIOR, P, LDP, IAG, ATIQ, ATI, WK, IFAIL)
INTEGER | NVAR, NG, NIG(NG), LDGMN, NOBS, M, ISX(M), LDX, LDP, IAG(NOBS), IFAIL
REAL (KIND=nag_wp) | GMN(LDGMN,NVAR), GC((NG+1)*NVAR*(NVAR+1)/2), DET(NG), X(LDX,M), PRIOR(NG), P(LDP,NG), ATI(LDP,*), WK(2*NVAR)
LOGICAL | ATIQ
CHARACTER(1) | TYP, EQUAL, PRIORS

3 Description

Discriminant analysis is concerned with the allocation of observations to groups using information from other observations whose group membership is known, Xt; these are called the training set. Consider p variables observed on ng populations or groups. Let x-j be the sample mean and Sj the within-group variance-covariance matrix for the jth group; these are calculated from a training set of n observations with nj observations in the jth group, and let xk be the kth observation from the set of observations to be allocated to the ng groups. The observation can be allocated to a group according to a selected rule. The allocation rule or discriminant function will be based on the distance of the observation from an estimate of the location of the groups, usually the group means. A measure of the distance of the observation from the jth group mean is given by the Mahalanobis distance, D kj:
D kj 2=xk-x-j T Sj-1 xk-x-j. (1)
If the pooled estimate of the variance-covariance matrix S is used rather than the within-group variance-covariance matrices, then the distance is:
D kj 2=xk-x-j TS-1 xk-x-j. (2)
Instead of using the variance-covariance matrices S and Sj, G03DCF uses the upper triangular matrices R and Rj supplied by G03DAF such that S=RT R and Sj=RjT Rj. D kj 2 can then be calculated as zT z where RT j z=xk-xj or RT z=xk-x as appropriate.
In addition to the distances, a set of prior probabilities of group membership, πj, for j=1,2,…,ng, may be used, with ∑πj=1. The prior probabilities reflect your view as to the likelihood of the observations coming from the different groups. Two common cases for prior probabilities are π 1=π 2=⋯=π ng, that is, equal prior probabilities, and πj=nj/n, for j=1,2,…,ng, that is, prior probabilities proportional to the number of observations in the groups in the training set.
G03DCF uses one of four allocation rules. In all four rules the p variables are assumed to follow a multivariate Normal distribution with mean μj and variance-covariance matrix Σj if the observation comes from the jth group. The different rules depend on whether or not the within-group variance-covariance matrices are assumed equal, i.e., Σ 1=Σ 2=⋯=Σ ng, and whether a predictive or estimative approach is used. If p xk∣ μj ,Σj is the probability of observing the observation xk from group j, then the posterior probability of belonging to group j is:
p j∣xk,μj,Σj∝ p xk∣ μj ,Σj πj. (3)
In the estimative approach, the arguments μj and Σj in (3) are replaced by their estimates calculated from Xt. In the predictive approach, a non-informative prior distribution is used for the arguments and a posterior distribution for the arguments, p μj, Σj∣ Xt , is found. A predictive distribution is then obtained by integrating p j∣xk,μj,Σj p μj, Σj∣ X over the argument space. This predictive distribution then replaces p xk∣ μj ,Σj in (3). See Aitchison and Dunsmore (1975), Aitchison et al. (1977) and Moran and Murphy (1979) for further details.
The observation is allocated to the group with the highest posterior probability. Denoting the posterior probabilities, p j∣xk,μj,Σj , by qj, the four allocation rules are:
(i) Estimative with equal variance-covariance matrices – Linear Discrimination
log⁡qj∝-12 D kj 2+log⁡πj
(ii) Estimative with unequal variance-covariance matrices – Quadratic Discrimination
log⁡qj∝-12 D kj 2+log⁡πj-12 log Sj
(iii) Predictive with equal variance-covariance matrices
q j - 1 ∝ n j +1 / n j p / 2 1 + n j / n - n g n j +1 D k j 2 n +1 - n g / 2
(iv) Predictive with unequal variance-covariance matrices
q j - 1 ∝ C n j 2 - 1 / n j S j p / 2 1 + n j / n j 2 - 1 D k j 2 n j / 2 ,
where
C=Γ 12 nj-p Γ 12 nj .
In the above the appropriate value of D kj 2 from (1) or (2) is used. The values of the qj are standardized so that,
∑j=1 ng qj=1.
Moran and Murphy (1979) show the similarity between the predictive methods and methods based upon likelihood ratio tests.
In addition to allocating the observation to a group, G03DCF computes an atypicality index, Ij xk. The predictive atypicality index is returned, irrespective of the value of the parameter TYP. This represents the probability of obtaining an observation more typical of group j than the observed xk (see Aitchison and Dunsmore (1975) and Aitchison et al. (1977)). The atypicality index is computed for unequal within-group variance-covariance matrices as:
Ij xk=P B≤z:12 p,12 nj-p
where P B≤β:a,b is the lower tail probability from a beta distribution and
z=D kj 2/D kj 2+nj 2-1/nj,
and for equal within-group variance-covariance matrices as:
Ij xk=P B≤z : 12 p,12 n-ng-p+ 1,
with
z=D kj 2/D kj 2+n-ngnj+1/nj.
If Ij xk is close to 1 for all groups it indicates that the observation may come from a grouping not represented in the training set. Moran and Murphy (1979) provide a frequentist interpretation of Ij xk.

4 References

Aitchison J and Dunsmore I R (1975) Statistical Prediction Analysis Cambridge
Aitchison J, Habbema J D F and Kay J W (1977) A critical comparison of two methods of statistical discrimination Appl. Statist. 26 15–25
Kendall M G and Stuart A (1976) The Advanced Theory of Statistics (Volume 3) (3rd Edition) Griffin
Krzanowski W J (1990) Principles of Multivariate Analysis Oxford University Press
Moran M A and Murphy B J (1979) A closer look at two alternative methods of statistical discrimination Appl. Statist. 28 223–232
Morrison D F (1967) Multivariate Statistical Methods McGraw–Hill

5 Arguments

1:   TYP – CHARACTER(1)Input
On entry: whether the estimative or predictive approach is used.
TYP='E'
The estimative approach is used.
TYP='P'
The predictive approach is used.
Constraint: TYP='E' or 'P'.
2:   EQUAL – CHARACTER(1)Input
On entry: indicates whether or not the within-group variance-covariance matrices are assumed to be equal and the pooled variance-covariance matrix used.
EQUAL='E'
The within-group variance-covariance matrices are assumed equal and the matrix R stored in the first p p+1/2 elements of GC is used.
EQUAL='U'
The within-group variance-covariance matrices are assumed to be unequal and the matrices Ri, for i=1,2,…,ng, stored in the remainder of GC are used.
Constraint: EQUAL='E' or 'U'.
3:   PRIORS – CHARACTER(1)Input
On entry: indicates the form of the prior probabilities to be used.
PRIORS='E'
Equal prior probabilities are used.
PRIORS='P'
Prior probabilities proportional to the group sizes in the training set, nj, are used.
PRIORS='I'
The prior probabilities are input in PRIOR.
Constraint: PRIORS='E', 'I' or 'P'.
4:   NVAR – INTEGERInput
On entry: p, the number of variables in the variance-covariance matrices.
Constraint: NVAR≥1.
5:   NG – INTEGERInput
On entry: the number of groups, ng.
Constraint: NG≥2.
6:   NIG NG – INTEGER arrayInput
On entry: the number of observations in each group in the training set, nj.
Constraints:
  • if EQUAL='E', NIG j>0 and ∑j=1 ng NIG j>NG+NVAR, for j=1,2,…,ng;
  • if EQUAL='U', NIG j>NVAR, for j=1,2,…,ng.
7:   GMN LDGMNNVAR – REAL (KIND=nag_wp) arrayInput
On entry: the jth row of GMN contains the means of the p variables for the jth group, for j=1,2,…,nj. These are returned by G03DAF.
8:   LDGMN – INTEGERInput
On entry: the first dimension of the array GMN as declared in the (sub)program from which G03DCF is called.
Constraint: LDGMN≥NG.
9:   GC NG+1×NVAR×NVAR+1/2 – REAL (KIND=nag_wp) arrayInput
On entry: the first p p+1/2 elements of GC should contain the upper triangular matrix R and the next ng blocks of p p+1/2 elements should contain the upper triangular matrices Rj.
All matrices must be stored packed by column. These matrices are returned by G03DAF. If EQUAL='E' only the first p p+1/2 elements are referenced, if EQUAL='U' only the elements p p+1/2+1 to ng+1 p p+1/2 are referenced.
Constraints:
  • if EQUAL='E', the diagonal elements of R must be ≠0.0;
  • if EQUAL='U', the diagonal elements of the Rj must be ≠0.0, for j=1,2,…,ng.
10:   DET NG – REAL (KIND=nag_wp) arrayInput
On entry: if EQUAL='U'. the logarithms of the determinants of the within-group variance-covariance matrices as returned by G03DAF. Otherwise DET is not referenced.
11:   NOBS – INTEGERInput
On entry: the number of observations in X which are to be allocated.
Constraint: NOBS≥1.
12:   M – INTEGERInput
On entry: the number of variables in the data array X.
Constraint: M≥NVAR.
13:   ISX M – INTEGER arrayInput
On entry: ISX l indicates if the lth variable in X is to be included in the distance calculations.
If ISX l>0, the lth variable is included, for l=1,2,…,M; otherwise the lth variable is not referenced.
Constraint: ISX l>0 for NVAR values of l.
14:   X LDXM – REAL (KIND=nag_wp) arrayInput
On entry: X kl must contain the kth observation for the lth variable, for k=1,2,…,NOBS and l=1,2,…,M.
15:   LDX – INTEGERInput
On entry: the first dimension of the array X as declared in the (sub)program from which G03DCF is called.
Constraint: LDX≥NOBS.
16:   PRIOR NG – REAL (KIND=nag_wp) arrayInput/Output
On entry: if PRIORS='I', the prior probabilities for the ng groups.
Constraint: if PRIORS='I', PRIOR j>0.0 and 1- ∑ j=1 ng PRIOR j ≤10×machine precision , for j=1,2,…,ng.
On exit: if PRIORS='P', the computed prior probabilities in proportion to group sizes for the ng groups.
If PRIORS='I', the input prior probabilities will be unchanged.
If PRIORS='E', PRIOR is not set.
17:   P LDPNG – REAL (KIND=nag_wp) arrayOutput
On exit: P kj contains the posterior probability p kj for allocating the kth observation to the jth group, for k=1,2,…,NOBS and j=1,2,…,ng.
18:   LDP – INTEGERInput
On entry: the first dimension of the arrays P and ATI as declared in the (sub)program from which G03DCF is called.
Constraint: LDP≥NOBS.
19:   IAG NOBS – INTEGER arrayOutput
On exit: the groups to which the observations have been allocated.
20:   ATIQ – LOGICALInput
On entry: ATIQ must be .TRUE. if atypicality indices are required. If ATIQ is .FALSE. the array ATI is not set.
21:   ATI LDP* – REAL (KIND=nag_wp) arrayOutput
Note: the second dimension of the array ATI must be at least NG if ATIQ=.TRUE., and at least 1 otherwise.
On exit: if ATIQ is .TRUE., ATI kj will contain the predictive atypicality index for the kth observation with respect to the jth group, for k=1,2,…,NOBS and j=1,2,…,ng.
If ATIQ is .FALSE., ATI is not set.
22:   WK 2×NVAR – REAL (KIND=nag_wp) arrayWorkspace
23:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, | NVAR<1,
or | NG<2,
or | NOBS<1,
or | M<NVAR,
or | LDGMN<NG,
or | LDX<NOBS,
or | LDP<NOBS,
or | TYP≠'E' or ‘P’,
or | EQUAL≠'E' or ‘U’,
or | PRIORS≠'E', ‘I’ or ‘P’.
IFAIL=2
On entry, | the number of variables indicated by ISX is not equal to NVAR,
or | EQUAL='E' and NIG j≤0, for some j,
or | EQUAL='E' and ∑j=1 ng NIG j≤NG+NVAR,
or | EQUAL='U' and NIG j≤NVAR for some j.
IFAIL=3
On entry, | PRIORS='I' and PRIOR j≤0.0 for some j,
or | PRIORS='I' and ∑j=1 ng PRIOR j is not within 10×machine precision of 1.
IFAIL=4
On entry, | EQUAL='E' and a diagonal element of R is zero,
or | EQUAL='U' and a diagonal element of Rj for some j is zero.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

The accuracy of the returned posterior probabilities will depend on the accuracy of the input R or Rj matrices. The atypicality index should be accurate to four significant places.

8 Parallelism and Performance

G03DCF makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The distances D kj 2 can be computed using G03DBF if other forms of discrimination are required.

10 Example

The data, taken from Aitchison and Dunsmore (1975), is concerned with the diagnosis of three ‘types’ of Cushing's syndrome. The variables are the logarithms of the urinary excretion rates (mg/24hr) of two steroid metabolites. Observations for a total of 21 patients are input and the group means and R matrices are computed by G03DAF. A further six observations of unknown type are input and allocations made using the predictive approach and under the assumption that the within-group covariance matrices are not equal. The posterior probabilities of group membership, qj, and the atypicality index are printed along with the allocated group. The atypicality index shows that observations 5 and 6 do not seem to be typical of the three types present in the initial 21 observations.

10.1 Program Text

Program Text (g03dcfe.f90)

10.2 Program Data

Program Data (g03dcfe.d)

10.3 Program Results

Program Results (g03dcfe.r)

G03 Chapter Contents
G03 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


G03EAF : NAG Library, Mark 26

G03 Chapter Contents
G03 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

G03EAF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

G03EAF computes a distance (dissimilarity) matrix.

2 Specification

SUBROUTINE G03EAF ( UPDATE, DIST, SCAL, N, M, X, LDX, ISX, S, D, IFAIL)
INTEGER | N, M, LDX, ISX(M), IFAIL
REAL (KIND=nag_wp) | X(LDX,M), S(M), D(N*(N-1)/2)
CHARACTER(1) | UPDATE, DIST, SCAL

3 Description

Given n objects, a distance or dissimilarity matrix is a symmetric matrix with zero diagonal elements such that the ijth element represents how far apart or how dissimilar the ith and jth objects are.
Let X be an n by p data matrix of observations of p variables on n objects, then the distance between object j and object k, d jk, can be defined as:
d jk= ∑i=1 p D x ji/si,x ki/si α ,
where x ji and x ki are the jith and kith elements of X, si is a standardization for the ith variable and D u,v is a suitable function. Three functions are provided in G03EAF.
(a) | Euclidean distance: D u,v= u-v 2 and α=12 .
(b) | Euclidean squared distance: D u,v= u-v 2 and α=1.
(c) | Absolute distance (city block metric): D u,v= u-v and α=1.
Three standardizations are available.
(a) | Standard deviation: si=∑j=1 n x ji-x- 2/n-1
(b) | Range: si = max x 1 i,x 2 i,…,x ni - min x 1 i,x 2 i,…,x ni
(c) | User-supplied values of si.
In addition to the above distances there are a large number of other dissimilarity measures, particularly for dichotomous variables (see Krzanowski (1990) and Everitt (1974)). For the dichotomous case these measures are simple to compute and can, if suitable scaling is used, be combined with the distances computed by G03EAF using the updating option.
Dissimilarity measures for variables can be based on the correlation coefficient for continuous variables and contingency table statistics for dichotomous data, see chapters G02 and G11 respectively.
G03EAF returns the strictly lower triangle of the distance matrix.

4 References

Everitt B S (1974) Cluster Analysis Heinemann
Krzanowski W J (1990) Principles of Multivariate Analysis Oxford University Press

5 Arguments

1:   UPDATE – CHARACTER(1)Input
On entry: indicates whether or not an existing matrix is to be updated.
UPDATE='U'
The matrix D is updated and distances are added to D.
UPDATE='I'
The matrix D is initialized to zero before the distances are added to D.
Constraint: UPDATE='U' or 'I'.
2:   DIST – CHARACTER(1)Input
On entry: indicates which type of distances are computed.
DIST='A'
Absolute distances.
DIST='E'
Euclidean distances.
DIST='S'
Euclidean squared distances.
Constraint: DIST='A', 'E' or 'S'.
3:   SCAL – CHARACTER(1)Input
On entry: indicates the standardization of the variables to be used.
SCAL='S'
Standard deviation.
SCAL='R'
Range.
SCAL='G'
Standardizations given in array S.
SCAL='U'
Unscaled.
Constraint: SCAL='S', 'R', 'G' or 'U'.
4:   N – INTEGERInput
On entry: n, the number of observations.
Constraint: N≥2.
5:   M – INTEGERInput
On entry: the total number of variables in array X.
Constraint: M>0.
6:   X LDXM – REAL (KIND=nag_wp) arrayInput
On entry: X ij must contain the value of the jth variable for the ith object, for i=1,2,…,n and j=1,2,…,M.
7:   LDX – INTEGERInput
On entry: the first dimension of the array X as declared in the (sub)program from which G03EAF is called.
Constraint: LDX≥N.
8:   ISX M – INTEGER arrayInput
On entry: ISX j indicates whether or not the jth variable in X is to be included in the distance computations.
If ISX j>0 the jth variable is included, for j=1,2,…,M; otherwise it is not referenced.
Constraint: ISX j>0 for at least one j, for j=1,2,…,M.
9:   S M – REAL (KIND=nag_wp) arrayInput/Output
On entry: if SCAL='G' and ISX j>0 then S j must contain the scaling for variable j, for j=1,2,…,M.
Constraint: if SCAL='G' and ISX j>0, S j>0.0, for j=1,2,…,M.
On exit: if SCAL='S' and ISX j>0 then S j contains the standard deviation of the variable in the jth column of X.
If SCAL='R' and ISX j>0, S j contains the range of the variable in the jth column of X.
If SCAL='U' and ISX j>0, S j=1.0.
If SCAL='G', S is unchanged.
10:   D N×N-1/2 – REAL (KIND=nag_wp) arrayInput/Output
On entry: if UPDATE='U', D must contain the strictly lower triangle of the distance matrix D to be updated. D must be stored packed by rows, i.e., D i-1 i-2 /2+j , i>j must contain d ij.
If UPDATE='I', D need not be set.
Constraint: if UPDATE='U', D j≥0.0, for j=1,2,…,n n-1/2.
On exit: the strictly lower triangle of the distance matrix D stored packed by rows, i.e., d ij is contained in D i-1 i-2 /2+j , i>j.
11:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, | N<2,
or | LDX<N,
or | M≤0,
or | UPDATE≠'I' or 'U',
or | DIST≠'A', 'E' or 'S',
or | SCAL≠'S', 'R', 'G' or 'U'.
IFAIL=2
On entry, | ISX j≤0, for j=1,2,…,M,
or | UPDATE='U' and D j<0.0, for some j=1,2,…,n n-1/2,
or | SCAL='S' or 'R' and X ij=X i+1 j for i=1,2,…,n-1, for some j with ISX i>0.
or | S j≤0.0 for some j when SCAL='G' and ISX j>0.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

The computations are believed to be stable.

8 Parallelism and Performance

G03EAF is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

G03ECF can be used to perform cluster analysis on the computed distance matrix.

10 Example

A data matrix of five observations and three variables is read in and a distance matrix is calculated from variables 2 and 3 using squared Euclidean distance with no scaling. This matrix is then printed.

10.1 Program Text

Program Text (g03eafe.f90)

10.2 Program Data

Program Data (g03eafe.d)

10.3 Program Results

Program Results (g03eafe.r)

G03 Chapter Contents
G03 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


G03ECF : NAG Library, Mark 26

G03 Chapter Contents
G03 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

G03ECF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

G03ECF performs hierarchical cluster analysis.

2 Specification

SUBROUTINE G03ECF ( METHOD, N, D, ILC, IUC, CD, IORD, DORD, IWK, IFAIL)
INTEGER | METHOD, N, ILC(N-1), IUC(N-1), IORD(N), IWK(2*N), IFAIL
REAL (KIND=nag_wp) | D(N*(N-1)/2), CD(N-1), DORD(N)

3 Description

Given a distance or dissimilarity matrix for n objects (see G03EAF), cluster analysis aims to group the n objects into a number of more or less homogeneous groups or clusters. With agglomerative clustering methods, a hierarchical tree is produced by starting with n clusters, each with a single object and then at each of n-1 stages, merging two clusters to form a larger cluster, until all objects are in a single cluster. This process may be represented by a dendrogram (see G03EHF).
At each stage, the clusters that are nearest are merged, methods differ as to how the distances between the new cluster and other clusters are computed. For three clusters i, j and k let ni, nj and nk be the number of objects in each cluster and let d ij, d ik and d jk be the distances between the clusters. Let clusters j and k be merged to give cluster jk, then the distance from cluster i to cluster jk, d i.jk can be computed in the following ways.
1. | Single link or nearest neighbour : d i.jk = min d ij,d ik .
2. | Complete link or furthest neighbour : d i.jk=max d ij,d ik.
3. | Group average : d i.jk= nj nj+nk d ij+ nk nj+nk d ik.
4. | Centroid : d i.jk= nj nj+nk d ij+ nk nj+nk d ik- njnk nj+nk 2 d jk.
5. | Median : d i.jk=12 d ij+12 d ik-14 d jk.
6. | Minimum variance : d i.jk=ni+nj d ij+ni+nk d ik-nid jk/ni+nj+nk.
For further details see Everitt (1974) or Krzanowski (1990).
If the clusters are numbered 1,2,…,n then, for convenience, if clusters j and k, j<k, merge then the new cluster will be referred to as cluster j. Information on the clustering history is given by the values of j, k and d jk for each of the n-1 clustering steps. In order to produce a dendrogram, the ordering of the objects such that the clusters that merge are adjacent is required. This ordering is computed so that the first element is 1. The associated distances with this ordering are also computed.

4 References

Everitt B S (1974) Cluster Analysis Heinemann
Krzanowski W J (1990) Principles of Multivariate Analysis Oxford University Press

5 Arguments

1:   METHOD – INTEGERInput
On entry: indicates which clustering method is used.
METHOD=1
Single link.
METHOD=2
Complete link.
METHOD=3
Group average.
METHOD=4
Centroid.
METHOD=5
Median.
METHOD=6
Minimum variance.
Constraint: METHOD=1, 2, 3, 4, 5 or 6.
2:   N – INTEGERInput
On entry: n, the number of objects.
Constraint: N≥2.
3:   D N×N-1/2 – REAL (KIND=nag_wp) arrayInput/Output
On entry: the strictly lower triangle of the distance matrix. D must be stored packed by rows, i.e., D i-1 i-2 /2+j , i>j must contain d ij.
On exit: is overwritten.
Constraint: D i≥0.0, for i=1,2,…,n n-1/2.
4:   ILC N-1 – INTEGER arrayOutput
On exit: ILC l contains the number, j, of the cluster merged with cluster k (see IUC), j<k, at step l, for l=1,2,…,n-1.
5:   IUC N-1 – INTEGER arrayOutput
On exit: IUC l contains the number, k, of the cluster merged with cluster j, j<k, at step l, for l=1,2,…,n-1.
6:   CD N-1 – REAL (KIND=nag_wp) arrayOutput
On exit: CD l contains the distance d jk, between clusters j and k, j<k, merged at step l, for l=1,2,…,n-1.
7:   IORD N – INTEGER arrayOutput
On exit: the objects in dendrogram order.
8:   DORD N – REAL (KIND=nag_wp) arrayOutput
On exit: the clustering distances corresponding to the order in IORD. DORD l contains the distance at which cluster IORD l and IORD l+1 merge, for l=1,2,…,n-1. DORD n contains the maximum distance.
9:   IWK 2×N – INTEGER arrayWorkspace
10:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, | METHOD≠1, 2, 3, 4, 5 or 6,
or | N<2.
IFAIL=2
On entry, D i<0.0 for some i=1,2,…,n n-1/2.
IFAIL=3
A true dendrogram cannot be formed because the distances at which clusters have merged are not increasing for all steps, i.e., CD l<CD l-1 for some l=2,3,…,n-1. This can occur for the median and centroid methods.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

For METHOD≥3 slight rounding errors may occur in the calculations of the updated distances. These would not normally significantly affect the results, however there may be an effect if distances are (almost) equal.
If at a stage, two distances d ij and d kl, (i<k) or (i=k), and j<l, are equal then clusters k and l will be merged rather than clusters i and j. For single link clustering this choice will only affect the order of the objects in the dendrogram. However, for other methods the choice of kl rather than ij may affect the shape of the dendrogram. If either of the distances d ij and d kl is affected by rounding errors then their equality, and hence the dendrogram, may be affected.

8 Parallelism and Performance

G03ECF is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The dendrogram may be formed using G03EHF. Groupings based on the clusters formed at a given distance can be computed using G03EJF.

10 Example

Data consisting of three variables on five objects are read in. Euclidean squared distances based on two variables are computed using G03EAF, the objects are clustered using G03ECF and the dendrogram computed using G03EHF. The dendrogram is then printed.

10.1 Program Text

Program Text (g03ecfe.f90)

10.2 Program Data

Program Data (g03ecfe.d)

10.3 Program Results

Program Results (g03ecfe.r)

G03 Chapter Contents
G03 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


G03EFF : NAG Library, Mark 26

G03 Chapter Contents
G03 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

G03EFF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

G03EFF performs K-means cluster analysis.

2 Specification

SUBROUTINE G03EFF ( WEIGHT, N, M, X, LDX, ISX, NVAR, K, CMEANS, LDC, WT, INC, NIC, CSS, CSW, MAXIT, IWK, WK, IFAIL)
INTEGER | N, M, LDX, ISX(M), NVAR, K, LDC, INC(N), NIC(K), MAXIT, IWK(N+3*K), IFAIL
REAL (KIND=nag_wp) | X(LDX,M), CMEANS(LDC,NVAR), WT(*), CSS(K), CSW(K), WK(N+2*K)
CHARACTER(1) | WEIGHT

3 Description

Given n objects with p variables measured on each object, x ij, for i=1,2,…,n and j=1,2,…,p, G03EFF allocates each object to one of K groups or clusters to minimize the within-cluster sum of squares:
∑k=1 K∑i∈Sk∑j=1 p x ij-x-kj 2,
where Sk is the set of objects in the kth cluster and x-kj is the mean for the variable j over cluster k. This is often known as K-means clustering.
In addition to the data matrix, a K by p matrix giving the initial cluster centres for the K clusters is required. The objects are then initially allocated to the cluster with the nearest cluster mean. Given the initial allocation, the procedure is to iteratively search for the K-partition with locally optimal within-cluster sum of squares by moving points from one cluster to another.
Optionally, weights for each object, wi, can be used so that the clustering is based on within-cluster weighted sums of squares:
∑k=1 K∑i∈Sk∑j=1 p wi x ij-x~kj 2,
where x~kj is the weighted mean for variable j over cluster k.
The routine is based on the algorithm of Hartigan and Wong (1979).

4 References

Everitt B S (1974) Cluster Analysis Heinemann
Hartigan J A and Wong M A (1979) Algorithm AS 136: A K-means clustering algorithm Appl. Statist. 28 100–108
Kendall M G and Stuart A (1976) The Advanced Theory of Statistics (Volume 3) (3rd Edition) Griffin
Krzanowski W J (1990) Principles of Multivariate Analysis Oxford University Press

5 Arguments

1:   WEIGHT – CHARACTER(1)Input
On entry: indicates if weights are to be used.
WEIGHT='U'
No weights are used.
WEIGHT='W'
Weights are used and must be supplied in WT.
Constraint: WEIGHT='U' or 'W'.
2:   N – INTEGERInput
On entry: n, the number of objects.
Constraint: N>1.
3:   M – INTEGERInput
On entry: the total number of variables in array X.
Constraint: M≥NVAR.
4:   X LDXM – REAL (KIND=nag_wp) arrayInput
On entry: X ij must contain the value of the jth variable for the ith object, for i=1,2,…,n and j=1,2,…,M.
5:   LDX – INTEGERInput
On entry: the first dimension of the array X as declared in the (sub)program from which G03EFF is called.
Constraint: LDX≥N.
6:   ISX M – INTEGER arrayInput
On entry: ISX j indicates whether or not the jth variable is to be included in the analysis. If ISX j>0, the variable contained in the jth column of X is included, for j=1,2,…,M.
Constraint: ISX j>0 for NVAR values of j.
7:   NVAR – INTEGERInput
On entry: p, the number of variables included in the sums of squares calculations.
Constraint: 1≤NVAR≤M.
8:   K – INTEGERInput
On entry: K, the number of clusters.
Constraint: K≥2.
9:   CMEANS LDCNVAR – REAL (KIND=nag_wp) arrayInput/Output
On entry: CMEANS ij must contain the value of the jth variable for the ith initial cluster centre, for i=1,2,…,K and j=1,2,…,p.
On exit: CMEANS ij contains the value of the jth variable for the ith computed cluster centre, for i=1,2,…,K and j=1,2,…,p.
10:   LDC – INTEGERInput
On entry: the first dimension of the array CMEANS as declared in the (sub)program from which G03EFF is called.
Constraint: LDC≥K.
11:   WT* – REAL (KIND=nag_wp) arrayInput
Note: the dimension of the array WT must be at least N if WEIGHT='W', and at least 1 otherwise.
On entry: if WEIGHT='W', the first n elements of WT must contain the weights to be used.
If WT i=0.0, the ith observation is not included in the analysis. The effective number of observation is the sum of the weights.
If WEIGHT='U', WT is not referenced and the effective number of observations is n.
Constraint: if WEIGHT='W', WT i≥0.0 and WT i>0.0 for at least two values of i, for i=1,2,…,n.
12:   INC N – INTEGER arrayOutput
On exit: INC i contains the cluster to which the ith object has been allocated, for i=1,2,…,n.
13:   NIC K – INTEGER arrayOutput
On exit: NIC i contains the number of objects in the ith cluster, for i=1,2,…,K.
14:   CSS K – REAL (KIND=nag_wp) arrayOutput
On exit: CSS i contains the within-cluster (weighted) sum of squares of the ith cluster, for i=1,2,…,K.
15:   CSW K – REAL (KIND=nag_wp) arrayOutput
On exit: CSW i contains the within-cluster sum of weights of the ith cluster, for i=1,2,…,K. If WEIGHT='U', the sum of weights is the number of objects in the cluster.
16:   MAXIT – INTEGERInput
On entry: the maximum number of iterations allowed in the analysis.
Suggested value: MAXIT=10.
Constraint: MAXIT>0.
17:   IWK N+3×K – INTEGER arrayWorkspace
18:   WK N+2×K – REAL (KIND=nag_wp) arrayWorkspace
19:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, | WEIGHT≠'W' or 'U',
or | N<2,
or | NVAR<1,
or | M<NVAR,
or | K<2,
or | LDX<N,
or | LDC<K,
or | MAXIT≤0.
IFAIL=2
On entry, | WEIGHT='W' and a value of WT i<0.0 for some i,
or | WEIGHT='W' and WT i=0.0 for all or all but one values of i.
IFAIL=3
On entry, the number of positive values in ISX does not equal NVAR.
IFAIL=4
On entry, at least one cluster is empty after the initial assignment. Try a different set of initial cluster centres in CMEANS and also consider decreasing the value of K. The empty clusters may be found by examining the values in NIC.
IFAIL=5
Convergence has not been achieved within the maximum number of iterations given by MAXIT. Try increasing MAXIT and, if possible, use the returned values in CMEANS as the initial cluster centres.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

G03EFF produces clusters that are locally optimal; the within-cluster sum of squares may not be decreased by transferring a point from one cluster to another, but different partitions may have the same or smaller within-cluster sum of squares.

8 Parallelism and Performance

G03EFF is not threaded in any implementation.

9 Further Comments

The time per iteration is approximately proportional to npK.

10 Example

The data consists of observations of five variables on twenty soils (see Hartigan and Wong (1979)). The data is read in, the K-means clustering performed and the results printed.

10.1 Program Text

Program Text (g03effe.f90)

10.2 Program Data

Program Data (g03effe.d)

10.3 Program Results

Program Results (g03effe.r)

G03 Chapter Contents
G03 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


G03EHF : NAG Library, Mark 26

G03 Chapter Contents
G03 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

G03EHF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

G03EHF produces a dendrogram from the results of G03ECF.

2 Specification

SUBROUTINE G03EHF ( ORIENT, N, DORD, DMIN, DSTEP, NSYM, C, LENC, IFAIL)
INTEGER | N, NSYM, LENC, IFAIL
REAL (KIND=nag_wp) | DORD(N), DMIN, DSTEP
CHARACTER(*) | C(LENC)
CHARACTER(1) | ORIENT

3 Description

Hierarchical cluster analysis, as performed by G03ECF, can be represented by a tree that shows at which distance the clusters merge. Such a tree is known as a dendrogram. See Everitt (1974) and Krzanowski (1990) for examples of dendrograms. A simple example is,
Figure 1
The end points of the dendrogram represent the objects that have been clustered. They should be in a suitable order as given by G03ECF. Object 1 is always the first object. In the example above the height represents the distance at which the clusters merge.
The dendrogram is produced in a character array using the ordering and distances provided by G03ECF. Suitable characters are used to represent parts of the tree.
There are four possible orientations for the dendrogram. The example above has the end points at the bottom of the diagram which will be referred to as south. If the dendrogram was the other way around with the end points at the top of the diagram then the orientation would be north. If the end points are at the left-hand or right-hand side of the diagram the orientation is west or east. Different symbols are used for east/west and north/south orientations.

4 References

Everitt B S (1974) Cluster Analysis Heinemann
Krzanowski W J (1990) Principles of Multivariate Analysis Oxford University Press

5 Arguments

1:   ORIENT – CHARACTER(1)Input
On entry: indicates which orientation the dendrogram is to take.
ORIENT='N'
The end points of the dendrogram are to the north.
ORIENT='S'
The end points of the dendrogram are to the south.
ORIENT='E'
The end points of the dendrogram are to the east.
ORIENT='W'
The end points of the dendrogram are to the west.
Constraint: ORIENT='N', 'S', 'E' or 'W'.
2:   N – INTEGERInput
On entry: the number of objects in the cluster analysis.
Constraint: N>2.
3:   DORD N – REAL (KIND=nag_wp) arrayInput
On entry: the array DORD as output by G03ECF. DORD contains the distances, in dendrogram order, at which clustering takes place.
Constraint: DORD N≥DORD i, for i=1,2,…,N-1.
4:   DMIN – REAL (KIND=nag_wp)Input
On entry: the clustering distance at which the dendrogram begins.
Constraint: DMIN≥0.0.
5:   DSTEP – REAL (KIND=nag_wp)Input
On entry: the distance represented by one symbol of the dendrogram.
Constraint: DSTEP>0.0.
6:   NSYM – INTEGERInput
On entry: the number of character positions used in the dendrogram. Hence the clustering distance at which the dendrogram terminates is given by DMIN+NSYM×DSTEP.
Constraint: NSYM≥1.
7:   C LENC – CHARACTER(*) arrayOutput
Note: the length of each element of C must be at least 3×N if ORIENT='N' or 'S', or at least NSYM if ORIENT='E' or 'W'.
On exit: the elements of C contain consecutive lines of the dendrogram.
8:   LENC – INTEGERInput
On entry: the dimension of the array C as declared in the (sub)program from which G03EHF is called.
Constraints:
  • if ORIENT='N' or 'S', LENC≥NSYM;
  • if ORIENT='E' or 'W', LENC≥N.
9:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, | N≤2,
or | NSYM<1,
or | DMIN<0.0,
or | DSTEP≤0.0,
or | ORIENT≠'N','S','E', or 'W',
or | ORIENT='N' or 'S', LENC<NSYM,
or | ORIENT='E' or 'W', LENC<N,
or | the number of characters that can be stored in each element of array C is insufficient for the requested orientation.
IFAIL=2
On entry, DORD N<DORD i, for some i=1,2,…,N-1.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

Not applicable.

8 Parallelism and Performance

G03EHF is not threaded in any implementation.

9 Further Comments

The scale of the dendrogram is controlled by DSTEP. The smaller the value DSTEP is, the greater the amount of detail that will be given but NSYM will have to be larger to give the full dendrogram. The range of distances represented by the dendrogram is DMIN to NSYM×DSTEP. The values of DMIN, DSTEP and NSYM can thus be set so that only part of the dendrogram is produced.
The dendrogram does not include any labelling of the objects. You can print suitable labels using the ordering given by the array IORD returned by G03ECF.

10 Example

Data consisting of three variables on five objects are read in. Euclidean squared distances are computed using G03EAF and median clustering performed by G03ECF. G03EHF is used to produce a dendrogram with orientation east and a dendrogram with orientation south. The two dendrograms are printed.

10.1 Program Text

Program Text (g03ehfe.f90)

10.2 Program Data

Program Data (g03ehfe.d)

10.3 Program Results

Program Results (g03ehfe.r)

G03 Chapter Contents
G03 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


G03EJF : NAG Library, Mark 26

G03 Chapter Contents
G03 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

G03EJF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

G03EJF computes a cluster indicator variable from the results of G03ECF.

2 Specification

SUBROUTINE G03EJF ( N, CD, IORD, DORD, K, DLEVEL, IC, IFAIL)
INTEGER | N, IORD(N), K, IC(N), IFAIL
REAL (KIND=nag_wp) | CD(N-1), DORD(N), DLEVEL

3 Description

Given a distance or dissimilarity matrix for n objects, cluster analysis aims to group the n objects into a number of more or less homogeneous groups or clusters. With agglomerative clustering methods (see G03ECF), a hierarchical tree is produced by starting with n clusters each with a single object and then at each of n-1 stages, merging two clusters to form a larger cluster until all objects are in a single cluster. G03EJF takes the information from the tree and produces the clusters that exist at a given distance. This is equivalent to taking the dendrogram (see G03EHF) and drawing a line across at a given distance to produce clusters.
As an alternative to giving the distance at which clusters are required, you can specify the number of clusters required and G03EJF will compute the corresponding distance. However, it may not be possible to compute the number of clusters required due to ties in the distance matrix.
If there are k clusters then the indicator variable will assign a value between 1 and k to each object to indicate to which cluster it belongs. Object 1 always belongs to cluster 1.

4 References

Everitt B S (1974) Cluster Analysis Heinemann
Krzanowski W J (1990) Principles of Multivariate Analysis Oxford University Press

5 Arguments

1:   N – INTEGERInput
On entry: n, the number of objects.
Constraint: N≥2.
2:   CD N-1 – REAL (KIND=nag_wp) arrayInput
On entry: the clustering distances in increasing order as returned by G03ECF.
Constraint: CD i+1≥CD i, for i=1,2,…,N-2.
3:   IORD N – INTEGER arrayInput
On entry: the objects in dendrogram order as returned by G03ECF.
4:   DORD N – REAL (KIND=nag_wp) arrayInput
On entry: the clustering distances corresponding to the order in IORD.
5:   K – INTEGERInput/Output
On entry: indicates if a specified number of clusters is required.
If K>0 then G03EJF will attempt to find K clusters.
If K≤0 then G03EJF will find the clusters based on the distance given in DLEVEL.
Constraint: K≤N.
On exit: the number of clusters produced, k.
6:   DLEVEL – REAL (KIND=nag_wp)Input/Output
On entry: if K≤0, DLEVEL must contain the distance at which clusters are produced. Otherwise DLEVEL need not be set.
Constraint: if DLEVEL>0.0, K≤0.
On exit: if K>0 on entry, DLEVEL contains the distance at which the required number of clusters are found. Otherwise DLEVEL remains unchanged.
7:   IC N – INTEGER arrayOutput
On exit: IC i indicates to which of k clusters the ith object belongs, for i=1,2,…,n.
8:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, | K>N,
or | K≤0 and DLEVEL≤0.0.
or | N<2.
IFAIL=2
On entry, | CD is not in increasing order,
or | DORD is incompatible with CD.
IFAIL=3
On entry, | K=1,
or | K=N,
or | DLEVEL≥CD N-1,
or | DLEVEL<CD 1.
Note: on exit with this value of IFAIL the trivial clustering solution is returned.
IFAIL=4
The precise number of clusters requested is not possible because of tied clustering distances. The actual number of clusters, less than the number requested, is returned in K.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

The accuracy will depend upon the accuracy of the distances in CD and DORD (see G03ECF).

8 Parallelism and Performance

G03EJF is not threaded in any implementation.

9 Further Comments

A fixed number of clusters can be found using the non-hierarchical method used in G03EFF.

10 Example

Data consisting of three variables on five objects are input. Euclidean squared distances are computed using G03EAF and median clustering performed using G03ECF. A dendrogram is produced by G03EHF and printed. G03EJF finds two clusters and the results are printed.

10.1 Program Text

Program Text (g03ejfe.f90)

10.2 Program Data

Program Data (g03ejfe.d)

10.3 Program Results

Program Results (g03ejfe.r)

G03 Chapter Contents
G03 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


G03FAF : NAG Library, Mark 26

G03 Chapter Contents
G03 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

G03FAF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

G03FAF performs a principal coordinate analysis also known as classical metric scaling.

2 Specification

SUBROUTINE G03FAF ( ROOTS, N, D, NDIM, X, LDX, EVAL, WK, IWK, IFAIL)
INTEGER | N, NDIM, LDX, IWK(5*N), IFAIL
REAL (KIND=nag_wp) | D(N*(N-1)/2), X(LDX,NDIM), EVAL(N), WK(N*(N+17)/2-1)
CHARACTER(1) | ROOTS

3 Description

For a set of n objects a distance matrix D can be calculated such that d ij is a measure of how ‘far apart’ are objects i and j (see G03EAF for example). Principal coordinate analysis or metric scaling starts with a distance matrix and finds points X in Euclidean space such that those points have the same distance matrix. The aim is to find a small number of dimensions, k≪n-1, that provide an adequate representation of the distances.
The principal coordinates of the points are computed from the eigenvectors of the matrix E where e ij = -1 / 2 d ij 2 - d i. 2 - d .j 2 + d .. 2 with d i.2 denoting the average of d ij 2 over the suffix j, etc.. The eigenvectors are then scaled by multiplying by the square root of the value of the corresponding eigenvalue.
Provided that the ordered eigenvalues, λi, of the matrix E are all positive, ∑ i=1 k λi / ∑ i=1 n-1 λi shows how well the data is represented in k dimensions. The eigenvalues will be non-negative if E is positive semidefinite. This will be true provided d ij satisfies the inequality: d ij ≤ d ik + d jk for all i,j,k. If this is not the case the size of the negative eigenvalue reflects the amount of deviation from this condition and the results should be treated cautiously in the presence of large negative eigenvalues. See Krzanowski (1990) for further discussion. G03FAF provides the option for all eigenvalues to be computed so that the smallest eigenvalues can be checked.

4 References

Chatfield C and Collins A J (1980) Introduction to Multivariate Analysis Chapman and Hall
Gower J C (1966) Some distance properties of latent root and vector methods used in multivariate analysis Biometrika 53 325–338
Krzanowski W J (1990) Principles of Multivariate Analysis Oxford University Press

5 Arguments

1:   ROOTS – CHARACTER(1)Input
On entry: indicates if all the eigenvalues are to be computed or just the NDIM largest.
ROOTS='A'
All the eigenvalues are computed.
ROOTS='L'
Only the largest NDIM eigenvalues are computed.
Constraint: ROOTS='A' or 'L'.
2:   N – INTEGERInput
On entry: n, the number of objects in the distance matrix.
Constraint: N>NDIM.
3:   D N×N-1/2 – REAL (KIND=nag_wp) arrayInput
On entry: the lower triangle of the distance matrix D stored packed by rows. That is D i-1 × i-2 /2+j must contain d ij for i=2,3,…,n;j=1,2,…,i-1.
Constraint: D i≥0.0, for i=1,2,…,n n-1/2.
4:   NDIM – INTEGERInput
On entry: k, the number of dimensions used to represent the data.
Constraint: NDIM≥1.
5:   X LDXNDIM – REAL (KIND=nag_wp) arrayOutput
On exit: the ith row contains k coordinates for the ith point, i=1,2,…,n.
6:   LDX – INTEGERInput
On entry: the first dimension of the array X as declared in the (sub)program from which G03FAF is called.
Constraint: LDX≥N.
7:   EVAL N – REAL (KIND=nag_wp) arrayOutput
On exit: if ROOTS='A', EVAL contains the n scaled eigenvalues of the matrix E.
If ROOTS='L', EVAL contains the largest k scaled eigenvalues of the matrix E.
In both cases the eigenvalues are divided by the sum of the eigenvalues (that is, the trace of E).
8:   WK N×N+17/2-1 – REAL (KIND=nag_wp) arrayWorkspace
9:   IWK 5×N – INTEGER arrayWorkspace
10:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, | NDIM<1,
or | N<NDIM,
or | ROOTS≠'A' or 'L',
or | LDX<N.
IFAIL=2
On entry, | D i<0.0 for some i, i=1,2,…,n n-1/2,
or | all elements of D=0.0.
IFAIL=3
There are less than NDIM eigenvalues greater than zero. Try a smaller number of dimensions (NDIM) or use non-metric scaling (G03FCF).
IFAIL=4
The computation of the eigenvalues or eigenvectors has failed. Seek expert help.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

G03FAF uses F08JFF (DSTERF) or F08JJF (DSTEBZ) to compute the eigenvalues and F08JKF (DSTEIN) to compute the eigenvectors. These routines should be consulted for a discussion of the accuracy of the computations involved.

8 Parallelism and Performance

G03FAF is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
G03FAF makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

Alternative, non-metric, methods of scaling are provided by G03FCF.
The relationship between principal coordinates and principal components, see G03FCF, is discussed in Krzanowski (1990) and Gower (1966).

10 Example

The data, given by Krzanowski (1990), are dissimilarities between water vole populations in Europe. The first two principal coordinates are computed.

10.1 Program Text

Program Text (g03fafe.f90)

10.2 Program Data

Program Data (g03fafe.d)

10.3 Program Results

Program Results (g03fafe.r)

GnuplotProduced by GNUPLOT 4.6 patchlevel 3 −0.4 −0.3 −0.2 −0.1 0 0.1 0.2 0.3 −0.6 −0.5 −0.4 −0.3 −0.2 −0.1 0 0.1 0.2 0.3 Second Principal Coordinate First Principal Coordinate Example Program Plot of Observation Number by the First Two Principal Coordinates gnuplot_plot_1 1 2 3 4 5 6 7 8 9 10 11 12 13 14
G03 Chapter Contents
G03 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


G03FCF : NAG Library, Mark 26

G03 Chapter Contents
G03 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

G03FCF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

G03FCF performs non-metric (ordinal) multidimensional scaling.

2 Specification

SUBROUTINE G03FCF ( TYP, N, NDIM, D, X, LDX, STRESS, DFIT, ITER, IOPT, WK, IWK, IFAIL)
INTEGER | N, NDIM, LDX, ITER, IOPT, IWK(N*(N-1)/2+N*NDIM+5), IFAIL
REAL (KIND=nag_wp) | D(N*(N-1)/2), X(LDX,NDIM), STRESS, DFIT(2*N*(N-1)), WK(15*N*NDIM)
CHARACTER(1) | TYP

3 Description

For a set of n objects, a distance or dissimilarity matrix D can be calculated such that d ij is a measure of how ‘far apart’ the objects i and j are. If p variables xk have been recorded for each observation this measure may be based on Euclidean distance, d ij=∑k=1 p x ki-x kj 2, or some other calculation such as the number of variables for which x kj≠x ki. Alternatively, the distances may be the result of a subjective assessment. For a given distance matrix, multidimensional scaling produces a configuration of n points in a chosen number of dimensions, m, such that the distance between the points in some way best matches the distance matrix. For some distance measures, such as Euclidean distance, the size of distance is meaningful, for other measures of distance all that can be said is that one distance is greater or smaller than another. For the former metric scaling can be used, see G03FAF, for the latter, a non-metric scaling is more appropriate.
For non-metric multidimensional scaling, the criterion used to measure the closeness of the fitted distance matrix to the observed distance matrix is known as STRESS. STRESS is given by,
∑i=1 n∑j=1 i-1 d ij^-d ij~ 2 ∑i=1 n∑j=1 i-1 d ij^2
where d ij^2 is the Euclidean squared distance between points i and j and d ij~ is the fitted distance obtained when d ij^ is monotonically regressed on d ij, that is d ij~ is monotonic relative to d ij and is obtained from d ij^ with the smallest number of changes. So STRESS is a measure of by how much the set of points preserve the order of the distances in the original distance matrix. Non-metric multidimensional scaling seeks to find the set of points that minimize the STRESS.
An alternate measure is squared STRESS, sstress,
∑i=1 n∑j=1 i-1 d ij^2-d ij~2 2 ∑i=1 n∑j=1 i-1 d ij^4
in which the distances in STRESS are replaced by squared distances.
In order to perform a non-metric scaling, an initial configuration of points is required. This can be obtained from principal coordinate analysis, see G03FAF. Given an initial configuration, G03FCF uses the optimization routine E04DGF/E04DGA to find the configuration of points that minimizes STRESS or sstress. The routine E04DGF/E04DGA uses a conjugate gradient algorithm. G03FCF will find an optimum that may only be a local optimum, to be more sure of finding a global optimum several different initial configurations should be used; these can be obtained by randomly perturbing the original initial configuration using routines from Chapter G05.

4 References

Chatfield C and Collins A J (1980) Introduction to Multivariate Analysis Chapman and Hall
Krzanowski W J (1990) Principles of Multivariate Analysis Oxford University Press

5 Arguments

1:   TYP – CHARACTER(1)Input
On entry: indicates whether STRESS or sstress is to be used as the criterion.
TYP='T'
STRESS is used.
TYP='S'
sstress is used.
Constraint: TYP='S' or 'T'.
2:   N – INTEGERInput
On entry: n, the number of objects in the distance matrix.
Constraint: N>NDIM.
3:   NDIM – INTEGERInput
On entry: m, the number of dimensions used to represent the data.
Constraint: NDIM≥1.
4:   D N×N-1/2 – REAL (KIND=nag_wp) arrayInput
On entry: the lower triangle of the distance matrix D stored packed by rows. That is D i-1 × i-2 /2+j must contain d ij, for i=2,3,…,n and j=1,2,…,i-1. If d ij is missing then set d ij<0; for further comments on missing values see Section 9.
5:   X LDXNDIM – REAL (KIND=nag_wp) arrayInput/Output
On entry: the ith row must contain an initial estimate of the coordinates for the ith point, for i=1,2,…,n. One method of computing these is to use G03FAF.
On exit: the ith row contains m coordinates for the ith point, for i=1,2,…,n.
6:   LDX – INTEGERInput
On entry: the first dimension of the array X as declared in the (sub)program from which G03FCF is called.
Constraint: LDX≥N.
7:   STRESS – REAL (KIND=nag_wp)Output
On exit: the value of STRESS or sstress at the final iteration.
8:   DFIT 2×N×N-1 – REAL (KIND=nag_wp) arrayOutput
On exit: auxiliary outputs.
If TYP='T', the first n n-1/2 elements contain the distances, d ij^, for the points returned in X, the second set of n n-1/2 contains the distances d ij^ ordered by the input distances, d ij, the third set of n n-1/2 elements contains the monotonic distances, d ij~, ordered by the input distances, d ij and the final set of n n-1/2 elements contains fitted monotonic distances, d ij~, for the points in X. The d ij~ corresponding to distances which are input as missing are set to zero.
If TYP='S', the results are as above except that the squared distances are returned.
Each distance matrix is stored in lower triangular packed form in the same way as the input matrix D.
9:   ITER – INTEGERInput
On entry: the maximum number of iterations in the optimization process.
ITER=0
A default value of 50 is used.
ITER<0
A default value of max 50,5 nm (the default for E04DGF/E04DGA) is used.
10:   IOPT – INTEGERInput
On entry: selects the options, other than the number of iterations, that control the optimization.
IOPT=0
Default values are selected as described in Section 9. In particular if an accuracy requirement of ε=0.00001 is selected, see Section 7.
IOPT>0
The default values are used except that the accuracy is given by 10-i where i=IOPT.
IOPT<0
The option setting mechanism of E04DGF/E04DGA can be used to set all options except Iteration Limit; this option is only recommended if you are an experienced user of NAG optimization routines. For further details see E04DGF/E04DGA.
11:   WK 15×N×NDIM – REAL (KIND=nag_wp) arrayWorkspace
12:   IWK N×N-1/2+N×NDIM+5 – INTEGER arrayWorkspace
13:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, | NDIM<1,
or | N≤NDIM,
or | TYP≠'T' or 'S',
or | LDX<N.
IFAIL=2
On entry, all elements of D≤0.0.
IFAIL=3
The optimization has failed to converge in ITER function iterations. Try either increasing the number of iterations using ITER or increasing the value of ε, given by IOPT, used to determine convergence. Alternatively try a different starting configuration.
IFAIL=4
The conditions for an acceptable solution have not been met but a lower point could not be found. Try using a larger value of ε, given by IOPT.
IFAIL=5
The optimization cannot begin from the initial configuration. Try a different set of points.
IFAIL=6
The optimization has failed. This error is only likely if IOPT<0. It corresponds to IFAIL=4, 7 and 9 in E04DGF/E04DGA.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

After a successful optimization the relative accuracy of STRESS should be approximately ε, as specified by IOPT.

8 Parallelism and Performance

G03FCF makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The optimization routine E04DGF/E04DGA used by G03FCF has a number of options to control the process. The options for the maximum number of iterations (Iteration Limit) and accuracy (Optimality Tolerance) can be controlled by ITER and IOPT respectively. The printing option (Print Level) is set to -1 to give no printing. The other option set is to stop the checking of derivatives (Verify=NO) for efficiency. All other options are left at their default values. If however IOPT<0 is used, only the maximum number of iterations is set. All other options can be controlled by the option setting mechanism of E04DGF/E04DGA with the defaults as given by that routine.
Missing values in the input distance matrix can be specified by a negative value and providing there are not more than about two thirds of the values missing the algorithm may still work. However the routine G03FAF does not allow for missing values so an alternative method of obtaining an initial set of coordinates is required. It may be possible to estimate the missing values with some form of average and then use G03FAF to give an initial set of coordinates.

10 Example

The data, given by Krzanowski (1990), are dissimilarities between water vole populations in Europe. Initial estimates are provided by the first two principal coordinates computed.

10.1 Program Text

Program Text (g03fcfe.f90)

10.2 Program Data

Program Data (g03fcfe.d)

10.3 Program Results

Program Results (g03fcfe.r)

GnuplotProduced by GNUPLOT 4.6 patchlevel 3 −0.4 −0.3 −0.2 −0.1 0 0.1 0.2 0.3 −0.6 −0.5 −0.4 −0.3 −0.2 −0.1 0 0.1 0.2 0.3 0.4 Second Principal Coordinate First Principal Coordinate Example Program Plot of Observation Number by the First Two Principal Coordinates gnuplot_plot_1 1 2 3 4 5 6 7 8 9 10 11 12 13 14
G03 Chapter Contents
G03 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


G03GAF : NAG Library, Mark 26

G03 Chapter Contents
G03 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

G03GAF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

G03GAF performs a mixture of Normals (Gaussians) for a given (co)variance structure.

2 Specification

SUBROUTINE G03GAF ( N, M, X, LDX, ISX, NVAR, NG, POPT, PROB, LPROB, NITER, RITER, W, G, SOPT, S, LDS, SDS, F, TOL, LOGLIK, IFAIL)
INTEGER | N, M, LDX, ISX(M), NVAR, NG, POPT, LPROB, NITER, RITER, SOPT, LDS, SDS, IFAIL
REAL (KIND=nag_wp) | X(LDX,M), PROB(LPROB,NG), W(NG), G(NVAR,NG), S(LDS,SDS,*), F(N,NG), TOL, LOGLIK

3 Description

A Normal (Gaussian) mixture model is a weighted sum of k group Normal densities given by,
p x∣w,μ,Σ = ∑ j=1 k wj g x∣μj,Σj ,  x∈ℝp
where:
  • x is a p-dimensional object of interest;
  • wj is the mixture weight for the jth group and ∑ j=1 k wj=1;
  • μj is a p-dimensional vector of means for the jth group;
  • Σj is the covariance structure for the jth group;
  • g(·) is the p-variate Normal density:
    g x∣μj,Σj = 1 2 π p/2 Σj 1/2 exp - 12 x-μj Σ j -1 x-μj T .
Optionally, the (co)variance structure may be pooled (common to all groups) or calculated for each group, and may be full or diagonal.

4 References

Hartigan J A (1975) Clustering Algorithms Wiley

5 Arguments

1:   N – INTEGERInput
On entry: n, the number of objects. There must be more objects than parameters in the model.
Constraints:
  • if SOPT=1, N>NG× NVAR×NVAR+NVAR;
  • if SOPT=2, N>NVAR× NG+NVAR ;
  • if SOPT=3, N>2×NG×NVAR ;
  • if SOPT=4, N>NVAR× NG+1 ;
  • if SOPT=5, N>NVAR×NG+1 .
2:   M – INTEGERInput
On entry: the total number of variables in array X.
Constraint: M≥1.
3:   X LDXM – REAL (KIND=nag_wp) arrayInput
On entry: X ij must contain the value of the jth variable for the ith object, for i=1,2,…,n and j=1,2,…,M.
4:   LDX – INTEGERInput
On entry: the first dimension of the array X as declared in the (sub)program from which G03GAF is called.
Constraint: LDX≥N.
5:   ISX M – INTEGER arrayInput
On entry: if NVAR=M all available variables are included in the model and ISX is not referenced; otherwise the jth variable will be included in the analysis if ISX j=1 and excluded if ISX j=0, for j=1,2,…,M.
Constraint: if NVAR≠M, ISX j=1 for NVAR values of j and ISX j=0 for the remaining M-NVAR values of j, for j=1,2,…,M.
6:   NVAR – INTEGERInput
On entry: p, the number of variables included in the calculations.
Constraint: 1≤NVAR≤M.
7:   NG – INTEGERInput
On entry: k, the number of groups in the mixture model.
Constraint: NG≥1.
8:   POPT – INTEGERInput
On entry: if POPT=1, the initial membership probabilities in PROB are set internally; otherwise these probabilities must be supplied.
9:   PROB LPROBNG – REAL (KIND=nag_wp) arrayInput/Output
On entry: if POPT≠1, PROB ij is the probability that the ith object belongs to the jth group. (These probabilities are normalised internally.)
On exit: PROB ij is the probability of membership of the ith object to the jth group for the fitted model.
10:   LPROB – INTEGERInput
On entry: the first dimension of the array PROB as declared in the (sub)program from which G03GAF is called.
Constraint: LPROB≥N.
11:   NITER – INTEGERInput/Output
On entry: the maximum number of iterations.
Suggested value: 15
On exit: the number of completed iterations.
Constraint: NITER≥1.
12:   RITER – INTEGERInput
On entry: if RITER>0, membership probabilities are rounded to 0.0 or 1.0 after the completion of every RITER iterations.
Suggested value: 5
13:   W NG – REAL (KIND=nag_wp) arrayOutput
On exit: wj, the mixing probability for the jth group.
14:   G NVARNG – REAL (KIND=nag_wp) arrayOutput
On exit: G ij gives the estimated mean of the ith variable in the jth group.
15:   SOPT – INTEGERInput
On entry: determines the (co)variance structure:
SOPT=1
Groupwise covariance matrices.
SOPT=2
Pooled covariance matrix.
SOPT=3
Groupwise variances.
SOPT=4
Pooled variances.
SOPT=5
Overall variance.
Constraint: SOPT=1, 2, 3, 4 or 5.
16:   S LDSSDS* – REAL (KIND=nag_wp) arrayOutput
Note: the last dimension of the array S must be at least NG if SOPT=1, and at least 1 otherwise.
On exit: if SOPT=1, S ijk gives the i,jth element of the kth group.
If SOPT=2, S ij 1 gives the i,jth element of the pooled covariance.
If SOPT=3, S jk 1 gives the jth variance in the kth group.
If SOPT=4, S j 11 gives the jth pooled variance.
If SOPT=5, S 111 gives the overall variance.
17:   LDS – INTEGERInput
On entry: the first dimension of the (co)variance structure S.
Constraints:
  • if SOPT=5, LDS=1;
  • otherwise LDS=NVAR.
18:   SDS – INTEGERInput
On entry: the second dimension of the (co)variance structure S.
Constraints:
  • if SOPT=1 or 2, SDS must be at least NVAR;
  • if SOPT=3, SDS must be at least NG;
  • if SOPT=4 or 5, SDS must be at least 1.
19:   F NNG – REAL (KIND=nag_wp) arrayOutput
On exit: F ij gives the p-variate Normal (Gaussian) density of the ith object in the jth group.
20:   TOL – REAL (KIND=nag_wp)Input
On entry: iterations cease the first time an improvement in log-likelihood is less than TOL. If TOL≤0 a value of 10-3 is used.
21:   LOGLIK – REAL (KIND=nag_wp)Output
On exit: the log-likelihood for the fitted mixture model.
22:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, N=value and p=value.
Constraint: N>p, the number of parameters, i.e., too few objects have been supplied for the model.
IFAIL=2
On entry, M=value.
Constraint: M≥1.
IFAIL=4
On entry, LDX=value and N=value.
Constraint: LDX≥N.
IFAIL=5
On entry, NVAR=value and M=value.
Constraint: 1≤NVAR≤M.
IFAIL=6
On entry, NVAR≠M and ISX is invalid.
IFAIL=7
On entry, NG=value.
Constraint: NG≥1.
IFAIL=8
On entry, POPT≠1 or 2.
IFAIL=9
On entry, row value of supplied PROB does not sum to 1.
IFAIL=10
On entry, LPROB=value and N=value.
Constraint: LPROB≥N.
IFAIL=11
On entry, NITER=value.
Constraint: NITER≥1.
IFAIL=16
On entry, SOPT<1 or SOPT>5.
IFAIL=18
On entry, LDS=value was invalid.
IFAIL=19
On entry, SDS=value was invalid.
IFAIL=44
A covariance matrix is not positive definite, try a different initial allocation.
IFAIL=45
An iteration cannot continue due to an empty group, try a different initial allocation.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

Not applicable.

8 Parallelism and Performance

G03GAF is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
G03GAF makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

None.

10 Example

This example fits a Gaussian mixture model with pooled covariance structure to New Haven schools test data, see Table 5.1 (p. 118) in Hartigan (1975).

10.1 Program Text

Program Text (g03gafe.f90)

10.2 Program Data

Program Data (g03gafe.d)

10.3 Program Results

Program Results (g03gafe.r)

G03 Chapter Contents
G03 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


G03 Chapter Introduction : NAG Library, Mark 26

G03 Chapter Contents
NAG Library Manual

NAG Library Chapter Introduction

G03 – Multivariate Methods

▸▿ Contents

1 Scope of the Chapter
▸▿ 2 Background to the Problems
▸▿ 2.1 Variable-directed Methods
2.1.1 Principal component analysis
2.1.2 Factor analysis
2.1.3 Canonical variate analysis
2.1.4 Canonical correlation analysis
2.1.5 Rotations
▸▿ 2.2 Individual-directed Methods
2.2.1 Hierarchical cluster analysis
2.2.2 Non-hierarchical clustering
2.2.3 Discriminant analysis
2.2.4 Scaling methods
3 Recommendations on Choice and Use of Available Routines
4 Functionality Index
5 Auxiliary Routines Associated with Library Routine Arguments
6 Routines Withdrawn or Scheduled for Withdrawal
7 References

1 Scope of the Chapter

This chapter is concerned with methods for studying multivariate data. A multivariate dataset consists of several variables recorded on a number of objects or individuals. Multivariate methods can be classified as those that seek to examine the relationships between the variables (e.g., principal components), known as variable-directed methods, and those that seek to examine the relationships between the objects (e.g., cluster analysis), known as individual-directed methods.
Multiple regression is not included in this chapter as it involves the relationship of a single variable, known as the response variable, to the other variables in the dataset, the explanatory variables. Routines for multiple regression are provided in Chapter G02.

2 Background to the Problems

2.1 Variable-directed Methods

Let the n by p data matrix consist of p variables, x 1,x 2,…,xp, observed on n objects or individuals. Variable-directed methods seek to examine the linear relationships between the p variables with the aim of reducing the dimensionality of the problem. There are different methods depending on the structure of the problem. Principal component analysis and factor analysis examine the relationships between all the variables. If the individuals are classified into groups, then canonical variate analysis examines the between group structure. If the variables can be considered as coming from two sets, then canonical correlation analysis examines the relationships between the two sets of variables. All four methods are based on an eigenvalue decomposition or a singular value decomposition (SVD) of an appropriate matrix.
The above methods may reduce the dimensionality of the data from the original p variables to a smaller number, k, of derived variables that adequately represent the data. In general, these k derived variables will be unique only up to an orthogonal rotation. Therefore, it may be useful to see if there exists suitable rotations of these variables that lead to a simple interpretation of the new variables in terms of the original variables.

2.1.1 Principal component analysis

Principal component analysis finds new variables which are linear combinations of the p observed variables so that they have maximum variation and are orthogonal (uncorrelated).
Let S be the p by p variance-covariance matrix of the n by p data matrix. A vector a 1 of length p is found such that
a 1 T S a 1​ is maximized subject to ​a 1 T a 1=1.
The variable z 1=∑i=1 p a 1 ixi is known as the first principal component and gives the linear combination of the variables that gives the maximum variation. A second principal component, z 2=∑i=1 p a 2 ixi, is found such that
a 2 T S a 2​ is maximized subject to ​a 2 T a 2=1​ and ​a 2 T a 1=0.
This gives the linear combination of variables, orthogonal to the first principal component, that gives the maximum variation. Further principal components are derived in a similar way.
The vectors ai, for i=1,2,…,p, are the eigenvectors of the matrix S and associated with each eigenvector is the eigenvalue, γi 2. The value of γi 2/∑γi 2 gives the proportion of variation explained by the ith principal component. Alternatively, the ai can be considered as the right singular vectors in a SVD of a scaled mean-centred data matrix. The singular values of the SVD are the γi-values.
Often fewer than p dimensions (principal components) are needed to represent most of the variation in the data. A test on the smaller eigenvalues can be used to investigate the number of dimensions needed.
The values of the principal component variables for the individuals are known as the principal component scores. These can be standardized so that the variance of these scores for each principal component is 1.0 or equal to the corresponding eigenvalue. The principal component scores correspond to the left-hand singular vectors in the SVD.

2.1.2 Factor analysis

Let the p variables have variance-covariance matrix Σ. The aim of factor analysis is to account for the covariances in these p variables in terms of a smaller number, k, of hypothetical variables or factors, f 1,f 2,…,fk. These are assumed to be independent and to have unit variance. The relationship between the observed variables and the factors is given by the model
xi=∑j=1 k λ ijfj+ei,  i=1,2,…,p
where λ ij, for i=1,2,…,p and j=1,2,…,k, are the factor loadings and ei, for i=1,2,…,p, are independent random variables with variances ψi. These represent the unique component of the variation of each observed variable. The proportion of variation for each variable accounted for by the factors is known as the communality.
The model for the variance-covariance matrix, Σ, can then be written as
Σ=Λ ΛT+Ψ,
where Λ is the matrix of the factor loadings, λ ij, and Ψ is a diagonal matrix of the unique variances ψi.
If it is assumed that both the k factors and the ei follow independent Normal distributions then the parameters of the model, Λ and Ψ, can be estimated by maximum likelihood, as described by Lawley and Maxwell (1971). The computation of the maximum likelihood estimates is an iterative procedure which involves computing the eigenvalues and eigenvectors of the matrix
S*=Ψ-1/2 S Ψ-1/2,
where S is the sample variance-covariance matrix. Alternatively, the SVD of the matrix R Ψ-1/2 can be used, where RT R=S. When convergence has been achieved, the estimates Λ^, of Λ, are obtained by scaling the eigenvectors of S*. The use of maximum likelihood estimation means that likelihood ratio tests can be constructed to test for the number of factors required.
Having found the estimates of the parameters of the model, the estimates of the values of the factors for the individuals, the factor scores, can be computed. These involve the calculation of the factor score coefficients. Two common methods of computing factor score coefficients are the regression method and Bartlett's method. Bartlett's method gives unbiased estimates of the factor scores while the estimates from the regression method are biased but have smaller variance; see Lawley and Maxwell (1971).

2.1.3 Canonical variate analysis

If the individuals can be classified into one of g groups, then canonical variate analysis finds the linear combinations of the p variables that maximize the ratio of the between-group variation to the within-group variation. These variables are known as canonical variates. As the canonical variates provide discrimination between the groups, the method is also known as canonical discrimination.
The canonical variates can be calculated from the eigenvectors of the within-group sums of squares and cross-products matrix or from the SVD of the matrix
V=QxT Qg,
where Qg is an orthogonal matrix that defines the groups and Qx is the first p columns of the orthogonal matrix Q from the QR decomposition of the data matrix with the variable means subtracted. If the data matrix is not of full rank, the Qx matrix can be obtained from a SVD. If the SVD of V is
V=Ux Δ UgT,
then the nonzero elements (δi>0) of the diagonal matrix Δ are the canonical correlations. The largest δi is called the first canonical correlation and associated with it is the first canonical variate.
The eigenvalues, γi 2, of the within-group sums of squares matrix are given by
γi 2=δi 2 1-δi 2 .
The value of πi=γi 2/∑γi 2 gives the proportion of variation explained by the ith canonical variate. The values of the πi give an indication as to how many canonical variates are needed to adequately describe the data, i.e., the dimensionality of the problem. The number of dimensions can be investigated by means of a test on the smaller canonical correlations.
The canonical variate loadings and the relationship between the original variables and the canonical variates are calculated from the matrix Ux. This matrix is scaled so that the canonical variates have unit variance.

2.1.4 Canonical correlation analysis

If the p variables can be considered as coming from two sets then canonical correlation analysis finds linear combinations of the variables in each set, known as canonical variates, such that the correlations between corresponding canonical variates for the two sets are maximized. Let the two sets of variables be denoted by x and y, with px and py variables in each set respectively. Let the variance-covariance of the dataset be
S= S xx S xy S yx S yy
and let
Σ=S yy -1 S yx S xx -1 S xy,
then the canonical correlations can be calculated from the eigenvalues of the matrix Σ. Alternatively, the canonical correlations can be calculated by means of a SVD of the matrix
V=QxT Qy,
where Qx is the first px columns of the orthogonal matrix Q from the QR decomposition of the x-variables in the data matrix, and Qy is the first py columns of the Q matrix of the QR decomposition of the y-variables in the data matrix. In both cases, the variable means are subtracted before the QR decomposition is computed. If either set of variables is not of full rank, an SVD can be used instead of the QR decomposition. If the SVD of V is
V=Ux Δ UyT,
then the nonzero elements (δi>0) of the diagonal matrix Δ are the canonical correlations. The largest δi is called the first canonical correlation and associated with it is the first canonical variate. The eigenvalues, γi 2, of the matrix Σ are given by
γi 2=δi 2 1+δi 2 .
The value of πi=γi 2/∑γi 2 gives the proportion of variation explained by the ith canonical variate. The values of the πi give an indication as to how many canonical variates are needed to adequately describe the data, i.e., the dimensionality of the problem; this can also be investigated by means of a test on the smaller values of the γi 2.
The relationship between the canonical variables and the original variables, the canonical variate loadings, can be computed from the Ux and Uy matrices.

2.1.5 Rotations

There are two principal reasons for using rotations: either
(a) | simplifying the structure to aid interpretation of derived variables, or
(b) | comparing two or more datasets or sets of derived variables.
The most common type of rotations used for (a) are orthogonal rotations. If Λ is the p by k loading matrix from a variable-directed multivariate method, then the rotations are selected such that the elements, λ ij*, of the rotated loading matrix, Λ*, are either relatively large or small. The rotations may be found by minimizing the criterion
V=∑j=1 k∑i=1 p λ ij* 4-γp∑j=1 k ∑i=1 p λ ij* 2 2
where the constant, γ, gives a family of rotations, with γ=1 giving varimax rotations and γ=0 giving quartimax rotations.
Given an orthogonal rotation matrix X, a solution may be further simplified by removing the orthogonality restriction with an oblique ProMax rotation. Let Y denote the matrix defined by a power transformation of X, designed to increase high values in X and decrease low values. Then the ProMax solution is based on a least squares fit of X to Y.
For (b) Procrustes rotations are used. Let A and B be two l by m matrices, which can be considered as representing l points in m dimensions. One example is if A is the loading matrix from a variable-directed multivariate method and B is a hypothesised pattern matrix. In order to try to match the points in A and B there are three steps:
(i) | translate so that centroids of both matrices are at the origin,
(ii) | find a rotation that minimizes the sum of squared distances between corresponding points of the matrices,
(iii) | scale the matrices.
For a more detailed description, see Krzanowski (1990).

2.2 Individual-directed Methods

While dealing with the same n by p data matrix as variable-directed methods, the emphasis is the n objects or individuals rather than the p variables. The methods are generally based on an n by n distance or dissimilarity matrix such that the (k,j)th element gives a measure of how ‘far apart’ the individuals k and j are. Alternatively, a similarity matrix can be used which measures how ‘close’ individuals are. The form of the measure of distance or similarity will depend upon the form of the p variables. For continuous variables it is usually assumed that some form of Euclidean distance is suitable. That is, for x ki and x ji measured for individuals k and j on variable i respectively, the contribution to distance between individuals k and j from variable i is given by
x ki-x ji 2.
Often there will be a need to scale the variables to produce satisfactory distances. For discrete variables, there are various measures of similarity or distance that can easily be computed. For example, for binary data a measure of similarity could be
  • 1 – if the individuals take the same value,
  • 0 – otherwise.
Given a measure of distance between individuals, there are three basic tasks that can be performed.
(i) | Group the individuals; that is, collect the individuals into groups so that those within a group are closer to each other than they are to members of another group.
(ii) | Classify individuals; that is, if some individuals are known to come from certain groups, allocate individuals whose group membership is unknown, to the nearest group.
(iii) | Map the individuals; that is, produce a multidimensional diagram in which the distances on the diagram represent the distances between the individuals.
In the above, (i) leads to cluster analysis, (ii) leads to discriminant analysis and (iii) leads to scaling methods.

2.2.1 Hierarchical cluster analysis

Approaches for cluster analysis can be classified into two types: hierarchical and non-hierarchical. Hierarchical cluster analysis produces a series of overlapping groups or clusters ranging from separate individuals to one single cluster. For example, five individuals could be hierarchically clustered as follows.
Step 1 | 1 | 2 | 3 | 4 | 5
Step 2 | 1,2 |  | 3 | 4 | 5
Step 3 | 1,2 |  | 3,4 |  | 5
Step 4 | 1,2 |  | 3,4,5
Step 5 | 1,2,3,4,5
The clusters at a level are constructed from the clusters at a previous level. There are two basic approaches to hierarchical cluster analysis: agglomerative methods which build up clusters starting from individuals until there is only one cluster, or divisive methods which start with a single cluster and split clusters until the individual level is reached. This chapter contains the more common agglomerative methods.
The stages in a hierarchical cluster analysis are usually as follows.
(i) | form a distance matrix;
(ii) | use selected criterion to form hierarchy;
(iii) | print cluster information in the form of a dendrogram or use information to form a set of clusters.
These three stages will be considered in turn.
(i) Form a distance matrix
For the n by p data matrix X, a general measure of the distance between object j and object k, d jk, is
d jk= ∑i=1 p D x ji/si,x ki/si α,
where x ji and x ki are the j,ith and k,ith elements of X, si is a standardization for the ith variable and D u,v is a suitable function. Three common distances for continuous variables are:
(a) | Euclidean distance: D u,v= u-v 2 and α=12 .
(b) | Euclidean squared distance: D u,v= u-v 2 and α=1.
(c) | Absolute distance (city block metric): D u,v=u-v and α=1.
The common standardizations are the standard deviation and the range. For dichotomous variables there are a number of different measures (see Krzanowski (1990) and Everitt (1974)); these are usually easy to compute. If the individuals in a cluster analysis are themselves variables, then a suitable distance measure will be based on the correlation coefficient for continuous variables and contingency table statistics for discrete data.
(ii) Form Hierarchy
Given a distance matrix for the n individuals, an agglomerative clustering method produces a hierarchical tree by starting with n clusters, each with a single individual and then at each of n-1 stages, merging two clusters to form a larger cluster until all individuals are in a single cluster. At each stage, the two clusters that are nearest are merged to form a new cluster and a new distance matrix is computed for the reduced number of clusters.
Methods differ as to how the distances between the new cluster and other clusters are computed. For three clusters i, j and k, let ni, nj and nk be the number of objects in each cluster, and let d ij, d ik and d jk be the distances between the clusters. If clusters j and k, are to be merged to give cluster jk, then the distance from cluster i to cluster jk, d i.jk, can be computed in the following ways.
(a) | Single link or nearest neighbour: d i.jk=min d ij,d ik.
(b) | Complete link or furthest neighbour: d i.jk=max d ij,d ik.
(c) | Group average: d i.jk=nj nj+nk d ij+nk nj+nk d ik.
(d) | Centroid: d i.jk=nj nj+nk d ij+nk nj+nk d ik-njnk nj+nk 2 d jk.
(e) | Median: d i.jk=12 d ij+12 d ik-14 d jk.
(f) | Minimum variance: d i.jk=ni+nj d ij+ni+nk d ik-nid jk/ni+nj+nk.
For further details, see Everitt (1974) or Krzanowski (1990).
(iii) Produce Dendrogram and Clusters
Hierarchical cluster analysis can be represented by a tree that shows at which distance the clusters merge. Such a tree is known as a dendrogram; see Everitt (1974) and Krzanowski (1990).
A simple example is
Figure 1
The end points of the dendrogram represent the individuals that have been clustered.
Alternatively, the information from the tree can be used to produce either a chosen number of clusters or the clusters that exist at a given distance. The latter is equivalent to taking the dendrogram and drawing a line across at a given distance to produce clusters.

2.2.2 Non-hierarchical clustering

Non-hierarchical cluster analysis usually forms a given number of clusters from the data. There is no requirement that if first k-1 and then k clusters were requested then the k-1 clusters would be formed from the k clusters.
Most non-hierarchical methods of cluster analysis seek to partition the set of individuals into a number of clusters so as to optimize a criterion. The number of clusters is usually specified prior to the analysis. One commonly used criterion is the within-cluster sum of squares. Given n individuals with p variables measured on each individual, x ij, for i=1,2,…,n and j=1,2,…,p, the within-cluster sum of squares for K clusters is
SSc=∑k=1 K∑i∈Sk ∑j=1 p x ij-x-kj 2,
where Sk is the set of objects in the kth cluster and x-kj is the mean for the variable j over cluster k. Starting with an initial allocation of individuals to clusters, the method then seeks to minimize SSc by a series of re-allocations. This is often known as K-means clustering.
In the K-means case individuals belong to a single cluster and are excluded from all remaining clusters. Alternatively, probabilities of cluster membership can be estimated and each cluster can have its own distributional properties. For example, given an initial set of probabilities, the Normal (Gaussian) mixture model uses the E–M method of Dempster et al. (1977) to maximize the sum of log-likelihoods over K clusters for a given covariance model ranging from pooled variance to individual covariance matrices.

2.2.3 Discriminant analysis

Discriminant analysis is concerned with the allocation of objects to ng groups on the basis of observations on those objects using an allocation rule. This rule is computed from observations coming from a training set in which group membership is known. The allocation rule is based on the distance between the object and an estimate of the location of the groups. If p variables are observed and the vector of means for the jth group in the training set are x-j then the usual measure of the distance of an observation, xk, from the jth group mean is given by Mahalanobis squared distance
D kj 2=xk-x-j T S*-1 xk-x-j,
where S* is either the within-group variance-covariance matrix, Sj, for the nj objects in the jth group, or a pooled variance-covariance matrix, S, computed from all n objects from all groups where
S=∑j=1 ng nj-1 Sj n-ng .
If the within-group variance-covariance matrices can be assumed to be equal then the pooled variance-covariance matrix can be used. This assumption can be tested using the test statistic
G=C n-ng log S-∑j= 1 ng nj- 1 log Sj ,
where
C=1-2 p 2+3 p-1 6 p+1ng-1 ∑j=1 ng 1 nj-1 -1 n-ng .
For large n, G is approximately distributed as a χ 2 variable with 12 p p+1ng-1 degrees of freedom; see Morrison (1967).
In addition to the distances, a set of prior probabilities of group membership, πj, for j=1,2,…,ng, may be used. The prior probabilities reflect your view as to the likelihood of the objects coming from the different groups.
It is generally assumed that the p variables follow a multivariate Normal distribution with, for the jth group, mean μj and variance-covariance matrix Σj. If p xk∣ μj ,Σj is the probability of observing the observation xk from group j, then the posterior probability of belonging to group j is
p j∣xk,μj,Σj∝ p xk∣ μj ,Σj πj .
An observation is allocated to the group with the highest posterior probability.
In the estimative approach to discrimination, the parameters μj and Σj in p j∣xk,μj,Σj are replaced by their estimates calculated from the training set. If it is assumed that the within-group variance-covariance matrices are equal then the linear discriminant function is obtained; otherwise if it is assumed that the variance-covariance matrices are unequal then the quadratic discriminant function is obtained.
In the Bayesian predictive approach, a non-informative prior distribution is used for the parameters giving the posterior distribution for the parameters from the training set, Xt, of, p μj, Σj∣ Xt . A predictive distribution is then obtained by integrating p j∣xk,μj,Σj p μj, Σj∣ X over the parameter space. This predictive distribution, p xk∣ Xt , then replaces p xk∣ μj ,Σj to give
p j∣xk,μj,Σj∝ p xk∣ Xt πj .
In addition to allocating the objects to groups, an atypicality index for each object and for each group can be computed. This represents the probability of obtaining an observation more typical of the group than that observed. A high value of the atypicality index for all groups indicates that the observation may in fact come from a group not represented in the training set.
Alternative approaches to discrimination are the use of canonical variates and logistic discrimination. Canonical variate analysis is described above and as it seeks to find the directions that best discriminate between groups these directions can also be used to allocate further observations. This can be viewed as an extension of Fisher's linear discriminant function. This approach does not assume that the data is Normally distributed, but Fisher's linear discriminant function may not perform well on non-Normal data. In the case of two groups, logistic regression can be performed with the response variable indicating the group allocation and the variables in the discriminant analysis being the explanatory variables. Allocation can then be made on the basis of the fitted response value. This is known as logistic discrimination and can be shown to be valid for a wide range of distributional assumptions.

2.2.4 Scaling methods

Scaling methods seek to represent the observed dissimilarities or distances between objects as distances between points in Euclidean space. For example if the distances between objects A, B and C were 3, 4 and 5, the distances could be represented exactly by three points in two-dimensional space. Only their relative positions would be important, the whole configuration of points could be rotated or shifted without effecting the distances between the points. If a one-dimensional representation was required, the ‘best’ representation might give distances of 2 13,3 13 and 5 23 , which may be an adequate representation. If the distances were 3, 4 and 8 then these distances could not be exactly represented in Euclidean space, even in two dimensions, the best representation being the three points in a straight line giving distances 3, 4 and 7.
In practice, the use of scaling methods has to decide upon the number of dimensions in which the data is to be represented. The smaller the number the easier it will be to assimilate the information. The chosen number of dimensions needs to give an adequate representation of the data but will often not give an exact representation because either the number of chosen dimensions is too small or the data cannot be represented in Euclidean space.
Two basic methods are available depending on the nature of the dissimilarities or distances being analysed. If the distances can be assumed to satisfy the metric inequality
d ij≤d ik+d kj,
then the distances can be represented exactly by points in Euclidean space and the technique known as metric scaling, classical scaling or principal coordinate analysis can be used. This technique involves the computing of the eigenvalues of a matrix derived from the distance matrix. The eigenvectors corresponding to the k largest positive eigenvalues gives the best k dimensions in which to represent the objects. If there are negative eigenvalues then the distance matrix cannot be represented in Euclidean space.
Instead of the above approach of requiring the distances from the points to match the distances from the objects as closely as possible, sometimes only a rank order equivalence is required. That is, the ith largest distance between objects should, as far as possible, be represented by the ith largest distance between points. This would be appropriate when the dissimilarities are based on subjective rankings. For example, if the objects were foods then a number of judges rank the foods for different qualities such as taste and texture, the resulting distances would not necessarily obey the metric inequality, but the rank order would be significant. Alternatively, by relaxing the requirement from matching distances to rank order equivalence only, the number of dimensions required to represent the distance matrix may be decreased. The requirement of rank order equivalence leads to non-metric or ordinal multidimensional scaling. The criterion used to measure the closeness of the fitted distance matrix to the observed distance matrix is known as STRESS, which is given by
∑i=1 n∑j=1 i-1 d ij^-d ij~ 2 ∑i=1 n∑j=1 i-1 d ij 2^ ,
where d ij 2^ is the Euclidean squared distance between the computed points i and j, and d ij~ is the fitted distance obtained when d ij^ is monotonically regressed on the observed distances d ij; that is, d ij~ is monotonic relative to d ij and is obtained from d ij^ with the smallest number of changes. Thus STRESS is a measure of by how much the set of points preserve the order of the distances in the original distance matrix, and non-metric multidimensional scaling seeks to find the set of points that minimize the STRESS.

3 Recommendations on Choice and Use of Available Routines

See Section 4 for a list of routines available in this Chapter.
Note also that G02GBF will fit a logistic regression model and can be used for logistic discrimination.

4 Functionality Index

Canonical correlation analysis G03ADF
Canonical variate analysis G03ACF
Cluster Analysis,
compute distance matrix G03EAF
construct clusters following G03ECF G03EJF
construct dendrogram following G03ECF G03EHF
Gaussian mixture model G03GAF
hierarchical G03ECF
K-means G03EFF
Discriminant Analysis,
allocation of observations to groups, following G03DAF G03DCF
Mahalanobis squared distances, following G03DAF G03DBF
test for equality of within-group covariance matrices G03DAF
Factor Analysis,
factor score coefficients, following G03CAF G03CCF
maximum likelihood estimates of parameters G03CAF
Principal component analysis G03AAF
Rotations,
orthogonal rotations for loading matrix G03BAF
Procustes rotations G03BCF
ProMax rotations G03BDF
Scaling Methods,
multidimensional scaling G03FCF
principal coordinate analysis G03FAF
Standardize values of a data matrix G03ZAF

5 Auxiliary Routines Associated with Library Routine Arguments

None.

6 Routines Withdrawn or Scheduled for Withdrawal

None.

7 References

Chatfield C and Collins A J (1980) Introduction to Multivariate Analysis Chapman and Hall
Dempster A P, Laird N M and Rubin D B (1977) Maximum likelihood from incomplete data via the EM algorithm (with discussion) J. Roy. Statist. Soc. Ser. B 39 1–38
Everitt B S (1974) Cluster Analysis Heinemann
Gnanadesikan R (1977) Methods for Statistical Data Analysis of Multivariate Observations Wiley
Hammarling S (1985) The singular value decomposition in multivariate statistics SIGNUM Newsl. 20(3) 2–25
Kendall M G and Stuart A (1976) The Advanced Theory of Statistics (Volume 3) (3rd Edition) Griffin
Krzanowski W J (1990) Principles of Multivariate Analysis Oxford University Press
Lawley D N and Maxwell A E (1971) Factor Analysis as a Statistical Method (2nd Edition) Butterworths
Morrison D F (1967) Multivariate Statistical Methods McGraw–Hill
G03 Chapter Contents
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


G03ZAF : NAG Library, Mark 26

G03 Chapter Contents
G03 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

G03ZAF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

G03ZAF produces standardized values (z-scores) for a data matrix.

2 Specification

SUBROUTINE G03ZAF ( N, M, X, LDX, NVAR, ISX, S, E, Z, LDZ, IFAIL)
INTEGER | N, M, LDX, NVAR, ISX(M), LDZ, IFAIL
REAL (KIND=nag_wp) | X(LDX,M), S(M), E(M), Z(LDZ,NVAR)

3 Description

For a data matrix, X, consisting of n observations on p variables, with elements x ij, G03ZAF computes a matrix, Z, with elements z ij such that:
z ij=x ij-μj σj,  i=1,2,…,n;  j=1,2,…,p,
where μj is a location shift and σj is a scaling factor. Typically, μj will be the mean and σj will be the standard deviation of the jth variable and therefore the elements in column j of Z will have zero mean and unit variance.

4 References

None.

5 Arguments

1:   N – INTEGERInput
On entry: n, the number of observations in the data matrix.
Constraint: N≥1.
2:   M – INTEGERInput
On entry: the number of variables in the data array X.
Constraint: M≥NVAR.
3:   X LDXM – REAL (KIND=nag_wp) arrayInput
On entry: X ij must contain the ith sample point for the jth variable, x ij, for i=1,2,…,n and j=1,2,…,M.
4:   LDX – INTEGERInput
On entry: the first dimension of the array X as declared in the (sub)program from which G03ZAF is called.
Constraint: LDX≥N.
5:   NVAR – INTEGERInput
On entry: p, the number of variables to be standardized.
Constraint: NVAR≥1.
6:   ISX M – INTEGER arrayInput
On entry: ISX j indicates whether or not the observations on the jth variable are included in the matrix of standardized values.
If ISX j≠0, the observations from the jth variable are included.
If ISX j=0, the observations from the jth variable are not included.
Constraint: ISX j≠0 for NVAR values of j.
7:   S M – REAL (KIND=nag_wp) arrayInput
On entry: if ISX j≠0, S j must contain the scaling (standard deviation), σj, for the jth variable.
If ISX j=0, S j is not referenced.
Constraint: if ISX j≠0, S j>0.0, for j=1,2,…,M.
8:   E M – REAL (KIND=nag_wp) arrayInput
On entry: if ISX j≠0, E j must contain the location shift (mean), μj, for the jth variable.
If ISX j=0, E j is not referenced.
9:   Z LDZNVAR – REAL (KIND=nag_wp) arrayOutput
On exit: the matrix of standardized values (z-scores), Z.
10:   LDZ – INTEGERInput
On entry: the first dimension of the array Z as declared in the (sub)program from which G03ZAF is called.
Constraint: LDZ≥N.
11:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, | N<1,
or | NVAR<1,
or | M<NVAR,
or | LDX<N,
or | LDZ<N.
IFAIL=2
On entry, there are not precisely NVAR elements of ISX≠0.
IFAIL=3
On entry, ISX j≠0 and S j≤0.0 for some j.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

Standard accuracy is achieved.

8 Parallelism and Performance

G03ZAF is not threaded in any implementation.

9 Further Comments

Means and standard deviations may be obtained using G01ATF or G02BXF.

10 Example

A 4 by 3 data matrix is input along with location and scaling values. The first and third columns are scaled and the results printed.

10.1 Program Text

Program Text (g03zafe.f90)

10.2 Program Data

Program Data (g03zafe.d)

10.3 Program Results

Program Results (g03zafe.r)

G03 Chapter Contents
G03 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


G04AGF : NAG Library, Mark 26

G04 Chapter Contents
G04 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

G04AGF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

G04AGF performs an analysis of variance for a two-way hierarchical classification with subgroups of possibly unequal size, and also computes the treatment group and subgroup means. A fixed effects model is assumed.

2 Specification

SUBROUTINE G04AGF ( Y, N, K, LSUB, NOBS, L, NGP, GBAR, SGBAR, GM, SS, IDF, F, FP, IFAIL)
INTEGER | N, K, LSUB(K), NOBS(L), L, NGP(K), IDF(4), IFAIL
REAL (KIND=nag_wp) | Y(N), GBAR(K), SGBAR(L), GM, SS(4), F(2), FP(2)

3 Description

In a two-way hierarchical classification, there are k (≥2) treatment groups, the ith of which is subdivided into li treatment subgroups. The jth subgroup of group i contains n ij observations, which may be denoted by
y 1 ij,y 2 ij,…,y n ij ij.
The general observation is denoted by y mij, being the mth observation in subgroup j of group i, for 1≤i≤k, 1≤j≤li, 1≤m≤n ij.
The following quantities are computed
(i) The subgroup means
y-.ij=∑m=1 n ij y mij n ij
(ii) The group means
y-.i.=∑j= 1 li∑m= 1 n ij y mij ∑j= 1 li n ij
(iii) The grand mean
y-…=∑i=1 k∑j=1 li∑m=1 n ij y mij ∑i=1 k∑j=1 li n ij
(iv) The number of observations in each group
n i.= ∑j= 1 li n ij
(v) Sums of squares
Between groups =SSg = ∑ i=1 k n i. y-.i.-y-… 2 Between subgroups within groups =SS sg= ∑ i=1 k ∑ j=1 li n ij y.ij-y-.i. 2 Residual (within subgroups) =SSres= ∑ i=1 k ∑ j=1 li ∑ m=1 n ij y mij-y-.ij 2 =SStot-SSg-SS sg Corrected total =SStot= ∑ i=1 k ∑ j=1 li ∑ m=1 n ij y mij-y-… 2
(vi) Degrees of freedom of variance components
Between groups: | k-1
Subgroups within groups: | l-k
Residual: | n-l
Total: | n-1
where
  • l=∑i=1 k li,
  • n=∑i=1 k n i.
(vii) F ratios. These are the ratios of the group and subgroup mean squares to the residual mean square.
Groups | F 1= Between groups sum of squares/k-1 Residual sum of squares/n-l = SSg/k-1 SSres/n-l
Subgroups | F 2= Between subgroups (within group) sum of squares/l-k Residual sum of squares/n-l = SS sg/l-k SSres/n-l
If either F ratio exceeds 9999.0, the value 9999.0 is assigned instead.
(viii) F significances. The probability of obtaining a value from the appropriate F-distribution which exceeds the computed mean square ratio.
Groups | p 1 = Prob F k - 1 , n - l > F 1
Subgroups | p 2 = Prob F l - k , n - l > F 2
where F ν 1,ν 2 denotes the central F-distribution with degrees of freedom ν 1 and ν 2.
If any Fi=9999.0, then pi is set to zero, i=1,2.

4 References

Kendall M G and Stuart A (1976) The Advanced Theory of Statistics (Volume 3) (3rd Edition) Griffin
Moore P G, Shirley E A and Edwards D E (1972) Standard Statistical Calculations Pitman

5 Arguments

1:   Y N – REAL (KIND=nag_wp) arrayInput
On entry: the elements of Y must contain the observations ymij in the following order:
y 111,y 211,…,y n 11 11,y 112,y 212,…,y n 12 12,…,y 11 l 1,…,
y n 1 l 1 1 l 1,…, y 1 ij,…,y n ij ij,…,y 1 k lk,…, y n k lk k lk.
In words, the ordering is by group, and within each group is by subgroup, the members of each subgroup being in consecutive locations in Y.
2:   N – INTEGERInput
On entry: n, the total number of observations.
3:   K – INTEGERInput
On entry: k, the number of groups.
Constraint: K≥2.
4:   LSUB K – INTEGER arrayInput
On entry: the number of subgroups within group i, li, for i=1,2,…,k.
Constraint: LSUB i>0, for i=1,2,…,k.
5:   NOBS L – INTEGER arrayInput
On entry: the numbers of observations in each subgroup, n ij, in the following order:
n 11,n 12,…,n 1 l 1,n 21,…,n 2 l 2,…,n k 1,…,n k lk
Constraint: n=∑i=1 k∑j=1 li n ij, that is N=∑i=1 l NOBS i and NOBS i>0, for i=1,2,…,l.
6:   L – INTEGERInput
On entry: l, the total number of subgroups.
Constraint: L=∑i=1 k LSUB i.
7:   NGP K – INTEGER arrayOutput
On exit: the total number of observations in group i, n i., for i=1,2,…,k.
8:   GBAR K – REAL (KIND=nag_wp) arrayOutput
On exit: the mean for group i, y-.i., for i=1,2,…,k.
9:   SGBAR L – REAL (KIND=nag_wp) arrayOutput
On exit: the subgroup means, y-.ij, in the following order:
y-.11,y-.12,…,y-.1 l 1,y-.21,y-.22,…,y-.2 l 2,…,y-.k 1,y-.k 2,…,y-.kl k.
10:   GM – REAL (KIND=nag_wp)Output
On exit: the grand mean, y-….
11:   SS 4 – REAL (KIND=nag_wp) arrayOutput
On exit: contains the sums of squares for the analysis of variance, as follows;
  • SS 1= Between group sum of squares, SSg,
  • SS 2= Between subgroup within groups sum of squares, SS sg,
  • SS 3= Residual sum of squares, SSres,
  • SS 4= Corrected total sum of squares, SStot.
12:   IDF 4 – INTEGER arrayOutput
On exit: contains the degrees of freedom attributable to each sum of squares in the analysis of variance, as follows:
  • IDF 1= Degrees of freedom for between group sum of squares,
  • IDF 2= Degrees of freedom for between subgroup within groups sum of squares,
  • IDF 3= Degrees of freedom for residual sum of squares,
  • IDF 4= Degrees of freedom for corrected total sum of squares.
13:   F 2 – REAL (KIND=nag_wp) arrayOutput
On exit: contains the mean square ratios, F 1 and F 2, for the between groups variation, and the between subgroups within groups variation, with respect to the residual, respectively.
14:   FP 2 – REAL (KIND=nag_wp) arrayOutput
On exit: contains the significances of the mean square ratios, p 1 and p 2 respectively.
15:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, K≤1.
IFAIL=2
On entry, LSUB i≤0, for some i=1,2,…,k.
IFAIL=3
On entry, L≠∑i=1 k LSUB i
IFAIL=4
On entry, NOBS i≤0, for some i=1,2,…,l.
IFAIL=5
On entry, N≠∑i=1 l NOBS i.
IFAIL=6
The total corrected sum of squares is zero, indicating that all the data values are equal. The means returned are therefore all equal, and the sums of squares are zero. No assignments are made to IDF, F, and FP.
IFAIL=7
The residual sum of squares is zero. This arises when either each subgroup contains exactly one observation, or the observations within each subgroup are equal. The means, sums of squares, and degrees of freedom are computed, but no assignments are made to F and FP.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

The computations are believed to be stable.

8 Parallelism and Performance

G04AGF is not threaded in any implementation.

9 Further Comments

The time taken by G04AGF increases approximately linearly with the total number of observations, n.

10 Example

This example has two groups, the first of which consists of five subgroups, and the second of three subgroups. The numbers of observations in each subgroup are not equal. The data represent the percentage stretch in the length of samples of sack kraft drawn from consignments (subgroups) received over two years (groups). For details see Moore et al. (1972).

10.1 Program Text

Program Text (g04agfe.f90)

10.2 Program Data

Program Data (g04agfe.d)

10.3 Program Results

Program Results (g04agfe.r)

G04 Chapter Contents
G04 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


G04BBF : NAG Library, Mark 26

G04 Chapter Contents
G04 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

G04BBF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

G04BBF computes the analysis of variance and treatment means and standard errors for a randomized block or completely randomized design.

2 Specification

SUBROUTINE G04BBF ( N, Y, IBLOCK, NT, IT, GMEAN, BMEAN, TMEAN, TABL, LDTABL, C, LDC, IREP, R, EF, TOL, IRDF, WK, IFAIL)
INTEGER | N, IBLOCK, NT, IT(*), LDTABL, LDC, IREP(NT), IRDF, IFAIL
REAL (KIND=nag_wp) | Y(N), GMEAN, BMEAN(abs(IBLOCK)), TMEAN(NT), TABL(LDTABL,5), C(LDC,NT), R(N), EF(NT), TOL, WK(3*NT)

3 Description

In a completely randomized design, experimental material is divided into a number of units, or plots, to which a treatment can be applied. In a randomized block design the units are grouped into blocks so that the variation within blocks is less than the variation between blocks. If every treatment is applied to one plot in each block it is a complete block design. If there are fewer plots per block than treatments then the design will be an incomplete block design and may be balanced or partially balanced.
For a completely randomized design, with t treatments and nt plots per treatment, the linear model is
y ij = μ + τj + e ij ,   j=1,2,…,t ​ and ​ i=1,2,…,nj ,
where y ij is the ith observation for the jth treatment, μ is the overall mean, τj is the effect of the jth treatment and e ij is the random error term. For a randomized block design, with t treatments and b blocks of k plots, the linear model is
y ij l = μ + βi + τl + e ij ,   i=1,2,…,b , ​ j=1,2,…,k ​ and ​ l=1,2,…,t ,
where βi is the effect of the ith block and the ij l notation indicates that the lth treatment is applied to the jth plot in the ith block.
The completely randomized design gives rise to a one-way analysis of variance. The treatments do not have to be equally replicated, i.e., do not have to occur the same number of times. First the overall mean, μ^, is computed and subtracted from the observations to give y ij′=y ij-μ^. The estimated treatment effects, τ^j are then computed as the treatment means of the mean adjusted observations, y ij′, and the treatment sum of squares can be computed from the sum of squares of the treatment totals of the y ij′ divided by the number of observations per treatment total, nj. The final residuals are computed as r ij=y ij′-τ^j, and, from the residuals, the residual sum of squares is calculated.
For the randomized block design the mean is computed and subtracted from the observations to give y ij l′=y ij l-μ^. The estimated block effects, ignoring treatment effects, β^i, are then computed using the block means of the y ij l′ and the unadjusted sum of squares computed as the sum of squared block totals for the y ij l′ divided by number of plots per block, k. The block adjusted observations are then computed as y ij l ′′=yi′j l=β^i. In the case of the complete block design, with the same replication for each treatment within each block, the blocks and treatments are orthogonal, and so the treatment effects are estimated as the treatment means of the block adjusted observations, y ij l ′′. The treatment sum of squares is computed as the sum of squared treatment totals of the y ij l ′′ divided by the number of replicates to the treatments, r=bk/t. Finally the residuals, and hence the residual sum of squares, are given by r ij l=y ij l ′′-τ^l.
For a design without the same replication for each treatment within each block the treatments and the blocks will not be orthogonal, so the treatments adjusted for blocks need to be computed. The adjusted treatment effects are found as the solution to the equations
R-N NT/k τ^=q,
where q is the vector of the treatment totals for block adjusted observations, y ij l ′′, R is a diagonal matrix with R ll equal to the number of times the lth treatment is replicated, and N is the t by b incidence matrix, with N lj equal to the number of times treatment l occurs in block j. The solution to the equations can be written as
τ^=Ωq
where Ω is a generalized inverse of R-N NT/k. The solution is found from the eigenvalue decomposition of R-N NT/k. The residuals are first calculated by subtracting the estimated treatment effects from the block adjusted observations to give r ij l′=y ij l ′′-τ^l. However, since only the unadjusted block effects have been removed and blocks and treatments are not orthogonal, the block means of the r ij l′ have to be subtracted to give the correct residuals, r ij l and residual sum of squares.
The mean squares are computed as the sum of squares divided by the degrees of freedom. The degrees of freedom for the unadjusted blocks is b-1, for the completely randomized and the complete block designs the degrees of freedom for the treatments is t-1. In the general case the degrees of freedom for treatments is the rank of the matrix Ω. The F-statistic given by the ratio of the treatment mean square to the residual mean square tests the hypothesis
H 0:τ 1=τ 2=⋯=τt=0.
The standard errors for the difference in treatment effects, or treatment means, for the completely randomized or the complete block designs, are given by:
se τj-τ j*=1 nj+1 n j* s 2
where s 2 is the residual mean square and nj=n j*=b in the complete block design. In the general case the variances of the treatment effects are given by
var τ=Ω s 2
from which the appropriate standard errors of the difference between treatment effects or the difference between adjusted means can be calculated.
In the complete block design all the information on the treatment effects is given by the within block analysis. In other designs there may be a loss of information due to the non-orthogonality of treatments and blocks. The efficiency of the within block analysis in these cases is given by the (canonical) efficiency factors, these are the nonzero eigenvalues of the matrix R-N NT/k, divided by the number of replicates in the case of equal replication, or by the mean of the number of replicates in the unequally replicated case, see John (1987). If more than one eigenvalue is zero then the design is said to be disconnected and some treatments can only be compared using a between block analysis.

4 References

Cochran W G and Cox G M (1957) Experimental Designs Wiley
Davis O L (1978) The Design and Analysis of Industrial Experiments Longman
John J A (1987) Cyclic Designs Chapman and Hall
John J A and Quenouille M H (1977) Experiments: Design and Analysis Griffin
Searle S R (1971) Linear Models Wiley

5 Arguments

1:   N – INTEGERInput
On entry: the number of observations.
Constraint: N≥2 and if abs IBLOCK≥2, N must be a multiple of abs IBLOCK.
2:   Y N – REAL (KIND=nag_wp) arrayInput
On entry: the observations in the order as described by IBLOCK and NT.
3:   IBLOCK – INTEGERInput
On entry: indicates the block structure.
abs IBLOCK≤1
There are no blocks, i.e., it is a completely randomized design.
IBLOCK≥2
There are IBLOCK blocks and the data should be input by blocks, i.e., Y must contain the observations for block 1 followed by the observations for block 2, etc.
IBLOCK≤-2
There are abs IBLOCK blocks and the data is input in parallel with respect to blocks, i.e., Y 1 must contain the first observation for block 1, Y 2 must contain the first observation for block 2⋯ Y abs IBLOCK must contain the first observation for block abs IBLOCK, Y abs IBLOCK+1 must contain the second observation for block 1, etc.
Constraint: IBLOCK=1, 2 or -2.
4:   NT – INTEGERInput
On entry: the number of treatments. If only blocks are required in the analysis then set NT=1.
Constraints:
  • if abs IBLOCK≥2, NT≥1;
  • otherwise NT≥2.
5:   IT* – INTEGER arrayInput
Note: the dimension of the array IT must be at least N if NT≥2, and at least 1 otherwise.
On entry: IT i indicates which of the NT treatments plot i received, for i=1,2,…,N.
If NT=1, IT is not referenced.
Constraint: 1≤IT i≤NT, for i=1,2,…,N.
6:   GMEAN – REAL (KIND=nag_wp)Output
On exit: the grand mean, μ^.
7:   BMEAN abs IBLOCK – REAL (KIND=nag_wp) arrayOutput
On exit: if abs IBLOCK≥2, BMEAN j contains the mean for the jth block, β^j, for j=1,2,…,b.
8:   TMEAN NT – REAL (KIND=nag_wp) arrayOutput
On exit: if NT≥2, TMEAN l contains the (adjusted) mean for the lth treatment, μ^*+τ^l, for l=1,2,…,t, where μ^* is the mean of the treatment adjusted observations, y ij l-τ^l.
9:   TABL LDTABL 5 – REAL (KIND=nag_wp) arrayOutput
On exit: the analysis of variance table. Column 1 contains the degrees of freedom, column 2 the sum of squares, and where appropriate, column 3 the mean squares, column 4 the F-statistic and column 5 the significance level of the F-statistic. Row 1 is for Blocks, row 2 for Treatments, row 3 for Residual and row 4 for Total. Mean squares are computed for all but the Total row; F-statistics and significance are computed for Treatments and Blocks, if present. Any unfilled cells are set to zero.
10:   LDTABL – INTEGERInput
On entry: the first dimension of the array TABL as declared in the (sub)program from which G04BBF is called.
Constraint: LDTABL≥4.
11:   C LDCNT – REAL (KIND=nag_wp) arrayOutput
On exit: if NT≥2, the upper triangular part of C contains the variance-covariance matrix of the treatment effects, the strictly lower triangular part contains the standard errors of the difference between two treatment effects (means), i.e., C ij contains the covariance of treatment i and j if j≥i and the standard error of the difference between treatment i and j if j<i, for i=1,2,…,t and j=1,2,…,t.
12:   LDC – INTEGERInput
On entry: the first dimension of the array C as declared in the (sub)program from which G04BBF is called.
Constraint: LDC≥NT.
13:   IREP NT – INTEGER arrayOutput
On exit: if NT≥2, the treatment replications, R ll, for l=1,2,…,NT.
14:   R N – REAL (KIND=nag_wp) arrayOutput
On exit: the residuals, ri, for i=1,2,…,N.
15:   EF NT – REAL (KIND=nag_wp) arrayOutput
On exit: if NT≥2, the canonical efficiency factors.
16:   TOL – REAL (KIND=nag_wp)Input
On entry: the tolerance value used to check for zero eigenvalues of the matrix Ω. If TOL=0.0 a default value of 10-5 is used.
Constraint: TOL≥0.0.
17:   IRDF – INTEGERInput
On entry: an adjustment to the degrees of freedom for the residual and total.
IRDF≥1
The degrees of freedom for the total is set to N-IRDF and the residual degrees of freedom adjusted accordingly.
IRDF=0
The total degrees of freedom for the total is set to N-1, as usual.
Constraint: IRDF≥0.
18:   WK 3×NT – REAL (KIND=nag_wp) arrayWorkspace
19:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, because for this routine the values of the output arguments may be useful even if IFAIL≠0 on exit, the recommended value is -1. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Note: G04BBF may return useful information for one or more of the following detected errors or warnings.
Errors or warnings detected by the routine:
IFAIL=1
On entry, | N<2,
or | NT≤0,
or | NT=1 and abs IBLOCK≤1,
or | LDTABL<4,
or | LDC<NT,
or | TOL<0.0,
or | IRDF<0.
IFAIL=2
On entry, abs IBLOCK≥2 and N is not a multiple of abs IBLOCK.
IFAIL=3
On entry, | IT i<1 or IT i>NT for some i when NT≥2,
or | no value of IT=j for some j=1,2,…,NT, when NT≥2.
IFAIL=4
On entry, the values of Y are constant.
IFAIL=5
A computed standard error is zero due to rounding errors, or the eigenvalue computation failed to converge. Both are unlikely error exits.
IFAIL=6
The treatments are totally confounded with blocks, so the treatment sum of squares and degrees of freedom are zero. The analysis of variance table is not computed, except for block and total sums of squares and degrees of freedom.
IFAIL=7
The residual degrees of freedom or the residual sum of squares are zero, columns 3, 4 and 5 of the analysis of variance table will not be computed and the matrix of standard errors and covariances, C, will not be scaled by s or s 2.
IFAIL=8
The design is disconnected; the standard errors may not be valid. The design may be nested.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

The algorithm used by G04BBF, described in Section 3, achieves greater accuracy than the traditional algorithms based on the subtraction of sums of squares.

8 Parallelism and Performance

G04BBF is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
G04BBF makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

To estimate missing values the Healy and Westmacott procedure or its derivatives may be used, see John and Quenouille (1977). This is an iterative procedure in which estimates of the missing values are adjusted by subtracting the corresponding values of the residuals. The new estimates are then used in the analysis of variance. This process is repeated until convergence. A suitable initial value may be the grand mean μ^. When using this procedure IRDF should be set to the number of missing values plus one to obtain the correct degrees of freedom for the residual sum of squares.
For designs such as Graeco–Latin squares one or more of the blocking factors has to be removed in a preliminary analysis before the final analysis using calls to G04BBF or G04BCF. The residuals from the preliminary analysis are then input to G04BBF. In these cases IRDF should be set to the difference between N and the residual degrees of freedom from preliminary analysis. Care should be taken when using this approach as there is no check on the orthogonality of the two analyses.
For analysis of covariance the residuals are obtained from an analysis of variance of both the response variable and the covariates. The residuals from the response variable are then regressed on the residuals from the covariates using, say, G02CBF or G02DAF. The results from those routines can be used to test for the significance of the covariates. To test the significance of the treatment effects after fitting the covariate, the residual sum of squares from the regression should be compared with the residual sum of squares obtained from the equivalent regression but using the residuals from fitting blocks only.

10 Example

The data, given by John and Quenouille (1977), are for a balanced incomplete block design with 10 blocks and 6 treatments and with 3 plots per block. The observations are the degree of pain experienced and the treatments are penicillin of different potency. The data is input and the analysis of variance table and treatment means are printed.

10.1 Program Text

Program Text (g04bbfe.f90)

10.2 Program Data

Program Data (g04bbfe.d)

10.3 Program Results

Program Results (g04bbfe.r)

G04 Chapter Contents
G04 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


G04BCF : NAG Library, Mark 26

G04 Chapter Contents
G04 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

G04BCF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

G04BCF computes the analysis of variance for a general row and column design together with the treatment means and standard errors.

2 Specification

SUBROUTINE G04BCF ( NREP, NROW, NCOL, Y, NT, IT, GMEAN, TMEAN, TABL, LDTABL, C, LDC, IREP, RPMEAN, RMEAN, CMEAN, R, EF, TOL, IRDF, WK, IFAIL)
INTEGER | NREP, NROW, NCOL, NT, IT(*), LDTABL, LDC, IREP(NT), IRDF, IFAIL
REAL (KIND=nag_wp) | Y(NREP*NROW*NCOL), GMEAN, TMEAN(NT), TABL(LDTABL,5), C(LDC,NT), RPMEAN(NREP), RMEAN(NREP*NROW), CMEAN(NREP*NCOL), R(NREP*NROW*NCOL), EF(NT), TOL, WK(3*NT)

3 Description

In a row and column design the experimental material can be characterised by a two-way classification, nominally called rows and columns. Each experimental unit can be considered as being located in a particular row and column. It is assumed that all rows are of the same length and all columns are of the same length. Sets of equal numbers of rows/columns can be grouped together to form replicates, sometimes known as squares or rectangles, as appropriate.
If for a replicate, the number of rows, the number of columns and the number of treatments are equal and every treatment occurs once in each row and each column then the design is a Latin square. If this is not the case the treatments will be non-orthogonal to rows and columns. For example in the case of a lattice square each treatment occurs only once in each square.
For a row and column design, with t treatments in r rows and c columns and b replicates or squares with n=brc observations the linear model is:
y ijk l = μ+ βi+ ρj+ γk+ τl+ e ijk
for i=1,2…,b, j=1,2,…,r, k=1,2…,c and l=1,2,…,t, where βi is the effect of the ith replicate, ρj is the effect of the jth row, γk is the effect of the kth column and the ijk l notation indicates that the lth treatment is applied to the unit in row j, column k of replicate i.
To compute the analysis of variance for a row and column design the mean is computed and subtracted from the observations to give, y ijk l′=y ijk l-μ^. Since the replicates, rows and columns are orthogonal the estimated effects, ignoring treatment effects, β^i, ρ^j, γ^k, can be computed using the appropriate means of the y ijk l′, and the unadjusted sum of squares computed as the appropriate sum of squared totals for the y ijk l′ divided by number of units per total. The observations adjusted for replicates, rows and columns can then be computed by subtracting the estimated effects from y ijk l′ to give y ijk l ′′.
In the case of a Latin square design the treatments are orthogonal to replicates, rows and columns and so the treatment effects, τ^l, can be estimated as the treatment means of the adjusted observations, y ijk l ′′. The treatment sum of squares is computed as the sum of squared treatment totals of the y ij l ′′ divided by the number of times each treatment is replicated. Finally the residuals, and hence the residual sum of squares, are given by r ij l=y ij l ′′-τ^l.
For a design which is not orthogonal, for example a lattice square or an incomplete Latin square, the treatment effects adjusted for replicates, rows and columns need to be computed. The adjusted treatment effects are found as the solution to the equations:
A τ^=R-Nb NbT/rc-Nr NrT/bc-Nc NcT/br τ^=q
where q is the vector of the treatment totals of the observations adjusted for replicates, rows and columns, y ijk l ′′, R is a diagonal matrix with R ll equal to the number of times the lth treatment is replicated, and Nb is the t by b incidence matrix, with N l,i equal to the number of times treatment l occurs in replicate i, with Nr and Nc being similarly defined for rows and columns. The solution to the equations can be written as:
τ^=Ωq
where, Ω is a generalized inverse of A. The solution is found from the eigenvalue decomposition of A. The residuals are first calculated by subtracting the estimated adjusted treatment effects from the adjusted observations to give r ij l′=y ij l ′′-τ^l. However, since only the unadjusted replicate, row and column effects have been removed and they are not orthogonal to treatments, the replicate, row and column means of the r ij l′ have to be subtracted to give the correct residuals, r ij l and residual sum of squares.
Given the sums of squares, the mean squares are computed as the sums of squares divided by the degrees of freedom. The degrees of freedom for the unadjusted replicates, rows and columns are b-1, r-1 and c-1 respectively and for the Latin square designs the degrees of freedom for the treatments is t-1. In the general case the degrees of freedom for treatments is the rank of the matrix Ω. The F-statistic given by the ratio of the treatment mean square to the residual mean square tests the hypothesis:
H 0:τ 1=τ 2=⋯=τt=0.
The standard errors for the difference in treatment effects, or treatment means, for Latin square designs, are given by:
se τ^j-τ^j*=2 s 2/bt
where s 2 is the residual mean square. In the general case the variances of the treatment effects are given by:
Var τ^=Ω s 2
from which the appropriate standard errors of the difference between treatment effects or the difference between adjusted means can be calculated.
The analysis of a row-column design can be considered as consisting of different strata: the replicate stratum, the rows within replicate and the columns within replicate strata and the units stratum. In the Latin square design all the information on the treatment effects is given at the units stratum. In other designs there may be a loss of information due to the non-orthogonality of treatments and replicates, rows and columns and information on treatments may be available in higher strata. The efficiency of the estimation at the units stratum is given by the (canonical) efficiency factors, these are the nonzero eigenvalues of the matrix, A, divided by the number of replicates in the case of equal replication, or by the mean of the number of replicates in the unequally replicated case, see John (1987). If more than one eigenvalue is zero then the design is said to be disconnected and information on some treatment comparisons can only be obtained from higher strata.

4 References

Cochran W G and Cox G M (1957) Experimental Designs Wiley
Davis O L (1978) The Design and Analysis of Industrial Experiments Longman
John J A (1987) Cyclic Designs Chapman and Hall
John J A and Quenouille M H (1977) Experiments: Design and Analysis Griffin
Searle S R (1971) Linear Models Wiley

5 Arguments

1:   NREP – INTEGERInput
On entry: b, the number of replicates.
Constraint: NREP≥1.
2:   NROW – INTEGERInput
On entry: r, the number of rows per replicate.
Constraint: NROW≥2.
3:   NCOL – INTEGERInput
On entry: c, the number of columns per replicate.
Constraint: NCOL≥2.
4:   Y NREP×NROW×NCOL – REAL (KIND=nag_wp) arrayInput
On entry: the n=brc observations ordered by columns within rows within replicates. That is Y rc i-1 +r j-1 +k contains the observation from the kth column of the jth row of the ith replicate, for i=1,2,…,b, j=1,2,…,r and k=1,2,…,c.
5:   NT – INTEGERInput
On entry: the number of treatments. If only replicates, rows and columns are required in the analysis then set NT=1.
Constraint: NT≥1.
6:   IT* – INTEGER arrayInput
Note: the dimension of the array IT must be at least NREP×NROW×NCOL if NT>1, and at least 1 otherwise.
On entry: if NT>1, IT i indicates which of the NT treatments unit i received, for i=1,2,…,n.
If NT=1, IT is not referenced.
Constraint: if NT≥2, 1≤IT i≤NT, for i=1,2,…,n.
7:   GMEAN – REAL (KIND=nag_wp)Output
On exit: the grand mean, μ^.
8:   TMEAN NT – REAL (KIND=nag_wp) arrayOutput
On exit: if NT≥2, TMEAN l contains the (adjusted) mean for the lth treatment, μ^*+τ^l, for l=1,2,…,t, where μ^* is the mean of the treatment adjusted observations y ijk l-τ^l. Otherwise TMEAN is not referenced.
9:   TABL LDTABL 5 – REAL (KIND=nag_wp) arrayOutput
On exit: the analysis of variance table. Column 1 contains the degrees of freedom, column 2 the sum of squares, and where appropriate, column 3 the mean squares, column 4 the F-statistic and column 5 the significance level of the F-statistic. Row 1 is for replicates, row 2 for rows, row 3 for columns, row 4 for treatments (if NT>1), row 5 for residual and row 6 for total. Mean squares are computed for all but the total row, F-statistics and significance are computed for treatments, replicates, rows and columns. Any unfilled cells are set to zero.
10:   LDTABL – INTEGERInput
On entry: the first dimension of the array TABL as declared in the (sub)program from which G04BCF is called.
Constraint: LDTABL≥6.
11:   C LDCNT – REAL (KIND=nag_wp) arrayOutput
On exit: the upper triangular part of C contains the variance-covariance matrix of the treatment effects, the strictly lower triangular part contains the standard errors of the difference between two treatment effects (means), i.e., C ij contains the covariance of treatment i and j if j≥i and the standard error of the difference between treatment i and j if j<i, for i=1,2,…,t and j=1,2,…,t.
12:   LDC – INTEGERInput
On entry: the first dimension of the array C as declared in the (sub)program from which G04BCF is called.
Constraint: LDC≥NT.
13:   IREP NT – INTEGER arrayOutput
On exit: if NT>1, the treatment replications, R ll, for l=1,2,…,NT. Otherwise IREP is not referenced.
14:   RPMEAN NREP – REAL (KIND=nag_wp) arrayOutput
On exit: if NREP>1, RPMEAN i contains the mean for the ith replicate, μ^+β^i, for i=1,2,…,b. Otherwise RPMEAN is not referenced.
15:   RMEAN NREP×NROW – REAL (KIND=nag_wp) arrayOutput
On exit: RMEAN j contains the mean for the jth row, μ^+ρ^i, for j=1,2,…,r.
16:   CMEAN NREP×NCOL – REAL (KIND=nag_wp) arrayOutput
On exit: CMEAN k contains the mean for the kth column, μ^+γ^k, for k=1,2,…,c.
17:   R NREP×NROW×NCOL – REAL (KIND=nag_wp) arrayOutput
On exit: the residuals, ri, for i=1,2,…,n.
18:   EF NT – REAL (KIND=nag_wp) arrayOutput
On exit: if NT≥2, the canonical efficiency factors. Otherwise EF is not referenced.
19:   TOL – REAL (KIND=nag_wp)Input
On entry: the tolerance value used to check for zero eigenvalues of the matrix Ω. If TOL=0.0 a default value of 0.00001 is used.
Constraint: TOL≥0.0.
20:   IRDF – INTEGERInput
On entry: an adjustment to the degrees of freedom for the residual and total.
IRDF≥1
The degrees of freedom for the total is set to n-IRDF and the residual degrees of freedom adjusted accordingly.
IRDF=0
the total degrees of freedom for the total is set to n-1, as usual.
Constraint: IRDF≥0.
21:   WK 3×NT – REAL (KIND=nag_wp) arrayWorkspace
22:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, because for this routine the values of the output arguments may be useful even if IFAIL≠0 on exit, the recommended value is -1. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Note: G04BCF may return useful information for one or more of the following detected errors or warnings.
Errors or warnings detected by the routine:
IFAIL=1
On entry, | NREP<1,
or | NROW<2,
or | NCOL<2,
or | NT<1,
or | LDTABL<6,
or | LDC<NT,
or | TOL<0.0,
or | IRDF<0.
IFAIL=2
On entry, | IT i<1 or IT i>NT for some i when NT≥2,
or | no value of IT=j for some j=1,2,…,NT, when NT≥2.
IFAIL=3
On entry, the values of Y are constant.
IFAIL=4
A computed standard error is zero due to rounding errors, or the eigenvalue computation failed to converge. Both are unlikely error exits.
IFAIL=5
The treatments are totally confounded with replicates, rows and columns, so the treatment sum of squares and degrees of freedom are zero. The analysis of variance table is not computed, except for replicate, row, column and total sums of squares and degrees of freedom.
IFAIL=6
The residual degrees of freedom or the residual sum of squares are zero, columns 3, 4 and 5 of the analysis of variance table will not be computed and the matrix of standard errors and covariances, C, will not be scaled by s or s 2.
IFAIL=7
The design is disconnected, the standard errors may not be valid. The design may have a nested structure.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

The algorithm used in G04BCF, described in Section 3, achieves greater accuracy than the traditional algorithms based on the subtraction of sums of squares.

8 Parallelism and Performance

G04BCF is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
G04BCF makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

To estimate missing values the Healy and Westmacott procedure or its derivatives may be used, see John and Quenouille (1977). This is an iterative procedure in which estimates of the missing values are adjusted by subtracting the corresponding values of the residuals. The new estimates are then used in the analysis of variance. This process is repeated until convergence. A suitable initial value may be the grand mean. When using this procedure IRDF should be set to the number of missing values plus one to obtain the correct degrees of freedom for the residual sum of squares.
For analysis of covariance the residuals are obtained from an analysis of variance of both the response variable and the covariates. The residuals from the response variable are then regressed on the residuals from the covariates using, say, G02CBF or G02DAF. The results from those routines can be used to test for the significance of the covariates. To test the significance of the treatment effects after fitting the covariate, the residual sum of squares from the regression should be compared with the residual sum of squares obtained from the equivalent regression but using the residuals from fitting replicates, rows and columns only.

10 Example

The data for a 5×5 Latin square is input and the ANOVA and treatment means computed and printed. Since the design is orthogonal only one standard error need be printed

10.1 Program Text

Program Text (g04bcfe.f90)

10.2 Program Data

Program Data (g04bcfe.d)

10.3 Program Results

Program Results (g04bcfe.r)

G04 Chapter Contents
G04 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


G04CAF : NAG Library, Mark 26

G04 Chapter Contents
G04 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

G04CAF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

G04CAF computes an analysis of variance table and treatment means for a complete factorial design.

2 Specification

SUBROUTINE G04CAF ( N, Y, NFAC, LFAC, NBLOCK, INTER, IRDF, MTERM, TABLE, ITOTAL, TMEAN, MAXT, E, IMEAN, SEMEAN, BMEAN, R, IWK, IFAIL)
INTEGER | N, NFAC, LFAC(NFAC), NBLOCK, INTER, IRDF, MTERM, ITOTAL, MAXT, IMEAN(MTERM), IWK(N+3*NFAC), IFAIL
REAL (KIND=nag_wp) | Y(N), TABLE(MTERM,5), TMEAN(MAXT), E(MAXT), SEMEAN(MTERM), BMEAN(NBLOCK+1), R(N)

3 Description

An experiment consists of a collection of units, or plots, to which a number of treatments are applied. In a factorial experiment the effects of several different sets of conditions are compared, e.g., three different temperatures, T 1, T 2 and T 3, and two different pressures, P 1 and P 2. The conditions are known as factors and the different values the conditions take are known as levels. In a factorial experiment the experimental treatments are the combinations of all the different levels of all factors, e.g.,
T 1P 1, T 2P 1, T 3P 1 T 1P 2, T 2P 2, T 3P 2
The effect of a factor averaged over all other factors is known as a main effect, and the effect of a combination of some of the factors averaged over all other factors is known as an interaction. This can be represented by a linear model. In the above example if the response was y ijk for the kth replicate of the ith level of T and the jth level of P the linear model would be
y ijk = μ+ ti+ pj+ γ ij+ e ijk
where μ is the overall mean, ti is the main effect of T, pj is the main effect of P, γ ij is the T×P interaction and e ijk is the random error term. In order to find unique estimates constraints are placed on the arguments estimates. For the example here these are:
∑i=1 3 t^i=0, ∑j=1 2 p^j=0, ∑ i=1 3 γ^ij = 0 , for ​j=1,2​ and ∑ j=1 2 γ^ ij = 0 , for ​ i=1,2,3 ,
where ​ ​^ denotes the estimate.
If there is variation in the experimental conditions (e.g., in an experiment on the production of a material different batches of raw material may be used, or the experiment may be carried out on different days), then plots that are similar are grouped together into blocks. For a balanced complete factorial experiment all the treatment combinations occur the same number of times in each block.
G04CAF computes the analysis of variance (ANOVA) table by sequentially computing the totals and means for an effect from the residuals computed when previous effects have been removed. The effect sum of squares is the sum of squared totals divided by the number of observations per total. The means are then subtracted from the residuals to compute a new set of residuals. At the same time the means for the original data are computed. When all effects are removed the residual sum of squares is computed from the residuals. Given the sums of squares an ANOVA table is then computed along with standard errors for the difference in treatment means.
The data for G04CAF has to be in standard order given by the order of the factors. Let there be k factors, f 1,f 2,…,fk in that order with levels l 1,l 2,…,lk respectively. Standard order requires the levels of factor f 1 are in order 1,2,…,l 1 and within each level of f 1 the levels of f 2 are in order 1,2,…,l 2 and so on.
For an experiment with blocks the data is for block 1 then for block 2, etc. Within each block the data must be arranged so that the levels of factor f 1 are in order 1,2,…,l 1 and within each level of f 1 the levels of f 2 are in order 1,2,…,l 2 and so on. Any within block replication of treatment combinations must occur within the levels of fk.
The ANOVA table is given in the following order. For a complete factorial experiment the first row is for blocks, if present, then the main effects of the factors in their order, e.g., f 1 followed by f 2, etc. These are then followed by all the two factor interactions then all the three factor interactions, etc., the last two rows being for the residual and total sums of squares. The interactions are arranged in lexical order for the given factor order. For example, for the three factor interactions for a five factor experiment the 10 interactions would be in the following order:
f 1f 2f 3 f 1f 2f 4 f 1f 2f 5 f 1f 3f 4 f 1f 3f 5 f 1f 4f 5 f 2f 3f 4 f 2f 3f 5 f 2f 4f 5 f 3f 4f 5

4 References

Cochran W G and Cox G M (1957) Experimental Designs Wiley
Davis O L (1978) The Design and Analysis of Industrial Experiments Longman
John J A and Quenouille M H (1977) Experiments: Design and Analysis Griffin

5 Arguments

1:   N – INTEGERInput
On entry: the number of observations.
Constraints:
  • N≥4;
  • if NBLOCK>1, N must be a multiple of NBLOCK;
  • N must be a multiple of the number of treatment combinations, that is a multiple of ∏i=1 k LFAC i.
2:   Y N – REAL (KIND=nag_wp) arrayInput
On entry: the observations in standard order, see Section 3.
3:   NFAC – INTEGERInput
On entry: k, the number of factors.
Constraint: NFAC≥1.
4:   LFAC NFAC – INTEGER arrayInput
On entry: LFAC i must contain the number of levels for the ith factor, for i=1,2,…,k.
Constraint: LFAC i≥2, for i=1,2,…,k.
5:   NBLOCK – INTEGERInput
On entry: the number of blocks. If there are no blocks, set NBLOCK=0 or 1.
Constraints:
  • NBLOCK≥0;
  • if NBLOCK≥2, N/NBLOCK must be a multiple of the number of treatment combinations, that is a multiple of ∏i=1 k LFAC i.
6:   INTER – INTEGERInput
On entry: the maximum number of factors in an interaction term. If no interaction terms are to be computed, set INTER=0 or 1.
Constraint: 0≤INTER≤NFAC.
7:   IRDF – INTEGERInput
On entry: the adjustment to the residual and total degrees of freedom. The total degrees of freedom are set to N-IRDF and the residual degrees of freedom adjusted accordingly. For examples of the use of IRDF see Section 9.
Constraint: IRDF≥0.
8:   MTERM – INTEGERInput
On entry: the maximum number of terms in the analysis of variance table, see Section 9.
Constraint: MTERM must be large enough to contain the terms specified by NFAC, INTER and NBLOCK. If the routine exits with IFAIL≥2, the required minimum value of MTERM is returned in ITOTAL.
9:   TABLE MTERM 5 – REAL (KIND=nag_wp) arrayOutput
On exit: the first ITOTAL rows of TABLE contain the analysis of variance table. The first column contains the degrees of freedom, the second column contains the sum of squares, the third column (except for the row corresponding to the total sum of squares) contains the mean squares, i.e., the sums of squares divided by the degrees of freedom, and the fourth and fifth columns contain the F ratio and significance level, respectively (except for rows corresponding to the total sum of squares, and the residual sum of squares). All other cells of the table are set to zero.
The first row corresponds to the blocks and is set to zero if there are no blocks. The ITOTALth row corresponds to the total sum of squares for Y and the ITOTAL-1th row corresponds to the residual sum of squares. The central rows of the table correspond to the main effects followed by the interaction if specified by INTER. The main effects are in the order specified by LFAC and the interactions are in lexical order, see Section 3.
10:   ITOTAL – INTEGEROutput
On exit: the row in TABLE corresponding to the total sum of squares. The number of treatment effects is ITOTAL-3.
11:   TMEAN MAXT – REAL (KIND=nag_wp) arrayOutput
On exit: the treatment means. The position of the means for an effect is given by the index in IMEAN. For a given effect the means are in standard order, see Section 3.
12:   MAXT – INTEGERInput
On entry: the maximum number of treatment means to be computed, see Section 9. If the value of MAXT is too small for the required analysis then the minimum number is returned in IMEAN 1.
Constraint: MAXT must be large enough for the number of means specified by LFAC and INTER; if INTER=NFAC then MAXT≥∏i=1 k LFAC i+1-1.
13:   E MAXT – REAL (KIND=nag_wp) arrayOutput
On exit: the estimated effects in the same order as for the means in TMEAN.
14:   IMEAN MTERM – INTEGER arrayOutput
On exit: indicates the position of the effect means in TMEAN. The effect means corresponding to the first treatment effect in the ANOVA table are stored in TMEAN 1 up to TMEAN IMEAN 1. Other effect means corresponding to the ith treatment effect, i=1,2,…,ITOTAL-3, are stored in TMEAN IMEAN i-1+1 up to TMEAN IMEAN i.
15:   SEMEAN MTERM – REAL (KIND=nag_wp) arrayOutput
On exit: the standard error of the difference between means corresponding to the ith treatment effect in the ANOVA table.
16:   BMEAN NBLOCK+1 – REAL (KIND=nag_wp) arrayOutput
On exit: BMEAN 1 contains the grand mean, if NBLOCK>1, BMEAN 2 up to BMEAN NBLOCK+1 contain the block means.
17:   R N – REAL (KIND=nag_wp) arrayOutput
On exit: the residuals.
18:   IWK N+3×NFAC – INTEGER arrayWorkspace
19:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, | N<4,
or | NFAC<1,
or | NBLOCK<0,
or | INTER<0,
or | INTER>NFAC,
or | IRDF<0.
IFAIL=2
On entry, | LFAC i≤1, for some i=1,2,…,NFAC,
or | the value of MAXT is too small,
or | the value of MTERM is too small,
or | NBLOCK>1 and N is not a multiple of NBLOCK,
or | the number of plots per block is not a multiple of the number of treatment combinations.
IFAIL=3
On entry, the values of Y are constant.
IFAIL=4
There are no degrees of freedom for the residual or the residual sum of squares is zero. In either case the standard errors and F-statistics cannot be computed.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

The block and treatment sums of squares are computed from the block and treatment residual totals. The residuals are updated as each effect is computed and the residual sum of squares computed directly from the residuals. This avoids any loss of accuracy in subtracting sums of squares.

8 Parallelism and Performance

G04CAF makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The number of rows in the ANOVA table and the number of treatment means are given by the following formulae.
Let there be k factors with levels li for i=1,2,…,k, and let t be the maximum number of terms in an interaction then the number of rows in the ANOVA tables is:
∑i=1 t k i +3.
The number of treatment means is:
∑ i =1 t ∏ j ∈ S i l j ,
where Si is the set of all combinations of the k factors i at a time.
To estimate missing values the Healy and Westmacott procedure or its derivatives may be used, see John and Quenouille (1977). This is an iterative procedure in which estimates of the missing values are adjusted by subtracting the corresponding values of the residuals. The new estimates are then used in the analysis of variance. This process is repeated until convergence. A suitable initial value may be the grand mean. When using this procedure IRDF should be set to the number of missing values plus one to obtain the correct degrees of freedom for the residual sum of squares.
For analysis of covariance the residuals are obtained from an analysis of variance of both the response variable and the covariates. The residuals from the response variable are then regressed on the residuals from the covariates using, say, G02CBF or G02DAF. The coefficients obtained from the regression can be examined for significance and used to produce an adjusted dependent variable using the original response variable and covariate. An approximate adjusted analysis of variance table can then be produced by using the adjusted dependent variable. In this case IRDF should be set to one plus the number of fitted covariates.
For designs such as Latin squares one more of the blocking factors has to be removed in a preliminary analysis before the final analysis. This preliminary analysis can be performed using G04BBF or a prior call to G04CAF if the data is reordered between calls. The residuals from the preliminary analysis are then input to G04CAF. In these cases IRDF should be set to the difference between N and the residual degrees of freedom from preliminary analysis. Care should be taken when using this approach as there is no check on the orthogonality of the two analyses.

10 Example

The data, given by John and Quenouille (1977), is for the yield of turnips for a factorial experiment with two factors, the amount of phosphate with 6 levels and the amount of liming with 3 levels. The design was replicated in 3 blocks. The data is input and the analysis of variance computed. The analysis of variance table and tables of means with their standard errors are printed.

10.1 Program Text

Program Text (g04cafe.f90)

10.2 Program Data

Program Data (g04cafe.d)

10.3 Program Results

Program Results (g04cafe.r)

G04 Chapter Contents
G04 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


G04 Chapter Contents : NAG Library Manual, Mark 26

G04 Chapter Introduction
NAG Library Manual

NAG Library Chapter Contents

G04 – Analysis of Variance

G04 Chapter Introduction – a description of the Chapter and an overview of the algorithms available

Routine Name | Mark of Introduction | Purpose
G04AGF Example Text Example Data | 8 | nagf_anova_hier2 Two-way analysis of variance, hierarchical classification, subgroups of unequal size
G04BBF Example Text Example Data | 16 | nagf_anova_random Analysis of variance, randomized block or completely randomized design, treatment means and standard errors
G04BCF Example Text Example Data | 17 | nagf_anova_rowcol Analysis of variance, general row and column design, treatment means and standard errors
G04CAF Example Text Example Data | 16 | nagf_anova_factorial Analysis of variance, complete factorial design, treatment means and standard errors
G04DAF Example Text Example Data | 17 | nagf_anova_contrasts Computes sum of squares for contrast between means
G04DBF Example Text Example Data | 17 | nagf_anova_confidence Computes confidence intervals for differences between means computed by G04BBF or G04BCF
G04EAF Example Text Example Data | 17 | nagf_anova_dummyvars Computes orthogonal polynomials or dummy variables for factor/classification variable
G04 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


G04DAF : NAG Library, Mark 26

G04 Chapter Contents
G04 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

G04DAF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

G04DAF computes sum of squares for a user-defined contrast between means.

2 Specification

SUBROUTINE G04DAF ( NT, TMEAN, IREP, RMS, RDF, NC, CT, LDCT, EST, TABL, LDTABL, TOL, USETX, TX, IFAIL)
INTEGER | NT, IREP(NT), NC, LDCT, LDTABL, IFAIL
REAL (KIND=nag_wp) | TMEAN(NT), RMS, RDF, CT(LDCT,NC), EST(NC), TABL(LDTABL,*), TOL, TX(NT)
LOGICAL | USETX

3 Description

In the analysis of designed experiments the first stage is to compute the basic analysis of variance table, the estimate of the error variance (the residual or error mean square), σ^2, and the (variance ratio) F-statistic for the t treatments. If this F-test is significant then the second stage of the analysis is to explore which treatments are significantly different.
If there is a structure to the treatments then this may lead to hypotheses that can be defined before the analysis and tested using linear contrasts. For example, if the treatments were three different fixed temperatures, say 18, 20 and 22, and an uncontrolled temperature (denoted by N) then the following contrasts might be of interest.
18 20 22 N a 13 13 13 -1 b -1 0 1 0
The first represents the average difference between the controlled temperatures and the uncontrolled temperature. The second represents the linear effect of an increasing fixed temperature.
For a randomized complete block design or a completely randomized design, let the treatment means be τ^i, i=1,2,…,t, and let the jth contrast be defined by λ ij, i=1,2,…,t, then the estimate of the contrast is simply:
Λj=∑i=1 t τ^iλ ij
and the sum of squares for the contrast is:
SSj=Λj 2 ∑i=1 t λ ij 2/ni (1)
where ni is the number of observations for the ith treatment. Such a contrast has one degree of freedom so that the appropriate F-statistic is SSj/σ^2.
The two contrasts λ ij and λ i j′ are orthogonal if ∑i=1 t λ ijλ i j′=0 and the contrast λ ij is orthogonal to the overall mean if ∑i=1 t λ ij=0. In practice these sums will be tested against a small quantity, ε. If each of a set of contrasts is orthogonal to the mean and they are all mutually orthogonal then the contrasts provide a partition of the treatment sum of squares into independent components. Hence the resulting F-tests are independent.
If the treatments come from a design in which treatments are not orthogonal to blocks then the sum of squares for a contrast is given by:
SSj=Λj Λj* ∑i=1 t λ ij 2/ni (2)
where
Λj*=∑i= 1 t τi*λ ij
with τi*, for i=1,2,…,t, being adjusted treatment means computed by first eliminating blocks then computing the treatment means from the block adjusted observations without taking into account the non-orthogonality between treatments and blocks. For further details see John (1987).

4 References

Cochran W G and Cox G M (1957) Experimental Designs Wiley
John J A (1987) Cyclic Designs Chapman and Hall
Winer B J (1970) Statistical Principles in Experimental Design McGraw–Hill

5 Arguments

1:   NT – INTEGERInput
On entry: t, the number of treatment means.
Constraint: NT≥2.
2:   TMEAN NT – REAL (KIND=nag_wp) arrayInput
On entry: the treatment means, τ^i, for i=1,2,…,t.
3:   IREP NT – INTEGER arrayInput
On entry: the replication for each treatment mean, ni, for i=1,2,…,t.
4:   RMS – REAL (KIND=nag_wp)Input
On entry: the residual mean square, σ^2.
Constraint: RMS>0.0.
5:   RDF – REAL (KIND=nag_wp)Input
On entry: the residual degrees of freedom.
Constraint: RDF≥1.0.
6:   NC – INTEGERInput
On entry: the number of contrasts.
Constraint: NC≥1.
7:   CT LDCTNC – REAL (KIND=nag_wp) arrayInput
On entry: the columns of CT must contain the NC contrasts, that is CT ij must contain λ ij, for i=1,2,…,t and j=1,2,…,NC.
8:   LDCT – INTEGERInput
On entry: the first dimension of the array CT as declared in the (sub)program from which G04DAF is called.
Constraint: LDCT≥NT.
9:   EST NC – REAL (KIND=nag_wp) arrayOutput
On exit: the estimates of the contrast, Λj, for j=1,2,…,NC.
10:   TABL LDTABL* – REAL (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array TABL must be at least 5.
On entry: the elements of TABL that are not referenced as described below remain unchanged.
On exit: the rows of the analysis of variance table for the contrasts. For each row column 1 contains the degrees of freedom, column 2 contains the sum of squares, column 3 contains the mean square, column 4 the F-statistic and column 5 the significance level for the contrast. Note that the degrees of freedom are always one and so the mean square equals the sum of squares.
11:   LDTABL – INTEGERInput
On entry: the first dimension of the array TABL as declared in the (sub)program from which G04DAF is called.
Constraint: LDTABL≥NC.
12:   TOL – REAL (KIND=nag_wp)Input
On entry: the tolerance, ε used to check if the contrasts are orthogonal and if they are orthogonal to the mean. If TOL≤0.0 the value machine precision is used.
13:   USETX – LOGICALInput
On entry: if USETX=.TRUE. the means τi* are provided in TX and the formula (2) is used instead of formula (1).
If USETX=.FALSE. formula (1) is used and TX is not referenced.
14:   TX NT – REAL (KIND=nag_wp) arrayInput
On entry: if USETX=.TRUE. TX must contain the means τi*, for i=1,2,…,t.
15:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, because for this routine the values of the output arguments may be useful even if IFAIL≠0 on exit, the recommended value is -1. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Note: G04DAF may return useful information for one or more of the following detected errors or warnings.
Errors or warnings detected by the routine:
IFAIL=1
On entry, | NC<1,
or | NT<2,
or | LDCT<NT,
or | LDTABL<NC,
or | RMS≤0.0,
or | RDF<1.0.
IFAIL=2
On entry, | a contrast is not orthogonal to the mean,
or | at least two contrasts are not orthogonal.
If IFAIL=2 full results are returned but they should be interpreted with care.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

The computations are stable.

8 Parallelism and Performance

G04DAF is not threaded in any implementation.

9 Further Comments

If the treatments have a factorial structure G04CAF should be used and if the treatments have no structure the means can be compared using G04DBF.

10 Example

The data is from a completely randomized experiment on potato scab with seven treatments representing amounts of sulphur applied, whether the application was in spring or autumn and a control treatment. The one-way anova is computed using G02BBF. Two contrasts are analysed, one comparing the control with use of sulphur, the other comparing spring with autumn application.

10.1 Program Text

Program Text (g04dafe.f90)

10.2 Program Data

Program Data (g04dafe.d)

10.3 Program Results

Program Results (g04dafe.r)

G04 Chapter Contents
G04 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


G04DBF : NAG Library, Mark 26

G04 Chapter Contents
G04 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

G04DBF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

G04DBF computes simultaneous confidence intervals for the differences between means. It is intended for use after G04BBF or G04BCF.

2 Specification

SUBROUTINE G04DBF ( TYP, NT, TMEAN, RDF, C, LDC, CLEVEL, CIL, CIU, ISIG, IFAIL)
INTEGER | NT, LDC, ISIG(NT*(NT-1)/2), IFAIL
REAL (KIND=nag_wp) | TMEAN(NT), RDF, C(LDC,NT), CLEVEL, CIL(NT*(NT-1)/2), CIU(NT*(NT-1)/2)
CHARACTER(1) | TYP

3 Description

In the computation of analysis of a designed experiment the first stage is to compute the basic analysis of variance table, the estimate of the error variance (the residual or error mean square), σ^2, the residual degrees of freedom, ν, and the (variance ratio) F-statistic for the t treatments. The second stage of the analysis is to compare the treatment means. If the treatments have no structure, for example the treatments are different varieties, rather than being structured, for example a set of different temperatures, then a multiple comparison procedure can be used.
A multiple comparison procedure looks at all possible pairs of means and either computes confidence intervals for the difference in means or performs a suitable test on the difference. If there are t treatments then there are t t-1/2 comparisons to be considered. In tests the type 1 error or significance level is the probability that the result is considered to be significant when there is no difference in the means. If the usual t-test is used with, say, a 6% significance level then the type 1 error for all k=t t-1/2 tests will be much higher. If the tests were independent then if each test is carried out at the 100 α percent level then the overall type 1 error would be α*=1-1-α k≃kα. In order to provide an overall protection the individual tests, or confidence intervals, would have to be carried out at a value of α such that α* is the required significance level, e.g., five percent.
The 100 1-α percent confidence interval for the difference in two treatment means, τ^i and τ^j is given by
τ^i-τ^j±T α,ν,t*se τ^i-τ^j,
where se denotes the standard error of the difference in means and T α,ν,t* is an appropriate percentage point from a distribution. There are several possible choices for T α,ν,t*. These are:
(a) | 12 q 1-α,ν,t, the studentized range statistic, see G01FMF. It is the appropriate statistic to compare the largest mean with the smallest mean. This is known as Tukey–Kramer method.
(b) | t α/k,ν, this is the Bonferroni method.
(c) | t α 0,ν, where α 0=1-1-α 1/k, this is known as the Dunn–Sidak method.
(d) | t α,ν, this is known as Fisher's LSD (least significant difference) method. It should only be used if the overall F-test is significant, the number of treatment comparisons is small and were planned before the analysis.
(e) | k-1 F 1-α,k-1,ν where F 1-α,k-1,ν is the deviate corresponding to a lower tail probability of 1-α from an F-distribution with k-1 and ν degrees of freedom. This is Scheffe's method.
In cases (b), (c) and (d), t α,ν denotes the α two tail significance level for the Student's t-distribution with ν degrees of freedom, see G01FBF.
The Scheffe method is the most conservative, followed closely by the Dunn–Sidak and Tukey–Kramer methods.
To compute a test for the difference between two means the statistic,
τ^i-τ^j se τ^i-τ^j
is compared with the appropriate value of T α,ν,t*.

4 References

Kotz S and Johnson N L (ed.) (1985a) Multiple range and associated test procedures Encyclopedia of Statistical Sciences 5 Wiley, New York
Kotz S and Johnson N L (ed.) (1985b) Multiple comparison Encyclopedia of Statistical Sciences 5 Wiley, New York
Winer B J (1970) Statistical Principles in Experimental Design McGraw–Hill

5 Arguments

1:   TYP – CHARACTER(1)Input
On entry: indicates which method is to be used.
TYP='T'
The Tukey–Kramer method is used.
TYP='B'
The Bonferroni method is used.
TYP='D'
The Dunn–Sidak method is used.
TYP='L'
The Fisher LSD method is used.
TYP='S'
The Scheffe's method is used.
Constraint: TYP='T', 'B', 'D', 'L' or 'S'.
2:   NT – INTEGERInput
On entry: t, the number of treatment means.
Constraint: NT≥2.
3:   TMEAN NT – REAL (KIND=nag_wp) arrayInput
On entry: the treatment means, τ^i, for i=1,2,…,t.
4:   RDF – REAL (KIND=nag_wp)Input
On entry: ν, the residual degrees of freedom.
Constraint: RDF≥1.0.
5:   C LDCNT – REAL (KIND=nag_wp) arrayInput
On entry: the strictly lower triangular part of C must contain the standard errors of the differences between the means as returned by G04BBF and G04BCF. That is C ij, i>j, contains the standard error of the difference between the ith and jth mean in TMEAN.
Constraint: C ij>0.0, for i=2,3,…,t and j=1,2,…,i-1.
6:   LDC – INTEGERInput
On entry: the first dimension of the array C as declared in the (sub)program from which G04DBF is called.
Constraint: LDC≥NT.
7:   CLEVEL – REAL (KIND=nag_wp)Input
On entry: the required confidence level for the computed intervals, (1-α).
Constraint: 0.0<CLEVEL<1.0.
8:   CIL NT×NT-1/2 – REAL (KIND=nag_wp) arrayOutput
On exit: the i-1i-2/2+j th element contains the lower limit to the confidence interval for the difference between ith and jth means in TMEAN, for i=2,3,…,t and j=1,2,…,i-1.
9:   CIU NT×NT-1/2 – REAL (KIND=nag_wp) arrayOutput
On exit: the i-1i-2/2+j th element contains the upper limit to the confidence interval for the difference between ith and jth means in TMEAN, for i=2,3,…,t and j=1,2,…,i-1.
10:   ISIG NT×NT-1/2 – INTEGER arrayOutput
On exit: the i-1i-2/2+j th element indicates if the difference between ith and jth means in TMEAN is significant, for i=2,3,…,t and j=1,2,…,i-1. If the difference is significant then the returned value is 1; otherwise the returned value is 0.
11:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, | NT<2,
or | LDC<NT,
or | RDF<1.0,
or | CLEVEL≤0.0,
or | CLEVEL≥1.0,
or | TYP≠'T', 'B', 'D', 'L' or 'S'.
IFAIL=2
On entry, C ij≤0.0 for some i,j, i=2,3,…,t and j=1,2,…,i-1.
IFAIL=3
There has been a failure in the computation of the studentized range statistic. This is an unlikely error. Try using a small value of CLEVEL.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

For the accuracy of the percentage point statistics see G01FBF and G01FMF.

8 Parallelism and Performance

G04DBF is not threaded in any implementation.

9 Further Comments

If the treatments have a structure then the use of linear contrasts as computed by G04DAF may be more appropriate.
An alternative approach to one used in G04DBF is the sequential testing of the Student–Newman–Keuls procedure. This, in effect, uses the Tukey–Kramer method but first ordering the treatment means and examining only subsets of the treatment means in which the largest and smallest are significantly different. At each stage the third argument of the Studentized range statistic is the number of means in the subset rather than the total number of means.

10 Example

In the example taken from Winer (1970) a completely randomized design with unequal treatment replication is analysed using G04BBF and then confidence intervals are computed by G04DBF using the Tukey–Kramer method.

10.1 Program Text

Program Text (g04dbfe.f90)

10.2 Program Data

Program Data (g04dbfe.d)

10.3 Program Results

Program Results (g04dbfe.r)

G04 Chapter Contents
G04 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


G04EAF : NAG Library, Mark 26

G04 Chapter Contents
G04 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

G04EAF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

G04EAF computes orthogonal polynomial or dummy variables for a factor or classification variable.

2 Specification

SUBROUTINE G04EAF ( TYP, N, LEVELS, IFACT, X, LDX, V, REP, IFAIL)
INTEGER | N, LEVELS, IFACT(N), LDX, IFAIL
REAL (KIND=nag_wp) | X(LDX,*), V(*), REP(LEVELS)
CHARACTER(1) | TYP

3 Description

In the analysis of an experimental design using a general linear model the factors or classification variables that specify the design have to be coded as dummy variables. G04EAF computes dummy variables that can then be used in the fitting of the general linear model using G02DAF.
If the factor of length n has k levels then the simplest representation is to define k dummy variables, Xj such that Xj=1 if the factor is at level j and 0 otherwise for j=1,2,…,k. However, there is usually a mean included in the model and the sum of the dummy variables will be aliased with the mean. To avoid the extra redundant argument k-1 dummy variables can be defined as the contrasts between one level of the factor, the reference level, and the remaining levels. If the reference level is the first level then the dummy variables can be defined as Xj=1 if the factor is at level j and 0 otherwise, for j=2,3,…,k. Alternatively, the last level can be used as the reference level.
A second way of defining the k-1 dummy variables is to use a Helmert matrix in which levels 2,3,…,k are compared with the average effect of the previous levels. For example if k=4 then the contrasts would be:
1 -1 -1 -1 2 1 -1 -1 3 0 2 -1 4 0 0 3
Thus variable j, for j=1,2,…,k-1 is given by
  • Xj=-1 if factor is at level less than j+1
  • Xj=∑i=1 j ri/r j+1 if factor is at level j+1
  • Xj=0 if factor is at level greater than j+1
where rj is the number of replicates of level j.
If the factor can be considered as a set of values from an underlying continuous variable then the factor can be represented by a set of k-1 orthogonal polynomials representing the linear, quadratic etc. effects of the underlying variable. The orthogonal polynomial is computed using Forsythe's algorithm (Forsythe (1957), see also Cooper (1968)). The values of the underlying continuous variable represented by the factor levels have to be supplied to the routine.
The orthogonal polynomials are standardized so that the sum of squares for each dummy variable is one. For the other methods integer (±1) representations are retained except that in the Helmert representation the code of level j+1 in dummy variable j will be a fraction.

4 References

Cooper B E (1968) Algorithm AS 10. The use of orthogonal polynomials Appl. Statist. 17 283–287
Forsythe G E (1957) Generation and use of orthogonal polynomials for data fitting with a digital computer J. Soc. Indust. Appl. Math. 5 74–88

5 Arguments

1:   TYP – CHARACTER(1)Input
On entry: the type of dummy variable to be computed.
  • If TYP='P', an orthogonal Polynomial representation is computed.
  • If TYP='H', a Helmert matrix representation is computed.
  • If TYP='F', the contrasts relative to the First level are computed.
  • If TYP='L', the contrasts relative to the Last level are computed.
  • If TYP='C', a Complete set of dummy variables is computed.
Constraint: TYP='P', 'H', 'F', 'L' or 'C'.
2:   N – INTEGERInput
On entry: n, the number of observations for which the dummy variables are to be computed.
Constraint: N≥LEVELS.
3:   LEVELS – INTEGERInput
On entry: k, the number of levels of the factor.
Constraint: LEVELS≥2.
4:   IFACT N – INTEGER arrayInput
On entry: the n values of the factor.
Constraint: 1≤IFACT i≤LEVELS, for i=1,2,…,n.
5:   X LDX* – REAL (KIND=nag_wp) arrayOutput
Note: the second dimension of the array X must be at least LEVELS-1 if TYP='P', 'H', 'F' or 'L' and at least LEVELS if TYP='C'.
On exit: the n by k* matrix of dummy variables, where k*=k-1 if TYP='P', 'H', 'F' or 'L' and k*=k if TYP='C'.
6:   LDX – INTEGERInput
On entry: the first dimension of the array X as declared in the (sub)program from which G04EAF is called.
Constraint: LDX≥N.
7:   V* – REAL (KIND=nag_wp) arrayInput
Note: the dimension of the array V must be at least LEVELS if TYP='P', and at least 1 otherwise.
On entry: if TYP='P', the k distinct values of the underlying variable for which the orthogonal polynomial is to be computed.
If TYP≠'P', V is not referenced.
Constraint: if TYP='P', the k values of V must be distinct.
8:   REP LEVELS – REAL (KIND=nag_wp) arrayOutput
On exit: the number of replications for each level of the factor, ri, for i=1,2,…,k.
9:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, | LEVELS<2,
or | N<LEVELS,
or | LDX<N,
or | TYP≠'P', 'H', 'F', 'L' or 'C'.
IFAIL=2
On entry, | a value of IFACT is not in the range 1≤IFACT i≤LEVELS, for i=1,2,…,n,
or | TYP='P' and not all values of V are distinct,
or | not all levels are represented in IFACT.
IFAIL=3
An orthogonal polynomial has all values zero. This will be due to some values of V being very close together. Note this can only occur if TYP='P'.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

The computations are stable.

8 Parallelism and Performance

G04EAF is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
G04EAF makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

Other routines for fitting polynomials can be found in Chapter E02.

10 Example

Data are read in from an experiment with four treatments and three observations per treatment with the treatment coded as a factor. G04EAF is used to compute the required dummy variables and the model is then fitted by G02DAF.

10.1 Program Text

Program Text (g04eafe.f90)

10.2 Program Data

Program Data (g04eafe.d)

10.3 Program Results

Program Results (g04eafe.r)

G04 Chapter Contents
G04 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


G04 Chapter Introduction : NAG Library, Mark 26

G04 Chapter Contents
NAG Library Manual

NAG Library Chapter Introduction

G04 – Analysis of Variance

▸▿ Contents

1 Scope of the Chapter
▸▿ 2 Background to the Problems
2.1 Experimental Designs
2.2 Analysis of Variance
3 Recommendations on Choice and Use of Available Routines
4 Functionality Index
5 Auxiliary Routines Associated with Library Routine Arguments
6 Routines Withdrawn or Scheduled for Withdrawal
7 References

1 Scope of the Chapter

This chapter is concerned with methods for analysing the results of designed experiments. The range of experiments covered include:
  • single factor designs with equal sized blocks such as randomized complete block and balanced incomplete block designs,
  • row and column designs such as Latin squares, and
  • complete factorial designs.
Further designs may be analysed by combining the analyses provided by multiple calls to routines or by using general linear model routines provided in Chapter G02.

2 Background to the Problems

2.1 Experimental Designs

An experimental design consists of a plan for allocating a set of controlled conditions, the treatments, to subsets of the experimental material, the plots or units. Two examples are:
(i) | In an experiment to examine the effects of different diets on the growth of chickens, the chickens were kept in pens and a different diet was fed to the birds in each pen. In this example the pens are the units and the different diets are the treatments.
(ii) | In an experiment to compare four materials for wear-loss, a sample from each of the materials is tested in a machine that simulates wear. The machine can take four samples at a time and a number of runs are made. In this experiment the treatments are the materials and the units are the samples from the materials.
In designing an experiment the following principles are important.
(a) | Randomization: given the overall plan of the experiment, the final allocation of treatments to units is performed using a suitable random allocation. This avoids the possibility of a systematic bias in the allocation and gives a basis for the statistical analysis of the experiment.
(b) | Replication: each treatment should be ‘observed’ more than once. So in example (b) more than one sample from each material should be tested. Replication allows for an estimate of the variability of the treatment effect to be measured.
(c) | Blocking: in many situations the experimental material will not be homogeneous and there may be some form of systematic variation in the experimental material. In order to reduce the effect of systematic variation the material can be grouped into blocks so that units within a block are similar but there is variation between blocks. For example, in an animal experiment litters may be considered as blocks; in an industrial experiment it may be material from one production batch.
(d) | Factorial designs: if more than one type of treatment is under consideration, for example the effect of changes in temperature and changes in pressure, a factorial design consists of looking at all combinations of temperature and pressure. The different types of treatment are known as factors and the different values of the factors that are considered in the experiment are known as levels. So if three temperatures and four different pressures were being considered, then factor 1 (temperature) would have 3 levels and factor 2 (pressure) would have four levels and the design would be a 3×4 factorial giving a total of 12 treatment combinations. This design has the advantage of being able to detect the interaction between factors, that is, the effect of the combination of factors.
The following are examples of standard experimental designs; in the descriptions, it is assumed that there are t treatments.
(a) | Completely Randomised Design: there are no blocks and the treatments are allocated to units at random.
(b) | Randomised Complete Block Design: the experimental units are grouped into b blocks of t units and each treatment occurs once in each block. The treatments are allocated to units within blocks at random.
(c) | Latin Square Designs: the units can be represented as cells of a t by t square classified by rows and columns. The t rows and t columns represent sources of variation in the experimental material. The design allocates the treatments to the units so that each treatment occurs once in each row and each column.
(d) | Balanced Incomplete Block Designs: the experimental units are grouped into b blocks of k<t units. The treatments are allocated so that each treatment is replicated the same number of times and each treatment occurs in the same block with any other treatment the same number of times. The treatments are allocated to units within blocks at random.
(e) | Complete Factorial Experiments: if there are t treatment combinations derived from the levels of all factors then either there are no blocks or the blocks are of size t units.
Other designs include: partially balanced incomplete block designs, split-plot designs, factorial designs with confounding, and fractional factorial designs. For further information on these designs, see Cochran and Cox (1957), Davis (1978) or John and Quenouille (1977).

2.2 Analysis of Variance

The analysis of a designed experiment usually consists of two stages. The first is the computation of the estimate of variance of the underlying random variation in the experiment along with tests for the overall effect of treatments. This results in an analysis of variance (ANOVA) table. The second stage is a more detailed examination of the effect of different treatments either by comparing the difference in treatment means with an appropriate standard error or by the use of orthogonal contrasts.
The analysis assumes a linear model such as
y ij=μ+δi+τl+e ij,
where y ij is the observed value for unit j of block i, μ is the overall mean, δi is the effect of the ith block, τl is the effect of the lth treatment which has been applied to the unit, and e ij is the random error term associated with this unit. The expected value of e ij is zero and its variance is σ 2.
In the analysis of variance, the total variation, measured by the sum of squares of observations about the overall mean, is partitioned into the sum of squares due to blocks, the sum of squares due to treatments, and a residual or error sum of squares. This partition corresponds to the parameters β, τ and σ. In parallel to the partition of the sum of squares there is a partition of the degrees of freedom associated with the sums of squares. The total degrees of freedom is n-1, where n is the number of observations. This is partitioned into b-1 degrees of freedom for blocks, t-1 degrees of freedom for treatments, and n-t-b+1 degrees of freedom for the residual sum of squares. From these the mean squares can be computed as the sums of squares divided by their degrees of freedom. The residual mean square is an estimate of σ 2. An F-test for an overall effect of the treatments can be calculated as the ratio of the treatment mean square to the residual mean square.
For row and column designs the model is
y ij=μ+ρi+γj+τl+e ij,
where ρi is the effect of the ith row and γj is the effect of the jth column. Usually the rows and columns are orthogonal. In the analysis of variance the total variation is partitioned into rows, columns treatments and residual.
In the case of factorial experiments, the treatment sum of squares and degrees of freedom may be partitioned into main effects for the factors and interactions between factors. The main effect of a factor is the effect of the factor averaged over all other factors. The interaction between two factors is the additional effect of the combination of the two factors, over and above the additive effects of the two factors, averaged over all other factors. For a factorial experiment in blocks with two factors, A and B, in which the jth unit of the ith block received level l of factor A and level k of factor B the model is
y ij=μ+δi+αl+βk+α β lk+e ij,
where αl is the main effect of level l of factor a, βk is the main effect of level k of factor B, and α β lk is the interaction between level l of A and level k of B. Higher-order interactions can be defined in a similar way.
Once the significant treatment effects have been uncovered they can be further investigated by comparing the differences between the means with the appropriate standard error. Some of the assumptions of the analysis can be checked by examining the residuals.

3 Recommendations on Choice and Use of Available Routines

This chapter contains routines that can handle a wide range of experimental designs plus routines for further analysis and a routine to compute dummy variables for use in a general linear model.
G04BBF computes the analysis of variance and treatment means with standard errors for any block design with equal sized blocks. The routine will handle both complete block designs and balanced and partially balanced incomplete block designs.
G04BCF computes the analysis of variance and treatment means with standard errors for a row and column designs such as a Latin square.
G04CAF computes the analysis of variance and treatment means with standard errors for a complete factorial experiment.
Other designs can be analysed by combinations of calls to G04BBF, G04BCF and G04CAF. The routines compute the residuals from the model specified by the design, so these can then be input as the response variable in a second call to one of the routines. For example a factorial experiment in a Latin square design can be analysed by first calling G04BCF to remove the row and column effects and then calling G04CAF with the residuals from G04BCF as the response variable to compute the ANOVA for the treatments. Another example would be to use both G02DAF and G04BBF to compute an analysis of covariance.
For experiments with missing values, these values can be estimated by using the Healy and Westmacott procedure; see John and Quenouille (1977). This procedure involves starting with initial estimates for the missing values and then making adjustments based on the residuals from the analysis. The improved estimates are then used in further iterations of the process.
For designs that cannot be analysed by the above approach the routine G04EAF can be used to compute dummy variables from the classification variables or factors that define the design. These dummy variables can then be used with the general linear model routine G02DAF.
As well as the routines considered above the routine G04AGF computes the analysis of variance for a two strata nested design.
In addition to the routines for computing the means and the basic analysis of variance two routines are available for further analysis.
G04DAF computes the sum of squares for a user-defined contrast between means. For example, if there are four treatments, the first is a control and the other three are different amounts of a chemical the contrasts that are the difference between no chemical and chemical and the linear effect of chemical could be defined. G04DAF could be used to compute the sums of squares for these contrasts from which the appropriate F-tests could be computed.
G04DBF computes simultaneous confidence intervals for the differences between means with the choice of different methods such as the Tukey–Kramer, Bonferron and Dunn–Sidak.

4 Functionality Index

Analysis of variance for,
complete factorial design G04CAF
general block design or completely randomized design G04BBF
general block design or completely randomized design,
row and column design G04BCF
two-way hierarchical classification, subgroups of unequal size G04AGF
General linear model,
generate dummy variables and orthogonal polynomials G04EAF
Inferences on means,
simultaneous confidence intervals G04DBF
sum of squares for contrast between means G04DAF

5 Auxiliary Routines Associated with Library Routine Arguments

None.

6 Routines Withdrawn or Scheduled for Withdrawal

None.

7 References

Cochran W G and Cox G M (1957) Experimental Designs Wiley
Davis O L (1978) The Design and Analysis of Industrial Experiments Longman
John J A (1987) Cyclic Designs Chapman and Hall
John J A and Quenouille M H (1977) Experiments: Design and Analysis Griffin
Searle S R (1971) Linear Models Wiley
G04 Chapter Contents
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


G05 Chapter Contents : NAG Library Manual, Mark 26

G05 Chapter Introduction
NAG Library Manual

NAG Library Chapter Contents

G05 – Random Number Generators

G05 Chapter Introduction – a description of the Chapter and an overview of the algorithms available

Routine Name | Mark of Introduction | Purpose
G05KFF Example Text Example Data | 22 | nagf_rand_init_repeat Initializes a pseudorandom number generator to give a repeatable sequence
G05KGF Example Text | 22 | nagf_rand_init_nonrepeat Initializes a pseudorandom number generator to give a non-repeatable sequence
G05KHF Example Text Example Data | 22 | nagf_rand_init_leapfrog Primes a pseudorandom number generator for generating multiple streams using leap-frog
G05KJF Example Text Example Data | 22 | nagf_rand_init_skipahead Primes a pseudorandom number generator for generating multiple streams using skip-ahead
G05KKF Example Text Example Data | 23 | nagf_rand_init_skipahead_power2 Primes a pseudorandom number generator for generating multiple streams using skip-ahead, skipping ahead a power of 2
G05NCF Example Text Example Data | 22 | nagf_rand_permute Pseudorandom permutation of an integer vector
G05NDF Example Text Example Data | 22 | nagf_rand_sample Pseudorandom sample from an integer vector
G05NEF Example Text Example Data | 23 | nagf_rand_sample_wgt Pseudorandom sample, without replacement, unequal weights
G05PDF Example Text Example Data | 22 | nagf_rand_times_garch_asym1 Generates a realization of a time series from a GARCH process with asymmetry of the form ε t-1+γ 2
G05PEF Example Text Example Data | 22 | nagf_rand_times_garch_asym2 Generates a realization of a time series from a GARCH process with asymmetry of the form ε t-1+γ ε t-1 2
G05PFF Example Text Example Data | 22 | nagf_rand_times_garch_GJR Generates a realization of a time series from an asymmetric Glosten, Jagannathan and Runkle (GJR) GARCH process
G05PGF Example Text Example Data | 22 | nagf_rand_times_garch_exp Generates a realization of a time series from an exponential GARCH (EGARCH) process
G05PHF Example Text Example Data | 22 | nagf_rand_times_arma Generates a realization of a time series from an ARMA model
G05PJF Example Text Example Data | 22 | nagf_rand_times_mv_varma Generates a realization of a multivariate time series from a VARMA model
G05PMF Example Text Example Data Example Plot | 22 | nagf_rand_times_smooth_exp Generates a realization of a time series from an exponential smoothing model
G05PVF Example Text Example Data | 25 | nagf_rand_kfold_xyw Permutes a matrix, vector, vector triplet into a form suitable for K-fold cross validation
G05PWF Example Text Example Data | 25 | nagf_rand_subsamp_xyw Permutes a matrix, vector, vector triplet into a form suitable for random sub-sampling validation
G05PXF Example Text Example Data | 22 | nagf_rand_matrix_orthog Generates a random orthogonal matrix
G05PYF Example Text Example Data | 22 | nagf_rand_matrix_corr Generates a random correlation matrix
G05PZF Example Text Example Data | 22 | nagf_rand_matrix_2waytable Generates a random two-way table
G05RCF Example Text Example Data | 22 | nagf_rand_copula_students_t Generates a matrix of pseudorandom numbers from a Student's t-copula
G05RDF Example Text Example Data | 22 | nagf_rand_copula_normal Generates a matrix of pseudorandom numbers from a Gaussian copula
G05REF Example Text Example Data | 23 | nagf_rand_copula_clayton_bivar Generates a matrix of pseudorandom numbers from a bivariate Clayton/Cook–Johnson copula
G05RFF Example Text Example Data | 23 | nagf_rand_copula_frank_bivar Generates a matrix of pseudorandom numbers from a bivariate Frank copula
G05RGF Example Text Example Data | 23 | nagf_rand_copula_plackett_bivar Generates a matrix of pseudorandom numbers from a bivariate Plackett copula
G05RHF Example Text Example Data | 23 | nagf_rand_copula_clayton Generates a matrix of pseudorandom numbers from a multivariate Clayton/Cook–Johnson copula
G05RJF Example Text Example Data | 23 | nagf_rand_copula_frank Generates a matrix of pseudorandom numbers from a multivariate Frank copula
G05RKF Example Text Example Data | 23 | nagf_rand_copula_gumbel Generates a matrix of pseudorandom numbers from a Gumbel–Hougaard copula
G05RYF Example Text Example Data | 22 | nagf_rand_multivar_students_t Generates a matrix of pseudorandom numbers from a multivariate Student's t-distribution
G05RZF Example Text Example Data | 22 | nagf_rand_multivar_normal Generates a matrix of pseudorandom numbers from a multivariate Normal distribution
G05SAF Example Text Example Data | 22 | nagf_rand_dist_uniform01 Generates a vector of pseudorandom numbers from a uniform distribution over 0,1
G05SBF Example Text Example Data | 22 | nagf_rand_dist_beta Generates a vector of pseudorandom numbers from a beta distribution
G05SCF Example Text Example Data | 22 | nagf_rand_dist_cauchy Generates a vector of pseudorandom numbers from a Cauchy distribution
G05SDF Example Text Example Data | 22 | nagf_rand_dist_chisq Generates a vector of pseudorandom numbers from a χ 2 distribution
G05SEF Example Text Example Data | 22 | nagf_rand_dist_dirichlet Generates a vector of pseudorandom numbers from a Dirichlet distribution
G05SFF Example Text Example Data | 22 | nagf_rand_dist_exp Generates a vector of pseudorandom numbers from an exponential distribution
G05SGF Example Text Example Data | 22 | nagf_rand_dist_expmix Generates a vector of pseudorandom numbers from an exponential mix distribution
G05SHF Example Text Example Data | 22 | nagf_rand_dist_f Generates a vector of pseudorandom numbers from an F-distribution
G05SJF Example Text Example Data | 22 | nagf_rand_dist_gamma Generates a vector of pseudorandom numbers from a gamma distribution
G05SKF Example Text Example Data | 22 | nagf_rand_dist_normal Generates a vector of pseudorandom numbers from a Normal distribution
G05SLF Example Text Example Data | 22 | nagf_rand_dist_logistic Generates a vector of pseudorandom numbers from a logistic distribution
G05SMF Example Text Example Data | 22 | nagf_rand_dist_lognormal Generates a vector of pseudorandom numbers from a log-normal distribution
G05SNF Example Text Example Data | 22 | nagf_rand_dist_students_t Generates a vector of pseudorandom numbers from a Student's t-distribution
G05SPF Example Text Example Data | 22 | nagf_rand_dist_triangular Generates a vector of pseudorandom numbers from a triangular distribution
G05SQF Example Text Example Data | 22 | nagf_rand_dist_uniform Generates a vector of pseudorandom numbers from a uniform distribution over a,b
G05SRF Example Text Example Data | 22 | nagf_rand_dist_vonmises Generates a vector of pseudorandom numbers from a von Mises distribution
G05SSF Example Text Example Data | 22 | nagf_rand_dist_weibull Generates a vector of pseudorandom numbers from a Weibull distribution
G05TAF Example Text Example Data | 22 | nagf_rand_int_binomial Generates a vector of pseudorandom integers from a binomial distribution
G05TBF Example Text Example Data | 22 | nagf_rand_logical Generates a vector of pseudorandom logical values
G05TCF Example Text Example Data | 22 | nagf_rand_int_geom Generates a vector of pseudorandom integers from a geometric distribution
G05TDF Example Text Example Data | 22 | nagf_rand_int_general Generates a vector of pseudorandom integers from a general discrete distribution
G05TEF Example Text Example Data | 22 | nagf_rand_int_hypergeom Generates a vector of pseudorandom integers from a hypergeometric distribution
G05TFF Example Text Example Data | 22 | nagf_rand_int_log Generates a vector of pseudorandom integers from a logarithmic distribution
G05TGF Example Text Example Data | 22 | nagf_rand_int_multinomial Generates a vector of pseudorandom integers from a multinomial distribution
G05THF Example Text Example Data | 22 | nagf_rand_int_negbin Generates a vector of pseudorandom integers from a negative binomial distribution
G05TJF Example Text Example Data | 22 | nagf_rand_int_poisson Generates a vector of pseudorandom integers from a Poisson distribution
G05TKF Example Text Example Data | 22 | nagf_rand_int_poisson_varmean Generates a vector of pseudorandom integers from a Poisson distribution with varying mean
G05TLF Example Text Example Data | 22 | nagf_rand_int_uniform Generates a vector of pseudorandom integers from a uniform distribution
G05XAF Example Text | 24 | nagf_rand_bb_init Initializes the Brownian bridge generator
G05XBF Example Text | 24 | nagf_rand_bb Generate paths for a free or non-free Wiener process using the Brownian bridge algorithm
G05XCF Example Text | 24 | nagf_rand_bb_inc_init Initializes the generator which backs out the increments of sample paths generated by a Brownian bridge algorithm
G05XDF Example Text | 24 | nagf_rand_bb_inc Backs out the increments from sample paths generated by a Brownian bridge algorithm
G05XEF Example Text | 24 | nagf_rand_bb_make_bridge_order Creates a Brownian bridge construction order out of a set of input times
G05YJF Example Text Example Data | 21 | nagf_rand_quasi_normal Generates a Normal quasi-random number sequence
G05YKF Example Text Example Data | 21 | nagf_rand_quasi_lognormal Generates a log-normal quasi-random number sequence
G05YLF | 22 | nagf_rand_quasi_init Initializes a quasi-random number generator
G05YMF Example Text Example Data | 22 | nagf_rand_quasi_uniform Generates a uniform quasi-random number sequence
G05YNF Example Text Example Data | 22 | nagf_rand_quasi_init_scrambled Initializes a scrambled quasi-random number generator
G05ZMF Example Text Example Data | 24 | nagf_rand_field_1d_user_setup Setup for simulating one-dimensional random fields, user-defined variogram
G05ZNF Example Text Example Data | 24 | nagf_rand_field_1d_predef_setup Setup for simulating one-dimensional random fields
G05ZPF Example Text Example Data | 24 | nagf_rand_field_1d_generate Generates realizations of a one-dimensional random field
G05ZQF Example Text Example Data | 24 | nagf_rand_field_2d_user_setup Setup for simulating two-dimensional random fields, user-defined variogram
G05ZRF Example Text Example Data Example Plot | 24 | nagf_rand_field_2d_predef_setup Setup for simulating two-dimensional random fields, preset variogram
G05ZSF Example Text Example Data | 24 | nagf_rand_field_2d_generate Generates realizations of a two-dimensional random field
G05ZTF Example Text Example Data | 24 | nagf_rand_field_fracbm_generate Generates realizations of fractional Brownian motion
G05 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


G05 Chapter Introduction : NAG Library, Mark 26

G05 Chapter Contents
NAG Library Manual

NAG Library Chapter Introduction

G05 – Random Number Generators

▸▿ Contents

1 Scope of the Chapter
▸▿ 2 Background to the Problems
▸▿ 2.1 Pseudorandom Numbers
2.1.1 NAG Basic Generator
2.1.2 Wichmann–Hill I Generator
2.1.3 Wichmann–Hill II Generator
2.1.4 Mersenne Twister Generator
2.1.5 ACORN Generator
2.1.6 L'Ecuyer MRG32k3a Combined Recursive Generator
2.2 Quasi-random Numbers
2.3 Scrambled Quasi-random Numbers
2.4 Non-uniform Random Numbers
2.5 Copulas
▸▿ 2.6 Brownian Bridge
2.6.1 Brownian Bridge Process
2.6.2 Brownian Bridge Algorithm
2.6.3 Bridge Construction Order and Quasi-random Sequences
2.6.4 Brownian Bridge and Stochastic Differential Equations
2.7 Random Fields
2.8 Sampling
2.9 Sampling Based Validation
2.10 Other Random Structures
▸▿ 2.11 Multiple Streams of Pseudorandom Numbers
2.11.1 Multiple Streams via Different Initial Values (Seeds)
2.11.2 Multiple Streams via Different Generators
2.11.3 Multiple Streams via Skip-ahead
2.11.4 Multiple Streams via Leap-frog
2.11.5 Skip-ahead and Leap-frog for a Linear Congruential Generator (LCG): An Example
2.11.6 Skip-ahead and Leap-frog for the Mersenne Twister: An Example
▸▿ 3 Recommendations on Choice and Use of Available Routines
▸▿ 3.1 Pseudorandom Numbers
3.1.1 Initialization
3.1.2 Repeated initialization
3.1.3 Choice of Base Generator
3.1.4 Choice of Method for Generating Multiple Streams
3.1.5 Copulas
3.2 Quasi-random Numbers
3.3 Brownian Bridge
3.4 Random Fields
3.5 Sampling
4 Functionality Index
5 Auxiliary Routines Associated with Library Routine Arguments
6 Routines Withdrawn or Scheduled for Withdrawal
7 References

1 Scope of the Chapter

This chapter is concerned with the generation of sequences of independent pseudorandom and quasi-random numbers from various distributions, and models.

2 Background to the Problems

2.1 Pseudorandom Numbers

A sequence of pseudorandom numbers is a sequence of numbers generated in some systematic way such that they are independent and statistically indistinguishable from a truly random sequence. A pseudorandom number generator (PRNG) is a mathematical algorithm that, given an initial state, produces a sequence of pseudorandom numbers. A PRNG has several advantages over a true random number generator in that the generated sequence is repeatable, has known mathematical properties and can be implemented without needing any specialist hardware. Many books on statistics and computer science have good introductions to PRNGs, for example Knuth (1981) or Banks (1998).
PRNGs can be split into base generators, and distributional generators. Within the context of this document a base generator is defined as a PRNG that produces a sequence (or stream) of variates (or values) uniformly distributed over the interval 0,1. Depending on the algorithm being considered, this interval may be open, closed or half-closed. A distribution generator is a routine that takes variates generated from a base generator and transforms them into variates from a specified distribution, for example a uniform, Gaussian (Normal) or gamma distribution.
The period (or cycle length) of a base generator is defined as the maximum number of values that can be generated before the sequence starts to repeat. The initial state of the base generator is often called the seed.
There are six base generators currently available in the NAG Library, these are; a basic linear congruential generator (LCG) (referred to as the NAG basic generator) (see Knuth (1981)), two sets of Wichmann–Hill generators (see Maclaren (1989) and Wichmann and Hill (2006)), the Mersenne Twister (see Matsumoto and Nishimura (1998)), the ACORN generator (see Wikramaratna (1989)) and L'Ecuyer generator (see L'Ecuyer and Simard (2002)).

2.1.1 NAG Basic Generator

The NAG basic generator is a linear congruential generator (LCG) and, like all linear congruential generators, has the form:
xi = a 1 x i-1 mod m 1 , ui = xi m 1 ,
where the ui, for i=1,2,…, form the required sequence.
The NAG basic generator uses a 1=1313 and m 1=259, which gives a period of approximately 257.
This generator has been part of the NAG Library since Mark 6 and as such has been widely used. It suffers from no known problems, other than those due to the lattice structure inherent in all linear congruential generators, and, even though the period is relatively short compared to many of the newer generators, it is sufficiently large for many practical problems.
The performance of the NAG basic generator has been analysed by the Spectral Test, see Section 3.3.4 of Knuth (1981), yielding the following results in the notation of Knuth (1981).
n | νn | Upper bound for νn
2 | 3.44×108 | 4.08×108
3 | 4.29×105 | 5.88×105
4 | 1.72×104 | 2.32×104
5 | 1.92×103 | 3.33×103
6 | 593 | 939
7 | 198 | 380
8 | 108 | 197
9 | 67 | 120
The right-hand column gives an upper bound for the values of νn attainable by any multiplicative congruential generator working modulo 259.
An informal interpretation of the quantities νn is that consecutive n-tuples are statistically uncorrelated to an accuracy of 1/νn. This is a theoretical result; in practice the degree of randomness is usually much greater than the above figures might support. More details are given in Knuth (1981), and in the references cited therein.
Note that the achievable accuracy drops rapidly as the number of dimensions increases. This is a property of all multiplicative congruential generators and is the reason why very long periods are needed even for samples of only a few random numbers.

2.1.2 Wichmann–Hill I Generator

This series of Wichmann–Hill base generators (see Maclaren (1989)) use a combination of four linear congruential generators and has the form:
wi=a 1w i-1 mod m 1 xi=a 2x i-1 mod m 2 yi=a 3y i-1 mod m 3 zi=a 4z i-1 mod m 4 ui = wi m 1 + xi m 2 + yi m 3 + zi m 4 mod 1 , (1)
where the ui, for i=1,2,…, form the required sequence. The NAG Library implementation includes 273 sets of parameters, aj,mj, for j=1,2,3,4, to choose from.
The constants ai are in the range 112 to 127 and the constants mj are prime numbers in the range 16718909 to 16776971, which are close to 224=16777216. These constants have been chosen so that each of the resulting 273 generators are essentially independent, all calculations can be carried out in 32-bit integer arithmetic and the generators give good results with the spectral test, see Knuth (1981) and Maclaren (1989). The period of each of these generators would be at least 292 if it were not for common factors between m 1-1, m 2-1, m 3-1 and m 4-1. However, each generator should still have a period of at least 280. Further discussion of the properties of these generators is given in Maclaren (1989).

2.1.3 Wichmann–Hill II Generator

This Wichmann–Hill base generator (see Wichmann and Hill (2006)) is of the same form as that described in Section 2.1.2, i.e., a combination of four linear congruential generators. In this case a 1=11600, m 1=2147483579, a 2=47003, m 2=2147483543, a 3=23000, m 3=2147483423, a 4=33000, m 4=2147483123.
Unlike in the original Wichmann–Hill generator, these values are too large to carry out the calculations detailed in (1) using 32-bit integer arithmetic, however, if
wi = 11600 w i-1 mod 2147483579
then setting
Wi = 11600 w i-1 mod 185127 - 10379 w i-1 / 185127
gives
wi = Wi ​ if ​ Wi≥0 2147483579+Wi ​ otherwise
and Wi can be calculated in 32-bit integer arithmetic. Similar expressions exist for xi, yi and zi. The period of this generator is approximately 2121.
Further details of implementing this algorithm and its properties are given in Wichmann and Hill (2006). This paper also gives some useful guidelines on testing PRNGs.

2.1.4 Mersenne Twister Generator

The Mersenne Twister (see Matsumoto and Nishimura (1998)) is a twisted generalized feedback shift register generator. The algorithm underlying the Mersenne Twister is as follows:
(i) Set some arbitrary initial values x 1,x 2,…,xr, each consisting of w bits.
(ii) Letting
A= 0 I w-1 aw a w-1⋯a 1 ,
where I w-1 is the w-1×w-1 identity matrix and each of the ai,i=1 to w take a value of either 0 or 1 (i.e., they can be represented as bits). Define
x i+r = x i+s ⊕ x i ω : l+1 | x i+1 l:1 A ,
where x i ω : l+1 | x i+1 l:1 indicates the concatenation of the most significant (upper) w-l bits of xi and the least significant (lower) l bits of x i+1.
(iii) Perform the following operations sequentially:
z = x i+r ⊕ x i+r ≫ t 1 z = z ⊕ z ≪ t 2 ​ AND ​ m 1 z = z ⊕ z ≪ t 3 ​ AND ​ m 2 z = z ⊕ z ≫ t 4 u i+r = z/ 2 w - 1 ,
where t 1, t 2, t 3 and t 4 are integers and m 1 and m 2 are bit-masks and ‘≫t’ and ‘≪t’ represent a t bit shift right and left respectively, ⊕ is bit-wise exclusively or (xor) operation and ‘AND’ is a bit-wise and operation.
The u i+r, for i=1,2,…, form the required sequence. The supplied implementation of the Mersenne Twister uses the following values for the algorithmic constants:
w = 32 a = 0x9908b0 df l = 31 r = 624 s = 397 t 1 = 11 t 2 = 7 t 3 = 15 t 4 = 18 m 1 = 0x9d2c5680 m 2 = 0xefc60000
where the notation 0xDD … indicates the bit pattern of the integer whose hexadecimal representation is DD ….
This algorithm has a period length of approximately 219,937-1 and has been shown to be uniformly distributed in 623 dimensions (see Matsumoto and Nishimura (1998)).

2.1.5 ACORN Generator

The ACORN generator is a special case of a multiple recursive generator (see Wikramaratna (1989) and Wikramaratna (2007)). The algorithm underlying ACORN is as follows:
(i) | Choose an integer value k≥1.
(ii) | Choose an integer value M, and an integer seed Y 0 0, such that 0<Y 0 0<M and Y 0 0 and M are relatively prime.
(iii) | Choose an arbitrary set of k initial integer values, Y 0 1,Y 0 2,…,Y 0 k, such that 0≤ Y 0 m<M, for all m=1,2,…,k.
(iv) Perform the following sequentially:
Y i m = Y i m-1 + Y i-1 m mod M
for m=1,2,…,k.
(v) | Set ui=Yi k/M.
The ui, for i=1,2,…, then form a pseudorandom sequence, with ui ∈0,1, for all i.
Although you can choose any value for k, M, Y 0 0 and the Y 0 m, within the constraints mentioned in (i) to (iii) above, it is recommended that k≥10, M is chosen to be a large power of two with M≥260 and Y 0 0 is chosen to be odd.
The period of the ACORN generator, with the modulus M equal to a power of two, and an odd value for Y 0 0 has been shown to be an integer multiple of M (see Wikramaratna (1992)). Therefore, increasing M will give a series with a longer period.

2.1.6 L'Ecuyer MRG32k3a Combined Recursive Generator

The base generator L'Ecuyer MRG32k3a (see L'Ecuyer and Simard (2002)) combines two multiple recursive generators:
xi = a 11 x i-1 + a 12 x i-2 + a 13 x i-3 mod m 1 yi = a 21 y i-1 + a 22 y i-2 + a 23 y i-3 mod m 2 zi = xi - yi mod m 1 ui = zi + 1 / d
where a 11 = 0 , a 12 = 1403580 , a 13 = -810728 , m 1 = 232-209 , a 21 = 527612 , a 22 = 0 , a 23 = -1370589 , m 2 = 232-22853 , and ui , i = 1 , 2 ,… form the required sequence. If d=m 1 then ui∈0,1 else if d=m 1+1 then ui∈0,1. Combining the two multiple recursive generators (MRG) results in sequences with better statistical properties in high dimensions and longer periods compared with those generated from a single MRG. The combined generator described above has a period length of approximately 2191.

2.2 Quasi-random Numbers

Low discrepancy (quasi-random) sequences are used in numerical integration, simulation and optimization. Like pseudorandom numbers they are uniformly distributed but they are not statistically independent, rather they are designed to give more even distribution in multidimensional space (uniformity). Therefore they are often more efficient than pseudorandom numbers in multidimensional Monte–Carlo methods.
The quasi-random number generators implemented in this chapter generate a set of points x 1,x 2,…,xN with high uniformity in the S-dimensional unit cube IS=0,1 S. One measure of the uniformity is the discrepancy which is defined as follows:
  • Given a set of points x 1,x 2,…,xN∈IS and a subset G⊂IS, define the counting function SN G as the number of points xi∈G. For each x=x 1,x 2,…,xS∈IS, let Gx be the rectangular S-dimensional region
    G x = 0, x 1 × 0, x 2 ×⋯× 0, x S
    with volume x 1,x 2,…,xS. Then the discrepancy of the points x 1,x 2,…,xN is
    DN* x 1,x 2,…,xN = sup x∈IS SN Gx - N ∑ k=1 S xk .
    The discrepancy of the first N terms of such a sequence has the form
    DN* x 1,x 2,…,xN ≤ CS log⁡N S + O log⁡N S-1   for all  N≥2.
    The principal aim in the construction of low-discrepancy sequences is to find sequences of points in IS with a bound of this form where the constant CS is as small as possible.
Three types of low-discrepancy sequences are supplied in this library, these are due to Sobol, Faure and Niederreiter. Two sets of Sobol sequences are supplied, the first is based on work of Joe and Kuo (2008) and the second on the work of Bratley and Fox (1988). More information on quasi-random number generation and the Sobol, Faure and Niederreiter sequences in particular can be found in Bratley and Fox (1988) and Fox (1986).
The efficiency of a simulation exercise may often be increased by the use of variance reduction methods (see Morgan (1984)). It is also worth considering whether a simulation is the best approach to solving the problem. For example, low-dimensional integrals are usually more efficiently calculated by routines in Chapter D01 rather than by Monte–Carlo integration.

2.3 Scrambled Quasi-random Numbers

Scrambled quasi-random sequences are an extension of standard quasi-random sequences that attempt to eliminate the bias inherent in a quasi-random sequence whilst retaining the low-discrepancy properties. The use of a scrambled sequence allows error estimation of Monte–Carlo results by performing a number of iterates and computing the variance of the results.
This implementation of scrambled quasi-random sequences is based on TOMS algorithm 823 and details can be found in the accompanying paper, Hong and Hickernell (2003). Three methods of scrambling are supplied; the first a restricted form of Owen's scrambling (Owen (1995)), the second based on the method of Faure and Tezuka (2000) and the last method combines the first two.
Scrambled versions of both Sobol sequences and the Niederreiter sequence can be obtained.

2.4 Non-uniform Random Numbers

Random numbers from other distributions may be obtained from the uniform random numbers by the use of transformations and rejection techniques, and for discrete distributions, by table based methods.
(a) | Transformation Methods For a continuous random variable, if the cumulative distribution function (CDF) is F x then for a uniform 0,1 random variate u, y=F-1 u will have CDF F x. This method is only efficient in a few simple cases such as the exponential distribution with mean μ, in which case F-1 u=-μ log u. Other transformations are based on the joint distribution of several random variables. In the bivariate case, if v and w are random variates there may be a function g such that y=g v,w has the required distribution; for example, the Student's t-distribution with n degrees of freedom in which v has a Normal distribution, w has a gamma distribution and g v,w=v⁢n/w.
(b) | Rejection Methods Rejection techniques are based on the ability to easily generate random numbers from a distribution (called the envelope) similar to the distribution required. The value from the envelope distribution is then accepted as a random number from the required distribution with a certain probability; otherwise, it is rejected and a new number is generated from the envelope distribution.
(c) | Table Search Methods For discrete distributions, if the cumulative probabilities, Pi=Prob x≤i, are stored in a table then, given u from a uniform 0,1 distribution, the table is searched for i such that P i-1<u≤Pi. The returned value i will have the required distribution. The table searching can be made faster by means of an index, see Ripley (1987). The effort required to set up the table and its index may be considerable, but the methods are very efficient when many values are needed from the same distribution.

2.5 Copulas

A copula is a function that links the univariate marginal distributions with their multivariate distribution. Sklar's theorem (see Sklar (1973)) states that if f is an m-dimensional distribution function with continuous margins f 1 , f 2 ,…, fm , then f has a unique copula representation, c, such that
f x 1 , x 2 ,…, xm = c f 1 x 1 , f 2 x 2 ,…, fm xm
The copula, c, is a multivariate uniform distribution whose dependence structure is defined by the dependence structure of the multivariate distribution f, with
c u 1 , u 2 ,…, um = f f 1-1 u 1 , f 2-1 u 2 ,… , fm-1 um
where ui ∈ 0,1 . This relationship can be used to simulate variates from distributions defined by the dependence structure of one distribution and each of the marginal distributions given by another. For additional information see Nelsen (1998) or Boye (Unpublished manuscript) and the references therein.

2.6 Brownian Bridge

2.6.1 Brownian Bridge Process

Fix two times t 0<T and let W = Wt 0≤t≤T-t 0 be a standard d-dimensional Wiener process on the interval 0,T-t 0. Recall that the terms Wiener process and Brownian motion are often used interchangeably.
A standard d-dimensional Brownian bridge B = Bt t 0≤t≤T on t 0,T is defined (see Revuz and Yor (1999)) as
Bt = W t-t 0 - t-t 0 T-t 0 W T-t 0 .
The process is continuous, starts at zero at time t 0 and ends at zero at time T. It is Gaussian, has zero mean and has a covariance structure given by
𝔼 Bs BtT = s-t 0 T-t T-t 0 Id
for any s≤t in t 0,T where Id is the d-dimensional identity matrix. The Brownian bridge is often called a non-free or ‘pinned’ Wiener process since it is forced to be 0 at time T, but is otherwise very similar to a standard Wiener process.
We can generalize this construction as follows. Fix points x,w∈ℝd, let Σ be a d×d covariance matrix and choose any d×d matrix C such that C CT=Σ. The generalized d-dimensional Brownian bridge X = Xt t 0≤t≤T is defined by setting
Xt = t-t 0 w+ T-t x T-t 0 + C Bt = t-t 0 w+ T-t x T-t 0 + C W t - t 0 - t-t 0 T-t 0 C W T-t 0
for all t∈t 0,T. The process X is continuous, starts at x at time t 0 and ends at w at time T. It has mean t-t 0 w+ T-t x / T-t 0 and covariance structure
𝔼 Xs - 𝔼 Xs Xt - 𝔼 Xt T = 𝔼 C Bs BtT CT = s-t 0 T-t T-t 0 Σ
for all s≤t in t 0,T. This is a non-free Wiener process since it is forced to be equal to w at time T. However if we set w=x+C W T-t 0, then X simplifies to
Xt = x+C W t-t 0
for all t∈t 0,T which is nothing other than a d-dimensional Wiener process with covariance given by Σ.
Two sample paths for a two-dimensional free Wiener process
Figure 1: Two sample paths for a two-dimensional free Wiener process
Figure 1 shows two sample paths for a two-dimensional free Wiener process X = Xt 1 , Xt 2 0≤t≤2 . The correlation coefficient between the one-dimensional processes X 1 and X 2 at any time is ρ=0.80. Note that the red and green paths in each figure are uncorrelated, however it is fairly evident that the two red paths are correlated, and that the two green paths are correlated (when one path increases so does the other, and vice versa).
Two sample paths for a two-dimensional non-free Wiener process. The process starts at 0,0 and ends at 1,-1
Figure 2: Two sample paths for a two-dimensional non-free Wiener process. The process starts at 0,0 and ends at 1,-1
Figure 2 shows two sample paths for a two-dimensional non-free Wiener process. The process starts at 0,0 and ends at 1,-1 . The correlation coefficient between the one-dimensional processes is again ρ=0.80. The red and green paths in each figure are uncorrelated, while the two red paths tend to increase and decrease together, as do the two green paths. Both Figure 1 and Figure 2 were constructed using G05XBF.

2.6.2 Brownian Bridge Algorithm

The ideas above can also be used to construct sample paths of a free or non-free Wiener process (recall that a non-free Wiener process is the Brownian bridge process outlined above). Fix two times t 0<T and let ti 1≤i≤N be any set of time points satisfying t 0<t 1<t 2<⋯<tN<T. Let X ti 1≤i≤N denote a d-dimensional (free or non-free) Wiener sample path at these times. These values can be generated by the so-called Brownian bridge algorithm (see Glasserman (2004)) which works as follows. From any two known points X ti at time t i and X tk at time tk with ti<tk, a new point X tj can be interpolated at any time tj ∈ ti,tk by setting
X tj = X ti tk - tj + X tk tj - ti tk-ti + C Z tk - tj tj - ti tk - ti (2)
where Z is a d-dimensional standard Normal random variable and C is any d×d matrix such that C CT is the desired covariance structure for the (free or non-free) Wiener process X. Clearly this algorithm is iterative in nature. All that is needed to complete the specification is to fix the start point X t 0 and end point XT, and to specify how successive interpolation times tj are chosen. For X to behave like a usual (free) Wiener process we should set X t 0 equal to some value x∈ℝd and then set XT=x+C T-t 0 Z where Z is any d-dimensional standard Normal random variable. However when it comes to deciding how the successive interpolation times tj should be chosen, there is virtually no restriction. Any method of choosing which tj ∈ ti,tk to interpolate next is equally valid, provided ti is the nearest known point to the left of tj and tk is the nearest known point to the right of tj. In other words, the interpolation interval ti,tk must not contain any other known points, otherwise the covariance structure of the process will be incorrect.
The order in which the successive interpolation times tj are chosen is called the bridge construction order. Since all construction orders will produce a correct process, the question arises whether one construction order should be preferred over another. When the Z values are drawn from a pseudorandom generator, the answer is typically no. However the bridge algorithm is frequently used with quasi-random numbers, and in this case the bridge construction order can be important.

2.6.3 Bridge Construction Order and Quasi-random Sequences

Consider the one-dimensional case of a free Wiener process where d=C=1. The Brownian bridge is frequently combined with low-discrepancy (quasi-random) sequences to perform quasi-Monte–Carlo integration. Quasi-random points Z 1, Z 2, Z 3, … are generated from the standard Normal distribution, where each quasi-random point Zi = Z 1 i,Z 2 i,⋯,ZDi consists of D one-dimensional values. The process X starts at X t 0=x which is known. There remain N+1 time points at which the bridge is to be computed, namely X ti 1≤i≤N and XT (recall we are considering a free Wiener process). In this case D is set equal to N+1, so that N+1 dimensional quasi-random points are generated. A single quasi-random point is used to construct one Wiener sample path.
The question is how to use the dimension values of each N+1 dimensional quasi-random point. Often the ‘lower’ dimension values (Z 1 i,Z 2 i, etc.) display better uniformity properties than the ‘higher’ dimension values (Z N+1 i,ZNi, etc.) so that the ‘lower’ dimension values should be used to construct the most important sections of the sample path. For example, consider a model which is particularly sensitive to the behaviour of the underlying process at time 3. When constructing the sample paths, one would therefore ensure that time 3 was one of the interpolation points of the bridge, and that a ‘lower’ dimension value was used in (2) to construct the corresponding bridge point X 3. Indeed, one would most likely also ensure that time X 3 was one of the first bridge points that was constructed: ‘lower’ dimension values would be used to construct both the left and right bridge points used in (2) to interpolate X 3, so that the distribution of X 3 benefits as much as possible from the uniformity properties of the quasi-random sequence. For further discussions in this regard we refer to Glasserman (2004). These remarks extend readily to the case of a non-free Wiener process.

2.6.4 Brownian Bridge and Stochastic Differential Equations

The Brownian bridge algorithm, especially when combined with quasi-random variates, is frequently used to obtain numerical solutions to stochastic differential equations (SDEs) driven by (free or non-free) Wiener processes. The quasi-random variates produce a family of Wiener sample paths which cover the space of all Wiener sample paths fairly evenly. This is analogous to the way in which a two-dimensional quasi-random sequence covers the unit square 0,1 2 evenly. When solving SDEs one is typically interested in the increments of the driving Wiener process between two time points, rather than the value of the process at a particular time point. Section 3.3 contains details on which routines can be used to obtain such Wiener increments.

2.7 Random Fields

A random field is a stochastic process, taking values in a Euclidean space, and defined over a parameter space of dimensionality at least one. They are often used to simulate some physical space-dependent parameter, such as the permeability of rock, which cannot be measured at every point in the space. The simulated values can then be used to model other dependent quantities, for example, underground flow of water, often through the use of partial differential equations (PDEs).
A d-dimensional random field Z x is a function which is random at every point x∈D for some domain D⊂ℝd, so Z x is a random variable for each x. The random field has a mean function μ x=𝔼 Z x and a symmetric positive semidefinite covariance function C x,y=𝔼 Z x-μ xZ y-μ y.
A random field, Z x, is a Gaussian random field if, for any choice of n∈ℕ and x 1,…,xn∈ℝd, the random vector Z x 1,…,Z xn T follows a multivariate Gaussian distribution.
A Gaussian random field Z x is stationary if μ x is constant for all x∈ℝ and C x,y=C x+a,y+a for all x,y,a∈ℝd and hence we can express the covariance function C x,y as a function γ of one variable: C x,y=γ x-y. γ is known as a variogram (or more correctly, a semivariogram) and includes the multiplicative factor σ 2 representing the variance such that γ 0=σ 2. There are a number of commonly used variograms, including:
Symmetric stable variogram
γ x = σ 2 exp - x′ ν .
Cauchy variogram
γ x = σ 2 1+ x′ 2 -ν .
Differential variogram with compact support
γ x = σ 2 1+8 x′+25 x′2+32 x′3 1-x′8, x′<1, 0, x′≥1.
Exponential variogram
γ x=σ 2 exp-x′.
Gaussian variogram
γ x=σ 2 exp-x′2.
Nugget variogram
γ x= σ 2, x=0, 0, x≠0.
Spherical variogram
γ x= σ 2 1-1.5 x′+0.5 x′3, x′<1, 0, x′≥1.
Bessel variogram
γ x=σ 2 2 ν Γ ν+1 Jν x′x′ν,
Hole effect variogram
γ x=σ 2 sin x′x′.
Whittle–Matérn variogram
γ x=σ 2 2 1-νx′ν Kν x′Γ ν.
Continuously parameterised variogram with compact support
γ x= σ 2 2 1-νx′ν Kν x′Γ ν 1+8 x′′+25 x′′2+32 x′′3 1-x′′8, x′′<1, 0, x′′≥1.
Generalized hyperbolic distribution variogram
γ x=σ 2 δ 2+x′2 λ 2 δλ Kλ κδ Kλ κ δ 2+x′2 12.
Cosine variogram
γ x=σ 2 cos x′.
Where x′ is a scaled norm of x.

2.8 Sampling

The term sampling can have a number of different meanings. Here we are using it to mean randomly selecting one or more observations or records from a particular dataset. Sampling can be performed in one of two ways:
With replacement: | where each observation in the original dataset can appear multiple times in the sample. The sample can therefore be larger than the original dataset.
Without replacement: | where each observation in the original dataset can appear at most once in the sample. The sample is therefore no larger than the original dataset.
Each of these sampling methods can be further divided into two categories:
With equal weights: | where each observation in the original dataset has the same probability of appearing in the sample as every other observation.
With unequal weights: | where the probability of an observation from the original dataset appearing in the sample is proportional to the weight assigned to that observation.
The need to sample from a dataset appears in many areas. For example, it forms the basis for: bootstrapping (sampling with replacement, usually using equal weights); cross-validation (sampling without replacement, using equal weights); importance sampling (sampling with replacement, using unequal weights); randomization of experimental units in designed experiments or reducing the size of large databases (sampling with replacement with either equal or unequal weights).
Rather than drawing a sample from the whole dataset it is sometimes desirable to take samples from different strata or subpopulations within that dataset, referred to as stratified sampling. Within each stratum one or more of the above sampling methods may be adopted.

2.9 Sampling Based Validation

Let Yo,Xo denote a dataset of observed values from a known population, where Yo is a matrix of one or more dependent or response variables and Xo a matrix of one more more independent variables or covariates. Let M denote a model described in terms β a vector of one or more unknown parameters. The purpose of model M is to describe the behaviour of the dependent variables in terms of the independent variables. In order to do this the parameter estimates must first be estimated and then how well the models fits, that is, how well it describes the dependent variables, assessed.
An example of such a model would be a simple linear regression as described in Section 2.3 in the G02 Chapter Introduction. The simple linear regression has two parameters, an intercept, β 0 and slope, β 1 and the observed dataset consists of the dependent variable y and the single independent variable x. The parameter estimates are usually obtained via least squares.
Given a set of parameter estimates and a matrix of independent variables one way of assessing how well a model fits is to use the model to predict the values of the dependent variable and compare these predictions to the observed values. Ideally two datasets will be involved, a training dataset, Yt,Xt, used to estimate the model parameters and a validation dataset, Yv,Xv, used for the prediction and comparison. These two datasets should be drawn independently from the same population. However, in practice, this is often not possible either because a second dataset can not be drawn from the same population or because the value of the dependent variables are unknowable (for example the dataset in question is a time series and the event of interest has not yet happened). Rather than use the same dataset as both the training and validation dataset, which leads to overfitting and hence an over estimation of how well the model fits, a sampling based validation method can be used.
In K-fold cross-validation the original dataset is randomly divided into K equally sized folds (or groups). The model fitting and assessment process is performed using a validation dataset consisting of those observations in the kth group and a training dataset consisting of all observations not in the kth group. This is repeated K times, with k=1,2,…,K, and the results combined. Repeated random sub-sampling validation is similar, but rather than systematically dividing the original dataset into a training and validation dataset, whether an observation resides in a given dataset is chosen randomly each time the model fitting and assessment process is repeated.

2.10 Other Random Structures

In addition to random numbers from various distributions, random compound structures can be generated. These include random time series and random matrices.

2.11 Multiple Streams of Pseudorandom Numbers

It is often advantageous to be able to generate variates from multiple, independent, streams (or sequences) of random variates. For example when running a simulation in parallel on several processors. There are four ways of generating multiple streams using the routines available in this chapter:
(i) | using different initial values (seeds);
(ii) | using different generators;
(iii) | skip ahead (also called block-splitting);
(iv) | leap-frogging.

2.11.1 Multiple Streams via Different Initial Values (Seeds)

A different sequence of variates can be generated from the same base generator by initializing the generator using a different set of seeds. The statistical properties of the base generators are only guaranteed within, not between sequences. For example, two sequences generated from two different starting points may overlap if these initial values are not far enough apart. The potential for overlapping sequences is reduced if the period of the generator being used is large. In general, of the four methods for creating multiple streams described here, this is the least satisfactory.
The one exception to this is the Wichmann–Hill II generator. The Wichmann and Hill (2006) paper describes a method of generating blocks of variates, with lengths up to 290, by fixing the first three seed values of the generator (w 0, x 0 and y 0), and setting z 0 to a different value for each stream required. This is similar to the skip-ahead method described in Section 2.11.3, in that the full sequence of the Wichmann–Hill II generator is split into a number of different blocks, in this case with a fixed length of 290. But without the computationally intensive initialization usually required for the skip-ahead method.

2.11.2 Multiple Streams via Different Generators

Independent sequences of variates can be generated using a different base generator for each sequence. For example, sequence 1 can be generated using the NAG basic generator, sequence 2 using Mersenne Twister, sequence 3 the ACORN generator and sequence 4 using L'Ecuyer generator. The Wichmann–Hill I generator implemented in this chapter is, in fact, a series of 273 independent generators. The particular sub-generator to use is selected using the SUBID variable. Therefore, in total, 278 independent streams can be generated with each using a different generator (273 Wichmann–Hill I generators, and 5 additional base generators).

2.11.3 Multiple Streams via Skip-ahead

Independent sequences of variates can be generated from a single base generator through the use of block-splitting, or skipping-ahead. This method consists of splitting the sequence into k non-overlapping blocks, each of length n, where n is no smaller than the maximum number of variates required from any of the sequences. For example,
x 1 , x 2 , … , xn block 1 , x n+1 , x n+2 , … , x 2 n block 2 , x 2 n+1 , x 2 n+2 , … , x 3 n block 3 , etc.
where x 1,x 2,… is the sequence produced by the generator of interest. Each of the k blocks provide an independent sequence.
The skip-ahead algorithm therefore requires the sequence to be advanced a large number of places, as to generate values from say, block b, you must skip over the b-1 n values in the first b-1 blocks. Owing to their form this can be done efficiently for linear congruential generators and multiple congruential generators. A skip-ahead algorithm is also provided for the Mersenne Twister generator.
Although skip-ahead requires some additional computation at the initialization stage (to ‘fast forward’ the sequence) no additional computation is required at the generation stage.
This method of producing multiple streams can also be used for the Sobol and Niederreiter quasi-random number generator via the argument ISKIP in G05YLF.

2.11.4 Multiple Streams via Leap-frog

Independent sequences of variates can also be generated from a single base generator through the use of leap-frogging. This method involves splitting the sequence from a single generator into k disjoint subsequences. For example:
Subsequence 1: x 1 , x k+1 , x 2 k+1 ,… Subsequence 2: x 2 , x k+2 , x 2 k+2 ,… ⋮ Subsequence ​k: xk , x 2 k , x 3 k ,… ,
where x 1,x 2,… is the sequence produced by the generator of interest. Each of the k subsequences then provides an independent stream of variates.
The leap-frog algorithm therefore requires the generation of every kth variate from the base generator. Owing to their form this can be done efficiently for linear congruential generators and multiple congruential generators. A leap-frog algorithm is provided for the NAG Basic generator, both the Wichmann–Hill I and Wichmann–Hill II generators and L'Ecuyer generator.
It is known that, dependent on the number of streams required, leap-frogging can lead to sequences with poor statistical properties, especially when applied to linear congruential generators. In addition, leap-frogging can increase the time required to generate each variate. Therefore leap-frogging should be avoided unless absolutely necessary.

2.11.5 Skip-ahead and Leap-frog for a Linear Congruential Generator (LCG): An Example

As an illustrative example, a brief description of the algebra behind the implementation of the leap-frog and skip-ahead algorithms for a linear congruential generator is given. A linear congruential generator has the form x i+1=a 1 xi mod m 1. The recursive nature of a linear congruential generator means that
x i+v = a 1 x i+v-1 mod m 1 = a 1 a 1 x i+v-2 mod m 1 mod m 1 = a 1 2 x i+v-2 mod m 1 = a 1 v xi mod m 1 .
The sequence can therefore be quickly advanced v places by multiplying the current state (xi) by a 1 v mod m 1, hence skipping the sequence ahead. Leap-frogging can be implemented by using a 1 k, where k is the number of streams required, in place of a 1 in the standard linear congruential generator recursive formula, in order to advance k places, rather than one, at each iteration.
In a linear congruential generator the multiplier a 1 is constructed so that the generator has good statistical properties in, for example, the spectral test. When using leap-frogging to construct multiple streams this multiplier is replaced with a 1 k, and there is no guarantee that this new multiplier will have suitable properties especially as the value of k depends on the number of streams required and so is likely to change depending on the application. This problem can be emphasized by the lattice structure of linear congruential generators. Similiarly, the value of a 1 is often chosen such that the computation a 1 xi mod m 1 can be performed efficiently. When a 1 is replaced by a 1 k, this is often no longer the case.
Note that, due to rounding, when using a distributional generator, a sequence generated using leap-frogging and a sequence constructed by taking every k value from a set of variates generated without leap-frogging may differ slightly. These differences should only affect the least significant digit.

2.11.6 Skip-ahead and Leap-frog for the Mersenne Twister: An Example

Skipping ahead with the Mersenne Twister generator is based on the definition of a k×k (where k=19937) transition matrix, A, over the finite field 𝔽 2 (with elements 0 and 1). Multiplying A by the current state xn, represented as a vector of bits, produces the next state vector x n+1:
x n + 1 = A ⁢ x n .
Thus, skipping ahead v places in a sequence is equivalent to multiplying by Av:
x n + v = A v x n .
Since calculating Av by a standard square and multiply algorithm is O k 3 log v and requires over 47MB of memory (see Haramoto et al. (2008)), an indirect calculation is performed which relies on a property of the characteristic polynomial p z of A, namely that p A=0. We then define
g z = z v mod p z = a k - 1 ⁢ z k - 1 + … + a 1 ⁢ z + a 0 ,
and observe that
g z = z v + q z ⁢ p z
for a polynomial q z. Since p A=0, we have that g A = A v and
A v ⁢ x n = a k - 1 ⁢ A k - 1 + … + a 1 A + a 0 I ⁢ x n .
This polynomial evaluation can be performed using Horner's method:
A v ⁢ x n = A ⁢ … A ⁢ A ⁢ A ⁢ a k - 1 ⁢ x n + a k - 2 ⁢ x n + a k - 3 ⁢ x n + ⋯ + a 1 ⁢ x n + a 0 ⁢ x n ,
which reduces the problem to advancing the generator k-1 places from state xn and adding (where addition is as defined over 𝔽 2) the intermediate states for which ai is nonzero.
There are therefore two stages to skipping the Mersenne Twister ahead v places:
(i) | Calculate the coefficients of the polynomial g z = z v mod p z ;
(ii) | advance the sequence k-1 places from the starting state and add the intermediate states that correspond to nonzero coefficients in the polynomial calculated in the first step.
The resulting state is that for position v in the sequence.
The cost of calculating the polynomial is O k 2 log v and the cost of applying it to state is constant. Skip ahead functionality is typically used in order to generate n independent pseudorandom number streams (e.g., for separate threads of computation). There are two options for generating the n states:
(i) | On the master thread calculate the polynomial for a skip ahead distance of v and apply this polynomial to state n times, after each iteration j saving the current state for later usage by thread j.
(ii) | Have each thread j independently and in parallel with other threads calculate the polynomial for a distance of j+1⁢v and apply to the original state.
Since lim v → ∞ log v = log⁡ n ⁢ v , then for large v the cost of generating the polynomial for a skip ahead distance of n⁢v (i.e., the calculation performed by thread n-1 in option (ii) above) is approximately the same as generating that for a distance of v (i.e., the calculation performed by thread 0). However, only one application to state need be made per thread, and if n is sufficiently large the cost of applying the polynomial to state becomes the dominant cost in option (i), in which case it is desirable to use option (ii). Tests have shown that as a guideline it becomes worthwhile to switch from option (i) to option (ii) for approximately n>30.
Leap frog calculations with the Mersenne Twister are performed by computing the sequence fully up to the required size and discarding the redundant numbers for a given stream.

3 Recommendations on Choice and Use of Available Routines

3.1 Pseudorandom Numbers

Before generating any pseudorandom variates the base generator being used must be initialized. Once initialized, a distributional generator can be called to obtain the variates required. No interfaces have been supplied for direct access to the base generators. If a sequence of random variates from a uniform distribution on the open interval 0,1, is required, then the uniform distribution routine (G05SAF) should be called.

3.1.1 Initialization

Before generating any variates the base generator must be initialized. Two utility routines are provided for this, G05KFF and G05KGF, both of which allow any of the base generators to be chosen.
G05KFF selects and initializes a base generator to a repeatable (when executed serially) state: two calls of G05KFF with the same argument-values will result in the same subsequent sequences of random numbers (when both generated serially).
G05KGF selects and initializes a base generator to a non-repeatable state in such a way that different calls of G05KGF, either in the same run or different runs of the program, will almost certainly result in different subsequent sequences of random numbers.
No utilities for saving, retrieving or copying the current state of a generator have been provided. All of the information on the current state of a generator (or stream, if multiple streams are being used) is stored in the integer array STATE and as such this array can be treated as any other integer array, allowing for easy copying, restoring, etc.

3.1.2 Repeated initialization

As mentioned in Section 2.11.1, it is important to note that the statistical properties of pseudorandom numbers are only guaranteed within sequences and not between sequences produced by the same generator. Repeated initialization will thus render the numbers obtained less rather than more independent. In a simple case there should be only one call to G05KFF or G05KGF and this call should be before any call to an actual generation routine.

3.1.3 Choice of Base Generator

If a single sequence is required then it is recommended that the Mersenne Twister is used as the base generator (GENID=3). This generator is fast, has an extremely long period and has been shown to perform well on various test suites, see Matsumoto and Nishimura (1998), L'Ecuyer and Simard (2002) and Wichmann and Hill (2006) for example.
When choosing a base generator, the period of the chosen generator should be borne in mind. A good rule of thumb is never to use more numbers than the square root of the period in any one experiment as the statistical properties are impaired. For closely related reasons, breaking numbers down into their bit patterns and using individual bits may also cause trouble.

3.1.4 Choice of Method for Generating Multiple Streams

If the Wichmann–Hill II base generator is being used, and a period of 290 is sufficient, then the method described in Section 2.11.1 can be used. If a different generator is used, or a longer period length is required then generating multiple streams by altering the initial values should be avoided.
Using a different generator works well if less than 277 streams are required.
Of the remaining two methods, both skip-ahead and leap-frogging use the sequence from a single generator, both guarantee that the different sequences will not overlap and both can be scaled to an arbitrary number of streams. Leap-frogging requires no a-priori knowledge about the number of variates being generated, whereas skip-ahead requires you to know (approximately) the maximum number of variates required from each stream. Skip-ahead requires no a-priori information on the number of streams required. In contrast leap-frogging requires you to know the maximum number of streams required, prior to generating the first value. Of these two, if possible, skip-ahead should be used in preference to leap-frogging. Both methods required additional computation compared with generating a single sequence, but for skip-ahead this computation occurs only at initialization. For leap-frogging additional computation is required both at initialization and during the generation of the variates. In addition, as mentioned in Section 2.11.4, using leap-frogging can, in some instances, change the statistical properties of the sequences being generated.
Leap-frogging is performed by calling G05KHF after the initialization routine (G05KFF or G05KGF). For skip-ahead, either G05KJF or G05KKF can be called. Of these, G05KKF restricts the amount being skipped to a power of 2, but allows for a large ‘skip’ to be performed.

3.1.5 Copulas

After calling one of the copula routines the inverse cumulative distribution function (CDF) can be applied to convert the uniform marginal distribution into the required form. Scalar and vector routines for evaluating the CDF, for a range of distributions, are supplied in Chapter G01. It should be noted that these routines are often described as computing the ‘deviates’ of the distribution.
When using the inverse CDF routines from Chapter G01 it should be noted that some are limited in the number of significant figures they return. This may affect the statistical properties of the resulting sequence of variates. Section 7 of the individual routine documentation will give a discussion of the accuracy of the particular algorithm being used and any available alternatives.

3.2 Quasi-random Numbers

Prior to generating any quasi-random variates the generator being used must be initialized via G05YLF or G05YNF. Of these, G05YLF can be used to initialize a standard Sobol, Faure or Niederreiter sequence and G05YNF can be used to initialize a scrambled Sobol or Niederreiter sequence.
Owing to the random nature of the scrambling, before calling the initialization routine G05YNF one of the pseudorandom initialization routines, G05KFF or G05KGF, must be called.
Once a quasi-random generator has been initialized, using either G05YLF or G05YNF, one of three generation routines can be called to generate uniformly distributed sequences (G05YMF), Normally distributed sequences (G05YJF) or sequences with a log-normal distribution (G05YKF). For example, for a repeatable sequence of scrambled quasi-random variates from the Normal distribution, G05KFF must be called first (to initialize a pseudorandom generator), followed by G05YNF (to initialize a scrambled quasi-random generator) and then G05YJF can be called to generate the sequence from the required distribution.
See the last paragraph of Section 3.1.5 on how sequences from other distributions can be obtained using the inverse CDF.

3.3 Brownian Bridge

G05XBF may be used to generate sample paths from a (free or non-free) Wiener process using the Brownian bridge algorithm. Prior to calling G05XBF, the generator must be initialized by a call to G05XAF. G05XAF requires you to specify a bridge construction order. The routine G05XEF can be used to convert a set of input times into one of several common bridge construction orders, which can then be used in the initialization call to G05XAF.
G05XDF may be used to generate the scaled increments of the sample paths of a (free or non-free) Wiener process. Prior to calling G05XDF, the generator must be initialized by a call to G05XCF. Note that G05XDF generates these scaled increments directly; it is not necessary to call G05XBF before calling G05XDF. As before, G05XEF can be used to convert a set of input times into a bridge construction order which can be passed to G05XCF.

3.4 Random Fields

Routines for simulating from either a one-dimensional or a two-dimensional stationary Gaussian random field are provided. These routines use the circulant embedding method of Dietrich and Newsam (1997) to efficiently generate from the required field. In both cases a setup routine is called, which defines the domain and variogram to use, followed by the generation routine. A number of preset variograms are supplied or a user-defined subroutine can be used.
  • One-dimensional random field:
    • G05ZNF setup routine, using a preset variogram.
    • G05ZMF setup routine, using a user-defined variogram.
    • G05ZPF generation routine.
  • Two-dimension random field:
    • G05ZQF setup routine, using a preset variogram.
    • G05ZRF setup routine, using a user-defined variogram.
    • G05ZSF generation routine.
In addition to generating a random field, it is possible to use the circulant embedding method to generate realizations of fractional Brownian motion, this functionality is provided in G05ZTF.
Before calling G05ZPF, G05ZRF or G05ZTF one of the initialization routines, G05KFF or G05KGF must be called.

3.5 Sampling

Each of the four sampling methods described in Section 2.8 can be performed using the following routines:
  • G05TLF Sampling with replacement, equal weights.
  • G05TDF Sampling with replacement, unequal weights.
  • G05NDF Sampling without replacement, equal weights.
  • G05NEF Sampling without replacement, unequal weights.
In addition to these routines for directly sampling from a dataset two utility routines that perform an in-place permutation to give datasets suitable for use in validation are provided. G05PVF generates training and validation datasets suitable for K-fold cross-validation and G05PWF generates training and validation datasets suitable for random sub-sampling validation. To perform stratified sampling the dataset should first be ordered by stratum using a sorting routine from Chapter M01 and then one of the above sampling routines can be applied to each stratum.

4 Functionality Index

Brownian bridge,
circulant embedding generator,
generate fractional Brownian motion G05ZTF
increments generator,
generate Wiener increments G05XDF
initialize generator G05XCF
path generator,
create bridge construction order G05XEF
generate a free or non-free (pinned) Wiener process for a given set of time steps G05XBF
initialize generator G05XAF
Generating samples, matrices and tables,
permutation of real matrix, vector, vector triplet
K − fold cross-validation G05PVF
random sub-sampling validation G05PWF
random correlation matrix G05PYF
random orthogonal matrix G05PXF
random permutation of an integer vector G05NCF
random sample from an integer vector,
unequal weights, without replacement G05NEF
unweighted, without replacement G05NDF
random table G05PZF
Generation of time series,
asymmetric GARCH Type II G05PEF
asymmetric GJR GARCH G05PFF
EGARCH G05PGF
exponential smoothing G05PMF
type I AGARCH G05PDF
univariate ARMA G05PHF
vector ARMA G05PJF
Pseudorandom numbers,
array of variates from multivariate distributions,
Dirichlet distribution G05SEF
multinomial distribution G05TGF
Normal distribution G05RZF
Student's t distribution G05RYF
copulas,
Clayton/Cook–Johnson copula (bivariate) G05REF
Clayton/Cook–Johnson copula (multivariate) G05RHF
Frank copula (bivariate) G05RFF
Frank copula (multivariate) G05RJF
Gaussian copula G05RDF
Gumbel–Hougaard copula G05RKF
Plackett copula G05RGF
Student's t copula G05RCF
initialize generator,
multiple streams,
leap-frog G05KHF
skip-ahead G05KJF
skip-ahead (power of 2) G05KKF
nonrepeatable sequence G05KGF
repeatable sequence G05KFF
vector of variates from discrete univariate distributions,
binomial distribution G05TAF
geometric distribution G05TCF
hypergeometric distribution G05TEF
logarithmic distribution G05TFF
logical value .TRUE. or .FALSE. G05TBF
negative binomial distribution G05THF
Poisson distribution G05TJF
uniform distribution G05TLF
user-supplied distribution G05TDF
variate array from discrete distributions with array of parameters,
Poisson distribution with varying mean G05TKF
vectors of variates from continuous univariate distributions,
beta distribution G05SBF
Cauchy distribution G05SCF
exponential mix distribution G05SGF
F-distribution G05SHF
gamma distribution G05SJF
logistic distribution G05SLF
log-normal distribution G05SMF
negative exponential distribution G05SFF
Normal distribution G05SKF
real number from the continuous uniform distribution G05SAF
Student's t-distribution G05SNF
triangular distribution G05SPF
uniform distribution G05SQF
von Mises distribution G05SRF
Weibull distribution G05SSF
χ2 square distribution G05SDF
Quasi-random numbers,
array of variates from univariate distributions,
log-normal distribution G05YKF
Normal distribution G05YJF
uniform distribution G05YMF
initialize generator,
scrambled Sobol or Niederreiter G05YNF
Sobol, Niederreiter or Faure G05YLF
Random fields,
one-dimensional,
generation G05ZPF
initialize generator,
preset variogram G05ZNF
user-defined variogram G05ZMF
two-dimensional,
generation G05ZSF
initialize generator,
preset variogram G05ZRF
user-defined variogram G05ZQF

5 Auxiliary Routines Associated with Library Routine Arguments

None.

6 Routines Withdrawn or Scheduled for Withdrawal

The following lists all those routines that have been withdrawn since Mark 19 of the Library or are scheduled for withdrawal at one of the next two marks.
Withdrawn Routine | Mark of Withdrawal | Replacement Routine(s)
G05CAF | 22 | G05SAF
G05CBF | 22 | G05KFF
G05CCF | 22 | G05KGF
G05CFF | 22 | F06DFF
G05CGF | 22 | F06DFF
G05DAF | 22 | G05SQF
G05DBF | 22 | G05SFF
G05DCF | 22 | G05SLF
G05DDF | 22 | G05SKF
G05DEF | 22 | G05SMF
G05DFF | 22 | G05SCF
G05DHF | 22 | G05SDF
G05DJF | 22 | G05SNF
G05DKF | 22 | G05SHF
G05DPF | 22 | G05SSF
G05DRF | 22 | G05TKF
G05DYF | 22 | G05TLF
G05DZF | 22 | G05TBF
G05EAF | 22 | G05RZF
G05EBF | 22 | G05TLF
G05ECF | 22 | G05TJF
G05EDF | 22 | G05TAF
G05EEF | 22 | G05THF
G05EFF | 22 | G05TEF
G05EGF | 22 | G05PHF
G05EHF | 22 | G05NCF
G05EJF | 22 | G05NDF
G05EWF | 22 | G05PHF
G05EXF | 22 | G05TDF
G05EYF | 22 | G05TDF
G05EZF | 22 | G05RZF
G05FAF | 22 | G05SQF
G05FBF | 22 | G05SFF
G05FDF | 22 | G05SKF
G05FEF | 22 | G05SBF
G05FFF | 22 | G05SJF
G05FSF | 22 | G05SRF
G05GAF | 22 | G05PXF
G05GBF | 22 | G05PYF
G05HDF | 22 | G05PJF
G05HKF | 24 | G05PDF
G05HLF | 24 | G05PEF
G05HMF | 24 | G05PFF
G05HNF | 24 | G05PGF
G05KAF | 24 | G05SAF
G05KBF | 24 | G05KFF
G05KCF | 24 | G05KGF
G05KEF | 24 | G05TBF
G05LAF | 24 | G05SKF
G05LBF | 24 | G05SNF
G05LCF | 24 | G05SDF
G05LDF | 24 | G05SHF
G05LEF | 24 | G05SBF
G05LFF | 24 | G05SJF
G05LGF | 24 | G05SQF
G05LHF | 24 | G05SPF
G05LJF | 24 | G05SFF
G05LKF | 24 | G05SMF
G05LLF | 24 | G05SJF
G05LMF | 24 | G05SSF
G05LNF | 24 | G05SLF
G05LPF | 24 | G05SRF
G05LQF | 24 | G05SGF
G05LXF | 24 | G05RYF
G05LYF | 24 | G05RZF
G05LZF | 24 | G05RZF
G05MAF | 24 | G05TLF
G05MBF | 24 | G05TCF
G05MCF | 24 | G05THF
G05MDF | 24 | G05TFF
G05MEF | 24 | G05TKF
G05MJF | 24 | G05TAF
G05MKF | 24 | G05TJF
G05MLF | 24 | G05TEF
G05MRF | 24 | G05TGF
G05MZF | 24 | G05TDF
G05NAF | 24 | G05NCF
G05NBF | 24 | G05NDF
G05PAF | 24 | G05PHF
G05PCF | 24 | G05PJF
G05QAF | 24 | G05PXF
G05QBF | 24 | G05PYF
G05QDF | 24 | G05PZF
G05RAF | 24 | G05RDF
G05RBF | 24 | G05RCF
G05YAF | 23 | G05YLF and G05YMF
G05YBF | 23 | G05YLF and either G05YJF or G05YKF
G05YCF | 24 | G05YLF
G05YDF | 24 | G05YMF
G05YEF | 24 | G05YLF
G05YFF | 24 | G05YMF
G05YGF | 24 | G05YLF
G05YHF | 24 | G05YMF
G05ZAF | 22 | No replacement routine required

7 References

Banks J (1998) Handbook on Simulation Wiley
Boye E (Unpublished manuscript) Copulas for finance: a reading guide and some applications Financial Econometrics Research Centre, City University Business School, London
Bratley P and Fox B L (1988) Algorithm 659: implementing Sobol's quasirandom sequence generator ACM Trans. Math. Software 14(1) 88–100
Dietrich C R and Newsam G N (1997) Fast and exact simulation of stationary Gaussian processes through circulant embedding of the covariance matrix SIAM J. Sci. Comput. 18 1088–1107
Faure H and Tezuka S (2000) Another random scrambling of digital (t,s)-sequences Monte Carlo and Quasi-Monte Carlo Methods Springer-Verlag, Berlin, Germany (eds K T Fang, F J Hickernell and H Niederreiter)
Fox B L (1986) Algorithm 647: implementation and relative efficiency of quasirandom sequence generators ACM Trans. Math. Software 12(4) 362–376
Glasserman P (2004) Monte Carlo Methods in Financial Engineering Springer
Haramoto H, Matsumoto M, Nishimura T, Panneton F and L'Ecuyer P (2008) Efficient jump ahead for F2-linear random number generators INFORMS J. on Computing 20(3) 385–390
Hong H S and Hickernell F J (2003) Algorithm 823: implementing scrambled digital sequences ACM Trans. Math. Software 29:2 95–109
Joe S and Kuo F Y (2008) Constructing Sobol sequences with better two-dimensional projections SIAM J. Sci. Comput. 30 2635–2654
Knuth D E (1981) The Art of Computer Programming (Volume 2) (2nd Edition) Addison–Wesley
L'Ecuyer P and Simard R (2002) TestU01: a software library in ANSI C for empirical testing of random number generators Departement d'Informatique et de Recherche Operationnelle, Universite de Montreal http://www.iro.umontreal.ca/~lecuyer
Maclaren N M (1989) The generation of multiple independent sequences of pseudorandom numbers Appl. Statist. 38 351–359
Matsumoto M and Nishimura T (1998) Mersenne twister: a 623-dimensionally equidistributed uniform pseudorandom number generator ACM Transactions on Modelling and Computer Simulations
Morgan B J T (1984) Elements of Simulation Chapman and Hall
Nelsen R B (1998) An Introduction to Copulas. Lecture Notes in Statistics 139 Springer
Owen A B (1995) Randomly permuted (t,m,s)-nets and (t,s)-sequences Monte Carlo and Quasi-Monte Carlo Methods in Scientific Computing, Lecture Notes in Statistics 106 Springer-Verlag, New York, NY 299–317 (eds H Niederreiter and P J-S Shiue)
Revuz D and Yor M (1999) Continuous Martingales and Brownian Motion Springer
Ripley B D (1987) Stochastic Simulation Wiley
Sklar A (1973) Random variables: joint distribution functions and copulas Kybernetika 9 499–460
Wichmann B A and Hill I D (2006) Generating good pseudo-random numbers Computational Statistics and Data Analysis 51 1614–1622
Wikramaratna R S (1989) ACORN - a new method for generating sequences of uniformly distributed pseudo-random numbers Journal of Computational Physics 83 16–31
Wikramaratna R S (1992) Theoretical background for the ACORN random number generator Report AEA-APS-0244 AEA Technology, Winfrith, Dorest, UK
Wikramaratna R S (2007) The additive congruential random number generator a special case of a multiple recursive generator Journal of Computational and Applied Mathematics
G05 Chapter Contents
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


G05KFF : NAG Library, Mark 26

G05 Chapter Contents
G05 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

G05KFF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

G05KFF initializes the selected base generator, as used by the group of pseudorandom number routines (see G05KHF–G05KJF, G05NCF, G05NDF, G05PDF–G05PJF, G05PXF–G05PZF, G05RCF, G05RDF, G05RYF, G05RZF and G05SAF–G05TLF) and the quasi-random scrambled sequence initialization routine, G05YNF.

2 Specification

SUBROUTINE G05KFF ( GENID, SUBID, SEED, LSEED, STATE, LSTATE, IFAIL)
INTEGER GENID, SUBID, SEED(LSEED), LSEED, STATE(LSTATE), LSTATE, IFAIL

3 Description

G05KFF selects a base generator through the input value of the arguments GENID and SUBID, and then initializes it based on the values given in the array SEED.
A given base generator will yield different sequences of random numbers if initialized with different values of SEED. Alternatively, the same sequence of random numbers will be generated if the same value of SEED is used. It should be noted that there is no guarantee of statistical properties between sequences, only within sequences.
A definition of some of the terms used in this description, along with details of the various base generators can be found in the G05 Chapter Introduction.

4 References

L'Ecuyer P and Simard R (2002) TestU01: a software library in ANSI C for empirical testing of random number generators Departement d'Informatique et de Recherche Operationnelle, Universite de Montreal http://www.iro.umontreal.ca/~lecuyer
Maclaren N M (1989) The generation of multiple independent sequences of pseudorandom numbers Appl. Statist. 38 351–359
Matsumoto M and Nishimura T (1998) Mersenne twister: a 623-dimensionally equidistributed uniform pseudorandom number generator ACM Transactions on Modelling and Computer Simulations
Wichmann B A and Hill I D (2006) Generating good pseudo-random numbers Computational Statistics and Data Analysis 51 1614–1622
Wikramaratna R S (1989) ACORN - a new method for generating sequences of uniformly distributed pseudo-random numbers Journal of Computational Physics 83 16–31

5 Arguments

1:   GENID – INTEGERInput
On entry: must contain the type of base generator to use.
GENID=1
NAG basic generator.
GENID=2
Wichmann Hill I generator.
GENID=3
Mersenne Twister.
GENID=4
Wichmann Hill II generator.
GENID=5
ACORN generator.
GENID=6
L'Ecuyer MRG32k3a generator.
See the G05 Chapter Introduction for details of each of the base generators.
Constraint: GENID=1, 2, 3, 4, 5 or 6.
2:   SUBID – INTEGERInput
On entry: if GENID=2, SUBID indicates which of the 273 sub-generators to use. In this case, the SUBID +272 mod 273 + 1 sub-generator is used.
If GENID=5, SUBID indicates the values of k and p to use, where k is the order of the generator, and p controls the size of the modulus, M, with M = 2 p×30 . If SUBID<1, the default values of k=10 and p=2 are used, otherwise values for k and p are calculated from the formula, SUBID=k+1000 p-1.
If GENID=6 and SUBID mod 2=0 the range of the generator is set to 0,1, otherwise the range is set to 0,1; in this case the sequence is identical to the implementation of MRG32k3a in TestU01 (see L'Ecuyer and Simard (2002)) for identical seeds.
For all other values of GENID, SUBID is not referenced.
3:   SEED LSEED – INTEGER arrayInput
On entry: the initial (seed) values for the selected base generator. The number of initial values required varies with each of the base generators.
If GENID=1, one seed is required.
If GENID=2, four seeds are required.
If GENID=3, 624 seeds are required.
If GENID=4, four seeds are required.
If GENID=5, k+1 p seeds are required, where k and p are defined by SUBID. For the ACORN generator it is recommended that an odd value is used for SEED 1.
If GENID=6, six seeds are required.
If insufficient seeds are provided then the first LSEED-1 values supplied in SEED are used and the remaining values are randomly generated using the NAG basic generator. In such cases the NAG basic generator is initialized using the value supplied in SEED LSEED.
Constraint: SEED i≥1, for i=1,2,…,LSEED.
4:   LSEED – INTEGERInput
On entry: the size of the SEED array.
Constraint: LSEED≥1.
5:   STATE LSTATE – INTEGER arrayCommunication Array
On exit: contains information on the selected base generator and its current state.
6:   LSTATE – INTEGERInput/Output
On entry: the dimension of the STATE array, or a value <1. If the Mersenne Twister (GENID=3) is being used and the skip ahead routine G05KJF or G05KKF will be called subsequently, then you must ensure that LSTATE≥1260.
On exit: if LSTATE<1 on entry, then the required length of the STATE array for the chosen base generator, otherwise LSTATE is unchanged. When GENID=3 (Mersenne Twister) a value of 1260 is returned, allowing for the skip ahead routine to be subsequently called. In all other cases the minimum length, as documented in the constraints below, is returned.
Constraints:
  • if GENID=1, LSTATE≥17;
  • if GENID=2, LSTATE≥21;
  • if GENID=3, LSTATE≥633;
  • if GENID=4, LSTATE≥29;
  • if GENID=5, LSTATE≥max k+1×p+9,14+3, where k and p are defined by SUBID;
  • if GENID=6, LSTATE≥61;
  • otherwise LSTATE<1.
7:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
On exit: IFAIL=0 or -1 unless the routine detects an error or a warning has been flagged (see Section 6).
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, GENID=value.
Constraint: GENID=1, 2, 3, 4, 5 or 6.
IFAIL=3
On entry, invalid SEED.
IFAIL=4
On entry, LSEED=value.
Constraint: LSEED≥1.
IFAIL=6
On entry, LSTATE=value.
Constraint: LSTATE≤0 or LSTATE≥value.
IFAIL=-1
Required length of STATE array returned in LSTATE but STATE array not initialized.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

Not applicable.

8 Parallelism and Performance

G05KFF is not threaded in any implementation.

9 Further Comments

None.

10 Example

This example prints the first five pseudorandom real numbers from a uniform distribution between 0 and 1, generated by G05SAF after initialization by G05KFF.

10.1 Program Text

Program Text (g05kffe.f90)

10.2 Program Data

Program Data (g05kffe.d)

10.3 Program Results

Program Results (g05kffe.r)

G05 Chapter Contents
G05 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


G05KGF : NAG Library, Mark 26

G05 Chapter Contents
G05 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

G05KGF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

G05KGF initializes the selected base generator to generate a non-repeatable sequence of variates. The base generator can then be used by the group of pseudorandom number routines (see G05KHF–G05KJF, G05NCF, G05NDF, G05PDF–G05PJF, G05PXF–G05PZF, G05RCF, G05RDF, G05RYF, G05RZF and G05SAF–G05TLF) and the quasi-random scrambled sequence initialization routine, G05YNF.

2 Specification

SUBROUTINE G05KGF ( GENID, SUBID, STATE, LSTATE, IFAIL)
INTEGER GENID, SUBID, STATE(LSTATE), LSTATE, IFAIL

3 Description

G05KGF selects a base generator through the input value of the arguments GENID and SUBID, and then initializes it based on the values taken from the real-time clock, resulting in the same base generator yielding different sequences of random numbers each time the calling program is run. It should be noted that there is no guarantee of statistical properties between sequences, only within sequences.
A definition of some of the terms used in this description, along with details of the various base generators can be found in the G05 Chapter Introduction.

4 References

L'Ecuyer P and Simard R (2002) TestU01: a software library in ANSI C for empirical testing of random number generators Departement d'Informatique et de Recherche Operationnelle, Universite de Montreal http://www.iro.umontreal.ca/~lecuyer
Maclaren N M (1989) The generation of multiple independent sequences of pseudorandom numbers Appl. Statist. 38 351–359
Matsumoto M and Nishimura T (1998) Mersenne twister: a 623-dimensionally equidistributed uniform pseudorandom number generator ACM Transactions on Modelling and Computer Simulations
Wichmann B A and Hill I D (2006) Generating good pseudo-random numbers Computational Statistics and Data Analysis 51 1614–1622
Wikramaratna R S (1989) ACORN - a new method for generating sequences of uniformly distributed pseudo-random numbers Journal of Computational Physics 83 16–31

5 Arguments

1:   GENID – INTEGERInput
On entry: must contain the type of base generator to use.
GENID=1
NAG basic generator.
GENID=2
Wichmann Hill I generator.
GENID=3
Mersenne Twister.
GENID=4
Wichmann Hill II generator.
GENID=5
ACORN generator.
GENID=6
L'Ecuyer MRG32k3a generator.
See the G05 Chapter Introduction for details of each of the base generators.
Constraint: GENID=1, 2, 3, 4, 5 or 6.
2:   SUBID – INTEGERInput
On entry: if GENID=2, SUBID indicates which of the 273 sub-generators to use. In this case, the SUBID +272 mod 273 + 1 sub-generator is used.
If GENID=5, SUBID indicates the values of k and p to use, where k is the order of the generator, and p controls the size of the modulus, M, with M = 2 p×30 . If SUBID<1, the default values of k=10 and p=2 are used, otherwise values for k and p are calculated from the formula, SUBID=k+1000 p-1.
If GENID=6 and SUBID mod 2=0 the range of the generator is set to 0,1, otherwise the range is set to 0,1; in this case the sequence is identical to the implementation of MRG32k3a in TestU01 (see L'Ecuyer and Simard (2002)) for identical seeds.
For all other values of GENID, SUBID is not referenced.
3:   STATE LSTATE – INTEGER arrayCommunication Array
On exit: contains information on the selected base generator and its current state.
4:   LSTATE – INTEGERInput/Output
On entry: the dimension of the STATE array, or a value <1. If the Mersenne Twister (GENID=3) is being used and the skip ahead routine G05KJF or G05KKF will be called subsequently, then you must ensure that LSTATE≥1260.
On exit: if LSTATE<1 on entry, then the required length of the STATE array for the chosen base generator, otherwise LSTATE is unchanged. When GENID=3 (Mersenne Twister) a value of 1260 is returned, allowing for the skip ahead routine to be subsequently called. In all other cases the minimum length, as documented in the constraints below, is returned.
Constraints:
  • if GENID=1, LSTATE≥17;
  • if GENID=2, LSTATE≥21;
  • if GENID=3, LSTATE≥633;
  • if GENID=4, LSTATE≥29;
  • if GENID=5, LSTATE≥max k+1×p+9,14+3, where k and p are defined by SUBID;
  • if GENID=6, LSTATE≥61;
  • otherwise LSTATE<1.
5:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
On exit: IFAIL=0 or -1 unless the routine detects an error or a warning has been flagged (see Section 6).
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, GENID=value.
Constraint: GENID=1, 2, 3, 4, 5 or 6.
IFAIL=4
On entry, LSTATE=value.
Constraint: LSTATE≤0 or LSTATE≥value.
IFAIL=-1
Required length of STATE array returned in LSTATE but STATE array not initialized.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

Not applicable.

8 Parallelism and Performance

G05KGF is not threaded in any implementation.

9 Further Comments

None.

10 Example

In order to preserve the statistical properties of the base generators, G05KGF should only be called once. If multiple streams of values are required then one of the methods described in Section 2.1.1 in the G05 Chapter Introduction should be used.
However, for illustrative purposes only, this example calls G05KGF twice. At each call a sample of 500 values from a discrete uniform distribution are generated and then the two samples are compared.

10.1 Program Text

Program Text (g05kgfe.f90)

10.2 Program Data

None.

10.3 Program Results

Program Results (g05kgfe.r)

G05 Chapter Contents
G05 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


G05KHF : NAG Library, Mark 26

G05 Chapter Contents
G05 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

G05KHF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

G05KHF allows for the generation of multiple, independent, sequences of pseudorandom numbers using the leap-frog method.

2 Specification

SUBROUTINE G05KHF ( N, K, STATE, IFAIL)
INTEGER N, K, STATE(*), IFAIL

3 Description

G05KHF adjusts a base generator to allow multiple, independent, sequences of pseudorandom numbers to be generated via the leap-frog method (see the G05 Chapter Introduction for details).
If, prior to calling G05KHF the base generator defined by STATE would produce random numbers x 1 , x 2 , x 3 , … , then after calling G05KHF the generator will produce random numbers xk , x k+n , x k+2 n , x k+3 n , … .
One of the initialization routines G05KFF (for a repeatable sequence if computed sequentially) or G05KGF (for a non-repeatable sequence) must be called prior to the first call to G05KHF.
The leap-frog algorithm can be used in conjunction with the NAG basic generator, both the Wichmann–Hill I and Wichmann–Hill II generators, the Mersenne Twister and L'Ecuyer.

4 References

Knuth D E (1981) The Art of Computer Programming (Volume 2) (2nd Edition) Addison–Wesley

5 Arguments

1:   N – INTEGERInput
On entry: n, the total number of sequences required.
Constraint: N>0.
2:   K – INTEGERInput
On entry: k, the number of the current sequence.
Constraint: 0<K≤N.
3:   STATE* – INTEGER arrayCommunication Array
Note: the actual argument supplied must be the array STATE supplied to the initialization routines G05KFF or G05KGF.
On entry: contains information on the selected base generator and its current state.
On exit: contains updated information on the state of the generator.
4:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, N=value.
Constraint: N≥1.
IFAIL=2
On entry, K=value and N=value.
Constraint: 0<K≤N.
IFAIL=3
On entry, STATE vector has been corrupted or not initialized.
IFAIL=4
On entry, cannot use leap-frog with the base generator defined by STATE.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

Not applicable.

8 Parallelism and Performance

G05KHF is not threaded in any implementation.

9 Further Comments

The leap-frog method tends to be less efficient than other methods of producing multiple, independent sequences. See the G05 Chapter Introduction for alternative choices.

10 Example

This example creates three independent sequences using G05KHF, after initialization by G05KFF. Five variates from a uniform distribution are then generated from each sequence using G05SAF.

10.1 Program Text

Program Text (g05khfe.f90)

10.2 Program Data

Program Data (g05khfe.d)

10.3 Program Results

Program Results (g05khfe.r)

G05 Chapter Contents
G05 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


G05KJF : NAG Library, Mark 26

G05 Chapter Contents
G05 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

G05KJF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

G05KJF allows for the generation of multiple, independent, sequences of pseudorandom numbers using the skip-ahead method.
The base pseudorandom number sequence defined by STATE is advanced n places.

2 Specification

SUBROUTINE G05KJF ( N, STATE, IFAIL)
INTEGER N, STATE(*), IFAIL

3 Description

G05KJF adjusts a base generator to allow multiple, independent, sequences of pseudorandom numbers to be generated via the skip-ahead method (see the G05 Chapter Introduction for details).
If, prior to calling G05KJF the base generator defined by STATE would produce random numbers x 1 , x 2 , x 3 , … , then after calling G05KJF the generator will produce random numbers x n+1 , x n+2 , x n+3 , … .
One of the initialization routines G05KFF (for a repeatable sequence if computed sequentially) or G05KGF (for a non-repeatable sequence) must be called prior to the first call to G05KJF.
The skip-ahead algorithm can be used in conjunction with any of the six base generators discussed in Chapter G05.

4 References

Haramoto H, Matsumoto M, Nishimura T, Panneton F and L'Ecuyer P (2008) Efficient jump ahead for F2-linear random number generators INFORMS J. on Computing 20(3) 385–390
Knuth D E (1981) The Art of Computer Programming (Volume 2) (2nd Edition) Addison–Wesley

5 Arguments

1:   N – INTEGERInput
On entry: n, the number of places to skip ahead.
Constraint: N≥0.
2:   STATE* – INTEGER arrayCommunication Array
Note: the actual argument supplied must be the array STATE supplied to the initialization routines G05KFF or G05KGF.
On entry: contains information on the selected base generator and its current state.
On exit: contains updated information on the state of the generator.
3:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, N=value.
Constraint: N≥0.
IFAIL=2
On entry, STATE vector has been corrupted or not initialized.
IFAIL=3
On entry, cannot use skip-ahead with the base generator defined by STATE.
IFAIL=4
On entry, the base generator is Mersenne Twister, but the STATE vector defined on initialization is not large enough to perform a skip ahead. See the initialization routine G05KFF or G05KGF.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

Not applicable.

8 Parallelism and Performance

G05KJF is not threaded in any implementation.

9 Further Comments

Calling G05KJF and then generating a series of uniform values using G05SAF is more efficient than, but equivalent to, calling G05SAF and discarding the first n values. This may not be the case for distributions other than the uniform, as some distributional generators require more than one uniform variate to generate a single draw from the required distribution.
To skip ahead k×m places you can either
(a) | call G05KJF once with N=k×m, or
(b) | call G05KJF k times with N=m, using the STATE vector output by the previous call as input to the next call
both approaches would result in the same sequence of values. When working in a multithreaded environment, where you want to generate (at most) m values on each of K threads, this would translate into either
(a) | spawning the K threads and calling G05KJF once on each thread with N=k-1×m, where k is a thread ID, taking a value between 1 and K, or
(b) | calling G05KJF on a single thread with N=m, spawning the K threads and then calling G05KJF a further k-1 times on each of the thread.
Due to the way skip ahead is implemented for the Mersenne Twister, approach (a) will tend to be more efficient if more than 30 threads are being used (i.e., K>30), otherwise approach (b) should probably be used. For all other base generators, approach (a) should be used. See the G05 Chapter Introduction for more details.

10 Example

This example initializes a base generator using G05KFF and then uses G05KJF to advance the sequence 50 places before generating five variates from a uniform distribution using G05SAF.

10.1 Program Text

Program Text (g05kjfe.f90)

10.2 Program Data

Program Data (g05kjfe.d)

10.3 Program Results

Program Results (g05kjfe.r)

G05 Chapter Contents
G05 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


G05KKF : NAG Library, Mark 26

G05 Chapter Contents
G05 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

G05KKF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

G05KKF allows for the generation of multiple, independent, sequences of pseudorandom numbers using the skip-ahead method. The base pseudorandom number sequence defined by STATE is advanced 2 n places.

2 Specification

SUBROUTINE G05KKF ( N, STATE, IFAIL)
INTEGER N, STATE(*), IFAIL

3 Description

G05KKF adjusts a base generator to allow multiple, independent, sequences of pseudorandom numbers to be generated via the skip-ahead method (see the G05 Chapter Introduction for details).
If, prior to calling G05KKF the base generator defined by STATE would produce random numbers x 1 , x 2 , x 3 , … , then after calling G05KKF the generator will produce random numbers x 2 n+1 , x 2 n+2 , x 2 n+3 , … .
One of the initialization routines G05KFF (for a repeatable sequence if computed sequentially) or G05KGF (for a non-repeatable sequence) must be called prior to the first call to G05KKF.
The skip-ahead algorithm can be used in conjunction with any of the six base generators discussed in the G05 Chapter Introduction.

4 References

Haramoto H, Matsumoto M, Nishimura T, Panneton F and L'Ecuyer P (2008) Efficient jump ahead for F2-linear random number generators INFORMS J. on Computing 20(3) 385–390
Knuth D E (1981) The Art of Computer Programming (Volume 2) (2nd Edition) Addison–Wesley

5 Arguments

1:   N – INTEGERInput
On entry: n, where the number of places to skip-ahead is defined as 2 n.
Constraint: N≥0.
2:   STATE* – INTEGER arrayCommunication Array
Note: the actual argument supplied must be the array STATE supplied to the initialization routines G05KFF or G05KGF.
On entry: contains information on the selected base generator and its current state.
On exit: contains updated information on the state of the generator.
3:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, N=value.
Constraint: N≥0.
IFAIL=2
On entry, STATE vector has been corrupted or not initialized.
IFAIL=3
On entry, cannot use skip-ahead with the base generator defined by STATE.
IFAIL=4
On entry, the STATE vector defined on initialization is not large enough to perform a skip-ahead (applies to Mersenne Twister base generator). See the initialization routine G05KFF or G05KGF.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

Not applicable.

8 Parallelism and Performance

G05KKF is not threaded in any implementation.

9 Further Comments

Calling G05KKF and then generating a series of uniform values using G05SAF is equivalent to, but more efficient than, calling G05SAF and discarding the first 2 n values. This may not be the case for distributions other than the uniform, as some distributional generators require more than one uniform variate to generate a single draw from the required distribution.

10 Example

This example initializes a base generator using G05KFF and then uses G05KKF to advance the sequence 217 places before generating five variates from a uniform distribution using G05SAF.

10.1 Program Text

Program Text (g05kkfe.f90)

10.2 Program Data

Program Data (g05kkfe.d)

10.3 Program Results

Program Results (g05kkfe.r)

G05 Chapter Contents
G05 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


G05NCF : NAG Library, Mark 26

G05 Chapter Contents
G05 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

G05NCF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

G05NCF performs a pseudorandom permutation of a vector of integers.

2 Specification

SUBROUTINE G05NCF ( INDX, N, STATE, IFAIL)
INTEGER INDX(N), N, STATE(*), IFAIL

3 Description

G05NCF permutes the elements of an integer array without inspecting their values. Each of the n! possible permutations of the n values may be regarded as being equally probable.
Even for modest values of n it is theoretically impossible that all n! permutations may occur, as n! is likely to exceed the cycle length of any of the base generators. For practical purposes this is irrelevant, as the time necessary to generate all possible permutations is many millenia.
One of the initialization routines G05KFF (for a repeatable sequence if computed sequentially) or G05KGF (for a non-repeatable sequence) must be called prior to the first call to G05NCF.

4 References

Kendall M G and Stuart A (1969) The Advanced Theory of Statistics (Volume 1) (3rd Edition) Griffin
Knuth D E (1981) The Art of Computer Programming (Volume 2) (2nd Edition) Addison–Wesley

5 Arguments

1:   INDX N – INTEGER arrayInput/Output
On entry: the n integer values to be permuted.
On exit: the n permuted integer values.
2:   N – INTEGERInput
On entry: the number of values to be permuted.
Constraint: N≥1.
3:   STATE* – INTEGER arrayCommunication Array
Note: the actual argument supplied must be the array STATE supplied to the initialization routines G05KFF or G05KGF.
On entry: contains information on the selected base generator and its current state.
On exit: contains updated information on the state of the generator.
4:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=2
On entry, N=value.
Constraint: N≥1.
IFAIL=3
On entry, STATE vector has been corrupted or not initialized.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

Not applicable.

8 Parallelism and Performance

G05NCF is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

None.

10 Example

In the example program a vector containing the first eight positive integers in ascending order is permuted by a call to G05NCF and the permutation is printed. This is repeated a total of ten times, after initialization by G05KFF.

10.1 Program Text

Program Text (g05ncfe.f90)

10.2 Program Data

Program Data (g05ncfe.d)

10.3 Program Results

Program Results (g05ncfe.r)

G05 Chapter Contents
G05 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


G05NDF : NAG Library, Mark 26

G05 Chapter Contents
G05 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

G05NDF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

G05NDF selects a pseudorandom sample without replacement from an integer vector.

2 Specification

SUBROUTINE G05NDF ( IPOP, N, ISAMPL, M, STATE, IFAIL)
INTEGER IPOP(N), N, ISAMPL(M), M, STATE(*), IFAIL

3 Description

G05NDF selects m elements from a population vector IPOP of length n and places them in a sample vector ISAMPL. Their order in IPOP will be preserved in ISAMPL. Each of the n m possible combinations of elements of ISAMPL may be regarded as being equally probable.
For moderate or large values of n it is theoretically impossible that all combinations of size m may occur, unless m is near 1 or near n. This is because n m exceeds the cycle length of any of the base generators. For practical purposes this is irrelevant, as the time taken to generate all possible combinations is many millenia.
One of the initialization routines G05KFF (for a repeatable sequence if computed sequentially) or G05KGF (for a non-repeatable sequence) must be called prior to the first call to G05NDF.

4 References

Kendall M G and Stuart A (1969) The Advanced Theory of Statistics (Volume 1) (3rd Edition) Griffin
Knuth D E (1981) The Art of Computer Programming (Volume 2) (2nd Edition) Addison–Wesley

5 Arguments

1:   IPOP N – INTEGER arrayInput
On entry: the population to be sampled.
2:   N – INTEGERInput
On entry: the number of elements in the population vector to be sampled.
Constraint: N≥1.
3:   ISAMPL M – INTEGER arrayOutput
On exit: the selected sample.
4:   M – INTEGERInput
On entry: the sample size.
Constraint: 1≤M≤N.
5:   STATE* – INTEGER arrayCommunication Array
Note: the actual argument supplied must be the array STATE supplied to the initialization routines G05KFF or G05KGF.
On entry: contains information on the selected base generator and its current state.
On exit: contains updated information on the state of the generator.
6:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=2
On entry, N=value.
Constraint: N≥1.
IFAIL=4
On entry, M=value and N=value.
Constraint: 1≤M≤N.
IFAIL=5
On entry, STATE vector has been corrupted or not initialized.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

Not applicable.

8 Parallelism and Performance

G05NDF is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The time taken by G05NDF is of order n.
In order to sample other kinds of vectors, or matrices of higher dimension, the following technique may be used:
(a) | set IPOP i=i, for i=1,2,…,n;
(b) | use G05NDF to take a sample from IPOP and put it into ISAMPL;
(c) | use the contents of ISAMPL as a set of indices to access the relevant vector or matrix.
In order to divide a population into several groups, G05NCF is more efficient.

10 Example

In the example program random samples of size 1,2,…,8 are selected from a vector containing the first eight positive integers in ascending order. The samples are generated and printed for each sample size by a call to G05NDF after initialization by G05KFF.

10.1 Program Text

Program Text (g05ndfe.f90)

10.2 Program Data

Program Data (g05ndfe.d)

10.3 Program Results

Program Results (g05ndfe.r)

G05 Chapter Contents
G05 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


G05NEF : NAG Library, Mark 26

G05 Chapter Contents
G05 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

G05NEF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

G05NEF selects a pseudorandom sample, without replacement and allowing for unequal probabilities.

2 Specification

SUBROUTINE G05NEF ( ORDER, WT, POP, IPOP, N, ISAMPL, M, STATE, IFAIL)
INTEGER | IPOP(*), N, ISAMPL(M), M, STATE(*), IFAIL
REAL (KIND=nag_wp) | WT(N)
CHARACTER(1) | ORDER, POP

3 Description

G05NEF selects m elements from either the set of values 1,2,…,n or a supplied population vector of length n. The probability of selecting the ith element is proportional to a user-supplied weight, wi. Each element will appear at most once in the sample, i.e., the sampling is done without replacement.
One of the initialization routines G05KFF (for a repeatable sequence if computed sequentially) or G05KGF (for a non-repeatable sequence) must be called prior to the first call to G05NEF.

4 References

None.

5 Arguments

1:   ORDER – CHARACTER(1)Input
On entry: a flag indicating the sorted status of the WT vector.
ORDER='A'
WT is sorted in ascending order,
ORDER='D'
WT is sorted in descending order,
ORDER='U'
WT is unsorted and G05NEF will sort the weights prior to using them.
Irrespective of the value of ORDER, no checks are made on the sorted status of WT, e.g., it is possible to supply ORDER='A', even when WT is not sorted. In such cases the WT array will not be sorted internally, but G05NEF will still work correctly except, possibly, in cases of extreme weight values.
It is usually more efficient to specify a value of ORDER that is consistent with the status of WT.
Constraint: ORDER='A', 'D' or 'U'.
2:   WT N – REAL (KIND=nag_wp) arrayInput
On entry: wi, the relative probability weights. These weights need not sum to 1.0.
Constraints:
  • WT i≥0.0, for i=1,2,…,N;
  • at least M values must be nonzero.
3:   POP – CHARACTER(1)Input
On entry: a flag indicating whether a population to be sampled has been supplied.
POP='D'
the population is assumed to be the integers 1,2,…,N and IPOP is not referenced,
POP='S'
the population must be supplied in IPOP.
Constraint: POP='D' or 'S'.
4:   IPOP* – INTEGER arrayInput
Note: the dimension of the array IPOP must be at least N if POP='S'.
On entry: the population to be sampled. If POP='D' then the population is assumed to be the set of values 1,2,…,N and the array IPOP is not referenced. Elements of IPOP with the same value are not combined, therefore if WT i≠0,WT j≠0 and i≠j then there is a nonzero probability that the sample will contain both IPOP i and IPOP j. If IPOP i=IPOP j then that value can appear in ISAMPL more than once.
5:   N – INTEGERInput
On entry: n, the size of the population.
Constraint: N≥1.
6:   ISAMPL M – INTEGER arrayOutput
On exit: the selected sample.
7:   M – INTEGERInput
On entry: m, the size of the sample required.
Constraint: 0≤M≤N.
8:   STATE* – INTEGER arrayCommunication Array
Note: the actual argument supplied must be the array STATE supplied to the initialization routines G05KFF or G05KGF.
On entry: contains information on the selected base generator and its current state.
On exit: contains updated information on the state of the generator.
9:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, ORDER=value was an illegal value.
On entry, ORDER had an illegal value.
IFAIL=2
On entry, at least one weight was less than zero.
IFAIL=3
On entry, POP had an illegal value.
IFAIL=5
On entry, N=value.
Constraint: N≥1.
IFAIL=7
On entry, M=value and N=value.
Constraint: 0≤M≤N.
IFAIL=8
On entry, STATE vector has been corrupted or not initialized.
IFAIL=21
On entry, M=value, number of nonzero weights =value.
Constraint: must be at least M nonzero weights.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

Not applicable.

8 Parallelism and Performance

G05NEF is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

G05NEF internally allocates N+1 reals and N integers.
Although it is possible to use G05NEF to sample using equal probabilities, by setting all elements of the input array WT to the same positive value, it is more efficient to use G05NDF. To sample with replacement, G05TDF can be used when the probabilities are unequal and G05TLF when the probabilities are equal.

10 Example

This example samples from a population of 25.

10.1 Program Text

Program Text (g05nefe.f90)

10.2 Program Data

Program Data (g05nefe.d)

10.3 Program Results

Program Results (g05nefe.r)

G05 Chapter Contents
G05 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


G05PDF : NAG Library, Mark 26

G05 Chapter Contents
G05 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

G05PDF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

G05PDF generates a given number of terms of a type I AGARCH p,q process (see Engle and Ng (1993)).

2 Specification

SUBROUTINE G05PDF ( DIST, NUM, IP, IQ, THETA, GAMMA, DF, HT, ET, FCALL, R, LR, STATE, IFAIL)
INTEGER | NUM, IP, IQ, DF, LR, STATE(*), IFAIL
REAL (KIND=nag_wp) | THETA(IQ+IP+1), GAMMA, HT(NUM), ET(NUM), R(LR)
LOGICAL | FCALL
CHARACTER(1) | DIST

3 Description

A type I AGARCH p,q process can be represented by:
ht = α 0 + ∑i=1 q αi ε t-i + γ 2 + ∑i=1 p βi h t-i ,   t=1,2,…,T ;
where εt∣ ψ t-1 = N 0,ht or εt∣ ψ t-1= St df,ht . Here St is a standardized Student's t-distribution with df degrees of freedom and variance ht, T is the number of observations in the sequence, εt is the observed value of the GARCH p,q process at time t, ht is the conditional variance at time t, and ψt the set of all information up to time t. Symmetric GARCH sequences are generated when γ is zero, otherwise asymmetric GARCH sequences are generated with γ specifying the amount by which positive (or negative) shocks are to be enhanced.
One of the initialization routines G05KFF (for a repeatable sequence if computed sequentially) or G05KGF (for a non-repeatable sequence) must be called prior to the first call to G05PDF.

4 References

Bollerslev T (1986) Generalised autoregressive conditional heteroskedasticity Journal of Econometrics 31 307–327
Engle R (1982) Autoregressive conditional heteroskedasticity with estimates of the variance of United Kingdom inflation Econometrica 50 987–1008
Engle R and Ng V (1993) Measuring and testing the impact of news on volatility Journal of Finance 48 1749–1777
Hamilton J (1994) Time Series Analysis Princeton University Press

5 Arguments

1:   DIST – CHARACTER(1)Input
On entry: the type of distribution to use for εt.
DIST='N'
A Normal distribution is used.
DIST='T'
A Student's t-distribution is used.
Constraint: DIST='N' or 'T'.
2:   NUM – INTEGERInput
On entry: T, the number of terms in the sequence.
Constraint: NUM≥0.
3:   IP – INTEGERInput
On entry: the number of coefficients, βi, for i=1,2,…,p.
Constraint: IP≥0.
4:   IQ – INTEGERInput
On entry: the number of coefficients, αi, for i=1,2,…,q.
Constraint: IQ≥1.
5:   THETA IQ+IP+1 – REAL (KIND=nag_wp) arrayInput
On entry: the first element must contain the coefficient αo, the next IQ elements must contain the coefficients αi, for i=1,2,…,q. The remaining IP elements must contain the coefficients βj, for j=1,2,…,p.
Constraints:
  • ∑ i=2 IQ+IP+1 THETA i<1.0;
  • THETA i≥0.0, for i=2,3,…,IP+IQ+1.
6:   GAMMA – REAL (KIND=nag_wp)Input
On entry: the asymmetry parameter γ for the GARCH p,q sequence.
7:   DF – INTEGERInput
On entry: the number of degrees of freedom for the Student's t-distribution.
If DIST='N', DF is not referenced.
Constraint: if DIST='T', DF>2.
8:   HT NUM – REAL (KIND=nag_wp) arrayOutput
On exit: the conditional variances ht, for t=1,2,…,T, for the GARCH p,q sequence.
9:   ET NUM – REAL (KIND=nag_wp) arrayOutput
On exit: the observations εt, for t=1,2,…,T, for the GARCH p,q sequence.
10:   FCALL – LOGICALInput
On entry: if FCALL=.TRUE., a new sequence is to be generated, otherwise a given sequence is to be continued using the information in R.
11:   R LR – REAL (KIND=nag_wp) arrayInput/Output
On entry: the array contains information required to continue a sequence if FCALL=.FALSE..
On exit: contains information that can be used in a subsequent call of G05PDF, with FCALL=.FALSE..
12:   LR – INTEGERInput
On entry: the dimension of the array R as declared in the (sub)program from which G05PDF is called.
Constraint: LR≥2×IP+IQ+2.
13:   STATE* – INTEGER arrayCommunication Array
Note: the actual argument supplied must be the array STATE supplied to the initialization routines G05KFF or G05KGF.
On entry: contains information on the selected base generator and its current state.
On exit: contains updated information on the state of the generator.
14:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, DIST is not valid: DIST=value.
IFAIL=2
On entry, NUM=value.
Constraint: NUM≥0.
IFAIL=3
On entry, IP=value.
Constraint: IP≥0.
IFAIL=4
On entry, IQ=value.
Constraint: IQ≥1.
IFAIL=5
On entry, THETA value=value.
Constraint: THETA i≥0.0.
IFAIL=7
On entry, DF=value.
Constraint: DF≥3.
IFAIL=11
IP or IQ is not the same as when R was set up in a previous call.
Previous value of IP=value and IP=value.
Previous value of IQ=value and IQ=value.
IFAIL=12
On entry, LR is not large enough, LR=value: minimum length required =value.
IFAIL=13
On entry, STATE vector has been corrupted or not initialized.
IFAIL=51
On entry, sum of THETA i, for i=2,3,…,IP+IQ+1 is ≥1.0: sum=value.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

Not applicable.

8 Parallelism and Performance

G05PDF is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

None.

10 Example

This example first calls G05KFF to initialize a base generator then calls G05PDF to generate two realizations, each consisting of ten observations, from a symmetric GARCH 1,1 model.

10.1 Program Text

Program Text (g05pdfe.f90)

10.2 Program Data

Program Data (g05pdfe.d)

10.3 Program Results

Program Results (g05pdfe.r)

G05 Chapter Contents
G05 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


G05PEF : NAG Library, Mark 26

G05 Chapter Contents
G05 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

G05PEF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

G05PEF generates a given number of terms of a type II AGARCH p,q process (see Engle and Ng (1993)).

2 Specification

SUBROUTINE G05PEF ( DIST, NUM, IP, IQ, THETA, GAMMA, DF, HT, ET, FCALL, R, LR, STATE, IFAIL)
INTEGER | NUM, IP, IQ, DF, LR, STATE(*), IFAIL
REAL (KIND=nag_wp) | THETA(IQ+IP+1), GAMMA, HT(NUM), ET(NUM), R(LR)
LOGICAL | FCALL
CHARACTER(1) | DIST

3 Description

A type II AGARCH p,q process can be represented by:
ht = α 0 + ∑ i=1 q αi ε t-i+γ ε t-i 2 + ∑ i=1 p βi h t-i ,   t=1,2,…,T ;
where εt∣ ψ t-1 = N 0,ht or εt∣ ψ t-1= St df,ht . Here St is a standardized Student's t-distribution with df degrees of freedom and variance ht, T is the number of observations in the sequence, εt is the observed value of the GARCH p,q process at time t, ht is the conditional variance at time t, and ψt the set of all information up to time t. Symmetric GARCH sequences are generated when γ is zero, otherwise asymmetric GARCH sequences are generated with γ specifying the amount by which positive (or negative) shocks are to be enhanced.
One of the initialization routines G05KFF (for a repeatable sequence if computed sequentially) or G05KGF (for a non-repeatable sequence) must be called prior to the first call to G05PEF.

4 References

Bollerslev T (1986) Generalised autoregressive conditional heteroskedasticity Journal of Econometrics 31 307–327
Engle R (1982) Autoregressive conditional heteroskedasticity with estimates of the variance of United Kingdom inflation Econometrica 50 987–1008
Engle R and Ng V (1993) Measuring and testing the impact of news on volatility Journal of Finance 48 1749–1777
Hamilton J (1994) Time Series Analysis Princeton University Press

5 Arguments

1:   DIST – CHARACTER(1)Input
On entry: the type of distribution to use for εt.
DIST='N'
A Normal distribution is used.
DIST='T'
A Student's t-distribution is used.
Constraint: DIST='N' or 'T'.
2:   NUM – INTEGERInput
On entry: T, the number of terms in the sequence.
Constraint: NUM≥0.
3:   IP – INTEGERInput
On entry: the number of coefficients, βi, for i=1,2,…,p.
Constraint: IP≥0.
4:   IQ – INTEGERInput
On entry: the number of coefficients, αi, for i=1,2,…,q.
Constraint: IQ≥1.
5:   THETA IQ+IP+1 – REAL (KIND=nag_wp) arrayInput
On entry: the first element must contain the coefficient αo, the next IQ elements must contain the coefficients αi, for i=1,2,…,q. The remaining IP elements must contain the coefficients βj, for j=1,2,…,p.
Constraints:
  • ∑ i=2 IQ+IP+1 THETA i<1.0;
  • THETA i≥0.0, for i=2,3,…,IP+IQ+1.
6:   GAMMA – REAL (KIND=nag_wp)Input
On entry: the asymmetry parameter γ for the GARCH p,q sequence.
7:   DF – INTEGERInput
On entry: the number of degrees of freedom for the Student's t-distribution.
If DIST='N', DF is not referenced.
Constraint: if DIST='T', DF>2.
8:   HT NUM – REAL (KIND=nag_wp) arrayOutput
On exit: the conditional variances ht, for t=1,2,…,T, for the GARCH p,q sequence.
9:   ET NUM – REAL (KIND=nag_wp) arrayOutput
On exit: the observations εt, for t=1,2,…,T, for the GARCH p,q sequence.
10:   FCALL – LOGICALInput
On entry: if FCALL=.TRUE., a new sequence is to be generated, otherwise a given sequence is to be continued using the information in R.
11:   R LR – REAL (KIND=nag_wp) arrayInput/Output
On entry: the array contains information required to continue a sequence if FCALL=.FALSE..
On exit: contains information that can be used in a subsequent call of G05PEF, with FCALL=.FALSE..
12:   LR – INTEGERInput
On entry: the dimension of the array R as declared in the (sub)program from which G05PEF is called.
Constraint: LR≥2×IP+IQ+2.
13:   STATE* – INTEGER arrayCommunication Array
Note: the actual argument supplied must be the array STATE supplied to the initialization routines G05KFF or G05KGF.
On entry: contains information on the selected base generator and its current state.
On exit: contains updated information on the state of the generator.
14:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, DIST is not valid: DIST=value.
IFAIL=2
On entry, NUM=value.
Constraint: NUM≥0.
IFAIL=3
On entry, IP=value.
Constraint: IP≥0.
IFAIL=4
On entry, IQ=value.
Constraint: IQ≥1.
IFAIL=5
On entry, THETA value=value.
Constraint: THETA i≥0.0.
IFAIL=7
On entry, DF=value.
Constraint: DF≥3.
IFAIL=11
IP or IQ is not the same as when R was set up in a previous call.
Previous value of IP=value and IP=value.
Previous value of IQ=value and IQ=value.
IFAIL=12
On entry, LR is not large enough, LR=value: minimum length required =value.
IFAIL=13
On entry, STATE vector has been corrupted or not initialized.
IFAIL=51
On entry, sum of THETA i, for i=2,3,…,IP+IQ+1 is ≥1.0: sum=value.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

Not applicable.

8 Parallelism and Performance

G05PEF is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

None.

10 Example

This example first calls G05KFF to initialize a base generator then calls G05PEF to generate two realizations, each consisting of ten observations, from an asymmetric GARCH 1,1 model.

10.1 Program Text

Program Text (g05pefe.f90)

10.2 Program Data

Program Data (g05pefe.d)

10.3 Program Results

Program Results (g05pefe.r)

G05 Chapter Contents
G05 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


G05PFF : NAG Library, Mark 26

G05 Chapter Contents
G05 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

G05PFF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

G05PFF generates a given number of terms of a GJR GARCH p,q process (see Glosten et al. (1993)).

2 Specification

SUBROUTINE G05PFF ( DIST, NUM, IP, IQ, THETA, GAMMA, DF, HT, ET, FCALL, R, LR, STATE, IFAIL)
INTEGER | NUM, IP, IQ, DF, LR, STATE(*), IFAIL
REAL (KIND=nag_wp) | THETA(IQ+IP+1), GAMMA, HT(NUM), ET(NUM), R(LR)
LOGICAL | FCALL
CHARACTER(1) | DIST

3 Description

A GJR GARCH p,q process is represented by:
ht = α 0 + ∑i=1 q αi + γ I t-i ε t-i 2 + ∑ i=1 p βi h t-i ,   t=1,2,…,T ;
where It=1 if εt<0, It=0 if εt≥0, and εt∣ψ t-1=N 0,ht or εt∣ψ t-1=St df,ht. Here St is a standardized Student's t-distribution with df degrees of freedom and variance ht, T is the number of observations in the sequence, εt is the observed value of the GARCH p,q process at time t, ht is the conditional variance at time t, and ψt the set of all information up to time t. Symmetric GARCH sequences are generated when γ is zero, otherwise asymmetric GARCH sequences are generated with γ specifying the amount by which negative shocks are to be enhanced.
One of the initialization routines G05KFF (for a repeatable sequence if computed sequentially) or G05KGF (for a non-repeatable sequence) must be called prior to the first call to G05PFF.

4 References

Bollerslev T (1986) Generalised autoregressive conditional heteroskedasticity Journal of Econometrics 31 307–327
Engle R (1982) Autoregressive conditional heteroskedasticity with estimates of the variance of United Kingdom inflation Econometrica 50 987–1008
Engle R and Ng V (1993) Measuring and testing the impact of news on volatility Journal of Finance 48 1749–1777
Glosten L, Jagannathan R and Runkle D (1993) Relationship between the expected value and the volatility of nominal excess return on stocks Journal of Finance 48 1779–1801
Hamilton J (1994) Time Series Analysis Princeton University Press

5 Arguments

1:   DIST – CHARACTER(1)Input
On entry: the type of distribution to use for εt.
DIST='N'
A Normal distribution is used.
DIST='T'
A Student's t-distribution is used.
Constraint: DIST='N' or 'T'.
2:   NUM – INTEGERInput
On entry: T, the number of terms in the sequence.
Constraint: NUM>0.
3:   IP – INTEGERInput
On entry: the number of coefficients, βi, for i=1,2,…,p.
Constraint: IP≥0.
4:   IQ – INTEGERInput
On entry: the number of coefficients, αi, for i=1,2,…,q.
Constraint: IQ≥1.
5:   THETA IQ+IP+1 – REAL (KIND=nag_wp) arrayInput
On entry: the first element must contain the coefficient αo, the next IQ elements must contain the coefficients αi, for i=1,2,…,q. The remaining IP elements must contain the coefficients βj, for j=1,2,…,p.
Constraints:
  • ∑ i=2 IQ+IP+1 THETA i<1.0;
  • THETA i≥0.0, for i=1 and i=IQ+2,…,IQ+IP+1.
6:   GAMMA – REAL (KIND=nag_wp)Input
On entry: the asymmetry parameter γ for the GARCH p,q sequence.
Constraint: GAMMA+THETA i≥0.0, for i=2,3,…,IQ+1.
7:   DF – INTEGERInput
On entry: the number of degrees of freedom for the Student's t-distribution.
If DIST='N', DF is not referenced.
Constraint: if DIST='T', DF>2.
8:   HT NUM – REAL (KIND=nag_wp) arrayOutput
On exit: the conditional variances ht, for t=1,2,…,T, for the GARCH p,q sequence.
9:   ET NUM – REAL (KIND=nag_wp) arrayOutput
On exit: the observations εt, for t=1,2,…,T, for the GARCH p,q sequence.
10:   FCALL – LOGICALInput
On entry: if FCALL=.TRUE., a new sequence is to be generated, otherwise a given sequence is to be continued using the information in R.
11:   R LR – REAL (KIND=nag_wp) arrayInput/Output
On entry: the array contains information required to continue a sequence if FCALL=.FALSE..
On exit: contains information that can be used in a subsequent call of G05PFF, with FCALL=.FALSE..
12:   LR – INTEGERInput
On entry: the dimension of the array R as declared in the (sub)program from which G05PFF is called.
Constraint: LR≥2×IP+IQ+2.
13:   STATE* – INTEGER arrayCommunication Array
Note: the actual argument supplied must be the array STATE supplied to the initialization routines G05KFF or G05KGF.
On entry: contains information on the selected base generator and its current state.
On exit: contains updated information on the state of the generator.
14:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, DIST is not valid: DIST=value.
IFAIL=2
On entry, NUM=value.
Constraint: NUM≥0.
IFAIL=3
On entry, IP=value.
Constraint: IP≥0.
IFAIL=4
On entry, IQ=value.
Constraint: IQ≥1.
IFAIL=5
On entry, THETA value=value and γ=value.
Constraint: αi+γ≥0.
IFAIL=7
On entry, DF=value.
Constraint: DF≥3.
IFAIL=11
IP or IQ is not the same as when R was set up in a previous call.
Previous value of IP=value and IP=value.
Previous value of IQ=value and IQ=value.
IFAIL=12
On entry, LR is not large enough, LR=value: minimum length required =value.
IFAIL=13
On entry, STATE vector has been corrupted or not initialized.
IFAIL=51
On entry, THETA value=value.
Constraint: THETA i≥0.0.
IFAIL=52
On entry, sum of THETA i=value.
Constraint: sum of THETA i, for i=1,2,…,IP+IQ is <1.0.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

Not applicable.

8 Parallelism and Performance

G05PFF is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

None.

10 Example

This example first calls G05KFF to initialize a base generator then calls G05PFF to generate two realizations, each consisting of ten observations, from a GJR GARCH 1,1 model.

10.1 Program Text

Program Text (g05pffe.f90)

10.2 Program Data

Program Data (g05pffe.d)

10.3 Program Results

Program Results (g05pffe.r)

G05 Chapter Contents
G05 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


G05PGF : NAG Library, Mark 26

G05 Chapter Contents
G05 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

G05PGF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

G05PGF generates a given number of terms of an exponential GARCH p,q process (see Engle and Ng (1993)).

2 Specification

SUBROUTINE G05PGF ( DIST, NUM, IP, IQ, THETA, DF, HT, ET, FCALL, R, LR, STATE, IFAIL)
INTEGER | NUM, IP, IQ, DF, LR, STATE(*), IFAIL
REAL (KIND=nag_wp) | THETA(2*IQ+IP+1), HT(NUM), ET(NUM), R(LR)
LOGICAL | FCALL
CHARACTER(1) | DIST

3 Description

An exponential GARCH p,q process is represented by:
ln ht=α 0+∑i=1 q αiz t-i+∑i=1 q ϕi z t-i-E z t-i+∑j=1 p βj ln h t-j,  t=1,2,…,T;
where zt= εt ht , E z t-i denotes the expected value of z t-i, and εt∣ψ t-1=N 0,ht or εt∣ψ t-1=St df,ht. Here St is a standardized Student's t-distribution with df degrees of freedom and variance ht, T is the number of observations in the sequence, εt is the observed value of the GARCH p,q process at time t, ht is the conditional variance at time t, and ψt the set of all information up to time t.
One of the initialization routines G05KFF (for a repeatable sequence if computed sequentially) or G05KGF (for a non-repeatable sequence) must be called prior to the first call to G05PGF.

4 References

Bollerslev T (1986) Generalised autoregressive conditional heteroskedasticity Journal of Econometrics 31 307–327
Engle R (1982) Autoregressive conditional heteroskedasticity with estimates of the variance of United Kingdom inflation Econometrica 50 987–1008
Engle R and Ng V (1993) Measuring and testing the impact of news on volatility Journal of Finance 48 1749–1777
Glosten L, Jagannathan R and Runkle D (1993) Relationship between the expected value and the volatility of nominal excess return on stocks Journal of Finance 48 1779–1801
Hamilton J (1994) Time Series Analysis Princeton University Press

5 Arguments

1:   DIST – CHARACTER(1)Input
On entry: the type of distribution to use for εt.
DIST='N'
A Normal distribution is used.
DIST='T'
A Student's t-distribution is used.
Constraint: DIST='N' or 'T'.
2:   NUM – INTEGERInput
On entry: T, the number of terms in the sequence.
Constraint: NUM≥0.
3:   IP – INTEGERInput
On entry: the number of coefficients, βi, for i=1,2,…,p.
Constraint: IP≥0.
4:   IQ – INTEGERInput
On entry: the number of coefficients, αi, for i=1,2,…,q.
Constraint: IQ≥1.
5:   THETA 2×IQ+IP+1 – REAL (KIND=nag_wp) arrayInput
On entry: the initial parameter estimates for the vector θ. The first element must contain the coefficient αo and the next IQ elements must contain the autoregressive coefficients αi, for i=1,2,…,q. The next IQ elements must contain the coefficients ϕi, for i=1,2,…,q. The next IP elements must contain the moving average coefficients βj, for j=1,2,…,p.
Constraints:
  • ∑ i=1 p βi≠1.0;
  • α 0 1- ∑ i=1 p βi ≤ - log X02AMF .
6:   DF – INTEGERInput
On entry: the number of degrees of freedom for the Student's t-distribution.
If DIST='N', DF is not referenced.
Constraint: if DIST='T', DF>2.
7:   HT NUM – REAL (KIND=nag_wp) arrayOutput
On exit: the conditional variances ht, for t=1,2,…,T, for the GARCH p,q sequence.
8:   ET NUM – REAL (KIND=nag_wp) arrayOutput
On exit: the observations εt, for t=1,2,…,T, for the GARCH p,q sequence.
9:   FCALL – LOGICALInput
On entry: if FCALL=.TRUE., a new sequence is to be generated, otherwise a given sequence is to be continued using the information in R.
10:   R LR – REAL (KIND=nag_wp) arrayInput/Output
On entry: the array contains information required to continue a sequence if FCALL=.FALSE..
On exit: contains information that can be used in a subsequent call of G05PGF, with FCALL=.FALSE..
11:   LR – INTEGERInput
On entry: the dimension of the array R as declared in the (sub)program from which G05PGF is called.
Constraint: LR≥2×IP+2×IQ+2.
12:   STATE* – INTEGER arrayCommunication Array
Note: the actual argument supplied must be the array STATE supplied to the initialization routines G05KFF or G05KGF.
On entry: contains information on the selected base generator and its current state.
On exit: contains updated information on the state of the generator.
13:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, DIST is not valid: DIST=value.
IFAIL=2
On entry, NUM=value.
Constraint: NUM≥0.
IFAIL=3
On entry, IP=value.
Constraint: IP≥0.
IFAIL=4
On entry, IQ=value.
Constraint: IQ≥1.
IFAIL=6
On entry, DF=value.
Constraint: DF≥3.
IFAIL=10
IP or IQ is not the same as when R was set up in a previous call.
Previous value of IP=value and IP=value.
Previous value of IQ=value and IQ=value.
IFAIL=11
On entry, LR is not large enough, LR=value: minimum length required =value.
IFAIL=12
On entry, STATE vector has been corrupted or not initialized.
IFAIL=20
Invalid sequence generated, use different parameters.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

Not applicable.

8 Parallelism and Performance

G05PGF is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

None.

10 Example

This example first calls G05KFF to initialize a base generator then calls G05PGF to generate two realizations, each consisting of ten observations, from an exponential GARCH 1,1 model.

10.1 Program Text

Program Text (g05pgfe.f90)

10.2 Program Data

Program Data (g05pgfe.d)

10.3 Program Results

Program Results (g05pgfe.r)

G05 Chapter Contents
G05 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


G05PHF : NAG Library, Mark 26

G05 Chapter Contents
G05 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

G05PHF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

G05PHF generates a realization of a univariate time series from an autoregressive moving average (ARMA) model. The realization may be continued or a new realization generated at subsequent calls to G05PHF.

2 Specification

SUBROUTINE G05PHF ( MODE, N, XMEAN, IP, PHI, IQ, THETA, AVAR, R, LR, STATE, VAR, X, IFAIL)
INTEGER | MODE, N, IP, IQ, LR, STATE(*), IFAIL
REAL (KIND=nag_wp) | XMEAN, PHI(IP), THETA(IQ), AVAR, R(LR), VAR, X(N)

3 Description

Let the vector xt, denote a time series which is assumed to follow an autoregressive moving average (ARMA) model of the form:
xt-μ= ϕ 1 x t-1-μ+ϕ 2 x t-2-μ+⋯+ϕp x t-p-μ+ εt-θ 1ε t-1-θ 2ε t-2-⋯-θqε t-q
where εt, is a residual series of independent random perturbations assumed to be Normally distributed with zero mean and variance σ 2. The parameters ϕi, for i=1,2,…,p, are called the autoregressive (AR) parameters, and θj, for j=1,2,…,q, the moving average (MA) parameters. The parameters in the model are thus the p ϕ values, the q θ values, the mean μ and the residual variance σ 2.
G05PHF sets up a reference vector containing initial values corresponding to a stationary position using the method described in Tunnicliffe–Wilson (1979). The routine can then return a realization of x 1,x 2,…,xn. On a successful exit, the recent history is updated and saved in the reference vector R so that G05PHF may be called again to generate a realization of x n+1,x n+2,…, etc. See the description of the argument MODE in Section 5 for details.
One of the initialization routines G05KFF (for a repeatable sequence if computed sequentially) or G05KGF (for a non-repeatable sequence) must be called prior to the first call to G05PHF.

4 References

Knuth D E (1981) The Art of Computer Programming (Volume 2) (2nd Edition) Addison–Wesley
Tunnicliffe–Wilson G (1979) Some efficient computational procedures for high order ARMA models J. Statist. Comput. Simulation 8 301–309

5 Arguments

1:   MODE – INTEGERInput
On entry: a code for selecting the operation to be performed by the routine.
MODE=0
Set up reference vector only.
MODE=1
Generate terms in the time series using reference vector set up in a prior call to G05PHF.
MODE=2
Set up reference vector and generate terms in the time series.
Constraint: MODE=0, 1 or 2.
2:   N – INTEGERInput
On entry: n, the number of observations to be generated.
Constraint: N≥0.
3:   XMEAN – REAL (KIND=nag_wp)Input
On entry: the mean of the time series.
4:   IP – INTEGERInput
On entry: p, the number of autoregressive coefficients supplied.
Constraint: IP≥0.
5:   PHI IP – REAL (KIND=nag_wp) arrayInput
On entry: the autoregressive coefficients of the model, ϕ 1,ϕ 2,…,ϕp.
6:   IQ – INTEGERInput
On entry: q, the number of moving average coefficients supplied.
Constraint: IQ≥0.
7:   THETA IQ – REAL (KIND=nag_wp) arrayInput
On entry: the moving average coefficients of the model, θ 1,θ 2,…,θq.
8:   AVAR – REAL (KIND=nag_wp)Input
On entry: σ 2, the variance of the Normal perturbations.
Constraint: AVAR≥0.0.
9:   R LR – REAL (KIND=nag_wp) arrayCommunication Array
On entry: if MODE=1, the reference vector from the previous call to G05PHF.
On exit: the reference vector.
10:   LR – INTEGERInput
On entry: the dimension of the array R as declared in the (sub)program from which G05PHF is called.
Constraint: LR≥IP+IQ+6+max IP,IQ+1.
11:   STATE* – INTEGER arrayCommunication Array
Note: the actual argument supplied must be the array STATE supplied to the initialization routines G05KFF or G05KGF.
On entry: contains information on the selected base generator and its current state.
On exit: contains updated information on the state of the generator.
12:   VAR – REAL (KIND=nag_wp)Output
On exit: the proportion of the variance of a term in the series that is due to the moving-average (error) terms in the model. The smaller this is, the nearer is the model to non-stationarity.
13:   X N – REAL (KIND=nag_wp) arrayOutput
On exit: contains the next n observations from the time series.
14:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, MODE=value.
Constraint: MODE=0, 1 or 2.
IFAIL=2
On entry, N=value.
Constraint: N≥0.
IFAIL=4
On entry, IP=value.
Constraint: IP≥0.
IFAIL=5
On entry, the AR parameters are outside the stationarity region.
IFAIL=6
On entry, IQ=value.
Constraint: IQ≥0.
IFAIL=8
On entry, AVAR=value.
Constraint: AVAR≥0.0.
IFAIL=9
IP or IQ is not the same as when R was set up in a previous call.
Previous value of IP=value and IP=value.
Previous value of IQ=value and IQ=value.
Reference vector R has been corrupted or not initialized correctly.
IFAIL=10
On entry, LR is not large enough, LR=value: minimum length required =value.
IFAIL=11
On entry, STATE vector has been corrupted or not initialized.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

Any errors in the reference vector's initial values should be very much smaller than the error term; see Tunnicliffe–Wilson (1979).

8 Parallelism and Performance

G05PHF is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The time taken by G05PHF is essentially of order IP 2.
Note: The reference vector, R, contains a copy of the recent history of the series. If attempting to re-initialize the series by calling G05KFF or G05KGF a call to G05PHF with MODE=0 must also be made. In the repeatable case the calls to G05PHF should be performed in the same order (at the same point(s) in simulation) every time G05KFF is used. When the generator state is saved and restored using the argument STATE, the time series reference vector must be saved and restored as well.
The ARMA model for a time series can also be written as:
xn-E = A 1 x n-1-E + ⋯ + ANA x n-NA-E + B 1 an + ⋯ + BNB a n-NB+1
where
  • xn is the observed value of the time series at time n,
  • NA is the number of autoregressive parameters, Ai,
  • NB is the number of moving average parameters, Bi,
  • E is the mean of the time series,
and
  • at is a series of independent random Standard Normal perturbations.
This is the form used in G05PHF. This is related to the form given in Section 3 by:
  • B 12=σ 2,
  • B i+1=-θi σ=-θiB 1,  i=1,2,…,q,
  • NB=q+1,
  • E=μ,
  • Ai=ϕi,  i=1,2,…,p,
  • NA=p.

10 Example

This example generates values for an autoregressive model given by
xt=0.4 x t-1+0.2 x t-2+εt
where εt is a series of independent random Normal perturbations with variance 1.0. The random number generators are initialized by G05KFF and then G05PHF is called to initialize a reference vector and generate a sample of ten observations.

10.1 Program Text

Program Text (g05phfe.f90)

10.2 Program Data

Program Data (g05phfe.d)

10.3 Program Results

Program Results (g05phfe.r)

G05 Chapter Contents
G05 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


G05PJF : NAG Library, Mark 26

G05 Chapter Contents
G05 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

G05PJF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

G05PJF generates a realization of a multivariate time series from a vector autoregressive moving average (VARMA) model. The realization may be continued or a new realization generated at subsequent calls to G05PJF.

2 Specification

SUBROUTINE G05PJF ( MODE, N, K, XMEAN, IP, PHI, IQ, THETA, VAR, LDVAR, R, LR, STATE, X, LDX, IFAIL)
INTEGER | MODE, N, K, IP, IQ, LDVAR, LR, STATE(*), LDX, IFAIL
REAL (KIND=nag_wp) | XMEAN(K), PHI(K*K*IP), THETA(K*K*IQ), VAR(LDVAR,K), R(LR), X(LDX,N)

3 Description

Let the vector Xt = x 1 t,x 2 t,…,x kt T , denote a k-dimensional time series which is assumed to follow a vector autoregressive moving average (VARMA) model of the form:
Xt-μ= ϕ 1 X t-1-μ+ϕ 2 X t-2-μ+⋯+ϕp X t-p-μ+ εt-θ 1ε t-1-θ 2ε t-2-⋯-θqε t-q (1)
where εt = ε 1 t,ε 2 t,…,ε kt T , is a vector of k residual series assumed to be Normally distributed with zero mean and covariance matrix Σ. The components of εt are assumed to be uncorrelated at non-simultaneous lags. The ϕi's and θj's are k by k matrices of parameters. ϕi, for i=1,2,…,p, are called the autoregressive (AR) parameter matrices, and θj, for j=1,2,…,q, the moving average (MA) parameter matrices. The parameters in the model are thus the p k by k ϕ-matrices, the q k by k θ-matrices, the mean vector μ and the residual error covariance matrix Σ. Let
A ϕ= ϕ 1 I 0 . . . 0 ϕ 2 0 I 0 . . 0 . . . . . . ϕ p-1 0 . . . 0 I ϕp 0 . . . 0 0 pk×pk   and   B θ= θ 1 I 0 . . . 0 θ 2 0 I 0 . . 0 . . . . . . θ q- 1 0 . . . 0 I θq 0 . . . 0 0 qk×qk
where I denotes the k by k identity matrix.
The model (1) must be both stationary and invertible. The model is said to be stationary if the eigenvalues of A ϕ lie inside the unit circle and invertible if the eigenvalues of B θ lie inside the unit circle.
For k≥6 the VARMA model (1) is recast into state space form and a realization of the state vector at time zero computed. For all other cases the routine computes a realization of the pre-observed vectors X 0,X-1,…,X 1-p, ε 0,ε-1,…,ε 1-q, from (1), see Shea (1988). This realization is then used to generate a sequence of successive time series observations. Note that special action is taken for pure MA models, that is for p=0.
At your request a new realization of the time series may be generated more efficiently using the information in a reference vector created during a previous call to G05PJF. See the description of the argument MODE in Section 5 for details.
The routine returns a realization of X 1,X 2,…,Xn. On a successful exit, the recent history is updated and saved in the array R so that G05PJF may be called again to generate a realization of X n+1,X n+2,…, etc. See the description of the argument MODE in Section 5 for details.
Further computational details are given in Shea (1988). Note, however, that G05PJF uses a spectral decomposition rather than a Cholesky factorization to generate the multivariate Normals. Although this method involves more multiplications than the Cholesky factorization method and is thus slightly slower it is more stable when faced with ill-conditioned covariance matrices. A method of assigning the AR and MA coefficient matrices so that the stationarity and invertibility conditions are satisfied is described in Barone (1987).
One of the initialization routines G05KFF (for a repeatable sequence if computed sequentially) or G05KGF (for a non-repeatable sequence) must be called prior to the first call to G05PJF.

4 References

Barone P (1987) A method for generating independent realisations of a multivariate normal stationary and invertible ARMAp,q process J. Time Ser. Anal. 8 125–130
Shea B L (1988) A note on the generation of independent realisations of a vector autoregressive moving average process J. Time Ser. Anal. 9 403–410

5 Arguments

1:   MODE – INTEGERInput
On entry: a code for selecting the operation to be performed by the routine.
MODE=0
Set up reference vector and compute a realization of the recent history.
MODE=1
Generate terms in the time series using reference vector set up in a prior call to G05PJF.
MODE=2
Combine the operations of MODE=0 and 1.
MODE=3
A new realization of the recent history is computed using information stored in the reference vector, and the following sequence of time series values are generated.
If MODE=1 or 3, then you must ensure that the reference vector R and the values of K, IP, IQ, XMEAN, PHI, THETA, VAR and LDVAR have not been changed between calls to G05PJF.
Constraint: MODE=0, 1, 2 or 3.
2:   N – INTEGERInput
On entry: n, the number of observations to be generated.
Constraint: N≥0.
3:   K – INTEGERInput
On entry: k, the dimension of the multivariate time series.
Constraint: K≥1.
4:   XMEAN K – REAL (KIND=nag_wp) arrayInput
On entry: μ, the vector of means of the multivariate time series.
5:   IP – INTEGERInput
On entry: p, the number of autoregressive parameter matrices.
Constraint: IP≥0.
6:   PHI K×K×IP – REAL (KIND=nag_wp) arrayInput
On entry: must contain the elements of the IP×K×K autoregressive parameter matrices of the model, ϕ 1,ϕ 2,…,ϕp. If PHI is considered as a three-dimensional array, dimensioned as PHI KKIP , then the i,jth element of ϕl would be stored in PHI ijl ; that is, PHI l-1×k×k+j-1×k+i must be set equal to the i,jth element of ϕl, for l=1,2,…,p, i=1,2,…,k and j=1,2,…,k.
Constraint: the elements of PHI must satisfy the stationarity condition.
7:   IQ – INTEGERInput
On entry: q, the number of moving average parameter matrices.
Constraint: IQ≥0.
8:   THETA K×K×IQ – REAL (KIND=nag_wp) arrayInput
On entry: must contain the elements of the IQ×K×K moving average parameter matrices of the model, θ 1,θ 2,…,θq. If THETA is considered as a three-dimensional array, dimensioned as THETA(K,K,IQ), then the i,jth element of θl would be stored in THETA ijl ; that is, THETA l-1×k×k+j-1×k+i must be set equal to the i,jth element of θl, for l=1,2,…,q, i=1,2,…,k and j=1,2,…,k.
Constraint: the elements of THETA must be within the invertibility region.
9:   VAR LDVARK – REAL (KIND=nag_wp) arrayInput
On entry: VAR ij must contain the (i,j)th element of Σ, for i=1,2,…,K and j=1,2,…,K. Only the lower triangle is required.
Constraint: the elements of VAR must be such that Σ is positive semidefinite.
10:   LDVAR – INTEGERInput
On entry: the first dimension of the array VAR as declared in the (sub)program from which G05PJF is called.
Constraint: LDVAR≥K.
11:   R LR – REAL (KIND=nag_wp) arrayCommunication Array
On entry: if MODE=1 or 3, the array R as output from the previous call to G05PJF must be input without any change.
If MODE=0 or 2, the contents of R need not be set.
On exit: information required for any subsequent calls to the routine with MODE=1 or 3. See Section 9.
12:   LR – INTEGERInput
On entry: the dimension of the array R as declared in the (sub)program from which G05PJF is called.
Constraints:
  • if K≥6, LR≥5⁢r 2+1×K 2+4⁢r+3×K+4;
  • if K<6, LR≥ IP+IQ 2+1×K 2+ 4×IP+IQ+3×K+max K⁢r⁢K⁢r+2,K 2⁢ IP+IQ 2+l⁢l+3+K 2⁢IQ+1+4.
Where r=max IP,IQ and if IP=0, l=K⁢K+1/2, or if IP≥1, l=K⁢K+1/2+IP-1⁢K 2.
See Section 9 for some examples of the required size of the array R.
13:   STATE* – INTEGER arrayCommunication Array
Note: the actual argument supplied must be the array STATE supplied to the initialization routines G05KFF or G05KGF.
On entry: contains information on the selected base generator and its current state.
On exit: contains updated information on the state of the generator.
14:   X LDXN – REAL (KIND=nag_wp) arrayOutput
On exit: X it will contain a realization of the ith component of Xt, for i=1,2,…,k and t=1,2,…,n.
15:   LDX – INTEGERInput
On entry: the first dimension of the array X as declared in the (sub)program from which G05PJF is called.
Constraint: LDX≥K.
16:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, MODE=value.
Constraint: MODE=0, 1, 2 or 3.
IFAIL=2
On entry, N=value.
Constraint: N≥0.
IFAIL=3
On entry, K=value.
Constraint: K≥1.
IFAIL=5
On entry, IP=value.
Constraint: IP≥0.
IFAIL=6
On entry, the AR parameters are outside the stationarity region.
IFAIL=7
On entry, IQ=value.
Constraint: IQ≥0.
IFAIL=8
On entry, the moving average parameter matrices are such that the model is non-invertible.
IFAIL=9
On entry, the covariance matrix VAR is not positive semidefinite to machine precision.
IFAIL=10
On entry, LDVAR=value and K=value.
Constraint: LDVAR≥K.
IFAIL=11
K is not the same as when R was set up in a previous call.
Previous value of K=value and K=value.
IFAIL=12
On entry, LR is not large enough, LR=value: minimum length required =value.
IFAIL=13
On entry, STATE vector has been corrupted or not initialized.
IFAIL=15
On entry, LDX=value and K=value.
Constraint: LDX≥K.
IFAIL=20
An excessive number of iterations were required by the NAG routine used to evaluate the eigenvalues of the matrices used to test for stationarity or invertibility.
IFAIL=21
The reference vector cannot be computed because the AR parameters are too close to the boundary of the stationarity region.
IFAIL=22
An excessive number of iterations were required by the NAG routine used to evaluate the eigenvalues of the covariance matrix.
IFAIL=23
An excessive number of iterations were required by the NAG routine used to evaluate the eigenvalues stored in the reference vector.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

The accuracy is limited by the matrix computations performed, and this is dependent on the condition of the argument and covariance matrices.

8 Parallelism and Performance

G05PJF is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
G05PJF makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

Note that, in reference to IFAIL=8, G05PJF will permit moving average parameters on the boundary of the invertibility region.
The elements of R contain amongst other information details of the spectral decompositions which are used to generate future multivariate Normals. Note that these eigenvectors may not be unique on different machines. For example the eigenvectors corresponding to multiple eigenvalues may be permuted. Although an effort is made to ensure that the eigenvectors have the same sign on all machines, differences in the signs may theoretically still occur.
The following table gives some examples of the required size of the array R, specified by the argument LR, for k=1,2 or 3, and for various values of p and q.
 |  |  |  | q
 |  | 0 | 1 | 2 | 3
 |  | 13 | 20 | 31 | 46
 | 0 | 36 | 56 | 92 | 144
 |  | 85 | 124 | 199 | 310
 |  | 19 | 30 | 45 | 64
 | 1 | 52 | 88 | 140 | 208
 |  | 115 | 190 | 301 | 448
p
 |  | 35 | 50 | 69 | 92
 | 2 | 136 | 188 | 256 | 340
 |  | 397 | 508 | 655 | 838
 |  | 57 | 76 | 99 | 126
 | 3 | 268 | 336 | 420 | 520
 |  | 877 | 1024 | 1207 | 1426
Note that G13DXF may be used to check whether a VARMA model is stationary and invertible.
The time taken depends on the values of p, q and especially n and k.

10 Example

This program generates two realizations, each of length 48, from the bivariate AR(1) model
Xt-μ=ϕ 1 X t-1-μ+εt
with
ϕ 1= 0.80 0.07 0.00 0.58 ,
μ= 5.00 9.00 ,
and
Σ= 2.97 0 0.64 5.38 .
The pseudorandom number generator is initialized by a call to G05KFF. Then, in the first call to G05PJF, MODE=2 in order to set up the reference vector before generating the first realization. In the subsequent call MODE=3 and a new recent history is generated and used to generate the second realization.

10.1 Program Text

Program Text (g05pjfe.f90)

10.2 Program Data

Program Data (g05pjfe.d)

10.3 Program Results

Program Results (g05pjfe.r)

G05 Chapter Contents
G05 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


G05PMF : NAG Library, Mark 26

G05 Chapter Contents
G05 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

G05PMF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

G05PMF simulates from an exponential smoothing model, where the model uses either single exponential, double exponential or a Holt–Winters method.

2 Specification

SUBROUTINE G05PMF ( MODE, N, ITYPE, P, PARAM, INIT, VAR, R, STATE, E, EN, X, IFAIL)
INTEGER | MODE, N, ITYPE, P, STATE(*), EN, IFAIL
REAL (KIND=nag_wp) | PARAM(*), INIT(*), VAR, R(*), E(EN), X(N)

3 Description

G05PMF returns xt:t=1,2,…,n, a realization of a time series from an exponential smoothing model defined by one of five smoothing functions:
  • Single Exponential Smoothing
    xt = m t-1 + εt mt = α xt + 1-α m t-1
  • Brown Double Exponential Smoothing
    xt = m t-1 + r t-1 α + εt mt = α xt + 1-α m t-1 rt = α mt - m t-1 + 1-α r t-1
  • Linear Holt Exponential Smoothing
    xt = m t-1 + ϕ r t-1 + εt mt = α xt + 1-α m t-1 + ϕ r t-1 rt = γ mt - m t-1 + 1-γ ϕ r t-1
  • Additive Holt–Winters Smoothing
    xt = m t-1 + ϕ r t-1 + s t-1-p + εt mt = α xt - s t-p + 1-α m t-1 +ϕ r t-1 rt = γ mt - m t-1 + 1-γ ϕ r t-1 st = β xt - mt + 1-β s t-p
  • Multiplicative Holt–Winters Smoothing
    xt = m t-1 + ϕ r t-1 × s t-1-p + εt mt = α xt / s t-p + 1-α m t-1 +ϕ r t-1 rt = γ mt - m t-1 + 1-γ ϕ r t-1 st = β xt / mt + 1-β s t-p
where mt is the mean, rt is the trend and st is the seasonal component at time t with p being the seasonal order. The errors, εt are either drawn from a normal distribution with mean zero and variance σ 2 or randomly sampled, with replacement, from a user-supplied vector.

4 References

Chatfield C (1980) The Analysis of Time Series Chapman and Hall

5 Arguments

1:   MODE – INTEGERInput
On entry: indicates if G05PMF is continuing from a previous call or, if not, how the initial values are computed.
MODE=0
Values for m 0, r 0 and s-j, for j=0,1,…,p-1, are supplied in INIT.
MODE=1
G05PMF continues from a previous call using values that are supplied in R. R is not updated.
MODE=2
G05PMF continues from a previous call using values that are supplied in R. R is updated.
Constraint: MODE=0, 1 or 2.
2:   N – INTEGERInput
On entry: the number of terms of the time series being generated.
Constraint: N≥0.
3:   ITYPE – INTEGERInput
On entry: the smoothing function.
ITYPE=1
Single exponential.
ITYPE=2
Brown's double exponential.
ITYPE=3
Linear Holt.
ITYPE=4
Additive Holt–Winters.
ITYPE=5
Multiplicative Holt–Winters.
Constraint: ITYPE=1, 2, 3, 4 or 5.
4:   P – INTEGERInput
On entry: if ITYPE=4 or 5, the seasonal order, p, otherwise P is not referenced.
Constraint: if ITYPE=4 or 5, P>1.
5:   PARAM* – REAL (KIND=nag_wp) arrayInput
Note: the dimension of the array PARAM must be at least 1 if ITYPE=1 or 2, 3 if ITYPE=3 and at least 4 if ITYPE=4 or 5.
On entry: the smoothing parameters.
If ITYPE=1 or 2, PARAM 1=α and any remaining elements of PARAM are not referenced.
If ITYPE=3, PARAM 1=α, PARAM 2=γ, PARAM 3=ϕ and any remaining elements of PARAM are not referenced.
If ITYPE=4 or 5, PARAM 1=α, PARAM 2=γ, PARAM 3=β and PARAM 4=ϕ and any remaining elements of PARAM are not referenced.
Constraints:
  • if ITYPE=1, 0.0≤α≤1.0;
  • if ITYPE=2, 0.0<α≤1.0;
  • if ITYPE=3, 0.0≤α≤1.0 and 0.0≤γ≤1.0 and ϕ≥0.0;
  • if ITYPE=4 or 5, 0.0≤α≤1.0 and 0.0≤γ≤1.0 and 0.0≤β≤1.0 and ϕ≥0.0.
6:   INIT* – REAL (KIND=nag_wp) arrayInput
Note: the dimension of the array INIT must be at least 1 if ITYPE=1, 2 if ITYPE=2 or 3 and at least 2+P if ITYPE=4 or 5.
On entry: if MODE=0, the initial values for m 0, r 0 and s-j, for j=0,1,…,p-1, used to initialize the smoothing.
If ITYPE=1, INIT 1=m 0 and any remaining elements of INIT are not referenced.
If ITYPE=2 or 3, INIT 1=m 0 and INIT 2=r 0 and any remaining elements of INIT are not referenced.
If ITYPE=4 or 5, INIT 1=m 0, INIT 2=r 0 and INIT 3 to INIT 2+p hold the values for s-j, for j=0,1,…,p-1. Any remaining elements of INIT are not referenced.
7:   VAR – REAL (KIND=nag_wp)Input
On entry: the variance, σ 2 of the Normal distribution used to generate the errors εi. If VAR≤0.0 then Normally distributed errors are not used.
8:   R* – REAL (KIND=nag_wp) arrayInput/Output
Note: the dimension of the array R must be at least 13 if ITYPE=1, 2 or 3 and at least 13+P if ITYPE=4 or 5.
On entry: if MODE=1 or 2, R must contain the values as returned by a previous call to G05PMF, R need not be set otherwise.
On exit: if MODE=1, R is unchanged. Otherwise, R contains the information on the current state of smoothing.
Constraint: if MODE=1 or 2, R must have been initialized by at least one call to G05PMF or G13AMF with MODE≠1, and R must not have been changed since that call.
9:   STATE* – INTEGER arrayCommunication Array
Note: the actual argument supplied must be the array STATE supplied to the initialization routines G05KFF or G05KGF.
On entry: contains information on the selected base generator and its current state.
On exit: contains updated information on the state of the generator.
10:   E EN – REAL (KIND=nag_wp) arrayInput
On entry: if EN>0 and VAR≤0.0, a vector from which the errors, εt are randomly drawn, with replacement.
If EN≤0, E is not referenced.
11:   EN – INTEGERInput
On entry: if EN>0, then the length of the vector E.
If both VAR≤0.0 and EN≤0 then εt=0.0, for t=1,2,…,n.
12:   X N – REAL (KIND=nag_wp) arrayOutput
On exit: the generated time series, xt, for t=1,2,…,n.
13:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, MODE=value.
Constraint: MODE=0, 1 or 2.
IFAIL=2
On entry, N=value.
Constraint: N≥0.
IFAIL=3
On entry, ITYPE=value.
Constraint: ITYPE=1, 2, 3, 4 or 5.
IFAIL=4
On entry, P=value.
Constraint: if ITYPE=4 or 5, P≥2.
IFAIL=5
On entry, PARAM value=value.
Constraint: 0≤PARAM i≤1.
On entry, PARAM value=value.
Constraint: if ITYPE=2, 0<PARAM i≤1.
On entry, PARAM value=value.
Constraint: PARAM i≥0.
IFAIL=8
On entry, some of the elements of the array R have been corrupted or have not been initialized.
IFAIL=9
On entry, STATE vector has been corrupted or not initialized.
IFAIL=12
Model unsuitable for multiplicative Holt–Winter, try a different set of parameters.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

Not applicable.

8 Parallelism and Performance

G05PMF is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

None.

10 Example

This example reads 11 observations from a time series relating to the rate of the earth's rotation about its polar axis and fits an exponential smoothing model using G13AMF.
G05PMF is then called multiple times to obtain simulated forecast confidence intervals.

10.1 Program Text

Program Text (g05pmfe.f90)

10.2 Program Data

Program Data (g05pmfe.d)

10.3 Program Results

Program Results (g05pmfe.r)

GnuplotProduced by GNUPLOT 4.6 patchlevel 3 100 150 200 250 300 350 0 5 10 15 20 25 30 35 Data Time Example Program Exponential Smoothing (95% confidence intervals (CIs) are shown) gnuplot_plot_1 observed gnuplot_plot_2 smoothed gnuplot_plot_3 forecast gnuplot_plot_4 estimated CI gnuplot_plot_5 gnuplot_plot_6 simulated CI gnuplot_plot_7 gnuplot_plot_8 bootstrapped CI gnuplot_plot_9
G05 Chapter Contents
G05 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


G05PVF : NAG Library, Mark 26

G05 Chapter Contents
G05 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

G05PVF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

G05PVF generates training and validation datasets suitable for use in cross-validation or jack-knifing.

2 Specification

SUBROUTINE G05PVF ( K, FOLD, N, M, SORDX, X, LDX, USEY, Y, USEW, W, NT, STATE, IFAIL)
INTEGER | K, FOLD, N, M, SORDX, LDX, USEY, USEW, NT, STATE(*), IFAIL
REAL (KIND=nag_wp) | X(LDX,*), Y(*), W(*)

3 Description

Let Xo denote a matrix of n observations on m variables and yo and wo each denote a vector of length n. For example, Xo might represent a matrix of independent variables, yo the dependent variable and wo the associated weights in a weighted regression.
G05PVF generates a series of training datasets, denoted by the matrix, vector, vector triplet Xt,yt,wt of nt observations, and validation datasets, denoted Xv,yv,wv with nv observations. These training and validation datasets are generated as follows.
Each of the original n observations is randomly assigned to one of K equally sized groups or folds. For the kth sample the validation dataset consists of those observations in group k and the training dataset consists of all those observations not in group k. Therefore at most K samples can be generated.
If n is not divisible by K then the observations are assigned to groups as evenly as possible, therefore any group will be at most one observation larger or smaller than any other group.
When using K=n the resulting datasets are suitable for leave-one-out cross-validation, or the training dataset on its own for jack-knifing. When using K≠n the resulting datasets are suitable for K-fold cross-validation. Datasets suitable for reversed cross-validation can be obtained by switching the training and validation datasets, i.e., use the kth group as the training dataset and the rest of the data as the validation dataset.
One of the initialization routines G05KFF (for a repeatable sequence if computed sequentially) or G05KGF (for a non-repeatable sequence) must be called prior to the first call to G05PVF.

4 References

None.

5 Arguments

1:   K – INTEGERInput
On entry: K, the number of folds.
Constraint: 2≤K≤N.
2:   FOLD – INTEGERInput
On entry: the number of the fold to return as the validation dataset.
On the first call to G05PVF FOLD should be set to 1 and then incremented by one at each subsequent call until all K sets of training and validation datasets have been produced. See Section 9 for more details on how a different calling sequence can be used.
Constraint: 1≤FOLD≤K.
3:   N – INTEGERInput
On entry: n, the number of observations.
Constraint: N≥1.
4:   M – INTEGERInput
On entry: m, the number of variables.
Constraint: M≥1.
5:   SORDX – INTEGERInput
On entry: determines how variables are stored in X.
Constraint: SORDX=1 or 2.
6:   X LDX* – REAL (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array X must be at least M if SORDX=1 and at least N if SORDX=2.
The way the data is stored in X is defined by SORDX.
If SORDX=1, X ij contains the ith observation for the jth variable, for i=1,2,…,N and j=1,2,…,M.
If SORDX=2, X ji contains the ith observation for the jth variable, for i=1,2,…,N and j=1,2,…,M.
On entry: if FOLD=1, X must hold Xo, the values of X for the original dataset, otherwise, X must not be changed since the last call to G05PVF.
On exit: values of X for the training and validation datasets, with Xt held in observations 1 to NT and Xv in observations NT+1 to N.
7:   LDX – INTEGERInput
On entry: the first dimension of the array X as declared in the (sub)program from which G05PVF is called.
Constraints:
  • if SORDX=2, LDX≥M;
  • otherwise LDX≥N.
8:   USEY – INTEGERInput
On entry: if USEY=1, the original dataset includes yo and yo will be processed alongside Xo.
Constraint: USEY=0 or 1.
9:   Y* – REAL (KIND=nag_wp) arrayInput/Output
Note: the dimension of the array Y must be at least N if USEY=1.
If USEY=0, Y is not referenced on entry and will not be modified on exit.
On entry: if FOLD=1, Y must hold yo, the values of y for the original dataset, otherwise Y must not be changed since the last call to G05PVF.
On exit: values of y for the training and validation datasets, with yt held in elements 1 to NT and yv in elements NT+1 to N.
10:   USEW – INTEGERInput
On entry: if USEW=1, the original dataset includes wo and wo will be processed alongside Xo.
Constraint: USEW=0 or 1.
11:   W* – REAL (KIND=nag_wp) arrayInput/Output
Note: the dimension of the array W must be at least N if USEW=1.
If USEW=0, W is not referenced on entry and will not be modified on exit.
On entry: if FOLD=1, W must hold wo, the values of w for the original dataset, otherwise W must not be changed since the last call to G05PVF.
On exit: values of w for the training and validation datasets, with wt held in elements 1 to NT and wv in elements NT+1 to N.
12:   NT – INTEGEROutput
On exit: nt, the number of observations in the training dataset.
13:   STATE* – INTEGER arrayCommunication Array
Note: the actual argument supplied must be the array STATE supplied to the initialization routines G05KFF or G05KGF.
On entry: contains information on the selected base generator and its current state.
On exit: contains updated information on the state of the generator.
14:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, because for this routine the values of the output arguments may be useful even if IFAIL≠0 on exit, the recommended value is -1. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Note: G05PVF may return useful information for one or more of the following detected errors or warnings.
Errors or warnings detected by the routine:
IFAIL=11
On entry, K=value and N=value.
Constraint: 2≤K≤N.
IFAIL=21
On entry, FOLD=value and K=value.
Constraint: 1≤FOLD≤K.
IFAIL=31
On entry, N=value.
Constraint: N≥1.
IFAIL=41
On entry, M=value.
Constraint: M≥1.
IFAIL=51
On entry, SORDX=value.
Constraint: SORDX=1 or 2.
IFAIL=61
More than 50% of the data did not move when the data was shuffled. value of the value observations stayed put.
IFAIL=71
On entry, LDX=value and N=value.
Constraint: if SORDX=1, LDX≥N.
IFAIL=72
On entry, LDX=value and M=value.
Constraint: if SORDX=2, LDX≥M.
IFAIL=81
Constraint: USEY=0 or 1.
IFAIL=101
Constraint: USEW=0 or 1.
IFAIL=131
On entry, STATE vector has been corrupted or not initialized.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

Not applicable.

8 Parallelism and Performance

G05PVF is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
G05PVF makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

G05PVF will be computationality more efficient if each observation in X is contiguous, that is SORDX=2.
Because of the way G05PVF stores the data you should usually generate the K training and validation datasets in order, i.e., set FOLD=1 on the first call and increment it by one at each subsequent call. However, there are times when a different calling sequence would be beneficial, for example, when performing different cross-validation analyses on different threads. This is possible, as long as the following is borne in mind:
  • G05PVF must be called with FOLD=1 first.
  • Other than the first set, you can obtain the training and validation dataset in any order, but for a given X you can only obtain each once.
For example, if you have three threads, you would call G05PVF once with FOLD=1. You would then copy the X returned onto each thread and generate the remaing K-1 sets of data by splitting them between the threads. For example, the first thread runs with FOLD=2,…,L 1, the second with FOLD=L 1+1,…,L 2 and the third with FOLD=L 2+1,…,K.

10 Example

This example uses G05PVF to facilitate K-fold cross-validation.
A set of simulated data is split into 5 training and validation datasets. G02GBF is used to fit a logistic regression model to each training dataset and then G02GPF is used to predict the response for the observations in the validation dataset.
The counts of true and false positives and negatives along with the sensitivity and specificity is then reported.

10.1 Program Text

Program Text (g05pvfe.f90)

10.2 Program Data

Program Data (g05pvfe.d)

10.3 Program Results

Program Results (g05pvfe.r)

G05 Chapter Contents
G05 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


G05PWF : NAG Library, Mark 26

G05 Chapter Contents
G05 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

G05PWF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

G05PWF generates a dataset suitable for use with repeated random sub-sampling validation.

2 Specification

SUBROUTINE G05PWF ( NT, N, M, SORDX, X, LDX, USEY, Y, USEW, W, STATE, IFAIL)
INTEGER | NT, N, M, SORDX, LDX, USEY, USEW, STATE(*), IFAIL
REAL (KIND=nag_wp) | X(LDX,*), Y(*), W(*)

3 Description

Let Xo denote a matrix of n observations on m variables and yo and wo each denote a vector of length n. For example, Xo might represent a matrix of independent variables, yo the dependent variable and wo the associated weights in a weighted regression.
G05PWF generates a series of training datasets, denoted by the matrix, vector, vector triplet Xt,yt,wt of nt observations, and validation datasets, denoted Xv,yv,wv with nv observations. These training and validation datasets are generated by randomly assigning each observation to either the training dataset or the validation dataset.
The resulting datasets are suitable for use with repeated random sub-sampling validation.
One of the initialization routines G05KFF (for a repeatable sequence if computed sequentially) or G05KGF (for a non-repeatable sequence) must be called prior to the first call to G05PWF.

4 References

None.

5 Arguments

1:   NT – INTEGERInput
On entry: nt, the number of observations in the training dataset.
Constraint: 1≤NT≤N.
2:   N – INTEGERInput
On entry: n, the number of observations.
Constraint: N≥1.
3:   M – INTEGERInput
On entry: m, the number of variables.
Constraint: M≥1.
4:   SORDX – INTEGERInput
On entry: determines how variables are stored in X.
Constraint: SORDX=1 or 2.
5:   X LDX* – REAL (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array X must be at least M if SORDX=1 and at least N if SORDX=2.
The way the data is stored in X is defined by SORDX.
If SORDX=1, X ij contains the ith observation for the jth variable, for i=1,2,…,N and j=1,2,…,M.
If SORDX=2, X ji contains the ith observation for the jth variable, for i=1,2,…,N and j=1,2,…,M.
On entry: X must hold Xo, the values of X for the original dataset. This may be the same X as returned by a previous call to G05PWF.
On exit: values of X for the training and validation datasets, with Xt held in observations 1 to NT and Xv in observations NT+1 to N.
6:   LDX – INTEGERInput
On entry: the first dimension of the array X as declared in the (sub)program from which G05PWF is called.
Constraints:
  • if SORDX=2, LDX≥M;
  • otherwise LDX≥N.
7:   USEY – INTEGERInput
On entry: if USEY=1, the original dataset includes yo and yo will be processed alongside Xo.
Constraint: USEY=0 or 1.
8:   Y* – REAL (KIND=nag_wp) arrayInput/Output
Note: the dimension of the array Y must be at least N if USEY=1.
If USEY=0, Y is not referenced on entry and will not be modified on exit.
On entry: Y must hold yo, the values of y for the original dataset. This may be the same Y as returned by a previous call to G05PWF.
On exit: values of y for the training and validation datasets, with yt held in elements 1 to NT and yv in elements NT+1 to N.
9:   USEW – INTEGERInput
On entry: if USEW=1, the original dataset includes wo and wo will be processed alongside Xo.
Constraint: USEW=0 or 1.
10:   W* – REAL (KIND=nag_wp) arrayInput/Output
Note: the dimension of the array W must be at least N if USEW=1.
If USEW=0, W is not referenced on entry or and will not be modified on exit.
On entry: W must hold wo, the values of w for the original dataset. This may be the same W as returned by a previous call to G05PWF.
On exit: values of w for the training and validation datasets, with wt held in elements 1 to NT and wv in elements NT+1 to N.
11:   STATE* – INTEGER arrayCommunication Array
Note: the actual argument supplied must be the array STATE supplied to the initialization routines G05KFF or G05KGF.
On entry: contains information on the selected base generator and its current state.
On exit: contains updated information on the state of the generator.
12:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=11
On entry, NT=value and N=value.
Constraint: 1≤NT≤N.
IFAIL=21
On entry, N=value.
Constraint: N≥1.
IFAIL=31
On entry, M=value.
Constraint: M≥1.
IFAIL=41
On entry, SORDX=value.
Constraint: SORDX=1 or 2.
IFAIL=61
On entry, LDX=value and N=value.
Constraint: if SORDX=1, LDX≥N.
IFAIL=62
On entry, LDX=value and M=value.
Constraint: if SORDX=2, LDX≥M.
IFAIL=71
Constraint: USEY=0 or 1.
IFAIL=91
Constraint: USEW=0 or 1.
IFAIL=111
On entry, STATE vector has been corrupted or not initialized.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

Not applicable.

8 Parallelism and Performance

G05PWF is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
G05PWF makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

G05PWF will be computationality more efficient if each observation in X is contiguous, that is SORDX=2.

10 Example

This example uses G05PWF to facilitate repeated random sub-sampling cross-validation.
A set of simulated data is randomly split into a training and validation datasets. G02GBF is used to fit a logistic regression model to each training dataset and then G02GPF is used to predict the response for the observations in the validation dataset. This process is repeated 10 times.
The counts of true and false positives and negatives along with the sensitivity and specificity is then reported.

10.1 Program Text

Program Text (g05pwfe.f90)

10.2 Program Data

Program Data (g05pwfe.d)

10.3 Program Results

Program Results (g05pwfe.r)

G05 Chapter Contents
G05 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


G05PXF : NAG Library, Mark 26

G05 Chapter Contents
G05 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

G05PXF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

G05PXF generates a random orthogonal matrix.

2 Specification

SUBROUTINE G05PXF ( SIDE, INIT, M, N, STATE, A, LDA, IFAIL)
INTEGER | M, N, STATE(*), LDA, IFAIL
REAL (KIND=nag_wp) | A(LDA,N)
CHARACTER(1) | SIDE, INIT

3 Description

G05PXF pre- or post-multiplies an m by n matrix A by a random orthogonal matrix U, overwriting A. The matrix A may optionally be initialized to the identity matrix before multiplying by U, hence U is returned. U is generated using the method of Stewart (1980). The algorithm can be summarised as follows.
Let x 1,x 2,…,x n-1 follow independent multinormal distributions with zero mean and variance I σ 2 and dimensions n,n-1,…,2; let Hj=diag I j-1, Hj*, where I j-1 is the identity matrix and Hj* is the Householder transformation that reduces xj to r jje 1, e 1 being the vector with first element one and the remaining elements zero and r jj being a scalar, and let D=diag sign r 11,sign r 22,…,sign r nn. Then the product U=D H 1H 2…H n-1 is a random orthogonal matrix distributed according to the Haar measure over the set of orthogonal matrices of n. See Theorem 3.3 in Stewart (1980).
One of the initialization routines G05KFF (for a repeatable sequence if computed sequentially) or G05KGF (for a non-repeatable sequence) must be called prior to the first call to G05PXF.

4 References

Stewart G W (1980) The efficient generation of random orthogonal matrices with an application to condition estimates SIAM J. Numer. Anal. 17 403–409

5 Arguments

1:   SIDE – CHARACTER(1)Input
On entry: indicates whether the matrix A is multiplied on the left or right by the random orthogonal matrix U.
SIDE='L'
The matrix A is multiplied on the left, i.e., premultiplied.
SIDE='R'
The matrix A is multiplied on the right, i.e., post-multiplied.
Constraint: SIDE='L' or 'R'.
2:   INIT – CHARACTER(1)Input
On entry: indicates whether or not A should be initialized to the identity matrix.
INIT='I'
A is initialized to the identity matrix.
INIT='N'
A is not initialized and the matrix A must be supplied in A.
Constraint: INIT='I' or 'N'.
3:   M – INTEGERInput
On entry: m, the number of rows of the matrix A.
Constraints:
  • if SIDE='L', M>1;
  • otherwise M≥1.
4:   N – INTEGERInput
On entry: n, the number of columns of the matrix A.
Constraints:
  • if SIDE='R', N>1;
  • otherwise N≥1.
5:   STATE* – INTEGER arrayCommunication Array
Note: the actual argument supplied must be the array STATE supplied to the initialization routines G05KFF or G05KGF.
On entry: contains information on the selected base generator and its current state.
On exit: contains updated information on the state of the generator.
6:   A LDAN – REAL (KIND=nag_wp) arrayInput/Output
On entry: if INIT='N', A must contain the matrix A.
On exit: the matrix UA when SIDE='L' or the matrix A U when SIDE='R'.
7:   LDA – INTEGERInput
On entry: the first dimension of the array A as declared in the (sub)program from which G05PXF is called.
Constraint: LDA≥M.
8:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, SIDE is not valid: SIDE=value.
IFAIL=2
On entry, INIT is not valid: INIT=value.
IFAIL=3
On entry, SIDE=value, M=value.
Constraint: if SIDE='L', M>1; otherwise M≥1.
IFAIL=4
On entry, SIDE=value, N=value.
Constraint: if SIDE='R', N>1; otherwise N≥1.
IFAIL=5
On entry, STATE vector has been corrupted or not initialized.
IFAIL=7
On entry, LDA=value and M=value.
Constraint: LDA≥M.
IFAIL=8
On entry, SIDE=value, M=value.
Constraint: if SIDE='L', M>1; otherwise M≥1.
On entry, SIDE=value, N=value.
Constraint: if SIDE='R', N>1; otherwise N≥1.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

The maximum error in UT U should be a modest multiple of machine precision (see Chapter X02).

8 Parallelism and Performance

G05PXF is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
G05PXF makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

None.

10 Example

Following initialization of the pseudorandom number generator by a call to G05KFF, a 4 by 4 orthogonal matrix is generated using the INIT='I' option and the result printed.

10.1 Program Text

Program Text (g05pxfe.f90)

10.2 Program Data

Program Data (g05pxfe.d)

10.3 Program Results

Program Results (g05pxfe.r)

G05 Chapter Contents
G05 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


G05PYF : NAG Library, Mark 26

G05 Chapter Contents
G05 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

G05PYF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

G05PYF generates a random correlation matrix with given eigenvalues.

2 Specification

SUBROUTINE G05PYF ( N, D, EPS, STATE, C, LDC, IFAIL)
INTEGER | N, STATE(*), LDC, IFAIL
REAL (KIND=nag_wp) | D(N), EPS, C(LDC,N)

3 Description

Given n eigenvalues, λ 1,λ 2,…,λn, such that
∑i=1 n λi=n
and
λi≥ 0,   i= 1,2,…,n,
G05PYF will generate a random correlation matrix, C, of dimension n, with eigenvalues λ 1,λ 2,…,λn.
The method used is based on that described by Lin and Bendel (1985). Let D be the diagonal matrix with values λ 1,λ 2,…,λn and let A be a random orthogonal matrix generated by G05PXF then the matrix C 0=A D AT is a random covariance matrix with eigenvalues λ 1,λ 2,…,λn. The matrix C 0 is transformed into a correlation matrix by means of n-1 elementary rotation matrices Pi such that C = P n-1 P n-2 … P 1 C 0 P 1 T … P n-2 T P n-1 T . The restriction on the sum of eigenvalues implies that for any diagonal element of C 0>1, there is another diagonal element <1. The Pi are constructed from such pairs, chosen at random, to produce a unit diagonal element corresponding to the first element. This is repeated until all diagonal elements are 1 to within a given tolerance ε.
The randomness of C should be interpreted only to the extent that A is a random orthogonal matrix and C is computed from A using the Pi which are chosen as arbitrarily as possible.
One of the initialization routines G05KFF (for a repeatable sequence if computed sequentially) or G05KGF (for a non-repeatable sequence) must be called prior to the first call to G05PYF.

4 References

Lin S P and Bendel R B (1985) Algorithm AS 213: Generation of population correlation on matrices with specified eigenvalues Appl. Statist. 34 193–198

5 Arguments

1:   N – INTEGERInput
On entry: n, the dimension of the correlation matrix to be generated.
Constraint: N≥1.
2:   D N – REAL (KIND=nag_wp) arrayInput
On entry: the n eigenvalues, λi, for i=1,2,…,n.
Constraints:
  • D i≥0.0, for i=1,2,…,n;
  • ∑i=1 n D i=n to within EPS.
3:   EPS – REAL (KIND=nag_wp)Input
On entry: the maximum acceptable error in the diagonal elements.
Suggested value: EPS=0.00001.
Constraint: EPS≥N×machine precision (see Chapter X02).
4:   STATE* – INTEGER arrayCommunication Array
Note: the actual argument supplied must be the array STATE supplied to the initialization routines G05KFF or G05KGF.
On entry: contains information on the selected base generator and its current state.
On exit: contains updated information on the state of the generator.
5:   C LDCN – REAL (KIND=nag_wp) arrayOutput
On exit: a random correlation matrix, C, of dimension n.
6:   LDC – INTEGERInput
On entry: the first dimension of the array C as declared in the (sub)program from which G05PYF is called.
Constraint: LDC≥N.
7:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, N=value.
Constraint: N≥1.
IFAIL=2
On entry, an eigenvalue is negative.
On entry, the eigenvalues do not sum to N.
IFAIL=3
On entry, EPS=value.
Constraint: EPS≥N×machine precision.
IFAIL=4
On entry, STATE vector has been corrupted or not initialized.
IFAIL=5
The diagonals of the returned matrix are not unity, try increasing the value of EPS, or rerun the code using a different seed.
IFAIL=6
On entry, LDC=value and N=value.
Constraint: LDC≥N.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

The maximum error in a diagonal element is given by EPS.

8 Parallelism and Performance

G05PYF is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
G05PYF makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The time taken by G05PYF is approximately proportional to n 2.

10 Example

Following initialization of the pseudorandom number generator by a call to G05KFF, a 3 by 3 correlation matrix with eigenvalues of 0.7, 0.9 and 1.4 is generated and printed.

10.1 Program Text

Program Text (g05pyfe.f90)

10.2 Program Data

Program Data (g05pyfe.d)

10.3 Program Results

Program Results (g05pyfe.r)

G05 Chapter Contents
G05 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


G05PZF : NAG Library, Mark 26

G05 Chapter Contents
G05 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

G05PZF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

G05PZF generates a random two-way table.

2 Specification

SUBROUTINE G05PZF ( MODE, NROW, NCOL, TOTR, TOTC, R, LR, STATE, X, LDX, IFAIL)
INTEGER | MODE, NROW, NCOL, TOTR(NROW), TOTC(NCOL), LR, STATE(*), X(LDX,NCOL), LDX, IFAIL
REAL (KIND=nag_wp) | R(LR)

3 Description

Given m row totals Ri and n column totals Cj (with ∑i=1 m Ri=∑j=1 n Cj=T, say), G05PZF will generate a pseudorandom two-way table of integers such that the row and column totals are satisfied.
The method used is based on that described by Patefield (1981) which is most efficient when T is large relative to the number of table entries m×n (i.e., T>2 mn). Entries are generated one row at a time and one entry at a time within a row. Each entry is generated using the conditional probability distribution for that entry given the entries in the previous rows and the previous entries in the same row.
A reference vector is used to store computed values that can be reused in the generation of new tables with the same row and column totals. G05PZF can be called to simply set up the reference vector, or to generate a two-way table using a reference vector set up in a previous call, or it can combine both functions in a single call.
One of the initialization routines G05KFF (for a repeatable sequence if computed sequentially) or G05KGF (for a non-repeatable sequence) must be called prior to the first call to G05PZF.

4 References

Patefield W M (1981) An efficient method of generating R×C tables with given row and column totals Appl. Stats. 30 91–97

5 Arguments

1:   MODE – INTEGERInput
On entry: a code for selecting the operation to be performed by the routine.
MODE=0
Set up reference vector only.
MODE=1
Generate two-way table using reference vector set up in a prior call to G05PZF.
MODE=2
Set up reference vector and generate two-way table.
Constraint: MODE=0, 1 or 2.
2:   NROW – INTEGERInput
On entry: m, the number of rows in the table.
Constraint: NROW≥2.
3:   NCOL – INTEGERInput
On entry: n, the number of columns in the table.
Constraint: NCOL≥2.
4:   TOTR NROW – INTEGER arrayInput
On entry: the m row totals, Ri, for i=1,2,…,m.
Constraints:
  • TOTR i≥0, for i=1,2,…,m;
  • ∑i=1 m TOTR i=∑j=1 n TOTC j;
  • ∑i TOTR i>0, for i=1,2,…,m.
5:   TOTC NCOL – INTEGER arrayInput
On entry: the n column totals, Cj, for j=1,2,…,n.
Constraints:
  • TOTC j≥0, for j=1,2,…,n;
  • ∑j=1 n TOTC j=∑i=1 m TOTR i.
6:   R LR – REAL (KIND=nag_wp) arrayCommunication Array
On entry: if MODE=1, the reference vector from the previous call to G05PZF.
On exit: the reference vector.
7:   LR – INTEGERInput
On entry: the dimension of the array R as declared in the (sub)program from which G05PZF is called.
Constraint: LR≥∑i=1 m TOTR i+5.
8:   STATE* – INTEGER arrayCommunication Array
Note: the actual argument supplied must be the array STATE supplied to the initialization routines G05KFF or G05KGF.
On entry: contains information on the selected base generator and its current state.
On exit: contains updated information on the state of the generator.
9:   X LDXNCOL – INTEGER arrayOutput
On exit: if MODE=1 or 2, a pseudorandom two-way m by n table, X, with element X ij containing the i,jth entry in the table such that ∑ i=1 m X ij=TOTC j and ∑ j=1 n X ij=TOTR i
10:   LDX – INTEGERInput
On entry: the first dimension of the array X as declared in the (sub)program from which G05PZF is called.
Constraint: LDX≥NROW.
11:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, MODE=value.
Constraint: MODE=0, 1 or 2.
IFAIL=2
On entry, NROW=value.
Constraint: NROW≥2.
IFAIL=3
On entry, NCOL=value.
Constraint: NCOL≥2.
IFAIL=4
On entry, at least one element of TOTR is negative or TOTR sums to zero.
IFAIL=5
On entry, TOTC has at least one negative element.
IFAIL=6
NROW or NCOL is not the same as when R was set up in a previous call.
Previous value of NROW=value and NROW=value.
Previous value of NCOL=value and NCOL=value.
IFAIL=7
On entry, LR is not large enough, LR=value: minimum length required =value.
IFAIL=8
On entry, STATE vector has been corrupted or not initialized.
IFAIL=10
On entry, LDX=value and NROW=value.
Constraint: LDX≥NROW.
IFAIL=15
On entry, the arrays TOTR and TOTC do not sum to the same total: TOTR array total is value, TOTC array total is value.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

None.

8 Parallelism and Performance

G05PZF is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

None.

10 Example

Following initialization of the pseudorandom number generator by a call to G05KFF, this example generates and prints a 4 by 3 two-way table, with row totals of 9, 11, 7 and 23 respectively, and column totals of 16, 17 and 17 respectively.

10.1 Program Text

Program Text (g05pzfe.f90)

10.2 Program Data

Program Data (g05pzfe.d)

10.3 Program Results

Program Results (g05pzfe.r)

G05 Chapter Contents
G05 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


G05RCF : NAG Library, Mark 26

G05 Chapter Contents
G05 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

G05RCF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

G05RCF sets up a reference vector and generates an array of pseudorandom numbers from a Student's t copula with ν degrees of freedom and covariance matrix ν ν-2 C .

2 Specification

SUBROUTINE G05RCF ( MODE, N, DF, M, C, LDC, R, LR, STATE, X, LDX, IFAIL)
INTEGER | MODE, N, DF, M, LDC, LR, STATE(*), LDX, IFAIL
REAL (KIND=nag_wp) | C(LDC,M), R(LR), X(LDX,M)

3 Description

The Student's t copula, G, is defined by
G u 1 , u 2 ,…, um ; C = T ν,C m t ν,C 11 -1 u 1 , t ν,C 22 -1 u 2 ,…, t ν,Cmm -1 um
where m is the number of dimensions, T ν,C m is the multivariate Student's t density function with ν degrees of freedom, mean zero and covariance matrix ν ν-2 C and t ν,Cii -1 is the inverse of the univariate Student's t density function with ν degrees of freedom, zero mean and variance ν ν-2 Cii .
G05RYF is used to generate a vector from a multivariate Student's t distribution and G01EBF is used to convert each element of that vector into a uniformly distributed value between zero and one.
One of the initialization routines G05KFF (for a repeatable sequence if computed sequentially) or G05KGF (for a non-repeatable sequence) must be called prior to the first call to G05RCF.

4 References

Nelsen R B (1998) An Introduction to Copulas. Lecture Notes in Statistics 139 Springer
Sklar A (1973) Random variables: joint distribution functions and copulas Kybernetika 9 499–460

5 Arguments

1:   MODE – INTEGERInput
On entry: a code for selecting the operation to be performed by the routine.
MODE=0
Set up reference vector only.
MODE=1
Generate variates using reference vector set up in a prior call to G05RCF.
MODE=2
Set up reference vector and generate variates.
Constraint: MODE=0, 1 or 2.
2:   N – INTEGERInput
On entry: n, the number of random variates required.
Constraint: N≥0.
3:   DF – INTEGERInput
On entry: ν, the number of degrees of freedom of the distribution.
Constraint: DF≥3 .
4:   M – INTEGERInput
On entry: m, the number of dimensions of the distribution.
Constraint: M>0.
5:   C LDCM – REAL (KIND=nag_wp) arrayInput
On entry: matrix which, along with DF, defines the covariance of the distribution. Only the upper triangle need be set.
Constraint: C must be positive semidefinite to machine precision.
6:   LDC – INTEGERInput
On entry: the first dimension of the array C as declared in the (sub)program from which G05RCF is called.
Constraint: LDC≥M.
7:   R LR – REAL (KIND=nag_wp) arrayCommunication Array
On entry: if MODE=1, the reference vector as set up by G05RCF in a previous call with MODE=0 or 2.
On exit: if MODE=0 or 2, the reference vector that can be used in subsequent calls to G05RCF with MODE=1.
8:   LR – INTEGERInput
On entry: the dimension of the array R as declared in the (sub)program from which G05RCF is called. If MODE=1, it must be the same as the value of LR specified in the prior call to G05RCF with MODE=0 or 2.
Constraint: LR≥M×M+1+2.
9:   STATE* – INTEGER arrayCommunication Array
Note: the actual argument supplied must be the array STATE supplied to the initialization routines G05KFF or G05KGF.
On entry: contains information on the selected base generator and its current state.
On exit: contains updated information on the state of the generator.
10:   X LDXM – REAL (KIND=nag_wp) arrayOutput
On exit: the array of values from a multivariate Student's t copula, with X ij holding the jth dimension for the ith variate.
11:   LDX – INTEGERInput
On entry: the first dimension of the array X as declared in the (sub)program from which G05RCF is called.
Constraint: LDX≥N.
12:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, MODE=value.
Constraint: MODE=0, 1 or 2.
IFAIL=2
On entry, N=value.
Constraint: N≥0.
IFAIL=3
On entry, DF=value.
Constraint: DF≥3.
IFAIL=4
On entry, M=value.
Constraint: M > 0.
IFAIL=5
On entry, the covariance matrix C is not positive semidefinite to machine precision.
IFAIL=6
On entry, LDC=value and M=value.
Constraint: LDC≥M.
IFAIL=7
M is not the same as when R was set up in a previous call.
Previous value of M=value and M=value.
IFAIL=8
On entry, LR is not large enough, LR=value: minimum length required =value.
IFAIL=9
On entry, STATE vector has been corrupted or not initialized.
IFAIL=11
On entry, LDX=value and N=value.
Constraint: LDX≥N.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

See Section 7 in G05RYF for an indication of the accuracy of the underlying multivariate Student's t-distribution.

8 Parallelism and Performance

G05RCF is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
G05RCF makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The time taken by G05RCF is of order n⁢m 3.
It is recommended that the diagonal elements of C should not differ too widely in order of magnitude. This may be achieved by scaling the variables if necessary. The actual matrix decomposed is C+E=L LT, where E is a diagonal matrix with small positive diagonal elements. This ensures that, even when C is singular, or nearly singular, the Cholesky factor L corresponds to a positive definite covariance matrix that agrees with C within machine precision.

10 Example

This example prints ten pseudorandom observations from a Student's t copula with ten degrees of freedom and C matrix
1.69 0.39 -1.86 0.07 0.39 98.01 -7.07 -0.71 -1.86 -7.07 11.56 0.03 0.07 -0.71 0.03 0.01 ,
generated by G05RCF. All ten observations are generated by a single call to G05RCF with MODE=2. The random number generator is initialized by G05KFF.

10.1 Program Text

Program Text (g05rcfe.f90)

10.2 Program Data

Program Data (g05rcfe.d)

10.3 Program Results

Program Results (g05rcfe.r)

G05 Chapter Contents
G05 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


G05RDF : NAG Library, Mark 26

G05 Chapter Contents
G05 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

G05RDF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

G05RDF sets up a reference vector and generates an array of pseudorandom numbers from a Normal (Gaussian) copula with covariance matrix C.

2 Specification

SUBROUTINE G05RDF ( MODE, N, M, C, LDC, R, LR, STATE, X, LDX, IFAIL)
INTEGER | MODE, N, M, LDC, LR, STATE(*), LDX, IFAIL
REAL (KIND=nag_wp) | C(LDC,M), R(LR), X(LDX,M)

3 Description

The Gaussian copula, G, is defined by
G u 1 , u 2 ,…, um ; C = ΦC ϕ C 11 -1 u 1 , ϕ C 22 -1 u 2 ,…, ϕ Cmm -1 um
where m is the number of dimensions, ΦC is the multivariate Normal density function with mean zero and covariance matrix C and ϕ Cii -1 is the inverse of the univariate Normal density function with mean zero and variance Cii .
G05RZF is used to generate a vector from a multivariate Normal distribution and G01EAF is used to convert each element of that vector into a uniformly distributed value between zero and one.
One of the initialization routines G05KFF (for a repeatable sequence if computed sequentially) or G05KGF (for a non-repeatable sequence) must be called prior to the first call to G05RDF.

4 References

Nelsen R B (1998) An Introduction to Copulas. Lecture Notes in Statistics 139 Springer
Sklar A (1973) Random variables: joint distribution functions and copulas Kybernetika 9 499–460

5 Arguments

1:   MODE – INTEGERInput
On entry: a code for selecting the operation to be performed by the routine.
MODE=0
Set up reference vector only.
MODE=1
Generate variates using reference vector set up in a prior call to G05RDF.
MODE=2
Set up reference vector and generate variates.
Constraint: MODE=0, 1 or 2.
2:   N – INTEGERInput
On entry: n, the number of random variates required.
Constraint: N≥0.
3:   M – INTEGERInput
On entry: m, the number of dimensions of the distribution.
Constraint: M>0.
4:   C LDCM – REAL (KIND=nag_wp) arrayInput
On entry: the covariance matrix of the distribution. Only the upper triangle need be set.
Constraint: C must be positive semidefinite to machine precision.
5:   LDC – INTEGERInput
On entry: the first dimension of the array C as declared in the (sub)program from which G05RDF is called.
Constraint: LDC≥M.
6:   R LR – REAL (KIND=nag_wp) arrayCommunication Array
On entry: if MODE=1, the reference vector as set up by G05RDF in a previous call with MODE=0 or 2.
On exit: if MODE=0 or 2, the reference vector that can be used in subsequent calls to G05RDF with MODE=1.
7:   LR – INTEGERInput
On entry: the dimension of the array R as declared in the (sub)program from which G05RDF is called. If MODE=1, it must be the same as the value of LR specified in the prior call to G05RDF with MODE=0 or 2.
Constraint: LR≥M×M+1+1.
8:   STATE* – INTEGER arrayCommunication Array
Note: the actual argument supplied must be the array STATE supplied to the initialization routines G05KFF or G05KGF.
On entry: contains information on the selected base generator and its current state.
On exit: contains updated information on the state of the generator.
9:   X LDXM – REAL (KIND=nag_wp) arrayOutput
On exit: the array of values from a multivariate Gaussian copula, with X ij holding the jth dimension for the ith variate.
10:   LDX – INTEGERInput
On entry: the first dimension of the array X as declared in the (sub)program from which G05RDF is called.
Constraint: LDX≥N.
11:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, MODE=value.
Constraint: MODE=0, 1 or 2.
IFAIL=2
On entry, N=value.
Constraint: N≥0.
IFAIL=3
On entry, M=value.
Constraint: M > 0.
IFAIL=4
On entry, the covariance matrix C is not positive semidefinite to machine precision.
IFAIL=5
On entry, LDC=value and M=value.
Constraint: LDC≥M.
IFAIL=6
M is not the same as when R was set up in a previous call.
Previous value of M=value and M=value.
IFAIL=7
On entry, LR is not large enough, LR=value: minimum length required =value.
IFAIL=8
On entry, STATE vector has been corrupted or not initialized.
IFAIL=10
On entry, LDX=value and N=value.
Constraint: LDX≥N.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

See Section 7 in G05RZF for an indication of the accuracy of the underlying multivariate Normal distribution.

8 Parallelism and Performance

G05RDF is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
G05RDF makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The time taken by G05RDF is of order n⁢m 3.
It is recommended that the diagonal elements of C should not differ too widely in order of magnitude. This may be achieved by scaling the variables if necessary. The actual matrix decomposed is C+E=L LT, where E is a diagonal matrix with small positive diagonal elements. This ensures that, even when C is singular, or nearly singular, the Cholesky factor L corresponds to a positive definite covariance matrix that agrees with C within machine precision.

10 Example

This example prints ten pseudorandom observations from a Normal copula with covariance matrix
1.69 0.39 -1.86 0.07 0.39 98.01 -7.07 -0.71 -1.86 -7.07 11.56 0.03 0.07 -0.71 0.03 0.01 ,
generated by G05RDF. All ten observations are generated by a single call to G05RDF with MODE=2. The random number generator is initialized by G05KFF.

10.1 Program Text

Program Text (g05rdfe.f90)

10.2 Program Data

Program Data (g05rdfe.d)

10.3 Program Results

Program Results (g05rdfe.r)

G05 Chapter Contents
G05 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


G05REF : NAG Library, Mark 26

G05 Chapter Contents
G05 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

G05REF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

G05REF generates pseudorandom uniform bivariates with joint distribution of a Clayton/Cook–Johnson Archimedean copula.

2 Specification

SUBROUTINE G05REF ( N, THETA, SORDER, STATE, X, LDX, SDX, IFAIL)
INTEGER | N, SORDER, STATE(*), LDX, SDX, IFAIL
REAL (KIND=nag_wp) | THETA, X(LDX,SDX)

3 Description

Generates pseudorandom uniform bivariates u1,u2∈0,1 2 whose joint distribution is the Clayton/Cook–Johnson Archimedean copula Cθ with parameter θ, given by
Cθ = max u1 -θ + u2 -θ -1 ,0 -1/θ ,   θ ∈ -1,∞ ∖ 0
with the special cases:
  • C-1 = max u1 + u2 -1 ,0 , the Fréchet–Hoeffding lower bound;
  • C0=u1u2, the product copula;
  • C∞=min u 1,u 2, the Fréchet–Hoeffding upper bound.
The generation method uses conditional sampling.
One of the initialization routines G05KFF (for a repeatable sequence if computed sequentially) or G05KGF (for a non-repeatable sequence) must be called prior to the first call to G05REF.

4 References

Nelsen R B (2006) An Introduction to Copulas (2nd Edition) Springer Series in Statistics

5 Arguments

1:   N – INTEGERInput
On entry: n, the number of bivariates to generate.
Constraint: N≥0.
2:   THETA – REAL (KIND=nag_wp)Input
On entry: θ, the copula parameter.
Constraint: THETA≥-1.0.
3:   SORDER – INTEGERInput
On entry: determines the storage order of variates; the i,jth variate is stored in X ij if SORDER=1, and X ji if SORDER=2, for i=1,2,…,n and j=1,2.
Constraint: SORDER=1 or 2.
4:   STATE* – INTEGER arrayCommunication Array
Note: the actual argument supplied must be the array STATE supplied to the initialization routines G05KFF or G05KGF.
On entry: contains information on the selected base generator and its current state.
On exit: contains updated information on the state of the generator.
5:   X LDXSDX – REAL (KIND=nag_wp) arrayOutput
On exit: the n bivariate uniforms with joint distribution described by Cθ, with X ij holding the ith value for the jth dimension if SORDER=1 and the jth value for the ith dimension if SORDER=2.
6:   LDX – INTEGERInput
On entry: the first dimension of the array X as declared in the (sub)program from which G05REF is called.
Constraints:
  • if SORDER=1, LDX≥N;
  • if SORDER=2, LDX≥2.
7:   SDX – INTEGERInput
On entry: the second dimension of the array X as declared in the (sub)program from which G05REF is called.
Constraints:
  • if SORDER=1, SDX≥2;
  • if SORDER=2, SDX≥N.
8:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, corrupt STATE argument.
IFAIL=2
On entry, invalid THETA: THETA=value.
Constraint: THETA≥-1.0.
IFAIL=3
On entry, N=value.
Constraint: N≥0.
IFAIL=4
On entry, invalid SORDER.
Constraint: SORDER=1 or 2.
IFAIL=6
On entry, LDX must be at least value: LDX=value.
IFAIL=7
On entry, SDX must be at least value: SDX=value.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

Not applicable.

8 Parallelism and Performance

G05REF is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

In practice, the need for numerical stability restricts the range of θ such that:
  • if θ+1<ε, the routine returns pseudorandom uniform variates with C-1 joint distribution;
  • if θ<1.0×10-6, the routine returns pseudorandom uniform variates with C 0 joint distribution;
  • if θ>ln⁡εs/ln 1.0×10-2, the routine returns pseudorandom uniform variates with C∞ joint distribution;
where εs is the safe-range parameter, the value of which is returned by X02AMF; and ε is the machine precision returned by X02AJF.

10 Example

This example generates thirteen variates for copula C-0.8.

10.1 Program Text

Program Text (g05refe.f90)

10.2 Program Data

Program Data (g05refe.d)

10.3 Program Results

Program Results (g05refe.r)

G05 Chapter Contents
G05 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


G05RFF : NAG Library, Mark 26

G05 Chapter Contents
G05 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

G05RFF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

G05RFF generates pseudorandom uniform bivariates with joint distribution of a Frank Archimedean copula.

2 Specification

SUBROUTINE G05RFF ( N, THETA, SORDER, STATE, X, LDX, SDX, IFAIL)
INTEGER | N, SORDER, STATE(*), LDX, SDX, IFAIL
REAL (KIND=nag_wp) | THETA, X(LDX,SDX)

3 Description

Generates pseudorandom uniform bivariates u1,u2∈0,1 2 whose joint distribution is the Frank Archimedean copula Cθ with parameter θ, given by
Cθ = - 1 θ ln 1 + e -θ u 1 -1 e -θ u 2 -1 e-θ-1 ,   θ ∈ -∞,∞ ∖ 0
with the special cases:
  • C-∞ = max u1 + u2 -1 ,0 , the Fréchet–Hoeffding lower bound;
  • C0=u1u2, the product copula;
  • C∞=min u 1,u 2, the Fréchet–Hoeffding upper bound.
The generation method uses conditional sampling.
One of the initialization routines G05KFF (for a repeatable sequence if computed sequentially) or G05KGF (for a non-repeatable sequence) must be called prior to the first call to G05RFF.

4 References

Nelsen R B (2006) An Introduction to Copulas (2nd Edition) Springer Series in Statistics

5 Arguments

1:   N – INTEGERInput
On entry: n, the number of bivariates to generate.
Constraint: N≥0.
2:   THETA – REAL (KIND=nag_wp)Input
On entry: θ, the copula parameter.
3:   SORDER – INTEGERInput
On entry: determines the storage order of variates; the i,jth variate is stored in X ij if SORDER=1, and X ji if SORDER=2, for i=1,2,…,n and j=1,2.
Constraint: SORDER=1 or 2.
4:   STATE* – INTEGER arrayCommunication Array
Note: the actual argument supplied must be the array STATE supplied to the initialization routines G05KFF or G05KGF.
On entry: contains information on the selected base generator and its current state.
On exit: contains updated information on the state of the generator.
5:   X LDXSDX – REAL (KIND=nag_wp) arrayOutput
On exit: the n bivariate uniforms with joint distribution described by Cθ, with X ij holding the ith value for the jth dimension if SORDER=1 and the jth value for the ith dimension if SORDER=2.
6:   LDX – INTEGERInput
On entry: the first dimension of the array X as declared in the (sub)program from which G05RFF is called.
Constraints:
  • if SORDER=1, LDX≥N;
  • if SORDER=2, LDX≥2.
7:   SDX – INTEGERInput
On entry: the second dimension of the array X as declared in the (sub)program from which G05RFF is called.
Constraints:
  • if SORDER=1, SDX≥2;
  • if SORDER=2, SDX≥N.
8:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, corrupt STATE argument.
IFAIL=3
On entry, N=value.
Constraint: N≥0.
IFAIL=4
On entry, invalid SORDER.
Constraint: SORDER=1 or 2.
IFAIL=6
On entry, LDX must be at least value: LDX=value.
IFAIL=7
On entry, SDX must be at least value: SDX=value.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

Not applicable.

8 Parallelism and Performance

G05RFF is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

In practice, the need for numerical stability restricts the range of θ such that:
  • if θ<ln⁡εs, the routine returns pseudorandom uniform variates with C-∞ joint distribution;
  • if θ<1.0×10-6, the routine returns pseudorandom uniform variates with C 0 joint distribution;
  • if θ>ln⁡ε, the routine returns pseudorandom uniform variates with C∞ joint distribution;
where εs is the safe-range parameter, the value of which is returned by X02AMF; and ε is the machine precision returned by X02AJF.

10 Example

This example generates thirteen variates for copula C-12.0.

10.1 Program Text

Program Text (g05rffe.f90)

10.2 Program Data

Program Data (g05rffe.d)

10.3 Program Results

Program Results (g05rffe.r)

G05 Chapter Contents
G05 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


G05RGF : NAG Library, Mark 26

G05 Chapter Contents
G05 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

G05RGF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

G05RGF generates pseudorandom uniform bivariates with joint distribution of a Plackett copula.

2 Specification

SUBROUTINE G05RGF ( N, THETA, SORDER, STATE, X, LDX, SDX, IFAIL)
INTEGER | N, SORDER, STATE(*), LDX, SDX, IFAIL
REAL (KIND=nag_wp) | THETA, X(LDX,SDX)

3 Description

Generates pseudorandom uniform bivariates u1,u2∈0,1 2 whose joint distribution is the Plackett copula Cθ with parameter θ, given by
Cθ = 1 + θ-1 u 1 + u 2 - 1 + θ-1 u 1 + u 2 2 - 4 u 1 u 2 θ θ-1 2 θ-1 ,   θ ∈ 0,∞ ∖ 1
with the special cases:
  • C 0 = max u1 + u2 -1 ,0 , the Fréchet–Hoeffding lower bound;
  • C 1=u1u2, the product copula;
  • C∞=min u 1,u 2, the Fréchet–Hoeffding upper bound.
The generation method uses conditional sampling.
One of the initialization routines G05KFF (for a repeatable sequence if computed sequentially) or G05KGF (for a non-repeatable sequence) must be called prior to the first call to G05RGF.

4 References

Nelsen R B (2006) An Introduction to Copulas (2nd Edition) Springer Series in Statistics

5 Arguments

1:   N – INTEGERInput
On entry: n, the number of bivariates to generate.
Constraint: N≥0.
2:   THETA – REAL (KIND=nag_wp)Input
On entry: θ, the copula parameter.
Constraint: THETA≥0.0.
3:   SORDER – INTEGERInput
On entry: determines the storage order of variates; the i,jth variate is stored in X ij if SORDER=1, and X ji if SORDER=2, for i=1,2,…,n and j=1,2.
Constraint: SORDER=1 or 2.
4:   STATE* – INTEGER arrayCommunication Array
Note: the actual argument supplied must be the array STATE supplied to the initialization routines G05KFF or G05KGF.
On entry: contains information on the selected base generator and its current state.
On exit: contains updated information on the state of the generator.
5:   X LDXSDX – REAL (KIND=nag_wp) arrayOutput
On exit: the n bivariate uniforms with joint distribution described by Cθ, with X ij holding the ith value for the jth dimension if SORDER=1 and the jth value for the ith dimension if SORDER=2.
6:   LDX – INTEGERInput
On entry: the first dimension of the array X as declared in the (sub)program from which G05RGF is called.
Constraints:
  • if SORDER=1, LDX≥N;
  • if SORDER=2, LDX≥2.
7:   SDX – INTEGERInput
On entry: the second dimension of the array X as declared in the (sub)program from which G05RGF is called.
Constraints:
  • if SORDER=1, SDX≥2;
  • if SORDER=2, SDX≥N.
8:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, corrupt STATE argument.
IFAIL=2
On entry, invalid THETA: THETA=value.
Constraint: THETA≥0.0.
IFAIL=3
On entry, N=value.
Constraint: N≥0.
IFAIL=4
On entry, invalid SORDER.
Constraint: SORDER=1 or 2.
IFAIL=6
On entry, LDX must be at least value: LDX=value.
IFAIL=7
On entry, SDX must be at least value: SDX=value.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

Not applicable.

8 Parallelism and Performance

G05RGF is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

In practice, the need for numerical stability restricts the range of θ such that:
  • if θ<εs, the routine returns pseudorandom uniform variates with C 0 joint distribution;
  • if θ-1<ε, the routine returns pseudorandom uniform variates with C 1 joint distribution;
  • if θ>εs-1/2, the routine returns pseudorandom uniform variates with C∞ joint distribution;
where εs is the safe-range parameter, the value of which is returned by X02AMF; and ε is the machine precision returned by X02AJF.

10 Example

This example generates thirteen variates for copula C 2.0.

10.1 Program Text

Program Text (g05rgfe.f90)

10.2 Program Data

Program Data (g05rgfe.d)

10.3 Program Results

Program Results (g05rgfe.r)

G05 Chapter Contents
G05 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


G05RHF : NAG Library, Mark 26

G05 Chapter Contents
G05 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

G05RHF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

G05RHF generates pseudorandom uniform variates with joint distribution of a Clayton/Cook–Johnson Archimedean copula.

2 Specification

SUBROUTINE G05RHF ( N, M, THETA, SORDER, STATE, X, LDX, SDX, IFAIL)
INTEGER | N, M, SORDER, STATE(*), LDX, SDX, IFAIL
REAL (KIND=nag_wp) | THETA, X(LDX,SDX)

3 Description

Generates n pseudorandom uniform m-variates whose joint distribution is the Clayton/Cook–Johnson Archimedean copula Cθ, given by
Cθ = u 1-θ + u 2-θ + ⋯ + um-θ - m + 1 -1/θ ,   θ ∈ 0,∞ , uj ∈ 0,1 ,   j = 1 , … m ;
with the special case:
  • C∞ = min u1,u2,…,um , the Fréchet–Hoeffding upper bound.
The generation method uses mixture of powers.
One of the initialization routines G05KFF (for a repeatable sequence if computed sequentially) or G05KGF (for a non-repeatable sequence) must be called prior to the first call to G05RHF.

4 References

Marshall A W and Olkin I (1988) Families of multivariate distributions Journal of the American Statistical Association 83 403
Nelsen R B (2006) An Introduction to Copulas (2nd Edition) Springer Series in Statistics

5 Arguments

1:   N – INTEGERInput
On entry: n, the number of pseudorandom uniform variates to generate.
Constraint: N≥0.
2:   M – INTEGERInput
On entry: m, the number of dimensions.
Constraint: M≥2.
3:   THETA – REAL (KIND=nag_wp)Input
On entry: θ, the copula parameter.
Constraint: THETA≥1.0×10-6.
4:   SORDER – INTEGERInput
On entry: determines the storage order of variates; the i,jth variate is stored in X ij if SORDER=1, and X ji if SORDER=2, for i=1,2,…,n and j=1,2,…,m.
Constraint: SORDER=1 or 2.
5:   STATE* – INTEGER arrayCommunication Array
Note: the actual argument supplied must be the array STATE supplied to the initialization routines G05KFF or G05KGF.
On entry: contains information on the selected base generator and its current state.
On exit: contains updated information on the state of the generator.
6:   X LDXSDX – REAL (KIND=nag_wp) arrayOutput
On exit: the pseudorandom uniform variates with joint distribution described by Cθ, with X ij holding the ith value for the jth dimension if SORDER=1 and the jth value for the ith dimension of SORDER=2.
7:   LDX – INTEGERInput
On entry: the first dimension of the array X as declared in the (sub)program from which G05RHF is called.
Constraints:
  • if SORDER=1, LDX≥N;
  • if SORDER=2, LDX≥M.
8:   SDX – INTEGERInput
On entry: the second dimension of the array X as declared in the (sub)program from which G05RHF is called.
Constraints:
  • if SORDER=1, SDX≥M;
  • if SORDER=2, SDX≥N.
9:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, corrupt STATE argument.
IFAIL=2
On entry, invalid THETA: THETA=value.
Constraint: THETA≥1.0×10-6.
IFAIL=3
On entry, N=value.
Constraint: N≥0.
IFAIL=4
On entry, M=value.
Constraint: M≥2.
IFAIL=5
On entry, invalid SORDER.
Constraint: SORDER=1 or 2.
IFAIL=7
On entry, LDX must be at least value: LDX=value.
IFAIL=8
On entry, SDX must be at least value: SDX=value.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

Not applicable.

8 Parallelism and Performance

G05RHF is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

In practice, the need for numerical stability restricts the range of θ such that:
  • the routine requires θ≥1.0×10-6;
  • if θ>200.0, the routine returns pseudorandom uniform variates with C∞ joint distribution.

10 Example

This example generates thirteen four-dimensional variates for copula C 1.3.

10.1 Program Text

Program Text (g05rhfe.f90)

10.2 Program Data

Program Data (g05rhfe.d)

10.3 Program Results

Program Results (g05rhfe.r)

G05 Chapter Contents
G05 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


G05RJF : NAG Library, Mark 26

G05 Chapter Contents
G05 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

G05RJF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

G05RJF generates pseudorandom uniform variates with joint distribution of a Frank Archimedean copula.

2 Specification

SUBROUTINE G05RJF ( N, M, THETA, SORDER, STATE, X, LDX, SDX, IFAIL)
INTEGER | N, M, SORDER, STATE(*), LDX, SDX, IFAIL
REAL (KIND=nag_wp) | THETA, X(LDX,SDX)

3 Description

Generates n pseudorandom uniform m-variates whose joint distribution is the Frank Archimedean copula Cθ, given by
Cθ = - 1 θ ln 1 + e -θ u 1 -1 e -θ u 2 -1 ⋯ e -θ um -1 e-θ - 1 m-1 ,   θ ∈ 0,∞ , uj ∈ 0,1 ,   j = 1 , … m ;
with the special case:
  • C∞ = min u1,u2,…,um , the Fréchet–Hoeffding upper bound.
The generation method uses mixture of powers.
One of the initialization routines G05KFF (for a repeatable sequence if computed sequentially) or G05KGF (for a non-repeatable sequence) must be called prior to the first call to G05RJF.

4 References

Marshall A W and Olkin I (1988) Families of multivariate distributions Journal of the American Statistical Association 83 403
Nelsen R B (2006) An Introduction to Copulas (2nd Edition) Springer Series in Statistics

5 Arguments

1:   N – INTEGERInput
On entry: n, the number of pseudorandom uniform variates to generate.
Constraint: N≥0.
2:   M – INTEGERInput
On entry: m, the number of dimensions.
Constraint: M≥2.
3:   THETA – REAL (KIND=nag_wp)Input
On entry: θ, the copula parameter.
Constraint: THETA≥1.0×10-6.
4:   SORDER – INTEGERInput
On entry: determines the storage order of variates; the i,jth variate is stored in X ij if SORDER=1, and X ji if SORDER=2, for i=1,2,…,n and j=1,2,…,m.
Constraint: SORDER=1 or 2.
5:   STATE* – INTEGER arrayCommunication Array
Note: the actual argument supplied must be the array STATE supplied to the initialization routines G05KFF or G05KGF.
On entry: contains information on the selected base generator and its current state.
On exit: contains updated information on the state of the generator.
6:   X LDXSDX – REAL (KIND=nag_wp) arrayOutput
On exit: the pseudorandom uniform variates with joint distribution described by Cθ, with X ij holding the ith value for the jth dimension if SORDER=1 and the jth value for the ith dimension of SORDER=2.
7:   LDX – INTEGERInput
On entry: the first dimension of the array X as declared in the (sub)program from which G05RJF is called.
Constraints:
  • if SORDER=1, LDX≥N;
  • if SORDER=2, LDX≥M.
8:   SDX – INTEGERInput
On entry: the second dimension of the array X as declared in the (sub)program from which G05RJF is called.
Constraints:
  • if SORDER=1, SDX≥M;
  • if SORDER=2, SDX≥N.
9:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, corrupt STATE argument.
IFAIL=2
On entry, invalid THETA: THETA=value.
Constraint: THETA≥1.0×10-6.
IFAIL=3
On entry, N=value.
Constraint: N≥0.
IFAIL=4
On entry, M=value.
Constraint: M≥2.
IFAIL=5
On entry, invalid SORDER.
Constraint: SORDER=1 or 2.
IFAIL=7
On entry, LDX must be at least value: LDX=value.
IFAIL=8
On entry, SDX must be at least value: SDX=value.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

Not applicable.

8 Parallelism and Performance

G05RJF is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

In practice, the need for numerical stability restricts the range of θ such that:
  • the routine requires θ≥1.0×10-6;
  • if θ>-ln⁡ε, the routine returns pseudorandom uniform variates with C∞ joint distribution;
where ε is the machine precision returned by X02AJF.

10 Example

This example generates thirteen four-dimensional variates for copula C 4.0.

10.1 Program Text

Program Text (g05rjfe.f90)

10.2 Program Data

Program Data (g05rjfe.d)

10.3 Program Results

Program Results (g05rjfe.r)

G05 Chapter Contents
G05 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


G05RKF : NAG Library, Mark 26

G05 Chapter Contents
G05 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

G05RKF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

G05RKF generates pseudorandom uniform variates with joint distribution of a Gumbel–Hougaard Archimedean copula.

2 Specification

SUBROUTINE G05RKF ( N, M, THETA, SORDER, STATE, X, LDX, SDX, IFAIL)
INTEGER | N, M, SORDER, STATE(*), LDX, SDX, IFAIL
REAL (KIND=nag_wp) | THETA, X(LDX,SDX)

3 Description

Generates n pseudorandom uniform m-variates whose joint distribution is the Gumbel–Hougaard Archimedean copula Cθ, given by
Cθ = exp - -ln⁡u 1 θ + -ln⁡u 2 θ + ⋯ + -ln⁡um θ ,   θ ∈ 1,∞ , uj ∈ 0,1 ,   j = 1 , 2 , … m ;
with the special cases:
  • C 1 = u1 u2 ⋯ um , the product copula;
  • C∞ = min u1,u2,…,um , the Fréchet–Hoeffding upper bound.
The generation method uses mixture of powers.
One of the initialization routines G05KFF (for a repeatable sequence if computed sequentially) or G05KGF (for a non-repeatable sequence) must be called prior to the first call to G05RKF.

4 References

Marshall A W and Olkin I (1988) Families of multivariate distributions Journal of the American Statistical Association 83 403
Nelsen R B (2006) An Introduction to Copulas (2nd Edition) Springer Series in Statistics

5 Arguments

1:   N – INTEGERInput
On entry: n, the number of pseudorandom uniform variates to generate.
Constraint: N≥0.
2:   M – INTEGERInput
On entry: m, the number of dimensions.
Constraint: M≥2.
3:   THETA – REAL (KIND=nag_wp)Input
On entry: θ, the copula parameter.
Constraint: THETA≥1.0.
4:   SORDER – INTEGERInput
On entry: determines the storage order of variates; the i,jth variate is stored in X ij if SORDER=1, and X ji if SORDER=2, for i=1,2,…,n and j=1,2,…,m.
Constraint: SORDER=1 or 2.
5:   STATE* – INTEGER arrayCommunication Array
Note: the actual argument supplied must be the array STATE supplied to the initialization routines G05KFF or G05KGF.
On entry: contains information on the selected base generator and its current state.
On exit: contains updated information on the state of the generator.
6:   X LDXSDX – REAL (KIND=nag_wp) arrayOutput
On exit: the pseudorandom uniform variates with joint distribution described by Cθ, with X ij holding the ith value for the jth dimension if SORDER=1 and the jth value for the ith dimension of SORDER=2.
7:   LDX – INTEGERInput
On entry: the first dimension of the array X as declared in the (sub)program from which G05RKF is called.
Constraints:
  • if SORDER=1, LDX≥N;
  • if SORDER=2, LDX≥M.
8:   SDX – INTEGERInput
On entry: the second dimension of the array X as declared in the (sub)program from which G05RKF is called.
Constraints:
  • if SORDER=1, SDX≥M;
  • if SORDER=2, SDX≥N.
9:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, corrupt STATE argument.
IFAIL=2
On entry, invalid THETA: THETA=value.
Constraint: THETA≥1.0.
IFAIL=3
On entry, N=value.
Constraint: N≥0.
IFAIL=4
On entry, M=value.
Constraint: M≥2.
IFAIL=5
On entry, invalid SORDER.
Constraint: SORDER=1 or 2.
IFAIL=7
On entry, LDX must be at least value: LDX=value.
IFAIL=8
On entry, SDX must be at least value: SDX=value.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

Not applicable.

8 Parallelism and Performance

G05RKF is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

In practice, the need for numerical stability restricts the range of θ such that:
  • if θ-1<1.0×10-6, the routine returns pseudorandom uniform variates with C 1 joint distribution;
  • if θ>max 80.0,-0.5 ln⁡εs, the routine returns pseudorandom uniform variates with C∞ joint distribution;
where εs is the safe-range parameter, the value of which is returned by X02AMF.

10 Example

This example generates thirteen four-dimensional variates for copula C 2.4.

10.1 Program Text

Program Text (g05rkfe.f90)

10.2 Program Data

Program Data (g05rkfe.d)

10.3 Program Results

Program Results (g05rkfe.r)

G05 Chapter Contents
G05 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


G05RYF : NAG Library, Mark 26

G05 Chapter Contents
G05 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

G05RYF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

G05RYF sets up a reference vector and generates an array of pseudorandom numbers from a multivariate Student's t distribution with ν degrees of freedom, mean vector a and covariance matrix ν ν-2 C .

2 Specification

SUBROUTINE G05RYF ( MODE, N, DF, M, XMU, C, LDC, R, LR, STATE, X, LDX, IFAIL)
INTEGER | MODE, N, DF, M, LDC, LR, STATE(*), LDX, IFAIL
REAL (KIND=nag_wp) | XMU(M), C(LDC,M), R(LR), X(LDX,M)

3 Description

When the covariance matrix is nonsingular (i.e., strictly positive definite), the distribution has probability density function
f x = Γ ν+m 2 πv m/2 Γ ν/2 C 12 1 + x-a T C-1 x-a ν -ν+m 2
where m is the number of dimensions, ν is the degrees of freedom, a is the vector of means, x is the vector of positions and ν ν-2 C is the covariance matrix.
The routine returns the value
x = a + νs z
where z is generated by G05SKF from a Normal distribution with mean zero and covariance matrix C and s is generated by G05SDF from a χ 2-distribution with ν degrees of freedom.
One of the initialization routines G05KFF (for a repeatable sequence if computed sequentially) or G05KGF (for a non-repeatable sequence) must be called prior to the first call to G05RYF.

4 References

Knuth D E (1981) The Art of Computer Programming (Volume 2) (2nd Edition) Addison–Wesley
Wilkinson J H (1965) The Algebraic Eigenvalue Problem Oxford University Press, Oxford

5 Arguments

1:   MODE – INTEGERInput
On entry: a code for selecting the operation to be performed by the routine.
MODE=0
Set up reference vector only.
MODE=1
Generate variates using reference vector set up in a prior call to G05RYF.
MODE=2
Set up reference vector and generate variates.
Constraint: MODE=0, 1 or 2.
2:   N – INTEGERInput
On entry: n, the number of random variates required.
Constraint: N≥0.
3:   DF – INTEGERInput
On entry: ν, the number of degrees of freedom of the distribution.
Constraint: DF≥3 .
4:   M – INTEGERInput
On entry: m, the number of dimensions of the distribution.
Constraint: M>0.
5:   XMU M – REAL (KIND=nag_wp) arrayInput
On entry: a, the vector of means of the distribution.
6:   C LDCM – REAL (KIND=nag_wp) arrayInput
On entry: matrix which, along with DF, defines the covariance of the distribution. Only the upper triangle need be set.
Constraint: C must be positive semidefinite to machine precision.
7:   LDC – INTEGERInput
On entry: the first dimension of the array C as declared in the (sub)program from which G05RYF is called.
Constraint: LDC≥M.
8:   R LR – REAL (KIND=nag_wp) arrayInput/Output
On entry: if MODE=1, the reference vector as set up by G05RYF in a previous call with MODE=0 or 2.
On exit: if MODE=0 or 2, the reference vector that can be used in subsequent calls to G05RYF with MODE=1.
9:   LR – INTEGERInput
On entry: the dimension of the array R as declared in the (sub)program from which G05RYF is called. If MODE=1, it must be the same as the value of LR specified in the prior call to G05RYF with MODE=0 or 2.
Constraint: LR≥M×M+1+2.
10:   STATE* – INTEGER arrayCommunication Array
Note: the actual argument supplied must be the array STATE supplied to the initialization routines G05KFF or G05KGF.
On entry: contains information on the selected base generator and its current state.
On exit: contains updated information on the state of the generator.
11:   X LDXM – REAL (KIND=nag_wp) arrayOutput
On exit: the array of pseudorandom multivariate Student's t vectors generated by the routine, with X ij holding the jth dimension for the ith variate.
12:   LDX – INTEGERInput
On entry: the first dimension of the array X as declared in the (sub)program from which G05RYF is called.
Constraint: LDX≥N.
13:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, MODE=value.
Constraint: MODE=0, 1 or 2.
IFAIL=2
On entry, N=value.
Constraint: N≥0.
IFAIL=3
On entry, DF=value.
Constraint: DF≥3.
IFAIL=4
On entry, M=value.
Constraint: M > 0.
IFAIL=6
On entry, the covariance matrix C is not positive semidefinite to machine precision.
IFAIL=7
On entry, LDC=value and M=value.
Constraint: LDC≥M.
IFAIL=8
M is not the same as when R was set up in a previous call.
Previous value of M=value and M=value.
IFAIL=9
On entry, LR is not large enough, LR=value: minimum length required =value.
IFAIL=10
On entry, STATE vector has been corrupted or not initialized.
IFAIL=12
On entry, LDX=value and N=value.
Constraint: LDX≥N.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

Not applicable.

8 Parallelism and Performance

G05RYF is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
G05RYF makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The time taken by G05RYF is of order n⁢m 3.
It is recommended that the diagonal elements of C should not differ too widely in order of magnitude. This may be achieved by scaling the variables if necessary. The actual matrix decomposed is C+E=L LT, where E is a diagonal matrix with small positive diagonal elements. This ensures that, even when C is singular, or nearly singular, the Cholesky factor L corresponds to a positive definite covariance matrix that agrees with C within machine precision.

10 Example

This example prints ten pseudorandom observations from a multivariate Student's t-distribution with ten degrees of freedom, means vector
1.0 2.0 -3.0 0.0
and C matrix
1.69 0.39 -1.86 0.07 0.39 98.01 -7.07 -0.71 -1.86 -7.07 11.56 0.03 0.07 -0.71 0.03 0.01 ,
generated by G05RYF. All ten observations are generated by a single call to G05RYF with MODE=2. The random number generator is initialized by G05KFF.

10.1 Program Text

Program Text (g05ryfe.f90)

10.2 Program Data

Program Data (g05ryfe.d)

10.3 Program Results

Program Results (g05ryfe.r)

G05 Chapter Contents
G05 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


G05RZF : NAG Library, Mark 26

G05 Chapter Contents
G05 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

G05RZF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

G05RZF sets up a reference vector and generates an array of pseudorandom numbers from a multivariate Normal distribution with mean vector a and covariance matrix C.

2 Specification

SUBROUTINE G05RZF ( MODE, N, M, XMU, C, LDC, R, LR, STATE, X, LDX, IFAIL)
INTEGER | MODE, N, M, LDC, LR, STATE(*), LDX, IFAIL
REAL (KIND=nag_wp) | XMU(M), C(LDC,M), R(LR), X(LDX,*)

3 Description

When the covariance matrix is nonsingular (i.e., strictly positive definite), the distribution has probability density function
f x = C-1 2 π m exp - 12 x-a T C-1 x-a
where m is the number of dimensions, C is the covariance matrix, a is the vector of means and x is the vector of positions.
Covariance matrices are symmetric and positive semidefinite. Given such a matrix C, there exists a lower triangular matrix L such that L LT=C. L is not unique, if C is singular.
G05RZF decomposes C to find such an L. It then stores m, a and L in the reference vector r which is used to generate a vector x of independent standard Normal pseudorandom numbers. It then returns the vector a+Lx, which has the required multivariate Normal distribution.
It should be noted that this routine will work with a singular covariance matrix C, provided C is positive semidefinite, despite the fact that the above formula for the probability density function is not valid in that case. Wilkinson (1965) should be consulted if further information is required.
One of the initialization routines G05KFF (for a repeatable sequence if computed sequentially) or G05KGF (for a non-repeatable sequence) must be called prior to the first call to G05RZF.

4 References

Knuth D E (1981) The Art of Computer Programming (Volume 2) (2nd Edition) Addison–Wesley
Wilkinson J H (1965) The Algebraic Eigenvalue Problem Oxford University Press, Oxford

5 Arguments

1:   MODE – INTEGERInput
On entry: a code for selecting the operation to be performed by the routine.
MODE=0
Set up reference vector only.
MODE=1 or 3
Generate variates using reference vector set up in a prior call to G05RZF.
MODE=2 or 4
Set up reference vector and generate variates.
The variates are stored differently in X for MODE=1 or 2 compared with MODE=3 or 4.
Constraint: MODE=0, 1, 2, 3 or 4.
2:   N – INTEGERInput
On entry: n, the number of random variates required.
Constraint: N≥0.
3:   M – INTEGERInput
On entry: m, the number of dimensions of the distribution.
Constraint: M>0.
4:   XMU M – REAL (KIND=nag_wp) arrayInput
On entry: a, the vector of means of the distribution.
5:   C LDCM – REAL (KIND=nag_wp) arrayInput
On entry: the covariance matrix of the distribution. Only the upper triangle need be set.
Constraint: C must be positive semidefinite to machine precision.
6:   LDC – INTEGERInput
On entry: the first dimension of the array C as declared in the (sub)program from which G05RZF is called.
Constraint: LDC≥M.
7:   R LR – REAL (KIND=nag_wp) arrayInput/Output
On entry: if MODE=1 or 3, the reference vector as set up by G05RZF in a previous call with MODE=0, 2 or 4.
On exit: if MODE=0 or 2, the reference vector that can be used in subsequent calls to G05RZF with MODE=1 or 3.
8:   LR – INTEGERInput
On entry: the dimension of the array R as declared in the (sub)program from which G05RZF is called. If MODE=1 or 3, it must be the same as the value of LR specified in the prior call to G05RZF with MODE=0, 2 or 4.
Constraint: LR≥M×M+1+1.
9:   STATE* – INTEGER arrayCommunication Array
Note: the actual argument supplied must be the array STATE supplied to the initialization routines G05KFF or G05KGF.
On entry: contains information on the selected base generator and its current state.
On exit: contains updated information on the state of the generator.
10:   X LDX* – REAL (KIND=nag_wp) arrayOutput
Note: the second dimension of the array X must be at least M if MODE=1 or 2 and at least N if MODE=3 or 4.
On exit: the array of pseudorandom multivariate Normal vectors generated by the routine.
Two possible storage orders are available. If MODE=1 or 2 then X ij holds the jth dimension for the ith variate. If MODE=3 or 4 this ordering is reversed and X ji holds the jth dimension for the ith variate.
11:   LDX – INTEGERInput
On entry: the first dimension of the array X as declared in the (sub)program from which G05RZF is called.
Constraints:
  • if MODE=1 or 2, LDX≥N;
  • if MODE=3 or 4, LDX≥M.
12:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, invalid value for MODE.
Constraint: MODE=0, 1, 2, 3 or 4.
IFAIL=2
On entry, N=value.
Constraint: N≥0.
IFAIL=3
On entry, M=value.
Constraint: M > 0.
IFAIL=5
On entry, the covariance matrix C is not positive semidefinite to machine precision.
IFAIL=6
On entry, LDC=value and M=value.
Constraint: LDC≥M.
IFAIL=7
M is not the same as when R was set up in a previous call.
Previous value of M=value and M=value.
IFAIL=8
On entry, LR is not large enough, LR=value: minimum length required =value.
IFAIL=9
On entry, STATE vector has been corrupted or not initialized.
IFAIL=11
On entry, LDX=value and M=value.
Constraint: LDX≥M.
On entry, LDX=value and N=value.
Constraint: LDX≥N.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

Not applicable.

8 Parallelism and Performance

G05RZF is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
G05RZF makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The time taken by G05RZF is of order n⁢m 3.
It is recommended that the diagonal elements of C should not differ too widely in order of magnitude. This may be achieved by scaling the variables if necessary. The actual matrix decomposed is C+E=L LT, where E is a diagonal matrix with small positive diagonal elements. This ensures that, even when C is singular, or nearly singular, the Cholesky factor L corresponds to a positive definite covariance matrix that agrees with C within machine precision.

10 Example

This example prints ten pseudorandom observations from a multivariate Normal distribution with means vector
1.0 2.0 -3.0 0.0
and covariance matrix
1.69 0.39 -1.86 0.07 0.39 98.01 -7.07 -0.71 -1.86 -7.07 11.56 0.03 0.07 -0.71 0.03 0.01 ,
generated by G05RZF. All ten observations are generated by a single call to G05RZF with MODE=2. The random number generator is initialized by G05KFF.

10.1 Program Text

Program Text (g05rzfe.f90)

10.2 Program Data

Program Data (g05rzfe.d)

10.3 Program Results

Program Results (g05rzfe.r)

G05 Chapter Contents
G05 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


G05SAF : NAG Library, Mark 26

G05 Chapter Contents
G05 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

G05SAF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

G05SAF generates a vector of pseudorandom numbers taken from a uniform distribution between 0 and 1.

2 Specification

SUBROUTINE G05SAF ( N, STATE, X, IFAIL)
INTEGER | N, STATE(*), IFAIL
REAL (KIND=nag_wp) | X(N)

3 Description

G05SAF generates n values from a uniform distribution over the half closed interval 0,1.
One of the initialization routines G05KFF (for a repeatable sequence if computed sequentially) or G05KGF (for a non-repeatable sequence) must be called prior to the first call to G05SAF.

4 References

Knuth D E (1981) The Art of Computer Programming (Volume 2) (2nd Edition) Addison–Wesley

5 Arguments

1:   N – INTEGERInput
On entry: n, the number of pseudorandom numbers to be generated.
Constraint: N≥0.
2:   STATE* – INTEGER arrayCommunication Array
Note: the actual argument supplied must be the array STATE supplied to the initialization routines G05KFF or G05KGF.
On entry: contains information on the selected base generator and its current state.
On exit: contains updated information on the state of the generator.
3:   X N – REAL (KIND=nag_wp) arrayOutput
On exit: the n pseudorandom numbers from a uniform distribution over the half closed interval 0,1.
4:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, N=value.
Constraint: N≥0.
IFAIL=2
On entry, STATE vector has been corrupted or not initialized.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

Not applicable.

8 Parallelism and Performance

G05SAF is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

None.

10 Example

This example prints the first five pseudorandom numbers from a uniform distribution between 0 and 1, generated by G05SAF after initialization by G05KFF.

10.1 Program Text

Program Text (g05safe.f90)

10.2 Program Data

Program Data (g05safe.d)

10.3 Program Results

Program Results (g05safe.r)

G05 Chapter Contents
G05 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


G05SBF : NAG Library, Mark 26

G05 Chapter Contents
G05 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

G05SBF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

G05SBF generates a vector of pseudorandom numbers taken from a beta distribution with parameters a and b.

2 Specification

SUBROUTINE G05SBF ( N, A, B, STATE, X, IFAIL)
INTEGER | N, STATE(*), IFAIL
REAL (KIND=nag_wp) | A, B, X(N)

3 Description

The beta distribution has PDF (probability density function)
f x = Γ a+b Γ a Γ b x a-1 1-x b-1 if 0≤x≤1 ; ​ a,b>0 , f x=0 otherwise.
One of four algorithms is used to generate the variates depending on the values of a and b. Let α be the maximum and β be the minimum of a and b. Then the algorithms are as follows:
(i) | if α<0.5, Johnk's algorithm is used, see for example Dagpunar (1988). This generates the beta variate as u 1 1/a/ u 1 1/a+u 2 1/b , where u 1 and u 2 are uniformly distributed random variates;
(ii) | if β>1, the algorithm BB given by Cheng (1978) is used. This involves the generation of an observation from a beta distribution of the second kind by the envelope rejection method using a log-logistic target distribution and then transforming it to a beta variate;
(iii) | if α>1 and β<1, the switching algorithm given by Atkinson (1979) is used. The two target distributions used are f 1 x=β xβ and f 2 x=α 1-x β-1, along with the approximation to the switching argument of t=1-β/α+1-β;
(iv) | in all other cases, Cheng's BC algorithm (see Cheng (1978)) is used with modifications suggested by Dagpunar (1988). This algorithm is similar to BB, used when β>1, but is tuned for small values of a and b.
One of the initialization routines G05KFF (for a repeatable sequence if computed sequentially) or G05KGF (for a non-repeatable sequence) must be called prior to the first call to G05SBF.

4 References

Atkinson A C (1979) A family of switching algorithms for the computer generation of beta random variates Biometrika 66 141–5
Cheng R C H (1978) Generating beta variates with nonintegral shape parameters Comm. ACM 21 317–322
Dagpunar J (1988) Principles of Random Variate Generation Oxford University Press
Hastings N A J and Peacock J B (1975) Statistical Distributions Butterworth

5 Arguments

1:   N – INTEGERInput
On entry: n, the number of pseudorandom numbers to be generated.
Constraint: N≥0.
2:   A – REAL (KIND=nag_wp)Input
On entry: a, the parameter of the beta distribution.
Constraint: A>0.0.
3:   B – REAL (KIND=nag_wp)Input
On entry: b, the parameter of the beta distribution.
Constraint: B>0.0.
4:   STATE* – INTEGER arrayCommunication Array
Note: the actual argument supplied must be the array STATE supplied to the initialization routines G05KFF or G05KGF.
On entry: contains information on the selected base generator and its current state.
On exit: contains updated information on the state of the generator.
5:   X N – REAL (KIND=nag_wp) arrayOutput
On exit: the n pseudorandom numbers from the specified beta distribution.
6:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, N=value.
Constraint: N≥0.
IFAIL=2
On entry, A=value.
Constraint: A>0.0.
IFAIL=3
On entry, B=value.
Constraint: B>0.0.
IFAIL=4
On entry, STATE vector has been corrupted or not initialized.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

Not applicable.

8 Parallelism and Performance

G05SBF is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

To generate an observation, y, from the beta distribution of the second kind from an observation, x, generated by G05SBF the transformation, y=x/1-x, may be used.

10 Example

This example prints a set of five pseudorandom numbers from a beta distribution with parameters a=2.0 and b=2.0, generated by a single call to G05SBF, after initialization by G05KFF.

10.1 Program Text

Program Text (g05sbfe.f90)

10.2 Program Data

Program Data (g05sbfe.d)

10.3 Program Results

Program Results (g05sbfe.r)

G05 Chapter Contents
G05 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


G05SCF : NAG Library, Mark 26

G05 Chapter Contents
G05 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

G05SCF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

G05SCF generates a vector of pseudorandom numbers from a Cauchy distribution with median a and semi-interquartile range b.

2 Specification

SUBROUTINE G05SCF ( N, XMED, SEMIQR, STATE, X, IFAIL)
INTEGER | N, STATE(*), IFAIL
REAL (KIND=nag_wp) | XMED, SEMIQR, X(N)

3 Description

The distribution has PDF (probability density function)
f x=1 πb 1+ x-a b 2 .
G05SCF returns the value
a+b 2 y 1- 1 y 2,
where y 1 and y 2 are a pair of consecutive pseudorandom numbers from a uniform distribution over 0,1, such that
2 y 1-1 2+y 22≤1.
One of the initialization routines G05KFF (for a repeatable sequence if computed sequentially) or G05KGF (for a non-repeatable sequence) must be called prior to the first call to G05SCF.

4 References

Kendall M G and Stuart A (1969) The Advanced Theory of Statistics (Volume 1) (3rd Edition) Griffin
Knuth D E (1981) The Art of Computer Programming (Volume 2) (2nd Edition) Addison–Wesley

5 Arguments

1:   N – INTEGERInput
On entry: n, the number of pseudorandom numbers to be generated.
Constraint: N≥0.
2:   XMED – REAL (KIND=nag_wp)Input
On entry: a, the median of the distribution.
3:   SEMIQR – REAL (KIND=nag_wp)Input
On entry: b, the semi-interquartile range of the distribution.
Constraint: SEMIQR≥0.0.
4:   STATE* – INTEGER arrayCommunication Array
Note: the actual argument supplied must be the array STATE supplied to the initialization routines G05KFF or G05KGF.
On entry: contains information on the selected base generator and its current state.
On exit: contains updated information on the state of the generator.
5:   X N – REAL (KIND=nag_wp) arrayOutput
On exit: the n pseudorandom numbers from the specified Cauchy distribution.
6:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, N=value.
Constraint: N≥0.
IFAIL=3
On entry, SEMIQR=value.
Constraint: SEMIQR≥0.0.
IFAIL=4
On entry, STATE vector has been corrupted or not initialized.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

Not applicable.

8 Parallelism and Performance

G05SCF is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

None.

10 Example

This example prints the first five pseudorandom real numbers from a Cauchy distribution with median 1.0 and semi-interquartile range 2.0, generated by a single call to G05SCF, after initialization by G05KFF.

10.1 Program Text

Program Text (g05scfe.f90)

10.2 Program Data

Program Data (g05scfe.d)

10.3 Program Results

Program Results (g05scfe.r)

G05 Chapter Contents
G05 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


G05SDF : NAG Library, Mark 26

G05 Chapter Contents
G05 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

G05SDF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

G05SDF generates a vector of pseudorandom numbers taken from a χ 2-distribution with ν degrees of freedom.

2 Specification

SUBROUTINE G05SDF ( N, DF, STATE, X, IFAIL)
INTEGER | N, DF, STATE(*), IFAIL
REAL (KIND=nag_wp) | X(N)

3 Description

The distribution has PDF (probability density function)
f x = x ν/2-1 × e -x/2 2 ν/2 × ν/2-1 ! if ​ x>0 ; f x=0 otherwise.
This is the same as a gamma distribution with parameters ν/2 and 2.
One of the initialization routines G05KFF (for a repeatable sequence if computed sequentially) or G05KGF (for a non-repeatable sequence) must be called prior to the first call to G05SDF.

4 References

Kendall M G and Stuart A (1969) The Advanced Theory of Statistics (Volume 1) (3rd Edition) Griffin
Knuth D E (1981) The Art of Computer Programming (Volume 2) (2nd Edition) Addison–Wesley

5 Arguments

1:   N – INTEGERInput
On entry: n, the number of pseudorandom numbers to be generated.
Constraint: N≥0.
2:   DF – INTEGERInput
On entry: ν, the number of degrees of freedom of the distribution.
Constraint: DF≥1 .
3:   STATE* – INTEGER arrayCommunication Array
Note: the actual argument supplied must be the array STATE supplied to the initialization routines G05KFF or G05KGF.
On entry: contains information on the selected base generator and its current state.
On exit: contains updated information on the state of the generator.
4:   X N – REAL (KIND=nag_wp) arrayOutput
On exit: the n pseudorandom numbers from the specified χ 2-distribution.
5:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, N=value.
Constraint: N≥0.
IFAIL=2
On entry, DF=value.
Constraint: DF≥1.
IFAIL=3
On entry, STATE vector has been corrupted or not initialized.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

Not applicable.

8 Parallelism and Performance

G05SDF is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The time taken by G05SDF increases with ν.

10 Example

This example prints five pseudorandom numbers from a χ 2-distribution with five degrees of freedom, generated by a single call to G05SDF, after initialization by G05KFF.

10.1 Program Text

Program Text (g05sdfe.f90)

10.2 Program Data

Program Data (g05sdfe.d)

10.3 Program Results

Program Results (g05sdfe.r)

G05 Chapter Contents
G05 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


G05SEF : NAG Library, Mark 26

G05 Chapter Contents
G05 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

G05SEF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

G05SEF generates a vector of pseudorandom numbers taken from a Dirichlet distribution.

2 Specification

SUBROUTINE G05SEF ( N, M, A, STATE, X, LDX, IFAIL)
INTEGER | N, M, STATE(*), LDX, IFAIL
REAL (KIND=nag_wp) | A(M), X(LDX,M)

3 Description

The distribution has PDF (probability density function)
f x = 1 B α ∏ i=1 m x i αi - 1   and B α = ∏ i=1 m Γ αi Γ ∑ i=1 m αi
where x = x 1,x 2,…,xm is a vector of dimension m, such that xi>0 for all i and ∑ i=1 m xi=1.
G05SEF generates a draw from a Dirichlet distribution by first drawing m independent samples, yi∼gamma αi,1, i.e., independent draws from a gamma distribution with parameters αi>0 and one, and then setting xi=yi/∑ j=1 m yj.
One of the initialization routines G05KFF (for a repeatable sequence if computed sequentially) or G05KGF (for a non-repeatable sequence) must be called prior to the first call to G05SEF.

4 References

Dagpunar J (1988) Principles of Random Variate Generation Oxford University Press
Hastings N A J and Peacock J B (1975) Statistical Distributions Butterworth

5 Arguments

1:   N – INTEGERInput
On entry: n, the number of pseudorandom numbers to be generated.
Constraint: N≥0.
2:   M – INTEGERInput
On entry: m, the number of dimensions of the distribution.
Constraint: M>0.
3:   A M – REAL (KIND=nag_wp) arrayInput
On entry: the parameter vector for the distribution.
Constraint: A i>0.0, for i=1,2,…,M.
4:   STATE* – INTEGER arrayCommunication Array
Note: the actual argument supplied must be the array STATE supplied to the initialization routines G05KFF or G05KGF.
On entry: contains information on the selected base generator and its current state.
On exit: contains updated information on the state of the generator.
5:   X LDXM – REAL (KIND=nag_wp) arrayOutput
On exit: the n pseudorandom numbers from the specified Dirichlet distribution, with X ij holding the jth dimension for the ith variate.
6:   LDX – INTEGERInput
On entry: the first dimension of the array X as declared in the (sub)program from which G05SEF is called.
Constraint: LDX≥N.
7:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, N=value.
Constraint: N≥0.
IFAIL=2
On entry, M=value.
Constraint: M > 0.
IFAIL=3
On entry, at least one A i≤0.
IFAIL=4
On entry, STATE vector has been corrupted or not initialized.
IFAIL=6
On entry, LDX=value and N=value.
Constraint: LDX≥N.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

Not applicable.

8 Parallelism and Performance

G05SEF is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

None.

10 Example

This example prints a set of five pseudorandom numbers from a Dirichlet distribution with parameters m=4 and α=2.0,2.0,2.0,2.0, generated by a single call to G05SEF, after initialization by G05KFF.

10.1 Program Text

Program Text (g05sefe.f90)

10.2 Program Data

Program Data (g05sefe.d)

10.3 Program Results

Program Results (g05sefe.r)

G05 Chapter Contents
G05 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


G05SFF : NAG Library, Mark 26

G05 Chapter Contents
G05 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

G05SFF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

G05SFF generates a vector of pseudorandom numbers from a (negative) exponential distribution with mean a.

2 Specification

SUBROUTINE G05SFF ( N, A, STATE, X, IFAIL)
INTEGER | N, STATE(*), IFAIL
REAL (KIND=nag_wp) | A, X(N)

3 Description

The exponential distribution has PDF (probability density function):
f x = 1 a e -x/a if ​x≥0, f x=0 otherwise.
G05SFF returns the values
xi = -a ln⁡yi
where yi are the next n numbers generated by a uniform 0,1 generator.
One of the initialization routines G05KFF (for a repeatable sequence if computed sequentially) or G05KGF (for a non-repeatable sequence) must be called prior to the first call to G05SFF.

4 References

Kendall M G and Stuart A (1969) The Advanced Theory of Statistics (Volume 1) (3rd Edition) Griffin
Knuth D E (1981) The Art of Computer Programming (Volume 2) (2nd Edition) Addison–Wesley

5 Arguments

1:   N – INTEGERInput
On entry: n, the number of pseudorandom numbers to be generated.
Constraint: N≥0.
2:   A – REAL (KIND=nag_wp)Input
On entry: a, the mean of the distribution.
Constraint: A>0.0.
3:   STATE* – INTEGER arrayCommunication Array
Note: the actual argument supplied must be the array STATE supplied to the initialization routines G05KFF or G05KGF.
On entry: contains information on the selected base generator and its current state.
On exit: contains updated information on the state of the generator.
4:   X N – REAL (KIND=nag_wp) arrayOutput
On exit: the n pseudorandom numbers from the specified exponential distribution.
5:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, N=value.
Constraint: N≥0.
IFAIL=2
On entry, A=value.
Constraint: A>0.0.
IFAIL=3
On entry, STATE vector has been corrupted or not initialized.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

Not applicable.

8 Parallelism and Performance

G05SFF is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

None.

10 Example

This example prints five pseudorandom numbers from an exponential distribution with mean 1.0, generated by a single call to G05SFF, after initialization by G05KFF.

10.1 Program Text

Program Text (g05sffe.f90)

10.2 Program Data

Program Data (g05sffe.d)

10.3 Program Results

Program Results (g05sffe.r)

G05 Chapter Contents
G05 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


G05SGF : NAG Library, Mark 26

G05 Chapter Contents
G05 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

G05SGF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

G05SGF generates a vector of pseudorandom numbers from an exponential mix distribution composed of m exponential distributions each having a mean ai and weight wi.

2 Specification

SUBROUTINE G05SGF ( N, NMIX, A, WGT, STATE, X, IFAIL)
INTEGER | N, NMIX, STATE(*), IFAIL
REAL (KIND=nag_wp) | A(NMIX), WGT(NMIX), X(N)

3 Description

The distribution has PDF (probability density function)
f x = ∑i=1 m 1 ai wi e-x/ai if ​x≥0, f x = 0 otherwise,
where ∑i=1 m wi=1 and ai>0, wi≥0.
G05SGF returns the values xi by selecting, with probability wj, random variates from an exponential distribution with argument aj.
One of the initialization routines G05KFF (for a repeatable sequence if computed sequentially) or G05KGF (for a non-repeatable sequence) must be called prior to the first call to G05SGF.

4 References

Kendall M G and Stuart A (1969) The Advanced Theory of Statistics (Volume 1) (3rd Edition) Griffin
Knuth D E (1981) The Art of Computer Programming (Volume 2) (2nd Edition) Addison–Wesley

5 Arguments

1:   N – INTEGERInput
On entry: n, the number of pseudorandom numbers to be generated.
Constraint: N≥0.
2:   NMIX – INTEGERInput
On entry: m, the number of exponential distributions in the mix.
Constraint: NMIX≥1.
3:   A NMIX – REAL (KIND=nag_wp) arrayInput
On entry: the m parameters ai for the m exponential distributions in the mix.
Constraint: A i>0.0, for i=1,2,…,NMIX.
4:   WGT NMIX – REAL (KIND=nag_wp) arrayInput
On entry: the m weights wi for the m exponential distributions in the mix.
Constraints:
  • ∑i=1 m WGT i=1.0;
  • WGT i≥0.0, for i=1,2,…,m.
5:   STATE* – INTEGER arrayCommunication Array
Note: the actual argument supplied must be the array STATE supplied to the initialization routines G05KFF or G05KGF.
On entry: contains information on the selected base generator and its current state.
On exit: contains updated information on the state of the generator.
6:   X N – REAL (KIND=nag_wp) arrayOutput
On exit: the n pseudorandom numbers from the specified exponential mix distribution.
7:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, N=value.
Constraint: N≥0.
IFAIL=2
On entry, NMIX=value.
Constraint: NMIX≥1.
IFAIL=3
On entry, A value=value.
Constraint: A i>0.0.
IFAIL=4
On entry, sum of WGT=value.
Constraint: sum of WGT=1.0.
On entry, WGT value=value.
Constraint: WGT i≥0.0.
IFAIL=5
On entry, STATE vector has been corrupted or not initialized.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

Not applicable.

8 Parallelism and Performance

G05SGF is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

None.

10 Example

This example prints the first five pseudorandom numbers from an exponential mix distribution comprising three exponential distributions with parameters a 1=1.0, a 2=5.0 and a 3=2.0, and with respective weights 0.5, 0.3 and 0.2. The numbers are generated by a single call to G05SGF, after initialization by G05KFF.

10.1 Program Text

Program Text (g05sgfe.f90)

10.2 Program Data

Program Data (g05sgfe.d)

10.3 Program Results

Program Results (g05sgfe.r)

G05 Chapter Contents
G05 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


G05SHF : NAG Library, Mark 26

G05 Chapter Contents
G05 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

G05SHF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

G05SHF generates a vector of pseudorandom numbers taken from an F (or Fisher's variance ratio) distribution with μ and ν degrees of freedom.

2 Specification

SUBROUTINE G05SHF ( N, DF1, DF2, STATE, X, IFAIL)
INTEGER | N, DF1, DF2, STATE(*), IFAIL
REAL (KIND=nag_wp) | X(N)

3 Description

The distribution has PDF (probability density function)
f x = μ+ν-2 2 ! x 12 μ-1 12 μ-1! 12 ν-1 ! 1+ μν x 12 μ+ν × μν 12 μ if ​ x>0 , f x=0 otherwise.
G05SHF calculates the values
ν yi μ zi ,   i=1,2,…,n ,
where yi and zi are generated by G05SJF from gamma distributions with parameters 12 μ,2 and 12 ν,2 respectively (i.e., from χ 2-distributions with μ and ν degrees of freedom).
One of the initialization routines G05KFF (for a repeatable sequence if computed sequentially) or G05KGF (for a non-repeatable sequence) must be called prior to the first call to G05SHF.

4 References

Knuth D E (1981) The Art of Computer Programming (Volume 2) (2nd Edition) Addison–Wesley

5 Arguments

1:   N – INTEGERInput
On entry: n, the number of pseudorandom numbers to be generated.
Constraint: N≥0.
2:   DF1 – INTEGERInput
On entry: μ, the number of degrees of freedom of the distribution.
Constraint: DF1≥1.
3:   DF2 – INTEGERInput
On entry: ν, the number of degrees of freedom of the distribution.
Constraint: DF2≥1.
4:   STATE* – INTEGER arrayCommunication Array
Note: the actual argument supplied must be the array STATE supplied to the initialization routines G05KFF or G05KGF.
On entry: contains information on the selected base generator and its current state.
On exit: contains updated information on the state of the generator.
5:   X N – REAL (KIND=nag_wp) arrayOutput
On exit: the n pseudorandom numbers from the specified F-distribution.
6:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, N=value.
Constraint: N≥0.
IFAIL=2
On entry, DF1=value.
Constraint: DF1≥1.
IFAIL=3
On entry, DF2=value.
Constraint: DF2≥1.
IFAIL=4
On entry, STATE vector has been corrupted or not initialized.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

Not applicable.

8 Parallelism and Performance

G05SHF is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The time taken by G05SHF increases with μ and ν.

10 Example

This example prints five pseudorandom numbers from an F-distribution with two and three degrees of freedom, generated by a single call to G05SHF, after initialization by G05KFF.

10.1 Program Text

Program Text (g05shfe.f90)

10.2 Program Data

Program Data (g05shfe.d)

10.3 Program Results

Program Results (g05shfe.r)

G05 Chapter Contents
G05 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


G05SJF : NAG Library, Mark 26

G05 Chapter Contents
G05 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

G05SJF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

G05SJF generates a vector of pseudorandom numbers taken from a gamma distribution with parameters a and b.

2 Specification

SUBROUTINE G05SJF ( N, A, B, STATE, X, IFAIL)
INTEGER | N, STATE(*), IFAIL
REAL (KIND=nag_wp) | A, B, X(N)

3 Description

The gamma distribution has PDF (probability density function)
f x= 1 ba Γ a x a-1e-x/b if ​x≥0;  a,b>0 f x=0 otherwise.
One of three algorithms is used to generate the variates depending upon the value of a:
(i) | if a<1, a switching algorithm described by Dagpunar (1988) (called G6) is used. The target distributions are f 1 x=ca x a-1/ta and f 2 x=1-c e-x-t, where c=t/t+a e-t, and the switching argument, t, is taken as 1-a. This is similar to Ahrens and Dieter's GS algorithm (see Ahrens and Dieter (1974)) in which t=1;
(ii) | if a=1, the gamma distribution reduces to the exponential distribution and the method based on the logarithmic transformation of a uniform random variate is used;
(iii) | if a>1, the algorithm given by Best (1978) is used. This is based on using a Student's t-distribution with two degrees of freedom as the target distribution in an envelope rejection method.
One of the initialization routines G05KFF (for a repeatable sequence if computed sequentially) or G05KGF (for a non-repeatable sequence) must be called prior to the first call to G05SJF.

4 References

Ahrens J H and Dieter U (1974) Computer methods for sampling from gamma, beta, Poisson and binomial distributions Computing 12 223–46
Best D J (1978) Letter to the Editor Appl. Statist. 27 181
Dagpunar J (1988) Principles of Random Variate Generation Oxford University Press
Hastings N A J and Peacock J B (1975) Statistical Distributions Butterworth

5 Arguments

1:   N – INTEGERInput
On entry: n, the number of pseudorandom numbers to be generated.
Constraint: N≥0.
2:   A – REAL (KIND=nag_wp)Input
On entry: a, the parameter of the gamma distribution.
Constraint: A>0.0.
3:   B – REAL (KIND=nag_wp)Input
On entry: b, the parameter of the gamma distribution.
Constraint: B>0.0.
4:   STATE* – INTEGER arrayCommunication Array
Note: the actual argument supplied must be the array STATE supplied to the initialization routines G05KFF or G05KGF.
On entry: contains information on the selected base generator and its current state.
On exit: contains updated information on the state of the generator.
5:   X N – REAL (KIND=nag_wp) arrayOutput
On exit: the n pseudorandom numbers from the specified gamma distribution.
6:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, N=value.
Constraint: N≥0.
IFAIL=2
On entry, A=value.
Constraint: A>0.0.
IFAIL=3
On entry, B=value.
Constraint: B>0.0.
IFAIL=4
On entry, STATE vector has been corrupted or not initialized.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

Not applicable.

8 Parallelism and Performance

G05SJF is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

None.

10 Example

This example prints a set of five pseudorandom numbers from a gamma distribution with parameters a=5.0 and b=1.0, generated by a single call to G05SJF, after initialization by G05KFF.

10.1 Program Text

Program Text (g05sjfe.f90)

10.2 Program Data

Program Data (g05sjfe.d)

10.3 Program Results

Program Results (g05sjfe.r)

G05 Chapter Contents
G05 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


G05SKF : NAG Library, Mark 26

G05 Chapter Contents
G05 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

G05SKF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

G05SKF generates a vector of pseudorandom numbers taken from a Normal (Gaussian) distribution with mean μ and variance σ 2.

2 Specification

SUBROUTINE G05SKF ( N, XMU, VAR, STATE, X, IFAIL)
INTEGER | N, STATE(*), IFAIL
REAL (KIND=nag_wp) | XMU, VAR, X(N)

3 Description

The distribution has PDF (probability distribution function)
f x=1 σ⁢2 π exp- x-μ 2 2 σ 2 .
G05SKF uses the algorithm of Wichura (1988).
One of the initialization routines G05KFF (for a repeatable sequence if computed sequentially) or G05KGF (for a non-repeatable sequence) must be called prior to the first call to G05SKF.

4 References

Kendall M G and Stuart A (1969) The Advanced Theory of Statistics (Volume 1) (3rd Edition) Griffin
Knuth D E (1981) The Art of Computer Programming (Volume 2) (2nd Edition) Addison–Wesley
Wichura (1988) Algorithm AS 241: the percentage points of the Normal distribution Appl. Statist. 37 477–484

5 Arguments

1:   N – INTEGERInput
On entry: n, the number of pseudorandom numbers to be generated.
Constraint: N≥0.
2:   XMU – REAL (KIND=nag_wp)Input
On entry: μ, the mean of the distribution.
3:   VAR – REAL (KIND=nag_wp)Input
On entry: σ 2, the variance of the distribution.
Constraint: VAR≥0.0.
4:   STATE* – INTEGER arrayCommunication Array
Note: the actual argument supplied must be the array STATE supplied to the initialization routines G05KFF or G05KGF.
On entry: contains information on the selected base generator and its current state.
On exit: contains updated information on the state of the generator.
5:   X N – REAL (KIND=nag_wp) arrayOutput
On exit: the n pseudorandom numbers from the specified Normal distribution.
6:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, N=value.
Constraint: N≥0.
IFAIL=3
On entry, VAR=value.
Constraint: VAR≥0.0.
IFAIL=4
On entry, STATE vector has been corrupted or not initialized.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

Not applicable.

8 Parallelism and Performance

G05SKF is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

None.

10 Example

This example prints five pseudorandom numbers from a Normal distribution with mean 1.0 and variance 1.5, generated by a single call to G05SKF, after initialization by G05KFF.

10.1 Program Text

Program Text (g05skfe.f90)

10.2 Program Data

Program Data (g05skfe.d)

10.3 Program Results

Program Results (g05skfe.r)

G05 Chapter Contents
G05 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


G05SLF : NAG Library, Mark 26

G05 Chapter Contents
G05 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

G05SLF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

G05SLF generates a vector of pseudorandom numbers from a logistic distribution with mean a and spread b.

2 Specification

SUBROUTINE G05SLF ( N, A, B, STATE, X, IFAIL)
INTEGER | N, STATE(*), IFAIL
REAL (KIND=nag_wp) | A, B, X(N)

3 Description

The distribution has PDF (probability density function)
f x=e x-a/b b 1+e x-a/b 2 .
G05SLF returns the value
a+b ln y 1-y ,
where y is a pseudorandom number uniformly distributed over 0,1.
One of the initialization routines G05KFF (for a repeatable sequence if computed sequentially) or G05KGF (for a non-repeatable sequence) must be called prior to the first call to G05SLF.

4 References

Kendall M G and Stuart A (1969) The Advanced Theory of Statistics (Volume 1) (3rd Edition) Griffin
Knuth D E (1981) The Art of Computer Programming (Volume 2) (2nd Edition) Addison–Wesley

5 Arguments

1:   N – INTEGERInput
On entry: n, the number of pseudorandom numbers to be generated.
Constraint: N≥0.
2:   A – REAL (KIND=nag_wp)Input
On entry: a, the mean of the distribution.
3:   B – REAL (KIND=nag_wp)Input
On entry: b, the spread of the distribution, where ‘spread’ is 3 π ×standard deviation.
Constraint: B≥0.0.
4:   STATE* – INTEGER arrayCommunication Array
Note: the actual argument supplied must be the array STATE supplied to the initialization routines G05KFF or G05KGF.
On entry: contains information on the selected base generator and its current state.
On exit: contains updated information on the state of the generator.
5:   X N – REAL (KIND=nag_wp) arrayOutput
On exit: the n pseudorandom numbers from the specified logistic distribution.
6:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, N=value.
Constraint: N≥0.
IFAIL=3
On entry, B=value.
Constraint: B≥0.0.
IFAIL=4
On entry, STATE vector has been corrupted or not initialized.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

Not applicable.

8 Parallelism and Performance

G05SLF is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

None.

10 Example

This example prints the first five pseudorandom real numbers from a logistic distribution with mean 1.0 and spread 2.0, generated by a single call to G05SLF, after initialization by G05KFF.

10.1 Program Text

Program Text (g05slfe.f90)

10.2 Program Data

Program Data (g05slfe.d)

10.3 Program Results

Program Results (g05slfe.r)

G05 Chapter Contents
G05 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


G05SMF : NAG Library, Mark 26

G05 Chapter Contents
G05 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

G05SMF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

G05SMF generates a vector of pseudorandom numbers from a log-normal distribution with parameters μ and σ 2.

2 Specification

SUBROUTINE G05SMF ( N, XMU, VAR, STATE, X, IFAIL)
INTEGER | N, STATE(*), IFAIL
REAL (KIND=nag_wp) | XMU, VAR, X(N)

3 Description

The distribution has PDF (probability density function)
f x = 1 xσ⁢2 π exp - ln⁡x-μ 2 2 σ 2 if ​ x>0 , f x=0 otherwise,
i.e., ln⁡x is normally distributed with mean μ and variance σ 2. G05SMF evaluates exp⁡yi, where the yi are generated by G05SKF from a Normal distribution with mean μ and variance σ 2, for i=1,2,…,n.
One of the initialization routines G05KFF (for a repeatable sequence if computed sequentially) or G05KGF (for a non-repeatable sequence) must be called prior to the first call to G05SMF.

4 References

Kendall M G and Stuart A (1969) The Advanced Theory of Statistics (Volume 1) (3rd Edition) Griffin
Knuth D E (1981) The Art of Computer Programming (Volume 2) (2nd Edition) Addison–Wesley

5 Arguments

1:   N – INTEGERInput
On entry: n, the number of pseudorandom numbers to be generated.
Constraint: N≥0.
2:   XMU – REAL (KIND=nag_wp)Input
On entry: μ, the mean of the distribution of ln⁡x.
3:   VAR – REAL (KIND=nag_wp)Input
On entry: σ 2, the variance of the distribution of ln⁡x.
Constraint: VAR≥0.0.
4:   STATE* – INTEGER arrayCommunication Array
Note: the actual argument supplied must be the array STATE supplied to the initialization routines G05KFF or G05KGF.
On entry: contains information on the selected base generator and its current state.
On exit: contains updated information on the state of the generator.
5:   X N – REAL (KIND=nag_wp) arrayOutput
On exit: the n pseudorandom numbers from the specified log-normal distribution.
6:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, N=value.
Constraint: N≥0.
IFAIL=2
On entry, XMU is too large to take the exponential of XMU=value.
IFAIL=3
On entry, VAR=value.
Constraint: VAR≥0.0.
IFAIL=4
On entry, STATE vector has been corrupted or not initialized.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

Not applicable.

8 Parallelism and Performance

G05SMF is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

None.

10 Example

This example prints five pseudorandom numbers from a log-normal distribution with mean 1.0 and variance 2.0, generated by a single call to G05SMF, after initialization by G05KFF.

10.1 Program Text

Program Text (g05smfe.f90)

10.2 Program Data

Program Data (g05smfe.d)

10.3 Program Results

Program Results (g05smfe.r)

G05 Chapter Contents
G05 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


G05SNF : NAG Library, Mark 26

G05 Chapter Contents
G05 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

G05SNF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

G05SNF generates a vector of pseudorandom numbers taken from a Student's t-distribution with ν degrees of freedom.

2 Specification

SUBROUTINE G05SNF ( N, DF, STATE, X, IFAIL)
INTEGER | N, DF, STATE(*), IFAIL
REAL (KIND=nag_wp) | X(N)

3 Description

The distribution has PDF (probability density function)
f x= ν-1 2 ! 12 ν-1!πν 1+x 2 ν 12 ν+1 .
G05SNF calculates the values
yi ν zi,   i= 1,…,n
where the yi are generated by G05SKF from a Normal distribution with mean 0 and variance 1.0, and the zi are generated by G05SJF from a gamma distribution with parameters 12 ν and 2 (i.e., from a χ 2-distribution with ν degrees of freedom).
One of the initialization routines G05KFF (for a repeatable sequence if computed sequentially) or G05KGF (for a non-repeatable sequence) must be called prior to the first call to G05SNF.

4 References

Knuth D E (1981) The Art of Computer Programming (Volume 2) (2nd Edition) Addison–Wesley

5 Arguments

1:   N – INTEGERInput
On entry: n, the number of pseudorandom numbers to be generated.
Constraint: N≥0.
2:   DF – INTEGERInput
On entry: ν, the number of degrees of freedom of the distribution.
Constraint: DF≥1 .
3:   STATE* – INTEGER arrayCommunication Array
Note: the actual argument supplied must be the array STATE supplied to the initialization routines G05KFF or G05KGF.
On entry: contains information on the selected base generator and its current state.
On exit: contains updated information on the state of the generator.
4:   X N – REAL (KIND=nag_wp) arrayOutput
On exit: the n pseudorandom numbers from the specified Student's t-distribution.
5:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, N=value.
Constraint: N≥0.
IFAIL=2
On entry, DF=value.
Constraint: DF≥1.
IFAIL=3
On entry, STATE vector has been corrupted or not initialized.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

Not applicable.

8 Parallelism and Performance

G05SNF is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The time taken by G05SNF increases with ν.

10 Example

This example prints five pseudorandom numbers from a Student's t-distribution with five degrees of freedom, generated by a single call to G05SNF, after initialization by G05KFF.

10.1 Program Text

Program Text (g05snfe.f90)

10.2 Program Data

Program Data (g05snfe.d)

10.3 Program Results

Program Results (g05snfe.r)

G05 Chapter Contents
G05 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


G05SPF : NAG Library, Mark 26

G05 Chapter Contents
G05 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

G05SPF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

G05SPF generates a vector of pseudorandom numbers from a triangular distribution with parameters xmin, xmed and xmax.

2 Specification

SUBROUTINE G05SPF ( N, XMIN, XMED, XMAX, STATE, X, IFAIL)
INTEGER | N, STATE(*), IFAIL
REAL (KIND=nag_wp) | XMIN, XMED, XMAX, X(N)

3 Description

The triangular distribution has a PDF (probability density function) that is triangular in profile. The base of the triangle ranges from x=xmin to x=xmax and the PDF has a maximum value of 2 xmax-xmin at x=xmed. If xmin=xmed=xmax then x=xmed with probability 1; otherwise the triangular distribution has PDF:
f x = x-xmin xmed-xmin × 2 xmax-xmin ​ if ​xmin≤x≤xmed, f x= xmax-x xmax-xmed ×2 xmax-xmin ​ if ​xmed<x≤xmax, f x=0 ​ otherwise.
One of the initialization routines G05KFF (for a repeatable sequence if computed sequentially) or G05KGF (for a non-repeatable sequence) must be called prior to the first call to G05SPF.

4 References

Knuth D E (1981) The Art of Computer Programming (Volume 2) (2nd Edition) Addison–Wesley

5 Arguments

1:   N – INTEGERInput
On entry: n, the number of pseudorandom numbers to be generated.
Constraint: N≥0.
2:   XMIN – REAL (KIND=nag_wp)Input
On entry: the end point xmin of the triangular distribution.
3:   XMED – REAL (KIND=nag_wp)Input
On entry: the median of the distribution xmed (also the location of the vertex of the triangular distribution at which the PDF reaches a maximum).
Constraint: XMED≥XMIN.
4:   XMAX – REAL (KIND=nag_wp)Input
On entry: the end point xmax of the triangular distribution.
Constraint: XMAX≥XMED.
5:   STATE* – INTEGER arrayCommunication Array
Note: the actual argument supplied must be the array STATE supplied to the initialization routines G05KFF or G05KGF.
On entry: contains information on the selected base generator and its current state.
On exit: contains updated information on the state of the generator.
6:   X N – REAL (KIND=nag_wp) arrayOutput
On exit: the n pseudorandom numbers from the specified triangular distribution.
7:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, N=value.
Constraint: N≥0.
IFAIL=3
On entry, XMED=value and XMIN=value.
Constraint: XMED≥XMIN.
IFAIL=4
On entry, XMAX=value and XMED=value.
Constraint: XMAX≥XMED.
IFAIL=5
On entry, STATE vector has been corrupted or not initialized.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

Not applicable.

8 Parallelism and Performance

G05SPF is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

None.

10 Example

This example prints five pseudorandom numbers from a triangular distribution with parameters xmin=-1.0, xmed=0.5 and xmax=1.0, generated by a single call to G05SPF, after initialization by G05KFF.

10.1 Program Text

Program Text (g05spfe.f90)

10.2 Program Data

Program Data (g05spfe.d)

10.3 Program Results

Program Results (g05spfe.r)

G05 Chapter Contents
G05 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


G05SQF : NAG Library, Mark 26

G05 Chapter Contents
G05 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

G05SQF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

G05SQF generates a vector of pseudorandom numbers uniformly distributed over the interval a,b.

2 Specification

SUBROUTINE G05SQF ( N, A, B, STATE, X, IFAIL)
INTEGER | N, STATE(*), IFAIL
REAL (KIND=nag_wp) | A, B, X(N)

3 Description

If a=0 and b=1, G05SQF returns the next n values yi from a uniform 0,1 generator (see G05SAF for details).
For other values of a and b, G05SQF applies the transformation
xi=a+b-a yi.
The routine ensures that the values xi lie in the closed interval a,b.
One of the initialization routines G05KFF (for a repeatable sequence if computed sequentially) or G05KGF (for a non-repeatable sequence) must be called prior to the first call to G05SQF.

4 References

Knuth D E (1981) The Art of Computer Programming (Volume 2) (2nd Edition) Addison–Wesley

5 Arguments

1:   N – INTEGERInput
On entry: n, the number of pseudorandom numbers to be generated.
Constraint: N≥0.
2:   A – REAL (KIND=nag_wp)Input
3:   B – REAL (KIND=nag_wp)Input
On entry: the end points a and b of the uniform distribution.
Constraint: A≤B.
4:   STATE* – INTEGER arrayCommunication Array
Note: the actual argument supplied must be the array STATE supplied to the initialization routines G05KFF or G05KGF.
On entry: contains information on the selected base generator and its current state.
On exit: contains updated information on the state of the generator.
5:   X N – REAL (KIND=nag_wp) arrayOutput
On exit: the n pseudorandom numbers from the specified uniform distribution.
6:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, N=value.
Constraint: N≥0.
IFAIL=3
On entry, A=value and B=value.
Constraint: B≥A.
IFAIL=4
On entry, STATE vector has been corrupted or not initialized.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

Not applicable.

8 Parallelism and Performance

G05SQF is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

Although yi takes a value from the half closed interval 0,1 and xi=a+b-a yi, xi is documented as taking values from the closed interval a,b. This is because for some values of a and b, G05SQF may return a value of a due to numerical rounding.

10 Example

This example prints five pseudorandom numbers from a uniform distribution between -1.0 and 1.0, generated by a single call to G05SQF, after initialization by G05KFF.

10.1 Program Text

Program Text (g05sqfe.f90)

10.2 Program Data

Program Data (g05sqfe.d)

10.3 Program Results

Program Results (g05sqfe.r)

G05 Chapter Contents
G05 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


G05SRF : NAG Library, Mark 26

G05 Chapter Contents
G05 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

G05SRF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

G05SRF generates a vector of pseudorandom numbers from a von Mises distribution with concentration parameter κ.

2 Specification

SUBROUTINE G05SRF ( N, VK, STATE, X, IFAIL)
INTEGER | N, STATE(*), IFAIL
REAL (KIND=nag_wp) | VK, X(N)

3 Description

The von Mises distribution is a symmetric distribution used in the analysis of circular data. The PDF (probability density function) of this distribution on the circle with mean direction μ 0=0 and concentration parameter κ, can be written as:
f θ= e κ cos⁡θ 2 π I 0 κ ,
where θ is reduced modulo 2 π so that -π≤θ<π and κ≥0. For very small κ the distribution is almost the uniform distribution, whereas for κ→∞ all the probability is concentrated at one point.
The n variates, θ 1,θ 2,…,θn, are generated using an envelope rejection method with a wrapped Cauchy target distribution as proposed by Best and Fisher (1979) and described by Dagpunar (1988).
One of the initialization routines G05KFF (for a repeatable sequence if computed sequentially) or G05KGF (for a non-repeatable sequence) must be called prior to the first call to G05SRF.

4 References

Best D J and Fisher N I (1979) Efficient simulation of the von Mises distribution Appl. Statist. 28 152–157
Dagpunar J (1988) Principles of Random Variate Generation Oxford University Press
Mardia K V (1972) Statistics of Directional Data Academic Press

5 Arguments

1:   N – INTEGERInput
On entry: n, the number of pseudorandom numbers to be generated.
Constraint: N≥0.
2:   VK – REAL (KIND=nag_wp)Input
On entry: κ, the concentration parameter of the required von Mises distribution.
Constraint: 0.0<VK≤X02ALF/2.0.
3:   STATE* – INTEGER arrayCommunication Array
Note: the actual argument supplied must be the array STATE supplied to the initialization routines G05KFF or G05KGF.
On entry: contains information on the selected base generator and its current state.
On exit: contains updated information on the state of the generator.
4:   X N – REAL (KIND=nag_wp) arrayOutput
On exit: the n pseudorandom numbers from the specified von Mises distribution.
5:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, N=value.
Constraint: N≥0.
IFAIL=2
On entry, VK≤0.0 or VK too large: VK=value.
IFAIL=3
On entry, STATE vector has been corrupted or not initialized.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

Not applicable.

8 Parallelism and Performance

G05SRF is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

For a given number of random variates the generation time increases slightly with increasing κ.

10 Example

This example prints the first five pseudorandom numbers from a von Mises distribution with κ=1.0, generated by a single call to G05SRF, after initialization by G05KFF.

10.1 Program Text

Program Text (g05srfe.f90)

10.2 Program Data

Program Data (g05srfe.d)

10.3 Program Results

Program Results (g05srfe.r)

G05 Chapter Contents
G05 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


G05SSF : NAG Library, Mark 26

G05 Chapter Contents
G05 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

G05SSF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

G05SSF generates a vector of pseudorandom numbers from a two parameter Weibull distribution with shape parameter a and scale parameter b.

2 Specification

SUBROUTINE G05SSF ( N, A, B, STATE, X, IFAIL)
INTEGER | N, STATE(*), IFAIL
REAL (KIND=nag_wp) | A, B, X(N)

3 Description

The distribution has PDF (probability density function)
f x = ab x a-1 e- xa / b if ​x>0, f x=0 otherwise.
G05SSF returns the value -b ln⁡y 1/a, where y is a pseudorandom number from a uniform distribution over 0,1.
One of the initialization routines G05KFF (for a repeatable sequence if computed sequentially) or G05KGF (for a non-repeatable sequence) must be called prior to the first call to G05SSF.

4 References

Kendall M G and Stuart A (1969) The Advanced Theory of Statistics (Volume 1) (3rd Edition) Griffin
Knuth D E (1981) The Art of Computer Programming (Volume 2) (2nd Edition) Addison–Wesley

5 Arguments

1:   N – INTEGERInput
On entry: n, the number of pseudorandom numbers to be generated.
Constraint: N≥0.
2:   A – REAL (KIND=nag_wp)Input
On entry: a, the shape parameter of the distribution.
Constraint: A>0.0.
3:   B – REAL (KIND=nag_wp)Input
On entry: b, the scale parameter of the distribution.
Constraint: B>0.0.
4:   STATE* – INTEGER arrayCommunication Array
Note: the actual argument supplied must be the array STATE supplied to the initialization routines G05KFF or G05KGF.
On entry: contains information on the selected base generator and its current state.
On exit: contains updated information on the state of the generator.
5:   X N – REAL (KIND=nag_wp) arrayOutput
On exit: the n pseudorandom numbers from the specified Weibull distribution.
6:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, N=value.
Constraint: N≥0.
IFAIL=2
On entry, A=value.
Constraint: A>0.0.
IFAIL=3
On entry, B=value.
Constraint: B>0.0.
IFAIL=4
On entry, STATE vector has been corrupted or not initialized.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

Not applicable.

8 Parallelism and Performance

G05SSF is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

None.

10 Example

This example prints the first five pseudorandom numbers from a Weibull distribution with shape parameter 1.0 and scale parameter 2.0, generated by a single call to G05SSF, after initialization by G05KFF.

10.1 Program Text

Program Text (g05ssfe.f90)

10.2 Program Data

Program Data (g05ssfe.d)

10.3 Program Results

Program Results (g05ssfe.r)

G05 Chapter Contents
G05 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


G05TAF : NAG Library, Mark 26

G05 Chapter Contents
G05 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

G05TAF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

G05TAF generates a vector of pseudorandom integers from the discrete binomial distribution with parameters m and p.

2 Specification

SUBROUTINE G05TAF ( MODE, N, M, P, R, LR, STATE, X, IFAIL)
INTEGER | MODE, N, M, LR, STATE(*), X(N), IFAIL
REAL (KIND=nag_wp) | P, R(LR)

3 Description

G05TAF generates n integers xi from a discrete binomial distribution, where the probability of xi=I is
P xi=I= m! I!m-I! ⁢ pI×1-p m-I,  I=0,1,…,m,
where m≥0 and 0≤p≤1. This represents the probability of achieving I successes in m trials when the probability of success at a single trial is p.
The variates can be generated with or without using a search table and index. If a search table is used then it is stored with the index in a reference vector and subsequent calls to G05TAF with the same parameter values can then use this reference vector to generate further variates.
One of the initialization routines G05KFF (for a repeatable sequence if computed sequentially) or G05KGF (for a non-repeatable sequence) must be called prior to the first call to G05TAF.

4 References

Kendall M G and Stuart A (1969) The Advanced Theory of Statistics (Volume 1) (3rd Edition) Griffin
Knuth D E (1981) The Art of Computer Programming (Volume 2) (2nd Edition) Addison–Wesley

5 Arguments

1:   MODE – INTEGERInput
On entry: a code for selecting the operation to be performed by the routine.
MODE=0
Set up reference vector only.
MODE=1
Generate variates using reference vector set up in a prior call to G05TAF.
MODE=2
Set up reference vector and generate variates.
MODE=3
Generate variates without using the reference vector.
Constraint: MODE=0, 1, 2 or 3.
2:   N – INTEGERInput
On entry: n, the number of pseudorandom numbers to be generated.
Constraint: N≥0.
3:   M – INTEGERInput
On entry: m, the number of trials of the distribution.
Constraint: M≥0.
4:   P – REAL (KIND=nag_wp)Input
On entry: p, the probability of success of the binomial distribution.
Constraint: 0.0≤P≤1.0.
5:   R LR – REAL (KIND=nag_wp) arrayCommunication Array
On entry: if MODE=1, the reference vector from the previous call to G05TAF.
If MODE=3, R is not referenced.
On exit: if MODE≠3, the reference vector.
6:   LR – INTEGERInput
On entry: the dimension of the array R as declared in the (sub)program from which G05TAF is called.
Suggested values:
  • if MODE≠3, LR=22+20×M×P×1-P;
  • otherwise LR=1.
Constraints:
  • if MODE=0 or 2,
    LR > min M,int M×P+7.15 × M × P × 1-P +1 - max 0,int M × P - 7.15 × M × P × 1-P - 7.15 +8 ;
  • if MODE=1, LR must remain unchanged from the previous call to G05TAF.
7:   STATE* – INTEGER arrayCommunication Array
Note: the actual argument supplied must be the array STATE supplied to the initialization routines G05KFF or G05KGF.
On entry: contains information on the selected base generator and its current state.
On exit: contains updated information on the state of the generator.
8:   X N – INTEGER arrayOutput
On exit: the n pseudorandom numbers from the specified binomial distribution.
9:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, MODE=value.
Constraint: MODE=0, 1, 2 or 3.
IFAIL=2
On entry, N=value.
Constraint: N≥0.
IFAIL=3
On entry, M=value.
Constraint: M≥0.
IFAIL=4
On entry, P=value.
Constraint: 0.0≤P≤1.0.
IFAIL=5
On entry, some of the elements of the array R have been corrupted or have not been initialized.
P or M is not the same as when R was set up in a previous call.
Previous value of P=value and P=value.
Previous value of M=value and M=value.
IFAIL=6
On entry, LR is too small when MODE=0 or 2: LR=value, minimum length required =value.
IFAIL=7
On entry, STATE vector has been corrupted or not initialized.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

Not applicable.

8 Parallelism and Performance

G05TAF is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

None.

10 Example

This example prints 20 pseudorandom integers from a binomial distribution with parameters m=6000 and p=0.8, generated by a single call to G05TAF, after initialization by G05KFF.

10.1 Program Text

Program Text (g05tafe.f90)

10.2 Program Data

Program Data (g05tafe.d)

10.3 Program Results

Program Results (g05tafe.r)

G05 Chapter Contents
G05 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


G05TBF : NAG Library, Mark 26

G05 Chapter Contents
G05 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

G05TBF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

G05TBF generates a vector of pseudorandom logical values – .TRUE. with probability p and .FALSE. with probability 1-p.

2 Specification

SUBROUTINE G05TBF ( N, P, STATE, X, IFAIL)
INTEGER | N, STATE(*), IFAIL
REAL (KIND=nag_wp) | P
LOGICAL | X(N)

3 Description

G05TBF generates n logical values xi from the relation
yi<p
where yi is a pseudorandom number from a uniform distribution over 0,1, generated by G05SAF using the values of STATE as input to this routine.
One of the initialization routines G05KFF (for a repeatable sequence if computed sequentially) or G05KGF (for a non-repeatable sequence) must be called prior to the first call to G05TBF.

4 References

Knuth D E (1981) The Art of Computer Programming (Volume 2) (2nd Edition) Addison–Wesley

5 Arguments

1:   N – INTEGERInput
On entry: n, the number of pseudorandom logical values to be generated.
Constraint: N≥0.
2:   P – REAL (KIND=nag_wp)Input
On entry: must contain the probability of G05TBF returning .TRUE..
Constraint: 0.0≤P≤1.0.
3:   STATE* – INTEGER arrayCommunication Array
Note: the actual argument supplied must be the array STATE supplied to the initialization routines G05KFF or G05KGF.
On entry: contains information on the selected base generator and its current state.
On exit: contains updated information on the state of the generator.
4:   X N – LOGICAL arrayOutput
On exit: the n logical values.
5:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, N=value.
Constraint: N≥0.
IFAIL=2
On entry, P=value.
Constraint: 0.0≤P≤1.0.
IFAIL=3
On entry, STATE vector has been corrupted or not initialized.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

Not applicable.

8 Parallelism and Performance

G05TBF is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

None.

10 Example

This example prints the first 20 pseudorandom logical values generated by G05TBF after initialization by G05KFF, when the probability of a .TRUE. value is 0.5.

10.1 Program Text

Program Text (g05tbfe.f90)

10.2 Program Data

Program Data (g05tbfe.d)

10.3 Program Results

Program Results (g05tbfe.r)

G05 Chapter Contents
G05 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


G05TCF : NAG Library, Mark 26

G05 Chapter Contents
G05 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

G05TCF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

G05TCF generates a vector of pseudorandom integers from the discrete geometric distribution with probability p of success at a trial.

2 Specification

SUBROUTINE G05TCF ( MODE, N, P, R, LR, STATE, X, IFAIL)
INTEGER | MODE, N, LR, STATE(*), X(N), IFAIL
REAL (KIND=nag_wp) | P, R(LR)

3 Description

G05TCF generates n integers xi from a discrete geometric distribution, where the probability of xi=I (a first success after I+1 trials) is
P xi=I = p × 1-p I ,   I=0,1,… .
The variates can be generated with or without using a search table and index. If a search table is used then it is stored with the index in a reference vector and subsequent calls to G05TCF with the same parameter value can then use this reference vector to generate further variates. If the search table is not used (as recommended for small values of p) then a direct transformation of uniform variates is used.
One of the initialization routines G05KFF (for a repeatable sequence if computed sequentially) or G05KGF (for a non-repeatable sequence) must be called prior to the first call to G05TCF.

4 References

Knuth D E (1981) The Art of Computer Programming (Volume 2) (2nd Edition) Addison–Wesley

5 Arguments

1:   MODE – INTEGERInput
On entry: a code for selecting the operation to be performed by the routine.
MODE=0
Set up reference vector only.
MODE=1
Generate variates using reference vector set up in a prior call to G05TCF.
MODE=2
Set up reference vector and generate variates.
MODE=3
Generate variates without using the reference vector.
Constraint: MODE=0, 1, 2 or 3.
2:   N – INTEGERInput
On entry: n, the number of pseudorandom numbers to be generated.
Constraint: N≥0.
3:   P – REAL (KIND=nag_wp)Input
On entry: the parameter p of the geometric distribution representing the probability of success at a single trial.
Constraint: machine precision≤P≤1.0 (see X02AJF).
4:   R LR – REAL (KIND=nag_wp) arrayCommunication Array
On entry: if MODE=1, the reference vector from the previous call to G05TCF.
If MODE=3, R is not referenced.
On exit: if MODE≠3, the reference vector.
5:   LR – INTEGERInput
On entry: the dimension of the array R as declared in the (sub)program from which G05TCF is called.
Suggested values:
  • if MODE≠3, LR=8+42/P approximately (see Section 9);
  • otherwise LR=1.
Constraints:
  • if MODE=0 or 2, LR≥30/P+8;
  • if MODE=1, LR should remain unchanged from the previous call to G05TCF.
6:   STATE* – INTEGER arrayCommunication Array
Note: the actual argument supplied must be the array STATE supplied to the initialization routines G05KFF or G05KGF.
On entry: contains information on the selected base generator and its current state.
On exit: contains updated information on the state of the generator.
7:   X N – INTEGER arrayOutput
On exit: the n pseudorandom numbers from the specified geometric distribution.
8:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, MODE=value.
Constraint: MODE=0, 1, 2 or 3.
IFAIL=2
On entry, N=value.
Constraint: N≥0.
IFAIL=3
On entry, P=value.
Constraint: machine precision≤P≤1.0.
P is so small that LR would have to be larger than the largest representable integer. Use MODE=3 instead. P=value
IFAIL=4
On entry, some of the elements of the array R have been corrupted or have not been initialized.
P is not the same as when R was set up in a previous call.
Previous value of P=value and P=value.
IFAIL=5
On entry, LR is too small when MODE=0 or 2: LR=value, minimum length required =value.
IFAIL=6
On entry, STATE vector has been corrupted or not initialized.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

Not applicable.

8 Parallelism and Performance

G05TCF is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The time taken to set up the reference vector, if used, increases with the length of array R. However, if the reference vector is used, the time taken to generate numbers decreases as the space allotted to the index part of R increases. Nevertheless, there is a point, depending on the distribution, where this improvement becomes very small and the suggested value for the length of array R is designed to approximate this point.
If P is very small then the storage requirements for the reference vector and the time taken to set up the reference vector becomes prohibitive. In this case it is recommended that the reference vector is not used. This is achieved by selecting MODE=3.

10 Example

This example prints 10 pseudorandom integers from a geometric distribution with parameter p=0.001, generated by a single call to G05TCF, after initialization by G05KFF.

10.1 Program Text

Program Text (g05tcfe.f90)

10.2 Program Data

Program Data (g05tcfe.d)

10.3 Program Results

Program Results (g05tcfe.r)

G05 Chapter Contents
G05 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


G05TDF : NAG Library, Mark 26

G05 Chapter Contents
G05 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

G05TDF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

G05TDF generates a vector of pseudorandom integers from a discrete distribution with a given PDF (probability density function) or CDF (cumulative distribution function) p.

2 Specification

SUBROUTINE G05TDF ( MODE, N, P, NP, IP1, ITYPE, R, LR, STATE, X, IFAIL)
INTEGER | MODE, N, NP, IP1, ITYPE, LR, STATE(*), X(N), IFAIL
REAL (KIND=nag_wp) | P(NP), R(LR)

3 Description

G05TDF generates a sequence of n integers xi, from a discrete distribution defined by information supplied in P. This may either be the PDF or CDF of the distribution. A reference vector is first set up to contain the CDF of the distribution in its higher elements, followed by an index.
Setting up the reference vector and subsequent generation of variates can each be performed by separate calls to G05TDF or may be combined in a single call.
One of the initialization routines G05KFF (for a repeatable sequence if computed sequentially) or G05KGF (for a non-repeatable sequence) must be called prior to the first call to G05TDF.

4 References

Kendall M G and Stuart A (1969) The Advanced Theory of Statistics (Volume 1) (3rd Edition) Griffin
Knuth D E (1981) The Art of Computer Programming (Volume 2) (2nd Edition) Addison–Wesley

5 Arguments

1:   MODE – INTEGERInput
On entry: a code for selecting the operation to be performed by the routine.
MODE=0
Set up reference vector only.
MODE=1
Generate variates using reference vector set up in a prior call to G05TDF.
MODE=2
Set up reference vector and generate variates.
MODE=3
Generate variates without using the reference vector.
Constraint: MODE=0, 1, 2 or 3.
2:   N – INTEGERInput
On entry: n, the number of pseudorandom numbers to be generated.
Constraint: N≥0.
3:   P NP – REAL (KIND=nag_wp) arrayInput
On entry: the PDF or CDF of the distribution.
Constraints:
  • 0.0≤P i≤1.0, for i=1,2,…,NP;
  • if ITYPE=1, ∑ i=1 NP P i=1.0;
  • if ITYPE=2, P i<P j, ​i<j​ and ​P NP=1.0.
4:   NP – INTEGERInput
On entry: the number of values supplied in P defining the PDF or CDF of the discrete distribution.
Constraint: NP>0.
5:   IP1 – INTEGERInput
On entry: the value of the variate, a whole number, to which the probability in P 1 corresponds.
6:   ITYPE – INTEGERInput
On entry: indicates the type of information contained in P.
ITYPE=1
P contains a probability distribution function (PDF).
ITYPE=2
P contains a cumulative distribution function (CDF).
Constraint: ITYPE=1 or 2.
7:   R LR – REAL (KIND=nag_wp) arrayCommunication Array
On entry: if MODE=1, the reference vector from the previous call to G05TDF.
On exit: the reference vector.
8:   LR – INTEGERInput
On entry: the dimension of the array R as declared in the (sub)program from which G05TDF is called.
Suggested values:
  • if MODE≠3, LR=10+1.4×NP approximately (for optimum efficiency in generating variates);
  • otherwise LR=1.
Constraints:
  • if MODE=0 or 2, LR≥NP+8;
  • if MODE=1, LR should remain unchanged from the previous call to G05TDF.
9:   STATE* – INTEGER arrayCommunication Array
Note: the actual argument supplied must be the array STATE supplied to the initialization routines G05KFF or G05KGF.
On entry: contains information on the selected base generator and its current state.
On exit: contains updated information on the state of the generator.
10:   X N – INTEGER arrayOutput
On exit: contains n pseudorandom numbers from the specified discrete distribution.
11:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, MODE=value.
Constraint: MODE=0, 1 or 2.
IFAIL=2
On entry, N=value.
Constraint: N≥0.
IFAIL=3
On entry, at least one element of the vector P is less than 0.0 or greater than 1.0.
On entry, ITYPE=1 and the sum of the elements of P do not equal one.
On entry, ITYPE=2 and the values of P are not all in stricly ascending order.
On entry, P NP=value.
Constraint: if ITYPE=2, P NP=1.0.
IFAIL=4
On entry, NP=value.
Constraint: NP>0.
IFAIL=6
On entry, ITYPE=value.
Constraint: ITYPE=1 or 2.
IFAIL=7
On entry, some of the elements of the array R have been corrupted or have not been initialized.
The value of NP or IP1 is not the same as when R was set up in a previous call.
Previous value of NP=value and NP=value.
Previous value of IP1=value and IP1=value.
IFAIL=8
On entry, LR is too small when MODE=0 or 2: LR=value, minimum length required =value.
IFAIL=9
On entry, STATE vector has been corrupted or not initialized.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

Not applicable.

8 Parallelism and Performance

G05TDF is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

None.

10 Example

This example prints 20 pseudorandom variates from a discrete distribution whose PDF, p, is defined as follows:
n p -5 0.01 -4 0.02 -3 0.04 -2 0.08 -1 0.20 -0 0.30 -1 0.20 -2 0.08 -3 0.04 -4 0.02 -5 0.01
The reference vector is set up and and the variates are generated by a single call to G05TDF, after initialization by G05KFF.

10.1 Program Text

Program Text (g05tdfe.f90)

10.2 Program Data

Program Data (g05tdfe.d)

10.3 Program Results

Program Results (g05tdfe.r)

G05 Chapter Contents
G05 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


G05TEF : NAG Library, Mark 26

G05 Chapter Contents
G05 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

G05TEF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

G05TEF generates a vector of pseudorandom integers from the discrete hypergeometric distribution of the number of specified items in a sample of size l, taken from a population of size k with m specified items in it.

2 Specification

SUBROUTINE G05TEF ( MODE, N, NS, NP, M, R, LR, STATE, X, IFAIL)
INTEGER | MODE, N, NS, NP, M, LR, STATE(*), X(N), IFAIL
REAL (KIND=nag_wp) | R(LR)

3 Description

G05TEF generates n integers xi from a discrete hypergeometric distribution, where the probability of xi=I is
P i=I= l!m!k-l!k-m! I!l-I!m-I!k-m-l+I!k!   if I = max 0,m+l-k , … , min l,m , P i=I=0   otherwise.
The variates can be generated with or without using a search table and index. If a search table is used then it is stored with the index in a reference vector and subsequent calls to G05TEF with the same parameter values can then use this reference vector to generate further variates. The reference array is generated by a recurrence relation if lm k-lk-m<50 k 3, otherwise Stirling's approximation is used.
One of the initialization routines G05KFF (for a repeatable sequence if computed sequentially) or G05KGF (for a non-repeatable sequence) must be called prior to the first call to G05TEF.

4 References

Knuth D E (1981) The Art of Computer Programming (Volume 2) (2nd Edition) Addison–Wesley

5 Arguments

1:   MODE – INTEGERInput
On entry: a code for selecting the operation to be performed by the routine.
MODE=0
Set up reference vector only.
MODE=1
Generate variates using reference vector set up in a prior call to G05TEF.
MODE=2
Set up reference vector and generate variates.
MODE=3
Generate variates without using the reference vector.
Constraint: MODE=0, 1, 2 or 3.
2:   N – INTEGERInput
On entry: n, the number of pseudorandom numbers to be generated.
Constraint: N≥0.
3:   NS – INTEGERInput
On entry: l, the sample size of the hypergeometric distribution.
Constraint: 0≤NS≤NP.
4:   NP – INTEGERInput
On entry: k, the population size of the hypergeometric distribution.
Constraint: NP≥0.
5:   M – INTEGERInput
On entry: m, the number of specified items of the hypergeometric distribution.
Constraint: 0≤M≤NP.
6:   R LR – REAL (KIND=nag_wp) arrayCommunication Array
On entry: if MODE=1, the reference vector from the previous call to G05TEF.
If MODE=3, R is not referenced.
On exit: if MODE≠3, the reference vector.
7:   LR – INTEGERInput
On entry: the dimension of the array R as declared in the (sub)program from which G05TEF is called.
Suggested values:
  • if MODE≠3, LR = 28+20× NS×M× NP-M × NP-NS / NP 3 approximately;
  • otherwise LR=1.
Constraints:
  • if MODE=0 or 2, LR must not be too small, but the limit is too complicated to specify;
  • if MODE=1, LR must remain unchanged from the previous call to G05TEF.
8:   STATE* – INTEGER arrayCommunication Array
Note: the actual argument supplied must be the array STATE supplied to the initialization routines G05KFF or G05KGF.
On entry: contains information on the selected base generator and its current state.
On exit: contains updated information on the state of the generator.
9:   X N – INTEGER arrayOutput
On exit: the pseudorandom numbers from the specified hypergeometric distribution.
10:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, MODE=value.
Constraint: MODE=0, 1, 2 or 3.
IFAIL=2
On entry, N=value.
Constraint: N≥0.
IFAIL=3
On entry, NS=value and NP=value.
Constraint: 0≤NS≤NP.
IFAIL=4
On entry, NP=value.
Constraint: NP≥0.
IFAIL=5
On entry, M=value and NP=value.
Constraint: 0≤M≤NP.
IFAIL=6
On entry, some of the elements of the array R have been corrupted or have not been initialized.
The value of NS, NP or M is not the same as when R was set up in a previous call with MODE=0 or 2.
IFAIL=7
On entry, LR is too small when MODE=0 or 2: LR=value, minimum length required =value.
IFAIL=8
On entry, STATE vector has been corrupted or not initialized.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

Not applicable.

8 Parallelism and Performance

G05TEF is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

None.

10 Example

The example program prints 20 pseudorandom integers from a hypergeometric distribution with l=500, m=900 and n=1000, generated by a single call to G05TEF, after initialization by G05KFF.

10.1 Program Text

Program Text (g05tefe.f90)

10.2 Program Data

Program Data (g05tefe.d)

10.3 Program Results

Program Results (g05tefe.r)

G05 Chapter Contents
G05 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


G05TFF : NAG Library, Mark 26

G05 Chapter Contents
G05 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

G05TFF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

G05TFF generates a vector of pseudorandom integers from the discrete logarithmic distribution with parameter a.

2 Specification

SUBROUTINE G05TFF ( MODE, N, A, R, LR, STATE, X, IFAIL)
INTEGER | MODE, N, LR, STATE(*), X(N), IFAIL
REAL (KIND=nag_wp) | A, R(LR)

3 Description

G05TFF generates n integers xi from a discrete logarithmic distribution, where the probability of xi=I is
P xi=I = - aI I × log 1-a ,   I=1,2,… ,
where 0<a<1.
The variates can be generated with or without using a search table and index. If a search table is used then it is stored with the index in a reference vector and subsequent calls to G05TFF with the same parameter value can then use this reference vector to generate further variates.
One of the initialization routines G05KFF (for a repeatable sequence if computed sequentially) or G05KGF (for a non-repeatable sequence) must be called prior to the first call to G05TFF.

4 References

Knuth D E (1981) The Art of Computer Programming (Volume 2) (2nd Edition) Addison–Wesley

5 Arguments

1:   MODE – INTEGERInput
On entry: a code for selecting the operation to be performed by the routine.
MODE=0
Set up reference vector only.
MODE=1
Generate variates using reference vector set up in a prior call to G05TFF.
MODE=2
Set up reference vector and generate variates.
MODE=3
Generate variates without using the reference vector.
Constraint: MODE=0, 1, 2 or 3.
2:   N – INTEGERInput
On entry: n, the number of pseudorandom numbers to be generated.
Constraint: N≥0.
3:   A – REAL (KIND=nag_wp)Input
On entry: a, the parameter of the logarithmic distribution.
Constraint: 0.0<A<1.0.
4:   R LR – REAL (KIND=nag_wp) arrayCommunication Array
On entry: if MODE=1, the reference vector from the previous call to G05TFF.
If MODE=3, R is not referenced.
On exit: MODE≠3, the reference vector.
5:   LR – INTEGERInput
On entry: the dimension of the array R as declared in the (sub)program from which G05TFF is called.
Suggested values:
  • if MODE≠3, LR=18+ 40 1-A ;
  • otherwise LR=1.
Constraints:
  • if MODE=0 or 2, LR must not be too small, but the lower limit is too complicated to specify;
  • if MODE=1, LR must remain unchanged from the previous call to G05TFF.
6:   STATE* – INTEGER arrayCommunication Array
Note: the actual argument supplied must be the array STATE supplied to the initialization routines G05KFF or G05KGF.
On entry: contains information on the selected base generator and its current state.
On exit: contains updated information on the state of the generator.
7:   X N – INTEGER arrayOutput
On exit: the n pseudorandom numbers from the specified logarithmic distribution.
8:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, MODE=value.
Constraint: MODE=0, 1, 2 or 3.
IFAIL=2
On entry, N=value.
Constraint: N≥0.
IFAIL=3
On entry, A=value.
Constraint: 0.0<A<1.0.
IFAIL=4
On entry, some of the elements of the array R have been corrupted or have not been initialized.
The value of A is not the same as when R was set up in a previous call.
Previous value of A=value and A=value .
IFAIL=5
On entry, LR is too small when MODE=0 or 2: LR=value, minimum length required =value.
IFAIL=6
On entry, STATE vector has been corrupted or not initialized.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

Not applicable.

8 Parallelism and Performance

G05TFF is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

None.

10 Example

This example prints 10 pseudorandom integers from a logarithmic distribution with parameter a=0.9999, generated by a single call to G05TFF, after initialization by G05KFF.

10.1 Program Text

Program Text (g05tffe.f90)

10.2 Program Data

Program Data (g05tffe.d)

10.3 Program Results

Program Results (g05tffe.r)

G05 Chapter Contents
G05 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


G05TGF : NAG Library, Mark 26

G05 Chapter Contents
G05 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

G05TGF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

G05TGF generates a sequence of n variates, each consisting of k pseudorandom integers, from the discrete multinomial distribution with k outcomes and m trials, where the outcomes have probabilities p 1,p 2,…,pk respectively.

2 Specification

SUBROUTINE G05TGF ( MODE, N, M, K, P, R, LR, STATE, X, LDX, IFAIL)
INTEGER | MODE, N, M, K, LR, STATE(*), X(LDX,K), LDX, IFAIL
REAL (KIND=nag_wp) | P(K), R(LR)

3 Description

G05TGF generates a sequence of n groups of k integers x i,j, for j=1,2,…,k and i=1,2,…,n, from a multinomial distribution with m trials and k outcomes, where the probability of x i,j=Ij for each j=1,2,…,k is
P i 1=I 1,…,ik=Ik= m! ∏j=1 k Ij! ∏j=1 k pj Ij= m! I 1!I 2!⋯Ik! p 1 I 1p 2 I 2⋯pk Ik,
where
∑j= 1 k pj= 1  and   ∑j= 1 k Ij=m.
A single trial can have several outcomes (k) and the probability of achieving each outcome is known (pj). After m trials each outcome will have occurred a certain number of times. The k numbers representing the numbers of occurrences for each outcome after m trials is then a single sample from the multinomial distribution defined by the parameters k, m and pj, for j=1,2,…,k. This routine returns n such samples.
When k=2 this distribution is equivalent to the binomial distribution with parameters m and p=p 1 (see G05TAF).
The variates can be generated with or without using a search table and index. If a search table is used then it is stored with the index in a reference vector and subsequent calls to G05TGF with the same parameter values can then use this reference vector to generate further variates. The reference array is generated only for the outcome with greatest probability. The number of successes for the outcome with greatest probability is calculated first as for the binomial distribution (see G05TAF); the number of successes for other outcomes are calculated in turn for the remaining reduced multinomial distribution; the number of successes for the final outcome is simply calculated to ensure that the total number of successes is m.
One of the initialization routines G05KFF (for a repeatable sequence if computed sequentially) or G05KGF (for a non-repeatable sequence) must be called prior to the first call to G05TGF.

4 References

Knuth D E (1981) The Art of Computer Programming (Volume 2) (2nd Edition) Addison–Wesley

5 Arguments

1:   MODE – INTEGERInput
On entry: a code for selecting the operation to be performed by the routine.
MODE=0
Set up reference vector only.
MODE=1
Generate variates using reference vector set up in a prior call to G05TGF.
MODE=2
Set up reference vector and generate variates.
MODE=3
Generate variates without using the reference vector.
Constraint: MODE=0, 1, 2 or 3.
2:   N – INTEGERInput
On entry: n, the number of pseudorandom numbers to be generated.
Constraint: N≥0.
3:   M – INTEGERInput
On entry: m, the number of trials of the multinomial distribution.
Constraint: M≥0.
4:   K – INTEGERInput
On entry: k, the number of possible outcomes of the multinomial distribution.
Constraint: K≥2.
5:   P K – REAL (KIND=nag_wp) arrayInput
On entry: contains the probabilities pj, for j=1,2,…,k, of the k possible outcomes of the multinomial distribution.
Constraint: 0.0≤P j≤1.0 and ∑j=1 k P j=1.0.
6:   R LR – REAL (KIND=nag_wp) arrayCommunication Array
On entry: if MODE=1, the reference vector from the previous call to G05TGF.
If MODE=3, R is not referenced.
On exit: if MODE≠3, the reference vector.
7:   LR – INTEGERInput
Note: for convenience p_max will be used here to denote the expression p_max=maxj P j.
On entry: the dimension of the array R as declared in the (sub)program from which G05TGF is called.
Suggested values:
  • if MODE≠3, LR=30+20×M×p_max×1-p_max;
  • otherwise LR=1.
Constraints:
  • if MODE=0 or 2,
    LR > min M,INT M×p_max+7.25 × M× p_max×1-p_max +8.5 - max 0,INT M×p_max-7.25 × M×p_max× 1-p_max +9 ;
  • if MODE=1, LR must remain unchanged from the previous call to G05TGF.
8:   STATE* – INTEGER arrayCommunication Array
Note: the actual argument supplied must be the array STATE supplied to the initialization routines G05KFF or G05KGF.
On entry: contains information on the selected base generator and its current state.
On exit: contains updated information on the state of the generator.
9:   X LDXK – INTEGER arrayOutput
On exit: the first n rows of X ij each contain k pseudorandom numbers representing a k-dimensional variate from the specified multinomial distribution.
10:   LDX – INTEGERInput
On entry: the first dimension of the array X as declared in the (sub)program from which G05TGF is called.
Constraint: LDX≥N.
11:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, MODE=value.
Constraint: MODE=0, 1, 2 or 3.
IFAIL=2
On entry, N=value.
Constraint: N≥0.
IFAIL=3
On entry, M=value.
Constraint: M≥0.
IFAIL=4
On entry, K=value.
Constraint: K≥2.
IFAIL=5
On entry, at least one element of the vector P is less than 0.0 or greater than 1.0.
On entry, the sum of the elements of P do not equal one.
IFAIL=6
On entry, some of the elements of the array R have been corrupted or have not been initialized.
The value of M or K is not the same as when R was set up in a previous call.
Previous value of M=value and M=value.
Previous value of K=value and K=value.
IFAIL=7
On entry, LR is too small when MODE=0 or 2: LR=value, minimum length required =value.
IFAIL=8
On entry, STATE vector has been corrupted or not initialized.
IFAIL=10
On entry, LDX=value and N=value.
Constraint: LDX≥N.
IFAIL=210
On entry, LDX=value and K=value.
Constraint: LDX≥K.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

Not applicable.

8 Parallelism and Performance

G05TGF is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The reference vector for only one outcome can be set up because the conditional distributions cannot be known in advance of the generation of variates. The outcome with greatest probability of success is chosen for the reference vector because it will have the greatest spread of likely values.

10 Example

This example prints 20 pseudorandom k-dimensional variates from a multinomial distribution with k=4, m=6000, p 1=0.08, p 2=0.1, p 3=0.8 and p 4=0.02, generated by a single call to G05TGF, after initialization by G05KFF.

10.1 Program Text

Program Text (g05tgfe.f90)

10.2 Program Data

Program Data (g05tgfe.d)

10.3 Program Results

Program Results (g05tgfe.r)

G05 Chapter Contents
G05 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


G05THF : NAG Library, Mark 26

G05 Chapter Contents
G05 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

G05THF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

G05THF generates a vector of pseudorandom integers from the discrete negative binomial distribution with parameter m and probability p of success at a trial.

2 Specification

SUBROUTINE G05THF ( MODE, N, M, P, R, LR, STATE, X, IFAIL)
INTEGER | MODE, N, M, LR, STATE(*), X(N), IFAIL
REAL (KIND=nag_wp) | P, R(LR)

3 Description

G05THF generates n integers xi from a discrete negative binomial distribution, where the probability of xi=I (I successes before m failures) is
P xi=I= m+I-1! I!m-1! ×pI×1-p m,  I=0,1,….
The variates can be generated with or without using a search table and index. If a search table is used then it is stored with the index in a reference vector and subsequent calls to G05THF with the same parameter value can then use this reference vector to generate further variates.
One of the initialization routines G05KFF (for a repeatable sequence if computed sequentially) or G05KGF (for a non-repeatable sequence) must be called prior to the first call to G05THF.

4 References

Knuth D E (1981) The Art of Computer Programming (Volume 2) (2nd Edition) Addison–Wesley

5 Arguments

1:   MODE – INTEGERInput
On entry: a code for selecting the operation to be performed by the routine.
MODE=0
Set up reference vector only.
MODE=1
Generate variates using reference vector set up in a prior call to G05THF.
MODE=2
Set up reference vector and generate variates.
MODE=3
Generate variates without using the reference vector.
Constraint: MODE=0, 1, 2 or 3.
2:   N – INTEGERInput
On entry: n, the number of pseudorandom numbers to be generated.
Constraint: N≥0.
3:   M – INTEGERInput
On entry: m, the number of failures of the distribution.
Constraint: M≥0.
4:   P – REAL (KIND=nag_wp)Input
On entry: p, the parameter of the negative binomial distribution representing the probability of success at a single trial.
Constraint: 0.0≤P<1.0.
5:   R LR – REAL (KIND=nag_wp) arrayCommunication Array
On entry: if MODE=1, the reference vector from the previous call to G05THF.
If MODE=3, R is not referenced.
On exit: if MODE≠3, the reference vector.
6:   LR – INTEGERInput
On entry: the dimension of the array R as declared in the (sub)program from which G05THF is called.
Suggested values:
  • if MODE≠3,
    LR=28+ 20× M×P +30×P / 1-P ​ approximately ;
  • otherwise LR=1.
Constraints:
  • if MODE=0 or 2,
    LR> int M×P+7.15 × M×P+ 20.15×P 1-P +8.5 - max⁡ 0,int M× P-7.15 × M×P 1-P +9 ;
  • if MODE=1, LR must remain unchanged from the previous call to G05THF.
7:   STATE* – INTEGER arrayCommunication Array
Note: the actual argument supplied must be the array STATE supplied to the initialization routines G05KFF or G05KGF.
On entry: contains information on the selected base generator and its current state.
On exit: contains updated information on the state of the generator.
8:   X N – INTEGER arrayOutput
On exit: the n pseudorandom numbers from the specified negative binomial distribution.
9:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, MODE=value.
Constraint: MODE=0, 1, 2 or 3.
IFAIL=2
On entry, N=value.
Constraint: N≥0.
IFAIL=3
On entry, M=value.
Constraint: M≥0.
IFAIL=4
On entry, P=value.
Constraint: 0.0≤P<1.0.
IFAIL=5
On entry, some of the elements of the array R have been corrupted or have not been initialized.
P or M is not the same as when R was set up in a previous call.
Previous value of P=value and P=value.
Previous value of M=value and M=value.
IFAIL=6
On entry, LR is too small when MODE=0 or 2: LR=value, minimum length required =value.
IFAIL=7
On entry, STATE vector has been corrupted or not initialized.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

Not applicable.

8 Parallelism and Performance

G05THF is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

None.

10 Example

This example prints 20 pseudorandom integers from a negative binomial distribution with parameters m=60 and p=0.999, generated by a single call to G05THF, after initialization by G05KFF.

10.1 Program Text

Program Text (g05thfe.f90)

10.2 Program Data

Program Data (g05thfe.d)

10.3 Program Results

Program Results (g05thfe.r)

G05 Chapter Contents
G05 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


G05TJF : NAG Library, Mark 26

G05 Chapter Contents
G05 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

G05TJF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

G05TJF generates a vector of pseudorandom integers from the discrete Poisson distribution with mean λ.

2 Specification

SUBROUTINE G05TJF ( MODE, N, LAMBDA, R, LR, STATE, X, IFAIL)
INTEGER | MODE, N, LR, STATE(*), X(N), IFAIL
REAL (KIND=nag_wp) | LAMBDA, R(LR)

3 Description

G05TJF generates n integers xi from a discrete Poisson distribution with mean λ, where the probability of xi=I is
P xi=I= λI×e-λ I! ,  I=0,1,…,
where λ≥0.
The variates can be generated with or without using a search table and index. If a search table is used then it is stored with the index in a reference vector and subsequent calls to G05TJF with the same parameter values can then use this reference vector to generate further variates. The reference array is found using a recurrence relation if λ is less than 50 and by Stirling's formula otherwise.
One of the initialization routines G05KFF (for a repeatable sequence if computed sequentially) or G05KGF (for a non-repeatable sequence) must be called prior to the first call to G05TJF.

4 References

Kendall M G and Stuart A (1969) The Advanced Theory of Statistics (Volume 1) (3rd Edition) Griffin
Knuth D E (1981) The Art of Computer Programming (Volume 2) (2nd Edition) Addison–Wesley

5 Arguments

1:   MODE – INTEGERInput
On entry: a code for selecting the operation to be performed by the routine.
MODE=0
Set up reference vector only.
MODE=1
Generate variates using reference vector set up in a prior call to G05TJF.
MODE=2
Set up reference vector and generate variates.
MODE=3
Generate variates without using the reference vector.
Constraint: MODE=0, 1, 2 or 3.
2:   N – INTEGERInput
On entry: n, the number of pseudorandom numbers to be generated.
Constraint: N≥0.
3:   LAMBDA – REAL (KIND=nag_wp)Input
On entry: λ, the mean of the Poisson distribution.
Constraint: LAMBDA≥0.0.
4:   R LR – REAL (KIND=nag_wp) arrayCommunication Array
On entry: if MODE=1, the reference vector from the previous call to G05TJF.
If MODE=3, R is not referenced.
On exit: if MODE≠3, the reference vector.
5:   LR – INTEGERInput
On entry: the dimension of the array R as declared in the (sub)program from which G05TJF is called.
Suggested values:
  • if MODE≠3, LR=30+20×LAMBDA+LAMBDA;
  • otherwise LR=1.
Constraints:
  • if MODE=0 or 2,
    • if LAMBDA>7.15, LR>9+int 8.5+14.3×LAMBDA;
    • otherwise LR>9+int LAMBDA+7.15×LAMBDA+8.5;
  • if MODE=1, LR must remain unchanged from the previous call to G05TJF.
6:   STATE* – INTEGER arrayCommunication Array
Note: the actual argument supplied must be the array STATE supplied to the initialization routines G05KFF or G05KGF.
On entry: contains information on the selected base generator and its current state.
On exit: contains updated information on the state of the generator.
7:   X N – INTEGER arrayOutput
On exit: the n pseudorandom numbers from the specified Poisson distribution.
8:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, MODE=value.
Constraint: MODE=0, 1, 2 or 3.
IFAIL=2
On entry, N=value.
Constraint: N≥0.
IFAIL=3
LAMBDA is such that LR would have to be larger than the largest representable integer. Use MODE=3 instead. LAMBDA=value.
On entry, LAMBDA=value.
Constraint: LAMBDA≥0.0.
IFAIL=4
LAMBDA is not the same as when R was set up in a previous call.
Previous value of LAMBDA=value and LAMBDA=value.
On entry, some of the elements of the array R have been corrupted or have not been initialized.
IFAIL=5
On entry, LR is too small when MODE=0 or 2: LR=value, minimum length required =value.
IFAIL=6
On entry, STATE vector has been corrupted or not initialized.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

Not applicable.

8 Parallelism and Performance

G05TJF is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

None.

10 Example

This example prints 10 pseudorandom integers from a Poisson distribution with mean λ=20, generated by a single call to G05TJF, after initialization by G05KFF.

10.1 Program Text

Program Text (g05tjfe.f90)

10.2 Program Data

Program Data (g05tjfe.d)

10.3 Program Results

Program Results (g05tjfe.r)

G05 Chapter Contents
G05 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


G05TKF : NAG Library, Mark 26

G05 Chapter Contents
G05 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

G05TKF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

G05TKF generates a vector of pseudorandom integers, each from a discrete Poisson distribution with differing parameter.

2 Specification

SUBROUTINE G05TKF ( M, VLAMDA, STATE, X, IFAIL)
INTEGER | M, STATE(*), X(M), IFAIL
REAL (KIND=nag_wp) | VLAMDA(M)

3 Description

G05TKF generates m integers xj, each from a discrete Poisson distribution with mean λj, where the probability of xj=I is
P xj=I = λjI × e -λj I! ,   I=0,1,… ,
where
λj ≥ 0 ,   j=1,2,…,m .
The methods used by this routine have low set up times and are designed for efficient use when the value of the parameter λ changes during the simulation. For large samples from a distribution with fixed λ using G05TJF to set up and use a reference vector may be more efficient.
When λ<7.5 the product of uniforms method is used, see for example Dagpunar (1988). For larger values of λ an envelope rejection method is used with a target distribution:
f x=13 if ​x≤1, f x=13 x-3 otherwise.
This distribution is generated using a ratio of uniforms method. A similar approach has also been suggested by Ahrens and Dieter (1989). The basic method is combined with quick acceptance and rejection tests given by Maclaren (1990). For values of λ≥87 Stirling's approximation is used in the computation of the Poisson distribution function, otherwise tables of factorials are used as suggested by Maclaren (1990).
One of the initialization routines G05KFF (for a repeatable sequence if computed sequentially) or G05KGF (for a non-repeatable sequence) must be called prior to the first call to G05TKF.

4 References

Ahrens J H and Dieter U (1989) A convenient sampling method with bounded computation times for Poisson distributions Amer. J. Math. Management Sci. 1–13
Dagpunar J (1988) Principles of Random Variate Generation Oxford University Press
Maclaren N M (1990) A Poisson random number generator Personal Communication

5 Arguments

1:   M – INTEGERInput
On entry: m, the number of Poisson distributions for which pseudorandom variates are required.
Constraint: M≥1.
2:   VLAMDA M – REAL (KIND=nag_wp) arrayInput
On entry: the means, λj, for j=1,2,…,M, of the Poisson distributions.
Constraint: 0.0≤VLAMDA j≤X02BBF/2.0, for j=1,2,…,M.
3:   STATE* – INTEGER arrayCommunication Array
Note: the actual argument supplied must be the array STATE supplied to the initialization routines G05KFF or G05KGF.
On entry: contains information on the selected base generator and its current state.
On exit: contains updated information on the state of the generator.
4:   X M – INTEGER arrayOutput
On exit: the m pseudorandom numbers from the specified Poisson distributions.
5:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, M=value.
Constraint: M≥1.
IFAIL=2
On entry, at least one element of VLAMDA is less than zero.
On entry, at least one element of VLAMDA is too large.
IFAIL=3
On entry, STATE vector has been corrupted or not initialized.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

Not applicable.

8 Parallelism and Performance

G05TKF is not threaded in any implementation.

9 Further Comments

None.

10 Example

This example prints ten pseudorandom integers from five Poisson distributions with means λ 1=0.5, λ 2=5, λ 3=10, λ 4=500 and λ 5=1000. These are generated by ten calls to G05TKF, after initialization by G05KFF.

10.1 Program Text

Program Text (g05tkfe.f90)

10.2 Program Data

Program Data (g05tkfe.d)

10.3 Program Results

Program Results (g05tkfe.r)

G05 Chapter Contents
G05 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


G05TLF : NAG Library, Mark 26

G05 Chapter Contents
G05 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

G05TLF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

G05TLF generates a vector of pseudorandom integers uniformly distributed over the interval a,b.

2 Specification

SUBROUTINE G05TLF ( N, A, B, STATE, X, IFAIL)
INTEGER N, A, B, STATE(*), X(N), IFAIL

3 Description

G05TLF generates the next n values yi from a uniform 0,1 generator (see G05SAF for details) and applies the transformation
xi = a+ b-a+1 yi ,
where z is the integer part of the real value z. The routine ensures that the values xi lie in the closed interval a,b.
One of the initialization routines G05KFF (for a repeatable sequence if computed sequentially) or G05KGF (for a non-repeatable sequence) must be called prior to the first call to G05TLF.

4 References

Knuth D E (1981) The Art of Computer Programming (Volume 2) (2nd Edition) Addison–Wesley

5 Arguments

1:   N – INTEGERInput
On entry: n, the number of pseudorandom numbers to be generated.
Constraint: N≥0.
2:   A – INTEGERInput
3:   B – INTEGERInput
On entry: the end points a and b of the uniform distribution.
Constraint: A≤B.
4:   STATE* – INTEGER arrayCommunication Array
Note: the actual argument supplied must be the array STATE supplied to the initialization routines G05KFF or G05KGF.
On entry: contains information on the selected base generator and its current state.
On exit: contains updated information on the state of the generator.
5:   X N – INTEGER arrayOutput
On exit: the n pseudorandom numbers from the specified uniform distribution.
6:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, N=value.
Constraint: N≥0.
IFAIL=3
On entry, A=value and B=value.
Constraint: B≥A.
IFAIL=4
On entry, STATE vector has been corrupted or not initialized.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

Not applicable.

8 Parallelism and Performance

G05TLF is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

None.

10 Example

This example prints five pseudorandom integers from a discrete uniform distribution between -5 and 5, generated by a single call to G05TLF, after initialization by G05KFF.

10.1 Program Text

Program Text (g05tlfe.f90)

10.2 Program Data

Program Data (g05tlfe.d)

10.3 Program Results

Program Results (g05tlfe.r)

G05 Chapter Contents
G05 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


G05XAF : NAG Library, Mark 26

G05 Chapter Contents
G05 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

G05XAF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
▸▿ 3 Description
3.1 Brownian Bridge Algorithm
3.2 Implementation
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

G05XAF initializes the Brownian bridge generator G05XBF. It must be called before any calls to G05XBF.

2 Specification

SUBROUTINE G05XAF ( T0, TEND, TIMES, NTIMES, RCOMM, IFAIL)
INTEGER | NTIMES, IFAIL
REAL (KIND=nag_wp) | T0, TEND, TIMES(NTIMES), RCOMM(12*(NTIMES+1))

3 Description

3.1 Brownian Bridge Algorithm

Details on the Brownian bridge algorithm and the Brownian bridge process (sometimes also called a non-free Wiener process) can be found in Section 2.6 in the G05 Chapter Introduction. We briefly recall some notation and definitions.
Fix two times t 0<T and let ti 1≤i≤N be any set of time points satisfying t 0<t 1<t 2<⋯<tN<T. Let X ti 1≤i≤N denote a d-dimensional Wiener sample path at these time points, and let C be any d by d matrix such that C CT is the desired covariance structure for the Wiener process. Each point X ti of the sample path is constructed according to the Brownian bridge interpolation algorithm (see Glasserman (2004) or Section 2.6 in the G05 Chapter Introduction). We always start at some fixed point X t 0 = x∈ℝd . If we set XT =x+ C T-t 0 Z where Z is any d-dimensional standard Normal random variable, then X will behave like a normal (free) Wiener process. However if we fix the terminal value XT = w∈ℝd , then X will behave like a non-free Wiener process.

3.2 Implementation

Given the start and end points of the process, the order in which successive interpolation times tj are chosen is called the bridge construction order. The construction order is given by the array TIMES. Further information on construction orders is given in Section 2.6.2 in the G05 Chapter Introduction. For clarity we consider here the common scenario where the Brownian bridge algorithm is used with quasi-random points. If pseudorandom numbers are used instead, these details can be ignored.
Suppose we require P Wiener sample paths each of dimension d. The main input to the Brownian bridge algorithm is then an array of quasi-random points Z 1,Z 2,…,ZP where each point Zp = Z 1 p,Z 2 p,…,ZDp has dimension D=d N+1 or D=dN respectively, depending on whether a free or non-free Wiener process is required. When G05XBF is called, the pth sample path for 1≤p≤P is constructed as follows: if a non-free Wiener process is required set XT equal to the terminal value w, otherwise construct XT as
XT = X t 0 + C T-t 0 Z 1 p ⋮ Zdp
where C is the matrix described in Section 3.1. The array TIMES holds the remaining time points t 1 , t 2 ,… tN in the order in which the bridge is to be constructed. For each j=1,…,N set r=TIMES j, find
q = max t 0, TIMES i : 1≤i<j , TIMES i < r
and
s = min T, TIMES i : 1≤i<j , TIMES i > r
and construct the point Xr as
Xr = Xq s-r + Xs r-q s-q + C s-r r-q s-q Z jd-ad+1 p ⋮ Z jd-ad+d p
where a=0 or a=1 respectively depending on whether a free or non-free Wiener process is required. Note that in our discussion j is indexed from 1, and so Xr is interpolated between the nearest (in time) Wiener points which have already been constructed. The routine G05XEF can be used to initialize the TIMES array for several predefined bridge construction orders.

4 References

Glasserman P (2004) Monte Carlo Methods in Financial Engineering Springer

5 Arguments

1:   T0 – REAL (KIND=nag_wp)Input
On entry: the starting value t 0 of the time interval.
2:   TEND – REAL (KIND=nag_wp)Input
On entry: the end value T of the time interval.
Constraint: TEND>T0.
3:   TIMES NTIMES – REAL (KIND=nag_wp) arrayInput
On entry: the points in the time interval t 0,T at which the Wiener process is to be constructed. The order in which points are listed in TIMES determines the bridge construction order. The routine G05XEF can be used to create predefined bridge construction orders from a set of input times.
Constraints:
  • T0<TIMES i<TEND, for i=1,2,…,NTIMES;
  • TIMES i ≠ TIMES j, for i,j=1,2,…NTIMES and i≠j.
4:   NTIMES – INTEGERInput
On entry: the length of TIMES, denoted by N in Section 3.1.
Constraint: NTIMES≥1.
5:   RCOMM 12×NTIMES+1 – REAL (KIND=nag_wp) arrayCommunication Array
On exit: communication array, used to store information between calls to G05XBF. This array must not be directly modified.
6:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, TEND=value and T0=value.
Constraint: TEND>T0.
IFAIL=2
On entry, NTIMES=value.
Constraint: NTIMES≥1.
IFAIL=3
On entry, TIMES value=value, T0=value and TEND=value.
Constraint: T0<TIMES i<TEND for all i.
IFAIL=4
On entry, TIMES value and TIMES value both equal value.
Constraint: all elements of TIMES must be unique.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

Not applicable.

8 Parallelism and Performance

G05XAF is not threaded in any implementation.

9 Further Comments

The efficient implementation of a Brownian bridge algorithm requires the use of a workspace array called the working stack. Since previously computed points will be used to interpolate new points, they should be kept close to the hardware processing units so that the data can be accessed quickly. Ideally the whole stack should be held in hardware cache. Different bridge construction orders may require different amounts of working stack. Indeed, a naive bridge algorithm may require a stack of size N 4 or even N 2 , which could be very inefficient when N is large. G05XAF performs a detailed analysis of the bridge construction order specified by TIMES. Heuristics are used to find an execution strategy which requires a small working stack, while still constructing the bridge in the order required.

10 Example

This example calls G05XAF, G05XBF and G05XEF to generate two sample paths of a three-dimensional free Wiener process. Pseudorandom variates are used to construct the sample paths.
See Section 10 in G05XBF and G05XEF for additional examples.

10.1 Program Text

Program Text (g05xafe.f90)

10.2 Program Data

None.

10.3 Program Results

Program Results (g05xafe.r)

G05 Chapter Contents
G05 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


G05XBF : NAG Library, Mark 26

G05 Chapter Contents
G05 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

G05XBF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

G05XBF uses a Brownian bridge algorithm to construct sample paths for a free or non-free Wiener process. The initialization routine G05XAF must be called prior to the first call to G05XBF.

2 Specification

SUBROUTINE G05XBF ( NPATHS, RCORD, D, START, A, TERM, Z, LDZ, C, LDC, B, LDB, RCOMM, IFAIL)
INTEGER | NPATHS, RCORD, D, A, LDZ, LDC, LDB, IFAIL
REAL (KIND=nag_wp) | START(D), TERM(D), Z(LDZ,*), C(LDC,*), B(LDB,*), RCOMM(*)

3 Description

For details on the Brownian bridge algorithm and the bridge construction order see Section 2.6 in the G05 Chapter Introduction and Section 3 in G05XAF. Recall that the terms Wiener process (or free Wiener process) and Brownian motion are often used interchangeably, while a non-free Wiener process (also known as a Brownian bridge process) refers to a process which is forced to terminate at a given point.

4 References

Glasserman P (2004) Monte Carlo Methods in Financial Engineering Springer

5 Arguments

Note: the following variable is used in the parameter descriptions: N=NTIMES, the length of the array TIMES passed to the initialization routine G05XAF.
1:   NPATHS – INTEGERInput
On entry: the number of Wiener sample paths to create.
Constraint: NPATHS≥1.
2:   RCORD – INTEGERInput
On entry: the order in which Normal random numbers are stored in Z and in which the generated values are returned in B.
Constraint: RCORD=1 or 2.
3:   D – INTEGERInput
On entry: the dimension of each Wiener sample path.
Constraint: D≥1.
4:   START D – REAL (KIND=nag_wp) arrayInput
On entry: the starting value of the Wiener process.
5:   A – INTEGERInput
On entry: if A=0, a free Wiener process is created beginning at START and TERM is ignored.
If A=1, a non-free Wiener process is created beginning at START and ending at TERM.
Constraint: A=0 or 1.
6:   TERM D – REAL (KIND=nag_wp) arrayInput
On entry: the terminal value at which the non-free Wiener process should end. If A=0, TERM is ignored.
7:   Z LDZ* – REAL (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array Z must be at least NPATHS if RCORD=1 and at least D×N+1-A if RCORD=2.
On entry: the Normal random numbers used to construct the sample paths.
If RCORD=1 and quasi-random numbers are used, the D×N+1-A, where N=nint RCOMM 2-dimensional quasi-random points should be stored in successive columns of Z.
If RCORD=2 and quasi-random numbers are used, the D×N+1-A, where N=nint RCOMM 2-dimensional quasi-random points should be stored in successive rows of Z.
On exit: the Normal random numbers premultiplied by C.
8:   LDZ – INTEGERInput
On entry: the first dimension of the array Z as declared in the (sub)program from which G05XBF is called.
Constraints:
  • if RCORD=1, LDZ≥D×N+1-A;
  • if RCORD=2, LDZ≥NPATHS.
9:   C LDC* – REAL (KIND=nag_wp) arrayInput
Note: the second dimension of the array C must be at least D.
On entry: the lower triangular Cholesky factorization C such that C CT gives the covariance matrix of the Wiener process. Elements of C above the diagonal are not referenced.
10:   LDC – INTEGERInput
On entry: the first dimension of the array C as declared in the (sub)program from which G05XBF is called.
Constraint: LDC≥D.
11:   B LDB* – REAL (KIND=nag_wp) arrayOutput
Note: the second dimension of the array B must be at least NPATHS if RCORD=1 and at least D×N+1 if RCORD=2.
On exit: the values of the Wiener sample paths.
Let X p,i k denote the kth dimension of the ith point of the pth sample path where 1≤k≤D, 1≤i≤N+1 and 1≤p≤NPATHS.
If RCORD=1, the point X p,i k will be stored at B k+i-1×D,p.
If RCORD=2, the point X p,i k will be stored at B p,k+i-1×D.
The starting value START is never stored, whereas the terminal value is always stored.
12:   LDB – INTEGERInput
On entry: the first dimension of the array B as declared in the (sub)program from which G05XBF is called.
Constraints:
  • if RCORD=1, LDB≥D×N+1;
  • if RCORD=2, LDB≥NPATHS.
13:   RCOMM* – REAL (KIND=nag_wp) arrayCommunication Array
Note: the dimension of this array is dictated by the requirements of associated functions that must have been previously called. This array must be the same array passed as argument RCOMM in the previous call to G05XAF or G05XBF.
On entry: communication array as returned by the last call to G05XAF or G05XBF. This array must not be directly modified.
14:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, RCOMM was not initialized or has been corrupted.
IFAIL=2
On entry, NPATHS=value.
Constraint: NPATHS≥1.
IFAIL=3
On entry, RCORD=value was an illegal value.
IFAIL=4
On entry, D=value.
Constraint: D≥1.
IFAIL=5
On entry, A=value.
Constraint: A=0​ or ​1.
IFAIL=6
On entry, LDZ=value and D×NTIMES+1-A=value.
Constraint: LDZ≥D×NTIMES+1-A.
On entry, LDZ=value and NPATHS=value.
Constraint: LDZ≥NPATHS.
IFAIL=7
On entry, LDC=value.
Constraint: LDC≥value.
IFAIL=8
On entry, LDB=value and D×NTIMES+1=value.
Constraint: LDB≥D×NTIMES+1.
On entry, LDB=value and NPATHS=value.
Constraint: LDB≥NPATHS.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

Not applicable.

8 Parallelism and Performance

G05XBF is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
G05XBF makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

None.

10 Example

This example calls G05XBF, G05XAF and G05XEF to generate two sample paths of a three-dimensional non-free Wiener process. The process starts at zero and each sample path terminates at the point 1.0,0.5,0.0. Quasi-random numbers are used to construct the sample paths.
See Section 10 in G05XAF and G05XEF for additional examples.

10.1 Program Text

Program Text (g05xbfe.f90)

10.2 Program Data

None.

10.3 Program Results

Program Results (g05xbfe.r)

G05 Chapter Contents
G05 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


G05XCF : NAG Library, Mark 26

G05 Chapter Contents
G05 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

G05XCF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
▸▿ 3 Description
3.1 Brownian Bridge Algorithm
3.2 Implementation
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

G05XCF initializes the Brownian bridge increments generator G05XDF. It must be called before any calls to G05XDF.

2 Specification

SUBROUTINE G05XCF ( T0, TEND, TIMES, NTIMES, RCOMM, IFAIL)
INTEGER | NTIMES, IFAIL
REAL (KIND=nag_wp) | T0, TEND, TIMES(NTIMES), RCOMM(12*(NTIMES+1))

3 Description

3.1 Brownian Bridge Algorithm

Details on the Brownian bridge algorithm and the Brownian bridge process (sometimes also called a non-free Wiener process) can be found in Section 2.6 in the G05 Chapter Introduction. We briefly recall some notation and definitions.
Fix two times t 0<T and let ti 1≤i≤N be any set of time points satisfying t 0<t 1<t 2<⋯<tN<T. Let X ti 1≤i≤N denote a d-dimensional Wiener sample path at these time points, and let C be any d by d matrix such that C CT is the desired covariance structure for the Wiener process. Each point X ti of the sample path is constructed according to the Brownian bridge interpolation algorithm (see Glasserman (2004) or Section 2.6 in the G05 Chapter Introduction). We always start at some fixed point X t 0 = x∈ℝd . If we set XT =x+ C T-t 0 Z where Z is any d-dimensional standard Normal random variable, then X will behave like a normal (free) Wiener process. However if we fix the terminal value XT = w∈ℝd , then X will behave like a non-free Wiener process.
The Brownian bridge increments generator uses the Brownian bridge algorithm to construct sample paths for the (free or non-free) Wiener process X, and then uses this to compute the scaled Wiener increments
X t 1 - X t 0 t 1 - t 0 , X t 2 - X t 1 t 2 - t 1 ,…, X tN - X t N-1 tN - t N-1 , XT - X tN T - tN .
Such increments can be useful in computing numerical solutions to stochastic differential equations driven by (free or non-free) Wiener processes.

3.2 Implementation

Conceptually, the output of the Wiener increments generator is the same as if G05XAF and G05XBF were called first, and the scaled increments then constructed from their output. The implementation adopts a much more efficient approach whereby the scaled increments are computed directly without first constructing the Wiener sample path.
Given the start and end points of the process, the order in which successive interpolation times tj are chosen is called the bridge construction order. The construction order is given by the array TIMES. Further information on construction orders is given in Section 2.6.2 in the G05 Chapter Introduction. For clarity we consider here the common scenario where the Brownian bridge algorithm is used with quasi-random points. If pseudorandom numbers are used instead, these details can be ignored.
Suppose we require the increments of P Wiener sample paths each of dimension d. The main input to the Brownian bridge increments generator is then an array of quasi-random points Z 1,Z 2,…,ZP where each point Zp = Z 1 p,Z 2 p,…,ZDp has dimension D=d N+1 or D=dN depending on whether a free or non-free Wiener process is required. When G05XDF is called, the pth sample path for 1≤p≤P is constructed as follows: if a non-free Wiener process is required set XT equal to the terminal value w, otherwise construct XT as
XT = X t 0 + C T-t 0 Z 1 p ⋮ Zdp
where C is the matrix described in Section 3.1. The array TIMES holds the remaining time points t 1 , t 2 ,… tN in the order in which the bridge is to be constructed. For each j=1,…,N set r=TIMES j, find
q = max t 0, TIMES i : 1≤i<j , TIMES i < r
and
s = min T, TIMES i : 1≤i<j , TIMES i > r
and construct the point Xr as
Xr = Xq s-r + Xs r-q s-q + C s-r r-q s-q Z jd-ad+1 p ⋮ Z jd-ad+d p
where a=0 or a=1 depending on whether a free or non-free Wiener process is required. The routine G05XEF can be used to initialize the TIMES array for several predefined bridge construction orders. Lastly, the scaled Wiener increments
X t 1 - X t 0 t 1 - t 0 , X t 2 - X t 1 t 2 - t 1 ,…, X tN - X t N-1 tN - t N-1 , XT - X tN T - tN
are computed.

4 References

Glasserman P (2004) Monte Carlo Methods in Financial Engineering Springer

5 Arguments

1:   T0 – REAL (KIND=nag_wp)Input
On entry: the starting value t 0 of the time interval.
2:   TEND – REAL (KIND=nag_wp)Input
On entry: the end value T of the time interval.
Constraint: TEND>T0.
3:   TIMES NTIMES – REAL (KIND=nag_wp) arrayInput
On entry: the points in the time interval t 0,T at which the Wiener process is to be constructed. The order in which points are listed in TIMES determines the bridge construction order. The routine G05XEF can be used to create predefined bridge construction orders from a set of input times.
Constraints:
  • T0<TIMES i<TEND, for i=1,2,…,NTIMES;
  • TIMES i ≠ TIMES j, for i,j=1,2,…NTIMES and i≠j.
4:   NTIMES – INTEGERInput
On entry: the length of TIMES, denoted by N in Section 3.1.
Constraint: NTIMES≥1.
5:   RCOMM 12×NTIMES+1 – REAL (KIND=nag_wp) arrayCommunication Array
On exit: communication array, used to store information between calls to G05XDF. This array must not be directly modified.
6:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, TEND=value and T0=value.
Constraint: TEND>T0.
IFAIL=2
On entry, NTIMES=value.
Constraint: NTIMES≥1.
IFAIL=3
On entry, TIMES value=value, T0=value and TEND=value.
Constraint: T0<TIMES i<TEND for all i.
IFAIL=4
On entry, TIMES i=TIMES j=value, for i=value and j=value.
Constraint: all elements of TIMES must be unique.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

Not applicable.

8 Parallelism and Performance

G05XCF is not threaded in any implementation.

9 Further Comments

The efficient implementation of a Brownian bridge algorithm requires the use of a workspace array called the working stack. Since previously computed points will be used to interpolate new points, they should be kept close to the hardware processing units so that the data can be accessed quickly. Ideally the whole stack should be held in hardware cache. Different bridge construction orders may require different amounts of working stack. Indeed, a naive bridge algorithm may require a stack of size N 4 or even N 2 , which could be very inefficient when N is large. G05XCF performs a detailed analysis of the bridge construction order specified by TIMES. Heuristics are used to find an execution strategy which requires a small working stack, while still constructing the bridge in the order required.

10 Example

The following example program calls G05XAF and G05XBF to generate two sample paths from a two-dimensional free Wiener process. It then calls G05XCF and G05XDF with the same input arguments to obtain the scaled increments of the Wiener sample paths. Lastly, the program prints the Wiener sample paths from G05XBF, the scaled increments from G05XDF, and the cumulative sum of the unscaled increments side by side. Note that the cumulative sum of the unscaled increments is identical to the output of G05XBF.
Please see Section 10 in G05XDF for additional examples.

10.1 Program Text

Program Text (g05xcfe.f90)

10.2 Program Data

None.

10.3 Program Results

Program Results (g05xcfe.r)

G05 Chapter Contents
G05 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


G05XDF : NAG Library, Mark 26

G05 Chapter Contents
G05 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

G05XDF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

G05XDF computes scaled increments of sample paths of a free or non-free Wiener process, where the sample paths are constructed by a Brownian bridge algorithm. The initialization routine G05XCF must be called prior to the first call to G05XDF.

2 Specification

SUBROUTINE G05XDF ( NPATHS, RCORD, D, A, DIFF, Z, LDZ, C, LDC, B, LDB, RCOMM, IFAIL)
INTEGER | NPATHS, RCORD, D, A, LDZ, LDC, LDB, IFAIL
REAL (KIND=nag_wp) | DIFF(D), Z(LDZ,*), C(LDC,*), B(LDB,*), RCOMM(*)

3 Description

For details on the Brownian bridge algorithm and the bridge construction order see Section 2.6 in the G05 Chapter Introduction and Section 3 in G05XCF. Recall that the terms Wiener process (or free Wiener process) and Brownian motion are often used interchangeably, while a non-free Wiener process (also known as a Brownian bridge process) refers to a process which is forced to terminate at a given point.
Fix two times t 0<T, let ti 1≤i≤N be any set of time points satisfying t 0<t 1<t 2<⋯<tN<T, and let X t 0, X ti 1≤i≤N , XT denote a d-dimensional Wiener sample path at these time points.
The Brownian bridge increments generator uses the Brownian bridge algorithm to construct sample paths for the (free or non-free) Wiener process X, and then uses this to compute the scaled Wiener increments
X t 1 - X t 0 t 1 - t 0 , X t 2 - X t 1 t 2 - t 1 ,…, X tN - X t N-1 tN - t N-1 , XT - X tN T - tN
The example program in Section 10 shows how these increments can be used to compute a numerical solution to a stochastic differential equation (SDE) driven by a (free or non-free) Wiener process.

4 References

Glasserman P (2004) Monte Carlo Methods in Financial Engineering Springer

5 Arguments

Note: the following variable is used in the parameter descriptions: N=NTIMES, the length of the array TIMES passed to the initialization routine G05XCF.
1:   NPATHS – INTEGERInput
On entry: the number of Wiener sample paths.
Constraint: NPATHS≥1.
2:   RCORD – INTEGERInput
On entry: the order in which Normal random numbers are stored in Z and in which the generated values are returned in B.
Constraint: RCORD=1 or 2.
3:   D – INTEGERInput
On entry: the dimension of each Wiener sample path.
Constraint: D≥1.
4:   A – INTEGERInput
On entry: if A=0, a free Wiener process is created and DIFF is ignored.
If A=1, a non-free Wiener process is created where DIFF is the difference between the terminal value and the starting value of the process.
Constraint: A=0 or 1.
5:   DIFF D – REAL (KIND=nag_wp) arrayInput
On entry: the difference between the terminal value and starting value of the Wiener process. If A=0, DIFF is ignored.
6:   Z LDZ* – REAL (KIND=nag_wp) arrayInput/Output
Note: the second dimension of the array Z must be at least NPATHS if RCORD=1 and at least D×N+1-A if RCORD=2.
On entry: the Normal random numbers used to construct the sample paths.
If quasi-random numbers are used, the D×N+1-A-dimensional quasi-random points should be stored in successive rows of Z.
On exit: the Normal random numbers premultiplied by C.
7:   LDZ – INTEGERInput
On entry: the first dimension of the array Z as declared in the (sub)program from which G05XDF is called.
Constraints:
  • if RCORD=1, LDZ≥D×N+1-A;
  • if RCORD=2, LDZ≥NPATHS.
8:   C LDC* – REAL (KIND=nag_wp) arrayInput
Note: the second dimension of the array C must be at least D.
On entry: the lower triangular Cholesky factorization C such that C CT gives the covariance matrix of the Wiener process. Elements of C above the diagonal are not referenced.
9:   LDC – INTEGERInput
On entry: the first dimension of the array C as declared in the (sub)program from which G05XDF is called.
Constraint: LDC≥D.
10:   B LDB* – REAL (KIND=nag_wp) arrayOutput
Note: the second dimension of the array B must be at least NPATHS if RCORD=1 and at least D×N+1 if RCORD=2.
On exit: the scaled Wiener increments.
Let X p,i k denote the kth dimension of the ith point of the pth sample path where 1≤k≤D, 1≤i≤N+1 and 1≤p≤NPATHS. The increment X p,i k-X p,i-1 kti-t i-1 is stored at B p,k+i-1×D.
11:   LDB – INTEGERInput
On entry: the first dimension of the array B as declared in the (sub)program from which G05XDF is called.
Constraints:
  • if RCORD=1, LDB≥D×N+1;
  • if RCORD=2, LDB≥NPATHS.
12:   RCOMM* – REAL (KIND=nag_wp) arrayCommunication Array
Note: the dimension of this array is dictated by the requirements of associated functions that must have been previously called. This array must be the same array passed as argument RCOMM in the previous call to G05XCF or G05XDF.
On entry: communication array as returned by the last call to G05XCF or G05XDF. This array must not be directly modified.
13:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, RCOMM was not initialized or has been corrupted.
IFAIL=2
On entry, NPATHS=value.
Constraint: NPATHS≥1.
IFAIL=3
On entry, RCORD=value was an illegal value.
IFAIL=4
On entry, D=value.
Constraint: D≥1.
IFAIL=5
On entry, A=value.
Constraint: A=0​ or ​1.
IFAIL=6
On entry, LDZ=value and D×NTIMES+1-A=value.
Constraint: LDZ≥D×NTIMES+1-A.
On entry, LDZ=value and NPATHS=value.
Constraint: LDZ≥NPATHS.
IFAIL=7
On entry, LDC=value.
Constraint: LDC≥value.
IFAIL=8
On entry, LDB=value and D×NTIMES+1=value.
Constraint: LDB≥D×NTIMES+1.
On entry, LDB=value and NPATHS=value.
Constraint: LDB≥NPATHS.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

Not applicable.

8 Parallelism and Performance

G05XDF is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
G05XDF makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

None.

10 Example

The scaled Wiener increments produced by this routine can be used to compute numerical solutions to stochastic differential equations (SDEs) driven by (free or non-free) Wiener processes. Consider an SDE of the form
d Yt = f t,Yt dt + σ t,Yt d Xt
on the interval t 0,T where Xt t 0 ≤ t≤T is a (free or non-free) Wiener process and f and σ are suitable functions. A numerical solution to this SDE can be obtained by the Euler–Maruyama method. For any discretization t 0 < t 1 < t 2 <⋯< t N+1=T of t 0,T , set
Y t i+1 = Y ti + f ti,Y ti t i+1 - ti + σ ti,Y ti X t i+1 - X ti
for i=1,…,N so that Y t N+1 is an approximation to YT. The scaled Wiener increments produced by G05XDF can be used in the Euler–Maruyama scheme outlined above by writing
Y t i+1 = Y ti + t i+1 - ti f ti,Y ti + σ ti,Y ti X t i+1 - X ti t i+1 - ti .
The following example program uses this method to solve the SDE for geometric Brownian motion
d St = r St dt + σ St d Xt
where X is a Wiener process, and compares the results against the analytic solution
ST = S 0 exp r-σ 2/2 T + σ XT .
Quasi-random variates are used to construct the Wiener increments.

10.1 Program Text

Program Text (g05xdfe.f90)

10.2 Program Data

None.

10.3 Program Results

Program Results (g05xdfe.r)

G05 Chapter Contents
G05 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


G05XEF : NAG Library, Mark 26

G05 Chapter Contents
G05 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

G05XEF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
▸▿ 3 Description
3.1 Supported Bridge Construction Orders
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

G05XEF takes a set of input times and permutes them to specify one of several predefined Brownian bridge construction orders. The permuted times can be passed to G05XAF or G05XCF to initialize the Brownian bridge generators with the chosen bridge construction order.

2 Specification

SUBROUTINE G05XEF ( BGORD, T0, TEND, NTIMES, INTIME, NMOVE, MOVE, TIMES, IFAIL)
INTEGER | BGORD, NTIMES, NMOVE, MOVE(NMOVE), IFAIL
REAL (KIND=nag_wp) | T0, TEND, INTIME(NTIMES), TIMES(NTIMES)

3 Description

The Brownian bridge algorithm (see Glasserman (2004)) is a popular method for constructing a Wiener process at a set of discrete times, t 0 < t 1 < t 2 < ,…, < tN < T , for N≥1. To ease notation we assume that T has the index N+1 so that T=t N+1. Inherent in the algorithm is the notion of a bridge construction order which specifies the order in which the N+2 points of the Wiener process, X t 0,XT and X ti, for i=1,2,…,N, are generated. The value of X t 0 is always assumed known, and the first point to be generated is always the final time XT. Thereafter, successive points are generated iteratively by an interpolation formula, using points which were computed at previous iterations. In many cases the bridge construction order is not important, since any construction order will yield a correct process. However, in certain cases, for example when using quasi-random variates to construct the sample paths, the bridge construction order can be important.

3.1 Supported Bridge Construction Orders

G05XEF accepts as input an array of time points t 1 , t 2 ,…, tN , T at which the Wiener process is to be sampled. These time points are then permuted to construct the bridge. In all of the supported construction orders the first construction point is T which has index N+1. The remaining points are constructed by iteratively bisecting (sub-intervals of) the time indices interval 0,N+1 , as Figure 1 illustrates:
0 N+1 L 0 0 L 0 0 / 2 L 1 1 L 1 1 / 2 L 2 1 L 2 1 / 2 L 2 1 L 1 1 / 2 + ( ) L 2 1 - L 3 2 L 2 2 L 2 2 L 0 0 / 2 + ( ) L 2 2 - L 3 4 L 1 1 L 0 0 / 2 + ( ) L 1 1 - L 1 1 L 2 2 / 2 + ( ) L 1 1 - L 3 1 L 3 3
Figure 1
The time indices interval is processed in levels Li, for i=1,2,…. Each level Li contains ni points L 1 i,…,L ni i where ni≤2 i-1. The number of points at each level depends on the value of N. The points Lji for i≥1 and j=1,2,…ni are computed as follows: define L 00=N+1 and set
Lji = J+ K-J/2 where J= max Lkp : 1≤k≤np , ​ 0≤p<i ​ and ​ Lkp < Lji ​ and ​ K = min Lkp : 1≤k≤np , ​ 0≤p<i ​ and ​ Lkp > Lji
By convention the maximum of the empty set is taken to be to be zero. Figure 1 illustrates the algorithm when N+1 is a power of two. When N+1 is not a power of two, one must decide how to round the divisions by 2. For example, if one rounds down to the nearest integer, then one could get the following:
L 0 0 L 0 0 / 2 L 1 1 L 1 1 / 2 L 2 1 L 2 1 L 1 1 / 2 + ( ) L 2 1 - L 3 2 L 2 2 L 2 2 L 0 0 / 2 + ( ) L 2 2 - L 1 1 L 0 0 / 2 + ( ) L 1 1 - L 1 1 L 2 2 / 2 + ( ) L 1 1 - L 3 1 L 3 3 0 N+1
Figure 2
From the series of bisections outlined above, two ways of ordering the time indices Lji are supported. In both cases, levels are always processed from coarsest to finest (i.e., increasing i). Within a level, the time indices can either be processed left to right (i.e., increasing j) or right to left (i.e., decreasing j). For example, when processing left to right, the sequence of time indices could be generated as:
N+1 L 11 L 12 L 22 L 13 L 23 L 33 L 43 ⋯
while when processing right to left, the same sequence would be generated as:
N+1 L 11 L 22 L 12 L 43 L 33 L 23 L 13 ⋯
G05XEF therefore offers four bridge construction methods; processing either left to right or right to left, with rounding either up or down. Which method is used is controlled by the BGORD argument. For example, on the set of times
t 1 t 2 t 3 t 4 t 5 t 6 t 7 t 8 t 9 t 10 t 11 t 12 T
the Brownian bridge would be constructed in the following orders:
BGORD=1 (processing left to right, rounding down)
T t 6 t 3 t 9 t 1 t 4 t 7 t 11 t 2 t 5 t 8 t 10 t 12
BGORD=2 (processing left to right, rounding up)
T t 7 t 4 t 10 t 2 t 6 t 9 t 12 t 1 t 3 t 5 t 8 t 11
BGORD=3 (processing right to left, rounding down)
T t 6 t 9 t 3 t 11 t 7 t 4 t 1 t 12 t 10 t 8 t 5 t 2
BGORD=4 (processing right to left, rounding up)
T t 7 t 10 t 4 t 12 t 9 t 6 t 2 t 11 t 8 t 5 t 3 t 1 .
The four construction methods described above can be further modified through the use of the input array MOVE. To see the effect of this argument, suppose that an array A holds the output of G05XEF when NMOVE=0 (i.e., the bridge construction order as specified by BGORD only). Let
B = tj : j=MOVE i, i=1,2,…,NMOVE
be the array of all times identified by MOVE, and let C be the array A with all the elements in B removed, i.e.,
C = A i : A i ≠ B j , i=1,2,…,NTIMES , j=1,2,…,NMOVE .
Then the output of G05XEF when NMOVE>0 is given by
B 1 B 2 ⋯ B NMOVE C 1 C 2 ⋯ C NTIMES-NMOVE
When the Brownian bridge is used with quasi-random variates, this functionality can be used to allow specific sections of the bridge to be constructed using the lowest dimensions of the quasi-random points.

4 References

Glasserman P (2004) Monte Carlo Methods in Financial Engineering Springer

5 Arguments

1:   BGORD – INTEGERInput
On entry: the bridge construction order to use.
Constraint: BGORD=1, 2, 3 or 4.
2:   T0 – REAL (KIND=nag_wp)Input
On entry: t 0, the start value of the time interval on which the Wiener process is to be constructed.
3:   TEND – REAL (KIND=nag_wp)Input
On entry: T, the largest time at which the Wiener process is to be constructed.
4:   NTIMES – INTEGERInput
On entry: N, the number of time points in the Wiener process, excluding t 0 and T.
Constraint: NTIMES≥1.
5:   INTIME NTIMES – REAL (KIND=nag_wp) arrayInput
On entry: the time points, t 1,t 2,…,tN, at which the Wiener process is to be constructed. Note that the final time T is not included in this array.
Constraints:
  • T0<INTIME i and INTIME i<INTIME i+1, for i=1,2,…,NTIMES-1;
  • INTIME NTIMES<TEND.
6:   NMOVE – INTEGERInput
On entry: the number of elements in the array MOVE.
Constraint: 0≤NMOVE≤NTIMES.
7:   MOVE NMOVE – INTEGER arrayInput
On entry: the indices of the entries in INTIME which should be moved to the front of the TIMES array, with MOVE j=i setting the jth element of TIMES to ti. Note that i ranges from 1 to NTIMES. When NMOVE=0, MOVE is not referenced.
Constraint: 1≤MOVE j≤NTIMES, for j=1,2,…,NMOVE.
The elements of MOVE must be unique.
8:   TIMES NTIMES – REAL (KIND=nag_wp) arrayOutput
On exit: the output bridge construction order. This should be passed to G05XAF or G05XCF.
9:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, BGORD=value.
Constraint: BGORD=1, 2, 3 or 4
IFAIL=2
On entry, NTIMES=value.
Constraint: NTIMES≥1.
IFAIL=3
On entry, NMOVE=value and NTIMES=value.
Constraint: 0≤NMOVE≤NTIMES.
IFAIL=4
On entry, INTIME value=value and INTIME value=value.
Constraint: the elements in INTIME must be in increasing order.
On entry, INTIME 1=value and T0=value.
Constraint: INTIME 1>T0.
On entry, NTIMES=value, INTIME NTIMES=value and TEND=value.
Constraint: INTIME NTIMES<TEND.
IFAIL=5
On entry, MOVE value=value.
Constraint: MOVE i≥1 for all i.
On entry, MOVE value=value and NTIMES=value.
Constraint: MOVE i≤NTIMES for all i.
IFAIL=6
On entry, MOVE value and MOVE value both equal value.
Constraint: all elements in MOVE must be unique.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

Not applicable.

8 Parallelism and Performance

G05XEF is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

None.

10 Example

This example calls G05XEF, G05XAF and G05XBF to generate two sample paths of a three-dimensional free Wiener process. The array MOVE is used to ensure that a certain part of the sample path is always constructed using the lowest dimensions of the input quasi-random points. For further details on using quasi-random points with the Brownian bridge algorithm, please see Section 2.6 in the G05 Chapter Introduction.

10.1 Program Text

Program Text (g05xefe.f90)

10.2 Program Data

None.

10.3 Program Results

Program Results (g05xefe.r)

G05 Chapter Contents
G05 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


G05YJF : NAG Library, Mark 26

G05 Chapter Contents
G05 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

G05YJF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

G05YJF generates a quasi-random sequence from a Normal (Gaussian) distribution. It must be preceded by a call to one of the initialization routines G05YLF or G05YNF.

2 Specification

SUBROUTINE G05YJF ( XMEAN, STD, N, QUAS, IREF, IFAIL)
INTEGER | N, IREF(liref), IFAIL
REAL (KIND=nag_wp) | XMEAN(idim), STD(idim), QUAS(N,idim)

3 Description

G05YJF generates a quasi-random sequence from a Normal distribution by first generating a uniform quasi-random sequence which is then transformed into a Normal sequence using the inverse of the Normal CDF. The type of uniform sequence used depends on the initialization routine called and can include the low-discrepancy sequences proposed by Sobol, Faure or Niederreiter. If the initialization routine G05YNF was used then the underlying uniform sequence is first scrambled prior to being transformed (see Section 3 in G05YNF for details).

4 References

Bratley P and Fox B L (1988) Algorithm 659: implementing Sobol's quasirandom sequence generator ACM Trans. Math. Software 14(1) 88–100
Fox B L (1986) Algorithm 647: implementation and relative efficiency of quasirandom sequence generators ACM Trans. Math. Software 12(4) 362–376
Wichura (1988) Algorithm AS 241: the percentage points of the Normal distribution Appl. Statist. 37 477–484

5 Arguments

Note: the following variables are used in the parameter descriptions:
  • idim=IDIM, the number of dimensions required, see G05YLF or G05YNF;
  • liref=LIREF, the length of IREF as supplied to the initialization routines G05YLF or G05YNF.
1:   XMEAN idim – REAL (KIND=nag_wp) arrayInput
On entry: specifies, for each dimension, the mean of the Normal distribution.
2:   STD idim – REAL (KIND=nag_wp) arrayInput
On entry: specifies, for each dimension, the standard deviation of the Normal distribution.
Constraint: STD i≥0.0, for i=1,2,…,idim.
3:   N – INTEGERInput
On entry: the number of quasi-random numbers required.
Constraint: N≥0 and N+previous number of generated values≤231-1.
4:   QUAS Nidim – REAL (KIND=nag_wp) arrayOutput
On exit: contains the N quasi-random numbers of dimension idim
5:   IREF liref – INTEGER arrayCommunication Array
On entry: contains information on the current state of the sequence.
On exit: contains updated information on the state of the sequence.
6:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, incorrect initialization has been detected.
IFAIL=2
On entry, N<1.
IFAIL=3
A standard deviation is negative.
IFAIL=4
There have been too many calls to the generator.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

Not applicable.

8 Parallelism and Performance

G05YJF is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
G05YJF makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.
The Sobol, Sobol (A659) and Niederreiter quasi-random number generators in G05YJF have been parallelized, but require quite large problem sizes to see any significant performance gain. The Faure generator is serial.

9 Further Comments

None.

10 Example

This example calls G05YLF to initialize the generator and then G05YJF to generate a sequence of five four-dimensional variates.

10.1 Program Text

Program Text (g05yjfe.f90)

10.2 Program Data

Program Data (g05yjfe.d)

10.3 Program Results

Program Results (g05yjfe.r)

G05 Chapter Contents
G05 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


G05YKF : NAG Library, Mark 26

G05 Chapter Contents
G05 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

G05YKF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

G05YKF generates a quasi-random sequence from a log-normal distribution. It must be preceded by a call to one of the initialization routines G05YLF or G05YNF.

2 Specification

SUBROUTINE G05YKF ( XMEAN, STD, N, QUAS, IREF, IFAIL)
INTEGER | N, IREF(liref), IFAIL
REAL (KIND=nag_wp) | XMEAN(idim), STD(idim), QUAS(N,idim)

3 Description

G05YKF generates a quasi-random sequence from a log-normal distribution by first generating a uniform quasi-random sequence which is then transformed into a log-normal sequence using the exponential of the inverse of the Normal CDF. The type of uniform sequence used depends on the initialization routine called and can include the low-discrepancy sequences proposed by Sobol, Faure or Niederreiter. If the initialization routine G05YNF was used then the underlying uniform sequence is first scrambled prior to being transformed (see Section 3 in G05YNF for details).

4 References

Bratley P and Fox B L (1988) Algorithm 659: implementing Sobol's quasirandom sequence generator ACM Trans. Math. Software 14(1) 88–100
Fox B L (1986) Algorithm 647: implementation and relative efficiency of quasirandom sequence generators ACM Trans. Math. Software 12(4) 362–376
Wichura (1988) Algorithm AS 241: the percentage points of the Normal distribution Appl. Statist. 37 477–484

5 Arguments

Note: the following variables are used in the parameter descriptions:
  • idim=IDIM, the number of dimensions required, see G05YLF or G05YNF;
  • liref=LIREF, the length of IREF as supplied to the initialization routines G05YLF or G05YNF.
1:   XMEAN idim – REAL (KIND=nag_wp) arrayInput
On entry: specifies, for each dimension, the mean of the underlying Normal distribution.
Constraint: XMEAN i ≤ - log X02AMF -10.0× STD i , for i=1,2,…,idim.
2:   STD idim – REAL (KIND=nag_wp) arrayInput
On entry: specifies, for each dimension, the standard deviation of the underlying Normal distribution.
Constraint: STD i≥0.0, for i=1,2,…,idim.
3:   N – INTEGERInput
On entry: the number of quasi-random numbers required.
Constraint: N≥0 and N+previous number of generated values≤231-1.
4:   QUAS Nidim – REAL (KIND=nag_wp) arrayOutput
On exit: contains the N quasi-random numbers of dimension idim.
5:   IREF liref – INTEGER arrayCommunication Array
On entry: contains information on the current state of the sequence.
On exit: contains updated information on the state of the sequence.
6:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, incorrect initialization has been detected.
IFAIL=2
On entry, N<1.
IFAIL=3
On entry,at least one element of XMEAN is too large.
IFAIL=4
There have been too many calls to the generator.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

Not applicable.

8 Parallelism and Performance

G05YKF is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
G05YKF makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.
The Sobol, Sobol (A659) and Niederreiter quasi-random number generators in g05ykc have been parallelized, but require quite large problem sizes to see any significant performance gain. The Faure generator is serial.

9 Further Comments

None.

10 Example

This example calls G05YLF to initialize the generator and then G05YKF to produce a sequence of five four-dimensional quasi-random numbers variates.

10.1 Program Text

Program Text (g05ykfe.f90)

10.2 Program Data

Program Data (g05ykfe.d)

10.3 Program Results

Program Results (g05ykfe.r)

G05 Chapter Contents
G05 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


G05YLF : NAG Library, Mark 26

G05 Chapter Contents
G05 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

G05YLF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
10 Example

1 Purpose

G05YLF initializes a quasi-random generator prior to calling G05YJF, G05YKF or G05YMF.

2 Specification

SUBROUTINE G05YLF ( GENID, IDIM, IREF, LIREF, ISKIP, IFAIL)
INTEGER GENID, IDIM, IREF(LIREF), LIREF, ISKIP, IFAIL

3 Description

G05YLF selects a quasi-random number generator through the input value of GENID and initializes the IREF communication array for use by the routines G05YJF, G05YKF or G05YMF.
One of three types of quasi-random generator may be chosen, allowing the low-discrepancy sequences proposed by Sobol, Faure or Niederreiter to be generated.
Two sets of Sobol sequences are supplied, the first, is based on the work of Joe and Kuo (2008). The second, referred to in the documentation as "Sobol (A659)", is based on Algorithm 659 of Bratley and Fox (1988) with the extension to 1111 dimensions proposed by Joe and Kuo (2003). Both sets of Sobol sequences should satisfy the so-called Property A, up to 1111 dimensions, but the first set should have better two-dimensional projections than those produced using Algorithm 659.

4 References

Bratley P and Fox B L (1988) Algorithm 659: implementing Sobol's quasirandom sequence generator ACM Trans. Math. Software 14(1) 88–100
Fox B L (1986) Algorithm 647: implementation and relative efficiency of quasirandom sequence generators ACM Trans. Math. Software 12(4) 362–376
Joe S and Kuo F Y (2003) Remark on Algorithm 659: implementing Sobol's quasirandom sequence generator ACM Trans. Math. Software (TOMS) 29 49–57
Joe S and Kuo F Y (2008) Constructing Sobol sequences with better two-dimensional projections SIAM J. Sci. Comput. 30 2635–2654

5 Arguments

1:   GENID – INTEGERInput
On entry: must identify the quasi-random generator to use.
GENID=1
Sobol generator.
GENID=2
Sobol (A659) generator.
GENID=3
Niederreiter generator.
GENID=4
Faure generator.
Constraint: GENID=1, 2, 3 or 4.
2:   IDIM – INTEGERInput
On entry: the number of dimensions required.
Constraints:
  • if GENID=1, 1≤IDIM≤10000;
  • if GENID=2, 1≤IDIM≤1111;
  • if GENID=3, 1≤IDIM≤318;
  • if GENID=4, 1≤IDIM≤40.
3:   IREF LIREF – INTEGER arrayCommunication Array
On exit: contains initialization information for use by the generator routines G05YJF, G05YKF and G05YMF. IREF must not be altered in any way between initialization and calls of the generator routines.
4:   LIREF – INTEGERInput
On entry: the dimension of the array IREF as declared in the (sub)program from which G05YLF is called.
Constraints:
  • if GENID=1, 2 or 3, LIREF≥32×IDIM+7;
  • if GENID=4, LIREF≥407.
5:   ISKIP – INTEGERInput
On entry: the number of terms of the sequence to skip on initialization for the Sobol and Niederreiter generators. If GENID=4, ISKIP is ignored.
Constraint: if GENID=1, 2 or 3, 0≤ISKIP≤230.
6:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, GENID=value.
Constraint: GENID=1, 2, 3 or 4.
IFAIL=2
On entry, IDIM=value.
Constraint: 1≤IDIM≤value.
IFAIL=4
On entry, LIREF is too small: LIREF=value, minimum length is value.
IFAIL=5
On entry, ISKIP<0 or ISKIP is too large: ISKIP=value, maximum value is value.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

Not applicable.

8 Parallelism and Performance

G05YLF is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The primitive polynomials and direction numbers used for the Sobol generator (GENID=1) were calculated by Joe and Kuo (2008) using the search critera D 6.

10 Example

See Section 10 in G05YMF.
G05 Chapter Contents
G05 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


G05YMF : NAG Library, Mark 26

G05 Chapter Contents
G05 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

G05YMF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

G05YMF generates a uniformly distributed low-discrepancy sequence as proposed by Sobol, Faure or Niederreiter. It must be preceded by a call to one of the initialization routines G05YLF or G05YNF.

2 Specification

SUBROUTINE G05YMF ( N, RCORD, QUAS, LDQUAS, IREF, IFAIL)
INTEGER | N, RCORD, LDQUAS, IREF(liref), IFAIL
REAL (KIND=nag_wp) | QUAS(LDQUAS,tdquas)

3 Description

Low discrepancy (quasi-random) sequences are used in numerical integration, simulation and optimization. Like pseudorandom numbers they are uniformly distributed but they are not statistically independent, rather they are designed to give more even distribution in multidimensional space (uniformity). Therefore they are often more efficient than pseudorandom numbers in multidimensional Monte–Carlo methods.
G05YMF generates a set of points x 1,x 2,…,xN with high uniformity in the S-dimensional unit cube IS=0,1 S.
Let G be a subset of IS and define the counting function SN G as the number of points xi∈G. For each x=x 1,x 2,…,xS∈IS, let Gx be the rectangular S-dimensional region
G x = 0, x 1 × 0, x 2 ×⋯× 0, x S
with volume x 1,x 2,…,xS. Then one measure of the uniformity of the points x 1,x 2,…,xN is the discrepancy:
DN* x 1,x 2,…,xN = sup x∈IS SN Gx - N x 1 , x 2 , … , xS .
which has the form
DN*x 1,x 2,…,xN≤CS log⁡N S+O log⁡N S-1  for all  N≥2.
The principal aim in the construction of low-discrepancy sequences is to find sequences of points in IS with a bound of this form where the constant CS is as small as possible.
The type of low-discrepancy sequence generated by G05YMF depends on the initialization routine called and can include those proposed by Sobol, Faure or Niederreiter. If the initialization routine G05YNF was used then the sequence will be scrambled (see Section 3 in G05YNF for details).

4 References

Bratley P and Fox B L (1988) Algorithm 659: implementing Sobol's quasirandom sequence generator ACM Trans. Math. Software 14(1) 88–100
Fox B L (1986) Algorithm 647: implementation and relative efficiency of quasirandom sequence generators ACM Trans. Math. Software 12(4) 362–376

5 Arguments

Note: the following variables are used in the parameter descriptions:
  • idim=IDIM, the number of dimensions required, see G05YLF or G05YNF
  • liref=LIREF, the length of IREF as supplied to the initialization routine G05YLF or G05YNF
  • tdquas=N if RCORD=1; otherwise tdquas=idim
1:   N – INTEGERInput
On entry: the number of quasi-random numbers required.
Constraint: N≥0 and N+previous number of generated values≤231-1.
2:   RCORD – INTEGERInput
On entry: the order in which the generated values are returned.
Constraint: RCORD=1 or 2.
3:   QUAS LDQUAStdquas – REAL (KIND=nag_wp) arrayOutput
On exit: contains the N quasi-random numbers of dimension idim.
If RCORD=1, QUAS ij holds the jth value for the ith dimension.
If RCORD=2, QUAS ij holds the ith value for the jth dimension.
4:   LDQUAS – INTEGERInput
On entry: the first dimension of the array QUAS as declared in the (sub)program from which G05YMF is called.
Constraints:
  • if RCORD=1, LDQUAS≥idim;
  • if RCORD=2, LDQUAS≥N.
5:   IREF liref – INTEGER arrayCommunication Array
On entry: contains information on the current state of the sequence.
On exit: contains updated information on the state of the sequence.
6:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, N=value.
Constraint: N≥0.
On entry, value of N would result in too many calls to the generator: N=value, generator has previously been called value times.
IFAIL=2
On entry, RCORD=value.
Constraint: RCORD=1 or 2.
IFAIL=4
On entry, LDQUAS=value, idim=value.
Constraint: if RCORD=1, LDQUAS≥idim.
On entry, LDQUAS=value and N=value.
Constraint: if RCORD=2, LDQUAS≥N.
IFAIL=5
On entry, IREF has either not been initialized or has been corrupted.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

Not applicable.

8 Parallelism and Performance

G05YMF is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.
The Sobol, Sobol (A659) and Niederreiter quasi-random number generators in G05YMF have been parallelized, but require quite large problem sizes to see any significant performance gain. Parallelism is only enabled when RCORD=2. The Faure generator is serial.

9 Further Comments

None.

10 Example

This example calls G05YLF and G05YMF to estimate the value of the integral
∫01 ⋯ ∫01 ∏ i=1 s 4 xi-2 d x 1, d x 2, …, d xs = 1 .
In this example the number of dimensions S is set to 8.

10.1 Program Text

Program Text (g05ymfe.f90)

10.2 Program Data

Program Data (g05ymfe.d)

10.3 Program Results

Program Results (g05ymfe.r)

G05 Chapter Contents
G05 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


G05YNF : NAG Library, Mark 26

G05 Chapter Contents
G05 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

G05YNF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

G05YNF initializes a scrambled quasi-random generator prior to calling G05YJF, G05YKF or G05YMF. It must be preceded by a call to one of the pseudorandom initialization routines G05KFF or G05KGF.

2 Specification

SUBROUTINE G05YNF ( GENID, STYPE, IDIM, IREF, LIREF, ISKIP, NSDIGI, STATE, IFAIL)
INTEGER GENID, STYPE, IDIM, IREF(LIREF), LIREF, ISKIP, NSDIGI, STATE(*), IFAIL

3 Description

G05YNF selects a quasi-random number generator through the input value of GENID, a method of scrambling through the input value of STYPE and initializes the IREF communication array for use in the routines G05YJF, G05YKF or G05YMF.
Scrambled quasi-random sequences are an extension of standard quasi-random sequences that attempt to eliminate the bias inherent in a quasi-random sequence whilst retaining the low-discrepancy properties. The use of a scrambled sequence allows error estimation of Monte–Carlo results by performing a number of iterates and computing the variance of the results.
This implementation of scrambled quasi-random sequences is based on TOMS Algorithm 823 and details can be found in the accompanying paper, Hong and Hickernell (2003). Three methods of scrambling are supplied; the first a restricted form of Owen's scrambling (Owen (1995)), the second based on the method of Faure and Tezuka (2000) and the last method combines the first two.
Scrambled versions of the Niederreiter sequence and two sets of Sobol sequences are provided. The first Sobol sequence is obtained using GENID=1. The first 10000 direction numbers for this sequence are based on the work of Joe and Kuo (2008). For dimensions greater than 10000 the direction numbers are randomly generated using the pseudorandom generator specified in STATE (see Jäckel (2002) for details). The second Sobol sequence is obtained using GENID=2 and referred to in the documentation as ‘Sobol (A659)’. The first 1111 direction numbers for this sequence are based on Algorithm 659 of Bratley and Fox (1988) with the extension proposed by Joe and Kuo (2003). For dimensions greater than 1111 the direction numbers are once again randomly generated. The Niederreiter sequence is obtained by setting GENID=3.

4 References

Bratley P and Fox B L (1988) Algorithm 659: implementing Sobol's quasirandom sequence generator ACM Trans. Math. Software 14(1) 88–100
Faure H and Tezuka S (2000) Another random scrambling of digital (t,s)-sequences Monte Carlo and Quasi-Monte Carlo Methods Springer-Verlag, Berlin, Germany (eds K T Fang, F J Hickernell and H Niederreiter)
Hong H S and Hickernell F J (2003) Algorithm 823: implementing scrambled digital sequences ACM Trans. Math. Software 29:2 95–109
Jäckel P (2002) Monte Carlo Methods in Finance Wiley Finance Series, John Wiley and Sons, England
Joe S and Kuo F Y (2003) Remark on Algorithm 659: implementing Sobol's quasirandom sequence generator ACM Trans. Math. Software (TOMS) 29 49–57
Joe S and Kuo F Y (2008) Constructing Sobol sequences with better two-dimensional projections SIAM J. Sci. Comput. 30 2635–2654
Niederreiter H (1988) Low-discrepancy and low dispersion sequences Journal of Number Theory 30 51–70
Owen A B (1995) Randomly permuted (t,m,s)-nets and (t,s)-sequences Monte Carlo and Quasi-Monte Carlo Methods in Scientific Computing, Lecture Notes in Statistics 106 Springer-Verlag, New York, NY 299–317 (eds H Niederreiter and P J-S Shiue)

5 Arguments

1:   GENID – INTEGERInput
On entry: must identify the quasi-random generator to use.
GENID=1
Sobol generator.
GENID=2
Sobol (A659) generator.
GENID=3
Niederreiter generator.
Constraint: GENID=1, 2 or 3.
2:   STYPE – INTEGERInput
On entry: must identify the scrambling method to use.
STYPE=0
No scrambling. This is equivalent to calling G05YLF.
STYPE=1
Owen like scrambling.
STYPE=2
Faure–Tezuka scrambling.
STYPE=3
Owen and Faure–Tezuka scrambling.
Constraint: STYPE=0, 1, 2 or 3.
3:   IDIM – INTEGERInput
On entry: the number of dimensions required.
Constraints:
  • if GENID=1, 1≤IDIM≤50000;
  • if GENID=2, 1≤IDIM≤50000;
  • if GENID=3, 1≤IDIM≤318.
4:   IREF LIREF – INTEGER arrayCommunication Array
On exit: contains initialization information for use by the generator routines G05YJF, G05YKF and G05YMF. IREF must not be altered in any way between initialization and calls of the generator routines.
5:   LIREF – INTEGERInput
On entry: the dimension of the array IREF as declared in the (sub)program from which G05YNF is called.
Constraint: LIREF≥32×IDIM+7.
6:   ISKIP – INTEGERInput
On entry: the number of terms of the sequence to skip on initialization for the Sobol and Niederreiter generators.
Constraint: 0≤ISKIP≤230.
7:   NSDIGI – INTEGERInput
On entry: controls the number of digits (bits) to scramble when GENID=1 or 2, otherwise NSDIGI is ignored. If NSDIGI<1 or NSDIGI>30 then all the digits are scrambled.
8:   STATE* – INTEGER arrayCommunication Array
Note: the actual argument supplied must be the array STATE supplied to the initialization routines G05KFF or G05KGF.
On entry: contains information on the selected base generator and its current state.
On exit: contains updated information on the state of the generator.
9:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, GENID=value.
Constraint: 1≤GENID≤value.
IFAIL=2
On entry, STYPE=value.
Constraint: 0≤STYPE≤3.
IFAIL=3
On entry, IDIM=value.
Constraint: 1≤IDIM≤value.
IFAIL=5
On entry, LIREF=value.
Constraint: LIREF≥32×IDIM+7.
IFAIL=6
On entry, ISKIP=value.
Constraint: 0≤ISKIP≤230.
IFAIL=8
On entry, STATE vector has been corrupted or not initialized.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

Not applicable.

8 Parallelism and Performance

G05YNF is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The additional computational cost in using a scrambled quasi-random sequence over a non-scrambled one comes entirely during the initialization. Once G05YNF has been called the computational cost of generating a scrambled sequence and a non-scrambled one is identical.

10 Example

This example calls G05KFF, G05YMF and G05YNF to estimate the value of the integral
∫01 ⋯ ∫01 ∏ i=1 s 4 xi-2 d x 1, d x 2, …, d xs = 1 ,
where s, the number of dimensions, is set to 8.

10.1 Program Text

Program Text (g05ynfe.f90)

10.2 Program Data

Program Data (g05ynfe.d)

10.3 Program Results

Program Results (g05ynfe.r)

G05 Chapter Contents
G05 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


G05ZMF : NAG Library, Mark 26

G05 Chapter Contents
G05 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

G05ZMF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

G05ZMF performs the setup required in order to simulate stationary Gaussian random fields in one dimension, for a user-defined variogram, using the circulant embedding method. Specifically, the eigenvalues of the extended covariance matrix (or embedding matrix) are calculated, and their square roots output, for use by G05ZPF, which simulates the random field.

2 Specification

SUBROUTINE G05ZMF ( NS, XMIN, XMAX, MAXM, VAR, COV1, PAD, ICORR, LAM, XX, M, APPROX, RHO, ICOUNT, EIG, IUSER, RUSER, IFAIL)
INTEGER | NS, MAXM, PAD, ICORR, M, APPROX, ICOUNT, IUSER(*), IFAIL
REAL (KIND=nag_wp) | XMIN, XMAX, VAR, LAM(MAXM), XX(NS), RHO, EIG(3), RUSER(*)
EXTERNAL | COV1

3 Description

A one-dimensional random field Z x in ℝ is a function which is random at every point x∈ℝ, so Z x is a random variable for each x. The random field has a mean function μ x=𝔼 Z x and a symmetric positive semidefinite covariance function C x,y=𝔼 Z x-μ xZ y-μ y. Z x is a Gaussian random field if for any choice of n∈ℕ and x 1,…,xn∈ℝ, the random vector Z x 1,…,Z xn T follows a multivariate Normal distribution, which would have a mean vector μ~ with entries μ~i=μ xi and a covariance matrix C~ with entries C~ij=C xi,xj. A Gaussian random field Z x is stationary if μ x is constant for all x∈ℝ and C x,y=C x+a,y+a for all x,y,a∈ℝ and hence we can express the covariance function C x,y as a function γ of one variable: C x,y=γ x-y. γ is known as a variogram (or more correctly, a semivariogram) and includes the multiplicative factor σ 2 representing the variance such that γ 0=σ 2.
The routines G05ZMF and G05ZPF are used to simulate a one-dimensional stationary Gaussian random field, with mean function zero and variogram γ x, over an interval xmin,xmax, using an equally spaced set of N points on the interval. The problem reduces to sampling a Normal random vector X of size N, with mean vector zero and a symmetric Toeplitz covariance matrix A. Since A is in general expensive to factorize, a technique known as the circulant embedding method is used. A is embedded into a larger, symmetric circulant matrix B of size M≥2 N-1, which can now be factorized as B=WΛ W*=R*R, where W is the Fourier matrix (W* is the complex conjugate of W), Λ is the diagonal matrix containing the eigenvalues of B and R=Λ 12W*. B is known as the embedding matrix. The eigenvalues can be calculated by performing a discrete Fourier transform of the first row (or column) of B and multiplying by M, and so only the first row (or column) of B is needed – the whole matrix does not need to be formed.
As long as all of the values of Λ are non-negative (i.e., B is positive semidefinite), B is a covariance matrix for a random vector Y, two samples of which can now be simulated from the real and imaginary parts of R*U+iV, where U and V have elements from the standard Normal distribution. Since R*U+iV=W Λ 12 U+iV, this calculation can be done using a discrete Fourier transform of the vector Λ 12 U+iV. Two samples of the random vector X can now be recovered by taking the first N elements of each sample of Y – because the original covariance matrix A is embedded in B, X will have the correct distribution.
If B is not positive semidefinite, larger embedding matrices B can be tried; however if the size of the matrix would have to be larger than MAXM, an approximation procedure is used. We write Λ=Λ++Λ-, where Λ+ and Λ- contain the non-negative and negative eigenvalues of B respectively. Then B is replaced by ρ B+ where B+=W Λ+W* and ρ∈0,1 is a scaling factor. The error ε in approximating the distribution of the random field is given by
ε= 1-ρ 2 trace⁡Λ + ρ 2 trace⁡Λ- M .
Three choices for ρ are available, and are determined by the input argument ICORR:
  • setting ICORR=0 sets
    ρ= trace⁡Λ trace⁡Λ+ ,
  • setting ICORR=1 sets
    ρ= trace⁡Λ trace⁡Λ+ ,
  • setting ICORR=2 sets ρ=1.
G05ZMF finds a suitable positive semidefinite embedding matrix B and outputs its size, M, and the square roots of its eigenvalues in LAM. If approximation is used, information regarding the accuracy of the approximation is output. Note that only the first row (or column) of B is actually formed and stored.

4 References

Dietrich C R and Newsam G N (1997) Fast and exact simulation of stationary Gaussian processes through circulant embedding of the covariance matrix SIAM J. Sci. Comput. 18 1088–1107
Schlather M (1999) Introduction to positive definite functions and to unconditional simulation of random fields Technical Report ST 99–10 Lancaster University
Wood A T A and Chan G (1994) Simulation of stationary Gaussian processes in 0,1 d Journal of Computational and Graphical Statistics 3(4) 409–432

5 Arguments

1:   NS – INTEGERInput
On entry: the number of sample points to be generated in realizations of the random field.
Constraint: NS≥1.
2:   XMIN – REAL (KIND=nag_wp)Input
On entry: the lower bound for the interval over which the random field is to be simulated.
Constraint: XMIN<XMAX.
3:   XMAX – REAL (KIND=nag_wp)Input
On entry: the upper bound for the interval over which the random field is to be simulated.
Constraint: XMIN<XMAX.
4:   MAXM – INTEGERInput
On entry: the maximum size of the circulant matrix to use. For example, if the embedding matrix is to be allowed to double in size three times before the approximation procedure is used, then choose MAXM = 2 k+2 where k = 1+ log 2 NS-1 .
Suggested value: 2 k+2​ where ​ k = 1+ log 2 NS-1 .
Constraint: MAXM ≥ 2 k , where k is the smallest integer satisfying 2 k ≥ 2 NS-1 .
5:   VAR – REAL (KIND=nag_wp)Input
On entry: the multiplicative factor σ 2 of the variogram γ x.
Constraint: VAR≥0.0.
6:   COV1 – SUBROUTINE, supplied by the user.External Procedure
COV1 must evaluate the variogram γ x, without the multiplicative factor σ 2, for all x≥0. The value returned in GAMMA is multiplied internally by VAR.
The specification of COV1 is:
SUBROUTINE COV1 ( X, GAMMA, IUSER, RUSER)
INTEGER | IUSER(*)
REAL (KIND=nag_wp) | X, GAMMA, RUSER(*)
1:   X – REAL (KIND=nag_wp)Input
On entry: the value x at which the variogram γ x is to be evaluated.
2:   GAMMA – REAL (KIND=nag_wp)Output
On exit: the value of the variogram γ x σ 2 .
3:   IUSER* – INTEGER arrayUser Workspace
4:   RUSER* – REAL (KIND=nag_wp) arrayUser Workspace
COV1 is called with the arguments IUSER and RUSER as supplied to G05ZMF. You are free to use the arrays IUSER and RUSER to supply information to COV1 as an alternative to using COMMON global variables.
COV1 must either be a module subprogram USEd by, or declared as EXTERNAL in, the (sub)program from which G05ZMF is called. Arguments denoted as Input must not be changed by this procedure.
7:   PAD – INTEGERInput
On entry: determines whether the embedding matrix is padded with zeros, or padded with values of the variogram. The choice of padding may affect how big the embedding matrix must be in order to be positive semidefinite.
PAD=0
The embedding matrix is padded with zeros.
PAD=1
The embedding matrix is padded with values of the variogram.
Suggested value: PAD=1.
Constraint: PAD=0 or 1.
8:   ICORR – INTEGERInput
On entry: determines which approximation to implement if required, as described in Section 3.
Suggested value: ICORR=0.
Constraint: ICORR=0, 1 or 2.
9:   LAM MAXM – REAL (KIND=nag_wp) arrayOutput
On exit: contains the square roots of the eigenvalues of the embedding matrix.
10:   XX NS – REAL (KIND=nag_wp) arrayOutput
On exit: the points at which values of the random field will be output.
11:   M – INTEGEROutput
On exit: the size of the embedding matrix.
12:   APPROX – INTEGEROutput
On exit: indicates whether approximation was used.
APPROX=0
No approximation was used.
APPROX=1
Approximation was used.
13:   RHO – REAL (KIND=nag_wp)Output
On exit: indicates the scaling of the covariance matrix. RHO=1.0 unless approximation was used with ICORR=0 or 1.
14:   ICOUNT – INTEGEROutput
On exit: indicates the number of negative eigenvalues in the embedding matrix which have had to be set to zero.
15:   EIG 3 – REAL (KIND=nag_wp) arrayOutput
On exit: indicates information about the negative eigenvalues in the embedding matrix which have had to be set to zero. EIG 1 contains the smallest eigenvalue, EIG 2 contains the sum of the squares of the negative eigenvalues, and EIG 3 contains the sum of the absolute values of the negative eigenvalues.
16:   IUSER* – INTEGER arrayUser Workspace
17:   RUSER* – REAL (KIND=nag_wp) arrayUser Workspace
IUSER and RUSER are not used by G05ZMF, but are passed directly to COV1 and may be used to pass information to this routine as an alternative to using COMMON global variables.
18:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, NS=value.
Constraint: NS≥1.
IFAIL=2
On entry, XMIN=value and XMAX=value.
Constraint: XMIN<XMAX.
IFAIL=4
On entry, MAXM=value.
Constraint: the minimum calculated value for MAXM is value.
Where the minimum calculated value is given by 2 k , where k is the smallest integer satisfying 2 k ≥ 2 NS-1 .
IFAIL=5
On entry, VAR=value.
Constraint: VAR≥0.0.
IFAIL=7
On entry, PAD=value.
Constraint: PAD=0 or 1.
IFAIL=8
On entry, ICORR=value.
Constraint: ICORR=0, 1 or 2.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

If on exit APPROX=1, see the comments in Section 3 regarding the quality of approximation; increase the value of MAXM to attempt to avoid approximation.

8 Parallelism and Performance

G05ZMF is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
G05ZMF makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

None.

10 Example

This example calls G05ZMF to calculate the eigenvalues of the embedding matrix for 8 sample points of a random field characterized by the symmetric stable variogram:
γ x = σ 2 exp - x′ ν ,
where x′=xℓ, and ℓ and ν are parameters.
It should be noted that the symmetric stable variogram is one of the pre-defined variograms available in G05ZNF. It is used here purely for illustrative purposes.

10.1 Program Text

Program Text (g05zmfe.f90)

10.2 Program Data

Program Data (g05zmfe.d)

10.3 Program Results

Program Results (g05zmfe.r)

G05 Chapter Contents
G05 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


G05ZNF : NAG Library, Mark 26

G05 Chapter Contents
G05 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

G05ZNF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

G05ZNF performs the setup required in order to simulate stationary Gaussian random fields in one dimension, for a preset variogram, using the circulant embedding method. Specifically, the eigenvalues of the extended covariance matrix (or embedding matrix) are calculated, and their square roots output, for use by G05ZPF, which simulates the random field.

2 Specification

SUBROUTINE G05ZNF ( NS, XMIN, XMAX, MAXM, VAR, ICOV1, NP, PARAMS, PAD, ICORR, LAM, XX, M, APPROX, RHO, ICOUNT, EIG, IFAIL)
INTEGER | NS, MAXM, ICOV1, NP, PAD, ICORR, M, APPROX, ICOUNT, IFAIL
REAL (KIND=nag_wp) | XMIN, XMAX, VAR, PARAMS(NP), LAM(MAXM), XX(NS), RHO, EIG(3)

3 Description

A one-dimensional random field Z x in ℝ is a function which is random at every point x∈ℝ, so Z x is a random variable for each x. The random field has a mean function μ x=𝔼 Z x and a symmetric positive semidefinite covariance function C x,y=𝔼 Z x-μ xZ y-μ y. Z x is a Gaussian random field if for any choice of n∈ℕ and x 1,…,xn∈ℝ, the random vector Z x 1,…,Z xn T follows a multivariate Normal distribution, which would have a mean vector μ~ with entries μ~i=μ xi and a covariance matrix C~ with entries C~ij=C xi,xj. A Gaussian random field Z x is stationary if μ x is constant for all x∈ℝ and C x,y=C x+a,y+a for all x,y,a∈ℝ and hence we can express the covariance function C x,y as a function γ of one variable: C x,y=γ x-y. γ is known as a variogram (or more correctly, a semivariogram) and includes the multiplicative factor σ 2 representing the variance such that γ 0=σ 2.
The routines G05ZNF and G05ZPF are used to simulate a one-dimensional stationary Gaussian random field, with mean function zero and variogram γ x, over an interval xmin,xmax, using an equally spaced set of N points. The problem reduces to sampling a Normal random vector X of size N, with mean vector zero and a symmetric Toeplitz covariance matrix A. Since A is in general expensive to factorize, a technique known as the circulant embedding method is used. A is embedded into a larger, symmetric circulant matrix B of size M≥2 N-1, which can now be factorized as B=WΛ W*=R*R, where W is the Fourier matrix (W* is the complex conjugate of W), Λ is the diagonal matrix containing the eigenvalues of B and R=Λ 12W*. B is known as the embedding matrix. The eigenvalues can be calculated by performing a discrete Fourier transform of the first row (or column) of B and multiplying by M, and so only the first row (or column) of B is needed – the whole matrix does not need to be formed.
As long as all of the values of Λ are non-negative (i.e., B is positive semidefinite), B is a covariance matrix for a random vector Y, two samples of which can now be simulated from the real and imaginary parts of R*U+iV, where U and V have elements from the standard Normal distribution. Since R*U+iV=W Λ 12 U+iV, this calculation can be done using a discrete Fourier transform of the vector Λ 12 U+iV. Two samples of the random vector X can now be recovered by taking the first N elements of each sample of Y – because the original covariance matrix A is embedded in B, X will have the correct distribution.
If B is not positive semidefinite, larger embedding matrices B can be tried; however if the size of the matrix would have to be larger than MAXM, an approximation procedure is used. We write Λ=Λ++Λ-, where Λ+ and Λ- contain the non-negative and negative eigenvalues of B respectively. Then B is replaced by ρ B+ where B+=W Λ+W* and ρ∈0,1 is a scaling factor. The error ε in approximating the distribution of the random field is given by
ε= 1-ρ 2 trace⁡Λ + ρ 2 trace⁡Λ- M .
Three choices for ρ are available, and are determined by the input argument ICORR:
  • setting ICORR=0 sets
    ρ= trace⁡Λ trace⁡Λ+ ,
  • setting ICORR=1 sets
    ρ= trace⁡Λ trace⁡Λ+ ,
  • setting ICORR=2 sets ρ=1.
G05ZNF finds a suitable positive semidefinite embedding matrix B and outputs its size, M, and the square roots of its eigenvalues in LAM. If approximation is used, information regarding the accuracy of the approximation is output. Note that only the first row (or column) of B is actually formed and stored.

4 References

Dietrich C R and Newsam G N (1997) Fast and exact simulation of stationary Gaussian processes through circulant embedding of the covariance matrix SIAM J. Sci. Comput. 18 1088–1107
Schlather M (1999) Introduction to positive definite functions and to unconditional simulation of random fields Technical Report ST 99–10 Lancaster University
Wood A T A and Chan G (1997) Algorithm AS 312: An Algorithm for Simulating Stationary Gaussian Random Fields Journal of the Royal Statistical Society, Series C (Applied Statistics) (Volume 46) 1 171–181

5 Arguments

1:   NS – INTEGERInput
On entry: the number of sample points to be generated in realizations of the random field.
Constraint: NS≥1.
2:   XMIN – REAL (KIND=nag_wp)Input
On entry: the lower bound for the interval over which the random field is to be simulated. Note that if ICOV1=14 (for simulating fractional Brownian motion), XMIN is not referenced and the lower bound for the interval is set to zero.
Constraint: if ICOV1≠14, XMIN<XMAX.
3:   XMAX – REAL (KIND=nag_wp)Input
On entry: the upper bound for the interval over which the random field is to be simulated. Note that if ICOV1=14 (for simulating fractional Brownian motion), the lower bound for the interval is set to zero and so XMAX is required to be greater than zero.
Constraints:
  • if ICOV1≠14, XMIN<XMAX;
  • if ICOV1=14, XMAX>0.0.
4:   MAXM – INTEGERInput
On entry: the maximum size of the circulant matrix to use. For example, if the embedding matrix is to be allowed to double in size three times before the approximation procedure is used, then choose MAXM = 2 k+2 where k = 1+ log 2 NS-1 .
Suggested value: 2 k+2​ where ​ k = 1+ log 2 NS-1 .
Constraint: MAXM ≥ 2 k , where k is the smallest integer satisfying 2 k ≥ 2 NS-1 .
5:   VAR – REAL (KIND=nag_wp)Input
On entry: the multiplicative factor σ 2 of the variogram γ x.
Constraint: VAR≥0.0.
6:   ICOV1 – INTEGERInput
On entry: determines which of the preset variograms to use. The choices are given below. Note that x′=x ℓ, where ℓ is the correlation length and is a parameter for most of the variograms, and σ 2 is the variance specified by VAR.
ICOV1=1
Symmetric stable variogram
γ x = σ 2 exp - x′ ν ,
where
  • ℓ=PARAMS 1, ℓ>0,
  • ν=PARAMS 2, 0≤ν≤2.
ICOV1=2
Cauchy variogram
γ x = σ 2 1+ x′ 2 -ν ,
where
  • ℓ=PARAMS 1, ℓ>0,
  • ν=PARAMS 2, ν>0.
ICOV1=3
Differential variogram with compact support
γ x = σ 2 1+8 x′+25 x′2+32 x′3 1-x′8, x′<1, 0, x′≥1,
where
  • ℓ=PARAMS 1, ℓ>0.
ICOV1=4
Exponential variogram
γ x=σ 2 exp-x′,
where
  • ℓ=PARAMS 1, ℓ>0.
ICOV1=5
Gaussian variogram
γ x=σ 2 exp-x′2,
where
  • ℓ=PARAMS 1, ℓ>0.
ICOV1=6
Nugget variogram
γ x= σ 2, x=0, 0, x≠0.
No parameters need be set for this value of ICOV1.
ICOV1=7
Spherical variogram
γ x= σ 2 1-1.5 x′+0.5 x′3, x′<1, 0, x′≥1,
where
  • ℓ=PARAMS 1, ℓ>0.
ICOV1=8
Bessel variogram
γ x=σ 2 2 ν Γ ν+1 Jν x′x′ν,
where
  • Jν(·) is the Bessel function of the first kind,
  • ℓ=PARAMS 1, ℓ>0,
  • ν=PARAMS 2, ν≥-0.5.
ICOV1=9
Hole effect variogram
γ x=σ 2 sin x′x′,
where
  • ℓ=PARAMS 1, ℓ>0.
ICOV1=10
Whittle-Matérn variogram
γ x=σ 2 2 1-νx′ν Kν x′Γ ν,
where
  • Kν(·) is the modified Bessel function of the second kind,
  • ℓ=PARAMS 1, ℓ>0,
  • ν=PARAMS 2, ν>0.
ICOV1=11
Continuously parameterised variogram with compact support
γ x= σ 2 2 1-νx′ν Kν x′Γ ν 1+8 x′′+25 x′′2+32 x′′3 1-x′′8, x′′<1, 0, x′′≥1,
where
  • x′′ = x′s ,
  • Kν(·) is the modified Bessel function of the second kind,
  • ℓ=PARAMS 1, ℓ>0,
  • s=PARAMS 2, s>0 (second correlation length),
  • ν=PARAMS 3, ν>0.
ICOV1=12
Generalized hyperbolic distribution variogram
γ x=σ 2 δ 2+x′2 λ 2 δλ Kλ κδ Kλ κ δ 2+x′2 12,
where
  • Kλ(·) is the modified Bessel function of the second kind,
  • ℓ=PARAMS 1, ℓ>0,
  • λ=PARAMS 2, no constraint on λ
  • δ=PARAMS 3, δ>0,
  • κ=PARAMS 4, κ>0.
ICOV1=13
Cosine variogram
γ x=σ 2 cos x′,
where
  • ℓ=PARAMS 1, ℓ>0.
ICOV1=14
Used for simulating fractional Brownian motion BH t. Fractional Brownian motion itself is not a stationary Gaussian random field, but its increments X~i=BH ti-BH t i-1 can be simulated in the same way as a stationary random field. The variogram for the so-called ‘increment process’ is
C X~ti,X~tj=γ~x=δ 2 H 2 xδ-1 2 H+xδ+1 2 H-2 xδ 2 H,
where
  • x=tj-ti,
  • H=PARAMS 1, 0<H<1, H is the Hurst parameter,
  • δ=PARAMS 2, δ>0, normally δ=ti-t i-1 is the (fixed) stepsize.
We scale the increments to set γ 0=1; let X i=X~i δ-H, then
C X ti,X tj = γ x = 12 xδ - 1 2 H + xδ + 1 2 H - 2 xδ 2 H .
The increments X i can then be simulated using G05ZPF, then multiplied by δH to obtain the original increments X~i for the fractional Brownian motion.
Constraint: ICOV1=1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13 or 14.
7:   NP – INTEGERInput
On entry: the number of parameters to be set. Different variograms need a different number of parameters.
ICOV1=6
NP must be set to 0.
ICOV1=3, 4, 5, 7, 9 or 13
NP must be set to 1.
ICOV1=1, 2, 8, 10 or 14
NP must be set to 2.
ICOV1=11
NP must be set to 3.
ICOV1=12
NP must be set to 4.
8:   PARAMS NP – REAL (KIND=nag_wp) arrayInput
On entry: the parameters set for the variogram.
Constraint: see ICOV1 for a description of the individual parameter constraints.
9:   PAD – INTEGERInput
On entry: determines whether the embedding matrix is padded with zeros, or padded with values of the variogram. The choice of padding may affect how big the embedding matrix must be in order to be positive semidefinite.
PAD=0
The embedding matrix is padded with zeros.
PAD=1
The embedding matrix is padded with values of the variogram.
Suggested value: PAD=1.
Constraint: PAD=0 or 1.
10:   ICORR – INTEGERInput
On entry: determines which approximation to implement if required, as described in Section 3.
Suggested value: ICORR=0.
Constraint: ICORR=0, 1 or 2.
11:   LAM MAXM – REAL (KIND=nag_wp) arrayOutput
On exit: contains the square roots of the eigenvalues of the embedding matrix.
12:   XX NS – REAL (KIND=nag_wp) arrayOutput
On exit: the points at which values of the random field will be output.
13:   M – INTEGEROutput
On exit: the size of the embedding matrix.
14:   APPROX – INTEGEROutput
On exit: indicates whether approximation was used.
APPROX=0
No approximation was used.
APPROX=1
Approximation was used.
15:   RHO – REAL (KIND=nag_wp)Output
On exit: indicates the scaling of the covariance matrix. RHO=1.0 unless approximation was used with ICORR=0 or 1.
16:   ICOUNT – INTEGEROutput
On exit: indicates the number of negative eigenvalues in the embedding matrix which have had to be set to zero.
17:   EIG 3 – REAL (KIND=nag_wp) arrayOutput
On exit: indicates information about the negative eigenvalues in the embedding matrix which have had to be set to zero. EIG 1 contains the smallest eigenvalue, EIG 2 contains the sum of the squares of the negative eigenvalues, and EIG 3 contains the sum of the absolute values of the negative eigenvalues.
18:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, NS=value.
Constraint: NS≥1.
IFAIL=2
On entry, ICOV1≠14, XMIN=value and XMAX=value.
Constraint: XMIN<XMAX.
IFAIL=3
On entry, ICOV1=14 and XMAX=value.
Constraint: XMAX>0.0.
IFAIL=4
On entry, MAXM=value.
Constraint: the minimum calculated value for MAXM is value.
Where the minimum calculated value is given by 2 k , where k is the smallest integer satisfying 2 k ≥ 2 NS-1 .
IFAIL=5
On entry, VAR=value.
Constraint: VAR≥0.0.
IFAIL=6
On entry, ICOV1=value.
Constraint: ICOV1≥1 and ICOV1≤14.
IFAIL=7
On entry, NP=value.
Constraint: for ICOV1=value, NP=value.
IFAIL=8
On entry, PARAMS value=value.
Constraint: dependent on ICOV1.
IFAIL=9
On entry, PAD=value.
Constraint: PAD=0 or 1.
IFAIL=10
On entry, ICORR=value.
Constraint: ICORR=0, 1 or 2.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

If on exit APPROX=1, see the comments in Section 3 regarding the quality of approximation; increase the value of MAXM to attempt to avoid approximation.

8 Parallelism and Performance

G05ZNF is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
G05ZNF makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

None.

10 Example

This example calls G05ZNF to calculate the eigenvalues of the embedding matrix for 8 sample points of a random field characterized by the symmetric stable variogram (ICOV1=1).

10.1 Program Text

Program Text (g05znfe.f90)

10.2 Program Data

Program Data (g05znfe.d)

10.3 Program Results

Program Results (g05znfe.r)

G05 Chapter Contents
G05 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


G05ZPF : NAG Library, Mark 26

G05 Chapter Contents
G05 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

G05ZPF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

G05ZPF produces realizations of a stationary Gaussian random field in one dimension, using the circulant embedding method. The square roots of the eigenvalues of the extended covariance matrix (or embedding matrix) need to be input, and can be calculated using G05ZMF or G05ZNF.

2 Specification

SUBROUTINE G05ZPF ( NS, S, M, LAM, RHO, STATE, Z, IFAIL)
INTEGER | NS, S, M, STATE(*), IFAIL
REAL (KIND=nag_wp) | LAM(M), RHO, Z(NS,S)

3 Description

A one-dimensional random field Z x in ℝ is a function which is random at every point x∈ℝ, so Z x is a random variable for each x. The random field has a mean function μ x=𝔼 Z x and a symmetric non-negative definite covariance function C x,y=𝔼 Z x-μ xZ y-μ y. Z x is a Gaussian random field if for any choice of n∈ℕ and x 1,…,xn∈ℝ, the random vector Z x 1,…,Z xn T follows a multivariate Normal distribution, which would have a mean vector μ~ with entries μ~i=μ xi and a covariance matrix C~ with entries C~ij=C xi,xj. A Gaussian random field Z x is stationary if μ x is constant for all x∈ℝ and C x,y=C x+a,y+a for all x,y,a∈ℝ and hence we can express the covariance function C x,y as a function γ of one variable: C x,y=γ x-y. γ is known as a variogram (or more correctly, a semivariogram) and includes the multiplicative factor σ 2 representing the variance such that γ 0=σ 2.
The routines G05ZMF or G05ZNF, along with G05ZPF, are used to simulate a one-dimensional stationary Gaussian random field, with mean function zero and variogram γ x, over an interval xmin,xmax, using an equally spaced set of N points. The problem reduces to sampling a Normal random vector X of size N, with mean vector zero and a symmetric Toeplitz covariance matrix A. Since A is in general expensive to factorize, a technique known as the circulant embedding method is used. A is embedded into a larger, symmetric circulant matrix B of size M≥2 N-1, which can now be factorized as B=WΛ W*=R*R, where W is the Fourier matrix (W* is the complex conjugate of W), Λ is the diagonal matrix containing the eigenvalues of B and R=Λ 12W*. B is known as the embedding matrix. The eigenvalues can be calculated by performing a discrete Fourier transform of the first row (or column) of B and multiplying by M, and so only the first row (or column) of B is needed – the whole matrix does not need to be formed.
As long as all of the values of Λ are non-negative (i.e., B is non-negative definite), B is a covariance matrix for a random vector Y, two samples of which can now be simulated from the real and imaginary parts of R*U+iV, where U and V have elements from the standard Normal distribution. Since R*U+iV=W Λ 12 U+iV, this calculation can be done using a discrete Fourier transform of the vector Λ 12 U+iV. Two samples of the random vector X can now be recovered by taking the first N elements of each sample of Y – because the original covariance matrix A is embedded in B, X will have the correct distribution.
If B is not non-negative definite, larger embedding matrices B can be tried; however if the size of the matrix would have to be larger than MAXM, an approximation procedure is used. See the documentation of G05ZMF or G05ZNF for details of the approximation procedure.
G05ZPF takes the square roots of the eigenvalues of the embedding matrix B, and its size M, as input and outputs S realizations of the random field in Z.
One of the initialization routines G05KFF (for a repeatable sequence if computed sequentially) or G05KGF (for a non-repeatable sequence) must be called prior to the first call to G05ZPF.

4 References

Dietrich C R and Newsam G N (1997) Fast and exact simulation of stationary Gaussian processes through circulant embedding of the covariance matrix SIAM J. Sci. Comput. 18 1088–1107
Schlather M (1999) Introduction to positive definite functions and to unconditional simulation of random fields Technical Report ST 99–10 Lancaster University
Wood A T A and Chan G (1994) Simulation of stationary Gaussian processes in 0,1 d Journal of Computational and Graphical Statistics 3(4) 409–432

5 Arguments

1:   NS – INTEGERInput
On entry: the number of sample points to be generated in realizations of the random field. This must be the same value as supplied to G05ZMF or G05ZNF when calculating the eigenvalues of the embedding matrix.
Constraint: NS≥1.
2:   S – INTEGERInput
On entry: S, the number of realizations of the random field to simulate.
Constraint: S≥1.
3:   M – INTEGERInput
On entry: M, the size of the embedding matrix, as returned by G05ZMF or G05ZNF.
Constraint: M≥max 1,2 NS-1.
4:   LAM M – REAL (KIND=nag_wp) arrayInput
On entry: must contain the square roots of the eigenvalues of the embedding matrix, as returned by G05ZMF or G05ZNF.
Constraint: LAM i≥0,i=1,2,…,M.
5:   RHO – REAL (KIND=nag_wp)Input
On entry: indicates the scaling of the covariance matrix, as returned by G05ZMF or G05ZNF.
Constraint: 0.0<RHO≤1.0.
6:   STATE* – INTEGER arrayCommunication Array
Note: the actual argument supplied must be the array STATE supplied to the initialization routines G05KFF or G05KGF.
On entry: contains information on the selected base generator and its current state.
On exit: contains updated information on the state of the generator.
7:   Z NSS – REAL (KIND=nag_wp) arrayOutput
On exit: contains the realizations of the random field. The jth realization, for the NS sample points, is stored in Z ij, for i=1,2,…,NS. The sample points are as returned in XX by G05ZMF or G05ZNF.
8:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, NS=value.
Constraint: NS≥1.
IFAIL=2
On entry, S=value.
Constraint: S≥1.
IFAIL=3
On entry, M=value and NS=value.
Constraint: M≥max 1,2×NS-1.
IFAIL=4
On entry, at least one element of LAM was negative.
Constraint: all elements of LAM must be non-negative.
IFAIL=5
On entry, RHO=value.
Constraint: 0.0≤RHO≤1.0.
IFAIL=6
On entry, STATE vector has been corrupted or not initialized.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

Not applicable.

8 Parallelism and Performance

G05ZPF is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
G05ZPF makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

Because samples are generated in pairs, calling this routine k times, with S=s, say, will generate a different sequence of numbers than calling the routine once with S=k⁢s, unless s is even.

10 Example

This example calls G05ZPF to generate 5 realizations of a random field on 8 sample points using eigenvalues calculated by G05ZNF for a symmetric stable variogram.

10.1 Program Text

Program Text (g05zpfe.f90)

10.2 Program Data

Program Data (g05zpfe.d)

10.3 Program Results

Program Results (g05zpfe.r)

G05 Chapter Contents
G05 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


G05ZQF : NAG Library, Mark 26

G05 Chapter Contents
G05 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

G05ZQF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

G05ZQF performs the setup required in order to simulate stationary Gaussian random fields in two dimensions, for a user-defined variogram, using the circulant embedding method. Specifically, the eigenvalues of the extended covariance matrix (or embedding matrix) are calculated, and their square roots output, for use by G05ZSF, which simulates the random field.

2 Specification

SUBROUTINE G05ZQF ( NS, XMIN, XMAX, YMIN, YMAX, MAXM, VAR, COV2, EVEN, PAD, ICORR, LAM, XX, YY, M, APPROX, RHO, ICOUNT, EIG, IUSER, RUSER, IFAIL)
INTEGER | NS(2), MAXM(2), EVEN, PAD, ICORR, M(2), APPROX, ICOUNT, IUSER(*), IFAIL
REAL (KIND=nag_wp) | XMIN, XMAX, YMIN, YMAX, VAR, LAM(MAXM(1)*MAXM(2)), XX(NS(1)), YY(NS(2)), RHO, EIG(3), RUSER(*)
EXTERNAL | COV2

3 Description

A two-dimensional random field Z x in ℝ 2 is a function which is random at every point x∈ℝ 2, so Z x is a random variable for each x. The random field has a mean function μ x=𝔼 Z x and a symmetric positive semidefinite covariance function C x,y=𝔼 Z x-μ xZ y-μ y. Z x is a Gaussian random field if for any choice of n∈ℕ and x 1,…,xn∈ℝ 2, the random vector Z x 1,…,Z xn T follows a multivariate Normal distribution, which would have a mean vector μ~ with entries μ~i=μ xi and a covariance matrix C~ with entries C~ij=C xi,xj. A Gaussian random field Z x is stationary if μ x is constant for all x∈ℝ 2 and C x,y=C x+a,y+a for all x,y,a∈ℝ 2 and hence we can express the covariance function C x,y as a function γ of one variable: C x,y=γ x-y. γ is known as a variogram (or more correctly, a semivariogram) and includes the multiplicative factor σ 2 representing the variance such that γ 0=σ 2.
The routines G05ZQF and G05ZSF are used to simulate a two-dimensional stationary Gaussian random field, with mean function zero and variogram γ x, over a domain xmin,xmax×ymin,ymax, using an equally spaced set of N 1×N 2 points; N 1 points in the x-direction and N 2 points in the y-direction. The problem reduces to sampling a Normal random vector X of size N 1×N 2, with mean vector zero and a symmetric covariance matrix A, which is an N 2 by N 2 block Toeplitz matrix with Toeplitz blocks of size N 1 by N 1. Since A is in general expensive to factorize, a technique known as the circulant embedding method is used. A is embedded into a larger, symmetric matrix B, which is an M 2 by M 2 block circulant matrix with circulant blocks of size M 1 by M 1, where M 1≥2 N 1-1 and M 2≥2 N 2-1. B can now be factorized as B=WΛ W*=R*R, where W is the two-dimensional Fourier matrix (W* is the complex conjugate of W), Λ is the diagonal matrix containing the eigenvalues of B and R=Λ 12W*. B is known as the embedding matrix. The eigenvalues can be calculated by performing a discrete Fourier transform of the first row (or column) of B and multiplying by M 1×M 2, and so only the first row (or column) of B is needed – the whole matrix does not need to be formed.
The symmetry of A as a block matrix, and the symmetry of each block of A, depends on whether the variogram γ is even or not. γ is even in its first coordinate if γ-x 1,x 2 T=γ x 1,x 2 T, even in its second coordinate if γ x 1,-x 2 T=γ x 1,x 2 T, and even if it is even in both coordinates (in two dimensions it is impossible for γ to be even in one coordinate and uneven in the other). If γ is even then A is a symmetric block matrix and has symmetric blocks; if γ is uneven then A is not a symmetric block matrix and has non-symmetric blocks. In the uneven case, M 1 and M 2 are set to be odd in order to guarantee symmetry in B.
As long as all of the values of Λ are non-negative (i.e., B is positive semidefinite), B is a covariance matrix for a random vector Y which has M 2 blocks of size M 1. Two samples of Y can now be simulated from the real and imaginary parts of R*U+iV, where U and V have elements from the standard Normal distribution. Since R*U+iV=W Λ 12 U+iV, this calculation can be done using a discrete Fourier transform of the vector Λ 12 U+iV. Two samples of the random vector X can now be recovered by taking the first N 1 elements of the first N 2 blocks of each sample of Y – because the original covariance matrix A is embedded in B, X will have the correct distribution.
If B is not positive semidefinite, larger embedding matrices B can be tried; however if the size of the matrix would have to be larger than MAXM, an approximation procedure is used. We write Λ=Λ++Λ-, where Λ+ and Λ- contain the non-negative and negative eigenvalues of B respectively. Then B is replaced by ρ B+ where B+=W Λ+W* and ρ∈0,1 is a scaling factor. The error ε in approximating the distribution of the random field is given by
ε= 1-ρ 2 trace⁡Λ + ρ 2 trace⁡Λ- M .
Three choices for ρ are available, and are determined by the input argument ICORR:
  • setting ICORR=0 sets
    ρ= trace⁡Λ trace⁡Λ+ ,
  • setting ICORR=1 sets
    ρ= trace⁡Λ trace⁡Λ+ ,
  • setting ICORR=2 sets ρ=1.
G05ZQF finds a suitable positive semidefinite embedding matrix B and outputs its sizes in the vector M and the square roots of its eigenvalues in LAM. If approximation is used, information regarding the accuracy of the approximation is output. Note that only the first row (or column) of B is actually formed and stored.

4 References

Dietrich C R and Newsam G N (1997) Fast and exact simulation of stationary Gaussian processes through circulant embedding of the covariance matrix SIAM J. Sci. Comput. 18 1088–1107
Schlather M (1999) Introduction to positive definite functions and to unconditional simulation of random fields Technical Report ST 99–10 Lancaster University
Wood A T A and Chan G (1994) Simulation of stationary Gaussian processes in 0,1 d Journal of Computational and Graphical Statistics 3(4) 409–432

5 Arguments

1:   NS 2 – INTEGER arrayInput
On entry: the number of sample points to use in each direction, with NS 1 sample points in the x-direction, N 1 and NS 2 sample points in the y-direction, N 2. The total number of sample points on the grid is therefore NS 1×NS 2.
Constraints:
  • NS 1≥1;
  • NS 2≥1.
2:   XMIN – REAL (KIND=nag_wp)Input
On entry: the lower bound for the x-coordinate, for the region in which the random field is to be simulated.
Constraint: XMIN<XMAX.
3:   XMAX – REAL (KIND=nag_wp)Input
On entry: the upper bound for the x-coordinate, for the region in which the random field is to be simulated.
Constraint: XMIN<XMAX.
4:   YMIN – REAL (KIND=nag_wp)Input
On entry: the lower bound for the y-coordinate, for the region in which the random field is to be simulated.
Constraint: YMIN<YMAX.
5:   YMAX – REAL (KIND=nag_wp)Input
On entry: the upper bound for the y-coordinate, for the region in which the random field is to be simulated.
Constraint: YMIN<YMAX.
6:   MAXM 2 – INTEGER arrayInput
On entry: determines the maximum size of the circulant matrix to use – a maximum of MAXM 1 elements in the x-direction, and a maximum of MAXM 2 elements in the y-direction. The maximum size of the circulant matrix is thus MAXM 1×MAXM 2.
Constraints:
  • if EVEN=1, MAXM i ≥ 2 k , where k is the smallest integer satisfying 2 k ≥ 2 NS i-1 , for i=1,2 ;
  • if EVEN=0, MAXM i ≥ 3 k , where k is the smallest integer satisfying 3 k ≥ 2 NS i-1 , for i=1,2 .
7:   VAR – REAL (KIND=nag_wp)Input
On entry: the multiplicative factor σ 2 of the variogram γ x.
Constraint: VAR≥0.0.
8:   COV2 – SUBROUTINE, supplied by the user.External Procedure
COV2 must evaluate the variogram γ x for all x if EVEN=0, and for all x with non-negative entries if EVEN=1. The value returned in GAMMA is multiplied internally by VAR.
The specification of COV2 is:
SUBROUTINE COV2 ( X, Y, GAMMA, IUSER, RUSER)
INTEGER | IUSER(*)
REAL (KIND=nag_wp) | X, Y, GAMMA, RUSER(*)
1:   X – REAL (KIND=nag_wp)Input
On entry: the coordinate x at which the variogram γ x is to be evaluated.
2:   Y – REAL (KIND=nag_wp)Input
On entry: the coordinate y at which the variogram γ x is to be evaluated.
3:   GAMMA – REAL (KIND=nag_wp)Output
On exit: the value of the variogram γ x.
4:   IUSER* – INTEGER arrayUser Workspace
5:   RUSER* – REAL (KIND=nag_wp) arrayUser Workspace
COV2 is called with the arguments IUSER and RUSER as supplied to G05ZQF. You are free to use the arrays IUSER and RUSER to supply information to COV2 as an alternative to using COMMON global variables.
COV2 must either be a module subprogram USEd by, or declared as EXTERNAL in, the (sub)program from which G05ZQF is called. Arguments denoted as Input must not be changed by this procedure.
9:   EVEN – INTEGERInput
On entry: indicates whether the covariance function supplied is even or uneven.
EVEN=0
The covariance function is uneven.
EVEN=1
The covariance function is even.
Constraint: EVEN=0 or 1.
10:   PAD – INTEGERInput
On entry: determines whether the embedding matrix is padded with zeros, or padded with values of the variogram. The choice of padding may affect how big the embedding matrix must be in order to be positive semidefinite.
PAD=0
The embedding matrix is padded with zeros.
PAD=1
The embedding matrix is padded with values of the variogram.
Suggested value: PAD=1.
Constraint: PAD=0 or 1.
11:   ICORR – INTEGERInput
On entry: determines which approximation to implement if required, as described in Section 3.
Suggested value: ICORR=0.
Constraint: ICORR=0, 1 or 2.
12:   LAM MAXM 1×MAXM 2 – REAL (KIND=nag_wp) arrayOutput
On exit: contains the square roots of the eigenvalues of the embedding matrix.
13:   XX NS 1 – REAL (KIND=nag_wp) arrayOutput
On exit: the points of the x-coordinates at which values of the random field will be output.
14:   YY NS 2 – REAL (KIND=nag_wp) arrayOutput
On exit: the points of the y-coordinates at which values of the random field will be output.
15:   M 2 – INTEGER arrayOutput
On exit: M 1 contains M 1, the size of the circulant blocks and M 2 contains M 2, the number of blocks, resulting in a final square matrix of size M 1×M 2.
16:   APPROX – INTEGEROutput
On exit: indicates whether approximation was used.
APPROX=0
No approximation was used.
APPROX=1
Approximation was used.
17:   RHO – REAL (KIND=nag_wp)Output
On exit: indicates the scaling of the covariance matrix. RHO=1.0 unless approximation was used with ICORR=0 or 1.
18:   ICOUNT – INTEGEROutput
On exit: indicates the number of negative eigenvalues in the embedding matrix which have had to be set to zero.
19:   EIG 3 – REAL (KIND=nag_wp) arrayOutput
On exit: indicates information about the negative eigenvalues in the embedding matrix which have had to be set to zero. EIG 1 contains the smallest eigenvalue, EIG 2 contains the sum of the squares of the negative eigenvalues, and EIG 3 contains the sum of the absolute values of the negative eigenvalues.
20:   IUSER* – INTEGER arrayUser Workspace
21:   RUSER* – REAL (KIND=nag_wp) arrayUser Workspace
IUSER and RUSER are not used by G05ZQF, but are passed directly to COV2 and may be used to pass information to this routine as an alternative to using COMMON global variables.
22:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, NS=value,value.
Constraint: NS 1≥1, NS 2≥1.
IFAIL=2
On entry, XMIN=value and XMAX=value.
Constraint: XMIN<XMAX.
IFAIL=4
On entry, YMIN=value and YMAX=value.
Constraint: YMIN<YMAX.
IFAIL=6
On entry, MAXM=value,value.
Constraint: the minima for MAXM are value,value.
Where, if EVEN=1, the minimum calculated value of MAXM i is given by 2 k , where k is the smallest integer satisfying 2 k ≥ 2 NS i-1 , and if EVEN=0, the minimum calculated value of MAXM i is given by 3 k , where k is the smallest integer satisfying 3 k ≥ 2 NS i-1 , for i=1,2.
IFAIL=7
On entry, VAR=value.
Constraint: VAR≥0.0.
IFAIL=9
On entry, EVEN=value.
Constraint: EVEN=0 or 1.
IFAIL=10
On entry, PAD=value.
Constraint: PAD=0 or 1.
IFAIL=11
On entry, ICORR=value.
Constraint: ICORR=0, 1 or 2.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

If on exit APPROX=1, see the comments in Section 3 regarding the quality of approximation; increase the values in MAXM to attempt to avoid approximation.

8 Parallelism and Performance

G05ZQF is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
G05ZQF makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

None.

10 Example

This example calls G05ZQF to calculate the eigenvalues of the embedding matrix for 25 sample points on a 5 by 5 grid of a two-dimensional random field characterized by the symmetric stable variogram:
γ x = σ 2 exp - x′ ν ,
where x′=x ℓ 1+y ℓ 2, and ℓ 1, ℓ 2 and ν are parameters.
It should be noted that the symmetric stable variogram is one of the pre-defined variograms available in G05ZRF. It is used here purely for illustrative purposes.

10.1 Program Text

Program Text (g05zqfe.f90)

10.2 Program Data

Program Data (g05zqfe.d)

10.3 Program Results

Program Results (g05zqfe.r)

G05 Chapter Contents
G05 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


G05ZRF : NAG Library, Mark 26

G05 Chapter Contents

G05 Chapter Introduction

NAG Library Manual

NAG Library Routine Document

G05ZRF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose

2 Specification

3 Description

4 References

5 Arguments

6 Error Indicators and Warnings

7 Accuracy

8 Parallelism and Performance

9 Further Comments

▸▿ 10 Example

10.1 Program Text

10.2 Program Data

10.3 Program Results

1 Purpose

G05ZRF performs the setup required in order to simulate stationary Gaussian random fields in two dimensions, for a preset variogram, using the circulant embedding method. Specifically, the eigenvalues of the extended covariance matrix (or embedding matrix) are calculated, and their square roots output, for use by G05ZSF, which simulates the random field.

2 Specification

SUBROUTINE G05ZRF (

NS, XMIN, XMAX, YMIN, YMAX, MAXM, VAR, ICOV2, NORM, NP, PARAMS, PAD, ICORR, LAM, XX, YY, M, APPROX, RHO, ICOUNT, EIG, IFAIL)

INTEGER

NS(2), MAXM(2), ICOV2, NORM, NP, PAD, ICORR, M(2), APPROX, ICOUNT, IFAIL

REAL (KIND=nag_wp)

XMIN, XMAX, YMIN, YMAX, VAR, PARAMS(NP), LAM(MAXM(1)*MAXM(2)), XX(NS(1)), YY(NS(2)), RHO, EIG(3)

3 Description

A two-dimensional random field Z x in ℝ 2 is a function which is random at every point x∈ℝ 2, so Z x is a random variable for each x. The random field has a mean function μ x=𝔼 Z x and a symmetric positive semidefinite covariance function C x,y=𝔼 Z x-μ xZ y-μ y. Z x is a Gaussian random field if for any choice of n∈ℕ and x 1,…,xn∈ℝ 2, the random vector Z x 1,…,Z xn T follows a multivariate Normal distribution, which would have a mean vector μ~ with entries μ~i=μ xi and a covariance matrix C~ with entries C~ij=C xi,xj. A Gaussian random field Z x is stationary if μ x is constant for all x∈ℝ 2 and C x,y=C x+a,y+a for all x,y,a∈ℝ 2 and hence we can express the covariance function C x,y as a function γ of one variable: C x,y=γ x-y. γ is known as a variogram (or more correctly, a semivariogram) and includes the multiplicative factor σ 2 representing the variance such that γ 0=σ 2.

The routines G05ZRF and G05ZSF are used to simulate a two-dimensional stationary Gaussian random field, with mean function zero and variogram γ x, over a domain xmin,xmax×ymin,ymax, using an equally spaced set of N 1×N 2 points; N 1 points in the x-direction and N 2 points in the y-direction. The problem reduces to sampling a Gaussian random vector X of size N 1×N 2, with mean vector zero and a symmetric covariance matrix A, which is an N 2 by N 2 block Toeplitz matrix with Toeplitz blocks of size N 1 by N 1. Since A is in general expensive to factorize, a technique known as the circulant embedding method is used. A is embedded into a larger, symmetric matrix B, which is an M 2 by M 2 block circulant matrix with circulant blocks of size M 1 by M 1, where M 1≥2 N 1-1 and M 2≥2 N 2-1. B can now be factorized as B=WΛ W*=R*R, where W is the two-dimensional Fourier matrix (W* is the complex conjugate of W), Λ is the diagonal matrix containing the eigenvalues of B and R=Λ 12W*. B is known as the embedding matrix. The eigenvalues can be calculated by performing a discrete Fourier transform of the first row (or column) of B and multiplying by M 1×M 2, and so only the first row (or column) of B is needed – the whole matrix does not need to be formed.

As long as all of the values of Λ are non-negative (i.e., B is positive semidefinite), B is a covariance matrix for a random vector Y which has M 2 blocks of size M 1. Two samples of Y can now be simulated from the real and imaginary parts of R*U+iV, where U and V have elements from the standard Normal distribution. Since R*U+iV=W Λ 12 U+iV, this calculation can be done using a discrete Fourier transform of the vector Λ 12 U+iV. Two samples of the random vector X can now be recovered by taking the first N 1 elements of the first N 2 blocks of each sample of Y – because the original covariance matrix A is embedded in B, X will have the correct distribution.

If B is not positive semidefinite, larger embedding matrices B can be tried; however if the size of the matrix would have to be larger than MAXM, an approximation procedure is used. We write Λ=Λ++Λ-, where Λ+ and Λ- contain the non-negative and negative eigenvalues of B respectively. Then B is replaced by ρ B+ where B+=W Λ+W* and ρ∈0,1 is a scaling factor. The error ε in approximating the distribution of the random field is given by

ε= 1-ρ 2 trace⁡Λ + ρ 2 trace⁡Λ- M .

Three choices for ρ are available, and are determined by the input argument ICORR:

setting ICORR=0 sets

ρ= trace⁡Λ trace⁡Λ+ ,

setting ICORR=1 sets

ρ= trace⁡Λ trace⁡Λ+ ,

setting ICORR=2 sets ρ=1.

G05ZRF finds a suitable positive semidefinite embedding matrix B and outputs its sizes in the vector M and the square roots of its eigenvalues in LAM. If approximation is used, information regarding the accuracy of the approximation is output. Note that only the first row (or column) of B is actually formed and stored.

4 References

Dietrich C R and Newsam G N (1997) Fast and exact simulation of stationary Gaussian processes through circulant embedding of the covariance matrix SIAM J. Sci. Comput. 18 1088–1107

Schlather M (1999) Introduction to positive definite functions and to unconditional simulation of random fields Technical Report ST 99–10 Lancaster University

Wood A T A and Chan G (1997) Algorithm AS 312: An Algorithm for Simulating Stationary Gaussian Random Fields Journal of the Royal Statistical Society, Series C (Applied Statistics) (Volume 46) 1 171–181

5 Arguments

1:   NS 2 – INTEGER arrayInput

On entry: the number of sample points to use in each direction, with NS 1 sample points in the x-direction, N 1 and NS 2 sample points in the y-direction, N 2. The total number of sample points on the grid is therefore NS 1×NS 2.

Constraints:

NS 1≥1;

NS 2≥1.

2:   XMIN – REAL (KIND=nag_wp)Input

On entry: the lower bound for the x-coordinate, for the region in which the random field is to be simulated.

Constraint: XMIN<XMAX.

3:   XMAX – REAL (KIND=nag_wp)Input

On entry: the upper bound for the x-coordinate, for the region in which the random field is to be simulated.

Constraint: XMIN<XMAX.

4:   YMIN – REAL (KIND=nag_wp)Input

On entry: the lower bound for the y-coordinate, for the region in which the random field is to be simulated.

Constraint: YMIN<YMAX.

5:   YMAX – REAL (KIND=nag_wp)Input

On entry: the upper bound for the y-coordinate, for the region in which the random field is to be simulated.

Constraint: YMIN<YMAX.

6:   MAXM 2 – INTEGER arrayInput

On entry: determines the maximum size of the circulant matrix to use – a maximum of MAXM 1 elements in the x-direction, and a maximum of MAXM 2 elements in the y-direction. The maximum size of the circulant matrix is thus MAXM 1×MAXM 2.

Constraint: MAXM i ≥ 2 k , where k is the smallest integer satisfying 2 k ≥ 2 NS i-1 , for i=1,2.

7:   VAR – REAL (KIND=nag_wp)Input

On entry: the multiplicative factor σ 2 of the variogram γ x.

Constraint: VAR≥0.0.

8:   ICOV2 – INTEGERInput

On entry: determines which of the preset variograms to use. The choices are given below. Note that x′ = x ℓ 1 , y ℓ 2 , where ℓ 1 and ℓ 2 are correlation lengths in the x and y directions respectively and are parameters for most of the variograms, and σ 2 is the variance specified by VAR.
ICOV2=1

Symmetric stable variogram

γ x = σ 2 exp - x′ ν ,

where

ℓ 1=PARAMS 1, ℓ 1>0,

ℓ 2=PARAMS 2, ℓ 2>0,

ν=PARAMS 3, 0<ν≤2.

ICOV2=2

Cauchy variogram

γ x = σ 2 1 + x′ 2 -ν ,

where

ℓ 1=PARAMS 1, ℓ 1>0,

ℓ 2=PARAMS 2, ℓ 2>0,

ν=PARAMS 3, ν>0.

ICOV2=3

Differential variogram with compact support

γ x = σ 2 1 + 8 x′ + 25 x′ 2 + 32 x′ 3 1 - x′ 8 , x′<1 , 0 , x′ ≥ 1 ,

where

ℓ 1=PARAMS 1, ℓ 1>0,

ℓ 2=PARAMS 2, ℓ 2>0.

ICOV2=4

Exponential variogram

γ x = σ 2 exp-x′ ,

where

ℓ 1=PARAMS 1, ℓ 1>0,

ℓ 2=PARAMS 2, ℓ 2>0.

ICOV2=5

Gaussian variogram

γ x = σ 2 exp -x′ 2 ,

where

ℓ 1=PARAMS 1, ℓ 1>0,

ℓ 2=PARAMS 2, ℓ 2>0.

ICOV2=6

Nugget variogram

γ x = σ 2, x=0, 0, x≠0.

No parameters need be set for this value of ICOV2.

ICOV2=7

Spherical variogram

γ x = σ 2 1 - 1.5 x′ + 0.5 x′ 3 , x′ < 1 , 0, x′ ≥ 1 ,

where

ℓ 1=PARAMS 1, ℓ 1>0,

ℓ 2=PARAMS 2, ℓ 2>0.

ICOV2=8

Bessel variogram

γ x = σ 2 2 ν Γ ν+1 Jν x′ x′ ν ,

where

Jν(·) is the Bessel function of the first kind,

ℓ 1=PARAMS 1, ℓ 1>0,

ℓ 2=PARAMS 2, ℓ 2>0,

ν=PARAMS 3, ν≥0.

ICOV2=9

Hole effect variogram

γ x = σ 2 sin x′ x′ ,

where

ℓ 1=PARAMS 1, ℓ 1>0,

ℓ 2=PARAMS 2, ℓ 2>0.

ICOV2=10

Whittle-Matérn variogram

γ x = σ 2 2 1-ν x′ ν Kν x′ Γ ν ,

where

Kν(·) is the modified Bessel function of the second kind,

ℓ 1=PARAMS 1, ℓ 1>0,

ℓ 2=PARAMS 2, ℓ 2>0,

ν=PARAMS 3, ν>0.

ICOV2=11

Continuously parameterised variogram with compact support

γ x = σ 2 2 1-ν x′ν Kν x′ Γ ν 1+8 x′′+25 x′′2+32 x′′3 1-x′′8, x′′<1, 0, x′′≥1,

where

x′′ = x′ ℓ 1s 1 , y′ ℓ 2s 2 ,

Kν(·) is the modified Bessel function of the second kind,

ℓ 1=PARAMS 1, ℓ 1>0,

ℓ 2=PARAMS 2, ℓ 2>0,

s 1=PARAMS 3, s 1>0,

s 2=PARAMS 4, s 2>0,

ν=PARAMS 5, ν>0.

ICOV2=12

Generalized hyperbolic distribution variogram

γ x=σ 2 δ 2+x′2 λ 2 δλ Kλ κδ Kλ κ δ 2+x′2 12,

where

Kλ(·) is the modified Bessel function of the second kind,

ℓ 1=PARAMS 1, ℓ 1>0,

ℓ 2=PARAMS 2, ℓ 2>0,

λ=PARAMS 3, no constraint on λ,

δ=PARAMS 4, δ>0,

κ=PARAMS 5, κ>0.

Constraint: ICOV2=1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11 or 12.

9:   NORM – INTEGERInput

On entry: determines which norm to use when calculating the variogram.
NORM=1

The 1-norm is used, i.e., x,y=x+y.

NORM=2

The 2-norm (Euclidean norm) is used, i.e., x,y= x 2+y 2.

Suggested value: NORM=2.

Constraint: NORM=1 or 2.

10:   NP – INTEGERInput

On entry: the number of parameters to be set. Different covariance functions need a different number of parameters.
ICOV2=6

NP must be set to 0.

ICOV2=3, 4, 5, 7 or 9

NP must be set to 2.

ICOV2=1, 2, 8 or 10

NP must be set to 3.

ICOV2=11 or 12

NP must be set to 5.

11:   PARAMS NP – REAL (KIND=nag_wp) arrayInput

On entry: the parameters for the variogram as detailed in the description of ICOV2.

Constraint: see ICOV2 for a description of the individual parameter constraints.

12:   PAD – INTEGERInput

On entry: determines whether the embedding matrix is padded with zeros, or padded with values of the variogram. The choice of padding may affect how big the embedding matrix must be in order to be positive semidefinite.
PAD=0

The embedding matrix is padded with zeros.

PAD=1

The embedding matrix is padded with values of the variogram.

Suggested value: PAD=1.

Constraint: PAD=0 or 1.

13:   ICORR – INTEGERInput

On entry: determines which approximation to implement if required, as described in Section 3.

Suggested value: ICORR=0.

Constraint: ICORR=0, 1 or 2.

14:   LAM MAXM 1×MAXM 2 – REAL (KIND=nag_wp) arrayOutput

On exit: contains the square roots of the eigenvalues of the embedding matrix.

15:   XX NS 1 – REAL (KIND=nag_wp) arrayOutput

On exit: the points of the x-coordinates at which values of the random field will be output.

16:   YY NS 2 – REAL (KIND=nag_wp) arrayOutput

On exit: the points of the y-coordinates at which values of the random field will be output.

17:   M 2 – INTEGER arrayOutput

On exit: M 1 contains M 1, the size of the circulant blocks and M 2 contains M 2, the number of blocks, resulting in a final square matrix of size M 1×M 2.

18:   APPROX – INTEGEROutput

On exit: indicates whether approximation was used.
APPROX=0

No approximation was used.

APPROX=1

Approximation was used.

19:   RHO – REAL (KIND=nag_wp)Output

On exit: indicates the scaling of the covariance matrix. RHO=1.0 unless approximation was used with ICORR=0 or 1.

20:   ICOUNT – INTEGEROutput

On exit: indicates the number of negative eigenvalues in the embedding matrix which have had to be set to zero.

21:   EIG 3 – REAL (KIND=nag_wp) arrayOutput

On exit: indicates information about the negative eigenvalues in the embedding matrix which have had to be set to zero. EIG 1 contains the smallest eigenvalue, EIG 2 contains the sum of the squares of the negative eigenvalues, and EIG 3 contains the sum of the absolute values of the negative eigenvalues.

22:   IFAIL – INTEGERInput/Output

On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.

On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).

Errors or warnings detected by the routine:

IFAIL=1

On entry, NS=value,value.
Constraint: NS 1≥1, NS 2≥1.

IFAIL=2

On entry, XMIN=value and XMAX=value.
Constraint: XMIN<XMAX.

IFAIL=4

On entry, YMIN=value and YMAX=value.
Constraint: YMIN<YMAX.

IFAIL=6

On entry, MAXM=value,value.
Constraint: the minimum calculated value for MAXM are value,value.
Where the minima of MAXM i is given by 2 k , where k is the smallest integer satisfying 2 k ≥ 2 NS i-1 , for i=1,2.

IFAIL=7

On entry, VAR=value.
Constraint: VAR≥0.0.

IFAIL=8

On entry, ICOV2=value.
Constraint: ICOV2≥1 and ICOV2≤12.

IFAIL=9

On entry, NORM=value.
Constraint: NORM=1 or 2.

IFAIL=10

On entry, NP=value.
Constraint: for ICOV2=value, NP=value.

IFAIL=11

On entry, PARAMS value=value.
Constraint: dependent on ICOV2, see documentation.

IFAIL=12

On entry, PAD=value.
Constraint: PAD=0 or 1.

IFAIL=13

On entry, ICORR=value.
Constraint: ICORR=0, 1 or 2.

IFAIL=-99

An unexpected error has been triggered by this routine. Please contact NAG.

See Section 3.9 in How to Use the NAG Library and its Documentation for further information.

IFAIL=-399

Your licence key may have expired or may not have been installed correctly.

See Section 3.8 in How to Use the NAG Library and its Documentation for further information.

IFAIL=-999

Dynamic memory allocation failed.

See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

If on exit APPROX=1, see the comments in Section 3 regarding the quality of approximation; increase the values in MAXM to attempt to avoid approximation.

8 Parallelism and Performance

G05ZRF is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.

G05ZRF makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.

Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

None.

10 Example

This example calls G05ZRF to calculate the eigenvalues of the embedding matrix for 25 sample points on a 5 by 5 grid of a two-dimensional random field characterized by the symmetric stable variogram (ICOV2=1).

10.1 Program Text

Program Text (g05zrfe.f90)

10.2 Program Data

Program Data (g05zrfe.d)

10.3 Program Results

Program Results (g05zrfe.r)

The two plots shown below illustrate the random fields that can be generated by G05ZSF using the eigenvalues calculated by G05ZRF. These are for two realizations of a two-dimensional random field, based on eigenvalues of the embedding matrix for points on a 100 by 100 grid. The random field is characterized by the exponential variogram (ICOV2=4) with correlation lengths both equal to 0.1.

G05 Chapter Contents

G05 Chapter Introduction

NAG Library Manual

© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


G05ZSF : NAG Library, Mark 26

G05 Chapter Contents
G05 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

G05ZSF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

G05ZSF produces realizations of a stationary Gaussian random field in two dimensions, using the circulant embedding method. The square roots of the eigenvalues of the extended covariance matrix (or embedding matrix) need to be input, and can be calculated using G05ZQF or G05ZRF.

2 Specification

SUBROUTINE G05ZSF ( NS, S, M, LAM, RHO, STATE, Z, IFAIL)
INTEGER | NS(2), S, M(2), STATE(*), IFAIL
REAL (KIND=nag_wp) | LAM(M(1)*M(2)), RHO, Z(NS(1)*NS(2),S)

3 Description

A two-dimensional random field Z x in ℝ 2 is a function which is random at every point x∈ℝ 2, so Z x is a random variable for each x. The random field has a mean function μ x=𝔼 Z x and a symmetric positive semidefinite covariance function C x,y=𝔼 Z x-μ xZ y-μ y. Z x is a Gaussian random field if for any choice of n∈ℕ and x 1,…,xn∈ℝ 2, the random vector Z x 1,…,Z xn T follows a multivariate Normal distribution, which would have a mean vector μ~ with entries μ~i=μ xi and a covariance matrix C~ with entries C~ij=C xi,xj. A Gaussian random field Z x is stationary if μ x is constant for all x∈ℝ 2 and C x,y=C x+a,y+a for all x,y,a∈ℝ 2 and hence we can express the covariance function C x,y as a function γ of one variable: C x,y=γ x-y. γ is known as a variogram (or more correctly, a semivariogram) and includes the multiplicative factor σ 2 representing the variance such that γ 0=σ 2.
The routines G05ZQF or G05ZRF along with G05ZSF are used to simulate a two-dimensional stationary Gaussian random field, with mean function zero and variogram γ x, over a domain xmin,xmax×ymin,ymax, using an equally spaced set of N 1×N 2 points; N 1 points in the x-direction and N 2 points in the y-direction. The problem reduces to sampling a Gaussian random vector X of size N 1×N 2, with mean vector zero and a symmetric covariance matrix A, which is an N 2 by N 2 block Toeplitz matrix with Toeplitz blocks of size N 1 by N 1. Since A is in general expensive to factorize, a technique known as the circulant embedding method is used. A is embedded into a larger, symmetric matrix B, which is an M 2 by M 2 block circulant matrix with circulant bocks of size M 1 by M 1, where M 1≥2 N 1-1 and M 2≥2 N 2-1. B can now be factorized as B=WΛ W*=R*R, where W is the two-dimensional Fourier matrix (W* is the complex conjugate of W), Λ is the diagonal matrix containing the eigenvalues of B and R=Λ 12W*. B is known as the embedding matrix. The eigenvalues can be calculated by performing a discrete Fourier transform of the first row (or column) of B and multiplying by M 1×M 2, and so only the first row (or column) of B is needed – the whole matrix does not need to be formed.
The symmetry of A as a block matrix, and the symmetry of each block of A, depends on whether the covariance function γ is even or not. γ is even if γ x=γ-x for all x∈ℝ 2, and uneven otherwise (in higher dimensions, γ can be even in some coordinates and uneven in others, but in two dimensions γ is either even in both coordinates or uneven in both coordinates). If γ is even then A is a symmetric block matrix and has symmetric blocks; if γ is uneven then A is not a symmetric block matrix and has non-symmetric blocks. In the uneven case, M 1 and M 2 are set to be odd in order to guarantee symmetry in B.
As long as all of the values of Λ are non-negative (i.e., B is positive semidefinite), B is a covariance matrix for a random vector Y which has M 2 ‘blocks’ of size M 1. Two samples of Y can now be simulated from the real and imaginary parts of R*U+iV, where U and V have elements from the standard Normal distribution. Since R*U+iV=W Λ 12 U+iV, this calculation can be done using a discrete Fourier transform of the vector Λ 12 U+iV. Two samples of the random vector X can now be recovered by taking the first N 1 elements of the first N 2 blocks of each sample of Y – because the original covariance matrix A is embedded in B, X will have the correct distribution.
If B is not positive semidefinite, larger embedding matrices B can be tried; however if the size of the matrix would have to be larger than MAXM, an approximation procedure is used. See the documentation of G05ZQF or G05ZRF for details of the approximation procedure.
G05ZSF takes the square roots of the eigenvalues of the embedding matrix B, and its size vector M, as input and outputs S realizations of the random field in Z.
One of the initialization routines G05KFF (for a repeatable sequence if computed sequentially) or G05KGF (for a non-repeatable sequence) must be called prior to the first call to G05ZSF.

4 References

Dietrich C R and Newsam G N (1997) Fast and exact simulation of stationary Gaussian processes through circulant embedding of the covariance matrix SIAM J. Sci. Comput. 18 1088–1107
Schlather M (1999) Introduction to positive definite functions and to unconditional simulation of random fields Technical Report ST 99–10 Lancaster University
Wood A T A and Chan G (1994) Simulation of stationary Gaussian processes in 0,1 d Journal of Computational and Graphical Statistics 3(4) 409–432

5 Arguments

1:   NS 2 – INTEGER arrayInput
On entry: the number of sample points to use in each direction, with NS 1 sample points in the x-direction and NS 2 sample points in the y-direction. The total number of sample points on the grid is therefore NS 1 × NS 2 . This must be the same value as supplied to G05ZQF or G05ZRF when calculating the eigenvalues of the embedding matrix.
Constraints:
  • NS 1≥1;
  • NS 2≥1.
2:   S – INTEGERInput
On entry: S, the number of realizations of the random field to simulate.
Constraint: S≥1.
3:   M 2 – INTEGER arrayInput
On entry: indicates the size, M, of the embedding matrix as returned by G05ZQF or G05ZRF. The embedding matrix is a block circulant matrix with circulant blocks. M 1 is the size of each block, and M 2 is the number of blocks.
Constraints:
  • M 1≥max 1,2 NS 1-1;
  • M 2≥max 1,2 NS 2-1.
4:   LAM M 1×M 2 – REAL (KIND=nag_wp) arrayInput
On entry: contains the square roots of the eigenvalues of the embedding matrix, as returned by G05ZQF or G05ZRF.
Constraint: LAM i≥0, i=1,2,…,M 1×M 2.
5:   RHO – REAL (KIND=nag_wp)Input
On entry: indicates the scaling of the covariance matrix, as returned by G05ZQF or G05ZRF.
Constraint: 0.0<RHO≤1.0.
6:   STATE* – INTEGER arrayCommunication Array
Note: the actual argument supplied must be the array STATE supplied to the initialization routines G05KFF or G05KGF.
On entry: contains information on the selected base generator and its current state.
On exit: contains updated information on the state of the generator.
7:   Z NS 1×NS 2 S – REAL (KIND=nag_wp) arrayOutput
On exit: contains the realizations of the random field. The kth realization (where k=1,2,…,S) of the random field on the two-dimensional grid xi,yj is stored in Z j-1× NS 1 +i k, for i=1,2,…,NS 1 and for j=1,2,…,NS 2. The points are returned in XX and YY by G05ZQF or G05ZRF.
8:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, NS=value,value.
Constraint: NS 1≥1, NS 2≥1.
IFAIL=2
On entry, S=value.
Constraint: S≥1.
IFAIL=3
On entry, M=value,value, and NS=value,value.
Constraints: M i≥max 1,2 NS i-1, for i=1,2.
IFAIL=4
On entry, at least one element of LAM was negative.
Constraint: all elements of LAM must be non-negative.
IFAIL=5
On entry, RHO=value.
Constraint: 0.0<RHO≤1.0.
IFAIL=6
On entry, STATE vector has been corrupted or not initialized.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

Not applicable.

8 Parallelism and Performance

G05ZSF is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
G05ZSF makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

Because samples are generated in pairs, calling this routine k times, with S=s, say, will generate a different sequence of numbers than calling the routine once with S=k⁢s, unless s is even.

10 Example

This example calls G05ZSF to generate 5 realizations of a two-dimensional random field on a 5 by 5 grid. This uses eigenvalues of the embedding covariance matrix for a symmetric stable variogram as calculated by G05ZRF with ICOV2=1.

10.1 Program Text

Program Text (g05zsfe.f90)

10.2 Program Data

Program Data (g05zsfe.d)

10.3 Program Results

Program Results (g05zsfe.r)

G05 Chapter Contents
G05 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


G05ZTF : NAG Library, Mark 26

G05 Chapter Contents
G05 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

G05ZTF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

G05ZTF produces realizations of a fractional Brownian motion, using the circulant embedding method. The square roots of the eigenvalues of the extended covariance matrix (or embedding matrix) need to be input, and can be calculated using G05ZNF.

2 Specification

SUBROUTINE G05ZTF ( NS, S, M, XMAX, H, LAM, RHO, STATE, Z, XX, IFAIL)
INTEGER | NS, S, M, STATE(*), IFAIL
REAL (KIND=nag_wp) | XMAX, H, LAM(M), RHO, Z(NS+1,S), XX(NS+1)

3 Description

The routines G05ZNF and G05ZTF are used to simulate a fractional Brownian motion process with Hurst argument H over an interval 0,xmax, using a set of equally spaced points. Fractional Brownian motion itself cannot be simulated directly using this method, since it is not a stationary Gaussian random field; however its increments can be simulated like a stationary Gaussian random field. The circulant embedding method is described in the documentation for G05ZNF.
G05ZTF takes the square roots of the eigenvalues of the embedding matrix as returned by G05ZNF when ICOV1=14, and its size M, as input and outputs S realizations of the fractional Brownian motion in Z.
One of the initialization routines G05KFF (for a repeatable sequence if computed sequentially) or G05KGF (for a non-repeatable sequence) must be called prior to the first call to G05ZTF.

4 References

Dietrich C R and Newsam G N (1997) Fast and exact simulation of stationary Gaussian processes through circulant embedding of the covariance matrix SIAM J. Sci. Comput. 18 1088–1107
Schlather M (1999) Introduction to positive definite functions and to unconditional simulation of random fields Technical Report ST 99–10 Lancaster University
Wood A T A and Chan G (1994) Simulation of stationary Gaussian processes in 0,1 d Journal of Computational and Graphical Statistics 3(4) 409–432

5 Arguments

1:   NS – INTEGERInput
On entry: the number of steps (points) to be generated in realizations of the increments of the fractional Brownian motion. This must be the same value as supplied to G05ZNF when calculating the eigenvalues of the embedding matrix.
Note: in the context of fractional Brownian motion, NS represents the number of steps from a zero starting state. Realizations returned in Z include this starting state and so NS+1 values are returned for each realization.
Constraint: NS≥1.
2:   S – INTEGERInput
On entry: S, the number of realizations of the fractional Brownian motion to simulate.
Constraint: S≥1.
3:   M – INTEGERInput
On entry: the size, M, of the embedding matrix, as returned by G05ZMF or G05ZNF.
Constraint: M≥max 1,2 NS-1.
4:   XMAX – REAL (KIND=nag_wp)Input
On entry: the upper bound for the interval over which the fractional Brownian motion is to be simulated, as input to G05ZMF or G05ZNF.
Constraint: XMAX>0.0.
5:   H – REAL (KIND=nag_wp)Input
On entry: the Hurst parameter, H, for the fractional Brownian motion. This must be the same value as supplied to G05ZNF in PARAMS 1, when the eigenvalues of the embedding matrix were calculated.
Constraint: 0.0<H<1.0.
6:   LAM M – REAL (KIND=nag_wp) arrayInput
On entry: contains the square roots of the eigenvalues of the embedding matrix, as returned by G05ZMF or G05ZNF.
Constraint: LAM i≥0, for i=1,2,…,M.
7:   RHO – REAL (KIND=nag_wp)Input
On entry: indicates the scaling of the covariance matrix, as returned by G05ZMF or G05ZNF.
Constraint: 0.0<RHO≤1.0.
8:   STATE* – INTEGER arrayCommunication Array
Note: the actual argument supplied must be the array STATE supplied to the initialization routines G05KFF or G05KGF.
On entry: contains information on the selected base generator and its current state.
On exit: contains updated information on the state of the generator.
9:   Z NS+1 S – REAL (KIND=nag_wp) arrayOutput
On exit: contains the realizations of the fractional Brownian motion, Z. The jth realization, for the ith point XX i, is stored in Z ij, for j=1,2,…,S and i=1,2,…,NS+1.
10:   XX NS+1 – REAL (KIND=nag_wp) arrayOutput
On exit: the points at which values of the fractional Brownian motion are output. The first point is always zero, and the subsequent NS points represent the equispaced steps towards the last point, XMAX. Note that in G05ZMF and G05ZNF, the returned NS sample points are the mid-points of the grid returned in XX here.
11:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, NS=value.
Constraint: NS≥1.
IFAIL=2
On entry, S=value.
Constraint: S≥1.
IFAIL=3
On entry, M=value, and NS=value.
Constraint: M≥max 1,2⁢NS-1.
IFAIL=4
On entry, XMAX=value.
Constraint: XMAX>0.0.
IFAIL=5
On entry, H=value.
Constraint: 0.0<H<1.0.
IFAIL=6
On entry, at least one element of LAM was negative.
Constraint: all elements of LAM must be non-negative.
IFAIL=7
On entry, RHO=value.
Constraint: 0.0<RHO≤1.0.
IFAIL=8
On entry, STATE vector has been corrupted or not initialized.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

Not applicable.

8 Parallelism and Performance

G05ZTF is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
G05ZTF makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

None.

10 Example

This example calls G05ZTF to generate 5 realizations of a fractional Brownian motion over 10 steps from x=0.0 to x=2.0 using eigenvalues generated by G05ZNF with ICOV1=14.

10.1 Program Text

Program Text (g05ztfe.f90)

10.2 Program Data

Program Data (g05ztfe.d)

10.3 Program Results

Program Results (g05ztfe.r)

G05 Chapter Contents
G05 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


G07AAF : NAG Library, Mark 26

G07 Chapter Contents
G07 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

G07AAF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

G07AAF computes a confidence interval for the argument p (the probability of a success) of a binomial distribution.

2 Specification

SUBROUTINE G07AAF ( N, K, CLEVEL, PL, PU, IFAIL)
INTEGER | N, K, IFAIL
REAL (KIND=nag_wp) | CLEVEL, PL, PU

3 Description

Given the number of trials, n, and the number of successes, k, this routine computes a 100 1-α% confidence interval for p, the probability argument of a binomial distribution with probability function,
f x= n x px1-p n-x,  x=0,1,…,n,
where α is in the interval 0,1.
Let the confidence interval be denoted by [pl,pu].
The point estimate for p is p^=k/n.
The lower and upper confidence limits pl and pu are estimated by the solutions to the equations;
∑x=k n n x plx 1-pl n-x =α/2 ,
∑x= 0 k n x pux 1-pu n-x =α /2 .
Three different methods are used depending on the number of trials, n, and the number of successes, k.
1. If max k,n-k<106.
The relationship between the beta and binomial distributions (see page 38 of Hastings and Peacock (1975)) is used to derive the equivalent equations,
pl = β k,n-k+1,α/2, pu = β k+1,n-k,1-α/2,
where β a,b,δ is the deviate associated with the lower tail probability, δ, of the beta distribution with arguments a and b. These beta deviates are computed using G01FEF.
2. If max k,n-k≥106 and min k,n-k ≤ 1000 .
The binomial variate with arguments n and p is approximated by a Poisson variate with mean np, see page 38 of Hastings and Peacock (1975).
The relationship between the Poisson and χ 2-distributions (see page 112 of Hastings and Peacock (1975)) is used to derive the following equations;
pl = 1 2 n χ 2 k,α/2 2, pu = 1 2 n χ 2 k+2,1-α/2 2,
where χ δ,ν 2 is the deviate associated with the lower tail probability, δ, of the χ 2-distribution with ν degrees of freedom.
In turn the relationship between the χ 2-distribution and the gamma distribution (see page 70 of Hastings and Peacock (1975)) yields the following equivalent equations;
pl = 1 2 n γ k,2;α/2, pu = 1 2 n γ k+1,2;1-α/2,
where γ α,β;δ is the deviate associated with the lower tail probability, δ, of the gamma distribution with shape argument α and scale argument β. These deviates are computed using G01FFF.
3. If max k,n-k>106 and min k,n-k > 1000 .
The binomial variate with arguments n and p is approximated by a Normal variate with mean np and variance np 1-p, see page 38 of Hastings and Peacock (1975).
The approximate lower and upper confidence limits pl and pu are the solutions to the equations;
k-n pl n pl 1-pl = z 1-α/2, k-n pu n pu 1-pu = z α/2,
where zδ is the deviate associated with the lower tail probability, δ, of the standard Normal distribution. These equations are solved using a quadratic equation solver (C02AJF).

4 References

Hastings N A J and Peacock J B (1975) Statistical Distributions Butterworth
Snedecor G W and Cochran W G (1967) Statistical Methods Iowa State University Press

5 Arguments

1:   N – INTEGERInput
On entry: n, the number of trials.
Constraint: N≥1.
2:   K – INTEGERInput
On entry: k, the number of successes.
Constraint: 0≤K≤N.
3:   CLEVEL – REAL (KIND=nag_wp)Input
On entry: the confidence level, 1-α, for two-sided interval estimate. For example CLEVEL=0.95 will give a 95% confidence interval.
Constraint: 0.0<CLEVEL<1.0.
4:   PL – REAL (KIND=nag_wp)Output
On exit: the lower limit, pl, of the confidence interval.
5:   PU – REAL (KIND=nag_wp)Output
On exit: the upper limit, pu, of the confidence interval.
6:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, | N<1,
or | K<0,
or | N<K,
or | CLEVEL≤0.0,
or | CLEVEL≥1.0.
IFAIL=2
When using the relationship with the gamma distribution to calculate one of the confidence limits, the series to calculate the gamma probabilities has failed to converge. Both PL and PU are set to zero. This is a very unlikely error exit and if it occurs please contact NAG.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

For most cases using the beta deviates the results should have a relative accuracy of max 0.5E−12,50.0×ε where ε is the machine precision (see X02AJF). Thus on machines with sufficiently high precision the results should be accurate to 12 significant figures. Some accuracy may be lost when α/2 or 1-α/2 is very close to 0.0, which will occur if CLEVEL is very close to 1.0. This should not affect the usual confidence levels used.
The approximations used when n is large are accurate to at least 3 significant digits but usually to more.

8 Parallelism and Performance

G07AAF is not threaded in any implementation.

9 Further Comments

None.

10 Example

The following example program reads in the number of deaths recorded among male recipients of war pensions in a six year period following an initial questionnaire in 1956. We consider two classes, non-smokers and those who reported that they smoked pipes only. The total number of males in each class is also read in. The data is taken from page 216 of Snedecor and Cochran (1967). An estimate of the probability of a death in the six year period in each class is computed together with 95% confidence intervals for these estimates.

10.1 Program Text

Program Text (g07aafe.f90)

10.2 Program Data

Program Data (g07aafe.d)

10.3 Program Results

Program Results (g07aafe.r)

G07 Chapter Contents
G07 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


G07ABF : NAG Library, Mark 26

G07 Chapter Contents
G07 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

G07ABF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

G07ABF computes a confidence interval for the mean argument of the Poisson distribution.

2 Specification

SUBROUTINE G07ABF ( N, XMEAN, CLEVEL, TL, TU, IFAIL)
INTEGER | N, IFAIL
REAL (KIND=nag_wp) | XMEAN, CLEVEL, TL, TU

3 Description

Given a random sample of size n, denoted by x 1,x 2,…,xn, from a Poisson distribution with probability function
p x=e-θ θx x! ,  x=0,1,2,…
the point estimate, θ^, for θ is the sample mean, x-.
Given n and x- this routine computes a 100 1-α% confidence interval for the argument θ, denoted by [θl,θu], where α is in the interval 0,1.
The lower and upper confidence limits are estimated by the solutions to the equations
e-n θl∑x=T∞ n θl x x! =α 2, e-n θu∑x=0 T n θu x x! =α 2,
where T=∑i=1 n xi=n θ^.
The relationship between the Poisson distribution and the χ 2-distribution (see page 112 of Hastings and Peacock (1975)) is used to derive the equations
θl= 1 2 n χ 2 T,α/2 2, θu= 1 2 n χ 2 T+2,1-α/2 2,
where χ ν,p 2 is the deviate associated with the lower tail probability p of the χ 2-distribution with ν degrees of freedom.
In turn the relationship between the χ 2-distribution and the gamma distribution (see page 70 of Hastings and Peacock (1975)) yields the following equivalent equations;
θl= 1 2 n γ T,2;α/2, θu= 1 2 n γ T+1,2;1-α/2,
where γ α,β;δ is the deviate associated with the lower tail probability, δ, of the gamma distribution with shape argument α and scale argument β. These deviates are computed using G01FFF.

4 References

Hastings N A J and Peacock J B (1975) Statistical Distributions Butterworth
Snedecor G W and Cochran W G (1967) Statistical Methods Iowa State University Press

5 Arguments

1:   N – INTEGERInput
On entry: n, the sample size.
Constraint: N≥1.
2:   XMEAN – REAL (KIND=nag_wp)Input
On entry: the sample mean, x-.
Constraint: XMEAN≥0.0.
3:   CLEVEL – REAL (KIND=nag_wp)Input
On entry: the confidence level, 1-α, for two-sided interval estimate. For example CLEVEL=0.95 gives a 95% confidence interval.
Constraint: 0.0<CLEVEL<1.0.
4:   TL – REAL (KIND=nag_wp)Output
On exit: the lower limit, θl, of the confidence interval.
5:   TU – REAL (KIND=nag_wp)Output
On exit: the upper limit, θu, of the confidence interval.
6:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, | N<1,
or | XMEAN<0.0,
or | CLEVEL≤0.0,
or | CLEVEL≥1.0.
IFAIL=2
When using the relationship with the gamma distribution to calculate one of the confidence limits, the series to calculate the gamma probabilities has failed to converge. Both TL and TU are set to zero. This is a very unlikely error exit and if it occurs please contact NAG.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

For most cases the results should have a relative accuracy of max 0.5E-12,50.0×ε where ε is the machine precision (see X02AJF). Thus on machines with sufficiently high precision the results should be accurate to 12 significant digits. Some accuracy may be lost when α/2 or 1-α/2 is very close to 0.0, which will occur if CLEVEL is very close to 1.0. This should not affect the usual confidence intervals used.

8 Parallelism and Performance

G07ABF is not threaded in any implementation.

9 Further Comments

None.

10 Example

The following example reads in data showing the number of noxious weed seeds and the frequency with which that number occurred in 98 subsamples of meadow grass. The data is taken from page 224 of Snedecor and Cochran (1967). The sample mean is computed as the point estimate of the Poisson argument θ. G07ABF is then called to compute both a 95% and a 99% confidence interval for the argument θ.

10.1 Program Text

Program Text (g07abfe.f90)

10.2 Program Data

Program Data (g07abfe.d)

10.3 Program Results

Program Results (g07abfe.r)

G07 Chapter Contents
G07 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


G07BBF : NAG Library, Mark 26

G07 Chapter Contents
G07 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

G07BBF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

G07BBF computes maximum likelihood estimates and their standard errors for arguments of the Normal distribution from grouped and/or censored data.

2 Specification

SUBROUTINE G07BBF ( METHOD, N, X, XC, IC, XMU, XSIG, TOL, MAXIT, SEXMU, SEXSIG, CORR, DEV, NOBS, NIT, WK, IFAIL)
INTEGER | N, IC(N), MAXIT, NOBS(4), NIT, IFAIL
REAL (KIND=nag_wp) | X(N), XC(N), XMU, XSIG, TOL, SEXMU, SEXSIG, CORR, DEV, WK(2*N)
CHARACTER(1) | METHOD

3 Description

A sample of size n is taken from a Normal distribution with mean μ and variance σ 2 and consists of grouped and/or censored data. Each of the n observations is known by a pair of values Li,Ui such that:
Li≤xi≤Ui.
The data is represented as particular cases of this form:
  • exactly specified observations occur when Li=Ui=xi,
  • right-censored observations, known only by a lower bound, occur when Ui→∞,
  • left-censored observations, known only by a upper bound, occur when Li→-∞,
  • and interval-censored observations when Li<xi<Ui.
Let the set A identify the exactly specified observations, sets B and C identify the observations censored on the right and left respectively, and set D identify the observations confined between two finite limits. Also let there be r exactly specified observations, i.e., the number in A. The probability density function for the standard Normal distribution is
Z x=1 2 π exp-12 x 2 ,  -∞<x<∞
and the cumulative distribution function is
P X= 1-Q X=∫-∞X Z x dx.
The log-likelihood of the sample can be written as:
L μ,σ =-r log⁡σ - 1 2 ∑ A x i -μ / σ 2 +∑B log Q l i + ∑ C log P u i + ∑ D log p i
where pi=P ui-P li and ui=Ui-μ/σ,  li=Li-μ/σ.
Let
S xi=Z xi Q xi ,  S 1 li,ui=Z li-Z ui pi
and
S 2 li,ui=ui Z ui-li Z li pi,
then the first derivatives of the log-likelihood can be written as:
∂L μ,σ ∂μ =L 1 μ,σ=σ-2∑A xi-μ+σ-1∑B S li-σ-1∑C S-ui+σ-1∑DS 1 li,ui
and
∂L μ,σ ∂σ =L 2 μ,σ=-r σ-1+σ-3∑A xi-μ 2+σ-1∑Bli S li-σ-1∑Cui S-ui
-σ-1∑DS 2 li,ui
The maximum likelihood estimates, μ^ and σ^, are the solution to the equations:
L 1 μ^,σ^=0 (1)
and
L 2 μ^,σ^=0 (2)
and if the second derivatives ∂2 L ∂2 μ , ∂2 L ∂μ ∂σ and ∂2 L ∂2 σ are denoted by L 11, L 12 and L 22 respectively, then estimates of the standard errors of μ^ and σ^ are given by:
se μ^=-L 22 L 11L 22-L 122 ,  se σ^=-L 11 L 11L 22-L 122
and an estimate of the correlation of μ^ and σ^ is given by:
L 12 L 12L 22 .
To obtain the maximum likelihood estimates the equations (1) and (2) can be solved using either the Newton–Raphson method or the Expectation-maximization EM algorithm of Dempster et al. (1977).
Newton–Raphson Method
This consists of using approximate estimates μ~ and σ~ to obtain improved estimates μ~+δ μ~ and σ~+δ σ~ by solving
δ μ~L 11+δ σ~L 12+L 1=0, δ μ~L 12+δ σ~L 22+L 2=0,
for the corrections δ μ~ and δ σ~.
EM Algorithm
The expectation step consists of constructing the variable wi as follows:
if   i∈A,   wi= xi E ∣ Li< xi< Ui = μ+σ S 1 li,ui (3)
if   i∈B,   wi= E xi∣ xi> Li =μ+σS li S 1 li,ui (4)
if   i∈C,   wi= E xi∣ xi< Ui =μ-σS -ui li,ui (5)
if   i∈D,   wi= E xi∣ Li< xi< Ui =μ+σ S 1 li,ui (6)
the maximization step consists of substituting (3), (4), (5) and (6) into (1) and (2) giving:
μ^=∑i=1 n w^i/n (7)
and
σ^2=∑i=1 n w^i-μ^2/ r+∑B T l^i+∑C T-u^i+∑DT 1 l^i,u^i (8)
where
T x=S xS x-x ,   T 1 l,u=S 12 l,u+S 2 l,u
and where w^i, l^i and u^i are wi, li and ui evaluated at μ^ and σ^. Equations (3) to (8) are the basis of the EM iterative procedure for finding μ^ and σ^2. The procedure consists of alternately estimating μ^ and σ^2 using (7) and (8) and estimating w^i using (3) to (6).
In choosing between the two methods a general rule is that the Newton–Raphson method converges more quickly but requires good initial estimates whereas the EM algorithm converges slowly but is robust to the initial values. In the case of the censored Normal distribution, if only a small proportion of the observations are censored then estimates based on the exact observations should give good enough initial estimates for the Newton–Raphson method to be used. If there are a high proportion of censored observations then the EM algorithm should be used and if high accuracy is required the subsequent use of the Newton–Raphson method to refine the estimates obtained from the EM algorithm should be considered.

4 References

Dempster A P, Laird N M and Rubin D B (1977) Maximum likelihood from incomplete data via the EM algorithm (with discussion) J. Roy. Statist. Soc. Ser. B 39 1–38
Swan A V (1969) Algorithm AS 16. Maximum likelihood estimation from grouped and censored normal data Appl. Statist. 18 110–114
Wolynetz M S (1979) Maximum likelihood estimation from confined and censored normal data Appl. Statist. 28 185–195

5 Arguments

1:   METHOD – CHARACTER(1)Input
On entry: indicates whether the Newton–Raphson or EM algorithm should be used.
If METHOD='N', then the Newton–Raphson algorithm is used.
If METHOD='E', then the EM algorithm is used.
Constraint: METHOD='N' or 'E'.
2:   N – INTEGERInput
On entry: n, the number of observations.
Constraint: N≥2.
3:   X N – REAL (KIND=nag_wp) arrayInput
On entry: the observations xi, Li or Ui, for i=1,2,…,n.
If the observation is exactly specified – the exact value, xi.
If the observation is right-censored – the lower value, Li.
If the observation is left-censored – the upper value, Ui.
If the observation is interval-censored – the lower or upper value, Li or Ui, (see XC).
4:   XC N – REAL (KIND=nag_wp) arrayInput
On entry: if the jth observation, for j=1,2,…,n is an interval-censored observation then XC j should contain the complementary value to X j, that is, if X j<XC j, then XC j contains upper value, Ui, and if X j>XC j, then XC j contains lower value, Li. Otherwise if the jth observation is exact or right- or left-censored XC j need not be set.
Note: if X j=XC j then the observation is ignored.
5:   IC N – INTEGER arrayInput
On entry: IC i contains the censoring codes for the ith observation, for i=1,2,…,n.
If IC i=0, the observation is exactly specified.
If IC i=1, the observation is right-censored.
If IC i=2, the observation is left-censored.
If IC i=3, the observation is interval-censored.
Constraint: IC i=0, 1, 2 or 3, for i=1,2,…,n.
6:   XMU – REAL (KIND=nag_wp)Input/Output
On entry: if XSIG>0.0 the initial estimate of the mean, μ; otherwise XMU need not be set.
On exit: the maximum likelihood estimate, μ^, of μ.
7:   XSIG – REAL (KIND=nag_wp)Input/Output
On entry: specifies whether an initial estimate of μ and σ are to be supplied.
XSIG>0.0
XSIG is the initial estimate of σ and XMU must contain an initial estimate of μ.
XSIG≤0.0
Initial estimates of XMU and XSIG are calculated internally from:
(a) | the exact observations, if the number of exactly specified observations is ≥2; or
(b) | the interval-censored observations; if the number of interval-censored observations is ≥1; or
(c) | they are set to 0.0 and 1.0 respectively.
On exit: the maximum likelihood estimate, σ^, of σ.
8:   TOL – REAL (KIND=nag_wp)Input
On entry: the relative precision required for the final estimates of μ and σ. Convergence is assumed when the absolute relative changes in the estimates of both μ and σ are less than TOL.
If TOL=0.0, then a relative precision of 0.000005 is used.
Constraint: machine precision<TOL≤1.0 or TOL=0.0.
9:   MAXIT – INTEGERInput
On entry: the maximum number of iterations.
If MAXIT≤0, then a value of 25 is used.
10:   SEXMU – REAL (KIND=nag_wp)Output
On exit: the estimate of the standard error of μ^.
11:   SEXSIG – REAL (KIND=nag_wp)Output
On exit: the estimate of the standard error of σ^.
12:   CORR – REAL (KIND=nag_wp)Output
On exit: the estimate of the correlation between μ^ and σ^.
13:   DEV – REAL (KIND=nag_wp)Output
On exit: the maximized log-likelihood, L μ^,σ^.
14:   NOBS 4 – INTEGER arrayOutput
On exit: the number of the different types of each observation;
NOBS 1 contains number of right-censored observations.
NOBS 2 contains number of left-censored observations.
NOBS 3 contains number of interval-censored observations.
NOBS 4 contains number of exactly specified observations.
15:   NIT – INTEGEROutput
On exit: the number of iterations performed.
16:   WK 2×N – REAL (KIND=nag_wp) arrayWorkspace
17:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, | METHOD≠'N' or 'E',
or | N<2,
or | IC i≠0, 1, 2 or 3, for some i,
or | TOL<0.0,
or | 0.0<TOL<machine precision,
or | TOL>1.0.
IFAIL=2
The chosen method failed to converge in MAXIT iterations. You should either increase TOL or MAXIT or, if using the EM algorithm try using the Newton–Raphson method with initial values those returned by the current call to G07BBF. All returned values will be reasonable approximations to the correct results if MAXIT is not very small.
IFAIL=3
The chosen method is diverging. This will be due to poor initial values. You should try different initial values.
IFAIL=4
G07BBF was unable to calculate the standard errors. This can be caused by the method starting to diverge when the maximum number of iterations was reached.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

The accuracy is controlled by the argument TOL.
If high precision is requested with the EM algorithm then there is a possibility that, due to the slow convergence, before the correct solution has been reached the increments of μ^ and σ^ may be smaller than TOL and the process will prematurely assume convergence.

8 Parallelism and Performance

G07BBF is not threaded in any implementation.

9 Further Comments

The process is deemed divergent if three successive increments of μ or σ increase.

10 Example

A sample of 18 observations and their censoring codes are read in and the Newton–Raphson method used to compute the estimates.

10.1 Program Text

Program Text (g07bbfe.f90)

10.2 Program Data

Program Data (g07bbfe.d)

10.3 Program Results

Program Results (g07bbfe.r)

G07 Chapter Contents
G07 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


G07BEF : NAG Library, Mark 26

G07 Chapter Contents
G07 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

G07BEF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

G07BEF computes maximum likelihood estimates for arguments of the Weibull distribution from data which may be right-censored.

2 Specification

SUBROUTINE G07BEF ( CENS, N, X, IC, BETA, GAMMA, TOL, MAXIT, SEBETA, SEGAM, CORR, DEV, NIT, WK, IFAIL)
INTEGER | N, IC(*), MAXIT, NIT, IFAIL
REAL (KIND=nag_wp) | X(N), BETA, GAMMA, TOL, SEBETA, SEGAM, CORR, DEV, WK(N)
CHARACTER(1) | CENS

3 Description

G07BEF computes maximum likelihood estimates of the arguments of the Weibull distribution from exact or right-censored data.
For n realizations, yi, from a Weibull distribution a value xi is observed such that
xi≤yi.
There are two situations:
(a) | exactly specified observations, when xi=yi
(b) | right-censored observations, known by a lower bound, when xi<yi.
The probability density function of the Weibull distribution, and hence the contribution of an exactly specified observation to the likelihood, is given by:
f x;λ,γ=λγ x γ-1 exp-λ xγ,  x>0,   for ​λ,γ>0;
while the survival function of the Weibull distribution, and hence the contribution of a right-censored observation to the likelihood, is given by:
S x;λ,γ=exp-λ xγ,   x> 0,   for ​ λ ,γ> 0.
If d of the n observations are exactly specified and indicated by i∈D and the remaining n-d are right-censored, then the likelihood function, Like ​λ,γ is given by
Like λ,γ∝λγ d ∏i∈D xi γ-1 exp-λ∑i=1 n xiγ .
To avoid possible numerical instability a different parameterisation β,γ is used, with β=log λ. The kernel log-likelihood function, L β,γ, is then:
L β,γ=d log γ+dβ+γ-1∑i∈D log xi-eβ∑i=1 n xiγ.
If the derivatives ∂L ∂β , ∂L ∂γ , ∂2 L ∂β 2 , ∂2 L ∂β ∂γ and ∂2 L ∂γ 2 are denoted by L 1, L 2, L 11, L 12 and L 22, respectively, then the maximum likelihood estimates, β^ and γ^, are the solution to the equations:
L 1 β^,γ^=0 (1)
and
L 2 β^,γ^=0 (2)
Estimates of the asymptotic standard errors of β^ and γ^ are given by:
se β^=-L 22 L 11L 22-L 122 ,  se γ^=-L 11 L 11L 22-L 122 .
An estimate of the correlation coefficient of β^ and γ^ is given by:
L 12 L 12L 22 .
Note: if an estimate of the original argument λ is required, then
λ^=exp β^  and  se λ^=λ^se β^.
The equations (1) and (2) are solved by the Newton–Raphson iterative method with adjustments made to ensure that γ^>0.0.

4 References

Gross A J and Clark V A (1975) Survival Distributions: Reliability Applications in the Biomedical Sciences Wiley
Kalbfleisch J D and Prentice R L (1980) The Statistical Analysis of Failure Time Data Wiley

5 Arguments

1:   CENS – CHARACTER(1)Input
On entry: indicates whether the data is censored or non-censored.
CENS='N'
Each observation is assumed to be exactly specified. IC is not referenced.
CENS='C'
Each observation is censored according to the value contained in IC i, for i=1,2,…,n.
Constraint: CENS='N' or 'C'.
2:   N – INTEGERInput
On entry: n, the number of observations.
Constraint: N≥1.
3:   X N – REAL (KIND=nag_wp) arrayInput
On entry: X i contains the ith observation, xi, for i=1,2,…,n.
Constraint: X i>0.0, for i=1,2,…,n.
4:   IC* – INTEGER arrayInput
Note: the dimension of the array IC must be at least N if CENS='C', and at least 1 otherwise.
On entry: if CENS='C', then IC i contains the censoring codes for the ith observation, for i=1,2,…,n.
If IC i=0, the ith observation is exactly specified.
If IC i=1, the ith observation is right-censored.
If CENS='N', then IC is not referenced.
Constraint: if CENS='C', then IC i=0 or 1, for i=1,2,…,n.
5:   BETA – REAL (KIND=nag_wp)Output
On exit: the maximum likelihood estimate, β^, of β.
6:   GAMMA – REAL (KIND=nag_wp)Input/Output
On entry: indicates whether an initial estimate of γ is provided.
If GAMMA>0.0, it is taken as the initial estimate of γ and an initial estimate of β is calculated from this value of γ.
If GAMMA≤0.0, then initial estimates of γ and β are calculated, internally, providing the data contains at least two distinct exact observations. (If there are only two distinct exact observations, then the largest observation must not be exactly specified.) See Section 9 for further details.
On exit: contains the maximum likelihood estimate, γ^, of γ.
7:   TOL – REAL (KIND=nag_wp)Input
On entry: the relative precision required for the final estimates of β and γ. Convergence is assumed when the absolute relative changes in the estimates of both β and γ are less than TOL.
If TOL=0.0, then a relative precision of 0.000005 is used.
Constraint: machine precision≤TOL≤1.0 or TOL=0.0.
8:   MAXIT – INTEGERInput
On entry: the maximum number of iterations allowed.
If MAXIT≤0, then a value of 25 is used.
9:   SEBETA – REAL (KIND=nag_wp)Output
On exit: an estimate of the standard error of β^.
10:   SEGAM – REAL (KIND=nag_wp)Output
On exit: an estimate of the standard error of γ^.
11:   CORR – REAL (KIND=nag_wp)Output
On exit: an estimate of the correlation between β^ and γ^.
12:   DEV – REAL (KIND=nag_wp)Output
On exit: the maximized kernel log-likelihood, L β^,γ^.
13:   NIT – INTEGEROutput
On exit: the number of iterations performed.
14:   WK N – REAL (KIND=nag_wp) arrayWorkspace
15:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, | CENS≠'N' or 'C',
or | N<1,
or | TOL<0.0,
or | 0.0<TOL<machine precision,
or | TOL>1.0.
IFAIL=2
On entry, | the ith observation, X i≤0.0, for some i=1,2,…,n,
or | the ith censoring code, IC i≠0 or 1, for some i=1,2,…,n and CENS='C'.
IFAIL=3
On entry, there are no exactly specified observations, or the routine was requested to calculate initial values and there are either less than two distinct exactly specified observations or there are exactly two and the largest observation is one of the exact observations.
IFAIL=4
The method has failed to converge in MAXIT iterations. You should increase TOL or MAXIT.
IFAIL=5
Process has diverged. The process is deemed divergent if three successive increments of β or γ increase or if the Hessian matrix of the Newton–Raphson process is singular. Either different initial estimates should be provided or the data should be checked to see if the Weibull distribution is appropriate.
IFAIL=6
A potential overflow has been detected. This is an unlikely exit usually caused by a large input estimate of γ.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

Given that the Weibull distribution is a suitable model for the data and that the initial values are reasonable the convergence to the required accuracy, indicated by TOL, should be achieved.

8 Parallelism and Performance

G07BEF is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The initial estimate of γ is found by calculating a Kaplan–Meier estimate of the survival function, S^x, and estimating the gradient of the plot of log-log S^x against x. This requires the Kaplan–Meier estimate to have at least two distinct points.
The initial estimate of β^, given a value of γ^, is calculated as
β^=log d∑i=1 n xi γ^ .

10 Example

In a study, 20 patients receiving an analgesic to relieve headache pain had the following recorded relief times (in hours):
1.1 1.4 1.3 1.7 1.9 1.8 1.6 2.2 1.7 2.7 4.1 1.8 1.5 1.2 1.4 3.0 1.7 2.3 1.6 2.0
(See Gross and Clark (1975).) This data is read in and a Weibull distribution fitted assuming no censoring; the parameter estimates and their standard errors are printed.

10.1 Program Text

Program Text (g07befe.f90)

10.2 Program Data

Program Data (g07befe.d)

10.3 Program Results

Program Results (g07befe.r)

G07 Chapter Contents
G07 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


G07BFF : NAG Library, Mark 26

G07 Chapter Contents
G07 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

G07BFF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

G07BFF estimates parameter values for the generalized Pareto distribution by using either moments or maximum likelihood.

2 Specification

SUBROUTINE G07BFF ( N, Y, OPTOPT, XI, BETA, ASVC, OBSVC, LL, IFAIL)
INTEGER | N, OPTOPT, IFAIL
REAL (KIND=nag_wp) | Y(N), XI, BETA, ASVC(4), OBSVC(4), LL

3 Description

Let the distribution function of a set of n observations
yi ,   i=1,2,…,n
be given by the generalized Pareto distribution:
F y = 1- 1+ ξy β -1/ξ , ξ≠0 1-e-yβ , ξ=0;
where
  • β>0 and
  • y≥0, when ξ≥0;
  • 0≤y≤-βξ, when ξ<0.
Estimates ξ^ and β^ of the parameters ξ and β are calculated by using one of:
  • method of moments (MOM);
  • probability-weighted moments (PWM);
  • maximum likelihood estimates (MLE) that seek to maximize the log-likelihood:
    L = -n ln⁡ β^ - 1+ 1 ξ^ ∑ i=1 n ln 1+ ξ^yi β^ .
The variances and covariance of the asymptotic Normal distribution of parameter estimates ξ^ and β^ are returned if ξ^ satisfies:
  • ξ^<14 for the MOM;
  • ξ^<12 for the PWM method;
  • ξ^<-12 for the MLE method.
If the MLE option is exercised, the observed variances and covariance of ξ^ and β^ is returned, given by the negative inverse Hessian of L.

4 References

Hosking J R M and Wallis J R (1987) Parameter and quantile estimation for the generalized Pareto distribution Technometrics 29(3)
McNeil A J, Frey R and Embrechts P (2005) Quantitative Risk Management Princeton University Press

5 Arguments

1:   N – INTEGERInput
On entry: the number of observations.
Constraint: N>1.
2:   Y N – REAL (KIND=nag_wp) arrayInput
On entry: the n observations yi, for i=1,2,…,n, assumed to follow a generalized Pareto distribution.
Constraints:
  • Y i≥0.0;
  • ∑ i=1 n Y i>0.0.
3:   OPTOPT – INTEGERInput
On entry: determines the method of estimation, set:
OPTOPT=-2
For the method of probability-weighted moments.
OPTOPT=-1
For the method of moments.
OPTOPT=1
For maximum likelihood with starting values given by the method of moments estimates.
OPTOPT=2
For maximum likelihood with starting values given by the method of probability-weighted moments.
Constraint: OPTOPT=-2, -1, 1 or 2.
4:   XI – REAL (KIND=nag_wp)Output
On exit: the parameter estimate ξ^.
5:   BETA – REAL (KIND=nag_wp)Output
On exit: the parameter estimate β^.
6:   ASVC 4 – REAL (KIND=nag_wp) arrayOutput
On exit: the variance-covariance of the asymptotic Normal distribution of ξ^ and β^. ASVC 1 contains the variance of ξ^; ASVC 4 contains the variance of β^; ASVC 2 and ASVC 3 contain the covariance of ξ^ and β^.
7:   OBSVC 4 – REAL (KIND=nag_wp) arrayOutput
On exit: if maximum likelihood estimates are requested, the observed variance-covariance of ξ^ and β^. OBSVC 1 contains the variance of ξ^; OBSVC 4 contains the variance of β^; OBSVC 2 and OBSVC 3 contain the covariance of ξ^ and β^.
8:   LL – REAL (KIND=nag_wp)Output
On exit: if maximum likelihood estimates are requested, LL contains the log-likelihood value L at the end of the optimization; otherwise LL is set to -1.0.
9:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, N=value.
Constraint: N>1.
IFAIL=2
On entry, Y value=value.
Constraint: Y i≥0.0 for all i.
IFAIL=3
On entry, OPTOPT=value.
Constraint: OPTOPT=-2, -1, 1 or 2.
IFAIL=6
The asymptotic distribution is not available for the returned parameter estimates.
IFAIL=7
The distribution of maximum likelihood estimates cannot be calculated for the returned parameter estimates because the Hessian matrix could not be inverted.
IFAIL=8
The asymptotic distribution of parameter estimates is invalid and the distribution of maximum likelihood estimates cannot be calculated for the returned parameter estimates because the Hessian matrix could not be inverted.
IFAIL=9
The optimization of log-likelihood failed to converge; no maximum likelihood estimates are returned. Try using the other maximum likelihood option by resetting OPTOPT. If this also fails, moments-based estimates can be returned by an appropriate setting of OPTOPT.
IFAIL=10
Variance of data in Y is too low for method of moments optimization.
IFAIL=11
The sum of Y is zero within machine precision.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

Not applicable.

8 Parallelism and Performance

G07BFF is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The search for maximum likelihood parameter estimates is further restricted by requiring
1+ ξ^yi β^ > 0 ,
as this avoids the possibility of making the log-likelihood L arbitrarily high.

10 Example

This example calculates parameter estimates for 23 observations assumed to be drawn from a generalized Pareto distribution.

10.1 Program Text

Program Text (g07bffe.f90)

10.2 Program Data

Program Data (g07bffe.d)

10.3 Program Results

Program Results (g07bffe.r)

G07 Chapter Contents
G07 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


G07CAF : NAG Library, Mark 26

G07 Chapter Contents
G07 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

G07CAF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

G07CAF computes a t-test statistic to test for a difference in means between two Normal populations, together with a confidence interval for the difference between the means.

2 Specification

SUBROUTINE G07CAF ( TAIL, EQUAL, NX, NY, XMEAN, YMEAN, XSTD, YSTD, CLEVEL, T, DF, PROB, DL, DU, IFAIL)
INTEGER | NX, NY, IFAIL
REAL (KIND=nag_wp) | XMEAN, YMEAN, XSTD, YSTD, CLEVEL, T, DF, PROB, DL, DU
CHARACTER(1) | TAIL, EQUAL

3 Description

Consider two independent samples, denoted by X and Y, of size nx and ny drawn from two Normal populations with means μx and μy, and variances σx 2 and σy 2 respectively. Denote the sample means by x- and y- and the sample variances by sx 2 and sy 2 respectively.
G07CAF calculates a test statistic and its significance level to test the null hypothesis H 0:μx=μy, together with upper and lower confidence limits for μx-μy. The test used depends on whether or not the two population variances are assumed to be equal.
1. It is assumed that the two variances are equal, that is σx 2=σy 2.
The test used is the two sample t-test. The test statistic t is defined by;
tobs=x--y- s⁢1/nx+1/ny
where
s 2 = nx-1 sx 2 + ny-1 sy 2 nx + ny - 2
is the pooled variance of the two samples.
Under the null hypothesis H 0 this test statistic has a t-distribution with nx+ny-2 degrees of freedom.
The test of H 0 is carried out against one of three possible alternatives;
  • H 1:μx≠μy; the significance level, p=P t≥tobs, i.e., a two tailed probability.
  • H 1:μx>μy; the significance level, p=P t≥tobs, i.e., an upper tail probability.
  • H 1:μx<μy; the significance level, p=P t≤tobs, i.e., a lower tail probability.
Upper and lower 100 1-α% confidence limits for μx-μy are calculated as:
x--y-±t 1-α/2 s⁢1/nx+1/ny.
where t 1-α/2 is the 100 1-α/2 percentage point of the t-distribution with (nx+ny-2) degrees of freedom.
2. It is not assumed that the two variances are equal.
If the population variances are not equal the usual two sample t-statistic no longer has a t-distribution and an approximate test is used.
This problem is often referred to as the Behrens–Fisher problem, see Kendall and Stuart (1969). The test used here is based on Satterthwaites procedure. To test the null hypothesis the test statistic t′ is used where
tobs′=x--y- se x--y-
where se x--y-= sx 2 nx+ sy 2 ny.
A t-distribution with f degrees of freedom is used to approximate the distribution of t′ where
f = se⁡ x- - y- 4 sx 2 / nx 2 nx-1 + sy 2 / ny 2 ny-1 .
The test of H 0 is carried out against one of the three alternative hypotheses described above, replacing t by t′ and tobs by tobs′.
Upper and lower 100 1-α% confidence limits for μx-μy are calculated as:
x--y-±t 1-α/2 se x-y-.
where t 1-α/2 is the 100 1-α/2 percentage point of the t-distribution with f degrees of freedom.

4 References

Johnson M G and Kotz A (1969) The Encyclopedia of Statistics 2 Griffin
Kendall M G and Stuart A (1969) The Advanced Theory of Statistics (Volume 1) (3rd Edition) Griffin
Snedecor G W and Cochran W G (1967) Statistical Methods Iowa State University Press

5 Arguments

1:   TAIL – CHARACTER(1)Input
On entry: indicates which tail probability is to be calculated, and thus which alternative hypothesis is to be used.
TAIL='T'
The two tail probability, i.e., H 1:μx≠μy.
TAIL='U'
The upper tail probability, i.e., H 1:μx>μy.
TAIL='L'
The lower tail probability, i.e., H 1:μx<μy.
Constraint: TAIL='T', 'U' or 'L'.
2:   EQUAL – CHARACTER(1)Input
On entry: indicates whether the population variances are assumed to be equal or not.
EQUAL='E'
The population variances are assumed to be equal, that is σx 2=σy 2.
EQUAL='U'
The population variances are not assumed to be equal.
Constraint: EQUAL='E' or 'U'.
3:   NX – INTEGERInput
On entry: nx, the size of the X sample.
Constraint: NX≥2.
4:   NY – INTEGERInput
On entry: ny, the size of the Y sample.
Constraint: NY≥2.
5:   XMEAN – REAL (KIND=nag_wp)Input
On entry: x-, the mean of the X sample.
6:   YMEAN – REAL (KIND=nag_wp)Input
On entry: y-, the mean of the Y sample.
7:   XSTD – REAL (KIND=nag_wp)Input
On entry: sx, the standard deviation of the X sample.
Constraint: XSTD>0.0.
8:   YSTD – REAL (KIND=nag_wp)Input
On entry: sy, the standard deviation of the Y sample.
Constraint: YSTD>0.0.
9:   CLEVEL – REAL (KIND=nag_wp)Input
On entry: the confidence level, 1-α, for the specified tail. For example CLEVEL=0.95 will give a 95% confidence interval.
Constraint: 0.0<CLEVEL<1.0.
10:   T – REAL (KIND=nag_wp)Output
On exit: contains the test statistic, tobs or tobs′.
11:   DF – REAL (KIND=nag_wp)Output
On exit: contains the degrees of freedom for the test statistic.
12:   PROB – REAL (KIND=nag_wp)Output
On exit: contains the significance level, that is the tail probability, p, as defined by TAIL.
13:   DL – REAL (KIND=nag_wp)Output
On exit: contains the lower confidence limit for μx-μy.
14:   DU – REAL (KIND=nag_wp)Output
On exit: contains the upper confidence limit for μx-μy.
15:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, | TAIL≠'T', 'U' or 'L',
or | EQUAL≠'E' or 'U',
or | NX<2,
or | NY<2,
or | XSTD≤0.0,
or | YSTD≤0.0,
or | CLEVEL≤0.0,
or | CLEVEL≥1.0.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

The computed probability and the confidence limits should be accurate to approximately five significant figures.

8 Parallelism and Performance

G07CAF is not threaded in any implementation.

9 Further Comments

The sample means and standard deviations can be computed using G01ATF.

10 Example

This example reads the two sample sizes and the sample means and standard deviations for two independent samples. The data is taken from page 116 of Snedecor and Cochran (1967) from a test to compare two methods of estimating the concentration of a chemical in a vat. A test of the equality of the means is carried out first assuming that the two population variances are equal and then making no assumption about the equality of the population variances.

10.1 Program Text

Program Text (g07cafe.f90)

10.2 Program Data

Program Data (g07cafe.d)

10.3 Program Results

Program Results (g07cafe.r)

G07 Chapter Contents
G07 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


G07 Chapter Contents : NAG Library Manual, Mark 26

G07 Chapter Introduction
NAG Library Manual

NAG Library Chapter Contents

G07 – Univariate Estimation

G07 Chapter Introduction – a description of the Chapter and an overview of the algorithms available

Routine Name | Mark of Introduction | Purpose
G07AAF Example Text Example Data | 15 | nagf_univar_ci_binomial Computes confidence interval for the parameter of a binomial distribution
G07ABF Example Text Example Data | 15 | nagf_univar_ci_poisson Computes confidence interval for the parameter of a Poisson distribution
G07BBF Example Text Example Data | 15 | nagf_univar_estim_normal Computes maximum likelihood estimates for parameters of the Normal distribution from grouped and/or censored data
G07BEF Example Text Example Data | 15 | nagf_univar_estim_weibull Computes maximum likelihood estimates for parameters of the Weibull distribution
G07BFF Example Text Example Data | 23 | nagf_univar_estim_genpareto Estimates parameter values of the generalized Pareto distribution
G07CAF Example Text Example Data | 15 | nagf_univar_ttest_2normal Computes t-test statistic for a difference in means between two Normal populations, confidence interval
G07DAF Example Text Example Data | 13 | nagf_univar_robust_1var_median Robust estimation, median, median absolute deviation, robust standard deviation
G07DBF Example Text Example Data | 13 | nagf_univar_robust_1var_mestim Robust estimation, M-estimates for location and scale parameters, standard weight functions
G07DCF Example Text Example Data | 13 | nagf_univar_robust_1var_mestim_wgt Robust estimation, M-estimates for location and scale parameters, user-defined weight functions
G07DDF Example Text Example Data | 14 | nagf_univar_robust_1var_trimmed Computes a trimmed and winsorized mean of a single sample with estimates of their variance
G07EAF Example Text Example Data | 16 | nagf_univar_robust_1var_ci Robust confidence intervals, one-sample
G07EBF Example Text Example Data | 16 | nagf_univar_robust_2var_ci Robust confidence intervals, two-sample
G07GAF Example Text Example Data | 23 | nagf_univar_outlier_peirce_1var Outlier detection using method of Peirce, raw data or single variance supplied
G07GBF Example Text Example Data | 23 | nagf_univar_outlier_peirce_2var Outlier detection using method of Peirce, two variances supplied
G07 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


G07DAF : NAG Library, Mark 26

G07 Chapter Contents
G07 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

G07DAF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

G07DAF finds the median, median absolute deviation, and a robust estimate of the standard deviation for a set of ungrouped data.

2 Specification

SUBROUTINE G07DAF ( N, X, Y, XME, XMD, XSD, IFAIL)
INTEGER | N, IFAIL
REAL (KIND=nag_wp) | X(N), Y(N), XME, XMD, XSD

3 Description

The data consists of a sample of size n, denoted by x 1,x 2,…,xn, drawn from a random variable X.
G07DAF first computes the median,
θmed=medi xi,
and from this the median absolute deviation can be computed,
σmed=medi xi-θmed.
Finally, a robust estimate of the standard deviation is computed,
σmed′=σmed/Φ-1 0.75
where Φ-1 0.75 is the value of the inverse standard Normal function at the point 0.75.
G07DAF is based upon subroutine LTMDDV within the ROBETH library, see Marazzi (1987).

4 References

Huber P J (1981) Robust Statistics Wiley
Marazzi A (1987) Subroutines for robust estimation of location and scale in ROBETH Cah. Rech. Doc. IUMSP, No. 3 ROB 1 Institut Universitaire de Médecine Sociale et Préventive, Lausanne

5 Arguments

1:   N – INTEGERInput
On entry: n, the number of observations.
Constraint: N>1.
2:   X N – REAL (KIND=nag_wp) arrayInput
On entry: the vector of observations, x 1,x 2,…,xn.
3:   Y N – REAL (KIND=nag_wp) arrayOutput
On exit: the observations sorted into ascending order.
4:   XME – REAL (KIND=nag_wp)Output
On exit: the median, θmed.
5:   XMD – REAL (KIND=nag_wp)Output
On exit: the median absolute deviation, σmed.
6:   XSD – REAL (KIND=nag_wp)Output
On exit: the robust estimate of the standard deviation, σmed′.
7:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, N≤1.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

The computations are believed to be stable.

8 Parallelism and Performance

G07DAF is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
G07DAF makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

Unless otherwise stated in the Users' Note, the routine may be called with the same actual array supplied for arguments X and Y, in which case the sorted data values will overwrite the original contents of X. However this is not standard Fortran, and may not work on all systems.

10 Example

The following program reads in a set of data consisting of eleven observations of a variable X. The median, median absolute deviation and a robust estimate of the standard deviation are calculated and printed along with the sorted data in output array Y.

10.1 Program Text

Program Text (g07dafe.f90)

10.2 Program Data

Program Data (g07dafe.d)

10.3 Program Results

Program Results (g07dafe.r)

G07 Chapter Contents
G07 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


G07DBF : NAG Library, Mark 26

G07 Chapter Contents
G07 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

G07DBF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

G07DBF computes an M-estimate of location with (optional) simultaneous estimation of the scale using Huber's algorithm.

2 Specification

SUBROUTINE G07DBF ( ISIGMA, N, X, IPSI, C, H1, H2, H3, DCHI, THETA, SIGMA, MAXIT, TOL, RS, NIT, WRK, IFAIL)
INTEGER | ISIGMA, N, IPSI, MAXIT, NIT, IFAIL
REAL (KIND=nag_wp) | X(N), C, H1, H2, H3, DCHI, THETA, SIGMA, TOL, RS(N), WRK(N)

3 Description

The data consists of a sample of size n, denoted by x 1,x 2,…,xn, drawn from a random variable X.
The xi are assumed to be independent with an unknown distribution function of the form
F xi-θ/σ
where θ is a location argument, and σ is a scale argument. M-estimators of θ and σ are given by the solution to the following system of equations:
∑i=1 n ψ xi-θ^ /σ^=0 (1)
∑i=1 n χ xi-θ^ /σ^=n-1 β (2)
where ψ and χ are given functions, and β is a constant, such that σ^ is an unbiased estimator when xi, for i=1,2,…,n has a Normal distribution. Optionally, the second equation can be omitted and the first equation is solved for θ^ using an assigned value of σ=σc.
The values of ψ xi-θ^σ^ σ^ are known as the Winsorized residuals.
The following functions are available for ψ and χ in G07DBF.
(a) Null Weights
ψ t=t t 2 2 χ t= t 2 2
Use of these null functions leads to the mean and standard deviation of the data.
(b) Huber's Function
ψ t = max-c,min c,t t 2 2 | χ t= t 2 2 t≤d
 | χ t= d 2 2 t>d
(c) Hampel's Piecewise Linear Function
ψ h 1,h 2,h 3 t=-ψ h 1,h 2,h 3-t |  |
ψ h 1,h 2,h 3 t=t t 2 2 | 0≤t≤h 1 t 2 2 | χ t= t 2 2 t≤d
ψ h 1,h 2,h 3 t=h 1 | h 1≤t≤h 2 |
ψ h 1,h 2,h 3 t=h 1 h 3-t/h 3-h 2 t 2 2 | h 2≤t≤h 3 t 2 2 | χ t= d 2 2 t>d
ψ h 1,h 2,h 3 t=0 | t>h 3 |
(d) Andrew's Sine Wave Function
ψ t=sin⁡t d 2 2 | -π≤t≤π d 2 2 | χ t= t 2 2 t≤d
ψ t=0 d 2 2 | otherwise d 2 2 | χ t= d 2 2 t>d
(e) Tukey's Bi-weight
ψ t=t 1-t 2 2 t 2 2 | t≤1 t 2 2 | χ t= t 2 2 t≤d
ψ t=t 1-t 2 2=0 t 2 2 | otherwise t 2 2 | χ t= d 2 2 t>d
where c, h 1, h 2, h 3 and d are constants.
Equations (1) and (2) are solved by a simple iterative procedure suggested by Huber:
σ^k=1 β n-1 ∑i=1 n χ xi-θ^k-1 σ^k-1 σ^k-1 2
and
θ^k=θ^k- 1+1 n∑i= 1 n ψ xi-θ^k- 1 σ^k σ^k
or
σ^k=σc,   if  σ  is fixed.
The initial values for θ^ and σ^ may either be user-supplied or calculated within G07DBF as the sample median and an estimate of σ based on the median absolute deviation respectively.
G07DBF is based upon subroutine LYHALG within the ROBETH library, see Marazzi (1987).

4 References

Hampel F R, Ronchetti E M, Rousseeuw P J and Stahel W A (1986) Robust Statistics. The Approach Based on Influence Functions Wiley
Huber P J (1981) Robust Statistics Wiley
Marazzi A (1987) Subroutines for robust estimation of location and scale in ROBETH Cah. Rech. Doc. IUMSP, No. 3 ROB 1 Institut Universitaire de Médecine Sociale et Préventive, Lausanne

5 Arguments

1:   ISIGMA – INTEGERInput
On entry: the value assigned to ISIGMA determines whether σ^ is to be simultaneously estimated.
ISIGMA=0
The estimation of σ^ is bypassed and SIGMA is set equal to σc.
ISIGMA=1
σ^ is estimated simultaneously.
2:   N – INTEGERInput
On entry: n, the number of observations.
Constraint: N>1.
3:   X N – REAL (KIND=nag_wp) arrayInput
On entry: the vector of observations, x 1,x 2,…,xn.
4:   IPSI – INTEGERInput
On entry: which ψ function is to be used.
IPSI=0
ψ t=t.
IPSI=1
Huber's function.
IPSI=2
Hampel's piecewise linear function.
IPSI=3
Andrew's sine wave,
IPSI=4
Tukey's bi-weight.
5:   C – REAL (KIND=nag_wp)Input
On entry: if IPSI=1, C must specify the argument, c, of Huber's ψ function. C is not referenced if IPSI≠1.
Constraint: if IPSI=1, C>0.0.
6:   H1 – REAL (KIND=nag_wp)Input
7:   H2 – REAL (KIND=nag_wp)Input
8:   H3 – REAL (KIND=nag_wp)Input
On entry: if IPSI=2, H1, H2 and H3 must specify the arguments, h 1, h 2, and h 3, of Hampel's piecewise linear ψ function. H1, H2 and H3 are not referenced if IPSI≠2.
Constraint: 0≤H1≤H2≤H3 and H3>0.0 if IPSI=2.
9:   DCHI – REAL (KIND=nag_wp)Input
On entry: d, the argument of the χ function. DCHI is not referenced if IPSI=0.
Constraint: if IPSI≠0, DCHI>0.0.
10:   THETA – REAL (KIND=nag_wp)Input/Output
On entry: if SIGMA>0 then THETA must be set to the required starting value of the estimation of the location argument θ^. A reasonable initial value for θ^ will often be the sample mean or median.
On exit: the M-estimate of the location argument, θ^.
11:   SIGMA – REAL (KIND=nag_wp)Input/Output
On entry: the role of SIGMA depends on the value assigned to ISIGMA, as follows:
  • if ISIGMA=1, SIGMA must be assigned a value which determines the values of the starting points for the calculations of θ^ and σ^. If SIGMA≤0.0 then G07DBF will determine the starting points of θ^ and σ^. Otherwise the value assigned to SIGMA will be taken as the starting point for σ^, and THETA must be assigned a value before entry, see above;
  • if ISIGMA=0, SIGMA must be assigned a value which determines the value of σc, which is held fixed during the iterations, and the starting value for the calculation of θ^. If SIGMA≤0, then G07DBF will determine the value of σc as the median absolute deviation adjusted to reduce bias (see G07DAF) and the starting point for θ^. Otherwise, the value assigned to SIGMA will be taken as the value of σc and THETA must be assigned a relevant value before entry, see above.
On exit: contains the M-estimate of the scale argument, σ^, if ISIGMA was assigned the value 1 on entry, otherwise SIGMA will contain the initial fixed value σc.
12:   MAXIT – INTEGERInput
On entry: the maximum number of iterations that should be used during the estimation.
Suggested value: MAXIT=50.
Constraint: MAXIT>0.
13:   TOL – REAL (KIND=nag_wp)Input
On entry: the relative precision for the final estimates. Convergence is assumed when the increments for THETA, and SIGMA are less than TOL×max 1.0,σ k-1.
Constraint: TOL>0.0.
14:   RS N – REAL (KIND=nag_wp) arrayOutput
On exit: the Winsorized residuals.
15:   NIT – INTEGEROutput
On exit: the number of iterations that were used during the estimation.
16:   WRK N – REAL (KIND=nag_wp) arrayOutput
On exit: if SIGMA≤0.0 on entry, WRK will contain the n observations in ascending order.
17:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, | N≤1,
or | MAXIT≤0,
or | TOL≤0.0,
or | ISIGMA≠0 or 1,
or | IPSI<0,
or | IPSI>4.
IFAIL=2
On entry, | C≤0.0 and IPSI=1,
or | H1<0.0 and IPSI=2,
or | H1=H2=H3=0.0 and IPSI=2,
or | H1>H2 and IPSI=2,
or | H1>H3 and IPSI=2,
or | H2>H3 and IPSI=2,
or | DCHI≤0.0 and IPSI≠0.
IFAIL=3
On entry, all elements of the input array X are equal.
IFAIL=4
SIGMA, the current estimate of σ, is zero or negative. This error exit is very unlikely, although it may be caused by too large an initial value of SIGMA.
IFAIL=5
The number of iterations required exceeds MAXIT.
IFAIL=6
On completion of the iterations, the Winsorized residuals were all zero. This may occur when using the ISIGMA=0 option with a redescending ψ function, i.e., Hampel's piecewise linear function, Andrew's sine wave, and Tukey's biweight.
If the given value of σ is too small, then the standardized residuals xi-θ^k σc , will be large and all the residuals may fall into the region for which ψ t=0. This may incorrectly terminate the iterations thus making THETA and SIGMA invalid.
Re-enter the routine with a larger value of σc or with ISIGMA=1.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

On successful exit the accuracy of the results is related to the value of TOL, see Section 5.

8 Parallelism and Performance

G07DBF is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
G07DBF makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

When you supply the initial values, care has to be taken over the choice of the initial value of σ. If too small a value of σ is chosen then initial values of the standardized residuals xi-θ^k σ will be large. If the redescending ψ functions are used, i.e., Hampel's piecewise linear function, Andrew's sine wave, or Tukey's bi-weight, then these large values of the standardized residuals are Winsorized as zero. If a sufficient number of the residuals fall into this category then a false solution may be returned, see page 152 of Hampel et al. (1986).

10 Example

The following program reads in a set of data consisting of eleven observations of a variable X.
For this example, Hampel's Piecewise Linear Function is used (IPSI=2), values for h 1, h 2 and h 3 along with d for the χ function, being read from the data file.
Using the following starting values various estimates of θ and σ are calculated and printed along with the number of iterations used:
(a) | G07DBF determines the starting values, σ is estimated simultaneously.
(b) | You must supply the starting values, σ is estimated simultaneously.
(c) | G07DBF determines the starting values, σ is fixed.
(d) | You must supply the starting values, σ is fixed.

10.1 Program Text

Program Text (g07dbfe.f90)

10.2 Program Data

Program Data (g07dbfe.d)

10.3 Program Results

Program Results (g07dbfe.r)

G07 Chapter Contents
G07 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


G07DCF : NAG Library, Mark 26

G07 Chapter Contents
G07 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

G07DCF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

G07DCF computes an M-estimate of location with (optional) simultaneous estimation of scale, where you provide the weight functions.

2 Specification

SUBROUTINE G07DCF ( CHI, PSI, ISIGMA, N, X, BETA, THETA, SIGMA, MAXIT, TOL, RS, NIT, WRK, IFAIL)
INTEGER | ISIGMA, N, MAXIT, NIT, IFAIL
REAL (KIND=nag_wp) | CHI, PSI, X(N), BETA, THETA, SIGMA, TOL, RS(N), WRK(N)
EXTERNAL | CHI, PSI

3 Description

The data consists of a sample of size n, denoted by x 1,x 2,…,xn, drawn from a random variable X.
The xi are assumed to be independent with an unknown distribution function of the form,
F xi-θ/σ
where θ is a location argument, and σ is a scale argument. M-estimators of θ and σ are given by the solution to the following system of equations;
∑i=1 n ψ xi-θ^/σ^ = 0 ∑i=1 n χ xi-θ^/σ^ = n-1 β
where ψ and χ are user-supplied weight functions, and β is a constant. Optionally the second equation can be omitted and the first equation is solved for θ^ using an assigned value of σ=σc.
The constant β should be chosen so that σ^ is an unbiased estimator when xi, for i=1,2,…,n has a Normal distribution. To achieve this the value of β is calculated as:
β=E χ=∫-∞∞χ z 1 2 π exp-z 2 2dz
The values of ψ xi-θ^σ^ σ^ are known as the Winsorized residuals.
The equations are solved by a simple iterative procedure, suggested by Huber:
σ^k=1 β n-1 ∑i=1 n χ xi-θ^k-1 σ^k-1 σ^k-1 2
and
θ^k=θ^k- 1+1 n ∑i= 1 n ψ xi-θ^k- 1 σ^k σ^k
or
σ^k=σc
if σ is fixed.
The initial values for θ^ and σ^ may be user-supplied or calculated within G07DBF as the sample median and an estimate of σ based on the median absolute deviation respectively.
G07DCF is based upon subroutine LYHALG within the ROBETH library, see Marazzi (1987).

4 References

Hampel F R, Ronchetti E M, Rousseeuw P J and Stahel W A (1986) Robust Statistics. The Approach Based on Influence Functions Wiley
Huber P J (1981) Robust Statistics Wiley
Marazzi A (1987) Subroutines for robust estimation of location and scale in ROBETH Cah. Rech. Doc. IUMSP, No. 3 ROB 1 Institut Universitaire de Médecine Sociale et Préventive, Lausanne

5 Arguments

1:   CHI – REAL (KIND=nag_wp) FUNCTION, supplied by the user.External Procedure
CHI must return the value of the weight function χ for a given value of its argument. The value of χ must be non-negative.
The specification of CHI is:
FUNCTION CHI ( T)
REAL (KIND=nag_wp) CHI
REAL (KIND=nag_wp) T
1:   T – REAL (KIND=nag_wp)Input
On entry: the argument for which CHI must be evaluated.
CHI must either be a module subprogram USEd by, or declared as EXTERNAL in, the (sub)program from which G07DCF is called. Arguments denoted as Input must not be changed by this procedure.
2:   PSI – REAL (KIND=nag_wp) FUNCTION, supplied by the user.External Procedure
PSI must return the value of the weight function ψ for a given value of its argument.
The specification of PSI is:
FUNCTION PSI ( T)
REAL (KIND=nag_wp) PSI
REAL (KIND=nag_wp) T
1:   T – REAL (KIND=nag_wp)Input
On entry: the argument for which PSI must be evaluated.
PSI must either be a module subprogram USEd by, or declared as EXTERNAL in, the (sub)program from which G07DCF is called. Arguments denoted as Input must not be changed by this procedure.
3:   ISIGMA – INTEGERInput
On entry: the value assigned to ISIGMA determines whether σ^ is to be simultaneously estimated.
ISIGMA=0
The estimation of σ^ is bypassed and SIGMA is set equal to σc.
ISIGMA=1
σ^ is estimated simultaneously.
4:   N – INTEGERInput
On entry: n, the number of observations.
Constraint: N>1.
5:   X N – REAL (KIND=nag_wp) arrayInput
On entry: the vector of observations, x 1,x 2,…,xn.
6:   BETA – REAL (KIND=nag_wp)Input
On entry: the value of the constant β of the chosen CHI function.
Constraint: BETA>0.0.
7:   THETA – REAL (KIND=nag_wp)Input/Output
On entry: if SIGMA>0, then THETA must be set to the required starting value of the estimate of the location argument θ^. A reasonable initial value for θ^ will often be the sample mean or median.
On exit: the M-estimate of the location argument θ^.
8:   SIGMA – REAL (KIND=nag_wp)Input/Output
On entry: the role of SIGMA depends on the value assigned to ISIGMA as follows.
If ISIGMA=1, SIGMA must be assigned a value which determines the values of the starting points for the calculation of θ^ and σ^. If SIGMA≤0.0, then G07DCF will determine the starting points of θ^ and σ^. Otherwise, the value assigned to SIGMA will be taken as the starting point for σ^, and THETA must be assigned a relevant value before entry, see above.
If ISIGMA=0, SIGMA must be assigned a value which determines the values of σc, which is held fixed during the iterations, and the starting value for the calculation of θ^. If SIGMA≤0, then G07DCF will determine the value of σc as the median absolute deviation adjusted to reduce bias (see G07DAF) and the starting point for θ. Otherwise, the value assigned to SIGMA will be taken as the value of σc and THETA must be assigned a relevant value before entry, see above.
On exit: the M-estimate of the scale argument σ^, if ISIGMA was assigned the value 1 on entry, otherwise SIGMA will contain the initial fixed value σc.
9:   MAXIT – INTEGERInput
On entry: the maximum number of iterations that should be used during the estimation.
Suggested value: MAXIT=50.
Constraint: MAXIT>0.
10:   TOL – REAL (KIND=nag_wp)Input
On entry: the relative precision for the final estimates. Convergence is assumed when the increments for THETA, and SIGMA are less than TOL×max 1.0,σ k-1.
Constraint: TOL>0.0.
11:   RS N – REAL (KIND=nag_wp) arrayOutput
On exit: the Winsorized residuals.
12:   NIT – INTEGEROutput
On exit: the number of iterations that were used during the estimation.
13:   WRK N – REAL (KIND=nag_wp) arrayOutput
On exit: if SIGMA≤0.0 on entry, WRK will contain the n observations in ascending order.
14:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, | N≤1,
or | MAXIT≤0,
or | TOL≤0.0,
or | ISIGMA≠0 or 1.
IFAIL=2
On entry, BETA≤0.0.
IFAIL=3
On entry, all elements of the input array X are equal.
IFAIL=4
SIGMA, the current estimate of σ, is zero or negative. This error exit is very unlikely, although it may be caused by too large an initial value of SIGMA.
IFAIL=5
The number of iterations required exceeds MAXIT.
IFAIL=6
On completion of the iterations, the Winsorized residuals were all zero. This may occur when using the ISIGMA=0 option with a redescending ψ function, i.e., ψ=0 if t>τ, for some positive constant τ.
If the given value of σ is too small, then the standardized residuals xi-θ^k σc , will be large and all the residuals may fall into the region for which ψ t=0. This may incorrectly terminate the iterations thus making THETA and SIGMA invalid.
Re-enter the routine with a larger value of σc or with ISIGMA=1.
IFAIL=7
The value returned by the CHI function is negative.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

On successful exit the accuracy of the results is related to the value of TOL, see Section 5.

8 Parallelism and Performance

G07DCF is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
G07DCF makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

Standard forms of the functions ψ and χ are given in Hampel et al. (1986), Huber (1981) and Marazzi (1987). G07DBF calculates M-estimates using some standard forms for ψ and χ.
When you supply the initial values, care has to be taken over the choice of the initial value of σ. If too small a value is chosen then initial values of the standardized residuals xi-θ^k σ will be large. If the redescending ψ functions are used, i.e., ψ=0 if t>τ, for some positive constant τ, then these large values are Winsorized as zero. If a sufficient number of the residuals fall into this category then a false solution may be returned, see page 152 of Hampel et al. (1986).

10 Example

The following program reads in a set of data consisting of eleven observations of a variable X.
The PSI and CHI functions used are Hampel's Piecewise Linear Function and Hubers CHI function respectively.
Using the following starting values various estimates of θ and σ are calculated and printed along with the number of iterations used:
(a) | G07DCF determined the starting values, σ is estimated simultaneously.
(b) | You must supply the starting values, σ is estimated simultaneously.
(c) | G07DCF determined the starting values, σ is fixed.
(d) | You must supply the starting values, σ is fixed.

10.1 Program Text

Program Text (g07dcfe.f90)

10.2 Program Data

Program Data (g07dcfe.d)

10.3 Program Results

Program Results (g07dcfe.r)

G07 Chapter Contents
G07 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


G07DDF : NAG Library, Mark 26

G07 Chapter Contents
G07 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

G07DDF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

G07DDF calculates the trimmed and Winsorized means of a sample and estimates of the variances of the two means.

2 Specification

SUBROUTINE G07DDF ( N, X, ALPHA, TMEAN, WMEAN, TVAR, WVAR, K, SX, IFAIL)
INTEGER | N, K, IFAIL
REAL (KIND=nag_wp) | X(N), ALPHA, TMEAN, WMEAN, TVAR, WVAR, SX(N)

3 Description

G07DDF calculates the α-trimmed mean and α-Winsorized mean for a given α, as described below.
Let xi, for i=1,2,…,n represent the n sample observations sorted into ascending order. Let k=αn where y represents the integer nearest to y; if 2 k=n then k is reduced by 1.
Then the trimmed mean is defined as:
x-t = 1 n-2 k ∑ i=k+1 n-k xi ,
and the Winsorized mean is defined as:
x-w = 1 n ∑ i=k+ 1 n-k xi + k ⁢ x k+1 + k ⁢ x n-k .
G07DDF then calculates the Winsorized variance about the trimmed and Winsorized means respectively and divides by n to obtain estimates of the variances of the above two means.
Thus we have;
Estimate of ​ var x-t = 1 n 2 ∑ i=k+1 n-k xi - x-t 2 + k x k+1 - x-t 2 + k x n-k - x-t 2
and
Estimate of ​ var x-w = 1 n 2 ∑ i=k+ 1 n-k xi - x-w 2 + k x k+ 1 - x-w 2 + k x n-k - x-w 2 .

4 References

Hampel F R, Ronchetti E M, Rousseeuw P J and Stahel W A (1986) Robust Statistics. The Approach Based on Influence Functions Wiley
Huber P J (1981) Robust Statistics Wiley

5 Arguments

1:   N – INTEGERInput
On entry: n, the number of observations.
Constraint: N≥2.
2:   X N – REAL (KIND=nag_wp) arrayInput
On entry: the sample observations, xi, for i=1,2,…,n.
3:   ALPHA – REAL (KIND=nag_wp)Input
On entry: α, the proportion of observations to be trimmed at each end of the sorted sample.
Constraint: 0.0≤ALPHA<0.5.
4:   TMEAN – REAL (KIND=nag_wp)Output
On exit: the α-trimmed mean, x-t.
5:   WMEAN – REAL (KIND=nag_wp)Output
On exit: the α-Winsorized mean, x-w.
6:   TVAR – REAL (KIND=nag_wp)Output
On exit: contains an estimate of the variance of the trimmed mean.
7:   WVAR – REAL (KIND=nag_wp)Output
On exit: contains an estimate of the variance of the Winsorized mean.
8:   K – INTEGEROutput
On exit: contains the number of observations trimmed at each end, k.
9:   SX N – REAL (KIND=nag_wp) arrayOutput
On exit: contains the sample observations sorted into ascending order.
10:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, N≤1.
IFAIL=2
On entry, | ALPHA<0.0,
or | ALPHA≥0.5.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

The results should be accurate to within a small multiple of machine precision.

8 Parallelism and Performance

G07DDF is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The time taken is proportional to n.

10 Example

The following program finds the α-trimmed mean and α-Winsorized mean for a sample of 16 observations where α=0.15. The estimates of the variances of the above two means are also calculated.

10.1 Program Text

Program Text (g07ddfe.f90)

10.2 Program Data

Program Data (g07ddfe.d)

10.3 Program Results

Program Results (g07ddfe.r)

G07 Chapter Contents
G07 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


G07EAF : NAG Library, Mark 26

G07 Chapter Contents
G07 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

G07EAF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

G07EAF computes a rank based (nonparametric) estimate and confidence interval for the location argument of a single population.

2 Specification

SUBROUTINE G07EAF ( METHOD, N, X, CLEVEL, THETA, THETAL, THETAU, ESTCL, WLOWER, WUPPER, WRK, IWRK, IFAIL)
INTEGER | N, IWRK(3*N), IFAIL
REAL (KIND=nag_wp) | X(N), CLEVEL, THETA, THETAL, THETAU, ESTCL, WLOWER, WUPPER, WRK(4*N)
CHARACTER(1) | METHOD

3 Description

Consider a vector of independent observations, x=x 1,x 2,…,xn T with unknown common symmetric density f xi-θ. G07EAF computes the Hodges–Lehmann location estimator (see Lehmann (1975)) of the centre of symmetry θ, together with an associated confidence interval. The Hodges–Lehmann estimate is defined as
θ^=median xi+xj 2,1≤i≤j≤n .
Let m=n n+1/2 and let ak, for k=1,2,…,m denote the m ordered averages xi+xj/2 for 1≤i≤j≤n. Then
  • if m is odd, θ^=ak where k=m+1/2;
  • if m is even, θ^=ak+a k+1/2 where k=m/2.
This estimator arises from inverting the one-sample Wilcoxon signed-rank test statistic, W x-θ 0, for testing the hypothesis that θ=θ 0. Effectively W x-θ 0 is a monotonically decreasing step function of θ 0 with
mean ​W=μ= n n+1 4, var W=σ 2= n n+12 n+1 24.
The estimate θ^ is the solution to the equation W x-θ^=μ; two methods are available for solving this equation. These methods avoid the computation of all the ordered averages ak; this is because for large n both the storage requirements and the computation time would be excessive.
The first is an exact method based on a set partitioning procedure on the set of all ordered averages xi+xj/2 for i≤j. This is based on the algorithm proposed by Monahan (1984).
The second is an iterative algorithm, based on the Illinois method which is a modification of the regula falsi method, see McKean and Ryan (1977). This algorithm has proved suitable for the function W x-θ 0 which is asymptotically linear as a function of θ 0.
The confidence interval limits are also based on the inversion of the Wilcoxon test statistic.
Given a desired percentage for the confidence interval, 1-α, expressed as a proportion between 0 and 1, initial estimates for the lower and upper confidence limits of the Wilcoxon statistic are found from
Wl=μ-0.5+σ Φ-1 α/2
and
Wu=μ+ 0.5+σ Φ-1 1-α /2,
where Φ-1 is the inverse cumulative Normal distribution function.
Wl and Wu are rounded to the nearest integer values. These estimates are then refined using an exact method if n≤80, and a Normal approximation otherwise, to find Wl and Wu satisfying
P W≤Wl≤α/2 P W≤Wl+1>α/2
and
P W≥Wu≤α /2 P W≥Wu- 1>α /2.
Let Wu=m-k; then θl=a k+1. This is the largest value θl such that W x-θl=Wu.
Let Wl=k; then θu=a m-k. This is the smallest value θu such that W x-θu=Wl.
As in the case of θ^, these equations may be solved using either the exact or the iterative methods to find the values θl and θu.
Then θl,θu is the confidence interval for θ. The confidence interval is thus defined by those values of θ 0 such that the null hypothesis, θ=θ 0, is not rejected by the Wilcoxon signed-rank test at the 100×α% level.

4 References

Lehmann E L (1975) Nonparametrics: Statistical Methods Based on Ranks Holden–Day
Marazzi A (1987) Subroutines for robust estimation of location and scale in ROBETH Cah. Rech. Doc. IUMSP, No. 3 ROB 1 Institut Universitaire de Médecine Sociale et Préventive, Lausanne
McKean J W and Ryan T A (1977) Algorithm 516: An algorithm for obtaining confidence intervals and point estimates based on ranks in the two-sample location problem ACM Trans. Math. Software 10 183–185
Monahan J F (1984) Algorithm 616: Fast computation of the Hodges–Lehman location estimator ACM Trans. Math. Software 10 265–270

5 Arguments

1:   METHOD – CHARACTER(1)Input
On entry: specifies the method to be used.
METHOD='E'
The exact algorithm is used.
METHOD='A'
The iterative algorithm is used.
Constraint: METHOD='E' or 'A'.
2:   N – INTEGERInput
On entry: n, the sample size.
Constraint: N≥2.
3:   X N – REAL (KIND=nag_wp) arrayInput
On entry: the sample observations, xi, for i=1,2,…,n.
4:   CLEVEL – REAL (KIND=nag_wp)Input
On entry: the confidence interval desired.
For example, for a 95% confidence interval set CLEVEL=0.95.
Constraint: 0.0<CLEVEL<1.0.
5:   THETA – REAL (KIND=nag_wp)Output
On exit: the estimate of the location, θ^.
6:   THETAL – REAL (KIND=nag_wp)Output
On exit: the estimate of the lower limit of the confidence interval, θl.
7:   THETAU – REAL (KIND=nag_wp)Output
On exit: the estimate of the upper limit of the confidence interval, θu.
8:   ESTCL – REAL (KIND=nag_wp)Output
On exit: an estimate of the actual percentage confidence of the interval found, as a proportion between 0.0,1.0.
9:   WLOWER – REAL (KIND=nag_wp)Output
On exit: the upper value of the Wilcoxon test statistic, Wu, corresponding to the lower limit of the confidence interval.
10:   WUPPER – REAL (KIND=nag_wp)Output
On exit: the lower value of the Wilcoxon test statistic, Wl, corresponding to the upper limit of the confidence interval.
11:   WRK 4×N – REAL (KIND=nag_wp) arrayWorkspace
12:   IWRK 3×N – INTEGER arrayWorkspace
13:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, | METHOD≠'E' or 'A',
or | N<2,
or | CLEVEL≤0.0,
or | CLEVEL≥1.0.
IFAIL=2
There is not enough information to compute a confidence interval since the whole sample consists of identical values.
IFAIL=3
For at least one of the estimates θ^, θl and θu, the underlying iterative algorithm (when METHOD='A') failed to converge. This is an unlikely exit but the estimate should still be a reasonable approximation.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

G07EAF should produce results accurate to five significant figures in the width of the confidence interval; that is the error for any one of the three estimates should be less than 0.00001×THETAU-THETAL.

8 Parallelism and Performance

G07EAF is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The time taken increases with the sample size n.

10 Example

The following program calculates a 95% confidence interval for θ, a measure of symmetry of the sample of 50 observations.

10.1 Program Text

Program Text (g07eafe.f90)

10.2 Program Data

Program Data (g07eafe.d)

10.3 Program Results

Program Results (g07eafe.r)

G07 Chapter Contents
G07 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


G07EBF : NAG Library, Mark 26

G07 Chapter Contents
G07 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

G07EBF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

G07EBF calculates a rank based (nonparametric) estimate and confidence interval for the difference in location between two independent populations.

2 Specification

SUBROUTINE G07EBF ( METHOD, N, X, M, Y, CLEVEL, THETA, THETAL, THETAU, ESTCL, ULOWER, UUPPER, WRK, IWRK, IFAIL)
INTEGER | N, M, IWRK(3*N), IFAIL
REAL (KIND=nag_wp) | X(N), Y(M), CLEVEL, THETA, THETAL, THETAU, ESTCL, ULOWER, UUPPER, WRK(3*(M+N))
CHARACTER(1) | METHOD

3 Description

Consider two random samples from two populations which have the same continuous distribution except for a shift in the location. Let the random sample, x=x 1,x 2,…,xn T, have distribution F x and the random sample, y=y 1,y 2,…,ym T, have distribution F x-θ.
G07EBF finds a point estimate, θ^, of the difference in location θ together with an associated confidence interval. The estimates are based on the ordered differences yj-xi. The estimate θ^ is defined by
θ^ = median yj-xi ,   i=1,2,…,n ; j=1,2,…,m .
Let dk, for k=1,2,…,nm, denote the nm (ascendingly) ordered differences yj-xi, for i=1,2,…,n and j=1,2,…,m. Then
  • if nm is odd, θ^=dk where k=nm-1/2;
  • if nm is even, θ^=dk+d k+1/2 where k=nm/2.
This estimator arises from inverting the two sample Mann–Whitney rank test statistic, U θ 0, for testing the hypothesis that θ=θ 0. Thus U θ 0 is the value of the Mann–Whitney U statistic for the two independent samples xi + θ 0 , for ​ i=1,2,…,n and yj , for ​ j=1,2,…,m . Effectively U θ 0 is a monotonically increasing step function of θ 0 with
mean ​U=μ= nm 2, var U=σ 2 nm n+m+1 12.
The estimate θ^ is the solution to the equation U θ^=μ; two methods are available for solving this equation. These methods avoid the computation of all the ordered differences dk; this is because for large n and m both the storage requirements and the computation time would be high.
The first is an exact method based on a set partitioning procedure on the set of all differences yj-xi, for i=1,2,…,n and j=1,2,…,m. This is adapted from the algorithm proposed by Monahan (1984) for the computation of the Hodges–Lehmann estimator for a single population.
The second is an iterative algorithm, based on the Illinois method which is a modification of the regula falsi method, see McKean and Ryan (1977). This algorithm has proved suitable for the function U θ 0 which is asymptotically linear as a function of θ 0.
The confidence interval limits are also based on the inversion of the Mann–Whitney test statistic.
Given a desired percentage for the confidence interval, 1-α, expressed as a proportion between 0.0 and 1.0 initial estimates of the upper and lower confidence limits for the Mann–Whitney U statistic are found;
Ul=μ-0.5+σ×Φ-1 α/2 Uu=μ+0.5+σ×Φ-1 1-α/2
where Φ-1 is the inverse cumulative Normal distribution function.
Ul and Uu are rounded to the nearest integer values. These estimates are refined using an exact method, without taking ties into account, if n+m≤40 and max n,m≤30 and a Normal approximation otherwise, to find Ul and Uu satisfying
P U≤Ul≤α/2 P U≤Ul+1>α/2
and
P U≥Uu≤α /2 P U≥Uu- 1>α /2.
The function U θ 0 is a monotonically increasing step function. It is the number of times a score in the second sample, yj, precedes a score in the first sample, xi+θ, where we only count a half if a score in the second sample actually equals a score in the first.
Let Ul=k; then θl=d k+1. This is the largest value θl such that U θl=Ul.
Let Uu=nm-k; then θu=d nm-k. This is the smallest value θu such that U θu=Uu.
As in the case of θ^, these equations may be solved using either the exact or iterative methods to find the values θl and θu.
Then θl,θu is the confidence interval for θ. The confidence interval is thus defined by those values of θ 0 such that the null hypothesis, θ=θ 0, is not rejected by the Mann–Whitney two sample rank test at the 100×α% level.

4 References

Lehmann E L (1975) Nonparametrics: Statistical Methods Based on Ranks Holden–Day
McKean J W and Ryan T A (1977) Algorithm 516: An algorithm for obtaining confidence intervals and point estimates based on ranks in the two-sample location problem ACM Trans. Math. Software 10 183–185
Monahan J F (1984) Algorithm 616: Fast computation of the Hodges–Lehman location estimator ACM Trans. Math. Software 10 265–270

5 Arguments

1:   METHOD – CHARACTER(1)Input
On entry: specifies the method to be used.
METHOD='E'
The exact algorithm is used.
METHOD='A'
The iterative algorithm is used.
Constraint: METHOD='E' or 'A'.
2:   N – INTEGERInput
On entry: n, the size of the first sample.
Constraint: N≥1.
3:   X N – REAL (KIND=nag_wp) arrayInput
On entry: the observations of the first sample, xi, for i=1,2,…,n.
4:   M – INTEGERInput
On entry: m, the size of the second sample.
Constraint: M≥1.
5:   Y M – REAL (KIND=nag_wp) arrayInput
On entry: the observations of the second sample, yj, for j=1,2,…,m.
6:   CLEVEL – REAL (KIND=nag_wp)Input
On entry: the confidence interval required, 1-α; e.g., for a 95% confidence interval set CLEVEL=0.95.
Constraint: 0.0<CLEVEL<1.0.
7:   THETA – REAL (KIND=nag_wp)Output
On exit: the estimate of the difference in the location of the two populations, θ^.
8:   THETAL – REAL (KIND=nag_wp)Output
On exit: the estimate of the lower limit of the confidence interval, θl.
9:   THETAU – REAL (KIND=nag_wp)Output
On exit: the estimate of the upper limit of the confidence interval, θu.
10:   ESTCL – REAL (KIND=nag_wp)Output
On exit: an estimate of the actual percentage confidence of the interval found, as a proportion between 0.0,1.0.
11:   ULOWER – REAL (KIND=nag_wp)Output
On exit: the value of the Mann–Whitney U statistic corresponding to the lower confidence limit, Ul.
12:   UUPPER – REAL (KIND=nag_wp)Output
On exit: the value of the Mann–Whitney U statistic corresponding to the upper confidence limit, Uu.
13:   WRK 3×M+N – REAL (KIND=nag_wp) arrayWorkspace
14:   IWRK 3×N – INTEGER arrayWorkspace
15:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, | METHOD≠'E' or 'A',
or | N<1,
or | M<1,
or | CLEVEL≤0.0,
or | CLEVEL≥1.0.
IFAIL=2
Each sample consists of identical values. All estimates are set to the common difference between the samples.
IFAIL=3
For at least one of the estimates θ^, θl and θu, the underlying iterative algorithm (when METHOD='A') failed to converge. This is an unlikely exit but the estimate should still be a reasonable approximation.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

G07EBF should return results accurate to five significant figures in the width of the confidence interval, that is the error for any one of the three estimates should be less than 0.00001×THETAU-THETAL.

8 Parallelism and Performance

G07EBF is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
G07EBF makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The time taken increases with the sample sizes n and m.

10 Example

The following program calculates a 95% confidence interval for the difference in location between the two populations from which the two samples of sizes 50 and 100 are drawn respectively.

10.1 Program Text

Program Text (g07ebfe.f90)

10.2 Program Data

Program Data (g07ebfe.d)

10.3 Program Results

Program Results (g07ebfe.r)

G07 Chapter Contents
G07 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


G07GAF : NAG Library, Mark 26

G07 Chapter Contents
G07 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

G07GAF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

G07GAF identifies outlying values using Peirce's criterion.

2 Specification

SUBROUTINE G07GAF ( N, P, Y, MEAN, VAR, IOUT, NIOUT, LDIFF, DIFF, LLAMB, IFAIL)
INTEGER | N, P, IOUT(N), NIOUT, LDIFF, IFAIL
REAL (KIND=nag_wp) | Y(N), MEAN, VAR, DIFF(LDIFF), LLAMB(LDIFF)

3 Description

G07GAF flags outlying values in data using Peirce's criterion. Let
  • y denote a vector of n observations (for example the residuals) obtained from a model with p parameters,
  • m denote the number of potential outlying values,
  • μ and σ 2 denote the mean and variance of y respectively,
  • y~ denote a vector of length n-m constructed by dropping the m values from y with the largest value of yi-μ,
  • σ~2 denote the (unknown) variance of y~,
  • λ denote the ratio of σ~ and σ with λ = σ~ σ .
Peirce's method flags yi as a potential outlier if yi-μ≥x, where x=σ 2 z and z is obtained from the solution of
Rm = λ m-n mm n-m n-m nn (1)
where
R = 2 exp z 2 - 1 2 1- Φ z (2)
and Φ is the cumulative distribution function for the standard Normal distribution.
As σ~2 is unknown an assumption is made that the relationship between σ~2 and σ 2, hence λ, depends only on the sum of squares of the rejected observations and the ratio estimated as
λ 2 = n-p-m z 2 n-p-m
which gives
z 2 = 1+ n-p-m m 1-λ 2 (3)
A value for the cutoff x is calculated iteratively. An initial value of R=0.2 is used and a value of λ is estimated using equation (1). Equation (3) is then used to obtain an estimate of z and then equation (2) is used to get a new estimate for R. This process is then repeated until the relative change in z between consecutive iterations is ≤ε, where ε is machine precision.
By construction, the cutoff for testing for m+1 potential outliers is less than the cutoff for testing for m potential outliers. Therefore Peirce's criterion is used in sequence with the existence of a single potential outlier being investigated first. If one is found, the existence of two potential outliers is investigated etc.
If one of a duplicate series of observations is flagged as an outlier, then all of them are flagged as outliers.

4 References

Gould B A (1855) On Peirce's criterion for the rejection of doubtful observations, with tables for facilitating its application The Astronomical Journal 45
Peirce B (1852) Criterion for the rejection of doubtful observations The Astronomical Journal 45

5 Arguments

1:   N – INTEGERInput
On entry: n, the number of observations.
Constraint: N≥3.
2:   P – INTEGERInput
On entry: p, the number of parameters in the model used in obtaining the y. If y is an observed set of values, as opposed to the residuals from fitting a model with p parameters, then p should be set to 1, i.e., as if a model just containing the mean had been used.
Constraint: 1≤P≤N-2.
3:   Y N – REAL (KIND=nag_wp) arrayInput
On entry: y, the data being tested.
4:   MEAN – REAL (KIND=nag_wp)Input
On entry: if VAR>0.0, MEAN must contain μ, the mean of y, otherwise MEAN is not referenced and the mean is calculated from the data supplied in Y.
5:   VAR – REAL (KIND=nag_wp)Input
On entry: if VAR>0.0, VAR must contain σ 2, the variance of y, otherwise the variance is calculated from the data supplied in Y.
6:   IOUT N – INTEGER arrayOutput
On exit: the indices of the values in Y sorted in descending order of the absolute difference from the mean, therefore Y IOUT i-1 - μ ≥ Y IOUT i - μ , for i=2,3,…,N.
7:   NIOUT – INTEGEROutput
On exit: the number of potential outliers. The indices for these potential outliers are held in the first NIOUT elements of IOUT. By construction there can be at most N-P-1 values flagged as outliers.
8:   LDIFF – INTEGERInput
On entry: the maximum number of values to be returned in arrays DIFF and LLAMB.
If LDIFF≤0, arrays DIFF and LLAMB are not referenced.
9:   DIFF LDIFF – REAL (KIND=nag_wp) arrayOutput
On exit: DIFF i holds y-μ-σ 2 z for observation Y IOUT i, for i=1,2,…,min LDIFF,NIOUT+1,N-P-1.
10:   LLAMB LDIFF – REAL (KIND=nag_wp) arrayOutput
On exit: LLAMB i holds log λ 2 for observation Y IOUT i, for i=1,2,…,min LDIFF,NIOUT+1,N-P-1.
11:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, N=value.
Constraint: N≥3.
IFAIL=2
On entry, P=value and N=value.
Constraint: 1≤P≤N-2.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

Not applicable.

8 Parallelism and Performance

G07GAF is not threaded in any implementation.

9 Further Comments

One problem with Peirce's algorithm as implemented in G07GAF is the assumed relationship between σ 2, the variance using the full dataset, and σ~2, the variance with the potential outliers removed. In some cases, for example if the data y were the residuals from a linear regression, this assumption may not hold as the regression line may change significantly when outlying values have been dropped resulting in a radically different set of residuals. In such cases G07GBF should be used instead.

10 Example

This example reads in a series of data and flags any potential outliers.
The dataset used is from Peirce's original paper and consists of fifteen observations on the vertical semidiameter of Venus.

10.1 Program Text

Program Text (g07gafe.f90)

10.2 Program Data

Program Data (g07gafe.d)

10.3 Program Results

Program Results (g07gafe.r)

G07 Chapter Contents
G07 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


G07GBF : NAG Library, Mark 26

G07 Chapter Contents
G07 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

G07GBF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

G07GBF returns a flag indicating whether a single data point is an outlier as defined by Peirce's criterion.

2 Specification

FUNCTION G07GBF ( N, E, VAR1, VAR2, X, LX, UX, IFAIL)
LOGICAL G07GBF
INTEGER | N, IFAIL
REAL (KIND=nag_wp) | E, VAR1, VAR2, X, LX, UX

3 Description

G07GBF tests a potential outlying value using Peirce's criterion. Let
  • e denote a vector of n residuals with mean zero and variance σ 2 obtained from fitting some model M to a series of data y,
  • e~ denote the largest absolute residual in e, i.e., e~ ≥ ei for all i, and let y~ denote the data series y with the observation corresponding to e~ having been omitted,
  • σ~2 denote the residual variance on fitting model M to y~,
  • λ denote the ratio of σ~ and σ with λ = σ~ σ .
Peirce's method flags e~ as a potential outlier if e~≥x, where x=σ 2 z and z is obtained from the solution of
R = λ 1-n n-1 n-1 nn (1)
where
R = 2 exp z 2 - 1 2 1- Φ z (2)
and Φ is the cumulative distribution function for the standard Normal distribution.
Unlike G07GAF, both σ 2 and σ~2 must be supplied and therefore no assumptions are made about the nature of the relationship between these two quantities. Only a single potential outlier is tested for at a time.
This routine uses an algorithm described in E04ABF/E04ABA to refine a lower, l, and upper, u, limit for x. This refinement stops when e~<l or e~>u.

4 References

Gould B A (1855) On Peirce's criterion for the rejection of doubtful observations, with tables for facilitating its application The Astronomical Journal 45
Peirce B (1852) Criterion for the rejection of doubtful observations The Astronomical Journal 45

5 Arguments

1:   N – INTEGERInput
On entry: n, the number of observations.
Constraint: N≥3.
2:   E – REAL (KIND=nag_wp)Input
On entry: e~, the value being tested.
3:   VAR1 – REAL (KIND=nag_wp)Input
On entry: σ 2, the residual variance on fitting model M to y.
Constraint: VAR1>0.0.
4:   VAR2 – REAL (KIND=nag_wp)Input
On entry: σ~2, the residual variance on fitting model M to y~.
Constraints:
  • VAR2>0.0;
  • VAR2<VAR1.
5:   X – REAL (KIND=nag_wp)Output
On exit: an estimated value of x, the cutoff that indicates an outlier.
6:   LX – REAL (KIND=nag_wp)Output
On exit: l, the lower limit for x.
7:   UX – REAL (KIND=nag_wp)Output
On exit: u, the upper limit for x.
8:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, N=value.
Constraint: N≥3.
IFAIL=3
On entry, VAR1=value.
Constraint: VAR1>0.0.
IFAIL=4
On entry, VAR1=value, VAR2=value.
Constraint: VAR2<VAR1.
On entry, VAR2=value.
Constraint: VAR2>0.0.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

Not applicable.

8 Parallelism and Performance

G07GBF is not threaded in any implementation.

9 Further Comments

None.

10 Example

This example reads in a series of values and variances and checks whether each is a potential outlier.
The dataset used is from Peirce's original paper and consists of fifteen observations on the vertical semidiameter of Venus. Each subsequent line in the dataset, after the first, is the result of dropping the observation with the highest absolute value from the previous data and recalculating the variance.

10.1 Program Text

Program Text (g07gbfe.f90)

10.2 Program Data

Program Data (g07gbfe.d)

10.3 Program Results

Program Results (g07gbfe.r)

G07 Chapter Contents
G07 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


G07 Chapter Introduction : NAG Library, Mark 26

G07 Chapter Contents
NAG Library Manual

NAG Library Chapter Introduction

G07 – Univariate Estimation

▸▿ Contents

1 Scope of the Chapter
▸▿ 2 Background to the Problems
2.1 Maximum Likelihood Estimation
2.2 Confidence Intervals
2.3 Robust Estimation
2.4 Robust Confidence Intervals
3 Recommendations on Choice and Use of Available Routines
4 Functionality Index
5 Auxiliary Routines Associated with Library Routine Arguments
6 Routines Withdrawn or Scheduled for Withdrawal
7 References

1 Scope of the Chapter

This chapter deals with the estimation of unknown parameters of a univariate distribution. It includes both point and interval estimation using maximum likelihood and robust methods.

2 Background to the Problems

Statistical inference is concerned with the making of inferences about a population using the observed part of the population called a sample. The population can usually be described using a probability model which will be written in terms of some unknown parameters. For example, the hours of relief given by a drug may be assumed to follow a Normal distribution with mean μ and variance σ 2; it is then required to make inferences about the parameters, μ and σ 2, on the basis of an observed sample of relief times.
There are two main aspects of statistical inference: the estimation of the parameters and the testing of hypotheses about the parameters. In the example above, the values of the parameter σ 2 may be estimated and the hypothesis that μ≥3 tested. This chapter is mainly concerned with estimation but the test of a hypothesis about a parameter is often closely linked to its estimation. Tests of hypotheses which are not linked closely to estimation are given in the chapter on nonparametric statistics (Chapter G08).
There are two types of estimation to be considered in this chapter: point estimation and interval estimation. Point estimation is when a single value is obtained as the best estimate of the parameter. However, as this estimate will be based on only one of a large number of possible samples, it can be seen that if a different sample were taken, a different estimate would be obtained. The distribution of the estimate across all the possible samples is known as the sampling distribution. The sampling distribution contains information on the performance of the estimator, and enables estimators to be compared. For example, a good estimator would have a sampling distribution with mean equal to the true value of the parameter; that is, it should be an unbiased estimator; also the variance of the sampling distribution should be as small as possible. When considering a parameter estimate it is important to consider its variability as measured by its variance, or more often the square root of the variance, the standard error.
The sampling distribution can be used to find interval estimates or confidence intervals for the parameter. A confidence interval is an interval calculated from the sample so that its distribution, as given by the sampling distribution, is such that it contains the true value of the parameter with a certain probability.
Estimates will be functions of the observed sample and these functions are known as estimators. It is usually more convenient for the estimator to be based on statistics from the sample rather than all the individuals observations. If these statistics contain all the relevant information then they are known as sufficient statistics. There are several ways of obtaining the estimators; these include least squares, the method of moments, and maximum likelihood. Least squares estimation requires no knowledge of the distributional form of the error apart from its mean and variance matrix, whereas the method of maximum likelihood is mainly applicable to situations in which the true distribution is known apart from the values of a finite number of unknown parameters. Note that under the assumption of Normality, the least squares estimation is equivalent to the maximum likelihood estimation. Least squares is often used in regression analysis as described in Chapter G02, and maximum likelihood is described below.
Estimators derived from least squares or maximum likelihood will often be greatly affected by the presence of extreme or unusual observations. Estimators that are designed to be less affected are known as robust estimators.

2.1 Maximum Likelihood Estimation

Let Xi be a univariate random variable with probability density function
f Xi xi;θ,
where θ is a vector of length p consisting of the unknown parameters. For example, a Normal distribution with mean θ 1 and standard deviation θ 2 has probability density function
1 2 π θ 2 exp-12 xi-θ 1 θ 2 2 .
The likelihood for a sample of n independent observations is
Like=∏i=1 n f Xi xi;θ ,
where xi is the observed value of Xi. If each Xi has an identical distribution, this reduces to
Like=∏i=1 n fX xi;θ , (1)
and the log-likelihood is
log Like=L=∑i=1 n log fX xi;θ. (2)
The maximum likelihood estimates (θ^) of θ are the values of θ that maximize (1) and (2). If the range of X is independent of the parameters, then θ^ can usually be found as the solution to
∑i=1 n ∂∂θ^j log fX xi;θ^= ∂L ∂θ^j =0,  j=1,2,…,p. (3)
Note that ∂L ∂θj is known as the efficient score.
Maximum likelihood estimators possess several important properties.
(a) | Maximum likelihood estimators are functions of the sufficient statistics.
(b) | Maximum likelihood estimators are (under certain conditions) consistent. That is, the estimator converges in probability to the true value as the sample size increases. Note that for small samples the maximum likelihood estimator may be biased.
(c) For maximum likelihood estimators found as a solution to (3), subject to certain conditions, it follows that
E ∂L ∂θ =0, (4)
and
I θ=-E ∂2 L ∂θ 2 =E ∂L ∂θ 2 , (5)
and then that θ^ is asymptotically Normal with mean vector θ 0 and variance-covariance matrix I θ 0-1 where θ 0 denotes the true value of θ. The matrix Iθ is known as the information matrix and I θ 0-1 is known as the Cramer–Rao lower bound for the variance of an estimator of θ.
For example, if we consider a sample, x 1,x 2,…,xn, of size n drawn from a Normal distribution with unknown mean μ and unknown variance σ 2 then we have
L=log Like μ,σ 2;x=-n 2 log 2 π-n 2 log σ 2-∑i=1 n xi-μ 2/2 σ 2
and thus
∂L ∂μ =∑i= 1 n xi-μ/σ 2
and
∂L ∂σ 2 =-n 2 σ 2 +∑i=1 n xi-μ 2/2 σ 4.
Then equating these two equations to zero and solving gives the maximum likelihood estimates
μ^=x-
and
σ^2=∑i=1 n xi-x- 2/n.
These maximum likelihood estimates are asymptotically Normal with mean vector a, where
aT=μ,σ 2,
and covariance matrix C. To obtain C we find the second derivatives of L with respect to μ and σ 2 as follows:
∂2 L ∂μ 2 =- n σ 2 ∂2 L ∂σ 2 2 = n 2 σ 4 -∑i=1 n xi-μ 2/σ 6 ∂2 L ∂μ∂σ 2 = ∂2 L ∂σ 2∂μ =- n x--μ σ 4.
Then
C-1=-E ∂2 L ∂μ 2 ∂2 L ∂σ 2∂μ ∂2 L ∂μ∂σ 2 ∂2 L ∂σ 2 2 = n/σ 2 0 0 n/2 σ 4
so that
C= σ 2/n 0 0 2 σ 4/n .
To obtain an estimate of C the matrix may be evaluated at the maximum likelihood estimates.
It may not always be possible to find maximum likelihood estimates in a convenient closed form, and in these cases iterative numerical methods, such as the Newton–Raphson procedure or the EM algorithm (expectation maximization), will be necessary to compute the maximum likelihood estimates. Their asymptotic variances and covariances may then be found by substituting the estimates into the second derivatives. Note that it may be difficult to find the expected value of the second derivatives required for the variance-covariance matrix and in these cases the observed value of the second derivatives is often used.
The use of maximum likelihood estimation allows the construction of generalized likelihood ratio tests. If λ=2 l 1-l 2, where l 1 is the maximized log-likelihood function for a model 1 and l 2 is the maximized log-likelihood function for a model 2, then under the hypothesis that model 2 is correct, 2 λ is asymptotically distributed as a χ 2 variable with p-q degrees of freedom. Consider two models in which model 1 has p parameters and model 2 is a sub-model (nested model) of model 1 with q<p parameters, that is model 1 has an extra p-q parameters. This result provides a useful method for performing hypothesis tests on the parameters. Alternatively, tests exist based on the asymptotic Normality of the estimator and the efficient score; see page 315 of Cox and Hinkley (1974).

2.2 Confidence Intervals

Suppose we can find a function, t x,θ, whose distribution depends upon the sample x but not on the unknown parameter θ, and which is a monotonic (say decreasing) function in θ for each x, then we can find t 1 such that P t 1 ≤ t x,θ = 1 - α no matter what θ happens to be. The function t x,θ is known as a pivotal quantity. Since the function is monotonic the statement that t 1≤t x,θ may be rewritten as θ≥θ 1 x see Figure 1. The statistic θ 1 x will vary from sample to sample and if we assert that θ≥θ 1 x for any sample values which arise, we will be right in a proportion 1-α of the cases, in the long run or on average. We call θ 1 x a 1-α upper confidence limit for θ.
Figure 1
We have considered only an upper confidence limit. The above idea may be generalized to a two-sided confidence interval where two quantities, t 0 and t 1, are found such that for all θ, P t 1 ≤ t x,θ ≤ t 0 = 1 - α . This interval may be rewritten as θ 0 x≤θ≤θ 1 x. Thus if we assert that θ lies in the interval [θ 0 x,θ 1 x] we will be right on average in 1-α proportion of the times under repeated sampling.
Hypothesis (significance) tests on the parameters may be used to find these confidence limits. For example, if we observe a value, k, from a binomial distribution, with known parameter n and unknown parameter p, then to find the lower confidence limit we find pl such that the probability that the null hypothesis H 0: p=pl (against the one sided alternative that p>pl) will be rejected, is less than or equal to α/2. Thus for a binomial random variable, B, with parameters n and pl we require that P B≥k≤α/2. The upper confidence limit, pu, can be constructed in a similar way.
For large samples the asymptotic Normality of the maximum likelihood estimates discussed above is used to construct confidence intervals for the unknown parameters.

2.3 Robust Estimation

For particular cases the probability density function can be written as
f Xi xi;θ=1 θ 2 g xi-θ 1 θ 2
for a suitable function g; then θ 1 is known as a location parameter and θ 2, usually written as σ, is known as a scale parameter. This is true of the Normal distribution.
If θ 1 is a location parameter, as described above, then equation (3) becomes
∑i=1 n ψ xi-θ^1 σ^=0, (6)
where ψ z=- d dz log g z.
For the scale parameter σ (or σ 2) the equation is
∑i=1 n χ xi-θ^1 σ^=n/2, (7)
where χ z=zψ z/2.
For the Normal distribution ψ z=z and χ z=z 2/2. Thus, the maximum likelihood estimates for θ 1 and σ 2 are the sample mean and variance with the n divisor respectively. As the latter is biased, (7) can be replaced by
∑i=1 n χ xi-θ^1 σ^=n-1 β, (8)
where β is a suitable constant, which for the Normal χ function is 12 .
The influence of an observation on the estimates depends on the form of the ψ and χ functions. For a discussion of influence, see Hampel et al. (1986) and Huber (1981). The influence of extreme values can be reduced by bounding the values of the ψ- and χ-functions. One suggestion due to Huber (1981) is
ψ z= -C, ||z<-C z, z≤C C, ||z>C.
Figure 2
Redescending ψ-functions are often considered; these give zero values to ψ z for large positive or negative values of z. Hampel et al. (1986) suggested
ψ z= -ψ-z z, 0≤z≤h 1. h 1, h 1≤z≤h 2. h 1 h 3-z/h 3-h 2, h 2≤z≤h 3. 0, z>h 3.
Figure 3
Usually a χ-function based on Huber's ψ-function is used: χ=ψ 2/2. Estimators based on such bounded ψ-functions are known as M-estimators, and provide one type of robust estimator.
Other robust estimators for the location parameter are
(i) | the sample median,
(ii) | the trimmed mean, i.e., the mean calculated after the extreme values have been removed from the sample,
(iii) | the winsorized mean, i.e., the mean calculated after the extreme values of the sample have been replaced by other more moderate values from the sample.
For the scale parameter, alternative estimators are
(i) | the median absolute deviation scaled to produce an estimator which is unbiased in the case of data coming from a Normal distribution,
(ii) | the winsorized variance, i.e., the variance calculated after the extreme values of the sample have been replaced by other more moderate values from the sample.
For a general discussion of robust estimation, see Hampel et al. (1986) and Huber (1981).

2.4 Robust Confidence Intervals

In Section 2.2 it was shown how tests of hypotheses can be used to find confidence intervals. That approach uses a parametric test that requires the assumption that the data used in the computation of the confidence has a known distribution. As an alternative, a more robust confidence interval can be found by replacing the parametric test by a nonparametric test. In the case of the confidence interval for the location parameter, a Wilcoxon test statistic can be used, and for the difference in location, computed from two samples, a Mann–Whitney test statistic can be used.

3 Recommendations on Choice and Use of Available Routines

Maximum Likelihood Estimation and Confidence Intervals
G07AAF provides a confidence interval for the parameter p of the binomial distribution.
G07ABF provides a confidence interval for the mean parameter of the Poisson distribution.
G07BBF provides maximum likelihood estimates and their standard errors for the parameters of the Normal distribution from grouped and/or censored data.
G07BEF provides maximum likelihood estimates and their standard errors for the parameters of the Weibull distribution from data which may be right-censored.
G07BFF provides maximum likelihood estimates and their standard errors for the parameters of the generalized Pareto distribution.
G07CAF provides a t-test statistic to test for a difference in means between two Normal populations, together with a confidence interval for the difference between the means.
Robust Estimation
G07DBF provides M-estimates for location and, optionally, scale using four common forms of the ψ-function.
G07DCF produces the M-estimates for location and, optionally, scale but for user-supplied ψ- and χ-functions.
G07DAF provides the sample median, median absolute deviation, and the scaled value of the median absolute deviation.
G07DDF provides the trimmed mean and winsorized mean together with estimates of their variance based on a winsorized variance.
Robust Internal Estimation
G07EAF produces a rank based confidence interval for locations.
G07EBF produces a rank based confidence interval for the difference in location between two populations.
Outlier Detection
This chapter provides two routines for identifying potential outlying values, G07GAF and G07GBF. Many of the model fitting routines, for examples those in Chapters G02 and G13 also return vectors of residuals which can also be used to aid in the identification of outlying values.

4 Functionality Index

2 sample t-test G07CAF
Confidence intervals for parameters,
binomial distribution G07AAF
Poisson distribution G07ABF
Maximum likelihood estimation of parameters,
Normal distribution, grouped and/or censored data G07BBF
Weibull distribution G07BEF
Outlier detection,
Peirce,
raw data or single variance supplied G07GAF
two variances supplied G07GBF
Parameter estimates,
generalized Pareto distribution G07BFF
Robust estimation,
confidence intervals,
one sample G07EAF
two samples G07EBF
median, median absolute deviation and robust standard deviation G07DAF
M-estimates for location and scale parameters,
standard weight functions G07DBF
trimmed and winsorized means and estimates of their variance G07DDF
user-defined weight functions G07DCF

5 Auxiliary Routines Associated with Library Routine Arguments

None.

6 Routines Withdrawn or Scheduled for Withdrawal

None.

7 References

Cox D R and Hinkley D V (1974) Theoretical Statistics Chapman and Hall
Hampel F R, Ronchetti E M, Rousseeuw P J and Stahel W A (1986) Robust Statistics. The Approach Based on Influence Functions Wiley
Huber P J (1981) Robust Statistics Wiley
Kendall M G and Stuart A (1973) The Advanced Theory of Statistics (Volume 2) (3rd Edition) Griffin
Silvey S D (1975) Statistical Inference Chapman and Hall
G07 Chapter Contents
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


G08AAF : NAG Library, Mark 26

G08 Chapter Contents
G08 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

G08AAF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

G08AAF performs the Sign test on two related samples of size n.

2 Specification

SUBROUTINE G08AAF ( X, Y, N, ISGN, N1, P, IFAIL)
INTEGER | N, ISGN, N1, IFAIL
REAL (KIND=nag_wp) | X(N), Y(N), P

3 Description

The Sign test investigates the median difference between pairs of scores from two matched samples of size n, denoted by xi,yi, for i=1,2,…,n. The hypothesis under test, H 0, often called the null hypothesis, is that the medians are the same, and this is to be tested against a one- or two-sided alternative H 1 (see below).
G08AAF computes:
(a) | the test statistic S, which is the number of pairs for which xi<yi;
(b) | the number n 1 of non-tied pairs xi≠yi;
(c) | the lower tail probability p corresponding to S (adjusted to allow the complement 1-p to be used in an upper one tailed or a two tailed test). p is the probability of observing a value ≤S if S<12 n 1, or of observing a value <S if S>12 n 1, given that H 0 is true. If S=12 n 1, p is set to 0.5.
Suppose that a significance test of a chosen size α is to be performed (i.e., α is the probability of rejecting H 0 when H 0 is true; typically α is a small quantity such as 0.05 or 0.01). The returned value of p can be used to perform a significance test on the median difference, against various alternative hypotheses H 1, as follows
(i) | H 1: median of x≠ median of y. H 0 is rejected if 2 × min p,1-p < α .
(ii) | H 1: median of x> median of y. H 0 is rejected if p<α.
(iii) | H 1: median of x< median of y. H 0 is rejected if 1-p<α.

4 References

Siegel S (1956) Non-parametric Statistics for the Behavioral Sciences McGraw–Hill

5 Arguments

1:   X N – REAL (KIND=nag_wp) arrayInput
2:   Y N – REAL (KIND=nag_wp) arrayInput
On entry: X i and Y i must be set to the ith pair of data values, xi,yi, for i=1,2,…,n.
3:   N – INTEGERInput
On entry: n, the size of each sample.
Constraint: N≥1.
4:   ISGN – INTEGEROutput
On exit: the Sign test statistic, S.
5:   N1 – INTEGEROutput
On exit: the number of non-tied pairs, n 1.
6:   P – REAL (KIND=nag_wp)Output
On exit: the lower tail probability, p, corresponding to S.
7:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, N<1.
IFAIL=2
N1=0, i.e., the samples are identical.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

The tail probability, p, is computed using the relationship between the binomial and beta distributions. For n 1<120, p should be accurate to at least 4 significant figures, assuming that the machine has a precision of 7 or more digits. For n 1≥120, p should be computed with an absolute error of less than 0.005. For further details see G01EEF.

8 Parallelism and Performance

G08AAF is not threaded in any implementation.

9 Further Comments

The time taken by G08AAF is small, and increases with n.

10 Example

This example is taken from page 69 of Siegel (1956). The data relates to ratings of ‘insight into paternal discipline’ for 17 sets of parents, recorded on a scale from 1 to 5.

10.1 Program Text

Program Text (g08aafe.f90)

10.2 Program Data

Program Data (g08aafe.d)

10.3 Program Results

Program Results (g08aafe.r)

G08 Chapter Contents
G08 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


G08ACF : NAG Library, Mark 26

G08 Chapter Contents
G08 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

G08ACF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

G08ACF performs the Median test on two independent samples of possibly unequal size.

2 Specification

SUBROUTINE G08ACF ( X, N, N1, W, I1, I2, P, IFAIL)
INTEGER | N, N1, I1, I2, IFAIL
REAL (KIND=nag_wp) | X(N), W(N), P

3 Description

The Median test investigates the difference between the medians of two independent samples of sizes n 1 and n 2, denoted by:
x 1,x 2,…,x n 1
and
x n 1+ 1, x n 1+ 2,…, xn,
where n=n 1+n 2.
The hypothesis under test, H 0, often called the null hypothesis, is that the medians are the same, and this is to be tested against the alternative hypothesis H 1 that they are different.
The test proceeds by forming a 2×2 frequency table, giving the number of scores in each sample above and below the median of the pooled sample:
 | Sample 1 | Sample 2 | Total
Scores < pooled median | i 1 | i 2 | i 1+i 2
Scores ≥ pooled median | n 1-i 1 | n 2-i 2 | n-i 1+i 2
Total | n 1 | n 2 | n
Under the null hypothesis, H 0, we would expect about half of each group's scores to be above the pooled median and about half below, that is, we would expect i 1, to be about n 1/2 and i 2 to be about n 2/2.
G08ACF returns:
(a) | the frequencies i 1 and i 2;
(b) | the probability, p, of observing a table at least as ‘extreme’ as that actually observed, given that H 0 is true. If n<40, p is computed directly (‘Fisher's exact test’); otherwise a χ 12 approximation is used (see G01AFF).
H 0 is rejected by a test of chosen size α if p<α.

4 References

Siegel S (1956) Non-parametric Statistics for the Behavioral Sciences McGraw–Hill

5 Arguments

1:   X N – REAL (KIND=nag_wp) arrayInput
On entry: the first n 1 elements of X must be set to the data values in the first sample, and the next n 2 (=N-n 1) elements to the data values in the second sample.
2:   N – INTEGERInput
On entry: the total of the two sample sizes, n (=n 1+n 2).
Constraint: N≥2.
3:   N1 – INTEGERInput
On entry: the size of the first sample n 1.
Constraint: 1≤N1<N.
4:   W N – REAL (KIND=nag_wp) arrayWorkspace
5:   I1 – INTEGEROutput
On exit: the number of scores in the first sample which lie below the pooled median, i 1.
6:   I2 – INTEGEROutput
On exit: the number of scores in the second sample which lie below the pooled median, i 2.
7:   P – REAL (KIND=nag_wp)Output
On exit: the tail probability p corresponding to the observed dichotomy of the two samples.
8:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, N<2.
IFAIL=2
On entry, | N1<1,
or | N1≥N.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

The probability returned should be accurate enough for practical use.

8 Parallelism and Performance

G08ACF is not threaded in any implementation.

9 Further Comments

The time taken by G08ACF is small, and increases with n.

10 Example

This example is taken from page 112 of Siegel (1956). The data relate to scores of ‘oral socialisation anxiety’ in 39 societies, which can be separated into groups of size 16 and 23 on the basis of their attitudes to illness.

10.1 Program Text

Program Text (g08acfe.f90)

10.2 Program Data

Program Data (g08acfe.d)

10.3 Program Results

Program Results (g08acfe.r)

G08 Chapter Contents
G08 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


G08AEF : NAG Library, Mark 26

G08 Chapter Contents
G08 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

G08AEF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

G08AEF performs the Friedman two-way analysis of variance by ranks on k related samples of size n.

2 Specification

SUBROUTINE G08AEF ( X, LDX, K, N, W1, W2, FR, P, IFAIL)
INTEGER | LDX, K, N, IFAIL
REAL (KIND=nag_wp) | X(LDX,N), W1(K), W2(K), FR, P

3 Description

The Friedman test investigates the score differences between k matched samples of size n, the scores in the ith sample being denoted by
x i 1,x i 2,…,x in.
(Thus the sample scores may be regarded as a two-way table with k rows and n columns.) The hypothesis under test, H 0, often called the null hypothesis, is that the samples come from the same population, and this is to be tested against the alternative hypothesis H 1 that they come from different populations.
The test is based on the observed distribution of score rankings between the matched observations in different samples.
The test proceeds as follows
(a) | The scores in each column are ranked, r ij denoting the rank within column j of the observation in row i. Average ranks are assigned to tied scores.
(b) | The ranks are summed over each row to give rank sums ti=∑j=1 n r ij, for i=1,2,…,k.
(c) The Friedman test statistic F is computed, where
F=12 nk k+1 ∑i=1 k ti-12 n k+1 2.
G08AEF returns the value of F, and also an approximation, p, to the significance of this value. (F approximately follows a χ k-1 2 distribution, so large values of F imply rejection of H 0). H 0 is rejected by a test of chosen size α if p<α. The approximation p is acceptable unless k=4 and n<5, or k=3 and n<10, or k=2 and n<20; for k=3​ or ​4, tables should be consulted (e.g., Siegel (1956)); for k=2 the Sign test (see G08AAF) or Wilcoxon test (see G08AGF) is in any case more appropriate.

4 References

Siegel S (1956) Non-parametric Statistics for the Behavioral Sciences McGraw–Hill

5 Arguments

1:   X LDXN – REAL (KIND=nag_wp) arrayInput
On entry: X ij must be set to the value, x ij, of observation j in sample i, for i=1,2,…,k and j=1,2,…,n.
2:   LDX – INTEGERInput
On entry: the first dimension of the array X as declared in the (sub)program from which G08AEF is called.
Constraint: LDX≥K.
3:   K – INTEGERInput
On entry: k, the number of samples.
Constraint: K≥2.
4:   N – INTEGERInput
On entry: n, the size of each sample.
Constraint: N≥1.
5:   W1 K – REAL (KIND=nag_wp) arrayWorkspace
6:   W2 K – REAL (KIND=nag_wp) arrayWorkspace
7:   FR – REAL (KIND=nag_wp)Output
On exit: the value of the Friedman test statistic, F.
8:   P – REAL (KIND=nag_wp)Output
On exit: the approximate significance, p, of the Friedman test statistic.
9:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, N<1.
IFAIL=2
On entry, LDX<K.
IFAIL=3
On entry, K≤1.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

For estimates of the accuracy of the significance p, see G01ECF. The χ 2 approximation is acceptable unless k=4 and n<5, or k=3 and n<10, or k=2 and n<20.

8 Parallelism and Performance

G08AEF is not threaded in any implementation.

9 Further Comments

The time taken by G08AEF is approximately proportional to the product nk.
If k=2, the Sign test (see G08AAF) or Wilcoxon test (see G08AGF) is more appropriate.

10 Example

This example is taken from page 169 of Siegel (1956). The data relates to training scores of three matched samples of 18 rats, trained under three different patterns of reinforcement.

10.1 Program Text

Program Text (g08aefe.f90)

10.2 Program Data

Program Data (g08aefe.d)

10.3 Program Results

Program Results (g08aefe.r)

G08 Chapter Contents
G08 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


G08AFF : NAG Library, Mark 26

G08 Chapter Contents
G08 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

G08AFF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

G08AFF performs the Kruskal–Wallis one-way analysis of variance by ranks on k independent samples of possibly unequal sizes.

2 Specification

SUBROUTINE G08AFF ( X, LX, L, K, W, H, P, IFAIL)
INTEGER | LX, L(K), K, IFAIL
REAL (KIND=nag_wp) | X(LX), W(LX), H, P

3 Description

The Kruskal–Wallis test investigates the differences between scores from k independent samples of unequal sizes, the ith sample containing li observations. The hypothesis under test, H 0, often called the null hypothesis, is that the samples come from the same population, and this is to be tested against the alternative hypothesis H 1 that they come from different populations.
The test proceeds as follows:
(a) | The pooled sample of all the observations is ranked. Average ranks are assigned to tied scores.
(b) | The ranks of the observations in each sample are summed, to give the rank sums Ri, for i=1,2,…,k.
(c) The Kruskal–Wallis' test statistic H is computed as:
H=12 N N+1 ∑i=1 k Ri 2 li-3 N+1,   where ​N=∑i=1 k li,
i.e., N is the total number of observations. If there are tied scores, H is corrected by dividing by:
1-∑t 3-t N 3-N
where t is the number of tied scores in a sample and the summation is over all tied samples.
G08AFF returns the value of H, and also an approximation, p, to the probability of a value of at least H being observed, H 0 is true. (H approximately follows a χ k-1 2 distribution). H 0 is rejected by a test of chosen size α if p<α. The approximation p is acceptable unless k=3 and l 1, l 2 or l 3≤5 in which case tables should be consulted (e.g., O of Siegel (1956)) or k=2 (in which case the Median test (see G08ACF) or the Mann–Whitney U test (see G08AHF) is more appropriate).

4 References

Moore P G, Shirley E A and Edwards D E (1972) Standard Statistical Calculations Pitman
Siegel S (1956) Non-parametric Statistics for the Behavioral Sciences McGraw–Hill

5 Arguments

1:   X LX – REAL (KIND=nag_wp) arrayInput
On entry: the elements of X must contain the observations in the K samples. The first l 1 elements must contain the scores in the first sample, the next l 2 those in the second sample, and so on.
2:   LX – INTEGERInput
On entry: N, the total number of observations.
Constraint: LX=∑i=1 k L i.
3:   L K – INTEGER arrayInput
On entry: L i must contain the number of observations li in sample i, for i=1,2,…,k.
Constraint: L i>0, for i=1,2,…,k.
4:   K – INTEGERInput
On entry: k, the number of samples.
Constraint: K≥2.
5:   W LX – REAL (KIND=nag_wp) arrayWorkspace
6:   H – REAL (KIND=nag_wp)Output
On exit: the value of the Kruskal–Wallis test statistic, H.
7:   P – REAL (KIND=nag_wp)Output
On exit: the approximate significance, p, of the Kruskal–Wallis test statistic.
8:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, K<2.
IFAIL=2
On entry, L i≤0 for some i, i=1,2,…,k.
IFAIL=3
On entry, LX≠∑i=1 k L i.
IFAIL=4
On entry, all the observations were equal.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

For estimates of the accuracy of the significance p, see G01ECF. The χ 2 approximation is acceptable unless k=3 and l 1,l 2 or l 3≤5.

8 Parallelism and Performance

G08AFF is not threaded in any implementation.

9 Further Comments

The time taken by G08AFF is small, and increases with N and k.
If k=2, the Median test (see G08ACF) or the Mann–Whitney U test (see G08AHF) is more appropriate.

10 Example

This example is taken from Moore et al. (1972). There are 5 groups of sizes 5, 8, 6, 8 and 8. The data represent the weight gain, in pounds, of pigs from five different litters under the same conditions.

10.1 Program Text

Program Text (g08affe.f90)

10.2 Program Data

Program Data (g08affe.d)

10.3 Program Results

Program Results (g08affe.r)

G08 Chapter Contents
G08 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


G08AGF : NAG Library, Mark 26

G08 Chapter Contents
G08 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

G08AGF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

G08AGF performs the Wilcoxon signed rank test on a single sample of size n.

2 Specification

SUBROUTINE G08AGF ( N, X, XME, TAIL, ZER, W, WNOR, P, N1, WRK, IFAIL)
INTEGER | N, N1, IFAIL
REAL (KIND=nag_wp) | X(N), XME, W, WNOR, P, WRK(3*N)
CHARACTER(1) | TAIL, ZER

3 Description

The Wilcoxon one-sample signed rank test may be used to test whether a particular sample came from a population with a specified median. It is assumed that the population distribution is symmetric. The data consists of a single sample of n observations denoted by x 1,x 2,…,xn. This sample may arise from the difference between pairs of observations from two matched samples of equal size taken from two populations, in which case the test may be used to test whether the median of the first population is the same as that of the second population.
The hypothesis under test, H 0, often called the null hypothesis, is that the median is equal to some given value Xmed, and this is to be tested against an alternative hypothesis H 1 which is
  • H 1: population median ≠Xmed; or
  • H 1: population median >Xmed; or
  • H 1: population median <Xmed,
using a two tailed, upper tailed or lower tailed probability respectively. You select the alternative hypothesis by choosing the appropriate tail probability to be computed (see the description of argument TAIL in Section 5).
The Wilcoxon test differs from the Sign test (see G08AAF) in that the magnitude of the scores is taken into account, rather than simply the direction of such scores.
The test procedure is as follows
(a) | For each xi, for i=1,2,…,n, the signed difference di=xi-Xmed is found, where Xmed is a given test value for the median of the sample.
(b) | The absolute differences di are ranked with rank ri and any tied values of di are assigned the average of the tied ranks. You may choose whether or not to ignore any cases where di=0 by removing them before or after ranking (see the description of the argument ZER in Section 5).
(c) | The number of nonzero di is found.
(d) | To each rank is affixed the sign of the di to which it corresponds. Let si=sign di ri.
(e) | The sum of the positive-signed ranks, W=∑si>0 si=∑i=1 n max si,0.0, is calculated.
G08AGF returns
(a) | the test statistic W;
(b) | the number n 1 of nonzero di;
(c) the approximate Normal test statistic z, where
z= W- n 1 n 1+1 4-sign W- n 1 n 1+1 4 × 12 14∑i=1 n si 2 ;
(d) | the tail probability, p, corresponding to W, depending on the choice of the alternative hypothesis, H 1.
If n 1≤80, p is computed exactly; otherwise, an approximation to p is returned based on an approximate Normal statistic corrected for continuity according to the tail specified.
The value of p can be used to perform a significance test on the median against the alternative hypothesis. Let α be the size of the significance test (that is, α is the probability of rejecting H 0 when H 0 is true). If p<α then the null hypothesis is rejected. Typically α might be 0.05 or 0.01.

4 References

Conover W J (1980) Practical Nonparametric Statistics Wiley
Neumann N (1988) Some procedures for calculating the distributions of elementary nonparametric teststatistics Statistical Software Newsletter 14(3) 120–126
Siegel S (1956) Non-parametric Statistics for the Behavioral Sciences McGraw–Hill

5 Arguments

1:   N – INTEGERInput
On entry: n, the size of the sample.
Constraint: N≥1.
2:   X N – REAL (KIND=nag_wp) arrayInput
On entry: the sample observations, x 1,x 2,…,xn.
3:   XME – REAL (KIND=nag_wp)Input
On entry: the median test value, Xmed.
4:   TAIL – CHARACTER(1)Input
On entry: indicates the choice of tail probability, and hence the alternative hypothesis.
TAIL='T'
A two tailed probability is calculated and the alternative hypothesis is H 1: population median ≠Xmed.
TAIL='U'
An upper tailed probability is calculated and the alternative hypothesis is H 1: population median >Xmed.
TAIL='L'
A lower tailed probability is calculated and the alternative hypothesis is H 1: population median <Xmed.
Constraint: TAIL='T', 'U' or 'L'.
5:   ZER – CHARACTER(1)Input
On entry: indicates whether or not to include the cases where di=0.0 in the ranking of the di's.
ZER='Y'
All di=0.0 are included when ranking.
ZER='N'
All di=0.0, are ignored, that is all cases where di=0.0 are removed before ranking.
Constraint: ZER='Y' or 'N'.
6:   W – REAL (KIND=nag_wp)Output
On exit: the Wilcoxon rank sum statistic, W, being the sum of the positive ranks.
7:   WNOR – REAL (KIND=nag_wp)Output
On exit: the approximate Normal test statistic, z, as described in Section 3.
8:   P – REAL (KIND=nag_wp)Output
On exit: the tail probability, p, as specified by the argument TAIL.
9:   N1 – INTEGEROutput
On exit: the number of nonzero di's, n 1.
10:   WRK 3×N – REAL (KIND=nag_wp) arrayWorkspace
11:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, | TAIL≠'T', 'U' or 'L'.
or | ZER≠'Y' or 'N'.
IFAIL=2
On entry, N<1.
IFAIL=3
The whole sample is identical to the given median test value.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

The approximation used to calculate p when n 1>80 will return a value with a relative error of less than 10% for most cases. The error may increase for cases where there are a large number of ties in the sample.

8 Parallelism and Performance

G08AGF is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The time taken by G08AGF increases with n 1, until n 1>80, from which point on the approximation is used. The time decreases significantly at this point and increases again modestly with n 1 for n 1>80.

10 Example

This example performs the Wilcoxon signed rank test on two matched samples of size 8, taken from two populations. The distribution of the differences between pairs of observations from the two populations is assumed to be symmetric. The test is used to test whether the medians of the two distributions of the populations are equal or not. The test statistic, the approximate Normal statistic and the two tailed probability are computed and printed.

10.1 Program Text

Program Text (g08agfe.f90)

10.2 Program Data

Program Data (g08agfe.d)

10.3 Program Results

Program Results (g08agfe.r)

G08 Chapter Contents
G08 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


G08AHF : NAG Library, Mark 26

G08 Chapter Contents
G08 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

G08AHF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

G08AHF performs the Mann–Whitney U test on two independent samples of possibly unequal size.

2 Specification

SUBROUTINE G08AHF ( N1, X, N2, Y, TAIL, U, UNOR, P, TIES, RANKS, WRK, IFAIL)
INTEGER | N1, N2, IFAIL
REAL (KIND=nag_wp) | X(N1), Y(N2), U, UNOR, P, RANKS(N1+N2), WRK(N1+N2)
LOGICAL | TIES
CHARACTER(1) | TAIL

3 Description

The Mann–Whitney U test investigates the difference between two populations defined by the distribution functions F x and G y respectively. The data consist of two independent samples of size n 1 and n 2, denoted by x 1,x 2,…,x n 1 and y 1,y 2,…,y n 2, taken from the two populations.
The hypothesis under test, H 0, often called the null hypothesis, is that the two distributions are the same, that is F x=G x, and this is to be tested against an alternative hypothesis H 1 which is
  • H 1: F x≠G y; or
  • H 1: F x<G y, i.e., the x's tend to be greater than the y's; or
  • H 1: F x>G y, i.e., the x's tend to be less than the y's,
using a two tailed, upper tailed or lower tailed probability respectively. You select the alternative hypothesis by choosing the appropriate tail probability to be computed (see the description of argument TAIL in Section 5).
Note that when using this test to test for differences in the distributions one is primarily detecting differences in the location of the two distributions. That is to say, if we reject the null hypothesis H 0 in favour of the alternative hypothesis H 1: F x>G y we have evidence to suggest that the location, of the distribution defined by F x, is less than the location, of the distribution defined by G y.
The Mann–Whitney U test differs from the Median test (see G08ACF) in that the ranking of the individual scores within the pooled sample is taken into account, rather than simply the position of a score relative to the median of the pooled sample. It is therefore a more powerful test if score differences are meaningful.
The test procedure involves ranking the pooled sample, average ranks being used for ties. Let r 1 i be the rank assigned to xi, i=1,2,…,n 1 and r 2 j the rank assigned to yj, j=1,2,…,n 2. Then the test statistic U is defined as follows;
U=∑i=1 n 1 r 1 i-n 1 n 1+1 2
U is also the number of times a score in the second sample precedes a score in the first sample (where we only count a half if a score in the second sample actually equals a score in the first sample).
G08AHF returns:
(a) | The test statistic U.
(b) The approximate Normal test statistic,
z=U-mean U±12 var U
where
mean U=n 1n 2 2
and
var U=n 1n 2 n 1+n 2+1 12-n 1n 2 n 1+n 2n 1+n 2-1 ×TS
where
TS=∑j= 1 τ tjtj- 1tj+ 1 12
τ is the number of groups of ties in the sample and tj is the number of ties in the jth group.
Note that if no ties are present the variance of U reduces to n 1n 2 12 n 1+n 2+1.
(c) | An indicator as to whether ties were present in the pooled sample or not.
(d) The tail probability, p, corresponding to U (adjusted to allow the complement to be used in an upper one tailed or a two tailed test), depending on the choice of TAIL, i.e., the choice of alternative hypothesis, H 1. The tail probability returned is an approximation of p is based on an approximate Normal statistic corrected for continuity according to the tail specified. If n 1 and n 2 are not very large an exact probability may be desired. For the calculation of the exact probability see G08AJF (no ties in the pooled sample) or G08AKF (ties in the pooled sample).
The value of p can be used to perform a significance test on the null hypothesis H 0 against the alternative hypothesis H 1. Let α be the size of the significance test (that is, α is the probability of rejecting H 0 when H 0 is true). If p<α then the null hypothesis is rejected. Typically α might be 0.05 or 0.01.

4 References

Conover W J (1980) Practical Nonparametric Statistics Wiley
Neumann N (1988) Some procedures for calculating the distributions of elementary nonparametric teststatistics Statistical Software Newsletter 14(3) 120–126
Siegel S (1956) Non-parametric Statistics for the Behavioral Sciences McGraw–Hill

5 Arguments

1:   N1 – INTEGERInput
On entry: the size of the first sample, n 1.
Constraint: N1≥1.
2:   X N1 – REAL (KIND=nag_wp) arrayInput
On entry: the first vector of observations, x 1,x 2,…,x n 1.
3:   N2 – INTEGERInput
On entry: the size of the second sample, n 2.
Constraint: N2≥1.
4:   Y N2 – REAL (KIND=nag_wp) arrayInput
On entry: the second vector of observations. y 1,y 2,…,y n 2.
5:   TAIL – CHARACTER(1)Input
On entry: indicates the choice of tail probability, and hence the alternative hypothesis.
TAIL='T'
A two tailed probability is calculated and the alternative hypothesis is H 1:F x≠G y.
TAIL='U'
An upper tailed probability is calculated and the alternative hypothesis H 1:F x<G y, i.e., the x's tend to be greater than the y's.
TAIL='L'
A lower tailed probability is calculated and the alternative hypothesis H 1:F x>G y, i.e., the x's tend to be less than the y's.
Constraint: TAIL='T', 'U' or 'L'.
6:   U – REAL (KIND=nag_wp)Output
On exit: the Mann–Whitney rank sum statistic, U.
7:   UNOR – REAL (KIND=nag_wp)Output
On exit: the approximate Normal test statistic, z, as described in Section 3.
8:   P – REAL (KIND=nag_wp)Output
On exit: the tail probability, p, as specified by the argument TAIL.
9:   TIES – LOGICALOutput
On exit: indicates whether the pooled sample contained ties or not. This will be useful in checking which routine to use should one wish to calculate an exact tail probability.
TIES=.FALSE., no ties were present (use G08AJF for an exact probability).
TIES=.TRUE., ties were present (use G08AKF for an exact probability).
10:   RANKS N1+N2 – REAL (KIND=nag_wp) arrayOutput
On exit: contains the ranks of the pooled sample. The ranks of the first sample are contained in the first N1 elements and those of the second sample are contained in the next N2 elements.
11:   WRK N1+N2 – REAL (KIND=nag_wp) arrayWorkspace
12:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, | N1<1,
or | N2<1.
IFAIL=2
On entry, TAIL≠'T', 'U' or 'L'.
IFAIL=3
The pooled sample values are all the same, that is the variance of U=0.0.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

The approximate tail probability, p, returned by G08AHF is a good approximation to the exact probability for cases where max n 1,n 2≥30 and n 1+n 2≥40. The relative error of the approximation should be less than 10%, for most cases falling in this range.

8 Parallelism and Performance

G08AHF is not threaded in any implementation.

9 Further Comments

The time taken by G08AHF increases with n 1 and n 2.

10 Example

This example performs the Mann–Whitney test on two independent samples of sizes 16 and 23 respectively. This is used to test the null hypothesis that the distributions of the two populations from which the samples were taken are the same against the alternative hypothesis that the distributions are different. The test statistic, the approximate Normal statistic and the approximate two tail probability are printed. An exact tail probability is also calculated and printed depending on whether ties were found in the pooled sample or not.

10.1 Program Text

Program Text (g08ahfe.f90)

10.2 Program Data

Program Data (g08ahfe.d)

10.3 Program Results

Program Results (g08ahfe.r)

G08 Chapter Contents
G08 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


G08AJF : NAG Library, Mark 26

G08 Chapter Contents
G08 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

G08AJF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

G08AJF calculates the exact tail probability for the Mann–Whitney rank sum test statistic for the case where there are no ties in the two samples pooled together.

2 Specification

SUBROUTINE G08AJF ( N1, N2, TAIL, U, P, WRK, LWRK, IFAIL)
INTEGER | N1, N2, LWRK, IFAIL
REAL (KIND=nag_wp) | U, P, WRK(LWRK)
CHARACTER(1) | TAIL

3 Description

G08AJF computes the exact tail probability for the Mann–Whitney U test statistic (calculated by G08AHF and returned through the argument U) using a method based on an algorithm developed by Harding (1983), and presented by Neumann (1988), for the case where there are no ties in the pooled sample.
The Mann–Whitney U test investigates the difference between two populations defined by the distribution functions F x and G y respectively. The data consist of two independent samples of size n 1 and n 2, denoted by x 1,x 2,…,x n 1 and y 1,y 2,…,y n 2, taken from the two populations.
The hypothesis under test, H 0, often called the null hypothesis, is that the two distributions are the same, that is F x=G x, and this is to be tested against an alternative hypothesis H 1 which is
  • H 1: F x≠G y; or
  • H 1: F x<G y, i.e., the x's tend to be greater than the y's; or
  • H 1: F x>G y, i.e., the x's tend to be less than the y's,
using a two tailed, upper tailed or lower tailed probability respectively. You select the alternative hypothesis by choosing the appropriate tail probability to be computed (see the description of argument TAIL in Section 5).
Note that when using this test to test for differences in the distributions one is primarily detecting differences in the location of the two distributions. That is to say, if we reject the null hypothesis H 0 in favour of the alternative hypothesis H 1: F x>G y we have evidence to suggest that the location, of the distribution defined by F x, is less than the location, of the distribution defined by G y.
G08AJF returns the exact tail probability, p, corresponding to U, depending on the choice of alternative hypothesis, H 1.
The value of p can be used to perform a significance test on the null hypothesis H 0 against the alternative hypothesis H 1. Let α be the size of the significance test (that is, α is the probability of rejecting H 0 when H 0 is true). If p<α then the null hypothesis is rejected. Typically α might be 0.05 or 0.01.

4 References

Conover W J (1980) Practical Nonparametric Statistics Wiley
Harding E F (1983) An efficient minimal-storage procedure for calculating the Mann–Whitney U, generalised U and similar distributions Appl. Statist. 33 1–6
Neumann N (1988) Some procedures for calculating the distributions of elementary nonparametric teststatistics Statistical Software Newsletter 14(3) 120–126
Siegel S (1956) Non-parametric Statistics for the Behavioral Sciences McGraw–Hill

5 Arguments

1:   N1 – INTEGERInput
On entry: the number of non-tied pairs, n 1.
Constraint: N1≥1.
2:   N2 – INTEGERInput
On entry: the size of the second sample, n 2.
Constraint: N2≥1.
3:   TAIL – CHARACTER(1)Input
On entry: indicates the choice of tail probability, and hence the alternative hypothesis.
TAIL='T'
A two tailed probability is calculated and the alternative hypothesis is H 1:F x≠G y.
TAIL='U'
An upper tailed probability is calculated and the alternative hypothesis H 1:F x<G y, i.e., the x's tend to be greater than the y's.
TAIL='L'
A lower tailed probability is calculated and the alternative hypothesis H 1:F x>G y, i.e., the x's tend to be less than the y's.
Constraint: TAIL='T', 'U' or 'L'.
4:   U – REAL (KIND=nag_wp)Input
On entry: U, the value of the Mann–Whitney rank sum test statistic. This is the statistic returned through the argument U by G08AHF.
Constraint: U≥0.0.
5:   P – REAL (KIND=nag_wp)Output
On exit: the exact tail probability, p, as specified by the argument TAIL.
6:   WRK LWRK – REAL (KIND=nag_wp) arrayWorkspace
7:   LWRK – INTEGERInput
On entry: the dimension of the array WRK as declared in the (sub)program from which G08AJF is called.
Constraint: LWRK≥N1×N2/2+1.
8:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, | N1<1,
or | N2<1.
IFAIL=2
On entry, TAIL≠'T', 'U' or 'L'.
IFAIL=3
On entry, U<0.0.
IFAIL=4
On entry, LWRK<N1×N2/2+1.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

The exact tail probability, p, is computed to an accuracy of at least 4 significant figures.

8 Parallelism and Performance

G08AJF is not threaded in any implementation.

9 Further Comments

The time taken by G08AJF increases with n 1 and n 2 and the product n 1n 2.

10 Example

This example finds the Mann–Whitney test statistic, using G08AHF for two independent samples of size 16 and 23 respectively. This is used to test the null hypothesis that the distributions of the two populations from which the samples were taken are the same against the alternative hypothesis that the distributions are different. The test statistic, the approximate normal statistic and the approximate two tail probability are printed. G08AJF is then called to obtain the exact two tailed probability. The exact probability is also printed.

10.1 Program Text

Program Text (g08ajfe.f90)

10.2 Program Data

Program Data (g08ajfe.d)

10.3 Program Results

Program Results (g08ajfe.r)

G08 Chapter Contents
G08 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


G08AKF : NAG Library, Mark 26

G08 Chapter Contents
G08 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

G08AKF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

G08AKF calculates the exact tail probability for the Mann–Whitney rank sum test statistic for the case where there are ties in the two samples pooled together.

2 Specification

SUBROUTINE G08AKF ( N1, N2, TAIL, RANKS, U, P, WRK, LWRK, IWRK, IFAIL)
INTEGER | N1, N2, LWRK, IWRK(2*(N1+N2+1)), IFAIL
REAL (KIND=nag_wp) | RANKS(N1+N2), U, P, WRK(LWRK)
CHARACTER(1) | TAIL

3 Description

G08AKF computes the exact tail probability for the Mann–Whitney U test statistic (calculated by G08AHF and returned through the argument U) using a method based on an algorithm developed by Neumann (1988), for the case where there are ties in the pooled sample.
The Mann–Whitney U test investigates the difference between two populations defined by the distribution functions F x and G y respectively. The data consist of two independent samples of size n 1 and n 2, denoted by x 1,x 2,…,x n 1 and y 1,y 2,…,y n 2, taken from the two populations.
The hypothesis under test, H 0, often called the null hypothesis, is that the two distributions are the same, that is F x=G x, and this is to be tested against an alternative hypothesis H 1 which is
  • H 1: F x≠G y; or
  • H 1: F x<G y, i.e., the x's tend to be greater than the y's; or
  • H 1: F x>G y, i.e., the x's tend to be less than the y's,
using a two tailed, upper tailed or lower tailed probability respectively. You select the alternative hypothesis by choosing the appropriate tail probability to be computed (see the description of argument TAIL in Section 5).
Note that when using this test to test for differences in the distributions one is primarily detecting differences in the location of the two distributions. That is to say, if we reject the null hypothesis H 0 in favour of the alternative hypothesis H 1: F x>G y we have evidence to suggest that the location, of the distribution defined by F x, is less than the location of the distribution defined by G y.
G08AKF returns the exact tail probability, p, corresponding to U, depending on the choice of alternative hypothesis, H 1.
The value of p can be used to perform a significance test on the null hypothesis H 0 against the alternative hypothesis H 1. Let α be the size of the significance test (that is α is the probability of rejecting H 0 when H 0 is true). If p<α then the null hypothesis is rejected. Typically α might be 0.05 or 0.01.

4 References

Conover W J (1980) Practical Nonparametric Statistics Wiley
Neumann N (1988) Some procedures for calculating the distributions of elementary nonparametric teststatistics Statistical Software Newsletter 14(3) 120–126
Siegel S (1956) Non-parametric Statistics for the Behavioral Sciences McGraw–Hill

5 Arguments

1:   N1 – INTEGERInput
On entry: the number of non-tied pairs, n 1.
Constraint: N1≥1.
2:   N2 – INTEGERInput
On entry: the size of the second sample, n 2.
Constraint: N2≥1.
3:   TAIL – CHARACTER(1)Input
On entry: indicates the choice of tail probability, and hence the alternative hypothesis.
TAIL='T'
A two tailed probability is calculated and the alternative hypothesis is H 1:F x≠G y.
TAIL='U'
An upper tailed probability is calculated and the alternative hypothesis H 1:F x<G y, i.e., the x's tend to be greater than the y's.
TAIL='L'
A lower tailed probability is calculated and the alternative hypothesis H 1:F x>G y, i.e., the x's tend to be less than the y's.
Constraint: TAIL='T', 'U' or 'L'.
4:   RANKS N1+N2 – REAL (KIND=nag_wp) arrayInput
On entry: the ranks of the pooled sample. These ranks are output in the array RANKS by G08AHF and should not be altered in any way if you are using the same n 1, n 2 and U as used in G08AHF.
5:   U – REAL (KIND=nag_wp)Input
On entry: U, the value of the Mann–Whitney rank sum test statistic. This is the statistic returned through the argument U by G08AHF.
Constraint: U≥0.0.
6:   P – REAL (KIND=nag_wp)Output
On exit: the tail probability, p, as specified by the argument TAIL.
7:   WRK LWRK – REAL (KIND=nag_wp) arrayWorkspace
8:   LWRK – INTEGERInput
On entry: the dimension of the array WRK as declared in the (sub)program from which G08AKF is called.
Constraint: LWRK≥n+n⁢n+1⁢n+m- n⁢n+1⁢2×n+1 3+1, where n=min N1,N2 and m=max N1,N2.
9:   IWRK 2×N1+N2+1 – INTEGER arrayWorkspace
10:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, | N1<1,
or | N2<1.
IFAIL=2
On entry, TAIL≠'T', 'U' or 'L'.
IFAIL=3
On entry, U<0.0.
IFAIL=4
On entry, LWRK is too small.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

The exact tail probability, p, is computed to an accuracy of at least 4 significant figures.

8 Parallelism and Performance

G08AKF is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The time taken by G08AKF increases with n 1 and n 2 and the product n 1n 2. Note that the amount of workspace required becomes very large for even moderate sizes of n 1 and n 2.

10 Example

This example finds the Mann–Whitney test statistic, using G08AHF for two independent samples of size 16 and 23 respectively. This is used to test the null hypothesis that the distributions of the two populations from which the samples were taken are the same against the alternative hypothesis that the distributions are different. The test statistic, the approximate Normal statistic and the approximate two tail probability are printed. G08AKF is then called to obtain the exact two tailed probability. The exact probability is also printed.

10.1 Program Text

Program Text (g08akfe.f90)

10.2 Program Data

Program Data (g08akfe.d)

10.3 Program Results

Program Results (g08akfe.r)

G08 Chapter Contents
G08 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


G08ALF : NAG Library, Mark 26

G08 Chapter Contents
G08 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

G08ALF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

G08ALF performs the Cochran Q-test on cross-classified binary data.

2 Specification

SUBROUTINE G08ALF ( N, K, X, LDX, Q, PROB, IFAIL)
INTEGER | N, K, LDX, IFAIL
REAL (KIND=nag_wp) | X(LDX,K), Q, PROB

3 Description

Cochran's Q-test may be used to test for differences between k treatments applied independently to n individuals or blocks (k related samples of equal size n), where the observed response can take only one of two possible values; for example a treatment may result in a ‘success’ or ‘failure’. The data is recorded as either 1 or 0 to represent this dichotomization.
The use of this ‘randomized block design’ allows the effect of differences between the blocks to be separated from the differences between the treatments. The test assumes that the blocks were randomly selected from all possible blocks and that the result may be one of two possible outcomes common to all treatments within blocks.
The null and alternative hypotheses to be tested may be stated as follows.
H 0 : | the treatments are equally effective, that is the probability of obtaining a 1 within a block is the same for each treatment.
H 1 : | there is a difference between the treatments, that is the probability of obtaining a 1 is not the same for different treatments within blocks.
The data is often represented in the form of a table with the n rows representing the blocks and the k columns the treatments. Let Ri represent the row totals, for i=1,2,…,n, and Cj represent the column totals, for j=1,2,…,k. Let x ij represent the response or result where x ij=0​ or ​1.
 | Treatments |  |  |  |
Blocks | 1 | 2 |  | k | Row Totals
1 | x 11 | x 12 | ⋯ | x 1 k | R 1
2 | x 21 | x 22 | ⋯ | x 2 k | R 2
⋮ |  |  | ⋮ |  | ⋮
n | x n 1 | x n 2 | ⋯ | x nk | Rn
Column Totals | C 1 | C 2 |  | Ck | N=Grand Total
If p ij=Pr x ij=1, for i=1,2,…,n and j=1,2,…,k, then the hypotheses may be restated as follows
H 0 : | p i 1=p i 2=…=p ik, for each i=1,2,…,n.
H 1: | p ij≠p ik, for some j and k, and for some i.
The test statistic is defined as
Q=k k-1∑j=1 k Cj-Nk 2 ∑i=1 n Ri k-Ri .
When the number of blocks, n, is large relative to the number of treatments, k, Q has an approximate χ 2-distribution with k-1 degrees of freedom. This is used to find the probability, p, of obtaining a statistic greater than or equal to the computed value of Q. Thus p is the upper tail probability associated with the computed value of Q, where the χ 2-distribution is used to approximate the true distribution of Q.

4 References

Conover W J (1980) Practical Nonparametric Statistics Wiley
Siegel S (1956) Non-parametric Statistics for the Behavioral Sciences McGraw–Hill

5 Arguments

1:   N – INTEGERInput
On entry: n, the number of blocks.
Constraint: N≥2.
2:   K – INTEGERInput
On entry: k, the number of treatments.
Constraint: K≥2.
3:   X LDXK – REAL (KIND=nag_wp) arrayInput
On entry: the matrix of observed zero-one data. X ij must contain the value x ij, for i=1,2,…,n and j=1,2,…,k.
Constraint: X ij=0.0 or 1.0, for i=1,2,…,n and j=1,2,…,k.
4:   LDX – INTEGERInput
On entry: the first dimension of the array X as declared in the (sub)program from which G08ALF is called.
Constraint: LDX≥N.
5:   Q – REAL (KIND=nag_wp)Output
On exit: the value of the Cochran Q-test statistic.
6:   PROB – REAL (KIND=nag_wp)Output
On exit: the upper tail probability, p, associated with the Cochran Q-test statistic, that is the probability of obtaining a value greater than or equal to the observed value (the output value of Q).
7:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, | N<2,
or | K<2,
or | LDX<N.
IFAIL=2
On entry, X ij≠0.0 or 1.0 for some i and j, i=1,2,…,n and j=1,2,…,k.
IFAIL=3
The approximation process used to calculate the tail probability has failed to converge. The result returned in PROB may still be a reasonable approximation.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

The use of the χ 2-distribution as an approximation to the true distribution of the Cochran Q-test statistic improves as k increases and as n increases relative to k. This approximation should be a reasonable one when the total number of observations left, after omitting those rows containing all 0 or 1, is greater than about 25 and the number of rows left is larger than 5.

8 Parallelism and Performance

G08ALF is not threaded in any implementation.

9 Further Comments

None.

10 Example

The following example is taken from page 201 of Conover (1980). The data represents the success of three basketball enthusiasts in predicting the outcome of 12 collegiate basketball games, selected at random, using 1 for successful prediction of the outcome and 0 for unsuccessful prediction. This data is read in and the Cochran Q-test statistic and its corresponding upper tail probability are computed and printed.

10.1 Program Text

Program Text (g08alfe.f90)

10.2 Program Data

Program Data (g08alfe.d)

10.3 Program Results

Program Results (g08alfe.r)

G08 Chapter Contents
G08 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


G08BAF : NAG Library, Mark 26

G08 Chapter Contents
G08 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

G08BAF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

G08BAF performs Mood's and David's tests for dispersion differences between two independent samples of possibly unequal size.

2 Specification

SUBROUTINE G08BAF ( X, N, N1, R, ITEST, W, V, PW, PV, IFAIL)
INTEGER | N, N1, ITEST, IFAIL
REAL (KIND=nag_wp) | X(N), R(N), W, V, PW, PV

3 Description

Mood's and David's tests investigate the difference between the dispersions of two independent samples of sizes n 1 and n 2, denoted by
x 1,x 2,…,x n 1
and
x n 1+ 1,x n 1+ 2,…,xn,   n=n 1+n 2.
The hypothesis under test, H 0, often called the null hypothesis, is that the dispersion difference is zero, and this is to be tested against a one- or two-sided alternative hypothesis H 1 (see below).
Both tests are based on the rankings of the sample members within the pooled sample formed by combining both samples. If there is some difference in dispersion, more of the extreme ranks will tend to be found in one sample than in the other.
Let the rank of xi be denoted by ri, for i=1,2,…,n.
(a) Mood's test.
The test statistic W=∑i=1 n 1 ri- n+1 2 2 is found.
W is the sum of squared deviations from the average rank in the pooled sample. For large n, W approaches normality, and so an approximation, pw, to the probability of observing W not greater than the computed value, may be found.
G08BAF returns W and pw if Mood's test is selected.
(b) David's test.
The disadvantage of Mood's test is that it assumes that the means of the two samples are equal. If this assumption is unjustified a high value of W could merely reflect the difference in means. David's test reduces this effect by using the variance of the ranks of the first sample about their mean rank, rather than the overall mean rank.
The test statistic for David's test is
V=1 n 1-1 ∑i=1 n 1 ri-r- 2
where
r-=∑i= 1 n 1 ri n 1.
For large n, V approaches normality, enabling an approximate probability pv to be computed, similarly to pw.
G08BAF returns V and pv if David's test is selected.
Suppose that a significance test of a chosen size α is to be performed (i.e., α is the probability of rejecting H 0 when H 0 is true; typically α is a small quantity such as 0.05 or 0.01).
The returned value p (=pv or pw) can be used to perform a significance test, against various alternative hypotheses H 1, as follows.
(i) | H 1: dispersions are unequal. H 0 is rejected if 2 × min p,1-p < α .
(ii) | H 1: dispersion of sample 1> dispersion of sample 2. H 0 is rejected if 1-p<α.
(iii) | H 1: dispersion of sample 2> dispersion of sample 1. H 0 is rejected if p<α.

4 References

Cooper B E (1975) Statistics for Experimentalists Pergamon Press

5 Arguments

1:   X N – REAL (KIND=nag_wp) arrayInput
On entry: the first n 1 elements of X must be set to the data values in the first sample, and the next n 2 (=N-n 1) elements to the data values in the second sample.
2:   N – INTEGERInput
On entry: the total of the two sample sizes, n (=n 1+n 2).
Constraint: N>2.
3:   N1 – INTEGERInput
On entry: the size of the first sample, n 1.
Constraint: 1<N1<N.
4:   R N – REAL (KIND=nag_wp) arrayOutput
On exit: the ranks ri, assigned to the data values xi, for i=1,2,…,n.
5:   ITEST – INTEGERInput
On entry: the test(s) to be carried out.
ITEST=0
Both Mood's and David's tests.
ITEST=1
David's test only.
ITEST=2
Mood's test only.
Constraint: ITEST=0, 1 or 2.
6:   W – REAL (KIND=nag_wp)Output
On exit: Mood's test statistic, W, if requested.
7:   V – REAL (KIND=nag_wp)Output
On exit: David's test statistic, V, if requested.
8:   PW – REAL (KIND=nag_wp)Output
On exit: the lower tail probability, pw, corresponding to the value of W, if Mood's test was requested.
9:   PV – REAL (KIND=nag_wp)Output
On exit: the lower tail probability, pv, corresponding to the value of V, if David's test was requested.
10:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, N≤2.
IFAIL=2
On entry, | N1≤1,
or | N1≥N.
IFAIL=3
On entry, | ITEST<0,
or | ITEST>2.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

All computations are believed to be stable. The statistics V and W should be accurate enough for all practical uses.

8 Parallelism and Performance

G08BAF is not threaded in any implementation.

9 Further Comments

The time taken by G08BAF is small, and increases with n.

10 Example

This example is taken from page 280 of Cooper (1975). The data consists of two samples of six observations each. Both Mood's and David's test statistics and significances are computed. Note that Mood's statistic is inflated owing to the difference in location of the two samples, the median ranks differing by a factor of two.

10.1 Program Text

Program Text (g08bafe.f90)

10.2 Program Data

Program Data (g08bafe.d)

10.3 Program Results

Program Results (g08bafe.r)

G08 Chapter Contents
G08 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


G08CBF : NAG Library, Mark 26

G08 Chapter Contents
G08 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

G08CBF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

G08CBF performs the one sample Kolmogorov–Smirnov test, using one of the distributions provided.

2 Specification

SUBROUTINE G08CBF ( N, X, DIST, PAR, ESTIMA, NTYPE, D, Z, P, SX, IFAIL)
INTEGER | N, NTYPE, IFAIL
REAL (KIND=nag_wp) | X(N), PAR(2), D, Z, P, SX(N)
CHARACTER(*) | DIST
CHARACTER(1) | ESTIMA

3 Description

The data consist of a single sample of n observations denoted by x 1 , x 2 , … , x n . Let S n x i and F 0 x i represent the sample cumulative distribution function and the theoretical (null) cumulative distribution function respectively at the point x i where x i is the i th smallest sample observation.
The Kolmogorov–Smirnov test provides a test of the null hypothesis H 0 : the data are a random sample of observations from a theoretical distribution specified by you against one of the following alternative hypotheses:
(i) | H 1 : the data cannot be considered to be a random sample from the specified null distribution.
(ii) | H 2 : the data arise from a distribution which dominates the specified null distribution. In practical terms, this would be demonstrated if the values of the sample cumulative distribution function S n x tended to exceed the corresponding values of the theoretical cumulative distribution function F 0 x .
(iii) | H 3 : the data arise from a distribution which is dominated by the specified null distribution. In practical terms, this would be demonstrated if the values of the theoretical cumulative distribution function F 0 x tended to exceed the corresponding values of the sample cumulative distribution function S n x .
One of the following test statistics is computed depending on the particular alternative null hypothesis specified (see the description of the argument NTYPE in Section 5).
For the alternative hypothesis H 1 .
  • D n – the largest absolute deviation between the sample cumulative distribution function and the theoretical cumulative distribution function. Formally D n = max D n + , D n - .
For the alternative hypothesis H 2 .
  • D n + – the largest positive deviation between the sample cumulative distribution function and the theoretical cumulative distribution function. Formally D n + = max S n x i - F 0 x i ,0 for both discrete and continuous null distributions.
For the alternative hypothesis H 3 .
  • D n - – the largest positive deviation between the theoretical cumulative distribution function and the sample cumulative distribution function. Formally if the null distribution is discrete then D n - = max F 0 x i - S n x i ,0 and if the null distribution is continuous then D n - = max F 0 x i - S n x i-1 ,0 .
The standardized statistic Z = D × n is also computed where D may be D n , D n + or D n - depending on the choice of the alternative hypothesis. This is the standardized value of D with no correction for continuity applied and the distribution of Z converges asymptotically to a limiting distribution, first derived by Kolmogorov (1933), and then tabulated by Smirnov (1948). The asymptotic distributions for the one-sided statistics were obtained by Smirnov (1933).
The probability, under the null hypothesis, of obtaining a value of the test statistic as extreme as that observed, is computed. If n≤100 an exact method given by Conover (1980), is used. Note that the method used is only exact for continuous theoretical distributions and does not include Conover's modification for discrete distributions. This method computes the one-sided probabilities. The two-sided probabilities are estimated by doubling the one-sided probability. This is a good estimate for small p , that is p≤0.10 , but it becomes very poor for larger p . If n>100 then p is computed using the Kolmogorov–Smirnov limiting distributions, see Feller (1948), Kendall and Stuart (1973), Kolmogorov (1933), Smirnov (1933) and Smirnov (1948).

4 References

Conover W J (1980) Practical Nonparametric Statistics Wiley
Feller W (1948) On the Kolmogorov–Smirnov limit theorems for empirical distributions Ann. Math. Statist. 19 179–181
Kendall M G and Stuart A (1973) The Advanced Theory of Statistics (Volume 2) (3rd Edition) Griffin
Kolmogorov A N (1933) Sulla determinazione empirica di una legge di distribuzione Giornale dell' Istituto Italiano degli Attuari 4 83–91
Siegel S (1956) Non-parametric Statistics for the Behavioral Sciences McGraw–Hill
Smirnov N (1933) Estimate of deviation between empirical distribution functions in two independent samples Bull. Moscow Univ. 2(2) 3–16
Smirnov N (1948) Table for estimating the goodness of fit of empirical distributions Ann. Math. Statist. 19 279–281

5 Arguments

1:   N – INTEGERInput
On entry: n, the number of observations in the sample.
Constraint: N≥3 .
2:   X N – REAL (KIND=nag_wp) arrayInput
On entry: the sample observations x 1 , x 2 , … , x n .
Constraint: the sample observations supplied must be consistent, in the usual manner, with the null distribution chosen, as specified by the arguments DIST and PAR. For further details see Section 9.
3:   DIST – CHARACTER(*)Input
On entry: the theoretical (null) distribution from which it is suspected the data may arise.
DIST='U'
The uniform distribution over a,b.
DIST='N'
The Normal distribution with mean μ and variance σ 2.
DIST='G'
The gamma distribution with shape parameterα and scale parameter β, where the mean =αβ.
DIST='BE'
The beta distribution with shape parameters α and β, where the mean =α/α+β.
DIST='BI'
The binomial distribution with the number of trials, m, and the probability of a success, p.
DIST='E'
The exponential distribution with parameter λ, where the mean =1/λ.
DIST='P'
The Poisson distribution with parameter μ, where the mean =μ.
DIST='NB'
The negative binomial distribution with the number of trials, m, and the probability of success, p.
DIST='GP'
The generalized Pareto distribution with shape parameter ξ and scale β.
Any number of characters may be supplied as the actual argument, however only the characters, maximum 2, required to uniquely identify the distribution are referenced.
Constraint: DIST='U', 'N', 'G', 'BE', 'BI', 'E', 'P', 'NB' or 'GP'.
4:   PAR 2 – REAL (KIND=nag_wp) arrayInput/Output
On entry: if ESTIMA='S', PAR must contain the known values of the parameter(s) of the null distribution as follows.
If a uniform distribution is used, then PAR 1 and PAR 2 must contain the boundaries a and b respectively.
If a Normal distribution is used, then PAR 1 and PAR 2 must contain the mean, μ, and the variance, σ 2, respectively.
If a gamma distribution is used, then PAR 1 and PAR 2 must contain the parameters α and β respectively.
If a beta distribution is used, then PAR 1 and PAR 2 must contain the parameters α and β respectively.
If a binomial distribution is used, then PAR 1 and PAR 2 must contain the parameters m and p respectively.
If an exponential distribution is used, then PAR 1 must contain the parameter λ.
If a Poisson distribution is used, then PAR 1 must contain the parameter μ.
If a negative binomial distribution is used, PAR 1 and PAR 2 must contain the parameters m and p respectively.
If a generalized Pareto distribution is used, PAR 1 and PAR 2 must contain the parameters ξ and β respectively.
If ESTIMA='E', PAR need not be set except when the null distribution requested is either the binomial or the negative binomial distribution in which case PAR 1 must contain the parameter m.
On exit: if ESTIMA='S', PAR is unchanged; if ESTIMA='E', and DIST='BI' or DIST='NB' then PAR 2 is estimated from the data; otherwise PAR 1 and PAR 2 are estimated from the data.
Constraints:
  • if DIST='U', PAR 1<PAR 2;
  • if DIST='N', PAR 2>0.0;
  • if DIST='G', PAR 1>0.0 and PAR 2>0.0;
  • if DIST='BE', PAR 1>0.0 and PAR 2>0.0 and PAR 1≤106 and PAR 2≤106;
  • if DIST='BI', PAR 1≥1.0 and 0.0<PAR 2<1.0 and PAR 1×PAR 2×1.0-PAR 2≤106 and PAR 1<1/eps, where eps=machine precision, see X02AJF;
  • if DIST='E', PAR 1>0.0;
  • if DIST='P', PAR 1>0.0 and PAR 1≤106;
  • if DIST='NB', PAR 1≥1.0 and 0.0<PAR 2<1.0 and PAR 1× 1.0-PAR 2 / PAR 2× PAR 2 ≤106 and PAR 1<1/eps, where eps=machine precision, see X02AJF;
  • if DIST='GP', PAR 2>0.
5:   ESTIMA – CHARACTER(1)Input
On entry: ESTIMA must specify whether values of the parameters of the null distribution are known or are to be estimated from the data.
ESTIMA='S'
Values of the parameters will be supplied in the array PAR described above.
ESTIMA='E'
Parameters are to be estimated from the data except when the null distribution requested is the binomial distribution or the negative binomial distribution in which case the first parameter, m, must be supplied in PAR 1 and only the second parameter, p, is estimated from the data.
Constraint: ESTIMA='S' or 'E'.
6:   NTYPE – INTEGERInput
On entry: the test statistic to be calculated, i.e., the choice of alternative hypothesis.
NTYPE=1
Computes D n , to test H 0 against H 1 ,
NTYPE=2
Computes D n + , to test H 0 against H 2 ,
NTYPE=3
Computes D n - , to test H 0 against H 3 .
Constraint: NTYPE=1, 2 or 3.
7:   D – REAL (KIND=nag_wp)Output
On exit: the Kolmogorov–Smirnov test statistic ( D n , D n + or D n - according to the value of NTYPE).
8:   Z – REAL (KIND=nag_wp)Output
On exit: a standardized value, Z , of the test statistic, D , without any correction for continuity.
9:   P – REAL (KIND=nag_wp)Output
On exit: the probability, p , associated with the observed value of D where D may be D n , D n + or D n - depending on the value of NTYPE (see Section 3).
10:   SX N – REAL (KIND=nag_wp) arrayOutput
On exit: the sample observations, x 1,x 2,…,xn, sorted in ascending order.
11:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, N=value.
Constraint: N≥3.
IFAIL=2
On entry, DIST=value was an illegal value.
IFAIL=3
On entry, NTYPE=value.
Constraint: NTYPE=1, 2 or 3.
IFAIL=4
On entry, ESTIMA=value was an illegal value.
IFAIL=5
On entry, DIST='BI' and m=PAR 1=value.
Note that m must always be supplied.
Constraint: for the binomial distribution, 1≤PAR 1<1/eps, where eps=machine precision, see X02AJF.
On entry, DIST='NB' and m=PAR 1=value.
Note that m must always be supplied.
Constraint: for the negative binomial distribution, 1≤PAR 1<1/eps, where eps=machine precision, see X02AJF.
On entry, ESTIMA='S' and PAR 1=value; PAR 2=value.
Constraint: for the beta distribution, 0<PAR 1 and PAR 2≤1000000.
On entry, ESTIMA='S' and PAR 1=value; PAR 2=value.
Constraint: for the gamma distribution, PAR 1 and PAR 2>0.
On entry, ESTIMA='S' and PAR 1=value; PAR 2=value.
Constraint: for the generalized Pareto distribution with PAR 1<0, 0≤X i≤-PAR 2/PAR 1, for i=1,2,…,N.
On entry, ESTIMA='S' and PAR 1=value; PAR 2=value.
Constraint: for the uniform distribution, PAR 1<PAR 2.
On entry, ESTIMA='S' and PAR 1=value.
Constraint: for the exponential distribution, PAR 1>0.
On entry, ESTIMA='S' and PAR 1=value.
Constraint: for the Poisson distribution, 0<PAR 1<1000000.
On entry, ESTIMA='S' and PAR 2=value.
Constraint: for the binomial distribution, 0<PAR 2<1.
On entry, ESTIMA='S' and PAR 2=value.
Constraint: for the generalized Pareto distribution, PAR 2>0.
On entry, ESTIMA='S' and PAR 2=value.
Constraint: for the negative binomial distribution, 0<PAR 2<1.
On entry, ESTIMA='S' and PAR 2=value.
Constraint: for the Normal distribution, PAR 2>0.
IFAIL=6
On entry, DIST='U' and at least one observation is illegal.
Constraint: PAR 1≤X i≤PAR 2, for i=1,2,…,N.
On entry, DIST='G', 'E', 'P', 'NB' or 'GP' and at least one observation is negative.
Constraint: X i≥0, for i=1,2,…,N.
On entry, DIST='BE' and at least one observation is illegal.
Constraint: 0≤X i≤1, for i=1,2,…,N.
On entry, DIST='BI' and all observations are zero or m.
Constraint: at least one 0.0<X i<PAR 1, for i=1,2,…,N.
On entry, DIST='BI' and at least one observation is illegal.
Constraint: 0≤X i≤PAR 1, for i=1,2,…,N.
On entry, DIST='E' or 'P' and all observations are zero.
Constraint: at least one X i>0, for i=1,2,…,N.
On entry, DIST='GP' and ESTIMA='E'.
The parameter estimates are invalid; the data may not be from the generalized Pareto distribution.
IFAIL=7
On entry, DIST='U', 'N', 'G', 'BE' or 'GP', ESTIMA='E' and the whole sample is constant. Thus the variance is zero.
IFAIL=8
On entry, DIST='BI', PAR 1=value, PAR 2=value.
The variance PAR 1×PAR 2×1-PAR 2 exceeds 1000000.
On entry, DIST='NB', PAR 1=value, PAR 2=value.
The variance PAR 1×1-PAR 2/PAR 2×PAR 2 exceeds 1000000.
IFAIL=9
On entry, DIST='G' and in the computation of the incomplete gamma function by S14BAF the convergence of the Taylor series or Legendre continued fraction fails within 600 iterations.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

The approximation for p , given when n>100 , has a relative error of at most 2.5% for most cases. The two-sided probability is approximated by doubling the one-sided probability. This is only good for small p , i.e., p<0.10 but very poor for large p . The error is always on the conservative side, that is the tail probability, p , is over estimated.

8 Parallelism and Performance

G08CBF is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The time taken by G08CBF increases with n until n>100 at which point it drops and then increases slowly with n . The time may also depend on the choice of null distribution and on whether or not the parameters are to be estimated.
The data supplied in the argument X must be consistent with the chosen null distribution as follows:
  • when DIST='U', then PAR 1 ≤ x i ≤ PAR 2 , for i = 1 , 2 , … , n ;
  • when DIST='N', then there are no constraints on the x i 's;
  • when DIST='G', then x i ≥ 0.0 , for i = 1 , 2 , … , n ;
  • when DIST='BE', then 0.0 ≤ x i ≤ 1.0 , for i = 1 , 2 , … , n ;
  • when DIST='BI', then 0.0 ≤ x i ≤ PAR 1 , for i = 1 , 2 , … , n ;
  • when DIST='E', then x i ≥ 0.0 , for i = 1 , 2 , … , n ;
  • when DIST='P', then x i ≥ 0.0 , for i = 1 , 2 , … , n ;
  • when DIST='NB', then x i ≥ 0.0 , for i = 1 , 2 , … , n ;
  • when DIST='GP' and PAR 1≥0.0, then xi≥0.0, for i=1,2,…,n;
  • when DIST='GP' and PAR 1<0.0, then 0.0≤xi≤-PAR 2/PAR 1, for i=1,2,…,n.

10 Example

The following example program reads in a set of data consisting of 30 observations. The Kolmogorov–Smirnov test is then applied twice, firstly to test whether the sample is taken from a uniform distribution, U 0,2, and secondly to test whether the sample is taken from a Normal distribution where the mean and variance are estimated from the data. In both cases we are testing against H 1; that is, we are doing a two tailed test. The values of D, Z and P are printed for each case.

10.1 Program Text

Program Text (g08cbfe.f90)

10.2 Program Data

Program Data (g08cbfe.d)

10.3 Program Results

Program Results (g08cbfe.r)

G08 Chapter Contents
G08 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


G08CCF : NAG Library, Mark 26

G08 Chapter Contents
G08 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

G08CCF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

G08CCF performs the one sample Kolmogorov–Smirnov distribution test, using a user-specified distribution.

2 Specification

SUBROUTINE G08CCF ( N, X, CDF, NTYPE, D, Z, P, SX, IFAIL)
INTEGER | N, NTYPE, IFAIL
REAL (KIND=nag_wp) | X(N), CDF, D, Z, P, SX(N)
EXTERNAL | CDF

3 Description

The data consists of a single sample of n observations, denoted by x 1,x 2,…,xn. Let Sn x i and F 0 x i represent the sample cumulative distribution function and the theoretical (null) cumulative distribution function respectively at the point x i, where x i is the ith smallest sample observation.
The Kolmogorov–Smirnov test provides a test of the null hypothesis H 0: the data are a random sample of observations from a theoretical distribution specified by you (in CDF) against one of the following alternative hypotheses.
(i) | H 1: the data cannot be considered to be a random sample from the specified null distribution.
(ii) | H 2: the data arise from a distribution which dominates the specified null distribution. In practical terms, this would be demonstrated if the values of the sample cumulative distribution function Sn x tended to exceed the corresponding values of the theoretical cumulative distribution function F 0 x.
(iii) | H 3: the data arise from a distribution which is dominated by the specified null distribution. In practical terms, this would be demonstrated if the values of the theoretical cumulative distribution function F 0 x tended to exceed the corresponding values of the sample cumulative distribution function Sn x.
One of the following test statistics is computed depending on the particular alternative hypothesis specified (see the description of the argument NTYPE in Section 5).
For the alternative hypothesis H 1:
  • Dn – the largest absolute deviation between the sample cumulative distribution function and the theoretical cumulative distribution function. Formally Dn=max Dn+,Dn-.
For the alternative hypothesis H 2:
  • Dn+ – the largest positive deviation between the sample cumulative distribution function and the theoretical cumulative distribution function. Formally Dn+=max Sn x i-F 0 x i,0.
For the alternative hypothesis H 3:
  • Dn- – the largest positive deviation between the theoretical cumulative distribution function and the sample cumulative distribution function. Formally Dn-=max F 0 x i-Sn x i-1,0. This is only true for continuous distributions. See Section 9 for comments on discrete distributions.
The standardized statistic, Z=D×n, is also computed, where D may be Dn,Dn+ or Dn- depending on the choice of the alternative hypothesis. This is the standardized value of D with no continuity correction applied and the distribution of Z converges asymptotically to a limiting distribution, first derived by Kolmogorov (1933), and then tabulated by Smirnov (1948). The asymptotic distributions for the one-sided statistics were obtained by Smirnov (1933).
The probability, under the null hypothesis, of obtaining a value of the test statistic as extreme as that observed, is computed. If n≤100, an exact method given by Conover (1980) is used. Note that the method used is only exact for continuous theoretical distributions and does not include Conover's modification for discrete distributions. This method computes the one-sided probabilities. The two-sided probabilities are estimated by doubling the one-sided probability. This is a good estimate for small p, that is p≤0.10, but it becomes very poor for larger p. If n>100 then p is computed using the Kolmogorov–Smirnov limiting distributions; see Feller (1948), Kendall and Stuart (1973), Kolmogorov (1933), Smirnov (1933) and Smirnov (1948).

4 References

Conover W J (1980) Practical Nonparametric Statistics Wiley
Feller W (1948) On the Kolmogorov–Smirnov limit theorems for empirical distributions Ann. Math. Statist. 19 179–181
Kendall M G and Stuart A (1973) The Advanced Theory of Statistics (Volume 2) (3rd Edition) Griffin
Kolmogorov A N (1933) Sulla determinazione empirica di una legge di distribuzione Giornale dell' Istituto Italiano degli Attuari 4 83–91
Siegel S (1956) Non-parametric Statistics for the Behavioral Sciences McGraw–Hill
Smirnov N (1933) Estimate of deviation between empirical distribution functions in two independent samples Bull. Moscow Univ. 2(2) 3–16
Smirnov N (1948) Table for estimating the goodness of fit of empirical distributions Ann. Math. Statist. 19 279–281

5 Arguments

1:   N – INTEGERInput
On entry: n, the number of observations in the sample.
Constraint: N≥1.
2:   X N – REAL (KIND=nag_wp) arrayInput
On entry: the sample observations, x 1,x 2,…,xn.
3:   CDF – REAL (KIND=nag_wp) FUNCTION, supplied by the user.External Procedure
CDF must return the value of the theoretical (null) cumulative distribution function for a given value of its argument.
The specification of CDF is:
FUNCTION CDF ( X)
REAL (KIND=nag_wp) CDF
REAL (KIND=nag_wp) X
1:   X – REAL (KIND=nag_wp)Input
On entry: the argument for which CDF must be evaluated.
CDF must either be a module subprogram USEd by, or declared as EXTERNAL in, the (sub)program from which G08CCF is called. Arguments denoted as Input must not be changed by this procedure.
Constraint: CDF must always return a value in the range 0.0,1.0 and CDF must always satify the condition that CDF x 1≤CDF x 2 for any x 1≤x 2.
4:   NTYPE – INTEGERInput
On entry: the statistic to be calculated, i.e., the choice of alternative hypothesis.
NTYPE=1
Computes Dn, to test H 0 against H 1.
NTYPE=2
Computes Dn+, to test H 0 against H 2.
NTYPE=3
Computes Dn-, to test H 0 against H 3.
Constraint: NTYPE=1, 2 or 3.
5:   D – REAL (KIND=nag_wp)Output
On exit: the Kolmogorov–Smirnov test statistic ( D n , D n + or D n - according to the value of NTYPE).
6:   Z – REAL (KIND=nag_wp)Output
On exit: a standardized value, Z, of the test statistic, D, without the continuity correction applied.
7:   P – REAL (KIND=nag_wp)Output
On exit: the probability, p, associated with the observed value of D, where D may Dn, Dn+ or Dn- depending on the value of NTYPE (see Section 3).
8:   SX N – REAL (KIND=nag_wp) arrayOutput
On exit: the sample observations, x 1,x 2,…,xn, sorted in ascending order.
9:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, N<1.
IFAIL=2
On entry, NTYPE≠1, 2 or 3.
IFAIL=3
The supplied theoretical cumulative distribution function returns a value less than 0.0 or greater than 1.0, thereby violating the definition of the cumulative distribution function.
IFAIL=4
The supplied theoretical cumulative distribution function is not a nondecreasing function thereby violating the definition of a cumulative distribution function, that is F 0 x>F 0 y for some x<y.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

For most cases the approximation for p given when n>100 has a relative error of less than 0.01. The two-sided probability is approximated by doubling the one-sided probability. This is only good for small p, that is p<0.10, but very poor for large p. The error is always on the conservative side.

8 Parallelism and Performance

G08CCF is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The time taken by G08CCF increases with n until n>100 at which point it drops and then increases slowly.
For a discrete theoretical cumulative distribution function F 0 x, Dn-=max F 0 x i-Sn x i,0. Thus if you wish to provide a discrete distribution function the following adjustment needs to be made,
  • for Dn+, return F x as x as usual;
  • for Dn-, return F x-d at x where d is the discrete jump in the distribution. For example d=1 for the Poisson or binomial distributions.

10 Example

The following example performs the one sample Kolmogorov–Smirnov test to test whether a sample of 30 observations arise firstly from a uniform distribution U 0,1 or secondly from a Normal distribution with mean 0.75 and standard deviation 0.5. The two-sided test statistic, Dn, the standardized test statistic, Z, and the upper tail probability, p, are computed and then printed for each test.

10.1 Program Text

Program Text (g08ccfe.f90)

10.2 Program Data

Program Data (g08ccfe.d)

10.3 Program Results

Program Results (g08ccfe.r)

G08 Chapter Contents
G08 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


G08CDF : NAG Library, Mark 26

G08 Chapter Contents
G08 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

G08CDF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

G08CDF performs the two sample Kolmogorov–Smirnov distribution test.

2 Specification

SUBROUTINE G08CDF ( N1, X, N2, Y, NTYPE, D, Z, P, SX, SY, IFAIL)
INTEGER | N1, N2, NTYPE, IFAIL
REAL (KIND=nag_wp) | X(N1), Y(N2), D, Z, P, SX(N1), SY(N2)

3 Description

The data consists of two independent samples, one of size n 1, denoted by x 1,x 2,…,x n 1, and the other of size n 2 denoted by y 1,y 2,…,y n 2. Let F x and G x represent their respective, unknown, distribution functions. Also let S 1 x and S 2 x denote the values of the sample cumulative distribution functions at the point x for the two samples respectively.
The Kolmogorov–Smirnov test provides a test of the null hypothesis H 0: F x=G x against one of the following alternative hypotheses:
(i) | H 1: F x≠G x.
(ii) | H 2: F x>G x. This alternative hypothesis is sometimes stated as, ‘The x's tend to be smaller than the y's’, i.e., it would be demonstrated in practical terms if the values of S 1 x tended to exceed the corresponding values of S 2 x.
(iii) | H 3: F x<G x. This alternative hypothesis is sometimes stated as, ‘The x's tend to be larger than the y's’, i.e., it would be demonstrated in practical terms if the values of S 2 x tended to exceed the corresponding values of S 1 x.
One of the following test statistics is computed depending on the particular alternative null hypothesis specified (see the description of the argument NTYPE in Section 5).
For the alternative hypothesis H 1.
  • D n 1,n 2 – the largest absolute deviation between the two sample cumulative distribution functions.
For the alternative hypothesis H 2.
  • D n 1,n 2+ – the largest positive deviation between the sample cumulative distribution function of the first sample, S 1 x, and the sample cumulative distribution function of the second sample, S 2 x. Formally D n 1,n 2+=max S 1 x-S 2 x,0.
For the alternative hypothesis H 3.
  • D n 1,n 2- – the largest positive deviation between the sample cumulative distribution function of the second sample, S 2 x, and the sample cumulative distribution function of the first sample, S 1 x. Formally D n 1,n 2-=max S 2 x-S 1 x,0.
G08CDF also returns the standardized statistic Z=n 1+n 2 n 1n 2 ×D, where D may be D n 1,n 2, D n 1,n 2+ or D n 1,n 2- depending on the choice of the alternative hypothesis. The distribution of this statistic converges asymptotically to a distribution given by Smirnov as n 1 and n 2 increase; see Feller (1948), Kendall and Stuart (1973), Kim and Jenrich (1973), Smirnov (1933) or Smirnov (1948).
The probability, under the null hypothesis, of obtaining a value of the test statistic as extreme as that observed, is computed. If max n 1,n 2≤2500 and n 1n 2≤10000 then an exact method given by Kim and Jenrich (see Kim and Jenrich (1973)) is used. Otherwise p is computed using the approximations suggested by Kim and Jenrich (1973). Note that the method used is only exact for continuous theoretical distributions. This method computes the two-sided probability. The one-sided probabilities are estimated by halving the two-sided probability. This is a good estimate for small p, that is p≤0.10, but it becomes very poor for larger p.

4 References

Conover W J (1980) Practical Nonparametric Statistics Wiley
Feller W (1948) On the Kolmogorov–Smirnov limit theorems for empirical distributions Ann. Math. Statist. 19 179–181
Kendall M G and Stuart A (1973) The Advanced Theory of Statistics (Volume 2) (3rd Edition) Griffin
Kim P J and Jenrich R I (1973) Tables of exact sampling distribution of the two sample Kolmogorov–Smirnov criterion D mn m<n Selected Tables in Mathematical Statistics 1 80–129 American Mathematical Society
Siegel S (1956) Non-parametric Statistics for the Behavioral Sciences McGraw–Hill
Smirnov N (1933) Estimate of deviation between empirical distribution functions in two independent samples Bull. Moscow Univ. 2(2) 3–16
Smirnov N (1948) Table for estimating the goodness of fit of empirical distributions Ann. Math. Statist. 19 279–281

5 Arguments

1:   N1 – INTEGERInput
On entry: the number of observations in the first sample, n 1.
Constraint: N1≥1.
2:   X N1 – REAL (KIND=nag_wp) arrayInput
On entry: the observations from the first sample, x 1,x 2,…,x n 1.
3:   N2 – INTEGERInput
On entry: the number of observations in the second sample, n 2.
Constraint: N2≥1.
4:   Y N2 – REAL (KIND=nag_wp) arrayInput
On entry: the observations from the second sample, y 1,y 2,…,y n 2.
5:   NTYPE – INTEGERInput
On entry: the statistic to be computed, i.e., the choice of alternative hypothesis.
NTYPE=1
Computes D n 1n 2, to test against H 1.
NTYPE=2
Computes D n 1n 2+, to test against H 2.
NTYPE=3
Computes D n 1n 2-, to test against H 3.
Constraint: NTYPE=1, 2 or 3.
6:   D – REAL (KIND=nag_wp)Output
On exit: the Kolmogorov–Smirnov test statistic (D n 1n 2, D n 1n 2+ or D n 1n 2- according to the value of NTYPE).
7:   Z – REAL (KIND=nag_wp)Output
On exit: a standardized value, Z , of the test statistic, D , without any correction for continuity.
8:   P – REAL (KIND=nag_wp)Output
On exit: the tail probability associated with the observed value of D, where D may be D n 1,n 2,D n 1,n 2+ or D n 1,n 2- depending on the value of NTYPE (see Section 3).
9:   SX N1 – REAL (KIND=nag_wp) arrayOutput
On exit: the observations from the first sample sorted in ascending order.
10:   SY N2 – REAL (KIND=nag_wp) arrayOutput
On exit: the observations from the second sample sorted in ascending order.
11:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, | N1<1,
or | N2<1.
IFAIL=2
On entry, NTYPE≠1, 2 or 3.
IFAIL=3
The iterative procedure used in the approximation of the probability for large n 1 and n 2 did not converge. For the two-sided test, p=1 is returned. For the one-sided test, p=0.5 is returned.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

The large sample distributions used as approximations to the exact distribution should have a relative error of less than 5% for most cases.

8 Parallelism and Performance

G08CDF is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The time taken by G08CDF increases with n 1 and n 2, until n 1n 2>10000 or max n 1,n 2≥2500. At this point one of the approximations is used and the time decreases significantly. The time then increases again modestly with n 1 and n 2.

10 Example

This example computes the two-sided Kolmogorov–Smirnov test statistic for two independent samples of size 100 and 50 respectively. The first sample is from a uniform distribution U 0,2. The second sample is from a uniform distribution U 0.25,2.25. The test statistic, D n 1,n 2, the standardized test statistic, Z, and the tail probability, p, are computed and printed.

10.1 Program Text

Program Text (g08cdfe.f90)

10.2 Program Data

Program Data (g08cdfe.d)

10.3 Program Results

Program Results (g08cdfe.r)

G08 Chapter Contents
G08 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


G08CGF : NAG Library, Mark 26

G08 Chapter Contents
G08 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

G08CGF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

G08CGF computes the test statistic for the χ 2 goodness-of-fit test for data with a chosen number of class intervals.

2 Specification

SUBROUTINE G08CGF ( NCLASS, IFREQ, CB, DIST, PAR, NPEST, PROB, CHISQ, P, NDF, EVAL, CHISQI, IFAIL)
INTEGER | NCLASS, IFREQ(NCLASS), NPEST, NDF, IFAIL
REAL (KIND=nag_wp) | CB(NCLASS-1), PAR(2), PROB(NCLASS), CHISQ, P, EVAL(NCLASS), CHISQI(NCLASS)
CHARACTER(1) | DIST

3 Description

The χ 2 goodness-of-fit test performed by G08CGF is used to test the null hypothesis that a random sample arises from a specified distribution against the alternative hypothesis that the sample does not arise from the specified distribution.
Given a sample of size n, denoted by x 1,x 2,…,xn, drawn from a random variable X, and that the data has been grouped into k classes,
x≤c 1, c i-1<x≤ci, i=2,3,…,k-1, x>c k-1,
then the χ 2 goodness-of-fit test statistic is defined by
X 2=∑i=1 k Oi-Ei 2 Ei,
where Oi is the observed frequency of the ith class, and Ei is the expected frequency of the ith class.
The expected frequencies are computed as
Ei=pi×n,
where pi is the probability that X lies in the ith class, that is
p 1=P X≤c 1, pi=P c i-1<X≤ci, i=2,3,…,k-1, pk=P X>c k-1.
These probabilities are either taken from a common probability distribution or are supplied by you. The available probability distributions within this routine are:
  • Normal distribution with mean μ, variance σ 2;
  • uniform distribution on the interval a,b;
  • exponential distribution with probability density function pdf=λ e-λx;
  • χ 2-distribution with f degrees of freedom; and
  • gamma distribution with pdf= x α-1e-x/β Γ α βα .
You must supply the frequencies and classes. Given a set of data and classes the frequencies may be calculated using G01AEF.
G08CGF returns the χ 2 test statistic, X 2, together with its degrees of freedom and the upper tail probability from the χ 2-distribution associated with the test statistic. Note that the use of the χ 2-distribution as an approximation to the distribution of the test statistic improves as the expected values in each class increase.

4 References

Conover W J (1980) Practical Nonparametric Statistics Wiley
Kendall M G and Stuart A (1973) The Advanced Theory of Statistics (Volume 2) (3rd Edition) Griffin
Siegel S (1956) Non-parametric Statistics for the Behavioral Sciences McGraw–Hill

5 Arguments

1:   NCLASS – INTEGERInput
On entry: k, the number of classes into which the data is divided.
Constraint: NCLASS≥2.
2:   IFREQ NCLASS – INTEGER arrayInput
On entry: IFREQ i must specify the frequency of the ith class, Oi, for i=1,2,…,k.
Constraint: IFREQ i≥0, for i=1,2,…,k.
3:   CB NCLASS-1 – REAL (KIND=nag_wp) arrayInput
On entry: CB i must specify the upper boundary value for the ith class, for i=1,2,…,k-1.
Constraint: CB 1<CB 2<⋯<CB NCLASS-1. For the exponential, gamma and χ 2-distributions CB 1≥0.0.
4:   DIST – CHARACTER(1)Input
On entry: indicates for which distribution the test is to be carried out.
DIST='N'
The Normal distribution is used.
DIST='U'
The uniform distribution is used.
DIST='E'
The exponential distribution is used.
DIST='C'
The χ 2-distribution is used.
DIST='G'
The gamma distribution is used.
DIST='A'
You must supply the class probabilities in the array PROB.
Constraint: DIST='N', 'U', 'E', 'C', 'G' or 'A'.
5:   PAR 2 – REAL (KIND=nag_wp) arrayInput
On entry: must contain the parameters of the distribution which is being tested. If you supply the probabilities (i.e., DIST='A') the array PAR is not referenced.
If a Normal distribution is used then PAR 1 and PAR 2 must contain the mean, μ, and the variance, σ 2, respectively.
If a uniform distribution is used then PAR 1 and PAR 2 must contain the boundaries a and b respectively.
If an exponential distribution is used then PAR 1 must contain the parameter λ. PAR 2 is not used.
If a χ 2-distribution is used then PAR 1 must contain the number of degrees of freedom. PAR 2 is not used.
If a gamma distribution is used PAR 1 and PAR 2 must contain the parameters α and β respectively.
Constraints:
  • if DIST='N', PAR 2>0.0;
  • if DIST='U', PAR 1<PAR 2 and PAR 1≤CB 1 and PAR 2≥CB NCLASS-1;
  • if DIST='E', PAR 1>0.0;
  • if DIST='C', PAR 1>0.0;
  • if DIST='G', PAR 1>0.0 and PAR 2>0.0.
6:   NPEST – INTEGERInput
On entry: the number of estimated parameters of the distribution.
Constraint: 0≤NPEST<NCLASS-1.
7:   PROB NCLASS – REAL (KIND=nag_wp) arrayInput
On entry: if you are supplying the probability distribution (i.e., DIST='A') then PROB i must contain the probability that X lies in the ith class.
If DIST≠'A', PROB is not referenced.
Constraint: if DIST='A', ∑i=1 k PROB i=1.0, PROB i>0.0, for i=1,2,…,k.
8:   CHISQ – REAL (KIND=nag_wp)Output
On exit: the test statistic, X 2, for the χ 2 goodness-of-fit test.
9:   P – REAL (KIND=nag_wp)Output
On exit: the upper tail probability from the χ 2-distribution associated with the test statistic, X 2, and the number of degrees of freedom.
10:   NDF – INTEGEROutput
On exit: contains NCLASS-1-NPEST, the degrees of freedom associated with the test.
11:   EVAL NCLASS – REAL (KIND=nag_wp) arrayOutput
On exit: EVAL i contains the expected frequency for the ith class, Ei, for i=1,2,…,k.
12:   CHISQI NCLASS – REAL (KIND=nag_wp) arrayOutput
On exit: CHISQI i contains the contribution from the ith class to the test statistic, that is, Oi-Ei 2/Ei, for i=1,2,…,k.
13:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, because for this routine the values of the output arguments may be useful even if IFAIL≠0 on exit, the recommended value is -1. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Note: G08CGF may return useful information for one or more of the following detected errors or warnings.
Errors or warnings detected by the routine:
IFAIL=1
On entry, NCLASS<2.
IFAIL=2
On entry, DIST is invalid.
IFAIL=3
On entry, | NPEST<0,
or | NPEST≥NCLASS-1.
IFAIL=4
On entry, IFREQ i<0.0 for some i, for i=1,2,…,k.
IFAIL=5
On entry, the elements of CB are not in ascending order. That is, CB i≤CB i-1 for some i, for i=2,3,…,k-1.
IFAIL=6
On entry, DIST='E', 'C' or 'G' and CB 1<0.0. No negative class boundary values are valid for the exponential, gamma or χ 2-distributions.
IFAIL=7
On entry, the values provided in PAR are invalid.
IFAIL=8
On entry, | with DIST='A', PROB i≤0.0 for some i, for i=1,2,…,k,
or | ∑i=1 k PROB i≠1.0.
IFAIL=9
An expected frequency is equal to zero when the observed frequency was not.
IFAIL=10
This is a warning that expected values for certain classes are less than 1.0. This implies that we cannot be confident that the χ 2-distribution is a good approximation to the distribution of the test statistic.
IFAIL=11
The solution obtained when calculating the probability for a certain class for the gamma or χ 2-distribution did not converge in 600 iterations. The solution may be an adequate approximation.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

The computations are believed to be stable.

8 Parallelism and Performance

G08CGF is not threaded in any implementation.

9 Further Comments

The time taken by G08CGF is dependent both on the distribution chosen and on the number of classes, k.

10 Example

This example applies the χ 2 goodness-of-fit test to test whether there is evidence to suggest that a sample of 100 randomly generated observations do not arise from a uniform distribution U 0,1. The class intervals are calculated such that the interval 0,1 is divided into five equal classes. The frequencies for each class are calculated using G01AEF.

10.1 Program Text

Program Text (g08cgfe.f90)

10.2 Program Data

Program Data (g08cgfe.d)

10.3 Program Results

Program Results (g08cgfe.r)

G08 Chapter Contents
G08 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


G08CHF : NAG Library, Mark 26

G08 Chapter Contents
G08 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

G08CHF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

G08CHF calculates the Anderson–Darling goodness-of-fit test statistic.

2 Specification

FUNCTION G08CHF ( N, ISSORT, Y, IFAIL)
REAL (KIND=nag_wp) G08CHF
INTEGER | N, IFAIL
REAL (KIND=nag_wp) | Y(N)
LOGICAL | ISSORT

3 Description

Denote by A 2 the Anderson–Darling test statistic for n observations y 1,y 2,…,yn of a variable Y assumed to be standard uniform and sorted in ascending order, then:
A 2 = -n-S ;
where:
S = ∑ i=1 n 2 i-1 n ln⁡yi + ln 1- y n-i+1 .
When observations of a random variable X are non-uniformly distributed, the probability integral transformation (PIT):
Y=F X ,
where F is the cumulative distribution function of the distribution of interest, yields a uniformly distributed random variable Y. The PIT is true only if all parameters of a distribution are known as opposed to estimated; otherwise it is an approximation.

4 References

Anderson T W and Darling D A (1952) Asymptotic theory of certain ‘goodness-of-fit’ criteria based on stochastic processes Annals of Mathematical Statistics 23 193–212

5 Arguments

1:   N – INTEGERInput
On entry: n, the number of observations.
Constraint: N>1.
2:   ISSORT – LOGICALInput
On entry: set ISSORT=.TRUE. if the observations are sorted in ascending order; otherwise the function will sort the observations.
3:   Y N – REAL (KIND=nag_wp) arrayInput/Output
On entry: yi, for i=1,2,…,n, the n observations.
On exit: if ISSORT=.FALSE., the data sorted in ascending order; otherwise the array is unchanged.
Constraint: if ISSORT=.TRUE., the values must be sorted in ascending order. Each yi must lie in the interval 0,1.
4:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, N=value.
Constraint: N>1.
IFAIL=3
ISSORT=.TRUE. and the data in Y is not sorted in ascending order.
IFAIL=9
The data in Y must lie in the interval 0,1.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

Not applicable.

8 Parallelism and Performance

G08CHF is not threaded in any implementation.

9 Further Comments

None.

10 Example

This example calculates the A 2 statistic for data assumed to arise from an exponential distribution with a sample parameter estimate and simulates its p-value using the NAG basic random number generator.

10.1 Program Text

Program Text (g08chfe.f90)

10.2 Program Data

Program Data (g08chfe.d)

10.3 Program Results

Program Results (g08chfe.r)

G08 Chapter Contents
G08 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


G08CJF : NAG Library, Mark 26

G08 Chapter Contents
G08 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

G08CJF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

G08CJF calculates the Anderson–Darling goodness-of-fit test statistic and its probability for the case of standard uniformly distributed data.

2 Specification

SUBROUTINE G08CJF ( N, ISSORT, Y, A2, P, IFAIL)
INTEGER | N, IFAIL
REAL (KIND=nag_wp) | Y(N), A2, P
LOGICAL | ISSORT

3 Description

Calculates the Anderson–Darling test statistic A 2 (see G08CHF) and its upper tail probability by using the approximation method of Marsaglia and Marsaglia (2004) for the case of uniformly distributed data.

4 References

Anderson T W and Darling D A (1952) Asymptotic theory of certain ‘goodness-of-fit’ criteria based on stochastic processes Annals of Mathematical Statistics 23 193–212
Marsaglia G and Marsaglia J (2004) Evaluating the Anderson–Darling distribution J. Statist. Software 9(2)

5 Arguments

1:   N – INTEGERInput
On entry: n, the number of observations.
Constraint: N>1.
2:   ISSORT – LOGICALInput
On entry: set ISSORT=.TRUE. if the observations are sorted in ascending order; otherwise the routine will sort the observations.
3:   Y N – REAL (KIND=nag_wp) arrayInput/Output
On entry: yi, for i=1,2,…,n, the n observations.
On exit: if ISSORT=.FALSE., the data sorted in ascending order; otherwise the array is unchanged.
Constraint: if ISSORT=.TRUE., the values must be sorted in ascending order. Each yi must lie in the interval 0,1.
4:   A2 – REAL (KIND=nag_wp)Output
On exit: A 2, the Anderson–Darling test statistic.
5:   P – REAL (KIND=nag_wp)Output
On exit: p, the upper tail probability for A 2.
6:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, N=value.
Constraint: N>1.
IFAIL=3
ISSORT=.TRUE. and the data in Y is not sorted in ascending order.
IFAIL=9
The data in Y must lie in the interval 0,1.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

Probabilities greater than approximately 0.09 are accurate to five decimal places; lower value probabilities are accurate to six decimal places.

8 Parallelism and Performance

G08CJF is not threaded in any implementation.

9 Further Comments

None.

10 Example

This example calculates the A 2 statistic and its p-value for uniform data obtained by transforming exponential variates.

10.1 Program Text

Program Text (g08cjfe.f90)

10.2 Program Data

Program Data (g08cjfe.d)

10.3 Program Results

Program Results (g08cjfe.r)

G08 Chapter Contents
G08 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


G08CKF : NAG Library, Mark 26

G08 Chapter Contents
G08 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

G08CKF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

G08CKF calculates the Anderson–Darling goodness-of-fit test statistic and its probability for the case of a fully-unspecified Normal distribution.

2 Specification

SUBROUTINE G08CKF ( N, ISSORT, Y, YBAR, YVAR, A2, AA2, P, IFAIL)
INTEGER | N, IFAIL
REAL (KIND=nag_wp) | Y(N), YBAR, YVAR, A2, AA2, P
LOGICAL | ISSORT

3 Description

Calculates the Anderson–Darling test statistic A 2 (see G08CHF) and its upper tail probability for the small sample correction:
Adjusted ​ A 2 = A 2 1+0.75/n+ 2.25/n 2 ,
for n observations.

4 References

Anderson T W and Darling D A (1952) Asymptotic theory of certain ‘goodness-of-fit’ criteria based on stochastic processes Annals of Mathematical Statistics 23 193–212
Stephens M A and D'Agostino R B (1986) Goodness-of-Fit Techniques Marcel Dekker, New York

5 Arguments

1:   N – INTEGERInput
On entry: n, the number of observations.
Constraint: N>1.
2:   ISSORT – LOGICALInput
On entry: set ISSORT=.TRUE. if the observations are sorted in ascending order; otherwise the routine will sort the observations.
3:   Y N – REAL (KIND=nag_wp) arrayInput
On entry: yi, for i=1,2,…,n, the n observations.
Constraint: if ISSORT=.TRUE., the values must be sorted in ascending order.
4:   YBAR – REAL (KIND=nag_wp)Output
On exit: the maximum likelihood estimate of mean.
5:   YVAR – REAL (KIND=nag_wp)Output
On exit: the maximum likelihood estimate of variance.
6:   A2 – REAL (KIND=nag_wp)Output
On exit: A 2, the Anderson–Darling test statistic.
7:   AA2 – REAL (KIND=nag_wp)Output
On exit: the adjusted A 2.
8:   P – REAL (KIND=nag_wp)Output
On exit: p, the upper tail probability for the adjusted A 2.
9:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, N=value.
Constraint: N>1.
IFAIL=3
ISSORT=.TRUE. and the data in Y is not sorted in ascending order.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

Probabilities are calculated using piecewise polynomial approximations to values estimated by simulation.

8 Parallelism and Performance

G08CKF is not threaded in any implementation.

9 Further Comments

None.

10 Example

This example calculates the A 2 statistics for data assumed to arise from a fully-unspecified Normal distribution and the p-value.

10.1 Program Text

Program Text (g08ckfe.f90)

10.2 Program Data

Program Data (g08ckfe.d)

10.3 Program Results

Program Results (g08ckfe.r)

G08 Chapter Contents
G08 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


G08CLF : NAG Library, Mark 26

G08 Chapter Contents
G08 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

G08CLF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

G08CLF calculates the Anderson–Darling goodness-of-fit test statistic and its probability for the case of an unspecified exponential distribution.

2 Specification

SUBROUTINE G08CLF ( N, ISSORT, Y, YBAR, A2, AA2, P, IFAIL)
INTEGER | N, IFAIL
REAL (KIND=nag_wp) | Y(N), YBAR, A2, AA2, P
LOGICAL | ISSORT

3 Description

Calculates the Anderson–Darling test statistic A 2 (see G08CHF) and its upper tail probability for the small sample correction:
Adjusted ​ A 2 = A 2 1+0.6/n ,
for n observations.

4 References

Anderson T W and Darling D A (1952) Asymptotic theory of certain ‘goodness-of-fit’ criteria based on stochastic processes Annals of Mathematical Statistics 23 193–212
Stephens M A and D'Agostino R B (1986) Goodness-of-Fit Techniques Marcel Dekker, New York

5 Arguments

1:   N – INTEGERInput
On entry: n, the number of observations.
Constraint: N>1.
2:   ISSORT – LOGICALInput
On entry: set ISSORT=.TRUE. if the observations are sorted in ascending order; otherwise the routine will sort the observations.
3:   Y N – REAL (KIND=nag_wp) arrayInput
On entry: yi, for i=1,2,…,n, the n observations.
Constraint: if ISSORT=.TRUE., values must be sorted in ascending order. Each yi must be greater than zero.
4:   YBAR – REAL (KIND=nag_wp)Output
On exit: the maximum likelihood estimate of mean.
5:   A2 – REAL (KIND=nag_wp)Output
On exit: A 2, the Anderson–Darling test statistic.
6:   AA2 – REAL (KIND=nag_wp)Output
On exit: the adjusted A 2.
7:   P – REAL (KIND=nag_wp)Output
On exit: p, the upper tail probability for the adjusted A 2.
8:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, N=value.
Constraint: N>1.
IFAIL=3
ISSORT=.TRUE. and the data in Y is not sorted in ascending order.
IFAIL=9
The data in Y must be greater than zero.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

Probabilities are calculated using piecewise polynomial approximations to values estimated by simulation.

8 Parallelism and Performance

G08CLF is not threaded in any implementation.

9 Further Comments

None.

10 Example

This example calculates the A 2 statistics for data assumed to arise from an unspecified exponential distribution and calculates the p-value.

10.1 Program Text

Program Text (g08clfe.f90)

10.2 Program Data

Program Data (g08clfe.d)

10.3 Program Results

Program Results (g08clfe.r)

G08 Chapter Contents
G08 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


G08 Chapter Contents : NAG Library Manual, Mark 26

G08 Chapter Introduction
NAG Library Manual

NAG Library Chapter Contents

G08 – Nonparametric Statistics

G08 Chapter Introduction – a description of the Chapter and an overview of the algorithms available

Routine Name | Mark of Introduction | Purpose
G08AAF Example Text Example Data | 8 | nagf_nonpar_test_sign Sign test on two paired samples
G08ACF Example Text Example Data | 8 | nagf_nonpar_test_median Median test on two samples of unequal size
G08AEF Example Text Example Data | 8 | nagf_nonpar_test_friedman Friedman two-way analysis of variance on k matched samples
G08AFF Example Text Example Data | 8 | nagf_nonpar_test_kruskal Kruskal–Wallis one-way analysis of variance on k samples of unequal size
G08AGF Example Text Example Data | 14 | nagf_nonpar_test_wilcoxon Performs the Wilcoxon one-sample (matched pairs) signed rank test
G08AHF Example Text Example Data | 14 | nagf_nonpar_test_mwu Performs the Mann–Whitney U test on two independent samples
G08AJF Example Text Example Data | 14 | nagf_nonpar_prob_mwu_noties Computes the exact probabilities for the Mann–Whitney U statistic, no ties in pooled sample
G08AKF Example Text Example Data | 14 | nagf_nonpar_prob_mwu_ties Computes the exact probabilities for the Mann–Whitney U statistic, ties in pooled sample
G08ALF Example Text Example Data | 15 | nagf_nonpar_test_cochranq Performs the Cochran Q test on cross-classified binary data
G08BAF Example Text Example Data | 8 | nagf_nonpar_test_mooddavid Mood's and David's tests on two samples of unequal size
G08CBF Example Text Example Data | 14 | nagf_nonpar_test_ks_1sample Performs the one-sample Kolmogorov–Smirnov test for standard distributions
G08CCF Example Text Example Data | 14 | nagf_nonpar_test_ks_1sample_user Performs the one-sample Kolmogorov–Smirnov test for a user-supplied distribution
G08CDF Example Text Example Data | 14 | nagf_nonpar_test_ks_2sample Performs the two-sample Kolmogorov–Smirnov test
G08CGF Example Text Example Data | 14 | nagf_nonpar_test_chisq Performs the χ 2 goodness-of-fit test, for standard continuous distributions
G08CHF Example Text Example Data | 23 | nagf_nonpar_gofstat_anddar Calculates the Anderson–Darling goodness-of-fit test statistic
G08CJF Example Text Example Data | 23 | nagf_nonpar_gofstat_anddar_unif Calculates the Anderson–Darling goodness-of-fit test statistic and its probability for the case of uniformly distributed data
G08CKF Example Text Example Data | 23 | nagf_nonpar_gofstat_anddar_normal Calculates the Anderson–Darling goodness-of-fit test statistic and its probability for the case of a fully-unspecified Normal distribution
G08CLF Example Text Example Data | 23 | nagf_nonpar_gofstat_anddar_exp Calculates the Anderson–Darling goodness-of-fit test statistic and its probability for the case of an unspecified exponential distribution
G08DAF Example Text Example Data | 8 | nagf_nonpar_concordance_kendall Kendall's coefficient of concordance
G08EAF Example Text Example Data | 14 | nagf_nonpar_randtest_runs Performs the runs up or runs down test for randomness
G08EBF Example Text Example Data | 14 | nagf_nonpar_randtest_pairs Performs the pairs (serial) test for randomness
G08ECF Example Text Example Data | 14 | nagf_nonpar_randtest_triplets Performs the triplets test for randomness
G08EDF Example Text Example Data | 14 | nagf_nonpar_randtest_gaps Performs the gaps test for randomness
G08RAF Example Text Example Data | 12 | nagf_nonpar_rank_regsn Regression using ranks, uncensored data
G08RBF Example Text Example Data | 12 | nagf_nonpar_rank_regsn_censored Regression using ranks, right-censored data
G08 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


G08DAF : NAG Library, Mark 26

G08 Chapter Contents
G08 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

G08DAF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

G08DAF calculates Kendall's coefficient of concordance on k independent rankings of n objects or individuals.

2 Specification

SUBROUTINE G08DAF ( X, LDX, K, N, RNK, W, P, IFAIL)
INTEGER | LDX, K, N, IFAIL
REAL (KIND=nag_wp) | X(LDX,N), RNK(LDX,N), W, P

3 Description

Kendall's coefficient of concordance measures the degree of agreement between k comparisons of n objects, the scores in the ith comparison being denoted by
x i 1,x i 2,…,x in.
The hypothesis under test, H 0, often called the null hypothesis, is that there is no agreement between the comparisons, and this is to be tested against the alternative hypothesis, H 1, that there is some agreement.
The n scores for each comparison are ranked, the rank r ij denoting the rank of object j in comparison i, and all ranks lying between 1 and n. Average ranks are assigned to tied scores.
For each of the n objects, the k ranks are totalled, giving rank sums Rj, for j=1,2,…,n. Under H 0, all the Rj would be approximately equal to the average rank sum k n+1/2. The total squared deviation of the Rj from this average value is therefore a measure of the departure from H 0 exhibited by the data. If there were complete agreement between the comparisons, the rank sums Rj would have the values k,2 k,…,nk (or some permutation thereof). The total squared deviation of these values is k 2 n 3-n/12.
Kendall's coefficient of concordance is the ratio
W = ∑ j=1 n Rj - 12 k n+1 2 112 k 2 n 3-n
and lies between 0 and 1, the value 0 indicating complete disagreement, and 1 indicating complete agreement.
If there are tied rankings within comparisons, W is corrected by subtracting k∑T from the denominator, where T=∑t 3-t/12, each t being the number of occurrences of each tied rank within a comparison, and the summation of T being over all comparisons containing ties.
G08DAF returns the value of W, and also an approximation, p, of the significance of the observed W. (For n>7,k n-1 W approximately follows a χ n-1 2 distribution, so large values of W imply rejection of H 0.) H 0 is rejected by a test of chosen size α if p<α. If n≤7, tables should be used to establish the significance of W (e.g., Table R of Siegel (1956)).

4 References

Siegel S (1956) Non-parametric Statistics for the Behavioral Sciences McGraw–Hill

5 Arguments

1:   X LDXN – REAL (KIND=nag_wp) arrayInput
On entry: X ij must be set to the value x ij of object j in comparison i, for i=1,2,…,k and j=1,2,…,n.
2:   LDX – INTEGERInput
On entry: the first dimension of the arrays X and RNK as declared in the (sub)program from which G08DAF is called.
Constraint: LDX≥K.
3:   K – INTEGERInput
On entry: k, the number of comparisons.
Constraint: K≥2.
4:   N – INTEGERInput
On entry: n, the number of objects.
Constraint: N≥2.
5:   RNK LDXN – REAL (KIND=nag_wp) arrayWorkspace
6:   W – REAL (KIND=nag_wp)Output
On exit: the value of Kendall's coefficient of concordance, W.
7:   P – REAL (KIND=nag_wp)Output
On exit: the approximate significance, p, of W.
8:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, N<2.
IFAIL=2
On entry, LDX<K.
IFAIL=3
On entry, K≤1.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

All computations are believed to be stable. The statistic W should be accurate enough for all practical uses.

8 Parallelism and Performance

G08DAF is not threaded in any implementation.

9 Further Comments

The time taken by G08DAF is approximately proportional to the product nk.

10 Example

This example is taken from page 234 of Siegel (1956). The data consists of 10 objects ranked on three different variables: X, Y and Z. The computed values of Kendall's coefficient is significant at the 1% level of significance p=0.008<0.01, indicating that the null hypothesis of there being no agreement between the three rankings X, Y, Z may be rejected with reasonably high confidence.

10.1 Program Text

Program Text (g08dafe.f90)

10.2 Program Data

Program Data (g08dafe.d)

10.3 Program Results

Program Results (g08dafe.r)

G08 Chapter Contents
G08 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


G08EAF : NAG Library, Mark 26

G08 Chapter Contents
G08 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

G08EAF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

G08EAF performs a runs up (or a runs down) test on a sequence of observations.

2 Specification

SUBROUTINE G08EAF ( CL, N, X, M, MAXR, NRUNS, NCOUNT, EX, COV, LDCOV, CHI, DF, PROB, WRK, LWRK, IFAIL)
INTEGER | N, M, MAXR, NRUNS, NCOUNT(MAXR), LDCOV, LWRK, IFAIL
REAL (KIND=nag_wp) | X(N), EX(MAXR), COV(LDCOV,MAXR), CHI, DF, PROB, WRK(LWRK)
CHARACTER(1) | CL

3 Description

Runs tests may be used to investigate for trends in a sequence of observations. G08EAF computes statistics for the runs up test. If the runs down test is desired then each observation must be multiplied by -1 before G08EAF is called with the modified vector of observations. G08EAF may be used in two different modes:
(i) | a single call to G08EAF which computes all test statistics after counting the runs;
(ii) | multiple calls to G08EAF with the final test statistics only being computed in the last call.
The second mode is necessary if all the data do not fit into the memory. See argument CL in Section 5 for details on how to invoke each mode.
A run up is a sequence of numbers in increasing order. A run up ends at xk when xk>x k+1 and the new run then begins at x k+1. G08EAF counts the number of runs up of different lengths. Let ci denote the number of runs of length i, for i=1,2,…,r-1. The number of runs of length r or greater is then denoted by cr.
An unfinished run at the end of a sequence is not counted unless the sequence is part of an initial or intermediate call to G08EAF (i.e., unless there is another call to G08EAF to follow) in which case the unfinished run is used together with the beginning of the next sequence of numbers input to G08EAF in the next call. The following is a trivial example.
Suppose we called G08EAF twice with the following two sequences:
  • (0.20 0.40 0.45 0.40 0.15 0.75 0.95 0.23) and
  • (0.27 0.40 0.25 0.10 0.34 0.39 0.61 0.12).
Then after the second call G08EAF would have counted the runs up of the following lengths:
  • 3, 1, 3, 3, 1, and 4.
When the counting of runs is complete G08EAF computes the expected values and covariances of the counts, ci. For the details of the method used see Knuth (1981). An approximate χ 2 statistic with r degrees of freedom is computed, where
X 2= c-μc T Σ c -1 c-μc ,
where
  • c is the vector of counts, ci, for i=1,2,…,r,
  • μc is the vector of expected values,
  • ei, for i=1,2,…,r, where ei is the expected value for ci under the null hypothesis of randomness, and
  • Σc is the covariance matrix of c under the null hypothesis.
The use of the χ 2-distribution as an approximation to the exact distribution of the test statistic, X 2, improves as the length of the sequence relative to m increases and hence the expected value, e, increases.
You may specify the total number of runs to be found. If the specified number of runs is found before the end of a sequence G08EAF will exit before counting any further runs. The number of runs actually counted and used to compute the test statistic is returned via NRUNS.

4 References

Dagpunar J (1988) Principles of Random Variate Generation Oxford University Press
Knuth D E (1981) The Art of Computer Programming (Volume 2) (2nd Edition) Addison–Wesley
Morgan B J T (1984) Elements of Simulation Chapman and Hall
Ripley B D (1987) Stochastic Simulation Wiley

5 Arguments

1:   CL – CHARACTER(1)Input
On entry: must specify the type of call to G08EAF.
CL='S'
This is the one and only call to G08EAF (single call mode). All data are to be input at once. All test statistics are computed after the counting of runs is complete.
CL='F'
This is the first call to the routine. All initializations are carried out and the counting of runs begins. The final test statistics are not computed since further calls will be made to G08EAF.
CL='I'
This is an intermediate call during which the counts of runs are updated. The final test statistics are not computed since further calls will be made to G08EAF.
CL='L'
This is the last call to G08EAF. The test statistics are computed after the final counting of runs is completed.
Constraint: CL='S', 'F', 'I' or 'L'.
2:   N – INTEGERInput
On entry: n, the length of the current sequence of observations.
Constraints:
  • if CL='S', N≥3;
  • otherwise N≥1.
3:   X N – REAL (KIND=nag_wp) arrayInput
On entry: the sequence of observations.
4:   M – INTEGERInput
On entry: the maximum number of runs to be sought. If M≤0 then no limit is placed on the number of runs that are found.
M must not be changed between calls to G08EAF.
Constraint: if M≤N, CL='S'.
5:   MAXR – INTEGERInput
On entry: r, the length of the longest run for which tabulation is desired. That is, all runs with length greater than or equal to r are counted together.
MAXR must not be changed between calls to G08EAF.
Constraint: MAXR≥1 and if CL='S', MAXR<N.
6:   NRUNS – INTEGERInput/Output
On entry: if CL='S' or 'F', NRUNS need not be set.
If CL='I' or 'L', NRUNS must contain the value returned by the previous call to G08EAF.
On exit: the number of runs actually found.
7:   NCOUNT MAXR – INTEGER arrayInput/Output
On entry: if CL='S' or 'F', NCOUNT need not be set.
If CL='I' or 'L', NCOUNT must contain the values returned by the previous call to G08EAF.
On exit: the counts of runs of the different lengths, ci, for i=1,2,…,r.
8:   EX MAXR – REAL (KIND=nag_wp) arrayOutput
On exit: if CL='S' or 'L', (i.e., if it is the final exit) then EX contains the expected values of the counts, ei, for i=1,2,…,r.
Otherwise the elements of EX are not set.
9:   COV LDCOVMAXR – REAL (KIND=nag_wp) arrayOutput
On exit: if CL='S' or 'L' (i.e., if it is the final exit) then COV contains the covariance matrix of the counts, Σc.
Otherwise the elements of COV are not set.
10:   LDCOV – INTEGERInput
On entry: the first dimension of the array COV as declared in the (sub)program from which G08EAF is called.
Constraint: LDCOV≥MAXR.
11:   CHI – REAL (KIND=nag_wp)Output
On exit: if CL='S' or 'L' (i.e., if it is the final exit) then CHI contains the approximate χ 2 test statistic, X 2.
Otherwise CHI is not set.
12:   DF – REAL (KIND=nag_wp)Output
On exit: if CL='S' or 'L' (i.e., if it is the final exit) then DF contains the degrees of freedom of the χ 2 statistic.
Otherwise DF is not set.
13:   PROB – REAL (KIND=nag_wp)Output
On exit: if CL='S' or 'L', (i.e., if it is the final exit) then PROB contains the upper tail probability corresponding to the χ 2 test statistic, i.e., the significance level.
Otherwise PROB is not set.
14:   WRK LWRK – REAL (KIND=nag_wp) arrayWorkspace
15:   LWRK – INTEGERInput
On entry: the dimension of the array WRK as declared in the (sub)program from which G08EAF is called.
Constraint: LWRK≥MAXR×MAXR+5 2+1.
16:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, because for this routine the values of the output arguments may be useful even if IFAIL≠0 on exit, the recommended value is -1. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Note: G08EAF may return useful information for one or more of the following detected errors or warnings.
Errors or warnings detected by the routine:
IFAIL=1
On entry, CL=value.
Constraint: CL='S', 'F', 'I' or 'L'.
IFAIL=2
On entry, N=value.
Constraint: if CL='S', N≥3, otherwise N≥1.
IFAIL=3
On entry, M=value and N=value.
Constraint: if CL='S', M≤N.
IFAIL=4
On entry, MAXR=value.
Constraint: MAXR≥1.
On entry, MAXR=value and N=value.
Constraint: if CL='S', MAXR<N.
IFAIL=5
On entry, LDCOV=value and MAXR=value.
Constraint: LDCOV≥MAXR.
IFAIL=6
On entry, LWRK=value.
Constraint: LWRK≥MAXR×MAXR+5/2+1=value.
IFAIL=7
There is a tie in the sequence of observations.
IFAIL=8
The total length of the runs found is less than MAXR.
MAXR=value whereas the total length of all runs is value.
IFAIL=9
The covariance matrix stored in COV is not positive definite, thus the approximate χ 2 test statistic cannot be computed.
This may be because MAXR is too large relative to the length of the full sequence.
IFAIL=10
The number of runs requested were not found, only value out of the requested value where found.
All statistics are returned and may still be of use.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

The computations are believed to be stable. The computation of PROB given the values of CHI and DF will obtain a relative accuracy of five significant figures for most cases.

8 Parallelism and Performance

G08EAF is not thread safe and should not be called from a multithreaded user program. Please see Section 3.12.1 in How to Use the NAG Library and its Documentation for more information on thread safety.
G08EAF makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The time taken by G08EAF increases with the number of observations n, and also depends to some extent on whether the call to G08EAF is an only, first, intermediate or last call.

10 Example

The following program performs a runs up test on 500 pseudorandom numbers. G08EAF is called 5 times with 100 observations each time. No limit is placed on the number of runs to be counted. All runs of length 6 or more are counted together.

10.1 Program Text

Program Text (g08eafe.f90)

10.2 Program Data

Program Data (g08eafe.d)

10.3 Program Results

Program Results (g08eafe.r)

G08 Chapter Contents
G08 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


G08EBF : NAG Library, Mark 26

G08 Chapter Contents
G08 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

G08EBF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

G08EBF performs a pairs test on a sequence of observations in the interval 0,1.

2 Specification

SUBROUTINE G08EBF ( CL, N, X, MSIZE, LAG, NCOUNT, LDC, EX, CHI, DF, PROB, WRK, IFAIL)
INTEGER | N, MSIZE, LAG, NCOUNT(LDC,MSIZE), LDC, IFAIL
REAL (KIND=nag_wp) | X(N), EX, CHI, DF, PROB, WRK(2*LAG)
CHARACTER(1) | CL

3 Description

G08EBF computes the statistics for performing a pairs test which may be used to investigate deviations from randomness in a sequence, x=xi:i=1,2,…,n, of 0,1 observations.
For a given lag, l≥1, an m by m matrix, C, of counts is formed as follows. The element c jk of C is the number of pairs xi,x i+l such that
j-1 m≤xi<jm
k- 1 m≤x i+l<km
where i=1,3,5,…,n-1 if l=1, and i=1,2,…,l,2 l+1,2 l+2,…3 l,4 l+1,…,n-l, if l>1.
Note that all pairs formed are non-overlapping pairs and are thus independent under the assumption of randomness.
Under the assumption that the sequence is random, the expected number of pairs for each class (i.e., each element of the matrix of counts) is the same; that is, the pairs should be uniformly distributed over the unit square 0,1 2. Thus the expected number of pairs for each class is just the total number of pairs, ∑j,k=1 m c jk, divided by the number of classes, m 2.
The χ 2 test statistic used to test the hypothesis of randomness is defined as
X 2=∑j,k=1 m c jk-e 2 e,
where e=∑j,k=1 m c jk/m 2= expected number of pairs in each class.
The use of the χ 2-distribution as an approximation to the exact distribution of the test statistic, X 2, improves as the length of the sequence relative to m increases and hence the expected value, e, increases.
G08EBF may be used in two different modes:
(i) | a single call to G08EBF which computes all test statistics after counting the pairs;
(ii) | multiple calls to G08EBF with the final test statistics only being computed in the last call.
The second mode is necessary if all the data do not fit into the memory. See argument CL in Section 5 for details on how to invoke each mode.

4 References

Dagpunar J (1988) Principles of Random Variate Generation Oxford University Press
Knuth D E (1981) The Art of Computer Programming (Volume 2) (2nd Edition) Addison–Wesley
Morgan B J T (1984) Elements of Simulation Chapman and Hall
Ripley B D (1987) Stochastic Simulation Wiley

5 Arguments

1:   CL – CHARACTER(1)Input
On entry: indicates the type of call to G08EBF.
CL='S'
This is the one and only call to G08EBF (single call mode). All data are to be input at once. All test statistics are computed after the counting of pairs is complete.
CL='F'
This is the first call to the routine. All initializations are carried out and the counting of pairs begins. The final test statistics are not computed since further calls will be made to G08EBF.
CL='I'
This is an intermediate call during which the counts of pairs are updated. The final test statistics are not computed since further calls will be made to G08EBF.
CL='L'
This is the last call to G08EBF. The test statistics are computed after the final counting of runs is complete.
Constraint: CL='S', 'F', 'I' or 'L'.
2:   N – INTEGERInput
On entry: n, the number of observations.
Constraints:
  • if CL='S', N≥2;
  • otherwise N≥1.
3:   X N – REAL (KIND=nag_wp) arrayInput
On entry: the sequence of observations.
Constraint: 0.0≤X i≤1.0, for i=1,2,…,n.
4:   MSIZE – INTEGERInput
On entry: m, the size of the matrix of counts.
MSIZE must not be changed between calls to G08EBF.
Constraint: MSIZE≥2.
5:   LAG – INTEGERInput
On entry: l, the lag to be used in choosing pairs.
If LAG=1, then we consider the pairs X i,X i+1, for i=1,3,…,n-1, where n is the number of observations.
If LAG>1, then we consider the pairs X i,X i+l, for i=1,2,…,l,2 l+1,2 l+2,…,3 l,4 l+1,…,n-l, where n is the number of observations.
LAG must not be changed between calls to G08EBF.
Constraints:
  • LAG≥1;
  • if CL='S', LAG<N.
6:   NCOUNT LDCMSIZE – INTEGER arrayInput/Output
On entry: if CL='S' or 'F', NCOUNT need not be set.
If CL='I' or 'L', NCOUNT must contain the values returned by the previous call to G08EBF.
On exit: is an MSIZE by MSIZE matrix containing the counts of the number of pairs in each cell, c ij, for i=1,2,…,m and j=1,2,…,m.
7:   LDC – INTEGERInput
On entry: the first dimension of the array NCOUNT as declared in the (sub)program from which G08EBF is called.
Constraint: LDC≥MSIZE.
8:   EX – REAL (KIND=nag_wp)Output
On exit: if CL='S' or 'L' (i.e., if it is a final exit) then EX contains the expected number of counts in each cell, e.
Otherwise EX is not set.
9:   CHI – REAL (KIND=nag_wp)Output
On exit: if CL='S' or 'L' (i.e., if it is a final exit) then CHI contains the χ 2 test statistic, X 2, for testing the null hypothesis of randomness.
Otherwise CHI is not set.
10:   DF – REAL (KIND=nag_wp)Output
On exit: if CL='S' or 'L' (i.e., if it is a final exit) then DF contains the degrees of freedom for the χ 2 statistic.
Otherwise DF is not set.
11:   PROB – REAL (KIND=nag_wp)Output
On exit: if CL='S' or 'L' (i.e., if it is a final exit) then PROB contains the upper tail probability associated with the χ 2 test statistic, i.e., the significance level.
Otherwise PROB is not set.
12:   WRK 2×LAG – REAL (KIND=nag_wp) arrayCommunication Array
WRK is used to store information between successive calls to G08EBF and therefore must not be changed.
13:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, because for this routine the values of the output arguments may be useful even if IFAIL≠0 on exit, the recommended value is -1. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Note: G08EBF may return useful information for one or more of the following detected errors or warnings.
Errors or warnings detected by the routine:
IFAIL=1
On entry, CL=value.
Constraint: CL='S', 'F', 'I' or 'L'.
IFAIL=2
On entry, N=value.
Constraint: if CL='S', N≥2, otherwise N≥1.
IFAIL=3
On entry, MSIZE=value.
Constraint: MSIZE≥2
IFAIL=4
On entry, LAG=value and N=value.
Constraint: LAG>0 and if CL='S', LAG<N.
IFAIL=5
On entry, LDC=value and MSIZE=value.
Constraint: LDC≥MSIZE.
IFAIL=6
On entry, at least one element of X is out of range.
Constraint: 0≤X i≤1, for i=1,2,…,N.
IFAIL=7
No pairs were found. This will occur if the value of LAG is greater than or equal to the total number of observations.
IFAIL=8
MSIZE is too large relative to the number of pairs, therefore the expected value for at least one cell is less than or equal to 5.0.
This implies that the χ 2 distribution may not be a very good approximation to the distribution of test statistic.
MSIZE=value, number of pairs =value and expected value =value.
All statistics are returned and may still be of use.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

The computations are believed to be stable. The computation of PROB given the values of CHI and DF will obtain a relative accuracy of five significant figures for most cases.

8 Parallelism and Performance

G08EBF is not thread safe and should not be called from a multithreaded user program. Please see Section 3.12.1 in How to Use the NAG Library and its Documentation for more information on thread safety.
G08EBF is not threaded in any implementation.

9 Further Comments

If after forming the pairs in an initial or intermediate call to G08EBF there is an observation left over at the end of the sequence, this observation is used at the beginning of the new sequence provided by the following call to G08EBF. Clearly an observation left over from an only or final call to G08EBF is ignored.
The time taken by the routine increases with the number of observations n, and also depends to some extent on whether the call to G08EBF is an only, first, intermediate or last call.

10 Example

The following program performs the pairs test on 500 pseudorandom numbers. G08EBF is called 5 times with 100 observations on each call. LAG=1 is used and the pairs are tallied into a 5 by 5 matrix.

10.1 Program Text

Program Text (g08ebfe.f90)

10.2 Program Data

Program Data (g08ebfe.d)

10.3 Program Results

Program Results (g08ebfe.r)

G08 Chapter Contents
G08 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


G08ECF : NAG Library, Mark 26

G08 Chapter Contents
G08 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

G08ECF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

G08ECF performs the triplets test on a sequence of observations from the interval 0,1.

2 Specification

SUBROUTINE G08ECF ( CL, N, X, MSIZE, NCOUNT, LDC, EX, CHI, DF, PROB, IFAIL)
INTEGER | N, MSIZE, NCOUNT(LDC,LDC,MSIZE), LDC, IFAIL
REAL (KIND=nag_wp) | X(N), EX, CHI, DF, PROB
CHARACTER(1) | CL

3 Description

G08ECF computes the statistics for performing a triplets test which may be used to investigate deviations from randomness in a sequence, x=xi:i=1,2,…,n, of 0,1 observations.
An m by m matrix, C, of counts is formed as follows. The element cjkl of C is the number of triplets xi,x i+1,x i+2 for i=1,4,7,…,n-2, such that
j-1 m≤xi<jm
k- 1 m≤x i+ 1< km
l-1 m≤x i+2< lm.
Note that all triplets formed are non-overlapping and are thus independent under the assumption of randomness.
Under the assumption that the sequence is random, the expected number of triplets for each class (i.e., each element of the count matrix) is the same; that is, the triplets should be uniformly distributed over the unit cube 0,1 3. Thus the expected number of triplets for each class is just the total number of triplets, ∑j,k,l=1 m cjkl, divided by the number of classes, m 3.
The χ 2 test statistic used to test the hypothesis of randomness is defined as
X 2=∑j,k,l=1 m cjkl-e 2 e,
where e=∑j,k,l=1 m cjkl/m 3= expected number of triplets in each class.
The use of the χ 2-distribution as an approximation to the exact distribution of the test statistic, X 2, improves as the length of the sequence relative to m increases and hence the expected value, e, increases.
G08ECF may be used in two different modes:
(i) | a single call to G08ECF which computes all test statistics after counting the triplets;
(ii) | multiple calls to G08ECF with the final test statistics only being computed in the last call.
The second mode is necessary if all the data do not fit into the memory. See argument CL in Section 5 for details on how to invoke each mode.

4 References

Dagpunar J (1988) Principles of Random Variate Generation Oxford University Press
Knuth D E (1981) The Art of Computer Programming (Volume 2) (2nd Edition) Addison–Wesley
Morgan B J T (1984) Elements of Simulation Chapman and Hall
Ripley B D (1987) Stochastic Simulation Wiley

5 Arguments

1:   CL – CHARACTER(1)Input
On entry: indicates the type of call to G08ECF.
CL='S'
This is the one and only call to G08ECF (single call mode). All data are to be input at once. All test statistics are computed after counting of the triplets is complete.
CL='F'
This is the first call to the routine. All initializations are carried out and the counting of triplets begins. The final test statistics are not computed since further calls will be made to G08ECF.
CL='I'
This is an intermediate call during which counts of the triplets are updated. The final test statistics are not computed since further calls will be made to G08ECF.
CL='L'
This is the last call to G08ECF. The test statistics are computed after the final counting of the triplets is complete.
Constraint: CL='S', 'F', 'I' or 'L'.
2:   N – INTEGERInput
On entry: n, the number of observations.
Constraints:
  • if CL='S', N≥3;
  • otherwise N≥1.
3:   X N – REAL (KIND=nag_wp) arrayInput
On entry: the sequence of observations.
Constraint: 0.0≤X i≤1.0, for i=1,2,…,n.
4:   MSIZE – INTEGERInput
On entry: m, the size of the count matrix to be formed.
MSIZE must not be changed between calls to G08ECF.
Constraint: MSIZE≥2.
5:   NCOUNT LDCLDCMSIZE – INTEGER arrayInput/Output
On entry: if CL='S' or 'F', NCOUNT need not be set.
If CL='I' or 'L', NCOUNT must contain the values returned by the previous call to G08ECF.
On exit: is an MSIZE by MSIZE by MSIZE matrix containing the counts of the number of triplets, c jkl, for j=1,2,…,m, k=1,2,…,m and l=1,2,…,m.
6:   LDC – INTEGERInput
On entry: the first dimension of the array NCOUNT and the second dimension of the array NCOUNT as declared in the (sub)program from which G08ECF is called.
Constraint: LDC≥MSIZE.
7:   EX – REAL (KIND=nag_wp)Output
On exit: if CL='S' or 'L' (i.e., if it is a final exit) then EX contains the expected number of counts for each element of the count matrix.
Otherwise EX is not set.
8:   CHI – REAL (KIND=nag_wp)Output
On exit: if CL='S' or 'L' (i.e., if it is a final exit) then CHI contains the χ 2 test statistic, X 2, for testing the null hypothesis of randomness.
Otherwise CHI is not set.
9:   DF – REAL (KIND=nag_wp)Output
On exit: if CL='S' or 'L' (i.e., if it is a final exit) then DF contains the degrees of freedom for the χ 2 statistic.
Otherwise DF is not set.
10:   PROB – REAL (KIND=nag_wp)Output
On exit: if CL='S' or 'L' (i.e., if it is a final exit) then PROB contains the upper tail probability associated with the χ 2 test statistic, i.e., the significance level.
Otherwise PROB is not set.
11:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, because for this routine the values of the output arguments may be useful even if IFAIL≠0 on exit, the recommended value is -1. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Note: G08ECF may return useful information for one or more of the following detected errors or warnings.
Errors or warnings detected by the routine:
IFAIL=1
On entry, CL=value.
Constraint: CL='S', 'F', 'I' or 'L'.
IFAIL=2
On entry, N=value.
Constraint: if CL='S', N≥3, otherwise N≥1.
IFAIL=3
On entry, MSIZE=value.
Constraint: MSIZE≥2.
IFAIL=4
On entry, LDC=value and MSIZE=value.
Constraint: LDC≥MSIZE.
IFAIL=5
On entry, at least one element of X is out of range.
Constraint: 0≤X i≤1, for i=1,2,…,N.
IFAIL=6
No triplets were found because less than 3 observations were provided in total.
IFAIL=7
MSIZE is too large relative to the number of triplets, therefore the expected value for at least one cell is less than or equal to 5.0.
This implies that the χ 2 distribution may not be a very good approximation to the distribution of the test statistic.
MSIZE=value , number of triplets =value and expected value=value.
All statistics are returned and may still be of use.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

The computations are believed to be stable. The computations of PROB given the values of CHI and DF will obtain a relative accuracy of five significant figures for most cases.

8 Parallelism and Performance

G08ECF is not thread safe and should not be called from a multithreaded user program. Please see Section 3.12.1 in How to Use the NAG Library and its Documentation for more information on thread safety.
G08ECF is not threaded in any implementation.

9 Further Comments

If the call to G08ECF is an initial call or intermediate call with further calls to follow then any unused observations are saved for use at the beginning of the new sequence provided in the following call. Clearly any observations left over from an only or final call to G08ECF are ignored.
The time taken by the routine increases with the number of observations n, and also depends to some extent whether the call to G08ECF is an only, first, intermediate or last call.

10 Example

The following program performs the triplets test on 500 pseudorandom numbers. G08ECF is called 5 times with 100 observations on each call. The triplets are tallied into a 2 by 2 by 2 matrix.

10.1 Program Text

Program Text (g08ecfe.f90)

10.2 Program Data

Program Data (g08ecfe.d)

10.3 Program Results

Program Results (g08ecfe.r)

G08 Chapter Contents
G08 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


G08EDF : NAG Library, Mark 26

G08 Chapter Contents
G08 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

G08EDF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

G08EDF performs a gaps test on a sequence of observations.

2 Specification

SUBROUTINE G08EDF ( CL, N, X, M, MAXG, RLO, RUP, TOTLEN, NGAPS, NCOUNT, EX, CHI, DF, PROB, IFAIL)
INTEGER | N, M, MAXG, NGAPS, NCOUNT(MAXG), IFAIL
REAL (KIND=nag_wp) | X(N), RLO, RUP, TOTLEN, EX(MAXG), CHI, DF, PROB
CHARACTER(1) | CL

3 Description

Gaps tests are used to test for cyclical trend in a sequence of observations. G08EDF computes certain statistics for the gaps test.
G08EDF may be used in two different modes:
(i) | a single call to G08EDF which computes all test statistics after counting the gaps;
(ii) | multiple calls to G08EDF with the final test statistics only being computed in the last call.
The second mode is necessary if all the data does not fit into the memory. See argument CL in Section 5 for details on how to invoke each mode.
The term gap is used to describe the distance between two numbers in the sequence that lie in the interval rl,ru. That is, a gap ends at xj if rl≤xj≤ru. The next gap then begins at x j+1. The interval rl,ru should lie within the region of all possible numbers. For example if the test is carried out on a sequence of 0,1 random numbers then the interval rl,ru must be contained in the whole interval 0,1. Let t len be the length of the interval which specifies all possible numbers.
G08EDF counts the number of gaps of different lengths. Let ci denote the number of gaps of length i, for i=1,2,…,k-1. The number of gaps of length k or greater is then denoted by ck. An unfinished gap at the end of a sequence is not counted unless the sequence is part of an initial or intermediate call to G08EDF (i.e., unless there is another call to G08EDF to follow) in which case the unfinished gap is used. The following is a trivial example.
Suppose we called G08EDF twice (i.e., with CL='F' and then with CL='L') with the following two sequences and with RLO=0.30 and RUP=0.60:
  • (0.20 0.40 0.45 0.40 0.15 0.75 0.95 0.23) and
  • (0.27 0.40 0.25 0.10 0.34 0.39 0.61 0.12).
Then after the second call G08EDF would have counted the gaps of the following lengths:
  • 2, 1, 1, 6, 3 and 1.
When the counting of gaps is complete G08EDF computes the expected values of the counts. An approximate χ 2 statistic with k degrees of freedom is computed where
X 2=∑i=1 k ci-ei 2 ei,
where
  • ei=ngaps×p×1-p i-1, if i<k;
  • ei=ngaps×1-p i-1, if i=k;
  • ngaps= the number of gaps found and
  • p=ru-rl/t len.
The use of the χ 2-distribution as an approximation to the exact distribution of the test statistic improves as the expected values increase.
You may specify the total number of gaps to be found. If the specified number of gaps is found before the end of a sequence G08EDF will exit before counting any further gaps.

4 References

Dagpunar J (1988) Principles of Random Variate Generation Oxford University Press
Knuth D E (1981) The Art of Computer Programming (Volume 2) (2nd Edition) Addison–Wesley
Morgan B J T (1984) Elements of Simulation Chapman and Hall
Ripley B D (1987) Stochastic Simulation Wiley

5 Arguments

1:   CL – CHARACTER(1)Input
On entry: indicates the type of call to G08EDF.
CL='S'
This is the one and only call to G08EDF (single call mode). All data are to be input at once. All test statistics are computed after the counting of gaps is complete.
CL='F'
This is the first call to the routine. All initializations are carried out before the counting of gaps begins. The final test statistics are not computed since further calls will be made to G08EDF.
CL='I'
This is an intermediate call during which the counts of gaps are updated. The final test statistics are not computed since further calls will be made to G08EDF.
CL='L'
This is the last call to G08EDF. The test statistics are computed after the final counting of gaps is complete.
Constraint: CL='S', 'F', 'I' or 'L'.
2:   N – INTEGERInput
On entry: n, the length of the current sequence of observations.
Constraint: N≥1.
3:   X N – REAL (KIND=nag_wp) arrayInput
On entry: the sequence of observations.
4:   M – INTEGERInput
On entry: the maximum number of gaps to be sought. If M≤0 then there is no limit placed on the number of gaps that are found.
M should not be changed between calls to G08EDF.
Constraint: if CL='S', M≤N.
5:   MAXG – INTEGERInput
On entry: k, the length of the longest gap for which tabulation is desired.
MAXG must not be changed between calls to G08EDF.
Constraints:
  • MAXG>1;
  • if CL='S', MAXG≤N.
6:   RLO – REAL (KIND=nag_wp)Input
On entry: the lower limit of the interval to be used to define the gaps, rl.
RLO must not be changed between calls to G08EDF.
7:   RUP – REAL (KIND=nag_wp)Input
On entry: the upper limit of the interval to be used to define the gaps, ru.
RUP must not be changed between calls to G08EDF.
Constraint: RUP>RLO.
8:   TOTLEN – REAL (KIND=nag_wp)Input
On entry: the total length of the interval which contains all possible numbers that may arise in the sequence.
Constraint: TOTLEN>0.0 and RUP-RLO<TOTLEN.
9:   NGAPS – INTEGERInput/Output
On entry: if CL='S' or 'F', NGAPS need not be set.
If CL='I' or 'L', NGAPS must contain the value returned by the previous call to G08EDF.
On exit: the number of gaps actually found, ngaps.
10:   NCOUNT MAXG – INTEGER arrayInput/Output
On entry: if CL='S' or 'F', NCOUNT need not be set.
If CL='I' or 'L', NCOUNT must contain the values returned by the previous call to G08EDF.
On exit: the counts of gaps of the different lengths, ci, for i=1,2,…,k.
11:   EX MAXG – REAL (KIND=nag_wp) arrayOutput
On exit: if CL='S' or 'L' (i.e., if it is a final exit) then EX contains the expected values of the counts.
Otherwise the elements of EX are not set.
12:   CHI – REAL (KIND=nag_wp)Output
On exit: if CL='S' or 'L' (i.e., if it is a final exit) then CHI contains the χ 2 test statistic, X 2, for testing the null hypothesis of randomness.
Otherwise CHI is not set.
13:   DF – REAL (KIND=nag_wp)Output
On exit: if CL='S' or 'L' (i.e., if it is a final exit) then DF contains the degrees of freedom for the χ 2 statistic.
Otherwise DF is not set.
14:   PROB – REAL (KIND=nag_wp)Output
On exit: if CL='S' or 'L' (i.e., if it is a final exit) then PROB contains the upper tail probability associated with the χ 2 test statistic, i.e., the significance level.
Otherwise PROB is not set.
15:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, because for this routine the values of the output arguments may be useful even if IFAIL≠0 on exit, the recommended value is -1. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Note: G08EDF may return useful information for one or more of the following detected errors or warnings.
Errors or warnings detected by the routine:
IFAIL=1
On entry, CL=value.
Constraint: CL='S', 'F', 'I' or 'L'.
IFAIL=2
On entry, N=value.
Constraint: N≥1.
IFAIL=3
On entry, M=value and N=value.
Constraint: if CL='S', M≤N.
IFAIL=4
On entry, MAXG=value.
Constraint: MAXG>1.
On entry, MAXG=value and N=value.
Constraint: if CL='S', MAXG≤N.
IFAIL=5
On entry, RLO=value, RUP=value and TOTLEN=value.
Constraint: RUP-RLO<TOTLEN.
On entry, RLO=value and RUP=value.
Constraint: RUP>RLO.
On entry, TOTLEN=value.
Constraint: TOTLEN>0.0.
IFAIL=6
No gaps were found. Try using a longer sequence, or increase the size of the interval RUP-RLO.
IFAIL=7
The expected frequency in class i=value is zero. The value of RUP-RLO/TOTLEN may be too close to 0.0​ or ​1.0. or MAXG is too large relative to the number of gaps found.
IFAIL=8
The number of gaps requested were not found, only value out of the requested value where found.
All statistics are returned and may still be of use.
IFAIL=9
The expected frequency of at least one class is less than one.
This implies that the χ 2 may not be a very good approximation to the distribution of the test statistics.
All statistics are returned and may still be of use.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

The computations are believed to be stable. The computation of PROB given the values of CHI and DF will obtain a relative accuracy of five significant places for most cases.

8 Parallelism and Performance

G08EDF is not thread safe and should not be called from a multithreaded user program. Please see Section 3.12.1 in How to Use the NAG Library and its Documentation for more information on thread safety.
G08EDF is not threaded in any implementation.

9 Further Comments

The time taken by G08EDF increases with the number of observations n, and depends to some extent whether the call is an only, first, intermediate or last call.

10 Example

The following program performs the gaps test on 500 pseudorandom numbers. G08EDF is called 5 times with 100 observations on each call. All gaps of length 10 or more are counted together.

10.1 Program Text

Program Text (g08edfe.f90)

10.2 Program Data

Program Data (g08edfe.d)

10.3 Program Results

Program Results (g08edfe.r)

G08 Chapter Contents
G08 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


G08 Chapter Introduction : NAG Library, Mark 26

G08 Chapter Contents
NAG Library Manual

NAG Library Chapter Introduction

G08 – Nonparametric Statistics

▸▿ Contents

1 Scope of the Chapter
▸▿ 2 Background to the Problems
2.1 Parametric and Nonparametric Hypothesis Testing
2.2 Types of Nonparametric Test
▸▿ 2.3 Principles of Nonparametric Tests
2.3.1 Location tests
2.3.2 Dispersion tests
2.3.3 Tests of fit
2.3.4 Association and correlation tests
2.3.5 Tests of randomness
2.4 Regression using ranks
▸▿ 3 Recommendations on Choice and Use of Available Routines
▸▿ 3.1 G08A – Location Tests
3.1.1 One-sample or matched-pairs case
3.1.2 Two independent samples
3.1.3 More than two related samples
3.1.4 More than two independent samples
3.2 G08B – Dispersion Tests
3.3 G08C – Tests of Fit
3.4 G08D – Association and Correlation Tests
3.5 G08E – Tests of Randomness
3.6 G08R – Regression Using Ranks
3.7 Related Routines
4 Functionality Index
5 Auxiliary Routines Associated with Library Routine Arguments
6 Routines Withdrawn or Scheduled for Withdrawal
7 References

1 Scope of the Chapter

The routines in this chapter perform nonparametric statistical tests which are based on distribution-free methods of analysis. For convenience, the chapter contents are divided into five types of test: tests of location, tests of dispersion, tests of distribution, tests of association and correlation, and tests of randomness. There are also routines to fit linear regression models using the ranks of the observations.
The emphasis in this chapter is on testing; if you wish to compute nonparametric correlations you are referred to Chapter G02, which contains several routines for that purpose.
There are a large number of nonparametric tests available. A selection of some of the more commonly used tests are included in this chapter.

2 Background to the Problems

2.1 Parametric and Nonparametric Hypothesis Testing

Classical techniques of statistical inference often make numerous or stringent assumptions about the nature of the population or populations from which the observations have been drawn. For instance, a testing procedure might assume that the set of data was obtained from Normally distributed populations. It might be further assumed that the populations involved have equal variances, or that there is a known relationship between the variances. In the Normal case, the test statistic derived would usually be a function of the sample means and variances, since a Normal distribution is completely characterised by its mean and variance. Alternatively, it might be assumed that the set of data was obtained from other distributions of known form, such as the gamma or the exponential. Again, a testing procedure would be devised based upon the parameters characterising such a distribution.
The type of hypothesis testing just described is usually termed parametric inference. Distributional assumptions are made which imply that the parameters of the chosen distribution, as estimated from the data, are sufficient to characterise the difference in distribution between the populations.
However, problems arise with parametric methods of inference when these assumptions cannot be made, either because they are contrary to the known nature of the mechanism generating a population, or because the data obviously do not satisfy the assumptions. Some parametric procedures become unreliable under relatively minor departures from the hypothesised distributional form. In the Normal case for example, tests on variances are extremely sensitive to departures from Normality in the underlying distribution.
There are also common situations, particularly in the behavioural sciences, where much more basic assumptions than that of Normality cannot be made. Data values are not always measured on continuous or even numerical scales. They may be simply categorical in nature, relating to such quantities as voting intentions or food preferences.
Techniques of inference are therefore required which do not involve making detailed assumptions about the underlying mechanism generating the observations. The routines in this chapter perform such distribution-free tests, evaluating from a set of data the value of a test statistic, together with an estimate of its significance.
For a comparison of some distribution-based and distribution-free tests, the interested reader is referred to Chapter 31 of Kendall and Stuart (1973). For a briefer and less mathematical account, see Conover (1980) or Siegel (1956).

2.2 Types of Nonparametric Test

This introduction is concerned with explaining the basic concepts of hypothesis testing, and some familiarity with the subject is assumed. Chapter 22 of Kendall and Stuart (1973) contains a detailed account, and the outline given in Conover (1980) or Siegel (1956) should be sufficient to understand this section.
Nonparametric tests may be grouped into five categories:
1. | Tests of location
2. | Tests of dispersion
3. | Distribution-free tests of fit
4. | Tests of association or correlation
5. | Tests of randomness
Tests can also be categorised by the design that they can be applied to:
1. | One sample
2. | Two related (paired) samples
3. | Two independent samples
4. | k>2 related (matched) samples
5. | k>2 independent samples
A third classification of a test relates to the type of data to which it may be applied. Variables are recorded on four scales of measurement: nominal (categorical), ordinal, interval, and ratio.
The nominal scale is used only to categorise data; for each category a name, perhaps numeric, is assigned so that two different categories will be identified by distinct names. The ordinal scale, as well as categorising the observations, orders the categories. Each is assigned a distinct identifying symbol, in such a way that the order of the symbols corresponds to the order of the categories. (The most common system for ordinal variables is to assign numerical identifiers to the categories, though if they have previously been assigned alphabetic characters, these may be transformed to a numerical system by any convenient method which preserves the ordering of the categories.) The interval scale not only categorises and orders the observations, but also quantifies the comparison between categories; this necessitates a common unit of measurement and an arbitrary zero-point. Finally, the ratio scale is similar to the interval scale, except that it has an absolute (as opposed to arbitrary) zero-point.
It is apparent that there are many possible combinations of these three characteristics of a problem, and many nonparametric tests have been derived to meet the different experimental situations. However, it is not usually a difficult matter to choose an appropriate test given the nature of the data and the type of test which one wishes to perform.

2.3 Principles of Nonparametric Tests

In this section, each type of test is considered in turn, and remarks are made on the design principles on which each is based.

2.3.1 Location tests

These tests are primarily concerned with inferences about differences in the location of the population distributions. In some cases, however, the tests are only concerned with inferences about the population distributions unless added assumptions are made which allow the hypotheses to be stated in terms of the location parameters.
For most of these tests, data must be measured numerically on at least an ordinal scale, in order that a measure of location may be devised. Ordinal measurement implies that pairs of values may be compared and numerically ordered. A vector of n values may therefore be ranked from smallest to largest using the ordering operation. The resultant ranks contain all the information in the original data, but have the advantage that tests may be derived easily based on them, and no testing bias is introduced by the use of ordinal values as though they were measured on an interval scale. Note that the requirement of the measurement scale being ordinal does not imply that all tests of this type involve the actual ranking of the original data.
For the one-sample or matched pairs case, test statistics may be derived based on the number of observations (or differences) lying either side of zero (or some other fixed value), as in the sign test, for example. Under the hypothesis that the median of the single population is zero or the difference in the medians of the paired populations is zero the number of positive and negative values should be similar. The Wilcoxon signed rank test goes further than the sign test by taking into account the magnitude of the single sample values or of the differences.
For the two-sample case, if median equality is hypothesised, the distribution of the ranks of each sample in the total pooled sample should be similar. Test statistics, such as the Mann–Whitney U statistic, which are based on the ranks of each sample and summarise the differences in rank sums for each sample, may be computed. These statistics are referred to their expected distributions under the null hypothesis. The above hypothesis can also be tested using the median test. Its test statistic is based on the number of values in each sample which are greater than or less than the pooled median of the two samples, rather than the ranks of each sample.
If median equality is hypothesised for several samples, the distribution ranks of the members of each sample in the total pooled sample should be ‘homogeneous’. Test statistics can be derived which summarise the differences in rank sums for the various samples, and again referred to their expected distributions under the null hypothesis.

2.3.2 Dispersion tests

These provide a distribution-free alternative to such tests as the F-(variance-ratio) test for variance equality, which is very sensitive to non-Normality in the generating distribution.
The dispersions of two or more samples may be compared by pooling the samples and observing the distribution of ranks in the ranked pooled sample. Equal dispersions should be recognizable by there being a wide distribution of the extreme ranks between the members of different samples. Statistics are evaluated which quantify the dispersion of ranks between samples, and their significance may be found by evaluating their permutation distributions assuming that no dispersion difference exists.

2.3.3 Tests of fit

In the one-sample case, these are tests which investigate whether or not a sample of observations can be considered to follow a specified distribution. In the two-sample case, a test of fit investigates whether the two samples can be considered to have arisen from a common probability distribution.
For the one-sample problem, the null hypothesis may specify only the distributional form, for example Normal μ,σ 2, or it may incorporate actual parameter values, for example Poisson with mean 10.
Some tests of this type proceed by forming the sample cumulative distribution function of the observations and computing a statistic whose value measures the departure of the sample cumulative distribution function from that of the null distribution. In the two-sample case, a statistic is computed which provides a measure of the difference between the sample cumulative distribution function of each sample. These tests are known as one- or two-sample Kolmogorov–Smirnov tests.
The significance for these test statistics can be computed directly for moderate sample sizes but for larger sample sizes asymptotic results are often used.
Another goodness-of-fit test is the χ 2 test. For this test, the data is first grouped into intervals and then the difference between the observed number of observations in each interval and the number expected, if the null hypothesis is true, is computed. A statistic based on these differences has asymptotically a χ 2-distribution.

2.3.4 Association and correlation tests

These are distribution-free analogues of tests based on such statistics as Pearson product-moment correlation coefficients.
Essentially they are based on rankings rather than the observed data values, and involve summing some function of the rank differences between the samples to obtain an overall measure of the concordance of ranks. This measure can be standardized by dividing by its theoretical maximum value for the given sample size and number of samples.
Significance levels may be calculated for quite small sample sizes by using an approximation to a χ 2-distribution.

2.3.5 Tests of randomness

These tests are designed to investigate sequences of observations and attempt to identify any deviations from randomness. There are clearly many ways in which a sequence may deviate from randomness. The tests provided here primarily detect some form of dependency between the observations in the sequence.
The most common application of this type of tests is in the area of random number generation. The tests are used as empirical tests on a sample of output from a generator to establish local randomness. Theoretical tests are necessary and useful for testing global randomness. Some of the more common empirical tests are discussed below.
A runs-up or runs-down test investigates whether runs of different lengths are occurring with greater or lesser frequency than would be expected under the null hypothesis of randomness. A run up is defined as a sequence of observations in which each observation is larger than the previous observation. The run up ends when an observation is smaller than the previous observation. A test statistic, modified to take into account the dependency between successive run lengths, is computed. The test statistic has an asymptotic χ 2-distribution.
The pairs test investigates the condition that, under the null hypothesis of randomness, the non-overlapping 2-tuples (pairs) of a sequence of observations from the interval 0,1 should be uniformly distributed over the unit square (0,1 2). The triplets test follows the same idea but considers 3-tuples and checks for uniformity over the unit cube (0,1 3). In each test, a test statistic, based on differences between the observed and expected distribution of the 2- or 3-tuples, is computed which has an asymptotic χ 2-distribution.
The gaps test considers the ‘gaps’ between successive occurrences of observations in the sequence lying in a specified range. Under the null hypothesis of randomness, the gap length should follow a geometric distribution with a parameter based on the length of the specified range, relative to the overall length of the interval containing all possible observations. The expected number of ‘gaps’, of a certain length, under the null hypothesis may thus be computed together with a test statistic based on the differences between the observed and expected numbers of ‘gaps’ of different length. Again the test statistic has an asymptotic χ 2-distribution.
Other empirical tests such as the χ 2 goodness-of-fit test and the one-sample Kolmogorov–Smirnov test may be used to investigate a sequence for non-uniformity.

2.4 Regression using ranks

If you wish to fit a regression model but is unsure about what transformation to take for the observed response to obtain a linear model, then one strategy is to replace response observations by their ranks. Estimates for regression parameters can be found by maximizing a likelihood function based on the ranks and the proposed regression model. The present routines give approximate estimates which are adequate when the signal-to-noise ratio is small, which is often the case with data from the medical and social sciences. Approximate standard errors of estimated regression coefficients are found. Also χ 2 statistics can be used to test the null hypothesis of no regression effect.

3 Recommendations on Choice and Use of Available Routines

The routines are grouped into six categories. The fourth character of the routine name is used to denote this categorisation.
Sub-chapter | Type of test
G08A | Location
G08B | Dispersion
G08C | Fit
G08D | Correlation and Association
G08E | Randomness
G08R | Regression using Ranks

3.1 G08A – Location Tests

3.1.1 One-sample or matched-pairs case

Note that a random sample of matched pairs, (xi,yi), may be reduced to a single sample by considering the differences, di=xi-yi say, of each pair. The matched pair may be thought of as a single observation on a bivariate random variable.
G08AAF performs the sign test on two paired samples. Each pair is classified as a + or - depending on the sign of the difference between the two data values within the pair. Under the assumptions that the di are mutually independent and that the observations are measured on at least an ordinal scale, the sign test tests the hypothesis that for any pair sampled from the population distribution, Probability+=Probability-. The hypothesis may be stated in terms of the equality of the location parameters but the test is no longer regarded as unbiased and consistent unless further assumptions are made. If you wish to test the hypothesis that the location parameters differ by a fixed amount then that amount must be added or subtracted from one of the samples as required before calling G08AAF.
G08AGF performs the one-sample Wilcoxon signed-rank test. The test may be used to test if the median of the population from which the random sample was taken is equal to some specified value (commonly used to test if the median is zero). In this test not only is the sign of the difference between the data values and the hypothesised median value important but also the magnitude of this difference. Thus, where the magnitude of the differences (or the data values themselves if the hypothesised median value is zero) is important this test is preferred to the sign test because it is more powerful. The test may easily be used to test whether the medians of two related populations are equal by taking the differences between the paired sample values and then testing the hypothesis that the median of the differences is zero, using the single sample of differences. The significance of the test statistic may be computed exactly for a moderate sample size but for a larger sample a Normal approximation is used. The exact method allows for ties in the differences.

3.1.2 Two independent samples

G08ACF performs the median test and G08AHF performs the Mann–Whitney U test.
For both tests the two samples are assumed to be random samples from their respective populations and mutually independent. The measurement scale must be at least ordinal.
Note that, although the median test may be generalized to more than two samples, G08ACF only deals with the two-sample case. For the median test, each observation is classified as being above or below the pooled median of the two samples. It may be used to test the hypothesis that the two population medians are equal; under the assumption that if the two population medians are equal then the probability of an observation exceeding the pooled median is the same for both populations.
The Mann–Whitney U test involves the ranking of the pooled sample. The Mann–Whitney test thus attaches importance to the position of each observation relative to the others and not just its position relative to the median of the pooled sample as in the median test. Thus when the magnitude of the differences between the observations is meaningful the Mann–Whitney U test is preferred as it is more powerful than the median test. The test tests whether the two population distributions are the same or not. If it is assumed that any difference between the two population distributions is a difference in the location then the test is testing whether the population means are the same or not.
In G08AHF, the significance of the U test statistic is computed using a Normal approximation. If the exact significance is desired then either G08AJF or G08AKF must be used. G08AJF computes the exact significance of the U test statistic for the case where there are no ties in the pooled sample. It requires only the value of the statistic and the two sample sizes. G08AKF computes the exact significance of the U test statistic for the case where there are ties in the pooled sample. It requires the value of the statistic and the two sample sizes and the ranks of the observations of the two samples as provided by G08AHF. G08AHF returns an indicator to inform you whether or not ties were found in the pooled sample.

3.1.3 More than two related samples

G08AEF performs the Friedman two-way analysis of variance. This test may in some ways be regarded as an extension of the sign test to the case of k (k>2) related samples. The data is in the form of a number of multivariate observations which are assumed to be mutually independent. This test also assumes that the measurement within each observation across the k variates is at least ordinal so that the observation for each variate may be ranked according to some criteria.
For data which may be defined as either a zero or one, that is binary response data, G08ALF performs Cochran's Q-test to examine differences between the treatments within blocks.

3.1.4 More than two independent samples

G08AFF performs the Kruskal–Wallis one-way analysis of variance. The test assumes that each sample is a random sample from its respective distributions and in addition that there is both independence within the samples and mutual independence among the various samples. The test requires that the measurement scale is at least ordinal so that the pooled sample may be ranked.

3.2 G08B – Dispersion Tests

G08BAF performs either Mood's or David's test for dispersion differences, or both, for two independent samples of possibly unequal size.
For both tests the null hypothesis is that the two samples have equal dispersions, the routine returning a probability value which may be used to perform the test against a one-sided or two-sided alternative, in a way described in the routine document.

3.3 G08C – Tests of Fit

G08CBF and G08CCF both perform the one-sample Kolmogorov–Smirnov distribution test. This test is used to test the null hypothesis that the random sample arises from a specified null distribution against one of three possible alternatives.
With G08CBF you may choose a null distribution from one of the following: the uniform, Normal, gamma, beta, binomial, exponential, and Poisson. The parameter values may either be specified by you or estimated from the data by the routine. With G08CCF you must provide a function which will compute the value of the cumulative distribution function at any specified point for the null distribution. The alternative hypotheses available correspond to one- and two-sided tests. The distribution of the test statistic is computed using an exact method for a moderate sample size. For a larger sample size an asymptotic result is used.
G08CDF performs the two-sample Kolmogorov–Smirnov test which tests the null hypothesis that the two samples may be considered to have arisen from the same population distribution against one of three possible alternative hypotheses, again corresponding to one-sided and two-sided tests. The distribution of the test statistic is computed using an exact method for moderate sample sizes, but for larger samples approximations based on asymptotic results are used.
Note that G01EYF and G01EZF are available for computing the distributions of the one-sample and two-sample Kolmogorov–Smirnov statistics respectively.
G08CGF performs the χ 2 goodness-of-fit test on a single sample which again tests the null hypothesis that the sample arises from a specified null distribution. You may choose a null distribution from one of the following: the Normal, uniform, exponential, χ 2, and gamma; or may define the distribution by specifying the probability that an observation lies in a certain interval for a range of intervals covering the support of the null distribution. The significance of this test is computed using the χ 2-distribution as an approximation to the distribution of the test statistic.
Several routines are available to perform Anderson–Darling goodness-of-fit tests:
  • G08CJF for the case of uniformly distributed data;
  • G08CKF for a full-unspecified Normal distribution;
  • G08CLF for an unspecified exponential distribution.
Note that data from a fully-specified distribution can be transformed to standard uniform by applying its cumulative distribution function. In all other cases use G08CHF to calculate the Anderson–Darling statistic, A 2, and simulate its probability.
Tests of Normality may also be carried out using routines in Chapter G01.

3.4 G08D – Association and Correlation Tests

G08DAF computes Kendall's coefficient of concordance on k independent ranks of n objects. An example of its application would be to compare for consistency the results of a group of IQ tests performed on the same set of people. Allowance is made for tied rankings, and the approximate significance of the computed coefficient is found.

3.5 G08E – Tests of Randomness

G08EAF performs the runs-up test on a sequence of observations. The runs-down test may be performed by multiplying each observation by -1 before calling the routine. All runs whose length is greater than or equal to a certain chosen length will be treated as a single group.
G08EBF performs the pairs (serial) test on a sequence of observations from the interval 0,1. The number of equal sub-intervals into which the interval 0,1 is to be divided must be specified.
G08ECF performs the triplets test on a sequence of observations from the interval 0,1. The number of equal sub-intervals into which the interval 0,1 is to be divided must be specified.
G08EDF performs the gaps test on a sequence of observations. The total length of the interval containing all possible values the observations could take must be specified together with the interval being used to define the ‘gaps’. All ‘gaps’ whose length is greater than or equal to a certain chosen length will be treated as a single group.

3.6 G08R – Regression Using Ranks

G08RAF fits a multiple linear regression model in which the observations on the response variable are replaced by their ranks.
G08RBF performs the same function but takes into account observations which may be right-censored.

3.7 Related Routines

Tests of location and distribution may be based on scores which are estimates of the expected values of the order statistics. G01DHF may be used to compute Normal scores, an approximation to the Normal scores (Blom, Tukey or van der Waerden scores) or Savage (exponential) scores. For more accurate Normal scores G01DAF may be used. Other routines in sub-chapter G01D may be used to test for Normality.

4 Functionality Index

Regression using ranks,
right-censored data G08RBF
uncensored data G08RAF
Tests of association and correlation,
Kendall's coefficient of concordance G08DAF
Tests of dispersion,
Mood's and David's tests on two samples of unequal size G08BAF
Tests of fit,
A2 and its probability of for a fully-unspecified Normal distribution G08CKF
A2 and its probability of for an unspecified exponential distribution G08CLF
A2 and its probability of for uniformly distributed data G08CJF
Anderson–Darling test statistic A2 G08CHF
Kolmogorov–Smirnov one-sample distribution test,
for a user-supplied distribution G08CCF
for standard distributions G08CBF
Kolmogorov–Smirnov two-sample distribution test G08CDF
χ2 goodness-of-fit test G08CGF
Tests of location,
Cochran Q test on cross-classified binary data G08ALF
exact probabilities for Mann–Whitney U statistic,
no ties in pooled sample G08AJF
ties in pooled sample G08AKF
Friedman two-way analysis of variance on k matched samples G08AEF
Kruskal–Wallis one-way analysis of variance on k samples of unequal size G08AFF
Mann–Whitney U test on two samples of possibly unequal size G08AHF
Median test on two samples of unequal size G08ACF
sign test on two paired samples G08AAF
Wilcoxon one sample signed rank test G08AGF
Tests of randomness,
Gaps test G08EDF
pairs (serial) test G08EBF
runs up or runs down test G08EAF
triplets test G08ECF

5 Auxiliary Routines Associated with Library Routine Arguments

None.

6 Routines Withdrawn or Scheduled for Withdrawal

None.

7 References

Conover W J (1980) Practical Nonparametric Statistics Wiley
Kendall M G and Stuart A (1973) The Advanced Theory of Statistics (Volume 2) (3rd Edition) Griffin
Siegel S (1956) Non-parametric Statistics for the Behavioral Sciences McGraw–Hill
G08 Chapter Contents
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


G08RAF : NAG Library, Mark 26

G08 Chapter Contents
G08 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

G08RAF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

G08RAF calculates the parameter estimates, score statistics and their variance-covariance matrices for the linear model using a likelihood based on the ranks of the observations.

2 Specification

SUBROUTINE G08RAF ( NS, NV, NSUM, Y, IP, X, LDX, IDIST, NMAX, TOL, PRVR, LDPRVR, IRANK, ZIN, ETA, VAPVEC, PAREST, WORK, LWORK, IWA, IFAIL)
INTEGER | NS, NV(NS), NSUM, IP, LDX, IDIST, NMAX, LDPRVR, IRANK(NMAX), LWORK, IWA(NMAX), IFAIL
REAL (KIND=nag_wp) | Y(NSUM), X(LDX,IP), TOL, PRVR(LDPRVR,IP), ZIN(NMAX), ETA(NMAX), VAPVEC(NMAX*(NMAX+1)/2), PAREST(4*IP+1), WORK(LWORK)

3 Description

Analysis of data can be made by replacing observations by their ranks. The analysis produces inference for regression arguments arising from the following model.
For random variables Y 1,Y 2,…,Yn we assume that, after an arbitrary monotone increasing differentiable transformation, h., the model
h Yi= xiT β+εi (1)
holds, where xi is a known vector of explanatory variables and β is a vector of p unknown regression coefficients. The εi are random variables assumed to be independent and identically distributed with a completely known distribution which can be one of the following: Normal, logistic, extreme value or double-exponential. In Pettitt (1982) an estimate for β is proposed as β^=M XT a with estimated variance-covariance matrix M. The statistics a and M depend on the ranks ri of the observations Yi and the density chosen for εi.
The matrix X is the n by p matrix of explanatory variables. It is assumed that X is of rank p and that a column or a linear combination of columns of X is not equal to the column vector of 1 or a multiple of it. This means that a constant term cannot be included in the model (1). The statistics a and M are found as follows. Let εi have pdf f ε and let g=-f′/f. Let W 1,W 2,…,Wn be order statistics for a random sample of size n with the density f.. Define Zi=g Wi, then ai=E Z ri. To define M we need M-1=XT B-A X, where B is an n by n diagonal matrix with B ii=E g′W ri and A is a symmetric matrix with A ij=cov Z ri,Z rj. In the case of the Normal distribution, the Z 1<⋯<Zn are standard Normal order statistics and E g′Wi=1, for i=1,2,…,n.
The analysis can also deal with ties in the data. Two observations are adjudged to be tied if Yi-Yj<TOL, where TOL is a user-supplied tolerance level.
Various statistics can be found from the analysis:
(a) | The score statistic XT a. This statistic is used to test the hypothesis H 0:β=0, see (e).
(b) | The estimated variance-covariance matrix XT B-A X of the score statistic in (a).
(c) | The estimate β^=M XT a.
(d) | The estimated variance-covariance matrix M=XT B-A X -1 of the estimate β^.
(e) | The χ 2 statistic Q=β^TM-1 β^=aT X XT B-A X -1XT a used to test H 0:β=0. Under H 0, Q has an approximate χ 2-distribution with p degrees of freedom.
(f) | The standard errors M ii 1/2 of the estimates given in (c).
(g) | Approximate z-statistics, i.e., Zi=β^i/se β^i for testing H 0:βi=0. For i=1,2,…,n, Zi has an approximate N 0,1 distribution.
In many situations, more than one sample of observations will be available. In this case we assume the model
hk Yk= XkT β+ek,  k=1,2,…,NS,
where NS is the number of samples. In an obvious manner, Yk and Xk are the vector of observations and the design matrix for the kth sample respectively. Note that the arbitrary transformation hk can be assumed different for each sample since observations are ranked within the sample.
The earlier analysis can be extended to give a combined estimate of β as β^=Dd, where
D-1=∑k=1 NS XkT Bk-Ak Xk
and
d=∑k= 1 NS XkT ak ,
with ak, Bk and Ak defined as a, B and A above but for the kth sample.
The remaining statistics are calculated as for the one sample case.

4 References

Pettitt A N (1982) Inference for the linear model using a likelihood based on ranks J. Roy. Statist. Soc. Ser. B 44 234–243

5 Arguments

1:   NS – INTEGERInput
On entry: the number of samples.
Constraint: NS≥1.
2:   NV NS – INTEGER arrayInput
On entry: the number of observations in the ith sample, for i=1,2,…,NS.
Constraint: NV i≥1, for i=1,2,…,NS.
3:   NSUM – INTEGERInput
On entry: the total number of observations.
Constraint: NSUM=∑ i=1 NS NV i .
4:   Y NSUM – REAL (KIND=nag_wp) arrayInput
On entry: the observations in each sample. Specifically, Y ∑ k=1 i-1 NV k+j must contain the jth observation in the ith sample.
5:   IP – INTEGERInput
On entry: the number of parameters to be fitted.
Constraint: IP≥1.
6:   X LDXIP – REAL (KIND=nag_wp) arrayInput
On entry: the design matrices for each sample. Specifically, X ∑ k=1 i-1 NV k +j l must contain the value of the lth explanatory variable for the jth observation in the ith sample.
Constraint: X must not contain a column with all elements equal.
7:   LDX – INTEGERInput
On entry: the first dimension of the array X as declared in the (sub)program from which G08RAF is called.
Constraint: LDX≥NSUM.
8:   IDIST – INTEGERInput
On entry: the error distribution to be used in the analysis.
IDIST=1
Normal.
IDIST=2
Logistic.
IDIST=3
Extreme value.
IDIST=4
Double-exponential.
Constraint: 1≤IDIST≤4.
9:   NMAX – INTEGERInput
On entry: the value of the largest sample size.
Constraint: NMAX=max 1≤i≤NS NV i and NMAX>IP.
10:   TOL – REAL (KIND=nag_wp)Input
On entry: the tolerance for judging whether two observations are tied. Thus, observations Yi and Yj are adjudged to be tied if Yi-Yj<TOL.
Constraint: TOL>0.0.
11:   PRVR LDPRVRIP – REAL (KIND=nag_wp) arrayOutput
On exit: the variance-covariance matrices of the score statistics and the parameter estimates, the former being stored in the upper triangle and the latter in the lower triangle. Thus for 1≤i≤j≤IP, PRVR ij contains an estimate of the covariance between the ith and jth score statistics. For 1≤j≤i≤IP-1, PRVR i+1 j contains an estimate of the covariance between the ith and jth parameter estimates.
12:   LDPRVR – INTEGERInput
On entry: the first dimension of the array PRVR as declared in the (sub)program from which G08RAF is called.
Constraint: LDPRVR≥IP+1.
13:   IRANK NMAX – INTEGER arrayOutput
On exit: for the one sample case, IRANK contains the ranks of the observations.
14:   ZIN NMAX – REAL (KIND=nag_wp) arrayOutput
On exit: for the one sample case, ZIN contains the expected values of the function g. of the order statistics.
15:   ETA NMAX – REAL (KIND=nag_wp) arrayOutput
On exit: for the one sample case, ETA contains the expected values of the function g′. of the order statistics.
16:   VAPVEC NMAX×NMAX+1/2 – REAL (KIND=nag_wp) arrayOutput
On exit: for the one sample case, VAPVEC contains the upper triangle of the variance-covariance matrix of the function g. of the order statistics stored column-wise.
17:   PAREST 4×IP+1 – REAL (KIND=nag_wp) arrayOutput
On exit: the statistics calculated by the routine.
The first IP components of PAREST contain the score statistics.
The next IP elements contain the parameter estimates.
PAREST 2×IP+1 contains the value of the χ 2 statistic.
The next IP elements of PAREST contain the standard errors of the parameter estimates.
Finally, the remaining IP elements of PAREST contain the z-statistics.
18:   WORK LWORK – REAL (KIND=nag_wp) arrayWorkspace
19:   LWORK – INTEGERInput
On entry: the dimension of the array WORK as declared in the (sub)program from which G08RAF is called.
Constraint: LWORK≥NMAX×IP+1.
20:   IWA NMAX – INTEGER arrayWorkspace
21:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, | NS<1,
or | TOL≤0.0,
or | NMAX≤IP,
or | LDPRVR<IP+1,
or | LDX<NSUM,
or | NMAX≠max 1≤i≤NS NV i,
or | NV i≤0, for some i, NV i,
or | NSUM≠∑i=1 NS NV i,
or | IP<1,
or | LWORK<NMAX×IP+1.
IFAIL=2
On entry, | IDIST<1,
or | IDIST>4.
IFAIL=3
On entry, all the observations are adjudged to be tied. You are advised to check the value supplied for TOL.
IFAIL=4
The matrix XT B-A X is either ill-conditioned or not positive definite. This error should only occur with extreme rankings of the data.
IFAIL=5
The matrix X has at least one of its columns with all elements equal.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

The computations are believed to be stable.

8 Parallelism and Performance

G08RAF is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
G08RAF makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The time taken by G08RAF depends on the number of samples, the total number of observations and the number of arguments fitted.
In extreme cases the parameter estimates for certain models can be infinite, although this is unlikely to occur in practice. See Pettitt (1982) for further details.

10 Example

A program to fit a regression model to a single sample of 20 observations using two explanatory variables. The error distribution will be taken to be logistic.

10.1 Program Text

Program Text (g08rafe.f90)

10.2 Program Data

Program Data (g08rafe.d)

10.3 Program Results

Program Results (g08rafe.r)

G08 Chapter Contents
G08 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


G08RBF : NAG Library, Mark 26

G08 Chapter Contents
G08 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

G08RBF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

G08RBF calculates the parameter estimates, score statistics and their variance-covariance matrices for the linear model using a likelihood based on the ranks of the observations when some of the observations may be right-censored.

2 Specification

SUBROUTINE G08RBF ( NS, NV, NSUM, Y, IP, X, LDX, ICEN, GAMMA, NMAX, TOL, PRVR, LDPRVR, IRANK, ZIN, ETA, VAPVEC, PAREST, WORK, LWORK, IWA, IFAIL)
INTEGER | NS, NV(NS), NSUM, IP, LDX, ICEN(NSUM), NMAX, LDPRVR, IRANK(NMAX), LWORK, IWA(4*NMAX), IFAIL
REAL (KIND=nag_wp) | Y(NSUM), X(LDX,IP), GAMMA, TOL, PRVR(LDPRVR,IP), ZIN(NMAX), ETA(NMAX), VAPVEC(NMAX*(NMAX+1)/2), PAREST(4*IP+1), WORK(LWORK)

3 Description

Analysis of data can be made by replacing observations by their ranks. The analysis produces inference for the regression model where the location parameters of the observations, θi, for i=1,2,…,n, are related by θ=Xβ. Here X is an n by p matrix of explanatory variables and β is a vector of p unknown regression parameters. The observations are replaced by their ranks and an approximation, based on Taylor's series expansion, made to the rank marginal likelihood. For details of the approximation see Pettitt (1982).
An observation is said to be right-censored if we can only observe Yj* with Yj*≤Yj. We rank censored and uncensored observations as follows. Suppose we can observe Yj, for j=1,2,…,n, directly but Yj*, for j=n+1,…,q and n≤q, are censored on the right. We define the rank rj of Yj, for j=1,2,…,n, in the usual way; rj equals i if and only if Yj is the ith smallest amongst the Y 1,Y 2,…,Yn. The right-censored Yj*, for j=n+1,n+2,…,q, has rank rj if and only if Yj* lies in the interval Y rj,Y rj+1, with Y 0=-∞, Y n+1=+∞ and Y 1<⋯<Y n the ordered Yj, for j=1,2,…,n.
The distribution of the Y is assumed to be of the following form. Let FL y=ey/1+ey, the logistic distribution function, and consider the distribution function Fγ y defined by 1-Fγ=1-FL y 1/γ . This distribution function can be thought of as either the distribution function of the minimum, X 1,γ, of a random sample of size γ-1 from the logistic distribution, or as the Fγ y-log⁡γ being the distribution function of a random variable having the F-distribution with 2 and 2 γ-1 degrees of freedom. This family of generalized logistic distribution functions Fγ.;0≤γ<∞ naturally links the symmetric logistic distribution γ=1 with the skew extreme value distribution (lim⁡γ→0) and with the limiting negative exponential distribution (lim⁡γ→∞). For this family explicit results are available for right-censored data. See Pettitt (1983) for details.
Let lR denote the logarithm of the rank marginal likelihood of the observations and define the q×1 vector a by a=lR′θ=0, and let the q by q diagonal matrix B and q by q symmetric matrix A be given by B-A=-lR′′θ=0. Then various statistics can be found from the analysis.
(a) | The score statistic XT a. This statistic is used to test the hypothesis H 0:β=0 (see (e)).
(b) | The estimated variance-covariance matrix of the score statistic in (a).
(c) | The estimate β^R=M XT a.
(d) | The estimated variance-covariance matrix M=XT B-A X -1 of the estimate β^R.
(e) | The χ 2 statistic Q=β^R M-1​ ​β^r=aT X XT B-A X -1XT a, used to test H 0:β=0. Under H 0, Q has an approximate χ 2-distribution with p degrees of freedom.
(f) | The standard errors M ii 1/2 of the estimates given in (c).
(g) | Approximate z-statistics, i.e., Zi=β^Ri/se β^Ri for testing H 0:βi=0. For i=1,2,…,n, Zi has an approximate N 0,1 distribution.
In many situations, more than one sample of observations will be available. In this case we assume the model,
hk Yk = XkT β+ek ,   k=1,2,…,NS ,
where NS is the number of samples. In an obvious manner, Yk and Xk are the vector of observations and the design matrix for the kth sample respectively. Note that the arbitrary transformation hk can be assumed different for each sample since observations are ranked within the sample.
The earlier analysis can be extended to give a combined estimate of β as β^=Dd, where
D-1=∑k=1 NS XT Bk-Ak Xk
and
d=∑k= 1 NS XkT ak ,
with ak, Bk and Ak defined as a, B and A above but for the kth sample.
The remaining statistics are calculated as for the one sample case.

4 References

Kalbfleisch J D and Prentice R L (1980) The Statistical Analysis of Failure Time Data Wiley
Pettitt A N (1982) Inference for the linear model using a likelihood based on ranks J. Roy. Statist. Soc. Ser. B 44 234–243
Pettitt A N (1983) Approximate methods using ranks for regression with censored data Biometrika 70 121–132

5 Arguments

1:   NS – INTEGERInput
On entry: the number of samples.
Constraint: NS≥1.
2:   NV NS – INTEGER arrayInput
On entry: the number of observations in the ith sample, for i=1,2,…,NS.
Constraint: NV i≥1, for i=1,2,…,NS.
3:   NSUM – INTEGERInput
On entry: the total number of observations.
Constraint: NSUM=∑ i=1 NS NV i .
4:   Y NSUM – REAL (KIND=nag_wp) arrayInput
On entry: the observations in each sample. Specifically, Y ∑ k=1 i-1 NV k+j must contain the jth observation in the ith sample.
5:   IP – INTEGERInput
On entry: the number of parameters to be fitted.
Constraint: IP≥1.
6:   X LDXIP – REAL (KIND=nag_wp) arrayInput
On entry: the design matrices for each sample. Specifically, X ∑ k=1 i-1 NV k + j l must contain the value of the lth explanatory variable for the jth observations in the ith sample.
Constraint: X must not contain a column with all elements equal.
7:   LDX – INTEGERInput
On entry: the first dimension of the array X as declared in the (sub)program from which G08RBF is called.
Constraint: LDX≥NSUM.
8:   ICEN NSUM – INTEGER arrayInput
On entry: defines the censoring variable for the observations in Y.
ICEN i=0
If Y i is uncensored.
ICEN i=1
If Y i is censored.
Constraint: ICEN i=0 or 1, for i=1,2,…,NSUM.
9:   GAMMA – REAL (KIND=nag_wp)Input
On entry: the value of the parameter defining the generalized logistic distribution. For GAMMA≤0.0001, the limiting extreme value distribution is assumed.
Constraint: GAMMA≥0.0.
10:   NMAX – INTEGERInput
On entry: the value of the largest sample size.
Constraint: NMAX=max 1≤i≤NS NV i and NMAX>IP.
11:   TOL – REAL (KIND=nag_wp)Input
On entry: the tolerance for judging whether two observations are tied. Thus, observations Yi and Yj are adjudged to be tied if Yi-Yj<TOL.
Constraint: TOL>0.0.
12:   PRVR LDPRVRIP – REAL (KIND=nag_wp) arrayOutput
On exit: the variance-covariance matrices of the score statistics and the parameter estimates, the former being stored in the upper triangle and the latter in the lower triangle. Thus for 1≤i≤j≤IP, PRVR ij contains an estimate of the covariance between the ith and jth score statistics. For 1≤j≤i≤IP-1, PRVR i+1 j contains an estimate of the covariance between the ith and jth parameter estimates.
13:   LDPRVR – INTEGERInput
On entry: the first dimension of the array PRVR as declared in the (sub)program from which G08RBF is called.
Constraint: LDPRVR≥IP+1.
14:   IRANK NMAX – INTEGER arrayOutput
On exit: for the one sample case, IRANK contains the ranks of the observations.
15:   ZIN NMAX – REAL (KIND=nag_wp) arrayOutput
On exit: for the one sample case, ZIN contains the expected values of the function g. of the order statistics.
16:   ETA NMAX – REAL (KIND=nag_wp) arrayOutput
On exit: for the one sample case, ETA contains the expected values of the function g′. of the order statistics.
17:   VAPVEC NMAX×NMAX+1/2 – REAL (KIND=nag_wp) arrayOutput
On exit: for the one sample case, VAPVEC contains the upper triangle of the variance-covariance matrix of the function g. of the order statistics stored column-wise.
18:   PAREST 4×IP+1 – REAL (KIND=nag_wp) arrayOutput
On exit: the statistics calculated by the routine.
The first IP components of PAREST contain the score statistics.
The next IP elements contain the parameter estimates.
PAREST 2×IP+1 contains the value of the χ 2 statistic.
The next IP elements of PAREST contain the standard errors of the parameter estimates.
Finally, the remaining IP elements of PAREST contain the z-statistics.
19:   WORK LWORK – REAL (KIND=nag_wp) arrayWorkspace
20:   LWORK – INTEGERInput
On entry: the dimension of the array WORK as declared in the (sub)program from which G08RBF is called.
Constraint: LWORK≥NMAX×IP+1.
21:   IWA 4×NMAX – INTEGER arrayWorkspace
22:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, | NS<1,
or | TOL≤0.0,
or | NMAX≤IP,
or | LDPRVR<IP+1,
or | LDX<NSUM,
or | NMAX≠max 1≤i≤NS NV i,
or | NV i≤0 for some i, i=1,2,…,NS,
or | NSUM≠∑i=1 NS NV i,
or | IP<1,
or | GAMMA<0.0,
or | LWORK<NMAX×IP+1.
IFAIL=2
On entry, ICEN i≠0 or 1, for some 1≤i≤NSUM.
IFAIL=3
On entry, all the observations are adjudged to be tied. You are advised to check the value supplied for TOL.
IFAIL=4
The matrix XT B-A X is either ill-conditioned or not positive definite. This error should only occur with extreme rankings of the data.
IFAIL=5
On entry, at least one column of the matrix X has all its elements equal.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

The computations are believed to be stable.

8 Parallelism and Performance

G08RBF is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
G08RBF makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The time taken by G08RBF depends on the number of samples, the total number of observations and the number of parameters fitted.
In extreme cases the parameter estimates for certain models can be infinite, although this is unlikely to occur in practice. See Pettitt (1982) for further details.

10 Example

This example fits a regression model to a single sample of 40 observations using just one explanatory variable.

10.1 Program Text

Program Text (g08rbfe.f90)

10.2 Program Data

Program Data (g08rbfe.d)

10.3 Program Results

Program Results (g08rbfe.r)

G08 Chapter Contents
G08 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


G10ABF : NAG Library, Mark 26

G10 Chapter Contents
G10 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

G10ABF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

G10ABF fits a cubic smoothing spline for a given smoothing parameter.

2 Specification

SUBROUTINE G10ABF ( MODE, WEIGHT, N, X, Y, WT, RHO, YHAT, C, LDC, RSS, DF, RES, H, COMM, IFAIL)
INTEGER | N, LDC, IFAIL
REAL (KIND=nag_wp) | X(N), Y(N), WT(*), RHO, YHAT(N), C(LDC,3), RSS, DF, RES(N), H(N), COMM(9*N+14)
CHARACTER(1) | MODE, WEIGHT

3 Description

G10ABF fits a cubic smoothing spline to a set of n observations (xi, yi), for i=1,2,…,n. The spline provides a flexible smooth function for situations in which a simple polynomial or nonlinear regression model is unsuitable.
Cubic smoothing splines arise as the unique real-valued solution function f, with absolutely continuous first derivative and squared-integrable second derivative, which minimizes:
∑i=1 n wi yi-f xi 2+ρ ∫-∞∞f′′x 2 dx,
where wi is the (optional) weight for the ith observation and ρ is the smoothing parameter. This criterion consists of two parts: the first measures the fit of the curve, and the second the smoothness of the curve. The value of the smoothing parameter ρ weights these two aspects; larger values of ρ give a smoother fitted curve but, in general, a poorer fit. For details of how the cubic spline can be estimated see Hutchinson and de Hoog (1985) and Reinsch (1967).
The fitted values, y^ = y^1,y^2,…,y^n T , and weighted residuals, ri, can be written as
y^=Hy  and  ri=wi yi-y^i
for a matrix H. The residual degrees of freedom for the spline is trace I-H and the diagonal elements of H, h ii, are the leverages.
The parameter ρ can be chosen in a number of ways. The fit can be inspected for a number of different values of ρ. Alternatively the degrees of freedom for the spline, which determines the value of ρ, can be specified, or the (generalized) cross-validation can be minimized to give ρ; see G10ACF for further details.
G10ABF requires the xi to be strictly increasing. If two or more observations have the same xi-value then they should be replaced by a single observation with yi equal to the (weighted) mean of the y values and weight, wi, equal to the sum of the weights. This operation can be performed by G10ZAF.
The computation is split into three phases.
(i) | Compute matrices needed to fit spline.
(ii) | Fit spline for a given value of ρ.
(iii) | Compute spline coefficients.
When fitting the spline for several different values of ρ, phase (i) need only be carried out once and then phase (ii) repeated for different values of ρ. If the spline is being fitted as part of an iterative weighted least squares procedure phases (i) and (ii) have to be repeated for each set of weights. In either case, phase (iii) will often only have to be performed after the final fit has been computed.
The algorithm is based on Hutchinson (1986).

4 References

Hastie T J and Tibshirani R J (1990) Generalized Additive Models Chapman and Hall
Hutchinson M F (1986) Algorithm 642: A fast procedure for calculating minimum cross-validation cubic smoothing splines ACM Trans. Math. Software 12 150–153
Hutchinson M F and de Hoog F R (1985) Smoothing noisy data with spline functions Numer. Math. 47 99–106
Reinsch C H (1967) Smoothing by spline functions Numer. Math. 10 177–183

5 Arguments

1:   MODE – CHARACTER(1)Input
On entry: indicates in which mode the routine is to be used.
MODE='P'
Initialization and fitting is performed. This partial fit can be used in an iterative weighted least squares context where the weights are changing at each call to G10ABF or when the coefficients are not required.
MODE='Q'
Fitting only is performed. Initialization must have been performed previously by a call to G10ABF with MODE='P'. This quick fit may be called repeatedly with different values of RHO without re-initialization.
MODE='F'
Initialization and full fitting is performed and the function coefficients are calculated.
Constraint: MODE='P', 'Q' or 'F'.
2:   WEIGHT – CHARACTER(1)Input
On entry: indicates whether user-defined weights are to be used.
WEIGHT='W'
User-defined weights should be supplied in WT.
WEIGHT='U'
The data is treated as unweighted.
Constraint: WEIGHT='W' or 'U'.
3:   N – INTEGERInput
On entry: n, the number of distinct observations.
Constraint: N≥3.
4:   X N – REAL (KIND=nag_wp) arrayInput
On entry: the distinct and ordered values xi, for i=1,2,…,n.
Constraint: X i<X i+1, for i=1,2,…,n-1.
5:   Y N – REAL (KIND=nag_wp) arrayInput
On entry: the values yi, for i=1,2,…,n.
6:   WT* – REAL (KIND=nag_wp) arrayInput
Note: the dimension of the array WT must be at least N if WEIGHT='W'.
On entry: if WEIGHT='W', WT must contain the n weights. Otherwise WT is not referenced and unit weights are assumed.
Constraint: if WEIGHT='W', WT i>0.0, for i=1,2,…,n.
7:   RHO – REAL (KIND=nag_wp)Input
On entry: ρ, the smoothing parameter.
Constraint: RHO≥0.0.
8:   YHAT N – REAL (KIND=nag_wp) arrayOutput
On exit: the fitted values, y^i, for i=1,2,…,n.
9:   C LDC 3 – REAL (KIND=nag_wp) arrayInput/Output
On entry: if MODE='Q', C must be unaltered from the previous call to G10ABF with MODE='P'. Otherwise C need not be set.
On exit: if MODE='F', C contains the spline coefficients. More precisely, the value of the spline at t is given by C i 3 × d + C i 2 × d + C i 1 × d + y^i , where xi≤t<x i+1 and d=t-xi.
If MODE='P' or 'Q', C contains information that will be used in a subsequent call to G10ABF with MODE='Q'.
10:   LDC – INTEGERInput
On entry: the first dimension of the array C as declared in the (sub)program from which G10ABF is called.
Constraint: LDC≥N-1.
11:   RSS – REAL (KIND=nag_wp)Output
On exit: the (weighted) residual sum of squares.
12:   DF – REAL (KIND=nag_wp)Output
On exit: the residual degrees of freedom.
13:   RES N – REAL (KIND=nag_wp) arrayOutput
On exit: the (weighted) residuals, ri, for i=1,2,…,n.
14:   H N – REAL (KIND=nag_wp) arrayOutput
On exit: the leverages, h ii, for i=1,2,…,n.
15:   COMM 9×N+14 – REAL (KIND=nag_wp) arrayCommunication Array
On entry: if MODE='Q', COMM must be unaltered from the previous call to G10ABF with MODE='P'. Otherwise COMM need not be set.
On exit: if MODE='P' or 'Q', COMM contains information that will be used in a subsequent call to G10ABF with MODE='Q'.
16:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, | N<3,
or | LDC<N-1,
or | RHO<0.0,
or | MODE≠'Q', 'P' or 'F',
or | WEIGHT≠'W' or 'U'.
IFAIL=2
On entry, WEIGHT='W' and at least one element of WT≤0.0.
IFAIL=3
On entry, X i≥X i+1, for some i, i=1,2,…,n-1.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

Accuracy depends on the value of ρ and the position of the x values. The values of xi-x i-1 and wi are scaled and ρ is transformed to avoid underflow and overflow problems.

8 Parallelism and Performance

G10ABF is not threaded in any implementation.

9 Further Comments

The time taken by G10ABF is of order n.
Regression splines with a small <n number of knots can be fitted by E02BAF and E02BEF.

10 Example

The data, given by Hastie and Tibshirani (1990), is the age, xi, and C-peptide concentration (pmol/ml), yi, from a study of the factors affecting insulin-dependent diabetes mellitus in children. The data is input, reduced to a strictly ordered set by G10ZAF and a series of splines fit using a range of values for the smoothing parameter, ρ.

10.1 Program Text

Program Text (g10abfe.f90)

10.2 Program Data

Program Data (g10abfe.d)

10.3 Program Results

Program Results (g10abfe.r)

GnuplotProduced by GNUPLOT 4.6 patchlevel 3 3 3.5 4 4.5 5 5.5 6 6.5 7 0 2 4 6 8 10 12 14 16 C-peptide concentration (pmol/ml) Age (years) Example Program Cubic Smoothing Spline Study of the factors affecting insulin-dependent diabetes mellitus in children Hastie and Tibshirani (1990) gnuplot_plot_1 raw data gnuplot_plot_2 ρ = 1 gnuplot_plot_3 ρ = 10 gnuplot_plot_4 ρ = 100
G10 Chapter Contents
G10 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


G10ACF : NAG Library, Mark 26

G10 Chapter Contents
G10 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

G10ACF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

G10ACF estimates the values of the smoothing parameter and fits a cubic smoothing spline to a set of data.

2 Specification

SUBROUTINE G10ACF ( METHOD, WEIGHT, N, X, Y, WT, YHAT, C, LDC, RSS, DF, RES, H, CRIT, RHO, U, TOL, MAXCAL, WK, IFAIL)
INTEGER | N, LDC, MAXCAL, IFAIL
REAL (KIND=nag_wp) | X(N), Y(N), WT(*), YHAT(N), C(LDC,3), RSS, DF, RES(N), H(N), CRIT, RHO, U, TOL, WK(7*(N+2))
CHARACTER(1) | METHOD, WEIGHT

3 Description

For a set of n observations xi,yi, for i=1,2,…,n, the spline provides a flexible smooth function for situations in which a simple polynomial or nonlinear regression model is not suitable.
Cubic smoothing splines arise as the unique real-valued solution function f, with absolutely continuous first derivative and squared-integrable second derivative, which minimizes
∑i=1 n wi yi-f xi 2+ρ ∫-∞∞f′′x 2 dx,
where wi is the (optional) weight for the ith observation and ρ is the smoothing argument. This criterion consists of two parts: the first measures the fit of the curve and the second the smoothness of the curve. The value of the smoothing argument ρ weights these two aspects; larger values of ρ give a smoother fitted curve but, in general, a poorer fit. For details of how the cubic spline can be fitted see Hutchinson and de Hoog (1985) and Reinsch (1967).
The fitted values, y^ = y^1,y^2,…,y^n T , and weighted residuals, ri, can be written as:
y^=Hy  and  ri=wi yi-y^i
for a matrix H. The residual degrees of freedom for the spline is trace I-H and the diagonal elements of H are the leverages.
The parameter ρ can be estimated in a number of ways.
(i) The degrees of freedom for the spline can be specified, i.e., find ρ such that trace H=ν 0 for given ν 0.
(ii) Minimize the cross-validation (CV), i.e., find ρ such that the CV is minimized, where
CV=1∑i=1 n wi ∑i=1 n ri 1-h ii 2.
(iii) Minimize the generalized cross-validation (GCV), i.e., find ρ such that the GCV is minimized, where
GCV=n 2∑i=1 n wi ∑i=1 n ri 2 ∑i=1 n 1-h ii 2 .
G10ACF requires the xi to be strictly increasing. If two or more observations have the same xi value then they should be replaced by a single observation with yi equal to the (weighted) mean of the y values and weight, wi, equal to the sum of the weights. This operation can be performed by G10ZAF.
The algorithm is based on Hutchinson (1986). C05AZF is used to solve for ρ given ν 0 and the method of E04ABF/E04ABA is used to minimize the GCV or CV.

4 References

Hastie T J and Tibshirani R J (1990) Generalized Additive Models Chapman and Hall
Hutchinson M F (1986) Algorithm 642: A fast procedure for calculating minimum cross-validation cubic smoothing splines ACM Trans. Math. Software 12 150–153
Hutchinson M F and de Hoog F R (1985) Smoothing noisy data with spline functions Numer. Math. 47 99–106
Reinsch C H (1967) Smoothing by spline functions Numer. Math. 10 177–183

5 Arguments

1:   METHOD – CHARACTER(1)Input
On entry: indicates whether the smoothing parameter is to be found by minimization of the CV or GCV functions, or by finding the smoothing parameter corresponding to a specified degrees of freedom value.
METHOD='C'
Cross-validation is used.
METHOD='D'
The degrees of freedom are specified.
METHOD='G'
Generalized cross-validation is used.
Constraint: METHOD='C', 'D' or 'G'.
2:   WEIGHT – CHARACTER(1)Input
On entry: indicates whether user-defined weights are to be used.
WEIGHT='W'
User-defined weights should be supplied in WT.
WEIGHT='U'
The data is treated as unweighted.
Constraint: WEIGHT='W' or 'U'.
3:   N – INTEGERInput
On entry: n, the number of observations.
Constraint: N≥3.
4:   X N – REAL (KIND=nag_wp) arrayInput
On entry: the distinct and ordered values xi, for i=1,2,…,n.
Constraint: X i<X i+1, for i=1,2,…,n-1.
5:   Y N – REAL (KIND=nag_wp) arrayInput
On entry: the values yi, for i=1,2,…,n.
6:   WT* – REAL (KIND=nag_wp) arrayInput
Note: the dimension of the array WT must be at least N if WEIGHT='W'.
On entry: if WEIGHT='W', WT must contain the n weights. Otherwise WT is not referenced and unit weights are assumed.
Constraint: if WEIGHT='W', WT i>0.0, for i=1,2,…,n.
7:   YHAT N – REAL (KIND=nag_wp) arrayOutput
On exit: the fitted values, y^i, for i=1,2,…,n.
8:   C LDC 3 – REAL (KIND=nag_wp) arrayOutput
On exit: the spline coefficients. More precisely, the value of the spline approximation at t is given by C i 3×d+C i 2×d+C i 1×d+y^i, where xi≤t<x i+1 and d=t-xi.
9:   LDC – INTEGERInput
On entry: the first dimension of the array C as declared in the (sub)program from which G10ACF is called.
Constraint: LDC≥N-1.
10:   RSS – REAL (KIND=nag_wp)Output
On exit: the (weighted) residual sum of squares.
11:   DF – REAL (KIND=nag_wp)Output
On exit: the residual degrees of freedom. If METHOD='D' this will be n-CRIT to the required accuracy.
12:   RES N – REAL (KIND=nag_wp) arrayOutput
On exit: the (weighted) residuals, ri, for i=1,2,…,n.
13:   H N – REAL (KIND=nag_wp) arrayOutput
On exit: the leverages, h ii, for i=1,2,…,n.
14:   CRIT – REAL (KIND=nag_wp)Input/Output
On entry: if METHOD='D', the required degrees of freedom for the spline.
If METHOD='C' or 'G', CRIT need not be set.
Constraint: 2.0<CRIT≤N.
On exit: if METHOD='C', the value of the cross-validation, or if METHOD='G', the value of the generalized cross-validation function, evaluated at the value of ρ returned in RHO.
15:   RHO – REAL (KIND=nag_wp)Output
On exit: the smoothing parameter, ρ.
16:   U – REAL (KIND=nag_wp)Input
On entry: the upper bound on the smoothing parameter. If U≤TOL, U=1000.0 will be used instead. See Section 9 for details on how this argument is used.
17:   TOL – REAL (KIND=nag_wp)Input
On entry: the accuracy to which the smoothing parameter RHO is required. TOL should preferably be not much less than ε, where ε is the machine precision. If TOL<ε, TOL=ε will be used instead.
18:   MAXCAL – INTEGERInput
On entry: the maximum number of spline evaluations to be used in finding the value of ρ. If MAXCAL<3, MAXCAL=100 will be used instead.
19:   WK 7×N+2 – REAL (KIND=nag_wp) arrayWorkspace
20:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, CRIT=value.
Constraint: if METHOD='D', CRIT>2.0.
On entry, CRIT=value.
Constraint: if METHOD='D', CRIT≤N.
On entry, LDC=value and N=value.
Constraint: LDC≥N-1.
On entry, METHOD is not valid: METHOD=value.
On entry, N=value.
Constraint: N≥3.
On entry, WEIGHT is not valid: WEIGHT=value.
IFAIL=2
On entry, at least one element of WT≤0.0.
IFAIL=3
On entry, X is not a strictly ordered array.
IFAIL=4
For the specified degrees of freedom, RHO>U: U=value.
IFAIL=5
Accuracy of TOL cannot be achieved: TOL=value.
IFAIL=6
MAXCAL iterations have been performed.
IFAIL=7
Optimum value of RHO lies above U: U=value.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

When minimizing the cross-validation or generalized cross-validation, the error in the estimate of ρ should be within ±3 TOL×RHO+TOL. When finding ρ for a fixed number of degrees of freedom the error in the estimate of ρ should be within ±2×TOL×max 1,RHO.
Given the value of ρ, the accuracy of the fitted spline depends on the value of ρ and the position of the x values. The values of xi-x i-1 and wi are scaled and ρ is transformed to avoid underflow and overflow problems.

8 Parallelism and Performance

G10ACF is not threaded in any implementation.

9 Further Comments

The time to fit the spline for a given value of ρ is of order n.
When finding the value of ρ that gives the required degrees of freedom, the algorithm examines the interval 0.0 to U. For small degrees of freedom the value of ρ can be large, as in the theoretical case of two degrees of freedom when the spline reduces to a straight line and ρ is infinite. If the CV or GCV is to be minimized then the algorithm searches for the minimum value in the interval 0.0 to U. If the function is decreasing in that range then the boundary value of U will be returned. In either case, the larger the value of U the more likely is the interval to contain the required solution, but the process will be less efficient.
Regression splines with a small <n number of knots can be fitted by E02BAF and E02BEF.

10 Example

This example uses the data given by Hastie and Tibshirani (1990), which consists of the age, xi, and C-peptide concentration (pmol/ml), yi, from a study of the factors affecting insulin-dependent diabetes mellitus in children. The data is input, reduced to a strictly ordered set by G10ZAF and a spline with 5 degrees of freedom is fitted by G10ACF. The fitted values and residuals are printed.

10.1 Program Text

Program Text (g10acfe.f90)

10.2 Program Data

Program Data (g10acfe.d)

10.3 Program Results

Program Results (g10acfe.r)

G10 Chapter Contents
G10 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


G10BAF : NAG Library, Mark 26

G10 Chapter Contents
G10 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

G10BAF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

G10BAF performs kernel density estimation using a Gaussian kernel.

2 Specification

SUBROUTINE G10BAF ( N, X, WINDOW, SLO, SHI, NS, SMOOTH, T, USEFFT, FFT, IFAIL)
INTEGER | N, NS, IFAIL
REAL (KIND=nag_wp) | X(N), WINDOW, SLO, SHI, SMOOTH(NS), T(NS), FFT(NS)
LOGICAL | USEFFT

3 Description

Given a sample of n observations, x 1,x 2,…,xn, from a distribution with unknown density function, f x, an estimate of the density function, f^x, may be required. The simplest form of density estimator is the histogram. This may be defined by:
f^ x = 1 nh nj ,   a + j-1 h < x < a + j h ,   j=1,2,…,ns ,
where nj is the number of observations falling in the interval a+j-1 h to a+jh, a is the lower bound to the histogram and b=ns h is the upper bound. The value h is known as the window width. To produce a smoother density estimate a kernel method can be used. A kernel function, K t, satisfies the conditions:
∫-∞∞K t dt=1  and  K t≥0.
The kernel density estimator is then defined as
f^x=1 nh ∑i= 1 n K x-xi h .
The choice of K is usually not important but to ease the computational burden use can be made of the Gaussian kernel defined as
K t=1 2 π e-t 2/2.
The smoothness of the estimator depends on the window width h. The larger the value of h the smoother the density estimate. The value of h can be chosen by examining plots of the smoothed density for different values of h or by using cross-validation methods (see Silverman (1990)).
Silverman (1982) and Silverman (1990) show how the Gaussian kernel density estimator can be computed using a fast Fourier transform (FFT). In order to compute the kernel density estimate over the range a to b the following steps are required.
(i) | Discretize the data to give ns equally spaced points tl with weights ξl (see Jones and Lotwick (1984)).
(ii) | Compute the FFT of the weights ξl to give Yl.
(iii) | Compute ζl=e-12 h 2 sl 2 Yl where sl=2 πl/b-a.
(iv) | Find the inverse FFT of ζl to give f^x.
To compute the kernel density estimate for further values of h only steps (iii) and (iv) need be repeated.

4 References

Jones M C and Lotwick H W (1984) Remark AS R50. A remark on algorithm AS 176. Kernel density estimation using the Fast Fourier Transform Appl. Statist. 33 120–122
Silverman B W (1982) Algorithm AS 176. Kernel density estimation using the fast Fourier transform Appl. Statist. 31 93–99
Silverman B W (1990) Density Estimation Chapman and Hall

5 Arguments

1:   N – INTEGERInput
On entry: n, the number of observations in the sample.
Constraint: N>0.
2:   X N – REAL (KIND=nag_wp) arrayInput
On entry: the n observations, xi, for i=1,2,…,n.
3:   WINDOW – REAL (KIND=nag_wp)Input
On entry: h, the window width.
Constraint: WINDOW>0.0.
4:   SLO – REAL (KIND=nag_wp)Input
On entry: a, the lower limit of the interval on which the estimate is calculated. For most applications SLO should be at least three window widths below the lowest data point.
Constraint: SLO<SHI.
5:   SHI – REAL (KIND=nag_wp)Input
On entry: b, the upper limit of the interval on which the estimate is calculated. For most applications SHI should be at least three window widths above the highest data point.
6:   NS – INTEGERInput
On entry: the number of points at which the estimate is calculated, ns.
Constraint: NS≥2.
7:   SMOOTH NS – REAL (KIND=nag_wp) arrayOutput
On exit: the ns values of the density estimate, f^tl, for l=1,2,…,ns.
8:   T NS – REAL (KIND=nag_wp) arrayOutput
On exit: the points at which the estimate is calculated, tl, for l=1,2,…,ns.
9:   USEFFT – LOGICALInput
On entry: must be set to .FALSE. if the values of Yl are to be calculated by G10BAF and to .TRUE. if they have been computed by a previous call to G10BAF and are provided in FFT. If USEFFT=.TRUE. then the arguments N, SLO, SHI, NS and FFT must remain unchanged from the previous call to G10BAF with USEFFT=.FALSE..
10:   FFT NS – REAL (KIND=nag_wp) arrayInput/Output
On entry: if USEFFT=.TRUE., FFT must contain the fast Fourier transform of the weights of the discretized data, ξl, for l=1,2,…,ns. Otherwise FFT need not be set.
On exit: the fast Fourier transform of the weights of the discretized data, ξl, for l=1,2,…,ns.
11:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, | N≤0,
or | NS<2,
or | SHI≤SLO,
or | WINDOW≤0.0.
IFAIL=2
On entry, | G10BAF has been called with USEFFT=.TRUE. but the routine has not been called previously with USEFFT=.FALSE.,
or | G10BAF has been called with USEFFT=.TRUE. but some of the arguments N, SLO, SHI, NS have been changed since the previous call to G10BAF with USEFFT=.FALSE..
IFAIL=4
On entry, the interval given by SLO to SHI does not extend beyond three window widths at either extreme of the dataset. This may distort the density estimate in some cases.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

See Jones and Lotwick (1984) for a discussion of the accuracy of this method.

8 Parallelism and Performance

G10BAF is not thread safe and should not be called from a multithreaded user program. Please see Section 3.12.1 in How to Use the NAG Library and its Documentation for more information on thread safety.
G10BAF is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
G10BAF makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The time for computing the weights of the discretized data is of order n, while the time for computing the FFT is of order ns log ns, as is the time for computing the inverse of the FFT.

10 Example

Data is read from a file and the density estimated. The first 20 values are then printed. The full estimated density function is shown in the accompanying plot.

10.1 Program Text

Program Text (g10bafe.f90)

10.2 Program Data

Program Data (g10bafe.d)

10.3 Program Results

Program Results (g10bafe.r)

GnuplotProduced by GNUPLOT 4.6 patchlevel 3 0 0.05 0.1 0.15 0.2 0.25 0.3 0.35 0.4 −5 −4 −3 −2 −1 0 1 2 3 4 5 Density Estimate t Example Program Plot of the Smoothed Density (window = 0.4) gnuplot_plot_1
G10 Chapter Contents
G10 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


G10BBF : NAG Library, Mark 26

G10 Chapter Contents
G10 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

G10BBF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

G10BBF performs kernel density estimation using a Gaussian kernel.

2 Specification

SUBROUTINE G10BBF ( N, X, WTYPE, WINDOW, SLO, SHI, NS, SMOOTH, T, FCALL, RCOMM, IFAIL)
INTEGER | N, WTYPE, NS, FCALL, IFAIL
REAL (KIND=nag_wp) | X(N), WINDOW, SLO, SHI, SMOOTH(NS), T(NS), RCOMM(NS+20)

3 Description

Given a sample of n observations, x 1,x 2,…,xn, from a distribution with unknown density function, f x, an estimate of the density function, f^x, may be required. The simplest form of density estimator is the histogram. This may be defined by:
f^ x = 1 nh nj ,   a + j-1 h < x < a + j h ,   j=1,2,…,ns ,
where nj is the number of observations falling in the interval a+j-1 h to a+jh, a is the lower bound to the histogram, b=ns h is the upper bound and ns is the total number of intervals. The value h is known as the window width. To produce a smoother density estimate a kernel method can be used. A kernel function, K t, satisfies the conditions:
∫-∞∞K t dt=1  and  K t≥0.
The kernel density estimator is then defined as
f^x=1 nh ∑i= 1 n K x-xi h .
The choice of K is usually not important but to ease the computational burden use can be made of the Gaussian kernel defined as
K t=1 2 π e-t 2/2.
The smoothness of the estimator depends on the window width h. The larger the value of h the smoother the density estimate. The value of h can be chosen by examining plots of the smoothed density for different values of h or by using cross-validation methods (see Silverman (1990)).
Silverman (1982) and Silverman (1990) show how the Gaussian kernel density estimator can be computed using a fast Fourier transform (FFT). In order to compute the kernel density estimate over the range a to b the following steps are required.
(i) | Discretize the data to give ns equally spaced points tl with weights ξl (see Jones and Lotwick (1984)).
(ii) | Compute the FFT of the weights ξl to give Yl.
(iii) | Compute ζl=e-12 h 2 sl 2 Yl where sl=2 πl/b-a.
(iv) | Find the inverse FFT of ζl to give f^x.
To compute the kernel density estimate for further values of h only steps (iii) and (iv) need be repeated.

4 References

Jones M C and Lotwick H W (1984) Remark AS R50. A remark on algorithm AS 176. Kernel density estimation using the Fast Fourier Transform Appl. Statist. 33 120–122
Silverman B W (1982) Algorithm AS 176. Kernel density estimation using the fast Fourier transform Appl. Statist. 31 93–99
Silverman B W (1990) Density Estimation Chapman and Hall

5 Arguments

1:   N – INTEGERInput
On entry: n, the number of observations in the sample.
If FCALL=0, N must be unchanged since the last call to G10BBF.
Constraint: N>0.
2:   X N – REAL (KIND=nag_wp) arrayInput
On entry: xi, for i=1,2,…,n.
If FCALL=0, X must be unchanged since the last call to G10BBF.
3:   WTYPE – INTEGERInput
On entry: how the window width, h, is to be calculated:
WTYPE=1
h is supplied in WINDOW.
WTYPE=2
h is to be calculated from the data, with
h=m× 0.9× min q 75-q 25,σ n 0.2
where q 75-q 25 is the inter-quartile range and σ the standard deviation of the sample, x, and m is a multipler supplied in WINDOW. The 25% and 75% quartiles, q 25 and q 75, are calculated using G01AMF. This is the "rule-of-thumb" suggested by Silverman (1990).
Suggested value: WTYPE=2 and WINDOW=1.0.
Constraint: WTYPE=1 or 2.
4:   WINDOW – REAL (KIND=nag_wp)Input/Output
On entry: if WTYPE=1, then h, the window width. Otherwise, m, the multiplier used in the calculation of h.
Suggested value: WINDOW=1.0 and WTYPE=2.
On exit: h, the window width actually used.
Constraint: WINDOW>0.0.
5:   SLO – REAL (KIND=nag_wp)Input/Output
On entry: if SLO<SHI then a, the lower limit of the interval on which the estimate is calculated. Otherwise, a and b, the lower and upper limits of the interval, are calculated as follows:
a = mini xi-SLO×h b = maxi xi+SLO×h
where h is the window width.
For most applications a should be at least three window widths below the lowest data point.
If FCALL=0, SLO must be unchanged since the last call to G10BBF.
Suggested value: SLO=3.0 and SHI=0.0 which would cause a and b to be set 3 window widths below and above the lowest and highest data points respectively.
On exit: a, the lower limit actually used.
6:   SHI – REAL (KIND=nag_wp)Input/Output
On entry: if SLO<SHI then b, the upper limit of the interval on which the estimate is calculated. Otherwise a value for b is calculated from the data as stated in the description of SLO and the value supplied in SHI is not used.
For most applications b should be at least three window widths above the highest data point.
If FCALL=0, SHI must be unchanged since the last call to G10BBF.
On exit: b, the upper limit actually used.
7:   NS – INTEGERInput
On entry: ns, the number of points at which the estimate is calculated.
If FCALL=0, NS must be unchanged since the last call to G10BBF.
Suggested value: NS=512.
Constraint: NS≥2.
8:   SMOOTH NS – REAL (KIND=nag_wp) arrayOutput
On exit: f^tl, for l=1,2,…,ns, the ns values of the density estimate.
9:   T NS – REAL (KIND=nag_wp) arrayOutput
On exit: tl, for l=1,2,…,ns, the points at which the estimate is calculated.
10:   FCALL – INTEGERInput
On entry: if FCALL=1 then the values of Yl are to be calculated by this call to G10BBF, otherwise it is assumed that the values of Yl were calculated by a previous call to this routine and the relevant information is stored in RCOMM.
Constraint: FCALL=0 or 1.
11:   RCOMM NS+20 – REAL (KIND=nag_wp) arrayCommunication Array
On entry: communication array, used to store information between calls to G10BBF.
If FCALL=0, RCOMM must be unchanged since the last call to G10BBF.
On exit: the last NS elements of RCOMM contain the fast Fourier transform of the weights of the discretized data, that is RCOMM l+20=Yl, for l=1,2,…,ns.
12:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, because for this routine the values of the output arguments may be useful even if IFAIL≠0 on exit, the recommended value is -1. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Note: G10BBF may return useful information for one or more of the following detected errors or warnings.
Errors or warnings detected by the routine:
IFAIL=11
On entry, N=value.
Constraint: N>0.
IFAIL=12
On entry, N=value.
On entry at previous call, N=value.
Constraint: if FCALL=0, N must be unchanged since previous call.
IFAIL=31
On entry, WTYPE=value.
Constraint: WTYPE=1 or 2.
IFAIL=41
On entry, WINDOW=value.
Constraint: WINDOW>0.0.
IFAIL=51
On entry, SLO=value.
On exit from previous call, SLO=value.
Constraint: if FCALL=0, SLO must be unchanged since previous call.
IFAIL=61
On entry, SLO=value and SHI=value.
On entry, min X=value and max X=value.
Expected values of at least value and value for SLO and SHI.
All output values have been returned.
IFAIL=62
On entry, SHI=value.
On exit from previous call, SHI=value.
Constraint: if FCALL=0, SHI must be unchanged since previous call.
IFAIL=71
On entry, NS=value.
Constraint: NS≥2.
IFAIL=74
On entry, NS=value.
On entry at previous call, NS=value.
Constraint: if FCALL=0, NS must be unchanged since previous call.
IFAIL=101
On entry, FCALL=value.
Constraint: FCALL=0 or 1.
IFAIL=111
RCOMM has been corrupted between calls.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

See Jones and Lotwick (1984) for a discussion of the accuracy of this method.

8 Parallelism and Performance

G10BBF is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
G10BBF makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The time for computing the weights of the discretized data is of order n, while the time for computing the FFT is of order ns log ns, as is the time for computing the inverse of the FFT.

10 Example

Data is read from a file and the density estimated. The first 20 values are then printed.

10.1 Program Text

Program Text (g10bbfe.f90)

10.2 Program Data

Program Data (g10bbfe.d)

10.3 Program Results

Program Results (g10bbfe.r)

This plot shows the estimated density function for the example data for several window widths.
GnuplotProduced by GNUPLOT 4.6 patchlevel 3 0 0.1 0.2 0.3 0.4 0.5 0.6 −6 −5 −4 −3 −2 −1 0 1 2 3 4 5 Density Estimate t Example Program Gaussian Kernel Density Estimation gnuplot_plot_1 window = 0.0941 gnuplot_plot_2 window = 0.1882 gnuplot_plot_3 window = 0.3764 gnuplot_plot_4 window = 0.7528
G10 Chapter Contents
G10 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


G10CAF : NAG Library, Mark 26

G10 Chapter Contents
G10 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

G10CAF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

G10CAF computes a smoothed data sequence using running median smoothers.

2 Specification

SUBROUTINE G10CAF ( ITYPE, N, Y, SMOOTH, ROUGH, IFAIL)
INTEGER | ITYPE, N, IFAIL
REAL (KIND=nag_wp) | Y(N), SMOOTH(N), ROUGH(N)

3 Description

Given a sequence of n observations recorded at equally spaced intervals, G10CAF fits a smooth curve through the data using one of two smoothers. The two smoothers are based on the use of running medians and averages to summarise overlapping segments. The fit and the residuals are called the smooth and the rough respectively. They obey the following:
Data=Smooth+Rough.
The two smoothers are:
1. | 4253H,twice consisting of a running median of 4, then 2, then 5, then 3 followed by hanning. Hanning is a running weighted average, the weights being 1/4, 1/2 and 1/4. The result of this smoothing is then reroughed by computing residuals, applying the same smoother to them and adding the result to the smooth of the first pass.
2. | 3RSSH,twice consisting of a running median of 3, two splitting operations named S to improve the smooth sequence, each of which is followed by a running median of 3, and finally hanning. The end points are dealt with using the method described by Velleman and Hoaglin (1981). The full smoother 3RSSH,twice is produced by reroughing as described above.
The compound smoother 4253H,twice is recommended. The smoother 3RSSH,twice is popular when calculating by hand as it requires simpler computations and is included for comparison purposes.

4 References

Tukey J W (1977) Exploratory Data Analysis Addison–Wesley
Velleman P F and Hoaglin D C (1981) Applications, Basics, and Computing of Exploratory Data Analysis Duxbury Press, Boston, MA

5 Arguments

1:   ITYPE – INTEGERInput
On entry: specifies the method to be used.
  • If ITYPE=0, 4253H,twice is used.
  • If ITYPE=1, 3RSSH,twice is used.
Constraint: ITYPE=0 or 1.
2:   N – INTEGERInput
On entry: n, the number of observations.
Constraint: N>6.
3:   Y N – REAL (KIND=nag_wp) arrayInput
On entry: the sample observations.
4:   SMOOTH N – REAL (KIND=nag_wp) arrayOutput
On exit: contains the smooth.
5:   ROUGH N – REAL (KIND=nag_wp) arrayOutput
On exit: contains the rough.
6:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, | ITYPE<0,
or | ITYPE>1.
IFAIL=2
On entry, N≤6.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

Not applicable.

8 Parallelism and Performance

G10CAF makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

Alternative methods of smoothing include the use of splines; see G10ABF and G10ACF.

10 Example

This example reads in a sequence of 49 observations on bituminous coal production (in millions of net tons per year) in the USA., 1920–1968 and is taken from Tukey (1977). For comparison purposes, both smoothers are applied to the data and the results are printed.

10.1 Program Text

Program Text (g10cafe.f90)

10.2 Program Data

Program Data (g10cafe.d)

10.3 Program Results

Program Results (g10cafe.r)

GnuplotProduced by GNUPLOT 4.6 patchlevel 3 300 350 400 450 500 550 600 650 0 5 10 15 20 25 30 35 40 45 50 y Observation Number Example Program Running Median Smoothers gnuplot_plot_1 Observed data gnuplot_plot_2 Smoothed using 3RSSH gnuplot_plot_3 Smoothed using 4253H
G10 Chapter Contents
G10 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


G10 Chapter Contents : NAG Library Manual, Mark 26

G10 Chapter Introduction
NAG Library Manual

NAG Library Chapter Contents

G10 – Smoothing in Statistics

G10 Chapter Introduction – a description of the Chapter and an overview of the algorithms available

Routine Name | Mark of Introduction | Purpose
G10ABF Example Text Example Data Example Plot | 16 | nagf_smooth_fit_spline Fit cubic smoothing spline, smoothing parameter given
G10ACF Example Text Example Data | 16 | nagf_smooth_fit_spline_parest Fit cubic smoothing spline, smoothing parameter estimated
G10BAF Example Text Example Data Example Plot | 16 | nagf_smooth_withdraw_kerndens_gauss Kernel density estimate using Gaussian kernel Note: this routine is scheduled for withdrawal at Mark 27, see Advice on Replacement Calls for Withdrawn/Superseded Routines for further information.
G10BBF Example Text Example Data Example Plot | 25 | nagf_smooth_kerndens_gauss Kernel density estimate using Gaussian kernel (thread safe)
G10CAF Example Text Example Data Example Plot | 16 | nagf_smooth_data_runningmedian Compute smoothed data sequence using running median smoothers
G10ZAF Example Text Example Data | 16 | nagf_smooth_data_order Reorder data to give ordered distinct observations
G10 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


G10 Chapter Introduction : NAG Library, Mark 26

G10 Chapter Contents
NAG Library Manual

NAG Library Chapter Introduction

G10 – Smoothing in Statistics

▸▿ Contents

1 Scope of the Chapter
▸▿ 2 Background to the Problems
2.1 Smoothing Methods
2.2 Smoothing Splines and Regression Models
2.3 Density Estimation
2.4 Smoothers for Time Series
3 Recommendations on Choice and Use of Available Routines
4 Functionality Index
5 Auxiliary Routines Associated with Library Routine Arguments
6 Routines Withdrawn or Scheduled for Withdrawal
7 References

1 Scope of the Chapter

This chapter is concerned with methods for smoothing data. Included are methods for density estimation, smoothing time series data, and statistical applications of splines. These methods may also be viewed as nonparametric modelling.

2 Background to the Problems

2.1 Smoothing Methods

Many of the methods used in statistics involve fitting a model, the form of which is determined by a small number of parameters, for example, a distribution model like the gamma distribution, a linear regression model or an autoregression model in time series. In these cases the fitting involves the estimation of the small number of parameters from the data. In modelling data with these models there are two important stages in addition to the estimation of the parameters; these are the identification of a suitable model, for example, the selection of a gamma distribution rather than a Weibull distribution, and the checking to see if the fitted model adequately fits the data. While these parametric models can be fairly flexible, they will not adequately fit all datasets, especially if the number of parameters is to be kept small.
Alternative models based on smoothing can be used. These models will not be written explicitly in terms of parameters. They are sufficiently flexible for a much wider range of situations than parametric models. The main requirement for such a model to be suitable is that the underlying models would be expected to be smooth, so excluding those situations where, for example, a step function would be expected.
These smoothing methods can be used in a variety of ways, for example:
1. | producing smoothed plots to aid understanding;
2. | identifying of a suitable parametric model from the shape of the smoothed data;
3. | eliminating complex effects that are not of direct interest so that attention can be focused on the effects of interest.
Several smoothing techniques make use of a smoothing parameter which can be either chosen by you or estimated from the data. The smoothing parameter balances the two criterion of smoothness of the fitted model and the closeness of the fit of the model to the data. Generally, the larger the smoothing parameter is, the smoother the fitted model will be, but for small values of the smoothing parameter the model will closely follow the data, and for large values the fit will be poorer.
The smoothing parameter can be either chosen using previous experience of a suitable value for such data, or estimated from the data. The estimation can be either formal, using a criterion such as the cross-validation, or informal by trying different values and examining the result by means of suitable graphs.
Smoothing methods can be used in three important areas of of statistics: regression modelling, distribution modelling and time series modelling.

2.2 Smoothing Splines and Regression Models

For a set of n observations (yi,xi), i=1,2,…,n, the spline provides a flexible smooth function for situations in which a simple polynomial or nonlinear regression model is not suitable.
Cubic smoothing splines arise as the function, f, with continuous first derivative which minimizes
∑i=1 n wi yi-f xi 2+ρ∫-∞∞f′′x 2 dx,
where wi is the (optional) weight for the ith observation and ρ is the smoothing parameter. This criterion consists of two parts: the first measures the fit of the curve and the second the smoothness of the curve. The value of the smoothing parameter, ρ, weights these two aspects: larger values of ρ give a smoother fitted curve but, in general, a poorer fit.
Splines are linear smoothers since the fitted values, y^ = y^1,y^2,…,y^n T , can be written as a linear function of the observed values y = y 1,y 2,…,yn T , that is,
y^=Hy
for a matrix H. The degrees of freedom for the spline is trace H giving residual degrees of freedom
trace I-H=∑i=1 n 1-h ii.
The diagonal elements of H, h ii, are the leverages.
The parameter ρ can be estimated in a number of ways.
1. The degrees of freedom for the spline can be specified, i.e., find ρ such that trace H=ν 0 for given ν 0.
2. Minimize the cross-validation (CV), i.e., find ρ such that the CV is minimized, where
CV=1 n∑i=1 n ri 1-h ii 2.
3. Minimize generalized cross-validation (GCV), i.e., find ρ such that the GCV is minimized, where
GCV=n ∑i=1 n ri 2 ∑i=1 n 1-h ii 2 .

2.3 Density Estimation

The object of density estimation is to produce from a set of observations a smooth nonparametric estimate of the unknown density function from which the observations were drawn. That is, given a sample of n observations, x 1, x 2,…,xn, from a distribution with unknown density function, f x, find an estimate of the density function, f^x. The simplest form of density estimator is the histogram; this may be defined by
f^x=1 nh nj;  a+j-1 h<x<a+jh;  j=1,2,…,ns,
where nj is the number of observations falling in the interval a+j-1 h to a+jh, a is the lower bound of the histogram and b=ns h is the upper bound. The value h is known as the window width. A simple development of this estimator would be the running histogram estimator
f^x=1 2 nh nx;  a≤x≤b,
where nx is the number of observations falling in the interval x-h:x+h. This estimator can be written as
f^x=1 nh ∑i=1 n w x-xi h
for a function w where
w x =12 if-1<x<1 =0 otherwise.
The function w can be considered as a kernel function. To produce a smoother density estimate, the kernel function, K t, which satisfies the following conditions can be used:
∫-∞∞K t dt=1 and ​K t≥0.0.
The kernel density estimator is therefore defined as
f^x=1 nh ∑i= 1 n K x-xi h .
The choice of K(·) is usually not important, but to ease the computational burden use can be made of the Gaussian kernel defined as
K t=1 2 π e-t 2/2.
The smoothness of the estimator, f^x, depends on the window width, h. In general, the larger the value h is, the smoother the resulting density estimate is. There is, however, the problem of oversmoothing when the value of h is too large and essential features of the distribution function are removed. For example, if the distribution was bimodal, a large value of h may result in a unimodal estimate. The value of h has to be chosen such that the essential shape of the distribution is retained while effects due only to the observed sample are smoothed out. The choice of h can be aided by looking at plots of the density estimate for different values of h, or by using cross-validation methods; see Silverman (1990).
Silverman (1990) shows how the Gaussian kernel density estimator can be computed using a fast Fourier transform (FFT).

2.4 Smoothers for Time Series

If the data consists of a sequence of n observations recorded at equally spaced intervals, usually a time series, several robust smoothers are available. The fitted curve is intended to be robust to any outlying observations in the sequence, hence the techniques employed primarily make use of medians rather than means. These ideas come from the field of exploratory data analysis (EDA); see Tukey (1977) and Velleman and Hoaglin (1981). The smoothers are based on the use of running medians to summarise overlapping segments; these provide a simple but flexible curve.
In EDA terminology, the fitted curve and the residuals are called the smooth and the rough respectively, so that
Data=Smooth+Rough.
Using the notation of Tukey, one of the smoothers commonly used is 4253H,twice. This consists of a running median of 4, then 2, then 5, then 3. This is then followed by what is known as hanning. Hanning is a running weighted mean, the weights being 1/4, 1/2 and 1/4. The result of this smoothing is then ‘reroughed’. This involves computing residuals from the computed fit, applying the same smoother to the residuals and adding the result to the smooth of the first pass.

3 Recommendations on Choice and Use of Available Routines

The following routines fit smoothing splines:
  • G10ABF computes a cubic smoothing spline for a given value of the smoothing parameter. The results returned include the values of leverages and the coefficients of the cubic spline. Options allow only parts of the computation to be performed when the routine is used to estimate the value of the smoothing parameter or as when it is part of an iterative procedure such as that used in fitting generalized additive models; see Hastie and Tibshirani (1990).
  • G10ACF estimates the value of the smoothing parameter using one of three criteria and fits the cubic smoothing spline using that value.
G10ABF and G10ACF require the xi to be strictly increasing. If two or more observations have the same xi-value then they should be replaced by a single observation with yi equal to the (weighted) mean of the y values and weight, wi, equal to the sum of the weights. This operation can be performed by G10ZAF.
The following routine produces an estimate of the density function:
  • G10BBF computes a density estimate using a Normal kernel.
The following routine produces a smoothed estimate for a time series:
  • G10CAF computes a smoothed series using running median smoothers.
The following service routine is also available:
  • G10ZAF orders and weights the x,y input data to produce a dataset strictly monotonic in x.

4 Functionality Index

Compute smoothed data sequence,
running median smoothers G10CAF
Fit cubic smoothing spline,
smoothing parameter estimated G10ACF
smoothing parameter given G10ABF
Kernel density estimation,
Gaussian kernel, thread safe G10BBF
Reorder data to give ordered distinct observations G10ZAF

5 Auxiliary Routines Associated with Library Routine Arguments

None.

6 Routines Withdrawn or Scheduled for Withdrawal

The following lists all those routines that have been withdrawn since Mark 19 of the Library or are scheduled for withdrawal at one of the next two marks.
Withdrawn Routine | Mark of Withdrawal | Replacement Routine(s)
G10BAF | 27 | G10BBF

7 References

Hastie T J and Tibshirani R J (1990) Generalized Additive Models Chapman and Hall
Silverman B W (1990) Density Estimation Chapman and Hall
Tukey J W (1977) Exploratory Data Analysis Addison–Wesley
Velleman P F and Hoaglin D C (1981) Applications, Basics, and Computing of Exploratory Data Analysis Duxbury Press, Boston, MA
G10 Chapter Contents
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


G10ZAF : NAG Library, Mark 26

G10 Chapter Contents
G10 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

G10ZAF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

G10ZAF orders and weights data which is entered unsequentially, weighted or unweighted.

2 Specification

SUBROUTINE G10ZAF ( WEIGHT, N, X, Y, WT, NORD, XORD, YORD, WTORD, RSS, IWRK, IFAIL)
INTEGER | N, NORD, IWRK(N), IFAIL
REAL (KIND=nag_wp) | X(N), Y(N), WT(*), XORD(N), YORD(N), WTORD(N), RSS
CHARACTER(1) | WEIGHT

3 Description

Given a set of observations xi,yi, for i=1,2,…,n, with corresponding weights wi, G10ZAF rearranges the observations so that the xi are in ascending order.
For any equal xi in the ordered set, say xj=x j+1=⋯=x j+k, a single observation xj is returned with a corresponding y′ and w′, calculated as
w′=∑l=0 k w i+l
and
y′=∑l= 0 k w i+ly i+l w′ .
Observations with zero weight are ignored. If no weights are supplied by you, then unit weights are assumed; that is wi=1, for i=1,2,…,n.
In addition, the within group sum of squares is computed for the tied observations using West's algorithm (see West (1979)).

4 References

Draper N R and Smith H (1985) Applied Regression Analysis (2nd Edition) Wiley
West D H D (1979) Updating mean and variance estimates: An improved method Comm. ACM 22 532–555

5 Arguments

1:   WEIGHT – CHARACTER(1)Input
On entry: indicates whether user-defined weights are to be used.
  • If WEIGHT='W', user-defined weights are to be used and must be supplied in WT.
  • If WEIGHT='U', the data is treated as unweighted.
Constraint: WEIGHT='W' or 'U'.
2:   N – INTEGERInput
On entry: n, the number of observations.
Constraint: N≥1.
3:   X N – REAL (KIND=nag_wp) arrayInput
On entry: the values, xi, for i=1,2,…,n.
4:   Y N – REAL (KIND=nag_wp) arrayInput
On entry: the values yi, for i=1,2,…,n.
5:   WT* – REAL (KIND=nag_wp) arrayInput
Note: the dimension of the array WT must be at least N if WEIGHT='W'.
On entry: if WEIGHT='W', WT must contain the n weights. Otherwise WT is not referenced and unit weights are assumed.
Constraints:
  • if WEIGHT='W', WT i>0.0, for i=1,2,…,n;
  • if WEIGHT='W', ∑i=1 n WT i>0.
6:   NORD – INTEGEROutput
On exit: the number of distinct observations.
7:   XORD N – REAL (KIND=nag_wp) arrayOutput
On exit: the first NORD elements contain the ordered and distinct xi.
8:   YORD N – REAL (KIND=nag_wp) arrayOutput
On exit: the first NORD elements contain the values y′ corresponding to the values in XORD.
9:   WTORD N – REAL (KIND=nag_wp) arrayOutput
On exit: the first NORD elements contain the values w′ corresponding to the values of XORD and YORD.
10:   RSS – REAL (KIND=nag_wp)Output
On exit: the within group sum of squares for tied observations.
11:   IWRK N – INTEGER arrayWorkspace
12:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, | WEIGHT≠'W' or 'U',
or | N<1.
IFAIL=2
On entry, WEIGHT='W' and at least one element of WT is <0.0, or all elements of WT are 0.0.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

For a discussion on the accuracy of the algorithm for computing mean and variance see West (1979).

8 Parallelism and Performance

G10ZAF is not threaded in any implementation.

9 Further Comments

G10ZAF may be used to compute the pure error sum of squares in simple linear regression along with G02DAF; see Draper and Smith (1985).

10 Example

A set of unweighted observations are input and G10ZAF used to produce a set of strictly increasing weighted observations.

10.1 Program Text

Program Text (g10zafe.f90)

10.2 Program Data

Program Data (g10zafe.d)

10.3 Program Results

Program Results (g10zafe.r)

G10 Chapter Contents
G10 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


G11AAF : NAG Library, Mark 26

G11 Chapter Contents
G11 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

G11AAF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

G11AAF computes χ 2 statistics for a two-way contingency table. For a 2×2 table with a small number of observations exact probabilities are computed.

2 Specification

SUBROUTINE G11AAF ( NROW, NCOL, NOBS, LDNOBS, EXPT, CHIST, PROB, CHI, G, DF, IFAIL)
INTEGER | NROW, NCOL, NOBS(LDNOBS,NCOL), LDNOBS, IFAIL
REAL (KIND=nag_wp) | EXPT(LDNOBS,NCOL), CHIST(LDNOBS,NCOL), PROB, CHI, G, DF

3 Description

For a set of n observations classified by two variables, with r and c levels respectively, a two-way table of frequencies with r rows and c columns can be computed.
n 11 n 12 … n 1 c n 1. n 21 n 22 … n 2 c n 2. ⋮ ⋮ ⋮ ⋮ ⋮ n r 1 n r 2 … n rc n r. n.1 n.2 … n.c n
To measure the association between the two classification variables two statistics that can be used are, the Pearson χ 2 statistic, ∑i=1 r∑j=1 c n ij-f ij 2 f ij , and the likelihood ratio test statistic, 2∑i=1 r∑j=1 c n ij×log n ij/f ij, where f ij are the fitted values from the model that assumes the effects due to the classification variables are additive, i.e., there is no association. These values are the expected cell frequencies and are given by
f ij=n i.n.j/n.
Under the hypothesis of no association between the two classification variables, both these statistics have, approximately, a χ 2-distribution with c-1r-1 degrees of freedom. This distribution is arrived at under the assumption that the expected cell frequencies, f ij, are not too small. For a discussion of this point see Everitt (1977). He concludes by saying, ‘... in the majority of cases the chi-square criterion may be used for tables with expectations in excess of 0.5 in the smallest cell’.
In the case of the 2×2 table, i.e., c=2 and r=2, the χ 2 approximation can be improved by using Yates' continuity correction factor. This decreases the absolute value of n ij-f ij by 12 . For 2×2 tables with a small value of n the exact probabilities from Fisher's test are computed. These are based on the hypergeometric distribution and are computed using G01BLF. A two tail probability is computed as min 1,2 pu,2 pl , where pu and pl are the upper and lower one-tail probabilities from the hypergeometric distribution.

4 References

Everitt B S (1977) The Analysis of Contingency Tables Chapman and Hall
Kendall M G and Stuart A (1973) The Advanced Theory of Statistics (Volume 2) (3rd Edition) Griffin

5 Arguments

1:   NROW – INTEGERInput
On entry: r, the number of rows in the contingency table.
Constraint: NROW≥2.
2:   NCOL – INTEGERInput
On entry: c, the number of columns in the contingency table.
Constraint: NCOL≥2.
3:   NOBS LDNOBSNCOL – INTEGER arrayInput
On entry: the contingency table NOBS ij must contain n ij, for i=1,2,…,r and j=1,2,…,c.
Constraint: NOBS ij≥0, for i=1,2,…,r and j=1,2,…,c.
4:   LDNOBS – INTEGERInput
On entry: the first dimension of the arrays NOBS, EXPT and CHIST as declared in the (sub)program from which G11AAF is called.
Constraint: LDNOBS≥NROW.
5:   EXPT LDNOBSNCOL – REAL (KIND=nag_wp) arrayOutput
On exit: the table of expected values. EXPT ij contains f ij, for i=1,2,…,r and j=1,2,…,c.
6:   CHIST LDNOBSNCOL – REAL (KIND=nag_wp) arrayOutput
On exit: the table of χ 2 contributions. CHIST ij contains n ij-f ij 2 f ij , for i=1,2,…,r and j=1,2,…,c.
7:   PROB – REAL (KIND=nag_wp)Output
On exit: if c=2, r=2 and n≤40 then PROB contains the two tail significance level for Fisher's exact test, otherwise PROB contains the significance level from the Pearson χ 2 statistic.
8:   CHI – REAL (KIND=nag_wp)Output
On exit: the Pearson χ 2 statistic.
9:   G – REAL (KIND=nag_wp)Output
On exit: the likelihood ratio test statistic.
10:   DF – REAL (KIND=nag_wp)Output
On exit: the degrees of freedom for the statistics.
11:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, because for this routine the values of the output arguments may be useful even if IFAIL≠0 on exit, the recommended value is -1. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Note: G11AAF may return useful information for one or more of the following detected errors or warnings.
Errors or warnings detected by the routine:
IFAIL=1
On entry, | NROW<2,
or | NCOL<2,
or | LDNOBS<NROW.
IFAIL=2
On entry, a value in NOBS<0, or all values in NOBS are zero.
IFAIL=3
On entry, a 2×2 table has a row or column with both values 0.
IFAIL=4
At least one cell has expected frequency, f ij, ≤0.5. The χ 2 approximation may be poor.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

For the accuracy of the probabilities for Fisher's exact test see G01BLF.

8 Parallelism and Performance

G11AAF is not threaded in any implementation.

9 Further Comments

The routine G01AFF allows for the automatic amalgamation of rows and columns. In most circumstances this is not recommended; see Everitt (1977).
Multidimensional contingency tables can be analysed using log-linear models fitted by G02GBF.

10 Example

The data below, taken from Everitt (1977), is from 141 patients with brain tumours. The row classification variable is the site of the tumour: frontal lobes, temporal lobes and other cerebral areas. The column classification variable is the type of tumour: benign, malignant and other cerebral tumours.
23 9 6 38 21 4 3 28 34 24 17 75 78 37 26 141
The data is read in and the statistics computed and printed.

10.1 Program Text

Program Text (g11aafe.f90)

10.2 Program Data

Program Data (g11aafe.d)

10.3 Program Results

Program Results (g11aafe.r)

G11 Chapter Contents
G11 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


G11BAF : NAG Library, Mark 26

G11 Chapter Contents
G11 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

G11BAF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

G11BAF computes a table from a set of classification factors using a selected statistic.

2 Specification

SUBROUTINE G11BAF ( STAT, UPDATE, WEIGHT, N, NFAC, ISF, LFAC, IFAC, LDF, Y, WT, TABLE, MAXT, NCELLS, NDIM, IDIM, ICOUNT, AUXT, IWK, IFAIL)
INTEGER | N, NFAC, ISF(NFAC), LFAC(NFAC), IFAC(LDF,NFAC), LDF, MAXT, NCELLS, NDIM, IDIM(NFAC), ICOUNT(MAXT), IWK(2*NFAC), IFAIL
REAL (KIND=nag_wp) | Y(N), WT(*), TABLE(MAXT), AUXT(*)
CHARACTER(1) | STAT, UPDATE, WEIGHT

3 Description

A dataset may include both classification variables and general variables. The classification variables, known as factors, take a small number of values known as levels. For example, the factor sex would have the levels male and female. These can be coded as 1 and 2 respectively. Given several factors, a multi-way table can be constructed such that each cell of the table represents one level from each factor. For example, the two factors sex and habitat, habitat having three levels (inner-city, suburban and rural) define the 2×3 contingency table
Sex | Habitat
 | Inner-city | Suburban | Rural
Male |  |  |
Female |  |  |
For each cell statistics can be computed. If a third variable in the dataset was age, then for each cell the average age could be computed:
Sex | Habitat
 | Inner-city | Suburban | Rural
Male | 25.5 | 30.3 | 35.6
Female | 23.2 | 29.1 | 30.4
That is the average age for all observations for males living in rural areas is 35.6. Other statistics can also be computed: the number of observations, the total, the variance, the largest value and the smallest value.
G11BAF computes a table for one of the selected statistics. The factors have to be coded with levels 1,2,…. Weights can be used to eliminate values from the calculations, e.g., if they represent ‘missing values’. There is also the facility to update an existing table with the addition of new observations.

4 References

John J A and Quenouille M H (1977) Experiments: Design and Analysis Griffin
Kendall M G and Stuart A (1969) The Advanced Theory of Statistics (Volume 1) (3rd Edition) Griffin
West D H D (1979) Updating mean and variance estimates: An improved method Comm. ACM 22 532–555

5 Arguments

1:   STAT – CHARACTER(1)Input
On entry: indicates which statistic is to be computed for the table cells.
STAT='N'
The number of observations for each cell.
STAT='T'
The total for the variable in Y for each cell.
STAT='A'
The average (mean) for the variable in Y for each cell.
STAT='V'
The variance for the variable in Y for each cell.
STAT='L'
The largest value for the variable in Y for each cell.
STAT='S'
The smallest value for the variable in Y for each cell.
Constraint: STAT='N', 'T', 'A', 'V', 'L' or 'S'.
2:   UPDATE – CHARACTER(1)Input
On entry: indicates if an existing table is to be updated by further observation.
UPDATE='I'
The table cells will be initialized to zero before tabulations take place.
UPDATE='U'
The table input in TABLE will be updated. The arguments NCELLS, TABLE, ICOUNT and AUXT must remain unchanged from the previous call to G11BAF.
Constraint: UPDATE='I' or 'U'.
3:   WEIGHT – CHARACTER(1)Input
On entry: indicates if weights are to be used.
WEIGHT='U'
Weights are not used and unit weights are assumed.
WEIGHT='W' or 'V'
Weights are used and must be supplied in WT. The only difference between WEIGHT='W' and WEIGHT='V' is if the variance is computed.
WEIGHT='W'
The divisor for the variance is the sum of the weights minus one and if WEIGHT='V', the divisor is the number of observations with nonzero weights minus one. The former is useful if the weights represent the frequency of the observed values.
If STAT='T' or 'A', the weighted total or mean is computed respectively.
If STAT='N', 'L' or 'S', the only effect of weights is to eliminate values with zero weights from the computations.
Constraint: WEIGHT='U', 'V' or 'W'.
4:   N – INTEGERInput
On entry: the number of observations.
Constraint: N≥2.
5:   NFAC – INTEGERInput
On entry: the number of classifying factors in IFAC.
Constraint: NFAC≥1.
6:   ISF NFAC – INTEGER arrayInput
On entry: indicates which factors in IFAC are to be used in the tabulation.
If ISF i>0 the ith factor in IFAC is included in the tabulation.
Note that if ISF i≤0, for i=1,2,…,NFAC then the statistic for the whole sample is calculated and returned in a 1×1 table.
7:   LFAC NFAC – INTEGER arrayInput
On entry: the number of levels of the classifying factors in IFAC.
Constraint: if ISF i>0, LFAC i≥2, for i=Ai,…,Ai.
8:   IFAC LDFNFAC – INTEGER arrayInput
On entry: the NFAC coded classification factors for the N observations.
Constraint: 1≤IFAC ij≤LFAC j, for i=1,2,…,N and j=1,2,…,NFAC.
9:   LDF – INTEGERInput
On entry: the first dimension of the array IFAC as declared in the (sub)program from which G11BAF is called.
Constraint: LDF≥N.
10:   Y N – REAL (KIND=nag_wp) arrayInput
On entry: the variable to be tabulated. If STAT='N', Y is not referenced.
11:   WT* – REAL (KIND=nag_wp) arrayInput
Note: the dimension of the array WT must be at least N if WEIGHT='W' or 'V', and at least 1 otherwise.
On entry: if WEIGHT='W' or 'V', WT must contain the N weights. Otherwise WT is not referenced.
Constraint: if WEIGHT='W' or 'V', WT i≥0.0, for i=Ai,…,Ai.
12:   TABLE MAXT – REAL (KIND=nag_wp) arrayInput/Output
On entry: if UPDATE='U', TABLE must be unchanged from the previous call to G11BAF, otherwise TABLE need not be set.
On exit: the computed table. The NCELLS cells of the table are stored so that for any two factors the index relating to the factor referred to later in LFAC and IFAC changes faster. For further details see Section 9.
13:   MAXT – INTEGERInput
On entry: the maximum size of the table to be computed.
Constraint: MAXT≥ product of the levels of the factors included in the tabulation.
14:   NCELLS – INTEGERInput/Output
On entry: if UPDATE='U', NCELLS must be unchanged from the previous call to G11BAF, otherwise NCELLS need not be set.
On exit: the number of cells in the table.
15:   NDIM – INTEGEROutput
On exit: the number of factors defining the table.
16:   IDIM NFAC – INTEGER arrayOutput
On exit: the first NDIM elements contain the number of levels for the factors defining the table.
17:   ICOUNT MAXT – INTEGER arrayInput/Output
On entry: if UPDATE='U', ICOUNT must be unchanged from the previous call to G11BAF, otherwise ICOUNT need not be set.
On exit: a table containing the number of observations contributing to each cell of the table, stored identically to TABLE. Note if STAT='N' this is the same as is returned in TABLE.
18:   AUXT* – REAL (KIND=nag_wp) arrayInput/Output
Note: the dimension of the array AUXT must be at least NCELLS if STAT='A', 2×NCELLS if STAT='V', and at least 1 otherwise.
On entry: if UPDATE='U', AUXT must be unchanged from the previous call to G11BAF, otherwise AUXT need not be set.
On exit: if STAT='A' or 'V', the first NCELLS values hold the table containing the sum of the weights for the observations contributing to each cell, stored identically to TABLE.
If STAT='V', the second set of NCELLS values hold the table of cell means. Otherwise AUXT is not referenced.
19:   IWK 2×NFAC – INTEGER arrayWorkspace
20:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, | N<2,
or | NFAC<1,
or | LDF<N,
or | UPDATE≠'I' or 'U',
or | WEIGHT≠'U', 'W' or 'V',
or | STAT≠'N', 'T', 'A', 'V', 'L' or 'S'.
IFAIL=2
On entry, | ISF i>0 and LFAC i<2, for some i,
or | IFAC ij<1, for some i,j,
or | IFAC ij>LFAC j for some i,j,
or | MAXT is too small,
or | WEIGHT='W' or 'V' and WT i<0.0, for some i.
IFAIL=3
STAT='V' and the divisor for the variance is ≤0.0.
IFAIL=4
UPDATE='U' and at least one of NCELLS, TABLE, AUXT or ICOUNT have been changed since previous call to G11BAF.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

Only applicable when STAT='V'. In this case a one pass algorithm is used as described by West (1979).

8 Parallelism and Performance

G11BAF is not threaded in any implementation.

9 Further Comments

The tables created by G11BAF and stored in TABLE, ICOUNT and, depending on STAT, also in AUXT are stored in the following way. Let there be n factors defining the table with factor k having lk levels, then the cell defined by the levels i 1, i 2,…,in of the factors is stored in the mth cell given by
m=1+∑k=1 n ik-1 ck,
where cj=∏k=j+1 n lk, for j=1,2,…,n-1 and cn=1.

10 Example

The data, given by John and Quenouille (1977), is for a 3×6 factorial experiment in 3 blocks of 18 units. The data is input in the order, blocks, factor with 3 levels, factor with 6 levels, yield. The 3×6 table of treatment means for yield over blocks is computed and printed.

10.1 Program Text

Program Text (g11bafe.f90)

10.2 Program Data

Program Data (g11bafe.d)

10.3 Program Results

Program Results (g11bafe.r)

G11 Chapter Contents
G11 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


G11BBF : NAG Library, Mark 26

G11 Chapter Contents
G11 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

G11BBF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

G11BBF computes a table from a set of classification factors using a given percentile or quantile, for example the median.

2 Specification

SUBROUTINE G11BBF ( TYP, WEIGHT, N, NFAC, ISF, LFAC, IFAC, LDF, PERCNT, Y, WT, TABLE, MAXT, NCELLS, NDIM, IDIM, ICOUNT, IWK, WK, IFAIL)
INTEGER | N, NFAC, ISF(NFAC), LFAC(NFAC), IFAC(LDF,NFAC), LDF, MAXT, NCELLS, NDIM, IDIM(NFAC), ICOUNT(MAXT), IWK(2*NFAC+N), IFAIL
REAL (KIND=nag_wp) | PERCNT, Y(N), WT(*), TABLE(MAXT), WK(2*N)
CHARACTER(1) | TYP, WEIGHT

3 Description

A dataset may include both classification variables and general variables. The classification variables, known as factors, take a small number of values known as levels. For example, the factor sex would have the levels male and female. These can be coded as 1 and 2 respectively. Given several factors, a multi-way table can be constructed such that each cell of the table represents one level from each factor. For example, the two factors sex and habitat, habitat having three levels (inner-city, suburban and rural) define the 2×3 contingency table
Sex | Habitat
 | Inner-city | Suburban | Rural
Male |  |  |
Female |  |  |
For each cell statistics can be computed. If a third variable in the dataset was age then for each cell the median age could be computed:
Sex | Habitat
 | Inner-city | Suburban | Rural
Male | 24 | 31 | 37
Female | 21.5 | 28.5 | 33
That is, the median age for all observations for males living in rural areas is 37, the median being the 50% quantile. Other quantiles can also be computed: the p percent quantile or percentile, qp, is the estimate of the value such that p percent of observations are less than qp. This is calculated in two different ways depending on whether the tabulated variable is continuous or discrete. Let there be m values in a cell and let y 1, y 2,…,y m be the values for that cell sorted into ascending order. Also, associated with each value there is a weight, w 1, w 2,…, w m, which could represent the observed frequency for that value, with Wj=∑i=1 j w i and Wj′=∑i=1 j w i-12 w j. For the p percentile let pw=p/100 Wm and pw′=p/100 Wm′, then the percentiles for the two cases are as given below.
If the variable is discrete, that is, it takes only a limited number of (usually integer) values, then the percentile is defined as
y j if ​W j-1<pW<Wj y j+1+y j 2 if ​pw=Wj.
If the data is continuous then the quantiles are estimated by linear interpolation.
y 1 if ​ pw′≤W 1′ 1-f y j- 1+f y j if ​ W j- 1′<pw′≤Wj′ y m if ​ pw′>Wm′,
where f=pw′-W j-1′/Wj′-W j-1′.

4 References

John J A and Quenouille M H (1977) Experiments: Design and Analysis Griffin
Kendall M G and Stuart A (1969) The Advanced Theory of Statistics (Volume 1) (3rd Edition) Griffin

5 Arguments

1:   TYP – CHARACTER(1)Input
On entry: indicates if the variable to be tabulated is discrete or continuous.
TYP='D'
The percentiles are computed for a discrete variable.
TYP='C'
The percentiles are computed for a continuous variable using linear interpolation.
Constraint: TYP='D' or 'C'.
2:   WEIGHT – CHARACTER(1)Input
On entry: indicates if there are weights associated with the variable to be tabulated.
WEIGHT='U'
Weights are not input and unit weights are assumed.
WEIGHT='W'
Weights must be supplied in WT.
Constraint: WEIGHT='U' or 'W'.
3:   N – INTEGERInput
On entry: the number of observations.
Constraint: N≥2.
4:   NFAC – INTEGERInput
On entry: the number of classifying factors in IFAC.
Constraint: NFAC≥1.
5:   ISF NFAC – INTEGER arrayInput
On entry: indicates which factors in IFAC are to be used in the tabulation.
If ISF i>0 the ith factor in IFAC is included in the tabulation.
Note that if ISF i≤0, for i=1,2,…,NFAC then the statistic for the whole sample is calculated and returned in a 1×1 table.
6:   LFAC NFAC – INTEGER arrayInput
On entry: the number of levels of the classifying factors in IFAC.
Constraint: if ISF i>0, LFAC i≥2, for i=1,2,…,NFAC.
7:   IFAC LDFNFAC – INTEGER arrayInput
On entry: the NFAC coded classification factors for the N observations.
Constraint: 1≤IFAC ij≤LFAC j, for i=1,2,…,N and j=1,2,…,NFAC.
8:   LDF – INTEGERInput
On entry: the first dimension of the array IFAC as declared in the (sub)program from which G11BBF is called.
Constraint: LDF≥N.
9:   PERCNT – REAL (KIND=nag_wp)Input
On entry: p, the percentile to be tabulated.
Constraint: 0.0<p<100.0.
10:   Y N – REAL (KIND=nag_wp) arrayInput
On entry: the variable to be tabulated.
11:   WT* – REAL (KIND=nag_wp) arrayInput
Note: the dimension of the array WT must be at least N if WEIGHT='W', and at least 1 otherwise.
On entry: if WEIGHT='W', WT must contain the N weights. Otherwise WT is not referenced.
Constraint: if WEIGHT='W', WT i≥0.0, for i=1,2,…,N.
12:   TABLE MAXT – REAL (KIND=nag_wp) arrayOutput
On exit: the computed table. The NCELLS cells of the table are stored so that for any two factors the index relating to the factor occurring later in LFAC and IFAC changes faster. For further details see Section 9.
13:   MAXT – INTEGERInput
On entry: the maximum size of the table to be computed.
Constraint: MAXT≥ product of the levels of the factors included in the tabulation.
14:   NCELLS – INTEGEROutput
On exit: the number of cells in the table.
15:   NDIM – INTEGEROutput
On exit: the number of factors defining the table.
16:   IDIM NFAC – INTEGER arrayOutput
On exit: the first NDIM elements contain the number of levels for the factors defining the table.
17:   ICOUNT MAXT – INTEGER arrayOutput
On exit: a table containing the number of observations contributing to each cell of the table, stored identically to TABLE.
18:   IWK 2×NFAC+N – INTEGER arrayWorkspace
19:   WK 2×N – REAL (KIND=nag_wp) arrayWorkspace
20:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, | N<2,
or | NFAC<1,
or | LDF<N,
or | TYP≠'D' or 'C',
or | WEIGHT≠'U' or 'W',
or | PERCNT≤0.0,
or | PERCNT≥100.0.
IFAIL=2
On entry, | ISF i>0 and LFAC i≤1, for some i,
or | IFAC ij<1, for some i,j,
or | IFAC ij>LFAC j, for some i,j,
or | MAXT is too small,
or | WEIGHT='W' and WT i<0.0, for some i.
IFAIL=3
At least one cell is empty.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

Not applicable.

8 Parallelism and Performance

G11BBF is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The tables created by G11BBF and stored in TABLE and ICOUNT are stored in the following way. Let there be n factors defining the table with factor k having lk levels, then the cell defined by the levels i 1, i 2,…,in of the factors is stored in the mth cell given by:
m=1+∑k=1 n ik-1 ck,
where cj=∏k=j+1 n lk, for j=1,2,…,n-1 and cn=1.

10 Example

The data, given by John and Quenouille (1977), is for a 3×6 factorial experiment in 3 blocks of 18 units. The data is input in the order, blocks, factor with 3 levels, factor with 6 levels, yield, and the 3×6 table of treatment medians for yield over blocks is computed and printed.

10.1 Program Text

Program Text (g11bbfe.f90)

10.2 Program Data

Program Data (g11bbfe.d)

10.3 Program Results

Program Results (g11bbfe.r)

G11 Chapter Contents
G11 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


G11BCF : NAG Library, Mark 26

G11 Chapter Contents
G11 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

G11BCF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

G11BCF computes a marginal table from a table computed by G11BAF or G11BBF using a selected statistic.

2 Specification

SUBROUTINE G11BCF ( STAT, TABLE, NCELLS, NDIM, IDIM, ISDIM, STABLE, MAXST, MCELLS, MDIM, MLEVEL, AUXT, IWK, WK, IFAIL)
INTEGER | NCELLS, NDIM, IDIM(NDIM), ISDIM(NDIM), MAXST, MCELLS, MDIM, MLEVEL(NDIM), IWK(3*NDIM), IFAIL
REAL (KIND=nag_wp) | TABLE(NCELLS), STABLE(MAXST), AUXT(*), WK(NCELLS)
CHARACTER(1) | STAT

3 Description

For a dataset containing classification variables (known as factors) the routines G11BAF and G11BBF compute a table using selected statistics, for example the mean or the median. The table is indexed by the levels of the selected factors, for example if there were three factors A, B and C with 3, 2 and 4 levels respectively and the mean was to be tabulated the resulting table would be 3×2×4 with each cell being the mean of all observations with the appropriate combination of levels of the three factors. In further analysis the table of means averaged over C for A and B may be required; this can be computed from the full table by taking the mean over the third dimension of the table, C.
In general, given a table computed by G11BAF or G11BBF, G11BCF computes a sub-table defined by a subset of the factors used to define the table such that each cell of the sub-table is the selected statistic computed over the remaining factors. The statistics that can be used are the total, the mean, the median, the variance, the smallest and the largest value.

4 References

John J A and Quenouille M H (1977) Experiments: Design and Analysis Griffin
Kendall M G and Stuart A (1969) The Advanced Theory of Statistics (Volume 1) (3rd Edition) Griffin
West D H D (1979) Updating mean and variance estimates: An improved method Comm. ACM 22 532–555

5 Arguments

1:   STAT – CHARACTER(1)Input
On entry: indicates which statistic is to be used to compute the marginal table.
STAT='T'
The total.
STAT='A'
The average or mean.
STAT='M'
The median.
STAT='V'
The variance.
STAT='L'
The largest value.
STAT='S'
The smallest value.
Constraint: STAT='T', 'A', 'M', 'V', 'L' or 'S'.
2:   TABLE NCELLS – REAL (KIND=nag_wp) arrayInput
On entry: the table as computed by G11BAF or G11BBF.
3:   NCELLS – INTEGERInput
On entry: the number of cells in TABLE as returned by G11BAF or G11BBF.
4:   NDIM – INTEGERInput
On entry: the number of dimensions for TABLE as returned by G11BAF or G11BBF.
Constraint: NDIM≥2.
5:   IDIM NDIM – INTEGER arrayInput
On entry: the number of levels for each dimension of TABLE as returned by G11BAF or G11BBF.
Constraint: IDIM i≥2, for i=1,2,…,NDIM.
6:   ISDIM NDIM – INTEGER arrayInput
On entry: indicates which dimensions of TABLE are to be included in the sub-table. If ISDIM i>0 the dimension or factor indicated by IDIM i is to be included in the sub-table, otherwise it is excluded.
7:   STABLE MAXST – REAL (KIND=nag_wp) arrayOutput
On exit: the first MCELLS elements contain the sub-table computed using the statistic indicated by STAT. The table is stored in a similar way to TABLE with the MCELLS cells stored so that for any two dimensions the index relating to the dimension given later in IDIM changes faster. For further details see Section 9.
8:   MAXST – INTEGERInput
On entry: the maximum size of sub-table to be computed.
Constraint: MAXST≥ the product of the levels of the dimensions of TABLE included in the sub-table, STABLE.
9:   MCELLS – INTEGEROutput
On exit: the number of cells in the sub-table in STABLE.
10:   MDIM – INTEGEROutput
On exit: the number of dimensions to the sub-table in STABLE.
11:   MLEVEL NDIM – INTEGER arrayOutput
On exit: the first MDIM elements contain the number of levels for the dimensions of the sub-table in STABLE. The remaining elements are not referenced.
12:   AUXT* – REAL (KIND=nag_wp) arrayOutput
Note: the dimension of the array AUXT must be at least MAXST if STAT='V', and at least 1 otherwise.
On exit: if STAT='V' AUXT contains the sub-table of means corresponding to the sub-table of variances in STABLE. Otherwise AUXT is not referenced.
13:   IWK 3×NDIM – INTEGER arrayWorkspace
14:   WK NCELLS – REAL (KIND=nag_wp) arrayWorkspace
15:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, | NDIM<2,
or | STAT≠'T', 'A', 'M', 'V', 'L' or 'S'.
IFAIL=2
On entry, | IDIM i≤1, for some i=1,2,…,NDIM,
or | NCELLS is incompatible with IDIM,
or | the requested sub-table is of dimension 0,
or | the requested sub-table is the full table,
or | MAXST is too small, the minimum value is returned in MDIM.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

Only applicable when STAT='V'. In this case a one pass algorithm is used as describe in West (1979).

8 Parallelism and Performance

G11BCF is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The sub-tables created by G11BCF and stored in STABLE and, depending on STAT, also in AUXT are stored in the following way. Let there be m dimensions defining the table with dimension k having lk levels, then the cell defined by the levels i 1,i 2,…,im of the factors is stored in sth cell given by
s=1+∑k=1 m ik-1 ck,
where
cj=∏k=j+ 1 m lk   for ​ j= 1, 2,…, n- 1   and   cm=1.

10 Example

The data, given by John and Quenouille (1977), is for 3 blocks of a 3×6 factorial experiment. The data can be considered as a 3×6×3 table (i.e., blocks × treatment with 6 levels × treatment with 3 levels). This table is input and the 6×3 table of treatment means for over blocks is computed and printed.

10.1 Program Text

Program Text (g11bcfe.f90)

10.2 Program Data

Program Data (g11bcfe.d)

10.3 Program Results

Program Results (g11bcfe.r)

G11 Chapter Contents
G11 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


G11CAF : NAG Library, Mark 26

G11 Chapter Contents
G11 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

G11CAF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

G11CAF returns parameter estimates for the conditional logistic analysis of stratified data, for example, data from case-control studies and survival analyses.

2 Specification

SUBROUTINE G11CAF ( N, M, NS, Z, LDZ, ISZ, IP, IC, ISI, DEV, B, SE, SC, COV, NCA, NCT, TOL, MAXIT, IPRINT, WK, LWK, IFAIL)
INTEGER | N, M, NS, LDZ, ISZ(M), IP, IC(N), ISI(N), NCA(NS), NCT(NS), MAXIT, IPRINT, LWK, IFAIL
REAL (KIND=nag_wp) | Z(LDZ,M), DEV, B(IP), SE(IP), SC(IP), COV(IP*(IP+1)/2), TOL, WK(LWK)

3 Description

In the analysis of binary data, the logistic model is commonly used. This relates the probability of one of the outcomes, say y=1, to p explanatory variates or covariates by
Prob y=1=exp α+zT β 1+exp α+zT β ,
where β is a vector of unknown coefficients for the covariates z and α is a constant term. If the observations come from different strata or groups, α would vary from strata to strata. If the observed outcomes are independent then the ys follow a Bernoulli distribution, i.e., a binomial distribution with sample size one and the model can be fitted as a generalized linear model with binomial errors.
In some situations the number of observations for which y=1 may not be independent. For example, in epidemiological research, case-control studies are widely used in which one or more observed cases are matched with one or more controls. The matching is based on fixed characteristics such as age and sex, and is designed to eliminate the effect of such characteristics in order to more accurately determine the effect of other variables. Each case-control group can be considered as a stratum. In this type of study the binomial model is not appropriate, except if the strata are large, and a conditional logistic model is used. This considers the probability of the cases having the observed vectors of covariates given the set of vectors of covariates in the strata. In the situation of one case per stratum, the conditional likelihood for ns strata can be written as
L=∏i=1 ns exp ziT β ∑l∈Si exp zlT β , (1)
where Si is the set of observations in the ith stratum, with associated vectors of covariates zl, l∈Si, and zi is the vector of covariates of the case in the ith stratum. In the general case of ci cases per strata then the full conditional likelihood is
L=∏i=1 ns exp siT β ∑l∈Ci exp slT β , (2)
where si is the sum of the vectors of covariates for the cases in the ith stratum and sl, l∈Ci refer to the sum of vectors of covariates for all distinct sets of ci observations drawn from the ith stratum. The conditional likelihood can be maximized by a Newton–Raphson procedure. The covariances of the parameter estimates can be estimated from the inverse of the matrix of second derivatives of the logarithm of the conditional likelihood, while the first derivatives provide the score function, Uj β, for j=1,2,…,p, which can be used for testing the significance of arguments.
If the strata are not small, Ci can be large so to improve the speed of computation, the algorithm in Howard (1972) and described by Krailo and Pike (1984) is used.
A second situation in which the above conditional likelihood arises is in fitting Cox's proportional hazard model (see G12BAF) in which the strata refer to the risk sets for each failure time and where the failures are cases. When ties are present in the data G12BAF uses an approximation. For an exact estimate, the data can be expanded using G12ZAF to create the risk sets/strata and G11CAF used.

4 References

Cox D R (1972) Regression models in life tables (with discussion) J. Roy. Statist. Soc. Ser. B 34 187–220
Cox D R and Hinkley D V (1974) Theoretical Statistics Chapman and Hall
Howard S (1972) Remark on the paper by Cox, D R (1972): Regression methods J. R. Statist. Soc. B 34 and life tables 187–220
Krailo M D and Pike M C (1984) Algorithm AS 196. Conditional multivariate logistic analysis of stratified case-control studies Appl. Statist. 33 95–103
Smith P G, Pike M C, Hill P, Breslow N E and Day N E (1981) Algorithm AS 162. Multivariate conditional logistic analysis of stratum-matched case-control studies Appl. Statist. 30 190–197

5 Arguments

1:   N – INTEGERInput
On entry: n, the number of observations.
Constraint: N≥2.
2:   M – INTEGERInput
On entry: the number of covariates in array Z.
Constraint: M≥1.
3:   NS – INTEGERInput
On entry: the number of strata, ns.
Constraint: NS≥1.
4:   Z LDZM – REAL (KIND=nag_wp) arrayInput
On entry: the ith row must contain the covariates which are associated with the ith observation.
5:   LDZ – INTEGERInput
On entry: the first dimension of the array Z as declared in the (sub)program from which G11CAF is called.
Constraint: LDZ≥N.
6:   ISZ M – INTEGER arrayInput
On entry: indicates which subset of covariates are to be included in the model.
If ISZ j≥1, the jth covariate is included in the model.
If ISZ j=0, the jth covariate is excluded from the model and not referenced.
Constraint: ISZ j≥0 and at least one value must be nonzero.
7:   IP – INTEGERInput
On entry: p, the number of covariates included in the model as indicated by ISZ.
Constraint: IP≥1 and IP= number of nonzero values of ISZ .
8:   IC N – INTEGER arrayInput
On entry: indicates whether the ith observation is a case or a control.
If IC i=0, indicates that the ith observation is a case.
If IC i=1, indicates that the ith observation is a control.
Constraint: IC i=0 or 1, for i=1,2,…,N.
9:   ISI N – INTEGER arrayInput
On entry: stratum indicators which also allow data points to be excluded from the analysis.
If ISI i=k, indicates that the ith observation is from the kth stratum, where k=1,2,…,NS.
If ISI i=0, indicates that the ith observation is to be omitted from the analysis.
Constraint: 0≤ISI i≤NS and more than IP values of ISI i>0, for i=1,2,…,N.
10:   DEV – REAL (KIND=nag_wp)Output
On exit: the deviance, that is, minus twice the maximized log-likelihood.
11:   B IP – REAL (KIND=nag_wp) arrayInput/Output
On entry: initial estimates of the covariate coefficient arguments β. B j must contain the initial estimate of the coefficent of the covariate in Z corresponding to the jth nonzero value of ISZ.
Suggested value: in many cases an initial value of zero for B j may be used. For another suggestion see Section 9.
On exit: B j contains the estimate β^i of the coefficient of the covariate stored in the ith column of Z where i is the jth nonzero value in the array ISZ.
12:   SE IP – REAL (KIND=nag_wp) arrayOutput
On exit: SE j is the asymptotic standard error of the estimate contained in B j and score function in SC j, for j=1,2,…,IP.
13:   SC IP – REAL (KIND=nag_wp) arrayOutput
On exit: SC j is the value of the score function Uj β for the estimate contained in B j.
14:   COV IP×IP+1/2 – REAL (KIND=nag_wp) arrayOutput
On exit: the variance-covariance matrix of the parameter estimates in B stored in packed form by column, i.e., the covariance between the parameter estimates given in B i and B j, j≥i, is given in COV j j-1/2+i.
15:   NCA NS – INTEGER arrayOutput
On exit: NCA i contains the number of cases in the ith stratum, for i=1,2,…,NS.
16:   NCT NS – INTEGER arrayOutput
On exit: NCT i contains the number of controls in the ith stratum, for i=1,2,…,NS.
17:   TOL – REAL (KIND=nag_wp)Input
On entry: indicates the accuracy required for the estimation. Convergence is assumed when the decrease in deviance is less than TOL×1.0+CurrentDeviance. This corresponds approximately to an absolute accuracy if the deviance is small and a relative accuracy if the deviance is large.
Constraint: TOL≥10×machine precision.
18:   MAXIT – INTEGERInput
On entry: the maximum number of iterations required for computing the estimates. If MAXIT is set to 0 then the standard errors, the score functions and the variance-covariance matrix are computed for the input value of β in B but β is not updated.
Constraint: MAXIT≥0.
19:   IPRINT – INTEGERInput
On entry: indicates if the printing of information on the iterations is required.
IPRINT≤0
No printing.
IPRINT≥1
The deviance and the current estimates are printed every IPRINT iterations. When printing occurs the output is directed to the current advisory message unit (see X04ABF).
Suggested value: IPRINT=0.
20:   WK LWK – REAL (KIND=nag_wp) arrayWorkspace
21:   LWK – INTEGERInput
On entry: the dimension of the array WK as declared in the (sub)program from which G11CAF is called.
Constraint: LWK≥p⁢n 0+cm+1⁢p+1⁢p+2/2+cm, where n 0 is the number of observations included in the model, i.e., the number of observations for which ISI i≠0 and cm is the maximum number of observations in any stratum.
22:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, | M<1,
or | N<2,
or | NS<1,
or | IP<1,
or | LDZ<N,
or | TOL<10×machine precision,
or | MAXIT<0.
IFAIL=2
On entry, | ISZ i<0, for some i,
or | the value of IP is incompatible with ISZ,
or | IC i≠1 or 0.
or | ISI i<0 or ISI i>NS,
or | the number of values of ISZ i>0 is greater than or equal to n 0, the number of observations excluding any with ISI i=0.
IFAIL=3
The value of LWK is too small.
IFAIL=4
Overflow has been detected. Try using different starting values.
IFAIL=5
The matrix of second partial derivatives is singular. Try different starting values or include fewer covariates.
IFAIL=6
Convergence has not been achieved in MAXIT iterations. The progress towards convergence can be examined by using a nonzero value of IPRINT. Any non-convergence may be due to a linear combination of covariates being monotonic with time.
Full results are returned.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

The accuracy is specified by TOL.

8 Parallelism and Performance

G11CAF is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
G11CAF makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The other models described in Section 3 can be fitted using the generalized linear modelling routines G02GBF and G02GCF.
The case with one case per stratum can be analysed by having a dummy response variable y such that y=1 for a case and y=0 for a control, and fitting a Poisson generalized linear model with a log link and including a factor with a level for each strata. These models can be fitted by using G02GCF.
G11CAF uses mean centering, which involves subtracting the means from the covariables prior to computation of any statistics. This helps to minimize the effect of outlying observations and accelerates convergence. In order to reduce the risk of the sums computed by Howard's algorithm becoming too large, the scaling factor described in Krailo and Pike (1984) is used.
If the initial estimates are poor then there may be a problem with overflow in calculating exp βT zi or there may be non-convergence. Reasonable estimates can often be obtained by fitting an unconditional model.

10 Example

The data was used for illustrative purposes by Smith et al. (1981) and consists of two strata and two covariates. The data is input, the model is fitted and the results are printed.

10.1 Program Text

Program Text (g11cafe.f90)

10.2 Program Data

Program Data (g11cafe.d)

10.3 Program Results

Program Results (g11cafe.r)

G11 Chapter Contents
G11 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


G11 Chapter Contents : NAG Library Manual, Mark 26

G11 Chapter Introduction
NAG Library Manual

NAG Library Chapter Contents

G11 – Contingency Table Analysis

G11 Chapter Introduction – a description of the Chapter and an overview of the algorithms available

Routine Name | Mark of Introduction | Purpose
G11AAF Example Text Example Data | 16 | nagf_contab_chisq χ 2 statistics for two-way contingency table
G11BAF Example Text Example Data | 17 | nagf_contab_tabulate_stat Computes multiway table from set of classification factors using selected statistic
G11BBF Example Text Example Data | 17 | nagf_contab_tabulate_percentile Computes multiway table from set of classification factors using given percentile/quantile
G11BCF Example Text Example Data | 17 | nagf_contab_tabulate_margin Computes marginal tables for multiway table computed by G11BAF or G11BBF
G11CAF Example Text Example Data | 19 | nagf_contab_condl_logistic Returns parameter estimates for the conditional analysis of stratified data
G11SAF Example Text Example Data | 12 | nagf_contab_binary Contingency table, latent variable model for binary data
G11SBF Example Text Example Data | 12 | nagf_contab_binary_service Frequency count for G11SAF
G11 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


G11 Chapter Introduction : NAG Library, Mark 26

G11 Chapter Contents
NAG Library Manual

NAG Library Chapter Introduction

G11 – Contingency Table Analysis

▸▿ Contents

1 Scope of the Chapter
▸▿ 2 Background to the Problems
2.1 Discrete Data
2.2 Tabulation
2.3 Discrete Response Variables and Logistic Regression
2.4 Contingency Tables
2.5 Latent Variable Models
▸▿ 3 Recommendations on Choice and Use of Available Routines
3.1 Tabulation
3.2 Analysis of Contingency Tables
3.3 Binary data
4 Functionality Index
5 Auxiliary Routines Associated with Library Routine Arguments
6 Routines Withdrawn or Scheduled for Withdrawal
7 References

1 Scope of the Chapter

The routines in this chapter are for the analysis of discrete multivariate data. One suite of routines computes tables while other routines are for the analysis of two-way contingency tables, conditional logistic models and one-factor analysis of binary data.
Routines in Chapter G02 may be used to fit generalized linear models to discrete data including binary data and contingency tables.

2 Background to the Problems

2.1 Discrete Data

Discrete variables can be defined as variables which take a limited range of values. Discrete data can be usefully categorized into three types.
  • Binary data. The variables can take one of two values: for example, yes or no. The data may be grouped: for example, the number of yes responses in ten questions.
  • Categorical data. The variables can take one of two or more values or levels, but the values are not considered to have any ordering: for example, the values may be red, green, blue or brown.
  • Ordered categorical data. This is similar to categorical data but an ordering can be placed on the levels: for example, poor, average or good.
Data containing discrete variables can be analysed by computing summaries and measures of association and by fitting models.

2.2 Tabulation

The basic summary for multivariate discrete data is the multidimensional table in which each dimension is specified by a discrete variable. If the cells of the table are the number of observations with the corresponding values of the discrete variables then it is a contingency table. The discrete variables that can be used to classify a table are known as factors. For example, the factor sex would have the levels male and female. These can be coded as 1 and 2 respectively. Given several factors a multi-way table can be constructed such that each cell of the table represents one level from each factor. For example, a sample of 120 observations with the two factors sex and habitat, habitat having three levels (inner-city, suburban and rural), would give the 2×3 contingency table
Sex | Habitat
 | Inner-city | Suburban | Rural
Male | 32 | 27 | 15
Female | 21 | 19 | 6
If the sample also contains continuous variables such as age, the average for the observations in each cell could be computed:
Sex | Habitat
 | Inner-city | Suburban | Rural
Male | 25.5 | 30.3 | 35.6
Female | 23.2 | 29.1 | 30.4
or other summary statistics.
Given a table, the totals or means for rows, columns etc. may be required. Thus the above contingency table with marginal totals is
Sex | Habitat |  |  |
 | Inner-city | Suburban | Rural | Total
Male | 32 | 27 | 15 | 74
Female | 21 | 19 | 6 | 46
Total | 53 | 46 | 21 | 120
Note that the marginal totals for columns is itself a 2×1 table. Also, other summary statistics could be used to produce the marginal tables such as means or medians. Having computed the marginal tables, the cells of the original table may be expressed in terms of the margins, for example in the above table the cells could be expressed as percentages of the column totals.

2.3 Discrete Response Variables and Logistic Regression

A second important categorization in addition to that given in Section 2.1 is whether one of the discrete variables can be considered as a response variable or whether it is just the association between the discrete variables that is being considered.
If the response variable is binary, for example, success or failure, then a logistic or probit regression model can be used. The logistic regression model relates the logarithm of the odds-ratio to a linear model. So if pi is the probability of success, the model relates log pi/1-pi to the explanatory variables. If the responses are independent then these models are special cases of the generalized linear model with binomial errors. However, there are cases when the binomial model is not suitable. For example, in a case-control study a number of cases (successes) and number of controls (failures) is chosen for a number of sets of case-controls. In this situation a conditional logistic analysis is required.
Handling a categorical or ordered categorical response variable is more complex, for a discussion on the appropriate models see McCullagh and Nelder (1983). These models generally use a Poisson distribution.
Note that if the response variable is a continuous variable and it is only the explanatory variables that are discrete then the regression models described in Chapter G02 should be used.

2.4 Contingency Tables

If there is no response variable then to investigate the association between discrete variables a contingency table can be computed and a suitable test performed on the table. The simplest case is the two-way table formed when considering two discrete variables. For a dataset of n observations classified by the two variables with r and c levels respectively, a two-way table of frequencies or counts with r rows and c columns can be computed.
n 11 n 12 … n 1 c n 1. n 21 n 22 … n 2 c n 2. ⋮ ⋮ ⋮ ⋮ ⋮ n r 1 n r 2 … n rc n r. n.1 n.2 … n.c n
If p ij is the probability of an observation in cell ij then the model which assumes no association between the two variables is the model
p ij=p i.p.j
where p i. is the marginal probability for the row variable and p.j is the marginal probability for the column variable, the marginal probability being the probability of observing a particular value of the variable ignoring all other variables. The appropriateness of this model can be assessed by two commonly used statistics:
the Pearson χ 2 statistic
∑i=1 r∑j=1 c n ij-f ij 2 f ij,
and the likelihood ratio test statistic
2∑i= 1 r∑j= 1 c n ij×log n ij/f ij.
The f ij are the fitted values from the model; these values are the expected cell frequencies and are given by
f ij=n p^ij=n p^i.p^.j=n n i./nn.j/n=n i.n.j/n.
Under the hypothesis of no association between the two classification variables, both these statistics have, approximately, a χ 2-distribution with c-1r-1 degrees of freedom. This distribution is arrived at under the assumption that the expected cell frequencies, f ij, are not too small.
In the case of the 2×2 table, i.e., c=2 and r=2, the χ 2 approximation can be improved by using Yates's continuity correction factor. This decreases the absolute value of (n ij-f ij) by 1/2. For 2×2 tables with a small values of n the exact probabilities can be computed; this is known as Fisher's exact test.
An alternative approach, which can easily be generalized to more than two variables, is to use log-linear models. A log-linear model for two variables can be written as
log p ij=log p i.+log p.j.
A model like this can be fitted as a generalized linear model with Poisson error with the cell counts, n ij, as the response variable.

2.5 Latent Variable Models

Latent variable models play an important role in the analysis of multivariate data. They have arisen in response to practical needs in many sciences, especially in psychology, educational testing and other social sciences.
Large-scale statistical enquiries, such as social surveys, generate much more information than can be easily absorbed without condensation. Elementary statistical methods help to summarise the data by looking at individual variables or the relationship between a small number of variables. However, with many variables it may still be difficult to see any pattern of inter-relationships. Our ability to visualize relationships is limited to two or three dimensions putting us under strong pressure to reduce the dimensionality of the data and yet preserve as much of the structure as possible. The question is thus one of how to replace the many variables with which we start by a much smaller number, with as little loss of information as possible.
One approach to the problem is to set up a model in which the dependence between the observed variables is accounted for by one or more latent variables. Such a model links the large number of observable variables with a much smaller number of latent variables.
Factor analysis, as described in Chapter G03, is based on a linear model of this kind when the observed variables are continuous. Here we consider the case where the observed variables are binary (e.g., coded 0/1 or true/false) and where there is one latent variable. In educational testing this is known as latent trait analysis, but, more generally, as factor analysis of binary data.
A variety of methods and models have been proposed for this problem. The models used here are derived from the general approach of Bartholomew (1980) and Bartholomew (1984). You are referred to Bartholomew (1980) for further information on the models and to Bartholomew (1987) for details of the method and application.

3 Recommendations on Choice and Use of Available Routines

3.1 Tabulation

The following routines can be used to perform the tabulation of discrete data:
  • G11BAF computes a multidimensional table from a set of discrete variables or classification factors. The cells of the table may be counts or a summary statistic (total, mean, variance, largest or smallest) computed for an associated continuous variable. Alternatively, G11BAF will update an existing table with further data.
  • G11BBF computes a multidimensional table from a set of discrete variables or classification factor where the cells are the percentile or quantile for an associated variable. For example, G11BBF can be used to produce a table of medians.
  • G11BCF computes a marginal table from a table computed by G11BAF or G11BBF using a summary statistic (total, mean, median variance, largest or smallest).

3.2 Analysis of Contingency Tables

G11AAF computes the Pearson and likelihood ratio χ 2 statistics for a two-way contingency table. For 2×2 tables Yates's correction factor is used and for small samples, n≤40, Fisher's exact test is used.
In addition, G02GCF can be used to fit a log-linear model to a contingency table.

3.3 Binary data

The following routines can be used to analyse binary data:
  • G11SAF fits a latent variable model to binary data. The frequency distribution of score patterns is required as input data. If your data is in the form of individual score patterns, then the service routine G11SBF may be used to calculate the frequency distribution.
  • G11CAF estimates the parameters for a conditional logistic model.
In addition, G02GBF fits generalized linear models to binary data.

4 Functionality Index

Conditional logistic model for stratified data G11CAF
Frequency count for G11SAF G11SBF
Latent variable model for dichotomous data G11SAF
Multiway tables from set of classification factors,
marginal table from G11BAF or G11BBF G11BCF
using given percentile/quantile G11BBF
using selected statistic G11BAF
χ2 statistics for two-way contingency table G11AAF

5 Auxiliary Routines Associated with Library Routine Arguments

None.

6 Routines Withdrawn or Scheduled for Withdrawal

None.

7 References

Bartholomew D J (1980) Factor analysis for categorical data (with Discussion) J. Roy. Statist. Soc. Ser. B 42 293–321
Bartholomew D J (1984) The foundations of factor analysis Biometrika 71 221–232
Bartholomew D J (1987) Latent Variable Models and Factor Analysis Griffin
Everitt B S (1977) The Analysis of Contingency Tables Chapman and Hall
Kendall M G and Stuart A (1969) The Advanced Theory of Statistics (Volume 1) (3rd Edition) Griffin
Kendall M G and Stuart A (1973) The Advanced Theory of Statistics (Volume 2) (3rd Edition) Griffin
McCullagh P and Nelder J A (1983) Generalized Linear Models Chapman and Hall
G11 Chapter Contents
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


G11SAF : NAG Library, Mark 26

G11 Chapter Contents
G11 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

G11SAF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
▸▿ 9 Further Comments
9.1 Timing
9.2 Initial Estimates
9.3 Heywood Cases
9.4 Goodness of Fit Statistic
9.5 First and Second Order Margins
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

G11SAF fits a latent variable model (with a single factor) to data consisting of a set of measurements on individuals in the form of binary-valued sequences (generally referred to as score patterns). Various measures of goodness-of-fit are calculated along with the factor (theta) scores.

2 Specification

SUBROUTINE G11SAF ( IP, N, GPROB, NS, X, LDX, IRL, A, C, IPRINT, CGETOL, MAXIT, CHISQR, ISHOW, NITER, ALPHA, PIGAM, CM, LDCM, G, EXPP, LDEXPP, OBS, EXF, Y, XL, IOB, RLOGL, CHI, IDF, SIGLEV, W, LW, IFAIL)
INTEGER | IP, N, NS, LDX, IRL(NS), IPRINT, MAXIT, ISHOW, NITER, LDCM, LDEXPP, IOB(NS), IDF, LW, IFAIL
REAL (KIND=nag_wp) | A(IP), C(IP), CGETOL, ALPHA(IP), PIGAM(IP), CM(LDCM,2*IP), G(2*IP), EXPP(LDEXPP,IP), OBS(LDEXPP,IP), EXF(NS), Y(NS), XL(NS), RLOGL, CHI, SIGLEV, W(LW)
LOGICAL | GPROB, X(LDX,IP), CHISQR

3 Description

Given a set of p dichotomous variables x~=x 1,x 2,…,xp′, where ′ denotes vector or matrix transpose, the objective is to investigate whether the association between them can be adequately explained by a latent variable model of the form (see Bartholomew (1980) and Bartholomew (1987))
G πi θ=α i 0+α i 1 θ. (1)
The xi are called item responses and take the value 0 or 1. θ denotes the latent variable assumed to have a standard Normal distribution over a population of individuals to be tested on p items. Call πi θ=P xi=1∣θ the item response function: it represents the probability that an individual with latent ability θ will produce a positive response (1) to item i. α i 0 and α i 1 are item parameters which can assume any real values. The set of parameters, α i 1, for i=1,2,…,p, being coefficients of the unobserved variable θ, can be interpreted as ‘factor loadings’.
G is a function selected by you as either Φ-1 or logit, mapping the interval 0,1 onto the whole real line. Data from a random sample of n individuals takes the form of the matrices X and R defined below:
X s×p= x 11 x 12 … x 1 p x 21 x 22 … x 2 p ⋮ ⋮ ⋮ x s 1 x s 2 … x sp = x~1 x~2 ⋮ x~s ,  R s×1= r 1 r 2 ⋮ rs
where x~l = x l 1,x l 2,…,x lp denotes the lth score pattern in the sample, rl the frequency with which x~l occurs and s the number of different score patterns observed. (Thus ∑l=1 s rl=n). It can be shown that the log-likelihood function is proportional to
∑ l=1 s rl log⁡Pl ,
where
Pl = P x~ = x~l = ∫ -∞ ∞ P x~ = x~l ∣ θ ϕ θ dθ (2)
(ϕ θ being the probability density function of a standard Normal random variable).
Pl denotes the unconditional probability of observing score pattern x~l. The integral in (2) is approximated using Gauss–Hermite quadrature. If we take G z=logit⁡z=log z 1-z in (1) and reparameterise as follows,
αi = α i 1, πi = logit-1⁡α i 0,
then (1) reduces to the logit model (see Bartholomew (1980))
πi θ = πi πi + 1-πi exp - αi θ .
If we take G z=Φ-1 z (where Φ is the cumulative distribution function of a standard Normal random variable) and reparameterise as follows,
αi = α i 1 1+α i 1 2 γi = -α i 0 1+α i 1 2 ,
then (1) reduces to the probit model (see Bock and Aitkin (1981))
πi θ=ϕ αi θ-γi 1-αi 2 .
An E-M algorithm (see Bock and Aitkin (1981)) is used to maximize the log-likelihood function. The number of quadrature points used is set initially to 10 and once convergence is attained increased to 20.
The theta score of an individual responding in score pattern x~l is computed as the posterior mean, i.e., E θ∣x~l. For the logit model the component score Xl=∑j=1 p αjx lj is also calculated. (Note that in calculating the theta scores and measures of goodness-of-fit G11SAF automatically reverses the coding on item j if αj<0; it is assumed in the model that a response at the one level is showing a higher measure of latent ability than a response at the zero level.)
The frequency distribution of score patterns is required as input data. If your data is in the form of individual score patterns (uncounted), then G11SBF may be used to calculate the frequency distribution.

4 References

Bartholomew D J (1980) Factor analysis for categorical data (with Discussion) J. Roy. Statist. Soc. Ser. B 42 293–321
Bartholomew D J (1987) Latent Variable Models and Factor Analysis Griffin
Bock R D and Aitkin M (1981) Marginal maximum likelihood estimation of item parameters: Application of an E-M algorithm Psychometrika 46 443–459

5 Arguments

1:   IP – INTEGERInput
On entry: p, the number of dichotomous variables.
Constraint: IP≥3.
2:   N – INTEGERInput
On entry: n, the number of individuals in the sample.
Constraint: N≥7.
3:   GPROB – LOGICALInput
On entry: must be set equal to .TRUE. if G z=Φ-1 z and .FALSE. if G z=logit⁡z.
4:   NS – INTEGERInput
On entry: NS must be set equal to the number of different score patterns in the sample, s.
Constraint: 2×IP<NS≤min 2 IP,N.
5:   X LDXIP – LOGICAL arrayInput/Output
On entry: the first s rows of X must contain the s different score patterns. The lth row of X must contain the lth score pattern with X lj set equal to .TRUE. if x lj=1 and .FALSE. if x lj=0. All rows of X must be distinct.
On exit: given a valid parameter set then the first s rows of X still contain the s different score patterns. However, the following points should be noted:
(i) | If the estimated factor loading for the jth item is negative then that item is re-coded, i.e., 0s and 1s (or .TRUE. and .FALSE.) in the jth column of X are interchanged.
(ii) | The rows of X will be reordered so that the theta scores corresponding to rows of X are in increasing order of magnitude.
6:   LDX – INTEGERInput
On entry: the first dimension of the array X as declared in the (sub)program from which G11SAF is called.
Constraint: LDX≥NS.
7:   IRL NS – INTEGER arrayInput/Output
On entry: the ith component of IRL must be set equal to the frequency with which the ith row of X occurs.
Constraints:
  • IRL i≥0, for i=1,2,…,s;
  • ∑i=1 s IRL i=n.
On exit: given a valid parameter set then the first s components of IRL are reordered as are the rows of X.
8:   A IP – REAL (KIND=nag_wp) arrayInput/Output
On entry: A j must be set equal to an initial estimate of α j 1. In order to avoid divergence problems with the E-M algorithm you are strongly advised to set all the A j to 0.5.
On exit: A j contains the latest estimate of α j 1, for j=1,2,…,p. (Because of possible recoding all elements of A will be positive.)
9:   C IP – REAL (KIND=nag_wp) arrayInput/Output
On entry: C j must be set equal to an initial estimate of α j 0. In order to avoid divergence problems with the E-M algorithm you are strongly advised to set all the C j to 0.0.
On exit: C j contains the latest estimate of α j 0, for j=1,2,…,p.
10:   IPRINT – INTEGERInput
On entry: the frequency with which the maximum likelihood search routine is to be monitored.
IPRINT>0
The search is monitored once every IPRINT iterations, and when the number of quadrature points is increased, and again at the final solution point.
IPRINT=0
The search is monitored once at the final point.
IPRINT<0
The search is not monitored at all.
IPRINT should normally be set to a small positive number.
Suggested value: IPRINT=1.
11:   CGETOL – REAL (KIND=nag_wp)Input
On entry: the accuracy to which the solution is required.
If CGETOL is set to 10-l and on exit IFAIL=0 or 7, then all elements of the gradient vector will be smaller than 10-l in absolute value. For most practical purposes the value 10-4 should suffice. You should be wary of setting CGETOL too small since the convergence criterion may then have become too strict for the machine to handle.
If CGETOL has been set to a value which is less than the square root of the machine precision, ε, then G11SAF will use the value ε instead.
12:   MAXIT – INTEGERInput
On entry: the maximum number of iterations to be made in the maximum likelihood search. There will be an error exit (see Section 6) if the search routine has not converged in MAXIT iterations.
Suggested value: MAXIT=1000.
Constraint: MAXIT≥1.
13:   CHISQR – LOGICALInput
On entry: if CHISQR is set equal to .TRUE., then a likelihood ratio statistic will be calculated (see CHI).
If CHISQR is set equal to .FALSE., no such statistic will be calculated.
14:   ISHOW – INTEGERInput
On entry: indicates which of the following three quantities are to be printed before exit from the routine (given a valid parameter set):
(a) | Table of maximum likelihood estimates and standard errors (as returned in the output arrays A, C, ALPHA, PIGAM and CM).
(b) | Table of observed and expected first and second order margins (as returned in the output arrays EXPP and OBS).
(c) | Table of observed and expected frequencies of score patterns along with theta scores (as returned in the output arrays IRL, EXF, Y, XL and IOB) and the likelihood ratio statistic (if required).
ISHOW=0
None of the above are printed.
ISHOW=1
(a) only is printed.
ISHOW=2
(b) only is printed.
ISHOW=3
(c) only is printed.
ISHOW=4
(a) and (b) are printed.
ISHOW=5
(a) and (c) are printed.
ISHOW=6
(b) and (c) are printed.
ISHOW=7
(a), (b) and (c) are printed.
Constraint: 0≤ISHOW≤7.
15:   NITER – INTEGEROutput
On exit: given a valid parameter set then NITER contains the number of iterations performed by the maximum likelihood search routine.
16:   ALPHA IP – REAL (KIND=nag_wp) arrayOutput
On exit: given a valid parameter set then ALPHA j contains the latest estimate of αj. (Because of possible recoding all elements of ALPHA will be positive.)
17:   PIGAM IP – REAL (KIND=nag_wp) arrayOutput
On exit: given a valid parameter set then PIGAM j contains the latest estimate of either πj if GPROB=.FALSE. (logit model) or γj if GPROB=.TRUE. (probit model).
18:   CM LDCM 2×IP – REAL (KIND=nag_wp) arrayOutput
On exit: given a valid parameter set then the strict lower triangle of CM contains the correlation matrix of the parameter estimates held in ALPHA and PIGAM on exit. The diagonal elements of CM contain the standard errors. Thus:
CM 2×i-12×i-1 = standard error ALPHA i
CM 2×i2×i = standard error PIGAM i
CM 2×i2×i-1 = correlation PIGAM i,ALPHA i,
for i=1,2,…,p;
CM 2×i-12×j-1 = correlation ALPHA i,ALPHA j
CM 2×i2×j = correlation PIGAM i,PIGAM j
CM 2×i-12×j = correlation ALPHA i,PIGAM j
CM 2×i2×j-1 = correlation ALPHA j,PIGAM i,
for j=1,2,…,i-1.
If the second derivative matrix cannot be computed then all the elements of CM are returned as zero.
19:   LDCM – INTEGERInput
On entry: the first dimension of the array CM as declared in the (sub)program from which G11SAF is called.
Constraint: LDCM≥2×IP.
20:   G 2×IP – REAL (KIND=nag_wp) arrayOutput
On exit: given a valid parameter set then G contains the estimated gradient vector corresponding to the final point held in the arrays ALPHA and PIGAM. G 2×j-1 contains the derivative of the log-likelihood with respect to ALPHA j, for j=1,2,…,p. G 2×j contains the derivative of the log-likelihood with respect to PIGAM j, for j=1,2,…,p.
21:   EXPP LDEXPPIP – REAL (KIND=nag_wp) arrayOutput
On exit: given a valid parameter set then EXPP ij contains the expected percentage of individuals in the sample who respond positively to items i and j (j≤i), corresponding to the final point held in the arrays ALPHA and PIGAM.
22:   LDEXPP – INTEGERInput
On entry: the first dimension of the arrays EXPP and OBS as declared in the (sub)program from which G11SAF is called.
Constraint: LDEXPP≥IP.
23:   OBS LDEXPPIP – REAL (KIND=nag_wp) arrayOutput
On exit: given a valid parameter set then OBS ij contains the observed percentage of individuals in the sample who responded positively to items i and j (j≤i).
24:   EXF NS – REAL (KIND=nag_wp) arrayOutput
On exit: given a valid parameter set then EXF l contains the expected frequency of the lth score pattern (lth row of X), corresponding to the final point held in the arrays ALPHA and PIGAM.
25:   Y NS – REAL (KIND=nag_wp) arrayOutput
On exit: given a valid parameter set then Y l contains the estimated theta score corresponding to the lth row of X, for the final point held in the arrays ALPHA and PIGAM.
26:   XL NS – REAL (KIND=nag_wp) arrayWorkspace
If GPROB has been set equal to .FALSE. (logit model) then on exit, given a valid parameter set, XL l contains the estimated component score corresponding to the lth row of X for the final point held in the arrays ALPHA and PIGAM.
If GPROB is set equal to .TRUE. (probit model), this array is not used.
27:   IOB NS – INTEGER arrayOutput
On exit: given a valid parameter set then IOB l contains the number of items in the lth row of X for which the response was positive (.TRUE.).
28:   RLOGL – REAL (KIND=nag_wp)Output
On exit: given a valid parameter set then RLOGL contains the value of the log-likelihood kernel corresponding to the final point held in the arrays ALPHA and PIGAM, namely
∑l=1 s IRL l×log EXF l/n.
29:   CHI – REAL (KIND=nag_wp)Output
On exit: if CHISQR was set equal to .TRUE. on entry, then given a valid parameter set, CHI will contain the value of the likelihood ratio statistic corresponding to the final parameter estimates held in the arrays ALPHA and PIGAM, namely
2×∑l=1 s IRL l×log EXF l/IRL l.
The summation is over those elements of IRL which are positive. If EXF l is less than 5.0, then adjacent score patterns are pooled (the score patterns in X being first put in order of increasing theta score).
If CHISQR has been set equal to .FALSE., then CHI is not used.
30:   IDF – INTEGEROutput
On exit: if CHISQR was set equal to .TRUE. on entry, then given a valid parameter set, IDF will contain the degrees of freedom associated with the likelihood ratio statistic, CHI.
IDF=s 0-2×p | if s 0<2 p;
IDF=s 0-2×p-1 | if s 0=2 p,
where s 0 denotes the number of terms summed to calculate CHI (s 0=s only if there is no pooling).
If CHISQR has been set equal to .FALSE., then IDF is not used.
31:   SIGLEV – REAL (KIND=nag_wp)Output
On exit: if CHISQR was set equal to .TRUE. on entry, then given a valid parameter set, SIGLEV will contain the significance level of CHI based on IDF degrees of freedom. If IDF is zero or negative then SIGLEV is set to zero.
If CHISQR was set equal to .FALSE., then SIGLEV is not used.
32:   W LW – REAL (KIND=nag_wp) arrayWorkspace
33:   LW – INTEGERInput
On entry: the dimension of the array W as declared in the (sub)program from which G11SAF is called.
Constraint: LW≥4×IP×IP+16.
34:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, because for this routine the values of the output arguments may be useful even if IFAIL≠0 on exit, the recommended value is -1. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Note: G11SAF may return useful information for one or more of the following detected errors or warnings.
Errors or warnings detected by the routine:
IFAIL=1
On entry, | IP<3,
or | N<7,
or | NS≤2×IP,
or | NS>N,
or | NS>2 IP,
or | two or more rows of X are identical,
or | LDX<NS,
or | ∑l=1 NS IRL l≠N,
or | at least one of IRL l<0, for l=1,2,…,NS,
or | MAXIT<1,
or | ISHOW<0,
or | ISHOW>7,
or | LDCM<IP+IP,
or | LDEXPP<IP,
or | LW<4×IP×IP+16.
IFAIL=2
For at least one of the IP items the responses are all at the same level. To proceed, you must delete this item from the dataset.
IFAIL=3
There have been MAXIT iterations of the maximum likelihood search routine. If steady increases in the log-likelihood kernel were monitored up to the point where this exit occurred, then the exit probably occurred simply because MAXIT was set too small, so the calculations should be restarted from the final point held in A and C. This type of exit may also indicate that there is no maximum to the likelihood surface.
IFAIL=4
One of the elements of A has exceeded 10.0 in absolute value (see Section 9.3). If steady increases in the log-likelihood kernel were monitored up to the point where this exit occurred then this exit may indicate that there is no maximum to the likelihood surface. You are advised to restart the calculations from a different point to see whether the E-M algorithm moves off in the same direction.
IFAIL=5
This indicates a failure in F01ABF which is used to invert the second derivative matrix for calculating the variance-covariance matrix of parameter estimates. It was also found that MAXIT iterations had been performed (see IFAIL=3). The elements of CM will then have been set to zero on exit. You are advised to restart the calculations with a larger value for MAXIT.
IFAIL=6
This indicates a failure in F01ABF which is used to invert the second derivative matrix for calculating the variance-covariance matrix of parameter estimates. It was also found that one of the elements of A had exceeded 10.0 in absolute value (see IFAIL=4). The elements of CM will have then been set to zero on exit. You are advised to restart the calculations from a different point to see whether the E-M algorithm moves off in the same direction.
IFAIL=7
If CHISQR was set equal to .TRUE. on entry, so that a likelihood ratio statistic was calculated, then IFAIL=7 merely indicates that the value of IDF on exit is ≤0, i.e., the χ 2 statistic is meaningless. In this case SIGLEV is returned as zero. All other output information should be correct, i.e., can be treated as if IFAIL=0 on exit.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

On exit from G11SAF if IFAIL=0 or 7 then the following condition will be satisfied:
max 1≤i≤2×p G i < CGETOL .
If IFAIL=3 or 5 on exit (i.e., MAXIT iterations have been performed but the above condition does not hold), then the elements in A, C, ALPHA and PIGAM may still be good approximations to the maximum likelihood estimates. You are advised to inspect the elements of G to see whether this is confirmed.

8 Parallelism and Performance

G11SAF is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
G11SAF makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

9.1 Timing

The number of iterations required in the maximum likelihood search depends upon the number of observed variables, p, and the distance of the starting point you supplied from the solution. The number of multiplications and divisions performed in an iteration is proportional to p.

9.2 Initial Estimates

You are strongly advised to use the recommended starting values for the elements of A and C. Divergence may result from values you supplied even if they are very close to the solution. Divergence may also occur when an item has nearly all its responses at one level.

9.3 Heywood Cases

As in normal factor analysis, Heywood cases can often occur, particularly when p is small and n not very big. To overcome this difficulty the maximum likelihood search routine is terminated when the absolute value of one of the α j 1 exceeds 10.0. You have the option of deciding whether to exit from G11SAF (by setting IFAIL=0 on entry) or to permit G11SAF to proceed onwards as if it had exited normally from the maximum likelihood search routine (setting IFAIL=-1 on entry). The elements in A, C, ALPHA and PIGAM may still be good approximations to the maximum likelihood estimates. You are advised to inspect the elements G to see whether this is confirmed.

9.4 Goodness of Fit Statistic

When n is not very large compared to s a goodness-of-fit statistic should not be calculated as many of the expected frequencies will then be less than 5.

9.5 First and Second Order Margins

The observed and expected percentages of sample members responding to individual and pairs of items held in the arrays OBS and EXPP on exit can be converted to observed and expected numbers by multiplying all elements of these two arrays by n/100.0.

10 Example

A program to fit the logit latent variable model to the following data:
Index | Score Pattern | Observed Frequency
0 1 | 0000 | 0 154
0 2 | 1000 | 00 11
0 3 | 0001 | 00 42
0 4 | 0100 | 00 49
0 5 | 1001 | 000 2
0 6 | 1100 | 00 10
0 7 | 0101 | 00 27
0 8 | 0010 | 00 84
0 9 | 1101 | 00 10
10 | 1010 | 00 25
11 | 0011 | 00 75
12 | 0110 | 0 129
13 | 1011 | 00 30
14 | 1110 | 00 50
15 | 0111 | 0 181
16 | 1111 | 0 121
 |  | ––––
Total |  | 1000

10.1 Program Text

Program Text (g11safe.f90)

10.2 Program Data

Program Data (g11safe.d)

10.3 Program Results

Program Results (g11safe.r)

G11 Chapter Contents
G11 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


G11SBF : NAG Library, Mark 26

G11 Chapter Contents
G11 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

G11SBF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

G11SBF is a service routine which may be used prior to calling G11SAF to calculate the frequency distribution of a set of dichotomous score patterns.

2 Specification

SUBROUTINE G11SBF ( IP, N, NS, X, LDX, IRL, IFAIL)
INTEGER | IP, N, NS, LDX, IRL(N), IFAIL
LOGICAL | X(LDX,IP)

3 Description

When each of n individuals responds to each of p dichotomous variables the data assumes the form of the matrix X defined below
X= x 11 x 12 … x 1 p x 21 x 22 … x 2 p ⋮ ⋮ ⋮ x n 1 x n 2 … x np = x̲1 x̲2 ⋮ x̲n ,
where the x take the value of 0 or 1 and x̲l=x l 1,x l 2,…,x lp, for l=1,2,…,n, denotes the score pattern of the lth individual. G11SBF calculates the number of different score patterns, s, and the frequency with which each occurs. This information can then be passed to G11SAF.

4 References

None.

5 Arguments

1:   IP – INTEGERInput
On entry: p, the number of dichotomous variables.
Constraint: IP≥3.
2:   N – INTEGERInput
On entry: n, the number of individuals in the sample.
Constraint: N≥7.
3:   NS – INTEGEROutput
On exit: the number of different score patterns, s.
4:   X LDXIP – LOGICAL arrayInput/Output
On entry: X ij must be set equal to .TRUE. if x ij=1, and .FALSE. if x ij=0, for i=1,2,…,n and j=1,2,…,p.
On exit: the first s rows of X contain the s different score patterns.
5:   LDX – INTEGERInput
On entry: the first dimension of the array X as declared in the (sub)program from which G11SBF is called.
Constraint: LDX≥N.
6:   IRL N – INTEGER arrayOutput
On exit: the frequency with which the lth row of X occurs, for l=1,2,…,s.
7:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, | IP<3,
or | N<7,
or | LDX<N.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

Exact.

8 Parallelism and Performance

G11SBF is not threaded in any implementation.

9 Further Comments

The time taken by G11SBF is small and increases with n.

10 Example

This example counts the frequencies of different score patterns in the following list:
Score Patterns
000
010
111
000
001
000
000
110
001
011

10.1 Program Text

Program Text (g11sbfe.f90)

10.2 Program Data

Program Data (g11sbfe.d)

10.3 Program Results

Program Results (g11sbfe.r)

G11 Chapter Contents
G11 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


G12AAF : NAG Library, Mark 26

G12 Chapter Contents
G12 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

G12AAF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

G12AAF computes the Kaplan–Meier, (or product-limit), estimates of survival probabilities for a sample of failure times.

2 Specification

SUBROUTINE G12AAF ( N, T, IC, FREQ, IFREQ, ND, TP, P, PSIG, IWK, IFAIL)
INTEGER | N, IC(N), IFREQ(*), ND, IWK(N), IFAIL
REAL (KIND=nag_wp) | T(N), TP(N), P(N), PSIG(N)
CHARACTER(1) | FREQ

3 Description

A survivor function, S t, is the probability of surviving to at least time t with S t=1-F t, where F t is the cumulative distribution function of the failure times. The Kaplan–Meier or product limit estimator provides an estimate of S t, S^t, from sample of failure times which may be progressively right-censored.
Let ti, i=1,2,…,nd, be the ordered distinct failure times for the sample of observed failure/censored times, and let the number of observations in the sample that have not failed by time ti be ni. If a failure and a loss (censored observation) occur at the same time ti, then the failure is treated as if it had occurred slightly before time ti and the loss as if it had occurred slightly after ti.
The Kaplan–Meier estimate of the survival probabilities is a step function which in the interval ti to t i+1 is given by
S^t=∏j=1 i nj-dj nj ,
where dj is the number of failures occurring at time tj.
G12AAF computes the Kaplan–Meier estimates and the corresponding estimates of the variances, var^S^t, using Greenwood's formula,
var^S^t=S^ t 2∑j=1 i dj nj nj-dj .

4 References

Gross A J and Clark V A (1975) Survival Distributions: Reliability Applications in the Biomedical Sciences Wiley
Kalbfleisch J D and Prentice R L (1980) The Statistical Analysis of Failure Time Data Wiley

5 Arguments

1:   N – INTEGERInput
On entry: the number of failure and censored times given in T.
Constraint: N≥2.
2:   T N – REAL (KIND=nag_wp) arrayInput
On entry: the failure and censored times; these need not be ordered.
3:   IC N – INTEGER arrayInput
On entry: IC i contains the censoring code of the ith observation, for i=1,2,…,N.
IC i=0
The ith observation is a failure time.
IC i=1
The ith observation is right-censored.
Constraint: IC i=0 or 1, for i=1,2,…,N.
4:   FREQ – CHARACTER(1)Input
On entry: indicates whether frequencies are provided for each time point.
FREQ='F'
Frequencies are provided for each failure and censored time.
FREQ='S'
The failure and censored times are considered as single observations, i.e., a frequency of 1 is assumed.
Constraint: FREQ='F' or 'S'.
5:   IFREQ* – INTEGER arrayInput
Note: the dimension of the array IFREQ must be at least N if FREQ='F' and at least 1 if FREQ='S'.
On entry: if FREQ='F', IFREQ i must contain the frequency of the ith observation.
If IFREQ='S', a frequency of 1 is assumed and IFREQ is not referenced.
Constraint: if FREQ='F', IFREQ i≥0, for i=1,2,…,N.
6:   ND – INTEGEROutput
On exit: the number of distinct failure times, nd.
7:   TP N – REAL (KIND=nag_wp) arrayOutput
On exit: TP i contains the ith ordered distinct failure time, ti, for i=1,2,…,nd.
8:   P N – REAL (KIND=nag_wp) arrayOutput
On exit: P i contains the Kaplan–Meier estimate of the survival probability, S^t, for time TP i, for i=1,2,…,nd.
9:   PSIG N – REAL (KIND=nag_wp) arrayOutput
On exit: PSIG i contains an estimate of the standard deviation of P i, for i=1,2,…,nd.
10:   IWK N – INTEGER arrayWorkspace
11:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, N<2.
IFAIL=2
On entry, FREQ≠'F' or 'S'.
IFAIL=3
On entry, IC i≠0 or 1, for some i=1,2,…,N.
IFAIL=4
On entry, FREQ='F' and IFREQ i<0, for some i=1,2,…,N.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

The computations are believed to be stable.

8 Parallelism and Performance

G12AAF is not threaded in any implementation.

9 Further Comments

If there are no censored observations, S^t reduces to the ordinary binomial estimate of the probability of survival at time t.

10 Example

The remission times for a set of 21 leukaemia patients at 18 distinct time points are read in and the Kaplan–Meier estimate computed and printed. For further details see page 242 of Gross and Clark (1975).

10.1 Program Text

Program Text (g12aafe.f90)

10.2 Program Data

Program Data (g12aafe.d)

10.3 Program Results

Program Results (g12aafe.r)

GnuplotProduced by GNUPLOT 4.6 patchlevel 3 0 0.2 0.4 0.6 0.8 1 5 10 15 20 Survival Probability Time Example Program Kaplan Meier Plot gnuplot_plot_1
G12 Chapter Contents
G12 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


G12ABF : NAG Library, Mark 26

G12 Chapter Contents
G12 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

G12ABF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

G12ABF calculates the rank statistics, which can include the logrank test, for comparing survival curves.

2 Specification

SUBROUTINE G12ABF ( N, T, IC, GRP, NGRP, FREQ, IFREQ, WEIGHT, WT, TS, DF, P, OBSD, EXPT, ND, DI, NI, LDN, IFAIL)
INTEGER | N, IC(N), GRP(N), NGRP, IFREQ(*), DF, ND, DI(LDN), NI(LDN), LDN, IFAIL
REAL (KIND=nag_wp) | T(N), WT(*), TS, P, OBSD(NGRP), EXPT(NGRP)
CHARACTER(1) | FREQ, WEIGHT

3 Description

A survivor function, S t, is the probability of surviving to at least time t. Given a series of n failure or right-censored times from g groups G12ABF calculates a rank statistic for testing the null hypothesis
  • H 0 : S 1 t = S 2 t = ⋯ = S g t , ∀ t ≤ τ
where τ is the largest observed time, against the alternative hypothesis
  • H 1 : at least one of the S i t differ, for some t ≤ τ .
Let t i , for i=1,2,…,nd, denote the list of distinct failure times across all g groups and wi a series of nd weights. Let d ij denote the number of failures at time ti in group j and n ij denote the number of observations in the group j that are known to have not failed prior to time ti, i.e., the size of the risk set for group j at time ti. If a censored observation occurs at time ti then that observation is treated as if the censoring had occurred slightly after ti and therefore the observation is counted as being part of the risk set at time ti. Finally let
di = ∑ j=1 g d ij   and   ni = ∑ j=1 g n ij .
The (weighted) number of observed failures in the jth group, Oj, is therefore given by
Oj = ∑ i=1 nd wi d ij
and the (weighted) number of expected failures in the jth group, Ej, by
Ej = ∑ i=1 nd wi n ij di ni .
If x denotes the vector of differences x = O 1 - E 1 , O 2 - E 2 , … , Og - Eg and
V jk = ∑ i=1 nd w i 2 di ni - di ni n i k I jk - n ij n ik n i 2 ni - 1
where I jk = 1 if j=k and 0 otherwise, then the rank statistic, T, is calculated as
T = x V- xT
where V- denotes a generalized inverse of the matrix V. Under the null hypothesis, T ∼ χ ν 2 where the degrees of freedom, ν, is taken as the rank of the matrix V.

4 References

Gross A J and Clark V A (1975) Survival Distributions: Reliability Applications in the Biomedical Sciences Wiley
Kalbfleisch J D and Prentice R L (1980) The Statistical Analysis of Failure Time Data Wiley
Rostomily R C, Duong D, McCormick K, Bland M and Berger M S (1994) Multimodality management of recurrent adult malignant gliomas: results of a phase II multiagent chemotherapy study and analysis of cytoreductive surgery Neurosurgery 35 378

5 Arguments

1:   N – INTEGERInput
On entry: n, the number of failure and censored times.
Constraint: N≥2.
2:   T N – REAL (KIND=nag_wp) arrayInput
On entry: the observed failure and censored times; these need not be ordered.
Constraint: T i≠T j for at least one i≠j, for i=1,2,…,N and j=1,2,…,N.
3:   IC N – INTEGER arrayInput
On entry: IC i contains the censoring code of the ith observation, for i=1,2,…,N.
IC i=0
the ith observation is a failure time.
IC i=1
the ith observation is right-censored.
Constraints:
  • IC i=0 or 1, for i=1,2,…,N;
  • IC i=0 for at least one i.
4:   GRP N – INTEGER arrayInput
On entry: GRP i contains a flag indicating which group the ith observation belongs in, for i=1,2,…,N.
Constraints:
  • 1≤GRP i≤NGRP, for i=1,2,…,N;
  • each group must have at least one observation.
5:   NGRP – INTEGERInput
On entry: g, the number of groups.
Constraint: 2≤NGRP≤N.
6:   FREQ – CHARACTER(1)Input
On entry: indicates whether frequencies are provided for each time point.
FREQ='F'
Frequencies are provided for each failure and censored time.
FREQ='S'
The failure and censored times are considered as single observations, i.e., a frequency of 1 is assumed.
Constraint: FREQ='F' or 'S'.
7:   IFREQ* – INTEGER arrayInput
Note: the dimension of the array IFREQ must be at least N if FREQ='F'.
On entry: if FREQ='F', IFREQ i must contain the frequency (number of observations) to which each entry in T corresponds.
If FREQ='S', each entry in T is assumed to correspond to a single observation, i.e., a frequency of 1 is assumed, and IFREQ is not referenced.
Constraint: if FREQ='F', IFREQ i≥0, for i=1,2,…,N.
8:   WEIGHT – CHARACTER(1)Input
On entry: indicates if weights are to be used.
WEIGHT='U'
All weights are assumed to be 1.
WEIGHT='W'
The weights, wi are supplied in WT.
Constraint: WEIGHT='U' or 'W'.
9:   WT* – REAL (KIND=nag_wp) arrayInput
Note: the dimension of the array WT must be at least LDN if WEIGHT='W'.
On entry: if WEIGHT='W', WT must contain the nd weights, wi, where nd is the number of distinct failure times.
If WEIGHT='U', WT is not referenced and wi=1 for all i.
Constraint: if WEIGHT='W', WT i≥0.0, for i=1,2,…,nd.
10:   TS – REAL (KIND=nag_wp)Output
On exit: T, the test statistic.
11:   DF – INTEGEROutput
On exit: ν, the degrees of freedom.
12:   P – REAL (KIND=nag_wp)Output
On exit: P X≥T, when X∼χν 2, i.e., the probability associated with TS.
13:   OBSD NGRP – REAL (KIND=nag_wp) arrayOutput
On exit: Oi, the observed number of failures in each group.
14:   EXPT NGRP – REAL (KIND=nag_wp) arrayOutput
On exit: Ei, the expected number of failures in each group.
15:   ND – INTEGEROutput
On exit: nd, the number of distinct failure times.
16:   DI LDN – INTEGER arrayOutput
On exit: the first ND elements of DI contain di, the number of failures, across all groups, at time ti.
17:   NI LDN – INTEGER arrayOutput
On exit: the first ND elements of NI contain ni, the size of the risk set, across all groups, at time ti.
18:   LDN – INTEGERInput
On entry: the size of arrays DI and NI. As nd≤n, if nd is not known a priori then a value of N can safely be used for LDN.
Constraint: LDN≥nd, the number of unique failure times.
19:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, N=value.
Constraint: N≥2.
IFAIL=2
On entry, all the times in T are the same.
IFAIL=3
On entry, IC value=value.
Constraint: IC i=0 or 1.
IFAIL=4
On entry, GRP value=value and NGRP=value.
Constraint: 1≤GRP i≤NGRP.
IFAIL=5
On entry, NGRP=value and N=value.
Constraint: 2≤NGRP≤N.
IFAIL=6
On entry, FREQ had an illegal value.
IFAIL=7
On entry, IFREQ value=value.
Constraint: IFREQ i≥0.
IFAIL=8
On entry, WEIGHT had an illegal value.
IFAIL=9
On entry, WT value=value.
Constraint: WT i≥0.0.
IFAIL=11
The degrees of freedom are zero.
IFAIL=18
On entry, LDN=value.
Constraint: LDN≥value.
IFAIL=31
On entry, all observations are censored.
IFAIL=41
On entry, group value has no observations.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

Not applicable.

8 Parallelism and Performance

G12ABF is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
G12ABF makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The use of different weights in the formula given in Section 3 leads to different rank statistics being calculated. The logrank test has wi=1, for all i, which is the equivalent of calling G12ABF when WEIGHT='U' . Other rank statistics include Wilcoxon (wi=ni), Tarone–Ware (wi=ni) and Peto–Peto ( wi = S~ ti where S~ ti = ∏ tj ≤ ti nj - dj + 1 nj+1 ) amongst others.
Calculation of any test, other than the logrank test, will probably require G12ABF to be called twice, once to calculate the values of ni and di to facilitate in the computation of the required weights, and once to calculate the test statistic itself.

10 Example

This example compares the time to death for 51 adults with two different types of recurrent gliomas (brain tumour), astrocytoma and glioblastoma, using a logrank test. For further details on the data see Rostomily et al. (1994).

10.1 Program Text

Program Text (g12abfe.f90)

10.2 Program Data

Program Data (g12abfe.d)

10.3 Program Results

Program Results (g12abfe.r)

G12 Chapter Contents
G12 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


G12BAF : NAG Library, Mark 26

G12 Chapter Contents
G12 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

G12BAF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

G12BAF returns parameter estimates and other statistics that are associated with the Cox proportional hazards model for fixed covariates.

2 Specification

SUBROUTINE G12BAF ( OFFSET, N, M, NS, Z, LDZ, ISZ, IP, T, IC, OMEGA, ISI, DEV, B, SE, SC, COV, RES, ND, TP, SUR, NDMAX, TOL, MAXIT, IPRINT, WK, IWK, IFAIL)
INTEGER | N, M, NS, LDZ, ISZ(M), IP, IC(N), ISI(*), ND, NDMAX, MAXIT, IPRINT, IWK(2*N), IFAIL
REAL (KIND=nag_wp) | Z(LDZ,M), T(N), OMEGA(*), DEV, B(IP), SE(IP), SC(IP), COV(IP*(IP+1)/2), RES(N), TP(NDMAX), SUR(NDMAX,*), TOL, WK(IP*(IP+9)/2+N)
CHARACTER(1) | OFFSET

3 Description

The proportional hazard model relates the time to an event, usually death or failure, to a number of explanatory variables known as covariates. Some of the observations may be right-censored, that is the exact time to failure is not known, only that it is greater than a known time.
Let ti, for i=1,2,…,n, be the failure time or censored time for the ith observation with the vector of p covariates zi. It is assumed that censoring and failure mechanisms are independent. The hazard function, λ t,z, is the probability that an individual with covariates z fails at time t given that the individual survived up to time t. In the Cox proportional hazards model (see Cox (1972)) λ t,z is of the form:
λ t,z=λ 0 t exp zT β+ω
where λ 0 is the base-line hazard function, an unspecified function of time, β is a vector of unknown arguments and ω is a known offset.
Assuming there are ties in the failure times giving nd<n distinct failure times, t 1<⋯<t nd such that di individuals fail at t i, it follows that the marginal likelihood for β is well approximated (see Kalbfleisch and Prentice (1980)) by:
L=∏i=1 nd exp siT β+ωi ∑l∈R t i exp zlT β+ωl di (1)
where si is the sum of the covariates of individuals observed to fail at t i and R t i is the set of individuals at risk just prior to t i, that is, it is all individuals that fail or are censored at time t i along with all individuals that survive beyond time t i. The maximum likelihood estimates (MLEs) of β, given by β^, are obtained by maximizing (1) using a Newton–Raphson iteration technique that includes step halving and utilizes the first and second partial derivatives of (1) which are given by equations (2) and (3) below:
Uj β= ∂ln⁡L ∂βj =∑i=1 nd s ji-diα ji β=0 (2)
for j=1,2,…,p, where s ji is the jth element in the vector si and
α ji β=∑l∈R t iz jl exp zlT β+ωl ∑l∈R t i exp zlT β+ωl .
Similarly,
I hj β=- ∂2 ln⁡L ∂βh∂βj =∑i=1 nd diγ hji (3)
where
γ hji=∑l∈R t i z hlz jl exp zlT β+ωl ∑l∈R t i exp zlT β+ωl -αhi β α ji β,   h,j= 1,…,p.
Uj β is the jth component of a score vector and I hj β is the h,j element of the observed information matrix I β whose inverse I β-1=I hj β -1 gives the variance-covariance matrix of β.
It should be noted that if a covariate or a linear combination of covariates is monotonically increasing or decreasing with time then one or more of the βj's will be infinite.
If λ 0 t varies across ν strata, where the number of individuals in the kth stratum is nk, for k=1,2,…,ν with n=∑k=1 ν nk, then rather than maximizing (1) to obtain β^, the following marginal likelihood is maximized:
L=∏k=1 ν Lk, (4)
where Lk is the contribution to likelihood for the nk observations in the kth stratum treated as a single sample in (1). When strata are included the covariate coefficients are constant across strata but there is a different base-line hazard function λ 0.
The base-line survivor function associated with a failure time t i, is estimated as exp-H^t i, where
H^t i=∑t j≤t i di∑l∈R t j exp zlT β^+ωl , (5)
where di is the number of failures at time t i. The residual for the lth observation is computed as:
r tl= H^tl exp zlT β^+ωl
where H^tl=H^t i,t i≤tl<t i+1. The deviance is defined as -2×(logarithm of marginal likelihood). There are two ways to test whether individual covariates are significant: the differences between the deviances of nested models can be compared with the appropriate χ 2-distribution; or, the asymptotic normality of the parameter estimates can be used to form z tests by dividing the estimates by their standard errors or the score function for the model under the null hypothesis can be used to form z tests.

4 References

Cox D R (1972) Regression models in life tables (with discussion) J. Roy. Statist. Soc. Ser. B 34 187–220
Gross A J and Clark V A (1975) Survival Distributions: Reliability Applications in the Biomedical Sciences Wiley
Kalbfleisch J D and Prentice R L (1980) The Statistical Analysis of Failure Time Data Wiley

5 Arguments

1:   OFFSET – CHARACTER(1)Input
On entry: indicates if an offset is to be used.
OFFSET='Y'
An offset must be included in OMEGA.
OFFSET='N'
No offset is included in the model.
Constraint: OFFSET='Y' or 'N'.
2:   N – INTEGERInput
On entry: n, the number of data points.
Constraint: N≥2.
3:   M – INTEGERInput
On entry: the number of covariates in array Z.
Constraint: M≥1.
4:   NS – INTEGERInput
On entry: the number of strata. If NS>0 then the stratum for each observation must be supplied in ISI.
Constraint: NS≥0.
5:   Z LDZM – REAL (KIND=nag_wp) arrayInput
On entry: the ith row must contain the covariates which are associated with the ith failure time given in T.
6:   LDZ – INTEGERInput
On entry: the first dimension of the array Z as declared in the (sub)program from which G12BAF is called.
Constraint: LDZ≥N.
7:   ISZ M – INTEGER arrayInput
On entry: indicates which subset of covariates is to be included in the model.
ISZ j≥1
The jth covariate is included in the model.
ISZ j=0
The jth covariate is excluded from the model and not referenced.
Constraint: ISZ j≥0 and at least one and at most n 0-1 elements of ISZ must be nonzero where n 0 is the number of observations excluding any with zero value of ISI.
8:   IP – INTEGERInput
On entry: the number of covariates included in the model as indicated by ISZ.
Constraints:
  • IP≥1;
  • IP=​ number of nonzero values of ​ISZ.
9:   T N – REAL (KIND=nag_wp) arrayInput
On entry: the vector of n failure censoring times.
10:   IC N – INTEGER arrayInput
On entry: the status of the individual at time t given in T.
IC i=0
The ith individual has failed at time T i.
IC i=1
The ith individual has been censored at time T i.
Constraint: IC i=0 or 1, for i=1,2,…,N.
11:   OMEGA* – REAL (KIND=nag_wp) arrayInput
Note: the dimension of the array OMEGA must be at least N if OFFSET='Y', and at least 1 otherwise.
On entry: if OFFSET='Y', the offset, ωi, for i=1,2,…,N. Otherwise OMEGA is not referenced.
12:   ISI* – INTEGER arrayInput
Note: the dimension of the array ISI must be at least N if NS>0, and at least 1 otherwise.
On entry: if NS>0, the stratum indicators which also allow data points to be excluded from the analysis.
If NS=0, ISI is not referenced.
ISI i=k
The ith data point is in the kth stratum, where k=1,2,…,NS.
ISI i=0
The ith data point is omitted from the analysis.
Constraint: if NS>0, 0≤ISI i≤NS and more than IP values of ISI i>0, for i=1,2,…,N.
13:   DEV – REAL (KIND=nag_wp)Output
On exit: the deviance, that is -2×(maximized log marginal likelihood).
14:   B IP – REAL (KIND=nag_wp) arrayInput/Output
On entry: initial estimates of the covariate coefficient arguments β. B j must contain the initial estimate of the coefficient of the covariate in Z corresponding to the jth nonzero value of ISZ.
Suggested value: in many cases an initial value of zero for B j may be used. For other suggestions see Section 9.
On exit: B j contains the estimate β^i, the coefficient of the covariate stored in the ith column of Z where i is the jth nonzero value in the array ISZ.
15:   SE IP – REAL (KIND=nag_wp) arrayOutput
On exit: SE j is the asymptotic standard error of the estimate contained in B j and score function in SC j, for j=1,2,…,IP.
16:   SC IP – REAL (KIND=nag_wp) arrayOutput
On exit: SC j is the value of the score function, Uj β, for the estimate contained in B j.
17:   COV IP×IP+1/2 – REAL (KIND=nag_wp) arrayOutput
On exit: the variance-covariance matrix of the parameter estimates in B stored in packed form by column, i.e., the covariance between the parameter estimates given in B i and B j, j≥i, is stored in COV j j-1/2+i .
18:   RES N – REAL (KIND=nag_wp) arrayOutput
On exit: the residuals, r tl, for l=1,2,…,N.
19:   ND – INTEGEROutput
On exit: the number of distinct failure times.
20:   TP NDMAX – REAL (KIND=nag_wp) arrayOutput
On exit: TP i contains the ith distinct failure time, for i=1,2,…,ND.
21:   SUR NDMAX* – REAL (KIND=nag_wp) arrayOutput
Note: the second dimension of the array SUR must be at least max NS,1.
On exit: if NS=0, SUR i 1 contains the estimated survival function for the ith distinct failure time.
If NS>0, SUR ik contains the estimated survival function for the ith distinct failure time in the kth stratum.
22:   NDMAX – INTEGERInput
On entry: the dimension of the array TP and the first dimension of the array SUR as declared in the (sub)program from which G12BAF is called.
Constraint: NDMAX≥the number of distinct failure times. This is returned in ​ND.
23:   TOL – REAL (KIND=nag_wp)Input
On entry: indicates the accuracy required for the estimation. Convergence is assumed when the decrease in deviance is less than TOL×1.0+CurrentDeviance. This corresponds approximately to an absolute precision if the deviance is small and a relative precision if the deviance is large.
Constraint: TOL≥10×machine precision.
24:   MAXIT – INTEGERInput
On entry: the maximum number of iterations to be used for computing the estimates. If MAXIT is set to 0 then the standard errors, score functions, variance-covariance matrix and the survival function are computed for the input value of β in B but β is not updated.
Constraint: MAXIT≥0.
25:   IPRINT – INTEGERInput
On entry: indicates if the printing of information on the iterations is required.
IPRINT≤0
No printing.
IPRINT≥1
The deviance and the current estimates are printed every IPRINT iterations. When printing occurs the output is directed to the current advisory message unit (see X04ABF).
26:   WK IP×IP+9/2+N – REAL (KIND=nag_wp) arrayWorkspace
27:   IWK 2×N – INTEGER arrayWorkspace
28:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, | OFFSET≠'Y' or 'N',
or | M<1,
or | N<2,
or | NS<0,
or | IP<1,
or | LDZ<N,
or | TOL<10×machine precision,
or | MAXIT<0.
IFAIL=2
On entry, | ISZ i<0 for some i,
or | the value of IP is incompatible with ISZ,
or | IC i≠1 or 0.
or | ISI i<0 or ISI i>NS,
or | number of values of ISZ i>0 is greater than or equal to n 0, the number of observations excluding any with ISI i=0,
or | all observations are censored, i.e., IC i=1 for all i,
or | NDMAX is too small.
IFAIL=3
The matrix of second partial derivatives is singular. Try different starting values or include fewer covariates.
IFAIL=4
Overflow has been detected. Try using different starting values.
IFAIL=5
Convergence has not been achieved in MAXIT iterations. The progress toward convergence can be examined by using a nonzero value of IPRINT. Any non-convergence may be due to a linear combination of covariates being monotonic with time.
Full results are returned.
IFAIL=6
In the current iteration 10 step halvings have been performed without decreasing the deviance from the previous iteration. Convergence is assumed.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

The accuracy is specified by TOL.

8 Parallelism and Performance

G12BAF is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
G12BAF makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

G12BAF uses mean centering which involves subtracting the means from the covariables prior to computation of any statistics. This helps to minimize the effect of outlying observations and accelerates convergence.
If the initial estimates are poor then there may be a problem with overflow in calculating exp βT zi or there may be non-convergence. Reasonable estimates can often be obtained by fitting an exponential model using G02GCF.

10 Example

The data are the remission times for two groups of leukemia patients (see page 242 of Gross and Clark (1975)). A dummy variable indicates which group they come from. An initial estimate is computed using the exponential model and then the Cox proportional hazard model is fitted and parameter estimates and the survival function are printed.

10.1 Program Text

Program Text (g12bafe.f90)

10.2 Program Data

Program Data (g12bafe.d)

10.3 Program Results

Program Results (g12bafe.r)

G12 Chapter Contents
G12 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


G12 Chapter Contents : NAG Library Manual, Mark 26

G12 Chapter Introduction
NAG Library Manual

NAG Library Chapter Contents

G12 – Survival Analysis

G12 Chapter Introduction – a description of the Chapter and an overview of the algorithms available

Routine Name | Mark of Introduction | Purpose
G12AAF Example Text Example Data Example Plot | 15 | nagf_surviv_kaplanmeier Computes Kaplan–Meier (product-limit) estimates of survival probabilities
G12ABF Example Text Example Data | 23 | nagf_surviv_logrank Computes rank statistics for comparing survival curves
G12BAF Example Text Example Data | 17 | nagf_surviv_coxmodel Fits Cox's proportional hazard model
G12ZAF Example Text Example Data | 19 | nagf_surviv_coxmodel_risksets Creates the risk sets associated with the Cox proportional hazards model for fixed covariates
G12 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


G12 Chapter Introduction : NAG Library, Mark 26

G12 Chapter Contents
NAG Library Manual

NAG Library Chapter Introduction

G12 – Survival Analysis

▸▿ Contents

1 Scope of the Chapter
▸▿ 2 Background to the Problems
2.1 Introduction to Terminology
2.2 Rank Statistics
2.3 Estimating the Survivor Function and Hazard Plotting
2.4 Proportional Hazard Models
2.5 Cox's Proportional Hazard Model
3 Recommendations on Choice and Use of Available Routines
4 Functionality Index
5 Auxiliary Routines Associated with Library Routine Arguments
6 Routines Withdrawn or Scheduled for Withdrawal
7 References

1 Scope of the Chapter

This chapter is concerned with statistical techniques used in the analysis of survival/reliability/failure time data.
Other chapters contain routines which are also used to analyse this type of data. Chapter G02 contains generalized linear models, Chapter G07 contains routines to fit distribution models, and Chapter G08 contains rank based methods.

2 Background to the Problems

2.1 Introduction to Terminology

This chapter is concerned with the analysis on the time, t, to a single event. This type of analysis occurs commonly in two areas. In medical research it is known as survival analysis and is often the time from the start of treatment to the occurrence of a particular condition or of death. In engineering it is concerned with reliability and the analysis of failure times, that is how long a component can be used until it fails. In this chapter the time t will be referred to as the failure time.
Let the probability density function of the failure time be f t, then the survivor function, S t, which is the probability of surviving to at least time t, is given by
S t=∫t∞f τ dτ=1-F t
where F t is the cumulative density function. The hazard function, λ t, is the probability that failure occurs at time t given that the individual survived up to time t, and is given by
λ t=f t/S t.
The cumulative hazard rate is defined as
Λ t=∫0 t λ τ dτ ,
hence S t=e-Λ t.
It is common in survival analysis for some of the data to be right-censored. That is, the exact failure time is not known, only that failure occurred after a known time. This may be due to the experiment being terminated before all the individuals have failed, or an individual being removed from the experiment for a reason not connected with effects being tested in the experiment. The presence of censored data leads to complications in the analysis.

2.2 Rank Statistics

There are a number of different rank statistics described in the literature, the most common being the logrank statistic. All of these statistics are designed to test the null hypothesis
  • H 0 : S 1 t = S 2 t = ⋯ = S g t , ∀ t ≤ τ
where Sj is the survivor function for group j, g is the number of groups being tested and τ is the largest observed time, against the alternative hypothesis
  • H 1 : at least one of the S j t differ, for some t ≤ τ .
A rank statistics T is calculated as follows:
Let ti , for i = 1 , 2 , … , n d , denote the list of distinct failure times across all g groups and wi a series of nd weights.
Let d ij denote the number of failures at time ti in group j and n ij denote the number of observations in the group j that are known to have not failed prior to time ti, i.e., the size of the risk set for group j at time ti. If a censored observation occurs at time ti then that observation is treated as if the censoring had occurred slightly after ti and therefore the observation is counted as being part of the risk set at time ti.
Finally let
di = ∑ j=1 g d ij   and   ni = ∑ j=1 g n ij .
The (weighted) number of observed failures in the jth group, Oj, is therefore given by
Oj = ∑ i=1 nd wi d ij
and the (weighted) number of expected failures in the jth group, Ej, by
Ej = ∑ i=1 nd wi n ij di ni
and if x denote the vector of differences x = O 1 - E 1 , O 2 - E 2 , … , Og - Eg
V jk = ∑ i=1 nd w i 2 di ni - di ni n i k I jk - n ij n ik n i 2 ni - 1
where I jk = 1 if j=k and 0 otherwise, then the rank statistic, T, is calculated as
T = x V- xT
where V- denotes a generalized inverse of the matrix V.
Under the null hypothesis, T ∼ χ ν 2 where the degrees of freedom, ν, is taken as the rank of the matrix V.
The different rank statistics are defined by using different weights in the above calculations, for example
logrank statistic | wi=1
Wilcoxon rank statistic | wi=ni
Tarone–Ware rank statistic | wi=ni
Peto–Peto rank statistic | wi = S~ ti where S~ ti = ∏ tj ≤ ti nj - dj + 1 nj+1

2.3 Estimating the Survivor Function and Hazard Plotting

The most common estimate of the survivor function for censored data is the Kaplan–Meier or product-limit estimate,
S^t=∏j=1 i nj-dj nj ,  ti≤t<t i+1
where dj is the number of failures occurring at time tj out of nj surviving to tj. This is a step function with steps at each failure time but not at censored times.
As S t=e-Λ t the cumulative hazard rate can be estimated by
Λ^t=-log S^t.
A plot of Λ^t or log Λ^t against t or log t is often useful in identifying a suitable parametric model for the survivor times. The following relationships can be used in the identification.
(a) | Exponential distribution: Λ t=λt.
(b) | Weibull distribution: log Λ t=log⁡λ+γ log t.
(c) | Gompertz distribution: log Λ t=log⁡λ+γt.
(d) | Extreme value (smallest) distribution: log Λ t=λ t-γ.

2.4 Proportional Hazard Models

Often in the analysis of survival data the relationship between the hazard function and the number of explanatory variables or covariates is modelled. The covariates may be, for example, group or treatment indicators or measures of the state of the individual at the start of the observational period. There are two types of covariate time independent covariates such as those described above which do not change value during the observational period and time dependent covariates. The latter can be classified as either external covariates, in which case they are not directly involved with the failure mechanism, or as internal covariates which are time dependent measurements taken on the individual.
The most common function relating the covariates to the hazard function is the proportional hazard function
λ t,z=λ 0 t exp βT z
where λ 0 t is a baseline hazard function, z is a vector of covariates and β is a vector of unknown parameters. The assumption is that the covariates have a multiplicative effect on the hazard.
The form of λ 0 t can be one of the distributions considered above or a nonparametric function. In the case of the exponential, Weibull and extreme value distributions the proportional hazard model can be fitted to censored data using the method described by Aitkin and Clayton (1980) which uses a generalized linear model with Poisson errors. Other possible models are the gamma distribution and the log-normal distribution.

2.5 Cox's Proportional Hazard Model

Rather than using a specified form for the hazard function, Cox (1972) considered the case when λ 0 t was an unspecified function of time. To fit such a model assuming fixed covariates a marginal likelihood is used. For each of the times at which a failure occurred, ti, the set of those who were still in the study is considered this includes any that were censored at ti. This set is known as the risk set for time ti and denoted by R ti. Given the risk set the probability that out of all possible sets of di subjects that could have failed the actual observed di cases failed can be written as
exp siT β ∑exp zlT β (1)
where si is the sum of the covariates of the di individuals observed to fail at ti and the summation is over all distinct sets of ni individuals drawn from R ti. This leads to a complex likelihood. If there are no ties in failure times the likelihood reduces to
L=∏i=1 nd exp ziT β ∑l∈R ti exp zlT β (2)
where nd is the number of distinct failure times. For cases where there are ties the following approximation, due to Peto [2], can be used:
L=∏i=1 nd exp siT β ∑l∈R ti exp zlT β di . (3)
Having fitted the model an estimate of the baseline survivor function (derived from λ 0 t and the residuals) can be computed to examine the suitability of the model, in particular the proportional hazard assumption.

3 Recommendations on Choice and Use of Available Routines

The following routines are available.
G12AAF computes Kaplan–Meier estimates of the survivor function and their standard deviations.
G12ABF performs a comparison of survival curves using rank statistics.
G12BAF fits the Cox proportional hazards model for fixed covariates.
G12ZAF creates the risk sets associated with the Cox proportional hazards model for fixed covariates.
Depending on the rank statistic required, it may be necessary to call G12ABF twice, once to calculate the number of failures (di) and the total number of observations (ni) at time ti, to facilitate in the computation of the required weights, and once to calculate the required rank statistics.
The following routines from other chapters may also be useful in the analysis of survival data.
G01MBF computes the reciprocal of Mills' Ratio, that is the hazard rate for the Normal distribution.
G02GCF fits a generalized linear model with Poisson errors (see Aitkin and Clayton (1980)).
G02GDF fits a generalized linear model with gamma errors.
G07BBF fits a Normal distribution to censored data.
G07BEF fits a Weibull distribution to censored data.
G08RBF fits a linear model using likelihood based on ranks to censored data (see Kalbfleisch and Prentice (1980)).
G11CAF fits a conditional logistic model. When applied to the risk sets generated by G12ZAF it fits the Cox proportional hazards model by exact marginal likelihood in the presence of tied observations.

4 Functionality Index

Cox's proportional hazard model,
create the risk sets G12ZAF
parameter estimates and other statistics G12BAF
Survival,
Rank statistics G12ABF
Survivor function G12AAF

5 Auxiliary Routines Associated with Library Routine Arguments

None.

6 Routines Withdrawn or Scheduled for Withdrawal

None.

7 References

Aitkin M and Clayton D (1980) The fitting of exponential, Weibull and extreme value distributions to complex censored survival data using GLIM Appl. Statist. 29 156–163
Cox D R (1972) Regression models in life tables (with discussion) J. Roy. Statist. Soc. Ser. B 34 187–220
Gross A J and Clark V A (1975) Survival Distributions: Reliability Applications in the Biomedical Sciences Wiley
Kalbfleisch J D and Prentice R L (1980) The Statistical Analysis of Failure Time Data Wiley
G12 Chapter Contents
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


G12ZAF : NAG Library, Mark 26

G12 Chapter Contents
G12 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

G12ZAF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

G12ZAF creates the risk sets associated with the Cox proportional hazards model for fixed covariates.

2 Specification

SUBROUTINE G12ZAF ( N, M, NS, Z, LDZ, ISZ, IP, T, IC, ISI, NUM, IXS, NXS, X, MXN, ID, ND, TP, IRS, IFAIL)
INTEGER | N, M, NS, LDZ, ISZ(M), IP, IC(N), ISI(*), NUM, IXS(MXN), NXS, MXN, ID(MXN), ND, IRS(N), IFAIL
REAL (KIND=nag_wp) | Z(LDZ,M), T(N), X(MXN,IP), TP(N)

3 Description

The Cox proportional hazards model (see Cox (1972)) relates the time to an event, usually death or failure, to a number of explanatory variables known as covariates. Some of the observations may be right-censored, that is, the exact time to failure is not known, only that it is greater than a known time.
Let ti, for i=1,2,…,n, be the failure time or censored time for the ith observation with the vector of p covariates zi. It is assumed that censoring and failure mechanisms are independent. The hazard function, λ t,z, is the probability that an individual with covariates z fails at time t given that the individual survived up to time t. In the Cox proportional hazards model, λ t,z is of the form
λ t,z=λ 0 t exp zT β,
where λ 0 is the base-line hazard function, an unspecified function of time, and β is a vector of unknown arguments. As λ 0 is unknown, the arguments β are estimated using the conditional or marginal likelihood. This involves considering the covariate values of all subjects that are at risk at the time when a failure occurs. The probability that the subject that failed had their observed set of covariate values is computed.
The risk set at a failure time consists of those subjects that fail or are censored at that time and those who survive beyond that time. As risk sets are computed for every distinct failure time, it should be noted that the combined risk sets may be considerably larger than the original data. If the data can be considered as coming from different strata such that λ 0 varies from strata to strata but β remains constant, then G12ZAF will return a factor that indicates to which risk set/strata each member of the risk sets belongs rather than just to which risk set.
Given the risk sets the Cox proportional hazards model can then be fitted using a Poisson generalized linear model (G02GCF with G04EAF to compute dummy variables) using Breslow's approximation for ties (see Breslow (1974)). This will give the same fit as G12BAF. If the exact treatment of ties in discrete time is required, as given by Cox (1972), then the model is fitted as a conditional logistic model using G11CAF.

4 References

Breslow N E (1974) Covariate analysis of censored survival data Biometrics 30 89–99
Cox D R (1972) Regression models in life tables (with discussion) J. Roy. Statist. Soc. Ser. B 34 187–220
Gross A J and Clark V A (1975) Survival Distributions: Reliability Applications in the Biomedical Sciences Wiley

5 Arguments

1:   N – INTEGERInput
On entry: n, the number of data points.
Constraint: N≥2.
2:   M – INTEGERInput
On entry: the number of covariates in array Z.
Constraint: M≥1.
3:   NS – INTEGERInput
On entry: the number of strata. If NS>0 then the stratum for each observation must be supplied in ISI.
Constraint: NS≥0.
4:   Z LDZM – REAL (KIND=nag_wp) arrayInput
On entry: the ith row must contain the covariates which are associated with the ith failure time given in T.
5:   LDZ – INTEGERInput
On entry: the first dimension of the array Z as declared in the (sub)program from which G12ZAF is called.
Constraint: LDZ≥N.
6:   ISZ M – INTEGER arrayInput
On entry: indicates which subset of covariates are to be included in the model.
ISZ j≥1
The jth covariate is included in the model.
ISZ j=0
The jth covariate is excluded from the model and not referenced.
Constraint: ISZ j≥0 and at least one value must be nonzero.
7:   IP – INTEGERInput
On entry: p, the number of covariates included in the model as indicated by ISZ.
Constraint: IP= the number of nonzero values of ISZ.
8:   T N – REAL (KIND=nag_wp) arrayInput
On entry: the vector of n failure censoring times.
9:   IC N – INTEGER arrayInput
On entry: the status of the individual at time t given in T.
IC i=0
Indicates that the ith individual has failed at time T i.
IC i=1
Indicates that the ith individual has been censored at time T i.
Constraint: IC i=0 or 1, for i=1,2,…,N.
10:   ISI* – INTEGER arrayInput
Note: the dimension of the array ISI must be at least N if NS>0, and at least 1 otherwise.
On entry: if NS>0, the stratum indicators which also allow data points to be excluded from the analysis.
If NS=0, ISI is not referenced.
ISI i=k
Indicates that the ith data point is in the kth stratum, where k=1,2,…,NS.
ISI i=0
Indicates that the ith data point is omitted from the analysis.
Constraint: if NS>0, 0≤ISI i≤NS, for i=1,2,…,N.
11:   NUM – INTEGEROutput
On exit: the number of values in the combined risk sets.
12:   IXS MXN – INTEGER arrayOutput
On exit: the factor giving the risk sets/strata for the data in X and ID.
If NS=0 or 1, IXS i=l for members of the lth risk set.
If NS>1, IXS i=j-1×ND+l for the observations in the lth risk set for the jth strata.
13:   NXS – INTEGEROutput
On exit: the number of levels for the risk sets/strata factor given in IXS.
14:   X MXNIP – REAL (KIND=nag_wp) arrayOutput
On exit: the first NUM rows contain the values of the covariates for the members of the risk sets.
15:   MXN – INTEGERInput
On entry: the first dimension of the array X and the dimension of the arrays IXS and ID as declared in the (sub)program from which G12ZAF is called.
Constraint: MXN must be sufficiently large for the arrays to contain the expanded risk sets. The size will depend on the pattern of failures times and censored times. The minimum value will be returned in NUM unless the routine exits with IFAIL=1 or 2.
16:   ID MXN – INTEGER arrayOutput
On exit: indicates if the member of the risk set given in X failed.
ID i=1 if the member of the risk set failed at the time defining the risk set and ID i=0 otherwise.
17:   ND – INTEGEROutput
On exit: the number of distinct failure times, i.e., the number of risk sets.
18:   TP N – REAL (KIND=nag_wp) arrayOutput
On exit: TP i contains the ith distinct failure time, for i=1,2,…,ND.
19:   IRS N – INTEGER arrayOutput
On exit: indicates rows in X and elements in IXS and ID corresponding to the risk sets. The first risk set corresponding to failure time TP 1 is given by rows 1 to IRS 1. The lth risk set is given by rows IRS l-1+1 to IRS l, for l=1,2,…,ND.
20:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, | M<1,
or | N<2,
or | NS<0,
or | LDZ<N.
IFAIL=2
On entry, | ISZ i<0 for some i,
or | the value of IP is incompatible with ISZ,
or | IC i≠1 or 0.
or | NS>0 and ISI i<0,
or | NS>1 and ISI i>NS.
IFAIL=3
MXN is too small, the minimum value is returned in NUM.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

Not applicable.

8 Parallelism and Performance

G12ZAF is not threaded in any implementation.

9 Further Comments

When there are strata present, i.e., NS>1, not all the NXS groups may be present.

10 Example

The data are the remission times for two groups of leukemia patients (see page 242 of Gross and Clark (1975)). A dummy variable indicates which group they come from. The risk sets are computed using G12ZAF and the Cox's proportional hazard model is fitted using G11CAF.

10.1 Program Text

Program Text (g12zafe.f90)

10.2 Program Data

Program Data (g12zafe.d)

10.3 Program Results

Program Results (g12zafe.r)

G12 Chapter Contents
G12 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


G13AAF : NAG Library, Mark 26

G13 Chapter Contents
G13 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

G13AAF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

G13AAF carries out non-seasonal and seasonal differencing on a time series. Information which allows the original series to be reconstituted from the differenced series is also produced. This information is required in time series forecasting.

2 Specification

SUBROUTINE G13AAF ( X, NX, ND, NDS, NS, XD, NXD, IFAIL)
INTEGER | NX, ND, NDS, NS, NXD, IFAIL
REAL (KIND=nag_wp) | X(NX), XD(NX)

3 Description

Let ∇d∇sD xi be the ith value of a time series xi, for i=1,2,…,n after non-seasonal differencing of order d and seasonal differencing of order D (with period or seasonality s). In general,
∇d∇sD xi | = | ∇d-1∇sD x i+1-∇d-1∇sD xi | d>0
∇d∇sD xi | = | ∇d∇s D-1 x i+s-∇d∇s D-1 xi | D>0
Non-seasonal differencing up to the required order d is obtained using
∇1 xi | = | x i+1-xi | for i=1,2,…,n-1
∇2 xi | = | ∇1 x i+1-∇1 xi | for i=1,2,…,n-2
⋮ |  |  |
∇d xi | = | ∇d-1 x i+1-∇d-1 xi | for i=1,2,…,n-d
Seasonal differencing up to the required order D is then obtained using
∇d∇s 1 xi | = | ∇d x i+s-∇d xi | for i=1,2,…,n-d-s
∇d∇s 2 xi | = | ∇d∇s 1 x i+s-∇d∇s 1 xi | for i=1,2,…,n-d-2 s
⋮ |  |  |
∇d∇sD xi | = | ∇d∇s D-1 x i+s-∇d∇s D-1 xi | for i=1,2,…,n-d-D×s
Mathematically, the sequence in which the differencing operations are performed does not affect the final resulting series of m=n-d-D×s values.

4 References

None.

5 Arguments

1:   X NX – REAL (KIND=nag_wp) arrayInput
On entry: the undifferenced time series, xi, for i=1,2,…,n.
2:   NX – INTEGERInput
On entry: n, the number of values in the undifferenced time series.
Constraint: NX>ND+NDS×NS.
3:   ND – INTEGERInput
On entry: d, the order of non-seasonal differencing.
Constraint: ND≥0.
4:   NDS – INTEGERInput
On entry: D, the order of seasonal differencing.
Constraint: NDS≥0.
5:   NS – INTEGERInput
On entry: s, the seasonality.
Constraints:
  • if NDS>0, NS>0;
  • if NDS=0, NS≥0.
6:   XD NX – REAL (KIND=nag_wp) arrayOutput
On exit: the differenced values in elements 1 to NXD, and reconstitution data in the remainder of the array.
7:   NXD – INTEGEROutput
On exit: the number of differenced values in the array XD.
8:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, | ND<0,
or | NDS<0,
or | NS<0,
or | NS=0 when NDS>0.
IFAIL=2
On entry, NX≤ND+NDS×NS.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

The computations are believed to be stable.

8 Parallelism and Performance

G13AAF is not threaded in any implementation.

9 Further Comments

The time taken by G13AAF is approximately proportional to ND+NDS×NX.

10 Example

This example reads in a set of data consisting of 20 observations from a time series. Non-seasonal differencing of order 2 and seasonal differencing of order 1 (with seasonality of 4) are applied to the input data, giving an output array holding 14 differenced values and 6 values which can be used to reconstitute the output array.

10.1 Program Text

Program Text (g13aafe.f90)

10.2 Program Data

Program Data (g13aafe.d)

10.3 Program Results

Program Results (g13aafe.r)

G13 Chapter Contents
G13 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


G13ABF : NAG Library, Mark 26

G13 Chapter Contents
G13 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

G13ABF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

G13ABF computes the sample autocorrelation function of a time series. It also computes the sample mean, the sample variance and a statistic which may be used to test the hypothesis that the true autocorrelation function is zero.

2 Specification

SUBROUTINE G13ABF ( X, NX, NK, XM, XV, R, STAT, IFAIL)
INTEGER | NX, NK, IFAIL
REAL (KIND=nag_wp) | X(NX), XM, XV, R(NK), STAT

3 Description

The data consists of n observations xi, for i=1,2,…,n from a time series.
The quantities calculated are
(a) The sample mean
x-=∑i=1 n xi n.
(b) The sample variance (for n≥2)
s 2=∑i=1 n xi-x- 2 n-1 .
(c) The sample autocorrelation coefficients of lags k=1,2,…,K, where K is a user-specified maximum lag, and K<n, n>1.
The coefficient of lag k is defined as
rk=∑i=1 n-k xi-x-x i+k-x- ∑i=1 n xi-x- 2 .
See page 496 of Box and Jenkins (1976) for further details.
(d) A test statistic defined as
STAT=n∑k= 1 K rk 2,
which can be used to test the hypothesis that the true autocorrelation function is identically zero.
If n is large and K is much smaller than n, STAT has a χK 2 distribution under the hypothesis of a zero autocorrelation function. Values of STAT in the upper tail of the distribution provide evidence against the hypothesis; G01ECF can be used to compute the tail probability.
Section 8.2.2 of Box and Jenkins (1976) provides further details of the use of STAT.

4 References

Box G E P and Jenkins G M (1976) Time Series Analysis: Forecasting and Control (Revised Edition) Holden–Day

5 Arguments

1:   X NX – REAL (KIND=nag_wp) arrayInput
On entry: the time series, xi, for i=1,2,…,n.
2:   NX – INTEGERInput
On entry: n, the number of values in the time series.
Constraint: NX>1.
3:   NK – INTEGERInput
On entry: K, the number of lags for which the autocorrelations are required. The lags range from 1 to K and do not include zero.
Constraint: 0<NK<NX.
4:   XM – REAL (KIND=nag_wp)Output
On exit: the sample mean of the input time series.
5:   XV – REAL (KIND=nag_wp)Output
On exit: the sample variance of the input time series.
6:   R NK – REAL (KIND=nag_wp) arrayOutput
On exit: the sample autocorrelation coefficient relating to lag k, for k=1,2,…,K.
7:   STAT – REAL (KIND=nag_wp)Output
On exit: the statistic used to test the hypothesis that the true autocorrelation function of the time series is identically zero.
8:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, | NX≤NK,
or | NX≤1,
or | NK≤0.
IFAIL=2
On entry, all values of X are practically identical, giving zero variance. In this case R and STAT are undefined on exit.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

The computations are believed to be stable.

8 Parallelism and Performance

G13ABF is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
G13ABF makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

If n<100, or K<10 log n then the autocorrelations are calculated directly and the time taken by G13ABF is approximately proportional to nK, otherwise the autocorrelations are calculated by utilizing fast fourier transforms (FFTs) and the time taken is approximately proportional to n log n. If FFTs are used then G13ABF internally allocates approximately 4 n real elements.
If the input series for G13ABF was generated by differencing using G13AAF, ensure that only the differenced values are input to G13ABF, and not the reconstituting information.

10 Example

In the example below, a set of 50 values of sunspot counts is used as input. The first 10 autocorrelations are computed.

10.1 Program Text

Program Text (g13abfe.f90)

10.2 Program Data

Program Data (g13abfe.d)

10.3 Program Results

Program Results (g13abfe.r)

This plot shows the autocorrelations for all possible lag values. Reference lines are given at ±z 0.975/n.
GnuplotProduced by GNUPLOT 4.6 patchlevel 3 −0.6 −0.4 −0.2 0 0.2 0.4 0.6 0.8 1 0 10 20 30 40 50 ACF Lag Example Program Sample Autocorrelation Coefficients gnuplot_plot_1 gnuplot_plot_2 gnuplot_plot_3
G13 Chapter Contents
G13 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


G13ACF : NAG Library, Mark 26

G13 Chapter Contents
G13 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

G13ACF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

G13ACF calculates partial autocorrelation coefficients given a set of autocorrelation coefficients. It also calculates the predictor error variance ratios for increasing order of finite lag autoregressive predictor, and the autoregressive parameters associated with the predictor of maximum order.

2 Specification

SUBROUTINE G13ACF ( R, NK, NL, P, V, AR, NVL, IFAIL)
INTEGER | NK, NL, NVL, IFAIL
REAL (KIND=nag_wp) | R(NK), P(NL), V(NL), AR(NL)

3 Description

The data consist of values of autocorrelation coefficients r 1,r 2,…,rK, relating to lags 1,2,…,K. These will generally (but not necessarily) be sample values such as may be obtained from a time series xt using G13ABF.
The partial autocorrelation coefficient at lag l may be identified with the parameter p l,l in the autoregression
xt = cl + p l,1 x t-1 + p l,2 x t-2 +⋯+ p l,l x t-l + e l,t
where e l,t is the predictor error.
The first subscript l of p l,l and e l,t emphasizes the fact that the parameters will in general alter as further terms are introduced into the equation (i.e., as l is increased).
The parameters are determined from the autocorrelation coefficients by the Yule–Walker equations
ri = p l,1 r i-1 + p l,2 r i-2 +⋯+ p l,l r i-l ,   i=1,2,…,l
taking rj=r j when j<0, and r 0=1.
The predictor error variance ratio vl=var e l,t/var xt is defined by
vl = 1- p l,1 r 1 - p l,2 r 2 -⋯- p l,l rl .
The above sets of equations are solved by a recursive method (the Durbin–Levinson algorithm). The recursive cycle applied for l=1,2,…,L-1, where L is the number of partial autocorrelation coefficients required, is initialized by setting p 1,1=r 1 and v 1=1-r 12.
Then
p l + 1 , l + 1 = r l + 1 - p l , 1 r l - p l , 2 r l - 1 - ⋯ - p l , l r 1 / v l p l + 1 , j = p l , j - p l + 1 , l + 1 p l , l + 1 - j ,   j=1,2,…,l v l + 1 = v l 1 - p l + 1 , l + 1 1 + p l + 1 , l + 1 .
If the condition p l,l≥1 occurs, say when l=l 0, it indicates that the supplied autocorrelation coefficients do not form a positive definite sequence (see Hannan (1960)), and the recursion is not continued. The autoregressive parameters are overwritten at each recursive step, so that upon completion the only available values are p Lj, for j=1,2,…,L, or p l 0-1,j if the recursion has been prematurely halted.

4 References

Box G E P and Jenkins G M (1976) Time Series Analysis: Forecasting and Control (Revised Edition) Holden–Day
Durbin J (1960) The fitting of time series models Rev. Inst. Internat. Stat. 28 233
Hannan E J (1960) Time Series Analysis Methuen

5 Arguments

1:   R NK – REAL (KIND=nag_wp) arrayInput
On entry: the autocorrelation coefficient relating to lag k, for k=1,2,…,K.
2:   NK – INTEGERInput
On entry: K, the number of lags. The lags range from 1 to K and do not include zero.
Constraint: NK>0.
3:   NL – INTEGERInput
On entry: L, the number of partial autocorrelation coefficients required.
Constraint: 0<NL≤NK.
4:   P NL – REAL (KIND=nag_wp) arrayOutput
On exit: P l contains the partial autocorrelation coefficient at lag l, p l,l, for l=1,2,…,NVL.
5:   V NL – REAL (KIND=nag_wp) arrayOutput
On exit: V l contains the predictor error variance ratio vl, for l=1,2,…,NVL.
6:   AR NL – REAL (KIND=nag_wp) arrayOutput
On exit: the autoregressive parameters of maximum order, i.e., p Lj if IFAIL=0, or p l 0-1,j if IFAIL=3, for j=1,2,…,NVL.
7:   NVL – INTEGEROutput
On exit: the number of valid values in each of P, V and AR. Thus in the case of premature termination at iteration l 0 (see Section 3), NVL is returned as l 0-1.
8:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, | NK≤0,
or | NL≤0,
or | NK<NL.
IFAIL=2
On entry, the autocorrelation coefficient of lag 1 has an absolute value greater than or equal to 1.0; no recursions could be performed.
IFAIL=3
Recursion has been prematurely terminated; the supplied autocorrelation coefficients do not form a positive definite sequence (see Section 3). Argument NVL returns the number of valid values computed.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

The computations are believed to be stable.

8 Parallelism and Performance

G13ACF is not threaded in any implementation.

9 Further Comments

The time taken by G13ACF is proportional to NVL 2.

10 Example

This example uses an input series of 10 sample autocorrelation coefficients derived from the original series of sunspot numbers generated by the G13ABF example program. The results show five values of each of the three output arrays: partial autocorrelation coefficients, predictor error variance ratios and autoregressive parameters. All of these were valid.

10.1 Program Text

Program Text (g13acfe.f90)

10.2 Program Data

Program Data (g13acfe.d)

10.3 Program Results

Program Results (g13acfe.r)

This plot shows the partial autocorrelations for all possible lag values. Reference lines are given at ±z 0.975/n.
GnuplotProduced by GNUPLOT 4.6 patchlevel 3 −0.6 −0.4 −0.2 0 0.2 0.4 0.6 0.8 1 0 10 20 30 40 50 PACF Lag Example Program Partial Autocorrelation Coefficients gnuplot_plot_1 gnuplot_plot_2 gnuplot_plot_3
G13 Chapter Contents
G13 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


G13ADF : NAG Library, Mark 26

G13 Chapter Contents
G13 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

G13ADF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

G13ADF calculates preliminary estimates of the parameters of an autoregressive integrated moving average (ARIMA) model from the autocorrelation function of the appropriately differenced times series.

2 Specification

SUBROUTINE G13ADF ( MR, R, NK, XV, NPAR, WA, NWA, PAR, RV, ISF, IFAIL)
INTEGER | MR(7), NK, NPAR, NWA, ISF(4), IFAIL
REAL (KIND=nag_wp) | R(NK), XV, WA(NWA), PAR(NPAR), RV

3 Description

Preliminary estimates of the p non-seasonal autoregressive parameters ϕ 1,ϕ 2,…,ϕp and the q non-seasonal moving average parameters θ 1,θ 2,…,θq may be obtained from the sample autocorrelations relating to lags 1 to p+q, i.e., r 1,…,r p+q, of the differenced ∇d∇sD xt, where xt is assumed to follow a (possibly) seasonal ARIMA model (see Section 3 in G13AEF for the specification of an ARIMA model).
Taking r 0=1 and r-k=rk, the ϕi, for i=1,2,…,p are the solutions to the equations
r q+i-1 ϕ 1+ r q+i-2 ϕ 2 +⋯+ r q+i-p ϕp = r q+i ,   i=1,2,…,p.
The θj, for j=1,2,…,q, are obtained from the solutions to the equations
cj=τ 0τj+τ 1τ j+1+⋯+τ q+jτq,   j=0,1,…,q
(Cramer Wold-factorization), by setting
θj=-τjτ 0 ,
where cj are the ‘covariances’ modified in a two stage process by the autoregressive parameters.
Stage 1:
dj=rj-ϕ 1r j-1-⋯-ϕpr j-p, j=0,1,…,q; dj=0, j=q+1,q+2,…,p+q.
Stage 2:
cj=dj-ϕ 1d j+ 1-ϕ 2d j+ 2-⋯-ϕpd j+p,   j= 0,1,…,q.
The P seasonal autoregressive parameters Φ 1,Φ 2,…,ΦP and the Q seasonal moving average parameters Θ 1,Θ 2,…,ΘQ are estimated in the same way as the non-seasonal parameters, but each rj is replaced in the calculation by r s×j, where s is the seasonal period.
An estimate of the residual variance is obtained by successively reducing the sample variance, first for non-seasonal, and then for seasonal, parameter estimates. If moving average parameters are estimated, the variance is reduced by a multiplying factor of τ 02, but otherwise by c 0.

4 References

Box G E P and Jenkins G M (1976) Time Series Analysis: Forecasting and Control (Revised Edition) Holden–Day

5 Arguments

1:   MR 7 – INTEGER arrayInput
On entry: the orders vector p,d,q,P,D,Q,s of the ARIMA model whose parameters are to be estimated. p, q, P and Q refer respectively to the number of autoregressive ϕ, moving average θ, seasonal autoregressive Φ and seasonal moving average Θ parameters. d, D and s refer respectively to the order of non-seasonal differencing, the order of seasonal differencing and the seasonal period.
Constraints:
  • p,d,q,P,D,Q,s≥0;
  • p+q+P+Q>0;
  • s≠1;
  • if s=0, P+D+Q=0;
  • if s>1, P+D+Q>0.
2:   R NK – REAL (KIND=nag_wp) arrayInput
On entry: the autocorrelations (starting at lag 1), which must have been calculated after the time series has been appropriately differenced.
Constraint: -1.0≤R i≤1.0, for i=1,2,…,NK.
3:   NK – INTEGERInput
On entry: the maximum lag of the autocorrelations in array R.
Constraint: NK≥max p+q,s×P+Q.
4:   XV – REAL (KIND=nag_wp)Input
On entry: the series sample variance, calculated after appropriate differencing has been applied to the series.
Constraint: XV>0.0.
5:   NPAR – INTEGERInput
On entry: the exact number of parameters specified in the model by array MR.
Constraint: NPAR=p+q+P+Q.
6:   WA NWA – REAL (KIND=nag_wp) arrayWorkspace
7:   NWA – INTEGERInput
On entry: the amount of workspace available.
Constraint: if MR=p,d,q,P,D,Q,s and p′=max p,P and q′=max q,Q, NWA≥max p′2+p′,4 q′+1.
8:   PAR NPAR – REAL (KIND=nag_wp) arrayOutput
On exit: the first NPAR elements of PAR contain the preliminary estimates of the ARIMA model parameters, in standard order.
9:   RV – REAL (KIND=nag_wp)Output
On exit: an estimate of the residual variance of the preliminarily estimated model.
10:   ISF 4 – INTEGER arrayOutput
On exit: contains success/failure indicators, one for each of the four types of parameter (autoregressive, moving average, seasonal autoregressive, seasonal moving average).
The indicator has the interpretation:
-0 | No parameter of this type is in the model.
-1 | Parameters of this type appear in the model and satisfactory preliminary estimates of this type were obtained.
-1 | Parameters of this type appear in the model but satisfactory preliminary estimates of this type were not obtainable. The estimates of this type of parameter were set to 0.0 in array PAR.
11:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, the orders vector MR is invalid. One of the constraints in Section 5 has been violated.
IFAIL=2
On entry, NK<max p+q,s×P+Q. There are not enough autocorrelations to enable the required model to be estimated.
IFAIL=3
On entry, at least one element of R lies outside the range -1.0,1.0.
IFAIL=4
On entry, XV≤0.0.
IFAIL=5
On entry, NPAR≠p+q+P+Q.
IFAIL=6
On entry, the workspace array WA is too small. See Section 5 for the minimum size formula.
IFAIL=7
Satisfactory parameter estimates could not be obtained for all parameter types in the model. Inspect array ISF for indicators of the parameter type(s) which could not be estimated.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

The performance of the algorithm is conditioned by the roots of the autoregressive and moving average operators. If these are not close to unity in modulus, the errors, e, should satisfy e<100 ε where ε is machine precision.

8 Parallelism and Performance

G13ADF is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
G13ADF makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The time taken by G13ADF is approximately proportional to p 3+q 2+P 3+Q 2.

10 Example

This example reads the sample autocorrelations to lag 40 and the sample variance of the lagged and doubly differenced series of airline passenger totals (Box and Jenkins example series G (see Box and Jenkins (1976))). Preliminary estimates of the parameters of the 0,1,1,0,1,1,12 model are obtained by a call to G13ADF.

10.1 Program Text

Program Text (g13adfe.f90)

10.2 Program Data

Program Data (g13adfe.d)

10.3 Program Results

Program Results (g13adfe.r)

G13 Chapter Contents
G13 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


G13AEF : NAG Library, Mark 26

G13 Chapter Contents
G13 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

G13AEF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

G13AEF fits a seasonal autoregressive integrated moving average (ARIMA) model to an observed time series, using a nonlinear least squares procedure incorporating backforecasting. Parameter estimates are obtained, together with appropriate standard errors. The residual series is returned, and information for use in forecasting the time series is produced for use by the routines G13AGF and G13AHF.
The estimation procedure is iterative, starting with initial parameter values such as may be obtained using G13ADF. It continues until a specified convergence criterion is satisfied, or until a specified number of iterations has been carried out. The progress of the procedure can be monitored by means of a user-supplied routine.

2 Specification

SUBROUTINE G13AEF ( MR, PAR, NPAR, C, KFC, X, NX, ICOUNT, EX, EXR, AL, IEX, S, G, IGH, SD, H, LDH, ST, IST, NST, PIV, KPIV, NIT, ITC, ZSP, KZSP, ISF, WA, IWA, HC, IFAIL)
INTEGER | MR(7), NPAR, KFC, NX, ICOUNT(6), IEX, IGH, LDH, IST, NST, KPIV, NIT, ITC, KZSP, ISF(4), IWA, IFAIL
REAL (KIND=nag_wp) | PAR(NPAR), C, X(NX), EX(IEX), EXR(IEX), AL(IEX), S, G(IGH), SD(IGH), H(LDH,IGH), ST(IST), ZSP(4), WA(IWA), HC(LDH,IGH)
EXTERNAL | PIV

3 Description

The time series x 1,x 2,…,xn supplied to G13AEF is assumed to follow a seasonal autoregressive integrated moving average (ARIMA) model defined as follows:
∇d∇sD xt-c=wt,
where ∇d∇sD xt is the result of applying non-seasonal differencing of order d and seasonal differencing of seasonality s and order D to the series xt, as outlined in the description of G13AAF. The differenced series is then of length N=n-d′, where d′=d+D×s is the generalized order of differencing. The scalar c is the expected value of the differenced series, and the series w 1,w 2,…,wN follows a zero-mean stationary autoregressive moving average (ARMA) model defined by a pair of recurrence equations. These express wt in terms of an uncorrelated series at, via an intermediate series et. The first equation describes the seasonal structure:
wt=Φ 1w t-s+Φ 2w t-2×s+⋯+ΦPw t-P×s+et-Θ 1e t-s-Θ 2e t-2×s-⋯-ΘQe t-Q×s.
The second equation describes the non-seasonal structure. If the model is purely non-seasonal the first equation is redundant and et above is equated with wt:
et=ϕ 1e t-1+ϕ 2e t-2+⋯+ϕpe t-p+at-θ 1a t-1-θ 2a t-2-⋯-θqa t-q.
Estimates of the model parameters defined by
ϕ 1,ϕ 2,…,ϕp,θ 1,θ 2,…,θq, Φ 1,Φ 2,…,ΦP,Θ 1,Θ 2,…,ΘQ
and (optionally) c are obtained by minimizing a quadratic form in the vector w=w 1,w 2,…,wN′.
This is QF=w′V-1 w, where V is the covariance matrix of w, and is a function of the model parameters. This matrix is not explicitly evaluated, since QF may be expressed as a ‘sum of squares’ function. When moving average parameters θi or Θi are present, so that the generalized moving average order q′=q+s×Q is positive, backforecasts w 1-q′,w 2-q′,…,w 0 are introduced as nuisance parameters. The ‘sum of squares’ function may then be written as
S pm=∑t=1-q′N at 2-∑t=1-q′-p′ -q′bt 2,
where pm is a combined vector of parameters, consisting of the backforecasts followed by the ARMA model parameters.
The terms at correspond to the ARMA model residual series at, and p′=p+s×P is the generalized autoregressive order. The terms bt are only present if autoregressive parameters are in the model, and serve to correct for transient errors introduced at the start of the autoregression.
The equations defining at and bt are precisely:
  • et=wt-Φ 1w t-s-Φ 2w t-2×s-⋯-ΦPw t-P×s+Θ 1e t-s+Θ 2e t-2×s+⋯+ΘQe t-Q×s,
    for t=1-q′,2-q′,…,n.
  • at=et-ϕ 1e t-1-ϕ 2e t-2-⋯-ϕpe t-p+θ 1a t-1+θ 2a t-2+⋯+θqa t-q,
    for t=1-q′,2-q′,…,n.
  • ft=wt-Φ 1w t+s-Φ 2w t+2×s-⋯-ΦPw t+P×s+Θ 1f t-s+Θ 2f t-2×s+⋯+ΘQf t-Q×s,
    for t=1-q′-s×P,2-q′-s×P,…,-q′+P
  • bt=ft-ϕ 1f t+1-ϕ 2f t+2-⋯-ϕpf t+p+θ 1b t-1+θ 2b t-2+⋯+θqb t-q,
    for t=1-q′-p′,2-q′-p′,…,-q′.
For all four of these equations, the following conditions hold:
  • wi=0 if i<1-q′
  • ei=0 if i<1-q′
  • ai=0 if i<1-q′
  • fi=0 if i<1-q′-s×P
  • bi=0 if i<1-q′-p′
Minimization of S with respect to pm uses an extension of the algorithm of Marquardt (1963).
The first derivatives of S with respect to the parameters are calculated as
2×∑at×a t,i-2∑bt×b t,i=2×Gi,
where a t,i and b t,i are derivatives of at and bt with respect to the ith parameter.
The second derivative of S is approximated by
2×∑a t,i×a t,j-2×∑b t,i×b t,j=2×H ij.
Successive parameter iterates are obtained by calculating a vector of corrections dpm by solving the equations
H+α×D×dpm=-G,
where G is a vector with elements Gi, H is a matrix with elements H ij, α is a scalar used to control the search and D is the diagonal matrix of H.
The new parameter values are then pm+dpm.
The scalar α controls the step size, to which it is inversely related.
If a step results in new parameter values which give a reduced value of S, then α is reduced by a factor β. If a step results in new parameter values which give an increased value of S, or in ARMA model parameters which in any way contravene the stationarity and invertibility conditions, then the new parameters are rejected, α is increased by the factor β, and the revised equations are solved for a new parameter correction.
This action is repeated until either a reduced value of S is obtained, or α reaches the limit of 109, which is used to indicate a failure of the search procedure.
This failure may be due to a badly conditioned sum of squares function or to too strict a convergence criterion. Convergence is deemed to have occurred if the fractional reduction in the residual sum of squares in successive iterations is less than a value γ, while α<1.0.
The stationarity and invertibility conditions are tested to within a specified tolerance multiple δ of machine accuracy. Upon convergence, or completion of the specified maximum number of iterations without convergence, statistical properties of the estimates are derived. In the latter case the sequence of iterates should be checked to ensure that convergence is adequate for practical purposes, otherwise these properties are not reliable.
The estimated residual variance is
erv = Smin / df ,
where Smin is the final value of S, and the residual number of degrees of freedom is given by
df = N-p-q-P-Q   -1 ​ if ​ c ​ is estimated .
The covariance matrix of the vector of estimates pm is given by
erv × H-1 ,
where H is evaluated at the final parameter values.
From this expression are derived the vector of standard deviations, and the correlation matrix for the whole parameter set. These are asymptotic approximations.
The differenced series wt (now uncorrected for the constant), intermediate series et and residual series at are all available upon completion of the iterations over the range (extended by backforecasts)
t=1-q′,2-q′,…,N.
The values at can only properly be interpreted as residuals for t≥1+p′-q′, as the earlier values are corrupted by transients if p′>0.
In consequence of the manner in which differencing is implemented, the residual at is the one step ahead forecast error for x t+d′.
For convenient application in forecasting, the following quantities constitute the ‘state set’, which contains the minimum amount of time series information needed to construct forecasts:
(i) | the differenced series wt, for N-s×P<t≤N,
(ii) | the d′ values required to reconstitute the original series xt from the differenced series wt,
(iii) | the intermediate series et, for N - max p, Q × s < t ≤ N ,
(iv) | the residual series at, for N-q<t≤N.
This state set is available upon completion of the iterations. The routine may be used purely for the construction of this state set, given a previously estimated model and time series xt, by requesting zero iterations. Backforecasts are estimated, but the model parameter values are unchanged. If later observations become available and it is desired to update the state set, G13AGF can be used.

4 References

Box G E P and Jenkins G M (1976) Time Series Analysis: Forecasting and Control (Revised Edition) Holden–Day
Marquardt D W (1963) An algorithm for least squares estimation of nonlinear parameters J. Soc. Indust. Appl. Math. 11 431

5 Arguments

1:   MR 7 – INTEGER arrayInput
On entry: the orders vector p,d,q,P,D,Q,s of the ARIMA model whose parameters are to be estimated. p, q, P and Q refer respectively to the number of autoregressive (ϕ), moving average θ, seasonal autoregressive (Φ) and seasonal moving average (Θ) parameters. d, D and s refer respectively to the order of non-seasonal differencing, the order of seasonal differencing and the seasonal period.
Constraints:
  • p, d, q, P, D, Q, s≥0;
  • p+q+P+Q>0;
  • s≠1;
  • if s=0, P+D+Q=0;
  • if s>1, P+D+Q>0;
  • d+s×P+D≤n;
  • p+d-q+s×P+D-Q≤n.
2:   PAR NPAR – REAL (KIND=nag_wp) arrayInput/Output
On entry: the initial estimates of the p values of the ϕ parameters, the q values of the θ parameters, the P values of the Φ parameters and the Q values of the Θ parameters, in that order.
On exit: the latest values of the estimates of these parameters.
3:   NPAR – INTEGERInput
On entry: the total number of ϕ, θ, Φ and Θ parameters to be estimated.
Constraint: NPAR=p+q+P+Q.
4:   C – REAL (KIND=nag_wp)Input/Output
On entry: if KFC=0, C must contain the expected value, c, of the differenced series.
If KFC=1, C must contain an initial estimate of c.
On exit: if KFC=0, C is unchanged.
If KFC=1, C contains the latest estimate of c.
Therefore, if C and KFC are both zero on entry, there is no constant correction.
5:   KFC – INTEGERInput
On entry: must be set to 1 if the constant, c, is to be estimated and 0 if it is to be held fixed at its initial value.
Constraint: KFC=0 or 1.
6:   X NX – REAL (KIND=nag_wp) arrayInput
On entry: the n values of the original undifferenced time series.
7:   NX – INTEGERInput
On entry: n, the length of the original undifferenced time series.
8:   ICOUNT 6 – INTEGER arrayOutput
On exit: size of various output arrays.
ICOUNT 1
Contains q+Q×s, the number of backforecasts.
ICOUNT 2
Contains n-d-D×s, the number of differenced values.
ICOUNT 3
Contains d+D×s, the number of values of reconstitution information.
ICOUNT 4
Contains n+q+Q×s, the number of values held in each of the series EX, EXR and AL.
ICOUNT 5
Contains n-d-D×s-p-q-P-Q-KFC, the number of degrees of freedom associated with S.
ICOUNT 6
Contains ICOUNT 1+NPAR+KFC, the number of parameters being estimated.
These values are always computed regardless of the exit value of IFAIL.
9:   EX IEX – REAL (KIND=nag_wp) arrayOutput
On exit: the extended differenced series which is made up of:
ICOUNT 1 backforecast values of the differenced series.
ICOUNT 2 actual values of the differenced series.
ICOUNT 3 values of reconstitution information.
The total number of these values held in EX is ICOUNT 4.
If the routine exits because of a faulty input argument, the contents of EX will be indeterminate.
10:   EXR IEX – REAL (KIND=nag_wp) arrayOutput
On exit: the values of the model residuals which is made up of:
ICOUNT 1 residuals corresponding to the backforecasts in the differenced series.
ICOUNT 2 residuals corresponding to the actual values in the differenced series.
The remaining ICOUNT 3 values contain zeros.
If the routine exits with IFAIL holding a value other than 0 or 9, the contents of EXR will be indeterminate.
11:   AL IEX – REAL (KIND=nag_wp) arrayOutput
On exit: the intermediate series which is made up of:
ICOUNT 1 intermediate series values corresponding to the backforecasts in the differenced series.
ICOUNT 2 intermediate series values corresponding to the actual values in the differenced series.
The remaining ICOUNT 3 values contain zeros.
If the routine exits with IFAIL≠0, the contents of AL will be indeterminate.
12:   IEX – INTEGERInput
On entry: the dimension of the arrays EX, EXR and AL as declared in the (sub)program from which G13AEF is called.
Constraint: IEX≥q+Q×s+n, which is equivalent to the exit value of ICOUNT 4.
13:   S – REAL (KIND=nag_wp)Output
On exit: the residual sum of squares after the latest series of parameter estimates has been incorporated into the model. If the routine exits with a faulty input argument, S contains zero.
14:   G IGH – REAL (KIND=nag_wp) arrayOutput
On exit: the latest value of the derivatives of S with respect to each of the parameters being estimated (backforecasts, PAR parameters, and where relevant the constant – in that order). The contents of G will be indeterminate if the routine exits with a faulty input argument.
15:   IGH – INTEGERInput
On entry: the dimension of the arrays G and SD and the second dimension of the arrays H and HC as declared in the (sub)program from which G13AEF is called.
Constraint: IGH≥q+Q×s+NPAR+KFC which is equivalent to the exit value of ICOUNT 6.
16:   SD IGH – REAL (KIND=nag_wp) arrayOutput
On exit: the standard deviations corresponding to each of the parameters being estimated (backforecasts, PAR parameters, and where relevant the constant, in that order).
If the routine exits with IFAIL containing a value other than 0 or 9, or if the required number of iterations is zero, the contents of SD will be indeterminate.
17:   H LDHIGH – REAL (KIND=nag_wp) arrayOutput
On exit: the second derivative of S and correlation coefficients.
(a) | the latest values of an approximation to the second derivative of S with respect to each of the q+Q×s+NPAR+KFC parameters being estimated (backforecasts, PAR parameters, and where relevant the constant – in that order), and
(b) | the correlation coefficients relating to each pair of these parameters.
These are held in a matrix defined by the first q+Q×s+NPAR+KFC rows and the first q+Q×s+NPAR+KFC columns of H. (Note that ICOUNT 6 contains the value of this expression.) The values of (a) are contained in the upper triangle, and the values of (b) in the strictly lower triangle.
These correlation coefficients are zero during intermediate printout using PIV, and indeterminate if IFAIL contains on exit a value other than 0 or 9.
All the contents of H are indeterminate if the required number of iterations are zero. The q+Q×s+NPAR+KFC+1th row of H is used internally as workspace.
18:   LDH – INTEGERInput
On entry: the first dimension of the arrays H and HC as declared in the (sub)program from which G13AEF is called.
Constraint: LDH≥1+q+Q×s+NPAR+KFC, which is equivalent to the exit value of ICOUNT 6.
19:   ST IST – REAL (KIND=nag_wp) arrayOutput
On exit: the NST values of the state set array. If the routine exits with IFAIL containing a value other than 0 or 9, the contents of ST will be indeterminate.
20:   IST – INTEGERInput
On entry: the dimension of the array ST as declared in the (sub)program from which G13AEF is called.
Constraint: IST≥P×s+d+D×s+q+max p,Q×s.
21:   NST – INTEGEROutput
On exit: the number of values in the state set array ST.
22:   PIV – SUBROUTINE, supplied by the NAG Library or the user.External Procedure
PIV is used to monitor the progress of the optimization.
The specification of PIV is:
SUBROUTINE PIV ( MR, PAR, NPAR, C, KFC, ICOUNT, S, G, H, LDH, IGH, ITC, ZSP)
INTEGER | MR(7), NPAR, KFC, ICOUNT(6), LDH, IGH, ITC
REAL (KIND=nag_wp) | PAR(NPAR), C, S, G(IGH), H(LDH,IGH), ZSP(4)
PIV is called on each iteration by G13AEF when the input value of KPIV is nonzero and is bypassed when it is 0.
The routine G13AFZ may be used as PIV. It prints the heading
G13AFZ MONITORING OUTPUT - ITERATION n
followed by the parameter values and the residual sum of squares. Output is directed to the advisory channel defined by X04ABF.
1:   MR 7 – INTEGER arrayInput
2:   PAR NPAR – REAL (KIND=nag_wp) arrayInput
3:   NPAR – INTEGERInput
4:   C – REAL (KIND=nag_wp)Input
5:   KFC – INTEGERInput
6:   ICOUNT 6 – INTEGER arrayInput
7:   S – REAL (KIND=nag_wp)Input
8:   G IGH – REAL (KIND=nag_wp) arrayInput
9:   H LDHIGH – REAL (KIND=nag_wp) arrayInput
10:   LDH – INTEGERInput
11:   IGH – INTEGERInput
12:   ITC – INTEGERInput
13:   ZSP 4 – REAL (KIND=nag_wp) arrayInput
On entry: all the arguments are defined as for G13AEF itself.
PIV must either be a module subprogram USEd by, or declared as EXTERNAL in, the (sub)program from which G13AEF is called. Arguments denoted as Input must not be changed by this procedure.
If KPIV=0 a dummy PIV must be supplied.
23:   KPIV – INTEGERInput
On entry: must be nonzero if the progress of the optimization is to be monitored using PIV. Otherwise KPIV must contain 0.
24:   NIT – INTEGERInput
On entry: the maximum number of iterations to be performed.
Constraint: NIT≥0.
25:   ITC – INTEGEROutput
On exit: the number of iterations performed.
26:   ZSP 4 – REAL (KIND=nag_wp) arrayInput/Output
On entry: when KZSP=1, the first four elements of ZSP must contain the four values used to guide the search procedure. These are as follows.
ZSP 1 contains α, the value used to constrain the magnitude of the search procedure steps.
ZSP 2 contains β, the multiplier which regulates the value α.
ZSP 3 contains δ, the value of the stationarity and invertibility test tolerance factor.
ZSP 4 contains γ, the value of the convergence criterion.
If KZSP≠1 on entry, default values for ZSP are supplied by the routine.
These are 0.001, 10.0, 1000.0 and max 100×machine precision, 0.0000001 respectively.
On exit: ZSP contains the values, default or otherwise, used by the routine.
Constraint: if KZSP=1, ZSP 1>0.0, ZSP 2>1.0, ZSP 3≥1.0, 0≤ZSP 4<1.0.
27:   KZSP – INTEGERInput
On entry: the value 1 if the routine is to use the input values of ZSP, and any other value if the default values of ZSP are to be used.
28:   ISF 4 – INTEGER arrayOutput
On exit: contains success/failure indicators, one for each of the four types of parameter in the model (autoregressive, moving average, seasonal autoregressive, seasonal moving average), in that order.
Each indicator has the interpretation:
-2 | On entry parameters of this type have initial estimates which do not satisfy the stationarity or invertibility test conditions.
-1 | The search procedure has failed to converge because the latest set of parameter estimates of this type is invalid.
-0 | No parameter of this type is in the model.
-1 | Valid final estimates for parameters of this type have been obtained.
29:   WA IWA – REAL (KIND=nag_wp) arrayWorkspace
30:   IWA – INTEGERInput
On entry: the dimension of the array WA as declared in the (sub)program from which G13AEF is called.
Constraint: IWA≥F 1×F 2+9×NPAR,
where | F 1=NX+1+p+P×s+q+Q×s;
and | F 2=8 if KFC=1;
F 2=7 if KFC=0, Q>0;
F 2=6 if KFC=0, Q=0, P>0;
F 2=5 if KFC=0, Q=0, P=0, q>0;
F 2=4 otherwise.
31:   HC LDHIGH – REAL (KIND=nag_wp) arrayWorkspace
32:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, because for this routine the values of the output arguments may be useful even if IFAIL≠0 on exit, the recommended value is -1. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Note: G13AEF may return useful information for one or more of the following detected errors or warnings.
Errors or warnings detected by the routine:
IFAIL=1
On entry, | NPAR≠p+q+P+Q,
or | the orders vector MR is invalid (check it against the constraints in Section 5),
or | KFC≠0 or 1.
IFAIL=2
On entry, NX-d-D×s≤NPAR+KFC, i.e., the number of terms in the differenced series is not greater than the number of parameters in the model. The model is over-parameterised.
IFAIL=3
On entry, | one or more of the user-supplied criteria for controlling the iterative process are invalid,
or | NIT<0,
or | if KZSP=1, ZSP 1≤0.0;
or | if KZSP=1, ZSP 2≤1.0;
or | if KZSP=1, ZSP 3<1.0;
or | if KZSP=1, ZSP 4<0.0;
or | if KZSP=1, ZSP 4≥1.0.
IFAIL=4
On entry, the state set array ST is too small. The output value of NST contains the required value (see the description of IST in Section 5 for the formula).
IFAIL=5
On entry, the workspace array WA is too small. Check the value of IWA against the constraints in Section 5.
IFAIL=6
On entry, | IEX<q+Q×s+NX,
or | IGH<q+Q×s+NPAR+KFC,
or | LDH≤q+Q×s+NPAR+KFC.
IFAIL=7
This indicates a failure in the search procedure, with ZSP 1≥1.0E09.
Some output arguments may contain meaningful values; see Section 5 for details.
IFAIL=8
This indicates a failure to invert H.
Some output arguments may contain meaningful values; see Section 5 for details.
IFAIL=9
Unable to calculate the latest estimates of the backforecasts.
Some output arguments may contain meaningful values; see Section 5 for details.
IFAIL=10
Satisfactory parameter estimates could not be obtained for all parameter types in the model. Inspect array ISF for further information on the parameter type(s) in error.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

The computations are believed to be stable.

8 Parallelism and Performance

G13AEF is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
G13AEF makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The time taken by G13AEF is approximately proportional to NX×ITC× q+Q×s+NPAR+KFC 2.

10 Example

The following program reads 30 observations from a time series relating to the rate of the earth's rotation about its polar axis. Differencing of order 1 is applied, and the number of non-seasonal parameters is 3, one autoregressive ϕ, and two moving average θ. No seasonal effects are taken into account.
The constant is estimated. Up to 25 iterations are allowed.
The initial estimates of ϕ 1, θ 1, θ 2 and c are zero.

10.1 Program Text

Program Text (g13aefe.f90)

10.2 Program Data

Program Data (g13aefe.d)

10.3 Program Results

Program Results (g13aefe.r)

G13 Chapter Contents
G13 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


G13AFF : NAG Library, Mark 26

G13 Chapter Contents
G13 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

G13AFF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

G13AFF is an easy-to-use version of G13AEF. It fits a seasonal autoregressive integrated moving average (ARIMA) model to an observed time series, using a nonlinear least squares procedure incorporating backforecasting. Parameter estimates are obtained, together with appropriate standard errors. The residual series is returned, and information for use in forecasting the time series is produced for use in G13AGF and G13AHF.
The estimation procedure is iterative, starting with initial parameter values such as may be obtained using G13ADF. It continues until a specified convergence criterion is satisfied or until a specified number of iterations have been carried out. The progress of the iteration can be monitored by means of an optional printing facility.

2 Specification

SUBROUTINE G13AFF ( MR, PAR, NPAR, C, KFC, X, NX, S, NDF, SD, NPPC, CM, LDCM, ST, NST, KPIV, NIT, ITC, ISF, RES, IRES, NRES, IFAIL)
INTEGER | MR(7), NPAR, KFC, NX, NDF, NPPC, LDCM, NST, KPIV, NIT, ITC, ISF(4), IRES, NRES, IFAIL
REAL (KIND=nag_wp) | PAR(NPAR), C, X(NX), S, SD(NPPC), CM(LDCM,NPPC), ST(NX), RES(IRES)

3 Description

The time series x 1,x 2,…,xn supplied to the routine is assumed to follow a seasonal autoregressive integrated moving average (ARIMA) model defined as follows:
∇d∇sD xt-c=wt,
where ∇d∇sD xt is the result of applying non-seasonal differencing of order d and seasonal differencing of seasonality s and order D to the series xt, as outlined in the description of G13AAF. The differenced series is then of length N=n-d′, where d′=d+D×s is the generalized order of differencing. The scalar c is the expected value of the differenced series, and the series w 1,w 2,…,wN follows a zero-mean stationary autoregressive moving average (ARMA) model defined by a pair of recurrence equations. These express wt in terms of an uncorrelated series at, via an intermediate series et. The first equation describes the seasonal structure:
wt=Φ 1w t-s+Φ 2w t-2×s+⋯+ΦPw t-P×s+et-Θ 1e t-s-Θ 2e t-2×s-⋯-ΘQe t-Q×s.
The second equation describes the non-seasonal structure. If the model is purely non-seasonal the first equation is redundant and et above is equated with wt:
et=ϕ 1e t-1+ϕ 2e t-2+⋯+ϕpe t-p+at-θ 1a t-1-θ 2a t-2-⋯-θqa t-q.
Estimates of the model parameters defined by
ϕ 1,ϕ 2,…,ϕp,θ 1,θ 2,…,θq, Φ 1,Φ 2,…,ΦP,Θ 1,Θ 2,…,ΘQ
and (optionally) c are obtained by minimizing a quadratic form in the vector w=w 1,w 2,…,wN′.
The minimization process is iterative, iterations being performed until convergence is achieved (see Section 3 in G13AEF for full details), or until the user-specified maximum number of iterations are completed.
The final values of the residual sum of squares and the parameter estimates are used to obtain asymptotic approximations to the standard deviations of the parameters, and the correlation matrix for the parameters. The ‘state set’ array of information required by forecasting is also returned.
Note: if the maximum number of iterations are performed without convergence, these quantities may not be reliable. In this case, the sequence of iterates should be checked, using the optional monitoring routine, to verify that convergence is adequate for practical purposes.

4 References

Box G E P and Jenkins G M (1976) Time Series Analysis: Forecasting and Control (Revised Edition) Holden–Day
Marquardt D W (1963) An algorithm for least squares estimation of nonlinear parameters J. Soc. Indust. Appl. Math. 11 431

5 Arguments

1:   MR 7 – INTEGER arrayInput
On entry: the orders vector p,d,q,P,D,Q,s of the ARIMA model whose parameters are to be estimated. p, q, P and Q refer respectively to the number of autoregressive ϕ, moving average θ, seasonal autoregressive Φ and seasonal moving average Θ parameters. d, D and s refer respectively to the order of non-seasonal differencing, the order of seasonal differencing and the seasonal period.
Constraints:
  • p, d, q, P, D, Q, s≥0;
  • p+q+P+Q>0;
  • s≠1;
  • if s=0, P+D+Q=0;
  • if s>1, P+D+Q>0;
  • d+s×P+D≤n;
  • p+d-q+s×P+D-Q≤n.
2:   PAR NPAR – REAL (KIND=nag_wp) arrayInput/Output
On entry: the initial estimates of the p values of the ϕ parameters, the q values of the θ parameters, the P values of the Φ parameters and the Q values of the Θ parameters, in that order.
On exit: contains the latest values of the estimates of these parameters.
3:   NPAR – INTEGERInput
On entry: the total number of ϕ, θ, Φ and Θ parameters to be estimated.
Constraint: NPAR=p+q+P+Q.
4:   C – REAL (KIND=nag_wp)Input/Output
On entry: if KFC=0, C must contain the expected value, c, of the differenced series.
If KFC=1, C must contain an initial estimate of c.
Therefore, if C and KFC are both zero on entry, there is no constant correction.
On exit: if KFC=0, C is unchanged.
If KFC=1, C contains the latest estimate of c.
5:   KFC – INTEGERInput
On entry: must be set to 1 if the constant, c, is to be estimated and 0 if it is to be held fixed at its initial value.
Constraint: KFC=0 or 1.
6:   X NX – REAL (KIND=nag_wp) arrayInput
On entry: the n values of the original undifferenced time series.
7:   NX – INTEGERInput
On entry: n, the length of the original undifferenced time series.
8:   S – REAL (KIND=nag_wp)Output
On exit: the residual sum of squares after the latest series of parameter estimates has been incorporated into the model. If the routine exits with a faulty input argument, S contains zero.
9:   NDF – INTEGEROutput
On exit: the number of degrees of freedom associated with S,
NDF=n-d-D×s-p-q-P-Q-KFC.
10:   SD NPPC – REAL (KIND=nag_wp) arrayOutput
On exit: the standard deviations corresponding to the parameters in the model (p autoregressive, q moving average, P seasonal autoregressive, Q seasonal moving average and c, if estimated, in that order). If the routine exits with IFAIL containing a value other than 0 or 9, or if the required number of iterations is zero, the contents of SD will be indeterminate.
11:   NPPC – INTEGERInput
On entry: the number of ϕ, θ, Φ, Θ and c parameters to be estimated. NPPC=p+q+P+Q+1 if the constant is being estimated and NPPC=p+q+P+Q if not.
Constraint: NPPC=NPAR+KFC.
12:   CM LDCMNPPC – REAL (KIND=nag_wp) arrayOutput
On exit: the correlation coefficients associated with each pair of the NPPC parameters. These are held in the first NPPC rows and the first NPPC columns of CM. These correlation coefficients are indeterminate if IFAIL contains on exit a value other than 0 or 9, or if the required number of iterations is zero.
13:   LDCM – INTEGERInput
On entry: the first dimension of the array CM as declared in the (sub)program from which G13AFF is called.
Constraint: LDCM≥NPPC.
14:   ST NX – REAL (KIND=nag_wp) arrayOutput
On exit: the value of the state set in its first NST elements. If the routine exits with IFAIL containing a value other than 0 or 9, the contents of ST will be indeterminate.
15:   NST – INTEGEROutput
On exit: the size of the state set. NST=P×s+D×s+d+q+max p,Q×s.
NST should be used subsequently in G13AGF and G13AHF as the dimension of ST.
16:   KPIV – INTEGERInput
On entry: must be nonzero if the progress of the optimization is to be monitored using the built-in printing facility. Otherwise KPIV must contain zero. If selected, monitoring output will be sent to the current advisory message unit defined by X04ABF. For each iteration, the heading
 G13AFZ MONITORING OUTPUT - ITERATION n
followed by the argument values, and residual sum of squares, are printed.
17:   NIT – INTEGERInput
On entry: the maximum number of iterations to be performed.
Constraint: NIT≥0.
18:   ITC – INTEGEROutput
On exit: the number of iterations performed.
19:   ISF 4 – INTEGER arrayOutput
On exit: the first four elements of ISF contain success/failure indicators, one for each of the four types of parameter in the model (autoregressive, moving average, seasonal autoregressive, seasonal moving average), in that order.
Each indicator has the interpretation:
-2 | On entry parameters of this type have initial estimates which do not satisfy the stationarity or invertibility test conditions.
-1 | The search procedure has failed to converge because the latest set of parameter estimates of this type is invalid.
-0 | No parameter of this type is in the model.
-1 | Valid final estimates for parameters of this type have been obtained.
20:   RES IRES – REAL (KIND=nag_wp) arrayOutput
On exit: the first NRES elements of RES contain the model residuals derived from the differenced series. If the routine exits with IFAIL holding a value other than 0 or 9, these elements of RES will be indeterminate. The rest of the array RES is used as workspace.
21:   IRES – INTEGERInput
On entry: the dimension of the array RES as declared in the (sub)program from which G13AFF is called.
Constraint: IRES≥15×Q′+11 n+13×NPPC+8×P′+12+2× Q′+NPPC 2,
where P′=p+P×s and Q′=q+Q×s.
22:   NRES – INTEGEROutput
On exit: the number of model residuals returned in RES.
23:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, because for this routine the values of the output arguments may be useful even if IFAIL≠0 on exit, the recommended value is -1. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Note: G13AFF may return useful information for one or more of the following detected errors or warnings.
Errors or warnings detected by the routine:
IFAIL=1
On entry, | NPAR≠p+q+P+Q,
or | the orders vector MR is invalid (check the constraints in Section 5),
or | KFC≠0 or 1,
or | NPPC≠NPAR+KFC.
IFAIL=2
On entry, NX-d-D×s≤NPAR+KFC, i.e., the number of terms in the differenced series is not greater than the number of parameters in the model. The model is over-parameterised.
IFAIL=3
On entry, NIT<0.
IFAIL=4
On entry, the required size of the state set array ST is greater than NX. This occurs only for very unusual models with long seasonal periods or large numbers of parameters. First check that the orders vector MR has been set up as intended. If it has, change to G13AEF with ST dimensioned at least (NST), where NST is the value returned by G13AFF, or computed using the formula in Section 5 of this document.
IFAIL=5
On entry, the workspace array RES is too small. Check the value of IRES against the constraints in Section 5.
IFAIL=6
On entry, LDCM<NPPC.
IFAIL=7
The search procedure in the algorithm has failed. This may be due to a badly conditioned sum of squares function, or the default convergence criterion may be too strict. Use G13AEF with a less strict convergence criterion.
Some output arguments may contain meaningful values; see Section 5 for details.
IFAIL=8
The inversion of the Hessian matrix in the calculation of the covariance matrix of the parameter estimates has failed.
Some output arguments may contain meaningful values; see Section 5 for details.
IFAIL=9
This indicates a failure when solving the equations giving the latest estimates of the backforecasts.
Some output arguments may contain meaningful values; see Section 5 for details.
IFAIL=10
Satisfactory parameter estimates could not be obtained for all parameter types in the model. Inspect array ISF for further information on the parameter type(s) in error.
IFAIL=11
An internal error has arisen in partitioning RES for use by G13AEF. This error should not occur; report it to NAG via your site representative.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

The computations are believed to be stable.

8 Parallelism and Performance

G13AFF is threaded by NAG for parallel execution in multithreaded implementations of the NAG Library.
G13AFF makes calls to BLAS and/or LAPACK routines, which may be threaded within the vendor library used by this implementation. Consult the documentation for the vendor library for further information.
Please consult the X06 Chapter Introduction for information on how to control and interrogate the OpenMP environment used within this routine. Please also consult the Users' Note for your implementation for any additional implementation-specific information.

9 Further Comments

The time taken by G13AFF is approximately proportional to NX×ITC× q+Q×s+NPPC 2.

10 Example

This example reads 30 observations from a time series relating to the rate of the earth's rotation about its polar axis. Differencing of order 1 is applied, and the number of non-seasonal parameters is 3, one autoregressive (ϕ) and two moving average (θ). No seasonal effects are taken into account.
The constant is estimated. Up to 50 iterations are allowed.
The initial estimates of ϕ 1, θ 1, θ 2 and c are zero.
Some intermediate monitoring output from G13AFZ has been omitted.

10.1 Program Text

Program Text (g13affe.f90)

10.2 Program Data

Program Data (g13affe.d)

10.3 Program Results

Program Results (g13affe.r)

G13 Chapter Contents
G13 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016


G13AGF : NAG Library, Mark 26

G13 Chapter Contents
G13 Chapter Introduction
NAG Library Manual

NAG Library Routine Document

G13AGF

Note: before using this routine, please read the Users' Note for your implementation to check the interpretation of bold italicised terms and other implementation-dependent details.

▸▿ Contents

1 Purpose
2 Specification
3 Description
4 References
5 Arguments
6 Error Indicators and Warnings
7 Accuracy
8 Parallelism and Performance
9 Further Comments
▸▿ 10 Example
10.1 Program Text
10.2 Program Data
10.3 Program Results

1 Purpose

G13AGF accepts a series of new observations of a time series, the model of which is already fully specified, and updates the ‘state set’ information for use in constructing further forecasts. The previous specifications of the time series model should have been obtained by using G13AEF or G13AFF to estimate the relevant parameters. The supplied state set will originally have been produced by G13AEF or G13AFF, but may since have been updated by earlier calls to G13AGF.
A set of residuals corresponding to the new observations is returned. These may be of use in checking that the new observations conform to the previously fitted model.

2 Specification

SUBROUTINE G13AGF ( ST, NST, MR, PAR, NPAR, C, ANX, NUV, ANEXR, WA, NWA, IFAIL)
INTEGER | NST, MR(7), NPAR, NUV, NWA, IFAIL
REAL (KIND=nag_wp) | ST(NST), PAR(NPAR), C, ANX(NUV), ANEXR(NUV), WA(NWA)

3 Description

The time series model is specified as outlined in Section 3 in G13AEF or G13AFF. This also describes how the state set, which contains the minimum amount of time series information needed to construct forecasts, is made up of
(i) | the differenced series wt (uncorrected for the constant c), for N-P×s<t≤N,
(ii) | the d′ values required to reconstitute the original series xt from the differenced series wt,
(iii) | the intermediate series et, for N - max p, Q × s < t ≤ N , and
(iv) | the residual series at, for N-q<t≤N.
If the number of original undifferenced observations was n, then d′=d+D×s and N=n-d′.
To update the state set, given a number of new undifferenced observations xt, t=n+1,n+2,…,n+k, the four series above are first reconstituted.
Differencing and residual calculation operations are then applied to the new observations and k new values of wt,et and at are derived.
The first k values in these three series are then discarded and a new state set is obtained.
The residuals in the at series corresponding to the k new observations are preserved in an output array. The parameters of the time series model are not changed in this routine.

4 References

None.

5 Arguments

1:   ST NST – REAL (KIND=nag_wp) arrayInput/Output
On entry: the state set derived from G13AEF or G13AFF, or as modified using earlier calls of G13AGF.
On exit: the updated values of the state set.
2:   NST – INTEGERInput
On entry: the number of values in the state set array ST.
Constraint: NST=P×s+D×s+d+q+max p,Q×s. (As returned by G13AEF or G13AFF).
3:   MR 7 – INTEGER arrayInput
On entry: the orders vector p,d,q,P,D,Q,s of the ARIMA model, in the usual notation.
Constraints:
  • p,d,q,P,D,Q,s≥0;
  • p+q+P+Q>0;
  • s≠1;
  • if s=0, P+D+Q=0;
  • if s>1, P+D+Q>0.
4:   PAR NPAR – REAL (KIND=nag_wp) arrayInput
On entry: the estimates of the p values of the ϕ parameters, the q values of the θ parameters, the P values of the Φ parameters and the Q values of the Θ parameters in the model – in that order, using the usual notation.
5:   NPAR – INTEGERInput
On entry: the number of ϕ, θ, Φ and Θ parameters in the model.
Constraint: NPAR=p+q+P+Q.
6:   C – REAL (KIND=nag_wp)Input
On entry: the constant to be subtracted from the differenced data.
7:   ANX NUV – REAL (KIND=nag_wp) arrayInput
On entry: the new undifferenced observations which are to be used to update ST.
8:   NUV – INTEGERInput
On entry: k, the number of new observations in ANX.
9:   ANEXR NUV – REAL (KIND=nag_wp) arrayOutput
On exit: the residuals corresponding to the new observations in ANX.
10:   WA NWA – REAL (KIND=nag_wp) arrayWorkspace
11:   NWA – INTEGERInput
On entry: the dimension of the array WA as declared in the (sub)program from which G13AGF is called.
Constraint: NWA≥4×NPAR+3×NST.
12:   IFAIL – INTEGERInput/Output
On entry: IFAIL must be set to 0, -1​ or ​1. If you are unfamiliar with this argument you should refer to Section 3.4 in How to Use the NAG Library and its Documentation for details.
For environments where it might be inappropriate to halt program execution when an error is detected, the value -1​ or ​1 is recommended. If the output of error messages is undesirable, then the value 1 is recommended. Otherwise, if you are not familiar with this argument, the recommended value is 0. When the value -1​ or ​1 is used it is essential to test the value of IFAIL on exit.
On exit: IFAIL=0 unless the routine detects an error or a warning has been flagged (see Section 6).

6 Error Indicators and Warnings

If on entry IFAIL=0 or -1, explanatory error messages are output on the current error message unit (as defined by X04AAF).
Errors or warnings detected by the routine:
IFAIL=1
On entry, | NPAR≠p+q+P+Q,
or | the orders vector MR is invalid (check the constraints in Section 5).
IFAIL=2
On entry, NST≠P×s+D×s+d+q+max Q×s,p.
IFAIL=3
On entry, NUV≤0.
IFAIL=4
On entry, NWA<4×NPAR+3×NST.
IFAIL=-99
An unexpected error has been triggered by this routine. Please contact NAG.
See Section 3.9 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-399
Your licence key may have expired or may not have been installed correctly.
See Section 3.8 in How to Use the NAG Library and its Documentation for further information.
IFAIL=-999
Dynamic memory allocation failed.
See Section 3.7 in How to Use the NAG Library and its Documentation for further information.

7 Accuracy

The computations are believed to be stable.

8 Parallelism and Performance

G13AGF is not threaded in any implementation.

9 Further Comments

The time taken by G13AGF is approximately proportional to NUV×NPAR.

10 Example

The following program is based on data derived from a study of monthly airline passenger totals (in thousands) to which a logarithmic transformation had been applied. The time series model was based on seasonal and non-seasonal differencing both of order 1, with seasonal period 12. The number of parameters estimated was two: a non-seasonal moving average parameter θ 1 with value 0.327 and a seasonal moving average parameter Θ 1 with value 0.6270. There was no constant correction. These, together with the state set array, were obtained using G13AEF.
Twelve new observations are supplied. The routine updates the state set and outputs a set of residuals corresponding to the new observations.

10.1 Program Text

Program Text (g13agfe.f90)

10.2 Program Data

Program Data (g13agfe.d)

10.3 Program Results

Program Results (g13agfe.r)

G13 Chapter Contents
G13 Chapter Introduction
NAG Library Manual
© The Numerical Algorithms Group Ltd, Oxford, UK. 2016